diff --git a/AUTHORS.md b/AUTHORS.md
--- a/AUTHORS.md
+++ b/AUTHORS.md
@@ -1,195 +1,540 @@
 # Contributors
 
-- Arata Mizuki
 - Aaron Wolen
+- Adelar da Silva Queiróz
+- Agriya Khetarpal
+- Agustín Martín Barbero
+- Akash Patel
+- Akos Marton
 - Albert Krewinkel
+- Albert Lei
 - Alex Ivkin
+- Alex Toldaiev
 - Alex Vong
+- Alexander Batischev
 - Alexander Kondratskiy
 - Alexander Krotov
 - Alexander Sulfrian
 - Alexander V Vershilov
+- Alexandre Franke
 - Alfred Wechselberger
+- Amar Al-Zubaidi
+- Amir Dekel
+- Amneesh Singh
+- Amogh Rathore
+- Amy de Buitléir
+- Anabra
+- Anders Waldenborg
+- Andreas Deininger
 - Andreas Lööw
+- Andreas Scherer
+- Andres Freund
 - Andrew Dunning
+- Andy Morris
+- Aner Lucero
+- Anti-Distinctlyminty
 - Antoine Latter
+- Anton Antich
+- Anton Melnikov
+- Antonio Terceiro
 - Arata Mizuki
+- Arata Mizuki
+- Arfon Smith
 - Arlo O'Keeffe
+- Artem Pelenitsyn
 - Artyom Kazak
-- Agustín Martín Barbero
+- Asliddinbek Azizovich
 - B. Scott Michel
+- Bastien Dumont
 - Ben Firshman
 - Ben Gamari
+- Ben Steinberg
 - Beni Cherniavsky-Paskin
+- Benjamin Bray
+- Benjamin Esham
+- Benjamin Wuethrich
 - Benoit Schweblin
+- Benson Muite
 - Bjorn Buckwalter
+- Blake Eryx
+- Bodigrim
 - Bradley Kuhn
 - Brent Yorgey
+- Brian Leung
 - Bryan O'Sullivan
 - Caleb McDaniel
+- Caleb Mclennan
 - Calvin Beck
+- Carlos Scheidegger
 - Carlos Sosa
+- Carsten Allefeld
+- Castedo Ellerman
+- Cécile Chemin
+- Cédric Couralet
+- Cezary Drożak
+- Chandrahas77
+- Charanjit Singh
+- Charles Tapley Hoyt
+- Charlotte Koch
 - Chris Black
+- Chris Callison-Burch
 - Christian Conkle
+- Christian Christiansen
+- Christian Despres
 - Christoffer Ackelman
 - Christoffer Sawicki
+- Christophe Dervieux
+- Christopher Kenny
 - Clare Macrae
 - Clint Adams
 - Conal Elliott
+- Cormac Relf
 - Craig S. Bosma
+- Damien Clochard
+- Dan Jacobson
 - Daniel Bergey
+- Daniel Kessler
+- Daniel Maslowski
 - Daniel T. Staal
 - Daniele D'Orazio
 - David A Roberts
 - David Lazar
+- David Martschenko
 - David Röthlisberger
 - Denis Laxalde
+- Denis Maier
+- Derek Chen-Becker
+- Diego Balseiro
+- Diogo Almiro
+- Dimitri Sabadie
+- Dimitris Apostolou
+- Dmitry Pogodin
+- Dmitry Volodin
 - Douglas Calvert
+- Edwin Török
+- Eigil Rischel
+- Elliot Bobrow
 - Emanuel Evans
+- Emmanuel Ferdman
+- Emerson Harkin
+- Emily Bourke
 - Emily Eisenberg
 - Eric Kow
+- Eric Schrijver
 - Eric Seidel
+- Erik Post
+- Erik Rask
+- Ethan Riley
+- Étienne Bersac
+- Evan Silberman
+- Even Brenden
+- Ezwal
+- Fabián Heredia Montiel
+- Félix Baylac-Jacqué
 - Felix Yan
+- Florian Beeres
 - Florian Eitel
+- Florian Klink
+- Florian Kohrt
+- FoxChillz
+- Francesco Mazzoli
+- Francesco Occhipinti
 - François Gannaz
+- Frank Seifferth
+- Frederik Elwert
 - Freiric Barral
 - Freirich Raabe
 - Frerich Raabe
 - Fyodor Sheremetyev
 - Gabor Pali
+- Gabriel Lewertowski
 - Gavin Beatty
+- George Stagg
+- Georgi Lyubenov
+- GHyman83
+- Gokul Rajiv
+- Gordon Woodhull
 - Gottfried Haider
 - Greg Maslov
 - Greg Rundlett
 - Grégory Bataille
+- Guriy Samarin
 - Gwern Branwen
 - Hamish Mackenzie
 - Hans-Peter Deifel
+- Hendrik Erz
+- Heiko Schlittermann
 - Henrik Tramberend
 - Henry de Valence
+- Herwig Stuetz
+- Hikaru Ibayashi
+- Hos Es
 - Hubert Plociniczak
+- Iacobus1983
+- Ian Max Andolina
+- Igor Khorlo
+- Igor Pashev
+- Ilona Silverwood
 - Ilya V. Portnov
+- Ivan Panchenko
+- Ivan Trubach
+- Ivar de Bruin
 - Ivo Clarysse
+- Jaap de Jong
+- Jacob Larkin
+- James J Balamuta
+- J. B. Rainsberger
 - J. Lewis Muir
+- Jackson Schuster
+- Jaehwang Jung
 - Jaime Marquínez Ferrándiz
+- Jake Zimmerman
 - Jakob Voß
 - James Aspnes
+- James P. Ascher
+- James Barlow
+- James Scott-Brown
 - Jamie F. Olson
 - Jan Larres
 - Jan Schulz
+- Jan Tojnar
+- Jannik Buhr
+- Jan-Otto Kröpke
+- Jared Lander
 - Jason Ronallo
 - Jeff Arnold
 - Jeff Runningen
 - Jens Getreu
 - Jens Petersen
+- Jens Oehlschlägel
+- Jesse Hathaway
+- Jeremie Knuesel
+- Jérémy Bobbio
+- Jeroen de Haas
+- Jerry Sky
 - Jesse Rosenthal
+- Jez Cope
+- Joe Hermaszewski
 - Joe Hillenbrand
+- Johan Larsson
+- John KetzerX
+- John Luke Bentley
 - John MacFarlane
 - John Muccigrosso
-- John Luke Bentley
+- John Purnell
+- Jonas Scholl
 - Jonas Smedegaard
+- Jonathan
 - Jonathan Daugherty
+- Jonathan Dönszelmann
 - Jose Luis Duran
+- José de Mattos Neto
 - Josef Svenningsson
+- Joseph C. Sible
+- Julia Diaz
 - Julien Cretel
+- Julien Dutant
+- Juliette Fourcot
 - Juliusz Gonera
 - Justin Bogner
-- Jérémy Bobbio
+- Justin Wood
+- Karl Pettersson
+- Keenan Brock
 - Keiichiro Shikano
 - Kelsey Hightower
+- Kevin Broch
 - Kolen Cheung
 - Konstantin Zudov
 - Kristof Bastiaensen
-- Herwig Stuetz
+- Krystof Beuermann
 - Lars-Dominik Braun
+- Laurent P. René de Cotret
+- Lawrence Chonavel
+- Leif Metcalf
+- Leo Heitmann Ruiz
+- Leonard Rosenthol
+- Lila
+- Link Swanson
+- Loïc Grobol
+- Lorenzo
+- Lucas Escot
+- Lucas Viana
+- Lucas V. R
+- Luis Rivera
 - Luke Plant
+- Manolis Stamatogiannakis
 - Marc Schreiber
+- Marcin Serwin
+- Mario Lang
+- Mark Gardner
 - Mark Szepieniec
 - Mark Wright
+- Martin Joerg
 - Martin Linn
+- Martin Michlmayr
+- Martín Pozo
+- Masataka Ogawa
 - Masayoshi Takahashi
 - Matej Kollar
 - Mathias Schenner
+- Mathias Walter
+- Mathieu Boespflug
 - Mathieu Duponchelle
+- Matt Dodson
+- Matthew Doty
 - Matthew Eddey
 - Matthew Pickering
 - Matthias C. M. Troffaes
 - Mauro Bieg
 - Max Bolingbroke
+- Max Heller
 - Max Rydahl Andersen
+- Meher Chaitanya
 - Merijn Verstraaten
 - Michael Beaumont
 - Michael Chladek
+- Michael Hoffmann
+- Michael McClurg
+- Michael Peyton Jones
+- Michael Reed
 - Michael Snoyman
+- Michael Stahl
 - Michael Thompson
+- Mickaël Canouil
+- Mike Tzou
+- Mikołaj Machowski
+- Milan Bracke
 - MinRK
+- Mohamed Akram
+- Morgan Willcock
 - Morton Fox
 - Nathan Gass
+- Naveen
 - Neil Mayhew
 - Nick Bart
+- Nick Berendsen
+- Nick Fleisher
 - Nicolas Kaiser
+- Niklas Eicker
+- Nikolai Korobeinikov
 - Nikolay Yakimov
+- Nils Carlson
+- Nixon Enraght-Moony
+- Noah Malmed
+- Nokome Bentley
+- Norwid Behrnd
+- OCzarnecki
+- Ola Wolska
+- Ole Martin Ruud
+- Oliver Fabel
 - Oliver Matthews
+- Olivier Benz
+- Olivier Dossmann
 - Ophir Lifshitz
 - Or Neeman
+- OvidiusCicero
+- Owen McGrath
 - Pablo Rodríguez
+- Pascal Wagler
+- Pau RE
 - Paul Rivier
+- Paul Tilley
 - Paulo Tanimoto
+- Pavol Otto
+- Per Christian Gaustad
+- Pete Ryland
+- Peter Briggs
+- Peter Fabinksi
 - Peter Wang
+- Philip Pesca
 - Philippe Ombredanne
 - Phillip Alday
+- Pranesh Prakash
+- Prat
 - Prayag Verma
 - Puneeth Chaganti
+- Quinn
+- R. N. West
 - Ralf Stephan
 - Raniere Silva
+- Raymond Berger
+- Raymond Ehlers
 - Recai Oktaş
+- Repetitive
+- Reuben Thomas
+- Rowan Rodrik van der Molen
 - Roland Hieber
+- Roman Beránek
+- Ruqi
 - RyanGlScott
+- Ryan Gibb
+- S.P.H
+- Sai Asish Y
+- Salim B
+- Sam S. Almahri
+- Sam May
+- Samuel Tardieu
+- Saumel Lemmenmeier
+- Santiago Zarate
 - Sascha Wilde
 - Scott Morrison
+- Sean Soon
+- Sebastian Talmon
+- Sebbones
+- Sen-wen Deng
 - Sergei Trofimovich
 - Sergey Astanin
+- Seth Speaks
 - Shahbaz Youssefi
 - Shaun Attfield
+- Shim Myeongseob
+- Shin Sang-jae
 - Sidarth Kapur
+- Sidney Mau
 - Sidharth Kapur
 - Simon Hengel
+- Simon Schuster
+- Siphalor
 - Stefan Dresselhaus
+- Stephan Daus
+- Stephan Meijer
+- Stephen Altamirano
+- Stephen Huan
+- Stephen Reindl
+- Stéphane Guillou
+- Sukil Etxenike
+- Sukka
 - Sumit Sahrawat
+- Suraj Patil
+- Sven Wick
+- TEC
+- Tarik Graba
+- Tatiana Porras
+- Terence Eden
 - Thenaesh Elango
 - Thomas Hodgson
+- Thomas Soeiro
 - Thomas Weißschuh
+- Tiago-Manzato
 - Tim Lin
+- Tim Stewart
+- Tim Wisotzki
 - Timm Albers
 - Timothy Humphries
 - Tiziano Müller
 - Todd Sifleet
+- Tomas Dahlqvist
+- TomBen
 - Tom Leese
+- Toni Dietze
+- Tristan Stenner
+- Tristan de Cacqueray
+- Tristano Ajmone
+- Tuong Nguyen Manh
 - Uli Köhler
+- Urs Liska
+- Václav Haisman
 - Václav Zeman
+- Vaibhav Sagar
+- Vanessa McHale
+- Vasily Alferov
+- Veratyr
 - Viktor Kronvall
 - Vincent
-- Václav Haisman
-- Václav Zeman
-- Wandmalfarbe
+- Vlad Hanciuta
+- Vladimir Alexiev
 - Waldir Pimenta
+- Wandmalfarbe
+- Wentao Han
 - Wikiwide
+- William Lupton
+- William Rusnack
+- Winnie Hellmann
+- Wout Gevaert
 - Xavier Olive
+- Yan Pashkovsky
+- Yann Trividic
+- Yehuda Katz
+- YI
+- Yoan Blanc
+- You Jiangbin
 - Yuchen Pei
+- Zihang Chen
+- 3w36zj6
+- arcnmx
+- a-vrma
+- andrebauer
+- benniekiss
+- black-desk
+- blmage
 - bucklereed
 - bumper314
+- chinapedia
+- cholonam
+- closeobserve
 - csforste
 - d-dorazio
-- iandol
+- damon-sava-stanley
+- dbecher-ito
+- ebiim
+- ech0
+- etclub
+- favonia
+- guqicun
+- har7an
+- harabat
+- hseg
 - infinity0x
+- jeongminkim-islab
+- josch
+- kaizshang91
+- lawcho
+- lifeunleaded
+- lux-lth
+- luz paz
 - lwolfsonkin
+- massifrg
+- mbracke
+- mbrackeantidot
+- mh4ckt3mh4ckt1c4s
+- mjfs
+- mt_caret
+- nbehrnd
+- nibras shami
+- niszet
 - nkalvi
+- nuew
+- obcat
+- oltolm
+- oquechy
+- pacien
+- perro tuerto
+- piq9117
+- priiduonu
 - qerub
+- quasicomputational
+- reptee
+- ricnorr
 - robabla
 - roblabla
 - rodja.trappe
 - rski
+- samuel-weinhardt
+- sdhoward
 - shreevatsa.public
 - takahashim
+- taotieren
+- tecosaur
 - tgkokk
+- the-solipsist
+- thomjur
 - thsutton
+- thron7
+- timo-a
+- vijayphoenix
+- vkraven
+- wgevaert
+- wiefling
+- willj-dev
+- wuffi
+- λx.x
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -1,24 +1,87 @@
 Contributing to pandoc
 ======================
 
+Welcome to pandoc! Very soon after its beginnings in 2006, pandoc
+has been influenced, improved, and modified, by users, devs, and
+newcomers alike. The project thrives on its active community. It is
+great to have you here.
+
+How can I help?
+---------------
+
+There are many ways in which you can support pandoc. Here are a few
+ideas:
+
+  * Participate in online discussions. The [discussion
+    forum] is a good place for this.
+
+  * Help with questions. Every request that is answered by the wider
+    community frees time for programming contributors. This will
+    speed up development of new features and issue fixes. Don't
+    underestimate your knowledge, please share it!
+
+    Good places to help are the [discussion forum], Q/A
+    sites like StackOverflow, community forums (e.g.
+    [RStudio][RStudio Community], [Zettlr][Zettlr Forum]), and, for
+    technical questions, the GitHub [issue tracker].
+
+  * Write or improve documentation. If you ran into a problem which
+    took more time to figure out than expected, please consider to
+    save other users from the same experience. People writing the
+    documentation tend to lack an outside view, so please help
+    provide one. Good documentation is both difficult and extremely
+    important.
+
+    The official docs are not the only place for documentation.
+    Pandoc also has a [Wiki][pandoc wiki]. Private blogs can serve
+    as documentation just as the official manual can.
+
+  * Contribute code. No matter whether it's a small fix in a format
+    template or a huge lump of Haskell code: help is welcome. It's
+    usually a good idea to talk about the plans early, as this can
+    prevent unnecessary work. See below for more information.
+
+  * Last but not least: consider funding the development and
+    maintenance of pandoc financially. You can find sponsor buttons
+    on the [pandoc website] and the [GitHub repository][GitHub
+    repo].
+
+A rich ecosystem of libraries, editors, filters, and templates has
+developed around pandoc; conversely, pandoc builds and depends on a
+large number of libraries. Contributing to any of these projects is
+another way that can help to ensure stability, and to keep pushing
+the boundaries of what is possible with pandoc.
+
+[RStudio Community]: https://community.rstudio.com/
+[Zettlr Forum]: https://forum.zettlr.com/
+[pandoc wiki]: https://github.com/jgm/pandoc/wiki
+[pandoc website]: https://pandoc.org
+[GitHub repo]: https://github.com/jgm/pandoc
+
 Have a question?
 ----------------
 
-Ask on [pandoc-discuss].
+Ask on the [discussion forum].
 
 
 Found a bug?
 ------------
 
-Bug reports are welcome!  Please report all bugs on pandoc's github
+Bug reports are welcome!  Please report all bugs on pandoc's GitHub
 [issue tracker].
 
 Before you submit a bug report, search the [open issues] *and* [closed issues]
 to make sure the issue hasn't come up before. Also, check the [User's Guide] and
 [FAQs] for anything relevant.
 
-Make sure you can reproduce the bug with the [latest released version] of pandoc
-(or, even better, the [development version]).
+Make sure you can reproduce the bug with the [latest released
+version] of pandoc---or, even better, the development version,
+since the bug may have been fixed since the last release.
+[Nightly builds] are available, so you don't need to compile
+from source to test against the development version.
+(To fetch a nightly, visit the link, click the topmost "Nightly"
+in the table, then choose your platform under "Artifacts."  Note
+that you must be logged in with a GitHub account.)
 
 Your report should give detailed, *reproducible* instructions, including
 
@@ -55,7 +118,7 @@
 So before submitting a bug report, consider whether it might be
 "out of scope." If it concerns a feature of documents that isn't
 representable in pandoc's Markdown, then it very likely is.
-(If in doubt, you can always ask on [pandoc-discuss].)
+(If in doubt, you can always ask on the [discussion forum].)
 
 Fixing bugs from the issue tracker
 ----------------------------------
@@ -65,12 +128,12 @@
 bug. There is not yet a way to indicate priority. An up to date
 summary of issues can be found on [GitHub labels].
 
-* [beginner-friendly] — The perfect starting point for new contributors. The
+* [good first issue] — The perfect starting point for new contributors. The
   issue is generic and can be resolved without deep knowledge of the code
   base.
 * [enhancement] — A feature which would be desirable. We recommend
-  you discuss any proposed enhancement on pandoc-discuss before
-  writing code.
+  you discuss any proposed enhancement on the [discussion forum]
+  before writing code.
 * [bug] — A problem which needs to be fixed.
 * [complexity:low] — The fix should only be a couple of lines.
 * [complexity:high] — The fix might require structural changes or in depth
@@ -92,22 +155,29 @@
 Have an idea for a new feature?
 -------------------------------
 
-First, search [pandoc-discuss] and the issue tracker (both [open issues] *and*
+First, search the [discussion forum]
+and the issue tracker (both [open issues] *and*
 [closed issues]) to make sure that the idea has not been discussed before.
 
 Explain the rationale for the feature you're requesting.  Why would this
 feature be useful?  Consider also any possible drawbacks, including backwards
 compatibility, new library dependencies, and performance issues.
 
-It is best to discuss a potential new feature on [pandoc-discuss]
-before opening an issue.
+Features are very rarely "implement and forget", as all code must be
+maintained. This is especially relevant for large or complex
+contributions. It is helpful to be sympathetic to that fact, and to
+communicate future plans and availability clearly.
 
+Any potential new feature is best discussed on the [discussion
+forum] before opening an issue.
+
 Patches and pull requests
 -------------------------
 
 Patches and pull requests are welcome.  Before you put time into a nontrivial
-patch, it is a good idea to discuss it on [pandoc-discuss], especially if it is
-for a new feature (rather than fixing a bug).
+patch, it is a good idea to discuss it on the
+[discussion forum], especially if it is for a new feature (rather
+than fixing a bug).
 
 Please follow these guidelines:
 
@@ -144,13 +214,10 @@
 9.  It is better not to introduce new dependencies.  Dependencies on
     external C libraries should especially be avoided.
 
-10. We aim for compatibility with ghc versions from 7.8.3 to the
-    latest release.  All pull requests and commits are tested
-    automatically on <travis-ci.org>, using GHC versions in the
-    `Tested-With` stanza of `pandoc.cabal`.  We currently relax
-    the "`-Wall` clean" requirement for GHC 7.10.x, because
-    there are so many warnings relating to the addition of type
-    classes to the Prelude.
+10. We aim for compatibility with at least the last three
+    released ghc versions, and sometimes more.  Currently we
+    support ghc versions 9.6 and higher. All pull requests
+    and commits are tested automatically on GitHub Actions.
 
 Tests
 -----
@@ -169,6 +236,77 @@
 
 The test program is `test/test-pandoc.hs`.
 
+To run particular tests (pattern-matching on their names), use
+the `-p` option:
+
+    cabal install pandoc --enable-tests
+    cabal test --test-options='-p markdown'
+
+Or with stack:
+
+    stack test --test-arguments='-p markdown'
+
+It is often helpful to add `-j4` (run tests in parallel) and
+`--hide-successes` (don't clutter output with successes) to the test
+arguments as well. Collecting all options in a `cabal.project.local`
+file in the project's root directory can help to keep `cabal`
+commands short. E.g.:
+
+    flags: +embed_data_files
+    tests: True
+    test-show-details: direct
+    test-options: -j4 --hide-successes
+
+If you add a new feature to pandoc, please add tests as well, following
+the pattern of the existing tests. The test suite code is in
+`test/test-pandoc.hs`. If you are adding a new reader or writer, it is
+probably easiest to add some data files to the `test` directory, and
+modify `test/Tests/Old.hs`. Otherwise, it is better to modify the module
+under the `test/Tests` hierarchy corresponding to the pandoc module you
+are changing.  Alternatively, you may add a "command test" to
+the `/test/command/` hierarchy, following the pattern of the tests there.
+These test files should have a meaningful name, which can include the issue
+number and/or the feature that's being tested. For example, `5474-tables.md`
+refers to both issue and feature.
+
+You can rebuild the golden tests in `tests/` by passing
+`--accept` to the test script. (If you're using stack, `stack
+test --test-arguments "--accept"`; or `make TESTARGS=--accept`).
+Then check the changed golden files for accuracy, and
+commit the changes.  For docx or pptx tests, open the files in Word
+or Powerpoint to ensure that they weren't corrupted and that
+they had the expected result, and mention the Word/Powerpoint
+version and OS in your commit comment.
+
+Code style
+----------
+
+Pandoc uses [hlint] to identify opportunities for code improvements
+like redundant brackets or unnecessary `Language` extensions.
+However, sometimes there are cases where there are good reasons to
+use code different from what hlint proposes. In these cases, the
+respective warning should be disabled in the file `.hlint.yaml`.
+
+There should be no errors when running `hlint .`; this is checked by
+the continuous integration (CI) setup. It is recommended that
+contributors check their code with a local hlint installation, but
+relying on the CI is fine, too.
+
+A good way to ensure no new warnings are introduced is to use a Git
+[pre-commit hook] which runs hlint on all updated Haskell files
+before creating a commit:
+
+    #!/bin/sh
+    git diff --diff-filter=MA --cached --name-only | grep '\.hs$' | \
+      xargs hlint --hint .hlint.yaml
+
+(If you are using GNU `xargs`, add the `-r` option immediately
+after `xargs`.)
+
+Saving this to `.git/hooks/pre-commit`, and making the script
+executable, will prevent accidental introduction of potentially
+problematic code.
+
 Benchmarks
 ----------
 
@@ -182,29 +320,29 @@
 
     stack bench
 
-You can also build pandoc with the `weigh-pandoc` flag and
-run `weigh-pandoc` to get some statistics on memory usage.
-(Eventually this should be incorporated into the benchmark
-suite.)
 
 Using the REPL
 --------------
 
 With a recent version of cabal, you can do `cabal repl` and get
 a ghci REPL for working with pandoc.  With [stack], use
-`cabal ghci`.
+`stack ghci`.
 
 We recommend using the following `.ghci` file (which can be
 placed in the source directory):
 
-	:set -fobject-code
-	:set -XTypeSynonymInstances
-	:set -XScopedTypeVariables
-	:set -XOverloadedStrings
+    :set -fobject-code
+    :set -XTypeSynonymInstances
+    :set -XScopedTypeVariables
+    :set -XOverloadedStrings
 
 Profiling
 ---------
 
+To diagnose a performance issue with parsing, first try using
+the `--trace` option.  This will give you a record of when block
+parsers succeed, so you can spot backtracking issues.
+
 To use the GHC profiler with cabal:
 
     cabal clean
@@ -219,28 +357,11 @@
     pandoc +RTS -p -RTS [file]...
     less pandoc.prof
 
-Templates
----------
-
-The default templates live in `data/templates`, which is a git
-subtree linked to <https://github.com/jgm/pandoc-templates.git>.
-The purpose of maintaining a separate repository is to allow
-people to maintain variant templates as a fork.
-
-You can modify the templates and submit patches without worrying
-much about this: when these patches are merged, we will
-push them to the main templates repository by doing
-
-    git subtree push --prefix=data/templates templates master
-
-where `templates` is a remote pointing to the templates
-repository.
-
 The code
 --------
 
 Pandoc has a publicly accessible git repository on
-github: <http://github.com/jgm/pandoc>.  To get a local copy of the source:
+GitHub: <https://github.com/jgm/pandoc>.  To get a local copy of the source:
 
     git clone https://github.com/jgm/pandoc.git
 
@@ -250,7 +371,7 @@
 
 The modules `Text.Pandoc.Definition`, `Text.Pandoc.Builder`, and
 `Text.Pandoc.Generic` are in a separate library `pandoc-types`.  The code can
-be found in <http://github.com/jgm/pandoc-types>.
+be found in <https://github.com/jgm/pandoc-types>.
 
 To build pandoc, you will need a working installation of the
 [Haskell platform].
@@ -263,18 +384,18 @@
   - `Text.Pandoc.Definition` (in `pandoc-types`) defines the types
     used for representing a pandoc document.
   - `Text.Pandoc.Builder` (in `pandoc-types`) provides functions for
-    building pandoc documents programatically.
+    building pandoc documents programmatically.
   - `Text.Pandoc.Generics` (in `pandoc-types`) provides functions allowing
     you to promote functions that operate on parts of pandoc documents
     to functions that operate on whole pandoc documents, walking the
     tree automatically.
   - `Text.Pandoc.Readers.*` are the readers, and `Text.Pandoc.Writers.*`
     are the writers.
-  - `Text.Pandoc.Biblio` is a utility module for formatting citations
-    using citeproc-hs.
+  - `Text.Pandoc.Citeproc.*` contain the code for citation handling,
+    including an interface to the [citeproc] library.
   - `Text.Pandoc.Data` is used to embed data files when the `embed_data_files`
-    cabal flag is used.  It is generated from `src/Text/Pandoc/Data.hsb` using
-    the preprocessor [hsb2hs].
+    cabal flag is used.
+  - `Text.Pandoc.Emoji` is a thin wrapper around [emojis].
   - `Text.Pandoc.Highlighting` contains the interface to the
     skylighting library, which is used for code syntax highlighting.
   - `Text.Pandoc.ImageSize` is a utility module containing functions for
@@ -285,7 +406,6 @@
   - `Text.Pandoc.PDF` contains functions for producing a PDF from a
     LaTeX source.
   - `Text.Pandoc.Parsing` contains parsing functions used in multiple readers.
-  - `Text.Pandoc.Pretty` is a pretty-printing library specialized to
     the needs of pandoc.
   - `Text.Pandoc.SelfContained` contains functions for making an HTML
     file "self-contained," by importing remotely linked images, CSS,
@@ -302,19 +422,53 @@
   - `Text.Pandoc.UUID` contains functions for generating UUIDs.
   - `Text.Pandoc.XML` contains functions for formatting XML.
 
+Adding a new command-line option
+--------------------------------
+
+To add a new command-line option, you'll need to make changes in several
+places:
+
+- `MANUAL.txt` -- documentation for new option, both in the list
+  of options and in the section on defaults files.
+- `Text.Pandoc.App.Opt` -- new constructor for Opt and default
+  value
+- `Text.Pandoc.App.CommandLineOptions` -- the option parser
+- `Text.Pandoc.App` or `Text.Pandoc.App.OutputSettings` --
+  handle the new option
+- possibly in pandoc-server: `Text.Pandoc.Server` -- handle the
+  new option
+
+If your change requires a new field for ReaderOptions or
+WriterOptions, you'll also need to
+
+- `Text.Pandoc.Options` -- type change and default value
+- in pandoc-lua-engine: Text.Pandoc.Lua.Marshal.WriterOptions
+  and/or Text.Pandoc.Lua.Marshal.ReaderOptions
+
+Lua filters
+-----------
+
+If you've written a useful pandoc [lua filter](./doc/lua-filters.md),
+you may want to consider submitting a pull request to the
+[lua-filters repository](https://github.com/pandoc/lua-filters).
+
 [open issues]: https://github.com/jgm/pandoc/issues
 [closed issues]: https://github.com/jgm/pandoc/issues?q=is%3Aissue+is%3Aclosed
 [latest released version]: https://github.com/jgm/pandoc/releases/latest
-[development version]: https://github.com/pandoc-extras/pandoc-nightly/releases/latest
-[pandoc-discuss]: http://groups.google.com/group/pandoc-discuss
+[Nightly builds]: https://github.com/jgm/pandoc/actions?query=workflow%3ANightly
+[pandoc-discuss]: https://groups.google.com/group/pandoc-discuss
 [issue tracker]: https://github.com/jgm/pandoc/issues
-[User's Guide]: http://pandoc.org/MANUAL.html
-[FAQs]:  http://pandoc.org/faqs.html
-[EditorConfig]: http://editorconfig.org/
-[Haskell platform]: http://www.haskell.org/platform/
-[hsb2hs]: http://hackage.haskell.org/package/hsb2hs
+[User's Guide]: https://pandoc.org/MANUAL.html
+[FAQs]:  https://pandoc.org/faqs.html
+[EditorConfig]: https://editorconfig.org/
+[Haskell platform]: https://www.haskell.org/platform/
+[hlint]: https://hackage.haskell.org/package/hlint
+[citeproc]: https://hackage.haskell.org/package/citeproc
+[emojis]: https://hackage.haskell.org/package/emojis
+[hsb2hs]: https://hackage.haskell.org/package/hsb2hs
+[pre-commit hook]: https://git-scm.com/book/en/v2/Customizing-Git-Git-Hooks
 [GitHub labels]: https://github.com/jgm/pandoc/labels
-[beginner-friendly]: https://github.com/jgm/pandoc/labels/beginner-friendly
+[good first issue]:https://github.com/jgm/pandoc/labels/good%20first%20issue
 [enhancement]: https://github.com/jgm/pandoc/labels/enhancement
 [bug]: https://github.com/jgm/pandoc/labels/bug
 [complexity:low]: https://github.com/jgm/pandoc/labels/complexity:low
@@ -327,4 +481,5 @@
 [status:more-discussion-needed]: https://github.com/jgm/pandoc/labels/status:more-discussion-needed
 [status:more-info-needed]: https://github.com/jgm/pandoc/labels/status:more-info-needed
 [stack]: https://github.com/commercialhaskell/stack
+[discussion forum]: https://github.com/jgm/pandoc/discussions
 
diff --git a/COPYING.md b/COPYING.md
--- a/COPYING.md
+++ b/COPYING.md
@@ -3,8 +3,8 @@
 Version 2, June 1991
 
     Copyright (C) 1989, 1991 Free Software Foundation, Inc.  
-    51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
-
+    <https://fsf.org/>
+    
     Everyone is permitted to copy and distribute verbatim copies
     of this license document, but changing it is not allowed.
 
@@ -317,10 +317,9 @@
     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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+    
+    You should have received a copy of the GNU General Public License along
+    with this program; if not, see <https://www.gnu.org/licenses/>.
 
 Also add information on how to contact you by electronic and paper
 mail.
@@ -357,5 +356,5 @@
 you may consider it more useful to permit linking proprietary
 applications with the library. If this is what you want to do, use the
 [GNU Lesser General Public
-License](http://www.gnu.org/licenses/lgpl.html) instead of this
+License](https://www.gnu.org/licenses/lgpl.html) instead of this
 License.
diff --git a/COPYRIGHT b/COPYRIGHT
--- a/COPYRIGHT
+++ b/COPYRIGHT
@@ -1,5 +1,5 @@
 Pandoc
-Copyright (C) 2006-2017 John MacFarlane <jgm at berkeley dot edu>
+Copyright (C) 2006-2024 John MacFarlane <jgm at berkeley dot edu>
 
 With the exceptions noted below, this code is released under the [GPL],
 version 2 or later:
@@ -14,19 +14,18 @@
    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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+   You should have received a copy of the GNU General Public License along
+   with this program; if not, see <https://www.gnu.org/licenses/>.
 
 The GNU General Public License is available in the file COPYING.md in
 the source distribution.  On Debian systems, the complete text of the
 GPL can be found in `/usr/share/common-licenses/GPL`.
 
-[GPL]: http://www.gnu.org/copyleft/gpl.html
-
-Pandoc's complete source code is available from the [Pandoc home page].
+[GPL]: https://www.gnu.org/copyleft/gpl.html
 
-[Pandoc home page]: http://pandoc.org
+The complete source code for pandoc version X.Y.Z is available at
+<https://hackage.haskell.org/package/pandoc-X.Y.Z/pandoc-X.Y.Z.tar.gz>
+and at <https://github.com/jgm/pandoc/tree/X.Y.Z>.
 
 Pandoc includes some code with different copyrights, or subject to different
 licenses.  The copyright and license statements for these sources are included
@@ -37,7 +36,7 @@
 Text.Pandoc.Builder, Text.Pandoc.Generics, Text.Pandoc.JSON,
 Text.Pandoc.Walk) are licensed under the BSD 3-clause license:
 
-Copyright (c) 2006-2017, John MacFarlane
+Copyright (c) 2006-2024, John MacFarlane
 
 All rights reserved.
 
@@ -69,32 +68,33 @@
 OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 
 ----------------------------------------------------------------------
-Pandoc's templates (in `data/templates`) are dual-licensed GPL (v2 or
-higher, same as pandoc) and the BSD 3-clause license.
+Pandoc's templates (in `data/templates`) are dual-licensed as either
+GPL (v2 or higher, same as pandoc) or (at your option) the BSD
+3-clause license.
 
-Copyright (c) 2014--2017, John MacFarlane
+Copyright (c) 2014--2024, John MacFarlane
 
 ----------------------------------------------------------------------
 src/Text/Pandoc/Writers/Muse.hs
-Copyright (C) 2017 Alexander Krotov
+Copyright (C) 2017-2020 Alexander Krotov
 
 Released under the GNU General Public License version 2 or later.
 
 ----------------------------------------------------------------------
 src/Text/Pandoc/Writers/Texinfo.hs
-Copyright (C) 2008-2017 John MacFarlane and Peter Wang
+Copyright (C) 2008-2024 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-2017 Andrea Rossato and John MacFarlane
+Copyright (C) 2008-2024 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-2017 Puneeth Chaganti, John MacFarlane, and
+Copyright (C) 2010-2024 Puneeth Chaganti, John MacFarlane, and
                         Albert Krewinkel
 
 Released under the GNU General Public License version 2 or later.
@@ -108,54 +108,75 @@
 ----------------------------------------------------------------------
 src/Text/Pandoc/Readers/Docx.hs
 src/Text/Pandoc/Readers/Docx/*
-Copyright (C) 2014-2017 Jesse Rosenthal
+Copyright (C) 2014-2020 Jesse Rosenthal
 
 Released under the GNU General Public License version 2 or later.
 
 ----------------------------------------------------------------------
 src/Text/Pandoc/Readers/Textile.hs
-Copyright (C) 2010-2017 Paul Rivier and John MacFarlane
+Copyright (C) 2010-2024 Paul Rivier and John MacFarlane
 
 Released under the GNU General Public License version 2 or later.
 
 ----------------------------------------------------------------------
+src/Text/Pandoc/Readers/TikiWiki.hs
+Copyright (C) 2017 Robin Lee Powell
+
+Released under the GNU General Public License version 2 or later.
+
+----------------------------------------------------------------------
+src/Text/Pandoc/Readers/JATS.hs
+Copyright (C) 2017-2018 Hamish Mackenzie
+
+Released under the GNU General Public License version 2 or later.
+
+----------------------------------------------------------------------
+src/Text/Pandoc/Readers/EPUB.hs
+Copyright (C) 2014-2024 Matthew Pickering and John MacFarlane
+
+Released under the GNU General Public License version 2 or later.
+
+----------------------------------------------------------------------
 src/Text/Pandoc/Readers/Org.hs
-test/Tests/Readers/Org.hs
-Copyright (C) 2014-2017 Albert Krewinkel
+src/Text/Pandoc/Readers/Org/*
+test/Tests/Readers/Org/*
+Copyright (C) 2014-2024 Albert Krewinkel
 
 Released under the GNU General Public License version 2 or later.
 
 ----------------------------------------------------------------------
-data/LaTeXMathML.js
-Adapted by Jeff Knisely and Douglas Woodall from
-ASCIIMathML.js v. 1.4.7
-Copyright (C) 2005 Peter Jipsen
+pandoc-lua-engine/src/Text/Pandoc/Lua.hs
+pandoc-lua-engine/src/Text/Pandoc/Lua/*
+pandoc-lua-engine/test/lua/*
+Copyright (C) 2017--2024 Albert Krewinkel and John MacFarlane
 
 Released under the GNU General Public License version 2 or later.
 
 ----------------------------------------------------------------------
-data/MathMLinHTML.js
-Copyright (C) 2004 Peter Jipsen http://www.chapman.edu/~jipsen
+src/Text/Pandoc/Readers/Jira.hs
+src/Text/Pandoc/Writers/Jira.hs
+test/Tests/Readers/Jira.hs
+Copyright (C) 2019--2024 Albert Krewinkel
 
 Released under the GNU General Public License version 2 or later.
 
-------------------------------------------------------------------------
-data/pandoc.lua
-Copyright (C) 2017 Albert Krewinkel
+----------------------------------------------------------------------
+src/Text/Pandoc/Readers/FB2.hs
+Copyright (C) 2018--2019 Alexander Krotov
 
 Released under the GNU General Public License version 2 or later.
 
 ----------------------------------------------------------------------
 The dzslides template contains JavaScript and CSS from Paul Rouget's
 dzslides template.
-http://github.com/paulrouget/dzslides
+https://github.com/paulrouget/dzslides
 
 Released under the Do What the Fuck You Want To Public License.
 
 ------------------------------------------------------------------------
-Pandoc embeds a lua interpreter (via hslua).
+Pandoc embeds a Lua interpreter (via hslua).
 
-Copyright © 1994–2015 Lua.org, PUC-Rio.
+Copyright © 1994--2023 Lua.org, PUC-Rio.
 
 Permission is hereby granted, free of charge, to any person obtaining
 a copy of this software and associated documentation files (the
@@ -177,10 +198,28 @@
 WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 
 ------------------------------------------------------------------------
-The template pandoc.jats is Copyright 2013--15 Martin Fenner,
-released under GPL version 2 or later.
+Some of the code in wasm/pandoc.js and the patches in wasm/patches is
+from https://github.com/haskell-wasm/pandoc-wasm. It is released under
+this license:
 
-The file data/jats.csl is derived from a csl file by Martin Fenner,
-revised by Martin Paul Eve and then John MacFarlane.
-"This work is licensed under a Creative Commons Attribution-ShareAlike 3.0
-License. Originally by Martin Fenner."
+MIT License
+
+Copyright (c) Tweag I/O Limited.
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/INSTALL.md b/INSTALL.md
--- a/INSTALL.md
+++ b/INSTALL.md
@@ -1,95 +1,209 @@
 # Installing pandoc
 
+The simplest way to get the latest pandoc release is to use the installer.
+
+<a href="https://github.com/jgm/pandoc/releases/latest"
+  class="btn btn-primary" id="downloadInstallerBtn">
+  Download the latest installer
+</a>
+
+For alternative ways to install pandoc, see below under the heading for
+your operating system.
+
+**Note**: the statically linked Pandoc binaries provided by us (or those
+available on Conda Forge) have a limitation. They are unable to utilise Lua
+filters that rely on Lua modules written in C. If you require the
+functionality offered by these filters, please consider an alternative
+method of installation.
+
 ## Windows
 
-  - There is a package installer at pandoc's [download page].
-    This will install pandoc, replacing older versions, and
-    update your path to include the directory where pandoc's
-    binaries are installed.
+There is a package installer at pandoc's [download page].
+This will install pandoc, replacing older versions, and
+update your path to include the directory where pandoc's
+binaries are installed.
 
-  - If you prefer not to use the msi installer, we also provide
-    a zip file that contains pandoc's binaries and
-    documentation.  Simply unzip this file and move the binaries
-    to a directory of your choice.
+If you prefer not to use the msi installer, we also provide
+a zip file that contains pandoc's binaries and
+documentation.  Simply unzip this file and move the binaries
+to a directory of your choice.
 
-  - For PDF output, you'll also need to install LaTeX.
-    We recommend [MiKTeX](http://miktex.org/).
+Alternatively, you can install pandoc using
+[Chocolatey](https://chocolatey.org):
 
+    choco install pandoc
+
+Chocolatey can also install other software that integrates with Pandoc.
+For example, to install `rsvg-convert` (from [librsvg], covering formats
+without SVG support), [Python] (to use Pandoc filters), and
+[MiKTeX] (to typeset PDFs with [LaTeX]):
+
+    choco install rsvg-convert python miktex
+
+Or, you can install pandoc using
+[winget](https://github.com/microsoft/winget-pkgs):
+
+    winget install --source winget --exact --id JohnMacFarlane.Pandoc
+
+Or, you can install Pandoc using [Conda forge].
+
+Using multiple installation methods can result in two separate
+installations of pandoc; it is recommended to properly uninstall
+pandoc before switching to an alternative installation method.
+
+By default, Pandoc creates PDFs using LaTeX.  We recommend
+installing it via [MiKTeX]. With the option `--pdf-engine`,
+you however can specify other programs for this task.
+
 ## macOS
 
-  - You can install pandoc using
-    [homebrew](http://brew.sh): `brew install pandoc`.
+There is a package installer at pandoc's [download page].
+If you later want to uninstall the package, you can do so
+by downloading [this script][uninstaller]
+and running it with `perl uninstall-pandoc.pl`.
 
-  - There is a package installer at pandoc's [download page].
-    If you later want to uninstall the package, you can do so
-    by downloading [this script][uninstaller]
-    and running it with `perl uninstall-pandoc.pl`.
+Alternatively, you can install pandoc using
+[Homebrew](https://brew.sh):
 
-  - We also provide a zip file containing the binaries and man
-    pages, for those who prefer not to use the installer.  Simply
-    unzip the file and move the binaries and man pages to
-    whatever directory you like.
+     brew install pandoc
 
-  - For PDF output, you'll also need LaTeX.  Because a full [MacTeX]
-    installation takes more than a gigabyte of disk space, we recommend
-    installing [BasicTeX](http://www.tug.org/mactex/morepackages.html)
-    (64M) and using the `tlmgr` tool to install additional packages
-    as needed.  If you get errors warning of fonts not found, try
+Homebrew can also install other software that integrates with Pandoc.
+For example, to install [librsvg] (its `rsvg-convert` covers formats
+without SVG support), [Python] (to use Pandoc filters), and
+[BasicTeX] (to typeset PDFs with [LaTeX]):
 
-        tlmgr install collection-fontsrecommended
+     brew install librsvg python homebrew/cask/basictex
 
+Note: On unsupported versions of macOS (more than three releases old),
+Homebrew installs from source, which takes additional time and disk space
+for the `ghc` compiler and dependent Haskell libraries.
+
+You can also install pandoc using [MacPorts]:
+
+    port install pandoc
+
+Or, you can install Pandoc using [Conda forge].
+
+We also provide a zip file containing the binaries and man
+pages, for those who prefer not to use the installer.  Simply
+unzip the file and move the binaries and man pages to
+whatever directory you like.
+
+By default, Pandoc creates PDFs using LaTeX.  Because a full [MacTeX]
+installation uses four gigabytes of disk space, we recommend
+[BasicTeX] or [TinyTeX](https://yihui.org/tinytex/)
+and using the `tlmgr` tool to install additional packages
+as needed.  If you receive errors warning of fonts not found:
+
+    tlmgr install collection-fontsrecommended
+
+With the option `--pdf-engine`, you however can specify other programs
+for this task.
+
 ## Linux
 
-  - First, try your package manager.
-    Pandoc is in the [Debian], [Ubuntu], [Slackware],
-    [Arch], [Fedora], [NiXOS], [openSUSE], and [gentoo] repositories.
-    Note, however, that versions in the repositories are often
-    old.
+Check whether the pandoc version in your package manager is
+not outdated. Pandoc is in the [Debian], [Ubuntu], [Slackware],
+[Arch], [Fedora], [NixOS], [openSUSE], [gentoo] and [Void] repositories.
 
-  - We provide a binary package for amd64 architecture on
-    the [download page].  This provides both `pandoc` and
-    `pandoc-citeproc`. The executables are statically linked and
-    have no dynamic dependencies or dependencies on external
-    data files.  Note:  because of the static
-    linking, the pandoc binary from this package cannot use lua
-    filters that require external lua modules written in C.
+To get the latest release, we provide a binary package for amd64
+architecture on the **[download page]**.
 
-    Both a tarball and a deb installer are provided.  To install the deb:
+The executable is statically linked and
+has no dynamic dependencies or dependencies on external
+data files.
 
-        sudo dpkg -i $DEB
+Both a tarball and a deb installer are provided.  To install the deb:
 
-    where `$DEB` is the path to the downloaded deb.  This will
-    install the `pandoc` and `pandoc-citeproc` executables and
-    man pages.
+    sudo dpkg -i $DEB
 
-    If you use an RPM-based distro, you may be able to install
-    the deb from our download page using `alien`.
+where `$DEB` is the path to the downloaded deb.  This will
+install the `pandoc` executable and man page.
 
-    On any distro, you may install from the tarball into `$DEST`
-    (say, `/usr/local/` or `$HOME/.local`) by doing
+If you use an RPM-based distro, you may be able to install
+the deb from our download page using `alien`.
 
-        tar xvzf $TGZ --strip-components 1 -C $DEST
+On any distro, you may install from the tarball into `$DEST`
+(say, `/usr/local/` or `$HOME/.local`) by doing
 
-    where `$TGZ` is the path to the downloaded zipped tarball.
-    For Pandoc versions before 2.0, which don't provide
-    a tarball, try instead
+    tar xvzf $TGZ --strip-components 1 -C $DEST
 
-        ar p $DEB data.tar.gz | tar xvz --strip-components 2 -C $DEST
+where `$TGZ` is the path to the downloaded zipped tarball.
+For Pandoc versions before 2.0, which don't provide
+a tarball, try instead
 
-  - You can also install from source, using the
-    instructions below under [Compiling from source].
-    Note that most distros have the Haskell platform in their
-    package repositories.  For example, on Debian/Ubuntu,
-    you can install it with `apt-get install haskell-platform`.
+    ar p $DEB data.tar.gz | tar xvz --strip-components 2 -C $DEST
 
-  - For PDF output, you'll need LaTeX.  We recommend installing
-    [TeX Live](http://www.tug.org/texlive/) via your package
-    manager.  (On Debian/Ubuntu, `apt-get install texlive`.)
+Or, you can install Pandoc using [Conda forge].
 
+You can also install from source, using the
+instructions below under [Compiling from source].
+
+By default, Pandoc creates PDFs using LaTeX.  We recommend installing
+[TeX Live](https://www.tug.org/texlive/) via your package
+manager.  (On Debian/Ubuntu, `apt-get install texlive`.)  With the option
+`--pdf-engine`, you however can specify other programs for this task.
+
+## Chrome OS
+
+On Chrome OS, pandoc can be installed using the
+[chromebrew](https://github.com/skycocker/chromebrew) package manager
+with the command:
+
+```sh
+crew install pandoc
+```
+
+This will automatically build and configure pandoc for the specific
+device you are using.
+
 ## BSD
 
-  - Pandoc is in the [NetBSD] and [FreeBSD ports] repositories.
+Pandoc is in the [NetBSD], [FreeBSD], and [OpenBSD ports] repositories.
 
+## Conda Forge
+
+You can install Pandoc using a [Conda
+Forge](https://anaconda.org/conda-forge/pandoc) tool, like
+[Conda](https://conda.pydata.org/docs/intro.html),
+[[Micro]Mamba](https://mamba.readthedocs.io/en/latest/index.html) or
+[Pixi](https://prefix.dev). Conda forge also includes multiple LaTeX and
+other relevant packages for Pandoc (including `pandoc-citeproc`,
+`pandoc-plot`, `rsvg-convert` via `librsvg` etc.). **Note:** conda forge
+installs a statically-linked executable.
+
+    conda install -c conda-forge pandoc
+    pixi global install pandoc
+    micromamba install pandoc
+
+## Docker
+
+The official Docker images for pandoc can be found at
+<https://github.com/pandoc/dockerfiles> and at
+[dockerhub](https://hub.docker.com/).
+
+The [pandoc/core](https://hub.docker.com/r/pandoc/core)
+image contains `pandoc`.
+
+The [pandoc/latex](https://hub.docker.com/r/pandoc/latex)
+image also contains the minimal LaTeX installation needed
+to produce PDFs using pandoc.
+
+To run pandoc using Docker, converting `README.md` to `README.pdf`:
+
+    docker run --rm --volume "`pwd`:/data" --user `id -u`:`id -g` pandoc/latex README.md -o README.pdf
+
+## GitHub Actions
+
+Pandoc can be run through
+[GitHub Actions](https://github.com/features/actions).  For some
+examples, see <https://github.com/pandoc/pandoc-action-example>.
+
+## GitLab CI/CD
+
+Pandoc can be run through [GitLab CI/CD].  For some
+examples, see <https://gitlab.com/pandoc/pandoc-ci-example>.
+
 ## Compiling from source
 
 If for some reason a binary package is not available for your
@@ -118,14 +232,13 @@
 
 ### Quick stack method
 
-The easiest way to build pandoc from source is to use [stack]:
-
-1.  Install [stack].
+The easiest way to build pandoc from source is to use [stack][stack]:
 
-2.  Change to the pandoc source directory and issue the following commands:
+1.  Install [stack][stack]. Note that Pandoc requires stack >= 1.7.0.
 
+2.
         stack setup
-        stack install --test
+        stack install pandoc-cli
 
     `stack setup` will automatically download the ghc compiler
     if you don't have it.  `stack install` will install the
@@ -133,11 +246,11 @@
     add to your `PATH`.  This process will take a while, and
     will consume a considerable amount of disk space.
 
+
 ### Quick cabal method
 
-1.  Install the [Haskell platform].  This will give you [GHC] and
-    the [cabal-install] build tool.  Note that pandoc requires
-    GHC >= 7.8.
+1.  Install [ghcup](https://www.haskell.org/ghcup/install/).
+    This will give you `ghc` and `cabal`.
 
 2.  Update your package database:
 
@@ -145,52 +258,30 @@
 
 3.  Use `cabal` to install pandoc and its dependencies:
 
-        cabal install pandoc --enable-tests
+        cabal install pandoc-cli
 
     This procedure will install the released version of pandoc,
     which will be downloaded automatically from HackageDB.
-
-    If you want to install a modified or development version
-    of pandoc instead, switch to the source directory and do
-    as above, but without the 'pandoc':
+    The `pandoc` executable will be symlinked in`$HOME/.cabal/bin`
+    on linux/unix/macOS and in `%APPDATA%\cabal\bin` on Windows.
+    Make sure this directory is in your path. To specify a
+    custom install directory, use `--installdir`. To have
+    the executable copied instead of symlinked, use
+    `--install-method=copy`.
 
-        cabal install
+    If you want to install a modified or development version of
+    pandoc instead, switch to the source directory before running
+    the above command -- cabal will use the local code for all
+    projects mentioned in the `cabal.project`.
 
-4.  Make sure the `$CABALDIR/bin` directory is in your path.  You should
-    now be able to run `pandoc`:
+4.  You should now be able to run `pandoc`:
 
         pandoc --help
 
-    [Not sure where `$CABALDIR` is?](http://www.haskell.org/haskellwiki/Cabal-Install#The_cabal-install_configuration_file)
-
-5.  If you want to process citations with pandoc, you will also need to
-    install a separate package, `pandoc-citeproc`.  This can be installed
-    using cabal:
-
-        cabal install pandoc-citeproc
-
-    By default `pandoc-citeproc` uses the "i;unicode-casemap" method
-    to sort bibliography entries (RFC 5051).  If you would like to
-    use the locale-sensitive unicode collation algorithm instead,
-    specify the `unicode_collation` flag:
-
-        cabal install pandoc-citeproc -funicode_collation
-
-    Note that this requires the `text-icu` library, which in turn
-    depends on the C library `icu4c`.  Installation directions
-    vary by platform.  Here is how it might work on macOS with homebrew:
-
-        brew install icu4c
-        cabal install --extra-lib-dirs=/usr/local/Cellar/icu4c/51.1/lib \
-          --extra-include-dirs=/usr/local/Cellar/icu4c/51.1/include \
-          -funicode_collation text-icu pandoc-citeproc
-
-6.  The `pandoc.1` man page will be installed automatically.  cabal shows
-    you where it is installed: you may need to set your `MANPATH`
-    accordingly. If `MANUAL.txt` has been modified, the man page can be
-    rebuilt: `make man/pandoc.1`.
-
-    The `pandoc-citeproc.1` man page will also be installed automatically.
+5.  Cabal does not install the `pandoc.1` man page, but you can
+    copy it from the `man/` directory of the source code to
+    `/usr/local/share/man/man1/` or wherever man pages go on
+    your system.
 
 
 ### Custom cabal method
@@ -200,13 +291,12 @@
 quick install, but this information may be of use to packagers.
 For more details, see the [Cabal User's Guide].  These instructions
 assume that the pandoc source directory is your working directory.
+You will need cabal version 2.0 or higher.
 
-1.  Install dependencies:  in addition to the [Haskell platform],
-    you will need a number of additional libraries.  You can install
-    them all with
+1.  Install dependencies:
 
         cabal update
-        cabal install --only-dependencies
+        cabal build --only-dependencies
 
 2.  Configure:
 
@@ -220,14 +310,20 @@
 
     `FLAGSPEC` is a list of Cabal configuration flags, optionally
     preceded by a `-` (to force the flag to `false`), and separated
-    by spaces.  Pandoc's flags include:
+    by spaces.  `pandoc`'s flags include:
 
     - `embed_data_files`: embed all data files into the binary (default no).
       This is helpful if you want to create a relocatable binary.
 
-    - `https`:  enable support for downloading resources over https
-      (using the `http-client` and `http-client-tls` libraries).
+    `pandoc-cli`'s flags include:
 
+    - `lua`:  compile in support for Lua filters and custom
+      writers.
+
+    - `server`:  compile in support for running in HTTP server
+      mode when the executable is renamed (or symlinked as)
+      `pandoc-server`.
+
 3.  Build:
 
         cabal build
@@ -237,19 +333,9 @@
 
         cabal haddock --html-location=URL --hyperlink-source
 
-5.  Copy the files:
-
-        cabal copy --destdir=PATH
-
-    The default destdir is `/`.
-
-6.  Register pandoc as a GHC package:
-
-        cabal register
+5.  Install
 
-    Package managers may want to use the `--gen-script` option to
-    generate a script that can be run to register the package at
-    install time.
+        cabal install pandoc-cli
 
 ### Creating a relocatable binary
 
@@ -257,12 +343,10 @@
 pandoc uses are embedded in the binary.  The resulting binary
 can be run from any directory and is completely self-contained.
 With cabal, add `-fembed_data_files` to the `cabal configure`
-or `cabal install` commands.
+or `cabal build` commands.
 
 With stack, use `--flag pandoc:embed_data_files`.
 
-
-
 ### Running tests
 
 Pandoc comes with an automated test suite.
@@ -310,25 +394,31 @@
     cabal bench --benchmark-options='markdown'
 
 
-[Arch]: https://www.archlinux.org/packages/community/x86_64/pandoc/
-[Cabal User's Guide]: http://www.haskell.org/cabal/release/latest/doc/users-guide/builders.html#setup-configure-paths
-[Debian]: https://packages.debian.org/pandoc
-[Fedora]: https://apps.fedoraproject.org/packages/pandoc
-[FreeBSD ports]: http://www.freshports.org/textproc/pandoc/
-[GHC]:  http://www.haskell.org/ghc/
-[GPL]:  http://www.gnu.org/copyleft/gpl.html
-[Haskell platform]: http://hackage.haskell.org/platform/
-[MacPorts]: http://trac.macports.org/browser/trunk/dports/textproc/pandoc/Portfile
+[Arch]: https://archlinux.org/packages/?q=pandoc
+[Cabal User's Guide]: https://cabal.readthedocs.io/
+[Debian]: https://packages.debian.org/search?keywords=pandoc
+[Fedora]: https://packages.fedoraproject.org/pkgs/pandoc/pandoc/
+[FreeBSD]: https://www.freshports.org/textproc/hs-pandoc/
+[GHC]:  https://www.haskell.org/ghc/
+[GitLab CI/CD]: https://about.gitlab.com/stages-devops-lifecycle/continuous-integration/
+[MacPorts]: https://ports.macports.org/port/pandoc/
 [MacTeX]: https://tug.org/mactex/
-[NetBSD]: http://pkgsrc.se/wip/pandoc
-[NixOS]: https://nixos.org/nixos/packages.html
+[OpenBSD ports]: https://cvsweb.openbsd.org/ports/textproc/pandoc/
+[BasicTeX]: https://www.tug.org/mactex/morepackages.html
+[LaTeX]: https://www.latex-project.org
+[MiKTeX]: https://miktex.org/
+[librsvg]: https://wiki.gnome.org/Projects/LibRsvg
+[Python]: https://www.python.org
+[NetBSD]: https://pkgsrc.se/converters/pandoc
+[NixOS]: https://search.nixos.org/packages?query=pandoc
 [Slackware]: https://www.slackbuilds.org/result/?search=pandoc&sv=
-[Ubuntu]: https://packages.ubuntu.com/pandoc
+[Ubuntu]: https://packages.ubuntu.com/search?keywords=pandoc
 [download page]: https://github.com/jgm/pandoc/releases/latest
-[gentoo]: http://packages.gentoo.org/package/app-text/pandoc
+[gentoo]: https://packages.gentoo.org/package/app-text/pandoc
 [haskell repository]: https://wiki.archlinux.org/index.php/Haskell_Package_Guidelines#.5Bhaskell.5D
 [openSUSE]: https://software.opensuse.org/package/pandoc
-[source tarball]: http://hackage.haskell.org/package/pandoc
-[stack]: http://docs.haskellstack.org/en/stable/install_and_upgrade.html
-[cabal-install]: http://hackage.haskell.org/trac/hackage/wiki/CabalInstall
-[uninstaller]: https://raw.githubusercontent.com/jgm/pandoc/master/macos/uninstall-pandoc.pl
+[source tarball]: https://hackage.haskell.org/package/pandoc
+[stack]: https://docs.haskellstack.org/en/stable/install_and_upgrade.html
+[cabal-install]: https://hackage.haskell.org/package/cabal-install
+[Void]: https://voidlinux.org/packages/?arch=x86_64&q=pandoc
+[uninstaller]: https://raw.githubusercontent.com/jgm/pandoc/main/macos/uninstall-pandoc.pl
diff --git a/MANUAL.txt b/MANUAL.txt
--- a/MANUAL.txt
+++ b/MANUAL.txt
@@ -1,4499 +1,8054 @@
-% Pandoc User's Guide
-% John MacFarlane
-% December 27, 2017
-
-Synopsis
-========
-
-`pandoc` [*options*] [*input-file*]...
-
-Description
-===========
-
-Pandoc is a [Haskell] library for converting from one markup format to
-another, and a command-line tool that uses this library. It can read
-[Markdown], [CommonMark], [PHP Markdown Extra], [GitHub-Flavored
-Markdown], [MultiMarkdown], and (subsets of) [Textile],
-[reStructuredText], [HTML], [LaTeX], [MediaWiki markup], [TWiki
-markup], [TikiWiki markup], [Creole 1.0], [Haddock markup], [OPML],
-[Emacs Org mode], [DocBook], [JATS], [Muse], [txt2tags], [Vimwiki],
-[EPUB], [ODT], and [Word docx]; and it can write plain text, [Markdown],
-[CommonMark], [PHP Markdown Extra], [GitHub-Flavored Markdown],
-[MultiMarkdown], [reStructuredText], [XHTML], [HTML5], [LaTeX]
-\(including [`beamer`] slide shows\), [ConTeXt], [RTF], [OPML],
-[DocBook], [JATS], [OpenDocument], [ODT], [Word docx], [GNU Texinfo],
-[MediaWiki markup], [DokuWiki markup], [ZimWiki markup], [Haddock
-markup], [EPUB] \(v2 or v3\), [FictionBook2], [Textile], [groff man],
-[groff ms], [Emacs Org mode], [AsciiDoc], [InDesign ICML], [TEI
-Simple], [Muse], [PowerPoint] slide shows and [Slidy], [Slideous],
-[DZSlides], [reveal.js] or [S5] HTML slide shows. It can also produce
-[PDF] output on systems where LaTeX, ConTeXt, `pdfroff`,
-`wkhtmltopdf`, `prince`, or `weasyprint` is installed.
-
-Pandoc's enhanced version of Markdown includes syntax for [footnotes],
-[tables], flexible [ordered lists], [definition lists], [fenced code
-blocks], [superscripts and subscripts], [strikeout], [metadata blocks],
-automatic tables of contents, embedded LaTeX [math], [citations], and
-[Markdown inside HTML block elements][Extension:
-`markdown_in_html_blocks`]. (These enhancements, described further under
-[Pandoc's Markdown], can be disabled using the `markdown_strict` input
-or output format.)
-
-In contrast to most existing tools for converting Markdown to HTML, which
-use regex substitutions, pandoc has a modular design: it consists of a
-set of readers, which parse text in a given format and produce a native
-representation of the document, and a set of writers, which convert
-this native representation into a target format. Thus, adding an input
-or output format requires only adding a reader or writer.
-
-Because pandoc's intermediate representation of a document is less
-expressive than many of the formats it converts between, one should
-not expect perfect conversions between every format and every other.
-Pandoc attempts to preserve the structural elements of a document, but
-not formatting details such as margin size.  And some document elements,
-such as complex tables, may not fit into pandoc's simple document
-model.  While conversions from pandoc's Markdown to all formats aspire
-to be perfect, conversions from formats more expressive than pandoc's
-Markdown can be expected to be lossy.
-
-[Markdown]: http://daringfireball.net/projects/markdown/
-[CommonMark]: http://commonmark.org
-[PHP Markdown Extra]: https://michelf.ca/projects/php-markdown/extra/
-[GitHub-Flavored Markdown]: https://help.github.com/articles/github-flavored-markdown/
-[MultiMarkdown]: http://fletcherpenney.net/multimarkdown/
-[reStructuredText]: http://docutils.sourceforge.net/docs/ref/rst/introduction.html
-[S5]: http://meyerweb.com/eric/tools/s5/
-[Slidy]: http://www.w3.org/Talks/Tools/Slidy/
-[Slideous]: http://goessner.net/articles/slideous/
-[HTML]: http://www.w3.org/html/
-[HTML5]: http://www.w3.org/TR/html5/
-[polyglot markup]: https://www.w3.org/TR/html-polyglot/
-[XHTML]: http://www.w3.org/TR/xhtml1/
-[LaTeX]: http://latex-project.org
-[`beamer`]: https://ctan.org/pkg/beamer
-[Beamer User's Guide]: http://ctan.math.utah.edu/ctan/tex-archive/macros/latex/contrib/beamer/doc/beameruserguide.pdf
-[ConTeXt]: http://www.contextgarden.net/
-[RTF]: http://en.wikipedia.org/wiki/Rich_Text_Format
-[DocBook]: http://docbook.org
-[JATS]: https://jats.nlm.nih.gov
-[txt2tags]: http://txt2tags.org
-[EPUB]: http://idpf.org/epub
-[OPML]: http://dev.opml.org/spec2.html
-[OpenDocument]: http://opendocument.xml.org
-[ODT]: http://en.wikipedia.org/wiki/OpenDocument
-[Textile]: http://redcloth.org/textile
-[MediaWiki markup]: https://www.mediawiki.org/wiki/Help:Formatting
-[DokuWiki markup]: https://www.dokuwiki.org/dokuwiki
-[ZimWiki markup]: http://zim-wiki.org/manual/Help/Wiki_Syntax.html
-[TWiki markup]: http://twiki.org/cgi-bin/view/TWiki/TextFormattingRules
-[TikiWiki markup]: https://doc.tiki.org/Wiki-Syntax-Text#The_Markup_Language_Wiki-Syntax
-[Haddock markup]: https://www.haskell.org/haddock/doc/html/ch03s08.html
-[Creole 1.0]: http://www.wikicreole.org/wiki/Creole1.0
-[groff man]: http://man7.org/linux/man-pages/man7/groff_man.7.html
-[groff ms]: http://man7.org/linux/man-pages/man7/groff_ms.7.html
-[Haskell]: https://www.haskell.org
-[GNU Texinfo]: http://www.gnu.org/software/texinfo/
-[Emacs Org mode]: http://orgmode.org
-[AsciiDoc]: http://www.methods.co.nz/asciidoc/
-[DZSlides]: http://paulrouget.com/dzslides/
-[Word docx]: https://en.wikipedia.org/wiki/Office_Open_XML
-[PDF]: https://www.adobe.com/pdf/
-[reveal.js]: http://lab.hakim.se/reveal-js/
-[FictionBook2]: http://www.fictionbook.org/index.php/Eng:XML_Schema_Fictionbook_2.1
-[InDesign ICML]: https://www.adobe.com/content/dam/Adobe/en/devnet/indesign/cs55-docs/IDML/idml-specification.pdf
-[TEI Simple]: https://github.com/TEIC/TEI-Simple
-[Muse]: https://amusewiki.org/library/manual
-[PowerPoint]: https://en.wikipedia.org/wiki/Microsoft_PowerPoint
-[Vimwiki]: https://vimwiki.github.io
-
-Using `pandoc`
---------------
-
-If no *input-file* is specified, input is read from *stdin*.
-Otherwise, the *input-files* are concatenated (with a blank
-line between each) and used as input.  Output goes to *stdout* by
-default (though output to the terminal is disabled for the
-`odt`, `docx`, `epub2`, and `epub3` output formats, unless it is
-forced using `-o -`).  For output to a file, use the `-o`
-option:
-
-    pandoc -o output.html input.txt
-
-By default, pandoc produces a document fragment, not a standalone
-document with a proper header and footer.  To produce a standalone
-document, use the `-s` or `--standalone` flag:
-
-    pandoc -s -o output.html input.txt
-
-For more information on how standalone documents are produced, see
-[Templates], below.
-
-Instead of a file, an absolute URI may be given.  In this case
-pandoc will fetch the content using HTTP:
-
-    pandoc -f html -t markdown http://www.fsf.org
-
-It is possible to supply a custom User-Agent string or other
-header when requesting a document from a URL:
-
-    pandoc -f html -t markdown --request-header User-Agent:"Mozilla/5.0" \
-      http://www.fsf.org
-
-If multiple input files are given, `pandoc` will concatenate them all (with
-blank lines between them) before parsing. This feature is disabled for
- binary input formats such as `EPUB`, `odt`, and `docx`.
-
-The format of the input and output can be specified explicitly using
-command-line options.  The input format can be specified using the
-`-r/--read` or `-f/--from` options, the output format using the
-`-w/--write` or `-t/--to` options.  Thus, to convert `hello.txt` from
-Markdown to LaTeX, you could type:
-
-    pandoc -f markdown -t latex hello.txt
-
-To convert `hello.html` from HTML to Markdown:
-
-    pandoc -f html -t markdown hello.html
-
-Supported output formats are listed below under the `-t/--to` option.
-Supported input formats are listed below under the `-f/--from` option. Note
-that the `rst`, `textile`, `latex`, and `html` readers are not complete;
-there are some constructs that they do not parse.
-
-If the input or output format is not specified explicitly, `pandoc`
-will attempt to guess it from the extensions of
-the input and output filenames.  Thus, for example,
-
-    pandoc -o hello.tex hello.txt
-
-will convert `hello.txt` from Markdown to LaTeX.  If no output file
-is specified (so that output goes to *stdout*), or if the output file's
-extension is unknown, the output format will default to HTML.
-If no input file is specified (so that input comes from *stdin*), or
-if the input files' extensions are unknown, the input format will
-be assumed to be Markdown unless explicitly specified.
-
-Pandoc uses the UTF-8 character encoding for both input and output.
-If your local character encoding is not UTF-8, you
-should pipe input and output through [`iconv`]:
-
-    iconv -t utf-8 input.txt | pandoc | iconv -f utf-8
-
-Note that in some output formats (such as HTML, LaTeX, ConTeXt,
-RTF, OPML, DocBook, and Texinfo), information about
-the character encoding is included in the document header, which
-will only be included if you use the `-s/--standalone` option.
-
-[`iconv`]: http://www.gnu.org/software/libiconv/
-
-Creating a PDF
---------------
-
-To produce a PDF, specify an output file with a `.pdf` extension.
-By default, pandoc will use LaTeX to create the PDF:
-
-    pandoc test.txt -o test.pdf
-
-Production of a PDF requires that a LaTeX engine be installed (see
-`--pdf-engine`, below), and assumes that the following LaTeX packages
-are available: [`amsfonts`], [`amsmath`], [`lm`], [`unicode-math`],
-[`ifxetex`], [`ifluatex`], [`listings`] (if the
-`--listings` option is used), [`fancyvrb`], [`longtable`],
-[`booktabs`], [`graphicx`] and [`grffile`] (if the document
-contains images), [`hyperref`], [`xcolor`] (with `colorlinks`), [`ulem`], [`geometry`] (with the
-`geometry` variable set), [`setspace`] (with `linestretch`), and
-[`babel`] (with `lang`).  The use of `xelatex` or `lualatex` as
-the LaTeX engine requires [`fontspec`].  `xelatex` uses
-[`polyglossia`] (with `lang`), [`xecjk`], and [`bidi`] (with the
-`dir` variable set). If the `mathspec` variable is set,
-`xelatex` will use [`mathspec`] instead of [`unicode-math`].
-The [`upquote`] and [`microtype`] packages are used if
-available, and [`csquotes`] will be used for [typography]
-if added to the template or included in any header file. The
-[`natbib`], [`biblatex`], [`bibtex`], and [`biber`] packages can
-optionally be used for [citation rendering]. These are included
-with all recent versions of [TeX Live].
-
-Alternatively, pandoc can use [ConTeXt], `pdfroff`, or any of the
-following HTML/CSS-to-PDF-engines, to create a PDF: [`wkhtmltopdf`],
-[`weasyprint`] or [`prince`].
-To do this, specify an output file with a `.pdf` extension, as before,
-but add the `--pdf-engine` option or `-t context`, `-t html`, or `-t ms`
-to the command line (`-t html` defaults to `--pdf-engine=wkhtmltopdf`).
-
-PDF output can be controlled using [variables for LaTeX] (if
-LaTeX is used) and [variables for ConTeXt] (if ConTeXt is used).
-When using an HTML/CSS-to-PDF-engine, `--css` affects the output.
-If `wkhtmltopdf` is used, then the variables `margin-left`,
-`margin-right`, `margin-top`, `margin-bottom`, and `papersize`
-will affect the output.
-
-[`amsfonts`]: https://ctan.org/pkg/amsfonts
-[`amsmath`]: https://ctan.org/pkg/amsmath
-[`lm`]: https://ctan.org/pkg/lm
-[`ifxetex`]: https://ctan.org/pkg/ifxetex
-[`ifluatex`]: https://ctan.org/pkg/ifluatex
-[`listings`]: https://ctan.org/pkg/listings
-[`fancyvrb`]: https://ctan.org/pkg/fancyvrb
-[`longtable`]: https://ctan.org/pkg/longtable
-[`booktabs`]: https://ctan.org/pkg/booktabs
-[`graphicx`]: https://ctan.org/pkg/graphicx
-[`grffile`]: https://ctan.org/pkg/grffile
-[`geometry`]: https://ctan.org/pkg/geometry
-[`setspace`]: https://ctan.org/pkg/setspace
-[`xecjk`]: https://ctan.org/pkg/xecjk
-[`hyperref`]: https://ctan.org/pkg/hyperref
-[`ulem`]: https://ctan.org/pkg/ulem
-[`babel`]: https://ctan.org/pkg/babel
-[`bidi`]: https://ctan.org/pkg/bidi
-[`mathspec`]: https://ctan.org/pkg/mathspec
-[`unicode-math`]: https://ctan.org/pkg/unicode-math
-[`polyglossia`]: https://ctan.org/pkg/polyglossia
-[`fontspec`]: https://ctan.org/pkg/fontspec
-[`upquote`]: https://ctan.org/pkg/upquote
-[`microtype`]: https://ctan.org/pkg/microtype
-[`csquotes`]: https://ctan.org/pkg/csquotes
-[`natbib`]: https://ctan.org/pkg/natbib
-[`biblatex`]: https://ctan.org/pkg/biblatex
-[`bibtex`]: https://ctan.org/pkg/bibtex
-[`biber`]: https://ctan.org/pkg/biber
-[TeX Live]: http://www.tug.org/texlive/
-[`wkhtmltopdf`]: https://wkhtmltopdf.org
-[`weasyprint`]: http://weasyprint.org
-[`prince`]: https://www.princexml.com/
-
-Options
-=======
-
-General options
----------------
-
-`-f` *FORMAT*, `-r` *FORMAT*, `--from=`*FORMAT*, `--read=`*FORMAT*
-
-:   Specify input format.  *FORMAT* can be `native` (native Haskell),
-    `json` (JSON version of native AST), `markdown` (pandoc's
-    extended Markdown), `markdown_strict` (original unextended
-    Markdown), `markdown_phpextra` (PHP Markdown Extra),
-    `markdown_mmd` (MultiMarkdown), `gfm` (GitHub-Flavored Markdown),
-    `commonmark` (CommonMark Markdown), `textile` (Textile), `rst`
-    (reStructuredText), `html` (HTML), `docbook` (DocBook), `t2t`
-    (txt2tags), `docx` (docx), `odt` (ODT), `epub` (EPUB), `opml` (OPML),
-    `org` (Emacs Org mode), `mediawiki` (MediaWiki markup), `twiki` (TWiki
-    markup), `tikiwiki` (TikiWiki markup), `creole` (Creole 1.0),
-    `haddock` (Haddock markup), or `latex` (LaTeX).
-    (`markdown_github` provides deprecated and less accurate support
-    for Github-Flavored Markdown; please use `gfm` instead, unless you
-    need to use extensions other than `smart`.)
-    Extensions can be individually enabled or disabled by
-    appending `+EXTENSION` or `-EXTENSION` to the format name.
-    See [Extensions] below, for a list of extensions and
-    their names.  See `--list-input-formats` and `--list-extensions`,
-    below.
-
-`-t` *FORMAT*, `-w` *FORMAT*, `--to=`*FORMAT*, `--write=`*FORMAT*
-
-:   Specify output format.  *FORMAT* can be `native` (native Haskell),
-    `json` (JSON version of native AST), `plain` (plain text),
-    `markdown` (pandoc's extended Markdown), `markdown_strict`
-    (original unextended Markdown), `markdown_phpextra` (PHP Markdown
-    Extra), `markdown_mmd` (MultiMarkdown), `gfm` (GitHub-Flavored
-    Markdown), `commonmark` (CommonMark Markdown), `rst`
-    (reStructuredText), `html4` (XHTML 1.0 Transitional), `html` or
-    `html5` (HTML5/XHTML [polyglot markup]), `latex` (LaTeX), `beamer`
-    (LaTeX beamer slide show), `context` (ConTeXt), `man` (groff man),
-    `mediawiki` (MediaWiki markup), `dokuwiki` (DokuWiki markup),
-    `zimwiki` (ZimWiki markup), `textile` (Textile), `org` (Emacs Org
-    mode), `texinfo` (GNU Texinfo), `opml` (OPML), `docbook` or
-    `docbook4` (DocBook 4), `docbook5` (DocBook 5), `jats` (JATS XML),
-    `opendocument` (OpenDocument), `odt` (OpenOffice text document),
-    `docx` (Word docx), `haddock` (Haddock markup), `rtf` (rich text
-    format), `epub2` (EPUB v2 book), `epub` or `epub3` (EPUB v3),
-    `fb2` (FictionBook2 e-book), `asciidoc` (AsciiDoc), `icml`
-    (InDesign ICML), `tei` (TEI Simple), `slidy` (Slidy HTML and
-    JavaScript slide show), `slideous` (Slideous HTML and JavaScript
-    slide show), `dzslides` (DZSlides HTML5 + JavaScript slide show),
-    `revealjs` (reveal.js HTML5 + JavaScript slide show), `s5` (S5
-    HTML and JavaScript slide show), `pptx` (PowerPoint slide show) or
-    the path of a custom lua writer (see [Custom writers],
-    below). (`markdown_github` provides deprecated and less accurate
-    support for Github-Flavored Markdown; please use `gfm` instead,
-    unless you use extensions that do not work with `gfm`.) Note that
-    `odt`, `epub`, and `epub3` output will not be directed to
-    *stdout*; an output filename must be specified using the
-    `-o/--output` option.  Extensions can be individually enabled or
-    disabled by appending `+EXTENSION` or `-EXTENSION` to the format
-    name.  See [Extensions] below, for a list of extensions and their
-    names.  See `--list-output-formats` and `--list-extensions`, below.
-
-`-o` *FILE*, `--output=`*FILE*
-
-:   Write output to *FILE* instead of *stdout*.  If *FILE* is
-    `-`, output will go to *stdout*, even if a non-textual format
-    (`docx`, `odt`, `epub2`, `epub3`) is specified.
-
-`--data-dir=`*DIRECTORY*
-
-:   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
-
-    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`,
-    `slidy`, `slideous`, or `s5` directory
-    placed in this directory will override pandoc's normal defaults.
-
-`--bash-completion`
-
-:   Generate a bash completion script.  To enable bash completion
-    with pandoc, add this to your `.bashrc`:
-
-         eval "$(pandoc --bash-completion)"
-
-`--verbose`
-
-:   Give verbose debugging output.  Currently this only has an effect
-    with PDF output.
-
-`--quiet`
-
-:   Suppress warning messages.
-
-`--fail-if-warnings`
-
-:   Exit with error status if there are any warnings.
-
-`--log=`*FILE*
-
-:   Write log messages in machine-readable JSON format to
-    *FILE*.  All messages above DEBUG level will be written,
-    regardless of verbosity settings (`--verbose`, `--quiet`).
-
-`--list-input-formats`
-
-:   List supported input formats, one per line.
-
-`--list-output-formats`
-
-:   List supported output formats, one per line.
-
-`--list-extensions`[`=`*FORMAT*]
-
-:   List supported Markdown extensions, one per line, preceded
-    by a `+` or `-` indicating whether it is enabled by default
-    in *FORMAT*. If *FORMAT* is not specified, defaults for
-    pandoc's Markdown are given.
-
-`--list-highlight-languages`
-
-:   List supported languages for syntax highlighting, one per
-    line.
-
-`--list-highlight-styles`
-
-:   List supported styles for syntax highlighting, one per line.
-    See `--highlight-style`.
-
-`-v`, `--version`
-
-:   Print version.
-
-`-h`, `--help`
-
-:   Show usage message.
-
-Reader options
---------------
-
-`--base-header-level=`*NUMBER*
-
-:   Specify the base level for headers (defaults to 1).
-
-`--strip-empty-paragraphs`
-
-:   *Deprecated.  Use the `+empty_paragraphs` extension instead.*
-    Ignore paragraphs with no content.  This option is useful
-    for converting word processing documents where users have
-    used empty paragraphs to create inter-paragraph space.
-
-`--indented-code-classes=`*CLASSES*
-
-:   Specify classes to use for indented code blocks--for example,
-    `perl,numberLines` or `haskell`. Multiple classes may be separated
-    by spaces or commas.
-
-`--default-image-extension=`*EXTENSION*
-
-:   Specify a default extension to use when image paths/URLs have no
-    extension.  This allows you to use the same source for formats that
-    require different kinds of images.  Currently this option only affects
-    the Markdown and LaTeX readers.
-
-`--file-scope`
-
-:   Parse each file individually before combining for multifile
-    documents. This will allow footnotes in different files with the
-    same identifiers to work as expected. If this option is set,
-    footnotes and links will not work across files. Reading binary
-    files (docx, odt, epub) implies `--file-scope`.
-
-`--filter=`*PROGRAM*
-
-:   Specify an executable to be used as a filter transforming the
-    pandoc AST after the input is parsed and before the output is
-    written.  The executable should read JSON from stdin and write
-    JSON to stdout.  The JSON must be formatted like  pandoc's own
-    JSON input and output.  The name of the output format will be
-    passed to the filter as the first argument.  Hence,
-
-        pandoc --filter ./caps.py -t latex
-
-    is equivalent to
-
-        pandoc -t json | ./caps.py latex | pandoc -f json -t latex
-
-    The latter form may be useful for debugging filters.
-
-    Filters may be written in any language.  `Text.Pandoc.JSON`
-    exports `toJSONFilter` to facilitate writing filters in Haskell.
-    Those who would prefer to write filters in python can use the
-    module [`pandocfilters`], installable from PyPI. There are also
-    pandoc filter libraries in [PHP], [perl], and
-    [JavaScript/node.js].
-
-    In order of preference, pandoc will look for filters in
-
-     1. a specified full or relative path (executable or
-     non-executable)
-
-     2. `$DATADIR/filters` (executable or non-executable)
-     where `$DATADIR` is the user data directory (see
-     `--data-dir`, above).
-
-     3. `$PATH` (executable only)
-
-`--lua-filter=`*SCRIPT*
-
-:   Transform the document in a similar fashion as JSON filters (see
-    `--filter`), but use pandoc's build-in lua filtering system.  The given
-    lua script is expected to return a list of lua filters which will be
-    applied in order.  Each lua filter must contain element-transforming
-    functions indexed by the name of the AST element on which the filter
-    function should be applied.
-
-    The `pandoc` lua module provides helper functions for element
-    creation.  It is always loaded into the script's lua environment.
-
-    The following is an example lua script for macro-expansion:
-
-        function expand_hello_world(inline)
-          if inline.c == '{{helloworld}}' then
-            return pandoc.Emph{ pandoc.Str "Hello, World" }
-          else
-            return inline
-          end
-        end
-
-        return {{Str = expand_hello_world}}
-
-
-`-M` *KEY*[`=`*VAL*], `--metadata=`*KEY*[`:`*VAL*]
-
-:   Set the metadata field *KEY* to the value *VAL*.  A value specified
-    on the command line overrides a value specified in the document.
-    Values will be parsed as YAML boolean or string values. If no value is
-    specified, the value will be treated as Boolean true.  Like
-    `--variable`, `--metadata` causes template variables to be set.
-    But unlike `--variable`, `--metadata` affects the metadata of the
-    underlying document (which is accessible from filters and may be
-    printed in some output formats).
-
-`-p`, `--preserve-tabs`
-
-:   Preserve tabs instead of converting them to spaces (the default).
-    Note that this will only affect tabs in literal code spans and code
-    blocks; tabs in regular text will be treated as spaces.
-
-`--tab-stop=`*NUMBER*
-
-:   Specify the number of spaces per tab (default is 4).
-
-`--track-changes=accept`|`reject`|`all`
-
-:   Specifies what to do with insertions, deletions, and comments
-    produced by the MS Word "Track Changes" feature.  `accept` (the
-    default), inserts all insertions, and ignores all
-    deletions. `reject` inserts all deletions and ignores
-    insertions. Both `accept` and `reject` ignore comments. `all` puts
-    in insertions, deletions, and comments, wrapped in spans with
-    `insertion`, `deletion`, `comment-start`, and `comment-end`
-    classes, respectively. The author and time of change is
-    included. `all` is useful for scripting: only accepting changes
-    from a certain reviewer, say, or before a certain date. This
-    option only affects the docx reader.
-
-`--extract-media=`*DIR*
-
-:   Extract images and other media contained in or linked from
-    the source document to the path *DIR*, creating it if
-    necessary, and adjust the images references in the document
-    so they point to the extracted files.  If the source format is
-    a binary container (docx, epub, or odt), the media is
-    extracted from the container and the original
-    filenames are used. Otherwise the media is read from the
-    file system or downloaded, and new filenames are constructed
-    based on SHA1 hashes of the contents.
-
-`--abbreviations=`*FILE*
-
-:   Specifies a custom abbreviations file, with abbreviations
-    one to a line.  If this option is not specified, pandoc will
-    read the data file `abbreviations` from the user data
-    directory or fall back on a system default.  To see the
-    system default, use
-    `pandoc --print-default-data-file=abbreviations`.  The only
-    use pandoc makes of this list is in the Markdown reader.
-    Strings ending in a period that are found in this list will
-    be followed by a nonbreaking space, so that the period will
-    not produce sentence-ending space in formats like LaTeX.
-
-[`pandocfilters`]: https://github.com/jgm/pandocfilters
-[PHP]: https://github.com/vinai/pandocfilters-php
-[perl]: https://metacpan.org/pod/Pandoc::Filter
-[JavaScript/node.js]: https://github.com/mvhenderson/pandoc-filter-node
-
-General writer options
-----------------------
-
-`-s`, `--standalone`
-
-:   Produce output with an appropriate header and footer (e.g. a
-    standalone HTML, LaTeX, TEI, or RTF file, not a fragment).  This option
-    is set automatically for `pdf`, `epub`, `epub3`, `fb2`, `docx`, and `odt`
-    output.
-
-`--template=`*FILE*
-
-:   Use *FILE* as a custom template for the generated document. Implies
-    `--standalone`. See [Templates], below, for a description
-    of template syntax. If no extension is specified, an extension
-    corresponding to the writer will be added, so that `--template=special`
-    looks for `special.html` for HTML output.  If the template is not
-    found, pandoc will search for it in the `templates` subdirectory of
-    the user data directory (see `--data-dir`). If this option is not used,
-    a default template appropriate for the output format will be used (see
-    `-D/--print-default-template`).
-
-`-V` *KEY*[`=`*VAL*], `--variable=`*KEY*[`:`*VAL*]
-
-:   Set the template variable *KEY* to the value *VAL* when rendering the
-    document in standalone mode. This is generally only useful when the
-    `--template` option is used to specify a custom template, since
-    pandoc automatically sets the variables used in the default
-    templates.  If no *VAL* is specified, the key will be given the
-    value `true`.
-
-`-D` *FORMAT*, `--print-default-template=`*FORMAT*
-
-:   Print the system default template for an output *FORMAT*. (See `-t`
-    for a list of possible *FORMAT*s.)  Templates in the user data
-    directory are ignored.
-
-`--print-default-data-file=`*FILE*
-
-:   Print a system default data file.  Files in the user data directory
-    are ignored.
-
-`--eol=crlf`|`lf`|`native`
-
-:   Manually specify line endings: `crlf` (Windows), `lf`
-    (macOS/Linux/UNIX), or `native` (line endings appropriate
-    to the OS on which pandoc is being run).  The default is
-    `native`.
-
-`--dpi`=*NUMBER*
-
-:   Specify the dpi (dots per inch) value for conversion from pixels
-    to inch/centimeters and vice versa. The default is 96dpi.
-    Technically, the correct term would be ppi (pixels per inch).
-
-`--wrap=auto`|`none`|`preserve`
-
-:   Determine how text is wrapped in the output (the source
-    code, not the rendered version).  With `auto` (the default),
-    pandoc will attempt to wrap lines to the column width specified by
-    `--columns` (default 72).  With `none`, pandoc will not wrap
-    lines at all.  With `preserve`, pandoc will attempt to
-    preserve the wrapping from the source document (that is,
-    where there are nonsemantic newlines in the source, there
-    will be nonsemantic newlines in the output as well).
-    Automatic wrapping does not currently work in HTML output.
-
-`--columns=`*NUMBER*
-
-:   Specify length of lines in characters.  This affects text wrapping
-    in the generated source code (see `--wrap`).  It also affects
-    calculation of column widths for plain text tables (see [Tables] below).
-
-`--toc`, `--table-of-contents`
-
-:   Include an automatically generated table of contents (or, in
-    the case of `latex`, `context`, `docx`, `odt`,
-    `opendocument`, `rst`, or `ms`, an instruction to create
-    one) in the output document. This option has no effect on
-    `man`, `docbook4`, `docbook5`, or `jats` output.
-
-`--toc-depth=`*NUMBER*
-
-:   Specify the number of section levels to include in the table
-    of contents.  The default is 3 (which means that level 1, 2, and 3
-    headers will be listed in the contents).
-
-`--strip-comments`
-
-:   Strip out HTML comments in the Markdown or Textile source,
-    rather than passing them on to Markdown, Textile or HTML
-    output as raw HTML.  This does not apply to HTML comments
-    inside raw HTML blocks when the `markdown_in_html_blocks`
-    extension is not set.
-
-`--no-highlight`
-
-:   Disables syntax highlighting for code blocks and inlines, even when
-    a language attribute is given.
-
-`--highlight-style=`*STYLE*|*FILE*
-
-:   Specifies the coloring style to be used in highlighted source code.
-    Options are `pygments` (the default), `kate`, `monochrome`,
-    `breezeDark`, `espresso`, `zenburn`, `haddock`, and `tango`.
-    For more information on syntax highlighting in pandoc, see
-    [Syntax highlighting], below.  See also
-    `--list-highlight-styles`.
-
-    Instead of a *STYLE* name, a JSON file with extension
-    `.theme` may be supplied.  This will be parsed as a KDE
-    syntax highlighting theme and (if valid) used as the
-    highlighting style.
-
-    To generate the JSON version of an existing style,
-    use `--print-highlight-style`.
-
-`--print-highlight-style=`*STYLE*|*FILE*
-
-:   Prints a JSON version of a highlighting style, which can
-    be modified, saved with a `.theme` extension, and used
-    with `--highlight-style`.
-
-`--syntax-definition=`*FILE*
-
-:   Instructs pandoc to load a KDE XML syntax definition file,
-    which will be used for syntax highlighting of appropriately
-    marked code blocks.  This can be used to add support for
-    new languages or to use altered syntax definitions for
-    existing languages.
-
-`-H` *FILE*, `--include-in-header=`*FILE*
-
-:   Include contents of *FILE*, verbatim, at the end of the header.
-    This can be used, for example, to include special
-    CSS or JavaScript in HTML documents.  This option can be used
-    repeatedly to include multiple files in the header.  They will be
-    included in the order specified.  Implies `--standalone`.
-
-`-B` *FILE*, `--include-before-body=`*FILE*
-
-:   Include contents of *FILE*, verbatim, at the beginning of the
-    document body (e.g. after the `<body>` tag in HTML, or the
-    `\begin{document}` command in LaTeX). This can be used to include
-    navigation bars or banners in HTML documents. This option can be
-    used repeatedly to include multiple files. They will be included in
-    the order specified.  Implies `--standalone`.
-
-`-A` *FILE*, `--include-after-body=`*FILE*
-
-:   Include contents of *FILE*, verbatim, at the end of the document
-    body (before the `</body>` tag in HTML, or the
-    `\end{document}` command in LaTeX). This option can be used
-    repeatedly to include multiple files. They will be included in the
-    order specified.  Implies `--standalone`.
-
-`--resource-path=`*SEARCHPATH*
-
-:   List of paths to search for images and other resources.
-    The paths should be separated by `:` on Linux, UNIX, and
-    macOS systems, and by `;` on Windows.  If `--resource-path`
-    is not specified, the default resource path is the working
-    directory. Note that, if `--resource-path` is specified,
-    the working directory must be explicitly listed or it
-    will not be searched.  For example:
-    `--resource-path=.:test` will search the working directory
-    and the `test` subdirectory, in that order.
-
-`--request-header=`*NAME*`:`*VAL*
-
-:   Set the request header *NAME* to the value *VAL* when making
-    HTTP requests (for example, when a URL is given on the
-    command line, or when resources used in a document must be
-    downloaded).
-
-Options affecting specific writers
-----------------------------------
-
-`--self-contained`
-
-:   Produce a standalone HTML file with no external dependencies, using
-    `data:` URIs to incorporate the contents of linked scripts, stylesheets,
-    images, and videos. The resulting file should be "self-contained,"
-    in the sense that it needs no external files and no net access to be
-    displayed properly by a browser. This option works only with HTML output
-    formats, including `html4`, `html5`, `html+lhs`, `html5+lhs`, `s5`,
-    `slidy`, `slideous`, `dzslides`, and `revealjs`. Scripts, images, and
-    stylesheets at absolute URLs will be downloaded; those at relative URLs
-    will be sought relative to the working directory (if the first source
-    file is local) or relative to the base URL (if the first source
-    file is remote).  Elements with the attribute
-    `data-external="1"` will be left alone; the documents they
-    link to will not be incorporated in the document.
-    Limitation: resources that are loaded dynamically through
-    JavaScript cannot be incorporated; as a result,
-    `--self-contained` does not work with `--mathjax`, and some
-    advanced features (e.g.  zoom or speaker notes) may not work
-    in an offline "self-contained" `reveal.js` slide show.
-
-`--html-q-tags`
-
-:   Use `<q>` tags for quotes in HTML.
-
-`--ascii`
-
-:   Use only ASCII characters in output.  Currently supported only for
-    HTML and DocBook output (which uses numerical entities instead of
-    UTF-8 when this option is selected).
-
-`--reference-links`
-
-:   Use reference-style links, rather than inline links, in writing Markdown
-    or reStructuredText.  By default inline links are used.  The
-    placement of link references is affected by the
-    `--reference-location` option.
-
-`--reference-location = block`|`section`|`document`
-
-:   Specify whether footnotes (and references, if `reference-links` is
-    set) are placed at the end of the current (top-level) block, the
-    current section, or the document. The default is
-    `document`. Currently only affects the markdown writer.
-
-`--atx-headers`
-
-:   Use ATX-style headers in Markdown and AsciiDoc output. The default is
-    to use setext-style headers for levels 1-2, and then ATX headers.
-    (Note: for `gfm` output, ATX headers are always used.)
-
-`--top-level-division=[default|section|chapter|part]`
-
-:   Treat top-level headers as the given division type in LaTeX, ConTeXt,
-    DocBook, and  TEI output. The hierarchy order is part, chapter, then section;
-    all headers are shifted such that the top-level header becomes the specified
-    type. The default behavior is to determine the best division type via
-    heuristics: unless other conditions apply, `section` is chosen. When the
-    LaTeX document class is set to `report`, `book`, or `memoir` (unless the
-    `article` option is specified), `chapter` is implied as the setting for this
-    option. If `beamer` is the output format, specifying either `chapter` or
-    `part` will cause top-level headers to become `\part{..}`, while
-    second-level headers remain as their default type.
-
-`-N`, `--number-sections`
-
-:   Number section headings in LaTeX, ConTeXt, HTML, or EPUB output.
-    By default, sections are not numbered.  Sections with class
-    `unnumbered` will never be numbered, even if `--number-sections`
-    is specified.
-
-`--number-offset=`*NUMBER*[`,`*NUMBER*`,`*...*]
-
-:   Offset for section headings in HTML output (ignored in other
-    output formats).  The first number is added to the section number for
-    top-level headers, the second for second-level headers, and so on.
-    So, for example, if you want the first top-level header in your
-    document to be numbered "6", specify `--number-offset=5`.
-    If your document starts with a level-2 header which you want to
-    be numbered "1.5", specify `--number-offset=1,4`.
-    Offsets are 0 by default.  Implies `--number-sections`.
-
-`--listings`
-
-:   Use the [`listings`] package for LaTeX code blocks
-
-`-i`, `--incremental`
-
-:   Make list items in slide shows display incrementally (one by one).
-    The default is for lists to be displayed all at once.
-
-`--slide-level=`*NUMBER*
-
-:   Specifies that headers with the specified level create
-    slides (for `beamer`, `s5`, `slidy`, `slideous`, `dzslides`).  Headers
-    above this level in the hierarchy are used to divide the
-    slide show into sections; headers below this level create
-    subheads within a slide.  Note that content that is
-    not contained under slide-level headers will not appear in
-    the slide show.  The default is to set the slide level based
-    on the contents of the document; see [Structuring the slide
-    show].
-
-`--section-divs`
-
-:   Wrap sections in `<section>` tags (or `<div>` tags for `html4`),
-    and attach identifiers to the enclosing `<section>` (or `<div>`)
-    rather than the header itself. See
-    [Header identifiers], below.
-
-`--email-obfuscation=none`|`javascript`|`references`
-
-:   Specify a method for obfuscating `mailto:` links in HTML documents.
-    `none` leaves `mailto:` links as they are.  `javascript` obfuscates
-    them using JavaScript. `references` obfuscates them by printing their
-    letters as decimal or hexadecimal character references.  The default
-    is `none`.
-
-`--id-prefix=`*STRING*
-
-:   Specify a prefix to be added to all identifiers and internal links
-    in HTML and DocBook output, and to footnote numbers in Markdown
-    and Haddock output. This is useful for preventing duplicate
-    identifiers when generating fragments to be included in other pages.
-
-`-T` *STRING*, `--title-prefix=`*STRING*
-
-:   Specify *STRING* as a prefix at the beginning of the title
-    that appears in the HTML header (but not in the title as it
-    appears at the beginning of the HTML body).  Implies
-    `--standalone`.
-
-`-c` *URL*, `--css=`*URL*
-
-:   Link to a CSS style sheet. This option can be used repeatedly to
-    include multiple files. They will be included in the order specified.
-
-    A stylesheet is required for generating EPUB.  If none is
-    provided using this option (or the `stylesheet` metadata
-    field), pandoc will look for a file `epub.css` in the
-    user data directory (see `--data-dir`).  If it is not
-    found there, sensible defaults will be used.
-
-`--reference-doc=`*FILE*
-
-:   Use the specified file as a style reference in producing a
-    docx or ODT file.
-
-    Docx
-
-    :   For best results, the reference docx should be a modified
-        version of a docx file produced using pandoc.  The contents
-        of the reference docx are ignored, but its stylesheets and
-        document properties (including margins, page size, header,
-        and footer) are used in the new docx. If no reference docx
-        is specified on the command line, pandoc will look for a
-        file `reference.docx` in the user data directory (see
-        `--data-dir`). If this is not found either, sensible
-        defaults will be used.
-
-        To produce a custom `reference.docx`, first get a copy of
-        the default `reference.docx`: `pandoc
-        --print-default-data-file reference.docx >
-        custom-reference.docx`.  Then open `custom-reference.docx`
-        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]
-        Normal, Body Text, First Paragraph, Compact, Title,
-        Subtitle, Author, Date, Abstract, Bibliography, Heading 1,
-        Heading 2, Heading 3, Heading 4, Heading 5, Heading 6,
-        Heading 7, Heading 8, Heading 9, Block Text, Footnote Text,
-        Definition Term, Definition, Caption, Table Caption,
-        Image Caption, Figure, Captioned Figure, TOC Heading;
-        [character] Default Paragraph Font, Body Text Char,
-        Verbatim Char, Footnote Reference, Hyperlink; [table]
-        Table.
-
-    ODT
-
-    :   For best results, the reference ODT should be a modified
-        version of an ODT produced using pandoc.  The contents of
-        the reference ODT are ignored, but its stylesheets are used
-        in the new ODT. If no reference ODT is specified on the
-        command line, pandoc will look for a file `reference.odt` in
-        the user data directory (see `--data-dir`). If this is not
-        found either, sensible defaults will be used.
-
-        To produce a custom `reference.odt`, first get a copy of
-        the default `reference.odt`: `pandoc
-        --print-default-data-file reference.odt >
-        custom-reference.odt`.  Then open `custom-reference.odt` in
-        LibreOffice, modify the styles as you wish, and save the
-        file.
-
-`--epub-cover-image=`*FILE*
-
-:   Use the specified image as the EPUB cover.  It is recommended
-    that the image be less than 1000px in width and height. Note that
-    in a Markdown source document you can also specify `cover-image`
-    in a YAML metadata block (see [EPUB Metadata], below).
-
-`--epub-metadata=`*FILE*
-
-:   Look in the specified XML file for metadata for the EPUB.
-    The file should contain a series of [Dublin Core elements].
-    For example:
-
-         <dc:rights>Creative Commons</dc:rights>
-         <dc:language>es-AR</dc:language>
-
-    By default, pandoc will include the following metadata elements:
-    `<dc:title>` (from the document title), `<dc:creator>` (from the
-    document authors), `<dc:date>` (from the document date, which should
-    be in [ISO 8601 format]), `<dc:language>` (from the `lang`
-    variable, or, if is not set, the locale), and `<dc:identifier
-    id="BookId">` (a randomly generated UUID). Any of these may be
-    overridden by elements in the metadata file.
-
-    Note: if the source document is Markdown, a YAML metadata block
-    in the document can be used instead.  See below under
-    [EPUB Metadata].
-
-`--epub-embed-font=`*FILE*
-
-:   Embed the specified font in the EPUB. This option can be repeated
-    to embed multiple fonts.  Wildcards can also be used: for example,
-    `DejaVuSans-*.ttf`.  However, if you use wildcards on the command
-    line, be sure to escape them or put the whole filename in single quotes,
-    to prevent them from being interpreted by the shell. To use the
-    embedded fonts, you will need to add declarations like the following
-    to your CSS (see `--css`):
-
-        @font-face {
-        font-family: DejaVuSans;
-        font-style: normal;
-        font-weight: normal;
-        src:url("DejaVuSans-Regular.ttf");
-        }
-        @font-face {
-        font-family: DejaVuSans;
-        font-style: normal;
-        font-weight: bold;
-        src:url("DejaVuSans-Bold.ttf");
-        }
-        @font-face {
-        font-family: DejaVuSans;
-        font-style: italic;
-        font-weight: normal;
-        src:url("DejaVuSans-Oblique.ttf");
-        }
-        @font-face {
-        font-family: DejaVuSans;
-        font-style: italic;
-        font-weight: bold;
-        src:url("DejaVuSans-BoldOblique.ttf");
-        }
-        body { font-family: "DejaVuSans"; }
-
-`--epub-chapter-level=`*NUMBER*
-
-:   Specify the header level at which to split the EPUB into separate
-    "chapter" files. The default is to split into chapters at level 1
-    headers. This option only affects the internal composition of the
-    EPUB, not the way chapters and sections are displayed to users. Some
-    readers may be slow if the chapter files are too large, so for large
-    documents with few level 1 headers, one might want to use a chapter
-    level of 2 or 3.
-
-`--epub-subdirectory=`*DIRNAME*
-
-:   Specify the subdirectory in the OCF container that is to hold
-    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`
-
-:   Use the specified engine when producing PDF output.
-    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.
-
-[Dublin Core elements]: http://dublincore.org/documents/dces/
-[ISO 8601 format]: http://www.w3.org/TR/NOTE-datetime
-
-Citation rendering
-------------------
-
-`--bibliography=`*FILE*
-
-:   Set the `bibliography` field in the document's metadata to *FILE*,
-    overriding any value set in the metadata, and process citations
-    using `pandoc-citeproc`. (This is equivalent to
-    `--metadata bibliography=FILE --filter pandoc-citeproc`.)
-    If `--natbib` or `--biblatex` is also supplied, `pandoc-citeproc` is not
-    used, making this equivalent to `--metadata bibliography=FILE`.
-    If you supply this argument multiple times, each *FILE* will be added
-    to bibliography.
-
-`--csl=`*FILE*
-
-:   Set the `csl` field in the document's metadata to *FILE*,
-    overriding any value set in the metadata.  (This is equivalent to
-    `--metadata csl=FILE`.)
-    This option is only relevant with `pandoc-citeproc`.
-
-`--citation-abbreviations=`*FILE*
-
-:   Set the `citation-abbreviations` field in the document's metadata to
-    *FILE*, overriding any value set in the metadata.  (This is equivalent to
-    `--metadata citation-abbreviations=FILE`.)
-    This option is only relevant with `pandoc-citeproc`.
-
-`--natbib`
-
-:   Use [`natbib`] for citations in LaTeX output.  This option is not for use
-    with the `pandoc-citeproc` filter or with PDF output.  It is intended for
-    use in producing a LaTeX file that can be processed with [`bibtex`].
-
-`--biblatex`
-
-:   Use [`biblatex`] for citations in LaTeX output.  This option is not for use
-    with the `pandoc-citeproc` filter or with PDF output. It is intended for
-    use in producing a LaTeX file that can be processed with [`bibtex`] or [`biber`].
-
-Math rendering in HTML
-----------------------
-
-The default is to render TeX math as far as possible using Unicode characters.
-Formulas are put inside a `span` with `class="math"`, so that they may be styled
-differently from the surrounding text if needed. However, this gives acceptable
-results only for basic math, usually you will want to use `--mathjax` or another
-of the following options.
-
-`--mathjax`[`=`*URL*]
-
-:   Use [MathJax] to display embedded TeX math in HTML output.
-    TeX math will be put between `\(...\)` (for inline math)
-    or `\[...\]` (for display math) and wrapped in `<span>` tags
-    with class `math`. Then the MathJax JavaScript will render it.
-    The *URL* should point to the `MathJax.js` load script.
-    If a *URL* is not provided, a link to the Cloudflare CDN will
-    be inserted.
-
-`--mathml`
-
-:   Convert TeX math to [MathML] (in `epub3`, `docbook4`, `docbook5`, `jats`,
-    `html4` and `html5`).  This is the default in `odt` output. Note that
-    currently only Firefox and Safari (and select e-book readers) natively
-    support MathML.
-
-`--webtex`[`=`*URL*]
-
-:   Convert TeX formulas to `<img>` tags that link to an external script
-    that converts formulas to images. The formula will be URL-encoded
-    and concatenated with the URL provided. For SVG images you can for
-    example use `--webtex https://latex.codecogs.com/svg.latex?`.
-    If no URL is specified, the CodeCogs URL generating PNGs
-    will be used (`https://latex.codecogs.com/png.latex?`).
-    Note:  the `--webtex` option will affect Markdown output
-    as well as HTML, which is useful if you're targeting a
-    version of Markdown without native math support.
-
-`--katex`[`=`*URL*]
-
-:   Use [KaTeX] to display embedded TeX math in HTML output.
-    The *URL* is the base URL for the KaTeX library. If a *URL* is
-    not provided, a link to the KaTeX CDN will be inserted.
-
-`--katex-stylesheet=`*URL*
-
-:   The *URL* should point to the `katex.css` stylesheet. If this option is
-    not specified, a link to the KaTeX CDN will be inserted. Note that this
-    option does not imply `--katex`.
-
-`-m` [*URL*], `--latexmathml`[`=`*URL*]
-
-:   *Deprecated.*
-    Use the [LaTeXMathML] script to display embedded TeX math in HTML output.
-    TeX math will be displayed between `$` or `$$` characters and put in
-    `<span>` tags with class `LaTeX`. The LaTeXMathML JavaScript will then
-    change it to MathML. Note that currently only Firefox and Safari
-    (and select e-book readers) natively support MathML.
-    To insert a link the `LaTeXMathML.js` script, provide a *URL*.
-
-`--jsmath`[`=`*URL*]
-
-:   *Deprecated.*
-    Use [jsMath] (the predecessor of MathJax) to display embedded TeX
-    math in HTML output. TeX math will be put inside `<span>` tags
-    (for inline math) or `<div>` tags (for display math) with class
-    `math` and rendered by the jsMath script. The *URL* should point to
-    the script (e.g. `jsMath/easy/load.js`); if provided, it will be linked
-    to in the header of standalone HTML documents. If a *URL* is not provided,
-    no link to the jsMath load script will be inserted; it is then
-    up to the author to provide such a link in the HTML template.
-
-`--gladtex`
-
-:   *Deprecated.*
-    Enclose TeX math in `<eq>` tags in HTML output.  The resulting HTML
-    can then be processed by [gladTeX] to produce images of the typeset
-    formulas and an HTML file with links to these images.
-    So, the procedure is:
-
-        pandoc -s --gladtex input.md -o myfile.htex
-        gladtex -d myfile-images myfile.htex
-        # produces myfile.html and images in myfile-images
-
-`--mimetex`[`=`*URL*]
-
-:   *Deprecated.*
-    Render TeX math using the [mimeTeX] CGI script, which generates an
-    image for each TeX formula. This should work in all browsers. If
-    *URL* is not specified, it is assumed that the script is at
-    `/cgi-bin/mimetex.cgi`.
-
-[MathML]: http://www.w3.org/Math/
-[LaTeXMathML]: http://math.etsu.edu/LaTeXMathML/
-[jsMath]: http://www.math.union.edu/~dpvc/jsmath/
-[MathJax]: https://www.mathjax.org
-[gladTeX]: http://ans.hsh.no/home/mgg/gladtex/
-[mimeTeX]: http://www.forkosh.com/mimetex.html
-[KaTeX]: https://github.com/Khan/KaTeX
-
-Options for wrapper scripts
----------------------------
-
-`--dump-args`
-
-:   Print information about command-line arguments to *stdout*, then exit.
-    This option is intended primarily for use in wrapper scripts.
-    The first line of output contains the name of the output file specified
-    with the `-o` option, or `-` (for *stdout*) if no output file was
-    specified.  The remaining lines contain the command-line arguments,
-    one per line, in the order they appear.  These do not include regular
-    pandoc options and their arguments, but do include any options appearing
-    after a `--` separator at the end of the line.
-
-`--ignore-args`
-
-:   Ignore command-line arguments (for use in wrapper scripts).
-    Regular pandoc options are not ignored.  Thus, for example,
-
-        pandoc --ignore-args -o foo.html -s foo.txt -- -e latin1
-
-    is equivalent to
-
-        pandoc -o foo.html -s
-
-Templates
-=========
-
-When the `-s/--standalone` option is used, pandoc uses a template to
-add header and footer material that is needed for a self-standing
-document.  To see the default template that is used, just type
-
-    pandoc -D *FORMAT*
-
-where *FORMAT* is the name of the output format. A custom template
-can be specified using the `--template` option.  You can also override
-the system default templates for a given output format *FORMAT*
-by putting a file `templates/default.*FORMAT*` in the user data
-directory (see `--data-dir`, above). *Exceptions:*
-
-- For `odt` output, customize the `default.opendocument`
-  template.
-- For `pdf` output, customize the `default.latex` template
-  (or the `default.context` template, if you use `-t context`,
-  or the `default.ms` template, if you use `-t ms`, or the
-  `default.html5` template, if you use `-t html5`).
-- `docx` has no template (however, you can use
-  `--reference-doc` to customize the output).
-
-Templates contain *variables*, which allow for the inclusion of
-arbitrary information at any point in the file. Variables may be set
-within the document using [YAML metadata blocks][Extension:
-`yaml_metadata_block`].  They may also be set at the
-command line using the `-V/--variable` option: variables set in this
-way override metadata fields with the same name.
-
-Variables set by pandoc
------------------------
-
-Some variables are set automatically by pandoc.  These vary somewhat
-depending on the output format, but include metadata fields as well
-as the following:
-
-`sourcefile`, `outputfile`
-:   source and destination filenames, as given on the command line.
-    `sourcefile` can also be a list if input comes from multiple files, or empty
-    if input is from stdin. You can use the following snippet in your template
-    to distinguish them:
-
-        $if(sourcefile)$
-        $for(sourcefile)$
-        $sourcefile$
-        $endfor$
-        $else$
-        (stdin)
-        $endif$
-
-    Similarly, `outputfile` can be `-` if output goes to the terminal.
-
-`title`, `author`, `date`
-:   allow identification of basic aspects of the document.  Included
-    in PDF metadata through LaTeX and ConTeXt.  These can be set
-    through a [pandoc title block][Extension: `pandoc_title_block`],
-    which allows for multiple authors, or through a YAML metadata block:
-
-        ---
-        author:
-        - Aristotle
-        - Peter Abelard
-        ...
-
-`subtitle`
-:   document subtitle, included in HTML, EPUB, LaTeX, ConTeXt, and Word docx;
-    renders in LaTeX only when using a document class that supports
-    `\subtitle`, such as `beamer` or the [KOMA-Script] series (`scrartcl`,
-    `scrreprt`, `scrbook`).[^subtitle]
-
-`institute`
-:   author affiliations (in LaTeX and Beamer only).  Can be a
-    list, when there are multiple authors.
-
-`abstract`
-:   document summary, included in LaTeX, ConTeXt, AsciiDoc, and Word docx
-
-`keywords`
-:   list of keywords to be included in HTML, PDF, and AsciiDoc metadata;
-    may be repeated as for `author`, above
-
-`header-includes`
-:   contents specified by `-H/--include-in-header` (may have multiple
-    values)
-
-`toc`
-:   non-null value if `--toc/--table-of-contents` was specified
-
-`toc-title`
-:   title of table of contents (works only with EPUB,
-    opendocument, odt, docx)
-
-`include-before`
-:   contents specified by `-B/--include-before-body` (may have
-    multiple values)
-
-`include-after`
-:   contents specified by `-A/--include-after-body` (may have
-    multiple values)
-
-`body`
-:   body of document
-
-`meta-json`
-:   JSON representation of all of the document's metadata. Field
-    values are transformed to the selected output format.
-
-[^subtitle]: To make `subtitle` work with other LaTeX
-    document classes, you can add the following to `header-includes`:
-
-        \providecommand{\subtitle}[1]{%
-          \usepackage{titling}
-          \posttitle{%
-            \par\large#1\end{center}}
-        }
-
-Language variables
-------------------
-
-`lang`
-:   identifies the main language of the document,
-    using a code according to [BCP 47] (e.g. `en` or `en-GB`).
-    For some output formats, pandoc will convert it to an appropriate
-    format stored in the additional variables `babel-lang`,
-    `polyglossia-lang` (LaTeX) and `context-lang` (ConTeXt).
-
-    Native pandoc `span`s and `div`s with the lang attribute
-    (value in BCP 47) can be used to switch the language in
-    that range.
-
-`otherlangs`
-:   a list of other languages used in the document
-    in the YAML metadata, according to [BCP 47]. For example:
-    `otherlangs: [en-GB, fr]`.
-    This is automatically generated from the `lang` attributes
-    in all `span`s and `div`s but can be overridden.
-    Currently only used by LaTeX through the generated
-    `babel-otherlangs` and `polyglossia-otherlangs` variables.
-    The LaTeX writer outputs polyglossia commands in the text but
-    the `babel-newcommands` variable contains mappings for them
-    to the corresponding babel.
-
-`dir`
-:   the base direction of the document, either `rtl` (right-to-left)
-    or `ltr` (left-to-right).
-
-    For bidirectional documents, native pandoc `span`s and `div`s
-    with the `dir` attribute (value `rtl` or `ltr`) can be used to
-    override the base direction in some output formats.
-    This may not always be necessary if the final renderer
-    (e.g. the browser, when generating HTML) supports the
-    [Unicode Bidirectional Algorithm].
-
-    When using LaTeX for bidirectional documents, only the `xelatex` engine
-    is fully supported (use `--pdf-engine=xelatex`).
-
-[BCP 47]: https://tools.ietf.org/html/bcp47
-[Unicode Bidirectional Algorithm]: http://www.w3.org/International/articles/inline-bidi-markup/uba-basics
-
-Variables for slides
---------------------
-
-Variables are available for [producing slide shows with pandoc],
-including all [reveal.js configuration options].
-
-`titlegraphic`
-:   title graphic for Beamer documents
-
-`logo`
-:   logo for Beamer documents
-
-`slidy-url`
-:   base URL for Slidy documents (defaults to
-    `https://www.w3.org/Talks/Tools/Slidy2`)
-
-`slideous-url`
-:   base URL for Slideous documents (defaults to `slideous`)
-
-`s5-url`
-:   base URL for S5 documents (defaults to `s5/default`)
-
-`revealjs-url`
-:   base URL for reveal.js documents (defaults to `reveal.js`)
-
-`theme`, `colortheme`, `fonttheme`, `innertheme`, `outertheme`
-:   themes for LaTeX [`beamer`] documents
-
-`themeoptions`
-:   options for LaTeX beamer themes (a list).
-
-`navigation`
-:   controls navigation symbols in `beamer` documents
-    (default is `empty` for no navigation symbols; other valid values
-    are `frame`, `vertical`, and `horizontal`).
-
-`section-titles`
-:   enables on "title pages" for new sections in `beamer`
-    documents (default = true).
-
-`beamerarticle`
-:   when true, the `beamerarticle` package is loaded (for
-    producing an article from beamer slides).
-
-`aspectratio`
-:   aspect ratio of slides (for beamer only, `1610` for 16:10, `169` for 16:9,
-    `149` for 14:9, `141` for 1.41:1, `54` for 5:4, `43` for 4:3 which is the
-    default, and `32` for 3:2).
-
-[reveal.js configuration options]: https://github.com/hakimel/reveal.js#configuration
-
-Variables for LaTeX
--------------------
-
-LaTeX variables are used when [creating a PDF].
-
-`papersize`
-:   paper size, e.g. `letter`, `a4`
-
-`fontsize`
-:   font size for body text (e.g. `10pt`, `12pt`)
-
-`documentclass`
-:   document class, e.g. [`article`], [`report`], [`book`], [`memoir`]
-
-`classoption`
-:   option for document class, e.g. `oneside`; may be repeated
-    for multiple options
-
-`geometry`
-:   option for [`geometry`] package, e.g. `margin=1in`;
-    may be repeated for multiple options
-
-`margin-left`, `margin-right`, `margin-top`, `margin-bottom`
-:   sets margins, if `geometry` is not used (otherwise `geometry`
-    overrides these)
-
-`linestretch`
-:   adjusts line spacing using the [`setspace`]
-    package, e.g. `1.25`, `1.5`
-
-`fontfamily`
-:   font package for use with `pdflatex`:
-    [TeX Live] includes many options, documented in the [LaTeX Font Catalogue].
-    The default is [Latin Modern][`lm`].
-
-`fontfamilyoptions`
-:   options for package used as `fontfamily`: e.g. `osf,sc` with
-    `fontfamily` set to [`mathpazo`] provides Palatino with old-style
-    figures and true small caps; may be repeated for multiple options
-
-`mainfont`, `sansfont`, `monofont`, `mathfont`, `CJKmainfont`
-:   font families for use with `xelatex` or
-    `lualatex`: take the name of any system font, using the
-    [`fontspec`] package.  Note that if `CJKmainfont` is used,
-    the [`xecjk`] package must be available.
-
-`mainfontoptions`, `sansfontoptions`, `monofontoptions`, `mathfontoptions`, `CJKoptions`
-:   options to use with `mainfont`, `sansfont`, `monofont`, `mathfont`,
-    `CJKmainfont` in `xelatex` and `lualatex`.  Allow for any choices
-    available through [`fontspec`], such as the OpenType features
-    `Numbers=OldStyle,Numbers=Proportional`. May be repeated for multiple options.
-
-`fontenc`
-:   allows font encoding to be specified through `fontenc` package (with `pdflatex`);
-    default is `T1` (see guide to [LaTeX font encodings])
-
-`microtypeoptions`
-:    options to pass to the microtype package
-
-`colorlinks`
-:   add color to link text; automatically enabled if any of `linkcolor`, `citecolor`,
-    `urlcolor`, or `toccolor` are set
-
-`linkcolor`, `citecolor`, `urlcolor`, `toccolor`
-:   color for internal links, citation links, external links, and links in table of contents:
-    uses options allowed by [`xcolor`], including the `dvipsnames`, `svgnames`, and `x11names` lists
-
-`links-as-notes`
-:   causes links to be printed as footnotes
-
-`indent`
-:   uses document class settings for indentation (the default LaTeX template
-    otherwise removes indentation and adds space between paragraphs)
-
-`subparagraph`
-:   disables default behavior of LaTeX template that redefines (sub)paragraphs
-    as sections, changing the appearance of nested headings in some classes
-
-`thanks`
-:   specifies contents of acknowledgments footnote after document title.
-
-`toc`
-:   include table of contents (can also be set using `--toc/--table-of-contents`)
-
-`toc-depth`
-:   level of section to include in table of contents
-
-`secnumdepth`
-:   numbering depth for sections, if sections are numbered
-
-`lof`, `lot`
-:   include list of figures, list of tables
-
-`bibliography`
-:   bibliography to use for resolving references
-
-`biblio-style`
-:   bibliography style, when used with `--natbib` and `--biblatex`.
-
-`biblio-title`
-:   bibliography title, when used with `--natbib` and `--biblatex`.
-
-`biblatexoptions`
-:   list of options for biblatex.
-
-`natbiboptions`
-:   list of options for natbib.
-
-`pagestyle`
-:   An option for LaTeX's `\pagestyle{}`. The default article class
-    supports 'plain' (default), 'empty', and 'headings'; headings puts
-    section titles in the header.
-
-[`article`]: https://ctan.org/pkg/article
-[`report`]: https://ctan.org/pkg/report
-[`book`]: https://ctan.org/pkg/book
-[KOMA-Script]: https://ctan.org/pkg/koma-script
-[`memoir`]: https://ctan.org/pkg/memoir
-[`xcolor`]: https://ctan.org/pkg/xcolor
-[LaTeX Font Catalogue]: http://www.tug.dk/FontCatalogue/
-[`mathpazo`]: https://ctan.org/pkg/mathpazo
-[LaTeX font encodings]: https://ctan.org/pkg/encguide
-
-Variables for ConTeXt
----------------------
-
-`papersize`
-:   paper size, e.g. `letter`, `A4`, `landscape` (see [ConTeXt Paper Setup]);
-    may be repeated for multiple options
-
-`layout`
-:   options for page margins and text arrangement (see [ConTeXt Layout]);
-    may be repeated for multiple options
-
-`margin-left`, `margin-right`, `margin-top`, `margin-bottom`
-:   sets margins, if `layout` is not used (otherwise `layout`
-    overrides these)
-
-`fontsize`
-:   font size for body text (e.g. `10pt`, `12pt`)
-
-`mainfont`, `sansfont`, `monofont`, `mathfont`
-:   font families: take the name of any system font (see [ConTeXt Font Switching])
-
-`linkcolor`, `contrastcolor`
-:   color for links outside and inside a page, e.g. `red`, `blue` (see [ConTeXt Color])
-
-`linkstyle`
-:   typeface style for links, e.g. `normal`, `bold`, `slanted`, `boldslanted`, `type`, `cap`, `small`
-
-`indenting`
-:   controls indentation of paragraphs, e.g. `yes,small,next` (see [ConTeXt Indentation]);
-    may be repeated for multiple options
-
-`whitespace`
-:   spacing between paragraphs, e.g. `none`, `small` (using [`setupwhitespace`])
-
-`interlinespace`
-:   adjusts line spacing, e.g. `4ex` (using [`setupinterlinespace`]);
-    may be repeated for multiple options
-
-`headertext`, `footertext`
-:   text to be placed in running header or footer (see [ConTeXt Headers and Footers]);
-    may be repeated up to four times for different placement
-
-`pagenumbering`
-:   page number style and location (using [`setuppagenumbering`]);
-    may be repeated for multiple options
-
-`toc`
-:   include table of contents (can also be set using `--toc/--table-of-contents`)
-
-`lof`, `lot`
-:   include list of figures, list of tables
-
-[ConTeXt Paper Setup]: http://wiki.contextgarden.net/PaperSetup
-[ConTeXt Layout]: http://wiki.contextgarden.net/Layout
-[ConTeXt Font Switching]: http://wiki.contextgarden.net/Font_Switching
-[ConTeXt Color]: http://wiki.contextgarden.net/Color
-[ConTeXt Headers and Footers]: http://wiki.contextgarden.net/Headers_and_Footers
-[ConTeXt Indentation]: http://wiki.contextgarden.net/Indentation
-[`setupwhitespace`]: http://wiki.contextgarden.net/Command/setupwhitespace
-[`setupinterlinespace`]: http://wiki.contextgarden.net/Command/setupinterlinespace
-[`setuppagenumbering`]: http://wiki.contextgarden.net/Command/setuppagenumbering
-
-Variables for man pages
------------------------
-
-`section`
-:   section number in man pages
-
-`header`
-:   header in man pages
-
-`footer`
-:   footer in man pages
-
-`adjusting`
-:   adjusts text to left (`l`), right (`r`), center (`c`),
-    or both (`b`) margins
-
-`hyphenate`
-:   if `true` (the default), hyphenation will be used
-
-Variables for ms
-----------------
-
-`pointsize`
-:    point size (e.g. `10p`)
-
-`lineheight`
-:    line height (e.g. `12p`)
-
-`fontfamily`
-:    font family (e.g. `T` or `P`)
-
-`indent`
-:    paragraph indent (e.g. `2m`)
-
-Using variables in templates
-----------------------------
-
-Variable names are sequences of alphanumerics, `-`, and `_`,
-starting with a letter.  A variable name surrounded by `$` signs
-will be replaced by its value.  For example, the string `$title$` in
-
-    <title>$title$</title>
-
-will be replaced by the document title.
-
-To write a literal `$` in a template, use `$$`.
-
-Templates may contain conditionals.  The syntax is as follows:
-
-    $if(variable)$
-    X
-    $else$
-    Y
-    $endif$
-
-This will include `X` in the template if `variable` has a non-null
-value; otherwise it will include `Y`. `X` and `Y` are placeholders for
-any valid template text, and may include interpolated variables or other
-conditionals. The `$else$` section may be omitted.
-
-When variables can have multiple values (for example, `author` in
-a multi-author document), you can use the `$for$` keyword:
-
-    $for(author)$
-    <meta name="author" content="$author$" />
-    $endfor$
-
-You can optionally specify a separator to be used between
-consecutive items:
-
-    $for(author)$$author$$sep$, $endfor$
-
-A dot can be used to select a field of a variable that takes
-an object as its value.  So, for example:
-
-    $author.name$ ($author.affiliation$)
-
-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
-is to fork the [pandoc-templates] repository and merge in changes after each
-pandoc release.
-
-Templates may contain comments:  anything on a line after `$--`
-will be treated as a comment and ignored.
-
-[pandoc-templates]: https://github.com/jgm/pandoc-templates
-
-Extensions
-==========
-
-The behavior of some of the readers and writers can be adjusted by
-enabling or disabling various extensions.
-
-An extension can be enabled by adding `+EXTENSION`
-to the format name and disabled by adding `-EXTENSION`. For example,
-`--from markdown_strict+footnotes` is strict Markdown with footnotes
-enabled, while `--from markdown-footnotes-pipe_tables` is pandoc's
-Markdown without footnotes or pipe tables.
-
-The markdown reader and writer make by far the most use of extensions.
-Extensions only used by them are therefore covered in the
-section [Pandoc's Markdown] below (See [Markdown variants] for
-`commonmark` and `gfm`.) In the following, extensions that also work
-for other formats are covered.
-
-Typography
-----------
-
-#### Extension: `smart` ####
-
-Interpret straight quotes as curly quotes, `---` as em-dashes,
-`--` as en-dashes, and `...` as ellipses. Nonbreaking spaces are
-inserted after certain abbreviations, such as "Mr." 
-
-This extension can be enabled/disabled for the following formats:
-
-input formats
-:  `markdown`, `commonmark`, `latex`, `mediawiki`, `org`, `rst`, `twiki`
-
-output formats
-:  `markdown`, `latex`, `context`, `rst`
-
-enabled by default in
-:  `markdown`, `latex`, `context` (both input and output)
-
-Note: If you are *writing* Markdown, then the `smart` extension
-has the reverse effect: what would have been curly quotes comes
-out straight.
-
-In LaTeX, `smart` means to use the standard TeX ligatures
-for quotation marks (` `` ` and ` '' ` for double quotes,
-`` ` `` and `` ' `` for single quotes) and dashes (`--` for
-en-dash and `---` for em-dash).  If `smart` is disabled,
-then in reading LaTeX pandoc will parse these characters
-literally.  In writing LaTeX, enabling `smart` tells pandoc
-to use the ligatures when possible; if `smart` is disabled
-pandoc will use unicode quotation mark and dash characters.
-
-Headers and sections
---------------------
-
-#### Extension: `auto_identifiers` ####
-
-A header without an explicitly specified identifier will be
-automatically assigned a unique identifier based on the header text.
-
-This extension can be enabled/disabled for the following formats:
-
-input formats
-:  `markdown`, `latex`, `rst`, `mediawiki`, `textile`
-
-output formats
-:  `markdown`, `muse`
-
-enabled by default in
-:  `markdown`, `muse`
-
-The algorithm used to derive the identifier from the header text is:
-
-  - Remove all formatting, links, etc.
-  - Remove all footnotes.
-  - Remove all punctuation, except underscores, hyphens, and periods.
-  - Replace all spaces and newlines with hyphens.
-  - Convert all alphabetic characters to lowercase.
-  - Remove everything up to the first letter (identifiers may
-    not begin with a number or punctuation mark).
-  - If nothing is left after this, use the identifier `section`.
-
-Thus, for example,
-
-  Header                            Identifier
-  -------------------------------   ----------------------------
-  `Header identifiers in HTML`      `header-identifiers-in-html`
-  `*Dogs*?--in *my* house?`         `dogs--in-my-house`
-  `[HTML], [S5], or [RTF]?`         `html-s5-or-rtf`
-  `3. Applications`                 `applications`
-  `33`                              `section`
-
-These rules should, in most cases, allow one to determine the identifier
-from the header text. The exception is when several headers have the
-same text; in this case, the first will get an identifier as described
-above; the second will get the same identifier with `-1` appended; the
-third with `-2`; and so on.
-
-These identifiers are used to provide link targets in the table of
-contents generated by the `--toc|--table-of-contents` option. They
-also make it easy to provide links from one section of a document to
-another. A link to this section, for example, might look like this:
-
-    See the section on
-    [header identifiers](#header-identifiers-in-html-latex-and-context).
-
-Note, however, that this method of providing links to sections works
-only in HTML, LaTeX, and ConTeXt formats.
-
-If the `--section-divs` option is specified, then each section will
-be wrapped in a `section` (or a `div`, if `html4` was specified),
-and the identifier will be attached to the enclosing `<section>`
-(or `<div>`) tag rather than the header itself. This allows entire
-sections to be manipulated using JavaScript or treated differently in
-CSS.
-
-#### Extension: `ascii_identifiers` ####
-
-Causes the identifiers produced by `auto_identifiers` to be pure ASCII.
-Accents are stripped off of accented Latin letters, and non-Latin
-letters are omitted.
-
-Math Input
-----------
-
-The extensions [`tex_math_dollars`](#extension-tex_math_dollars),
-[`tex_math_single_backslash`](#extension-tex_math_single_backslash), and
-[`tex_math_double_backslash`](#extension-tex_math_double_backslash)
-are described in the section about Pandoc's Markdown.
-
-However, they can also be used with HTML input. This is handy for
-reading web pages formatted using MathJax, for example.
-
-Raw HTML/TeX
-------------
-
-The following extensions (especially how they affect Markdown
-input/output) are also described in more detail in their respective
-sections of [Pandoc's Markdown].
-
-#### [Extension: `raw_html`] {#raw_html}
-
-When converting from HTML, parse elements to raw HTML which are not
-representable in pandoc's AST.
-By default, this is disabled for HTML input.
-
-#### [Extension: `raw_tex`] {#raw_tex}
-
-Allows raw LaTeX, TeX, and ConTeXt to be included in a document.
-
-This extension can be enabled/disabled for the following formats
-(in addition to `markdown`):
-
-input formats
-:  `latex`, `org`, `textile`
-
-output formats
-:  `textile`
-
-#### [Extension: `native_divs`] {#native_divs}
-
-This extension is enabled by default for HTML input. This means that
-`div`s are parsed to pandoc native elements. (Alternatively, you
-can parse them to raw HTML using `-f html-native_divs+raw_html`.)
-
-When converting HTML to Markdown, for example, you may want to drop all
-`div`s and `span`s:
-
-    pandoc -f html-native_divs-native_spans -t markdown
-
-#### [Extension: `native_spans`] {#native_spans}
-
-Analogous to `native_divs` above.
-
-
-Literate Haskell support
-------------------------
-
-#### Extension: `literate_haskell` ####
-
-Treat the document as literate Haskell source.
-
-This extension can be enabled/disabled for the following formats:
-
-input formats
-:  `markdown`, `rst`, `latex`
-
-output formats
-:  `markdown`, `rst`, `latex`, `html`
-
-If you append `+lhs` (or `+literate_haskell`) to one of the formats
-above, pandoc will treat the document as literate Haskell source.
-This means that
-
-  - In Markdown input, "bird track" sections will be parsed as Haskell
-    code rather than block quotations.  Text between `\begin{code}`
-    and `\end{code}` will also be treated as Haskell code.  For
-    ATX-style headers the character '=' will be used instead of '#'.
-
-  - In Markdown output, code blocks with classes `haskell` and `literate`
-    will be rendered using bird tracks, and block quotations will be
-    indented one space, so they will not be treated as Haskell code.
-    In addition, headers will be rendered setext-style (with underlines)
-    rather than ATX-style (with '#' characters). (This is because ghc
-    treats '#' characters in column 1 as introducing line numbers.)
-
-  - In restructured text input, "bird track" sections will be parsed
-    as Haskell code.
-
-  - In restructured text output, code blocks with class `haskell` will
-    be rendered using bird tracks.
-
-  - In LaTeX input, text in `code` environments will be parsed as
-    Haskell code.
-
-  - In LaTeX output, code blocks with class `haskell` will be rendered
-    inside `code` environments.
-
-  - In HTML output, code blocks with class `haskell` will be rendered
-    with class `literatehaskell` and bird tracks.
-
-Examples:
-
-    pandoc -f markdown+lhs -t html
-
-reads literate Haskell source formatted with Markdown conventions and writes
-ordinary HTML (without bird tracks).
-
-    pandoc -f markdown+lhs -t html+lhs
-
-writes HTML with the Haskell code in bird tracks, so it can be copied
-and pasted as literate Haskell source.
-
-Note that GHC expects the bird tracks in the first column, so indentend literate
-code blocks (e.g. inside an itemized environment) will not be picked up by the
-Haskell compiler.
-
-Other extensions
-----------------
-
-#### Extension: `empty_paragraphs` ####
-
-Allows empty paragraphs.  By default empty paragraphs are
-omitted.
-
-This extension can be enabled/disabled for the following formats:
-
-input formats
-:  `docx`, `html`
-
-output formats
-:  `markdown`, `docx`, `odt`, `opendocument`, `html`
-
-#### Extension: `amuse` ####
-
-In the `muse` input format, this enables Text::Amuse
-extensions to Emacs Muse markup.
-
-#### Extension: `citations` {#org-citations}
-
-Some aspects of [Pandoc's Markdown citation syntax](#citations) are also accepted
-in `org` input.
-
-
-Pandoc's Markdown
-=================
-
-Pandoc understands an extended and slightly revised version of
-John Gruber's [Markdown] syntax.  This document explains the syntax,
-noting differences from standard Markdown. Except where noted, these
-differences can be suppressed by using the `markdown_strict` format instead
-of `markdown`. Extensions can be enabled or disabled to specify the
-behavior more granularly. They are described in the following. See also
-[Extensions] above, for extensions that work also on other formats.
-
-Philosophy
-----------
-
-Markdown is designed to be easy to write, and, even more importantly,
-easy to read:
-
-> A Markdown-formatted document should be publishable as-is, as plain
-> text, without looking like it's been marked up with tags or formatting
-> instructions.
-> -- [John Gruber](http://daringfireball.net/projects/markdown/syntax#philosophy)
-
-This principle has guided pandoc's decisions in finding syntax for
-tables, footnotes, and other extensions.
-
-There is, however, one respect in which pandoc's aims are different
-from the original aims of Markdown.  Whereas Markdown was originally
-designed with HTML generation in mind, pandoc is designed for multiple
-output formats.  Thus, while pandoc allows the embedding of raw HTML,
-it discourages it, and provides other, non-HTMLish ways of representing
-important document elements like definition lists, tables, mathematics, and
-footnotes.
-
-Paragraphs
-----------
-
-A paragraph is one or more lines of text followed by one or more blank lines.
-Newlines are treated as spaces, so you can reflow your paragraphs as you like.
-If you need a hard line break, put two or more spaces at the end of a line.
-
-#### Extension: `escaped_line_breaks` ####
-
-A backslash followed by a newline is also a hard line break.
-Note:  in multiline and grid table cells, this is the only way
-to create a hard line break, since trailing spaces in the cells
-are ignored.
-
-Headers
--------
-
-There are two kinds of headers: Setext and ATX.
-
-### Setext-style headers ###
-
-A setext-style header is a line of text "underlined" with a row of `=` signs
-(for a level one header) or `-` signs (for a level two header):
-
-    A level-one header
-    ==================
-
-    A level-two header
-    ------------------
-
-The header text can contain inline formatting, such as emphasis (see
-[Inline formatting], below).
-
-
-### ATX-style headers ###
-
-An ATX-style header consists of one to six `#` signs and a line of
-text, optionally followed by any number of `#` signs.  The number of
-`#` signs at the beginning of the line is the header level:
-
-    ## A level-two header
-
-    ### A level-three header ###
-
-As with setext-style headers, the header text can contain formatting:
-
-    # A level-one header with a [link](/url) and *emphasis*
-
-#### Extension: `blank_before_header` ####
-
-Standard Markdown syntax does not require a blank line before a header.
-Pandoc does require this (except, of course, at the beginning of the
-document). The reason for the requirement is that it is all too easy for a
-`#` to end up at the beginning of a line by accident (perhaps through line
-wrapping). Consider, for example:
-
-    I like several of their flavors of ice cream:
-    #22, for example, and #5.
-
-#### Extension: `space_in_atx_header` ####
-
-Many Markdown implementations do not require a space between the
-opening `#`s of an ATX header and the header text, so that
-`#5 bolt` and `#hashtag` count as headers.  With this extension,
-pandoc does require the space.
-
-### Header identifiers ###
-
-See also the [`auto_identifiers` extension](#extension-auto_identifiers) above.
-
-#### Extension: `header_attributes` ####
-
-Headers can be assigned attributes using this syntax at the end
-of the line containing the header text:
-
-    {#identifier .class .class key=value key=value}
-
-Thus, for example, the following headers will all be assigned the identifier
-`foo`:
-
-    # My header {#foo}
-
-    ## My header ##    {#foo}
-
-    My other header   {#foo}
-    ---------------
-
-(This syntax is compatible with [PHP Markdown Extra].)
-
-Note that although this syntax allows assignment of classes and key/value
-attributes, writers generally don't use all of this information.  Identifiers,
-classes, and key/value attributes are used in HTML and HTML-based formats such
-as EPUB and slidy.  Identifiers are used for labels and link anchors in the
-LaTeX, ConTeXt, Textile, and AsciiDoc writers.
-
-Headers with the class `unnumbered` will not be numbered, even if
-`--number-sections` is specified.  A single hyphen (`-`) in an attribute
-context is equivalent to `.unnumbered`, and preferable in non-English
-documents.  So,
-
-    # My header {-}
-
-is just the same as
-
-    # My header {.unnumbered}
-
-#### Extension: `implicit_header_references` ####
-
-Pandoc behaves as if reference links have been defined for each header.
-So, to link to a header
-
-    # Header identifiers in HTML
-
-you can simply write
-
-    [Header identifiers in HTML]
-
-or
-
-    [Header identifiers in HTML][]
-
-or
-
-    [the section on header identifiers][header identifiers in
-    HTML]
-
-instead of giving the identifier explicitly:
-
-    [Header identifiers in HTML](#header-identifiers-in-html)
-
-If there are multiple headers with identical text, the corresponding
-reference will link to the first one only, and you will need to use explicit
-links to link to the others, as described above.
-
-Like regular reference links, these references are case-insensitive.
-
-Explicit link reference definitions always take priority over
-implicit header references.  So, in the following example, the
-link will point to `bar`, not to `#foo`:
-
-    # Foo
-
-    [foo]: bar
-
-    See [foo]
-
-Block quotations
-----------------
-
-Markdown uses email conventions for quoting blocks of text.
-A block quotation is one or more paragraphs or other block elements
-(such as lists or headers), with each line preceded by a `>` character
-and an optional space. (The `>` need not start at the left margin, but
-it should not be indented more than three spaces.)
-
-    > This is a block quote. This
-    > paragraph has two lines.
-    >
-    > 1. This is a list inside a block quote.
-    > 2. Second item.
-
-A "lazy" form, which requires the `>` character only on the first
-line of each block, is also allowed:
-
-    > This is a block quote. This
-    paragraph has two lines.
-
-    > 1. This is a list inside a block quote.
-    2. Second item.
-
-Among the block elements that can be contained in a block quote are
-other block quotes. That is, block quotes can be nested:
-
-    > This is a block quote.
-    >
-    > > A block quote within a block quote.
-
-If the `>` character is followed by an optional space, that space
-will be considered part of the block quote marker and not part of
-the indentation of the contents.  Thus, to put an indented code
-block in a block quote, you need five spaces after the `>`:
-
-    >     code
-
-#### Extension: `blank_before_blockquote` ####
-
-Standard Markdown syntax does not require a blank line before a block
-quote.  Pandoc does require this (except, of course, at the beginning of the
-document). The reason for the requirement is that it is all too easy for a
-`>` to end up at the beginning of a line by accident (perhaps through line
-wrapping). So, unless the `markdown_strict` format is used, the following does
-not produce a nested block quote in pandoc:
-
-    > This is a block quote.
-    >> Nested.
-
-
-Verbatim (code) blocks
-----------------------
-
-### Indented code blocks ###
-
-A block of text indented four spaces (or one tab) is treated as verbatim
-text: that is, special characters do not trigger special formatting,
-and all spaces and line breaks are preserved.  For example,
-
-        if (a > 3) {
-          moveShip(5 * gravity, DOWN);
-        }
-
-The initial (four space or one tab) indentation is not considered part
-of the verbatim text, and is removed in the output.
-
-Note: blank lines in the verbatim text need not begin with four spaces.
-
-
-### Fenced code blocks ###
-
-#### Extension: `fenced_code_blocks` ####
-
-In addition to standard indented code blocks, pandoc supports
-*fenced* code blocks.  These begin with a row of three or more
-tildes (`~`) and end with a row of tildes that must be at least as long as
-the starting row. Everything between these lines is treated as code. No
-indentation is necessary:
-
-    ~~~~~~~
-    if (a > 3) {
-      moveShip(5 * gravity, DOWN);
-    }
-    ~~~~~~~
-
-Like regular code blocks, fenced code blocks must be separated
-from surrounding text by blank lines.
-
-If the code itself contains a row of tildes or backticks, just use a longer
-row of tildes or backticks at the start and end:
-
-    ~~~~~~~~~~~~~~~~
-    ~~~~~~~~~~
-    code including tildes
-    ~~~~~~~~~~
-    ~~~~~~~~~~~~~~~~
-
-#### Extension: `backtick_code_blocks` ####
-
-Same as `fenced_code_blocks`, but uses backticks (`` ` ``) instead of tildes
-(`~`).
-
-#### Extension: `fenced_code_attributes` ####
-
-Optionally, you may attach attributes to fenced or backtick code block using
-this syntax:
-
-    ~~~~ {#mycode .haskell .numberLines startFrom="100"}
-    qsort []     = []
-    qsort (x:xs) = qsort (filter (< x) xs) ++ [x] ++
-                   qsort (filter (>= x) xs)
-    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-Here `mycode` is an identifier, `haskell` and `numberLines` are classes, and
-`startFrom` is an attribute with value `100`. Some output formats can use this
-information to do syntax highlighting. Currently, the only output formats
-that uses this information are HTML, LaTeX, Docx, and Ms. If highlighting
-is supported for your output format and language, then the code block above
-will appear highlighted, with numbered lines. (To see which languages are
-supported, type `pandoc --list-highlight-languages`.) Otherwise, the code
-block above will appear as follows:
-
-    <pre id="mycode" class="haskell numberLines" startFrom="100">
-      <code>
-      ...
-      </code>
-    </pre>
-
-The `numberLines` (or `number-lines`) class will cause the lines
-of the code block to be numbered, starting with `1` or the value
-of the `startFrom` attribute.  The `lineAnchors` (or
-`line-anchors`) class will cause the lines to be clickable
-anchors in HTML output.
-
-A shortcut form can also be used for specifying the language of
-the code block:
-
-    ```haskell
-    qsort [] = []
-    ```
-
-This is equivalent to:
-
-    ``` {.haskell}
-    qsort [] = []
-    ```
-
-If the `fenced_code_attributes` extension is disabled, but
-input contains class attribute(s) for the code block, the first
-class attribute will be printed after the opening fence as a bare
-word.
-
-To prevent all highlighting, use the `--no-highlight` flag.
-To set the highlighting style, use `--highlight-style`.
-For more information on highlighting, see [Syntax highlighting],
-below.
-
-Line blocks
------------
-
-#### Extension: `line_blocks` ####
-
-A line block is a sequence of lines beginning with a vertical bar (`|`)
-followed by a space.  The division into lines will be preserved in
-the output, as will any leading spaces; otherwise, the lines will
-be formatted as Markdown.  This is useful for verse and addresses:
-
-    | The limerick packs laughs anatomical
-    | In space that is quite economical.
-    |    But the good ones I've seen
-    |    So seldom are clean
-    | And the clean ones so seldom are comical
-
-    | 200 Main St.
-    | Berkeley, CA 94718
-
-The lines can be hard-wrapped if needed, but the continuation
-line must begin with a space.
-
-    | The Right Honorable Most Venerable and Righteous Samuel L.
-      Constable, Jr.
-    | 200 Main St.
-    | Berkeley, CA 94718
-
-This syntax is borrowed from [reStructuredText].
-
-Lists
------
-
-### Bullet lists ###
-
-A bullet list is a list of bulleted list items.  A bulleted list
-item begins with a bullet (`*`, `+`, or `-`).  Here is a simple
-example:
-
-    * one
-    * two
-    * three
-
-This will produce a "compact" list. If you want a "loose" list, in which
-each item is formatted as a paragraph, put spaces between the items:
-
-    * one
-
-    * two
-
-    * three
-
-The bullets need not be flush with the left margin; they may be
-indented one, two, or three spaces. The bullet must be followed
-by whitespace.
-
-List items look best if subsequent lines are flush with the first
-line (after the bullet):
-
-    * here is my first
-      list item.
-    * and my second.
-
-But Markdown also allows a "lazy" format:
-
-    * here is my first
-    list item.
-    * and my second.
-
-### Block content in list items ###
-
-A list item may contain multiple paragraphs and other block-level
-content. However, subsequent paragraphs must be preceded by a blank line
-and indented to line up with the first non-space content after
-the list marker.
-
-      * First paragraph.
-
-        Continued.
-
-      * Second paragraph. With a code block, which must be indented
-        eight spaces:
-
-            { code }
-
-Exception: if the list marker is followed by an indented code
-block, which must begin 5 spaces after the list marker, then
-subsequent paragraphs must begin two columns after the last
-character of the list marker:
-
-    *     code
-
-      continuation paragraph
-
-List items may include other lists.  In this case the preceding blank
-line is optional.  The nested list must be indented to line up with
-the first non-space character after the list marker of the
-containing list item.
-
-    * fruits
-      + apples
-        - macintosh
-        - red delicious
-      + pears
-      + peaches
-    * vegetables
-      + broccoli
-      + chard
-
-As noted above, Markdown allows you to write list items "lazily," instead of
-indenting continuation lines. However, if there are multiple paragraphs or
-other blocks in a list item, the first line of each must be indented.
-
-    + A lazy, lazy, list
-    item.
-
-    + Another one; this looks
-    bad but is legal.
-
-        Second paragraph of second
-    list item.
-
-### Ordered lists ###
-
-Ordered lists work just like bulleted lists, except that the items
-begin with enumerators rather than bullets.
-
-In standard Markdown, enumerators are decimal numbers followed
-by a period and a space.  The numbers themselves are ignored, so
-there is no difference between this list:
-
-    1.  one
-    2.  two
-    3.  three
-
-and this one:
-
-    5.  one
-    7.  two
-    1.  three
-
-#### Extension: `fancy_lists` ####
-
-Unlike standard Markdown, pandoc allows ordered list items to be marked
-with uppercase and lowercase letters and roman numerals, in addition to
-Arabic numerals. List markers may be enclosed in parentheses or followed by a
-single right-parentheses or period. They must be separated from the
-text that follows by at least one space, and, if the list marker is a
-capital letter with a period, by at least two spaces.[^2]
-
-[^2]:  The point of this rule is to ensure that normal paragraphs
-    starting with people's initials, like
-
-        B. Russell was an English philosopher.
-
-    do not get treated as list items.
-
-    This rule will not prevent
-
-        (C) 2007 Joe Smith
-
-    from being interpreted as a list item.  In this case, a backslash
-    escape can be used:
-
-        (C\) 2007 Joe Smith
-
-The `fancy_lists` extension also allows '`#`' to be used as an
-ordered list marker in place of a numeral:
-
-    #. one
-    #. two
-
-#### Extension: `startnum` ####
-
-Pandoc also pays attention to the type of list marker used, and to the
-starting number, and both of these are preserved where possible in the
-output format. Thus, the following yields a list with numbers followed
-by a single parenthesis, starting with 9, and a sublist with lowercase
-roman numerals:
-
-     9)  Ninth
-    10)  Tenth
-    11)  Eleventh
-           i. subone
-          ii. subtwo
-         iii. subthree
-
-Pandoc will start a new list each time a different type of list
-marker is used.  So, the following will create three lists:
-
-    (2) Two
-    (5) Three
-    1.  Four
-    *   Five
-
-If default list markers are desired, use `#.`:
-
-    #.  one
-    #.  two
-    #.  three
-
-
-### Definition lists ###
-
-#### Extension: `definition_lists` ####
-
-Pandoc supports definition lists, using the syntax of
-[PHP Markdown Extra] with some extensions.[^3]
-
-    Term 1
-
-    :   Definition 1
-
-    Term 2 with *inline markup*
-
-    :   Definition 2
-
-            { some code, part of Definition 2 }
-
-        Third paragraph of definition 2.
-
-Each term must fit on one line, which may optionally be followed by
-a blank line, and must be followed by one or more definitions.
-A definition begins with a colon or tilde, which may be indented one
-or two spaces.
-
-A term may have multiple definitions, and each definition may consist of one or
-more block elements (paragraph, code block, list, etc.), each indented four
-spaces or one tab stop.  The body of the definition (including the first line,
-aside from the colon or tilde) should be indented four spaces. However,
-as with other Markdown lists, you can "lazily" omit indentation except
-at the beginning of a paragraph or other block element:
-
-    Term 1
-
-    :   Definition
-    with lazy continuation.
-
-        Second paragraph of the definition.
-
-If you leave space before the definition (as in the example above),
-the text of the definition will be treated as a paragraph.  In some
-output formats, this will mean greater spacing between term/definition
-pairs. For a more compact definition list, omit the space before the
-definition:
-
-    Term 1
-      ~ Definition 1
-
-    Term 2
-      ~ Definition 2a
-      ~ Definition 2b
-
-Note that space between items in a definition list is required.
-(A variant that loosens this requirement, but disallows "lazy"
-hard wrapping, can be activated with `compact_definition_lists`: see
-[Non-pandoc extensions], below.)
-
-[^3]:  I have been influenced by the suggestions of [David Wheeler](http://www.justatheory.com/computers/markup/modest-markdown-proposal.html).
-
-### Numbered example lists ###
-
-#### Extension: `example_lists` ####
-
-The special list marker `@` can be used for sequentially numbered
-examples. The first list item with a `@` marker will be numbered '1',
-the next '2', and so on, throughout the document. The numbered examples
-need not occur in a single list; each new list using `@` will take up
-where the last stopped. So, for example:
-
-    (@)  My first example will be numbered (1).
-    (@)  My second example will be numbered (2).
-
-    Explanation of examples.
-
-    (@)  My third example will be numbered (3).
-
-Numbered examples can be labeled and referred to elsewhere in the
-document:
-
-    (@good)  This is a good example.
-
-    As (@good) illustrates, ...
-
-The label can be any string of alphanumeric characters, underscores,
-or hyphens.
-
-Note:  continuation paragraphs in example lists must always
-be indented four spaces, regardless of the length of the
-list marker.  That is, example lists always behave as if the
-`four_space_rule` extension is set.  This is because example
-labels tend to be long, and indenting content to the
-first non-space character after the label would be awkward.
-
-### Compact and loose lists ###
-
-Pandoc behaves differently from `Markdown.pl` on some "edge
-cases" involving lists.  Consider this source:
-
-    +   First
-    +   Second:
-    	-   Fee
-    	-   Fie
-    	-   Foe
-
-    +   Third
-
-Pandoc transforms this into a "compact list" (with no `<p>` tags around
-"First", "Second", or "Third"), while Markdown puts `<p>` tags around
-"Second" and "Third" (but not "First"), because of the blank space
-around "Third". Pandoc follows a simple rule: if the text is followed by
-a blank line, it is treated as a paragraph. Since "Second" is followed
-by a list, and not a blank line, it isn't treated as a paragraph. The
-fact that the list is followed by a blank line is irrelevant. (Note:
-Pandoc works this way even when the `markdown_strict` format is specified. This
-behavior is consistent with the official Markdown syntax description,
-even though it is different from that of `Markdown.pl`.)
-
-
-### Ending a list ###
-
-What if you want to put an indented code block after a list?
-
-    -   item one
-    -   item two
-
-        { my code block }
-
-Trouble! Here pandoc (like other Markdown implementations) will treat
-`{ my code block }` as the second paragraph of item two, and not as
-a code block.
-
-To "cut off" the list after item two, you can insert some non-indented
-content, like an HTML comment, which won't produce visible output in
-any format:
-
-    -   item one
-    -   item two
-
-    <!-- end of list -->
-
-        { my code block }
-
-You can use the same trick if you want two consecutive lists instead
-of one big list:
-
-    1.  one
-    2.  two
-    3.  three
-
-    <!-- -->
-
-    1.  uno
-    2.  dos
-    3.  tres
-
-Horizontal rules
-----------------
-
-A line containing a row of three or more `*`, `-`, or `_` characters
-(optionally separated by spaces) produces a horizontal rule:
-
-    *  *  *  *
-
-    ---------------
-
-
-Tables
-------
-
-Four kinds of tables may be used. The first three kinds presuppose the use of
-a fixed-width font, such as Courier. The fourth kind can be used with
-proportionally spaced fonts, as it does not require lining up columns.
-
-#### Extension: `table_captions` ####
-
-A caption may optionally be provided with all 4 kinds of tables (as
-illustrated in the examples below). A caption is a paragraph beginning
-with the string `Table:` (or just `:`), which will be stripped off.
-It may appear either before or after the table.
-
-#### Extension: `simple_tables` ####
-
-Simple tables look like this:
-
-      Right     Left     Center     Default
-    -------     ------ ----------   -------
-         12     12        12            12
-        123     123       123          123
-          1     1          1             1
-
-    Table:  Demonstration of simple table syntax.
-
-The headers and table rows must each fit on one line.  Column
-alignments are determined by the position of the header text relative
-to the dashed line below it:[^4]
-
-  - If the dashed line is flush with the header text on the right side
-    but extends beyond it on the left, the column is right-aligned.
-  - If the dashed line is flush with the header text on the left side
-    but extends beyond it on the right, the column is left-aligned.
-  - If the dashed line extends beyond the header text on both sides,
-    the column is centered.
-  - If the dashed line is flush with the header text on both sides,
-    the default alignment is used (in most cases, this will be left).
-
-[^4]:  This scheme is due to Michel Fortin, who proposed it on the
-       [Markdown discussion list](http://six.pairlist.net/pipermail/markdown-discuss/2005-March/001097.html).
-
-The table must end with a blank line, or a line of dashes followed by
-a blank line.
-
-The column headers may be omitted, provided a dashed line is used
-to end the table. For example:
-
-    -------     ------ ----------   -------
-         12     12        12             12
-        123     123       123           123
-          1     1          1              1
-    -------     ------ ----------   -------
-
-When headers are omitted, column alignments are determined on the basis
-of the first line of the table body. So, in the tables above, the columns
-would be right, left, center, and right aligned, respectively.
-
-#### Extension: `multiline_tables` ####
-
-Multiline tables allow headers and table rows to span multiple lines
-of text (but cells that span multiple columns or rows of the table are
-not supported).  Here is an example:
-
-    -------------------------------------------------------------
-     Centered   Default           Right Left
-      Header    Aligned         Aligned Aligned
-    ----------- ------- --------------- -------------------------
-       First    row                12.0 Example of a row that
-                                        spans multiple lines.
-
-      Second    row                 5.0 Here's another one. Note
-                                        the blank line between
-                                        rows.
-    -------------------------------------------------------------
-
-    Table: Here's the caption. It, too, may span
-    multiple lines.
-
-These work like simple tables, but with the following differences:
-
-  - They must begin with a row of dashes, before the header text
-    (unless the headers are omitted).
-  - They must end with a row of dashes, then a blank line.
-  - The rows must be separated by blank lines.
-
-In multiline tables, the table parser pays attention to the widths of
-the columns, and the writers try to reproduce these relative widths in
-the output. So, if you find that one of the columns is too narrow in the
-output, try widening it in the Markdown source.
-
-Headers may be omitted in multiline tables as well as simple tables:
-
-    ----------- ------- --------------- -------------------------
-       First    row                12.0 Example of a row that
-                                        spans multiple lines.
-
-      Second    row                 5.0 Here's another one. Note
-                                        the blank line between
-                                        rows.
-    ----------- ------- --------------- -------------------------
-
-    : Here's a multiline table without headers.
-
-It is possible for a multiline table to have just one row, but the row
-should be followed by a blank line (and then the row of dashes that ends
-the table), or the table may be interpreted as a simple table.
-
-#### Extension: `grid_tables` ####
-
-Grid tables look like this:
-
-    : Sample grid table.
-
-    +---------------+---------------+--------------------+
-    | Fruit         | Price         | Advantages         |
-    +===============+===============+====================+
-    | Bananas       | $1.34         | - built-in wrapper |
-    |               |               | - bright color     |
-    +---------------+---------------+--------------------+
-    | Oranges       | $2.10         | - cures scurvy     |
-    |               |               | - tasty            |
-    +---------------+---------------+--------------------+
-
-The row of `=`s separates the header from the table body, and can be
-omitted for a headerless table. The cells of grid tables may contain
-arbitrary block elements (multiple paragraphs, code blocks, lists,
-etc.). Cells that span multiple columns or rows are not
-supported. Grid tables can be created easily using [Emacs table mode].
-
-[Emacs table mode]: http://table.sourceforge.net/
-
-Alignments can be specified as with pipe tables, by putting
-colons at the boundaries of the separator line after the
-header:
-
-    +---------------+---------------+--------------------+
-    | Right         | Left          | Centered           |
-    +==============:+:==============+:==================:+
-    | Bananas       | $1.34         | built-in wrapper   |
-    +---------------+---------------+--------------------+
-
-For headerless tables, the colons go on the top line instead:
-
-    +--------------:+:--------------+:------------------:+
-    | Right         | Left          | Centered           |
-    +---------------+---------------+--------------------+
-
-##### Grid Table Limitations #####
-
-Pandoc does not support grid tables with row spans or column spans.
-This means that neither variable numbers of columns across rows nor
-variable numbers of rows across columns are supported by Pandoc.
-All grid tables must have the same number of columns in each row,
-and the same number of rows in each column.  For example, the
-Docutils [sample grid tables] will not render as expected with
-Pandoc.
-
-[sample grid tables]: http://docutils.sourceforge.net/docs/ref/rst/restructuredtext.html#grid-tables
-
-
-#### Extension: `pipe_tables` ####
-
-Pipe tables look like this:
-
-    | Right | Left | Default | Center |
-    |------:|:-----|---------|:------:|
-    |   12  |  12  |    12   |    12  |
-    |  123  |  123 |   123   |   123  |
-    |    1  |    1 |     1   |     1  |
-
-      : Demonstration of pipe table syntax.
-
-The syntax is identical to [PHP Markdown Extra tables].  The beginning and
-ending pipe characters are optional, but pipes are required between all
-columns.  The colons indicate column alignment as shown.  The header
-cannot be omitted.  To simulate a headerless table, include a header
-with blank cells.
-
-Since the pipes indicate column boundaries, columns need not be vertically
-aligned, as they are in the above example.  So, this is a perfectly
-legal (though ugly) pipe table:
-
-    fruit| price
-    -----|-----:
-    apple|2.05
-    pear|1.37
-    orange|3.09
-
-The cells of pipe tables cannot contain block elements like paragraphs
-and lists, and cannot span multiple lines.  If a pipe table contains a
-row whose printable content is wider than the column width (see
-`--columns`), then the cell contents will wrap, with the
-relative cell widths determined by the widths of the separator
-lines.  (In this case, the table will take up the full text
-width.)  If no lines are wider than column width, then
-cell contents will not be wrapped, and the cells will be sized
-to their contents.
-
-Note:  pandoc also recognizes pipe tables of the following
-form, as can be produced by Emacs' orgtbl-mode:
-
-    | One | Two   |
-    |-----+-------|
-    | my  | table |
-    | is  | nice  |
-
-The difference is that `+` is used instead of `|`. Other orgtbl features
-are not supported. In particular, to get non-default column alignment,
-you'll need to add colons as above.
-
-[PHP Markdown Extra tables]: https://michelf.ca/projects/php-markdown/extra/#table
-
-Metadata blocks
----------------
-
-#### Extension: `pandoc_title_block` ####
-
-If the file begins with a title block
-
-    % title
-    % author(s) (separated by semicolons)
-    % date
-
-it will be parsed as bibliographic information, not regular text.  (It
-will be used, for example, in the title of standalone LaTeX or HTML
-output.)  The block may contain just a title, a title and an author,
-or all three elements. If you want to include an author but no
-title, or a title and a date but no author, you need a blank line:
-
-    %
-    % Author
-
-    % My title
-    %
-    % June 15, 2006
-
-The title may occupy multiple lines, but continuation lines must
-begin with leading space, thus:
-
-    % My title
-      on multiple lines
-
-If a document has multiple authors, the authors may be put on
-separate lines with leading space, or separated by semicolons, or
-both.  So, all of the following are equivalent:
-
-    % Author One
-      Author Two
-
-    % Author One; Author Two
-
-    % Author One;
-      Author Two
-
-The date must fit on one line.
-
-All three metadata fields may contain standard inline formatting
-(italics, links, footnotes, etc.).
-
-Title blocks will always be parsed, but they will affect the output only
-when the `--standalone` (`-s`) option is chosen. In HTML output, titles
-will appear twice: once in the document head -- this is the title that
-will appear at the top of the window in a browser -- and once at the
-beginning of the document body. The title in the document head can have
-an optional prefix attached (`--title-prefix` or `-T` option). The title
-in the body appears as an H1 element with class "title", so it can be
-suppressed or reformatted with CSS. If a title prefix is specified with
-`-T` and no title block appears in the document, the title prefix will
-be used by itself as the HTML title.
-
-The man page writer extracts a title, man page section number, and
-other header and footer information from the title line. The title
-is assumed to be the first word on the title line, which may optionally
-end with a (single-digit) section number in parentheses. (There should
-be no space between the title and the parentheses.)  Anything after
-this is assumed to be additional footer and header text. A single pipe
-character (`|`) should be used to separate the footer text from the header
-text.  Thus,
-
-    % PANDOC(1)
-
-will yield a man page with the title `PANDOC` and section 1.
-
-    % PANDOC(1) Pandoc User Manuals
-
-will also have "Pandoc User Manuals" in the footer.
-
-    % PANDOC(1) Pandoc User Manuals | Version 4.0
-
-will also have "Version 4.0" in the header.
-
-#### Extension: `yaml_metadata_block` ####
-
-A YAML metadata block is a valid YAML object, delimited by a line of three
-hyphens (`---`) at the top and a line of three hyphens (`---`) or three dots
-(`...`) at the bottom.  A YAML metadata block may occur anywhere in the
-document, but if it is not at the beginning, it must be preceded by a blank
-line.  (Note that, because of the way pandoc concatenates input files when
-several are provided, you may also keep the metadata in a separate YAML file
-and pass it to pandoc as an argument, along with your Markdown files:
-
-    pandoc chap1.md chap2.md chap3.md metadata.yaml -s -o book.html
-
-Just be sure that the YAML file begins with `---` and ends with `---` or
-`...`.)
-
-Metadata will be taken from the fields of the YAML object and added to any
-existing document metadata.  Metadata can contain lists and objects (nested
-arbitrarily), but all string scalars will be interpreted as Markdown.  Fields
-with names ending in an underscore will be ignored by pandoc.  (They may be
-given a role by external processors.)
-
-A document may contain multiple metadata blocks.  The metadata fields will
-be combined through a *left-biased union*:  if two metadata blocks attempt
-to set the same field, the value from the first block will be taken.
-
-When pandoc is used with `-t markdown` to create a Markdown document,
-a YAML metadata block will be produced only if the `-s/--standalone`
-option is used.  All of the metadata will appear in a single block
-at the beginning of the document.
-
-Note that YAML escaping rules must be followed. Thus, for example,
-if a title contains a colon, it must be quoted.  The pipe character
-(`|`) can be used to begin an indented block that will be interpreted
-literally, without need for escaping.  This form is necessary
-when the field contains blank lines or block-level formatting:
-
-    ---
-    title:  'This is the title: it contains a colon'
-    author:
-    - Author One
-    - Author Two
-    tags: [nothing, nothingness]
-    abstract: |
-      This is the abstract.
-
-      It consists of two paragraphs.
-    ...
-
-Template variables will be set automatically from the metadata.  Thus, for
-example, in writing HTML, the variable `abstract` will be set to the HTML
-equivalent of the Markdown in the `abstract` field:
-
-    <p>This is the abstract.</p>
-    <p>It consists of two paragraphs.</p>
-
-Variables can contain arbitrary YAML structures, but the template must match
-this structure.  The `author` variable in the default templates expects a
-simple list or string, but can be changed to support more complicated
-structures.  The following combination, for example, would add an affiliation
-to the author if one is given:
-
-    ---
-    title: The document title
-    author:
-    - name: Author One
-      affiliation: University of Somewhere
-    - name: Author Two
-      affiliation: University of Nowhere
-    ...
-
-To use the structured authors in the example above, you would need a custom
-template:
-
-    $for(author)$
-    $if(author.name)$
-    $author.name$$if(author.affiliation)$ ($author.affiliation$)$endif$
-    $else$
-    $author$
-    $endif$
-    $endfor$
-
-
-Backslash escapes
------------------
-
-#### Extension: `all_symbols_escapable` ####
-
-Except inside a code block or inline code, any punctuation or space
-character preceded by a backslash will be treated literally, even if it
-would normally indicate formatting.  Thus, for example, if one writes
-
-    *\*hello\**
-
-one will get
-
-    <em>*hello*</em>
-
-instead of
-
-    <strong>hello</strong>
-
-This rule is easier to remember than standard Markdown's rule,
-which allows only the following characters to be backslash-escaped:
-
-    \`*_{}[]()>#+-.!
-
-(However, if the `markdown_strict` format is used, the standard Markdown rule
-will be used.)
-
-A backslash-escaped space is parsed as a nonbreaking space.  It will
-appear in TeX output as `~` and in HTML and XML as `\&#160;` or
-`\&nbsp;`.
-
-A backslash-escaped newline (i.e. a backslash occurring at the end of
-a line) is parsed as a hard line break.  It will appear in TeX output as
-`\\` and in HTML as `<br />`.  This is a nice alternative to
-Markdown's "invisible" way of indicating hard line breaks using
-two trailing spaces on a line.
-
-Backslash escapes do not work in verbatim contexts.
-
-Inline formatting
------------------
-
-### Emphasis ###
-
-To *emphasize* some text, surround it with `*`s or `_`, like this:
-
-    This text is _emphasized with underscores_, and this
-    is *emphasized with asterisks*.
-
-Double `*` or `_` produces **strong emphasis**:
-
-    This is **strong emphasis** and __with underscores__.
-
-A `*` or `_` character surrounded by spaces, or backslash-escaped,
-will not trigger emphasis:
-
-    This is * not emphasized *, and \*neither is this\*.
-
-#### Extension: `intraword_underscores` ####
-
-Because `_` is sometimes used inside words and identifiers,
-pandoc does not interpret a `_` surrounded by alphanumeric
-characters as an emphasis marker.  If you want to emphasize
-just part of a word, use `*`:
-
-    feas*ible*, not feas*able*.
-
-
-### Strikeout ###
-
-#### Extension: `strikeout` ####
-
-To strikeout a section of text with a horizontal line, begin and end it
-with `~~`. Thus, for example,
-
-    This ~~is deleted text.~~
-
-
-### Superscripts and subscripts ###
-
-#### Extension: `superscript`, `subscript` ####
-
-Superscripts may be written by surrounding the superscripted text by `^`
-characters; subscripts may be written by surrounding the subscripted
-text by `~` characters.  Thus, for example,
-
-    H~2~O is a liquid.  2^10^ is 1024.
-
-If the superscripted or subscripted text contains spaces, these spaces
-must be escaped with backslashes.  (This is to prevent accidental
-superscripting and subscripting through the ordinary use of `~` and `^`.)
-Thus, if you want the letter P with 'a cat' in subscripts, use
-`P~a\ cat~`, not `P~a cat~`.
-
-
-### Verbatim ###
-
-To make a short span of text verbatim, put it inside backticks:
-
-    What is the difference between `>>=` and `>>`?
-
-If the verbatim text includes a backtick, use double backticks:
-
-    Here is a literal backtick `` ` ``.
-
-(The spaces after the opening backticks and before the closing
-backticks will be ignored.)
-
-The general rule is that a verbatim span starts with a string
-of consecutive backticks (optionally followed by a space)
-and ends with a string of the same number of backticks (optionally
-preceded by a space).
-
-Note that backslash-escapes (and other Markdown constructs) do not
-work in verbatim contexts:
-
-    This is a backslash followed by an asterisk: `\*`.
-
-#### Extension: `inline_code_attributes` ####
-
-Attributes can be attached to verbatim text, just as with
-[fenced code blocks]:
-
-    `<$>`{.haskell}
-
-### Small caps ###
-
-To write small caps, use the `smallcaps` class:
-
-    [Small caps]{.smallcaps}
-
-Or, without the `bracketed_spans` extension:
-
-    <span class="smallcaps">Small caps</span>
-
-For compatibility with other Markdown flavors, CSS is also supported:
-
-    <span style="font-variant:small-caps;">Small caps</span>
-
-This will work in all output formats that support small caps.
-
-
-Math
-----
-
-#### Extension: `tex_math_dollars` ####
-
-Anything between two `$` characters will be treated as TeX math.  The
-opening `$` must have a non-space character immediately to its right,
-while the closing `$` must have a non-space character immediately to its
-left, and must not be followed immediately by a digit.  Thus,
-`$20,000 and $30,000` won't parse as math.  If for some reason
-you need to enclose text in literal `$` characters, backslash-escape
-them and they won't be treated as math delimiters.
-
-TeX math will be printed in all output formats. How it is rendered
-depends on the output format:
-
-Markdown, LaTeX, Emacs Org mode, ConTeXt, ZimWiki
-  ~ It will appear verbatim between `$` characters.
-
-reStructuredText
-  ~ It will be rendered using an [interpreted text role `:math:`].
-
-AsciiDoc
-  ~ It will be rendered as `latexmath:[...]`.
-
-Texinfo
-  ~ It will be rendered inside a `@math` command.
-
-groff man
-  ~ It will be rendered verbatim without `$`'s.
-
-MediaWiki, DokuWiki
-  ~ It will be rendered inside `<math>` tags.
-
-Textile
-  ~ It will be rendered inside `<span class="math">` tags.
-
-RTF, OpenDocument
-  ~ It will be rendered, if possible, using Unicode characters,
-    and will otherwise appear verbatim.
-
-ODT
-  ~ It will be rendered, if possible, using MathML.
-
-DocBook
-  ~ If the `--mathml` flag is used, it will be rendered using MathML
-    in an `inlineequation` or `informalequation` tag.  Otherwise it
-    will be rendered, if possible, using Unicode characters.
-
-Docx
-  ~ It will be rendered using OMML math markup.
-
-FictionBook2
-  ~ If the `--webtex` option is used, formulas are rendered as images
-    using CodeCogs or other compatible web service, downloaded
-    and embedded in the e-book. Otherwise, they will appear verbatim.
-
-HTML, Slidy, DZSlides, S5, EPUB
-  ~ The way math is rendered in HTML will depend on the
-    command-line options selected. Therefore see [Math rendering in HTML]
-    above.
-
-[interpreted text role `:math:`]: http://docutils.sourceforge.net/docs/ref/rst/roles.html#math
-
-Raw HTML
---------
-
-#### Extension: `raw_html` ####
-
-Markdown allows you to insert raw HTML (or DocBook) anywhere in a document
-(except verbatim contexts, where `<`, `>`, and `&` are interpreted
-literally).  (Technically this is not an extension, since standard
-Markdown allows it, but it has been made an extension so that it can
-be disabled if desired.)
-
-The raw HTML is passed through unchanged in HTML, S5, Slidy, Slideous,
-DZSlides, EPUB, Markdown, Emacs Org mode, and Textile output, and suppressed
-in other formats.
-
-#### Extension: `markdown_in_html_blocks` ####
-
-Standard Markdown allows you to include HTML "blocks":  blocks
-of HTML between balanced tags that are separated from the surrounding text
-with blank lines, and start and end at the left margin.  Within
-these blocks, everything is interpreted as HTML, not Markdown;
-so (for example), `*` does not signify emphasis.
-
-Pandoc behaves this way when the `markdown_strict` format is used; but
-by default, pandoc interprets material between HTML block tags as Markdown.
-Thus, for example, pandoc will turn
-
-    <table>
-    <tr>
-    <td>*one*</td>
-    <td>[a link](http://google.com)</td>
-    </tr>
-    </table>
-
-into
-
-    <table>
-    <tr>
-    <td><em>one</em></td>
-    <td><a href="http://google.com">a link</a></td>
-    </tr>
-    </table>
-
-whereas `Markdown.pl` will preserve it as is.
-
-There is one exception to this rule:  text between `<script>` and
-`<style>` tags is not interpreted as Markdown.
-
-This departure from standard Markdown should make it easier to mix
-Markdown with HTML block elements.  For example, one can surround
-a block of Markdown text with `<div>` tags without preventing it
-from being interpreted as Markdown.
-
-#### Extension: `native_divs` ####
-
-Use native pandoc `Div` blocks for content inside `<div>` tags.
-For the most part this should give the same output as
-`markdown_in_html_blocks`, but it makes it easier to write pandoc
-filters to manipulate groups of blocks.
-
-#### Extension: `native_spans` ####
-
-Use native pandoc `Span` blocks for content inside `<span>` tags.
-For the most part this should give the same output as `raw_html`,
-but it makes it easier to write pandoc filters to manipulate groups
-of inlines.
-
-#### Extension: `fenced_divs` ####
-
-Allow special fenced syntax for native `Div` blocks.  A Div
-starts with a fence containing at least three consecutive
-colons plus some attributes. The attributes may optionally
-be followed by another string of consecutive colons.
-The attribute syntax is exactly as in fenced code blocks (see
-[Extension: `fenced_code_attributes`]).  As with fenced
-code blocks, one can use either attributes in curly braces
-or a single unbraced word, which will be treated as a class
-name.  The Div ends with another line containing a string of at
-least three consecutive colons.  The fenced Div should be
-separated by blank lines from preceding and following blocks.
-
-Example:
-
-    ::::: {#special .sidebar}
-    Here is a paragraph.
-
-    And another.
-    :::::
-
-Fenced divs can be nested.  Opening fences are distinguished
-because they *must* have attributes:
-
-    ::: Warning ::::::
-    This is a warning.
-
-    ::: Danger
-    This is a warning within a warning.
-    :::
-    ::::::::::::::::::
-
-Fences without attributes are always closing fences.  Unlike
-with fenced code blocks, the number of colons in the closing
-fence need not match the number in the opening fence.  However,
-it can be helpful for visual clarity to use fences of different
-lengths to distinguish nested divs from their parents.
-
-#### Extension: `raw_tex` ####
-
-In addition to raw HTML, pandoc allows raw LaTeX, TeX, and ConTeXt to be
-included in a document. Inline TeX commands will be preserved and passed
-unchanged to the LaTeX and ConTeXt writers. Thus, for example, you can use
-LaTeX to include BibTeX citations:
-
-    This result was proved in \cite{jones.1967}.
-
-Note that in LaTeX environments, like
-
-    \begin{tabular}{|l|l|}\hline
-    Age & Frequency \\ \hline
-    18--25  & 15 \\
-    26--35  & 33 \\
-    36--45  & 22 \\ \hline
-    \end{tabular}
-
-the material between the begin and end tags will be interpreted as raw
-LaTeX, not as Markdown.
-
-Inline LaTeX is ignored in output formats other than Markdown, LaTeX,
-Emacs Org mode, and ConTeXt.
-
-### Generic raw attribute ###
-
-#### Extension: `raw_attribute` ####
-
-Inline spans and fenced code blocks with a special
-kind of attribute will be parsed as raw content with the
-designated format.  For example, the following produces a raw
-groff `ms` block:
-
-    ```{=ms}
-    .MYMACRO
-    blah blah
-    ```
-And the following produces a raw `html` inline element:
-
-    This is `<a>html</a>`{=html}
-
-The format name should match the target format name (see
-`-t/--to`, above, for a list, or use `pandoc
---list-output-formats`).
-
-This extension presupposes that the relevant kind of
-inline code or fenced code block is enabled.  Thus, for
-example, to use a raw attribute with a backtick code block,
-`backtick_code_blocks` must be enabled.
-
-The raw attribute cannot be combined with regular attributes.
-
-LaTeX macros
-------------
-
-#### Extension: `latex_macros` ####
-
-For output formats other than LaTeX, pandoc will parse LaTeX
-macro definitions and apply the resulting macros to all LaTeX
-math and raw LaTeX.  So, for example, the following will work in
-all output formats, not just LaTeX:
-
-    \newcommand{\tuple}[1]{\langle #1 \rangle}
-
-    $\tuple{a, b, c}$
-
-In LaTeX output, the macro definitions will not be passed
-through as raw LaTeX.
-
-When `latex_macros` is disabled, the macro definitions will
-be passed through as raw LaTeX, and the raw LaTeX and math will
-not have macros applied. This is usually a better approach when
-you are targeting LaTeX or PDF.
-
-Links
------
-
-Markdown allows links to be specified in several ways.
-
-### Automatic links ###
-
-If you enclose a URL or email address in pointy brackets, it
-will become a link:
-
-    <http://google.com>
-    <sam@green.eggs.ham>
-
-### Inline links ###
-
-An inline link consists of the link text in square brackets,
-followed by the URL in parentheses. (Optionally, the URL can
-be followed by a link title, in quotes.)
-
-    This is an [inline link](/url), and here's [one with
-    a title](http://fsf.org "click here for a good time!").
-
-There can be no space between the bracketed part and the parenthesized part.
-The link text can contain formatting (such as emphasis), but the title cannot.
-
-Email addresses in inline links are not autodetected, so they have to be
-prefixed with `mailto`:
-
-    [Write me!](mailto:sam@green.eggs.ham)
-
-### Reference links ###
-
-An *explicit* reference link has two parts, the link itself and the link
-definition, which may occur elsewhere in the document (either
-before or after the link).
-
-The link consists of link text in square brackets, followed by a label in
-square brackets. (There cannot be space between the two unless the
-`spaced_reference_links` extension is enabled.) The link definition
-consists of the bracketed label, followed by a colon and a space, followed by
-the URL, and optionally (after a space) a link title either in quotes or in
-parentheses.  The label must not be parseable as a citation (assuming
-the `citations` extension is enabled):  citations take precedence over
-link labels.
-
-Here are some examples:
-
-    [my label 1]: /foo/bar.html  "My title, optional"
-    [my label 2]: /foo
-    [my label 3]: http://fsf.org (The free software foundation)
-    [my label 4]: /bar#special  'A title in single quotes'
-
-The URL may optionally be surrounded by angle brackets:
-
-    [my label 5]: <http://foo.bar.baz>
-
-The title may go on the next line:
-
-    [my label 3]: http://fsf.org
-      "The free software foundation"
-
-Note that link labels are not case sensitive.  So, this will work:
-
-    Here is [my link][FOO]
-
-    [Foo]: /bar/baz
-
-In an *implicit* reference link, the second pair of brackets is
-empty:
-
-    See [my website][].
-
-    [my website]: http://foo.bar.baz
-
-Note:  In `Markdown.pl` and most other Markdown implementations,
-reference link definitions cannot occur in nested constructions
-such as list items or block quotes.  Pandoc lifts this arbitrary
-seeming restriction.  So the following is fine in pandoc, though
-not in most other implementations:
-
-    > My block [quote].
-    >
-    > [quote]: /foo
-
-#### Extension: `shortcut_reference_links` ####
-
-In a *shortcut* reference link, the second pair of brackets may
-be omitted entirely:
-
-    See [my website].
-
-    [my website]: http://foo.bar.baz
-
-### Internal links ###
-
-To link to another section of the same document, use the automatically
-generated identifier (see [Header identifiers]). For example:
-
-    See the [Introduction](#introduction).
-
-or
-
-    See the [Introduction].
-
-    [Introduction]: #introduction
-
-Internal links are currently supported for HTML formats (including
-HTML slide shows and EPUB), LaTeX, and ConTeXt.
-
-Images
-------
-
-A link immediately preceded by a `!` will be treated as an image.
-The link text will be used as the image's alt text:
-
-    ![la lune](lalune.jpg "Voyage to the moon")
-
-    ![movie reel]
-
-    [movie reel]: movie.gif
-
-#### Extension: `implicit_figures` ####
-
-An image with nonempty alt text, occurring by itself in a
-paragraph, will be rendered as a figure with a caption.  The
-image's alt text will be used as the caption.
-
-    ![This is the caption](/url/of/image.png)
-
-How this is rendered depends on the output format. Some output
-formats (e.g. RTF) do not yet support figures.  In those
-formats, you'll just get an image in a paragraph by itself, with
-no caption.
-
-If you just want a regular inline image, just make sure it is not
-the only thing in the paragraph. One way to do this is to insert a
-nonbreaking space after the image:
-
-    ![This image won't be a figure](/url/of/image.png)\ 
-
-Note that in reveal.js slide shows, an image in a paragraph
-by itself that has the `stretch` class will fill the screen,
-and the caption and figure tags will be omitted.
-
-#### Extension: `link_attributes` ####
-
-Attributes can be set on links and images:
-
-    An inline ![image](foo.jpg){#id .class width=30 height=20px}
-    and a reference ![image][ref] with attributes.
-
-    [ref]: foo.jpg "optional title" {#id .class key=val key2="val 2"}
-
-(This syntax is compatible with [PHP Markdown Extra] when only `#id`
-and `.class` are used.)
-
-For HTML and EPUB, all attributes except `width` and `height` (but
-including `srcset` and `sizes`) are passed through as is. The other
-writers ignore attributes that are not supported by their output
-format.
-
-The `width` and `height` attributes on images are treated specially. When
-used without a unit, the unit is assumed to be pixels. However, any of
-the following unit identifiers can be used: `px`, `cm`, `mm`, `in`, `inch`
-and `%`. There must not be any spaces between the number and the unit.
-For example:
-
-```
-![](file.jpg){ width=50% }
-```
-
-- Dimensions are converted to inches for output in page-based formats like
-  LaTeX. Dimensions are converted to pixels for output in HTML-like
-  formats.  Use the `--dpi` option to specify the number of pixels per
-  inch.  The default is 96dpi.
-- The `%` unit is generally relative to some available space.
-  For example the above example will render to
-  `<img href="file.jpg" style="width: 50%;" />` (HTML),
-  `\includegraphics[width=0.5\textwidth]{file.jpg}` (LaTeX), or
-  `\externalfigure[file.jpg][width=0.5\textwidth]` (ConTeXt).
-- Some output formats have a notion of a class
-  ([ConTeXt](http://wiki.contextgarden.net/Using_Graphics#Multiple_Image_Settings))
-  or a unique identifier (LaTeX `\caption`), or both (HTML).
-- When no `width` or `height` attributes are specified, the fallback
-  is to look at the image resolution and the dpi metadata embedded in
-  the image file.
-
-Spans
------
-
-#### Extension: `bracketed_spans` ####
-
-A bracketed sequence of inlines, as one would use to begin
-a link, will be treated as a span with attributes if it is
-followed immediately by attributes:
-
-    [This is *some text*]{.class key="val"}
-
-Footnotes
----------
-
-#### Extension: `footnotes` ####
-
-Pandoc's Markdown allows footnotes, using the following syntax:
-
-    Here is a footnote reference,[^1] and another.[^longnote]
-
-    [^1]: Here is the footnote.
-
-    [^longnote]: Here's one with multiple blocks.
-
-        Subsequent paragraphs are indented to show that they
-    belong to the previous footnote.
-
-            { some.code }
-
-        The whole paragraph can be indented, or just the first
-        line.  In this way, multi-paragraph footnotes work like
-        multi-paragraph list items.
-
-    This paragraph won't be part of the note, because it
-    isn't indented.
-
-The identifiers in footnote references may not contain spaces, tabs,
-or newlines.  These identifiers are used only to correlate the
-footnote reference with the note itself; in the output, footnotes
-will be numbered sequentially.
-
-The footnotes themselves need not be placed at the end of the
-document.  They may appear anywhere except inside other block elements
-(lists, block quotes, tables, etc.).  Each footnote should be
-separated from surrounding content (including other footnotes)
-by blank lines.
-
-#### Extension: `inline_notes` ####
-
-Inline footnotes are also allowed (though, unlike regular notes,
-they cannot contain multiple paragraphs).  The syntax is as follows:
-
-    Here is an inline note.^[Inlines notes are easier to write, since
-    you don't have to pick an identifier and move down to type the
-    note.]
-
-Inline and regular footnotes may be mixed freely.
-
-Citations
----------
-
-#### Extension: `citations` ####
-
-Using an external filter, `pandoc-citeproc`, pandoc can automatically generate
-citations and a bibliography in a number of styles.  Basic usage is
-
-    pandoc --filter pandoc-citeproc myinput.txt
-
-In order to use this feature, you will need to specify a bibliography file
-using the `bibliography` metadata field in a YAML metadata section, or
-`--bibliography` command line argument. You can supply multiple `--bibliography`
-arguments or set `bibliography` metadata field to YAML array, if you want to
-use multiple bibliography files.  The bibliography may have any of these
-formats:
-
-  Format            File extension
-  ------------      --------------
-  BibLaTeX          .bib
-  BibTeX            .bibtex
-  Copac             .copac
-  CSL JSON          .json
-  CSL YAML          .yaml
-  EndNote           .enl
-  EndNote XML       .xml
-  ISI               .wos
-  MEDLINE           .medline
-  MODS              .mods
-  RIS               .ris
-
-Note that `.bib` can be used with both BibTeX and BibLaTeX files;
-use `.bibtex` to force BibTeX.
-
-Note that `pandoc-citeproc --bib2json` and `pandoc-citeproc --bib2yaml`
-can produce `.json` and `.yaml` files from any of the supported formats.
-
-In-field markup: In BibTeX and BibLaTeX databases, pandoc-citeproc parses
-a subset of LaTeX markup; in CSL YAML databases, pandoc Markdown; and in CSL JSON databases, an [HTML-like markup][CSL markup specs]:
-
-`<i>...</i>`
-:   italics
-
-`<b>...</b>`
-:   bold
-
-`<span style="font-variant:small-caps;">...</span>` or `<sc>...</sc>`
-:   small capitals
-
-`<sub>...</sub>`
-:   subscript
-
-`<sup>...</sup>`
-:   superscript
-
-`<span class="nocase">...</span>`
-:   prevent a phrase from being capitalized as title case
-
-`pandoc-citeproc -j` and `-y` interconvert the CSL JSON
-and CSL YAML formats as far as possible.
-
-As an alternative to specifying a bibliography file using `--bibliography`
-or the YAML metadata field `bibliography`, you can include
-the citation data directly in the `references` field of the
-document's YAML metadata. The field should contain an array of
-YAML-encoded references, for example:
-
-    ---
-    references:
-    - type: article-journal
-      id: WatsonCrick1953
-      author:
-      - family: Watson
-        given: J. D.
-      - family: Crick
-        given: F. H. C.
-      issued:
-        date-parts:
-        - - 1953
-          - 4
-          - 25
-      title: 'Molecular structure of nucleic acids: a structure for deoxyribose
-        nucleic acid'
-      title-short: Molecular structure of nucleic acids
-      container-title: Nature
-      volume: 171
-      issue: 4356
-      page: 737-738
-      DOI: 10.1038/171737a0
-      URL: http://www.nature.com/nature/journal/v171/n4356/abs/171737a0.html
-      language: en-GB
-    ...
-
-(`pandoc-citeproc --bib2yaml` can produce these from a bibliography file in one
-of the supported formats.)
-
-Citations and references can be formatted using any style supported by the
-[Citation Style Language], listed in the [Zotero Style Repository].
-These files are specified using the `--csl` option or the `csl` metadata field.
-By default, `pandoc-citeproc` will use the [Chicago Manual of Style] author-date
-format.  The CSL project provides further information on [finding and editing styles].
-
-To make your citations hyperlinks to the corresponding bibliography
-entries, add `link-citations: true` to your YAML metadata.
-
-Citations go inside square brackets and are separated by semicolons.
-Each citation must have a key, composed of '@' + the citation
-identifier from the database, and may optionally have a prefix,
-a locator, and a suffix.  The citation key must begin with a letter, digit,
-or `_`, and may contain alphanumerics, `_`, and internal punctuation
-characters (`:.#$%&-+?<>~/`).  Here are some examples:
-
-    Blah blah [see @doe99, pp. 33-35; also @smith04, chap. 1].
-
-    Blah blah [@doe99, pp. 33-35, 38-39 and *passim*].
-
-    Blah blah [@smith04; @doe99].
-
-`pandoc-citeproc` detects locator terms in the [CSL locale files].
-Either abbreviated or unabbreviated forms are accepted. In the `en-US`
-locale, locator terms can be written in either singular or plural forms,
-as `book`, `bk.`/`bks.`; `chapter`, `chap.`/`chaps.`; `column`,
-`col.`/`cols.`; `figure`, `fig.`/`figs.`; `folio`, `fol.`/`fols.`;
-`number`, `no.`/`nos.`; `line`, `l.`/`ll.`; `note`, `n.`/`nn.`; `opus`,
-`op.`/`opp.`; `page`, `p.`/`pp.`; `paragraph`, `para.`/`paras.`; `part`,
-`pt.`/`pts.`; `section`, `sec.`/`secs.`; `sub verbo`, `s.v.`/`s.vv.`;
-`verse`, `v.`/`vv.`; `volume`, `vol.`/`vols.`; `¶`/`¶¶`; `§`/`§§`. If no
-locator term is used, "page" is assumed.
-
-A minus sign (`-`) before the `@` will suppress mention of
-the author in the citation.  This can be useful when the
-author is already mentioned in the text:
-
-    Smith says blah [-@smith04].
-
-You can also write an in-text citation, as follows:
-
-    @smith04 says blah.
-
-    @smith04 [p. 33] says blah.
-
-If the style calls for a list of works cited, it will be placed
-at the end of the document.  Normally, you will want to end your
-document with an appropriate header:
-
-    last paragraph...
-
-    # References
-
-The bibliography will be inserted after this header.  Note that
-the `unnumbered` class will be added to this header, so that the
-section will not be numbered.
-
-If you want to include items in the bibliography without actually
-citing them in the body text, you can define a dummy `nocite` metadata
-field and put the citations there:
-
-    ---
-    nocite: |
-      @item1, @item2
-    ...
-
-    @item3
-
-In this example, the document will contain a citation for `item3`
-only, but the bibliography will contain entries for `item1`, `item2`, and
-`item3`.
-
-It is possible to create a bibliography with all the citations,
-whether or not they appear in the document, by using a wildcard:
-
-    ---
-    nocite: |
-      @*
-    ...
-
-For LaTeX or PDF output, you can also use [`natbib`] or [`biblatex`]
-to render bibliography. In order to do so, specify bibliography files as
-outlined above, and add `--natbib` or `--biblatex` argument to `pandoc`
-invocation. Bear in mind that bibliography files have to be in respective
-format (either BibTeX or BibLaTeX).
-
-For more information, see the [pandoc-citeproc man page].
-
-[CSL markup specs]: http://docs.citationstyles.org/en/1.0/release-notes.html#rich-text-markup-within-fields
-[Chicago Manual of Style]: http://chicagomanualofstyle.org
-[Citation Style Language]: http://citationstyles.org
-[Zotero Style Repository]: https://www.zotero.org/styles
-[finding and editing styles]: http://citationstyles.org/styles/
-[CSL locale files]: https://github.com/citation-style-language/locales
-[pandoc-citeproc man page]: https://github.com/jgm/pandoc-citeproc/blob/master/man/pandoc-citeproc.1.md
-
-Non-pandoc extensions
----------------------
-
-The following Markdown syntax extensions are not enabled by default
-in pandoc, but may be enabled by adding `+EXTENSION` to the format
-name, where `EXTENSION` is the name of the extension.  Thus, for
-example, `markdown+hard_line_breaks` is Markdown with hard line breaks.
-
-#### Extension: `old_dashes` ####
-
-Selects the pandoc <= 1.8.2.1 behavior for parsing smart dashes:
-`-` before a numeral is an en-dash, and `--` is an em-dash.
-This option only has an effect if `smart` is enabled. It is
-selected automatically for `textile` input.
-
-#### Extension: `angle_brackets_escapable` ####
-
-Allow `<` and `>` to be backslash-escaped, as they can be in
-GitHub flavored Markdown but not original Markdown.  This is
-implied by pandoc's default `all_symbols_escapable`.
-
-#### Extension: `lists_without_preceding_blankline` ####
-
-Allow a list to occur right after a paragraph, with no intervening
-blank space.
-
-#### Extension: `four_space_rule` ####
-
-Selects the pandoc <= 2.0 behavior for parsing lists, so that
-four spaces indent are needed for list item continuation
-paragraphs.
-
-#### Extension: `spaced_reference_links` ####
-
-Allow whitespace between the two components of a reference link,
-for example,
-
-    [foo] [bar].
-
-#### Extension: `hard_line_breaks` ####
-
-Causes all newlines within a paragraph to be interpreted as hard line
-breaks instead of spaces.
-
-#### Extension: `ignore_line_breaks` ####
-
-Causes newlines within a paragraph to be ignored, rather than being
-treated as spaces or as hard line breaks.  This option is intended for
-use with East Asian languages where spaces are not used between words,
-but text is divided into lines for readability.
-
-#### Extension: `east_asian_line_breaks` ####
-
-Causes newlines within a paragraph to be ignored, rather than
-being treated as spaces or as hard line breaks, when they occur
-between two East Asian wide characters.  This is a better choice
-than `ignore_line_breaks` for texts that include a mix of East
-Asian wide characters and other characters.
-
-#### Extension: `emoji` ####
-
-Parses textual emojis like `:smile:` as Unicode emoticons.
-
-#### Extension: `tex_math_single_backslash` ####
-
-Causes anything between `\(` and `\)` to be interpreted as inline
-TeX math, and anything between `\[` and `\]` to be interpreted
-as display TeX math.  Note: a drawback of this extension is that
-it precludes escaping `(` and `[`.
-
-#### Extension: `tex_math_double_backslash` ####
-
-Causes anything between `\\(` and `\\)` to be interpreted as inline
-TeX math, and anything between `\\[` and `\\]` to be interpreted
-as display TeX math.
-
-#### Extension: `markdown_attribute` ####
-
-By default, pandoc interprets material inside block-level tags as Markdown.
-This extension changes the behavior so that Markdown is only parsed
-inside block-level tags if the tags have the attribute `markdown=1`.
-
-#### Extension: `mmd_title_block` ####
-
-Enables a [MultiMarkdown] style title block at the top of
-the document, for example:
-
-    Title:   My title
-    Author:  John Doe
-    Date:    September 1, 2008
-    Comment: This is a sample mmd title block, with
-             a field spanning multiple lines.
-
-See the MultiMarkdown documentation for details.  If `pandoc_title_block` or
-`yaml_metadata_block` is enabled, it will take precedence over
-`mmd_title_block`.
-
-#### Extension: `abbreviations` ####
-
-Parses PHP Markdown Extra abbreviation keys, like
-
-    *[HTML]: Hypertext Markup Language
-
-Note that the pandoc document model does not support
-abbreviations, so if this extension is enabled, abbreviation keys are
-simply skipped (as opposed to being parsed as paragraphs).
-
-#### Extension: `autolink_bare_uris` ####
-
-Makes all absolute URIs into links, even when not surrounded by
-pointy braces `<...>`.
-
-#### Extension: `mmd_link_attributes` ####
-
-Parses multimarkdown style key-value attributes on link
-and image references. This extension should not be confused with the
-[`link_attributes`](#extension-link_attributes) extension.
-
-    This is a reference ![image][ref] with multimarkdown attributes.
-
-    [ref]: http://path.to/image "Image title" width=20px height=30px
-           id=myId class="myClass1 myClass2"
-
-#### Extension: `mmd_header_identifiers` ####
-
-Parses multimarkdown style header identifiers (in square brackets,
-after the header but before any trailing `#`s in an ATX header).
-
-#### Extension: `compact_definition_lists` ####
-
-Activates the definition list syntax of pandoc 1.12.x and earlier.
-This syntax differs from the one described above under [Definition lists]
-in several respects:
-
-  - No blank line is required between consecutive items of the
-    definition list.
-  - To get a "tight" or "compact" list, omit space between consecutive
-    items; the space between a term and its definition does not affect
-    anything.
-  - Lazy wrapping of paragraphs is not allowed:  the entire definition must
-    be indented four spaces.[^6]
-
-[^6]:  To see why laziness is incompatible with relaxing the requirement
-    of a blank line between items, consider the following example:
-
-        bar
-        :    definition
-        foo
-        :    definition
-
-    Is this a single list item with two definitions of "bar," the first of
-    which is lazily wrapped, or two list items?  To remove the ambiguity
-    we must either disallow lazy wrapping or require a blank line between
-    list items.
-
-Markdown variants
------------------
-
-In addition to pandoc's extended Markdown, the following Markdown
-variants are supported:
-
-`markdown_phpextra` (PHP Markdown Extra)
-:   `footnotes`, `pipe_tables`, `raw_html`, `markdown_attribute`,
-    `fenced_code_blocks`, `definition_lists`, `intraword_underscores`,
-    `header_attributes`, `link_attributes`, `abbreviations`,
-    `shortcut_reference_links`, `spaced_reference_links`.
-
-`markdown_github` (deprecated GitHub-Flavored Markdown)
-:   `pipe_tables`, `raw_html`, `fenced_code_blocks`, `gfm_auto_identifiers`,
-    `ascii_identifiers`, `backtick_code_blocks`, `autolink_bare_uris`,
-    `space_in_atx_header`, `intraword_underscores`, `strikeout`,
-    `emoji`, `shortcut_reference_links`, `angle_brackets_escapable`,
-    `lists_without_preceding_blankline`.
-
-`markdown_mmd` (MultiMarkdown)
-:   `pipe_tables`, `raw_html`, `markdown_attribute`, `mmd_link_attributes`,
-    `tex_math_double_backslash`, `intraword_underscores`,
-    `mmd_title_block`, `footnotes`, `definition_lists`,
-    `all_symbols_escapable`, `implicit_header_references`,
-    `auto_identifiers`, `mmd_header_identifiers`,
-    `shortcut_reference_links`, `implicit_figures`,
-    `superscript`, `subscript`, `backtick_code_blocks`,
-    `spaced_reference_links`, `raw_attribute`.
-
-`markdown_strict` (Markdown.pl)
-:   `raw_html`, `shortcut_reference_links`,
-    `spaced_reference_links`.
-
-We also support `commonmark` and `gfm` (GitHub-Flavored Markdown,
-which is implemented as a set of extensions on `commonmark`).
-
-Note, however, that `commonmark` and `gfm` have limited support
-for extensions. Only those  listed below (and `smart` and
-`raw_tex`) will work. The extensions can, however, all be
-individually disabled.
-Also, `raw_tex` only affects `gfm` output, not input.
-
-`gfm` (GitHub-Flavored Markdown)
-:   `pipe_tables`, `raw_html`, `fenced_code_blocks`, `auto_identifiers`,
-    `ascii_identifiers`, `backtick_code_blocks`, `autolink_bare_uris`,
-    `intraword_underscores`, `strikeout`, `hard_line_breaks`, `emoji`,
-    `shortcut_reference_links`, `angle_brackets_escapable`.
-
-Producing slide shows with pandoc
-=================================
-
-You can use pandoc to produce an HTML + JavaScript slide presentation
-that can be viewed via a web browser.  There are five ways to do this,
-using [S5], [DZSlides], [Slidy], [Slideous], or [reveal.js].
-You can also produce a PDF slide show using LaTeX [`beamer`], or
-slides shows in Microsoft [PowerPoint] format.
-
-Here's the Markdown source for a simple slide show, `habits.txt`:
-
-    % Habits
-    % John Doe
-    % March 22, 2005
-
-    # In the morning
-
-    ## Getting up
-
-    - Turn off alarm
-    - Get out of bed
-
-    ## Breakfast
-
-    - Eat eggs
-    - Drink coffee
-
-    # In the evening
-
-    ## Dinner
-
-    - Eat spaghetti
-    - Drink wine
-
-    ------------------
-
-    ![picture of spaghetti](images/spaghetti.jpg)
-
-    ## Going to sleep
-
-    - Get in bed
-    - Count sheep
-
-To produce an HTML/JavaScript slide show, simply type
-
-    pandoc -t FORMAT -s habits.txt -o habits.html
-
-where `FORMAT` is either `s5`, `slidy`, `slideous`, `dzslides`, or `revealjs`.
-
-For Slidy, Slideous, reveal.js, and S5, the file produced by pandoc with the
-`-s/--standalone` option embeds a link to JavaScript and CSS files, which are
-assumed to be available at the relative path `s5/default` (for S5), `slideous`
-(for Slideous), `reveal.js` (for reveal.js), or at the Slidy website at
-`w3.org` (for Slidy).  (These paths can be changed by setting the `slidy-url`,
-`slideous-url`, `revealjs-url`, or `s5-url` variables; see [Variables for slides],
-above.) For DZSlides, the (relatively short) JavaScript and CSS are included in
-the file by default.
-
-With all HTML slide formats, the `--self-contained` option can be used to
-produce a single file that contains all of the data necessary to display the
-slide show, including linked scripts, stylesheets, images, and videos.
-
-To produce a PDF slide show using beamer, type
-
-    pandoc -t beamer habits.txt -o habits.pdf
-
-Note that a reveal.js slide show can also be converted to a PDF
-by printing it to a file from the browser.
-
-To produce a Powerpoint slide show, type
-
-    pandoc habits.txt -o habits.pptx
-
-Structuring the slide show
---------------------------
-
-By default, the *slide level* is the highest header level in
-the hierarchy that is followed immediately by content, and not another
-header, somewhere in the document. In the example above, level 1 headers
-are always followed by level 2 headers, which are followed by content,
-so 2 is the slide level.  This default can be overridden using
-the `--slide-level` option.
-
-The document is carved up into slides according to the following
-rules:
-
-  * A horizontal rule always starts a new slide.
-
-  * A header at the slide level always starts a new slide.
-
-  * Headers *below* the slide level in the hierarchy create
-    headers *within* a slide.
-
-  * 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.
-
-  * A title page is constructed automatically from the document's title
-    block, if present.  (In the case of beamer, this can be disabled
-    by commenting out some lines in the default template.)
-
-These rules are designed to support many different styles of slide show. If
-you don't care about structuring your slides into sections and subsections,
-you can just use level 1 headers for all each slide. (In that case, level 1
-will be the slide level.) But you can also structure the slide show into
-sections, as in the example above.
-
-Note:  in reveal.js slide shows, if slide level is 2, a two-dimensional
-layout will be produced, with level 1 headers building horizontally
-and level 2 headers building vertically.  It is not recommended that
-you use deeper nesting of section levels with reveal.js.
-
-Incremental lists
------------------
-
-By default, these writers produce lists that display "all at once."
-If you want your lists to display incrementally (one item at a time),
-use the `-i` option. If you want a particular list to depart from the
-default (that is, to display incrementally without the `-i` option and
-all at once with the `-i` option), put it in a block quote:
-
-    > - Eat spaghetti
-    > - Drink wine
-
-In this way incremental and nonincremental lists can be mixed in
-a single document.
-
-Inserting pauses
-----------------
-
-You can add "pauses" within a slide by including a paragraph containing
-three dots, separated by spaces:
-
-    # Slide with a pause
-
-    content before the pause
-
-    . . .
-
-    content after the pause
-
-Styling the slides
-------------------
-
-You can change the style of HTML slides by putting customized CSS files
-in `$DATADIR/s5/default` (for S5), `$DATADIR/slidy` (for Slidy),
-or `$DATADIR/slideous` (for Slideous),
-where `$DATADIR` is the user data directory (see `--data-dir`, above).
-The originals may be found in pandoc's system data directory (generally
-`$CABALDIR/pandoc-VERSION/s5/default`). Pandoc will look there for any
-files it does not find in the user data directory.
-
-For dzslides, the CSS is included in the HTML file itself, and may
-be modified there.
-
-All [reveal.js configuration options] can be set through variables.
-For example, themes can be used by setting the `theme` variable:
-
-    -V theme=moon
-
-Or you can specify a custom stylesheet using the `--css` option.
-
-To style beamer slides, you can specify a `theme`, `colortheme`,
-`fonttheme`, `innertheme`, and `outertheme`, using the `-V` option:
-
-    pandoc -t beamer habits.txt -V theme:Warsaw -o habits.pdf
-
-Note that header attributes will turn into slide attributes
-(on a `<div>` or `<section>`) in HTML slide formats, allowing you
-to style individual slides.  In beamer, the only header attribute
-that affects slides is the `allowframebreaks` class, which sets the
-`allowframebreaks` option, causing multiple slides to be created
-if the content overfills the frame.  This is recommended especially for
-bibliographies:
-
-    # References {.allowframebreaks}
-
-Speaker notes
--------------
-
-reveal.js has good support for speaker notes.  You can add notes to your
-Markdown document thus:
-
-    ::: notes
-
-    This is my note.
-
-    - It can contain Markdown
-    - like this list
-
-    :::
-
-To show the notes window, press `s` while viewing the presentation.
-Notes are not yet supported for other slide formats, but the notes
-will not appear on the slides themselves.
-
-Columns
--------
-
-To put material in side by side columns, you can use a native
-div container with class `columns`, containing two or more div
-containers with class `column` and a `width` attribute:
-
-    :::::::::::::: {.columns}
-    ::: {.column width="40%"}
-    contents...
-    :::
-    ::: {.column width="60%"}
-    contents...
-    :::
-    ::::::::::::::
-
-Frame attributes in beamer
---------------------------
-
-Sometimes it is necessary to add the LaTeX `[fragile]` option to
-a frame in beamer (for example, when using the `minted` environment).
-This can be forced by adding the `fragile` class to the header
-introducing the slide:
-
-    # Fragile slide {.fragile}
-
-All of the other frame attributes described in Section 8.1 of
-the [Beamer User's Guide] may also be used: `allowdisplaybreaks`,
-`allowframebreaks`, `b`, `c`, `t`, `environment`, `label`, `plain`,
-`shrink`.
-
-Creating EPUBs with pandoc
-==========================
-
-EPUB Metadata
--------------
-
-EPUB metadata may be specified using the `--epub-metadata` option, but
-if the source document is Markdown, it is better to use a [YAML metadata
-block][Extension: `yaml_metadata_block`].  Here is an example:
-
-    ---
-    title:
-    - type: main
-      text: My Book
-    - type: subtitle
-      text: An investigation of metadata
-    creator:
-    - role: author
-      text: John Smith
-    - role: editor
-      text: Sarah Jones
-    identifier:
-    - scheme: DOI
-      text: doi:10.234234.234/33
-    publisher:  My Press
-    rights: © 2007 John Smith, CC BY-NC
-    ibooks:
-      version: 1.3.4
-    ...
-
-The following fields are recognized:
-
-`identifier`
-  ~ Either a string value or an object with fields `text` and
-    `scheme`.  Valid values for `scheme` are `ISBN-10`,
-    `GTIN-13`, `UPC`, `ISMN-10`, `DOI`, `LCCN`, `GTIN-14`,
-    `ISBN-13`, `Legal deposit number`, `URN`, `OCLC`,
-    `ISMN-13`, `ISBN-A`, `JP`, `OLCC`.
-
-`title`
-  ~ Either a string value, or an object with fields `file-as` and
-    `type`, or a list of such objects.  Valid values for `type` are
-    `main`, `subtitle`, `short`, `collection`, `edition`, `extended`.
-
-`creator`
-  ~ Either a string value, or an object with fields `role`, `file-as`,
-    and `text`, or a list of such objects.  Valid values for `role` are
-    [MARC relators], but
-    pandoc will attempt to translate the human-readable versions
-    (like "author" and "editor") to the appropriate marc relators.
-
-`contributor`
-  ~ Same format as `creator`.
-
-`date`
-  ~ A string value in `YYYY-MM-DD` format.  (Only the year is necessary.)
-    Pandoc will attempt to convert other common date formats.
-
-`lang` (or legacy: `language`)
-  ~ A string value in [BCP 47] format.  Pandoc will default to the local
-    language if nothing is specified.
-
-`subject`
-  ~ A string value or a list of such values.
-
-`description`
-  ~ A string value.
-
-`type`
-  ~ A string value.
-
-`format`
-  ~ A string value.
-
-`relation`
-  ~ A string value.
-
-`coverage`
-  ~ A string value.
-
-`rights`
-  ~ A string value.
-
-`cover-image`
-  ~ A string value (path to cover image).
-
-`stylesheet`
-  ~ A string value (path to CSS stylesheet).
-
-`page-progression-direction`
-  ~ Either `ltr` or `rtl`. Specifies the `page-progression-direction`
-    attribute for the [`spine` element].
-
-`ibooks`
-  ~ iBooks-specific metadata, with the following fields:
-
-    - `version`: (string)
-    - `specified-fonts`: `true`|`false` (default `false`)
-    - `ipad-orientation-lock`: `portrait-only`|`landscape-only`
-    - `iphone-orientation-lock`: `portrait-only`|`landscape-only`
-    - `binding`: `true`|`false` (default `true`)
-    - `scroll-axis`: `vertical`|`horizontal`|`default`
-
-[MARC relators]: http://loc.gov/marc/relators/relaterm.html
-[`spine` element]: http://idpf.org/epub/301/spec/epub-publications.html#sec-spine-elem
-
-Linked media
-------------
-
-By default, pandoc will download linked media (including audio and
-video) and include it in the EPUB container, yielding a completely
-self-contained EPUB.  If you want to link to external media resources
-instead, use raw HTML in your source and add `data-external="1"` to the tag
-with the `src` attribute.  For example:
-
-    <audio controls="1">
-      <source src="http://example.com/music/toccata.mp3"
-              data-external="1" type="audio/mpeg">
-      </source>
-    </audio>
-
-Syntax highlighting
-===================
-
-Pandoc will automatically highlight syntax in [fenced code blocks] that
-are marked with a language name.  The Haskell library [skylighting] is
-used for highlighting, which works in HTML, Docx, Ms, and LaTeX/PDF output.
-To see a list of language names that pandoc will recognize, type
-`pandoc --list-highlight-languages`.
-
-The color scheme can be selected using the `--highlight-style` option.
-The default color scheme is `pygments`, which imitates the default color
-scheme used by the Python library pygments (though pygments is not actually
-used to do the highlighting).  To see a list of highlight styles,
-type `pandoc --list-highlight-styles`.
-
-To disable highlighting, use the `--no-highlight` option.
-
-[skylighting]: https://github.com/jgm/skylighting
-
-Custom Styles in Docx Output
-============================
-
-By default, pandoc's docx 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.
-
-If the styles are not yet in your reference.docx, they will be defined
-in the output file as inheriting from normal text. 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
-==============
-
-Pandoc can be extended with custom writers written in [lua].  (Pandoc
-includes a lua interpreter, so lua need not be installed separately.)
-
-To use a custom writer, simply specify the path to the lua script
-in place of the output format. For example:
-
-    pandoc -t data/sample.lua
-
-Creating a custom writer requires writing a lua function for each
-possible element in a pandoc document.  To get a documented example
-which you can modify according to your needs, do
-
-    pandoc --print-default-data-file sample.lua
-
-[lua]: http://www.lua.org
-
-Authors
-=======
-
-Copyright 2006-2017 John MacFarlane (jgm@berkeley.edu). Released
-under the [GPL], version 2 or greater.  This software carries no
-warranty of any kind.  (See COPYRIGHT for full copyright and
-warranty notices.) For a full list of contributors, see the file
-AUTHORS.md in the pandoc source code.
-
-[GPL]: http://www.gnu.org/copyleft/gpl.html "GNU General Public License"
+---
+title: Pandoc User's Guide
+author: John MacFarlane
+date: 2026-06-03
+---
+
+# Synopsis
+
+`pandoc` [*options*] [*input-file*]...
+
+# Description
+
+Pandoc is a [Haskell] library for converting from one markup format to
+another, and a command-line tool that uses this library.
+
+Pandoc can convert between numerous markup and word processing formats,
+including, but not limited to, various flavors of [Markdown], [HTML],
+[LaTeX] and [Word docx]. For the full lists of input and output formats,
+see the `--from` and `--to` [options below][General options].
+Pandoc can also produce [PDF] output: see [creating a PDF], below.
+
+Pandoc's enhanced version of Markdown includes syntax for [tables],
+[definition lists], [metadata blocks], [footnotes], [citations], [math],
+and much more.  See below under [Pandoc's Markdown].
+
+Pandoc has a modular design: it consists of a set of readers, which parse
+text in a given format and produce a native representation of the document
+(an _abstract syntax tree_ or AST), and a set of writers, which convert
+this native representation into a target format. Thus, adding an input
+or output format requires only adding a reader or writer. Users can also
+run custom [pandoc filters] to modify the intermediate AST.
+
+Because pandoc's intermediate representation of a document is less
+expressive than many of the formats it converts between, one should
+not expect perfect conversions between every format and every other.
+Pandoc attempts to preserve the structural elements of a document, but
+not formatting details such as margin size.  And some document elements,
+such as complex tables, may not fit into pandoc's simple document
+model.  While conversions from pandoc's Markdown to all formats aspire
+to be perfect, conversions from formats more expressive than pandoc's
+Markdown can be expected to be lossy.
+
+## Using pandoc
+
+If no *input-files* are specified, input is read from *stdin*.
+Output goes to *stdout* by default. For output to a file,
+use the `-o`/`--output` option:
+
+    pandoc -o output.html input.txt
+
+By default, pandoc produces a document fragment. To produce a standalone
+document (e.g. a valid HTML file including `<head>` and `<body>`),
+use the `-s` or `--standalone` flag:
+
+    pandoc -s -o output.html input.txt
+
+For more information on how standalone documents are produced, see
+[Templates] below.
+
+If multiple input files are given, pandoc will concatenate them all (with
+blank lines between them) before parsing. (Use `--file-scope` to parse files
+individually.)
+
+## Specifying formats
+
+The format of the input and output can be specified explicitly using
+command-line options.  The input format can be specified using the
+`-f/--from` option, the output format using the `-t/--to` option.
+Thus, to convert `hello.txt` from Markdown to LaTeX, you could type:
+
+    pandoc -f markdown -t latex hello.txt
+
+To convert `hello.html` from HTML to Markdown:
+
+    pandoc -f html -t markdown hello.html
+
+Supported input and output formats are listed below under [Options]
+(see `-f` for input formats and `-t` for output formats).  You
+can also use `pandoc --list-input-formats` and
+`pandoc --list-output-formats` to print lists of supported
+formats.
+
+If the input or output format is not specified explicitly, pandoc
+will attempt to guess it from the extensions of the filenames.
+Thus, for example,
+
+    pandoc -o hello.tex hello.txt
+
+will convert `hello.txt` from Markdown to LaTeX.  If no output file
+is specified (so that output goes to *stdout*), or if the output file's
+extension is unknown, the output format will default to HTML.
+If no input file is specified (so that input comes from *stdin*), or
+if the input files' extensions are unknown, the input format will
+be assumed to be Markdown.
+
+## Character encoding
+
+Pandoc uses the UTF-8 character encoding for both input and output.
+If your local character encoding is not UTF-8, you
+should pipe input and output through [`iconv`]:
+
+    iconv -t utf-8 input.txt | pandoc | iconv -f utf-8
+
+Note that in some output formats (such as HTML, LaTeX, ConTeXt,
+RTF, OPML, DocBook, and Texinfo), information about
+the character encoding is included in the document header, which
+will only be included if you use the `-s/--standalone` option.
+
+[`iconv`]: https://www.gnu.org/software/libiconv/
+
+## Creating a PDF
+
+To produce a PDF, specify an output file with a `.pdf` extension:
+
+    pandoc test.txt -o test.pdf
+
+By default, pandoc will use LaTeX to create the PDF, which requires
+that a LaTeX engine be installed (see `--pdf-engine` below).
+Alternatively, pandoc can use ConTeXt, roff ms, or HTML as an
+intermediate format.  To do this, specify an output file with a
+`.pdf` extension, as before, but add the `--pdf-engine` option
+or `-t context`, `-t html`, or `-t ms` to the command line.
+The tool used to generate the PDF from the intermediate format
+may be specified using `--pdf-engine`.
+
+You can control the PDF style using variables, depending on
+the intermediate format used: see [variables for LaTeX],
+[variables for ConTeXt], [variables for `wkhtmltopdf`],
+[variables for ms].  When HTML is used as an intermediate
+format, the output can be styled using `--css`.
+
+To debug the PDF creation, it can be useful to look at the intermediate
+representation: instead of `-o test.pdf`, use for example `-s -o test.tex`
+to output the generated LaTeX. You can then test it with `pdflatex test.tex`.
+
+When using LaTeX, the following packages need to be available
+(they are included with all recent versions of [TeX Live]):
+[`amsfonts`], [`amsmath`], [`lm`], [`unicode-math`],
+[`iftex`], [`listings`] (if the
+`--listings` option is used), [`fancyvrb`], [`longtable`],
+[`booktabs`], [`multirow`] (if the document contains a table with
+cells that cross multiple rows), [`graphicx`] (if the document
+contains images), [`bookmark`], [`xcolor`],
+[`soul`], [`geometry`] (with the `geometry` variable set),
+[`setspace`] (with `linestretch`), and
+[`babel`] (with `lang`).  If `CJKmainfont` is set, [`xeCJK`]
+is needed if `xelatex` is used, else [`luatexja`] is needed if
+`lualatex` is used. [`framed`] is required if code is highlighted in a
+scheme that use a colored background. The use of `xelatex` or
+`lualatex` as the PDF engine requires [`fontspec`]. `lualatex`
+uses [`selnolig`] and [`lua-ul`]. `xelatex` uses [`bidi`] (with
+the `dir` variable set).
+If the `mathspec` variable is set, `xelatex` will use [`mathspec`]
+instead of [`unicode-math`].  The [`csquotes`] package will be used
+for [typography] if the `csquotes` variable or metadata field is
+set to a true value.  The [`natbib`], [`biblatex`], [`bibtex`],
+and [`biber`] packages can optionally be used for [citation
+rendering].  If math with `\cancel`, `\bcancel`, or `\xcancel`
+is used, the [`cancel`] package is needed.
+The following packages will be used to improve
+output quality if present, but pandoc does not require them to
+be present: [`upquote`] (for straight quotes in verbatim
+environments), [`microtype`] (for better spacing adjustments),
+[`parskip`] (for better inter-paragraph spaces), [`xurl`] (for
+better line breaks in URLs), and [`footnotehyper`] or
+[`footnote`] (to allow footnotes in tables).
+
+[TeX Live]: https://www.tug.org/texlive/
+[`amsfonts`]: https://ctan.org/pkg/amsfonts
+[`amsmath`]: https://ctan.org/pkg/amsmath
+[`babel`]: https://ctan.org/pkg/babel
+[`biber`]: https://ctan.org/pkg/biber
+[`biblatex`]: https://ctan.org/pkg/biblatex
+[`bibtex`]: https://ctan.org/pkg/bibtex
+[`bidi`]: https://ctan.org/pkg/bidi
+[`bookmark`]: https://ctan.org/pkg/bookmark
+[`booktabs`]: https://ctan.org/pkg/booktabs
+[`csquotes`]: https://ctan.org/pkg/csquotes
+[`fancyvrb`]: https://ctan.org/pkg/fancyvrb
+[`fontspec`]: https://ctan.org/pkg/fontspec
+[`footnote`]: https://ctan.org/pkg/footnote
+[`footnotehyper`]: https://ctan.org/pkg/footnotehyper
+[`framed`]: https://ctan.org/pkg/framed
+[`geometry`]: https://ctan.org/pkg/geometry
+[`graphicx`]: https://ctan.org/pkg/graphicx
+[`cancel`]: https://ctan.org/pkg/cancel
+[`hyperref`]: https://ctan.org/pkg/hyperref
+[`iftex`]: https://ctan.org/pkg/iftex
+[`listings`]: https://ctan.org/pkg/listings
+[`lm`]: https://ctan.org/pkg/lm
+[`lua-ul`]: https://ctan.org/pkg/lua-ul
+[`luatexja`]: https://ctan.org/pkg/luatexja
+[`longtable`]: https://ctan.org/pkg/longtable
+[`mathspec`]: https://ctan.org/pkg/mathspec
+[`microtype`]: https://ctan.org/pkg/microtype
+[`multirow`]: https://ctan.org/pkg/multirow
+[`natbib`]: https://ctan.org/pkg/natbib
+[`parskip`]: https://ctan.org/pkg/parskip
+[`polyglossia`]: https://ctan.org/pkg/polyglossia
+[`prince`]: https://www.princexml.com/
+[`setspace`]: https://ctan.org/pkg/setspace
+[`soul`]: https://ctan.org/pkg/soul
+[`unicode-math`]: https://ctan.org/pkg/unicode-math
+[`upquote`]: https://ctan.org/pkg/upquote
+[`weasyprint`]: https://weasyprint.org
+[`wkhtmltopdf`]: https://wkhtmltopdf.org
+[`xcolor`]: https://ctan.org/pkg/xcolor
+[`xeCJK`]: https://ctan.org/pkg/xecjk
+[`xurl`]: https://ctan.org/pkg/xurl
+[`selnolig`]: https://ctan.org/pkg/selnolig
+
+
+
+## Reading from the Web
+
+Instead of an input file, an absolute URI may be given. In this case
+pandoc will fetch the content using HTTP:
+
+    pandoc -f html -t markdown https://www.fsf.org
+
+It is possible to supply a custom User-Agent string or other
+header when requesting a document from a URL:
+
+    pandoc -f html -t markdown --request-header User-Agent:"Mozilla/5.0" \
+      https://www.fsf.org
+
+# Options
+
+## General options {.options}
+
+`-f` *FORMAT*, `-r` *FORMAT*, `--from=`*FORMAT*, `--read=`*FORMAT*
+
+:   Specify input format.  *FORMAT* can be:
+
+    ::: {#input-formats}
+    - `asciidoc` ([AsciiDoc] markup)
+    - `bibtex` ([BibTeX] bibliography)
+    - `biblatex` ([BibLaTeX] bibliography)
+    - `bits` ([BITS] XML, alias for `jats`)
+    - `commonmark` ([CommonMark] Markdown)
+    - `commonmark_x` ([CommonMark] Markdown with extensions)
+    - `creole` ([Creole 1.0])
+    - `csljson` ([CSL JSON] bibliography)
+    - `csv` ([CSV] table)
+    - `tsv` ([TSV] table)
+    - `djot` ([Djot markup])
+    - `docbook` ([DocBook])
+    - `docx` ([Word docx])
+    - `dokuwiki` ([DokuWiki markup])
+    - `endnotexml` ([EndNote XML bibliography])
+    - `epub` ([EPUB])
+    - `fb2` ([FictionBook2] e-book)
+    - `gfm` ([GitHub-Flavored Markdown]),
+      or the deprecated and less accurate `markdown_github`;
+      use [`markdown_github`](#markdown-variants) only
+      if you need extensions not supported in [`gfm`](#markdown-variants).
+    - `haddock` ([Haddock markup])
+    - `html` ([HTML])
+    - `ipynb` ([Jupyter notebook])
+    - `jats` ([JATS] XML)
+    - `jira` ([Jira]/Confluence wiki markup)
+    - `json` (JSON version of native AST)
+    - `latex` ([LaTeX])
+    - `markdown` ([Pandoc's Markdown])
+    - `markdown_mmd` ([MultiMarkdown])
+    - `markdown_phpextra` ([PHP Markdown Extra])
+    - `markdown_strict` (original unextended [Markdown])
+    - `mediawiki` ([MediaWiki markup])
+    - `man` ([roff man])
+    - `mdoc` ([mdoc] manual page markup)
+    - `muse` ([Muse])
+    - `native` (native Haskell)
+    - `odt` ([OpenDocument text document][ODT])
+    - `opml` ([OPML])
+    - `org` ([Emacs Org mode])
+    - `pod` (Perl's [Plain Old Documentation])
+    - `pptx` ([PowerPoint])
+    - `ris` ([RIS] bibliography)
+    - `rtf` ([Rich Text Format])
+    - `rst` ([reStructuredText])
+    - `t2t` ([txt2tags])
+    - `textile` ([Textile])
+    - `tikiwiki` ([TikiWiki markup])
+    - `twiki` ([TWiki markup])
+    - `typst` ([typst])
+    - `vimwiki` ([Vimwiki])
+    - `xlsx` ([Excel spreadsheet][XLSX])
+    - `xml` (XML version of native AST)
+    - the path of a custom Lua reader, see [Custom readers and writers] below
+    :::
+
+    Extensions can be individually enabled or disabled by
+    appending `+EXTENSION` or `-EXTENSION` to the format name.
+    See [Extensions] below, for a list of extensions and
+    their names.  See `--list-input-formats` and `--list-extensions`,
+    below.
+
+`-t` *FORMAT*, `-w` *FORMAT*, `--to=`*FORMAT*, `--write=`*FORMAT*
+
+:   Specify output format.  *FORMAT* can be:
+
+    ::: {#output-formats}
+    - `ansi` (text with [ANSI escape codes], for terminal viewing)
+    - `asciidoc` (modern [AsciiDoc] as interpreted by [AsciiDoctor])
+    - `asciidoc_legacy` ([AsciiDoc] as interpreted by [`asciidoc-py`]).
+    - `asciidoctor` (deprecated synonym for `asciidoc`)
+    - `bbcode` [BBCode]
+    - `bbcode_fluxbb` [BBCode (FluxBB)]
+    - `bbcode_phpbb` [BBCode (phpBB)]
+    - `bbcode_steam` [BBCode (Steam)]
+    - `bbcode_hubzilla` [BBCode (Hubzilla)]
+    - `bbcode_xenforo` [BBCode (xenForo)]
+    - `beamer` ([LaTeX beamer][`beamer`] slide show)
+    - `bibtex` ([BibTeX] bibliography)
+    - `biblatex` ([BibLaTeX] bibliography)
+    - `chunkedhtml` (zip archive of multiple linked HTML files)
+    - `commonmark` ([CommonMark] Markdown)
+    - `commonmark_x` ([CommonMark] Markdown with extensions)
+    - `context` ([ConTeXt])
+    - `csljson` ([CSL JSON] bibliography)
+    - `djot` ([Djot markup])
+    - `docbook` or `docbook4` ([DocBook] 4)
+    - `docbook5` (DocBook 5)
+    - `docx` ([Word docx])
+    - `dokuwiki` ([DokuWiki markup])
+    - `epub` or `epub3` ([EPUB] v3 book)
+    - `epub2` (EPUB v2)
+    - `fb2` ([FictionBook2] e-book)
+    - `gfm` ([GitHub-Flavored Markdown]),
+      or the deprecated and less accurate `markdown_github`;
+      use [`markdown_github`](#markdown-variants) only
+      if you need extensions not supported in [`gfm`](#markdown-variants).
+    - `haddock` ([Haddock markup])
+    - `html` or `html5` ([HTML], i.e. [HTML5]/XHTML [polyglot markup])
+    - `html4` ([XHTML] 1.0 Transitional)
+    - `icml` ([InDesign ICML])
+    - `ipynb` ([Jupyter notebook])
+    - `jats_archiving` ([JATS] XML, Archiving and Interchange Tag Set)
+    - `jats_articleauthoring` ([JATS] XML, Article Authoring Tag Set)
+    - `jats_publishing` ([JATS] XML, Journal Publishing Tag Set)
+    - `jats` (alias for `jats_archiving`)
+    - `jira` ([Jira]/Confluence wiki markup)
+    - `json` (JSON version of native AST)
+    - `latex` ([LaTeX])
+    - `man` ([roff man])
+    - `markdown` ([Pandoc's Markdown])
+    - `markdown_mmd` ([MultiMarkdown])
+    - `markdown_phpextra` ([PHP Markdown Extra])
+    - `markdown_strict` (original unextended [Markdown])
+    - `markua` ([Markua])
+    - `mediawiki` ([MediaWiki markup])
+    - `ms` ([roff ms])
+    - `muse` ([Muse])
+    - `native` (native Haskell)
+    - `odt` ([OpenDocument text document][ODT])
+    - `opml` ([OPML])
+    - `opendocument` ([OpenDocument XML])
+    - `org` ([Emacs Org mode])
+    - `pdf` ([PDF])
+    - `plain` (plain text)
+    - `pptx` ([PowerPoint] slide show)
+    - `rst` ([reStructuredText])
+    - `rtf` ([Rich Text Format])
+    - `texinfo` ([GNU Texinfo])
+    - `textile` ([Textile])
+    - `slideous` ([Slideous] HTML and JavaScript slide show)
+    - `slidy` ([Slidy] HTML and JavaScript slide show)
+    - `dzslides` ([DZSlides] HTML5 + JavaScript slide show)
+    - `revealjs` ([reveal.js] HTML5 + JavaScript slide show)
+    - `s5` ([S5] HTML and JavaScript slide show)
+    - `tei` ([TEI Simple])
+    - `typst` ([typst])
+    - `vimdoc` ([Vimdoc])
+    - `xml` (XML version of native AST)
+    - `xwiki` ([XWiki markup])
+    - `zimwiki` ([ZimWiki markup])
+    - the path of a custom Lua writer, see [Custom readers and writers] below
+    :::
+
+    Note that `odt`, `docx`, `epub`, and `pdf` output will not be directed
+    to *stdout* unless forced with `-o -`.
+
+    Extensions can be individually enabled or
+    disabled by appending `+EXTENSION` or `-EXTENSION` to the format
+    name.  See [Extensions] below, for a list of extensions and their
+    names.  See `--list-output-formats` and `--list-extensions`, below.
+
+`-o` *FILE*, `--output=`*FILE*
+
+:   Write output to *FILE* instead of *stdout*.  If *FILE* is
+    `-`, output will go to *stdout*, even if a non-textual format
+    (`docx`, `odt`, `epub2`, `epub3`) is specified.  If the
+    output format is `chunkedhtml` and *FILE* has no extension,
+    then instead of producing a `.zip` file pandoc will create
+    a directory *FILE* and unpack the zip archive there
+    (unless *FILE* already exists, in which case an error
+    will be raised).
+
+`--data-dir=`*DIRECTORY*
+
+:   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.  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 and
+    `$HOME/.pandoc` exists, it will be used (for backwards compatibility).
+    On Windows the default user data directory is `%APPDATA%\pandoc`.
+    You can find the default user data directory on your system by
+    looking at the output of `pandoc --version`.
+    Data files placed in this directory (for example, `reference.odt`,
+    `reference.docx`, `epub.css`, `templates`) will override
+    pandoc's normal defaults.  (Note that the user data directory
+    is not created by pandoc, so you will need to create it yourself
+    if you want to make use of it.)
+
+`-d` *FILE*, `--defaults=`*FILE*
+
+:   Specify a set of default option settings.  *FILE* is a YAML or JSON
+    file whose fields correspond to command-line option
+    settings.  All options for document conversion, including input
+    and output files, can be set using a defaults file.  The file will
+    be searched for first in the working directory, and then in
+    the `defaults` subdirectory of the user data directory
+    (see `--data-dir`).  The `.yaml` extension will be added if
+    *FILE* lacs an extension. See the section [Defaults files]
+    for more information on the file format. Settings from the
+    defaults file may be overridden or extended by subsequent
+    options on the command line.
+
+`--bash-completion`
+
+:   Generate a bash completion script.  To enable bash completion
+    with pandoc, add this to your `.bashrc`:
+
+        eval "$(pandoc --bash-completion)"
+
+`--sandbox[=true|false]`
+
+:   Run pandoc in a sandbox, limiting IO operations in readers
+    and writers to reading the files specified on the command line.
+    Note that this option does not limit IO operations by
+    filters or in the production of PDF documents.  But it does
+    offer security against, for example, disclosure of files
+    through the use of `include` directives.  Anyone using
+    pandoc on untrusted user input should use this option.
+
+    Note: some readers and writers (e.g., `docx`) need access to data
+    files.  If these are stored on the file system, then pandoc
+    will not be able to find them when run in `--sandbox` mode
+    and will raise an error. For these applications, we
+    recommend using a pandoc binary compiled with the `embed_data_files`
+    option, which causes the data files to be baked into the binary
+    instead of being stored on the file system.
+
+`--verbose`
+
+:   Give verbose debugging output.
+
+`--quiet`
+
+:   Suppress warning messages.
+
+`--fail-if-warnings[=true|false]`
+
+:   Exit with error status if there are any warnings.
+
+`--log=`*FILE*
+
+:   Write log messages in machine-readable JSON format to
+    *FILE*.  All messages above DEBUG level will be written,
+    regardless of verbosity settings (`--verbose`, `--quiet`).
+
+`--list-input-formats`
+
+:   List supported input formats, one per line.
+
+`--list-output-formats`
+
+:   List supported output formats, one per line.
+
+`--list-extensions`[`=`*FORMAT*]
+
+:   List supported extensions for *FORMAT*, one per line, preceded
+    by a `+` or `-` indicating whether it is enabled by default
+    in *FORMAT*. If *FORMAT* is not specified, defaults for
+    pandoc's Markdown are given.
+
+`--list-highlight-languages`
+
+:   List supported languages for syntax highlighting, one per
+    line.
+
+`--list-highlight-styles`
+
+:   List supported styles for syntax highlighting, one per line.
+    See `--syntax-highlighting`.
+
+`-v`, `--version`
+
+:   Print version.
+
+`-h`, `--help`
+
+:   Show usage message.
+
+[ANSI escape codes]: https://en.wikipedia.org/wiki/ANSI_escape_code
+[Markdown]: https://daringfireball.net/projects/markdown/
+[CommonMark]: https://commonmark.org
+[PHP Markdown Extra]: https://michelf.ca/projects/php-markdown/extra/
+[GitHub-Flavored Markdown]: https://help.github.com/articles/github-flavored-markdown/
+[MultiMarkdown]: https://fletcherpenney.net/multimarkdown/
+[reStructuredText]: https://docutils.sourceforge.io/docs/ref/rst/introduction.html
+[S5]: https://meyerweb.com/eric/tools/s5/
+[Slidy]: https://www.w3.org/Talks/Tools/Slidy2/
+[Slideous]: https://goessner.net/articles/slideous/
+[HTML]: https://www.w3.org/html/
+[HTML5]: https://html.spec.whatwg.org/
+[polyglot markup]: https://www.w3.org/TR/html-polyglot/
+[XHTML]: https://www.w3.org/TR/xhtml1/
+[LaTeX]: https://www.latex-project.org/
+[`beamer`]: https://ctan.org/pkg/beamer
+[Beamer User's Guide]: http://mirrors.ctan.org/macros/latex/contrib/beamer/doc/beameruserguide.pdf
+[ConTeXt]: https://www.contextgarden.net/
+[Rich Text Format]: https://en.wikipedia.org/wiki/Rich_Text_Format
+[DocBook]: https://docbook.org
+[Djot markup]: https://djot.net
+[JATS]: https://jats.nlm.nih.gov
+[BITS]: https://jats.nlm.nih.gov/extensions/bits/
+[Jira]: https://jira.atlassian.com/secure/WikiRendererHelpAction.jspa?section=all
+[txt2tags]: https://txt2tags.org
+[EPUB]: http://idpf.org/epub
+[OPML]: https://opml.org/spec2.opml
+[OpenDocument XML]: https://www.oasis-open.org/2021/06/16/opendocument-v1-3-oasis-standard-published/
+[ODT]: https://en.wikipedia.org/wiki/OpenDocument
+[Plain Old Documentation]: https://perldoc.perl.org/perlpod
+[Textile]: https://textile-lang.com
+[MediaWiki markup]: https://www.mediawiki.org/wiki/Help:Formatting
+[DokuWiki markup]: https://www.dokuwiki.org/dokuwiki
+[ZimWiki markup]: https://zim-wiki.org/manual/Help/Wiki_Syntax.html
+[XWiki markup]: https://www.xwiki.org/xwiki/bin/view/Documentation/UserGuide/Features/XWikiSyntax/
+[XLSX]: https://en.wikipedia.org/wiki/Microsoft_Excel#File_formats
+[Vimdoc]: https://vimhelp.org/helphelp.txt.html#help-writing
+[TWiki markup]: https://twiki.org/cgi-bin/view/TWiki/TextFormattingRules
+[TikiWiki markup]: https://doc.tiki.org/Wiki-Syntax-Text#The_Markup_Language_Wiki-Syntax
+[Haddock markup]: https://www.haskell.org/haddock/doc/html/ch03s08.html
+[Creole 1.0]: http://www.wikicreole.org/wiki/Creole1.0
+[CSV]: https://tools.ietf.org/html/rfc4180
+[TSV]: https://www.iana.org/assignments/media-types/text/tab-separated-values
+[roff man]: https://man.cx/groff_man(7)
+[roff ms]: https://man.cx/groff_ms(7)
+[Haskell]: https://www.haskell.org
+[GNU Texinfo]: https://www.gnu.org/software/texinfo/
+[RIS]: https://en.wikipedia.org/wiki/RIS_(file_format)
+[Emacs Org mode]: https://orgmode.org
+[AsciiDoc]: https://asciidoc.org/
+[AsciiDoctor]: https://asciidoctor.org/
+[`asciidoc-py`]: https://github.com/asciidoc-py/asciidoc-py
+[DZSlides]: https://paulrouget.com/dzslides/
+[Word docx]: https://en.wikipedia.org/wiki/Office_Open_XML
+[PDF]: https://www.adobe.com/pdf/
+[reveal.js]: https://revealjs.com/
+[FictionBook2]: http://www.fictionbook.org/index.php/Eng:XML_Schema_Fictionbook_2.1
+[Jupyter notebook]: https://nbformat.readthedocs.io/en/latest/
+[InDesign ICML]: https://web.archive.org/web/20211006210211/https://wwwimages.adobe.com/www.adobe.com/content/dam/acom/en/devnet/indesign/sdk/cs6/idml/idml-cookbook.pdf
+[TEI Simple]: https://github.com/TEIC/TEI-Simple
+[Muse]: https://amusewiki.org/library/manual
+[PowerPoint]: https://en.wikipedia.org/wiki/Microsoft_PowerPoint
+[Vimwiki]: https://vimwiki.github.io
+[CSL JSON]: https://citeproc-js.readthedocs.io/en/latest/csl-json/markup.html
+[BibTeX]: https://ctan.org/pkg/bibtex
+[BibLaTeX]: https://ctan.org/pkg/biblatex
+[Markua]: https://leanpub.com/markua/read
+[EndNote XML bibliography]: https://support.clarivate.com/Endnote/s/article/EndNote-XML-Document-Type-Definition
+[typst]: https://typst.app
+[mdoc]: https://mandoc.bsd.lv/man/mdoc.7.html
+[BBCode]: https://www.bbcode.org/reference.php
+[BBCode (FluxBB)]: https://web.archive.org/web/20210623155046/https://fluxbb.org/forums/help.php#bbcode
+[BBCode (Hubzilla)]: https://hubzilla.org/help/member/bbcode
+[BBCode (Steam)]: https://steamcommunity.com/comment/ForumTopic/formattinghelp
+[BBCode (phpBB)]: https://www.phpbb.com/community/help/bbcode
+[BBCode (xenForo)]: https://www.xenfocus.com/community/help/bb-codes/
+
+## Reader options {.options}
+
+`--shift-heading-level-by=`*NUMBER*
+
+:   Shift heading levels by a positive or negative integer.
+    For example, with `--shift-heading-level-by=-1`, level 2
+    headings become level 1 headings, and level 3 headings
+    become level 2 headings.  Headings cannot have a level
+    less than 1, so a heading that would be shifted below level 1
+    becomes a regular paragraph.  Exception: with a shift of -N,
+    a level-N heading at the beginning of the document
+    replaces the metadata title. `--shift-heading-level-by=-1`
+    is a good choice when converting HTML or Markdown documents that
+    use an initial level-1 heading for the document title and
+    level-2+ headings for sections. `--shift-heading-level-by=1`
+    may be a good choice for converting Markdown documents that
+    use level-1 headings for sections to HTML, since pandoc uses
+    a level-1 heading to render the document title.
+
+`--base-header-level=`*NUMBER*
+
+:   *Deprecated.  Use `--shift-heading-level-by`=X instead,
+    where X = NUMBER - 1.* Specify the base level for headings
+    (defaults to 1).
+
+`--indented-code-classes=`*CLASSES*
+
+:   Specify classes to use for indented code blocks---for example,
+    `perl,numberLines` or `haskell`. Multiple classes may be separated
+    by spaces or commas.
+
+`--default-image-extension=`*EXTENSION*
+
+:   Specify a default extension to use when image paths/URLs have no
+    extension.  This allows you to use the same source for formats that
+    require different kinds of images.  Currently this option only affects
+    the Markdown and LaTeX readers.
+
+`--file-scope[=true|false]`
+
+:   Parse each file individually before combining for multifile
+    documents. This will allow footnotes in different files with the
+    same identifiers to work as expected. If this option is set,
+    footnotes and links will not work across files. Reading binary
+    files (docx, odt, epub) implies `--file-scope`.
+
+    If two or more files are processed using `--file-scope`,
+    prefixes based on the filenames will be added to identifiers
+    in order to disambiguate them, and internal links will
+    be adjusted accordingly.  For example, a header with
+    identifier `foo` in `subdir/file1.txt` will have its
+    identifier changed to `subdir__file1.txt__foo`.
+
+`-F` *PROGRAM*, `--filter=`*PROGRAM*
+
+:   Specify an executable to be used as a filter transforming the
+    pandoc AST after the input is parsed and before the output is
+    written.  The executable should read JSON from stdin and write
+    JSON to stdout.  The JSON must be formatted like  pandoc's own
+    JSON input and output.  The name of the output format will be
+    passed to the filter as the first argument.  Hence,
+
+        pandoc --filter ./caps.py -t latex
+
+    is equivalent to
+
+        pandoc -t json | ./caps.py latex | pandoc -f json -t latex
+
+    The latter form may be useful for debugging filters.
+
+    Filters may be written in any language.  `Text.Pandoc.JSON`
+    exports `toJSONFilter` to facilitate writing filters in Haskell.
+    Those who would prefer to write filters in python can use the
+    module [`pandocfilters`], installable from PyPI. There are also
+    pandoc filter libraries in [PHP], [perl], and
+    [JavaScript/node.js].
+
+    In order of preference, pandoc will look for filters in
+
+     1. a specified full or relative path (executable or
+     non-executable),
+
+     2. `$DATADIR/filters` (executable or non-executable)
+     where `$DATADIR` is the user data directory (see
+     `--data-dir`, above),
+
+     3. `$PATH` (executable only).
+
+    Filters, Lua-filters, and citeproc processing are applied in
+    the order specified on the command line.
+
+`-L` *SCRIPT*, `--lua-filter=`*SCRIPT*
+
+:   Transform the document in a similar fashion as JSON filters (see
+    `--filter`), but use pandoc's built-in Lua filtering system.  The given
+    Lua script is expected to return a list of Lua filters which will be
+    applied in order.  Each Lua filter must contain element-transforming
+    functions indexed by the name of the AST element on which the filter
+    function should be applied.
+
+    The `pandoc` Lua module provides helper functions for element
+    creation.  It is always loaded into the script's Lua environment.
+
+    See the [Lua filters documentation] for further details.
+
+    In order of preference, pandoc will look for Lua filters in
+
+     1. a specified full or relative path,
+
+     2. `$DATADIR/filters` where `$DATADIR` is the user data
+     directory (see `--data-dir`, above).
+
+    Filters, Lua filters, and citeproc processing are applied in
+    the order specified on the command line.
+
+`-M` *KEY*[`=`*VAL*], `--metadata=`*KEY*[`:`*VAL*]
+
+:   Set the metadata field *KEY* to the value *VAL*.  A value specified
+    on the command line overrides a value specified in the document
+    using [YAML metadata blocks][Extension: `yaml_metadata_block`].
+    Values will be parsed as YAML boolean or string values. If no value is
+    specified, the value will be treated as Boolean true.  Like
+    `--variable`, `--metadata` causes template variables to be set.
+    But unlike `--variable`, `--metadata` affects the metadata of the
+    underlying document (which is accessible from filters and may be
+    printed in some output formats) and metadata values will be escaped
+    when inserted into the template.
+
+`--metadata-file=`*FILE*
+
+:   Read metadata from the supplied YAML (or JSON) file. This
+    option can be used with every input format, but string scalars
+    in the metadata file will always be parsed as Markdown. (If the
+    input format is Markdown or a Markdown variant, then the
+    same variant will be used to parse the metadata file;
+    if it is a non-Markdown format, pandoc's default Markdown
+    extensions will be used.) This option can be used
+    repeatedly to include multiple metadata files; values in
+    files specified later on the command line will be preferred
+    over those specified in earlier files. Metadata values
+    specified inside the document, or by using `-M`, overwrite
+    values specified with this option. The file will be searched
+    for first in the working directory, and then in the `metadata`
+    subdirectory of the user data directory (see `--data-dir`).
+
+`-p`, `--preserve-tabs[=true|false]`
+
+:   Preserve tabs instead of converting them to spaces. (By default, pandoc
+    converts tabs to spaces before parsing its input.)  Note that this will
+    only affect tabs in literal code spans and code blocks. Tabs in regular
+    text are always treated as spaces.
+
+`--tab-stop=`*NUMBER*
+
+:   Specify the number of spaces per tab (default is 4).
+
+`--track-changes=accept`|`reject`|`all`
+
+:   Specifies what to do with insertions, deletions, and comments
+    produced by the MS Word "Track Changes" feature.  `accept` (the
+    default) processes all the insertions and deletions.
+    `reject` ignores them.  Both `accept` and `reject` ignore comments.
+    `all` includes all insertions, deletions, and comments, wrapped
+    in spans with `insertion`, `deletion`, `comment-start`, and
+    `comment-end` classes, respectively. The author and time of
+    change is included. `all` is useful for scripting: only
+    accepting changes from a certain reviewer, say, or before a
+    certain date. If a paragraph is inserted or deleted,
+    `track-changes=all` produces a span with the class
+    `paragraph-insertion`/`paragraph-deletion` before the
+    affected paragraph break. This option only affects the docx
+    reader.
+
+`--extract-media=`*DIR*|*FILE*`.zip`
+
+:   Extract images and other media contained in or linked from
+    the source document to the path *DIR*, creating it if
+    necessary, and adjust the images references in the document
+    so they point to the extracted files.  Media are downloaded,
+    read from the file system, or extracted from a binary
+    container (e.g. docx), as needed.  The original file paths
+    are used if they are relative paths not containing `..`.
+    Otherwise filenames are constructed from the SHA1 hash of
+    the contents.
+
+    If the path given ends in `.zip`, then instead of creating
+    a directory, pandoc will create a zip archive containing the
+    media files.
+
+`--abbreviations=`*FILE*
+
+:   Specifies a custom abbreviations file, with abbreviations
+    one to a line.  If this option is not specified, pandoc will
+    read the data file `abbreviations` from the user data
+    directory or fall back on a system default.  To see the
+    system default, use
+    `pandoc --print-default-data-file=abbreviations`.  The only
+    use pandoc makes of this list is in the Markdown reader.
+    Strings found in this list will be followed by a nonbreaking
+    space, and the period will not produce sentence-ending space
+    in formats like LaTeX.  The strings may not contain spaces.
+
+`--typst-input=`*KEY*[`=`*VAL*]
+
+:   Set a parameter value that will be made available to the typst
+    parser in `sys.inputs`, like `--input` in the `typst` CLI.
+    Either `:` or `=` may be used to separate *KEY* from *VAL*.
+    Values containing spaces must be quoted.
+
+`--trace[=true|false]`
+
+:   Print diagnostic output tracing parser progress to stderr.
+    This option is intended for use by developers in diagnosing
+    performance issues.
+
+[`pandocfilters`]: https://github.com/jgm/pandocfilters
+[PHP]: https://github.com/vinai/pandocfilters-php
+[perl]: https://metacpan.org/pod/Pandoc::Filter
+[JavaScript/node.js]: https://github.com/mvhenderson/pandoc-filter-node
+[Lua filters documentation]: https://pandoc.org/lua-filters.html
+
+## General writer options {.options}
+
+`-s`, `--standalone`
+
+:   Produce output with an appropriate header and footer (e.g. a
+    standalone HTML, LaTeX, TEI, or RTF file, not a fragment).  This option
+    is set automatically for `pdf`, `epub`, `epub3`, `fb2`, `docx`, and `odt`
+    output.  For `native` output, this option causes metadata to
+    be included; otherwise, metadata is suppressed.
+
+`--template=`*FILE*|*URL*
+
+:   Use the specified file as a custom template for the generated document.
+    Implies `--standalone`. See [Templates], below, for a
+    description of template syntax. If the template is not found,
+    pandoc will search for it in the `templates` subdirectory of
+    the user data directory (see `--data-dir`). If no extension
+    is specified and an extensionless template is not found,
+    pandoc will look for a template with an extension
+    corresponding to the writer, so that `--template=special`
+    looks for `special.html` for HTML output. If this option is
+    not used, a default template appropriate for the output
+    format will be used (see `-D/--print-default-template`).
+
+`-V` *KEY*[`=`*VAL*], `--variable=`*KEY*[`=`*VAL*]
+
+:   Set the template variable *KEY* to the string value *VAL* when rendering
+    the document in standalone mode. Either `:` or `=` may be used
+    to separate *KEY* from *VAL*. If no *VAL* is specified, the
+    key will be given the value `true`.  Structured values (lists, maps)
+    cannot be assigned using this option, but they can be assigned in
+    the `variables` section of a [defaults file][Defaults files] or
+    using the `--variable-json` option. If the variable already has
+    a *list* value, the value will be added to the list. If it already
+    has another kind of value, it will be made into a list containing
+    the previous and the new value. For example,
+    `-V author=Joe -V author=Sue` makes `author` contain a list
+    of strings: `Joe` and `Sue`.
+
+`--variable-json=`*KEY*[`=`*JSON*]
+
+:   Set the template variable *KEY* to the value specified by a JSON
+    string (this may be a boolean, a string, a list, or a mapping;
+    a number will be treated as a string). For example,
+    `--variable-json foo=false` will give `foo` the boolean false
+    value, while `--variable-json foo='"false"'` will give it the
+    string value `"false"`. Either `:` or `=` may be used to
+    separate *KEY* from *VAL*. If the variable already has a
+    value, this value will be replaced.
+
+`-D` *FORMAT*, `--print-default-template=`*FORMAT*
+
+:   Print the system default template for an output *FORMAT*. (See `-t`
+    for a list of possible *FORMAT*s.)  Templates in the user data
+    directory are ignored.  This option may be used with
+    `-o`/`--output` to redirect output to a file, but
+    `-o`/`--output` must come before `--print-default-template`
+    on the command line.
+
+    Note that some of the default templates use partials, for
+    example `styles.html`.  To print the partials, use
+    `--print-default-data-file`: for example,
+    `--print-default-data-file=templates/styles.html`.
+
+`--print-default-data-file=`*FILE*
+
+:   Print a system default data file.  Files in the user data directory
+    are ignored.  This option may be used with `-o`/`--output` to
+    redirect output to a file, but `-o`/`--output` must come before
+    `--print-default-data-file` on the command line.
+
+`--eol=crlf`|`lf`|`native`
+
+:   Manually specify line endings: `crlf` (Windows), `lf`
+    (macOS/Linux/UNIX), or `native` (line endings appropriate
+    to the OS on which pandoc is being run).  The default is
+    `native`.
+
+`--dpi`=*NUMBER*
+
+:   Specify the default dpi (dots per inch) value for conversion
+    from pixels to inch/centimeters and vice versa. (Technically,
+    the correct term would be ppi: pixels per inch.) The default
+    is 96dpi.   When images contain information about dpi
+    internally, the encoded value is used instead of the default
+    specified by this option.
+
+`--wrap=auto`|`none`|`preserve`
+
+:   Determine how text is wrapped in the output (the source
+    code, not the rendered version).  With `auto` (the default),
+    pandoc will attempt to wrap lines to the column width specified by
+    `--columns` (default 72).  With `none`, pandoc will not wrap
+    lines at all.  With `preserve`, pandoc will attempt to
+    preserve the wrapping from the source document (that is,
+    where there are nonsemantic newlines in the source, there
+    will be nonsemantic newlines in the output as well).
+    In `ipynb` output, this option affects wrapping of the
+    contents of Markdown cells.
+
+`--columns=`*NUMBER*
+
+:   Specify length of lines in characters.  This affects text wrapping
+    in the generated source code (see `--wrap`).  It also affects
+    calculation of column widths for plain text tables (see [Tables] below).
+
+`--toc[=true|false]`, `--table-of-contents[=true|false]`
+
+:   Include an automatically generated table of contents (or, in
+    the case of `latex`, `context`, `docx`, `odt`,
+    `opendocument`, `rst`, or `ms`, an instruction to create
+    one) in the output document. This option has no effect
+    unless `-s/--standalone` is used, and it has no effect
+    on `man`, `docbook4`, `docbook5`, or `jats` output.
+
+    Note that if you are producing a PDF via `ms` and using
+    (the default) `groff` as a `--pdf-engine`, the table of
+    contents will appear at the end of the document. If you would
+    prefer it to be at the beginning of the document, before the
+    title, you can use `--pdf-engine=pdfroff`.
+
+`--toc-depth=`*NUMBER*
+
+:   Specify the number of section levels to include in the table
+    of contents.  The default is 3 (which means that level-1, 2, and 3
+    headings will be listed in the contents).
+
+`--lof[=true|false]`, `--list-of-figures[=true|false]`
+
+:   Include an automatically generated list of figures (or, in
+    some formats, an instruction to create one) in the output
+    document. This option has no effect unless `-s/--standalone`
+    is used, and it only has an effect on `latex`, `context`, and
+    `docx` output.
+
+`--lot[=true|false]`, `--list-of-tables[=true|false]`
+
+:   Include an automatically generated list of tables (or, in
+    some formats, an instruction to create one) in the output
+    document. This option has no effect unless `-s/--standalone`
+    is used, and it only has an effect on `latex`, `context`, and
+    `docx` output.
+
+`--strip-comments[=true|false]`
+
+:   Strip out HTML comments in the Markdown or Textile source,
+    rather than passing them on to Markdown, Textile or HTML
+    output as raw HTML.  This does not apply to HTML comments
+    inside raw HTML blocks when the `markdown_in_html_blocks`
+    extension is not set.
+
+`--syntax-highlighting=default|none|idiomatic|`*STYLE*`|`*FILE*
+
+:   The method to use for code syntax highlighting. Setting a
+    specific *STYLE* causes highlighting to be performed with the
+    internal highlighting engine, using KDE syntax definitions and
+    styles. The `idiomatic` method uses a format-specific
+    highlighter if one is available, or the default style if the
+    target format has no idiomatic highlighting method. Setting this
+    option to `none` disables all syntax highlighting. The
+    `default` method uses a format-specific default.
+
+    The default for HTML, EPUB, Docx, Ms, Man, and LaTeX output is
+    to use the internal highlighter with the default style; for Typst
+    it is to use Typst's own syntax highlighting system.
+
+    Style options are `pygments` (the default), `kate`,
+    `monochrome`, `breezeDark`, `espresso`, `zenburn`, `haddock`,
+    and `tango`. For more information on syntax highlighting in
+    pandoc, see [Syntax highlighting], below. See also
+    `--list-highlight-styles`.
+
+    Instead of a *STYLE* name, a JSON file with extension
+    `.theme` may be supplied.  This will be parsed as a KDE
+    syntax highlighting theme and (if valid) used as the
+    highlighting style.
+
+    To generate the JSON version of an existing style,
+    use `--print-highlight-style`.
+
+`--no-highlight`
+
+:   *Deprecated, use `--syntax-highlighting=none` instead.*
+
+    Disables syntax highlighting for code blocks and inlines, even when
+    a language attribute is given.
+
+`--highlight-style=`*STYLE*|*FILE*
+
+:   _Deprecated, use `--syntax-highlighting=`*STYLE*|*FILE* instead._
+
+    Specifies the coloring style to be used in highlighted source code.
+
+`--print-highlight-style=`*STYLE*|*FILE*
+
+:   Prints a JSON version of a highlighting style, which can
+    be modified, saved with a `.theme` extension, and used
+    with `--syntax-highlighting`.  This option may be used with
+    `-o`/`--output` to redirect output to a file, but
+    `-o`/`--output` must come before `--print-highlight-style`
+    on the command line.
+
+`--syntax-definition=`*FILE*
+
+:   Instructs pandoc to load a KDE XML syntax definition file,
+    which will be used for syntax highlighting of appropriately
+    marked code blocks.  This can be used to add support for
+    new languages or to use altered syntax definitions for
+    existing languages.  This option may be repeated to add
+    multiple syntax definitions.
+
+`-H` *FILE*, `--include-in-header=`*FILE*|*URL*
+
+:   Include contents of *FILE*, verbatim, at the end of the header.
+    This can be used, for example, to include special
+    CSS or JavaScript in HTML documents.  This option can be used
+    repeatedly to include multiple files in the header.  They will be
+    included in the order specified.  Implies `--standalone`.
+
+`-B` *FILE*, `--include-before-body=`*FILE*|*URL*
+
+:   Include contents of *FILE*, verbatim, at the beginning of the
+    document body (e.g. after the `<body>` tag in HTML, or the
+    `\begin{document}` command in LaTeX). This can be used to include
+    navigation bars or banners in HTML documents. This option can be
+    used repeatedly to include multiple files. They will be included in
+    the order specified.  Implies `--standalone`. Note that if the
+    output format is `odt`, this file must be in OpenDocument XML format
+    suitable for insertion into the body of the document, and if
+    the output is `docx`, this file must be in appropriate
+    OpenXML format.
+
+`-A` *FILE*, `--include-after-body=`*FILE*|*URL*
+
+:   Include contents of *FILE*, verbatim, at the end of the document
+    body (before the `</body>` tag in HTML, or the
+    `\end{document}` command in LaTeX). This option can be used
+    repeatedly to include multiple files. They will be included in the
+    order specified.  Implies `--standalone`. Note that if the
+    output format is `odt`, this file must be in OpenDocument XML format
+    suitable for insertion into the body of the document, and if
+    the output is `docx`, this file must be in appropriate
+    OpenXML format.
+
+`--resource-path=`*SEARCHPATH*
+
+:   List of paths to search for images and other resources.
+    The paths should be separated by `:` on Linux, UNIX, and
+    macOS systems, and by `;` on Windows.  If `--resource-path`
+    is not specified, the default resource path is the working
+    directory. Note that, if `--resource-path` is specified,
+    the working directory must be explicitly listed or it
+    will not be searched.  For example:
+    `--resource-path=.:test` will search the working directory
+    and the `test` subdirectory, in that order.
+    This option can be used repeatedly. Search path components
+    that come later on the command line will be searched before
+    those that come earlier, so
+    `--resource-path foo:bar --resource-path baz:bim` is
+    equivalent to `--resource-path baz:bim:foo:bar`.
+    Note that this option only has an effect when pandoc
+    itself needs to find an image (e.g., in producing a
+    PDF or docx, or when `--embed-resources` is used.)
+    It will not cause image paths to be rewritten in other
+    cases (e.g., when pandoc is generating LaTeX or HTML).
+
+`--request-header=`*NAME*`:`*VAL*
+
+:   Set the request header *NAME* to the value *VAL* when making
+    HTTP requests (for example, when a URL is given on the
+    command line, or when resources used in a document must be
+    downloaded). If you're behind a proxy, you also need to set
+    the environment variable `http_proxy` to `http://...`.
+
+`--no-check-certificate[=true|false]`
+
+:   Disable the certificate verification to allow access to
+    unsecure HTTP resources (for example when the certificate
+    is no longer valid or self signed).
+
+## Options affecting specific writers {.options}
+
+`--self-contained[=true|false]`
+
+:   *Deprecated synonym for `--embed-resources --standalone`.*
+
+`--embed-resources[=true|false]`
+
+:   Produce a standalone HTML file with no external dependencies, using
+    `data:` URIs to incorporate the contents of linked scripts, stylesheets,
+    images, and videos. The resulting file should be "self-contained," in the
+    sense that it needs no external files and no net access to be displayed
+    properly by a browser. This option works only with HTML output formats,
+    including `html4`, `html5`, `html+lhs`, `html5+lhs`, `s5`, `slidy`,
+    `slideous`, `dzslides`, and `revealjs`. Scripts, images, and stylesheets at
+    absolute URLs will be downloaded; those at relative URLs will be sought
+    relative to the working directory (if the first source
+    file is local) or relative to the base URL (if the first source
+    file is remote).  Elements with the attribute
+    `data-external="1"` will be left alone; the documents they
+    link to will not be incorporated in the document.
+    Limitation: resources that are loaded dynamically through
+    JavaScript cannot be incorporated; as a result, fonts may
+    be missing when `--mathjax` is used, and some
+    advanced features (e.g.  zoom or speaker notes) may not work
+    in an offline "self-contained" `reveal.js` slide show.
+
+    For SVG images, `img` tags with `data:` URIs are used,
+    unless the image has the class `inline-svg`, in which case
+    an inline SVG element is inserted. This approach is
+    recommended when there are many occurrences of the same
+    SVG in a document, as `<use>` elements will be used to
+    reduce duplication.
+
+`--link-images[=true|false]`
+
+:   Include links to images instead of embedding the images in ODT.
+    (This option currently only affects ODT output.)
+
+`--html-q-tags[=true|false]`
+
+:   Use `<q>` tags for quotes in HTML.  (This option only has an
+    effect if the `smart` extension is enabled for the input
+    format used.)
+
+`--ascii[=true|false]`
+
+:   Use only ASCII characters in output. Currently supported for XML
+    and HTML formats (which use entities instead of UTF-8 when this
+    option is selected), CommonMark, gfm, and Markdown (which use
+    entities), roff man and ms (which use hexadecimal escapes), and to a
+    limited degree LaTeX (which uses standard commands for accented
+    characters when possible).
+
+`--reference-links[=true|false]`
+
+:   Use reference-style links, rather than inline links, in writing Markdown
+    or reStructuredText.  By default inline links are used.  The
+    placement of link references is affected by the
+    `--reference-location` option.
+
+`--reference-location=block`|`section`|`document`
+
+:   Specify whether footnotes (and references, if `reference-links` is
+    set) are placed at the end of the current (top-level) block, the
+    current section, or the document. The default is
+    `document`. Currently this option only affects the
+    `markdown`, `muse`, `html`, `epub`, `slidy`, `s5`, `slideous`,
+    `dzslides`, and `revealjs` writers.  In slide formats,
+    specifying `--reference-location=section` will cause notes
+    to be rendered at the bottom of a slide.
+
+`--figure-caption-position=above`|`below`
+
+:   Specify whether figure captions go above or below figures
+    (default is `below`).  This option only affects HTML,
+    LaTeX, Docx, ODT, and Typst output.
+
+`--table-caption-position=above`|`below`
+
+:   Specify whether table captions go above or below tables
+    (default is `above`).  This option only affects HTML,
+    LaTeX, Docx, ODT, and Typst output.
+
+`--markdown-headings=setext`|`atx`
+
+:   Specify whether to use ATX-style (`#`-prefixed) or
+    Setext-style (underlined) headings for level 1 and 2
+    headings in Markdown output.  (The default is `atx`.)
+    ATX-style headings are always used for levels 3+.
+    This option also affects Markdown cells in `ipynb` output.
+
+`--list-tables[=true|false]`
+
+:   Render tables as list tables in RST output.
+
+`--top-level-division=default`|`section`|`chapter`|`part`
+
+:   Treat top-level headings as the given division type in
+    LaTeX, ConTeXt, DocBook, and TEI output. The hierarchy
+    order is part, chapter, then section; all headings are
+    shifted such that the top-level heading becomes the
+    specified type. The default behavior is to determine the
+    best division type via heuristics: unless other conditions
+    apply, `section` is chosen. When the `documentclass`
+    variable is set to `report`, `book`, or `memoir` (unless the
+    `article` option is specified), `chapter` is implied as the
+    setting for this option. If `beamer` is the output format,
+    specifying either `chapter` or `part` will cause top-level
+    headings to become `\part{..}`, while second-level headings
+    remain as their default type.
+
+    In Docx output, this option adds section breaks before first-level
+    headings if `chapter` is selected, and before first- and second-level
+    headings if `part` is selected. Footnote numbers will restart
+    with each section break unless the reference doc modifies this.
+
+`-N`, `--number-sections=[true|false]`
+
+:   Number section headings in LaTeX, ConTeXt, HTML, Docx, ms, or EPUB
+    output.  By default, sections are not numbered.  Sections with class
+    `unnumbered` will never be numbered, even if `--number-sections`
+    is specified.
+
+`--number-offset=`*NUMBER*[`,`*NUMBER*`,`*...*]
+
+:   Offsets for section heading numbers. The first number is added
+    to the section number for level-1 headings, the second for
+    level-2 headings, and so on. So, for example, if you
+    want the first level-1 heading in your document to be
+    numbered "6" instead of "1", specify `--number-offset=5`.
+    If your document starts with a level-2 heading which you want
+    to be numbered "1.5", specify `--number-offset=1,4`.
+    `--number-offset` only directly affects the number of the
+    first section heading in a document; subsequent numbers
+    increment in the normal way. Implies `--number-sections`.
+    Currently this feature only affects HTML and Docx output.
+
+`--listings[=true|false]`
+
+:   *Deprecated, use `--syntax-highlighting=idiomatic` or
+    `--syntax-highlighting=default` instead.
+
+    Use the [`listings`] package for LaTeX code blocks. The package
+    does not support multi-byte encoding for source code. To handle UTF-8
+    you would need to use a custom template. This issue is fully
+    documented here: [Encoding issue with the listings package].
+
+`-i`, `--incremental[=true|false]`
+
+:   Make list items in slide shows display incrementally (one by one).
+    The default is for lists to be displayed all at once.
+
+`--slide-level=`*NUMBER*
+
+:   Specifies that headings with the specified level create
+    slides (for `beamer`, `revealjs`, `pptx`, `s5`, `slidy`,
+    `slideous`, `dzslides`). Headings above this level in the
+    hierarchy are used to divide the slide show into sections;
+    headings below this level create subheads within a slide.
+    Valid values are 0-6. If a slide level of 0 is specified,
+    slides will not be split automatically on headings, and
+    horizontal rules must be used to indicate slide boundaries.
+    If a slide level is not specified explicitly, the slide level
+    will be set automatically based on the contents of the
+    document; see [Structuring the slide show].
+
+`--section-divs[=true|false]`
+
+:   Wrap sections in `<section>` tags (or `<div>` tags for `html4`),
+    and attach identifiers to the enclosing `<section>` (or `<div>`)
+    rather than the heading itself (see
+    [Heading identifiers], below). This option only affects
+    HTML output (and does not affect HTML slide formats).
+
+`--email-obfuscation=none`|`javascript`|`references`
+
+:   Specify a method for obfuscating `mailto:` links in HTML documents.
+    `none` leaves `mailto:` links as they are.  `javascript` obfuscates
+    them using JavaScript. `references` obfuscates them by printing their
+    letters as decimal or hexadecimal character references.  The default
+    is `none`.
+
+`--id-prefix=`*STRING*
+
+:   Specify a prefix to be added to all identifiers and internal links
+    in HTML and DocBook output, and to footnote numbers in Markdown
+    and Haddock output. This is useful for preventing duplicate
+    identifiers when generating fragments to be included in other pages.
+
+`-T` *STRING*, `--title-prefix=`*STRING*
+
+:   Specify *STRING* as a prefix at the beginning of the title
+    that appears in the HTML header (but not in the title as it
+    appears at the beginning of the HTML body).  Implies `--standalone`.
+
+`-c` *URL*, `--css=`*URL*
+
+:   Link to a CSS style sheet. This option can be used repeatedly to
+    include multiple files. They will be included in the order specified.
+    This option only affects HTML (including HTML slide shows)
+    and EPUB output.  It should be used together with
+    `-s/--standalone`, because the link to the stylesheet goes
+    in the document header.
+
+    A stylesheet is required for generating EPUB.  If none is
+    provided using this option (or the `css` or `stylesheet`
+    metadata fields), pandoc will look for a file `epub.css` in the
+    user data directory (see `--data-dir`).  If it is not
+    found there, sensible defaults will be used.
+
+[`--reference-doc=`*FILE*|*URL*]{#option--reference-doc}
+
+:   Use the specified file as a style reference in producing a
+    docx or ODT file.
+
+    Docx
+
+    :   For best results, the reference docx should be a modified
+        version of a docx file produced using pandoc.  The contents
+        of the reference docx are ignored, but its stylesheets and
+        document properties (including margins, page size, header,
+        and footer) are used in the new docx. If no reference docx
+        is specified on the command line, pandoc will look for a
+        file `reference.docx` in the user data directory (see
+        `--data-dir`). If this is not found either, sensible
+        defaults will be used.
+
+        To produce a custom `reference.docx`, first get a copy of
+        the default `reference.docx`: `pandoc
+        -o custom-reference.docx --print-default-data-file reference.docx`.
+        Then open `custom-reference.docx` in Word or LibreOffice, 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
+        - Compact
+        - Title
+        - Subtitle
+        - Author
+        - Date
+        - Abstract
+        - AbstractTitle
+        - Bibliography
+        - Heading 1
+        - Heading 2
+        - Heading 3
+        - Heading 4
+        - Heading 5
+        - Heading 6
+        - Heading 7
+        - Heading 8
+        - Heading 9
+        - Block Text [for block quotes]
+        - Footnote Block Text [for block quotes in footnotes]
+        - Source Code
+        - Footnote Text
+        - Definition Term
+        - Definition
+        - Caption
+        - Table Caption
+        - Image Caption
+        - Figure
+        - Captioned Figure
+        - TOC Heading
+
+        Character styles:
+
+        - Default Paragraph Font
+        - Verbatim Char
+        - Footnote Reference
+        - Hyperlink
+        - Section Number
+
+        Table style:
+
+        - Table
+
+    ODT
+
+    :   For best results, the reference ODT should be a modified
+        version of an ODT produced using pandoc.  The contents of
+        the reference ODT are ignored, but its stylesheets are used
+        in the new ODT. If no reference ODT is specified on the
+        command line, pandoc will look for a file `reference.odt` in
+        the user data directory (see `--data-dir`). If this is not
+        found either, sensible defaults will be used.
+
+        To produce a custom `reference.odt`, first get a copy of
+        the default `reference.odt`: `pandoc
+        -o custom-reference.odt --print-default-data-file reference.odt`.
+        Then open `custom-reference.odt` in LibreOffice, modify
+        the styles as you wish, and save the file.
+
+    PowerPoint
+
+    :   Templates included with Microsoft PowerPoint 2013 (either with
+        `.pptx` or `.potx` extension) are known to work, as are most
+        templates derived from these.
+
+        The specific requirement is that the template should contain layouts
+        with the following names (as seen within PowerPoint):
+
+        - Title Slide
+        - Title and Content
+        - Section Header
+        - Two Content
+        - Comparison
+        - Content with Caption
+        - Blank
+
+        For each name, the first layout found with that name will be used.
+        If no layout is found with one of the names, pandoc will output a
+        warning and use the layout with that name from the default reference
+        doc instead. (How these layouts are used is described in [PowerPoint
+        layout choice](#powerpoint-layout-choice).)
+
+        All templates included with a recent version of MS PowerPoint
+        will fit these criteria. (You can click on `Layout` under the
+        `Home` menu to check.)
+
+        You can also modify the default `reference.pptx`: first run
+        `pandoc -o custom-reference.pptx --print-default-data-file
+        reference.pptx`, and then modify `custom-reference.pptx`
+        in MS PowerPoint (pandoc will use the layouts with the names
+        listed above).
+
+`--split-level=`*NUMBER*
+
+:   Specify the heading level at which to split an EPUB or
+    chunked HTML document into separate files. The default is to split
+    into chapters at level-1 headings. In the case of EPUB, this
+    option only affects the internal composition of the EPUB, not the way
+    chapters and sections are displayed to users. Some
+    readers may be slow if the chapter files are too large, so for large
+    documents with few level-1 headings, one might want to use a chapter
+    level of 2 or 3. For chunked HTML, this option determines
+    how much content goes in each "chunk."
+
+`--chunk-template=`*PATHTEMPLATE*
+
+:   Specify a template for the filenames in a `chunkedhtml` document.
+    In the template, `%n` will be replaced by the chunk number (padded
+    with leading 0s to 3 digits), `%s` with the section number of the chunk,
+    `%h` with the heading text (with formatting removed), `%i` with
+    the section identifier. For example, `section-%s-%i.html` might
+    be resolved to `section-1.1-introduction.html`. The characters
+    `/` and `\` are not allowed in chunk templates and will be
+    ignored. The default is `%s-%i.html`.
+
+`--epub-chapter-level=`*NUMBER*
+
+:   *Deprecated synonym for `--split-level`.*
+
+`--epub-cover-image=`*FILE*
+
+:   Use the specified image as the EPUB cover.  It is recommended
+    that the image be less than 1000px in width and height. Note that
+    in a Markdown source document you can also specify `cover-image`
+    in a YAML metadata block (see [EPUB Metadata], below).
+
+`--epub-title-page=true`|`false`
+
+:   Determines whether a the title page is included in the EPUB
+    (default is `true`).
+
+`--epub-metadata=`*FILE*
+
+:   Look in the specified XML file for metadata for the EPUB.
+    The file should contain a series of [Dublin Core elements].
+    For example:
+
+         <dc:rights>Creative Commons</dc:rights>
+         <dc:language>es-AR</dc:language>
+
+    By default, pandoc will include the following metadata elements:
+    `<dc:title>` (from the document title), `<dc:creator>` (from the
+    document authors), `<dc:date>` (from the document date, which should
+    be in [ISO 8601 format]), `<dc:language>` (from the `lang`
+    variable, or, if is not set, the locale), and `<dc:identifier
+    id="BookId">` (a randomly generated UUID). Any of these may be
+    overridden by elements in the metadata file.
+
+    Note: if the source document is Markdown, a YAML metadata block
+    in the document can be used instead.  See below under
+    [EPUB Metadata].
+
+`--epub-embed-font=`*FILE*
+
+:   Embed the specified font in the EPUB. This option can be repeated
+    to embed multiple fonts.  Wildcards can also be used: for example,
+    `DejaVuSans-*.ttf`.  However, if you use wildcards on the command
+    line, be sure to escape them or put the whole filename in single quotes,
+    to prevent them from being interpreted by the shell. To use the
+    embedded fonts, you will need to add declarations like the following
+    to your CSS (see `--css`):
+
+        @font-face {
+           font-family: DejaVuSans;
+           font-style: normal;
+           font-weight: normal;
+           src:url("../fonts/DejaVuSans-Regular.ttf");
+        }
+        @font-face {
+           font-family: DejaVuSans;
+           font-style: normal;
+           font-weight: bold;
+           src:url("../fonts/DejaVuSans-Bold.ttf");
+        }
+        @font-face {
+           font-family: DejaVuSans;
+           font-style: italic;
+           font-weight: normal;
+           src:url("../fonts/DejaVuSans-Oblique.ttf");
+        }
+        @font-face {
+           font-family: DejaVuSans;
+           font-style: italic;
+           font-weight: bold;
+           src:url("../fonts/DejaVuSans-BoldOblique.ttf");
+        }
+        body { font-family: "DejaVuSans"; }
+
+`--epub-subdirectory=`*DIRNAME*
+
+:   Specify the subdirectory in the OCF container that is to hold
+    the EPUB-specific contents.  The default is `EPUB`.  To put
+    the EPUB contents in the top level, use an empty string.
+
+`--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`,
+    `tectonic`, `wkhtmltopdf`, `weasyprint`, `pagedjs-cli`,
+    `prince`, `context`, `groff`, `pdfroff`, and `typst`.
+    If the engine is not in your PATH, the full path of the engine
+    may be specified here. If this option is not specified,
+    pandoc uses the following defaults depending on the output
+    format specified using `-t/--to`:
+
+    - `-t latex` or none: `pdflatex` (other options: `xelatex`, `lualatex`,
+        `tectonic`, `latexmk`)
+    - `-t context`: `context`
+    - `-t html`:  `weasyprint` (other options: `prince`, `wkhtmltopdf`,
+        `pagedjs-cli`;
+        see [print-css.rocks](https://print-css.rocks) for a good
+        introduction to PDF generation from HTML/CSS)
+    - `-t ms`:  `groff`
+    - `-t typst`: `typst`
+
+    This option is normally intended to be used when a PDF
+    file is specified as `-o/--output`.  However, it may still
+    have an effect when other output formats are requested.
+    For example, `ms` output will include `.pdfhref` macros
+    only if a `--pdf-engine` is selected, and the macros will
+    be differently encoded depending on whether `groff` or
+    `pdfroff` is specified.
+
+`--pdf-engine-opt=`*STRING*
+
+:   Use the given string as a command-line argument to the `pdf-engine`.
+    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]: https://www.dublincore.org/specifications/dublin-core/dces/
+[ISO 8601 format]: https://www.w3.org/TR/NOTE-datetime
+[Encoding issue with the listings package]:
+  https://en.wikibooks.org/wiki/LaTeX/Source_Code_Listings#Encoding_issue
+
+## Citation rendering {.options}
+
+`-C`, `--citeproc`
+
+:   Process the citations in the file, replacing them with
+    rendered citations and adding a bibliography.
+    Citation processing will not take place unless bibliographic
+    data is supplied, either through an external file specified
+    using the `--bibliography` option or the `bibliography`
+    field in metadata, or via a `references` section in metadata
+    containing a list of citations in CSL YAML format with
+    Markdown formatting.  The style is controlled by a [CSL]
+    stylesheet specified using the `--csl` option or the `csl`
+    field in metadata. (If no stylesheet is specified,
+    the `chicago-author-date` style will be used by default.)
+    The citation processing transformation may be applied before
+    or after filters or Lua filters (see `--filter`,
+    `--lua-filter`): these transformations are applied in the
+    order they appear on the command line.  For more
+    information, see the section on [Citations].
+
+    Note: if this option is specified, the `citations` extension
+    will be disabled automatically in the writer, to ensure that
+    the citeproc-generated citations will be rendered instead of
+    the format's own citation syntax.
+
+`--bibliography=`*FILE*
+
+:   Set the `bibliography` field in the document's metadata to *FILE*,
+    overriding any value set in the metadata.  If you supply
+    this argument multiple times, each *FILE* will be added to
+    bibliography.  If *FILE* is a URL, it will be fetched
+    via HTTP. If *FILE* is not found relative to the
+    working directory, it will be sought in the resource path
+    (see `--resource-path`).
+
+`--csl=`*FILE*
+
+:   Set the `csl` field in the document's metadata to *FILE*,
+    overriding any value set in the metadata.  (This is equivalent to
+    `--metadata csl=FILE`.)  If *FILE* is a URL, it will be
+    fetched via HTTP.  If *FILE* is not found relative to the
+    working directory, it will be sought in the resource path
+    (see `--resource-path`) and finally in the `csl`
+    subdirectory of the pandoc user data directory.
+
+`--citation-abbreviations=`*FILE*
+
+:   Set the `citation-abbreviations` field in the document's metadata to
+    *FILE*, overriding any value set in the metadata.  (This is equivalent to
+    `--metadata citation-abbreviations=FILE`.)
+    If *FILE* is a URL, it will be fetched via HTTP.  If *FILE* is not
+    found relative to the working directory, it will be sought
+    in the resource path (see `--resource-path`) and finally in
+    the `csl` subdirectory of the pandoc user data directory.
+
+`--natbib`
+
+:   Use [`natbib`] for citations in LaTeX output.  This option
+    is not for use with the `--citeproc` option or with PDF
+    output.  It is intended for use in producing a LaTeX file
+    that can be processed with [`bibtex`].
+
+`--biblatex`
+
+:   Use [`biblatex`] for citations in LaTeX output.  This option
+    is not for use with the `--citeproc` option or with PDF
+    output. It is intended for use in producing a LaTeX file
+    that can be processed with [`bibtex`] or [`biber`].
+
+## Math rendering in HTML {.options}
+
+The default is to render TeX math as far as possible using
+Unicode characters.  Formulas are put inside a `span` with
+`class="math"`, so that they may be styled differently from the
+surrounding text if needed. However, this gives acceptable
+results only for basic math, usually you will want to use
+`--mathjax` or another of the following options.
+
+`--mathjax`[`=`*URL*]
+
+:   Use [MathJax] to display embedded TeX math in HTML output.
+    TeX math will be put between `\(...\)` (for inline math)
+    or `\[...\]` (for display math) and wrapped in `<span>` tags
+    with class `math`. Then the MathJax JavaScript will render it.
+    The *URL* should point to the `MathJax.js` load script.
+    If a *URL* is not provided, a link to the Cloudflare CDN will
+    be inserted.
+
+`--mathml`
+
+:   Convert TeX math to [MathML] (in `epub3`, `docbook4`,
+    `docbook5`, `jats`, `html4` and `html5`).  This is the
+    default in `odt` output. MathML is supported natively by
+    the main web browsers and select e-book readers.
+
+`--webtex`[`=`*URL*]
+
+:   Convert TeX formulas to `<img>` tags that link to an external script
+    that converts formulas to images. The formula will be URL-encoded
+    and concatenated with the URL provided. For SVG images you can for
+    example use `--webtex https://latex.codecogs.com/svg.latex?`.
+    If no URL is specified, the CodeCogs URL generating PNGs
+    will be used (`https://latex.codecogs.com/png.latex?`).
+    Note:  the `--webtex` option will affect Markdown output
+    as well as HTML, which is useful if you're targeting a
+    version of Markdown without native math support.
+
+`--katex`[`=`*URL*]
+
+:   Use [KaTeX] to display embedded TeX math in HTML output.
+    The *URL* is the base URL for the KaTeX library. That directory
+    should contain a `katex.min.js` and a `katex.min.css` file.
+    If a *URL* is not provided, a link to the KaTeX CDN will be inserted.
+
+`--gladtex`
+
+:   Enclose TeX math in `<eq>` tags in HTML output.  The resulting HTML
+    can then be processed by [GladTeX] to produce SVG images of the typeset
+    formulas and an HTML file with these images embedded.
+
+        pandoc -s --gladtex input.md -o myfile.htex
+        gladtex -d image_dir myfile.htex
+        # produces myfile.html and images in image_dir
+
+[MathML]: https://www.w3.org/Math/
+[MathJax]: https://www.mathjax.org
+[KaTeX]: https://github.com/Khan/KaTeX
+[GladTeX]: https://humenda.github.io/GladTeX/
+
+## Options for wrapper scripts {.options}
+
+`--dump-args[=true|false]`
+
+:   Print information about command-line arguments to *stdout*, then exit.
+    This option is intended primarily for use in wrapper scripts.
+    The first line of output contains the name of the output file specified
+    with the `-o` option, or `-` (for *stdout*) if no output file was
+    specified.  The remaining lines contain the command-line arguments,
+    one per line, in the order they appear.  These do not include regular
+    pandoc options and their arguments, but do include any options appearing
+    after a `--` separator at the end of the line.
+
+`--ignore-args[=true|false]`
+
+:   Ignore command-line arguments (for use in wrapper scripts).
+    Regular pandoc options are not ignored.  Thus, for example,
+
+        pandoc --ignore-args -o foo.html -s foo.txt -- -e latin1
+
+    is equivalent to
+
+        pandoc -o foo.html -s
+
+# Exit codes
+
+If pandoc completes successfully, it will return exit code 0.
+Nonzero exit codes have the following meanings:
+
+ Code Error
+----- ------------------------------------
+    1 PandocIOError
+    3 PandocFailOnWarningError
+    4 PandocAppError
+    5 PandocTemplateError
+    6 PandocOptionError
+   21 PandocUnknownReaderError
+   22 PandocUnknownWriterError
+   23 PandocUnsupportedExtensionError
+   24 PandocCiteprocError
+   25 PandocBibliographyError
+   31 PandocEpubSubdirectoryError
+   43 PandocPDFError
+   44 PandocXMLError
+   47 PandocPDFProgramNotFoundError
+   61 PandocHttpError
+   62 PandocShouldNeverHappenError
+   63 PandocSomeError
+   64 PandocParseError
+   66 PandocMakePDFError
+   67 PandocSyntaxMapError
+   83 PandocFilterError
+   84 PandocLuaError
+   89 PandocNoScriptingEngine
+   91 PandocMacroLoop
+   92 PandocUTF8DecodingError
+   93 PandocIpynbDecodingError
+   94 PandocUnsupportedCharsetError
+   95 PandocInputNotTextError
+   97 PandocCouldNotFindDataFileError
+   98 PandocCouldNotFindMetadataFileError
+   99 PandocResourceNotFound
+----- ------------------------------------
+
+# Defaults files
+
+The `--defaults` option may be used to specify a package
+of options, in the form of a YAML or JSON file. Examples in
+this section will be given in YAML, but the equivalent forms in
+JSON will also work.
+
+Fields that are omitted will just have their regular
+default values.  So a defaults file can be as simple as
+one line:
+
+``` yaml
+verbosity: INFO
+```
+
+or in JSON:
+
+``` json
+{ "verbosity": "INFO" }
+```
+
+In fields that expect a file path (or list of file paths), the
+following syntax may be used to interpolate environment variables:
+
+``` yaml
+csl:  ${HOME}/mycsldir/special.csl
+```
+
+`${USERDATA}` may also be used; this will always resolve to the
+user data directory that is current when the defaults file is
+parsed, regardless of the setting of the environment
+variable `USERDATA`.
+
+`${.}` will resolve to the directory containing the defaults
+file itself.  This allows you to refer to resources contained
+in that directory:
+
+``` yaml
+epub-cover-image: ${.}/cover.jpg
+epub-metadata: ${.}/meta.xml
+resource-path:
+- .             # the working directory from which pandoc is run
+- ${.}/images   # the images subdirectory of the directory
+                # containing this defaults file
+```
+
+This environment variable interpolation syntax *only* works in
+fields that expect file paths.
+
+Defaults files can be placed in the `defaults` subdirectory of
+the user data directory and used from any directory.  For
+example, one could create a file specifying defaults for writing
+letters, save it as `letter.yaml` in the `defaults` subdirectory
+of the user data directory, and then invoke these defaults
+from any directory using `pandoc --defaults letter`
+or `pandoc -dletter`.
+
+When multiple defaults are used, their contents will be combined.
+
+Note that, where command-line arguments may be repeated
+(`--metadata-file`, `--css`, `--include-in-header`,
+`--include-before-body`, `--include-after-body`, `--variable`,
+`--metadata`, `--syntax-definition`), the values specified on
+the command line will combine with values specified in the
+defaults file, rather than replacing them.
+
+The following tables show the mapping between the command line and
+defaults file entries.
+
++----------------------------------+-----------------------------------+
+| command line                     | defaults file                     |
++:=================================+:==================================+
+| ```                              | ``` yaml                          |
+| foo.md                           | input-file: foo.md                |
+| ```                              | ```                               |
++----------------------------------+-----------------------------------+
+| ```                              | ``` yaml                          |
+| foo.md bar.md                    | input-files:                      |
+|                                  |   - foo.md                        |
+|                                  |   - bar.md                        |
+| ```                              | ```                               |
++----------------------------------+-----------------------------------+
+
+The value of `input-files` may be left empty to indicate input from
+stdin, and it can be an empty sequence `[]` for no input.
+
+## General options
+
++----------------------------------+-----------------------------------+
+| command line                     | defaults file                     |
++:=================================+:==================================+
+| ```                              | ``` yaml                          |
+| --from markdown+emoji            | from: markdown+emoji              |
+| ```                              | ```                               |
+|                                  | ``` yaml                          |
+|                                  | reader: markdown+emoji            |
+|                                  | ```                               |
++----------------------------------+-----------------------------------+
+| ```                              | ``` yaml                          |
+| --to markdown+hard_line_breaks   | to: markdown+hard_line_breaks     |
+| ```                              | ```                               |
+|                                  | ``` yaml                          |
+|                                  | writer: markdown+hard_line_breaks |
+|                                  | ```                               |
++----------------------------------+-----------------------------------+
+| ```                              | ``` yaml                          |
+| --output foo.pdf                 | output-file: foo.pdf              |
+| ```                              | ```                               |
++----------------------------------+-----------------------------------+
+| ```                              | ``` yaml                          |
+| --output -                       | output-file:                      |
+| ```                              | ```                               |
++----------------------------------+-----------------------------------+
+| ```                              | ``` yaml                          |
+| --data-dir dir                   | data-dir: dir                     |
+| ```                              | ```                               |
++----------------------------------+-----------------------------------+
+| ```                              | ``` yaml                          |
+| --defaults file                  | defaults:                         |
+| ```                              | - file                            |
+|                                  | ```                               |
++----------------------------------+-----------------------------------+
+| ```                              | ``` yaml                          |
+| --verbose                        | verbosity: INFO                   |
+| ```                              | ```                               |
++----------------------------------+-----------------------------------+
+| ```                              | ``` yaml                          |
+| --quiet                          | verbosity: ERROR                  |
+| ```                              | ```                               |
++----------------------------------+-----------------------------------+
+| ```                              | ``` yaml                          |
+| --fail-if-warnings               | fail-if-warnings: true            |
+| ```                              | ```                               |
++----------------------------------+-----------------------------------+
+| ```                              | ``` yaml                          |
+| --sandbox                        | sandbox: true                     |
+| ```                              | ```                               |
++----------------------------------+-----------------------------------+
+| ```                              | ``` yaml                          |
+| --log=FILE                       | log-file: FILE                    |
+| ```                              | ```                               |
++----------------------------------+-----------------------------------+
+
+Options specified in a defaults file itself always have priority over
+those in another file included with a `defaults:` entry.
+
+`verbosity` can have the values `ERROR`, `WARNING`, or `INFO`.
+
+## Reader options
+
++----------------------------------+-----------------------------------+
+| command line                     | defaults file                     |
++:=================================+:==================================+
+| ```                              | ``` yaml                          |
+| --shift-heading-level-by -1      | shift-heading-level-by: -1        |
+| ```                              | ```                               |
++----------------------------------+-----------------------------------+
+| ```                              | ``` yaml                          |
+| --indented-code-classes python   | indented-code-classes:            |
+|                                  |   - python                        |
+| ```                              | ```                               |
++----------------------------------+-----------------------------------+
+| ```                              | ``` yaml                          |
+| --default-image-extension ".jpg" | default-image-extension: '.jpg'   |
+| ```                              | ```                               |
++----------------------------------+-----------------------------------+
+| ```                              | ``` yaml                          |
+| --file-scope                     | file-scope: true                  |
+| ```                              | ```                               |
++----------------------------------+-----------------------------------+
+| ```                              | ``` yaml                          |
+| --citeproc \                     | filters:                          |
+|  --lua-filter count-words.lua \  |   - citeproc                      |
+|  --filter special.lua            |   - count-words.lua               |
+|                                  |   - type: json                    |
+|                                  |     path: special.lua             |
+| ```                              | ```                               |
++----------------------------------+-----------------------------------+
+| ```                              | ``` yaml                          |
+| --metadata key=value \           | metadata:                         |
+|  --metadata key2                 |   key: value                      |
+|                                  |   key2: true                      |
+| ```                              | ```                               |
++----------------------------------+-----------------------------------+
+| ```                              | ``` yaml                          |
+| --metadata-file meta.yaml        | metadata-files:                   |
+|                                  |   - meta.yaml                     |
+| ```                              | ```                               |
+|                                  | ``` yaml                          |
+|                                  | metadata-file: meta.yaml          |
+|                                  | ```                               |
++----------------------------------+-----------------------------------+
+| ```                              | ``` yaml                          |
+| --preserve-tabs                  | preserve-tabs: true               |
+| ```                              | ```                               |
++----------------------------------+-----------------------------------+
+| ```                              | ``` yaml                          |
+| --tab-stop 8                     | tab-stop: 8                       |
+| ```                              | ```                               |
++----------------------------------+-----------------------------------+
+| ```                              | ``` yaml                          |
+| --track-changes accept           | track-changes: accept             |
+| ```                              | ```                               |
++----------------------------------+-----------------------------------+
+| ```                              | ``` yaml                          |
+| --extract-media dir              | extract-media: dir                |
+| ```                              | ```                               |
++----------------------------------+-----------------------------------+
+| ```                              | ``` yaml                          |
+| --abbreviations abbrevs.txt      | abbreviations: abbrevs.txt        |
+| ```                              | ```                               |
++----------------------------------+-----------------------------------+
+| ```                              | ``` yaml                          |
+| --typst-input foo=bar            | typst-inputs:                     |
+|                                  |   foo: bar                        |
+| ```                              | ```                               |
++----------------------------------+-----------------------------------+
+| ```                              | ``` yaml                          |
+| --trace                          | trace: true                       |
+| ```                              | ```                               |
++----------------------------------+-----------------------------------+
+
+Metadata values specified in a defaults file are parsed as literal
+string text, not Markdown.
+
+Filters will be assumed to be Lua filters if they have the `.lua`
+extension, and JSON filters otherwise.  But the filter type can also be
+specified explicitly, as shown.  Filters are run in the order specified.
+To include the built-in citeproc filter, use either `citeproc` or
+`{type: citeproc}`.
+
+## General writer options
+
++----------------------------------+-----------------------------------+
+| command line                     | defaults file                     |
++:=================================+:==================================+
+| ```                              | ``` yaml                          |
+| --standalone                     | standalone: true                  |
+| ```                              | ```                               |
++----------------------------------+-----------------------------------+
+| ```                              | ``` yaml                          |
+| --template letter                | template: letter                  |
+| ```                              | ```                               |
++----------------------------------+-----------------------------------+
+| ```                              | ``` yaml                          |
+| --variable key=val \             | variables:                        |
+|   --variable key2                |   key: val                        |
+|                                  |   key2: true                      |
+| ```                              | ```                               |
++----------------------------------+-----------------------------------+
+| ```                              | ``` yaml                          |
+| --eol nl                         | eol: nl                           |
+| ```                              | ```                               |
++----------------------------------+-----------------------------------+
+| ```                              | ``` yaml                          |
+| --dpi 300                        | dpi: 300                          |
+| ```                              | ```                               |
++----------------------------------+-----------------------------------+
+| ```                              | ``` yaml                          |
+| --wrap preserve                  | wrap: "preserve"                  |
+| ```                              | ```                               |
++----------------------------------+-----------------------------------+
+| ```                              | ``` yaml                          |
+| --columns 72                     | columns: 72                       |
+| ```                              | ```                               |
++----------------------------------+-----------------------------------+
+| ```                              | ``` yaml                          |
+| --table-of-contents              | table-of-contents: true           |
+| ```                              | ```                               |
++----------------------------------+-----------------------------------+
+| ```                              | ``` yaml                          |
+| --toc                            | toc: true                         |
+| ```                              | ```                               |
++----------------------------------+-----------------------------------+
+| ```                              | ``` yaml                          |
+| --toc-depth 3                    | toc-depth: 3                      |
+| ```                              | ```                               |
++----------------------------------+-----------------------------------+
+| ```                              | ``` yaml                          |
+| --strip-comments                 | strip-comments: true              |
+| ```                              | ```                               |
++----------------------------------+-----------------------------------+
+| ```                              | ``` yaml                          |
+| --no-highlight                   | syntax-highlighting: 'none'       |
+| ```                              | ```                               |
++----------------------------------+-----------------------------------+
+| ```                              | ``` yaml                          |
+| --syntax-highlighting kate       | syntax-highlighting: kate         |
+| ```                              | ```                               |
++----------------------------------+-----------------------------------+
+| ```                              | ``` yaml                          |
+| --syntax-definition mylang.xml   | syntax-definitions:               |
+|                                  |   - mylang.xml                    |
+| ```                              | ```                               |
+|                                  | ``` yaml                          |
+|                                  | syntax-definition: mylang.xml     |
+|                                  | ```                               |
++----------------------------------+-----------------------------------+
+| ```                              | ``` yaml                          |
+| --include-in-header inc.tex      | include-in-header:                |
+|                                  |   - inc.tex                       |
+| ```                              | ```                               |
++----------------------------------+-----------------------------------+
+| ```                              | ``` yaml                          |
+| --include-before-body inc.tex    | include-before-body:              |
+|                                  |   - inc.tex                       |
+| ```                              | ```                               |
++----------------------------------+-----------------------------------+
+| ```                              | ``` yaml                          |
+| --include-after-body inc.tex     | include-after-body:               |
+|                                  |   - inc.tex                       |
+| ```                              | ```                               |
++----------------------------------+-----------------------------------+
+| ```                              | ``` yaml                          |
+| --resource-path .:foo            | resource-path: ['.','foo']        |
+| ```                              | ```                               |
++----------------------------------+-----------------------------------+
+| ```                              | ``` yaml                          |
+| --request-header foo:bar         | request-headers:                  |
+|                                  |   - ["User-Agent", "Mozilla/5.0"] |
+| ```                              | ```                               |
++----------------------------------+-----------------------------------+
+| ```                              | ``` yaml                          |
+| --no-check-certificate           | no-check-certificate: true        |
+| ```                              | ```                               |
++----------------------------------+-----------------------------------+
+
+
+## Options affecting specific writers
+
++----------------------------------+-----------------------------------+
+| command line                     | defaults file                     |
++:=================================+:==================================+
+| ```                              | ``` yaml                          |
+| --self-contained                 | self-contained: true              |
+| ```                              | ```                               |
++----------------------------------+-----------------------------------+
+| ```                              | ``` yaml                          |
+| --link-images                    | link-images: true                 |
+| ```                              | ```                               |
++----------------------------------+-----------------------------------+
+| ```                              | ``` yaml                          |
+| --html-q-tags                    | html-q-tags: true                 |
+| ```                              | ```                               |
++----------------------------------+-----------------------------------+
+| ```                              | ``` yaml                          |
+| --ascii                          | ascii: true                       |
+| ```                              | ```                               |
++----------------------------------+-----------------------------------+
+| ```                              | ``` yaml                          |
+| --reference-links                | reference-links: true             |
+| ```                              | ```                               |
++----------------------------------+-----------------------------------+
+| ```                              | ``` yaml                          |
+| --reference-location block       | reference-location: block         |
+| ```                              | ```                               |
++----------------------------------+-----------------------------------+
+| ```                              | ``` yaml                          |
+| --figure-caption-position=above  | figure-caption-position: above    |
+| ```                              | ```                               |
++----------------------------------+-----------------------------------+
+| ```                              | ``` yaml                          |
+| --table-caption-position=below   | table-caption-position: below     |
+| ```                              | ```                               |
++----------------------------------+-----------------------------------+
+| ```                              | ``` yaml                          |
+| --markdown-headings atx          | markdown-headings: atx            |
+| ```                              | ```                               |
++----------------------------------+-----------------------------------+
+| ```                              | ``` yaml                          |
+| --list-tables                    | list-tables: true                 |
+| ```                              | ```                               |
++----------------------------------+-----------------------------------+
+| ```                              | ``` yaml                          |
+| --top-level-division chapter     | top-level-division: chapter       |
+| ```                              | ```                               |
++----------------------------------+-----------------------------------+
+| ```                              | ``` yaml                          |
+| --number-sections                | number-sections: true             |
+| ```                              | ```                               |
++----------------------------------+-----------------------------------+
+| ```                              | ``` yaml                          |
+| --number-offset=1,4              | number-offset: \[1,4\]            |
+| ```                              | ```                               |
++----------------------------------+-----------------------------------+
+| ```                              | ``` yaml                          |
+| --listings                       | listings: true                    |
+| ```                              | ```                               |
++----------------------------------+-----------------------------------+
+| ```                              | ``` yaml                          |
+| --list-of-figures                | list-of-figures: true             |
+| ```                              | ```                               |
++----------------------------------+-----------------------------------+
+| ```                              | ``` yaml                          |
+| --lof                            | lof: true                         |
+| ```                              | ```                               |
++----------------------------------+-----------------------------------+
+| ```                              | ``` yaml                          |
+| --list-of-tables                 | list-of-tables: true              |
+| ```                              | ```                               |
++----------------------------------+-----------------------------------+
+| ```                              | ``` yaml                          |
+| --lot                            | lot: true                         |
+| ```                              | ```                               |
++----------------------------------+-----------------------------------+
+| ```                              | ``` yaml                          |
+| --incremental                    | incremental: true                 |
+| ```                              | ```                               |
++----------------------------------+-----------------------------------+
+| ```                              | ``` yaml                          |
+| --slide-level 2                  | slide-level: 2                    |
+| ```                              | ```                               |
++----------------------------------+-----------------------------------+
+| ```                              | ``` yaml                          |
+| --section-divs                   | section-divs: true                |
+| ```                              | ```                               |
++----------------------------------+-----------------------------------+
+| ```                              | ``` yaml                          |
+| --email-obfuscation references   | email-obfuscation: references     |
+| ```                              | ```                               |
++----------------------------------+-----------------------------------+
+| ```                              | ``` yaml                          |
+| --id-prefix ch1                  | identifier-prefix: ch1            |
+| ```                              | ```                               |
++----------------------------------+-----------------------------------+
+| ```                              | ``` yaml                          |
+| --title-prefix MySite            | title-prefix: MySite              |
+| ```                              | ```                               |
++----------------------------------+-----------------------------------+
+| ```                              | ``` yaml                          |
+| --css styles/screen.css  \       | css:                              |
+|   --css styles/special.css       |   - styles/screen.css             |
+|                                  |   - styles/special.css            |
+| ```                              | ```                               |
++----------------------------------+-----------------------------------+
+| ```                              | ``` yaml                          |
+| --reference-doc my.docx          | reference-doc: my.docx            |
+| ```                              | ```                               |
++----------------------------------+-----------------------------------+
+| ```                              | ``` yaml                          |
+| --epub-cover-image cover.jpg     | epub-cover-image: cover.jpg       |
+| ```                              | ```                               |
++----------------------------------+-----------------------------------+
+| ```                              | ``` yaml                          |
+| --epub-title-page=false          | epub-title-page: false            |
+| ```                              | ```                               |
++----------------------------------+-----------------------------------+
+| ```                              | ``` yaml                          |
+| --epub-metadata meta.xml         | epub-metadata: meta.xml           |
+| ```                              | ```                               |
++----------------------------------+-----------------------------------+
+| ```                              | ``` yaml                          |
+| --epub-embed-font special.otf \  | epub-fonts:                       |
+|   --epub-embed-font headline.otf |   - special.otf                   |
+|                                  |   - headline.otf                  |
+| ```                              | ```                               |
++----------------------------------+-----------------------------------+
+| ```                              | ``` yaml                          |
+| --split-level 2                  | split-level: 2                    |
+| ```                              | ```                               |
++----------------------------------+-----------------------------------+
+| ```                              | ``` yaml                          |
+| --chunk-template="%i.html"       | chunk-template: "%i.html"         |
+| ```                              | ```                               |
++----------------------------------+-----------------------------------+
+| ```                              | ``` yaml                          |
+| --epub-subdirectory=""           | epub-subdirectory: ''             |
+| ```                              | ```                               |
++----------------------------------+-----------------------------------+
+| ```                              | ``` yaml                          |
+| --ipynb-output best              | ipynb-output: best                |
+| ```                              | ```                               |
++----------------------------------+-----------------------------------+
+| ```                              | ``` yaml                          |
+| --pdf-engine xelatex             | pdf-engine: xelatex               |
+| ```                              | ```                               |
++----------------------------------+-----------------------------------+
+| ```                              | ``` yaml                          |
+| --pdf-engine-opt=--shell-escape  | pdf-engine-opts:                  |
+|                                  |   - '-shell-escape'               |
+| ```                              | ```                               |
+|                                  | ``` yaml                          |
+|                                  | pdf-engine-opt: '-shell-escape'   |
+|                                  | ```                               |
++----------------------------------+-----------------------------------+
+
+## Citation rendering
+
++----------------------------------+-----------------------------------+
+| command line                     | defaults file                     |
++:=================================+:==================================+
+| ```                              | ``` yaml                          |
+| --citeproc                       | citeproc: true                    |
+| ```                              | ```                               |
++----------------------------------+-----------------------------------+
+| ```                              | ``` yaml                          |
+| --bibliography logic.bib         | bibliography: logic.bib           |
+| ```                              | ```                               |
++----------------------------------+-----------------------------------+
+| ```                              | ``` yaml                          |
+| --csl ieee.csl                   | csl: ieee.csl                     |
+| ```                              | ```                               |
++----------------------------------+-----------------------------------+
+| ```                              | ``` yaml                          |
+| --citation-abbreviations ab.json | citation-abbreviations: ab.json   |
+| ```                              | ```                               |
++----------------------------------+-----------------------------------+
+| ```                              | ``` yaml                          |
+| --natbib                         | cite-method: natbib               |
+| ```                              | ```                               |
++----------------------------------+-----------------------------------+
+| ```                              | ``` yaml                          |
+| --biblatex                       | cite-method: biblatex             |
+| ```                              | ```                               |
++----------------------------------+-----------------------------------+
+
+`cite-method` can be `citeproc`, `natbib`, or `biblatex`. This only
+affects LaTeX output.  If you want to use citeproc to format citations,
+you should also set 'citeproc: true'.
+
+If you need control over when the citeproc processing is done relative
+to other filters, you should instead use `citeproc` in the list
+of `filters` (see [Reader options](#reader-options-1)).
+
+## Math rendering in HTML
+
++----------------------------------+-----------------------------------+
+| command line                     | defaults file                     |
++:=================================+:==================================+
+| ```                              | ``` yaml                          |
+| --mathjax                        | html-math-method:                 |
+|                                  |   method: mathjax                 |
+| ```                              | ```                               |
++----------------------------------+-----------------------------------+
+| ```                              | ``` yaml                          |
+| --mathml                         | html-math-method:                 |
+|                                  |   method: mathml                  |
+| ```                              | ```                               |
++----------------------------------+-----------------------------------+
+| ```                              | ``` yaml                          |
+| --webtex                         | html-math-method:                 |
+|                                  |   method: webtex                  |
+| ```                              | ```                               |
++----------------------------------+-----------------------------------+
+| ```                              | ``` yaml                          |
+| --katex                          | html-math-method:                 |
+|                                  |   method: katex                   |
+| ```                              | ```                               |
++----------------------------------+-----------------------------------+
+| ```                              | ``` yaml                          |
+| --gladtex                        | html-math-method:                 |
+|                                  |   method: gladtex                 |
+| ```                              | ```                               |
++----------------------------------+-----------------------------------+
+
+In addition to the values listed above, `method` can have the
+value `plain`.
+
+If the command line option accepts a URL argument, an `url:` field can
+be added to `html-math-method:`.
+
+## Options for wrapper scripts
+
++----------------------------------+-----------------------------------+
+| command line                     | defaults file                     |
++:=================================+:==================================+
+| ```                              | ``` yaml                          |
+| --dump-args                      | dump-args: true                   |
+| ```                              | ```                               |
++----------------------------------+-----------------------------------+
+| ```                              | ``` yaml                          |
+| --ignore-args                    | ignore-args: true                 |
+| ```                              | ```                               |
++----------------------------------+-----------------------------------+
+
+# Templates
+
+When the `-s/--standalone` option is used, pandoc uses a template to
+add header and footer material that is needed for a self-standing
+document.  To see the default template that is used, just type
+
+    pandoc -D *FORMAT*
+
+where *FORMAT* is the name of the output format. A custom template
+can be specified using the `--template` option.  You can also override
+the system default templates for a given output format *FORMAT*
+by putting a file `templates/default.*FORMAT*` in the user data
+directory (see `--data-dir`, above). *Exceptions:*
+
+- For `odt` output, customize the `default.opendocument` template.
+- For `docx` output, customize the `default.openxml` template.
+- For `pdf` output, customize the `default.latex` template
+  (or the `default.context` template, if you use `-t context`,
+  or the `default.ms` template, if you use `-t ms`, or the
+  `default.html` template, if you use `-t html`).
+- `pptx` has no template.
+
+Note that `docx`, `odt`, and `pptx` output can also be customized
+using `--reference-doc`.  Use a reference doc to adjust the styles
+in your document; use a template to handle variable interpolation and
+customize the presentation of metadata, the position of the table
+of contents, boilerplate text, etc.
+
+Templates contain *variables*, which allow for the inclusion of
+arbitrary information at any point in the file. They may be set at the
+command line using the `-V/--variable` option. If a variable is not set,
+pandoc will look for the key in the document's metadata, which can be set
+using either [YAML metadata blocks][Extension: `yaml_metadata_block`]
+or with the `-M/--metadata` option.  In addition, some variables
+are given default values by pandoc.  See [Variables] below for
+a list of variables used in pandoc's default templates.
+
+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
+is to fork the [pandoc-templates] repository and merge in
+changes after each pandoc release.
+
+  [pandoc-templates]: https://github.com/jgm/pandoc-templates
+
+## Template syntax
+
+### Comments
+
+Anything between the sequence `$--` and the end of the
+line will be treated as a comment and omitted from the output.
+
+### Delimiters
+
+To mark variables and control structures in the template,
+either `$`...`$` or `${`...`}` may be used as delimiters.
+The styles may also be mixed in the same template, but the
+opening and closing delimiter must match in each case.  The
+opening delimiter may be followed by one or more spaces
+or tabs, which will be ignored. The closing delimiter may
+be preceded by one or more spaces or tabs, which will be
+ignored.
+
+To include a literal `$` in the document, use `$$`.
+
+### Interpolated variables
+
+A slot for an interpolated variable is a variable name surrounded
+by matched delimiters.  Variable names must begin with a letter
+and can contain letters, numbers, `_`, `-`, and `.`.  The
+keywords `it`, `if`, `else`, `endif`, `for`, `sep`, and `endfor` may
+not be used as variable names. Examples:
+
+```
+$foo$
+$foo.bar.baz$
+$foo_bar.baz-bim$
+$ foo $
+${foo}
+${foo.bar.baz}
+${foo_bar.baz-bim}
+${ foo }
+```
+
+Variable names with periods are used to get at structured
+variable values.  So, for example, `employee.salary` will return the
+value of the `salary` field of the object that is the value of
+the `employee` field.
+
+- If the value of the variable is a simple value, it will be
+  rendered verbatim.  (Note that no escaping is done;
+  the assumption is that the calling program will escape
+  the strings appropriately for the output format.)
+- If the value is a list, the values will be concatenated.
+- If the value is a map, the string `true` will be rendered.
+- Every other value will be rendered as the empty string.
+
+### Conditionals
+
+A conditional begins with `if(variable)` (enclosed in
+matched delimiters) and ends with `endif` (enclosed in matched
+delimiters).  It may optionally contain an `else` (enclosed in
+matched delimiters).  The `if` section is used if
+`variable` has a true value, otherwise the `else`
+section is used (if present).  The following values count
+as true:
+
+- any map
+- any array containing at least one true value
+- any nonempty string
+- boolean True
+
+Note that in YAML metadata (and metadata specified on the
+command line using `-M/--metadata`), unquoted `true` and `false` will be
+interpreted as Boolean values. But a variable specified on the
+command line using `-V/--variable` will always be given a string
+value. Hence a conditional `if(foo)` will be triggered if you
+use `-V foo=false`, but not if you use `-M foo=false`.
+
+Examples:
+
+```
+$if(foo)$bar$endif$
+
+$if(foo)$
+  $foo$
+$endif$
+
+$if(foo)$
+part one
+$else$
+part two
+$endif$
+
+${if(foo)}bar${endif}
+
+${if(foo)}
+  ${foo}
+${endif}
+
+${if(foo)}
+${ foo.bar }
+${else}
+no foo!
+${endif}
+```
+
+The keyword `elseif` may be used to simplify complex nested
+conditionals:
+
+```
+$if(foo)$
+XXX
+$elseif(bar)$
+YYY
+$else$
+ZZZ
+$endif$
+```
+
+### For loops
+
+A for loop begins with `for(variable)` (enclosed in
+matched delimiters) and ends with `endfor` (enclosed in matched
+delimiters).
+
+- If `variable` is an array, the material inside the loop will
+  be evaluated repeatedly, with `variable` being set to each
+  value of the array in turn, and concatenated.
+- If `variable` is a map, the material inside will be set to
+  the map.
+- If the value of the associated variable is not an array or
+  a map, a single iteration will be performed on its value.
+
+Examples:
+
+```
+$for(foo)$$foo$$sep$, $endfor$
+
+$for(foo)$
+  - $foo.last$, $foo.first$
+$endfor$
+
+${ for(foo.bar) }
+  - ${ foo.bar.last }, ${ foo.bar.first }
+${ endfor }
+
+$for(mymap)$
+$it.name$: $it.office$
+$endfor$
+```
+
+You may optionally specify a separator between consecutive
+values using `sep` (enclosed in matched delimiters).  The
+material between `sep` and the `endfor` is the separator.
+
+```
+${ for(foo) }${ foo }${ sep }, ${ endfor }
+```
+
+Instead of using `variable` inside the loop, the special
+anaphoric keyword `it` may be used.
+
+```
+${ for(foo.bar) }
+  - ${ it.last }, ${ it.first }
+${ endfor }
+```
+
+### Partials
+
+Partials (subtemplates stored in different files) may be
+included by using the name of the partial, followed
+by `()`, for example:
+
+```
+${ styles() }
+```
+
+Partials will be sought in the directory containing
+the main template. The file name will be assumed to
+have the same extension as the main template if it
+lacks an extension. When calling the partial, the
+full name including file extension can also be used:
+
+```
+${ styles.html() }
+```
+
+(If a partial is not found in the directory of the
+template and the template path is given as a relative
+path, it will also be sought in the `templates`
+subdirectory of the user data directory.)
+
+Partials may optionally be applied to variables using
+a colon:
+
+```
+${ date:fancy() }
+
+${ articles:bibentry() }
+```
+
+If `articles` is an array, this will iterate over its
+values, applying the partial `bibentry()` to each one.  So the
+second example above is equivalent to
+
+```
+${ for(articles) }
+${ it:bibentry() }
+${ endfor }
+```
+
+Note that the anaphoric keyword `it` must be used when
+iterating over partials.  In the above examples,
+the `bibentry` partial should contain `it.title`
+(and so on) instead of `articles.title`.
+
+Final newlines are omitted from included partials.
+
+Partials may include other partials.
+
+A separator between values of an array may be specified
+in square brackets, immediately after the variable name
+or partial:
+
+```
+${months[, ]}
+
+${articles:bibentry()[; ]}
+```
+
+The separator in this case is literal and (unlike with `sep`
+in an explicit `for` loop) cannot contain interpolated
+variables or other template directives.
+
+### Nesting
+
+To ensure that content is "nested," that is, subsequent lines
+indented, use the `^` directive:
+
+```
+$item.number$  $^$$item.description$ ($item.price$)
+```
+
+In this example, if `item.description` has multiple lines,
+they will all be indented to line up with the first line:
+
+```
+00123  A fine bottle of 18-year old
+       Oban whiskey. ($148)
+```
+
+To nest multiple lines to the same level, align them
+with the `^` directive in the template. For example:
+
+```
+$item.number$  $^$$item.description$ ($item.price$)
+               (Available til $item.sellby$.)
+```
+
+will produce
+
+```
+00123  A fine bottle of 18-year old
+       Oban whiskey. ($148)
+       (Available til March 30, 2020.)
+```
+
+If a variable occurs by itself on a line, preceded by whitespace
+and not followed by further text or directives on the same line,
+and the variable's value contains multiple lines, it will be
+nested automatically.
+
+### Breakable spaces
+
+Normally, spaces in the template itself (as opposed to values of
+the interpolated variables) are not breakable, but they can be
+made breakable in part of the template by using the `~` keyword
+(ended with another `~`).
+
+```
+$~$This long line may break if the document is rendered
+with a short line length.$~$
+```
+
+### Pipes
+
+A pipe transforms the value of a variable or partial. Pipes are
+specified using a slash (`/`) between the variable name (or partial)
+and the pipe name. Example:
+
+```
+$for(name)$
+$name/uppercase$
+$endfor$
+
+$for(metadata/pairs)$
+- $it.key$: $it.value$
+$endfor$
+
+$employee:name()/uppercase$
+```
+
+Pipes may be chained:
+
+```
+$for(employees/pairs)$
+$it.key/alpha/uppercase$. $it.name$
+$endfor$
+```
+
+Some pipes take parameters:
+
+```
+|----------------------|------------|
+$for(employee)$
+$it.name.first/uppercase/left 20 "| "$$it.name.salary/right 10 " | " " |"$
+$endfor$
+|----------------------|------------|
+```
+
+Currently the following pipes are predefined:
+
+- `pairs`:  Converts a map or array to an array of maps,
+  each with `key` and `value` fields.  If the original
+  value was an array, the `key` will be the array index,
+  starting with 1.
+
+- `uppercase`:  Converts text to uppercase.
+
+- `lowercase`:  Converts text to lowercase.
+
+- `length`:  Returns the length of the value:  number
+  of characters for a textual value, number of elements
+  for a map or array.
+
+- `reverse`:  Reverses a textual value or array,
+  and has no effect on other values.
+
+- `first`: Returns the first value of an array, if
+  applied to a non-empty array; otherwise returns
+  the original value.
+
+- `last`: Returns the last value of an array, if
+  applied to a non-empty array; otherwise returns
+  the original value.
+
+- `rest`: Returns all but the first value of an array, if
+  applied to a non-empty array; otherwise returns
+  the original value.
+
+- `allbutlast`: Returns all but the last value of an array, if
+  applied to a non-empty array; otherwise returns
+  the original value.
+
+- `chomp`:  Removes trailing newlines (and breakable space).
+
+- `nowrap`:  Disables line wrapping on breakable spaces.
+
+- `alpha`:  Converts textual values that can be
+  read as an integer into lowercase alphabetic
+  characters `a..z` (mod 26). This can be used to get lettered
+  enumeration from array indices.  To get uppercase
+  letters, chain with `uppercase`.
+
+- `roman`:  Converts textual values that can be
+  read as an integer into lowercase roman numerals.
+  This can be used to get lettered enumeration from array indices.
+  To get uppercase roman, chain with `uppercase`.
+
+- `left n "leftborder" "rightborder"`:  Renders a textual value
+  in a block of width `n`, aligned to the left, with an optional
+  left and right border.  Has no effect on other values. This
+  can be used to align material in tables.  Widths are positive
+  integers indicating the number of characters.  Borders
+  are strings inside double quotes; literal `"` and `\` characters
+  must be backslash-escaped.
+
+- `right n "leftborder" "rightborder"`:  Renders a textual value
+  in a block of width `n`, aligned to the right, and has no
+  effect on other values.
+
+- `center n "leftborder" "rightborder"`:  Renders a textual
+  value in a block of width `n`, aligned to the center, and has
+  no effect on other values.
+
+
+## Variables
+
+### Metadata variables
+
+`title`, `author`, `date`
+:   allow identification of basic aspects of the document.  Included
+    in PDF metadata through LaTeX and ConTeXt.  These can be set
+    through a [pandoc title block][Extension: `pandoc_title_block`],
+    which allows for multiple authors, or through a
+    [YAML metadata block][Extension: `yaml_metadata_block`]:
+
+        ---
+        author:
+        - Aristotle
+        - Peter Abelard
+        ...
+
+    Note that if you just want to set PDF or HTML metadata, without
+    including a title block in the document itself, you can
+    set the `title-meta`, `author-meta`, and `date-meta`
+    variables.  (By default these are set automatically, based
+    on `title`, `author`, and `date`.) The page title in HTML
+    is set by `pagetitle`, which is equal to `title` by default.
+
+`subtitle`
+:   document subtitle, included in HTML, EPUB, LaTeX, ConTeXt, and docx
+    documents
+
+`abstract`
+:   document summary, included in HTML, LaTeX, ConTeXt, AsciiDoc, and docx
+    documents
+
+`abstract-title`
+:   title of abstract, currently used only in HTML, EPUB, docx, and Typst.
+    This will be set automatically to a localized value,
+    depending on `lang`, but can be manually overridden.
+
+`keywords`
+:   list of keywords to be included in HTML, PDF, ODT, pptx, docx
+    and AsciiDoc metadata; repeat as for `author`, above
+
+`subject`
+:   document subject, included in ODT, PDF, docx, EPUB, and pptx metadata
+
+`description`
+:   document description, included in ODT, docx and pptx metadata. Some
+    applications show this as `Comments` metadata.
+
+`category`
+:   document category, included in docx and pptx metadata
+
+Additionally,
+any root-level string metadata, not included in ODT, docx
+or pptx metadata is added as a *custom property*.
+The following [YAML] metadata block for instance:
+
+    ---
+    title:  'This is the title'
+    subtitle: "This is the subtitle"
+    author:
+    - Author One
+    - Author Two
+    description: |
+        This is a long
+        description.
+
+        It consists of two paragraphs
+    ...
+
+will include `title`, `author` and `description` as standard document
+properties and `subtitle` as a custom property when converting to docx,
+ODT or pptx.
+
+### Language variables
+
+`lang`
+:   identifies the main language of the document using IETF language
+    tags (following the [BCP 47] standard), such as `en` or `en-GB`.
+    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
+        ...
+
+        Text in the main document language (British English).
+
+        ::: {lang=fr-CA}
+        > Cette citation est écrite en français canadien.
+        :::
+
+        More text in English. ['Zitat auf Deutsch.']{lang=de}
+
+`dir`
+:   the base script direction, either `rtl` (right-to-left)
+    or `ltr` (left-to-right).
+
+    For bidirectional documents, native pandoc `span`s and
+    `div`s with the `dir` attribute (value `rtl` or `ltr`) can
+    be used to override the base direction in some output
+    formats.  This may not always be necessary if the final
+    renderer (e.g. the browser, when generating HTML) supports
+    the [Unicode Bidirectional Algorithm].
+
+    When using LaTeX for bidirectional documents, only the
+    `xelatex` engine is fully supported (use
+    `--pdf-engine=xelatex`).
+
+[BCP 47]: https://tools.ietf.org/html/bcp47
+[Unicode Bidirectional Algorithm]: https://www.w3.org/International/articles/inline-bidi-markup/uba-basics
+[Language subtag lookup]: https://r12a.github.io/app-subtags/
+
+### Variables for HTML
+
+`document-css`
+:   Enables inclusion of most of the [CSS] in the `styles.html`
+    [partial](#partials) (have a look with
+    `pandoc --print-default-data-file=templates/styles.html`).
+    Unless you use `--css`, this variable
+    is set to `true` by default. You can disable it with
+    e.g. `pandoc -M document-css=false`.
+
+`mainfont`
+:   sets the CSS `font-family` property on the `html` element.
+
+`fontsize`
+:   sets the base CSS `font-size`, which you'd usually set
+    to e.g. `20px`, but it also accepts `pt`
+    (12pt = 16px in most browsers).
+
+`fontcolor`
+:   sets the CSS `color` property on the `html` element.
+
+`linkcolor`
+:   sets the CSS `color` property on all links.
+
+`monofont`
+:   sets the CSS `font-family` property on `code` elements.
+
+`monobackgroundcolor`
+:   sets the CSS `background-color` property on `code` elements
+    and adds extra padding.
+
+`linestretch`
+:   sets the CSS `line-height` property on the `html` element,
+    which is preferred to be unitless.
+
+`maxwidth`
+:   sets the CSS `max-width` property (default is 36em).
+
+`backgroundcolor`
+:   sets the CSS `background-color` property on the `html` element.
+
+`margin-left`, `margin-right`, `margin-top`, `margin-bottom`
+:   sets the corresponding CSS `padding` properties on the `body` element.
+
+To override or extend some [CSS] for just one document, include for example:
+
+    ---
+    header-includes: |
+      <style>
+      blockquote {
+        font-style: italic;
+      }
+      tr.even {
+        background-color: #f0f0f0;
+      }
+      td, th {
+        padding: 0.5em 2em 0.5em 0.5em;
+      }
+      tbody {
+        border-bottom: none;
+      }
+      </style>
+    ---
+
+[CSS]: https://developer.mozilla.org/en-US/docs/Learn/CSS
+
+### Variables for HTML math
+
+`classoption`
+:   when using `--katex`, you can render display math equations
+    flush left using [YAML metadata](#layout) or with `-M
+    classoption=fleqn`.
+
+### Variables for HTML slides
+
+These affect HTML output when [producing slide shows with
+pandoc](#slide-shows).
+
+`institute`
+:   author affiliations: can be a list when there are multiple authors
+
+`revealjs-url`
+:   base URL for reveal.js documents (defaults to
+    `https://unpkg.com/reveal.js@^5`)
+
+`s5-url`
+:   base URL for S5 documents (defaults to `s5/default`)
+
+`slidy-url`
+:   base URL for Slidy documents (defaults to
+    `https://www.w3.org/Talks/Tools/Slidy2`)
+
+`slideous-url`
+:   base URL for Slideous documents (defaults to `slideous`)
+
+`title-slide-attributes`
+:   additional attributes for the title slide of reveal.js slide shows.
+    See [background in reveal.js, beamer, and pptx] for an example.
+
+`highlightjs-theme`
+:   highlight.js theme for code highlighting when using
+    `--syntax-highlighting=idiomatic` with reveal.js (defaults to
+    `monokai`). See the [highlight.js demo page] for available themes.
+
+[highlight.js demo page]: https://highlightjs.org/demo
+
+All [reveal.js configuration options] are available as variables.
+To turn off boolean flags that default to true in reveal.js, use `0`.
+
+[reveal.js configuration options]: https://revealjs.com/config/
+
+### Variables for Beamer slides
+
+These variables change the appearance of PDF slides using [`beamer`].
+
+`aspectratio`
+:   slide aspect ratio (`43` for 4:3 [default], `169` for 16:9,
+    `1610` for 16:10, `149` for 14:9, `141` for 1.41:1, `54` for 5:4,
+    `32` for 3:2)
+
+`beameroption`
+:   add extra beamer option with `\setbeameroption{}`
+
+`institute`
+:   author affiliations: can be a list when there are multiple authors
+
+`logo`
+:   logo image for slides
+
+`logooptions`
+:   options for logo image (e.g., `width`, `height`)
+
+`navigation`
+:   controls navigation symbols (default is `empty` for no navigation
+    symbols; other valid values are `frame`, `vertical`, and `horizontal`)
+
+`section-titles`
+:   enables "title pages" for new sections (default is true)
+
+`theme`, `colortheme`, `fonttheme`, `innertheme`, `outertheme`
+:   beamer themes
+
+`themeoptions`, `colorthemeoptions`, `fontthemeoptions`, `innerthemeoptions`, `outerthemeoptions`
+:   options for LaTeX beamer themes (lists)
+
+`titlegraphic`
+:   image for title slide: can be a list
+
+`titlegraphicoptions`
+:   options for title slide image (e.g., `width`, `height`)
+
+`shorttitle`, `shortsubtitle`, `shortauthor`, `shortinstitute`, `shortdate`
+:   some beamer themes use short versions of the title, subtitle, author,
+    institute, date
+
+### Variables for PowerPoint
+
+These variables control the visual aspects of a slide show that
+are not easily controlled via templates.
+
+`monofont`
+:   font to use for code.
+
+### Variables for LaTeX
+
+Pandoc uses these variables when [creating a PDF] with a LaTeX engine.
+
+#### Layout
+
+`block-headings`
+:   make `\paragraph` and `\subparagraph` (fourth- and
+    fifth-level headings, or fifth- and sixth-level with book
+    classes) free-standing rather than run-in; requires further
+    formatting to distinguish from `\subsubsection` (third- or
+    fourth-level headings). Instead of using this option,
+    [KOMA-Script] can adjust headings more extensively:
+
+        ---
+        documentclass: scrartcl
+        header-includes: |
+          \RedeclareSectionCommand[
+            beforeskip=-10pt plus -2pt minus -1pt,
+            afterskip=1sp plus -1sp minus 1sp,
+            font=\normalfont\itshape]{paragraph}
+          \RedeclareSectionCommand[
+            beforeskip=-10pt plus -2pt minus -1pt,
+            afterskip=1sp plus -1sp minus 1sp,
+            font=\normalfont\scshape,
+            indent=0pt]{subparagraph}
+        ...
+
+`classoption`
+:   option for document class, e.g. `oneside`; repeat for multiple options:
+
+        ---
+        classoption:
+        - twocolumn
+        - landscape
+        ...
+
+`documentclass`
+:   document class: usually one of the standard classes,
+    [`article`], [`book`], and [`report`]; the [KOMA-Script]
+    equivalents, `scrartcl`, `scrbook`, and `scrreprt`, which
+    default to smaller margins; or [`memoir`]
+
+`geometry`
+:   option for [`geometry`] package, e.g. `margin=1in`;
+    repeat for multiple options:
+
+        ---
+        geometry:
+        - top=30mm
+        - left=20mm
+        - heightrounded
+        ...
+
+`shorthands`
+:   Enable language-specific shorthands when loading `babel`.
+    (By default, pandoc includes `shorthands=off` when loading
+    `babel`, disabling language-specific shorthands.)
+
+`hyperrefoptions`
+:   option for [`hyperref`] package, e.g. `linktoc=all`;
+    repeat for multiple options:
+
+        ---
+        hyperrefoptions:
+        - linktoc=all
+        - pdfwindowui
+        - pdfpagemode=FullScreen
+        ...
+
+`indent`
+:   if true, pandoc will use document class settings for
+    indentation (the default LaTeX template otherwise removes
+    indentation and adds space between paragraphs)
+
+`linestretch`
+:   adjusts line spacing using the [`setspace`]
+    package, e.g. `1.25`, `1.5`
+
+`margin-left`, `margin-right`, `margin-top`, `margin-bottom`
+:   sets margins if `geometry` is not used (otherwise `geometry`
+    overrides these)
+
+`pagestyle`
+:   control `\pagestyle{}`: the default article class
+    supports `plain` (default), `empty` (no running heads or page numbers),
+    and `headings` (section titles in running heads)
+
+`papersize`
+:   paper size, e.g. `letter`, `a4`
+
+`secnumdepth`
+:   numbering depth for sections (with `--number-sections` option
+    or `numbersections` variable)
+
+`beamerarticle`
+:   produce an article from Beamer slides.  Note: if you set
+    this variable, you must specify the beamer writer but use the
+    default *LaTeX* template: for example,
+    `pandoc -Vbeamerarticle -t beamer --template default.latex`.
+
+`handout`
+:   produce a handout version of Beamer slides (with overlays condensed
+    into single slides)
+
+`csquotes`
+:   load `csquotes` package and use `\enquote` or `\enquote*` for quoted text.
+
+`csquotesoptions`
+:   options to use for `csquotes` package (repeat for multiple options).
+
+`babeloptions`
+:   options to pass to the babel package (may be repeated for
+    multiple options). This defaults to `provide=*` if the main
+    language isn't a European language written with Latin or
+    Cyrillic script or Vietnamese. Most users will not need to
+    adjust the default setting.
+
+#### Fonts
+
+`fontenc`
+:   allows font encoding to be specified through `fontenc` package (with
+    `pdflatex`); default is `T1` (see [LaTeX font encodings guide])
+
+`fontfamily`
+:   font package for use with `pdflatex`:
+    [TeX Live] includes many options, documented in the [LaTeX Font Catalogue].
+    The default is [Latin Modern][`lm`].
+
+`fontfamilyoptions`
+:   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:
+        - osf
+        - p
+        ...
+
+`fontsize`
+:   font size for body text. The standard classes allow 10pt, 11pt, and
+    12pt.  To use another size, set `documentclass` to one of
+    the [KOMA-Script] classes, such as `scrartcl` or `scrbook`.
+
+`mainfont`, `sansfont`, `monofont`, `mathfont`, `CJKmainfont`, `CJKsansfont`, `CJKmonofont`
+:   font families for use with `xelatex` or
+    `lualatex`: take the name of any system font, using the
+    [`fontspec`] package.  `CJKmainfont` uses the [`xecjk`] package if `xelatex` is used,
+    or the [`luatexja`] package if `lualatex` is used.
+
+`mainfontoptions`, `sansfontoptions`, `monofontoptions`, `mathfontoptions`, `CJKoptions`, `luatexjapresetoptions`
+:   options to use with `mainfont`, `sansfont`, `monofont`, `mathfont`,
+    `CJKmainfont` in `xelatex` and `lualatex`.  Allow for any
+    choices available through [`fontspec`]; repeat for multiple
+    options. For example, to use the [TeX Gyre] version of
+    Palatino with lowercase figures:
+
+        ---
+        mainfont: TeX Gyre Pagella
+        mainfontoptions:
+        - Numbers=Lowercase
+        - Numbers=Proportional
+        ...
+
+`mainfontfallback`, `sansfontfallback`, `monofontfallback`
+:   fonts to try if a glyph isn't found in `mainfont`, `sansfont`, or `monofont`
+    respectively. These are lists. The font name must be followed by a colon
+    and optionally a set of options, for example:
+
+        ---
+        mainfontfallback:
+          - "FreeSans:"
+          - "NotoColorEmoji:mode=harf"
+        ...
+
+    Font fallbacks currently only work with `lualatex`.
+
+`babelfonts`
+:   a map of Babel language names (e.g. `chinese`) to the font
+    to be used with the language:
+
+        ---
+        babelfonts:
+          chinese-hant: "Noto Serif CJK TC"
+          russian: "Noto Serif"
+        ...
+
+`microtypeoptions`
+:    options to pass to the microtype package
+
+#### Links
+
+`colorlinks`
+:   add color to link text; automatically enabled if any of
+    `linkcolor`, `filecolor`, `citecolor`, `urlcolor`, or `toccolor` are set
+
+`boxlinks`
+:   add visible box around links (has no effect if `colorlinks` is set)
+
+`linkcolor`, `filecolor`, `citecolor`, `urlcolor`, `toccolor`
+:   color for internal links, external links, citation links, linked
+    URLs, and links in table of contents, respectively: uses options
+    allowed by [`xcolor`], including the `dvipsnames`, `svgnames`, and
+    `x11names` lists
+
+`links-as-notes`
+:   causes links to be printed as footnotes
+
+`urlstyle`
+:   style for URLs (e.g., `tt`, `rm`, `sf`, and, the default, `same`)
+
+#### Front matter
+
+`lof`, `lot`
+:   include list of figures, list of tables (can also be set using
+    `--lof/--list-of-figures`, `--lot/--list-of-tables`)
+
+`thanks`
+:   contents of acknowledgments footnote after document title
+
+`toc`
+:   include table of contents (can also be set using
+    `--toc/--table-of-contents`)
+
+`toc-depth`
+:   level of section to include in table of contents
+
+#### BibLaTeX Bibliographies
+
+These variables function when using BibLaTeX for [citation rendering].
+
+`biblatexoptions`
+:   list of options for biblatex
+
+`biblio-style`
+:   bibliography style, when used with `--natbib` and `--biblatex`
+
+`biblio-title`
+:   bibliography title, when used with `--natbib` and `--biblatex`
+
+`bibliography`
+:   bibliography to use for resolving references
+
+`natbiboptions`
+:   list of options for natbib
+
+#### Other
+
+`pdf-trailer-id`
+:   the PDF trailer ID; must be two PDF byte strings if set,
+    conventionally with 16 bytes each. E.g.,
+    `<00112233445566778899aabbccddeeff>
+    <00112233445566778899aabbccddeeff>`.
+
+    See the section on [reproducible builds].
+
+`pdfstandard`
+:   PDF standard(s) for the document, e.g. `ua-2`, `a-4f`.
+    Supports PDF/A, PDF/X, and PDF/UA variants.
+    Requires LuaLaTeX and LaTeX 2023+. Repeat for multiple standards:
+
+        ---
+        pdfstandard:
+        - ua-2
+        - a-4f
+        ...
+
+[KOMA-Script]: https://ctan.org/pkg/koma-script
+[LaTeX Font Catalogue]: https://tug.org/FontCatalogue/
+[LaTeX font encodings guide]: https://ctan.org/pkg/encguide
+[TeX Gyre]: http://www.gust.org.pl/projects/e-foundry/tex-gyre
+[`article`]: https://ctan.org/pkg/article
+[`book`]: https://ctan.org/pkg/book
+[`libertinus`]: https://ctan.org/pkg/libertinus
+[`memoir`]: https://ctan.org/pkg/memoir
+[`report`]: https://ctan.org/pkg/report
+
+### Variables for ConTeXt
+
+Pandoc uses these variables when [creating a PDF] with ConTeXt.
+
+`fontsize`
+:   font size for body text (e.g. `10pt`, `12pt`)
+
+`headertext`, `footertext`
+:   text to be placed in running header or footer (see [ConTeXt Headers and
+    Footers]); repeat up to four times for different placement
+
+`indenting`
+:   controls indentation of paragraphs, e.g. `yes,small,next` (see
+    [ConTeXt Indentation]); repeat for multiple options
+
+`interlinespace`
+:   adjusts line spacing, e.g. `4ex` (using [`setupinterlinespace`]);
+    repeat for multiple options
+
+`layout`
+:   options for page margins and text arrangement (see [ConTeXt Layout]);
+    repeat for multiple options
+
+`linkcolor`, `contrastcolor`
+:   color for links outside and inside a page, e.g. `red`, `blue` (see
+    [ConTeXt Color])
+
+`linkstyle`
+:   typeface style for links, e.g. `normal`, `bold`, `slanted`, `boldslanted`,
+    `type`, `cap`, `small`
+
+`lof`, `lot`
+:   include list of figures, list of tables
+
+`mainfont`, `sansfont`, `monofont`, `mathfont`
+:   font families: take the name of any system font (see
+    [ConTeXt Font Switching])
+
+`mainfontfallback`, `sansfontfallback`, `monofontfallback`
+:   list of fonts to try, in order, if a glyph is not found in the
+    main font. Use `\definefallbackfamily`-compatible font name syntax.
+    Emoji fonts are unsupported.
+
+`margin-left`, `margin-right`, `margin-top`, `margin-bottom`
+:   sets margins, if `layout` is not used (otherwise `layout`
+    overrides these)
+
+`pagenumbering`
+:   page number style and location (using [`setuppagenumbering`]);
+    repeat for multiple options
+
+`papersize`
+:   paper size, e.g. `letter`, `A4`, `landscape` (see [ConTeXt Paper Setup]);
+    repeat for multiple options
+
+`pdfa`
+:   adds to the preamble the setup necessary to generate PDF/A
+    of the type specified, e.g. `1a:2005`, `2a`. If no type is
+    specified (i.e. the value is set to True, by e.g.
+    `--metadata=pdfa` or `pdfa: true` in a YAML metadata block),
+    `1b:2005` will be used as default, for reasons of backwards
+    compatibility. Using `--variable=pdfa` without specified value
+    is not supported.  To successfully generate PDF/A the required
+    ICC color profiles have to be available and the content and all
+    included files (such as images) have to be standard-conforming.
+    The ICC profiles and output intent may be specified using the
+    variables `pdfaiccprofile` and `pdfaintent`.  See also [ConTeXt
+    PDFA] for more details.
+
+`pdfaiccprofile`
+:   when used in conjunction with `pdfa`, specifies the ICC profile to use
+    in the PDF, e.g. `default.cmyk`. If left unspecified, `sRGB.icc` is
+    used as default. May be repeated to include multiple profiles. Note that
+    the profiles have to be available on the system. They can be obtained
+    from [ConTeXt ICC Profiles].
+
+`pdfaintent`
+:   when used in conjunction with `pdfa`, specifies the output intent for
+    the colors, e.g. `ISO coated v2 300\letterpercent\space (ECI)`
+    If left unspecified, `sRGB IEC61966-2.1` is used as default.
+
+`toc`
+:   include table of contents (can also be set using
+    `--toc/--table-of-contents`)
+
+`urlstyle`
+:   typeface style for links without link text, e.g. `normal`, `bold`, `slanted`, `boldslanted`,
+    `type`, `cap`, `small`
+
+`whitespace`
+:   spacing between paragraphs, e.g. `none`, `small` (using
+    [`setupwhitespace`])
+
+`includesource`
+:   include all source documents as file attachments in the PDF file
+
+[ConTeXt Paper Setup]: https://wiki.contextgarden.net/Document_layout_and_layers/Paper_setup
+[ConTeXt Layout]: https://wiki.contextgarden.net/Document_layout_and_layers/Tutorials
+[ConTeXt Font Switching]: https://wiki.contextgarden.net/Characters_words_and_fonts/Tutorials
+[ConTeXt Color]: https://wiki.contextgarden.net/Color
+[ConTeXt Headers and Footers]: https://wiki.contextgarden.net/Document_layout_and_layers/Headers_and_footers
+[ConTeXt Indentation]: https://wiki.contextgarden.net/Text_blocks/Typography/Indentation
+[ConTeXt PDFA]: https://wiki.contextgarden.net/Input_and_compilation/PDF/PDFA
+[ConTeXt ICC Profiles]: https://wiki.contextgarden.net/Input_and_compilation/PDF/PDFX#ICC_profiles
+[`setupwhitespace`]: https://wiki.contextgarden.net/Command/setupwhitespace
+[`setupinterlinespace`]: https://wiki.contextgarden.net/Command/setupinterlinespace
+[`setuppagenumbering`]: https://wiki.contextgarden.net/Command/setuppagenumbering
+
+### Variables for `wkhtmltopdf`
+
+Pandoc uses these variables when [creating a PDF] with [`wkhtmltopdf`].
+The `--css` option also affects the output.
+
+`footer-html`, `header-html`
+:   add information to the header and footer
+
+`margin-left`, `margin-right`, `margin-top`, `margin-bottom`
+:   set the page margins
+
+`papersize`
+:   sets the PDF paper size
+
+### Variables for man pages
+
+`adjusting`
+:   adjusts text to left (`l`), right (`r`), center (`c`),
+    or both (`b`) margins
+
+`footer`
+:   footer in man pages
+
+`header`
+:   header in man pages
+
+`section`
+:   section number in man pages
+
+### Variables for Texinfo
+
+`version`
+:   version of software (used in title and title page)
+
+`filename`
+:   name of info file to be generated (defaults to a name based on the
+    texi filename)
+
+### Variables for Typst
+
+`template`
+:   Typst template to use (relative path only).
+
+`margin`
+:   A dictionary with the fields defined in the Typst documentation:
+    `x`, `y`, `top`, `bottom`, `left`, `right`.
+
+`papersize`
+:    Paper size: `a4`, `us-letter`, etc.
+
+`mainfont`
+:    Name of system font to use for the main font.
+
+`fontsize`
+:    Font size (e.g., `12pt`).
+
+`section-numbering`
+:    Schema to use for numbering sections, e.g. `1.A.1`.
+
+`page-numbering`
+:    Schema to use for numbering pages, e.g. `1` or `i`, or
+     an empty string to omit page numbering.
+
+`columns`
+:    Number of columns for body text.
+
+`thanks`
+:   contents of acknowledgments footnote after document title
+
+`mathfont`, `codefont`
+:    Name of system font to use for math and code, respectively.
+
+`linestretch`
+:   adjusts line spacing, e.g. `1.25`, `1.5`
+
+`linkcolor`, `filecolor`, `citecolor`
+:   color for external links, internal links, and citation links,
+    respectively: expects a hexadecimal color code
+
+### Variables for ms
+
+`fontfamily`
+:   `A` (Avant Garde), `B` (Bookman), `C` (Helvetica), `HN`
+    (Helvetica Narrow), `P` (Palatino), or `T` (Times New Roman).
+    This setting does not affect source code, which is always
+    displayed using monospace Courier. These built-in fonts are
+    limited in their coverage of characters. Additional fonts may
+    be installed using the script [`install-font.sh`] provided
+    by Peter Schaffter and documented in detail on [his web
+    site][ms-font-steps].
+
+`indent`
+:   paragraph indent (e.g. `2m`)
+
+`lineheight`
+:   line height (e.g. `12p`)
+
+`pointsize`
+:   point size (e.g. `10p`)
+
+[`install-font.sh`]: https://www.schaffter.ca/mom/bin/install-font.sh
+[ms-font-steps]: https://www.schaffter.ca/mom/momdoc/appendices.html#steps
+
+### Variables set automatically
+
+Pandoc sets these variables automatically in response to [options] or
+document contents; users can also modify them. These vary depending
+on the output format, and include the following:
+
+`body`
+:   body of document
+
+`date-meta`
+:   the `date` variable converted to ISO 8601 YYYY-MM-DD,
+    included in all HTML based formats (dzslides, epub,
+    html, html4, html5, revealjs, s5, slideous, slidy).
+    The recognized formats for `date` are: `mm/dd/yyyy`,
+    `mm/dd/yy`, `yyyy-mm-dd` (ISO 8601), `dd MM yyyy`
+    (e.g. either `02 Apr 2018` or `02 April 2018`),
+    `MM dd, yyyy` (e.g. `Apr. 02, 2018` or `April 02, 2018),
+    `yyyy[mm[dd]]` (e.g. `20180402, `201804` or `2018`).
+
+`header-includes`
+:   contents specified by `-H/--include-in-header` (may have multiple
+    values)
+
+`include-before`
+:   contents specified by `-B/--include-before-body` (may have
+    multiple values)
+
+`include-after`
+:   contents specified by `-A/--include-after-body` (may have
+    multiple values)
+
+`meta-json`
+:   JSON representation of all of the document's metadata. Field
+    values are transformed to the selected output format.
+
+`numbersections`
+:   non-null value if `-N/--number-sections` was specified
+
+`sourcefile`, `outputfile`
+:   source and destination filenames, as given on the command line.
+    `sourcefile` can also be a list if input comes from multiple files,
+    or empty if input is from stdin. You can use the following snippet in
+    your template to distinguish them:
+
+        $if(sourcefile)$
+        $for(sourcefile)$
+        $sourcefile$
+        $endfor$
+        $else$
+        (stdin)
+        $endif$
+
+    Similarly, `outputfile` can be `-` if output goes to the terminal.
+
+    If you need absolute paths, use e.g. `$curdir$/$sourcefile$`.
+
+`pdf-engine`
+:   name of PDF engine if provided using `--pdf-engine`, or the
+    default engine for the format if PDF output is requested.
+
+`curdir`
+:   working directory from which pandoc is run.
+
+`pandoc-version`
+:   pandoc version.
+
+`toc`
+:   non-null value if `--toc/--table-of-contents` was specified
+
+`toc-title`
+:   title of table of contents (works only with EPUB,
+    HTML, revealjs, opendocument, odt, docx, pptx, beamer, LaTeX).
+    Note that in docx and pptx a custom `toc-title` will be
+    picked up from metadata, but cannot be set as a variable.
+
+[pandoc-templates]: https://github.com/jgm/pandoc-templates
+
+# Extensions
+
+The behavior of some of the readers and writers can be adjusted by
+enabling or disabling various extensions.
+
+An extension can be enabled by adding `+EXTENSION`
+to the format name and disabled by adding `-EXTENSION`. For example,
+`--from markdown_strict+footnotes` is strict Markdown with footnotes
+enabled, while `--from markdown-footnotes-pipe_tables` is pandoc's
+Markdown without footnotes or pipe tables.
+
+The Markdown reader and writer make by far the most use of extensions.
+Extensions only used by them are therefore covered in the
+section [Pandoc's Markdown] below (see [Markdown variants] for
+`commonmark` and `gfm`). In the following, extensions that also work
+for other formats are covered.
+
+Note that Markdown extensions added to the `ipynb` format
+affect Markdown cells in Jupyter notebooks (as do command-line
+options like `--markdown-headings`).
+
+## Typography
+
+### Extension: `smart` ###
+
+Interpret straight quotes as curly quotes, `---` as em-dashes,
+`--` as en-dashes, and `...` as ellipses. Nonbreaking spaces are
+inserted after certain abbreviations, such as "Mr."
+
+This extension can be enabled/disabled for the following formats:
+
+input formats
+:  `markdown`, `commonmark`, `latex`, `mediawiki`, `org`, `rst`, `twiki`,
+   `html`
+
+output formats
+:  `markdown`, `latex`, `context`, `org`, `rst`
+
+enabled by default in
+:  `markdown`, `latex`, `context` (both input and output)
+
+Note: If you are *writing* Markdown, then the `smart` extension
+has the reverse effect: what would have been curly quotes comes
+out straight.
+
+In LaTeX, `smart` means to use the standard TeX ligatures
+for quotation marks (` `` ` and ` '' ` for double quotes,
+`` ` `` and `` ' `` for single quotes) and dashes (`--` for
+en-dash and `---` for em-dash).  If `smart` is disabled,
+then in reading LaTeX pandoc will parse these characters
+literally.  In writing LaTeX, enabling `smart` tells pandoc
+to use the ligatures when possible; if `smart` is disabled
+pandoc will use unicode quotation mark and dash characters.
+
+## Headings and sections
+
+### Extension: `auto_identifiers` ###
+
+A heading without an explicitly specified identifier will be
+automatically assigned a unique identifier based on the heading text.
+
+This extension can be enabled/disabled for the following formats:
+
+input formats
+:  `markdown`, `latex`, `rst`, `mediawiki`, `textile`, `man`
+
+output formats
+:  `markdown`, `muse`
+
+enabled by default in
+:  `markdown`, `muse`, `man`
+
+The default algorithm used to derive the identifier from the
+heading text is:
+
+  - Remove all formatting, links, etc.
+  - Remove all footnotes.
+  - Remove all non-alphanumeric characters,
+    except underscores, hyphens, and periods.
+  - Replace all spaces and newlines with hyphens.
+  - Convert all alphabetic characters to lowercase.
+  - Remove everything up to the first letter (identifiers may
+    not begin with a number or punctuation mark).
+  - If nothing is left after this, use the identifier `section`.
+
+Thus, for example,
+
+  Heading                           Identifier
+  -------------------------------   ----------------------------
+  `Heading identifiers in HTML`     `heading-identifiers-in-html`
+  `Maître d'hôtel`                  `maître-dhôtel`
+  `*Dogs*?--in *my* house?`         `dogs--in-my-house`
+  `[HTML], [S5], or [RTF]?`         `html-s5-or-rtf`
+  `3. Applications`                 `applications`
+  `33`                              `section`
+
+These rules should, in most cases, allow one to determine the identifier
+from the heading text. The exception is when several headings have the
+same text; in this case, the first will get an identifier as described
+above; the second will get the same identifier with `-1` appended; the
+third with `-2`; and so on.
+
+(However, a different algorithm is used if
+`gfm_auto_identifiers` is enabled; see below.)
+
+These identifiers are used to provide link targets in the table of
+contents generated by the `--toc|--table-of-contents` option. They
+also make it easy to provide links from one section of a document to
+another. A link to this section, for example, might look like this:
+
+    See the section on
+    [heading identifiers](#heading-identifiers-in-html-latex-and-context).
+
+Note, however, that this method of providing links to sections works
+only in HTML, LaTeX, and ConTeXt formats.
+
+If the `--section-divs` option is specified, then each section will
+be wrapped in a `section` (or a `div`, if `html4` was specified),
+and the identifier will be attached to the enclosing `<section>`
+(or `<div>`) tag rather than the heading itself. This allows entire
+sections to be manipulated using JavaScript or treated differently in
+CSS.
+
+### Extension: `ascii_identifiers` ###
+
+Causes the identifiers produced by `auto_identifiers` to be pure ASCII.
+Accents are stripped off of accented Latin letters, and non-Latin
+letters are omitted.
+
+### Extension: `gfm_auto_identifiers` ###
+
+Changes the algorithm used by `auto_identifiers` to conform to
+GitHub's method.  Spaces are converted to dashes (`-`),
+uppercase characters to lowercase characters, and punctuation
+characters other than `-` and `_` are removed.
+Emojis are replaced by their names.
+
+## Math Input
+
+The extensions [`tex_math_dollars`](#extension-tex_math_dollars),
+[`tex_math_gfm`](#extension-tex_math_gfm),
+[`tex_math_single_backslash`](#extension-tex_math_single_backslash), and
+[`tex_math_double_backslash`](#extension-tex_math_double_backslash)
+are described in the section about Pandoc's Markdown.
+
+However, they can also be used with HTML input. This is handy for
+reading web pages formatted using MathJax, for example.
+
+## Raw HTML/TeX
+
+The following extensions are described in more detail in
+their respective sections of [Pandoc's Markdown]:
+
+- [`raw_html`](#extension-raw_html) allows HTML elements which
+  are not representable in pandoc's AST to be parsed as raw HTML.
+  By default, this is disabled for HTML input.
+
+- [`raw_tex`](#extension-raw_tex) allows raw LaTeX, TeX, and ConTeXt
+  to be included in a document.  This extension can be enabled/disabled
+  for the following formats (in addition to `markdown`):
+
+  input formats
+  :  `latex`, `textile`, `html` (environments, `\ref`, and
+     `\eqref` only), `ipynb`
+
+  output formats
+  :  `textile`, `commonmark`
+
+  Note: as applied to `ipynb`, `raw_html` and `raw_tex` affect not
+  only raw TeX in Markdown cells, but data with mime type
+  `text/html` in output cells.  Since the `ipynb` reader attempts
+  to preserve the richest possible outputs when several options
+  are given, you will get best results if you disable `raw_html`
+  and `raw_tex` when converting to formats like `docx` which don't
+  allow raw `html` or `tex`.
+
+- [`native_divs`](#extension-native_divs) causes HTML `div`
+  elements to be parsed as native pandoc Div blocks.
+  If you want them to be parsed as raw HTML, use
+  `-f html-native_divs+raw_html`.
+
+- [`native_spans`](#extension-native_spans) causes HTML `span`
+  elements to be parsed as native pandoc Span inlines.
+  If you want them to be parsed as raw HTML, use
+  `-f html-native_spans+raw_html`.  If you want to drop all
+  `div`s and `span`s when converting HTML to Markdown, you
+  can use `pandoc -f html-native_divs-native_spans -t markdown`.
+
+## Literate Haskell support
+
+### Extension: `literate_haskell` ###
+
+Treat the document as literate Haskell source.
+
+This extension can be enabled/disabled for the following formats:
+
+input formats
+:  `markdown`, `rst`, `latex`
+
+output formats
+:  `markdown`, `rst`, `latex`, `html`
+
+If you append `+lhs` (or `+literate_haskell`) to one of the formats
+above, pandoc will treat the document as literate Haskell source.
+This means that
+
+  - In Markdown input, "bird track" sections will be parsed as Haskell
+    code rather than block quotations.  Text between `\begin{code}`
+    and `\end{code}` will also be treated as Haskell code.  For
+    ATX-style headings the character '=' will be used instead of '#'.
+
+  - In Markdown output, code blocks with classes `haskell` and `literate`
+    will be rendered using bird tracks, and block quotations will be
+    indented one space, so they will not be treated as Haskell code.
+    In addition, headings will be rendered setext-style (with underlines)
+    rather than ATX-style (with '#' characters). (This is because ghc
+    treats '#' characters in column 1 as introducing line numbers.)
+
+  - In restructured text input, "bird track" sections will be parsed
+    as Haskell code.
+
+  - In restructured text output, code blocks with class `haskell` will
+    be rendered using bird tracks.
+
+  - In LaTeX input, text in `code` environments will be parsed as
+    Haskell code.
+
+  - In LaTeX output, code blocks with class `haskell` will be rendered
+    inside `code` environments.
+
+  - In HTML output, code blocks with class `haskell` will be rendered
+    with class `literatehaskell` and bird tracks.
+
+Examples:
+
+    pandoc -f markdown+lhs -t html
+
+reads literate Haskell source formatted with Markdown conventions and writes
+ordinary HTML (without bird tracks).
+
+    pandoc -f markdown+lhs -t html+lhs
+
+writes HTML with the Haskell code in bird tracks, so it can be copied
+and pasted as literate Haskell source.
+
+Note that GHC expects the bird tracks in the first column, so indented
+literate code blocks (e.g. inside an itemized environment) will not be
+picked up by the Haskell compiler.
+
+## Other extensions
+
+### Extension: `empty_paragraphs` ###
+
+Allows empty paragraphs.  By default empty paragraphs are
+omitted.
+
+This extension can be enabled/disabled for the following formats:
+
+input formats
+:  `docx`, `html`
+
+output formats
+:  `docx`, `odt`, `opendocument`, `html`, `latex`
+
+### Extension: `native_numbering` ###
+
+Enables native numbering of figures and tables. Enumeration
+starts at 1.
+
+This extension can be enabled/disabled for the following formats:
+
+output formats
+:  `odt`, `opendocument`, `docx`
+
+### Extension: `xrefs_name` ###
+
+Links to headings, figures and tables inside the document are
+substituted with cross-references that will use the name or caption
+of the referenced item. The original link text is replaced once
+the generated document is refreshed. This extension can be combined
+with `xrefs_number` in which case numbers will appear before the
+name.
+
+Text in cross-references is only made consistent with the referenced
+item once the document has been refreshed.
+
+This extension can be enabled/disabled for the following formats:
+
+output formats
+:  `odt`, `opendocument`
+
+### Extension: `xrefs_number` ###
+
+Links to headings, figures and tables inside the document are
+substituted with cross-references that will use the number
+of the referenced item. The original link text is discarded.
+This extension can be combined with `xrefs_name` in which case
+the name or caption numbers will appear after the number.
+
+For the `xrefs_number` to be useful heading numbers must be enabled
+in the generated document, also table and figure captions must be enabled
+using for example the `native_numbering` extension.
+
+Numbers in cross-references are only visible in the final document once
+it has been refreshed.
+
+This extension can be enabled/disabled for the following formats:
+
+output formats
+:  `odt`, `opendocument`
+
+### Extension: `styles` ### {#ext-styles}
+
+When converting from docx, add `custom-styles` attributes
+for all docx styles, regardless of whether pandoc understands
+the meanings of these styles. Because attributes cannot be
+added directly to paragraphs or text in the pandoc AST,
+paragraph styles will cause Divs to be created and character
+styles will cause Spans to be created to hold the attributes.
+(Table styles will be added to the Table elements directly.)
+This extension can be used with [docx custom styles](#custom-styles).
+
+input formats
+:  `docx`
+
+### Extension: `amuse` ###
+
+In the `muse` input format, this enables Text::Amuse
+extensions to Emacs Muse markup.
+
+### Extension: `raw_markdown` ###
+
+In the `ipynb` input format, this causes Markdown cells
+to be included as raw Markdown blocks (allowing lossless
+round-tripping) rather than being parsed.  Use this only
+when you are targeting `ipynb` or a Markdown-based
+output format.
+
+### Extension: `citations` (typst) {#typst-citations}
+
+When the `citations` extension is enabled in `typst`
+(as it is by default), `typst` citations will
+be parsed as native pandoc citations, and native
+pandoc citations will be rendered as `typst` citations.
+
+### Extension: `citations` (org) {#org-citations}
+
+When the `citations` extension is enabled in `org`,
+org-cite and org-ref style citations will be parsed as
+native pandoc citations, and org-cite citations will
+be used to render native pandoc citations.
+
+  [org-cite]: https://orgmode.org/manual/Citations.html
+  [org-ref]:  https://github.com/jkitchin/org-ref
+
+### Extension: `citations` (docx) {#docx-citations}
+
+When `citations` is enabled in `docx`, citations inserted
+by Zotero or Mendeley or EndNote plugins will be parsed as native
+pandoc citations.  (Otherwise, the formatted citations generated
+by the bibliographic software will be parsed as regular text.)
+
+### Extension: `fancy_lists` (org) {#org-fancy-lists}
+
+Some aspects of [Pandoc's Markdown fancy lists](#extension-fancy_lists) are also
+accepted in `org` input, mimicking the option `org-list-allow-alphabetical` in
+Emacs. As in Org Mode, enabling this extension allows lowercase and uppercase
+alphabetical markers for ordered lists to be parsed in addition to arabic ones.
+Note that for Org, this does not include roman numerals or the `#` placeholder
+that are enabled by the extension in Pandoc's Markdown.
+
+### Extension: `element_citations` ###
+
+In the `jats` output formats, this causes reference items to
+be replaced with `<element-citation>` elements. These
+elements are not influenced by CSL styles, but all information
+on the item is included in tags.
+
+### Extension: `ntb` ###
+
+In the `context` output format this enables the use of [Natural Tables
+(TABLE)](https://wiki.contextgarden.net/TABLE) instead of the default
+[Extreme Tables (xtables)](https://wiki.contextgarden.net/xtables).
+Natural tables allow more fine-grained global customization but come
+at a performance penalty compared to extreme tables.
+
+### Extension: `smart_quotes` (org) ###
+
+Interpret straight quotes as curly quotes during parsing. When
+*writing* Org, then the `smart_quotes` extension has the reverse
+effect: what would have been curly quotes comes out straight.
+
+This extension is implied if `smart` is enabled.
+
+### Extension: `special_strings` (org) ###
+
+Interpret `---` as em-dashes, `--` as en-dashes, `\-` as shy
+hyphen, and `...` as ellipses.
+
+This extension is implied if `smart` is enabled.
+
+### Extension: `tagging` ### {#extension--tagging}
+
+Enabling this extension with `context` output will produce markup
+suitable for the production of tagged PDFs. This includes
+additional markers for paragraphs and alternative markup for
+emphasized text. The `emphasis-command` template variable is set
+if the extension is enabled.
+
+# Pandoc's Markdown
+
+Pandoc understands an extended and slightly revised version of
+John Gruber's [Markdown] syntax.  This document explains the syntax,
+noting differences from original Markdown. Except where noted, these
+differences can be suppressed by using the `markdown_strict` format instead
+of `markdown`. Extensions can be enabled or disabled to specify the
+behavior more granularly. They are described in the following. See also
+[Extensions] above, for extensions that work also on other formats.
+
+## Philosophy
+
+Markdown is designed to be easy to write, and, even more importantly,
+easy to read:
+
+> A Markdown-formatted document should be publishable as-is, as plain
+> text, without looking like it's been marked up with tags or formatting
+> instructions.\
+> -- [John Gruber](https://daringfireball.net/projects/markdown/syntax#philosophy)
+
+This principle has guided pandoc's decisions in finding syntax for
+tables, footnotes, and other extensions.
+
+There is, however, one respect in which pandoc's aims are different
+from the original aims of Markdown.  Whereas Markdown was originally
+designed with HTML generation in mind, pandoc is designed for multiple
+output formats.  Thus, while pandoc allows the embedding of raw HTML,
+it discourages it, and provides other, non-HTMLish ways of representing
+important document elements like definition lists, tables, mathematics, and
+footnotes.
+
+## Paragraphs
+
+A paragraph is one or more lines of text followed by one or more blank lines.
+Newlines are treated as spaces, so you can reflow your paragraphs as you like.
+If you need a hard line break, put two or more spaces at the end of a line.
+
+### Extension: `escaped_line_breaks` ###
+
+A backslash followed by a newline is also a hard line break.
+Note:  in multiline and grid table cells, this is the only way
+to create a hard line break, since trailing spaces in the cells
+are ignored.
+
+## Headings
+
+There are two kinds of headings: Setext and ATX.
+
+### Setext-style headings ###
+
+A setext-style heading is a line of text "underlined" with a row of `=` signs
+(for a level-one heading) or `-` signs (for a level-two heading):
+
+    A level-one heading
+    ===================
+
+    A level-two heading
+    -------------------
+
+The heading text can contain inline formatting, such as emphasis (see
+[Inline formatting], below).
+
+
+### ATX-style headings ###
+
+An ATX-style heading consists of one to six `#` signs and a line of
+text, optionally followed by any number of `#` signs.  The number of
+`#` signs at the beginning of the line is the heading level:
+
+    ## A level-two heading
+
+    ### A level-three heading ###
+
+As with setext-style headings, the heading text can contain formatting:
+
+    # A level-one heading with a [link](/url) and *emphasis*
+
+### Extension: `blank_before_header` ###
+
+Original Markdown syntax does not require a blank line before a heading.
+Pandoc does require this (except, of course, at the beginning of the
+document). The reason for the requirement is that it is all too easy for a
+`#` to end up at the beginning of a line by accident (perhaps through line
+wrapping). Consider, for example:
+
+    I like several of their flavors of ice cream:
+    #22, for example, and #5.
+
+### Extension: `space_in_atx_header` ###
+
+Many Markdown implementations do not require a space between the
+opening `#`s of an ATX heading and the heading text, so that
+`#5 bolt` and `#hashtag` count as headings.  With this extension,
+pandoc does require the space.
+
+### Heading identifiers ###
+
+See also the [`auto_identifiers`
+extension](#extension-auto_identifiers) above.
+
+### Extension: `header_attributes` ###
+
+Headings can be assigned attributes using this syntax at the end
+of the line containing the heading text:
+
+    {#identifier .class .class key=value key=value}
+
+Thus, for example, the following headings will all be assigned the identifier
+`foo`:
+
+    # My heading {#foo}
+
+    ## My heading ##    {#foo}
+
+    My other heading   {#foo}
+    ---------------
+
+(This syntax is compatible with [PHP Markdown Extra].)
+
+Note that although this syntax allows assignment of classes and key/value
+attributes, writers generally don't use all of this information.  Identifiers,
+classes, and key/value attributes are used in HTML and HTML-based formats such
+as EPUB and slidy.  Identifiers are used for labels and link anchors in the
+LaTeX, ConTeXt, Textile, Jira markup, and AsciiDoc writers.
+
+Headings with the class `unnumbered` will not be numbered, even if
+`--number-sections` is specified.  A single hyphen (`-`) in an attribute
+context is equivalent to `.unnumbered`, and preferable in non-English
+documents.  So,
+
+    # My heading {-}
+
+is just the same as
+
+    # My heading {.unnumbered}
+
+If the `unlisted` class is present in addition to `unnumbered`,
+the heading will not be included in a table of contents.
+(Currently this feature is only implemented for certain
+formats: those based on LaTeX and HTML, PowerPoint, and RTF.)
+
+### Extension: `implicit_header_references` ###
+
+Pandoc behaves as if reference links have been defined for each heading.
+So, to link to a heading
+
+    # Heading identifiers in HTML
+
+you can simply write
+
+    [Heading identifiers in HTML]
+
+or
+
+    [Heading identifiers in HTML][]
+
+or
+
+    [the section on heading identifiers][heading identifiers in
+    HTML]
+
+instead of giving the identifier explicitly:
+
+    [Heading identifiers in HTML](#heading-identifiers-in-html)
+
+If there are multiple headings with identical text, the corresponding
+reference will link to the first one only, and you will need to use explicit
+links to link to the others, as described above.
+
+Like regular reference links, these references are case-insensitive.
+
+Explicit link reference definitions always take priority over
+implicit heading references.  So, in the following example, the
+link will point to `bar`, not to `#foo`:
+
+    # Foo
+
+    [foo]: bar
+
+    See [foo]
+
+## Block quotations
+
+Markdown uses email conventions for quoting blocks of text.
+A block quotation is one or more paragraphs or other block elements
+(such as lists or headings), with each line preceded by a `>` character
+and an optional space. (The `>` need not start at the left margin, but
+it should not be indented more than three spaces.)
+
+    > This is a block quote. This
+    > paragraph has two lines.
+    >
+    > 1. This is a list inside a block quote.
+    > 2. Second item.
+
+A "lazy" form, which requires the `>` character only on the first
+line of each block, is also allowed:
+
+    > This is a block quote. This
+    paragraph has two lines.
+
+    > 1. This is a list inside a block quote.
+    2. Second item.
+
+Among the block elements that can be contained in a block quote are
+other block quotes. That is, block quotes can be nested:
+
+    > This is a block quote.
+    >
+    > > A block quote within a block quote.
+
+If the `>` character is followed by an optional space, that space
+will be considered part of the block quote marker and not part of
+the indentation of the contents.  Thus, to put an indented code
+block in a block quote, you need five spaces after the `>`:
+
+    >     code
+
+### Extension: `blank_before_blockquote` ###
+
+Original Markdown syntax does not require a blank line before a
+block quote.  Pandoc does require this (except, of course, at
+the beginning of the document). The reason for the requirement
+is that it is all too easy for a `>` to end up at the beginning
+of a line by accident (perhaps through line wrapping). So,
+unless the `markdown_strict` format is used, the following does
+not produce a nested block quote in pandoc:
+
+    > This is a block quote.
+    >> Not nested, since `blank_before_blockquote` is enabled by default
+
+
+## Verbatim (code) blocks
+
+### Indented code blocks ###
+
+A block of text indented four spaces (or one tab) is treated as verbatim
+text: that is, special characters do not trigger special formatting,
+and all spaces and line breaks are preserved.  For example,
+
+        if (a > 3) {
+          moveShip(5 * gravity, DOWN);
+        }
+
+The initial (four space or one tab) indentation is not considered part
+of the verbatim text, and is removed in the output.
+
+Note: blank lines in the verbatim text need not begin with four spaces.
+
+
+### Fenced code blocks ###
+
+### Extension: `fenced_code_blocks` ###
+
+In addition to standard indented code blocks, pandoc supports
+*fenced* code blocks.  These begin with a row of three or more
+tildes (`~`) and end with a row of tildes that must be at least as long as
+the starting row. Everything between these lines is treated as code. No
+indentation is necessary:
+
+    ~~~~~~~
+    if (a > 3) {
+      moveShip(5 * gravity, DOWN);
+    }
+    ~~~~~~~
+
+Like regular code blocks, fenced code blocks must be separated
+from surrounding text by blank lines.
+
+If the code itself contains a row of tildes or backticks, just use a longer
+row of tildes or backticks at the start and end:
+
+    ~~~~~~~~~~~~~~~~
+    ~~~~~~~~~~
+    code including tildes
+    ~~~~~~~~~~
+    ~~~~~~~~~~~~~~~~
+
+### Extension: `backtick_code_blocks` ###
+
+Same as `fenced_code_blocks`, but uses backticks (`` ` ``) instead of tildes
+(`~`).
+
+### Extension: `fenced_code_attributes` ###
+
+Optionally, you may attach attributes to fenced or backtick code block using
+this syntax:
+
+    ~~~~ {#mycode .haskell .numberLines startFrom="100"}
+    qsort []     = []
+    qsort (x:xs) = qsort (filter (< x) xs) ++ [x] ++
+                   qsort (filter (>= x) xs)
+    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Here `mycode` is an identifier, `haskell` and `numberLines` are
+classes, and `startFrom` is an attribute with value `100`. Some
+output formats can use this information to do syntax
+highlighting. Currently, the only output formats that use this
+information are HTML, LaTeX, Docx, Ms, and PowerPoint. If
+highlighting is supported for your output format and language,
+then the code block above will appear highlighted, with numbered
+lines. (To see which languages are supported, type `pandoc
+--list-highlight-languages`.) Otherwise, the code block above
+will appear as follows:
+
+    <pre id="mycode" class="haskell numberLines" startFrom="100">
+      <code>
+      ...
+      </code>
+    </pre>
+
+The `numberLines` (or `number-lines`) class will cause the lines
+of the code block to be numbered, starting with `1` or the value
+of the `startFrom` attribute.  The `lineAnchors` (or
+`line-anchors`) class will cause the lines to be clickable
+anchors in HTML output.
+
+A shortcut form can also be used for specifying the language of
+the code block:
+
+    ```haskell
+    qsort [] = []
+    ```
+
+This is equivalent to:
+
+    ``` {.haskell}
+    qsort [] = []
+    ```
+
+This shortcut form may be combined with attributes:
+
+    ```haskell {.numberLines}
+    qsort [] = []
+    ```
+
+Which is equivalent to:
+
+    ``` {.haskell .numberLines}
+    qsort [] = []
+    ```
+
+If the `fenced_code_attributes` extension is disabled, but
+input contains class attribute(s) for the code block, the first
+class attribute will be printed after the opening fence as a bare
+word.
+
+To prevent all highlighting, use the `--syntax-highlighting=none`
+option. To set the highlighting style or method, use
+`--syntax-highlighting`. For more information on highlighting, see
+[Syntax highlighting], below.
+
+## Line blocks
+
+### Extension: `line_blocks` ###
+
+A line block is a sequence of lines beginning with a vertical bar (`|`)
+followed by a space.  The division into lines will be preserved in
+the output, as will any leading spaces; otherwise, the lines will
+be formatted as Markdown.  This is useful for verse and addresses:
+
+    | The limerick packs laughs anatomical
+    | In space that is quite economical.
+    |    But the good ones I've seen
+    |    So seldom are clean
+    | And the clean ones so seldom are comical
+
+    | 200 Main St.
+    | Berkeley, CA 94718
+
+The lines can be hard-wrapped if needed, but the continuation
+line must begin with a space.
+
+    | The Right Honorable Most Venerable and Righteous Samuel L.
+      Constable, Jr.
+    | 200 Main St.
+    | Berkeley, CA 94718
+
+Inline formatting (such as emphasis) is allowed in the content
+(though it can't cross line boundaries). Block-level formatting
+(such as block quotes or lists) is not recognized.
+
+This syntax is borrowed from [reStructuredText].
+
+## Lists
+
+### Bullet lists ###
+
+A bullet list is a list of bulleted list items.  A bulleted list
+item begins with a bullet (`*`, `+`, or `-`).  Here is a simple
+example:
+
+    * one
+    * two
+    * three
+
+This will produce a "compact" list. If you want a "loose" list, in which
+each item is formatted as a paragraph, put spaces between the items:
+
+    * one
+
+    * two
+
+    * three
+
+The bullets need not be flush with the left margin; they may be
+indented one, two, or three spaces. The bullet must be followed
+by whitespace.
+
+List items look best if subsequent lines are flush with the first
+line (after the bullet):
+
+    * here is my first
+      list item.
+    * and my second.
+
+But Markdown also allows a "lazy" format:
+
+    * here is my first
+    list item.
+    * and my second.
+
+### Block content in list items ###
+
+A list item may contain multiple paragraphs and other block-level
+content. However, subsequent paragraphs must be preceded by a blank line
+and indented to line up with the first non-space content after
+the list marker.
+
+      * First paragraph.
+
+        Continued.
+
+      * Second paragraph. With a code block, which must be indented
+        eight spaces:
+
+            { code }
+
+Exception: if the list marker is followed by an indented code
+block, which must begin 5 spaces after the list marker, then
+subsequent paragraphs must begin two columns after the last
+character of the list marker:
+
+    *     code
+
+      continuation paragraph
+
+List items may include other lists.  In this case the preceding blank
+line is optional.  The nested list must be indented to line up with
+the first non-space character after the list marker of the
+containing list item.
+
+    * fruits
+      + apples
+        - macintosh
+        - red delicious
+      + pears
+      + peaches
+    * vegetables
+      + broccoli
+      + chard
+
+As noted above, Markdown allows you to write list items "lazily," instead of
+indenting continuation lines. However, if there are multiple paragraphs or
+other blocks in a list item, the first line of each must be indented.
+
+    + A lazy, lazy, list
+    item.
+
+    + Another one; this looks
+    bad but is legal.
+
+        Second paragraph of second
+    list item.
+
+### Ordered lists ###
+
+Ordered lists work just like bulleted lists, except that the items
+begin with enumerators rather than bullets.
+
+In original Markdown, enumerators are decimal numbers followed
+by a period and a space.  The numbers themselves are ignored, so
+there is no difference between this list:
+
+    1.  one
+    2.  two
+    3.  three
+
+and this one:
+
+    5.  one
+    7.  two
+    1.  three
+
+### Extension: `fancy_lists` ###
+
+Unlike original Markdown, pandoc allows ordered list items to be marked
+with uppercase and lowercase letters and roman numerals, in addition to
+Arabic numerals. List markers may be enclosed in parentheses or followed by a
+single right-parenthesis or period. They must be separated from the
+text that follows by at least one space, and, if the list marker is a
+capital letter with a period, by at least two spaces.[^2]
+
+[^2]:  The point of this rule is to ensure that normal paragraphs
+    starting with people's initials, like
+
+        B. Russell won a Nobel Prize (but not for "On Denoting").
+
+    do not get treated as list items.
+
+    This rule will not prevent
+
+        (C) 2007 Joe Smith
+
+    from being interpreted as a list item.  In this case, a backslash
+    escape can be used:
+
+        (C\) 2007 Joe Smith
+
+The `fancy_lists` extension also allows '`#`' to be used as an
+ordered list marker in place of a numeral:
+
+    #. one
+    #. two
+
+Note:  the '`#`' ordered list marker doesn't work with `commonmark`.
+
+### Extension: `startnum` ###
+
+Pandoc also pays attention to the type of list marker used, and to the
+starting number, and both of these are preserved where possible in the
+output format. Thus, the following yields a list with numbers followed
+by a single parenthesis, starting with 9, and a sublist with lowercase
+roman numerals:
+
+     9)  Ninth
+    10)  Tenth
+    11)  Eleventh
+           i. subone
+          ii. subtwo
+         iii. subthree
+
+Pandoc will start a new list each time a different type of list
+marker is used.  So, the following will create three lists:
+
+    (2) Two
+    (5) Three
+    1.  Four
+    *   Five
+
+If default list markers are desired, use `#.`:
+
+    #.  one
+    #.  two
+    #.  three
+
+### Extension: `task_lists` ###
+
+Pandoc supports task lists, using the syntax of GitHub-Flavored Markdown.
+
+    - [ ] an unchecked task list item
+    - [x] checked item
+
+### Definition lists ###
+
+### Extension: `definition_lists` ###
+
+Pandoc supports definition lists, using the syntax of
+[PHP Markdown Extra] with some extensions.[^3]
+
+    Term 1
+
+    :   Definition 1
+
+    Term 2 with *inline markup*
+
+    :   Definition 2
+
+            { some code, part of Definition 2 }
+
+        Third paragraph of definition 2.
+
+Each term must fit on one line, which may optionally be followed by
+a blank line, and must be followed by one or more definitions.
+A definition begins with a colon or tilde, which may be indented one
+or two spaces.
+
+A term may have multiple definitions, and each definition may
+consist of one or more indented block elements (paragraph, code block,
+list, etc.). The blocks in the definition shoud be indented to the column
+of the first non-space content after the `:` or `~` marker, or
+(if the `four_space_rule` extension is enabled) four spaces or
+one tab stop. As with other Markdown lists, you can "lazily" omit
+indentation in paragraph continuation lines:
+
+    Term 1
+
+    : Definition
+    with lazy continuation.
+
+      Second paragraph of the definition.
+
+If you leave space before the definition (as in the example above),
+the text of the definition will be treated as a paragraph.  In some
+output formats, this will mean greater spacing between term/definition
+pairs. For a more compact definition list, omit the space before the
+definition:
+
+    Term 1
+      ~ Definition 1
+
+    Term 2
+      ~ Definition 2a
+      ~ Definition 2b
+
+Note that space between items in a definition list is required.
+
+[^3]:  I have been influenced by the suggestions of [David
+  Wheeler](https://justatheory.com/2009/02/modest-markdown-proposal/).
+
+### Numbered example lists ###
+
+### Extension: `example_lists` ###
+
+The special list marker `@` can be used for sequentially numbered
+examples. The first list item with a `@` marker will be numbered '1',
+the next '2', and so on, throughout the document. The numbered examples
+need not occur in a single list; each new list using `@` will take up
+where the last stopped. So, for example:
+
+    (@)  My first example will be numbered (1).
+    (@)  My second example will be numbered (2).
+
+    Explanation of examples.
+
+    (@)  My third example will be numbered (3).
+
+Numbered examples can be labeled and referred to elsewhere in the
+document:
+
+    (@good)  This is a good example.
+
+    As (@good) illustrates, ...
+
+The label can be any string of alphanumeric characters, underscores,
+or hyphens.
+
+Continuation paragraphs in example lists must always
+be indented four spaces, regardless of the length of the
+list marker.  That is, example lists always behave as if the
+`four_space_rule` extension is set.  This is because example
+labels tend to be long, and indenting content to the
+first non-space character after the label would be awkward.
+
+You can repeat an earlier numbered example by re-using its label:
+
+    (@foo) Sample sentence.
+
+    Intervening text...
+
+    This theory can explain the case we saw earlier (repeated):
+
+    (@foo) Sample sentence.
+
+This only works reliably, though, if the repeated item is in a list
+by itself, because each numbered example list will be numbered
+continuously from its starting number.
+
+### Ending a list ###
+
+What if you want to put an indented code block after a list?
+
+    -   item one
+    -   item two
+
+        { my code block }
+
+Trouble! Here pandoc (like other Markdown implementations) will treat
+`{ my code block }` as the second paragraph of item two, and not as
+a code block.
+
+To "cut off" the list after item two, you can insert some non-indented
+content, like an HTML comment, which won't produce visible output in
+any format:
+
+    -   item one
+    -   item two
+
+    <!-- end of list -->
+
+        { my code block }
+
+You can use the same trick if you want two consecutive lists instead
+of one big list:
+
+    1.  one
+    2.  two
+    3.  three
+
+    <!-- -->
+
+    1.  uno
+    2.  dos
+    3.  tres
+
+## Horizontal rules
+
+A line containing a row of three or more `*`, `-`, or `_` characters
+(optionally separated by spaces) produces a horizontal rule:
+
+    *  *  *  *
+
+    ---------------
+
+We strongly recommend that horizontal rules be separated from
+surrounding text by blank lines.  If a horizontal rule is not
+followed by a blank line, pandoc may try to interpret the
+lines that follow as a YAML metadata block or a table.
+
+## Tables
+
+Four kinds of tables may be used. The first three kinds presuppose the use of
+a fixed-width font, such as Courier. The fourth kind can be used with
+proportionally spaced fonts, as it does not require lining up columns.
+
+### Extension: `table_captions` ###
+
+A caption may optionally be provided with all 4 kinds of tables (as
+illustrated in the examples below). A caption is a paragraph beginning
+with the string `Table:` (or `table:` or just `:`), which will be stripped
+off. It may appear either before or after the table.
+
+### Extension: `simple_tables` ###
+
+Simple tables look like this:
+
+      Right     Left     Center     Default
+    -------     ------ ----------   -------
+         12     12        12            12
+        123     123       123          123
+          1     1          1             1
+
+    Table:  Demonstration of simple table syntax.
+
+The header and table rows must each fit on one line.  Column
+alignments are determined by the position of the header text relative
+to the dashed line below it:[^4]
+
+  - If the dashed line is flush with the header text on the right side
+    but extends beyond it on the left, the column is right-aligned.
+  - If the dashed line is flush with the header text on the left side
+    but extends beyond it on the right, the column is left-aligned.
+  - If the dashed line extends beyond the header text on both sides,
+    the column is centered.
+  - If the dashed line is flush with the header text on both sides,
+    the default alignment is used (in most cases, this will be left).
+
+[^4]:  This scheme is due to Michel Fortin, who proposed it on the
+       [Markdown discussion list](http://six.pairlist.net/pipermail/markdown-discuss/2005-March/001097.html).
+
+The table must end with a blank line, or a line of dashes followed by
+a blank line.
+
+The column header row may be omitted, provided a dashed line is used
+to end the table. For example:
+
+    -------     ------ ----------   -------
+         12     12        12             12
+        123     123       123           123
+          1     1          1              1
+    -------     ------ ----------   -------
+
+When the header row is omitted, column alignments are determined on the basis
+of the first line of the table body. So, in the tables above, the columns
+would be right, left, center, and right aligned, respectively.
+
+### Extension: `multiline_tables` ###
+
+Multiline tables allow header and table rows to span multiple lines
+of text (but cells that span multiple columns or rows of the table are
+not supported).  Here is an example:
+
+    -------------------------------------------------------------
+     Centered   Default           Right Left
+      Header    Aligned         Aligned Aligned
+    ----------- ------- --------------- -------------------------
+       First    row                12.0 Example of a row that
+                                        spans multiple lines.
+
+      Second    row                 5.0 Here's another one. Note
+                                        the blank line between
+                                        rows.
+    -------------------------------------------------------------
+
+    Table: Here's the caption. It, too, may span
+    multiple lines.
+
+These work like simple tables, but with the following differences:
+
+  - They must begin with a row of dashes, before the header text
+    (unless the header row is omitted).
+  - They must end with a row of dashes, then a blank line.
+  - The rows must be separated by blank lines.
+
+In multiline tables, the table parser pays attention to the widths of
+the columns, and the writers try to reproduce these relative widths in
+the output. So, if you find that one of the columns is too narrow in the
+output, try widening it in the Markdown source.
+
+The header may be omitted in multiline tables as well as simple tables:
+
+    ----------- ------- --------------- -------------------------
+       First    row                12.0 Example of a row that
+                                        spans multiple lines.
+
+      Second    row                 5.0 Here's another one. Note
+                                        the blank line between
+                                        rows.
+    ----------- ------- --------------- -------------------------
+
+    : Here's a multiline table without a header.
+
+It is possible for a multiline table to have just one row, but the row
+should be followed by a blank line (and then the row of dashes that ends
+the table), or the table may be interpreted as a simple table.
+
+### Extension: `grid_tables` ###
+
+Grid tables look like this:
+
+    : Sample grid table.
+
+    +---------------+---------------+--------------------+
+    | Fruit         | Price         | Advantages         |
+    +===============+===============+====================+
+    | Bananas       | $1.34         | - built-in wrapper |
+    |               |               | - bright color     |
+    +---------------+---------------+--------------------+
+    | Oranges       | $2.10         | - cures scurvy     |
+    |               |               | - tasty            |
+    +---------------+---------------+--------------------+
+
+The row of `=`s separates the header from the table body,
+and can be omitted for a headerless table. The cells of grid
+tables may contain arbitrary block elements (multiple
+paragraphs, code blocks, lists, etc.).
+
+Cells can span multiple columns or rows:
+
+    +---------------------+----------+
+    | Property            | Earth    |
+    +=============+=======+==========+
+    |             | min   | -89.2 °C |
+    | Temperature +-------+----------+
+    | 1961-1990   | mean  | 14 °C    |
+    |             +-------+----------+
+    |             | max   | 56.7 °C  |
+    +-------------+-------+----------+
+
+A table header may contain more than one row:
+
+    +---------------------+-----------------------+
+    | Location            | Temperature 1961-1990 |
+    |                     | in degree Celsius     |
+    |                     +-------+-------+-------+
+    |                     | min   | mean  | max   |
+    +=====================+=======+=======+=======+
+    | Antarctica          | -89.2 | N/A   | 19.8  |
+    +---------------------+-------+-------+-------+
+    | Earth               | -89.2 | 14    | 56.7  |
+    +---------------------+-------+-------+-------+
+
+Alignments can be specified as with pipe tables, by putting
+colons at the boundaries of the separator line after the
+header:
+
+    +---------------+---------------+--------------------+
+    | Right         | Left          | Centered           |
+    +==============:+:==============+:==================:+
+    | Bananas       | $1.34         | built-in wrapper   |
+    +---------------+---------------+--------------------+
+
+For headerless tables, the colons go on the top line instead:
+
+    +--------------:+:--------------+:------------------:+
+    | Right         | Left          | Centered           |
+    +---------------+---------------+--------------------+
+
+A table foot can be defined by enclosing it with separator lines
+that use `=` instead of `-`:
+
+     +---------------+---------------+
+     | Fruit         | Price         |
+     +===============+===============+
+     | Bananas       | $1.34         |
+     +---------------+---------------+
+     | Oranges       | $2.10         |
+     +===============+===============+
+     | Sum           | $3.44         |
+     +===============+===============+
+
+The foot must always be placed at the very bottom of the table.
+
+Grid tables can be created easily using Emacs' table-mode
+(`M-x table-insert`).
+
+### Extension: `pipe_tables` ###
+
+Pipe tables look like this:
+
+    | Right | Left | Default | Center |
+    |------:|:-----|---------|:------:|
+    |   12  |  12  |    12   |    12  |
+    |  123  |  123 |   123   |   123  |
+    |    1  |    1 |     1   |     1  |
+
+      : Demonstration of pipe table syntax.
+
+The syntax is identical to [PHP Markdown Extra tables].  The beginning and
+ending pipe characters are optional, but pipes are required between all
+columns.  The colons indicate column alignment as shown.  The header
+cannot be omitted.  To simulate a headerless table, include a header
+with blank cells.
+
+Since the pipes indicate column boundaries, columns need not be vertically
+aligned, as they are in the above example.  So, this is a perfectly
+legal (though ugly) pipe table:
+
+    fruit| price
+    -----|-----:
+    apple|2.05
+    pear|1.37
+    orange|3.09
+
+The cells of pipe tables cannot contain block elements like paragraphs
+and lists, and cannot span multiple lines.  If any line of the
+Markdown source is longer than the column width (see `--columns`),
+then the table will take up the full text width and the cell
+contents will wrap, with the relative cell widths determined by
+the number of dashes in the line separating the table header
+from the table body. (For example `---|-` would make the first column 3/4
+and the second column 1/4 of the full text width.)
+On the other hand, if no lines are wider than column width, then
+cell contents will not be wrapped, and the cells will be sized
+to their contents.
+
+Note:  pandoc also recognizes pipe tables of the following
+form, as can be produced by Emacs' orgtbl-mode:
+
+    | One | Two   |
+    |-----+-------|
+    | my  | table |
+    | is  | nice  |
+
+The difference is that `+` is used instead of `|`. Other orgtbl features
+are not supported. In particular, to get non-default column alignment,
+you'll need to add colons as above.
+
+[PHP Markdown Extra tables]: https://michelf.ca/projects/php-markdown/extra/#table
+
+### Extension: `table_attributes` ###
+
+Attributes may be attached to tables by including them at the end
+of the caption. (For the syntax, see
+[`header_attributes`][Extension: `header_attributes`].)
+
+      : Here's the caption. {#ident .class key="value"}
+
+## Metadata blocks
+
+### Extension: `pandoc_title_block` ###
+
+If the file begins with a title block
+
+    % title
+    % author(s) (separated by semicolons)
+    % date
+
+it will be parsed as bibliographic information, not regular text.  (It
+will be used, for example, in the title of standalone LaTeX or HTML
+output.)  The block may contain just a title, a date and an author,
+or all three elements. If you want to include an author but no
+title, or a title and a date but no author, you need a blank line:
+
+```
+%
+% Author
+```
+
+```
+% My title
+%
+% June 15, 2006
+```
+
+The title may occupy multiple lines, but continuation lines must
+begin with leading space, thus:
+
+```
+% My title
+  on multiple lines
+```
+
+If a document has multiple authors, the authors may be put on
+separate lines with leading space, or separated by semicolons, or
+both.  So, all of the following are equivalent:
+
+```
+% Author One
+  Author Two
+```
+
+```
+% Author One; Author Two
+```
+
+```
+% Author One;
+  Author Two
+```
+
+The date must fit on one line.
+
+All three metadata fields may contain standard inline formatting
+(italics, links, footnotes, etc.).
+
+Title blocks will always be parsed, but they will affect the output only
+when the `--standalone` (`-s`) option is chosen. In HTML output, titles
+will appear twice: once in the document head---this is the title that
+will appear at the top of the window in a browser---and once at the
+beginning of the document body. The title in the document head can have
+an optional prefix attached (`--title-prefix` or `-T` option). The title
+in the body appears as an H1 element with class "title", so it can be
+suppressed or reformatted with CSS. If a title prefix is specified with
+`-T` and no title block appears in the document, the title prefix will
+be used by itself as the HTML title.
+
+The man page writer extracts a title, man page section number, and
+other header and footer information from the title line. The title
+is assumed to be the first word on the title line, which may optionally
+end with a (single-digit) section number in parentheses. (There should
+be no space between the title and the parentheses.)  Anything after
+this is assumed to be additional footer and header text. A single pipe
+character (`|`) should be used to separate the footer text from the header
+text.  Thus,
+
+    % PANDOC(1)
+
+will yield a man page with the title `PANDOC` and section 1.
+
+    % PANDOC(1) Pandoc User Manuals
+
+will also have "Pandoc User Manuals" in the footer.
+
+    % PANDOC(1) Pandoc User Manuals | Version 4.0
+
+will also have "Version 4.0" in the header.
+
+### Extension: `yaml_metadata_block` ###
+
+A [YAML] metadata block is a valid YAML object, delimited by a line of three
+hyphens (`---`) at the top and a line of three hyphens (`---`) or three dots
+(`...`) at the bottom.  The initial line `---` must not be followed by a blank
+line. A YAML metadata block may occur anywhere in the document, but if
+it is not at the beginning, it must be preceded by a blank line.
+(Note that JSON may be used as well, because JSON is a subset of YAML.)
+
+Note that, because of the way pandoc concatenates input files
+when several are provided, you may also keep the metadata in a
+separate YAML file and pass it to pandoc as an argument, along
+with your Markdown files:
+
+    pandoc chap1.md chap2.md chap3.md metadata.yaml -s -o book.html
+
+Just be sure that the YAML file begins with `---` and ends with `---` or
+`...`. Alternatively, you can use the `--metadata-file` option. Using
+that approach however, you cannot reference content (like footnotes)
+from the main Markdown input document.
+
+Metadata will be taken from the fields of the YAML object and added to any
+existing document metadata.  Metadata can contain lists and objects (nested
+arbitrarily), but all string scalars will be interpreted as Markdown.  Fields
+with names ending in an underscore will be ignored by pandoc.  (They may be
+given a role by external processors.)  Field names must not be
+interpretable as YAML numbers or boolean values (so, for
+example, `yes`, `True`, and `15` cannot be used as field names).
+
+A document may contain multiple metadata blocks.  If two
+metadata blocks attempt to set the same field, the value from
+the second block will be taken.
+
+Each metadata block is handled internally as an independent YAML document.
+This means, for example, that any YAML anchors defined in a block cannot be
+referenced in another block.
+
+When pandoc is used with `-t markdown` to create a Markdown document,
+a YAML metadata block will be produced only if the `-s/--standalone`
+option is used.  All of the metadata will appear in a single block
+at the beginning of the document.
+
+Note that [YAML] escaping rules must be followed. Thus, for example,
+if a title contains a colon, it must be quoted, and if it contains a
+backslash escape, then it must be ensured that it is not treated as a
+[YAML escape sequence]. The pipe character (`|`) can be used to begin
+an indented block that will be interpreted literally, without need for
+escaping. This form is necessary when the field contains blank lines
+or block-level formatting:
+
+    ---
+    title:  'This is the title: it contains a colon'
+    author:
+    - Author One
+    - Author Two
+    keywords: [nothing, nothingness]
+    abstract: |
+      This is the abstract.
+
+      It consists of two paragraphs.
+    ...
+
+The literal block after the `|` must be indented relative to the
+line containing the `|`.  If it is not, the YAML will be invalid
+and pandoc will not interpret it as metadata.  For an overview
+of the complex rules governing YAML, see the [Wikipedia entry on
+YAML syntax].
+
+Template variables will be set automatically from the metadata.  Thus, for
+example, in writing HTML, the variable `abstract` will be set to the HTML
+equivalent of the Markdown in the `abstract` field:
+
+    <p>This is the abstract.</p>
+    <p>It consists of two paragraphs.</p>
+
+Variables can contain arbitrary YAML structures, but the template must match
+this structure.  The `author` variable in the default templates expects a
+simple list or string, but can be changed to support more complicated
+structures.  The following combination, for example, would add an affiliation
+to the author if one is given:
+
+    ---
+    title: The document title
+    author:
+    - name: Author One
+      affiliation: University of Somewhere
+    - name: Author Two
+      affiliation: University of Nowhere
+    ...
+
+To use the structured authors in the example above, you would need a custom
+template:
+
+    $for(author)$
+    $if(author.name)$
+    $author.name$$if(author.affiliation)$ ($author.affiliation$)$endif$
+    $else$
+    $author$
+    $endif$
+    $endfor$
+
+Raw content to include in the document's header may be specified
+using `header-includes`; however, it is important to mark up
+this content as raw code for a particular output format, using
+the [`raw_attribute` extension](#extension-raw_attribute), or it
+will be interpreted as Markdown. For example:
+
+    header-includes:
+    - |
+      ```{=latex}
+      \let\oldsection\section
+      \renewcommand{\section}[1]{\clearpage\oldsection{#1}}
+      ```
+
+Note:  the `yaml_metadata_block` extension works not just with
+`markdown` but with `commonmark` (and it is enabled by default in
+`gfm` and `commonmark_x`). However, in `commonmark`, `gfm`,
+and `commonmark_x`, the following restrictions apply:
+
+- The YAML metadata block must occur at the beginning of the
+  document (and there can be only one).  If multiple files are
+  given as arguments to pandoc, only the first can be a YAML
+  metadata block.
+
+- The leaf nodes of the YAML structure are parsed in isolation from
+  each other and from the rest of the document.  So, for
+  example,  you can't use a reference link in these contexts
+  if the link definition is somewhere else in the document.
+
+[YAML escape sequence]: https://yaml.org/spec/1.2/spec.html#id2776092
+[Wikipedia entry on YAML syntax]:  https://en.wikipedia.org/wiki/YAML#Syntax
+
+## Backslash escapes
+
+### Extension: `all_symbols_escapable` ###
+
+Except inside a code block or inline code, any punctuation or space
+character preceded by a backslash will be treated literally, even if it
+would normally indicate formatting.  Thus, for example, if one writes
+
+    *\*hello\**
+
+one will get
+
+    <em>*hello*</em>
+
+instead of
+
+    <strong>hello</strong>
+
+This rule is easier to remember than original Markdown's rule,
+which allows only the following characters to be backslash-escaped:
+
+    \`*_{}[]()>#+-.!
+
+(However, if the `markdown_strict` format is used, the original Markdown rule
+will be used.)
+
+A backslash-escaped space is parsed as a nonbreaking space. In TeX output,
+it will appear as `~`. In HTML and XML output, it will appear as a
+literal unicode nonbreaking space character (note that it will thus
+actually look "invisible" in the generated HTML source; you can still
+use the `--ascii` command-line option to make it appear as an explicit
+entity).
+
+A backslash-escaped newline (i.e. a backslash occurring at the end of
+a line) is parsed as a hard line break.  It will appear in TeX output as
+`\\` and in HTML as `<br />`.  This is a nice alternative to
+Markdown's "invisible" way of indicating hard line breaks using
+two trailing spaces on a line.
+
+Backslash escapes do not work in verbatim contexts.
+
+## Inline formatting
+
+### Emphasis ###
+
+To *emphasize* some text, surround it with `*`s or `_`, like this:
+
+    This text is _emphasized with underscores_, and this
+    is *emphasized with asterisks*.
+
+Double `*` or `_` produces **strong emphasis**:
+
+    This is **strong emphasis** and __with underscores__.
+
+A `*` or `_` character surrounded by spaces, or backslash-escaped,
+will not trigger emphasis:
+
+    This is * not emphasized *, and \*neither is this\*.
+
+### Extension: `intraword_underscores` ###
+
+Because `_` is sometimes used inside words and identifiers,
+pandoc does not interpret a `_` surrounded by alphanumeric
+characters as an emphasis marker.  If you want to emphasize
+just part of a word, use `*`:
+
+    feas*ible*, not feas*able*.
+
+### Strikeout ###
+
+### Extension: `strikeout` ###
+
+To strike out a section of text with a horizontal line, begin and end it
+with `~~`. Thus, for example,
+
+    This ~~is deleted text.~~
+
+
+### Superscripts and subscripts ###
+
+### Extension: `superscript`, `subscript` ###
+
+Superscripts may be written by surrounding the superscripted text by `^`
+characters; subscripts may be written by surrounding the subscripted
+text by `~` characters.  Thus, for example,
+
+    H~2~O is a liquid.  2^10^ is 1024.
+
+The text between `^...^` or `~...~` may not contain spaces or
+newlines.  If the superscripted or subscripted text contains
+spaces, these spaces must be escaped with backslashes.  (This is
+to prevent accidental superscripting and subscripting through
+the ordinary use of `~` and `^`, and also bad interactions with
+footnotes.) Thus, if you want the letter P with 'a cat' in
+subscripts, use `P~a\ cat~`, not `P~a cat~`.
+
+### Verbatim ###
+
+To make a short span of text verbatim, put it inside backticks:
+
+    What is the difference between `>>=` and `>>`?
+
+If the verbatim text includes a backtick, use double backticks:
+
+    Here is a literal backtick `` ` ``.
+
+(The spaces after the opening backticks and before the closing
+backticks will be ignored.)
+
+The general rule is that a verbatim span starts with a string
+of consecutive backticks (optionally followed by a space)
+and ends with a string of the same number of backticks (optionally
+preceded by a space).
+
+Note that backslash-escapes (and other Markdown constructs) do not
+work in verbatim contexts:
+
+    This is a backslash followed by an asterisk: `\*`.
+
+### Extension: `inline_code_attributes` ###
+
+Attributes can be attached to verbatim text, just as with
+[fenced code blocks]:
+
+    `<$>`{.haskell}
+
+### Underline ###
+
+To underline text, use the `underline` class:
+
+    [Underline]{.underline}
+
+Or, without the `bracketed_spans` extension (but with `native_spans`):
+
+    <span class="underline">Underline</span>
+
+This will work in all output formats that support underline.
+
+### Small caps ###
+
+To write small caps, use the `smallcaps` class:
+
+    [Small caps]{.smallcaps}
+
+Or, without the `bracketed_spans` extension:
+
+    <span class="smallcaps">Small caps</span>
+
+For compatibility with other Markdown flavors, CSS is also supported:
+
+    <span style="font-variant:small-caps;">Small caps</span>
+
+This will work in all output formats that support small caps.
+
+### Highlighting ###
+
+To highlight text, use the `mark` class:
+
+    [Mark]{.mark}
+
+Or, without the `bracketed_spans` extension (but with `native_spans`):
+
+    <span class="mark">Mark</span>
+
+This will work in all output formats that support highlighting.
+
+
+## Math
+
+### Extension: `tex_math_dollars` ###
+
+Anything between two `$` characters will be treated as TeX math.  The
+opening `$` must have a non-space character immediately to its right,
+while the closing `$` must have a non-space character immediately to its
+left, and must not be followed immediately by a digit.  Thus,
+`$20,000 and $30,000` won't parse as math.  If for some reason
+you need to enclose text in literal `$` characters, backslash-escape
+them and they won't be treated as math delimiters.
+
+For display math, use `$$` delimiters.  (In this case, the delimiters
+may be separated from the formula by whitespace.  However, there can be
+no blank lines between the opening and closing `$$` delimiters.)
+
+TeX math will be printed in all output formats. How it is rendered
+depends on the output format:
+
+LaTeX
+  ~ It will appear verbatim surrounded by `\(...\)` (for inline
+    math) or `\[...\]` (for display math).
+
+Markdown, Emacs Org mode, ConTeXt, ZimWiki
+  ~ It will appear verbatim surrounded by `$...$` (for inline
+    math) or `$$...$$` (for display math).
+
+XWiki
+  ~ It will appear verbatim surrounded by `{{formula}}..{{/formula}}`.
+
+reStructuredText
+  ~ It will be rendered using an [interpreted text role `:math:`].
+
+AsciiDoc
+  ~ For AsciiDoc output math will appear verbatim surrounded by
+    `latexmath:[...]`. For `asciidoc_legacy` the bracketed
+    material will also include inline or display math delimiters.
+
+Texinfo
+  ~ It will be rendered inside a `@math` command.
+
+roff man, Jira markup
+  ~ It will be rendered verbatim without `$`'s.
+
+MediaWiki, DokuWiki
+  ~ It will be rendered inside `<math>` tags.
+
+Textile
+  ~ It will be rendered inside `<span class="math">` tags.
+
+RTF, OpenDocument
+  ~ It will be rendered, if possible, using Unicode characters,
+    and will otherwise appear verbatim.
+
+ODT
+  ~ It will be rendered, if possible, using MathML.
+
+DocBook
+  ~ If the `--mathml` flag is used, it will be rendered using MathML
+    in an `inlineequation` or `informalequation` tag.  Otherwise it
+    will be rendered, if possible, using Unicode characters.
+
+Docx and PowerPoint
+  ~ It will be rendered using OMML math markup.
+
+FictionBook2
+  ~ If the `--webtex` option is used, formulas are rendered as images
+    using CodeCogs or other compatible web service, downloaded
+    and embedded in the e-book. Otherwise, they will appear verbatim.
+
+HTML, Slidy, DZSlides, S5, EPUB
+  ~ The way math is rendered in HTML will depend on the
+    command-line options selected. Therefore see [Math rendering in HTML]
+    above.
+
+[interpreted text role `:math:`]: https://docutils.sourceforge.io/docs/ref/rst/roles.html#math
+
+## Raw HTML
+
+### Extension: `raw_html` ###
+
+Markdown allows you to insert raw HTML (or DocBook) anywhere in a document
+(except verbatim contexts, where `<`, `>`, and `&` are interpreted
+literally).  (Technically this is not an extension, since standard
+Markdown allows it, but it has been made an extension so that it can
+be disabled if desired.)
+
+The raw HTML is passed through unchanged in HTML, S5, Slidy, Slideous,
+DZSlides, EPUB, Markdown, CommonMark, Emacs Org mode, and Textile
+output, and suppressed in other formats.
+
+For a more explicit way of including raw HTML in a Markdown
+document, see the [`raw_attribute` extension][Extension: `raw_attribute`].
+
+In the CommonMark format, if `raw_html` is enabled, superscripts,
+subscripts, strikeouts and small capitals will be represented as HTML.
+Otherwise, plain-text fallbacks will be used. Note that even if
+`raw_html` is disabled, tables will be rendered with HTML syntax if
+they cannot use pipe syntax.
+
+### Extension: `markdown_in_html_blocks` ###
+
+Original Markdown allows you to include HTML "blocks":  blocks
+of HTML between balanced tags that are separated from the surrounding text
+with blank lines, and start and end at the left margin.  Within
+these blocks, everything is interpreted as HTML, not Markdown;
+so (for example), `*` does not signify emphasis.
+
+Pandoc behaves this way when the `markdown_strict` format is used; but
+by default, pandoc interprets material between HTML block tags as Markdown.
+Thus, for example, pandoc will turn
+
+    <table>
+    <tr>
+    <td>*one*</td>
+    <td>[a link](https://google.com)</td>
+    </tr>
+    </table>
+
+into
+
+    <table>
+    <tr>
+    <td><em>one</em></td>
+    <td><a href="https://google.com">a link</a></td>
+    </tr>
+    </table>
+
+whereas `Markdown.pl` will preserve it as is.
+
+There is one exception to this rule:  text between `<script>`,
+`<style>`, `<pre>`, and `<textarea>` tags is not interpreted as Markdown.
+
+This departure from original Markdown should make it easier to mix
+Markdown with HTML block elements.  For example, one can surround
+a block of Markdown text with `<div>` tags without preventing it
+from being interpreted as Markdown.
+
+### Extension: `native_divs` ###
+
+Use native pandoc `Div` blocks for content inside `<div>` tags.
+For the most part this should give the same output as
+`markdown_in_html_blocks`, but it makes it easier to write pandoc
+filters to manipulate groups of blocks.
+
+### Extension: `native_spans` ###
+
+Use native pandoc `Span` blocks for content inside `<span>` tags.
+For the most part this should give the same output as `raw_html`,
+but it makes it easier to write pandoc filters to manipulate groups
+of inlines.
+
+### Extension: `raw_tex` ###
+
+In addition to raw HTML, pandoc allows raw LaTeX, TeX, and ConTeXt to be
+included in a document. Inline TeX commands will be preserved and passed
+unchanged to the LaTeX and ConTeXt writers. Thus, for example, you can use
+LaTeX to include BibTeX citations:
+
+    This result was proved in \cite{jones.1967}.
+
+Note that in LaTeX environments, like
+
+    \begin{tabular}{|l|l|}\hline
+    Age & Frequency \\ \hline
+    18--25  & 15 \\
+    26--35  & 33 \\
+    36--45  & 22 \\ \hline
+    \end{tabular}
+
+the material between the begin and end tags will be interpreted as raw
+LaTeX, not as Markdown.
+
+For a more explicit and flexible way of including raw TeX in a
+Markdown document, see the [`raw_attribute`
+extension][Extension: `raw_attribute`].
+
+Inline LaTeX is ignored in output formats other than Markdown, LaTeX,
+Emacs Org mode, and ConTeXt.
+
+### Generic raw attribute ###
+
+### Extension: `raw_attribute` ###
+
+Inline spans and fenced code blocks with a special
+kind of attribute will be parsed as raw content with the
+designated format.  For example, the following produces a raw
+roff `ms` block:
+
+    ```{=ms}
+    .MYMACRO
+    blah blah
+    ```
+And the following produces a raw `html` inline element:
+
+    This is `<a>html</a>`{=html}
+
+This can be useful to insert raw xml into `docx` documents, e.g.
+a pagebreak:
+
+    ```{=openxml}
+    <w:p>
+      <w:r>
+        <w:br w:type="page"/>
+      </w:r>
+    </w:p>
+    ```
+
+The format name should match the target format name (see
+`-t/--to`, above, for a list, or use `pandoc
+--list-output-formats`). Use `openxml` for `docx` output,
+`opendocument` for `odt` output, `html5` for `epub3` output,
+`html4` for `epub2` output, and `latex`, `beamer`,
+`ms`, or `html5` for `pdf` output (depending on what you
+use for `--pdf-engine`).
+
+This extension presupposes that the relevant kind of
+inline code or fenced code block is enabled.  Thus, for
+example, to use a raw attribute with a backtick code block,
+`backtick_code_blocks` must be enabled.
+
+The raw attribute cannot be combined with regular attributes.
+
+## LaTeX macros
+
+### Extension: `latex_macros` ###
+
+When this extension is enabled, pandoc will parse LaTeX
+macro definitions and apply the resulting macros to all LaTeX
+math and raw LaTeX.  So, for example, the following will work in
+all output formats, not just LaTeX:
+
+    \newcommand{\tuple}[1]{\langle #1 \rangle}
+
+    $\tuple{a, b, c}$
+
+Note that LaTeX macros will not be applied if they occur
+inside a raw span or block marked with the
+[`raw_attribute` extension](#extension-raw_attribute).
+
+When `latex_macros` is disabled, the raw LaTeX and math will
+not have macros applied. This is usually a better approach when
+you are targeting LaTeX or PDF.
+
+Macro definitions in LaTeX will be passed through as raw LaTeX
+only if `latex_macros` is not enabled.  Macro definitions in
+Markdown source (or other formats allowing `raw_tex`) will
+be passed through regardless of whether `latex_macros` is
+enabled.
+
+## Links
+
+Markdown allows links to be specified in several ways.
+
+### Automatic links ###
+
+If you enclose a URL or email address in pointy brackets, it
+will become a link:
+
+    <https://google.com>
+    <sam@green.eggs.ham>
+
+### Inline links ###
+
+An inline link consists of the link text in square brackets,
+followed by the URL in parentheses. (Optionally, the URL can
+be followed by a link title, in quotes.)
+
+    This is an [inline link](/url), and here's [one with
+    a title](https://fsf.org "click here for a good time!").
+
+There can be no space between the bracketed part and the parenthesized part.
+The link text can contain formatting (such as emphasis), but the title cannot.
+
+Email addresses in inline links are not autodetected, so they have to be
+prefixed with `mailto`:
+
+    [Write me!](mailto:sam@green.eggs.ham)
+
+### Reference links ###
+
+An *explicit* reference link has two parts, the link itself and the link
+definition, which may occur elsewhere in the document (either
+before or after the link).
+
+The link consists of link text in square brackets, followed by a label in
+square brackets. (There cannot be space between the two unless the
+`spaced_reference_links` extension is enabled.) If the label is empty
+(`[]`), then it will be implicitly be taken to be the same as the link text;
+thus `[foo][]` is equivalent to `[foo][foo]`. (If the
+`shortcut_reference_links` extension is enabled, the empty `[]`
+may be omitted.)
+
+The link definition consists of the bracketed label, followed by
+a colon and a space, followed by the URL, and optionally (after a
+space) a link title either in quotes or in parentheses. The label
+must not be parseable as a citation (assuming the `citations`
+extension is enabled): citations take precedence over link
+labels.
+
+Here are some examples of reference links and link definitions;
+
+    See [the website *I* built][my website].
+
+    See [my website][] and [the bar page][1] and
+    the [home page of the FSF][fsf].
+
+    [my website]: http://foo.bar.baz
+    [1]: /foo/bar.html  "My title, optional"
+    [fsf]: https://fsf.org (The Free Software Foundation)
+    [special page]: /bar#special  'A title in single quotes'
+
+The URL in a link definition may optionally be surrounded by
+angle brackets:
+
+    [my label 5]: <http://foo.bar.baz>
+
+The title may go on the next line:
+
+    [my label 3]: https://fsf.org
+      "The Free Software Foundation"
+
+Note that link labels are not case sensitive.  So, this will work:
+
+    Here is [my link][FOO]
+
+    [Foo]: /bar/baz
+
+The link definition may come either before or after a
+reference link that uses the label.
+
+Note: In some Markdown implementations, reference link
+definitions cannot occur in nested constructions such as list
+items or block quotes. Pandoc lifts this arbitrary-seeming
+restriction. So the following is fine in pandoc, though not in
+all implementations:
+
+    > My block [quote].
+    >
+    > [quote]: /foo
+
+### Extension: `shortcut_reference_links` ###
+
+In a *shortcut* reference link, the second pair of brackets may
+be omitted entirely:
+
+    See [my website].
+
+    [my website]: http://foo.bar.baz
+
+### Internal links ###
+
+To link to another section of the same document, use the automatically
+generated identifier (see [Heading identifiers]). For example:
+
+    See the [Introduction](#introduction).
+
+or
+
+    See the [Introduction].
+
+    [Introduction]: #introduction
+
+Internal links are currently supported for HTML formats (including
+HTML slide shows and EPUB), LaTeX, and ConTeXt.
+
+## Images
+
+A link immediately preceded by a `!` will be treated as an image.
+The link text will be used as the image's alt text:
+
+    ![la lune](lalune.jpg "Voyage to the moon")
+
+    ![movie reel]
+
+    [movie reel]: movie.gif
+
+### Extension: `implicit_figures` ###
+
+An image with nonempty alt text, occurring by itself in a
+paragraph, will be rendered as a figure with a caption.  The
+image's description will be used as the caption.
+
+    ![This is the caption.](image.png)
+
+How this is rendered depends on the output format. Some output
+formats (e.g. RTF) do not yet support figures. In those
+formats, you'll just get an image in a paragraph by itself, with
+no caption.
+
+If you just want a regular inline image, just make sure it is not
+the only thing in the paragraph. One way to do this is to insert a
+nonbreaking space after the image:
+
+    ![This image won't be a figure](image.png)\
+
+Note that in reveal.js slide shows, an image in a paragraph
+by itself that has the `r-stretch` class will fill the screen,
+and the caption and figure tags will be omitted.
+
+To specify an alt text for the image that is different
+from the caption, you can use an explicit attribute (assuming the
+`link_attributes` extension is set):
+
+    ![The caption.](image.png){alt="description of image"}
+
+For LaTeX output, you can specify a [figure's
+positioning](https://www.overleaf.com/learn/latex/Positioning_images_and_tables#The_figure_environment)
+by adding the `latex-placement` attribute.
+
+    ![The caption.](image.png){latex-placement="ht"}
+
+### Extension: `link_attributes` ###
+
+Attributes can be set on links and images:
+
+    An inline ![image](foo.jpg){#id .class width=30 height=20px}
+    and a reference ![image][ref] with attributes.
+
+    [ref]: foo.jpg "optional title" {#id .class key=val key2="val 2"}
+
+(This syntax is compatible with [PHP Markdown Extra] when only `#id`
+and `.class` are used.)
+
+For HTML and EPUB, all known HTML5 attributes except `width` and
+`height` (but including `srcset` and `sizes`) are passed through
+as is. Unknown attributes are passed through as custom
+attributes, with `data-` prepended. The other writers ignore
+attributes that are not specifically supported by their output format.
+
+The `width` and `height` attributes on images are treated specially. When
+used without a unit, the unit is assumed to be pixels. However, any of
+the following unit identifiers can be used: `px`, `cm`, `mm`, `in`, `inch`
+and `%`. There must not be any spaces between the number and the unit.
+For example:
+
+```
+![](file.jpg){ width=50% }
+```
+
+- Dimensions may be converted to a form that is compatible with
+  the output format (for example, dimensions given in pixels will
+  be converted to inches when converting HTML to LaTeX). Conversion
+  between pixels and physical measurements is affected by the
+  `--dpi` option (by default, 96 dpi is assumed, unless the image
+  itself contains dpi information).
+- The `%` unit is generally relative to some available space.
+  For example the above example will render to the following.
+  - HTML: `<img href="file.jpg" style="width: 50%;" />`
+  - LaTeX: `\includegraphics[width=0.5\textwidth,height=\textheight]{file.jpg}`
+    (If you're using a custom template, you need to configure `graphicx`
+    as in the default template.)
+  - ConTeXt: `\externalfigure[file.jpg][width=0.5\textwidth]`
+- Some output formats have a notion of a class
+  ([ConTeXt](https://wiki.contextgarden.net/Using_Graphics#Multiple_Image_Settings))
+  or a unique identifier (LaTeX `\caption`), or both (HTML).
+- When no `width` or `height` attributes are specified, the fallback
+  is to look at the image resolution and the dpi metadata embedded in
+  the image file.
+
+## Divs and Spans
+
+Using the `native_divs` and `native_spans` extensions
+(see [above][Extension: `native_divs`]), HTML syntax can
+be used as part of Markdown to create native `Div` and `Span`
+elements in the pandoc AST (as opposed to raw HTML).
+However, there is also nicer syntax available:
+
+### Extension: `fenced_divs` ###
+
+Allow special fenced syntax for native `Div` blocks.  A Div
+starts with a fence containing at least three consecutive
+colons plus some attributes. The attributes may optionally
+be followed by another string of consecutive colons.
+
+Note:  the `commonmark` parser doesn't permit colons after
+the attributes.
+
+The attribute syntax is exactly as in fenced code blocks (see
+[Extension: `fenced_code_attributes`]).  As with fenced
+code blocks, one can use either attributes in curly braces
+or a single unbraced word, which will be treated as a class
+name.  The Div ends with another line containing a string of at
+least three consecutive colons.  The fenced Div should be
+separated by blank lines from preceding and following blocks.
+
+Example:
+
+    ::::: {#special .sidebar}
+    Here is a paragraph.
+
+    And another.
+    :::::
+
+Fenced divs can be nested.  Opening fences are distinguished
+because they *must* have attributes:
+
+    ::: Warning ::::::
+    This is a warning.
+
+    ::: Danger
+    This is a warning within a warning.
+    :::
+    ::::::::::::::::::
+
+Fences without attributes are always closing fences.  Unlike
+with fenced code blocks, the number of colons in the closing
+fence need not match the number in the opening fence.  However,
+it can be helpful for visual clarity to use fences of different
+lengths to distinguish nested divs from their parents.
+
+
+### Extension: `bracketed_spans` ###
+
+A bracketed sequence of inlines, as one would use to begin
+a link, will be treated as a `Span` with attributes if it is
+followed immediately by attributes:
+
+    [This is *some text*]{.class key="val"}
+
+## Footnotes
+
+### Extension: `footnotes` ###
+
+Pandoc's Markdown allows footnotes, using the following syntax:
+
+    Here is a footnote reference,[^1] and another.[^longnote]
+
+    [^1]: Here is the footnote.
+
+    [^longnote]: Here's one with multiple blocks.
+
+        Subsequent paragraphs are indented to show that they
+    belong to the previous footnote.
+
+            { some.code }
+
+        The whole paragraph can be indented, or just the first
+        line.  In this way, multi-paragraph footnotes work like
+        multi-paragraph list items.
+
+    This paragraph won't be part of the note, because it
+    isn't indented.
+
+The identifiers in footnote references may not contain spaces, tabs,
+newlines, or the characters `^`, `[`, or `]`. These identifiers
+are used only to correlate the footnote reference with the note
+itself; in the output, footnotes will be numbered sequentially.
+
+The footnotes themselves need not be placed at the end of the
+document.  They may appear anywhere except inside other block elements
+(lists, block quotes, tables, etc.).  Each footnote should be
+separated from surrounding content (including other footnotes)
+by blank lines.
+
+### Extension: `inline_notes` ###
+
+Inline footnotes are also allowed (though, unlike regular notes,
+they cannot contain multiple paragraphs).  The syntax is as follows:
+
+    Here is an inline note.^[Inline notes are easier to write, since
+    you don't have to pick an identifier and move down to type the
+    note.]
+
+Inline and regular footnotes may be mixed freely.
+
+## Citation syntax
+
+### Extension: `citations` ###
+
+To cite a bibliographic item with an identifier foo, use the
+syntax `@foo`.  Normal citations should be included in square
+brackets, with semicolons separating distinct items:
+
+    Blah blah [@doe99; @smith2000; @smith2004].
+
+How this is rendered depends on the citation style.  In an
+author-date style, it might render as
+
+    Blah blah (Doe 1999, Smith 2000, 2004).
+
+In a footnote style, it might render as
+
+    Blah blah.[^1]
+
+    [^1]:  John Doe, "Frogs," *Journal of Amphibians* 44 (1999);
+    Susan Smith, "Flies," *Journal of Insects* (2000);
+    Susan Smith, "Bees," *Journal of Insects* (2004).
+
+See the [CSL user documentation] for more information about CSL
+styles and how they affect rendering.
+
+Unless a citation key starts with a letter, digit, or `_`,
+and contains only alphanumerics and single internal punctuation
+characters (`:.#$%&-+?<>~/`), it must be surrounded
+by curly braces, which are not considered part of the key.
+In `@Foo_bar.baz.`, the key is `Foo_bar.baz` because the final
+period is not *internal* punctuation, so it is not included in
+the key.  In `@{Foo_bar.baz.}`, the key is `Foo_bar.baz.`, including
+the final period.
+In `@Foo_bar--baz`, the key is `Foo_bar` because the repeated internal
+punctuation characters terminate the key.
+The curly braces are recommended if you use URLs as
+keys: `[@{https://example.com/bib?name=foobar&date=2000}, p.  33]`.
+
+Citation items may optionally include a prefix, a locator, and
+a suffix.  In
+
+    Blah blah [see @doe99, pp. 33-35 and *passim*; @smith04, chap. 1].
+
+the first item (`doe99`) has prefix `see `, locator `pp.  33-35`,
+and suffix `and *passim*`.  The second item (`smith04`) has
+locator `chap. 1` and no prefix or suffix.
+
+Pandoc uses some heuristics to separate the locator from the
+rest of the subject.  It is sensitive to the locator terms
+defined in the [CSL locale files].  Either abbreviated or
+unabbreviated forms are accepted. In the `en-US` locale, locator
+terms can be written in either singular or plural forms, as
+`book`, `bk.`/`bks.`; `chapter`, `chap.`/`chaps.`; `column`,
+`col.`/`cols.`; `figure`, `fig.`/`figs.`; `folio`,
+`fol.`/`fols.`; `number`, `no.`/`nos.`; `line`, `l.`/`ll.`;
+`note`, `n.`/`nn.`; `opus`, `op.`/`opp.`; `page`, `p.`/`pp.`;
+`paragraph`, `para.`/`paras.`; `part`, `pt.`/`pts.`; `section`,
+`sec.`/`secs.`; `sub verbo`, `s.v.`/`s.vv.`; `verse`,
+`v.`/`vv.`; `volume`, `vol.`/`vols.`; `¶`/`¶¶`; `§`/`§§`. If no
+locator term is used, "page" is assumed.
+
+In complex cases, you can force something to be treated as
+a locator by enclosing it in curly braces or prevent parsing
+the suffix as locator by prepending curly braces:
+
+    [@smith{ii, A, D-Z}, with a suffix]
+    [@smith, {pp. iv, vi-xi, (xv)-(xvii)} with suffix here]
+    [@smith{}, 99 years later]
+
+A minus sign (`-`) before the `@` will suppress mention of
+the author in the citation.  This can be useful when the
+author is already mentioned in the text:
+
+    Smith says blah [-@smith04].
+
+You can also write an author-in-text citation, by omitting the
+square brackets:
+
+    @smith04 says blah.
+
+    @smith04 [p. 33] says blah.
+
+This will cause the author's name to be rendered, followed by
+the bibliographical details.  Use this form when you want to
+make the citation the subject of a sentence.
+
+When you are using a note style, it is usually better to let
+citeproc create the footnotes from citations rather than writing
+an explicit note.  If you do write an explicit note that
+contains a citation, note that normal citations will be put in
+parentheses, while author-in-text citations will not.  For
+this reason, it is sometimes preferable to use the
+author-in-text style inside notes when using a note style.
+
+Many CSL styles will format citations differently when the
+same source has been cited earlier.  In documents with chapters,
+it is usually desirable to reset this position information
+at the beginning of every chapter. To do this, add the class
+`reset-citation-positions` to the heading for each chapter:
+
+    # The Beginning {.reset-citation-positions}
+
+Note that this class only has an effect when placed on
+top-level headings; it is ignored in nested blocks.
+
+[CSL user documentation]: https://citationstyles.org/authors/
+[CSL]: https://docs.citationstyles.org/en/stable/specification.html
+[CSL markup specs]: https://citeproc-js.readthedocs.io/en/latest/csl-json/markup.html#html-like-formatting-tags
+[Chicago Manual of Style]: https://chicagomanualofstyle.org
+[Citation Style Language]: https://citationstyles.org
+[Zotero Style Repository]: https://www.zotero.org/styles
+[finding and editing styles]: https://citationstyles.org/authors/
+[CSL locale files]: https://github.com/citation-style-language/locales
+
+## Non-default extensions
+
+The following Markdown syntax extensions are not enabled by default
+in pandoc, but may be enabled by adding `+EXTENSION` to the format
+name, where `EXTENSION` is the name of the extension.  Thus, for
+example, `markdown+hard_line_breaks` is Markdown with hard line breaks.
+
+### Extension: `rebase_relative_paths` ###
+
+Rewrite relative paths for Markdown links and images, depending
+on the path of the file containing the link or image link.  For
+each link or image, pandoc will compute the directory of the
+containing file, relative to the working directory, and prepend
+the resulting path to the link or image path.
+
+The use of this extension is best understood by example.
+Suppose you have a subdirectory for each chapter of a book,
+`chap1`, `chap2`, `chap3`. Each contains a file `text.md` and a
+number of images used in the chapter.  You would like to have
+`![image](spider.jpg)` in `chap1/text.md` refer to
+`chap1/spider.jpg` and `![image](spider.jpg)` in `chap2/text.md`
+refer to `chap2/spider.jpg`.  To do this, use
+
+    pandoc chap*/*.md -f markdown+rebase_relative_paths
+
+Without this extension, you would have to use
+`![image](chap1/spider.jpg)` in `chap1/text.md` and
+`![image](chap2/spider.jpg)` in `chap2/text.md`.  Links with
+relative paths will be rewritten in the same way as images.
+
+Absolute paths and URLs are not changed.  Neither are empty
+paths or paths consisting entirely of a fragment, e.g., `#foo`.
+
+Note that relative paths in reference links and images will
+be rewritten relative to the file containing the link
+reference definition, not the file containing the reference link
+or image itself, if these differ.
+
+### Extension: `mark` ###
+
+To highlight out a section of text, begin and end it with
+with `==`. Thus, for example,
+
+    This ==is deleted text.==
+
+### Extension: `attributes` ###
+
+Allows attributes to be attached to any inline or block-level
+element when parsing `commonmark`.
+The syntax for the attributes is the same as that
+used in [`header_attributes`][Extension: `header_attributes`].
+
+- Attributes that occur immediately after an inline
+  element affect that element.  If they follow a space, then they
+  belong to the space.  (Hence, this option subsumes
+  `inline_code_attributes` and `link_attributes`.)
+- Attributes that occur immediately before a block
+  element, on a line by themselves, affect that
+  element.
+- Consecutive attribute specifiers may be used,
+  either for blocks or for inlines.  Their attributes
+  will be combined.
+- Attributes that occur at the end of the text of
+  a Setext or ATX heading (separated by whitespace
+  from the text) affect the heading element. (Hence, this
+  option subsumes `header_attributes`.)
+- Attributes that occur after the opening fence
+  in a fenced code block affect the code block element. (Hence,
+  this option subsumes `fenced_code_attributes`.)
+- Attributes that occur at the end of a reference
+  link definition affect links that refer to that
+  definition.
+
+Note that pandoc's AST does not currently allow attributes
+to be attached to arbitrary elements.  Hence a Span or Div
+container will be added if needed.
+
+### Extension: `old_dashes` ###
+
+Selects the pandoc <= 1.8.2.1 behavior for parsing smart dashes:
+`-` before a numeral is an en-dash, and `--` is an em-dash.
+This option only has an effect if `smart` is enabled. It is
+selected automatically for `textile` input.
+
+### Extension: `angle_brackets_escapable` ###
+
+Allow `<` and `>` to be backslash-escaped, as they can be in
+GitHub flavored Markdown but not original Markdown.  This is
+implied by pandoc's default `all_symbols_escapable`.
+
+### Extension: `lists_without_preceding_blankline` ###
+
+Allow a list to occur right after a paragraph, with no intervening
+blank space.
+
+### Extension: `four_space_rule` ###
+
+Selects the pandoc <= 2.0 behavior for parsing lists, so that
+four spaces indent are needed for list item continuation
+paragraphs.
+
+### Extension: `spaced_reference_links` ###
+
+Allow whitespace between the two components of a reference link,
+for example,
+
+    [foo] [bar].
+
+### Extension: `hard_line_breaks` ###
+
+Causes all newlines within a paragraph to be interpreted as hard line
+breaks instead of spaces.
+
+### Extension: `ignore_line_breaks` ###
+
+Causes newlines within a paragraph to be ignored, rather than being
+treated as spaces or as hard line breaks.  This option is intended for
+use with East Asian languages where spaces are not used between words,
+but text is divided into lines for readability.
+
+### Extension: `east_asian_line_breaks` ###
+
+Causes newlines within a paragraph to be ignored, rather than
+being treated as spaces or as hard line breaks, when they occur
+between two East Asian wide characters.  This is a better choice
+than `ignore_line_breaks` for texts that include a mix of East
+Asian wide characters and other characters.
+
+### Extension: `emoji` ###
+
+Parses textual emojis like `:smile:` as Unicode emoticons.
+
+### Extension: `tex_math_gfm` ###
+
+Supports two GitHub-specific formats for math.
+Inline math: ``$`e=mc^2`$``.
+
+Display math:
+
+````
+``` math
+e=mc^2
+```
+````
+
+### Extension: `tex_math_single_backslash` ###
+
+Causes anything between `\(` and `\)` to be interpreted as inline
+TeX math, and anything between `\[` and `\]` to be interpreted
+as display TeX math.  Note: a drawback of this extension is that
+it precludes escaping `(` and `[`.
+
+### Extension: `tex_math_double_backslash` ###
+
+Causes anything between `\\(` and `\\)` to be interpreted as inline
+TeX math, and anything between `\\[` and `\\]` to be interpreted
+as display TeX math.
+
+### Extension: `markdown_attribute` ###
+
+By default, pandoc interprets material inside block-level tags as Markdown.
+This extension changes the behavior so that Markdown is only parsed
+inside block-level tags if the tags have the attribute `markdown=1`.
+
+### Extension: `mmd_title_block` ###
+
+Enables a [MultiMarkdown] style title block at the top of
+the document, for example:
+
+    Title:   My title
+    Author:  John Doe
+    Date:    September 1, 2008
+    Comment: This is a sample mmd title block, with
+             a field spanning multiple lines.
+
+See the MultiMarkdown documentation for details.  If `pandoc_title_block` or
+`yaml_metadata_block` is enabled, it will take precedence over
+`mmd_title_block`.
+
+### Extension: `abbreviations` ###
+
+Parses PHP Markdown Extra abbreviation keys, like
+
+    *[HTML]: Hypertext Markup Language
+
+Note that the pandoc document model does not support
+abbreviations, so if this extension is enabled, abbreviation keys are
+simply skipped (as opposed to being parsed as paragraphs).
+
+### Extension: `alerts` ###
+
+Supports [GitHub-style Markdown alerts], like
+
+    > [!TIP]
+    > Helpful advice for doing things better or more easily.
+
+  [GitHub-style Markdown alerts]: https://docs.github.com/en/get-started/writing-on-github/getting-started-with-writing-and-formatting-on-github/basic-writing-and-formatting-syntax#alerts
+
+### Extension: `autolink_bare_uris` ###
+
+Makes all absolute URIs into links, even when not surrounded by
+pointy braces `<...>`.
+
+### Extension: `mmd_link_attributes` ###
+
+Parses MultiMarkdown-style key-value attributes on link
+and image references. This extension should not be confused with the
+[`link_attributes`](#extension-link_attributes) extension.
+
+    This is a reference ![image][ref] with MultiMarkdown attributes.
+
+    [ref]: https://path.to/image "Image title" width=20px height=30px
+           id=myId class="myClass1 myClass2"
+
+### Extension: `mmd_header_identifiers` ###
+
+Parses MultiMarkdown-style heading identifiers (in square brackets,
+after the heading but before any trailing `#`s in an ATX heading).
+
+### Extension: `gutenberg` ###
+
+Use [Project Gutenberg] conventions for `plain` output:
+all-caps for strong emphasis, surround by underscores
+for regular emphasis, add extra blank space around headings.
+
+  [Project Gutenberg]: https://www.gutenberg.org
+
+### Extension: `sourcepos` ###
+
+Include source position attributes when parsing `commonmark`.
+For elements that accept attributes, a `data-pos` attribute
+is added; other elements are placed in a surrounding
+Div or Span element with a `data-pos` attribute.
+
+### Extension: `short_subsuperscripts` ###
+
+Parse MultiMarkdown-style subscripts and superscripts, which start with
+a '~' or '^' character, respectively, and include the alphanumeric sequence
+that follows. For example:
+
+    x^2 = 4
+
+or
+
+    Oxygen is O~2.
+
+### Extension: `wikilinks_title_after_pipe` ###
+
+Pandoc supports multiple Markdown wikilink syntaxes, regardless of
+whether the title is before or after the pipe.
+
+Using `--from=markdown+wikilinks_title_after_pipe` results in
+```[[Wiki]]
+[[URL|title]]
+```
+
+while using `--from=markdown+wikilinks_title_before_pipe` results
+in
+```[[Wiki]]
+[[title|URL]]
+```
+
+## Markdown variants
+
+In addition to pandoc's extended Markdown, the following Markdown
+variants are supported:
+
+- `markdown_phpextra` (PHP Markdown Extra)
+- `markdown_github` (deprecated GitHub-Flavored Markdown)
+- `markdown_mmd` (MultiMarkdown)
+- `markdown_strict` (Markdown.pl)
+- `commonmark` (CommonMark)
+- `gfm` (Github-Flavored Markdown)
+- `commonmark_x` (CommonMark with many pandoc extensions)
+
+To see which extensions are supported for a given format,
+and which are enabled by default, you can use the command
+
+    pandoc --list-extensions=FORMAT
+
+where `FORMAT` is replaced with the name of the format.
+
+Note that the list of extensions for `commonmark`,
+`gfm`, and `commonmark_x` are defined relative to default
+commonmark.  So, for example, `backtick_code_blocks`
+does not appear as an extension, since it is enabled by
+default and cannot be disabled.
+
+# Citations
+
+When the `--citeproc` option is used, pandoc can automatically generate
+citations and a bibliography in a number of styles.  Basic usage is
+
+    pandoc --citeproc myinput.txt
+
+To use this feature, you will need to have
+
+- a document containing citations (see [Citation syntax]);
+- a source of bibliographic data: either an external bibliography
+  file or a list of `references` in the document's YAML metadata;
+- optionally, a [CSL] citation style.
+
+## Specifying bibliographic data
+
+You can specify an external bibliography using the
+`bibliography` metadata field in a YAML metadata section or the
+`--bibliography` command line argument. If you want to use
+multiple bibliography files, you can supply multiple
+`--bibliography` arguments or set `bibliography` metadata field
+to YAML array.  A bibliography may have any of these formats:
+
+  Format            File extension
+  ------------      --------------
+  BibLaTeX          .bib
+  BibTeX            .bibtex
+  CSL JSON          .json
+  CSL YAML          .yaml
+  RIS               .ris
+
+Note that `.bib` can be used with both BibTeX and BibLaTeX files;
+use the extension `.bibtex` to force interpretation as BibTeX.
+
+In BibTeX and BibLaTeX databases, pandoc parses LaTeX markup
+inside fields such as `title`; in CSL YAML databases, pandoc
+Markdown; and in CSL JSON databases, an [HTML-like markup][CSL
+markup specs]:
+
+`<i>...</i>`
+:   italics
+
+`<b>...</b>`
+:   bold
+
+`<span style="font-variant:small-caps;">...</span>` or `<sc>...</sc>`
+:   small capitals
+
+`<sub>...</sub>`
+:   subscript
+
+`<sup>...</sup>`
+:   superscript
+
+`<span class="nocase">...</span>`
+:   prevent a phrase from being capitalized as title case
+
+As an alternative to specifying a bibliography file using
+`--bibliography` or the YAML metadata field `bibliography`, you
+can include the citation data directly in the `references` field
+of the document's YAML metadata. The field should contain an
+array of YAML-encoded references, for example:
+
+    ---
+    references:
+    - type: article-journal
+      id: WatsonCrick1953
+      author:
+      - family: Watson
+        given: J. D.
+      - family: Crick
+        given: F. H. C.
+      issued:
+        date-parts:
+        - - 1953
+          - 4
+          - 25
+      title: 'Molecular structure of nucleic acids: a structure for
+        deoxyribose nucleic acid'
+      title-short: Molecular structure of nucleic acids
+      container-title: Nature
+      volume: 171
+      issue: 4356
+      page: 737-738
+      DOI: 10.1038/171737a0
+      URL: https://www.nature.com/articles/171737a0
+      language: en-GB
+    ...
+
+If both an external bibliography and inline (YAML metadata)
+references are provided, both will be used. In case of
+conflicting `id`s, the inline references will take precedence.
+
+Note that pandoc can be used to produce such a YAML metadata
+section from a BibTeX, BibLaTeX, or CSL JSON bibliography:
+
+    pandoc chem.bib -s -f biblatex -t markdown
+    pandoc chem.json -s -f csljson -t markdown
+
+Indeed, pandoc can convert between any of these
+citation formats:
+
+    pandoc chem.bib -s -f biblatex -t csljson
+    pandoc chem.yaml -s -f markdown -t biblatex
+
+Running pandoc on a bibliography file with the `--citeproc`
+option will create a formatted bibliography in the format
+of your choice:
+
+    pandoc chem.bib -s --citeproc -o chem.html
+    pandoc chem.bib -s --citeproc -o chem.pdf
+
+### Capitalization in titles
+
+If you are using a bibtex or biblatex bibliography, then observe
+the following rules:
+
+  - English titles should be in title case.  Non-English titles should
+    be in sentence case, and the `langid` field in biblatex should be
+    set to the relevant language.  (The following values are treated
+    as English:  `american`, `british`, `canadian`, `english`,
+    `australian`, `newzealand`, `USenglish`, or `UKenglish`.)
+
+  - As is standard with bibtex/biblatex, proper names should be
+    protected with curly braces so that they won't be lowercased
+    in styles that call for sentence case.  For example:
+
+        title = {My Dinner with {Andre}}
+
+  - In addition, words that should remain lowercase (or camelCase)
+    should be protected:
+
+        title = {Spin Wave Dispersion on the {nm} Scale}
+
+    Though this is not necessary in bibtex/biblatex, it is necessary
+    with citeproc, which stores titles internally in sentence case,
+    and converts to title case in styles that require it.  Here we
+    protect "nm" so that it doesn't get converted to "Nm" at this stage.
+
+If you are using a CSL bibliography (either JSON or YAML), then observe
+the following rules:
+
+  - All titles should be in sentence case.
+
+  - Use the `language` field for non-English titles to prevent their
+    conversion to title case in styles that call for this. (Conversion
+    happens only if `language` begins with `en` or is left empty.)
+
+  - Protect words that should not be converted to title case using
+    this syntax:
+
+        Spin wave dispersion on the <span class="nocase">nm</span> scale
+
+### Conference Papers, Published vs. Unpublished
+
+For a formally published conference paper, use the biblatex entry type
+`inproceedings` (which will be mapped to CSL `paper-conference`).
+
+For an unpublished manuscript, use the biblatex entry type
+`unpublished` without an `eventtitle` field (this entry type
+will be mapped to CSL `manuscript`).
+
+For a talk, an unpublished conference paper, or a poster
+presentation, use the biblatex entry type `unpublished` with an
+`eventtitle` field (this entry type will be mapped to CSL
+`speech`). Use the biblatex `type` field to indicate the type,
+e.g. "Paper", or "Poster". `venue` and `eventdate` may be useful
+too, though `eventdate` will not be rendered by most CSL styles.
+Note that `venue` is for the event's venue, unlike `location`
+which describes the publisher's location; do not use the latter
+for an unpublished conference paper.
+
+
+## Specifying a citation style
+
+Citations and references can be formatted using any style supported by the
+[Citation Style Language], listed in the [Zotero Style Repository].
+These files are specified using the `--csl` option or the `csl`
+(or `citation-style`) metadata field.  By default, pandoc will
+use the [Chicago Manual of Style] author-date format.  (You can
+override this default by copying a CSL style of your choice
+to `default.csl` in your user data directory.)
+The CSL project provides further information on [finding and
+editing styles].
+
+The `--citation-abbreviations` option (or the
+`citation-abbreviations` metadata field) may be used to specify
+a JSON file containing abbreviations of journals that should be
+used in formatted bibliographies when `form="short"` is
+specified.  The format of the file can be illustrated with an
+example:
+
+
+    { "default": {
+        "container-title": {
+                "Lloyd's Law Reports": "Lloyd's Rep",
+                "Estates Gazette": "EG",
+                "Scots Law Times": "SLT"
+        }
+      }
+    }
+
+
+## Citations in note styles
+
+Pandoc's citation processing is designed to allow you to
+move between author-date, numerical, and note styles without
+modifying the Markdown source.  When you're using a note
+style, avoid inserting footnotes manually. Instead, insert
+citations just as you would in an author-date style---for
+example,
+
+    Blah blah [@foo, p. 33].
+
+The footnote will be created automatically. Pandoc will take
+care of removing the space and moving the note before or
+after the period, depending on the setting of
+`notes-after-punctuation`, as described below in [Other relevant
+metadata fields].
+
+In some cases you may need to put a citation inside a regular
+footnote.  Normal citations in footnotes (such as `[@foo, p.
+33]`) will be rendered in parentheses.  In-text citations (such
+as `@foo [p. 33]`) will be rendered without parentheses. (A
+comma will be added if appropriate.)  Thus:
+
+    [^1]:  Some studies [@foo; @bar, p. 33] show that
+    frubulicious zoosnaps are quantical.  For a survey
+    of the literature, see @baz [chap. 1].
+
+
+## Placement of the bibliography
+
+If the style calls for a list of works cited, it will be placed
+in a div with id `refs`, if one exists:[^note-on-refs]
+
+    ::: {#refs}
+    :::
+
+Otherwise, it will be placed at the end of the document.
+Generation of the bibliography can be suppressed by setting
+`suppress-bibliography: true` in the YAML metadata.
+
+[^note-on-refs]:
+    Note that if `--file-scope` is used, a div written this way will be
+    given an identifier of the form `FILE__refs`, to avoid duplicate
+    identifiers (see `--file-scope`). In view of this possibility,
+    pandoc will place the bibliography in any div whose identifier is
+    `refs` *or* ends with `__refs`.
+
+If you wish the bibliography to have a section heading, you can
+set `reference-section-title` in the metadata, or put the heading
+at the beginning of the div with id `refs` (if you are using it)
+or at the end of your document:
+
+    last paragraph...
+
+    # References
+
+The bibliography will be inserted after this heading.  Note that
+the `unnumbered` class will be added to this heading, so that the
+section will not be numbered.
+
+If you want to put the bibliography into a variable in your
+template, one way to do that is to put the div with id `refs`
+into a metadata field, e.g.
+
+    ---
+    refs: |
+       ::: {#refs}
+       :::
+    ...
+
+You can then put the variable `$refs$` into your template where
+you want the bibliography to be placed.
+
+## Including uncited items in the bibliography
+
+If you want to include items in the bibliography without actually
+citing them in the body text, you can define a dummy `nocite` metadata
+field and put the citations there:
+
+    ---
+    nocite: |
+      @item1, @item2
+    ...
+
+    @item3
+
+In this example, the document will contain a citation for `item3`
+only, but the bibliography will contain entries for `item1`, `item2`, and
+`item3`.
+
+It is possible to create a bibliography with all the citations,
+whether or not they appear in the document, by using a wildcard:
+
+    ---
+    nocite: |
+      @*
+    ...
+
+For LaTeX output, you can also use [`natbib`] or [`biblatex`] to
+render the bibliography. In order to do so, specify bibliography
+files as outlined above, and add `--natbib` or `--biblatex`
+argument to pandoc invocation. Bear in mind that bibliography
+files have to be in either BibTeX (for `--natbib`)
+or BibLaTeX (for `--biblatex`) format.
+
+## Other relevant metadata fields
+
+A few other metadata fields affect bibliography formatting:
+
+`link-citations`
+:   If true, citations will be hyperlinked to the
+    corresponding bibliography entries (for author-date and
+    numerical styles only).  Defaults to false.
+
+`link-bibliography`
+:   If true, DOIs, PMCIDs, PMID, and URLs in bibliographies will
+    be rendered as hyperlinks.  (If an entry contains a DOI, PMCID,
+    PMID, or URL, but none of these fields are rendered by the style,
+    then the title, or in the absence of a title the whole entry, will
+    be hyperlinked.)  Defaults to true.
+
+`lang`
+:   The `lang` field will affect how the style is localized,
+    for example in the translation of labels, the use
+    of quotation marks, and the way items are sorted.
+    (For backwards compatibility, `locale` may be used instead
+    of `lang`, but this use is deprecated.)
+
+    A BCP 47 language tag is expected:  for example, `en`,
+    `de`, `en-US`, `fr-CA`, `ug-Cyrl`.  The unicode extension
+    syntax (after `-u-`) may be used to specify options for
+    collation (sorting) more precisely. Here are some examples:
+
+    - `zh-u-co-pinyin`: Chinese with the Pinyin collation.
+    - `es-u-co-trad`: Spanish with the traditional collation
+      (with `Ch` sorting after `C`).
+    - `fr-u-kb`: French with "backwards" accent sorting
+      (with `coté` sorting after `côte`).
+    - `en-US-u-kf-upper`: English with uppercase letters sorting
+       before lower (default is lower before upper).
+
+`notes-after-punctuation`
+:    If true (the default for note styles), pandoc will put
+     footnote references or superscripted numerical citations
+     after following punctuation.  For example, if the source
+     contains `blah blah [@jones99].`, the result will look like
+     `blah blah.[^1]`, with the note moved after the period and
+     the space collapsed.  If false, the space will still be
+     collapsed, but the footnote will not be moved after the
+     punctuation.  The option may also be used in numerical styles
+     that use superscripts for citation numbers (but for these
+     styles the default is not to move the citation).
+
+
+# Slide shows
+
+You can use pandoc to produce an HTML + JavaScript slide presentation
+that can be viewed via a web browser.  There are five ways to do this,
+using [S5], [DZSlides], [Slidy], [Slideous], or [reveal.js].
+You can also produce a PDF slide show using LaTeX [`beamer`], or
+slide shows in Microsoft [PowerPoint] format.
+
+Here's the Markdown source for a simple slide show, `habits.txt`:
+
+    % Habits
+    % John Doe
+    % March 22, 2005
+
+    # In the morning
+
+    ## Getting up
+
+    - Turn off alarm
+    - Get out of bed
+
+    ## Breakfast
+
+    - Eat eggs
+    - Drink coffee
+
+    # In the evening
+
+    ## Dinner
+
+    - Eat spaghetti
+    - Drink wine
+
+    ------------------
+
+    ![picture of spaghetti](images/spaghetti.jpg)
+
+    ## Going to sleep
+
+    - Get in bed
+    - Count sheep
+
+To produce an HTML/JavaScript slide show, simply type
+
+    pandoc -t FORMAT -s habits.txt -o habits.html
+
+where `FORMAT` is either `s5`, `slidy`, `slideous`, `dzslides`, or `revealjs`.
+
+For Slidy, Slideous, reveal.js, and S5, the file produced by
+pandoc with the `-s/--standalone` option embeds a link to
+JavaScript and CSS files, which are assumed to be available at
+the relative path `s5/default` (for S5), `slideous` (for
+Slideous), `reveal.js` (for reveal.js), or at the Slidy website
+at `w3.org` (for Slidy).  (These paths can be changed by setting
+the `slidy-url`, `slideous-url`, `revealjs-url`, or `s5-url`
+variables; see [Variables for HTML slides], above.) For
+DZSlides, the (relatively short) JavaScript and CSS are included
+in the file by default.
+
+With all HTML slide formats, the `--self-contained` option can
+be used to produce a single file that contains all of the data
+necessary to display the slide show, including linked scripts,
+stylesheets, images, and videos.
+
+To produce a PDF slide show using beamer, type
+
+    pandoc -t beamer habits.txt -o habits.pdf
+
+Note that a reveal.js slide show can also be converted to a PDF
+by printing it to a file from the browser.
+
+To produce a PowerPoint slide show, type
+
+    pandoc habits.txt -o habits.pptx
+
+## Structuring the slide show
+
+By default, the *slide level* is the highest heading level in
+the hierarchy that is followed immediately by content, and not another
+heading, somewhere in the document. In the example above, level-1 headings
+are always followed by level-2 headings, which are followed by content,
+so the slide level is 2. This default can be overridden using the
+`--slide-level` option.
+
+The document is carved up into slides according to the following
+rules:
+
+  * A horizontal rule always starts a new slide.
+
+  * A heading at the slide level always starts a new slide.
+
+  * Headings *below* the slide level in the hierarchy create
+    headings *within* a slide.  (In beamer, a "block" will be
+    created.  If the heading has the class `example`, an
+    `exampleblock` environment will be used; if it has the class
+    `alert`, an `alertblock` will be used; otherwise a regular
+    `block` will be used.)
+
+  * Headings *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.
+    Non-slide content under these headings 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
+    by commenting out some lines in the default template.)
+
+These rules are designed to support many different styles of slide show. If
+you don't care about structuring your slides into sections and subsections,
+you can either just use level-1 headings for all slides (in that case, level 1
+will be the slide level) or you can set `--slide-level=0`.
+
+Note:  in reveal.js slide shows, if slide level is 2, a two-dimensional
+layout will be produced, with level-1 headings building horizontally
+and level-2 headings building vertically. It is not recommended that
+you use deeper nesting of section levels with reveal.js unless you set
+`--slide-level=0` (which lets reveal.js produce a one-dimensional layout
+and only interprets horizontal rules as slide boundaries).
+
+### PowerPoint layout choice
+
+When creating slides, the pptx writer chooses from a number of pre-defined
+layouts, based on the content of the slide:
+
+Title Slide
+:   This layout is used for the initial slide, which is generated and
+    filled from the metadata fields `date`, `author`, and `title`, if
+    they are present.
+
+Section Header
+:   This layout is used for what pandoc calls “title slides”, i.e.
+    slides which start with a header which is above the slide level in
+    the hierarchy.
+
+Two Content
+:   This layout is used for two-column slides, i.e. slides containing a
+    div with class `columns` which contains at least two divs with class
+    `column`.
+
+Comparison
+:   This layout is used instead of “Two Content” for any two-column
+    slides in which at least one column contains text followed by
+    non-text (e.g. an image or a table).
+
+Content with Caption
+:   This layout is used for any non-two-column slides which contain text
+    followed by non-text (e.g. an image or a table).
+
+Blank
+:   This layout is used for any slides which only contain blank content,
+    e.g. a slide containing only speaker notes, or a slide containing
+    only a non-breaking space.
+
+Title and Content
+:   This layout is used for all slides which do not match the criteria
+    for another layout.
+
+These layouts are chosen from the default pptx reference doc included with
+pandoc, unless an alternative reference doc is specified using
+`--reference-doc`.
+
+## Incremental lists
+
+By default, these writers produce lists that display "all at once."
+If you want your lists to display incrementally (one item at a time),
+use the `-i` option. If you want a particular list to depart from the
+default, put it in a `div` block with class `incremental` or
+`nonincremental`. So, for example, using the `fenced div` syntax, the
+following would be incremental regardless of the document default:
+
+    ::: incremental
+
+    - Eat spaghetti
+    - Drink wine
+
+    :::
+
+or
+
+    ::: nonincremental
+
+    - Eat spaghetti
+    - Drink wine
+
+    :::
+
+While using `incremental` and `nonincremental` divs is the
+recommended method of setting incremental lists on a per-case basis,
+an older method is also supported: putting lists inside a blockquote
+will depart from the document default (that is, it will display
+incrementally without the `-i` option and all at once with the `-i`
+option):
+
+    > - Eat spaghetti
+    > - Drink wine
+
+Both methods allow incremental and nonincremental lists to be mixed
+in a single document.
+
+If you want to include a block-quoted list, you can work around
+this behavior by putting the list inside a fenced div, so that
+it is not the direct child of the block quote:
+
+    > ::: wrapper
+    > - a
+    > - list in a quote
+    > :::
+
+## Inserting pauses
+
+You can add "pauses" within a slide by including a paragraph containing
+three dots, separated by spaces:
+
+    # Slide with a pause
+
+    content before the pause
+
+    . . .
+
+    content after the pause
+
+Note: this feature is not yet implemented for PowerPoint output.
+
+## Styling the slides
+
+You can change the style of HTML slides by putting customized CSS files
+in `$DATADIR/s5/default` (for S5), `$DATADIR/slidy` (for Slidy),
+or `$DATADIR/slideous` (for Slideous),
+where `$DATADIR` is the user data directory (see `--data-dir`, above).
+The originals may be found in pandoc's system data directory (generally
+`$CABALDIR/pandoc-VERSION/s5/default`). Pandoc will look there for any
+files it does not find in the user data directory.
+
+For dzslides, the CSS is included in the HTML file itself, and may
+be modified there.
+
+All [reveal.js configuration options] can be set through variables.
+For example, themes can be used by setting the `theme` variable:
+
+    -V theme=moon
+
+Or you can specify a custom stylesheet using the `--css` option.
+
+To style beamer slides, you can specify a `theme`, `colortheme`,
+`fonttheme`, `innertheme`, and `outertheme`, using the `-V` option:
+
+    pandoc -t beamer habits.txt -V theme:Warsaw -o habits.pdf
+
+Note that heading attributes will turn into slide attributes
+(on a `<div>` or `<section>`) in HTML slide formats, allowing you
+to style individual slides.  In beamer, a number of heading
+classes and attributes are recognized as frame options and
+will be passed through as options to the frame: see
+[Frame attributes in beamer], below.
+
+## Speaker notes
+
+Speaker notes are supported in reveal.js, PowerPoint (pptx),
+and beamer output. You can add notes to your Markdown document thus:
+
+    ::: notes
+
+    This is my note.
+
+    - It can contain Markdown
+    - like this list
+
+    :::
+
+To show the notes window in reveal.js, press `s` while viewing the
+presentation. Speaker notes in PowerPoint will be available, as usual,
+in handouts and presenter view.
+
+Notes are not yet supported for other slide formats, but the notes
+will not appear on the slides themselves.
+
+### Speaker notes on the title slide (PowerPoint)
+
+For PowerPoint output, the title slide is generated from the document's
+YAML metadata block. To add speaker notes to this slide, use a `notes`
+field in the metadata:
+
+    ---
+    title: My Presentation
+    author: Jane Doe
+    notes: |
+      Welcome everyone to this presentation.
+
+      Remember to introduce yourself and mention the key topics.
+    ---
+
+The `notes` field can contain multiple paragraphs and Markdown formatting.
+
+## Columns
+
+To put material in side by side columns, you can use a native
+div container with class `columns`, containing two or more div
+containers with class `column` and a `width` attribute:
+
+    :::::::::::::: {.columns}
+    ::: {.column width="40%"}
+    contents...
+    :::
+    ::: {.column width="60%"}
+    contents...
+    :::
+    ::::::::::::::
+
+Note: Specifying column widths does not currently work for PowerPoint.
+
+### Additional columns attributes in beamer
+
+The div containers with classes `columns` and `column` can optionally have
+an `align` attribute.
+The class `columns` can optionally have a `totalwidth` attribute or an
+`onlytextwidth` class.
+
+    :::::::::::::: {.columns align=center totalwidth=8em}
+    ::: {.column width="40%"}
+    contents...
+    :::
+    ::: {.column width="60%" align=bottom}
+    contents...
+    :::
+    ::::::::::::::
+
+The `align` attributes on `columns` and `column` can be used with the
+values `top`, `top-baseline`, `center` and `bottom` to vertically align
+the columns. It defaults to `top` in `columns`.
+
+The `totalwidth` attribute limits the width of the columns to the given value.
+
+    :::::::::::::: {.columns align=top .onlytextwidth}
+    ::: {.column width="40%" align=center}
+    contents...
+    :::
+    ::: {.column width="60%"}
+    contents...
+    :::
+    ::::::::::::::
+
+The class `onlytextwidth` sets the `totalwidth` to `\textwidth`.
+
+See Section 12.7 of the [Beamer User's Guide] for more details.
+
+## Frame attributes in beamer
+
+Sometimes it is necessary to add the LaTeX `[fragile]` option to
+a frame in beamer (for example, when using the `minted` environment).
+This can be forced by adding the `fragile` class to the heading
+introducing the slide:
+
+    # Fragile slide {.fragile}
+
+All of the other frame attributes described in Section 8.1 of
+the [Beamer User's Guide] may also be used: `allowdisplaybreaks`,
+`allowframebreaks`, `b`, `c`, `s`, `t`, `environment`, `label`, `plain`,
+`shrink`, `standout`, `noframenumbering`, `squeeze`.
+`allowframebreaks` is recommended especially for bibliographies, as
+it allows multiple slides to be created if the content overfills the
+frame:
+
+    # References {.allowframebreaks}
+
+In addition, the `frameoptions` attribute may be used to
+pass arbitrary frame options to a beamer slide:
+
+    # Heading {frameoptions="squeeze,shrink,customoption=foobar"}
+
+## Background in reveal.js, beamer, and pptx
+
+Background images can be added to self-contained reveal.js slide shows,
+beamer slide shows, and pptx slide shows.
+
+### On all slides (beamer, reveal.js, pptx)
+
+With beamer and reveal.js, the configuration option `background-image` can be
+used either in the YAML metadata block or as a command-line variable to get the same image on every slide.
+
+Note that for reveal.js, the `background-image` will be used as
+a `parallaxBackgroundImage` (see below).
+
+For pptx, you can use a `--reference-doc` in which
+background images have been set on the [relevant
+layouts](#powerpoint-layout-choice).
+
+#### `parallaxBackgroundImage` (reveal.js)
+
+For reveal.js, there is also the reveal.js-native option
+`parallaxBackgroundImage`, which produces a parallax scrolling background.
+You must also set `parallaxBackgroundSize`, and can optionally set
+`parallaxBackgroundHorizontal`
+and `parallaxBackgroundVertical` to configure the scrolling behaviour.
+See the [reveal.js
+documentation](https://revealjs.com/backgrounds/#parallax-background)
+for more details about the meaning of these options.
+
+In reveal.js's overview mode, the parallaxBackgroundImage will show up
+only on the first slide.
+
+### On individual slides (reveal.js, pptx)
+
+To set an image for a particular reveal.js or pptx slide, add
+`{background-image="/path/to/image"}` to the first slide-level heading on the
+slide (which may even be empty).
+
+As the [HTML writers pass unknown attributes
+through](#extension-link_attributes), other reveal.js background settings also
+work on individual slides, including `background-size`, `background-repeat`,
+`background-color`, `transition`, and `transition-speed`. (The `data-` prefix
+will automatically be added.)
+
+Note: `data-background-image` is also supported in pptx for consistency with
+reveal.js – if `background-image` isn’t found, `data-background-image` will be
+checked.
+
+### On the title slide (reveal.js, pptx)
+
+To add a background image to the automatically generated title slide for
+reveal.js, use the `title-slide-attributes` variable in the YAML metadata block.
+It must contain a map of attribute names and values. (Note that the `data-`
+prefix is required here, as it isn’t added automatically.)
+
+For pptx, pass a `--reference-doc` with the background
+image set on the “Title Slide” layout.
+
+### Example (reveal.js)
+
+```
+---
+title: My Slide Show
+parallaxBackgroundImage: /path/to/my/background_image.png
+title-slide-attributes:
+    data-background-image: /path/to/title_image.png
+    data-background-size: contain
+---
+
+## Slide One
+
+Slide 1 has background_image.png as its background.
+
+## {background-image="/path/to/special_image.jpg"}
+
+Slide 2 has a special image for its background, even though the heading has no content.
+```
+
+# EPUBs
+
+## EPUB Metadata
+
+There are two ways to specify metadata for an EPUB. The first is to use
+the `--epub-metadata` option, which takes as its argument an XML file
+with [Dublin Core elements].
+
+The second way is to use YAML, either in a
+[YAML metadata block][Extension: `yaml_metadata_block`] in a Markdown
+document, or in a separate YAML file specified with `--metadata-file`.
+Here is an example of a YAML metadata block with EPUB metadata:
+
+    ---
+    title:
+    - type: main
+      text: My Book
+    - type: subtitle
+      text: An investigation of metadata
+    creator:
+    - role: author
+      text: John Smith
+    - role: editor
+      text: Sarah Jones
+    identifier:
+    - scheme: DOI
+      text: doi:10.234234.234/33
+    publisher:  My Press
+    rights: © 2007 John Smith, CC BY-NC
+    ibooks:
+      version: 1.3.4
+    ...
+
+The following fields are recognized:
+
+`identifier`
+  ~ Either a string value or an object with fields `text` and
+    `scheme`.  Valid values for `scheme` are `ISBN-10`,
+    `GTIN-13`, `UPC`, `ISMN-10`, `DOI`, `LCCN`, `GTIN-14`,
+    `ISBN-13`, `Legal deposit number`, `URN`, `OCLC number`,
+    `Co-publisher’s ISBN-13`, `ISMN-13`, `ISBN-A`, `JP e-code`,
+    `OLCC number`, `JP Magazine ID`, `UPC-12+5`, `BNF Control number`,
+    `ISSN-13`, `ARK`, `Digital file internal version number`.
+
+`title`
+  ~ Either a string value, or an object with fields `file-as` and
+    `type`, or a list of such objects.  Valid values for `type` are
+    `main`, `subtitle`, `short`, `collection`, `edition`, `extended`.
+
+`creator`
+  ~ Either a string value, or an object with fields `role`, `file-as`,
+    and `text`, or a list of such objects.  Valid values for `role` are
+    [MARC relators], but
+    pandoc will attempt to translate the human-readable versions
+    (like "author" and "editor") to the appropriate marc relators.
+
+`contributor`
+  ~ Same format as `creator`.
+
+`date`
+  ~ A string value in `YYYY-MM-DD` format.  (Only the year is necessary.)
+    Pandoc will attempt to convert other common date formats.
+
+`lang` (or legacy: `language`)
+  ~ A string value in [BCP 47] format.  Pandoc will default to the local
+    language if nothing is specified.
+
+`subject`
+  ~ Either a string value, or an object with fields `text`, `authority`,
+    and `term`, or a list of such objects. Valid values for `authority`
+    are either a [reserved authority value] (currently `AAT`, `BIC`,
+    `BISAC`, `CLC`, `DDC`, `CLIL`, `EuroVoc`, `MEDTOP`, `LCSH`, `NDC`,
+    `Thema`, `UDC`, and `WGS`) or an absolute IRI identifying a custom
+    scheme. Valid values for `term` are defined by the scheme.
+
+`description`
+  ~ A string value.
+
+`type`
+  ~ A string value.
+
+`format`
+  ~ A string value.
+
+`relation`
+  ~ A string value.
+
+`coverage`
+  ~ A string value.
+
+`rights`
+  ~ A string value.
+
+`belongs-to-collection`
+  ~ A string value.  Identifies the name of a collection to which
+    the EPUB Publication belongs.
+
+`group-position`
+  ~ The `group-position` field indicates the numeric position in which
+    the EPUB Publication belongs relative to other works belonging to
+    the same `belongs-to-collection` field.
+
+`cover-image`
+  ~ A string value (path to cover image).
+
+`css` (or legacy: `stylesheet`)
+  ~ A string value (path to CSS stylesheet).
+
+`page-progression-direction`
+  ~ Either `ltr` or `rtl`. Specifies the `page-progression-direction`
+    attribute for the [`spine` element].
+
+`accessModes`
+  ~ An array of strings ([schema][accessibility schema]).
+    Defaults to `["textual"]`.
+
+`accessModeSufficient`
+  ~ An array of strings ([schema][accessibility schema]).
+    Defaults to `["textual"]`.
+
+`accessibilityHazards`
+  ~ An array of strings ([schema][accessibility schema]).
+    Defaults to `["none"]`.
+
+`accessibilityFeatures`
+  ~ An array of strings ([schema][accessibility schema]).
+    Defaults to
+
+        - "alternativeText"
+        - "readingOrder"
+        - "structuralNavigation"
+        - "tableOfContents"
+
+`accessibilitySummary`
+  ~ A string value.
+
+`ibooks`
+  ~ iBooks-specific metadata, with the following fields:
+
+    - `version`: (string)
+    - `specified-fonts`: `true`|`false` (default `false`)
+    - `ipad-orientation-lock`: `portrait-only`|`landscape-only`
+    - `iphone-orientation-lock`: `portrait-only`|`landscape-only`
+    - `binding`: `true`|`false` (default `true`)
+    - `scroll-axis`: `vertical`|`horizontal`|`default`
+
+[accessibility schema]:  https://kb.daisy.org/publishing/docs/metadata/schema.org/index.html
+[MARC relators]: https://loc.gov/marc/relators/relaterm.html
+[reserved authority value]: https://idpf.github.io/epub-registries/authorities/
+[`spine` element]: http://idpf.org/epub/301/spec/epub-publications.html#sec-spine-elem
+
+## The `epub:type` attribute
+
+For `epub3` output, you can mark up the heading that corresponds to an EPUB
+chapter using the [`epub:type` attribute][epub-type]. For example, to set
+the attribute to the value `prologue`, use this Markdown:
+
+    # My chapter {epub:type=prologue}
+
+Which will result in:
+
+    <body epub:type="frontmatter">
+      <section epub:type="prologue">
+        <h1>My chapter</h1>
+
+Pandoc will output `<body epub:type="bodymatter">`, unless
+you use one of the following values, in which case either
+`frontmatter` or `backmatter` will be output.
+
+`epub:type` of first section      `epub:type` of body
+----------------------------      ------------------
+prologue                          frontmatter
+abstract                          frontmatter
+acknowledgments                   frontmatter
+copyright-page                    frontmatter
+dedication                        frontmatter
+credits                           frontmatter
+keywords                          frontmatter
+imprint                           frontmatter
+contributors                      frontmatter
+other-credits                     frontmatter
+errata                            frontmatter
+revision-history                  frontmatter
+titlepage                         frontmatter
+halftitlepage                     frontmatter
+seriespage                        frontmatter
+foreword                          frontmatter
+preface                           frontmatter
+frontispiece                      frontmatter
+appendix                          backmatter
+colophon                          backmatter
+bibliography                      backmatter
+index                             backmatter
+
+[epub-type]: http://www.idpf.org/epub/31/spec/epub-contentdocs.html#sec-epub-type-attribute
+
+## Linked media
+
+By default, pandoc will download media referenced from any `<img>`, `<audio>`,
+`<video>` or `<source>` element present in the generated EPUB,
+and include it in the EPUB container, yielding a completely
+self-contained EPUB.  If you want to link to external media resources
+instead, use raw HTML in your source and add `data-external="1"` to the tag
+with the `src` attribute.  For example:
+
+    <audio controls="1">
+      <source src="https://example.com/music/toccata.mp3"
+              data-external="1" type="audio/mpeg">
+      </source>
+    </audio>
+
+If the input format already is HTML then `data-external="1"` will work
+as expected for `<img>` elements. Similarly, for Markdown, external
+images can be declared with `![img](url){external=1}`. Note that this
+only works for images; the other media elements have no native
+representation in pandoc's AST and require the use of raw HTML.
+
+## EPUB styling
+
+By default, pandoc will include some basic styling
+contained in its `epub.css` data file.  (To see this,
+use `pandoc --print-default-data-file epub.css`.)
+To use a different CSS file, just use the `--css` command
+line option.  A few inline styles are defined in addition; these
+are essential for correct formatting of pandoc's HTML output.
+
+The `document-css` variable may be set if the more opinionated
+styling of pandoc's default HTML templates is desired (and
+in that case the variables defined in [Variables for HTML] may
+be used to fine-tune the style).
+
+# Chunked HTML
+
+`pandoc -t chunkedhtml` will produce a zip archive of linked
+HTML files, one for each section of the original document.
+Internal links will automatically be adjusted to point to
+the right place, images linked to under the working directory
+will be incorporated, and navigation links will be added.
+In addition, a JSON file `sitemap.json` will be included
+describing the hierarchical structure of the files.
+
+If an output file without an extension is specified, then
+it will be interpreted as a directory and the zip archive
+will be automatically unpacked into it (unless it already
+exists, in which case an error will be raised).  Otherwise
+a `.zip` file will be produced.
+
+The navigation links can be customized by adjusting the
+template.  By default, a table of contents is included only
+on the top page. To include it on every page, set the
+`toc` variable manually.
+
+# Jupyter notebooks
+
+When creating a [Jupyter notebook], pandoc will try to infer the
+notebook structure.  Code blocks with the class `code` will be
+taken as code cells, and intervening content will be taken as
+Markdown cells.  Attachments will automatically be created for
+images in Markdown cells. Metadata will be taken from the
+`jupyter` metadata field.  For example:
+
+````
+---
+title: My notebook
+jupyter:
+  nbformat: 4
+  nbformat_minor: 5
+  kernelspec:
+     display_name: Python 2
+     language: python
+     name: python2
+  language_info:
+     codemirror_mode:
+       name: ipython
+       version: 2
+     file_extension: ".py"
+     mimetype: "text/x-python"
+     name: "python"
+     nbconvert_exporter: "python"
+     pygments_lexer: "ipython2"
+     version: "2.7.15"
+---
+
+# Lorem ipsum
+
+**Lorem ipsum** dolor sit amet, consectetur adipiscing elit. Nunc luctus
+bibendum felis dictum sodales.
+
+``` code
+print("hello")
+```
+
+## Pyout
+
+``` code
+from IPython.display import HTML
+HTML("""
+<script>
+console.log("hello");
+</script>
+<b>HTML</b>
+""")
+```
+
+## Image
+
+This image ![image](myimage.png) will be
+included as a cell attachment.
+````
+
+If you want to add cell attributes, group cells differently, or
+add output to code cells, then you need to include divs to
+indicate the structure. You can use either [fenced
+divs][Extension: `fenced_divs`] or [native divs][Extension:
+`native_divs`] for this.  Here is an example:
+
+````
+:::::: {.cell .markdown}
+# Lorem
+
+**Lorem ipsum** dolor sit amet, consectetur adipiscing elit. Nunc luctus
+bibendum felis dictum sodales.
+::::::
+
+:::::: {.cell .code execution_count=1}
+``` {.python}
+print("hello")
+```
+
+::: {.output .stream .stdout}
+```
+hello
+```
+:::
+::::::
+
+:::::: {.cell .code execution_count=2}
+``` {.python}
+from IPython.display import HTML
+HTML("""
+<script>
+console.log("hello");
+</script>
+<b>HTML</b>
+""")
+```
+
+::: {.output .execute_result execution_count=2}
+```{=html}
+<script>
+console.log("hello");
+</script>
+<b>HTML</b>
+hello
+```
+:::
+::::::
+````
+
+If you include raw HTML or TeX in an output cell, use the
+[raw attribute](#extension-raw_attribute), as shown
+in the last cell of the example above.  Although pandoc can
+process "bare" raw HTML and TeX, the result is often
+interspersed raw elements and normal textual elements, and
+in an output cell pandoc expects a single, connected raw
+block.  To avoid using raw HTML or TeX except when
+marked explicitly using raw attributes, we recommend
+specifying the extensions `-raw_html-raw_tex+raw_attribute` when
+translating between Markdown and ipynb notebooks.
+
+Note that options and extensions that affect reading and
+writing of Markdown will also affect Markdown cells in ipynb
+notebooks.  For example, `--wrap=preserve` will preserve
+soft line breaks in Markdown cells; `--markdown-headings=setext` will
+cause Setext-style headings to be used; and `--preserve-tabs` will
+prevent tabs from being turned to spaces.
+
+# Vimdoc
+
+Vimdoc writer generates Vim help files and makes use of the following metadata
+variables:
+
+``` yaml
+abstract: "A short description"
+author: Author
+title: Title
+
+# Vimdoc-specific
+filename: "definition-lists.txt"
+vimdoc-prefix: pandoc
+```
+
+Complete header requires `abstract`, `author`, `title` and `filename` to
+be set. Compiling file with such metadata produces the following file
+(assumes `--standalone`, see [Templates]):
+
+``` vimdoc
+*definition-lists.txt*  A short description
+
+                            Title by Author
+
+
+                                 Type |gO| to see the table of contents.
+
+[...]
+
+ vim:tw=72:sw=4:ts=4:ft=help:norl:et:
+```
+
+If `vimdoc-prefix` is set, all non-command tags are prefixed with its
+value, it is used to prevent tag collision: all headers have a tag
+(either inferred or explicit) and multiple help pages can have the same
+header names, therefore collision is to be expected. Let our input be
+the following markdown file:
+
+``` markdown
+## Header
+
+`:[range]Fnl {expr}`{#:Fnl}
+:   Evaluates {expr} or range
+
+`vim.b`{#vim.b}
+:   Buffer-scoped (`:h b:`) variables for the current buffer. Invalid or unset
+    key returns `nil`. Can be indexed with an integer to access variables for a
+    specific buffer.
+
+[Span]{#span}
+:   generic inline container for phrasing content, which does not inherently
+    represent anything.
+```
+
+Convert it to vimdoc:
+
+``` vimdoc
+------------------------------------------------------------------------
+Header                                                            *header*
+
+:[range]Fnl {expr}                                                  *:Fnl*
+    Evaluates {expr} or range
+`vim.b`                                                            *vim.b*
+    Buffer-scoped (|b:|) variables for the current buffer. Invalid or
+    unset key returns `nil`. Can be indexed with an integer to access
+    variables for a specific buffer.
+Span                                                                *span*
+    generic inline container for phrasing content, which does not
+    inherently represent anything.
+```
+
+Convert it to vimdoc with metadata variable set (e.g. with
+`-M vimdoc-prefix=pandoc`)
+
+``` vimdoc
+------------------------------------------------------------------------
+Header                                                     *pandoc-header*
+
+:[range]Fnl {expr}                                                  *:Fnl*
+    Evaluates {expr} or range
+`vim.b`                                                     *pandoc-vim.b*
+    Buffer-scoped (|b:|) variables for the current buffer. Invalid or
+    unset key returns `nil`. Can be indexed with an integer to access
+    variables for a specific buffer.
+Span                                                         *pandoc-span*
+    generic inline container for phrasing content, which does not
+    inherently represent anything.
+```
+
+`vim.b` and `Span` got their prefixes but not `:Fnl` because ex-commands
+(those starting with `:`) don't get a prefix, since they are considered
+unique across help pages.
+
+In both cases `:help b:` became reference `|b:|` (also works with
+`:h b:`). Links pointing to either <https://vimhelp.org/> or
+<https://neovim.io/doc/user> become references too.
+
+Vim traditionally wraps at 78, but Pandoc defaults to 72. Use
+`--columns 78` to match Vim.
+
+# Syntax highlighting
+
+Pandoc will automatically highlight syntax in [fenced code blocks] that
+are marked with a language name.  The Haskell library [skylighting] is
+used for highlighting. Currently highlighting is supported only for
+HTML, EPUB, Docx, Ms, Man, Typst, and LaTeX/PDF output. To see a list
+of language names that pandoc will recognize, type `pandoc
+--list-highlight-languages`.
+
+The color scheme can be selected using the `--syntax-highlighting`
+option. The default color scheme is `pygments`, which imitates the
+default color scheme used by the Python library pygments (though
+pygments is not actually used to do the highlighting). To see a
+list of highlight styles, type `pandoc --list-highlight-styles`.
+
+If you are not satisfied with the predefined styles, you can use
+`--print-highlight-style` to generate a JSON `.theme` file which
+can be modified and used as the argument to
+`--syntax-highlighting`. To get a JSON version of the `pygments`
+style, for example:
+
+    pandoc -o my.theme --print-highlight-style pygments
+
+Then edit `my.theme` and use it like this:
+
+    pandoc --syntax-highlighting my.theme
+
+If you are not satisfied with the built-in highlighting, or you
+want to highlight a language that isn't supported, you can use the
+`--syntax-definition` option to load a [KDE-style XML syntax definition
+file](https://docs.kde.org/stable5/en/kate/katepart/highlight.html).
+Before writing your own, have a look at KDE's [repository of syntax
+definitions](https://github.com/KDE/syntax-highlighting/tree/master/data/syntax).
+
+If you receive an error that pandoc "Could not read highlighting theme",
+check that the JSON file is encoded with UTF-8 and has no Byte-Order Mark (BOM).
+
+To disable highlighting, use `--syntax-highlighting=none`.
+
+To use a format's idiomatic syntax highlighting instead of
+pandoc's built-in highlighting, use `--syntax-highlighting=idiomatic`.
+Currently, `idiomatic` only affects the following formats:
+
+- In reveal.js, it causes reveal.js's highlighting plugin to be
+  used for source code highlighting.  The style may be customized
+  by setting the `highlightjs-theme` variable.
+
+- In Typst, it causes Typst's built-in highlighting to be used.
+  (This is also the default for Typst.)
+
+- In LaTeX, it causes the [`listings`][] package  to be used. Note that
+  `listings` does not support multi-byte encoding for source code. To handle
+  UTF-8 you would need to use a custom template. This issue is fully
+  documented here: [Encoding issue with the listings package][].
+
+- In other formats, `idiomatic` will have the same result as `default`.
+
+[skylighting]: https://github.com/jgm/skylighting
+
+# Custom Styles
+
+Custom styles can be used in the docx, odt and ICML formats.
+
+## Output
+
+By default, pandoc's odt, 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 doc](#option--reference-doc) 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, Span, or Table with the attribute
+`custom-style`, pandoc will apply your specified style to the
+contained elements (with the exception of elements whose function
+depends on a style, like headings, code blocks, block quotes, or
+links). So, for example, using the `bracketed_spans` syntax,
+
+    [Get out]{custom-style="Emphatically"}, he said.
+
+would produce a 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.
+
+Styles will be defined in the output file as inheriting
+from normal text (docx) or Default Paragraph Style (odt), if the
+styles are not yet in your [reference doc](#option--reference-doc).
+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 or odt output, you don't need to enable any extensions for
+custom styles to work.
+
+For icml output, you can also set an `object-style` in images:
+
+    ![Image with object style](myImage.jpg){object-style="fixedSizeImage"}
+
+In InDesign you'll see that object style given to the image,
+and you'll be able to customize it, or load its definition from
+a template of yours.
+
+[pandoc filters]: https://pandoc.org/filters.html
+
+## Input
+
+The docx reader, by default, only reads those styles that it can
+convert into pandoc elements, either by direct conversion or
+interpreting the derivation of the input document's styles.
+
+By enabling the [`styles` extension](#ext-styles) in the docx reader
+(`-f docx+styles`), you can produce output that maintains the styles
+of the input document, using the `custom-style` class. A `custom-style`
+attribute will be added for each style. Divs will be created to
+hold the paragraph styles, and Spans to hold the character styles.
+Table styles will be applied directly to the Table.
+
+For example, using the `custom-style-reference.docx` file in the test
+directory, we have the following different outputs:
+
+Without the `+styles` extension:
+
+    $ pandoc test/docx/custom-style-reference.docx -f docx -t markdown
+    This is some text.
+
+    This is text with an *emphasized* text style. And this is text with a
+    **strengthened** text style.
+
+    > Here is a styled paragraph that inherits from Block Text.
+
+And with the extension:
+
+    $ pandoc test/docx/custom-style-reference.docx -f docx+styles -t markdown
+
+    ::: {custom-style="First Paragraph"}
+    This is some text.
+    :::
+
+    ::: {custom-style="Body Text"}
+    This is text with an [emphasized]{custom-style="Emphatic"} text style.
+    And this is text with a [strengthened]{custom-style="Strengthened"}
+    text style.
+    :::
+
+    ::: {custom-style="My Block Style"}
+    > Here is a styled paragraph that inherits from Block Text.
+    :::
+
+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.
+
+# Custom readers and writers
+
+Pandoc can be extended with custom readers and writers written
+in [Lua].  (Pandoc includes a Lua interpreter, so Lua need not
+be installed separately.)
+
+To use a custom reader or writer, simply specify the path to the
+Lua script in place of the input or output format. For example:
+
+    pandoc -t data/sample.lua
+    pandoc -f my_custom_markup_language.lua -t latex -s
+
+If the script is not found relative to the working directory,
+it will be sought in the `custom` subdirectory of the user data
+directory (see `--data-dir`).
+
+A custom reader is a Lua script that defines one function,
+Reader, which takes a string as input and returns a Pandoc
+AST.  See the [Lua filters documentation] for documentation
+of the functions that are available for creating pandoc
+AST elements.  For parsing, the [lpeg] parsing library
+is available by default. To see a sample custom reader:
+
+    pandoc --print-default-data-file creole.lua
+
+If you want your custom reader to have access to reader options
+(e.g. the tab stop setting), you give your Reader function a
+second `options` parameter.
+
+A custom writer is a Lua script that defines a function
+that specifies how to render each element in a Pandoc AST.
+See the [djot-writer.lua] for a full-featured example.
+
+Note that custom writers have no default template.  If you want
+to use `--standalone` with a custom writer, you will need to
+specify a template manually using `--template` or add a new
+default template with the name
+`default.NAME_OF_CUSTOM_WRITER.lua` to the `templates`
+subdirectory of your user data directory (see [Templates]).
+
+[Lua]: https://www.lua.org
+[lpeg]:  http://www.inf.puc-rio.br/~roberto/lpeg/
+[djot-writer.lua]: https://github.com/jgm/djot.lua/blob/main/djot-writer.lua
+
+# Reproducible builds
+
+Some of the document formats pandoc targets (such as EPUB,
+docx, and ODT) include build timestamps in the generated document.
+That means that the files generated on successive builds will
+differ, even if the source does not.  To avoid this, set the
+`SOURCE_DATE_EPOCH` environment variable, and the timestamp will
+be taken from it instead of the current time.
+`SOURCE_DATE_EPOCH` should contain an integer unix timestamp
+(specifying the number of seconds since midnight UTC January 1, 1970).
+
+For reproducible builds with LaTeX, you can either specify the
+`pdf-trailer-id` in the metadata or leave it undefined, in which
+case pandoc will create a trailer-id based on a hash of the
+`SOURCE_DATE_EPOCH` and the document's contents.
+
+Some document formats also include a unique identifier.  For
+EPUB, this can be set explicitly by setting the `identifier`
+metadata field (see [EPUB Metadata], above).
+
+# Accessible PDFs and PDF archiving standards
+
+PDF is a flexible format, and using PDF in certain contexts
+requires additional conventions. For example, PDFs are not
+accessible by default; they define how characters are placed on a
+page but do not contain semantic information on the content.
+However, it is possible to generate accessible PDFs, which use
+tagging to add semantic information to the document.
+
+Pandoc defaults to LaTeX to generate PDF. LaTeX's `\DocumentMetadata`
+interface supports PDF standards and tagging when using LuaLaTeX;
+set the `pdfstandard` variable to enable this (see below). For older
+LaTeX installations, alternative engines must be used.
+
+The PDF standards PDF/A and PDF/UA define further restrictions
+intended to optimize PDFs for archiving and accessibility. Tagging
+is commonly used in combination with these standards to ensure
+best results.
+
+Note, however, that standard compliance depends on many things,
+including the colorspace of embedded images. Pandoc cannot check
+this, and external programs must be used to ensure that generated
+PDFs are in compliance.
+
+## LaTeX
+
+Set the `pdfstandard` variable to produce tagged PDFs conforming
+to PDF/A, PDF/X, or PDF/UA standards. For example:
+
+    pandoc -V pdfstandard=ua-2 --pdf-engine=lualatex doc.md -o doc.pdf
+
+Multiple standards can be combined:
+
+    ---
+    pdfstandard:
+      - ua-2
+      - a-4f
+    ---
+
+The required PDF version is inferred automatically. This feature
+requires LuaLaTeX in TeX Live 2025 with LaTeX kernel 2025-06-01
+or newer.
+
+## ConTeXt
+
+ConTeXt always produces tagged PDFs, but the quality depends on
+the input. The default ConTeXt markup generated by pandoc is
+optimized for readability and reuse, not tagging. Enable the
+[`tagging`](#extension--tagging) format extension to force markup
+that is optimized for tagging. For example:
+
+    pandoc -t context+tagging doc.md -o doc.pdf
+
+A recent `context` version should be used, as older versions
+contained a bug that lead to invalid PDF metadata.
+
+## WeasyPrint
+
+The HTML-based engine WeasyPrint includes experimental support for
+PDF/A and PDF/UA since version 57. Tagged PDFs can created with
+
+    pandoc --pdf-engine=weasyprint \
+           --pdf-engine-opt=--pdf-variant=pdf/ua-1 ...
+
+The feature is experimental and standard compliance should not be
+assumed.
+
+## Prince XML
+
+The non-free HTML-to-PDF converter `prince` has extensive support
+for various PDF standards as well as tagging. E.g.:
+
+    pandoc --pdf-engine=prince \
+           --pdf-engine-opt=--tagged-pdf ...
+
+See the prince documentation for more info.
+
+## Typst
+
+Typst 0.12 can produce PDF/A-2b:
+
+    pandoc --pdf-engine=typst --pdf-engine-opt=--pdf-standard=a-2b ...
+
+## Word Processors
+
+Word processors like LibreOffice and MS Word can also be used to
+generate standardized and tagged PDF output. Pandoc does not
+support direct conversions via these tools. However, pandoc can
+convert a document to a `docx` or `odt` file, which can then be
+opened and converted to PDF with the respective word processor.
+See the documentation for [Word][word-accessible-pdfs] and
+[LibreOffice][lo-pdf-export].
+
+[word-accessible-pdfs]: https://support.microsoft.com/en-us/office/create-accessible-pdfs-064625e0-56ea-4e16-ad71-3aa33bb4b7ed
+[lo-pdf-export]: https://help.libreoffice.org/latest/en-US/text/shared/01/ref_pdf_export_general.html
+
+
+# Running pandoc as a web server
+
+If you rename (or symlink) the pandoc executable to
+`pandoc-server`, or if you call pandoc with `server` as the first
+argument, it will start up a web server with a JSON API. This
+server exposes most of the conversion functionality of pandoc. For
+full documentation, see the [pandoc-server] man page.
+
+If you rename (or symlink) the pandoc executable to
+`pandoc-server.cgi`, it will function as a CGI program
+exposing the same API as `pandoc-server`.
+
+`pandoc-server` is designed to be maximally secure; it uses
+Haskell's type system to provide strong guarantees that no I/O
+will be performed on the server during pandoc conversions.
+
+[pandoc-server]: https://github.com/jgm/pandoc/blob/master/doc/pandoc-server.md
+
+# Running pandoc as a Lua interpreter
+
+Calling the pandoc executable under the name `pandoc-lua` or with
+`lua` as the first argument will make it function as a standalone
+Lua interpreter. The behavior is mostly identical to that of the
+[standalone `lua` executable][lua standalone], version 5.4.
+All `pandoc.*` packages, as well as the packages `re` and `lpeg`,
+are available via global variables. Furthermore, the globals
+`PANDOC_VERSION`, `PANDOC_STATE`, and `PANDOC_API_VERSION` are
+set at startup. For full documentation, see the [pandoc-lua] man page.
+
+[lua standalone]: https://www.lua.org/manual/5.4/manual.html#7
+[pandoc-lua]: https://github.com/jgm/pandoc/blob/master/doc/pandoc-lua.md
+
+# A note on security
+
+1. Although pandoc itself will not create or modify any files other
+   than those you explicitly ask it create (with the exception
+   of temporary files used in producing PDFs), a filter or custom
+   writer could in principle do anything on your file system. Please
+   audit filters and custom writers very carefully before using them.
+
+2. Several input formats (including LaTeX, Org, RST, and Typst)
+   support `include` directives that allow the contents of a file to be
+   included in the output. An untrusted attacker could use these
+   to view the contents of files on the file system. (Using the
+   `--sandbox` option can protect against this threat.)
+
+3. Several output formats (including RTF, FB2, HTML with
+   `--self-contained`, EPUB, Docx, and ODT) will embed encoded
+   or raw images into the output file.  An untrusted attacker
+   could exploit this to view the contents of non-image files on the
+   file system.  (Using the `--sandbox` option can protect
+   against this threat, but will also prevent including images in
+   these formats.)
+
+4. In reading HTML files, pandoc will attempt to include the
+   contents of `iframe` elements by fetching content from the
+   local file or URL specified by `src`. If untrusted HTML is
+   processed on a server, this has the potential to reveal anything
+   readable by the process running the server. Using the `-f html+raw_html`
+   will mitigate this threat by causing the whole `iframe`
+   to be parsed as a raw HTML block. Using `--sandbox` will also
+   protect against the threat.
+
+5. If your application uses pandoc as a Haskell library (rather than
+   shelling out to the executable), it is possible to use it in a mode
+   that fully isolates pandoc from your file system, by running the
+   pandoc operations in the `PandocPure` monad. See the document
+   [Using the pandoc API](https://pandoc.org/using-the-pandoc-api.html)
+   for more details. (This corresponds to the use of the `--sandbox`
+   option on the command line.)
+
+6. Pandoc's parsers can exhibit pathological performance on some
+   corner cases.  It is wise to put any pandoc operations under
+   a timeout, to avoid DOS attacks that exploit these issues.
+   If you are using the pandoc executable, you can add the
+   command line options `+RTS -M512M -RTS` (for example) to limit
+   the heap size to 512MB.  Note that the `commonmark` parser
+   (including `commonmark_x` and `gfm`) is much less vulnerable
+   to pathological performance than the `markdown` parser, so
+   it is a better choice when processing untrusted input.
+
+7. The HTML generated by pandoc is not guaranteed to be safe.
+   If `raw_html` is enabled for the Markdown input, users can
+   inject arbitrary HTML.  Even if `raw_html` is disabled,
+   users can include dangerous content in URLs and attributes.
+   To be safe, you should run all HTML generated from untrusted
+   user input through an HTML sanitizer.
+
+# Authors
+
+Copyright 2006--2024 John MacFarlane (jgm@berkeley.edu). Released
+under the [GPL], version 2 or greater.  This software carries no
+warranty of any kind.  (See COPYRIGHT for full copyright and
+warranty notices.) For a full list of contributors, see the file
+AUTHORS.md in the pandoc source code.
+
+[GPL]: https://www.gnu.org/copyleft/gpl.html "GNU General Public License"
+[YAML]: https://yaml.org/spec/1.2/spec.html "YAML v1.2 Spec"
diff --git a/README.md b/README.md
--- a/README.md
+++ b/README.md
@@ -1,155 +1,300 @@
-Pandoc
-======
+<!-- Do not edit this file.  It is generated automatically from
+README.template and MANUAL.txt via the command:
+pandoc --lua-filter tools/update-readme.lua README.template -o README.md
+-->
 
-[![github release](https://img.shields.io/github/release/jgm/pandoc.svg?label=current+release)](https://github.com/jgm/pandoc/releases)
-[![hackage release](https://img.shields.io/hackage/v/pandoc.svg?label=hackage)](http://hackage.haskell.org/package/pandoc)
-[![homebrew](https://img.shields.io/homebrew/v/pandoc.svg)](http://brewformulas.org/Pandoc)
-[![stackage LTS package](http://stackage.org/package/pandoc/badge/lts)](http://stackage.org/lts/package/pandoc)
-[![travis build status](https://img.shields.io/travis/jgm/pandoc/master.svg?label=travis+build)](https://travis-ci.org/jgm/pandoc)
-[![appveyor build status](https://ci.appveyor.com/api/projects/status/nvqs4ct090igjiqc?svg=true)](https://ci.appveyor.com/project/jgm/pandoc)
+# Pandoc
+
+[![github
+release](https://img.shields.io/github/release/jgm/pandoc.svg?label=current+release)](https://github.com/jgm/pandoc/releases)
+[![hackage
+release](https://img.shields.io/hackage/v/pandoc.svg?label=hackage)](https://hackage.haskell.org/package/pandoc)
+[![homebrew](https://img.shields.io/homebrew/v/pandoc.svg)](https://formulae.brew.sh/formula/pandoc)
+[![stackage LTS
+package](https://stackage.org/package/pandoc/badge/lts)](https://www.stackage.org/lts/package/pandoc)
+[![CI
+tests](https://github.com/jgm/pandoc/workflows/CI%20tests/badge.svg)](https://github.com/jgm/pandoc/actions)
 [![license](https://img.shields.io/badge/license-GPLv2+-lightgray.svg)](https://www.gnu.org/licenses/gpl.html)
-[![pandoc-discuss on google groups](https://img.shields.io/badge/pandoc-discuss-red.svg?style=social)](https://groups.google.com/forum/#!forum/pandoc-discuss)
+[![pandoc-discuss on google
+groups](https://img.shields.io/badge/pandoc-discuss-red.svg?style=social)](https://groups.google.com/forum/#!forum/pandoc-discuss)
 
+## The universal markup converter
 
-The universal markup converter
-------------------------------
+Pandoc is a [Haskell](https://haskell.org) library for converting from
+one markup format to another, and a command-line tool that uses this
+library.
 
-Pandoc is a [Haskell] library for converting from one markup format to
-another, and a command-line tool that uses this library. It can read
-[Markdown], [CommonMark], [PHP Markdown Extra], [GitHub-Flavored
-Markdown], [MultiMarkdown], and (subsets of) [Textile],
-[reStructuredText], [HTML], [LaTeX], [MediaWiki markup], [TWiki markup],
-[TikiWiki markup], [Creole 1.0], [Haddock markup], [OPML], [Emacs Org mode],
-[DocBook], [JATS], [Muse], [txt2tags], [Vimwiki], [EPUB], [ODT], and
-[Word docx]; and it can write plain text, [Markdown], [CommonMark], [PHP
-Markdown Extra], [GitHub-Flavored Markdown], [MultiMarkdown],
-[reStructuredText], [XHTML], [HTML5], [LaTeX] \(including
-[`beamer`] slide shows\), [ConTeXt], [RTF], [OPML], [DocBook], [JATS],
-[OpenDocument], [ODT], [Word docx], [GNU Texinfo], [MediaWiki
-markup], [DokuWiki markup], [ZimWiki markup], [Haddock markup],
-[EPUB] \(v2 or v3\), [FictionBook2], [Textile], [groff man],
-[groff ms], [Emacs Org mode], [AsciiDoc], [InDesign ICML], [TEI
-Simple], [Muse], [PowerPoint] slide shows and [Slidy], [Slideous],
-[DZSlides], [reveal.js] or [S5] HTML slide shows. It can also produce
-[PDF] output on systems where LaTeX, ConTeXt, `pdfroff`, `wkhtmltopdf`,
-`prince`, or `weasyprint` is installed.
+It can convert *from*
 
-Pandoc's enhanced version of Markdown includes syntax for [footnotes],
-[tables], flexible [ordered lists], [definition lists], [fenced code
-blocks], [superscripts and subscripts], [strikeout], [metadata blocks],
-automatic tables of contents, embedded LaTeX [math], [citations], and
-[Markdown inside HTML block elements](#extension-markdown_in_html_blocks).
-(These enhancements, described further under
-[Pandoc's Markdown], can be disabled using the `markdown_strict` input
-or output format.)
+<div id="input-formats">
 
-In contrast to most existing tools for converting Markdown to HTML, which
-use regex substitutions, pandoc has a modular design: it consists of a
-set of readers, which parse text in a given format and produce a native
-representation of the document, and a set of writers, which convert
-this native representation into a target format. Thus, adding an input
-or output format requires only adding a reader or writer.
+- `asciidoc` ([AsciiDoc](https://asciidoc.org/) markup)
+- `bibtex` ([BibTeX](https://ctan.org/pkg/bibtex) bibliography)
+- `biblatex` ([BibLaTeX](https://ctan.org/pkg/biblatex) bibliography)
+- `bits` ([BITS](https://jats.nlm.nih.gov/extensions/bits/) XML, alias
+  for `jats`)
+- `commonmark` ([CommonMark](https://commonmark.org) Markdown)
+- `commonmark_x` ([CommonMark](https://commonmark.org) Markdown with
+  extensions)
+- `creole` ([Creole 1.0](http://www.wikicreole.org/wiki/Creole1.0))
+- `csljson` ([CSL
+  JSON](https://citeproc-js.readthedocs.io/en/latest/csl-json/markup.html)
+  bibliography)
+- `csv` ([CSV](https://tools.ietf.org/html/rfc4180) table)
+- `tsv`
+  ([TSV](https://www.iana.org/assignments/media-types/text/tab-separated-values)
+  table)
+- `djot` ([Djot markup](https://djot.net))
+- `docbook` ([DocBook](https://docbook.org))
+- `docx` ([Word docx](https://en.wikipedia.org/wiki/Office_Open_XML))
+- `dokuwiki` ([DokuWiki markup](https://www.dokuwiki.org/dokuwiki))
+- `endnotexml` ([EndNote XML
+  bibliography](https://support.clarivate.com/Endnote/s/article/EndNote-XML-Document-Type-Definition))
+- `epub` ([EPUB](http://idpf.org/epub))
+- `fb2`
+  ([FictionBook2](http://www.fictionbook.org/index.php/Eng:XML_Schema_Fictionbook_2.1)
+  e-book)
+- `gfm` ([GitHub-Flavored
+  Markdown](https://help.github.com/articles/github-flavored-markdown/)),
+  or the deprecated and less accurate `markdown_github`; use
+  [`markdown_github`](https://pandoc.org/MANUAL.html#markdown-variants)
+  only if you need extensions not supported in
+  [`gfm`](https://pandoc.org/MANUAL.html#markdown-variants).
+- `haddock` ([Haddock
+  markup](https://www.haskell.org/haddock/doc/html/ch03s08.html))
+- `html` ([HTML](https://www.w3.org/html/))
+- `ipynb` ([Jupyter
+  notebook](https://nbformat.readthedocs.io/en/latest/))
+- `jats` ([JATS](https://jats.nlm.nih.gov) XML)
+- `jira`
+  ([Jira](https://jira.atlassian.com/secure/WikiRendererHelpAction.jspa?section=all)/Confluence
+  wiki markup)
+- `json` (JSON version of native AST)
+- `latex` ([LaTeX](https://www.latex-project.org/))
+- `markdown` ([Pandoc’s
+  Markdown](https://pandoc.org/MANUAL.html#pandocs-markdown))
+- `markdown_mmd`
+  ([MultiMarkdown](https://fletcherpenney.net/multimarkdown/))
+- `markdown_phpextra` ([PHP Markdown
+  Extra](https://michelf.ca/projects/php-markdown/extra/))
+- `markdown_strict` (original unextended
+  [Markdown](https://daringfireball.net/projects/markdown/))
+- `mediawiki` ([MediaWiki
+  markup](https://www.mediawiki.org/wiki/Help:Formatting))
+- `man` ([roff man](https://man.cx/groff_man(7)))
+- `mdoc` ([mdoc](https://mandoc.bsd.lv/man/mdoc.7.html) manual page
+  markup)
+- `muse` ([Muse](https://amusewiki.org/library/manual))
+- `native` (native Haskell)
+- `odt` ([OpenDocument text
+  document](https://en.wikipedia.org/wiki/OpenDocument))
+- `opml` ([OPML](https://opml.org/spec2.opml))
+- `org` ([Emacs Org mode](https://orgmode.org))
+- `pod` (Perl’s [Plain Old
+  Documentation](https://perldoc.perl.org/perlpod))
+- `pptx`
+  ([PowerPoint](https://en.wikipedia.org/wiki/Microsoft_PowerPoint))
+- `ris` ([RIS](https://en.wikipedia.org/wiki/RIS_(file_format))
+  bibliography)
+- `rtf` ([Rich Text
+  Format](https://en.wikipedia.org/wiki/Rich_Text_Format))
+- `rst`
+  ([reStructuredText](https://docutils.sourceforge.io/docs/ref/rst/introduction.html))
+- `t2t` ([txt2tags](https://txt2tags.org))
+- `textile` ([Textile](https://textile-lang.com))
+- `tikiwiki` ([TikiWiki
+  markup](https://doc.tiki.org/Wiki-Syntax-Text#The_Markup_Language_Wiki-Syntax))
+- `twiki` ([TWiki
+  markup](https://twiki.org/cgi-bin/view/TWiki/TextFormattingRules))
+- `typst` ([typst](https://typst.app))
+- `vimwiki` ([Vimwiki](https://vimwiki.github.io))
+- `xlsx` ([Excel
+  spreadsheet](https://en.wikipedia.org/wiki/Microsoft_Excel#File_formats))
+- `xml` (XML version of native AST)
+- the path of a custom Lua reader, see [Custom readers and
+  writers](https://pandoc.org/MANUAL.html#custom-readers-and-writers)
+  below
 
-Because pandoc's intermediate representation of a document is less
-expressive than many of the formats it converts between, one should
-not expect perfect conversions between every format and every other.
-Pandoc attempts to preserve the structural elements of a document, but
-not formatting details such as margin size.  And some document elements,
-such as complex tables, may not fit into pandoc's simple document
-model.  While conversions from pandoc's Markdown to all formats aspire
-to be perfect, conversions from formats more expressive than pandoc's
-Markdown can be expected to be lossy.
+</div>
 
-[Markdown]: http://daringfireball.net/projects/markdown/
-[CommonMark]: http://commonmark.org
-[PHP Markdown Extra]: https://michelf.ca/projects/php-markdown/extra/
-[GitHub-Flavored Markdown]: https://help.github.com/articles/github-flavored-markdown/
-[MultiMarkdown]: http://fletcherpenney.net/multimarkdown/
-[reStructuredText]: http://docutils.sourceforge.net/docs/ref/rst/introduction.html
-[S5]: http://meyerweb.com/eric/tools/s5/
-[Slidy]: http://www.w3.org/Talks/Tools/Slidy/
-[Slideous]: http://goessner.net/articles/slideous/
-[HTML]: http://www.w3.org/html/
-[HTML5]: http://www.w3.org/TR/html5/
-[XHTML]: http://www.w3.org/TR/xhtml1/
-[LaTeX]: http://latex-project.org
-[`beamer`]: https://ctan.org/pkg/beamer
-[Beamer User's Guide]: http://ctan.math.utah.edu/ctan/tex-archive/macros/latex/contrib/beamer/doc/beameruserguide.pdf
-[ConTeXt]: http://www.contextgarden.net/
-[RTF]: http://en.wikipedia.org/wiki/Rich_Text_Format
-[Creole 1.0]: http://www.wikicreole.org/wiki/Creole1.0
-[DocBook]: http://docbook.org
-[JATS]: https://jats.nlm.nih.gov
-[txt2tags]: http://txt2tags.org
-[EPUB]: http://idpf.org/epub
-[OPML]: http://dev.opml.org/spec2.html
-[OpenDocument]: http://opendocument.xml.org
-[ODT]: http://en.wikipedia.org/wiki/OpenDocument
-[Textile]: http://redcloth.org/textile
-[MediaWiki markup]: https://www.mediawiki.org/wiki/Help:Formatting
-[DokuWiki markup]: https://www.dokuwiki.org/dokuwiki
-[ZimWiki markup]: http://zim-wiki.org/manual/Help/Wiki_Syntax.html
-[TWiki markup]: http://twiki.org/cgi-bin/view/TWiki/TextFormattingRules
-[Haddock markup]: https://www.haskell.org/haddock/doc/html/ch03s08.html
-[groff man]: http://man7.org/linux/man-pages/man7/groff_man.7.html
-[groff ms]: http://man7.org/linux/man-pages/man7/groff_ms.7.html
-[Haskell]: https://www.haskell.org
-[GNU Texinfo]: http://www.gnu.org/software/texinfo/
-[Emacs Org mode]: http://orgmode.org
-[AsciiDoc]: http://www.methods.co.nz/asciidoc/
-[DZSlides]: http://paulrouget.com/dzslides/
-[Word docx]: https://en.wikipedia.org/wiki/Office_Open_XML
-[PDF]: https://www.adobe.com/pdf/
-[reveal.js]: http://lab.hakim.se/reveal-js/
-[FictionBook2]: http://www.fictionbook.org/index.php/Eng:XML_Schema_Fictionbook_2.1
-[InDesign ICML]: https://www.adobe.com/content/dam/Adobe/en/devnet/indesign/cs55-docs/IDML/idml-specification.pdf
-[TEI Simple]: https://github.com/TEIC/TEI-Simple
-[Muse]: https://amusewiki.org/library/manual
-[PowerPoint]: https://en.wikipedia.org/wiki/Microsoft_PowerPoint
-[Vimwiki]: https://vimwiki.github.io
+It can convert *to*
 
+<div id="output-formats">
 
+- `ansi` (text with [ANSI escape
+  codes](https://en.wikipedia.org/wiki/ANSI_escape_code), for terminal
+  viewing)
+- `asciidoc` (modern [AsciiDoc](https://asciidoc.org/) as interpreted by
+  [AsciiDoctor](https://asciidoctor.org/))
+- `asciidoc_legacy` ([AsciiDoc](https://asciidoc.org/) as interpreted by
+  [`asciidoc-py`](https://github.com/asciidoc-py/asciidoc-py)).
+- `asciidoctor` (deprecated synonym for `asciidoc`)
+- `bbcode` [BBCode](https://www.bbcode.org/reference.php)
+- `bbcode_fluxbb` [BBCode
+  (FluxBB)](https://web.archive.org/web/20210623155046/https://fluxbb.org/forums/help.php#bbcode)
+- `bbcode_phpbb` [BBCode
+  (phpBB)](https://www.phpbb.com/community/help/bbcode)
+- `bbcode_steam` [BBCode
+  (Steam)](https://steamcommunity.com/comment/ForumTopic/formattinghelp)
+- `bbcode_hubzilla` [BBCode
+  (Hubzilla)](https://hubzilla.org/help/member/bbcode)
+- `bbcode_xenforo` [BBCode
+  (xenForo)](https://www.xenfocus.com/community/help/bb-codes/)
+- `beamer` ([LaTeX beamer](https://ctan.org/pkg/beamer) slide show)
+- `bibtex` ([BibTeX](https://ctan.org/pkg/bibtex) bibliography)
+- `biblatex` ([BibLaTeX](https://ctan.org/pkg/biblatex) bibliography)
+- `chunkedhtml` (zip archive of multiple linked HTML files)
+- `commonmark` ([CommonMark](https://commonmark.org) Markdown)
+- `commonmark_x` ([CommonMark](https://commonmark.org) Markdown with
+  extensions)
+- `context` ([ConTeXt](https://www.contextgarden.net/))
+- `csljson` ([CSL
+  JSON](https://citeproc-js.readthedocs.io/en/latest/csl-json/markup.html)
+  bibliography)
+- `djot` ([Djot markup](https://djot.net))
+- `docbook` or `docbook4` ([DocBook](https://docbook.org) 4)
+- `docbook5` (DocBook 5)
+- `docx` ([Word docx](https://en.wikipedia.org/wiki/Office_Open_XML))
+- `dokuwiki` ([DokuWiki markup](https://www.dokuwiki.org/dokuwiki))
+- `epub` or `epub3` ([EPUB](http://idpf.org/epub) v3 book)
+- `epub2` (EPUB v2)
+- `fb2`
+  ([FictionBook2](http://www.fictionbook.org/index.php/Eng:XML_Schema_Fictionbook_2.1)
+  e-book)
+- `gfm` ([GitHub-Flavored
+  Markdown](https://help.github.com/articles/github-flavored-markdown/)),
+  or the deprecated and less accurate `markdown_github`; use
+  [`markdown_github`](https://pandoc.org/MANUAL.html#markdown-variants)
+  only if you need extensions not supported in
+  [`gfm`](https://pandoc.org/MANUAL.html#markdown-variants).
+- `haddock` ([Haddock
+  markup](https://www.haskell.org/haddock/doc/html/ch03s08.html))
+- `html` or `html5` ([HTML](https://www.w3.org/html/),
+  i.e. [HTML5](https://html.spec.whatwg.org/)/XHTML [polyglot
+  markup](https://www.w3.org/TR/html-polyglot/))
+- `html4` ([XHTML](https://www.w3.org/TR/xhtml1/) 1.0 Transitional)
+- `icml` ([InDesign
+  ICML](https://web.archive.org/web/20211006210211/https://wwwimages.adobe.com/www.adobe.com/content/dam/acom/en/devnet/indesign/sdk/cs6/idml/idml-cookbook.pdf))
+- `ipynb` ([Jupyter
+  notebook](https://nbformat.readthedocs.io/en/latest/))
+- `jats_archiving` ([JATS](https://jats.nlm.nih.gov) XML, Archiving and
+  Interchange Tag Set)
+- `jats_articleauthoring` ([JATS](https://jats.nlm.nih.gov) XML, Article
+  Authoring Tag Set)
+- `jats_publishing` ([JATS](https://jats.nlm.nih.gov) XML, Journal
+  Publishing Tag Set)
+- `jats` (alias for `jats_archiving`)
+- `jira`
+  ([Jira](https://jira.atlassian.com/secure/WikiRendererHelpAction.jspa?section=all)/Confluence
+  wiki markup)
+- `json` (JSON version of native AST)
+- `latex` ([LaTeX](https://www.latex-project.org/))
+- `man` ([roff man](https://man.cx/groff_man(7)))
+- `markdown` ([Pandoc’s
+  Markdown](https://pandoc.org/MANUAL.html#pandocs-markdown))
+- `markdown_mmd`
+  ([MultiMarkdown](https://fletcherpenney.net/multimarkdown/))
+- `markdown_phpextra` ([PHP Markdown
+  Extra](https://michelf.ca/projects/php-markdown/extra/))
+- `markdown_strict` (original unextended
+  [Markdown](https://daringfireball.net/projects/markdown/))
+- `markua` ([Markua](https://leanpub.com/markua/read))
+- `mediawiki` ([MediaWiki
+  markup](https://www.mediawiki.org/wiki/Help:Formatting))
+- `ms` ([roff ms](https://man.cx/groff_ms(7)))
+- `muse` ([Muse](https://amusewiki.org/library/manual))
+- `native` (native Haskell)
+- `odt` ([OpenDocument text
+  document](https://en.wikipedia.org/wiki/OpenDocument))
+- `opml` ([OPML](https://opml.org/spec2.opml))
+- `opendocument` ([OpenDocument
+  XML](https://www.oasis-open.org/2021/06/16/opendocument-v1-3-oasis-standard-published/))
+- `org` ([Emacs Org mode](https://orgmode.org))
+- `pdf` ([PDF](https://www.adobe.com/pdf/))
+- `plain` (plain text)
+- `pptx`
+  ([PowerPoint](https://en.wikipedia.org/wiki/Microsoft_PowerPoint)
+  slide show)
+- `rst`
+  ([reStructuredText](https://docutils.sourceforge.io/docs/ref/rst/introduction.html))
+- `rtf` ([Rich Text
+  Format](https://en.wikipedia.org/wiki/Rich_Text_Format))
+- `texinfo` ([GNU Texinfo](https://www.gnu.org/software/texinfo/))
+- `textile` ([Textile](https://textile-lang.com))
+- `slideous` ([Slideous](https://goessner.net/articles/slideous/) HTML
+  and JavaScript slide show)
+- `slidy` ([Slidy](https://www.w3.org/Talks/Tools/Slidy2/) HTML and
+  JavaScript slide show)
+- `dzslides` ([DZSlides](https://paulrouget.com/dzslides/) HTML5 +
+  JavaScript slide show)
+- `revealjs` ([reveal.js](https://revealjs.com/) HTML5 + JavaScript
+  slide show)
+- `s5` ([S5](https://meyerweb.com/eric/tools/s5/) HTML and JavaScript
+  slide show)
+- `tei` ([TEI Simple](https://github.com/TEIC/TEI-Simple))
+- `typst` ([typst](https://typst.app))
+- `vimdoc`
+  ([Vimdoc](https://vimhelp.org/helphelp.txt.html#help-writing))
+- `xml` (XML version of native AST)
+- `xwiki` ([XWiki
+  markup](https://www.xwiki.org/xwiki/bin/view/Documentation/UserGuide/Features/XWikiSyntax/))
+- `zimwiki` ([ZimWiki
+  markup](https://zim-wiki.org/manual/Help/Wiki_Syntax.html))
+- the path of a custom Lua writer, see [Custom readers and
+  writers](https://pandoc.org/MANUAL.html#custom-readers-and-writers)
+  below
 
-[footnotes]: http://pandoc.org/MANUAL.html#footnotes
-[tables]: http://pandoc.org/MANUAL.html#tables
-[ordered lists]: http://pandoc.org/MANUAL.html#ordered-lists
-[definition lists]: http://pandoc.org/MANUAL.html#definition-lists
-[fenced code blocks]: http://pandoc.org/MANUAL.html#fenced-code-blocks
-[superscripts and subscripts]: http://pandoc.org/MANUAL.html#superscripts-and-subscripts
-[strikeout]: http://pandoc.org/MANUAL.html#strikeout
-[metadata blocks]: http://pandoc.org/MANUAL.html#metadata-blocks
-[math]: http://pandoc.org/MANUAL.html#math
-[citations]: http://pandoc.org/MANUAL.html#citations
-[Markdown inside HTML block elements]: http://pandoc.org/MANUAL.html#extension-markdown_in_html_blocks
-[Pandoc's Markdown]: http://pandoc.org/MANUAL.html#pandocs-markdown
+</div>
 
-Installing
-----------
+Pandoc can also produce PDF output via LaTeX, Groff ms, or HTML.
 
-Here's [how to install pandoc](INSTALL.md).
+Pandoc’s enhanced version of Markdown includes syntax for tables,
+definition lists, metadata blocks, footnotes, citations, math, and much
+more. See the User’s Manual below under [Pandoc’s
+Markdown](https://pandoc.org/MANUAL.html#pandocs-markdown).
 
-Documentation
--------------
+Pandoc has a modular design: it consists of a set of readers, which
+parse text in a given format and produce a native representation of the
+document (an *abstract syntax tree* or AST), and a set of writers, which
+convert this native representation into a target format. Thus, adding an
+input or output format requires only adding a reader or writer. Users
+can also run custom pandoc filters to modify the intermediate AST (see
+the documentation for [filters](https://pandoc.org/filters.html) and
+[Lua filters](https://pandoc.org/lua-filters.html)).
 
-Pandoc's website contains a full [User's Guide](https://pandoc.org/MANUAL.html).
-It is also available [here](MANUAL.txt) as pandoc-flavored Markdown.
-The website also contains some [examples of the use of
-pandoc](https://pandoc.org/demos.html) and a limited [online
-demo](https://pandoc.org/try).
+Because pandoc’s intermediate representation of a document is less
+expressive than many of the formats it converts between, one should not
+expect perfect conversions between every format and every other. Pandoc
+attempts to preserve the structural elements of a document, but not
+formatting details such as margin size. And some document elements, such
+as complex tables, may not fit into pandoc’s simple document model.
+While conversions from pandoc’s Markdown to all formats aspire to be
+perfect, conversions from formats more expressive than pandoc’s Markdown
+can be expected to be lossy.
 
-Contributing
-------------
+## Installing
 
-Pull requests, bug reports, and feature requests are welcome.  Please make
-sure to read [the contributor guidelines](CONTRIBUTING.md) before opening a
-new issue.
+Here’s [how to install pandoc](INSTALL.md).
 
+## Documentation
 
-License
--------
+Pandoc’s website contains a full [User’s
+Guide](https://pandoc.org/MANUAL.html). It is also available
+[here](MANUAL.txt) as pandoc-flavored Markdown. The website also
+contains some [examples of the use of
+pandoc](https://pandoc.org/demos.html), a limited [online
+demo](https://pandoc.org/try), and a [WebAssembly-based online
+demo](https://pandoc.org/app).
 
-© 2006-2017 John MacFarlane (jgm@berkeley.edu). Released under the
-[GPL], version 2 or greater.  This software carries no warranty of
-any kind.  (See COPYRIGHT for full copyright and warranty notices.)
+## Contributing
 
-[GPL]: http://www.gnu.org/copyleft/gpl.html "GNU General Public License"
+Pull requests, bug reports, and feature requests are welcome. Please
+make sure to read [the contributor guidelines](CONTRIBUTING.md) before
+opening a new issue.
+
+## License
+
+© 2006-2024 John MacFarlane (jgm@berkeley.edu). Released under the
+[GPL](https://www.gnu.org/licenses/old-licenses/gpl-2.0.html "GNU General Public License"),
+version 2 or greater. This software carries no warranty of any kind.
+(See COPYRIGHT for full copyright and warranty notices.)
diff --git a/Setup.hs b/Setup.hs
deleted file mode 100644
--- a/Setup.hs
+++ /dev/null
@@ -1,38 +0,0 @@
-{-
-Copyright (C) 2006-2017 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
--}
-
-import Distribution.Simple
-import Distribution.Simple.Setup (CopyFlags(..), fromFlag)
-import Distribution.PackageDescription (PackageDescription(..))
-import Distribution.Simple.Utils (notice, installOrdinaryFiles)
-import Distribution.Simple.LocalBuildInfo
-
-main :: IO ()
-main = defaultMainWithHooks $ simpleUserHooks {
-      postCopy = installManPage
-    }
-
-installManPage :: Args -> CopyFlags
-               -> PackageDescription -> LocalBuildInfo -> IO ()
-installManPage _ flags pkg lbi = do
-  let verbosity = fromFlag (copyVerbosity flags)
-  let copydest  = fromFlag (copyDest flags)
-  let mandest   = mandir (absoluteInstallDirs pkg lbi copydest)
-                     ++ "/man1"
-  notice verbosity $ "Copying man page to " ++ mandest
-  installOrdinaryFiles verbosity mandest [("man", "pandoc.1")]
diff --git a/benchmark/benchmark-pandoc.hs b/benchmark/benchmark-pandoc.hs
--- a/benchmark/benchmark-pandoc.hs
+++ b/benchmark/benchmark-pandoc.hs
@@ -1,5 +1,6 @@
+{-# LANGUAGE OverloadedStrings #-}
 {-
-Copyright (C) 2012-2017 John MacFarlane <jgm@berkeley.edu>
+Copyright (C) 2012-2024 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
@@ -16,73 +17,89 @@
 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 -}
 import Text.Pandoc
+import Text.Pandoc.MIME
+import Control.DeepSeq (force)
+import Control.Monad.Except (throwError)
 import qualified Text.Pandoc.UTF8 as UTF8
-import Data.Text (Text)
-import Data.Time (getCurrentTime)
 import qualified Data.ByteString as B
-import qualified Data.Map as Map
-import Criterion.Main
-import Criterion.Types (Config(..))
+import qualified Data.Text as T
+import Test.Tasty.Bench
+-- import Gauge
+import qualified Data.ByteString.Lazy as BL
 import Data.Maybe (mapMaybe)
-import Debug.Trace (trace)
-import System.Environment (getArgs)
+import Data.List (sortOn)
+import Text.Pandoc.Format (FlavoredFormat(..))
 
 readerBench :: Pandoc
-            -> (String, ReaderOptions -> Text -> Pandoc)
+            -> T.Text
             -> Maybe Benchmark
-readerBench doc (name, reader) =
-  case lookup name writers of
-       Just (TextWriter writer) ->
-         let inp = either (error . show) id $ runPure
-                       $ writer def{ writerWrapText = WrapAuto} doc
-         in return $ bench (name ++ " reader") $ nf
-                 (reader def) inp
-       _ -> Debug.Trace.trace
-             ("\nCould not find writer for " ++ name ++ "\n") Nothing
+readerBench _ name
+  | name `elem` ["bibtex", "biblatex", "csljson"] = Nothing
+readerBench doc name = either (const Nothing) Just $
+  runPure $ do
+    (rdr, rexts) <- getReader $ FlavoredFormat name mempty
+    (wtr, wexts) <- getWriter $ FlavoredFormat name mempty
+    tmpl <- Just <$> compileDefaultTemplate name
+    case (rdr, wtr) of
+      (TextReader r, TextWriter w) -> do
+        inp <- w def{ writerWrapText = WrapAuto
+                    , writerExtensions = wexts
+                    , writerTemplate = tmpl } doc
+        return $ bench (T.unpack name) $
+          nf (either (error . show) id . runPure . r def) inp
+      (ByteStringReader r, ByteStringWriter w) -> do
+        inp <- w def{ writerWrapText = WrapAuto
+                    , writerExtensions = wexts
+                    , writerTemplate = tmpl } doc
+        return $ bench (T.unpack name) $
+          nf (either (error . show) id .
+                runPure . r def{readerExtensions = rexts}) inp
+      _ -> throwError $ PandocSomeError $ "text/bytestring format mismatch: "
+                           <> name
 
-writerBench :: Pandoc
-            -> (String, WriterOptions -> Pandoc -> Text)
-            -> Benchmark
-writerBench doc (name, writer) = bench (name ++ " writer") $ nf
-    (writer def{ writerWrapText = WrapAuto }) doc
+getImages :: IO [(FilePath, MimeType, BL.ByteString)]
+getImages = do
+  ll <- B.readFile "test/lalune.jpg"
+  mv <- B.readFile "test/movie.jpg"
+  return [("lalune.jpg", "image/jpg", BL.fromStrict ll)
+         ,("movie.jpg", "image/jpg", BL.fromStrict mv)]
 
+writerBench :: [(FilePath, MimeType, BL.ByteString)]
+            -> Pandoc
+            -> T.Text
+            -> Maybe Benchmark
+writerBench _ _ name
+  | name `elem` ["bibtex", "biblatex", "csljson"] = Nothing
+writerBench imgs doc name = either (const Nothing) Just $
+  runPure $ do
+    (wtr, wexts) <- getWriter $ FlavoredFormat name mempty
+    case wtr of
+      TextWriter writerFun ->
+        return $ bench (T.unpack name)
+               $ nf (\d -> either (error . show) id $
+                       runPure $ do
+                         mapM_ (\(fp,mt,bs) -> insertMedia fp (Just mt) bs) imgs
+                         writerFun def{ writerExtensions = wexts} d)
+                    doc
+      ByteStringWriter writerFun ->
+        return $ bench (T.unpack name)
+               $ nf (\d -> either (error . show) id $
+                       runPure $ do
+                         mapM_ (\(fp,mt,bs) -> insertMedia fp (Just mt) bs) imgs
+                         writerFun def{ writerExtensions = wexts} d)
+                    doc
+
 main :: IO ()
 main = do
-  args <- getArgs
-  let matchReader (n, TextReader _) =
-        case args of
-             [] -> True
-             [x] -> x == n
-             (x:y:_) -> x == n && y == "reader"
-      matchReader (_, _) = False
-  let matchWriter (n, TextWriter _) =
-        case args of
-             [] -> True
-             [x] -> x == n
-             (x:y:_) -> x == n && y == "writer"
-      matchWriter (_, _) = False
-  let matchedReaders = filter matchReader readers
-  let matchedWriters = filter matchWriter writers
   inp <- UTF8.toText <$> B.readFile "test/testsuite.txt"
-  lalune <- B.readFile "test/lalune.jpg"
-  movie <- B.readFile "test/movie.jpg"
-  time <- Data.Time.getCurrentTime
-  let setupFakeFiles = modifyPureState $ \st -> st{ stFiles =
-                        FileTree $ Map.fromList [
-                           ("lalune.jpg", FileInfo time lalune),
-                           ("movie.jpg", FileInfo time movie)
-                           ]}
   let opts = def
-  let doc = either (error . show) id $ runPure $ readMarkdown opts inp
-  let readers' = [(n, \o d ->
-             either (error . show) id $ runPure $ r o d)
-                        | (n, TextReader r) <- matchedReaders]
-  let readerBs = mapMaybe (readerBench doc)
-                 $ filter (\(n,_) -> n /="haddock") readers'
-  let writers' = [(n, \o d ->
-                   either (error . show) id $ runPure $ setupFakeFiles >> w o d)
-                        | (n, TextWriter w) <- matchedWriters]
-  let writerBs = map (writerBench doc)
-                 $ writers'
-  defaultMainWith defaultConfig{ timeLimit = 6.0 }
-    (writerBs ++ readerBs)
+  let doc = either (error . show) force $ runPure $ readMarkdown opts inp
+  defaultMain
+    [ env getImages $ \imgs ->
+      bgroup "writers" $ mapMaybe (writerBench imgs doc . fst)
+                         (sortOn fst
+                           writers :: [(T.Text, Writer PandocPure)])
+    , bgroup "readers" $ mapMaybe (readerBench doc . fst)
+                         (sortOn fst
+                           readers :: [(T.Text, Reader PandocPure)])
+    ]
diff --git a/benchmark/weigh-pandoc.hs b/benchmark/weigh-pandoc.hs
deleted file mode 100644
--- a/benchmark/weigh-pandoc.hs
+++ /dev/null
@@ -1,38 +0,0 @@
-import Weigh
-import Text.Pandoc
-import Data.Text (Text)
-
-main :: IO ()
-main = do
-  doc <- read <$> readFile "test/testsuite.native"
-  mainWith $ do
-    func "Pandoc document" id doc
-    mapM_
-      (\(n,r) -> weighReader doc n (either (error . show) id . runPure . r def{readerExtensions = pandocExtensions}))
-      [("markdown", readMarkdown)
-      ,("html", readHtml)
-      ,("docbook", readDocBook)
-      ,("latex", readLaTeX)
-      ,("commonmark", readCommonMark)
-      ]
-    mapM_
-      (\(n,w) -> weighWriter doc n (either (error . show) id . runPure . w def))
-      [("markdown", writeMarkdown)
-      ,("html", writeHtml5String)
-      ,("docbook", writeDocbook5)
-      ,("latex", writeLaTeX)
-      ,("commonmark", writeCommonMark)
-      ]
-
-weighWriter :: Pandoc -> String -> (Pandoc -> Text) -> Weigh ()
-weighWriter doc name writer = func (name ++ " writer") writer doc
-
-weighReader :: Pandoc -> String -> (Text -> Pandoc) -> Weigh ()
-weighReader doc name reader = do
-  case lookup name writers of
-       Just (TextWriter writer) ->
-         let inp = either (error . show) id $ runPure $ writer def{ writerWrapText = WrapAuto} doc
-         in func (name ++ " reader") reader inp
-       _ -> return () -- no writer for reader
-
-
diff --git a/changelog b/changelog
deleted file mode 100644
--- a/changelog
+++ /dev/null
@@ -1,13586 +0,0 @@
-pandoc (2.0.6)
-
-  * Added `jats` as an input format.
-
-    + Add Text.Pandoc.Readers.JATS, exporting `readJATS` (API
-      change) (Hamish Mackenzie).
-    + Improved citation handling in JATS reader.  JATS citations
-      are now converted to pandoc citations, and JATS ref-lists
-      are converted into a `references` field in metadata, suitable
-      for use with pandoc-citeproc. Thus a JATS article with embedded
-      bibliographic information can be processed with pandoc and
-      pandoc-citeproc to produce a formatted bibliography.
-
-  * Allow `--list-extensions` to take an optional FORMAT argument.
-    This lists the extensions set by default for the selected FORMAT.
-    The extensions are now alphabetized, and the `+` or `-`
-    indicating the default setting comes before, rather than after,
-    the extension.
-
-  * Markdown reader:
-
-    + Preserve original whitespace between blocks.
-    + Recognize `\placeformula` as context.
-    + Be pickier about table captions.  A caption starts with a `:` which
-      can't be followed by punctuation.  Otherwise we can falsely interpret
-      the start of a fenced div, or even a table header line like
-      `:--:|:--:`, as a caption.
-    + Always use four space rule for example lists.  It would be awkward
-      to indent example list contents to the first non-space character after
-      the label, since example list labels are often long.  Thanks to
-      Bernhard Fisseni for the suggestion.
-    + Improve raw tex parsing.  Note that the Markdown reader is also
-      affected by the `latex_macros` extension changes described below
-      under the LaTeX reader.
-
-  * LaTeX reader:
-
-    + `latex_macros` extension changes (#4179).  Don't pass through macro
-      definitions themselves when `latex_macros` is set.  The macros
-      have already been applied.  If `latex_macros` is enabled, then
-      `rawLaTeXBlock` in Text.Pandoc.Readers.LaTeX will succeed in parsing
-      a macro definition, and will update pandoc's internal macro map
-      accordingly, but the empty string will be returned.
-    + Export `tokenize`, `untokenize` (API change).
-    + Use `applyMacros` in `rawLaTeXBlock`, `rawLaTeXInline`.
-    + Refactored `inlineCommand`.
-    + Fix bug in tokenizer.  Material following `^^` was
-      dropped if it wasn't a character escape.  This only affected
-      invalid LaTeX, so we didn't see it in the wild, but it appeared
-      in a QuickCheck test failure.
-    + Fix regression in LateX tokenization (#4159).  This mainly affects the
-      Markdown reader when parsing raw LaTeX with escaped spaces.
-    + Add tests of LaTeX tokenizer.
-    + Support `\foreignlanguage` from babel.
-    + Be more tolerant of `&` character (#4208).  This allows us to parse
-      unknown tabular environments as raw LaTeX.
-
-  * Muse reader (Alexander Krotov):
-
-    + Parse anchors immediately after headings as IDs.
-    + Require that note references does not start with 0.
-    + Parse empty comments correctly.
-
-  * Org reader (Albert Krewinkel):
-
-    + Fix asterisks-related parsing error (#4180).
-    + Support minlevel option for includes (#4154).  The level of headers
-      in included files can be shifted to a higher level by specifying a
-      minimum header level via the `:minlevel` parameter. E.g.
-      `#+include: "tour.org" :minlevel 1` will shift the headers in
-      tour.org such that the topmost headers become level 1 headers.
-    + Break-up org reader test file into multiple modules.
-
-  * OPML reader:
-
-    + Enable raw HTML and other extensions by default for notes
-      (#4164).  This fixes a regression in 2.0.  Note that extensions can
-      now be individually disabled, e.g.  `-f opml-smart-raw_html`.
-
-  * RST reader:
-
-    + Allow empty list items (#4193).
-    + More accurate parsing of references (#4156).  Previously we erroneously
-      included the enclosing backticks in a reference ID (#4156).  This
-      change also disables interpretation of syntax inside references, as
-      in docutils.  So, there is no emphasis in `` `my *link*`_ ``.
-
-  * Docx reader:
-
-    + Continue lists after interruption (#4025, Jesse Rosenthal).
-      Docx expects that lists will continue where they left off after an
-      interruption and introduces a new id if a list is starting again. So
-      we keep track of the state of lists and use them to define a "start"
-      attribute, if necessary.
-    + Add tests for structured document tags unwrapping (Jesse Rosenthal).
-    + Preprocess Document body to unwrap `w:sdt` elements (Jesse Rosenthal,
-      #4190).
-
-  * Plain writer:
-
-    + Don't linkify table of contents.
-
-  * RST writer:
-
-    + Fix anchors for headers (#4188).  We were missing an `_`.
-
-  * PowerPoint writer (Jesse Rosenthal):
-
-    + Treat lists inside BlockQuotes as lists.  We don't yet produce
-      incremental lists in PowerPoint, but we should at least treat lists
-      inside BlockQuotes as lists, for compatibility with other slide formats.
-    + Add ability to force size.  This replaces the more specific
-      `blockQuote runProp`, which only affected the size of blockquotes. We
-      can use this for notes, etc.
-    + Implement notes.  This currently prints all notes on a final slide.
-      Note that at the moment, there is a danger of text overflowing the
-      note slide, since there is no logic for adding further slides.
-    + Implement basic definition list functionality to PowerPoint writer.
-    + Don't look for default template file for Powerpoint (#4181).
-    + Add pptx to isTextFormat list.  This is used to check standalone
-      and not writing to the terminal.
-    + Obey slide level option (Jesse Rosenthal).
-    + Introduce tests.
-
-  * Docx writer:
-
-    + Ensure that `distArchive` is the one that comes with pandoc
-      (#4182).  Previously a `reference.docx` in `~/.pandoc` (or the user data
-      dir) would be used instead, and this could cause problems because a
-      user-modified docx sometimes lacks vital sections that we count
-      on the `distArchive` to supply.
-
-  * Org writer:
-
-    + Do not wrap "-" to avoid accidental bullet lists (Alexander Krotov).
-    + Don't allow fn refs to wrap to beginning of line (#4171, with help from
-      Alexander Krotov).  Otherwise they can be interpreted as footnote
-      definitions.
-
-  * Muse writer (Alexander Krotov):
-
-    + Don't wrap note references to the next line (#4172).
-
-  * HTML writer:
-
-    + Use br elements in line blocks instead of relying on CSS
-      (#4162).  HTML-based templates have had the custom CSS for
-      `div.line-block` removed.  Those maintaining custom templates will want
-      to remove this too.  We still enclose line blocks in a div with class
-      `line-block`.
-
-  * LaTeX writer:
-
-    + Use `\renewcommand` for `\textlatin` with babel (#4161).
-      This avoids a clash with a deprecated `\textlatin` command defined
-      in Babel.
-    + Allow fragile=singleslide attribute in beamer slides (#4169).
-    + Use `\endhead` after `\toprule` in headerless tables (#4207).
-
-  * FB2 writer:
-
-    + Add cover image specified by `cover-image` meta (Alexander Krotov,
-      #4195).
-
-  * JATS writer (Hamish Mackenzie):
-
-    + Support writing `<fig>` and `<table-wrap>` elements
-      with `<title>` and `<caption>` inside them by using Divs with class set
-      to one of `fig`, `table-wrap` or `caption` (Hamish Mackenzie).  The
-      title is included as a Heading so the constraint on where Heading can
-      occur is also relaxed.
-    + Leave out empty alt attributes on links.
-    + Deduplicate image mime type code.
-    + Make `<p>` optional in `<td>` and `<th>` (#4178).
-    + Self closing tags for empty xref (#4187).
-    + Improve support for code language.
-
-  * Custom writer:
-
-    + Use init file to setup Lua interpreter (Albert Krewinkel).
-      The same init file (`data/init`) that is used to setup the Lua
-      interpreter for Lua filters is also used to setup the interpreter of
-      custom writers.lua.
-    + Define instances for newtype wrapper (Albert Krewinkel).  The custom
-      writer used its own `ToLuaStack` instance definitions, which made
-      it difficult to share code with Lua filters, as this could result
-      in conflicting instances.  A `Stringify` wrapper is introduced to
-      avoid this problem.
-    + Added tests for custom writer.
-    + Fixed definition lists and tables in `data/sample.lua`.
-
-  * Fixed regression: when target is PDF, writer extensions were being
-    ignored.  So, for example, `pandoc -t latex-smart -o file.pdf`
-    did not work properly.
-
-  * Lua modules (Albert Krewinkel):
-
-    + Add `pandoc.utils` module, to hold utility functions.
-    + Create a Haskell module Text.Pandoc.Lua.Module.Pandoc to
-      define the `pandoc` lua module.
-    + Make a Haskell module for each Lua module. Move definitions for the
-      `pandoc.mediabag` modules to a separate Haskell module.
-    + Move `sha1` from the main `pandoc` module to `pandoc.utils`.
-    + Add function `pandoc.utils.hierarchicalize` (convert list of
-      Pandoc blocks into (hierarchical) list of Elements).
-    + Add function `pandoc.utils.normalize_date` (parses a date and
-      converts it (if possible) to "YYYY-MM-DD" format).
-    + Add function `pandoc.utils.to_roman_numeral` (allows conversion
-      of numbers below 4000 into roman numerals).
-    + Add function `pandoc.utils.stringify` (converts any AST element
-      to a string with formatting removed).
-    + `data/init.lua`: load `pandoc.utils` by default
-    + Turn pipe, read into full Haskell functions.  The `pipe` and `read`
-      utility functions are converted from hybrid lua/haskell functions
-      into full Haskell functions. This avoids the need for intermediate
-      `_pipe`/`_read` helper functions, which have dropped.
-    + pandoc.lua: re-add missing MetaMap function.  This was a bug
-      introduced in version 2.0.4.
-
-  * Text.Pandoc.Class: Add `insertInFileTree` [API change].  This gives
-    a pure way to insert an ersatz file into a `FileTree`.  In addition, we
-    normalize paths both on insertion and on lookup.
-
-  * Text.Pandoc.Shared: export `blocksToInlines'` (API change, Maura Bieg).
-
-  * Text.Pandoc.MIME: Add opus to MIME type table as audio/ogg (#4198).
-
-  * Text.Pandoc.Extensions:   Alphabetical order constructors for
-    `Extension`.  This makes them appear in order in `--list-extensions`.
-
-  * Allow lenient decoding of latex error logs, which are not always
-    properly UTF8-encoded (#4200).
-
-  * Update latex template to work with recent versions of beamer.
-    The old template produced numbered sections with some recent
-    versions of beamer.  Thanks to Thomas Hodgson.
-
-  * Updated reference.docx (#4175).  Instead of just "Hello, world", the
-    document now contains exemplars of most of the styles that have an
-    effect on pandoc documents.  This makes it easier to see the effect
-    of style changes.
-
-  * Removed `default.theme` data file (#4096).  It is no longer needed now
-    that we have `--print-highlight-style`.
-
-  * Added `stack.lts9.yaml` for building with lts 9 and ghc 8.0.2.
-    We still need this for the alpine static linux build, since
-    we don't have ghc 8.2.2 for that yet.
-
-  * Removed `stack.pkg.yaml`.  We only really need `stack.yaml`; we
-    can put flag settings for pandoc-citeproc there.
-
-  * Makefile: Add 'trypandoc' and 'pandoc-templates' targets to
-    make releases easier.
-
-  * MANUAL.txt:
-
-    + Add note on what formats have `+smart` by default.
-    + Use native syntax for custom-style (#4174, Mauro Bieg).
-    + Introduce dedicated Extensions section, since some extensions
-      affect formats other than markdown (Mauro Bieg, #4204).
-    + Clarify default html output for `--section-divs` (Richard Edwards).
-
-  * filters.md: say that Text.Pandoc.JSON comes form pandoc-types.
-    Closes jgm/pandoc-website#16.
-
-  * epub.md: Delete removed `-S` option from command (#4151, Georger Araújo).
-
-pandoc (2.0.5)
-
-  * Fix a bug in 2.0.4, whereby pandoc could not read the theme files
-    generated with `--print-highlight-style` (#4133).  Improve JSON
-    serialization of styles.
-
-  * Fix CSS issues involving line numbers (#4128).
-    Highlighted code blocks are now enclosed in a div with class `sourceCode`.
-    Highlighting CSS no longer sets a generic color for pre and code; we only
-    set these for class `sourceCode`.
-
-  * `--pdf-engine-opt`: fix bug where option order was reversed (#4137).
-
-  * Add PowerPoint (pptx) writer (Jesse Rosenthal).
-    It works following the standard Pandoc conventions for making other
-    sorts of slides. Caveats:
-
-    + Syntax highlighting is not yet implemented. (This is difficult
-      because there are no character classes in Powerpoint.)
-    + Footnotes and Definition lists are not yet implemented. (Notes will
-      usually take the form of a final slide.
-    + Image placement and auto-resizing has a few glitches.
-    + Reference powerpoint files don't work dependably from the command
-      line. This will be implemented, but at the moment users are advised
-      to change themes from within Powerpoint.
-
-  * Create shared Text.Pandoc.Writers.OOXML module (Jesse Rosenthal).
-    This is for functions used by both Powerpoint and Docx writers.
-
-  * Add default pptx data for Powerpoint writer (Jesse Rosenthal).
-
-  * Add `empty_paragraphs` extension.
-
-    + Deprecate `--strip-empty-paragraphs` option.  Instead we now
-      use an `empty_paragraphs` extension that can be enabled on
-      the reader or writer.  By default, disabled.
-    + Add `Ext_empty_paragraphs` constructor to `Extension`.
-    + Revert "Docx reader: don't strip out empty paragraphs."
-      This reverts commit d6c58eb836f033a48955796de4d9ffb3b30e297b.
-    + Implement `empty_paragraphs` extension in docx reader and writer,
-      opendocument writer, HTML reader and writer.
-    + Add tests for `empty_paragraphs` extension.
-
-  * Markdown reader:
-
-    + Don't parse native div as table caption (#4119).
-    + Improved computation of column widths in pipe tables.
-      Pipe tables with lines longer than the text width (as set
-      by `--columns`) are now scaled to text width, with the relative
-      widths of columns determined by the ratios between the
-      header lines.  Previously we computed column widths using
-      the ratio of header line lengths to column width, so that
-      tables with narrow header lines were extremely thin, which
-      was very rarely the desired result.
-
-  * LaTeX reader: fix `\` before newline (#4134).  This should be a space,
-    as long as it's not followed by a blank line. This has been fixed at the
-    tokenizer level.
-
-  * Muse reader (Alexander Krotov):
-
-    + Add test for `#disable-tables` directive in Emacs mode.
-    + Don't allow emphasis to be preceded by letter.
-    + Add underline support in Emacs Muse mode..
-    + Support multiline directives in Amusewiki mode
-
-  * Man writer: omit internal links (#4136).  That is, just print the link
-    text without the URL.
-
-  * Markdown reader: accept processing instructions as raw HTML (#4125).
-
-  * Lua filters (Albert Krewinkel):
-
-    + Use script to initialize the interpreter.  The file `init.lua` is
-      used to initialize the Lua interpreter which is used in Lua filters.
-      This gives users the option to require libraries which they want to
-      use in all of their filters, and to extend default modules.
-    + Fix package loading for Lua 5.1.  The list of package searchers is
-      named `package.loaders` in Lua 5.1 and LuaJIT, and `package.searchers`
-      in Lua 5.2 and later.
-    + Refactor lua module handling.  The integration with Lua's package/module
-      system is improved: A pandoc-specific package searcher is prepended to
-      the searchers in `package.searchers`. The modules `pandoc` and
-      `pandoc.mediabag` can now be loaded via `require`.
-    + Bump lower bound of hslua.  The release hslua 0.9.3 contains a new
-      function which makes using Haskell functions as package loaders much
-      easier.
-
-  * reveal.js template:  add title-slide identifier to title slide (#4120).
-    This allows it to be styled more easily.
-
-  * LaTeX template: Added support for `pagestyle` variable (#4135,
-    Thomas Hodgson)
-
-  * Add `-threaded` to ghc-options for executable (#4130, fixes a build
-    error on linux).
-
-
-pandoc (2.0.4)
-
-  * Add `--print-highlight-style` option.  This generates a JSON version
-    of a highlighting style, which can be saved as a `.theme` file, modified,
-    and used with `--highlight-style` (#4106, #4096).
-
-  * Add `--strip-empty-paragraphs` option.  This works for any input format.
-    It is primarily intended for use with docx and odt documents where
-    empty paragraphs have been used for inter-paragraph spaces.
-
-  * Support `--webtex` for `gfm` output.
-
-  * Recognize `.muse` file extension.
-
-  * Support beamer `\alert` in LaTeX reader. Closes #4091.
-
-  * Docx reader: don't strip out empty paragraphs (#2252).
-    Users who have a conversion pipeline from docx may want to consider adding
-    `--strip-empty-paragraphs` to the command line.
-
-  * Org reader (Albert Krewinkel): Allow empty list items (#4090).
-
-  * Muse reader (Alexander Krotov):
-
-    + Parse markup in definition list terms.
-    + Allow definition to end with EOF.
-    + Make code blocks round trip.
-    + Drop common space prefix from list items.
-    + Add partial round trip test.
-    + Don't interpret XML entities.
-    + Remove `nested`.
-    + Parse `~~` as non-breaking space in Emacs mode.
-    + Correctly remove indentation from notes.  Exactly one space is
-      required and considered to be part of the marker.
-    + Allow list items to be empty.
-    + Add ordered list test.
-    + Add more multiline definition tests.
-    + Don't allow blockquotes within lists.
-    + Fix reading of multiline definitions.
-    + Add inline `<literal>` support.
-    + Concatenate inlines of the same type
-
-  * Docx writer: allow empty paragraphs (#2252).
-
-  * CommonMark/gfm writer:
-
-    + Use raw html for native divs/spans (#4113).  This allows a pandoc
-      markdown native div or span to be rendered in gfm using raw html tags.
-    + Implement `raw_html` and `raw_tex` extensions.  Note that `raw_html`
-      is enabled by default for `gfm`, while `raw_tex` is disabled by default.
-
-  * Muse writer (Alexander Krotov):
-
-    + Test that inline math conversion result is normalized.
-      Without normalization this test produced
-      `<em>a</em><em>b</em><em>c</em>`.
-    + Improve inline list normalization and move to writer.
-    + Escape hash symbol.
-    + Escape `----` to avoid accidental horizontal rules.
-    + Escape only `</code>` inside code tag.
-    + Additional `<verbatim>` is not needed as `<code>` is verbatim already.
-
-  * LaTeX writer:
-
-    + Allow specifying just width or height for image size.
-      Previously both needed to be specified (unless the image was
-      being resized to be smaller than its original size).
-      If height but not width is specified, we now set width to
-      textwidth. If width but not height is specified, we now set
-      height to textheight.  Since we have `keepaspectratio`, this
-      yields the desired result.
-    + Escape `~` and `_` in code with `--listings` (#4111).
-
-  * HTML writer: export `tagWithAttributes`.  This is a helper allowing
-    other writers to create single HTML tags.
-
-  * Let papersizes `a0`, `a1`, `a2`, ... be case-insensitive by
-    converting the case as needed in LaTeX and ConTeXt writers.
-
-  * Change `fixDisplayMath` from `Text.Pandoc.Writers.Shared`
-    so that it no longer produces empty `Para`'s as an artifact.
-
-  * `Text.Pandoc.Shared.blocksToInlines`:  rewrote using builder.
-    This gives us automatic normalization, so we don't get
-    for example two consecutive Spaces.
-
-  * Include default CSS for 'underline' class in HTML-based templates.
-
-  * revealjs template:  add `tex2jax` configuration for the
-    math plugin.  With the next release of reveal.js, this will
-    fix the problem of `$`s outside of math contexts being
-    interpreted as math delimiters (#4027).
-
-  * `pandoc.lua` module for use in lua filters (Albert Krewinkel):
-
-    + Add basic lua List module (#4099, #4081).  The List module is
-      automatically loaded, but not assigned to a global variable. It can be
-      included in filters by calling `List = require 'List'`.  Lists of blocks,
-      lists of inlines, and lists of classes are now given `List` as a metatable,
-      making working with them more convenient.  E.g., it is now possible to
-      concatenate lists of inlines using Lua's concatenation operator `..`
-      (requires at least one of the operants to have `List` as a metatable):
-
-          function Emph (emph)
-            local s = {pandoc.Space(), pandoc.Str 'emphasized'}
-            return pandoc.Span(emph.content .. s)
-          end
-
-      The `List` metatable is assigned to the tables which get passed to
-      the constructors `MetaBlocks`, `MetaInline`, and `MetaList`. This
-      enables the use of the resulting objects as lists.
-    + `Lua/StackInstances`: push Pandoc and Meta via constructor.
-      Pandoc and Meta elements are now pushed by calling the respective
-      constructor functions of the pandoc Lua module. This makes serialization
-      consistent with the way blocks and inlines are pushed to lua and allows
-      to use List methods with the `blocks` value.
-    + Add documentation for pandoc.List in `lua-filters.md`.
-
-  * Use latest tagsoup.  This fixes a bug in parsing HTML tags with
-    `&` (but not a valid entity) following them (#4094, #4088).
-
-  * Use skylighting 0.4.4.1, fixing the color of unmarked code text
-    when `numberLines` is used (#4103).
-
-  * Make `normalizeDate` more forgiving (Mauro Bieg, #4101), not
-    requiring a leading 0 on single-digit days.
-
-  * Fix `--help` output for `--highlight-style` to include `FILE` (Mauro
-    Bieg, #4095).
-
-  * Clearer deprecation warning for `--latexmathml, --asciimathml, -m`.
-    Previously we only mentioned `--latexmathml`, even if `-m` was
-    used.
-
-  * Changelog: fix description of lua filters in 2.0 release
-    (Albert Krewinkel).  Lua filters were initially run *after* conventional
-    (JSON) filters.  However, this was changed later to make it easier to deal
-    with files in the mediabag. The changelog is updated to describe that
-    feature of the 2.0 release correctly.
-
-  * Change Generic JSON instances to TemplateHaskell (Jasper Van der Jeugt,
-    #4085).  This reduces compile time and memory usage significantly.
-
-  * `lua-filters.md`: Added tikz filter example.
-
-  * Create alternative zip file for macOS binaries.
-
-  * Create alternative zip file for Windows binaries.
-
-  * Update INSTALL.md since we now provide zips for binaries.
-
-  * Relax `http-types` dependency (Justus Sagemüller, #4084).
-
-  * Add `epub.md`, `getting-started.md` to docs.  These used to live in
-    the website repo.
-
-  * Add `packages` target to Makefile.
-
-  * Bump bounds for binary, http-types, tasty-hunit
-
-pandoc (2.0.3)
-
-  * Lua filters: preload text module (Albert Krewinkel, #4077).
-    The `text` module is preloaded in lua. The module contains some UTF-8
-    aware string functions, implemented in Haskell.  The module is loaded on
-    request only, e.g.:
-
-        text = require 'text'
-        function Str (s)
-          s.text = text.upper(s.text)
-          return s
-        end
-
-  * Allow table-like access to attributes in lua filters (Albert Krewinkel,
-    #4071).  Attribute lists are represented as associative lists in Lua. Pure
-    associative lists are awkward to work with. A metatable is attached to
-    attribute lists, allowing to access and use the associative list as if
-    the attributes were stored in as normal key-value pair in table.
-    Note that this changes the way `pairs` works on attribute lists. Instead
-    of producing integer keys and two-element tables, the resulting iterator
-    function now returns the key and value of those pairs.  Use `ipairs` to
-    get the old behavior.  Warning: the new iteration mechanism only works if
-    pandoc has been compiled with Lua 5.2 or later (current default: 5.3).
-
-  * Text.Pandoc.Parsing.uri:  allow `&` and `=` as word characters (#4068).
-    This fixes a bug where pandoc would stop parsing a URI with an
-    empty attribute:  for example, `&a=&b=` wolud stop at `a`.
-    (The uri parser tries to guess which punctuation characters
-    are part of the URI and which might be punctuation after it.)
-
-  * Introduce `HasSyntaxExtensions` typeclass (Alexander Krotov, #4074).
-
-    + Added new `HasSyntaxExtensions` typeclass for `ReaderOptions` and
-      `WriterOptions`.
-    + Reimplemented `isEnabled` function from `Options.hs` to accept both
-      `ReaderOptions` and `WriterOptions`.
-    + Replaced `enabled` from `CommonMark.hs` with new `isEnabled`.
-
-  * Add `amuse` extension (Alexander Krotov) to enable Amuse wiki
-    behavior for `muse`.  New `Ext_amuse` constructor for
-    `Extension`. Note: this is switched on by default; for
-    Emacs behavior, use `muse-amuse`.
-
-  * Muse reader (Alexander Krotov):
-
-    + Count only one space as part of list item marker.
-    + Produce SoftBreaks on newlines. Now wrapping can be preserved
-      with `--wrap=preserve`.
-    + Add Text::Amuse footnote extensions.  Footnote end is indicated by
-      indentation, so footnotes can be placed anywhere in the text,
-      not just at the end of it.
-    + Accept Emacs Muse definition lists when `-amuse`.
-      Emacs Muse does not require indentation.
-
-  * HTML reader:
-
-    + Ensure we don't produce level 0 headers (#4076), even for chapter
-      sections in epubs.  This causes problems because writers aren't set
-      up to expect these.
-    + Allow spaces after `\(` and before `\)` with `tex_math_single_backslash`.
-      Previously `\( \frac{1}{a} < \frac{1}{b} \)` was not parsed as math in
-      `markdown` or `html` `+tex_math_single_backslash`.
-    + Parse div with class `line-block` as LineBlock.
-    + Don't fail with block-level content in figcaption (Mauro Bieg, #4183).
-
-  * MANUAL: clarify that math extensions work with HTML.
-    Clarify that `tex_math_dollars` and `tex_math_single_backslash`
-    will work with HTML as well as Markdown.
-
-  * Creole reader: Fix performance issue for longer lists (Sascha Wilde,
-    #4067).
-
-  * RST reader: better support for 'container' directive (#4066).
-    Create a div, incorporate name attribute and classes.
-
-  * LaTeX reader:
-
-    + Support column specs like `*{2}{r}` (#4056).  This is equivalent to
-      `rr`.  We now expand it like a macro.
-    + Allow optional args for parbox (#4056).
-    + Allow optional arguments on `\footnote` (#4062).
-
-  * EPUB writer: Fixed path for cover image (#4069).  It was previously
-    `media/media/imagename`, and should have been `media/imagename`.
-
-  * Markdown writer: fix bug with doubled footnotes in grid tables
-    (#4061).
-
-  * LaTeX template:  include natbib/biblatex after polyglossia (#4073).
-    Otherwise we seem to get an error; biblatex wants polyglossia
-    language to be defined.
-
-  * Added examples to lua filters documentation.
-
-
-pandoc (2.0.2)
-
-  * Deprecated ancient HTML math methods: `--latexmathml`, `--gladtex`,
-    `--mimetex`, `--jsmath`.
-
-  * Fixed URIs in `data/jats.csl`.  They were being rendered twice,
-    leading to invalid XML in default JATS output with pandoc-citeproc.
-
-  * `lua-filters.md`: use real-world man page filter as example.
-
-  * Add lua filter functions `walk_inline` and `walk_block`
-    in the pandoc module, to apply filters inside particular
-    inline and block elements.
-
-  * Refactored some code from `Text.Pandoc.Lua.PandocModule`
-    into new internal module `Text.Pandoc.Lua.Filter`.
-
-  * Markdown reader:
-
-    + Allow fenced code blocks to be indented 1-3 spaces (#4011).
-      This brings our handling of them into alignment with CommonMark's.
-    + Fix YAML metadata with "chomp" (`|-`).  Previously if a
-      YAML block under `|-` contained a blank line, pandoc would
-      not parse it as metadata.
-
-  * Removed `etc.` from abbreviations file.  Often `etc.` ends a
-    sentence, and we want the period to be treated as a
-    sentence-ending period.
-
-  * Fix regression with `--metadata` (#4054).  Values specified with
-    `--metadata` should replace a metadata value set in the document
-    itself, rather than creating a list including a new value.
-
-  * EPUB writer:
-
-    + Fix EPUB OCF structure.  #3720 had been improperly implemented.
-    + Fix modified paths for raw HTML tags (src, poster, etc.)
-      (#4050, #4055). This had not been updated for the new EPUB
-      container layout, with a separate text/ subdirectory.
-    + Fix image paths with empty `--epub-subdirectory`.
-
-  * Miscellaneous code cleanup (Alexander Krotov).
-
-  * Use pandoc-types 1.17.3, which adds `Walkable` instances
-    for `[Block] Block` and `[Inline] Inline`.
-
-  * Remove obsolete `stack.full.yaml` (#4052).
-
-  * Change to using pandoc-citeproc 0.12.1 in binary packages.
-
-  * Consolidate math output method documentation (#4049, Mauro Bieg).
-
-  * `MANUAL.txt`: fix header level of "Extension: emoji" (Albert Krewinkel).
-
-  * Use lua filter to generate man page from `MANUAL.txt`, replacing old
-    Haskell filters.  This is easier and faster.
-
-  * Improved `INSTALL.md`.
-
-  * Update commands to extract deb archive on Linux (#4043, Salim B).
-
-
-pandoc (2.0.1.1)
-
-  * Improved fix to #3989 (parsing of HTML tags containing
-    `>` in an attribute or comment). The previous fix (in 2.0.1) only
-    worked in certain cases.
-
-  * FB2 writer (Alexander Krotov):
-
-    + Add `unrecognised` genre to `<title-info>`
-      (Alexander Krotov).  XML schema requires at least one genre.
-    + Remove `<annotation>` from `<body>`.
-
-  * CommonMark writer: fix strikethrough for `gfm` (#4038).
-
-  * Use texmath 0.10, which adds support for a wider range of
-    symbols and fixes default column alignments in MathML
-    and OMML.
-
-  * Highlighting fixes, using skylighting 0.4.3.2:
-
-    + Fix invalid CSS.
-    + Support `lineAnchors` (or `line-anchors`) in HTML code blocks.
-    + Ensure that code lines don't get duplicate identifiers (#4031).
-      The line identifiers are built using the code block's identifier
-      as a prefix. If the code block has null identifier, we use
-      `cb1`, `cb2`, etc.
-
-  * Added a few abbreviations to `data/abbreviations`,
-    and sorted the list (#3984, Wandmalfarbe).
-
-  * Improved support for columns in HTML writer (#4028).
-
-    + Remove `width` attribute from the `div`.
-    + Remove space between `<div class="column">` elements,
-      since this prevents columns whose widths sum to 100%
-      (the space takes up space).
-    + Move as much as possible of the CSS to the template.
-    + Ensure that all the HTML-based templates (including epub)
-      contain the CSS for columns.
-    + Columns default to 50% width unless they are given a width
-      attribute.  So if you want two equal-width columns, you
-      can use a div with class `column` and no `width` attribute.
-
-  * SelfContained: use `base64` for css links with media attribute (#4026).
-    This fixes `--self-contained` with S5.
-
-  * Improve `pandoc-template-mode.el` (Vaclav Haisman).
-
-  * Issue INFO, not WARNING, when a .sty file cannot be
-    read in LaTeX reader.  It is normally not an issue requiring
-    a fix from the user if .sty files are not found.
-
-  * INSTALL.md: MacOS instructions needed xar -f (adam234).
-
-  * MANUAL.txt:
-
-    + Clarify that --setext-headers doesn't affect gfm output (#4035).
-    + Clarify what is needed to open and close a div in `fenced_divs`
-      (#4039, Tristano Ajmone).
-    + Removed reference to `default.beamer` in docs (#4024).
-      Also added mention of other templates affecting PDF output
-      with different settings.
-
-pandoc (2.0.1)
-
-  * Fixed regression in parsing of HTML comments in markdown and other
-    non-HTML formats (`Text.Pandoc.Readers.HTML.htmlTag`) (#4019).
-    The parser stopped at the first `>` character, even if it wasn't
-    the end of the comment.
-
-  * Creole reader (Sascha Wilde):
-
-    + Fix some minor typos and formatting.
-    + Add additional test on nowiki-block after para.
-    + Fix lists with trailing white space.
-
-  * LaTeX reader: handle `%` comment right after command.
-    For example, `\emph%`.
-
-  * Markdown reader:  make sure fenced div closers work in lists.
-    Previously the following failed:
-
-        ::: {.class}
-        1. one
-        2. two
-        :::
-
-    and you needed a blank line before the closing `:::`.
-
-  * Make `fenced_divs` affect the Markdown writer.  If `fenced_divs` is
-    enabled, Divs will be rendered as fenced divs.
-
-  * LaTeX/Beamer writer: support "blocks" inside columns and other Divs
-    (#4016).
-
-  * HTML Writer: consistently use dashed class-names (Mauro Bieg, #3556).
-    Note: this change may require some changes in CSS rules.
-    `footnoteRef` has become `footnote-ref`, `titleslide` has
-    become `title-slide`, and `footnoteBack` has become `footnote-back`.
-
-  * JATS writer: Properly pass through author metadata (#4020).
-
-  * FB2 writer (Alexander Krotov):
-
-    + Write blocks outside of `<p>` in definitions.
-    + Make bullet lists consistent with ordered lists, repeating
-      the marker for the outer list rather than indenting sublists,
-      since indentation does not work in readers.
-    + Add new style FB2 tests.
-
-  * `Text.Pandoc.ImageSize`: Add `Millimeter` constructor to `Dimension`
-    (#4012) [API change]. Now sizes given in 'mm' are no longer converted
-    to 'cm'.
-
-  * Revise documentation of small caps syntax (Andrew Dunning, #4013).
-
-  * Fix broken reference links in manual (Andrew Dunning, #4014)
-
-  * Fixed example of slide columns structure in changelog (#4015).
-    Also documented this feature in MANUAL.txt.
-
-
-pandoc (2.0.0.1)
-
-  * EPUB writer:
-
-    + Fixed filepaths for nonstandard epub-subdirectory values.
-    + Ensure that epub2 is recognized as a non-text format,
-      so that a template is used.
-    + Don't include "prefix" attribute for ibooks for epub2.
-      It doesn't validate.
-    + Fix stylesheet paths; previously we had an incorrect
-      stylesheet path for the cover page and nav page.
-
-  * LaTeX reader:
-
-    + Insert space when needed in macro expansion (#4007).
-      Sometimes we need to insert a space after a control sequence
-      to prevent it merging with a following letter.
-    + Allow unbraced arguments for macros (#4007).
-    + Allow body of macro definition to be unbraced (#4007).
-
-  * Linux package build: ensure that pandoc-citeproc is statically linked.
-
-  * trypandoc: add native, ms.
-
-pandoc (2.0)
-
-  [new features]
-
-  * New output format `ms` (groff ms). Complete support, including
-    tables, math, syntax highlighting, and PDF bookmarks. The writer uses
-    texmath's new eqn writer to convert math to eqn format, so a ms file
-    produced with this writer should be processed with `groff -ms -e` if
-    it contains math.
-
-  * New output format `jats` (Journal Article Tag Suite).  This is an XML
-    format used in archiving and publishing articles.  Note that a
-    URI-encoded CSL stylesheet (`data/jats.csl`) is added automatically
-    unless a stylesheet is specified using `--css`.
-
-  * New output format `gfm` (GitHub-flavored CommonMark) (#3841).
-    This uses bindings to GitHub's fork of cmark, so it should parse
-    gfm exactly as GitHub does (excepting certain postprocessing
-    steps, involving notifications, emojis, etc.).  `markdown_github`
-    has been deprecated in favor of `gfm`.
-
-  * New output format `muse` (Emacs Muse) (Alexander Krotov, #3489).
-
-  * New input format `gfm` (GitHub-flavored CommonMark) (#3841).
-    This uses bindings to GitHub's fork of cmark.  `markdown_github`
-    has been deprecated in favor of `gfm`.
-
-  * New input format `muse` (Emacs Muse) reader (Alexander Krotov, #3620).
-
-  * New input format `tikiwiki` (TikiWiki markup) (rlpowell, #3800).
-
-  * New input format `vimwiki` (Vimwiki markup) (Yuchen Pei, #3705).
-    Note that there is a new data file, `data/vimwiki.css`, which can
-    be used to display the HTML produced by this reader and
-    pandoc's HTML writer in the style of vimwiki's own HTML
-    export.
-
-  * New input format `creole` (Creole 1.0) (#3994, Sascha Wilde).
-
-  * New syntax for Divs, with `fenced_divs` extension enabled by
-    default (#168).  This gives an attractive, plain-text way to create
-    containers for block-level content.
-
-  * Added new syntax for including raw content in any output format,
-    enabled by the `raw_attribute` extension (which is on by default
-    for `markdown` and `multimarkdown`).  The syntax is the same as
-    for fenced code blocks or code inlines, only with `{=FORMAT}` for
-    attributes, where `FORMAT` is the name of the output format
-    (e.g., `ms`, `html`).
-
-  * Implement multicolumn support for slide formats (#1710).
-    The structure expected is:
-
-        :::::::::::::: {.columns}
-        ::: {.column width="40%"}
-        contents...
-        :::
-        ::: {.column width="60%"}
-        contents...
-        :::
-        ::::::::::::::
-
-    Support has been added for beamer and all HTML slide formats.
-
-  * Allows line comments in templates, beginning with `$--` (#3806).
-    (Requires doctemplates 0.2.1.)
-
-  * Add `--eol=crlf|lf|native` flag and writer option to control line endings
-    (Stefan Dresselhaus, #3663, #2097).
-
-  * Add `--log` option to save log messages in JSON format to a file (#3392).
-
-  * Add `--request-header` option, to set request headers when pandoc
-    makes HTTP requests to fetch external resources. For example:
-    `--request-header User-Agent:blah`.
-
-  * Added lua filters (Albert Krewinkel, #3514).  The new `--lua-filter`
-    option works like `--filter` but takes pathnames of special lua filters
-    and uses the lua interpreter baked into pandoc, so that no external
-    interpreter is needed.  Note that lua filters are all applied before
-    regular filters, regardless of their position on the command line.
-    For documentation of lua filters, see `doc/lua-filters.md`.
-
-  * Set `PANDOC_READER_OPTIONS` in environment where filters are run.
-    This contains a JSON representation of `ReaderOptions`, so filters
-    can access it.
-
-  * Support creation of pdf via groff `ms` and pdfroff.
-    `pandoc -t ms -o output.pdf input.txt`.
-
-  * Support for PDF generation via HTML and `weasyprint` or `prince`
-    (Mauro Bieg, #3909).  `pandoc -t html5 -o output.pdf --pdf-engine=prince`.
-
-  * Added `--epub-subdirectory` option (#3720).  This specifies the
-    subdirectory in the OCF container that holds the EPUB specific content.
-    We now put all EPUB related content in an `EPUB/` subdirectory by default
-    (later this will be configurable).
-
-    ```
-      mimetype
-      META-INF/
-        com.apple.ibooks.display-options.xml
-        container.xml
-      EPUB/ <<--configurable-->>
-        fonts/ <<--static-->>
-        font.otf
-      media/ <<--static-->>
-        cover.jpg
-        fig1.jpg
-      styles/ <<--static-->>
-        stylesheet.css
-      content.opf
-      toc.ncx
-      text/ <<--static-->>
-        ch001.xhtml
-    ```
-
-  * Added `--resource-path=SEARCHPATH` command line option (#852).
-    SEARCHPATH is separated by the usual character, depending on OS
-    (: on unix, ; on windows).  Default resource path is just working
-    directory.  However, the working directory must be explicitly
-    specified if the `--resource-path` option is used.
-
-  * Added --abbreviations=FILE option for custom abbreviations file
-    (#256).  Default abbreviations file (`data/abbreviations`) contains
-    a list of strings that will be recognized by pandoc's
-    Markdown parser as abbreviations.  (A nonbreaking space will
-    be inserted after the period, preventing a sentence space in
-    formats like LaTeX.) Users can override the default by putting a file
-    abbreviations in their user data directory (`~/.pandoc` on *nix).
-
-  * Allow a theme file as argument to `--highlight-style`.
-    Also include a sample, `default.theme`, in `data/`.
-
-  * Allow `--syntax-definition` option for dynamic loading of syntax
-    highlighting definitions (#3334).
-
-  * Lists in `markdown` by default now use the CommonMark variable
-    nesting rules (#3511). The indentation required for a block-level
-    item to be included in a list item is no longer fixed, but is
-    determined by the first line of the list item.  To be included in
-    the list item, a block must be indented to the level of the first
-    non-space content after the list marker. Exception: if are 5 or more
-    spaces after the list marker, then the content is interpreted as an
-    indented code block, and continuation paragraphs must be indented
-    two spaces beyond the end of the list marker.  See the CommonMark
-    spec for more details and examples.
-
-    Documents that adhere to the four-space rule should, in most cases,
-    be parsed the same way by the new rules.  Here are some examples
-    of texts that will be parsed differently:
-
-        - a
-          - b
-
-    will be parsed as a list item with a sublist; under the four-space
-    rule, it would be a list with two items.
-
-        - a
-
-              code
-
-    Here we have an indented code block under the list item, even though it
-    is only indented six spaces from the margin, because it is four spaces
-    past the point where a continuation paragraph could begin.  With the
-    four-space rule, this would be a regular paragraph rather than a code
-    block.
-
-        - a
-
-                code
-
-    Here the code block will start with two spaces, whereas under
-    the four-space rule, it would start with `code`.  With the four-space
-    rule, indented code under a list item always must be indented eight
-    spaces from the margin, while the new rules require only that it
-    be indented four spaces from the beginning of the first non-space
-    text after the list marker (here, `a`).
-
-    This change was motivated by a slew of bug reports from people
-    who expected lists to work differently (#3125, #2367, #2575, #2210,
-     #1990, #1137, #744, #172, #137, #128) and by the growing prevalance
-    of CommonMark (now used by GitHub, for example).  Those who
-    prefer the old behavior can use `-f markdown+four_space_rule`.
-
-  * Added `four_space_rule` extension.  This triggers the old pandoc
-    parsing rule for content nested under list items (the "four space
-    rule").
-
-  * Added `spaced_reference_links` extension (#2602).  It allows whitespace
-    between the two parts of a reference link:  e.g.
-
-        [a] [b]
-
-        [b]: url
-
-    This was previously enabled by default; now it is now forbidden by default.
-
-  * Add `space_in_atx_header` extension (#3512).  This is enabled by default
-    in pandoc and GitHub markdown but not the other flavors.
-    This requires a space between the opening #'s and the header
-    text in ATX headers (as CommonMark does but many other implementations
-    do not).  This is desirable to avoid falsely capturing things like
-
-        #hashtag
-
-    or
-
-        #5
-
-  * Add `sourcefile` and `outputfile` template variables (Roland Hieber,
-    #3431).
-
-  * Allow ibooks-specific metadata in epubs (#2693).  You can now have
-    the following fields in your YAML metadata, and it will be treated
-    appropriately in the generated EPUB:
-
-    ```
-      ibooks:
-        version: 1.3.4
-        specified-fonts: false
-        ipad-orientation-lock: portrait-only
-        iphone-orientation-lock: landscape-only
-        binding: true
-        scroll-axis: vertical
-    ```
-
-
-  [behavior changes]
-
-  * Reader functions no longer presuppose that CRs have been
-    stripped from the input. (They strip CRs themselves, before
-    parsing, to simplify the parsers.)
-
-  * Added support for translations (localization) (#3559).
-    Currently this only affects the LaTeX reader, for things
-    like `\figurename`.  Translation data files for 46 languages
-    can be found in `data/translations`.
-
-  * Make `--ascii` work with DocBook output too.
-
-  * Rename `--latex-engine` to `--pdf-engine`,
-    and `--latex-engine-opt` to `--pdf-engine-opt`.
-
-  * Removed `--parse-raw` and `readerParseRaw`.  These were confusing.
-    Now we rely on the `+raw_tex` or `+raw_html` extension with latex or html
-    input.  Thus, instead of `--parse-raw -f latex` we use `-f latex+raw_tex`,
-    and instead of `--parse-raw -f html` we use `-f html+raw_html`.
-
-  * With `--filter` R filters are now recognized, even if they are
-    not executable (#3940, #3941, Andrie de Vries).
-
-  * Support SVG in PDF output, converting with `rsvg2pdf` (#1793).
-
-  * Make epub an alias for epub3, not epub2.
-
-  * Removed `--epub-stylesheet`; use `--css` instead (#3472, #847).
-    Multiple stylesheets may be used.  Stylesheets will be taken both from
-    `--css` and from the `stylesheet` metadata field (which can contain
-    either a file path or a list of them).
-
-  * `--mathml` and MathML in HTMLMathMethod no longer take an argument.
-    The argument was for a bridge JavaScript that used to be necessary
-    in 2004.  We have removed the script already.
-
-  * `--katex` improvements.  The latest version is used, and the
-    autoload script is loaded by default.
-
-  * Change MathJax CDN default since old one is shutting down (#3544).
-    Note:  The new URL requires a version number, which we'll have
-    to update manually in subsequent pandoc releases in order to
-    take advantage of mathjax improvements.
-
-  * `--self-contained`: don't incorporate elements with `data-external="1"`
-    (#2656).  You can leave an external link as it is by adding the attribute
-    data-external="1" to the element.  Pandoc will then not try to
-    incorporate its content when `--self-contained` is used.  This is
-    similar to a feature already supported by the EPUB writer.
-
-  * Allow `--extract-media` to work with non-binary input formats
-    (#1583, #2289).  If `--extract-media` is supplied with a non-binary
-    input format, pandoc will attempt to extract the contents of all
-    linked images, whether in local files, data: uris, or external uris.
-    They will be named based on the sha1 hash of the contents.
-
-  * Make `papersize: a4` work regardless of the case of `a4`.
-    It is converted to `a4` in LaTeX and `A4` in ConTeXt.
-
-  * Make `east_asian_line_breaks` affect all readers/writers (#3703).
-
-  * Underlined elements are now treated consistently by readers
-    (#2270, hftf); they are always put in a Span with class `underline`.
-    This allows the user to treat them differently from other emphasis,
-    using a filter.  Docx, Org, Textile, Txt2Tags, and HTML readers
-    have been changed.
-
-  * Improved behavior of `auto_identifiers` when there are explicit ids
-    (#1745).  Previously only autogenerated ids were added to the list
-    of header identifiers in state, so explicit ids weren't taken
-    into account when generating unique identifiers.  Duplicated
-    identifiers could result.  This simple fix ensures that explicitly given
-    identifiers are also taken into account.
-
-  * Use `table-of-contents` for contents of toc, make `toc` a boolean
-    (#2872).  Changed markdown, rtf, and HTML-based templates accordingly.
-    This allows you to set `toc: true` in the metadata; this
-    previously produced strange results in some output formats.
-    For backwards compatibility, `toc` is still set to the
-    toc contents.  But it is recommended that you update templates
-    to use `table-of-contents` for the toc contents and `toc`
-    for a boolean flag.
-
-  * Change behavior with binary format output to stdout.
-    Previously, for binary formats, output to stdout was disabled
-    unless we could detect that the output was being piped (and not
-    sent to the terminal).  Unfortunately, such detection is not
-    possible on Windows, leaving windows users no way to pipe binary
-    output.  So we have changed the behavior in the following way:
-
-    + Output to stdout is allowed when it can be determined that
-      the output is being piped (on non-Windows platforms).
-    + If the `-o` option is not used, binary output is never sent
-      to stdout by default; instead, an error is raised.
-    + If `-o -` is used, binary output is sent to stdout, regardless
-      of whether it is being piped. This works on Windows too.
-
-  * Better error behavior:  uses of `error` have been replaced by
-    raising of `PandocError`, which can be trapped and handled by the
-    calling program.
-
-  * Removed `hard_line_breaks` extension from `markdown_github` (#3594).
-    GitHub has two Markdown modes, one for long-form documents like READMEs
-    and one for short things like issue coments. In issue comments, a line
-    break is treated as a hard line break. In README, wikis, etc., it is
-    treated as a space as in regular Markdown.  Since pandoc is more likely to
-    be used to convert long-form documents from GitHub Markdown,
-    `-hard_line_breaks` is a better default.
-
-  * Include `backtick_code_blocks` extension in `mardkown_mmd` (#3637).
-
-  * Escape `MetaString` values (as added with `-M/--metadata` flag) (#3792).
-    Previously they would be transmitted to the template without any
-    escaping.  Note that `--M title='*foo*'` yields a different result from
-
-        ---
-        title: *foo*
-        ---
-
-    In the latter case, we have emphasis; in the former case, just
-    a string with literal asterisks (which will be escaped
-    in formats, like Markdown, that require it).
-
-  * Allow `em`, `cm`, `in` for image height/width in HTML, LaTeX (#3450).
-
-  * HTML writer: Insert `data-` in front of unsupported attributes.  Thus,
-    a span with attribute `foo` gets written to HTML5 with `data-foo`, so
-    it is valid HTML5.  HTML4 is not affected.  This will allow us to use
-    custom attributes in pandoc without producing invalid HTML. (With help
-    from Wandmalfarbe, #3817.)
-
-  * Plain writer:  improved super/subscript rendering.  We now
-    handle more non-digit characters for which there are
-    sub/superscripted unicode characters.  When unicode
-    sub/superscripted characters are not available, we use
-    `_(..)` or `^(..)` (#3518).
-
-  * Docbook, JATS, TEI writers: print INFO message when omitting interior
-    header (#3750).  This only applies to section headers inside list items,
-    e.g., which were otherwise silently omitted.
-
-  * Change to `--reference-links` in Markdown writer (#3701).  With
-    `--reference-location` of `section` or `block`, pandoc will now repeat
-    references that have been used in earlier sections.  The Markdown
-    reader has also been modified, so that *exactly* repeated references
-    do not generate a warning, only references with the same label but
-    different targets.  The idea is that, with references after every block,
-    one might want to repeat references sometimes.
-
-  * ODT/OpenDocument writer:
-
-    + Support `lang` attribute (#1667).
-    + Added support for `--toc` (#2836).  Thanks to @anayrat.
-
-  * Docx writer:
-
-    + `lang` meta, see #1667 (Mauro Bieg, #3515).
-    + Change `FigureWithCaption` to `CaptionedFigure` (iandol, #3658).
-    + Use `Table` rather than `Table Normal` for table style (#3275).
-      `Table Normal` is the default table style and can't be modified.
-    + Pass through comments (#2994).  We assume that comments are defined as
-      parsed by the docx reader:
-
-        I want <span class="comment-start" id="0" author="Jesse Rosenthal"
-        date="2016-05-09T16:13:00Z">I left a comment.</span>some text to
-        have a comment <span class="comment-end" id="0"></span>on it.
-
-      We assume also that the id attributes are unique and properly
-      matched between comment-start and comment-end.
-    + Bookmark improvements.  Bookmark start/end now surrounds content rather
-      than preceding it.  Bookmarks generated for Div with id
-      (jgm/pandoc-citeproc#205).
-    + Add `keywords` metadata to docx document properties (Ian).
-
-  * RST writer: support unknown interpreted text roles by
-    parsing them as `Span` with `role` attributes (#3407).  This
-    way they can be manipulated in the AST.
-
-  * HTML writer:
-
-    + Line block: Use class instead of style attribute (#1623).  We now
-      issue `<div class="line-block">` and include a default definition
-      for `line-block` in the default templates, instead of hard-coding a
-      `style` on the div.
-    + Add class `footnoteBack` to footnote back references (Timm Albers).
-      This allows for easier CSS styling.
-    + Render SmallCaps as span with smallcaps class (#1592), rather than
-      using a style attribute directly.  This gives the user more flexibility
-      in styling small caps in CSS.
-    + With reveal.js we use `data-src` instead of `src` for images for
-      lazy loading.
-    + Special-case `.stretch` class for images in reveal.js (#1291).
-      Now in reveal.js, an image with class `stretch` in a paragraph
-      by itself will stretch to fill the whole screen, with no
-      caption or figure environment.
-
-  * Added warnings for non-rendered blocks to writers.
-
-  * Writers now raise an error on template failure.
-
-  * When creating a PDF via LaTeX, warn if the font is missing some
-    characters (#3742).
-
-  * Remove initial check for PDF-creating program (#3819).
-    Instead, just try running it and raise the exception if it
-    isn't found at that point.  This improves things for users of Cygwin
-    on Windows, where the executable won't be found by `findExecutable`
-    unless `.exe` is added.  The same exception is raised as before, but
-    at a later point.
-
-  * Readers issue warning for duplicate header identifiers (#1745).
-    Autogenerated header identifiers are given suffixes so as not to clash
-    with previously used header identifiers. But they may still coincide with
-    an explicit identifier that is given for a header later in the document,
-    or with an identifier on a div, span, link, or image. We now issue
-    a warning in this case, so users can supply an explicit identifier.
-
-  * CommonMark reader now supports `emoji`, `hard_line_breaks`, `smart`,
-    and `raw_html` extensions.
-
-  * Markdown reader:
-
-    + Don't allow backslash + newline to affect block structure (#3730).
-      Note that as a result of this change, the following, which formerly
-      produced a header with two lines separated by a line break, will
-      now produce a header followed by a paragraph:
-
-        # Hi\
-        there
-
-      This may affect some existing documents that relied on
-      this undocumented and unintended behavior.  This change makes pandoc
-      more consistent with other Markdown implementations, and with itself
-      (since the two-space version of a line break doesn't work inside ATX
-      headers, and neither version works inside Setext headers).
-
-
-  * Org reader (Albert Krewinkel, unless noted):
-
-    + Support `table.el` tables (#3314).
-    + Support macros (#3401).
-    + Support the `#+INCLUDE:` file inclusion mechanism (#3510).
-      Recognized include types are `example`, `export`, `src`, and
-      normal org file inclusion.  Advanced features like line numbers
-      and level selection are not implemented yet.
-    + Interpret more meta value as inlines.  The values of the following
-      meta variables are now interpreted using org-markup instead of
-      treating them as pure strings: `keywords` (comma-separated list of
-      inlines), `subtitle` (inline values), `nocite` (inline values, can
-      be repeated).
-    + Support `\n` export option (#3940).  This turns all newlines in the
-      text into hard linebreaks.
-
-  * RST reader:
-
-    + Improved admonition support (#223).  We no longer add an
-      `admonition` class, we just use the class for the type of admonition,
-      `note` for example.  We put the word corresponding to the label in
-      a paragraph inside a `Div` at the beginning of the admonition with
-      class `admonition-title`.  This is about as close as we can get to
-      RST's own output.
-    + Initial support of `.. table` directive.  This allows adding captions
-      to tables.
-    + Support `.. line-block` directive.  This is deprecated but may still
-      be in older documents.
-    + Support scale and align attributes of images (#2662).
-    + Implemented implicit internal header links (#3475).
-    + Support RST-style citations (#853).  The citations appear at the end
-      of the document as a definition list in a special div with id
-      `citations`. Citations link to the definitions.
-    + Recurse into bodies of unknown directives (#3432).
-      In most cases it's better to preserve the content than
-      to emit it.  This isn't guaranteed to have good results;
-      it will fail spectacularly for unknown raw or verbatim directives.
-    + Handle chained link definitions (#262).  For example,
-
-          .. _hello:
-          .. _goodbye: example.com
-
-      Here both `hello` and `goodbye` should link to `example.com`.
-    + Support anchors (#262).  E.g.
-
-          `hello`
-
-          .. _hello:
-
-          paragraph
-
-      This is supported by putting "paragraph" in a `Div` with id `hello`.
-    + Support `:widths:` attribute for table directive.
-    + Implement csv-table directive (#3533).  Most attributes are supported,
-      including `:file:` and `:url:`.
-    + Support unknown interpreted text roles by parsing them as Span
-      with "role" attributes (#3407).  This way they can be manipulated in
-      the AST.
-
-  * HTML reader: parse a span with class `smallcaps` as `SmallCaps`.
-
-  * LaTeX reader:
- 
-    + Implemented `\graphicspath` (#736).
-    + Properly handle column prefixes/suffixes.  For example, in
-      `\begin{tabular}{>{$}l<{$}>{$}l<{$} >{$}l<{$}}`
-      each cell will be interpreted as if it has a `$`
-      before its content and a `$` after (math mode).
-    + Handle komascript `\dedication` (#1845).  It now adds a
-      `dedication` field to metadata.  It is up to the user to supply
-      a template that uses this variable.
-    + Support all `\textXX` commands, where XX = `rm`, `tt`, `up`, `md`,
-      `sf`, `bf` (#3488).  Spans with a class are used when there is
-      nothing better.
-    + Expand `\newenvironment` macros (#987).
-    + Add support for LaTeX subfiles package (Marc Schreiber, #3530).
-    + Better support for subfigure package (#3577).
-      A figure with two subfigures turns into two pandoc
-      figures; the subcaptions are used and the main caption
-      ignored, unless there are no subcaptions.
-    + Add support for \vdots (Marc Schreiber, #3607).
-    + Add basic support for hyphenat package (Marc Schreiber, #3603).
-    + Add basic `\textcolor` support (Marc Schreiber).
-    + Add support for `tabularx` environment (Marc Schreiber, #3632).
-    + Better handling of comments inside math environments (#3113).
-      This solves a problem with commented out `\end{eqnarray}` inside
-      an eqnarray (among other things).
-    + Parse tikzpicture as raw verbatim environment if `raw_tex` extension
-      is selected (#3692).  Otherwise skip with a warning.  This is better
-      than trying to parse it as text!
-    + Add `\colorbox` support (Marc Schreiber).
-    + Set identifiers on Spans used for `\label`.
-    + Have `\setmainlanguage` set `lang` in metadata.
-    + Support etoolbox's `\ifstrequal`.
-    + Support `plainbreak`, `fancybreak` et al from the memoir class
-      (bucklereed, #3833).
-    + Support `\let`.  Also, fix regular macros so they're expanded at the
-      point of use, and NOT also the point of definition.  `\let` macros,
-      by contrast, are expanded at the point of definition.  Added an
-      `ExpansionPoint` field to `Macro` to track this difference.
-    + Support simple `\def` macros.  Note that we still don't support
-      macros with fancy parameter delimiters, like `\def\foo#1..#2{...}`.
-    + Support \chaptername, \partname, \abstractname, etc.  (#3559,
-      obsoletes #3560).
-    + Put content of `\ref`, `\label`, `\eqref` commands into `Span` with
-      attributes, so they can be handled in filters (Marc Schreiber, #3639)
-    + Add Support for `glossaries` and `acronym` package (Marc Schreiber,
-      #3589). Acronyms are not resolved by the reader, but acronym and
-      glossary information is put into attributes on Spans so that they
-      can be processed in filters.
-    + Use `Link` instead of `Span` for `\ref`.  This makes more sense
-      semantically and avoids unnecessary `Span [Link]` nestings when
-      references are resolved.
-    + Rudimentary support for `\hyperlink`.
-    + Support `\textquoteleft|right`, `\textquotedblleft|right` (#3849).
-    + Support `\lq`, `\rq`.
-    + Implement `\newtoggle`, `\iftoggle`, `\toggletrue|false` from etoolbox
-      (#3853).
-    + Support `\RN` and `\Rn`, from biblatex (bucklereed, #3854).
-    + Improved support for `\hyperlink`, `\hypertarget` (#2549).
-    + Support `\k` ogonek accent.
-    + Improve handling of accents.  Handle ogonek, and fall back correctly
-      with forms like `\"{}`.
-    + Better support for ogonek accents.
-    + Support for `\faCheck` and `\faClose` (Marc Schreiber, #3727).
-    + Support for `xspace` (Marc Schreiber, #3797).
-    + Support `\setmainlanguage` or `\setdefaultlanguage` (polyglossia)
-      and `\figurename`.
-    + Better handling of `\part` in LaTeX (#1905).  Now we parse chapters as
-      level 0 headers, and parts as level -1 headers.  After parsing, we
-      check for the lowest header level, and if it's less than 1 we bump
-      everything up so that 1 is the lowest header level.  So `\part` will
-      always produce a header; no command-line options are needed.
-    + Add block version of `\textcolor` (Marc Schreiber).
-    + `\textcolor` works as inline and block command (Marc Schreiber).
-    + `\textcolor` will be parse as span at the beginning of a paragraph
-      (Marc Schreiber).
-    + Read polyglossia/babel `\text(LANG){...}` (bucklereed)
-    + Improved handling of include files in LaTeX reader (#3971).
-      Previously `\include` wouldn't work if the included file
-      contained, e.g., a begin without a matching end.
-    + Support `\expandafter` (#3983).
-    + Handle `\DeclareRobustCommand` (#3983).  Currently it's just treated
-      as a synonym for `\newcommand`.
-    + Handle `\lettrine` (Mauro Bieg).
-
-  * Math improvements due to updates in texmath:
-
-    + Improved handling of accents and upper/lower delimiters.
-    + Support for output in GNU eqn format (used with *roff).
-    + Allow `\boldsymbol` + a token without braces, and similarly
-      with other styling commands.
-    + Improve parsing of `\mathop` to allow multi-character operator names.
-    + Add thin space after math operators when "faking it with
-      unicode."
-
-  * `walk` is now used instead of `bottomUp` in the `ToJSONFilter`
-    instance for `a -> [a]` (pandoc-types).  Note that behavior
-    will be slightly different, since `bottomUp`'s treatment of
-    a function `[a] -> [a]` is to apply it to each sublist of a
-    list, while walk applies it only to maximal sublists.
-    Usually the latter behavior is what is wanted, and the
-    former can be simulated when needed.  But there may be
-    existing filters that need to be rewritten in light of the
-    new behavior.  Performance should be improved.
-
-  * There are some changes to syntax highlighting due to revisions
-    in the `skylighting` library:
-
-    + Support for `powershell` has been added, and many syntax
-      definitions have been updated.
-    + Background colors have been added to the `kate` style.
-    + The way highlighted code blocks are formatted in HTML has
-      been changed (David Baynard), in ways that may require
-      changes in hard-coded CSS affecting highlighting.
-      (If you haven't included hard-coded highlighting CSS in
-      your template, you needn't change anything.)
-
-
-  [API changes]
-
-  * New module `Text.Pandoc.Class` (Jesse Rosenthal, John MacFarlane).
-    This contains definitions of the `PandocMonad` typeclass, the
-    `PandocIO` and `PandocPure` monads, and associated functions.
-
-  * Changed types of all writers and readers.
-
-    + We now use `Text` instead of `String` in the interface (#3731).
-      (We have not yet changed the internals of most readers to work
-      with `Text`, but making this change in the API now opens up a
-      path to doing that.)
-    + The result is now of form `m a` with constraint `PandocMonad m`.
-      Readers and writers can be combined to form monadic values which
-      can be run using either `runIO` or `runPure`.  If `runIO` is used,
-      then both readers and writers will be able to do IO when needed
-      (for include files, for example); if `runPure` is used,
-      then the functions are pure and will not touch IO.
-    + Where previously you used
-      `writeRST def (readMarkdown def "[foo](url)")`, now you
-      would use
-      `runPure $ readMarkdown def (pack "[foo](url)") >>= writeRST def`.
-
-  * New module `Text.Pandoc.Readers` (Albert Krewinkel).  This
-    contains reader helper functions formerly defined in the
-    top-level `Text.Pandoc` module.
-
-    + Changed `StringReader` -> `TextReader`.
-    + `getReader` now returns a pair of a reader and
-      `Extensions`, instead of building the extensions into the
-      reader (#3659).  The calling code must explicitly set
-      `readerExtensions` using the `Extensions` returned.  The
-      point of the change is to make it possible for the calling
-      code to determine what extensions are being used.
-
-  * New module `Text.Pandoc.Writers` (Albert Krewinkel).
-    This contains writer helper functions formerly defined in the
-    top-level `Text.Pandoc` module.
-
-    + Changed `StringWriter` -> `TextWriter`.
-    + `getWriter` now retuns a pair of a reader and
-      `Extensions`, instead of building the extensions into the
-      reader (#3659).  The calling code must explicitly set
-      `readerExtensions` using the `Extensions` returned.  The
-      point of the change is to make it possible for the calling
-      code to determine what extensions are being used.
-
-  * New module `Text.Pandoc.Lua`, exporting `runLuaFilter` (Albert Krewinkel,
-    #3514).
-
-  * New module `Text.Pandoc.App`.  This abstracts out the functionality
-    of the command line program (`convertWithOpts`), so it can be reproduced
-    e.g. in a desktop or web application.  Instead of exiting, we throw errors
-    (#3548), which are caught (leading to exit) in pandoc.hs, but allow other
-    users of `Text.Pandoc.App` to recover.  `pandoc.hs` is now a 2-liner.
-    The module also exports some utility functions for parsing options
-    and running filters.
-
-  * New module `Text.Pandoc.Logging` (exported module) (#3392).
-    This now contains the `Verbosity` definition previously in
-    `Text.Pandoc.Options`, as well as a new `LogMessage` datatype that will
-    eventually be used instead of raw strings for warnings.  This will enable
-    us, among other things, to provide machine-readable warnings if desired.
-    Include ToJSON instance and showLogMessage.  This gives us the possibility
-    of both machine-readable and human-readable output for log messages.
-
-  * New module `Text.Pandoc.BCP47`, with `getLang`, `Lang(..)`, `parseBCP47`.
-
-  * New module `Text.Pandoc.Translations`, exporting `Term`,
-    `Translations`, `readTranslations`.
-
-  * New module `Text.Pandoc.Readers.LaTeX.Types', exporting `Macro`, `Tok`,
-    `TokType`, `Line`, `Column`.
-
-  * `Text.Pandoc.Error`: added many new constructors for `PandocError`.
-
-  * Expose some previously private modules (#3260).  These are often
-    helpful to people writing their own reader or writer modules:
-
-    + `Text.Pandoc.Writers.Shared`
-    + `Text.Pandoc.Parsing`
-    + `Text.Pandoc.Asciify`
-    + `Text.Pandoc.Emoji`
-    + `Text.Pandoc.ImageSize`
-    + `Text.Pandoc.Highlighting`
-`
-  * New module `Text.Pandoc.Extensions` (Albert Krewinkel):
-    Extension parsing and processing functions were defined in the top-level
-    `Text.Pandoc` module.  These functions are moved to the Extensions
-    submodule as to enable reuse in other submodules.
-
-  * Add `Ext_raw_attribute` constructor for `Extension`.
-
-  * Add `Ext_fenced_divs` constructor for `Extension'.
-
-  * Add `Ext_four_space_rule` constructor in `Extension`.
-
-  * Add `Ext_gfm_auto_identifiers` constructor for `Extension`.
-
-  * Add `Monoid` instance for `Extensions`.
-
-  * Add `Text.Pandoc.Writers.Ms`, exporting `writeMs`.
-
-  * Add `Text.Pandoc.Writers.JATS`, exporting `writeJATS`.
-
-  * Add `Text.Pandoc.Writers.Muse`, exporting `writeMuse`.
-
-  * Add `Text.Pandoc.Readers.Muse`, exporting `readMuse`.
-
-  * Add `Text.Pandoc.Readers.TikiWiki`, exporting `readTikiWiki`.
-
-  * Add `Text.Pandoc.Readers.Vimwiki`, exporting `readVimwiki`.
-
-  * Add `Text.Pandoc.Readers.Creole`, exporting `readCreole`.
-
-  * Export `setVerbosity` from `Text.Pandoc`.
-
-  * `Text.Pandoc.Pretty`: Add `Eq` instance for `Doc`.
-
-  * `Text.Pandoc.XML`: `toEntities`: changed type to `Text -> Text`.
-
-  * `Text.Pandoc.UTF8`:
-
-    + Export `fromText`, `fromTextLazy`, `toText`, `toTextLazy`.
-      Define `toString`, `toStringLazy` in terms of them.
-    + Add new functions parameterized on `Newline`: `writeFileWith`,
-      `putStrWith`, `putStrLnWith`, `hPutStrWith`, `hPutStrLnWith`.
-
-  * `Text.Pandoc.MediaBag`: removed `extractMediaBag`.
-
-  * `Text.Pandoc.Highlighting`:
-
-    + `highlighting` now returns an Either rather than Maybe.
-      This allows us to display error information returned by the skylighting
-      library.  Display a warning if the highlighting library throws an error.
-    + Add parameter for `SyntaxMap` to `highlight`.
-
-  * `Text.Pandoc.Writers.Math`:
-
-    + Export `defaultMathJaxURL`, `defaultKaTeXURL`.  This will ensure that
-      we only need to update these in one place.
-
-  * `Text.Pandoc.SelfContained`:
-
-    + Removed `WriterOptions` parameter from `makeSelfContained`.
-    + Put `makeSelfContained` in PandocMonad instead of IO.  This removes
-      the need to pass MediaBag around and improves exceptions.  It also
-      opens up the possibility of using makeSelfContained purely.
-    + Export `makeDataURI`.
-
-  * `Text.Pandoc.ImageSize`:
-
-    + Export `lengthToDim`, new function `scaleDimension`.
-    + Export `inEm` from ImageSize (#3450).
-    + Change `showFl` and `show` instance for `Dimension` so
-      extra decimal places are omitted.
-    + Added `Em` as a constructor of `Dimension`.
-    + Add `WriterOptions` parameter to `imageSize` signature (Mauro Bieg).
-
-  * `Text.Pandoc.Templates`:
-
-    + Change type of `renderTemplate'`.  Now it runs in `PandocMonad`
-      and raises a proper `PandocTemplateError` if there are problems, rather
-      than failing with uncatchable `error`.
-    + Change signature of `getDefaultTemplate`.  Now it runs in any instance
-      of `PandocMonad`, and returns a `String` rather than an `Either` value.
-      And it no longer takes a `datadir` parameter, since this can be
-      retrieved from `CommonState`.
-
-  * `Text.Pandoc.Options`:
-
-    + Added `writerEpubSubdirectory` to `WriterOptions` (#3720).
-      The EPUB writer now takes its EPUB subdirectory from this option.
-    + In `WriterOptions`, rename `writerLaTeXEngine` to `writerPdfEngine`
-      and `writerLaTeXArgs` to `writerPdfArgs` (Mauro Bieg, #3909).
-    + Add `writerSyntaxMap` to `WriterOptions`.
-    + Removed `writerEpubStylesheet` from `WriterOptions`.
-    + Remove `writerUserDataDir` from `WriterOptions`.  It is now carried
-      in `CommonState` in `PandocMonad` instances.  (And thus it can be used
-      by readers too.)
-    + Changed `writerEpubMetadata` to a `Maybe String`.
-    + Removed `readerApplyMacros` from `ReaderOptions`.  Now we just check
-      the `latex_macros` reader extension.
-    + FromJSON/ToJSON instances for `ReaderOptions`.
-    + In `HTMLMathMethod`, the `KaTeX` contsructor now takes only
-      one string (for the KaTeX base URL), rather than two.
-    + Removed `writerSourceURL` from `WriterOptions`.  We now use
-      `stSourceURL` in `CommonState`, which is set by `setInputFiles`.
-
-  * `Text.Pandoc.Shared`:
-
-    + `tabFilter` now takes a `Text`, not `String`.
-    + `openURL`: Changed type from an Either.  Now it will just raise
-      an exception to be trapped later.
-    + Remove `normalizeSpaces` (#1530).
-    + Remove `warn`.  (Use `report` from `Text.Pandoc.Class` instead.)
-    + Export a new function `crFilter`.
-    + Add `eastAsianLineBreakFilter` (previously in Markdown reader).
-    + Provide custom `isURI` that rejects unknown schemes.
-      (Albert Krewinkel, #2713).  We also export the set of known
-      `schemes`.  The new function replaces the function of the same name
-      from `Network.URI`, as the latter did not check whether a scheme is
-      well-known.  All official IANA schemes (as of 2017-05-22) are
-      included in the set of known schemes.  The four non-official schemes
-      `doi`, `isbn`, `javascript`, and `pmid` are kept.
-    + Remove `err`.
-    + Remove `readDataFile`, `readDefaultDataFile`, `getReferenceDocx`,
-      `getReferenceODT`. These now live in `Text.Pandoc.Class`,
-      where they are defined in terms of `PandocMonad`
-      primitives and have different signatures.
-    + Remove `openURL`.  Use `openURL` from `Text.Pandoc.Class` instead.
-    + Add `underlineSpan`.
-
-  * `Text.Pandoc.Readers.HTML`: export new `NamedTag` class.
-
-  * `Text.Pandoc.Readers.Markdown`: remove `readDocxWithWarnings`.
-     With the new API one can simply use `getLog` after running
-     the reader.
-
-  * `Text.Pandoc.Readers.LaTeX`: Changed types for `rawLaTeXInline`
-     and `rawLaTeXBlock`.  (Both now return a `String`, and they are
-     polymorphic in state.)
-
-
-  [bug fixes and under-the-hood improvements]
-
-  * TEI writer: Added identifiers on `<div>` elements.
-
-  * DokuWiki reader: Better handling for code block in list item (#3824).
-
-  * Custom writer: Remove old preprocesesor conditionals (Albert Krewinkel).
-
-  * ZimWiki writer: Removed internal formatting from note and table cells,
-    because ZimWiki does not support it (Alex Ivkin, #3446).
-
-  * MediaWiki writer:
-
-    + Updated list of syntax highlighting languages (#3461).
-      Now `r` gets you `<source>` rather than `<code>` (among others).
-    + Add display attribute on `<math>` tags (#3452).  This allows display
-      math to be rendered properly.
-    + Remove newline before `</ref>` (#2652).
-    + Don't softbreak lines inside list items (#3531).
-
-  * Org writer:
-
-    + Reduce to two spaces after bullets (#3417, Albert Krewinkel).
-    + Add unit tests (Alexander Krotov).
-    + Stop using raw HTML to wrap divs (Albert Krewinkel, #3771).
-    + Do not strip `#` from Org anchor links (Alexander Krotov).
-
-  * CommonMark writer:
-
-    + Avoid excess blank lines at end of output.
-    + Prefer pipe tables to HTML tables even if it means losing relative
-      column width information (#3734).
-    + Support table, strikethrough extensions, when enabled (as with gfm).
-      Note that we bypass the commonmark writer from cmark and construct our
-      own pipe tables, with better results.
-    + Properly support `--wrap=none`.
-    + Use smallcaps class for `SmallCaps` (#1592).
-    + Omit "fig:" prefix in image titles.  This is used internally to
-      indicate internal figures.
-
-  * RST writer:
-
-    + Properly handle table captions.
-    + Don't wrap lines in in definition list terms.  Wrapping is not allowed.
-    + Implemented `+/-smart` and improved escaping with `+smart`.
-    + Add empty comments when needed to avoid including a blockquote
-      in the indented content of a preceding block (#3675).
-    + Improve grid table output, fix bug with empty rows (#3516).
-      Uses the new `gridTable` in Writers.Shared, which is here
-      improved to better handle 0-width cells.
-    + Remove space at beginning/end of RST code span (#3496).  Otherwise
-      we get invalid RST.  There seems to be no way to escape the space.
-    + Add header anchors when header has non-standard id (#3937).
-    + Correctly handle inline code containing backticks, using a `:literal:`
-      role (#3974).
-    + Don't backslash-escape word-internal punctuation (#3978).
-
-  * Markdown writer:
-
-    + Don't include variables in metadata blocks.  Previously variables set
-      on the command line were included in e.g. YAML metadata, contrary to
-      documentation and intentions.
-    + Improved escaping with `+smart`.
-    + Fixed grid tables embedded in grid tables (#2834).
-    + Use span with class 'smallcaps' for SmallCaps, instead of a style
-      attribute as before (#1592).
-    + Escape initial `%` in a paragraph if the `pandoc_title_blocks`
-      extension is enabled (#3454).  Otherwise in a document starting with
-      a literal `%` the first line is wrongly interpreted as a title.
-    + Fixed false ordered lists in YAML metadata (#3492, #1685).  Now we
-      properly escape things that would otherwise start ordered lists,
-      such as
-
-          ---
-          title: 1. inline
-          ...
-    + Better handling of tables with empty columns (#3337).  We now
-      calculate the number of columns based on the longest row (or the
-      length of aligns or widths).
-    + Escape unordered list markers at beginning of paragraph (#3497), to
-      avoid false interpretation as a list.
-    + Escape `|` appropriately.
-    + Ensure space before list at top level (#3487).
-    + Avoid spurious blanklines at end of document after tables and list,
-      for example.
-    + Fixed bugs in simple/multiline list output (#3384).
-      Previously we got overlong lists with `--wrap=none`.  This is fixed.
-      Previously a multiline list could become a simple list (and would
-      always become one with `--wrap=none`).
-    + Don't emit a simple table if `simple_tables` disabled (#3529).
-    + Case-insensitive reference links (David A Roberts, #3616).
-      Ensure that we do not generate reference links whose labels differ only
-      by case.  Also allow implicit reference links when the link
-      text and label are identical up to case.
-    + Put space before reference link definitions (Mauro Bieg, #3630).
-    + Better escaping for links (David A. Roberts, #3619).  Previously the
-      Markdown writer would sometimes create links where there were none
-      in the source.  This is now avoided by selectively escaping bracket
-      characters when they occur in a place where a link might be created.
-    + Added missing `\n` (David A. Roberts, #3647).
-    + Fixed duplicated reference links with `--reference-links`
-      and `--reference-location=section` (#3674).  Also ensure that there
-      are no empty link references `[]`.
-    + Avoid inline surround-marking with empty content (#3715).
-      E.g. we don't want `<strong></strong>` to become `****`.
-      Similarly for emphasis, super/subscript, strikeout.
-    + Don't allow soft break in header (#3736).
-    + Make sure `plain`, `markdown_github`, etc. work for raw.
-      Previously only `markdown` worked.  Note: currently a raw block labeled
-      `markdown_github` will be printed for any `markdown` format.
-    + Ensure that `+` and `-` are escaped properly so they don't cause
-      spurious lists (#3773).  Previously they were only
-      if succeeded by a space, not if they were at end of line.
-    + Use pipe tables if `raw_html` disabled and `pipe_tables` enabled,
-      even if the table has relative width information (#3734).
-    + Markdown writer: don't crash on `Str ""`.
-    + Make `Span` with null attribute transparent.  That is, we don't use
-      brackets or `<span>` tags to mark spans when there are no attributes;
-      we simply output the contents.
-    + Escape pipe characters when `pipe_tables` enabled (#3887).
-    + Better escaping of `<` and `>`.  If `all_symbols_escapable` is set,
-      we backslash escape these.  Otherwise we use entities as before.
-    + When writing plain, don't use `&nbsp;` to separate list and indented
-      code.  There's no need for it in this context, since this isn't to be
-      interpreted using Markdown rules.
-    + Preserve classes in JS obfuscated links (Timm Albers, #2989).
-      HTML links containing classes originally now preserve them when using
-      JavaScript email obfuscation.
-    + Render `SmallCaps` as a native span when `native_spans` are enabled.
-    + Always write attributes with `bracketed_spans` (d-dorazio).
-
-  * Man writer:
-
-    + Fix handling of nested font commands (#3568).  Previously pandoc emitted
-      incorrect markup for bold + italic, for example, or bold + code.
-    + Avoid error for definition lists with no definitions (#3832).
-
-  * DocBook writer:
-
-    + Fix internal links with `writerIdentifierPrefix opt`
-      (#3397, Mauro Bieg).
-
-  * Docx writer:
-
-    + Don't include bookmarks on headers unless non-null id (#3476).
-    + Support 9 levels of headers (#1642).
-    + Allow 9 list levels (#3519).
-    + Don't take `distArchive` from datadir (#3322).  The docx writer takes
-      components from the distribution's version of `reference.docx` when it
-      can't find them in a user's custom `reference.docx`.  Previously, we
-      allowed a `reference.docx` in the data directory (e.g. `~/.pandoc`)
-      to be used as the distribution's reference.docx.  This led to a
-      bizarre situation where pandoc would produce a good docx using
-      `--template ~/.pandoc/ref.docx`, but if `ref.docx` were moved to
-      `~/.pandoc/reference.docx`, it would then produce a corrupted docx.
-    + Fixed handling of soft hyphen (0173) (#3691).
-    + Better handling of keywords (#3719).
-    + Cleaner code for handling dir and style attributes for `Div`.
-    + Use `Set` for dynamic styles to avoid duplicates.
-    + Removed redundant element from data/docx/word/numbering.xml.
-      The elements we need are generated when the document is
-      compiled; this didn't do anything.
-    + Activate `evenAndOddHeaders` from reference docx (#3901,
-      Augustín Martín Barbero).
-
-  * ODT/OpenDocument writer:
-
-    + Calculate aspect ratio for percentage-sized images (Mauro Bieg, #3239).
-    + Use more widely available bullet characters (#1400).  The old
-      characters weren't available in some font sets.  These seem to work
-      well on Windows and Linux versions of LibreOffice.
-    + Wider labels for lists (#2421).  This avoids overly narrow labels for
-      ordered lists with `()` delimiters.  However, arguably it creates
-      overly wide labels for bullets.  Also, lists now start flush with
-      the margin, rather than indented.
-    + Fixed dropped elements in some ordered lists (#2434).
-
-  * FB2 writer:
-
-    + Don't render `RawBlock` as code.
-    + Don't fail with an error on interior headers (e.g. in list) (#3750).
-      Instead, omit them with an INFO message.
-    + Add support for "lang" metadata (Alexander Krotov, #3625).
-    + Format `LineBlock` as poem (Alexander Krotov).  Previously writer
-      produced one paragraph with `<empty-line/>` elements, which are not
-      allowed inside `<p>` according to FB2 schema.
-    + Replace `concatMap` with `cMap` (Alexander Krotov).
-    + Write FB2 lists without nesting blocks inside `<p>` (Alexander
-      Krotov, #4004)
-
-  * HTML writer:
-
-    + Make sure `html4`, `html5` formats work for raw blocks/inlines.
-    + Render raw inline environments when `--mathjax` used (#3816).
-      We previously did this only with raw blocks, on the assumption
-      that math environments would always be raw blocks. This has changed
-      since we now parse them as inline environments.
-    + Ensure we don't get two style attributes for width and height.
-    + Report when not rendering raw inline/block.
-    + Issue warning if no title specified and template used (#3473).
-    + Info message if `lang` is unspecified (#3486).
-    + Removed unused parameter in `dimensionsToAttributeList`.
-    + Avoid two class attributes when adding `uri` class (#3716).
-    + Fix internal links with `writerIdentifierPrefix opt` (#3397, Mauro
-      Bieg).
-    + Use revealjs's math plugin for mathjax (#3743).  This is a thin
-      wrapper around mathjax that makes math look better on revealjs.
-    + Slidy:  use h1 for all slides, even if they were originally
-      level 2 headers (#3566).  Otherwise the built-in table of contents
-      in Slidy breaks.
-
-  * LaTeX writer:
-
-    + Don't render LaTeX images with data: URIs (#3636).  Note that
-      `--extract-media` can be used when the input contains data: URIs.
-    + Make highlighted code blocks work in footnotes (Timm Albers).
-    + Don't use figure inside table cell (#3836).
-    + Use proper code for list enumerators (#3891).  This should fix problems
-      with lists that don't use arabic numerals.
-    + Always add hypertarget when there's a non-empty identifier (#2719).
-      Previously the hypertargets were only added when there was actually
-      a link to that identifier.
-    + Use `%` after hypertarget before code block.
-    + Add `\leavevmode` before hypertarget at start of paragraph (#2704,
-      fixes formatting problems in beamer citations).
-    + Don't use `lstinline` in \item[..] (#645).  If you do, the contents
-      of item disappear or are misplaced.  Use `\texttt` instead.
-    + Fix problem with escaping in `lstinline` (#1629).  Previously the
-      LaTeX writer created invalid LaTeX when `--listings` was specified and
-      a code span occured inside emphasis or another construction.
-    + Fix error with line breaks after empty content (#2874).  LaTeX
-      requires something before a line break, so we insert a `~` if no
-      printable content has yet been emitted.
-    + Use BCP47 parser.
-    + Fixed detection of otherlangs (#3770).  We weren't recursing into
-      inline contexts.
-    + Handle language in inline code with `--listings` (#3422).
-    + Write euro symbol directly in LaTeX (Andrew Dunning, #3801).
-      The textcomp package allows pdfLaTeX to parse `€` directly, making the
-      `\euro` command unneeded.
-    + Fixed footnotes in table captions (#2378).  Note that if the table has
-      a first page header and a continuation page header, the notes will
-      appear only on the first occurrence of the header.
-    + In `writeBeamer` output, allow hyperlinks to frames (#3220).
-      Previously you could link to a header above or below slide level but
-      not *to* slide level.  This commit changes that.  Hypertargets are
-      inserted inside frame titles; technically the reference is to just
-      after the title, but in normal use (where slides are viewed full
-      screen in a slide show), this does not matter.
-    + Remove `\strut` at beginning of table cells (#3436).  This fixes a
-      problem with alignment of lists in table cells.  The `\strut` at the
-      end seems to be enough to avoid the too-close spacing that motivated
-      addition of the strut  in #1573.
-    + Add partial siunitx Support (Marc Schreiber, #3588).
-
-  * ConTeXt writer:
-
-    + Refactored to use BCP47 module.
-    + Remove unnecessary `$` (Alexander Krotov, #3482).
-    + Use header identifiers for chapters (#3968).
-
-  * EPUB writer:
-
-    + `title_page.xhtml` is now put in `text/`.
-    + Don't strip formatting in TOC (#1611).
-
-  * Textile reader:
-
-    + Fix bug for certain links in table cells (#3667).
-    + Allow 'pre' code in list item (#3916).
-
-  * HTML reader:
-
-    + Added warnings for ignored material (#3392).
-    + Better sanity checks to avoid parsing unintended things as
-      raw HTML in the Markdown reader (#3257).
-    + Revise treatment of `li` with `id` attribute (#3596).  Previously we
-      always added an empty div before the list item, but this created
-      problems with spacing in tight lists.  Now we do this: If the list
-      item contents begin with a `Plain` block, we modify the `Plain`
-      block by adding a `Span` around its contents.  Otherwise, we add a
-      `Div` around the contents of the list item (instead of adding an
-      empty `Div` to the beginning, as before).
-    + Add `details` tag to list of block tags (#3694).
-    + Removed `button` from block tag list (#3717).  It is already in the
-      `eitherBlockOrInlineTag` list, and should be both places.
-    + Use `Set`s instead of lists for block tag lookup.
-    + Rewrote to use `Text` throughout.  Effect on memory usage is modest
-      (< 10%).
-    + Use the lang value of `<html>` to set the lang meta value (bucklereed,
-      #3765).
-    + Ensure that paragraphs are closed properly when the parent block
-      element closes, even without `</p>` (#3794).
-    + Parse `<figure>` and `<figcaption>` (Mauro Bieg, #3813).
-    + Parse `<main>` like `<div role=main>` (bucklereed, #3791).
-      `<main>` closes `<p>` and behaves like a block element generally
-    + Support column alignments (#1881).  These can be set either
-      with a `width` attribute or with `text-width` in a `style` attribute.
-    + Modified state type to be an instance of `HasLogMessages`, so
-      `registerHeader` can issue warnings.
-    + `</td>` or `</th>` should close any open block tag (#3991).
-    + `<td>` should close an open `<th>` or `<td>`.
-    + `htmlTag` improvements (#3989).  We previously failed on cases
-      where an attribute contained a `>` character. This patch fixes the
-      bug, which especially affects raw HTML in Markdown.
-
-  * Txt2Tags reader:
-
-    + Newline is not indentation (Alexander Krotov).
-
-  * MediaWiki reader:
-
-    + Allow extra hyphens after `|-` in tables (#2649).
-    + Allow blank line after table start (#2649).
-    + Fixed more table issues (#2649).
-    + Ensure that list starts begin at left margin (#2606).  Including when
-      they're in tables or other list items.
-    + Make smart double quotes depend on `smart` extension (#3585).
-    + Don't do curly quotes inside `<tt>` contexts (#3585).  Even if `+smart`.
-    + Modified state type to be an instance of `HasLogMessages`, so
-      `registerHeader` can issue warnings.
-
-  * TWiki reader (Alexander Krotov):
-
-    + Remove unnecessary `$` (#3597).
-    + Simplify `linkText` (#3605).
-
-  * EPUB reader:
-
-    + Minor refactoring, avoiding explicit MediaBag handling.
-      This all works behind the scenes in CommonState plumbing.
-
-  * Docx reader:
-
-    + Don't drop smartTag contents (#2242).
-    + Handle local namespace declarations (#3365).  Previously we didn't
-      recognize math, for example, when the xmlns declaration occured on
-      the element and not the root.
-    + More efficient trimSps (#1530).  Replacing `trimLineBreaks`.  This
-      does the work of `normalizeSpaces` as well, so we avoid the need for
-      that function here.
-    + Avoid 0-level headers (Jesse Rosenthal, #3830).  We used to parse
-      paragraphs styled with "HeadingN" as "nth-level header." But if a
-      document has a custom style named "Heading0", this will produce a
-      0-level header, which shouldn't exist. We only parse this style
-      if N>0. Otherwise we treat it as a normal style name, and
-      follow its dependencies, if any.
-    + Add tests for avoiding zero-level header (Jesse Rosenthal).
-
-  * ODT reader:
-
-    + Replaced `collectRights` with Rights from `Data.Either`.
-    + Remove dead code (Albert Krewinkel).
-
-  * Org reader (Albert Krewinkel, unless noted).
-
-    + Don't allow tables inside list items (John MacFarlane, #3499).
-    + Disallow tables on list marker lines (#3499).
-    + Convert markup at beginning of footnotes (John MacFarlane, #3576).
-    + Allow emphasized text to be followed by `[` (#3577).
-    + Handle line numbering switch for src blocks.
-      The line-numbering switch that can be given to source blocks (`-n` with
-      an start number as an optional parameter) is parsed and translated to a
-      class/key-value combination used by highlighting and other readers and
-      writers.
-    + Stop adding rundoc prefix to src params.  Source block parameter names
-      are no longer prefixed with `rundoc`. This was intended to simplify
-      working with the rundoc project, a babel runner. However, the rundoc
-      project is unmaintained, and adding those markers is not the reader's
-      job anyway.  The original language that is specified for a source
-      element is now retained as the `data-org-language` attribute and only
-      added if it differs from the translated language.
-    + Allow multi-word arguments to src block params (#3477).  The reader now
-      correctly parses src block parameter list even if parameter arguments
-      contain multiple words.
-    + Avoid creating `nullMeta` by applying `setMeta` directly
-      (Alexander Krotov).
-    + Replace `sequence . map` with `mapM`.
-    + Fix smart parsing behavior.  Parsing of smart quotes and special
-      characters can either be enabled via the `smart` language extension or
-      the `'` and `-` export options. Smart parsing is active if either the
-      extension or export option is enabled.  Only smart parsing of special
-      characters (like ellipses and en and em dashes) is enabled by default,
-      while smart quotes are disabled.  Previously, all smart parsing was
-      disabled unless the language extension was enabled.
-    + Subject full doc tree to headline transformations (Albert Krewinkel,
-      #3695).  Emacs parses org documents into a tree structure, which is
-      then post-processed during exporting. The reader is changed to do the
-      same, turning the document into a single tree of headlines starting
-      at level 0.
-    + Fix cite parsing behaviour (Herwig Stuetz).  Until now, `org-ref`
-      cite keys included special characters also at the end. This caused
-      problems when citations occur right before colons or at the end of
-      a sentence.  With this change, all non alphanumeric characters at
-      the end of a cite key are ignored.  This also adds `,` to the list
-      of special characters that are legal in cite keys to better mirror
-      the behaviour of org-export.
-    + Fix module names in haddock comments.  Copy-pasting had lead to
-      haddock module descriptions containing the wrong module names.
-    + Recognize babel result blocks with attributes (#3706).  Babel
-      result blocks can have block attributes like captions and names.
-      Result blocks with attributes were not recognized and were parsed
-      as normal blocks without attributes.
-    + Include tags in headlines.  The Emacs default is to include tags in the
-      headline when exporting.  Instead of just empty spans, which contain the
-      tag name as attribute, tags are rendered as small caps and wrapped in
-      those spans.  Non-breaking spaces serve as separators for multiple tags.
-    + Respect export option for tags (#3713).  Tags are appended to
-      headlines by default, but will be omitted when the `tags` export option
-      is set to nil.
-    + Use `tag-name` attribute instead of `data-tag-name`.
-    + Use `org-language` attribute rather than `data-org-language`.
-    + Modified state type to be an instance of `HasLogMessages`, so
-      `registerHeader` can issue warnings.
-    + End footnotes after two blank lines.  Footnotes can not only be
-      terminated by the start of a new footnote or a header, but also by two
-      consecutive blank lines.
-    + Update emphasis border chars (#3933).  The org reader was updated to
-      match current org-mode behavior: the set of characters which are
-      acceptable to occur as the first or last character in an org emphasis
-      have been changed and now allows all non-whitespace chars at the
-      inner border of emphasized text (see `org-emphasis-regexp-components`).
-
-  * RST reader:
-
-    + Fixed small bug in list parsing (#3432).  Previously the parser didn't
-      handle properly this case:
-
-          * - a
-            - b
-          * - c
-            - d
-    + Handle multiline cells in simple tables (#1166).
-    + Parse list table directive (Keiichiro Shikano, #3432).
-    + Make use of `anyLineNewline` (Alexander Krotov, #3686).
-    + Use `anyLineNewline` in `rawListItem` (Alexander Krotov, #3702).
-    + Reorganize block parsers for ~20% faster parsing.
-    + Fixed `..include::` directive (#3880).
-    + Handle blank lines correctly in line blocks (Alexander Krotov, #3881).
-      Previously pandoc would sometimes combine two line blocks separated
-      by blanks, and ignore trailing blank lines within the line block.
-    + Fix indirect hyperlink targets (#512).
-
-  * Markdown reader:
-
-    + Allow attributes in reference links to start on next line (#3674).
-    + Parse YAML metadata in a context that sees footnotes defined in
-      the body of the document (#1279).
-    + When splitting pipe table cells, skip tex math (#3481).
-      You might have a `|` character inside math.  (Or for that matter
-      something that the parser might mistake for raw HTML.)
-    + Treat span with class `smallcaps` as SmallCaps.
-      This allows users to specify small caps in Markdown this way:
-      `[my text]{.smallcaps}` (#1592).
-    + Fixed internal header links (#2397).
-      This patch also adds `shortcut_reference_links` to the list
-      of mmd extensions.
-    + Treat certain environments as inline
-      when they occur without space surrounding them (#3309, #2171).
-      E.g. equation, math.  This avoids incorrect vertical space
-      around equations.
-    + Optimized `nonindentSpaces`.  Makes the benchmark go from 40 to 36 ms.
-    + Allow latex macro definitions indented 1-3 spaces.
-      Previously they only worked if nonindented.
-    + Improved parsing of indented raw HTML blocks (#1841).
-      Previously we inadvertently interpreted indented HTML as
-      code blocks.  This was a regression.  We now seek to determine the
-      indentation level of the contents of an HTML block, and (optionally)
-      skip that much indentation.  As a side effect, indentation may be
-      stripped off of raw HTML blocks, if `markdown_in_html_blocks` is
-      used. This is better than having things interpreted as indented
-      code blocks.
-    + Fixed smart quotes after emphasis (#2228).  E.g. in `*foo*'s 'foo'`.
-    + Warn for notes defined but not used (#1718).
-    + Use `anyLineNewline` (Alexander Krotov).
-    + Interpret YAML metadata as Inlines when possible (#3755).  If
-      the metadata field is all on one line, we try to interpret it as
-      Inlines, and only try parsing as Blocks if that fails.  If it
-      extends over one line (including possibly the `|` or `>` character
-      signaling an indented block), then we parse as Blocks.  This was
-      motivated by some German users finding that `date: '22. Juin 2017'`
-      got parsed as an ordered list.
-    + Fixed spurious parsing as citation as reference def (#3840).
-      We now disallow reference keys starting with `@` if the
-      `citations` extension is enabled.
-    + Parse `-@roe` as suppress-author citation (pandoc-citeproc#237).
-      Previously only `[-@roe]` (with brackets) was recognized as
-      suppress-author, and `-@roe` was treated the same as `@roe`.
-    + Fixed parsing of fenced code after list when there is no intervening
-      blank line (#3733).
-    + Allow raw latex commands starting with `\start` (#3558).  Previously
-      these weren't allowed because they were interpreted as starting
-      ConTeXt environments, even without a corresponding `\stop`...
-    + Added `inlines`, `inlines1`.
-    + Require nonempty alt text for `implicit_figures` (#2844).
-      A figure with an empty caption doesn't make sense.
-    + Removed texmath macro material; now all this is handled
-      in the LaTeX reader functions.
-    + Fixed bug with indented code following raw LaTeX (#3947).
-
-  * LaTeX reader:
-
-    + Rewrote LaTeX reader with proper tokenization (#1390,
-      #2118, #3236, #3779, #934, #982).  This rewrite is primarily
-      motivated by the need to get macros working properly.  A side benefit
-      is that the reader is significantly faster.  We now tokenize the
-      input text, then parse the token stream.  Macros modify the token
-      stream, so they should now be effective in any context, including
-      math. Thus, we no longer need the clunky macro processing
-      capacities of texmath.
-    + Parse `\,` to `\8198` (six-per-em space) (Henri Werth).
-    + Allow `\newcommand\foo{blah}` without braces.
-    + Support `\lstinputlisting` (#2116).
-    + Issue warnings when skipping unknown latex commands (#3392).
-    + Include contents of `\parbox`.
-    + Allow `\hspace` and `\vspace` to count as raw block or inline.
-      Previously we would refuse to parse anything as raw inline if
-      it was in the `blockCommands` list.  Now we allow exceptions
-      if they're listed under ignoreInlines in inlineCommands.
-      This should make it easier e.g. to include an `\hspace`
-      between two side-by-side raw LaTeX tables.
-    + Don't drop contents of `\hypertarget`.
-    + Handle spaces before `\cite` arguments.
-    + Allow newpage, clearpage, pagebreak in inline contexts as well as
-      block contexts (#3494).
-    + Treat `{{xxx}}` the same as `{xxx}` (#2115).
-    + Use `pMacroDefinition` in macro (for more direct parsing).
-      Note that this means that `macro` will now parse one
-      macro at a time, rather than parsing a whole group together.
-    + Fixed failures on \ref{}, \label{} with `+raw_tex`.  Now these
-      commands are parsed as raw if `+raw_tex`; otherwise, their argument
-      is parsed as a bracketed string.
-    + Don't crash on empty `enumerate` environment (#3707).
-    + Handle escaped `&` inside table cell (#3708).
-    + Handle block structure inside table cells (#3709).  `minipage` is no
-      longer required.
-    + Handle some width specifiers on table columns (#3709).  Currently
-      we only handle the form `0.9\linewidth`.  Anything else would have
-      to be converted to a percentage, using some kind arbitrary assumptions
-      about line widths.
-    + Make sure `\write18` is parsed as raw LaTeX.  The change is in the
-      LaTeX reader's treatment of raw commands, but it also affects the
-      Markdown reader.
-    + Fixed regression with starred environment names (#3803).
-    + Handle optional args in raw `\titleformat` (#3804).
-    + Improved heuristic for raw block/inline.  An unknown command at the
-      beginning of the line that could be either block or inline is
-      treated as block if we have a sequence of block commands followed by
-      a newline or a `\startXXX` command (which might start a raw ConTeXt
-      environment).
-    + Don't remove macro definitions from the output, even if
-      `Ext_latex_macros` is set, so that macros will be applied.
-      Since they're only applied to math in Markdown, removing the macros
-      can have bad effects.  Even for math macros, keeping them should be
-      harmless.
-    + Removed `macro`.  It is no longer necessary, since the
-      `rawLaTeXBlock` parser will parse macro definitions.  This also avoids
-      the need for a separate `latexMacro` parser in the Markdown reader.
-    + Use `label` instead of `data-label` for label in caption (#3639).
-    + Fixed space after \figurename etc.
-    + Resolve references to section numbers.
-    + Fix `\let\a=0` case, with single character token.
-    + Allow `@` as a letter in control sequences.  `@` is commonly used
-      in macros using `\makeatletter`.  Ideally we'd make the tokenizer
-      sensitive to `\makeatletter` and `\makeatother`, but until then this
-      seems a good change.
-    + Track header numbers and correlate with labels.
-    + Allow `]` inside group in option brackets (#3857).
-    + lstinline with braces can be used (verb cannot be used with braces)
-      (Marc Schreiber, #3535).
-    + Fix keyval funtion: pandoc did not parse options in braces correctly
-      (Marc Schreiber, #3642).
-    + When parsing raw LaTeX commands, include trailing space (#1773).
-      Otherwise things like `\noindent foo` break and turn into
-      `\noindentfoo`.  Affects `-f latex+raw_tex` and `-f markdown` (and other
-      formats that allow `raw_tex`).
-    + Don't treat "..." as Quoted (#3958).  This caused quotes to be omitted in
-      `\texttt` contexts.
-    + Add tests for existing `\includegraphics` behaviour (Ben Firshman).
-    + Allow space before `=` in bracketd options (Ben Firshman).
-    + Be more forgiving in parsing command options.  This was needed, for
-      example, to make some minted options work.
-    + Strip off quotes in `\include` filenames.
-
-  * Added `Text.Pandoc.CSV`, simple (unexported) CSV parser.
-
-  * `Text.Pandoc.PDF`:
-
-    + Got `--resource-path` working with PDF output (#852).
-    + Fetch images when generating PDF via context (#3380).
-      To do this, we create the temp directory as a subdirectory
-      of the working directory. Since context mk IV by default looks
-      for images in the parent directory, this works.
-    + Use `report` instead of `warn`, make it sensitive to verbosity settings.
-    + Use `fillMediaBag` and `extractMedia` to extract media to temp dir.
-      This reduces code duplication.
-    + `html2pdf`: use stdin instead of intermediate HTML file
-    + Removed useless `TEXINPUTS` stuff for `context2pdf`.  mkiv context
-      doesn't use `TEXINPUTS`.
-
-  * `Text.Pandoc.Pretty`:
-
-    + Simplified definition of `realLength`.
-    + Don't error for blocks of size < 1.  Instead, resize to 1 (see #1785).
-
-  * `Text.Pandoc.MIME`:
-
-    + Use `application/javascript` (not `application/x-javascript`).
-    + Added `emf` to mimeTypes with type `application/x-msmetafile` (#1713).
-
-  * `Text.Pandoc.ImageSize`:
-
-    + Improve SVG image size code (Marc Schreiber, #3580).
-    + Make `imageSize` recognize basic SVG dimensions (Mauro Bieg, #3462).
-
-  * Use `Control.Monad.State.Strict` throughout.  This gives 20-30% speedup
-    and reduction of memory usage in most of the writers.
-
-  * Use `foldrWithKey` instead of deprecated `foldWithKey`.
-
-  * `Text.Pandoc.SelfContained`:
-
-    + Fixed problem with embedded fonts (#3629).
-    + Refactored getData from `getDataURI` in `SelfContained`.
-    + Don't use data URIs for script or style (#3423).  Instead, just use
-      script or style tags with the content inside.  The old method with
-      data URIs prevents certain optimizations outside pandoc.  Exception:
-      data URIs are still used when a script contains `</script>` or a
-      style contains `</`.
-    + SelfContained: Handle URL inside material retrieved from a URL
-      (#3629).  This can happen e.g. with an @import of a google web font.
-      (What is imported is some CSS which contains an url reference
-      to the font itself.) Also, allow unescaped pipe (|) in URL.
-    + Load resources from `data-src` (needed for lazy loading in
-      reveal.js slide shows).
-    + Handle `data-background-image` attribute on section (#3979).
-
-  * `Text.Pandoc.Parsing`:
-
-    + Added `indentWith` (Alexander Krotov, #3687).
-    + Added `stateCitations` to `ParserState`.
-    + Removed `stateChapters` from `ParserState`.
-    + In `ParserState`, make `stateNotes'` a Map, add `stateNoteRefs`.
-    + Added `gobbleSpaces` and `gobbleAtMostSpaces`.
-    + Adjusted type of `insertIncludedFile` so it can be used with token
-      parser.
-    + Replace old texmath macro stuff from Parsing.  Use Macro from
-      Text.Pandoc.Readers.LaTeX.Types instead.
-    + Export `insertIncludedFile`.
-    + Added `HasLogMessages`, `logMessage`, `reportLogMessages` (#3447).
-    + Replace partial with total function (Albert Krewinkel).
-    + Introduce `HasIncludeFiles` type class (Albert Krewinkel).  The
-      `insertIncludeFile` function is generalized to work with all parser
-      states which are instances of that class.
-    + Add `insertIncludedFilesF` which returns F blocks (Albert Krewinkel).
-      The `insertIncludeFiles` function was generalized and renamed
-      to `insertIncludedFiles'`; the specialized versions are based on that.
-    + `many1Till`: Check for the end condition before parsing (Herwig
-      Stuetz).  By not checking for the end condition before the first
-      parse, the parser was applied too often, consuming too much of the
-      input. This only affects `many1Till p end` where `p` matches on a
-      prefix of `end`.
-    + Provide `parseFromString` (#3690).  This is a verison of
-      `parseFromString` specialied to ParserState, which resets
-      `stateLastStrPos` at the end.  This is almost always what we want.
-      This fixes a bug where `_hi_` wasn't treated as emphasis in the
-      following, because pandoc got confused about the position of the
-      last word: `- [o] _hi_`.
-    + Added `takeP`, `takeWhileP` for efficient parsing of `[Char]`.
-    + Fix `blanklines` documentation (Alexander Krotov, #3843).
-    + Give less misleading line information with `parseWithString`.
-      Previously positions would be reported past the end of the chunk.
-      We now reset the source position within the chunk and report
-      positions "in chunk."
-    + Add `anyLineNewline` (Alexander Krotov).
-    + Provide shared F monad functions for Markdown and Org readers
-      (Albert Krewinkel).  The `F` monads used for delayed evaluation
-      of certain values in the Markdown and Org readers are based on a
-      shared data type capturing the common pattern of both `F` types.
-    + Add `returnF` (Alexander Krotov).
-    + Avoid parsing `Notes:**` as a bare URI (#3570).  This avoids parsing
-      bare URIs that start with a scheme + colon + `*`, `_`, or `]`.
-    + Added `readerAbbreviations` to `ParserState`.  Markdown reader
-      now consults this to determine what is an abbreviation.
-    + Combine grid table parsers (Albert Krewinkel, #3638).  The grid table
-      parsers for markdown and rst was combined into one single
-      parser `gridTable`, slightly changing parsing behavior of both
-      parsers: (1) The markdown parser now compactifies block content
-      cell-wise: pure text blocks in cells are now treated as paragraphs
-      only if the cell contains multiple paragraphs, and as plain blocks
-      otherwise. Before, this was true only for single-column tables. (2)
-      The rst parser now accepts newlines and multiple blocks in header
-      cells.
-    + Generalize tableWith, gridTableWith (Albert Krewinkel).
-      The parsing functions `tableWith` and `gridTableWith` are generalized
-      to work with more parsers. The parser state only has to be an
-      instance of the `HasOptions` class instead of requiring a concrete
-      type. Block parsers are required to return blocks wrapped into a
-      monad, as this makes it possible to use parsers returning results
-      wrapped in `Future`s.
-
-  * `Text.Pandoc.Shared`:
-
-    + Simplify `toRomanNumeral` using guards (Alexander Krotov, #3445)
-    + `stringify`: handle Quoted better (#3958).  Previously we were losing
-      the quotation marks in Quoted elements.
-
-  * `Text.Pandoc.Writers.Shared`:
-
-    + Export `metaToJSON'`, `addVariablesToJSON` (#3439).
-      This allows us to add the variables AFTER using the metadata
-      to generate a YAML header (in the Markdown writer).
-    + Added `unsmartify` (previously in RST writer).
-      Undo literal double curly quotes.  Previously we left these.
-    + Generalize type of `metaToJSON` so it can take a Text.  Previously a
-      String was needed as argument; now any ToJSON instance will do.
-    + Added `gridTable` (previously in Markdown writer).
-    + `gridTable`: Refactored to use widths in chars.
-    + `gridTable`:  remove unnecessary extra space in cells.
-    + Fixed `addVariablesToJSON`.  It was previously not allowing multiple
-      values to become lists.
-    + Pipe tables: impose minimum cell size (see #3526).
-
-
-  [default template changes]
-
-  * HTML templates (including EPUB and HTML slide show templates):
-
-    + Make default.html5 polyglot markup conformant (John Luke Bentley,
-      #3473).  Polyglot markup is HTML5 that is also valid XHTML. See
-      <https://www.w3.org/TR/html-polyglot>.  With this change, pandoc's
-      html5 writer creates HTML that is both valid HTML5 and valid XHTML.
-    + Regularized CSS in html/epub/html slide templates (#3485).
-      All templates now include `code{white-space: pre-wrap}`
-      and CSS for `q` if `--html-q-tags` is used.  Previously some templates
-      had `pre` and others `pre-wrap`; the `q` styles were only sometimes
-      included.
-    + CSS for `.smallcaps`, (Mauro Bieg, #1592)
-    + `default.revealjs`: make `history` default to true.
-    + `default.revealjs`: use lazy loading (#2283).
-    + `default.revealjs`: add `mathjax` variable and some conditional code
-      to use the MathJaX plugin.
-    + `default.slidy` uses `https` instead of `http` (ickc, #3848).
-    + `default.dzslides`: Load Google Font using HTTPS by default
-      (Yoan Blanc).
-
-  * DocBook5 template: Use `lang` and `subtitle` variables (Jens Getreu,
-    #3855).
-
-  * LaTeX/Beamer template:
-
-    + Combine LaTeX/Beamer templates (Andrew Dunning, #3878).
-      `default.beamer` has been removed; beamer now uses the
-      `default.latex` template.  Beamer-specific parts are conditional
-      on the `beamer` variable set by the writer. Note that
-      `pandoc -D beamer` will return this (combined) template.
-    + Use `xcolor` for `colorlinks` option (Andrew Dunning, #3877).
-      Beamer loads `xcolor` rather than `color`, and thus the
-      `dvipsnames` option doesn't take effect. This also provides a wider
-      range of colour selections with the `svgnames` option.
-    + Use starred versions of `xcolor` names (Andrew Dunning).
-      Prevents changes to documents defined using the `dvipsnames` list (e.g.
-      `Blue` gives a different result with svgnames enabled).
-    + Load `polyglossia` after header-includes (#3898).  It needs to be
-      loaded as late as possible.
-    + Use `unicode-math` (Vaclav Haisman).  Use `mathspec` with only
-      XeLaTeX on request.
-    + Don't load `fontspec` before `unicode-math` (over there).
-      The `unicode-math` package loads `fontspec` so explict loading of
-      `fontspec` before `unicode-math` is not necessary.
-    + Use `unicode-math` by default in default.latex template.  mathspec will
-      be used in xelatex if the `mathspec` variable is set; otherwise
-      unicode-math will be used (Václav Haisman).
-    + Use `dvipsnames` options when `colorlinks` specified (otherwise
-      we get an error for `maroon`) (Thomas Hodgson).
-    + Added beamer `titlegraphic` and `logo` variables (Thomas Hodgson).
-    + Fix typo in fix for notes in tables (#2378, zeeMonkeez).
-    + Fix `hyperref` options clash (Andrew Dunning, #3847) Avoids an options
-      clash when loading a package (e.g. `tufte-latex`) that uses
-      `hyperref` settings different from those in the template.
-    + Add `natbiboptions` variable (#3768).
-    + Fix links inside captions in LaTeX output with links-as-notes
-      (Václav Haisman, #3651).  Declare our redefined `\href` robust.
-    + Load `parskip` before `hyperref` (Václav Haisman, #3654).
-    + Allow setting Japanese fonts when using LuaLaTeX (Václav Haisman,
-      #3873).  by using the `luatexja-fontspec` and `luatexja-preset`
-      packages. Use existing `CJKmainfont` and `CJKoptions` template
-      variables. Add `luatexjafontspecoptions` for `luatexja-fontspec`
-      and `luatexjapresetoptions` for `luatexja-preset`.
-    + Added `aspectratio` variable to beamer template (Václav Haisman,
-      #3723).
-    + Modified template.latex to fix XeLaTex being used with tables
-      (lwolfsonkin, #3661).  Reordered `lang` variable handling to
-      immediately before `bidi`.
-
-  * ConTeXt template: Improved font handling: `simplefonts` is now
-    obsolete in ConTeXt (Pablo Rodríguez).
-
-
-  [documentation improvements]
-
-  * MANUAL.txt:
-
-    + Add URL for Prince HTML > PDF engine (Ian, #3919).
-    + Document that content above slide-level will be omitted in
-      slide shows.  See #3460, #2265.
-    + Explain `--webtex` SVG url (Mauro Bieg, #3471)
-    + Small clarification in YAML metadata section.
-    + Document that html4 is technically XHTML 1.0 transitional.
-    + Remove refs to highlighting-kate (#3672).
-    + Document ibooks specific epub metadata.
-    + Clarify that mathml is used for ODT math.
-    + Mention limitations of Literate Haskell Support (#3410,
-      Joachim Breitner).
-    + Add documentation of limitations of grid tables (Stephen
-      McDowell, #3864).
-    + Clarify that meta-json contains transformed values (Jakob Voß,
-      #3491) Make clear that template variable `meta-json` does not
-      contain plain text values or JSON output format but field values
-      transformed to the selected output format.
-
-  * COPYRIGHT:
-
-    + Clarify that templates are dual-licensed.
-    + Clarify that pandoc-types is BSD3 licensed.
-    + List new files not written by jgm (Albert Krewinkel).
-    + Update dates in copyright notices (Albert Krewinkel).  This follows
-      the suggestions given by the FSF for GPL licensed software.
-      <https://www.gnu.org/prep/maintain/html_node/Copyright-Notices.html>
-
-  * INSTALL.md:
-
-    + Improved instructions for tests with patterns.
-    + Put RPM-based distros on separate point (Mauro Bieg, #3449)
-
-  * CONTRIBUTING.md:
-
-    + Fixed typos (Wandmalfarbe, #3479).
-    + Add "ask on pandoc-discuss" (Mauro Bieg).
-
-  * Add lua filter documentation in `doc/lua-filters.md`.  Note that the
-    end of this document is autogenerated from `data/pandoc.lua`
-    using `make doc/lua-filters.md`, which uses `tools/ldoc.ltp`
-    (Albert Krewinkel).
-
-  * Add `doc/filters.md`. This is the old scripting tutorial from
-    the website.
-
-  * Add `doc/using-the-pandoc-api.md` (#3289).  This gives an introduction
-    to using pandoc as a Haskell library.
-
-
-  [build infrastructure improvements]
-
-  * Removed `data/templates` submodule.  Templates are now a subtree
-    in `data/templates`.  This removes the need to do `git submodule
-    update`.
-
-  * Renamed `tests` -> `test`.
-
-  * Remove `https` flag.  Always build with HTTPS support.
-
-  * Use `file-embed` instead of `hsb2hs` to embed data files when
-    `embed_data_files` flag is set.  `file-embed` gives us better dependency
-    tracking:  if a data file changes, ghc/stack/cabal know to recompile
-    the Data module.  This also removes `hsb2hs` as a build dependency.
-
-  * Add `custom-setup` stanza to pandoc, lowercase field names.
-
-  * Add `static` Cabal flag.
-
-  * Name change OSX -> MacOS.  Add a -MacOS suffix to mac package rather
-    than -OSX.  Changed local names from osx to macos.
-
-  * make_macos_package.sh - Use strip to reduce executable size.
-
-  * Revised binary linux package.  Now a completely static executable
-    is created, using Docker and alpine.  We create both a deb and a
-    tarball.  The old `deb` directory has been replaced with a `linux`
-    directory.  Running `make` in the `linux` directory should
-    perform the build, putting the binary packages in `artifacts/`.
-
-  * `linux/control.in`: add `Replaces:`, so existing pandoc-citeproc and
-    pandoc-data packages will be uninstalled; this package provides
-    both (#3822).  Add latex packages as 'suggested', update
-    description.
-
-  * Remove cpphs build requirement -- it is no longer needed.
-
-  * Replaced `{deb,macos,windows}/stack.yaml` with `stack.pkg.yaml`.
-
-  * Name change OSX -> macOS (ickc, #3869).
-
-  * Fix casing of Linux, UNIX, and Windows (ickc).
-
-  * `.travis.yml`:  create a source dist and do cabal build and test there.
-    That way we catch errors due to files missing from the data
-    section of pandoc.cabal.
-
-  * Makefile:
-
-    + Split `make haddock` from `make full`.
-    + Add BRANCH variable for winpkg.
-    + Add `lint` target.
-    + Improve `make full`. Disable optimizations.
-      Build everything, inc. trypandoc and benchmarks.  Use parallel build.
-    + Allow `make test` to take `TESTARGS`.
-
-  * Added new command tests (`Tests.Command`), using small text files
-    in `test/command/`.  Any files added in this directory will be treated
-    as shell tests (see smart.md for an example).  This makes it very easy
-    to add regression tests etc.
-
-  * Test fixes so we can find data files.  In old tests & command tests,
-    we now set the environment variable `pandoc_datadir`.  In lua tests,
-    we set the datadir explicitly.
-
-  * Refactored `compareOutput` in docx writer test.
-
-  * Consolidated some common functions in `Tests.Helper`.
-
-  * Small change to unbalanced bracket test to speed up test suite.
-
-  * Speed up Native writer quickcheck tests.
-
-  * Use tasty for tests rather than test-framework.
-
-  * Add simple Emacs mode to help with Pandoc templates editing.
-    (Václav Haisman, #3889). `tools/pandoc-template-mode.el`
-
-
-pandoc (1.19.2)
-
-  * Use skylighting library instead of highlighting-kate for syntax
-    highlighting. Skylighting is faster and more accurate (#3363).
-    Later we'll be able to add features like warning messages, dynamic
-    loading of xml syntax definitions, and dynamic loading of themes.
-
-  * Added a new highlight style, `breezeDark`.
-
-  * Text.Pandoc.Highlighting: Update list of `listings` languages (#3374).
-    This allows more languages to be used when using the `--listings`
-    option.
-
-  * OpenDocument writer:
-
-    + Small refactoring.  Removed separate 'parent' parameter in paraStyle.
-    + Don't profilerate text styles unnecessarily (#3371).
-      This change makes the writer create only as many temporary
-      text styles as are absolutely necessary. It also consolidates
-      adjacent nodes with the same style.
-
-  * Org reader (Albert Krewinkel):
-
-    + Allow short hand for single-line raw blocks (Albert Krewinkel,
-      #3366).  Single-line raw blocks can be given via `#+FORMAT: raw line`,
-      where `FORMAT` must be one of `latex`, `beamer`, `html`, or `texinfo`.
-    + Accept org-ref citations followed by commas (Albert Krewinkel).
-      Bugfix for an issue which, whenever the citation was immediately
-      followed by a comma, prevented correct parsing of org-ref citations.
-    + Ensure emphasis markup can be nested.  Nested emphasis markup (e.g.
-      `/*strong and emphasized*/`) was interpreted incorrectly in that the
-      inner markup was not recognized.
-    + Remove pipe char irking the haddock coverage tool (Albert Krewinkel).
-
-  * Docx reader: Empty header should be list of lists (Jesse Rosenthal).
-    In the past, the docx reader wrote an empty header as an empty list. It
-    should have the same width as a row (and be filled with empty cells).
-
-  * MediaWiki reader:
-
-    + Improved handling of display math (#3362).  Sometimes display math is
-      indented with more than one colon.  Previously we handled these cases
-      badly, generating definition lists and missing the math.
-    + Fix quotation mark parsing (#3336, tgkokk).  Change MediaWiki reader's
-      behavior when the smart option is parsed to match other readers'
-      behavior.
-
-  * Markdown reader:
-
-    + Fixed `-f markdown_github-hard_line_breaks+escaped_line_breaks`
-      (#3341).  Previously this did not properly enable escaped line breaks.
-    + Disallow space between inline code and attributes (#3326, #3323,
-      Mauro Bieg).
-
-  * DocBook5 writer: make id attribute xml:id, fixes #3329 (#3330, Mauro Bieg).
-
-  * Added some test cases for ODT reader (#3306, #3308, Hubert Plociniczak).
-
-  * LaTeX writer: allow tables with empty cells to count as "plain."
-    This addresses a problem of too-wide tables when empty cells
-    are used.  Thanks to Joost Kremers for reporting the issue.
-
-  * Org writer: prefix footnote numbers with `fn:` (Albert Krewinkel).
-    Unprefixed numbers where used by older org-mode versions, but are no
-    longer supported.
-
-  * HTML writer: don't process pars with empty RawInline, (#1040, #3327,
-    Mauro Bieg).
-
-  * Markdown writer: Fix display math with `--webtex` (#3298).
-
-  * Fix sample.lua so it properly handles raw blocks/inlines (#3358,
-    bumper314).
-
-  * Templates:
-
-    + default.latex: Moved geometry after hyperref (Václav Haisman).
-      Otherwise PDF sizes can be wrong in some circumstances.
-    + Copied a few changes from default.latex to default.beamer
-      (Wandmalfarbe).
-    + default.latex, default.beamer: Changed position of `\VerbatimNotes`
-      and `fancyvrb`.  This fixes hyperlinks on footnotes in documents
-      that contain verbatim in notes (#3361).  (Note: the beamer template
-      was updated to match the LaTeX template, but at this point verbatim
-      in notes seems not to work in beamer.)
-    + default.latex: Allow passing `microtypeoptions` to microtype
-      (Václav Haisman).
-    + default.latex: Add hyphen option to url package.
-    + default.docbook5: Fix namespace declarations (Mauro Bieg).
-
-  * Moved `make_osx_package.sh` to `osx/` directory.
-
-  * Travis continuous integration:
-
-    + Fix false positives with dist build.
-    + Speed improvements (Kolen Cheung, #3304, #3357).
-
-  * MANUAL.txt:
-
-    + Clarify that blank space is needed around footnotes (#3352).
-    + Fixed typo (#3351, Alexey Rogechev).
-    + Note that `--wrap=auto` does not work in HTML output.
-    + Default `--columns` width is 72, not 80.
-    + Fixed broken links (#3316, Kolen Cheung).
-    + Document usage of `@*` in nocite section (#3333, John Muccigrosso).
-
-  * INSTALL.md:
-
-    + Indent code so it's properly formatted (#3335, Bheesham Persaud).
-    + Added instructions for extracting binary from OSX, Windows packages.
-
-  * CONTRIBUTING.md: Describe labels currently used in issue tracker
-    (Albert Krewinkel).  The labels have changed over time, the list of
-    labels is updated to reflect the current set of labels used in the
-    issue tracker.
-
-  * Rearrange and extend badges in README (Albert Krewinkel, #3354)
-
-  * Bumped version bounds for dependencies.
-
-
-pandoc (1.19.1)
-
-  * Set `PANDOC_VERSION` environment variable for filters (#2640).
-    This allows filters to check the pandoc version that produced
-    the JSON they are receiving.
-
-  * Docx reader: Ensure one-row tables don't have header (#3285,
-    Jesse Rosenthal).  Tables in MS Word are set by default to have
-    special first-row formatting, which pandoc uses to determine whether
-    or not they have a header. This means that one-row tables will, by
-    default, have only a header -- which we imagine is not what people
-    want. This change ensures that a one-row table is not understood to
-    be a header only.  Note that this means that it is impossible to
-    produce a header-only table from docx, even though it is legal
-    pandoc. But we believe that in nearly all cases, it will be an
-    accidental (and unwelcome) result
-
-  * HTML reader:
-
-    + Fixed some bad regressions in HTML table parser (#3280).
-      This regression leads to the introduction of empty rows
-      in some circumstances.
-    + Understand `style=width:` as well as `width` in `col` (#3286).
-
-  * RST reader:
-
-    + Print warnings when keys, substitition, notes not found.
-      Previously the parsers failed and we got raw text.  Now we get a
-      link with an empty URL, or empty inlines in the case of a note or
-      substitution.
-
-    + Fix hyperlink aliases (#3283).
-
-  * Man writer: Ensure that periods are escaped at beginning of line
-    (#3270).
-
-  * LaTeX writer: Fix unnumbered headers when used with `--top-level`
-    (#3272, Albert Krewinkel).  Fix interaction of top-level divisions
-    `part` or `chapter` with unnumbered headers when emitting LaTeX.  Headers
-    are ensured to be written using stared commands (like `\subsection*{}`).
-
-  * LaTeX template: use comma not semicolon to separate keywords for
-    `pdfkeywords`.  Thanks to Wandmalfarbe.
-
-  * Markdown writer: Fixed incorrect word wrapping (#3277).  Previously pandoc
-    would sometimes wrap lines too early due to this bug.
-
-  * Text.Pandoc.Pretty:  Added `afterBreak` [API change].  This makes it
-    possible to insert escape codes for content that needs escaping at the
-    beginning of a line.
-
-  * Removed old MathMLInHTML.js from 2004, which should no longer
-    be needed for MathML with modern browsers.
-
-  * Fixed tests with dynamic linking (#2709).
-
-  * Makefile: Use stack instead of cabal for targets.  This is just
-    a convenience for developers.
-
-  * Fixed bash completion of filenames with space (#2749).
-
-  * MANUAL: improved documentation on how to create a custom `reference.docx`.
-
-  * Fix minor spelling typos in the manual (#3273, Anthony Geoghegan)
-
-pandoc (1.19)
-
-  * Changed resolution of filter paths.
-
-    + We now first treat the argument of `--filter` as a full (absolute
-      or relative) path, looking for a program there. If it's found, we
-      run it.
-    + If not, and if it is a simple program name or a relative path, we
-      try resolving it relative to `$DATADIR/filters`.
-    + If this fails, then we treat it as a program name and look in the
-      user's PATH.
-    + Removed a hardcoded '/' that may have caused problems with
-      Windows paths.
-
-    Previously if you did `--filter foo` and you had `foo` in your path and
-    also an executable `foo` in your working directory, the one in the path
-    would be used. Now the one in the working directory is used.
-
-    In addition, when you do `--filter foo/bar.hs`, pandoc will now find a
-    filter `$DATADIR/filters/foo/bar.hs` -- assuming there isn't a
-    `foo/bar.hs` relative to the working directory.
-
-  * Allow `file://` URIs as arguments (#3196). Also improved default reader
-    format detection. Previously with a URI ending in .md or .markdown,
-    pandoc would assume HTML input. Now it treats these as markdown.
-
-  * Allow to overwrite top-level division type heuristics (#3258,
-    Albert Krewinkel). Pandoc uses heuristics to determine the most
-    reasonable top-level division type when emitting LaTeX or
-    Docbook markup. It is now possible to overwrite this implicitly set
-    top-level division via the `top-level-division` command line parameter.
-
-  * Text.Pandoc.Options \[API changes\]:
-
-    + Removed `writerStandalone` field in `WriterOptions`, made
-      `writerTemplate` a `Maybe` value. Previously setting
-      `writerStandalone = True` did nothing unless a template was provided
-      in writerTemplate. Now a fragment will be generated if
-      `writerTemplate` is `Nothing`; otherwise, the specified template
-      will be used and standalone output generated.
-    + `Division` has been renamed `TopLevelDivision` (#3197). The
-      `Section`, `Chapter`, and `Part` constructors were renamed to
-      `TopLevelSection`, `TopLevelChapter`, and
-      `TopLevelPart`, respectively. An additional `TopLevelDefault`
-      constructor was added, which is now also the new default value of
-      the `writerTopLevelDivision` field in `WriterOptions`.
-
-  * Improved error if they give wrong arg to `--top-level-division`.
-
-  * Use new module from texmath to lookup MS font codepoints in Docx reader.
-    Removed unexported module Text.Pandoc.Readers.Docx.Fonts. Its code now
-    lives in texmath (0.9).
-
-  * DocBook reader: Fixed xref lookup (#3243). It previously only worked
-    when the qnames lacked the docbook namespace URI.
-
-  * HTML reader:
-
-    + Improved table parsing (#3027). We now check explicitly for non-1
-      rowspan or colspan attributes, and fail when we encounter them.
-      Previously we checked that each row had the same number of cells,
-      but that could be true even with rowspans/colspans. And there are
-      cases where it isn't true in tables that we can handle fine -- e.g.
-      when a tr element is empty. So now we just pad rows with empty cells
-      when needed.
-    + Treat `<math>` as MathML by default unless something else is
-      explicitly specified in xmlns. Provided it parses as MathML,
-      of course. Also fixed default which should be to inline math if no
-      display attribute is used.
-    + Only treat "a" element as link if it has href (#3226). Otherwise
-      treat as span.
-
-  * Docx reader (Jesse Rosenthal):
-
-    + Add a placeholder value for CHART. We wrap `[CHART]` in a
-      `<span class="chart">`. Note that it maps to inlines because, in
-      docx, anything in a drawing tag can be part of a larger paragraph.
-    + Be more specific in parsing images We not only want `w:drawing`,
-      because that could also include charts. Now we specify
-      `w:drawing/pic:pic`. This shouldn't change behavior at all, but it's
-      a first step toward allowing other sorts of drawing data as well.
-    + Abstract out function to avoid code repetition.
-    + Update tests for img title and alt (#3204).
-    + Handle Alt text and titles in images. We use the "description" field
-      as alt text and the "title" field as title. These can be accessed
-      through the "Format Picture" dialog in Word.
-    + Docx reader utils: handle empty namespace in `elemName`. Previously,
-      if given an empty namespace `(elemName ns "" "foo")` `elemName`
-      would output a QName with a `Just ""` namespace. This is never what
-      we want. Now we output a `Nothing`. If someone *does* want a
-      `Just ""` in the namespace, they can enter the QName
-      value explicitly.
-
-  * ODT reader/writer:
-
-    + Inline code when text has a special style (Hubert Plociniczak). When
-      a piece of text has a text `Source_Text` then we assume that this is
-      a piece of the document that represents a code that needs to
-      be inlined. Adapted the writer to also reflect that change.
-      Previously it was just writing a 'preformatted' text using a
-      non-distinguishable font style. Code blocks are still not recognized
-      by the ODT reader. That's a separate issue.
-    + Infer table's caption from the paragraph (#3224,
-      Hubert Plociniczak). ODT's reader always put empty captions for the
-      parsed tables. This commit
-
-        1.  checks paragraphs that follow the table definition
-        2.  treats specially a paragraph with a style named 'Table'
-        3.  does some postprocessing of the paragraphs that combines tables
-            followed immediately by captions
-
-      The ODT writer used the `TableCaption` style for the caption
-      paragraph.  This commit follows the OpenOffice approach which allows
-      for appending captions to table but uses a built-in style named
-      `Table` instead of `TableCaption`. Users of a custom `reference.odt`
-      should change the style's name from `TableCaption` to `Table`.
-
-  * ODT reader: Infer tables' header props from rows (#3199,
-    Hubert Plociniczak). ODT reader simply provided an empty header list
-    which meant that the contents of the whole table, even if not empty, was
-    simply ignored. While we still do not infer headers we at least have to
-    provide default properties of columns.
-
-  * Markdown reader:
-
-    +   Allow reference link labels starting with `@...` if `citations`
-        extension disabled (#3209). Example: in
-
-            \[link text\]\[@a\]
-
-        `link text` isn't hyperlinked because `[@a]` is parsed as
-        a citation. Previously this happened whether or not the `citations`
-        extension was enabled. Now it happens only if the `citations`
-        extension is enabled.
-    +   Allow alignments to be specified in Markdown grid tables. For
-        example,
-
-            +-------+---------------+--------------------+
-            | Right    | Left                 | Centered |
-            +=========:+:=================+:=============:+
-            | Bananas | $1.34         | built-in wrapper |
-            +-------+---------------+--------------------+
-
-    +   Allow Small Caps elements to be created using bracketed spans (as
-        they already can be using HTML-syntax spans) (#3191, Kolen Cheung).
-
-  * LaTeX reader:
-
-    + Don't treat `\vspace` and `\hspace` as block commands (#3256).
-      Fixed an error which came up, for example, with `\vspace` inside
-      a caption. (Captions expect inlines.)
-    + Improved table handling. We can now parse all of the tables emitted
-      by pandoc in our tests. The only thing we don't get yet are
-      alignments and column widths in more complex tables. See #2669.
-    + Limited support for minipage.
-    + Allow for `[]`s inside LaTeX optional args. Fixes cases like:
-    + Handle BVerbatim from fancyvrb (#3203).
-    + Handle hungarumlaut (#3201).
-    + Allow beamer-style `<...>` options in raw LaTeX (also in Markdown)
-      (#3184). This allows use of things like `\only<2,3>{my content}` in
-      Markdown that is going to be converted to beamer.
-
-  * Use pre-wrap for code in dzslides template (Nicolas Porcel). Otherwise
-    overly long code will appear on every slide.
-
-  * Org reader (Albert Krewinkel):
-
-    +   Respect column width settings (#3246). Table column properties can
-        optionally specify a column's width with which it is displayed in
-        the buffer. Some exporters, notably the ODT exporter in org-mode
-        v9.0, use these values to calculate relative column widths. The org
-        reader now implements the same behavior. Note that the org-mode
-        LaTeX and HTML exporters in Emacs don't support this feature yet,
-        which should be kept in mind by users who use the column
-        widths parameters.
-    +   Allow HTML attribs on non-figure images (#3222). Images which are
-        the only element in a paragraph can still be given HTML attributes,
-        even if the image does not have a caption and is hence not a figure.
-        The following will add set the `width` attribute of the image to
-        `50%`:
-
-            +ATTR\_HTML: :width 50%
-            =======================
-
-            \[\[file:image.jpg\]\]
-
-    +   Support `ATTR_HTML` for special blocks (#3182). Special
-        blocks (i.e. blocks with unrecognized names) can be prefixed with an
-        `ATTR_HTML` block attribute. The attributes defined in that
-        meta-directive are added to the `Div` which is used to represent the
-        special block.
-    +   Support the `todo` export option. The `todo` export option allows to
-        toggle the inclusion of TODO keywords in the output. Setting this to
-        `nil` causes TODO keywords to be dropped from headlines. The default
-        is to include the keywords.
-    +   Add support for todo-markers. Headlines can have optional
-        todo-markers which can be controlled via the `#+TODO`, `#+SEQ_TODO`,
-        or `#+TYP_TODO` meta directive. Multiple such directives can be
-        given, each adding a new set of recognized todo-markers. If no
-        custom todo-markers are defined, the default `TODO` and `DONE`
-        markers are used. Todo-markers are conceptually separate from
-        headline text and are hence excluded when autogenerating
-        headline IDs. The markers are rendered as spans and labelled with
-        two classes: One class is the markers name, the other signals the
-        todo-state of the marker (either `todo` or `done`).
-
-  * LaTeX writer:
-
-    + Use `\autocites*` when "suppress-author" citation used.
-    + Ensure that simple tables have simple cells (#2666). If cells
-      contain more than a single Plain or Para, then we need to set
-      nonzero widths and put contents into minipages.
-    + Remove invalid inlines in sections (#3218, Hubert Plociniczak).
-
-  * Markdown writer:
-
-    + Fix calculation of column widths for aligned multiline tables
-      (#1911, Björn Peemöller). This also fixes excessive CPU and memory
-      usage for tables when `--columns` is set in such a way that cells
-      must be very tiny. Now cells are guaranteed to be big enough so that
-      single words don't need to line break, even if this pushes the line
-      length above the column width.
-    + Use bracketed form for native spans when `bracketed_spans`
-      enabled (#3229).
-    + Fixed inconsistent spacing issue (#3232). Previously a tight bullet
-      sublist got rendered with a blank line after, while a tight ordered
-      sublist did not. Now we don't get the blank line in either case.
-    + Fix escaping of spaces in super/subscript (#3225). Previously two
-      backslashes were inserted, which gave a literal backslash.
-    + Adjust widths in Markdown grid tables so that they match
-      on round-trip.
-
-  * Docx writer:
-
-    + Give full detail when there are errors converting tex math.
-    + Handle title text in images (Jesse Rosenthal). We already handled
-      alt text. This just puts the image "title" into the docx
-      "title" attr.
-    + Fixed XML markup for empty cells (#3238). Previously the Compact
-      style wasn't being applied properly to empty cells.
-
-  * HTML writer:
-
-    + Updated `renderHtml` import from blaze-html.
-
-  * Text.Pandoc.Pretty:
-
-    + Fixed some bugs that caused blank lines in tables (#3251). The bugs
-      caused spurious blank lines in grid tables when we had things like
-      `blankline $$ blankline`.
-    + Add exported function `minOffet` \[API change\] (Björn Peemöller).
-    + Added error message for illegal call to `block` (Björn Peemöller).
-
-  * Text.Pandoc.Shared:
-
-    + Put `warn` in MonadIO.
-    + `fetchItem`: Better handling of protocol-relative URL (#2635). If
-      URL starts with `//` and there is no "base URL" (as there would be
-      if a URL were used on the command line), then default to http:.
-
-  * Export Text.Pandoc.getDefaultExtensions \[API change\] (#3178).
-
-  * In --version, trap error in `getAppUserDataDirectory` (#3241). This
-    fixes a crash with `pandoc --version` on unusual systems with no real
-    user (e.g. SQL Server 2016).
-
-  * Added weigh-pandoc for memory usage diagnostics (#3169).
-
-  * Use correct mime types for woff and woff2 (#3228).
-
-  * Remove make\_travis\_yml.hs (#3235, Kolen Cheung).
-
-  * changelog: Moved an item that was misplaced in the 1.17.2 section to the
-    1.18 section where it belongs.
-
-  * CONTRIBUTING.md: minor change in wording and punctuation (#3252,
-    Kolen Cheung).
-
-  * Further revisions to manual for `--version` changes (#3244).
-
-
-pandoc (1.18)
-
-  * Added `--list-input-formats`, `--list-output-formats`,
-    `--list-extensions`, `--list-highlight-languages`, and
-    `--list-highlight-styles` (#3173).  Removed list of highlighting
-    languages from `--version` output.  Removed list of input and output
-    formats from default `--help` output.
-
-  * Added `--reference-location=block|section|document` option
-    (Jesse Rosenthal).  This determines whether Markdown link references
-    and footnotes are placed at the end of the document, the end of the
-    section, or the end of the top-level block.
-
-  * Added `--top-level-division=section|chapter|part` (Albert Krewinkel).
-    This determines what a level-1 header corresponds to in LaTeX,
-    ConTeXt, DocBook, and TEI output.  The default is `section`.
-    The `--chapters` option has been deprecated in favor of
-    `--top-level-division=chapter`.
-
-  * Added `LineBlock` constructor for `Block` (Albert Krewinkel).  This
-    is now used in parsing RST and Markdown line blocks, DocBook
-    `linegroup`/`line` combinations, and Org-mode `VERSE` blocks.
-    Previously `Para` blocks with hard linebreaks were used.  `LineBlock`s
-    are handled specially in the following ouput formats: AsciiDoc
-    (as `[verse]` blocks), ConTeXt (`\startlines`/`\endlines`),
-    HTML (`div` with a style), Markdown (line blocks if `line_blocks`
-    is enabled), Org-mode (`VERSE` blocks), RST (line blocks). In
-    other output formats, a paragraph with hard linebreaks is emitted.
-
-  * Allow binary formats to be written to stdout (but not to tty) (#2677).
-    Only works on posix, since we use the unix library to check whether
-    output is to tty.  On Windows, pandoc works as before and always requires
-    an output file parameter for binary formats.
-
-  * Changed JSON output format (Jesse Rosenthal).  Previously we used
-    generically generated JSON, but this was subject to change depending
-    on the version of aeson pandoc was compiled with.  To ensure stability,
-    we switched to using manually written ToJSON and FromJSON
-    instances, and encoding the API version.  **Note:**  pandoc filter
-    libraries will need to be revised to handle the format change.
-    Here is a summary of the essential changes:
-
-    + The toplevel JSON format is now `{"pandoc-api-version" :
-      [MAJ, MIN, REV], "meta" : META, "blocks": BLOCKS}`
-      instead of `[{"unMeta": META}, [BLOCKS]]`.
-      Decoding fails if the major and minor version numbers don't
-      match.
-    + Leaf nodes no longer have an empty array for their "c" value.
-      Thus, for example, a `Space` is encoded as `{"t":"Space"}`
-      rather than `{"t":"Space","c":[]}` as before.
-
-  * Removed `tests/Tests/Arbitrary.hs` and added a `Text.Pandoc.Arbitrary`
-    module to pandoc-types (Jesse Rosenthal).  This makes it easier
-    to use QuickCheck with pandoc types outside of pandoc itself.
-
-  * Add `bracketed_spans` Markdown extension, enabled by default
-    in pandoc `markdown`.  This allows you to create a native span
-    using this syntax:  `[Here is my span]{#id .class key="val"}`.
-
-  * Added `angle_brackets_escapable` Markdown extension (#2846).
-    This is needed because github flavored Markdown has a slightly
-    different set of escapable symbols than original Markdown;
-    it includes angle brackets.
-
-  * Export `Text.Pandoc.Error` in `Text.Pandoc` [API change].
-
-  * Print highlighting-kate version in `--version`.
-
-  * `Text.Pandoc.Options`:
-
-    + `Extension` has new constructors `Ext_brackted_spans` and
-      `Ext_angle_brackets_escapable` [API change].
-    + Added `ReferenceLocation` type [API change] (Jesse Rosenthal).
-    + Added `writerReferenceLocation` field to `WriterOptions` (Jesse
-      Rosenthal).
-
-  * `--filter`:  we now check `$DATADIR/filters` for filters before
-    looking in the path (#3127, Jesse Rosenthal, thanks to Jakob
-    Voß for the idea).  Filters placed in this directory need not
-    be executable; if the extension is `.hs`, `.php`, `.pl`, `.js`,
-    or `.rb`, pandoc will run the right interpreter.
-
-  * For `--webtex`, replace deprecated Google Chart API by CodeCogs as
-    default (Kolen Cheung).
-
-  * Removed `raw_tex` extension from `markdown_mmd` defaults (Kolen Cheung).
-
-  * Execute .js filters with node (Jakob Voß).
-
-  * Textile reader:
-
-    + Support `bc..` extended code blocks (#3037).  Also, remove trailing
-      newline in code blocks (consistently with Markdown reader).
-    + Improve table parsing.  We now handle cell and row attributes, mostly
-      by skipping them.  However, alignments are now handled properly.
-      Since in pandoc alignment is per-column, not per-cell, we
-      try to devine column alignments from cell alignments.
-      Table captions are also now parsed, and textile indicators
-      for thead and tfoot no longer cause parse failure.  (However,
-      a row designated as tfoot will just be a regular row in pandoc.)
-    + Improve definition list parsing.  We now allow multiple terms
-      (which we concatenate with linebreaks).  An exponential parsing
-      bug (#3020) is also fixed.
-    + Disallow empty URL in explicit link (#3036).
-
-  * RST reader:
-
-    + Use Div instead of BlockQuote for admonitions (#3031).
-      The Div has class `admonition` and (if relevant) one of the
-      following:  `attention`, `caution`, `danger`, `error`, `hint`,
-      `important`, `note`, `tip`, `warning`.  **Note:** This will change
-      the rendering of some RST documents!  The word ("Warning", "Attention",
-      etc.) is no longer added; that must be done with CSS or a filter.
-    + A Div is now used for `sidebar` as well.
-    + Skip whitespace before note (Jesse Rosenthal, #3163).  RST requires a
-      space before a footnote marker. We discard those spaces so that footnotes
-      will be adjacent to the text that comes before it. This is in line with
-      what rst2latex does.
-    + Allow empty lines when parsing line blocks (Albert Krewinkel).
-
-  * Markdown reader:
-
-    + Allow empty lines when parsing line blocks (Albert Krewinkel).
-    + Allow attributes on autolinks (#3183, Daniele D'Orazio).
-
-  * LaTeX reader:
-
-    + More robust parsing of unknown environments (#3026).
-      We no longer fail on things like `^` inside options for tikz.
-    + Be more forgiving of non-standard characters, e.g. `^` outside of math.
-      Some custom environments give these a meaning, so we should try not to
-      fall over when we encounter them.
-    + Drop duplicate `*` in bibtexKeyChars (Albert Krewinkel)
-
-  * MediaWiki reader:
-
-    + Fix for unquoted attribute values in mediawiki tables (#3053).
-      Previously an unquoted attribute value in a table row
-      could cause parsing problems.
-    + Improved treatment of verbatim constructions (#3055).
-      Previously these yielded strings of alternating Code and Space
-      elements; we now incorporate the spaces into the Code.  Emphasis
-      etc. is still possible inside these.
-    + Properly interpret XML tags in pre environments (#3042).  They are meant
-      to be interpreted as literal text.
-
-  * EPUB reader:  don't add root path to data: URIs (#3150).
-    Thanks to @lep for the bug report and patch.
-
-  * Org reader (Albert Krewinkel):
-
-    + Preserve indentation of verse lines (#3064).  Leading spaces in verse
-      lines are converted to non-breaking spaces, so indentation is preserved.
-    + Ensure image sources are proper links.  Image sources as those in plain
-      images, image links, or figures, must be proper URIs or relative file
-      paths to be recognized as images.  This restriction is now enforced
-      for all image sources.  This also fixes the reader's usage of uncleaned
-      image sources, leading to `file:` prefixes not being deleted from
-      figure images.  Thanks to @bsag for noticing this bug.
-    + Trim verse lines properly (Albert Krewinkel).
-    + Extract meta parsing code to module.  Parsing of meta-data is well
-      separable from other block parsing tasks.  Moving into new module to
-      get small files and clearly arranged code.
-    + Read markup only for special meta keys.  Most meta-keys should be read
-      as normal string values, only a few are interpreted as marked-up text.
-    + Allow multiple, comma-separated authors.  Multiple authors can be
-      specified in the `#+AUTHOR` meta line if they are given as a
-      comma-separated list.
-    + Give precedence to later meta lines.  The last meta-line of any given
-      type is the significant line.  Previously the value of the first line
-      was kept, even if more lines of the same type were encounterd.
-    + Read LaTeX_header as header-includes.  LaTeX-specific header commands
-      can be defined in `#+LaTeX_header` lines.  They are parsed as
-      format-specific inlines to ensure that they will only show up in LaTeX
-      output.
-    + Set documentclass meta from LaTeX_class.
-    + Set classoption meta from LaTeX_class_options.
-    + Read HTML_head as header-includes.  HTML-specific head content can be
-      defined in `#+HTML_head` lines.  They are parsed as format-specific
-      inlines to ensure that they will only show up in HTML output.
-    + Respect `author` export option.  The `author` option controls whether
-      the author should be included in the final markup.  Setting
-      `#+OPTIONS: author:nil` will drop the author from the final meta-data
-      output.
-    + Respect `email` export option.  The `email` option controls whether the
-      email meta-field should be included in the final markup. Setting
-      `#+OPTIONS: email:nil` will drop the email field from the final
-      meta-data output.
-    + Respect `creator` export option.  The `creator` option controls whether
-      the creator meta-field should be included in the final markup.  Setting
-      `#+OPTIONS: creator:nil` will drop the creator field from the final
-      meta-data output.  Org-mode recognizes the special value `comment` for
-      this field, causing the creator to be included in a comment.  This is
-      difficult to translate to Pandoc internals and is hence interpreted the
-      same as other truish values (i.e. the meta field is kept if it's
-      present).
-    + Respect unnumbered header property (#3095).  Sections the `unnumbered`
-      property should, as the name implies, be excluded from the automatic
-      numbering of section provided by some output formats.  The Pandoc
-      convention for this is to add an "unnumbered" class to the header.  The
-      reader treats properties as key-value pairs per default, so a special
-      case is added to translate the above property to a class instead.
-    + Allow figure with empty caption (Albert Krewinkel, #3161).
-      A `#+CAPTION` attribute before an image is enough to turn an image into
-      a figure. This wasn't the case because the `parseFromString` function,
-      which processes the caption value, would fail on empty values. Adding
-      a newline character to the caption value fixes this.
-
-  * Docx reader:
-
-    + Use XML convenience functions (Jesse Rosenthal).
-      The functions `isElem` and `elemName` (defined in Docx/Util.hs) make
-      the code a lot cleaner than the original XML.Light functions, but they
-      had been used inconsistently. This puts them in wherever applicable.
-    + Handle anchor spans with content in headers.  Previously, we would only
-      be able to figure out internal links to a header in a docx if the
-      anchor span was empty. We change that to read the inlines out of the
-      first anchor span in a header.
-    + Let headers use exisiting id.  Previously we always generated an id for
-      headers (since they wouldn't bring one from Docx). Now we let it use an
-      existing one if possible. This should allow us to recurs through anchor
-      spans.
-    + Use all anchor spans for header ids.  Previously we only used the first
-      anchor span to affect header ids. This allows us to use all the anchor
-      spans in a header, whether they're nested or not (#3088).
-    + Test for nested anchor spans in header.  This ensures that anchor spans
-      in header with content (or with other anchor spans inside) will resolve
-      to links to a header id properly.
-
-  * ODT reader (Hubert Plociniczak)
-
-    + Include list's starting value.  Previously the starting value of
-      the lists' items has been hardcoded to 1. In reality ODT's list
-      style definition can provide a new starting value in one of its
-      attributes.
-    + Infer caption from the text following the image.
-      Frame can contain other frames with the text boxes.
-    + Add `fig:` to title for Image with a caption (as expected
-      by pandoc's writers).
-    + Basic support for images in ODT documents.
-    + Don't duplicate text for anchors (#3143).  When creating an anchor
-      element we were adding its representation as well as the original
-      content, leading to text duplication.
-
-  * DocBook writer:
-
-    + Include an anchor element when a div or span has an id (#3102).
-      Note that DocBook does not have a class attribute, but at least this
-      provides an anchor for internal links.
-
-  * LaTeX writer:
-
-    + Don't use * for unnumbered paragraph, subparagraph.  The starred
-      variants don't exist.  This helps with part of #3058...it gets rid of
-      the spurious `*`s.  But we still have numbers on the 4th and 5th level
-      headers.
-    + Properly escape backticks in verbatim (#3121, Jesse Rosenthal).
-      Otherwise they can cause unintended ligatures like `` ?` ``.
-    + Handle NARRAOW NO-BREAK SPACE into LaTeX (Vaclav Zeman) as `\,`.
-    + Don't include `[htbp]` placement for figures (#3103, Václav Haisman).
-      This allows figure placement defaults to be changed by the user
-      in the template.
-
-  * HTML writer (slide show formats): In slide shows, don't change slide title
-    to level 1 header (#2221).
-
-  * TEI writer: remove heuristic to detect book template (Albert Krewinkel).
-    TEI doesn't have `<book>` elements but only generic `<divN>` division
-    elements. Checking the template for a trailing `</book>` is nonsensical.
-
-  * MediaWiki writer:  transform filename with underscores in images (#3052).
-    `foo bar.jpg` becomes `foo_bar.jpg`. This was already done
-    for internal links, but it also needs to happen for images.
-
-  * ICML writer: replace partial function (!!) in table handling (#3175,
-    Mauro Bieg).
-
-  * Man writer: allow section numbers that are not a single digit (#3089).
-
-  * AsciiDoc writer: avoid unnecessary use of "unconstrained" emphasis
-    (#3068).  In AsciiDoc, you must use a special form of emphasis
-    (double `__`) for intraword emphasis.  Pandoc was previously using
-    this more than necessary.
-
-  * EPUB writer:  use stringify instead of plain writer for metadata
-    (#3066).  This means that underscores won't be used for emphasis,
-    or CAPS for bold.  The metadata fields will just have unadorned
-    text.
-
-  * Docx Writer:
-
-    + Implement user-defined styles (Jesse Rosenthal).  Divs and Spans
-      with a `custom-style` key in the attributes will apply the corresponding
-      key to the contained blocks or inlines.
-    + Add ReaderT env to the docx writer (Jesse Rosenthal).
-    + Clean up and streamline RTL behavior (Jesse Rosenthal, #3140).
-      You can set `dir: rtl` in YAML metadata, or use `-M dir=rtl`
-      on the command line.  For finer-grained control, you can set
-      the `dir` attribute in Div or Span elements.
-
-  * Org writer (Albert Krewinkel):
-
-    + Remove blank line after figure caption.  Org-mode only treats an image
-      as a figure if it is directly preceded by a caption.
-    + Ensure blank line after figure.  An Org-mode figure should be surrounded
-      by blank lines.  The figure would be recognized regardless, but images
-      in the following line would unintentionally be treated as figures as
-      well.
-    + Ensure link targets are paths or URLs.  Org-mode treats links as
-      document internal searches unless the link target looks like a URL or
-      file path, either relative or absolute.  This change ensures that this
-      is always the case.
-    + Translate language identifiers.  Pandoc and Org-mode use different
-      programming language identifiers.  An additional translation between
-      those identifiers is added to avoid unexpected behavior.  This fixes a
-      problem where language specific source code would sometimes be output
-      as example code.
-    + Drop space before footnote markers (Albert Krewinkel, #3162).
-      The writer no longer adds an extra space before footnote markers.
-
-  * Markdown writer:
-
-    + Don't emit HTML for tables unless `raw_html` extension is set (#3154).
-      Emit `[TABLE]` if no suitable table formats are enabled and raw HTML
-      is disabled.
-    + Check for the `raw_html` extension before emiting a raw HTML block.
-    + Abstract out note/ref function (Jesse Rosenthal).
-    + Add ReaderT monad for environment variables (Jesse Rosenthal).
-
-  * HTML, EPUB, slidy, revealjs templates: Use `<p>` instead of `<h1>` for
-    subtitle, author, date (#3119).  Note that, as a result of this change,
-    authors may need to update CSS.
-
-  * revealjs template:  Added `notes-server` option
-    (jgm/pandoc-templates#212, Yoan Blanc).
-
-  * Beamer template:
-
-    + Restore whitespace between paragraphs. This was
-      a regression in the last release (jgm/pandoc-templates#207).
-    + Added `themeoptions` variable (Carsten Gips).
-    + Added `beamerarticle` variable.  This causes the `beamerarticle`
-      package to be loaded in beamer, to produce an article from beamer
-      slides.  (Carsten Gips)
-    + Added support for `fontfamilies` structured variable
-      (Artem Klevtsov).
-    + Added hypersetup options (Jake Zimmerman).
-
-  * LaTeX template:
-
-    + Added dummy definition for `\institute`.
-      This isn't a standard command, and we want to avoid a crash when
-      `institute` is used with the default template.
-    + Define default figure placement (Václav Haisman), since pandoc
-      no longer includes `[htbp]` for figures.  Users with custom templates
-      will want to add this. See #3103.
-    + Use footnote package to fix notes in tables (jgm/pandoc-templates#208,
-      Václav Haisman).
-
-  * Moved template compiling/rendering code to a separate library.
-    `doctemplates`.  This allows the pandoc templating system to be
-    used independently.
-
-  * Text.Pandoc.Error: Fix out of index error in `handleError`
-    (Matthew Pickering).  The fix is to not try to show the exact line when
-    it would cause an out-of-bounds error as a result of included files.
-
-  * Text.Pandoc.Shared: Add `linesToBlock` function (Albert Krewinkel).
-
-  * Text.Pandoc.Parsing.emailAddress: tighten up parsing of email
-    addresses.  Technically `**@user` is a valid email address, but if we
-    allow things like this, we get bad results in markdown flavors
-    that autolink raw email addresses (see #2940).  So we exclude a few
-    valid email addresses in order to avoid these more common bad cases.
-
-  * Text.Pandoc.PDF:  Don't crash with nonexistent image (#3100).  Instead,
-    emit the alt text, emphasized.  This accords with what the ODT writer
-    currently does.  The user will still get a warning about a nonexistent
-    image.
-
-  * Fix example in API documentation (#3176, Thomas Weißschuh).
-
-  * Tell where to get tarball in INSTALL (#3062).
-
-  * Rename README to MANUAL.txt and add GitHub-friendly README.md
-    (Albert Krewinkel, Kolen Cheung).
-
-  * Replace COPYING with Markdown version COPYING.md from GNU (Kolen Cheung).
-
-  * MANUAL.txt:
-
-    + Put note on structured vars in separate paragraph (#2148, Albert
-      Krewinkel).  Make it clearer that structured author variables require a
-      custom template
-    + Note that `--katex` works best with `html5` (#3077).
-    + Fix the LaTeX and EPUB links in manual (Morton Fox).
-    + Document `biblio-title` variable.
-
-  * Improve spacing of footnotes in `--help` output (Waldir Pimenta).
-
-  * Update KaTeX to v0.6.0 (Kolen Cheung).
-
-  * Allow latest dependencies.
-
-  * Use texmath 0.8.6.6 (#3040).
-
-  * Allow http-client 0.4.30, which is the version in stackage lts.
-    Previously we required 0.5.
-    Remove CPP conditionals for earlier versions.
-
-  * Remove support for GHC < 7.8 (Jesse Rosenthal).
-
-    + Remove Compat.Monoid.
-    + Remove an inline monad compatibility macro.
-    + Remove Text.Pandoc.Compat.Except.
-    + Remove directory compat.
-    + Change constraint on mtl.
-    + Remove unnecessary CPP condition in UTF8.
-    + Bump base lower bound to 4.7.
-    + Remove 7.6 build from .travis.yaml.
-    + Bump supported ghc version in CONTRIBUTING.md.
-    + Add note about GHC version support to INSTALL.
-    + Remove GHC 7.6 from list of tested versions (Albert Krewinkel).
-    + Remove TagSoup compat.
-    + Add EOL note to time compat module.  Because time 1.4 is a boot library
-      for GHC 7.8, we will support the compatibility module as long as we
-      support 7.8. But we should be clear about when we will no longer need
-      it.
-    + Remove blaze-html CPP conditional.
-    + Remove unnecessary CPP in custom Prelude.
-
-pandoc (1.17.2)
-
-  * Added Zim Wiki writer, template and tests. `zimwiki` is now
-    a valid output format. (Alex Ivkin)
-
-  * Changed email-obfuscation default to no obfuscation (#2988).
-    + `writerEmailObfuscation` in `defaultWriterOptions` is now
-      `NoObfuscation`.
-    + the default for the command-line `--email-obfuscation` option is
-      now `none`.
-
-  * Docbook writer: Declare xlink namespace in Docbook5 output (Ivo Clarysse).
-
-  * Org writer:
-
-    + Support arbitrary raw inlines (Albert Krewinkel).
-      Org mode allows arbitrary raw inlines ("export snippets" in Emacs
-      parlance) to be included as `@@format:raw foreign format text@@`.
-    + Improve Div handling (Albert Krewinkel).  Div blocks handling is
-      changed to make the output look more like idiomatic org mode:
-        - Div-wrapped content is output as-is if the div's attribute is the
-          null attribute.
-        - Div containers with an id but neither classes nor key-value pairs
-          are unwrapped and the id is added as an anchor.
-        - Divs with classes associated with greater block elements are
-          wrapped in a `#+BEGIN`...`#+END` block.
-        - The old behavior for Divs with more complex attributes is kept.
-
-  * HTML writer:
-
-    + Better support for raw LaTeX environments (#2758).
-      Previously we just passed all raw TeX through when MathJax was used for
-      HTML math.  This passed through too much.  With this patch, only raw
-      LaTeX environments that MathJax can handle get passed through.
-      This patch also causes raw LaTeX environments to be treated
-      as math, when possible, with MathML and WebTeX output.
-
-  * Markdown writer:  use raw HTML for simple, pipe tables with linebreaks
-    (#2993).  Markdown line breaks involve a newline, and simple and pipe
-    tables can't contain one.
-
-  * Make --webtex work with the Markdown writer (#1177).
-    This is a convenient option for people using
-    websites whose Markdown flavors don't provide for math.
-
-  * Docx writer:
-
-    + Set paragraph to FirstPara after display math (Jesse Rosenthal).
-      We treat display math like block quotes, and apply FirstParagraph style
-      to paragraphs that follow them. These can be styled as the user
-      wishes. (But, when the user is using indentation, this allows for
-      paragraphs to continue after display math without indentation.)
-    + Use actual creation time as doc prop (Jesse Rosenthal).
-      Previously, we had used the user-supplied date, if available, for Word's
-      document creation metadata. This could lead to weird results, as in
-      cases where the user post-dates a document (so the modification might be
-      prior to the creation). Here we use the actual computer time to set the
-      document creation.
-
-  * LaTeX writer:
-
-    + Don't URI-escape image source (#2825).  Usually this is a local file,
-      and replacing spaces with `%20` ruins things.
-    + Allow 'standout' as a beamer frame option (#3007).
-      `## Slide title {.standout}`.
-
-  * RST reader: Fixed links with no explicit link text.  The link
-    `` `<foo>`_ `` should have `foo` as both its link text and its URL.
-    See RST spec at <http://docutils.sourceforge.net/docs/ref/rst/restructuredtext.html#embedded-uris-and-aliases>
-    Closes Debian #828167 -- reported by Christian Heller.
-
-  * Textile reader:
-
-    + Fixed attributes (#2984).  Attributes can't be followed by
-      a space.  So, `_(class)emph_` but `_(noclass) emph_`.
-    + Fixed exponential parsing bug (#3020).
-    + Fix overly aggressive interpretation as images (#2998).
-      Spaces are not allowed in the image URL in textile.
-
-  * LaTeX reader:
-
-    + Fix `\cite` so it is a NormalCitation not AuthorInText.
-    + Strip off double quotes around image source if present (#2825).
-      Avoids interpreting these as part of the literal filename.
-
-  * Org reader:
-
-    + Add semicolon to list of special chars (Albert Krewinkel)
-      Semicolons are used as special characters in citations syntax.  This
-      ensures the correct parsing of Pandoc-style citations: `[prefix; @key;
-      suffix]`.  Previously, parsing would have failed unless there was a space
-      or other special character as the last <prefix> character.
-    + Add support for "Berkeley-style" cites (Albert Krewinkel, #1978).
-      A specification for an official Org-mode citation syntax was drafted by
-      Richard Lawrence and enhanced with the help of others on the orgmode
-      mailing list.  Basic support for this citation style is added to the
-      reader.
-    + Support arbitrary raw inlines (Albert Krewinkel).
-      Org mode allows arbitrary raw inlines ("export snippets" in Emacs
-      parlance) to be included as `@@format:raw foreign format text@@`.
-    + Remove partial functions (Albert Krewinkel, #2991).
-      Partial functions like `head` lead to avoidable errors and should be
-      avoided.  They are replaced with total functions.
-    + Support figure labels (Albert Krewinkel, #2496, #2999).
-      Figure labels given as `#+LABEL: thelabel` are used as the ID of the
-      respective image.  This allows e.g. the LaTeX to add proper `\label`
-      markup.
-    + Improve tag and properties type safety (Albert Krewinkel).
-      Specific newtype definitions are used to replace stringly typing of tags
-      and properties.  Type safety is increased while readability is improved.
-    + Parse as headlines, convert to blocks (Albert Krewinkel).
-      Emacs org-mode is based on outline-mode, which treats documents as trees
-      with headlines are nodes.  The reader is refactored to parse into a
-      similar tree structure.  This simplifies transformations acting on
-      document (sub-)trees.
-    * Refactor comment tree handling (Albert Krewinkel).
-      Comment trees were handled after parsing, as pattern matching on lists
-      is easier than matching on sequences.  The new method of reading
-      documents as trees allows for more elegant subtree removal.
-    * Support archived trees export options (Albert Krewinkel).
-      Handling of archived trees can be modified using the `arch` option.
-      Archived trees are either dropped, exported completely, or collapsed to
-      include just the header when the `arch` option is nil, non-nil, or
-      `headline`, respectively.
-    * Put export setting parser into module (Albert Krewinkel).
-      Export option parsing is distinct enough from general block parsing to
-      justify putting it into a separate module.
-    * Support headline levels export setting (Albert Krewinkel).
-      The depths of headlines can be modified using the `H` option.  Deeper
-      headlines will be converted to lists.
-    * Replace ugly code with view pattern (Albert Krewinkel).
-      Some less-than-smart code required a pragma switching of overlapping
-      pattern warnings in order to compile seamlessly.  Using view patterns
-      makes the code easier to read and also doesn't require overlapping
-      pattern checks to be disabled.
-    * Fix parsing of verbatim inlines (Albert Krewinkel, #3016).
-      Org rules for allowed characters before or after markup chars were not
-      checked for verbatim text.  This resultet in wrong parsing outcomes of
-      if the verbatim text contained e.g. space enclosed markup characters as
-      part of the text (`=is_substr = True=`).  Forcing the parser to update
-      the positions of allowed/forbidden markup border characters fixes this.
-
-  * LaTeX template: fix for obscure hyperref/xelatex issue.
-    Here's a minimal case:
-
-        \documentclass[]{article}
-        \usepackage{hyperref}
-        \begin{document}
-        \section{\%á}
-        \end{document}
-
-    Without this change, this fails on the second invocation of xelatex.
-    This affects inputs this like `# %á` with pdf output via xelatex.
-
-  * trypandoc:  call results 'html' instead of 'result'.
-    This is for better compatibility with babelmark2.
-
-  * Document MultiMarkdown as input/output format (Albert Krewinkel, #2973).
-    MultiMarkdown was only mentioned as a supported Markdown dialect but not
-    as a possible input or output format.  A brief mention is added
-    everywhere the other supported markdown dialects are mentioned.
-
-  * Document Org mode as a format containing raw HTML (Albert Krewinkel)
-    Raw HTML is kept when the output format is Emacs Org mode.
-
-  * Implement `RawInline` and `RawBlock` in sample lua custom writer (#2985).
-
-  * Text.Pandoc.Shared:
-
-    + Introduce blocksToInlines function (Jesse Rosenthal).
-      This is a lossy function for converting `[Block] -> [Inline]`. Its main
-      use, at the moment, is for docx comments, which can contain arbitrary
-      blocks (except for footnotes), but which will be converted to spans.
-      This is, at the moment, pretty useless for everything but the basic
-      `Para` and `Plain` comments. It can be improved, but the docx reader
-      should probably emit a warning if the comment contains more than this.
-    + Add BlockQuote to blocksToInlines (Jesse Rosenthal).
-    + Add further formats for `normalizeDate` (Jesse Rosenthal).
-      We want to avoid illegal dates -- in particular years with greater than
-      four digits. We attempt to parse series of digits first as `%Y%m%d`, then
-      `%Y%m`, and finally `%Y`.
-    + `normalizeDate` should reject illegal years (Jesse Rosenthal).
-      We only allow years between 1601 and 9999, inclusive. The ISO 8601
-      actually says that years are supposed to start with 1583, but MS Word
-      only allows 1601-9999. This should stop corrupted word files if the date
-      is out of that range, or is parsed incorrectly.
-    + Improve year sanity check in normalizeDate (Jesse Rosenthal).
-      Previously we parsed a list of dates, took the first one, and then
-      tested its year range. That meant that if the first one failed, we
-      returned nothing, regardless of what the others did. Now we test for
-      sanity before running `msum` over the list of Maybe values. Anything
-      failing the test will be Nothing, so will not be a candidate.
-
-  * Docx reader:
-
-    + Add simple comment functionality. (Jesse Rosenthal).
-      This adds simple track-changes comment parsing to the docx reader. It is
-      turned on with `--track-changes=all`. All comments are converted to
-      inlines, which can list some information. In the future a warning will be
-      added for comments with formatting that seems like it will be excessively
-      denatured.  Note that comments can extend across blocks. For that reason
-      there are two spans: `comment-start` and `comment-end`.  `comment-start`
-      will contain the comment. `comment-end` will always be empty.  The two
-      will be associated by a numeric id.
-    + Enable warnings in top-level reader (Jesse Rosenthal).
-      Previously we had only allowed for warnings in the parser. Now we allow
-      for them in the `Docx.hs` as well. The warnings are simply concatenated.
-    + Add warning for advanced comment formatting. (Jesse Rosenthal).
-      We can't guarantee we'll convert every comment correctly, though we'll
-      do the best we can. This warns if the comment includes something other
-      than Para or Plain.
-    + Add tests for warnings. (Jesse Rosenthal).
-    + Add tests for comments (Jesse Rosenthal).
-      We test for comments, using all track-changes options. Note that we
-      should only output comments if `--track-changes=all`. We also test for
-      emitting warnings if there is complicated formatting.
-
-  * README: update to include track-changes comments. (Jesse Rosenthal)
-
-  * Improved Windows installer - don't ignore properties set on command-line.
-    See #2708.  Needs testing to see if this resolves the issue.
-    Thanks to @nkalvi.
-
-  * Process markdown extensions on command line in L->R order (#2995).
-    Previously they were processed, very unintuitively, in R->L
-    order, so that `markdown-tex_math_dollars+tex_math_dollars`
-    had `tex_math_dollars` disabled.
-
-  * Added `secnumdepth` variable to LaTeX template (#2920).
-
-  * Include table of contents in README.html in Windows package.
-
-  * Writers: treat SoftBreak as space for stripping (Jesse Rosenthal)
-    In Writers.Shared, we strip leading and trailing spaces for display
-    math. Since SoftBreak's are treated as spaces, we should strip those
-    too.
-
-  * beamer, latex templates:  pass biblatexoptions directly in package load.
-    This allows runtime optinos to be used.  Fixes jgm/pandoc-citeproc#201
-
-  * CPP workaround for deprecation of `parseUrl` in http-client.
-
-  * Removed some redundant class constraints.
-
-  * make_oxs_package.sh - use OSX env variable.
-
-  * Replaced INSTALL with INSTALL.md, incorporating INSTALL and the
-    old installing page from website.
-
-  * Added `winpkg` target to Makefile.  This downloads the windows package
-    from appveyor and signs it using the key.
-
-  * Document Org mode as a format containing raw TeX (Albert Krewinkel).
-    Raw TeX is kept verbatim when the output format is Emacs Org mode.
-
-  * Support math with haddock-library >= 1.4.
-
-  * Removed `-rtsopts` from library stanza.  It has no effect, and Hackage
-    wouldn't accept the package.
-
-  * Update library dependency versions.
-
-pandoc (1.17.1)
-
-  * New output format: `docbook5` (Ivo Clarysse).
-
-  * `Text.Pandoc.Options`: Add `writerDocBook5` to `WriterOptions`
-    (API change).
-
-  * Org writer:
-
-    + Add :PROPERTIES: drawer support (Albert Krewinkel, #1962).
-      This allows header attributes to be added to org documents in the form
-      of `:PROPERTIES:` drawers.  All available attributes are stored as
-      key/value pairs.  This reflects the way the org reader handles
-      `:PROPERTIES:` blocks.
-    + Add drawer capability (Carlos Sosa).  For the implementation of the
-      Drawer element in the Org Writer, we make use of a generic Block
-      container with attributes.  The presence of a `drawer` class defines
-      that the `Div` constructor is a drawer. The first class defines the
-      drawer name to use.  The key-value list in the attributes defines
-      the keys to add inside the Drawer.  Lastly, the list of Block elements
-      contains miscellaneous blocks elements to add inside of the Drawer.
-    + Use `CUSTOM_ID` in properties (Albert Krewinkel).  The `ID` property is
-      reserved for internal use by Org-mode and should not be used.
-      The `CUSTOM_ID` property is to be used instead, it is converted to the
-      `ID` property for certain export format.
-
-  * LaTeX writer:
-
-    + Ignore `--incremental` unless output format is beamer (#2843).
-    + Fix polyglossia to babel env mapping (Mauro Bieg, #2728).
-      Allow for optional argument in square brackets.
-    + Recognize `la-x-classic` as Classical Latin (Andrew Dunning).
-      This allows one to access the hyphenation patterns in CTAN's
-      hyph-utf8.
-    + Add missing languages from hyph-utf8 (Andrew Dunning).
-    + Improve use of `\strut` with `\minipage` inside tables
-      (Jose Luis Duran).  This improves spacing in multiline
-      tables.
-    + Use `{}` around options containing special chars (#2892).
-    + Avoid lazy `foldl`.
-    + Don't escape underscore in labels (#2921).  Previously they were
-      escaped as `ux5f`.
-    + brazilian -> brazil for polyglossia (#2953).
-
-  * HTML writer: Ensure mathjax link is added when math appears in footnote
-    (#2881).  Previously if a document only had math in a footnote, the
-    MathJax link would not be added.
-
-  * EPUB writer: set `navpage` variable on nav page.
-    This allows templates to treat it differently.
-
-  * DocBook writer:
-
-    + Use docbook5 if `writerDocbook5` is set (Ivo Clarysse).
-    + Properly handle `ulink`/`link` (Ivo Clarysse).
-
-  * EPUB reader:
-
-    + Unescape URIs in spine (#2924).
-    + EPUB reader:  normalise link id (Mauro Bieg).
-
-  * Docx Reader:
-
-    + Parse `moveTo` and `moveFrom` (Jesse Rosenthal).
-      `moveTo` and `moveFrom` are track-changes tags that are used when a
-      block of text is moved in the document. We now recognize these tags and
-      treat them the same as `insert` and `delete`, respectively. So,
-      `--track-changes=accept` will show the moved version, while
-      `--track-changes=reject` will show the original version.
-    + Tests for track-changes moving (Jesse Rosenthal).
-
-  * ODT, EPUB, Docx readers: throw `PandocError` on unzip failure
-    (Jesse Rosenthal) Previously, `readDocx`, `readEPUB`, and `readOdt`
-    would error out if zip-archive failed. We change the archive extraction
-    step from `toArchive` to `toArchiveOrFail`, which returns an Either value.
-
-  * Markdown, HTML readers:  be more forgiving about unescaped `&` in
-    HTML (#2410).  We are now more forgiving about parsing invalid HTML with
-    unescaped `&` as raw HTML.  (Previously any unescaped `&`
-    would cause pandoc not to recognize the string as raw HTML.)
-
-  * Markdown reader:
-
-    + Added bracket syntax for native spans (#168).
-    + Fix pandoc title blocks with lines ending in 2 spaces (#2799).
-    + Added `-s` to markdown-reader-more test.
-
-  * HTML reader: fixed bug in `pClose`.  This caused exponential parsing
-    behavior in documnets with unclosed tags in `dl`, `dd`, `dt`.
-
-  * MediaWiki reader: Allow spaces before `!` in MediaWiki table header
-    (roblabla).
-
-  * RST reader: Support `:class:` option for code block in RST reader
-    (Sidharth Kapur).
-
-  * Org reader (all Albert Krewinkel, except where noted otherwise):
-
-    + Stop padding short table rows.
-      Emacs Org-mode doesn't add any padding to table rows.  The first
-      row (header or first body row) is used to determine the column count,
-      no other magic is performed.
-    + Refactor rows-to-table conversion.  This refactors
-      the codes conversing a list table lines to an org table ADT.
-      The old code was simplified and is now slightly less ugly.
-    + Fix handling of empty table cells, rows (Albert Krewinkel, #2616).
-      This fixes Org mode parsing of some corner cases regarding empty cells
-      and rows.  Empty cells weren't parsed correctly, e.g. `|||` should be
-      two empty cells, but would be parsed as a single cell containing a pipe
-      character.  Empty rows where parsed as alignment rows and dropped from
-      the output.
-    + Fix spacing after LaTeX-style symbols.
-      The org-reader was droping space after unescaped LaTeX-style symbol
-      commands: `\ForAll \Auml` resulted in `∀Ä` but should give `∀ Ä`
-      instead.  This seems to be because the LaTeX-reader treats the
-      command-terminating space as part of the command.  Dropping the trailing
-      space from the symbol-command fixes this issue.
-    + Print empty table rows.  Empty table rows should not
-      be dropped from the output, so row-height is always set to be at least 1.
-    + Move parser state into separate module.
-      The org reader code has become large and confusing.  Extracting smaller
-      parts into submodules should help to clean things up.
-    + Add support for sub/superscript export options.
-      Org-mode allows to specify export settings via `#+OPTIONS` lines.
-      Disabling simple sub- and superscripts is one of these export options,
-      this options is now supported.
-    + Support special strings export option Parsing of special strings
-      (like `...` as ellipsis or `--` as en dash) can be toggled using the `-`
-      option.
-    + Support emphasized text export option.  Parsing of emphasized text can
-      be toggled using the `*` option.  This influences parsing of text marked
-      as emphasized, strong, strikeout, and underline.  Parsing of inline math,
-      code, and verbatim text is not affected by this option.
-    + Support smart quotes export option.  Reading of smart quotes can be
-      toggled using the `'` option.
-    + Parse but ignore export options. All known export options are parsed
-      but ignored.
-    + Refactor block attribute handling.  A parser state attribute was used
-      to keep track of block attributes defined in meta-lines.  Global state
-      is undesirable, so block attributes are no longer saved as part of the
-      parser state.  Old functions and the respective part of the parser state
-      are removed.
-    + Use custom `anyLine`.  Additional state changes need to be made after
-      a newline is parsed, otherwise markup may not be recognized correctly.
-      This fixes a bug where markup after certain block-types would not be
-      recognized.
-    + Add support for `ATTR_HTML` attributes (#1906).
-      Arbitrary key-value pairs can be added to some block types using a
-      `#+ATTR_HTML` line before the block.  Emacs Org-mode only includes these
-      when exporting to HTML, but since we cannot make this distinction here,
-      the attributes are always added.  The functionality is now supported
-      for figures.
-    + Add `:PROPERTIES:` drawer support (#1877).
-      Headers can have optional `:PROPERTIES:` drawers associated with them.
-      These drawers contain key/value pairs like the header's `id`.  The
-      reader adds all listed pairs to the header's attributes; `id` and
-      `class` attributes are handled specially to match the way `Attr` are
-      defined.  This also changes behavior of how drawers of unknown type
-      are handled.  Instead of including all unknown drawers, those are not
-      read/exported, thereby matching current Emacs behavior.
-    + Use `CUSTOM_ID` in properties.  See above on Org writer changes.
-    + Respect drawer export setting.  The `d` export option can be used
-      to control which drawers are exported and which are discarded.
-      Basic support for this option is added here.
-    + Ignore leading space in org code blocks (Emanuel Evans, #2862).
-      Also fix up tab handling for leading whitespace in code blocks.
-    + Support new syntax for export blocks.  Org-mode version 9
-      uses a new syntax for export blocks.  Instead of `#+BEGIN_<FORMAT>`,
-      where `<FORMAT>` is the format of the block's content, the new
-      format uses `#+BEGIN_export <FORMAT>` instead.  Both types are
-      supported.
-    + Refactor `BEGIN...END` block parsing.
-    + Fix handling of whitespace in blocks, allowing content to be indented
-      less then the block header.
-    + Support org-ref style citations.  The *org-ref* package is an
-      org-mode extension commonly used to manage citations in org
-      documents.  Basic support for the `cite:citeKey` and
-      `[[cite:citeKey][prefix text::suffix text]]` syntax is added.
-    + Split code into separate modules, making for cleaner code and
-      better decoupling.
-
-  * Added `docbook5` template.
-
-  * `--mathjax` improvements:
-
-    + Use new CommonHTML output for MathJax (updated default MathJax URL,
-      #2858).
-    + Change default mathjax setup to use `TeX-AMS_CHTML` configuration.
-      This is designed for cases where the input is always TeX and maximal
-      conformity with TeX is desired.  It seems to be smaller and load faster
-      than what we used before.  See #2858.
-    + Load the full MathJax config to maximize loading speed (KolenCheung).
-
-  * Bumped upper version bounds to allow use of latest packages
-    and compilation with ghc 8.
-
-  * Require texmath 0.8.6.2.  Closes several texmath-related bugs (#2775,
-    #2310, #2310, #2824).  This fixes behavior of roots, e.g.
-    `\sqrt[3]{x}`, and issues with sub/superscript positioning
-    and matrix column alignment in docx.
-
-  * README:
-
-    + Clarified documentation of `implicit_header_references` (#2904).
-    + Improved documentation of `--columns` option.
-
-  * Added appveyor setup, with artefacts (Jan Schulz).
-
-  * stack.yaml versions: Use proper flags used for texmath, pandoc-citeproc.
-
-  * LaTeX template: support for custom font families (vladipus).
-    Needed for correct polyglossia operation with Cyrillic fonts and perhaps
-    can find some other usages.  Example usage in YAML metadata:
-
-          fontfamilies:
-          - name: \cyrillicfont
-            font: Liberation Serif
-          - name: \cyrillicfonttt
-            options: Scale=MatchLowercase
-            font: Liberation
-
-  * Create unsigned msi as build artifact in appveyor build.
-
-  * On travis, test with ghc 8.0.1; drop testing for ghc 7.4.1.
-
-pandoc (1.17.0.3)
-
-  * LaTeX writer: Fixed position of label in figures (#2813).
-    Previously the label wasn't in the right place, and `\ref`
-    wouldn't work properly.
-  * Added .tei test files to pandoc.cabal so they'll be included
-    in tarball (#2811).
-  * Updated copyright dates.
-
-pandoc (1.17.0.2)
-
-  * Fixed serious regression in `htmlInBalanced`, which caused
-    newlines to be omitted in some raw HTML blocks in Markdown
-    (#2804).
-
-pandoc (1.17.0.1)
-
-  * File scope is no longer used when there are no input files (i.e.,
-    when input comes from stdin).  Previously file scope was triggered
-    when the `json` reader was specified and input came from `stdin`,
-    and this caused no output to be produced.  (Fix due to Jesse Rosenthal;
-    thanks to Fedor Sheremetyev for calling the bug to our attention.)
-  * Improved documentation of templates (#2797).
-
-pandoc (1.17)
-
-  * Added `--file-scope` option (Jesse Rosenthal).
-    By default pandoc operates on multiple files by first concatenating
-    them (around extra line breaks) and then processing the joined file. So
-    it only parses a multi-file document at the document scope. This has the
-    benefit that footnotes and links can be in different files, but for
-    some purposes it is useful to parse the individual files first
-    and then combine their outputs (e.g. when the files use footnotes
-    or links with the same labels).  The `--file-scope` option causes
-    pandoc to parse the files first, and then combine the parsed output,
-    instead of combining before parsing. `--file-scope` is selected
-    automatically for binary input files (which cannot be concatenated)
-    and for pandoc json.
-
-  * Add TEI Writer (Chris Forster) and `tei` output format.
-
-  * Added a general `ByteStringReader` with warnings, used by the docx
-    reader (API change, Jesse Rosenthal).
-
-  * Add `readDocxWithWarnings` (API change, Jesse Rosenthal).
-
-  * Changed type of `Shared.uniqueIdent`'s argument from `[String]`
-    to `Set String.` This avoids performance problems in documents with
-    many identically named headers (API change, #2671).
-
-  * Removed `tex_math_single_backslash` from `markdown_github` options
-    (#2707).
-
-  * Make language extensions as well as full language names
-    trigger syntax highlighting.  For example, `py` will now work as
-    well as `python` (jgm/highlighting-kate#83).
-
-  * Added `institute` variable to latex, beamer templates (Fraser
-    Tweedale, Josef Svenningsson).
-
-  * Docx reader (Jesse Rosenthal):
-
-    + Handle alternate content.  Some word functions (especially graphics)
-      give various choices for content so there can be backwards compatibility.
-    + Don't turn numbered headers into lists.
-    + Docx Reader: Add state to the parser, for warnings
-    + Update feature checklist in source code.
-    + Get rid of `Modifiable` typeclass.
-    + Add tests for adjacent hyperlinks.
-    + Add a "Link" modifier to `Reducible`. We want to make sure that
-      links have their spaces removed, and are appropriately smushed
-      together (#2689).
-
-  * HTML reader:
-
-    + Fixed behavior of base tag (#2777).
-      If the base path does not end with slash, the last component
-      will be replaced.  E.g. base = `http://example.com/foo`
-      combines with `bar.html` to give `http://example.com/bar.html`.
-      If the href begins with a slash, the whole path of the base
-      is replaced.  E.g. base = `http://example.com/foo/` combines
-      with `/bar.html` to give `http://example.com/bar.html`.
-    + Rewrote `htmlInBalanced`.  This version avoids an exponential
-      performance problem with `<script>` tags, and it should be faster
-      in general (#2730).
-    + Properly handle an empty cell in a simple table (#2718).
-    + Handle multiple `<meta>` tags with same name.  Put them in a list
-      in the metadata so they are all preserved, rather than (as before)
-      throwing out all but one..
-
-  * Markdown reader:
-
-    + Improved pipe table parsing (#2765).
-    + Allow `+` separators in pipe table cells.  We already allowed
-      them in the header, but not in the body rows, for some reason.
-      This gives compatibility with org-mode tables.
-    + Don't cross line boundary parsing pipe table row.
-      Previously an Emph element could be parsed across the newline
-      at the end of the pipe table row.
-    + Use `htmlInBalanced` for `rawVerbatimBlock`, for better
-      performance (#2730).
-    + Fixed bug with smart quotes around tex math.
-
-  * LaTeX reader:
-
-    + Handle interior `$` characters in math (#2743).  For example,
-      `$$\hbox{$i$}$$`.
-    + `inlineCommand` now gobbles an empty `{}` after any command (#2687).
-      This gives better results when people write e.g. `\TeX{}` in Markdown.
-    + Properly handle LaTeX "math" environment as inline math (#2171).
-
-  * Textile reader: Support `>`, `<`, `=`, `<>` text alignment attributes.
-    Closes #2674.
-
-  * Org reader (Albert Krewinkel):
-
-    + Prefix even empty figure names with "fig:" (#2643).  The
-      convention used by pandoc for figures is to mark them by prefixing
-      the name with `fig:`.  The org reader failed to do this if a figure
-      had no name.
-    + Refactor link-target processing (#2684).
-
-  * ConTeXt writer: Fix whitespace at line beginning in line blocks (#2744).
-    Thanks to @c-foster.
-
-  * HTML writer: Don't include alignment attribute for default table columns.
-    Previously these were given "left" alignment.  Better to leave off
-    alignment attributes altogether (#2694).
-
-  * Markdown writer: Use hyphens for YAML metadata block bottom line, for
-    better compatibility with other Markdown flavors (Henrik Tramberend).
-
-  * LaTeX writer:
-
-    + Use image identifier to create a label and hypertarget for
-      figures (Mauro Bieg).
-    + Avoid double toprule in headerless table with caption (#2742).
-    + Clean up options parser (Jesse Rosenthal).
-    + Treat `memoir` template with `article` option as article, instead
-      of treating all `memoir` templates as books.
-    + Allow more flexible table alignment (Henrik Tramberend, #2665).
-      New default is not to include `[c]` option (which is the default
-      anyway if no positioning is specified).  Now LaTeX emplates can
-      control the overall table alignment in a document by setting the
-      longtable length variables `LTleft` and `LTright`.  For example,
-      `\setlength\LTleft\parindent\setlength\LTright\fill`
-      will create left-aligned tables that respect paragraph indentation.
-
-  * Docx writer: Handle image alt text (#2754, Mauro Bieg).
-
-  * Org writer - pass through RawInline with format "org".
-
-  * DokuWiki writer: use `$$` for display math.
-
-  * Custom writer: Pass attributes parameter to CaptionedImage (#2697).
-
-  * Make protocol-relative URIs work again (#2737).
-
-  * make_osx_package.sh:  Use env variable for developer id certs.
-
-  * Raise `tagsoup` lower bound to 0.13.7 to fix entity-related
-    problems (#2734).
-
-  * Allow `zip-archive` 0.3.
-
-  * Allow `aeson` 0.11.
-
-pandoc (1.16.0.2)
-
-  * Depend on deepseq rather than deepseq-generics (fpco/stackage#1096).
-
-  * Fixed regression in latex smart quote parsing (#2645).
-    In cases where a match was not found for a quote, everything
-    from the open quote to the end of the paragraph was being dropped.
-
-pandoc (1.16.0.1)
-
-  * Fixed regression with `--latex-engine` (#2618).  In 1.16 `--latex-engine`
-    raises an error if a full path is given.
-
-  * Org reader: Fix function dropping subtrees tagged `:noexport`
-    (Albert Krewinkel, #2628):
-
-  * Markdown reader: renormalize table column widths if they exceed 100%
-    (#2626).
-
-  * Textile reader:  don't allow block HTML tags in inline contexts.
-    The reader previously did allow this, following redcloth,
-    which happily parses
-
-        Html blocks can be <div>inlined</div> as well.
-
-    as
-
-        <p>Html blocks can be <div>inlined</div> as well.</p>
-
-    This is invalid HTML.  The above sample now produces;
-
-        <p>Html blocks can be</p>
-        <div>
-        <p>inlined</p>
-        </div>
-        <p>as well.</p>
-
-  * Improved default template lookup for custom lua scripts (#2625).
-    Previously, if you tried to do `pandoc -s -t /path/to/lua/script.lua`,
-    pandoc would look for the template in
-    `~/.pandoc/templates/default./path/to/lua/script.lua`.
-    With this change it will look in the more reasonable
-    `~/.pandoc/templates/default.script.lua`.  This makes it possible to
-    store default templates for custom writers.
-
-  * RST, Markdown writers: Fixed rendering of grid tables with blank rows
-    (#2615).
-
-  * LaTeX writer: restore old treatment of Span (#2624).  A Span is
-    now rendered with surrounding `{}`, as it was before 1.16.
-
-  * Entity handling fixes: improved handling of entities like
-    `&lang;` that require a trailing semicolon.  Allow uppercase
-    `x` in numerical hexidecimal character references, working
-    around a tagsoup bug.
-
-  * `stack.yaml` - use lts-4.0, but with older aeson to avoid excessive
-    memory use on compile.  With aeson 0.10 we were getting an out of
-    memory error on a 2GB Ubuntu 64-bit VM.
-
-  * Improved deb package creation script. Made `DPKGVER` work.
-    Renamed `COMMIT` to `TREE`.  You should now be able to do
-    `TREE=1.16.0.1 DPKGVER=2 make deb`.
-
-
-pandoc (1.16)
-
-  * Added `Attr` field to `Link` and `Image` (Mauro Bieg, #261, API change).
-
-    + Added syntax for link and image attributes to pandoc's Markdown.
-    + Updated readers and writers to use link and image attributes
-      when appropriate.
-    + Support image attributes in Docx, Textile, RST readers.
-
-  * Renamed link attribute extensions.  The old `link_attributes` is
-    now `mmd_link_attributes`, and `link_attributes` now enables the
-    new pandoc-style link and image attributes (API change).
-    Note: this change could break some existing workflows.
-
-  * Implemented `SoftBreak` and new `--wrap` option (#1701, API change).
-    Added threefold wrapping option.
-
-    + Command line option: deprecated `--no-wrap`, added
-      `--wrap=[auto|none|preserve]`
-    + Added `WrapOption`, exported from `Text.Pandoc.Options`
-    + Changed type of `writerWrapText` in `WriterOptions` from
-      `Bool` to `WrapOption`.
-    + Modified `Text.Pandoc.Shared` functions to allow `SoftBreak`.
-    + Supported `SoftBreak` in readers and writers.
-
-  * Text.Pandoc.Options:  Added `writerDpi` to `WriterOptions` (API
-    change, Mauro Bieg).
-
-  * Added `--dpi` command-line option (Mauro Bieg).
-
-  * Rationalized behavior of `--no-tex-ligatures` and `--smart` (#2541).
-    This change makes `--no-tex-ligatures` affect the LaTeX reader
-    as well as the LaTeX and ConTeXt writers.  If it is used,
-    the LaTeX reader will parse characters `` ` ``, `'`, and `-`
-    literally, rather than parsing ligatures for quotation marks
-    and dashes.  And the LaTeX writer will print unicode quotation
-    mark and dash characters literally, rather than converting
-    them to the standard ASCII ligatures.  Note that `--smart` has
-    no effect on the LaTeX reader.  `--smart` is still the default
-    for all input formats when LaTeX or ConTeXt is the output format,
-    *unless* `--no-tex-ligatures` is used.
-
-    Some examples to illustrate the logic:
-
-    ```
-    % echo "'hi'" | pandoc -t latex
-    `hi'
-    % echo "'hi'" | pandoc -t latex --no-tex-ligatures
-    'hi'
-    % echo "'hi'" | pandoc -t latex --no-tex-ligatures --smart
-    ‘hi’
-    % echo "'hi'" | pandoc -f latex --no-tex-ligatures
-    <p>'hi'</p>
-    % echo "'hi'" | pandoc -f latex
-    <p>’hi’</p>
-    ```
-
-  * Removed deprecated options `--offline` and `--html5`.
-
-  * Fixed language code for Czech (`cs` not `cz`) (#2597).
-
-  * Implemented `east_asian_line_breaks` extension (#2586).
-    In `Text.Pandoc.Options`, added `Ext_east_asian_line_breaks` constructor
-    to `Extension` (API change).  This extension is like
-    `ignore_line_breaks`, but smarter -- it only ignores line breaks
-    between two East Asian wide characters.  This makes it better suited
-    for writing with a mix of East Asian and non-East Asian scripts.
-
-  * Added support for PDF creation via `wkhtmltopdf`.
-    To use this: `pandoc -t html5 -o result.pdf` (and add `--mathjax`
-    if you have math.) Margins can be set using the variables
-    `margin-top`, `margin-bottom`, `margin-left`, `margin-right`.
-    Other styling can be done through CSS.
-
-  * Fixed cite key parsing regression (jgm/pandoc-citeproc#201).
-    We were capturing final colons as in `[@foo: bar]`; the citation id
-    was being parsed as `@foo:`.
-
-  * ICML writer:
-
-    + Fixed image syntax for local files (#2589).
-    + Changed type of `writeICML` (Mauro Bieg).
-      API change:  It is now `WriterOptions -> Pandoc -> IO String`.
-      Also handle new image attributes.
-    + Intersperse line breaks instead of appending them to
-      every `ParagraphStyleRange` (Mauro Bieg, #2501).
-    + Add `Cite` style to citations (Mauro Bieg).
-    + Added figure handling (#2590, Mauro Bieg).
-    + Better handling of math.  Instead of just printing the raw tex,
-      we now try to fake it with unicode characters.
-
-  * HTML writer: Include `example` class for example lists (#2524).
-
-  * ODT/OpenDocument writer: improved image attributes (Mauro Bieg).
-
-    + Support for percentage widths/heights
-    + Use `Attr` instead of title to get dimensions from ODT walker
-      to `writeOpenDocument`.
-
-  * AsciiDoc writer:
-
-    + Support anchors in spans and divs with id elements
-      (jgm/pandoc-citeproc#143).
-    + Fixed code blocks (#1861).
-
-  * Haddock writer:  omit formatting inside links, which isn't supported
-    by Haddock (#2515).
-
-  * MediaWiki writer:  Fixed spacing issues in table cells.
-
-    + Start cell on new line unless it's a single Para or Plain
-      (#2606).
-    + For single Para or Plain, insert a space after the `|` to
-      avoid problems when the text begins with a character like
-      `-` (#2604).
-
-  * Beamer writer: mark frame as fragile when it contains verbatim (#1613).
-
-  * LaTeX writer:
-
-    + Add support for GAP highlighting using listings (Raniere Silva).
-    + Consider `header-includes` content as well as templates
-      when determining whether to use csquotes (Andreas Lööw).
-    + Create defaults for geometry using `margin-left` etc.
-      If `geometry` has no value, but `margin-left`, `margin-right`,
-      `margin-top`, and/or `-margin-bottom` are given, a default value
-      for `geometry` is created from these.  Note that these variables
-      already affect PDF production via HTML5 with `wkhtmltopdf`.
-
-  * ConTeXt writer: set default layout based on `margin-left`, etc.
-    This sets up `\setuplayout` based on the variables `margin-left`,
-    `margin-right`, `margin-bottom`, and `margin-top`, if no layout
-    is given.
-
-  * Docx writer:  better handling of PDF images.  Previously we tried
-    to get the image size from the image even if an explicit size was
-    specified.  Since we still can't get image size for PDFs, this made
-    it impossible to use PDF images in docx.  Now we don't try to get
-    the image size when a size is already explicitly specified.
-
-  * Markdown writer:  use raw HTML for link/image attributes when
-    the `link_attributes` extension is unset and `raw_html` is set (#2554).
-
-  * MediaWiki reader: interpret markup inside `<tt>`, `<code>` (#2607).
-
-  * LaTeX reader:
-
-    + Improved smart quote parsing (#2555). This fixes redering of
-      unmatched quotes.
-    + Use curly quotes for unmatched ` (#2555).
-    + Allow blank space between braced arguments of commands (#2592).
-
-  * Markdown reader:
-
-    + Improved pipe table relative widths.  Previously pipe table
-      columns got relative widths (based on the header underscore lines)
-      when the source of one of the rows was greater in width than the
-      column width.  This gave bad results in some cases where much of
-      the width of the row was due to nonprinting material (e.g. link
-      URLs).  Now pandoc only looks at printable width (the width of a
-      plain string version of the source), which should give better results.
-      Thanks to John Muccigrosso for bringing up the issue.
-    + Fixed parsing bug with macros.  Previously macro definitions in
-      indented code blocks were being parsed as macro definitions, not code.
-
-  * Textile reader:  skip over attribute in image source (#2515).
-    We don't have a place yet for styles or sizes on images, but
-    we can skip the attributes rather than incorrectly taking them
-    to be part of the filename.
-
-  * Docx reader: Handle dummy list items (Jesse Rosenthal).
-    These come up when people create a list item and then delete the
-    bullet. It doesn't refer to any real list item, and we used to ignore
-    it.
-
-  * CommonMark reader/writer rewritten to use latest `cmark`.
-
-  * Fixed Emoji character definitions (#2523).  There were many bugs in the
-    definitions.
-
-  * `Text.Pandoc.CSS`:
-
-    + Added `pickStylesToKVs` function to extract multiple properties at
-      once (API change, Mauro Bieg).
-    + Parse CSS that doesn't contain the optional semicolon (Mauro Bieg).
-
-  * `trypandoc`: sort drop-down lists.
-
-  * Beamer template:
-
-    + Made `\euro` conditional on presence of character.
-      for xelatex and lualatex, as it is for pdflatex (Andrew Dunning).
-    + Moved `header-includes` before setting of title (Thomas Hodgson),
-      to match the LaTeX template (jgm/pandoc-templates#168).
-    + Added `section-titles` variable (defaults to true)
-      to enable/suppress section title pages in beamer
-      slide shows (Thomas Hodgson).
-    + Moved beamer themes after fonts, so that themes can
-      change fonts.  (Previously the fonts set were being
-      clobbered by lmodern.sty.) (Thomas Hodgson).
-
-  * Beamer/LaTeX template changes (Thomas Hodgson):
-    + Added `thanks` variable
-    + Use `parskip.sty` when `indent` isn't set (fall back to using
-      `setlength` as before if `parskip.sty` isn't available).
-    + Use `biblio-style` with biblatex.
-    + Added `biblatexoptions` variable.
-
-  * LaTeX template changes:
-
-    + Added `paper` after `$papersize$` variable in latex template.
-      Thus you can say `papersize: a4` and the latex will contain
-      `a4paper`.  This change may break some existing workflows; if
-      you currently specify `a4paper`, you'll get `a4paperpaper` which
-      is meaningless.  However, the change seems worth it, as it will
-      make the `papersize` variable work uniformly across ConTeXt, LaTeX,
-      and html->pdf via wkhtmltopdf.
-    + Only pass options to color package if `colorlinks` is set
-      (Andrew Dunning).
-    + Make definition of `\euro` conditional in xelatex/lualatex,
-      as it is already for pdflatex (Andrew Dunning).
-    + Removed setting of `subject` in PDF metadata.
-      This used to be set to the subtitle, but really the subtitle
-      need not give the subject.  Also, `subtitle` can contain formatting,
-      so we'd need, at least, a plain text version for this.
-    + Moved `header-includes` before setting of `\title`, `\author`,
-      etc.  This allows these macros to be redefined.
-    + Use `\subtitle` command for `subtitle`, instead of tacking it
-      on to the title as before.  We give a no-op fallback definition if it
-      is not defined.  This change should produce much better results
-      in classes that support `\subtitle`.  With the default article
-      class, which does not define `\subtitle`, subtitles will no
-      longer be printed unless the user defines `\subtitle` and
-      redefines `\maketitle`.
-    + Moved redefinitions of `\paragraph` and `\subparagraph` to
-      before header-includes.
-
-  * Context template:
-
-    + Use `simplefonts` for font loading (Paolo Rodríguez).  This is
-      needed for things to work on ConTeXt stable from TeXLive 2015.
-    + Revert use of `\setuphead` in title block (Andrew Dunning,
-      Rik Kabel).
-
-  * Update LaTeX/ConTeXt link colour usage (Andrew Dunning).
-
-  * Fixed man template so disabling hyphenation actually works.
-    The command needs to come after .TH.
-
-  * Added 'navigation' variable to beamer template (#2543).
-    Valid values are `empty` (the default), `horizontal`, `vertical`,
-    and `frame`.  Note that this changes the default behavior from
-    `horizontal` to `empty`.  Closes #2543.
-
-  * Added `toc` to HTML slide format templates (Andrew Dunning),
-    so that `--toc` creates a contents slide.
-
-  * Added `stack.full.yaml` to build `pandoc-citeproc` as well.
-
-  * Allow pipe tables with no body rows (#2556).
-    Previously this raised a runtime error.
-
-  * Shared: Improved `fetchItem` so that `C:/Blah/Blah.jpg` isn't treated
-    as URL.  The Haskell URI parsing routines will accept "C:" as a
-    scheme, so we rule that out manually.  This helps with
-    `--self-contained` and absolute Windows paths.
-
-  * Define a `meta-json` variable for all writers (#2019).  This contains
-    a JSON version of all the metadata, in the format selected for the
-    writer.  So, for example, to get just the YAML metadata, you can run
-    pandoc with the following custom template: `$meta-json$`.  The intent
-    is to make it easier for static site generators and other tools to get
-    at the metadata.
-
-  * Document limitations of --self-contained (#2553).
-
-  * Improved Citations section of README (#2551).  Added information
-    about `link-citations` and a link to the pandoc-citeproc man page.
-
-  * `ImageSize`: use `safeRead` instead of `readMaybe`, which isn't
-    in base < 4.6.
-
-  * Allow .adoc file extension for AsciiDoc (Andrew Dunning).
-
-  * Improved implicit pandoc-citeproc inclusion.
-    The filter pandoc-citeproc is automatically used when
-    `--bibliography` is specified on the command line, unless
-    `--natbib` or `--biblatex` is used.  However, previously this
-    only worked if `--bibliography` was spelled out in full, and not
-    if `--biblio` was used.
-
-  * reveal.js: Interpret pauses correctly for all headers (#2530).
-    Previously, when using headers below the slide level, pauses are left
-    uninterpreted into pauses. In my opinion, unexpected behavior but
-    intentional looking at the code.
-
-  * Remove redundant `center` variable for reveal.js (Andrew Dunning).
-
-  * Parsing: Add `extractIdClass`, modified type of `KeyTable` (Mauro
-    Bieg, API change).
-
-  * ImageSize:  Added functions for converting between image dimensions
-    (Mauro Bieg).
-
-  * Use lts-3.18 in stack.yaml.  This avoids Windows build
-    issues with the HTTP library.
-
-  * Bump version bounds for dependencies.
-
-pandoc (1.15.2.1)
-
-  * Added two missing test files, and `stack.yaml`, to
-    `extra-source-files` so they're included in the source tarball.
-
-  * reveal.js template: Fixed parallaxBackground options.
-    `parallaxBackgroundHorizontal` and `parallaxBackgroundVertical`
-    need integer values, not strings.  (Vaughn Iverson)
-
-pandoc (1.15.2)
-
-  * `pandoc my.md -t context -o my.pdf` will now create a PDF using
-    ConTeXt rather than LaTeX (#2463).
-
-  * Fixed omitted `url(...)` in CSS data-uri with `--self-contained` (#2489).
-
-  * Added `emoji` Markdown extension, enabled by default in `markdown_github`
-    (#2523).  Added `Ext_emoji` to `Extension` in `Text.Pandoc.Options`
-    (API change).
-
-  * `Text.Pandoc.Readers.HTML.parseTags`: Fixed over-eager raw HTML inline
-    parsing (#2469).  Tightened up the inline HTML parser so it disallows
-    TagWarnings.
-
-  * Derive `Generic` instances for the types in `Text.Pandoc.Options`.
-
-  * Org reader:
-
-    + Fix paragraph/list interaction (Albert Krewinkel, #2464).
-      Paragraphs can be followed by lists, even if there is no blank line
-      between the two blocks.  However, this should only be true if the
-      paragraph is not within a list, were the preceding block should be
-      parsed as a plain instead of paragraph (to allow for compact lists).
-      Thanks to @rgaiacs for bringing this up.
-    + Allow toggling header args (Albert Krewinkel, #2269).
-      Org-mode allows to skip the argument of a code block header argument if
-      it's toggling a value.  Argument-less headers are now recognized,
-      avoiding weird parsing errors.
-    + Fix markup parsing in headers (Albert Krewinkel, #2504).
-      Markup as the very first item in a header wasn't recognized.  This was
-      caused by an incorrect parser state: positions at which inline markup
-      can start need to be marked explicitly by changing the parser state.
-      This wasn't done for headers.  The proper function to update the state
-      is now called at the beginning of the header parser, fixing this issue.
-    + Fix emphasis rules for smart parsing (Albert Krewinkel, #2513).
-      Smart quotes, ellipses, and dashes should behave like normal quotes,
-      single dashes, and dots with respect to text markup parsing.
-    + Require whitespace around definition list markers (#2518).
-      This rule was not checked before, resulting in bugs with footnotes
-      and some link types.
-
-  * Markdown reader:
-
-    + Pipe tables with long lines now get relative cell widths (#2471).
-      If a pipe table contains a line longer than the column width (as set by
-      `--columns` or 80 by default), relative widths are computed based on the
-      widths of the separator lines relative to the column width.  This should
-      solve persistent problems with long pipe tables in LaTeX/PDF output, and
-      give more flexibility for determining relative column widths in other
-      formats, too.  For narrower pipe tables, column widths of 0 are used,
-      telling pandoc not to specify widths explicitly in output formats that
-      permit this.
-    + Improved parser for `mmd_title_block`.  We now allow blank metadata
-      fields.  These were explicitly disallowed before.
-    + Citation keys can now contain `://`, so URLs and DOIs can be used
-      as citation keys (jgm/pandoc-citeproc#166).
-
-  * Beamer template:  fix incompatibility of section slides with natbib.
-    Natbib (and presumably biblatex) bibliography commands create
-    their own section.  Since these are in frame environments,
-    we have an incompatibility with the `\AtBeginSection` macro
-    which creates a special frame when a new section occurs.
-    (We can't have a frame inside another frame.) This change disables
-    `\AtBeginSection` inside bibliography slides.  Thinks to Yihui Xie for
-    bringing the problem to my attention.  This supersedes #145.  See
-    discussion there.
-
-  * Textile reader:  don't do smart punctuation unless explicitly asked
-    (#2480).  Note that although smart punctuation is part of the textile
-    spec, it's not always wanted when converting from textile
-    to, say, Markdown.  So it seems better to make this an option.
-
-  * LaTeX reader: Handle `comment` environment (Arata Mizuki).
-    The `comment` environment is handled in a similar way to the
-    `verbatim` environment, except that its content is discarded.
-
-  * Docx reader:  Follow relationships correctly in foot/endnotes (#2258,
-    Jesse Rosenthal).  This fixes a problem with links in notes.
-
-  * LaTeX and ConTeXt writers: support `lang` attribute on divs and spans
-    (Mauro Bieg).  For LaTeX, also collect `lang` and `dir` attributes on
-    spans and divs to set the `lang`, `otherlangs` and `dir` variables if
-    they aren’t set already.  See #895.
-
-  * LaTeX writer:
-
-    + Use proper command for `\textarabic` (Mauro Bieg).
-    + Added `de-CH-1901`, fixed `el-polyton` in `toPloyglossia` (Nick Bart).
-    + Use `\hypertarget` and `\hyperlink` for links.  This works correctly
-      to link to Div or Span elements.  We now don't bother defining `\label`
-      for Div or Span elements.  Closes jgm/pandoc-citeproc#174.
-    + Avoid footnotes in list of figures (#1506).
-    + Properly handle footnotes in captions (#1506).
-    + Add `\protect` to `\hyperlink` (#2490).  Thanks to Hadrien Mary.
-    + Set `colorlinks` if `linkcolor`, `urlcolor`, `citecolor`, or
-      `toccolor` is set (#2508).
-
-  * Textile writer: support start number in ordered lists (#2465).
-
-  * OpenDocument writer:  Allow customization of opendocument
-    automatic styles.  Automatic styles can now be inserted in the
-    template, which now provides the enclosing `<office:automatic-styles>`
-    tags (#2520).
-
-  * Docx writer:  insert space between footnote reference and note (#2527).
-    This matches Word's default behavior.
-
-  * EPUB writer:  don't download linked media when `data-external` attribute
-    set (#2473).  By default pandoc downloads all linked media and includes it
-    in the EPUB container.  This can be disabled by setting `data-external` on
-    the tags linking to media that should not be downloaded.  Example:
-
-        <audio controls="1">
-          <source src="http://example.com/music/toccata.mp3"
-                  data-external="1" type="audio/mpeg">
-          </source>
-        </audio>
-
-  * HTML writer:  use width on whole table if col widths sum to < 100%.
-    Otherwise some browsers display the table with the columns
-    separated far apart.
-
-  * AsciiDoc template:  Fix `author` and `date`; add `keywords`,
-    `abstract` (Andrew Dunning).
-
-  * HTML-based templates (Andrew Dunning):
-
-    + Use en dash instead of hyphen between title prefix and title.
-    + Add `keywords` to metadata.
-    + Add `lang`, `dir`, `quotes` where missing.
-    + Always make author and date display conditional.
-    + Updated dzslides template from source.
-
-  * Man template: make "generated by" comment conditional.
-
-  * LaTeX, Beamer templates:
-
-    + Add `babel-otherlangs` for language divs/spans; `babel-newcommands`,
-      filled by commands that make babel understand the polyglossia-style
-      language directives (Mauro Bieg, #137).
-    + Improved formatting of conditionals; `$for$` is always provided to allow
-      multiple options (Andrew Dunning, #141).
-    + Use `Ligatures=TeX` rather than `Mapping=tex-text` with `fontspec`
-      to improve support for LuaTeX (Andrew Dunning, #135).
-    + Revise `hyperref` usage (Andrew Dunning, #139, #141):
-        - use same options for all LaTeX engines;
-        - add `subtitle` and `keywords` to PDF metadata;
-        - do not override `hyperref` link coloring without user input, effectively making
-          the `hidelinks` option the default (removed as a separate variable);
-        - link colors can be enabled (using a slightly darker version of the old
-          defaults) using a new `colorlinks` variable, automatically used by
-          the LaTeX writer when custom colors are specified;
-        - `pdfborder={0 0 0}` is automatically set by `hyperref` with
-          `colorlinks`, and is only applied if `colorlinks` is disabled.
-
-  * ConTeXt template (Andrew Dunning):
-
-    + New variables for controlling styles: `linkstyle`, `linkcolor`,
-      `linkcontrastcolor`, `layout`, `pagenumbering`, `whitespace`, `indenting`,
-      `interlinespace`, `headertext`, `footertext`, `mainfont`, `sansfont`,
-      `monofont`, `mathfont`, `fontsize`.
-    + Default template no longer supports MkII.
-    + Improve writing of title block (suppressing numbering of first page).
-    + Add `title` `subtitle`, `author`, `date`, `keywords` to PDF metadata.
-    + Support `subtitle`, `abstract`.
-    + Support list of figures (`lof`), list of tables (`lot`).
-    + Disable link styling by default.
-    + Define styles for all section types.
-    + Enable microtype.
-    + Improved formatting of conditionals.
-
-  * Beamer template:  added code to prevent slide breaks inside paragraphs
-    (#2422, thanks to Nick Bart).  This will matter, in practice, only when
-    `allowframebreaks` is used.  It is especially helpful for bibliography
-    slides.
-
-  * OpenDocument template:  Add `<office:automatic-styles>` tag around
-    automatic styles.  The writer now longer provides this (see #2520).
-
-  * Restored Text.Pandoc.Compat.Monoid.
-
-  * Do not export (<>) from custom Prelude.  The Prelude now matches
-    base 4.8 Prelude's API.
-
-  * Don't use custom prelude with ghc 7.10.  Use the custom prelude
-    only for earlier versions.  This change makes `stack ghci` and
-    `cabal repl` work (#2503), at least with ghc 7.10.
-
-  * Changed § to % in operators from Odt.Arrows.Utils (#2457).
-    This prevents problems building haddocks with "C" locale.
-
-  * Change default for old-locale flag to False.
-
-  * Use stack in deb, osx, and Windows package generators.
-
-  * Added Vagrantfile for building deb in vm.
-    This should help in automating binary package creation.  'make package'
-    will make the package.  'make package COMMIT=blah' will make the package
-    from commit blah.
-
-  * README:
-
-    + Consistent capitalization for pandoc and Markdown.
-    + Fixed `auto_identifiers` examples (Benoit Schweblin).
-    + Improved documentation of template variables (Andrew Dunning).
-
-pandoc (1.15.1.1)
-
-  * `Text.Pandoc.Data`:  store paths in dataFiles using posix separators.
-    This way we have uniform separators, whether on Windows or Linux.
-    This should solve a problem where on some Windows versions
-    the data files weren't being found (#2459).
-
-pandoc (1.15.1)
-
-  * `pandocVersion` is now defined in `Text.Pandoc.Shared`
-    and reexported from `Text.Pandoc` (Alex Vong).  This allows
-    writers to access it.  (Alex Vong) (API change)
-
-  * For `markdown_mmd`, add: `implicit_figures`, `superscripts`,
-    `subscripts` (#2401).
-
-  * Added `odt` as input format (Martin Linnemann).  Added new module
-    `Text.Pandoc.Reader.ODT` (API change). Fully implemented features:
-    Paragraphs, Headers, Basic styling, Unordered lists, Ordered lists,
-    External Links, Internal Links, Footnotes, Endnotes, Blockquotes.
-    Partly implemented features: Citations, Tables.
-
-  * Markdown Reader:
-
-    + Add basic tests for each header style (Ophir Lifshitz).
-    + Add implicit header ref tests for headers with spaces (Ophir Lifshitz).
-    + Skip spaces in headers (Ophir Lifshitz).
-    + Handle 'id' and 'class' in parsing key/value attributes (#2396).
-      `# Header {id="myid" class="foo bar"}`
-      is now equivalent to `# Header {#myid .foo .bar}`.
-    + Use '=' instead of '#' for atx-style headers in markdown+lhs.
-      (Kristof Bastiaensen)
-    + Pipe tables: allow indented columns.  Previously the left-hand column
-      could not start with 4 or more spaces indent.  This was inconvenient
-      for right-aligned left columns.  Note that the first (header column)
-      must still have 3 or fewer spaces indentation, or the table will be
-      treated as an indented code  block.
-    + Fix regression:  allow HTML comments containing `--`.
-      Technically this isn't allowed in an HTML comment, but
-      we've always allowed it, and so do most other implementations.
-      It is handy if e.g. you want to put command line arguments
-      in HTML comments.
-
-  * LaTeX reader:
-
-    + Don't eat excess whitespace after macros with only optional
-      arguments (#2446).
-    + Support longtable (#2411).
-    + Implement `\Cite` (#2335).
-    + Support abstract environment.  The abstract populates an
-      `abstract` metadata field.
-    + Properly handle booktabs lines.  Lines aren't part of the
-      pandoc table model, so we just ignore them (#2307).
-
-  * HTML reader:
-
-    + Handle type attribute on ol, e.g. `<ol type="i">` (#2313).
-    + Updated for new automatic header attributes.
-    + Add auto identifiers if not present on headers.  This makes
-      TOC linking work properly.
-    + Detect `font-variant` with `pickStyleAttrProps` (Ophir Lifshitz).
-    + Test `<ol>` type, class, and inline list-style(-type) CSS
-      (Ophir Lifshitz).
-    + Better handling of "section" elements (#2438).  Previously
-      `<section>` tags were just parsed as raw HTML blocks.  With
-      this change, section elements are parsed as Div elements with
-      the class "section".
-
-  * MediaWiki reader:  handle unquoted table attributes (#2355).
-
-  * DocBook reader:
-
-    + Added proper support for DocBook `xref` elements (Frerich Raabe).
-      Added `dbContent` field to reader state, so we can lookup
-      cross refs.
-    + Handle `informalexample` (#2319).
-
-  * Docx Reader:
-
-    + Create special punctuation test (Ophir Lifshitz).
-    + Parse soft, no-break hyphen elements (Ophir Lifshitz).
-    + Updated headers test (Ophir Lifshitz). Replaced `styles.xml`
-      in `headers.docx` with pandoc's current `styles.xml`, which
-      contains styles for Heading 1 through 6. Added Heading 4
-      through 7 to the test document. Note that Heading 7 is not
-      parsed as a Heading because there is no Heading 7 style.
-
-  * RST reader:  better handling of indirect roles.
-    Previously the parser failed on this kind of case
-
-        .. role:: indirect(code)
-
-        .. role:: py(indirect)
-           :language: python
-
-        :py:`hi`
-
-    Now it correctly recognizes `:py:` as a code role.
-
-  * Org reader:
-
-    + Add auto identifiers if not present on headers
-      (#2354, Juliusz Gonera).
-    + Allow verse blocks to contain empty lines (#2402,
-      Albert Krewinkel).
-
-  * EPUB reader:  stop mangling external URLs (#2284).
-
-  * RST writer:
-
-    + Don't insert `\ ` when complex expression in matched pairs.
-      E.g. `` [:sup:`3`] `` is okay; you don't need `` [:sup:`3`\ ] ``.
-    + Ensure that `\ ` is inserted when needed before Cite and Span
-      elements that begin with a "complex" element (jgm/pandoc-citeproc#157).
-    + Normalize headers only in "standalone" mode (#2394).
-
-  * Haddock writer: escape `*` and `^` (G. Bataille).
-
-  * Markdown writer:
-
-    + In TOC, add links to headers (#829).
-    + Use unicode super/subscripts for digits in plain output
-      (when the `superscripts` and `subscripts` extensions are
-      not enabled).
-
-  * Docx writer:
-
-    + Moved invalid character stripping to `formattedString`.
-      This avoids an inefficient generic traversal (#2356).
-    + Use user data directory for `reference.docx` archive.
-      This allows the test suite to work without installing pandoc first.
-      It also brings the docx writer in line with the odt writer.
-    + Tests:  docx writer tests now use `../data` for data directory.
-      This allows tests to be run without installing first.
-    + Tests: Use real jpg (not empty) for docx tests to avoid warning.
-
-  * LaTeX writer:
-
-    + Fixed detection of 'chapters' from template.
-      If a documentclass isn't specified in metadata, but the
-      template has a hardwired bookish documentclass, act as if
-      `--chapters` was used.  This was the default in earlier
-      versions, but it has been broken for a little while.
-    + Correctly recognize book documentclass in metadata (#2395).
-    + Set language-related variables automatically, depending
-      on the value of the `lang` field, which is now always
-      assumed to be in BCP47 format (Mauro Bieg, #1614, #2437).
-    + Add `\protect` to `\hyperdef` in inline context.  This way we
-      don't get an error when this is used as a moveable argument (#2136).
-    + Support all frame attributes in Beamer.
-    + Percent-encode more special characters in URLs (#1640, #2377).
-      The special characters are '<','>','|','"','{','}','[',']','^', '`'.
-
-  * HTML writer:
-
-    + Update KaTeX JS and CSS versions (Emily Eisenberg).
-    + For dzslides, add `role="note"` for speaker notes (#1693).
-    + Percent-encode more special characters in URLs (#1640, #2377).
-      The special characters are '<','>','|','"','{','}','[',']','^', '`'.
-    + Render Div with class `section` as `<section>` in HTML5.
-
-  * EPUB writer:
-
-    + In TOC, replace literal `<br/>` with space (#2105).
-    + With `--webtex`, include image file rather than `data:` URI (#2363).
-
-  * Native writer: format Div properly, with blocks separated.
-
-  * Support bidirectional text output with XeLaTeX, ConTeXt and HTML
-    (#2191, Mauro Bieg).
-
-  * Reference Docx:
-
-    + Add missing Header 6 style (steel blue) (Ophir Lifshitz).
-    + Correct `outlineLvl` for Header styles (Ophir Lifshitz).
-
-  * Templates
-
-    + Beamer:  Add `innertheme`, `outertheme` variables
-      (Guilhem Bonnefille, #121). Add space after colon in figure caption.
-      Integrate recent font and language updates from LaTeX template;
-      allow use of `mainfont` variable for changing the slide text
-      in XeTeX and LuaTeX (Andrew Dunning, #131).
-    + LaTeX:  Add `mainfontoptions`, `sansfontoptions`,
-      `monofontoptions`, `mathfontoptions`, `fontfamilyoptions`
-      (Andrew Dunning, #122).  Support handling of bidirectional
-      text (Mauro Bieg, #120). Improve reliability of superscripts/subscripts
-      under XeTeX and prevent letters and numbers from appearing on a
-      different baseline by removing use of the `realscripts` package
-      (via `xltxtra`).  To restore use of OpenType characters for these
-      features under XeTeX or LuaTeX, add `\usepackage{realscripts}` to
-      `header-includes` (Andrew Dunning, #130).  Remove redundant
-      reference to `xunicode` (Andrew Dunning, #130).  Add `fontenc`,
-      `indent`, `subparagraph` variables (Andrew Dunning).
-      Allow use of `hidelinks` variable for `hyperref` package (Hugo Roy,
-      #113).  Prevent package clash with `tufte-latex` and other classes that
-      include `hyperref` or `color` (Xavier Olive, #115).
-    + ConTeXt:  Support handling of bidirectional text (Mauro Bieg, #120).
-    + LaTeX and ConTeXt: Use more specific language variables.
-      Instead of directly using `lang`, we now use `babel-lang` and
-      `polyglossia-lang` and `context-lang`.  These variables are set by
-      the writers to the necessary values, based on the `lang` variable
-      (which now always takes a value in BCP47 format). (Mauro Bieg, #114,
-      #129).
-    + HTML:  Support handling of bidirectional text (Mauro Bieg, #120).
-      Move HTML5 shiv after CSS and fix URL (Andrew Dunning).
-      Add dir attribute in html5 (Andrew Dunning).
-    + reveal.js: Add `controls`, `progress` variables (Grégoire Pineau, #127).
-      Add `width`, `height` variables (Andrew Dunning).  Update template
-      from 3.1 source (Andrew Dunning).  All configuration options are now
-      available as variables, but are only be included if set (reveal.js
-      uses defaults otherwise).
-    + man: Added comment stating that the page is autogenerated by pandoc,
-      giving version.  Added `adjusting` and `hyphenate` variables
-      (Alex Vong, #123).
-
-  * epub.css: added selectors for nested emphasis (Pablo Rodriguez).
-
-  * MediaBag:  ensure that `/` is always used as path separator.
-
-  * `sample.lua`: define `CaptionedImage`, add newline at end (#2393).
-
-  * Added `--bash-completion` option.  This generates a bash completion
-    script.  To use: `eval "$(pandoc --bash-completion)"`.
-
-  * Text.Pandoc.Error: Define Typeable and Exception instances
-    for PandocError (#2386).
-
-  * Text.Pandoc.Parsing: `toKey`: strip off outer brackets.
-    This makes keys with extra space at the beginning and end
-    work:  e.g.
-
-        [foo]: bar
-
-        [ foo ]
-
-    will now be a link to bar (it wasn't before).
-
-  * Text.Pandoc: disable `auto_identifiers` for epub.
-    The epub writer inserts its own auto identifiers;
-    this is more complex due to splitting into "chapter" files.
-
-  * Renamed Text.Pandoc.Compat.Locale -> Text.Pandoc.Compat.Time.
-    It now reexports Data.Time.
-
-  * Use custom Prelude to avoid compiler warnings.
-
-    + The (non-exported) prelude is in prelude/Prelude.hs.
-    + It exports Monoid and Applicative, like base 4.8 prelude,
-      but works with older base versions.
-    + It exports (<>) for mappend.
-    + It hides 'catch' on older base versions.
-
-  * Added a `stack.ymal` and stack install instructions to INSTALL.
-
-  * Clarified what is "out of scope" in README and CONTRIBUTING.md.
-
-  * Added note to CONTRIBUTING.md about ghc versions and travis.
-
-  * Clarify docs on block quotes.  The space after `>` is optional (#2346).
-
-  * Removed obsolete reference to default.csl (#2372).
-
-  * List all styles in manual for `--reference-docx` (Chris Black)
-
-  * Don't capitalize header links in man page.
-
-  * Added section on repl to CONTRIBUTING.md.
-
-  * README:  Added space after backslash in image example (#2329).
-
-  * Document details of citation locator terms (Nick Bart).
-
-  * Fixed some internal links in README (#2309).
-
-  * Improve CSL documentation, variables documentations,
-    links, and cross-references in README. (Andrew Dunning)
-
-  * Fix build failure with `--flags=-https` (Sergei Trofimovich).
-
-  * Use `newManager` instead of `withManager` in recent `http-client`.
-    This avoids a deprecation warning.
-
-  * Allow building with latest versions of http-types,
-    HUnit, criterion, syb, aeson.
-
-  * Updated benchmark program for new criterion API.
-
-  * Setup.hs: rewrite so as not to use process, directory, filepath.
-    Using anything outside base is dangerous, since older
-    versions of ghc may link against two different versions.
-
-  * Added appveyor (Windows continuous integration) builds.
-
-  * New `.travis.yml`.  Autgenerated using `make_travis_yml.hs`.
-    This script has been modified in a few ways, e.g. to add `GHCOPTS`.
-    `make .travis.yml` regenerates it based on the tested-with
-    field of the cabal file.
-
-pandoc (1.15.0.6)
-
-  * `--self-contained`:  Fixed overaggressive CSS minimization (#2301, 2286).
-    Previously `--self-contained` wiped out all spaces in CSS,
-    including semantically significant spaces.  This was a regression
-    from 1.14.x.
-
-  * Markdown reader: don't allow bare URI links or autolinks in link
-    label (#2300).  Added test cases.
-
-  * `Text.Pandoc.Parsing`, `uri`: Improved bare autolink detection (#2299).
-    Previously we disallowed `-` at the end of an autolink,
-    and disallowed the combination `=-`.  This commit liberalizes the
-    rules for allowing punctuation in a bare URI, and adds test cases.
-    One potential drawback is that you can no longer put a bare
-    URI in em dashes like this:
-    `this uri---http://example.com---is an example.`
-    But in this respect we now match github's treatment of bare URIs.
-
-  * HTML writer:  support speaker notes in dzslides.
-    With this change `<div class="notes">` and also `<div class="notes"
-    role="note">` will be output if `-t dzslides` is used. So we can
-    have speaker notes in dzslides too.  Thanks to maybegeek.
-
-  * Updated dzslides template.
-
-  * Improved documentation of options to print system default files (#2298).
-    `--print-default-data-file` and `--print-default-template`.
-
-  * DokuWiki writer: use `$..$` for Math instead of `<math>..</math>`
-    (Tiziano Müller).  MathJax seems currently to be the only maintained
-    math rendering extension for DokuWiki.
-
-  * `Text.Pandoc.Shared`: Changed `hierarchicalize` so it treats references
-    div as top-level header (#2294).  This fixes a bug with `--section-divs`,
-    where the final references section added by pandoc-citeproc, enclosed in
-    its own div, got nested in the div for the section previous to it.
-
-  * Allow vector 0.11.
-
-  * Require cmark > 0.4.
-
-pandoc (1.15.0.5)
-
-  * HTML writer: Fixed email javascript obfuscation with `mailto:`
-    URLs (#2280).  This fixes a potential security issue.  Because
-    single quotes weren't being escaped in the link portion, a
-    specially crafted email address could allow javascript code injection.
-
-  * Markdown/HTML readers:  Avoid parsing partial URLs like
-    `<www.pandoc.org/blah#foo>` as HTML tags (#2277).
-
-  * RST reader:  allow inline formatting in definition list field
-    names (Lars-Dominik Braun).
-
-  * PDF:  Make sure `--latex-engine-opt` goes before the filename
-    on the command line.  LaTeX needs the argument to come after
-    the options (#1779).
-
-  * CommonMark writer: fixed tags used for super/subscript.
-
-  * ConTeXt template:  activate hanging indent for definition lists
-    (Mauro Bieg).
-
-  * Make cabal require `hsb2hs` >= 0.3.1 if `embed_data_files` specified.
-    This is done by adding `hookedPrograms` in `Setup.hs`, which allows us
-    to include `hsb2hs` in Build-Tools in cabal.
-
-  * Improved Windows installer (thanks to nkalvi).
-
-    + When per-machine installation is chosen, the system path
-      is updated instead of the user's.
-    + An appropriate default is used for per-machine installation
-      directory.
-    + Admin privileges are no longer required for a per-user install
-
-  * Travis:  unpack sdist for build to catch packaging bugs.
-
-  * Improved documentation on where user templates go (#2272).
-
-pandoc (1.15.0.4)
-
-  * Added pandoc.1 man page to the repository.  It is no longer
-    built as part of the cabal build process. (This proved too
-    fragile.)  pandoc.1 can be regenerated (`make man/pandoc.1`)
-    when `README` is changed.
-
-  * Copying of the man page now respects `--destdir` (#2262).
-
-  * Improved error messages for filters.  User is now informed if
-    the filter requires an interpreter that isn't found in the path,
-    or if the filter returns an error status.
-
-pandoc (1.15.0.3)
-
-  * Ensure target directory is created when installing man page.
-
-pandoc (1.15.0.2)
-
-  * Added files needed for building man page to Extra-Source-Files.
-
-pandoc (1.15.0.1)
-
-  * Man page is now built and installed as part of the cabal build
-    process. Removed Makefile target for man page.
-
-pandoc (1.15)
-
-  * Man page changes:
-
-    + Removed `--man1`, `--man5` options (breaking change).
-    + Removed `Text.Pandoc.ManPages` module (breaking API change).
-    + Makefile target for `man/man1/pandoc.1`.  This uses pandoc to
-      create the man page from README using a custom template and filters.
-    + Added `man/` directory with template and filters needed to build
-      man page.
-    + We no longer have two man pages: `pandoc.1` and `pandoc_markdown.5`.
-      Now there is just pandoc.1, which has all the content from README.
-      This change was needed because of the extensive cross-references
-      between parts of the README.
-    + Removed old `data/pandoc.1.template` and
-      `data/pandoc_markdown.5.template`.
-
-  * OpenDocument writer: Do not add a carriage return after a hard
-    line break (Michael Chladek).
-
-  * ConTeXt writer:
-
-    + use `\goto` for internal links.
-    + Added a `%` at end for `\reference` to avoid spurious space.
-
-  * Ignore sandbox on 'make quick'
-
-pandoc (1.14.1)
-
-  * Added `--man1` and `--man5` options to pandoc, allowing pandoc
-    to generate its own man pages.  Man pages are no longer automatically
-    generated in the build process (the process for this was too complex
-    and prone to failure, #2190).  The `make-pandoc-man-pages` executable
-    has been removed.  The `man/` directory has been removed, and man page
-    templates have been moved to `data/`.  NOTE TO PACKAGERS:  You will no
-    longer find pandoc's man pages in `man/`, but you can generate them using
-    `pandoc --man1 > pandoc.1` and `pandoc --man5 > pandoc_markdown.5`.
-
-  * Added new unexported module:  `Text.Pandoc.ManPages`.
-
-  * `README` now acts like a data file (even though it isn't in
-    `data/`).  So, for example, `pandoc --print-default-data-file README`
-    will produce the README.)  This change was required for the `--man1`
-    and `--man5` options, since the man pages are produced from the
-    README, but it may be useful for other purposes as well.
-
-  * Allow `reference.docx` and `reference.odt` to be used with
-    `--print-default-data-file` and to shadow defaults if placed in
-    the user data directory.  Note that as of 1.14, we no longer
-    include these files as data files; instead, we include their
-    components.  This change causes pandoc to behave as if it has
-    these data files; they are constructed on demand when needed
-    using `getDefaultReferenceDocx` and `getDefaultReferenceODT`.
-
-  * Fixed regression in CSS parsing with `--self-contained` (#2224).
-    Pandoc 1.14.0.x used css-text to parse the CSS, but its parser
-    silently drops big sections of CSS.  This commit replaces the
-    use of css-text with a small but principled CSS preprocessor,
-    which removes whitespace and comments and replaces `url()` with
-    base 64 data when possible.
-
-  * Use `https://` instead of `//` for MathJax and KaTeX CDN URLs (#1920).
-    This will allow math to work when pages are being viewed locally.
-
-  * `Text.Pandoc.Options`:  Export `plainExtensions`.
-    These are the extensions used in `plain` output.
-
-  * LaTeX reader: Don't parse `_` and `^` as sub/superscript outside of
-    math mode; treat them as regular inline text.  Normally these will
-    cause an error in LaTeX, but there are contexts (e.g. `alltt`
-    environments) where they are allowed.
-
-  * HTML reader:  allow `<body>` to close `<head>`.
-
-  * DocBook reader: support `mediaobject`s and `figures` (#2184, Mauro Bieg).
-
-  * RST reader: Fix reference names with special characters
-    (Lars-Dominik Braun).
-
-  * Textile writer:  escape `+` and `-` as entities (#2225).
-
-  * DokuWiki writer: Use proper `<code>` tags for code blocks (#2213).
-
-  * Plain writer:  don't use symbols for super/subscript (#2237).
-    Simplified code by using `plainExtensions`.
-
-  * InDesign writer: Properly escape URLs containing more than one
-    colon character (gohai).
-
-  * Docx writer: Make sure we use dist version of `reference.docx`
-    (and not the user's version) for certain settings.  Taking some
-    settings values from a user-supplied reference.docx can lead to
-    corruption.  This fixes a regression from the last release (#2249).
-
-  * `Text.Pandoc.Shared`: exports `getDefaultReferenceDocx` and
-    `getDefaultReferenceODT` (API change).  These functions have been
-    removed from the Docx and ODT writers.
-
-  * LaTeX template (Xavier Olive):
-    + Added `CJKmainfont` and `CJKoptions` variables.
-    + Allow dvipsnames (e.g. `MidnightBlue`) for colors (Xavier Olive).
-
-  * Epub templates:  use `author.role`, not `author.type`.
-
-  * Bump cmark version to >= 0.3.4.
-
-  * Improved Windows installer (#2205, thanks to nkalvi).
-    Users can now select a per-user or systemwide install, and can set
-    the installation path.  At the end of installation, the install location
-    is given.  The install location is also now given in the list of
-    installed programs in Control Panel.  Cleaner WiX syntax is used for
-    setting the path.
-
-  * Added `download_stats` target to Makefile.
-
-pandoc (1.14.0.4)
-
-  * Added missing commonmark template.
-
-  * Improved try pandoc (moved button, show raw command).
-
-pandoc (1.14.0.3)
-
-  * Allow compilation with syb 0.5.*.
-
-  * Custom writer:  fixed some compiler warnings for ghc < 7.10.
-
-pandoc (1.14.0.2)
-
-  * Allow building with hslua 0.4.
-
-pandoc (1.14.0.1)
-
-  * Fixed problem with building of `reference.docx` and `reference.odt`
-    when the `embed_data_files` flag is used.  Instead of having a phase
-    of the build where `reference.docx` and `reference.odt` are created
-    from their constituent data files, we now construct these archives
-    from their constituents when a `docx` or `odt` is built.  The
-    constituent files have been moved from `extra-source-files` to
-    `data-files`, and `reference.docx` and `reference.odt` have been
-    removed. Users can create their own `reference.docx` or
-    `reference.odt` by using pandoc to create a simple `docx` or `odt`.
-    `make-reference-files.hs` has been removed, simplifying the build
-    process (#2187)
-
-  * Don't include generated man pages in extra-source-files (#2189).
-
-  * Bumped upper bound for aeson.
-
-  * ConTeXt writer:  create internal link anchors for Div elements with
-    identifiers.  (This is needed for linked citations to work.)
-
-pandoc (1.14)
-
-  [new features]
-
-  * Added `commonmark` as input and output format.
-
-  * Added `--verbose` flag for debugging output in PDF production (#1840,
-    #1653).
-
-  * Allow wildcards in `--epub-embed-font` arguments (#1939).
-
-  * Added `--latex-engine-opt` option (#969, #1779, Sumit Sahrawat).
-
-  * Added `shortcut_reference_links` extension (Konstantin Zudov, #1977).
-    This is enabled by default for those markdown flavors that
-    support reading shortcut reference links, namely: `markdown`,
-    `markdown_strict`, `markdown_github`, `markdown_php`.
-    If the extension is enabled, the reader parses shortcut reference
-    links like `[foo]`, and the writer creates such links unless doing
-    so would cause problems.  Users of markdown flavors that support
-    shortcut reference links should not notice a difference in reading
-    markdown, but the markdown pandoc produces may differ.
-    If shortcut links are not desired, the extension can be disabled
-    in the normal way.
-
-  [behavior changes]
-
-  * `--toc` is now supported for `docx` output (#458, Nikolay Yakimov).
-    A "dirty" TOC is created at the beginning of document.
-    It can be regenerated after the document has been opened.
-
-  * An implicit `--filter pandoc-citeproc` is now triggered only when the
-    `--bibliography` option is used, and not when the `bibliography`
-    field in metadata is specified (#1849).
-
-  * Markdown reader:
-
-    + Reference links with `implicit_header_references` are no longer
-      case-sensitive (#1606).
-    + Definition lists no longer require indentation for first line (#2087).
-      Previously the body of the definition (after the `:` or `~` marker)
-      needed to be in column 4.  This commit relaxes that requirement,
-      to better match the behavior of PHP Markdown Extra.  So, now
-      this is a valid definition list:
-
-            foo
-            : bar
-    + Resolve a potentially ambiguity with table captions:
-
-            foo
-
-              : bar
-
-              -----
-              table
-              -----
-
-      Is "bar" a definition, or the caption for the table?  We'll count
-      it as a caption for the table.
-    + Disallow headerless pipe tables (#1996), to conform to GFM and PHP
-      Markdown Extra.  Note:  If you have been using headerless pipe tables,
-      this change may cause existing tables to break.
-    + Allow pipe tables with header but no body (#2017).
-    + Allow a digit as first character of a citation key (Matthias Troffaes).
-      See https://github.com/jgm/pandoc-citeproc/issues/97
-
-  * LaTeX reader:
-
-    + Don't limit includes to `.tex` extension (#1882).
-      If the extension is not `.tex`, it must be given explicitly in
-      the `\input` or `\include`.
-
-  * Docx reader:
-
-    + Allow numbering in the style file.  This allows inherited styles
-      with numbering (lists) (Jesse Rosenthal).
-
-  * Org reader:
-
-    + Support smart punctuation (Craig Bosma).
-    + Drop trees with a :noexport: tag (Albert Krewinkel). Trees having a
-      `:noexport:` tag set are not exported.  This mirrors org-mode.
-    + Put header tags into empty spans (Albert Krewinkel, #2160).
-      Org mode allows headers to be tagged: `* Headline  :TAG1:TAG2`.
-      Instead of being interpreted as part of the headline, the tags are now
-      put into the attributes of empty spans.  Spans without textual content
-      won't be visible by default, but they are detectable by filters.  They
-      can also be styled using CSS when written as HTML.
-    + Generalize code block result parsing (Albert Krewinkel).
-      Previously, only code blocks were recognized as result blocks;
-      now, any kind of block can be the result.
-
-  * Append newline to the LineBreak in Dokuwiki, HTML, EPUB,
-    LaTeX, MediaWiki, OpenDocument, Texinfo writers (#1924, Tim Lin).
-
-  * HTML writer:
-
-    + Add "inline" or "display" class to math spans (#1914).
-      This allows inline and display math to be styled differently.
-    + Include raw latex blocks if `--mathjax` specified (#1938).
-    + Require highlighting-kate >= 0.5.14 (#1903).
-      This ensures that all code blocks will be wrapped in a `div`
-      with class `sourceCode`.  Also, the default highlighting CSS
-      now adds `div.sourceCode { x-overflow: auto; }`, which means
-      that code blocks (even with line numbers) will acquire a scroll
-      bar on screens too small to display them (e.g. mobile phones).
-      See also jgm/highlighting-kate#65.
-
-  * LaTeX writer:
-
-    + Use a declaration for tight lists (Jose Luis Duran, Joseph
-      Harriott). Previously, pandoc hard-coded some commands to make
-      tight lists in LaTeX.  Now we use a custom command instead,
-      allowing the styling to be changed in a macro in the header.
-      (Note:  existing templates may need to be modified to include
-      the definition of this macro.  See the current template.)
-    + Beamer output: if the header introducing a slide has the
-      class `fragile`, add the `[fragile]` option to the slide (#2119).
-
-  * MediaWiki writer:
-
-    + Use `File:` instead of the deprecated `Image:` for images and
-      other media files (Greg Rundlett).
-
-  * DocBook writer:
-
-    + Render a `Div (id,_,_) [Para _]` element as a `para` element
-      with an `id` attribute.  This makes links to citations work in
-      DocBook with pandoc-citeproc.
-
-  * RST writer:
-
-    + Normalize headings to sequential levels (Nikolay Yakimov).
-      This is pretty much required by docutils.
-    + Treat headings in block quotes, etc as rubrics (Nikolay Yakimov).
-    + Better handling of raw latex inline (#1961).  We use
-      `` :raw-latex:`...` `` and add a definition for this role to
-      the template.
-
-  * EPUB writer:
-
-    + Remove `linear=no` from cover `itemref` (#1609).
-    + Don't use `sup` element for epub footnotes (#1995).
-      Instead, just use an a element with class `footnoteRef`.
-      This allows more styling options, and provides better results
-      in some readers (e.g. iBooks, where anything inside the a
-      tag breaks popup footnotes).
-    + Take TOC title from `toc-title` metadata field.
-
-  * Docx writer:
-
-    + Implemented `FirstParagraph` style (Jesse Rosenthal).
-      Following the ODT writer, we add the `FirstParagraph` style to the
-      first text paragraph following an image, blockquote, table, heading,
-      or beginning of document.  This allows it to be styled differently.
-      The default is for it to be the same as `Normal`.
-    + Added `BodyText` style (Jesse Rosenthal).
-      We apply a `BodyText` style to all unstyled paragraphs. This is,
-      essentially, the same as `Normal`, except that since not everything
-      inherits from `BodyText` (the metadata won't, for example, or
-      the headers or footnote numbers), we can change the text in the body
-      without having to make exceptions for everything.  If we do want to
-      change *everything*, we can still do it through `Normal`.
-    + Altered `Blockquote` style slightly (Jesse Rosenthal).
-      Since `BlockQuote` derives from `BodyText`, we just want to specify
-      by default that it won't indent, regardless of what `BodyText` does.
-      Note that this will not produce any visible difference in the default
-      configuration.
-    + Take TOC title from `toc-title` metadata field (Nikolay Yakimov).
-    + Added a style to figure images (Nikolay Yakimov).
-      Figures with empty captions use style `Figure`.
-      Figures with nonempty captions use style `Figure with Caption`, which
-      is based on `Figure`, and additionally has `keepNext` set.
-
-  * ODT writer:
-
-    + Added figure captions (Nikolay Yakimov). The following styles are
-      used for figures:
-      `Figure` -- for figure with empty caption),
-      `FigureWithCaption` (based on `Figure`) -- for figure with caption,
-      `FigureCaption` (based on `Caption`) -- for figure captions.
-      Also, `TableCaption` (based on `Caption`) is used for table captions.
-
-  [API changes]
-
-  * New `Text.Pandoc.Error` module with `PandocError` type
-    (Matthew Pickering).
-
-  * All readers now return `Either PandocError Pandoc` instead of `Pandoc`
-    (Matthew Pickering).  This allows better handling of errors.
-
-  * Added `Text.Pandoc.Writers.CommonMark`, exporting `writeCommonMark`.
-
-  * Added `Text.Pandoc.Readers.CommonMark`, exporting `readCommonMark`.
-
-  * Derive `Data` and `Typeable` instances for `MediaBag`, `Extension`,
-    `ReaderOptions`, `EPUBVersion`, `CiteMethod`, `ObfuscationMethod`,
-    `HTMLSlideVariant`, `TrackChanges`, `WriterOptions` (Shabbaz
-    Youssefi).
-
-  * New `Ext_shortcut_reference_links` constructor for `Extension`
-    (Konstantin Zudov).
-
-  [bug fixes]
-
-  * Markdown reader:
-
-    + Allow smart `'` after inline math (#1909, Nikolay Yakimov).
-    + Check for tex macros after indented code (#1973).
-    + Rewrote `charsInBalancedBrackets` for efficiency.
-    + Make sure a closing `</div>` doesn't get included in a
-      definition list item (#2127).
-    + Don't parse bracketed text as citation if it might be a link,
-      image, or footnote (Nikolay Yakimov).
-    + Require space after key in mmd title block (#2026, Nikolay
-      Yakimov).  Require space after key-value delimiter colon in mmd title
-      block.
-    + Require nonempty value in mmd title block (Nikolay Yakimov).
-    + Disable all metadata block extensions when parsing
-      metadata field values (#2026, Nikolay Yakimov).  Otherwise we
-      could get a mmd title block inside YAML metadata, for example.
-
-  * HTML reader:
-
-    + Improve self-closing tag detection in `htmlInBalanced` (#2146).
-    + Handle tables with `<th>` in body rows (#1859, Mauro Bieg).
-    + Fixed `htmlTag` (#1820).  If the tag parses as a comment, we check
-      to see if the input starts with `<!--`. If not, it's bogus comment
-      mode and we fail `htmlTag`.
-    + Handle `base` tag; if it has an `href` value, this is added to
-      all relative URLs in links and images.
-
-  * DocBook reader:
-
-    + Look inside "info" elements for section titles (#1931).
-
-  * Docx reader:
-
-    + Parse images in deprecated vml format (Jesse Rosenthal).
-    + Allow sub/superscript verbatims (Jesse Rosenthal).
-      Verbatim usually shuts off all other run styles, but we don't want it
-      to shut off sub/superscript.
-
-  * LaTeX reader:
-
-    + Handle `tabular*` environment (#1850).
-      Note that the table width is not actually parsed or taken into
-      account, but pandoc no longer chokes on it.
-    + Ignore options in `\lstinline` rather than raising error (#1997).
-    + Add some test cases for simple tables (Mathias Schenner).
-    + Handle valign argument in tables (Mathias Schenner) (currently
-      we just ignore this).
-    + Allow non-empty colsep in tables (Mathias Schenner).
-      The `tabular` environment allows non-empty column separators
-      with the "@{...}" syntax. Previously, pandoc would fail to
-      parse tables if a non-empty colsep was present. With this
-      commit, these separators are still ignored, but the table gets
-      parsed. A test case is included.
-    + Recognize `\newpage` as a block command.
-    + Allow block content in \title{} (#2001).
-    + Check for block-level newcommand aliases in blockCommand (Nikolay
-      Yakimov).
-    + Guard against paragraph starting with inline macro (Nikolay Yakimov).
-    + Properly gobble spaces after `\\` (#2007).
-
-  * Textile reader:
-
-    +  Handle newlines in table cells, and empty cells (#1919).
-
-  * Org reader:
-
-    + Allow image links with non-image targets (Hans-Peter Deifel).
-      This matches behavior of Org-Mode for links like
-      `[[http://example.com][https://www.haskell.org/static/img/logo.png]]`.
-
-  * Docbook writer:
-
-    + Don't print empty id attributes (thanks to Steve Horne).
-
-  * HTML writer:
-
-    + Fixed list-style-type for numbered example lists.
-      Should be "decimal," not "example" (#1902).
-    + Do not omit missing `alt` attribute on `img` tag (#1131,
-      Konstantin Zudov).
-    + Allow multiple colgroups in table (#2122).
-    + In revealjs, ensure that lists in speaker notes don't add "fragment"
-      classes, which can cause additional keypresses to be needed to
-      advance a slide (#1394).
-
-  * LaTeX writer:
-
-    + Don't escape `$` in URL (#1913).
-    + Don't use listings in headers (Matthew Pickering, #1963).
-    + Recognize book documentclass if set in metadata (#1971).
-      This sets `--chapters` implicitly if the documentclass in metadata
-      is a book documentclass.  Previously this was done only if a book
-      documentclass was set in a variable.
-    + Add a `\label` in `\hyperdef` for Div, Span (or links don't work).
-    + Make `mainlang` work when `lang` is in metadata (#2174).
-
-  * Texinfo writer:
-
-    + Fix wrapping by using breakable spaces (Tim Lin).
-
-  * RST writer:
-
-    + Fixed toc depth in RST writer.  Previously the depth was being
-      rendered as a floating point number with a decimal point.
-
-  * Markdown writer:
-
-    + Improved escaping (#2086).  `<` should not be escaped as `\<`, for
-      compatibility with original Markdown.  We now escape `<` and `>`
-      with entities.  Also, we now backslash-escape square brackets.
-    + Avoid introducing spurious list items through wrapping (#1946).
-    + Don't emit span tags if plain or raw HTML disabled.
-
-  * MediaWiki writer:
-
-    + Convert spaces to underscores in wikilink URL (#1982), like MediaWiki.
-
-  * AsciiDoc writer:
-
-    + Insert some needed blank lines (#1860).
-    + Avoid wrapping after list marker (#1858).
-
-  * EPUB writer:
-
-    + Properly handle internal links to IDs in spans, divs (#1884).
-    + Use plain writer for metadata dc: fields (#2121).
-      This gives better results when we have, e.g. multiple paragraphs.
-      Note that tags aren't allowed in these fields.
-    + Properly handle image links without an extension (#1855).
-    + Improved chapter splitting and internal link rewriting (#1887,
-      #2162, #2163).  This will ensure that internal links work and
-      that the references section produced by pandoc-citeproc is
-      in its own chapter.
-    + Fixed handling of svg images (#2183).
-
-  * ICML writer:
-
-    + Better handling of raw blocks and inlines (#1951).
-      Previously these were always escaped and printed verbatim.
-      Now they are ignored unless the format is `icml`, in which
-      case they are passed through unescaped.
-    + Fixed image URIs in ICML output (gohai).
-
-  * Custom writer:
-
-    + Raise error if loadstring returns an error status.
-    + Raise `PandocLuaException` instead of using 'error'.
-      Eventually we'll change the return type so that no exception
-      is involved, but at least this can be trapped.
-    + Use UTF-8 aware bytestring conversion.
-    + Set foreign encoding to UTF-8 (Nikolay Yakimov, #2101, #1634).
-      Also factored out ByteString, since it's only used as an intermediate
-      representation.
-
-  * Docx writer:
-
-    + Copy hyphenation settings from reference.docx (Nikolay Yakimov).
-    + Filter out illegal XML characters (#1992, Matthew Pickering).
-    + Added `noProof` to docx syntax highlighting `SourceCode` style.
-    + Added footnotes id -1 and 0 (Jesse Rosenthal).
-      Word uses, by default, footnotes with id -1 and 0 for separators. If a
-      user modifies `reference.docx`, they will end up with a `settings.xml`
-      file that references these footnotes, but no such footnotes in the
-      document. This will produce a corruption error. Here we add these to the
-      document and `settings.xml` file, so future modifications won't break
-      the file.
-    + Handle lists correctly inside table cells (Jesse Rosenthal).
-      Previously we didn't transform lists inside table cells.
-    + Set firstRow information in tables (Nikolay Yakimov).
-    + Don't replace `SourceCode` style in `reference.docx` if it is defined
-      there (Nikolay Yakimov, #1872).  If `--no-highlight` specified, remove
-      any `SourceCode` and `*Tok` styles in `reference.docx`.
-    + Attempt to match international style names (#1607, Nikolay Yakimov).
-    + Set these styles as custom (Nikolay Yakimov): `Author`, `Abstract`,
-      `Compact`, `Image Caption`, `Table Caption`, `Definition Term`,
-      `Definition`, `First Paragraph`.
-    + Rename these styles to correspond with Word `Normal.dotm` (Nikolay
-      Yakimov): `Block Quote -> Block Text`, `Link -> Hyperlink`,
-      `Footnote Ref -> Footnote Reference`.
-    + Added `Caption` style (Nikolay Yakimov).
-    + Changed these styles' inheritance (Nikolay Yakimov):
-      `Image Caption <- Caption`, `Table Caption <- Caption`.
-    + Remove `SourceCode` style from `reference.docx` (#1872).
-      This is added automatically by the docx writer.
-    + Added toc heading style to `reference.docx` (Nikolay Yakimov).
-
-  * `Text.Pandoc.PDF`
-
-    + Don't suggest "Try xelatex" if xelatex already in use (Mauro Bieg,
-      #1832).
-    + More comprehensible errors on image conversion (#2067).
-      EPS can't be supported without shelling out to something like
-      ImageMagick, but at least we can avoid mysterious error messages.
-
-  * `Text.Pandoc.Shared`:
-
-    + Make safeRead safe (#1801, Matthew Pickering).
-    + Addded `mapLeft`, `hush` (Matthew Pickering).
-
-  * `Text.Pandoc.Pretty`:
-
-    + Remove partial function (Matthew Pickering).
-
-  * `Text.Pandoc.SelfContained`:
-
-    + Add `;charset=utf-8` to script mime type if missing (#1842).
-    + Improved building of data URIs (#1940).  Now base64 is used except
-      for `text/*` mime types.
-    + `cssURLs` no longer tries to fetch fragment URLs (#2121).
-    + Properly handle data URIs in css urls (#2129).
-      Use a proper CSS parser (adds dependency on `text-css`).
-
-  * `Text.Pandoc.UTF8`:
-
-    + Better handling of bare CRs in input files (#2132).
-      Previously we just stripped them out; now we convert
-      other line ending styles to LF line endings.
-
-  * `Text.Pandoc.ImageSize`:
-
-    + Fixed some exif header parsing bugs (#1834).
-    + Make imageSize return an Either, not a Maybe (#1834).
-      Use `runGetOrFail` (with `binary >= 0.7`) to return `Left` on
-      parse failure (rather than `error`).
-    + Improved warnings when image size can't be determined.
-    + Removed error landmines (Matthew Pickering).
-
-  * Added woff2 to MIME types (Alfred Wechselberger).
-
-  * pandoc:  When a binary input format is used, warn that file
-    arguments past the first one are being ignored (Matthew Pickering).
-
-  [template changes]
-
-  * LaTeX template:
-
-    + Degrade gracefully if `\paragraph` not defined.
-    + Include `grffile` together with `graphicx` (#2074).
-      This properly handles filenames containing spaces and dots.
-    + Redefine `\paragraph`, `\subparagraph`...  to behave more
-      like section headers (#1658).
-    + Import hyperref before polyglossia to avoid an error with xelatex,
-      "please load package hyperref before bidi package" (Nick Bart).
-    + Added `toccolor` variable to control link color in toc (Kaixhin).
-
-  * LaTeX, Beamer templates:
-
-    + Provide `\tightlist`, which is now used by the LaTeX writer.
-    + Use polyglossia in beamer (#85).
-    + Use `bibliography` instead of `biblio-files`
-      (#1661).  Also use `\addbibresource` instead of `\bibliography` for
-      biblatex.
-    + Added `setotherlanguages` in polyglossia. This uses an `otherlang`
-      variable that is derived from a comma-separated list in `lang`;
-      the last language is `mainlang` and the others are `otherlang`.
-
-  * EPUB templates:
-
-    + Use `div`, not `p`, for "rights" on title page.
-    + Added header-includes, include-before, include-after (#1987).
-
-  * OpenDocument template:
-
-    + Use `text:p` instead of `text:h` for title.
-      Using `text:h` causes problems with numbering.  Closes #2059.
-      Thansk to @nkalvi for diagnosing this.
-
-  * reveal.js template:
-
-    + Link to non-minified css, js.  The minified versions no longer
-      ship with the library.
-    + Correctly include style CSS (#1949).
-    + New configurable options options: `center`, `maxScale`, `slideNuber`
-      (Dmitry Smirnov, pandoc-templates#89).
-    + Moved custom CSS after theme.  This allows custom CSS to modify
-      themes, instead of being replaced by them.
-    + Allow `center` to be set to false.
-
-  [under the hood improvements]
-
-  * Removed pre-built `reference.docx` and `reference.odt` (Nikolay
-    Yakimov).  Instead the repository now includes the component text files,
-    and the zipped binaries are built from these using a helper
-    program, `make-reference-files`.  This should make maintenance of
-    these components easier going forward.
-
-  * `Text.Pandoc.Parsing`:
-
-    + Added new `<+?>` combinator (Nikolay Yakimov).
-    + Added `stateHeaderKeys` to `ParserState`.
-
-  * `make_deb.sh` fixes:
-
-    + Detect architecture.
-    + Add Installed-Size to debian package control file (#1900).
-    + Use `fakeroot` to get permissions right.
-    + Use `mkdir` and `cp` instead of `install`.
-    + Set permissions of directories to 755.
-    + Install in `/usr` rather than `/usr/local`.
-    + Compress man pages.
-    + Combine copyright files for `pandoc`, `pandoc-citeproc`.
-
-  * Added `Text.Pandoc.Compat.Locale` and `old-locale` flag
-    to assist with transition to `time` 1.5.
-
-  * Updated CONTRIBUTING.md with information about issue tags (Matthew
-    Pickering).
-
-  * Updated travis installs to the new sudo-less syntax (Tim Lin).
-
-  * Updated dependency version bounds.
-
-  * EPUB tests:  don't use `joinPath`, which varies across platforms.
-    Instead, use a forward-slash to join paths, regardless of the
-    platform. This matches the way `MediaBag` now works.
-
-  * Clarify JSON input and output in usage message (Caleb McDaniel).
-
-  * Improved INSTALL instructions.
-
-  * Always build man pages.  Removed make-pandoc-man-pages flag.
-
-  * Makefile:  removed man target, now that we generate man pages by default.
-
-  * README:
-
-    + Fixed typos (J. Lewis Muir).
-    + Added documentation on backtick_code_blocks (#2135, Nikolay Yakimov).
-    + Added note on in-field markup in biblio databases (Nick Bart).
-    + Fixed misleading example of raw HTML block.
-    + Various minor formatting and consistency fixes for the program
-      options (Andreas Lööw).
-    + Made definition lists for options all "loose" for consistency.
-    + Added YAML biblio format to table, and note on `pandoc-citeproc`'s
-      `--bib2json` and `--bib2yaml` options (Nick Bart).
-    + Removed obsolete reference to `mods2yaml` (Nick Bart).
-    + Added section on syntax highlighting.
-    + Documented `toccolor` variable.
-
-pandoc (1.13.2.1)
-
-  * Updated to build with ghc 7.10.1.
-
-  * Bumped package upper bounds for filepath, blaze-html,
-    blaze-markup.
-
-pandoc (1.13.2)
-
-  * TWiki Reader: add new new twiki reader (API change, Alexander Sulfrian).
-
-  * Markdown reader:
-
-    + Better handling of paragraph in div (#1591).
-      Previously text that ended a div would be parsed as Plain
-      unless there was a blank line before the closing div tag.
-    + Don't treat a citation as a reference link label (#1763).
-    + Fix autolinks with following punctuation (#1811).
-      The price of this is that autolinked bare URIs can no longer
-      contain `>` characters, but this is not a big issue.
-    + Fix `Ext_lists_without_preceding_blankline` bug (#1636, Artyom).
-    + Allow `startnum` to work without `fancy_lists`. Formerly
-      `pandoc -f markdown-fancy_lists+startnum` did not work properly.
-
-  * RST reader (all Daniel Bergey):
-
-    + Parse quoted literal blocks (#65).  RST quoted literal blocks are
-      the same as indented literal blocks (which pandoc already supports)
-      except that the quote character is preserved in each line.
-    + Parse RST class directives. The class directive accepts one or more
-      class names, and creates a Div value with those classes.  If the
-      directive has an indented body, the body is parsed as the children of
-      the Div.  If not, the first block folowing the directive is made a
-      child of the Div. This differs from the behavior of rst2xml, which
-      does not create a Div element.  Instead, the specified classes are
-      applied to each child of the directive.  However, most Pandoc Block
-      constructors to not take an Attr argument, so we can't duplicate this
-      behavior.
-    + Warn about skipped directives.
-    + Literal role now produces Code. Code role should have "code" class.
-    + Improved support for custom roles
-
-        - Added `sourceCode` to classes for `:code:` role, and anything
-          inheriting from it.
-        - Add the name of the custom role to classes if the Inline
-          constructor supports Attr.
-        - If the custom role directive does not specify a parent role,
-          inherit from the `:span:` role.
-
-      This differs somewhat from the `rst2xml.py` behavior.  If a custom
-      role inherits from another custom role, Pandoc will attach both
-      roles' names as classes.  `rst2xml.py` will only use the class of
-      the directly invoked role (though in the case of inheriting from a
-      `:code:` role with a `:language:` defined, it will also provide the
-      inherited language as a class).
-    + Warn about ignored fields in role directives.
-
-  * LaTeX reader:
-
-    + Parse label after caption into a span instead of
-     inserting an additional paragraph of bracketed text (#1747).
-    + Parse math environments as inline when possible (#1821).
-    + Better handling of `\noindent` and `\greektext` (#1783).
-    + Handle `\texorpdfstring` more gracefully.
-    + Handle `\cref` and `\sep` (Wikiwide).
-    + Support `\smartcite` and `\Smartcite` from biblatex.
-
-  * HTML reader:
-
-    + Retain display type of MathML output (#1719, Matthew Pickering).
-    + Recognise `<br>` tags inside `<pre>` blocks (#1620, Matthew Pickering).
-    + Make `embed` tag either block or inline (#1756).
-
-  * DocBook reader:
-
-    + Handle `keycombo`, `keycap` (#1815).
-    + Get string content in inner tags for literal elements (#1816).
-    + Handle `menuchoice` elements better, with a `>` between (#1817).
-    + Include `id` on section headers (#1818).
-    + Document/test "type" as implemented (Brian O'Sullivan).
-    + Add support for calloutlist and callout (Brian O'Sullivan).
-      We treat a calloutlist as a bulleted list. This works well in practice.
-    + Add support for `classname` (Bryan O'Sullivan).
-
-  * Docx reader:
-
-    + Fix window path for image lookup (Jesse Rosenthal).
-      Don't use os-sensitive "combine", since we always want the paths in our
-      zip-archive to use forward-slashes.
-    + Single-item headers in ordered lists are headers (Jesse Rosenthal).
-      When users number their headers, Word understands that as a single item
-      enumerated list. We make the assumption that such a list is, in fact,
-      a header.
-    + Rewrite rewriteLink to work with new headers (Jesse Rosenthal).
-      There could be new top-level headers after making lists, so we have to
-      rewrite links after that.
-    + Use polyglot header list (Jesse Rosenthal).
-      We're just keeping a list of header formats that different languages
-      use as their default styles. At the moment, we have English, German,
-      Danish, and French. We can continue to add to this.
-      This is simpler than parsing the styles file, and perhaps less
-      error-prone, since there seems to be some variations, even within a
-      language, of how a style file will define headers.
-    + Remove header class properly in other langs (Jesse Rosenthal).
-      When we encounter one of the polyglot header styles, we want to remove
-      that from the par styles after we convert to a header. To do that, we
-      have to keep track of the style name, and remove it appropriately.
-    + Account for external link URLs with anchors. Previously, if a URL
-      had an anchor, the reader would incorrectly identify it as an
-      internal link and return only the anchor as URL. (Caleb McDaniel)
-    + Fix for Issue #1692 (i18n styles) (Nikolay Yakimov).
-
-  * Org reader:
-
-    + Added state changing blanklines (Jesse Rosenthal).
-      This allows us to emphasize at the beginning of a new paragraph (or, in
-      general, after blank lines).
-    + Fixed bug with bulleted lists:
-
-        - a
-        - b
-        * c
-
-      was being parsed as a list, even though an unindented `*`
-      should make a heading.  See
-      <http://orgmode.org/manual/Plain-lists.html#fn-1>.
-    + Org reader: absolute, relative paths in link (#1741, Albert
-      Krewinkel). The org reader was too restrictive when parsing links;
-      some relative links and links to files given as absolute paths
-      were not recognized correctly.
-    + Org reader:  allow empty links (jgm/gitit#471, Albert Krewinkel).
-      This is important for use in gitit, which uses empty links
-      for wikilinks.
-    + Respect indent when parsing Org bullet lists (#1650, Timothy
-      Humphries).  Fixes issue with top-level bullet list parsing.
-    + Fix indent issue for definition lists (Timothy Humphries,
-      see #1650, #1698, #1680).
-    + Parse multi-inline terms correctly in definition list (#1649,
-      Matthew Pickering).
-    + Fix rules for emphasis recognition (Albert Krewinkel).
-      Things like `/hello,/` or `/hi'/` were falsy recognized as emphasised
-      strings.  This is wrong, as `,` and `'` are forbidden border chars and
-      may not occur on the inner border of emphasized text.
-    + Drop COMMENT document trees (Albert Krewinkel).
-      Document trees under a header starting with the word `COMMENT` are
-      comment trees and should not be exported.  Those trees are dropped
-      silently (#1678).
-    + Properly handle links to `file:target` (Albert Krewinkel).
-      Org links like `[[file:target][title]]` were not handled correctly,
-      parsing the link target verbatim.  The org reader is changed such that
-      the leading `file:` is dropped from the link target (see #756, #1812).
-    + Parse LaTeX-style MathML entities (#1657, Albert Krewinkel).
-      Org supports special symbols which can be included using LaTeX syntax,
-      but are actually MathML entities.  Examples for this are
-      `\nbsp` (non-breaking space), `\Aacute` (the letter A with accent acute)
-      or `\copy` (the copyright sign ©)
-
-  * EPUB reader:
-
-    + URI handling improvements. Now we outsource most of the work to
-      `fetchItem'`. Also, do not include queries in file extensions (#1671).
-
-  * LaTeX writer:
-
-    + Use `\texorpdfstring` for section captions when needed (Vaclav Zeman).
-    + Handle consecutive linebreaks (#1733).
-    + Protect graphics in headers (Jesse Rosenthal).
-      Graphics in `\section`/`\subsection` etc titles need to be `\protect`ed.
-    + Put `~` before header in list item text (Jesse Rosenthal).
-      Because of the built-in line skip, LaTeX can't handle a section header
-      as the first element in a list item.
-    + Avoid using reserved characters as `\lstinline` delimiters (#1595).
-    + Better handling of display math in simple tables (#1754).
-      We convert display math to inline math in simple tables,
-      since LaTeX can't deal with display math in simple tables.
-    + Escape spaces in code (#1694, Bjorn Buckwalter).
-
-  * MediaWiki writer:
-
-    + Fixed links with URL = text. Previously these were rendered as bare
-      words, even if the URL was not an absolute URL (#1825).
-
-  * ICML writer:
-
-    + Don't force all citations into footnotes.
-
-  * RTF writer:
-
-    + Add blankline at end of output (#1732, Matthew Pickering).
-
-  * RST writer:
-
-    + Ensure blank line after figure.
-    + Avoid exces whitespace after last list item (#1777).
-    + Wrap line blocks with spaces before continuations (#1656).
-    + Fixed double-rendering of footnotes in RST tables (#1769).
-
-  * DokuWiki writer:
-
-    + Better handling of block quotes. This change ensures that
-      multiple paragraph blockquotes are rendered using native `>`
-      rather than as HTML (#1738).
-    + Fix external images (#1739). Preface relative links with ":",
-      absolute URIs without. (Timothy Humphries)
-
-  * HTML writer:
-
-    + Use protocol-relative URL for mathjax.
-    + Put newline btw img and caption paragraph.
-    + MathML now outputted with tex annotation (#1635, Matthew Pickering).
-    + Add support for KaTeX HTML math (#1626, Matthew Pickering).
-      This adds `KaTeX` to `HTMLMathMethod` (API change).
-    + Don't double render when `email-obfuscation=none` (#1625, Matthew
-      Pickering).
-    + Make header attributes work outside top level (#1711).
-      Previously they only appeared on top level header elements.
-      Now they work e.g. in blockquotes.
-
-  * ODT writer:
-
-    + Correctly handle images without extensions (#1729).
-    + Strip querystring in ODT write (#1682, Todd Sifleet).
-
-  * FB2 writer:
-
-    + Add newline to output.
-
-  * EPUB writer:
-
-    + Don't add `sourceURL` to absolute URIs (#1669).
-    + Don't use unsupported `opf:title-type` for epub2.
-    + Include "landmarks" section in nav document for epub3 (#1757).
-    + Removed playOrder from navpoint elements in ncx file (#1760).
-      These aren't required, and they make manual modification of epubs
-      difficult.
-    + Extract title even from structured title.
-    + Don't include nav node in spine unless `--toc` was requested.
-      Previously we included it in the spine with `linear="no"`, leading
-      to odd results in some readers (#1593).
-    + Fixed absolute URI detection (#1672).
-    + Correctly resolve relative URIs (#1671).
-    + Use regular page template for `nav.xhtml`, including doctype (#1759).
-
-  * Docx writer:
-
-    + Put docx table captions above tables (#1641, Nikolay Yakimov).
-    + Get the page width from the reference docx file, and use
-      it to scale images that are too large to fit (Grégory Bataille).
-    + Partial fix for #1607 (Nikolay Yakimov). International heading styles
-      are inferred based on `<w:name val="heading #">` fallback, if there
-      are no en-US "Heading#" styles
-    + Look in user data dir for archive `reference.docx`.
-    + Renumber header and footer relationships to avoid collisions (Jesse
-      Rosenthal). We previously took the old relationship names of the
-      headers and footer in secptr. That led to collisions. We now make
-      a map of availabl names in the relationships file, and then rename
-     in secptr.
-
-  * ConTeXt writer:
-
-    + Add function toLabel (Mark Szepieniec).
-      This function can be used to sanitize reference labels so that
-      they do not contain any of the illegal characters \#[]",{}%()|= .
-      Currently only Links have their labels sanitized, because they
-      are the only Elements that use passed labels.
-
-  * `Text.Pandoc.Shared`:
-
-    + Moved import of `toChunks` outside of CPP conditional (#1590).
-    + Fix `inDirectory` to reset to the original directory in case
-      an exception occurs (Freiric Barral).
-
-  * Templates:
-
-    + LaTeX template: load polyglossia before bibtex (jgm/pandoc-templates#70).
-      Thanks to bluebirch.
-    + LaTeX template: Added `\VerbatimFootnotes` if there is verbatim in notes
-      (#1616).
-    + LaTeX template:  Add shorthands=off to babel options (#1648).
-    + EPUB, EPUB3 templates: Added `id="cover"` to body of cover page.
-      This aids styling, making it possible for example to set 0 margins
-      on the title page (#1758).
-    + EPUB, EPUB3 templates:  Handle structured metadata on titlepage.
-      Previously we just expected 'title', 'subtitle', 'author', 'date'.
-      Now we still support those, but also support the format recommended
-      for epub metadata in the pandoc README:
-
-            ---
-            title:
-            - type: main
-              text: My Book
-            - type: subtitle
-              text: An investigation of metadata
-            creator:
-            - role: author
-              text: John Smith
-            - role: editor
-              text: Sarah Jones
-            identifier:
-            - scheme: DOI
-              text: doi:10.234234.234/33
-            publisher:  My Press
-            rights:  (c) 2007 John Smith, CC BY-NC
-            ...
-
-  * `Text.Pandoc.Templates.getDefaultTemplate`:
-    don't fail when called with "fb2" (#1660).
-
-  * `Text.Pandoc.Parsing`:
-
-    + Fixed `inlineMath` so it handles `\text{..}` containing `$`.
-      For example: `$x = \text{the $n$th root of $y$}` (#1677).
-    + Change `parseFromString` to fail if not all input is consumed.
-      (Matthew Pickering)
-    + Moved `addWarning` from Markdown reader to `Parsing`, so it can be
-      used by more readers (API change, Daniel Bergey).
-
-  * `Text.Pandoc.Pretty`:
-
-    +  Improve performance of `realLength` (Matthew Pickering).
-    +  Make CR + BLANKLINE = BLANKLINE. This fixes an extra blank line we
-       were getting at the end of markdown fragments (as well as rst, org,
-       etc.) (#1705).
-
-  * `Text.Pandoc.MIME`:
-
-    + Add mime type for WebVTT (Jason Ronallo).
-    + Changed mime type for `otf` to `application/vnd.ms-opentype` (#1761).
-      This is needed for epub3 validation.
-
-  * `Text.Pandoc.MediaBag`:
-
-    + Fix Windows specific path problems (#1597).
-
-  * `Text.Pandoc.Shared`:
-
-    + Make `collapseFilePath` OS-agnostic (Matthew Pickering).
-
-  * Link the test suite using `-threaded`.
-    This allows the test suite to be run using `+RTS -N`.
-
-  * Added `network` dependency under `network-uri` flag in test section.
-
-  * Give better error messages when someone tries to convert from
-    pdf, doc, odt (#1683).
-
-  * Added `track` to list of tags treated by `--self-contained` (#1664).
-
-pandoc (1.13.1)
-
-  * Fixed `--self-contained` with Windows paths (#1558).
-    Previously `C:\foo.js` was being wrongly interpreted as a URI.
-
-  * HTML reader:  improved handling of tags that can be block or inline.
-    Previously a section like this would be enclosed in a paragraph,
-    with RawInline for the video tags (since video is a tag that can
-    be either block or inline):
-
-        <video controls="controls">
-           <source src="../videos/test.mp4" type="video/mp4" />
-           <source src="../videos/test.webm" type="video/webm" />
-           <p>
-              The videos can not be played back on your system.<br/>
-              Try viewing on Youtube (requires Internet connection):
-              <a href="http://youtu.be/etE5urBps_w">Relative Velocity on
-        Youtube</a>.
-           </p>
-        </video>
-
-    This change will cause the video and source tags to be parsed
-    as RawBlock instead, giving better output.
-    The general change is this:  when we're parsing a "plain" sequence
-    of inlines, we don't parse anything that COULD be a block-level tag.
-
-  * Docx reader:
-
-    + Be sensitive to user styles.  Note that "Hyperlink" is
-      "blacklisted," as we don't want the default underline styling to be
-      inherited by all links by default (Jesse Rosenthal).
-    + Read single paragraph in table cell as `Plain` (Jesse Rosenthal).
-      This makes to docx reader's native output fit with the way the markdown
-      reader understands its markdown output.
-
-  * Textile writer:  Extended the range of cases where native textile
-    tables will be used (as opposed to raw HTML):  we now handle any
-    alignment type, but only for simple tables with no captions.
-
-  * Txt2Tags reader:
-
-    + Header is now parsed only if standalone flag is set (Matthew Pickering).
-    + The header is now parsed as meta information. The first line is the
-      `title`, the second is the `author` and third line is the `date`
-      (Matthew Pickering).
-    + Corrected formatting of `%%mtime` macro (Matthew Pickering).
-    + Fixed crash when reading from stdin.
-
-  * EPUB writer:  Don't use page-progression-direction in EPUB2, which
-    doesn't support it.  Also, if page-progression-direction not specified
-    in metadata, don't include the attribute even in EPUB3; not including it
-    is the same as including it with the value "default", as we did before.
-    (#1550)
-
-  * Org writer: Accept example lines with indentation at the beginning
-    (Calvin Beck).
-
-  * DokuWiki writer:
-
-    + Refactor to use Reader monad (Matthew Pickering).
-    + Avoid using raw HTML in table cells; instead, use `\\`
-      instead of newlines (Jesse Rosenthal).
-    + Properly handle HTML table cell alignments, and use spacing
-      to make the tables look prettier (#1566).
-
-  * Docx writer:
-
-    + Bibliography entries get `Bibliography` style (#1559).
-    + Implement change tracking (Jesse Rosenthal).
-
-  * LaTeX writer:
-
-    + Fixed a bug that caused a table caption to repeat across all pages
-      (Jose Luis Duran).
-    + Improved vertical spacing in tables and made it customizable using
-      standard lengths set by booktab.  See
-      <https://groups.google.com/forum/#!msg/pandoc-discuss/qMu6_5lYy0o/ZAU7lzAIKw0J>
-      (Jose Luis Duran).
-    + Added `\strut` to fix spacing in multiline tables (Jose Luis Duran).
-    + Use `\tabularnewline` instead of `\\` in table cells (Jose Luis Duran).
-    + Made horizontal rules more flexible (Jose Luis Duran).
-
-  * Text.Pandoc.MIME:
-
-    + Added `MimeType` (type synonym for `String`) and `getMimeTypeDef`.
-      Code cleanups (Artyom Kazak).
-
-  * Templates:
-
-    + LaTeX template: disable microtype protrusion for typewriter font (#1549,
-      thanks lemzwerg).
-
-  * Improved OSX build procedure.
-
-  * Added `network-uri` flag, to deal with split of `network-uri` from
-    `network`.
-
-  * Fix build dependencies for the `trypandoc` flag, so that they are
-    ignored if `trypandoc` flag is set to False (Gabor Pali).
-
-  * Updated README to remove outdated claim that `--self-contained`
-    looks in the user data directory for missing files.
-
-pandoc (1.13.0.1)
-
-  * Docx writer:
-
-    + Fixed regression which bungled list numbering (#1544), causing
-      all lists to appear as basic ordered lists.
-    + Include row width in table rows (Christoffer Ackelman, Viktor Kronvall).
-      Added a property to all table rows where the sum of column widths
-      is specified in pct (fraction of 5000).  This helps persuade Word
-      to lay out the table with the widths we specify.
-
-  * Fixed a bug in Windows 8 which caused pandoc not to find the
-    `pandoc-citeproc` filter (#1542).
-
-  * Docx reader: miscellaneous under-the-hood improvements (Jesse Rosenthal).
-    Most significantly, the reader now uses Builder, leading to some
-    performance improvements.
-
-  * HTML reader:  Parse appropriately styled span as SmallCaps.
-
-  * Markdown writer: don't escape `$`, `^`, `~` when `tex_math_dollars`,
-    `superscript`, and `subscript` extensions, respectively, are
-    deactivated (#1127).
-
-  * Added `trypandoc` flag to build CGI executable used in the online
-    demo.
-
-  * Makefile:  Added 'quick', 'osxpkg' targets.
-
-  * Updated README in templates to indicate templates license.
-    The templates are dual-licensed, BSD3 and GPL2+.
-
-pandoc (1.13)
-
-  [new features]
-
-  * Added `docx` as an input format (Jesse Rosenthal).  The docx
-    reader includes conversion of native Word equations to pandoc
-    LaTeX `Math` elements.  Metadata is taken from paragraphs at the
-    beginning of the document with styles `Author`, `Title`, `Subtitle`,
-    `Date`, and `Abstract`.
-
-  * Added `epub` as an input format (Matthew Pickering).  The epub
-    reader includes conversion of MathML to pandoc LaTeX `Math`
-    elements.
-
-  * Added `t2t` (Txt2Tags) as an input format (Matthew Pickering).
-    Txt2tags is a lightweight markup format described at
-    <http://txt2tags.org/>.
-
-  * Added `dokuwiki` as an output format (Clare Macrae).
-
-  * Added `haddock` as an output format.
-
-  * Added `--extract-media` option to extract media contained in a zip
-    container (docx or epub) while adjusting image paths to point to the
-    extracted images.
-
-  * Added a new markdown extension, `compact_definition_lists`, that
-    restores the syntax for definition lists of pandoc 1.12.x, allowing
-    tight definition lists with no blank space between items, and
-    disallowing lazy wrapping.  (See below under behavior changes.)
-
-  * Added an extension `epub_html_exts` for parsing HTML in EPUBs.
-
-  * Added extensions `native_spans` and `native_divs` to activate
-    parsing of material in HTML span or div tags as Pandoc Span
-    inlines or Div blocks.
-
-  * `--trace` now works with the Markdown, HTML, Haddock, EPUB,
-    Textile, and MediaWiki readers.  This is an option intended
-    for debugging parsing problems; ordinary users should not need
-    to use it.
-
-  [behavior changes]
-
-  * Changed behavior of the `markdown_attribute` extension, to bring
-    it in line with PHP markdown extra and multimarkdown.  Setting
-    `markdown="1"` on an outer tag affects all contained tags,
-    recursively, until it is reversed with `markdown="0"` (#1378).
-
-  * Revised markdown definition list syntax (#1429).  Both the reader
-    and writer are affected.  This change brings pandoc's definition list
-    syntax into alignment with that used in PHP markdown extra and
-    multimarkdown (with the exception that pandoc is more flexible about
-    the definition markers, allowing tildes as well as colons).  Lazily
-    wrapped definitions are now allowed.  Blank space is required
-    between list items.  The space before a definition is used to determine
-    whether it is a paragraph or a "plain" element.  **WARNING: This change
-    may break existing documents!**  Either check your documents for
-    definition lists without blank space between items, or use
-    `markdown+compact_definition_lists` for the old behavior.
-
-  * `.numberLines` now works in fenced code blocks even if no language
-    is given (#1287, jgm/highlighting-kate#40).
-
-  * Improvements to `--filter`:
-
-    + Don't search PATH for a filter with an explicit path.
-      This fixed a bug wherein `--filter ./caps.py` would run `caps.py` from
-      the system path, even if there was a `caps.py` in the working directory.
-    + Respect shebang if filter is executable (#1389).
-    + Don't print misleading error message.
-      Previously pandoc would say that a filter was not found,
-      even in a case where the filter had a syntax error.
-
-  * HTML reader:
-
-    + Parse `div` and `span` elements even without `--parse-raw`,
-      provided `native_divs` and `native_spans` extensions are set.
-      Motivation:  these now generate native pandoc Div and Span
-      elements, not raw HTML.
-    + Parse EPUB-specific elements if the `epub_html_exts`
-      extension is enabled.  These include `switch`, `footnote`,
-      `rearnote`, `noteref`.
-
-  * Org reader:
-
-    + Support for inline LaTeX.  Inline LaTeX is now accepted and parsed by the
-      org-mode reader.  Both math symbols (like `\tau`) and LaTeX commands (like
-      `\cite{Coffee}`), can be used without any further escaping (Albert
-      Krewinkel).
-
-  * Textile reader and writer:
-
-    + The `raw_tex` extension is no longer set by default.  You can
-      enable it with `textile+raw_tex`.
-
-  * DocBook reader:
-
-    + Support `equation`, `informalequation`, `inlineequation` elements with
-      `mml:math` content.  This is converted into LaTeX and put into a Pandoc
-      Math inline.
-
-  * Revised `plain` output, largely following the style of Project
-    Gutenberg:
-
-    + Emphasis is rendered with `_underscores_`, strong emphasis
-      with ALL CAPS.
-    + Headings are rendered differently, with space to set them off,
-      not with setext style underlines. Level 1 headers are ALL CAPS.
-    + Math is rendered using unicode when possible, but without the
-      distracting emphasis markers around variables.
-    + Footnotes use a regular `[n]` style.
-
-  * Markdown writer:
-
-    + Horizontal rules are now a line across the whole page.
-    + Prettier pipe tables.  Columns are now aligned  (#1323).
-    + Respect the `raw_html` extension.  `pandoc -t markdown-raw_html`
-      no longer emits any raw HTML, including span and div tags
-      generated by Span and Div elements.
-    + Use span with style for `SmallCaps` (#1360).
-
-  * HTML writer:
-
-    + Autolinks now have class `uri`, and email autolinks have class
-      `email`, so they can be styled.
-
-  * Docx writer:
-
-    + Document formatting is carried over from `reference.docx`.
-      This includes margins, page size, page orientation, header,
-      and footer, including images in headers and footers.
-    + Include abstract (if present) with `Abstract` style (#1451).
-    + Include subtitle (if present) with `Subtitle` style, rather
-      than tacking it on to the title (#1451).
-
-  * Org writer:
-
-    + Write empty span elements with an id attribute as org anchors.
-      For example `Span ("uid",[],[]) []` becomes `<<uid>>`.
-
-  * LaTeX writer:
-
-    + Put table captions above tables, to match the conventional
-      standard.  (Previously they appeared below tables.)
-    + Use `\(..\)` instead of `$..$` for inline math (#1464).
-    + Use `\nolinkurl` in email autolinks.  This allows them to be styled
-      using `\urlstyle{tt}`.  Thanks to Ulrike Fischer for the solution.
-    + Use `\textquotesingle` for `'` in inline code.  Otherwise we get
-      curly quotes in the PDF output (#1364).
-    + Use `\footnote<.>{..}` for notes in beamer, so that footnotes
-      do not appear before the overlays in which their markers appear
-      (#1525).
-    + Don't produce a `\label{..}` for a Div or Span element.  Do produce
-      a `\hyperdef{..}` (#1519).
-
-  * EPUB writer:
-
-    + If the metadata includes `page-progression-direction` (which can be
-      `ltr` or `rtl`, the `page-progression-direction` attribute will
-      be set in the EPUB spine (#1455).
-
-  * Custom lua writers:
-
-    + Custom writers now work with `--template`.
-    + Removed HTML header scaffolding from `sample.lua`.
-    + Made citation information available in lua writers.
-
-  * `--normalize` and `Text.Pandoc.Shared.normalize` now consolidate
-    adjacent `RawBlock`s when possible.
-
-  [API changes]
-
-  * Added `Text.Pandoc.Readers.Docx`, exporting `readDocx` (Jesse Rosenthal).
-
-  * Added `Text.Pandoc.Readers.EPUB`, exporting `readEPUB` (Matthew
-    Pickering).
-
-  * Added `Text.Pandoc.Readers.Txt2Tags`, exporting `readTxt2Tags` (Matthew
-    Pickering).
-
-  * Added `Text.Pandoc.Writers.DokuWiki`, exporting `writeDokuWiki`
-    (Clare Macrae).
-
-  * Added `Text.Pandoc.Writers.Haddock`, exporting `writeHaddock`.
-
-  * Added `Text.Pandoc.MediaBag`, exporting `MediaBag`, `lookupMedia`,
-    `insertMedia`, `mediaDirectory`, `extractMediaBag`.  The docx and epub
-    readers return a pair of a `Pandoc` document and a `MediaBag` with
-    the media resources they contain.  This can be extracted using
-    `--extract-media`.  Writers that incorporate media (PDF, Docx,
-    ODT, EPUB, RTF, or HTML formats with `--self-contained`) will look
-    for resources in the `MediaBag` generated by the reader, in addition to
-    the file system or web.
-
-  * `Text.Pandoc.Readers.TexMath`: Removed deprecated `readTeXMath`.
-    Renamed `readTeXMath'` to `texMathToInlines`.
-
-  * `Text.Pandoc`: Added `Reader` data type (Matthew Pickering).
-    `readers` now associates names of readers with `Reader`
-     structures.  This allows inclusion of readers, like the docx
-     reader, that take binary rather than textual input.
-
-  * `Text.Pandoc.Shared`:
-
-    + Added `capitalize` (Artyom Kazak), and replaced uses of
-      `map toUpper` (which give bad results for many languages).
-    + Added `collapseFilePath`, which removes intermediate `.` and
-      `..` from a path (Matthew Pickering).
-    + Added `fetchItem'`, which works like `fetchItem` but searches
-      a `MediaBag` before looking on the net or file system.
-    + Added `withTempDir`.
-    + Added `removeFormatting`.
-    + Added `extractSpaces` (from HTML reader) and generalized its type
-      so that it can be used by the docx reader (Matthew Pickering).
-    + Added `ordNub`.
-    + Added `normalizeInlines`, `normalizeBlocks`.
-    + `normalize` is now `Pandoc -> Pandoc` instead of
-      `Data a :: a -> a`.  Some users may need to change their uses of
-      `normalize` to the newly exported `normalizeInlines` or
-      `normalizeBlocks`.
-
-  * `Text.Pandoc.Options`:
-
-    + Added `writerMediaBag` to `WriterOptions`.
-    + Removed deprecated and no longer used `readerStrict` in
-      `ReaderOptions`.  This is handled by `readerExtensions` now.
-    + Added `Ext_compact_definition_lists`.
-    + Added `Ext_epub_html_exts`.
-    + Added `Ext_native_divs` and `Ext_native_spans`.
-      This allows users to turn off the default pandoc behavior of
-      parsing contents of div and span tags in markdown and HTML
-      as native pandoc Div blocks and Span inlines.
-
-  * `Text.Pandoc.Parsing`:
-
-    + Generalized `readWith` to `readWithM` (Matthew Pickering).
-    + Export `runParserT` and `Stream` (Matthew Pickering).
-    + Added `HasQuoteContext` type class (Matthew Pickering).
-    + Generalized types of `mathInline`, `smartPunctuation`, `quoted`,
-      `singleQuoted`, `doubleQuoted`, `failIfInQuoteContext`,
-      `applyMacros` (Matthew Pickering).
-    + Added custom `token` (Matthew Pickering).
-    + Added `stateInHtmlBlock` to `ParserState`.  This is used to keep
-      track of the ending tag we're waiting for when we're parsing inside
-      HTML block tags.
-    + Added `stateMarkdownAttribute` to `ParserState`. This is used
-      to keep track of whether the markdown attribute has been set in
-      an enclosing tag.
-    + Generalized type of `registerHeader`, using new type classes
-      `HasReaderOptions`, `HasIdentifierList`, `HasHeaderMap` (Matthew
-      Pickering).  These allow certain common functions to be reused
-      even in parsers that use custom state (instead of `ParserState`),
-      such as the MediaWiki reader.
-    + Moved `inlineMath`, `displayMath` from Markdown reader to Parsing,
-      and generalized their types (Matthew Pickering).
-
-  * `Text.Pandoc.Pretty`:
-
-    + Added `nestle`.
-    + Added `blanklines`, which guarantees a certain number of blank lines
-      (and no more).
-
-  [bug fixes]
-
-  * Markdown reader:
-
-    + Fixed parsing of indented code in list items.  Indented code
-      at the beginning of a list item must be indented eight spaces
-      from the margin (or edge of the container), or four spaces
-      from the list marker, whichever is greater.
-    + Fixed small bug in HTML parsing with `markdown_attribute`, which
-      caused incorrect tag nesting for input like
-      `<aside markdown="1">*hi*</aside>`.
-    + Fixed regression with intraword underscores (#1121).
-    + Improved parsing of inline links containing quote characters (#1534).
-    + Slight rewrite of `enclosure`/`emphOrStrong` code.
-    + Revamped raw HTML block parsing in markdown (#1330).
-      We no longer include trailing spaces and newlines in the
-      raw blocks.  We look for closing tags for elements (but without
-      backtracking).  Each block-level tag is its own `RawBlock`;
-      we no longer try to consolidate them (though `--normalize` will do so).
-    + Combine consecutive latex environments.  This helps when you have
-      two minipages which can't have blank lines between them (#690, #1196).
-    + Support smallcaps through span.
-      `<span style="font-variant:small-caps;">foo</span>` will be
-      parsed as a `SmallCaps` inline, and will work in all output
-      formats that support small caps (#1360).
-    + Prevent spurious line breaks after list items (#1137).  When the
-      `hard_line_breaks` option was specified, pandoc would formerly
-      produce a spurious line break after a tight list item.
-    + Fixed table parsing bug (#1333).
-    + Handle `c++` and `objective-c` as language identifiers in
-      github-style fenced blocks (#1318).
-    + Inline math must have nonspace before final `$` (#1313).
-
-  * LaTeX reader:
-
-    + Handle comments at the end of tables.  This resolves the issue
-      illustrated in <http://stackoverflow.com/questions/24009489>.
-    + Correctly handle table rows with too few cells.  LaTeX seems to
-      treat them as if they have empty cells at the end  (#241).
-    + Handle leading/trailing spaces in `\emph` better.
-      `\emph{ hi }` gets parsed as `[Space, Emph [Str "hi"], Space]`
-      so that we don't get things like `* hi *` in markdown output.
-      Also applies to `\textbf` and some other constructions (#1146).
-    + Don't assume preamble doesn't contain environments (#1338).
-    + Allow (and discard) optional argument for `\caption` (James Aspnes).
-
-  * HTML reader:
-
-    + Fixed major parsing problem with HTML tables.  Table cells were
-      being combined into one cell (#1341).
-    + Fixed performance issue with malformed HTML tables.
-      We let a `</table>` tag close an open `<tr>` or `<td>` (#1167).
-    + Allow space between `<col>` and `</col>`.
-    + Added `audio` and `source` in `eitherBlockOrInline`.
-    + Moved `video`, `svg`, `progress`, `script`, `noscript`, `svg` from
-      `blockTags` to `eitherBlockOrInline`.
-    + `map` and `object` were mistakenly in both lists; they have been removed
-      from `blockTags`.
-    + Ignore `DOCTYPE` and `xml` declarations.
-
-  * MediaWiki reader:
-
-    + Don't parse backslash escapes inside `<source>` (#1445).
-    + Tightened up template parsing.
-      The opening `{{` must be followed by an alphanumeric or `:`.
-      This prevents the exponential slowdown in #1033.
-    + Support "Bild" for images.
-
-  * DocBook reader:
-
-    + Better handle elements inside code environments.  Pandoc's document
-      model does not allow structure inside code blocks, but at least this way
-      we preserve the text (#1449).
-    + Support `<?asciidoc-br?>` (#1236).
-
-  * Textile reader:
-
-    + Fixed list parsing. Lists can now start without an intervening
-      blank line (#1513).
-    + HTML block-level tags that do not start a line are parsed as
-      inline HTML and do not interrupt paragraphs (as in RedCloth).
-
-  * Org reader:
-
-    + Make tildes create inline code (#1345).  Also relabeled `code` and
-      `verbatim` parsers to accord with the org-mode manual.
-    + Respect `:exports` header argument in code blocks (Craig Bosma).
-    + Fixed tight lists with sublists (#1437).
-
-  * EPUB writer:
-
-    + Avoid excess whitespace in `nav.xhtml`.  This should improve
-      TOC view in iBooks (#1392).
-    + Fixed regression on cover image.
-      In 1.12.4 and 1.12.4.2, the cover image would not appear properly,
-      because the metadata id was not correct.  Now we derive the id from the
-      actual cover image filename, which we preserve rather than using
-      "cover-image."
-    + Keep newlines between block elements.  This allows
-      easier diff-ability (#1424).
-    + Use `stringify` instead of custom `plainify`.
-    + Use `renderTags'` for all tag rendering.  This properly handles tags
-      that should be self-closing.  Previously `<hr/>` would appear in EPUB
-      output as `<hr></hr>` (#1420).
-    + Better handle HTML media tags.
-    + Handle multiple dates with OPF `event` attributes.  Note: in EPUB3 we
-      can have only one dc:date, so only the first one is used.
-
-  * LaTeX writer:
-
-    + Correctly handle figures in notes.  Notes can't contain figures in
-      LaTeX, so we fake it to avoid an error  (#1053).
-    + Fixed strikeout + highlighted code (#1294).
-      Previously strikeout highlighted code caused an error.
-
-  * ConTeXt writer:
-
-    + Improved detection of autolinks with URLs containing escapes.
-
-  * RTF writer:
-
-    + Improved image embedding: `fetchItem'` is now used to get the
-      images, and calculated image sizes are indicated in the RTF.
-    + Avoid extra paragraph tags in metadata (#1421).
-
-  * HTML writer:
-
-    + Deactivate "incremental" inside slide speaker notes (#1394).
-    + Don't include empty items in the table of contents for
-      slide shows.  (These would result from creating a slide
-      using a horizontal rule.)
-
-  * MediaWiki writer:
-
-    + Minor renaming of `st` prefixed names.
-
-  * AsciiDoc writer:
-
-    + Double up emphasis and strong emphasis markers in intraword
-      contexts, as required by asciidoc (#1441).
-
-  * Markdown writer:
-
-    + Avoid wrapping that might start a list, blockquote, or header (#1013).
-    + Use Span instead of (hackish) `SmallCaps` in `plainify`.
-    + Don't use braced attributes for fenced code (#1416).
-      If `Ext_fenced_code_attributes` is not set, the first class
-      attribute will be printed after the opening fence as a bare word.
-    + Separate adjacent lists of the same kind with an HTML comment (#1458).
-
-  * PDF writer:
-
-    + Fixed treatment of data uris for images (#1062).
-
-  * Docx writer:
-
-    + Use Compact style for empty table cells (#1353).
-      Otherwise we get overly tall lines when there are empty
-      table cells and the other cells are compact.
-    + Create overrides per-image for `media/` in reference docx.
-      This should be somewhat more robust and cover more types of images.
-    + Improved `entryFromArchive` to avoid an unneeded parse.
-    + Section numbering carries over from reference.docx (#1305).
-    + Simplified `abstractNumId` numbering.  Instead of sequential numbering,
-      we assign numbers based on the list marker styles.
-
-  * `Text.Pandoc.Options`:
-
-    + Removed `Ext_fenced_code_attributes` from `markdown_github`
-      extensions.
-
-  * `Text.Pandoc.ImageSize`:
-
-    + Use default instead of failing if image size not found
-      in exif header (#1358).
-    + ignore unknown exif header tag rather than crashing.
-      Some images seem to have tag type of 256, which was causing
-      a runtime error.
-
-  * `Text.Pandoc.Shared`:
-
-    + `fetchItem`:  unescape URI encoding before reading local file (#1427).
-    + `fetchItem`:  strip a fragment like `?#iefix` from the extension before
-      doing mime lookup, to improve mime type guessing.
-    + Improved logic of `fetchItem`:  absolute URIs are fetched from the net;
-      other things are treated as relative URIs if `sourceURL` is `Just _`,
-      otherwise as file paths on the local file system.
-    + `fetchItem` now properly handles links without a protocol (#1477).
-    + `fetchItem` now escapes characters not allowed in URIs before trying
-      to parse the URIs.
-    + Fixed runtime error with `compactify'DL` on certain lists (#1452).
-
-  * `pandoc.hs`: Don't strip path off of `writerSourceURL`: the path is
-    needed to resolve relative URLs when we fetch resources (#750).
-
-  * `Text.Pandoc.Parsing`
-
-    + Simplified `dash` and `ellipsis` (#1419).
-    + Removed `(>>~)` in favor of the equivalent `(<*)` (Matthew Pickering).
-    + Generalized functions to use `ParsecT` (Matthew Pickering).
-    + Added `isbn` and `pmid` to list of recognized schemes (Matthew
-      Pickering).
-
-  [template changes]
-
-  * Added haddock template.
-  * EPUB3:  Added `type` attribute to `link` tags.  They are supposed to
-    be "advisory" in HTML5, but kindlegen seems to require them.
-  * EPUB3:  Put title page in section with `epub:type="titlepage"`.
-  * LaTeX: Made `\subtitle` work properly (#1327).
-  * LaTeX/Beamer: remove conditional around date (#1321).
-  * LaTeX:  Added `lot` and `lof` variables, which can be set to
-    get `\listoftables` and `\listoffigures` (#1407).  Note that
-    these variables can be set at the command line with `-Vlot -Vlof`
-    or in YAML metadata.
-
-  [under the hood improvements]
-
-  * Rewrote normalize for efficiency (#1385).
-
-  * Rewrote Haddock reader to use `haddock-library` (#1346).
-
-    + This brings pandoc's rendering of haddock markup in line
-      with the new haddock.
-    + Fixed line breaks in `@` code blocks.
-    + alex and happy are no longer build-depends.
-
-  * Added `Text.Pandoc.Compat.Directory` to allow building against
-    different versions of the `directory` library.
-
-  + Added `Text.Pandoc.Compat.Except` to allow building against
-    different verions of `mtl`.
-
-  * Code cleanup in some writers, using Reader monad to avoid
-    passing options parameter around (Matej Kollar).
-
-  * Improved readability in `pandoc.hs`.
-
-  * Miscellaneous code cleanups (Artyom Kazak).
-
-  * Avoid `import Prelude hiding (catch)` (#1309, thanks to Michael
-    Thompson).
-
-  * Changed `http-conduit` flag to `https`.  Depend on `http-client`
-    and `http-client-tls` instead of `http-conduit`.  (Note:  pandoc still
-    depends on `conduit` via `yaml`.)
-
-  * Require `highlighting-kate >= 0.5.8.5` (#1271, #1317, Debian #753299).
-    This change to highlighting-kate means that PHP fragments no longer need
-    to start with `<?php`.  It also fixes a serious bug causing failures with
-    ocaml and fsharp.
-
-  * Require latest `texmath`.  This fixes `\tilde{E}` and allows
-    `\left` to be used with `]`, `)` etc. (#1319), among many other
-    improvements.
-
-  * Require latest `zip-archive`.  This has fixes for unicode path names.
-
-  * Added tests for plain writer.
-
-  * `Text.Pandoc.Templates`:
-
-    + Fail informatively on template syntax errors.
-      With the move from parsec to attoparsec, we lost good error
-      reporting.  In fact, since we weren't testing for end of input,
-      malformed templates would fail silently.  Here we revert back to
-      Parsec for better error messages.
-    + Use `ordNub` (#1022).
-
-  * Benchmarks:
-
-    + Made benchmarks compile again (Artyom Kazak).
-    + Fixed so that the failure of one benchmark does not prevent others
-      from running (Artyom Kazak).
-    + Use `nfIO` instead of the `getLength` trick to force full evaluation.
-    + Changed benchmark to use only the test suite, so that benchmarks
-      run more quickly.
-
-  * Windows build script:
-
-    + Add `-windows` to file name.
-    + Use one install command for pandoc, pandoc-citeproc.
-    + Force install of pandoc-citeproc.
-
-  * `make_osx_package`:  Call zip file `pandoc-VERSION-osx.zip`.
-    The zip should not be named `SOMETHING.pkg.zip`, or OSX finder
-    will extract it into a folder named `SOMETHING.pkg`, which it
-    will interpret as a defective package (#1308).
-
-  * `README`:
-
-    + Made headers for all extensions so they have IDs and can be
-      linked to (Beni Cherniavsky-Paskin).
-    + Fixed typos (Phillip Alday).
-    + Fixed documentation of attributes (#1315).
-    + Clarified documentation on small caps (#1360).
-    + Better documentation for `fenced_code_attributes` extension
-      (Caleb McDaniel).
-    + Documented fact that you can put YAML metadata in a separate file
-      (#1412).
-
-
-pandoc (1.12.4.2)
-
-  * Require highlighting-kate >= 0.5.8.  Fixes a performance regression.
-
-  * Shared:  `addMetaValue` now behaves slightly differently:
-    if both the new and old values are lists, it concatenates their
-    contents to form a new list.
-
-  * LaTeX reader:
-
-    + Set `bibliography` in metadata from `\bibliography` or
-      `\addbibresource` command.
-    + Don't error on `%foo` with no trailing newline.
-
-  * Org reader:
-
-    + Support code block headers (`#+BEGIN_SRC ...`) (Albert Krewinkel).
-    + Fix parsing of blank lines within blocks (Albert Krewinkel).
-    + Support pandoc citation extension (Albert Krewinkel).  This can
-      be turned off by specifying `org-citations` as the input format.
-
-  * Markdown reader:
-
-    + `citeKey` moved to `Text.Pandoc.Parsing` so it can be used by
-      other readers (Albert Krewinkel).
-
-  * `Text.Pandoc.Parsing`:
-
-    + Added `citeKey` (see above).
-    + Added `HasLastStrPosition` type class and `updateLastStrPos`
-      and `notAfterString` functions.
-
-  * Updated copyright notices (Albert Krewinkel).
-
-  * Added default.icml to data files so it installs with the package.
-
-  * OSX package:
-
-    + The binary is now built with options to ensure that it can be
-      used with OSX 10.6+.
-    + Moved OSX package materials to osx directory.
-    + Added OSX package uninstall script, included in the zip container
-      (thanks to Daniel T. Staal).
-
-pandoc (1.12.4)
-
-  * Made it possible to run filters that aren't executable (#1096).
-    Pandoc first tries to find the executable (searching the path
-    if path isn't given).  If it fails, but the file exists and has
-    a `.py`, `.pl`, `.rb`, `.hs`, or `.php` extension, pandoc runs the filter
-    using the appropriate interpreter.  This should make it easier to
-    use filters on Windows, and make it more convenient for everyone.
-
-  * Added Emacs org-mode reader (Albert Krewinkel).
-
-  * Added InDesign ICML Writer (Mauro Bieg).
-
-  * MediaWiki reader:
-
-    + Accept image links in more languages (Jaime Marquínez Ferrándiz).
-    + Fixed bug in certain nested lists (#1213).  If a level 2 list was
-      followed by a level 1 list, the first item of the level 1 list
-      would be lost.
-    + Handle table rows containing just an HTML comment (#1230).
-
-  * LaTeX reader:
-
-    + Give better location information on errors, pointing to line
-      numbers within included files (#1274).
-    + LaTeX reader:  Better handling of `table` environment (#1204).
-      Positioning options no longer rendered verbatim.
-    + Better handling of figure and table with caption (#1204).
-    + Handle `@{}` and `p{length}` in tabular.  The length is not actually
-      recorded, but at least we get a table (#1180).
-    + Properly handle `\nocite`.  It now adds a `nocite` metadata
-      field.  Citations there will appear in the bibliography but not
-      in the text (unless you explicitly put a `$nocite$` variable
-      in your template).
-
-  * Markdown reader:
-
-    + Ensure that whole numbers in YAML metadata are rendered without
-      decimal points.  (This became necessary with changes to aeson
-      and yaml libraries.  aeson >= 0.7 and yaml >= 0.8.8.2 are now required.)
-    + Fixed regression on line breaks in strict mode (#1203).
-    + Small efficiency improvements.
-    + Improved parsing of nested `div`s.  Formerly a closing `div` tag
-      would be missed if it came right after other block-level tags.
-    + Avoid backtracking when closing `</div>` not found.
-    + Fixed bug in reference link parsing in `markdown_mmd`.
-    + Fixed a bug in list parsing (#1154).  When reading a raw list
-      item, we now strip off up to 4 spaces.
-    + Fixed parsing of empty reference link definitions (#1186).
-    + Made one-column pipe tables work (#1218).
-
-  * Textile reader:
-
-    + Better support for attributes.  Instead of being ignored, attributes
-      are now parsed and included in Span inlines.  The output will be a bit
-      different from stock textile: e.g. for `*(foo)hi*`, we'll get
-      `<em><span class="foo">hi</span></em>` instead of
-      `<em class="foo">hi</em>`.  But at least the data is not lost.
-    + Improved treatment of HTML spans (%) (#1115).
-    + Improved link parsing.  In particular we now pick up on attributes.
-      Since pandoc links can't have attributes, we enclose the whole link in
-      a span if there are attributes (#1008).
-    + Implemented correct parsing rules for inline markup (#1175, Matthew
-      Pickering).
-    + Use Builder (Matthew Pickering).
-    + Fixed list parsing bug (#1500).
-    + Don't allow inline formatting to extend over newlines.
-      This matches the behavior of RedCarpet, avoids some ugly bugs,
-      and improves performance.
-
-  * DocBook reader:
-
-    + Better treatment of `formalpara`.  We now emit the title (if present)
-      as a separate paragraph with boldface text (#1215).
-    + Set metadata `author` not `authors`.
-    + Added recognition of `authorgroup` and `releaseinfo` elements (#1214,
-      Matthew Pickering).
-    + Converted current meta information parsing in DocBook to a more
-      extensible version which is aware of the more recent meta
-      representation (Matthew Pickering).
-
-  * HTML reader:
-
-    + Require tagsoup 0.13.1, to fix a bug with parsing of script tags
-      (#1248).
-    + Treat processing instructions & declarations as block.  Previously
-      these were treated as inline, and included in paragraph tags in HTML
-      or DocBook output, which is generally not what is wanted (#1233).
-    + Updated `closes` with rules from HTML5 spec.
-    + Use Builder (Matthew Pickering, #1162).
-
-  * RST reader:
-
-    + Remove duplicate `http` in PEP links (Albert Krewinkel).
-    + Make rst figures true figures (#1168, CasperVector)
-    + Enhanced Pandoc's support for rST roles (Merijn Verstaaten).
-      rST parser now supports: all built-in rST roles, new role definition,
-      role inheritance, though with some limitations.
-    + Use `author` rather than `authors` in metadata.
-    + Better handling of directives.  We now correctly handle field
-      lists that are indented more than three spaces.  We treat an
-      `aafig` directive as a code block with attributes, so it can be
-      processed in a filter (#1212).
-
-  * LaTeX writer:
-
-    + Mark span contents with label if span has an ID (Albert Krewinkel).
-    + Made `--toc-depth` work well with books in latex/pdf output (#1210).
-    + Handle line breaks in simple table cells (#1217).
-    + Workaround for level 4-5 headers in quotes.  These previously produced
-      invalid LaTeX: `\paragraph` or `\subparagraph` in a `quote` environment.
-      This adds an `mbox{}` in these contexts to work around the problem.
-      See <http://tex.stackexchange.com/a/169833/22451> (#1221).
-    + Use `\/` to avoid en-dash ligature instead of `-{}-` (Vaclav Zeman).
-      This is to fix LuaLaTeX output. The `-{}-` sequence does not avoid the
-      ligature with LuaLaTeX but `\/` does.
-    + Fixed string escaping in `hyperref` and `hyperdef` (#1130).
-
-  * ConTeXt writer:  Improved autolinks (#1270).
-
-  * DocBook writer:
-
-    + Improve handling of hard line breaks in Docbook writer
-      (Neil Mayhew).  Use a `<literallayout>` for the entire paragraph, not
-      just for the newline character.
-    + Don't let line breaks inside footnotes influence the enclosing
-      paragraph (Neil Mayhew).
-    + Distinguish tight and loose lists in DocBook output, using
-      `spacing="compact"` (Neil Mayhew, #1250).
-
-  * Docx writer:  When needed files are not present in the user's
-    `reference.docx`, fall back on the versions in the `reference.docx`
-    in pandoc's data files. This fixes a bug that occurs when a
-    `reference.docx` saved by LibreOffice is used. (#1185)
-
-  * EPUB writer:
-
-    + Include extension in epub ids.  This fixes a problem with duplicate
-      extensions for fonts and images with the same base name but different
-      extensions (#1254).
-    + Handle files linked in raw `img` tags (#1170).
-    + Handle media in `audio` source tags (#1170).
-      Note that we now use a `media` directory rather than `images`.
-    + Incorporate files linked in `video` tags (#1170).  `src` and `poster`
-      will both be incorporated into `content.opf` and the epub container.
-
-  * HTML writer:
-
-    + Add colgroup around col tags (#877).  Also affects EPUB writer.
-    + Fixed bug with unnumbered section headings.  Unnumbered section
-      headings (with class `unnumbered`) were getting numbers.
-    + Improved detection of image links. Previously image links with
-      queries were not recognized, causing `<embed>` to be used instead
-      of `<img>`.
-
-  * Man writer:  Ensure that terms in definition lists aren't line wrapped
-    (#1195).
-
-  * Markdown writer:
-
-    + Use proper escapes to avoid unwanted lists (#980).  Previously we used
-      0-width spaces, an ugly hack.
-    + Use longer backtick fences if needed (#1206).  If the content contains a
-      backtick fence and there are attributes, make sure longer fences are
-      used to delimit the code.  Note:  This works well in pandoc, but github
-      markdown is more limited, and will interpret the first string of three
-      or more backticks as ending the code block.
-
-  * RST writer:  Avoid stack overflow with certain tables (#1197).
-
-  * RTF writer:  Fixed table cells containing paragraphs.
-
-  * Custom writer:
-
-    + Correctly handle UTF-8 in custom lua scripts (#1189).
-    + Fix bugs with lua scripts with mixed-case filenames and
-      paths containing `+` or `-` (#1267).  Note that `getWriter`
-      in `Text.Pandoc` no longer returns a custom writer on input
-      `foo.lua`.
-
-  * AsciiDoc writer:  Handle multiblock and empty table cells
-    (#1245, #1246).  Added tests.
-
-  * `Text.Pandoc.Options`: Added `readerTrace` to `ReaderOptions`
-
-  * `Text.Pandoc.Shared`:
-
-    + Added `compactify'DL` (formerly in markdown reader) (Albert Krewinkel).
-    + Fixed bug in `toRomanNumeral`:  numbers ending with '9' would
-      be rendered as Roman numerals ending with 'IXIV' (#1249).  Thanks to
-      Jesse Rosenthal.
-    + `openURL`: set proxy with value of http_proxy env variable (#1211).
-      Note:  proxies with non-root paths are not supported, due to
-      limitations in `http-conduit`.
-
-  * `Text.Pandoc.PDF`:
-
-    + Ensure that temp directories deleted on Windows (#1192).  The PDF is
-      now read as a strict bytestring, ensuring that process ownership will
-      be terminated, so the temp directory can be deleted.
-    + Use `/` as path separators in a few places, even on Windows.
-      This seems to be necessary for texlive (#1151, thanks to Tim Lin).
-    + Use `;` for `TEXINPUTS` separator on Windows (#1151).
-    + Changes to error reporting, to handle non-UTF8 error output.
-
-  * `Text.Pandoc.Templates`:
-
-    + Removed unneeded datatype context (Merijn Verstraaten).
-
-    + YAML objects resolve to "true" in conditionals (#1133).
-      Note:  If `address` is a YAML object and you just have `$address$`
-      in your template, the word `true` will appear, which may be
-      unexpected.  (Previously nothing would appear.)
-
-  * `Text.Pandoc.SelfContained`:
-
-    + `mkSelfContained` now takes just two arguments, `WriterOptions` and
-      the string.
-    * It no longer looks in data files.  This only made sense when we
-      had copies of slidy and S5 code there.
-    * `fetchItem'` is used instead of the nearly duplicate `getItem`.
-    + Handle `poster` attribute in `video` tags (#1188).
-
-  * `Text.Pandoc.Parsing`:
-
-    + Made `F` an instance of Applicative (#1138).
-    + Added `stateCaption`.
-    + Added `HasMacros`, simplified other typeclasses.
-      Removed `updateHeaderMap`, `setHeaderMap`, `getHeaderMap`,
-      `updateIdentifierList`, `setIdentifierList`, `getIdentifierList`.
-    + Changed the smart punctuation parser to return `Inlines`
-      rather than `Inline` (Matthew Pickering).
-    + Changed `HasReaderOptions`, `HasHeaderMap`, `HasIdentifierList`
-      from typeclasses of monads to typeclasses of states.  This simplifies
-      the instance definitions and provides more flexibility.  Generalized
-      type of `getOption` and added a default definition.  Removed
-      `askReaderOption`.  Added `extractReaderOption`.  Added
-      `extractHeaderMap` and `updateHeaderMap` in `HasHeaderMap`.
-      Gave default definitions for `getHeaderMap`, `putHeaderMap`,
-      `modifyHeaderMap`.  Added `extractIdentifierList` and
-      `updateIdentifierList` in `HasIdentifierList`.  Gave defaults
-      for `getIdentifierList`, `putIdentifierList`, and
-      `modifyIdentifierList`.  The ultimate goal here is to allow different
-      parsers to use their own, tailored parser states (instead of
-      `ParserState`) while still using shared functions.
-
-  * Template changes:
-
-    + LaTeX template: Use `fontenc` package only with `pdflatex` (#1164).
-    + LaTeX template:  Add `linestretch` and `fontfamily` variables.
-    + LaTeX template:  Conditionalize author and date commands.
-    + Beamer template: Consistent styles for figure and table captions
-      (aaronwolen).
-    + LaTeX and beamer template:  Adjust widths correctly for oversized
-      images.  Use `\setkeys{Gin}{}` to set appropriate defaults for
-      `\includegraphics` (Yihui Xie, Garrick Aden-Buie).  Load
-      `upquote` only after `fontenc` (Yihui Xie).
-    + Beamer template: Added caption package (#1200).
-    + Beamer template:  changes for better unicode handling (KarolS).
-    + DocBook template:  use `authorgroup` if there are authors.
-    + revealjs template: Move `include-after` to end (certainlyakey).
-    + revealjs template: Fixed PDF print function (#1220, kevinkenan).
-
-  * Bumped version bounds of dependencies.
-
-  * Added a `--trace` command line option, for debugging backtracking
-    bugs.  So far this only works with the markdown reader.
-
-  * MathMLinHTML:  Fixed deprecation warning (#362, gwern, Albert Krewinkel).
-
-  * Updated travis script to test with multiple GHC versions.
-
-  * Force failure of a Travis build if GHC produces warnings (Albert
-    Krewinkel).
-
-  * Add `.editorconfig` (Albert Krewinkel).
-    See <http://editorconfig.org/> for details.
-
-  * Give more useful error message if '-t pdf' is specified (#1155).
-
-  * Added `Cite`, `SmallCaps` to `Arbitrary` instance (#1269).
-
-  * Allow `html4` as a synonym of `html` as a reader (it already works
-    as a writer).
-
-  * README:
-
-    + Added an explanation of how to use YAML metadata to
-      force items to appear in the bibliography without citations in
-      the text (like LaTeX `\nocite`).
-    + Added note to `--bibtex/--natbib`: not for use in making PDF
-      (#1194, thanks to nahoj).
-    + Added explanatory notes about `--natbib` and `--biblatex`.
-    + Added specification of legal syntax for citation keys.
-    + Fixed variable defaults documentation (Albert Krewinkel).
-
-  * Removed copyright statements for files that have been removed
-    (Albert Krewinkel).
-
-  * Moved some doc files from `data-files` to `extra-source-files` (#1123).
-    They aren't needed at runtime.  We keep README and COPYRIGHT in data
-    to ensure that they'll be available on all systems on which pandoc
-    is installed.
-
-  * Use cabal sandboxes in Windows build script.
-
-pandoc (1.12.3.3)
-
-  * To changes to source; recompiled tarball with latest alex and
-    happy, so they will work with GHC 7.8.
-
-pandoc (1.12.3.2)
-
-  * Bumped version bounds for blaze-html, blaze-markup.
-
-  * ImageSize:  Avoid use of lookAhead, which is not in binary >= 0.6
-    (#1124).
-
-  * Fixed mediawiki ordered list parsing (#1122).
-
-  * HTML reader:  Fixed bug reading inline math with `$$` (#225).
-
-  * Added support for LaTeX style literate Haskell code blocks in rST
-    (Merijn Verstraaten).
-
-pandoc (1.12.3.1)
-
-  * Relaxed version constraint on binary, allowing the use of binary 0.5.
-
-pandoc (1.12.3)
-
-  * The `--bibliography` option now sets the `biblio-files` variable.
-    So, if you're using `--natbib` or `--biblatex`, you can just use
-    `--bibliography=foo.bib` instead of `-V bibliofiles=foo`.
-
-  * Don't run pandoc-citeproc filter if `--bibliography` is
-    used together with `--natbib` or `--biblatex` (Florian Eitel).
-
-  * Template changes:
-
-    + Updated beamer template to include booktabs.
-    + Added `abstract` variable to LaTeX template.
-    + Put `header-includes` after `title` in LaTeX template (#908).
-    + Allow use of `\includegraphics[size]` in beamer.
-      This just required porting a macro definition from the default
-      LaTeX template to the default beamer template.
-
-  * `reference.docx`:  Include `FootnoteText` style.
-    Otherwise Word ignores the style, even when specified in the `pPr`.
-    (#901)
-
-  * `reference.odt`:  Tidied `styles.xml`.
-
-  * Relaxed version bounds for dependencies.
-
-  * Added `withSocketsDo` around http conduit code in `openURL`,
-    so it works on Windows (#1080).
-
-  * Added `Cite` function to `sample.lua`.
-
-  * Markdown reader:
-
-    + Fixed regression in title blocks (#1089).
-      If author field was empty, date was being ignored.
-    + Allow backslash-newline hard line breaks in grid and
-      multiline table cells.
-    + Citation keys may now start with underscores, and may contain
-      underscores adjacent to internal punctuation.
-
-  * LaTeX reader:
-
-    + Add support for `Verb` macro (jrnold) (#1090).
-    + Support babel-style quoting: `` "`..."' ``.
-
-  * Properly handle script blocks in strict mode.  (That is,
-    `markdown-markdown_in_html_blocks`.) Previously a spurious
-    `<p>` tag was being added (#1093).
-
-  * Docbook reader: Avoid failure if `tbody` contains no `tr` or `row`
-    elements.
-
-  * LaTeX writer:
-
-    + Factored out function for table cell creation.
-    + Better treatment of footnotes in tables.
-      Notes now appear in the regular sequence, rather than in the
-      table cell.  (This was a regression in 1.10.)
-
-  * HTML reader: Parse name/content pairs from meta tags as metadata.
-    Closes #1106.
-
-  * Moved `fixDisplayMath` from Docx writer to `Writer.Shared`.
-
-  * OpenDocument writer:  Fixed `RawInline`, `RawBlock` so they don't escape.
-
-  * ODT writer:  Use mathml for proper rendering of formulas.
-    Note:  LibreOffice's support for this seems a bit buggy.  But
-    it should be better than what we had before.
-
-  * RST writer: Ensure no blank line after def in definition list (#992).
-
-  * Markdown writer: Don't use tilde code blocks with braced attributes in
-    `markdown_github` output.  A consequence of this change is that the
-    backtick form will be preferred in general if both are enabled.  That
-    is good, as it is much more widespread than the tilde form.  (#1084)
-
-  * Docx writer:  Fixed problem with some modified reference docx files.
-    Include `word/_rels/settings.xml.rels` if it exists, as well as other
-    `rels` files besides the ones pandoc generates explicitly.
-
-  * HTML writer:
-
-    + With `--toc`, headers no longer link to themselves (#1081).
-    + Omit footnotes from TOC entries.  Otherwise we get doubled
-      footnotes when headers have notes!
-
-  * EPUB writer:
-
-    + Avoid duplicate notes when headings contain notes.
-      This arose because the headings are copied into the metadata
-      "title" field, and the note gets rendered twice.  We strip the
-      note now before putting the heading in "title".
-    + Strip out footnotes from toc entries.
-    + Fixed bug with `--epub-stylesheet`.  Now the contents of
-      `writerEpubStylesheet` (set by `--epub-stylesheet`)
-      should again work, and take precedence over a stylesheet specified
-      in the metadata.
-
-  * `Text.Pandoc.MIME`: Added `wmf`, `emf`.
-
-  * `Text.Pandoc.Shared`:  `fetchItem` now handles image URLs beginning
-    with `//`.
-
-  * `Text.Pandoc.ImageSize`:  Parse EXIF format JPEGs.  Previously
-    we could only get size information for JFIF format, which led
-    to squished images in Word documents. Closes #976.
-
-  * Removed old `MarkdownTest_1.0.3` directory (#1104).
-
-pandoc (1.12.2.1)
-
-  * Markdown reader:  Fixed regression in list parser, involving
-    continuation lines containing raw HTML (or even verbatim raw HTML).
-
-pandoc (1.12.2)
-
-  * Metadata may now be included in YAML blocks in a markdown document.
-    For example,
-
-        ---
-        title:
-        - type: main
-          text: My Book
-        - type: subtitle
-          text: An investigation of metadata
-        creator:
-        - role: author
-          text: John Smith
-        - role: editor
-          text: Sarah Jones
-        identifier:
-        - scheme: DOI
-          text: doi:10.234234.234/33
-        publisher:  My Press
-        rights:  (c) 2007 John Smith, CC BY-NC
-        cover-image: img/mypic.jpg
-        ...
-
-    Metadata may still be provided using `--epub-metadata`; it will
-    be merged with the metadata in YAML blocks.
-
-  * EPUB writer:
-
-    + `meta` tags are now used instead of `opf` attributes for EPUB3.
-    + Insert "svg" property as needed in opf (EPUB 3).
-    + Simplify `imageTypeOf` using `getMimeType`.
-    + Add properties attribute to `cover-image` item for EPUB 3.
-    + Don't include node for `cover.xhtml` if no cover!
-    + Ensure that same identifier is used throughout (#1044).
-      If an identifier is given in metadata, we use that; otherwise
-      we generate a random uuid.
-    + Add cover reference to guide element (EPUB 2) (Shaun Attfield).
-      Fixes an issue with Calibre putting the cover at the end of the book
-      if the spine has `linear="no"`.  Apparently this is best practice
-      for other converters as well:
-      <http://www.idpf.org/epub/20/spec/OPF_2.0.1_draft.htm#Section2.6>.
-    + Allow `stylesheet` in metadata.  The value is a path to the stylesheet.
-    + Allow partial dates:  `YYYY`, `YYYY-MM`.
-
-  * Markdown writer:  Fix rendering of tight sublists (#1050).
-    Previously a spurious blank line was included after a tight sublist.
-
-  * ODT writer:  Add `draw:name` attribute to `draw:frame` elements (#1069).
-    This is reported to be necessary to avoid an error from recent
-    versions of Libre Office when files contain more than one image
-    Thanks to wmanley for reporting and diagnosing the problem.
-
-  * ConTeXt writer:  Don't hardcode figure/table placement and numbering.
-    Instead, let this be set in the template, using `\setupfloat`.
-    Thanks to on4aa and Aditya Mahajan for the suggestion (#1067).
-
-  * Implemented CSL flipflopping spans in DOCX, LaTeX, and HTML writers.
-
-  * Fixed bug with markdown intraword emphasis.  Closes #1066.
-
-  * Docbook writer:  Hierarchicalize block content in metadata.
-    Previously headers just disappeared from block-level metadata
-    when it was used in templates.  Now we apply the 'hierarchicalize'
-    transformation.  Note that a block headed by a level-2 header will
-    turn into a `<sect1>` element.
-
-  * OpenDocument writer:  Skip raw HTML (#1035).
-    Previously it was erroneously included as verbatim text.
-
-  * HTML/EPUB writer, footnotes:  Put `<sup>` tag inside `<a>` tags.
-    This allows better control of formatting, since the `<a>`
-    tags have a distinguishing class (#1049).
-
-  * Docx writer:
-
-    + Use mime type info returned by fetchItem.
-    + Fixed core metadata (#1046).
-      Don't create empty date nodes if no date given.
-      Don't create multiple `dc:creator` nodes; instead separate by
-      semicolons.
-    + Fix URL for core-properties in `_rels/.rels` (#1046).
-
-  * Plain writer: don't print `<span>` tags.
-
-  * LaTeX writer:
-
-    + Fix definition lists with internal links in terms (#1032).
-      This fix puts braces around a term that contains an internal
-      link, to avoid problems with square brackets.
-    + Properly escape pdftitle, pdfauthor (#1059).
-    + Use booktabs package for tables (thanks to Jose Luis Duran).
-
-  * Updated beamer template.  Now references should work properly
-    (in a slide) when `--biblatex` or `--natbib` is used.
-
-  * LaTeX reader:
-
-    + Parse contents of curly quotes or matched `"` as quotes.
-    + Support `\textnormal` as span with class `nodecor`.
-      This is needed for pandoc-citeproc.
-    + Improved citation parsing.  This fixes a run-time error that occured
-      with `\citet{}` (empty list of keys).  It also ensures that empty keys
-      don't get produced.
-
-  * MediaWiki reader:  Add automatic header identifiers.
-
-  * HTML reader:
-
-    + Use pandoc `Div` and `Span` for raw `<div>`, `<span>` when
-      `--parse-raw`.
-    + Recognize `svg` tags as block level content (thanks to MinRK).
-    + Parse LaTeX math if appropriate options are set.
-
-  * Markdown reader:
-
-    + Yaml block must start immediately after `---`.  If there's a blank
-      line after `---`, we interpreted it as a horizontal rule.
-    + Correctly handle empty bullet list items.
-    + Stop parsing "list lines" when we hit a block tag.
-      This fixes exponential slowdown in certain input, e.g.
-      a series of lists followed by `</div>`.
-
-  * Slides:  Preserve `<div class="references">` in references slide.
-
-  * `Text.Pandoc.Writer.Shared`:
-
-    + Fixed bug in `tagWithAttrs`.  A space was omitted before key-value
-      attributes, leading to invalid HTML.
-    + `normalizeDate`: Allow dates with year only (thanks to Shaun Attfield).
-    + Fixed bug in `openURL` with `data:` URIs.  Previously the base-64
-      encoded bytestring was returned.  We now decode it so it's a proper
-      image!
-
-  * DocBook reader:  Handle numerical attributes starting with decimal.
-    Also use `safeRead` instead of `read`.
-
-  * `Text.Pandoc.Readers.TexMath`: Export `readTeXMath'`, which attends
-    to display/inline.  Deprecate `readTeXMath`, and use `readTeXMath'`
-    in all the writers.  Require `texmath >= 0.6.5.2`.
-
-  * `Text.Pandoc.MIME`:
-
-    + Add entry for `jfif`.
-    + In looking up extensions, drop the encoding info.
-      E.g. for 'image/jpg;base64' we should lookup 'image/jpg'.
-
-  * Templates:  Changed how array variables are resolved.  Previously if
-    `foo` is an array (which might be because multiple values were set on
-    the command line), `$foo$` would resolve to the concatenation of the
-    elements of foo.  This is rarely useful behavior.  It has been changed
-    so that the first value is rendered.  Of course, you can still iterate
-    over the values using `$for(foo)$`.  This has the result that you can
-    override earlier settings using `-V` by putting new values later on the
-    command line, which is useful for many purposes.
-
-  * `Text.Pandoc`:  Don't default to `pandocExtensions` for all writers.
-
-  * Allow "epub2" as synonym for "epub", "html4" for "html".
-
-  * Don't look for slidy files in data files with `--self-contained`.
-
-  * Allow `https:` command line arguments to be downloaded.
-
-  * Fixed `make_osx_package.sh` so data files embedded in `pandoc-citeproc`.
-
-pandoc (1.12.1)
-
-  * `Text.Pandoc.Definition`:  Changed default JSON serialization format.
-    Instead of `{"Str": "foo"}`, for example, we now have `{"t": "Str",
-    "c": "foo"}`.  This new format is easier to work with outside of Haskell.
-    Incidentally, "t" stands for "tag", "c" for "contents".
-
-  * MediaWiki reader: Trim contents of `<math>` tags, to avoid problems
-    when converting to markdown (#1027).
-
-  * LaTeX reader:
-
-    + Ensure that preamble doesn't contribute to the text of
-      the document.
-    + Fixed character escaping in \url{}.  Previously `\~` wasn't handled
-      properly, among others.
-    + Parse `{groups}` as `Span`.  This is needed for accurate conversion of
-      bibtex titles, since we need to know what was protected from
-      titlecase conversions.
-
-  * LaTeX writer:
-
-    + Specially escape non-ascii characters in labels.
-      Otherwise we can get compile errors and other bugs when
-      compiled with pdflatex (#1007).  Thanks to begemotv2718 for the fix.
-    + Add link anchors for code blocks with identifiers (#1025).
-
-  * Throughout the code, use `isURI` instead of `isAbsoluteURI`.
-    It allows fragments identifiers.
-
-  * Slide formats:
-
-    + A Div element with class "notes" is treated as speaker
-      notes.  Currently beamer goes to `\note{}`, revealjs to
-      `<aside class="notes">`, and the notes are simply suppressed in
-      other formats  (#925).
-    + Fixed `. . .` (pause) on HTML slide formats.  Closes #1029.
-      The old version caused a pause to be inserted before the first
-      material on a slide. This has been fixed.
-    + Removed data files for s5, slideous, slidy.
-      Users of s5 and slideous will have to download the needed
-      files, as has been documented for some time in the README.
-      By default, slidy code will be sought on the web, as before.
-
-  * HTML writer: Insert command to typeset mathjax only in slideous output
-    (#966, #1012).
-
-  * RST writer:  Skip spaces after display math.  Otherwise we get indentation
-    problems, and part of the next paragraph may be rendered as part of the
-    math.
-
-  * OpenDocument writer:  Fix formatting of strikeout code (#995),
-    thanks to wilx.  don't use `font-face-decls` variable.
-
-  * Fixed test suite so it works with cabal sandboxes.
-
-pandoc (1.12.0.2)
-
-  * Removed `stringable` dependency.
-
-pandoc (1.12.0.1)
-
-  * Allow `--metadata` to be repeated for the same key to form a list.
-    This also has the effect that `--bibliography` can be repeated,
-    as before.
-
-  * Handle boolean values in `--metadata`.  Note that anything not parseable
-    as a YAML boolean or string is treated as a literal string.
-    You can get a string value with "yes", or any of the strings interpretable
-    as booleans, by quoting it:
-
-        -M boolvalue=yes -M stringvalue='"yes"'
-
-  * LaTeX writer: Don't print references if `--natbib` or `--biblatex`
-    option used.
-
-  * DOCX writer: Add `settings.xml` to the zip container.  Fixes a bug
-    in which docx files could not be read by some versions of Word
-    and LibreOffice (#990).
-
-  * Fixed a regression involving slide shows with bibliographies.
-    The Div container around references messed up the procedure for carving
-    a document into slides.  So we now remove the surrounding Div in
-    `prepSlides`.
-
-  * More informative error message when a filter is not found in path.
-
-  * Depend on pandoc-types 1.12.1.  This provide `ToJSONFilter`
-    instances for `Data a => a -> [a]` and `Data a => a -> IO [a]`.
-
-  * Don't use unicode_collation in building OSX package:
-    it adds something like 50MB of dependencies to the package.
-
-  * Declare alex and happy as build-tools (#986).
-
-pandoc (1.12)
-
-  [new features]
-
-  * Much more flexible metadata, including arbitrary fields and structured
-    values.  Metadata can be specified flexibly in pandoc markdown using
-    YAML metadata blocks, which may occur anywhere in the document:
-
-        ---
-        title: Here is my title.
-        abstract: |
-          This is the abstract.
-
-          1. It can contain
-          2. block content
-             and *inline markup*
-
-        tags: [cat, dog, animal]
-        ...
-
-    Metadata fields automatically populate template variables.
-
-  * Added `opml` (OPML) as input and output format.  The `_note` attribute,
-    used in OmniOutliner and supported by multimarkdown, is supported.
-    We treat the contents as markdown blocks under a section header.
-
-  * Added `haddock` (Haddock markup) as input format (David Lazar).
-
-  * Added `revealjs` output format, for reveal.js HTML 5 slide shows.
-    (Thanks to Jamie F. Olson for the initial patch.)
-    Nested vertical stacks are used for hierarchical structure.
-    Results for more than one level of nesting may be odd.
-
-  * Custom writers can now be written in lua.
-
-        pandoc -t data/sample.lua
-
-    will load the script sample.lua and use it as a custom writer.
-    (For a sample, do `pandoc --print-default-data-file sample.lua`.)
-    Note that pandoc embeds a lua interpreter, so lua need not be
-    installed separately.
-
-  * New `--filter/-F` option to make it easier to run "filters"
-    (Pandoc AST transformations that operate on JSON serializations).
-    Filters are always passed the name of the output format, so their
-    behavior can be tailored to it.  The repository
-    <https://github.com/jgm/pandocfilters> contains
-    a python module for writing pandoc filters in python, with
-    a number of examples.
-
-  * Added `--metadata/-M` option.
-    This is like `--variable/-V`, but actually adds to metadata, not
-    just variables.
-
-  * Added `--print-default-data-file` option, which allows printing
-    of any of pandoc's data files. (For example,
-    `pandoc --print-default-data-file reference.odt` will print
-    `reference.odt`.)
-
-  * Added syntax for "pauses" in slide shows:
-
-        This gives
-
-        . . .
-
-        me pause.
-
-  * New markdown extensions:
-
-    + `ignore_line_breaks`:  causes intra-paragraph line breaks to be ignored,
-      rather than being treated as hard line breaks or spaces.  This is useful
-      for some East Asian languages, where spaces aren't used between words,
-      but text is separated into lines for readability.
-    + `yaml_metadata_block`:  Parse YAML metadata blocks.  (Default.)
-    + `ascii_identifiers`: This will force `auto_identifiers` to use ASCII
-       only. (Default for `markdown_github`.) (#807)
-    + `lists_without_preceding_blankline`:  Allow lists to start without
-      preceding blank space.  (Default for `markdown_github`.) (#972)
-
-  [behavior changes]
-
-  * `--toc-level` no longer implies `--toc`.
-    Reason: EPUB users who don't want a visible TOC may still want
-    to set the TOC level for in the book navigation.
-
-  * `--help` now prints in and out formats in alphabetical order, and
-    says something about PDF output (#720).
-
-  * `--self-contained` now returns less verbose output (telling you
-    which URLs it is fetching, but not giving the full header).  In
-    addition, there are better error messages when fetching a URL fails.
-
-  * Citation support is no longer baked in to core pandoc. Users who
-    need citations will need to install and use a separate filter
-    (`--filter pandoc-citeproc`).  This filter will take `bibliography`,
-    `csl`, and `citation-abbreviations` from the metadata, though it
-    may still be specified on the command line as before.
-
-  * A `Cite` element is now created in parsing markdown whether or not
-    there is a matching reference.
-
-  * The `pandoc-citeproc` script will put the bibliography at the
-    end of the document, as before.  However, it will be put inside a `Div`
-    element with class "references", allowing users some control
-    over the styling of references.  A final header, if any, will
-    be included in the `Div`.
-
-  * The markdown writer will not print a bibliography if the
-    `citations` extension is enabled.  (If the citations are formatted
-    as markdown citations, it is redundant to have a bibliography,
-    since one will be generated automatically.)
-
-  * Previously we used to store the directory of the first input file,
-    even if it was local, and used this as a base directory for finding
-    images in ODT, EPUB, Docx, and PDF.  This has been confusing to many
-    users.  So we now look for images relative to the current
-    working directory, even if the first file argument is in another
-    directory.   Note that this change may break some existing workflows.
-    If you have been assuming that relative links will be interpreted
-    relative to the directory of the first file argument, you'll need
-    to make that the current directory before running pandoc. (#942)
-
-  * Better error reporting in some readers, due to changes in `readWith`:
-    the line in which the error occured is printed, with a caret pointing
-    to the column.
-
-  * All slide formats now support incremental slide view for definition lists.
-
-  * Parse `\(..\)` and `\[..\]` as math in MediaWiki reader.
-    Parse `:<math>...</math>` as display math.  These notations are used with
-    the MathJax MediaWiki extension.
-
-  * All writers: template variables are set automatically from metadata
-    fields.  However, variables specified on the command line with
-    `--variable` will completely shadow metadata fields.
-
-  * If `--variable` is used to set many variables with the same name,
-    a list is created.
-
-  * Man writer:  The `title`, `section`, `header`, and `footer` can now
-    all be set individually in metadata.  The `description` variable has been
-    removed.  Quotes have been added so that spaces are allowed in the
-    title.  If you have a title that begins
-
-        COMMAND(1) footer here | header here
-
-    pandoc will still parse it into a title, section, header, and
-    footer.  But you can also specify these elements explicitly (#885).
-
-  * Markdown reader
-
-    + Added support for YAML metadata blocks, which can come anywhere
-      in the document (not just at the beginning).  A document can contain
-      multiple YAML metadata blocks.
-    + HTML span and div tags are parsed as pandoc Span and Div elements.
-
-  * Markdown writer
-
-    + Allow simple tables to be printed as grid tables,
-      if other table options are disabled.  This means you can do
-      `pandoc -t markdown-pipe_tables-simple_tables-multiline_tables`
-      and all tables will render as grid tables.
-    + Support YAML title block (render fields in alphabetical order
-      to make output predictable).
-
-  [API changes]
-
-  * `Meta` in `Text.Pandoc.Definition` has been changed to allow
-    structured metadata.  (Note:  existing code that pattern-matches
-    on `Meta` will have to be revised.)  Metadata can now contain
-    indefinitely many fields, with content that can be a string,
-    a Boolean, a list of `Inline` elements, a list of `Block`
-    elements, or a map or list of these.
-
-  * A new generic block container (`Div`) has been added to `Block`,
-    and a generic inline container (`Span`) has been added to `Inline`.
-    These can take attributes.  They will render in HTML, Textile,
-    MediaWiki, Org, RST and and Markdown (with `markdown_in_html`
-    extension) as HTML `<div>` and `<span>` elements; in other formats
-    they will simply pass through their contents.  But they can be
-    targeted by scripts.
-
-  * `Format` is now a newtype, not an alias for String.
-    Equality comparisons are case-insensitive.
-
-  * Added `Text.Pandoc.Walk`, which exports hand-written tree-walking
-    functions that are much faster than the SYB functions from
-    `Text.Pandoc.Generic`.  These functions are now used where possible
-    in pandoc's code.  (`Tests.Walk` verifies that `walk` and `query`
-    match the generic traversals `bottomUp` and `queryWith`.)
-
-  * Added `Text.Pandoc.JSON`, which provides `ToJSON` and `FromJSON`
-    instances for the basic pandoc types. They use GHC generics and
-    should be faster than the old JSON serialization using
-    `Data.Aeson.Generic`.
-
-  * Added `Text.Pandoc.Process`, exporting `pipeProcess`.
-    This is a souped-up version of `readProcessWithErrorcode` that
-    uses lazy bytestrings instead of strings and allows setting
-    environment variables.  (Used in `Text.Pandoc.PDF`.)
-
-  * New module `Text.Pandoc.Readers.OPML`.
-
-  * New module `Text.Pandoc.Writers.OPML`.
-
-  * New module `Text.Pandoc.Readers.Haddock` (David Lazar).
-    This is based on Haddock's own lexer/parser.
-
-  * New module `Text.Pandoc.Writers.Custom`.
-
-  * In `Text.Pandoc.Shared`, `openURL` and `fetchItem` now return an
-    Either, for better error handling.
-
-  * Made `stringify` polymorphic in `Text.Pandoc.Shared`.
-
-  * Removed `stripTags` from `Text.Pandoc.XML`.
-
-  * `Text.Pandoc.Templates`:
-
-    + Simplified `Template` type to a newtype.
-    + Removed `Empty`.
-    + Changed type of `renderTemplate`: it now takes a JSON context
-      and a compiled template.
-    + Export `compileTemplate`.
-    + Export `renderTemplate'` that takes a string instead of a compiled
-      template.
-    + Export `varListToJSON`.
-
-  * `Text.Pandoc.PDF` exports `makePDF` instead of `tex2pdf`.
-    The signature of `makePDF` has changed and now contains
-    an additional argument for pdf engine options.
-
-  * `Text.Pandoc`:
-
-    + Made `toJsonFilter` an alias for `toJSONFilter` from `Text.Pandoc.JSON`.
-    + Removed `ToJsonFilter` typeclass.  `ToJSONFilter` from
-      `Text.Pandoc.JSON` should be used instead.  (Compiling against
-      pandoc-types instead of pandoc will also produce smaller executables.)
-    * Removed the deprecated `jsonFilter` function.
-    + Added `readJSON`, `writeJSON` to the API (#817).
-
-  * `Text.Pandoc.Options`:
-
-    + Added `Ext_lists_without_preceding_blankline`,
-      `Ext_ascii_identifiers`, `Ext_ignore_line_breaks`,
-      `Ext_yaml_metadataBlock` to `Extension`.
-    + Changed `writerSourceDirectory` to `writerSourceURL` and changed the
-      type to a `Maybe`.  `writerSourceURL` is set to 'Just url' when the
-      first command-line argument is an absolute URL.  (So, relative links
-      will be resolved in relation to the first page.)  Otherwise, 'Nothing'.
-    + All bibliography-related fields have been removed from
-      `ReaderOptions` and `WriterOptions`: `writerBiblioFiles`,
-      `readerReferences`, `readerCitationStyle`.
-    + Removed `writerPdfArgs` from `WriterOptions`.  These are now
-      passed in as a parameter to `makePDF`.
-
-  * The `Text.Pandoc.Biblio` module has been removed.  Users of the
-    pandoc library who want citation support will need to use
-    `Text.CSL.Pandoc` from `pandoc-citeproc`.
-
-
-  [bug fixes]
-
-  * In markdown, don't autolink a bare URI that is followed by `</a>`
-    (#937).
-
-  * `Text.Pandoc.Shared`
-
-    + `openURL` now follows redirects (#701), properly handles `data:`
-      URIs, and prints diagnostic output to stderr rather than stdout.
-    + `readDefaultDataFile`: normalize the paths.  This fixes bugs in
-      `--self-contained` on pandoc compiled with `embed_data_files` (#833).
-    + Fixed `readDefaultDataFile` so it works on Windows.
-    + Better error messages for `readDefaultDataFile`.  Instead of
-      listing the last path tried, which can confuse people who are
-      using `--self-contained`, so now we just list the data file name.
-    + URL-escape pipe characters.  Even though these are legal, `Network.URI`
-      doesn't regard them as legal in URLs.  So we escape them first (#535).
-
-  * Mathjax in HTML slide shows:  include explicit "Typeset" call.
-    This seems to be needed for some formats (e.g. slideous) and won't
-    hurt in others (#966).
-
-  * `Text.Pandoc.PDF`
-
-    + On Windows, create temdir in working directory, since the system
-      temp directory path may contain tildes, which can cause
-      problems in LaTeX (#777).
-    + Put temporary output directory in `TEXINPUTS` (see #917).
-    + `makePDF` tries to download images that are not found locally,
-      if the first argument is a URL (#917).
-    + If compiling with `pdflatex` yields an encoding error, offer
-      the suggestion to use `--latex-engine=xelatex`.
-
-  * Produce automatic header identifiers in parsing textile, RST,
-    and LaTeX, unless `auto_identifiers` extension is disabled (#967).
-
-  * `Text.Pandoc.SelfContained`:  Strip off fragment, query of relative URL
-     before treating as a filename.  This fixes `--self-contained` when used
-     with CSS files that include web fonts using the method described here:
-      <http://paulirish.com/2009/bulletproof-font-face-implementation-syntax/>
-      (#739).  Handle `src` in `embed`, `audio`, `source`, `input` tags.
-
-  * `Text.Pandoc.Parsing`: `uri` parser no longer treats punctuation before
-    percent-encoding, or a `+` character, as final punctuation.
-
-  * `Text.Pandoc.ImageSize`:  Handle EPS (#903).  This change will make
-    EPS images properly sized on conversion to Word.
-
-  * Slidy:  Use slidy.js rather than slidy.js.gz.
-    Reason:  some browsers have trouble with the gzipped js file,
-    at least on the local file system (#795).
-
-  * Markdown reader
-
-    + Properly handle blank line at beginning of input (#882).
-    + Fixed bug in unmatched reference links.  The input
-      `[*infile*] [*outfile*]` was getting improperly parsed:
-      "infile" was emphasized, but "*outfile*" was literal (#883).
-    + Allow internal `+` in citation identifiers (#856).
-    + Allow `.` or `)` after `#` in ATX headers if no `fancy_lists`.
-    + Do not generate blank title, author, or date metadata elements.
-      Leave these out entirely if they aren't present.
-    + Allow backtick code blocks not to be preceded by blank line (#975).
-
-  * Textile reader:
-
-    + Correctly handle entities.
-    + Improved handling of `<pre>` blocks (#927). Remove internal HTML tags
-      in code blocks, rather than printing them verbatim. Parse attributes
-      on `<pre>` tag for code blocks.
-
-  * HTML reader: Handle non-simple tables (#893).  Column widths are read from
-    `col` tags if present, otherwise divided equally.
-
-  * LaTeX reader
-
-    + Support alltt environment (#892).
-    + Support `\textasciitilde`, `\textasciicircum` (#810).
-    + Treat `\textsl` as emphasized text reader (#850).
-    + Skip positional options after `\begin{figure}`.
-    + Support `\v{}` for hacek (#926).
-    + Don't add spurious ", " to citation suffixes.
-      This is added when needed in pandoc-citeproc.
-    + Allow spaces in alignment spec in tables, e.g. `{ l r c }`.
-    + Improved support for accented characters (thanks to Scott Morrison).
-    + Parse label after section command and set id (#951).
-
-  * RST reader:
-
-    + Don't insert paragraphs where docutils doesn't.
-      `rst2html` doesn't add `<p>` tags to list items (even when they are
-      separated by blank lines) unless there are multiple paragraphs in the
-      list.  This commit changes the RST reader to conform more closely to
-      what docutils does (#880).
-    + Improved metadata.  Treat initial field list as metadata when
-      standalone specified.  Previously ALL fields "title", "author",
-      "date" in field lists were treated as metadata, even if not at
-      the beginning.  Use `subtitle` metadata field for subtitle.
-    + Fixed 'authors' metadata parsing in reST.  Semicolons separate
-      different authors.
-
-  * MediaWiki reader
-
-    + Allow space before table rows.
-    + Fixed regression for `<ref>URL</ref>`.
-      `<` is no longer allowed in URLs, according to the uri parser
-      in `Text.Pandoc.Parsing`.  Added a test case.
-    + Correctly handle indented preformatted text without preceding
-      or following blank line.
-    + Fixed `|` links inside table cells.  Improved attribute parsing.
-    + Skip attributes on table rows.  Previously we just crashed if
-      rows had attributes, now we ignore them.
-    + Ignore attributes on headers.
-    + Allow `Image:` for images (#971).
-    + Parse an image with caption in a paragraph by itself as a figure.
-
-  * LaTeX writer
-
-    + Don't use ligatures in escaping inline code.
-    + Fixed footnote numbers in LaTeX/PDF tables.  This fixes a bug
-      wherein notes were numbered incorrectly in tables (#827).
-    + Always create labels for sections.  Previously the labels were only
-      created when there were links to the section in the document (#871).
-    + Stop escaping `|` in LaTeX math.
-      This caused problems with array environments (#891).
-    + Change `\` to `/` in paths.  `/` works even on Windows in LaTeX.
-      `\` will cause major problems if unescaped.
-    + Write id for code block to label attribute in LaTeX when listings
-      is used (thanks to Florian Eitel).
-    + Scale LaTeX tables so they don't exceed columnwidth.
-    + Avoid problem with footnotes in unnumbered headers (#940).
-
-  * Beamer writer: when creating beamer slides, add `allowframebreaks` option
-      to the slide if it is one of the header classes.  It is recommended
-      that your bibliography slide have this attribute:
-
-        # References {.allowframebreaks}
-
-    This causes multiple slides to be created if necessary, depending
-    on the length of the bibliography.
-
-  * ConTeXt writer: Properly handle tables without captions.  The old output
-    only worked in MkII. This should work in MkIV as well (#837).
-
-  * MediaWiki writer: Use native mediawiki tables instead of HTML (#720).
-
-  * HTML writer:
-
-    + Fixed `--no-highlight` (Alexander Kondratskiy).
-    + Don't convert to lowercase in email obfuscation (#839).
-    + Ensure proper escaping in `<title>` and `<meta>` fields.
-
-  * AsciiDoc writer:
-
-    + Support `--atx-headers` (Max Rydahl Andersen).
-    + Don't print empty identifier blocks `([[]])` on headers (Max
-      Rydahl Andersen).
-
-  * ODT writer:
-
-    + Fixing wrong numbered-list indentation in open document format
-      (Alexander Kondratskiy) (#369).
-    + `reference.odt`: Added pandoc as "generator" in `meta.xml`.
-    + Minor changes for ODF 1.2 conformance (#939). We leave the
-      nonconforming `contextual-spacing` attribute, which is provided by
-      LibreOffice itself and seems well supported.
-
-  * Docx writer:
-
-    + Fixed rendering of display math in lists.
-      In 1.11 and 1.11.1, display math in lists rendered as a new list
-      item.  Now it always appears centered, just as outside of lists,
-      and in proper display math style, no matter how far indented the
-      containing list item is (#784).
-    + Use `w:br` with `w:type` `textWrapping` for linebreaks.
-      Previously we used `w:cr` (#873).
-    + Use Compact style for Plain block elements, to
-      differentiate between tight and loose lists (#775).
-    + Ignore most components of `reference.docx`.
-      We take the `word/styles.xml`, `docProps/app.xml`,
-      `word/theme/theme1.xml`, and `word/fontTable.xml` from
-      `reference.docx`, ignoring everything else.  This should help
-      with the corruption problems caused when different versions of
-      Word resave the reference.docx and reorganize things.
-    +  Made `--no-highlight` work properly.
-
-  * EPUB writer
-
-    + Don't add `dc:creator` tags if present in EPUB metadata.
-    + Add `id="toc-title"` to `h1` in `nav.xhtml` (#799).
-    + Don't put blank title page in reading sequence.
-      Set `linear="no"` if no title block.  Addresses #797.
-    + Download webtex images and include as data URLs.
-      This allows you to use `--webtex` in creating EPUBs.
-      Math with `--webtex` is automatically made self-contained.
-    + In `data/epub.css`, removed highlighting styles (which
-      are no longer needed, since styles are added by the HTML
-      writer according to `--highlighting-style`).  Simplified
-      margin fields.
-    + If resource not found, skip it, as in Docx writer (#916).
-
-  * RTF writer:
-
-    + Properly handle characters above the 0000-FFFF range.
-      Uses surrogate pairs.  Thanks to Hiromi Ishii for the patch.
-    + Fixed regression with RTF table of contents.
-    + Only autolink absolute URIs.  This fixes a regression, #830.
-
-  * Markdown writer:
-
-    + Only autolink absolute URIs.  This fixes a regression, #830.
-    + Don't wrap attributes in fenced code blocks.
-    + Write full metadata in MMD style title blocks.
-    + Put multiple authors on separate lines in pandoc titleblock.
-      Also, don't wrap long author entries, as new lines get treated
-      as new authors.
-
-  * `Text.Pandoc.Templates`:
-
-    + Fixed bug retrieving default template for markdown variants.
-    + Templates can now contain "record lookups" in variables;
-      for example, `author.institution` will retrieve the `institution`
-      field of the `author` variable.
-    + More consistent behavior of `$for$`.  When `foo` is not a list,
-      `$for(foo)$...$endfor$` should behave like $if(foo)$...$endif$.
-      So if `foo` resolves to "", no output should be produced.
-      See pandoc-templates#39.
-
-  * Citation processing improvements (now part of pandoc-citeproc):
-
-    + Fixed `endWithPunct` The new version correctly sees a sentence
-      ending in '.)' as ending with punctuation.  This fixes a bug which
-      led such sentences to receive an extra period at the end: '.).'.
-      Thanks to Steve Petersen for reporting.
-    + Don't interfere with Notes that aren't citation notes.
-      This fixes a bug in which notes not generated from citations were
-      being altered (e.g. first letter capitalized) (#898).
-    + Only capitalize footnote citations when they have a prefix.
-    + Changes in suffix parsing.  A suffix beginning with a digit gets 'p'
-      inserted before it before passing to citeproc-hs, so that bare numbers
-      are treated as page numbers by default.  A suffix not beginning with
-      punctuation has a space added at the beginning (rather than a comma and
-      space, as was done before for not-author-in-text citations).
-      The result is that `\citep[23]{item1}` in LaTeX will be interpreted
-      properly, with '23' treated as a locator of type 'page'.
-    + Many improvements to citation rendering, due to fixes in citeproc-hs
-      (thanks to Andrea Rossato).
-    + Warnings are issued for undefined citations, which are rendered
-      as `???`.
-    + Fixed hanging behavior when locale files cannot be found.
-
-  [template changes]
-
-  * DocBook:  Use DocBook 4.5 doctype.
-
-  * Org: '#+TITLE:' is inserted before the title.
-    Previously the writer did this.
-
-  * LaTeX:  Changes to make mathfont work with xelatex.
-    We need the mathspec library, not just fontspec, for this.
-    We also need to set options for setmathfont (#734).
-
-  * LaTeX: Use `tex-ansi` mapping for `monofont`.
-    This ensures that straight quotes appear as straight, rather than
-    being treated as curly.  See #889.
-
-  * Made `\includegraphics` more flexible in LaTeX template.
-    Now it can be used with options, if needed.  Thanks to Bernhard Weichel.
-
-  * LaTeX/Beamer: Added `classoption` variable.
-    This is intended for class options like `oneside`; it may
-    be repeated with different options.  (Thanks to Oliver Matthews.)
-
-  * Beamer: Added `fonttheme` variable.  (Thanks to Luis Osa.)
-
-  * LaTeX: Added `biblio-style` variable (#920).
-
-  * DZSlides: title attribute on title section.
-
-  * HTML5: add meta tag to allow scaling by user (Erik Evenson)
-
-  [under-the-hood improvements]
-
-  * Markdown reader:Improved strong/emph parsing, using the strategy of
-    <https://github.com/jgm/Markdown>.  The new parsing algorithm requires
-    no backtracking, and no keeping track of nesting levels.  It will give
-    different results in some edge cases, but these should not affect normal
-    uses.
-
-  * Added `Text.Pandoc.Compat.Monoid`.
-    This allows pandoc to compile with `base` < 4.5, where `Data.Monoid`
-    doesn't export `<>`.  Thanks to Dirk Ullirch for the patch.
-
-  * Added `Text.Pandoc.Compat.TagSoupEntity`.
-    This allows pandoc to compile with `tagsoup` 0.13.x.
-    Thanks to Dirk Ullrich for the patch.
-
-  * Most of `Text.Pandoc.Readers.TeXMath` has been moved to the
-    `texmath` module (0.6.4).  (This allows `pandoc-citeproc` to
-    handle simple math in bibliography fields.)
-
-  * Added `Text.Pandoc.Writers.Shared` for shared functions used
-    only in writers.  `metaToJSON` is used in writers to create a
-    JSON object for use in the templates from the pandoc metadata
-    and variables.  `getField`, `setField`, and `defField` are
-    for working with JSON template contexts.
-
-  * Added `Text.Pandoc.Asciify` utility module.
-    This exports functions to create ASCII-only versions of identifiers.
-
-  * `Text.Pandoc.Parsing`
-
-    + Generalized state type on `readWith` (API change).
-    + Specialize readWith to `String` input. (API change).
-    + In `ParserState`, replace `stateTitle`, `stateAuthors`, `stateDate`
-      with `stateMeta` and `stateMeta'`.
-
-  * `Text.Pandoc.UTF8`: use strict bytestrings in reading.  The use of lazy
-     bytestrings seemed to cause problems using pandoc on 64-bit Windows
-     7/8 (#874).
-
-  * Factored out `registerHeader` from markdown reader, added to
-    `Text.Pandoc.Parsing`.
-
-  * Removed `blaze_html_0_5` flag, require `blaze-html` >= 0.5.
-    Reason:  < 0.5 does not provide a monoid instance for Attribute,
-    which is now needed by the HTML writer (#803).
-
-  * Added `http-conduit` flag, which allows fetching https resources.
-    It also brings in a large number of dependencies (`http-conduit`
-    and its dependencies), which is why for now it is an optional flag
-    (#820).
-
-  * Added CONTRIBUTING.md.
-
-  * Improved INSTALL instructions.
-
-  * `make-windows-installer.bat`: Removed explicit paths for executables.
-
-  * `aeson` is now used instead of `json` for JSON.
-
-  * Set default stack size to 16M.  This is needed for some large
-    conversions, esp. if pandoc is compiled with 64-bit ghc.
-
-  * Various small documentation improvements.
-    Thanks to achalddave and drothlis for patches.
-
-  * Removed comment that chokes recent versions of CPP (#933).
-
-  * Removed support for GHC version < 7.2, since pandoc-types now
-    requires at least GHC 7.2 for GHC generics.
-
-
-pandoc (1.11.1)
-
-  * Markdown reader:
-
-    + Fixed regression in which parentheses were lost in link URLs.
-      Added tests.  Closes #786.
-    + Better handling of unmatched double quotes in `--smart` mode.
-      These occur frequently in fiction, since it is customary not to
-      close quotes in dialogue if the speaker does not change between
-      paragraphs.  The unmatched quotes now get turned into literal
-      left double quotes. (No `Quoted` inline is generated, however.)
-      Closes #99 (again).
-
-  * HTML writer: Fixed numbering mismatch between TOC and sections.
-    `--number-offset` now affects TOC numbering as well
-    as section numbering, as it should have all along.  Closes #789.
-
-  * Markdown writer: Reverted 1.11 change that caused citations to be rendered
-    as markdown citations, even if `--bibliography` was specified, unless
-    `citation` extension is disabled.  Now, formatted citations are always
-    printed if `--bibliography` was specified.  If you want to reformat
-    markdown keeping pandoc markdown citations intact, don't use
-    `--bibliography`.  Note that citations parsed from LaTeX documents will
-    be rendered as pandoc markdown citations when `--bibliography` is not
-    specified.
-
-  * ODT writer: Fixed regression leading to corrupt ODTs.
-    This was due to a change in the `Show` instance for
-    `Text.Pandoc.Pretty.Doc`.  Closes #780.
-
-  * Fixed spacing bugs involving code block attributes in
-    RST reader and Markdown writer. Closes #763.
-
-  * Windows package:  Various improvements due to Fyodor Sheremetyev.
-
-    + Automatically set installation path (Program Files or Local App Data).
-    + Set system PATH environment variable when installing for all users.
-    + Pandoc can installed for all users using the following command.
-      `msiexec /i pandoc-1.11.msi ALLUSERS=1`.
-
-  * Bumped QuickCheck version bound.
-
-pandoc (1.11)
-
-  * Added `--number-offset` option.  (See README for description.)
-
-  * Added `--default-image-extension` option.  (See README for description.)
-
-  * `--number-sections` behavior change: headers with class `unnumbered`
-    will not be numbered.
-
-  * `--version` now reports the default data directory.
-
-  * `Text.Pandoc.Parsing` is no longer exposed. (API change.)
-
-  * `Text.Pandoc.Highlighting` is no longer exposed. (API change.)
-
-  * `Text.Pandoc.Shared`:  Changed type of `Element`.  `Sec` now includes
-    a field for `Attr` rather than just `String`.  (API change.)
-
-  * Added `markdown_github` as input format.  This was an accidental
-    omission in 1.10.
-
-  * Added `readerDefaultImageExtension` field to `ReaderOptions`.  (API
-    change.)
-
-  * Added `writerNumberOffset` field in `WriterOptions`. (API change.)
-
-  * Beamer template:
-
-    + Fixed captions with longtable.  Thanks to Joost Kremers.
-    + Provide `\Oldincludegraphics` as in LaTeX template (Benjamin Bannier).
-
-  * LaTeX template:
-
-    + Load microtype after fonts.  Microtype needs to know
-      what fonts are being used.  Thanks to dfc for the patch.
-    + Set `secnumdepth` to 5 if `--number-sections` specified.
-      This yields behavior equivalent to the other writers, numbering
-      level 4 and 5 headers too.  Closes #753.
-
-  * HTML reader:
-
-    + Handle `<colgroup>` tag.
-    + Preserve all header attributes.
-
-  * LaTeX reader:
-
-    + Parse `\hrule` as `HorizontalRule`.  Closes #746.
-    + Parse starred variants of `\section` etc. as headers with
-      attribute `unnumbered`.
-    + Read optional attributes in `lstlisting` and `Verbatim` environments.
-      We convert these to pandoc standard names, e.g. `numberLines`
-      for `numbers=left`, `startFrom=100` from `firstnumber=100`.
-    + Handle language attribute for lstlistings.
-    + Better support for Verbatim and minted environments.  Closes #763.
-
-  * Markdown reader:
-
-    + `-` in an attribute context = `.unnumbered`.  The point of this
-      is to provide a way to specify unnumbered headers in non-English
-      documents.
-    + Fixed bug parsing key/value attributes.  Parsing failed if you
-      had an unquoted attribute immediately before the final '}'.
-    + Make backslash escape work in attributes.
-    + Fix title block parsing.  Now if `mmd_title_blocks` is specified,
-      pandoc will parse a MMD title block if it sees one, even if
-      `pandoc_title_blocks` is enabled.
-    + Refactoring: `litChar` now includes entities, so we don't need
-      to use `fromEntities` e.g. on titles.
-    + Allow spaces around borders in pipe tables.  Closes #772.
-    + Allow all punctuation in angle-bracket autolinks.  Previously
-      things like `----` were disallowed, because the uri parser
-      treated them as trailing punctuation.  Closes #768.
-    + Make `implicit_header_references` work properly when
-      headers are given explicit identifiers.
-    + Check for tables before line blocks.  Otherwise some pipe
-      tables get treated as line blocks.
-    + Allow `&` in emails (for entities).
-    + Properly handle entities in titles and links.  A markdown link
-      `<http://g&ouml;ogle.com>` should be a link to `http://göogle.com`.
-      Closes #723.
-
-  * Textile reader:
-
-    + Handle attributes on headers.
-
-  * LaTeX reader:
-
-    + Add `fig:` as title for images with captions.
-      This is needed for them to be rendered as figures.  Closes #766.
-    + Never emit an empty paragraph.  See #761.
-    + Handle `\caption` for images in figures.  Closes #766.
-    + Parse `\section*`, etc. as unnumbered sections.
-
-  * HTML writer:
-
-    + Support header attributes.  The attributes go on
-      the enclosing `section` or `div` tag if `--section-divs` is specified.
-    + Fixed a regression (only now noticed) in html+lhs output.
-      Previously the bird tracks were being omitted.
-
-  * LaTeX writer:
-
-    + Omit lists with no items to avoid LaTeX errors.
-    + Support line numbering with `--listings`.
-      If `numberLines` class is present, we add `numbers=left`;
-      if `startFrom` is present, we add `firstnumber=`. (#763)
-
-  * ConTeXt writer:
-
-    + Removed `\placecontent`.  This produced a duplicate toc,
-      in conjunction with `\placelist`.
-    + Use `\title`, `\subject` etc. for headers with
-      `unnumbered` class.
-
-  * Textile writer:
-
-    + Support header attributes.
-
-  * Markdown writer:
-
-    + Use grid tables when needed, and if enabled.  Closes #740.
-    + Render citations as pandoc-markdown citations.
-      Previously citations were rendered as citeproc-formatted citations
-      by default.  Now we render them as pandoc citations, e.g. `[@item1]`,
-      unless the `citations` extension is disabled.
-      If you still want formatted citations in your markdown output,
-      use `pandoc -t markdown-citations`.
-
-  * RST writer:
-
-    + Support `:number-lines:` in code blocks.
-
-  * Docx writer:
-
-    + Better treatment of display math.  Display math inside a
-      paragraph is now put in a separate paragraph, so it will render
-      properly (centered and without extra blank lines around it).
-      Partially addresses #742.
-    + Content types and document rels xml files are now created from
-      scratch, rather than being taken over from `reference.docx`.
-      This fixes problems that arise when you edit the `reference.docx`
-      with Word.
-    + We also now encode mime types for each individual image rather
-      than using defaults.  This should allow us to handle a wider
-      range of image types (including PDF).   Closes #414.
-    + Changed style names in `reference docx`.
-      `FootnoteReference` -> `FootnoteRef`, `Hyperlink` -> `Link`.
-      The old names got changed by Word when the `reference.docx` was
-      edited.  Closes #414.
-
-  * EPUB writer:
-
-    + Fix section numbering.  Previously the numbering restarted from 1
-      in each chapter (with `--number-sections`), though the numbers in
-      the table of contents were correct.
-    + Headers with "unnumbered" attribute are not numbered.  (Nor do they
-      cause an increment in running numbering.) Section numbers now work
-      properly, even when there is material before the first numbered section.
-    + Include HTML TOC, even in epub2.  The TOC is included in `<spine>`,
-      but `linear` is set to `no` unless the `--toc` option is specified.
-      Include `<guide>` element in OPF.  This should allow the TOC to
-      be useable in Kindles when converted with kindlegen. Closes #773.
-
-  * `Text.Pandoc.Parsing`: Optimized `oneOfStringsCI`.
-    This dramatically reduces the speed penalty that comes from enabling the
-    `autolink_bare_uris` extension.  The penalty is still substantial (in one
-    test, from 0.33s to 0.44s), but nowhere near what it used to be.
-    The RST reader is also much faster now, as it autodetects URIs.
-
-  * `Text.Pandoc.Shared`:  `hierarchicalize` will not number section
-    with class "unnumbered".  Unnumbered sections get `[]` for their
-    section number.
-
-  * `Text.Pandoc.Pretty`:
-
-    + Fixed `chomp` so it works inside `Prefixed` elements.
-    + Changed `Show` instance so it is better for debugging.
-
-  * `Text.Pandoc.ImageSize`:  Added `Pdf` to `ImageType`.
-
-  * `Text.Pandoc.UTF8`:  Strip off BOM if present.  Closes #743.
-
-  * Windows installer improvements:
-
-    + The installer is now signed with a certificate (thanks to
-      Fyodor Sheremetyev).
-    + WiX is used instead of InnoSetup.  The installer is now a
-      standard msi file.
-    + The version number is now auto-detected, and need not be
-      updated separately.
-
-  * OSX installer improvements:
-
-    + The package and pandoc executable are now signed with a
-      certificate (thanks to Fyodor Sheremetyev).
-    + RTF version of license is used.
-    + Use full path for sysctl in `InstallationCheck` script (jonahbull).
-      Closes #580.
-
-  * Converted COPYING to markdown.
-
-  * pandoc.cabal:  Require latest versions of highlighting-kate,
-    texmath, citeproc-hs, zip-archive.
-
-pandoc (1.10.1)
-
-  * Markdown reader:  various optimizations, leading to a
-    significant performance boost.
-
-  * RST reader:  Allow anonymous form of inline links:
-    `` `hello <url>`__ `` Closes #724.
-
-  * Mediawiki reader: Don't require newlines after tables.
-    Thanks to jrunningen for the patch. Closes #733.
-
-  * Fixed LaTeX macro parsing.  Now LaTeX macro definitions are preserved
-    when output is LaTeX, and applied when it is another format.
-    Partially addresses #730.
-
-  * Markdown and RST readers:  Added parser to `block` that skips blank
-    lines.  This fixes a subtle regression involving grid tables with
-    empty cells.  Also added test for grid table with empty cells.
-    Closes #732.
-
-  * RST writer:  Use `.. code:: language` for code blocks with language.
-    Closes #721.
-
-  * DocBook writer:  Fixed output for hard line breaks, adding a newline
-    between `<literallayout>` tags.
-
-  * Markdown writer:  Use an autolink when link text matches url.
-    Previously we also checked for a null title, but this
-    test fails for links produced by citeproc-hs in bibliographies.
-    So, if the link has a title, it will be lost on conversion
-    to an autolink, but that seems okay.
-
-  * Markdown writer:  Set title, author, date variables as before.
-    These are no longer used in the default template, since we use
-    titleblock, but we set them anyway for those who use custom templates.
-
-  * LaTeX writer:  Avoid extra space at start/end of table cell.
-    Thanks to Nick Bart for the suggestion of using @{}.
-
-  * `Text.Pandoc.Parsing`:
-
-    + More efficient version of `anyLine`.
-    + Type of `macro` has changed; the parser now returns `Blocks`
-      instead of `Block`.
-
-  * Relaxed old-time version bound, allowing 1.0.*.
-
-  * Removed obsolete `hsmarkdown` script.  Those who need `hsmarkdown`
-    should create a symlink as described in the README.
-
-pandoc (1.10.0.5)
-
-  * Markdown reader: Try `lhsCodeBlock` before `rawTeXBlock`.  Otherwise
-    `\begin{code}...\end{code}` isn't handled properly in markdown+lhs.
-    Thanks to Daniel Miot for noticing the bug and suggesting the fix.
-
-  * Markdown reader: Fixed bug with headerless grid tables.
-    The 1.10 code assumed that each table header cell contains exactly one
-    block. That failed for headerless tables (0) and also for tables with
-    multiple blocks in a header cell.  The code is fixed and tests provided.
-    Thanks to Andrew Lee for pointing out the bug.
-
-  * Markdown reader: Fixed regressions in fenced code blocks. Closes #722.
-
-    + Tilde code fences can again take a bare language string
-      (`~~~ haskell`), not just curly-bracketed attributes
-      (`~~~ {.haskell}`).
-    + Backtick code blocks can take the curly-bracketed attributes.
-    + Backtick code blocks don't *require* a language.
-    + Consolidated code for the two kinds of fenced code blocks.
-
-  * LaTeX template: Use `\urlstyle{same}` to avoid monospace URLs.
-
-  * Markdown writer: Use proportional font for email autolinks with
-    obfuscation.  Closes #714.
-
-  * Corrected name of `blank_before_blockquote` in README.  Closes #718.
-
-  * `Text.Pandoc.Shared`: Fixed bug in `uri` parser.
-    The bug prevented an autolink at the end of a string (e.g.
-    at the end of a line block line) from counting as a link.  Closes #711.
-
-  * Use the `hsb2hs` preprocessor instead of TH for embed_data_files.
-    This should work on Windows, unlike the TH solution with
-    file-embed.
-
-  * Eliminated use of TH in test suite.
-
-  * Added `Text.Pandoc.Data` (non-exported) to hold the association
-    list of embedded data files, if the `embed_data_files` flag is selected.
-    This isolates the code that needs special treatment with file-embed or
-    `hsb2hs`.
-
-  * Changes to `make-windows-installer.bat`.
-
-    + Exit batch file if any of the cabal-dev installs fail.
-    + There's no longer any need to reinstall `highlighting-kate`.
-    + Don't start with a `cabal update`; leave that to the user.
-    + Force reinstall of pandoc.
-
-  * Fixed EPUB writer so it builds with blaze-html 0.4.x. Thanks to
-    Jens Petersen.
-
-pandoc (1.10.0.4)
-
-  * Fixed bug with escaped % in LaTeX reader. Closes #710.
-
-pandoc (1.10.0.3)
-
-  * Added further missing fb2 tests to cabal file.
-
-pandoc (1.10.0.2)
-
-  * Added fb2 tests to cabal file's extra-source-files.
-
-pandoc (1.10.0.1)
-
-  * Bump version bounds on test-framework packages.
-
-pandoc (1.10)
-
-  [new features]
-
-  * New input formats:  `mediawiki` (MediaWiki markup).
-
-  * New output formats:  `epub3` (EPUB v3 with MathML),
-    `fb2` (FictionBook2 ebooks).
-
-  * New `--toc-depth` option, specifying how many levels of
-    headers to include in a table of contents.
-
-  * New `--epub-chapter-level` option, specifying the header
-    level at which to divide EPUBs into separate files.
-    Note that this normally affects only performance, not the
-    visual presentation of the EPUB in a reader.
-
-  * Removed the `--strict` option.  Instead of using `--strict`,
-    one can now use the format name `markdown_strict` for either input
-    or output.  This gives more fine-grained control that `--strict`
-    did, allowing one to convert from pandoc's markdown to strict
-    markdown or vice versa.
-
-  * It is now possible to enable or disable specific syntax
-    extensions by appending them (with `+` or `-`) to the writer
-    or reader name.  For example,
-
-        pandoc -f markdown-footnotes+hard_line_breaks
-
-    disables footnotes and enables treating newlines as hard
-    line breaks.  The literate Haskell extensions are now implemented
-    this way as well, using either `+lhs` or `+literate_haskell`.
-    For a list of extension names, see the README under
-    "Pandoc's Markdown."
-
-  * The following aliases have been introduced for specific
-    combinations of markdown extensions:  `markdown_phpextra`,
-    `markdown_github`, `markdown_mmd`, `markdown_strict`.  These aliases
-    work just like regular reader and writer names, and can be modified
-    with extension modifiers as described above. (Note that conversion
-    from one markdown dialect to another does not work perfectly,
-    because there are differences in markdown parsers besides
-    just the extensions, and because pandoc's internal document model is
-    not rich enough to capture all of the extensions.)
-
-  * New `--html-q-tags` option.  The previous default was to use `<q>`
-    tags for smart quotes in HTML5.  But `<q>` tags are also valid HTML4.
-    Moreover, they are not a robust way of typesetting quotes, since
-    some user agents don't support them, and some CSS resets (e.g.
-    bootstrap) prevent pandoc's quotes CSS from working properly.
-    We now just insert literal quote characters by default in both
-    `html` and `html5` output, but this option is provided for
-    those who still want `<q>` tags.
-
-  * The markdown reader now prints warnings (to stderr) about
-    duplicate link and note references.  Closes #375.
-
-  * Markdown syntax extensions:
-
-    + Added pipe tables.  Thanks to François Gannaz for the initial patch.
-      These conform to PHP Markdown Extra's pipe table syntax. A subset
-      of org-mode table syntax is also supported, which means that you can
-      use org-mode's nice table editor to create tables.
-
-    + Added support for RST-style line blocks. These are
-      useful for verse and addresses.
-
-    + Attributes can now be specified for headers, using the same
-      syntax as in code blocks.  (However, currently only the
-      identifier has any effect in most writers.)  For example,
-
-            # My header {#foo}
-
-            See [the header above](#foo).
-
-    + Pandoc will now act as if link references have been defined
-      for all headers without explicit identifiers.
-      So, you can do this:
-
-            # My header
-
-            Link to [My header].
-            Another link to [it][My header].
-
-      Closes #691.
-
-  * LaTeX reader:
-
-    + Command macros now work everywhere, including non-math.
-      Environment macros still not supported.
-    + `\input` now works, as well as `\include`.  TEXINPUTS is used.
-      Pandoc looks recursively into included files for more included files.
-
-  [behavior changes]
-
-  * The Markdown reader no longer puts the text of autolinks in a
-    `Code` inline.  This means that autolinks will no longer appear
-    in a monospace font.
-
-  * The character `/` can now appear in markdown citation keys.
-
-  * HTML blocks in strict_markdown are no longer required to begin
-    at the left margin.  Technically this is required, according to
-    the markdown syntax document, but `Markdown.pl` and other markdown
-    processors are more liberal.
-
-  * The `-V` option has been changed so that if there are duplicate
-    variables, those specified later on the command line take precedence.
-
-  * Tight lists now work in LaTeX and ConTeXt output.
-
-  * The LaTeX writer no longer relien on the `enumerate` package.
-    Instead, it uses standard LaTeX commands to change the list numbering
-    style.
-
-  * The LaTeX writer now uses `longtable` instead of `ctable`. This allows
-    tables to be split over page boundaries.
-
-  * The RST writer now uses a line block to render paragraphs containing
-    linebreaks (which previously weren't supported at all).
-
-  * The markdown writer now applies the `--id-prefix` to footnote IDs.
-    Closes #614.
-
-  * The plain writer no longer uses backslash-escaped line breaks
-    (which are not very "plain").
-
-  * `Text.Pandoc.UTF8`: Better error message for invalid UTF8.
-    Read bytestring and use `Text`'s decodeUtf8 instead of using
-    `System.IO.hGetContents`.  This way you get a message saying
-    "invalid UTF-8 stream" instead of "invalid byte sequence."
-    You are also told which byte caused the problem.
-
-  * Docx, ODT, and EPUB writers now download images specified by a URL
-    instead of skipping them or raising an error.
-
-  * EPUB writer:
-
-    + The default CSS now left-aligns headers by default, instead of
-      centering.  This is more consistent with the rest of the writers.
-    + A proper multi-level table of contents is now used in `toc.ncx`.
-      There is no longer a subsidiary table of contents at the beginning
-      of each chapter.
-    + Code highlighting now works by default.
-    + Section divs are used by default for better semantic markup.
-    + The title is used instead of "Title Page" in the table of contents.
-      Otherwise we have a hard-coded English string, which looks
-      strange in ebooks written in other languages.  Closes #572.
-
-  * HTML writer:
-
-    + Put mathjax in span with class "math".  Closes #562.
-    + Put citations in a span with class "citation." In HTML5, also include
-      a `data-cite` attribute with a space-separated list of citation
-      keys.
-
-  * `Text.Pandoc.UTF8`:  use universalNewlineMode in reading.
-    This treats both `\r\n` and `\n` as `\n` on input, no matter
-    what platform we're running on.
-
-  * Citation processing is now done in the Markdown and LaTeX
-    readers, not in `pandoc.hs`.  This makes it easier for library users
-    to use citations.
-
-  [template changes]
-
-  * HTML: Added css to template to preserve spaces in `<code>` tags.
-    Thanks to Dirk Laurie.
-
-  * Beamer:  Remove English-centric strings in section pages.
-    Section pages used to have "Section" and a number as well as the
-    section title. Now they just have the title.  Similarly for part
-    and subsection.  Closes #566.
-
-  * LaTeX, ConTeXt: Added papersize variable.
-
-  * LaTeX, Beamer templates: Use longtable instead of ctable.
-
-  * LaTeX, Beamer templates: Don't require 'float' package for tables.
-    We don't actually seem to use the '[H]' option.
-
-  * LaTeX:  Use `upquote` package if it is available.  This fixes
-    straight quotes in verbatim environments.
-
-  * Markdown, plain: Fixed titleblock so it is just a single string.
-    Previously separate title, author, and date variables were used,
-    but this didn't allow different kinds of title blocks.
-
-  * EPUB:
-
-    + Rationalized templates.  Previously there were three different
-      templates involved in epub production. There is now just one
-      template, `default.epub` or `default.epub3`. It can now be
-      overridden using `--template`, just like other templates.
-      The titlepage is now folded into the default template.
-      A `titlepage` variable selects it.
-    + UTF-8, lang tag, meta tags, title element.
-
-  * Added scale-to-width feature to beamer template
-
-  [API changes]
-
-  * `Text.Pandoc.Definition`: Added `Attr` field to `Header`.
-    Previously header identifers were autogenerated by the writers.
-    Now they are added in the readers (either automatically or explicitly).
-
-  * `Text.Pandoc.Builder`:
-
-    + `Inlines` and `Blocks` are now synonyms for `Many Inline` and
-      `Many Block`.  `Many` is a newtype wrapper around `Seq`, with
-      custom Monoid instances for `Many Inline` and `Many Block.  This
-      allows `Many` to be made an instance of `Foldable` and `Traversable`.
-    + The old `Listable` class has been removed.
-    + The module now exports `isNull`, `toList`, `fromList`.
-    + The old `Read` and `Show` instances have been removed; derived
-      instances are now used.
-    + Added `headerWith`.
-
-  * The readers now take a `ReaderOptions` rather than a `ParserState`
-    as a parameter.  Indeed, not all parsers use the `ParserState` type;
-    some have a custom state.  The motivation for this change was to separate
-    user-specifiable options from the accounting functions of parser state.
-
-  * New module `Text.Pandoc.Options`.  This includes the `WriterOptions`
-    formerly in `Text.Pandoc.Shared`, and its associated
-    data types.  It also includes a new type `ReaderOptions`, which
-    contains many options formerly in `ParserState`, and its associated
-    data types:
-
-    + `ParserState.stateParseRaw` -> `ReaderOptions.readerParseRaw`.
-    + `ParserState.stateColumns` -> `ReaderOptions.readerColumns`.
-    + `ParserState.stateTabStop` -> `ReaderOptions.readerTabStop`.
-    + `ParserState.stateOldDashes` -> `ReaderOptions.readerOldDashes`.
-    + `ParserState.stateLiterateHaskell` -> `ReaderOptions.readerLiterateHaskell`.
-    + `ParserState.stateCitations` -> `ReaderOptions.readerReferences`.
-    + `ParserState.stateApplyMacros` -> `ReaderOptions.readerApplyMacros`.
-    + `ParserState.stateIndentedCodeClasses` ->
-      `ReaderOptions.readerIndentedCodeClasses`.
-    + Added `ReaderOptions.readerCitationStyle`.
-
-  * `WriterOptions` now includes `writerEpubVersion`, `writerEpubChapterLevel`,
-    `writerEpubStylesheet`, `writerEpubFonts`, `writerReferenceODT`,
-    `writerReferenceDocx`, and `writerTOCDepth`.  `writerEPUBMetadata` has
-    been renamed `writerEpubMetadata` for consistency.
-
-  * Changed signatures of `writeODT`, `writeDocx`, `writeEPUB`, since they no
-    longer stylesheet, fonts, reference files as separate parameters.
-
-  * Removed `writerLiterateHaskell` from `WriterOptions`, and
-    `readerLiterateHaskell` from `ReaderOptions`.  LHS is now handled
-    by an extension (`Ext_literate_haskell`).
-
-  * Removed deprecated `writerXeTeX`.
-
-  * Removed `writerStrict` from `WriterOptions`.  Added `writerExtensions`.
-    Strict is now handled through extensions.
-
-  * `Text.Pandoc.Options` exports `pandocExtensions`, `strictExtensions`,
-    `phpMarkdownExtraExtensions`, `githubMarkdownExtensions`,
-    and `multimarkdownExtensions`, as well as the `Extensions` type.
-
-  * New `Text.Pandoc.Readers.MediaWiki` module, exporting
-    `readMediaWiki`.
-
-  * New `Text.Pandoc.Writers.FB2` module, exporting `writeFB2`
-    (thanks to Sergey Astanin).
-
-  * `Text.Pandoc`:
-
-    + Added `getReader`, `getWriter` to `Text.Pandoc`.
-    + `writers` is now an association list `(String, Writer)`.
-      A `Writer` can be a `PureStringWriter`, an `IOStringWriter`, or
-      an `IOByteStringWriter`.  ALL writers are now in the 'writers'
-      list, including the binary writers and FB2 writer.  This allows
-      code in `pandoc.hs` to be simplified.
-    + Changed type of `readers`, so all readers are in IO.
-      Users who want pure readers can still get them form the reader
-      modules; this just affects the function `getReader` that looks up
-      a reader based on the format name.  The point of this change is to
-      make it possible to print warnings from the parser.
-
-  * `Text.Pandoc.Parsing`:
-
-    + `Text.Parsec` now exports all Parsec functions used in pandoc code.
-      No other module directly imports Parsec.  This will make it easier
-      to change the parsing backend in the future, if we want to.
-    + `Text.Parsec` is used instead of `Text.ParserCombinators.Parsec`.
-    + Export the type synonym `Parser`.
-    + Export `widthsFromIndices`, `NoteTable'`, `KeyTable'`, `Key'`, `toKey'`,
-     `withQuoteContext`, `singleQuoteStart`, `singleQuoteEnd`,
-     `doubleQuoteStart`, `doubleQuoteEnd`, `ellipses`, `apostrophe`,
-     `dash`, `nested`, `F(..)`, `askF`, `asksF`, `runF`, `lineBlockLines`.
-    + `ParserState` is no longer an instance of `Show`.
-    + Added `stateSubstitutions` and `stateWarnings` to `ParserState`.
-    + Generalized type of `withQuoteContext`.
-    + Added `guardEnabled`, `guardDisabled`, `getOption`.
-    + Removed `failIfStrict`.
-    + `lookupKeySrc` and `fromKey` are no longer exported.
-
-  * `Data.Default` instances are now provided for `ReaderOptions`,
-    `WriterOptions`, and `ParserState`.  `Text.Pandoc` re-exports `def`.
-    Now you can use `def` (which is re-exported by `Text.Pandoc`) instead
-    of `defaultWriterOptions` (which is still defined).  Closes #546.
-
-  * `Text.Pandoc.Shared`:
-
-    + Added `safeRead`.
-    + Renamed `removedLeadingTrailingSpace` to `trim`,
-      `removeLeadingSpace` to `triml`, and `removeTrailingSpace` to `trimr`.
-    + Count `\r` as space in `trim` functions.
-    + Moved `renderTags'` from HTML reader and `Text.Pandoc.SelfContained`
-      to `Shared`.
-    + Removed `failUnlessLHS`.
-    + Export `compactify'`, formerly in Markdown reader.
-    + Export `isTightList`.
-    + Do not export `findDataFile`.
-    + `readDataFile` now returns a strict ByteString.
-    + Export `readDataFileUTF8` which returns a String, like the
-      old `readDataFile`.
-    + Export `fetchItem` and `openURL`.
-
-  * `Text.Pandoc.ImageSize`: Use strict, not lazy bytestrings.
-    Removed `readImageSize`.
-
-  * `Text.Pandoc.UTF8`: Export `encodePath`, `decodePath`,
-     `decodeArg`, `toString`, `fromString`, `toStringLazy`,
-     `fromStringLazy`.
-
-  * `Text.Pandoc.UTF8` is now an exposed module.
-
-  * `Text.Pandoc.Biblio`:
-
-    + csl parameter now a `String` rather than a `FilePath`.
-    + Changed type of `processBiblio`.  It is no longer in the IO monad.
-      It now takes a `Maybe Style` argument rather than parameters for CSL
-      and abbrev filenames.  (`pandoc.hs` now calls the functions to parse
-      the style file and add abbreviations.)
-
-  * Markdown reader now exports `readMarkdownWithWarnings`.
-
-  * `Text.Pandoc.RTF` now exports `writeRTFWithEmbeddedImages` instead of
-    `rtfEmbedImage`.
-
-  [bug fixes]
-
-  * Make `--ascii` work properly with `--self-contained`.  Closes #568.
-
-  * Markdown reader:
-
-    + Fixed link parser to avoid exponential slowdowns.  Closes #620.
-      Previously the parser would hang on input like this:
-
-            [[[[[[[[[[[[[[[[[[hi
-
-      We fixed this by making the link parser parser characters
-      between balanced brackets (skipping brackets in inline code spans),
-      then parsing the result as an inline list.  One change is that
-
-            [hi *there]* bud](/url)
-
-      is now no longer parsed as a link.  But in this respect pandoc behaved
-      differently from most other implementations anyway, so that seems okay.
-
-    + Look for raw html/latex blocks before tables.
-      Otherwise the following gets parsed as a table:
-
-            \begin{code}
-            --------------
-            -- My comment.
-            \end{code}
-
-      Closes #578.
-
-  * RST reader:
-
-    + Added support for `:target:` on `.. image::` blocks
-      and substitutions.
-    + Field list fixes:
-
-        - Fixed field lists items with body beginning after a new line
-          (Denis Laxalde).
-        - Allow any char but ':' in names of field lists in RST reader
-          (Denis Laxalde).
-        - Don't allow line breaks in field names.
-        - Require whitespace after field list field names.
-        - Don't create empty definition list for metadata field lists.
-          Previously a field list consisting only of metadata fields (author,
-          title, date) would be parsed as an empty DefinitionList, which is
-          not legal in LaTeX and not needed in any format.
-
-    + Don't recognize inline-markup starts inside words.
-      For example, `2*2 = 4*1` should not contain an emphasized
-      section.  Added test case for "Literal symbols".  Closes #569.
-    + Allow dashes as separator in simple tables.  Closes #555.
-    + Added support for `container`, `compound`, `epigraph`,
-      `rubric`, `highlights`, `pull-quote`.
-    + Added support for `.. code::`.
-    + Made directive labels case-insensitive.
-    + Removed requirement that directives begin at left margin.
-      This was (correctly) not in earlier releases; docutils doesn't
-      make the requirement.
-    + Added support for `replace::` and `unicode::` substitutions.
-    + Ignore unknown interpreted roles.
-    + Renamed image parser to `subst`, since it now handles all
-      substitution references.
-
-  * Textile reader:
-
-    + Allow newlines before pipes in table.  Closes #654.
-    + Fixed bug with list items containing line breaks.
-      Now pandoc correctly handles hard line breaks inside list items.
-      Previously they broke list parsing.
-    + Implemented comment blocks.
-    + Fixed bug affected words ending in hyphen.
-    + Properly handle links with surrounding brackets.
-      Square brackets need to be used when the link isn't surrounded by
-      spaces or punctuation, or when the URL ending may be ambiguous.
-      Closes #564.
-    + Removed nullBlock.  Better to know about parsing problems than
-      to skip stuff when we get stuck.
-    + Allow ID attributes on headers.
-    + Textile reader:  Avoid parsing dashes as strikeout.
-      Previously the input
-
-            text--
-            text--
-            text--
-            text--
-
-      would be parsed with strikeouts rather than dashes. This fixes
-      the problem by requiring that a strikeout delimiting - not be
-      followed by a -.  Closes #631.
-    + Expanded list of `stringBreakers`.
-      This fixes a bug on input like "(_hello_)" which should
-      be a parenthesized emphasized "hello".
-      The new list is taken from the PHP source of textile 2.4.
-    + Fixed autolinks.  Previously the textile reader and writer
-      incorrectly implented RST-style autolinks for URLs and email
-      addresses.  This has been fixed.  Now an autolink is done this way:
-      `"$":http://myurl.com`.
-    + Fixed footnotes bug in textile.  This affected notes occuring
-      before punctuation, e.g. `foo[1].`.  Closes #518.
-
-  * LaTeX reader:
-
-    + Better handling of citation commands.
-    + Better handling of `\noindent`.
-    + Added a 'try' in rawLaTeXBlock, so we can handle `\begin` without `{`.
-      Closes #622.
-    + Made `rawLaTeXInline` try to parse block commands as well.  This
-      is usually what we want, given how `rawLaTeXInline` is used in
-      the markdown and textile readers.  If a block-level LaTeX command
-      is used in the middle of a paragraph (e.g. `\subtitle` inside a title),
-      we can treat it as raw inline LaTeX.
-    + Handle \slash command.  Closes #605.
-    + Basic `\enquote` support.
-    + Fixed parsing of paragraphs beginning with a group.  Closes #606.
-    + Use curly quotes for bare straight quotes.
-    + Support obeylines environment.  Closes #604.
-    + Guard against "begin", "end" in inlineCommand and
-      blockCommand.
-    + Better error messages for environments.  Now it should tell you that
-      it was looking for \end{env}, instead of giving "unknown parse error."
-
-  * HTML reader:
-
-    + Added HTML 5 tags to list of block-level tags.
-    + HTML reader: Fixed bug in `htmlBalanced`, which
-      caused hangs in parsing certain markdown input using
-      strict mode.
-    + Parse `<q>` as `Quoted DoubleQuote`.
-    + Handle nested `<q>` tags properly.
-    + Modified `htmlTag` for fewer false positives.
-      A tag must start with `<` followed by `!`,`?`, `/`, or a letter.
-      This makes it more useful in the wikimedia and markdown parsers.
-
-  * DocBook reader: Support title in "figure" element.  Closes #650.
-
-  * MediaWiki writer:
-
-    + Remove newline after `<br/>` in translation of `LineBreak`
-      There's no particular need for a newline (other than making the
-      generated MediaWiki source look nice to a human), and in fact
-      sometimes it is incorrect: in particular, inside an enumeration, list
-      items cannot have embedded newline characters. (Brent Yorgey)
-    + Use `<code>` not `<tt>` for Code.
-
-  * Man writer: Escape `-` as `\-`.
-    Unescaped `-`'s become hyphens, while `\-`'s are left as ascii minus
-    signs.  That is preferable for use with command-line options.  See
-    <http://lintian.debian.org/tags/hyphen-used-as-minus-sign.html>.  Thanks
-    to Andrea Bolognani for bringing the issue to our attention.
-
-  * RST writer:
-
-    + Improved line block output. Use nonbreaking spaces for
-      initial indent (otherwise lost in HTML and LaTeX).
-      Allow multiple paragraphs in a single line block.
-      Allow soft breaks w continuations in line blocks.
-    + Properly handle images with no alt text.  Closes #678.
-    + Fixed bug with links with duplicate text.  We now (a) use anonymous
-      links for links with inline URLs, and (b) use an inline link instead
-      of a reference link if the reference link would require a label that
-      has already been used for a different link.  Closes #511.
-    + Fixed hyperlinked images. Closes #611. Use `:target:`
-      field when you have a simple linked image.
-    + Don't add `:align: center` to figures.
-
-  * Texinfo writer:  Fixed internal cross-references.
-    Now we insert anchors after each header, and use `@ref` instead of `@uref`
-    for links.  Commas are now escaped as `@comma{}` only when needed;
-    previously all commas were escaped.  (This change is needed, in part,
-    because `@ref` commands must be followed by a real comma or period.) Also
-    insert a blank line in from of `@verbatim` environments.
-
-  * DocBook writer:
-
-    + Made --id-prefix work in DocBook as well as HTML.
-      Closes #607.
-    + Don't include empty captions in figures.  Closes #581.
-
-  * LaTeX writer:
-
-    + Use `\hspace*` for nonbreaking space after line break,
-      since `~` spaces after a line break are just ignored.
-      Closes #687.
-    + Don't escape `_` in URLs or hyperref identifiers.
-    + Properly escape strings inside \url{}.  Closes #576.
-    + Use `[fragile]` only for slides containing code rendered
-      using listings. Closes #649.
-    + Escape `|` as `\vert` in LaTeX math.  This avoids a clash with
-      highlighting-kate's macros, which redefine `|` as a short verbatim
-      delimiter.  Thanks to Björn Peemöller for raising this issue.
-    + Use minipage rather than parbox for block containers in tables.
-      This allows verbatim code to be included in grid tables.
-      Closes #663.
-    + Prevent paragraphs containing only linebreaks or spaces.
-
-  * HTML writer:
-
-    + Included `highlighting-css` for code spans, too.
-      Previously it was only included if used in a code block.  Closes #653.
-    + Improved line breaks with `<dd>` tags.  We now put a newline between
-      `</dd>` and `<dd>` when there are multiple definitions.
-    + Changed mathjax cdn url so it doesn't use https.  (This caused
-      problems when used with `--self-contained`.) See #609.
-
-  * EPUB writer:
-
-    + `--number-sections` now works properly.
-    + Don't strip meta and link elements in epub metadata.
-      Patch from aberrancy. Closes #589.
-    + Fixed a couple validation bugs.
-    + Use ch001, ch002, etc. for chapter filenames.  This improves sorting
-      of chapters in some readers, which apparently sort ch2 after ch10.
-      Closes #610.
-
-  * ODT writer: properly set title property (Arlo O'Keeffe).
-
-  * Docx writer:
-
-    + Fixed bug with nested lists.  Previously a list like
-
-            1. one
-                - a
-                - b
-            2. two
-
-      would come out with a bullet instead of "2."
-      Thanks to Russell Allen for reporting the bug.
-    + Use `w:cr` in `w:r` instead of `w:br` for linebreaks.
-      This seems to fix a problem viewing pandoc-generated
-      docx files in LibreOffice.
-    + Use integer ids for bookmarks.  Closes #626.
-    + Added nsid to abstractNum elements.  This helps when merging
-      word documents with numbered or bulleted lists.  Closes #627.
-    + Use separate footnotes.xml for notes.
-      This seems to help LibreOffice convert the file, even though
-      it was valid docx before.  Closes #637.
-    + Use rIdNN identifiers for r:embed in images.
-    + Avoid reading image files again when we've already processed them.
-    + Fixed typo in `referenc.docx` that prevented image captions from
-      working. Thanks to Huashan Chen.
-
-  * `Text.Pandoc.Parsing`:
-
-    + Fixed bug in `withRaw`, which didn't correctly handle the case
-      where nothing is parsed.
-    + Made `emailAddress` parser more correct.  Now it is based on RFC 822,
-      though it still doesn't implement quoted strings in email addresses.
-    + Revised URI parser.  It now allows many more schemes, allows
-      uppercase URIs, and better handles trailing punctuation and
-      trailing slashes in bare URIs.  Added many tests.
-    + Simplified and improved singleQuoteStart.  This makes `'s'`, `'l'`,
-      etc. parse properly.  Formerly we had some English-centric heuristics,
-      but they are no longer needed. Closes #698.
-
-  * `Text.Pandoc.Pretty`:  Added wide punctuation range to `charWidth`.
-    This fixes bug with Chinese commas in markdown and reST tables, and
-    a bug that caused combining characters to be dropped.
-
-  * `Text.Pandoc.MIME`: Added MIME types for .wof and .eot.  Closes #640.
-
-  * `Text.Pandoc.Biblio`:
-
-    + Run `mvPunc` and `deNote` on metadata too.
-      This fixed a bug with notes on titles using footnote styles.
-    + Fixed bug in fetching CSL files from CSL data directory.
-
-  * `pandoc.hs`:  Give correct value to `writerSourceDirectory` when a URL
-    is provided.  It should be the URL up to the path.
-
-  * Fixed/simplified diff output for tests.
-    Biblio: Make sure mvPunc and deNote run on metadata too.
-    This fixed a bug with notes on titles using footnote styles.
-
-  [under the hood improvements]
-
-  * We no longer depend on `utf8-string`.  Instead we use functions
-    defined in `Text.Pandoc.UTF8` that use `Data.Text`'s conversions.
-
-  * Use `safeRead` instead of using `reads` directly (various modules).
-
-  * "Implicit figures" (images alone in a paragraph) are now handled
-    differently.  The markdown reader gives their titles the prefix `fig:`; the
-    writers look for this before treating the image as a figure.  Though this
-    is a bit of a hack, it has two advantages: (i) implicit figures can be
-    limited to the markdown reader, and (ii) they can be deactivated by turning
-    off the `implicit_figures` extension.
-
-  * `catch` from `Control.Exception` is now used instead of the
-    old Preface `catch`.
-
-  * `Text.Pandoc.Shared`:  Improved algorithm for `normalizeSpaces`
-    and `oneOfStrings` (which is now non-backtracking).
-
-  * `Text.Pandoc.Biblio`: Remove workaround for `toCapital`.
-    Now citeproc-hs is fixed upstream, so this is no longer needed.
-    Closes #531.
-
-  * Textile reader: Improved speed of `hyphenedWords`.
-    This speeds up the textile  reader by about a factor of 4.
-
-  * Use `Text.Pandoc.Builder` in RST reader, for more flexibility,
-    better performance, and automatic normalization.
-
-  * Major rewrite of markdown reader:
-
-    + Use `Text.Pandoc.Builder` instead of lists.  This also
-      means that everything is normalized automatically.
-    + Move to a one-pass parsing strategy, returning values in the reader
-      monad, which are then run (at the end of parsing) against the final
-      parser state.
-
-  * In HTML writer, we now use `toHtml` instead of pre-escaping.
-    We work around the problem that blaze-html unnecessarily escapes `'`
-    by pre-escaping just the `'` characters, instead of the whole string.
-    If blaze-html later stops escaping `'` characters, we can simplify
-    `strToHtml` to `toHtml`.  Closes #629.
-
-  * Moved code for embedding images in RTFs from `pandoc.hs` to the
-    RTF writer (which now exports `writeRTFWithEmbeddedImages`).
-
-  * Moved citation processing from `pandoc.hs` into the readers.
-    This makes things more convenient for library users.
-
-  * The man pages are now built by an executable `make-pandoc-man-pages`,
-    which has its own stanza in the cabal file so that dependencies can be
-    handled by Cabal. Special treatment in `Setup.hs` ensures that this
-    executable never gets installed; it is only used to create the man pages.
-
-  * The cabal file has been modified so that the pandoc library is used
-    in building the pandoc executable.  (This required moving `pandoc.hs`
-    from `src` to `.`.)  This cuts compile time in half.
-
-  * `-O2` is no longer used in building pandoc.  The performance improvement
-    it yields is so slight that it is not worth it.  (Measured with
-    benchmarks on ghc 7.4.)
-
-  * The `executable` and `library` flags have been removed.
-
-  * `-threaded` has been removed from ghc-options.
-
-  * Version bounds of dependencies have been raised, and the
-    `blaze_html_0_5` flag now defaults to True.  Pandoc now compiles on
-    GHC 7.6.
-
-  * We now require base >= 4.2.
-
-  * Integrated the benchmark program into cabal.  One can now do:
-
-        cabal configure --enable-benchmarks && cabal build
-        cabal bench --benchmark-option='markdown' --benchmark-option='-s 20'
-
-    The benchmark now uses README + testsuite, so benchmark results
-    from older versions aren't comparable.
-
-  * Integrated test suite with cabal.
-    To run tests, configure with `--enable-tests`, then `cabal test`.
-    You can specify particular tests using `--test-options='-t markdown'`.
-    No output is shown unless tests fail.  The Haskell test modules
-    have been moved from `src/` to `tests/`.
-
-  * Moved all data files and templates to the `data/` subdirectory.
-
-  * Added an `embed_data_files` cabal flag.  This causes all
-    data files to be embedded in the binary, so that the binary
-    is self-sufficient and can be relocated anywhere, copied on
-    a USB key, etc.  The Windows installer now uses this.
-    (Since we no longer have the option to build the executable
-    without the library, this is the only way to get a relocatable
-    binary on Windows.)
-
-  * Removed pcre3.dll from windows package.
-    It isn't needed unless highlighting-kate is compilled with the
-    `pcre-light` flag. By default, regex-prce-builtin is used.
-
-
-pandoc (1.9.4.2)
-
-  * Don't encode/decode file paths if base >= 4.4.
-    Prior to base 4.4, filepaths and command line arguments were treated
-    as unencoded lists of bytes, not unicode strings, so we had to work
-    around that by encoding and decoding them. This commit adds CPP
-    checks for the base version that intelligibly enable encoding/decoding
-    when needed. Fixes a bug with multilingual filenames when pandoc was
-    compiled with ghc 7.4 (#540).
-
-  * Don't generate an empty H1 after hrule slide breaks.
-    We now use a slide-level header with contents `[Str "\0"]` to mark
-    an hrule break.  This avoids creation of an empty H1 in these
-    contexts.  Closes #484.
-
-  * Docbook reader: Added support for "bold" emphasis.  Thanks to Mauro Bieg.
-
-  * In make_osx_package.sh, ensure citeproc-hs is built with the
-    embed_data_files flag.
-
-  * MediaWiki writer: Avoid extra blank lines after sublists (Gavin Beatty).
-
-  * ConTeXt writer: Don't escape `&`, `^`, `<`, `>`, `_`,
-    simplified escapes for `}` and `{` to `\{` and `\}` (Aditya Mahajan).
-
-  * Fixed handling of absolute URLs in CSS imports with `--self-contained`.
-    Closes #535.
-
-  * Added webm to mime types. Closes #543.
-
-  * Added some missing exports and tests to the cabal file
-    (Alexander V Vershilov).
-
-  * Compile with `-rtsopts` and `-threaded` by default.
-
-pandoc (1.9.4.1)
-
-  * Markdown reader: Added `cf.` and `cp.` to list of likely abbreviations.
-
-  * LaTeX template: Added `linkcolor`, `urlcolor` and `links-as-notes`
-    variables.  Make TOC links black.
-
-  * LaTeX template improvements.
-
-    + Don't print date unless one is given explicitly in the document.
-    + Simplified templates.
-    + Use fontenc [T1] by default, and lmodern.
-    + Use microtype if available.
-
-  * Biblio:
-
-    + Add comma to beginning of bare suffix, e.g. `@item1 [50]`.
-      Motivation: `@item1 [50]` should be as close as possible to
-      `[@item1, 50]`.
-    + Added workaround for a bug in citeproc-hs 0.3.4 that causes footnotes
-      beginning with a citation to be empty.  Closes #531.
-
-  * Fixed documentation on mixed lists.  Closes #533.
-
-pandoc (1.9.4)
-
-  * Simplified `Text.Pandoc.Biblio` and fixed bugs with citations inside
-    footnotes and captions.  We now handle note citations by inserting
-    footnotes during initial citation processing, and doing a separate
-    pass later to remove notes inside notes.
-
-  * Added 'zenburn' highlight style from highlighting-kate.
-
-  * Added Slideous writer. Slideous is an HTML + javascript slide show
-    format, similar to Slidy, but works with IE 7. (Jonas Smedegaard)
-
-  * LaTeX writer:
-
-    + Ensure we don't have extra blank lines at ends of cells.
-      This can cause LaTeX errors, as they are interpreted as new paragraphs.
-    + More consistent interblock spacing.
-    + Require highlighting-kate >= 0.5.1, for proper highlighted inline
-      code in LaTeX.  Closes #527.
-    + Ensure that a Verbatim at the end of a footnote is followed by
-      a newline. (Fixes a regression in the previous version.)
-    + In default template, use black for internal links and TOC.
-      Added commented-out code to use footnotes for links, as would
-      be suitable in print output.
-
-  * Beamer writer:  When `--incremental` is used, lists inside
-    a block quote should appear all at once.  (This makes Beamer
-    output consistent with the HTML slide show formats.)
-
-  * ConTeXt writer:
-
-    + Escape `%` as `\letterpercent{}` not `\letterpercent `,
-      to avoid gobbling spaces after the `%` sign.
-    + Ensure space after `\stopformula`.
-
-  * Markdown writer:
-
-    + Use `:` form instead of `~` in definition lists, for better
-      compatibility with other markdown implementations.
-    + Don't wrap the term, because it breaks definition lists.
-    + Use a nonzero space to prevent false recognition
-      of list marker in ordered lists.  Closes #516.
-
-  * Org writer: Add space before language name.  Closes #523.
-
-  * Docx writer: Simplified bullet characters so they work properly
-    with Word 2007. Closes #520.
-
-  * LaTeX reader: Support `\centerline`.
-
-  * RST reader:  handle figures.  Closes #522.
-
-  * Textile reader: fix for `<notextile>` and `==`.  Closes #517.
-    (Paul Rivier)
-
-pandoc (1.9.3)
-
-  * Fixed bug in `fromEntities`.  The previous version would turn
-    `hi & low you know;` into `hi &`.
-
-  * HTML reader:
-
-    + Don't skip nonbreaking spaces.
-      Previously a paragraph containing just `&nbsp;` would be rendered
-      as an empty paragraph. Thanks to Paul Vorbach for pointing out the bug.
-    + Support `<col>` and `<caption>` in tables. Closes #486.
-
-  * Markdown reader:
-
-    + Don't recognize references inside delimited code blocks.
-    + Allow list items to begin with lists.
-
-  * Added basic docbook reader (John MacFarlane and Mauro Bieg).
-
-  * LaTeX reader:
-
-    + Handle `\bgroup`, `\egroup`, `\begingroup`, `\endgroup`.
-    + Control sequences can't be followed by a letter.
-      This fixes a bug where `\begingroup` was parsed as `\begin`
-      followed by `group`.
-    + Parse 'dimension' arguments to unknown commands.  e.g. `\parindent0pt`
-    + Make `\label` and `\ref` sensitive to `--parse-raw`.
-      If `--parse-raw` is selected, these will be parsed as raw latex
-      inlines, rather than bracketed text.
-    + Don't crash on unknown block commands (like `\vspace{10pt}`)
-      inside `\author`; just skip them.  Closes #505.
-
-  * Textile reader:
-
-    + Implemented literal escapes with `==` and `<notextile>`.  Closes #473.
-    + Added support for LaTeX blocks and inlines (Paul Rivier).
-    + Better conformance to RedCloth inline parsing (Paul Rivier).
-    + Parse '+text+' as emphasized (should be underlined, but this
-      is better than leaving literal plus characters in the output.
-
-  * Docx writer: Fixed multi-paragraph list items.  Previously they each
-    got a list marker.  Closes #457.
-
-  * LaTeX writer:
-
-    + Added `--no-tex-ligatures` option to avoid replacing
-      quotation marks and dashes with TeX ligatures.
-    + Use `fixltx2e` package to provide '\textsubscript'.
-    + Improve spacing around LaTeX block environments:
-      quote, verbatim, itemize, description, enumerate.
-      Closes #502.
-    + Use blue instead of pink for URL links in latex/pdf output.
-
-  * ConTeXt writer: Fixed escaping of `%`.
-    In text, `%` needs to be escaped as `\letterpercent`, not `\%`
-    Inside URLs, `%` needs to be escaped as `\%`
-    Thanks to jmarca and adityam for the fix.  Closes #492.
-
-  * Texinfo writer:  Escape special characters in node titles.
-    This fixes a problem pointed out by Joost Kremers.  Pandoc used
-    to escape an '@' in a chapter title, but not in the corresponding
-    node title, leading to invalid texinfo.
-
-  * Fixed document encoding in texinfo template.
-    Resolves Debian Bug #667816.
-
-  * Markdown writer:
-
-    + Don't force delimited code blocks to be flush left.
-      Fixes bug with delimited code blocks inside lists etc.
-    + Escape `<` and `$`.
-
-  * LaTeX writer: Use `\hyperref[ident]{text}` for internal links.
-    Previously we used `\href{\#ident}{text}`, which didn't work on
-    all systems. Thanks to Dirk Laurie.
-
-  * RST writer: Don't wrap link references.  Closes #487.
-
-  * Updated to use latest versions of blaze-html, mtl.
-
-
-pandoc (1.9.2)
-
-  * LaTeX reader:
-
-    + Made `lstlisting` work as a proper verbatim environment.
-    + Fixed bug parsing LaTeX tables with one column.
-
-  * LaTeX writer:
-
-    + Use `{}` around `ctable` caption, so that formatting can be used.
-    + Don't require eurosym package unless document has a €.
-
-  * LaTeX template: Added variables for `geometry`, `romanfont`,
-    `sansfont`, `mathfont`, `mainfont` so users can more easily
-    customize fonts.
-
-  * PDF writer:
-
-    + Run latex engine at least two times, to ensure
-      that PDFs will have hyperlinked bookmarks.
-    + Added PDF metadata (title,author) in LaTeX standalone + PDF output.
-
-  * Texinfo writer: retain directories in image paths.  (Peter Wang)
-
-  * RST writer:  Better handling of inline formatting, in accord
-    with docutils' "inline markup recognition rules" (though we don't
-    implement the unicode rules fully). Now `hi*there*hi` gets
-    rendered properly as `hi\ *there*\ hi`, and unnecessary
-    `\ ` are avoided around `:math:`, `:sub:`, `:sup:`.
-
-  * RST reader:
-
-    + Parse `\ ` as null, not escaped space.
-    + Allow `` :math:`...` `` even when not followed by blank
-      or `\`.  This does not implement the complex rule docutils follows,
-      but it should be good enough for most purposes.
-    + Add support for the rST default-role directive. (Greg Maslov)
-
-  * Text.Pandoc.Parsing: Added `stateRstDefaultRole` field to `ParserState`.
-    (Greg Maslov)
-
-  * Markdown reader: Properly handle citations nested in other inline
-    elements.
-
-  * Markdown writer:  don't replace empty alt in image with "image".
-
-  * DZSlides:  Updated template.html and styles in default template.
-    Removed bizarre CSS for `q` in dzslides template.
-
-  * Avoid repeated `id` attribute in section and header in HTML slides.
-
-  * README improvements:  new instructions on internal links,
-    removed misleading note on reST math.
-
-  * Build system:
-
-    + Fixed Windows installer so that dzslides works.
-    + Removed stripansi.sh.
-    + Added .travis.yml for Travis continuous integration support..
-    + Fixed upper bound for zlib (Sergei Trofimovich).
-    + Fixed upper bound for test-framework.
-    + Updated haddocks for haddock-2.10 (Sergei Trofimovich).
-
-pandoc (1.9.1.2)
-
-  * Added `beamer+lhs` as output format.
-
-  * Don't escape `<` in `<style>` tags with `--self-contained`.
-    This fixes a bug which prevented highlighting from working
-    when using `--self-contained`.
-
-  * PDF: run latex engine three times if `--toc` specified.
-    This fixes page numbers in the table of contents.
-
-  * Docx writer: Added TableNormal style to tables.
-
-  * LaTeX math environment fixes. `aligned` is now used instead of
-    the nonexistent `aligned*`. `multline` instead of the nonexistent
-    `multiline`.
-
-  * LaTeX writer: Use `\textasciitilde` for literal `~`.
-
-  * HTML writer: Don't escape contents of EQ tags with --gladtex.
-    This fixes a regression from 1.8.
-
-  * Use `<q>` tags for Quoted items for HTML5 output.
-    The quote style can be changed by modifying the template
-    or including a css file. A default quote style is included.
-
-  * LaTeX reader: Fixed accents (\~{a}, `\c{c}`).
-    Correctly handle \^{}. Support "minted" as a LaTeX verbatim block.
-
-  * Updated LaTeX template for better language support.
-    Use `polyglossia` instead of `babel` with xetex.
-    Set `lang` as documentclass option.
-    `\setmainlanguage` will use the last of a comma-separated
-    list of languages. Thanks to François Gannaz.
-
-  * Fixed default LaTeX template so `\euro` and `€` work.  The
-    `eurosym` package is needed if you are using pdflatex.
-
-  * Fixed escaping of period in man writer (thanks to Michael Thompson).
-
-  * Fixed list label positions in beamer.
-
-  * Set `mainlang` variable in context writer.
-    This parallels behavior of latex writer.  `mainlang` is the last
-    of a comma-separated list of languages in lang.
-
-  * EPUB language metadat: convert e.g. `en_US` from locale to `en-US`.
-
-  * Changed `-V` so that you can specify a key without a value.
-    Such keys get the value `true`.
-
-  * Fixed permissions on installed man pages - thanks Magnus Therning.
-
-  * Windows installer: require XP or higher.  The installer is
-    now compiled on a Windows 7 machine, which fixes a problem
-    using citation functions on Windows 7.
-
-  * OSX package: Check for 64-bit Intel CPU before installing.
-
-pandoc (1.9.1.1)
-
-  * Better handling of raw latex environments in markdown.  Now
-
-        \begin{equation}
-        a_1
-        \end{equation}
-
-    turns into a raw latex block as expected.
-
-  * Improvements to LaTeX reader:
-
-    + Skip options after block commands.
-    + Correctly handle `{\\}` in braced.
-    + Added a needed 'try'.
-    + Citations: add `, ` to suffix if it doesn't start with space or
-      punctuation. Otherwise we get no space between the year and the
-      suffix in author-date styles.
-
-  * Added two needed data files for S5.  This fixes a problem with
-    `pandoc -t s5 --self-contained`.  Also removed `slides.min.js`,
-    which was no longer being used.
-
-  * Fixed some minor problems in `reference.docx`:
-    name on "Date" style, `xCs` instead of `xIs`.
-
-  * Fixed a problem creating docx files using a reference docx
-    modified using Word.  The problem seems to be that Word
-    modifies `_rels/.rels`, changing the Type of the Relationship to
-    `docProps/core.xml`. Pandoc now changes this back to the correct
-    value if it has been altered, fixing the problem.
-
-  * Fixed html5 template so it works properly with highlighting.
-
-pandoc (1.9.1)
-
-  * LaTeX reader:
-
-    + Fixed regression in 1.9; properly handle escaped $ in latex math.
-    + Put LaTeX verse environments in blockquotes.
-
-  * Markdown reader:
-
-    + Limit nesting of strong/emph.  This avoids exponential lookahead
-      in parasitic cases, like `a**a*a**a*a**a*a**a*a**a*a**a*a**a*a**`.
-    + Improved attributes syntax (inn code blocks/spans):
-      (1) Attributes can contain line breaks. (2) Values in key-value
-      attributes can be surrounded by either double or single quotes, or
-      left unquoted if they contain no spaces.
-
-  * Don't wrap headers in markdown or RST writers.
-
-  * Added `stateMaxNestingLevel` to `ParserState`.
-    We set this to 6, so you can still have `Emph` inside `Emph`,
-    just not indefinitely.
-
-  * More efficient implementation of `nowrap` in `Text.Pandoc.Pretty`.
-
-  * `Text.Pandoc.PDF`:  Only run latex twice if `\tableofcontents`
-    is present.
-
-  * Require highlighting-kate >= 0.5.0.2, texmath >= 0.6.0.2.
-
-pandoc (1.9.0.5)
-
-  * Changed cabal file so that build-depends for the test program
-    are not required unless the tests flag is used.
-
-  * LaTeX writer:  insert `{}` between adjacent hyphens so they don't
-    form ligatures (dashes) in code spans.
-
-pandoc (1.9.0.4)
-
-  * Raised version bound on test-framework to avoid problems
-    compiling tests on GHC 7.4.1.
-
-  * LaTeX reader: Use raw LaTeX as fallback inline text for Cites,
-    so citations don't just disappear unless you process with
-    citeproc.  Ignore `\bibliographystyle`, `\nocite`.
-
-  * Simplified tex2pdf; it will always run latex twice to
-    resolve table of contents and hyperrefs.
-
-pandoc (1.9.0.3)
-
-  * Require Cabal >= 1.10.
-  * Tweaked cabal file to meet Cabal 1.10 requirements.
-
-pandoc (1.9.0.2)
-
-  * Allow build with json 0.4 or 0.5.  Otherwise we can't build with
-    ghc 6.12.
-
-pandoc (1.9)
-
-  [new features]
-
-  * Added a Microsoft Word `docx` writer. The writer includes support
-    for highlighted code and for math (which is converted from TeX to OMML,
-    Office's native math markup language, using texmath's new OMML module).
-    A new option `--reference-docx` allows the user to customize the
-    styles.
-
-  * Added an `asciidoc` writer (<http://www.methods.co.nz/asciidoc/>).
-
-  * Better support for slide shows:
-
-    + Added a `dzslides` writer. DZSlides is a lightweight HTML5/javascript
-      slide show format due to Paul Rouget (<http://paulrouget.com/dzslides/>).
-
-    + Added a LaTeX `beamer` writer. Beamer is a LaTeX package for creating
-      slide presentations.
-
-    + New, flexible rules for dividing documents into sections and slides
-      (see the "Structuring the slide show" in the User's Guide).  These
-      are backward-compatible with the old rules, but they allow slide
-      shows to be organized into sections and subsections containing
-      multiple slides.
-
-    + A new `--slide-level` option allows users to override defaults
-      and select a slide level below the first header level with content.
-
-  * A new `--self-contained` option produces HTML output that does not
-    depend on an internet connection or the presence of any external
-    files. Linked images, CSS, and javascript is downloaded (or fetched
-    locally) and encoded in `data:` URIs. This is useful for making portable
-    `HTML slide shows. The --offline` option has been deprecated and is now
-    `treated as a synonym or --self-contained`.
-
-  * Support for PDF output:
-
-    + Removed the old `markdown2pdf`.
-    + `pandoc` can now create PDFs (assuming you have latex and a set of
-      appropriate packages installed): just specify an output file with the
-      `.pdf` extension.
-    + A new option `--latex-engine` allows you to specify `pdflatex`,
-      `xelatex`, or `lualatex` as the processor.
-
-  * Highlighting changes:
-
-    + Syntax highlighting is now a standard feature; the `highlighting`
-      flag is no longer needed when compiling.
-    + A new `--no-highlight` option allows highlighting to be disabled.
-    + Highlighting now works in `docx`, `latex`, and `epub`, as well as
-      `html`, `html5`, `dzslides`, `s5`, and `slidy`.
-    + A new `--highlight-style` option selects between various highlighting
-      color themes.
-
-  * Internal links to sections now work in ConTeXt and LaTeX as well as HTML.
-
-  * LaTeX `\include` and `\usepackage` commands are now processed,
-    provided the files are in the working directory.
-
-  * EPUB improvements:
-
-    + Internal and external links now work in EPUB.
-    + Raw HTML is allowed.
-    + New `--epub-embed-font` option.
-    + Customizable templates for EPUB pages offer more control over
-      formatting: `epub-page.html`, `epub-coverimage.html`,
-      `epub-titlepage.html`.
-
-  * `--mathml` now works with DocBook.
-
-  * Added support for math in RST reader and writer.  Inline math uses the
-    `` :math:`...` `` construct.  Display math uses
-
-        .. math:: ...
-
-    or if the math is multiline,
-
-        .. math::
-
-           ...
-
-    These constructions are now supported now by `rst2latex.py`.
-
-  * GitHub syntax for fenced code blocks is supported in pandoc's
-    markdown.  You can now write
-
-        ```ruby
-        x = 2
-        ```
-
-    instead of
-
-        ~~~ {.ruby}
-        x = 2
-        ~~~~
-
-  * Easier scripting:  a new `toJsonFilter` function makes it easier to
-    write Haskell scripts to manipulate the Pandoc AST.
-
-  [behavior changes]
-
-  * Fixed parsing of consecutive lists in markdown.
-    Pandoc previously behaved like Markdown.pl for consecutive
-    lists of different styles. Thus, the following would be parsed
-    as a single ordered list, rather than an ordered list followed
-    by an unordered list:
-
-        1. one
-        2. two
-
-        - one
-        - two
-
-    This change makes pandoc behave more sensibly, parsing this as
-    two lists.  Any change in list type (ordered/unordered) or in
-    list number style will trigger a new list. Thus, the following
-    will also be parsed as two lists:
-
-        1. one
-        2. two
-
-        a. one
-        b. two
-
-    Since we regard this as a bug in Markdown.pl, and not something
-    anyone would ever rely on, we do not preserve the old behavior
-    even when `--strict` is selected.
-
-  * Dashes work differently with `--smart`: `---` is always em-dash,
-    and `--` is always en-dash.  Pandoc no longer tries to guess when
-    `-` should be en-dash.  *Note:* This may change how existing documents
-    look when processed with pandoc. A new option, `--old-dashes`,
-    is provided for legacy documents.
-
-  * The markdown writer now uses setext headers for levels 1-2.
-    The old behavior (ATX headers for all levels) can be restored
-    using the new `--atx-headers` option.
-
-  * Links are now allowed in markdown image captions.  They are also
-    allowed in links, but will appear there as regular text. So,
-
-        [link with [link](/url)](/url)
-
-    will turn into
-
-        <p><a href="/url">link with link</a></p>
-
-  * Improved handling of citations using `citeproc-hs-0.3.4`.
-    Added `--citation-abbreviations` option.
-
-  * Citation keys can no longer end with a punctuation character.
-    This means that `@item1.` will be parsed as a citation with key
-    'item1', followed by a period, instead of a citation with key
-    'item1.', as was the case previously.
-
-  * In HTML output, citations are now put in a span with class `citation`.
-
-  * The markdown reader now recognizes DocBook block and inline tags.
-    It was always possible to include raw DocBook tags in a markdown
-    document, but now pandoc will be able to distinguish block from
-    inline tags and behave accordingly. Thus, for example,
-
-        <sidebar>
-        hello
-        </sidebar>
-
-    will not be wrapped in `<para>` tags.
-
-  * The LaTeX parser has been completely rewritten; it is now much more
-    accurate, robust, and extensible. However, there are two important
-    changes in how it treats unknown LaTeX. (1) Previously, unknown
-    environments became BlockQuote elements; now, they are treated
-    as "transparent", so `\begin{unknown}xyz\end{unknown}` is the
-    same as `xyz`.  (2) Previously, arguments of unknown commands
-    were passed through with their braces; now the braces are stripped
-    off.
-
-  * `--smart` is no longer selected automatically with `man` output.
-
-  * The deprecated `--xetex` option has been removed.
-
-  * The `--html5`/`-5` option has been deprecated. Use `-t html5`
-    instead. `html5` and `html5+lhs` are now separate output formats.
-
-  * Single quotes are no longer escaped in HTML output.  They do not
-    need to be escaped outside of attributes.
-
-  * Pandoc will no longer transform leading newlines in code
-    blocks to `<br/>` tags.
-
-  * The ODT writer now sizes images appropriately, using the image
-    size and DPI information embedded in the image.
-
-  * `--standalone` is once again implicitly for a non-text output format
-    (ODT, EPUB).  You can again do `pandoc test.txt -o test.odt`
-    and get a standalone ODT file.
-
-  * The Docbook writer now uses `<sect1>`, `<sect2>`, etc. instead of
-    `<section>`.
-
-  * The HTML writer now uses `<del>` for strikeout.
-
-  * In HTML output with `--section-divs`, the classes `section` and
-    `level[1,2,..6]` are put on the `div` tags so they can be styled.
-    In HTML 5 output with `--section-divs`, the classes
-    `level[1,2,...6]` are put on `section` tags.
-
-  * EPUB writer changes:
-
-    + The `lang` variable now sets the language
-      in the metadata (if it is not set, we default to the locale).
-    + EPUB:  UTF-8 is used rather than decimal entities.
-
-  * Added `titleslide` class to title slide in S5 template.
-
-  * In HTML, EPUB, and docx metadata, the date is normalized into
-    YYYY-MM-DD format if possible. (This is required for validation.)
-
-  * Attributes in highlighted code blocks are now preserved in HTML.
-    The container element will have the classes, id, and key-value attributes
-    you specified in the delimited code block. Previously these were stripped
-    off.
-
-  * The reference backlink in the HTML writer no longer has a special
-    `footnoteBacklink` class.
-
-  * The HTML template has been split into `html` and `html5` templates.
-
-  * Author and date are treated more consistently in HTML templates.
-    Authors are now `<h2>`, date `<h3>`.
-
-  * URLs are hyphenated in the ConTeXt writer (B. Scott Michel).
-
-  * In `Text.Pandoc.Builder`, `+++` has been replaced by `<>`.
-
-  [bug fixes]
-
-  * Better support for combining characters and East Asian wide characters
-    in markdown and reST.
-
-  * Better handling of single quotes with `--smart`.
-    Previously `D'oh l'*aide*` would be parsed with left and right single
-    quotes instead of apostrophes. This kind of error is now fixed.
-
-  * Highlighting: Use `reads` instead of `read` for better error handling.
-    Fixes crash on `startNum="abc"`.
-
-  * Added blank comment after directives in rst template.
-
-  * Unescape entities in citation `refId`. The `refId`s coming
-    from citeproc contain XML numeric entities, and these don't match with the
-    citation keys parsed by pandoc. Solution is to unescape them.
-
-  * HTML reader: Fixed bug parsing tables with both thead and tbody.
-
-  * Markdown reader:
-
-    + Better handling of escapes in link URLs and titles.
-    + Fixed backslash escapes in reference links.
-    + Fixed bug in table/hrule parsing, by checking that the top
-      line of a table is not followed by a blank line. This bug caused
-      slowdowns on some files with hrules and tables, as pandoc tried to
-      interpret the hrules as the tops of multiline tables.
-    + Fixed bug in code block attribute parser. Previously the ID attribute
-      got lost if it didn't come first. Now attributes can come in any order.
-
-  * RST reader: allow footnotes followed by newline without space characters.
-
-  * LaTeX reader:
-
-    + Ignore empty groups {}, { }.
-    + LaTeX reader: Handle \@.
-    + LaTeX reader:  Don't crash on commands like `\itemsep`.
-    + LaTeX reader:  Better handling of letter environments.
-
-  * RST writer: Fixed bug involving empty table cells. isSimple was being
-    calculated in a way that assumed there were no non-empty cells.
-
-  * ConTeXt writer:
-
-    + Made `--toc` work even without `--number-sections`.
-    + Escape # in link URLs.
-    + Use buffering for footnotes containing code blocks.
-    + Changed 'descr' to 'description', fixed alignment.
-
-  * LaTeX writer:
-
-    + Escape euro character.
-    + Don't escape ~ inside href{...}.
-    + Escape # in href URLs.
-    + Improved detection of book classes.  We now check the
-      `documentclass` variable, and if that is not set, we look through
-      the template itself.  Also, we have added the KOMA classes scrreprt
-      and scrbook.  You can now make a book using
-      `pandoc -V documentclass:book mybook.txt -o mybook.pdf`
-    + LHS files now set the "listings" variable, so that the definition
-      of the `code` environment will be included in the template.
-    + Links are colored blue by default (this can be changed by
-      modifying `hyperref` settings in the template).
-    + Added `lang` variable to LaTeX template.
-
-  * HTML writer:
-
-    + Fixed bug in HTML template with html5 and mathml.
-    + Don't use self-closing img, br, hr tags for HTML5.
-    + Use `<section>` for footnotes if HTML5.
-    + Update HTML templates to use Content-Style-Type meta tag.
-    + Use separate variables for meta-date, meta-author.
-      This makes footnotes work in author and date fields.
-    + Use 'vertical-align:middle' in WebTeX math for better alignment.
-
-  * S5/slidy writer:  Make footnotes appear on separate slide at end.
-
-  * MIME: Added 'layout-cache' to getMimeType. This ensures that the
-    META-INF/manifest.xml for ODT files will have everything it needs, so
-    that ODT files modified by LibreOffice can be used as `--reference-odt`.
-
-  * `Text.Pandoc.Templates`: Return empty string for json template.
-
-  * `Text.Pandoc.Biblio`:
-
-    + Expand citations recursively inside nested inlines.
-    + Treat `\160` as space when parsing locator and suffix.
-      This fixes a bug with "p. 33" when `--smart` is used. Previously
-      the whole "p. 33" would be included in the suffix, with no locator.
-    + Put whole author-in-text citation in a Cite.  Previously just the
-      date and other info went in the Cite.
-    + Don't add comma+space to prefix if it ends in punctuation.
-
-  * Updated chicago-author-date.csl.  The old version did not work
-    properly for edited volumes with no author.
-
-  * EPUB writer:
-
-    + Add date to EPUB titlepage and metadata.
-    + Added TOC identifier in EPUB page template.
-    + Don't generate superfluous file `cover-image.jpg`.
-
-  [under the hood improvements]
-
-  * Modified `make_osx_package.sh` to use cabal-dev.
-    Items are no longer installed as root.
-    Man pages are zipped and given proper permissions.
-
-  * Modified windows installer generater to use cabal-dev.
-
-  * Setup: Making man pages now works with cabal-dev (at least on OSX). In
-    Setup.hs we now invoke 'runghc' in a way that points it to the correct
-    package databases, instead of always falling back to the default user
-    package db.
-
-  * Updated to work with GHC 7.4.1.
-
-  * Removed dependency on old-time.
-
-  * Removed dependency on dlist.
-
-  * New slidy directory for "self-contained."
-
-  * TeXMath writer:  Use unicode thin spaces for thin spaces.
-
-  * Markdown citations: don't strip off initial space in locator.
-
-  [API changes]
-
-  * Removed `Apostrophe`, `EmDash`, `EnDash`, and `Ellipses`
-    from the native `Inline` type in pandoc-types.  Now we use `Str`
-    elements with unicode.
-
-  * Improvements to `Text.Pandoc.Builder`:
-
-    + `Inlines` and `Blocks` are now newtypes (not synonyms for
-      sequences).
-    + Instances are defined for `IsString`, `Show`, `Read`, `Monoid`,
-      and a new `Listable` class, which allows these to be manipulated
-      to some extent like lists. Monoid append includes automatic
-      normalization.
-    + `+++` has been replaced by `<>` (mappend).
-
-  * Use blaze-html instead of xhtml for HTML generation.
-    This changes the type of `writeHtml`.
-
-  * `Text.Pandoc.Shared`:
-
-    + Added `warn` and `err`.
-    + Removed `unescapeURI`, modified `escapeURI`.
-      (See under [behavior changes], above.)
-
-  * Changes in URI escaping:  Previously the readers escaped URIs by
-    converting unicode characters to octets and then percent encoding.
-    Now unicode characters are left as they are, and `escapeURI` only
-    percent-encodes space characters.  This gives more readable
-    URIs, and works well with modern user agents. URIs are no longer unescaped
-    at all on conversion to `markdown`, `asciidoc`, `rst`, `org`.
-
-  * New module `Text.Pandoc.SelfContained`.
-
-  * New module `Text.Pandoc.Docx`.
-
-  * New module `Text.Pandoc.PDF`.
-
-  * Added `writerBeamer` to `WriterOptions`.
-
-  * Added `normalizeDate` to `Text.Pandoc.Shared`.
-
-  * Added `splitStringWithIndices` in `Text.Pandoc.Shared`.
-    This is like `splitWithIndices`, but it is sensitive to distinctions
-    between wide, combining, and regular characters.
-
-  * `Text.Pandoc.Pretty`:
-
-    + Added `chomp` combinator.
-    + Added `beforeNonBreak` combinator.  This allows you to include
-      something conditionally on it being before a nonblank.
-      Used for RST inline math.
-    + Added `charWidth` function. All characters marked W or F in the unicode
-      spec EastAsianWidth.txt get width 2.
-    + Added `realLength`, based on `charWidth`. `realLength` is now
-      used in calculating offsets.
-
-  * New module `Text.Pandoc.Slides`, for common functions for breaking
-    a document into slides.
-
-  * Removed `Text.Pandoc.S5`, which is no longer needed.
-
-  * Removed `Text.Pandoc.CharacterReferences`.  Moved
-    `characterReference` to `Text.Pandoc.Parsing`.
-    `decodeCharacterReferences` is replaced by `fromEntities`
-    in `Text.Pandoc.XML`.
-
-  * Added `Text.Pandoc.ImageSize`.  This is intened for use
-    in `docx` and `odt` writers, so the size and dpi of images
-    can be calculated.
-
-  * Removed `writerAscii` in `WriterOptions`.
-
-  * Added `writerHighlight` to `WriterOptions`.
-
-  * Added `DZSlides` to `HTMLSlideVariant`.
-
-  * `writeEPUB` has a new argument for font files to embed.
-
-  * Added `stateLastStrPos` to `ParserState`. This lets us keep track
-    of whether we're parsing the position immediately after a regular
-    (non-space, non-symbol) string, which is useful for distinguishing
-    apostrophes from single quote starts.
-
-  * `Text.Pandoc.Parsing`:
-
-    + `escaped` now returns a `Char`.
-    + Removed `charsInBalanced'`, added a character parser as
-      a parameter of `charsInBalanced`.  This is needed for
-      proper handling of escapes, etc.
-    + Added `withRaw`.
-
-  * Added `toEntities` to `Text.Pandoc.XML`.
-
-  * `Text.Pandoc.Readers.LaTeX`:
-
-    + Export `handleIncludes`.
-    + Export `rawLaTeXBlock` instead of `rawLaTeXEnvironment'`.
-
-  * Added `ToJsonFilter` class and `toJsonFilter` function to
-    `Text.Pandoc`, deprecating the old `jsonFilter` function.
-
-  * `Text.Pandoc.Highlighting`:
-
-     + Removed `highlightHtml`, `defaultHighlightingCss`.
-     + Export `formatLaTeXInline`, `formatLaTeXBlock`, and `highlight`, plus
-       key functions from highlighting-kate.
-     + Changed types of highlighting function.  `highlight` returns a
-       `Maybe`, not an `Either`.
-
-pandoc (1.8.2.1)
-
-  * Relaxed cabal consntraints for test-framework (S. Trofimovich).
-
-  * Relaxed cabal constraints for pandoc-types.
-
-  * Adjusted Arbitrary instance to help avoid timeouts in tests.
-
-  * Added `Tests.Writers.Markdown` to cabal file.
-
-pandoc (1.8.2)
-
-  * Added script to produce OS X package.
-
-  * Made `templates` directory a git submodule.  This should make it
-    easier for people to revise their custom templates when the default
-    templates change.
-
-  * Changed template naming scheme: `FORMAT.template` -> `default.FORMAT`.
-    **Note:** If you have existing templates in `~/.pandoc/templates`, you
-    must rename them to conform to the new scheme!
-
-  * Fixed smart quotes bug, now handling `'...hi'` properly.
-
-  * RST reader:
-
-    + Partial support for labeled footnotes.
-    + Improved accuracy of `simpleReferenceName` parser.
-
-  * HTML reader:
-
-    + Substitute correct unicode characters for
-      characters in the 128..159 range, which are often found even in
-      HTML that purports to be UTF-8.
-
-  * LaTeX reader:  Handle `\subtitle` command (a subtitle is added
-    to the title, after a colon and linebreak). Closes #280.
-
-  * Leaner `reference.odt`.
-
-  * Added unexported module `Text.Pandoc.MIME` for use in
-    the ODT writer.
-
-  * ODT writer:  Construct `manifest.xml` based on archive contents.
-    This fixes a bug in ODTs containing images. Recent versions of
-    LibreOffice would reject these as corrupt, because `manifest.xml`
-    did not contain a reference to the image files.
-
-  * LaTeX writer:
-
-    + Make verbatim environments flush to avoid spurious
-      blank lines.  Closes #277.
-    + Use `\texttt` and escapes insntead of `\verb!...!`, which
-      is too fragile (doesn't work in command arguments).
-    + Use `\enquote{}` for quotes if the template includes
-      the `csquotes` package. This provides better support for
-      local quoting styles. (Thanks to Andreas Wagner for the idea.)
-
-  * ConTeXt writer:  Make `\starttyping`/`\stoptyping` flush with
-    margin, preventing spurious blank lines.
-
-  * Slidy writer:
-
-    + Use non-minimized version of `slidy.css` with `--offline`
-      option, so users can more easily edit it.
-    + Also fixed a bug in the CSS that prevented proper centering
-      of title (now reported and fixed upstream).
-
-  * S5 writer:
-
-    + Replaced `s5/default/slides.js.{comment,packed}` with
-      new compressed `s5/default/slides.min.js`.
-    + Use `data:` protocol to embed S5 CSS in `<link>` tags,
-      when `--offline` is specified. Using inline CSS didn't
-      work with Chrome or Safari.  This fixes offline
-      S5 on those browsers.
-
-  * HTML writer:  Removed English title on footnote backlinks.
-    This is incongrous in non-English documents.
-
-  * Docbook writer:
-
-    + Use CALS tables.  (Some older docbook software does not work
-      well with XHTML tables.)  Closes #77.
-    + Use `programlisting` tags (instead of `screen`) for code blocks.
-
-  * `markdown2pdf`:
-
-    + Calls latex with `-halt-on-error -interaction nonstopmode` instead
-      of `-interaction=batchmode`, which essentially just ignored errors,
-      leading to bad results. Better to know when something is wrong.
-    + Fixed issues with non-UTF-8 output of `pdflatex`.
-    + Better error reporting.
-
-  * `--mathjax` now takes an optional URL argument. If it is not
-    provided, pandoc links directly to the (secure) mathjax CDN,
-    as now recommended (thanks to dsanson).
-
-  * Deprecated `--xetex` option in `pandoc`.  It is no longer needed,
-    since the LaTeX writer now produces a file that can be processed by
-    `latex`, `pdflatex`, `lualatex`, or `xelatex`.
-
-  * Introduced `--luatex` option to `markdown2pdf`. This causes `lualatex`
-    to be used to create the PDF.
-
-  * If a template specified with `--template` is not found, look for it
-    in `datadir`.  Also, if no extension is provided, supply one based
-    on the writer.  So now you can put your `special.latex` template in
-    `~/.pandoc/templates`, and use it from any directory via
-    `pandoc -t latex --template special`.
-
-  * Default template improvements:
-
-    + HTML:  Display author and date after title.
-    + HTML:  Made table of contents more customizable.  The container
-      for the TOC is now in the template, so users can insert a header
-      or other styling. (Thanks to Bruce D'Arcus for the suggestion.)
-    + HTML, Slidy, S5:  Enclose scripts in CDATA tags.
-    + Slidy, S5: Added `s5-url` and `slidy-url` variables, instead of
-      hard-coding.  If you want to put your slidy files in the slidy
-      subdirectory, for example, you can do
-      `pandoc -t slidy -V slidy-url=slidy -s`.
-    + LaTeX: Use `\and` to separate authors in LaTeX documents (reader
-      & writer).  Closes #279.
-    + LaTeX: Use different `hyperref` options for `xetex`, fixing
-      problems with unicode bookmarks (thanks to CircleCode).
-    + LaTeX: Removed `ucs` package, use `utf8` rather than `utf8x`
-      with `inputenc`.  This covers fewer characters but is more
-      robust with other packages, and `ucs` is unmaintained.  Users
-      who need better unicode support should use xelatex or lualatex.
-
-pandoc (1.8.1.2)
-
-  * Added `--epub-cover-image` option.
-
-  * Documented `--biblatex` and `--natbib` options.
-
-  * Allow `--section-divs` with slidy output.  Resolves Issue #296.
-
-  * Disallow notes within notes in reST and markdown.
-    These previously caused infinite looping and stack overflows.
-    For example:
-
-        [^1]
-
-        [^1]: See [^1]
-
-    Note references are allowed in reST notes, so this isn't a full
-    implementation of reST. That can come later. For now we need to
-    prevent the stack overflows.  Partially resolves Issue #297.
-
-  * EPUB writer: Allow non-plain math methods.
-
-  * Forbid ()s in citation item keys.  Resolves Issue #304: problems with
-    `(@item1; @item2)` because the final paren was being parsed as part of
-    the item key.
-
-  * Changed URI parser so it doesn't include trailing punctuation.
-    So, in RST, `http://google.com.` should be parsed as a link followed by a
-    period. The parser is smart enough to recognize balanced parentheses, as
-    often occur in wikipedia links: `http://foo.bar/baz_(bam)`.
-
-  * Markdown+lhs reader: Require space after inverse bird tracks, so that
-    HTML tags can be used freely at the left margin of a markdown+lhs document.
-    Thanks to Conal Elliot for the suggestion.
-
-  * Markdown reader:
-
-    + Improved emph/strong parsing; fixes bug found by Perry Wagle.
-    + Fixed bug in footnote order (reported by CircleCode).
-
-  * RST reader:
-      + Fixed bug in in field lists with multi-line items at the
-        end of the list.
-      + Added parentheses to RST `specialChars`, so
-        `(http://google.com)` will be parsed as a link in parens.
-        Resolves Issue #291.
-      + Allow `|` followed by newline in RST line block.
-
-  * LaTeX reader:
-      + Support `\dots`.
-      + Gobble option & space after linebreak `\\[10pt]`.
-
-  * Textile reader:
-      + Make it possible to have colons after links.  (qerub)
-      + Make it possible to have colons after links.  (Christoffer Sawicki)
-
-  * HTML reader:
-      + Skip spaces after `<b>`, `<emph>`, etc.
-      + Handle tbody, thead in simple tables.  Closes #274.
-      + Implicit `Para`s instead of `Plains` in some contexts.
-
-  * OpenDocument writer:  Use special `First paragraph` style for
-    first paragraph after most non-paragraph blocks. This allows users to
-    specify e.g. that only paragraphs after the first paragraph of a block are
-    to be indented. Thanks to Andrea Rossato for the patch. Closes #20.
-
-  * LaTeX writer:  use `deVerb` on table and picture captions.
-    Otherwise LaTeX complains about `\verb` inside command argument.
-    Thanks to bbanier for reporting the bug.
-
-  * Markdown writer: Insert HTML comment btw list and indented code block.
-    This prevents the code block from being interpreted as part of the list.
-
-  * EPUB writer: Add a meta element specify the cover.
-    Some EPUB e-readers, such as the Nook, require a meta element inside the
-    OPF metadata block to ensure the cover image is properly displayed.
-    (Kelsey Hightower)
-
-  * HTML writer: Use embed tag for images with non-image extensions.
-    (e.g.  PDFs).  Closes #264.
-
-  * LaTeX writer: Improved tables.
-
-      + More space between lines, top-align cells.
-      + Use ctable package, which allows footnotes and
-        provides additional options.
-      + Made cell alignments work in multiline tables.
-      + Closes #271, #272.
-
-  * Un-URI-escape image filenames in LaTeX, ConTeXt, RTF, Texinfo.
-    Also do this when copying image files into EPUBs and ODTs.
-    Closes #263.
-
-  * Changed to github issue tracker.
-
-  * Added failing emph/strong markdown test case due to Perry Wagle.
-
-  * Slidy improvements:
-      + Updated to use Slidy2.
-      + Fixed bug, unclosed div tag.
-      + Added `duration` variable in template.
-        Setting this activates the timer.
-      + Use 'titlepage' instead of 'cover' for title div.
-
-pandoc (1.8.1.1)
-
-  * `markdown2pdf`:  Removed some debugging lines accidentally included
-    in the 1.8.1 release. With those lines, the temp directory is created
-    in the working directory, and it is not deleted.  This fix restores
-    the original behavior.
-
-pandoc (1.8.1)
-
-  * Added `--ascii` option.  Currently supported only in HTML writer,
-    which it causes to use numerical entities instead of UTF-8.
-
-  * EPUB writer: `--toc` now works to provide a table of contents
-    at the beginning of each chapter.
-
-  * LaTeX writer:  Change figure defaults to `htbp`.
-    This prevents "too many unprocessed floats."  Resolves
-    Issue #285.
-
-  * `Text.Pandoc.UTF8`:  Encode filenames even when using recent
-    base.
-
-  * `markdown2pdf`: Fixed filename encoding issues. With help from Paulo
-    Tanimoto. Resolves Issue #286.
-
-  * HTML writer: Put line breaks in section divs.
-
-  * `Text.Pandoc.Shared`: Make `writerSectionDivs` default to False.
-
-pandoc (1.8.0.3)
-
-  * Fixed Source-repository stanza in cabal file.
-
-pandoc (1.8.0.2)
-
-  * HTML writer:
-
-    + Stringify alt text instead of converting to HTML.
-    + Break lines after block elements, not inside tags.
-      HTML output now closely resembles that of tidy. Resolves Issue #134.
-
-  * Markdown reader: Fixed bug in footnote block parser (pointed out
-    by Jesse Rosenthal).  The problem arose when the blank line
-    at the end of a footnote block contained indenting spaces.
-
-  * Shared: Improved 'normalize' function so it normalizes Spaces too.
-    In normal form, Space elements only occur to separate two non-Space
-    elements.  So, we never have [Space], or [, ..., Space].
-
-  * Tests:
-
-    + Improved Arbitrary instance.
-    + Added timeout for test instances.
-
-  * README:
-
-    + Added section on four-space rule for lists.  Resolves Issue #283.
-    + Clarified optional arguments on math options.
-
-  * markdown2pdf: Fixed bug with output file extensions.
-    Previously `markdown2pdf test.txt -o test.en.pdf` would produce
-    `test.pdf`, not `test.en.pdf`.  Thanks to Paolo Tanimoto for the fix.
-
-pandoc (1.8.0.1)
-
-  * Revised Interact.hs so that it works with the CPP macros
-    in the UTF8 module.
-
-  * Revised Setup.hs so that we don't call MakeManPage.hs unless
-    the man pages are out of date.
-
-pandoc (1.8)
-
-  [new features]
-
-  * Support for citations using Andrea Rossato's `citeproc-hs` 0.3.
-    You can now write, for example,
-
-        Water is wet [see @doe99, pp. 33-35; also @smith04, ch. 1].
-
-    and, when you process your document using `pandoc`, specifying
-    a citation style using `--csl` and a bibliography using `--bibliography`,
-    the citation will be replaced by an appropriately formatted
-    citation, and a list of works cited will be added to the end
-    of the document.
-
-    This means that you can switch effortlessly between different citation
-    and bibliography styles, including footnote, numerical, and author-date
-    formats. The bibliography can be in any of the following formats: MODS,
-    BibTeX, BibLaTeX, RIS, EndNote, EndNote XML, ISI, MEDLINE, Copac, or JSON.
-    See the README for further details.
-
-    Citations are supported in the markdown reader, using a special
-    syntax, and in the LaTeX reader, using natbib or biblatex syntax.
-    (Thanks to Nathan Gass for the natbib and biblatex support.)
-
-  * New `textile` reader and writer.  Thanks to Paul Rivier for contributing
-    the `textile` reader, an almost complete implementation of the textile
-    syntax used by the ruby [RedCloth library](http://redcloth.org/textile).
-    Resolves Issue #51.
-
-  * New `org` writer, for Emacs Org-mode, contributed by Puneeth Chaganti.
-
-  * New `json` reader and writer, for reading and writing a JSON
-    representation of the native Pandoc AST.  These are much faster
-    than the `native` reader and writer, and should be used for
-    serializing Pandoc to text.  To convert between the JSON representation
-    and native Pandoc, use `encodeJSON` and `decodeJSON` from
-    `Text.JSON.Generic`.
-
-  * A new `jsonFilter` function in `Text.Pandoc` makes it easy
-    to write scripts that transform a JSON-encoded pandoc document.
-    For example:
-
-        -- removelinks.hs - removes links from document
-        import Text.Pandoc
-        main = interact $ jsonFilter $ bottomUp removeLink
-                 where removeLink (Link xs _) = Emph xs
-                       removeLink x = x
-
-    To use this to remove links while translating markdown to LaTeX:
-
-        pandoc -t json | runghc removelinks.hs | pandoc -f json -t latex
-
-  * Attributes are now allowed in inline `Code` elements, for example:
-
-        In this code, `ulist ! [theclass "special"] << elts`{.haskell} is...
-
-    The attribute syntax is the same as for delimited code blocks.
-    `Code` inline has an extra argument place for attributes, just like
-    `CodeBlock`. Inline code will be highlighted in HTML output, if pandoc
-    is compiled with highlighting support. Resolves Issue #119.
-
-  * New `RawBlock` and `RawInline` elements (replacing `RawHtml`,
-    `HtmlInline`, and `TeX`) provide lots of flexibility in writing
-    scripts to transform Pandoc documents. Scripts can now change
-    how each element is rendered in each output format.
-
-  * You can now define LaTeX macros in markdown documents, and pandoc
-    will apply them to TeX math.  For example,
-
-        \newcommand{\plus}[2]{#1 + #2}
-        $\plus{3}{4}$
-
-    yields `3+4`.  Since the macros are applied in the reader, they
-    will work in every output format, not just LaTeX.
-
-  * LaTeX macros can also be used in LaTeX documents (both in math
-    and in non-math contexts).
-
-  * A new `--mathjax` option has been added for displaying
-    math in HTML using MathJax.  Resolves issue #259.
-
-  * Footnotes are now supported in the RST reader. (Note, however,
-    that unlike docutils, pandoc ignores the numeral or symbol used in
-    the note; footnotes are put in an auto-numbered ordered list.)
-    Resolves Issue #258.
-
-  * A new `--normalize` option causes pandoc to normalize the AST
-    before writing the document.  This means that, for example,
-    `*hi**there*` will be rendered as `<em>hithere</em>`
-    instead of `<em>hi</em><em>there</em>`.  This is not the default,
-    because there is a significant performance penalty.
-
-  * A new `--chapters` command-line option causes headers
-    in DocBook, LaTeX, and ConTeXt to start with "chapter" (level one).
-    Resolves Issue #265.
-
-  * In DocBook output, `<chapter>` is now used for top-level
-    headers if the template contains `<book>`. Resolves Issue #265.
-
-  * A new `--listings` option in `pandoc` and `markdown2pdf` causes
-    the LaTeX writer to use the listings package for code blocks.
-    (Thanks to Josef Svennigsson for the pandoc patch, and Etienne
-    Millon for the markdown2pdf patch.)
-
-  * `markdown2pdf` now supports `--data-dir`.
-
-  * URLs in autolinks now have class "url" so they can be styled.
-
-  * Improved prettyprinting in most formats.  Lines will be wrapped
-    more evenly and duplicate blank lines avoided.
-
-  * New `--columns` command-line option sets the column width for
-    line wrapping and relative width calculations for tables.
-
-  * Made `--smart` work in HTML, RST, and Textile readers, as well
-    as markdown.
-
-  * Added `--html5` option for HTML5 output.
-
-  * Added support for listings package in LaTeX reader
-    (Puneeth Chaganti).
-
-  * Added support for simple tables in the LaTeX reader.
-
-  * Added support for simple tables in the HTML reader.
-
-  * Significant performance improvements in many readers and writers.
-
-  [API and program changes]
-
-  * Moved `Text.Pandoc.Definition` from the `pandoc` package to a new
-    auxiliary package, `pandoc-types`. This will make it possible for other
-    programs to supply output in Pandoc format, without depending on the whole
-    pandoc package.
-
-  * Added `Attr` field to `Code`.
-
-  * Removed `RawHtml`, `HtmlInline`, and `TeX` elements; added generic
-    `RawBlock` and `RawInline`.
-
-  * Moved generic functions to `Text.Pandoc.Generic`. Deprecated
-    `processWith`, replacing it with two functions, `bottomUp` and `topDown`.
-    Removed previously deprecated functions `processPandoc` and `queryPandoc`.
-
-  * Added `Text.Pandoc.Builder`, for building `Pandoc` structures.
-
-  * `Text.Pandoc` now exports association lists `readers` and `writers`.
-
-  * Added `Text.Pandoc.Readers.Native`, which exports `readNative`.
-    `readNative` can now read full pandoc documents, block lists, blocks,
-    inline lists, or inlines.  It will interpret `Str "hi"`
-    as if it were `Pandoc (Meta [] [] []) [Plain [Str "hi"]]`.
-    This should make testing easier.
-
-  * Removed deprecated `-C/--custom-header` option.
-    Use `--template` instead.
-
-  * `--biblio-file` has been replaced by `--bibliography`.
-    `--biblio-format` has been removed; pandoc now guesses the format
-    from the file extension (see README).
-
-  * pandoc will treat an argument as a URI only if it has an
-    `http(s)` scheme.  Previously pandoc would treat some
-    Windows pathnames beginning with `C:/` as URIs.
-
-  * The `--sanitize-html` option and the `stateSanitize` field in
-    `ParserState` have been removed. Sanitization is better done in the
-    resulting HTML using `xss-sanitize`, which is based on pandoc's
-    sanitization, but improved.
-
-  * pandoc now adds a newline to the end of its output in fragment
-    mode (= not `--standalone`).
-
-  * Added support for `lang` in `html` tag in the HTML template,
-    so you can do `pandoc -s -V lang=es`, for example.
-
-  * `highlightHtml` in `Text.Pandoc.Highlighting` now takes
-    a boolean argument that selects between "inline" and
-    "block" HTML.
-
-  * `Text.Pandoc.Writers.RTF` now exports `rtfEmbedImage`.
-    Images are embedded in RTF output when possible (png, jpeg).
-    Resolves Issue #275.
-
-  * Added `Text.Pandoc.Pretty`. This is better suited for pandoc than the
-    `pretty` package.  Changed all writers that used
-    `Text.PrettyPrint.HughesPJ` to use `Text.Pandoc.Pretty` instead.
-
-  * Rewrote `writeNative` using the new prettyprinting module. It is
-    now much faster. The output has been made more consistent and compressed.
-    `writeNative` is also now sensitive to writerStandalone`, and will simply
-    `print a block list if writerStandalone` is False.
-
-  * Removed `Text.Pandoc.Blocks`. `Text.Pandoc.Pretty` allows you to define
-    blocks and concatenate them, so a separate module is no longer needed.
-
-  * `Text.Pandoc.Shared`:
-
-    + Added `writerColumns`, `writerChapters`, and `writerHtml5` to
-      `WriterOptions`.
-    + Added `normalize`.
-    + Removed unneeded prettyprinting functions:
-      `wrapped`, `wrapIfNeeded`, `wrappedTeX`, `wrapTeXIfNeeded`, `hang'`,
-      `BlockWrapper`, `wrappedBlocksToDoc`.
-    + Made `splitBy` take a test instead of an element.
-    + Added `findDataFile`, refactored `readDataFile`.
-    + Added `stringify`. Rewrote `inlineListToIdentifier` using `stringify`.
-    + Fixed `inlineListToIdentifier` to treat '\160' as ' '.
-
-  * `Text.Pandoc.Readers.HTML`:
-
-    + Removed `rawHtmlBlock`, `anyHtmlBlockTag`, `anyHtmlInlineTag`,
-      `anyHtmlTag`, `anyHtmlEndTag`, `htmlEndTag`, `extractTagType`,
-      `htmlBlockElement`, `htmlComment`
-    + Added `htmlTag`, `htmlInBalanced`, `isInlineTag`, `isBlockTag`,
-      `isTextTag`
-
-  * Moved `smartPunctuation` from `Text.Pandoc.Readers.Markdown`
-    to `Text.Pandoc.Readers.Parsing`, and parameterized it with
-    an inline parser.
-
-  * Added `nonspaceChar` to `Text.Pandoc.Parsing`.
-
-  * Ellipses are no longer allowed to contain spaces.
-    Previously we allowed '. . .', ' . . . ', etc.  This caused
-    too many complications, and removed author's flexibility in
-    combining ellipses with spaces and periods.
-
-  * Allow linebreaks in URLs (treat as spaces). Also, a string of
-    consecutive spaces or tabs is now parsed as a single space. If you have
-    multiple spaces in your URL, use `%20%20`.
-
-  * `Text.Pandoc.Parsing`:
-
-    + Removed `refsMatch`.
-    + Hid `Key` constructor.
-    + Removed custom `Ord` and `Eq` instances for `Key`.
-    + Added `toKey` and `fromKey` to convert between `Key` and `[Inline]`.
-    + Generalized type on `readWith`.
-
-  * Small change in calculation of relative widths of table columns.
-    If the size of the header > the specified column width, use
-    the header size as 100% for purposes of calculating
-    relative widths of columns.
-
-  * Markdown writer now uses some pandoc-specific features when `--strict`
-    is not specified: `\` newline is used for a hard linebreak instead of
-    two spaces then a newline. And delimited code blocks are used when
-    there are attributes.
-
-  * HTML writer:  improved gladTeX output by setting ENV appropriately
-    for display or inline math (Jonathan Daugherty).
-
-  * LaTeX writer: Use `\paragraph`, `\subparagraph` for level 4,5 headers.
-
-  * LaTeX reader:
-
-    + `\label{foo}` and `\ref{foo}` now become `{foo}` instead of `(foo)`.
-    + `\index{}` commands are skipped.
-
-  * Added `fontsize` variable to default LaTeX template.
-    This makes it easy to set the font size using `markdown2pdf`:
-    `markdown2pdf -V fontsize=12pt input.txt`.
-
-  * Fixed problem with strikeout in LaTeX headers when using
-    hyperref, by adding a command to the default LaTeX template
-    that disables `\sout` inside pdf strings. Thanks to Joost Kremers
-    for the fix.
-
-  * The `COLUMNS` environment variable no longer has any effect.
-
-  [under-the-hood improvements]
-
-  * Pandoc now compiles with GHC 7. (This alone leads to a
-    significant performance improvement, 15-20%.)
-
-  * Completely rewrote HTML reader using tagsoup as a lexer. The
-    new reader is faster and more accurate.  Unlike the
-    old reader, it does not get bogged down on some input
-    (Issues #277, 255). And it handles namespaces in tags
-    (Issue #274).
-
-  * Replaced `escapeStringAsXML` with a faster version.
-
-  * Rewrote `spaceChar` and some other parsers in Text.Pandoc.Parsing
-    for a significant performance boost.
-
-  * Improved performance of all readers by rewriting parsers.
-
-  * Simplified Text.Pandoc.CharacterReferences by using
-    entity lookup functions from TagSoup.
-
-  * `Text.Pandoc.UTF8` now uses the unicode-aware IO functions
-    from `System.IO` if base >= 4.2.  This gives support for
-    windows line endings on windows.
-
-  * Remove duplications in documentation by generating the
-    pandoc man page from README, using `MakeManPage.hs`.
-
-  * README now includes a full description of markdown syntax,
-    including non-pandoc-specific parts.  A new `pandoc_markdown`
-    man page is extracted from this, so you can look up markdown
-    syntax by doing `man pandoc_markdown`.
-
-  * Completely revised test framework (with help from Nathan Gass).
-    The new test framework is built when the `tests` Cabal flag is set. It
-    includes the old integration tests, but also some new unit and quickcheck
-    tests. Test output has been much improved, and you can now specify a glob
-    pattern after `cabal test` to indicate which tests should be run;
-    for example `cabal test citations` will run all the citation tests.
-
-  * Added a shell script, `stripansi.sh`, for filtering ANSI control
-    sequences from test output: `cabal test | ./stripansi.sh > test.log`.
-
-  * Added `Interact.hs` to make it easier to use ghci while developing.
-    `Interact.hs` loads `ghci` from the `src` directory, specifying
-    all the options needed to load pandoc modules (including
-    specific package dependencies, which it gets by parsing
-    dist/setup-config).
-
-  * Added `Benchmark.hs`, testing all readers + writers using criterion.
-
-  * Added `stats.sh`, to make it easier to collect and archive
-    benchmark and lines-of-code stats.
-
-  * Added upper bounds to all cabal dependencies.
-
-  * Include man pages in extra-source-files.  This allows users to
-    install pandoc from the tarball without needing to build the man
-    pages.
-
-  [bug fixes]
-
-  * Filenames are encoded as UTF8.  Resolves Issue #252.
-
-  * Handle curly quotes better in `--smart` mode. Previously, curly quotes
-    were just parsed literally, leading to problems in some output formats.
-    Now they are parsed as `Quoted` inlines, if `--smart` is specified.
-    Resolves Issue #270.
-
-  * Text.Pandoc.Parsing: Fixed bug in grid table parser.
-    Spaces at end of line were not being stripped properly,
-    resulting in unintended LineBreaks.
-
-  * Markdown reader:
-
-    + Allow HTML comments as inline elements in markdown.
-      So, `aaa <!-- comment --> bbb` can be a single paragraph.
-    + Fixed superscripts with links: `^[link](/foo)^` gets
-      recognized as a superscripted link, not an inline note followed by
-      garbage.
-    + Fixed regression, making markdown reference keys case-insensitive again.
-      Resolves Issue #272.
-    + Properly handle abbreviations (like `Mr.`) at the end of a line.
-    + Better handling of intraword underscores, avoiding exponential
-      slowdowns in some cases.  Resolves Issue #182.
-    + Fixed bug in alignments in tables with blank rows in the header.
-
-  * RST reader:
-
-    + Field lists now allow spaces in field names, and
-      block content in field values. (Thanks to Lachlan Musicman
-      for pointing out the bug.)
-    + Definition list items are now always `Para` instead of
-      `Plain`, matching behavior of `rst2xml.py`.
-    + In image blocks, the description is parsed properly and
-      used for the alt attribute, not also the title.
-    + Skip blank lines at beginning of file. Resolves
-      Debian #611328.
-
-  * LaTeX reader:
-
-    + Improved parsing of preamble.
-      Previously you'd get unexpected behavior on a document that
-      contained `\begin{document}` in, say, a verbatim block.
-    + Allow spaces between `\begin` or `\end` and `{`.
-    + Support `\L` and `\l`.
-    + Skip comments inside paragraphs.
-
-  * LaTeX writer:
-
-    + Escape strings in `\href{..}`.
-    + In nonsimple tables, put cells in `\parbox`.
-
-  * OpenDocument writer:  don't print raw TeX.
-
-  * Markdown writer:
-
-    + Fixed bug in `Image`.  URI was getting unescaped twice!
-    + Avoid printing extra blank lines at the end if there are
-      no notes or references.
-
-  * LaTeX and ConTeXt: Escape `[` and `]` as `{[}` and `{]}`.
-    This avoids unwanted interpretation as an optional argument.
-
-  * ConTeXt writer: Fixed problem with inline code.  Previously
-    `}` would be rendered `\type{}}`. Now we check the string for '}' and '{'.
-    If it contains neither, use `\type{}`; otherwise use `\mono{}`
-    with an escaped version of the string.
-
-  * `:` now allowed in HTML tags. Resolves Issue #274.
-
-pandoc (1.6)
-
-  [ John MacFarlane ]
-
-  * New EPUB and HTML Slidy writers. (Issue #122)
-
-      - EPUB is a standard ebook format, used in Apple's iBooks for
-        the iPad and iPhone, Barnes and Noble's nook reader, the Sony
-        reader, and many other devices.
-      - Slidy, like S5, is a system for producing HTML+javascript slide
-        shows.
-
-  * All input is assumed to be UTF-8, no matter what the locale and ghc
-    version, and all output is UTF-8. This reverts to pre-1.5 behavior.
-    Also, a BOM, if present, is stripped from the input.
-
-  * Markdown now supports grid tables, whose cells can contain
-    arbitrary block elements. (Issue #43)
-
-  * Sequentially numbered example lists in markdown with `@` marker.
-
-  * Markdown table captions can begin with a bare colon and no longer need
-    to include the English word "table." Also, a caption can now occur
-    either before or after the table. (Issue #227)
-
-  * New command-line options:
-
-      - `--epub-stylesheet` allows you to specify a CSS file that will
-        be used to style your ebook.
-      - `--epub-metadata` allows you to specify metadata for the ebook.
-      - `--offline` causes the generated HTML slideshow to include all
-        needed scripts and stylesheets.
-      - `--webtex` causes TeX math to be converted to images using the
-        Google Charts API (unless a different URL is specified).
-      - `--section-divs` causes div tags to be added around each section
-        in an HTML document. (Issue #230, 239)
-
-  * Default behavior of S5 writer in standalone mode has changed:
-    previously, it would include all needed scripts and stylesheets
-    in the generated HTML; now, only links are included unless
-    the `--offline` option is used.
-
-  * Default behavior of HTML writer has changed. Between 1.2 and 1.5,
-    pandoc would enclose sections in div tags with identifiers on the
-    div tags, so that the sections can be manipulated in javascript.
-    This caused undesirable interactions with raw HTML div tags. So,
-    starting with 1.6, the default is to put the identifiers directly
-    on the header tags, and not to include the divs.  The `--section-divs`
-    option selects the 1.2-1.5 behavior.
-
-  * API changes:
-
-      - `HTMLMathMethod`: Added `WebTeX`, removed `MimeTeX`.
-      - `WriterOptions`: Added `writerUserDataDir`, `writerSourceDirectory`,
-        `writerEPUBMetadata` fields. Removed `writerIncludeBefore`,
-        `writerIncludeAfter`.
-      - Added `headerShift` to `Text.Pandoc.Shared`.
-      - Moved parsing code and `ParserState` from `Text.Pandoc.Shared`
-        to a new module, `Text.Pandoc.Parsing`.
-      - Added `stateHasChapters` to `ParserState`.
-      - Added `HTMLSlideVariant`.
-      - Made `KeyTable` a map instead of an association list.
-      - Added accessors for `Meta` fields (`docTitle`, `docAuthors`,
-        `docDate`).
-      - `Pandoc`, `Meta`, `Inline`, and `Block` have been given `Ord`
-        instances.
-      - Reference keys now have a type of their own (`Key`), with its
-        own `Ord` instance for case-insensitive comparison.
-      - Added `Text.Pandoc.Writers.EPUB`.
-      - Added `Text.Pandoc.UUID`.
-      - Removed `Text.Pandoc.ODT`, added `Text.Pandoc.Writers.ODT`.
-        Removed `saveOpenDocumentAsODT`, added `writeODT`.
-      - Added `Text.Pandoc.Writers.Native` and `writeNative`.
-        Removed `prettyPandoc`.
-      - Added `Text.Pandoc.UTF8` for portable UTF8 string IO.
-      - Removed `Text.Pandoc.Writers.S5` and the `writeS5` function.
-        Moved `s5Includes` to a new module, `Text.Pandoc.S5`.
-        To write S5, you now use `writeHtml` with `writerSlideVariant`
-        set to `S5Slides` or `SlidySlides`.
-
-  * Template changes.  If you use custom templates, please update them,
-    particularly if you use syntax highlighting with pandoc. The old HTML
-    templates hardcoded highlighting CSS that will no longer work with
-    the most recent version of highlighting-kate.
-
-      - HTML template: avoid empty meta tag if no date.
-      - HTML template: Use default highlighting CSS from highlighting-kate
-        instead of hard-coding the CSS into the template.
-      - HTML template: insert-before text goes before the title, and
-        immediately after the <body> tag, as documented. (Issue #241)
-      - Added slidy and s5 templates.
-      - Added amssymb to preamble of latex template. (github Issue 1)
-
-  * Removed excess newlines at the end of output. Note: because output
-    will not contain an extra newline, you may need to make adjustments
-    if you are inserting pandoc's output into a template.
-
-  * In S5 and slidy, horizontal rules now cause a new slide, so you
-    are no longer limited to one slide per section.
-
-  * Improved handling of code in man writer. Inline code is now monospace,
-    not bold, and code blocks now use .nf (no fill) and .IP (indented para).
-
-  * HTML reader parses `<tt>` as Code. (Issue #247)
-
-  * html+lhs output now contains bird tracks, even when compiled without
-    highlighting support. (Issue #242)
-
-  * Colons are now no longer allowed in autogenerated XML/HTML identifiers,
-    since they have a special meaning in XML.
-
-  * Code improvements in ODT writer.  Remote images are now replaced with
-    their alt text rather than a broken link.
-
-  * LaTeX reader improvements:
-
-      - Made latex `\section`, `\chapter` parsers more forgiving of
-        whitespace.
-      - Parse `\chapter{}` in latex.
-      - Changed `rawLaTeXInline` to accept `\section`, `\begin`, etc.
-      - Use new `rawLaTeXInline'` in LaTeX reader, and export `rawLaTeXInline`
-        for use in markdown reader.
-      - Fixes bug wherein `\section{foo}` was not recognized as raw TeX
-        in markdown document.
-
-  * LaTeX writer:  images are automatically shrunk if they would extend
-    beyond the page margin.
-
-  * Plain, markdown, RST writers now use unicode for smart punctuation.
-
-  * Man writer converts math to unicode when possible, as in other writers.
-
-  * `markdown2pdf` can now recognize citeproc options.
-
-  * Command-line arguments are converted to UTF-8. (Issue #234)
-
-  * `Text.Pandoc.TeXMath` has been rewritten to use texmath's parser.
-    This allows it to handle a wider range of formulas. Also, if a formula
-    cannot be converted, it is left in raw TeX; formulas are no longer
-    partially converted.
-
-  * Unicode curly quotes are left alone when parsing smart quotes. (Issue
-    #143)
-
-  * Cabal file changes:
-
-      - Removed parsec < 3 restriction.
-      - Added 'threaded' flag for architectures where GHC lacks a threaded
-        runtime.
-      - Use 'threaded' only for markdown2pdf; it is not needed for pandoc.
-      - Require highlighting-kate 0.2.7.
-
-  * Use explicit imports from `Data.Generics`. Otherwise we have a
-    conflict with the 'empty' symbol, introduced in syb >= 0.2. (Issue #237)
-
-  * New data files:  slidy/slidy.min.js, slidy/slidy.min.css, epub.css.
-
-pandoc (1.5.1.1)
-
-  [ John MacFarlane ]
-
-  * Fixed uniqueIdent in Shared so that header identifiers work as
-   advertized in the README and are are valid XHTML names.
-
-pandoc (1.5.1)
-
-  [ John MacFarlane ]
-
-  * Fixed treatment of unicode characters in URIs.
-    + Shared now exports escapeURI and unescapeURI. These handle
-      UTF8 encoding and decoding as well as URI escaping/unescaping.
-    + Shared: uri and emailAddress now return a pair of the original
-      parsed text and the escaped URI (in the latter case, with
-      the mailto: prefix).
-    + HTML reader: unsanitaryURI has been modified to allow unicode
-      high characters in a URI.
-    + Readers:  All link and image URIs are now escaped using
-      escapeURI.
-    + Markdown and RST writers:  unescapeURI is used so that URIs
-      in these formats are human-readable.
-
-  * Setup.hs: Don't assume that the build directory is "dist".
-    Instead, get it from localBuildInfo.
-
-  * OpenDocument writer: Use a Map for stTextStyleAttr.
-    This avoids duplicates (and invalid xml). Resolves Issue #222.
-
-pandoc (1.5.0.1)
-
-  [ John MacFarlane ]
-
-  * HTML writer: Fixed error in math writer (with MathML option)
-    that caused an infinite loop for unparsable MathML.
-
-pandoc (1.5)
-
-  [ John MacFarlane ]
-
-  * Added --mathml option.  When this is selected, pandoc will convert
-    TeX math into MathML.
-    + Added data/MathMLinHTML.js, which is included when no URL is
-      provided for --mathml.  This allows MathML to be displayed (in
-      better browsers) as text/html.
-    + Removed Text.Pandoc.LaTeXMathML.  The module was no longer
-      necessary; it was replaced by two lines in pandoc.hs.
-    + Replaced LaTeXMathML.js.commend and LaTeXMathML.js.packed with a
-      single combined file, LaTeXMathML.js.
-
-  * Added --data-dir option.
-    This specifies a user data directory. If not specified, will default
-    to ~/.pandoc on unix or Application Data\pandoc on Windows.
-    Files placed in the user data directory will override system default
-    data files.
-
-  * Added Maybe datadir parameter to readDataFile, saveOpenDocumentAsODT,
-    latexMathMLScript, s5HeaderIncludes, and getDefaultTemplate. If
-	  Nothing, no user directory is searched for an override.
-
-  * Added 'plain' output format. This is similar to markdown, but
-    removes links, pictures, inline formatting, and most anything that
-    looks even vaguely markupish. The function writePlain is exported by
-    Text.Pandoc.Writers.Markdown, with which it shares most of its code.
-
-  * Allow multi-line titles and authors in meta block.
-    Titles may span multiple lines, provided continuation lines
-    begin with a space character.  Separate authors may be put on
-    multiple lines, provided each line after the first begins with
-    a space character.  Each author must fit on one line. Multiple
-    authors on a single line may still be separated by a semicolon.
-    Based on a patch by Justin Bogner.
-
-  * When given an absolute URI as parameter, pandoc will try to fetch
-    the content via HTTP.  So you can do:
-    'pandoc -r html -w markdown http://www.fsf.org'
-    Adds dependency on HTTP.
-
-  * Made HTML reader much more forgiving.
-    + Incorporated idea (from HXT) that an element can be closed
-      by an open tag for another element.
-    + Javascript is partially parsed to make sure that a <script>
-      section is not closed by a </script> in a comment or string.
-    + More lenient non-quoted attribute values.
-      Now we accept anything but a space character, quote, or <>.
-      This helps in parsing e.g. www.google.com!
-    + Bare & signs are now parsed as a string.  This is a common
-      HTML mistake.
-    + Skip a bare < in malformed HTML.
-
-  * Removed html2markdown and hsmarkdown.
-    + html2markdown is no longer needed, since you can now pass URI
-      arguments to pandoc and directly convert web pages. (Note,
-      however, that pandoc assumes the pages are UTF8. html2markdown
-      made an attempt to guess the encoding and convert them.)
-    + hsmarkdown is pointless -- a large executable that could be
-      replaced by 'pandoc --strict'.
-
-  * In most writers, an image in a paragraph by itself is now rendered
-    as a figure, with the alt text as the caption. (Texinfo, HTML, RST,
-    MediaWiki, Docbook, LaTeX, ConTeXt, HTML.) Other images are
-    rendered inline.
-
-  * Depend on extensible-exceptions.  This allows pandoc to be compiled
-    on GHC 6.8.
-
-  * Added --base-header-level option.  For example, --base-header-level=2
-    will change level 1 headers to level 2, level 2 to level 3, etc.
-    Closes Debian #563416.
-
-  * Incomplete support for RST tables (simple and grid).
-    Thanks to Eric Kow. Colspans and rowspans not yet supported.
-
-  * Added accessors (docTitle, docAuthors, docDate) to Meta type.
-
-  * MediaWiki writer:  format links with relative URLs as wikilinks.
-    The new rule:  If the link target is an absolute URL, an external
-    link is created. Otherwise, a wikilink is created.
-
-  * Text.Pandoc.Shared: Export uniqueIdent, and don't allow tilde in
-    identifier.  Note:  This may break links to sections that involve
-    tildes.
-
-  * Markdown(+lhs) reader:  handle "inverse bird tracks."
-    Inverse bird tracks (<) are used for haskell example code that is not
-    part of the literate Haskell program.  Resolves Issue #211.
-
-  * LaTeX reader:
-    + Recognize '\ ' (interword space).
-    + Recognize nonbreaking space '~'.
-    + Ignore \section, \pdfannot, \pdfstringdef.  Ignore alt title in
-      section headers.  Don't treat \section as inline LaTeX.
-      Resolves Issue #202.
-    + LaTeX reader:  allow any special character to be escaped.
-      Resolves Issue #221.
-    + LaTeX reader: treat \paragraph and \subparagraph as level 4, 5
-      headers.  Resolves Issue #207.
-
-  * Use template variables for include-before/after.
-    + These options now imply -s; previously they worked also in fragment
-      mode.
-    + Users can now adjust position of include-before and include-after
-      text in the templates.
-    + Default position of include-before moved back (as it was before 1.4)
-      before table of contents.
-    + Resolves Issue #217.
-
-  * Don't print an empty table header: (all writers).
-    Resolves Issue #210.
-
-  * HTML, Docbook writer: Use tbody, thead, and cols in tables.
-
-  * HTML writer: Don't include TOC div if table of contents is empty.
-
-  * Markdown writer:  Fixed citations.
-    Previously the markdown writer printed raw citation codes, e.g.
-    [geach1970], rather than the expanded citations provided by
-    citeproc, e.g. (Geach 1970). Now it prints the expanded citations.
-    This means that the document produced can be processed as a markdown
-    document without citeproc. Thanks to dsanson for reporting, and
-    Andrea Rossato for the patch.
-
-  * Improved and simplified title block in context template.
-    Previously it caused an error if there was no title.
-    This method should also be easier for users to customize.
-
-  * Markdown reader:
-    + Treat p., pp., sec., ch., as abbreviations in smart mode.
-    + Disallow blank lines in inline code span.
-    + Allow footnotes to be indented < 4 spaces.
-      This fixes a regression.  A test case has been added.
-    + Escape spaces in URLs as %20. Previously they were incorrectly
-		  escaped as +, which is appropriate only for the query part of
-			a URL. Resolves Issue #220.
-    + Require two spaces after capital letter + period for list item.
-      Otherwise "E. coli" starts a list. This might change the semantics
-      of some existing documents, since previously the two-space
-      requirement was only enforced when the second word started
-      with a capital letter. But it is consistent with the existing
-      documentation and follows the principle of least surprise.
-      Resolves Issue #212.
-
-  * LaTeX template: redefine labelwidth when using enumerate package.
-    Otherwise the list labels (numbers) often extend past the left
-    margin, which looks bad.
-
-  * Mediawiki writer: Don't print a "== Notes ==" header before
-    references.  This is too English-centric. Writers can provide their
-    own header at the end of the document.
-
-  * Promoted mediawiki headers.  '= head =' is now level 1, '== head =='
-    level 2, etc.  This seems to be correct; it's only by convention
-    that wikipedia articles have level 2 headers at most.
-    Patch due to Eric Kow.
-
-  * RunTests.hs: Set LANG to a UTF-8 locale. Use 'pandoc --data-dir=' so
-    data files don't need to have been installed. This removes the need to
-    set HOME.
-
-  * HTML reader:
-    + Handle spaces before <html>.  Resolves Issue #216.
-    + Be forgiving in parsing a bare list within a list.
-      The following is not valid xhtml, but the intent is clear:
-      <ol>
-      <li>one</li>
-      <ol><li>sub</li></ol>
-      <li>two</li>
-      </ol>
-      We'll treat the <ol> as if it's in a <li>.  Resolves Issue #215.
-
-  * Updated INSTALL instructions.  cabal method is now promoted.
-
-  * Updated markdown2pdf man page. It no longer says all pandoc options
-    are accepted.
-
-  * README/man pages: Removed advice to pipe through tidy before HTML
-    reader.  This is obsolete, now that we have a forgiving HTML parser.
-
-  * LaTeX writer: set numbersections template variable, so
-    the section numbering options work again.
-
-  * Removed obsolete Makefile.
-
-  * Website: renamed index.txt.in -> index.txt.
-
-  * New batch file to make-windows-installer.
-    + Removed old Makefile.windows
-    + Added make-windows-installer.bat
-    + Modified default installer name in pandoc-setup.iss
-
-  * Removed freebsd and macports directories.
-    They are no longer up to date.
-
-  * Setup.hs:
-    + Made man page building sensitive to build verbosity.
-    + Improved detection of highlighting support in test hook.
-    + Install wrapper scripts into cabal bin directory.
-    + Also simplified installManpages.
-    + Setup.hs: install manpages to mandir.  Code borrowed from darcs.
-
-  * Changed default of writerXeTeX to False.
-
-  * HTML writer: don't include empty UL if --toc but no sections.
-    Resolves Issue #199.
-
-  * LaTeX writer:
-
-    + If book, report, or memoir documentclass, use \chapter{}
-      for first-level headers. Otherwise use \section{}.
-    + Removed stLink, link template variable. Reason: we now always
-      include hyperref in the template.
-
-  * LaTeX template:
-
-    + Only show \author if there are some.
-    + Always include hyperref package. It is used not just for links but
-      for toc, section heading bookmarks, footnotes, etc. Also added
-      unicode=true on hyperref options.
-
-  * markdown2pdf: always do at least two runs. hyperref bookmarks
-    require this.
-
-  * cabal file: Removed unneeded dependency on template-haskell.
-
-  * Windows installer - fixed bug in data file locations.
-    Resolves Issue #197.
-
-  * Deprecated --custom-header in documentation.
-    Removed old "Custom Headers" section in README.
-
-pandoc (1.4)
-
-  [ John MacFarlane ]
-
-  * Pandoc will now compile with either GHC 6.10 or 6.12.
-    + Don't use System.IO.UTF8 when compiling with 6.12
-    + Use -fno-warn-unused-do-bind option when compiling with 6.12
-
-  * Replaced old headers with templates.  Now users have much more
-    control over the way documents appear in --standalone mode,
-    and writer code is simplified.  Resolves Issues #59, 147.
-    Every effort has been made to retain backwards compatibilty.
-    So, the --custom-header option should still work as before.
-
-    + Added Text.Pandoc.Templates.  This provides functions for
-      retrieving default templates and for rendering templates.
-    + System templates (in the pandoc data directory) can be
-      overridden by user templates in $HOME/.pandoc/templates.
-    + Removed Text.Pandoc.DefaultHeaders.
-    + Removed data/headers directory.
-    + Added templates directory.
-    + Added writerTemplate and writerVariables fields to WriterOptions.
-    + Removed writerTitlePrefix, writerHeader fields from WriterOptions.
-    + Changed --print-default-header to --print-default-template.
-    + Added --template option.
-    + Added -V/--variable option to set custom template variables.
-
-  * Pandoc no longer requires Template Haskell.  Resolves Issue #186.
-
-    + Removed need for TH in ODT module. Instead get reference.odt from
-	  data file at run time.
-    + Removed TH dependency from S5 module. S5 module now exports
-      s5HeaderIncludes, which pandoc.hs includes if writer is s5 and
-      standalone.
-    + Refactored LaTeXMathML not to use TH.
-
-  * Meta is now Meta [Inline] [[Inline]] [Inline] rather than
-    Meta [Inline] [String] String. Authors and date in Meta are now lists
-    of Inline elements rather than raw strings. This means that they can
-    be formatted and can include footnotes. NOTE: This may be a breaking
-    change for those using pandoc as a library.
-
-  * Added readDataFile to Text.Pandoc.Shared.  This retrieves
-    a data file from the user pandoc data directory (~/.pandoc
-    on unix), or, if not found there, from the system data
-    directory ($CABALDIR/shared/pandoc-VERSION/). All data
-    files, including templates, LaTeXMathML.js, s5 styles,
-	and reference.odt, can be overridden by the user.
-
-  * s5 files moved from data/ui/default to s5/default.
-
-  * Use unicode instead of entities in HTML and XML output.  Resolves
-    Issue #163.
-
-  * Prettier HTML footnote references:  put anchor inside sup,
-    instead of other way.  Resolves Issue #191. Thanks to
-    infinity0x.
-
-  * Added --xetex option to pandoc and markdown2pdf.
-    If --xetex is specified, pandoc produces latex suitable for
-    processing by xelatex, and markdown2pdf uses xelatex to create
-    the PDF. Resolves Issue #185.
-
-  * RTF writer: multiple authors now occupy multiple paragraphs rather
-    than using a line break.
-
-  * Man writer: now the "--after-body" will come after the "AUTHORS"
-    section, whereas before it would come before it.  This is a
-    slight break from backwards compatibility.
-
-  * Added --reference-odt option, so users may customize the styles
-    used in pandoc-generated ODT files.  Users may also place a
-	default reference.odt in the ~\.pandoc directory.
-
-  * ODT writer:
-    + Indented and line-broke styles.xml so it can be modified more easily.
-    + Omitted some unnecessary style declarations.
-    + Don't wrap text in OpenDocument writer.  The tags are too long, making
-      wrapping ugly and pointless.
-
-  * LaTeX reader: use \\ to separate multiple authors.
-
-  * Markdown reader: use ; as separator between authors.
-    This allows you to use ',' within author names: e.g. "John Jones, Jr."
-
-  * S5 writer: use linebreak to separate authors in title page.
-
-  * RST reader: Allow :: before lhs code block. The RST spec requires the
-    :: before verbatim blocks. This :: should not be treated as literal
-    colons. Resolves Issue #189.
-
-  * Documented pandoc 1.3's new definition list syntax in README.
-    (An oversight in the last release.)
-
-  * markdown2pdf.hs:
-    + interpret ! in a log as an error line.
-    + --toc now works properly.
-
-  * Changes in RunTests.hs:
-    + Use the Diff library rather than a local copy of Diff.hs.
-      (This vastly increases performance.) This change means that 'cabal
-      test' presupposes that the Diff library is installed.
-    + Removed tests/Diff.hs from cabal file.
-    + Changed RunTests to use local environment. We need at least HOME, so
-      pandoc can find its data directory.
-
-  * Updated windows installer to install data files in the app directory.
-
-  * Windows installer now installs portable wrappers hsmarkdown and
-    markdown2pdf.
-
-pandoc (1.3)
-
-  [ John MacFarlane ]
-
-  * Added --id-prefix option (Issue #41). This adds a prefix to all
-    automatically generated HTML identifiers, which helps prevent
-    duplicate identifiers when you're generating a fragment (say a blog
-    post).
-
-  * Added --indented-code-classes option.  This specifies classes
-    to use for indented code blocks.  (Patch due to buttock; Issue #87.)
-
-  * --number-sections now affects HTML output as well as ConTeXt and LaTeX
-    (Issue #150).
-
-  * Improved syntax for markdown definition lists (Issue #24).
-    Definition lists are now more compatible with PHP Markdown Extra.
-    + You can have multiple definitions for a term (but still not
-      multiple terms).
-    + Multi-block definitions no longer need a column before each block
-      (indeed, this will now cause multiple definitions).
-    + The marker no longer needs to be flush with the left margin,
-      but can be indented at or two spaces.  Also, ~ as well as :
-      can be used as the marker (this suggestion due to David
-      Wheeler.)
-    + There can now be a blank line between the term and the
-      definitions.
-
-  * Better looking simple tables.  Resolves Issue #180.
-    + Markdown reader: simple tables are now given column widths of 0.
-    + Column width of 0 is interpreted as meaning: use default column width.
-    + Writers now include explicit column width information only
-      for multiline tables.  (Exception:  RTF writer, which requires
-      column widths.  In this case, columns are given equal widths,
-      adding up to the text width.)
-    + Simple tables should now look better in most output formats.
-
-  * Allow markdown tables without headers (Issue #50).
-    The new syntax is described in README. Also allow optional line of
-    dashes at bottom of simple tables.
-
-  * Compensate for width of final table column (Issue #144).
-
-  * Treat a backslash followed by a newline as a hard line break
-    in markdown.  Resolves Issue #154.  This is a nice alternative
-	to markdown's "invisible" way of indicating hardline breaks
-	using lines that end with two spaces.
-
-  * Improved performance of markdown reader by ~10% by eliminating the
-    need for a separate parsing pass for notes. Raw notes are now stored
-    on the first pass (which parses references), then parsed when the
-    note is inserted into the AST. The stateNotes field in ParserState
-    is now a list of [(String, String)] pairs instead of [(String,
-    [Block])].
-
-  * In markdown reader, treat 4 or more * or _ in a row as literal
-    text.  (Trying to parse long strings of * or _ as strong or emph
-	leads to exponential performance problems.)
-
-  * Markdown reader: Use + rather than %20 for spaces in URLs.
-
-  * Fixed htmlComment parser, adding a needed 'try'.
-
-  * Don't print raw HTML in man output.
-
-  * Allow . _ and ~ in header identifiers.
-
-  * Specially mark code blocks that were "literate" in the input.
-    They can then be treated differently in the writers.  This allows
-    authors to distinguish bits of the literate program they are writing
-    from source code examples, even if the examples are marked as
-    Haskell for highlighting.  (Issue #174.)
-
-  * Modified html+lhs output to use "haskell" highlighter instead
-    of "literateHaskell". The highlighting module now adds bird tracks
-	after highlighting (for HTML output), if the code block has the
-	"literate" class.  This gives better results, because kate's
-    haskell highlighter is much better than the literateHaskell
-    highlighter.
-
-  * Fixed handling of footnotes in titles (HTML) and headers (LaTeX).
-    (Issue #137.)
-
-  * Support for "..code-block" directive in RST reader. Not core
-    RST, but used in Sphinx for code blocks annotated with syntax
-    information. Thanks to Luke Plant for the patch.
-
-  * Added "head" to list of block-level HTML tags. Resolves
-    Issue #108.
-
-  * Added stripTags to Text.Pandoc.XML.  This is used in the HTML writer.
-
-  * Set utf-8 encoding in texinfo headers.
-
-  * Docbook writer: add ids to sections.  Use link for internal links.
-    (Issue #60.)
-
-  * Blank lines after lists in MediaWiki writer.
-
-  * Properly handle commented-out list items in markdown.
-    Resolves Issue #142.  Example:
-
-    - a
-    <!--
-    - b
-    -->
-    - c
-
-  * Changed heuristic in compactify. compactify has to decide whether a
-    Para that ends a list is a Para intentionally, or just because of
-    the blank lines at the end of every list. In the latter case the
-    Para is turned to a Plain. The old heuristic was: change final Para
-    to Plain iff the other items all end in Plain. This produces bad
-    results when, for example, an item contains just a Plain and an HTML
-    comment, as it does in the list above. The new heuristic: change
-    final Para to Plain iff the other items don't contain a Para.
-
-  * Added % as an rst underline character.  Resolves Issue #173.
-
-  * Fix inline math parser so that \$ is allowed in math.
-    Resolves Issue #169.
-
-  * Translate \int (integral) into unicode when using unicode math
-    method. Resolves Issue #177.
-
-  * markdown2pdf.hs improvements:
-    + Use System.IO.UTF8.
-    + Print error messages on last attempt.
-    + Do not create a backup when overwriting a PDF (Issue #166).
-    + Accept --longopt=val options.
-    + Added man/man1/markdown2pdf.1 to extra-tmp-files in cabal, so that
-      it is properly cleaned.
-
-  * Added haddock comments warning that readers assume \n line endings.
-
-  * Updated COPYRIGHT file.
-
-  * Makefile: Changed EXECSBASE so it doesn't pull in hsmarkdown &
-    markdown2pdf. Otherwise strip tries to strip shell scripts when you
-    install using 'make'.
-
-  * Changed Makefile so it doesn't build Haskell wrappers.
-
-  * Fixed Makefile so it doesn't try to build man pages in build-doc.
-
-  * Install pcre3.dll in Windows install script; this allows us to
-    package a version of pandoc with highlighting support.
-
-pandoc (1.2.1)
-
-  [ John MacFarlane ]
-
-  * Fixed regression with --preserveTabs. Brought back optPreserveTabs.
-    The trick of setting tabStop to 0 to mean "preserve tabs" had a bad
-    side effect: strings of 0 spaces were interpreted as indentation.
-    So, with --preserve-tabs, unindented paragraphs were treated as
-    code. Resolves Issue #138.
-
-  * HTML writer:  wrap sections in divs.  Resolves Issue #70.
-
-    + hierarchicalize has been rationalized; it builds a hierarchical
-      representation of the document from the headers, and simultaneously
-      gives each section a unique identifier based on the heading title.
-    + Identifiers are now attached to the divs rather than
-      to the headers themselves.
-    + Table of content backlinks go to the beginning of the table, rather
-      than to the section reference that was clicked.
-    + Code for constructing identifiers has been moved to Text.Pandoc.Shared
-      from the HTML writer, since it is now consumed only by
-      hierarchicalize.
-    + In --strict mode, pandoc just prints bare headings, as before
-      (unless --toc has been specified).
-    + In s5 output, it does not wrap sections in divs, as that seems to
-      confuse the s5 javascript.
-
-  * Man writer: break lines at end of each sentence. groff expects this
-    and treats '.' and '?' differently when followed by line ending as
-    opposed to ordinary space. Also, don't escape periods. Instead, use
-    zero-width character \& to avoid unwanted interpretation of periods
-    at start of line. Resolves Issue #148.
-
-  * Markdown writer:  Added '#' and '>' to list of characters to be
-    escaped in markdown output.  Removed '<', as it is not an officially
-    escapable character. This partially resolves Issue #96.
-
-  * Make --smart the default for man output format. Otherwise we have
-    trouble dividing lists of endlines into sentences.
-
-  * DocBook writer: Use language attribute to indicate source language
-    in code blocks.
-
-  * RST reader:
-
-    + Allow # to continue list, even if the list was started with an
-      explicit marker. For example:
-
-        A. my list
-		#. continued
-
-      Resolves Issue #140.
-    + Allow continuation lines in line blocks. Also added test cases for
-      line blocks for RST reader. Resolves Issue #149.
-    + Allow explicit links with spaces in URL: `link <to this>`_
-
-  * Improved LaTeX reader's coverage of math modes. Remove displaymath*
-    (which is not in LaTeX) and recognize all the amsmath environments
-    that are alternatives to eqnarray, namely equation, equation*,
-    gather, gather*, gathered, multline, multline*, align, align*,
-    alignat, alignat*, aligned, alignedat, split. Resolves Issue #103.
-    Thanks to shreevatsa.public for the patch.
-
-  * Markdown reader:
-
-    + Allow -, _, :, . in markdown attribute names. These are legal in
-      XML attribute names.
-    + Use non-breaking spaces in abbreviations.
-    + Markdown reader: improved efficiency of abbreviation parsing.
-      Instead of a separate abbrev parser, we just check for
-      abbreviations each time we parse a string. This gives a huge
-      performance boost with -S. Resolves Issue #141.
-
-  * Improved efficiency of shared parsers:  hexNum, htmlComment,
-    whitespace, indentSpaces.
-
-  * Export HTMLMathMethod in Text.Pandoc.
-
-  * Export languagesByExtension in Text.Pandoc.Highlighting.
-
-  * Added new Haskell version of markdown2pdf, due to
-    Paulo Tanimoto.  This should be more portable than the old
-	shell script.
-
-  * Made 'pandoc -v' more explicit about compiler options.
-    Resolves Issue #139.
-
-  * pandoc.hs:  Made --strict compatible with --standalone, --toc.
-
-  * Use Paths_pandoc to get version number, instead of hard-coding it
-    into Text/Pandoc.hs.
-
-pandoc (1.2)
-
-  [ John MacFarlane ]
-
-  * Added support for literate Haskell. lhs support is triggered by
-    '+lhs' suffixes in formats. For example, 'latex+lhs' is literate
-    Haskell LaTeX. '.lhs' files are treated by default as literate
-    markdown.
-
-    + Added stateLiterateHaskell to parser state.
-    + Added parser for lhsCodeBlock to Markdown, RST, LaTeX readers.
-    + Added parser for |inline lhs| to LaTeX reader.
-    + Added writerLiterateHaskell to WriterOptions.
-    + Added lhs support to Markdown, RST, LaTeX, HTML writers.
-    + Added definition of code environment to LaTeX header.
-    + Added tests (run only if highlighting support compiled in).
-    + Documented lhs features in man page and README.
-
-  * In Text.Pandoc.Definition, added processWith, processWithM,
-    and queryWith, and deprecated processPandoc and queryPandoc
-    for these more general functions.
-
-  * Fixed bug in mediawiki writer:  improper closing tags in tables.
-    Thanks to Benct Philip Jonsson for reporting the bug.
-
-  * Added --email-obfuscation option.
-
-    + Added writer option for email obfuscation.
-    + Implemented email obfuscation options in HTML writer.
-    + Added option to option parser.
-    + Documented in README and pandoc man page.
-    + Resolves Issue #97.
-
-  * LaTeX writer: fixed bug with empty table cells.
-    Resolves Issue #107.  Thanks to rodja.trappe for the patch.
-
-  * Fixed bug with header spacing in Markdown and RST writers.
-    A null header (Meta [] [] []) should not cause a blank line
-    at the beginning of output.  But a blank line is needed between
-    a non-null header and the main text.
-
-  * Markdown reader: Relax spacing rules for $$ in display math. Now
-    space and newlines are allowed after the opening $$ and before the
-    closing $$. However, the display math cannot contain an entirely
-    blank line. Resolves Issue #105.
-
-  * Markdown reader: Gobble space after Plain blocks containing only
-    raw html inline. Otherwise following header blocks are not parsed
-    correctly, since the parser sees blank space before them. Resolves
-    Issue #124.
-
-  * Markdown reader: Allow " as well as '' to end a latex double-quote.
-
-  * Conditionally depend on syb and base >= 4 if ghc >= 6.10.
-    Resolves Issue #109.
-
-  * Fixed problems in RST and markdown output due to bug in pretty-1.0.1.0
-
-    + Added hang' function to Text.Pandoc.Shared; this will be used instead
-      of hang, which doesn't work properly in pretty-1.0.1.0.  When pretty
-      is upgraded, we can go back to hang.
-      See  http://article.gmane.org/gmane.comp.lang.haskell.general/16687
-    + Use hang' (and some different techniques) in RST and markdown writers.
-      Some output is now a bit different.
-
-  * Brought citeproc support up to date for citeproc-hs-0.2.
-    (Patch by Andrea Rossato.)
-
-  * Moved all haskell source to src subdirectory.  Renamed Main.hs to
-    pandoc.hs.
-
-  * Rewrote hsmarkdown in Haskell for portability (src/hsmarkdown.hs).
-    For now, keeping the old shell script too.
-
-  * Added TemplateHaskell to Extensions for executable, removed
-    -threaded for library. Thanks to duncan.coutts for the bug report.
-    Resolves Issue #121.
-
-  * Moved some Extra-Source-Files to Data-Files.
-
-  * Moved tabFilter to Shared.
-
-  * In pandoc.hs, removed optPreserveTabs; instead, tabstop of 0 means
-    preserve tabs.
-
-  * Minor code cleanup based on hlint suggestions.
-
-pandoc (1.1)
-
-  [ John MacFarlane ]
-
-  * Main.hs:
-
-    + Changed date on copyright message in Main.hs.
-    + Have the '-v' option print syntax highlighting languages
-      separated by commas, and wrapped in lines, instead of in five
-      columns as before.
-
-  * Added --jsmath option.  Resolves Issue #68.
-
-    + Added --jsmath option to Main.hs
-    + Added JsMath to HTMLMathMethod in Text.Pandoc.Shared.
-    + Handle math appropriately in HTML writer when JsMath selected.
-    + Documented the option in README and man page.
-
-  * Text.Pandoc.Shared:  Changed compactify to use a better heuristic
-    for tight and loose lists. Final Para is changed to Plain if all
-    other list items *end* with a Plain block. Addresses Issue #99.
-
-  * HTML reader:
-
-    + Added colons to protocols in unsanitaryURI. Closes Issue #88.
-    + HTML reader: Don't interpret contents of <pre> blocks as markdown.
-      Added rawVerbatimBlock parser.  Resolves Issue #94.
-
-  * Markdown reader:
-
-    + Allow URLs with spaces in them in links and references, but escape
-      them as "%20".
-    + Allow blank space at the end of horizontal rules.
-
-  * RST reader: Modified 'unknownDirective' parser to handle comment
-    blocks correctly, and added tests for comment blocks. Resolves Issue
-    #86. Closes Debian Bug #500662.
-
-  * HTML writer:
-
-    + Include classes on tr elements in HTML output:
-      "header", "odd", "even".  This allows tables to be styled with
-      lines in alternating colors.  Resolves Issue #91.
-    + Enclose all LaTeXMathML bits in <span class="LaTeX">.
-      This prevents parts of the document that are not math from being
-      interpreted as math by LaTeXMathML.js.
-
-  * OpenDocument and ODT writers:  Added support for HorizontalRule elements,
-    which were formerly ignored.  Resolves Issue #95.
-
-  * Text.Pandoc.Shared:  Modified wrappedTeX to eliminate the line break
-    between a footnote and immediately following nonspace characters in
-    LaTeX and ConTeXt output. (This gets interpreted as a space, which
-    is not desired in cases like `text^[note]---`.)  Resolves Issue #93.
-
-  * Windows installer: Don't require admin privileges to run
-    installer.  Modified pandoc-setup.iss, and changed modpath.iss to
-    modify HKCU path if user lacks admin privileges.  Also fixed case
-    where oldpath is empty (previously this led to the new path
-    beginning with a semicolon).
-
-  * Updated INSTALL instructions for Arch packages and OS X install using
-    cabal-install.
-
-  * Removed the (now unneeded) debian directory.
-    Removed empty Codec and System directories.
-
-  * Moved odt-styles/ to data/.  Removed unneeded variable in Makefile.
-
-  * Modified Setup.hs so that the "test" target returns an error status
-    when tests fail, and "build" returns a success status if
-    the build succeeds.  Resolves Issue #100.
-
-  * Added BUGS to files in tarball.
-
-
-pandoc (1.0.0.1)
-
-  [ John MacFarlane ]
-
-  * Removed spurious reference to pdf output format from pandoc(1) man page.
-
-pandoc (1.0)
-
-  [ Andrea Rossato ]
-
-  * Added new OpenDocument writer.
-
-  * Added support for SmallCaps inline element.
-
-  * Added support for integrating pandoc with citeproc-hs.
-
-    + Added Cite element to definition and writers.
-    + Added Text.Pandoc.Biblio module
-    + Note: This support is included only if the 'citeproc'
-      Cabal configuration flag is set.
-
-  * Made Pandoc data structure an instance of Typeable.
-    Added new processPandoc and queryPandoc functions, to query
-    or transform matching elements in a Pandoc structure.
-
-  [ Peter Wang ]
-
-  * Added new Texinfo writer.
-
-  [ John MacFarlane ]
-
-  * Changes to Texinfo writer:
-
-    + No space between paragraph and following @verbatim (provides more
-      pleasing appearance in text formats)
-    + Blank line consistently after list environments.
-    + Removed deVerb.
-    + Use @code instead of @verb for inline code (this solves the character
-      escaping problem for texi2dvi and texi2pdf).
-    + Added news of Texinfo writer to README.
-    + Added Texinfo to list of formats in man page, and removed extra 'groff'.
-    + Added texi & texinfo extensions to Main.hs, and fixed bug in determining
-      default output extension.
-    + Modified disallowedInNode in Texinfo writer to correct list of disallowed characters.
-
-  * Added tests for OpenDocument writer.
-
-  * Added ODT writer (using zip-archive library to package output of
-    OpenDocument writer).  Added odt-styles directory with default ODT styles.
-
-  * Added new mediawiki writer and tests.
-
-  * Markdown reader: Added support for delimited code blocks, with optional
-    syntax highlighting using highlighting-kate (if the 'highlighting'
-    configuration option is selected).
-
-    + Currently highlighting is supported only in the HTML writer.
-    + Delimited code blocks can have attributes; using the language name as
-      class triggers highlighting.
-    + New Attributes parameter in CodeBlock structure.
-    + --version now indicates whether syntax highlighting support is compiled
-      in, and prints a list of supported languages
-
-  * Removed debian directory. Pandoc is no longer a native debian package.
-
-  * Changes to build process:  pandoc can now be built from the repository
-    using Cabal.  No unix tools are needed (so, pandoc can be built on Windows
-    without Cygwin).
-
-    + Include shell scripts themselves in repo, rather than generating from wrappers.
-      Removed wrappers directory and wrappers Makefile target.
-    + Text/Pandoc/ASCIIMathML.hs, Text/Pandoc/DefaultHeaders.hs,
-      and Text/Pandoc/Writers/S5.hs are no longer built in Makefile
-      from templates in the templates/ directory. Instead, they use template
-      haskell to read data at compile time from the relevant files in data/.
-      Template haskell functions go in a new module, Text.Pandoc.TH.
-    + man pages are now generated in Setup.hs hook, not by Makefile
-    + Makefile 'tarball' target now calls Cabal's 'sdist'
-    + Added "Extra-Source-Files" to pandoc.cabal, so sdist contains everything needed
-    + Added "Build-Type" field to pandoc.cabal to avoid warning.
-    + Added to "Extra-source-files" and "Extra-tmp-files" in pandoc.cabal,
-      so 'sdist' and 'clean' will work properly.
-    + Setup.hs now generates man pages in a postbuild hook.
-    + Added dependency-checking to Setup.hs, so it only rebuilds things
-      that need rebuilding.
-    + Added 'library' and 'executable' configuration flags.
-      Cabal can now be told to build just the library or just the executable.
-    + CABALOPTS may now be specified with 'make' to pass Cabal configuration flags.
-      For example:  CABALOPTS=-fhighlighting make
-
-  * Rewrote test suite so it doesn't depend on perl or unix tools.
-
-    + Replaced old runtests.pl with a Haskell script RunTests.hs.
-    + Added Diff.hs module to be used by RunTests.hs instead of unix 'diff'.
-    + Added test hook to Setup.hs, so tests may be run from cabal.
-    + Changed Makefile's 'test' target to run tests via cabal.
-    + Removed old generate.sh.
-    + Since we no longer have 'sed' to filter out raw HTML sections
-      from the docbook writer test, or raw LaTeX sections from the
-      context writer test, we now just include these sections.
-      They can be taken out if it is necessary to process the files.
-    + Updated latex and context writer tests to remove extra spaces
-      after '\\item'
-    + Added a markdown table reader test.
-    + Added markdown-reader-more.txt to test suite, for additional test cases
-      for raw ConTeXt environments and more.
-
-  * Compatibility fixes for CPP, Cabal, and haddock:
-
-    + Use CPP in "Extensions" field in pandoc.cabal.
-    + Removed use of backslash string continuations in source files.
-
-  * Removed pandoc.cabal.ghc66.  We now require Cabal >= 1.2, GHC >= 6.8,
-    base >= 3.
-
-  * Require parsec < 3.
-    The compatibility module in parsec 3.0.0 gives far worse performance than
-    parsec 2.1.  Eventually pandoc will be upgraded to use the new bytestring
-    version of parsec, and then we'll go to parsec 3.0.0.
-
-  * Removed Text.Regex dependencies by rewriting using plain Haskell
-    (Text.Pandoc.Writers.RTF, Text.Pandoc.Writers.HTML, Main.hs)
-
-  * Moved Text.Pandoc.Writers.DefaultHeaders -> Text.Pandoc.DefaultHeaders.
-
-  * Makefile:
-
-    + Added 'configure' as dependency of 'uninstall-all'.
-      (It uses the Cabal build program.)
-    + Makefile:  only use --with-hc-pkg if GHC_PKG is defined.
-      Note that Cabal will automatically choose the ghc-pkg appropriate
-      for the compiler selected, so normally specifying GHC by itself
-      is sufficient.
-
-  * Removed Text.Pandoc.UTF8 module; instead, depend on utf8-string and use
-    its IO and conversion functions.
-
-  * Added -Wall to ghc-options in pandoc.cabal.  Cleaned up modules so that
-    everything is -Wall clean.
-
-    + Added pragma to HTML writer to avoid deprecation warning for use of "start" attribute.
-    + Added pragma to Text/Pandoc/Shared.hs to get rid of "orphan instance" warnings.
-      (These are caused by the Lift instance for ByteString.)
-
-  * Changed the comment used to replace unsafe HTML if sanitize-html option
-    selected.
-
-  * Made -c/--css option repeatable on the command line (like -H, -A, -B).
-
-  * Moved XML-formatting functions to new unexported module Text.Pandoc.XML.
-
-  * Escape '\160' as "&#160;", not "&nbsp;" in XML.
-    "nbsp" isn't a predefined XML entity.
-
-  * Fixed bug in RST reader, which would choke on: "p. one\ntwo\n".
-    Added some try's in ordered list parsers.
-
-  * Man writer:  don't escape " as \".
-
-  * Allow newline before URL in markdown link references.  Resolves Issue #81.
-    Added tests for this issue in new "markdown-reader-more" tests.
-    Changed RunTests.hs to run these tests.
-
-  * Support for display math.  Resolves Issue #47.
-
-    + Added a DisplayMath/InlineMath selector to Math inlines.
-    + Markdown parser yields DisplayMath for $$...$$.
-    + LaTeX parser yields DisplayMath when appropriate.  Removed
-      mathBlock parsers, since the same effect is achieved by the math
-      inline parsers, now that they handle display math.
-    + Writers handle DisplayMath as appropriate for the format.
-    + Modified tests accordingly; added new tests for display math.
-
-  * Use LaTeXMathML instead of ASCIIMathML.  LaTeXMathML is closer
-    to LaTeX in its display of math, and supports many non-math LaTeX environments.
-
-    + Changed -m option to use LaTeXMathML rather than ASCIIMathML.
-    + Modified HTML writer to print raw TeX when LaTeXMathML is
-      being used instead of suppressing it.
-    + Removed ASCIIMathML files from data/ and added LaTeXMathML.
-    + Replaced ASCIIMathML with LaTeXMathML in source files.
-    + Modified README and pandoc man page source.
-    + Added --latexmathml option (kept --asciimathml as a synonym
-      for backwards compatibility)
-
-  * Markdown reader: Parse setext headers before atx headers.
-    Test case:
-       # hi
-       ====
-    parsed by Markdown.pl as an H1 header with contents "# hi".
-
-  * Markdown reader: Treat "mixed" lists the same way as Markdown.pl does.
-    The marker on the first list item determines the type of the whole
-    list.  Thus, a list like
-       1. one
-       -  two
-       *  three
-    gets parsed as a single ordered list.  (Previous versions of pandoc
-    treated this as an ordered list with an unordered sublist.)
-
-  * Markdown smart typography:
-
-    + Em dashes no longer eat surrounding whitespace.  Resolves Issue #69.
-    + Use nonbreaking spaces after known abbreviations in markdown parser.
-      Thus, for example, "Mr. Brown" comes out as "Mr.~Brown" in LaTeX, and does
-      not produce a sentence-separating space.  Resolves Issue #75.
-
-  * Markdown writer: Print unicode \160 literally, rather than as &nbsp;.
-
-  * Treat '\ ' in (extended) markdown as nonbreaking space.
-    Print nonbreaking space appropriately in each writer (e.g. ~ in LaTeX).
-
-  * The '--sanitize-html' option now examines URIs in markdown links
-    and images, and in HTML href and src attributes.  If the URI scheme
-    is not on a whitelist of safe schemes, it is rejected.  The main point
-    is to prevent cross-site scripting attacks using 'javascript:' URIs.
-    See http://www.mail-archive.com/markdown-discuss@six.pairlist.net/msg01186.html
-    and http://ha.ckers.org/xss.html.  Resolves Issue #62.
-
-  * HTML writer:
-
-    + Override Text.XHtml's stringToHtml function,
-      so that characters below 0xff are not converted to numerical entity
-      references. Also convert '\160' to "&nbsp;". This should aid readability
-      and editability of the HTML source. It does presuppose that the HTML
-      will be served as UTF-8.
-    + In code blocks, change leading newlines to <br /> tags.
-      (Some browsers ignore them.)  Resolves Issue #71.
-      See http://six.pairlist.net/pipermail/markdown-discuss/2008-May/001297.html
-    + Use style attributes rather than css classes for strikethrough
-      and ordered list styles.  This works better when fragments, rather than
-      standalone documents, are generated.
-
-  * HTML reader: Count anything that isn't a known block (HTML) tag as an
-    inline tag (rather than the other way around).  Added "html", "head", and
-    "body" to list of block tags.  Resolves Issue #66, allowing
-    <lj> to count as an inline tag.
-
-  * RTF writer: Fixed bug.  Extra spaces were being printed after emphasized,
-    boldface, and other inline elements.  Resolves Issue #64.
-
-  * LaTeX reader:  improvements in raw LaTeX parsing.
-
-    + "loose punctuation" (like {}) parsed as Space
-    + Para elements must contain more than Str "" and Space elements
-    + Added parser for "\ignore" command used in literate haskell.
-    + Reworked unknownCommand and rawLaTeXInline: when not in "parse raw"
-      mode, these parsers simply strip off the command part and allow
-      the arguments to be parsed normally.  So, for example,
-      \blorg{\emph{hi}} will be parsed as Emph "hi" rather than
-      Str "{\\emph{hi}}".
-    + Parse lhs "code" environments as verbatim.
-      Refactored parsers for verbatim environments.
-    + Removed specialEnvironment parser.
-    + parse '{}', if present, after \textless, \textgreater,
-      \textbar, \textbackslash, \ldots.
-    + Parse unescaped special characters verbatim rather than
-      changing them to spaces.  This way arguments of unknown
-      commands will appear in braces.
-
-  * Parse raw ConTeXt environments as TeX in markdown reader.
-    Resolves Issue #73.
-
-  * Moved BlockWrapper and wrappedBlocksToDoc from ConTeXt writer to Shared.
-
-  * Made some structural changes to parsing of raw LaTeX environments.
-    Previously there was a special block parser for LaTeX environments.
-    It returned a Para element containing the raw TeX inline. This has
-    been removed, and the raw LaTeX environment parser is now used in the
-    rawLaTeXInline parser. The effect is exactly the same, except that we
-    can now handle consecutive LaTeX and ConTeXt environments not separated
-    by spaces.  This new flexibility is required by the example in
-    Issue #73:
-
-        \placeformula \startformula
-             L_{1} = L_{2}
-        \stopformula
-
-    API change: The LaTeX reader now exports rawLaTeXEnvironment' (which
-    returns a string) rather than rawLaTeXEnvironment (which returns a block
-    element). This is more likely to be useful in other applications.
-
-  * Use \textsubscr instead of \textsubscript for LaTeX subscript macro.
-    \textsubscript conflicts with a definition in the memoir class.
-    Resolves Issue #65.
-
-  * Removed unneeded space after "\\item" in LaTeX and ConTeXt output.
-
-  * Added amsmath package to default LaTeX header. Resolves Issue #48.
-
-  * Added \setupitemize[autointro] to ConTeXt header, to prevent orphaned
-    list introduction lines.
-
-  * Changed Float to Double in definition of Table element.
-    (Double is more efficient in GHC.)
-
-  * Fixed bug in Markdown parser:  regular $s triggering math mode.
-    For example:  "shoes ($20) and socks ($5)."
-    The fix consists in two new restrictions:
-
-    + the $ that ends a math span may not be directly followed by a digit.
-    + no blank lines may be included within a math span.
-
-    Thanks to Joseph Reagle for noticing the bug.
-
-  * Use Data.List's 'intercalate' instead of custom 'joinWithSep'.
-    Removed 'joinWithSep' from Text.Pandoc.Shared.
-
-  * Updated README and man pages.  Acknowledge contributors in README.
-    Added paragraph to README about producing S5 with separate CSS/javascript.
-
-  * Updated INSTALL to reflect new build system (including configuration
-    options) and document new dependencies.  Added note to INSTALL that
-    Cabal >= 1.2 is required for build.  Resolves Issue #74.
-
-  * Fixed some haddock documentation errors.
-
-  * Small fix to markdown2pdf man page: only input needs to be piped through iconv.
-
-pandoc (0.46) unstable; urgency=low
-
-  [ John MacFarlane ]
-
-  * Made -H, -A, and -B options cumulative: if they are specified
-    multiple times, multiple files will be included.
-
-  * Added optional HTML sanitization using a whitelist.
-    When this option is specified (--sanitize-html on the command line),
-    unsafe HTML tags will be replaced by HTML comments, and unsafe HTML
-    attributes will be removed.  This option should be especially useful
-    for those who want to use pandoc libraries in web applications, where
-    users will provide the input.
-
-    + Main.hs:  Added --sanitize-html option.
-
-    + Text.Pandoc.Shared:  Added stateSanitizeHTML to ParserState.
-
-    + Text.Pandoc.Readers.HTML:
-      - Added whitelists of sanitaryTags and sanitaryAttributes.
-      - Added parsers to check these lists (and state) to see if a given
-        tag or attribute should be counted unsafe.
-      - Modified anyHtmlTag and anyHtmlEndTag to replace unsafe tags
-        with comments.
-      - Modified htmlAttribute to remove unsafe attributes.
-      - Modified htmlScript and htmlStyle to remove these elements if
-        unsafe.
-
-    + Modified README and man pages to document new option.
-
-  * Improved handling of email addresses in markdown and reStructuredText.
-    Consolidated uri and email address parsers.  (Resolves Issue #37.)
-
-    + New emailAddress and uri parsers in Text.Pandoc.Shared.
-      - uri parser uses parseURI from Network.URI.
-      - emailAddress parser properly handles email addresses with periods
-        in them.
-
-    + Removed uri and emailAddress parsers from Text.Pandoc.Readers.RST
-      and Text.Pandoc.Readers.Markdown.
-
-  * Markdown reader:
-
-    + Fixed emph parser so that "*hi **there***" is parsed as a Strong
-      nested in an Emph. (A '*' is only recognized as the end of the
-      emphasis if it's not the beginning of a strong emphasis.)
-
-    + Moved blockQuote parser before list parsers for performance.
-
-    + Modified 'source' parser to allow backslash-escapes in URLs.
-      So, for example, [my](/url\(1\)) yields a link to /url(1).
-      Resolves Issue #34.
-
-    + Disallowed links within links. (Resolves Issue #35.)
-      - Replaced inlinesInBalanced with inlinesInBalancedBrackets, which
-        instead of hard-coding the inline parser takes an inline parser
-        as a parameter.
-      - Modified reference and inlineNote to use inlinesInBalancedBrackets.
-      - Removed unneeded inlineString function.
-      - Added inlineNonLink parser, which is now used in the definition of
-        reference.
-      - Added inlineParsers list and redefined inline and inlineNonLink parsers
-        in terms of it.
-      - Added failIfLink parser.
-
-    + Better handling of parentheses in URLs and quotation marks in titles.
-      - 'source' parser first tries to parse URL with balanced parentheses;
-        if that doesn't work, it tries to parse everything beginning with
-        '(' and ending with ')'.
-      - source parser now uses an auxiliary function source'.
-      - linkTitle parser simplified and improved, under assumption that it
-        will be called in context of source'.
-
-    + Make 'block' conditional on strictness state, instead of using
-      failIfStrict in block parsers. Use a different ordering of parsers
-      in strict mode (raw HTML block before paragraph) for performance.
-      In non-strict mode use rawHtmlBlocks instead of htmlBlock.
-      Simplified htmlBlock, since we know it's only called in strict
-      mode.
-
-    + Improved handling of raw HTML.  (Resolves Issue #36.)
-      - Tags that can be either block or inline (e.g. <ins>) should
-        be treated as block when appropriate and as inline when
-        appropriate. Thus, for example,
-        <ins>hi</ins>
-        should be treated as a paragraph with inline <ins> tags, while
-        <ins>
-        hi
-        </ins>
-        should be treated as a paragraph within <ins> tags.
-      - Moved htmlBlock after para in list of block parsers.  This ensures
-        that tags that can be either block or inline get parsed as inline
-        when appropriate.
-      - Modified rawHtmlInline' so that block elements aren't treated as
-        inline.
-      - Modified para parser so that paragraphs containing only HTML tags and
-        blank space are not allowed.  Treat these as raw HTML blocks instead.
-
-    + Fixed bug wherein HTML preceding a code block could cause it to
-      be parsed as a paragraph.  The problem is that the HTML parser
-      used to eat all blank space after an HTML block, including the
-      indentation of the code block.  (Resolves Issue #39.)
-      - In Text.Pandoc.Readers.HTML, removed parsing of following space
-        from rawHtmlBlock.
-      - In Text.Pandoc.Readers.Markdown, modified rawHtmlBlocks so that
-        indentation is eaten *only* on the first line after the HTML
-        block.  This means that in
-        <div>
-             foo
-        <div>
-        the foo won't be treated as a code block, but in
-        <div>
-
-            foo
-
-        </div>
-        it will.  This seems the right approach for least surprise.
-
-  * RST reader:
-
-    + Fixed bug in parsing explicit links (resolves Issue #44).
-      The problem was that we were looking for inlines until a '<' character
-      signaled the start of the URL; so, if you hit a reference-style link,
-      it would keep looking til the end of the document.  Fix:  change
-      inline => (notFollowedBy (char '`') >> inline).  Note that this won't
-      allow code inlines in links, but these aren't allowed in resT anyway.
-
-    + Cleaned up parsing of reference names in key blocks and links.
-      Allow nonquoted reference links to contain isolated '.', '-', '_', so
-      so that strings like 'a_b_' count as links.
-
-    + Removed unnecessary check for following link in str.
-      This is unnecessary now that link is above str in the definition of
-      'inline'.
-
-  * HTML reader:
-
-    + Modified rawHtmlBlock so it parses </html> and </body> tags.
-      This allows these tags to be handled correctly in Markdown.
-      HTML reader now uses rawHtmlBlock', which excludes </html> and </body>,
-      since these are handled in parseHtml.  (Resolves Issue #38.)
-
-    + Fixed bug (emph parser was looking for `<IT>` tag, not `<I>`).
-
-    + Don't interpret contents of style tags as markdown.
-      (Resolves Issue #40.)
-      - Added htmlStyle, analagous to htmlScript.
-      - Use htmlStyle in htmlBlockElement and rawHtmlInline.
-      - Moved "script" from the list of tags that can be either block or
-        inline to the list of block tags.
-
-    + Modified rawHtmlBlock to use anyHtmlBlockTag instead of anyHtmlTag
-      and anyHtmlEndTag.  This fixes a bug in markdown parsing, where
-      inline tags would be included in raw HTML blocks.
-
-    + Modified anyHtmlBlockTag to test for (not inline) rather than
-      directly for block.  This allows us to handle e.g. docbook in
-      the markdown reader.
-
-  * LaTeX reader:  Properly recognize --parse-raw in rawLaTeXInline.
-    Updated LaTeX reader test to use --parse-raw.
-
-  * HTML writer:
-
-    + Modified rules for automatic HTML header identifiers to
-      ensure that identifiers begin with an alphabetic character.
-      The new rules are described in README.  (Resolves Issue #33.)
-
-    + Changed handling of titles in HTML writer so you don't get
-      "titleprefix - " followed by nothing.
-
-  * ConTeXt writer: Use wrappers around Doc elements to ensure proper
-    spacing.  Each block element is wrapped with either Pad or Reg.
-    Pad'ed elements are guaranteed to have a blank line in between.
-
-  * RST writer:
-
-    + Refactored RST writer to use a record instead of a tuple for state,
-      and to include options in state so it doesn't need to be passed as
-      a parameter.
-
-    + Use an interpreted text role to render math in restructuredText.
-      See http://www.american.edu/econ/itex2mml/mathhack.rst for the
-      strategy.
-
-  [ Recai Oktaş ]
-
-  * Debian packaging changes:
-
-    + Remove the empty 'include' directory in -dev package, which lintian
-      complains about.
-    + Bump Standarts-Version to 3.7.3.
-    + Use new 'Homepage:' field to specify the upstream URL on suggestion of
-      lintian.
-
- -- Recai Oktaş <roktas@debian.org>  Tue, 08 Jan 2008 05:13:31 +0200
-
-pandoc (0.45) unstable; urgency=low
-
-  [ John MacFarlane ]
-
-  * Simplified parsing of reference keys and notes in markdown and RST
-    readers: The Reference data structure from Text.Pandoc.Shared is no
-    longer needed, since referenceKey and noteBlock parses return strings
-    (as many blank lines as were occupied by the key or note) and update
-    state themselves.  getPosition and setPosition are now used to ensure
-    that error messages will give the correct line number. This yields
-    cleaner (and slightly faster) code, with more accurate parsing error
-    messages.
-
-  * Added new Math inline element:
-
-    + Markdown and LaTeX readers now convert TeX math into Math elements,
-      not TeX.
-    + This allows math to be treated differently from raw TeX in output.
-      TeX elements are no longer printed in output formats other than
-      Markdown, LaTeX, and ConTeXt.  But Math elements are always printed.
-
-  * New default handling of math in writers:
-
-    + New module Text.Pandoc.Readers.TeXMath exports readTeXMath, which
-      parses raw TeX math and outputs a string of Pandoc inlines that
-      tries to render it as far as possible using unicode characters,
-      lapsing into literal TeX when needed.
-    + readTeXMath is now used for default HTML output in HTML, S5, RTF,
-      and Docbook, if no other method for displaying math in HTML is
-      specified.  Enclosing $'s are no longer printed by default.
-    + By default, math is put inside `<span class="math">`. This way it can be
-      distinguished from the surrounding text, e.g. put in a different
-      font.
-
-  * New --gladtex and --mimetex options for display of math in HTML:
-
-    + If --gladtex is specified, math is output between `<eq>` tags, so
-      it can be processed by gladTeX.
-    + If --mimetex is specified, math is put in `<img>` tags with a link
-      to the mimetex CGI script (or any other script that takes TeX math
-      as input and outputs an image).  The URL of the script may be
-      specified, but defaults to /cgi-bin/mimetex.cgi.
-    + HTMLMathMethod structure in WriterOptions keeps track of how to
-      display math in HTML output.
-    + Updated README with a description of the four options for displaying
-      math in HTML.
-
-  * HTML reader:
-
-    + Fixed bug: parser for minimized attributes should not swallow
-      trailing spaces.
-    + Simplified HTML attribute parsing.
-    + Changed parsing of code blocks in HTML reader:  `<code>` tag is no
-      longer needed. `<pre>` suffices. All HTML tags in the code block
-      (e.g. for syntax highlighting) are skipped, because they are not
-      portable to other output formats. A `<code>...</code>` block not
-      surrounded by `<pre>` now counts as inline HTML, not a code block.
-    + Remove just one leading and one trailing newline from contents of
-      `<pre>...</pre>` in codeBlock parser.
-
-  * Markdown reader:
-
-    + Removed support for box-style block quotes.
-    + Require space before title in links and references.
-      This fixes a bug in parsing URLs like http://silly/url(withparen).
-    + Improved and simplified setextHeader parser.
-    + Fixed logic in smart quote parsing, adding some needed 'try'
-      statements.
-    + Fixed smart quote parsing so that unicode characters 8216 and 8217
-      are recognized as single quotes, and 8220 and 8221 as double quotes.
-
-  * RST reader:
-
-    + Fixed bug in parsing of code blocks. Previously a full tab indent
-      was required, but RST allows code to be indented any amount.
-      Resolves Issue #27.
-    + Allow field lists to be indented.
-    + Parse the contents of field lists instead of treating as a raw string.
-    + Represent field lists as definition lists instead of blockquotes.
-    + Fixed bug in which metadata would be overridden if the document
-      contained multiple field lists.
-    + Parse fields associated with '.. image::' blocks, and use 'alt'
-      field, if given, for image alt and title attributes.
-
-  * LaTeX reader:
-
-    + Modified specialChar so that '"' characters are parsed.
-    + Fixed a bug in parsing of \[ \] math blocks (thanks to Mark Kalderon).
-
-  * HTML writer:
-
-    + Changes in handling of math (see above).
-    + Don't produce HTML for table of contents if there are
-      no headers. (This would be an empty list, which is invalid XHTML.)
-
-  * Markdown writer:
-
-    + Don't print title attribute if title is empty. (This differs from
-      the behavior of Markdown.pl, and agrees with PHP Markdown. But John
-      Gruber has indicated that he prefers this behavior.) Adjusted test
-      suite accordingly.
-    + Fixed incorrect line wrapping in paragraphs including hard line
-      breaks. Resolves Issue #25.
-    + Fixed bug in markdown writer:  If an ordered list item began with
-      a marker greater than 3 characters in width, and the item took more
-      than one line, it would appear on the line after the list marker,
-      e.g.:
-
-          (12)
-              My list item.
-              Multiline.
-
-      Now it works as follows:
-
-          (12) My list item.
-              Multiline.
-
-  * RST writer
-
-    + Fixed bug in RST writer's handling of ordered lists. Previously,
-      list items with multiple lines would not always line up with
-      single-line list items. Now, list items are nested the length of
-      the list marker + 1. This looks better and ensures that list items
-      all line up. (Note that list markers are padded to the length of
-      the longest list marker in the series.)
-    + Use 3-space indent for unordered lists.
-    + If label for a link reference contains a colon, surround it by `
-      signs so it won't be interpreted as the end of the link label.
-
-  * LaTeX writer:
-
-    + Cleaner output for footnotes. Footnotes now always begin on a new
-      line, and the final } is on a line by itself only when it needs to
-      be (i.e. only when the note ends with a Verbatim environment).
-    + Added writer options to state, so state doesn't need to be passed as
-      a parameter.
-    + Text wrapping now provided, using wrapTeXIfNeeded.
-
-  * ConTeXt writer:  many improvements for more idiomatic ConTeXt output
-    (thanks to Idris Samawi Hamid for suggestions).
-
-    + PrettyPrint module now used for output.
-    + Writer options are now in state, so they don't have to be passed as
-      a parameter.
-    + Text wrapping now provided, using wrapTeXIfNeeded.
-    + Better treatment of footnotes:  footnotes are always on lines by
-      themselves, and the final } is on a line by itself only when
-      it needs to be (after \stoptyping).
-    + Use \subject, \subsubject, ... or \section, \subsection, ... for headings,
-      depending on whether --number-sections option is selected.
-    + Extra blank line inserted after \stopitemize
-    + Use new, "official" definition of blockquote environment. Also, use
-      blank line after \startblockquote to balance blank line at the end.
-    + Both itemized and enumerated lists are now generated using
-      \start-stopitemize, with appropriate options. Removed definitions
-      of ltxenum and ltxitem, which are no longer needed. Provided
-      defaults for itemized lists in the preamble. State keeps track of
-      ordered list level, so that when default numbering is specified,
-      the appropriate scheme can be used.
-    + Changed \useurl to \useURL.
-    + Changed link color from red to blue.
-    + Use \subsubsubsubsection etc., since these are supported
-      (up to at least sub x 5).
-
-  * Text.Pandoc.Shared:
-
-    + Save and restore position in parseFromString, so that accurate
-      error messages can be given.
-    + Improved efficiency of romanNumeral parser.
-    + Added wrappedTeX and wrapTeXIfNeeded functions.  These ensure
-      that footnotes occur on lines by themselves (to make them
-      easier to see and move) and do not screw up line wrapping.
-
-  * Text.Pandoc.UTF8:  modified fromUTF8 to strip out the BOM
-    if present.  Windows Notepad and other applications insert a
-    BOM at the beginning of a UTF8 file.
-
-  * Main.hs (tabFilter): Treat '\r' at end of line as newline (in
-    addition to "\r\n" and '\n').
-
-  * Added a writer option for wrapped text and a command-line option
-    '--no-wrap', which disables text wrapping and minimizes whitespace
-    in HTML. (Resolves Issue #26.)
-
-    + Added support for '--no-wrap' to Main.hs.
-    + Added wrapIfNeeded function to Text.Pandoc.Shared.
-    + Use wrapIfNeeded instead of wrapped in the RST, Man, Docbook, and
-      Markdown writers.
-    + Added render and renderFragment helpers to HTML writer.
-
-  * Modified html2markdown to run tidy only if the HTML cannot be
-    parsed. Previously html2markdown piped all input through tidy
-    before passing it to pandoc. This caused problems on certain pages
-    (e.g. http://daringfireball.com/markdown) which have well-formed
-    XHTML that causes tidy to choke. The solution is to pipe through
-    tidy only if pandoc cannot parse the input by itself. This means
-    that a temp file is now always used, even when input comes from a
-    local file or standard input.
-
-  * Removed 'version' constant from Main.hs; added 'pandocVersion' to
-    Text.Pandoc library.
-
-  * pandoc.cabal:
-
-    + Modified to work with GHC 6.8 and Cabal configurations. (For GHC
-      6.8, pretty and containers must be added to Build-Depends, and it
-      is desirable to use the -O2 compiler option.)  Cabal configurations
-      allows one to select options depending on the compiler version.
-      For GHC 6.6, the splitBase option can be disabled.
-    + pandoc.cabal.ghc66 is provided for users with older versions of
-      Cabal, which do not support configurations.
-    + Use Ghc-Prof-Options to ensure that '-auto-all' is used when
-      '--enable-(executable|library)-profiling' is specified. Updated
-      PROFILING instructions accordingly.
-
-  * Makefile:
-
-    + Makefile now checks GHC version. If GHC is 6.6, pandoc.cabal.ghc66
-      is copied to pandoc.cabal, and the old pandoc.cabal is copied
-      to pandoc.cabal.orig. Otherwise, pandoc.cabal is copied to
-      pandoc.cabal.orig but otherwise unmodified. This way, the Makefile
-      will work properly with either GHC 6.6 or 6.8.
-    + Changed BUILDCONF to point to dist/setup-config, not .setup-config.
-      This is where current versions of Cabal put it.
-    + Added $(BUILDCMD) target, so setup doesn't get compiled every time.
-    + Removed dependency of templates on ./templates, which is circular
-      now that templates is a subdirectory of the top-level.
-
-  * MacPorts Portfile:
-
-    + Modified to install the pandoc library in addition to programs.
-    + Installation must be done manually rather than using Makefile's
-      install-all.
-    + Note that the library must be registered in the activate phase,
-      after the library files have been copied out of the destroot.
-      Cabal generates a 'register.sh' script that will do this.
-
-  * debian/control: Added libghc6-network-dev, libghc6-xhtml-dev, and
-    libghc6-mtl-dev as dependencies for libghc6-pandoc-dev.
-    Closes: #445235
-
-  * debian/rules:  Converted to UTF-8.
-
-  * Changed pandoc home page to http://johnmacfarlane.net/pandoc/.
-
-  * Updated ASCIIMathML.js to latest version.
-
-  * Directory structure:
-
-    + Moved everything from src into the top-level directory.
-    + Changed references to source directory in Makefile and
-      pandoc.cabal.*.
-    + Moved ASCIIMathML.js, headers, and ui into templates directory.
-    + Modified fillTemplates.pl to reflect new paths.
-
-  [ Recai Oktaş ]
-
-  * Makefile: Fixed the issue of having two copies of the library
-    documentation under some usage scenarios.
-
-  * Replaced 'ghc' with '$(GHC)' in Makefile, and made GHC
-    and GHC_PKG configurable through the environment, to support
-    unusual ghc installations.  For example:
-    GHC=/opt/ghc/bin/ghc GHC_PKG=/opt/ghc/bin/ghc-pkg make
-
- -- Recai Oktaş <roktas@debian.org>  Sun, 07 Oct 2007 20:51:43 +0300
-
-pandoc (0.44) unstable; urgency=low
-
-  [ John MacFarlane ]
-
-  * Fixed bug in HTML writer:  when --toc was used, anchors were put around
-    headers, which is invalid XHTML (block content within inline element).
-    Now the anchors are put inside the header tags.  Resolves Issue #23.
-
-  * Added xmlns attribute to html element in html writer tests.
-    This attribute is added by more recent versions of the
-    xhtml library (>= 3000), and is required for valid XHTML.
-
-  [ Recai Oktaş ]
-
-  * On configure, compile 'Setup.hs' to 'setup' and use 'setup' as the build
-    command instead of 'runhaskell', which, on some platforms (such as s390,
-    alpha, m68k), throws the following error:
-
-        runhaskell Setup.hs configure --prefix=/usr
-        ghc-6.6.1: not built for interactive use
-
-    This causes a serious FTBFS bug.  Closes: #440668.
-
- -- Recai Oktaş <roktas@debian.org>  Mon, 03 Sep 2007 18:24:02 +0300
-
-pandoc (0.43) unstable; urgency=low
-
-  [ John MacFarlane ]
-
-  * The focus of this release is performance.  The markdown parser
-    is about five times faster than in 0.42, based on benchmarks
-    with the TextMate manual.
-
-  * Main.hs: Replaced CRFilter and tabFilter with single function
-    tabFilter, which operates on the whole string rather than breaking
-    it into lines, and handles dos-style line-endings as well as tabs.
-
-  * Added separate LaTeX reader and native reader tests; removed
-    round-trip tests.
-
-  * Text.Pandoc.Shared:
-
-    + Removed tabsToSpaces and tabsInLine (they were used only in Main.hs.)
-    + General code cleanup (to elimante warnings when compiling with -Wall.)
-    + Added 'wrapped' function, which helps wrap text into paragraphs,
-      using the prettyprinting library.
-    + Rewrote charsInBalanced and charsInBalanced'.
-        - Documented restriction: open and close must be distinct characters.
-        - Rearranged options for greater efficiency.
-        - Bug fix: Changed inner call to charsInBalanced inside
-          charsInBalanced' to charsInBalanced'.
-    + anyLine now requires that the line end with a newline (not eof).
-      This is a harmless assumption, since we always add newlines to the
-      end of a block before parsing with anyLine, and it yields a 10% speed
-      boost.
-    + Removed unnecessary 'try' in anyLine.
-    + Removed unneeded 'try' from romanNumeral parser.
-    + Use notFollowedBy instead of notFollowedBy' in charsInBalanced.
-    + Removed unneeded 'try' in parseFromString.
-    + Removed unneeded 'try' from stringAnyCase.  (Now it behaves
-      like 'string'.)
-    + Changed definition of 'enclosed' in Text.Pandoc.Shared so that
-      'try' is not automatically applied to the 'end' parser. Added
-      'try' in calls to 'enclosed' where needed. Slight speed increase.
-
-  * Writers:
-
-    + Replaced individual wrapping routines in RST, Man, and Markdown
-      writers with 'wrapped' from Text.Pandoc.Shared.
-    + Rewrote LaTeX writer to use the prettyprinting library,
-      so we get word wrapping, etc.
-    + Modified latex writer tests for new latex writer using prettyprinter.
-    + Fixed bug in LaTeX writer: autolinks would not cause
-      '\usepackage{url}' to be put in the document header. Also, changes
-      to state in enumerated list items would be overwritten.
-    + In Markdown writer, escape paragraphs that begin with ordered list
-      markers, so they don't get interpreted as ordered lists.
-
-  * Text.Pandoc.Reades.LaTeX:
-
-    + Fixed bug in LaTeX reader, which wrongly assumed that the roman
-      numeral after "enum" in "setcounter" would consist entirely of
-      "i"s. 'enumiv' is legitimate.
-    + LaTeX command and environment names can't contain numbers.
-    + Rearranged order of parsers in inline for slight speed improvement.
-    + Added '`' to special characters and 'unescapedChar'.
-
-  * Text.Pandoc.Readers.RST:
-
-    + Removed unneeded try's in RST reader; also minor code cleanup.
-    + Removed tabchar.
-    + Rearranged parsers in inline (doubled speed).
-
-  * Text.Pandoc.Readers.Markdown:
-
-    + Skip notes parsing if running in strict mode. (This yields a nice
-      speed improvement in strict mode.)
-    + Simplify autolink parsing code, using Network.URI to test for
-      URIs. Added dependency on network library to debian/control and
-      pandoc.cabal.
-    + More perspicuous definition of nonindentSpaces.
-    + Removed unneeded 'try' in 'rawLine'.
-    + Combined linebreak and whitespace into a new whitespace parser, to
-      avoid unnecessary reparsing of space characters.
-    + Removed unnecessary 'try' in 'codeBlock', 'ellipses', 'noteMarker',
-      'multilineRow', 'dashedLine', 'rawHtmlBlocks'.
-    + Use lookAhead in parsers for setext headers and definition lists
-      to see if the next line begins appropriately; if not, don't waste
-      any more time parsing.
-    + Don't require blank lines after code block. (It's sufficient to
-      end code block with a nonindented line.)
-    + Changed definition of 'emph': italics with '_' must not
-      be followed by an alphanumeric character. This is to help
-      prevent interpretation of e.g. `[LC_TYPE]: my_type` as
-      `[LC<em>TYPE]:my</em>type`.
-    + Improved Markdown.pl-compatibility in referenceLink: the two parts
-      of a reference-style link may be separated by one space, but not
-      more... [a] [link], [not]    [a link].
-    + Fixed markdown inline code parsing so it better accords with
-      Markdown.pl: the marker for the end of the code section is a clump
-      of the same number of `'s with which the section began, followed
-      by a non-` character. So, for example,
-         ` h ``` i ` -> `<code>h ``` i</code>`.
-    + Split 'title' into 'linkTitle' and 'referenceTitle', since the
-      rules are slightly different.
-    + Rewrote 'para' for greater efficiency.
-    + Rewrote link parsers for greater efficiency.
-    + Removed redundant 'referenceLink' in definition of inline (it's
-      already in 'link').
-    + Refactored escapeChar so it doesn't need 'try'.
-    + Refactored hrule for performance in Markdown reader.
-    + More intelligent rearranging of 'inline' so that most frequently
-      used parsers are tried first.
-    + Removed tabchar parser, as whitespace handles tabs anyway.
-
-  * Text.Pandoc.CharacterReferences:
-
-    + Refactored.
-    + Removed unnecessary 'try's for a speed improvement.
-    + Removed unnecessary '&' and ';' from the entity table.
-
-  * Build process:
-
-    + Makefile: Get VERSION from cabal file, not Main.hs.
-    + Modified MacPorts Portfile:
-        - Depend on haddock
-        - Build and install libraries and library documentation in
-          addition to pandoc executable
-        - Added template item for md5 sum in Portfile.in.
-        - Incorporated changes from MacPorts repository (r28278).
-    + FreeBSD port:  Don't try to generate distinfo in Makefile.
-      It can be made using 'make makesum' in FreeBSD.
-    + Make both freebsd and macports targets depend on tarball.
-
-  * Website and documentation:
-
-    + Updated INSTALL instructions.
-    + Added pandocwiki demo to website.
-    + Removed local references to Portfile, since pandoc is now in the
-      MacPorts repository.
-
- -- Recai Oktaş <roktas@debian.org>  Sun, 02 Sep 2007 15:50:11 +0300
-
-pandoc (0.42) unstable; urgency=low
-
-  [ John MacFarlane ]
-
-  * Main.hs: Use utf8 conversion on the extra files loaded with
-    the -H, -C, -B, and -A options.  This fixes problems with unicode
-    characters in these files.
-
-  * Exposed Text.Pandoc.ASCIIMathML, since it is imported in
-    Text.Pandoc.Readers.HTML and without it we get a linking error when
-    using the library.
-
-  * Markdown reader:
-
-    + Added new rule for enhanced markdown ordered lists: if the list
-      marker is a capital letter followed by a period (including a
-      single-letter capital roman numeral), then it must be followed by
-      at least two spaces. The point of this is to avoid accidentally
-      treating people's initials as list markers: a paragraph might begin,
-      "B. Russell was an English philosopher," and this shouldn't be
-      treated as a list.  Documented change in README.
-    + Blocks that start with "p. " and a digit are no longer treated
-      as ordered lists (it's a page number).
-    + Added a needed 'try' to listItem.
-    + Removed check for a following setext header in endline.
-      A full test is too inefficient (doubles benchmark time), and the
-      substitute we had before is not 100% accurate.
-    + Don't use Code elements for autolinks if --strict specified.
-
-  * LaTeX writer:  When a footnote ends with a Verbatim environment, the
-    close } of the footnote cannot occur on the same line or an error occurs.
-    Fixed this by adding a newline before the closing } of every footnote.
-
-  * HTML writer:
-    + Removed incorrect "{}" around style information in HTML tables.
-      Column widths now work properly in HTML.
-    + If --strict option is specified (and --toc is not), don't include
-      identifiers in headers, for better Markdown compatibility.
-
-  * Build process:
-
-    + Separated $(web_dest) and website targets.
-    + In website, index.txt is now constructed from template index.txt.in.
-    + Added freebsd target to Markefile. This creates the freebsd Makefile
-      from Makefile.in, and creates distinfo.  Removed Makefile and distinfo
-      from the repository.
-    + Added macport target to Makefile. Portfile is built from template
-      Portfile.in.
-    + Removed OSX package targets.  (Too many difficulties involving
-      dependencies on dynamic libraries.)
-    + More complete INSTALL instructions for all architectures.
-
-  * Website:
-    + Added a programming demo, pandocwiki.
-
-  [ Recai Oktaş ]
-
-  * Do not forget to close pandoc's ITP.  Closes: #391666
-
- -- Recai Oktaş <roktas@debian.org>  Sun, 26 Aug 2007 22:51:32 +0300
-
-pandoc (0.41) unstable; urgency=low
-
-  [ John MacFarlane ]
-
-  * Fixed bugs in HTML reader:
-    + Skip material at end *only if* `</html>` is present (previously,
-      only part of the document would be parsed if an error was
-      found; now a proper error message is given).
-    + Added new constant eitherBlockOrInline with elements that may
-      count either as block-level or as inline. Modified isInline and
-      isBlock to take this into account.
-    + Modified rawHtmlBlock to accept any tag (even an inline tag):
-      this is innocuous, because rawHtmlBlock is tried only if a regular
-      inline element can't be parsed.
-    + Added a necessary 'try' in definition of 'para'.
-
-  * Fixed bug in markdown ordered list parsing.  The problem was that
-    anyOrderedListStart did not check for a space following the
-    ordered list marker.  So in 'A.B. 2007' the parser would be
-    expecting a list item, but would not find one, causing an error.
-    Fixed a similar bug in the RST reader.  Resolves Issue #22.
-
-  * Refactored RST and Markdown readers using parseFromString.
-
-  * LaTeX reader will now skip anything after \end{document}.
-
-  * Fixed blockquote output in markdown writer: previously, block
-    quotes in indented contexts would be indented only in the first
-    line.
-
-  * Added note to INSTALL about variations in versions of the xhtml
-    library that can lead to failed tests (thanks to Leif LeBaron).
-
- -- Recai Oktaş <roktas@debian.org>  Sun, 19 Aug 2007 23:26:07 +0300
-
-pandoc (0.4) unstable; urgency=low
-
-  [ John MacFarlane ]
-
-  * Added two new output formats: groff man pages and ConTeXt. By
-    default, output files with extensions ".ctx" and ".context" are
-    assumed to be ConTeXt, and output files with single-digit extensions
-    are assumed to be man pages.
-
-  * Enhanced ordered lists (documented in README, under Lists):
-    + The OrderedList block element now stores information about
-      list number style, list number delimiter, and starting number.
-    + The readers parse this information when possible.
-    + The writers use this information to style ordered lists.
-    + The enhancement can be disabled using the --strict option.
-
-  * Added support for tables (with a new Table block element). Two kinds
-    of tables are supported: a simple table with one-line rows, and a
-    more complex variety with multiline rows. All output formats are
-    supported, but only markdown tables are parsed at the moment. The
-    syntax is documented in README.
-
-  * Added support for definition lists (with a new DefinitionList block
-    element). All output and input formats are supported. The syntax is
-    documented in README.
-
-  * Added support for superscripts and subscripts (with new Superscript
-    and Subscript inline elements).  All input and output
-    formats.  The syntax is documented in README.
-
-  * Added support for strikeout (with a new Strikeout inline element).
-    All input and output formats are supported. Thanks to Bradley Kuhn,
-    who contributed a patch. The syntax is documented in README. Resolves
-    Issue #18.
-
-  * Added a --toc|--table-of-contents option.  This causes an automatically
-    generated table of contents (or an instruction that creates one) to
-    be inserted at the beginning of the document. Not supported in S5,
-    DocBook, or man page writers.
-
-  * Modified the -m|--asciimathml option:
-
-    + If an optional URL argument is provided, a link is inserted
-      instead of the contents of the ASCIIMathML.js script.
-    + Nothing is inserted unless the document actually contains
-      LaTeX math.
-
-  * Removed Blank block element as unnecessary.
-
-  * Removed Key and Note blocks from the Pandoc data structure. All
-    links are now stored as explicit links, and note contents are
-    stored with the (inline) notes.
-
-    + All link Targets are now explicit (URL, title) pairs; there
-      is no longer a 'Ref' target.
-    + Markdown and RST parsers now need to extract data from key and
-      note blocks and insert them into the relevant inline elements.
-      Other parsers have been simplified, since there is no longer any need
-      to construct separate key and note blocks.
-    + Markdown, RST, and HTML writers need to construct lists of
-      notes; Markdown and RST writers need to construct lists of link
-      references (when the --reference-links option is specified); and
-      the RST writer needs to construct a list of image substitution
-      references. All writers have been rewritten to use the State monad
-      when state is required.
-    + Several functions (generateReference, keyTable,
-      replaceReferenceLinks, replaceRefLinksBlockList, and some auxiliaries
-      used by them) have been removed from Text.Pandoc.Shared, since
-      they are no longer needed. New functions and data structures
-      (Reference, isNoteBlock, isKeyBlock, isLineClump) have been
-      added. The functions inTags, selfClosingTag, inTagsSimple, and
-      inTagsIndented have been moved to the DocBook writer, since that
-      is now the only module that uses them. NoteTable is now exported
-      in Text.Pandoc.Shared.
-    + Added stateKeys and stateNotes to ParserState; removed stateKeyBlocks,
-      stateKeysUsed, stateNoteBlocks, stateNoteIdentifiers, stateInlineLinks.
-    + Added writerNotes and writerReferenceLinks to WriterOptions.
-
-  * Added Text.Pandoc module that exports basic readers, writers,
-    definitions, and utility functions. This should export everything
-    needed for most uses of Pandoc libraries. The haddock documentation
-    includes a short example program.
-
-  * Text.Pandoc.ASCIIMathML is no longer an exported module.
-
-  * Added Text.Pandoc.Blocks module to help in printing markdown
-    and RST tables.  This module provides functions for working with
-    fixed-width blocks of text--e.g., placing them side by side, as
-    in a table row.
-
-  * Refactored to avoid reliance on Haskell's Text.Regex library, which
-    (a) is slow, and (b) does not properly handle unicode.  This fixed
-    some strange bugs, e.g. in parsing S-cedilla, and improved performance.
-
-    + Replaced 'gsub' with a general list function  'substitute'
-      that does not rely on Text.Regex.
-    + Rewrote extractTagType in HTML reader so that it doesn't use
-      regexs.
-    + In Markdown reader, replaced email regex test with a custom email
-      autolink parser (autoLinkEmail). Also replaced selfClosingTag regex
-      with a custom function isSelfClosingTag.
-    + Modified Docbook writer so that it doesn't rely on Text.Regex for
-      detecting 'mailto' links.
-    + Removed escapePreservingRegex and reamped entity-handling
-      functions in Text.Pandoc.Shared and Text.Pandoc.CharacterReferences to
-      avoid reliance on Text.Regex (see below on character reference
-      handling changes).
-
-  * Renamed Text.Pandoc.Entities as Text.Pandoc.CharacterReferences.
-
-  * Changed handling of XML entities.  Entities are now parsed (and unicode
-    characters returned) in the Markdown and HTML readers, rather than being
-    handled in the writers.  In HTML and Docbook writers, UTF-8 is now used
-    instead of entities for characters above 128.  This makes the HTML and
-    DocBook output much more readable and more easily editable.
-
-    + Removed sgmlHexEntity, sgmlDecimalEntity, sgmlNamedEntity, and
-      sgmlCharacterEntity regexes from Text.Pandoc.Shared.
-    + Renamed escapeSGMLChar to escapeCharForXML.  Added escapeStringForXML.
-      Moved both functions to Text.Pandoc.Writers.Docbook.
-    + Added characterReference parser to Text.Pandoc.CharacterReferences.
-      This parses a string and return a unicode character.
-    + Rewrote decodeCharacterReferences to use the new parser instead of
-      Text.Regex.
-    + Added new charRef parser for Markdown and HTML, which replaces the
-      old 'entity' parser. Added '&' as a special character in Markdown reader.
-    + Modified HTML and Markdown readers to call decodeEntities on all raw
-      strings (e.g. authors, dates, link titles), to ensure that no
-      unprocessed entities are included in the native representation of
-      the document.  (In the HTML reader, most of this work is done by a
-      change in extractAttributeName.)
-    + In XML and Markdown output, escape unicode nonbreaking space as '&nbsp;',
-      since a unicode non-breaking space is impossible to distinguish visually
-      from a regular space.  (Resolves Issue #3.)
-    + Removed encodeEntitiesNumerical.
-    + Use Data.Map for entityTable and (new) reverseEntityTable, for a
-      slight performance boost over the old association list.
-    + Removed unneeded decodeEntities from 'str' parser in HTML and
-      Markdown readers.
-
-  * Text.Pandoc.UTF8:  Renamed encodeUTF8 to toUTF8, decodeUTF8 to
-    fromUTF8, for clarity.
-
-  * Replaced old haskell98 module names replaced by hierarchical module
-    names, e.g. List by Data.List.  Removed haskell98 from dependencies
-    in pandoc.cabal, and added mtl (needed for state monad). Substituted
-    xhtml for html.
-
-  * Refactored and cleaned up character escaping in writers, using
-    backslashEscapes and escapeStringUsing functions.
-
-  * Instead of adding "\n\n" to the end of an input string in Main.hs,
-    this is now done in the readers. This makes the libraries behave
-    the way you'd expect from the pandoc program. Resolves Issue #10.
-
-  * URLs and email addresses in autolinks are now typeset as Code.
-
-  * In Main.hs, changed putStr to putStrLn -- mainly because MacOS X
-    doesn't display the whole output unless there's a line ending.
-
-  * Major code cleanup in all modules, for greater consistency, concision,
-    and readability.
-
-  * HTML reader:
-
-    + Fixed several bugs (extractTagType, attribute parsing).
-    + Remove Null blocks in lists of blocks when possible.
-    + Allow HTML comments as raw HTML inline.
-
-  * Markdown reader:
-
-    + Ordered list items may no longer begin with uppercase letters, or
-      letters greater than 'n'.  (This prevents first initials and page
-      reference, e.g. 'p. 400', from being parsed as beginning lists.)
-      Also, numbers beginning list items may no longer end with ')',
-      which is now allowed only after letters.  Note: These changes
-      may cause documents to be parsed differently. Users should take
-      care in upgrading.
-    + Changed autoLink parsing to conform better to Markdown.pl's
-      behavior. `<google.com>` is not treated as a link, but
-      `<http://google.com>`, `<ftp://google.com>`, and
-      `<mailto:google@google.com>` are.
-    + Cleaned up handling of embedded quotes in link titles.  Now these are
-      stored as a '"' character, not as '&quot;'.
-    + Use lookAhead parser for the 'first pass' (looking for reference keys),
-      instead of parsing normally, then using setInput to reset input.  This
-      yields a slight performance boost.
-    + Fixed several bugs in smart quote recognition.
-    + Fixed bug in indentSpaces (which didn't properly handle
-      cases with mixed spaces and tabs).
-    + Consolidated 'text', 'special', and 'inline' into 'inline'.
-    + Fixed bug which allowed URL and title to be separated by multiple blank
-      lines in links and reference keys.  They can be on separate lines but
-      can't have blank lines between them.
-    + Correctly handle bracketed text inside inline footnotes and links,using
-      new function inlinesInBalanced.  Resolves Issue #14.
-    + Fixed bug in footnotes: links in footnotes were not being
-      processed. Solution: three-stage parse. First, get all the
-      reference keys and add information to state. Next, get all the
-      notes and add information to state. (Reference keys may be needed
-      at this stage.) Finally, parse everything else.
-    + Replaced named constants like 'emphStart' with literals.
-    + Removed an extra occurance of escapedChar in definition of inline.
-
-  * RST reader:
-
-    + Allow the URI in a RST hyperlink target to start on the line
-      after the reference key.
-    + Added 'try' in front of 'string', where needed, or used a different
-      parser.  This fixes a bug where ````` would not be correctly parsed as
-      a verbatim `.
-    + Fixed slow performance in parsing inline literals in RST reader.  The
-      problem was that ``#`` was seen by 'inline' as a potential link or image.
-      Fix:  inserted 'notFollowedBy (char '`')' in link parsers.
-      Resolves Issue #8.
-    + Use lookAhead instead of getInput/setInput in RST reader.  Removed
-      unneeded getState call, since lookAhead automatically saves and
-      restores the parser state.
-    + Allow hyperlink target URIs to be split over multiple lines, and
-      to start on the line after the reference. Resolves Issue #7.
-    + Fixed handling of autolinks.
-
-  * LaTeX reader:
-
-    + Replaced 'choice [(try (string ...), ...]' idiom with 'oneOfStrings',
-      for clarity.
-    + Added clauses for tilde and caret. Tilde is \ensuremath{\sim}, and
-      caret is \^{}, not \^ as before.
-    + Added parsing for \url.
-    + Parse \texttt{} as code, provided there's nothing fancy inside.
-
-  * HTML writer:
-
-    + Modified HTML writer to use the Text.XHtml library. This results
-      in cleaner, faster code, and it makes it easier to use Pandoc in
-      other projects, like wikis, which use Text.XHtml. Two functions are
-      now provided, writeHtml and writeHtmlString: the former outputs an
-      Html structure, the latter a rendered string. The S5 writer is also
-      changed, in parallel ways (writeS5, writeS5String).
-    + The Html header is now written programmatically, so it has been
-      removed from the 'headers' directory. The S5 header is still
-      needed, but the doctype and some of the meta declarations have
-      been removed, since they are written programatically. This change
-      introduces a new dependency on the xhtml package.
-    + Fixed two bugs in email obfuscation involving improper escaping
-      of '&' in the `<noscript>` section and in `--strict` mode. Resolves
-      Issue #9.
-    + Fixed another bug in email obfuscation: If the text to be obfuscated
-      contains an entity, this needs to be decoded before obfuscation.
-      Thanks to thsutton for the patch. Resolves Issue #15.
-    + Changed the way the backlink is displayed in HTML footnotes.
-      Instead of appearing on a line by itself, it now generally
-      appears on the last line of the note.  (Exception:  when the
-      note does not end with a Plain or Para block.) This saves space
-      and looks better.
-    + Added automatic unique identifiers to headers:
-      - The identifier is derived from the header via a scheme
-        documented in README.
-      - WriterState now includes a list of header identifiers and a table
-        of contents in addition to notes.
-      - The function uniqueIdentifiers creates a list of unique identifiers
-        from a list of inline lists (e.g. headers).
-      - This list is part of WriterState and gets consumed by blockToHtml
-        each time a header is encountered.
-    + Include CSS for .strikethrough class in header only if strikethrough
-      text appears in the document.
-    + If the 'strict' option is specified, elements that do not appear in
-      standard markdown (like definition lists) are passed through as
-      raw HTML.
-    + Simplified treatment of autolinks, using pattern matching instead of
-      conditionals.
-
-  * Markdown writer:
-
-    + Links in markdown output are now printed as inline links by default,
-      rather than reference links.  A --reference-links option has been added
-      that forces links to be printed as reference links.  Resolves Issue #4.
-    + Use autolinks when possible.  Instead of `[site.com](site.com)`,
-      use `<site.com>`.
-
-  * LaTeX writer:
-
-    + Rewrote to use the State monad. The preamble now includes only those
-      packages that are actually required, given the document's content.
-      Thus, for example, if strikeout is not used, ulem is not required.
-      Modified LaTeXHeader accordingly.
-    + Modified LaTeX writer to insert '\,' between consecutive quotes.
-    + Removed unused function tableRowColumnWidths.
-    + Simplified code for escaping special characters.
-    + Leave extra blank line after \maketitle.
-    + Include empty '\author{}' when no author specified to avoid LaTeX
-      errors.
-    + Include fancyvrb code in header only if needed -- that is, only
-      if there is actually code in a footnote.
-    + Use \url{} for autolinks.
-    + Include [mathletters] option in ucs package, so that basic unicode
-      Greek letters will work correctly.
-
-  * RST writer:  Force blank line before lists, so that sublists will
-    be handled correctly.
-
-  * Docbook writer:  Fixed a bug:  email links with text, like
-    [foo](me@bar.baz), were being incorrectly treated as autolinks.
-
-  * Removed Text.ParserCombinators.Pandoc and moved all its functions to
-    Text.Pandoc.Shared.
-
-  * Text.Pandoc.Shared:
-
-    + Added defaultWriterOptions.
-    + Added writerTableOfContents to WriterOptions.
-    + Added writerIgnoreNotes option to WriterOptions.  This is needed
-      for processing header blocks for a table of contents, since notes on
-      headers should not appear in the TOC.
-    + Added prettyprinting for native Table format.
-    + Removed some unneeded imports.
-    + Moved escape and nullBlock parsers from
-      Text.ParserCombinators.Pandoc, since the latter is for
-      general-purpose parsers that don't depend on Text.Pandoc.Definition.
-    + Moved isHeaderBlock from Text.Pandoc.Writers.HTML.
-    + Moved Element, headerAtLeast, and hierarchicalize from Docbook
-      writer, because HTML writer now uses these in constructing a table
-      of contents.
-    + Added clauses for new inline elements (Strikeout, Superscript,
-      Subscript) to refsMatch.
-    + Removed backslashEscape; added new functions escapeStringUsing and
-      backslashEscapes.
-    + Moved failIfStrict from markdown reader, since it is now used also
-      by the HTML reader.
-    + Added a 'try' to the definition of indentSpaces.
-    + In definition of 'reference', added check to make sure it's not a note
-      reference.
-    + Added functions: camelCaseToHyphenated, toRomanNumeral,
-      anyOrderedListMarker, orderedListmarker, orderedListMarkers,
-      charsInBalanced', withHorizDisplacement, romanNumeral
-    + Fixed a bug in the anyLine parser. Previously it would parse an empty
-      string "", but it should fail on an empty string, or we get an error
-      when it is used inside "many" combinators.
-    + Removed followedBy' parser, replacing it with the lookAhead parser from
-      Parsec.
-    + Added some needed 'try's before multicharacter parsers, especially in
-      'option' contexts.
-    + Removed the 'try' from the 'end' parser in 'enclosed', so that
-      'enclosed' behaves like 'option', 'manyTill', etc.
-    + Added lineClump parser, which parses a raw line block up to and
-      including any following blank lines.
-    + Renamed parseFromStr to parseFromString.
-    + Added a 'try' to the 'end' parser in 'enclosed'.  This makes errors in
-      the use of 'enclosed' less likely. Removed some now-unnecessary 'try's
-      in calling code.
-    + Removed unneeded 'try' in blanklines.
-    + Removed endsWith function and rewrote calling functions to use
-      isSuffixOf instead.
-    + Added >>~ combinator.
-    + Fixed bug in normalizeSpaces:  Space:Str "":Space should compress to
-      Space.
-
-  * Refactored runtests.pl; added separate tests for tables.
-
-  * Shell scripts:
-
-    + Added -asxhtml flag to tidy in html2markdown. This will
-      perhaps help the parser, which expects closing tags.
-    + Modified markdown2pdf to run pdflatex a second time if --toc or
-      --table-of-contents was specified; otherwise the table of
-      contents won't appear.
-    + Modified markdown2pdf to print a helpful message if the 'ulem'
-      LaTeX package is required and not found.
-
-  * Changes to build process:
-
-    + Dropped support for compilation with GHC 6.4.  GHC 6.6 or higher
-      is now required.
-    + Removed cabalize and Pandoc.cabal.in. The repository now contains
-      pandoc.cabal itself.
-    + Pandoc.cabal has been changed to pandoc.cabal, because HackageDB
-      likes the cabal file to have the same name as the tarball.
-    + Expanded and revised the package description in pandoc.cabal.
-      Revised the package synopsis.
-    + The tarball built by 'make tarball' now contains files built from
-      templates (including man pages and shell scripts), so pandoc can
-      be built directly using Cabal tools, without preprocessing.
-    + Executable binaries are now stripped before installing.
-    + Man pages are now generated from markdown sources, using pandoc's
-      man page writer.
-    + Use HTML version of README (instead of RTF) in Mac OS X installer.
-    + Instead of testing for the existence of a pandoc symlink in build-exec,
-      use ln -f.
-
-  * Documentation:
-
-    + Updated README and man pages with information on new features.
-    + Updated INSTALL instructions with some useful clarifications and
-      links.
-    + Updated web content.
-
-  * Added FreeBSD port.
-
-  [ Recai Oktaş ]
-
-  * debian/control:
-
-    + Changed pandoc's Build-Depends to include libghc6-mtl-dev and
-      libghc6-xhtml-dev.  Removed libghc6-html-dev.
-    + Suggest texlive-latex-recommended | tetex-extra instead of
-      tetex-bin.  This brings in fancyvrb and unicode support.
-
- -- Recai Oktaş <roktas@debian.org>  Tue, 16 Jan 2007 00:37:21 +0200
-
-pandoc (0.3) unstable; urgency=low
-
-  [ John MacFarlane ]
-
-  * Changes in pandoc options:
-
-    + Allow options to follow or precede arguments.
-    + Changed '--smartypants' to '--smart' and adjusted symbols accordingly.
-    + Added '--strict' option.
-    + Added '-o/--output' option.
-    + Added '--dump-args' and '--ignore-args' options (for use in wrappers).
-    + Modified '-v' and '-h' output to go to STDERR, not STDOUT, and return
-      error conditions.  This is helpful for writing wrappers.
-    + Added copyright message to '-v' output, modeled after FSF messages.
-    + Reformatted usage message so that it doesn't wrap illegibly.
-    + Removed extra blanks after '-h' and '-D' output.
-
-  * Added docbook writer.
-
-  * Added implicit setting of default input and output format based
-    on input and output filename extensions.  These defaults are
-    overridden if explicit input and output formats are specified using
-    '-t', '-f', '-r', or '-w' options.  Documented in pandoc(1) man page
-    and README.
-
-  * Allow ordered list items to begin with (single) letters, as well
-    as numbers.  The list item marker may now be terminated either by
-    '.' or by ')'.  This extension to standard markdown is documented
-    in README.
-
-  * Revised footnote syntax.  (See README for full details.)  The
-    '[^1]' format now standard in markdown extensions is supported,
-    as are inline footnotes with this syntax: `^[My note.]`.
-    The earlier footnote syntax `^(1)` is no longer supported.
-
-  * Improved HTML representation of footnotes.  All footnotes
-    are now auto-numbered and appear in an ordered list at the
-    end of the HTML document.  Since the default appearance is now
-    acceptable, the old footnote styles have been removed from the
-    HTML header.
-
-  * Bug fixes:
-
-    + Fixed a serious bug in the markdown, LaTeX, and RST readers.
-      These readers ran 'runParser' on processed chunks of text to handle
-      embedded block lists in lists and quotation blocks.  But then
-      any changes made to the parser state in these chunks was lost,
-      as the state is local to the parser.  So, for example, footnotes
-      didn't work in quotes or list items.  The fix:  instead of calling
-      runParser on some raw text, use setInput to make it the input, then
-      parse it, then use setInput to restore the input to what it was
-      before.  This is shorter and more elegant, and it fixes the problem.
-    + Fixed bug in notFollowedBy' combinator (adding 'try' before
-      'parser').  Adjusted code that uses this combinator accordingly.
-    + Fixed bug in RTF writer that caused improper indentation on
-      footnotes occurring in indented blocks like lists.
-    + Fixed parsing of metadata in LaTeX reader.  Now the title, author,
-      and date are parsed correctly.  Everything else in the preamble
-      is skipped.
-    + Modified escapedChar in LaTeX reader to allow a '\' at the end of a
-      line to count as escaped whitespace.
-    + Modified LaTeX reader to produce inline links rather than reference
-      links.  Otherwise, links in footnotes aren't handled properly.
-    + Fixed handling of titles in links in Markdown reader, so that
-      embedded quotation marks are now handled properly.
-    + Fixed Markdown reader's handling of embedded brackets in links.
-    + Fixed Markdown reader so that it only parses bracketed material
-      as a reference link if there is actually a corresponding key.
-    + Revised inline code parsing in Markdown reader to conform to
-      markdown standard.  Now any number of `s can begin inline code,
-      which will end with the same number of `s.  For example, to
-      have two backticks as code, write ``` `` ```.  Modified Markdown
-      writer accordingly.
-    + Fixed bug in text-wrapping routine in Markdown and RST writers.
-      Now LineBreaks no longer cause wrapping problems.
-    + Supported hexadecimal numerical entity references as well as
-      decimal ones.
-    + Fixed bug in Markdown reader's handling of underscores and other
-      inline formatting markers inside reference labels:  for example,
-      in '[A_B]: /url/a_b', the material between underscores was being
-      parsed as emphasized inlines.
-    + Changed Markdown reader's handling of backslash escapes so that
-      only non-alphanumeric characters can be escaped.  Strict mode
-      follows Markdown.pl in only allowing a select group of punctuation
-      characters to be escaped.
-    + Modified HTML reader to skip a newline following a `<br>` tag.
-      Otherwise the newline will be treated as a space at the beginning
-      of the next line.
-
-  * Made handling of code blocks more consistent.  Previously, some
-    readers allowed trailing newlines, while others stripped them.
-    Now, all readers strip trailing newlines in code blocks. Writers
-    insert a newline at the end of code blocks as needed.
-
-  * Modified readers to make spacing at the end of output more consistent.
-
-  * Minor improvements to LaTeX reader:
-
-    + '\thanks' now treated like a footnote.
-    + Simplified parsing of LaTeX command arguments and options.
-      commandArgs now returns a list of arguments OR options (in
-      whatever order they appear).  The brackets are included, and
-      a new stripFirstAndLast function is provided to strip them off
-      when needed.  This fixes a problem in dealing with \newcommand
-      and \newenvironment.
-
-  * Revised RTF writer:
-
-    + Default font is now Helvetica.
-    + An '\f0' is added to each '\pard', so that font resizing works
-      correctly.
-
-  * Moved handling of "smart typography" from the writers to the Markdown
-    and LaTeX readers.  This allows great simplification of the writers
-    and more accurate smart quotes, dashes, and ellipses.  DocBook can
-    now use `<quote>`.  The '--smart' option now toggles an option in
-    the parser state rather than a writer option.  Several new kinds
-    of inline elements have been added: Quoted, Ellipses, Apostrophe,
-    EmDash, EnDash.
-
-  * Changes in HTML writer:
-
-    + Include title block in header even when title is null.
-    + Made javascript obfuscation of emails even more obfuscatory,
-      by combining it with entity obfuscation.
-
-  * Changed default ASCIIMathML text color to black.
-
-  * Test suite:
-
-    + Added --strip-trailing-cr option to diff in runtests.pl, for
-      compatibility with Windows.
-    + Added regression tests with footnotes in quote blocks and lists.
-
-  * Makefile changes:
-
-    + osx-pkg target creates a Mac OS X package (directory). New osx
-      directory contains files needed for construction of the package.
-    + osx-dmg target creates a compressed disk image containing the package.
-    + win-pkg target creates Windows binary package.
-    + tarball target creates distribution source tarball.
-    + website target generates pandoc's website automatically, including
-      demos.  New 'web' directory containts files needed for construction
-      of the website (which will be created as the 'pandoc' subdirectory
-      of 'web').
-    + Makefile checks to see if we're running Windows/Cygwin; if so,
-      a '.exe' extension is added to each executable in EXECS.
-
-  * Removed all wrappers except markdown2pdf and html2markdown.
-
-  * Added new wrapper hsmarkdown, to be used as a drop-in replacement
-    for Markdown.pl.  hsmarkdown calls pandoc with the '--strict'
-    option and disables other options.
-
-  * Added code to html2markdown that tries to determine the character
-    encoding of an HTML file, by parsing the "Content-type" meta tag.
-
-    + If the encoding can't be determined, then if the content is local,
-      the local encoding is used; if it comes from a URL, UTF-8 is used
-      by default.
-    + If input is from STDIN, don't try to determine character encoding.
-    + Encoding can be specified explicitly using '-e' option.
-
-  * Improved warning messages in wrappers:
-
-    + Print warning if iconv not available
-    + More user-friendly error messages in markdown2pdf, when
-      pdflatex fails.
-
-  * Code cleanup:
-
-    + Renamed 'Text/Pandoc/HtmlEntities' module to
-      'Text/Pandoc/Entities'. Also changed function names so as
-      not to be HTML-specific.
-    + Refactored SGML string escaping functions from HTML and Docbook
-      writers into Text/Pandoc/Shared.  (escapeSGML, stringToSGML)
-    + Removed 'BlockQuoteContext' from ParserContext, as it isn't
-      used anywhere.
-    + Removed splitBySpace and replaced it with a general, polymorphic
-      splitBy function.
-    + Refactored LaTeX reader for clarity (added isArg function).
-    + Converted some CR's to LF's in src/ui/default/print.css.
-    + Added license text to top of source files.
-    + Added module data for haddock to source files.
-    + Reformatted code for consistency.
-
-  * Rewrote documentation and man pages.  Split README into INSTALL
-    and README.
-
-  * Split LICENSE into COPYING and COPYRIGHT.
-
-  * Removed TODO, since we now maintain ToDo on the wiki.
-
-  * Made COPYRIGHT in top level a symlink to debian/copyright, to avoid
-    duplication.
-
-  [ Recai Oktaş ]
-
-  * Revamped build process to conform to debian standards and created
-    a proper debian package.  Closes: #391666.
-
-  * Modified build process to support GHC 6.6.
-
-    + The package can still be compiled using GHC 6.4.2, though because
-      of dependencies the "make deb" target works only with GHC 6.6+.
-    + The script 'cabalize' is used to create an appropriate
-      'Pandoc.cabal' from 'Pandoc.cabal.in', depending on the GHC and
-      Cabal versions.
-
-  * Refactored template processing (fillTemplates.pl).
-
-  * Modified wrapper scripts to make them more robust and portable.
-    To avoid code duplication and ensure consistency, wrappers are
-    generated via a templating system from templates in src/wrappers.
-
-    + Wrappers now accept multiple filenames, when appropriate.
-    + Spaces and tabs allowed in filenames.
-    + getopts shell builtin is used for portable option parsing.
-    + Improved html2markdown's web grabber code, making it more robust,
-      configurable and verbose.  Added '-e', '-g' options.
-
- -- Recai Oktaş <roktas@debian.org>  Fri, 05 Jan 2007 09:41:19 +0200
-
-pandoc (0.2) unstable; urgency=low
-
-  * Fixed unicode/utf-8 translation
-
- -- John MacFarlane <jgm@berkeley.edu>  Mon,  14 Aug 2006 00:00:00 -0400
-
-pandoc (0.1) unstable; urgency=low
-
-  * Initial creation of debian package
-
- -- John MacFarlane <jgm@berkeley.edu>  Mon,  14 Aug 2006 00:00:00 -0400
diff --git a/changelog.md b/changelog.md
new file mode 100644
--- /dev/null
+++ b/changelog.md
@@ -0,0 +1,29619 @@
+# Revision history for pandoc
+
+## pandoc 3.10 (2026-06-03)
+
+  * Add `--typst-input` CLI option (#11588). This allows one to
+    pass parameters to typst, which are available at `sys.inputs`,
+    just as `typst` itself does with its `--input` option.
+
+  * Avoid trailing spaces in `--help` output (#11623).
+
+  * Make groff the default pdf-engine for `ms` output (#11558).
+    Formerly it was pdfroff.
+
+  * Set default User-Agent request header to `pandoc/VERSION`.
+    This can be overridden using the `--request-header` option.
+
+  * Markdown reader:
+
+     + Allow grid tables to be indented (#11671, Johan Larsson). Like
+      the other table syntaxes (pipe, simple, and multiline tables)
+      and block-level constructs generally, a grid table may now be
+      indented by up to three spaces and still be recognized as a
+      table. Previously the grid-table parser required the table to
+      begin at the left margin, so an indented grid table was parsed
+      as a paragraph.
+    + Fix calculation of column widths for default columns in grid tables
+      (#11664). This fixes a bug which produced too-narrow columns in some
+      cases.
+    + Don't produce empty Raw element with `--strip-comments` (#11625).
+    + Fix quotes in inline notes (#11613, Andrew Dunning).
+    + Allow spaces inside attributes in super/sub (#11589).
+    + Simplify `checkNotes`, remove dead code
+    + Various small performance optimizations.
+
+  * HTML reader:
+
+    + Parse aside as a Div with class "aside" (instead of using
+      raw HTML) (#11626).
+    + Add "header" class to Divs created from headers.
+
+  * Docx reader:
+
+    + Fix bug in bitmask checking (#8299). This led to some table rows
+      being wrongly considered header rows.
+    + Improve treatment of `tblHeader` element (#8299).
+      If `tblHeader` exists but has `w:val="0"`, then don't consider
+      the element a header.
+    + With `citations` extension, prefer `citation-key` as the key for
+      item data, if it is defined (#11581; cf. #10366, #11567). The `id` key
+      used by Zotero is not exposed by their API and is generally not what
+      is wanted when converting to biblatex.
+    + Don't look to `ext` tags for image extent (#11580).
+      This reverts a change from 7ff1b798c4e6681ef9050899442d80883116573a.
+      The change was mistaken and could cause images to be parsed with
+      the wrong sizes.
+
+  * Man reader:
+
+    + Support `auto_identifiers`, `gfm_auto_identifiers`, and
+      `ascii_identifiers` extensions (#8852, Meher Chaitanya).
+      Section headings parsed from .SH and .SS macros now receive
+      auto-generated id attributes when the extension is enabled (as
+      it is by default). This enables `--toc` to produce working anchor links.
+    + Better handling of `.TP` macro (#11668). We parse these as
+      DefinitionList items, but we previously sometimes stopped prematurely
+      in including material in the definition.  We should include everything
+      until we hit a new indentation-changing macro.
+
+  * Roff reader:
+
+    + Handle `\` line continuation in table cells (#11635).
+
+  * LaTeX reader:
+
+    + Evaluate theorem name when used rather than evaluating it when
+      the `\newtheorem` command is encountered (#11608). It may include
+      macros only defined later.
+    + Put identifier from label on table attributes rather than adding
+      an enclosing Div (#11604).
+
+  * Typst reader:
+
+    + Fix issue parsing figure inside rotate or box (#11598).
+    + Implement "rotate" as pass-through (#11531). Information about the
+      angle is encoded in an attribute of an enclosing span or div.
+
+  * RTF reader:
+
+    + Fix tables parsed as deeply nested tables (#11682).
+
+  * Docx writer:
+
+    + Fix display of paragraph with just inline math (#11674).
+      Word displays a paragraph containing just one inline math
+      element as if it were display math. We don't want that,
+      so we add a zero-width space to defeat this behavior.
+    + Fix FirstParagraph style lost after heading with footnote (#11573).
+    + Fix empty keywords in core document properties (#11666, Sai Asish Y).
+
+  * OpenDocument/ODT writer:
+
+    + Use predefined styles (#9316, #5086, #2747, #3426, #7336).
+      Previously the OpenDocument writer emitted a fresh automatic
+      style (L1..Ln, P1..Pn, T1..Tn) for nearly every list, list-item
+      paragraph, block quote, preformatted block, and inline text
+      style. This commit teaches the writer to reference the
+      predefined styles that LibreOffice ships and that pandoc's
+      reference.odt now exports:
+
+      - Bullet lists use `List_20_1`; ordered lists with default start and
+        decimal format use `Numbering_20_1`.  Non-default ordered lists
+        generate a single named override style (`Pandoc_Numbering_N`)
+        memoised by (ListNumberStyle, ListNumberDelim); a non-default start
+        value with the default format is expressed via `text:start-value`
+        on the `text:list` element instead of a new style.
+      - List-item paragraphs use `List_20_Bullet[_Tight]` and
+        `List_20_Number[_Tight]`.  The Tight variants are pandoc-specific
+        (zero top/bottom margin) and are injected into the user's
+        reference.odt if missing, just like the Skylighting token styles.
+      - Block quotes use the predefined `Quotations` paragraph style
+        directly.  Nested block quotes use a single automatic style that
+        inherits from Quotations and only adds extra margin-left, so a list
+        inside a block quote now inherits its container's indent (#2747).
+      - Preformatted blocks use `Preformatted_20_Text` directly.
+      - Emphasis, Strong, Strikeout, Subscript, Superscript and Code spans
+        use the predefined `Emphasis`, `Strong_20_Emphasis`, `Strikeout`,
+        `Subscript`, `Superscript` and `Source_20_Text` text styles.
+      - `paraStyle`/`paraStyleFromParent` no longer emit a wrapper automatic
+        style when its only attribute would be `parent-style-name`; the
+        parent name is returned directly.
+
+  * EPUB writer:
+
+    + Support multiple EPUB versions for raw content (#11628,
+      nibras shami). This change ensures that raw content marked `epub2`
+      will appear in (only) EPUBv2 output and content marked `epub3` will
+      appear in (only) EPUBv3 output.
+
+  * Typst writer:
+
+    + Add zero-width space before a Span label if otherwise the label
+      doesn't come after anything (#11568). (In this case typst will
+      raise an error.)
+    + Add newline after `#set text` directive (#11583). This ensures that
+      blocks such as lists are parsed correctly after a `set text`.
+
+  * LaTeX writer:
+
+    + Fix `fr-CA` babel language mapping (#11575, Christophe
+      Dervieux). Map fr-CA to `french` instead of deprecated `canadien`.
+      The babel-french package's `canadien.ldf` is deprecated and
+      broken: it never calls `\ldf@finish`, so `\bbl@main@language` is
+      left undefined, causing babel to crash at `\begin{document}`.
+      Since `canadien` was always just an unconditional alias for
+      `french`, use `french` directly.
+
+  * MediaWiki writer:
+
+    + Handle some technically malformed URLs (#11562).
+    + Fix escaping to avoid accidental lists (#11563).
+
+  * Markdown writer:
+
+    + Fix spacing issues with definition lists.
+      - Properly handle the case where the first item is an indented
+        code block (#11542).
+      - Use correct indentation when `four_space_rule` extension is
+        disabled.
+    + Escape `:::` to avoid triggering unintended divs (#11571).
+
+  * Man writer:
+
+   + Don't run together successive definitions in a tight definition list
+     with multiple definitions after a term (#11547).
+
+  * Text.Pandoc.Writers.Shared:
+
+    + `htmlAttrs`: use `data-` prefix when needed (#11680). This now
+      behaves like the HTML writer, adding the `data-` prefix for
+      custom attributes. This will affect, e.g., the mediawiki writer.
+
+  * Text.Pandoc.Error:
+
+    + Display IOError without stack trace (#11676).
+    + Use single quotes around paths and format names (#11645) in
+      displayed messages.
+
+  * Text.Pandoc.App.Opt:
+
+    + Opt has a new field `optTypstInputs` [API change].
+
+  * Text.Pandoc.Options:
+
+    + Change `defaultMathJaxURL` to use MathJax v4 (#11669).
+    + ReaderOptions has a new field `readerTypstInputs` [API change].
+
+  * Text.Pandoc.Citeproc.BibTeX:
+
+    + Prevent wrong combination of `subtitle` and `titleaddon` with
+      `maintitle` (#11677, Amir Dekel). When `maintitle` is present, `subtitle`
+      should not be added to `title`, but only to `volume-title`.
+    + BibLaTeX `inbook` should be CSL `book`, not `chapter` (#11552).
+    + Allow `doi` field in bibtex (input and output) (#11617, Thomas Hodson).
+
+  * Text.Pandoc.Translations:
+
+    + Find lang-script type translations (#11648).
+      E.g. for `zh-Hant-TW` look for (in order) `zh-Hant-TW.yaml`,
+      `zh-Hant.yaml`, `zh.yaml`.
+
+  * Text.Pandoc.Parsing:
+
+    + Various small optimizations.
+    + Fix bug in `extractIdClass` to ensure that both `id` and
+      `class` are stripped from key/value attributes..
+
+  * Text.Pandoc.Shared:
+
+    + Various small optimizations.
+
+  * ODT reference doc: demonstrate predefined styles (310327).
+    This mirrors the demonstration content already present in
+    the Word reference doc.
+
+  * HTML templates:
+
+    + Include pandoc-version in generator meta tag (#11624).
+    + Styles: make screen-only CSS conditional (#11524, Keenan Brock).
+
+  * EPUB templates:
+
+    + Add dir attribute to html element (#11554).
+
+  * LaTeX template: Define `\xmpquote` if not defined (#11528).
+    `\xmpquote` is defined by the hyperref driver hyperxmp; we need a
+    fallback for those who aren't using that.
+
+  * Lua subsystem:
+
+    + Add constructor `pandoc.TableBody`.
+
+  * doc/lua-filters.md: Re-indent definition list items
+    (Albert Krewinkel).
+
+  * wasm/index.js: include filter to embed images for pdf-via-typst.
+    Auto-inject `embed_images` filter for PDF via Typst. Otherwise
+    conversion fails because we can't write the images in a temporary
+    directory in the WASM sandbox. See jgm/pandoc#11584.
+
+  * Fix test suite parallel execution failures (#11566).
+
+  * linux/make_artifacts.sh: add `loong64` support (#11597,
+    Olivier Benz).
+
+  * `bash_completion.tpl`: add `groff` to `--pdf-engine` completions (#11555).
+
+  * MANUAL.txt:
+
+    + Improve description of reference links (#11643).
+    + Update instructions for modifying reference.docx
+      (#11600, Dan Jacobson). Mention LibreOffice as an alternative.
+    + Clarify indentation rules for definition lists (#11542).
+    + Move `--sandbox` to general options.
+    + Reword restrictions on YAML metadata in commonmark (#11561).
+
+  * Bump upper bound for time, tls, aeson.
+
+  * Use latest releases of doclayout, asciidoc, texmath, typst,
+    typst-symbols, pandoc-types, citeproc, commonmark, commonmark-pandoc,
+    commonmark-extensions.
+
+  * Add missing NAME heading to pandoc-lua, pandoc-server man pages (#11634).
+
+## pandoc 3.9.0.2 (2026-03-19)
+
+  * Typst template: fix regression introduced in 3.9.0.1 (#11538).
+
+## pandoc 3.9.0.1 (2026-03-17)
+
+  * WASM GUI:
+
+    + Don't block everything while pandoc.wasm loads.
+    + Fix bug with Unicode filenames (#11447).
+    + Catch errors loading pandoc.
+
+  * Docx reader:
+
+    + Recognize media inside textboxes (#11053, Raymond Berger).
+    + Properly handle media stored with packaged-rooted paths
+      such as `/media` (#11518).  This can be produced by the online version of Word.
+      With this change, media stored at an absolute path will be stored
+      with its original name and not given a SHA1-based name.
+    + Preserve non-textbox content when unwrapping textboxes (#11510, #6893,
+      #11412, #5394, #9633). Treat text inside a textbox containing an image
+      as a figure caption.
+    + Support `w:gridBefore` table row property (#11464, Jan Tojnar).
+
+  * Typst reader:
+
+    + Handle bibliography command (#11460). If this is present, a
+      bibliography section is added to the document and the bibliography
+      paths are added to `bibliography` in the metadata. This sets things
+      up for using `--citeproc`.
+
+  * Textile reader:
+
+    + Handle block content in cells (#11455).
+
+  * LaTeX reader:
+
+    + Support `\footnotemark` and `\footnotetext` (#11450).
+      These commands allow separating the footnote mark from its content, useful
+      in tables, minipages, and other contexts where \footnote cannot be used
+      directly.
+    + Support supertabular environment (#11523, bodigrim).
+
+  * ODT Reader:
+
+    + Fix relative linked images (#11369, Tuong Nguyen Manh).
+    + Recognize `Preformatted_20_Text` style Jan Tojnar
+      This is used by LibreOffice, and we will switch to that as well.
+    + Add block smushing logic (Jan Tojnar).
+    + Support Preformatted Text style (#4841, Jan Tojnar).
+
+  * Markdown reader:
+
+    + Fix bug with `lists_without_preceding_blankline` (#11534).
+
+  * Typst writer:
+
+    + Don't add a carriage return after `\` for hard break (#11446).
+      They are not necessary.  Note that they can still be included
+      if you use `--wrap=preserve` and add a newline in your source document.
+    + Improve handling of data: URIs in images. Instead of using an
+      SVG with a link containing the data URI (the solution of #10460),
+      we can now simply produce a `bytes` object with the requisite bytes.
+      Typst figures out the format automatically.
+    + Fix escaping of quotes (#11463).
+    + Include alt attributes on images (mcanouil).
+    + Properly escape `.` after bracketed argument (#11511).
+
+  * Docx writer:
+
+    + Don't depend on `extractTarget` from Docx reader.
+    + Fix section breaks with `--top-level-division` (#11482, #10578).
+
+  * EPUB writer:
+
+    + Add cover metadata for EPUB3 (#11479). This allows
+      file managers to show cover thumbnails for EPUB3 files as well.
+    + Update allowed values for EPUB3 metadata `identifier.scheme` (#11481,
+      Pascal Wagler).
+
+  * ODT writer:
+
+    + Rename inline source class to match LibreOffice (#3390, Jan Tojnar).
+      Rename the text style we use to represent `Code` inlines from
+      `Source_20_Text` to `Source_Text`. This is the same name LibreOffice
+      Writer uses so it will be recognized by the Character Styles section
+      of the Styles menu.
+    + Remove font size from inline source class (Jan Tojnar). This matches
+      what LibreOffice Writer is doing. Also fixes literals inside
+      headings being too small.
+    + Modernize `Preformatted Text` & `Source Text` styles (Jan Tojnar).
+      Presumably, `font-family-generic` and `font-pitch` will allow to find a
+      replacement on systems that do not have `Courier New`.
+
+  * Markdown writer:
+
+    + Fix rendering of alerts (#11479). We only properly handled the case
+      where the alert started with a paragraph, but it can start with a list
+      or other block type.
+    + Escape literal `&` that would trigger entity (#11490).
+
+  * HTML writer:
+
+    + For revealjs, default `scrollProgress` to `auto` (Christophe Dervieux).
+
+  * PPTX writer:
+
+    + Register content type for embedded fonts (#11492).
+
+  * MediaWiki writer:
+
+    + Use appropriate syntax for external images (#11494).
+      Note that they will only be rendered as images if an option
+      `$wgAllowExternalImages` is enabled in the MediaWiki instance.
+
+  * ICML writer:
+
+    + Support for image object styles (#11498, massifrg).
+      This change allows users to style images in InDesign bysetting the
+      `object-style` attribute in a pandoc Image, which is mapped to the
+      AppliedObjectStyle attribute in the Rectangle element around an Image
+      element in the resulting ICML.
+
+  * JATS writer:
+
+    + Improve representation of Divs (Albert Krewinkel).  The writer now
+      checks if the element used to represent (non-special) Divs has any
+      `<boxed-text>` specific attributes. If it does, the writer keeps
+      wrapping the Div contents in a `<boxed-text>`, as it did before.
+      Otherwise, the writer falls back to the more appropriate `<p>` element
+      or simply unwraps the Div if the wrapping element wouldn't have any
+      attributes. The new behavior gives better semantic results in most cases,
+      as `<boxed-text>` should be used for text that "is outside the flow of the
+      narrative text", which doesn't apply to most divs.
+      "Special" divs, like those used to mark sections, are not
+      affected by this change.
+
+  * Text.Pandoc.Writers.GridTable:
+
+    + Normalize tables (#8102). Previously, if an invalid table was passed to
+      `toTable`, an array index error could be raised. Normalizing the table
+      forces it into a shape that won't allow this error.
+
+  * Lua subsystem (Albert Krewinkel):
+
+    + Add new function `pandoc.types.Sources` (#11441).
+
+  * LaTeX template: properly handle keywords with commas.
+    These need to be put in an `\xmpquote{..}` command. Closes #11528.
+
+  * HTML styles template:  avoid duplicate code selector.
+    Consolidate two clauses. Closes #11484.
+
+  * Revealjs template: fix type rendering of scroll-view options
+    (Christophe Dervieux, #11486).
+
+  * Typst template:
+
+    + Use both place and block for title (Gordon Woodhull).
+      Otherwise the title will be confined to the left column
+    + Put title block in a conditional (#11529). This avoids an
+      empty block for documents that lack metadata information.
+      The empty block causes problems if `#set page` is used, as
+      it will cause a page break.
+
+  * Beamer template: add `logooption` variable (#11452, Sidney Mau).
+
+  * Text.Pandoc.ImageSize:
+
+    + Correctly handle percentage width, height on SVG (#11530).
+      Previously we were getting image size of 0 when a percentage
+      was specified for width or height on SVG.  With this change,
+      we simply ignore these percentages (becaues ImageSize doesn't
+      know the size of the containing element).
+
+  * Re-add `-threaded` to compile options in pandoc-cli.
+
+  * Use released djot, asciidoc, texmath, typst.
+
+  * Allow crypton 1.1, tls 2.2, http-client-tls 0.4.
+
+  * Require auto-update >= 0.2.6 to fix server on macOS (#11488).
+
+  * pandoc-cli.cabal: bump base min bound to 4.18 (same as pandoc).
+
+  * MANUAL.txt:
+
+    + Note that JSON may be used in YAML metadata blocks (#11525).
+    + Update link for ICML in manual.
+    + Fix outdated OPML spec URL in MANUAL.txt (#11504, Peter Briggs).
+
+## pandoc 3.9 (2026-02-03)
+
+  * Add support for compiling pandoc to WASM. (To build, `make
+    pandoc.wasm`.) A stanza in `cabal.project` contains the
+    necessary build modifications. We owe this almost entirely to
+    TerrorJack, who created the original proof of context and
+    came up with the necessary build flags and patches to some
+    dependencies.
+
+    `pandoc.wasm` has almost all the power of regular pandoc. The
+    main limitations is that it operates in a WASM sandbox and thus
+    cannot use HTTP to fetch resources and cannot run system commands.
+    As a result, JSON filters cannot be used, `--embed-resources`
+    works only with resources that have been explicitly provided in
+    the WASM sandbox, and PDFs cannot be produced (since that requires
+    running external commands). However, Lua filters can be used,
+    as long as they do not run system commands.
+
+    A JavaScript bridge module, `wasm/pandoc.js`, is provided; this
+    handles the setup necessary to run `pandoc.wasm` in a browser.
+
+    In addition, a full-featured GUI interface is provided in the
+    `wasm` subdirectory. `make serve` from that directory and it
+    will run locally, or visit <https://pandoc.org/app>.  Note that
+    once the relevant code has been downloaded by the browser, it runs
+    entirely in the browser, and the conversions never touch a server.
+    The GUI was developed in interaction with Claude Code.  This app
+    includes a WASM version of Typst and can produce PDF output via
+    Typst.
+
+  * Defaults files may now be either JSON or YAML (though a `.yaml`
+    extension will still be assumed if the file has no extension).
+    The structure of a JSON defaults file is isomorphic to that of
+    a YAML defaults file.
+
+  * Variable expansion now works even for the `defaults` field of
+    defaults files (#8024, Jacob Larkin).
+
+  * `--extract-media` will now create a zip archive containing the media
+    (instead of a directory) if the path provided has a `.zip` extension.
+
+  * Processing with `--citeproc` is now affected by a
+    `reset-citation-positions` class on headings. When the
+    `reset-citation-positions` class is added to a top-level
+    heading, `--citeproc` will reset position information at that
+    point in the document. This is needed in order to ensure that
+    the first citation in a chapter to a work that has been cited
+    in a previous chapter will not be in abbreviated form.
+
+  * RST reader:
+
+    + Fix definition lists where term ends with `-` (#11323).
+      This reverts some old code giving special treatment to
+      lines ending in hyphens; I don't understand why it was
+      there, because rst2html does not seem to do this.
+
+  * HTML reader:
+
+    + Revert an earlier change that caused style tags in the body
+      to be ignored (#10643, #11246).
+    + Parse inline style elements as RawInline (#10643, #11246).
+
+  * Markdown reader:
+
+    + Fix parsing of inline math (`$...$`) (#11311, benniekiss).
+      Do not allow blank lines before closing `$` delimiter. This brings the
+      parser in line with the documentation.
+    + Allow superscripted spans (#11409). These were being parsed as inline
+      notes. Now we disallow an inline note followed by
+      attributes, as this is almost certainly meant to be a span.
+    + Support `alerts` extension for pandoc markdown (#9716). It is not
+      enabled by default.
+
+  * MediaWiki reader:
+
+    + Add behavior switches support (#11354, Anton Melnikov).
+      They add a field to metadata without producing any text.
+    + Handle non-recognized tags as plain text (#11299).
+    + Better handling of inline tags (#11299). `<mark>`, `<var>`,
+      `<samp>`, and `<kbd>` now produce Code or Span elements with
+      classes, which can be handled by multiple output formats,
+      instead of simply being parsed as raw HTML tags.
+
+  * RTF reader:
+
+    + Ensure a new paragraph on `\pard` (#11361, Tuong Nguyen Manh). New
+      paragraphs may start with `\pard` alone without an explicit paragraph
+      break with `\par` preceding it.
+    + Improve hyperlink parsing more (#10942, Tuong Nguyen Manh).
+      Both the field instruction and its result may be ungrouped.
+    + Fix bug where list items were incorporated into a following table
+      (#11364).
+
+  * ODT reader:
+
+    + Add table row and column spans (#11366, Tuong Nguyen Manh).
+      Parse the number-rows-spanned and number-columns-spanned attributes to
+      create Cells for the Table.
+
+  * DocBook reader:
+
+    + Support "role" attribute (#11255, Yann Trividic). The `role`
+      attribute is parsed and added to Pandoc AST elements, using a
+      wrapper Div if needed.
+    + Omit empty title when not required (#11422).
+      This affects example and sidebar elements.
+    + Fix adding wrong metadata (#11300, Tuong Nguyen Manh). Now
+      keep track of the current element stack to only add metadata
+      if inside an appropriate parent element.
+
+  * DocBook/JATS reader:
+
+    + Don't export surrounding space from inline elements (#11398). Previously
+      we would export leading and trailing space inside elements like
+      emphasis or ulink so they appeared outside the resulting pandoc Inline
+      (Emph or Link). This is not really motivated; DocBook and XML in general
+      treats leading and trailing whitespace in this context as significant.
+
+  * Docx reader:
+
+    + Handle tables without `tblGrid` (#11380).
+    + Look inside v:rect as well as v:shape (#11412).
+
+  * LaTeX reader:
+
+    + Handle more quote macros from fontspec and ngerman babel (#6120).
+
+  * Org reader:
+
+    + Don't include 'example' class when parsing org example blocks (#11339).
+      These are just unmarked code blocks.
+
+  * Texinfo writer:
+
+    + Improve handling of certain code blocks (#11312).
+      MediaWiki, for example, will parse a code block containing
+      formatting as a sequence of Code elements separated by
+      LineBreaks. For this we now use a texinfo example block.
+
+  * Typst writer:
+
+    + Escape hyphens when needed (#11334).
+
+  * HTML writer:
+
+    + Include all classes on highlighted code elements (#11423). Previously,
+      only the language class was included, and the others were dropped.
+    + Slide formats: Make `. . .` pause work in nested blocks (#7201, #7582).
+    + For revealjs, add idiomatic highlight.js support (#11420, Claude Opus 4.5).
+      When using `--syntax-highlighting=idiomatic` with reveal.js output, pandoc
+      now generates HTML compatible with reveal.js's built-in highlight.js plugin:
+      Code blocks use `<pre><code class="language-X">` format.
+      The template loads highlight.js CSS, JS, and RevealHighlight plugin.
+
+  * Markdown writer:
+
+    + Ensure that `\ ` line breaks are used for commonmark.
+    + Use setext for headers containing line breaks for commonmark (#11341).
+    + Allow display math to start/end with space (#11384).
+      This reverts to earlier < 3.7 behavior.
+    + Properly handle tables with footers (#11416).
+
+  * JATS writer:
+
+    + Fix XML output for nested figures (#11362, Albert Krewinkel).
+      Subfigures are now wrapped inside a `<fig-group>` element. Furthermore,
+      figure content that isn't allowed as children of `<fig>` elements, such as
+      raw text, gets wrapped in `<p>` elements to ensure schema-conforming XML.
+
+  * AsciiDoc writer:
+
+    + Use doubled delims in more contexts (#11362). Also escape the `#` character.
+    + Use a span with role for SmallCaps (#11374).
+    + Export spaces inside delimited constructs like emph.
+
+  * Docx writer:
+
+    + Skip directory entries when building media overrides (#11379, You Jiangbin).
+      Pandoc's docx writer was previously adding an `<Override>` for
+      `/word/media/` in `[Content_Types].xml` when the reference doc contains
+      media, which violates OPC rules and causes Word to report corruption.
+    + Refactor the monolithic `writeDocx` into a number of smaller functions
+      (Claude Opus 4.5).
+    + Replace generic XML traversal with direct path navigation (Claude
+      Opus 4.5). Instead of using Data.Generics `everywhere` to traverse the
+      entire XML tree when setting language attributes, navigate directly to
+      the known path `w:docDefaults/w:rPr/w:lang`. This is more efficient and
+      removes the dependency on `Data.Generics`.
+
+  * EPUB writer:
+
+    + Don't use footnote backlinks for EPUBv3. Here we use aside elements,
+      which are popups, and the backlinks are not needed; in some readers
+      they cause a redundant number to appear, since the reader adds a note number.
+
+  * MediaWiki writer:
+
+    + Use Doc Text instead of Text for document construction (with Claude Open 4.5).
+      This refactors the writer to use Text.DocLayout combinators (vcat, hcat,
+      literal, blankline, cr, chomp) for building output, following the pattern
+      used by other text format writers (RST, Markdown, Man). This enables
+      better control over line spacing and paragraph separation.
+    + Improve blank space around div elements (#11417). This is merely cosmetic.
+
+  * PPTX writer:
+
+    + Support notes field in metadata for title slide (#5844, Chris Callison-Burch).
+      This adds support for a `notes` field in the YAML metadata block that will
+      be used as speaker notes for the title slide in PowerPoint output.
+      Previously, there was no way to add speaker notes to the title slide since
+      it is generated from metadata rather than from content blocks.
+
+  * LaTeX writer:
+
+    + Add PDF standard support via DocumentMetadata (#11407, Gordon Woodhull
+      with Claude Opus 4.5). The `pdfstandard` variable can be
+      used to specify PDF standards (PDF/A, PDF/X, PDF/UA) in
+      LaTeX output. This uses LaTeX's `\DocumentMetadata`
+      command, which requires LuaLaTeX. PDF version requirements
+      are automatically inferred, but can be explicitly overridden.
+      Automatic tagging is added for standards that require it.
+
+  * Typst template:
+
+    + Fix keywords usage. (#11317, har7an).
+    + Disable hyphenation for title, subtitle (#11375).
+    + Improve accessibility of definition lists (#11436). Before this
+      change, our show rule produced an error when typst was run with
+      `--pdf-standard=ua1`.
+
+  * HTML5 template:
+
+    + Conditionally include lang attribute, instead of providing
+      it with an empty value.
+
+  * JATS template:
+
+    + Fix author prefix placeholder (#11381, Christophe Dervieux).
+
+  * Text.Pandoc.Citeproc:
+
+    + Fix biblatex parsing of `@commentary` entries (#11322).
+    + Fix typo affecting `jurisdiction` biblatex type (#11321).
+    + Avoid adding an extra space at the beginning of a Cite.
+
+  * Text.Pandoc.Shared:
+
+    + Export `hasLineBreaks` [API change]. This was formerly
+      defined in the DocBook writer but more generally useful.
+
+  * Text.Pandoc.PDF:
+
+    + Add `SOURCE_DATE_EPOCH` to verbose environment variable info.
+
+  * Text.Pandoc.Class:
+
+    + Factor out `openURL` into Text.Pandoc.Class.IO.HTTP (unexported module).
+
+  * Lua subsystem (Albert Krewinkel):
+
+    + Mark readers and writers with their types (#11367). The
+      `pandoc.readers` and `pandoc.writers` maps now have string values
+      instead of boolean values. The string signals the type of the
+      reader/writer, `"text"` for TextReader/TextWriter and `"bytestring"`
+      for ByteStringReader/ByteStringWriter.
+    + Support equallity checks of LogMessage objects.
+    + Add function `pandoc.with_state` (#10859). The function allows
+      to run a callback with a modified pandoc state. This provides
+      the ability to temporarily modify the resource path, the user
+      data directory, and the HTTP request headers.
+    + Let `pandoc.with_state` error on unknown options (#11376).
+    + Add function `pandoc.utils.documentation` (#10999).
+      This is now used to generate much of the Lua API documentation.
+
+  * Text.Pandoc.App:
+
+    + Remove redundant check for asciidoc in UnknownReader.
+
+  * Text.Pandoc.Logging:
+
+    + Add `pretty` field to ToJSON instance for LogMessage.
+      This just reproduces the output of `logMessage`, for convenience for those
+      who are using the JSON output outside of Haskell.
+
+  * Text.Pandoc.Error:
+
+    + Change PandocHttpError constructor to take a Text instead of an
+      HttpException as the second argument (see #10980) [API change]
+      Motivation: exposing HttpException in the public API makes it
+      difficult to provide a version of pandoc that can be compiled
+      to wasm, which currently can't handle the network libraries.
+    + Define `displayException` for PandocError. This is a behavior change,
+      not an API change, since there was already a definition that defaulted
+      to using Show. The change here is that we use `renderError` for
+      a more human-readable version.
+
+  * Drop support for compilation with GHC versions < 9.6.
+
+  * Use released citeproc 0.13, djot 0.1.3, skylighting-format-blaze-html
+    0.1.2 (see #11423), texmath 0.13.1, asciidoc 0.1.0.1, typst-0.9,
+    hslua 2.5.
+
+  * Add `-Wno-deriving-typeble` to cabal ghc-options for ghc >= 9.12.
+
+  * Add `http` cabal flag (#10980). This allows pandoc to be
+    compiled without support for making HTTP requests, which is
+    useful when WASM is the target.
+
+  * pandoc-lua-engine has a new build flag `repl`, allowing support
+    for the Lua repl to be disabled for the wasm build.
+
+  * We now sign Windows artifacts with a code signing
+    certificate provided by SignPath.
+
+  * Mention Excel in cabal description.
+
+  * Makefile: remove some obsolete targets.
+
+  * MANUAL.txt:
+
+    + Fix typo about `--chunk-template` (#11358, Albert Lei).
+    + Fix link for bbcode_steam (#11389).
+    + Small rewrite of syntax-highlighting info.
+    + Fix defaults.yaml example for `wrap`.
+
+  * Fix a few mistakes in the contributing docs. (#11318, har7an).
+
+  * Fix a couple small errors in `doc/lua-filters.md`,
+    `doc/custom-writers.md`, and `doc/custom-readers.md`
+    (#11408, #11388).
+
+## pandoc 3.8.3 (2025-12-01)
+
+  * Add `asciidoc` as an input format (#1456).
+
+  * Add `xlsx` (Microsoft Excel) as an input format (Anton Antich).
+    Each worksheet turns into a section containing a table.
+
+  * Add `pptx` (PowerPoint) as new input format (Anton Antich).
+
+  * Add `bbcode` as a new output format (#11242, reptee). Several variants
+    of BBCode are also supported: `bbcode_fluxbb` (FluxBB), `bbcode_phpbb`
+    (phpBB), `bbcode_steam` (Hubzilla), `bbcode_hubzilla` (Hubzilla),
+    and `bbcode_xenforo` (xenForo).
+
+  * New exported module Text.Pandoc.Readers.AsciiDoc,
+    exporting `readAsciiDoc` [API change].
+
+  * New module `Text.Pandoc.Readers.Pptx`,
+    exporting `readPptx` (Anton Antich) [API change].
+
+  * New module `Text.Pandoc.Readers.Xlsx`,
+    exporting `readXlsx` (Anton Antich) [API change].
+
+  * LaTeX reader:
+
+    + Revert `\linebreak` as LineBreak (#11272). `\linebreak` is more
+      of a hint, it shouldn't produce a hard break.
+    + Better handling of `\makeatletter` in parsing raw LaTeX (#11270).
+    + Fix spurious paragraph breaks in math environments (#11265,
+      Emmanuel Ferdman). Previously, a math environment with extra
+      space before the `\end` would get rendered with a blank line,
+      which LaTeX treats as a paragraph break.
+    + Change type on `rawLaTeXParser` in Text.Pandoc.LaTeX.Parsing.
+      The preparser doesn't need to return a value.
+    + Fix `rawTeXParser` (#11253).  Make macro expansion in raw LaTeX
+      depend on the setting of the `latex_macros` extension.  Previously
+      macros were always expanded, even in raw TeX in markdown. In
+      addition, there was previously a bug that caused content to be
+      garbled in certain cases.
+    + Handle `ifstrequal` at a lower level, like the other `if`
+      commands (#11253).
+    + Move `ifstrequal`, `iftoggle`, etc., which were misplaced in
+      `environments`, to `blockCommands`, so these commands work properly.
+
+  * Docx reader:
+
+    + Handle REF link instruction (#11296, Ezwal).
+    + Check recursively for caption styles (Albert Krewinkel).
+      The docx reader uses caption styles to identify figures and
+      captioned tables. It now checks for known caption styles in the
+      full styles hierarchy of a paragraph instead of just checking
+      the style directly. This allows to recognize caption styles that
+      are built on top of the basic *caption* style, as is sometimes
+      the case in sophisticated styles.
+
+  * Markdown reader:
+
+    + Fix performance issue in links with `'` (#10880).
+
+  * Typst reader:
+
+    + Handle document metadata and `#title` (jgm/typst-hs#80).
+      Note that previously, the typst reader never returned document
+      metadata.  Now it does, even if the typst document does not contain
+      a `#title` function that would result in actually printing the
+      title block.
+
+  * Djot reader:
+
+    + Add Space elements (#11250). Previously we just got big
+      Str elements with spaces included. But many pandoc writers
+      assume that breakable spaces will be Space elements, and this
+      is also required for automatic wrapping.
+
+  * RST reader:
+
+    + Correctly handle intraword emphasis (#11309).
+
+  * Text.Pandoc.Readers:
+
+    + Export `readAsciiDoc`, `readXlsx`, `readPptx` [API change].
+
+  * New module Text.Pandoc.Writers.BBCode, exporting
+    `writeBBCode`,  `writeBBCodeSteam`, `writeBBCodeFluxBB`,
+    `writeBBCodePhpBB`, `writeBBCodeHubzilla`, `writeBBCodeXenforo`
+    [API change].
+
+  * LaTeX writer:
+
+    + Make level 1-3 headings work inside blockquotes (#11281, James Barlow).
+    + Remove `split` from list of math environments (#11274).
+    + Improve handling of math environments in tex math (#11266).
+
+  * HTML writer:
+
+    + Add reveal.js `scroll` and `scrollSnap` options to writer and
+      template (#10052, Asliddinbek Azizovich).
+    + Use 'defer' when including mathjax script, as recommended in
+      MathJax docs (#11292).
+
+  * ANSI writer:
+
+    + Apply row spans in tables (#10149, Tuong Nguyen Manh).
+      The ANSI writer is now able to keep track of row spans and apply
+      them in rows.
+
+  * Pptx writer:
+
+    + Handle reference doc without slides (#7536, Tuong Nguyen Manh).
+
+  * AsciiDoc writer:
+
+    + Add more table features (#11267, Tuong Nguyen Manh):
+      Row span and column span, footer row, individual horizontal
+      cell alignment.
+
+  * Typst template:
+
+    + Fix font for compatibility with typst 0.14, which doesn't
+      permit an empty array for `font` (#11238).
+    + Re-add `columns` to typst template (#11259), fixing a
+      pandoc 3.8 regression.
+    + Fix syntax for bibliography inclusion (#11233, Mickaël Canouil).
+      Previously the syntax was wrong when multiple bibliography files
+      were specified. Typst expects an array.
+
+  * Text.Pandoc.Writers:
+
+    + Export `writeBBCode`,  `writeBBCodeSteam`, `writeBBCodeFluxBB`,
+      `writeBBCodePhpBB`, `writeBBCodeHubzilla`, `writeBBCodeXenforo`
+      [API change].
+
+  * Text.Pandoc.Writers.Shared:
+
+    + Add functions `insertCurrentSpansAtColumn`, `takePreviousSpansAtColumn`
+      and `decrementTrailingRowSpans` for applying and keeping track of
+      RowSpans over multiple rows (#10149, Tuong Nguyen Manh). [API change]
+
+  * Text.Pandoc.Logging:
+
+    + Change message for missing HTML title warning (#11307). Suggest
+      setting the `pagetitle` variable instead of setting `title` in metadata.
+
+  * Lua subsystem:
+
+    + Preserve common state of custom Lua readers (Albert Krewinkel).
+      The common state is transferred to Lua when calling a custom Lua
+      reader, and is now also transferred back after the reader has
+      finished. This ensures that info messages, warnings, and
+      mediabag entries are available to the main program and all
+      subsequent processing steps.
+
+  * Text.Pandoc.PDF:
+
+    + Avoid converting SVG to PDF when non-TeX PDF engine is used (#11275).
+      This fixes a 3.8 regression, which caused documents with SVGs to
+      raise an error when converted to PDF using WeasyPrint.
+    + Fix a 3.8 regression with typst and smart quotes (#11256).
+      Before 3.8, the default behavior when producing a PDF `-t typst`
+      was to produce smart quotes according to typst's defaults.
+      (This could be defeated by specifying `-t typst-smart`.)
+      This behavior broke in 3.8 because of a change to Text.Pandoc.PDF.
+      This change caused `smart` to be disabled for all formats when
+      producing PDFs, when before it was only disable for TeX-based
+      formats (to avoid bad ligatures). This commit restores the old
+      behavior. Possibly the regression also other affects other
+      non-TeX formats, e.g. HTML.
+
+  * Text.Pandoc.Shared:
+
+    + Add functions `allRowsEmpty` and `tableBodiesToRows` from the
+      RST writer for reuse in other writers. (Tuong Nguyen Manh) [API
+      change].
+
+  * Text.Pandoc.Citeproc:
+
+    + Allow formatting in locator to be transmitted to citeproc.
+      We do this indirectly, by rendering the formatting using the
+      HTML tags that citeproc recognizes.  Fixes jgm/citeproc#68
+      and jgm/citeproc#163. Note that formatting is only possible for
+      locators given in the explicit form, surrounded by curly braces.
+      It won't work for implicit locators, since these expect
+      number-like expressions.
+
+  * New non-exported module Text.Pandoc.Readers.OOXML.Shared
+    containing functions factored out from
+    Text.Pandoc.Readers.Docx.Util (Anton Antich).
+
+  * Tests: The common file `nativeDiff` has been extracted from
+    the Docx and Pptx text files and put in Tests.Helpers.
+
+  * Use asciidoc 0.1, djot 0.1.2.4, texmath 0.13.0.2, typst 0.8.1,
+    citeproc 0.12.
+
+  * MANUAL.txt:
+
+    + Improve `implicit_figure` documentation (#11082).
+    + Give both forms of options when referring to them (#11306).
+
+  * Update INSTALL.md (#11271).
+
+## pandoc 3.8.2.1 (2025-10-20)
+
+  * HTML reader: allow blank space between open and close `iframe`.
+
+  * RTF reader: improve hyperlink parsing (#11211).
+
+  * Org reader:
+
+    + Parse parameter lists on unknown blocks (#11188, Albert
+      Krewinkel). The reader tries to parse the rest of the opening
+      line of a block, e.g., `#+begin_myblock …`, as a parameters
+      list. It first assumes that the parameters are in lisp-style
+      (`:key value`), then alternatively tries to read python-style
+      key-value pairs (`key=value`) and falls back to reading the
+      entire remaining line as a single `parameter` attribute.
+    + Add support for dynamic blocks.
+
+  * Docx writer: properly handle nested comment spans (#8189, #6959,
+    mourino).
+
+  * RST writer: Don't use simple tables with RowSpans (#11214,
+    Tuong Nguyen Manh).
+
+  * Typst writer: Escape open paren after non-space (#11210).
+    This fixes an issue that occurs if an open paren comes
+    right after e.g. `#strong[test]`.
+
+  * Typst template: ensure that title block is properly centered (#11221).
+
+  * LaTeX writer/template: small fix for unnumbered tables for
+    compatibility with older LaTeX installations (#11201).
+    Thanks to @priiduonu for the solution.
+
+  * MANUAL.txt: Fixed missing backtick (#11209, FoxChillz).
+
+  * Correct anchor references to `pandoc.text` module documentation (#11111,
+    Emmanuel Ferdman).
+
+  * Fixed golden test regeneration in Docx reader test.
+
+  * Allow unicode-data 0.8.
+
+  * Use citeproc 0.11. This fixes a significant performance
+    regression in pandoc 3.8, which was due to a rewrite of the
+    default chicago-author-date.csl file. Performance with `--citeproc`
+    is now on par with what we had in pandoc 3.7, even with the
+    revised Chicago styles.
+
+## pandoc 3.8.2 (2025-10-05)
+
+  * Markdown reader/writer: implement new `table_attributes` extension
+    (#10884). When `table_attributes` is enabled (as it is by default for
+    pandoc's Markdown), attributes can be attached to a table by
+    including them at the end of the caption. Previously the writer
+    would emit an identifier in this position, but the reader didn't
+    handle it. Now arbitrary attributes are allowed, and they work in
+    both the reader and writer.
+
+  * Typst writer: don't add superfluous semicolons (#11196).
+    Previously we added semicolons after inline commands not
+    followed by spaces, but mainly this was to deal with one issue:
+    the presence of a semicolon after an inline command, which
+    would be swallowed as a command separator (#9252).
+    This commits adopts an approach that should avoid so many
+    superfluous semicolons: it escapes semicolons that might come
+    right after a command.
+
+  * Typst template: fix 3.8 regression in which links disappear
+    (#11194). A template change in 3.8 added a show rule for links which
+    causes them to disappear except in special cases.
+
+  * Text.Pandoc.Parsing: rewrite `oneOfStrings` more efficiently.
+
+  * LaTeX writer: Fix strikeout in links (#11192, Tuong Nguyen Manh).
+    As in #1294 `\url` and `\href` need to be protected
+    inside an mbox for `soul` commands.
+
+  * Text.Pandoc.Extensions: Add `Ext_table_attributes` constructor for
+    `Extension` [API change].
+
+  * Use released texmath 0.13.0.1.
+
+  * Update FSF contact information in COPYING (#11183, Bensun Muite).
+
+  * MANUAL.txt: remove some redundancy (#11178, Reuben Thomas).
+
+## pandoc 3.8.1 (2025-09-29)
+
+  * New output format `vimdoc` (Vim documentation format) (#11132, reptee).
+
+    + [API change] Added module Text.Pandoc.Writers.Vimdoc, exporting
+      `writeVimdoc`.
+
+  * Markdown reader:
+
+    + Improve superscript/subscript/inline note parsing (#8652).
+      We do not allow inline notes to be followed by `(` or `[`.
+      Otherwise, we parse inline notes before superscripts.
+      Also, the sub/superscript parsers have been adjusted so that they
+      really exclude unescaped spaces (as they did not before, when the
+      spaces occurred in nested inlines).
+    + Fix simple table alignment (#11136, Tuong Nguyen Manh). Take wide
+      characters into account when determining the alignment.
+
+  * LaTeX reader:
+
+    + Ignore `\pandocbounded` (#11140).
+
+  * XML reader:
+
+    + Parse `<MetaString>` (#11137, massifrg).
+
+  * Typst reader:
+
+    + Add support for reading typst pagebreak (#11101, Raymond Berger).
+      The pagebreak is parsed as a HorizontalRule inside a wrapper Div
+      with class `page-break`.
+
+  * Docx reader:
+
+    + Handle figures in indented paragraphs (#11028).
+    + Change default for textwidth. This should only be used if `sectPr`
+      is not found.
+    + Properly calculate table column widths (#9837, #11147).
+      Previously we assumed that every table took up the full text
+      width. Now we read the text width from the document's `sectPr`.
+    + Use Tasty.Golden for Docx reader tests. This way we can update
+      them with `--accept`.
+
+  * RST reader:
+
+    + Fix regression in simple table parsing (#11150).
+    + SkippedContent warning if table directive contains
+      non-tabular content.
+    + Simple tables: leading space in a cell should not cause the contents
+      to be parsed as a block quote (#11146).
+    + Parse `:alt:` on figure (#11140). Also give a better default if
+      `alt` is not specified, using the stringified caption rather
+      than the filename.
+    + Support col spans for simple tables (Tuong Nguyen Manh).
+
+  * Markdown writer:
+
+    + Improve handling of implicit figures (#11140).
+      Allow implicit figures when alt text differs from caption
+      (in this case, we use an image attribute to add the alt).
+    + Use approximate pipe tables when it's the only option (#11128).
+      If we have a table with row/colspans that can rendered as an
+      approximate pipe table (without row/colspans), and no other table
+      format is enabled that could render the table, we fall back to
+      an "approximate" pipe table, with no row/colspans.
+
+  * RST writer:
+
+    + Ensure blank line before directives (#11162).
+    + Add col spans for simple tables (#10127, Tuong Nguyen Manh).
+
+  * OpenDocument writer:
+
+    + Add missing table elements (#10002, Tuong Nguyen Manh).
+      Add missing header rows after the first one,
+      footer rows as well as TableBody header rows.
+
+  * Docx writer:
+
+    + Fix regression (from 3.8) in highlighted code (#11156).
+
+  * Powerpoint writer:
+
+    + Handle single column (Tuong Nguyen Manh).
+
+  * Typst writer:
+
+    + Fix syntax highlighting (#11171, completes #10525).
+      Previously the native typst highlighting was always used, regardless
+      of the setting of `--syntax-highlighting`. With this change,
+      `--syntax-highlighting=none` and `--syntax-highlighting=<stylename>`
+      (with skylighting style) will work.
+
+  * LaTeX writer:
+
+    + Make beamer footnotes compatible with pauses (#5954).
+      Previously they would appear before the content to which
+      the note was attached, when there were pauses in a slide.
+    + Avoid `\_` in bibliography variable (#11152).
+    + Ensure that unlabelled tables don't increment counter (#11141).
+    + Protect VERB in caption (#11139, Tuong Nguyen Manh).
+    + Don't add links to TOC (#11124, Albert Krewinkel).
+    + Fix strikeouts in beamer title (#11168, Tuong Nguyen Manh).
+
+  * LaTeX template: Add `shorthands` variable for LaTeX output
+    (#11160). If true, pandoc will allow language-specific shorthands
+    when loading babel. (This is helpful, for example, in getting
+    proper spacing around French punctuation.)
+
+  * epub.css: Remove coloring for `a, a:visiting` (#11174).
+    This was causing links in iOS books app not to be distinguished in
+    any way (since underlining is not used there).
+
+  * Text.Pandoc.Parsing:
+
+    + [API chage] (Tuong Nguyen Manh). New functions `tableWithSpans`,
+      `tableWithSpans'`, `toTableComponentsWithSpans` and
+      `toTableComponentsWithSpans'` take a list of lists of
+      (Blocks, RowSpan, ColSpan) to parse a Table with different RowSpan and
+      ColSpan values accordingly. New helper functions `singleRowSpans` and
+      `singleColumnSpans` help set all RowSpans or ColSpans to be 1 in case
+      the table format only allows setting one or the other.
+
+  * Text.Pandoc.Class:
+
+    + Let `fetchItem` fail if the HTTP request is not
+      successful (Albert Krewinkel). HTTP requests that don't return a 200
+      error code are now treated as an error. This ensures that a warning is
+      triggered when using `--embed-resources` or `--extract-media`.
+
+  * Text.Pandoc.Writers.Shared:
+
+    + Add new function `removeLinks` [API change] (Albert Krewinkel).
+      The function converts links to spans. It is used, for example, to avoid
+      nested links. The HTML writer used to put the description of nested links
+      into small caps, but uses a simple *span* now.
+
+  * Text.Pandoc.Highlighting: export typst functions
+    [API change]. New exported functions `formatTypstBlock`,
+    `formatTypstInline`, `styleToTypst`.
+
+  * Text.Pandoc.XML:
+
+    + Add `fetchpriority` to list of HTML attributes (#11176).
+
+  * Allow unicode-data 0.7.
+
+  * Use released djot 0.1.2.3. Fixes a bug in which indentation
+    was swallowed in a code block inside a blockquote.
+
+
+## pandoc 3.8 (2025-09-06)
+
+  * Add a new input and output format `xml`, exactly representing a Pandoc
+    AST and isomorphic to the existing `native` and `json` formats (massifrg).
+    XML schemas for validation can be found in `tools/pandoc-xml.*`.
+    The format is documented in `doc/xml.md`. Pandoc now defaults to this
+    reader and writer when the `.xml` extension is used.
+
+    Two new exported modules are added [API change]:
+    Text.Pandoc.Readers.XML, exporting `readXML`, and
+    Text.Pandoc.Writers.XML, exporting `writeXML`.
+    A new unexported module Text.Pandoc.XMLFormat is also added.
+
+  * Add a new command line option `--syntax-highlighting`; this takes
+    the values `none`, `default`, `idiomatic`, a style name, or a path to a
+    theme file. It replaces the `--no-highlighting`, `--highlighting-style`,
+    and `--listings` options, which will still work but with a deprecation
+    warning. (Albert Krewinkel)
+
+  * Create directory of output file if it doesn't exist (#11040).
+
+  * Update `--version` copyright dates (#10961), and use a hardcoded
+    string "pandoc" for the program name in `--version`, per GNU
+    guidelines.
+
+  * Add `smart_quotes` and `special_strings` extensions (Albert Krewinkel).
+    Currently these only affect `org`. Org mode makes a distinction between
+    smart parsing of quotes, and smart parsing of special strings like `...`.
+    The finer grained control over these features is necessary to truthfully
+    reproduce Emacs Org mode behavior. Special strings are enabled by default,
+    while smart quotes are disabled.
+
+  * Remove the old `compact_definition_lists` extension. This was
+    neded to preserve backwards compatibility after pandoc 1.12
+    was released, but at this point we can get rid of it.
+
+  * Make `-t chunkedhtml -o -` output to stdout (as documented), rather
+    than creating a directory called `-` (#11068).
+
+  * RST reader: Support multiple header rows (#10338, TuongNM).
+
+  * LaTeX reader:
+
+    + Support soft hyphens (Albert Krewinkel).
+    + Parse `\minisec` as unlisted level 6 headings (#10635, Albert Krewinkel).
+    + Support `\ifmmode` (#10915).
+    + Change handling of math environments (#9711, #9296).
+      Certain environments in LaTeX will trigger math mode and can't
+      occur within math mode: e.g., `align` or `equation`.  Previously
+      we "downshifted" these, parsing an `align` environment as a
+      Math element with `aligned`, and an `equation` environment as a
+      regular display math element.  With this shift, we put these in
+      Math inlines but retain the original environments.
+      texmath and MathJax both handle these environments well.
+
+  * Typst reader:
+
+    + Fix addition of image path prefix to use posix separator.
+    + Properly resolve image paths in included files (#11090).
+    + Handle inline-level show rules on block content (#11017).
+      Typst allows things like `smallcaps` to be applied to block-level
+      content like headings.  This produces a type mismatch in pandoc,
+      so before processing the output of typst-hs, we transform it,
+      pulling the block-level elements outside of the inline-level
+      elements.
+
+  * Org reader:
+
+    + Improve sub- and superscript parsing (Albert Krewinkel).
+      Sub- and superscript must be preceded by a string in Org mode. Some text
+      preceded by space or at the start of a paragraph was previously parsed
+      incorrectly as sub- or superscript.
+    + Allow "greater block" names to contain any non-space char (#4287,
+      Albert Krewinkel).
+    + Accept quoted values as argument values (#8869, Albert Krewinkel).
+    + Recognize "fast access" characters in TODO state definitions
+      (#10990, Ryan Gibb).
+    + Improve org-cite parsing: Handle global prefix and suffix properly.
+      Use all and only the styles mentioned in oc-basic.el.
+      Allow space after `;`.
+
+  * HTML reader:
+
+    + Don't drop the initial newline in a `pre` element (#11064).
+
+  * DocBook reader:
+
+    + Add rowspan support (#10981, Sean Soon).
+    + Be sensitive to startingnumber attribute on ordered lists (#10912).
+
+  * POD reader:
+
+    + Fix named entity lookup (#11015, Evan Silberman).
+
+  * Man reader:
+
+    + Support header and footer reader (Sean Soon).
+
+  * Markdown reader:
+
+    + Don't confuse a span after an author-in-text citation with a
+      locator.  E.g. `@foo [test]{.bar}`.
+      See https://github.com/jgm/pandoc/issues/9080#issuecomment-3221689892.
+    + Make definition lists behave like other lists (#10889).
+      If the `four_space_rule` extension is not enabled,
+      figure out the indentation needed for child blocks dynamically,
+      by looking at the first nonspace content after the `:` marker.
+      Previously the four-space rule was always obeyed.
+    + Fix tight/loose detection for definition lists, to conform to
+      the documentation.
+
+  * ODT reader:
+
+    + Support `table-header-rows` (Tuong Nguyen Manh).
+
+  * Docx reader:
+
+    + Don't add highlighting if highlight color is "none" (#10900).
+    + Handle strict OpenXML as well as transitional (#7691).
+    + Fix `stringToInteger` (#9184). It previously converted things like
+      `11ccc` to an integer; now it requires that the whole string be parsable
+      as an integer.
+    + Improve handling of AlternateContent. This fixes handling of
+      one representation of emojis in Word (#11113).
+
+  * LaTeX writer:
+
+    + Control figure placement with attribute (#10369, Sean Soon).
+      If a `latex-placement` attribute is present on a figure, it will be used
+      as the optional positioning hint in LaTeX (e.g. `ht`). With implicit
+      figures, `latex-placement` will be added to the figure (and removed from
+      the image) if it is present on the image.
+    + Include cancel package only if there is math that contains `\cancel`,
+      `\bcancel`, or `\xcancel`.
+    + Add braces around comments in `title-meta` (#10501). This is needed to
+      prevent PDFs from interpreting this as a sequence of titles.
+    + Set `pdf-trailer-id` if `SOURCE_DATE_EPOCH` envvar is set (#6539, Albert
+      Krewinkel). The `SOURCE_DATE_EPOCH` environment variable is used to trigger
+      reproducible PDF compilation, i.e., PDFs that are identical down to the
+      byte level for repeated runs.
+    + Be more conservative about using `\url` (#8802). We only use it when the
+      URL is all ASCII, since the `\url` macro causes problems when used with
+      some non-ASCII characters.
+    + Support soft hyphens (Albert Krewinkel).
+    + Change handling of math environments (#9711, #9296).
+      When certain math environments (e.g. `align`) are found in Math
+      elements, we emit them "raw" instead of putting them in `$..$`.
+
+  * Typst writer:
+
+    + Check `XID_Continue` in identifiers (Tuong Nguyen Manh).
+    + Add escapes to prevent inadvertent lists due to automatic wrapping
+      (#10047). Also simplify existing code that was meant to do this.
+    + Add parentheses around typst-native year-only citations (#11044).
+    + Add native Typst support for `nocite` (#10680, Albert Krewinkel).
+      The `nocite` metadata field can now be used to supply
+      additional citations that don't appear in the text, just as with citeproc
+      and LaTeX's bibtex and natbib.
+    + Set `lang` attribute in Divs (#10965).
+    + Rename `numbering` variable to `section-numbering` (Albert Krewinkel).
+      This is the name expected by the default template.
+    + Add support for custom and/or translated "Abstract" titles (Albert
+      Krewinkel, #9724).
+
+  * Org writer:
+
+    + Don't wrap link descriptions (#9000). Org doesn't reliable display
+      these as links if they have hard breaks.
+    + Disable smart quotes by default (Albert Krewinkel).
+
+  * Markdown writer:
+
+    + Better handling of pandoc-generated code blocks (#10926).
+      Omit the wrapper sourceCode divs added by pandoc around code blocks.
+      More intelligently identify which class to use for the one class
+      allowed in GFM code blocks.  If there is a class of form `language-X`,
+      use `X`; otherwise use the first class other than `sourceCode`.
+    + Use fenced divs even with empty attributes (#10955, Carlos Scheidegger).
+      Previously fenced divs were not used in this case, causing the writer to
+      fall back to raw HTML.
+    + Match indents in definition items (#10890, Albert Krewinkel).
+      Previously, the first line of a definition details item always used a
+      colon and three spaces instead of respecting the tab-stop setting, which
+      could lead to round-tripping issues. Likewise, the indentation of
+      continuation paragraphs in definition lists now matches the
+      two-characters leader of the first line for Markua output.
+
+  * DocBook writer:
+
+    + Use `startingnumber` instead of `override` for start numbers on ordered
+      lists (#10912).
+
+  * ANSI writer:
+
+    + Make `--wrap=none` work properly (#10898).
+
+  * Djot writer:
+
+    + Fix duplicate attributes before section headings (#10984).
+
+  * Docx writer:
+
+    + Ensure that documents don't start with a section separator
+      (#10578, Albert Krewinkel). Any leading section separator is removed from
+      the result.
+
+  * HTML writer:
+
+    + Unwrap "wrapper" divs (#11014). Some of the readers (e.g. djot) add
+      "wrapper" divs to hold attributes for elements that have no slot for
+      attributes in the pandoc AST. The HTML reader now "unwraps"
+      these wrappers so that the attributes go on the intended elements.
+
+  * Asciidoc writer:
+
+    + Handle lists with sublists following continuations (#11006).
+      These require an additional blank line in some cases.
+
+  * HTML styles template: prefix default styles with informative CSS comment
+    (Albert Krewinkel, #8819).
+
+  * Org template: add `#+options` lines if necessary (Albert Krewinkel).
+    The default template now adds `#+options` lines if non-default settings
+    are used for the `smart_quotes` and `special_strings` extensions.
+
+  * LaTeX template:
+
+    + Don't emit empty `linkcolor=` in hypersetup (#11098).
+    + Add RTL support for LuaTeX engine (Reuben Thomas).
+
+  * Typst template:
+
+    + Add several new variables (Christopher T. Kenny, #9956):
+      `thanks`, `abstract-title`, `linestretch`, `mathfont`, `codefont`,
+      `linkcolor`, `filecolor`, `citecolor`.
+
+  * `reference.docx`:
+
+    + Don't left-align table header row (R. N. West, #11019).
+    + Update East Asia font theme in `styles.xml` to `minorEastAsia` (TomBen).
+    + Update language settings in `styles.xml` for East Asia to Simplified
+      Chinese (TomBen).
+
+  * Text.Pandoc.PDF:
+
+    + `makePDF`: automatically embed resources from media bag in HTML
+      before trying to convert it with weasyprint, etc. (#11099).
+      This will give better results when converting from formats like docx.
+    + Use `utf8ToText` for LaTeX log messages.
+    + Make images from MediaBag available in tmp dir for every PDF engine,
+      not just LaTeX/ConTeXt (#10911).
+    + Improve error readability when pdf-engine is not supported (Albert
+      Krewinkel). Each supported engine is now printed on a line of its own.
+    + Allow `pdflatex-dev` and `lualatex-dev` as PDF engines (#10991, Albert
+      Krewinkel). These are the development versions of the LaTeX binaries;
+      installable, e.g., with `tlmgr install latex-base-dev`.
+    + Clean up `makePDF` (Albert Krewinkel).
+    + Avoid encoding errors when reading LaTeX logs (#10954).
+
+  * Text.Pandoc.Readers:
+
+    + Raise unknown reader error for `ods`, `odp`, `odf`, `xls`,
+      `xslx`, `zip` extensions.
+
+  * Text.Pandoc.App:
+
+    + Recognize binary signatures and fail early (Repetitive). Fail early when
+      receiving binary input with recognized signature: zip[-based], including
+      OpenDocument and Microsoft formats, PDF, CFBF-based (old Microsoft formats
+      including .doc and .xls), DjVu.
+    + Remove code duplication around version info.
+      Text.Pandoc.App.CommandLineOptions and `pandoc-cli/src/pandoc.hs`
+      had similar code for generating version information.
+      To avoid duplication, we now export `versionInfo` from
+      Text.Pandoc.App [API change]. This function has three parameters that can
+      be filled in when it is called by `pandoc-cli`.
+
+  * Text.Pandoc.Parsing:
+
+    + `tableWith` and `tableWith'` now return a list of lists of Blocks, rather
+      than a list of Blocks, for the header rows, allowing for multiple header
+      rows [API change] (#10338, TuongNM).
+
+  * Text.Pandoc.Citeproc:
+
+    + Don't move footnotes around em-dashes (#11046).
+    + Allow `--citeproc` to put the bibliography in a Div with id `refs`
+      even when `--file-scope` is used (#11072). When `--file-scope`
+      is used, a prefix will be added based on the filename, so the Div
+      will end up having an identifier like `myfile.md__refs`.
+      Previously, this prevented the bibliography from being added to
+      the marked Div. Now pandoc will add the bibliography to any Div
+      with the id `refs` or any id ending in `__refs`.
+
+  * Text.Pandoc.Citeproc.BibTeX: Protect case in periodical titles (#11048).
+    Thus, for example, `{npj} Quantum Information` should translate as
+    `[npj]{.nocase} Quantum Information`.
+
+  * Text.Pandoc.ImageSize:
+
+    + Detect more JPEG file signatures (R. N. West and John MacFarlane, #11049).
+    + Unpack compressed object streams in PDFs and look inside for MediaBox
+      information (#10902).
+    + Add Point and Pica as constructors of ImageSize [API change] (#8957).
+      This will prevent unnecessary conversion of units.
+    + Add Avif constructor on ImageType [API change] and support avif images
+      (#10979).
+
+  * Text.Pandoc.Writers.Shared:
+
+    + Amend docs of `lookupMeta...` functions (#10634, Albert Krewinkel).
+
+  * Text.Pandoc.Options:
+
+    + Add and export `defaultWebTeXURL` WebTeX URL [API change] (#11029,
+      Sean Soon). This fixes the `webtex` option when used without
+      parameter in a defaults file.
+    + Add type `HighlightMethod` and patterns [API Change] (Albert Krewinkel).
+    + The `writerListings` and `writerHighlightStyle` fields of the
+      `WriterOptions` type are replaced with `writerHighlightMethod`
+      [API change] (Albert Krewinkel, #10525).
+
+  * Text.Pandoc.Extensions:
+
+    + Remove `Ext_compact_definition_lists` constructor for
+      `Extension` [API change].
+    + Add `Ext_smart_quotes` and `Ext_special_strings` constructors.
+      [API change].
+
+  * Text.Pandoc.SelfContained:
+
+    + Try fetching relative resources without query or fragment if the original
+      fetch fails. This provides a fix for #1477 in a way that doesn't raise
+      the problems mentioned in #11021.
+
+  * Text.Pandoc.Highlighting:
+
+    + Export `defaultStyle` [API Change] (Albert Krewinkel).
+      This allows to be more explicit about using a default style, and
+      providing a single point of truth for its value. The variable is
+      an alias for `pygments`.
+
+  * Text.Pandoc.Class:
+
+    + `downloadOrRead`: do not drop fragment/hash for local file paths (#11021).
+      With the previous behavior it was impossible to have an image
+      file containing `#` or `?`.
+    + Export function `runSilently` [API Change] (Albert Krewinkel).
+      The function runs an action in the PandocMonad, but returns all log
+      messages reported by that action instead of adding them to the main log.
+    + Make CommonState opaque. Text.Pandoc.Class now exports CommonState as
+      an opaque object, without its fields. [API change]
+      The internal module Text.Pandoc.Class.CommonState still exports
+      the fields.
+    + Text.Pandoc.Class now exports the following new functions:
+      `getRequestHeaders`, `setRequestHeaders`, `getSourceURL`,
+      `getTrace`. [API change]
+    + CommonState now has a `stManager` field. This allows us to cache the HTTP
+      client manager and reuse it for many requests, instead of creating it again
+      (an expensive operation) for each request. This fixes a memory leak and
+      performance issue in files with a large number of remote images (#10997).
+
+  * Lua subsystem (Albert Krewinkel):
+
+    + Add function `pandoc.structure.unique_identifier`.
+    + Add functions `pandoc.text.superscript` and `subscript`.
+    + Use proper interface functions to access the CommonState.
+      The `PANDOC_STATE` is no longer a userdata object, but a table that
+      behaves like the old object. Log messages in `PANDOC_STATE.log` are now
+      in temporal order.
+    + Add function `pandoc.path.exists`.
+    + Add `normalize` function to *Pandoc* objects (#10356).
+      This function performs a normalization of Pandoc documents. E.g.,
+      multiple successive spaces are collapsed, and tables are normalized such
+      that all rows and columns contain the same number of cells.
+    + Add more UTF-8-aware file operations to `pandoc.system`.
+      Functions that expect UTF-8-encoded filenames should make it easier to
+      write platform-independent scripts, as the encoding of the actual
+      filename depends on the system. In addition, there is a new
+      generalized method to run commands, and functions to retrieve XDG
+      directory names. The new functions are `command`, `copy`, `read_file`,
+      `remove`, `rename`, `times`, `write_file`, `xdg`.
+    + Allow hslua-2.4.
+    + Require lua-module-system 1.2.3. This provides List methods to the value
+      returned by `pandoc.system.list_directory` (#11032).
+
+  * MANUAL.txt:
+
+    + Fix broken ConTeXt links (R. N. West, #11055).
+    + Add `xml` as input/output format.
+    + Fix minor capitalization typo (#11052, Albert Krewinkel).
+
+  * `doc/lua-filters`:
+
+    + Fix docs for `pandoc.Cite` (Albert Krewinkel).
+    + Don't encourage returning tables of filters from Lua filters
+      (R. N. West, #10995). Use the `Pandoc:walk` method instead.
+
+  * doc/extras.md: Fix link to pandoc-mode (Erik Post).
+
+  * doc/lua-filters.md: Add example on using pandoc.Table constructor (#10956,
+    Sean Soon).
+
+  * Update `default.csl` from new chicago-author-date.csl, which is now
+    for the 18th edition.
+
+  * Use latest releases of citeproc, typst-hs, texmath, doclayout,
+    skylighting-core, skylighting.
+
+## pandoc 3.7.0.2 (2025-05-28)
+
+  * RST writer:
+
+    + Don't emit alignment markers in grid tables (#10857).
+
+  * Asciidoc writer:
+
+    + Add support for sidebars (GHyman83).
+
+  * LaTeX writer:
+
+    + Include alt option in `\includegraphics` (#6095).
+
+  * Markdown writer:
+
+    + Preserve figure attributes (Nikolay Yakimov, #10867).
+      Fixes a regression introduced by 0d2114e, which caused the
+      Markdown writer to ignore attributes on the figure if it
+      has class or key-value attributes set.
+
+  * HTML writer:
+
+    + Use the ID prefix in the ID for the footnotes section (Benjamin Esham).
+
+  * Text.Pandoc.Writers.Shared:
+
+    + `gridTable`: fix (3.7) regression with missing cell alignments (#10853).
+    + `gridTable`: fix headings with colspans (#10855). If the heading
+      contains a colspan, we still need to include information in the header
+      line about the colspecs.
+    + `gridTable`: fix headerless tables. The top line should encode
+      colspan information.
+
+  * Text.Pandoc.SelfContained:
+
+    + Fix handling of empty script element (#10862). Previously in this
+      case the closing tag was dropped.
+    + Do not drop `data-` attributes in script tags (#10861).
+
+  * Lua subsystem (Albert Krewinkel):
+
+    + Add function `pandoc.mediabag.make_data_uri` (#10876).
+      The function takes a MIME type and raw data from which it creates an
+      RFC 2397 data URI.
+
+  * `tools/update-lua-module-docs`: fix handling of wikilinks
+    (Albert Krewinkel).
+
+  * `doc/lua-filters.md`: add missing docs for `pandoc.Caption`
+    (Albert Krewinkel).
+
+  * Require texmath 0.12.10.3, typst 0.8.0.1
+
+## pandoc 3.7.0.1 (2025-05-17)
+
+  * Text.Pandoc.Shared.Writer:  Fix numerous problems with `gridTable` and add
+    tests (#10848).  These fixes affect the Markdown, RST, and Muse writers.
+
+  * Fix context writer/template to produce tagged PDFs (#10846).
+    As before, the `tagging` extension must be enabled.
+    We now add the command that tells ConTeXt to start tagging.
+
+## pandoc 3.7 (2025-05-14)
+
+  * Add new command-line option `--variable-json` (#10341).
+    This allows non-string values (booleans, lists, maps) to be given to
+    template variables on the command line.
+
+  * The `--pdf-engine` option can now take `groff` as a value.
+
+  * Markdown writer:
+
+    + Avoid spaces after/before open/close delimiters (#10696).
+      E.g. instead of rendering `x<em> space </em>y` as `x* space *y` we render
+      it as `x *space* y`.
+    + Handle row/colspans in grid tables, and expand cells when it isn't
+      possible to lay them out without breaking string of non-whitespace.
+    + Render a figure with Para caption as implicit figure (#10755).
+    + When falling back to a Div with class `figure` for a figure that
+      can't be represented any other way, include a Div with class
+      `caption` containing the caption.
+    + Improve use of implicit figures when possible (#10758).
+      When the alt differs from the caption, but only as regards formatting, we
+      still use an implicit figure.
+    + Omit initial newlines in gfm `math` blocks to avoid an ugly blank line.
+    * Support the `four_space_rule` extension for `plain` output (#10813,
+      Manolis Stamatogiannakis).
+
+  * RST writer:
+
+    + Handle row/colspans in grid tables, and expand cells when it isn't
+      possible to lay them out without breaking string of non-whitespace.
+
+  * Muse writer:
+
+    + Handle row/colspans in grid tables, and expand cells when it isn't
+      possible to lay them out without breaking string of non-whitespace.
+
+  * JATS writer:
+
+    + Fix escaping for writing-review-editing role (#10744).
+
+  * HTML writer:
+
+    + Remove trailing slash from default revealjs URL (#8749). This
+      avoids a double slash in the URL's path component.
+
+  * LaTeX writer:
+
+    + Make alignment work within `multirow` in tables (#10772).
+
+  * Typst writer:
+
+    + Support `mark` class on spans (#10747).
+    + Add equation label if math contains `\label{..}` (#10805).
+
+  * Roff format writers (man, ms):
+
+    + Use the most compatible form for roff escapes (#10716).
+      For example, `\(xy` instead of `\[xy]`. This was the original
+      AT&T troff form and is the most widely supported. The
+      bracketed form causes problem for some tools, e.g.
+      `makewhatis` on macOS. And emit `e` followed by an escape
+      for a unicode combining accent rather than the form `\[e aa]`,
+      which works for groff but not e.g. on macOS's man.
+      This change affects Text.Pandoc.RoffChar,
+      Text.Pandoc.Writers.Roff, and the Man and Ms writers.
+
+  * Docx writer:
+
+    + Ensure that figures and tables with custom styles are not dropped
+      (#10705).
+    + Preserve Relationships for images from reference docx (#10759).
+      This should allow one to include an image in a reference.docx and
+      reference it in an openxml template.
+    + Don't renumber rels (#10769). We used to renumber the
+      Relationships so they didn't conflict with the set of fixed
+      Relationships we imposed. We are now preserving the ids
+      from the reference doc's document.xml.refs, so we shouldn't
+      renumber them or references introduced by the user (e.g. in
+      a template) will fail.
+
+  * Ms writer:
+
+    + Improve PDF TOC labels. We now use the plain writer to render these,
+      so that Greek characters etc. will show up properly.
+    + When no `pdf-engine` variable is specified, do not use the
+      `.pdfhref` macros at all (#10738). This gives better results for links
+      in formats other than PDF, since the link text would simply
+      disappear if it exists only in a `.pdfhref` macro. When a PDF
+      engine is specified, escape the argument of `.pdfhref O` in a way
+      that is appropriate.
+
+  * OpenDocument writer:
+
+    + Fix character styles in footnotes (#10791). Character
+      styles governing the position of the footnote reference
+      should not be imposed on the footnote text.
+
+  * Powerpoint writer:
+
+    + Use reference-doc font for captions (#9896, R. N. West).
+
+  * DocBook writer:
+
+    + Use literallayout element for LineBlock (#10825).
+
+  * MediaWiki reader/writer:
+
+    + Allow definition on same line as term (#10708).
+
+  * LaTeX reader:
+
+    + Skip at most one argument to LaTeX tabular newline (#7512,
+      Evan Silberman).
+    + Disable ligatures inside `\texttt` (#10781).
+    + Support more symbol commands (#10782).
+
+  * Commonmark Reader:
+
+    + Handle GFM math irregularity with braces (#10631). In GFM, you need
+      to use `\\{` rather than `\{` for a literal brace.
+
+  * DocBook reader:
+
+    + Improve handling of literallayout (#10825). This is now only made
+      a CodeBlock when there is a `monospaced` class. Otherwise it is made
+      a LineBlock.
+
+  * Org reader:
+
+    + Add AVIF to Org Reader image extensions (#10736, Christian Christiansen).
+    + Don't include newlines in inine code/verbatim (#10730).
+      Convert newlines to spaces as we do in other formats.
+    + Change handling of inline TeX (#10836). Previously inline
+      TeX was handled in a way that was different from org's own export,
+      and that could lead to information loss. This was particularly noticeable
+      for inline math environments such as `equation`.  Previously, an
+      `equation` environment starting at the beginning of a line would create
+      a raw block, splitting up the paragraph containing it (see
+      #10836). On the other hand, an `equation` environment not
+      at the beginning of a line would be turned into regular
+      inline elements representing the math. (This would cause
+      the equation number to go missing and in some cases degrade
+      the math formatting.) Now, we parse all of these as raw
+      "latex" inlines, which will be omitted when converting to
+      formats other than LaTeX (and other formats like pandoc's
+      Markdown that allow raw LaTex).
+
+  * Beamer template: fix regression in 3.6.4, reverting the omission of
+    `\date` when the document does not have a date. By default, beamer
+    will display a date when no `\date` is present in the title block,
+    so this was an unintended behavior change. The reverted
+    change was motivated by the desire to include a custom
+    `\date` in the frontmatter via header-includes. This can be
+    achieved more simply by simply setting the `date` variable.
+    In markdown you can even use `date` in metadata and put some
+    raw LaTeX there.
+
+  * Ms template:
+
+    + Use T rather than P as default font family (#10738).
+    + Put PDF-specific things under a conditional.
+      Don't include them if `pdf-engine` isn't set.
+
+  * Upgrade reveal.js URL to v5 (#10740, Kolen Cheung).
+    v4 is no longer available on unpkg.com.
+
+  * Text.Pandoc.PDF: Allow `groff` to be used as `--pdf-engine` with `ms`
+    (#10738). When `groff` is used as a PDF engine, the `groff`
+    extension to `ms` is automatically enabled. Limitations:
+
+    - `groff` currently produces larger PDFs than `pdfroff`.
+    - With `groff`, a table of contents produced with
+      `--table-of-contents/--toc` will always be placed at the end of
+      the document.
+    - Certain characters (e.g. Greek characters) may be dropped in
+      the PDF outline.
+
+  * Text.Pandoc.Writers.Shared:
+
+    + Export `delimited` [API change].
+    + New version of `gridTable` (#6344) [API change]. This
+      handles row and colspans. It also ensures that cells won't
+      wrap text in places where it wouldn't normally wrap, even
+      if this means making the cells wider than requested by the
+      colspec (#9001, #7641). Because the parameters are
+      different, this is a breaking API change.
+
+  * Text.Pandoc.App: set `pdf-engine` variable.
+    If `--pdf-engine` is specified or if a PDF is being produced, we set the
+    `pdf-engine` variable. This allows writers and templates to behave
+    differently depending on the PDF engine.
+
+  * Text.Pandoc.Class and Text.Pandoc.URI:
+
+    + Fix parsing of base64 data URIs to allow URI escapes and
+      whitespace (which will be ignored) (#10704).
+    + Handle percent encoding in `pBase64URI` instead of
+      unescaping later, for efficiency (#10704).
+
+  * Text.Pandoc.Citeproc.BibTeX:
+
+    + Recognize `en` as a `langid` in biblatex bibliographies (#10764).
+
+  * Text.Pandoc.MIME:
+
+    + Add mime type and extension for `avif` (#10704).
+    + Handle `apng`, `avif`, `jxl` (#10704).
+
+  * Text.Pandoc.Readers.LaTeX.Math: export `inlineEnvironmentNames`.
+    Internal module, not a change to the public API.
+
+  * `reference.docx` (Andrew Dunning):
+
+    + Remove extra spaces around text placeholders.
+    + Add footnote block text sample.
+
+  * Text.Pandoc.Class.Sandbox:
+
+    + Add `sandboxWithFileTree` function [API change] (Albert Krewinkel).
+
+  * Lua subsystem (Albert Krewinkel):
+
+    + pandoc-lua-engine: add all test files to the cabal file.
+    + Allow `pandoc.read` to be called in "sandbox" mode for added
+      security (#10831). Readers running in a sandbox will not be
+      able to access the network or file system. The sandbox is
+      enabled if the fourth parameter is a list of files or
+      filename/content pairs. The files are read and then made
+      available in the sandbox via en ersatz file system.
+
+  * Makefile:
+
+    + Add target `release-checkist`.
+    + Install @daisy/ace from npm if not present.
+    + Use pandoc lua instead of lua.
+    + Fix typo in `latex-package-dependencies` target.
+    + Use `jq` instead of `json_reformat` in `validate-docx-golden-tests2`.
+
+  * NiX infrastructure: new working `flake.nix` and simpler `shell.nix`.
+    Removed old `default.nix`.
+
+  * Require random >= 1.3 and use `splitGen`. `split` has been deprecated.
+
+  * Use citeproc-0.9. Bump citeproc bounds for pandoc, pandoc-lua-engine.
+
+  * Use texmath-0.12.10.1.
+
+  * Use released typst 0.8 (partially supporting typst 0.13).
+
+  * Use citeproc 0.9.0.1.
+
+  * MANUAL.txt:
+
+    + Fix default URL for revealjs.
+    + Add note that `alerts` extension only works with commonmark (#9716).
+    + Remove "Body Text Char" from list of Word styles that can be customized
+      using a reference.docx (#10646). This doesn't seem to be present in
+      pandoc-generated docx files, nor is it a Word default.
+    + For pandoc lua, add note about the environment.
+    + Improve documentation of `--variable` option.
+
+  * `doc/typst-property-output.md`: Mention that `typst:no-figure` is a
+    class, not an attribute (#10826, Niklas Eicker).
+
+  * Change RELEASE-CHECKLIST to RELEASE-CHECKLIST-TEMPLATE.org. Use org-babel
+    to automate many of the steps of the release.
+
+  * INSTALL.md: update MacPorts information (#10719, Mohamed Akram).
+
+  * COPYRIGHT: fix link to source code.
+
+  * CONTRIBUTING.md: Fix link to discussion forum. (#10834, R. N. West).
+
+## pandoc 3.6.4 (2025-03-16)
+
+  * Disable `citations` extension in writers if `--citeproc` is used (#10662).
+    Otherwise we get undesirable results, as the format's native
+    citation mechanism is used instead of (or in addition to) the
+    citeproc-generated citations.
+
+  * Markdown reader:
+
+    + Allow line break between URL and title of link (#10621).
+    + Give better position information when YAML metadata parsing fails
+      with a YAML exception (#10231).
+    + Fixed `escapedChar'` parser (#10672). It should not accept
+      escaped newlines.
+    + Remove some misguided list fanciness (#9865, #7778, cf. #5628).
+      Previously we tried to handle things like commented out list items:
+      ```
+      - one
+      <!--
+      - two
+      -->
+      - three
+      ```
+      and also things like:
+      ```
+      - one `and
+      - two` and
+      ```
+      But the code we added to handle these cases caused problems with
+      other, more straightforward things, like:
+      ````
+      - one
+      - ```
+        code
+        ```
+      - three
+      ````
+      So we are rolling back all the fanciness, so that the markdown
+      parser now behaves more like the commonmark parser, in which
+      indicators of block-level structure always take priority over
+      indicators of inline structure.
+
+  * HTML reader:
+
+    + Skip MathJaX-introduced cruft (#10673).
+    + Ignore style tags in the body (#10643).
+
+  * LaTeX reader:
+
+    + Better handle comments/whitespace in option lists and includes (#10659).
+    + Support `\newline`, `\linebreak`.
+
+  * Docx reader/writer:
+
+    + Revert commit adding row heads
+      (cbe67b9602a736976ef6921aefbbc60d51c6755a) (#10627).
+      Word sets `w:firstColumn="1"` by default for tables.  You have to find
+      the Table Design tab and explicitly uncheck "First Column" to make this
+      go away.  In most cases, I don't think writers intend to designate
+      the first column as a row head, so this commit is going to produce
+      unexpected results.  In addition, because of the table normalization
+      done by pandoc-type's `tableWith`, any table containing a colspanned
+      cell in the left-hand column will get broken if the first column is
+      designated a row head.  For these reasons it seems best to revert this
+      change, which was made in response to #9495.
+
+  * LaTeX writer and template:
+
+    + Remove `selnolig-langs` (#9863). We now specify the language as
+      a global option again, so we no longer need to specify it when
+      invoking selnolig.
+    + Use babel options `shorthands=off` (#6817).
+    + Use `*` for multirow width when no colwidth specified (#10685).
+      Otherwise the multirow will be excessively wide.
+    + Protect `\phantomsection` (#10688, etclub).
+
+  * Markdown writer:
+
+    + Omit extra space after bullets (#7172). Those who want the old
+      behavior can obtain it by using `-t markdown+four_space_rule`.
+    + Treat `Emph [Emph ils]]` as `ils` (#10642). Otherwise we get
+      `**content**` which means strong emphasis.
+
+  * EPUB writer:
+
+    + Use a nonbreaking space after section number in nav.xhtml.
+      This seems to be required for iOS books app to display the space.
+
+  * Typst writer:
+
+    + Better heuristics for escaping potential list markers (#10650).
+    + Ensure that `citation-style` works as well as `csl` (#10661).
+
+  * Powerpoint writer:
+
+    + Avoid extra blank lines before author when there is no
+      subtitle (#10619).
+
+  * JATS template:
+
+    + Fix typo in author prefix in article.jats_publishing template
+      (#10622, Tiago-Manzato).
+
+  * Text.Pandoc.Parsing:
+
+    + Smart quote parsing: ignore curly quotes (#10610). Previously we
+      tried to match curly quotes as well as straight quotes,
+      producing Quoted inlines. But it seems better just to assume
+      that those who use curly quotes want them passed through
+      verbatim. This also fixes an (unintended) bug whereby curly
+      single left quotes would sometimes be changed to single right quotes.
+
+  * Text.Pandoc.Shared:
+
+    + `makeSections`: put some attributes on section element only.
+      Certain `role` and `epub:type` attributes should only be on the section
+      (and indeed, many `role`s give a validation error if left on the
+      heading element).
+
+  * Text.Pandoc.Logging:
+
+    + Change NoTitleElement from WARNING to INFO (#10671). Users
+      commonly complain about the warning when producing HTML
+      documents without an explicit title. It seems that an info
+      message is more appropriate, since pandoc's default here (using
+      the input's base name) ensures compliance with the standard and
+      many users are happy with that default. Those who want to make
+      sure the message is seen can use `--verbose`.
+
+  * Beamer template: only emit `\date` if set (#10687, josch).
+
+  * Fix invalid OOXML in definition_list.docx test (#10394).
+
+  * MANUAL.txt:
+
+    + Correct typo: 'date' for doubled 'title' (#10654, Olivier Dossmann).
+    + Add note about `template` variable for typst.
+    + Change maxwidth default in MANUAL.txt (#10683).
+    + Improve EPUB metadata documentation.
+    + In Security section, alert readers to a threat relating to iframe in
+      HTML, and add LaTeX, Typst to the list of formats that have an
+      `include` (#10682).
+
+  * `doc/lua-filters.md`: Add missing html_math_method 'katex' (R. N. West).
+
+  * Use texmath 0.12.9.
+
+  * Use typst 0.7. Fixes an issue with package loading, a regression
+    in pandoc 3.6.3.
+
+## pandoc 3.6.3 (2025-02-09)
+
+  * Track wikilinks with a class instead of a title (Evan Silberman).
+    Previously wikilinks were distinguished by giving them the `title`
+    `wikilink`.  Now that we have link attributes, it makes more sense
+    to give them the `class` `wikilink`. This change affects all readers
+    and writers that support wikilinks.
+
+  * DocBook reader:
+
+    + Handle title inside `orderedlist` (#10594). Also some other
+      elements that allow title: `blockquote`, `calloutlist`, etc.
+    + Better handle `informalequation` (#10592, tombolano). Include `id`
+      attribute.
+    + Better handle `formalpara`, `example`, and `sidebar` (#8666, tombolano).
+      Include identifiers and titles in each case.
+
+  * Markdown reader:
+
+    + Simplify and fix normal citation parsing (#10584).
+      This fixes a bug that causes some normal citations to be
+      parsed as bracketed regular citations.
+
+  * ODT reader:
+
+    + Create Figure elements for images that are figures (#10567).
+    + Avoid producing spurious blockquotes in list items (#9505).
+    + Fix unwanted block quotes (#10575). Previously the reader created
+      block quotes whenever a paragraph was marked indented (even though
+      this just affects the first line). With this change we still
+      generate block quotes for content that has an altered left margin,
+      but not for indented paragraphs.
+
+  * Docx reader:
+
+    + Do not issue warning for comments with `+styles` (#10571, Stephen Reindl).
+
+  * LaTeX reader:
+
+    + Test \{,re}newcommand arguments (#4470, Evan Silberman).
+
+  * Pod reader:
+
+    + Consume blanks after =encoding in pod reader (#10537, Evan Silberman).
+
+  * JATS writer:
+
+    + Add CRediT roles to JATS (Charles Tapley Hoyt and Jez Cope, #10152).
+      Enable annotating author roles using the Contribution Role Taxonomy
+      (CRediT) and export this information in conformant JATS.
+
+  * LaTeX writer/templates:
+
+    + Improve babel support (#8283). Previously we used the `.ini`
+      files for every language, but for European languages these tend to
+      provide inferior results to the `.ldf` files used by classic
+      Babel. Currently Babel documentation recommends using the classic
+      system for European languages written in Latin and Cyrillic
+      scripts and Vietnamese. So the LaTeX writer and template now
+      follow this guidance.
+
+      Main languages in the list of languages with good "classic" support
+      are added to global documentclass options and will be automatically
+      handled by Babel using the `.ldf` files.
+
+      If the main language is not in this list, the `babeloptions` variable
+      will be set to `provide=*`, which will cause support to be loaded from
+      the `.ini` file rather than an `.ldf`. So, for example, setting
+      `-V babeloptions=''` with a polytonic Greek document will cause the
+      `.ldf` support to be used instead of the `.ini`.
+
+      The default setting of this variable can be overwritten, but in most
+      cases the default should give good results.
+
+    + Allow `csquotesoptions` to be specified.
+    + Fix indentation bugs in `font-settings.latex`.
+
+  * Docx writer:
+
+    + Repeat reference doc's `sectPr` for each new section (#10577).
+      Previously we were only carrying over the reference doc's `sectPr`
+      at the end of the document, so it wouldn't affect the intermediate
+      sections that are now added if `--top-level-division` is `chapter`
+      or `part`. This could lead to bad results (e.g. page numbering
+      starting only on the last chapter).
+    + Create section divisions with `--top-level-division=part` (#10576).
+    + Improve title style in reference.docx; base Author and Date
+      on Title; remove condensed spacing (Andrew Dunning, #10581).
+
+  * Typst writer:
+
+    + Brace tables with `typst:no-figure` and `typst:text` attributes (#10563,
+      Gordon Woodhull).
+
+  * Ms writer:
+
+    + Fix escaping of `-` (#10536). `-` should now be escaped in man
+      output but not in ms output (where `\-` is a unicode minus sign).
+
+  * HTML styles: fix style of `hr` so it works when printed (#10535, Hendrik Erz).
+    Previously `background-color` was used to style the hr, but this gets ignored
+    when printing.  This commit uses `border-top` instead.
+
+  * Text.Pandoc.Shared:
+
+    + Handle `<abbr>` as a span-like inline in `htmlSpanLikeElements`
+      (#5793, Evan Silberman).
+
+  * Text.Pandoc.MediaBag:
+
+    + Prefer MIME type when determining extensions for MediaBag items (#10557,
+      Max Heller).  This should give different results for remote images
+      that are served at URLs that do not contain misleading extensions
+      (e.g. `shields.io`).
+
+  * Text.Pandoc.Citeproc:
+
+    + Fix moving punctuation before citation notes. This previously worked with
+      regular citations, but not author-in-text citations. Now it works with both.
+
+  * `doc/lua-filters.md`:
+
+    + Correct luacheck URL (#10589, R. N. West).
+    + Add static analysis paragraph to debugging section (#10568, R. N. West).
+    + Add note about extensions handling in `read` and `write` (Albert Krewinkel).
+
+  * `doc/extras.md`:
+
+    + Add entry for pandoc-subfigs (R. N. West).
+    + Update diagram Lua filter URL and description (R. N. West).
+
+  * MANUAL.txt:
+
+    + Add note on using typst to produce pdf/a-2b.
+    + Document top-level-division functionality with Docx (#10579, Andrew Dunning).
+
+  * Raise xml-conduit upper bound.
+
+  * Depend on latest commonmark-pandoc, commonmark-extensions,
+    citeproc, typst.
+
+  * Makefile: make `make binpath` quiet.
+
+## pandoc 3.6.2 (2025-01-12)
+
+  * New input format: `pod` (Evan Silberman). Pod ("Plain old documentation")
+    is a markup languaged used principally to document Perl modules and
+    programs.
+
+  * New reader module Text.Pandoc.Readers.Pod, exporting `readPod`
+    [API change].
+
+  * Docx reader:
+
+    + Support row heads in tables (#9495). Reader: When `w:tblLook` has
+      `w:firstColumn` set (or an equivalent bit mask), we set row heads = 1
+      in the AST.
+    + Read table styles as custom styles when `styles` extension
+      is enabled (#9603).
+
+  * HTML reader:
+
+    + Add size information for font awesome SVG icons (#10134).
+      If the icon has class `fa-fw` or `fa-w16` or `fa-w14`, we add a width
+      attribute to prevent the icon from appearing full-width in PDF or
+      docx output.
+
+  * Djot reader:
+
+    + Use a Span with class "mark" rather than "highlighted" for
+      highlighted text, for consistency with the other pandoc readers and
+      writers.
+
+  * mandoc reader:
+
+    + Add mdoc St for C23 (Evan Silberman).
+
+  * RST reader:
+
+    + Fix handling of underscores (#10497). Fixes a a regression
+      introduced in 3.6.
+
+  * Docx writer:
+
+    + Support row heads in tables (#9495). Writer: set `w:firstColumn` in
+      `w:tblLook` when there are row heads. (Word only allows one, so this
+      is triggered by any number of row heads > 0.)
+
+  * Djot writer:
+
+    + Render a Span with sole class "mark" as highlighted text.
+
+  * Asciidoc writer:
+
+    + Don't emit the class in a span if it's just "mark" (#10511).
+      The "mark" class is used for highlighting, and Asciidoc treats
+      bare `#...#` with no attributes as highlighted text.
+    + Improve escaping (#10385, #2337, #6424).
+
+  * EPUB v2 writer:
+
+    + Fix cover image (#10505).  This is a regression introduced in 3.6.
+
+  * Typst writer:
+
+    + Fix handling of pixel image dimensions (#9945).
+      These are now converted to inches as in the LaTeX writer.
+
+  * Improve error message given when users specify `asciidoc` as input
+    format (#8416, Santiago Zarate).
+
+  * Allow random 1.3.
+
+  * Use texmath 0.12.8.13 (typst improvements).
+
+  * `lua-filters.md`: document `system.os` return values (#10523).
+
+  * `MANUAL.txt`:
+
+    + Improve manual's coverage of custom styles.
+    + Replace LibreOffice PDF documentation link to latest so it links
+      to the latest major release rather than a specific major release
+      (which there are two of every year) (Stéphane Guillou).
+    + Improve links and descriptions for `odt`, `opendocument` (#10518).
+
+## pandoc 3.6.1 (2024-12-23)
+
+  * Allow YAML bibliographies to be arrays of references (#10452).
+    Previously, they had to be YAML objects with a `references` key.
+
+  * Change `--template` to allow use of extensionless templates (#5270).
+    The intent is to allow bash process substitution: e.g.,
+    `--template <(echo "foo")`. Previously pandoc *always* added an
+    extension based on the output format, which caused problems
+    with the absolute filenames used by bash process substitution
+    (e.g. `/dev/fd/11`). Now, if the template has no extension,
+    pandoc will first try to find it without the extension, and
+    then add the extension if it can't be found. So, in general,
+    extensionless templates can now be used. But this has been
+    implemented in a way that should not cause problems for
+    existing uses, unless you are using a template `NAME.FORMAT`
+    but happen to have an extensionless file `NAME` in the template
+    search path.
+
+  * Allow `--shift-heading-level-by=-1` to work in djot in the same way
+    it works for other formats (with the top-level heading being
+    promoted to metadata title) (#10459).  This needed special
+    treatment because of the way djot surrounds sections with Divs.
+
+  * RST reader:
+
+    + Handle explicit reference links (#10484, Evan Silberman).
+      This case was missed when changing the reference link strategy for
+      RST to allow a single pass. (It is a regression in pandoc 3.6.)
+
+  * Markdown reader:
+
+    + Use T.P.URI's `pBase64DataURI` in parsing data URIs (#10075,
+      Evan Silberman and John MacFarlane).
+    + More efficient base64 data URI parsing (#10075, Evan
+      Silberman and John MacFarlane). This should yield dramatic
+      performance improvements for markdown documents containing
+      large data URIs in images.
+
+  * HTML reader:
+
+    + Don't canonicalize data: URIs (#10075). It can be very expensive
+      to call network-uri's URI parser on these.
+
+  * LaTeX reader:
+
+    + Handle `figure*` environment as a figure (#10472).
+
+  * MediaWiki reader:
+
+    + Allow empty quoted attributes (#10490).
+    + Allow cells starting with `+` (#10491).
+
+  * Textile reader:
+
+    + Improve parsing of spans (#9878). The span needs to be separated
+      from its surroundings by spaces. Also, a span can have attributes,
+      which we now attach.
+    + Inline constructors shouldn't trigger if closer is preceded by
+      whitespace (#10414).
+
+  * Docx writer:
+
+    + Put chapters in separate sections, and restart footnotes
+      by section by default (#2773). The main effect of this change is that
+      when `--top-level-division=chapter` is used, chapters will start on
+      a new page and footnote numbering will restart for each chapter.
+      Both of these defaults can be overridden in the reference.docx.
+    + Use styleIds not styleNames for Title, Subtitle, etc.
+      (#10282). This fixes a regression introduced in pandoc 3.5.
+      This change affects the default openxml template as well as the
+      OpenXML writer.
+
+  * Markdown writer:
+
+    + Avoid collapsing of initial/final newline in markdown raw blocks.
+      This makes it easy to write a filter that adds extra blank lines
+      before certain elements (#10477).
+
+  * Mediawiki writer:
+
+    + Escape line-initial characters that would otherwise be interpreted
+      as list starts (#9700).
+
+  * LaTeX writer:
+
+    + Properly handle boolean value for `csquotes` variable (#10403).
+    + Use displayquote for block quotes with `csquotes` (#10456).
+
+  * HTML writer:
+
+    + Avoid calling parseURIString for data URIs (#10075).
+      This was done to determine the "media category," but we can
+      get that directly from the mime component of data: URIs.
+
+  * Typst writer:
+
+    + Properly handle data URIs in images (#10460).
+
+  * LaTeX/Beamer templates:
+
+    + Fix default.beamer `nocite` location (Thomas Hodgson).
+      It must be inside a frame or it is ignored (#10465).
+    + Move nocites from LaTeX preamble to body (#10461, Thomas
+      Hodgson). Putting `\nocite` in the preamble works only with biblatex.
+
+  * Text.Pandoc.Parsing:
+
+    + Correct example in comment on `charsInBalanced` (Evan Silberman).
+
+  * Text.Pandoc.Error:
+
+    + Mention typst in rendering `PandocUnknownWriterError` for `pdf`
+      (Evan Silberman).
+
+  * Text.Pandoc.MediaBag:
+
+    + `insertMedia`: fast path for data URIs. Avoid the slow URI
+      parser from network-uri on large data URIs (#10075).
+
+  * Text.Pandoc.Class:
+
+    + Add shortcut for base64 data URIs in `downloadOrRead` (#10075).
+      This avoids calling the slow URI parser from network-uri on
+      data URIs, instead calling our own parser.
+
+  * Text.Pandoc.MIME:
+
+    + Fix `extensionFromMimeType`. We had a few special cases encoded,
+      but as previously written they wouldn't work properly with
+      modifiers like `;charset=utf-8`.
+
+  * Text.Pandoc.URI:
+
+    + Export `pBase64DataURI`.  Modify `isURI` to use this and avoid
+      calling network-uri's inefficient `parseURI` for data URIs.
+
+  * Text.Pandoc.PDF:
+
+    + Fix temp file extension in `toPdfViaTempFile` (#10468).
+      This fixes a regression in pandoc 3.6, which changed
+      the extension from `html` to `source`. Apparently
+      `wkhtmltopdf` needs it to be `.html`.  So now we have added
+      a parameter to `toPdfViaTempFile` that allows the extension
+      to be specified in a way that is appropriate to the PDF engine
+      used.
+
+  * Lua (Albert Krewinkel):
+
+    + Support more elements as input to `pandoc.utils.stringify`
+      (#10450). Elements of type Caption, Cell, TableHead, and TableFoot
+      can now be stringified.
+    + Add `Caption` constructor to `pandoc` module.
+
+  * Miscellaneous code quality improvements (Joseph C. Sible).
+
+  * Depend on citeproc 0.8.1.2, skylighting and skylighting-core
+    0.14.5.
+
+  * `doc/lua-filters.md: Fix links to constructors (Albert Krewinkel).
+
+
+## pandoc 3.6 (2024-12-07)
+
+  * Add `mdoc` as input format (Evan Silberman). This change
+    introduces a reader for mdoc, a roff-derived semantic markup
+    language for manual pages. This reader has been developed almost
+    exclusively against mandoc's documentation and implementation of
+    mdoc as a reference, and the real-world manual pages tested
+    against are those from the OpenBSD base system. Of ~3500 manuals
+    in mdoc format shipped with a fresh OpenBSD install, 17 cause the
+    mdoc reader to exit with a parse error. Any further chasing of
+    edge cases is deferred to future work.
+
+  * New module: Text.Pandoc.Readers.Mdoc, exporting `readMdoc` [API change].
+
+  * Issue warnings for duplicate YAML metadata keys (#10312).
+
+  * Ensure that `--sandbox` affects `--embed-resources`. Previously it
+    did not (contrary to what was implied by the manual), which means
+    that an image with URL `/etc/passwd` would leak an encoded version
+    of that file to HTML output with `--self-contained` or
+    `--embed-resources`, even if `--sandbox` was used. Thanks to
+    Samuel Mortenson for pointing out the issue.
+
+  * Text.Pandoc.App.OutputSettings: add `sandbox'` function.
+    This computes the sandboxed files from Opt and avoids code repetition.
+
+  * Docx reader:
+
+    + Parse index references as empty spans with attributes (#10171).
+      Attributes included are `entry`, and optionally `bold`, `italic`,
+      `yomi`, `see`.
+    + Don't create multiple paragraphs for title or subtitle (#10359).
+      If there are multiple paragraphs with Title or Subtitle style,
+      use only the first for metadata.
+    + Handle case where Zotero `itemData` has different id from the
+      `citationItem` id.  In this case we use the `citationItemId`
+      in the bibliography as well, overriding the `referenceId`
+      in the itemData (#10366).
+
+  * LaTeX reader:
+
+    + Put parsed minipage in specially marked Div (#10266).
+
+  * HTML reader:
+
+    + Parse footnotes defined by dpub-aria roles (#5294).
+
+  * MediaWiki reader:
+
+    + Fix indented tables with caption (#10390).
+    + Fix parsing of col/rowspan (#6992).
+
+  * Typst reader:
+
+    + Avoid generating empty paragraphs.
+    + Support `underparen`, `overparen`.
+    + Fix `#quote` attribution. If attribution is not present, don't print
+      the `--` (#10320).
+    + Fix typo in unicode code point for em dash (see #10320).
+
+  * Commonmark reader:
+
+    + `implicit_figures` should check for empty caption
+      and not produce an implicit figure in this case (#10429).
+
+  * RST reader:
+
+    + Use a new one-pass parsing strategy. Instead of having an initial pass
+      where we collect reference definitions, we create links with target
+      `##SUBST##something` or `##REF##something` or `##NOTE##something`,
+      and resolve these in a pass over the parsed AST. This allows us to handle
+      link references that are not at the top level (#10281).
+    + Ignore newlines in URL in explicit link (#10279).
+    + Handle block level substitutions.
+    + Support `:file:` on raw directive (#8584).
+    + Implement option lists (#10318).
+    + Avoid putting metadata in Para (#7766). Create MetaInlines when possible,
+      just as with markdown input. MetaBlocks is still used when there are
+      multiple paragraphs or non-paragraph content.
+      This change also affects field lists.
+    + Fix linked substitutions (#6588). E.g. `|Python|_`.
+    + Support inline anchors (#9196).
+    + Explicit links define references (#5081). For example,
+      ``Go to `g`_ `g <www.example.com>`_.`` should produce two links to
+      www.example.com.
+
+  * EPUB writer:
+
+    + Use standardized filename for cover image instead of the original name
+      (#10404). This avoids problems with e.g. filenames containing spaces.
+
+  * Markdown writer:
+
+    + Issue INFO warning when not rendering table, e.g., when `raw_html` is
+      disabled and the table can't be fit into a supported markdown table
+      format (#10407).
+    + Respect empty LineBlock lines in `plain` output (Evan Silberman).
+      The plain writer behaved as a markdown variant with `Ext_line_blocks`
+      turned off, and so empty lines in a line block would get eliminated.
+
+  * LaTeX writer:
+
+    Ensure that beamer footnotes go on frame, not column (#5769).
+
+  * HTML writer:
+
+    + Unwrap empty incremental divs (#10328, Albert Krewinkel).
+      Divs are unwrapped if the only purpose of the div seems to be to control
+      whether lists are presented incrementally on slides.
+
+  * Typst writer:
+
+    + Make template sensitive to a `page-numbering` variable (#10370).
+      This can be set to an empty string (or, in metadata, to false) for
+      no page numbers.
+    + Make `smart` extension work (#10271). If `smart` is not enabled, a command
+      in the default template will disable smartquote substitutions.
+      When `smart` is enabled, render curly apostrophes as straight
+      and escape straight apostrophes. When `smart` is disabled,
+      render curly apostrophes as curly and don't escape straight
+      apostrophes. Similarly for quotes, em and en dashes. This should
+      give more idiomatic typst output, with fewer unnecessary
+      escapes.
+
+  * ANSI writer:
+
+    + Respect empty LineBlock lines (Evan Silberman).
+
+  * JATS writer:
+
+    + Correct spelling of suppress attribute (#10350, Andreas Deininger).
+
+  * Typst template:
+
+    + Remove `definitions.typst` partial.
+    + Remove unnecessary definition of `endnote`.
+    + Incorporate the one remaining definition into `default.typst`.
+    + Use typst 0.12 code for two column layout (#10294, Luis Rivera).
+    + Note: the new templates presuppose typst 0.12; if you try to use an
+      earlier version of typst, an error will be raised.
+
+  * LaTeX/Beamer template:
+
+    + Split `fonts.latex` partial into two parts: `fonts.latex` and
+      `font-settings.latex`.
+    + In beamer template, load beamer theme between `fonts.latex` and
+      `font-settings.latex`. This allows a theme (such as metropolis)
+      to set its own default font, while still allowing the user to
+      override it. This fixes a regression in pandoc 3.5 (#10297).
+    + Note: Users who have custom templates based on pandoc 3.5 templates will
+      need to add `font-settings.latex()` after `fonts.latex()` in the
+      latex template. In a beamer template, the beamer theme-setting
+      code needs to be moved between these two partials.
+
+  * ConTeXt template: Ensure that font names don't wrap (#10305).
+
+  * `epub.css`: remove background-color (#10264, Suraj Patil).
+    With this greyish background color, epubs look bad on a Kindle (#10263).
+
+  * Text.Pandoc.ImageSize: add WebP support (Evan Silberman, #10397).
+    Add `Webp` constructor on ImageType [API change].
+
+  * Text.Pandoc.Readers.Roff and a new unexported module
+    Text.Pandoc.Readers.Roff.Escape: parameterize Roff
+    escaping (Evan Silberman) [API change]. This allows code to
+    be reused between the mdoc and man readers, despite the
+    differing Token types.
+
+  * Text.Pandoc.PDF:
+
+    + PDF via LaTeX: always do max runs if `toc` is present (#10308).
+      The old method (checking to see if toc hash had changed) is not
+      completely reliable.
+    + Use `.source` extension, not `.html`, in `toPdfViaTempFile` (#10314).
+
+  * Text.Pandoc.Logging: add `YamlWarning` constructor to `LogMessage`
+    [API change] (#10312).
+
+  * Text.Pandoc.Format: remove duplicate typst entry (#10388, Caleb Mclennan).
+
+  * Fix a typo in the `ua.yaml` localization for 'See' (Jens).
+
+  * Lua subsystem (Albert Krewinkel):
+
+    + Remove prefixes from Lua type names (#8574). Lua type names were
+      inconsistent with regard to the use of prefixes; all prefixes
+      are removed now, and Lua types now have the same name as the
+      Haskell types. The use of app-specific prefixes is suggested by
+      the Lua manual to avoid collisions. However, this shouldn't be a
+      problem with pandoc, as it cannot be used as a Lua package.
+
+  * doc/libraries.md: Add newly developed Haskell packages.
+    Sort list alphabetically (Albert Krewinkel).
+
+  * doc/lua-filters.md: document `pandoc.List:iter` method (Albert Krewinkel).
+    List objects have a new function `iter` that returns an iterator
+    function that returns the next list item on each call.
+
+  * MANUAL.txt:
+
+    + Clarify what the example of YAML EPUB metadata shows (#10405).
+    + Fix typo in template syntax (#10265, Pascal Wagler).
+    + Update manual with information on openxml template (#10273).
+    + Clarify that `--variable` can only assign string values (#10298).
+
+  * Fix comments in TEI writer referring to DocBook (#10430, Evan Silberman).
+
+  * Fix several typos in documentation (#10349, Andreas Deininger).
+
+  * Allow Diff 1.0.
+
+  * Add font-settings.latex partial to pandoc.cabal (#10379).
+
+  * Bump upper bound for data-default.
+
+  * Use latest typst, texmath, pandoc-lua-marshal, commonmark-pandoc,
+    commonmark-extensions, skylighting, skylighting-format-blaze-html.
+
+
+## pandoc 3.5 (2024-10-04)
+
+  * Add command-line options `--list-of-figures/--lof` and
+    `--list-of-tables/--lot` (#10029, Akash Patel).
+    Only docx, latex, and context are affected by these options currently.
+    Setting the `lof` and `lot` variables will also work for the formats
+    that are currently supported.
+
+  * Defaults files:  interpolation of environment variables now
+    works for `to` and `from` fields (#8024). This is needed because
+    these files can contain paths of custom readers/writers.
+
+  * Docx reader:
+
+    + Reset lists after headers in same list `numId` (#10258).
+      To accomplish this, we add a Heading constructor to BodyPart and
+      include on it all the information list items have.
+
+  * DocBook reader:
+
+    + Parse id, class, and tabstyle on tables (#10181, Erik Rask).
+      Add parsing of id (xml:id), class, and tabstyle XML attributes
+      for table and informaltable in the DocBook reader.
+      The tabstyle value is put in the 'custom-style' attribute.
+
+  * Dokuwiki reader:
+
+    + Be more forgiving about misaligned lists, like dokuwiki itself (#8863).
+    + Improve blockquote parsing in dokuwiki. Allow for quoted code blocks.
+    + Enable smart extension.
+    + Properly parse `--` and `---` as dashes.
+    + Fix block quote behavior (#6461). Blockquotes are not really block
+      containers in DokuWiki; the lines are interpreted literally (so,
+      e.g., you can't start a list), and line breaks are added at the ends.
+
+  * EPUB reader:
+
+    + Fix links to other files in the EPUB, making them internal links
+      to a fragment derived from the filename (#10207).  There was
+      already code to handle links like `#foo`, but not to handle links
+      like `ch0001.html#foo`.
+
+  * LaTeX reader:
+
+    + Add em, ex, px, mu to list of units for dimension args (#10212).
+
+  * ANSI writer:
+
+    + Fix subscripts (Evan Silberman).
+
+  * DokuWiki writer:
+
+    + Don't emit `<HTML>` tags (#7413). The use of these tags is now
+      strongly discouraged for security reasons, and will be removed.
+      We previously used them as a fallback for lists that could not
+      be represented using DokuWiki syntax, e.g. ordered lists with
+      fancy numbers or lists with multiple blocks in their items.
+      We also used them for block quotes with multiple blocks as
+      their contents. We now use the `<WRAP>` syntax (from the optional
+      WRAP plugin) to handle lists with multiple blocks as their contents.
+      A new method of handling block quotes with complex contents
+      has the side benefit of also handling nested block quotes,
+      which weren't supported before.
+      `<HTML>` and `<html>` tags are only for raw HTML blocks and
+      inlines, and only if the `raw_html` extension is enabled. (It is
+      now a valid extension for `dokuwiki`, though off by default.)
+
+  * Docx writer:
+
+    + Support `--list-of-figures` and `--list-of-tables` (or `lof` and
+      `lot` variables) (Akash Patel).
+
+  * HTML writer:
+
+    + Don't emit missing title/lang warnings if templates does not
+      contain the `pagetitle` or `lang` variables respectively (#9370).
+
+  * LaTeX writer:
+
+    + Better fix for lists in definition lists (#10241).
+      In commit a26ec96d89ccf532f7bca7591c96ba30d8544e4a we added an
+      empty `\item[]` to the beginning of a list that occurs first
+      in a definition list, to avoid having one item on the line with
+      the label. This gave bad results in some cases (#10241) and there
+      is a more idiomatic solution anyway: using `\hfill`.
+    + Avoid error on `refs` div with empty citations (#10185).
+      If there are no citations, don't emit an empty CSLReferences environment.
+
+  * RST writer:
+
+    + Change bullet list hang from 3 to 2. This accords with the style in
+      the RST reference docs.
+    + Handle cases where indented context starts with block quote (#10236).
+      In these cases we emit an empty comment to fix the point from
+      which indentation is measured; otherwise the block quote is not
+      parsed as a block quote. This affects list items and admonitions.
+    + Don't enclose the list table in a `.. table::`; this leads to
+      doubled captions (#10226).
+    + Fix alignment of list table items corresponding to cells (#10227).
+
+  * JATS template:
+
+    + Support `floats-group` (Albert Krewinkel, see #10196).
+      The content of the `floats-group` variable is now rendered in a
+      `<floats-group>` element when using the *publishing* or *archiving* tag
+      sets.
+
+  * LaTeX and Beamer templates:
+
+    + Split old default.latex into two templates, `default.latex` and
+      `default.beamer`, factoring common parts into partials:
+      `fonts.latex`, `common.latex`, `passoptions.latex`,
+      `hypersetup.latex`, `after-header-includes.latex`.
+    + Make `default.beamer` the default template for beamer.
+    + Add `shorttitle`, `shortsubtitle`, `shortauthor`, `shortinstitute`,
+      `shortdate` variables to beamer template (#10248, Thomas Hodgson).
+    + Make `--number-sections` work with beamer (#12045, Thomas Hodgson).
+    + Support a list of images for `titlegraphic` in beamer template
+      (#10246, Thomas Hodgson). Title graphic options will be
+      applied to each title graphic. Images will be separated by `\enspace`.
+    + Beamer theme options (#10243)
+    + Add theme options to beamer template: `colorthemeoptions`,
+      `fontthemeoptions`, `innerthemeoptions`, `outerthemeoptions` (#10243,
+      Thomas Hodgson).
+    + Don't load amsmath, amssym in beamer template. These are loaded by
+      beamer automatically.
+
+  * Text.Pandoc.SelfContained:
+
+    + Improve handling of links to remote CSS (#10261).
+
+  * Text.Pandoc.Class:
+
+    + Allow extracting `data:` URIs even in PandocPure (`--sandbox`)
+      (#10249).
+    + Export `extractURIData` [API change].
+
+  * Text.Pandoc.PDF:
+
+    + Read `.toc` and `.log` files from output directory (#10186).
+      When this is different from the input directory, this is
+      where `.toc` and `.log` files are written.
+
+  * Text.Pandoc.Shared:
+
+    + Modify `addPandocAttributes` for changes in commonmark-pandoc.
+      The new commonmark-pandoc version automatically adds the
+      attribute `wrapper="1"` on all Divs and Spans that
+      are introduced just as containers for attributes that belong
+      properly to their contents.  So we don't need to add the
+      attribute here. This gives much better results in some cases.
+      Previously the wrapper attribute was being added even for
+      explicit Divs and Spans in djot, but it is not needed in these cases.
+
+  * Text.Pandoc.Options:
+
+    + Add `writerListOfFigures` and `writerListOfTables` fields
+      to `WriterOptions` (#8245, Akash Patel). [API change]
+
+  * Text.Pandoc.App:
+
+    + Add `optListOfFigures` and `optListOfTables` to `Opt` (#8245)
+      [API change].
+
+  * Lua subsystem (Albert Krewinkel):
+
+    + Update List module (#9835). The module now comes with a method
+      `:at(index[, def])` that allows to access indices, accepts
+      negative indices to count from the end, and will return the
+      `def` value as a default if the list has no item at the given position.
+      Furthermore, the list constructor `pandoc.List` now accepts iterators.
+      E.g., `pandoc.List(text:gmatch '%S+')` returns the list of words
+      in `text`.
+    + Support character styling via `pandoc.layout`. The `Doc` values
+      produced and handled by the `pandoc.layout` module can now
+      be styled using `bold`, `italic`, `underlined`, or `strikeout`. The
+      style is ignored in normal rendering, but becomes visible when
+      rendering to ANSI output. The `pandoc.layout.render` function
+      now takes a third parameter that defines the output style,
+      either *plain* or *ansi*.
+    + It is now possible to return a single filter from a filter file, e.g.
+      ``` lua
+      -- Switch single- and double quotes
+      return {
+        Quoted = function (q)
+          elem.quotetype = elem.quotetype == 'SingleQuote'
+            and 'DoubleQuote' or 'SingleQuote'
+          return elem
+        end
+      }
+      ```
+      The filter must not contain numerical indexes, or it might be treated
+      as a list of filters.
+    + Add `list_of_figures` and `list_of_tables` to writer options
+      (Akash Patel).
+
+  * Use latest releases of commonmark, commonmark-pandoc, texmath, djot.
+
+  * Stop depending on package SHA (Albert Krewinkel). Use `crypton` instead.
+
+  * `linux/make_artifacts.sh`: add riscv64 support (Olivier Benz).
+
+  * Fix invalid XML in `test/docx/normalize.docx` (#10242).
+
+  * `doc/lua-filters.md`: list functions in `pandoc.utils` alphabetically
+    (Albert Krewinkel).
+
+  * MANUAL.txt:
+
+    + Clarify  use of `beamerarticle` variable (#10250).
+    + Add clarification to address user issues like #6704 (Yehuda Katz).
+
+## pandoc 3.4 (2024-09-09)
+
+  * New output format: `ansi` (for formatted console output) (Evan Silberman).
+    Most Pandoc elements are supported and printed in a reasonable way, if
+    not always ideally. This version does no detection of terminal
+    capabilities, nor does it fall back to different output styles for
+    less-capable terminals.
+
+  * Add command line options `--table-caption-position` and
+    `--figure-caption-position`. These allow the user to specify whether
+    to put captions above or below tables and figures, respectively.
+    The following output formats are supported: HTML (and related such
+    as EPUB), LaTeX (and Beamer), Docx, ODT/OpenDocument, Typst.
+
+  * Change default `--pdf-engine` via HTML to WeasyPrint (#10142).
+    `wkhtmltopdf` is deprecated.  `weasyprint` is the easiest-to-install,
+    maintained alternative.  For better results, one might prefer
+    `pagedjs-cli`.
+
+  * Org reader:
+
+    + Fix parsing of src blocks with an `-i` flag (#10071, Albert Krewinkel).
+      Tabs are now preserved in the contents of *src* blocks if the the block
+      has the `-i` flag.
+
+  * RTF reader:
+
+    + Handle images inside `shp` contexts (#10145).
+
+  * RST reader:
+
+    + Improve simple table support (#10093). Multiline rows occur
+      only when the *first* cell is empty; we were previously treating
+      lines with *any* empty cell as row continuations. In addition, we
+      no longer wrap multiline cells in Para if they can be represented
+      as Plain. This is consistent with docutils behavior.
+
+  * LaTeX reader:
+
+    + Math environments don't have bracketed options (#10160).
+    + Parse nested tabular environments (#4746).
+
+  * Typst reader:
+
+    + Change how "block" elements are handled. Previously they were
+      always parsed as divs.  But actually they can occur in some "inline"
+      contexts.  Now we first try to parse them as inlines, and only as
+      blocks if that fails.  A surrounding Div or Span element is added
+      only if there is an identifier.
+
+  * HTML reader:
+
+    + Only parse main element's contents (if present) (#10140).
+      If main has an id or class, we include a div with that id or class;
+      otherwise just the contents.
+    + Read TeX annotation in MathML content if present (#9971).
+    + Better handle KaTeX-generated math (#9971). KaTeX emits the mathml
+      followed by a span with an HTML fallback. Previously pandoc was
+      converting both.  We now ignore the HTML fallback span, marked
+      with class `katex-html`.
+
+  * Docx reader:
+
+    + Add "SuppressAuthor" and "AuthorOnly" to citationMode
+      when `+citations` is used (thomjur).
+
+  * New module: Text.Pandoc.Writers.ANSI [API change] (Evan Silberman).
+
+  * Docx writer:
+
+    + Support `custom-style` attribute for docx table (Sebbones).
+    + Support `--number-offsets`.
+    + Make table/figure rendering sensitive to caption position settings.
+
+  * OpenDocument writer:
+
+    + Make table/figure rendering sensitive to caption position settings.
+
+  * Typst writer/template:
+
+    + Implement figure caption positions by triggering a show rule in
+      the default template, which determines caption positions for
+      figures and tables globally.
+    + Don't include trailing semicolon after `@` style citations with suffixes
+      (#10148).
+    + Template: move header-includes before show doc (#9996, Gordon Woodhull).
+
+  * LaTeX writer:
+
+    + Make table/figure rendering sensitive to caption position settings (#5116).
+    + Preserve locator labels with `--natbib` (#10057).
+
+  * HTML writer/template:
+
+    + Make `<figcaption>` placement sensitive to caption position
+      settings. For tables, `<caption>` must be the first element, and
+      positioning is determined by CSS, for here we set a variable
+      which the default template is sensitive to.
+    + Use `makeSectionsWithOffsets` for `writerNumberOffsets`,
+      instead of the old, inefficient code.
+    + Don't add doc-biblioref role to every link in a citation;
+      only to links to the bibliography (#10156).
+    + Add `data-` when rendering `label` attribute (#10048).
+
+  * Markdown writer:
+
+    + Avoid emitting markdown caption if table has fallen back to raw HTML,
+      which will then contain a `<caption>` tag (#10094).
+    + Make math sensitive to `tex_math_gfm` extension (#9121).
+      This means that in GFM output, the "new style" math will be used
+      by default, e.g.
+
+          $`x=y`$
+
+          ```math
+          x = y
+          ```
+
+      To defeat this and get the older behavior, namely
+
+          $x=y$
+
+          $$x=y$$
+
+      one could use `-t gfm-tex_math_gfm`.
+
+  * AsciiDoc writer:
+
+    + Add `link:` prefix when needed (#10105). AsciiDoc requires it
+      except for `http`, `https`, `irc`, `mailto`, `ftp` schemes (#10105).
+    + Preserve original base level (#10062). We used to normalize so
+      that the base level is always 1, but asciidoc no longer seems
+      to care about that, and the behavior creates difficulties when
+      we are converting fragments.
+    + Don't emit empty figure caption (#10047).
+
+  * ODT writer:
+
+    + Add TableCaption to styles.xml (#10058, Ian Max Andolina).
+
+  * LaTeX template:
+
+    + Fix wrong beamer color in (sub)section page (Jonathan).
+
+  * Text.Pandoc.Options:
+
+    + Add `CaptionPosition` and new `WriterOptions` fields
+      `writerFigureCaptionPosition` and `writerTableCaptionPosition`
+      [API change].
+
+  * Text.Pandoc.Opt:
+
+    + Change default for optNumberOffset to `[]`. This behaves the same as
+      `[0,0,0,0,0]`.
+    + Add `Opt` fields `optFigureCaptionPosition` and
+      `optTableCaptionPosition` [API change].
+
+  * Text.Pandoc.Format: change `formatFromFilePaths` so that it is
+    smarter about URLs.  URLs are parsed, and we take the format from
+    the path component, if present (#10141). This means that
+    `https://emacs.org/` will be treated as HTML, while
+    `https://emacs.org/sample.org` will be treated as Org.
+
+  * Text.Pandoc.URI:
+
+    + Add unofficial `gemini:` to list of URI schemes (Pau RE).
+
+  * Text.Pandoc.Shared:
+
+    + Add `makeSectionsWithOffsets` [API change].
+    + Remove `stripEmptyParagraphs [API change] (Albert Krewinkel).
+      This function is no longer used.
+
+  * Text.Pandoc.Highlighting: Expose `formatANSI` [API change]
+    (Evan Silberman).
+
+  * Text.Pandoc.Writers.Shared: export `to{Sub,Super}scriptInline`
+    [API change] (Evan Silberman).
+
+  * Remove use of partial functions (e.g. `head`) in code.
+
+  * Use latest skylighting-core, skylighting, doclayout, texmath, typst.
+
+  * pandoc-lua-engine: Add accessors for several writer options, including
+    some that were added in previous releases.
+
+  * pandoc-server: Initialize some missing fields in WriterOptions:
+    `writerEpubTitlePage`, `writerChunkTemplate`, `writerListTables`,
+    `writerFigureCaptionPosition`, `writerTableCaptionPosition`.
+
+  * CONTRIBUTING.md: Summarize steps for adding a new cli option.
+
+  * MANUAL.txt:
+
+    + Clarify that the `--number-offset` option should only
+      directly affect numbering of the first section heading in
+      a document; subsequent headings will increment normally.
+    + Fix asciidoc link (#10039).
+    + Fix CSL Docs broken link (#10100, Tristano Ajmone).
+    + Document the use of `luatexja` when CJKmainfont is used with lualatex
+      (#3873, Kolen Cheung).
+    + Add a `citations` (typst) section to the manual (#9127).
+    + Clarify that `citations` affects both input and output for `org`.
+    + Add note on `--citeproc` that you may need to disable `citations`
+      extension on the output format (e.g., `-t markdown-citations`) to
+      see the rendered citation (#9127, #10012).
+
+  * INSTALL.md — reorganise info on static binaries and add conda-forge
+    install options (#10098, #10069, Ian Max Andolina).
+
+## pandoc 3.3 (2024-07-28)
+
+  * New cli option: `--link-images`.  This causes images to be linked
+    rather than embedded in ODT.
+
+  * Allow `--number-sections` to take an optional `true|false` argument.
+
+  * RTF reader:
+
+    + Handle `\*\shppict` without dropping image (#10025).
+
+  * TWiki Reader:
+
+    + Recognize WikiWords as internal links (#9941).
+    + Avoid partial function.
+
+  * Typst reader:
+
+    + Ignore 'pad' and just parse its body (#9958).
+    + Use typst 0.5.0.5. Fixes parsing of equations like `$1.$`.
+
+  * Docx writer:
+
+    + Fix regression with nested lists (#9994). The bug affects e.g.
+      ordered lists with bullet sublists; after the sublist the top-level
+      list reverts to bullets instead of being properly numbered.
+      This is a regression introduced in version 3.2.1.
+
+  * BibTeX writer:
+
+    + Ensure that "literal" names are enclosed in braces (#9987).
+
+  * Man writer:
+
+    + Use default middle header when metadata does not include `header`
+      (#9943).  This change causes pandoc to omit the middle
+      header parameter when `header` is not set, rather than
+      emitting `""`.  The parameter is optional and man will use
+      a default based on the section if it is not specified.
+
+  * HTML templates: don't load polyfill (#9918).
+    This was added in a period when MathJaX required polyfill.
+    MathJaX no longer recommends this and polyfill should no
+    longer be necessary on any reasonably modern browser.
+
+  * Translations:
+
+    + Add `ua.yaml` (Jens Oehlschlägel).
+    + Add a script (`tools/update-translations.py`) and Makefile
+      target (`update-translations`) to update translation data
+      automatically from babel and polyglossia upstream
+      (Stephen Huan).
+    + Use this script to update language data, increasing the number
+      of languages we cover (Stephen Huan).  Fix a few small bugs in
+      existing translations.
+
+  * Fix some mistakes with Japanese language code (#9938).
+    In several places we were mistakenly assuming that the BCP 47 code for
+    Japanese language was `jp`.  It is `ja`.
+
+  * Text.Pandoc.Options:
+
+    + New field in WriterOptions: `writerLinkImages` [API change] (#9815).
+
+  * Text.Pandoc.App.Opt:
+
+    + New field in Opt: `optLinkImages` [API change] (#9815).
+
+  * Lua subsystem:
+
+    + Keep `lpeg` and `re` as "loaded" modules (Albert Krewinkel).
+      The modules `lpeg` and `re` are now treated as if they had been
+      loaded with `require`. Previously the modules were only assigned
+      to global values, but could be loaded again via `require`,
+      thereby allowing to use a system-wide installation. However, this
+      proved to be confusing.
+
+      The old behavior can be restored by adding the following lines to
+      the top of Lua scripts, or to the `init.lua` in the data dir.
+
+          debug.registry()['_LOADED'].lpeg = nil
+          debug.registry()['_LOADED'].re = nil
+
+  * `pandoc-cli`: Include pandoc copyright in Lua version info (Albert
+    Krewinkel).
+
+  * `pandoc-cli`: Refer printing of version info to the Lua interpreter
+    (Albert Krewinkel). The Lua interpreter no longer terminates when
+    called with `-v` or `--version` arguments, thus improving
+    compatibility with the default `lua` interpreter program.
+
+  * Avoid partial functions in JATS reader, DocBook writer, Haddock reader.
+
+  * Allow tls 2.1.x.
+
+  * MANUAL.txt:
+
+    + Make documentation of extensions clearer (#9060).
+    + Fix section level for two Extensions entries.
+
+  * lua-filters.md: Partially autogenerate docs for module `pandoc`
+    (Albert Krewinkel). The documentation system isn't powerful enough to
+    generate the full documentation automatically.
+
+## pandoc 3.2.1 (2024-06-24)
+
+  * Fix `gfm_auto_identifiers` to replace emojis with their aliases,
+    as documented (#9876).
+
+  * CSV reader:
+
+    + Turn line breaks into LineBreaks not SoftBreaks (#9797).
+
+  * Docx reader:
+
+    + Support task lists (#8211).
+    + Fix a small bug in parsing delimiters in numbered lists,
+      which led to the default delimiter being used wrongly in some cases.
+    + Improve handling of captions.
+      - Turn captioned images into Figure elements. Closes #9391.
+      - Improve the logic for associating elements with captions (#9358).
+      - Ensure that captions that can't be associated with an
+        element aren't just silently dropped (#9610).
+    + Support HorizontalRule. We support both pandoc-style and the style
+      described on a Microsoft support page, an empty paragraph with
+      a bottom border (#6285).
+    + React to `"left"` value on `jc` attribute.
+    + Handle column and cell alignments (#8551). We take the column alignments
+      from the first body row.
+    + Fix a bug that caused comments inside insertions or deletions
+      to be ignored (#9833).
+
+  * HTML reader:
+
+    + Better handle non-`li` elements in `ul` and `ol` (#9809).
+      For example, a `p` after a closed `li` will be incorporated into
+      the previous `li`. This mirrors what browsers do with this
+      invalid HTML.
+
+  * LaTeX reader:
+
+    + Fix parsing of dimensions beginning with `.`, e.g. `\kern.1pt` (#9902).
+
+  * Markdown reader:
+
+    + Allow author-only textual citations (#7219). E.g. `-@reese2002`
+      outside of brackets.
+
+  * RST reader:
+
+    + Tighten up rules for when emphasis can start (#9805).
+    + Support `:cite:` role with citeproc (#9904). A subset of the
+      functionality of the sphinxcontrib-bibtex extension to Sphinx
+      is supported.
+
+  * Textile reader:
+
+    + Don't let spans begin right after a symbol (#9878).
+
+  * Typst reader:
+
+    + Fix an incomplete pattern match (#9807).
+    + Handle inline bodies ending in a parbreak. E.g.
+      ```
+      `#strong[
+      test
+      ]
+      ```
+
+  * ConTeXt template: remove `\setupbackend[export=yes]` (#9820).
+
+  * Docx writer:
+
+    + Allow OpenXML templates to be used with `docx` (#8338, #9069, #7256,
+      #2928). The `--reference-doc` option allows customization of styles in
+      docx output, but it does not allow one to adjust the content of the output
+      (e.g., changing the order in which metadata, the table of contents,
+      and the body of the document are displayed), or adding boilerplate
+      text before or after the document body.  For these changes, one can
+      now use `--template` with an OpenXML template.  (See the default
+      `openxml` template for a sample.) `--include-before-body` and
+      `--include-after-body` can also now be used with `docx` output.
+      The included files must be OpenXML fragments suitable for
+      inclusion in the document body.
+    + New unexported module Text.Pandoc.Writers.Docx.OpenXML.
+    + Omit `jc` attribute on table cells with AlignDefault (#5662).
+    + Better formatting for task lists. Task lists are now properly
+      formatted, with no bullet (#5198).
+    + Replace an expensive generic traverse to remove Space elements,
+      for better performance.
+    + Wrap figures with `id` in a bookmark (#8662).
+    + Add eastAsia font hints to `w:r` (#9817). We do this when the text
+      in the run contains any CJK characters. This ensures that ambiguous
+      code points (e.g. quotation marks) will be represented as "wide"
+      characters when together with CJK characters.
+    + Clean up Abstract Title and Subtitle in default reference docx.
+      Center Subtitle, remove color.
+
+  * HTML writer:
+
+    + Ensure URI escaping needed for `html4` (#9905).
+      Unicode characters need not be escaped for html5, and still won't be.
+    + Don't emit unnecessary classes in HTML tables (#9325, Thomas Soeiro).
+      Pandoc used to emit a `header` class on the `tr` element that forms
+      the table header. This is no longer needed, because `head > tr` will
+      do the same thing. Similarly, pandoc used to emit `even` and `odd`
+      classes on `tr`s, allowing striped styling.  This is no longer needed,
+      because one can use e.g. `tbody tr:nth-child(2n)`.
+      Compatibility warning:  users who relied on these classes to style
+      tables may need to adjust their CSS.
+
+  * JATS writer:
+
+    + Support `supplementary-material` in metadata for `jats_articlepublishing`
+      (#9818).
+
+  * LaTeX writer:
+
+    + New method for ensuring images don't overflow (#9660).
+      Previously we relied on graphicx internals and made global
+      changes to Gin to force images to be resized if they exceed
+      textwidth.  This approach is brittle and caused problems
+      with `\includesvg` (see #9660). The new approach uses a new macro
+      `\pandocbounded` that is now defined in the LaTeX template.
+      (Thanks here to Falk Hanisch in https://github.com/mrpiggi/svg/issues/60.)
+      The LaTeX writer has been changed to enclose `\includegraphics`
+      and `\includesvg` commands in this macro when they don't explicitly
+      specify a width or height. In addition, the writer now adds
+      `keepaspectratio` to the `\includegraphics` or `\includesvg`
+      options if `height` is specified without width, or vice versa.
+      Previously, this was set in the preamble as a global option.
+      Users should attend to the following compatibility issues:
+      - If custom templates are used with the new LaTeX writer, they will have
+        to be updated to include the new `\pandocbounded` macro, or an error
+        will be raised because of the undefined macro.
+      - Documents that specify explicit dimensions for an image may render
+        differently, if the dimensions are greater than the line width or
+        page height. Previously pandoc would shrink these images to fit,
+        but the new behavior takes the specified dimensions literally.
+        In addition, pandoc previously always enforced `keepaspectratio`,
+        even when width and height were both specified, so images with
+        width and height specified that do not conform to their intrinsic
+        aspect ratio will appear differently.
+    + Task lists must be unordered (#9185).
+    + Specify language option for `selnolig` and only include it if
+      `english` or `german` is used (#9863). (This includes changes to the
+      LaTeX template.) This should restore proper ligature suppression when
+      lualatex is used.
+    + Fix `--toc-depth` with beamer output (#9861). Previously only top-level
+      sections were ever included in the TOC, regardless of the setting of
+      `--toc-depth`.
+    + Use `\linewidth` instead of `\columnwidth` or `\textwidth`
+      for resizing figures, table cells, etc. in LaTeX (#9775).
+      `\linewidth`, unlike the others, is sensitive to indented environments
+      like lists.
+
+  * LaTeX template: put `babel-lang` in options to beamer (#9868).
+    This is required to make beamer use proper localized terms for
+    things like "Section."
+
+  * Markdown writer:
+
+    + Don't print extra caption when using `implicit_figures`.
+    + Ensure blank line after HTML blocks in commonmark-based formats (#9792).
+    + Fix bug rendering block quotes in lists (#9908).
+
+  * Texinfo writer:
+
+    + Ensure proper escaping in all node/link contexts.
+    + Target node rather than anchor when possible in internal links.
+    + Remove illegal characters from internal link anchors (#6177).
+    + Use two commas not one in `@ref`.
+    + Don't add anchors to headings. We don't need them, now that we
+      make internal links use the node.
+    + Avoid duplicate node names.
+    + Improve menus. Properly handle the case where the node name is
+      different from the descriptive title.
+
+  * Texinfo template: add variables for filename and version.
+
+  * Typst writer:
+
+    + Support '.typst:no-figure' and 'typst:figure:kind=kind' attributes
+      (#9778, Carlos Scheidegger). This extends support for fine-grained
+      properties in Typst. If the `typst:no-figure` class is present on a
+      Table, the table will not be placed in a figure. If the
+      `typst:figure:kind` attribute is present, its value will be used
+      for the figure's `kind` (#9777). These features are documented in
+      `doc/typst-property-output.md`.
+
+  * Typst template:
+
+    + Add subtitle (#9747, Mickaël Canouil).
+    + Use content rather than string for title, author, date, email (#9823).
+      This allows formatting in title, author, date, and email fields.
+      Since the PDF metadata requires a string, and typst only
+      converts the title to a string (not the authors), we use
+
+  * Textile writer:
+
+    + Get rid of header, odd, even classes on `tr` (#9376).
+
+  * Text.Pandoc.Class:
+
+    + `fillMediaBag`: Convert IOErrors to warnings when fetching absolute
+       paths (#9859, Albert Krewinkel).  This will allow many conversions that
+       would have failed with an error to succeed (albeit without images or
+       other needed resources).
+
+  * Text.Pandoc.ImageSize:
+
+    + Don't prefer exif width/height when they conflict with image
+      width/height (#9871).  That was a mistaken call in #6936.
+      Usually when these values disagree, it is because the image
+      has been resized by a tool that leaves the original exif values
+      the same, so the width/height metadata are more likely to be
+      correct that exif width/height.
+
+  * Text.Pandoc.SelfContained:
+
+    + Strip CRs from XML before base64 encoding for data URI
+      (so tests can work on Windows).
+    + Only create `<svg>` elements for SVG images when the image has
+      the class `inline-svg`. Otherwise just use a `data` URI as we do
+      with other images (#9787).
+
+  * Lua subsystem (Albert Krewinkel):
+
+    + Split Init module into more modules. The module has grown unwieldy and
+      is therefore split into three internal Haskell modules, `Init`,
+      `Module`, and `Run`.
+    + Add function `pandoc.utils.run_lua_filter` (#9803).
+    + Add function `pandoc.template.get` (#9854, co-authored by Carsten Gips).
+      The function allows to specify a template with the same argument value
+      that would be used with the `--template` command line parameter.
+    + Keep CommonState object in the registry. The state is an internal
+      value and should be treated as such. The `PANDOC_STATE` global is
+      merely a copy; unsetting the global no longer breaks the Lua engine.
+    + Allow passing an environment to `run_lua_filter`.
+      The default is now to use a *copy* of the global environment when running
+      a filter; this ensures better separation when `run_lua_filter` is used
+      multiple times. A custom environment can be specified via the
+      optional third parameter.
+    + Set `pandoc.List` as default metatable for JSON lists (#9834).
+      Lists created by `pandoc.json.decode` now behave like lists generated
+      via `pandoc.List`. This also ensures that `pandoc.List` tables are
+      encoded as JSON arrays when passed to `pandoc.json.encode`.
+
+  * Text.Pandoc.Writers.Shared: export `toTaskListItem` [API change].
+
+  * Add unexported module Text.Pandoc.Char. This exports `isCJK`.
+    Use this instead of locally defined `isCJK` in T.P.Readers.MediaWiki.
+
+  * MANUAL.txt:
+
+    + Remove false claim that Lua mode does not support `-i` (#9757,
+      Ian Max Andolina).
+    + Use level-3 headings for extensions (to avoid gaps).
+    + Add anchor for tagging extension.
+    + Remove explicit referencess to generate anchors.
+      These will be linkified automatically.
+    + Fixed links to `option--reference-doc`.
+    + Add a note that column widths aren't supported in pptx for Divs
+      with class `columns` (#9890).
+    + Fix alerts example (#9826, Ian Max Andolina).
+    + Fix markup of `babelfonts` example code (Albert Krewinkel).
+
+  * `doc/custom-writers.md`:
+
+    + Fix usage of Template in example (Albert Krewinkel).
+    + Document the separator arg of `Writer.Blocks` (Albert Krewinkel).
+
+  * `doc/lua-filters.md` (Albert Krewinkel):
+
+    + Fix outdated documentation for math and quoting functions and fields.
+    + Autogenerate docs for module `pandoc.template` and `pandoc.layout`.
+    + Document operators of the "Doc" type.
+
+  * pandoc-lua-engine: depend on pandoc >= 3.2 (see #9755).
+
+  * Allow crypton-connection 0.4, time 1.14.
+
+  * Allow tasty-quickcheck 0.11.
+
+  * Use latest emojis, skylighting, skylighting-core, citeproc, djot,
+    commonmark-extensions, typst-hs
+
+## pandoc 3.2 (2024-05-11)
+
+  * Change to `--file-scope` behavior (#8741): previously a Div with an
+    identifier derived from the filename would be added around the contents
+    of each file. This caused problems for "chunking" files into chapters,
+    e.g. in EPUB. We no longer add the surrounding Div. This cooperates
+    better with chunking. Note, however, that if you have relied on the old
+    behavior to link to the beginning of the contents of a file using
+    its filename as identifier, that will no longer work.
+
+  * Markdown reader:
+
+    + Allow repeated labels in numbered example lists.
+      Previously if you tried to use the same label as an earlier
+      example list item, you'd get a new number, not the old one,
+      and references to the label would go to the second occurrence.
+      Now an existing label will be reused, and no new number will
+      be generated.  Caveat:  this only works reliably when the
+      re-used example list item occurs by itself in a list, or
+      occurs in a list of previously used example list items that
+      occur in exactly the same order as previously.
+    + Fix `normalCite` so it doesn't consume past a closing `]` boundary
+      (#9710).  This was causing an exponential performance bug on long
+      lists of links containing potential emphasis characters.
+    + Generalize `inlinesInBalancedBrackets` to `inBalancedBrackets`,
+      with a parameter for the inner parser.
+    + Auto-close unclosed divs (#9635). This applies to both fenced and
+      HTML-ish varieties. Otherwise we face an exponential performance
+      problem with backtracking. A warning is issued when a div is
+      implicitly closed.
+
+  * RST reader:
+
+    + Fix `figclass` and `align` annotations for figures (#7473, Gokul
+      Rajiv).
+
+  * LaTeX writer:
+
+    + Use `polytonicgreek` instead of `polutonikogreek` with babel (#9698).
+      `polutonikogreek` is outdated. Also recognize both in the LaTeX
+      reader.
+    + Improve treatment of math inside soul commands (#1294, #5529).
+      soul commands (`ul`, `hl`, `st`) are very fragile and the math
+      must be handled specially.
+
+  * LaTeX reader:
+
+    + Fix over-eager macro expansion in conditionals (#9676).
+    + Parse `flalign`, `flalign*` math environments (#9679). We parse
+      these as Math elements with an `aligned` environment. Semantically
+      it's not exactly the same, but better than falling back to raw LaTeX.
+
+  * LaTeX template: add `titlegraphicoptions` variable (#9207, Guilhem
+    Saurel).
+
+  * Docx reader:
+
+    + Issue warning rather than error when we can't parse EndNote citations
+      (see #8433).
+    + Fix anchor in header after anchor (#9626, mbracke).
+
+  * RTF reader:
+
+    + Don't try to handle non-default code pages (#9683). Emit a warning
+      instead.
+
+  * OpenDocument writer:
+
+    + Implement custom-style for spans (#9657).
+
+  * Typst writer:
+
+    + Add blank line in definition lists with multiple definitions (see
+      #9704).
+    + Property output (#9648, Gordon Woodhull). The Typst writer will pass
+      on specially marked attributes as raw Typst parameters on selected
+      elements. This allows extensive customization using filters.
+      A separate document (`doc/typst-property-output.md`) has been added
+      that provides extensive documentation and examples of the use of
+      this feature.
+
+  * Markdown writer:
+
+    + Don't try to align columns in pipe tables with lines greater than
+      COLUMNS. The alignment just reduces readibility when the lines
+      soft wrap.
+    + Don't use `raw_attribute` syntax for raw blocks, unless there is no
+      other option (see #9677).  Macros in a `raw_attribute` block don't
+      get interpreted when it is read again by pandoc's markdown reader.
+
+  * ConTeXt writer:
+
+    + Replace depreciated `\sc` with `\setsmallcaps` (#9518, James P.
+      Ascher).
+
+  * Docx writer:
+
+    + Use conventional styles/indents for Word bullet lists (#7280).
+
+  * `reference.docx`:
+
+    + Use current standard Word theme (#7280). This includes using the
+      sans-serif font Aptos instead of the serif font Cambria, and
+      default colors for headings.
+    + Remove duplicate `DefaultParagraphFont` in `styles.xml`.
+
+  * New module Text.Pandoc.Transforms [API change] (Albert Krewinkel).
+    This module exports the following functions which were formerly
+    exported from Text.Pandoc.Shared: `headerShift`,
+    `filterIpynbOutput`, `eastAsianLineBreakFilter`, as well as some
+    functions that were previously not exported.
+
+  * Text.Pandoc.Shared:
+
+    + `headerShift`, `filterIpynbOutput`, and `eastAsianLineBreakFilter`
+      are no longer exported from this module; they are now exported
+      from Text.Pandoc.Transforms (Albert Krewinkel).
+
+  * Text.Pandoc.Error:
+
+    + Improve reporting of unsupported extensions errors (#9247, Albert
+      Krewinkel).
+
+  * Text.Pandoc.App:
+
+    + Move "transforms" after filters (#9664). This will mean that
+      `--shift-heading-level-by` affects a heading added by
+      `reference-section-title`.
+
+  * Text.Pandoc.App.CommandLineOptions:
+
+    + Simplify output for `OptVersion`. Omit the information about versions
+      of dependencies. We no longer emit version info at this level anyway;
+      `pandoc-cli` intercepts and handles `--version`. This code would
+      only be called if someone used the pandoc library function
+      `handleWithOptInfo` in their own program.
+
+  * Text.Pandoc.ImageSize:
+
+    + Export `ImageSize` datatype.
+
+  * Text.Pandoc.SelfContained:
+
+    + Merge class attribute when both img and svg specify it (#9652,
+      Carlos Scheidegger).
+
+  * Text.Pandoc.Logging:
+
+    + Add `ScriptingInfo` constructor for `LogMessage` [API change]
+      (Albert Krewinkel).
+    + Make `DocxParserWarning` a WARNING, not INFO. [API change].
+    + Add `UnsupportedCodePage` constructor to `LogMessage` [API change].
+    + Add `UnclosedDiv` constructor for `LogMessage` [API change].
+
+  * Lua subsystem (Albert Krewinkel:
+
+    + Add a `pandoc.log` module.
+    + Uupdate to pandoc-lua-marshal version 0.2.7 (#8916).
+      This fixes counterintuitive behavior of the `content` property on
+      BulletList and OrderedList items. Unmarshalling of that field now
+      matches the behavior of the constructor.
+    + Use newest zip module. This adds a `symlink` function to Entry objects,
+      allowing to check if an entry represents a symbolic link.
+    + Improve `pandoc.json.decode` docs.
+    + Update and fix docs for `pandoc.types.Version` and `pandoc.utils.type`.
+    + Add new module `pandoc.image` The module provides basic querying
+      functions for image properties.
+    + Bump pandoc-lua-engine to 0.2.1.4.
+
+  * Use latest KaTeX CDN asset (#9707, Salim B).
+
+  * `pandoc-cli`: ensure UTF8 when emitting version info.
+
+  * tools/update-lua-module-docs.lua: improve script-internal docs, cleanup
+    (Albert Krewinkel).
+
+  * Allow network 3.2.
+
+  * Use latest versions of texmath, djot, skylighting-core, skylighting.
+
+  * Fix command test for #9652.
+
+  * Fix some typos in code comments (#9638, guqicun).
+
+  * Command tests: include regular PATH after directory with the test
+    executable (ensures that DLLs will be found on Windows).
+
+  * MANUAL.txt:
+
+    + Document `handout` variable for beamer (#9742).
+    + Document formats affected by `--slide-level` (#9745).
+    + Update the list of required LaTeX packages (#9728, Albert Krewinkel).
+    + Use more descriptive link text for ODT (#9673).
+    + Add clarification about `toc-title` in `docx`, `pptx` (#9645).
+    + Better document truthiness for conditionals (#9661).
+    + Mention that `custom-style` works with ODT (Ian Max Andolina).
+    + Harmonize typographic dashes (#9688, Salim B). Standardize on `---`
+      with no space.
+
+  * INSTALL.md: Minor tweaks (#9705, Leo Heitmann Ruiz).
+
+## pandoc 3.1.13 (2024-04-07)
+
+  * Org reader:
+
+    + Fix treatment of `id` property under heading (#9639).
+
+  * DocBook reader:
+
+    + Add empty title to admonition div if not present (#9569).
+      This allows admonition elements (e.g. `<note>`) to work with
+      `gfm` admonitions even if the `<title>` is not present.
+
+  * DokuWiki reader:
+
+    + Link text cannot contain formatting (e.g., `//` is not italics) (#9630).
+    + An explicitly empty link text (`[[url|]]`) works the same as an omitted
+      link text (#9632).
+
+  * Typst reader:
+
+    + Support Typst 0.11 table features: col/rowspans, table head
+      and foot (#9588).
+    + Parse cell col/rowspans.
+
+  * CSLJson writer:
+
+    + Put `$` or `$$` around math in `csljson` output (#9616).
+
+  * ConTeXt writer:
+
+    + Fix options order with `\externalfigure`. The dimensions should
+      come after the class if both are present.
+
+  * Typst writer:
+
+    + Put label after Span, not before. Labels get applied to preceding markup
+      item.
+    + Support Typst 0.11 table features (#9588): colspans, rowspans,
+      cell alignment overrides, relative column widths,
+      header and footer, multiple table bodies with intermediate headers.
+      Row heads are not yet supported.
+    + The default typst template has been modified so that tables
+      don't have lines by default. As is standard with pandoc, we only
+      add a line under a header or over a footer. However, a different
+      default stroke pattern can easily be added in a template.
+    + More reliable escaping in inline `[..]` contexts (#9586). For example,
+      we need to escape `[\1. April]` or it will be treated as an ordered list.
+    + Handle `unnumbered` on headings (#9585).
+
+  * LaTeX writer:
+
+    + Fix math inside strikeout (#9597).
+
+  * Text.Pandoc.Writers.Shared:
+
+    + Export `isOrderedListMarker` [API change].
+
+  * Change lhs tests so they don't use `--standalone`.
+    This will avoid test failures due to minor changes in
+    skylighting versions, e.g. #9589.
+
+  * Use latest texmath, typst.
+
+  * Require pandoc-lua-marshal 0.2.6 (#9613, Albert Krewinkel).
+    Fixes an issue arising when the value of `content` properties
+    on *BlockQuote*, *Figure*, and *Div* elements was an empty list.
+
+  * Update lua-filters.md (#9611, Carlos Scheidegger).
+
+
+## pandoc 3.1.12.3 (2024-03-17)
+
+  * Markdown reader: Fix bug with footnotes at end of fenced div (#9576).
+
+  * LaTeX reader:
+
+    + Improve tokenization of `@` (#9555). Make tokenization sensitive to
+      `\makeatletter`/`\makeatother`. Previously we just always treated
+      `@` as a letter.  This led to bad results, e.g. with the sequence `\@`.
+      E.g., `a\@ b` would parse as "ab" and `a\@b` as "a".
+    + Make `withRaw` work inside `parseFromToks` (#9517).
+      This is needed for raw environments to work inside table cells.
+    + Better handling of table colwidths (#9579). Previously the parser just
+      failed if the column width specified in `p{}` wasn't a multiple of
+      `\linewidth`. This led to cases where content was skipped.
+
+  * Typst writer:
+
+    + Add 'kind' parameter to figures with tables (#9574).
+    + Avoid unnecessary box around image in figure (#9236).
+    + Omit width/height in images unless explicitly specified (#9236).
+      Previously we computed width/heigth for images that didn't have
+      size information, because otherwise typst would expand the image
+      to fit page width. This typst behavior has changed in 0.11.
+      This change fixes a bug in which images would sometimes overflow
+      page margins, depending on their intrinsic size.
+    + Don't add hard-coded `inset` to tables (#9580). Instead, set this
+      globally in the default template, allowing it to be customized.
+
+  * LaTeX template: Fix block headings support for unnumbered paragraphs
+    (#9542, #6018, Oliver Fabel).
+
+  * HTML templates: Replace polyfill provider (#9537, @SukkaW).
+    Replace polyfill.io with cdnjs.cloudflare.com/polyfill.
+    polyfill.io has been acquired by Funnull, and the service has
+    become unstable.
+
+  * Korean translations: delete colon in translation for 'to'.
+    This was invalid YAML, and not desired anyway, since a colon
+    is added.
+
+  * Use latest commonmark, commonmark-extensions.
+    This fixes a 3.12 regression in parsing of commonmark/gfm autolinks
+    (jgm/commonmark-hs#151).
+
+  * Depend on djot 0.1.1.3, which fixes a serious parsing bug affecting
+    regular paragraphs after lists.
+
+  * Depend on latest skylighting, skylighting-core, typst-hs, texmath.
+
+  * MANUAL.txt: Change broken link to IDML cookbook (#9563).
+
+## pandoc 3.1.12.2 (2024-02-29)
+
+  * Docx reader:
+
+    + Ensure that table captions are counted (#9518).
+    + Detect caption by style name not id (#9518).
+      The styleId can change depending on the localization.
+    + Avoid emitting empty paragraph where caption was.
+
+  * Markdown reader: fix regression in link parsing with wikilinks extensions
+    (#9481).  This fixes a regression introduced in 3.1.12.
+
+  * Org reader/writer: support admonitions (#9475).
+
+  * Org writer: omit extra blank line at end of quote block.
+
+  * Typst writer: ensure that `-`, `+`, etc. are escaped at beginning of block
+    (#9478). Our recent relaxing of escaping (#9386) caused problems for
+    things like emphasized `-` characters that were rendered using
+    `#strong[-]#`.  This now gets rendered as `#strong[\-]`.
+
+  * LaTeX writer: fix bug when a language is specified in two different ways
+    (#9472). If you used `lang: de-DE` but then had a span or div with
+    `lang=de`, the preamble would try to load `ngerman` twice, leading
+    to an error. This fix ensures that a language is only loaded once.
+
+  * Docx writer: Don't copy over `footnotePr` in `settings.xml`
+    from reference.docx (#9522).
+
+  * EPUB writer: omit EPUB2-specific meta tag on EPUB3 (#9493).
+    This caused a validation failure in epubs with cover images.
+
+  * Lua: avoid crashing when an error message is not valid UTF-8 (Albert
+    Krewinkel).
+
+  * Text.Pandoc.SelfContained:
+
+    + Add `role="img"` to svgs.
+    + Add `aria-label` to svg elements with `alt` text if present.
+      Screen readers ignore `alt` attributes on svg elements but do
+      pay attention to `aria-label` (#9525).
+
+  * Text.Pandoc.Shared: Fix regression in section numbering in
+    `makeSections` (#9516). Starting with pandoc 3.1.12, unnumbered
+    sections incremented the section number.
+
+  * Text.Pandoc.Class: fix `openUrl` TLS negotiation (#9483).
+    With the release of TLS 2.0.0, the TLS library started requiring
+    Extended Main Secret for the TLS handshake. This caused problems
+    connecting to zotero's server and others that do not support TLS 1.3.
+    This commit relaxes this requirement.
+
+  * Depend on djot 0.1.1.0 (fixes rendering on multiline block attributes).
+
+  * Use new releases of skylighting-format-blaze-html (#9520).
+    Fixes auto-wrapping of long source lines in HTML print media.
+
+  * Use new commonmark-extensions (fixes issue with the
+    `rebase_relative_paths` extension when used with commonmark/gfm.
+
+  * Makefile: improve epub-validation target (#9493).
+    Use `--epub-cover-image` to catch issues that only arise with that.
+
+## pandoc 3.1.12.1 (2024-02-17)
+
+  * EPUB writer: omit EPUBv3-specific accessibility features on epub2
+    (#9469). Fixes a regression in 3.1.12.
+
+  * More fixes for SVG ids with `--self-contained` (#9467).
+    This generalizes the fix to #9420 so it applies to things like
+    `style="fill(url(#..."` and should fix problems with SVGs including
+    gradients.
+
+  * Powerpoint writer: properly handle math in headings and tables (#9465).
+    This ensures that paragraphs containing math are wrapped in
+    a `mc:AlternateContent` node as required.
+
+  * Makefile: make validate-epub check v2 output too.
+
+## pandoc 3.1.12 (2024-02-14)
+
+  * Add `djot` as input and output format. Djot is a light markup syntax
+    (https://djot.net).
+
+    + New module Text.Pandoc.Readers.Djot [API change]. The function
+      `readDjot` is also exported by Text.Pandoc.Readers.
+    + New module Text.Pandoc.Writers.Djot [API change]. The function
+      `writeDjot` is also exported by Text.Pandoc.Writers.
+
+  * `--number-sections` now uses the first digit for the number of
+    the top-level section, no matter what its level. So if the top-level
+    section is level-2, numbers will be `1`, `2`, etc. rather than
+    `0.1`, `0.2`, as in the past (#5071). For some backwards compatibility,
+    we revert to the old behavior when the `--number-offset` option is used.
+
+  * DocBook reader:
+
+    + Better handling of `<procedure>` and `<substeps>` (#9341):
+      `<procedure>` now gets parsed as an ordered list, and
+      `<substeps>` as a sublist.
+
+  * Man reader:
+
+    + Move spaces outside of emph/strong (#9445).
+
+  * MediaWiki reader:
+
+    + Don't make leading blanks underscores in image links (#9425).
+    + Allow lowercase `image:` (#9424).
+
+  * BibTeX reader:
+
+    + Support `pagetotal` in converting BibLaTeX.
+
+  * Markdown reader:
+
+    + Fix wikilinks extensions to allow newlines in titles (#9454).
+
+  * EPUB reader:
+
+    + Don't put `#` characters in identifiers.
+
+  * LaTeX reader:
+
+    + Improve treatment of `\cref`, `\Cref` (#7463). Use the
+      reference-type `ref+label` and `ref+Label`. Also, associate with
+      `\vref` `ref` instead of `ref+page`.
+    + Limited support for `\Cref` (#7463).
+    + Generate relative widths for `\linewidth`, `\textheight` (#9388).
+
+  * Typst reader:
+
+    + Fix handling of `\overline` (#9294). Due to a typo, it was being
+      incorrectly rendered as an `\underset`.
+    + Improve handling of inline `#quote` (#9413).
+    + Fix handling of `dot()`, `tilde()`, `ddot()` (jgm/typst-hs#38).
+    + Fix character used for `norm` (jgm/typst-hs#38).
+
+  * Typst writer:
+
+    + Use reference form (e.g. `@jones2000[p. 30]`) for citations when
+      possible.
+    + Use `#ref` or `@` for links with `reference-type="ref"` (#7463).
+      This attribute is added to LaTeX `\cref`, for example.
+    + Improve citation support (#9452). Emit `form: "prose"` or `form: "year"`
+      qualifiers if the citation is author-in-text or suppress-author.
+      Strip initial comma from suffix, since typst will add an extra one.
+    + Unescape URI escapes in image paths (#9389).
+    + Handle labels and citaiton ids with spaces and other special
+      characters (#9387). In these cases, we produce an explicit `label()`
+      rather than using `<>` or `@`.
+    + Avoid producing illegal labels (#9387).
+    + Avoid unnecessary escapes (#9386).
+
+  * LaTeX writer:
+
+    + Make writer sensitive to `empty_paragraphs` extension (#9443).
+    + Fix beamer highlighting (mh4ckt3mh4ckt1c4s).
+    + Create valid table even when table is empty (#9350).
+    + Set font fallback for babel main font (Max Heller).
+    + Add some kerns where needed between quotes (#9371).
+
+  * HTML writer:
+
+    + Add suffix to multiple footnote section ids, so they are
+      unique (Sam May). This is necessary when `--reference-location`
+      is `block` or `section`.
+
+  * EPUB writer:
+
+    + Add ARA roles for accessibility (#9378, Iacobus1983).
+      Footnote references are given role "doc-noteref", footnote text
+      gets "doc-footnote", and nav gets "doc-toc".
+    + Ensure that an alt attribute is always added (#9354). This seems to
+      be required by iBooks; even an empty alt attribute will satisfy it.
+    + Add `xml:lang` to package element (#9372).
+    + Add accessibility metadata to EPUB metadata (#9372, #9400,
+      Iacobus1983 and John MacFarlane). Reasonable default values are
+      used to ensure that pandoc's EPUBs conform to the EU Accessibilty Act
+      requirements, but values can be overridden using metadata.
+
+  * Docx writer:
+
+    + Restore ability to center-justify table (#9393). The fix to
+      #5947 caused all tables to be left indented. This was necessary
+      to avoid extra indentation in table cells when a table appeared
+      in a list item. This change makes the changes conditional, so
+      that they only affect tables in list items.
+
+  * Man writer:
+
+    + Fix bug with long URLs (#9458). URLs with more than 68 characters didn't
+      display properly because of wrapping.
+    + Support (limited) syntax highlighting in code blocks (#9446).
+      Currently only boldface and italics are supported. The `monochrome`
+      style might be of use for those generating man pages.
+
+  * Org writer:
+
+    + Escape special lines in code blocks (#9218, Albert Krewinkel).
+
+  * Markdown writer:
+
+    + Use different width fences for nested divs (#9450). Outer divs
+      have longer fences. This aids clarity for the reader, making it
+      easier to see where the div ends. It also makes the output
+      compatible with some other implementations, e.g. micromark,
+      which require different-width fences for nesting.
+    + Fix output for pipe tables with a huge number
+      of columns (#9346). Previously we got invalid pipe tables when the
+      number of table columns exceeded the setting of `--columns`.
+
+  * Powerpoint writer:
+
+    + Fix regression in layout for slides with figures (#9442).
+    + Use internal column widths in pptx writer tables (#5706,
+      Tomas Dahlqvist). The table writer used to only divide all
+      available width evenly for all columns. In this update the code
+      uses the incoming widths if they are available. If they are not
+      set the earlier even distribution is used. Some of the golden
+      templates are adjusted slightly because of different rounding when
+      using the new calculation model.
+
+  * Custom writers:
+
+    + Fix handling of common state (#9229, Albert Krewinkel).
+      The CommonState (`PANDOC_STATE` in Lua) may change between the time that
+      a custom writer script is first loaded and when the writer is run.
+      However, the writer was always using the initial state, which led to
+      problems, e.g. when the mediabag was updated in a filter, as those
+      updates where not visible to the writer. The state is now updated
+      right before the writer function runs.
+
+  * Text.Pandoc.SelfContained:
+
+    + Fix id replacements in SVGs with clipping paths (#9420).
+      This fixes `--embed-resources` when SVGs have `clip-path` attributes.
+    + Fix size of duplicated SVGs with `--embed-resources` (#9439).
+
+  * ConTeXt template: support font fallback (#9361, Lawrence Chonavel).
+
+  * Text.Pandoc.Shared:
+
+    + `addPandocAttributes`: use `wrapper` attribute, not `wrap`, for
+      Divs and Spans added as wrappers to hold attributes on elements
+      that do not accept them.
+    + `makeSections` behavior changes:
+      - When the optional base level parameter is provided, we no
+        longer ensure that the sequence of heading levels is gapless
+        (#9398). Instead, we set the lowest heading level to
+        the specified base level, and adjust the others accordingly. If
+        an author wants to skip a level, e.g. from level 1 to level 3,
+        they can do that. In general, the heading levels specified
+        in the source document are preserved; `makeSections` only
+        puts them into a hierarchical structure.
+      - Section numbers are now assigned differently, as described above
+        under `--number-sections` changes (#5071).
+    + Improve `makeSections` code for section number calculation.
+
+  * Text.Pandoc.Chunks:
+
+    + Autogenerate unique ids for sections missing them (#9383).
+      This is needed for TOC generation to work properly. We can't
+      create TOC links if there are no ids. This fixes some EPUB validation
+      issues we've been getting since switching over to Chunks for chunking.
+    + Improve `fixTOCTreePaths`. We weren't adding ids for section headings
+      that don't head a chunk, but these headings are needed for a TOC.
+
+  * Lua: catch encoding error in `pandoc.read` (#9385, Albert Krewinkel).
+    Fixed a bug that could lead to an un-catchable error and program
+    termination when `pandoc.read` was called with invalid UTF-8 input.
+
+  * LaTeX template: support font fallback (lawcho).  This support is
+    LuaLaTeX-specific.  See MANUAL.txt for documentation.
+
+  * Text.Pandoc.Readers: Add `readMan` to exports [API change] (George Stagg).
+
+  * Text.Pandoc.PDF:
+
+    + Reliably detect when TOC has changed (#9295). Sometimes the TOC
+      changes but there are no warnings: this happens when no labels
+      are present. In this case we must rerun LaTeX. So we now take the
+      SHA1 hash of the TOC file and rerun LaTeX if it changes between runs.
+    + Increase maximum number of LaTeX runs to 4 (#9299). On some documents,
+      4 runs are needed (e.g. when a LastPage reference is used).
+    + Avoid `readFileLazy`, which caused improperly cleaned-up
+      temp directories on Windows (#9460).
+
+  * MANUAL.txt:
+
+    + Harmonize spelling of Markdown and MultiMarkdown (#9402, Salim B).
+    + Add `<pre>` to list of exceptions for `markdown_in_html_blocks`
+      extension (#9305).
+    + Add clarification to docs for `--resource-path` (#9417).
+
+  * Makefile: Validate generated EPUB as part of prerelease checks.
+
+  * Add validation for docx golden files to CI (Edwin Török).
+
+## pandoc 3.1.11.1 (2024-01-05)
+
+  * Docx reader:
+
+    + Fix HYPERLINK with only switch and no argument (#9246).
+
+  * Org reader:
+
+    + Parse caption and label for grid tables (#9279).
+
+  * MediaWiki reader:
+
+    + Handle multiline math in list items (#9293).
+
+  * OPML writer:
+
+    + Respect `--wrap` options & `--columns` in contents of notes (#9297).
+
+  * ODT/OpenDocument writers:
+
+    + Properly handle highlighting styles (#9287). These styles were
+      going into an `office:styles` element in `content.xml`, but this
+      is invalid. Instead they must go in `styles.xml`. The variable
+      `highlighting-styles` no longer has any effect on the default
+      opendocument template, and highlighting styles are not included
+      in `opendocument` output.
+
+  * Markdown writer:
+
+    + Add table identifier at end of caption if present (#9279).
+
+  * Text.Pandoc.PDF:
+
+    + Expand list of environment variables to display in verbose output
+      (#9303).
+    + Ensure that we find all the LaTeX warnings requiring a rerun (#9284).
+      This should fix a regression from 3.1.9 that led to incorrect
+      alignments in tables (and possibly other issues).
+
+  * Docx writer:
+
+    + Ensure that pandoc's output validates (Edwin Török, #9273, #9269,
+      John MacFarlane, #9265, #9266, #9264).
+    + Don't emit empty table rows, which seem to cause problems for
+      Word (#9224).
+
+  * LaTeX writer:
+
+    + Omit superfluous page locator label when used with `--natbib` or
+      `--biblatex` (#9275). These will treat a bare number as a
+      page locator, and they will be able to localize it. Note that the
+      recognition of the locator label is locale-sensitive; if `lang` is
+      `de`, then `S. 33` is a page reference, and `p. 33` is not!
+
+  * Text.Pandoc.Chunks: Fine tune `makeChunks` (#9281).
+
+    + Ensure that chunks not based on sections (those with the
+      "preamble" class) get unique identifiers, by appending chunk number.
+    + This will also ensure that they get unique path names when
+      the path is generated from the identifier.
+
+  * Default HTML5 template: remove html5shiv (and support for IE < 9).
+
+  * Makefile:
+
+    + Fix `make quick-stack`: `j` was expecting a number (Edwin Török).
+    + Run built pandoc (instead of pandoc in path).
+    + Add `validate-epub` target, using `epubcheck` to test the golden files.
+    + Add `validate-docx-golden-tests` target.
+
+## pandoc 3.1.11 (2023-12-15)
+
+  * Typst writer:
+
+    + Emit `;` after typst code, unless followed by space (#9252).
+      Otherwise there's the potential that the typst code will swallow
+      up a following character.
+
+  * Text.Pandoc.Logging:
+
+    + Add `MakePDFWarning` constructor to LogMessage [API change].
+    + Add `MakePDFInfo` constructor to LogMessage [API change].
+
+  * Text.Pandoc.PDF:
+
+    + LaTeX warnings are passed on to the user as warnings.
+    + Use `report` with `MakePDFWarning` and `MakePDFInfo` to relay
+      verbose information and warnings, instead of writing directly
+      to stderr.
+    + Parse logs to determine whether additional runs needed, instead of
+      running a fixed number of times (#9255). (The number of times
+      that was appropriate given pandoc's default templates didn't
+      always work for custom templates, and thus pandoc 3.1.10's
+      change in the number of runs led to some regressions in PDF
+      production.)
+
+  * Makefile: in `make prelease`, add checks that pandoc-cli and
+    pandoc have the same version, that pandoc-cli depends on this
+    exact version of pandoc, that there is an entry for this version
+    in the changelog, and that the version numbers in the
+    generated man pages are correct.
+
+  * Regenerate man pages with pandoc 3.1.10. This properly escapes hyphens
+    and fixes version numbers in man pages for `pandoc-server` and
+    `pandoc-lua`.
+
+  * Depend on texmath 0.12.8.6. This omits unneeded `lr`s in typst
+    math output.
+
+  * Depend on typst 0.5. This allows the typst reader to support
+    multiline strings, the version type, and the `as`
+    keyword with `import`.
+
+## pandoc 3.1.10 (2023-12-12)
+
+  * Link pandoc-cli version to pandoc version. Henceforth pandoc-cli's
+    version will be synchronized with pandoc's, and pandoc-cli will
+    depend on an exact pandoc version. This will avoid confusion by
+    ensuring that `cabal install pandoc-cli-X.Y.Z` installs pandoc
+    version X.Y.Z. It will make things more straightforward for
+    upstream packagers (see #9232). This scheme does not follow the
+    Haskell PVP, but that should cause no harm, because this package
+    does not expose a library.
+
+  * Add `alerts` markdown extension. This enables GitHub style markdown
+    alerts as a commonmark extension. This extension is now default for
+    `gfm`. It can't be used with `markdown`, only with `commonmark` and
+    variants.
+
+  * Markdown reader:
+
+    + Preserve newlines in math instead of changing to spaces.
+      Otherwise we can get unwanted results if there's
+      a `%` comment (#9193).
+    + Make attributes work with reference links (#9171).
+
+  * HTML reader:
+
+    + Improve handling of invalidly nested sublists (#9187, cf. #8150).
+
+  * MediaWiki reader:
+
+    + Allow attribute keys with hyphens (#9178).
+
+  * ODT reader:
+
+    + Support attr `text:continue-numbering` (#8979, Stephan Meijer).
+
+  * Typst reader:
+
+    + Allow references (e.g. `@foo`) to become citations
+      if there is no corresponding label in the document.
+    + Collapse adjacent `cite` elements.
+    + Handle supplements in `cite`.
+    + Change `cite` (only one key allowed, a label) (typst 0.9 breaking change).
+    + Support `quote` element (typst 0.9).
+
+  * LaTeX reader:
+
+    + Handle otherlanguage environment and language-name environments like
+    `\begin{french}...\end{french}` (#9202).
+    + Fix theorem label parsing (#8872, Hikaru Ibayashi).
+
+  * Docx reader:
+
+    + Unwrap content of shaped textboxes (Stephan Meijer, #9214).
+    + Improve handling of `w:sym` (#9220). We now look up symbols in symbol
+      fonts using the table defined at Text.Pandoc.Readers.Docx.Symbols.
+    + Add unexported module Text.Pandoc.Readers.Docx.Symbols. This gives us a
+      table to use to resolve characters included in docx via `w:sym` element.
+
+  * Man reader:
+
+    + Properly handle `.sp` macro inside lists and block quotes (#9201).
+
+  * LaTeX writer:
+
+    + Fix bug with big footnotes inside emphasis (#8982, Hikaru Ibayashi).
+    + Handle identifiers inside heading contents. `\phantomsection` can't
+      be used in this case, so we need `\hypertarget` (#9209).
+
+  * LaTeX template:
+
+    + Include `bookmark` package unconditionally. This package
+      produces better PDF bookmarks than `hyperref` and does it on the
+      first pass.
+
+  * Typst writer:
+
+    + Use `quote` for block quotes.
+    + Support `--toc-depth` as in other writers (#9242).
+    + Put inline image dimensions on enclosing box, not image (#9104).
+    + Better handling of tables with captions (#9194).
+      We now put these in a figure with a caption argument.
+    + Update typst writer to typst 0.9 citation format (#9188).
+
+  * Typst template:
+
+    + Remove custom definition of `blockquote` in default template.
+      (We now use built-in `quote`.)
+    + Support table of contents.
+    + Support csl (#9186, Ian Max Andolina). Typst now supports CSL for its
+      native citation engine, so pandoc should use a specified `csl`
+      style in the template, falling back to `bibliographystyle` if
+      `csl` is not specified.
+
+  * Docx writer:
+
+    + Use different style for block quotes in notes (#9243).
+      Using "Footnote Block Text" for the style name, so it can be
+      given a different font size if footnotes are.
+    + Allow embedded fonts to be used in reference.docx (#6728).
+
+  * HTML5 writer:
+
+    + To conform to validator's expectations, `doc-footnote` role is used
+      with `aside` and `doc-endnotes` with `section`.
+    + `aside` is used only for notes at ends of sections or blocks;
+      if all the notes come at the end of the document, `section` is
+      used so we can have the `doc-endnotes` role.
+
+  * JATS writer:
+
+    + Handle case where there is material after refs div (#9166). Previously in
+      such cases the references were not being moved to back matter.
+
+  * Ms writer:
+
+    + Don't do normal escapes in filename arguments for PSPIC etc.
+
+  * T.P.RoffChar: escape `-` as `\-`. The `groff_man (7)` man page indicates
+    that `-` characters will be treated as typographic hyphens and are not
+    appropriate for cases where the output should be copy-pasteable as an
+    ASCII hyphen-minus character.  (E.g. in command line options.)
+    However, until a recent update groff man did not actually do this;
+    it treated `-` and `\-` the same.  With the new update (1.23.0)
+    the two are distinguished (see https://lwn.net/Articles/947941/
+    for background), so now it is important that pandoc escape `-`.
+
+  * Text.Pandoc.Extension: add `Ext_alerts` constructor [API change].
+
+  * Text.Pandoc.PDF: We now default to running LaTeX only
+    once in producing a PDF (instead of twice). This is made possible by the
+    shift to the `bookmark` package, which does not require a second pass for
+    PDF bookmarks. If a table of contents is present, we still have to run
+    three times to get the page numbers, and if beamer is used we still do a
+    minimum of two runs.
+
+  * Text.Pandoc.Shared:
+
+    + `renderTags'`: use minimized tag for `rect`.
+    + Allow svg `path` element to be minimized.
+    + Export `combineAttr` [API change].
+    + Improve `isTightList` so that it recognizes an item containing only a list
+      which is itself tight as potentially an item in a tight list (#9161).
+
+  * Text.Pandoc.MIME: Ensure we use `.svg` not `.svgz` as extension
+    for `image/svg+xml` mime type. This fixes issues with embedded
+    SVG images in docx output, among other things (#9195).
+
+  * Text.Pandoc.Class: `openURL` improvements for data uris.
+    Only treat data URI as `base64` if ';base64' is specified.
+    Otherwise treat as UTF-8 (not 100% reliable but should cover most
+    other cases). Strip off `;base64` (or `;charset=...` or whatever)
+    from mime type (#9195).
+
+  * Text.Pandoc.SelfContained: Improve treatment of embedded SVGs
+    (#9206, #8948).
+
+    + Ensure unique ids for elements by prefixing SVG id.
+    + Ensure SVG `id` attribute except when `use` element is used.
+    + Remove `width`, `height` attributes from svg element when `use`
+      element is used. Instead, add `width` and `height` 100% to the
+      `use` element. This seems to get the sizing right.
+
+  * Text.Pandoc.Citeproc: Don't link citations if
+    `suppress-bibliography` specified, for there will be nothing to
+    link to (#9163).
+
+  * epub.css: add styling for sup and sub (#9160).
+
+  * Switch from `base64` to `base64-bytestring` (#9233).
+
+  * Use newest versions of commonmark, commonmark-extensions,
+    commonmark-pandoc, texmath, typst, skylighting, skylighting-core.
+
+  * Benchmark: use standalone documents for reader tests.
+    Otherwise typst reader benchmark fails. Note: this means that we are now
+    parsing longer documents, so bench results on readers won't be comparable
+    to before.
+
+  * MANUAL.txt: update defaults file docs for bibliography fields (#9173).
+    Recommend using top-level `bibliography` `csl`, etc. instead
+    of a nested `metadata` field. Reason: `${USERDATA}` and `${HOME}`
+    are only expanded in these contexts, not in `metadata`.
+
+  * Move man pages to pandoc-cli package (#9245).
+
+## pandoc 3.1.9 (2023-10-27)
+
+  * Make `reference-section-title` work with `jats+element_citations`
+    (#9021).
+
+  * Add `bits` as synonym of `jats` as input format.
+
+  * JATS reader:
+
+    + Modify JATS reader to handle BITS too (#9138, Julia Diaz).
+      Add provision for title-group, book, book-part-wrapper, book-meta,
+      book-part-meta, book-title, book-title-group, index, toc, legend,
+      title, collection-meta
+    + Fix handling of alt-text (#9130, Julia Diaz). Previously we were
+      looking for an attribute that doesn't exist in JATS; alt-text is
+      provided by a child element.
+
+  * CommonMark reader:
+
+    + Handle `Ext_tex_math_gfm` (#9121). Parse GFM-specific math
+      constructions when `tex_math_gfm` enabled.
+
+  * DokuWiki reader:
+
+    + Allow autolinks to be avoided using e.g. `https:%%//%%...` (#9153).
+    + Parse `<code>` and `<file>` as block-level code (#9154).
+      Previously we treated them as inline code in some contexts,
+      but that is not how DokuWiki works.
+
+  * LaTeX reader:
+
+    + Better handle spacing commands `\hfill`, `\vfill`, `\hskip`,
+      `\vskip`, etc. (#9150).
+    + Fix incorrect abbreviation for astronomical unit (#9125,
+      Michael McClurg).
+
+  * Markdown reader:
+
+    + Fix blindspot with superscript in links (#8981).
+      Previously `[^super^](#ref)` wasn't parsed as a link, due to
+      code that was meant to prevent footnote markers from being
+      recognized as reference links.  This commit tightens up that
+      code to avoid this bad effect. We have also added a new
+      restriction on footnote labels: they cannot contain the characters
+      `^`, `[`, or `]`. Though this is technically a breaking change, we
+      suspect that the impact will be minimal, as it's very unlikely
+      people would be using these characters in their note labels.
+    + Don't apply `--default-image-extension` to data URIs (#9118).
+    + More accurate check that a normalCite is not a link,
+      bracketed span, or reference (#9080).
+
+  * HTML reader:
+
+    + Allow th to close td and vice versa (#9090).
+    + Parse task lists using input elements (#9047, Seth Speaks).
+
+  * Creole reader:
+
+    + Handle empty cells correctly (#9141, Sascha Wilde).
+
+  * Org writer:
+
+    + Escape literal `*`, `|`, `#` at beginning of line with ZWS (#9159).
+
+  * ICML writer:
+
+    + Prevent doubled attributes (#9158).
+
+  * Powerpoint writer:
+
+    + Fix a corruption error caused when the document used both a
+      regular png and a png in a data URI (#9113). (Similarly for any
+      other image format.) The problem was that duplicate entries in
+      `[Content Types].xml` were being created, one for the mime type
+      `image/png`, one for `image/png;base64`.
+
+  * LaTeX writer:
+
+    + Fix rowspans in tables so they use the width of
+      the column (`=` as the width parameter) (#9140).
+    + Don't treat table as "simple" if they have col widths.
+      This should help fix a problem wherein some grid tables with
+      colspans were overly wide (#9140).
+    + Fix uneven indents in line block output (#9088).
+
+  * JATS writer: fix 3.1.4 regression in handling block-level metadata
+    (#9092).
+
+  * Ms writer: improvements in image handling (#4475).
+
+    + PDFPIC is now used for PDF images in figures.
+    + Inline images that are postscript or PDF are rendered using
+      PSPIC or PDFPIC. This isn't ideal, because they will still be
+      rendered as if in a separate paragraph, but it's probably
+      better than just printing the image name.
+    + Units are included in height.
+
+  * HTML writer:
+
+    + If raw format is an HTML side deck format, emit it (James J Balamuta).
+
+  * Typst writer:
+
+    + Add `#box` around image to make it inline. (#9104)
+      An `#image` by itself in typst is a block-level element.
+      To force images to be inline (as they are in pandoc), we need
+      to add a box with an explicit width. When a width is not given
+      in image attributes, we compute one from the image itself, when
+      possible.
+    + Don't allow long heading to wrap (#9132).
+    + Escape `(` (#9137). If unescaped `(` occurs in
+      certain contexts, it can be parsed as function application.
+
+  * Man writer:
+
+    + Fix some spacing issues around links (#9120).
+      We need to use `\c` before a `.UR` or `.MT`, to avoid
+      an extra space, and also after.  To ensure that a space
+      at the beginning of the following line doesn't get swallowed
+      up, we escape it with `\`.
+    + Use UR, MT macros for URLs, emails (#9120).
+
+  * Text.Pandoc.Extensions:
+
+    + Add `Ext_tex_math_gfm` constructor to Extension (#9121).
+      [API change]. This handles two GitHub-specific syntaxes for math.
+      This is now default for `gfm`, in addition to `tex_math_dollars`.
+    + Remove duplicates for `Ext_raw_html` and `Ext_pipe_tables`
+      in some of the lists (Tim Stewart).
+
+  * Text.Pandoc.Metadata: Add helpful message on some metadata
+    YAML errors (#9155).
+
+  * Text.Pandoc.Shared:
+
+    + `splitSentences`: don't split after initials.
+      This improves the man and ms writer output, preventing
+      sentence breaks after initials.
+    + Add `addPandocAttributes` function [API change].
+      This is meant to simplify addition of attributes to Pandoc
+      elements: for elements that don't have a slot for attributes, an
+      enclosing Div or Span is added to hold the attributes.
+
+  * MANUAL.txt:
+
+    + Clarify that formatting can't cross line boundaries
+      in line blocks (#9119).
+    + Fix legacy option for citation (#8737, 3w36zj6)
+
+  * Update `et` translations (priiduonu).
+
+  * Updated `no` translations (Stephan Daus).
+    Renamed no.yaml (macrolanguage Norwegian) to nb.yaml (Norwegian Bokmål).
+    Created soft symbolic link from no.yaml pointing to nb.yaml.
+
+  * Lua subsystem: Use the newest LPeg version (lpeg-1.1.*) (#9107,
+    Albert Krewinkel).
+
+  * Default `epub.css`: Apply style to h6, format styles, and
+    combine identical styles under shared selectors (samuel-weinhardt).
+
+  * Update nix flake with dependencies (piq9117).
+
+  * LaTeX template: fix `\CSLBlock` vertical space (John Purnell).
+
+  * Allow tasty 1.5 and Diff 0.5.
+
+  * Require commonmark-extensions 0.2.4, commonmark 0.2.4.
+
+  * Require texmath 0.12.8.4. This should improve math in
+    powerpoint, fixing empty boxes around roots in some cases.
+
+  * Require typst 0.3.2.1
+
+## pandoc 3.1.8 (2023-09-08)
+
+  * JATS reader:
+
+    + Ignore `<processing-meta>` element (#9057, Julia Diaz).
+    + Fix conversion of date to ISO 8601 format (#8865).
+
+  * LaTeX template:
+
+    + Add code allow `\cite` to break across lines (#9050).
+    + Fix regression with CSL `display="block"` (#7363).
+      This restores the line break before the block.
+    + Rewrite `CSLReferences` environment to avoid depending on
+      `enumitem`, which plays badly with beamer.  Instead we use
+      a regular list environment. Thanks to @jpcirrus for the
+      concept (#9053).
+    + Restore the pre-3.1.7 format of the `CSLReferences`
+      environment, which again has two parameters. The first
+      determines whether a hanging indent is used (1 = yes, 0 = no),
+      and the second is the entry line spacing (0 = none).
+    + Add a strut to avoid inconsistencies in spacing (#9058).
+    - Remove a break at the end of `CSLRightInline` to avoid
+      inconsistencies in spacing. It shouldn't be necessary
+      because the paragraph should extend to the right margin (#9058).
+
+  * LaTeX writer:
+
+    + Fix regression with figure labels (#9045). In 3.1.7, pandoc
+      added two labels to LaTeX figure environments, one with a
+      phantomsection.
+    + Fix default citeproc entry-spacing. According to the CSL manual,
+      the default entry spacing is 1. We were treating it as 0 (#9058).
+
+  * HTML writer:
+
+    + Use the ID prefix in the ID for the footnotes section (#9044,
+      Benjamin Esham).
+    + Fix CSL entry-spacing default (#9058).
+
+  * Text.Pandoc.Citeproc:  always include an `entry-spacing` attribute
+    in the Div if the bibliography element contains an entry-spacing
+    attribute (previously we omitted it when it was 0) (#9058).
+
+  * Clean up pandoc's own man pages by regenerating with pandoc 3.1.7.
+
+  * pandoc-lua-engine: bump lower bound for pandoc (#9046).
+
+  * Depend on texmath 0.12.8.2, fixing binom in typst writer (#9063).
+
+## pandoc 3.1.7 (2023-08-31)
+
+  * Org reader:
+
+    + Don't parse alphabetical lists unless the `fancy_lists` extension is
+      enabled (#9042).
+    + Allow escaping commas in macro arguments (Amneesh Singh).
+
+  * JATS reader:
+
+    + Support for `<permissions>` metadata (#9037, Julia Diaz).
+      metadata objects with multiple fields are created, matching the
+      structure in JATS.
+    + Correct name of JATS element `attrib`.
+
+  * Markdown reader:
+
+    + Support images with wikilink syntax, e.g. `![[foo|bar]]`, when
+      one of the `wikilinks` extension is enabled (#8853).
+    + Allow a citation or reference link to be parsed after a `!` (#8254).
+    + Fix dropped `!` before nonexistent reference (#9038).
+
+  * LaTeX writer:
+
+    + Fix regression in escaping URLs (#9043).
+    + Use `\cite` and `\bibitem` to link up citations, even with citeproc.
+      (#9031). This will give us better accessibility; when tagging is
+      enabled, the citation can be linked to the bibliography entry.
+      This changes some of the details of the layout and the default
+      template. We now make `CSLReferences` a special enumitem list
+      that will contain `\bibitem`s. Internal links inside citations to
+      ids beginning in `ref-` are creating using `\cite` instead of
+      `\hyperref`.
+    + Use `\phantomsection` and `\label` instead of `\hypertarget` (#9022).
+    + Use `\hyperref` for LaTeX internal links, `\hyperlink` for
+      beamer (since `\hyperref` doesn't seem to work) (#9022).
+    + Backslash-escape `%` and `#` in URLs (#9014).
+
+  * JATS writer:
+
+    + Fix placement of ref-list when no title is specified for the
+      reference section (#9017). (In this case we place it in `back`
+      with an empty title.)
+
+  * Man writer:
+
+    + Avoid a `.PP` right after a section heading (#9020).
+      This is at best a no-op (in groff man and mandoc) and at worst
+      (in some formatters) may create extra whitespace.
+    + We revert the fanciness introduced in #7506, which employs a
+      custom font name `V` and a macro that makes this act like boldface
+      in a terminal and monospace in other formats.  Unfortunately,
+      this code uses a mechanism that is not portable (and does not
+      work in mandoc) (#9020).
+    + Instead of using `V` for inline code, we simply use `CR`.
+      Note that `\f[CR]` is emitted instead of plain `\f[C]`,
+      because there is no `C` font in man.  (This produces warnings
+      in recent versions of groff, #9020.)
+    + For code blocks, we now use the `.EX` and `.EE` macros,
+      together with `.IP` for spacing and indentation.  This gives
+      more standard code that can be better interpreted e.g. by mandoc
+      (#9020).
+
+  * Man template: don't emit `.hy`, regardless of setting of
+    `hyphenate` variable (#9020).
+
+  * LaTeX template: special redefinition of `\st` for CJK (#9019).
+    soul's version raises on error on CJK text.
+
+  * Use latest skylighting-format-blaze-html (#7248).
+    This works around a longstanding iOS Safari bug that caused long
+    lines to be displayed in a different font size in highlighted code.
+
+  * Allow skylighting 0.14 (and require it in pandoc core).
+
+  * Allow text 2.1.
+
+## pandoc 3.1.6.2 (2023-08-22)
+
+  * Org reader: allow example lines to end immediately after the colon
+    (Brian Leung).
+
+  * Docx reader:
+
+    + Omit "Table NN" from caption (#9002).
+    + Avoid spurious block quotes in list items (#8836).
+
+  * JATS reader: Fix display of block elements (#8889, Julia Diaz).
+    A number of block elements, like disp-quote, list, and disp-formula, were
+    always treated as inlines if appearing inside paragraphs, even if their
+    usage granted a separate block.
+
+  * HTML reader: avoid duplicate id on header and div (#8991).
+
+  * Typst writer:
+
+    + Use `~` for nonbreaking space, and escape literal `~` (#9010).
+    + Put the label in right place for Div, use `#block` (#8991).
+      Previously we were putting the label at the beginning of
+      the Div's contents, but according to the documentation such a
+      label gets attached to the *preceding* element.  We now use an
+      explicit `#block` and add the label at the end.
+
+  * LaTeX writer:
+
+    + Improve escaping of URIs in href, url (#8992).
+    + Improve internal links and targets (#8744). We no longer
+      wrap section headings in a `\hypertarget`. This is unnecessary
+      (hyperref creates an anchor based on the label) and it interferes with
+      tagging. In addition, we now use `\hyperref` rather than `\hyperlink`
+      for internal links. Currently `\hypertarget` is still being used for
+      link anchors not on headings. Thanks to @u-fischer.
+
+  * HTML format templates (style.html): Fix typo in clause for svg
+    (Jackson Schuster).
+
+  * Use lastest texmath, typst-symbols, typst. Targets typst 0.7.
+
+
+## pandoc 3.1.6.1 (2023-08-11)
+
+ * HTML reader: properly calculate RowHeadColumns (#8984). This fixes a
+   bug in the calculation of the number of header columns in table row.
+   It also changes the algorithm for determining the table body's
+   RowHeadColumns based on the numbers of head columns in each row.
+   Previously we used the max, and #8634 switched to the min, which
+   led to bad results. Now we only set RowHeadColumns to a non-zero value
+   if *all* rows have the same number of head columns.
+
+  * OpenDocument writer:
+
+    + Implement syntax highlighting for inline and block code (#6710).
+    + Support highlighted text in ODT/OpenDocument writers for Span
+      with class `mark` (#8960). The color can be adjusted by
+      modifying the Highlighted style.
+
+  * Typst writer: escape `//` so it doesn't get interpreted as a comment
+    (#8966).
+
+  * ChunkedHTML writer: Fix regression including MathJax script (#8967).
+    The fix for #8620 caused the script to be included when the table of
+    contents but not the body text of a page contains math.  But it broke the
+    case where the table of contents doesn't contain math but the page does.
+    This patch fixes the issue.
+
+  * Text.Pandoc.SelfContained:
+
+    + Retain attributes in SVG tag when referring to another
+      SVG's content using `<use>` (#8969).
+    + Allow units in width and height for SVG. Units are optional but allowed.
+    + Don't coerce calculated SVG dimensions to Int.
+    + fix calculation of SVG width and height. We were computing width and
+      height from viewBox incorrectly (#8969).
+    + Add clause for SVG to default CSS for HTML (#8969).
+    + Ensure that width and height attributes don't get specified
+      twice is both the img tag and the svg include them (#8965).
+    + Omit unnecessary attributes xmlns, xmlns:xlink, and version on
+      SVG element (#8965).
+    + Use 20 character rather than 40 character hashes for generated IDs
+      (#8965).
+
+  * Use pandoc-types 1.23.1. This fixes a regression with toJSONFilter (#8976),
+    which in 1.23.0.1 no longer worked on pure values of type `a -> [a]`.
+
+  * Use ghc 9.6 for release builds (#8947).
+
+  * Fix some links in FAQs (Diogo Almiro).
+
+
+## pandoc 3.1.6 (2023-07-20)
+
+  * Fix CVE-2023-38745, a variant of the vulnerability in CVE-2023-35936.
+    Guilhem Moulin noticed that the fix to CVE-2023-35936 was incomplete.
+    An attacker could get around it by double-encoding the malicious
+    extension to create or override arbitrary files.
+
+  * `--embed-resources`: Use inline SVG instead of data uris for SVG
+    images in HTML5 (#8948). Note that SelfContained does not have
+    access to the writer name, so we check for HTML5 by determining
+    whether the document starts with `<DOCTYPE! html>`. This means
+    that inline SVG won't be used when generating document fragments.
+
+  * Fix regression on short boolean arguments (#8956).
+    In 3.1.5 boolean arguments were allowed an optional argument
+    (`true|false`).  This created a regression for uses of fused
+    short arguments, e.g. `-somyfile.html`, which was equivalent
+    to `-s -omyfile.html`, but now raised an error because
+    pandoc attempted to parse `o` as a boolean `true` or `false`.
+    This change allows the fused short arguments to be used again.
+    Note that `-strue` will be interpreted as `-s` with an
+    argument `true`, not as `-s -t -rue`.  It is best to
+    use long option names with the optional boolean values,
+    to avoid confusion.
+
+  * Make `--epub-title-page`'s argument optional. It takes a boolean
+    argument, and now that all of our boolean flags take such an
+    argument, we can make this one optional for consistency.
+
+  * Improve errors for illegal output formats. Previously if you did
+    `pandoc -s -t bbb`, it would give you an error about the missing
+    `bbb` template instead of saying that `bbb` is not a
+    supported output format.
+
+  * Improve errors for incorrect command-line option values (#8879).
+    Always give the name of the relevant argument.
+
+  * Fix typo on error message for incorrect `--preserve-tabs` argument.
+    Thanks @fsoedjede
+
+  * Docx reader: use SVG version of image if present (#7244).
+    Previously the backup PNG was exported even if an SVG was
+    present, but the SVG should be preferred.
+
+  * Typst reader: fix regression in recognition of display math (#8949).
+    The last release caused all math to be parsed as inline math.
+
+  * JATS writer: don't use `<code>` for inline code (#8889).
+    It is intended for block-level code.
+
+  * HTML writer: don't make line blocks sensitive to `--wrap` (#8952).
+
+  * RST writer: fix figure handling (#8930, #8871).
+    This fixes a number of regressions from pandoc 2.x.
+    Properly handle caption, alt attribute in figures.
+    No longer treat a paragraph with a single image in it as a figure
+    (we have a dedicated Figure element now).
+
+  * Docx writer: Copy "mirror margins" property from reference.docx (#8946).
+
+  * Text.Pandoc.UTF8: Deprecate `decodeArg` which is now a no-op.
+    This was needed for old base versions which we no longer support.
+
+  * Use released skylighting, typst.
+
+  * Allow latest commonmark-extensions. This allows entities in wikilinks.
+
+  * Switch back to using ghc 9.2 for linux and Windows binary releases
+    (#8947, #8955). With ghc 9.4+, we were getting AVX instructions
+    in the amd64 binary, which aren't supported on older hardware.
+    For maximum compatibility we switch back to ghc 9.2, which doesn't
+    cause the problem. (As documented, ghc should not be emitting these
+    instructions, so we aren't clear on the diagnosis, but the cure
+    has been tested.)
+
+  * Change Windows release build to use cabal instead of stack.
+
+## pandoc 3.1.5 (2023-07-07)
+
+  * Allow all boolean flags to take an optional `true` or `false` value
+    (#8788, Sam S. Almahri). The default is true if no value is specified,
+    so this is fully backwards-compatible.
+
+  * Support `--id-prefix` for markdown output (#8878)
+
+  * Markdown reader:
+
+    + Add strictness annotations to fix a memory leak (#8762).
+
+  * Typst reader:
+
+    + Use typst-hs 0.3.0.0, which is more robust, fixes many bugs, and
+      targets typst 0.6.
+    + Package loading is now supported, as long as the package has been
+      cached or is local.
+    + Rewrite Typst reader in a way that makes it easier to extend.
+    + Filter out CR in raw.
+    + Handle block content for link element.
+    + Handle block-level content in text element.
+    + Handle style, align, place in inline contexts too.
+    + Improve info message for skipped elements.
+
+  * Add typst reader tests (#8942).
+
+  * MediaWiki reader:
+
+    + Revise treatment of "link trail." Previously we only included ASCII
+      letters. That is correct for English but not for, e.g., Spanish (see
+      comment in #8525). A safer approach is to include all letters except
+      those in the CJK unified ideograph ranges.
+
+  * AsciiDoc writer:
+
+    + Make modern AsciiDoc the target for `asciidoc` (#8936).
+      The AsciiDoc community now regards the dialect parsed by `asciidoctor`
+      as the official AsciiDoc syntax, so it should be the target of our
+      `asciidoc` format. The `asciidoc` output format now behaves like
+      `asciidoctor` used to. `asciidoctor` is a deprecated synonym. For
+      the old `asciidoc` behavior (targeting the Python script),
+      use `asciidoc_legacy`. The templates have been consolidated. Instead of
+      separate `default.asciidoctor` and `default.asciidoc` templates, there
+      is just `default.asciidoc`.
+    + Text.Pandoc.Writers.AsciiDoc API changes:
+      - `writeAsciiDoc` now behaves like `writeAsciiDoctor` used to.
+      - `writeAsciiDoctor` is now a deprecated synonym for `writeAsciiDoc`.
+      - New exported function `writeAsciiDocLegacy` behaves like
+        `writeAsciDoc` used to.
+    + Update line-through for asciidoc writer to custom inline style (#8933,
+      Kevin Broch).
+
+  * Typst writer:
+
+    + Support `unlisted` class in headings (#8941).
+    + Consolidate bibliography files into one `#bibliography` command (#8937).
+    + Improve handling of autolinks (#8931).
+
+  * Docx writer:
+
+    + Make relative widths work in tables. This didn't work before because we
+      were missing an attribute that tells Word to used fixed widths rather
+      than computing optimal ones.
+
+  * DokuWiki writer: fix lists with Div elements (#8920).
+    The DokuWiki writer doesn't render Divs specially, so their presence in
+    a list (e.g. because of custom-styles) need not prevent a regular
+    DokuWiki list from being used. (Falling back to raw HTML in this case is
+    pointless because no new information is given.)
+
+  * LaTeX writer:
+
+    + Fix babel name for `fa` (should be `persian`).
+    + Prevent babel language from being imported twice (#8925).
+
+  * Text.Pandoc.Class:
+
+    + Add `toTextM` [API change]. This is like `Text.Pandoc.UTF8.toText`,
+      except:
+
+      - it takes a file path as first argument, in addition to
+        bytestring contents
+      - it raises an informative error with source position if
+        the contents are not UTF8-encoded
+
+    This replaces `utf8ToText` whenever we have the filename and are
+    in a PandocMonad instance. This will lead to more informative error
+    messages for UTF8-encoding, indicating the file path and byte offset
+    where the error occurs (#8884).
+
+  * Remove invalid term "Subject" from Turkish translations (#8921).
+
+  * stack.yaml: add pkg-config to nix packages (#8927, pacien).
+
+  * Allow aeson 2.2.
+
+  * MANUAL: Add clarification on --section-divs. Closes #8882.
+
+
+## pandoc 3.1.4 (2023-06-24)
+
+  * Fix a security vulnerability in MediaBag and T.P.Class.IO.writeMedia.
+    This vulnerability, discovered by Entroy C, allows users to write
+    arbitrary files to any location by feeding pandoc a specially crafted
+    URL in an image element.  The vulnerability is serious for anyone
+    using pandoc to process untrusted input.  The vulnerability does
+    not affect pandoc when run with the `--sandbox` flag. [CVE-2023-35936]
+
+  * Allow `epub-title-page` to be used in defaults files (#8908).
+
+  * Issue `Extracting` info message (in `--verbose` mode) when using
+    `--extract-media` or extracting media temporarily in PDF production.
+
+  * HTML reader: Update TableBody RowHeadColumns caculation (#8634,
+    Ruqi). This change sets RowHeadColumns to the minimum value of each row,
+    which gives better results in cases where rows have different numbers
+    of leading th tags.
+
+  * Dokuwiki reader: retain image query parameters as attributes (#8887, echo0).
+
+  * Textile reader: Add support for link references (#8706, Stephen Altamirano).
+    Textile supports what it calls "link alias", which are analogous to
+    Markdown's reference-style links.
+
+  * LaTeX reader: support alt text on images (#8743, Albert Krewinkel).
+
+  * Commonmark reader: Make `implicit_figures` work again.
+    Support for this (introduced in #6350) disappeared when we made an
+    architectural change.
+
+  * JATS reader:
+
+    + Add footer and multiple body parsing to table reader (#8765, Noah Malmed).
+    + Parse references title from ref-list (#8365).
+
+  * JATS writer:
+
+     + Make `--number-sections` work.
+     + Include title in ref-list (#8364). Previously the reference title ended
+       up in a separate section at the back of the body instead of in the ref-list
+       in the back matter.
+
+  * Mediawiki writer: allow highlighting to work for F# language
+    (Adelar da Silva Queiróz).
+
+  * LaTeX writer: Fix escaping of `&` in `\href` and `\url` (#8903).
+
+  * Docx writer:
+
+    + Fix localization of "Abstract" title (#8702).
+    + Allow `abstract-title` to be specified in docx metadata (#8794).
+
+  * ChunkedHTML writer: Make math work in top-level page (#8915).
+
+  * Text.Pandoc.Logging: add new log message type `ScriptingWarning`
+    [API change] (Albert Krewinkel).
+
+  * Lua: report warnings from Lua scripts (Albert Krewinkel).
+    Lua's warning system is plugged into pandoc's reporting architecture.
+    Warnings that are raised with the Lua `warn` function are now reported
+    together with other messages.
+
+  * Use crypton-connection instead of connection (#8896, Felix Yan).
+    Follows the change introduced in tls 1.7.0.
+
+  * Bump versions for skylighting-core, skylighting.
+
+  * Include lua/module/sample.svg in cabal extra-source-files (Felix Yan).
+
+  * Add Nynorsk (New Norwegian) translations (Per Christian Gaustad).
+
+  * Add tests for `fillMediaBag`/`extractMedia`.
+
+  * INSTALL.md:
+
+    + Mention alternatives to LaTeX to generate PDF (Norwid Behrnd).
+    + Update Linux install links (harabat).
+
+  * pandoc-extras.md: add to "Academic publishing workflows" (#8696,
+    Vladimir Alexiev).
+
+## pandoc 3.1.3 (2023-06-07)
+
+  * New output format: `typst`.
+
+  * New module: Text.Pandoc.Readers.Typst [API change].
+
+  * DocBook reader:
+
+    + Support more emphasis roles (Albert Krewinkel).
+      The role "bf" is taken to indicate "bold face", i.e.,
+      "strongly emphasized" text, while "underline" leads to
+      underlined text.
+
+  * JATS reader:
+
+    + Improve title and label parsing in the JATS reader (#8718,
+      Noah Malmed.)
+    + Add rowspan, colspan and alignment to cells in jats table
+      reader (#8408, Noah Malmed)
+
+  * Org reader (Albert Krewinkel):
+
+    + Require abstract environment to use lowercase.
+    + Treat `#+NAME` as synonym for `#+LABEL` (#8578).
+
+  * ODT reader:
+
+    + Allow lists in table cells (#8892).
+    + Allow frames inside spans (#8886).
+
+  * RST reader:
+
+    + Fix sorting on anonymous keys (#8877). This fixes a link
+      resolution bug bug affecting RST documents with anonymous links.
+
+  * HTML reader:
+
+    + Fix iframe with data URI of an image (#8856).
+      In this case we don't want to try to parse the data at the URL.
+      Instead, create an image inside a div.
+
+  * RTF reader:
+
+    + Fix bug in table parsing (#8767). In certain cases, text before a
+      table was being incorporated into the table itself.
+
+  * Docx reader:
+
+    + Introduce support for Intense Quote (Stephan Meijer).
+
+  * Markdown reader:
+
+    + Disallow escaping of `~` and `"` in `markdown_strict` (#8777,
+      Albert Krewinkel). This matches the behavior of the legacy
+      `Markdown.pl` as well as what is described in the manual.
+
+  * LaTeX reader: ignore args to column type in `\multicolumn` (#8789).
+
+  * HTML writer:
+
+    + Use first paragraph in task item as checkbox label (#8729, Albert
+      Krewinkel).
+
+  * Ms writer:
+
+    + Coerce titles to inlines (#8835). Block-level formatting is not
+      allowed inside `.TL`.
+
+  * LaTeX writer:
+
+    + Fix width for multicolumn simple table (#8831).
+
+  * Jira writer:
+
+    + Use first code block class as highlighting language (#8814, Albert
+      Krewinkel). The writer no longer searches the list of
+      classes for a known programming language but always uses
+      the first class in that list as the language identifier.
+
+  * OpenDocument writer:
+
+    + Handle row header column cells as header cells (#8764, Michael Stahl).
+    + Fix invalid `text:p` inside `text:p` from meta (#8256).
+
+  * ODT writer:
+
+    + Don't add settings.xml (Michael Stahl). This will cause defaults
+      to be used, which is what we want.
+    + Don't add unnecessary Configurations2 directory (Michael Stahl).
+    + Don't add thumbnail (Michael Stahl).
+    + Put `manifest.version` on directory file-entry (Michael Stahl).
+      See ODF 1.3 part 2, 4.16.14.1.
+    + Stop validator complaints by producing ODF 1.3 (Michael Stahl).
+
+  * MediaWiki writer:
+
+    + Remove links from inside links in mediawiki writer (#8739,
+      Wout Gevaert).
+
+  * Typst writer:
+
+     + Omit bibliography if `citations` not enabled (#8763).
+      With this change, the typst writer will omit the `#bibliography`
+      command when `citations` is not enabled.  (If you want to use
+      pandoc's own `--citeproc`, you should combine it with
+      `-t typst-citations` to disable native typst citations.
+    + Use `<..>` for labels, create internal links.
+    + Use `#footnote` for notes (#8893).
+    + Fix alignment issue in lists.  It's an aesthetic issue
+      only; the first line had an extra space indent after the
+      list marker.
+
+  * Commonmark writer:
+
+    + Use shortcut reference links: commonmark supports these.
+
+  * EPUB template: add `lang` attribute to `<html>` (Gabriel Lewertoski).
+
+  * Template styles.html: fix task-list styling in reveal.js
+    (#8731, Albert Krewinkel).
+
+  * LaTeX template: Fix `\babelfont` (#8728).
+
+  * Text.Pandoc.Parsing:
+
+    + Remove unnecessary 'spaces' in `parseFromString`.
+
+  * Text.Pandoc.ImageSize: Drop BOM at start of SVG if present.
+    Otherwise our code can fail to determine image size.
+
+  * Lua subsystem:
+
+    + Fix value of PANDOC_SCRIPT_FILE for custom readers & writers
+      (#8781, Albert Krewinkel). The value did not hold the actual
+      file path for scripts in the *custom* folder of the datadir.
+
+  * Fix YAML in translation files for `cs` and `pl` (#8787).
+
+  * Fix pdf output via typst (#8754).  One must now use `typst
+    compile` rather than `typst`.
+
+  * MANUAL.txt:
+
+    + Added note that the user will need to create the user data
+      dir (#8727).
+    + Add `wikilinks` to non-default extensions (Ilona).
+    + Update link to custom djot writer (Albert Krewinkel).
+    + Better link to citation syntax.
+    + Fix typo (sdhoward).
+    + Note that `#` fancy list markers don't work with commonmark (#8772,
+      William Lupton).
+    + Add commonmark `fenced_div` note (#8773, William Lupton).
+    + Move highlighting documentation, with minor adjustments
+      (William Lupton).
+    + Fix inaccurate statement about spaces and tabs in template
+      syntax
+      (Frank Seifferth).
+
+  * Update documentation for org-mode (Christian Christiansen, #8716).
+
+  * doc/lua-filter.md:
+
+    + Fix typos (#8734, perro tuerto).
+    + Fix anchor (Toni Dietze).
+    + Use full field name in example (#8857, Matt Dodson).
+    + Fix copy-paste error (#8798, thron7).
+
+  * CONTRIBUTING.md: update info on ghc versions.
+
+  * INSTALL.md:
+
+    + Fix cabal install instructions (Albert Krewinkel).
+    + Use more relevant link to NetBSD/pkgsrc entry (Charlotte Koch).
+    + Fix Windows install instructions for winget (#8799).
+
+  * Tests: Rename test/docx/block_quotes_parse_indent.native for
+    consistency (Stephan Meijer).
+
+  * Add `tls` constraint on cabal.project. This is needed to
+    avoid problems caused by the transition to `crypton`.
+
+  * Require texmath 0.12.8.
+
+
+## pandoc 3.1.2 (2023-03-26)
+
+  * Add a Lua REPL (Albert Krewinkel). This can be started
+    with `pandoc lua -i`.  It is also possible to instruct a filter to
+    open the REPL at a certain point, for debugging (see `pandoc.cli.repl`).
+
+  * Support `typst` as a `--pdf-engine`.
+
+  * Add typst writer (#8713).  New module Text.Pandoc.Writers.Typst,
+    exporting `writeTypst` [API change].
+
+  * Org reader:
+
+    + Allow zero width space as an escape character (#8716,
+      Christian Christiansen). Allow the character U+200B to be used as
+      an escape character as described in the Org-mode documentation
+      (<https://orgmode.org/manual/Escape-Character.html>).
+
+  * DocBook reader:
+
+    + Handle "book" for xref references (#8712, Andres Freund)
+      This also adds a test xref to book and part.
+    + Handle `<part>` (#8712).
+
+  * HTML reader:
+
+    + Fix behavior with `-native_spans-raw_html` (#8711). Previously with
+      this configuration, `<span>`s were not treated as inline elements at all.
+
+  * HTML writer:
+
+    + Avoid duplicate classes (#8705).
+    + Use img element instead of embed for `.svg.gz` and `.png.gz` etc. (#8699).
+    + HTML writer footnotes changes (#8695): when `--reference-location=section`
+      or `=block`, use an `aside` element for the notes rather than a `section`.
+      When `--reference-location=section`, include the `aside` element inside
+      the section element, rather than outside. (In slide shows, this option
+      causes footnotes on a slide to be displayed at the bottom of the slide.)
+
+  * EPUB writer:
+
+    + Use different structure for epub footnotes (#8676, see #8672, #5583).
+      Many EPUB readers are thrown off by pandoc's current footnote
+      output.  Both the ol and the fact that the footnote backlink is
+      at the end of the note seem to pose problems.
+      With this commit, we now create a list of aside (or div) elements,
+      instead of an ordered list. Each element begins with a note number
+      that is linked back to the note reference.  (So, the backlink occurs
+      at the beginning rather than the end.) Thanks to @Porges and @lewer.
+
+  * Docx writer:
+
+    + Include abstract title (#8702). Uses localized term for abstract.
+
+  * Markdown writer:
+
+    + Use implicit figures if there's a caption but no alt (#8689,
+      Albert Krewinkel).
+
+  * Jira reader (Albert Krewinkel):
+
+    + Add panel title as nested div (#8681).
+    + Require jira-wiki-markup 1.5.1 (#8680). This fixes a bug in the parser
+      that caused text between two exclamation marks to be parsed as an
+      image. The first `!` of image markup must now be followed by a
+      non-space character; otherwise, the enclosed text is parsed as
+      normal content.
+
+  * Ms writer:
+
+    + Fix handling of Figure (#8660).
+
+  * ICML writer:
+
+    + Fix images with data (#8675). The Contents element
+      should be inside Properties.
+
+  * LaTeX writer:
+
+    + Add Chinese to Babel languages.
+    + Fix background image in Beamer when there are figure environments (#8671,
+      Martín Pozo).
+
+  * LaTeX template:
+
+    + Add `babelfonts` variable to default LaTeX template.
+      This allows specifying certain fonts to be used with
+      certain babel languages. Thanks to Frederik Elwert.
+    + Fix highlight/underline with lualatex (#8707). We need the lua-ul package
+      instead of soul, which doesn't work with lualatex.
+
+  * Lua (Albert Krewinkel):
+
+    + Add `pandoc.cli.repl` function
+    + Fix `json.encode` for nested AST elements. Ensures that objects with
+      nested AST elements can be encoded as JSON.
+    + Auto-generate docs for pandoc modules.
+    + Load text module as `pandoc.text`. This only affects the name in the
+      Lua-internal documentation. It is still possible to load the modules
+      via `require 'text'`, although this is deprecated.
+    + Move docs from module `text` to `pandoc.text`
+      The latter is easier to use and more consistent with the other modules.
+    + Keep the Lua stack clean A metatable used during initialization was
+      not properly removed from the stack. Likewise, accessing the
+      CommonState from Lua previously led to the pollution of the
+      Lua stack with a left-over value.
+    * Add function `pandoc.format.from_path`.
+    + Allow to get the JSON encoding of log messages.
+
+  * Text.Pandoc.Format: Add new function `formatFromFilePaths` [API change]
+    (#8710, Albert Krewinkel).
+
+  * The old Text.Pandoc.App.FormatHeuristics module has been removed.
+
+  * In `--version`, use Windows `%APPDATA%` variable to describe
+    user data dir (#8686, Pablo Rodríguez).
+
+  * Text.Pandoc.App.CommandLineOptions: don't lowercase arg to `--from`/`--read`
+    (Albert Krewinkel). This prevented users to use custom writers with
+    uppercase characters in their filenames. Format-normalization,
+    including lower-casing of format identifiers, happens during
+    format parsing.
+
+  * Documentation:
+
+    + Add `doc/nix.md`.
+    + Add `doc/extras.md`. This was formally in the website repo.
+    + `doc/lua-filters.md`: improve docs for `pandoc.zip`.
+
+  * Factor out `make_macos_release.sh` from the release candidate workflow.
+    Use cabal instead of stack to build the macos binary.
+
+  * Modify linux/make_artifacts.sh so it will work on cirrus.
+
+  * Switch to hslua-2.3
+
+  * Depend on latest releases of texmath, doclayout.
+
+## pandoc 3.1.1 (2023-03-05)
+
+  * EPUB reader: Give additional information in error if the epub
+    zip container can't be unpacked.
+
+  * TSV reader: don't gobble tabs as whitespace (#8661).
+
+  * Org reader: accept empty tables (#8659).
+
+  * LaTeX reader: fix multiplication syntax for tabular (#8658).
+    We recognized `*{6}{...}` but not `*6{...}` or `*6c`.
+
+  * Docx reader: parse image alt texts in LibreOffice generated files.
+    LibreOffice tags images slightly differently than Word; this change lets
+    the parses take that difference into account when looking for an image
+    description (alt text).
+
+  * DocBook reader:
+
+    + Fix `<xref>` references to tables in DocBook files
+      (#8626, Pavol Otto).
+    + Parse `figure` as a Figure element in the AST (#8668).
+
+  * JATS reader: avoid generating duplicate figure captions (#8669).
+
+  * RST reader: align with spec in syntax for role names (#8653).
+    In particular, we now allow colons in row names.
+
+  * Add note on converting from .doc format to FAQs (#8654).
+
+  * Trap error in getAppUserDataDirectory (#8648).
+    This can raise an error if pandoc is run in a non-user environment.
+
+  * LaTeX writer: do not use longtable foot with Beamer (#8638, Albert
+    Krewinkel). The table foot is made part of the table body, as
+    otherwise it won't show up in the output. The root cause for
+    this is that longtable cannot detect page breaks in Beamer.
+
+  * LaTeX template: Add CJKsansfont and CJKmonofont for XeLaTeX
+    (#8656, Yudong Jin). `CJKsansfont` and `CJKmonofont` will be
+    set for xelatex only if `CJKmainfont` is also provided.
+
+  * URL style in ConTeXt (#8612, Thomas Hodgson). Previously, a
+    URL like this would be in monospace text:
+    `\useURL[url1][https://example.com]`.  Now, it will match the
+    main text unless the `linkstyle` variable is set, which
+    controls the styling of all links.  Closes #8602.
+
+  * Asciidoc writer: Properly escape `|` in table cells (#8665).
+
+  * asciidoc{,tor} template: fix revision date when author is unset
+    (#8637, arcnmx). Revision line syntax is only valid in
+    combination with an author line, so the date attribute must be
+    set explicitly when the author is missing
+
+  * HTML writer: allow "track" element to be treated as block-level HTML
+    (#8629).
+
+  * Include needed polyfill when MathJaX is used (#8625).
+
+  * JATS writer: include alt-text in `<graphic>`,
+    `<inline-graphic>` elements (#8631, Albert Krewinkel).
+
+  * Chunked HTML writer:  Retain metadata in processing sections
+    for chunked HTML (#8620).  Previously we suppressed metadata
+    in all but the top page, in order to prevent the title block
+    from being printed on every page. This prevented use of
+    custom variables set by metadata fields.  This commit moves
+    to a better solution: a conditional in the default template
+    restricts the title block to the top page.
+
+  * Lua API:
+
+    + Add new function `pandoc.system.cputime` (Albert
+      Krewinkel).  The function returns the CPU time consumed by
+      pandoc and can be used to benchmark Lua computations.
+    + Add module `pandoc.json` to handle JSON encoding (#8605,
+      Albert Krewinkel).
+
+  * Use pandoc-lua-marshal 0.2.1 (Albert Krewinkel).
+    All major AST elements now have `__tojson` metamethods that return the
+    JSON representation of an element. This allows to JSON-encode these
+    elements with libraries that respect the `__tojson` metamethod,
+    including dkjson.
+
+  * Use latest zip-archive.  This allows pandoc to open certain
+    epubs that it could not open before.
+
+  * Use commonmark-extensions 0.2.3.4. This fixes some bugs involving
+    definition lists and inline formatting.
+
+  * Use latest skylighting-format-context
+
+  * MANUAL.txt:
+
+    + Document chunk-template in defaults file.
+    + Remove obsolete "raw content in a style" section.
+    + Revise documentation for `--mathml` to reflect support in all major
+      browsers (#8667).
+
+  * docs/custom-readers.md: Update JSON parsing example. The example now
+    uses the built-in `pandoc.json` library to parse the API output.
+
+  * doc/press.md: Add article on CiTO in J Cheminform by @egonw.
+
+  * doc/lua-filters.md: fix typo in `run_json_filter` (Morgan Willcock).
+
+
+## pandoc 3.1 (2023-02-09)
+
+  * Fix regression with `--print-highlight-style` option (#8586).
+
+  * Add new `--chunk-template` option (#8581), allowing more control
+    over the filenames in chunked HTML output.
+
+  * Text.Pandoc.App: Add `optChunkTemplate` constructor to Opt [API change].
+
+  * Text.Pandoc.Options: add `writerChunkTemplate` constructor to
+    `WriterOptions` [API change].
+
+  * Text.Pandoc.Chunks: add Data, Typeable, Generic, ToJSON, FromJSON
+    instances for `PathTemplate` [API change].
+
+  * Text.Pandoc.Citeproc: Fix bug in `metaValueToReference` (#8611).
+    This bug caused us to get some repeated content when converting
+    MetaBlock to Inlines.
+
+  * Textile reader:
+
+    + Support footnote backlinks (#8585, Stephen Altamirano).
+    + Don't allow brackets in URLs (#8582).
+
+  * ODT reader: fix blockquote indent detection (#3437, Daniel Kessler).
+
+  * LaTeX writer: include short figure/table caption if one is given
+    (Albert Krewinkel). Short captions are used by LaTeX when generating
+    the list of figures or list of tables. Adding a short caption will
+    now overwrite the full caption in these lists.
+
+  * Powerpoint writer: fix handling of simple figures (#8565,
+    Albert Krewinkel). This ensures that simple figures are displayed
+    in the same way as before the introduction of a dedicated `Figure`
+    constructor in the AST.
+
+  * Improve handling of `%` in bib(la)tex parsing (#8597, #8595).
+
+  * Use released skylighting 0.13.2.1
+
+  * INSTALL.md: direct people to cabal install pandoc-cli.
+
+  * doc/lua-filters.md: document 'Figure' type and constructor (Albert
+    Krewinkel). Fix typos (Martin Joerg).
+
+  * Fix link in manual (#8583, Salim B).
+
+## pandoc 3.0.1 (2023-01-25)
+
+  * Fix use of extensions with custom readers (#8571).
+
+  * Text.Pandoc.Writers.Shared: export `setupTranslations` [API change].
+    Use this in HTML and OpenDocument writers, to ensure that
+    translations are set up properly even when we don't go through
+    `convertWithOpts`.
+
+  * LaTeX reader: fix regression in macro resolution for environments (#8573).
+
+  * Chunked HTML writer: Fix handling of images with absolute URLs (#8567).
+
+  * HTML writer:
+
+    + Don't omit newlines in task lists.
+    + Don't disable checkboxes in task lists (#8562).
+
+  * Ensure that automatically set variables `pandoc-version`, `outputfile`,
+    `title-prefix`, `epub-cover-image`, `curdir`, `dzslides-core` can be
+    overridden by `--variable` on the command line. Previously they would
+    create lists in the template Context, which is not desirable.
+
+  * Fix man page copying in `linux/make_artifacts.sh` (#8566).
+    Previously we were copying the pandoc-server.1 pandoc page to pandoc-lua.1.
+
+  * pandoc.cabal: remove pandoc.cabal, stack.cabal from extra-source-files
+    (#8560). The problem is that if these are in extra-source-files, then they
+    get put in the tarball, and then anyone trying to build the source
+    from an unpacked tarball will run into the problem that cabal.project
+    and stack.yaml refer to pandoc-server, pandoc-lua-engine, and
+    pandoc-cli, which aren't in the tarball.
+
+  * Require texmath 0.12.6 for better MathML output.
+
+  * Fix typo in Lua filter documentation (Carlos Scheidegger).
+
+  * Fix formatting of link in pandoc-server.md (James Scott-Brown).
+
+  * Minor changelog fixups.
+
+## pandoc 3.0 (2023-01-18)
+
+  * Split pandoc-server, pandoc-cli, and pandoc-lua-engine
+    into separate packages (#8309). Note that installing
+    the `pandoc` package from Hackage will no longer give you the
+    `pandoc` executable; for that you need to install `pandoc-cli`.
+
+  * Pandoc now behaves like a Lua interpreter when called as
+    `pandoc-lua` or when `pandoc lua` is used (#8311, Albert Krewinkel).
+    The Lua API that is available in filters is automatically
+    available to the interpreter. (See the `pandoc-lua` man page.)
+
+  * Pandoc behaves like a server when called as `pandoc-server`
+    or when `pandoc server` is used. (See the `pandoc-server` man page.)
+
+  * A new command-line option `--list-tables`, causes tables to be
+    formatted as list tables in RST (#4564, with Francesco Occhipinti).
+
+  * New command line option: `--epub-title-page=true|false` allows
+    the EPUB title page to be omitted (#6097).
+
+  * `--reference-doc` can now accept a URL argument (#8535) and
+    load a remote reference doc.
+
+  * `--version` output no longer contains version info for dependent
+    packages. Instead, it contains a "Features" line that indicates
+    whether the binary was compiled with support for acting as a server,
+    and for using Lua filters and Custom writers.
+
+  * A new option `--split-level` replaces `--epub-chapter-level`
+    and affects both EPUB and chunked HTML output.  `--epub-chapter-level`
+    will still work but is deprecated.
+
+  * Multiple input files with `--file-scope`: fix case where the links
+    are URL-encoded, e.g. with `%20` (#8467).
+
+  * Produce error if `--csl` is used more than once (#8195, Prat).
+
+  * Remove deprecated `--atx-headers` option.
+
+  * Remove deprecated option `--strip-empty-paragraphs`.
+
+  * In `--verbose` mode add message when running citeproc (as with
+    other filters).
+
+  * Add new `mark` extension for highlighted text in Markdown,
+    using `==` delimiters (#7743).
+
+  * Add new extensions `wikilinks_title_after_pipe` and
+    `wikilinks_title_before_pipe` for `commonmark` and `markdown`.
+    (#2923, Albert Krewinkel). The former enables links of style
+    `[[Name of page|Title]]` and the latter `[[Title|Name of
+    page]]`. Titles are optional in both variants, so this works
+    for both: `[[https://example.org]]`, `[[Name of page]]`. The
+    writer is modified to render links with title `wikilink` as
+    a wikilink if a respective extension is enabled. Pandoc will
+    use `wikilinks_title_after_pipe` if both extensions are
+    enabled.
+
+  * Add prefixes to identifiers with `--file-scope` (#6384).
+    This change only affects the case where `--file-scope` is used
+    and more than one file is specified on the command line.
+    In this case, identifiers will be prefixed with a string
+    derived from the file path, to disambiguate them. For example,
+    an identifier `foo` in `contents/file1.txt` will become
+    `contents__file1.txt__foo`.  Links will be adjusted accordingly:
+    if `file2.txt` links to `file1.txt#foo`, then the link will
+    be changed to point to `#file1.txt__foo`.  Similarly, a link
+    to `file1.txt` will point to `#file1.txt`.  A Div with an
+    identifier derived from the file path will be added around
+    each file's content, so that links to files will still work.
+
+  * New output format: `chunkedhtml`. This creates a zip file
+    containing multiple HTML files, one for each section,
+    linked with "next," "previous," "up," and "top" links.
+    (If `-o` is used with an argument without an extension,
+    it is treated as a directory and the zip file is automatically
+    extracted there, unless it already exists.) The top page will
+    contain a table of contents if `--toc` is used.  A
+    `sitemap.json` file is also included. The option
+    `--split-level` determines the level at which sections are
+    to be split.
+
+  * Support complex figures (Albert Krewinkel, Aner Lucero).
+    There is now a dedicate Figure block constructor for
+    figures.  The old hack of representing a figure as
+    `Para [Image attr [..alt..] (source, "fig:title")]`
+    has been dropped.  Here is a summary of figure support
+    in different formats:
+
+    + Markdown reader: paragraphs containing just an image are treated as
+      figures if the `implicit_figures` extension is enabled. The identifier
+      is used as the figure's identifier and the image description is also
+      used as figure caption; all other attributes are treated as belonging
+      to the image.
+    + Markdown writer: figures are output as implicit figures if possible,
+      via HTML if the `raw_html` extension is enabled, and as Div elements
+      otherwise.
+    + HTML reader: `<figure>` elements are parsed as figures, with the
+      caption taken from the respective `<figcaption>` elements.
+    + HTML writer: the alt text is no longer constructed from the caption,
+      as was the case with implicit figures. This reduces duplication, but
+      comes at the risk of images that are missing alt texts. Authors should
+      take care to provide alt texts for all images. Some readers, most
+      notably the Markdown reader with the `implicit_figures` extension,
+      add a caption that's identical to the image description. The writer
+      checks for this and adds an `aria-hidden` attribute to the
+      `<figcaption>` element in that case.
+    + JATS reader: The `<fig>` and `<caption>` elements are parsed into
+      figure elements, even if the contents is more complex.
+    + JATS writer: The `<fig>` and `<caption>` elements are used write
+      figures.
+    + LaTeX reader: support for figures with non-image contents and for
+      subfigures.
+    + LaTeX writer: complex figures, e.g. with non-image contents and
+      subfigures, are supported. The `subfigure` template variable is set if
+      the document contains subfigures, triggering the conditional loading
+      of the *subcaption* package. Contants of figures that contain tables
+      are become unwrapped, as longtable environments are not allowed within
+      figures.
+    + DokuWiki, Haddock, Jira, Man, MediaWiki, Ms, Muse, PPTX, RTF, TEI,
+      ZimWiki writers: Figures are rendered like Div elements.
+    + Asciidoc writer: The figure contents is unwrapped; each image in the
+      the figure becomes a separate figure.
+    + Classic custom writers: Figures are passed to the global function
+      `Figure(caption, contents, attr)`, where `caption` and `contents` are
+      strings and `attr` is a table of key-value pairs.
+    + ConTeXt writer: Figures are wrapped in a "placefigure" environment
+      with `\startplacefigure`/`\endplacefigure`, adding the features
+      caption and listing title as properties. Subfigures are place in a
+      single row with the `\startfloatcombination` environment.
+    + DocBook writer: Uses `mediaobject` elements, unless the figure contains
+      subfigures or tables, in which case the figure content is unwrapped.
+    - Docx writer: figures with multiple content blocks are rendered as
+      tables with style `FigureTable`; like before, single-image figures are
+      still output as paragraphs with style `Figure` or `Captioned Figure`,
+      depending on whether a caption is attached.
+    + DokuWiki writer: Caption and "alt-text" are no longer combined. The
+      alt text of a figure will now be lost in the conversion.
+    + FB2 writer: The figure caption is added as alt text to the images in
+      the figure; pre-existing alt texts are kept.
+    + ICML writer: Only single-image figures are supported. The contents of
+      figures with additional elements gets unwrapped.
+    + OpenDocument writer: A separate paragraph is generated for each block
+      element in a figure, each with style `FigureWithCaption`. Behavior for
+      single-image figures therefore remains unchanged.
+    + Org writer: Only the first element in a figure is given a caption;
+      additional block elements in the figure are appended without any
+      caption being added.
+    + RST writer: Single-image figures are supported as before; the contents
+      of more complex images become nested in a container of type `float`.
+    + Texinfo writer: Figures are rendered as float with type `figure`.
+    + Textile writer: Figures are rendered with the help of HTML elements.
+    + XWiki: Figures are placed in a group.
+
+  * Changes in custom readers/writers:
+
+    + It is now possible to have a custom reader and a custom writer for
+      a format together in the same file.  The file may also define
+      a custom template for the writer.
+    + Pandoc now checks the folder `custom` in the user's data directory
+      for a matching script if it can't find one in the local directory.
+      Previously, the `readers` and `writers` data directories were
+      searched for custom readers and writers, respectively. Scripts in
+      those directories must be moved to the `custom` folder.
+    + Custom readers used to implement a fallback behavior that allowed to
+      consume just a string value as input to the `Reader` function. This
+      has been removed, the first argument is now always a list of
+      sources. Use `tostring` on that argument to get a string.
+
+  * New module Text.Pandoc.Writers.ChunkedHTML,
+    exporting `writeChunkedHtml` [API change].
+
+  * We now set the `pandoc-version` variable centrally rather
+    than in the writers.  One effect is the man writer now emits
+    a comment with the pandoc version.
+
+  * pandoc-server:
+
+    + Add simple CORS support to pandoc-server (#8427).
+    + Print message to stderr when starting the server.
+
+  * Docx reader:
+
+    + Mark unnumbered headings with class `unnumbered` (#8148,
+      Albert Krewinkel). This change ensures good conversion
+      results when converting with `--number-sections`.
+    + Support parsing of highlighted text.
+    + Fix handling of `oMathPara` in `w:p` with other content (#8483).
+
+  * ODT reader:
+
+    + Fix relative links. ODT adds a `../` to relative links
+      (see #3524); this needs to be removed when converting from ODT.
+    + Handle "section" elements (#8409).
+    + Rename Text.Pandoc.Readers.Odt -> Text.Pandoc.Readers.ODT,
+      for consistency with Writers.ODT. Rename `readOdt` -> `readODT`.
+      [API change]
+
+  * DocBook reader:
+
+    + Support href on link even in a fragment (#8437).
+      (We now just look for an `href` attribute without
+      worrying about the namespace.)
+    + Parse title from imageobject/objectinfo (#8437).
+
+  * JATS reader:
+
+    + Handle uri element in references (#8270).
+
+  * Ipynb reader:
+
+    + Add cell id to attachment filename when storing in MediaBag (#8415).
+      Otherwise attachments with the same name can overwrite each other.
+
+  * LaTeX reader:
+
+    + Skip parenthenized args of toprule, midrule, etc (#8242).
+    + Handle `##` macro arguments properly (#8243).
+    + Remove unused function `toksToString` in Parsing module.
+    + Support more `soul` commands, including `\hl`.
+    + Add `unnumbered` class for `\part*` (#8447)
+    + Fix `TEXINPUTS` handling (#8392). If `TEXINPUTS` ends with `:`,
+      then the system default `TEXINPUTS` is added.  We handle this by
+      just adding the working directory in this case.
+    + Parse short table caption (see jgm/pandoc-types#103).
+      This is not too useful yet, because writers don't do anything with
+      the short caption.
+
+  * MediaWiki reader:
+
+    + Parse table cell with attributess, to support rowspan, colspan (#8231,
+      Ruqi).
+    + Refine "blending" rules for MediaWiki links (#8525, Ruqi).
+      The rules for "blending" characters outside a link into the link are
+      described here: https://en.wikipedia.org/wiki/Help:Wikitext#Blend_link
+      These pose a problem for CJK languages, which generally don't have
+      spaces after links. However, it turns out that the blending behavior, as
+      implemented on Wikipedia, is (contrary to the documentation) only for
+      ASCII letters. This commit implements that restriction, which fixes
+      the problem for CJK.
+
+  * HTML reader:
+
+    + Fix regression for `<tt>` (#8330). It was no longer being parsed as
+      Code (Justin Wood).
+
+  * RST reader:
+
+    + Support `mark` role for round-trip.
+
+  * Textile reader:
+
+    + Support linked images (#8541).
+    + Fix strong emph ending with link (#8540).
+    + Adding a Parser to look for ordered list start attribute numbers
+      if any (#2465, vkraven).
+    + Handle empty paragraphs (#8487). Also, if attributes are added
+      explicitly to a paragraph, put it in a Div with the attributes.
+
+  * Markdown reader:
+
+    + Allow fenced code block "bare" language to be combined
+      with attributes (#8174, Siphalor), e.g.
+      ````
+      ```haskell {.class #id}
+      ```
+      ````
+    + Allow table caption labels to start with lowercase `t` (#8259).
+    + Grid tables: allow specifying a table foot by enclosing it with
+      part separator lines, i.e., row separator lines consisting only
+      of `+` and `=` characters (#8257, Albert Krewinkel). E.g.:
+      ```
+      +------+-------+
+      | Item | Price |
+      +======+=======+
+      | Eggs | 5£    |
+      +------+-------+
+      | Spam | 3£    |
+      +======+=======+
+      | Sum  | 8£    |
+      +======+=======+
+      ```
+    + Fix `implicit_header_references` with duplicate headings (#8300).
+      Documentation says that when more than one heading has the same text,
+      an implicit reference `[Heading text][]` refers to the first one.
+      Previously pandoc linked to the last one instead. This patch
+      makes pandoc conform to the documented behavior.
+    + Parse highlighted text inside `==..==` if `mark` extension enabled.
+
+  * Org reader:
+
+    + Allow org-ref v2 citations with `&` prefix (#8302).
+    + Make `#+pandoc-emphasis-pre` work as expected (#8360, Amir Dekel).
+
+  * BibTeX reader:
+
+    + Fix handling of `%` in `url` field (#7678).
+      `%` does not function as a comment character inside `url`
+      (where URL-encoding is common).
+    + Allow `url` field in `bibtex` as well as `biblatex` (#8287).
+      This field is not officially supported for BibTeX, but many styles
+      can handle it (<https://www.bibtex.com/f/url-field/>),
+      and others will ignore it.
+    + Support `software` type in biblatex <-> CSL conversions (#8504).
+    + Make sure `version` field comes through in biblatex (#8504).
+
+  * BibTeX writer:
+
+    + Pass through `url` even for `bibtex` (#8287).
+
+  * Org writer:
+
+    + Pass through unknown languages in code blocks (#8278), instead
+      of producing `begin_example`.
+    + Use span attributes `tag-name` in headers as tags (#8513, Albert
+      Krewinkel). This enables round-tripping of tags in Org headings.
+
+  * EndNote reader:
+
+    + Better error when parsing EndNote references fails.
+
+  * DocBook writer:
+
+    + Rename Text.Pandoc.Writers.Docbook -> Text.Pandoc.Writers.DocBook.
+      Rename `writeDocbook` -> `writeDocBook`, for consistency with
+      the DocBook reader's naming. [API change]
+    + Fix position of textobject (#8437). It is a child of
+      `inlinemediaobject`, not `imageobject`.
+    + Add regression tests for #8437.
+    + Render image alt text using textobject element (#8437).
+    + Don't indent contents of title element.
+    + Store "unnumbered" class in DocBook role attribute (#1402, lifeunleaded).
+
+  * ConTeXt writer (Albert Krewinkel):
+
+    + Support syntax highlighting for code.
+    + Always use `\type` for inline code.
+      Inline codes that contained curly braces where previously rendered
+      with `\mono`; this led to unexpected results when the presentation
+      of `\type` was customized, as those changes would not have
+      been applied to code rendered with `\mono`.
+    + Add support for unlisted, unnumbered headings (#8486).
+    + Support `tagging` extension (Albert Krewinkel). Paragraphs
+      are enclosed by `\bpar` and `\epar` commands, and `highlight` commands
+      are used for emphasis. This results in much better tagging in PDF output.
+
+  * LaTeX writer:
+
+    + Do not repeat caption on headless tables (Albert Krewinkel).
+      The caption of headless tables was repeated on each page that
+      contained part of the table. It is now made part of the
+      "first head", i.e. the table head that is printed only once.
+    + Add separator line between table's body and its foot
+      (Albert Krewinkel).
+    + Ignore languages with no babel equivalent, instead of generating an
+      invalid command in the preamble (#8325).
+    + Use `\includesvg` for SVGs and include the `svg` package (#8334).
+    + Use `soul` instead of `ulem` for strikeout, underline (#8411).
+      This handles things like hyphenation, line breaks, and nonbreaking
+      spaces better.
+    + Use `\toprule\noalign{}` instead of `\toprule()` in tables,
+      and similarly for `\midrule` and `\bottomrule` (#8223).
+      This facilitates redefining `\toprule`, `\midrule`, and `\bottomrule`
+      without needing to gobble the ()s. (Those who redefine these macros
+      on the assumption that they will be followed by `()` may need to
+      change their definitions.)
+    + Support highlighted text for Span with class `mark`.
+
+  * JATS writer:
+
+    + Use `<break/>` for LineBreak in the limited contexts that accept it
+      (#8344).
+    + Officially deprecate `writeJATS` in favor of `writeJatsArchiving`.
+
+  * RTF writer:
+
+    + Add space after unicode escape commands (#8264).  This fixes
+      a bug that caused characters to disappear after unicode escapes.
+
+  * RST writer:
+
+    + Render tables as list tables when the `--list-tables` option is
+      specified (`writerListTables`) (#4564, Francesco Occhipinti).
+    + Improve inline escaping rules (#8380).
+    + Use special `mark` role for Span with class `mark`.
+
+  * Commonmark writer:
+
+    + Ensure that we don't have blank lines in raw HTML (#8307).
+
+  * HTML writer:
+
+    + Only add role attribute in HTML5 (#8241). It is not valid in HTML4.
+    + Avoid aria-hidden in code blocks for HTML4 (#8241).
+    + Only treat `. . .` as a slide pause in slides, and not in regular
+      HTML output (#8281).
+    + Properly merge classes for headings of level > 6 (#8363).
+    + Prevent `<a>` inside `<a>` (#7585). If a link text contains a link,
+      we replace it with a span.
+    + Replace deprecated aria roles for bibliography entries (#8354).
+      `doc-biblioentry` -> `listitem`, `doc-bibliography` -> `list`.
+    + Remove obsolete stuff about mathml-script.
+      This was a shim we used to include for mathml support.
+      We don't do anything with this any more, so this is dead code.
+    + Include math links if there are raw commands or environments that
+      can be interpreted as math e.g. by MathJax (#8469).
+    + Add prooftree to list of math environments (#8462). This will cause
+      raw LaTeX prooftree environments to be rendered appropriately when
+      `--mathjax` is used.
+
+  * HTML, Markdown writers: filter out empty class attributes (#8251).
+    These should not be generated by any pandoc readers, but they
+    might be produced programmatically.
+
+  * Markdown writer:
+
+    + Avoid HTML fallbacks in the generated TOC (Albert Krewinkel, #8131).
+      The generated table of contents usually has IDs for each TOC link,
+      allowing to link back to specific parts of the TOC. However, this
+      leads to unidiomatic markup in formats like gfm, which do not support
+      attributes on links and hence fall back to HTML. The IDs on TOC items
+      are now removed in that case, leading to more aesthetic TOCs.
+    + Escape `!` before `[` (#8254).
+    + Support `mark` extension.
+
+  * AsciiDoc writer:
+
+    + In link text, only replace commas with entities when they're in
+      Str elements.  If a link contains an image, it may have attributes,
+      and the commas there should not be converted (see #8437, #8070).
+
+  * ODT writer:
+
+    + Fix relative links (#3524).
+
+  * Docx writer:
+
+    + Better handling of tables in lists (#5947). Previously the content
+      of each list cell was indented when the table belonged to a list
+      item.
+    + Indent tables in list items (#5947).
+    + Adjust correct attribute on `lang` element (#7022). For East Asian
+      languages, we need to adjust `w:eastAsia` rather than `w:val`.
+      This allows normal fonts to be used for any Latin-font text.
+      Similarly, for bidi languages, we need to adjust `w:bidi`
+      rather than `w:val`. We treat `he` and `ar` as bidi languages,
+      `zh`, `ja`, `ko` as East Asian languages.
+    + Support relative image widths (Albert Krewinkel).
+      Image widths given in percent are interpreted to be relative to
+      the text width. Previously, percent widths were taken relative to
+      the image's native size, inconsistently with other writers.
+    + Avoid using 'error' for unassigned table cells (#8468). Instead,
+      throw a regular pandoc error.
+    + Render a Span with class `mark` as highlighted. Currently
+      yellow is hardcoded.
+
+  * MediaWiki writer:
+
+    + Use the 'new' table structure, so that colspan and rowspan are
+      supported (Wout Gevaert).
+
+  * Man writer:
+
+    + Use UTF-8 by default for non-ascii characters (#8507).
+      Only use groff escapes if `--ascii` has been specified on the
+      command line (`writerPreferAscii`).
+
+  * ICML writer:
+
+    + Use Contents element for images with raw data instead of a link
+      with a data: uri (#8398).
+
+  * EPUB writer:
+
+    + Refactor to use Text.Pandoc.Chunks.
+    + Refactored and simplified code.
+    + Make title page optional (#6097).
+
+  * Ms writer:
+
+    + Properly format display equations (#8308).
+    + Remove -C option on PSPIC. Some old versions don't support this
+      option, and since it's the default it shouldn't be necessary.
+
+  * XWiki writer:
+
+    + Use template if it is specified (#8296). Previously
+      templates were ignored.
+
+  * LaTeX template:
+
+    + Set fonts after Beamer theme (Jeremie Knuesel). Beamer themes
+      such as metropolis and saintpetersburg change the default
+      fonts. This change gives precedence to the user font settings
+      by moving them after the loading of the Beamer theme.
+    + Set `\babelfont` when `mainlang` and `lang` are specified and
+      `pdflatex` is not being used (#8538). This is needed for good
+      results in Arabic.
+    + Add variable `urlstyle` (#8429, Amar Al-Zubaidi). This is set to
+      `same` by default, so users should not experience any change.
+
+  * HTML template:
+
+    + Remove default font size, line height and font family in
+      default inline css (#8423). `mainfont`, `fontsize`,
+      and `linestretch` can still be used as before; the only difference
+      is that we no longer provide opinionated defaults.
+      This commit also adds a `maxwidth` variable that sets `max-width`;
+      if not set, 36em is used as a default.
+    + Add `code { hyphens: manual; }`.
+    + Use `styles.citations.html` partial in `styles.html`.
+    + Fix class name `hanging` -> `hanging-indent` in
+      `styles.citations.html`.
+    + Put Consolas before Lucida Console for code font (#8543).
+      This is to prevent Lucida Console from being used on Windows, where
+      it causes spacing issues in some applications, with boldface
+      glyphs wider than regular ones.
+
+  * EPUB CSS changes: Reduce the amount of inline CSS used for EPUBs
+    (#8379). Almost everything is now in the default EPUB CSS
+    (`data/epub.css`), which can be overridden either by
+    putting `epub.css` in the user data directory or by using
+    `--css` on the command line.  Inline styles are only used
+    for syntax highlighting (which depends on the style
+    specified, and is only included on pages with highlighted
+    code) and for bibliography formatting (which can depend on
+    the CSL style, and is only used in the page containing the
+    bibliography).
+
+    Note that, for compatibility with older readers, we don't
+    use flexbox to style `column/columns` divs by default, as
+    we do in HTML.  Instead, we use an older method which only
+    works when there are two `column` divs inside a `columns`
+    div.  If you need more than two columns and aren't worried
+    about support for older EPUB readers, you can modify the
+    default CSS (there is a comment in the CSS telling you what
+    to do).
+
+  * Reveal.js template: prevent line-wrapping of parallax options
+    (#8503, Albert Krewinkel).
+
+  * reference.pptx: Remove unsupported element (#8342, #6338, Link Swanson).
+    The default template contained text above the header, which can mislead
+    users into thinking there is a way to put text there using pandoc.
+
+  * Text.Pandoc.Readers.Metadata:
+
+    + Fix metadata parsing corner case (#8465).
+    + Don't fail on inline metadata beginning with newline (#8358).
+
+  * Text.Pandoc.App:
+
+    + Move initial input-to-Pandoc code to internal submodule (Albert
+      Krewinkel).
+    + Change `parseOptionsFromArgs` and `parseOptions` (#8406)
+      They now return `Either OptInfo Opt`. [API change]
+    + Add `OptInfo` type [API change].
+    + Add `handleOptInfo` function.  This performs the IO actions for
+      things like `--version` that were previously done in
+      `parseOptionsFromArgs` [API change].
+    + `convertWithOpts`: add argument for a `ScriptingEngine` [API change].
+    + Unify check for standalone output (Albert Krewinkel).
+    + New `optEpubTitlePage` field on `Opt` [API change] (#6097).
+    + Remove `optEpubChapterLevel`, add `optSplitLevel` [API change].
+    + Export `IpynbOutput(..)` [API change].
+
+  * Text.Pandoc.App.OutputSettings:
+
+    + Remove unused field `outputWriterName` in `OutputSettings`.
+
+  * Text.Pandoc.Citeproc:
+
+    + Check both extension and mime type to determine bibliography type
+      when the bibliography is fetched remotely (#7151).
+    + CslJson: allow an object with `items` property in addition to
+      an array of references. This is what is returned by e.g.
+      `https://api.zotero.org/groups/904125/items?v=...&format=csljson`
+    + Require a digit for an implicit "page" locator inside explicit
+      locator syntax `{...}` (#8288). Previously a locator specified as
+      `{}` would be rendered as `p.` with nothing after it.
+    + Update `sub verbo` to `sub-verbo` (#8315). This is a change in
+      the term's canonical name in citeproc. As a result of this change,
+      `sub verbo` locators have not worked in pandoc since citeproc 0.7.
+    + Text.Pandoc.Citeproc.MetaValue: remove unused function
+      `metaValueToPath`.
+    + Add internal module Text.Pandoc.Citeproc.Name (#8345). This exports
+      `toName`, which previously had been part of T.P.Citeproc.BibTeX,
+      and allows for cleaner module dependencies.
+
+  * Export module `Text.Pandoc.Slides` [API Change] (Albert Krewinkel).
+
+  * Add new module Text.Pandoc.Format [API change] (Albert Krewinkel).
+    The module provides functions and types for format spec parsing and
+    processing. The function `parseFormatSpec` was moved from
+    Text.Pandoc.Extensions to the new module and renamed to
+    `parseFlavoredFormat`. It now operates in
+    a PandocMonad and is based on the updated types.
+
+  * Text.Pandoc.Sources:
+
+    + Add UpdateSourcePos instances for String and
+      strict and lazy ByteString [API change].
+
+  * Text.Pandoc.Extensions:
+
+    + Fix JSON decoding of Extensions (#8352, Albert Krewinkel).
+    + Add new exported function `readExtension` [API change].
+    + Remove `parseFormatSpec` [API change]. This has been moved
+      to Text.Pandoc.Format and renamed as `parseFlavoredFormat`
+      (Albert Krewinkel).
+    + Simpler implementation of Extensions based on Set
+      (benchmarks show no performance penalty).
+    + Add `CustomExtension` constructor to `Extension` [API change].
+    + Remove `Bounded`, `Enum` instances for `Extension`.
+    + Add `extensionsToList` function.
+    + Revise `readExtension` so it can handle `CustomExtension`, and so
+      that it returns a Text rather than `Maybe Text`.
+    + Add `showExtension` [API change].
+    + Add `Ext_mark` extension [API change].
+    + Add `Ext_tagging` constructor [API change] (Albert Krewinkel).
+    + Add `Ext_wikilinks_title_after_pipe`, `Ext_wikilinks_title_before_pipe`
+      [API change] (Albert Krewinkel).
+
+  * Text.Pandoc.PDF:
+
+    + Fix `papersize` on PDF generation via ms (#8403).
+      We need to set an option in pdfroff in addition to including
+      a macro in the ms file. With this fix, `-Vpapersize=a4` should be
+      sufficient to produce A4 PDF via ms.
+    + Change default background color of PDFs generated via HTML (#8422,
+      Marcin Serwin).
+
+  * Text.Pandoc.MIME:
+
+    + Base module on package `mime-types`, which
+      is already a transitive dependency (#8277, Albert Krewinkel).
+    + Remove deprecated overrides (#8292).
+
+  * Text.Pandoc.XML:
+
+    + Re-export `lookupEntity` from commonmark-hs [API change].
+
+  * Text.Pandoc.Parsing:
+
+    + Remove gratuitious renaming of Parsec types. We were exporting
+      Parser, ParserT as synonyms of Parsec, ParsecT.
+      There is no good reason for this and it can cause confusion.
+      Also, when possible, we replace imports of Text.Parsec with
+      Text.Pandoc.Parsing. The idea is to make it easier, at some point,
+      to switch to megaparsec or another parsing engine if we want to.
+      New (re-)exports: `Stream(..)`, `updatePosString`, `SourceName`,
+      `Parsec`, `ParsecT`. Removed exports: `Parser`, `ParserT`
+      [API change].
+    + Export `errorMessages`, `messageString` [API change].
+    + Export `fromParsecError`, which can be used to turn a parsec
+      ParseError into a regular PandocParseError (#8382) [API change].
+    + Remove `nested` [API change]. It was not being used, and in fact it
+      was a bad idea from the beginning, as it had no hope of solving
+      the problem it was introduced to solve.
+    + Change `characterReference`, `charsInBalanced`. `characterReference`
+      so they now return a Text (some named references don't correspond
+      to a single Char). Use the the `lookupEntity` function from
+      commonmark-hs instead of the slow one from tagsoup [API change].
+    + `charsInBalanced` now takes a Text parser rather than a Char parser
+      as argument [API change].
+
+  * Text.Pandoc.Shared:
+
+    + Export `textToIdentifier` [API change].
+    + Remove deprecated `crFilter`. [API change]
+    + Remove deprecated `deLink`. [API change]
+    + Deprecate `notElemText`.
+    + Deprecate `makeMeta`.
+    + Remove `pandocVersion` (now available in Text.Pandoc.Version
+      as `pandocVersionText`).
+    + Remove `findM` [API change]. This was only used in one place, and
+      can be replaced with simpler code.
+    + Remove deprecated `makeMeta` [API change].
+    + Remove `ordNub` [API change]. This is just `nubOrd` from
+      Data.Containers.ListUtils.
+    + Remove `mapLeft` [API change]. This is just a synonym for
+      Bifunctor.first.
+    + Remove `elemText`, `notElemText` [API change].
+    + Drop export of `pandocVersion` and `pandocVersionText`,
+      which are now exported by Text.Pandoc.Version.
+    + Remove `escapeURI`, `isURI`. These are now exported by
+      Text.Pandoc.URI, and removing them from Shared helps make
+      the module structure more straightforward.
+    + Use LineBreak as default block sep in `blocksToInlines`.
+      (#8499, Albert Krewinkel). This change also affects the
+      `pandoc.utils.blocks_to_inlines` Lua function.
+    + `defaultUserDataDir` is no longer exported (it has been
+      moved to T.P.Data) [API change].
+    + New function `figureDiv`, offering offers a standardized way
+      to convert a figure into a Div element (Albert Krewinkel) [API change].
+
+  * Text.Pandoc.Writers.Shared:
+
+    + Export `htmlAddStyle`, `htmlAlignmentToString` and `htmlAttrs`
+      [API change] (Wout Gevaert).
+    + Use 'literal tag' instead of 'text (T.unpack tag)' in `tagWithAttrs`
+      (Wout Gevaert).
+    + `toTableOfContents`: handle nested Divs better (#8402).
+
+  * Rename Text.Pandoc.Network.HTTP -> Text.Pandoc.URI.
+    This is still an unexported internal module.
+    Export `urlEncode`, `escapeURI`, `isURI`, `schemes`, `uriPathToPath`.
+    Drop exports of `schemes` and `uriPathToPath`.
+
+  * Text.Pandoc.URI `isURI`: don't require non-ASCII characters to be
+    escaped (#8508).
+
+  * Rename Text.Pandoc.Readers.LaTeX.Types -> Text.Pandoc.TeX (internal
+    module).
+
+  * Text.Pandoc.Options:
+
+    + WriterOptions now has a field `writerListTables`,
+      specifying that list tables be used in RST output [API change].
+    + New `writerEpubTitlePage` field on `WriterOptions` (#6097)
+      [API change].
+    + Remove `writerEpubChapterLevel`, add `writerSplitLevel` [API change].
+
+  * Text.Pandoc.Filter:
+
+    + Export `applyFilters` [API change].
+    + Export `applyJSONFilter` [API Change] (Albert Krewinkel).
+    + Parameterize `applyFilters` over scripting engine [API change] (Albert
+      Krewinkel).
+
+  * New exported module Text.Pandoc.Chunks [API change].  This
+    module provides functions to split Pandoc documents into
+    chunks to be rendered in separate files, e.g. one per
+    section.  Internal identifiers are rewritten appropriately to
+    point to the new locations (#6122).
+
+  * Text.Pandoc.Readers:
+
+    + Change argument type of `getReader`, so it takes a `FlavoredFormat`
+      instead of a `Text` [API change] (Albert Krewinkel).
+
+  * Text.Pandoc.Writers:
+
+    + Change argument type of `getWriter`, so it takes a `FlavoredFormat`
+      instead of a `Text` [API change] (Albert Krewinkel).
+
+  * Text.Pandoc.Templates:
+
+    + Do not try to normalize input to `getDefaultTemplate` (Albert
+      Krewinkel). The function `getDefaultTemplate` no longer splits off
+      extension modifers from the given format, as that conflicts with
+      using custom writers as formats. Haskell library users should use
+      `getDefaultTemplate <=< (fmap formatName . parseFlavoredFormat)`
+      if the input format can still contain extensions. The same is true
+      for `compileDefaultTemplate`, which calls `getDefaultTemplate`
+      internally
+    + Add Wrapper type documentation (#8490, William Rusnack).
+
+  * New exported module Text.Pandoc.Scripting (Albert Krewinkel).
+    The module contains the central data structure for scripting engines
+    (e.g., Lua) [API change].
+
+  * Text.Pandoc.Error:
+
+    + Add new PandocError constructor `PandocNoScriptingEngine` [API change]
+      (Albert Krewinkel).
+    + Add new PandocError constructor `PandocFormatError` [API change]
+      (Albert Krewinkel). The new error is used to report problems with
+      input or output format specifications.
+    + Add new PandocError constructor `PandocNoTemplateError`
+      (Albert Krewinkel).
+    + Remove `PandocParsecError` constructor from `PandocError` (#8385).
+      Henceforth we just use `PandocParseError`.
+
+  * New module Text.Pandoc.Version, exporting `pandocVersionText`
+    and `pandocVersion` [API change].  `pandocVersion` returns a `Version`
+    instead of a `Text`, which is consistent with `pandocTypesVersion`.
+
+  * Text.Pandoc.Class:
+
+    + Make `getPOSIXTime`, `getZonedTime` sensitive to `SOURCE_DATE_EPOCH`
+      environment variable if set (#7093).  (`getTimestamp` was
+      already sensitive.)  This ensures that EPUB builds are reproducible.
+    + Text.Pandoc.Class no longer exports `readDataFile`,
+      `readDefaultDataFile`, `setTranslations`, and `translateTerm`
+      [API change].
+    + Text.Pandoc.Class now exports `checkUserDataDir` [API change].
+
+  * T.P.Class.IO: export function `writeMedia` [API change] (Albert Krewinkel).
+    This is useful for the `pandoc.mediabag` module.
+
+  * Separate out Text.Pandoc.Data and Text.Pandoc.Translations from
+    Text.Pandoc.Class (#8348). This makes Text.Pandoc.Class
+    more self-contained.
+
+    + Text.Pandoc.Data is now an exported module, providing `readDataFile`
+      and `readDefaultDataFile` (both formerly provided by
+      Text.Pandoc.Class), and also `getDataFileNames` (formerly
+      unexported in Text.Pandoc.App.CommandLineOptions)
+      and `defaultUSerDataDir` (formerly provided by
+      Text.Pandoc.Shared). [API change]
+    + Text.Pandoc.Translations is now an exported module (along with
+      Text.Pandoc.Translations.Types), providing `readTranslations`,
+      `getTranslations`, `setTranslations`, `translateTerm`,
+      `lookupTerm`, `readTranslations`, `Term(..)`, and `Translations` [API
+      change].
+
+  * Text.Pandoc now exports Text.Pandoc.Data and `setTranslations`
+    and `translateTerm` {API change].
+
+  * Export module Text.Pandoc.Class.IO [API change].
+    The module is useful when defining instances of class PandocMonad for
+    types that are also instances of MonadIO.
+
+  * Remove modules Text.Pandoc.Writers.Custom and Text.Pandoc.Readers.Custom
+    [API Change] (Albert Krewinkel). The functions `writeCustom` and
+    `readCustom` are available from module Text.Pandoc.Lua.
+
+  * Text.Pandoc.Server:
+
+    + Split this module into a separate package, `pandoc-server`,
+      allowing the `pandoc` library to be compiled without server support.
+    + Return object if JSON is accepted. Previously we just returned
+      a JSON-encoded string. Now we return something like:
+      ```
+      {
+          "output": "<p>hello</p>"
+          "base64": false,
+          "messages": [
+              {
+                  "message": "Not rendering RawInline (Format \"tex\") \"\\\\noe\"",
+                  "verbosity": "INFO"
+              }
+          ],
+      }
+      ```
+      This is a change in the pandoc-server JSON API.
+    + Set translations in the writer based on `lang` metadata.
+    + Return error in JSON object if response is JSON.
+    + Remove `parseServerOpts`. [API change]
+
+  * Text.Pandoc.Lua:
+
+    + This module has been moved to a separate package,
+      `pandoc-lua-engine`.
+    + Export `applyFilter`, `readCustom`, and `writeCustom`.
+      No longer export the lower-level function `runFilterFile` [API
+      change].
+    + Change type of `applyFilter` [API Change] (Albert Krewinkel).
+      The module Text.Pandoc.Filter.Lua has been merged into
+      Text.Pandoc.Lua. The function `applyFilter` now has type
+      ``` haskell
+      applyFilter :: (PandocMonad m, MonadIO m)
+                  => Environment-> [String]-> FilePath-> Pandoc-> m Pandoc
+      ```
+      where `Environment` is defined in Text.Pandoc.Filter.Environment.
+    + Export new function `getEngine` [API Change].
+      The function returns the Lua scripting engine.
+    + Add unexported modules T.P.Lua.Reader, T.P.Lua.Writer.
+      These contain the definitions of `readCustom` and `writeCustom`
+      that were previously in T.P.Readers.Custom and T.P.Writers.Custom.
+    + Cleanup module dependencies, for a cleaner module dependency graph.
+    + The `writeCustom` function has changed to return a Writer and
+      an ExtensionsConfig [API change].  This allows ByteString writers
+      to be defined.
+    + The `readCustom` function has changed to return a Reader and an
+      ExtensionsConfig [API change].
+
+  * Lua subsystem (Albert Krewinkel):
+
+    + The whole Lua subsystem has been moved to a separate package,
+      `pandoc-lua-engine`.  `pandoc` does not depend on it.
+      `convertWithOpts` has a new parameter that can be used to
+      pass in the scripting engine defined in `pandoc-lua-engine`
+      (or a different one, in theory).
+    + Fix the behavior of Lua "Version" objects under equality
+      comparisons (#8267).
+    + Support running Lua with a GC-collected Lua state.
+    + Ensure that extensions marshaling is consistent.
+    + Produce more informative error messages for pandoc errors.
+      Errors are reported in Lua in the same words in which they would be
+      reported in the terminal.
+    + Add new module `pandoc.format`. The module provides functions to
+      query the set of extensions supported by formats and the set
+      of extension enabled per default.
+    + Add function `pandoc.template.apply`.
+    + Add function `pandoc.template.meta_to_context`.
+      The functions converts Meta values to template contexts; the intended
+      use is in combination with `pandoc.template.apply`.
+    + Allow Doc values in `WriterOptions.variables`.
+      The specialized peeker and pusher function for `Context Text` values
+      does not go via JSON, and thus keeps Doc values unchanged during
+      round-tripping.
+    + Fix rendering of Lua errors in Lua, so that the
+      `Error running Lua` message is not prepended multiple times.
+    + Add new module `pandoc.zip`.
+    + Allow strings in place of compiled templates (#8321).
+      This allows to use a string as parameter to `pandoc.template.apply`
+      and in the WriterOptions `template` field.
+    + Rename `reader_extensions`/`writer_extensions` globals as `Extensions`
+      (#8390).
+    + Add `pandoc.scaffolding.Writer` (#8377). This can be used to reduce
+      boilerplate in custom writers.
+    + Fix peeker for PandocError (Albert Krewinkel). String error messages
+      were incorrectly popped of the stack when retrieving a PandocError.
+    + Add functions `pandoc.text.toencoding`, `pandoc.text.fromencoding`
+      (#8512, Albert Krewinkel).
+    + Add `pandoc.cli` module. Allow processing of CLI options in Lua.
+    + Support `-D` CLI option for custom writers.
+      A new error `PandocNoTemplateError` (code 87) is thrown if a template
+      is required but cannot be found.
+    + Allow table structure as format spec. This allows to pass structured
+      values as format specifiers to `pandoc.write` and `pandoc.read`.
+    + Add function `pandoc.mediabag.write` (Albert Krewinkel).
+    + Add module `pandoc.structure` (Albert Krewinkel). The function
+      `make_sections` has been given a friendlier interface and moved to the
+      new module; the old `pandoc.utils.make_sections` has been deprecated.
+
+  * Custom writers:
+
+    + The global variables `PANDOC_DOCUMENT` and `PANDOC_WRITER_OPTIONS`
+      are no longer set when the writer script is loaded. Both variables
+      are still set in classic writers before the conversion is started,
+      so they can be used when they are wrapped in functions.
+    + Deprecate classic custom writers.
+    + Add function `pandoc.write_classic`. The function can be used to
+      convert a classic writer into a new-style writer by setting it as
+      the value of `Writer`:
+      ``` lua
+      Writer = pandoc.write_classic
+      ```
+      or to fully restore the old behavior:
+      ``` lua
+      function Writer (doc, opts)
+        PANDOC_DOCUMENT = doc
+        PANDOC_WRITER_OPTIONS = opts
+        load(PANDOC_SCRIPT_FILE)()
+        return pandoc.write_classic(doc, opts)
+      end
+      ```
+    + Support extensions in custom writers. Custom writers can define the
+      extensions that they support via the global `writer_extensions`.
+      The variable's value must be a table with all supported extensions
+      as keys, and their default status as values. For example,
+      the below specifies that the writer supports the extensions `smart`
+      and `sourcepos`, but only the `smart` extension is enabled by default:
+      ``` lua
+      writer_extensions = {
+        smart = true,
+        sourcepos = false,
+      }
+      ```
+    + Custom writers can define a default template via a global `Template`
+      function; the data directory is no longer searched for a default
+      template. Writer authors can restore the old lookup behavior with
+      ``` lua
+      Template = function ()
+        local template
+        return template.compile(template.default(PANDOC_SCRIPT_FILE))
+      end
+      ```
+
+  * Custom readers:
+
+    + Support extensions in custom readers.
+      Custom readers, like writers, can define the set of supported
+      extensions by setting a global. E.g.:
+      ``` lua
+      reader_extensions = {
+        smart = true,
+        citations = false,
+      }
+      ```
+
+  * Use latest versions of `commonmark-extensions`, `texmath`,
+    `citeproc`, `gridtables`, and `skylighting`.
+
+  * Use pandoc-types 1.23.  This adds the `Figure` Block
+    constructor and removes the `Null` Block constructor.
+
+  * Require aeson >= 2.0.
+
+  * Use jira-wiki-markup 1.5.0 (#8511, Albert Krewinkel). Fixes issues with
+    icon-like sequences at the beginning of words.
+
+  * Use doctemplates 0.11, avoiding a transitive dependency on HsYAML.
+
+  * Use skylighting 0.13.1.2.
+
+  * Allow mtl 2.3.1 (Alexander Batischev).
+
+  * Use latest skylighting-format-context.
+
+  * Allow building with mtl 2.3.
+
+  * Remove `lua53` flag.  We now only support Lua 5.4.
+
+  * Add hie.yaml for haskell language server.
+
+  * Add tools/latex-package-dependencies.lua.
+
+  * Update default CSL with latest `chicago-author-date.csl`.
+
+  * make_artifacts.sh: various small improvements.
+
+  * Remove sample.lua from data files (#8356).
+
+  * Documentation:
+
+    + Deprecate `PANDOC_WRITER_OPTIONS` in custom writers (Albert Krewinkel).
+    + Document `pandoc.write_classic` (Albert Krewinkel).
+    + Document new table features (Albert Krewinkel).
+    + Clarify what background-image does in reveal.js (#6450).
+    + Documentation improvements for `blank_before_blockquote`
+      (#8324, Pranesh Prakash).
+    + Update grid table documentation (#8346).
+    + Add note about MathJax fonts to `--embed-resources`.
+    + Use cabal's --package-env more (#8317, Artem Pelenitsyn).
+    + Modify Zerobrane instructions to use Lua 5.4 (#8353, Ian Max Andolina).
+    + Fix documentation for highlight-style in `pandoc-server.md`.
+    + Fix link to fedora package site (#8246, Akos Marton).
+    + Rephrase paragraph on format extensions (#8375, Ilona Silverwood).
+    + Update README.template (#8496, Sven Wick).
+    + Fix a tiny typo in lua-filters.md (TomBen).
+    + Clarify that `--css` should be used with `-s`.
+    + Clarify font selection for pdf -t ms (#8421, nbehrnd).
+    + Clarify docs for `--metadata-file` (#8459).
+    + Fix typo in epub.md (Vladimir Alexiev).
+    + Add missing backtick in filters.md (R. N. West).
+    + `doc/lua-filters.md`: add documentation for `pandoc.format`
+      (Albert Krewinkel).
+    + Fix epub-embed-font documentation (#8455, Terence Eden).
+    + Removed obsolete Templates section in CONTRIBUTING.md.
+    + Add manual section on accessible PDFs, archiving standards (#8312,
+      Albert Krewinkel).
+
+  * Tests.Command: remove unused `runTest`.
+
+  * Add pandoc-lua.1 man page.
+
+  * Improve `shell.nix`.
+
+  * Add `tools/moduledeps.lua` for inspecting the internal module
+    dependency tree.
+
+  * Fix macOS zip so pandoc-server is a symlink. This cuts its size by 2x.
+
+  * CI: Improve CI speed by caching more, eliminating macos builds,
+    and splitting benchmarks into a separate action, run by
+    manual dispatch. (We still test that benchmarks build in
+    the regular CI.) The cache can be expired manually by
+    modifying the secret `CACHE_VERSION`.
+
+  * Remove the unnecessary Setup.hs from pandoc.
+    Cabal does not need this with build-type 'simple'.
+
+  * Add pandoc-lua and pandoc-server (symlinks) and their man pages
+    to releases.
+
+  * Use hslua-cli package for pandoc-lua interface (Albert Krewinkel).
+
+  * Add `server` flag to pandoc-cli, allowing it to be compiled without
+    server support.
+
+  * pandoc-cli: Allow building a binary without Lua support (Albert
+    Krewinkel). Disabling the `lua` cabal flag will result in a
+    binary without Lua.
+
+  * Move `--version` handling to pandoc-cli. We need it here in order
+    to print information about whether server and Lua support have been
+    compiled in.
+
+  * Move `nightly` flag from pandoc to pandoc-cli (#8339).
+
+  * Makefile changes:
+
+    - `make help` will now print all the targets and what they do.
+    - Add targets: `coverage`, `weeder`, `moduledeps`, `prerelease`,
+      `ghcid`, `repl`, `linecounts`, `hie.yaml`, `binpath`.
+    - Note that you can `` alias pandoc=`make binpath` `` for
+      convenient local testing of a build.
+    - Rename `quick-cabal` -> `build`, `quick-test` -> `test`.
+    - Exclude tests from `SOURCEFILES`.
+
+  * Factor out xml-light into an internal library.
+
+  * Add CITATION.cff (#8434).
+
+  * Move trypandoc to a separate repository, jgm/trypandoc.
+
+## pandoc 2.19.2 (2022-08-22)
+
+  * Fix regression with data uris in 2.19.1 (#8239).
+    In 2.19.1 we used the base64URL encoding rather than base64.
+
+  * pandoc-server: handle `citeproc` parameter as documented (#8235).
+
+  * Org reader: treat *emacs-jupyter* src blocks as code cells (#8236,
+    Albert Krewinkel). This improves support for notebook-like org files
+    that are intended to be used with emacs-jupyter package.
+
+  * HTML writer and templates: revert to using `width` property for column
+    widths (Albert Krewinkel). The default `flex` and `overflow-x` properties
+    of a column are set to `auto`. In combination, these changes allow to
+    get good results when using columns with or without explicit widths.
+
+  * Org writer (Albert Krewinkel):
+
+    + Add support for jupyter nodebook cells (#6367).
+    + Prefix code language of ipynb code blocks with `jupyter-`.
+      This is the convention used by the *emacs-jupyter* package.
+    + Keep code block attributes as header args. This allows to keep more
+      information in the resulting `src` blocks, making it easier to
+      roundtrip from or through Org. Org babel ignores unknown header
+      arguments.
+    + Add code block identifier as `#+name` to src blocks.
+
+  * Fix some typos in the codebase (luz paz).
+
+  * Require hslua-module-path 1.0.3 (#8228, Albert Krewinkel).
+
+## pandoc 2.19.1 (2022-08-18)
+
+  * Add server capabilities.
+
+    + New exported module Text.Pandoc.Server [API change].
+    + The pandoc executable now starts up a web server when renamed or
+      symlinked as `pandoc-server`, and functions as a CGI program when
+      renamed or symlinked as `pandoc-server.cgi`.  See the man page for
+      `pandoc-server` for full documentation.
+
+  * Text.Pandoc.App.Opts: Redo `FromJSON` for `Opt` so that optional
+    values can be omitted (in which case the values from
+    `defaultOptions` are used).
+
+  * Org reader: treat "abstract" block as metadata (Albert Krewinkel, #8204).
+    A block of type "abstract" is assumed to define the document's abstract.
+    It is transferred from the main text to the metadata.
+
+  * Org template: add abstract from metadata as block of type "abstract"
+    (#8204).
+
+  * HTML writer: use `flex` property for column widths
+    (Albert Krewinkel, #8232).
+
+  * LaTeX writer:
+
+    + Add label to tables that have an identifier (Albert Krewinkel, #8219).
+      Tables with an identifier are marked with a `\label`. A caption is
+      always included in this case, even if the caption is empty.
+    + Use `\textquotesingle` for straight quotes in text.
+    + Fix widths of multicolumn cells (#8218).
+
+  * LaTeX template: fix behavior of `colorlinks` variable (Albert
+    Krewinkel, #8226). Fixes a regression in 2.19 that required the
+    `boxlinks` variable to be set in addition to the usual link coloring
+    variables. Otherwise links were never colored in LaTeX PDF output.
+
+  * Text.Pandoc.Highlighting: Export `lookupHighlightingStyle`
+    [API change]. Previously this lived in an unexported module
+    Text.Pandoc.App.CommandLineOptions, under the name
+    `lookupHighlightStyle`.
+
+  * Text.Pandoc.App:
+
+    + Remove unneeded MonadIO constraints in readSources.
+    + Factor out `convertWithOpts'` from `convertWithOpts`.
+      This runs in any PandocMonad, MonadIO, MonadMask instance.
+      So far it is not exported, but it might find a use later.
+
+  * Support `--strip-comments` in commonmark/gfm (#8222).
+    This change makes the commonmark reader sensitive to
+    `readerStripComments`.
+
+  * Lua: add function `pandoc.utils.citeproc` (Albert Krewinkel).
+    The function runs the *citeproc* processor on a Pandoc document.
+    Exposing this functionality to Lua allows to make citation processing
+    part of a filter or writer, simplifies the creation of multiple
+    bibliographies, and enables the use of varying citation styles in
+    different parts of a document.
+
+  * Refactor `linux/make_artifacts.sh`.
+
+  * Update INSTALL.md installation from source instructions.
+
+  * Use base64 package instead of base64-bytestring. It is supposed to be
+    faster and more standards-compliant.
+
+  * trypandoc improvements:
+
+    + Add dropdown with canned examples.
+    + Add citeproc support.
+    + Support csv, bibliographic and binary formats.
+    + Add load from file.
+    + Add permalink.  Don't always reload page.
+    + Use vanilla JS and CSS + the new `pandoc-server.cgi`.
+
+  * Allow haddock-library-1.11.0.
+
+  * Convert `tool/extract-changes.hs` to a Lua filter.
+
+
+## pandoc 2.19 (2022-08-03)
+
+  * Add `--embed-resources` flag (Elliot Bobrow, #7331).  This can be
+    used to embed resources without implying `--standalone`.
+    Deprecate `--self-contained` in favor of `--embed-resources --standalone`.
+
+  * Allow environment variable interpolation in `highlight-style`
+    and `pdf-engine` fields in defaults files
+    (#8061; Jaehwang Jung, #8073).
+
+  * Allow placing custom readers and writers in user data directory
+    (Albert Krewinkel, #8112) (`readers` and `writers` subdirectories).
+
+  * Add `tsv` (tab separated values) as an input format (#7974).
+    [API change]: Text.Pandoc.Readers.CSV now exports `readTSV`.
+    Internal change:  In Text.Pandoc.CSV, `CSVOptions` has changed
+    so that `csvQuote` takes a Maybe value.
+
+  * Add `tex_math_dollars` to `gfm` default extensions (reflecting
+    gfm's new support for math).
+
+  * RST, Org, Markdown readers: support rowspans and colspans in grid tables
+    (#8202, Albert Krewinkel). Note: the writers does not yet support these
+    more complex grid table features, so these complex grid tables will
+    not round-trip.
+
+  * HTML, LaTeX, and MediaWiki readers: use `formatCode`
+    (#8162, #8129, Elliot Bobrow). This moves formatting from inside inline
+    code elements to the outside, since pandoc's Code element only takes string
+    content.
+
+  * Markdown reader:
+
+    + Don't parse inline notes with blank lines inside (#8028).
+    + Allow attributes in special spans (e.g. `smallcaps`, `underline`)
+      (Albert krewinkel, #4102). These spans are parsed as
+      SmallCaps or Underline elements, but any attributes are included
+      in a wrapping Span.
+
+  * HTML reader:
+
+    + Allow sublists that are not marked as items (Albert
+      Krewinkel, #8150). This is technically invalid HTML, but it can
+      be found in the wild and browsers handle it.
+
+  * Org reader (Albert Krewinkel):
+
+    + Recognize absolute paths on Windows (Albert Krewinkel, #8201).
+    + Recognize {webp,jxl} files as images (YI).
+    + Allow attrs for Org tables (Albert Krewinkel, #8049). Tables with
+      attributes are no longer wrapped in Div elements; attributes are added
+      directly to the table element.
+    + Support line selection in INCLUDE directives (Brian Leung, #8060).
+    + Fix Post / Pre mixup when setting emphasis chars (Amir Dekel, #8134).
+
+  * LaTeX reader:
+
+    + Support `\includesvg` (#8027).
+    + Unescape characters in `\lstinline` inside `\passthrough` (#8179).
+    + Improve `mathEnvWith` (#8122). When converting e.g. an align
+      environment to an aligned environment inside a Math element, we need
+      to include a newline before the `\end{aligned}`, since the previous
+      line might end in a comment.
+    + Fix treatment of extensions for `\input` in LaTeX reader (#8092).
+      Previously we required a `.tex` extension, but TeX
+      allows any extension for `\input` (as opposed to `\include`).
+
+  * RTF reader:
+
+    + support `\nosupersub` (#8170).
+
+  * TikiWiki reader:
+
+    + Support underlined text
+
+  * DocBook reader:
+
+    + Improved reading `<xref>` elements (Frerich Raabe, #8065).
+
+  * JATS reader:
+
+    + Strip `ref-` prefix from ref id in xref (#8007).
+    + Support edition in references (#8087).
+
+  * RIS reader:
+
+    + Make parser more forgiving (#8034). Allow blank lines after entries.
+      Allow entries with no space after the `-`, provided they
+      just have a newline, e.g. `DB -\n`.
+    + Get right order of names (#8055).
+
+  * MediaWiki reader:
+
+    + Allow HTML comment after row start (#8110).
+
+  * DokuWiki reader:
+
+    + The `tex_math_dollars` extension is now supported for `dokuwiki`
+      (but off by default) (#8178).
+    + Content inside `<latex>...</latex>` is parsed as raw LaTeX inline,
+      and inside `<LATEX>..</LATEX>` as raw LaTeX block (#8178).
+    + The behavior of `<php>...</php>` is changed, so that instead of
+      producing a code block, it produces raw HTML with `<?php ... ?>`.
+
+  * LaTeX writer:
+
+    + Improve grouping with autocites (#8088).
+    + Extend list of book documentclasses (Wentau Han, #8053).
+    + Fix width of multicolumn cells (Albert Krewinkel, #8090).
+      Cells spanning multiple columns must be given an explicit width,
+      calculated from the table properties.
+    + Beamer: allow containsverbatim as alternative to fragile (#8080).
+
+  * HTML writer:
+
+    + Add 'footnotes' identifier to footnotes section (#8043).
+    + Fix bug with `--number-offset`. This formerly caused section divs
+      to be produced, even when `--section-divs` was not specified (#8097).
+    + Use CSS flexboxes for columns (Albert Krewinkel). This allows
+      an arbitrary number of columns, while the previous approach assumed
+      exactly two columns.
+    + Allow "spanlike" classes to be combined (see #8194). Previously
+      classes like "underline" and "marked" had to be the first class
+      in a span in order for the span to be interpreted as a "ul" or
+      "mark" element.  This commit allows these special classes to be
+      "stacked," e.g. `[test]{.mark .underline}`; in addition, the
+      special classes are no longer required to come first in the list
+      of classes.
+    + Avoid doubled style attribute when height and width are added to
+      style because of an image, but the image already has a style attribute
+      (#8047).
+    + Do not include the deprecated doc-endnote role (#8030).
+      doc-endnote was deprecated in DPUB-ARIA 1.1.
+    + Remove extra soft break for tasklist (black-desk, #8142).
+      Browser will display the extra newline character between checkbox and
+      text as a space, which make tasklist items cannot be aligned.
+
+  * EPUB writer:
+
+    + Allow choice of math method for v3 (#8164). Previously we always
+      used MathML for math in EPUB3, because the spec includes MathML.
+      But this is not widely supported by readers, so it seems better
+      to allow users to choose their math method as they can with
+      EPUB2 or HTML. **NOTE:** Existing workflows that produce EPUBv3
+      documents including math will be affected by this change.  You
+      must add `--mathml` to your command line if you want to continue
+      producing MathML.
+
+  * RST writer:
+
+    + Fix missing spaces with nested inlines (#8182).
+    + Always escape literal backslash (#8178).
+
+  * Ms writer:
+
+    + Add comment in preamble stating generator.
+    + Fix roff ms syntax highlighting definitions (#8175, thanks to
+      Branden Robinson).
+
+  * ConTeXt writer:
+
+    + Support complex table structures (Albert Krewinkel, #8116).
+      The following table feature are now supported in ConTeXt:
+
+      - colspans,
+      - rowspans,
+      - multiple bodies,
+      - row headers, and
+      - multi-row table head and foot.
+
+      The wrapping `placetable` environment is also given a `reference` option
+      with the table identifier, enabling referencing of the table from within
+      the document.
+    + Unify link handling (Albert Krewinkel, #8096).
+      Autolinks, i.e. links with content that's the same as the linked URL,
+      are now marked with the `\url` command. All other links, both internal
+      and external, are created with the `\goto` command, leading to shorter,
+      slightly more idiomatic code. As before, autolinks can still be styled
+      via `\setupurl`, other links via `\setupinteraction`.
+    + Use "sectionlevel" environment for headings (Albert Krewinkel, #5539).
+      The document hierarchy is now conveyed using the
+      `\startsectionlevel`/`\stopsectionlevel` by default. This makes it easy
+      to include pandoc-generated snippets in documents at arbitrary levels.
+      The more semantic environments "chapter", "section", "subsection", etc.
+      are used if the `--top-level-division` command line parameter is set to
+      a non-default value.
+
+  * Docx writer:
+
+    + Add `w:lang` to `rPr` for Span and Div with lang attribute, so
+      that Word can know that "Apfel" is not a spelling error (#8026).
+    + Prevent crashing when handling invalid tables (Albert Krewinkel, #8102).
+      Tables with different numbers of cells per row would sometimes crash
+      pandoc. This fix prevents this by cutting off overlong rows.
+
+  * ICML writer:
+
+    + Support custom-style attribute on Table (#8079).
+
+  * AsciiDoc writer:
+
+    + Fix commas in link text (#8070). Commas in link text trigger
+      interpretation of attributes. To block this, we replace them with
+      numeric entities.
+    + Fix underline. We were rendering it as `+++text+++`; this is now
+      changed to `[.underline]#text#`.  See comment at
+      <https://github.com/jgm/pandoc/issues/8070#issuecomment-1126883824>.
+
+  * FB2 writer:
+
+    + Fix handling of non-section Divs (#8123).
+
+  * Markdown writer:
+
+    + Disable soft wrapping when `hard_line_breaks` enabled (#8035).
+      We were already doing this for `markdown`; this commit does
+      the same thing for `markua` and `commonmark` and `gfm`.
+    + Avoid excessive indentation on bullet lists for `commonmark`,
+      `markua`, `gfm`.  They are now nested by 2 spaces instead of 4 (#8011).
+
+  * Text.Pandoc.Class:
+
+    + Add new function `findFileWithDataFallback` [API Change]
+      (Albert Krewinkel).
+    + `fillMediaBag`: Keep attributes of original image on Span (Albert
+      Krewinkel, #8099). Images that cannot be fetched are replaced with a
+      Span that contains the image's description. The span now also retains
+      all original image attributes and inherits all attributes of the image.
+      Furthermore, the classes `image` and `placeholder` are added, and path
+      and title are store in attributes `original-image-src` and
+      `original-image-title`, respectively.
+
+  * Text.Pandoc.Shared:
+
+    + `makeSections`: don't make a section for a div with class "fragments"
+      (#8098).
+    + Ensure that Nulls are ignored by `makeSection` and in segmenting
+      slides (#8155).
+    + Add `formatCode` function to Text.Pandoc.Shared [API change]
+      (Elliot Bobrow, #8129).
+    + `taskListItemToAscii`: handle asciidoctor's characters (#8011).
+      Asciidoctor uses different unicode characters for task
+      lists; we should recognize them too and be able to convert
+      them to ascii task lists in formats like gfm.
+    + Deprecate `deLink` and mark for later removal.
+
+  * Text.Pandoc.Writers.Shared:
+
+    + `toTableOfContents`: Don't replace links with empty spans in TOC (#8020).
+
+  * Text.Pandoc.Readers.Metadata:
+
+    + Ensure that metadata values w/o trailing newlines are
+      parsed as inlines, as the manual states.
+      Previously, they were parsed as inlines if they would
+      otherwise have been a single Plain or Para, but otherwise
+      left unchanged.  This led to some quirky results (e.g. #8143).
+      We now use the general function `blocksToInlines` from T.P.Shared.
+
+  * Text.Pandoc.Parsing:
+
+    + Simplify `gridTableWith'`, `gridTableWith` [API Change] (Albert
+      Krewinkel). The functions `gridTableWith` and `gridTableWith'` no
+      longer takes a boolean argument that toggles whether a table head
+      should be parsed: both, tables with heads and without heads, are
+      always accepted now.
+
+  * Lua subsystem (Albert Krewinkel):
+
+    + Extend `pandoc.system` module (Albert Krewinkel, #8184).
+      The module now has the additional functions `list_directory`,
+      `make_directory`, and `remove_directory`. This makes it easier to write
+      cross-platform scripts that need to inspect or modify the file system.
+    + Require pandoc-lua-marshal 0.1.7. Adds a `clone` methods to
+      Pandoc objects and allows to pass Blocks in instead of full
+      Caption elements.
+    + Add fields `pandoc.readers` and `pandoc.writers` (#8177).
+      The set of supported input and output formats is made available to Lua
+      users.
+    + Ensure that tables marshaled via JSON arrays behave like Lists.
+      This allows to invoke methods like `map` and `includes` on lists like
+      `PANDOC_WRITER_OPTIONS.extensions`.
+    + Require hslua-2.2.1, unless lua53 flag is set, and do not reset
+      foreign encoding before running Lua. This fixes a problem where
+      the encoding used for Lua filenames would sometimes mismatch the
+      encoding used by the OS.
+    + Simplify module loading code. Modules are now loaded directly;
+      the special pandoc Lua package searcher is no longer necessary and
+      has been removed.
+    + Add function pandoc.mediabag.fill (#8104). The function allows to
+      fill the mediabag with all images in a given document. Images that
+      cannot be fetched are replaced with a Span containing the
+      image description.
+
+  * Populate mediabag after filters have run (Albert Krewinkel, #8099).
+    The mediabag is filled with document resources after the filters have
+    run. This allows, for example, filter authors to modify image paths
+    before pandoc tries to fetch the images.
+    Lua filters that rely on a filled mediabag can use the new
+    `pandoc.mediabag.fill` function to perform that action in the filter.
+
+  * Ms template: redefine rather than removing .CH macro (#8175).
+
+  * JATS template (Albert Krewinkel, except as noted):
+
+    + Include particles, prefix, suffix in names.
+    + Mark authors with cor-id as corresponding authors.
+      Corresponding authors are marked by setting the attribute
+      `corresp="yes"` in their respective `<contrib>` element.
+    + Unconditionally include permissions element (#8040).
+      Fixes a bug that caused license information to be omitted when no
+      copyright information was provided.
+    + Follow JATS4R recommendation and PudMed Central for license URI
+      (Castedo Ellerman, #8041).
+
+  * LaTeX template:
+
+    + Rename  `\textormath` to `\TextOrMath` (Hos Es, #8036).
+    + Fix links-as-notes (Albert Krewinkel, #8077).
+
+  * HTML template styles:
+
+    + Remove `span.underline` rule. This is superfluous now that we
+      render Underline as `<u>`.
+    + Improve CSS for task lists (#8151).
+
+  * LaTeX template: Add `boxlinks` variable for LaTeX/PDF output (#8198).
+    If `boxlinks` is set but `colorlinks` is not, then boxes will
+    be printed around links (`hidelinks` will not be set in `hypersetup`).
+
+  * `--self-contained`: Handle `url()` in `<style>` elements (#8193).
+
+  * Text.Pandoc.PDF: use SHA1 hash of filename when converting SVG.
+    The previous code threw away the directory component of
+    the filename in constructing a new one. This led to
+    surprising results if you had e.g. `foo/pic.svg` and `bar/pic.svg`;
+    in the final PDF they'd be the same image, because the latter
+    would overwrite the former in the temp directory.
+
+  * Remove Muse reader round-trip tests. These are nondeterministic and have
+    repeatedly failed on strange edge cases.
+
+  * Update fonts MIME following IANA recommendation (Gabriel Lewertowski,
+    #8127).
+
+  * Future compat change for `liftA2` export from Prelude (Georgi Lyubenov,
+    #8132).
+
+  * Update `default.csl` from the latest chicago-author-date.csl.
+
+  * Update manfilter.hs for greater portability (#8045).
+    The tables in our man pages were not rendering correctly
+    with mandoc, now used by default with macOS. mandoc doesn't
+    allow man formatting inside table cells. For maximum portability,
+    we now render the tables in plain format and include them as code
+    blocks in the man page.
+
+  * CI: update macos container version (#8197, Sukka).
+
+  * Add `nightly` flag. This causes a `-nightly-COMPILEDATE`
+    suffix to be added the the output of `--version` (#8016).
+    This is used in the nightly CI builds.
+
+  * Update dependencies (aeson, skylighting, pandoc-lua-marshall,
+    citeproc, texmath).
+
+  * Documentation improvements (thanks to Jiří Wolker,
+    Castedo Ellerman, Albert Krewinkel, Bastien Dumont, Cezar Drożak, Benjamin
+    Wuethrich, Ivan Panchenko, Sukil Etxenike, Masataka Ogawa).
+
+## pandoc 2.18 (2022-04-04)
+
+  * New input formats: `endnotexml` (EndNote XML bibliography),
+    `ris` (RIS bibliography).
+
+  * A RIS bibliography file may now be used with `--citeproc`.
+
+  * Citeproc: Allow a formatted bibliography to be placed in metadata fields
+    via a Div with class `refs` (#7969, #526).  Thus, one can include a
+    metadata field, say `refs`, whose content is an
+    empty div with id `refs`, and the formatted bibliography will be put into
+    this metadata field.  It may then be interpolated into a template using the
+    variable `refs`.
+
+  * Ensure that you don't get PDF output to terminal.  `-t pdf` now behaves
+    like `-t docx` and gives an error unless the output is redirected.
+
+  * `--version` now prints hslua version (#7929) and
+    Lua version (#7997, Albert Krewinkel).
+
+  * Change `--metadata-file` parsing so that, when the input format is not
+    markdown or a markdown variant, pandoc's markdown is used (#6832, #7926).
+    When the input format is a markdown variant, the same format is used.
+    Reason for the change: it doesn't make sense to run the markdown parser
+    with a set of extensions designed for a non-markdown format, and
+    this dramatically limits what people can do in metadata files.
+
+  * Trim whitespace from math in `--webtex` (#7892).
+    This fixes problems with --webtex and markdown output,
+    when display math starts or ends with a newline.
+
+  * `--self-contained`: issue warning rather than failing with an error
+    if a resource can't be found (#7904).
+
+  * New exported module Text.Pandoc.Readers.EndNote, exporting
+    `readEndNoteXML` and `readEndNoteXMLCitation` [API change].
+
+  * New exported module, Text.Pandoc.Readers.RIS, exporting `readRIS` (#7894)
+    [API change].
+
+  * LaTeX reader:
+
+    + Handle subequations as inline math environment (#7883).
+    + Rudimentary support for `vbox` (#7939).
+    + Support `\today` (#7905).
+    + Handle `\label` and `\ref` for footnotes (#7930).
+    + Allow inline groups starting with `\bgroup` (#7953).
+    + Use custom TokStream that keeps track of whether macros are expanded.
+      This allows us to improve performance a bit by avoiding unnecessary
+      runs of the macro expansion code (e.g. from 24 ms to 20 ms on
+      our standard benchmark).
+    + Further optimizations for inline parsing.
+    + Better handling of `\usepackage`.  If the package is local but
+      causes parse errors, parse everything up to the error and skip the
+      rest.  Issue a `CouldNotParseIncludeFile` warning indicating that
+      parsing failed at that point.
+    + Text.Pandoc.Readers.LaTeX.Parsing: Monoid and Semigroup instances for
+      TokStream.
+
+  * HTML reader:
+
+    + Give warnings and emit empty note when parsing
+      `<a epub:type="noteref">` and the identifier
+      doesn't correspond to anything in the note table (#7884).
+      Previously we just silently skipped these cases.
+    + Fix parsing of epub footnotes (#7884).
+
+  * DocBook reader:
+
+    + Handle complete set of entities as specified at
+      <https://www.w3.org/2003/entities/2007doc/byalpha.html> (#7938).
+    + Handle abstract in info section (#7747).
+    + Improve info parsing.
+    + Simplify metadata parsing code (#7747).
+      Handle abstract as block-level content.
+      Report skipped info elements with `--verbose`.
+    + Handle address and coyright in metadata (#7747).
+
+  * DokuWiki reader:
+
+    + Add DokuWiki table alignment (#5202, damon-sava-stanley).
+
+  * RST reader:
+
+    + Fix treatment of headerless simple tables (#7902).
+    + Wrap math in Span to preserve attributes (#7998, Albert Krewinkel).
+      Math elements with a name, classes, or other fields are wrapped in a
+      `Span` with these attributes.
+
+  * JATS reader:
+
+    + Improve handling of fn-group elements (#6348, Albert Krewinkel).
+      Footnotes in `<fn-group>` elements are collected and re-inserted into
+      the document as proper footnotes in the place where they are referenced.
+    + Handle `pub-date` (#8000).
+    + Support PMID, DOI, issue in citations (#7995).
+    + Improve refs parsing.  Handle `issn` and `isbn`; use simpler form
+      for issued date.
+    + Strip 'ref-' from ref id in constructing CSL id.  This allows better
+      round-tripping, because the JATS writer adds the `ref-` prefix to
+      the citation id to get the ref element's id.
+
+  * Org reader:
+
+    + Allow ":" in property drawer keys (Lucas V. R).
+      Any non-space character is allowed as property drawer key, including ":"
+      itself (so it is not really a delimiter). The real delimiter is a space
+      character, so in a drawer like
+      ```
+      :PROPERTIES:
+      ::k:ey:: value
+      :END:
+      ```
+      ":k:ey:" is a key with value "value".
+
+    + Allow comments above property drawer.
+    + More flexible LaTeX environments (Lucas V. R).
+    + Handle `#+bibliography:` as metadata so that it can work with
+      `--citeproc`.
+    + Parse `#+print_bibliography:` as Div with id `refs`.
+    + Allow multiple `#+bibliography:`.
+
+  * Markdown reader:
+
+    + Allow one-column pipe tables with pipe on right (#7919).
+    + Remove restriction on identifiers, so they no longer need to
+      begin with a letter (#7920).
+
+  * Docx reader:
+
+    + Enable `citations` extension for docx reader (#7840).
+      When enabled, Zotero, Mendeley, and EndNote citations embedded in
+      a docx are parsed as native pandoc citations.
+      (When disabled, the generated citation
+      text and bibliography are passed through as regular text.)
+      The bibliography generated by the plugin is suppressed.
+      Instead, bibliographic data embedded in citation items is added
+      to the `references` metadata field so that it can be used
+      with `--citeproc`.
+
+  * Docbook writer:
+
+    + Interpret links without contents as cross-references (#7360, Jan Tojnar).
+      Links without text contents are converted to `<xref>` elements. DocBook
+      processors will generate appropriate cross-reference text when presented
+      with an xref element.
+
+  * Docx writer:
+
+    + Single numbering ID for examples (#7895, mjfs).
+      This change ensures that example list items all belong to a single
+      number sequence, so that if items are added or deleted in a word
+      processor, the other items will renumber automatically.
+    + Add bookmark with table id to table (#7989, Nikolai
+      Korobeinikov, #7285).  This allows tables with ids to be linked to.
+
+  * Ipynb writer:
+
+    + Handle metadata better (#7928).  Previously we used the markdown
+      writer to render metadata.  This had some undesirable consequences
+      (e.g. en dash expanded to `--` when `smart` enabled), so now we use
+      the plain writer.
+
+  * LaTeX writer:
+
+    + Avoid extra space before `\CSLRightInline` (#7932).
+    + Add `scrreport` to `chaptersClasses` (#6168, ivardb).
+    + Support `page`,`trim`,`clip` attributes on images (#7181).
+    + Add `()` after booktabs rules (#8001).  These commands take optional
+      arguments with () and [], which can lead to problems if the content
+      of the table cell begins with these characters.
+
+  * RST writer:
+
+    + Support all standard metadata ("bibliographic") fields.
+
+  * HTML writer: performance improvements.
+
+  * Org writer:
+
+    + Stop indenting property drawers, quote blocks
+      (#3245, Albert Krewinkel).  This follows the current default org-mode
+      behavior.
+
+  * Markdown writer:
+
+    + Move table-related code into submodule (Albert Krewinkel).
+    + Don't produce redundant header identifier when the
+      `gfm_auto_identifiers` extension is set (#7941).
+    + Update escaping rules for `\`.  We now escape `\` only if `raw_tex`
+      is enabled or it is followed by a non-alphanumeric.
+
+  * JATS writer:
+
+    + Encode author "others" as `<etal/>` (Albert Krewinkel).
+      Citeproc adopted the BibTeX convention to use the author name "others"
+      when there are additional authors that are not named. JATS uses the
+      `<etal>` element for this.
+    + Avoid doubled ref-list element (#7990).  Previously when generating JATS
+      with the `element_citations` extension enabled, the references were
+      put in a doubly-nested ref-list element (`<ref-list><ref-list>...`).
+    + Keep edition info in element citations (#7993, Albert Krewinkel).
+    + Fix handling of CSL variable 'page' (not 'pages' as we had before).
+      It should go to 'lpage' and 'rpage', not 'page-range'.
+
+  * EPUB writer: refactor for clarity (#7991, Jonathan Dönszelmann,
+    Ola Wolska, Ivar de Bruin, Jaap de Jong).
+
+  * Custom writer (Albert Krewinkel):
+
+    + Support new-style Writer function (Albert Krewinkel).
+      See the documentation for custom writers for details.
+    + Produce stacktrace if Writer function fails
+
+  * Text.Pandoc.Logging: add `CouldNotParseIncludeFile` constructor
+    for `LogMessage` [API change].
+
+  * Text.Pandoc.Shared:
+
+    + Put id attributes on TOC entries (#7907, damon-sava-stanley).
+      Naming scheme of id is "toc-" + id of linked to header/section.
+      Effects HTML, Markdown, Powerpoint, and RTF.
+    + Define `ordNub` as alias for `nubOrd` from containers package (#7963,
+      Albert Krewinkel).
+    + Export `ensureValidXmlIdentifiers`.  This function changes identifiers
+      that don't start with letters, and internal links to these identifiers,
+      making them compatible with XML standards.  The change
+      is simple: we add `id_` to the front.  There is potential
+      for duplication if there are already `id_...` identifiers
+      defined, but this seems rare enough not to worry too much
+      about.
+
+  * Ensure that valid XML identifiers are used in Docbook, EPUB, FB2,
+    HTML4, S5, Slidy, Slideous, ICML, ODT, TEI writers.
+    Thus, if you convert `[anchor]{#1} and [link to](#1)`,
+    `id_1` will be used instead of `1` for the identifier.
+
+  * Lua (Albert Krewinkel).
+
+    + Add module `pandoc.layout` to format and layout text.
+    + Move custom writer code into Lua hierarchy.
+    + Use pandoc-lua-marshal 0.1.5.
+    +  Allow any type of callable object as argument to List
+       functions `filter`, `map`, and `find_if`. These previously
+       required the argument to be of type `function`, which was too
+       restrictive.
+    + Inline: the type of Image captions is now `Inlines` instead of `List`.
+    + Allow passing `Sources` to `pandoc.read` (#8002).
+
+  * Text.Pandoc.PDF:
+
+    + Restore `wkhtmltopdf` as default pdf engine for HTML (Albert Krewinkel).
+    + Allow custom writer as format if engine is explicitly specified (#7898,
+      Albert Krewinkel).  Note that it may be necessary to explicitly
+      specify a template on the command line.
+
+  * Text.Pandoc.MediaBag: improve detection of absolute paths (#7881).
+
+  * Text.Pandoc.Extensions:
+
+    + Remove `raw_tex` extension from list of commonmark extensions, and
+      from the `commonmark_x` defaults.  commonmark doesn't parse raw TeX,
+      and it doesn't make sense to write it if we don't parse it.
+    + Remove `native_divs` from allowed gfm extensions (#7965).  This allows
+      `<div>` to be suppressed using `-raw_html`.  Previously `native_divs`
+      was enabled but could not be suppressed, because it was not in the
+      list of available extensions for commonmark-based formats.
+
+  * Text.Pandoc.Parsing:
+
+    + Partition module into (internal) submodules (#7962, Albert Krewinkel).
+    + Unify grid table parsing (#7971, Albert Krewinkel).
+      Grid table parsing in Markdown and RST are updated use the same
+      functions. Functions are generalized to meet requirements for both
+      formats.  This change also lays the ground for further generalizations
+      in table parsers, including support for advanced table features.
+      [API change] in Text.Pandoc.Parsing:
+
+      - Parse results of functions `tableWith'` and `gridTableWith'` are now a
+        `mf TableComponents` instead of a quadruple of alignments, column
+        widths, header rows and body rows.
+      - Additional exports from Text.Pandoc.Parsing:
+        `tableWith'`, `TableComponents`, `TableNormalization`,
+        `toTableComponents`, `toTableComponents'`.
+
+  * Text.Pandoc.XML.Light: add versions of the parsers that allow
+    specifying a custom entity map.  Exports new functions:
+    `parseXMLElementWithEntities`, `parseXMLContentsWithEntities` [API change].
+
+  * Text.Pandoc.Writers.GridTable: improve module documentation (Albert
+    Krewinkel).
+
+  * Text.Pandoc.Parsing.GridTable: simplify column handling code (Albert
+    Krewinkel).
+
+  * Text.Pandoc.MIME: Add mime type for mkv extension (#7181).
+
+  * Text.Pandoc.Asciify: Fix regression with `ascii_identifiers` and Turkish
+    undotted i (#8003).
+
+  * Relax upper bound for hslua, allow hslua-2.2. (#7929)
+    Lua 5.4 is used by default after this is merged. Packagers may still
+    include Lua 5.3 instead by building pandoc with `--constraint='hslua <2.2'`.
+    Differences between 5.3 and 5.4 should not generally affect pandoc Lua
+    filters.  See list of incompatible changes here:
+    <https://www.lua.org/manual/5.4/manual.html#8.1>
+
+  * JATS template: allow multiple licenses (Albert Krewinkel).
+
+  * LaTeX template:
+
+    + Skip `\babelprovide` if `babel-lang` is empty (#7945) to avoid an error.
+    + Move hyperref near end of preamble (#5811).  It now comes after
+      header-includes and right before title, author, date, abstract.
+      Note:  Users who presuppose hyperref in their header-includes
+      will now have to add `\usepackage{hyperref}` to their header-includes
+      to make it available there.  (The redundant `\usepackage` will
+      do no harm in this case.)
+    + Remove special redefinition of `\sout`.  This used to be necessary to
+      avoid problems with hyperref, when headings contain strikeout text,
+      but it does not seem to be necessary any more (tested).
+
+  * Tests: improve location reporting of failing tests (Albert Krewinkel).
+
+  * Add tests for idempotency of `makeSections` (#7950).
+
+  * Add armhf support in linux build script (#7944, Tony).
+
+  * Use latest pandoc-types, so that toJSONFilter will work with
+    Meta and MetaValue.
+
+  * Use latest doclayout, texmath, commonmark, citeproc.
+
+  * INSTALL.md: add reference to install via winget (#7951, Guriy Samarin).
+
+  * MANUAL.txt:
+
+    - Document way to get list in block quote in slide shows (#7916).
+    - Minor changes to security section.
+    - Note that `smart` works for html input.
+    - Fix typos (#7934, Dimitris Apostolou).
+    - Fix documentation for citations and org mode.
+    - Remove claim that `--self-contained` does not work with `--mathjax`
+      (#682).
+
+  * doc/org.md: remove obsolete citations section.
+    This mostly described citation formats we no longer support.
+
+  * doc/lua-filters.md: Fix typo (#7981, Mario Lang).
+
+  * Makefile: Use cabal for default build
+
+  * Add `lua53` cabal flag.  It is false by default.  If set to true, compile
+    with hslua 2.1 and Lua 5.3, otherwise hslua 2.2 and Lua 5.4.
+
+
+## pandoc 2.17.1.1 (2022-01-31)
+
+  * Fix regression in 2.17.1 which caused problems finding
+    default files in the default user data directory.  (Reverts
+    the item "logic bug in `fullDefaultsPath`", which was
+    misguided.)
+
+  * Sample custom writer: use single quotes for strings (#7487,
+    Albert Krewinkel).
+
+## pandoc 2.17.1 (2022-01-30)
+
+  * Support `pagedjs-cli` as pdf engine (#7838, Albert Krewinkel).
+    PagedJS is a polyfill and supports the Paged Media standards by the W3C.
+    <https://www.pagedjs.org/>
+
+  * CommonMark reader: fix source position after YAML metadata (#7863).
+
+  * LaTeX reader:
+
+    + Remove retokenizing in `rawLaTeXParser`.
+    + Ensure that `\raggedright` doesn't gobble an argument (#7757).
+    + Improve `descItem`.  For some reason we were skipping
+      arbitrary blocks before `\item`.  This is now changed to "skip
+      whitespace and comments."
+    + Improve handling of `\newif`.  Adding a pair of braces around the
+      second argument of `\def` prevents LaTeX from an emergency stop
+      on input like the following (#6096).
+      ```
+      \newif\ifepub
+      \epubtrue
+      \ifepub
+      hi
+      \fi
+      ```
+
+  * Docx reader: Parse both Zotero citation and bibliography as
+    `FieldInfo` (#7840).
+
+  * LaTeX writer:
+
+    + Allow arbitrary frameoptions to be passed to a beamer
+      frame, using the frameoptions attribute (#7869).
+    + Add s and squeeze to recognized beamer frameoptions (#7869).
+
+  * Markdown writer: handle explicit column widths with pipe tables (#7847).
+    If a table has explicit column width information *and* the content
+    extends beyond the `--columns` width, we need to adjust the
+    widths of the pipe separators to encode this width information.
+
+  * Docx writer: Separate tables even with RawBlocks between (#7724,
+    Michael Hoffmann).  Adjacent docx tables need to be separated by an
+    empty paragraph. If there's a RawBlock between tables which renders
+    to nothing, be sure to still insert the empty paragraph so that
+    they will not collapse together.
+
+  * Man writer: use custom font V for inline code (#7506).
+    The V font is defined conditionally, so that it renders
+    like CB in output formats that support that, and like B
+    in those that don't (e.g. the terminal).
+    Aliases also defined for VI, VB, VBI.
+
+  * Asciidoc writer: Support checklists in asciidoctor writer (#7832,
+    Nikolai Korobeinikov, ricnorr).  The checklist syntax (similar to
+    `task_list` in markdown) seems to be an asciidoctor-only addition.
+
+  * HTML writer:
+
+    + Avoid duplicate "style" attributes on table cells (#7871).
+    + Don't break lines inside code elements.  With the new (default)
+      line wrapping of HTML, in conjunction with the default CSS which
+      includes `code { whitespace: pre-wrap; }`, spurious line
+      breaks could be introduced into inline code (#7858).
+
+  * Custom writer: preserve order of element attributes (#7489, Albert
+    Krewinkel).  Attribute key-value pairs are marshaled as AttributeList,
+    i.e., as a userdata type that behaves both like a list and a map. This
+    allows to preserve the order of key-value pairs.
+
+  * Switch to hslua-2.1 (Albert Krewinkel). This allows for some code
+    simplification and improves stability.
+
+  * Don't read files outside of user data directory (Even Brenden).
+    If a file path does not exist relative to the working directory, and
+    it does exist relative to the user data directory, but outside of
+    of the user data directory, do not read it. This applies to
+    `readDataFile` and `readMetadataFile` in PandocMonad and, by
+    extension, any module that uses these by passing them relative paths.
+
+  * Text.Pandoc.Class.`makeCanonical`: Correctly handle consecutive ".."s
+    at the beginning of a path (Even Brenden).  Prior to this commit,
+    `../../file` would evaluate to `file`, when it should be unchanged.
+
+  * Search for metadata files in `$DATADIR/metadata` (#7851, Even Brenden).
+    If files specified with `--metadata-file` are not found in the working
+    directory, look in `$DATADIR/metadata` (#5876).
+
+  * Text.Pandoc.Class: export `readMetadataFile` [API change] (#5876).
+
+  * Text.Pandoc.Error: export new `PandocCouldNotFindMetadataFileError`
+    constructor for `PandocError` [API change] (#5876).
+
+  * Avoid putting a frame around speaker notes in beamer (#7857).
+    If speaker notes (a Div with class 'notes') occur right
+    after a section heading, but above slide level, the
+    resulting `\note{..}` caommand should not be wrapped in
+    a frame, as that will cause a spurious blank slide.
+
+  * CSS in HTML template: adjust #TOC and h1 on mobile (#7835, Mauro Bieg).
+
+  * Text.Pandoc.Readers.LaTeX.Parsing: don't export `totoks`.
+    Make the first param of `tokenize` a SourcePos instead of
+    SourceName, and use it instead of `totoks`.
+
+  * Text.Pandoc.Shared: Modify `stringify` so it ignores `[Citation]`
+    inside `Cite` (#7855).  Otherwise we'll sometimes get two copies of
+    things, one from the `citationPrefix` or `citationSuffix` and another
+    from the embedded fallback text.  When there is no fallback text,
+    we'll get no content.  However, it really isn't an alternative to just
+    rely on the result of running `query` on the embedded `Citation`s;
+    this will result in a jumble of text rather than anything structured.
+
+  * Omit `--enable-doc` in the cabal haddock invocation in
+    `tools/build-and-upload-api-docs.sh`.
+
+  * Text.Pandoc.App.Opt: fix logic bug in `fullDefaultsPath`.
+    Previously we would (also) search the default user data directory
+    for a defaults file, even if a different user data directory
+    was specified using `--data-dir`.  This was a mistake; if
+    `--data-dir` is used, the default user data directory should
+    not be searched.
+
+  * Text.Pandoc.Shared: `defaultUserDataDir` behavior change (#7842).
+    If the XDG data directory is not defined (e.g. because
+    it's not supported in the OS or HOME isn't defined), we
+    return the empty string instead of raising an exception.
+
+  * Update command tests to distinguish stderr and test exit status.
+
+  * MANUAL: add that speaker notes can be used with beamer (#7856).
+
+  * Update `build-and-upload-api-docs.sh`.
+
+  * Document `--trace` option.
+    Document `no-check-certificate` in defaults files.
+    Document 'sandbox' option for defaults files.  (#7873).
+
+  * Fix pattern syntax in sample readability custom reader.
+
+  * doc/custom-readers.lua: add example for "readable HTML."
+
+  * Fix message in man page about where code can be found.
+
+  * `manfilter.lua`:  remove extra indent in table cells with code blocks.
+
+  * Fix lua-filters documentation for table column widths (#7864).
+
+  * epub.doc: Update links to KindleGen (#7846, Benson Muite, Mauro Bieg).
+    KindleGen has been deprecated and we need to link to archived versions.
+
+  * Use tables in defaults files documentation, so each
+    default option is paired with the corresponding command-line
+    option (Carsten Allefeld).
+
+  * Use skylighting 0.12.2.
+
+  * Add pandoc-lua-marshal to Nix shell (#7849, Even Brenden).
+
+
+## pandoc 2.17.0.1 (2022-01-14)
+
+  * Require pandoc-lua-marshal 0.1.3.1 (#7831, Albert Krewinkel).
+    Fixes a problem with `List.includes` and `List.find` that caused a
+    Lua stackoverflow and subsequent program crash.
+
+  * HTML template: load header-includes before math (#7833, Kolen Cheung).
+    MathJax expect the config comes before loading the MathJax script.
+    This change of order allows one to config MathJax via
+    header-includes, which loads before the MathJax script. Cf. #2750.
+
+  * When reading defaults file, stop at a line `...`.  This line signals
+    the end of a YAML document.  This restores the behavior we got with
+    HsYaml.  yaml complains about content past this line.  See
+    https://github.com/jgm/pandoc/issues/4627#issuecomment-1012438765
+
+  * Text.Pandoc.Citeproc: allow `notes-after-punctuation` to work with
+    numerical styles that use superscripts (e.g.
+    american-medical-association.csl), as well as with note styles. The
+    default setting of `notes-after-punctuation` is true for note styles
+    and false otherwise.  This restores a behavior of pandoc-citeproc
+    that wasn't properly carried over to Citeproc (#7826, cf.
+    jgm/pandoc-citeproc#384).
+
+  * Use commonmark-pandoc 0.2.1.2 (#7769).
+
+  * Add FAQ on images in ipynb containers (#7749, Kolen Cheung).
+
+## pandoc 2.17 (2022-01-12)
+
+  * Support `markua` as an output format (#1871, Tim Wisotzki and
+    Saumel Lemmenmeier). Markua is a markdown variant used by Leanpub.
+
+  * Add text wrapping for HTML output (#7764). Previously the HTML writer
+    was exceptional in not being sensitive to the `--wrap` option.  With
+    this change `--wrap` now works for HTML. The default (as with other
+    formats) is automatic wrapping.  Note that the contents of `script`,
+    `textarea`, and `pre` tags are always laid out with the `flush`
+    combinator, so that unwanted spaces won't be introduced if these occur
+    in an indented context in a template.
+
+  * Don't read sources until in/out format are verified (#7797).
+
+  * Issue error with `--list-extensions` for invalid formats (#7797).
+
+  * Make `--citeproc` recognize `.yml` as well as `.yaml` extensions
+    as YAML bibliography files (#7707, Jörn Krenzer).
+
+  * Use latest version of KaTeX with `--katex`.
+
+  * Fix parsing of footnotes in `--metadata-file` (#7813).  Previously
+    non-inline footnotes were not being parsed.
+
+  * ODT reader:
+
+    + Parse list-header as a list item (Tuong Nguyen Manh).
+
+  * Commonmark reader:
+
+    + Put sourcepos attribute on header, not enclosing div
+      with `-f commonmark+sourcepos` (#7769).
+
+  * Markdown reader:
+
+    + Don't allow `^` at beginning of link or image label (#7723).
+      This is reserved for footnotes. Fixes regression from 0a93acf.
+    + Fix parsing of "bare locators" after author-in-text citations.
+      Previously `@item [p. 12; @item2]` was incorrectly parsed as
+      three citations rather than two.  This is now fixed by ensuring
+      that `prefix` doesn't gobble any semicolons.
+    + Revert changes to `inlinesInBalancedBrackets` (commit fa83246),
+      which caused regressions.
+    + Improve detection of pipe table line widths (#7713).  Fixed
+      calculation of maximum column widths in pipe tables.  It is
+      now based on the length of the markdown line, rather than a
+      "stringified" version of the parsed line.  This should be
+      more predictable for users. In addition, we take into account
+      double-wide characters such as emojis.
+
+  * Custom (Lua) readers:
+
+    + First argument is now a list of sources instead of the
+      concatenated text (Albert Krewinkel).  The list
+      structure can easily be converted to a string by applying
+      `tostring`, but it is also possible to access the elements
+      (each with a `text` and `name`). A small example is added
+      to the custom reader documentation, showcasing its use in a
+      reader that creates a syntax-highlighted code block for
+      each source code file passed as input. Existing readers
+      will still work through a fallback mechanism, issuing a
+      deprecation notice.
+
+  * Org reader:
+
+    + Parse official org-cite citations (#7329). We also support the older
+      org-ref style as a fallback. We no longer support the
+      "markdown style" or "Berkeley style" citations.
+    + Support alphabetical (fancy) lists (Lucas Viana). When the
+      `fancy_lists` extension is enabled, alphabetical list markers are
+      allowed, mimicking the behaviour of Org Mode when
+      `org-list-allow-alphabetical` is enabled.
+    + Support counter cookies in lists (Lucas Viana). Such cookies are
+      used to override the item counter in ordered lists. In org it is
+      possible to set the counter at any list item, but since Pandoc AST
+      does not support this, we restrict the usage to setting an offset for
+      the entire ordered list, by using the cookie in the first list item.
+    + Allow trailing spaces after key/value pairs in directives (Albert
+      Krewinkel). Ensures that spaces at the end of attribute directives like
+      `#+ATTR_HTML: :width 100%` (note the trailing spaces) are accepted.
+
+  * LaTeX reader:
+
+    + Omit visible content for `\label{...}`. Previously we
+      included the text of the label in square brackets, but this is
+      undesirable in many cases. See discussion in
+      <https://github.com/jgm/pandoc/issues/813#issuecomment-978232426>.
+    + Improve references (#813). Resolve references to theorem environments.
+      Remove the Span caused by "label" in figure, table, and theorem
+      environments; this had an id that duplicated the environments' id.
+    + Fix semantics of `\ref`. We were including the ams
+      environment type in addition to the number. This is proper
+      behavior for `\cref` but not for `\ref`.  To support `\cref`
+      we need to store the environment label separately.
+    + Add babel mappings for Guajati (gu) and Oriya (or) (#7815).
+    + Fix typo `panjabi` -> `punjabi` in babel mappings (#7814).
+
+  * HTML reader:
+
+    + Parse attributes on links and images (#6970).
+
+ * Docx reader:
+
+    + Handle multiple pic elements inside a drawing (#7786).
+    + Change `elemToParPart` to return `[ParPart]` instead of `ParPart`.
+      Also remove `NullParPart `constructor, as it is no longer
+      needed. This will allow us to handle elements that contain
+      multiple ParParts, e.g. `w:drawing` elements with multiple `pic:pic`.
+
+  * DocBook reader:
+
+    + Collapse internal spaces in literal and other similar tags (#7821),
+      as the standard docbook toolchain does.
+    + Be sensitive to spacing="compact" in lists (#7799). When
+      `spacing="compact"` is set, Para elements are turned into Plain,
+      so we get a "tight" list.
+
+  * Markdown writer:
+
+    + Add new exported function `writeMarkua` from Text.Pandoc.Writers.Markdown
+      [API change] (#1871, Tim Wisotzki and Saumel Lemmenmeier).
+    + Fix indentation issue in footnotes (#7801).
+    + Avoid extra space before citation suffix if it already starts
+      with a space.
+    + Ensure semicolon between the locator and the next citation when an
+      author-in-text citation has a locator and following citations.
+    + Improve escaping for `#` (#7726).
+
+  * Custom (Lua) writers:
+
+    + Allow variables to be set via second return value of `Doc`
+      (#6731, Albert Krewinkel). New templates variables can be added by
+      giving variable-value pairs as a second return value of the
+      global function `Doc`. Example:
+      ```
+      function Doc (body, meta, vars)
+        vars.date = vars.date or os.date '%B %e, %Y'
+        return body, vars
+      end
+      ```
+    + Provide global `PANDOC_WRITER_OPTIONS` (#6731, Albert Krewinkel).
+    + Assign default Pandoc object to global `PANDOC_DOCUMENT` (Albert
+      Krewinkel). The default Pandoc object is now non-strict, i.e., only
+      the parts of the document that are accessed will be marshaled to Lua.
+      A special type is no longer necessary. This change also makes it
+      possible to use the global variable with library functions such as
+      `pandoc.utils.references`, or to inspect the document contents with
+      `walk()`.
+
+  * LaTeX writer:
+
+    + Fix typo `panjabi` -> `punjabi` in babel mappings (#7814).
+
+  * MediaWiki writer:
+
+    + Remove redundant display text for wiki links (Jesse Hathaway).
+
+  * Docx writer:
+
+    + Handle bullets correctly in lists by not reusing numIds
+      (#7689, Michael Hoffmann).  This fixes a bug in which a Div in
+      a list item would receive bullets on its contained paragraphs.
+
+  * Org writer:
+
+    + Fix list items starting with a code block or other non-paragraph
+      content (#7810).
+    + Avoid blank lines after tight sublists (#7810).
+    + Fix extra blank line inserted after empty list item (#7810).
+    + Don't add blank line before lists (#7810).
+    + Support starting number cookies (Lucas Viana).  This is necessary
+      for lists that start at a number other than 1.
+    + Support the new org-cite syntax (#7329).
+
+  * Haddock writer:
+
+    + Avoid blank lines after tight sublists (#7810).
+
+  * Ipynb writer:
+
+    + Ensure deterministic order of keys.
+    + Handle cell output with raw block of markdown (#7563, Kolen Cheung).
+      Write RawBlock of markdown in code-cell output. This is designed
+      to fit the behavior of #7561, which makes the ipynb reader parse
+      code-cell output with mime "text/markdown" to a RawBlock of markdown.
+      This commit makes the ipynb writer writes this RawBlock of markdown
+      back inside a code-cell output with the same mime, preserving this
+      information in round-trip.
+    + In choosing between multiple output options, always favor
+      those marked with the output format over images (Kolen Cheung).
+      Previously, both `fmt == f` case and Image have a rank of 1.
+
+  * Ipynb reader & writer: properly handle cell "id" (#7728).
+    This is passed through if it exists (in Nb4); otherwise
+    the writer will add a random one so that all cells have an "id".
+
+  * Ms writer:
+
+    + Properly encode strings for PDF contents (#7731).
+
+  * JATS writer:
+
+    + Keep quotes in element-citations (Albert Krewinkel).
+      Fixed a bug that lead to quote characters being lost in
+      element-citations.
+
+  * RTF writer:
+
+    + Properly handle images in data URIs (#7771).
+
+  * Commonmark writer:
+
+    + Allow ')' delimiters on ordered lists.
+
+  * RST writer:
+
+    + Avoid extra blank line after empty list item (#7810).
+
+  * HTML writer:
+
+    + Make line breaks more consistent. With `--wrap=none`, we now
+      output line breaks between block-level elements. Previously they
+      were omitted entirely, so the whole document was on one line, unless
+      there were literal line breaks in pre sections.  This makes
+      the HTML writer's behavior more consistent with that of
+      other writers. Also, regardless of wrap settings,
+      put newline after `<dd>` and after block-level elements in
+      the footnotes section. And add a line break between an `img` tag
+      and the associated `figcaption`.
+    + reveal.js: Make sure images with `r-stretch` are not in p tags.
+      They must be direct children of the section. There was previously
+      code to make this work with the older class name `stretch`, but
+      the name has changed in reveal.js.
+    + reveal.js:  don't add `r-fit-text` class to section. It must go on
+      the header only.
+
+  * AsciiDoc writer:
+
+    + Improve detection of intraword emphasis (#7803).
+
+  * OpenDocument writer:
+
+    + Fix vertical alignment bug with display math (#7777).  Previously some
+      displayed formulas would be floated above a preceding text line.
+      This is fixed by setting `vertical-rel` to `text` rather than
+      `paragraph-content`.
+
+  * JATS template (Albert Krewinkel):
+
+    + Fix position of contrib affiliations in authoring set. Any
+      `<aff>` element must come before any `<email>` element.
+    + Fix affiliation tagging in `articleauthoring` output.
+      Affiliations were `xlink`ed even in the articleauthoring tag set, but
+      `<aff>` are not allowed as children of `contrib-group` elements in that
+      tag set. Each affiliation must be listed directly in the contrib
+      element.
+    + Add support for article subtitles.
+
+  * EPUB template:
+
+    + Include abstract in default template.
+    + Ensure that the essential styles needed by pandoc (`styles.html`
+      partial) are included in the templates. This is important for correct
+      formatting of CSL bibliographies. Note that much of the styling in
+      `styles.html` will be ignored for EPUB, because of the conditional on
+      `document-css`.  Setting the `document-css` variable will cause it
+      not to be ignored.
+
+  * HTML template:  Add abstract (#7588, Jannik Buhr, John MacFarlane).
+    By default, a localized title (the word "Abstract") will be
+    used, unless the variable `abstract-title` is set.
+
+  * ConTeXt template:  Make title appear in PDF title bar.  This is
+    recommended for accessibility reasons.  Note: doesn't work with macOS
+    Preview.app.
+
+  * `reference.pptx`: change to use 16:9 aspect ratio, Powerpoint's default.
+
+  * Text.Pandoc.Writers:
+
+    + Do not export `writeCustom` [API change]. This ensures that all
+      writers exported in T.P.Writers are parameterized and work with any
+      `PandocMonad` type. This is consistent with T.P.Readers, as
+      `readCustom` is not exported from that module either.
+
+  * Text.Pandoc.Writers.Shared:
+
+    + `endsWithPlain` now returns True if the list ends with a list
+      that ends with a Plain, and so on recursively (#7810).
+
+  * Text.Pandoc.Class.IO:
+
+    + `writeMedia`:  unescape percent-encoding in creating file path.
+      This addresses a problem with spaces in image filenames
+      when creating PDFs (#7819); it also affects `--extract-media`.
+
+  * New internal module Text.Pandoc.Writers.Blaze, exporting `layoutMarkup`.
+    This converts a blaze Html structure into a doclayout Doc Text.
+
+  * Text.Pandoc.Extensions:
+
+    + `parseFormatSpec`: cleaner error message for invalid extensions.
+
+  * Text.Pandoc.MediaBag:
+
+    + Fix bug in `extractMedia`, which caused the test for `..`
+      in paths to fail, with the result that images with `..`
+      in the path name could be extracted outside of the
+      directory specified by `extractMedia`. It also led a check for
+      `media` in resource paths to fail in the docx reader.
+
+  * Text.Pandoc.Citeproc:
+
+    + Avoid adding comma before an author-in-text citation in a note
+      if it begins with a title (no author) (#7761).
+    + Text.Pandoc.Citeproc.Locator now exports `toLocatorMap`,
+      `LocatorInfo`, and `LocatorMap`.  The type of `parseLocator`
+      has changed, so it now takes a `LocatorMap` rather than a `Locale`
+      as parameter, and returns a `LocatorInfo` instead of a tuple.
+    + Fix citation locator detection for German.  `toLocatorMap` now
+      stores keys case-folded. We want to do a case-insensitive
+      comparison when parsing locators, so that e.g. both
+      `Chap.` and `chap.` work. Previously we case-folded terms
+      when doing the lookup, but they weren't case-folded in the
+      map itself, which led to locator-detection breaking for
+      German (where the terms have uppercase letters).
+
+  * Lua (Albert Krewinkel):
+
+    + Allow single elements as singleton MetaBlocks/MetaInlines. Single
+      elements should always be treated as singleton lists in the Lua
+      subsystem.
+    + Add `pandoc.template` module. The module provides a `compile`
+      function to use strings as templates.
+    + Add `pandoc.WriterOptions` constructor.
+    + Add function `pandoc.write`.
+    + Provide global `PANDOC_WRITER_OPTIONS` (#5221).
+    + The function Text.Pandoc.Filter.applyFilters now takes a filter
+      environment of type `Environment`, instead of a ReaderOptions value
+      [API change].
+    + The `Environment` type is exported from Text.Pandoc.Filter
+      and allows to combine ReaderOptions and WriterOptions in a single
+      value [API change].
+    + Global, exported from Text.Pandoc.Lua, has a new type constructor
+      `PANDOC_WRITER_OPTIONS` [API change].
+    + Add constructors `pandoc.Blocks` and `pandoc.Inlines`.
+      The functions convert their argument into a list of Block and Inline
+      values, respectively. When applied to a string, they split the
+      string into `Str` elements separated by `Space` or `SoftBreak`
+      (#7712).
+    + Support topdown traversals The traversal order of filters can now
+      be selected by setting the key `traverse` of the filter to either
+      `'topdown'` or `'typewise'`; the default remains `'typewise'`.
+      Topdown traversals can be cut short by returning `false` as a
+      second value from the filter function. No child-element of the
+      returned element is processed in that case.
+    + Marshal ReaderOptions field `extensions`, `track_changes` via JSON.
+      Extensions are now available as a list of strings; the track-changes
+      settings are given as the kebab-case representation used in JSON.
+    + Allow binary (byte string) readers to be used with `pandoc.read`.
+    + Use global state when parsing documents in `pandoc.read`.
+      The function `pandoc.read` is updated to use the same state that was
+      used while parsing the main input files. This ensures that log
+      messages are preserved and that images embedded in the input are
+      added to the mediabag.
+    + Cleanup stack in `peekReadOptionsTable`. A ReaderOptions element was
+      left on top of the stack when the `peekReadOptionsTable` function
+      was invoked.
+    + `walk` methods are added to `Pandoc`, `Block`, `Inline`,
+      `Blocks`, `Inlines` values; the methods are similar to
+      `pandoc.utils.walk_block` and `pandoc.utils.walk_inline`, but
+      apply to filter to the element's contents.
+    + Functions of name `Doc` are no longer accepted as alternatives for
+      `Pandoc` filter functions. This functionality was undocumented.
+    + Improve handling of empty caption, body by `from_simple_table`
+      #7776). Create truly empty table caption and body when these are
+      empty in the simple table.
+    + Change representation of `TableHead`, `TableFoot`, and `Row` values
+      (#7718).  The objects now also follow the principle that element
+      attributes are accessible through the `.attr` field. Rows in `TableHead`
+      and `TableFoot` are available via the `.rows` field. Row objects have a
+      `.cells` field, containing the list of table cells.
+    + [Simplify](Simplify) code of `pandoc.utils.stringify`. Minor behavior change:
+      plain strings nested in tables are now included in the result string.
+    + Simplify and deprecate function `pandoc.utils.equals`. The function
+      is no longer required for element comparisons; it is now an alias
+      for the `==` operator.
+    + Add function `pandoc.utils.references` (#7752).
+    + Add new library function `pandoc.utils.type`.  The function behaves
+      like the default `type` function from Lua's standard library,
+      but is aware of pandoc userdata types. A typical use-case would be
+      to determine the type of a metadata value.
+    + Fix return types of `blocks_to_inlines`, `make_sections`.
+      Ensures the returned lists have the correct type (`Inlines` and
+      `Blocks`, respectively).
+    + Use more natural representation for Reference values
+      Omit `false` boolean values, push integers as numbers.
+
+  * Lua: use package pandoc-lua-marshal (#7719, Albert Krewinkel).
+    The marshaling functions for pandoc's AST are extracted into a separate
+    package. The package comes with a number of changes:
+
+    + Pandoc's List module was rewritten in C, and error messages were
+      improved.
+    + Lists of `Block` and `Inline` elements are marshaled using the new
+      list types `Blocks` and `Inlines`, respectively. These types
+      currently behave identical to the generic List type, but give better
+      error messages. This also opens up the possibility of adding
+      element-specific methods to these lists in the future.
+    + Elements of type `MetaValue` are no longer pushed as values which
+      have `.t` and `.tag` properties. This was already true for
+      `MetaString` and `MetaBool` values, which are still marshaled as Lua
+      strings and booleans, respectively. Affected values:
+      - `MetaBlocks` values are marshaled as a `Blocks` list;
+      - `MetaInlines` values are marshaled as a `Inlines` list;
+      - `MetaList` values are marshaled as a generic pandoc `List`s.
+      - `MetaMap` values are marshaled as plain tables and no longer
+        given any metatable.
+    + `Cell` values are now marshaled as userdata objects; a constructor
+      function for table cells is provided as `pandoc.Cell`.
+    + The test suite for marshaled objects and their constructors has
+      been extended and improved.
+    + A bug in `Citation` objects, where setting a citation's suffix
+      modified it's prefix, has been fixed.
+    + Inlines, Blocks, and List objects now have an `__eq` metamethod,
+      testing equality by comparing two lists element-wise.
+
+  * Powerpoint tests: shorten lines by grouping tests (Albert
+    Krewinkel). This makes the test output more pleasant to read
+    in narrow terminal windows.
+
+  * make check: check for unreleased dependencies.
+
+  * Add `tools/build-and-upload-api-docs.sh`.
+
+  * Update cabal description.
+
+  * `MANUAL.txt`: Add section on EPUB styling.
+
+  * `MANUAL.txt`: clarify "standard Markdown" as "original Markdown"
+    (#7802, Martin Fischer).
+
+  * `doc/custom-writers.md`: use filter to include source of example.
+
+  * Add an example to `doc/custom-readers.md`.
+
+  * Fix typo in `custom-readers.md` (#7722, Mauro Bieg).
+
+  * `doc/jats.md`: add link to JATS documentation (Martin Fischer).
+
+  * `doc/lua-filters.md`: many improvements (Albert Krewinkel,
+    John MacFarlane).
+
+  * Use commonmark-extensions 0.2.3. This allows a bare-word class attribute
+    on fenced divs.
+
+  * Use ipynb 0.2.
+
+  * Use citeproc 0.6.0.1.
+
+  * Use texmath 0.12.4.
+
+  * Use doctemplates 0.10.0.1.
+
+## pandoc 2.16.2 (2021-11-21)
+
+  * Add interface for custom readers written in Lua (#7669).
+    Users can now do `-f myreader.lua` and pandoc will treat the
+    script `myreader.lua` as a custom reader, which parses an input
+    string to a pandoc AST, using the pandoc module defined for
+    Lua filters.  A sample custom reader can be found in `data/creole.lua`.
+    Also see documentation in `doc/custom-readers.md`.
+
+  * New module Text.Pandoc.Readers.Custom, exporting `readCustom` [API change].
+
+  * Allow `plain` to be used in raw attribute syntax.
+
+  * Accept empty `--metadata-file` (#7675).
+    This was a regression from 2.15 behavior.
+
+  * Markdown reader: Improve `inlinesInBalancedBrackets`.
+    This is just a small improvement in terms of performance, but it's simpler
+    and more direct code.  Also, we avoid parsing interparagraph spaces in
+    balanced brackets, as the original did.
+
+  * BibTeX reader: Properly handle commented lines in BibTeX/BibLaTeX (#7668).
+
+  * RST reader: handle class attribute for for custom roles (#7699,
+    willj-dev).  Previously the class attribute was ignored, and the name
+    of the role used as the class.
+
+  * DocBook reader:
+
+    + Add `<titleabbr>` support (Rowan Rodrik van der Molen).
+    + Support for `<indexterm>` (#7607, Rowan Rodrik van der Molen).
+
+  * LaTeX reader:
+
+    + Add rudimentary support for `\autoref` (#7693).
+    + Add 'uri' class when parsing `\url`, for consistency
+      with treatment of autolinks in other formats (#7672).
+
+  * JATS reader: Capture `alt-text` in figures (#7703, Aner Lucero).
+
+  * MediaWiki writer: use HTML spans for anchors when header has id (#7697).
+    We need to generate a span when the header's ID doesn't match
+    the one MediaWiki would generate automatically.  Note that MediaWiki's
+    generation scheme is different from pandoc's (it uses uppercase letters,
+    and `_` instead of `-`, for example).  This means that in going from
+    markdown to mediawiki, we'll now get spans before almost every heading,
+    unless explicit identifiers are used that correspond to the ones MediaWiki
+    auto-generates.  This is uglier output but it's necessary for internal
+    links to work properly.
+
+  * Markdown writer: don't create autolinks when this loses information
+    (#7692).  Previously we sometimes lost attributes when rendering links
+    as autolinks.
+
+  * Text.Pandoc.Readers.Metadata: allow multiple YAML documents when parsing
+    YAML for `yamlBsToRefs`.  Some people use `---` as the end delimiter in
+    YAML bibliography files, which causes the `yaml` library to emit an
+    error unless we explicitly allow multiple YAML documents (and just
+    consider the first).
+
+  * JATS writer:
+
+    + Ensure figures are wrapped with `<p>` in list items
+      (Albert Krewinkel).  This prevents the generation of invalid output.
+    + Add URL to element citation entries (Albert Krewinkel).
+      The URL of a reference, if present, is added in tag `<uri>` to
+      element-citation entries.
+
+  * HTML writer: Don't create invalid `data-` attribute for empty
+    attribute key (#7546).
+
+  * LaTeX writer:
+
+    + Babel mappings: use `ancientgreek` for `grc`.
+    + With `-t latex-smart`, don't generate `\ldots` from ellipsis (#7674).
+      Instead just use unicode ellipsis.
+
+  * JATS template: fix `equal-contrib` attribute (Albert Krewinkel).
+    The standard requires the value to be either `yes` or `no`, but is was
+    set to `true` for authors who contributed equally.
+
+  * reveal.js template: Add `disableLayout` variable (Christophe Dervieux).
+
+  * Text.Pandoc.Error: sort errors in `handleError` by exit code
+    (Albert Krewinkel).
+
+  * Text.Pandoc.Writers.Shared: Improve toLegacyTable (#7683,
+    Christian Despres).
+
+  * Lua subsystem:
+
+    + Include lpeg module (#7649, Albert Krewinkel).  Compiles the `lpeg`
+      library (Parsing Expression Grammars For Lua) into
+      the program.  Package maintainers may choose to rely on package
+      dependencies to make lpeg available, in which case they can compile
+      the with the constraint `lpeg +rely-on-shared-lpeg-library`.
+      `lpeg` and `re` are always made available in global variables,
+      without the need for a `require`.
+
+    + Set `lpeg` and `re` as globals; allow shared lib access via `require`.
+      The `lpeg` and `re` modules are loaded into globals of the respective
+      name, but they are not necessarily registered as loaded packages. This
+      ensures that
+
+      - the built-in library versions are preferred when setting the globals,
+      - a shared library is used if pandoc has been compiled without `lpeg`,
+        and
+      - the `require` mechanism can be used to load the shared library if
+        available, falling back to the internal version if possible and
+        necessary.
+
+    + Fix argument order in constructor `pandoc.Cite` (Albert Krewinkel).
+      This restores the old behavior; argument order had been switched
+      accidentally in pandoc 2.15.
+
+    + Add Pushable instance for `ReaderOptions` (Albert Krewinkel).
+
+    + Allow to pass custom reader options to `pandoc.read` as an
+      optional third argument (#7656, Albert Krewinkel).
+      The object can either be a table or a ReaderOptions value
+      like `PANDOC_READER_OPTIONS`. Creating new ReaderOptions objects is
+      possible through the new constructor `pandoc.ReaderOptions`.
+
+    + Display Pandoc values using their native Haskell representation
+      (Albert Krewinkel).
+
+    + Require latest hslua (2.0.1) (#7661, #7657, Albert Krewinkel).
+      This fixes issues with
+
+      - misleading error messages when a required function parameter is
+        omitted;
+      - absent properties still being listed in the output of `pairs`; and
+      - alias accessing leading to errors instead of returning `nil`, e.g.
+        with `(pandoc.Str '').identifier`.
+
+    + Add missing space in "package not found" message (#7658, Albert
+      Krewinkel).
+
+  * Update build files (#7696, Fabián Heredia Montiel).
+    Drop old windows 32-bit constraints.
+    Update cabal `tested-with` field to correspond to `ci.yml` matrix
+
+  * Remove unneeded package dependencies from benchmark target.
+
+  * Require ghc >= 8.6, base >= 4.12.
+    This allows us to get rid of the old custom prelude and
+    some crufty cpp.  But the primary reason for this is that
+    conduit has bumped its base lower bound to 4.12, making it
+    impossible for us to support lower base versions.
+
+  * Require Cabal 2.4.  Use wildcards to ensure that all pptx tests are
+    included (#7677).
+
+  * Update `bash_completion.tpl` (S.P.H.).
+
+  * Add `data/creole.lua` as sample custom reader.
+
+  * Add `doc/custom-readers.md` and `doc/custom-writers.md`.
+
+  * `doc/lua-filters.md`: add section on global modules, including lpeg
+    (Albert Krewinkel).
+
+  * `MANUAL.txt`: update table of exit codes and corresponding errors
+    (Albert Krewinkel).
+
+  * Use latest texmath.
+
+## pandoc 2.16.1 (2021-11-02)
+
+
+  * Docx reader:  don't let first line indents trigger block quotes (#7655).
+    This fixes a regression introduced in pandoc 2.15.
+
+  * Docx writer: use `getTimestamp` for modification times in
+    reference.docx (#7654).  This ensures that when `SOURCE_DATE_EPOCH` is
+    set, the modification times of files taken from the reference.docx will
+    be set deterministically, allowing for reproducible builds.
+
+  * Lua subsystem (Albert Krewinkel):
+
+    + Load module `pandoc.path` on startup (#7524).  Previously the module
+      always had to be loaded via `require 'pandoc.path'`.
+    + Fix typo in SoftBreak constructor.
+    + Re-add `content` property to Strikeout elements.
+      Fixes a regression introduced in 2.15.
+    + Be more forgiving when retrieving the Image `caption` property.
+      Fixes a regression introduced in 2.15.
+    + Display Attr values using their native Haskell representation.
+    + Allow omitting the 2nd parameter in pandoc.Code constructor.
+      Fixes a regression introduced in 2.15 which required users to always
+      specify an Attr value when constructing a Code element.
+    + Allow to compare, show Citation values.  Comparisons of Citation
+      values are performed in Haskell; values are equal if they represent
+      the same Haskell value. Converting a Citation value to a string
+      now yields its native Haskell string representation.
+    + Restore List behavior of MetaList (#7650).  Fixes a regression
+      introduced in 2.16 which had MetaList elements lose
+      the `pandoc.List` properties.
+    + Restore `content` property on Header elements.
+    + Ensure Block elements have all expected properties.
+    + Ensure Inline elements have all expected properties.
+
+  * Allow tasty-bench 0.3.x.
+
+## pandoc 2.16 (2021-10-31)
+
+  * Switch back from HsYAML to yaml for parsing YAML metadata (#6084).
+    HsYAML is around 20 times slower in parsing large YAML bibliographies.
+    In addition, HsYAML is not being actively maintained.  This sets us back
+    in our attempts to free ourselves from C dependencies (#4535).  But I
+    don't see a good alternative until a faster pure Haskell parser is available.
+    Notes:
+
+    + We've removed the FromYAML instances for all types that had them, since
+      this is a HsYAML-specific typeclass [API change].  (The yaml package just
+      uses From/ToJSON instead of having a dedicated From/ToYAML class.)
+    + Unlike HsYAML (in the configuration we were using), yaml parses 'Y', 'N',
+      'Yes', 'No', 'On', 'Off' as boolean values.  Users may need to quote these
+      when they are meant to be interpreted as strings.  Similarly, 'null' is
+      parsed as a YAML null value (and will be treated as an empty string by
+      pandoc rather than the string 'null').  Quoting it will force it to be
+      interpreted as a string.
+    + Some tests had to be adjusted accordingly.
+    + Pandoc now behaves in a more useful way when the YAML metadata contains
+      escaping errors: instead of just failng silently and falling back to
+      some other interpretation of the section, it raises a YAML parsing error.
+
+  * Markdown writer: Ensure that special values are quoted in YAML metadata.
+    These include "Y", "yes", "on", and "off", which are now (with yaml library)
+    considered boolean values, as well as "null".
+
+  * Change JSON encodings of some types.
+
+    + For LineEnding use lowercase constructors, e.g. `crlf`, `native`.
+    + For HTMLSlideVariant use lowercase constructors.
+    + For ReaderOptions use e.g. `default-image-extension`
+      instead of `readerDefaultImageExtension` for field names.
+    + For Extension, use e.g. `tex_math_dollars` instead of
+      `Ext_tex_math_dollars` as constructor.
+    + For Extensions, use an array of Extensions, instead of
+      an object wrapping the tag `Extensions` and an integer.
+      (The integer representation is not supposed to be part of the
+      public API.)
+    + For Opt, use field names like `tab-stop` instead of `optTabStop`.
+
+  * Docx writer:
+
+    + Add IDs to native_numbering test (Tristan Stenner).
+    + Move ": " out of the caption bookmark (Tristan Stenner).
+      This is needed so that native references to the figure are included as
+      "As seen in Figure X, it is..." instead of "As seen in [Figure: X, it is..."
+
+  * Lua (Albert Krewinkel, except as noted):
+
+    + Use hslua module abstraction where possible.
+    + Fix placement of tests for Block elements in pandoc module tests
+    + Increase strictness when getting attribute keys
+    + Re-add `t` and `tag` property to Attr values.
+      Removal of these properties from Attr values was a regression.
+    + Fix `pandoc.utils.stringify` regression.  The `pandoc.utils.stringify`
+      function returned empty strings when called with a string argument.
+    + Fix a copy/paste bug in Lua marshalling code (John MacFarlane, #7639).
+      This caused links to be changed to figures when Lua filters changed
+      link properties.
+    + Re-add `content` property to Link elements (#7647).
+      This was a regression introduced in version 2.15.
+    + Generate constants in module pandoc programmatically.
+    + Marshal SimpleTable, ListAttributes, Citation, and Block values as
+      userdata objects.  Properties of Block values are marshalled lazily,
+      which generally improves performance considerably. Script users may also
+      notice the following differences:
+
+      - Block element properties can no longer be accessed by numerical
+        indexing of the `.c` field. The `.c` property now serves as an alias
+        for `.content`, so some filter that used this undocumented method
+        for property access may continue to work, while others will need to
+        be updated and use proper property names.
+      - The marshalled Block elements now have a `show` method, and a
+        `__tostring` metamethod. Both return the Haskell string
+        representation of the element.
+      - Block values now have the Lua type `userdata` instead of `table`.
+
+  * Add a short guide to pandoc's sources (Albert Krewinkel).
+
+  * Fix epub files in epub reader tests, so that they are valid
+    according to epubcheck (#7586).
+
+  * Allow time 1.13.
+
+  * Require latest skylighting (0.12.1).
+
+  * Fix build on GHC 9.2 (Joseph C. Sible).
+
+  * Fix trypandoc so it builds with aeson > 2.
+
+
+## pandoc 2.15 (2021-10-23)
+
+  * Add `--sandbox` option  (#5045).
+
+    + Add sandbox feature.  When this option is used, readers and writers
+      only have access to input files (and other files specified directly on
+      command line).  This restriction is enforced in the type system.
+    + Filters, PDF production, custom writers are unaffected.  This
+      feature only insulates the actual readers and writers, not
+      the pipeline around them in Text.Pandoc.App.
+    + Note that when `--sandboxed` is specified, readers won't have
+      access to the resource path, nor will anything have access to
+      the user data directory.
+
+  * `--self-contained`: Fix bug that caused everything to be made a data
+    URI (#7635, #7367).  We only need to use data URIs in certain cases, but
+    due to a bug they were being used always.
+
+  * Pandoc will now fall back to latin1 encoding for inputs that can't be
+    read as UTF-8.  This is what it did previously for content fetched
+    from the web and not marked as to content type. It makes sense to do
+    the same for local files.  In this case a `NotUTF8Encoded` warning
+    will be issued, indicating that pandoc is interpreting the input as latin1.
+
+  * Markdown reader:
+
+    + Don't parse links or bracketed spans as citations (#7632).
+      Previously pandoc would parse `[link to (@a)](url)` as a
+      citation; similarly `[(@a)]{#ident}`.  This is undesirable.  One should
+      be able to use example references in citations, and even if `@a` is
+      not defined as an example reference, `[@a](url)` should be a link
+      containing an author-in-text citation rather than a normal citation
+      followed by literal `(url)`.
+    + Fix interaction of `--strip-comments` and list parsing (#7521).
+      Use of `--strip-comments` was causing tight lists to be rendered as
+      loose (as if the comment were a blank line).
+    + Fix parsing bug for math in bracketed spans and links (#7623).
+      This affects math with unbalanced brackets (e.g. `$(0,1]$`)
+      inside links, images, bracketed spans.
+    + Fix code blocks using `--preserve-tabs` (#7573).  Previously they
+      did not behave as the equivalent input with spaces would.
+
+  * DocBook reader:
+
+    + Honor linenumbering attribute (Samuel Tardieu).
+    The attribute DocBook `linenumbering="numbered"` on code blocks
+    maps to the `numberLines` class internally.
+
+  * LaTeX reader:
+
+    + Implement siunitx v3 commands (#7614).
+      We support `\unit`, `\qty`, `\qtyrange`, and `\qtylist`
+      as synonyms of `\si`, `\SI`, `\SIrange`, and `\SIlist`.
+    + Properly handle `\^` followed by group closing (#7615).
+    + Recognize that `\vadjust` sometimes takes "pre" (#7531).
+    + Ignore (and gobble parameters of) CSLReferences environment (#7531).
+      Otherwise we get the parameters as numbers in the output.
+    + Restrict `\endinput` to current file (Simun Schuster).
+
+  * RST reader: handle escaped colons in reference definitions (#7568).
+
+  * HTML reader:
+
+    + Handle empty tbody element in table (#7589).
+
+  * Ipynb reader (Kolen Cheung):
+
+    + Get cell output mime from `raw_mimetype` in addition to `format`.
+      (`format` is what the spec calls for, but `raw_mimetype` is
+      often used in practice; see jupyter/nbformat#229).
+    + Add more formats that can be handled as "raw" cells.
+    + Fix mime type for `rst`.
+    + Support `text/markdown`, which is now a supported mime type for raw
+      output (#7561).
+
+  * RTF reader:
+
+    + Support `\binN` for binary image data.
+    + If doc begins with {\rtf1 ... } only parse its contents.
+      Some documents seem to have non-RTF (e.g. XML) material after the
+      `{\rtf1 ... }` group.
+    + Ignore `\pgdsc` group.  Otherwise we get style names treated as test.
+    + Better handling of `\*` and bookmarks.  We now ensure that groups
+      starting with `\*` never cause text to be added to the document.
+      In addition, bookmarks now create a span between the start
+      and end of the bookmark, rather than an empty span.
+
+  * Docx reader:
+
+    + Avoid blockquote when parent style has more indent (Milan Bracke).
+      When a paragraph has an indentation different from the parent (named)
+      style, it used to be considered a blockquote. But this only makes sense
+      when the paragraph has more indentation. So this commit adds a check
+      for the indentation of the parent style.
+    + Fix handling of empty fields (Milan Bracke).  Some fields only
+      have an `instrText` and no content, Pandoc didn't understand these,
+      causing other fields to be misunderstood because it seemed like
+      a field was still open when it wasn't.
+    + Implement PAGEREF fields (Milan Bracke).  These fields, often used
+      in tables of contents, can be a hyperlink.
+    + Fix handling of nested fields (Milan Bracke).  Fields delimited by
+      `fldChar` elements can contain other fields. Before, the nested
+      fields would be ignored, except for the end, which would be
+      considered the end of the parent field.
+    + Add placeholder for word diagram instead of just omitting it (Ezwal).
+
+  * Org reader:
+
+    + Don't parse a list as first item in a list item (#7557).
+    + Allow an initial `:PROPERTIES:` drawer to add to metadata (#7520).
+
+  * Docx writer:
+
+    + Make id used in `native_numbering` predictable (#7551).
+    If the image has the id IMAGEID, then we use the id ref_IMAGEID
+    for the figure number.  This allows one to create a filter that
+    adds a figure number with figure name, e.g.
+    `<w:fldSimple w:instr=" REF ref_superfig "><w:r><w:t>Figure X</w:t>
+    </w:r></w:fldSimple>`.
+    If an image lack an id, an id of the form `ref_fig1` is used.
+  + Ensure we have unique ids for `wp:docPr` and `pic:cNvPr` elements
+    (#7527, #7503).
+  + Handle SVG images (#4058).  This change has several parts:
+    - In Text.Pandoc.App, if the writer is docx, we fill the media
+      bag and attempt to convert any SVG images to PNG, adding these
+      to the media bag.  The PNG backups have the same filenames as
+      the SVG images, but with an added .png extension.  If the conversion
+      cannot be done (e.g. because rsvg-convert is not present),
+      a warning is omitted.
+    - In Text.Pandoc.Writers.Docx, we now use Word 2016's syntax for
+      including SVG images. If a PNG fallback is present in the media bag,
+      we include a link to that too.
+
+  * Powerpoint writer (Emily Bourke):
+
+    + Add support for more layouts (#5097).  Up til now, four layouts
+      were supported: "Title Slide" (used for the automatically generated
+      metadata slide), "Section Header" (used for headings above slide
+      level), "Two Column" (used when there's a columns div), "Title and
+      Content" (used for all other slides).  We now support three
+      additional layouts: "Comparison", "Content with Caption", and
+      "Blank".  The manual describes the logic that determines which
+      layout is used for a slide.  Layouts may be customized in the
+      reference doc.
+    + Support specifying slide background images using a `background-image`
+      attribute on the slide's heading.  Only the "stretch" mode is supported,
+      and the background image is centred around the slide in the image's
+      larger axis, matching the observed default behaviour of PowerPoint.
+    + Add support for incremental lists (through same methods as in
+      other slide writers) (#5689).
+    + Copy embedded fonts from reference doc.
+    + Include all themes in output archive.
+    + Fix list level numbering (#4828, #4663).  In PowerPoint,
+      the content of a top-level list is at the same level as the content
+      of a top-level paragraph: the only difference is that a list style
+      has been applied.  Previously, the writer incremented the paragrap
+      h level on each list, turning what should be top-level lists into
+      second-level lists.
+    + Line up list continuation paragraphs.  This commit
+      changes the `marL` and `indent` values used for plain paragraphs
+      and numbered lists, and changes the spacing defined in the
+      reference doc master for bulleted lists.  For paragraphs, there is
+      now a left-indent taken from the `otherStyle` in the master.
+      For numbered lists, the number is positioned where the text would be
+      if this were a plain paragraph, and the text is indented to the next
+      level. This means that continuation paragraphs line up nicely with
+      numbered lists.  Existing reference docs may need to be modified so
+      that `otherStyle` and `bodyStyle` indent levels match, for this
+      feature to work with them.
+    + Consolidate text runs when possible (jgm).  This slims down the output
+      files by avoiding unnecessary text run elements.
+    + Support footers in the reference doc.
+      There is one behaviour which may not be immediately obvious: if the
+      reference doc specifies a fixed date (i.e. not automatically updating),
+      and there’s a date specified in the metadata for the document, the
+      footer date is replaced by the metadata date.
+    + Fix presentation rel numbering.  Before now, the numbering of `rId`s
+      was inconsistent when making the presentation XML and when making
+      the presentation relationships XML.
+    + Don’t add relationships unnecessarily.  Before now, for any layouts
+      added to the output from the default reference doc, the relationships
+      were unconditionally added to the output. However, if there was already
+      a layout in slideMaster1 at the same index then that results in
+      duplicate relationships.
+    + If slide level is 0, don't insert a slide break between a heading
+      and a following table, "columns" div, or paragraph starting
+      with an image.
+    + Fix capitalisation of `notesMasterId`.
+    + Restructure tests.
+
+  * Asciidoc writer:
+
+    + Translate numberLines attribute to `linesnum` switch (Samuel Tardieu).
+    + Improve escaping for `--` in URLs (#7529).
+
+  * LaTeX writer:
+
+    + Make babel use more idiomatic (#7604, hseg).  Use babel's
+      bidi implementation.  Import babel languages individually instead
+      of as package options.  Move `header-includes` to after
+      `babel` setup so it can be modified.
+    + Use babel, not polyglossia, with xelatex.  Previously polyglossia
+      worked better with xelatex, but that is no longer the case, so
+      we simplify the code so that babel is used with all latex
+      engines.  This involves a change to the default LaTeX template.
+
+  * Markdown writer:
+
+    + Avoid bad wraps at the Doc Text level.  Previously we tried to
+      do this at the Inline list level, but it makes more sense to
+      intervene on breaking spaces at the Doc Text level.
+    + Use `underline` class rather than `ul` for underline.
+      This only affects output with `bracketed_spans` enabled.
+      The markdown reader parses spans with either `.ul` or `.underline` as
+      Underline elements, but we're moving towards preferring the latter.
+
+  * RST writer:
+
+    + Properly handle anchors to ids with spaces or leading underscore
+      (#7593).  In this cases we need the quoted form, e.g.
+      ```
+      .. _`foo bar`:
+
+      .. _`_foo`:
+      ```
+      Side note: rST will "normalize" these identifiers anyway,
+      ignoring the underscore.
+
+  * HTML writer:
+
+    + Render `\ref` and `\eqref` as inline math, not display (see #7589).
+    + Pass through `\ref` and `\eqref` if MathJax is used (#7587).
+    + Pass through inline math environments with KaTeX.
+    + Support `--reference-location` for HTML output (#7461,
+      Francesco Mazzoli).
+    + Set "hash" to True by default (for reveal.js) (#7574).  See #6968
+      where the motivation for setting "hash" to True is explained.
+
+  * Native writer:  Use pretty-show to format native output (#7580).
+    Previously we used our own homespun formatting.  But this produces
+    over-long lines that aren't ideal for diffs in tests.
+    Performance is slower by about a factor of 10, but this isn't
+    really a problem because native isn't suitable as a serialization
+    format. (For serialization you should use json, because the reader
+    is so much faster than native.)
+
+  * Org writer:
+
+    + Don't indent contents of code blocks.  We previously indented them
+      by two spaces, following a common convention.  Since the convention
+      is fading, and the indentation is inconvenient for copy/paste, we are
+      discontinuing this practice.
+    + Update list of supported source languages in org writer (#5440).
+
+  * Ipynb writer (Kolen Cheung):
+
+    + Improve round trip identity for raw cell output.
+      See jupyter/nbformat#229.  The Jupyter ecosystem, including nbconvert,
+      lab and notebook, deviated from their own spec in nbformat, where
+      they used the key `raw_mimetype` instead of `format`.  Moreover,
+      the mime-type of rst used in Jupyter deviated from that suggested by
+      https://docutils.sourceforge.io/FAQ.html and is defined as
+      `text/restructuredtext` when chosen from "Raw NBConvert Format" in
+      Jupyter.  The new behavior should matche the real world usage better,
+      hence improving the round-trip "identity" in raw-cell.
+    + Add more formats that can be handled as "raw" cells.
+
+  * EPUB writer:
+
+    + Add EPUB3 subject metadata (authority/term) (nuew).
+      This adds the ability to specify EPUB 3 `authority` and `term` specific
+      refinements to the `subject` tag. Specifying a plain `subject` tag in
+      metadata will function as before.
+    + Treat epub:type "frontispiece" as front matter (#7600).
+
+  * reveal.js template: Fix line numbers in source code (#7634).
+    We need `overflow: visible` for these to work, and reveal's
+    default css disables this.  So we re-enable it in the default template.
+
+  * Text.Pandoc.Writers.Shared:
+
+    + Export `splitSentences` as a Doc Text transform [API change].
+      Use this in man/ms.  We used to attempt automatic sentence
+      splitting in man and ms output, since sentence-ending
+      periods need to be followed by two spaces or a newline in
+      these formats.  But it's difficult to do this reliably at
+      the level of `[Inline]`.
+
+  * Text.Pandoc.Translations: small revisions for compatibility
+    with aeson 2.
+
+  * Don't prepend `file://` to `--syntax-definition` on Windows (#6374).
+    This was a fix for a problem in skylighting, but this
+    problem doesn't exist now that we've moved from HXT to xml-conduit.
+
+  * Text.Pandoc.Extensions:
+
+    + Add `Ext_footnotes` to default `gfm` etxensions.  Now `gfm`
+      supports footnotes.
+    + Alphabetize Extension constructors (also affects `--list-extensions`).
+
+  * Text.Pandoc.Citeproc.Util: Better implementation of `splitStrWhen`.
+    Previously the citeproc code had two less efficient
+    implementations.
+
+  * Update documentation for definition_list extension (#7594).
+    In 2015, we relaxed indentation requirements for the first
+    line of a definition (see commit d3544dc and issue #2087), but
+    the documnentation wasn't updated to reflect the change.
+
+  * Text.Pandoc.Citeproc.BibTeX: Fix expansion of special strings in series
+    e.g. `newseries` or `library` (#7591).  Expansion should not happen
+    when these strings are protected in braces, or when they're
+    capitalized.
+
+  * Text.Pandoc.Logging: add `NotUTF8Encoded` constructor to `LogMessage`
+    [API change].
+
+  * Text.Pandoc.App.FormatHeuristics: remove `.tei.xml` extension for TEI
+    (#7630).  This never worked, because `takeExtension`
+    only returns `.xml`.  So it won't be missed if we remove it.
+
+  * Text.Pandoc.Image:
+
+    + Generalize `svgToPng` to MonadIO.
+    + `svgToPng`, change first parameter from WriterOptions to Int.
+
+  * Text.Pandoc.Class:
+
+    + Add `readStdinStrict` method to PandocMonad [API change].
+    + Generalize type of `extractMedia` [API change].
+      It was uselessly  restricted to PandocIO, instead of any
+      instance of PandocMonad and MonadIO.
+
+  * Text.Pandoc.Class.PandocIO: derive MonadCatch, MonadThrow, MonadMask.
+    This allows us to use `withTempDir` [API change].
+
+  * Add module Text.Pandoc.Class.Sandbox, defining
+   `sandbox`.  Exported via Text.Pandoc.Class. [API change]
+
+  * Text.Pandoc.Filter:  Generalize type of `applyFilters`
+    from PandocIO to any instance of MonadIO and PandocMonad [API change].
+
+  * Text.Pandoc.PDF: generalize type of `makePDF`:
+    instead of PandocIO, it can be used in any instance of
+    PandocMonad, MonadIO, and MonadMask [API change].
+
+  * Lua subsystem and custom writers: generalize types from PandocIO
+    to any instance of PandocMonad and MonadIO [API change].
+    The type of `runLua` is now
+
+        (PandocMonad m, MonadIO m) =>
+        LuaE PandocError a -> m (Either PandocError a)
+
+    The change from `Lua` to `LuaE PandocError` is due to the switch to
+    hslua-2.0; see next item.
+
+  * Lua modules (Albert Krewinkel):
+
+    + Switch to hslua-2.0.  The new HsLua version takes a somewhat different
+      approach to marshalling and unmarshalling, relying less on typeclasses
+      and more on specialized types. This allows for better performance and
+      improved error messages.  Furthermore, new abstractions allow to
+      document the code and exposed functions.
+    + Marshal Version values, Inline elements, Attr elements,
+      and Pandoc elements as userdata.
+    + Remove deprecated inline constructors `DoubleQuoted`,
+      `SingleQuoted`, `DisplayMath`, and `InlineMath`.
+    + Attr values are no longer normalized when assigned to an Inline
+      element property.
+    + It's no longer possible to access parts of Inline elements via
+      numerical indexes. E.g., `pandoc.Span('test')[2]` used to give
+      `pandoc.Str 'test'`, but yields `nil` now. This was undocumented
+      behavior not intended to be used in user scripts. Use named properties
+      instead.
+    + Accessing `.c` to get a JSON-like tuple of all components no longer
+      works. This was undocumented behavior.
+    + Only known properties can be set on an element value. Trying to set a
+      different property will now raise an error.
+    + Adds a new `pandoc.AttributeList()` constructor, which creates the
+      associative attribute list that is used as the third component of
+      `Attr` values. Values of this type can often be passed to constructors
+      instead of `Attr` values.
+    + Convert IOErrors to PandocErrors in `pandoc.pipe` function (#7523).
+
+  * Text.Pandoc.PDF:  Previously we had to run `runIOorExplode` inside
+    `withTempDir`.  Now that PandocIO is an instance of MonadMask, this is
+    no longer necessary.
+
+  * Text.Pandoc.App:
+
+    + Reorganize to make it easier to limit IO in main loop.
+      Previously we used liftIO fairly liberally.  The code has
+      been restructured to avoid this.
+    + Move output-file writing out of PandocMonad action.
+
+  * Text.Pandoc.App.OutputSettings: Generalize some types
+    so we can run this with any instance of PandocMonad and MonadIO,
+    not just PandocIO.
+
+  * Use `simpleFigure` builder in readers  and `SimpleFigure`
+    pattern synonym in writers (Aner Lucero).
+
+  * Allow time 1.12.
+
+  * Use skylighting-0.12, skylighting-core-0.12.
+    This fixes highlighting issues with typescript, scala, and other
+    syntaxes that include keyword lists from different syntaxes.
+
+  * Use citeproc 0.6, commonmark 0.2.2.1, commonmark-extensions 0.2.2,
+    texmath 0.12.3.2, ipynb 0.1.0.2.  (These changes also allow
+    building with aeson >= 2.)
+
+  * Require doclayout >= 0.3.1.1.  This fixes recognition of "real widths"
+    of emoji characters, which is important for tabular layout.
+
+  * Cut out over 100K of fat in epub test golden files.
+
+  * Make `test/epub/wasteland.epub` valid.
+
+  * Add missing `%` on some command tests.
+    This prevented `--accept` from working properly.
+
+  * Command tests: raise error if command doesn't begin with `%`.
+
+  * OOXML tests: use pretty-printed form to display diffs.
+    Otherwise everything is on one line and the diff is uninformative.
+
+  * Fix compareXML helper in Tests.Writers.OOXML.
+    Given how it is used, we were getting "mine" and "good"
+    flipped in the test results.
+
+  * MANUAL.txt:
+
+    + Clarify `attributes` extension support (William Lupton).
+    + Document formats affected by `--reference-location`.
+    + Document error code 25
+    + Add some more info regarding `--slide-level=0` (Salim B).
+    + Add more to security section of manual.
+    + Mention support of `title-toc` (#7171, Christophe Dervieux).
+
+  * doc/lua-filters.md:
+
+    + Add missing type for Image title (Quinn).
+    + Improve order of Image fields (Quinn).
+    + Rephrase pandoc.path docs (#7548, Quinn).
+    + Do not leak working directory in TikZ filter (Jeroen de Haas).
+
+## pandoc 2.14.2 (2021-08-21)
+
+  * Allow `--slide-level=0` (#7476). When the slide level is set
+    to 0, headings won't be used at all in splitting the document
+    into slides. Horizontal rules must be used to separate slides.
+
+  * Add RTF reader (#3982). `rtf` is now supported as an input
+    format as well as an output format. New module
+    Text.Pandoc.Readers.RTF (exporting `readRTF`). [API change]
+
+  * HTML reader:  treat comments as blank when parsing (#7482).
+
+  * Markdown reader:
+
+    + Fix raw LaTeX injection issue (#7497). Using a code block
+      containing `\end{verbatim}`, one could inject raw TeX into a
+      LaTeX document even when `raw_tex` is disabled. Thanks to
+      Augustin Laville for noticing the bug.
+    + Multimarkdown sub- and superscripts (#5512, OCzarnecki).
+      Added an extension `short_subsuperscripts` which modifies
+      the behavior of `subscript` and `superscript`, allowing
+      subscripts or superscripts containing only alphanumerics
+      to end with a space character (eg. `x^2 = 4` or `H~2 is
+      combustible`).  This improves support for multimarkdown.
+
+  * RST reader: Fix `:literal:` includes (#7513).  These should create
+    code blocks, not insert raw RST.
+
+  * LaTeX reader:
+
+    + Proper implicit grouping around environment macros.
+    + Support `\global` before `\def`, `\let`, etc. (#7494).
+    + Fix scope for LaTeX macros (#7494). They should by default
+      scope over the group in which they are defined (except `\gdef`
+      and `\xdef`, which are global). In addition, environments must
+      be treated as groups.
+    + Improve handling of plain TeX macro primitives (#7474).
+      Fixed semantics for `\let`.
+    + Implement `\edef`, `\gdef`, and `\xdef`.
+
+  * Docx reader: Improve docx reader's robustness in extracting
+    images (#7511). The docx reader made some assumptions about
+    how docx containers were laid out that were not always true, with
+    the result that some images in documents did not get
+    extracted.
+
+  * LaTeX writer: Increase table column width precision (#7466,
+    Peter Fabinski). In some cases, the rounding performed by the
+    LaTeX table writer would introduce visible overrun outside
+    the text area. This adds two more decimal places to the width
+    values.
+
+  * Powerpoint writer:
+
+    + Include image title in description (#7352, Emily Bourke). The
+      image title (i.e. `![alt text](link "title")`) was previously
+      ignored when writing to pptx. This commit includes it in
+      PowerPoint's description of the image, along with the link.
+    + Select layouts from reference doc by name (Emily Bourke). Until
+      now, users had to make sure that their reference doc contains
+      layouts in a specific order: the first four layouts in the file
+      had to have a specific structure. Now the layout selection uses
+      the layout names rather than order: users must make sure their
+      reference doc contains four layouts with specific names, and if
+      a layout with the right name isn’t found pandoc will emit
+      a warning and use the corresponding layout from the default
+      reference doc as a fallback.
+
+  * Docx writer: be sensitive to the `native_numbering` extension
+    (#7499).  Figure and table numbers are now only included if
+    `native_numbering` is enabled.  (By default it is disabled.)
+    This is a behavior change with respect to 2.14.1, but the
+    default behavior is now that of previous versions.  The
+    change was necessary to avoid incompatibilities between
+    pandoc's native numbering and third-party cross reference
+    filters like pandoc-crossref.
+
+  * RTF writer:
+
+    + Omit `\bin` in `\pict`. According to the spec, this is not
+      needed or wanted when the data is in hexadecimal format, as
+      here.
+    + Emit `\outlinelevel`` for section headings.
+
+  * RTF template: specify font family for fixed-width font f1.
+    According to the spec, this is mandatory.
+
+  * LaTeX writer: Use ulem for underline (#7351). ulem is
+    conditionally included already when the `strikeout` variable
+    is set, so we set this when there is underlined text, and use
+    `\uline` instead of `\underline`. This fixes wrapping for
+    underlined text.
+
+  * Text.Pandoc.Citeproc:
+
+    + Revise citeproc code to fit new citeproc 0.5 API (thanks to
+      Benjamin Bray). Linkification of URLs in the bibliography
+      is now done in the citeproc library, depending on the
+      setting of an option.  We set that option depending on the
+      value of the metadata field `link-bibliography` (defaulting
+      to true, for consistency with earlier behavior). If a DOI,
+      PMID, PMCID, or URL field is present but not explicitly
+      rendered, the title (or if no title, the whole entry) is
+      hyperlinked. These changes implement the recommendations
+      from the draft CSL v1.0.2 spec (Appendix VI):
+      <https://github.com/citation-style-language/documentation/blob/master/specification.rst#appendix-vi-links>
+    + Avoid odd handling of quotes. Recent citeproc changes
+      allow us to ignore Quoted elements; citeproc now uses its own
+      method for represented quoted things, and only localizes and
+      flipflops quotes it adds itself. Convert Quoted in bib
+      entries to special Spans before passing them off to
+      citeproc. This ensures that we get proper localization and
+      flipflopping if, e.g., quotes are used in titles
+      (jgm/citeproc#87).
+    + Removed quote localization from citeproc processing.
+      This is now done in citeproc itself.
+
+  * Text.Pandoc.Logging: Add PowerpointTemplateWarning log message
+    type [API change] (Emily Bourke).
+
+  * Text.Pandoc.Extension: Add `Ext_short_subsuperscripts`
+    constructor to `Extension` [API change] (OCzarnecki).
+
+  * Various sample.lua editorial fixes (#7493, #7487, William
+    Lupton).
+
+  * Bump base-compat version so we get compatibility with base 4.12.
+
+  * Use Prelude from base-compat for ghc 8.4 too.
+
+  * Add haskell-language-server to shell.nix (#7496, Emily Bourke).
+
+  * Tests.Helpers: export testGolden and use it in RTF reader.
+    This gives a diff output on failure.
+
+  * Remove obsolete and incorrect sentence in `--slide-level` docs.
+
+  * Add internal module Text.Pandoc.Network.HTTP, exporting
+    `urlEncode`.
+
+  * Text.Pandoc.Parsing: `parseFromString`: preserve at least
+    the source directory (#7464). Previously we just set the
+    source name to "chunk" when parsing from strings, to avoid
+    misleading source positions. This had the side effect that
+    `rebase_relative_paths` would break inside sections that
+    were parsed as strings. So, now we use
+    "ORIGINAL_SOURCE_PATH_chunk" instead of just "chunk".
+
+  * Text.Pandoc.MIME: use image/x-xcf instead of application/x-xcf
+    (#7454).
+
+  * Don’t compare `cdLine` in OOXML golden tests (Emily Bourke).
+    The `cdLine` field gives the line of the file some CData was
+    found on, which reflects irrelevant formatting differences.
+
+  * Provide more detailed XML diff in tests (Emily Bourke).
+
+  * OOXML tests: silence warnings. These can make the test output
+    confusing, making people think tests are failing when they're
+    passing.
+
+  * INSTALL.md: Add GitLab CI/CD example (#7448, Veratyr).
+
+  * MANUAL.txt
+
+    - Clarifications (William Lupton).
+    - Add a note on security risks of include directives.
+
+  * Document use of the 'underline' class (#7492, #7484, William
+    Lupton).
+
+  * Add a FAQ about the "Cannot allocate memory" error on M1 macs.
+
+  * Use texmath 0.12.3.1.
+
+  * Use released citeproc 0.5.
+
+  * Remove dependency on HTTP package (#7456, mt_caret).
+
+## pandoc 2.14.1 (2021-07-18)
+
+  * Text.Pandoc.ImageSize: Add Tiff constructor for ImageType (#7405)
+    [Minor API change].  This allows pandoc to get size information from
+    tiff images.
+
+  * Markdown reader:  don't try to read contents in self-closing HTML tag.
+    Previously we had problems parsing raw HTML with self-closing
+    tags like `<col/>`. The problem was that pandoc would look
+    for a closing tag to close the markdown contents, but the
+    closing tag had, in effect, already been parsed by `htmlTag`.
+
+  * LaTeX reader:
+
+    + Avoid trailing hyphen in translating languages (#7447).
+      Previously `\foreignlanguage{english}` turned into `<span lang="en-">`.
+      The same issue affected Arabic.
+    + Support `\cline` in LaTeX tables (#7442).
+    + Improved parsing of raw LaTeX from Text streams (`rawLaTeXParser`,
+      used to read LaTeX in Markdown files, #7434).  We now use source
+      positions from the token stream to tell us how much of the text stream
+      to consume.  Getting this to work required a few other changes to
+      make token source positions accurate.
+
+  * DocBook reader:
+
+    + Handle images with imageobjectco elements (#7440).
+    + Add support for citerefentry (#7437, Jan Tojnar).
+
+  * RST reader: fix regression with code includes (#7436).
+    With the recent changes to include infrastructure,
+    included code blocks were getting an extra newline.
+
+  * HTML reader:
+
+    + Recognize data-external when reading HTML img tags (#7429,
+      Michael Hoffmann).  Preserve all attributes in img tags.  If attributes
+      have a `data-` prefix, it will be stripped.  In particular, this
+      preserves a `data-external` attribute as an `external` attribute in
+      the pandoc AST.
+    + Add col, colgroup to 'closes' definitions
+
+  * HTML writer:
+
+    + Remove duplicated alt text in HTML output (Aner Lucero).
+    + Remove `aria-hidden` when explicit alt text is provided (Aner Lucero).
+    + Set boolean values for reveal.js variables.
+
+  * Docx writer:
+
+    + Add table numbering for captioned tables.
+      The numbers are added using fields, so that Word can
+      create a list of tables that will update automatically.
+    + Support figure numbers.  These are set up in such a way that they
+      will work with Word's automatic table of figures (#7392).
+
+  * Markdown writer: put space between Plain and following fenced Div
+    (#4465).
+
+  * EPUB writer: Don't incorporate externally linked images in EPUB documents
+    (#7430, Michael Hoffmann).  Just as it is possible to avoid incorporating
+    an image in EPUB by passing `data-external="1"` to a raw HTML snippet,
+    this makes the same possible for native Images, by looking for an
+    associated `external` attribute.
+
+  * Text.Pandoc.PDF:
+
+    + Fix `svgIn` path error (#7431).  We were duplicating
+      the temp directory; this didn't cause problems on macOS or linux
+      because there we use absolute paths for the temp directory.
+      But on Windows it caused errors converting SVG files.
+    + `convertImage`: normalize paths (#7431).  This will avoid paths
+      on Windows with mixed path separators.
+
+  * Text.Pandoc.Class: Always use / when adding directory to image destination
+    with `extractMedia`, even on Windows.
+
+  * Text.Pandoc.Citeproc:
+
+    + Allow `$` characters in bibtex keys (#7409).
+    + Set proper initial source name in parsing BibTeX (for better error
+      messages.)
+    + Revamp note citation handling (#7394).  Use latest
+      citeproc, which uses a Span with a class rather than a Note for notes.
+      This helps us distinguish between user notes and citation notes.  Don't
+      put citations at the beginning of a note in parentheses.  Fix small bug
+      in handling of citations in notes, which led to commas at the end of
+      sentences in some cases.
+    + Cleanup and efficiency improvement in `deNote`.
+    + Improve punctuation moving with `--citeproc`.  Previously, using
+      `--citeproc` could cause punctuation to move in quotes even when
+      there aer no citations. This has been changed; punctuation moving
+      is now limited to citations.  In addition, we only move footnotes
+      around punctuation if the style is a note style, even if
+      `notes-after-punctuation` is `true`.
+
+  * Use citeproc 0.10. This helps improve note citations (see above)
+    and eliminates double hyperlinks in author-in-text citations.
+    Author-only citations are no longer hyperlinked.  See jgm/citeproc#77.
+    It also fixes moving of punctuation inside quotes to conform to
+    the CSL spec: only comma and period are moved, not question
+    mark or exclamation point.
+
+  * Text.Pandoc.Error: fix line calculations in reporting parsec errors.
+    Also remove a spurious initial newline in the error report.
+
+  * Use doctemplates 0.4.1, which gives us better support for boolean
+    variable values.  Previously `$if(foo)$` would evaluate to true
+    for variables with boolean `false` values, because it cared only
+    about the string rendering (#7402).
+
+  * Require commonmark-pandoc >= 0.2.2.1.
+    This fixes task lists with multiple paragraphs.
+
+  * Use skylighting 0.11.
+
+  * CSS in HTML template: reset overflow-wrap on code blocks
+    (Mauro Bieg, #7423).
+
+  * LaTeX template: Revert change in PR #7295: "move title, author, date up
+    to top of preamble." The change caused problem for people who used
+    LaTeX commands defined defined later in the preamble in the title
+    or author fields (#7422).
+
+  * Add `doc/faqs.md`.  This is imported from the website; in the future the
+    website version will be drawn from here.
+    Added a FAQ on the use of `\AtEndPreamble` for cases when the contents of
+    `header-includes` need to refer to definitions that come later in the
+    preamble.  See #7422.
+
+  * Upgrade Debian 10 AMI for build-arm.sh.
+
+  * CircleCI: change to using xcode 11.1.0 (macOS 10.14.4).
+    We previously built on 10.13, but 10.13 no longer gets
+    security updates and CirclCI is deprecating.
+
+## pandoc 2.14.0.3 (2021-06-22)
+
+  * Text.Pandoc.MediaBag `insertMediaBag`: ensure we get a sane mediaPath
+    for URLs (#7391).  In earlier 2.14.x versions, we'd get
+    incorrect paths for resources downloaded from URLs when the
+    media are extracted (including in PDF production).
+  * Text.Pandoc.Parsing: improve `emailAddress` (#7398).
+    Previously the parser would accept characters in domains
+    that are illegal in domains, and this sometimes caused it
+    to gobble bits of the following text.
+  * txt2tags reader: modify the email address parser so
+    it still includes form parameters, even after the change to
+    `emailAddress` in Text.Pandoc.Parsing.
+  * Text.Pandoc.Readers.Metadata: Fix regression with comment-only YAML
+    metadata blocks (#7400).
+  * reveal.js writer and template: better handling of options.  Previously
+    it was impossible to specify false values for options that default to
+    true (e.g. `center`); setting the option to false just caused the portion
+    of the template setting the option to be omitted.  Now we prepopulate
+    all the variables with their default values, including them all
+    unconditionally and allowing them to be overridden.
+  * Markdown writer: Fix regression in code blocks with attributes (#7397).
+    Code blocks with a single class but nonempty attributes
+    were having attributes drop as a result of #7242.
+  * LaTeX writer:
+    + Add strut at end of minipage if it contains line breaks.
+      Without them, the last line is not as tall as it should be in
+      some cases.
+    + Always use a minipage for cells with line breaks, when
+      width information is available (#7393).  Otherwise the way we treat them
+      can lead to content that overflows a cell.
+    + Use `\strut` instead of `~` before `\\` in empty line.
+  * Use lts-18.0 stack resolver.
+  * Require skylighting 0.10.5.2 (adding support for Swift).
+  * Require commonmark 0.2.1.
+  * Rephrase section on unsafe HTML in manual.
+  * Create SECURITY.md
+
+## pandoc 2.14.0.2 (2021-06-13)
+
+  * Fix MediaBag regressions (#7345). iIn the 2.14 release `--extract-media`
+    stopped working as before; there could be mismatches between the
+    paths in the rendered document and the extracted media.
+    This patch makes several changes that restore the earlier behavior
+    (while keeping the same API).  The `mediaPath` in 2.14 was always
+    constructed from the SHA1 hash of the media contents.  Now, we
+    preserve the original path unless it's an absolute path or contains
+    `..` segments (in that case we use a path based on the SHA1 hash of
+    the contents).
+
+    In Text.Pandoc.MediaBag, `mediaDirectory` and `mediaItems` now use the
+    `mediaPath`, rather than the mediabag key, for the first component of the
+    tuple.  This makes more sense, I think, and fits with the documentation of
+    these functions; eventually, though, we should rework the API so that
+    `mediaItems` returns both the keys and the MediaItems.
+
+    In Text.Pandoc.Class.IO, rewriting of source paths in `extractMedia` has
+    been fixed.
+
+    In Text.Pandoc.Class.PandocMonad, `fillMediaBag` has been modified so that
+    it doesn't modify image paths (that was part of the problem in #7345).
+
+    We now do path normalization (e.g. `\` separators on Windows) in
+    writing the media.
+
+  * Text.Pandoc.PDF:
+
+    + Text.Pandoc.PDF: Fix regression in 2.14 for generation of PDFs with
+      SVGs (#7344).
+    + Only print relevant part of environment on `--verbose`.  Since
+      `--verbose` output might be put in an issue, we want to avoid
+      spilling out secrets in environment variables.
+
+  * Markdown reader: fix pipe table regression in 2.11.4 (#7343).
+    Previously pipe tables with empty headers (that is, a header
+    line with all empty cells) would be rendered as headerless
+    tables.  This broke in 2.11.4.  The fix here is to produce an
+    AST with an empty table head when a pipe table has all empty
+    header cells.
+
+  * LaTeX reader: don't allow optional `*` on symbol control sequences
+    (#7340).  Generally we allow optional starred variants of LaTeX commands
+    (since many allow them, and if we don't accept these explicitly,
+    ignoring the star usually gives acceptable results).  But we
+    don't want to do this for `\(*\)` and similar cases.
+
+  * Docx reader: handle absolute URIs in Relationship Target (#7374).
+
+  * Docx writer: fix handling of empty table headers (Albert Krewinkel,
+    #7369).  A table header which does not contain any cells is now treated as
+    an empty header.
+
+  * LaTeX writer: Fix regression in table header position (#7347).
+    In recent versions the table headers were no longer bottom-aligned
+    (if more than one line).  This patch fixes that by using minipages
+    for table headers in non-simple tables.
+
+  * CommonMark writer:
+
+    + Do not use simple class for fenced-divs (Jan Tojnar, amends #7242.)
+    + Do not throw away attributes when `Ext_attributes` is enabled.
+      `Ext_attributes` covers at least the following:
+      `Ext_fenced_code_attributes`, `Ext_header_attributes`,
+      `Ext_inline_code_attributes`, `Ext_link_attributes`.
+
+  * Markdown writer:
+
+    + Allow `pipe_tables` to be disabled for commonmark formats
+      (`commonmark_x`, `gfm`) (#7375).
+    + Re-use functions from Text.Pandoc.Markdown.Inline (Jan Tojnar).
+
+  * DocBook writer: Remove non-existent admonitions (Jan Tojnar).
+    `attention`, `error` and `hint` are reStructuredText specific.
+
+  * HTML writer: Don't omit width attribute on div (#7342).
+
+  * Text.Pandoc.MIME, `extensionFromMimeType`: add a few special cases.
+    When we do a reverse lookup in the MIME table, we just get the
+    last match, so when the same mime type is associated with several
+    different extensions, we sometimes got weird results, e.g. `.vs`
+    for `text/plain`.  These special cases help us get the most standard
+    extensions for mime types like `text/plain`.
+
+  * Lua utils: fix handling of table headers in `from_simple_table` (Albert
+    Krewinkel, #7369).  Passing an empty list of header cells now results
+    in an empty table header.
+
+  * Text.Pandoc.Citeproc:
+
+    + Avoid duplicate classes and attributes on references div.
+    + Fix regression in citeproc processing (#7376).  If inline
+      references are used (in the metadata `references` field), we
+      should still only include in the bibliography items that are
+      actually cited (unless `nocite` is used).
+
+  * Require citeproc 0.4.0.1.  This fixes a bug which led to doubled
+    "et al." in some (rare) circumstances.
+
+  * MANUAL.txt:
+
+    + Mention GladTeX for EPUB export (Sebastian Humenda).
+      This updates the manual and the web site about the GladTeX usage.
+    + More details and a useful link for YAML syntax.
+
+  * CONTRIBUTING.md: update modules overview (Albert Krewinkel).
+
+  * using-the-pandoc-api.md: switch from String to Text (Albert Krewinkel).
+
+
+## pandoc 2.14.0.1 (2021-06-01)
+
+  * Commonmark reader: Fix regression in 2.14 with YAML metdata block parsing,
+    which could cause the document body to be omitted after metadata (#7339).
+
+  * HTML reader: fix column width regression in 2.14 (#7334).
+    Column widths specified with a style attribute were off by a factor of 100.
+
+  * Markdown reader: in `rebasePaths`, check for both Windows and Posix
+    absolute paths.  Previously Windows pandoc was treating
+    `/foo/bar.jpg` as non-absolute.
+
+  * Text.Pandoc.Logging: In rendering `LoadedResource`, use relative paths.
+
+  * Docx writer: fix regression on captions (#7328).  The "Table Caption"
+    style was no longer getting applied.  (It was overwritten by "Compact.")
+
+  * Use commonmark-extensions 0.2.1.2
+
+## pandoc 2.14 (2021-05-28)
+
+  * Change reader types, allowing better tracking of source positions
+    [API change].  Previously, when multiple file arguments were provided,
+    pandoc simply concatenated them and passed the contents to the readers,
+    which took a Text argument.  As a result, the readers had no way of knowing
+    which file was the source of any particular bit of text.  This meant that
+    we couldn't report accurate source positions on errors or include accurate
+    source positions as attributes in the AST.  More seriously, it meant that
+    we couldn't resolve resource paths relative to the files containing them
+    (see e.g. #5501, #6632, #6384, #3752).
+
+  * Add `rebase_relative_paths` extension (#3752).  When enabled, this
+    extension rewrites relative image and link paths by prepending
+    the (relative) directory of the containing file.  This
+    behavior is useful when your input sources are split
+    into multiple files, across several directories, with files
+    referring to images stored in the same directory.  The
+    extension can be enabled for all markdown and commonmark-based formats.
+
+  * Add Text.Pandoc.Sources (exported module), with a `Sources` type and a
+    `ToSources` class.  A `Sources` wraps a list of `(SourcePos, Text)` pairs
+    [API change]. A parsec `Stream` instance is provided for `Sources`.  The
+    module also exports versions of parsec's `satisfy` and other Char parsers
+    that track source positions accurately from a `Sources` stream (or any
+    instance of the new `UpdateSourcePos` class).
+
+  * Text.Pandoc.Parsing
+
+    + Export the modified Char parsers defined in Text.Pandoc.Sources
+      instead of the ones parsec provides.  Modified parsers to use a
+      `Sources` as stream [API change].
+    + Improve include file functions [API change].  Remove old
+      `insertIncludedFileF`.  Give `insertIncludedFile` a more general type,
+      allowing it to be used where `insertIncludedFileF` was.
+    + Add parameter to the `citeKey` parser from
+      Text.Pandoc.Parsing, which controls whether the `@{..}`
+      syntax is allowed [API change].
+
+  * Text.Pandoc.Error: Modified the constructor `PandocParsecError` to take a
+    `Sources` rather than a `Text` as first argument, so parse error locations
+    can be accurately reported.
+
+  * Fix source position reporting for YAML bibliographies (#7273).
+
+  * Issue error message when  reader or writer format is malformed
+    (#7231).  Previously we exited with an error status but (due to a bug)
+    no message.
+
+  * Smarter smart quotes (#7216, #2103).  Treat a leading `"` with no
+    closing `"` as a left curly quote.  This supports the practice, in
+    fiction, of continuing paragraphs quoting the same speaker without an
+    end quote.  It also helps with quotes that break over lines in line blocks.
+
+  * Markdown reader:
+
+    + Use MetaInlines not MetaBlocks for multimarkdown metadata fields.
+      This gives better results in converting to e.g.  pandoc markdown.
+    + Implement curly-brace syntax for Markdown citation keys (#6026).
+      The change provides a way to use citation keys that contain
+      special characters not usable with the standard citation key syntax.
+      Example: `@{foo_bar{x}'}` for the key `foo_bar{x}`.  It also allows
+      separating citation keys from immediately following text, e.g. `@{foo}A`.
+
+  * RST reader:
+
+    + Seek include files in the directory of the file
+      containing the include directive, as RST requires (#6632).
+    + Use `insertIncludedFile` from Text.Pandoc.Parsing
+      instead of reproducing much of its code.
+
+  * Org reader: Resolve org includes relative to the directory containing the
+    file containing the INCLUDE directive (#5501).
+
+  * ODT reader: Treat tabs as spaces (#7185, niszet).
+
+  * Docx reader:
+
+    + Add handling of vml image objects (#7257, mbrackeantidot).
+    + Support new table features (Emily Bourke, #6316):  column
+      spans, row spans, multiple header rows, table description
+      (parsed as a simple caption), captions, column widths.
+
+  * LaTeX reader:
+
+    + Improved siunitx support (#6658, #6620).
+    + Better support for `\xspace` (#7299).
+    + Improve parsing of `\def` macros.  We previously set "verbatim mode"
+      even for parsing the initial `\def`; this caused problems
+      for `\def` nested inside another `\def`.
+    + Implement `\newif`.
+
+  * ConTeXt writer: improve ordered lists (#5016, Denis Maier).
+    Change ordered list from itemize to enumerate.  Add new
+    itemgroup for ordered lists.  Remove manual insertion of
+    width attributes.  Use tabular figures in ordered list
+    enumerators.
+
+  * HTML reader:
+
+    + Don't fail on unmatched closing "script" tag (Albert Krenkel, #7282).
+    + Keep h1 tags as normal headers (#2293, Albert Krewinkel).
+      The tags `<title>` and `<h1 class="title">` often contain the same
+      information, so the latter was dropped from the document. However, as
+      this can lead to loss of information, the heading is now always
+      retained.  Use `--shift-heading-level-by=-1` to turn the `<h1>`
+      into the document title, or a filter to restore the previous behavior.
+    + Handle relative lengths (e.g. `2*`) in HTML column widths (#4063).
+      See <https://www.w3.org/TR/html4/types.html#h-6.6>.
+
+  * DocBook/JATS readers:
+
+    + Fix mathml regression caused by the switch in XML libraries (#7173).
+    + Fix "phrase" in DocBook: take classes from "role" not "class" (#7195).
+
+  * DocBook reader: ensure that first and last names are separated (#6541).
+
+  * Jira reader (Albert Krewinkel, #7218):
+
+    + Support "smart" links: `[alias|https://example.com|smart-card]` syntax.
+    + Allow spaces and most unicode characters in attachment links.
+    + No longer require a newline character after `{noformat}`.
+    + Only allow URI path segment characters in bare links.
+    + The `file:` schema is no longer allowed in bare links; these
+      rarely make sense.
+
+  * Plain writer: handle superscript unicode minus (#7276).
+
+  * LaTeX writer:
+
+    + Better handling of line breaks in simple tables (#7272).
+      Now we also handle the case where they're embedded in other elements,
+      e.g. spans.
+    + For beamer output, support `exampleblock` and `alertblock` (#7278).
+      A block will be rendered as an `exampleblock` if the heading
+      has class `example` and an `alertblock` if it has class `alert`.
+    + Separate successive quote chars with thin space (#6958,
+      Albert Krewinkel).  Successive quote characters are separated with
+      a thin space to improve readability and to prevent unwanted ligatures.
+      Detection of these quotes sometimes had failed if the second quote
+      was nested in a span element.
+    + Separate successive quote chars with thin space (#6958, Albert
+      Krewinkel).
+
+  * EPUB Writer: Fix belongs-to-collection XML id choice (#7267, nuew).
+    The epub writer previously used the same XML id for both the book
+    identifier and the epub collection. This causes an error on epubcheck.
+
+  * BibTeX/BibLaTeX writer: Handle `annote` field (#7266).
+
+  * ZimWiki writer: allow links and emphasis in headers (#6605,
+    Albert Krewinkel).
+
+  * ConTeXt writer:
+
+    + Support blank lines in line blocks (#6564, Albert Krewinkel,
+      thanks to @denismaier).
+    + Use span identifiers as reference anchors (#7246, Albert Krewinkel).
+
+  * HTML writer:
+
+    + Keep attributes from code nested below `pre` tag (#7221,
+      Albert Krewinkel).  If a code block is defined with `<pre><code
+      class="language-x">…</code></pre>`, where the `<pre>` element has no
+      attributes, then the attributes from the `<code>` element are used
+      instead. Any leading `language-` prefix is dropped in the code's
+      `class` attribute are dropped to improve syntax highlighting.
+    + Ensure headings only have valid attribs in HTML4 (#5944, Albert
+      Krewinkel).
+    + Parse `<header>` as a Div (Albert Krewinkel).
+
+  * Org writer:
+
+    + Inline latex envs need newlines (#7252, tecosaur).
+      As specified in https://orgmode.org/manual/LaTeX-fragments.html, an
+      inline \begin{}...\end{} LaTeX block must start on a new line.
+    + Use LaTeX style maths deliminators (#7196, tecosaur).
+
+  * JATS writer (Albert Krewinkel):
+
+    + Use either styled-content or named-content for spans (#7211).
+      If the element has a content-type attribute, or at least one class,
+      then that value is used as `content-type` and the span is put inside
+      a `<named-content>` element. Otherwise a `<styled-content>` element
+      is used instead.
+    + Reduce unnecessary use of `<p>` elements for wrapping (#7227).
+      The `<p>` element is used for wrapping in cases were the contents
+      would otherwise not be allowed in a certain context. Unnecessary
+      wrapping is avoided, especially around quotes (`<disp-quote>` elements).
+    + Convert spans to `<named-content>` elements (#7211).  Spans with
+      attributes are converted to `<named-content>` elements instead of
+      being wrapped with `<milestone-start/>` and `<milestone-end>`
+      elements. Milestone elements are not allowed in documents using the
+      articleauthoring tag set, so this change ensures the creation of valid
+      documents.
+    + Add footnote number as label in backmatter (#7210).  Footnotes in the
+      backmatter are given the footnote's number as a label.  The
+      articleauthoring output is unaffected from this change, as footnotes
+      are placed inline there.
+    + Escape disallows chars in identifiers.  XML identifiers must start
+      with an underscore or letter, and can contain only a limited set
+      of punctuation characters. Any IDs not adhering to these rules are
+      rewritten by writing the offending characters as `Uxxxx`,
+      where `xxxx` is the character's hex code.
+
+  * Jira writer:  use `{color}` when span has a color attribute
+    (Albert Krewinkel, tarleb/jira-wiki-markup#10).
+
+  * Docx writer:
+
+    + Autoset table width if no column has an explicit width (Albert
+      Krewinkel).
+    + Extract Table handling into separate module (Albert Krewinkel).
+    + Support colspans and rowspans in tables (Albert Krewinkel, #6315).
+    + Support multirow table headers (Albert Krewinkel).
+    + Improve integration of settings from reference.docx (#1209).
+      This change allows users to create a reference.docx that
+      sets `w:proofState` for spelling or grammar to `dirty`,
+      so that spell/grammar checking will be triggered on the
+      generated docx.
+    + Copy over more settings from reference.docx (#7240).  From settings.xml
+      in the reference-doc, we now include: `zoom`, `embedSystemFonts`,
+      `doNotTrackMoves`, `defaultTabStop`, `drawingGridHorizontalSpacing`,
+      `drawingGridVerticalSpacing`, `displayHorizontalDrawingGridEvery`,
+      `displayVerticalDrawingGridEvery`, `characterSpacingControl`,
+      `savePreviewPicture`, `mathPr`, `themeFontLang`, `decimalSymbol`,
+      `listSeparator`, `autoHyphenation`, `compat`.
+    + Set zoom to 100% by default in settings.xml.
+    + Align math options more with current Word defaults (e.g.  Cambria Math
+      font).
+    + Remove `rsid`s from default settings.xml.  Word will add these
+      when revisions are made.
+
+  * Ms writer: Handle tables with multiple paragraphs (#7288).
+    Previously they overflowed the table cell width.  We now set line lengths
+    per-cell and restore them after the table has been written.
+
+  * Markdown writer:
+
+    + Use cleaner braceless syntax for code blocks with a
+      single class (#7242, Jan Tojnar).
+    + Add quotes properly in markdown YAML metadata fields (#7245).
+      This fixes a bug, which caused the writer to look at the *last*
+      rather than the *first* character in determining whether quotes
+      were needed.  So we got spurious quotes in some cases and
+      didn't get necessary quotes in others.
+    + Use `@{..}` syntax for citations when needed.
+    + Use fewer unneeded escapes for `#` (see #6259).
+    + Improve escaping of `@`.  We need to escape literal `@` before
+      `{` because of the new citation syntax.
+
+  * Commonmark writer: Use backslash escapes for `<` and `|`...
+    instead of entities (#7208).
+
+  * Powerpoint writer: allow `monofont` to be specified in metadata
+    (#7187).
+
+  * LaTeX template:
+
+    + Use non-starred names for xcolor color names (#6109).
+      This should make svgnames and x11names work properly.
+    + Fix bad vertical spacing after bibliography (#7234, badumont).
+    + List of figures before list of tables (#7235, Julien Dutant).
+    + Move CSL macro definitions before header-includes so they can be
+      overridden (#7286).
+    + Improve treatment of CSL `entry-spacing` (#7296).
+      Previously with the default template settings (`indent` variable
+      not set), we would get interparagraph spaces separating bib
+      entries even with `entry-spacing="0"`.  On the other hand,
+      setting `entry-spacing="2"` gave ridiculously large spacing.
+      This change makes the spacing caused by `entry-spacing` a multiple
+      of `\parskip` by default, which gives aesthetically reasonable
+      output.  Those who want a larger or smaller unit (e.g. because
+      they use `indent` which sets `\parskip` to 0) may
+      `\setlength{\cslentryspacingunit}{10pt}` in header-includes
+      to override the defaults.
+    + Move title, author, date up to top of preamble (#7295).
+      This allows header-includes to use them, and puts them
+      in a position where you can see them immediately.
+    + Define commands for zero width non-joiner character
+      (#6639, Albert Krewinkel).  The zero-width non-joiner character
+      is used to avoid ligatures (e.g. in German).
+
+  * ConTeXt template:
+
+    + Define `enumerate` itemgroup (#5016, Denis Maier).
+    + List of figures before list of tables (#7235, Julien Dutant).
+
+  * reveal.js template:
+
+    + Support `toc-title` (#7171, Florian Kohrt).
+    + Use `hash: true` by default rather than `history: true` (#6968).
+
+  * HTML-based slide shows: add support for `institute` (#7289, Thomas
+    Hodgson).
+
+  * Text.Pandoc.Extensions: Add constructor `Ext_rebase_relative_paths` to
+    `Extensions` [API change].
+
+  * Text.Pandoc.XML.Light: add Eq, Ord instances for Content,
+    Element, Attr, CDataKind [API change].
+
+  * Text.Pandoc.MediaBag:
+
+    + Change type to use a `Text` key instead of `[FilePath]`.
+      We normalize the path and use `/` separators for consistency.
+    + Export `MediaItem` type [API change].
+    + Change `MediaBag` type to a map from Text to MediaItem [API change].
+    + `lookupMedia` now returns a `MediaItem` [API change].
+    + Change `insertMedia` so it sets the `mediaPath` to a filename based on
+      the SHA1 hash of the contents.  This will be used when contents
+      are extracted.
+
+  * Text.Pandoc.Class.PandocMonad:
+
+    + Remove `fetchMediaResource` [API change].  Use `fetchItem` to get
+      resources in `fillMediaBag`.
+    + Add informational message in `downloadOrRead` indicating what path
+      local resources have been loaded from.
+
+  * Text.Pandoc.Logging:
+
+    + Remove single quotes around paths in messages.
+    + Add LoadedResource constructor to LogMessage [API change].
+      This is for INFO-level messages telling where image data has been
+      loaded from.  (This can vary because of the resource path.)
+
+  * Text.Pandoc.Asciify: simplify code and export `toAsciiText` [API change].
+    Instead of encoding a giant (and incomplete) map, we now
+    just use unicode-transforms to normalize the text to
+    a canonical decomposition, and manipulate the result.
+
+  * App: allow tabs expansion even if file-scope is used (Albert Krewinkel,
+    #6709).  Tabs in plain-text inputs  are now handled correctly, even if
+    the `--file-scope` flag is used.
+
+  * Add new internal module Text.Pandoc.Writers.GridTable (Albert Krewinkel).
+
+  * Text.Pandoc.Highlighting: Change type of `languagesByExtension`, adding
+    a parameter for a `SyntaxMap` [API change] (Jan Tojnar, #7241).
+    Languages defined using `--syntax-definition` were not recognized by
+    `languagesByExtension`.  This patch corrects that, allowing the writers
+    to see all custom definitions.  The LaTeX writer still uses the default
+    syntax map, but that's okay in that context, since
+    `--syntax-definition` won't create new listings styles.
+
+  * Text.Pandoc.Citeproc:
+
+    + Ensure that CSL-related attributes are passed on to a Div with id
+      'refs'.  Otherwise things like `entry-spacing` won't work when
+      such Divs are used.
+    + Use metadata's `lang` for the lang parameter of citeproc, overriding
+      `localeLanguage`.
+    + Recognize locators spelled with a capital letter (#7323).
+    + Add a comma and a space in front of the suffix if it doesn't start
+      with space or punctuation (#7324).
+    + Don't detect math elements as locators (#7321).
+
+  * Remove Text.Pandoc.BCP47 module [API change].  Use types and functions
+    from UnicodeCollation.Lang instead.  This is a richer implementation
+    of BCP 47.
+
+  * Text.Pandoc.Shared:
+
+    + Fix regression in grid tables for wide characters (#7214).
+      In the translation from String to Text, a char-width-sensitive
+      `splitAt'` was dropped.  This commit reinstates it and uses it to make
+      `splitTextByInstances` char-width sensitive.
+    + Add `getLang` (formerly in the now-removed BCP47) [API change].
+
+  * Text.Pandoc.SelfContained: use `application/octet-stream`
+    for unknown mime types instead of halting with an error (#7202).
+
+  * Lua filters: respect Inlines/Blocks filter functions in `pandoc.walk_*`
+    (Albert Krewinkel).
+
+  * Add text as build-depend for trypandoc (#7193, Roman Beránek).
+
+  * Bump upper-bounds for network-uri, time, attoparsec.
+
+  * Use citeproc 0.4.
+
+  * Use texmath 0.12.3.
+
+  * Use jira-wiki-markup 1.3.5 (Albert Krewinkel).
+
+  * Require latest skylighting (fixes a bug in XML syntax highlighting).
+
+  * Use latest xml-conduit.
+
+  * Use latest commonmark, commonmark-extensions, commonmark-pandoc.
+
+  * Use haddock-library-1.10.0 (Albert Krewinkel).
+
+  * Allow compilation with base 4.15 (Albert Krewinkel).
+
+  * MANUAL:
+
+    + Add information about `lang` and bibliography sorting.
+    + Add info about YAML escape sequences, link to spec (#7152,
+      Albert Krewinkel).
+    + Note that `institute` variable works for HTML-based slides.
+    + Update documentation on citation syntax.
+    + Add citation example for locators and suffixes (Tristan Stenner)
+
+  * Updated and fixed typos in documentation (Charanjit Singh,
+    Anti-Distinctlyminty, Tatiana Porras, obcat).
+
+  * Add instructions for installing pandoc-types before compiling filter.
+
+  * INSTALL: add note that parallel installations should be avoided
+    (#6865).
+
+  * Remove `biblatex-nussbaum.md` test.  It is basically the same
+    as `biblaetx-quotes.md`.
+
+  * Command tests: fail if a file contains no tests---and fix a
+    test that failed in that way!
+
+  * Use smaller images in tests, reducing the size of the source tarball by 8 MB.
+
+
+## pandoc 2.13 (2021-03-21)
+
+  * Support `yaml_metadata_block` extension for `commonmark`, `gfm` (#6537).
+    This supported is a bit more limited than with pandoc's
+    `markdown`.  The YAML block must be the first thing in the input,
+    and the leaf notes are parsed in isolation from the rest of
+    the document.  So, for example, you can't use reference
+    links if the references are defined later in the document.
+
+  * Fix fallback to default partials when custom templates are used.
+    If the directory containing a template does not contain the partial,
+    it should be sought in the default templates, but this was not
+    working properly (#7164).
+
+  * Handle `nocite` better with `--biblatex` and `--natbib` (#4585).
+    Previously the nocite metadata field was ignored with these formats.
+    Now it populates a `nocite-ids` template variable and causes a
+    `\nocite` command to be issued.
+
+  * Text.Pandoc.Citeproc: apply `fixLinks` correctly (#7130).  This is code
+    that incorporates a prefix like `https://doi.org/` into a following link
+    when appropriate.
+
+  * Text.Pandoc.Shared:
+
+    + Remove `backslashEscapes`, `escapeStringUsing` [API change].  Replace
+      these inefficient association list lookups with more efficient escaping
+      functions in the writers that used them (for a 10-25% performance boost
+      in org, haddock, rtf, texinfo writers).
+    + Remove `ToString`, `ToText` typeclasses [API change].  These were needed
+      for the transition from String to Text, but they are no longer used and
+      may clash with other things.
+    + Simplify `compactDL`.
+
+  * Text.Pandoc.Parsing:
+
+    + Change type of `readWithM` so that it is no longer polymorphic
+      [API change].  The `ToText` class has been removed, and now that we've
+      completed the transition to Text we no longer need this to operate
+      on Strings.
+    + Remove `F` type synonym [API change].  Muse and Org were defining their
+      own `F` anyway.
+
+  * Text.Pandoc.Readers.Metadata:
+
+    + Export `yamlMetaBlock` [API change].
+    + Make `yamlBsToMeta`, `yamlBsToRefs` polymorphic on the parser state
+      [API change].
+
+  * Markdown reader: Fix regression with `tex_math_backslash` (#7155).
+
+  * MediaWiki reader: Allow block-level content in notes (ref) (#7145).
+
+  * Jira reader (Albert Krewinkel):
+
+    + Fixed parsing of autolinks (i.e., of bare URLs in the text).
+      Previously an autolink would take up the rest of a line, as spaces
+      were allowed characters in these items.
+    + Emoji character sequences no longer cause parsing failures. This was
+      due to missing backtracking when emoji parsing fails.
+    + Mark divs created from panels with class "panel".
+
+  * RST reader: fix logic for ending comments (#7134).  Previously comments
+    sometimes got extended too far.
+
+  * DocBook writer:  include Header attributes as XML attributes on
+    section (Erik Rask).  Attributes with key names that are not allowed
+    as XML attributes are dropped, as are attributes with invalid values
+    and `xml:id` (DocBook 5) and `id` (DocBook 4).
+
+  * Docx writer:
+
+    + Make `nsid` in `abstractNum` deterministic.  Previously we assigned
+      a random number, but we don't need random values, so now we just
+      assign a value based on the list marker.
+    + Use integral values for `w:tblW` (#7141).
+
+  * Jira writer (Albert Krewinkel):
+
+    + Block quotes are only rendered as `bq.` if they do not contain a
+      linebreak.
+    + Jira writer: improve div/panel handling.  Include div attributes in
+      panels, always render divs with class `panel` as panels, and
+      avoid nesting of panels.
+
+  * HTML writer: Add warnings on duplicate attribute values.
+    This prevents emitting invalid HTML.  Ultimately it would be good to
+    prevent this in the types themselves, but this is better for now.
+
+  * Org writer: Prevent unintended creation of ordered list items (#7132,
+    Albert Krewinkel).  Adjust line wrapping if default wrapping would cause
+    a line to be read as an ordered list item.
+
+  * JATS templates: support 'equal-contrib' attrib for authors (Albert
+    Krewinkel).  Authors who contributed equally to a paper may be marked
+    with `equal-contrib`.
+
+  * reveal.js template: replace JS comment with HTML (#7154, Florian Kohrt).
+
+  * Text.Pandoc.Logging: Add `DuplicateAttribute` constructor to `LogMessage`.
+    [API change]
+
+  * Use `-j4` for linux release build.  This speeds up the build dramatically
+    on arm.
+
+  * cabal.project: remove ghcoptions.  Move flags to top level, so they can
+    be set differently on the command line.
+
+  * Require latest texmath, skylighting, citeproc, jira-wiki-markup.
+    (The latest skylighting fixes a bad bug with Haskell syntax highlighting.)
+    Narrow version bounds for texmath, skylighting, and citeproc, since
+    the test output depend on them.
+
+  * Use doclayout 0.3.0.2.  This significantly reduces the time and memory
+    needed to compile pandoc.
+
+  * Use `foldl'` instead of `foldl` everywhere.
+
+  * Update bounds for random (#7156, Alexey Kuleshevich).
+
+  * Remove uses of some partial functions.
+
+  * Don't bake in a larger stack size for the executable.
+
+  * Test improvements:
+
+    + Use `getExecutablePath` from base, avoiding the dependency on
+      `executable-path`.
+    + Factor out `setupEnvironment` in Helpers, to avoid code duplication.
+    + Fix finding of data files by setting teh `pandoc_datadir` environment
+      variable when we shell out to pandoc. This avoids the need to use
+      `--data-dir` for the tests, which caused problems finding `pandoc.lua`
+      when compiling without the `embed_data_files` flag (#7163).
+
+  * Benchmark improvements:
+
+    + Build `+RTS -A8m -RTS` into default ghc-options for benchmark.
+      This is necessary to get accurate benchmark results; otherwise we
+      are largely measuring garbage collecting, some not related to the
+      current benchmark.
+    + Allow specifying BASELINE file in 'make bench' for comparison
+      (otherwise the latest benchmark is chosen by default).
+    + Force `readFile` in benchmarks early (Bodigrim).
+
+  * CONTRIBUTING: suggest using a `cabal.project.local` file (#7153,
+    Albert Krewinkel).
+
+  * Add ghcid-test to Makefile.  This loads the test suite in ghcid.
+
+
+## pandoc 2.12 (2021-03-08)
+
+  * `--resource-path` now accumulates if specified multiple
+    times (#6152).  Resource paths specified later on the command line are
+    prepended to those specified earlier.  Thus,
+    `--resource-path foo --resource-path bar:baz` is equivalent to
+    `--resource-path bar:bas:foo`.  (The previous behavior was
+    for the last `--resource-path` to replace all the rest.)
+    `resource-path` in defaults files behaves the same way: it
+    will be prepended to the resource path set by earlier
+    command line options or defaults files.  This change
+    facilitates the use of multiple defaults files: each can
+    specify a directory containing resources it refers to
+    without clobbering the resource paths set by the others.
+
+  * Allow defaults files to refer to the home directory, the
+    user data directory, and the directory containing the defaults file
+    itself (#5871, #5982, #5977).  In fields that expect file paths
+    (and only in these fields),
+
+    + `${VARIABLE}` will expand to the value of the environment variable
+      `VARIABLE` (and in particular `${HOME}` will expand to the path
+      of the home directory).  A warning will be raised for undefined
+      variables.
+    + `${USERDATA}` will expand to the path of the user data
+      directory in force when the defaults file is being processed.
+    + `${.}` will expand to the directory containing the defaults file.
+      (This allows default files to be placed in a directory containing
+      resources they make use of.)
+
+  * When downloading content from URL arguments, be sensitive to
+    the character encoding (#5600).  We can properly handle UTF-8 and latin1
+    (ISO-8859-1); for others we raise an error.  Fall back to latin1 if
+    no charset is given in the mime type and UTF-8 decoding fails.
+
+  * Allow abbreviations that don't end in a period to be
+    specified using `--abbreviations` (#7124).
+
+  * Add new unexported module Text.Pandoc.XML.Light, as well
+    as Text.Pandoc.XML.Light.Types, Text.Pantoc.XML.Light.Proc,
+    Text.Pandoc.XML.Light.Output.  (Closes #6001, #6565, #7091).
+
+    This module exports definitions of `Element` and `Content`
+    that are isomorphic to xml-light's, but with Text
+    instead of String.  This allows us to keep most of the code in existing
+    readers that use xml-light, but avoid lots of unnecessary allocation.
+
+    We also add versions of the functions from xml-light's
+    Text.XML.Light.Output and Text.XML.Light.Proc that operate on our
+    modified XML types, and functions that convert xml-light types to our
+    types (since some of our dependencies, like texmath, use xml-light).
+
+    We export functions that use xml-conduit's parser to produce an
+    `Element` or `[Content]`.  This allows existing pandoc code to use
+    a better parser without much modification.
+
+    The new parser is used in all places where xml-light's parser was
+    previously used.  Benchmarks show a significant performance improvement
+    in parsing XML-based formats (with docbook, opml, jats, and docx
+    almost twice as fast, odt and fb2 more than twice as fast).
+
+    In addition, the new parser gives us better error reporting than
+    xml-light.  We report XML errors, when possible, using the new
+    `PandocXMLError` constructor in `PandocError`.
+
+    These changes revealed the need for some changes in the tests.  The
+    docbook-reader.docbook test lacked definitions for the entities it used;
+    these have been added. And the docx golden tests have been updated,
+    because the new parser does not preserve the order of attributes.
+
+  * DocBook reader:
+
+    + Avoid expensive tree normalization step, as it is not necessary
+      with the new XML parser.
+    + Support `informalfigure` (#7079) (Nils Carlson).
+
+  * Docx reader:
+
+    + Use Map instead of list for Namespaces.  This gives a speedup of
+      about 5-10%. With this and the XML parsing changes, the docx reader
+      is now about twice as fast as in the previous release.
+
+  * HTML reader:
+
+    + Small performance tweaks.
+    + Also, remove exported class `NamedTag(..)` [API change]. This was just
+      intended to smooth over the transition from String to Text and is no
+      longer needed.
+    + As a result, the functions `isInlineTag` and `isBlockTag`
+      are no longer polymorphic; they apply to a `Tag Text` [API change].
+    + Do a lookahead to find the right parser to use.  This takes
+      benchmarks from 34ms to 23ms, with less allocation.
+    + Fix bad handling of empty `src` attribute in `iframe` (#7099).
+      If `src` is empty, we simply skip the `iframe`.
+      If `src` is invalid or cannot be fetched, we issue a warning
+      nd skip instead of failing with an error.
+
+  * JATS reader:
+
+    + Avoid tree normalization, which is no longer necessary given the
+      new XML parser.
+
+  * LaTeX reader:
+
+    + Don't export `tokenize`, `untokenize` [API change].  These are internal
+      implementation details, which were only exported for testing.
+      They don't belong in the public API.
+    + Improved efficiency of the parser.  With these changes the reader
+      is almost twice as fast as in the last release in our benchmarks.
+    + Code cleanup, removing some unnecessary things.
+    + Rewrite `withRaw` so it doesn't rely on fragile assumptions
+      about token positions (which break when macros are expanded)
+      (#7092).  This requires the addition of `sEnableWithRaw` and
+      `sRawTokens` in `LaTeXState`, and a new combinator `disablingWithRaw`
+      to disable collecting of raw tokens in certain contexts.
+      Add `parseFromToks` to Text.Pandoc.Readers.LaTeX.Parsing.
+      Fix parsing of single character tokens so it doesn't mess
+      up the new raw token collecting.  These changes slightly increase
+      allocations and have a small performance impact.
+    + Handle some bibtex/biblatex-specific commands that used to be
+      dealt with in pandoc-citeproc (#7049).
+    + Optimize `satisfyTok`, avoiding unnecessary macro expansion steps.
+      Benchmarks after this change show 2/3 of the run time and 2/3 of the
+      allocation of the Feb. 10 benchmarks.
+    + Removed `sExpanded` in state.  This isn't actually needed and checking
+      it doesn't change anything.
+    + Improve `braced'`.  Remove the parameter, have it parse the
+      opening brace, and make it more efficient.
+    + Factor out pieces of the LaTeX reader to make the module smaller.
+      This reduces memory demands when compiling.  Created
+      Text.Pandoc.Readers.{LaTeX,Math,Citation,Table,Macro,Inline}.
+      Changed Text.Pandoc.Readers.LaTeX.SIunitx to export a command map
+      instead of individual commands.
+    + Handle table cells containing `&` in `\verb` (#7129).
+
+  * Make Text.Pandoc.Readers.LaTeX.Types an unexported module [API change].
+
+  * Markdown reader:
+
+    + Improved handling of mmd link attributes in references (#7080).
+      Previously they only worked for links that had titles.
+    + Improved efficiency of the parser (benchmarks show a 15% speedup).
+
+  * OPML reader:
+
+    + Avoid tree normalization, which is no longer necessary with the
+      new XML parser.
+
+  * ODT reader:
+
+    + Finer-grained errors on parse failure (#7091).
+    + Give more information if the zip container can't be unpacked.
+
+  * Org reader:
+
+    + Support `task_lists` extension (Albert Krewinkel, #6336).
+    + Fix bug in org-ref citation parsing (Albert Krewinkel, #7101).
+      The org-ref syntax allows to list multiple citations separated by
+      comma.  Previously commas were accepted as part of the citation id,
+      so all citation lists were parsed as one single citation.
+
+  * RST reader:
+
+    + Use `getTimestamp` instead of `getCurrentTime` to fetch timestamp.
+      Setting `SOURCE_DATE_EPOCH` will allow reproducible builds.
+    + RST reader: fix handling of header in CSV tables (#7064).
+      The interpretation of this line is not affected by the delim option.
+
+  * Jira reader:
+
+    + Modified the Doc parser to skip leading blank lines. This fixes
+      parsing of documents which start with multiple blank lines (Albert
+      Krewinkel, #7095).
+    + Prevent URLs within link aliases to be treated as autolinks (Albert
+      Krewinkel, #6944).
+
+  * Text.Pandoc.Shared
+
+    + Remove formerly exported functions that are no longer used in the
+      code base: `splitByIndices`, `splitStringByIndicies`, `substitute`,
+      and `underlineSpan` (which had been deprecated in April 2020)
+      [API change].
+    + Export `handleTaskListItem` (Albert Krewinkel) [API change].
+    + Change `defaultUserDataDirs` to `defaultUserDataDir` [API
+      change].  We determine what is the default user data directory
+      by seeing whether the XDG directory and/or legacy
+      directory exist.
+
+  * BibTeX writer:
+
+    + BibTeX writer: use doclayout and doctemplate.  This change allows
+      bibtex/biblatex output to wrap as other formats do,
+      depending on the settings of `--wrap` and `--columns` (#7068).
+
+  * CSL JSON writer:
+
+    + Output `[]` if no references in input, instead of raising a
+      PandocAppError as before.
+
+  * Docx writer:
+
+    + Use `getTimestamp` instead of `getCurrentTime` for timestamp.
+      Setting `SOURCE_DATE_EPOCH` will allow reproducible builds.
+
+  * EPUB writer:
+
+    + Use `getTimestamp` instead of `getCurrentTime` for timestamp.
+      Setting `SOURCE_DATE_EPOCH` will allow reproducible builds (#7093).
+      This does not suffice to fully enable reproducible in EPUB, since
+      a unique id is still being generated for each build.
+    + Support `belongs-to-collection` metadata (#7063) (Nick Berendsen).
+
+  * JATS writer:
+
+    + Escape special chars in reference elements (Albert Krewinkel).
+      Prevents the generation of invalid markup if a citation element
+      contains an ampersand or another character with a special meaning
+      in XML.
+
+  * Jira writer:
+
+    + Use Span identifiers as anchors (Albert Krewinkel).
+    + Use `{noformat}` instead of `{code}` for unknown languages (Albert
+      Krewinkel). Code blocks which are not marked as a language supported
+      by Jira are rendered as preformatted text via `{noformat}` blocks.
+
+  * LaTeX writer:
+
+    + Adjust hypertargets to beginnings of paragraphs (#7078).
+      Use `\vadjust pre` so that the hypertarget takes you to the beginning
+      of the paragraph rather than one line down.
+      This makes a particular difference for links to citations using
+      `--citeproc` and `link-citations: true`.
+    + Change BCP47 lang tag from `jp` to `ja` (Mauro Bieg, #7047).
+    + Use function instead of map for accent lookup (should be
+      more efficient).
+    + Split the module to make it easier to compile on low-memory
+      systems:  added Text.Pandoc.Writers.LaTeX.{Util,Citation,Lang}.
+
+  * Markdown writer:
+
+    + Handle math right before digit.  We insert an HTML comment to
+      avoid a `$` right before a digit, which pandoc will not recognize
+      as a math delimiter.
+    + Split the module to make it easier to compile on low-memory
+      systems: added Text.Pandoc.Writers.Markdown.{Types,Inline}.
+
+  * ODT writer:
+
+    + Use `getTimestamp` instead of `getCurrentTime` for timestamp.
+      Setting `SOURCE_DATE_EPOCH` will allow reproducible builds.
+    + Update default ODT style (Lorenzo).  Previously, the "First paragraph"
+      style inherited from "Standard" but not from "Text body." Now
+      it is adjusted to inherit from "Text body", to avoid some ugly
+      spacing issues. It may be necessary to update a custom `reference.odt`
+      in light of this change.
+
+  * Org writer:
+
+    + Support `task_lists` extension (Albert Krewinkel, #6336).
+
+  * Pptx writer:
+
+    + Use `getTimestamp` instead of `getCurrentTime` for timestamp.
+      Setting `SOURCE_DATE_EPOCH` will allow reproducible builds.
+
+  * JATS templates: tag `author.name` as `string-name` (Albert Krewinkel).
+    The partitioning the components of a name into surname, given names,
+    etc. is not always possible or not available. Using `author.name`
+    allows to give the full name as a fallback to be used when
+    `author.surname` is not available.
+
+  * Add default templates for bibtex and biblatex, so that
+    the variables `header-include`, `include-before`, `include-after`
+    (or alternatively the command line options
+    `--include-in-header`, `--include-before-body`, `--include-after-body`)
+    may be used.
+
+  * LaTeX template:
+
+    + Update to iftex package (#7073) (Andrew Dunning)
+    + Wrap url colours in braces (#7121) (Loïc Grobol).
+
+  * revealjs template: Add 'center' option for vertical slide centering.
+    (maurerle, #7104).
+
+  * Text.Pandoc.XML: Improve efficiency of `fromEntities`.
+
+  * Text.Pandoc.MIME
+
+    + Add exported function `getCharset` [API change].
+
+  * Text.Pandoc.UTF8: change IO functions to return Text, not String
+    [API change].  This affects `readFile`, `getContents`, `writeFileWith`,
+    `writeFile`, `putStrWith`, `putStr`, `putStrLnWith`, `putStrLn`.
+    `hPutStrWith`, `hPutStr`, `hPutStrLnWith`, `hPutStrLn`, `hGetContents`.
+    This avoids the need to uselessly create a linked list of characters
+    when emiting output.
+
+  * Text.Pandoc.App
+
+    + Add `parseOptionsFromArgs` [API change, new exported function].
+    + Add fields for CSL options to `Opt` [API change]:
+      `optCSL`, `optbibliography`, `optCitationAbbreviations`.
+
+  * Text.Pandoc.Citeproc.BibTeX
+
+    + `Text.Pandoc.Citeproc.writeBibTeXString` now returns
+      `Doc Text` instead of `Text` (#7068).
+    + Correctly handle `pages` (= `page` in CSL) (#7067).
+    + Correctly handle BibLaTeX `langid` (= `language` in CSL, #7067).
+    + In BibTeX output, protect foreign titles since there's no language
+      field (#7067).
+    + Clean up BibTeX parsing (#7049).  Previously there was a messy code
+      path that gave strange results in some cases, not passing through raw
+      tex but trying to extract a string content.  This was an artefact of
+      trying to handle some special bibtex-specific commands in the BibTeX
+      reader. Now we just handle these in the LaTeX reader and simplify
+      parsing in the BibTeX reader. This does mean that more raw tex will
+      be passed through (and currently this is not sensitive to the
+      `raw_tex` extension; this should be fixed).
+
+  * Text.Pandoc.Citeproc.MetaValue
+
+    + Correctly parse "raw" date value in markdown references metadata.
+      (See jgm/citeproc#53.)
+
+  * Text.Pandoc.Citeproc
+
+    + Use https URLs for links (Salim B, #7122).
+
+  * Text.Pandoc.Class
+
+    + Add `getTimestamp` [API change].  This attempts to read the
+      `SOURCE_DATE_EPOCH` environment variable and parse a UTC time
+      from it (treating it as a unix date stamp, see
+      https://reproducible-builds.org/specs/source-date-epoch/). If the
+      variable is not set or can't be parsed as a unix date stamp, then the
+      function returns the current date.
+
+  * Text.Pandoc.Error
+
+    + Add `PandocUnsupportedCharsetError` constructor for
+      `PandocError` [API change].
+    + Export `renderError` [API change].
+    + Refactor `handleError` to use `renderError`. This allows us render
+      error messages without exiting.
+
+  * Text.Pandoc.Extensions
+
+    + `Ext_task_lists` is now supported by org (and turned
+      on by default) (Albert Krewinkel, #6336).
+    + Remove `Ext_fenced_code_attributes` from allowed commonmark attributes
+      (#7097).  This attribute was listed as allowed, but it didn't actually
+      do anything. Use `attributes` for code attributes and more.
+
+  * Lua subsystem:
+
+    + Always load built-in Lua scripts from default data-dir (Albert
+      Krewinkel).  The Lua modules `pandoc` and `pandoc.List` are now always
+      loaded from the system's default data directory. Loading from a
+      different directory by overriding the default path, e.g. via
+      `--data-dir`, is no longer supported to avoid unexpected behavior
+      and to address security concerns.
+    + Add module "pandoc.path" (Albert Krewinkel, #6001, #6565).
+      The module allows to work with file paths in a convenient and
+      platform-independent manner.
+    + Use strict evaluation when retrieving AST value from the stack
+      (Albert Krewinkel, #6674).
+
+  * Text.Pandoc.PDF
+
+    + Disable `smart` extension when building PDF via LaTeX.
+      This is to prevent accidental creation of ligatures like
+      `` ?` `` and `` !` `` (especially in languages with quotations like
+      German), and similar ligature issues.  (See jgm/citeproc#54.)
+
+  * Text.Pandoc.CSV:
+
+    + Fix parsing of unquoted values (#7112).  Previously we didn't allow
+      unescaped quotes in unquoted values, but they are allowed
+      in CSV.
+
+  * Test suite:
+
+    + Use a more robust method for testing the executable.  Many
+      of our tests require running the pandoc executable. This
+      is problematic for a few different reasons. First,
+      cabal-install will sometimes run the test suite after
+      building the library but before building the executable,
+      which means the executable isn't in place for the tests.
+      One can work around that by first building, then building
+      and running the tests, but that's fragile.  Second, we
+      have to find the executable. So far, we've done that using
+      a function `findPandoc` that attempts to locate it
+      relative to the test executable (which can be located
+      using findExecutablePath).  But the logic here is delicate
+      and work with every combination of options.  To solve both
+      problems, we add an `--emulate` option to the
+      `test-pandoc` executable.  When `--emulate` occurs as the
+      first argument passed to `test-pandoc`, the program simply
+      emulates the regular pandoc executable, using the rest of
+      the arguments (after `--emulate`). Thus, `test-pandoc
+      --emulate -f markdown -t latex` is just like `pandoc -f
+      markdown -t latex`.  Since all the work is done by library
+      functions, implementing this emulation just takes a couple
+      lines of code and should be entirely reliable.  With this
+      change, we can test the pandoc executable by running the
+      test program itself (locatable using `findExecutablePath`)
+      with the `--emulate` option. This removes the need for the
+      fragile `findPandoc` step, and it means we can run our
+      integration tests even when we're just building the
+      library, not the executable.  [Note: part of this change
+      involved simplifying some complex handling to set
+      environment variables for dynamic library paths.  I have
+      tested a build with `--enable-dynamic-executable`, and it
+      works, but further testing may be needed.]
+    + Print accurate location if a test fails (Albert
+      Krewinkel).  Ensures that tasty-hunit reports the location
+      of the failing test instead of the location of the helper
+      `test` function.
+
+  * Documentation: Update URLs and use `https` where possible (#7122,
+    Salim B).
+
+  * Add `doc/libraries.md`, a description of libraries that support pandoc.
+
+  * MANUAL.txt
+
+    + MANUAL: block-level formatting is not allowed in line blocks (#7107).
+    + Clarify `tex_math_dollars` extension.  Note that no blank lines
+      are allowed between the delimiters in display math.
+    + Add MANUAL section on reproducible builds.
+    + Document no template fallback for absolute path (#7077, Nixon
+      Enraght-Moony.)
+    + Improve docs for cite-method.
+    + Update README and man page.
+
+  * Makefile: in `make bench`, create CSV files for comparison and compare
+    against previous benchmark run.  Add timestamp to CSV filenames.
+
+  * cabal.project: don't explicitly set -trypandoc.
+    If we do, this can't be overridden on the cabal command line.
+
+  * doc/lua-filters.md: improve documentation for
+    `pandoc.mediabag.insert`, `pandoc.mediabag.fetch`,
+    `directory`, `normalize` (Albert Krewinkel).
+
+  * Allow base64-bytestring-1.2.* (Dmitrii Kovanikov)
+
+  * Require jira-wiki-markup 1.3.3 (Albert Krewinkel)
+
+  * Require citeproc 0.3.0.8, which correctly titlecases when titles
+    contain non-ASCII characters.
+
+  * Use skylighting 0.10.4.  This version of skylighting uses xml-conduit
+    rather than hxt. This speeds up parsing of XML syntax definitions
+    fourfold, and removes four packages from pandoc's dependency graph:
+    hxt-charproperties, hxt-unicode, hxt-regex-xmlschema, hxt.
+
+  * Add script `tools/parseTimings.pl` to help pin down which
+    modules take the most time and memory to compile.
+
+  * Avoid unnecessary use of NoImplicitPrelude pragma (#7089) (Albert
+    Krewinkel)
+
+  * Benchmarks
+
+    + Use the lighter-weight tasty-bench instead of criterion.
+    + Run writer benchmarks for binary formats too.
+    + Alphabetize benchmarks.
+    + Don't run benchmarks for bibliography formats
+      (yet; we need a special input for them).
+    + Show allocation data
+    + Clean up benchmark code.
+    + Allow specifying patterns using `-p blah'.
+
+  * trypandoc: add 2 second timeout.
+
+  * Use `-split-sections` in creating linux release binary.
+    This reduces executable size significantly (by about 30%).
+
+  * Remove `weigh-pandoc`.  It's not really useful any more, now that our
+    regular benchmarks include data on allocation.
+
+  * Improve linux package build process and add script to
+    automate building an arm64 binary package.
+
+
+## pandoc 2.11.4 (2021-01-22)
+
+  * Add `biblatex`, `bibtex` as output formats (closes #7040).
+
+  * Recognize more extensions as markdown by default (#7034):
+    `mkdn`, `mkd`, `mdwn`, `mdown`, `Rmd`.
+
+  * Implement defaults file inheritance (#6924, David Martschenko).
+    Allow defaults files to inherit options from other defaults files by
+    specifying them with the following syntax:
+    `defaults: [list of defaults files or single defaults file]`.
+
+  * Fix infinite HTTP requests when writing epubs from URL source (#7013).
+    Due to a bug in code added to avoid overwriting the cover image
+    if it had the form `fileX.YYY`, pandoc made an endless sequence
+    of HTTP requests when writing epub with input from a URL.
+
+  * Org reader:
+
+    + Allow multiple pipe chars in todo sequences (Albert Krewinkel, #7014).
+      Additional pipe chars, used to separate "action" state from "no further
+      action" states, are ignored. E.g., for the following sequence, both
+      `DONE` and `FINISHED` are states with no further action required:
+      `#+TODO: UNFINISHED | DONE | FINISHED`.
+    + Restructure output of captioned code blocks (Albert Krewinkel, #6977).
+      The Div wrapper of code blocks with captions now has the class
+      "captioned-content". The caption itself is added as a Plain block
+      inside a Div of class "caption". This makes it easier to write filters
+      which match on captioned code blocks. Existing filters will need to be
+      updated.
+    + Mark verbatim code with class `verbatim` (Dimitri Sabadie, #6998).
+
+  * LaTeX reader:
+
+    + Handle `filecontents` environment (#7003).
+    + Put contents of unknown environments in a Div when `raw_tex` is not
+      enabled (#6997). (When `raw_tex` is enabled, the whole environment is
+      parsed as a raw block.) The class name is the name of the environment.
+      Previously, we just included the contents without the surrounding Div,
+      but having a record of the environment's boundaries and name can be
+      useful.
+
+  * Mediawiki reader:
+
+    + Allow space around storng/emph delimiters (#6993).
+
+  * New module Text.Pandoc.Writers.BibTeX, exporting
+    writeBibTeX and writeBibLaTeX. [API change]
+
+  * LaTeX writer:
+
+    + Revert table line height increase in 2.11.3 (#6996).
+      In 2.11.3 we started adding `\addlinespace`, which produced less dense
+      tables.  This wasn't an intentional change; I misunderstood a comment in
+      the discussion leading up to the change. This commit restores the earlier
+      default table appearance.  Note that if you want a less dense table, you
+      can use something like `\def\arraystretch{1.5}` in your header.
+
+  * EPUB writer:
+
+    + Adjust internal links to identifiers defined in raw HTML sections
+      after splitting into chapters (#7000).
+    + Recognize `Format "html4"`, `Format "html5"` as raw HTML.
+    + Adjust internal links to images, links, and tables after splitting into
+      chapters. Previously we only did this for Div and Span and Header
+      elements (see #7000).
+
+  * Ms writer:
+
+    + Don't justify text inside table cells.
+
+  * JATS writer:
+
+    + Use `<element-citation>` if `element_citations`
+      extension is enabled (Albert Krewinkel).
+    + Fix citations (Albert Krewinkel, #7018).  By default
+      we use formatted citations.
+    + Ensure that `<disp-quote>` is always wrapped in `<p>` (#7041).
+
+  * Markdown writer:
+
+    + Cleaned up raw formats.  We now react appropriately
+      to `gfm`, `commonmark`, and `commonmark_x` as raw formats.
+
+  * RST writer:
+
+    + Fix bug with dropped content from inside spans with a class in
+      some cases (#7039).
+
+  * Docx writer:
+
+    + Handle table header using styles (#7008).  Instead of hard-coding
+      the border and header cell vertical alignment, we now let this
+      be determined by the Table style, making use of Word's
+      "conditional formatting" for the table's first row.  For
+      headerless tables, we use the tblLook element to tell Word
+      not to apply conditional first-row formatting.
+
+  * Commonmark writer:
+
+    + Implement start number on ordered lists (#7009).  Previously they always
+      started at 1, but according to the spec the start number is respected.
+
+  * HTML writer:
+
+    + Fix implicit_figure at end of footnotes (#7006).
+
+  * ConTeXt template: Remove `\setupthinrules` from default template.
+    The width parameter this used is not actually supported,
+    and the command didn't do anything.
+
+  * Text.Pandoc.Extensions:
+
+    + Add `Ext_element_citations` constructor (Albert Krewinkel).
+
+  * Text.Pandoc.Citeproc.BibTeX: New unexported function
+    `writeBibtexString`.
+
+  * Text.Pandoc.Citeproc:
+
+    + Use finer grained imports (Albert Krewinkel).
+    + Factor out and export `getStyle` [API change].
+    + Export `getReferences` [API change, #7106].
+    + Factor out getLang.
+
+  * Text.Pandoc.Parsing: modify `gridTableWith'` for headerless tables.
+    If the table lacks a header, the header row should be an empty
+    list. Previously we got a list of empty cells, which caused
+    an empty header to be emitted instead of no header.  In LaTeX/PDF
+    output that meant we got a double top line with space between.
+
+  * ImageSize:  use `viewBox` for SVG if no length, width attributes (#7045).
+    This change allows pandoc to extract size information from more SVGs.
+
+  * Add simple default.nix.
+
+  * Use commonmark 0.1.1.3.
+
+  * Use citeproc 0.3.0.5.
+
+  * Update default CSL to use latest chicago-author-date.csl.
+
+  * CONTRIBUTING.md: add note on GNU xargs.
+
+  * MANUAL.txt:
+
+    + Update description of `-L`/`--lua-filter`.
+    + Document use of citations in note styles (#6828).
+
+## pandoc 2.11.3.2 (2020-12-29)
+
+  * HTML reader: use renderTags' from Text.Pandoc.Shared (Albert Krewinkel).
+    A side effect of this change is that empty `<col>` elements are written
+    as self-closing tags in raw HTML blocks.
+
+  * Asciidoc writer: Add support for writing nested tables (#6972, timo-a).
+    Asciidoc supports one level of nesting. If deeper tables are to be
+    written, they are omitted and a warning is issued.
+
+  * Docx writer: fix nested tables with captions (#6983).
+    Previously we got unreadable content, because docx seems
+    to want a `<w:p>` element (even an empty one) at the end of
+    every table cell.
+
+  * Powerpoint writer: allow arbitrary OOXML in raw inline elements
+    (Albert Krewinkel).  The raw text is now included verbatim in the
+    output. Previously is was parsed into XML elements, which prevented
+    the inclusion of partial XML snippets.
+
+  * LaTeX writer: support colspans and rowspans in tables (#6950,
+    Albert Krewinkel).  Note that the multirow package is needed for
+    rowspans.  It is included in the latex template under a variable,
+    so that it won't be used unless needed for a table.
+
+  * HTML writer: don't include p tags in CSL bibliography entries
+    (#6966).  Fixes a regression in 2.11.3.
+
+  * Add `meta-description` variable to HTML templates (#6982). This
+    is populated by the writer by stringifying the `description`
+    field of metadata (Jerry Sky).  The `description` meta tag will
+    make the generated HTML documents more complete and SEO-friendly.
+
+  * Citeproc: fix handling of empty URL variables (`DOI`, etc.).
+    The `linkifyVariables` function was changing these to links
+    which then got treated as non-empty by citeproc, leading
+    to wrong results (e.g. ignoring nonempty URL when empty DOI is present).
+    See jgm/citeproc#41.
+
+  * Use citeproc 0.3.0.3.  Fixes an issue in author-only citations when
+    both an author and translator are present, and an issue with
+    citation group delimiters.
+
+  * Require texmath 0.12.1.  This improves siunitx support in math,
+    fixes bugs with `\*mod` family operators and arrays, and avoids
+    italicizing symbols and operator names in docx output.
+
+  * Ensure that the perl interpreter used for filters with `.pl`
+    extension (wuffi).
+
+  * MANUAL: note that textarea content is never parsed as Markdown
+    (Albert Krewinkel).
+
+
+## pandoc 2.11.3.1 (2020-12-18)
+
+  * Added some missing files to extra-source-files and data
+    files, so they are included in the sdist tarball.  Closes #6961.
+    Cleaned up some extraneous data and test files, and added
+    a CI check to ensure that the test and data files included
+    in the sdist match what is in the git repository.
+
+  * Use citeproc 0.3.0.1, which avoids removing nonbreaking
+    space at the end of the `initialize-with` attribute. (Some
+    journals require nonbreaking space after initials, and this
+    makes that possible.)
+
+## pandoc 2.11.3 (2020-12-17)
+
+  * With `--bibliography` (or `bibliography` in metadata), a
+    URL may now be provided, and pandoc will fetch the resource.
+    In addition, if a file path is provided and it is not
+    found relative to the working directory, the resource
+    path will be searched (#6940).
+
+  * Add `sourcepos` extension for `commonmark`, `gfm`, `commonmark_x`
+    (#4565).  With the `sourcepos` extension set set, `data-pos`
+    attributes are added to the AST by the commonmark reader. No other
+    readers are affected.  The `data-pos` attributes are put on elements
+    that accept attributes; for other elements, an enlosing Div or Span
+    is added to hold the attributes.
+
+  * Change extensions for `commonmark_x`: replace `auto_identifiers`
+    with `gfm_auto_identifiers` (#6863).  `commonmark_x` never actually
+    supported `auto_identifiers` (it didn't do anything), because the
+    underlying library implements gfm-style identifiers only.  Attempts
+    to add the `auto_identifiers` extension to `commonmark` will now
+    fail with an error.
+
+  * HTML reader:
+
+    + Split module into several submodules (Albert Krewinkel).  Reducing
+      module size should reduce memory use during compilation.
+    + Support advanced table features (Albert Krewinkel):
+      block level content in captions, row and colspans,
+      body headers, row head columns, footers, attributes.
+    + Disable round-trip testing for tables. Information for cell
+      alignment in a column is not preserved during round-trips (Albert
+      Krewinkel).
+    + Allow finer grained options for tag omission (Albert Krewinkel).
+    + Simplify list attribute handling (Albert Krewinkel).
+    + Pay attention to `lang` attributes on body element (#6938).
+      These (as well as `lang` attributes on the html element) should update
+      lang in metadata.
+    + Retain attribute prefixes and avoid duplicates (#6938).
+      Previously we stripped attribute prefixes, reading `xml:lang` as
+      `lang` for example. This resulted in two duplicate `lang`
+      attributes when `xml:lang` and `lang` were both used.  This commit
+      causes the prefixes to be retained, and also avoids invald
+      duplicate attributes.
+
+  * Commonmark reader:
+
+    + Refactor `specFor`.
+    + Set input name to `""` to avoid clutter in sourcepos output.
+
+  * Org reader:
+
+    + Parse `#+LANGUAGE` into `lang` metadata field (#6845, Albert
+      Krewinkel).
+    + Preserve targets of spurious links (#6916, Albert
+      Krewinkel).  Links with (internal) targets that the reader doesn't
+      know about are converted into emphasized text. Information on the
+      link target is now preserved by wrapping the text in a Span of class
+      `spurious-link`, with an attribute `target` set to the link's
+      original target. This allows to recover and fix broken or unknown
+      links with filters.
+
+  * DocBook reader:
+
+    + Table text width support (#6791, Nils Carlson).
+      Table width in relation to text width is not natively supported
+      by docbook but is by the docbook `fo` stylesheets through an XML
+      processing instruction, `<?dbfo table-width="50%"?>`.
+
+  * LaTeX reader:
+
+    + Improve parsing of command options (#6869, #6873).
+      In cases where we run into trouble parsing inlines til the
+      closing `]`, e.g. quotes, we return a plain string with the
+      option contents. Previously we mistakenly included the brackets
+      in this string.
+    + Preserve center environment (#6852, Igor Pashev).
+      The contents of the `center` environment are put in a `Div`
+      with class `center`.
+    + Don't parse `\rule` with width 0 as horizontal rule. These are
+      sometimes used as spacers in LaTeX.
+    + Don't apply theorem default styling to a figure inside (#6925).
+      If we put an image in italics, then when rendering to Markdown
+      we no longer get an implicit figure.
+
+  * Dokuwiki reader:
+
+    + Handle unknown interwiki links better (#6932).
+      DokuWiki lets the user define his own Interwiki links.  Previously
+      pandoc reacted to these by emitting a google search link, which is
+      not helpful. Instead, we now just emit the full URL including the
+      wikilink prefix, e.g. `faquk>FAQ-mathml`.  This at least gives users
+      the ability to modify the links using filters.
+
+  * Markdown writer:
+
+    + Properly handle boolean values in writing YAML metadata (#6388).
+    + Ensure that a new csl-block begins on a new line (#6921).
+      This just looks better and doesn't affect the semantics.
+
+  * RST writer:
+
+    + Better image handling (#6948).  An image alone in its paragraph
+    (but not a figure) is now rendered as an independent image, with an
+    `alt` attribute if a description is supplied.  An inline image that
+    is not alone in its paragraph will be rendered, as before, using a
+    substitution.  Such an image cannot have a "center", "left", or
+    "right" alignment, so the classes `align-center`, `align-left`, or
+    `align-right` are ignored.  However, `align-top`, `align-middle`,
+    `align-bottom` will generate a corresponding `align` attribute.
+
+  * Docx writer:
+
+    + Keep raw openxml strings verbatim  (#6933, Albert Krewinkel).
+    + Use Content instead of Element.  This allows us to inject
+      raw OpenXML into the document without reparsing it into an
+      Element, which is necessary if you want to inject an open
+      tag or close tag.
+    + Fix bullets/lists indentation, so that the first level is slightly
+      indented to the right instead of right on the margin (cholonam).
+    + Support bold and italic in "complex script" (#6911).
+      Previously bold and italics didn't work properly in LTR
+      text.  This commit causes the w:bCs and w:iCs attributes
+      to be used, in addition to w:b and w:i, for bold and
+      italics respectively.
+
+  * ICML writer:
+
+    + Fix image bounding box for custom widths/heighta (Mauro Bieg, #6936).
+
+  * LaTeX writer:
+
+    + Improve table spacing (#6842, #6860).
+      Remove the `\strut` that was added at the end of minipage
+      environments in cells.  Replace `\tabularnewline` with
+      `\\ \addlinespace`.
+    + Improve calculation of column spacing (#6883).
+    + Extract table handling into separate module (Albert Krewinkel).
+    + Fix bug with nested `csl-` display Spans (#6921).
+    + Improve longtable output (#6883).  Don't create minipages for
+      regular paragraphs.  Put width and alignment information in the
+      longtable column descriptors.
+
+  * OpenDocument writer:
+
+    + Support for table width as a percentage of text width
+      (#6792, Nils Carson).
+    + Implement Div and Span ident support (#6755, Nils Carson).
+      Spans and Divs containing an ident in the Attr will become bookmarks
+      or sections with idents in OpenDocument format.
+    + Add two extensions, `xrefs_name` and `xrefs_number` (#6774, Nils
+      Carlson).  Links to headings, figures and tables inside the
+      document are substituted with cross-references that will use the
+      name or caption of the referenced item for `xrefs_name` or the
+      number for `xrefs_number`.  For the `xrefs_number` to be useful
+      heading numbers must be enabled in the generated document and
+      table and figure captions must be enabled using for example the
+      `native_numbering` extension.  In order for numbers and reference
+      text to be updated the generated document must be refreshed.
+
+  * JATS writer:
+
+    + Support advanced table features (Albert Krewinkel).
+    + Support author affiliations (#6687, Albert Krewinkel).
+
+  * Docbook writer:
+
+    + Use correct id attribute consistently (Jan Tojnar).
+      DocBook5 should always use `xml:id` instead of `id`.
+    + Handle admonition titles better (Jan Tojnar).
+      Docbook reader produces a `Div` with `title` class for `<title>`
+      element within an “admonition” element. Markdown writer then turns
+      this into a fenced div with `title` class attribute. Since fenced
+      divs are block elements, their content is recognized as a
+      paragraph by the Markdown reader. This is an issue for Docbook
+      writer because it would produce an invalid DocBook document from
+      such AST – the `<title>` element can only contain “inline”
+      elements.  Handle this special case separately by unwrapping
+      the paragraph before creating the `<title>` element.
+    + Add XML namespaces to top-level elements (#6923, Jan Tojnar).
+      Previously, we only added `xmlns` attributes to chapter
+      elements, even when running with `--top-level-division=section`.
+      These namespaces are now added to part and section elements too,
+      when they are the selected top-level divisions.
+      We do not need to add namespaces to documents produced with
+      `--standalone` flag, since those will already have xmlns attribute on
+      the root element in the template.
+
+  * HTML writer:
+
+    + Fix handling of nested `csl-` display spans (#6921).
+      Previously inner Spans used to represent CSL display attributes were
+      not rendered as div tags as intended.
+
+  * EPUB writer:
+
+    + Include title page in landmarks (#6919).
+      Note that the toc is also included if `--toc` is specified.
+    + Add frontmatter type on body element for nav.xhtml (#6918).
+
+  * EPUB templates: use preserveAspectRatio="xMidYMid" for cover image (#6895,
+    Shin Sang-jae).  This change affects both the epub2 and the epub3
+    templates.  It avoids distortion of the cover image by requiring that the
+    aspect ratio be preserved.
+
+  * LaTeX template:
+
+    + Include `csquotes` package if `csquotes` variable set.
+    + Put back `amssymb`.  We need it for checkboxes in todo lists,
+      and maybe for other things.  In this location it seems compatible
+      with the cases that prompted #6469 and PR #6762.
+    + Disable language-specific shorthands in babel (#6817, #6887).
+      Babel defines "shorthands" for some languages, and these can
+      produce unexpected results. For example, in Spanish, `1.22`
+      gets rendered as `122`, and `et~al.` as `etal`.
+      One would think that babel's `shorthands=off` option (which
+      we were using) would disable these, but it doesn't.  So we
+      remove `shorthands=off` and add some code that redefines
+      the shorthands macro.  Eventually this will be fixed in babel,
+      I hope, and we can revert to something simpler.
+
+  * JATS template: allow array of persistent institute ids in `pid`
+    (Albert Krewinkel).
+
+  * Text.Pandoc.Parsing:  minor code and efficiency improvements.
+
+  * Text.Pandoc.Extension:
+
+    + Add `Ext_sourcepos` constructor for `Extension` [API change].
+    + Add `Ext_xrefs_name` and `Ext_xrefs_number` constructors for
+      `Extension` (Nils Carson) [API change].
+
+  * Text.Pandoc.Citeproc:
+
+    + Fix truncation of `[Citation]` list in `Cite` inside footnotes (#6890).
+      This affected author-in-text citations in footnotes.  It didn't cause
+      problems for the printed output, but for filters that expected the
+      citation id and other information.
+    + Allow the use of both inline and external references (#6951),
+      as with pandoc-citeproc.  References defined in the document's
+      metadata take priority over references with the same id defined in
+      an external bibliography.
+    + Use `fetchItem` to get external bibliography (#6940).
+    + Ensure that BCP47 lang codes can be used.  We ignore the variants
+      and just use the base lang code and country code when passing off
+      to citeproc.
+    + Citeproc BibTeX parser: revert change in `getRawField`
+      which was made (for reasons forgotten) when transferring
+      this code from pandoc-citeproc.  The change led to `--` in
+      URLs being interpreted as en-dashes, which is unwanted (#6874).
+
+  * Text.Pandoc.ImageSize:
+
+    + Default to DPI 72 if the format specifies DPI of 0 (#6880).
+      This shouldn't happen, in general, but it can happen with
+      JPEGs that don't conform to the spec.  Having a DPI of 0
+      will blow up size calculations (division by 0).
+    + ImageSize: use JuicyPixels to determine size for png, jpeg, and
+      gif, instead of doing our own binary parsing (#6936). This
+      gives more reliable results.
+
+  * Text.Pandoc.CSS:
+
+    + Remove `foldOrElse` (internal module) (Albert Krewinkel).
+
+  * Use skylighting 0.10.2 (#6625).
+
+  * Use citeproc 0.3. This fixes issues with references with
+    duplicate ids (jgm/citeproc#36).
+
+  * Use doctemplates 0.9.  This fixes issues with boolean
+    metadata values in the Markdown writer (#6388)
+    and in `meta-json` (#6650).  It also fixes
+    issues with nested for loops in templates.
+
+  * Add translations zh-Hans.yaml and zh-Hant.yaml (#6904, #6909,
+    Kolen Cheung, taotieren).
+
+  * Add tests: True to cabal.project.
+    This fixes some CI failures for cabal.
+
+  * Normalize test/tables/*.native (#6888, Kolen Cheung).
+
+  * Move executable to `app` directory to avoid problems with cabal repl.
+
+  * CONTRIBUTING: add section "How can I help?" (#6892, Albert Krewinkel).
+    Also adds a paragraph aimed at highlighting the importance of feature
+    maintenance.
+
+  * MANUAL: Document that --number-sections works in `ms` (#6935).
+
+
+## pandoc 2.11.2 (2020-11-19)
+
+  * Default to using ATX (`##`-style) headings for Markdown output
+    (#6662, Aner Lucero).  Previously we used Setext (underlined) headings
+    by default for levels 1--2.
+
+  * Add option `--markdown-headings=atx|setext`, and deprecate
+    `--atx-headers` (#6662, Aner Lucero).
+
+  * Support `markdown-headings` in defaults files.
+
+  * Fix corner case in YAML metadata parsing (#6823).  Previously YAML
+    metadata would sometimes not get recognized if a field ended with a
+    newline followed by spaces.
+
+  * `--self-contained`: increase coverage (#6854).
+    Previously we only self-contained attributes for certain tag names
+    (`img`, `embed`, `video`, `input`, `audio`, `source`, `track`,
+    `section`).  Now we self-contain any occurrence of `src`,
+    `data-src`, `poster`, or `data-background-image`, on any tag; and
+    also `href` on `link` tags.
+
+  * Markdown reader:
+
+    + Fix detection of locators following in-text citations.
+      Prevously, if we had `@foo [p. 33; @bar]`, the `p. 33` would be
+      incorrectly parsed as a prefix of `@bar` rather than a suffix of
+      `@foo`.
+    + Improve period suppression algorithm for citations in notes
+      in note citation styles (#6835).
+    + Don't increment `stateNoteNumber` for example list references.
+      This helps with #6836 (a bug in which example list references
+      disturb calculation of citation note number and affect when
+      `ibid` is triggered).
+
+  * LaTeX reader:
+
+    + Move `getNextNumber` from Readers.LaTeX to Readers.LaTeX.Parsing.
+    + Fix negative numbers in siunitx commands.  A change in pandoc 2.11
+      broke negative numbers, e.g.  `\SI{-33}{\celcius}` or `\num{-3}`.
+      This fixes the regression.
+
+  * DocBook reader: drop period in formalpara title
+    and put it in a div with class `formalpara-title`, so that
+    people can reformat with filters (#6562).
+
+  * Man reader: improve handling of `.IP` (#6858).  We now better handle
+    `.IP` when it is used with non-bullet, non-numbered lists, creating a
+    definition list.  We also skip blank lines like groff itself.
+
+  * Bibtex reader: fall back on `en-US` if locale for LANG not found.
+    This reproduces earlier pandoc-citeproc behavior (jgm/citeproc#26).
+
+  * JATS writer:
+
+    + Wrap all tables (Albert Krewinkel).
+      All `<table>` elements are put inside `<table-wrap>` elements, as the
+      former are not valid as immediate child elements of `<body>`.
+    + Move Table handling to separate module (Albert Krewinkel).
+      Adds two new unexported modules:
+      Text.Pandoc.Writers.JATS.Types, Text.Pandoc.Writers.JATS.Table.
+
+  * Org writer:
+
+    + Replace org #+KEYWORDS with #+keywords (TEC).
+      As of ~2 years ago, lower case keywords became the standard (though
+      they are handled case insensitive, as always).
+    + Update org supported languages and identifiers according to the
+      current list contained in
+      <https://orgmode.org/worg/org-contrib/babel/languages/index.html>
+      (TEC).
+
+  * Only use `filterIpynbOutput` if input format is ipynb (#6841).
+    Before this change content could go missing from divs with class
+    `output`, even when non-ipynb was being converted.
+
+  * When checking reader/writer name, check base name now that we permit
+    extensions on formats other than markdown.
+
+  * Text.Pandoc.PDF: Fix `changePathSeparators` for Windows (#6173).
+    Previously a path beginning with a drive, like `C:\foo\bar`, was
+    translated to `C:\/foo/bar`, which caused problems.
+    With this fix, the backslashes are removed.
+
+  * Text.Pandoc.Logging:
+
+    + Add constructor `ATXHeadingInLHS` to `LogMessage` [API change].
+    + Add constructor `EnvironmentVariableUndefined` to
+      `LogMessage` [API change].
+
+  * Fix error that is given when people specify `doc` output (#6834,
+    gison93).
+
+  * LaTeX template:  add a `\break` after parbox in `CSLRightInline`.
+    This should fix spacing problems between entries with numeric styles.
+    Also fix number of params on `CSLReferences`.
+
+  * reveal.js template: Put quotes around `controlsLayout`,
+    `controlsBackArrows`, and `display`, since these require strings.
+    Add `showSlideNumber`, `hashOneBasedIndex`, `pause`.
+
+  * Use citeproc 0.2.  This fixes a bug with title case around parentheses.
+
+  * pandoc.cabal: remove 'static' flag.
+    This isn't really necessary and can be misleading (e.g. on macOS,
+    where a fully static build isn't possible). cabal's new option
+    `--enable-executable-static` does the same. On stack you can add
+    something like this to the options for your executable in package.yaml:
+
+        ld-options: -static -pthread
+
+  * Remove obsolete bibutils flag setting in `linux/make_artifacts.sh`.
+
+  * Manual:
+
+    + Correct `link-citation` -> `link-citations`.
+    + Add a sentence about `pagetitle` for HTML (#6843, Alex Toldaiev).
+
+  * INSTALL.md: Remove references to `pandoc-citeproc` (#6857).
+
+  * CONTRIBUTING: describe hlint and how it's used (#6840, Albert
+    Krewinkel).
+
+## pandoc 2.11.1.1 (2020-11-07)
+
+  * Citeproc: improve punctuation in in-text note citations (#6813).
+    Previously in-text note citations inside a footnote would sometimes have
+    the final period stripped, even if it was needed (e.g. on the end of
+    'ibid').
+
+  * Use citeproc 0.1.1.1.  This improves the decision about when
+    to use `ibid` in cases where citations are used inside
+    a footnote (#6813).
+
+  * Support `nocase` spans for `csljson` output.
+
+  * Require latest commonmark, commonmark-extensions.
+    This fixes a bug with `autolink_bare_uris` and commonmark.
+
+  * LaTeX reader: better handling of `\\` inside math in table cells (#6811).
+
+  * DokuWiki writer:  translate language names for code elements
+    and improve whitespace (#6807).
+
+  * MediaWiki writer: use `syntaxhighlight` tag instead of deprecated
+    `source` for highlighted code (#6810).  Also support `startFrom`
+    attribute and `numberLines`.
+
+  * Lint code in PRs and when committing to master (#6790,
+    Albert Krewinkel).
+
+  * doc/filters.md: describe technical details of filter invocations (#6815,
+    Albert Krewinkel).
+
+
+## pandoc 2.11.1 (2020-11-03)
+
+  * DocBook Reader: fix duplicate bibliography bug (#6773, Nils Carlson).
+
+  * HTML reader:
+
+    + Parse contents of iframes (#6770).
+    + Parse inline svg as image unless `raw_html` is set in the reader (in
+      which case the svg is passed through as raw HTML) (#6770).
+
+  * LaTeX reader:
+
+    + Fix bug parsing macro arguments (#6796).  If `\cL` is
+      defined as `\mathcal{L}`, and `\til` as `\tilde{#1}`, then
+      `\til\cL` should expand to `\tilde{\mathcal{L}}`, but
+      pandoc was expanding it to `\tilde\mathcal{L}`.  This is
+      fixed by parsing the arguments in "verbatim mode" when the
+      macro expands arguments at the point of use.
+    + Properly support optional (cite) argument for
+      `\blockquote` from `csquotes` (#6802).
+
+  * LaTeX writer: Improved calculation of table column widths.
+    We now have LaTeX do the calculation, using `\tabcolsep`.
+    So we should now have accurate relative column widths no
+    matter what the text width.  The default template has been modified to load
+    the calc package if tables are used.
+
+  * HTML writer: Fix duplicate "class" attribute for table
+    rows (Andy Morris).
+
+  * Text.Pandoc.Filter: allow shorter YAML representation of Citeproc
+    (Albert Krewinkel).  The map-based YAML representation of filters expects
+    `type` and `path` fields. The path field had to be present for all filter
+    types, but is not used for citeproc filters. The field can now be omitted
+    when type is "citeproc", as described in the MANUAL.
+
+  * Text.Pandoc.Error: Add `PandocBibliographyError` constructor
+    for `PandocError` [API change].  This ensures that bibliography parsing
+    errors generate messages that include the bibliography file name --
+    otherwise it can be quite mysterious where it is coming from.
+
+  * Citeproc: properly handle `csl` field with `data:` URI (#6783).
+    This is used with the JATS writer, so this fixes a regression
+    in pandoc 2.11 with JATS output and citeproc.
+
+  * Allow `citation-abbreviations` in defaults file.
+
+  * JATS templates: ensure `jats_publishing` output is valid
+    (Albert Krewinkel).
+
+  * LaTeX template:  Fix `CSLRightInline`, so that it does not
+    run over the right margin.
+
+  * HTML template: default CSS tweaks (Mauro Bieg and John
+    MacFarlane).
+
+    - Fix margin before codeblock
+    - Add `monobackgroundcolor` variable, making the background color
+      and padding of code optional.
+    - Ensure that backgrounds from highlighting styles take precedence over
+      monobackgroundcolor
+    - Remove list markers from TOC
+    - Add margin-bottom where needed
+    - Remove italics from blockquote styling
+    - Change borders and spacing in tables to be more consistent with other
+       output formats
+    - Style h5, h6
+    - Set font-size for print media to 12pt.
+    - Reduce interline space.
+    - Reduce interparagraph space.
+    - Reduce line width.
+    - Remove the special `line-height: 1` for table cells.
+    - Remove the special line-height for pre.
+    - Ensure that there is a bit more space before a heading
+      than after.
+    - Slightly reduced space after title header.
+    - Add CSS example to MANUAL
+
+  * man template:  Change comment that triggers `tbl` from
+    `.\"t` to `'\" t`, as specified in groff_man(7) (#6803).
+
+  * Use latest commonmark, commonmark-extensions.
+    This fixes a bug with nested blocks in footnotes with the
+    `footnote` extension to `commonmark`.  See jgm/commonmark-hs#63.
+
+  * Citeproc: use comma for in-text citations inside footnotes.
+    When an author-in-text citation like `@foo` occurs in a footnote,
+    we now render it with:  `AUTHOR NAME + COMMA + SPACE + REST`.
+    Previously we rendered: `AUTHOR NAME + SPACE + "(" + REST + ")"`.
+    This gives better results.  Note that normal citations are still
+    rendered in parentheses.
+
+  * Use latest citeproc:
+
+    + citeproc no longer capitalizes notes, so we do it
+      in pandoc when appropriate.
+    + Closes #6783.
+
+  * Clarify manual on `--track-changes` (#6801).
+
+  * Add `doc/jats.md` to document pandoc's handling of JATS
+    (#6794, Albert Krewinkel).
+
+  * Fix code example in lua-filters.md (#6795).
+
+## pandoc 2.11.0.4 (2020-10-21)
+
+  * Commonmark writer: fix regression with fenced divs (#6768).
+    Starting with 2.10.1, fenced divs no longer render with
+    HTML div tags in commonmark output.  This is a regression
+    due to our transition from cmark-gfm.  This commit fixes it.
+
+  * Use released version of citeproc.  (This fixes a mis-step
+    in the 2.11.0.3 release, which is now deprecated.)
+
+  * Use latest sylighting, with support for `groovy`.
+
+  * Document that --html-q-tags requires the smart extension on the reader
+    (#6766).
+
+## pandoc 2.11.0.3 (2020-10-20)
+
+  * Use latest citeproc (closes #6765). This fixes a problem with
+    author-in-text citations for references including both an author
+    and an editor. Previously, both were included in the text, but only
+    the author should be.
+
+  * With `--citeproc`, ensure that the final period is removed when
+    citations that occur in notes in note-based styles get put in
+    parentheses.  See jgm/citeproc#20.
+
+  * Normalize rewritten image paths with `--extract-media` (#6761).
+    This change will avoid mixed paths like this one when
+    `--extract-media` is used with a Word file:
+    `![](C:\Git\TIJ4\Markdown/media/image30.wmf)`.  Instead we'll get
+    `![](C:\Git\TIJ4\Markdown`media`image30.wmf)`.
+
+  * Modify `--version` output.  Use space more efficiently and report the
+    citeproc and ipynb versions, along with skylighting, texmath, and
+    pandoc-types.  Drop the word "default" before "user data directory."
+
+  * DocBook reader: bibliomisc and anchor support (#6754, Nils Carlson).
+    Also ensure that bibliodiv without a title no longer results in
+    an empty Header.
+
+  * ConTeXt template: adds `\setupinterlinespace` to fonts larger
+    than normal (#6763, Denis Maier).
+
+  * LaTeX template: Do not load amssymb if not needed (#6469, Angelo Peronio).
+    See <https://tex.stackexchange.com/a/549938>.
+
+  * Relax upper bound on hslua, allow hslua-1.3.* (Albert Krewinkel).
+
+  * MANUAL:
+
+    + Improve explanation of "indent" variable (#6767, Cyrus Yip).
+    + Remove org from list of input formats supporting raw_tex (#6753,
+      Nick Fleisher).
+
+
+## pandoc 2.11.0.2 (2020-10-15)
+
+  * Fix handling of `xdata` in bibtex/biblatex bibliographies (#6752).
+
+  * Fix some small typos in the API documentation (#6751, Michael Hoffmann).
+
+  * Require citeproc 0.1.0.2.  This fixes a regression from pandoc-citeproc
+    involving spacing between components of a reference in certain styles
+    (e.g. `cell.csl`).
+
+  * Fix typos in comments, doc strings, error messages, and tests
+    (Albert Krewinkel, #6738).
+
+## pandoc 2.11.0.1 (2020-10-13)
+
+  * LaTeX reader: support more acronym commands (#6746):
+    `\acl`, `\aclp`, and capitalized versions of already
+    supported commands.
+
+  * Commonmark reader: add `pipe_table` extension *after* defaults (#6739).
+    Otherwise we get bad results for non-table, non-paragraph
+    lines containing pipe characters.
+
+  * Markdown writer: Fix autolinks rendering for gfm (#6740).
+    Previously, autolinks rendered as raw HTML, due to the
+    `class="uri"` added by pandoc's markdown reader.
+
+  * LaTeX writer:
+
+    + Escape option values in lstlistings environment (#6742).
+    + Fix handling of `lang` `pt-BR` (#2953).  For polyglossia we now
+      use `\setmainlanguage[variant=brazilian]{portuguese}` and for babel
+      `\usepackage[shorthands=off,main=brazilian]{babel}`.
+
+  * Depend on latest citeproc (0.1.0.1).
+
+    + This fixes the citation number issue with ieee.csl and other
+      styles that do not explicitly sort bibliographies (#6741). (Pandoc
+      was numbering them by their order in the bibliography file,
+      rather than the order cited, as required by the CSL spec.)
+    + Fixes groupin/collapsing with citation items with prefixes.
+
+  * default.latex: fix `CSLReference` macro definition.
+
+  * Fix MANUAL.txt CSL JSON conversion examples.
+
+  * Fix spelling errors in changelog, MANUAL.txt, `doc/org.md` (#6738).
+
+
+## pandoc 2.11 (2020-10-11)
+
+  * Add `--citeproc` (`-C`) option to trigger built-in citation processing.
+    It is no longer necessary to use the external `pandoc-citeproc`
+    filter.  `--citeproc` behaves like a filter and can be positioned
+    relative to other filters as they appear on the command line.
+
+    The new built-in citation processing uses the citeproc library,
+    a reimplementation of CSL citation processing that fixes many
+    of the shortcomings of pandoc-citeproc.  In general, citation
+    processing should work much the same as it did with pandoc-citeproc,
+    but with greater fidelity to CSL styles and better performance.
+    (The tests from the pandoc-citeproc package have been carried
+    over to pandoc.) The following differences should be noted:
+
+    - At this point, only some of the writers (HTML, ms, LaTeX) properly
+      interpret CSL display styles.  You should get decent output in
+      all formats (at least as good as with pandoc-citeproc), but
+      indentation and block-alignment may not be right.
+
+    - pandoc-citeproc searches the `~/.csl` directory for `.csl`
+      styles.  Pandoc instead searches the `csl` subdirectory of
+      the pandoc user data directory (e.g., `~/.pandoc/csl` or
+      `~/.local/share/pandoc/csl`).  Users who already keep
+      CSL styles in `~/.csl` may find it convenient to add a
+      symlink.
+
+    - Some of the bibliography formats supported by pandoc-citeproc (via
+      hs-bibutils) are no longer supported:  Copac, EndNote,
+      ISI, MEDLINE, MODS, and RIS.  If you use one of these formats,
+      you may use the `bibutils` utility to convert to BibLaTeX.
+      We now support only BibTeX, BibLaTeX, CSL JSON,
+      and pandoc's YAML/Markdown analogue of CSL JSON.
+
+    - pandoc-citeproc would always retrieve the independent parent
+      of a dependent style by doing an HTTP request.  pandoc will
+      now first seek the independent parent locally (in the resource
+      path or in the `csl` subdirectory of the pandoc user data
+      directory) before resorting to HTTP.  In addition, you may
+      omit the `.csl` extension, e.g. `--csl zoology`.
+
+    - Using the `--bibliography` option (or including
+      `bibliography` in YAML metadata) no longer triggers
+      citation processing implicitly: one must always use the
+      `--citeproc` option if citation processing is wanted.
+
+  * Add `csljson` as and input and output format. This allows pandoc
+    to convert between `csljson` and other bibliography formats
+    (e.g. `-f csljson -t markdown -s` or `-f bibtex -t csljson`),
+    and to generate formatted versions of CSL JSON bibliographies
+    (e.g., `pandoc -f csljson --citeproc pl.json -o pl.pdf`).
+
+  * Added `bibtex`, `biblatex` as input formats.  This allows pandoc
+    to convert between BibLaTeX and BibTeX and other bibliography formats,
+    and to generated formatted versions of BibTeX/BibLaTeX bibliographies
+    (e.g., `pandoc -f biblatex --citeproc pl.bib -o pl.pdf`).
+
+  * Raise informative errors when YAML metadata parsing fails (#6730).
+    Previously the command would succeed, returning empty metadata,
+    with no errors or warnings.
+
+  * Sort languages in `--list-highlight-languages` output (#6718,
+    Albert Krewinkel).  Languages were previously sorted by their
+    long name, which leads to unexpected results).
+
+  * Add CSS to default HTML template (#6601, Mauro Bieg).  This
+    greatly improves the default typography in pandoc's HTML
+    output.  The CSS is sensitive to a number of variables
+    (e.g. `mainfont`, `fontsize`, `linestretch`): see the manual for
+    details. To restore the earlier, more spartan output, you can
+    disable this with `-M document-css=false`.
+
+  * Support `--toc-depth` option for ODT writer (#6696, niszet).
+
+  * Fix issues with Windows UNC paths with some options (#5127).
+
+  * Remove `fenced_code_blocks` and `backtick_code_blocks` from allowed
+    `commonmark` and `gfm` extensions.  These shouldn't really be counted
+    as extensions, because they can't be disabled in commonmark.
+    Adjust markdown writer to check for the commonmark variant in addition
+    to extensions.
+
+  * Add these extensions to `gfm` and `commonmark`:
+    `fenced_code_blocks`, `backtick_code_blocks`, `fenced_code_attributes`.
+    These can't really be disabled in the reader, but they need to be enabled
+    in the writer or we just get indented code.
+
+  * Make sure proper set of extensions is recognized for `commonmark_x`.
+
+  * Allow `gfm_auto_identifiers`, `ascii_identifiers` extensions for `docx`.
+
+  * Markdown reader:
+
+    + Add `Maybe FilePath` parameter to `yamlToMeta` [API change].
+    + Export `yamlToRefs` [API change], a version of `yamlToMeta`
+      specialized to references.
+    + Set `citationNoteNum` accurately in citations.
+    + Revise abbreviation support.  Don't insert a nonbreaking space after a
+      potential abbreviation if it comes right before a note or citation.
+      This causes problems for citeproc's moving of note citations.
+
+  * LaTeX reader:
+
+    + Support missing siunitx commands (#6658).
+    + Support `squared`, `cubed`, `tothe` in siunitx (#6657).
+    + Improved uncertainty handling in slunitx.
+    + Factored out siunitx stuff into separate unexposed module.
+    + Fix improper empty cell filtering (#6689, Christian Despres).
+    + Fix parsing of "show name" in `\newtheorem` (#6734).
+      Previously we were just treating it as a string and
+      ignoring  accents and formatting.
+    + Prevent wrong nesting of `\multirow` and `\multicolumn` table
+      cells (#6603, Laurent P. René de Cotret).
+    + Table cell parser not consuming spaces correctly (#6596,
+      Laurent P. René de Cotret).
+    + Change `SIRange` to `SIrange` (#6617, Emerson Harkin).
+    + Allow blank lines inside `\author` (#6324).
+
+  * DocBook reader:
+
+    + Don't squelch space at end of emphasis and other inline elements;
+      instead, move it outside the element (#6719).
+    + Implement table cell alignment (#6698, Nils Carlson).
+    + Implement column span support for tables (#6492, Nils Carlson).
+    + Update list of block level tags (#6610).
+
+
+  * JATS reader:
+
+    + Don't squelch space at end of emphasis and other inline elements;
+      instead, move it outside the element (#6719).
+
+  * RST reader:
+
+    + Apply `.. class::` directly to following Header rather than creating
+      a surrounding Div (#6699).
+
+  * Docx reader:
+
+    + Allow empty dates in comments and tracked changes (#6726, Diego
+      Balseiro).
+
+  * Markdown writer:
+
+    + Be less aggressive about using quotes for YAML values,
+      allowing e.g. a quotation mark or bracket as long as it's not at the
+      beginning of the line.
+    + Use double quotes for YAML metadata (#6727).
+    + Sort YAML metadata keys in Markdown output case-insensitive.
+
+
+  * Asciidoc writer:
+
+    + Support asciidoctor's block figures (#6538, argent0).
+
+  * LaTeX writer:
+
+    + Fix spacing issue with list in definition list.
+      When a list occurs at the beginning of a definition list definition,
+      it can start on the same line as the label, which looks bad.
+      Fix that by starting such lists with an `\item[]`.
+
+  * HTML writer:
+
+    + Support intermediate table headers (#5314, Albert Krewinkel).
+    + Support attributes on all table elements (Albert Krewinkel).
+    + Render table footers if present (#6314, Albert Krewinkel).
+    + Fix addition of `doc-biblioentry` role.
+    + Support colspans and rowspans in HTML tables (#6312, Albert Krewinkel).
+
+  * ICML writer:
+
+    + Support internal document links (#5541, Leonard Rosenthol).
+    + Changed default link state to invisible (#6676, Leonard Rosenthol).
+
+  * Docx writer:
+
+    + Better handle list items whose contents are lists (#5948, Michael
+      Hoffmann).  If the first element of a bulleted or ordered list is
+      another list, then that first item would previously disappear if the
+      target format is docx.
+    + Separate adjacent tables (#4315).  Word combines adjacent tables,
+      so to prevent this we insert an empty paragraph between two
+      adjacent tables.
+
+  * Org writer:
+
+    + Don't force blank line after headings (#6554).
+
+  * OpenDocument writer:
+
+    + Implement table cell alignment (#6700 Nils Carson, Mauro Bieg).
+    + New table cell support with row and column spans (#6682, Nils Carson).
+    + Syntax highlighting for inline code (#6711, niszet).
+
+  * Add Text.Pandoc.Citeproc module, exporting `processCitations`
+    [API change].  This depends on several other, unexported
+    modules under Text.Pandoc.Citeproc.
+
+  * Add module Text.Pandoc.Writers.CslJson, exporting `writeCslJson`.
+    [API change]
+
+  * Add module Text.Pandoc.Readers.CslJson, exporting `readCslJson`.
+    [API change]
+
+  * Add module Text.Pandoc.Readers.BibTeX, exporting `readBibTeX` and
+    `readBibLaTeX`. [API change]
+
+  * Text.Pandoc.Filter: Add `CiteprocFilter` constructor to Filter.
+    [API change] This runs the processCitations transformation.
+    We need to treat it like a filter so it can be placed
+    in the sequence of filter runs (after some, before others).
+    In FromYAML, this is parsed from `citeproc` or `{type: citeproc}`,
+    so this special filter may be specified either way in a defaults file
+    (or by `citeproc: true`, though this gives no control of positioning
+    relative to other filters).
+
+  * Add new exported module Text.Pandoc.Writers.AnnotatedTable [API change]
+    (#6655, Christian Despres).  This module (which should generally
+    be imported qualified to avoid name conflicts) provides a
+    `Table` type that mirrors the structure of a pandoc `Table`,
+    but with added inferred information so that the writers do not have to
+    lay out tables themselves. The `toTable` and `fromTable` functions convert
+    between an annotated `Table` and a regular pandoc `Table`. In addition to
+    producing a `Table` with coherent and well-formed annotations, the
+    `toTable` function also normalizes its input table like the table
+    builder does.  Tests ensure that `toTable` normalizes tables exactly
+    like the table builder, and that its annotations are coherent.
+
+  * Text.Pandoc.Logging:
+
+    + Remove unused `CouldNotParseYamlMetadata` constructor for `LogMessage`
+      [API change].
+    + Add `CiteprocWarning` constructor to `LogMessage` [API change].
+
+  * Text.Pandoc.Readers.Metadata: export `yamlBsToRefs` [API change].
+    These allow specifying an id filter so we parse only references
+    that are used in the document.
+
+  * Text.Pandoc.Parsing:
+
+    + Export ParseError [API change].
+    + Add `stateInNote` and `stateNoteNumber` to `ParserState`
+      [API change].  These are used to populate note numbers for citation
+      processing.
+
+  * Fix apparent typos in sample.lua (#6729, William Lupton).
+    Also make the writer less aggressive in escaping quotes.
+
+  * Text.Pandoc.Options:
+
+    + `defaultMathJaxURL`: use `tex-chtml-full` instead of `tex-mml-chtml`
+      (#6599, Kolen Cheung).  This drops the MathML support (which we
+      don't need for HTML math rendering) and includes the full JavaScript,
+      which makes it possible to use `--self-contained` (though there may
+      still be issues if the required math fonts aren't available).  This
+      change should also reduce latency in pages with lots of formulas.
+    + Add `/tex-chtml-full.js` to `defaultMathJaxURL` (#6593) Previously we
+      added this in processing command line options, but not in processing
+      defaults files, which was inconsistent.
+
+  * epub.css: Fix cover page selectors and add note explaining their use
+    (#6649, a-vrma).
+
+  * Add data files needed for Text.Pandoc.Citeproc:  these include
+    `default.csl` in the data directory and a `citeproc` directory that
+    is only used at compile-time for biblatex localizations.  Note that we've
+    added `file-embed` as a mandatory rather than a conditional
+    dependency, because of the biblatex localization files.
+
+  * Lua filters:
+
+    + Add SimpleTable for backwards compatibility (#6575, Albert Krewinkel).
+      A new type `SimpleTable` is made available to Lua filters. It is
+      similar to the `Table` type in pandoc versions before 2.10;
+      conversion functions from and to the new Table type are provided.
+      Old filters using tables now require minimal changes and can use, e.g.,
+
+          if PANDOC_VERSION > {2,10,1} then
+            pandoc.Table = pandoc.SimpleTable
+          end
+
+      and
+
+          function Table (tbl)
+            tbl = pandoc.utils.to_simple_table(tbl)
+            …
+            return pandoc.utils.from_simple_table(tbl)
+          end
+
+      to work with the current pandoc version.
+
+    + Make `attr` argument optional in `Table` constructor (Albert Krewinkel).
+      This changes the Lua API. It is highly unlikely for this change to affect
+      existing filters, since the documentation for the new Table constructor
+      (and type) was incomplete and partly wrong before.  The Lua API is now
+      more consistent, as all constructors for elements with attributes now
+      take attributes as the last parameter.
+
+  * MANUAL.txt:
+
+    * Add a dedicated Citations section which consolidates the information
+      the manual used to contain about citation processing, and incorporates
+      some information formerly found in the pandoc-citeproc man page.
+    + Add note about lualatex using `selnolig`.
+    + Remove duplicate `seriespage` (#6568, Blake Eryx).
+    + Remove lists of support extensions for markdown variants (#6604).
+      Instead, offer the advice to use `--list-extensions=FORMAT`.
+    + Fix position of attributes in header (Albert Krewinkel).
+    + Delete obsolete section on compact and loose lists (#6684).
+
+
+  * doc/lua-filters.md:
+
+    + Add info on how to debug Lua filters (#6732, Ian Max Andolina).
+    + Document Underline type and constructor (Albert Krewinkel).
+    + Document `body` field (Albert Krewinkel).
+    + Add missing header attribute
+    + Add missing Link.title field (Albert Krewinkel).
+    + Make the setting-the-date example conditional (the-solipsist).
+      This makes the example a bit more realistic.
+    + Remove outdated link table example.
+
+  * doc/org.md:
+
+    + Add section on tables (Albert Krewinkel).
+    + Add section on handling of unknown directives (Albert Krewinkel).
+
+  * CONTRIBUTING.md: fix typo (#6584, Dmitry Volodin).
+
+  * Use golden test framework for command tests.  This means that
+    `--accept` can be used to update expected output.
+
+  * Use the `smart` extension when generating pandoc's man page (#6613).
+
+  * Release-candidate: don't build windows i386.
+    So far we haven't been able to figure out how to get
+    stack to use a 32-bit ghc.
+
+  * Use `null` instead of deprecated `Builder.isNull`.
+
+  * Makefile:
+
+    + Fix macospkg target to fetch target from S3 artifacts.
+    + Fix pandoc-templates target to include all partials.
+
+  * Remove duplicated dependency in pandoc.cabal (#6591, Felix Yan).
+
+  * Sort build depends in pandoc.cabal alphabetically (#6691,
+    Albert Krewinkel).
+
+  * Add .travis.yml for macos release candidate build (#6622).
+    We need to build the release candidate on Travis rather
+    than GitHub actions, because GH has macos 10.15, and
+    binaries compiled on that OS will not work with 10.13.
+    This build is only triggered on `rc/*` branches.
+
+  * Remove instructions for building pandoc-citeproc from CI and
+    release binary build instructions.  We will no longer distribute
+    pandoc-citeproc.
+
+  * Fix math rendering in trypandoc (this broke after
+    commit d8ad766d17603784b86fc5c2e1b22864125d04d1).
+
+  * Use latest versions of skylighting, commonmark (#6589),
+    comonmark-extensions, commonmark-pandoc, texmath.
+
+  * Relax version bounds for hslua, hslua-module-text, bytestring.
+
+  * Use released pandoc-types 1.22.  This changes the JSON
+    encoding slightly for the new table types introduced
+    in 1.21, so they're more consistent with the rest.
+    Developers of libraries for pandoc filters will want
+    to take note.
+
+  * Fix hlint suggestions, update hlint.yaml (#6680, Christian Despres).
+
+  * Code cleanup (#6678, Joseph C. Sible).
+
+  * Add haddocks to functions in Text.Pandoc.Writers.Shared (Albert
+    Krewinkel).
+
+  * Remove duplicate `tshow` definition.
+
+  * Linux release candidate build: use ghc-musl container.  This simplifies
+    our build process (over using a customized alpine container).
+
+
+## pandoc 2.10.1 (2020-07-23)
+
+  * Add `commonmark_x` output format. This is `commonmark` with a number
+    of useful pandoc extensions enabled.
+
+  * Many more extensions now work with `commonmark` and `gfm`.
+
+  * Add generic `attributes` extension.  This allows attributes to
+    be added to any block or inline element in a uniform way.  Since
+    the Pandoc AST doesn't include attributes on each element type,
+    the attributes will sometimes be added by creating a surrounding
+    Div or Span container.  Currently this extension is only
+    compatible with the `commonmark` and `gfm` readers.
+
+    To add an attribute to a block-level element, e.g. a paragraph,
+    put it before the block:
+    ```
+    {#mypara}
+    This is a paragraph.
+    ```
+    Multiple attributes may be used and will be combined:
+    ```
+    {#mypara}
+    {.blue .warning key="val"}
+    This is a paragraph.
+    ```
+    To add an attribute to an inline-level element, put it
+    immediately after the element:
+    ```
+    *emphasized text*{.special}
+    ```
+
+  * Support `--number-sections` for docx output (#1413).
+
+  * LaTeX reader:
+
+    + Support `\SIRange` reader (#6418, Emerson Harkin).
+    + Support table col-span and row-span (#6311, Laurent P. René de Cotret).
+      Supports `\multirow` and `\multicolumn`.
+    + Support amsthm:  `\newtheorem`, `\theoremstyle`, and theorem and
+      proof environments, including labels and references.  The only thing
+      that is unsupported is the second optional argument, which causes
+      numbering to be reset after the specified series is incremented.
+    + Moved some code to T.P.LaTeX.Parsing.  We need to reduce the size
+      of the LaTeX reader to ease compilation on resource-limited systems.
+
+  * RST reader:
+
+    + Fix csv tables with multiline cells (#6549).
+    + Fix spurious newlines in some attributes from directives.
+    + Avoid extra newline in included code blocks.
+
+  * Commonmark reader:
+
+    + Switch from cmark-gfm to commonmark-hs for commonmark and gfm
+      parsing.  This avoids depending on a C library
+      and allows us to support more pandoc extensions for
+      `commonmark` and `gfm`.
+
+  * DocBook reader:
+
+    + Parse releaseinfo as metadata (#6542).
+
+  * Docx reader:
+
+    + Only use `bCs/iCs` on runs with `rtl` or `cs` property (#6514, Nikolay
+      Yakimov).
+    + Code cleanup/refactoring (Nikolay Yakimov).
+
+  * Org reader (Albert Krewinkel):
+
+    + Respect export setting which disables entities
+      MathML-like entities, e.g., `\alpha`, can be disabled with the
+      `#+OPTION: e:nil` export setting (Albert Krewinkel).
+    + Respect export setting disabling footnotes.  Footnotes can be removed
+      from the final document with the `#+OPTION: f:nil` export setting.
+    + Respect tables-excluding export setting.  Tables can be removed from
+      the final document with the `#+OPTION: |:nil` export setting.
+
+  * Markdown writer:
+
+    + Move `asciify` out of `escapeString`.  Otherwise `unsmartify`
+      doesn't catch quotes that have already been turned to entities.
+    + Add `writeCommonmark` (new exported function, API change).
+    + Use unicode super/subscript characters when possible if the
+      `superscript` or `subscript` extension or `raw_html` aren't available.
+    + Render caption as following paragraph when `table_caption` extension
+      is not enabled.
+    + Use numerical labels for reference links that are longer
+      than 999 characters or contain square brackets, for conformity
+      with commonmark (#6560).
+
+  * Commonmark writer:
+
+    + Instead of using cmark-gfm, use `writeCommonmark` from the
+      Markdown writer.  This function calls the markdown writer
+      with appropriate extensions and a few small modifications
+      (e.g. not requiring backslashes before spaces inside
+      super/subscripts).  With this change `comonmark` and
+      `gfm` output can be used with a wider selection of
+      extensions.
+
+  * Jira writer: keep image caption as alt attribute (#6529, Albert
+    Krewinkel).
+
+  * HTML writer:
+
+    + Improve alt-text/caption handling for HTML5 (#6491, Albert Krewinkel).
+      Screen readers read an image's `alt` attribute and the figure caption,
+      both of which come from the same source in pandoc. The figure caption is
+      hidden from screen readers with the `aria-hidden` attribute. This
+      improves accessibility.  For HTML4, where `aria-hidden` is not allowed,
+      pandoc still uses an empty `alt` attribute to avoid duplicate contents.
+
+  * Ms writer:
+
+    + Fix code highlighting with blank lines.  Previously blank lines
+      were simply omitted from highlighted code.
+    + Escape starting periods in ms writer code blocks (#6505, Michael
+      Hoffmann).  If a line of ms code block output starts with a period (.),
+      it should be prepended by `\&` so that it is not interpreted as a roff
+      command.
+
+  * Text.Pandoc.Extensions:
+
+    + Add `raw_markdown` extension (which only affects `ipynb`
+      input).
+    + Trim down `githubMarkdownExtensions`.
+      Previously it included all of the following, which make
+      sense for the legacy `markdown_github` but not for `gfm`,
+      since they are part of base commonmark and thus
+      can't be turned off in `gfm`:
+
+      - `Ext_all_symbols_escapable`
+      - `Ext_backtick_code_blocks`
+      - `Ext_fenced_code_blocks`
+      - `Ext_space_in_atx_header`
+      - `Ext_intraword_underscores`
+      - `Ext_lists_without_preceding_blankline`
+      - `Ext_shortcut_reference_links`
+
+      These have been removed from `githubMarkdownExtensions`, though
+      they're still turned on for legacy `markdown_github`.
+    + Add `Ext_attributes` constructor for `Extension` [API change].
+
+  * LaTeX template: use selnolig to selectively suppress ligatures with
+    lualatex (#6534).
+
+  * Benchmark bytestring readers (Nikolay Yakimov).
+
+  * Documentation:
+
+    + Update using-the-pandoc-api.md (favonia).
+    + Fix Typos in lua-filters.md (tajmone).
+    + Rewrite Raw HTML/TeX section in MANUAL.txt to avoid duplicate
+      headings for the extensions.
+    + Fix typo in MANUAL.txt (Benjamin Wuethrich).
+    + Remove duplicate 'titlepage' in MANUAL.txt (Blake Eryx).
+    + CONTRIBUTING.md: Advertise the official nightlies in GitHub actions.
+      Replaces #6500, thanks to @ickc.
+
+
+
+## pandoc 2.10 (2020-06-29)
+
+  * Use pandoc-types 1.21.  This adds two things:
+
+    + A native Underline constructor for Inline (#6277, Vaibhav Sagar).
+    + More expressive types for tables (#1024, Christian Despres).
+      Tables can now take attributes; and rowspans and colspans,
+      column headers, multiple row headers, table head and foot
+      can all be represented.  (Note, however, that reader and
+      writer support for these features is still lacking, so
+      most users won't see any differences in table conversion
+      yet.  These changes just lay the foundation for further
+      improvements.)
+
+  * Support new Underline element in readers and writers (#6277,
+    Vaibhav Sagar).
+
+  * Support new Table type (Christian Despres).
+    The Builder.simpleTable now only adds a row to the TableHead
+    when the given header row is not null. This uncovered an
+    inconsistency in the readers: some would unconditionally
+    emit a header filled with empty cells, even if the header
+    was not present. Now every reader has the conditional
+    behaviour.  Only the XWiki writer depended on the header row
+    being always present; it now pads its head as necessary.
+
+  * Add an option to disable certificate validation (#6156, Cédric Couralet,
+    Cécile Chemin, Juliette Fourcot).  This commit adds the option
+    `--no-check-certificate`, which disables certificate checking when
+    resources are fetched by HTTP.
+
+  * Unify defaults and markdown metadata parsers (#6328, Nikolay
+    Yakimov). Clean up code in Text.Pandoc.Readers.Metadata and
+    properly handle errors in `yamlToMeta`.  This fixes parsing
+    of Boolean fields in metadata withinin defaults files and reduces
+    code duplication.
+
+  * Docbook reader:
+
+    + Implement `<procedure>` (#6442, Mathieu Boespflug).
+    + Implement `<phrase>` (#6438, Mathieu Boespflug).
+    + Treat envar and systemitem like code (#6435, Mathieu Boespflug).
+    + Implement `<replaceable>` (#6437, Mathieu Boespflug)
+    + Map `<simplesect>` to unnumbered section (#6436, Mathieu Boespflug).
+
+  * JATS reader:
+
+    + Handle "label" element in section title (#6288).
+    + Parse abstract element into metadata field of same name
+      (#6480, Albert Krewinkel).
+
+  * Jira reader (Albert Krewinkel):
+
+    + Resolve multiple parsing problems, including issues with empty
+      table cells, faulty recognition of closing emphasis characters, and
+      parsing of image attributes (#6212, #6219, #6220).
+    + Two consecutive markup chars are now parsed verbatim (#6343);
+      styled text must not be empty.
+    + Newlines are no longer allowed within styled text (#6325).
+    + Links to anchors are now parsed as links (#6407).
+    + Retain image attributes (#6234).  Jira images attributes as in
+      `!image.jpg|align=right!` are retained as key-value pairs. Thumbnail
+      images, such as `!example.gif|thumbnail!`, are marked by a
+      `thumbnail` class in their attributes.
+    + Use Underline for inserted text (#6237). Previously, the span was
+      marked with the non-standard class `inserted`.
+    + Improve icon conversion for `(/)`, `(x)`, `(!)`, `(?)`
+      `(+)`, `(-)`, `(off)`, `(*)`. (#6236, #6264).
+    + Support citations, attachment links, and user links (#6231, #6238,
+      #6239).
+    + Resolve parsing issues of blockquote, color (#6233, #6235).
+
+  * HTML reader:
+
+    + Parse attributes into table attributes.
+    + Support `<bdo>` (#5794, Tristan de Cacqueray).
+    + Add `summary` to list of block-level HTML tags (#6385).
+      This improves support for summary/details inside Markdown.
+      NOTE:  you need to include a blank line before the closing
+      `</details>`, if you want the last part of the content to
+      be parsed as a paragraph.
+    + Fix parsing unclosed th elements in a table (#6247).
+
+  * Commonmark reader: Implement `implicit_figures` extension (#6350).
+
+  * Markdown Reader:
+
+    + Fix inline code in lists (#6284, Nikolay Yakimov).
+      Previously inline code containing list markers was sometimes
+      parsed incorrectly.
+    + Don't require blank line after grid table (#6481).
+      This allows grid tables to be enclosed in fenced divs with no
+      intervening blank lines.
+
+  * LaTeX reader:
+
+    + Don't parse beyond `\end{document}` (#6380).
+      This required some internal changes to `\subfile` handling.
+    + Better handling of `\lettrine`.  SmallCaps instead of Span
+      for the part after the initial capital.  Ensure that both
+      arguments are parsed, so that in Markdown both
+      are treated as raw LateX. (Closes #6258.)
+
+  * Org reader (Albert Krewinkel):
+
+    + Recognize images with uppercase extensions (#6472).
+    + Keep unknown keyword lines as raw org.  The lines of unknown
+      keywords, like `#+SOMEWORD: value` are no longer read as metadata,
+      but kept as raw `org` blocks. This ensures that more information
+      is retained when round-tripping org-mode files; additionally,
+      this change makes it possible to support non-standard org
+      extensions via filters.
+    + Unify keyword handling.  Handling of export settings and other
+      keywords (like `#+LINK`) has been combined and unified.
+    + Support `LATEX_HEADER_EXTRA` and `HTML_HEAD_EXTRA`
+      settings.  These export settings are treated like their non-extra
+      counterparts, i.e., the values are added to the `header-includes`
+      metadata list.
+    + Allow multiple `#+SUBTITLE` export settings.  The values of all
+      lines are read as inlines and collected in the `subtitle`
+      metadata field.
+    + Read `#+INSTITUTE` values as text with markup.  The value is
+      stored in the `institute` metadata field and used in the
+      default beamer presentation template.
+    + The behavior of the `#+AUTHOR` and `#+KEYWORD` export
+      settings has changed: Org now allows multiple such lines
+      and adds a space between the contents of each line. Pandoc
+      now always parses these settings as meta inlines; setting
+      values are no longer treated as comma-separated lists.
+      Note that a Lua filter can be used to restore the previous
+      behavior.
+    + Read description lines as inlines (#6485). `#+DESCRIPTION` lines
+      are now treated as text with markup. If multiple such
+      lines are given, then all lines are read and separated by soft
+      linebreaks.
+    + Honor tex export option (#4070).  The `tex` export option can be set
+      with `#+OPTION: tex:nil` and allows three settings:
+      `t` (the default) causes LaTeX fragments to be parsed as TeX or added
+      as raw TeX.  `nil` removes all LaTeX fragments from the document.
+      `verbatim` treats LaTeX as text.
+
+
+  * RST reader:
+
+    + Pass arbitrary attributes through in code blocks (#6465).
+      Exceptions: name (which becomes the id), class (which becomes the
+      classes), and number-lines (which is treated specially to fit
+      with pandoc highlighting).
+    + Handle `date::` directive (#6276).
+
+  * Textile reader: support `pre.` for code blocks (#6454).
+
+  * Ipynb reader:
+
+    + Implement `raw_markdown` extension (#5408).  Specifying
+      `-f ipynb+raw_markdown` will cause Markdown cells
+      to be represented as raw Markdown blocks, instead of being
+      parsed.  This is not what you want when going from `ipynb`
+      to other formats, but it may be useful when going from `ipynb`
+      to Markdown or to `ipynb`, to avoid semantically insignificant
+      changes in the contents of the Markdown cells that might
+      otherwise be introduced.
+    + Handle application/pdf output as image (#6430).
+    + Properly handle image/svg+xml as an image (#6430).
+
+  * Docx reader:
+
+    + Distinguish between docx parsing and docx container unpacking errors.
+
+  * MediaWiki reader:
+
+    + Fix `gfm_auto_identifiers` so that `-` is not replaced by `_` (#6335).
+
+  * Vimwiki reader:
+
+    + Add nested syntax highlighting (#6256, Vlad Hanciuta).
+      Nested syntaxes are specified like this:
+      ```
+      {{{sql
+      SELECT * FROM table
+      }}}
+      ```
+      The preformatted code block parser has been extended to check if the
+      first attribute of the block is not a `key=value` pair, and in that
+      case it will be considered as a class.
+
+
+  * Jira writer (Albert Krewinkel):
+
+    + Always escape braces (#6478).  Braces are now always escaped, even
+      within words or when surrounded by whitespace. Jira and
+      Confluence treat braces specially.
+    + Convert Underline to inserted text (`+inserted+`).
+    + Add image attributes (#6234).  Image attributes are added
+      to the output as image parameters. If the image has a
+      class "thumbnail", then a thumbnail image is generated;
+      all other attributes are discarded in this case.
+
+  * LaTeX writer:
+
+    + Ensure that `-M csquotes` works even in fragment mode (#6265).
+    + Escape `^` specially for listings (#6460).
+    + Create hypertarget for links with identifier (#6360).
+    + Distinguish between single and double quotes when using enquote
+      package (#6457, dbecher-ito).
+    + Add support for customizable alignment of columns in beamer (#6331,
+      andrebauer).
+    + Add support for customizable alignment of columns in beamer
+      (#4805, #4150, andrebauer).
+
+  * HTML writer:
+
+    + Use CSS in favor of `<br>` for display math (#6372)
+      Some CSS to ensure that display math is
+      displayed centered and on a new line is now included
+      in the default HTML-based templates; this may be
+      overridden if the user wants a different behavior.
+
+  * Org writer:
+
+    + Clean-up Div handling (Albert Krewinkel).
+
+  * Docx writer:
+
+    + Enable column and row bands for tables (#6371).
+      This change will not have any effect with the default style.
+      However, it enables users to use a style (via a reference.docx)
+      that turns on row and/or column bands.
+
+  * OpenDocument (and ODT) writer:
+
+    + Add custom-style "Abstract" in metadata abstract.
+      This ensures that the abstract is rendered with style Abstract.
+    + Enable custom-style attribute on a Div.
+      This allows you to apply a custom style to contained paragraphs.
+
+  * DocBook writer:
+
+    + Add id of figure to enclosed image.
+    + Add personname element to docbook author (#6244).
+
+  * FB2 writer:
+
+    + Properly handle cover-image containing spaces (#6391).
+
+  * Markdown writer:
+
+    + Ensure consistent padding for pipe tables (#6240).
+    + Avoid unnecessary escapes before intraword `_` when
+      `intraword_underscores` extension is enabled (#6296).
+
+  * RST writer:
+
+    + Properly handle images with same alt text (#6194).
+      Previously we created duplicate references for these in rendering RST.
+
+  * AsciiDoc writer:
+
+    + Add blank line after Div (#6308).
+
+  * Haddock Writer:
+
+    + Support Haddock tables (Joe Hermaszewski).
+      See this PR on Haddock for details on the table format:
+      <https://github.com/haskell/haddock/pull/718>.
+
+  * PowerPoint writer (Jesse Rosenthal):
+
+    + Write math input verbatim in speaker notes (#6301).
+      OMML in speaker notes would lead to corrupt PowerPoint output. We now
+      output the OMML verbatim as LaTeX in the speaker notes.
+
+  * LaTeX template: Make polyglossia package options list-aware
+    (#6444, Frederik Elwert).
+
+  * Reveal.js template:
+
+    + Update template for reveal.js 4.0.0 (#6390, Salim B).
+    + Update template with newly available options (#6347, Jake Zimmerman).
+    + Use CDN version of revealjs v4 by default (#6408).
+
+  * opendocument template: Add abstract and subtitle to opendocument
+    template (#6369).
+
+  * reference.odt: clean up styles.  Add Abstract.
+    Change Author, Date to centered paragraphs with no character
+    styling.
+
+  * epub.css: wrap overlong lines in highlighted code blocks (#6242).
+    This fixes a problem in iBooks v2.4 with our earlier
+    horizontally scrolling code blocks.  The problem seems to
+    be a bug in iBooks, not pandoc, but since iBooks is a major
+    target we're changing pandoc's default behavior so that
+    pandoc-produced epubs work on that platform.
+
+  * Text.Pandoc.PDF:
+
+    + Use `--enable-local-file-access` in invoking `wkhtmltopdf` (#6474).
+      `wkhtmltopdf` changed in recent versions to require this for
+      access to local files.  This fixes PDF via HTML5 with `--css`.
+    + Send verbose output to stderr, not stdout (#6483).
+
+  * Text.Pandoc.MIME: Fix MIME type for TrueType fonts in EPUBs
+    (#6464, Michael Reed).
+
+  * Text.Pandoc.Shared:
+
+    + `makeSections`: omit number attribute when unnumbered class
+      is present (#6339).  Previously the attribute was included but given
+      an empty value, and this caused the table of contents creation
+      functions in Text.Pandoc.Writers.Shared to think these items had
+      numbers, which meant that they were included in the TOC even if the
+      `unlisted` class was used.
+    + Deprecate `underlineSpan` in Shared in favor of
+      `Text.Pandoc.Builder.underline` (Vaibhav Sagar).
+    + `renderTags'`: use self-closing tag for col element (#6295).
+
+  * Text.Pandoc.UUID: Fix `getRandomUUID`, which previously would
+    return the same value twice in a row. Make `getRandomUUID`
+    polymorphic in PandocMonad.  Remove `getUUID` (#6228, Joseph C. Sible).
+
+  * Text.Pandoc.Class: Generalize `PandocIO` functions to `MonadIO`.
+
+  * Fixed Katex standalone script (#6399, Lucas Escot).
+    Global macros are now persistent when using the HTML Writer with the
+    `--katex` option.
+
+  * Lua subsystem (Albert Krewinkel):
+
+    + Use new type PandocLua for all pandoc Lua operations (API change).
+      The new type `PandocLua` is an instance of the `PandocMonad` typeclass
+      and can thus be used in a way similar to `PandocIO`.
+    + Use PandocError for exceptions in Lua subsystem (API change).
+      The PandocError type is used throughout the Lua subsystem. All Lua
+      functions throw an exception of this type if an error occurs. The
+      `LuaException` type is removed and no longer exported from
+      `Text.Pandoc.Lua`. In its place, a new constructor `PandocLuaError`
+      is added to PandocError.
+
+  * Lua filters: improve error messages for failing filters (#6332,
+    Albert Krewinkel).  Print the Lua error properly instead of
+    displaying their `show` string.
+
+  * Use latest skylighting.  This fixes a bug with lua multiline
+    comments (and may improve handling of other syntaxes as well).
+    IT also adds `aria-hidden="true"` to the empty a elements, which
+    helps people who use screen readers.
+
+  * Use latest texmath.
+
+  * Require latest doctemplates 0.8.2.
+    This adds support for template pipes `first`, `rest`,
+    `last`, `allbutlast`.
+
+  * Revert  0e48a02 and dependency on base-noprelude, which hasn't
+    been updated for ghc 8.10 (see #6187).
+
+  * Dependency adjustments:
+
+    + Allow haddock-library 1.9.x.
+    + Allow hslua 1.1 (#6243, Felix Yan).
+    + Allow base64-bytestring 1.1.
+    + Use latest jira-wiki-markup.
+    + Allow http-client 0.7.
+    + Allow tasty 1.3.x.
+    + Allow aeson 1.5 (#6400, Felix Yan).
+    + Remove unused dependency `vector` (#6462, Laurent P. René de Cotret).
+    + Bump QuickCheck upper bound.
+
+  * Significant code cleanup and simplification (Joseph C. Sible, #6223,
+    #6209, #6225, #6229, #6226, #6340).
+
+  * Remove unnecessary hlint ignores (#6341, Joseph C. Sible).
+
+  * Remove obsolete RelaxedPolyRec extension (#6487, Nikolay Yakimov).
+
+  * trypandoc improvements (Mike Tzou):
+
+    + Add standalone option to the command text (#6210).
+    + Update third party libraries.
+
+  * MANUAL.txt:
+
+    + Clarify template partial naming (#6476, Mauro Bieg).
+    + Describe `jira` as "Jira/Confluence wiki markup" (#6351, Albert
+      Krewinkel).  In the past, Jira's wiki markup was also used by -- and
+      could be imported into -- Atlassian Confluence.
+    + Add link to print-css.rocks (#6272, Mauro Bieg).
+    + Clarify pipe table column width adjustment (#6254).
+    + Fix ATX header syntax.
+    + Fix misleading note about image size conversions (#6353).
+    + Update links to reveal.js documentation (#6386, Salim B).
+    + Separate adjacent verbatim code blocks (#6307, tom-audm).
+
+  * org.md:
+
+    + Document behavior of `smart` extension (#4387, Albert Krewinkel).
+    + Describe all supported export options in detail.
+
+  * lua-filters.md:
+
+    + Fix description of BulletList Lua type (Levi Gruspe).
+    + Use pandoc.system module in TikZ example (Albert
+      Krewinkel).  Showcase temporary directory handling with
+      `with_temporary_directory` and `with_working_directory`.
+
+  * INSTALL.md: fix FreeBSD port link (#6422, Mo).
+    The FreeBSD port was renamed from pandoc to hs-pandoc in 2010.
+    The old pandoc port is still at version 1.5.1.1
+
+  * Propagate `(DY)LD_LIBRARY_PATH` in tests (#6376, Lila).
+
+  * Bump `cabal-version` to 2.2 (#6377).
+
+  * Make it possible to compile using Stack on NixOS (#6439, Mathieu
+    Boespflug).
+
+  * CI action to check for commit message length (Nikolay Yakimov, #6398).
+
+
+## pandoc 2.9.2.1 (2020-03-23)
+
+  * Markdown reader: Fix table alignment when heading begins with t (#6153).
+    Due to a typo (`t` instead of `\t`) we were center aligning column
+    headings that begin with a lowercase `t`!
+
+  * Text.Pandoc.Readers.Roff:
+
+    + Fix parsing of `\.` in man/ms readers (#6175).
+      Previously due to a typo it was being parsed as `` ` ``.
+    + Fix parsing of `\'` in man/ms readers (#6175).  It was being parsed
+      as a backtick.
+
+  * Jira reader (Albert Krewinkel):
+
+    + Fix parsing of tables without preceding blankline (#6198).
+      A bug was fixed which caused faulty parsing if a table was not
+      preceded by a newline and the first table cell had no space
+      after the initial `|` characters.
+    + Fix parsing of strikeout, emphasis (#6196).  A bug was fixed which
+      caused non-emphasized text containing digits and/or non-special
+      symbols (like dots) to sometimes be parsed incorrectly.
+    + Support colored inline text, indented lists (#6183, #6184).
+
+  * Ms writer:
+
+    + Fix definition lists so indent even when paragraph indent is
+      set to 0 (as is the default).  Also ensure indent for display math
+      that falls back to TeX.
+    + Use `.QS/.QE` instead of `.RS/.RE` for block quotes.
+
+  * EPUB writer: fix regression on detection of front/back/bodymatter
+    (#6170).  This bug caused sections with epub:type `dedication` to be
+    misplaced in bodymatter instead of frontmatter as specified
+    in the manual.  The same problem would affect other epub:types.
+    The pattern matching needed to be changed with the use of
+    `makeSection`.
+
+  * AsciiDoc writer:  remove redundant `otherwise` guard in
+    `inlineToAsciiDoc` (#6146, Ryan Scott).
+
+  * Text.Pandoc.Class:
+
+    + Fix missing import when data files are not embedded (Albert Krewinkel).
+    + Subdivide Text.Pandoc.Class into small unexported modules
+      and ensure that all functions have Haddock documentation (#6106,
+      Albert Krewinkel).
+    + Finer grained imports of Text.Pandoc.Class submodules (#6203, Albert
+      Krewinkel).
+
+  * Text.Pandoc.XML: Add to list of HTML5 attributes:
+    `allow`, `autocapitalize`, `decoding`, `enterkeyhint`,
+    `imagesizes`, `imagesrcset`, `loading`.
+
+  * Use implicit Prelude (#6187, Albert Krewinkel).
+    The previous behavior was introduced as a fix for #4464. It seems that
+    this change alone did not fix the issue, and `stack ghci` and `cabal
+    repl` only work with GHC 8.4.1 or newer, as no custom Prelude is loaded
+    for these versions. Given this, it seems cleaner to revert to the
+    implicit Prelude.
+
+  * Always use custom prelude (#6187, Albert Krewinkel).
+    Previously, the custom prelude was used only with older GHC versions, as
+    a workaround for problems with ghci. The ghci problems are resolved by
+    replacing package `base` with `base-noprelude`, allowing for consistent
+    use of the custom prelude across all GHC versions.
+
+  * Remove outdated checks for no longer supported base versions
+    (Albert Krewinkel).
+
+  * PDF via wkhtmltopdf: put user-specified options last (#6171).
+    Certain options (e.g. `cover`) need to come after flags on
+    the command line.
+
+  * Text.Pandoc.App: set resource path at the beginning so it can affect
+    things like include-in-header (#5982).
+
+  * Change macOS release candidate CI process so that notarized
+    packages can be produced (#6169).
+
+  * Make MANUAL more explicit about nonbreaking space handling by
+    `all_symbols_escapable` (#6154, Fabien Schurter).
+
+  * trypandoc (Mike Tzou):
+
+    + Add checkbox for standalone option (#6189).
+    + Use strict mode for JavaScript code (#6188).
+    + Fetch resources over https (#6188).
+    + Remove unnecessary attributes on style, script elements (#6188).
+
+  * Use details tag to make GitHub releases changelog collapsible.
+
+  * Update filter code in doc/filters.md so it works with latest pandoc
+    (#6185).
+
+  * linux/Dockerfile: upgrade to alpine 3.11 (#6180, Albert Krewinkel).
+    This is used to build the static linux binaries.
+
+
+## pandoc 2.9.2 (2020-02-15)
+
+  * Add `csv` as an input format (#6100).  The CSV table is converted into a
+    pandoc simple table.  A new module Text.Pandoc.Readers.CSV
+    exports `readCSV` [API change].
+
+  * Introduce new format variants for JATS writer (#6014, Albert Krewinkel):
+
+    - `jats_archiving` for the "Archiving and Interchange Tag Set",
+    - `jats_publishing` for the "Journal Publishing Tag Set", and
+    - `jats_articleauthoring` for the "Article Authoring Tag Set."
+
+    The `jats` output format is now an alias for `jats_archiving`.
+    The module Text.Pandoc.Writers.JATS now exports
+    `writeJatsArchiving`, `writeJatsPublishing`, and
+    `writeJatsArticleAuthoring`, as well as the legacy
+    `writeJATS` [API change].
+
+  * `--defaults`: Support `bibliography` and `csl` fields.
+    Move `addMeta` from Text.Pandoc.App.CommandLineOptions to
+    Text.Pandoc.App.Opt (internal change).
+
+  * Add timing info for filters in `--verbose` mode (#6112).
+    When verbose mode is specified (verbosity == INFO), print a
+    notice when running a filter and when a filter completes (including
+    timing).
+
+  * LaTeX reader:
+
+    + Allow `&` in LaTeX citation keys (#6110).
+    + Improve caption and label parsing.
+    + Don't emit empty Span elements for labels.
+    + Put tables with labels in a surrounding Div.
+    + Resolve `\ref` to table numbers (#6137).
+    + Skip comments in more places where this is needed (#6114).
+    + Allow beamer overlays for all commands in all raw tex (#6043).
+      This affects parsing of raw tex in LaTeX and in Markdown and
+      other formats.
+    + Improve parsing of raw environments (#6034).  If parsing fails
+      in a raw environment (e.g. due to special characters like unescaped
+      `_`), try again as a verbatim environment, which is less sensitive to
+      special characters.  This allows us to capture special environments
+      that change catcodes as raw tex when `-f latex+raw_tex` is used.
+
+  * RST reader:
+
+    + Add highlight directive (#6140, Lucas Escot).
+
+  * MediaWiki writer:
+
+    + Prevent triple `[[[` which confuses MediaWiki (#6119).
+
+  * HTML reader:
+
+    + Don't parse `data-id` as `id` attribute.  And similarly don't
+      parse any `data-X` as `X` when `X` is a valid HTML attribute.
+
+  * Org reader:
+
+    + Simplify parsing of sub- and superscripts (#6127, Albert Krewinkel).
+      Speeds up parsing of single-word, markup-less sub- and superscripts.
+
+  * LaTeX writer:
+
+    + Group biblatex citations even with prefix and suffix (#5849, Ethan
+      Riley).  Previously biblatex citations were only grouped if there
+      was no prefix.  This patch allows them to be grouped in subgroups split
+      by prefixes and suffixes, which allows better citation sorting.
+    + Fix regression in handling of columns in beamer slides (#6033).
+      Columns in title slides were causing problems with
+      slide division.
+    + Fix duplicate frame classes in LaTeX/Beamer output (#6107).
+
+  * HTML writer:
+
+    + Fix duplicate attributes on headings (#6062), regression from 2.7.x.
+    + Fix `--number-offset` with HTML TOC.  Eventually it would be worth
+      adding a parameter to `makeSections` so this could be done at that
+      level; then it would also affect other writers that construct
+      TOC manually.
+    + reveal.js: restore old behavior for 2D nesting (#6032).
+      The fix to #6030 actually changed behavior, so that the
+      2D nesting occurred at slide level N-1 and N, instead of
+      at the top-level section.  This commit restores the v2.7.3 behavior.
+      If there are more than 2 levels, the top level is horizontal
+      and the rest are collapsed to vertical.
+    + reveal.js: ensure that pauses work even in title slides (#5819).
+
+  * Markdown writer:
+
+    + Fix regression: spurious dots in markdown_mmd metadata output (#6133).
+
+  * Docx writer:
+
+    + Fix regression with Compact style on tight lists (#6072).
+      Starting in 2.8, the docx writer no longer distinguishes between tight
+      and loose lists, since the Compact style is omitted.  This is a
+      side-effect of the fix to #5670, as explained in the changelog.  This
+      patch fixes the problem by extending the exception currently offered to
+      Plain blocks inside tables to Plain blocks inside list items.
+
+  * Jira writer:
+
+    + Fix output of table headers (Albert Krewinkel, #6035).
+
+  * Add Text.Pandoc.Image with unexported svgToPng.
+
+  * Text.Pandoc.XML: Export `html5Attributes`, `html4Attributes`,
+    `rdfaAttributes` (formerly unexported in Text.Pandoc.Writers.HTML).
+    [API change]
+
+  * Text.Pandoc.Shared: Export a new function `findM` (#6125,
+    Joseph C. Sible).
+
+  * Text.Pandoc.Logging: Add `RunningFilter`, `FilterCompleted`
+    constructors to LogMessage [API change].
+
+  * Text.Pandoc.CSV: fix bug in CSV parser; previously an extra blank record
+    would sometimes be inserted at the end.
+
+  * LaTeX template: add space option to xeCJK with PassOptionsToPackage
+    (#6002).  Otherwise we can get a clash with documentclasses that
+    already load the package.
+
+  * Lua filters:
+
+    + Allow filtering of element lists (#6038, Albert Krewinkel).  Lists of
+      Inline and Block elements can now be filtered via `Inlines` and
+      `Blocks` functions, respectively. This is helpful if a filter
+      conversion depends on the order of elements rather than a single
+      element.  For example, the following filter can be used to remove all
+      spaces before a citation:
+
+          function isSpaceBeforeCite (spc, cite)
+            return spc and spc.t == 'Space'
+             and cite and cite.t == 'Cite'
+          end
+
+          function Inlines (inlines)
+            for i = #inlines-1,1,-1 do
+              if isSpaceBeforeCite(inlines[i], inlines[i+1]) then
+                inlines:remove(i)
+              end
+            end
+            return inlines
+          end
+
+    + Add methods `insert`, `remove`, and `sort` to pandoc.List
+      (Albert Krewinkel).  Example of use:
+
+          local numbers = pandoc.List {2, 3, 1}
+          numbers:sort()     -- numbers is now {1, 2, 3}
+    + Make `pandoc.List` a callable constructor (Albert Krewinkel).
+      It is now possible to construct a new List via
+      `pandoc.List()` instead of `pandoc.List:new()`.
+    + Add tests for pandoc.List module (Albert Krewinkel).
+
+  * Text.Pandoc.App.CommandLineOptions: Change `setVariable` to use `Text`
+    instead of `String`.  This avoids some unnecessary unpacking.
+
+  * Use versioned directory for windows release zipfile.
+    Also remove old `make-windows-installer.bat`, superseded by GitHub
+    actions workflow, and modify `pandoc.wxs` for new paths.
+
+  * Extensive code cleanup (#6141, #6128, #6129, #6130, #6123,
+    #6105, 6102, #6117, #6124, #6115, #6116, #6111, Joseph C. Sible).
+
+  * Fix hlint warnings (Albert Krewinkel).
+
+  * Use latest doclayout, doctemplates (#6031).  The new version of
+    doclayout fixes a memory leak that affected `--include-in-header` with
+    large files (and possibly other cases involving extremely long lines).
+
+  * Use latest texmath.
+
+  * Use latest skylighting and fix test suite (#6086).
+
+  * sample.lua: Fix typo in descriptive comments (#6136, Caleb Maclennan).
+    Fix typo in error message (#6135).
+
+  * Add Docker and GH Actions instructions/links to INSTALL.md.
+
+  * Update filter documentation (#6065). Improve cabal v2 instructions.
+    Remove example using pandoc API directly (we have other
+    docs for that and it was outdated).
+
+  * Lua filter docs:
+
+    + Cross-link constructors and types (Albert Krewinkel).
+      Thanks to @bpj for the idea.
+    + Sort pandoc.List methods alphabetically (Albert Krewinkel).
+    + Unify, fix anchors and internal links (#6061, Albert Krewinkel).
+      Links and anchors now follow consistent conventions, like
+      lowercase-only anchor names.  This breaks some links to specific
+      sections in the document, but will make it much easier to link
+      documentation in the future.
+    + Clarify filter function execution order (#6059, Albert Krewinkel).
+
+  * In docs, update URLs and use `https:` wherever possible (#6090,
+    Salim B).
+
+## pandoc 2.9.1.1 (2020-01-05)
+
+  * Markdown reader:
+
+    + Fix parsing bug affected indented code after raw HTML (#6009, #5360).
+
+  * LaTeX writer:
+
+    + Fix regression in beamer slide structure with certain slide levels
+      (#6030).
+    + Allow framebreaks for beamer's TOC (Heiko Schlittermann, #6012)
+    + Properly handle unnumbered headings level 4+ (#6018).
+      Previously the `\paragraph` command was used instead of
+      `\paragraph*` for unnumbered level 4 headings.
+
+  * HTML writer:
+
+    + Fix revealjs slide structure regression with certain slide levels
+      (#6030).
+    + Add newlines to make slide show output more readable.
+
+  * Org writer:
+
+    + Remove extra spaces from table cells (Albert Krewinkel, #6024).
+
+  * JATS template: Update JATS dtd (Arfon Smith, #6020).  Use the archiving
+    and interchange DTD rather than the more restrictive journal publishing
+    DTD (which doesn't permit ext-link as a valid child).
+
+  * Text.Pandoc.PDF: Fix `runTeXProgram` so that the input source is always
+    overwritten (#6027).  Previously it wasn't overridden if the file already
+    existed, which led to bad results on subsequent runs when
+    `pdf-engine-opt=-output-directory=` was used to specify an explicit temp
+    dir.
+
+  * Text.Pandoc.BCP47: Change `getLang` to handle block-level contents
+    (#6008).  Some readers (e.g. RST) will populate the `lang` metadata field
+    with block-level content.  `getLang` has been modified to handle this.
+    Previously in these cases the LaTeX writer would not properly set the
+    "main language" of the document.
+
+  * Fix `test/tables.org` (Albert Krewinkel).
+
+  * Use HTTPS in copyright message (Felix Yan, #6010)
+
+
+## pandoc 2.9.1 (2019-12-23)
+
+  * Add Jira reader (Albert Krewinkel, #5556).
+
+  * Jira writer: use jira-wiki-markup renderer (Albert Krewinkel,
+    #5926). The following improvements are included in this change:
+
+    + non-jira raw blocks are fully discarded instead of showing
+      as blank lines;
+    + table cells can contain multiple blocks;
+    + unnecessary blank lines are removed from the output;
+    + markup chars within words are properly surrounded by
+      braces;
+    + preserving soft linebreaks via `--wrap=preserve` is
+      supported.
+
+    Note that backslashes are rendered as HTML entities, as there
+    appears no alternative to produce a plain backslash if it is
+    followed by markup. This may cause problems when used with
+    confluence, where rendering seems to fail in this case.
+
+  * Fix regression with `--number-sections`. Starting with 2.8,
+    `--number-sections` also had the effect of `--section-divs`,
+    even if `--section-divs` was not specified.
+
+  * Improved table of contents generation in markdown, RTF,
+    commonmark, better handling cases where section headings are
+    enclosed in divs.
+
+  * Ensure that later default file values for `variable` replace
+    earlier ones (5988).
+
+  * HTML reader: Add `nav` to list of block-level tags.
+
+  * Org reader (Albert Krewinkel):
+
+    + Wrap named table in Div, using name as id (#5984).
+      Tables which are given a name via `#+NAME:` or `#+LABEL:`
+      are wrapped in an additional Div, with the name set as the
+      Div's ID.
+    + Report parsing errors properly.
+    + Fix parsing problem for colons in headline (#5993).
+
+  * Text.Pandoc.PDF: Ensure UTF8 when printing source in
+    `--verbose` mode, avoiding an error on platforms that
+    default to something other than UTF-8 (#5997).
+
+  * Text.Pandoc.Templates: Strip directory before trying to find
+    partial in data files (#5987).
+
+  * Text.Pandoc.Shared: Improve `makeSections` so we don't get
+    doubled "number" attributes in EPUB output (or anywhere
+    else) (#5986).
+
+  * Added tests for `--toc` and `--section-divs`.
+
+  * Text.Pandoc.MIME: Added glsl MIME type for WebGL maps (#6000,
+    Jared Lander).
+
+  * MANUAL: A bit clearer explanation for `--base-header-level`.
+    We now say exactly how to translate between the deprecated
+    `--base-header-level` and `--shift-heading-level-by`.
+
+  * lua-filters.md:
+
+    + Remove spurious dot in title (#5996, Mauro Bieg).
+    + Replace metadata example with image centering (#6004,
+      Albert Krewinkel). Thanks to @efx for proposing this filter.
+
+
+## pandoc 2.9 (2019-12-11)
+
+  * Text.Pandoc.Templates [API change]
+
+    + Add Monad wrappers `WithDefaultPartials` and `WithPartials`.
+      Wrapping these around an instance of `PandocMonad` gives
+      us different instances of `TemplateMonad`, with different
+      search behavior in retrieving partials.
+      To compile a template and limit partial search to pandoc's
+      data files, use `runWithDefaultPartials (compileTemplate ...)`.
+      To compile a template and allow partials to be found locally
+      (either on the file system or via HTTP, in the event that
+      the main template has an absolute URL), ue
+      `runWithPartials (compileTemplate ...)`.
+    + Export `getTemplate`, which seeks a template locally,
+      or via HTTP if the template has an absolute URL, falling
+      back to the data files if not found.
+    + Export `compileDefaultTemplate` -- does `getDefaultTemplate`
+      and compiles the result, raising an error on failure.
+
+  * Text.Pandoc.Class [API change]
+
+    + Remove `TemplateMonad` instances for `PandocIO` and `PandocPure`.
+      These were too limiting and caused a bug whereby a local
+      partial could be used even when the default template was requested.
+      We now rely on instances provided in the Templates module.
+
+  * Text.Pandoc.App.OutputSettings: Simplify template retrieval code.
+
+  * ConTeXt template: Adjust to title formatting (#5949, Denis Maier).
+    Add `\setupinterlinespace` to `title`, `subtitle`, `date` and `author`
+    elements:  otherwise longer titles that run over multiple lines will look
+    squashed as `\tfd` etc. won't adapt the line spacing to the font size.
+
+  * reveal.js template: Add title-slide-attributes variable (#5981,
+    Frederik Elwert).
+
+  * More informative JSON parse error (#5973).
+
+  * Use external emojis package (forked from pandoc).  Removed emoji data
+    in Text.Pandoc.Emoji.
+
+  * Fix regression in `makeSections` (#5965).
+    Previously `hierarchicalize` (the ancestor of `makeSections`) would put
+    header attributes on the containing Div.  In 2.8 this behavior changed,
+    which broke some tools depending on pandoc.  Here we roll back this change,
+    so that attributes again migrate from the header to the containing Div when
+    `makeSections` is run.  Note that attributes are retained on the header as
+    well (unlike before) -- with the exception of the `id` attribute, which of
+    course cannot be duplicated.
+
+  * Fix `--toc-depth` regression in 2.8 (#5967).
+
+  * Use doctemplates 0.8.  Rename template 'filters' as 'pipes'
+    to avoid confusion with the other notion of filter used by pandoc.
+
+  * Fix README.md so that relative links from manual become absolute.
+    Previously they'd be broken links when viewed on GitHub or Hackage.
+    So we add the base URL for the pandoc manual.
+
+  * Document display math syntax in manual.
+
+## pandoc 2.8.1 (2019-12-05)
+
+  * Add `ascii_identifiers` as a supported extension for `markdown`.
+    This fixes a regression in 2.8.
+
+  * Fix regression with behavior of `--variable` (#5962).
+    Previously `-Vfoo=1 -Vfoo=2` would produce a list value for foo;
+    with 2.8 it produced just `2`.  This commit restores the earlier
+    behavior.
+
+  * Roll back part of of `--shift-heading-level-by` change (#5957).
+    With positive heading shifts, starting in 2.8 this option
+    caused metadata titles to be removed and changed to regular
+    headings.  This behavior is incompatible with the old
+    behavior of `--base-header-level` and breaks old workflows,
+    so we have rolled back the change. Note that there is now an
+    asymmetry in positive and negative heading level shifts:
+    With positive shifts, the metadata title stays the same and
+    does not get changed to a heading in the body, while with
+    negative shifts, a heading can be converted into the
+    metadata title.
+
+  * Text.Pandoc.Shared: Fix `makeSections` so it doesn't turn
+    column Divs into sections.
+
+  * HTML writer: add task-list class to ul if all elements are
+    task list items.  This will allow styling unordered task
+    lists in a way that omits the bullet.
+
+  * HTML-based templates: Add CSS to suppress bullet on unordered task lists.
+
+  * ConTeXt template: Fix `\startcslreferences` and use ConTeXt syntax
+    conventions (#5945, Denis Maier).  The old version had a too large
+    a skip at the beginning of the reference list.
+
+  * LaTeX template: keep the `\author{}` command even if author is not
+    specified (#5961, Yihui Xie).  Avoids a LaTeX warning.
+
+  * Generate Emoji module with TH.
+
+    + Add Text.Pandoc.Emoji.TH.
+    + Replace long literal list in Text.Pandoc.Emoji with one-liner
+      generating it from `emoji.json` using TH.
+    + Add Makefile target to download `emoji.json`.
+    + Remove `tools/emoji.hs`.
+
+  * Increase GC allocation space for compilation in cabal.project.
+
+  * Clean up manual on PDF generation backend options (#5940).
+
+  * Update release checklist to include code signing step and update
+    Windows release-candidate builds (#5950).
+
+
+## pandoc 2.8.0.1 (2019-11-26)
+
+  * List `pdf` in `--list-output-formats`.
+  * EPUB writer: Fix regression with `--css` (#5937).  In 2.8 `--css`
+    would not have an effect on EPUB output.
+  * RST writer: Use grid tables for one-column tables, since
+    simple tables clash with heading syntax in this case (#5936).
+  * Add unexported module Text.Pandoc.Readers.Metadata (see #5914).
+  * Use doctemplates 0.7.2, which adds the `nowrap` filter to
+    templates.
+  * Update default man template using `nowrap` for .TH heading (#5929).
+  * HTML templates: Add support for `toc-title` variable (#5930,
+    Alexandre Franke).
+  * Remove `grffile` (LaTeX package) requirement in MANUAL.txt
+    (#5927, Ian Max Andolina).
+  * Use skylighting 0.8.3.
+
+## pandoc 2.8 (2019-11-22)
+
+  * Improvements in templates system (from doctemplates):
+
+    + Pandoc templates now support a number of new features that
+      have been added in doctemplates: notably, `elseif`, `it`,
+      partials, filters, and syntax to control nesting and reflowing of
+      text.  These changes make pandoc more suitable out of the
+      box for generating plain-text documents from data in YAML
+      metadata.  It can create enumerated lists and even tabular
+      structures.
+    + We now used templates parameterized on doclayout Doc types.
+      The main impact of this change is better reflowing of
+      content interpolated into templates.  Previously,
+      interpolated variables were rendered independently and
+      interpolated as strings, which could lead to overly long
+      lines. Now the templates interpolated as Doc values which
+      may include breaking spaces, and reflowing occurs after
+      template interpolation rather than before.
+    + Remove code from the LaTeX, Docbook, and JATS writers that
+      looked in the template for strings to determine whether it
+      is a book or an article, or whether csquotes is used. This
+      was always kludgy and unreliable.
+    + Change template code to use new API for doctemplates.
+
+  * Add `--defaults`/`-d` option.  This adds the ability to specify
+    a collection of default values for options in a YAML file. For
+    example, one might define a set of defaults for letters,
+    and then do `pandoc -d letter myletter.md -o myletter.pdf`.
+    See the documentation of this feature in MANUAL.txt.
+
+  * Raise error on unsupported extensions (#4338).
+
+  * The `--list-extensions[=FORMAT]` option now lists only
+    extensions that affect the given FORMAT.
+
+  * Add `-L` option as shortcut for `--lua-filter`.
+
+  * Add `--shift-heading-level-by` option and deprecate
+    `--base-heading-level` (#5615). The new option does
+   everything the old one does, but also allows negative shifts.
+   It also promotes the document metadata (if not null) to a
+   level-1 heading with a +1 shift, and demotes an initial
+   level-1 heading to document metadata with a -1 shift. This
+   supports converting documents that use an initial level-1
+   heading for the document title.
+
+  * Allow `--metadata-file` to be used repeatedly to include
+    multiple metadata files (Owen McGrath, #5702). Values in
+    files specified first will be overridden by those in later
+    files.
+
+  * `--ascii` now uses numerical hex character references (#5718).
+
+  * Allow PDF output to stdout (#5751).  PDF output now behaves like other
+    binary formats: it will not be output to the terminal, but can be
+    sent to stdout using either `-o -` or a pipe.  The intermediate format
+    will be determined based on the setting of `--pdf-engine`.
+
+  * Make some writers sensitive to 'unlisted' class on headings (#1762).
+    If this is present on a heading with the 'unnumbered' class,
+    the heading won't appear in the TOC.  This class has no
+    effect if 'unnumbered' is not also specified.  This affects HTML-based
+    writers (including slide shows and EPUB), LateX (including beamer), RTF,
+    and PowerPoint.  Other writers do not yet support `unlisted`.
+
+  * Fix `gfm_auto_identifiers` behavior with emojis (#5813).  Note that
+    we also now use emoji names for emojis when `ascii_identifiers`
+    is enabled.
+
+  * When `--ipynb-output` is used with the default "best" format, strip
+    ANSI escape codes for non-ipynb output (#5633).  These cause problems
+    in many formats, including LaTeX.
+
+  * Don't look for template files remotely for remote input (#5579).
+    Previously pandoc would look for the template at a remote URL when a
+    URL was used for the input file, instead of taking it from the
+    data directory.
+
+  * Allow combining `-Vheader-includes` and `--include-in-header` (#5904).
+    Previously `header-includes` set as a variable would be
+    clobbered by material included using `--include-in-header`.
+
+  * Change merge behavior for metadata.  Previously, if a document
+    contained two YAML metadata blocks that set the same field, the
+    conflict would be resolved in favor of the first. Now it is resolved
+    in favor of the second (due to a change in pandoc-types).
+    This makes the behavior more uniform with other things in pandoc
+    (such as reference links and `--metadata-file`).
+
+  * Don't add a newline to fragment output if there's already one.
+
+  * Change exit codes and document in MANUAL.txt:
+
+    + `PandocAppError` was 1, is now 4
+    + `PandocOptionError` was 2, is now 6
+    + `PandocMakePDFError` was 65, is now 66
+
+  * Switch to new pandoc-types and use Text instead of String [API change].
+    (Christian Despres, #5884).
+
+  * HTML reader:
+
+    + Better handling of `<q>` with cite attribute (#5798, Ole Martin Ruud).
+      If a `<q>` tag has a `cite` attribute, we interpret it as a Quoted
+      element with an inner Span.
+    + Add support for HTML `<samp>` element (#5792, Amogh Rathore).
+      The `<samp>` element is parsed as Code with class `sample`.
+    + Add support for HTML `<var>` element (#5799, Amogh Rathore).
+      The `<var>` element is parsed as Code with class `variable`.
+    + Add support for `<mark>` elements (Florian B, #5797).  Parse
+      `<mark>` elements from HTML as Spans with class `mark`.
+    + Add support for `<kbd>` elements, parsing them as Span with class
+      `kbd` (Daniele D'Orazio, #5796).
+    + Add support for `<dfn>`, parsing this as a Span with class `dfn`
+      (#5882, Florian Beeres).
+
+  * Markdown reader:
+
+    + Headers: don't parse content over newline boundary (#5714).
+    + Handle inline code more eagerly within lists (Brian Leung, #5627).
+    + Removed some needless lookaheads.
+    + Don't parse footnote body unless extension enabled.
+    + Fix small super/subscript issue (#5878).  Superscripts and subscripts
+      cannot contain spaces, but newlines were previously allowed
+      (unintentionally).  This led to bad interactions in some cases
+      with footnotes.  With this change newlines are also not allowed inside
+      super/subscripts.
+    + Use `take1WhileP` for `str`, table row.  This yields a small but
+      measurable performance improvement.
+
+
+  * LaTeX reader:
+
+    + Fix parsing of optional arguments that contain braced text (#5740).
+    + Don't try to parse includes if `raw_tex` is set (#5673).
+      When the `raw_tex` extension is set, we just carry through
+      `\usepackage`, `\input`, etc. verbatim as raw LaTeX.
+    + Properly handle optional arguments for macros (#5682).
+    + Fix `\\` in `\parbox` inside a table cell (#5711).
+    + Improve `withRaw` so it can handle cases where the token string is
+      modified by a parser (e.g. accent when it only takes part of a Word
+      token) (#5686).  This fixes a bug that caused the ends of
+      certain documents to be dropped.
+    + Handle `\passthrough` macro used by latex writer (#5659).
+    + Support tex `\tt` command (#5654).
+    + Search for image with list of extensions like latex does, if an
+      extension is not provided (#4933).
+    + Handle `\looseness` command values better (#4439).
+    + Add `mbox` and `hbox` handling (Vasily Alferov, #5586).
+      When `+raw_tex` is enabled, these are passed through literally.
+      Otherwise, they are handled in a way that emulates LaTeX's behavior.
+    + Properly handle `\providecommand` and `\provideenvironment` (#5635).
+      They are now ignored if the corresponding command or environment
+      is already defined.
+    + Support epigraph command in LaTeX Reader (oquechy, #3523).
+    + Ensure that expanded macros in raw LaTeX  end with a space
+      if the original did (#4442).
+    + Treat `ly` environment from lilypond as verbatim (Urs Liska, #5671).
+    + Add `tikzcd` to list of special environments (Eigil Rischel).
+      This allows it to be processed by filters, in the same way that
+      one can do for `tikzpicture`.
+
+  * Roff reader:
+
+    + Better support for `while`.
+    + More improvements in parsing conditionals.
+    + Fix problem parsing comments before macro.
+    + Improve handling of groups.
+    + Better parsing of groups (#5410).  We now allow groups
+      where the closing `\\}` isn't at the beginning of a line.
+
+  * RST reader:
+
+    + Keep `name` property in `imgAttr` (Brian Leung, #5619).
+    + Fixed parsing of indented blocks (#5753).  We were requiring
+      consistent indentation, but this isn't required by RST.
+    + Use title, not admonition-title, for admonition title.
+      This puts RST reader into alignment with docbook reader.
+    + Don't strip final underscore from absolute URI (#5763).
+    + Avoid spurious warning when resolving links to internal anchors
+      ending with `_` (#5763).
+
+  * Org reader:
+
+    + Accept `ATTR_LATEX` in block attributes (Albert Krewinkel, #5648).
+      Attributes for LaTeX output are accepted as valid block attributes;
+      however, their values are ignored.
+    + Modify handling of example blocks (Brian Leung, #5717).
+    + Allow the `-i` switch to ignore leading spaces (Brian Leung).
+    + Handle awkwardly-aligned code blocks within lists (Brian Leung).
+      Code blocks in Org lists must have their `#+BEGIN_` aligned in a
+      reasonable way, but their other components can be
+      positioned otherwise.
+    + Fix parsing of empty comment lines (#5856, Albert Krewinkel).
+      Comment lines in Org-mode can be completely empty.
+
+  * Muse reader (Alexander Krotov):
+
+    + Add RTL support (#5551).
+    + Do not allow closing asterisks to be followed by `*`.
+    + Do not split series of asterisks into symbols and emphasis (#5821).
+    + Do not terminate emphasis on `*` not followed by space.
+
+  * DokuWiki reader:
+
+    + Parse markup inside monospace ('') (#5916, Alexander Krotov).
+
+  * Docx reader:
+
+    + Move style-parsing-specific code to a new unexported module,
+      Text.Pandoc.Readers.Docx.Parse.Styles (Nikolay Yakimov).
+    + Move StyleMap to docx writer (Nikolay Yakimov).
+    + Only use LTR when it is overriding BiDi setting (#5723, Jesse
+      Rosenthal).  The left-to-right direction setting in docx is used
+      in the spec only for overriding an explicit right-to-left setting.
+      We only process it when it happens in a paragraph set with BiDi.
+      This is especially important for docs exported from Google Docs,
+      which explicitly (and unnecessarily) set `rtl=0` for every paragraph.
+    + Fix list number resumption for sublists (#4324).
+      The first list item of a sublist should not resume numbering
+      from the number of the last sublist item of the same level,
+      if that sublist was a sublist of a different list item.
+
+  * Docbook reader:
+
+    + Richer parse for admonitions (Michael Peyton Jones, #1234).
+      Instead of parsing admonitions as blockquotes, we now parse
+      them as Divs with an appropriate class. We also handle titles
+      for admonitions as a nested Div with the "title" class.
+    + Fix nesting of chapters and sections (#5864, Florian Klink,
+      Félix Baylac-Jacqué).
+    + Fix bug with entities in mathphrase element (#5885).
+
+  * MediaWiki reader:
+
+    + Skip optional `{{table}}` template (#5757).
+
+  * LaTeX reader:
+
+    + Fix dollar-math parsing to ensure that space is left between a
+      control sequence and a following letter (#5836).
+    + In `untokenize`, ensure space between control sequence
+      and following letter (#5836).
+    + Don't omit macro definitions defined in the preamble.
+      These were formerly omitted (though they still affected macro
+      resolution if `latex_macros` was set).  Now they are included in
+      the document body.
+    + Parse macro definitions as raw LaTeX when `latex_macros` is
+      disabled.  (When `latex_macros` is enabled, we omit them, since
+      pandoc is applying the macros itself.)
+    + Fix a hang/memory leak in certain circumstances (#5845).
+    + Text.Pandoc.Readers.LaTeX.Parsing: add `[Tok]` parameter to
+      `rawLaTeXParser`.  This allows us to repeat retokenizing
+      unnecessarily in e.g. `rawLaTeXBlock`.
+    + Add KOMA-Script metadata commands (#5910, Andrew Dunning).
+      Add all titling commands to existing definition for `\dedication`.
+    + Parse `\micro` siunitx unit command (#5921, Jose Luis Duran).
+
+  * Markdown writer:
+
+    + Ensure proper nesting when we have long ordered list markers (#5705).
+    + Make `plain` output plainer (#5741).  Previously we used the following
+      Project Gutenberg conventions for plain output: extra space before and
+      after level 1 and 2 headings, all-caps for strong emphasis,
+      underscores surrounding regular emphasis. Now these
+      conventions are used only when the `gutenberg` extension is
+      enabled. By default, Strong and Emph are rendered without
+      special formatting, and headings are rendered without
+      special formatting, and with only one blank line following.
+      To restore the former behavior, use `-t plain+gutenberg`.
+    + Prefer using raw_attribute when enabled (#4311).
+      The `raw_attribute` will be used to mark raw bits, even HTML
+      and LaTeX, and even when `raw_html` and `raw_tex` are
+      enabled, as they are by default. To get the old behavior,
+      disable `raw_attribute` in the writer.
+    + Prefer `pipe_tables` to raw HTML even when we must
+      lose width information (#2608, #4497).
+    + Improve escaping in list items (#5918).
+
+  * AsciiDoc writer:
+
+    + Don't include `+` in code blocks for regular asciidoc.
+      This is asciidoctor-specific.
+    + Handle admonitions (#5690).
+
+  * LaTeX writer:
+
+    + Add thin space when needed in LaTeX quote ligatures (#5684).
+    + Use `\hspace{0pt}` for 0-width space U+200B (#5756).
+    + Use `cslreferences` environment for csl bibliographies.
+      This allows bibliographies to receive special formatting.
+      The template now contains definition of this environment (enabled
+      only when CSL is used).  It also defines a `\cslhangindent` length.
+      This is set to 2em by default when the bibliography style specifies
+      a hanging indent.  To override the length, you can use e.g.
+      `\setlength{\cslhangindent}{7em}` in header-includes.
+      See jgm/pandoc-citeproc#410.
+    + Strip off `{}` around locator for biblatex/natbib output (#5722).
+    + Fix line breaks at start of paragraph (#3324).
+      Previously we just omitted these. Now we render them
+      using `\hfill\break` instead of `\\`.  This is a revision
+      of a PR by @sabine (#5591) who should be credited with the idea.
+    + We no longer look in the template or header-includes to see if a
+      book or article documentclass is used, or to see whether the
+      `csquotes` package is used. To use `csquotes` for LaTeX, set
+      `csquotes` in your variables or metadata. To specify a book
+      style, use the `documentclass` variable or
+      `--top-level-division`.
+    + Fix horizontal rule (#5801).  We change to use 0.5pt rather than
+      `\linethickness`, which apparently only ever worked "by accident"
+      and no longer works with recent updates to texlive.
+
+  * ConTeXt writer:
+
+    + Add option to include source files in ConTeXt PDFs (Tristan
+      Stenner, #5578). The metadata field or variable
+      (`includesource`) can be set to attach the source documents
+      to the resulting PDF.
+    + Customizable type of PDF/A for the ConTeXt writer (Karl
+      Pettersson, #5608).  The `pdfa` variable may now be set in metadata.
+      Also updated color profile settings in accordance with ConTeXt wiki,
+      and made ICC profile and output intent for PDF/A customizable
+      using `pdfaiccprofile` and `pdfaintent`.
+    + Unit tests: adjust code property to avoid an irrelevant
+      failure involving inline code with two consecutive newlines.
+    + Set `csl-hanging-indent` variable if needed.
+    + Use special environment for CSL references.
+    + Use braces, not start/stop, for inline language tags.
+      This prevents unwanted gobbling of spaces.
+
+  * HTML writer:
+
+    + Use numeric character references with `--ascii` (#5718).
+      Previously we used named character references with html5 output.
+      But these aren't valid XML, and we aim to produce html5 that is
+      also valid XHTML (polyglot markup).  (This is also needed for epub3.)
+    + Ensure that line numbers in code blocks get id-prefix (#5650).
+    + Ensure TeX formulas are rendered correctly (Philip Pesca,
+      #5658). The web service passed in to `--webtex` may render
+      formulas using inline or display style by default.
+      Prefixing formulas with the appropriate command ensures
+      they are rendered correctly.
+    + Render inline formulas correctly with `--webtex` (Philip
+      Pesca, #5655). We add `\textstyle` to the beginning of the
+      formula to ensure it will be rendered in inline style.
+    + Pass through `aria-` attributes to HTML5 (#5642).
+    + Render a Quoted element with an inner Span with
+      `cite` attribute using a `<q>` tag (#5798, Ole Martin Ruud).
+    + Render a Span with class `mark` using the `<mark>` element
+      (Florian Beeres, #5797).
+    + Render Span with class `dfn` using `<dfn>` element
+      (Florian Beeres, #5882).
+    + Render Span with class `kbd` using `<kbd>` element (Daniele
+      D'Orazio, #5796).
+    + Render Code with class `variable` using `<var>` element
+      (Amogh Rathore, #5799).
+    + Render Code with class `sample` using `<samp>` element
+      (Amogh Rathore, #5799).
+
+  * EPUB writer:
+
+    + Improve splitting into chapters (#5761), using `makeSection`.
+    + Avoid issuing warning multiple times when title not set (see #5760).
+    + Use svg tag wrapper for cover image (#5638).  In addition, the
+      code generating the image has been moved to the template, to make it
+      more customizable. NOTE: Those who use custom EPUB
+      templates will need to adjust their templates, adding the
+      code to generate the cover image. (Previously this was just
+      inserted into 'body'.)
+    + Improve toChapters, making it work better if there are Divs
+      around sections.
+    + Add support for EPUB2 covers (blmage, #3992).
+    + Do not override existing "fileN" medias when writing to EPUB format
+      (blmage, #4206).
+    + Ensure that `lang` variable is set on all chapters (so that it
+      will add an `xml:lang` attribute on the `html` element).
+
+  * RST writer:
+
+    + Removed remnants of `admonition-title`.
+    + Fix handling of `:align:` on figures and images (#4420).
+      When the image has the `align-right` (etc.) class, we now use
+      an `:align:` attribute.
+    + Improve spacing for tables with no width information (#5899).
+      If a simple table would be too wide, we use a grid table.
+    + Fix backslash escaping after strings (Albert Krewinkel, #5906).
+      The check whether a complex inline element following a string must
+      be escaped, now depends on the last character of the string instead
+      of the first.
+    + Ensure there's a blank line before tables (#5898).
+
+  * Dokuwiki writer:
+
+    + Handle mixed lists without HTML fallback (#5107).
+
+  * XWiki writer:
+
+    + Fix multiline table (Zihang Chen, #5683).
+
+  * Muse writer:
+
+    + Add RTL support (Alexander Krotov, #5551).
+
+  * Man writer:
+
+    + Suppress non-absolute link URLs (#5770).  Absolute URLs are
+      still printed in parentheses following the link text, but relative
+      URLs are suppressed (just as internal links starting with '#'
+      always have been).
+    + Improved definition list term output.  Now we boldface code but
+      not other things. This matches the most common style in man pages
+      (particularly option lists).
+
+  * Ms writer:
+
+    + Use `.LP` instead of `.PP` for line block (#5588).
+    + Use boldface for definition terms in DefinitionLists.
+
+  * JATS writer:
+
+    + Do not emit empty `<fn-group>` (Mauro Bieg, #5595).
+    + Update template to v1.1dtd (#5632, Arfon Smith).
+    + Update `data/jats.csl` to avoid commas between editor
+      name-part elements. (#5629)
+    + Add `abstract` to template (Mauro Bieg).
+
+  * TEI writer:
+
+    + Don't strip hash from internal links (#5922).
+
+  * Jira writer:
+
+    + Remove escapeStringForJira for code blocks (Jan-Otto Kröpke).
+    + Remove extraneous newline after single-line block quotes
+      (#5858, Albert Krewinkel).
+    + Improve escaping of special characters, using backslash escapes
+      instead of HTML entities (#5858, Albert Krewinkel).
+
+  * OpenDocument writer:
+
+    + Avoid duplicate attributes (#4634). We use the innermost
+      attribute in nested cases.
+    + If `native_numbering` extension is set, use native OpenDocument
+      enumeration for figures and tables (Nils Carlson).
+    + Place caption before table (#5681, Dmitry Pogodin).
+
+  * ODT writer:
+
+    + Add a test for MathML formulas in ODT documents (blmage).
+    + Improve the parsing of frames in ODT documents (blmage).
+
+  * Docx writer:
+
+    + Make handling of styles more robust in localized versions
+      of Word (Nikolay Yakimov, #5523, #5052, #5074).  We now use
+      style names, not ids, for assigning semantic meaning, since
+      the ids can change depending on the locale. Style name
+      comparisons are case-insensitive, since those are
+      case-insensitive in Word. Since docx style names can have
+      spaces in them, and pandoc-markdown classes can't, anywhere
+      when style name is used as a class name, spaces are
+      replaced with ASCII dashes `-`. Code styles, i.e. "Source
+      Code" and "Verbatim Char" now honor style inheritance. Docx
+      Reader now honours "Compact" style (used in
+      Pandoc-generated docx). The side-effect is that "Compact"
+      style no longer shows up in docx+styles output. Styles
+      inherited from "Compact" will still show up.
+    + Re-use Readers.Docx.Parse for StyleMap (#5766, Nikolay Yakimov).
+    + Internal improvements and code simplification (Nikolay Yakimov).
+    + Preserve built-in styles in DOCX with custom style (Ben Steinberg,
+      #5670).  This change prevents custom styles on divs and spans
+      from overriding styles on certain elements inside them, like
+      headings, blockquotes, and links. On those elements, the
+      "native" style is required for the element to display correctly.
+      This change also allows nesting of custom styles; in order to do so,
+      it removes the default "Compact" style applied to Plain blocks,
+      except when inside a table.
+    + Add `proofState` to list of elements carried over from
+      settings.xml in the reference.docx (Krystof Beuermann, #5703).
+    + Change order of `ilvl` and `numId` in `document.xml` (Agustín
+      Martín Barbero, #5645). Also, make list para properties go first.
+      This reordering of properties shouldn't be necessary but
+      it seems Word Online does not understand the docx correctly otherwise.
+
+  * PowerPoint writer:
+
+    + Code formatting is now context dependent (Jeroen de Haas, #5573).
+      This commit alters the way in which the Powerpoint writer treats
+      inline code and code blocks. Inline code is now formatted at
+      the same size as the surrounding text. Code blocks are now given
+      a margin and font size according to their level.
+      Furthermore this commit allows changing the font with which code is
+      formatted via the `monofont` option.
+    + Start numbering at appropriate numbers (Jesse Rosenthal, #5709).
+      Starting numbers for ordered lists were previously ignored. Now
+      we specify the number if it is something other than 1.
+
+  * Text.Pandoc.Parsing:
+
+    + Add `manyChar`, `many1Char`, `manyTillChar`, `many1TillChar`,
+      `many1Till`, `manyUntil`, `mantyUntilChar`: these are like their
+      unsuffixed counterparts but pack some or all of their output
+      (Christian Despres, #5884).
+    + Add `stateAllowLineBreaks` to `ParserState` [API change].
+    + Fix inline parsing in grid table cells (#5708).
+    + Change type of `setLastStrPos` so it takes a `Maybe SourcePos`
+      rather than a `SourcePos` [API change].
+    + Make `parseFromString'` and `gridTableWith` and
+      `gridTableWith'` polymorphic in the parser state,
+      constraining it with `HasLastStrPosition` [API change].
+    + `parseFromString'`: reset `stateLastStrPos` to `Nothing` before parse.
+    + Rename takeWhileP -> take1WhileP and clean it up.
+      (It doesn't match the empty sequence.)
+
+  * Text.Pandoc.PDF:
+
+    + For PDFs via HTML, ensure temp file is deleted even if the pdf
+      program is not found (#5720).
+    + Better detection of a Cygwin environment (#5451).
+    + Don't assume tex log file is UTF8-encoded (#5872).
+      Fall back to latin1 if it can't be read as UTF-8.
+
+  * Text.Pandoc.Extensions:
+
+    + Export new function `getAllExtensions`, which returns the
+      extensions that affect a given format (whether enabled by default
+      or not) [API change].
+    + Change type of `parseFormatSpec` from
+      `Either ParseError (String, Extensions -> Extensions)`
+      to `Either ParseError (String, [Extension], [Extension])`
+      [API change].
+    + Add `Ext_gutenberg` constructor to `Extension` [API change].
+    + Add `Ext_native_numbering` constructor to `Extension` [API change]
+      (Nils Carlson).
+
+  * Text.Pandoc.Readers, Text.Pandoc.Writers:
+
+    + Change type of `getReader` and `getWriter` so they return
+      a value in the PandocMonad instance rather than an Either
+      [API change].  Exceptions for unknown formats and unsupported
+      extensions are now raised by these functions.
+
+  * Text.Pandoc.App
+
+    + Change `optMetadataFile` type from `Maybe FilePath` to `[FilePath]`
+      (Owen McGrath, #5702) [API change].
+
+  * Text.Pandoc.Logging:
+
+    + Add `CouldNotDeduceFormat` constructor to `LogMessage` [API change].
+      Issue this warning when we're falling back to markdown or
+      html because we don't recognize the extension of the input or
+      output files.
+    + Clarify warning for missing title (#5760).
+    + Add `UnusualConversion` constructor to `LogMessage` [API change]
+      (Mauro Bieg, #5736).  Emit warning on `-f latex -o out.pdf`.
+
+  * Lua filters:
+
+    + Improve function documentation (Albert Krewkinkel).
+    + Traverse nested blocks and inlines in correct order (Albert
+      Krewinkel, #5667). Traversal methods are updated to use the new
+      Walk module so that sequences with nested Inline (or Block) elements
+      are traversed in the order in which they appear in the linearized
+      document.
+    + New unexported module `Text.Pandoc.Lua.Walk` (Albert Krewinkel).
+      Lua filters must be able to traverse sequences of AST
+      elements and to replace elements by splicing sequences back
+      in their place. Special `Walkable` instances can be used for
+      this; those are provided in a new module
+      `Text.Pandoc.Lua.Walk`.
+    + `Attr` values can now be given as normal Lua tables (Albert
+      Krewinkel, #5744).  This can be used as a convenient alternative
+      to constructing `Attr` values with `pandoc.Attr`. Identifiers
+      are taken from the `id` field, classes must be given as
+      space separated words in the `class` field. All remaining fields
+      are included as attributes. With this change, the following lines
+      now create equal elements:
+      ```
+      pandoc.Span('test', {id = 'test', class = 'a b', check = 1})
+      pandoc.Span('test', pandoc.Attr('test', {'a','b'}, {check = 1}))
+      ```
+      This also works when using the *attr* setter:
+      ```
+      local span = pandoc.Span 'text'
+      span.attr = {id = 'test', class = 'a b', check = 1}
+      ```
+      Furthermore, the *attributes* field of AST elements can now be a
+      plain key-value table even when using the `attributes` accessor:
+      ```
+      local span = pandoc.Span 'test'
+      span.attributes = {check = 1}   -- works as expected now
+      ```
+    + Export `make_sections`, remove `hierarchicalize`. Lua filters that
+      use `hierarchicalize` will need to be rewritten to use
+      `make_sections`.
+    + Add a `clone()` method to all AST elements (Albert Krewinkel, #5568).
+    + Fix Lua function names in pandoc.system (niszet). Change
+      `get_current_directory` to `get_working_directory` and
+      `with_temp_directory` to `with_temporary_directory`, to
+      conform to the manual.
+
+  * Text.Pandoc.Error:
+
+    + Add constructors `PandocUnknownReaderError`,
+      `PandocUnknownWriterError`, `PandocUnsupportedExtensionError`.
+      [API change].
+    + Better message for `PandocShouldNeverHappenError`.
+    + Better message for `PandocTemplateError`.
+
+  * Text.Pandoc.Emoji:
+
+    + Update emoji list (#5666). Done using new `tools/emojis.hs`,
+     which uses the list from the gem GitHub uses. Future updates
+     can be done with this tool.
+
+  * Text.Pandoc.PDF:
+
+    + Pass value of `--dpi` to `rsvg-convert` when converting SVG to PDF
+      in the process of creating a PDF (#5721).
+
+  * Text.Pandoc.Shared:
+
+    + Replace `Element` and `makeHierarchical` with `makeSections`.
+      Now that we have Divs, we can use them to represent the
+      structure of sections, and we don't need a special Element type.
+      `makeSections` reorganizes a block list, adding Divs with class
+      `section` around sections, and adding numbering if needed.
+      This change also fixes some longstanding issues recognizing section
+      structure when the document contains Divs (#3057, see also #997).
+    + Remove `Element` type [API change]
+    + Remove `makeHierarchicalize` [API change]
+    + Add `makeSections` [API change]
+    + Export `deLink` [API change]
+    + Make `filterIpynbOutput` strip ANSI escapes from code in output
+      for non-ipynb formats, when the default "best" option is used with
+      `--ipynb-output` (#5633).
+    + Fix `camelCaseToHyphenated` so it handles `ABCDef` better.
+    + Improve `isTight` (#5857).  If a list has an empty item,
+      this should not count against its being a tight list.
+    + Export `htmlSpanLikeElements` [API change] (Daniele D'Orazio, #5796).
+      This is a mapping of HTML span-like elements that are internally
+      represented as a Span with a single class.
+    + Change the implementation of `htmlSpanLikeElements` to retain
+      classes and attributes (#5882, Florian Beeres).
+
+  * Text.Pandoc.Slides: recognize content in Divs when determining
+    slide level.
+
+  * Text.Pandoc.SelfContained:
+
+    + Omit content-type on type attribute for `<style>` (#5725).
+      It doesn't seem to be valid for HTML5, and as a result Chrome
+      ignores the style element.
+
+  * Text.Pandoc.Pretty has been removed [API change].
+    We now use the new external doclayout module instead.
+
+  * Text.Pandoc.Writers.Shared:
+
+    + Remove `metaToJSON`, `metaToJSON'` [API change].
+    + Modify `addVariablesToContext`, `defField`, `setField`, `getField`,
+     `resetField` to work with Context rather than JSON values. [API change]
+    + Export new function `endsWithPlain` [API change].
+    + Change `gridTables` so it does better at keeping the widths of
+      columns (#4320) and does better at figuring out column widths
+      when no widths are given (#5899).
+
+  * Text.Pandoc.Options
+
+    + Change type of `writerTemplate` to `Maybe Template` instead
+      of `Maybe String`.
+    + Change To/FromJSON instances for `HTMLMathMethod`, `CiteMethod`,
+      `ObfuscationMethod`, `TrackChanges`, `WrapOption`,
+      `TopLevelDivision`, `ReferenceLocation`, `HTMLSlideVariant` (#5790).
+      In each case we use lowercase (or hyphenated lowercase) for
+      constructors to line up more closely with command-line option
+      values.  This is a breaking change for those who manually decode or
+      encode JSON for these data types (e.g. for `ReaderOptions` or
+      `WriterOptions`).
+
+  * Text.Pandoc.Filters:
+
+    + Add `FromYAML` instance for `Filter`.
+    + `applyFilters`: Add and apply filters in order (not reversed)
+      This changes `applyFilters` from Text.Pandoc.Filter so
+      that it does a left fold rather than a right fold, applying
+      the filters in the order listed.
+
+  * Text.Pandoc.XML:
+
+    + Change `toEntities` to emit numerical hex character references
+      (#5718).
+
+  * Text.Pandoc.Highlighting:
+
+    + Add additional listings languages (Wandmalfarbe).
+
+  * Text.Pandoc.MediaBag:
+
+    + Some of the types using Strings were switched to use FilePath instead
+      (Christian Despres, #5884).
+
+  * Text.Pandoc.Templates:
+
+    + Don't import/export `varListToJSON` [API change].  It is removed in
+      doctemplates >= 0.3.
+    + Change type of `renderTemplate'` [API change].  Return value is
+      now Text rather than being polymorphic.  This makes room for
+      upcoming removal of the `TemplateTarget` class from doctemplates.
+
+  * Text.Pandoc.App.Opt [API changes]:
+
+    + More convenient To/FromJSON instances.  Make the field names
+      like `strip-empty-paragraphs` rather than `optStripEmptyParagraphs`.
+      Anyone who is using JSON serialization of Opt will need to adjust
+      things accordingly.
+    + Change `optHighlightStyle` to a `Maybe String` instead of
+      `Maybe Style`.  Do the parsing/loading of themes later, after
+      option parsing.
+    + Remove `optBaseHeaderLevel` from `Opt`.  We now just use
+      `optShiftHeadingLevelBy`, to avoid redundancy.
+    + Change `optShiftHeadingLevel` to `optShiftHeadingLevelBy` to
+      match the option.
+    + Custom FromJSON instance for `LineEnding`, so either `CRLF`
+      or `crlf` will work.
+    + Change `optVariables` from `[(String, String)]` to `Context Text`.
+    + Change `optMetadata` to `Meta`, to allow structured values.
+      The current behavior of the `--metadata` option stays the same.
+    + Rename `optReader`, `optWriter` as `optFrom`, `optTo`.
+    + Add `FromYAML` instances to `Opt` and to all subsidiary types.
+    + Rename `optMetadataFile` to `optMetadataFiles`.
+    + Rename `optPDFEngineArgs` to `optPDFEngineOpts`.
+    + Rename `optWrapText` to `optWrap`.
+    + Add `IpynbOutput` enumerated type: use this instead of
+      a string for `optIpynbOutput`.
+    + Change optInputFiles to a `Maybe [FilePath]` (#5888) [API change].
+      `Nothing` means: nothing specified.
+      `Just []` means: an empty list specified (e.g. in defaults).
+    + List fields in Opt so they aren't reversed (#5881) [API change].
+      Previously `optIncludeInHeader`, etc. were in reverse order.
+    + The `sourcefile` variable is now always a list. It used to be
+      sometimes a string, sometimes a list (when there was more than one).
+
+  * Template changes:
+
+    + default.latex: added code for `cslreferences` environment,
+      to be used for pandoc-citeproc references. A `csl-hanging-indent`
+      variable (set automatically if there is a `hanging-ident`
+      class on the references Div) controls whether contents of this
+      environment receive a hanging indent.
+    + default.latex: Add `space` as default option for xeCJK, so that
+      spaces between words are preserved (#5855, jeongminkim-islab).
+      This is necessary for Korean.
+    + default.latex: Remove include of `grffile` (#5848).
+      This package used to be needed for proper handling of image filenames
+      containing periods (in addition to the period before the extension).
+      It no longer works with the latest LaTeX kernel and graphicx,
+      so we have removed it. Future versions of graphicx will handle
+      these filenames without the need for `grffile`.
+    + default.context: add a saner default for page numbers.
+      Previously they appeared centered at the top of the page;
+      now we put them centered at the bottom, unless the `pagenumbering`
+      variable is set.
+    + default.context: define a start-stop-pair `cslreferences` to
+      allow for hanging indents in the bibliography (#5875, Denis Maier).
+    + default.ms: update defaults.  Use Palatino font, use slightly
+      wider interparagraph space, don't indent paragraphs,
+      and put page numbers on the bottom.  This brings ms output
+      closer to default LaTeX output.
+    + default.revealjs: add navigationMode (Mauro Bieg, #5657).
+    + default.muse: handle multiple authors better.
+    + docbook4, docbook5 templates: add indentation to body.
+    + HTML-based templates: use `styles.html` partial to avoid
+      code duplication.
+    + HTML-based templates: change indentation of styles in template.
+
+  * reference.docx (#5820):
+
+    + Change Block Text (block quote) style so that the same font
+      is used as in the body text, and the block text is indented
+      left and right.
+    + All headings now have a uniform color.
+    + Level-1 headings no longer set `w:themeShade="B5"`.
+    + Level-2 headings are now 14 point rather than 16 point.
+    + Level-3 headings are now 12 point rather than 14 point.
+    + Level-4 headings are italic rather than bold.
+
+  * epub.css: Add CSS for hanging-indent div to support pandoc-citeproc's
+   new hanging indents.
+
+  * pandoc.cabal:
+
+    + Repeat ghc-options in all stanzas.
+    + Remove conditionals for ghc < 8 (Albert Krewinkel, #5693).
+    + Compile with `-Wcpp-undef` and `-fhide-source-paths` when possible
+      (Albert Krewinkel).
+    + Add cabal.project to extra-source-files (Albert Krewinkel).
+    + Add dependency on skylighting-core (#5729). Even though it shouldn't
+      be needed, some tools require it.
+    + Require latest pandoc-types, texmath, skylighting, haddock-library.
+    + Ensure TemplateHaskell is added to other-extensions when it is
+      used (Vanessa McHale, #5728).
+    + Remove `derive_json_via_th` flag; always use TH.  This cuts down
+      on code duplication and reduces the chance for errors.  See #4083.
+
+  * Makefile:
+
+    + Add ghci target.
+    + Add ghcid target.
+    + Remove references to obsolete flag (#5694).
+
+  * Benchmarks: fix failure on ipynb.
+
+  * Use MathJax 3 (zorkow).
+
+  * KaTeX math: respect `classoption=fleqn` variable,
+    bump KaTeX version to 0.11.1 (#5815, Mauro Bieg).
+
+  * Fix redundant constraint compiler warnings (Pete Ryland, #5625).
+
+  * Use throwError instead of fail when appropriate.
+
+  * Use Prelude.fail to avoid ambiguity with fail from GHC.Base.
+
+  * Add `diff-zip.sh` to tools (John MacFarlane, Agustín Martín Barbero).
+    This is intended to make it easier to test differences in zip
+    containers, like epub, docx, or odt.
+
+  * Add `.gitattributes` (#5747).  This ensures that the golden files
+    in `test/fb2/reader/` don't have newlines converted. This should fix
+    a test failure on GitHub CI with Windows.
+
+  * Reorder options in `--help`.
+
+  * Revise code for HsYAML-0.2.0.0 (@vijayphoenix, #5704).
+
+  * Remove blank line in code example in Haddocks (Leif Metcalf, #5679).
+
+  * Fix trypandoc with `getReader`/`getWriter` changes.
+
+  * Allow building pandoc with GHC 8.8.
+
+  * linux tarball: add architecture `-amd64` to filename.
+    Now it will be: `pandoc-VERSION-linux-ARCH.tar.gz`.
+
+  * MANUAL.txt:
+
+    + Add section for exit codes.
+    + Document some pptx limitations in slide show section:
+      No incremental display (#5689).  No pause with `. . .` (#5701).
+    + reveal.js flags (Mauro Bieg, #5653).
+    + Document addition of `data-` prefix to unknown attributes in HTML5.
+    + Link to YAML spec (Mauro Bieg, #5687).
+    + Fix capitalization of "Linux" (#5859, Marcus Stollsteimer).
+    + Use a table for exit codes.
+    + Put all template variable docs into one section.
+    + Use ATX headers consistently.
+    + Add fuller documentation of templates (#5779), including
+      new template syntax, partials, etc.
+    + Add documentation for the variable `hyperrefoptions` (Wandmalfarbe).
+    + Clarify when macro definitions are passed as raw latex.
+      In Markdown input, they are always passed through.  In LaTeX, only if
+      `latex_macros` is disabled.
+    + Clarify that `--dpi` provides a default and doesn't override
+      dpi values specified in the images themselves (#5721).
+    + Document how to use custom writers with `--standalone` (#5866).
+    + Clarify `--preserve-tabs` default.
+
+  * INSTALL.md:
+
+    + Fix instructions for libicu.
+    + Add Void Linux instructions (Volodymyr Kozachnyskyi).
+
+  * CONTRIBUTING.md:
+
+    + Add information on tests (Agustín Martín Barbero, #5652).
+    + Add information about command test naming to CONTRIBUTING (Florian B).
+
+  * Fix typos in changelog and comments (#5896, Brian Wignall).
+
+  * doc/lua-filters.md:
+
+    + Fix mistakes in mediabag module docs (#5851, Albert Krewinkel).
+    + Improve metadata replacement example in lua-filters doc (#5851).
+    + Mention which Lua version is shipped with pandoc (Albert Krewinkel,
+      #5892).
+
+## pandoc 2.7.3 (2019-06-11)
+
+  * Add `jira` (Atlassian's Jira wiki markup) as output format (#2497,
+    Albert Krewinkel).
+
+  * Add `tex_math_dollars` to `multimarkdownExtensions` (#5512).
+    This form is now supported in multimarkdown,
+    in addition to `tex_math_double_backslash`.
+
+  * Fix `--self-contained` so it works when output format has extensions.
+    Previously if you used `--self-contained` with `html-smart` or
+    `html+smart`, it wouldn't work.
+
+  * Add template variable `curdir` with working directory
+    from which pandoc is run (#5464).
+
+  * Markdown reader: don't create implicit reference for empty header
+    (#5549).
+
+  * Muse reader: allow images inside link descriptions (Alexander Krotov).
+
+  * HTML reader: epub related fixes.
+
+    + With epub extensions, check for `epub:type` in addition to `type`.
+    + Fix problem with noteref parsing which caused block-level
+      content to be eaten with the noteref.
+    + Rename `pAnyTag` to `pAny`.
+    + Refactor note resolution.
+    + Trim definition list terms (Alexander Krotov).
+
+  * LaTeX reader:
+
+    + Add braces when resolving `\DeclareMathOperator`
+      (#5441).  These seem to be needed for xelatex but not pdflatex.
+    + Allow newlines in `\mintinline`.
+    + Pass through unknown listings language as class (#5540).
+      Previously if the language was not in the list of languages supported
+      by listings, it would not be added as a class, so highlighting
+      would not be triggered.
+    + `rawLaTeXInline`: Include trailing `{}`s in raw latex commands (#5439).
+      This change affects the markdown reader and other readers that allow raw
+      LaTeX.  Previously, trailing `{}` would be included for unknown
+      commands, but not for known commands.  However, they are sometimes used
+      to avoid a trailing space after the command.  The chances that a `{}`
+      after a LaTeX command is not part of the command are very small.
+
+  * MediaWiki reader: handle multiple attributes in table row (#5471,
+    chinapedia).
+
+  * Docx reader: Add support for `w:rtl` (#5545).  Elements with this
+    property are put into Span inlines with `dir="rtl"`.
+
+  * DocBook reader: Issue `IgnoredElement` warnings.
+
+  * Org reader (Albert Krewinkel):
+
+    + Fix planning elements in headers level 3 and higher
+      (#5494).  Planning info is now always placed before
+      the subtree contents.  Previously, the planning info was placed after
+      the content if the header's subtree was converted to a list, which
+      happens with headers of level 3 and higher per default.
+    + Omit, but warn about unknown export options.  Unknown export
+      options are properly ignored and omitted from the output.
+    + Prefer plain symbols over math symbols (#5483).
+      Symbols like `\alpha` are output plain and unemphasized, not as math.
+    + Recognize emphasis after TODO/DONE keyword (#5484).
+
+  * FB2 reader:
+
+    + Skip unknown elements rather than throwing errors (#5560).
+      Sometimes custom elements are used (e.g. `id` element
+      inside `author`); previously the reader would halt with an error.
+      Now it skips the element and issues an `IgnoredElement` warning.
+    + Parse notes (#5493, Alexander Krotov).
+    + Internal improvements (Alexander Krotov).
+
+  * OpenDocument writer:  Roll back automatic figure/table numbering
+    (#5474).  This was added in pandoc 2.7.2, but it makes it impossible
+    to use pandoc-crossref. So this has been rolled back for now,
+    until we find a good solution to make this behavior optional
+    (or a creative way to let pandoc-crossref and this feature
+    to coexist).
+
+  * New module Text.Pandoc.Writers.Jira, exporting `writeJira` [API
+    change] (Albert Krewinkel).
+
+  * EPUB writer:
+
+    + Don't include 'landmarks' if there aren't any.
+      Previously we could get an empty ol element, which caused
+      validation errors with epubcheck.
+    + Ensure unique ids for styleesheets in content.opf (#5463).
+    + Make stylesheet link compatible with kindlegen (#5466,
+      Eric Schrijver).  Pandoc omitted `type="text/css"` from both
+      `<style>` and `<rel="stylesheet">` elements in all templates, which
+      is valid according to the spec. However, Amazon’s kindlegen software
+      relies on this attribute on `<link>` elements when detecting
+      stylesheets to include.
+
+  * HTML writer:
+
+    + Output video and audio elements depending on file
+      extension of the image path (Mauro Bieg).
+    + Emit empty alt tag in figures (#5518, Mauro Bieg).
+      The same text is already in the <figcaption> and
+      screen-readers would read it twice, see #4737.
+    + Don't add variation selector if it's already there.
+      This fixes round-trip failures.
+    + Prevent gratuitous emojification on iOS (#5469).
+      iOS chooses to render a number of Unicode entities, including '↩', as
+      big colorful emoji.  This can be defeated by appending Unicode
+      VARIATION SELECTOR-15'/'VARIATION SELECTOR-16'.  So we now append this
+      character when escaping strings, for both '↩' and '↔'.  If other
+      characters prove problematic, they can simply be added to
+      `needsVariationSelector`.  + Add `class="heading"` to level 7+ Headers
+      rendered as `<p>` elements (#5457).
+
+  * RST writer: treat Span with no attributes as transparent (#5446).
+    Previously an Emph inside a Span was being treated as
+    nested markup and ignored.  With this patch, the Span
+    is just ignored.
+
+  * LaTeX writer:
+
+    + Include inline code attributes with `--listings` (#5420).
+    + Don't produce columns environment unless beamer (#5485).
+    + Fix footnote in image caption.  Regression: the fix for #4683 broke
+      this case.
+    + Don't highlight code in headings (#5574).  This causes
+      compilation errors.
+    + Use `\mbox` to get proper behavior inside `\sout` (#5529).
+
+  * EPUB writer: Fix document section assignments (#5546).
+    For example, introduction should go in bodymatter, not frontmatter, and
+    epigraph, conclusion, and afterward should go in bodymatter, not
+    backmatter.  For the full list of assignments, see the manual.
+
+  * Markdown writer:
+
+    + Add backslashes to avoid unwanted interpretation of
+      definition list terms as other kinds of block (#554).
+    + Ensure the code fence is long enough (#5519).
+      Previously too few backticks were used when the code block
+      contained an indented line of backticks.  (Ditto tildes.)
+    + Handle labels with integer names (Jesse Rosenthal, #5495).
+      Previously if labels had integer names, it could produce a conflict
+      with auto-labeled reference links. Now we test for a conflict and
+      find the next available integer.  This involves adding a new state
+      variable `stPrevRefs` to keep track of refs used in other document
+      parts when using `--reference-location=block|section`
+
+  * Textile writer: fix closing tag for math output (Albert Krewinkel).
+    Opening and closing tag for math output match now.
+
+  * Org writer: always indent src blocks content by 2 spaces (#5440, Albert
+    Krewinkel).  Emacs always uses two spaces when indenting the content of
+    src blocks, e.g., when exiting a `C-c '` edit-buffer. Pandoc used to
+    indent contents by the space-equivalent of one tab, but now always uses
+    two spaces, too.
+
+  * Asciidoc writer:
+
+    + Use `` `+...+` `` form for inline code.
+      The old `` `a__b__c` `` yields emphasis inside code in asciidoc.
+      To get a pure literal code span, use `` `+a__b__c+` ``.
+    + Use proper smart quotes with asciidoctor (#5487).
+      Asciidoctor has a different format for smart quotes.
+    + Use doubled ## when necessary for spans (#5566).
+    + Ensure correct nesting of strong/emph (#5565): strong
+      must be the outer element.
+
+  * JATS writer:
+
+    + Wrap elements with p when needed (#5570).  The JATS spec restricts
+      what elements can go inside `fn` and `list-item`.  So we wrap other
+      elements inside `<p specific-use="wrapper">` when needed.
+    + Properly handle footnotes (#5511) according to "best practice."
+      (Group them at the end in `<fn-group>` and use `<xref>` elements
+      to link them.)
+    + Fix citations with PMID so they validate (#5481).  This includes
+      an update to data/jats.csl.
+    + Ensure validity of `<pub-date>` by parsing the date and
+      extracting year, month, and day, as expected.  Also add an
+      iso-8601-date attribute automatically.
+    + Don't use `<break>` element for LineBreak. It is only
+      allowed in a few special contexts, and not in `<p>` elements.
+    + Don't make `<string-name>` a child of `<string>`, which is illegal.
+
+  * FB2 writer:
+
+    + Do not wrap note references into `<sup>` and brackets
+      (Alexander Krotov).  Existing FB2 readers, such as FBReader, already
+      display links with type="note" as a superscript.
+    + Use genre metadata field (#5478).
+
+  * Muse writer: do not escape empty line after `<br>` (Alexander Krotov).
+
+  * Add unicode code point in "Missing character" warning (#5538).
+    If the character isn't in the console font, the message is pretty useless,
+    so we show the code point for anything non-ASCII.
+
+  * Lua: add Version type to simplify comparisons (Albert Krewinkel).
+    Version specifiers like `PANDOC_VERSION` and `PANDOC_API_VERSION` are
+    turned into `Version` objects. The objects simplify version-appropriate
+    comparisons while maintaining backward-compatibility.
+    A function `pandoc.types.Version` is added as part of the newly
+    introduced module `pandoc.types`, allowing users to create version
+    objects in scripts.
+
+  * pandoc lua module (Albert Krewinkel):
+
+    - Fix deletion of nonexistent attributes (#5569).
+    - Better tests for Attr and AttributeList.
+
+  * pandoc.mediabag lua module (Albert Krewinkel):
+
+    + Add function `delete` for deleting a single item.
+    + Add function `empty` for removing all entries.
+    + Add function `items` for iterating over mediabag.
+
+  * Text.Pandoc.Class: Fix handling of `file:` URL scheme in
+    `downloadOrRead` (#5517, Mauro Bieg).  Previously `file:/`
+    URLs were handled wrongly and pandoc attempted to make HTTP
+    requests, which failed.
+
+  * Text.Pandoc.MIME: add `mediaCategory` [API change] (Mauro Bieg).
+
+  * Text.Pandoc.Shared:
+
+    + Add `onlySimpleTableCells` [API change]
+      (Mauro Bieg) and use this to consolidate simple-table detection
+      (#5524).  This fixes an inconsistency in the HTML reader, which did not
+      treat tables with `<p>` inside cells as simple.
+    + `metaToJSON`: treat digits starting with 0 as a string, not a number
+      (#5479).  This fixes a regression in YAML metadata in pandoc 2.7.2.
+
+  * Text.Pandoc.Logging: Add `IgnoredElement` constructor for
+    `LogMessage`.  `SkippedConetnt` doesn't work for some XML-based
+    readers which don't have access to parsec source positions.
+
+  * Text.Pandoc.Asciify: Add Turkish undotted-i (#5433, Mauro Bieg).
+
+  * Improve output of Lua tests (#5499, Albert Krewinkel).
+    This makes use of tasty-lua, a package to write tests in Lua
+    and integrate the results into Tasty output. Test output becomes
+    more informative: individual tests and test groups become visible
+    in test output. Failures are reported with helpful error messages.
+
+  * Lua: add `pandoc.system` module (#5468, Albert Krewinkel).
+    The `system` Lua module provides utility functions to interact with the
+    operating- and file system. E.g.
+    `print(pandoc.system.get_current_directory())`
+    or
+    ```lua
+        pandoc.system.with_temporary_directory('tikz', function (dir)
+          -- write and compile a TikZ file with pdflatex
+        end)
+    ```
+
+  * LaTeX template: Add pdflang to hypersetup if lang is set (#5443).
+
+  * beamer template: Fix using Beamer with geometry (#5505, Daniel Maslowski).
+    Beamer already loads geometry, so we need to use the `\geometry`
+    command to set geometry options.
+
+  * EPUB2/3 templates: Move inline styles to default epub.css (#5466).
+    NOTE: Those who use a custom CSS stylesheet with EPUB should
+    add these lines:
+
+        code{ white-space: pre-wrap; }
+        span.smallcaps{ font-variant: small-caps; }
+        span.underline{ text-decoration: underline; }
+        q { quotes: "“" "”" "‘" "’"; }
+        div.column{ display: inline-block; vertical-align: top; width: 50%; }
+
+  * reveal.js template:
+
+    + Updates for revealjs 3.8.0 (#5435, ebiim).
+    + Remove reference to head.min.js (#5448, Winnie Hellmann).
+      NOTE: users will need to update reveal.js to at least 3.8.0
+      for their presentations generated with this version of pandoc
+      to work correctly.
+
+  * Text.Pandoc.PDF:
+
+    + Replace `</>` with literal `/` (#5451).
+      We use forward-slash for a directory separator in tmpDir,
+      even on Windows (because that's what tex likes).  So we
+      should not put a backslash between the tmpDir and the
+      filename on Windows.  This is harmless enough in normal
+      Windows setups, but it breaks on Cygwin.
+      Thanks to @cc2x for noticing and diagnosing the problem.
+    + Allow use of `-output-directory` in `--pdf-engine-opt` (#5462).
+      This is currently possible with `mklatex` and `-outdir`, but
+      was not yet possible with xelatex and `-output-directory`.
+    + For PDF via ms/pdfroff, make TOC appear at beginning and in
+      PDF bookmarks (#5553).  Previously the TOC appeared at the end
+      of the document, and was not bookmarked.  To keep it at the end,
+      add `--pdf-engine-opt=--no-toc-relocation` to your command line.
+
+  * Fix broken links in documents (#5473, Shim Myeongseob).
+    Also, use absolute links to pandoc.org when possible, so that
+    the links can be followed by people viewing these documents
+    on GitHub.
+
+  * Improved sample lua tikz filter in lua-filters docs (#5445,
+    Matthew Doty).  There are three changes:
+
+    + It only processes elements which begin with `\begin{tikzpicture}`
+    + It uses pdf2svg instead of imagemagick to preserve fidelity
+    + The images produced have transparent backgrounds
+
+  * MANUAL.txt:
+
+    + Add note about `title-meta`, `author-meta`, `date-meta` (#5486).
+    + Fix typo (#5489, Christian Krause).
+
+  * add test/tables.xwiki to git and pandoc.cabal (#5498, Mauro Bieg).
+
+  * Disable missing-home-modules warning in `stack.yaml`.
+    Otherwise `stack ghci` fails.
+
+
+## pandoc 2.7.2 (2019-04-05)
+
+  * Add XWiki writer (#1800, Derek Chen-Becker).
+    Add `Text.Pandoc.Writers.XWiki`, exporting `writeXWiki` [API change].
+
+  * Dokuwiki Reader: parse single curly brace (#5416, Mauro Bieg).
+
+  * Vimwiki reader: improve handling of internal links (#5414).
+    We no longer append `.html` to link targets, and we add a title
+    `wikilink`.  This mirrors behavior of other wiki readers.  Generally
+    the `.html` extension is not wanted.  It may be important for output
+    to HTML in certain circumstances, but it can always be added using a
+    filter that matches on links with title `wikilink`.
+
+    If your workflow requires the current behavior, here is a lua filter
+    that will add the `.html` extension:
+
+    ```lua
+    function Link(el)
+      if el.title == 'wikilink' then
+        el.target = el.target .. ".html"
+      end
+      return el
+    end
+    ```
+  * ipynb reader:
+
+    + Use format `ipynb` for raw cell where no format given.
+    + Avoid introducing spurious `.0` on integers in metadata.
+
+  * Markdown reader: fenced div takes priority over setext header.
+
+  * HTML reader: read `data-foo` attribute into `foo` (#5392).
+    The HTML writer adds the `data-` prefix for HTML5 for nonstandard
+    attributes.  But the attributes are represented in the AST without
+    the `data-` prefix, so we should strip this when reading HTML.
+
+  * LaTeX reader: Improve autolink detection (#5340).
+
+  * PowerPoint writer (Jesse Rosenthal):
+
+    + Expand builtin reference doc to model all layouts.
+      The previous built-in reference doc had only title and content
+      layouts. Add in a section-header slide and a two-content slide, so
+      users can more easily modify it to build their own templates.
+    + Always open up in slide view.  When editing a
+      template/reference-doc, the user might be in Master view, but when
+      producing a slide show, it is assumed that slide view will be
+      desired.
+    + Remove `handoutsMasterList` from template presentation.xml
+    + Fix numerous errors in templating (#5402). Previously, some templates
+      produced by Office 365 (MacOS) would not render with `--reference-doc`
+      correctly. We now apply correct shapes for content, and build
+      shape trees correctly.
+    + Make default placeholder type for template lookup.
+    + Apply speaker notes to metadata slide if applicable.
+    + Test for speaker notes after breaking header.
+    + Correctly handle notes after section-title header.
+      Previously, if notes came after a section-title header (ie, a level-1
+      header in a slide-level=2 presentation), they would go on the next
+      slide. This keeps them on the slide with the header.
+    + Internal improvements.
+
+  * ipynb writer:
+
+    + Use format `ipynb` for raw cell where no format given.
+      According to nbformat docs, this is supposed to render in every
+      format.  We don't do that, but we at least preserve it as a raw
+      block in markdown, so you can round-trip.
+    + Consolidate adjacent raw blocks.  Sometimes pandoc creates two
+      HTML blocks, e.g. one for the open tag and one for a close tag.
+      If these aren't consolidated, only one will show up in output cell.
+    + Fixed carry-over of nbformat from metadata.
+    + Preserve `nbformat_minor` if it's given.  This helps with round-tripping.
+
+  * LaTeX writer:
+
+    + Avoid inadvertently creating ?` or !` ligatures (#5407).
+      These are upside down ? and !, resp.
+    + Fix footnotes in table caption and cells (#5367).  This fixes a
+      bug wherein footnotes appeared in the wrong order, and with
+      duplicate numbers, when in table captions and cells.
+      We now use regular `\footnote` commands, even in the table
+      caption and the minipages containing cells. Apparently
+      longtable knows how to handle this.
+
+  * HTML writer: Don't add data- prefix to RDFa attributes (#5403).
+
+  * JATS writer: Ensure that plain strings go inside `<pub-id>` tag (#5397).
+
+  * Markdown writer:
+
+    + Better rendering of numbers (#5398).  If the number is integral,
+      we render it as an integral not a float.
+    + Proper rendering of empty map in YAML metadata (#5398).  Should
+      be `{}`, not empty string.
+    + Properly escape attributes in Markdown writer (#5369).
+    + Be sure implicit figures work in list contexts (#5368).
+      Previously they would sometimes not work: e.g., when they
+      occurred in final paragraphs in lists that were originally
+      parsed as Plain and converted later using PlainToPara.
+
+  * Docx writer: Use `w:br` without attributes for line breaks (#5377).
+    We previously added the attribute `type="textWrapping"`, but
+    this causes problems on Word Online.
+
+  * LaTeX template (Andrew Dunning):
+
+    + Ensure correct heading/table order (#5365).  Improve workaround
+      (#1658) for tables following headings.  The new solution works whether
+      or not the `indent` variable is enabled.
+    + Remove `subparagraph` variable. The default is now to use run-in
+      style for level 4 and 5 headings (`\paragraph` and `\subparagraph`).
+      To get the previous default behavior (where these were formatted as
+      blocks, like `\subsubsection`), set the `block-headings` variable.
+    + Add pandoc to PDF metadata (#5388).
+    + Group graphics-related code (#5389).
+    + Move `\setstretch` after front matter (#5179).  Ensures that
+      `\maketitle`, `\tableofcontents`, and so forth are not affected by
+      changes to line spacing.
+
+  * Update data/jats.csl to avoid commas between name-part elements
+    (#5397).
+
+  * Add support for golang (`go`) with `--listings` (#5427).
+
+  * Text.Pandoc.Shared - improve `metaToJSON` behavior with numbers.
+    We now do a better job marshalling numbers from MetaString
+    or MetaInlines into JSON Number.
+
+  * Text.Pandoc.Writers.Shared: `metaValueToJSON`: use Number Values for
+    integers.  Pandoc's MetaValue doesn't have a distinguished number type,
+    so numbers are put in MetaStrings.  If the MetaString consists
+    entirely of digits, we convert it to a Number.  We should probably
+    consider adding a MetaNumber constructor to MetaValue, for better
+    round-tripping with JSON etc.  This change aids round-tripping in
+    ipynb metadata fields, like `toc_depth`.
+
+  * Text.Pandoc.Class: `fetchItem`: don't treat UNC paths as
+    protocol-relative URLs (#5127).  These are paths beginning `//?/UNC/...`.
+
+  * Text.Pandoc.ImageSize: Improve `pdfSize` so it handles
+    a wider range of PDFs (#4322, with help from Richard Davis).
+
+  * Text.Pandoc.Pretty: avoid stack overflow by using strict sum (#5401).
+
+  * Fix harmless error in file-scope code (#5422).
+
+  * MANUAL.txt:
+
+    + Improve 'header' and 'heading' usage (#5423, Andrew
+      Dunning).  The term 'header' was being used where 'heading'
+      is more appropriate.
+    + Add paragraph on options affecting markdown in ipynb.
+
+  * stack.yaml - remove -Wmissing-home-modules
+    This seems to cause problems with stack ghci.  Remove RTS options.
+
+  * Add ghc-options to cabal.project.
+
+  * appveyor.yml - use ghc 8.6.4.  Fixes segfault issues on Windows (#5037).
+
+  * linux build process: Remove clone of pandoc-citeproc (#5366).
+    It wasn't being used; cabal.project specifies the version to use.
+
+## pandoc 2.7.1 (2019-03-14)
+
+  * Add tectonic as an option for --pdf-engine (#5345, Cormac Relf).
+    Runs tectonic on STDIN instead of a temporary .tex file, so that it
+    looks in the working directory for `\include` and `\input` like the rest
+    of the engines.  Allows overriding the output directory
+    args with `--pdf-engine-opt=--outdir --pdf-engine-opt="$DIR"`.
+
+  * Allow `-o/--output` to be used with `--print-default-data-file`,
+    `--print-highlighting-style`, `--print-default-template`.
+    Note that `-o` must occur BEFORE the `--print*` command on the command
+    line (this is documented, #5357).
+
+  * LaTeX reader:
+
+    + Support `\underline`, `\ul`, `\uline` (#5359, Paul
+      Tilley).  These are parsed as a Span with class `underline`, as
+      with other readers.
+    + Ensure that `\Footcite` and `\Footcites` get put in a note.
+
+  * ipynb reader:
+
+    + Remove sensitivity to `raw_html`, `raw_tex` extensions.
+      We now include every output format. Pruning is handled by
+      `--ipynb-output`.
+    + Better handling of cell metadata.  We now include even complex cell
+      metadata in the Div's attributes (as JSON, in complex cases, or
+      as plain strings in simple cases).
+
+  * ipynb writer:
+
+    + Recurse into native divs for output cell data (#5354).
+    + Render cell metadata fields from div attributes.
+
+  * Docx writer: avoid extra copy of abstractNum and num elements
+    in numbering.xml.  This caused pandoc-produced docx files to
+    be uneditable using Word Online (#5358).
+
+  * Markdown writer: improve handling of raw blocks/inline.
+    We now emit raw content using `raw_attribute` when no more
+    direct method is available.  Use of `raw_attribute` can be
+    forced by disabling `raw_html` and `raw_tex`.
+
+  * LaTeX writer: Add classes for frontmatter support (#5353, Andrew Dunning)
+    and remove frontmatter from `scrreprt`.
+
+  * LaTeX template:
+
+    + Improve readability (#5363, Andrew Dunning).
+    + Robust section numbering removal (#5351, Andrew Dunning).
+      Ensures that section numbering does not reappear with custom
+      section levels.  See <https://tex.stackexchange.com/questions/473653/>.
+    + Better handling of front/main/backmatter (#5348).
+      In pandoc 2.7 we assumed that every class with chapters would accept
+      `\frontmatter`, `\mainmatter`, and `\backmatter`.  This is not so (e.g.
+      report does not).  So pandoc 2.7 breaks on report class by including an
+      unsupported command.  Instead of the `book-class` variable, we use two
+      variables, `has-chapters` and `has-frontmatter`, and set these
+      intelligently in the writer.
+
+  * Text.Pandoc.Shared: Improve `filterIpynbOutput`.  Ensure that
+    images are prioritized over text. `best` should include everything
+    for ipynb.
+
+  * Tests.Old: specify `--data-dir=../data` to ensure tests can find
+    data files even if they haven't been installed.  Remove old
+    `pandoc_datadir` environment variable, which hasn't done anything for a
+    long time.
+
+  * MANUAL.txt: Add recommendation to use `raw_attribute` with ipynb (#5354).
+
+  * Use cmark-gfm-hs 0.1.8 (note that 0.1.7 is buggy).
+
+  * Use latest pandoc-citeproc, texmath.
+
+
+## pandoc 2.7 (2019-03-03)
+
+  * 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 selected extensions (#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 (2019-01-30)
+
+  * Support ipynb (Jupyter notebook) as input and output format.
+
+    + Add `ipynb` as input and output format (extension `.ipynb`).
+    + Added Text.Pandoc.Readers.Ipynb [API change].
+    + Added Text.Pandoc.Writers.Ipynb [API change].
+    + Add `PandocIpynbDecodingError` constructor to Text.Pandoc.Error.Error
+      [API change].
+    + Depend on ipynb library.
+    + Note: there is no template for ipynb.
+
+  * Add DokuWiki reader (#1792, Alexander Krotov).  This adds
+    Text.Pandoc.Readers.DokuWiki [API change], and adds `dokuwiki`
+    as an input format.
+
+  * Implement task lists (#3051, Mauro Bieg). Added `task_lists`
+    extension. Task lists are supported from markdown and gfm input.
+    They should work, to some degree, in all output formats, though in
+    most formats you'll get a bullet list with a unicode character for
+    the box. In HTML, you get checkboxes and in LaTeX/PDF output, a
+    box is used as the list marker. API changes:
+
+    + Added constructor `Ext_task_lists` to `Extension`.
+    + Added `taskListItemFromAscii` and `taskListItemToAscii` to
+      Text.Pandoc.Shared.
+
+  * Allow some command line options to take URL in addition to FILE.
+    `--include-in-header`, `--include-before-body`, `--include-after-body`.
+
+  * HTML reader:
+
+    + Handle empty `start` attribute (see #5162).
+    + Treat `textarea` as a verbatim environment (#5241) and preserve
+      spacing.
+
+  * RST reader:
+
+    + Change treatment of `number-lines` directive (Brian Leung,
+      #5207). Directives of this type without numeric inputs should
+      not have a `startFrom` attribute; with a blank value, the
+      writers can produce extra whitespace.
+    + Removed superfluous `sourceCode` class on code blocks (#5047).
+    + Handle `sourcecode` directive as synonym for `code` (#5204).
+
+  * Markdown reader:
+
+    + Remove `sourceCode` class for literate Haskell code blocks
+      (#5047). Reverse order of `literate` and `haskell` classes on
+      code blocks when parsing literate Haskell, so `haskell` is
+      first.
+    + Treat `<textarea>` as a verbatim environment (#5241).
+
+  * Org reader:
+
+    + Handle `minlevel` option differently (#5190, Brian Leung).
+      When `minlevel` exceeds the original minimum level observed in
+      the file to be included, every heading should be shifted
+      rightward.
+    + Allow for case of `:minlevel == 0` (#5190).
+    + Fix treatment of links to images (#5191, Albert Krewinkel).
+      Links with descriptions which are pointing to images are no
+      longer parsed as inline images, but as links.
+    + Add support for #+SELECT_TAGS (Brian Leung).
+    + Separate filtering logic from conversion function (Brian Leung).
+
+  * TWiki reader: Fix performance issue with underscores (#3921).
+
+  * MediaWiki reader: use `_` instead of `-` in auto-identifiers (#4731).
+    We may not still be exactly matching mediawiki's algorithm.
+
+  * LaTeX reader:
+
+    + Remove `sourceCode` class for literate Haskell code blocks
+      (#5047). Reverse order of `literate` and `haskell` classes on
+      code blocks when parsing literate Haskell, so `haskell` is
+      first.
+    + Support `\DeclareMathOperator` (#5149).
+    + Support `\inputminted` (#5103).
+    + Support `\endinput` (#5233).
+    + Allow includes with dots like `cc_by_4.0`.  Previously the `.0`
+      was interpreted as a file extension, leading pandoc not to add
+      `.tex` (and thus not to find the file).  The new behavior matches
+      tex more closely.
+
+  * Man reader:
+
+    + Use `mapLeft` from Shared instead of defining own.
+
+  * Docx reader (Jesse Rosenthal):
+
+    + Handle level overrides (#5134).
+
+  * Docx writer:
+
+    + Support custom properties (#3024, #5252, Agustín Martín Barbero).
+      Also supports additional core properties:  `subject`, `lang`,
+      `category`, `description`.
+    + Make Level into a real type, instead of an alias for a tuple
+      (Jesse Rosenthal).
+
+  * ICML writer (Mauro Bieg):
+
+    + Support custom-styles (#5137, see #2106).
+    + Support unnumbered headers (#5140).
+
+  * Texinfo writer: Use header identifier for anchor if present (#4731).
+    Previously we were overwriting an existing identifier with a new one.
+
+  * Org writer: Preserve line-numbering for example and code blocks
+    (Brian Leung).
+
+  * Man/Ms writers: Don't escape `-` as `\-`. The `\-` gets rendered
+    in HTML and PDF as a unicode minus sign.
+
+  * Ms writer: Ensure we have a newline after .EN in display math (#5251).
+
+  * RST writer: Don't wrap simple table header lines (#5128).
+
+  * Asciidoc writer: Shorter delimiters for tables, blockquotes
+    (#4364). This matches asciidoctor reference docs.
+
+  * Dokuwiki writer: Remove automatic `:` prefix before internal image
+    links (#5183, Damien Clochard).  This prevented users from making
+    relative image links.
+
+ *  Zimwiki writer: remove automatic colon prefix before internal
+    images (#5183, Damien Clochard).
+
+  * MediaWiki writer: fix caption, use 'thumb' instead of 'frame'
+    (#5105). Captions used to have the word 'caption' prepended; this
+    has been removed. Also, 'thumb' is used instead of 'frame' to
+    allow images to be resized.
+
+  * reveal.js writer:
+
+    + Ensure that we don't get > 2 levels of section nesting,
+      even with slide level > 2 (#5168).
+    + If slide level == N but there is no N-level header, make
+      sure the next header with level > N gets treated as a slide
+      and put in a section, rather than remaining loose (#5168).
+
+  * Markdown writer:
+
+    + Make `plain` RawBlocks pass through in `plain` output.
+    + Include needed whitespace after HTML figure (#5121).
+      We use HTML for a figure in markdown dialects that can't
+      represent it natively.
+
+  * Commonmark writer:
+
+    + Fix handling of SoftBreak with `hard_line_breaks` (#5195).
+    + Implement `--toc` (`writerTableOfContents`)
+      in commonmark/gfm writers (#5172).
+
+  * EPUB writer:
+
+    + Ensure that picture transforms are done on metadata too.
+    + Small fixes to `nav.xhtml`:
+      Add 'landmarks' id attribute to the landmarks nav.
+      Replace old default CSS removing numbers from ol.toc li
+      with new rules that match `nav#toc ol, nav#landmarks ol`.
+      We keep the `toc` class on `ol` for backwards compatibility.
+
+  * LaTeX writer:
+
+    + Make raw content marked `beamer` pass through in `beamer`
+      output (pandoc/lua-filters#40).
+    + Beamer: avoid duplicated `fragile` property in some cases
+      (#5208).
+    + Add `#` special characters for listings (#4939).
+      This character needs special handling in `\lstinline`.
+
+ *  RTF writer: use `toTableOfContents` from Shared to replace
+    old duplicated code.
+
+  * Pptx writer:
+
+    + Support custom properties.  Also supports additional core
+      properties: `subject`, `category`, `description` (#5252,
+      Agustín Martín Barbero).
+    + Use `toTableOfContents` from Shared to replace old duplicated code.
+
+  * ODT writer (Augustín Martín Barbero):
+
+    + Fix typo in custom properties (#2839).
+    + Improve standard properties, including the following core
+      properties: `generator` (Pandoc/VERSION), `description`, `subject`,
+      `keywords`, `initial-creator` (from authors), `creation-date`
+      (actual creation date) (#5252).
+
+  * Custom writers:
+
+    + Allow '-' in filenames for custom lua writers (#5187).
+    + sample.lua: add `SingleQuoted`, `DoubleQuoted` (#5104).
+    + sample.lua: Add a missing `>` (MichaWiedenmann).
+
+  * reveal.js template:  Add `zoomKey` config (#4249).
+
+  * HTML5 template: Remove unnecessary type="text/css" on style and
+    link for HTML5 (#5146).
+
+  * LaTeX template (Andrew Dunning, except where noted):
+
+    + Prevent fontspec from scaling `mainfont` to match the default
+      font, Latin Modern. A main font set to 12pt could
+      previously appear between 11pt to 13pt depending on its design.
+      To return to the earlier rendering, use `-V
+      mainfontoptions="Scale=MatchLowercase"` (#5212, #5218).
+    + Display monospaced fonts without TeX ligatures when using
+      `--pdf-engine=lualatex`. It now matches the behaviour of other
+      engines (#5212, #5218).
+    + Remove the deprecated `romanfont` variable. The functionality of
+      `mainfont` is identical (#5218).
+    + Render `\subtitle` with the standard document classes.
+      Previously, `subtitle` only appeared when using the KOMA-Script
+      classes or Beamer (#5213, #5244).
+    + Use Babel instead of Polyglossia for LuaLaTeX. This avoids
+      several language selection problems, notably with retaining
+      French spacing conventions when switching to a verbatim
+      environment or another language; and in printing Greek text
+      without hyphenation (#5193).
+    + Use the [`xurl`](https://ctan.org/pkg/xurl) package if
+      available, improving the appearance of URLs by allowing them to
+      break at additional points (#5193).
+    + Use [`bookmark`](https://ctan.org/pkg/bookmark) if available
+      to correct heading levels in PDF bookmarks: see the [KOMA-Script
+      3.26 release notes](https://komascript.de/release3.26) (#5193).
+    + Require the [`xcolor`](https://ctan.org/pkg/xcolor) package to
+      avoid a possible error when using additional packages alongside
+      footnotes in tables (#5193, closes #4861).
+    + Remove obsolete `fixltx2e` package, which has no functionality
+      with TeX Live 2015 or later (#5193).
+    + Allow multiple `fontfamilies.options` (#5193, closes #5194).
+    + Restrict `institute` variable to Beamer (#5219).
+    + Use [`footnotehyper`](https://ctan.org/pkg/footnotehyper)
+      package if available to make footnotes in tables compatible
+      with `hyperref` (#5234).
+    + Number parts and chapters in book classes only if the
+      `numbersections` variable is set, for consistency with other
+      output formats. To return to the previous behaviour, use
+      `-V numbersections -V secnumdepth=0` (#5235).
+    + Reindent file (#5193).
+    + Use built-in parskip handling with KOMA-Script classes (#5143, Enno).
+    + Set default listings language for lua, assembler (#5227, John
+      MacFarlane).  Otherwise we get an error when trying to compile code
+      with lua or assembler code.  To change the default dialect
+      (currently 5.3 for lua and x86masm for assembler), you can use
+      `--include-in-header` to inject something like
+      `\lstset{defaultdialect=[5.2]Lua}`.
+
+  * Text.Pandoc.Readers: Changed types of `readJSON`; it now runs
+    in an instance of PandocMonad, like the other readers and
+    writers.  [API change]
+
+  * Text.Pandoc.Writers: Changed types of `writeJSON`; it now runs
+    in an instance of PandocMonad, like the other readers and
+    writers.  [API change]
+
+  * Text.Pandoc.Error: Added `PandocUTF8DecodingError` constructor
+    for `PandocError`. [API change]
+
+  * Text.Pandoc.Writers.Shared - add `toTableOfContents`. [API change]
+    This is refactored out from the Markdown writer.
+    It can be used in other writers to create a table of contents.
+
+  * Improve error messages for UTF-8 decoding errors. Now we give
+    the filename and byte offset (#4765).
+
+  * Text.Pandoc.XML: Strip out illegal XML characters in
+    `escapeXMLString` (#5119).
+
+  * Text.Pandoc.Process: update `pipeProcess` (Albert Krewinkel).
+    The implementation of `pipeProcess` was rewritten to fix sporadic
+    failures caused by prematurely closed pipes.
+
+  * Use `safeRead` instead of `read` everywhere in the code
+    (John MacFarlane, Mauro Bieg, #5162, #5180).
+
+  * Text.Pandoc.SelfContained: Decompress `.svgz` when
+    converting to `data:` URI (#5163, Alexander Krotov).
+
+  * Text.Pandoc.Parsing: Remove unused `HasHeaderMap`
+    (#5175, Alexander Krotov). [API change]
+
+  * Normalize Windows paths to account for change in ghc 8.6 (#5127).
+    When pandoc is compiled with ghc 8.6, Windows paths are treated
+    differently, and paths beginning `\\server` no longer work.
+    This commit rewrites such patsh to `\\?\UNC\server` which works.
+    The change operates at the level of argument parsing, so it
+    only affects the command line program.
+
+  * Simplify/fix reading of `--metadata` values on command line
+    to avoid problems relating to hvr/HsYAML#7 (#5177).
+
+  * data/pandoc.lua: auto-fix nested constructor arguments (Albert
+    Krewinkel).  Incorrect types to pandoc element constructors are
+    automatically converted to the correct types when possible. This was
+    already done for most constructors, but conversions are now also done
+    for nested types (like lists of lists).
+
+  * Removed custom Setup.hs, use build-type: simple. The only thing we
+    gained from the custom build was automatic installation of the man
+    page when using 'cabal install'. But custom builds cause problems,
+    e.g., with cross-compilation. Installation of the man page is
+    better handled by packagers. Note to packagers (e.g. Debian): it
+    may be necessary to add a step installing the man page with the
+    next release.
+
+  * Allow latest http-client, tasty, zip-archive, Glob.
+
+  * Require skylighting >= 0.7.5, adding support for sml, J,
+    typescript.
+
+   * Tests:  Cleaned up `findPandoc` in `Tests.Helpers`, so it
+     works well with cabal v2.
+
+  * INSTALL.md:
+
+    + Use button for installer links (John MacFarlane, Mauro Bieg,
+      #5167).
+    + Fix links and bump required stack version (max).
+    + Improve installation notes on associated software (Andrew
+      Dunning). Includes explanation of how to install related tools
+      with package managers (since the method of installing
+      `rsvg-convert` is not obvious).
+
+  * doc/org.md: improve documentation of org features (Albert
+    Krewinkel).
+
+  * doc/lua-filters.md:  use 3rd level headers for module fields.
+
+  * MANUAL:
+
+    + Clarify automatic identifiers (#5201). We remove
+      non-alphanumerics. This includes, e.g., emojis.
+    + Fix example for Div with id (Geoffrey Ely).
+    + Update list of LaTeX packages used.
+    + Make it clear that `hard_line_breaks` works in `gfm` (see #5195).
+    + Mention `raw_attribute` in documentation for `raw_html` and
+      `raw_tex` (#5240, thanks to @eiro).
+    + Clarify that `$sep$` must come right before `$endfor$` in templates
+      (#5243, Lev Givon).
+    + Document metadata support for docx, odt, pptx writers (Agustín
+      Martín Barbero).
+    + Reorganize template variables (#5249, Andrew Dunning).
+      Add additional headings to categorize variables, and
+      alphabetize when there is large number; add more examples.
+    + Document `date-meta` template variable (#5260, Tristan Stenner).
+
+  * trypandoc: Fix CSS and viewport.
+
+## pandoc 2.5 (2018-11-27)
+
+  * Text.Pandoc.App: split into several unexported submodules (Albert
+    Krewinkel):  Text.Pandoc.App.FormatHeuristics,
+    Text.Pandoc.App.Opt, Text.Pandoc.App.CommandLineOptions,
+    Text.Pandoc.App.OutputSettings.  This is motivated partly by the
+    desire to reduce recompilations when something is modified,
+    since App previously depended on virtually every other module.
+
+  * Text.Pandoc.Extensions
+
+    + Semantically, `gfm_auto_identifiers` is now a modifier of
+      `auto_identifiers`; for identifiers to be set, `auto_identifiers` must
+      be turned on, and then the type of identifier produced depends on
+      `gfm_auto_identifiers` and `ascii_identifiers` are set. Accordingly,
+      `auto_identifiers` is now added to `githubMarkdownExtensions` (#5057).
+    + Remove `ascii_identifiers` from `githubMarkdownExtensions`.
+      GitHub doesn't seem to strip non-ascii characters any more.
+
+  * Text.Pandoc.Lua.Module.Utils (Albert Krewinkel)
+
+    + Test AST object equality via Haskell (#5092).  Equality of Lua
+      objects representing pandoc AST elements is tested by unmarshalling
+      the objects and comparing the result in Haskell.
+      A new function `equals` which performs this test has been added to the
+      `pandoc.utils` module.
+    + Improve stringify.  Meta value strings (MetaString)
+      and booleans (MetaBool) are now converted to the literal string and the
+      lowercase boolean name, respectively. Previously, all values of these
+      types were converted to the empty string.
+
+  * Text.Pandoc.Parsing: Remove Functor and Applicative constraints where Monad
+    already exists (Alexander Krotov).
+
+  * Text.Pandoc.Pretty: Don't render BreakingSpace at end of line
+    or beginning of line (#5050).
+
+  * Text.Pandoc.Readers.Markdown
+
+    + Fix parsing of citations, quotes, and underline emphasis
+      after symbols.  Starting with pandoc 2.4, citations, quoted inlines,
+      and underline emphasis were no longer recognized after certain
+      symbols, like parentheses (#5099, #5053).
+    + In pandoc 2.4, a soft break after an abbreviation would be
+      relocated before it to allow for insertion of a nonbreaking
+      space after the abbreviation. This behavior is here reverted.
+      A soft break after an abbreviation will remain, and no nonbreaking
+      space will be added. Those who care about this issue should take care not
+      to end lines with an abbreviation, or to insert nonbreaking spaces
+      manually.
+
+  * Text.Pandoc.Readers.FB2: Do not throw error for unknown elements in
+    `<body>` (Alexander Krotov).  Some libraries include custom elements
+    in their FB2 files.
+
+  * Text.Pandoc.Readers.HTML
+
+    + Allow `tfoot` before body rows (#5079).
+    + Parse `<small>` as a Span with class "small" (#5080).
+    + Allow thead containing a row with `td` rather than `th` (#5014).
+
+  * Text.Pandoc.Readers.LaTeX
+
+    + Cleaned up handling of dimension arguments.  Allow decimal points,
+      preceding space.
+    + Don't allow arguments for verbatim, etc.
+    + Allow space before bracketed options.
+    + Allow optional arguments after `\\` in tables.
+    + Improve parsing of `\tiny`, `\scriptsize`, etc.  Parse as raw,
+      but know that these font changing commands take no arguments.
+
+  * Text.Pandoc.Readers.Muse
+
+    + Trim whitespace before parsing grid table cells (Alexander Krotov).
+    + Add grid tables support (Alexander Krotov).
+
+  * Text.Pandoc.Shared
+
+    + For bibliography match Div with id `refs`, not class `references`.
+      This was a mismatch between pandoc's docx, epub, latex, and markdown
+      writers and the behavior of pandoc-citeproc, which actually looks for a
+      div with id `refs` rather than one with class `references`.
+    + Exactly match GitHub's identifier generating algorithm (#5057).
+    + Add parameter for `Extensions` to `uniqueIdent` and
+      `inlineListToIdentifier` (#5057).  [API change]
+      This allows these functions to be sensitive to the settings of
+      `Ext_gfm_auto_identifiers` and `Ext_ascii_identifiers`, and allows us to
+      use `uniqueIdent` in the CommonMark reader, replacing custom code.  It
+      also means that `gfm_auto_identifiers` can now be used in all formats.
+
+  * Text.Pandoc.Writers.AsciiDoc
+
+    + Use `.`+ as list markers to support nested ordered lists (#5087).
+    + Support list number styles (#5089).
+    + Render Spans using `[#id .class]#contents#` (#5080).
+
+  * Text.Pandoc.Writers.CommonMark
+
+    + Respect `--ascii` (#5043, quasicomputational).
+    + Make sure `--ascii` affects quotes, super/subscript.
+
+  * Text.Pandoc.Writers.Docx
+
+    + Fix bookmarks to headers with long titles (#5091).
+      Word has a 40 character limit for bookmark names.  In addition, bookmarks
+      must begin with a letter.  Since pandoc's auto-generated identifiers may
+      not respect these constraints, some internal links did not work.  With
+      this change, pandoc uses a bookmark name based on the SHA1 hash of the
+      identifier when the identifier isn't a legal bookmark name.
+    + Add bookmarks to code blocks (Nikolay Yakimov).
+    + Add bookmarks to images (Nikolay Yakimov).
+    + Refactor common bookmark creation code into a function (Nikolay Yakimov).
+
+  * Text.Pandoc.Writers.EPUB: Handle calibre metadata (#5098).
+    Nodes of the form
+
+          <meta name="calibre:series" content="Classics on War and Politics"/>
+
+      are now included from an epub XML metadata file.  You can also include
+      this information in your YAML metadata, like so:
+
+          calibre:
+           series: Classics on War and Policitics
+
+      In addition, ibooks-specific metadata can now be included via an XML
+      file. (Previously, it could only be included via YAML metadata, see
+      #2693.)
+
+  * Text.Pandoc.Writers.HTML: Use plain `"` instead of `&quot;` outside of
+    attributes.
+
+  * Text.Pandoc.Writers.ICML: Consolidate adjacent strings, inc. spaces.
+    This avoids splitting up the output unnecessarily into separate elements.
+
+  * Text.Pandoc.Writers.LaTeX: Don't emit `[<+->]` unless beamer output, even
+    if `writerIncremental` is True (#5072).
+
+  * Text.Pandoc.Writers.Muse (Alexander Krotov).
+
+    + Output tables as grid tables if they have multi-line cells.
+    + Indent simple tables only on the top level.
+    + Output tables with one column as grid tables.
+    + Add support for `--reference-location`.
+    + Internal improvements.
+
+  * Text.Pandoc.Writers.OpenDocument: Fix list indentation (Nils Carlson,
+    #5095).  This was a regression in pandoc 2.4.
+
+  * Text.Pandoc.Writers.RTF: Fix warnings for skipped raw inlines.
+
+  * Text.Pandoc.Writers.Texinfo: Add blank line before `@menu` section (#5055).
+
+  * Text.Pandoc.XML: in `toHtml5Entities`, prefer shorter entities
+    when there are several choices for a particular character.
+
+  * data/abbreviations
+
+    + Add additional abbreviations (Andrew Dunning)
+      Many of these borrowed from the Chicago Manual of Style 10.42,
+      'Scholarly abbreviations'.
+
+  * Templates
+
+    + Asciidoc template:  add :lang: to title header is lang is set in
+      metadata (#5088).
+
+  * pandoc.cabal: Add cabal flag `derive_json_via_th` (Albert Krewinkel)
+    Disabling the flag will cause derivation of ToJSON and FromJSON
+    instances via GHC Generics instead of Template Haskell. The flag is
+    enabled by default, as deriving via Generics can be slow (see #4083).
+
+  * trypandoc:
+
+    + Tweaked drop-down lists.
+    + Put link to site in footer.
+    + Preselect output format.
+    + Update on change of in or out format.
+    + Add man input format.
+
+  * MANUAL.txt:
+
+    + Fix outdated description of latex_macros extension.
+    + Clarified placement of bibliography.
+    + Added "A note on security."
+    + Fix note on curly brace syntx for locators.
+    + Document new explicit syntax for citeproc locators.
+    + Remove confusing cross-links for some extensions.
+    + Don't put pandoc in code ticks in heading.
+    + Document that `--ascii` works for gfm and commonmark too.
+    + Add `man` to `--from` options.
+
+  * doc/customizing-pandoc.md: various improvements (Mauro Bieg).
+
+
+## pandoc 2.4 (2018-11-03)
+
+### New features
+
+  * New input format `man` (Yan Pashkovsky, John MacFarlane).
+
+### Behavior changes
+
+  * `--ascii` is now implemented in the writers, not in Text.Pandoc.App,
+    via the new `writerPreferAscii` field in `WriterOptions`.
+    Now the `write*` functions for Docbook, HTML, ICML, JATS, LaTeX,
+    Ms, Markdown, and OPML are sensitive to `writerPreferAscii`.
+    Previously the to-ascii translation was done in Text.Pandoc.App,
+    and thus not available to those using the writer functions
+    directly.
+
+  * `--ascii` now works with Markdown output.  HTML5 character reference
+    entities are used.
+
+  * `--ascii` now works with LaTeX output. 100% ASCII output can't be
+    guaranteed, but the writer will use commands like `\"{a}` and `\l`
+    whenever possible, to avoid emitting a non-ASCII character.
+
+  * For HTML5 output, `--ascii` now uses HTML5 character reference
+    entities rather than numerical entities.
+
+  * Improved detection of format based on extension (in Text.Pandoc.App).
+    We now ensure that if someone tries to convert a file for a
+    format that has a pandoc writer but not a reader, it won't just
+    default to markdown.
+
+  * Add viz. to abbreviations file (#5007, Nick Fleisher).
+
+  * AsciiDoc writer:  always use single-line section headers,
+    instead of the old underline style (#5038).  Previously the single-line
+    style would be used if `--atx-headers` was specified, but
+    now it is always used.
+
+  * RST writer: Use simple tables when possible (#4750).
+
+  * CommonMark (and gfm) writer: Add plain text fallbacks. (#4528,
+    quasicomputational). Previously, the writer would unconditionally
+    emit HTML output for subscripts, superscripts, strikeouts (if the
+    strikeout extension is disabled) and small caps, even with
+    `raw_html` disabled. Now there are plain-text (and, where
+    possible, fancy Unicode) fallbacks for all of these corresponding
+    (mostly) to the Markdown fallbacks, and the HTML output is only
+    used when `raw_html` is enabled.
+
+  * Powerpoint writer: support raw openxml (Jesse Rosenthal, #4976).
+    This allows raw openxml blocks and inlines to be used in the pptx
+    writer. Caveats: (1) It's up to the user to write
+    well-formed openxml. The chances for corruption, especially with
+    such a brittle format as pptx, is high. (2) Because of
+    the tricky way that blocks map onto shapes, if you are using
+    a raw block, it should be the only block on a slide
+    (otherwise other text might end up overlapping it). (3) The
+    pptx ooxml namespace abbreviations are different from the
+    docx ooxml namespaces. Again, it's up to the user to get it
+    right. Unzipped document and ooxml specification should be
+    consulted.
+
+  * With `--katex` in HTML formats, do not use the autorenderer (#4946).
+    We no longer surround formulas with `\(..\)` or `\[..\]`. Instead,
+    we tell katex to convert the contents of span elements with
+    class "math". Since math has already been identified, this
+    avoids wasted time parsing for LaTeX delimiters. Note, however,
+    that this may yield unexpected results if you have span elements
+    with class "math" that don't contain LaTeX math.
+    Also, use latest version of KaTeX by default (0.9.0).
+
+  * The man writer now produces ASCII-only output, using groff escapes,
+    for portability.
+
+  * ODT writer:
+
+    + Add title, author and date to metadata; any remaining
+      metadata fields are added as `meta:user-defined` tags.
+    + Implement table caption numbering (#4949, Nils Carlson).
+      Captioned tables are numbered and labeled with format "Table 1:
+      caption", where "Table" is replaced by a translation, depending
+      on the value of `lang` in metadata. Uncaptioned tables are not
+      enumerated.
+    + OpenDocument writer: Implement figure numbering in captions (#4944,
+      Nils Carlson). Figure captions are now numbered 1, 2, 3, ...
+      The format in the caption is "Figure 1: caption" and so on
+      (where "Figure" is replaced by a translation, depending on the
+      value of `lang` in the metadata). Captioned figures are numbered
+      consecutively and uncaptioned figures are not enumerated. This
+      is necessary in order for LibreOffice to generate an
+      Illustration Index (Table of Figures) for included figures.
+
+  * RST reader: Pass through fields in unknown directives as div attributes
+    (#4715). Support `class` and `name` attributes for all directives.
+
+  * Org reader: Add partial support for `#+EXCLUDE_TAGS` option. (#4284,
+    Brian Leung). Headers with the corresponding tags should not
+    appear in the output.
+
+  * Log warnings about missing title attributes now include a
+    suggestion about how to fix the problem (#4909).
+
+  * Lua filter changes (Albert Krewinkel):
+
+    + Report traceback when an error occurs. A proper Lua traceback is
+      added if either loading of a file or execution of a filter
+      function fails. This should be of help to authors of Lua filters
+      who need to debug their code.
+
+    + Allow access to pandoc state (#5015). Lua filters and custom
+      writers now have read-only access to most fields of pandoc's
+      internal state via the global variable `PANDOC_STATE`.
+
+    + Push ListAttributes via constructor (Albert Krewinkel).
+      This ensures that ListAttributes, as present in OrderedList elements,
+      have additional accessors (viz. `start`, `style`, and `delimiter`).
+
+    + Rename ReaderOptions fields, use snake_case. Snake case is used
+      in most variable names, using camelCase for these fields was an
+      oversight. A metatable is added to ensure that the old field
+      names remain functional.
+
+    + Iterate over AST element fields when using `pairs`. This makes
+      it possible to iterate over all ield names of an AST element by
+      using a generic `for` loop with pairs`:
+
+          for field_name, field_content in pairs(element) do
+          ...
+          end
+
+      Raw table fields of AST elements should be considered an
+      implementation detail and might change in the future. Accessing
+      element properties should always happen through the fields
+      listed in the Lua filter docs.
+
+      Note that the iterator currently excludes the `t`/`tag` field.
+
+    + Ensure that MetaList elements behave like Lists. Methods usable
+      on Lists can also be used on MetaList objects.
+
+    + Fix MetaList constructor (Albert Krewinkel). Passing a MetaList
+      object to the constructor `pandoc.MetaList` now returns the
+      passed list as a MetaList. This is consistent with the
+      constructor behavior when passed an (untagged) list.
+
+  * Custom writers: Custom writers have access to the global variable
+    `PANDOC_DOCUMENT`(Albert Krewinkel, #4957). The variable contains
+    a userdata wrapper around the full pandoc AST and exposes two
+    fields, `meta` and `blocks`. The field content is only
+    marshaled on-demand, performance of scripts not accessing the
+    fields remains unaffected.
+
+### API changes
+
+  * Text.Pandoc.Options: add `writerPreferAscii` to `WriterOptions`.
+
+  * Text.Pandoc.Shared:
+
+    + Export `splitSentences`. This was previously duplicated in the Man and
+      Ms writers.
+    + Add `ToString` typeclass (Alexander Krotov).
+
+  * New exported module Text.Pandoc.Filter (Albert Krewinkel).
+
+  * Text.Pandoc.Parsing
+
+    + Generalize `gridTableWith` to any `Char` Stream (Alexander Krotov).
+    + Generalize `readWithM` from `[Char]` to any `Char` Stream
+      that is a `ToString` instance (Alexander Krotov).
+
+  * New exposed module Text.Pandoc.Filter (Albert Krewinkel).
+
+  * Text.Pandoc.XML: add `toHtml5Entities`.
+
+  * New exported module Text.Pandoc.Readers.Man (Yan Pashkovsky, John
+    MacFarlane).
+
+  * Text.Pandoc.Writers.Shared
+
+    + Add exported functions `toSuperscript` and
+      `toSubscript` (quasicomputational, #4528).
+    + Remove exported functions `metaValueToInlines`,
+      `metaValueToString`. Add new exported functions
+      `lookupMetaBool`, `lookupMetaBlocks`, `lookupMetaInlines`,
+      `lookupMetaString`. Use these whenever possible for uniformity
+      in writers (Mauro Bieg, #4907). (Note that
+      removed function `metaValueToInlines` was in previous
+      released versions.)
+    + Add `metaValueToString`.
+
+  * Text.Pandoc.Lua
+
+    + Expose more useful internals (Albert Krewinkel):
+
+      - `runFilterFile` to run a Lua filter from file;
+      - data type `Global` and its constructors; and
+      - `setGlobals` to add globals to a Lua environment.
+
+      This module also contains `Pushable` and `Peekable` instances
+      required to get pandoc's data types to and from Lua. Low-level
+      Lua operation remain hidden in Text.Pandoc.Lua.
+
+    + Rename `runPandocLua` to `runLua` (Albert Krewinkel).
+
+    + Remove `runLuaFilter`, merging this into Text.Pandoc.Filter.Lua's
+      `apply` (Albert Krewinkel).
+
+### Bug fixes and under-the-hood improvements
+
+  * Text.Pandoc.Parsing
+
+    + Make `uri` accept any stream with Char tokens (Alexander Krotov).
+    + Rewrite `uri` without `withRaw` (Alexander Krotov).
+    + Generalize `parseFromString` and `parseFromString'` to any
+      streams with Char token (Alexander Krotov)
+    + Rewrite `nonspaceChar` using `noneOf` (Alexander Krotov)
+
+  * Text.Pandoc.Shared: Reimplement `mapLeft` using `Bifunctor.first`
+    (Alexander Krotov).
+
+  * Text.Pandoc.Pretty: Simplify `Text.Pandoc.Pretty.offset`
+    (Alexander Krotov).
+
+  * Text.Pandoc.App
+
+    + Work around HXT limitation for --syntax-definition with windows
+      drive (#4836).
+    + Always preserve tabs for man format. We need it for tables.
+    + Split command line parsing code into a separate unexported
+      module, Text.Pandoc.App.CommandLineOptions (Albert Krewinkel).
+
+  * Text.Pandoc.Readers.Roff: new unexported module for tokenizing
+    roff documents.
+
+  * New unexported module Text.Pandoc.RoffChar, provided character
+    escape tables for roff formats.
+
+  * Text.Pandoc.Readers.HTML: Fix `htmlTag` and `isInlineTag` to
+    accept processing instructions (#3123, regression since 2.0).
+
+  * Text.Pandoc.Readers.JATS: Use `foldl'` instead of `maximum` to
+    account for empty lists (Alexander Krotov).
+
+  * Text.Pandoc.Readers.RST: Don't allow single-dash separator in
+    headerless table (#4382).
+
+  * Text.Pandoc.Readers.Org: Parse empty argument array in inline src
+    blocks (Brian Leung).
+
+  * Text.Pandoc.Readers.Vimwiki:
+
+    + Get rid of `F`, `runF` and `stateMeta'` in favor of `stateMeta`
+      (Alexander Krotov).
+    + Parse `Text` without converting to `[Char]` (Alexander Krotov).
+
+  * Text.Pandoc.Readers.Creole: Parse `Text` without converting to
+    `[Char]` (Alexander Krotov).
+
+  * Text.Pandoc.Readers.LaTeX
+
+    + Allow space at end of math after `\` (#5010).
+    + Add support for `nolinkurl` command (#4992, Brian Leung).
+    + Simplified type on `doMacros'`.
+    + Tokenize before pulling tokens, rather than after (#4408). This
+      has some performance penalty but is more reliable.
+    + Make macroDef polymorphic and allow in inline context.
+      Otherwise we can't parse something like `\lowercase{\def\x{Foo}}`.
+     I have actually seen tex like this in the wild.
+    + Improved parsing of `\def`, `\let`. We now correctly parse:
+      ```
+      \def\bar{hello}
+      \let\fooi\bar
+      \def\fooii{\bar}
+      \fooi +\fooii
+
+      \def\bar{goodbye}
+      \fooi +\fooii
+      ```
+    + Improve parsing of `\def` argspec.
+    + Skip `\PackageError` commands (see #4408).
+    + Fix bugs omitting raw tex (#4527). The default is `-raw_tex`,
+      so no raw tex should result unless we explicitly say `+raw_tex`.
+      Previously some raw commands did make it through.
+    + Moved `isArgTok` to Text.Pandoc.Readers.LaTeX.Parsing.
+    + Moved `babelLangToBCP`, `polyglossiaLangToBCP` to new module,
+      Text.Pandoc.Readers.LaTeX.Lang (unexported).
+    + Simplified accent code using unicode-transforms.
+      New dependency on unicode-transforms package for normalization.
+    + Allow verbatim blocks ending with blank lines (#4624).
+    + Support `breq` math environments: `dmath`, `dgroup`, `darray`.
+      This collects some of the general-purpose code from the LaTeX reader,
+      with the aim of making the module smaller.
+
+  * Text.Pandoc.Readers.Markdown
+
+    + Fix awkward soft break movements before abbreviations (#4635).
+    + Add updateStrPos in a couple places where needed.
+
+  * Text.Pandoc.Readers.Docx: Trigger bold/italic with bCs, iCs
+    (#4947). These are variants for "complex scripts" like Arabic
+    and are now treated just like b, i (bold, italic).
+
+  * Text.Pandoc.Readers.Muse (Alexander Krotov)
+
+    + Try to parse lists before trying to parse table.
+      This ensures that tables inside lists are parsed correctly.
+    + Forbid whitespace after opening and before closing markup
+      elements.
+    + Parse page breaks.
+    + Simplify `museToPandocTable` to get rid of partial functions.
+    + Allow footnotes to start with empty line.
+    + Make sure that the whole text is parsed.
+    + Allow empty headers. Previously empty headers caused parser to
+      terminate without parsing the rest of the document.
+    + Allow examples to be indented with tabs.
+    + Remove indentation from examples indicated by `{{{` and `}}}`.
+    + Fix parsing of empty cells.
+    + Various changes to internals.
+    + Rewrite some parsers in applicative style.
+    + Avoid tagsoup dependency.
+    + Allow table caption to contain `+`.
+
+  * Text.Pandoc.Writers.LaTeX
+
+    + Add newline if math ends in a comment (#4880). This prevents the
+      closing delimiter from being swalled up in the comment.
+    + With `--listings`, don't pass through org-babel attributes (#4889).
+    + With `--biblatex`, use `\autocite` when possible (#4960).
+      `\autocites{a1}{a2}{a3}` will not collapse the entries. So, if
+      we don't have prefixes and suffixes, we use instead
+      `\autocite{a1,a2,a3}`.
+    + Fix description lists contining highlighted code (#4662).
+
+  * Text.Pandoc.Writers.Man
+
+    + Don't wrap `.SH` and `.SS` lines (#5019).
+    + Avoid unnecessary `.RS`/`.RE` pair in definition lists with
+      one paragraph definitions.
+    + Moved common groff functions to Text.Pandoc.Writers.Groff.
+    * Fix strong/code combination on man (should be `\f[CB]` not
+      `\f[BC]`, see #4973).
+    + Man writer: use `\f[R]` instead of `\f[]` to reset font
+      (Alexander Krotov, #4973).
+    + Move `splitSentences` to Text.Pandoc.Shared.
+
+  * Text.Pandoc.Writers.Docx
+
+    + Add framework for custom properties (#3034). So far, we don't
+      actually write any custom properties, but we have the
+      infrastructure to add this.
+
+    + Handle tables in table cells (#4953). Although this is not
+      documented in the spec, some versions of Word require a `w:p`
+      element inside every table cell. Thus, we add one when the
+      contents of a cell do not already include one (e.g. when a table
+      cell contains a table).
+
+  * Text.Pandoc.Writers.AsciiDoc:  Prevent illegal nestings.
+    Adjust header levels so that n+1 level headers are only
+    found under n level headers, and the top level is 1.
+
+  * Text.Pandoc.Writers.OpenDocument: Improve bullet/numbering
+    alignment (#4385). This change eliminates the large gap we used
+    to have between bullet and text, and also ensures that numbers
+    in numbered lists will be right-aligned.
+
+  * Text.Pandoc.Writers.ZimWiki
+
+    + Number ordered list items sequentially, rather than always
+      with 1 (#4962).
+    + Remove extra indentation on lists (#4963).
+
+  * Text.Pandoc.Writers.EPUB: Use metadata field `css` instead of
+    `stylesheet` (Mauro Bieg, #4990).
+
+  * Text.Pandoc.Writers.Markdown: Ensure blank between raw block and
+    normal content (#4629). Otherwise a raw block can prevent a
+    paragraph from being recognized as such.
+
+  * Text.Pandoc.Writers.Ms
+
+    + Removed old `escapeBar`. We don't need this now that we use
+      `@` for math delim.
+    + Moved common code to Text.Pandoc.Writers.Roff and to
+      Text.Pandoc.RoffChar.
+    + Move `splitSentences` to Text.Pandoc.Shared (to avoid duplication
+      with the man writer).
+
+   * Text.Pandoc.Writers.Muse (Alexander Krotov).
+
+    + Add support for grid tables.
+    + Fix Muse writer style.
+    + Use `length` instead of `realLength` to calculate definition
+      indentation. Muse parsers don't take character width into
+      account when calculating indentation.
+    + Do not insert newline before lists.
+    + Use lightweight markup after `</em>` tag.
+
+  * New unexported module Text.Pandoc.Writers.Roff, providing functions
+    useful for all roff format writers (man, ms).
+
+  * Text.Pandoc.Lua
+
+    + Move globals handling to separate module Text.Pandoc.Lua.Global
+      (Albert Krewinkel).
+
+    + Lua filter internals: push Shared.Element as userdata (Albert
+      Krewinkel). Hierarchical Elements were pushed to Lua as plain
+      tables. This is simple, but has the disadvantage that marshaling
+      is eager: all child elements will be marshaled as part of the
+      object. Using a Lua userdata object instead allows lazy access
+      to fields, causing content marshaling just (but also each time)
+      when a field is accessed. Filters which do not traverse the full
+      element contents tree become faster as a result.
+
+### Default template changes
+
+  * LaTeX template:
+
+    + Add variable `hyperrefoptions` (#4925, Mathias Walter).
+    + Add variable `romanfont`, `romanfontoptions` (#4665, OvidiusCicero).
+
+  * AsciiDoc template: use single-line style for title.
+
+  * revealjs template: Fix typo in the socket.io javascript plugin (#5006,
+    Yoan Blanc).
+
+  * Text.Pandoc.Lua.Util: add missing docstring to `defineHowTo`
+    (Albert Krewinkel).
+
+  * data/pandoc.lua: add datatype ListAttributes (Albert Krewinkel)
+
+  * data/sample.lua: replace custom pipe function with pandoc.utils.pipe
+    (Albert Krewinkel).
+
+### Documentation improvements
+
+  * INSTALL.md
+
+    + Add chromeos install instructions (#4958) (Evan Pratten).
+    + Add note about TinyTeX.
+
+  * MANUAL.txt
+
+    + Change `groff` -> `roff`.
+    + Implement `--ascii` for Markdown writer.
+    + Clarify LaTeX image dimensions output (Mauro Bieg).
+
+  * doc/customizing-pandoc.md: added skeleton (Mauro Bieg, #3288).
+
+  * doc/getting-started.md: Added title to test1.md to avoid warning.
+
+  * doc/lua-filters.md: merge type references into main document,
+    fix description of Code.text (Albert Krewinkel).
+
+### Build infrastructure improvements
+
+  * Makefile
+
+    + Makefile: added quick-cabal, full-cabal targets.
+    + Make .msi download targets insensitive to order of appveyor builds.
+
+  * Update benchmarks for ghc 8.6.1.
+
+   * pandoc.cabal:
+
+    + Enable more compiler warnings (Albert Krewinkel).
+    + Make base lower bound 4.8.
+    + Bump upper bound for QuickCheck.
+    + Bump upper bound for binary.
+    + Updated version bounds for containers and haddock-library (#4974).
+    + Added docx/docPropos/custom.xml to cabal data-files.
+    + Require skylighting 0.7.4 (#4920).
+    + New dependency on unicode-transforms package for normalization.
+
+  * Improved .travis.yml testing and test with GHC 8.6.1 (Albert Krewinkel).
+
+  * Added `tools/changelog-helper.sh`.
+
+  * Added test/grofftest.sh for testing the man reader on real man pages.
+
+## pandoc 2.3.1 (2018-09-28)
+
+  * RST reader:
+
+    + Parse RST inlines containing newlines (#4912, Francesco Occhipinti).
+      This eliminates a regression introduced after pandoc 2.1.1, which
+      caused inline constructions containing newlines not to be recognized.
+    + Fix bug with internal link targets (#4919).  They were gobbling up
+      indented content underneath.
+
+  * Markdown reader: distinguish autolinks in the AST.  With this change,
+    autolinks are parsed as Links with the `uri` class. (The same is true
+    for bare links, if the `autolink_bare_uris` extension is enabled.)
+    Email autolinks are parsed as Links with the `email` class.  This
+    allows the distinction to be represented in the AST.
+
+  * Org reader:
+
+    + Force inline code blocks to honor export options (Brian Leung).
+    + Parse empty argument array in inline src blocks (Brian Leung).
+
+  * Muse reader (Alexander Krotov):
+
+    + Added additional tests.
+    + Do not allow code markup to be followed by digit.
+    + Remove heading level limit.
+    + Simplify `<literal>` tag parsers
+    + Parse Text instead of String. Benchmark shows 7% improvement.
+    + Get rid of HTML parser dependency.
+    + Various code improvements.
+
+  * ConTeXt writer: change `\` to `/` in Windows image paths (#4918).
+    We do this in the LaTeX writer, and it avoids problems.
+    Note that `/` works as a LaTeX path separator on Windows.
+
+  * LaTeX writer:
+
+    + Add support for multiprenote and multipostnote arguments
+      with `--biblatex` (Brian Leung, #4930).  The multiprenotes occur before
+      the first prefix of a multicite, and the multipostnotes follow the
+      last suffix.
+    + Fix a use of `last` that might take empty list.  If you ran with
+      `--biblatex` and have an empty document (metadata but no blocks),
+      pandoc would previously raise an error because of the use of
+      `last` on an empty list.
+
+  * RTF writer: Fix build failure with ghc-8.6.1 caused by missing
+    MonadFail instance (Jonas Scholl).
+
+  * ODT Writer: Improve table header row style handling (Nils Carlson).
+    This changes the way styles for cells in the header row
+    and normal rows are handled in ODT tables.
+    Previously a new (but identical) style was generated for
+    every table, specifying the style of the cells within the table.
+    After this change there are two style definitions for table cells,
+    one for the cells in the header row, one for all other cells.
+    This doesn't change the actual styles, but makes post-processing
+    changes to the table styles much simpler as it is no longer
+    necessary to introduce new styles for header rows and there are
+    now only two styles where there was previously one per table.
+
+  * HTML writer:
+
+    + Don't add `uri` class to presumed autolinks.  Formerly the `uri`
+      class was added to autolinks by the HTML writer, but it had to
+      guess what was an autolink and could not distinguish
+      `[http://example.com](http://example.com)` from
+      `<http://example.com>`.  It also incorrectly recognized
+      `[pandoc](pandoc)` as an autolink.  Now the HTML writer
+      simply passes through the `uri` attribute if it is present,
+      but does not add anything.
+    + Avoid adding extra section nestings for revealjs.
+      Previously revealjs title slides at level (slidelevel - 1)
+      were nested under an extra section element, even when
+      the section contained no additional (vertical) content.
+      That caused problems for some transition effects.
+    + Omit unknown attributes in EPUB2 output.  For example,
+      `epub:type` attributes should not be passed through,
+      or the epub produced will not validate.
+
+  * JATS writer: remove 'role' attribute on 'bold' and 'sc' elements (#4937).
+    The JATS spec does not allow these.
+
+  * Textile writer: don't represent `uri` class explicitly
+    for autolinks (#4913).
+
+  * Lua filters (Albert Krewinkel):
+
+    + Cleanup filter execution code.
+    + Better error on test failure.
+
+  * HTML, Muse reader tests: reduce time taken by round-trip test.
+
+  * Added cabal.project.
+
+  * MANUAL: `epub:type` is only useful for epub3 (Maura Bieg).
+
+  * Use hslua v1.0.0 (Albert Krewinkel).
+
+  * Fix `translations/ru` to use modern Russian orthography
+    (Ivan Trubach).
+
+  * Build Windows binary using ghc 8.6.1 and cabal new-build. This
+    fixes issues with segfaults in the 32-bit Windows binaries (#4283).
+
+## pandoc 2.3 (2018-09-16)
+
+  * Add `--metadata-file` option (Mauro Bieg, #1960), which allows
+    users to specify metadata in a YAML file, regardless of the
+    input format (#1960).
+
+  * Text.Pandoc.Writers.Shared: export `isDisplayMath` (API change).
+
+  * Text.Pandoc.Readers.Markdown: export `yamlToMeta` (API change,
+    Mauro Bieg).
+
+  * Text.Pandoc.Readers.LaTeX.Types:
+
+    + New type `ArgSpec` (API change).
+    + Second parameter of `Macro` constructor is now `[ArgSpec]` instead of
+      `Int` (API change).
+
+  * Markdown reader:
+
+    + Use `tex` instead of `latex` for raw tex-ish content. We can't
+      always tell if it's LaTeX, ConTeXt, or plain TeX. Better just to
+      use `tex` always. Note that if `context` or `latex` specifically
+      is desired, you can still force that in a markdown document by
+      using the raw attribute. Note that this change may affect some
+      filters, if they assume that raw tex parsed by the Markdown reader
+      will be RawBlock (Format `latex`). In most cases it should be
+      trivial to modify the filters to accept `tex` as well.
+    + Refactor and reorganize YAML code (Mauro Bieg).
+    + Make `example_lists` work for interrupted lists
+      without `startnum` (#4908).
+
+  * HTML reader:
+
+    + Parse `<script type="math/tex` tags as math (#4877).
+      These are used by MathJax in some configurations.
+    + Extract spaces inside links instead of trimming them
+      (Alexander Krotov, #4845).
+    + Added round-trip tests (Alexander Krotov).
+    + Make parsing sensitive to the `raw_tex` extension (#1126). This now
+      allows raw LaTeX environments, `\ref`, and `\eqref` to be parsed
+      (which is helpful for translation HTML documents using MathJaX).
+
+  * Org reader (Albert Krewinkel):
+
+    + Respect export option `p` for planning info.  Inclusion of planning info
+      (`*DEADLINE*`, `*SCHEDULED*`, and `*CLOSED*`) can be controlled via the
+      `p` export option: setting the option to `t` will add all planning
+      information in a *Plain* block below the respective headline.
+    + Org reader internals: don't rely on RecordWildCards and ViewPatterns
+      ghc extensions.
+    + Strip planning info from output.  Planning info is parsed, but not
+      included in the output (as is the default with Emacs Org-mode, #4867).
+
+  * LaTeX reader:
+
+    + Handle parameter patterns for `\def` (#4768, #4771).
+      For example:  `\def\foo#1[#2]{#1 and #2}`.
+    + Allow `%` characters in URLs. This affects `\href` and `\url` (#4832).
+    + Fixed parsing of `\texorpdfstring`. We were returning the wrong
+      argument as the content.
+    + Support `blockcquote`, `foreignblockquote`, `foreigncblockquote`,
+      `hyphenblockquote`, `hyphencblockquote`, `enquote*`, `foreignquote`,
+      `hyphenquote` from `csquotes` (#4848). Note that `foreignquote`
+      will be parsed as a regular Quoted inline (not using the quotes
+      appropriate to the foreign language).
+    + Support more text-mode accents (#4652). Add support for `\|`, `\b`, `\G`,
+      `\h`, `\d`, `\f`, `\r`, `\t`, `\U`, `\i`, `\j`, `\newtie`,
+      `\textcircled`. Also fall back to combining characters when composed
+      characters are not available.
+    + Resolve `\ref` for figure numbers.
+    + Support `mintinline` (#4365, Marc Schreiber).
+    + Fix siunitx unit commands so they are only recognized in
+      siunitx contexts (#4842). For example, `\l` outside of an
+      siunitx context should be l-slash, not l (for liter).
+    + Fix double `unnumbered` class (#4838). The `unnumbered` class
+      was being included twice for starred sections.
+
+  * RST reader: Don't skip link definitions after comments (#4860).
+
+  * Muse reader (Alexander Krotov):
+
+    + Close the `</quote>` in indented tag test.
+      There is already a separate test for unclosed `</quote>`.
+    + Autonumber sections in the correct order.  Parsing now stops
+      at each section header to ensure the header is registered before
+      parsing of the next section starts.
+    + Move duplicate code into `headingStart` function.
+    + Allow newline after opening `*` or `**`.
+    + Don't allow digits after closing marker in lightweight markup
+      This change makes reader more compatible with Emacs Muse.
+    + Parse `<verse>` tag in one pass instead of using
+      `parseFromString`. This change makes it possible to have
+      verbatim `</verse>` tag inside verse.
+
+  * ODT reader:  deal gracefully with missing `<office:font-face-decls/>`
+    (#4336). This allows pandoc to parse ODT document produced by KDE's
+    Calligra.
+
+  * Muse writer (Alexander Krotov):
+
+    + Output headers without asterisks if not on the top level.
+    + Never wrap definition list terms.
+    + Set `envInsideBlock = True` when rendering notes.
+    + Use `""` instead of `[]` for empty String.
+    + Check for whitespace in the beginning and end of Str's.
+    + Escape `-`, `;` and `>` in the beginning of strings.
+    + Escape list markers in the beginning of notes.
+    + Normalize inline list before testing if tags should be used.
+    + Use tags instead of lightweight markup for empty strings.
+    + Use lightweight markup when possible.
+    + Escape empty strings.  This guarantees that `conditionalEscapeString`
+      never returns empty string.
+    + Wrap conditionalEscapeString result into `Muse` type.
+      This removes the need to pass `envInsideLinkDescription` to it.
+    + Separate `shouldEscapeString` function.
+    + Simplify inline list rendering.
+    + Replace newlines in strings with spaces.
+
+  * Docx writer:
+
+    + Add MetaString case for abstract, subtitle (#4900, Mauro Bieg).
+    + Properly handle display math in spans (#4826). This isn't a
+      complete solution, since other nestings of display math may still
+      cause problems, but it should work for what is by far the most
+      common case.
+
+  * HTML writer:
+
+    + Always output `<dt>` element, even if it is empty (#4883,
+      Alexander Krotov).
+    + Don't prefix `epub:` attributes with `data-`.
+
+  * Org writer: Don't escape literal `_`, `^` (#4882). Org doesn't
+    recognize these escapes.
+
+  * ODT writer: Fix percentage image scaling (#4881, Nils Carlson).
+    Image scaling was broken when a width was set to a percentage.
+
+  * EPUB writer: set `epub:type` on body element in each chapter,
+    depending on the `epub:type` of the first section (#4823). This
+    only affects epub3. See
+    http://www.idpf.org/epub/profiles/edu/structure/#h.l0bzsloklt10
+
+  * FB2 writer: put `coverpage` element between title and date rather than in
+    `document-info` element (#4854).
+
+  * Markdown writer: Escape `~` if strikeout extension enabled (#4840).
+
+  * Haddock writer: Use proper format for latex math in haddock (#4571, Joe
+    Hermaszewski). Inline math in `\(..\)`, display math in `\[..\]`,
+    tex is now used. Previously we'd "fake it with unicode" and fall
+    back to tex when that didn't work. But newer haddock versions
+    support latex math.
+
+  * TEI writer:
+
+    + Ensure that title element is always present, even if empty (#4839).
+    + Put author tags in the template, rather than adding them in
+      the writer (#4839).
+
+  * LaTeX writer/template: be sensitive to `filecolor` variable (#4822).
+    `linkcolor` only affects internal links, and `urlcolor` only
+    affects linked URLs.  For external links, the option to use is
+    `filecolor`.
+
+  * ConTeXt writer: output raw `tex` blocks as well as `context` (#969).
+
+  * RST writer:
+
+    + Use `.. raw:: latex` for `tex` content.
+    + Use `.. container` for generic Divs, instead of raw HTML.
+    + Render Divs with admonition classes as admonitions (#4833).
+      Also omit Div with class `admonition-title`. These are generated
+      by the RST reader and should be omitted on round-trip.
+
+  * Text.Pandoc.PDF: fix message printed when rsvg-convert is not available
+    (#4855, Antonio Terceiro).
+
+  * HTML5 template: add the `title-block-header` identifier to the
+    `header` element, to make it easier to style precisely (#4767,
+    J. B. Rainsberger).
+
+  * OpenDocument template: Remove unnecessary indenting of TOC title (#4798,
+    José de Mattos Neto).
+
+  * latex template: Add support for $toc-title$ to LaTeX (and PDF)
+    (#4853, Wandmalfarbe).
+
+  * TEI template: improve `publicationStmt`. Add support for
+    `publisher`, `address`, `pubPlace`, and `date` variables.
+
+  * beamer template: Support "toc-title" (#4835, Cyril Roelandt).
+
+  * Text.Pandoc.Extensions: Fix haddock on `Ext_footnotes` (Chris Martin).
+
+  * Lua: cleanup Lua utils, remove unused functions (Albert Krewinkel).
+
+  * MANUAL.txt:
+
+    + Clarify that `--biblatex/--natbib` don't work directly for PDF
+      (#4904).
+    + Document `epub:type` attribute (Mauro Bieg, #4901)
+    + Clarify when `--resource-path` has an effect.
+    + More detail on customization in syntax highlighting section.
+    + Document encoding issue with `--listings` (#4871, Damien Clochard).
+    + Remove docs on removed `--katex-stylesheet` (Mauro Bieg, #4862).
+    + Use https for context wiki links (#4910).
+
+  * CONTRIBUTING.md:
+
+    + Link to lua-filters repository (#4874).
+    + Fix mistake in REPL instructions for stack. (#4849, Brian Leung).
+
+  * lua-filters.md: add links to filters, and to lua-filters repository
+    (#4874).
+
+  * INSTALL.md:
+
+    + Indicate that cabal >= 2.0 is needed.
+    + Added chocolatey installation method (#4844, Miodrag Milić).
+
+  * Travis: exclude round-trip tests, except for nightly test which can fail.
+
+  * Use latest texmath, pandoc-citeproc.
+
+  * Use a patched version of foundation until
+    https://github.com/haskell-foundation/foundation/pull/503
+    is fixed.
+
+  * Clean up appveyor build and Windows package creation.
+    We now use 64-bit stack and ghc 8.4.3, lts-12 for the 64-bit build. The
+    WiX-based msi is now 64-bit for 64-bit builds (fixing #4795).
+
+  * Remove obsolete RELEASE-CHECKLIST.md.
+
+  * Added additional compiler warnings in Makefile and CI builds.
+
+## pandoc 2.2.3.2 (2018-08-07)
+
+  * Markdown reader: Properly handle boolean values in YAML metadata (#4819).
+    This fixes a regression in 2.2.3, which cause boolean values to
+    be parsed as MetaInlines instead of MetaBool.
+
+    We here record another undocumented (but desirable) change in 2.2.3:
+    numerical metadata fields are now parsed as MetaInlines rather than
+    MetaString.
+
+## pandoc 2.2.3.1 (2018-08-06)
+
+  * Markdown reader: Fix parsing of embedded mappings in YAML metadata
+    (#4817).  This fixes a regression in 2.2.3 which caused embedded
+    mappings (e.g. mappings in sequences) not to work in YAML metadata.
+
+## pandoc 2.2.3 (2018-08-05)
+
+  * RST reader: improve parsing of inline interpreted text roles (#4811).
+
+    + Use a Span with class "title-reference" for the default
+      title-reference role.
+    + Use `B.text` to split up contents into `Space`s, `SoftBreak`s,
+      and `Str`s for `title-reference`.
+    + Use Code with class "interpreted-text" instead of Span and Str for
+      unknown roles.  (The RST writer has also been modified to round-trip
+      this properly.)
+    + Disallow blank lines in interpreted text.
+    + Backslash-escape now works in interpreted text.
+    + Backticks followed by alphanumerics no longer end interpreted text.
+    + Remove support for nested inlines (Francesco Occhipinti).
+      RST does not allow nested emphasis, links, or other inline
+      constructs.  This fixes several bugs (#4581, #4561, #4792).
+
+  * Org reader: fix parsers relying on `parseFromString` (#4784, Albert
+    Krewinkel).  Emphasis was not parsed when it followed directly after
+    some block types (e.g., lists).
+
+  * Markdown reader: Allow unquoted numbers and booleans as YAML mapping
+    keys.  Previously in 2.2.2 you could not do
+    ```
+    ---
+    0: bar
+    ...
+    ```
+    but only
+    ```
+    ---
+    '0': bar
+    ...
+    ```
+    With this change, both forms work.
+
+  * DocBook reader: metadata handling improvements.
+    Now we properly parse title and subtitle elements that are direct
+    children of book and article (as well as children of bookinfo,
+    articleinfo, or info).  We also now use the `subtitle` metadata
+    field for subtitles, rather than tacking the subtitle on to the
+    title.
+
+  * RST writer:
+
+    + Allow images to be directly nested within links (#4810, Francesco
+      Occhipinti).
+    + Use `titleblock` instead of `title` variable for title block (#4803,
+      Francesco Occhipinti).  `titleblock` contains a properly formatted
+      title and subtitle (using top-level headers).  `title` and
+      `subtitle` variables are still available and just contain the
+      title and subtitle text.  Note that this change will require an
+      update to custom rst templates.
+    + Render Code with class "interpreted-text" as interpreted text role.
+
+  * MediaWiki writer: Avoid extra blank line in tables with empty cells
+    (#4794).  Note that the old output is semantically identical, but the
+    new output looks better.
+
+  * Lua Utils module: add function `blocks_to_inlines` (#4799, Albert
+    Krewinkel).  Exposes a function converting which flattenes a list of
+    blocks into a list of inlines. An example use case would be the
+    conversion of Note elements into other inlines.
+
+  * RST template:  use `titleblock` instead of `title`.  Users of
+    custom RST templates will want to update this.
+
+  * LaTeX template: Moved some beamer code in default.latex template.
+    This change allows beamer themes to change the template and font (as
+    Metropolis does) (#4450).
+
+  * Better error message on `-t pdf -o out.pdf` (#1155, Mauro Bieg).
+
+  * Added test case for #4669 to repository.
+
+  * INSTALL.md: Fix broken link for cabal-install (#4806, ChanHoHo).
+
+  * MANUAL.txt:
+
+    + Add beamer info for slide backgrounds (#4802, John Muccigrosso).
+    + Clarify when `csquotes` is used in LaTeX writer (#4514).
+    + Add `commonmark` to list of output formats where `raw_tex` has an
+      effect (see #4527).
+
+
+## pandoc 2.2.2.1 (2018-07-19)
+
+  * Fix regression finding templates in user data directory (#4777).
+    Under version 2.2.1 and prior pandoc found latex templates in the
+    templates directory under the data directory, but this broke in 2.2.2.
+
+  * Fix for bug in parsing `\input` in `rawLaTeXBlock` and
+    `rawLaTeXInline` (#4781). (This primarily affects the markdown
+    reader, and other readers that accept raw tex.)
+    Starting in 2.2.2, everything after an `\input` (or `\include`)
+    in a markdown file would be parsed as raw LaTeX.
+
+  * MANUAL:
+
+    + Clarify `gfm` vs `markdown_github` (#4783, Mauro Bieg).
+    * Use `keywords` instead of `tags` in YAML metadata example (#4779).
+      Unlike `tags`, `keywords` is used in some of the writers
+      and default templates.
+
+  * Add missing `rollingLinks` option to revealjs template (#4778,
+    Igor Khorlo).
+
+## pandoc 2.2.2 (2018-07-16)
+
+  * Use HsYAML instead of yaml for translations and YAML metadata (#4747).
+    yaml wraps a C library; HsYAML is pure Haskell.  Advances #4535.
+
+    Note: HsYAML implements YAML 1.2, in which the valid true
+    values are `true`, `True`, `TRUE`.  This means a change in
+    the semantics of YAML metadata that could affect users:
+    `y`, `yes`, and `on` no longer count as true values.
+
+  * Fix regression: make `--pdf-engine` work with full paths (#4681, Mauro
+    Bieg).
+
+  * CommonMark reader: Handle `ascii_identifiers` extension (#4742,
+    Anders Waldenborg).  Non-ascii characters were not stripped from
+    identifiers even if the `ascii_identifiers` extension was
+    enabled (which is is by default for gfm).
+
+  * TikiWiki reader: Improve list parsing (#4722, Mauro Bieg).
+    Remove trailing Space from list items.  Parse lists that have no space
+    after marker.
+
+  * LaTeX reader:
+
+    + Treat `lilypond` as a verbatim environment (#4725).
+    + Parse figure label into Image id (#4700, Mauro Bieg).
+    + Beamer: Allow "noframenumbering" option (#4696, Raymond Ehlers).
+    + Allow spaces around `\graphicspath` arguments (#4698).
+    + Handle includes without surrounding blanklines (#4553).
+      In addition, `\input` can now be used in an inline context,
+      e.g. to provide part of a paragraph, as it can in LaTeX.
+    + In `rawLaTeXBlock`, handle macros that resolve to a
+      `\begin` or `\end` (#4667).
+    + In `rawLaTeXBlock`, don't expand macros in macro definitions (#4653).
+      Note that this only affected LaTeX in markdown.
+    + Tighten up reading of beamer overlay specifications (#4669).
+      Ideally we'd turn these on only when reading beamer, but currently
+      beamer is not distinguished from latex as an input format.
+      This commit also activates parsing of overlay specifications
+      after commands in general (e.g. `\item`), since they can occur
+      in many contexts in beamer.
+    + Parse more siunitx unit commands (#4296, #4773).
+    + Be more forgiving in key/value option parsing (#4761).
+
+  * Markdown reader:
+
+    + Allow empty code spans, e.g. `` ` ` ``.
+    + Emojis are now wrapped in Spans with class `emoji` and
+      attribute `data-emoji` (Anders Waldenborg, #4743).
+      This allows the writer to handle them in a special way
+      (e.g. using a special font, or just rendering the
+      emoji name).
+
+  * Muse reader (Alexander Krotov, except where indicated):
+
+    + Get rid of non-exhaustive pattern match warning (Mauro Bieg).
+    + Add support for floating images.
+    + Add support for images with specified width.
+    + Parse image URLs without "guard" and "takeExtension".
+    + Split link and image parsing into separate functions.
+    + Parse links starting with "URL:" explicitly instead of trying to strip
+      "URL:" prefix after parsing.
+
+  * Texinfo writer: Use `@sup` and `@sub` instead of custom macros (#4728,
+    Alexander Krotov).
+
+  * Markdown writer: Preserve `implicit_figures` with attributes, even if
+    `implicit_attributes` is not set, by rendering in raw HTML (#4677).
+
+  * Markdown and commonmark/github writers now respect the `emoji`
+    extension.  So, `-f markdown+emoji -t markdown+emoji` now leaves
+    `:smile:` as `:smile:` rather than converting it to a smile
+    character.
+
+  * Docx writer: Be sensitive to `toc` in YAML metadata (#4645).
+
+  * ODT/OpenDocument writer: Make internal links work (#4358).
+    This adds proper bookmarks to the headers with non-null IDs.
+
+  * EPUB writer: Properly escape pagetitle.  Previously we weren't
+    escaping `&` and other XML characters in the pagetitle, so a title
+    containing a `&` would be invalid.
+
+  * AsciiDoc Writer: Eescape square brackets at start of line (#4545,
+    Mauro Bieg).
+
+  * RST writer:
+
+    + Don't treat 'example' as a syntax name (#4748).
+      This fixes conversions from org with example blocks.
+    + Support `--number-sections` via the `section-numbering`
+      directive in standalone output.
+
+  * reveal.js writer and template: reuse mathjax URL
+    provided by the argument to `--mathjax` or the normal pandoc default,
+    rather than a hard-coded one in the template (#4701).
+
+  * LaTeX writer:
+
+    + Properly handle footnotes in table captions (#4683).
+      Refactored code from figure captions to use in both places.
+    + In beamer output, fix single digit column percentage (#4690, Mauro
+      Bieg).
+
+  * FB2 writer (Alexander Krotov):
+
+    + Convert Plain to Para in annotation (#2424).
+    + Fix order of items in title-info (#2424).
+
+  * Custom writer: fix error message on script failure (Albert Krewinkel).
+    Error messages produced by Lua were not displayed by Pandoc.
+
+  * Text.Pandoc.Emoji now exports `emojiToInline`, which returns a Span
+    inline containing the emoji character and some attributes with metadata
+    (class `emoji`, attribute `data-emoji` with emoji name).  (API change,
+    Anders Waldenborg, #4743).
+
+  * Text.Pandoc.PDF:
+
+    + Revert fix for #4484 (only compress images on last run, #4755).
+      This will mean some increase in the time it takes to
+      produce an image-heavy PDF with xelatex, but it will
+      make tables of contents correct, which is more important.
+    + Fix logic error in `runTeXProgram`.  We were running the tex program
+      one more time than requested.  This should speed up PDF production.
+
+  * Allow `--template` to take a URL as argument.
+
+  * Text.Pandoc.Highlighting: Add missing re-export of `breezeDark`
+    highlighting style (#4687, Adrian Sieber, API change).
+
+  * Clarify macOS install in INSTALL.md (#4661).  Make the binary package
+    installer the recommended method, and note that on some older versions of
+    macOS, homebrew installs from source and takes a lot of disk space
+    (#4664, Ian).
+
+  * MANUAL:
+
+    + Clarify EPUB linked media (#4756, Mauro Bieg)
+    + Update manual for "true" YAML values.  Now that we're using HsYAML and
+      YAML 1.2, the valid true values are `true`, `True`, `TRUE`.  NOTE!
+      `y`, `yes`, `on` no longer count as true values.
+    + Document `-F` as alias for `--filter` (thanks to Gandalf Saxe).
+    + Update manual on how math is rendered in LaTeX.
+    + Add proxy description (#4131, Mauro Bieg).
+    + Clarify that `--toc` requires `--standalone` (#4703).
+    + Update citation styles link (#4699, wiefling).
+
+  * In API docs, clarify how `Ext_east_asian_line_breaks` extension works
+    (kaizshang91).  Note that it will not take effect when readers/writers
+    are called as libraries (#4674).
+
+  * Improved translations/fr (#4766, lux-lth).
+
+  * Removed inadvertently added `.orig` files from repository (#4648).
+
+  * Remove `network-uri` flag and use 'Network.Socket'.
+    This removes a compiler warning.  There is no need for the old
+    `network-uri` flag, since network 2.6 was released in 2014.
+
+  * Add stack.lts10.yaml, stack.lts11.yaml.  use lts-12 in stack.yaml.
+
+  * Bump upper bounds for dependent packages.
+
+  * Exclude foundation 0.0.21 for ghc 7.10.  Otherwise cabal gets
+    confused because of the way ghc 7.10 is excluded in foundation's
+    cabal file.  This can be removed when haskell-foundation/foundation#500
+    is fixed.
+
+  * Require cabal-version >= 2.0.  This is needed for haddock-library.
+
+
+
+
+## pandoc 2.2.1 (2018-05-10)
+
+  * Restored and undeprecated gladtex for HTML math (#4607).
+
+    + Added `GladTeX` constructor to `Text.Pandoc.Options.HTMLMathMethod`
+      [API change, reverts removal in v2.2]
+    + Restored and undeprecated `--gladtex` option, removed in v2.2.
+
+  * LaTeX reader:  Handle `$` in `/text{..}` inside math (#4576).
+
+  * Org reader: Fix image filename recognition (Albert Krewinkel).
+    Use a function from the filepath library to check whether a string is a
+    valid file name.  The custom validity checker that was used before gave
+    wrong results (e.g. for absolute file paths on Windows,
+    kawabata/ox-pandoc#52).
+
+  * FB2 reader: Replace some errors with warnings (Alexander Krotov).
+
+  * HTML writer:
+
+    + Strip links from headers when creating TOC (#4340).
+      Otherwise the TOC entries will not link to the sections.
+    + Fix regression with tex math environments in HTML + MathJax (#4639).
+
+  * Muse writer (Alexander Krotov): Add support for left-align and
+    right-align classes (#4542).
+
+  * Docx writer: Support underline (#4633).
+
+  * Text.Pandoc.Parsing: Lookahead for non-whitespace after
+    `singleQuoteStart` and `doubleQuoteStart` (#4637).
+
+  * `test-pandoc-utils.lua`:  more robust testing on both windows
+    and \*nix. Previously the pipe tests were only run if
+    `\bin/false` and `/bin/sed` were present, which they aren't
+    in default MacOS and Windows systems.  Fixed by using `tr`
+    and `false`, which should always be in the path on a \*nix
+    system, and `find` and `echo` for Windows.
+
+  * Text.Pandoc.Shared: add `uriPathToPath`.
+    This adjusts the path from a file: URI in a way that is sensitive
+    to Windows/Linux differences.  Thus, on Windows,
+    `/c:/foo` gets interpreted as `c:/foo`, but on Linux,
+    `/c:/foo` gets interpreted as `/c:/foo`.  See #4613.
+
+  * Use `uriPathToPath` with file: URIs (#4613).
+
+  * Revert piping HTML to pdf-engine (Mauro Bieg, #4413).  Use a temp
+    file as before.
+
+  * Text.Pandoc.Class: Catch IO errors when writing media files
+    and issue a warning, rather than an error (Francesco Occhipinti, #4559).
+
+  * Don't lowercase custom writer filename (Alexander Krotov, #4610).
+
+  * MANUAL (Mauro Bieg):
+
+    + Clarify truthiness in template variables (#2281).
+    + Clarify pipe table width calculation (#4520).
+
+  * ConTeXt template: New Greek fallback typeface (Pablo Rodríguez, #4405).
+    CMU Serif gives better typographic results than the previous
+    Greek fallback DejaVu Serif.
+
+  * Make HTML template polyglot (#4606, OvidiusCicero), by making
+    `<link rel="stylesheet" href="$css$">` self-closing.
+
+  * Use texmath 0.11, allowing better translation of non-ASCII
+    characters in math (#4642).
+
+
+## pandoc 2.2 (2018-04-27)
+
+  * New input format: `fb2` (FictionBook2) (Alexander Krotov).
+
+  * Make `--ascii` work for all XML formats (ICML, OPML, JATS,...),
+    and for `ms` and `man`.
+
+  * Remove deprecated `--latexmathml`, `--gladtex`, `--mimetex`, `--jsmath`, `-m`,
+    `--asciimathml` options.
+
+  * New module Text.Pandoc.Readers.FB2, exporting readFB2 (Alexander
+    Krotov, API change).
+
+  * Markdown reader:
+
+    + Allow empty key-value attributes, like `title=""` (#2944).
+    + Handle table w/o following blank line in fenced div (#4560).
+    + Remove "fallback" for `doubleQuote` parser.  Previously the
+      parser tried to be efficient -- if no end double quote was found,
+      it would just return the contents.  But this could backfire in a
+      case `**this should "be bold**`, since the fallback would return
+      the content `"be bold**` and the closing boldface delimiter
+      would never be encountered.
+    + Improve computation of the relative width of the last column in a
+      multiline table, so we can round-trip tables without constantly
+      shrinking the last column.
+
+  * EPUB reader:
+
+    + Fix images with space in file path (#4344).
+
+  * LaTeX reader:
+
+    + Properly resolve section numbers with `\ref` and chapters (#4529).
+    + Parse sloppypar environment (#4517, Marc Schreiber).
+    + Improve handling of raw LaTeX (for markdown etc.) (#4589, #4594).
+      Previously there were some bugs in how macros were handled.
+    + Support `\MakeUppercase`, `\MakeLowercase`, `\uppercase`,
+      `\lowercase`, and also `\MakeTextUppercase` and
+      `\MakeTextLowercase` from textcase (#4959).
+
+  * Textile reader:
+
+    + Fixed tables with no body rows (#4513).
+      Previously these raised an exception.
+
+  * Mediawiki reader:
+
+    + Improve table parsing (#4508).  This fixes detection of table
+      attributes and also handles `!` characters in cells.
+
+  * DocBook reader:
+
+    + Properly handle title in `section` element (#4526).
+      Previously we just got `section_title` for `section` (though `sect1`,
+      `sect2`, etc. were handled properly).
+    + Read tex math as output by asciidoctor (#4569, Joe Hermaszewski).
+
+  * Docx reader:
+
+    + Combine adjacent CodeBlocks with the same attributes into
+      a single CodeBlock.  This prevents a multiline codeblock in
+      Word from being read as different paragraphs.
+
+  * RST reader:
+
+    + Allow < 3 spaces indent under directives (#4579).
+    + Fix anonymous redirects with backticks (#4598).
+
+  * Muse reader (Alexander Krotov):
+
+    + Add support for Text::Amuse multiline headings.
+    + Add `<math>` tag support.
+    + Add support for `<biblio>` and `<play>` tags.
+    + Allow links to have empty descriptions.
+    + Require block `<literal>` tags to be on separate lines.
+    + Allow `-` in anchors.
+    + Allow verse to be indented.
+    + Allow nested footnotes.
+    + Internal improvements.
+
+  * Muse writer (Alexander Krotov):
+
+    + Escape `>` only at the beginning of a line.
+    + Escape `]` in image title.
+    + Escape `]` brackets in URLs as `%5D`.
+    + Only escape brackets when necessary.
+    + Escape ordered list markers.
+    + Do not escape list markers unless preceded by space.
+    + Escape strings starting with space.
+    + Escape semicolons and markers after line break.
+    + Escape `;` to avoid accidental comments.
+    + Don't break headers, line blocks and tables with line breaks.
+    + Correctly output empty headings.
+    + Escape horizontal rule only if at the beginning of the line.
+    + Escape definition list terms starting with list markers.
+    + Place header IDs before header.
+    + Improve span writing.
+    + Do not join Spans in normalization.
+    + Don't align ordered list items.
+    + Remove key-value pairs from attributes before normalization.
+    + Enable `--wrap=preserve` for all tests by default.
+    + Reduced `<verbatim>` tags in output.
+    + Internal changes.
+
+  * RST writer:
+
+    + Use more consistent indentation (#4563).  Previously we
+      used an odd mix of 3- and 4-space indentation.  Now we use 3-space
+      indentation, except for ordered lists, where indentation must
+      depend on the width of the list marker.
+    + Flatten nested inlines (#4368, Francesco Occhipinti).
+      Nested inlines are not valid RST syntax, so we flatten them following
+      some readability criteria discussed in #4368.
+
+  * EPUB writer:
+
+    + Ensure that `pagetitle` is always set, even when structured titles
+      are used.  This prevents spurious warnings about empty title
+      elements (#4486).
+
+  * FB2 writer (Alexander Krotov):
+
+    + Output links inline instead of producing notes.  Previously all links
+      were turned into footnotes with unclickable URLs inside.
+    + Allow emphasis and notes in titles.
+    + Don't intersperse paragraph with empty lines.
+    + Convert metadata value `abstract` to book annotation.
+    + Use `<empty-line />` for `HorizontalRule` rather than `LineBreak`.
+      FB2 does not have a way to represent line breaks inside paragraphs;
+      previously we used `<empty-line />` elements, but these are not allowed
+      inside paragraphs.
+
+  * Powerpoint writer (Jesse Rosenthal):
+
+    + Handle Quoted Inlines (#4532).
+    + Simplify code with `ParseXml`.
+    + Allow fallback options when looking for placeholder type.
+    + Check reference-doc for all layouts.
+    + Simplify speaker notes logic.
+    + Change notes state to a simpler per-slide value.
+    + Remove `Maybe` from `SpeakerNotes` in `Slide`. `mempty`
+      means no speaker notes.
+    + Add tests for improved speaker notes.
+    + Handle speaker notes earlier in the conversion process.
+    + Keep notes with related blocks (#4477).  Some blocks automatically
+      split slides (imgs, tables, `column` divs). We assume that any
+      speaker notes immediately following these are connected to these
+      elements, and keep them with the related blocks, splitting after them.
+    + Remove `docProps/thumbnail.jpeg` in data dir (Jesse Rosenthal, #4588).
+      It contained a nonfree ICC color calibration profile and is not needed
+      for production of a powerpoint document.
+
+  * Markdown writer:
+
+    + Include a blank line at the end of the row in a single-row multiline
+      table, to prevent it from being interpreted as a simple table (#4578).
+
+  * CommonMark writer:
+
+    + Correctly ignore LaTeX raw blocks when `raw_tex` is not
+      enabled (#4527, quasicomputational).
+
+  * EPUB writer:
+
+    + Add `epub:type="footnotes"` to notes section in EPUB3 (#4489).
+
+  * LaTeX writer:
+
+    + In beamer, don't use format specifier for default ordered lists
+      (#4556).  This gives better results for styles that put ordered list
+      markers in boxes or circles.
+    + Update `\lstinline` delimiters (#4369, Tim Parenti).
+
+  * Ms writer:
+
+    + Use `\f[R]` rather than `\f[]` to reset font (#4552).
+    + Use `\f[BI]` and `\f[CB]` in headers, instead of `\f[I]` and `\f[C]`,
+      since the header font is automatically bold (#4552).
+    + Use `\f[CB]` rather than `\f[BC]` for monospace bold (#4552).
+    + Create pdf anchor for a Div with an identifier (#4515).
+    + Escape `/` character in anchor ids (#4515).
+    + Improve escaping for anchor ids: we now use _uNNN_ instead of uNNN
+      to avoid ambiguity.
+
+  * Man writer:
+
+    + Don't escape U+2019 as `'` (#4550).
+
+  * Text.Pandoc.Options:
+
+    + Removed `JsMath`, `LaTeXMathML`, and `GladTeX` constructors from
+    `Text.Pandoc.Options.HTMLMathMethod` [API change].
+
+  * Text.Pandoc.Class:
+
+    + `writeMedia`: unescape URI-escaping in file path.  This avoids
+      writing things like `file%20one.png` to the file system.
+
+  * Text.Pandoc.Parsing:
+
+    + Fix `romanNumeral` parser (#4480).  We previously accepted 'DDC'
+      as 1100.
+    + `uri`: don't treat `*` characters at end as part of URI (#4561).
+
+  * Text.Pandoc.MIME:
+
+    + Use the alias `application/eps` for EPS (#2067).
+      This will ensure that we retain the eps extension after reading the
+      image into a mediabag and writing it again.
+
+  * Text.Pandoc.PDF:
+
+    + Use `withTempDir` in `html2pdf`.
+    + With `xelatex`, don't compress images til the last run (#4484).
+      This saves time for image-heavy documents.
+    + Don't try to convert EPS files (#2067).  `pdflatex` converts them
+      itself, and JuicyPixels can't do it.
+    + For `pdflatex`, use a temp directory in the working directory.
+      Otherwise we can have problems with the EPS conversion pdflatex
+      tries to do, which can't operate on a file above the working
+      directory without `--shell-escape`.
+
+  * Changes to tests to accommodate changes in pandoc-types.
+    In <https://github.com/jgm/pandoc-types/pull/36> we changed
+    the table builder to pad cells.  This commit changes tests
+    (and two readers) to accord with this behavior.
+
+  * Set default extensions for `beamer` same as `latex`.
+
+  * LaTeX template:
+
+    + Add `beameroption` variable (#4359, Étienne Bersac).
+    + Use `pgfpages` package; this is needed for notes on second
+      screen in beamer (Étienne Bersac).
+    + Add `background-image` variable (#4601, John Muccigrosso).
+
+  * reveal.js template: Add `background-image` variable (#4600,
+    John Muccigrosso).
+
+  * ms template: Fix date.  Previously `.ND` was used, but this only
+    works if you have a title page, which we don't.  Thanks to @teoric.
+
+  * Removed pragmas for unused extensions (#4506, Anabra).
+
+  * Fix bash completion for `--print-default-data-file` (#4549).
+    Previously this looked in the filesystem, even if pandoc
+    was compiled with `embed_data_files` (and sometimes it looked
+    in a nonexistent build directory).  Now the bash completion
+    script just includes a hard-coded list of data file names.
+
+  * MANUAL:
+
+    + Clarify template vs metadata variables (#4501, Mauro Bieg).
+    + Fix raw content example (#4479, Mauro Bieg).
+    + Specify that you use html for raw output in epub.
+    + Add examples for raw docx blocks (#4472, Tristan Stenner).
+      The documentation states that the target format name should match
+      the output format, which isn't the case for `docx`/`openxml` and
+      some others.
+    + Don't say that `empty_paragraphs` affects markdown output (#4540).
+    + Consolidate input/output format documentation (#4577, Mauro Bieg).
+
+  * New README template. Take in/out formats from manual.
+
+  * Fix example in lua-filters docs (#4459, HeirOfNorton).
+
+  * Use the `-threaded` GHC flag when building benchmarks (#4587,
+    Francesco Occhipinti).
+
+  * Bump temporary upper bound to 1.4.
+
+  * Use pandoc-citeproc 0.14.3.1.
+
+  * Use texmath-0.10.1.2 (fixes escapes in math in ms, #4597).
+
+  * Removed old lib directory.  This was used for something long ago,
+    but plays no role now.
+
+  * Removed unneeded data file `LaTeXMathML.js`.
+
+  * Create 64- and 32-bit versions of Windows binary packages.
+
+## pandoc 2.1.3 (2018-03-18)
+
+  * Docx reader (Jesse Rosenthal):
+
+    + Add tests for nested smart tags.
+    + Parse nested smart tags.
+    + Make unwrapSDT into a general `unwrap` function that can unwrap both
+      nested SDT tags and smartTags. This makes the SmartTags constructor in
+      the Docx type unnecessary, so we remove it (#4446).
+    + Remove unused `docxWarnings` (Alexander Krotov).
+
+  * RST reader: Allow unicode bullet characters (#4454).
+
+  * Haddock reader:  Better table handling, using haddock-library's
+    new table support, if compiled against a version that
+    includes it.  Note that tables with col/rowspans will not
+    translate well into Pandoc.
+
+  * Muse reader (Alexander Krotov):
+
+    + Various internal improvements.
+    + Require closing tag to have the same indentation as opening.
+    + Do not reparse blocks inside unclosed block tag (#4425).
+    + Parse `<class>` tag (supported by Emacs Muse).
+    + Do not produce empty Str element for unindented verse lines.
+
+  * LaTeX reader:
+
+    + Add support to parse unit string of `\SI` command (closes #4296,
+      Marc Schreiber).
+
+  * Haddock writer:  In the writer, we now render tables always as
+    grid tables, since Haddock supports these.
+
+  * DokuWiki writer: rewrite backSlashLineBreaks (#4445, Mauro Bieg).
+
+  * Docx writer: Fixed formatting of `DefaultStyle` ordered lists in
+    docx writer.  We want decimal for the top level, not lower roman.
+
+  * RST writer:
+
+    + Strip whitespace at beginning and ending of inline containers
+      (#4327, Francesco Occhipinti).
+    + Filter out empty inline containers (#4434).  There is nothing in
+      RST that corresponds to e.g. `Emph []`, so we just ignore elements
+      like this (Francesco Occhipinti).
+
+  * Muse writer (Alexander Krotov):
+
+    + Support spans with anchors.
+    + Replace smallcaps with emphasis before normalization.
+    + Output smallcaps as emphasis.
+    + Expand Cite before list normalization.
+    + Write empty inline lists as `<verbatim></verbatim>`.
+    + Remove empty Str from the beginning of inline lists during normalization.
+    + Escape "-" to avoid creating bullet lists.
+    + Fix math expansion for more than one expression per paragraph.
+    + Expand math before inline list normalization.
+
+  * Dokuwiki writer: fix LineBreaks in Tables (#4313, Mauro Bieg).
+
+  * Ms writer:
+
+    + Asciify pdf anchors, since unicode anchors don't work (#4436).
+      Internal links should be converted automatically, so this shouldn't
+      affect users directly.
+    + Don't escape hyphens as `\-`; that's for a minus sign (#4467).
+
+  * Beamer writer: put hyperlink after `\begin{frame}` and not in the title
+    (#4307).  If it's in the title, then we get a titlebar on slides with
+    the `plain` attribute, when the id is non-null.  This fixes a regression
+    in 2.0.
+
+  * EPUB writer: Remove notes from TOC in nav.xhtml (#4453, Mauro Bieg).
+
+  * JATS writer: Remove extraneous, significant whitespace (#4335,
+    Nokome Bentley).
+
+  * html2pdf: inject base tag with current working directory (#4413, Mauro
+    Bieg).  This helps ensure that linked resources are included.
+
+  * Add Semigroup instances for everything for which we defined a
+    Monoid instance previously (API change):
+
+    + Text.Pandoc.Class.FileTree.
+    + Text.Pandoc.Translations.Translations.
+    + Text.Pandoc.Extensions.Extensions.
+    + Text.Pandoc.Readers.Odt.StyleReader.Styles.
+    + Text.Pandoc.Pretty.Doc.
+    + Text.Pandoc.MediaBag.MediaBag.
+
+  * Add custom Prelude to give clean code for Monoid and Semigroup
+    that works with ghc 7.10-8.4.  The custom Prelude (`prelude/Prelude`)
+    is used for ghc versions < 8.4.  `NoImplicitPrelude` is used
+    in all source files, and Prelude is explicitly imported
+    (this is necessary for ghci to work properly with the custom prelude).
+
+  * Text.Pandoc.Writers.Shared (Francesco Occhipinti):
+
+    + Export `stripLeadingTrailingSpace`.
+    + Don't wrap lines in grid tables when `--wrap=none` (#4320).
+    + `gridTable`: Don't wrap lines in tables when `--wrap=none`.  Instead,
+      expand cells, even if it results in cells that don't respect relative
+      widths or surpass page column width.  This change affects RST,
+      Markdown, and Haddock writers.
+
+  * Raise error if someone tries to print docx, odt, etc. template (#4441).
+
+  * LaTeX template: Provide `bidi` package's option using
+    `\PassOptionsToPackage`  (#4357, Václav Haisman).  This avoid a
+    clash when   `polyglossia` loads it first and then it is loaded again
+    for XeLaTeX.
+
+  * ConTeXt template: Added `pdfa` variable to generate PDF/A (#4294, Henri
+    Menke).  Instructions on how to install the ICC profiles on ConTeXt
+    standalone can be found in the wiki:
+    <http://wiki.contextgarden.net/PDFX#ICC_profiles>.
+    If the ICC profiles are not available the log will contain error
+    messages.
+
+  * Use latest pandoc-types, skylighting
+
+  * Use latest pandoc-citeproc in binary package.
+
+  * Bump upper bound for time, criterion, haddock-library, exceptions,
+    http-types, aeson, haddock-library.
+
+  * Bump upper bound tasty-quickcheck 0.10 (#4429, Felix Yan).
+
+  * pandoc.cabal:  fix up other-extensions and language fields.
+    Language is now consistently `Haskell2010`, and other-extensions
+    is consistently `NoImplicitPrelude`. Everything else to be specified
+    in the module header as needed.
+
+  * Removed `old-locale` flag and Text.Pandoc.Compat.Time.
+    This is no longer necessary since we no longer support ghc 7.8.
+
+  * Make `weigh-pandoc` into a benchmark program.
+    Remove `weigh-pandoc` flag.  `weigh-pandoc` is now built (and run)
+    automatically when you build (and run) benchmarks.
+
+  * MANUAL: add instructions for background images reveal.js (#4325, John
+    Muccigrosso).
+
+  * appveyor: use VS 2013 environment instead of VS 2015 for Windows builds.
+
+## pandoc 2.1.2 (2018-03-02)
+
+  * Markdown reader:
+
+    + Fix parsing bug with nested fenced divs (#4281).  Previously we allowed
+      "nonindent spaces" before the opening and closing `:::`, but this
+      interfered with list parsing, so now we require the fences to be flush with
+      the margin of the containing block.
+
+  * Commonmark reader:
+
+    + `raw_html` is now on by default.  It can be disabled explicitly
+      using `-f commonmark-raw_html`.
+
+  * Org reader (Albert Krewinkel):
+
+    + Move citation tests to separate module.
+    + Allow changing emphasis syntax (#4378).  The characters allowed before
+      and after emphasis can be configured via `#+pandoc-emphasis-pre` and
+      `#+pandoc-emphasis-post`, respectively. This allows to change which
+      strings are recognized as emphasized text on a per-document or even
+      per-paragraph basis.  Example:
+
+          #+pandoc-emphasis-pre: "-\t ('\"{"
+          #+pandoc-emphasis-post: "-\t\n .,:!?;'\")}["
+
+  * LaTeX reader:
+
+    + Fixed comments inside citations (#4374).
+    + Fix regression in package options including underscore (#4424).
+    + Make `--trace` work.
+    + Fixed parsing of `tabular*` environment (#4279).
+
+  * RST reader:
+
+    + Fix regression in parsing of headers with trailing space (#4280).
+
+  * Muse reader (Alexander Krotov):
+
+    + Enable `<literal>` tags even if amuse extension is enabled.
+      Amusewiki disables <literal> tags for security reasons.
+      If user wants similar behavior in pandoc, RawBlocks and RawInlines
+      can be removed or replaced with filters.
+    + Remove space prefix from `<literal>` tag contents.
+    + Do not consume whitespace while looking for closing end tag.
+    + Convert alphabetical list markers to decimal in round-trip test.
+      Alphabetical lists are an addition of Text::Amuse.
+      They are not present in Emacs Muse and can be ambiguous
+      when list starts with "i.", "c." etc.
+    + Allow `<quote>` and other tags to be indented.
+    + Allow single colon in definition list term.
+    + Fix parsing of verse in lists.
+    + Improved parsing efficiency.  Avoid `parseFromString`.
+      Lists are parsed in linear instead of exponential time now.
+    + Replace ParserState with MuseState.
+    + Prioritize lists with roman numerals over alphabetical lists.
+      This is to make sure "i." starts a roman numbered list,
+      instead of a list with letter "i" (followed by "j", "k", ...").
+    + Fix directive parsing.
+    + Parse definition lists with multiple descriptions.
+    + Parse next list item before parsing more item contents.
+    + Fixed a bug: headers did not terminate lists.
+    + Move indentation parsing from `definitionListItem` to `definitionList`.
+    + Paragraph indentation does not indicate nested quote.
+      Muse allows indentation to indicate quotation or alignment,
+      but only on the top level, not within a <quote> or list.
+    + Require that block tags are on separate lines.
+      Text::Amuse already explicitly requires it anyway.
+    + Fix matching of closing inline tags.
+    + Various internal changes.
+    + Fix parsing of nested definition lists.
+    + Require only one space for nested definition list indentation.
+    + Do not remove trailing whitespace from `<code>`.
+    + Fix parsing of trailing whitespace.  Newline after whitespace now
+      results in softbreak instead of space.
+
+  * Docx reader (Jesse Rosenthal, except where noted):
+
+    + Handle nested sdt tags (#4415).
+    + Don't look up dependant run styles if `+styles` is enabled.
+    + Move pandoc inline styling inside custom-style span.
+    + Read custom styles (#1843).  This will read all paragraph and
+      character classes as divs and spans, respectively. Dependent styles
+      will still be resolved, but will be wrapped with appropriate style
+      tags. It is controlled by the `+styles` extension (`-f docx+styles`).
+      This can be used in conjunction with the `custom-style` feature in the
+      docx writer for a pandoc-docx editing workflow. Users can convert from
+      an input docx, reading the custom-styles, and then use that same input
+      docx file as a reference-doc for producing an output docx file. Styles
+      will be maintained across the conversion, even if pandoc doesn't
+      understand them.
+    + Small change to Fields hyperlink parser.  Previously, unquoted string
+      required a space at the end of the line (and consumed it). Now we
+      either take a space (and don't consume it), or end of input.
+    + Pick table width from the longest row or header (Francesco Occhipinti,
+      #4360).
+
+  * Muse writer (Alexander Krotov):
+
+    + Change verse markup: `> ` instead of `<verse>` tag.
+    + Remove empty strings during inline normalization.
+    + Don't indent nested definition lists.
+    + Use unicode quotes for quoted text.
+    + Write image width specified in percent in Text::Amuse mode.
+    + Don't wrap displayMath into `<verse>`.
+    + Escape nonbreaking space (`~~`).
+    + Join code with different attributes during normalization.
+    + Indent lists inside Div.
+    + Support definitions with multiple descriptions.
+
+  * Powerpoint writer (Jesse Rosenthal):
+
+    + Use table styles This will use the default table style in the
+      reference-doc file. As a result they will be easier when using
+      in a template, and match the color scheme.
+    + Remove empty slides.  Because of the way that slides were split, these
+      could be accidentally produced by comments after images.  When animations
+      are added, there will be a way to add an empty slide with either
+      incremental lists or pauses.
+    + Implement syntax highlighting.  Note that background colors can't
+      be implemented in PowerPoint, so highlighting styles that require
+      these will be incomplete.
+    + New test framework for pptx.  We now compare the output of the
+      Powerpoint writer with files that we know to (a) not be corrupt,
+      and (b) to show the desired output behavior (details below).
+    + Add `notesMaster` to `presentation.xml` if necessary.
+    + Ignore links and (end)notes in speaker notes.
+    + Output speaker notes.
+    + Read speaker note templates conditionally.  If there are speaker
+      notes in the presentation, we read in the notesMasters templates
+      from the reference pptx file.
+    + Fix deletion track changes (#4303, Jesse Rosenthal).
+
+  * Markdown writer: properly escape @ to avoid capture as citation
+    (#4366).
+
+  * LaTeX writer:
+
+    + Put hypertarget inside figure environment (#4388).
+      This works around a problem with the endfloat package and
+      makes pandoc's output compatible with it.
+    + Fix image height with percentage (#4389).  This previously caused
+      the image to be resized to a percentage of textwidth, rather than
+      textheight.
+
+  * ConTeXt writer (Henri Menke):
+
+    + New section syntax and support `--section-divs` (#2609).
+      `\section[my-header]{My Header}` ->
+      `\section[title={My Header},reference={my-header}]`.
+      The ConTeXt writer now supports the `--section-divs` option to
+      write sections in the fenced style, with `\startsection` and
+      `\stopsection`.
+    + xtables: correct wrong usage of caption (Henri Menke).
+
+  * Docx writer:
+
+    + Fix image resizing with multiple images (#3930, Andrew Pritchard).
+    + Use new golden framework (Jesse Rosenthal).
+    + Make more deterministic to facilitate testing (Jesse Rosenthal).
+      - `getUniqueId` now calls to the state to get an incremented digit,
+        instead of calling to P.uniqueHash.
+      - we always start the PRNG in mkNumbering/mkAbstractNum with the same
+        seed (1848), so our randoms should be the same each time.
+    + Fix ids in comment writing (Jesse Rosenthal).  Comments from
+      `--track-changes=all` were producing corrupt docx, because the
+      writer was trying to get id from the `(ID,_,_)` field of
+      the attributes, and ignoring the "id" entry in the key-value pairs. We
+      now check both.
+
+  * Ms writer: Added papersize variable.
+
+  * TEI writer:
+
+    + Use `height` instead of `depth` for images (#4331).
+    + Ensure that id prefix is always used.
+    + Don't emit `role` attribute; that was a leftover from the
+      Docbook writer.
+    + Use 'xml:id', not 'id' attribute (#4371).
+
+  * AsciiDoc writer:
+
+    + Do not output implicit heading IDs (#4363, Alexander
+      Krotov).  Convert to `asciidoc-auto_identifiers` for old behaviour.
+
+  * RST writer:
+
+    + Remove `blockToRST'` moving its logic into `fixBlocks`
+      (Francesco Occhipinti).
+    + Insert comment between lists and quotes (#4248, Francesco Occchipinti).
+
+  * RST template: remove definition of 'math' role as raw.
+    This used to be needed prior to v 0.8 of docutils, but
+    now math support is built-in.
+
+  * Slides: Use divs to set incremental/non-incremental (#4381,
+    Jesse Rosenthal).  The old method (list inside blockquote) still
+    works, but we are encouraging the use of divs with class
+    `incremental` or `nonincremental`.
+
+  * Text.Pandoc.ImageSize:
+
+    + Make image size detection for PDFs more robust (#4322).
+    + Determine image size for PDFs (#4322).
+    + EMF Image size support (#4375, Andrew Pritchard).
+
+  * Text.Pandoc.Extensions:
+
+    + Add `Ext_styles` (Jesse Rosenthal, API change).  This will be used in
+      the docx reader (defaulting to off) to read pargraph and character
+      styles not understood by pandoc (as divs and spans, respectively).
+    + Made `Ext_raw_html` default for `commonmark` format.
+
+  * Text.Pandoc.Parsing:
+
+    + Export `manyUntil` (Alexander Krotov, API change).
+    + Export improved `sepBy1` (Alexander Krotov).
+    + Export list marker parsers: `upperRoman`, `lowerRoman`,
+      `decimal`, `lowerAlpha`, `upperAlpha` (Alexander Krotov, API change).
+
+  * Tests/Lua: fix tests on windows (Albert Krewinkel).
+
+  * Lua: register script name in global variable (#4393).  The name of the Lua
+    script which is executed is made available in the global Lua variable
+    `PANDOC_SCRIPT_FILE`, both for Lua filters and custom writers.
+
+  * Tests: Abstract powerpoint tests out to OOXML tests (Jesse Rosenthal).
+    There is very little pptx-specific in these tests, so we abstract out
+    the basic testing function so it can be used for docx as well. This
+    should allow us to catch some errors in the docx writer that slipped
+    by the roundtrip testing.
+
+  * Lua filters: store constructors in registry (Albert Krewinkel).  Lua
+    functions used to construct AST element values are stored in the Lua
+    registry for quicker access. Getting a value from the registry is much
+    faster than getting a global value (partly to idiosyncrasies of hslua);
+    this change results in a considerable performance boost.
+
+  * Documentation:
+
+    + `doc/org.md` Add draft of Org-mode documentation (Albert Krewinkel).
+    + `doc/lua-filters.md`: document global vars set for filters
+      (Albert Krewinkel).
+    + INSTALL.md: mention Stack version. (#4343, Adam Brandizzi).
+    + MANUAL: add documentation on custom styles (Jesse Rosenthal).
+    + MANUAL.txt: Document incremental and nonincremental divs (Jesse
+      Rosenthal).  Blockquoted lists are still described, but fenced divs are
+      presented in preference.
+    + MANUAL.txt: document header and footer variables (newmana).
+    + MANUAL.txt: self-contained implies standalone (#4304, Daniel Lublin).
+    + CONTRIBUTING.md: label was renamed. (#4310, Alexander Brandizzi).
+
+  * Require tagsoup 0.14.3 (#4282), fixing HTML tokenization bug.
+
+  * Use latest texmath.
+
+  * Use latest pandoc-citeproc.
+
+  * Allow exceptions 0.9.
+
+  * Require aeson-pretty 0.8.5 (#4394).
+
+  * Bump blaze-markup, blaze-html lower bounds to 0.8, 0.9 (#4334).
+
+  * Update tagsoup to 0.14.6 (Alexander Krotov, #4282).
+
+  * Removed ghc-prof-options.  As of cabal 1.24, sensible defaults are used.
+
+  * Update default.nix to current nixpkgs-unstable for hslua-0.9.5 (#4348,
+    jarlg).
+
+## pandoc 2.1.1 (2018-01-18)
+
+  * Markdown reader:
+
+    + Don't coalesce adjacent raw LaTeX blocks if they are separated by a
+      blank line.  See lierdakil/pandoc-crossref#160.
+    + Improved `inlinesInBalancedBrackets` (#4272, jgm/pandoc-citeproc#315).
+      The change both improves performance and fixes a regression whereby
+      normal citations inside inline notes and figure captions were not
+      parsed correctly.
+
+  * RST reader:
+
+    + Better handling for headers with an anchor (#4240).  Instead of creating a
+      Div containing the header, we put the id directly on the header.
+      This way header promotion will work properly.
+    + Add aligned environment when needed in math (#4254).  `rst2latex.py`
+      uses an `align*` environment for math in `.. math::` blocks, so this
+      math may contain line breaks.  If it does, we put the math in an
+      `aligned` environment to simulate `rst2latex.py`'s behavior.
+
+  * HTML reader:
+
+    + Fix col width parsing for percentages < 10% (#4262, n3fariox).
+
+  * LaTeX reader:
+
+    + Advance source position at end of stream.
+    + Pass through macro defs in `rawLaTeXBlock` even if the `latex_macros`
+      extension is set (#4246).  This reverts to earlier behavior and is
+      probably safer on the whole, since some macros only modify things in
+      included packages, which pandoc's macro expansion can't modify.
+    + Fixed pos calculation in tokenizing escaped space.
+    + Allow macro definitions inside macros (#4253).  Previously we went into
+      an infinite loop with
+      ```
+      \newcommand{\noop}[1]{#1}
+      \noop{\newcommand{\foo}[1]{#1}}
+      \foo{hi}
+      ```
+    + Fix inconsistent column widths (#4238).  This fixes a bug whereby column
+      widths for the body were different from widths for the header in some
+      tables.
+
+  * Docx reader (Jesse Rosenthal):
+
+    + Parse hyperlinks in `instrText` tags (#3389, #4266).  This was a form of
+      hyperlink found in older versions of word. The changes introduced for
+      this, though, create a framework for parsing further fields in MS Word
+      (see the spec, ECMA-376-1:2016, §17.16.5, for more on these fields).
+      We introduce a new module, `Text.Pandoc.Readers.Docx.Fields` which
+      contains a simple parsec parser. At the moment, only simple hyperlink
+      fields are accepted, but that can be extended in the future.
+
+  * Muse reader (Alexander Krotov):
+
+    + Parse `~~` as non-breaking space in Text::Amuse mode.
+    + Refactor list parsing.
+
+  * Powerpoint writer (Jesse Rosenthal):
+
+    + Change reference to `notesSlide` to `endNotesSlide`.
+    + Move image sizing into `picProps`.
+    + Improve table placement.
+    + Make our own `_rels/.rels` file.
+    + Import reference-doc images properly.
+    + Move `Presentation.hs` out of `PandocMonad`.
+    + Refactor into separate modules.  T.P.W.Powerpoint.Presentation
+      defines the Presentation datatype and goes Pandoc->Presentation;
+      T.P.W.Pandoc.Output goes Presentation->Archive.
+      Text.Pandoc.Writers.Powerpoint a thin wrapper around the two modules.
+    + Avoid overlapping blocks in column output.
+    + Position images correctly in two-column layout.
+    + Make content shape retrieval environment-aware.
+    + Improve image handling.  We now determine image and caption placement
+      by getting the dimensions of the content box in a given layout.
+      This allows for images to be correctly sized and positioned in a
+      different template.  Note that images without captions and headers are
+      no longer full-screened. We can't do this dependably in different
+      layouts, because we don't know where the header is (it could be to
+      the side of the content, for example).
+    + Read presentation size from reference file.  Our presentation size is
+      now dependent on the reference/template file we use.
+    + Handle (sub)headers above slidelevel correctly.  Above the slidelevel,
+      subheaders will be printed in bold and given a bit of extra space
+      before them. Note that at the moment, no distinction is made between
+      levels of headers above the slide header, though that can be changed.
+    + Check for required files.  Since we now import from reference/dist
+      file by glob, we need to make sure that we're getting the files we
+      need to make a non-corrupt Powerpoint. This performs that check.
+    + Improve templating using `--reference-doc`.  Templating should work
+      much more reliably now.
+    + Include Notes slide in TOC.
+    + Set notes slide header to slide-level.
+    + Add table of contents.  This is triggered by the `--toc` flag. Note
+      that in a long slide deck this risks overrunning the text box. The user
+      can address this by setting `--toc-depth=1`.
+    + Set notes slide number correctly.
+    + Clean up adding metadata slide.  We want to count the slide numbers
+      correctly if it's in there.
+    + Add anchor links.  For anchor-type links (`[foo](#bar)`) we produce
+      an anchor link. In powerpoint these are links to slides, so we keep
+      track of a map relating anchors to the slides they occur on.
+    + Make the slide number available to the blocks.  For anchors,
+      block-processing functions need to know what slide number
+      they're in. We make the `envCurSlideId` available to blocks.
+    + Move `curSlideId` to environment.
+    + Allow setting `toc-title` in metadata.
+    + Link notes to endnotes slide.
+
+  * Markdown writer:
+
+    + Fix cell width calculation (#4265).  Previously we could get
+      ever-lengthening cell widths when a table was run repeatedly through
+      `pandoc -f markdown -t markdown`.
+
+  * LaTeX writer:
+
+    + Escape `&` in lstinline (Robert Schütz).
+
+  * ConTeXt writer:
+
+    + Use xtables instead of Tables (#4223, Henri Menke).
+      Default to xtables for context output.  Natural Tables are used
+      if the new `ntb` extension is set.
+
+  * HTML writer:
+
+     + Fixed footnote backlinks with `--id-prefix` (#4235).
+
+  * `Text.Pandoc.Extensions`:  Added `Ext_ntb` constructor (API change,
+    Henri Menke).
+
+  * `Text.Pandoc.ImageSize`: add derived `Eq` instance to `Dimension`
+    (Jesse Rosenthal, API change).
+
+  * Lua filters (Albert Krewinkel):
+
+    + Make `PANDOC_READER_OPTIONS` available.
+      The options which were used to read the document are made available to
+      Lua filters via the `PANDOC_READER_OPTIONS` global.
+    + Add lua module `pandoc.utils.run_json_filter`, which runs a JSON filter
+      on a Pandoc document.
+    + Refactor filter-handling code into `Text.Pandoc.Filter.JSON`,
+      `Text.Pandoc.Filter.Lua`, and `Text.Pandoc.Filter.Path`.
+    + Improve error messages.  Provide more context about the task
+      which caused an error.
+
+  * data/pandoc.lua (Albert Krewinkel):
+
+    + Accept singleton inline as a list.  Every constructor which accepts a
+      list of inlines now also accepts a single inline element for
+      convenience.
+    + Accept single block as singleton list. Every constructor which accepts
+      a list of blocks now also accepts a single block element for
+      convenience.  Furthermore, strings are accepted as shorthand for
+      `{pandoc.Str "text"}` in constructors.
+    + Add attr, listAttributes accessors.  Elements with
+      attributes got an additional `attr` accessor. Attributes were
+      accessible only via the `identifier`, `classes`, and `attributes`,
+      which was in conflict with the documentation, which indirectly states
+      that such elements have the an `attr` property.
+    + Drop `_VERSION`.  Having a `_VERSION` became superfluous, as this
+      module is closely tied to the pandoc version, which is available via
+      `PANDOC_VERSION`.
+    + Fix access to Attr components.  Accessing an Attr value (e.g.,
+      ` Attr().classes`) was broken; the more common case of accessing it via
+      an Inline or Block element was unaffected by this.
+
+  * Move `metaValueToInlines` to from Docx writer to
+    `Text.Pandoc.Writers.Shared`, so it can be used by other writers
+    (Jesse Rosenthal).
+
+  * MANUAL.txt:
+
+    + Clarify otherlangs in LaTeX (#4072).
+    + Clarify `latex_macros` extension.
+    + Recommend use of `raw_attribute` extension in header includes (#4253).
+
+  * Allow latest QuickCheck, tasty, criterion.
+
+  * Remove custom prelude and ghc 7.8 support.
+
+  * Reduce compiler noise (exact paths for compiled modules).
+
+## pandoc 2.1 (2018-01-07)
+
+  * Allow filters and lua filters to be interspersed (#4196).  Previously
+    we ran all lua filters before JSON filters.  Now we run filters in
+    the order they are presented on the command line, whether lua or JSON.
+    There are two incompatible API changes: The type of `applyFilters`
+    has changed, and `applyLuaFilters` has been removed.  `Filter` is
+    also now exported.
+
+  * Use latest skylighting and omit the `missingIncludes` check, fixing
+    a major performance regression in earlier releases of the 2.x series
+    (#4226).  Behavior change: If you use a custom syntax definition that
+    refers to a syntax you haven't loaded, pandoc will now complain when
+    it is highlighting the text, rather than doing a check at the start.
+    This change dramatically speeds up invocations of pandoc on short
+    inputs.
+
+  * Text.Pandoc.Class: make `FileTree` opaque (don't export
+    `FileTree` constructor).  This forces users to interact with it using
+    `insertInFileTree` and `getFileInfo`, which normalize file names.
+
+  * Markdown reader:
+
+    + Rewrite `inlinesInBalancedBrackets`.  The rewrite is much more
+      direct, avoiding `parseFromString`.  And it performs significantly
+      better; unfortunately, parsing time still increases exponentially
+      (see #1735).
+    + Avoid parsing raw tex unless `\` + letter seen.  This seems to
+      help with the performance problem, #4216.
+
+  * LaTeX reader: Simplified a check for raw tex command.
+
+  * Muse reader (Alexander Krotov):
+
+    + Enable round trip test (#4107).
+    + Automatically translate `#cover` into `#cover-image`.
+      Amusewiki uses #cover directive to specify cover image.
+
+  * Docx reader (Jesse Rosenthal):
+
+    + Allow for insertion/deletion of paragraphs (#3927).
+      If the paragraph has a deleted or inserted paragraph break (depending
+      on the track-changes setting) we hold onto it until the next
+      paragraph. This takes care of accept and reject. For this we introduce
+      a new state which holds the ils from the previous para if necessary.
+      For `--track-changes=all`, we add an empty span with class
+      `paragraph-insertion`/`paragraph-deletion` at the end of the paragraph
+      prior to the break to be inserted or deleted.
+    + Remove unused anchors (#3679).  Docx produces a lot of anchors with
+      nothing pointing to them---we now remove these to produce cleaner
+      output. Note that this has to occur at the end of the process
+      because it has to follow link/anchor rewriting.
+    + Read multiple children of `w:sdtContents`.
+    + Combine adjacent anchors.  There isn't any reason to have numerous
+      anchors in the same place, since we can't maintain docx's
+      non-nesting overlapping. So we reduce to a single anchor.
+    + Improved tests.
+
+  * Muse writer (Alexander Krotov): don't escape URIs from AST
+
+  * Docx writer:
+
+    + Removed redundant subtitle in title (Sebastian Talmon).
+    + `firstRow` table definition compatibility for Word 2016 (Sebastian
+      Talmon).  Word 2016 seems to use a default value of "1" for table
+      headers, if there is no firstRow definition (although a default
+      value of 0 is documented), so all tables get the first Row formatted
+      as header.  Setting the parameter to 0 if the table has no header
+      row fixes this for Word 2016
+    + Fix custom styles with spaces in the name (#3290).
+
+  * Powerpoint writer (Jesse Rosenthal):
+
+    + Ignore Notes div for parity with other slide outputs.
+    + Set default slidelevel correctly.  We had previously defaulted to
+      slideLevel 2. Now we use the correct behavior of defaulting to the
+      highest level header followed by content. We change an expected test
+      result to match this behavior.
+    + Split blocks correctly for linked images.
+    + Combine adjacent runs.
+    + Make inline code inherit code size.  Previously (a) the code size
+      wasn't set when we force size, and (b) the properties was set from
+      the default, instead of inheriting.
+    + Simplify `replaceNamedChildren` function.
+    + Allow linked images.  The following markdown:
+      `[![Image Title](image.jpg)](http://www.example.com)`
+      will now produce a linked image in the resulting PowerPoint file.
+    + Fix error with empty table cell.  We require an empty `<a:p>` tag,
+      even if the cell contains no paragraphs---otherwise PowerPoint
+      complains of corruption.
+    + Implement two-column slides.  This uses the columns/column div
+      format described in the pandoc manual. At the moment, only two
+      columns (half the screen each) are allowed. Custom widths are not
+      supported.
+    + Added more tests.
+
+  * OpenDocument/ODT writers: improved rendering of formulas (#4170, oltolm).
+
+  * Lua filters (Albert Krewinkel):
+
+    + `data/pandoc.lua`: drop 'pandoc-api-version' from Pandoc objects
+    + The current pandoc-types version is made available to Lua programs in
+      the global `PANDOC_API_VERSION`. It contains the version as a list of
+      numbers.
+    + The pandoc version available as a global `PANDOC_VERSION` (a list
+      of numbers).
+    + `data/pandoc.lua`: make `Attr` an `AstElement`.
+    + `data/pandoc.lua`: make all types subtypes of `AstElement`.
+      `Pandoc`, `Meta`, and `Citation` were just plain functions and did
+      not set a metatable on the returned value, which made it difficult
+      to amend objects of these types with new behavior. They are now
+      subtypes of AstElement, meaning that all their objects can gain
+      new features when a method is added to the behavior object
+      (e.g., `pandoc.Pandoc.behavior`).
+    + `data/pandoc.lua`: split type and behavior tables.  Clearly distinguish
+      between a type and the behavioral properties of an instance of that
+      type. The behavior of a type (and all its subtypes) can now be
+      amended by adding methods to that types `behavior` object, without
+      exposing the type objects internals.  E.g.:
+      ```lua
+      pandoc.Inline.behavior.frob = function () print'42' end
+      local str = pandoc.Str'hello'
+      str.frob() -- outputs '42'
+      ```
+    + `data/pandoc.lua`: fix Element inheritance.  Extending all elements
+      of a given type (e.g., all inline elements) was difficult, as the
+      table used to lookup unknown methods would be reset every time a
+      new element of that type was created, preventing recursive property
+      lookup. This is was changed in that all methods and attributes of
+      supertypes are now available to their subtypes.
+    + `data/pandoc.lua`: fix attribute names of Citation (#4222).  The
+      fields were named like the Haskell fields, not like the documented,
+      shorter version.  The names are changed to match the documentation
+      and Citations are given a shared metatable to enable simple
+      extensibility.
+    + `data/pandoc.lua`: drop function `pandoc.global_filter`.
+    + Bump `hslua` version to 0.9.5.  This version fixes a bug that made it
+      difficult to handle failures while getting lists or a Map from Lua.
+      A bug in pandoc, which made it necessary to always pass a tag when
+      using MetaList or MetaBlock, is fixed as a result. Using the pandoc
+      module's constructor functions for these values is now optional
+      (if still recommended).
+    + Stop exporting `pushPandocModule` (API change).  The introduction
+      of `runPandocLua` renders direct use of this function obsolete.
+    + Update generation of module docs for lua filters.
+    + `Lua.Module.Utils`: make stringify work on `MetaValues` (John
+      MacFarlane).  I'm sure this was intended in the first place,
+      but currently only `Meta` is supported.
+
+  * Improve benchmarks.
+
+    + Set the default extensions properly.
+    + Improve benchmark argument parsing.  You can now say
+      `make bench BENCHARGS="markdown latex reader"` and both the
+      markdown and latex readers will be benchmarked.
+
+  * MANUAL.txt simplify and add more structure (Mauro Bieg).
+
+  * Generate README.md from template and MANUAL.txt.
+    `make README.md` will generate the README.md after changes
+    to MANUAL.txt have been made.
+
+  * Update copyright notices to include 2018 (Albert Krewinkel).
+
+## pandoc 2.0.6 (2017-12-28)
+
+  * Added `jats` as an input format.
+
+    + Add Text.Pandoc.Readers.JATS, exporting `readJATS` (API
+      change) (Hamish Mackenzie).
+    + Improved citation handling in JATS reader.  JATS citations
+      are now converted to pandoc citations, and JATS ref-lists
+      are converted into a `references` field in metadata, suitable
+      for use with pandoc-citeproc. Thus a JATS article with embedded
+      bibliographic information can be processed with pandoc and
+      pandoc-citeproc to produce a formatted bibliography.
+
+  * Allow `--list-extensions` to take an optional FORMAT argument.
+    This lists the extensions set by default for the selected FORMAT.
+    The extensions are now alphabetized, and the `+` or `-`
+    indicating the default setting comes before, rather than after,
+    the extension.
+
+  * Markdown reader:
+
+    + Preserve original whitespace between blocks.
+    + Recognize `\placeformula` as context.
+    + Be pickier about table captions.  A caption starts with a `:` which
+      can't be followed by punctuation.  Otherwise we can falsely interpret
+      the start of a fenced div, or even a table header line like
+      `:--:|:--:`, as a caption.
+    + Always use four space rule for example lists.  It would be awkward
+      to indent example list contents to the first non-space character after
+      the label, since example list labels are often long.  Thanks to
+      Bernhard Fisseni for the suggestion.
+    + Improve raw tex parsing.  Note that the Markdown reader is also
+      affected by the `latex_macros` extension changes described below
+      under the LaTeX reader.
+
+  * LaTeX reader:
+
+    + `latex_macros` extension changes (#4179).  Don't pass through macro
+      definitions themselves when `latex_macros` is set.  The macros
+      have already been applied.  If `latex_macros` is enabled, then
+      `rawLaTeXBlock` in Text.Pandoc.Readers.LaTeX will succeed in parsing
+      a macro definition, and will update pandoc's internal macro map
+      accordingly, but the empty string will be returned.
+    + Export `tokenize`, `untokenize` (API change).
+    + Use `applyMacros` in `rawLaTeXBlock`, `rawLaTeXInline`.
+    + Refactored `inlineCommand`.
+    + Fix bug in tokenizer.  Material following `^^` was
+      dropped if it wasn't a character escape.  This only affected
+      invalid LaTeX, so we didn't see it in the wild, but it appeared
+      in a QuickCheck test failure.
+    + Fix regression in LateX tokenization (#4159).  This mainly affects the
+      Markdown reader when parsing raw LaTeX with escaped spaces.
+    + Add tests of LaTeX tokenizer.
+    + Support `\foreignlanguage` from babel.
+    + Be more tolerant of `&` character (#4208).  This allows us to parse
+      unknown tabular environments as raw LaTeX.
+
+  * Muse reader (Alexander Krotov):
+
+    + Parse anchors immediately after headings as IDs.
+    + Require that note references does not start with 0.
+    + Parse empty comments correctly.
+
+  * Org reader (Albert Krewinkel):
+
+    + Fix asterisks-related parsing error (#4180).
+    + Support minlevel option for includes (#4154).  The level of headers
+      in included files can be shifted to a higher level by specifying a
+      minimum header level via the `:minlevel` parameter. E.g.
+      `#+include: "tour.org" :minlevel 1` will shift the headers in
+      tour.org such that the topmost headers become level 1 headers.
+    + Break-up org reader test file into multiple modules.
+
+  * OPML reader:
+
+    + Enable raw HTML and other extensions by default for notes
+      (#4164).  This fixes a regression in 2.0.  Note that extensions can
+      now be individually disabled, e.g.  `-f opml-smart-raw_html`.
+
+  * RST reader:
+
+    + Allow empty list items (#4193).
+    + More accurate parsing of references (#4156).  Previously we erroneously
+      included the enclosing backticks in a reference ID (#4156).  This
+      change also disables interpretation of syntax inside references, as
+      in docutils.  So, there is no emphasis in `` `my *link*`_ ``.
+
+  * Docx reader:
+
+    + Continue lists after interruption (#4025, Jesse Rosenthal).
+      Docx expects that lists will continue where they left off after an
+      interruption and introduces a new id if a list is starting again. So
+      we keep track of the state of lists and use them to define a "start"
+      attribute, if necessary.
+    + Add tests for structured document tags unwrapping (Jesse Rosenthal).
+    + Preprocess Document body to unwrap `w:sdt` elements (Jesse Rosenthal,
+      #4190).
+
+  * Plain writer:
+
+    + Don't linkify table of contents.
+
+  * RST writer:
+
+    + Fix anchors for headers (#4188).  We were missing an `_`.
+
+  * PowerPoint writer (Jesse Rosenthal):
+
+    + Treat lists inside BlockQuotes as lists.  We don't yet produce
+      incremental lists in PowerPoint, but we should at least treat lists
+      inside BlockQuotes as lists, for compatibility with other slide formats.
+    + Add ability to force size.  This replaces the more specific
+      `blockQuote runProp`, which only affected the size of blockquotes. We
+      can use this for notes, etc.
+    + Implement notes.  This currently prints all notes on a final slide.
+      Note that at the moment, there is a danger of text overflowing the
+      note slide, since there is no logic for adding further slides.
+    + Implement basic definition list functionality to PowerPoint writer.
+    + Don't look for default template file for Powerpoint (#4181).
+    + Add pptx to isTextFormat list.  This is used to check standalone
+      and not writing to the terminal.
+    + Obey slide level option (Jesse Rosenthal).
+    + Introduce tests.
+
+  * Docx writer:
+
+    + Ensure that `distArchive` is the one that comes with pandoc
+      (#4182).  Previously a `reference.docx` in `~/.pandoc` (or the user data
+      dir) would be used instead, and this could cause problems because a
+      user-modified docx sometimes lacks vital sections that we count
+      on the `distArchive` to supply.
+
+  * Org writer:
+
+    + Do not wrap "-" to avoid accidental bullet lists (Alexander Krotov).
+    + Don't allow fn refs to wrap to beginning of line (#4171, with help from
+      Alexander Krotov).  Otherwise they can be interpreted as footnote
+      definitions.
+
+  * Muse writer (Alexander Krotov):
+
+    + Don't wrap note references to the next line (#4172).
+
+  * HTML writer:
+
+    + Use br elements in line blocks instead of relying on CSS
+      (#4162).  HTML-based templates have had the custom CSS for
+      `div.line-block` removed.  Those maintaining custom templates will want
+      to remove this too.  We still enclose line blocks in a div with class
+      `line-block`.
+
+  * LaTeX writer:
+
+    + Use `\renewcommand` for `\textlatin` with babel (#4161).
+      This avoids a clash with a deprecated `\textlatin` command defined
+      in Babel.
+    + Allow fragile=singleslide attribute in beamer slides (#4169).
+    + Use `\endhead` after `\toprule` in headerless tables (#4207).
+
+  * FB2 writer:
+
+    + Add cover image specified by `cover-image` meta (Alexander Krotov,
+      #4195).
+
+  * JATS writer (Hamish Mackenzie):
+
+    + Support writing `<fig>` and `<table-wrap>` elements
+      with `<title>` and `<caption>` inside them by using Divs with class set
+      to one of `fig`, `table-wrap` or `caption` (Hamish Mackenzie).  The
+      title is included as a Heading so the constraint on where Heading can
+      occur is also relaxed.
+    + Leave out empty alt attributes on links.
+    + Deduplicate image mime type code.
+    + Make `<p>` optional in `<td>` and `<th>` (#4178).
+    + Self closing tags for empty xref (#4187).
+    + Improve support for code language.
+
+  * Custom writer:
+
+    + Use init file to setup Lua interpreter (Albert Krewinkel).
+      The same init file (`data/init`) that is used to setup the Lua
+      interpreter for Lua filters is also used to setup the interpreter of
+      custom writers.lua.
+    + Define instances for newtype wrapper (Albert Krewinkel).  The custom
+      writer used its own `ToLuaStack` instance definitions, which made
+      it difficult to share code with Lua filters, as this could result
+      in conflicting instances.  A `Stringify` wrapper is introduced to
+      avoid this problem.
+    + Added tests for custom writer.
+    + Fixed definition lists and tables in `data/sample.lua`.
+
+  * Fixed regression: when target is PDF, writer extensions were being
+    ignored.  So, for example, `pandoc -t latex-smart -o file.pdf`
+    did not work properly.
+
+  * Lua modules (Albert Krewinkel):
+
+    + Add `pandoc.utils` module, to hold utility functions.
+    + Create a Haskell module Text.Pandoc.Lua.Module.Pandoc to
+      define the `pandoc` lua module.
+    + Make a Haskell module for each Lua module. Move definitions for the
+      `pandoc.mediabag` modules to a separate Haskell module.
+    + Move `sha1` from the main `pandoc` module to `pandoc.utils`.
+    + Add function `pandoc.utils.hierarchicalize` (convert list of
+      Pandoc blocks into (hierarchical) list of Elements).
+    + Add function `pandoc.utils.normalize_date` (parses a date and
+      converts it (if possible) to "YYYY-MM-DD" format).
+    + Add function `pandoc.utils.to_roman_numeral` (allows conversion
+      of numbers below 4000 into roman numerals).
+    + Add function `pandoc.utils.stringify` (converts any AST element
+      to a string with formatting removed).
+    + `data/init.lua`: load `pandoc.utils` by default
+    + Turn pipe, read into full Haskell functions.  The `pipe` and `read`
+      utility functions are converted from hybrid lua/haskell functions
+      into full Haskell functions. This avoids the need for intermediate
+      `_pipe`/`_read` helper functions, which have dropped.
+    + pandoc.lua: re-add missing MetaMap function.  This was a bug
+      introduced in version 2.0.4.
+
+  * Text.Pandoc.Class: Add `insertInFileTree` [API change].  This gives
+    a pure way to insert an ersatz file into a `FileTree`.  In addition, we
+    normalize paths both on insertion and on lookup.
+
+  * Text.Pandoc.Shared: export `blocksToInlines'` (API change, Maura Bieg).
+
+  * Text.Pandoc.MIME: Add opus to MIME type table as audio/ogg (#4198).
+
+  * Text.Pandoc.Extensions:   Alphabetical order constructors for
+    `Extension`.  This makes them appear in order in `--list-extensions`.
+
+  * Allow lenient decoding of latex error logs, which are not always
+    properly UTF8-encoded (#4200).
+
+  * Update latex template to work with recent versions of beamer.
+    The old template produced numbered sections with some recent
+    versions of beamer.  Thanks to Thomas Hodgson.
+
+  * Updated reference.docx (#4175).  Instead of just "Hello, world", the
+    document now contains exemplars of most of the styles that have an
+    effect on pandoc documents.  This makes it easier to see the effect
+    of style changes.
+
+  * Removed `default.theme` data file (#4096).  It is no longer needed now
+    that we have `--print-highlight-style`.
+
+  * Added `stack.lts9.yaml` for building with lts 9 and ghc 8.0.2.
+    We still need this for the alpine static linux build, since
+    we don't have ghc 8.2.2 for that yet.
+
+  * Removed `stack.pkg.yaml`.  We only really need `stack.yaml`; we
+    can put flag settings for pandoc-citeproc there.
+
+  * Makefile: Add 'trypandoc' and 'pandoc-templates' targets to
+    make releases easier.
+
+  * MANUAL.txt:
+
+    + Add note on what formats have `+smart` by default.
+    + Use native syntax for custom-style (#4174, Mauro Bieg).
+    + Introduce dedicated Extensions section, since some extensions
+      affect formats other than markdown (Mauro Bieg, #4204).
+    + Clarify default html output for `--section-divs` (Richard Edwards).
+
+  * filters.md: say that Text.Pandoc.JSON comes form pandoc-types.
+    Closes jgm/pandoc-website#16.
+
+  * epub.md: Delete removed `-S` option from command (#4151, Georger Araújo).
+
+## pandoc 2.0.5 (2017-12-12)
+
+  * Fix a bug in 2.0.4, whereby pandoc could not read the theme files
+    generated with `--print-highlight-style` (#4133).  Improve JSON
+    serialization of styles.
+
+  * Fix CSS issues involving line numbers (#4128).
+    Highlighted code blocks are now enclosed in a div with class `sourceCode`.
+    Highlighting CSS no longer sets a generic color for pre and code; we only
+    set these for class `sourceCode`.
+
+  * `--pdf-engine-opt`: fix bug where option order was reversed (#4137).
+
+  * Add PowerPoint (pptx) writer (Jesse Rosenthal).
+    It works following the standard Pandoc conventions for making other
+    sorts of slides. Caveats:
+
+    + Syntax highlighting is not yet implemented. (This is difficult
+      because there are no character classes in Powerpoint.)
+    + Footnotes and Definition lists are not yet implemented. (Notes will
+      usually take the form of a final slide.
+    + Image placement and auto-resizing has a few glitches.
+    + Reference powerpoint files don't work dependably from the command
+      line. This will be implemented, but at the moment users are advised
+      to change themes from within Powerpoint.
+
+  * Create shared Text.Pandoc.Writers.OOXML module (Jesse Rosenthal).
+    This is for functions used by both Powerpoint and Docx writers.
+
+  * Add default pptx data for Powerpoint writer (Jesse Rosenthal).
+
+  * Add `empty_paragraphs` extension.
+
+    + Deprecate `--strip-empty-paragraphs` option.  Instead we now
+      use an `empty_paragraphs` extension that can be enabled on
+      the reader or writer.  By default, disabled.
+    + Add `Ext_empty_paragraphs` constructor to `Extension`.
+    + Revert "Docx reader: don't strip out empty paragraphs."
+      This reverts commit d6c58eb836f033a48955796de4d9ffb3b30e297b.
+    + Implement `empty_paragraphs` extension in docx reader and writer,
+      opendocument writer, html reader and writer.
+    + Add tests for `empty_paragraphs` extension.
+
+  * Markdown reader:
+
+    + Don't parse native div as table caption (#4119).
+    + Improved computation of column widths in pipe tables.
+      Pipe tables with lines longer than the text width (as set
+      by `--columns`) are now scaled to text width, with the relative
+      widths of columns determined by the ratios between the
+      header lines.  Previously we computed column widths using
+      the ratio of header line lengths to column width, so that
+      tables with narrow header lines were extremely thin, which
+      was very rarely the desired result.
+
+  * LaTeX reader: fix `\` before newline (#4134).  This should be a space,
+    as long as it's not followed by a blank line. This has been fixed at the
+    tokenizer level.
+
+  * Muse reader (Alexander Krotov):
+
+    + Add test for `#disable-tables` directive in Emacs mode.
+    + Don't allow emphasis to be preceded by letter.
+    + Add underline support in Emacs Muse mode..
+    + Support multiline directives in Amusewiki mode
+
+  * Man writer: omit internal links (#4136).  That is, just print the link
+    text without the URL.
+
+  * Markdown reader: accept processing instructions as raw HTML (#4125).
+
+  * Lua filters (Albert Krewinkel):
+
+    + Use script to initialize the interpreter.  The file `init.lua` is
+      used to initialize the Lua interpreter which is used in Lua filters.
+      This gives users the option to require libraries which they want to
+      use in all of their filters, and to extend default modules.
+    + Fix package loading for Lua 5.1.  The list of package searchers is
+      named `package.loaders` in Lua 5.1 and LuaJIT, and `package.searchers`
+      in Lua 5.2 and later.
+    + Refactor lua module handling.  The integration with Lua's package/module
+      system is improved: A pandoc-specific package searcher is prepended to
+      the searchers in `package.searchers`. The modules `pandoc` and
+      `pandoc.mediabag` can now be loaded via `require`.
+    + Bump lower bound of hslua.  The release hslua 0.9.3 contains a new
+      function which makes using Haskell functions as package loaders much
+      easier.
+
+  * reveal.js template:  add title-slide identifier to title slide (#4120).
+    This allows it to be styled more easily.
+
+  * LaTeX template: Added support for `pagestyle` variable (#4135,
+    Thomas Hodgson)
+
+  * Add `-threaded` to ghc-options for executable (#4130, fixes a build
+    error on linux).
+
+
+## pandoc 2.0.4 (2017-12-03)
+
+  * Add `--print-highlight-style` option.  This generates a JSON version
+    of a highlighting style, which can be saved as a `.theme` file, modified,
+    and used with `--highlight-style` (#4106, #4096).
+
+  * Add `--strip-empty-paragraphs` option.  This works for any input format.
+    It is primarily intended for use with docx and odt documents where
+    empty paragraphs have been used for inter-paragraph spaces.
+
+  * Support `--webtex` for `gfm` output.
+
+  * Recognize `.muse` file extension.
+
+  * Support beamer `\alert` in LaTeX reader. Closes #4091.
+
+  * Docx reader: don't strip out empty paragraphs (#2252).
+    Users who have a conversion pipeline from docx may want to consider adding
+    `--strip-empty-paragraphs` to the command line.
+
+  * Org reader (Albert Krewinkel): Allow empty list items (#4090).
+
+  * Muse reader (Alexander Krotov):
+
+    + Parse markup in definition list terms.
+    + Allow definition to end with EOF.
+    + Make code blocks round trip.
+    + Drop common space prefix from list items.
+    + Add partial round trip test.
+    + Don't interpret XML entities.
+    + Remove `nested`.
+    + Parse `~~` as non-breaking space in Emacs mode.
+    + Correctly remove indentation from notes.  Exactly one space is
+      required and considered to be part of the marker.
+    + Allow list items to be empty.
+    + Add ordered list test.
+    + Add more multiline definition tests.
+    + Don't allow blockquotes within lists.
+    + Fix reading of multiline definitions.
+    + Add inline `<literal>` support.
+    + Concatenate inlines of the same type
+
+  * Docx writer: allow empty paragraphs (#2252).
+
+  * CommonMark/gfm writer:
+
+    + Use raw html for native divs/spans (#4113).  This allows a pandoc
+      markdown native div or span to be rendered in gfm using raw html tags.
+    + Implement `raw_html` and `raw_tex` extensions.  Note that `raw_html`
+      is enabled by default for `gfm`, while `raw_tex` is disabled by default.
+
+  * Muse writer (Alexander Krotov):
+
+    + Test that inline math conversion result is normalized.
+      Without normalization this test produced
+      `<em>a</em><em>b</em><em>c</em>`.
+    + Improve inline list normalization and move to writer.
+    + Escape hash symbol.
+    + Escape `----` to avoid accidental horizontal rules.
+    + Escape only `</code>` inside code tag.
+    + Additional `<verbatim>` is not needed as `<code>` is verbatim already.
+
+  * LaTeX writer:
+
+    + Allow specifying just width or height for image size.
+      Previously both needed to be specified (unless the image was
+      being resized to be smaller than its original size).
+      If height but not width is specified, we now set width to
+      textwidth. If width but not height is specified, we now set
+      height to textheight.  Since we have `keepaspectratio`, this
+      yields the desired result.
+    + Escape `~` and `_` in code with `--listings` (#4111).
+
+  * HTML writer: export `tagWithAttributes`.  This is a helper allowing
+    other writers to create single HTML tags.
+
+  * Let papersizes `a0`, `a1`, `a2`, ... be case-insensitive by
+    converting the case as needed in LaTeX and ConTeXt writers.
+
+  * Change `fixDisplayMath` from `Text.Pandoc.Writers.Shared`
+    so that it no longer produces empty `Para`'s as an artifact.
+
+  * `Text.Pandoc.Shared.blocksToInlines`:  rewrote using builder.
+    This gives us automatic normalization, so we don't get
+    for example two consecutive Spaces.
+
+  * Include default CSS for 'underline' class in HTML-based templates.
+
+  * revealjs template:  add `tex2jax` configuration for the
+    math plugin.  With the next release of reveal.js, this will
+    fix the problem of `$`s outside of math contexts being
+    interpreted as math delimiters (#4027).
+
+  * `pandoc.lua` module for use in lua filters (Albert Krewinkel):
+
+    + Add basic lua List module (#4099, #4081).  The List module is
+      automatically loaded, but not assigned to a global variable. It can be
+      included in filters by calling `List = require 'List'`.  Lists of blocks,
+      lists of inlines, and lists of classes are now given `List` as a metatable,
+      making working with them more convenient.  E.g., it is now possible to
+      concatenate lists of inlines using Lua's concatenation operator `..`
+      (requires at least one of the operants to have `List` as a metatable):
+
+          function Emph (emph)
+            local s = {pandoc.Space(), pandoc.Str 'emphasized'}
+            return pandoc.Span(emph.content .. s)
+          end
+
+      The `List` metatable is assigned to the tables which get passed to
+      the constructors `MetaBlocks`, `MetaInline`, and `MetaList`. This
+      enables the use of the resulting objects as lists.
+    + `Lua/StackInstances`: push Pandoc and Meta via constructor.
+      Pandoc and Meta elements are now pushed by calling the respective
+      constructor functions of the pandoc Lua module. This makes serialization
+      consistent with the way blocks and inlines are pushed to lua and allows
+      to use List methods with the `blocks` value.
+    + Add documentation for pandoc.List in `lua-filters.md`.
+
+  * Use latest tagsoup.  This fixes a bug in parsing HTML tags with
+    `&` (but not a valid entity) following them (#4094, #4088).
+
+  * Use skylighting 0.4.4.1, fixing the color of unmarked code text
+    when `numberLines` is used (#4103).
+
+  * Make `normalizeDate` more forgiving (Mauro Bieg, #4101), not
+    requiring a leading 0 on single-digit days.
+
+  * Fix `--help` output for `--highlight-style` to include `FILE` (Mauro
+    Bieg, #4095).
+
+  * Clearer deprecation warning for `--latexmathml, --asciimathml, -m`.
+    Previously we only mentioned `--latexmathml`, even if `-m` was
+    used.
+
+  * Changelog: fix description of lua filters in 2.0 release
+    (Albert Krewinkel).  Lua filters were initially run *after* conventional
+    (JSON) filters.  However, this was changed later to make it easier to deal
+    with files in the mediabag. The changelog is updated to describe that
+    feature of the 2.0 release correctly.
+
+  * Change Generic JSON instances to TemplateHaskell (Jasper Van der Jeugt,
+    #4085).  This reduces compile time and memory usage significantly.
+
+  * `lua-filters.md`: Added tikz filter example.
+
+  * Create alternative zip file for macOS binaries.
+
+  * Create alternative zip file for Windows binaries.
+
+  * Update INSTALL.md since we now provide zips for binaries.
+
+  * Relax `http-types` dependency (Justus Sagemüller, #4084).
+
+  * Add `epub.md`, `getting-started.md` to docs.  These used to live in
+    the website repo.
+
+  * Add `packages` target to Makefile.
+
+  * Bump bounds for binary, http-types, tasty-hunit
+
+## pandoc 2.0.3 (2017-11-20)
+
+  * Lua filters: preload text module (Albert Krewinkel, #4077).
+    The `text` module is preloaded in lua. The module contains some UTF-8
+    aware string functions, implemented in Haskell.  The module is loaded on
+    request only, e.g.:
+
+        text = require 'text'
+        function Str (s)
+          s.text = text.upper(s.text)
+          return s
+        end
+
+  * Allow table-like access to attributes in lua filters (Albert Krewinkel,
+    #4071).  Attribute lists are represented as associative lists in Lua. Pure
+    associative lists are awkward to work with. A metatable is attached to
+    attribute lists, allowing to access and use the associative list as if
+    the attributes were stored in as normal key-value pair in table.
+    Note that this changes the way `pairs` works on attribute lists. Instead
+    of producing integer keys and two-element tables, the resulting iterator
+    function now returns the key and value of those pairs.  Use `ipairs` to
+    get the old behavior.  Warning: the new iteration mechanism only works if
+    pandoc has been compiled with Lua 5.2 or later (current default: 5.3).
+
+  * Text.Pandoc.Parsing.uri:  allow `&` and `=` as word characters (#4068).
+    This fixes a bug where pandoc would stop parsing a URI with an
+    empty attribute:  for example, `&a=&b=` wolud stop at `a`.
+    (The uri parser tries to guess which punctuation characters
+    are part of the URI and which might be punctuation after it.)
+
+  * Introduce `HasSyntaxExtensions` typeclass (Alexander Krotov, #4074).
+
+    + Added new `HasSyntaxExtensions` typeclass for `ReaderOptions` and
+      `WriterOptions`.
+    + Reimplemented `isEnabled` function from `Options.hs` to accept both
+      `ReaderOptions` and `WriterOptions`.
+    + Replaced `enabled` from `CommonMark.hs` with new `isEnabled`.
+
+  * Add `amuse` extension (Alexander Krotov) to enable Amuse wiki
+    behavior for `muse`.  New `Ext_amuse` constructor for
+    `Extension`. Note: this is switched on by default; for
+    Emacs behavior, use `muse-amuse`.
+
+  * Muse reader (Alexander Krotov):
+
+    + Count only one space as part of list item marker.
+    + Produce SoftBreaks on newlines. Now wrapping can be preserved
+      with `--wrap=preserve`.
+    + Add Text::Amuse footnote extensions.  Footnote end is indicated by
+      indentation, so footnotes can be placed anywhere in the text,
+      not just at the end of it.
+    + Accept Emacs Muse definition lists when `-amuse`.
+      Emacs Muse does not require indentation.
+
+  * HTML reader:
+
+    + Ensure we don't produce level 0 headers (#4076), even for chapter
+      sections in epubs.  This causes problems because writers aren't set
+      up to expect these.
+    + Allow spaces after `\(` and before `\)` with `tex_math_single_backslash`.
+      Previously `\( \frac{1}{a} < \frac{1}{b} \)` was not parsed as math in
+      `markdown` or `html` `+tex_math_single_backslash`.
+
+  * MANUAL: clarify that math extensions work with HTML.
+    Clarify that `tex_math_dollars` and `tex_math_single_backslash`
+    will work with HTML as well as Markdown.
+
+  * Creole reader: Fix performance issue for longer lists (Sascha Wilde,
+    #4067).
+
+  * RST reader: better support for 'container' directive (#4066).
+    Create a div, incorporate name attribute and classes.
+
+  * LaTeX reader:
+
+    + Support column specs like `*{2}{r}` (#4056).  This is equivalent to
+      `rr`.  We now expand it like a macro.
+    + Allow optional args for parbox (#4056).
+    + Allow optional arguments on `\footnote` (#4062).
+
+  * EPUB writer: Fixed path for cover image (#4069).  It was previously
+    `media/media/imagename`, and should have been `media/imagename`.
+
+  * Markdown writer: fix bug with doubled footnotes in grid tables
+    (#4061).
+
+  * LaTeX template:  include natbib/biblatex after polyglossia (#4073).
+    Otherwise we seem to get an error; biblatex wants polyglossia
+    language to be defined.
+
+  * Added examples to lua filters documentation.
+
+
+## pandoc 2.0.2 (2017-11-12)
+
+  * Deprecated ancient HTML math methods: `--latexmathml`, `--gladtex`,
+    `--mimetex`, `--jsmath`.
+
+  * Fixed URIs in `data/jats.csl`.  They were being rendered twice,
+    leading to invalid XML in default JATS output with pandoc-citeproc.
+
+  * `lua-filters.md`: use real-world man page filter as example.
+
+  * Add lua filter functions `walk_inline` and `walk_block`
+    in the pandoc module, to apply filters inside particular
+    inline and block elements.
+
+  * Refactored some code from `Text.Pandoc.Lua.PandocModule`
+    into new internal module `Text.Pandoc.Lua.Filter`.
+
+  * Markdown reader:
+
+    + Allow fenced code blocks to be indented 1-3 spaces (#4011).
+      This brings our handling of them into alignment with CommonMark's.
+    + Fix YAML metadata with "chomp" (`|-`).  Previously if a
+      YAML block under `|-` contained a blank line, pandoc would
+      not parse it as metadata.
+
+  * Removed `etc.` from abbreviations file.  Often `etc.` ends a
+    sentence, and we want the period to be treated as a
+    sentence-ending period.
+
+  * Fix regression with `--metadata` (#4054).  Values specified with
+    `--metadata` should replace a metadata value set in the document
+    itself, rather than creating a list including a new value.
+
+  * EPUB writer:
+
+    + Fix EPUB OCF structure.  #3720 had been improperly implemented.
+    + Fix modified paths for raw HTML tags (src, poster, etc.)
+      (#4050, #4055). This had not been updated for the new EPUB
+      container layout, with a separate text/ subdirectory.
+    + Fix image paths with empty `--epub-subdirectory`.
+
+  * Miscellaneous code cleanup (Alexander Krotov).
+
+  * Use pandoc-types 1.17.3, which adds `Walkable` instances
+    for `[Block] Block` and `[Inline] Inline`.
+
+  * Remove obsolete `stack.full.yaml` (#4052).
+
+  * Change to using pandoc-citeproc 0.12.1 in binary packages.
+
+  * Consolidate math output method documentation (#4049, Mauro Bieg).
+
+  * `MANUAL.txt`: fix header level of "Extension: emoji" (Albert Krewinkel).
+
+  * Use lua filter to generate man page from `MANUAL.txt`, replacing old
+    Haskell filters.  This is easier and faster.
+
+  * Improved `INSTALL.md`.
+
+  * Update commands to extract deb archive on Linux (#4043, Salim B).
+
+
+## pandoc 2.0.1.1 (2017-11-04)
+
+  * Improved fix to #3989 (parsing of HTML tags containing
+    `>` in an attribute or comment). The previous fix (in 2.0.1) only
+    worked in certain cases.
+
+  * FB2 writer (Alexander Krotov):
+
+    + Add `unrecognised` genre to `<title-info>`
+      (Alexander Krotov).  XML schema requires at least one genre.
+    + Remove `<annotation>` from `<body>`.
+
+  * CommonMark writer: fix strikethrough for `gfm` (#4038).
+
+  * Use texmath 0.10, which adds support for a wider range of
+    symbols and fixes default column alignments in MathML
+    and OMML.
+
+  * Highlighting fixes, using skylighting 0.4.3.2:
+
+    + Fix invalid CSS.
+    + Support `lineAnchors` (or `line-anchors`) in HTML code blocks.
+    + Ensure that code lines don't get duplicate identifiers (#4031).
+      The line identifiers are built using the code block's identifier
+      as a prefix. If the code block has null identifier, we use
+      `cb1`, `cb2`, etc.
+
+  * Added a few abbreviations to `data/abbreviations`,
+    and sorted the list (#3984, Wandmalfarbe).
+
+  * Improved support for columns in HTML writer (#4028).
+
+    + Remove `width` attribute from the `div`.
+    + Remove space between `<div class="column">` elements,
+      since this prevents columns whose widths sum to 100%
+      (the space takes up space).
+    + Move as much as possible of the CSS to the template.
+    + Ensure that all the HTML-based templates (including epub)
+      contain the CSS for columns.
+    + Columns default to 50% width unless they are given a width
+      attribute.  So if you want two equal-width columns, you
+      can use a div with class `column` and no `width` attribute.
+
+  * SelfContained: use `base64` for css links with media attribute (#4026).
+    This fixes `--self-contained` with S5.
+
+  * Improve `pandoc-template-mode.el` (Vaclav Haisman).
+
+  * INSTALL.md: MacOS instructions needed xar -f (adam234).
+
+  * MANUAL.txt:
+
+    + Clarify that --setext-headers doesn't affect gfm output (#4035).
+    + Clarify what is needed to open and close a div in `fenced_divs`
+      (#4039, Tristano Ajmone).
+    + Removed reference to `default.beamer` in docs (#4024).
+      Also added mention of other templates affecting PDF output
+      with different settings.
+
+
+## pandoc 2.0.1 (2017-10-31)
+
+  * Fixed regression in parsing of HTML comments in markdown and other
+    non-HTML formats (`Text.Pandoc.Readers.HTML.htmlTag`) (#4019).
+    The parser stopped at the first `>` character, even if it wasn't
+    the end of the comment.
+
+  * Creole reader (Sascha Wilde):
+
+    + Fix some minor typos and formatting.
+    + Add additional test on nowiki-block after para.
+    + Fix lists with trailing white space.
+
+  * LaTeX reader: handle `%` comment right after command.
+    For example, `\emph%`.
+
+  * Markdown reader:  make sure fenced div closers work in lists.
+    Previously the following failed:
+
+        ::: {.class}
+        1. one
+        2. two
+        :::
+
+    and you needed a blank line before the closing `:::`.
+
+  * Make `fenced_divs` affect the Markdown writer.  If `fenced_divs` is
+    enabled, Divs will be rendered as fenced divs.
+
+  * LaTeX/Beamer writer: support "blocks" inside columns and other Divs
+    (#4016).
+
+  * HTML Writer: consistently use dashed class-names (Mauro Bieg, #3556).
+    Note: this change may require some changes in CSS rules.
+    `footnoteRef` has become `footnote-ref`, `titleslide` has
+    become `title-slide`, and `footnoteBack` has become `footnote-back`.
+
+  * JATS writer: Properly pass through author metadata (#4020).
+
+  * FB2 writer (Alexander Krotov):
+
+    + Write blocks outside of `<p>` in definitions.
+    + Make bullet lists consistent with ordered lists, repeating
+      the marker for the outer list rather than indenting sublists,
+      since indentation does not work in readers.
+    + Add new style FB2 tests.
+
+  * `Text.Pandoc.ImageSize`: Add `Millimeter` constructor to `Dimension`
+    (#4012) [API change]. Now sizes given in 'mm' are no longer converted
+    to 'cm'.
+
+  * Revise documentation of small caps syntax (Andrew Dunning, #4013).
+
+  * Fix broken reference links in manual (Andrew Dunning, #4014)
+
+  * Fixed example of slide columns structure in changelog (#4015).
+    Also documented this feature in MANUAL.txt.
+
+
+## pandoc 2.0.0.1 (2017-10-30)
+
+  * EPUB writer:
+
+    + Fixed filepaths for nonstandard epub-subdirectory values.
+    + Ensure that epub2 is recognized as a non-text format,
+      so that a template is used.
+    + Don't include "prefix" attribute for ibooks for epub2.
+      It doesn't validate.
+    + Fix stylesheet paths; previously we had an incorrect
+      stylesheet path for the cover page and nav page.
+
+  * LaTeX reader:
+
+    + Insert space when needed in macro expansion (#4007).
+      Sometimes we need to insert a space after a control sequence
+      to prevent it merging with a following letter.
+    + Allow unbraced arguments for macros (#4007).
+    + Allow body of macro definition to be unbraced (#4007).
+
+  * Linux package build: ensure that pandoc-citeproc is statically linked.
+
+  * trypandoc: add native, ms.
+
+
+## pandoc 2.0 (2017-10-29)
+
+### New features
+
+  * New output format `ms` (groff ms). Complete support, including
+    tables, math, syntax highlighting, and PDF bookmarks. The writer uses
+    texmath's new eqn writer to convert math to eqn format, so a ms file
+    produced with this writer should be processed with `groff -ms -e` if
+    it contains math.
+
+  * New output format `jats` (Journal Article Tag Suite).  This is an XML
+    format used in archiving and publishing articles.  Note that a
+    URI-encoded CSL stylesheet (`data/jats.csl`) is added automatically
+    unless a stylesheet is specified using `--css`.
+
+  * New output format `gfm` (GitHub-flavored CommonMark) (#3841).
+    This uses bindings to GitHub's fork of cmark, so it should parse
+    gfm exactly as GitHub does (excepting certain postprocessing
+    steps, involving notifications, emojis, etc.).  `markdown_github`
+    has been deprecated in favor of `gfm`.
+
+  * New output format `muse` (Emacs Muse) (Alexander Krotov, #3489).
+
+  * New input format `gfm` (GitHub-flavored CommonMark) (#3841).
+    This uses bindings to GitHub's fork of cmark.  `markdown_github`
+    has been deprecated in favor of `gfm`.
+
+  * New input format `muse` (Emacs Muse) reader (Alexander Krotov, #3620).
+
+  * New input format `tikiwiki` (TikiWiki markup) (rlpowell, #3800).
+
+  * New input format `vimwiki` (Vimwiki markup) (Yuchen Pei, #3705).
+    Note that there is a new data file, `data/vimwiki.css`, which can
+    be used to display the HTML produced by this reader and
+    pandoc's HTML writer in the style of vimwiki's own HTML
+    export.
+
+  * New input format `creole` (Creole 1.0) (#3994, Sascha Wilde).
+
+  * New syntax for Divs, with `fenced_divs` extension enabled by
+    default (#168).  This gives an attractive, plain-text way to create
+    containers for block-level content.
+
+  * Added new syntax for including raw content in any output format,
+    enabled by the `raw_attribute` extension (which is on by default
+    for `markdown` and `multimarkdown`).  The syntax is the same as
+    for fenced code blocks or code inlines, only with `{=FORMAT}` for
+    attributes, where `FORMAT` is the name of the output format
+    (e.g., `ms`, `html`).
+
+  * Implement multicolumn support for slide formats (#1710).
+    The structure expected is:
+
+        :::::::::::::: {.columns}
+        ::: {.column width="40%"}
+        contents...
+        :::
+        ::: {.column width="60%"}
+        contents...
+        :::
+        ::::::::::::::
+
+    Support has been added for beamer and all HTML slide formats.
+
+  * Allows line comments in templates, beginning with `$--` (#3806).
+    (Requires doctemplates 0.2.1.)
+
+  * Add `--eol=crlf|lf|native` flag and writer option to control line endings
+    (Stefan Dresselhaus, #3663, #2097).
+
+  * Add `--log` option to save log messages in JSON format to a file (#3392).
+
+  * Add `--request-header` option, to set request headers when pandoc
+    makes HTTP requests to fetch external resources. For example:
+    `--request-header User-Agent:blah`.
+
+  * Added lua filters (Albert Krewinkel, #3514).  The new `--lua-filter`
+    option works like `--filter` but takes pathnames of special lua filters
+    and uses the lua interpreter baked into pandoc, so that no external
+    interpreter is needed.  Note that lua filters are all applied after
+    regular filters, regardless of their position on the command line.
+    For documentation of lua filters, see `doc/lua-filters.md`.
+
+  * Set `PANDOC_READER_OPTIONS` in environment where filters are run.
+    This contains a JSON representation of `ReaderOptions`, so filters
+    can access it.
+
+  * Support creation of pdf via groff `ms` and pdfroff.
+    `pandoc -t ms -o output.pdf input.txt`.
+
+  * Support for PDF generation via HTML and `weasyprint` or `prince`
+    (Mauro Bieg, #3909).  `pandoc -t html5 -o output.pdf --pdf-engine=prince`.
+
+  * Added `--epub-subdirectory` option (#3720).  This specifies the
+    subdirectory in the OCF container that holds the EPUB specific content.
+    We now put all EPUB related content in an `EPUB/` subdirectory by default
+    (later this will be configurable).
+
+    ```
+      mimetype
+      META-INF/
+        com.apple.ibooks.display-options.xml
+        container.xml
+      EPUB/ <<--configurable-->>
+        fonts/ <<--static-->>
+        font.otf
+      media/ <<--static-->>
+        cover.jpg
+        fig1.jpg
+      styles/ <<--static-->>
+        stylesheet.css
+      content.opf
+      toc.ncx
+      text/ <<--static-->>
+        ch001.xhtml
+    ```
+
+  * Added `--resource-path=SEARCHPATH` command line option (#852).
+    SEARCHPATH is separated by the usual character, depending on OS
+    (: on unix, ; on windows).  Default resource path is just working
+    directory.  However, the working directory must be explicitly
+    specified if the `--resource-path` option is used.
+
+  * Added --abbreviations=FILE option for custom abbreviations file
+    (#256).  Dfault abbreviations file (`data/abbreviations`) contains
+    a list of strings that will be recognized by pandoc's
+    Markdown parser as abbreviations.  (A nonbreaking space will
+    be inserted after the period, preventing a sentence space in
+    formats like LaTeX.) Users can override the default by putting a file
+    abbreviations in their user data directory (`~/.pandoc` on *nix).
+
+  * Allow a theme file as argument to `--highlight-style`.
+    Also include a sample, `default.theme`, in `data/`.
+
+  * Allow `--syntax-definition` option for dynamic loading of syntax
+    highlighting definitions (#3334).
+
+  * Lists in `markdown` by default now use the CommonMark variable
+    nesting rules (#3511). The indentation required for a block-level
+    item to be included in a list item is no longer fixed, but is
+    determined by the first line of the list item.  To be included in
+    the list item, a block must be indented to the level of the first
+    non-space content after the list marker. Exception: if are 5 or more
+    spaces after the list marker, then the content is interpreted as an
+    indented code block, and continuation paragraphs must be indented
+    two spaces beyond the end of the list marker.  See the CommonMark
+    spec for more details and examples.
+
+    Documents that adhere to the four-space rule should, in most cases,
+    be parsed the same way by the new rules.  Here are some examples
+    of texts that will be parsed differently:
+
+        - a
+          - b
+
+    will be parsed as a list item with a sublist; under the four-space
+    rule, it would be a list with two items.
+
+        - a
+
+              code
+
+    Here we have an indented code block under the list item, even though it
+    is only indented six spaces from the margin, because it is four spaces
+    past the point where a continuation paragraph could begin.  With the
+    four-space rule, this would be a regular paragraph rather than a code
+    block.
+
+        - a
+
+                code
+
+    Here the code block will start with two spaces, whereas under
+    the four-space rule, it would start with `code`.  With the four-space
+    rule, indented code under a list item always must be indented eight
+    spaces from the margin, while the new rules require only that it
+    be indented four spaces from the beginning of the first non-space
+    text after the list marker (here, `a`).
+
+    This change was motivated by a slew of bug reports from people
+    who expected lists to work differently (#3125, #2367, #2575, #2210,
+     #1990, #1137, #744, #172, #137, #128) and by the growing prevalance
+    of CommonMark (now used by GitHub, for example).  Those who
+    prefer the old behavior can use `-f markdown+four_space_rule`.
+
+  * Added `four_space_rule` extension.  This triggers the old pandoc
+    parsing rule for content nested under list items (the "four space
+    rule").
+
+  * Added `spaced_reference_links` extension (#2602).  It allows whitespace
+    between the two parts of a reference link:  e.g.
+
+        [a] [b]
+
+        [b]: url
+
+    This was previously enabled by default; now it is forbidden by default.
+
+  * Add `space_in_atx_header` extension (#3512).  This is enabled by default
+    in pandoc and GitHub markdown but not the other flavors.
+    This requirse a space between the opening #'s and the header
+    text in ATX headers (as CommonMark does but many other implementations
+    do not).  This is desirable to avoid falsely capturing things ilke
+
+        #hashtag
+
+    or
+
+        #5
+
+  * Add `sourcefile` and `outputfile` template variables (Roland Hieber,
+    #3431).
+
+  * Allow ibooks-specific metadata in epubs (#2693).  You can now have
+    the following fields in your YAML metadata, and it will be treated
+    appropriately in the generated EPUB:
+
+    ```
+      ibooks:
+        version: 1.3.4
+        specified-fonts: false
+        ipad-orientation-lock: portrait-only
+        iphone-orientation-lock: landscape-only
+        binding: true
+        scroll-axis: vertical
+    ```
+
+
+### Behavior changes
+
+  * Reader functions no longer presuppose that CRs have been
+    stripped from the input. (They strip CRs themselves, before
+    parsing, to simplify the parsers.)
+
+  * Added support for translations (localization) (#3559).
+    Currently this only affects the LaTeX reader, for things
+    like `\figurename`.  Translation data files for 46 languages
+    can be found in `data/translations`.
+
+  * Make `--ascii` work with DocBook output too.
+
+  * Rename `--latex-engine` to `--pdf-engine`,
+    and `--latex-engine-opt` to `--pdf-engine-opt`.
+
+  * Removed `--parse-raw` and `readerParseRaw`.  These were confusing.
+    Now we rely on the `+raw_tex` or `+raw_html` extension with latex or html
+    input.  Thus, instead of `--parse-raw -f latex` we use `-f latex+raw_tex`,
+    and instead of `--parse-raw -f html` we use `-f html+raw_html`.
+
+  * With `--filter` R filters are now recognized, even if they are
+    not executable (#3940, #3941, Andrie de Vries).
+
+  * Support SVG in PDF output, converting with `rsvg2pdf` (#1793).
+
+  * Make epub an alias for epub3, not epub2.
+
+  * Removed `--epub-stylesheet`; use `--css` instead (#3472, #847).
+    Multiple stylesheets may be used.  Stylesheets will be taken both from
+    `--css` and from the `stylesheet` metadata field (which can contain
+    either a file path or a list of them).
+
+  * `--mathml` and MathML in HTMLMathMethod no longer take an argument.
+    The argument was for a bridge JavaScript that used to be necessary
+    in 2004.  We have removed the script already.
+
+  * `--katex` improvements.  The latest version is used, and the
+    autoload script is loaded by default.
+
+  * Change MathJax CDN default since old one is shutting down (#3544).
+    Note:  The new URL requires a version number, which we'll have
+    to update manually in subsequent pandoc releases in order to
+    take advantage of mathjax improvements.
+
+  * `--self-contained`: don't incorporate elements with `data-external="1"`
+    (#2656).  You can leave an external link as it is by adding the attribute
+    data-external="1" to the element.  Pandoc will then not try to
+    incorporate its content when `--self-contained` is used.  This is
+    similar to a feature already supported by the EPUB writer.
+
+  * Allow `--extract-media` to work with non-binary input formats
+    (#1583, #2289).  If `--extract-media` is supplied with a non-binary
+    input format, pandoc will attempt to extract the contents of all
+    linked images, whether in local files, data: uris, or external uris.
+    They will be named based on the sha1 hash of the contents.
+
+  * Make `papersize: a4` work regardless of the case of `a4`.
+    It is converted to `a4` in LaTeX and `A4` in ConTeXt.
+
+  * Make `east_asian_line_breaks` affect all readers/writers (#3703).
+
+  * Underlined elements are now treated consistently by readers
+    (#2270, hftf); they are always put in a Span with class `underline`.
+    This allows the user to treat them differently from other emphasis,
+    using a filter.  Docx, Org, Textile, Txt2Tags, and HTML readers
+    have been changed.
+
+  * Improved behavior of `auto_identifiers` when there are explicit ids
+    (#1745).  Previously only autogenerated ids were added to the list
+    of header identifiers in state, so explicit ids weren't taken
+    into account when generating unique identifiers.  Duplicated
+    identifiers could result.  This simple fix ensures that explicitly given
+    identifiers are also taken into account.
+
+  * Use `table-of-contents` for contents of toc, make `toc` a boolean
+    (#2872).  Changed markdown, rtf, and HTML-based templates accordingly.
+    This allows you to set `toc: true` in the metadata; this
+    previously produced strange results in some output formats.
+    For backwards compatibility, `toc` is still set to the
+    toc contents.  But it is recommended that you update templates
+    to use `table-of-contents` for the toc contents and `toc`
+    for a boolean flag.
+
+  * Change behavior with binary format output to stdout.
+    Previously, for binary formats, output to stdout was disabled
+    unless we could detect that the output was being piped (and not
+    sent to the terminal).  Unfortunately, such detection is not
+    possible on Windows, leaving windows users no way to pipe binary
+    output.  So we have changed the behavior in the following way:
+
+    + Output to stdout is allowed when it can be determined that
+      the output is being piped (on non-Windows platforms).
+    + If the `-o` option is not used, binary output is never sent
+      to stdout by default; instead, an error is raised.
+    + If `-o -` is used, binary output is sent to stdout, regardless
+      of whether it is being piped. This works on Windows too.
+
+  * Better error behavior:  uses of `error` have been replaced by
+    raising of `PandocError`, which can be trapped and handled by the
+    calling program.
+
+  * Removed `hard_line_breaks` extension from `markdown_github` (#3594).
+    GitHub has two Markdown modes, one for long-form documents like READMEs
+    and one for short things like issue comments. In issue comments, a line
+    break is treated as a hard line break. In README, wikis, etc., it is
+    treated as a space as in regular Markdown.  Since pandoc is more likely to
+    be used to convert long-form documents from GitHub Markdown,
+    `-hard_line_breaks` is a better default.
+
+  * Include `backtick_code_blocks` extension in `mardkown_mmd` (#3637).
+
+  * Escape `MetaString` values (as added with `-M/--metadata` flag) (#3792).
+    Previously they would be transmitted to the template without any
+    escaping.  Note that `--M title='*foo*'` yields a different result from
+
+        ---
+        title: *foo*
+        ---
+
+    In the latter case, we have emphasis; in the former case, just
+    a string with literal asterisks (which will be escaped
+    in formats, like Markdown, that require it).
+
+  * Allow `em`, `cm`, `in` for image height/width in HTML, LaTeX (#3450).
+
+  * HTML writer: Insert `data-` in front of unsupported attributes.  Thus,
+    a span with attribute `foo` gets written to HTML5 with `data-foo`, so
+    it is valid HTML5.  HTML4 is not affected.  This will allow us to use
+    custom attributes in pandoc without producing invalid HTML. (With help
+    from Wandmalfarbe, #3817.)
+
+  * Plain writer:  improved super/subscript rendering.  We now
+    handle more non-digit characters for which there are
+    sub/superscripted unicode characters.  When unicode
+    sub/superscripted characters are not available, we use
+    `_(..)` or `^(..)` (#3518).
+
+  * Docbook, JATS, TEI writers: print INFO message when omitting interior
+    header (#3750).  This only applies to section headers inside list items,
+    e.g., which were otherwise silently omitted.
+
+  * Change to `--reference-links` in Markdown writer (#3701).  With
+    `--reference-location` of `section` or `block`, pandoc will now repeat
+    references that have been used in earlier sections.  The Markdown
+    reader has also been modified, so that *exactly* repeated references
+    do not generate a warning, only references with the same label but
+    different targets.  The idea is that, with references after every block,
+    one might want to repeat references sometimes.
+
+  * ODT/OpenDocument writer:
+
+    + Support `lang` attribute (#1667).
+    + Added support for `--toc` (#2836).  Thanks to @anayrat.
+
+  * Docx writer:
+
+    + `lang` meta, see #1667 (Mauro Bieg, #3515).
+    + Change `FigureWithCaption` to `CaptionedFigure` (iandol, #3658).
+    + Use `Table` rather than `Table Normal` for table style (#3275).
+      `Table Normal` is the default table style and can't be modified.
+    + Pass through comments (#2994).  We assume that comments are defined as
+      parsed by the docx reader:
+
+        I want <span class="comment-start" id="0" author="Jesse Rosenthal"
+        date="2016-05-09T16:13:00Z">I left a comment.</span>some text to
+        have a comment <span class="comment-end" id="0"></span>on it.
+
+      We assume also that the id attributes are unique and properly
+      matched between comment-start and comment-end.
+    + Bookmark improvements.  Bookmark start/end now surrounds content rather
+      than preceding it.  Bookmarks generated for Div with id
+      (jgm/pandoc-citeproc#205).
+    + Add `keywords` metadata to docx document properties (Ian).
+
+  * RST writer: support unknown interpreted text roles by
+    parsing them as `Span` with `role` attributes (#3407).  This
+    way they can be manipulated in the AST.
+
+  * HTML writer:
+
+    + Line block: Use class instead of style attribute (#1623).  We now
+      issue `<div class="line-block">` and include a default definition
+      for `line-block` in the default templates, instead of hard-coding a
+      `style` on the div.
+    + Add class `footnoteBack` to footnote back references (Timm Albers).
+      This allows for easier CSS styling.
+    + Render SmallCaps as span with smallcaps class (#1592), rather than
+      using a style attribute directly.  This gives the user more flexibility
+      in styling small caps in CSS.
+    + With reveal.js we use `data-src` instead of `src` for images for
+      lazy loading.
+    + Special-case `.stretch` class for images in reveal.js (#1291).
+      Now in reveal.js, an image with class `stretch` in a paragraph
+      by itself will stretch to fill the whole screen, with no
+      caption or figure environment.
+
+  * Added warnings for non-rendered blocks to writers.
+
+  * Writers now raise an error on template failure.
+
+  * When creating a PDF via LaTeX, warn if the font is missing some
+    characters (#3742).
+
+  * Remove initial check for PDF-creating program (#3819).
+    Instead, just try running it and raise the exception if it
+    isn't found at that point.  This improves things for users of Cygwin
+    on Windows, where the executable won't be found by `findExecutable`
+    unless `.exe` is added.  The same exception is raised as before, but
+    at a later point.
+
+  * Readers issue warning for duplicate header identifiers (#1745).
+    Autogenerated header identifiers are given suffixes so as not to clash
+    with previously used header identifiers. But they may still coincide with
+    an explicit identifier that is given for a header later in the document,
+    or with an identifier on a div, span, link, or image. We now issue
+    a warning in this case, so users can supply an explicit identifier.
+
+  * CommonMark reader now supports `emoji`, `hard_line_breaks`, `smart`,
+    and `raw_html` extensions.
+
+  * Markdown reader:
+
+    + Don't allow backslash + newline to affect block structure (#3730).
+      Note that as a result of this change, the following, which formerly
+      produced a header with two lines separated by a line break, will
+      now produce a header followed by a paragraph:
+
+        # Hi\
+        there
+
+      This may affect some existing documents that relied on
+      this undocumented and unintended behavior.  This change makes pandoc
+      more consistent with other Markdown implementations, and with itself
+      (since the two-space version of a line break doesn't work inside ATX
+      headers, and neither version works inside Setext headers).
+
+
+  * Org reader (Albert Krewinkel, unless noted):
+
+    + Support `table.el` tables (#3314).
+    + Support macros (#3401).
+    + Support the `#+INCLUDE:` file inclusion mechanism (#3510).
+      Recognized include types are `example`, `export`, `src`, and
+      normal org file inclusion.  Advanced features like line numbers
+      and level selection are not implemented yet.
+    + Interpret more meta value as inlines.  The values of the following
+      meta variables are now interpreted using org-markup instead of
+      treating them as pure strings: `keywords` (comma-separated list of
+      inlines), `subtitle` (inline values), `nocite` (inline values, can
+      be repeated).
+    + Support `\n` export option (#3940).  This turns all newlines in the
+      text into hard linebreaks.
+
+  * RST reader:
+
+    + Improved admonition support (#223).  We no longer add an
+      `admonition` class, we just use the class for the type of admonition,
+      `note` for example.  We put the word corresponding to the label in
+      a paragraph inside a `Div` at the beginning of the admonition with
+      class `admonition-title`.  This is about as close as we can get to
+      RST's own output.
+    + Initial support of `.. table` directive.  This allows adding captions
+      to tables.
+    + Support `.. line-block` directive.  This is deprecated but may still
+      be in older documents.
+    + Support scale and align attributes of images (#2662).
+    + Implemented implicit internal header links (#3475).
+    + Support RST-style citations (#853).  The citations appear at the end
+      of the document as a definition list in a special div with id
+      `citations`. Citations link to the definitions.
+    + Recurse into bodies of unknown directives (#3432).
+      In most cases it's better to preserve the content than
+      to emit it.  This isn't guaranteed to have good results;
+      it will fail spectacularly for unknown raw or verbatim directives.
+    + Handle chained link definitions (#262).  For example,
+
+          .. _hello:
+          .. _goodbye: example.com
+
+      Here both `hello` and `goodbye` should link to `example.com`.
+    + Support anchors (#262).  E.g.
+
+          `hello`
+
+          .. _hello:
+
+          paragraph
+
+      This is supported by putting "paragraph" in a `Div` with id `hello`.
+    + Support `:widths:` attribute for table directive.
+    + Implement csv-table directive (#3533).  Most attributes are supported,
+      including `:file:` and `:url:`.
+    + Support unknown interpreted text roles by parsing them as Span
+      with "role" attributes (#3407).  This way they can be manipulated in
+      the AST.
+
+  * HTML reader: parse a span with class `smallcaps` as `SmallCaps`.
+
+  * LaTeX reader:
+
+    + Implemented `\graphicspath` (#736).
+    + Properly handle column prefixes/suffixes.  For example, in
+      `\begin{tabular}{>{$}l<{$}>{$}l<{$} >{$}l<{$}}`
+      each cell will be interpreted as if it has a `$`
+      before its content and a `$` after (math mode).
+    + Handle komascript `\dedication` (#1845).  It now adds a
+      `dedication` field to metadata.  It is up to the user to supply
+      a template that uses this variable.
+    + Support all `\textXX` commands, where XX = `rm`, `tt`, `up`, `md`,
+      `sf`, `bf` (#3488).  Spans with a class are used when there is
+      nothing better.
+    + Expand `\newenvironment` macros (#987).
+    + Add support for LaTeX subfiles package (Marc Schreiber, #3530).
+    + Better support for subfigure package (#3577).
+      A figure with two subfigures turns into two pandoc
+      figures; the subcaptions are used and the main caption
+      ignored, unless there are no subcaptions.
+    + Add support for `\vdots` (Marc Schreiber, #3607).
+    + Add basic support for hyphenat package (Marc Schreiber, #3603).
+    + Add basic `\textcolor` support (Marc Schreiber).
+    + Add support for `tabularx` environment (Marc Schreiber, #3632).
+    + Better handling of comments inside math environments (#3113).
+      This solves a problem with commented out `\end{eqnarray}` inside
+      an eqnarray (among other things).
+    + Parse tikzpicture as raw verbatim environment if `raw_tex` extension
+      is selected (#3692).  Otherwise skip with a warning.  This is better
+      than trying to parse it as text!
+    + Add `\colorbox` support (Marc Schreiber).
+    + Set identifiers on Spans used for `\label`.
+    + Have `\setmainlanguage` set `lang` in metadata.
+    + Support etoolbox's `\ifstrequal`.
+    + Support `plainbreak`, `fancybreak` et al from the memoir class
+      (bucklereed, #3833).
+    + Support `\let`.  Also, fix regular macros so they're expanded at the
+      point of use, and NOT also the point of definition.  `\let` macros,
+      by contrast, are expanded at the point of definition.  Added an
+      `ExpansionPoint` field to `Macro` to track this difference.
+    + Support simple `\def` macros.  Note that we still don't support
+      macros with fancy parameter delimiters, like `\def\foo#1..#2{...}`.
+    + Support `\chaptername`, `\partname`, `\abstractname`, etc.  (#3559,
+      obsoletes #3560).
+    + Put content of `\ref`, `\label`, `\eqref` commands into `Span` with
+      attributes, so they can be handled in filters (Marc Schreiber, #3639)
+    + Add Support for `glossaries` and `acronym` package (Marc Schreiber,
+      #3589). Acronyms are not resolved by the reader, but acronym and
+      glossary information is put into attributes on Spans so that they
+      can be processed in filters.
+    + Use `Link` instead of `Span` for `\ref`.  This makes more sense
+      semantically and avoids unnecessary `Span [Link]` nestings when
+      references are resolved.
+    + Rudimentary support for `\hyperlink`.
+    + Support `\textquoteleft|right`, `\textquotedblleft|right` (#3849).
+    + Support `\lq`, `\rq`.
+    + Implement `\newtoggle`, `\iftoggle`, `\toggletrue|false` from etoolbox
+      (#3853).
+    + Support `\RN` and `\Rn`, from biblatex (bucklereed, #3854).
+    + Improved support for `\hyperlink`, `\hypertarget` (#2549).
+    + Support `\k` ogonek accent.
+    + Improve handling of accents.  Handle ogonek, and fall back correctly
+      with forms like `\"{}`.
+    + Better support for ogonek accents.
+    + Support for `\faCheck` and `\faClose` (Marc Schreiber, #3727).
+    + Support for `xspace` (Marc Schreiber, #3797).
+    + Support `\setmainlanguage` or `\setdefaultlanguage` (polyglossia)
+      and `\figurename`.
+    + Better handling of `\part` in LaTeX (#1905).  Now we parse chapters as
+      level 0 headers, and parts as level -1 headers.  After parsing, we
+      check for the lowest header level, and if it's less than 1 we bump
+      everything up so that 1 is the lowest header level.  So `\part` will
+      always produce a header; no command-line options are needed.
+    + Add block version of `\textcolor` (Marc Schreiber).
+    + `\textcolor` works as inline and block command (Marc Schreiber).
+    + `\textcolor` will be parse as span at the beginning of a paragraph
+      (Marc Schreiber).
+    + Read polyglossia/babel `\text(LANG){...}` (bucklereed)
+    + Improved handling of include files in LaTeX reader (#3971).
+      Previously `\include` wouldn't work if the included file
+      contained, e.g., a begin without a matching end.
+    + Support `\expandafter` (#3983).
+    + Handle `\DeclareRobustCommand` (#3983).  Currently it's just treated
+      as a synonym for `\newcommand`.
+    + Handle `\lettrine` (Mauro Bieg).
+
+  * Math improvements due to updates in texmath:
+
+    + Improved handling of accents and upper/lower delimiters.
+    + Support for output in GNU eqn format (used with *roff).
+    + Allow `\boldsymbol` + a token without braces, and similarly
+      with other styling commands.
+    + Improve parsing of `\mathop` to allow multi-character operator names.
+    + Add thin space after math operators when "faking it with
+      unicode."
+
+  * `walk` is now used instead of `bottomUp` in the `ToJSONFilter`
+    instance for `a -> [a]` (pandoc-types).  Note that behavior
+    will be slightly different, since `bottomUp`'s treatment of
+    a function `[a] -> [a]` is to apply it to each sublist of a
+    list, while walk applies it only to maximal sublists.
+    Usually the latter behavior is what is wanted, and the
+    former can be simulated when needed.  But there may be
+    existing filters that need to be rewritten in light of the
+    new behavior.  Performance should be improved.
+
+  * There are some changes to syntax highlighting due to revisions
+    in the `skylighting` library:
+
+    + Support for `powershell` has been added, and many syntax
+      definitions have been updated.
+    + Background colors have been added to the `kate` style.
+    + The way highlighted code blocks are formatted in HTML has
+      been changed (David Baynard), in ways that may require
+      changes in hard-coded CSS affecting highlighting.
+      (If you haven't included hard-coded highlighting CSS in
+      your template, you needn't change anything.)
+
+
+### API changes
+
+  * New module `Text.Pandoc.Class` (Jesse Rosenthal, John MacFarlane).
+    This contains definitions of the `PandocMonad` typeclass, the
+    `PandocIO` and `PandocPure` monads, and associated functions.
+
+  * Changed types of all writers and readers.
+
+    + We now use `Text` instead of `String` in the interface (#3731).
+      (We have not yet changed the internals of most readers to work
+      with `Text`, but making this change in the API now opens up a
+      path to doing that.)
+    + The result is now of form `m a` with constraint `PandocMonad m`.
+      Readers and writers can be combined to form monadic values which
+      can be run using either `runIO` or `runPure`.  If `runIO` is used,
+      then both readers and writers will be able to do IO when needed
+      (for include files, for example); if `runPure` is used,
+      then the functions are pure and will not touch IO.
+    + Where previously you used
+      `writeRST def (readMarkdown def "[foo](url)")`, now you
+      would use
+      `runPure $ readMarkdown def (pack "[foo](url)") >>= writeRST def`.
+
+  * New module `Text.Pandoc.Readers` (Albert Krewinkel).  This
+    contains reader helper functions formerly defined in the
+    top-level `Text.Pandoc` module.
+
+    + Changed `StringReader` -> `TextReader`.
+    + `getReader` now returns a pair of a reader and
+      `Extensions`, instead of building the extensions into the
+      reader (#3659).  The calling code must explicitly set
+      `readerExtensions` using the `Extensions` returned.  The
+      point of the change is to make it possible for the calling
+      code to determine what extensions are being used.
+
+  * New module `Text.Pandoc.Writers` (Albert Krewinkel).
+    This contains writer helper functions formerly defined in the
+    top-level `Text.Pandoc` module.
+
+    + Changed `StringWriter` -> `TextWriter`.
+    + `getWriter` now returns a pair of a reader and
+      `Extensions`, instead of building the extensions into the
+      reader (#3659).  The calling code must explicitly set
+      `readerExtensions` using the `Extensions` returned.  The
+      point of the change is to make it possible for the calling
+      code to determine what extensions are being used.
+
+  * New module `Text.Pandoc.Lua`, exporting `runLuaFilter` (Albert Krewinkel,
+    #3514).
+
+  * New module `Text.Pandoc.App`.  This abstracts out the functionality
+    of the command line program (`convertWithOpts`), so it can be reproduced
+    e.g. in a desktop or web application.  Instead of exiting, we throw errors
+    (#3548), which are caught (leading to exit) in pandoc.hs, but allow other
+    users of `Text.Pandoc.App` to recover.  `pandoc.hs` is now a 2-liner.
+    The module also exports some utility functions for parsing options
+    and running filters.
+
+  * New module `Text.Pandoc.Logging` (exported module) (#3392).
+    This now contains the `Verbosity` definition previously in
+    `Text.Pandoc.Options`, as well as a new `LogMessage` datatype that will
+    eventually be used instead of raw strings for warnings.  This will enable
+    us, among other things, to provide machine-readable warnings if desired.
+    Include ToJSON instance and showLogMessage.  This gives us the possibility
+    of both machine-readable and human-readable output for log messages.
+
+  * New module `Text.Pandoc.BCP47`, with `getLang`, `Lang(..)`, `parseBCP47`.
+
+  * New module `Text.Pandoc.Translations`, exporting `Term`,
+    `Translations`, `readTranslations`.
+
+  * New module `Text.Pandoc.Readers.LaTeX.Types', exporting `Macro`, `Tok`,
+    `TokType`, `Line`, `Column`.
+
+  * `Text.Pandoc.Error`: added many new constructors for `PandocError`.
+
+  * Expose some previously private modules (#3260).  These are often
+    helpful to people writing their own reader or writer modules:
+
+    + `Text.Pandoc.Writers.Shared`
+    + `Text.Pandoc.Parsing`
+    + `Text.Pandoc.Asciify`
+    + `Text.Pandoc.Emoji`
+    + `Text.Pandoc.ImageSize`
+    + `Text.Pandoc.Highlighting`
+`
+  * New module `Text.Pandoc.Extensions` (Albert Krewinkel):
+    Extension parsing and processing functions were defined in the top-level
+    `Text.Pandoc` module.  These functions are moved to the Extensions
+    submodule as to enable reuse in other submodules.
+
+  * Add `Ext_raw_attribute` constructor for `Extension`.
+
+  * Add `Ext_fenced_divs` constructor for `Extension'.
+
+  * Add `Ext_four_space_rule` constructor in `Extension`.
+
+  * Add `Ext_gfm_auto_identifiers` constructor for `Extension`.
+
+  * Add `Monoid` instance for `Extensions`.
+
+  * Add `Text.Pandoc.Writers.Ms`, exporting `writeMs`.
+
+  * Add `Text.Pandoc.Writers.JATS`, exporting `writeJATS`.
+
+  * Add `Text.Pandoc.Writers.Muse`, exporting `writeMuse`.
+
+  * Add `Text.Pandoc.Readers.Muse`, exporting `readMuse`.
+
+  * Add `Text.Pandoc.Readers.TikiWiki`, exporting `readTikiWiki`.
+
+  * Add `Text.Pandoc.Readers.Vimwiki`, exporting `readVimwiki`.
+
+  * Add `Text.Pandoc.Readers.Creole`, exporting `readCreole`.
+
+  * Export `setVerbosity` from `Text.Pandoc`.
+
+  * `Text.Pandoc.Pretty`: Add `Eq` instance for `Doc`.
+
+  * `Text.Pandoc.XML`: `toEntities`: changed type to `Text -> Text`.
+
+  * `Text.Pandoc.UTF8`:
+
+    + Export `fromText`, `fromTextLazy`, `toText`, `toTextLazy`.
+      Define `toString`, `toStringLazy` in terms of them.
+    + Add new functions parameterized on `Newline`: `writeFileWith`,
+      `putStrWith`, `putStrLnWith`, `hPutStrWith`, `hPutStrLnWith`.
+
+  * `Text.Pandoc.MediaBag`: removed `extractMediaBag`.
+
+  * `Text.Pandoc.Highlighting`:
+
+    + `highlighting` now returns an Either rather than Maybe.
+      This allows us to display error information returned by the skylighting
+      library.  Display a warning if the highlighting library throws an error.
+    + Add parameter for `SyntaxMap` to `highlight`.
+
+  * `Text.Pandoc.Writers.Math`:
+
+    + Export `defaultMathJaxURL`, `defaultKaTeXURL`.  This will ensure that
+      we only need to update these in one place.
+
+  * `Text.Pandoc.SelfContained`:
+
+    + Removed `WriterOptions` parameter from `makeSelfContained`.
+    + Put `makeSelfContained` in PandocMonad instead of IO.  This removes
+      the need to pass MediaBag around and improves exceptions.  It also
+      opens up the possibility of using makeSelfContained purely.
+    + Export `makeDataURI`.
+
+  * `Text.Pandoc.ImageSize`:
+
+    + Export `lengthToDim`, new function `scaleDimension`.
+    + Export `inEm` from ImageSize (#3450).
+    + Change `showFl` and `show` instance for `Dimension` so
+      extra decimal places are omitted.
+    + Added `Em` as a constructor of `Dimension`.
+    + Add `WriterOptions` parameter to `imageSize` signature (Mauro Bieg).
+
+  * `Text.Pandoc.Templates`:
+
+    + Change type of `renderTemplate'`.  Now it runs in `PandocMonad`
+      and raises a proper `PandocTemplateError` if there are problems, rather
+      than failing with uncatchable `error`.
+    + Change signature of `getDefaultTemplate`.  Now it runs in any instance
+      of `PandocMonad`, and returns a `String` rather than an `Either` value.
+      And it no longer takes a `datadir` parameter, since this can be
+      retrieved from `CommonState`.
+
+  * `Text.Pandoc.Options`:
+
+    + Added `writerEpubSubdirectory` to `WriterOptions` (#3720).
+      The EPUB writer now takes its EPUB subdirectory from this option.
+    + In `WriterOptions`, rename `writerLaTeXEngine` to `writerPdfEngine`
+      and `writerLaTeXArgs` to `writerPdfArgs` (Mauro Bieg, #3909).
+    + Add `writerSyntaxMap` to `WriterOptions`.
+    + Removed `writerEpubStylesheet` from `WriterOptions`.
+    + Remove `writerUserDataDir` from `WriterOptions`.  It is now carried
+      in `CommonState` in `PandocMonad` instances.  (And thus it can be used
+      by readers too.)
+    + Changed `writerEpubMetadata` to a `Maybe String`.
+    + Removed `readerApplyMacros` from `ReaderOptions`.  Now we just check
+      the `latex_macros` reader extension.
+    + FromJSON/ToJSON instances for `ReaderOptions`.
+    + In `HTMLMathMethod`, the `KaTeX` contsructor now takes only
+      one string (for the KaTeX base URL), rather than two.
+    + Removed `writerSourceURL` from `WriterOptions`.  We now use
+      `stSourceURL` in `CommonState`, which is set by `setInputFiles`.
+
+  * `Text.Pandoc.Shared`:
+
+    + `tabFilter` now takes a `Text`, not `String`.
+    + `openURL`: Changed type from an Either.  Now it will just raise
+      an exception to be trapped later.
+    + Remove `normalizeSpaces` (#1530).
+    + Remove `warn`.  (Use `report` from `Text.Pandoc.Class` instead.)
+    + Export a new function `crFilter`.
+    + Add `eastAsianLineBreakFilter` (previously in Markdown reader).
+    + Provide custom `isURI` that rejects unknown schemes.
+      (Albert Krewinkel, #2713).  We also export the set of known
+      `schemes`.  The new function replaces the function of the same name
+      from `Network.URI`, as the latter did not check whether a scheme is
+      well-known.  All official IANA schemes (as of 2017-05-22) are
+      included in the set of known schemes.  The four non-official schemes
+      `doi`, `isbn`, `javascript`, and `pmid` are kept.
+    + Remove `err`.
+    + Remove `readDataFile`, `readDefaultDataFile`, `getReferenceDocx`,
+      `getReferenceODT`. These now live in `Text.Pandoc.Class`,
+      where they are defined in terms of `PandocMonad`
+      primitives and have different signatures.
+    + Remove `openURL`.  Use `openURL` from `Text.Pandoc.Class` instead.
+    + Add `underlineSpan`.
+
+  * `Text.Pandoc.Readers.HTML`: export new `NamedTag` class.
+
+  * `Text.Pandoc.Readers.Markdown`: remove `readDocxWithWarnings`.
+     With the new API one can simply use `getLog` after running
+     the reader.
+
+  * `Text.Pandoc.Readers.LaTeX`: Changed types for `rawLaTeXInline`
+     and `rawLaTeXBlock`.  (Both now return a `String`, and they are
+     polymorphic in state.)
+
+
+### Bug fixes and under-the-hood improvements
+
+  * TEI writer: Added identifiers on `<div>` elements.
+
+  * DokuWiki reader: Better handling for code block in list item (#3824).
+
+  * Custom writer: Remove old preprocesesor conditionals (Albert Krewinkel).
+
+  * ZimWiki writer: Removed internal formatting from note and table cells,
+    because ZimWiki does not support it (Alex Ivkin, #3446).
+
+  * MediaWiki writer:
+
+    + Updated list of syntax highlighting languages (#3461).
+      Now `r` gets you `<source>` rather than `<code>` (among others).
+    + Add display attribute on `<math>` tags (#3452).  This allows display
+      math to be rendered properly.
+    + Remove newline before `</ref>` (#2652).
+    + Don't softbreak lines inside list items (#3531).
+
+  * Org writer:
+
+    + Reduce to two spaces after bullets (#3417, Albert Krewinkel).
+    + Add unit tests (Alexander Krotov).
+    + Stop using raw HTML to wrap divs (Albert Krewinkel, #3771).
+    + Do not strip `#` from Org anchor links (Alexander Krotov).
+
+  * CommonMark writer:
+
+    + Avoid excess blank lines at end of output.
+    + Prefer pipe tables to HTML tables even if it means losing relative
+      column width information (#3734).
+    + Support table, strikethrough extensions, when enabled (as with gfm).
+      Note that we bypass the commonmark writer from cmark and construct our
+      own pipe tables, with better results.
+    + Properly support `--wrap=none`.
+    + Use smallcaps class for `SmallCaps` (#1592).
+    + Omit "fig:" prefix in image titles.  This is used internally to
+      indicate internal figures.
+
+  * RST writer:
+
+    + Properly handle table captions.
+    + Don't wrap lines in in definition list terms.  Wrapping is not allowed.
+    + Implemented `+/-smart` and improved escaping with `+smart`.
+    + Add empty comments when needed to avoid including a blockquote
+      in the indented content of a preceding block (#3675).
+    + Improve grid table output, fix bug with empty rows (#3516).
+      Uses the new `gridTable` in Writers.Shared, which is here
+      improved to better handle 0-width cells.
+    + Remove space at beginning/end of RST code span (#3496).  Otherwise
+      we get invalid RST.  There seems to be no way to escape the space.
+    + Add header anchors when header has non-standard id (#3937).
+    + Correctly handle inline code containing backticks, using a `:literal:`
+      role (#3974).
+    + Don't backslash-escape word-internal punctuation (#3978).
+
+  * Markdown writer:
+
+    + Don't include variables in metadata blocks.  Previously variables set
+      on the command line were included in e.g. YAML metadata, contrary to
+      documentation and intentions.
+    + Improved escaping with `+smart`.
+    + Fixed grid tables embedded in grid tables (#2834).
+    + Use span with class 'smallcaps' for SmallCaps, instead of a style
+      attribute as before (#1592).
+    + Escape initial `%` in a paragraph if the `pandoc_title_blocks`
+      extension is enabled (#3454).  Otherwise in a document starting with
+      a literal `%` the first line is wrongly interpreted as a title.
+    + Fixed false ordered lists in YAML metadata (#3492, #1685).  Now we
+      properly escape things that would otherwise start ordered lists,
+      such as
+
+          ---
+          title: 1. inline
+          ...
+    + Better handling of tables with empty columns (#3337).  We now
+      calculate the number of columns based on the longest row (or the
+      length of aligns or widths).
+    + Escape unordered list markers at beginning of paragraph (#3497), to
+      avoid false interpretation as a list.
+    + Escape `|` appropriately.
+    + Ensure space before list at top level (#3487).
+    + Avoid spurious blanklines at end of document after tables and list,
+      for example.
+    + Fixed bugs in simple/multiline list output (#3384).
+      Previously we got overlong lists with `--wrap=none`.  This is fixed.
+      Previously a multiline list could become a simple list (and would
+      always become one with `--wrap=none`).
+    + Don't emit a simple table if `simple_tables` disabled (#3529).
+    + Case-insensitive reference links (David A Roberts, #3616).
+      Ensure that we do not generate reference links whose labels differ only
+      by case.  Also allow implicit reference links when the link
+      text and label are identical up to case.
+    + Put space before reference link definitions (Mauro Bieg, #3630).
+    + Better escaping for links (David A. Roberts, #3619).  Previously the
+      Markdown writer would sometimes create links where there were none
+      in the source.  This is now avoided by selectively escaping bracket
+      characters when they occur in a place where a link might be created.
+    + Added missing `\n` (David A. Roberts, #3647).
+    + Fixed duplicated reference links with `--reference-links`
+      and `--reference-location=section` (#3674).  Also ensure that there
+      are no empty link references `[]`.
+    + Avoid inline surround-marking with empty content (#3715).
+      E.g. we don't want `<strong></strong>` to become `****`.
+      Similarly for emphasis, super/subscript, strikeout.
+    + Don't allow soft break in header (#3736).
+    + Make sure `plain`, `markdown_github`, etc. work for raw.
+      Previously only `markdown` worked.  Note: currently a raw block labeled
+      `markdown_github` will be printed for any `markdown` format.
+    + Ensure that `+` and `-` are escaped properly so they don't cause
+      spurious lists (#3773).  Previously they were only
+      if succeeded by a space, not if they were at end of line.
+    + Use pipe tables if `raw_html` disabled and `pipe_tables` enabled,
+      even if the table has relative width information (#3734).
+    + Markdown writer: don't crash on `Str ""`.
+    + Make `Span` with null attribute transparent.  That is, we don't use
+      brackets or `<span>` tags to mark spans when there are no attributes;
+      we simply output the contents.
+    + Escape pipe characters when `pipe_tables` enabled (#3887).
+    + Better escaping of `<` and `>`.  If `all_symbols_escapable` is set,
+      we backslash escape these.  Otherwise we use entities as before.
+    + When writing plain, don't use `&nbsp;` to separate list and indented
+      code.  There's no need for it in this context, since this isn't to be
+      interpreted using Markdown rules.
+    + Preserve classes in JS obfuscated links (Timm Albers, #2989).
+      HTML links containing classes originally now preserve them when using
+      javascript email obfuscation.
+    + Render `SmallCaps` as a native span when `native_spans` are enabled.
+    + Always write attributes with `bracketed_spans` (d-dorazio).
+
+  * Man writer:
+
+    + Fix handling of nested font commands (#3568).  Previously pandoc emitted
+      incorrect markup for bold + italic, for example, or bold + code.
+    + Avoid error for definition lists with no definitions (#3832).
+
+  * DocBook writer:
+
+    + Fix internal links with `writerIdentifierPrefix opt`
+      (#3397, Mauro Bieg).
+
+  * Docx writer:
+
+    + Don't include bookmarks on headers unless non-null id (#3476).
+    + Support 9 levels of headers (#1642).
+    + Allow 9 list levels (#3519).
+    + Don't take `distArchive` from datadir (#3322).  The docx writer takes
+      components from the distribution's version of `reference.docx` when it
+      can't find them in a user's custom `reference.docx`.  Previously, we
+      allowed a `reference.docx` in the data directory (e.g. `~/.pandoc`)
+      to be used as the distribution's reference.docx.  This led to a
+      bizarre situation where pandoc would produce a good docx using
+      `--template ~/.pandoc/ref.docx`, but if `ref.docx` were moved to
+      `~/.pandoc/reference.docx`, it would then produce a corrupted docx.
+    + Fixed handling of soft hyphen (0173) (#3691).
+    + Better handling of keywords (#3719).
+    + Cleaner code for handling dir and style attributes for `Div`.
+    + Use `Set` for dynamic styles to avoid duplicates.
+    + Removed redundant element from data/docx/word/numbering.xml.
+      The elements we need are generated when the document is
+      compiled; this didn't do anything.
+    + Activate `evenAndOddHeaders` from reference docx (#3901,
+      Augustín Martín Barbero).
+
+  * ODT/OpenDocument writer:
+
+    + Calculate aspect ratio for percentage-sized images (Mauro Bieg, #3239).
+    + Use more widely available bullet characters (#1400).  The old
+      characters weren't available in some font sets.  These seem to work
+      well on Windows and Linux versions of LibreOffice.
+    + Wider labels for lists (#2421).  This avoids overly narrow labels for
+      ordered lists with `()` delimiters.  However, arguably it creates
+      overly wide labels for bullets.  Also, lists now start flush with
+      the margin, rather than indented.
+    + Fixed dropped elements in some ordered lists (#2434).
+
+  * FB2 writer:
+
+    + Don't render `RawBlock` as code.
+    + Don't fail with an error on interior headers (e.g. in list) (#3750).
+      Instead, omit them with an INFO message.
+    + Add support for "lang" metadata (Alexander Krotov, #3625).
+    + Format `LineBlock` as poem (Alexander Krotov).  Previously writer
+      produced one paragraph with `<empty-line/>` elements, which are not
+      allowed inside `<p>` according to FB2 schema.
+    + Replace `concatMap` with `cMap` (Alexander Krotov).
+    + Write FB2 lists without nesting blocks inside `<p>` (Alexander
+      Krotov, #4004)
+
+  * HTML writer:
+
+    + Make sure `html4`, `html5` formats work for raw blocks/inlines.
+    + Render raw inline environments when `--mathjax` used (#3816).
+      We previously did this only with raw blocks, on the assumption
+      that math environments would always be raw blocks. This has changed
+      since we now parse them as inline environments.
+    + Ensure we don't get two style attributes for width and height.
+    + Report when not rendering raw inline/block.
+    + Issue warning if no title specified and template used (#3473).
+    + Info message if `lang` is unspecified (#3486).
+    + Removed unused parameter in `dimensionsToAttributeList`.
+    + Avoid two class attributes when adding `uri` class (#3716).
+    + Fix internal links with `writerIdentifierPrefix opt` (#3397, Mauro
+      Bieg).
+    + Use revealjs's math plugin for mathjax (#3743).  This is a thin
+      wrapper around mathjax that makes math look better on revealjs.
+    + Slidy:  use h1 for all slides, even if they were originally
+      level 2 headers (#3566).  Otherwise the built-in table of contents
+      in Slidy breaks.
+
+  * LaTeX writer:
+
+    + Don't render LaTeX images with data: URIs (#3636).  Note that
+      `--extract-media` can be used when the input contains data: URIs.
+    + Make highlighted code blocks work in footnotes (Timm Albers).
+    + Don't use figure inside table cell (#3836).
+    + Use proper code for list enumerators (#3891).  This should fix problems
+      with lists that don't use arabic numerals.
+    + Always add hypertarget when there's a non-empty identifier (#2719).
+      Previously the hypertargets were only added when there was actually
+      a link to that identifier.
+    + Use `%` after hypertarget before code block.
+    + Add `\leavevmode` before hypertarget at start of paragraph (#2704,
+      fixes formatting problems in beamer citations).
+    + Don't use `lstinline` in `\item[..]` (#645).  If you do, the contents
+      of item disappear or are misplaced.  Use `\texttt` instead.
+    + Fix problem with escaping in `lstinline` (#1629).  Previously the
+      LaTeX writer created invalid LaTeX when `--listings` was specified and
+      a code span occurred inside emphasis or another construction.
+    + Fix error with line breaks after empty content (#2874).  LaTeX
+      requires something before a line break, so we insert a `~` if no
+      printable content has yet been emitted.
+    + Use BCP47 parser.
+    + Fixed detection of otherlangs (#3770).  We weren't recursing into
+      inline contexts.
+    + Handle language in inline code with `--listings` (#3422).
+    + Write euro symbol directly in LaTeX (Andrew Dunning, #3801).
+      The textcomp package allows pdfLaTeX to parse `€` directly, making the
+      `\euro` command unneeded.
+    + Fixed footnotes in table captions (#2378).  Note that if the table has
+      a first page header and a continuation page header, the notes will
+      appear only on the first occurrence of the header.
+    + In `writeBeamer` output, allow hyperlinks to frames (#3220).
+      Previously you could link to a header above or below slide level but
+      not *to* slide level.  This commit changes that.  Hypertargets are
+      inserted inside frame titles; technically the reference is to just
+      after the title, but in normal use (where slides are viewed full
+      screen in a slide show), this does not matter.
+    + Remove `\strut` at beginning of table cells (#3436).  This fixes a
+      problem with alignment of lists in table cells.  The `\strut` at the
+      end seems to be enough to avoid the too-close spacing that motivated
+      addition of the strut  in #1573.
+    + Add partial siunitx Support (Marc Schreiber, #3588).
+
+  * ConTeXt writer:
+
+    + Refactored to use BCP47 module.
+    + Remove unnecessary `$` (Alexander Krotov, #3482).
+    + Use header identifiers for chapters (#3968).
+
+  * EPUB writer:
+
+    + `title_page.xhtml` is now put in `text/`.
+    + Don't strip formatting in TOC (#1611).
+
+  * Textile reader:
+
+    + Fix bug for certain links in table cells (#3667).
+    + Allow 'pre' code in list item (#3916).
+
+  * HTML reader:
+
+    + Added warnings for ignored material (#3392).
+    + Better sanity checks to avoid parsing unintended things as
+      raw HTML in the Markdown reader (#3257).
+    + Revise treatment of `li` with `id` attribute (#3596).  Previously we
+      always added an empty div before the list item, but this created
+      problems with spacing in tight lists.  Now we do this: If the list
+      item contents begin with a `Plain` block, we modify the `Plain`
+      block by adding a `Span` around its contents.  Otherwise, we add a
+      `Div` around the contents of the list item (instead of adding an
+      empty `Div` to the beginning, as before).
+    + Add `details` tag to list of block tags (#3694).
+    + Removed `button` from block tag list (#3717).  It is already in the
+      `eitherBlockOrInlineTag` list, and should be both places.
+    + Use `Set`s instead of lists for block tag lookup.
+    + Rewrote to use `Text` throughout.  Effect on memory usage is modest
+      (< 10%).
+    + Use the lang value of `<html>` to set the lang meta value (bucklereed,
+      #3765).
+    + Ensure that paragraphs are closed properly when the parent block
+      element closes, even without `</p>` (#3794).
+    + Parse `<figure>` and `<figcaption>` (Mauro Bieg, #3813).
+    + Parse `<main>` like `<div role=main>` (bucklereed, #3791).
+      `<main>` closes `<p>` and behaves like a block element generally
+    + Support column alignments (#1881).  These can be set either
+      with a `width` attribute or with `text-width` in a `style` attribute.
+    + Modified state type to be an instance of `HasLogMessages`, so
+      `registerHeader` can issue warnings.
+    + `</td>` or `</th>` should close any open block tag (#3991).
+    + `<td>` should close an open `<th>` or `<td>`.
+    + `htmlTag` improvements (#3989).  We previously failed on cases
+      where an attribute contained a `>` character. This patch fixes the
+      bug, which especially affects raw HTML in Markdown.
+
+  * Txt2Tags reader:
+
+    + Newline is not indentation (Alexander Krotov).
+
+  * MediaWiki reader:
+
+    + Allow extra hyphens after `|-` in tables (#2649).
+    + Allow blank line after table start (#2649).
+    + Fixed more table issues (#2649).
+    + Ensure that list starts begin at left margin (#2606).  Including when
+      they're in tables or other list items.
+    + Make smart double quotes depend on `smart` extension (#3585).
+    + Don't do curly quotes inside `<tt>` contexts (#3585).  Even if `+smart`.
+    + Modified state type to be an instance of `HasLogMessages`, so
+      `registerHeader` can issue warnings.
+
+  * TWiki reader (Alexander Krotov):
+
+    + Remove unnecessary `$` (#3597).
+    + Simplify `linkText` (#3605).
+
+  * EPUB reader:
+
+    + Minor refactoring, avoiding explicit MediaBag handling.
+      This all works behind the scenes in CommonState plumbing.
+
+  * Docx reader:
+
+    + Don't drop smartTag contents (#2242).
+    + Handle local namespace declarations (#3365).  Previously we didn't
+      recognize math, for example, when the xmlns declaration occurred on
+      the element and not the root.
+    + More efficient trimSps (#1530).  Replacing `trimLineBreaks`.  This
+      does the work of `normalizeSpaces` as well, so we avoid the need for
+      that function here.
+    + Avoid 0-level headers (Jesse Rosenthal, #3830).  We used to parse
+      paragraphs styled with "HeadingN" as "nth-level header." But if a
+      document has a custom style named "Heading0", this will produce a
+      0-level header, which shouldn't exist. We only parse this style
+      if N>0. Otherwise we treat it as a normal style name, and
+      follow its dependencies, if any.
+    + Add tests for avoiding zero-level header (Jesse Rosenthal).
+
+  * ODT reader:
+
+    + Replaced `collectRights` with Rights from `Data.Either`.
+    + Remove dead code (Albert Krewinkel).
+
+  * Org reader (Albert Krewinkel, unless noted).
+
+    + Don't allow tables inside list items (John MacFarlane, #3499).
+    + Disallow tables on list marker lines (#3499).
+    + Convert markup at beginning of footnotes (John MacFarlane, #3576).
+    + Allow emphasized text to be followed by `[` (#3577).
+    + Handle line numbering switch for src blocks.
+      The line-numbering switch that can be given to source blocks (`-n` with
+      an start number as an optional parameter) is parsed and translated to a
+      class/key-value combination used by highlighting and other readers and
+      writers.
+    + Stop adding rundoc prefix to src params.  Source block parameter names
+      are no longer prefixed with `rundoc`. This was intended to simplify
+      working with the rundoc project, a babel runner. However, the rundoc
+      project is unmaintained, and adding those markers is not the reader's
+      job anyway.  The original language that is specified for a source
+      element is now retained as the `data-org-language` attribute and only
+      added if it differs from the translated language.
+    + Allow multi-word arguments to src block params (#3477).  The reader now
+      correctly parses src block parameter list even if parameter arguments
+      contain multiple words.
+    + Avoid creating `nullMeta` by applying `setMeta` directly
+      (Alexander Krotov).
+    + Replace `sequence . map` with `mapM`.
+    + Fix smart parsing behavior.  Parsing of smart quotes and special
+      characters can either be enabled via the `smart` language extension or
+      the `'` and `-` export options. Smart parsing is active if either the
+      extension or export option is enabled.  Only smart parsing of special
+      characters (like ellipses and en and em dashes) is enabled by default,
+      while smart quotes are disabled.  Previously, all smart parsing was
+      disabled unless the language extension was enabled.
+    + Subject full doc tree to headline transformations (Albert Krewinkel,
+      #3695).  Emacs parses org documents into a tree structure, which is
+      then post-processed during exporting. The reader is changed to do the
+      same, turning the document into a single tree of headlines starting
+      at level 0.
+    + Fix cite parsing behaviour (Herwig Stuetz).  Until now, `org-ref`
+      cite keys included special characters also at the end. This caused
+      problems when citations occur right before colons or at the end of
+      a sentence.  With this change, all non alphanumeric characters at
+      the end of a cite key are ignored.  This also adds `,` to the list
+      of special characters that are legal in cite keys to better mirror
+      the behaviour of org-export.
+    + Fix module names in haddock comments.  Copy-pasting had lead to
+      haddock module descriptions containing the wrong module names.
+    + Recognize babel result blocks with attributes (#3706).  Babel
+      result blocks can have block attributes like captions and names.
+      Result blocks with attributes were not recognized and were parsed
+      as normal blocks without attributes.
+    + Include tags in headlines.  The Emacs default is to include tags in the
+      headline when exporting.  Instead of just empty spans, which contain the
+      tag name as attribute, tags are rendered as small caps and wrapped in
+      those spans.  Non-breaking spaces serve as separators for multiple tags.
+    + Respect export option for tags (#3713).  Tags are appended to
+      headlines by default, but will be omitted when the `tags` export option
+      is set to nil.
+    + Use `tag-name` attribute instead of `data-tag-name`.
+    + Use `org-language` attribute rather than `data-org-language`.
+    + Modified state type to be an instance of `HasLogMessages`, so
+      `registerHeader` can issue warnings.
+    + End footnotes after two blank lines.  Footnotes can not only be
+      terminated by the start of a new footnote or a header, but also by two
+      consecutive blank lines.
+    + Update emphasis border chars (#3933).  The org reader was updated to
+      match current org-mode behavior: the set of characters which are
+      acceptable to occur as the first or last character in an org emphasis
+      have been changed and now allows all non-whitespace chars at the
+      inner border of emphasized text (see `org-emphasis-regexp-components`).
+
+  * RST reader:
+
+    + Fixed small bug in list parsing (#3432).  Previously the parser didn't
+      handle properly this case:
+
+          * - a
+            - b
+          * - c
+            - d
+    + Handle multiline cells in simple tables (#1166).
+    + Parse list table directive (Keiichiro Shikano, #3432).
+    + Make use of `anyLineNewline` (Alexander Krotov, #3686).
+    + Use `anyLineNewline` in `rawListItem` (Alexander Krotov, #3702).
+    + Reorganize block parsers for ~20% faster parsing.
+    + Fixed `..include::` directive (#3880).
+    + Handle blank lines correctly in line blocks (Alexander Krotov, #3881).
+      Previously pandoc would sometimes combine two line blocks separated
+      by blanks, and ignore trailing blank lines within the line block.
+    + Fix indirect hyperlink targets (#512).
+
+  * Markdown reader:
+
+    + Allow attributes in reference links to start on next line (#3674).
+    + Parse YAML metadata in a context that sees footnotes defined in
+      the body of the document (#1279).
+    + When splitting pipe table cells, skip tex math (#3481).
+      You might have a `|` character inside math.  (Or for that matter
+      something that the parser might mistake for raw HTML.)
+    + Treat span with class `smallcaps` as SmallCaps.
+      This allows users to specify small caps in Markdown this way:
+      `[my text]{.smallcaps}` (#1592).
+    + Fixed internal header links (#2397).
+      This patch also adds `shortcut_reference_links` to the list
+      of mmd extensions.
+    + Treat certain environments as inline
+      when they occur without space surrounding them (#3309, #2171).
+      E.g. equation, math.  This avoids incorrect vertical space
+      around equations.
+    + Optimized `nonindentSpaces`.  Makes the benchmark go from 40 to 36 ms.
+    + Allow latex macro definitions indented 1-3 spaces.
+      Previously they only worked if nonindented.
+    + Improved parsing of indented raw HTML blocks (#1841).
+      Previously we inadvertently interpreted indented HTML as
+      code blocks.  This was a regression.  We now seek to determine the
+      indentation level of the contents of an HTML block, and (optionally)
+      skip that much indentation.  As a side effect, indentation may be
+      stripped off of raw HTML blocks, if `markdown_in_html_blocks` is
+      used. This is better than having things interpreted as indented
+      code blocks.
+    + Fixed smart quotes after emphasis (#2228).  E.g. in `*foo*'s 'foo'`.
+    + Warn for notes defined but not used (#1718).
+    + Use `anyLineNewline` (Alexander Krotov).
+    + Interpret YAML metadata as Inlines when possible (#3755).  If
+      the metadata field is all on one line, we try to interpret it as
+      Inlines, and only try parsing as Blocks if that fails.  If it
+      extends over one line (including possibly the `|` or `>` character
+      signaling an indented block), then we parse as Blocks.  This was
+      motivated by some German users finding that `date: '22. Juin 2017'`
+      got parsed as an ordered list.
+    + Fixed spurious parsing as citation as reference def (#3840).
+      We now disallow reference keys starting with `@` if the
+      `citations` extension is enabled.
+    + Parse `-@roe` as suppress-author citation (pandoc-citeproc#237).
+      Previously only `[-@roe]` (with brackets) was recognized as
+      suppress-author, and `-@roe` was treated the same as `@roe`.
+    + Fixed parsing of fenced code after list when there is no intervening
+      blank line (#3733).
+    + Allow raw latex commands starting with `\start` (#3558).  Previously
+      these weren't allowed because they were interpreted as starting
+      ConTeXt environments, even without a corresponding `\stop`...
+    + Added `inlines`, `inlines1`.
+    + Require nonempty alt text for `implicit_figures` (#2844).
+      A figure with an empty caption doesn't make sense.
+    + Removed texmath macro material; now all this is handled
+      in the LaTeX reader functions.
+    + Fixed bug with indented code following raw LaTeX (#3947).
+
+  * LaTeX reader:
+
+    + Rewrote LaTeX reader with proper tokenization (#1390,
+      #2118, #3236, #3779, #934, #982).  This rewrite is primarily
+      motivated by the need to get macros working properly.  A side benefit
+      is that the reader is significantly faster.  We now tokenize the
+      input text, then parse the token stream.  Macros modify the token
+      stream, so they should now be effective in any context, including
+      math. Thus, we no longer need the clunky macro processing
+      capacities of texmath.
+    + Parse `\,` to `\8198` (six-per-em space) (Henri Werth).
+    + Allow `\newcommand\foo{blah}` without braces.
+    + Support `\lstinputlisting` (#2116).
+    + Issue warnings when skipping unknown latex commands (#3392).
+    + Include contents of `\parbox`.
+    + Allow `\hspace` and `\vspace` to count as raw block or inline.
+      Previously we would refuse to parse anything as raw inline if
+      it was in the `blockCommands` list.  Now we allow exceptions
+      if they're listed under ignoreInlines in inlineCommands.
+      This should make it easier e.g. to include an `\hspace`
+      between two side-by-side raw LaTeX tables.
+    + Don't drop contents of `\hypertarget`.
+    + Handle spaces before `\cite` arguments.
+    + Allow newpage, clearpage, pagebreak in inline contexts as well as
+      block contexts (#3494).
+    + Treat `{{xxx}}` the same as `{xxx}` (#2115).
+    + Use `pMacroDefinition` in macro (for more direct parsing).
+      Note that this means that `macro` will now parse one
+      macro at a time, rather than parsing a whole group together.
+    + Fixed failures on `\ref{}`, `\label{}` with `+raw_tex`.  Now these
+      commands are parsed as raw if `+raw_tex`; otherwise, their argument
+      is parsed as a bracketed string.
+    + Don't crash on empty `enumerate` environment (#3707).
+    + Handle escaped `&` inside table cell (#3708).
+    + Handle block structure inside table cells (#3709).  `minipage` is no
+      longer required.
+    + Handle some width specifiers on table columns (#3709).  Currently
+      we only handle the form `0.9\linewidth`.  Anything else would have
+      to be converted to a percentage, using some kind arbitrary assumptions
+      about line widths.
+    + Make sure `\write18` is parsed as raw LaTeX.  The change is in the
+      LaTeX reader's treatment of raw commands, but it also affects the
+      Markdown reader.
+    + Fixed regression with starred environment names (#3803).
+    + Handle optional args in raw `\titleformat` (#3804).
+    + Improved heuristic for raw block/inline.  An unknown command at the
+      beginning of the line that could be either block or inline is
+      treated as block if we have a sequence of block commands followed by
+      a newline or a `\startXXX` command (which might start a raw ConTeXt
+      environment).
+    + Don't remove macro definitions from the output, even if
+      `Ext_latex_macros` is set, so that macros will be applied.
+      Since they're only applied to math in Markdown, removing the macros
+      can have bad effects.  Even for math macros, keeping them should be
+      harmless.
+    + Removed `macro`.  It is no longer necessary, since the
+      `rawLaTeXBlock` parser will parse macro definitions.  This also avoids
+      the need for a separate `latexMacro` parser in the Markdown reader.
+    + Use `label` instead of `data-label` for label in caption (#3639).
+    + Fixed space after `\figurename` etc.
+    + Resolve references to section numbers.
+    + Fix `\let\a=0` case, with single character token.
+    + Allow `@` as a letter in control sequences.  `@` is commonly used
+      in macros using `\makeatletter`.  Ideally we'd make the tokenizer
+      sensitive to `\makeatletter` and `\makeatother`, but until then this
+      seems a good change.
+    + Track header numbers and correlate with labels.
+    + Allow `]` inside group in option brackets (#3857).
+    + lstinline with braces can be used (verb cannot be used with braces)
+      (Marc Schreiber, #3535).
+    + Fix keyval function: pandoc did not parse options in braces correctly
+      (Marc Schreiber, #3642).
+    + When parsing raw LaTeX commands, include trailing space (#1773).
+      Otherwise things like `\noindent foo` break and turn into
+      `\noindentfoo`.  Affects `-f latex+raw_tex` and `-f markdown` (and other
+      formats that allow `raw_tex`).
+    + Don't treat "..." as Quoted (#3958).  This caused quotes to be omitted in
+      `\texttt` contexts.
+    + Add tests for existing `\includegraphics` behaviour (Ben Firshman).
+    + Allow space before `=` in bracketd options (Ben Firshman).
+    + Be more forgiving in parsing command options.  This was needed, for
+      example, to make some minted options work.
+    + Strip off quotes in `\include` filenames.
+
+  * Added `Text.Pandoc.CSV`, simple (unexported) CSV parser.
+
+  * `Text.Pandoc.PDF`:
+
+    + Got `--resource-path` working with PDF output (#852).
+    + Fetch images when generating PDF via context (#3380).
+      To do this, we create the temp directory as a subdirectory
+      of the working directory. Since context mk IV by default looks
+      for images in the parent directory, this works.
+    + Use `report` instead of `warn`, make it sensitive to verbosity settings.
+    + Use `fillMediaBag` and `extractMedia` to extract media to temp dir.
+      This reduces code duplication.
+    + `html2pdf`: use stdin instead of intermediate HTML file
+    + Removed useless `TEXINPUTS` stuff for `context2pdf`.  mkiv context
+      doesn't use `TEXINPUTS`.
+
+  * `Text.Pandoc.Pretty`:
+
+    + Simplified definition of `realLength`.
+    + Don't error for blocks of size < 1.  Instead, resize to 1 (see #1785).
+
+  * `Text.Pandoc.MIME`:
+
+    + Use `application/javascript` (not `application/x-javascript`).
+    + Added `emf` to mimeTypes with type `application/x-msmetafile` (#1713).
+
+  * `Text.Pandoc.ImageSize`:
+
+    + Improve SVG image size code (Marc Schreiber, #3580).
+    + Make `imageSize` recognize basic SVG dimensions (Mauro Bieg, #3462).
+
+  * Use `Control.Monad.State.Strict` throughout.  This gives 20-30% speedup
+    and reduction of memory usage in most of the writers.
+
+  * Use `foldrWithKey` instead of deprecated `foldWithKey`.
+
+  * `Text.Pandoc.SelfContained`:
+
+    + Fixed problem with embedded fonts (#3629).
+    + Refactored getData from `getDataURI` in `SelfContained`.
+    + Don't use data URIs for script or style (#3423).  Instead, just use
+      script or style tags with the content inside.  The old method with
+      data URIs prevents certain optimizations outside pandoc.  Exception:
+      data URIs are still used when a script contains `</script>` or a
+      style contains `</`.
+    + SelfContained: Handle URL inside material retrieved from a URL
+      (#3629).  This can happen e.g. with an @import of a google web font.
+      (What is imported is some CSS which contains an url reference
+      to the font itself.) Also, allow unescaped pipe (|) in URL.
+    + Load resources from `data-src` (needed for lazy loading in
+      reveal.js slide shows).
+    + Handle `data-background-image` attribute on section (#3979).
+
+  * `Text.Pandoc.Parsing`:
+
+    + Added `indentWith` (Alexander Krotov, #3687).
+    + Added `stateCitations` to `ParserState`.
+    + Removed `stateChapters` from `ParserState`.
+    + In `ParserState`, make `stateNotes'` a Map, add `stateNoteRefs`.
+    + Added `gobbleSpaces` and `gobbleAtMostSpaces`.
+    + Adjusted type of `insertIncludedFile` so it can be used with token
+      parser.
+    + Replace old texmath macro stuff from Parsing.  Use Macro from
+      Text.Pandoc.Readers.LaTeX.Types instead.
+    + Export `insertIncludedFile`.
+    + Added `HasLogMessages`, `logMessage`, `reportLogMessages` (#3447).
+    + Replace partial with total function (Albert Krewinkel).
+    + Introduce `HasIncludeFiles` type class (Albert Krewinkel).  The
+      `insertIncludeFile` function is generalized to work with all parser
+      states which are instances of that class.
+    + Add `insertIncludedFilesF` which returns F blocks (Albert Krewinkel).
+      The `insertIncludeFiles` function was generalized and renamed
+      to `insertIncludedFiles'`; the specialized versions are based on that.
+    + `many1Till`: Check for the end condition before parsing (Herwig
+      Stuetz).  By not checking for the end condition before the first
+      parse, the parser was applied too often, consuming too much of the
+      input. This only affects `many1Till p end` where `p` matches on a
+      prefix of `end`.
+    + Provide `parseFromString` (#3690).  This is a version of
+      `parseFromString` specialied to ParserState, which resets
+      `stateLastStrPos` at the end.  This is almost always what we want.
+      This fixes a bug where `_hi_` wasn't treated as emphasis in the
+      following, because pandoc got confused about the position of the
+      last word: `- [o] _hi_`.
+    + Added `takeP`, `takeWhileP` for efficient parsing of `[Char]`.
+    + Fix `blanklines` documentation (Alexander Krotov, #3843).
+    + Give less misleading line information with `parseWithString`.
+      Previously positions would be reported past the end of the chunk.
+      We now reset the source position within the chunk and report
+      positions "in chunk."
+    + Add `anyLineNewline` (Alexander Krotov).
+    + Provide shared F monad functions for Markdown and Org readers
+      (Albert Krewinkel).  The `F` monads used for delayed evaluation
+      of certain values in the Markdown and Org readers are based on a
+      shared data type capturing the common pattern of both `F` types.
+    + Add `returnF` (Alexander Krotov).
+    + Avoid parsing `Notes:**` as a bare URI (#3570).  This avoids parsing
+      bare URIs that start with a scheme + colon + `*`, `_`, or `]`.
+    + Added `readerAbbreviations` to `ParserState`.  Markdown reader
+      now consults this to determine what is an abbreviation.
+    + Combine grid table parsers (Albert Krewinkel, #3638).  The grid table
+      parsers for markdown and rst was combined into one single
+      parser `gridTable`, slightly changing parsing behavior of both
+      parsers: (1) The markdown parser now compactifies block content
+      cell-wise: pure text blocks in cells are now treated as paragraphs
+      only if the cell contains multiple paragraphs, and as plain blocks
+      otherwise. Before, this was true only for single-column tables. (2)
+      The rst parser now accepts newlines and multiple blocks in header
+      cells.
+    + Generalize tableWith, gridTableWith (Albert Krewinkel).
+      The parsing functions `tableWith` and `gridTableWith` are generalized
+      to work with more parsers. The parser state only has to be an
+      instance of the `HasOptions` class instead of requiring a concrete
+      type. Block parsers are required to return blocks wrapped into a
+      monad, as this makes it possible to use parsers returning results
+      wrapped in `Future`s.
+
+  * `Text.Pandoc.Shared`:
+
+    + Simplify `toRomanNumeral` using guards (Alexander Krotov, #3445)
+    + `stringify`: handle Quoted better (#3958).  Previously we were losing
+      the quotation marks in Quoted elements.
+
+  * `Text.Pandoc.Writers.Shared`:
+
+    + Export `metaToJSON'`, `addVariablesToJSON` (#3439).
+      This allows us to add the variables AFTER using the metadata
+      to generate a YAML header (in the Markdown writer).
+    + Added `unsmartify` (previously in RST writer).
+      Undo literal double curly quotes.  Previously we left these.
+    + Generalize type of `metaToJSON` so it can take a Text.  Previously a
+      String was needed as argument; now any ToJSON instance will do.
+    + Added `gridTable` (previously in Markdown writer).
+    + `gridTable`: Refactored to use widths in chars.
+    + `gridTable`:  remove unnecessary extra space in cells.
+    + Fixed `addVariablesToJSON`.  It was previously not allowing multiple
+      values to become lists.
+    + Pipe tables: impose minimum cell size (see #3526).
+
+
+### Default template changes
+
+  * HTML templates (including EPUB and HTML slide show templates):
+
+    + Make default.html5 polyglot markup conformant (John Luke Bentley,
+      #3473).  Polyglot markup is HTML5 that is also valid XHTML. See
+      <https://www.w3.org/TR/html-polyglot>.  With this change, pandoc's
+      html5 writer creates HTML that is both valid HTML5 and valid XHTML.
+    + Regularized CSS in html/epub/html slide templates (#3485).
+      All templates now include `code{white-space: pre-wrap}`
+      and CSS for `q` if `--html-q-tags` is used.  Previously some templates
+      had `pre` and others `pre-wrap`; the `q` styles were only sometimes
+      included.
+    + CSS for `.smallcaps`, (Mauro Bieg, #1592)
+    + `default.revealjs`: make `history` default to true.
+    + `default.revealjs`: use lazy loading (#2283).
+    + `default.revealjs`: add `mathjax` variable and some conditional code
+      to use the MathJaX plugin.
+    + `default.slidy` uses `https` instead of `http` (ickc, #3848).
+    + `default.dzslides`: Load Google Font using HTTPS by default
+      (Yoan Blanc).
+
+  * DocBook5 template: Use `lang` and `subtitle` variables (Jens Getreu,
+    #3855).
+
+  * LaTeX/Beamer template:
+
+    + Combine LaTeX/Beamer templates (Andrew Dunning, #3878).
+      `default.beamer` has been removed; beamer now uses the
+      `default.latex` template.  Beamer-specific parts are conditional
+      on the `beamer` variable set by the writer. Note that
+      `pandoc -D beamer` will return this (combined) template.
+    + Use `xcolor` for `colorlinks` option (Andrew Dunning, #3877).
+      Beamer loads `xcolor` rather than `color`, and thus the
+      `dvipsnames` option doesn't take effect. This also provides a wider
+      range of colour selections with the `svgnames` option.
+    + Use starred versions of `xcolor` names (Andrew Dunning).
+      Prevents changes to documents defined using the `dvipsnames` list (e.g.
+      `Blue` gives a different result with svgnames enabled).
+    + Load `polyglossia` after header-includes (#3898).  It needs to be
+      loaded as late as possible.
+    + Use `unicode-math` (Vaclav Haisman).  Use `mathspec` with only
+      XeLaTeX on request.
+    + Don't load `fontspec` before `unicode-math` (over there).
+      The `unicode-math` package loads `fontspec` so explicit loading of
+      `fontspec` before `unicode-math` is not necessary.
+    + Use `unicode-math` by default in default.latex template.  mathspec will
+      be used in xelatex if the `mathspec` variable is set; otherwise
+      unicode-math will be used (Václav Haisman).
+    + Use `dvipsnames` options when `colorlinks` specified (otherwise
+      we get an error for `maroon`) (Thomas Hodgson).
+    + Added beamer `titlegraphic` and `logo` variables (Thomas Hodgson).
+    + Fix typo in fix for notes in tables (#2378, zeeMonkeez).
+    + Fix `hyperref` options clash (Andrew Dunning, #3847) Avoids an options
+      clash when loading a package (e.g. `tufte-latex`) that uses
+      `hyperref` settings different from those in the template.
+    + Add `natbiboptions` variable (#3768).
+    + Fix links inside captions in LaTeX output with links-as-notes
+      (Václav Haisman, #3651).  Declare our redefined `\href` robust.
+    + Load `parskip` before `hyperref` (Václav Haisman, #3654).
+    + Allow setting Japanese fonts when using LuaLaTeX (Václav Haisman,
+      #3873).  by using the `luatexja-fontspec` and `luatexja-preset`
+      packages. Use existing `CJKmainfont` and `CJKoptions` template
+      variables. Add `luatexjafontspecoptions` for `luatexja-fontspec`
+      and `luatexjapresetoptions` for `luatexja-preset`.
+    + Added `aspectratio` variable to beamer template (Václav Haisman,
+      #3723).
+    + Modified template.latex to fix XeLaTex being used with tables
+      (lwolfsonkin, #3661).  Reordered `lang` variable handling to
+      immediately before `bidi`.
+
+  * ConTeXt template: Improved font handling: `simplefonts` is now
+    obsolete in ConTeXt (Pablo Rodríguez).
+
+
+### Documentation improvements
+
+  * MANUAL.txt:
+
+    + Add URL for Prince HTML > PDF engine (Ian, #3919).
+    + Document that content above slide-level will be omitted in
+      slide shows.  See #3460, #2265.
+    + Explain `--webtex` SVG url (Mauro Bieg, #3471)
+    + Small clarification in YAML metadata section.
+    + Document that html4 is technically XHTML 1.0 transitional.
+    + Remove refs to highlighting-kate (#3672).
+    + Document ibooks specific epub metadata.
+    + Clarify that mathml is used for ODT math.
+    + Mention limitations of Literate Haskell Support (#3410,
+      Joachim Breitner).
+    + Add documentation of limitations of grid tables (Stephen
+      McDowell, #3864).
+    + Clarify that meta-json contains transformed values (Jakob Voß,
+      #3491) Make clear that template variable `meta-json` does not
+      contain plain text values or JSON output format but field values
+      transformed to the selected output format.
+
+  * COPYRIGHT:
+
+    + Clarify that templates are dual-licensed.
+    + Clarify that pandoc-types is BSD3 licensed.
+    + List new files not written by jgm (Albert Krewinkel).
+    + Update dates in copyright notices (Albert Krewinkel).  This follows
+      the suggestions given by the FSF for GPL licensed software.
+      <https://www.gnu.org/prep/maintain/html_node/Copyright-Notices.html>
+
+  * INSTALL.md:
+
+    + Improved instructions for tests with patterns.
+    + Put RPM-based distros on separate point (Mauro Bieg, #3449)
+
+  * CONTRIBUTING.md:
+
+    + Fixed typos (Wandmalfarbe, #3479).
+    + Add "ask on pandoc-discuss" (Mauro Bieg).
+
+  * Add lua filter documentation in `doc/lua-filters.md`.  Note that the
+    end of this document is autogenerated from `data/pandoc.lua`
+    using `make doc/lua-filters.md`, which uses `tools/ldoc.ltp`
+    (Albert Krewinkel).
+
+  * Add `doc/filters.md`. This is the old scripting tutorial from
+    the website.
+
+  * Add `doc/using-the-pandoc-api.md` (#3289).  This gives an introduction
+    to using pandoc as a Haskell library.
+
+
+### Build infrastructure improvements
+
+  * Removed `data/templates` submodule.  Templates are now a subtree
+    in `data/templates`.  This removes the need to do `git submodule
+    update`.
+
+  * Renamed `tests` -> `test`.
+
+  * Remove `https` flag.  Always build with HTTPS support.
+
+  * Use `file-embed` instead of `hsb2hs` to embed data files when
+    `embed_data_files` flag is set.  `file-embed` gives us better dependency
+    tracking:  if a data file changes, ghc/stack/cabal know to recompile
+    the Data module.  This also removes `hsb2hs` as a build dependency.
+
+  * Add `custom-setup` stanza to pandoc, lowercase field names.
+
+  * Add `static` Cabal flag.
+
+  * Name change OSX -> MacOS.  Add a -MacOS suffix to mac package rather
+    than -OSX.  Changed local names from osx to macos.
+
+  * make_macos_package.sh - Use strip to reduce executable size.
+
+  * Revised binary linux package.  Now a completely static executable
+    is created, using Docker and alpine.  We create both a deb and a
+    tarball.  The old `deb` directory has been replaced with a `linux`
+    directory.  Running `make` in the `linux` directory should
+    perform the build, putting the binary packages in `artifacts/`.
+
+  * `linux/control.in`: add `Replaces:`, so existing pandoc-citeproc and
+    pandoc-data packages will be uninstalled; this package provides
+    both (#3822).  Add latex packages as 'suggested', update
+    description.
+
+  * Remove cpphs build requirement -- it is no longer needed.
+
+  * Replaced `{deb,macos,windows}/stack.yaml` with `stack.pkg.yaml`.
+
+  * Name change OSX -> macOS (ickc, #3869).
+
+  * Fix casing of Linux, UNIX, and Windows (ickc).
+
+  * `.travis.yml`:  create a source dist and do cabal build and test there.
+    That way we catch errors due to files missing from the data
+    section of pandoc.cabal.
+
+  * Makefile:
+
+    + Split `make haddock` from `make full`.
+    + Add BRANCH variable for winpkg.
+    + Add `lint` target.
+    + Improve `make full`. Disable optimizations.
+      Build everything, inc. trypandoc and benchmarks.  Use parallel build.
+    + Allow `make test` to take `TESTARGS`.
+
+  * Added new command tests (`Tests.Command`), using small text files
+    in `test/command/`.  Any files added in this directory will be treated
+    as shell tests (see smart.md for an example).  This makes it very easy
+    to add regression tests etc.
+
+  * Test fixes so we can find data files.  In old tests & command tests,
+    we now set the environment variable `pandoc_datadir`.  In lua tests,
+    we set the datadir explicitly.
+
+  * Refactored `compareOutput` in docx writer test.
+
+  * Consolidated some common functions in `Tests.Helper`.
+
+  * Small change to unbalanced bracket test to speed up test suite.
+
+  * Speed up Native writer quickcheck tests.
+
+  * Use tasty for tests rather than test-framework.
+
+  * Add simple Emacs mode to help with Pandoc templates editing.
+    (Václav Haisman, #3889). `tools/pandoc-template-mode.el`
+
+
+## pandoc 1.19.2.4 (2017-09-10)
+
+  * Add dependencies on texmath and skylighting to the executable.
+    This is needed for dependency version numbers to be available,
+    with Cabal > 2.
+
+## pandoc 1.19.2.3 (2017-09-09)
+
+  * Add CPP to Setup.hs so it works with Cabal >= 2 and < 2.
+
+## pandoc 1.19.2.2 (2017-09-08)
+
+  * Fix build with GHC 8.2.1 (#3876, Peter Simons).  Setup.hs does not
+    compile with Cabal 2.x, so we require an earlier version via
+    setup-depends.  The following packages need newer versions with
+    GHC 8.2.1 and had their constraints relaxed accordingly:
+    executable-path, process, syb, and time.
+
+## pandoc 1.19.2.1 (2017-01-31)
+
+  * Require skylighting >= 0.1.1.4.
+  * Adjust test output for skylighting version.
+  * Relax upper bounds on blaze-html and blaze-markup.
+
+## pandoc 1.19.2 (2017-01-29)
+
+  * Use skylighting library instead of highlighting-kate for syntax
+    highlighting. Skylighting is faster and more accurate (#3363).
+    Later we'll be able to add features like warning messages, dynamic
+    loading of xml syntax definitions, and dynamic loading of themes.
+
+  * Added a new highlight style, `breezeDark`.
+
+  * Text.Pandoc.Highlighting: Update list of `listings` languages (#3374).
+    This allows more languages to be used when using the `--listings`
+    option.
+
+  * OpenDocument writer:
+
+    + Small refactoring.  Removed separate 'parent' parameter in paraStyle.
+    + Don't profilerate text styles unnecessarily (#3371).
+      This change makes the writer create only as many temporary
+      text styles as are absolutely necessary. It also consolidates
+      adjacent nodes with the same style.
+
+  * Org reader (Albert Krewinkel):
+
+    + Allow short hand for single-line raw blocks (Albert Krewinkel,
+      #3366).  Single-line raw blocks can be given via `#+FORMAT: raw line`,
+      where `FORMAT` must be one of `latex`, `beamer`, `html`, or `texinfo`.
+    + Accept org-ref citations followed by commas (Albert Krewinkel).
+      Bugfix for an issue which, whenever the citation was immediately
+      followed by a comma, prevented correct parsing of org-ref citations.
+    + Ensure emphasis markup can be nested.  Nested emphasis markup (e.g.
+      `/*strong and emphasized*/`) was interpreted incorrectly in that the
+      inner markup was not recognized.
+    + Remove pipe char irking the haddock coverage tool (Albert Krewinkel).
+
+  * Docx reader: Empty header should be list of lists (Jesse Rosenthal).
+    In the past, the docx reader wrote an empty header as an empty list. It
+    should have the same width as a row (and be filled with empty cells).
+
+  * MediaWiki reader:
+
+    + Improved handling of display math (#3362).  Sometimes display math is
+      indented with more than one colon.  Previously we handled these cases
+      badly, generating definition lists and missing the math.
+    + Fix quotation mark parsing (#3336, tgkokk).  Change MediaWiki reader's
+      behavior when the smart option is parsed to match other readers'
+      behavior.
+
+  * Markdown reader:
+
+    + Fixed `-f markdown_github-hard_line_breaks+escaped_line_breaks`
+      (#3341).  Previously this did not properly enable escaped line breaks.
+    + Disallow space between inline code and attributes (#3326, #3323,
+      Mauro Bieg).
+
+  * DocBook5 writer: make id attribute xml:id, fixes #3329 (#3330, Mauro Bieg).
+
+  * Added some test cases for ODT reader (#3306, #3308, Hubert Plociniczak).
+
+  * LaTeX writer: allow tables with empty cells to count as "plain."
+    This addresses a problem of too-wide tables when empty cells
+    are used.  Thanks to Joost Kremers for reporting the issue.
+
+  * Org writer: prefix footnote numbers with `fn:` (Albert Krewinkel).
+    Unprefixed numbers where used by older org-mode versions, but are no
+    longer supported.
+
+  * HTML writer: don't process pars with empty RawInline, (#1040, #3327,
+    Mauro Bieg).
+
+  * Markdown writer: Fix display math with `--webtex` (#3298).
+
+  * Fix sample.lua so it properly handles raw blocks/inlines (#3358,
+    bumper314).
+
+  * Templates:
+
+    + default.latex: Moved geometry after hyperref (Václav Haisman).
+      Otherwise PDF sizes can be wrong in some circumstances.
+    + Copied a few changes from default.latex to default.beamer
+      (Wandmalfarbe).
+    + default.latex, default.beamer: Changed position of `\VerbatimNotes`
+      and `fancyvrb`.  This fixes hyperlinks on footnotes in documents
+      that contain verbatim in notes (#3361).  (Note: the beamer template
+      was updated to match the LaTeX template, but at this point verbatim
+      in notes seems not to work in beamer.)
+    + default.latex: Allow passing `microtypeoptions` to microtype
+      (Václav Haisman).
+    + default.latex: Add hyphen option to url package.
+    + default.docbook5: Fix namespace declarations (Mauro Bieg).
+
+  * Moved `make_osx_package.sh` to `osx/` directory.
+
+  * Travis continuous integration:
+
+    + Fix false positives with dist build.
+    + Speed improvements (Kolen Cheung, #3304, #3357).
+
+  * MANUAL.txt:
+
+    + Clarify that blank space is needed around footnotes (#3352).
+    + Fixed typo (#3351, Alexey Rogechev).
+    + Note that `--wrap=auto` does not work in HTML output.
+    + Default `--columns` width is 72, not 80.
+    + Fixed broken links (#3316, Kolen Cheung).
+    + Document usage of `@*` in nocite section (#3333, John Muccigrosso).
+
+  * INSTALL.md:
+
+    + Indent code so it's properly formatted (#3335, Bheesham Persaud).
+    + Added instructions for extracting binary from OSX, Windows packages.
+
+  * CONTRIBUTING.md: Describe labels currently used in issue tracker
+    (Albert Krewinkel).  The labels have changed over time, the list of
+    labels is updated to reflect the current set of labels used in the
+    issue tracker.
+
+  * Rearrange and extend badges in README (Albert Krewinkel, #3354)
+
+  * Bumped version bounds for dependencies.
+
+
+## pandoc 1.19.1 (2016-12-10)
+
+  * Set `PANDOC_VERSION` environment variable for filters (#2640).
+    This allows filters to check the pandoc version that produced
+    the JSON they are receiving.
+
+  * Docx reader: Ensure one-row tables don't have header (#3285,
+    Jesse Rosenthal).  Tables in MS Word are set by default to have
+    special first-row formatting, which pandoc uses to determine whether
+    or not they have a header. This means that one-row tables will, by
+    default, have only a header -- which we imagine is not what people
+    want. This change ensures that a one-row table is not understood to
+    be a header only.  Note that this means that it is impossible to
+    produce a header-only table from docx, even though it is legal
+    pandoc. But we believe that in nearly all cases, it will be an
+    accidental (and unwelcome) result
+
+  * HTML reader:
+
+    + Fixed some bad regressions in HTML table parser (#3280).
+      This regression leads to the introduction of empty rows
+      in some circumstances.
+    + Understand `style=width:` as well as `width` in `col` (#3286).
+
+  * RST reader:
+
+    + Print warnings when keys, substitition, notes not found.
+      Previously the parsers failed and we got raw text.  Now we get a
+      link with an empty URL, or empty inlines in the case of a note or
+      substitution.
+
+    + Fix hyperlink aliases (#3283).
+
+  * Man writer: Ensure that periods are escaped at beginning of line
+    (#3270).
+
+  * LaTeX writer: Fix unnumbered headers when used with `--top-level`
+    (#3272, Albert Krewinkel). Fix interaction of top-level
+    divisions `part` or `chapter` with unnumbered headers when
+    emitting LaTeX. Headers are ensured to be written using
+    stared commands (like `\subsection*{}`).
+
+  * LaTeX template: use comma not semicolon to separate keywords for
+    `pdfkeywords`.  Thanks to Wandmalfarbe.
+
+  * Markdown writer: Fixed incorrect word wrapping (#3277).
+    Previously pandoc would sometimes wrap lines too early due to
+    this bug.
+
+  * Text.Pandoc.Pretty:  Added `afterBreak` [API change].  This makes it
+    possible to insert escape codes for content that needs escaping at the
+    beginning of a line.
+
+  * Removed old MathMLInHTML.js from 2004, which should no longer
+    be needed for MathML with modern browsers.
+
+  * Fixed tests with dynamic linking (#2709).
+
+  * Makefile: Use stack instead of cabal for targets.  This is just
+    a convenience for developers.
+
+  * Fixed bash completion of filenames with space (#2749).
+
+  * MANUAL: improved documentation on how to create a custom
+    `reference.docx`.
+
+  * Fix minor spelling typos in the manual (#3273, Anthony Geoghegan)
+
+## pandoc 1.19 (2016-12-01)
+
+  * Changed resolution of filter paths.
+
+    + We now first treat the argument of `--filter` as a full (absolute
+      or relative) path, looking for a program there. If it's found, we
+      run it.
+    + If not, and if it is a simple program name or a relative path, we
+      try resolving it relative to `$DATADIR/filters`.
+    + If this fails, then we treat it as a program name and look in the
+      user's PATH.
+    + Removed a hardcoded '/' that may have caused problems with
+      Windows paths.
+
+    Previously if you did `--filter foo` and you had `foo` in your path and
+    also an executable `foo` in your working directory, the one in the path
+    would be used. Now the one in the working directory is used.
+
+    In addition, when you do `--filter foo/bar.hs`, pandoc will now find a
+    filter `$DATADIR/filters/foo/bar.hs` -- assuming there isn't a
+    `foo/bar.hs` relative to the working directory.
+
+  * Allow `file://` URIs as arguments (#3196). Also improved default reader
+    format detection. Previously with a URI ending in .md or .markdown,
+    pandoc would assume HTML input. Now it treats these as markdown.
+
+  * Allow to overwrite top-level division type heuristics (#3258,
+    Albert Krewinkel). Pandoc uses heuristics to determine the most
+    reasonable top-level division type when emitting LaTeX or
+    Docbook markup. It is now possible to overwrite this implicitly set
+    top-level division via the `top-level-division` command line parameter.
+
+  * Text.Pandoc.Options \[API changes\]:
+
+    + Removed `writerStandalone` field in `WriterOptions`, made
+      `writerTemplate` a `Maybe` value. Previously setting
+      `writerStandalone = True` did nothing unless a template was provided
+      in writerTemplate. Now a fragment will be generated if
+      `writerTemplate` is `Nothing`; otherwise, the specified template
+      will be used and standalone output generated.
+    + `Division` has been renamed `TopLevelDivision` (#3197). The
+      `Section`, `Chapter`, and `Part` constructors were renamed to
+      `TopLevelSection`, `TopLevelChapter`, and
+      `TopLevelPart`, respectively. An additional `TopLevelDefault`
+      constructor was added, which is now also the new default value of
+      the `writerTopLevelDivision` field in `WriterOptions`.
+
+  * Improved error if they give wrong arg to `--top-level-division`.
+
+  * Use new module from texmath to lookup MS font codepoints in Docx reader.
+    Removed unexported module Text.Pandoc.Readers.Docx.Fonts. Its code now
+    lives in texmath (0.9).
+
+  * DocBook reader: Fixed xref lookup (#3243). It previously only worked
+    when the qnames lacked the docbook namespace URI.
+
+  * HTML reader:
+
+    + Improved table parsing (#3027). We now check explicitly for non-1
+      rowspan or colspan attributes, and fail when we encounter them.
+      Previously we checked that each row had the same number of cells,
+      but that could be true even with rowspans/colspans. And there are
+      cases where it isn't true in tables that we can handle fine -- e.g.
+      when a tr element is empty. So now we just pad rows with empty cells
+      when needed.
+    + Treat `<math>` as MathML by default unless something else is
+      explicitly specified in xmlns. Provided it parses as MathML,
+      of course. Also fixed default which should be to inline math if no
+      display attribute is used.
+    + Only treat "a" element as link if it has href (#3226). Otherwise
+      treat as span.
+
+  * Docx reader (Jesse Rosenthal):
+
+    + Add a placeholder value for CHART. We wrap `[CHART]` in a
+      `<span class="chart">`. Note that it maps to inlines because, in
+      docx, anything in a drawing tag can be part of a larger paragraph.
+    + Be more specific in parsing images We not only want `w:drawing`,
+      because that could also include charts. Now we specify
+      `w:drawing/pic:pic`. This shouldn't change behavior at all, but it's
+      a first step toward allowing other sorts of drawing data as well.
+    + Abstract out function to avoid code repetition.
+    + Update tests for img title and alt (#3204).
+    + Handle Alt text and titles in images. We use the "description" field
+      as alt text and the "title" field as title. These can be accessed
+      through the "Format Picture" dialog in Word.
+    + Docx reader utils: handle empty namespace in `elemName`. Previously,
+      if given an empty namespace `(elemName ns "" "foo")` `elemName`
+      would output a QName with a `Just ""` namespace. This is never what
+      we want. Now we output a `Nothing`. If someone *does* want a
+      `Just ""` in the namespace, they can enter the QName
+      value explicitly.
+
+  * ODT reader/writer:
+
+    + Inline code when text has a special style (Hubert Plociniczak). When
+      a piece of text has a text `Source_Text` then we assume that this is
+      a piece of the document that represents a code that needs to
+      be inlined. Adapted the writer to also reflect that change.
+      Previously it was just writing a 'preformatted' text using a
+      non-distinguishable font style. Code blocks are still not recognized
+      by the ODT reader. That's a separate issue.
+    + Infer table's caption from the paragraph (#3224,
+      Hubert Plociniczak). ODT's reader always put empty captions for the
+      parsed tables. This commit
+
+        1.  checks paragraphs that follow the table definition
+        2.  treats specially a paragraph with a style named 'Table'
+        3.  does some postprocessing of the paragraphs that combines tables
+            followed immediately by captions
+
+      The ODT writer used the `TableCaption` style for the caption
+      paragraph.  This commit follows the OpenOffice approach which allows
+      for appending captions to table but uses a built-in style named
+      `Table` instead of `TableCaption`. Users of a custom `reference.odt`
+      should change the style's name from `TableCaption` to `Table`.
+
+  * ODT reader: Infer tables' header props from rows (#3199,
+    Hubert Plociniczak). ODT reader simply provided an empty header list
+    which meant that the contents of the whole table, even if not empty, was
+    simply ignored. While we still do not infer headers we at least have to
+    provide default properties of columns.
+
+  * Markdown reader:
+
+    +   Allow reference link labels starting with `@...` if `citations`
+        extension disabled (#3209). Example: in
+
+            \[link text\]\[@a\]
+
+        `link text` isn't hyperlinked because `[@a]` is parsed as
+        a citation. Previously this happened whether or not the `citations`
+        extension was enabled. Now it happens only if the `citations`
+        extension is enabled.
+    +   Allow alignments to be specified in Markdown grid tables. For
+        example,
+
+            +-------+---------------+--------------------+
+            | Right    | Left                 | Centered |
+            +=========:+:=================+:=============:+
+            | Bananas | $1.34         | built-in wrapper |
+            +-------+---------------+--------------------+
+
+    +   Allow Small Caps elements to be created using bracketed spans (as
+        they already can be using HTML-syntax spans) (#3191, Kolen Cheung).
+
+  * LaTeX reader:
+
+    + Don't treat `\vspace` and `\hspace` as block commands (#3256).
+      Fixed an error which came up, for example, with `\vspace` inside
+      a caption. (Captions expect inlines.)
+    + Improved table handling. We can now parse all of the tables emitted
+      by pandoc in our tests. The only thing we don't get yet are
+      alignments and column widths in more complex tables. See #2669.
+    + Limited support for minipage.
+    + Allow for `[]`s inside LaTeX optional args. Fixes cases like:
+    + Handle BVerbatim from fancyvrb (#3203).
+    + Handle hungarumlaut (#3201).
+    + Allow beamer-style `<...>` options in raw LaTeX (also in Markdown)
+      (#3184). This allows use of things like `\only<2,3>{my content}` in
+      Markdown that is going to be converted to beamer.
+
+  * Use pre-wrap for code in dzslides template (Nicolas Porcel). Otherwise
+    overly long code will appear on every slide.
+
+  * Org reader (Albert Krewinkel):
+
+    +   Respect column width settings (#3246). Table column properties can
+        optionally specify a column's width with which it is displayed in
+        the buffer. Some exporters, notably the ODT exporter in org-mode
+        v9.0, use these values to calculate relative column widths. The org
+        reader now implements the same behavior. Note that the org-mode
+        LaTeX and HTML exporters in Emacs don't support this feature yet,
+        which should be kept in mind by users who use the column
+        widths parameters.
+    +   Allow HTML attribs on non-figure images (#3222). Images which are
+        the only element in a paragraph can still be given HTML attributes,
+        even if the image does not have a caption and is hence not a figure.
+        The following will add set the `width` attribute of the image to
+        `50%`:
+
+            +ATTR\_HTML: :width 50%
+            =======================
+
+            \[\[file:image.jpg\]\]
+
+    +   Support `ATTR_HTML` for special blocks (#3182). Special
+        blocks (i.e. blocks with unrecognized names) can be prefixed with an
+        `ATTR_HTML` block attribute. The attributes defined in that
+        meta-directive are added to the `Div` which is used to represent the
+        special block.
+    +   Support the `todo` export option. The `todo` export option allows to
+        toggle the inclusion of TODO keywords in the output. Setting this to
+        `nil` causes TODO keywords to be dropped from headlines. The default
+        is to include the keywords.
+    +   Add support for todo-markers. Headlines can have optional
+        todo-markers which can be controlled via the `#+TODO`, `#+SEQ_TODO`,
+        or `#+TYP_TODO` meta directive. Multiple such directives can be
+        given, each adding a new set of recognized todo-markers. If no
+        custom todo-markers are defined, the default `TODO` and `DONE`
+        markers are used. Todo-markers are conceptually separate from
+        headline text and are hence excluded when autogenerating
+        headline IDs. The markers are rendered as spans and labelled with
+        two classes: One class is the markers name, the other signals the
+        todo-state of the marker (either `todo` or `done`).
+
+  * LaTeX writer:
+
+    + Use `\autocites*` when "suppress-author" citation used.
+    + Ensure that simple tables have simple cells (#2666). If cells
+      contain more than a single Plain or Para, then we need to set
+      nonzero widths and put contents into minipages.
+    + Remove invalid inlines in sections (#3218, Hubert Plociniczak).
+
+  * Markdown writer:
+
+    + Fix calculation of column widths for aligned multiline tables
+      (#1911, Björn Peemöller). This also fixes excessive CPU and memory
+      usage for tables when `--columns` is set in such a way that cells
+      must be very tiny. Now cells are guaranteed to be big enough so that
+      single words don't need to line break, even if this pushes the line
+      length above the column width.
+    + Use bracketed form for native spans when `bracketed_spans`
+      enabled (#3229).
+    + Fixed inconsistent spacing issue (#3232). Previously a tight bullet
+      sublist got rendered with a blank line after, while a tight ordered
+      sublist did not. Now we don't get the blank line in either case.
+    + Fix escaping of spaces in super/subscript (#3225). Previously two
+      backslashes were inserted, which gave a literal backslash.
+    + Adjust widths in Markdown grid tables so that they match
+      on round-trip.
+
+  * Docx writer:
+
+    + Give full detail when there are errors converting tex math.
+    + Handle title text in images (Jesse Rosenthal). We already handled
+      alt text. This just puts the image "title" into the docx
+      "title" attr.
+    + Fixed XML markup for empty cells (#3238). Previously the Compact
+      style wasn't being applied properly to empty cells.
+
+  * HTML writer:
+
+    + Updated `renderHtml` import from blaze-html.
+
+  * Text.Pandoc.Pretty:
+
+    + Fixed some bugs that caused blank lines in tables (#3251). The bugs
+      caused spurious blank lines in grid tables when we had things like
+      `blankline $$ blankline`.
+    + Add exported function `minOffet` \[API change\] (Björn Peemöller).
+    + Added error message for illegal call to `block` (Björn Peemöller).
+
+  * Text.Pandoc.Shared:
+
+    + Put `warn` in MonadIO.
+    + `fetchItem`: Better handling of protocol-relative URL (#2635). If
+      URL starts with `//` and there is no "base URL" (as there would be
+      if a URL were used on the command line), then default to http:.
+
+  * Export Text.Pandoc.getDefaultExtensions \[API change\] (#3178).
+
+  * In --version, trap error in `getAppUserDataDirectory` (#3241). This
+    fixes a crash with `pandoc --version` on unusual systems with no real
+    user (e.g. SQL Server 2016).
+
+  * Added weigh-pandoc for memory usage diagnostics (#3169).
+
+  * Use correct mime types for woff and woff2 (#3228).
+
+  * Remove make\_travis\_yml.hs (#3235, Kolen Cheung).
+
+  * changelog: Moved an item that was misplaced in the 1.17.2 section to the
+    1.18 section where it belongs.
+
+  * CONTRIBUTING.md: minor change in wording and punctuation (#3252,
+    Kolen Cheung).
+
+  * Further revisions to manual for `--version` changes (#3244).
+
+
+
+## pandoc 1.18 (2016-10-26)
+
+  * Added `--list-input-formats`, `--list-output-formats`,
+    `--list-extensions`, `--list-highlight-languages`, and
+    `--list-highlight-styles` (#3173).  Removed list of highlighting
+    languages from `--version` output.  Removed list of input and output
+    formats from default `--help` output.
+
+  * Added `--reference-location=block|section|document` option
+    (Jesse Rosenthal).  This determines whether Markdown link references
+    and footnotes are placed at the end of the document, the end of the
+    section, or the end of the top-level block.
+
+  * Added `--top-level-division=section|chapter|part` (Albert Krewinkel).
+    This determines what a level-1 header corresponds to in LaTeX,
+    ConTeXt, DocBook, and TEI output.  The default is `section`.
+    The `--chapters` option has been deprecated in favor of
+    `--top-level-division=chapter`.
+
+  * Added `LineBlock` constructor for `Block` (Albert Krewinkel).  This
+    is now used in parsing RST and Markdown line blocks, DocBook
+    `linegroup`/`line` combinations, and Org-mode `VERSE` blocks.
+    Previously `Para` blocks with hard linebreaks were used.  `LineBlock`s
+    are handled specially in the following output formats: AsciiDoc
+    (as `[verse]` blocks), ConTeXt (`\startlines`/`\endlines`),
+    HTML (`div` with a style), Markdown (line blocks if `line_blocks`
+    is enabled), Org-mode (`VERSE` blocks), RST (line blocks). In
+    other output formats, a paragraph with hard linebreaks is emitted.
+
+  * Allow binary formats to be written to stdout (but not to tty) (#2677).
+    Only works on posix, since we use the unix library to check whether
+    output is to tty.  On Windows, pandoc works as before and always requires
+    an output file parameter for binary formats.
+
+  * Changed JSON output format (Jesse Rosenthal).  Previously we used
+    generically generated JSON, but this was subject to change depending
+    on the version of aeson pandoc was compiled with.  To ensure stability,
+    we switched to using manually written ToJSON and FromJSON
+    instances, and encoding the API version.  **Note:**  pandoc filter
+    libraries will need to be revised to handle the format change.
+    Here is a summary of the essential changes:
+
+    + The toplevel JSON format is now `{"pandoc-api-version" :
+      [MAJ, MIN, REV], "meta" : META, "blocks": BLOCKS}`
+      instead of `[{"unMeta": META}, [BLOCKS]]`.
+      Decoding fails if the major and minor version numbers don't
+      match.
+    + Leaf nodes no longer have an empty array for their "c" value.
+      Thus, for example, a `Space` is encoded as `{"t":"Space"}`
+      rather than `{"t":"Space","c":[]}` as before.
+
+  * Removed `tests/Tests/Arbitrary.hs` and added a `Text.Pandoc.Arbitrary`
+    module to pandoc-types (Jesse Rosenthal).  This makes it easier
+    to use QuickCheck with pandoc types outside of pandoc itself.
+
+  * Add `bracketed_spans` Markdown extension, enabled by default
+    in pandoc `markdown`.  This allows you to create a native span
+    using this syntax:  `[Here is my span]{#id .class key="val"}`.
+
+  * Added `angle_brackets_escapable` Markdown extension (#2846).
+    This is needed because github flavored Markdown has a slightly
+    different set of escapable symbols than original Markdown;
+    it includes angle brackets.
+
+  * Export `Text.Pandoc.Error` in `Text.Pandoc` [API change].
+
+  * Print highlighting-kate version in `--version`.
+
+  * `Text.Pandoc.Options`:
+
+    + `Extension` has new constructors `Ext_brackted_spans` and
+      `Ext_angle_brackets_escapable` [API change].
+    + Added `ReferenceLocation` type [API change] (Jesse Rosenthal).
+    + Added `writerReferenceLocation` field to `WriterOptions` (Jesse
+      Rosenthal).
+
+  * `--filter`:  we now check `$DATADIR/filters` for filters before
+    looking in the path (#3127, Jesse Rosenthal, thanks to Jakob
+    Voß for the idea).  Filters placed in this directory need not
+    be executable; if the extension is `.hs`, `.php`, `.pl`, `.js`,
+    or `.rb`, pandoc will run the right interpreter.
+
+  * For `--webtex`, replace deprecated Google Chart API by CodeCogs as
+    default (Kolen Cheung).
+
+  * Removed `raw_tex` extension from `markdown_mmd` defaults (Kolen Cheung).
+
+  * Execute .js filters with node (Jakob Voß).
+
+  * Textile reader:
+
+    + Support `bc..` extended code blocks (#3037).  Also, remove trailing
+      newline in code blocks (consistently with Markdown reader).
+    + Improve table parsing.  We now handle cell and row attributes, mostly
+      by skipping them.  However, alignments are now handled properly.
+      Since in pandoc alignment is per-column, not per-cell, we
+      try to devine column alignments from cell alignments.
+      Table captions are also now parsed, and textile indicators
+      for thead and tfoot no longer cause parse failure.  (However,
+      a row designated as tfoot will just be a regular row in pandoc.)
+    + Improve definition list parsing.  We now allow multiple terms
+      (which we concatenate with linebreaks).  An exponential parsing
+      bug (#3020) is also fixed.
+    + Disallow empty URL in explicit link (#3036).
+
+  * RST reader:
+
+    + Use Div instead of BlockQuote for admonitions (#3031).
+      The Div has class `admonition` and (if relevant) one of the
+      following:  `attention`, `caution`, `danger`, `error`, `hint`,
+      `important`, `note`, `tip`, `warning`.  **Note:** This will change
+      the rendering of some RST documents!  The word ("Warning", "Attention",
+      etc.) is no longer added; that must be done with CSS or a filter.
+    + A Div is now used for `sidebar` as well.
+    + Skip whitespace before note (Jesse Rosenthal, #3163).  RST requires a
+      space before a footnote marker. We discard those spaces so that footnotes
+      will be adjacent to the text that comes before it. This is in line with
+      what rst2latex does.
+    + Allow empty lines when parsing line blocks (Albert Krewinkel).
+
+  * Markdown reader:
+
+    + Allow empty lines when parsing line blocks (Albert Krewinkel).
+    + Allow attributes on autolinks (#3183, Daniele D'Orazio).
+
+  * LaTeX reader:
+
+    + More robust parsing of unknown environments (#3026).
+      We no longer fail on things like `^` inside options for tikz.
+    + Be more forgiving of non-standard characters, e.g. `^` outside of math.
+      Some custom environments give these a meaning, so we should try not to
+      fall over when we encounter them.
+    + Drop duplicate `*` in bibtexKeyChars (Albert Krewinkel)
+
+  * MediaWiki reader:
+
+    + Fix for unquoted attribute values in mediawiki tables (#3053).
+      Previously an unquoted attribute value in a table row
+      could cause parsing problems.
+    + Improved treatment of verbatim constructions (#3055).
+      Previously these yielded strings of alternating Code and Space
+      elements; we now incorporate the spaces into the Code.  Emphasis
+      etc. is still possible inside these.
+    + Properly interpret XML tags in pre environments (#3042).  They are meant
+      to be interpreted as literal text.
+
+  * EPUB reader:  don't add root path to data: URIs (#3150).
+    Thanks to @lep for the bug report and patch.
+
+  * Org reader (Albert Krewinkel):
+
+    + Preserve indentation of verse lines (#3064).  Leading spaces in verse
+      lines are converted to non-breaking spaces, so indentation is preserved.
+    + Ensure image sources are proper links.  Image sources as those in plain
+      images, image links, or figures, must be proper URIs or relative file
+      paths to be recognized as images.  This restriction is now enforced
+      for all image sources.  This also fixes the reader's usage of uncleaned
+      image sources, leading to `file:` prefixes not being deleted from
+      figure images.  Thanks to @bsag for noticing this bug.
+    + Trim verse lines properly (Albert Krewinkel).
+    + Extract meta parsing code to module.  Parsing of meta-data is well
+      separable from other block parsing tasks.  Moving into new module to
+      get small files and clearly arranged code.
+    + Read markup only for special meta keys.  Most meta-keys should be read
+      as normal string values, only a few are interpreted as marked-up text.
+    + Allow multiple, comma-separated authors.  Multiple authors can be
+      specified in the `#+AUTHOR` meta line if they are given as a
+      comma-separated list.
+    + Give precedence to later meta lines.  The last meta-line of any given
+      type is the significant line.  Previously the value of the first line
+      was kept, even if more lines of the same type were encountered.
+    + Read LaTeX_header as header-includes.  LaTeX-specific header commands
+      can be defined in `#+LaTeX_header` lines.  They are parsed as
+      format-specific inlines to ensure that they will only show up in LaTeX
+      output.
+    + Set documentclass meta from LaTeX_class.
+    + Set classoption meta from LaTeX_class_options.
+    + Read HTML_head as header-includes.  HTML-specific head content can be
+      defined in `#+HTML_head` lines.  They are parsed as format-specific
+      inlines to ensure that they will only show up in HTML output.
+    + Respect `author` export option.  The `author` option controls whether
+      the author should be included in the final markup.  Setting
+      `#+OPTIONS: author:nil` will drop the author from the final meta-data
+      output.
+    + Respect `email` export option.  The `email` option controls whether the
+      email meta-field should be included in the final markup. Setting
+      `#+OPTIONS: email:nil` will drop the email field from the final
+      meta-data output.
+    + Respect `creator` export option.  The `creator` option controls whether
+      the creator meta-field should be included in the final markup.  Setting
+      `#+OPTIONS: creator:nil` will drop the creator field from the final
+      meta-data output.  Org-mode recognizes the special value `comment` for
+      this field, causing the creator to be included in a comment.  This is
+      difficult to translate to Pandoc internals and is hence interpreted the
+      same as other truish values (i.e. the meta field is kept if it's
+      present).
+    + Respect unnumbered header property (#3095).  Sections the `unnumbered`
+      property should, as the name implies, be excluded from the automatic
+      numbering of section provided by some output formats.  The Pandoc
+      convention for this is to add an "unnumbered" class to the header.  The
+      reader treats properties as key-value pairs per default, so a special
+      case is added to translate the above property to a class instead.
+    + Allow figure with empty caption (Albert Krewinkel, #3161).
+      A `#+CAPTION` attribute before an image is enough to turn an image into
+      a figure. This wasn't the case because the `parseFromString` function,
+      which processes the caption value, would fail on empty values. Adding
+      a newline character to the caption value fixes this.
+
+  * Docx reader:
+
+    + Use XML convenience functions (Jesse Rosenthal).
+      The functions `isElem` and `elemName` (defined in Docx/Util.hs) make
+      the code a lot cleaner than the original XML.Light functions, but they
+      had been used inconsistently. This puts them in wherever applicable.
+    + Handle anchor spans with content in headers.  Previously, we would only
+      be able to figure out internal links to a header in a docx if the
+      anchor span was empty. We change that to read the inlines out of the
+      first anchor span in a header.
+    + Let headers use existing id.  Previously we always generated an id for
+      headers (since they wouldn't bring one from Docx). Now we let it use an
+      existing one if possible. This should allow us to recurs through anchor
+      spans.
+    + Use all anchor spans for header ids.  Previously we only used the first
+      anchor span to affect header ids. This allows us to use all the anchor
+      spans in a header, whether they're nested or not (#3088).
+    + Test for nested anchor spans in header.  This ensures that anchor spans
+      in header with content (or with other anchor spans inside) will resolve
+      to links to a header id properly.
+
+  * ODT reader (Hubert Plociniczak)
+
+    + Include list's starting value.  Previously the starting value of
+      the lists' items has been hardcoded to 1. In reality ODT's list
+      style definition can provide a new starting value in one of its
+      attributes.
+    + Infer caption from the text following the image.
+      Frame can contain other frames with the text boxes.
+    + Add `fig:` to title for Image with a caption (as expected
+      by pandoc's writers).
+    + Basic support for images in ODT documents.
+    + Don't duplicate text for anchors (#3143).  When creating an anchor
+      element we were adding its representation as well as the original
+      content, leading to text duplication.
+
+  * DocBook writer:
+
+    + Include an anchor element when a div or span has an id (#3102).
+      Note that DocBook does not have a class attribute, but at least this
+      provides an anchor for internal links.
+
+  * LaTeX writer:
+
+    + Don't use * for unnumbered paragraph, subparagraph.  The starred
+      variants don't exist.  This helps with part of #3058...it gets rid of
+      the spurious `*`s.  But we still have numbers on the 4th and 5th level
+      headers.
+    + Properly escape backticks in verbatim (#3121, Jesse Rosenthal).
+      Otherwise they can cause unintended ligatures like `` ?` ``.
+    + Handle NARRAOW NO-BREAK SPACE into LaTeX (Vaclav Zeman) as `\,`.
+    + Don't include `[htbp]` placement for figures (#3103, Václav Haisman).
+      This allows figure placement defaults to be changed by the user
+      in the template.
+
+  * TEI writer: remove heuristic to detect book template (Albert Krewinkel).
+    TEI doesn't have `<book>` elements but only generic `<divN>` division
+    elements. Checking the template for a trailing `</book>` is nonsensical.
+
+  * MediaWiki writer:  transform filename with underscores in images (#3052).
+    `foo bar.jpg` becomes `foo_bar.jpg`. This was already done
+    for internal links, but it also needs to happen for images.
+
+  * ICML writer: replace partial function (!!) in table handling (#3175,
+    Mauro Bieg).
+
+  * Man writer: allow section numbers that are not a single digit (#3089).
+
+  * AsciiDoc writer: avoid unnecessary use of "unconstrained" emphasis
+    (#3068).  In AsciiDoc, you must use a special form of emphasis
+    (double `__`) for intraword emphasis.  Pandoc was previously using
+    this more than necessary.
+
+  * EPUB writer:  use stringify instead of plain writer for metadata
+    (#3066).  This means that underscores won't be used for emphasis,
+    or CAPS for bold.  The metadata fields will just have unadorned
+    text.
+
+  * Docx Writer:
+
+    + Implement user-defined styles (Jesse Rosenthal).  Divs and Spans
+      with a `custom-style` key in the attributes will apply the corresponding
+      key to the contained blocks or inlines.
+    + Add ReaderT env to the docx writer (Jesse Rosenthal).
+    + Clean up and streamline RTL behavior (Jesse Rosenthal, #3140).
+      You can set `dir: rtl` in YAML metadata, or use `-M dir=rtl`
+      on the command line.  For finer-grained control, you can set
+      the `dir` attribute in Div or Span elements.
+
+  * Org writer (Albert Krewinkel):
+
+    + Remove blank line after figure caption.  Org-mode only treats an image
+      as a figure if it is directly preceded by a caption.
+    + Ensure blank line after figure.  An Org-mode figure should be surrounded
+      by blank lines.  The figure would be recognized regardless, but images
+      in the following line would unintentionally be treated as figures as
+      well.
+    + Ensure link targets are paths or URLs.  Org-mode treats links as
+      document internal searches unless the link target looks like a URL or
+      file path, either relative or absolute.  This change ensures that this
+      is always the case.
+    + Translate language identifiers.  Pandoc and Org-mode use different
+      programming language identifiers.  An additional translation between
+      those identifiers is added to avoid unexpected behavior.  This fixes a
+      problem where language specific source code would sometimes be output
+      as example code.
+    + Drop space before footnote markers (Albert Krewinkel, #3162).
+      The writer no longer adds an extra space before footnote markers.
+
+  * Markdown writer:
+
+    + Don't emit HTML for tables unless `raw_html` extension is set (#3154).
+      Emit `[TABLE]` if no suitable table formats are enabled and raw HTML
+      is disabled.
+    + Check for the `raw_html` extension before emitting a raw HTML block.
+    + Abstract out note/ref function (Jesse Rosenthal).
+    + Add ReaderT monad for environment variables (Jesse Rosenthal).
+
+  * HTML, EPUB, slidy, revealjs templates: Use `<p>` instead of `<h1>` for
+    subtitle, author, date (#3119).  Note that, as a result of this change,
+    authors may need to update CSS.
+
+  * revealjs template:  Added `notes-server` option
+    (jgm/pandoc-templates#212, Yoan Blanc).
+
+  * Beamer template:
+
+    + Restore whitespace between paragraphs. This was
+      a regression in the last release (jgm/pandoc-templates#207).
+    + Added `themeoptions` variable (Carsten Gips).
+    + Added `beamerarticle` variable.  This causes the `beamerarticle`
+      package to be loaded in beamer, to produce an article from beamer
+      slides.  (Carsten Gips)
+    + Added support for `fontfamilies` structured variable
+      (Artem Klevtsov).
+    + Added hypersetup options (Jake Zimmerman).
+
+  * LaTeX template:
+
+    + Added dummy definition for `\institute`.
+      This isn't a standard command, and we want to avoid a crash when
+      `institute` is used with the default template.
+    + Define default figure placement (Václav Haisman), since pandoc
+      no longer includes `[htbp]` for figures.  Users with custom templates
+      will want to add this. See #3103.
+    + Use footnote package to fix notes in tables (jgm/pandoc-templates#208,
+      Václav Haisman).
+
+  * Moved template compiling/rendering code to a separate library.
+    `doctemplates`.  This allows the pandoc templating system to be
+    used independently.
+
+  * Text.Pandoc.Error: Fix out of index error in `handleError`
+    (Matthew Pickering).  The fix is to not try to show the exact line when
+    it would cause an out-of-bounds error as a result of included files.
+
+  * Text.Pandoc.Shared: Add `linesToBlock` function (Albert Krewinkel).
+
+  * Text.Pandoc.Parsing.emailAddress: tighten up parsing of email
+    addresses.  Technically `**@user` is a valid email address, but if we
+    allow things like this, we get bad results in markdown flavors
+    that autolink raw email addresses (see #2940).  So we exclude a few
+    valid email addresses in order to avoid these more common bad cases.
+
+  * Text.Pandoc.PDF:  Don't crash with nonexistent image (#3100).  Instead,
+    emit the alt text, emphasized.  This accords with what the ODT writer
+    currently does.  The user will still get a warning about a nonexistent
+    image.
+
+  * Fix example in API documentation (#3176, Thomas Weißschuh).
+
+  * Tell where to get tarball in INSTALL (#3062).
+
+  * Rename README to MANUAL.txt and add GitHub-friendly README.md
+    (Albert Krewinkel, Kolen Cheung).
+
+  * Replace COPYING with Markdown version COPYING.md from GNU (Kolen Cheung).
+
+  * MANUAL.txt:
+
+    + Put note on structured vars in separate paragraph (#2148, Albert
+      Krewinkel).  Make it clearer that structured author variables require a
+      custom template
+    + Note that `--katex` works best with `html5` (#3077).
+    + Fix the LaTeX and EPUB links in manual (Morton Fox).
+    + Document `biblio-title` variable.
+
+  * Improve spacing of footnotes in `--help` output (Waldir Pimenta).
+
+  * Update KaTeX to v0.6.0 (Kolen Cheung).
+
+  * Allow latest dependencies.
+
+  * Use texmath 0.8.6.6 (#3040).
+
+  * Allow http-client 0.4.30, which is the version in stackage lts.
+    Previously we required 0.5.
+    Remove CPP conditionals for earlier versions.
+
+  * Remove support for GHC < 7.8 (Jesse Rosenthal).
+
+    + Remove Compat.Monoid.
+    + Remove an inline monad compatibility macro.
+    + Remove Text.Pandoc.Compat.Except.
+    + Remove directory compat.
+    + Change constraint on mtl.
+    + Remove unnecessary CPP condition in UTF8.
+    + Bump base lower bound to 4.7.
+    + Remove 7.6 build from .travis.yaml.
+    + Bump supported ghc version in CONTRIBUTING.md.
+    + Add note about GHC version support to INSTALL.
+    + Remove GHC 7.6 from list of tested versions (Albert Krewinkel).
+    + Remove TagSoup compat.
+    + Add EOL note to time compat module.  Because time 1.4 is a boot library
+      for GHC 7.8, we will support the compatibility module as long as we
+      support 7.8. But we should be clear about when we will no longer need
+      it.
+    + Remove blaze-html CPP conditional.
+    + Remove unnecessary CPP in custom Prelude.
+
+## pandoc 1.17.2 (2016-07-17)
+
+  * Added Zim Wiki writer, template and tests. `zimwiki` is now
+    a valid output format. (Alex Ivkin)
+
+  * Changed email-obfuscation default to no obfuscation (#2988).
+    + `writerEmailObfuscation` in `defaultWriterOptions` is now
+      `NoObfuscation`.
+    + the default for the command-line `--email-obfuscation` option is
+      now `none`.
+
+  * Docbook writer: Declare xlink namespace in Docbook5 output (Ivo Clarysse).
+
+  * Org writer:
+
+    + Support arbitrary raw inlines (Albert Krewinkel).
+      Org mode allows arbitrary raw inlines ("export snippets" in Emacs
+      parlance) to be included as `@@format:raw foreign format text@@`.
+    + Improve Div handling (Albert Krewinkel).  Div blocks handling is
+      changed to make the output look more like idiomatic org mode:
+        - Div-wrapped content is output as-is if the div's attribute is the
+          null attribute.
+        - Div containers with an id but neither classes nor key-value pairs
+          are unwrapped and the id is added as an anchor.
+        - Divs with classes associated with greater block elements are
+          wrapped in a `#+BEGIN`...`#+END` block.
+        - The old behavior for Divs with more complex attributes is kept.
+
+  * HTML writer:  Better support for raw LaTeX environments (#2758).
+    Previously we just passed all raw TeX through when MathJax
+    was used for HTML math.  This passed through too much.
+    With this patch, only raw LaTeX environments that MathJax
+    can handle get passed through.
+    This patch also causes raw LaTeX environments to be treated
+    as math, when possible, with MathML and WebTeX output.
+
+  * Markdown writer:  use raw HTML for simple, pipe tables with linebreaks
+    (#2993).  Markdown line breaks involve a newline, and simple and pipe
+    tables can't contain one.
+
+  * Make --webtex work with the Markdown writer (#1177).
+    This is a convenient option for people using
+    websites whose Markdown flavors don't provide for math.
+
+  * Docx writer:
+
+    + Set paragraph to FirstPara after display math (Jesse Rosenthal).
+      We treat display math like block quotes, and apply FirstParagraph style
+      to paragraphs that follow them. These can be styled as the user
+      wishes. (But, when the user is using indentation, this allows for
+      paragraphs to continue after display math without indentation.)
+    + Use actual creation time as doc prop (Jesse Rosenthal).
+      Previously, we had used the user-supplied date, if available, for Word's
+      document creation metadata. This could lead to weird results, as in
+      cases where the user post-dates a document (so the modification might be
+      prior to the creation). Here we use the actual computer time to set the
+      document creation.
+
+  * LaTeX writer:
+
+    + Don't URI-escape image source (#2825).  Usually this is a local file,
+      and replacing spaces with `%20` ruins things.
+    + Allow 'standout' as a beamer frame option (#3007).
+      `## Slide title {.standout}`.
+
+  * RST reader: Fixed links with no explicit link text.  The link
+    `` `<foo>`_ `` should have `foo` as both its link text and its URL.
+    See RST spec at <http://docutils.sourceforge.net/docs/ref/rst/restructuredtext.html#embedded-uris-and-aliases>
+    Closes Debian #828167 -- reported by Christian Heller.
+
+  * Textile reader:
+
+    + Fixed attributes (#2984).  Attributes can't be followed by
+      a space.  So, `_(class)emph_` but `_(noclass) emph_`.
+    + Fixed exponential parsing bug (#3020).
+    + Fix overly aggressive interpretation as images (#2998).
+      Spaces are not allowed in the image URL in textile.
+
+  * LaTeX reader:
+
+    + Fix `\cite` so it is a NormalCitation not AuthorInText.
+    + Strip off double quotes around image source if present (#2825).
+      Avoids interpreting these as part of the literal filename.
+
+  * Org reader:
+
+    + Add semicolon to list of special chars (Albert Krewinkel)
+      Semicolons are used as special characters in citations syntax.  This
+      ensures the correct parsing of Pandoc-style citations: `[prefix; @key;
+      suffix]`.  Previously, parsing would have failed unless there was a space
+      or other special character as the last <prefix> character.
+    + Add support for "Berkeley-style" cites (Albert Krewinkel, #1978).
+      A specification for an official Org-mode citation syntax was drafted by
+      Richard Lawrence and enhanced with the help of others on the orgmode
+      mailing list.  Basic support for this citation style is added to the
+      reader.
+    + Support arbitrary raw inlines (Albert Krewinkel).
+      Org mode allows arbitrary raw inlines ("export snippets" in Emacs
+      parlance) to be included as `@@format:raw foreign format text@@`.
+    + Remove partial functions (Albert Krewinkel, #2991).
+      Partial functions like `head` lead to avoidable errors and should be
+      avoided.  They are replaced with total functions.
+    + Support figure labels (Albert Krewinkel, #2496, #2999).
+      Figure labels given as `#+LABEL: thelabel` are used as the ID of the
+      respective image.  This allows e.g. the LaTeX to add proper `\label`
+      markup.
+    + Improve tag and properties type safety (Albert Krewinkel).
+      Specific newtype definitions are used to replace stringly typing of tags
+      and properties.  Type safety is increased while readability is improved.
+    + Parse as headlines, convert to blocks (Albert Krewinkel).
+      Emacs org-mode is based on outline-mode, which treats documents as trees
+      with headlines are nodes.  The reader is refactored to parse into a
+      similar tree structure.  This simplifies transformations acting on
+      document (sub-)trees.
+    * Refactor comment tree handling (Albert Krewinkel).
+      Comment trees were handled after parsing, as pattern matching on lists
+      is easier than matching on sequences.  The new method of reading
+      documents as trees allows for more elegant subtree removal.
+    * Support archived trees export options (Albert Krewinkel).
+      Handling of archived trees can be modified using the `arch` option.
+      Archived trees are either dropped, exported completely, or collapsed to
+      include just the header when the `arch` option is nil, non-nil, or
+      `headline`, respectively.
+    * Put export setting parser into module (Albert Krewinkel).
+      Export option parsing is distinct enough from general block parsing to
+      justify putting it into a separate module.
+    * Support headline levels export setting (Albert Krewinkel).
+      The depths of headlines can be modified using the `H` option.  Deeper
+      headlines will be converted to lists.
+    * Replace ugly code with view pattern (Albert Krewinkel).
+      Some less-than-smart code required a pragma switching of overlapping
+      pattern warnings in order to compile seamlessly.  Using view patterns
+      makes the code easier to read and also doesn't require overlapping
+      pattern checks to be disabled.
+    * Fix parsing of verbatim inlines (Albert Krewinkel, #3016).
+      Org rules for allowed characters before or after markup chars were not
+      checked for verbatim text.  This resultet in wrong parsing outcomes of
+      if the verbatim text contained e.g. space enclosed markup characters as
+      part of the text (`=is_substr = True=`).  Forcing the parser to update
+      the positions of allowed/forbidden markup border characters fixes this.
+
+  * LaTeX template: fix for obscure hyperref/xelatex issue.
+    Here's a minimal case:
+
+        \documentclass[]{article}
+        \usepackage{hyperref}
+        \begin{document}
+        \section{\%á}
+        \end{document}
+
+    Without this change, this fails on the second invocation of xelatex.
+    This affects inputs this like `# %á` with pdf output via xelatex.
+
+  * trypandoc:  call results 'html' instead of 'result'.
+    This is for better compatibility with babelmark2.
+
+  * Document MultiMarkdown as input/output format (Albert Krewinkel, #2973).
+    MultiMarkdown was only mentioned as a supported Markdown dialect but not
+    as a possible input or output format.  A brief mention is added
+    everywhere the other supported markdown dialects are mentioned.
+
+  * Document Org mode as a format containing raw HTML (Albert Krewinkel)
+    Raw HTML is kept when the output format is Emacs Org mode.
+
+  * Implement `RawInline` and `RawBlock` in sample lua custom writer (#2985).
+
+  * Text.Pandoc.Shared:
+
+    + Introduce blocksToInlines function (Jesse Rosenthal).
+      This is a lossy function for converting `[Block] -> [Inline]`. Its main
+      use, at the moment, is for docx comments, which can contain arbitrary
+      blocks (except for footnotes), but which will be converted to spans.
+      This is, at the moment, pretty useless for everything but the basic
+      `Para` and `Plain` comments. It can be improved, but the docx reader
+      should probably emit a warning if the comment contains more than this.
+    + Add BlockQuote to blocksToInlines (Jesse Rosenthal).
+    + Add further formats for `normalizeDate` (Jesse Rosenthal).
+      We want to avoid illegal dates -- in particular years with greater than
+      four digits. We attempt to parse series of digits first as `%Y%m%d`, then
+      `%Y%m`, and finally `%Y`.
+    + `normalizeDate` should reject illegal years (Jesse Rosenthal).
+      We only allow years between 1601 and 9999, inclusive. The ISO 8601
+      actually says that years are supposed to start with 1583, but MS Word
+      only allows 1601-9999. This should stop corrupted word files if the date
+      is out of that range, or is parsed incorrectly.
+    + Improve year sanity check in normalizeDate (Jesse Rosenthal).
+      Previously we parsed a list of dates, took the first one, and then
+      tested its year range. That meant that if the first one failed, we
+      returned nothing, regardless of what the others did. Now we test for
+      sanity before running `msum` over the list of Maybe values. Anything
+      failing the test will be Nothing, so will not be a candidate.
+
+  * Docx reader:
+
+    + Add simple comment functionality. (Jesse Rosenthal).
+      This adds simple track-changes comment parsing to the docx reader. It is
+      turned on with `--track-changes=all`. All comments are converted to
+      inlines, which can list some information. In the future a warning will be
+      added for comments with formatting that seems like it will be excessively
+      denatured.  Note that comments can extend across blocks. For that reason
+      there are two spans: `comment-start` and `comment-end`.  `comment-start`
+      will contain the comment. `comment-end` will always be empty.  The two
+      will be associated by a numeric id.
+    + Enable warnings in top-level reader (Jesse Rosenthal).
+      Previously we had only allowed for warnings in the parser. Now we allow
+      for them in the `Docx.hs` as well. The warnings are simply concatenated.
+    + Add warning for advanced comment formatting. (Jesse Rosenthal).
+      We can't guarantee we'll convert every comment correctly, though we'll
+      do the best we can. This warns if the comment includes something other
+      than Para or Plain.
+    + Add tests for warnings. (Jesse Rosenthal).
+    + Add tests for comments (Jesse Rosenthal).
+      We test for comments, using all track-changes options. Note that we
+      should only output comments if `--track-changes=all`. We also test for
+      emitting warnings if there is complicated formatting.
+
+  * README: update to include track-changes comments. (Jesse Rosenthal)
+
+  * Improved Windows installer - don't ignore properties set on command-line.
+    See #2708.  Needs testing to see if this resolves the issue.
+    Thanks to @nkalvi.
+
+  * Process markdown extensions on command line in L->R order (#2995).
+    Previously they were processed, very unintuitively, in R->L
+    order, so that `markdown-tex_math_dollars+tex_math_dollars`
+    had `tex_math_dollars` disabled.
+
+  * Added `secnumdepth` variable to LaTeX template (#2920).
+
+  * Include table of contents in README.html in Windows package.
+
+  * Writers: treat SoftBreak as space for stripping (Jesse Rosenthal)
+    In Writers.Shared, we strip leading and trailing spaces for display
+    math. Since SoftBreak's are treated as spaces, we should strip those
+    too.
+
+  * beamer, latex templates:  pass biblatexoptions directly in package load.
+    This allows runtime optinos to be used.  Fixes jgm/pandoc-citeproc#201
+
+  * CPP workaround for deprecation of `parseUrl` in http-client.
+
+  * Removed some redundant class constraints.
+
+  * make_oxs_package.sh - use OSX env variable.
+
+  * Added `winpkg` target to Makefile.  This downloads the windows package
+    from appveyor and signs it using the key.
+
+  * Document Org mode as a format containing raw TeX (Albert Krewinkel).
+    Raw TeX is kept verbatim when the output format is Emacs Org mode.
+
+  * Support math with haddock-library >= 1.4.
+
+  * Removed `-rtsopts` from library stanza.  It has no effect, and Hackage
+    wouldn't accept the package.
+
+  * Update library dependency versions.
+
+## pandoc 1.17.1 (2016-06-04)
+
+  * New output format: `docbook5` (Ivo Clarysse).
+
+  * `Text.Pandoc.Options`: Add `writerDocBook5` to `WriterOptions`
+    (API change).
+
+  * Org writer:
+
+    + Add :PROPERTIES: drawer support (Albert Krewinkel, #1962).
+      This allows header attributes to be added to org documents in the form
+      of `:PROPERTIES:` drawers.  All available attributes are stored as
+      key/value pairs.  This reflects the way the org reader handles
+      `:PROPERTIES:` blocks.
+    + Add drawer capability (Carlos Sosa).  For the implementation of the
+      Drawer element in the Org Writer, we make use of a generic Block
+      container with attributes.  The presence of a `drawer` class defines
+      that the `Div` constructor is a drawer. The first class defines the
+      drawer name to use.  The key-value list in the attributes defines
+      the keys to add inside the Drawer.  Lastly, the list of Block elements
+      contains miscellaneous blocks elements to add inside of the Drawer.
+    + Use `CUSTOM_ID` in properties (Albert Krewinkel).  The `ID` property is
+      reserved for internal use by Org-mode and should not be used.
+      The `CUSTOM_ID` property is to be used instead, it is converted to the
+      `ID` property for certain export format.
+
+  * LaTeX writer:
+
+    + Ignore `--incremental` unless output format is beamer (#2843).
+    + Fix polyglossia to babel env mapping (Mauro Bieg, #2728).
+      Allow for optional argument in square brackets.
+    + Recognize `la-x-classic` as Classical Latin (Andrew Dunning).
+      This allows one to access the hyphenation patterns in CTAN's
+      hyph-utf8.
+    + Add missing languages from hyph-utf8 (Andrew Dunning).
+    + Improve use of `\strut` with `\minipage` inside tables
+      (Jose Luis Duran).  This improves spacing in multiline
+      tables.
+    + Use `{}` around options containing special chars (#2892).
+    + Avoid lazy `foldl`.
+    + Don't escape underscore in labels (#2921).  Previously they were
+      escaped as `ux5f`.
+    + brazilian -> brazil for polyglossia (#2953).
+
+  * HTML writer: Ensure mathjax link is added when math appears in footnote
+    (#2881).  Previously if a document only had math in a footnote, the
+    MathJax link would not be added.
+
+  * EPUB writer: set `navpage` variable on nav page.
+    This allows templates to treat it differently.
+
+  * DocBook writer:
+
+    + Use docbook5 if `writerDocbook5` is set (Ivo Clarysse).
+    + Properly handle `ulink`/`link` (Ivo Clarysse).
+
+  * EPUB reader:
+
+    + Unescape URIs in spine (#2924).
+    + EPUB reader:  normalise link id (Mauro Bieg).
+
+  * Docx Reader:
+
+    + Parse `moveTo` and `moveFrom` (Jesse Rosenthal).
+      `moveTo` and `moveFrom` are track-changes tags that are used when a
+      block of text is moved in the document. We now recognize these tags and
+      treat them the same as `insert` and `delete`, respectively. So,
+      `--track-changes=accept` will show the moved version, while
+      `--track-changes=reject` will show the original version.
+    + Tests for track-changes moving (Jesse Rosenthal).
+
+  * ODT, EPUB, Docx readers: throw `PandocError` on unzip failure
+    (Jesse Rosenthal) Previously, `readDocx`, `readEPUB`, and `readOdt`
+    would error out if zip-archive failed. We change the archive extraction
+    step from `toArchive` to `toArchiveOrFail`, which returns an Either value.
+
+  * Markdown, HTML readers:  be more forgiving about unescaped `&` in
+    HTML (#2410).  We are now more forgiving about parsing invalid HTML with
+    unescaped `&` as raw HTML.  (Previously any unescaped `&`
+    would cause pandoc not to recognize the string as raw HTML.)
+
+  * Markdown reader:
+
+    + Fix pandoc title blocks with lines ending in 2 spaces (#2799).
+    + Added `-s` to markdown-reader-more test.
+
+  * HTML reader: fixed bug in `pClose`.  This caused exponential parsing
+    behavior in documnets with unclosed tags in `dl`, `dd`, `dt`.
+
+  * MediaWiki reader: Allow spaces before `!` in MediaWiki table header
+    (roblabla).
+
+  * RST reader: Support `:class:` option for code block in RST reader
+    (Sidharth Kapur).
+
+  * Org reader (all Albert Krewinkel, except where noted otherwise):
+
+    + Stop padding short table rows.
+      Emacs Org-mode doesn't add any padding to table rows.  The first
+      row (header or first body row) is used to determine the column count,
+      no other magic is performed.
+    + Refactor rows-to-table conversion.  This refactors
+      the codes conversing a list table lines to an org table ADT.
+      The old code was simplified and is now slightly less ugly.
+    + Fix handling of empty table cells, rows (Albert Krewinkel, #2616).
+      This fixes Org mode parsing of some corner cases regarding empty cells
+      and rows.  Empty cells weren't parsed correctly, e.g. `|||` should be
+      two empty cells, but would be parsed as a single cell containing a pipe
+      character.  Empty rows where parsed as alignment rows and dropped from
+      the output.
+    + Fix spacing after LaTeX-style symbols.
+      The org-reader was dropping space after unescaped LaTeX-style symbol
+      commands: `\ForAll \Auml` resulted in `∀Ä` but should give `∀ Ä`
+      instead.  This seems to be because the LaTeX-reader treats the
+      command-terminating space as part of the command.  Dropping the trailing
+      space from the symbol-command fixes this issue.
+    + Print empty table rows.  Empty table rows should not
+      be dropped from the output, so row-height is always set to be at least 1.
+    + Move parser state into separate module.
+      The org reader code has become large and confusing.  Extracting smaller
+      parts into submodules should help to clean things up.
+    + Add support for sub/superscript export options.
+      Org-mode allows to specify export settings via `#+OPTIONS` lines.
+      Disabling simple sub- and superscripts is one of these export options,
+      this options is now supported.
+    + Support special strings export option Parsing of special strings
+      (like `...` as ellipsis or `--` as en dash) can be toggled using the `-`
+      option.
+    + Support emphasized text export option.  Parsing of emphasized text can
+      be toggled using the `*` option.  This influences parsing of text marked
+      as emphasized, strong, strikeout, and underline.  Parsing of inline math,
+      code, and verbatim text is not affected by this option.
+    + Support smart quotes export option.  Reading of smart quotes can be
+      toggled using the `'` option.
+    + Parse but ignore export options. All known export options are parsed
+      but ignored.
+    + Refactor block attribute handling.  A parser state attribute was used
+      to keep track of block attributes defined in meta-lines.  Global state
+      is undesirable, so block attributes are no longer saved as part of the
+      parser state.  Old functions and the respective part of the parser state
+      are removed.
+    + Use custom `anyLine`.  Additional state changes need to be made after
+      a newline is parsed, otherwise markup may not be recognized correctly.
+      This fixes a bug where markup after certain block-types would not be
+      recognized.
+    + Add support for `ATTR_HTML` attributes (#1906).
+      Arbitrary key-value pairs can be added to some block types using a
+      `#+ATTR_HTML` line before the block.  Emacs Org-mode only includes these
+      when exporting to HTML, but since we cannot make this distinction here,
+      the attributes are always added.  The functionality is now supported
+      for figures.
+    + Add `:PROPERTIES:` drawer support (#1877).
+      Headers can have optional `:PROPERTIES:` drawers associated with them.
+      These drawers contain key/value pairs like the header's `id`.  The
+      reader adds all listed pairs to the header's attributes; `id` and
+      `class` attributes are handled specially to match the way `Attr` are
+      defined.  This also changes behavior of how drawers of unknown type
+      are handled.  Instead of including all unknown drawers, those are not
+      read/exported, thereby matching current Emacs behavior.
+    + Use `CUSTOM_ID` in properties.  See above on Org writer changes.
+    + Respect drawer export setting.  The `d` export option can be used
+      to control which drawers are exported and which are discarded.
+      Basic support for this option is added here.
+    + Ignore leading space in org code blocks (Emanuel Evans, #2862).
+      Also fix up tab handling for leading whitespace in code blocks.
+    + Support new syntax for export blocks.  Org-mode version 9
+      uses a new syntax for export blocks.  Instead of `#+BEGIN_<FORMAT>`,
+      where `<FORMAT>` is the format of the block's content, the new
+      format uses `#+BEGIN_export <FORMAT>` instead.  Both types are
+      supported.
+    + Refactor `BEGIN...END` block parsing.
+    + Fix handling of whitespace in blocks, allowing content to be indented
+      less then the block header.
+    + Support org-ref style citations.  The *org-ref* package is an
+      org-mode extension commonly used to manage citations in org
+      documents.  Basic support for the `cite:citeKey` and
+      `[[cite:citeKey][prefix text::suffix text]]` syntax is added.
+    + Split code into separate modules, making for cleaner code and
+      better decoupling.
+
+  * Added `docbook5` template.
+
+  * `--mathjax` improvements:
+
+    + Use new CommonHTML output for MathJax (updated default MathJax URL,
+      #2858).
+    + Change default mathjax setup to use `TeX-AMS_CHTML` configuration.
+      This is designed for cases where the input is always TeX and maximal
+      conformity with TeX is desired.  It seems to be smaller and load faster
+      than what we used before.  See #2858.
+    + Load the full MathJax config to maximize loading speed (KolenCheung).
+
+  * Bumped upper version bounds to allow use of latest packages
+    and compilation with ghc 8.
+
+  * Require texmath 0.8.6.2.  Closes several texmath-related bugs (#2775,
+    #2310, #2310, #2824).  This fixes behavior of roots, e.g.
+    `\sqrt[3]{x}`, and issues with sub/superscript positioning
+    and matrix column alignment in docx.
+
+  * README:
+
+    + Clarified documentation of `implicit_header_references` (#2904).
+    + Improved documentation of `--columns` option.
+
+  * Added appveyor setup, with artefacts (Jan Schulz).
+
+  * stack.yaml versions: Use proper flags used for texmath, pandoc-citeproc.
+
+  * LaTeX template: support for custom font families (vladipus).
+    Needed for correct polyglossia operation with Cyrillic fonts and perhaps
+    can find some other usages.  Example usage in YAML metadata:
+
+          fontfamilies:
+          - name: \cyrillicfont
+            font: Liberation Serif
+          - name: \cyrillicfonttt
+            options: Scale=MatchLowercase
+            font: Liberation
+
+  * Create unsigned msi as build artifact in appveyor build.
+
+  * On travis, test with ghc 8.0.1; drop testing for ghc 7.4.1.
+
+
+
+## pandoc 1.17.0.3 (2016-03-24)
+
+  * LaTeX writer: Fixed position of label in figures (#2813).
+    Previously the label wasn't in the right place, and `\ref`
+    wouldn't work properly.
+  * Added .tei test files to pandoc.cabal so they'll be included
+    in tarball (#2811).
+  * Updated copyright dates.
+
+## pandoc 1.17.0.2 (2016-03-23)
+
+  * Fixed serious regression in `htmlInBalanced`, which caused
+    newlines to be omitted in some raw HTML blocks in Markdown
+    (#2804).
+
+## pandoc 1.17.0.1 (2016-03-21)
+
+  * File scope is no longer used when there are no input files (i.e.,
+    when input comes from stdin).  Previously file scope was triggered
+    when the `json` reader was specified and input came from `stdin`,
+    and this caused no output to be produced.  (Fix due to Jesse Rosenthal;
+    thanks to Fedor Sheremetyev for calling the bug to our attention.)
+  * Improved documentation of templates (#2797).
+
+## pandoc 1.17 (2016-03-20)
+
+  * Added `--file-scope` option (Jesse Rosenthal).
+    By default pandoc operates on multiple files by first concatenating
+    them (around extra line breaks) and then processing the joined file. So
+    it only parses a multi-file document at the document scope. This has the
+    benefit that footnotes and links can be in different files, but for
+    some purposes it is useful to parse the individual files first
+    and then combine their outputs (e.g. when the files use footnotes
+    or links with the same labels).  The `--file-scope` option causes
+    pandoc to parse the files first, and then combine the parsed output,
+    instead of combining before parsing. `--file-scope` is selected
+    automatically for binary input files (which cannot be concatenated)
+    and for pandoc json.
+
+  * Add TEI Writer (Chris Forster) and `tei` output format.
+
+  * Added a general `ByteStringReader` with warnings, used by the docx
+    reader (API change, Jesse Rosenthal).
+
+  * Add `readDocxWithWarnings` (API change, Jesse Rosenthal).
+
+  * Changed type of `Shared.uniqueIdent` argument from
+    `[String]` to `Set String`.  This avoids performance problems in documents
+    with many identically named headers (API change, #2671).
+
+  * Removed `tex_math_single_backslash` from `markdown_github` options
+    (#2707).
+
+  * Make language extensions as well as full language names
+    trigger syntax highlighting.  For example, `py` will now work as
+    well as `python` (jgm/highlighting-kate#83).
+
+  * Added `institute` variable to latex, beamer templates (Fraser
+    Tweedale, Josef Svenningsson).
+
+  * Docx reader (Jesse Rosenthal):
+
+    + Handle alternate content.  Some word functions (especially graphics)
+      give various choices for content so there can be backwards compatibility.
+    + Don't turn numbered headers into lists.
+    + Docx Reader: Add state to the parser, for warnings
+    + Update feature checklist in source code.
+    + Get rid of `Modifiable` typeclass.
+    + Add tests for adjacent hyperlinks.
+    + Add a "Link" modifier to `Reducible`. We want to make sure that
+      links have their spaces removed, and are appropriately smushed
+      together (#2689).
+
+  * HTML reader:
+
+    + Fixed behavior of base tag (#2777).
+      If the base path does not end with slash, the last component
+      will be replaced.  E.g. base = `http://example.com/foo`
+      combines with `bar.html` to give `http://example.com/bar.html`.
+      If the href begins with a slash, the whole path of the base
+      is replaced.  E.g. base = `http://example.com/foo/` combines
+      with `/bar.html` to give `http://example.com/bar.html`.
+    + Rewrote `htmlInBalanced`.  This version avoids an exponential
+      performance problem with `<script>` tags, and it should be faster
+      in general (#2730).
+    + Properly handle an empty cell in a simple table (#2718).
+    + Handle multiple `<meta>` tags with same name.  Put them in a list
+      in the metadata so they are all preserved, rather than (as before)
+      throwing out all but one..
+
+  * Markdown reader:
+
+    + Improved pipe table parsing (#2765).
+    + Allow `+` separators in pipe table cells.  We already allowed
+      them in the header, but not in the body rows, for some reason.
+      This gives compatibility with org-mode tables.
+    + Don't cross line boundary parsing pipe table row.
+      Previously an Emph element could be parsed across the newline
+      at the end of the pipe table row.
+    + Use `htmlInBalanced` for `rawVerbatimBlock`, for better
+      performance (#2730).
+    + Fixed bug with smart quotes around tex math.
+
+  * LaTeX reader:
+
+    + Handle interior `$` characters in math (#2743).  For example,
+      `$$\hbox{$i$}$$`.
+    + `inlineCommand` now gobbles an empty `{}` after any command (#2687).
+      This gives better results when people write e.g. `\TeX{}` in Markdown.
+    + Properly handle LaTeX "math" environment as inline math (#2171).
+
+  * Textile reader: Support `>`, `<`, `=`, `<>` text alignment attributes.
+    Closes #2674.
+
+  * Org reader (Albert Krewinkel):
+
+    + Prefix even empty figure names with "fig:" (#2643).  The
+      convention used by pandoc for figures is to mark them by prefixing
+      the name with `fig:`.  The org reader failed to do this if a figure
+      had no name.
+    + Refactor link-target processing (#2684).
+
+  * ConTeXt writer: Fix whitespace at line beginning in line blocks (#2744).
+    Thanks to @c-foster.
+
+  * HTML writer: Don't include alignment attribute for default table columns.
+    Previously these were given "left" alignment.  Better to leave off
+    alignment attributes altogether (#2694).
+
+  * Markdown writer: Use hyphens for YAML metadata block bottom line, for
+    better compatibility with other Markdown flavors (Henrik Tramberend).
+
+  * LaTeX writer:
+
+    + Use image identifier to create a label and hypertarget for
+      figures (Mauro Bieg).
+    + Avoid double toprule in headerless table with caption (#2742).
+    + Clean up options parser (Jesse Rosenthal).
+    + Treat `memoir` template with `article` option as article, instead
+      of treating all `memoir` templates as books.
+    + Allow more flexible table alignment (Henrik Tramberend, #2665).
+      New default is not to include `[c]` option (which is the default
+      anyway if no positioning is specified).  Now LaTeX emplates can
+      control the overall table alignment in a document by setting the
+      longtable length variables `LTleft` and `LTright`.  For example,
+      `\setlength\LTleft\parindent\setlength\LTright\fill`
+      will create left-aligned tables that respect paragraph indentation.
+
+  * Docx writer: Handle image alt text (#2754, Mauro Bieg).
+
+  * Org writer - pass through RawInline with format "org".
+
+  * DokuWiki writer: use `$$` for display math.
+
+  * Custom writer: Pass attributes parameter to CaptionedImage (#2697).
+
+  * Make protocol-relative URIs work again (#2737).
+
+  * make_osx_package.sh:  Use env variable for developer id certs.
+
+  * Raise `tagsoup` lower bound to 0.13.7 to fix entity-related
+    problems (#2734).
+
+  * Allow `zip-archive` 0.3.
+
+  * Allow `aeson` 0.11.
+
+## pandoc 1.16.0.2 (2016-01-12)
+
+  * Depend on deepseq rather than deepseq-generics (fpco/stackage#1096).
+
+  * Fixed regression in latex smart quote parsing (#2645).
+    In cases where a match was not found for a quote, everything
+    from the open quote to the end of the paragraph was being dropped.
+
+## pandoc 1.16.0.1 (2016-01-10)
+
+  * Fixed regression with `--latex-engine` (#2618). In 1.16
+    `--latex-engine` raises an error if a full path is given.
+
+  * Org reader: Fix function dropping subtrees tagged `:noexport`
+    (Albert Krewinkel, #2628):
+
+  * Markdown reader: renormalize table column widths if they exceed 100%
+    (#2626).
+
+  * Textile reader:  don't allow block HTML tags in inline contexts.
+    The reader previously did allow this, following redcloth,
+    which happily parses
+
+        Html blocks can be <div>inlined</div> as well.
+
+    as
+
+        <p>Html blocks can be <div>inlined</div> as well.</p>
+
+    This is invalid HTML.  The above sample now produces;
+
+        <p>Html blocks can be</p>
+        <div>
+        <p>inlined</p>
+        </div>
+        <p>as well.</p>
+
+  * Improved default template lookup for custom lua scripts (#2625).
+    Previously, if you tried to do `pandoc -s -t /path/to/lua/script.lua`,
+    pandoc would look for the template in
+    `~/.pandoc/templates/default./path/to/lua/script.lua`.
+    With this change it will look in the more reasonable
+    `~/.pandoc/templates/default.script.lua`.  This makes it possible to
+    store default templates for custom writers.
+
+  * RST, Markdown writers: Fixed rendering of grid tables with blank rows
+    (#2615).
+
+  * LaTeX writer: restore old treatment of Span (#2624).  A Span is
+    now rendered with surrounding `{}`, as it was before 1.16.
+
+  * Entity handling fixes: improved handling of entities like
+    `&lang;` that require a trailing semicolon.  Allow uppercase
+    `x` in numerical hexadecimal character references, working
+    around a tagsoup bug.
+
+  * `stack.yaml` - use lts-4.0, but with older aeson to avoid excessive
+    memory use on compile.  With aeson 0.10 we were getting an out of
+    memory error on a 2GB Ubuntu 64-bit VM.
+
+  * Improved deb package creation script. Made `DPKGVER` work.
+    Renamed `COMMIT` to `TREE`.  You should now be able to do
+    `TREE=1.16.0.1 DPKGVER=2 make deb`.
+
+
+## pandoc 1.16 (2016-01-02)
+
+  * Added `Attr` field to `Link` and `Image` (Mauro Bieg, #261, API change).
+
+    + Added syntax for link and image attributes to pandoc's Markdown.
+    + Updated readers and writers to use link and image attributes
+      when appropriate.
+    + Support image attributes in Docx, Textile, RST readers.
+
+  * Renamed link attribute extensions.  The old `link_attributes` is
+    now `mmd_link_attributes`, and `link_attributes` now enables the
+    new pandoc-style link and image attributes (API change).
+    Note: this change could break some existing workflows.
+
+  * Implemented `SoftBreak` and new `--wrap` option (#1701, API change).
+    Added threefold wrapping option.
+
+    + Command line option: deprecated `--no-wrap`, added
+      `--wrap=[auto|none|preserve]`
+    + Added `WrapOption`, exported from `Text.Pandoc.Options`
+    + Changed type of `writerWrapText` in `WriterOptions` from
+      `Bool` to `WrapOption`.
+    + Modified `Text.Pandoc.Shared` functions to allow `SoftBreak`.
+    + Supported `SoftBreak` in readers and writers.
+
+  * Text.Pandoc.Options:  Added `writerDpi` to `WriterOptions` (API
+    change, Mauro Bieg).
+
+  * Added `--dpi` command-line option (Mauro Bieg).
+
+  * Rationalized behavior of `--no-tex-ligatures` and `--smart` (#2541).
+    This change makes `--no-tex-ligatures` affect the LaTeX reader
+    as well as the LaTeX and ConTeXt writers.  If it is used,
+    the LaTeX reader will parse characters `` ` ``, `'`, and `-`
+    literally, rather than parsing ligatures for quotation marks
+    and dashes.  And the LaTeX writer will print unicode quotation
+    mark and dash characters literally, rather than converting
+    them to the standard ASCII ligatures.  Note that `--smart` has
+    no effect on the LaTeX reader.  `--smart` is still the default
+    for all input formats when LaTeX or ConTeXt is the output format,
+    *unless* `--no-tex-ligatures` is used.
+
+    Some examples to illustrate the logic:
+
+    ```
+    % echo "'hi'" | pandoc -t latex
+    `hi'
+    % echo "'hi'" | pandoc -t latex --no-tex-ligatures
+    'hi'
+    % echo "'hi'" | pandoc -t latex --no-tex-ligatures --smart
+    ‘hi’
+    % echo "'hi'" | pandoc -f latex --no-tex-ligatures
+    <p>'hi'</p>
+    % echo "'hi'" | pandoc -f latex
+    <p>’hi’</p>
+    ```
+
+  * Removed deprecated options `--offline` and `--html5`.
+
+  * Fixed language code for Czech (`cs` not `cz`) (#2597).
+
+  * Implemented `east_asian_line_breaks` extension (#2586).
+    In `Text.Pandoc.Options`, added `Ext_east_asian_line_breaks` constructor
+    to `Extension` (API change).  This extension is like
+    `ignore_line_breaks`, but smarter -- it only ignores line breaks
+    between two East Asian wide characters.  This makes it better suited
+    for writing with a mix of East Asian and non-East Asian scripts.
+
+  * Added support for PDF creation via `wkhtmltopdf`.
+    To use this: `pandoc -t html5 -o result.pdf` (and add `--mathjax`
+    if you have math.) Margins can be set using the variables
+    `margin-top`, `margin-bottom`, `margin-left`, `margin-right`.
+    Other styling can be done through CSS.
+
+  * Fixed cite key parsing regression (jgm/pandoc-citeproc#201).
+    We were capturing final colons as in `[@foo: bar]`; the citation id
+    was being parsed as `@foo:`.
+
+  * ICML writer:
+
+    + Fixed image syntax for local files (#2589).
+    + Changed type of `writeICML` (Mauro Bieg).
+      API change:  It is now `WriterOptions -> Pandoc -> IO String`.
+      Also handle new image attributes.
+    + Intersperse line breaks instead of appending them to
+      every `ParagraphStyleRange` (Mauro Bieg, #2501).
+    + Add `Cite` style to citations (Mauro Bieg).
+    + Added figure handling (#2590, Mauro Bieg).
+    + Better handling of math.  Instead of just printing the raw tex,
+      we now try to fake it with unicode characters.
+
+  * HTML writer: Include `example` class for example lists (#2524).
+
+  * ODT/OpenDocument writer: improved image attributes (Mauro Bieg).
+
+    + Support for percentage widths/heights
+    + Use `Attr` instead of title to get dimensions from ODT walker
+      to `writeOpenDocument`.
+
+  * AsciiDoc writer:
+
+    + Support anchors in spans and divs with id elements
+      (jgm/pandoc-citeproc#143).
+    + Fixed code blocks (#1861).
+
+  * Haddock writer:  omit formatting inside links, which isn't supported
+    by Haddock (#2515).
+
+  * MediaWiki writer:  Fixed spacing issues in table cells.
+
+    + Start cell on new line unless it's a single Para or Plain
+      (#2606).
+    + For single Para or Plain, insert a space after the `|` to
+      avoid problems when the text begins with a character like
+      `-` (#2604).
+
+  * Beamer writer: mark frame as fragile when it contains verbatim (#1613).
+
+  * LaTeX writer:
+
+    + Add support for GAP highlighting using listings (Raniere Silva).
+    + Consider `header-includes` content as well as templates
+      when determining whether to use csquotes (Andreas Lööw).
+    + Create defaults for geometry using `margin-left` etc.
+      If `geometry` has no value, but `margin-left`, `margin-right`,
+      `margin-top`, and/or `-margin-bottom` are given, a default value
+      for `geometry` is created from these.  Note that these variables
+      already affect PDF production via HTML5 with `wkhtmltopdf`.
+
+  * ConTeXt writer: set default layout based on `margin-left`, etc.
+    This sets up `\setuplayout` based on the variables `margin-left`,
+    `margin-right`, `margin-bottom`, and `margin-top`, if no layout
+    is given.
+
+  * Docx writer:  better handling of PDF images.  Previously we tried
+    to get the image size from the image even if an explicit size was
+    specified.  Since we still can't get image size for PDFs, this made
+    it impossible to use PDF images in docx.  Now we don't try to get
+    the image size when a size is already explicitly specified.
+
+  * Markdown writer:  use raw HTML for link/image attributes when
+    the `link_attributes` extension is unset and `raw_html` is set (#2554).
+
+  * MediaWiki reader: interpret markup inside `<tt>`, `<code>` (#2607).
+
+  * LaTeX reader:
+
+    + Improved smart quote parsing (#2555). This fixes redering of
+      unmatched quotes.
+    + Use curly quotes for unmatched ` (#2555).
+    + Allow blank space between braced arguments of commands (#2592).
+
+  * Markdown reader:
+
+    + Improved pipe table relative widths.  Previously pipe table
+      columns got relative widths (based on the header underscore lines)
+      when the source of one of the rows was greater in width than the
+      column width.  This gave bad results in some cases where much of
+      the width of the row was due to nonprinting material (e.g. link
+      URLs).  Now pandoc only looks at printable width (the width of a
+      plain string version of the source), which should give better results.
+      Thanks to John Muccigrosso for bringing up the issue.
+    + Fixed parsing bug with macros.  Previously macro definitions in
+      indented code blocks were being parsed as macro definitions, not code.
+
+  * Textile reader:  skip over attribute in image source (#2515).
+    We don't have a place yet for styles or sizes on images, but
+    we can skip the attributes rather than incorrectly taking them
+    to be part of the filename.
+
+  * Docx reader: Handle dummy list items (Jesse Rosenthal).
+    These come up when people create a list item and then delete the
+    bullet. It doesn't refer to any real list item, and we used to ignore
+    it.
+
+  * CommonMark reader/writer rewritten to use latest `cmark`.
+
+  * Fixed Emoji character definitions (#2523).  There were many bugs in the
+    definitions.
+
+  * `Text.Pandoc.CSS`:
+
+    + Added `pickStylesToKVs` function to extract multiple properties at
+      once (API change, Mauro Bieg).
+    + Parse CSS that doesn't contain the optional semicolon (Mauro Bieg).
+
+  * `trypandoc`: sort drop-down lists.
+
+  * Beamer template:
+
+    + Made `\euro` conditional on presence of character.
+      for xelatex and lualatex, as it is for pdflatex (Andrew Dunning).
+    + Moved `header-includes` before setting of title (Thomas Hodgson),
+      to match the LaTeX template (jgm/pandoc-templates#168).
+    + Added `section-titles` variable (defaults to true)
+      to enable/suppress section title pages in beamer
+      slide shows (Thomas Hodgson).
+    + Moved beamer themes after fonts, so that themes can
+      change fonts.  (Previously the fonts set were being
+      clobbered by lmodern.sty.) (Thomas Hodgson).
+
+  * Beamer/LaTeX template changes (Thomas Hodgson):
+    + Added `thanks` variable
+    + Use `parskip.sty` when `indent` isn't set (fall back to using
+      `setlength` as before if `parskip.sty` isn't available).
+    + Use `biblio-style` with biblatex.
+    + Added `biblatexoptions` variable.
+
+  * LaTeX template changes:
+
+    + Added `paper` after `$papersize$` variable in latex template.
+      Thus you can say `papersize: a4` and the latex will contain
+      `a4paper`.  This change may break some existing workflows; if
+      you currently specify `a4paper`, you'll get `a4paperpaper` which
+      is meaningless.  However, the change seems worth it, as it will
+      make the `papersize` variable work uniformly across ConTeXt, LaTeX,
+      and html->pdf via wkhtmltopdf.
+    + Only pass options to color package if `colorlinks` is set
+      (Andrew Dunning).
+    + Make definition of `\euro` conditional in xelatex/lualatex,
+      as it is already for pdflatex (Andrew Dunning).
+    + Removed setting of `subject` in PDF metadata.
+      This used to be set to the subtitle, but really the subtitle
+      need not give the subject.  Also, `subtitle` can contain formatting,
+      so we'd need, at least, a plain text version for this.
+    + Moved `header-includes` before setting of `\title`, `\author`,
+      etc.  This allows these macros to be redefined.
+    + Use `\subtitle` command for `subtitle`, instead of tacking it
+      on to the title as before.  We give a no-op fallback definition if it
+      is not defined.  This change should produce much better results
+      in classes that support `\subtitle`.  With the default article
+      class, which does not define `\subtitle`, subtitles will no
+      longer be printed unless the user defines `\subtitle` and
+      redefines `\maketitle`.
+    + Moved redefinitions of `\paragraph` and `\subparagraph` to
+      before header-includes.
+
+  * Context template:
+
+    + Use `simplefonts` for font loading (Paolo Rodríguez).  This is
+      needed for things to work on ConTeXt stable from TeXLive 2015.
+    + Revert use of `\setuphead` in title block (Andrew Dunning,
+      Rik Kabel).
+
+  * Update LaTeX/ConTeXt link colour usage (Andrew Dunning).
+
+  * Fixed man template so disabling hyphenation actually works.
+    The command needs to come after .TH.
+
+  * Added 'navigation' variable to beamer template (#2543).
+    Valid values are `empty` (the default), `horizontal`, `vertical`,
+    and `frame`.  Note that this changes the default behavior from
+    `horizontal` to `empty`.  Closes #2543.
+
+  * Added `toc` to HTML slide format templates (Andrew Dunning),
+    so that `--toc` creates a contents slide.
+
+  * Added `stack.full.yaml` to build `pandoc-citeproc` as well.
+
+  * Allow pipe tables with no body rows (#2556).
+    Previously this raised a runtime error.
+
+  * Shared: Improved `fetchItem` so that `C:/Blah/Blah.jpg` isn't treated
+    as URL.  The Haskell URI parsing routines will accept "C:" as a
+    scheme, so we rule that out manually.  This helps with
+    `--self-contained` and absolute Windows paths.
+
+  * Define a `meta-json` variable for all writers (#2019).  This contains
+    a JSON version of all the metadata, in the format selected for the
+    writer.  So, for example, to get just the YAML metadata, you can run
+    pandoc with the following custom template: `$meta-json$`.  The intent
+    is to make it easier for static site generators and other tools to get
+    at the metadata.
+
+  * Document limitations of --self-contained (#2553).
+
+  * Improved Citations section of README (#2551).  Added information
+    about `link-citations` and a link to the pandoc-citeproc man page.
+
+  * `ImageSize`: use `safeRead` instead of `readMaybe`, which isn't
+    in base < 4.6.
+
+  * Allow .adoc file extension for AsciiDoc (Andrew Dunning).
+
+  * Improved implicit pandoc-citeproc inclusion.
+    The filter pandoc-citeproc is automatically used when
+    `--bibliography` is specified on the command line, unless
+    `--natbib` or `--biblatex` is used.  However, previously this
+    only worked if `--bibliography` was spelled out in full, and not
+    if `--biblio` was used.
+
+  * reveal.js: Interpret pauses correctly for all headers (#2530).
+    Previously, when using headers below the slide level, pauses are left
+    uninterpreted into pauses. In my opinion, unexpected behavior but
+    intentional looking at the code.
+
+  * Remove redundant `center` variable for reveal.js (Andrew Dunning).
+
+  * Parsing: Add `extractIdClass`, modified type of `KeyTable` (Mauro
+    Bieg, API change).
+
+  * ImageSize:  Added functions for converting between image dimensions
+    (Mauro Bieg).
+
+  * Use lts-3.18 in stack.yaml.  This avoids Windows build
+    issues with the HTTP library.
+
+  * Bump version bounds for dependencies.
+
+## pandoc 1.15.2.1 (2015-11-16)
+
+  * Added two missing test files, and `stack.yaml`, to
+    `extra-source-files` so they're included in the source tarball.
+
+  * reveal.js template: Fixed parallaxBackground options.
+    `parallaxBackgroundHorizontal` and `parallaxBackgroundVertical`
+    need integer values, not strings.  (Vaughn Iverson)
+
+## pandoc 1.15.2 (2015-11-15)
+
+  * `pandoc my.md -t context -o my.pdf` will now create a PDF using
+    ConTeXt rather than LaTeX (#2463).
+
+  * Fixed omitted `url(...)` in CSS data-uri with `--self-contained` (#2489).
+
+  * Added `emoji` Markdown extension, enabled by default in `markdown_github`
+    (#2523).  Added `Ext_emoji` to `Extension` in `Text.Pandoc.Options`
+    (API change).
+
+  * `Text.Pandoc.Readers.HTML.parseTags`: Fixed over-eager raw HTML inline
+    parsing (#2469).  Tightened up the inline HTML parser so it disallows
+    TagWarnings.
+
+  * Derive `Generic` instances for the types in `Text.Pandoc.Options`.
+
+  * Org reader:
+
+    + Fix paragraph/list interaction (Albert Krewinkel, #2464).
+      Paragraphs can be followed by lists, even if there is no blank line
+      between the two blocks.  However, this should only be true if the
+      paragraph is not within a list, were the preceding block should be
+      parsed as a plain instead of paragraph (to allow for compact lists).
+      Thanks to @rgaiacs for bringing this up.
+    + Allow toggling header args (Albert Krewinkel, #2269).
+      Org-mode allows to skip the argument of a code block header argument if
+      it's toggling a value.  Argument-less headers are now recognized,
+      avoiding weird parsing errors.
+    + Fix markup parsing in headers (Albert Krewinkel, #2504).
+      Markup as the very first item in a header wasn't recognized.  This was
+      caused by an incorrect parser state: positions at which inline markup
+      can start need to be marked explicitly by changing the parser state.
+      This wasn't done for headers.  The proper function to update the state
+      is now called at the beginning of the header parser, fixing this issue.
+    + Fix emphasis rules for smart parsing (Albert Krewinkel, #2513).
+      Smart quotes, ellipses, and dashes should behave like normal quotes,
+      single dashes, and dots with respect to text markup parsing.
+    + Require whitespace around definition list markers (#2518).
+      This rule was not checked before, resulting in bugs with footnotes
+      and some link types.
+
+  * Markdown reader:
+
+    + Pipe tables with long lines now get relative cell widths (#2471).
+      If a pipe table contains a line longer than the column width (as set by
+      `--columns` or 80 by default), relative widths are computed based on the
+      widths of the separator lines relative to the column width.  This should
+      solve persistent problems with long pipe tables in LaTeX/PDF output, and
+      give more flexibility for determining relative column widths in other
+      formats, too.  For narrower pipe tables, column widths of 0 are used,
+      telling pandoc not to specify widths explicitly in output formats that
+      permit this.
+    + Improved parser for `mmd_title_block`.  We now allow blank metadata
+      fields.  These were explicitly disallowed before.
+    + Citation keys can now contain `://`, so URLs and DOIs can be used
+      as citation keys (jgm/pandoc-citeproc#166).
+
+  * Beamer template:  fix incompatibility of section slides with natbib.
+    Natbib (and presumably biblatex) bibliography commands create
+    their own section.  Since these are in frame environments,
+    we have an incompatibility with the `\AtBeginSection` macro
+    which creates a special frame when a new section occurs.
+    (We can't have a frame inside another frame.) This change disables
+    `\AtBeginSection` inside bibliography slides.  Thinks to Yihui Xie for
+    bringing the problem to my attention.  This supersedes #145.  See
+    discussion there.
+
+  * Textile reader:  don't do smart punctuation unless explicitly asked
+    (#2480).  Note that although smart punctuation is part of the textile
+    spec, it's not always wanted when converting from textile
+    to, say, Markdown.  So it seems better to make this an option.
+
+  * LaTeX reader: Handle `comment` environment (Arata Mizuki).
+    The `comment` environment is handled in a similar way to the
+    `verbatim` environment, except that its content is discarded.
+
+  * Docx reader:  Follow relationships correctly in foot/endnotes (#2258,
+    Jesse Rosenthal).  This fixes a problem with links in notes.
+
+  * LaTeX and ConTeXt writers: support `lang` attribute on divs and spans
+    (mb21).  For LaTeX, also collect `lang` and `dir` attributes on spans and
+    divs to set the `lang`, `otherlangs` and `dir` variables if they aren’t set
+    already.  See #895.
+
+  * LaTeX writer:
+
+    + Use proper command for `\textarabic` (mb21).
+    + Added `de-CH-1901`, fixed `el-polyton` in `toPloyglossia` (Nick Bart).
+    + Use `\hypertarget` and `\hyperlink` for links.  This works correctly
+      to link to Div or Span elements.  We now don't bother defining `\label`
+      for Div or Span elements.  Closes jgm/pandoc-citeproc#174.
+    + Avoid footnotes in list of figures (#1506).
+    + Properly handle footnotes in captions (#1506).
+    + Add `\protect` to `\hyperlink` (#2490).  Thanks to Hadrien Mary.
+    + Set `colorlinks` if `linkcolor`, `urlcolor`, `citecolor`, or
+      `toccolor` is set (#2508).
+
+  * Textile writer: support start number in ordered lists (#2465).
+
+  * OpenDocument writer:  Allow customization of opendocument
+    automatic styles.  Automatic styles can now be inserted in the
+    template, which now provides the enclosing `<office:automatic-styles>`
+    tags (#2520).
+
+  * Docx writer:  insert space between footnote reference and note (#2527).
+    This matches Word's default behavior.
+
+  * EPUB writer:  don't download linked media when `data-external` attribute
+    set (#2473).  By default pandoc downloads all linked media and includes it
+    in the EPUB container.  This can be disabled by setting `data-external` on
+    the tags linking to media that should not be downloaded.  Example:
+
+        <audio controls="1">
+         <source src="http://www.sixbarsjail.it/tmp/bach_toccata.mp3"
+         type="audio/mpeg"></source>
+        </audio>
+
+  * HTML writer:  use width on whole table if col widths sum to < 100%.
+    Otherwise some browsers display the table with the columns
+    separated far apart.
+
+  * AsciiDoc template:  Fix `author` and `date`; add `keywords`,
+    `abstract` (Andrew Dunning).
+
+  * HTML-based templates (Andrew Dunning):
+
+    + Use en dash instead of hyphen between title prefix and title.
+    + Add `keywords` to metadata.
+    + Add `lang`, `dir`, `quotes` where missing.
+    + Always make author and date display conditional.
+    + Updated dzslides template from source.
+
+  * Man template: make "generated by" comment conditional.
+
+  * LaTeX, Beamer templates:
+
+    + Add `babel-otherlangs` for language divs/spans; `babel-newcommands`,
+      filled by commands that make babel understand the polyglossia-style
+      language directives (mb21, #137).
+    + Improved formatting of conditionals; `$for$` is always provided to allow
+      multiple options (Andrew Dunning, #141).
+    + Use `Ligatures=TeX` rather than `Mapping=tex-text` with `fontspec`
+      to improve support for LuaTeX (Andrew Dunning, #135).
+    + Revise `hyperref` usage (Andrew Dunning, #139, #141):
+        - use same options for all LaTeX engines;
+        - add `subtitle` and `keywords` to PDF metadata;
+        - do not override `hyperref` link coloring without user input, effectively making
+          the `hidelinks` option the default (removed as a separate variable);
+        - link colors can be enabled (using a slightly darker version of the old
+          defaults) using a new `colorlinks` variable, automatically used by
+          the LaTeX writer when custom colors are specified;
+        - `pdfborder={0 0 0}` is automatically set by `hyperref` with
+          `colorlinks`, and is only applied if `colorlinks` is disabled.
+
+  * ConTeXt template (Andrew Dunning):
+
+    + New variables for controlling styles: `linkstyle`, `linkcolor`,
+      `linkcontrastcolor`, `layout`, `pagenumbering`, `whitespace`, `indenting`,
+      `interlinespace`, `headertext`, `footertext`, `mainfont`, `sansfont`,
+      `monofont`, `mathfont`, `fontsize`.
+    + Default template no longer supports MkII.
+    + Improve writing of title block (suppressing numbering of first page).
+    + Add `title` `subtitle`, `author`, `date`, `keywords` to PDF metadata.
+    + Support `subtitle`, `abstract`.
+    + Support list of figures (`lof`), list of tables (`lot`).
+    + Disable link styling by default.
+    + Define styles for all section types.
+    + Enable microtype.
+    + Improved formatting of conditionals.
+
+  * Beamer template:  added code to prevent slide breaks inside paragraphs
+    (#2422, thanks to Nick Bart).  This will matter, in practice, only when
+    `allowframebreaks` is used.  It is especially helpful for bibliography
+    slides.
+
+  * OpenDocument template:  Add `<office:automatic-styles>` tag around
+    automatic styles.  The writer now longer provides this (see #2520).
+
+  * Restored Text.Pandoc.Compat.Monoid.
+
+  * Do not export (<>) from custom Prelude.  The Prelude now matches
+    base 4.8 Prelude's API.
+
+  * Don't use custom prelude with ghc 7.10.  Use the custom prelude
+    only for earlier versions.  This change makes `stack ghci` and
+    `cabal repl` work (#2503), at least with ghc 7.10.
+
+  * Changed § to % in operators from Odt.Arrows.Utils (#2457).
+    This prevents problems building haddocks with "C" locale.
+
+  * Change default for old-locale flag to False.
+
+  * Use stack in deb, osx, and Windows package generators.
+
+  * Added Vagrantfile for building deb in vm.
+    This should help in automating binary package creation.  'make package'
+    will make the package.  'make package COMMIT=blah' will make the package
+    from commit blah.
+
+  * README:
+
+    + Consistent capitalization for pandoc and Markdown.
+    + Fixed `auto_identifiers` examples (Benoit Schweblin).
+    + Improved documentation of template variables (Andrew Dunning).
+
+## pandoc 1.15.1 (2015-10-15)
+
+  * `pandocVersion` is now defined in `Text.Pandoc.Shared`
+    and reexported from `Text.Pandoc` (Alex Vong).  This allows
+    writers to access it.  (Alex Vong) (API change)
+
+  * For `markdown_mmd`, add: `implicit_figures`, `superscripts`,
+    `subscripts` (#2401).
+
+  * Added `odt` as input format (MarLinn).  Added new module
+    `Text.Pandoc.Reader.ODT` (API change). Fully implemented features:
+    Paragraphs, Headers, Basic styling, Unordered lists, Ordered lists,
+    External Links, Internal Links, Footnotes, Endnotes, Blockquotes.
+    Partly implemented features: Citations, Tables.
+
+  * Markdown Reader:
+
+    + Add basic tests for each header style (Ophir Lifshitz).
+    + Add implicit header ref tests for headers with spaces (Ophir Lifshitz).
+    + Skip spaces in headers (Ophir Lifshitz).
+    + Handle 'id' and 'class' in parsing key/value attributes (#2396).
+      `# Header {id="myid" class="foo bar"}`
+      is now equivalent to `# Header {#myid .foo .bar}`.
+    + Use '=' instead of '#' for atx-style headers in markdown+lhs.
+      (Kristof Bastiaensen)
+    + Pipe tables: allow indented columns.  Previously the left-hand column
+      could not start with 4 or more spaces indent.  This was inconvenient
+      for right-aligned left columns.  Note that the first (header column)
+      must still have 3 or fewer spaces indentation, or the table will be
+      treated as an indented code  block.
+    + Fix regression:  allow HTML comments containing `--`.
+      Technically this isn't allowed in an HTML comment, but
+      we've always allowed it, and so do most other implementations.
+      It is handy if e.g. you want to put command line arguments
+      in HTML comments.
+
+  * LaTeX reader:
+
+    + Don't eat excess whitespace after macros with only optional
+      arguments (#2446).
+    + Support longtable (#2411).
+    + Implement `\Cite` (#2335).
+    + Support abstract environment.  The abstract populates an
+      `abstract` metadata field.
+    + Properly handle booktabs lines.  Lines aren't part of the
+      pandoc table model, so we just ignore them (#2307).
+
+  * HTML reader:
+
+    + Handle type attribute on ol, e.g. `<ol type="i">` (#2313).
+    + Updated for new automatic header attributes.
+    + Add auto identifiers if not present on headers.  This makes
+      TOC linking work properly.
+    + Detect `font-variant` with `pickStyleAttrProps` (Ophir Lifshitz).
+    + Test `<ol>` type, class, and inline list-style(-type) CSS
+      (Ophir Lifshitz).
+    + Better handling of "section" elements (#2438).  Previously
+      `<section>` tags were just parsed as raw HTML blocks.  With
+      this change, section elements are parsed as Div elements with
+      the class "section".
+
+  * MediaWiki reader:  handle unquoted table attributes (#2355).
+
+  * DocBook reader:
+
+    + Added proper support for DocBook `xref` elements (Frerich Raabe).
+      Added `dbContent` field to reader state, so we can lookup
+      cross refs.
+    + Handle `informalexample` (#2319).
+
+  * Docx Reader:
+
+    + Create special punctuation test (Ophir Lifshitz).
+    + Parse soft, no-break hyphen elements (Ophir Lifshitz).
+    + Updated headers test (Ophir Lifshitz). Replaced `styles.xml`
+      in `headers.docx` with pandoc's current `styles.xml`, which
+      contains styles for Heading 1 through 6. Added Heading 4
+      through 7 to the test document. Note that Heading 7 is not
+      parsed as a Heading because there is no Heading 7 style.
+
+  * RST reader:  better handling of indirect roles.
+    Previously the parser failed on this kind of case
+
+        .. role:: indirect(code)
+
+        .. role:: py(indirect)
+           :language: python
+
+        :py:`hi`
+
+    Now it correctly recognizes `:py:` as a code role.
+
+  * Org reader:
+
+    + Add auto identifiers if not present on headers
+      (#2354, Juliusz Gonera).
+    + Allow verse blocks to contain empty lines (#2402,
+      Albert Krewinkel).
+
+  * EPUB reader:  stop mangling external URLs (#2284).
+
+  * RST writer:
+
+    + Don't insert `\ ` when complex expression in matched pairs.
+      E.g. `` [:sup:`3`] `` is okay; you don't need `` [:sup:`3`\ ] ``.
+    + Ensure that `\ ` is inserted when needed before Cite and Span
+      elements that begin with a "complex" element (jgm/pandoc-citeproc#157).
+    + Normalize headers only in "standalone" mode (#2394).
+
+  * Haddock writer: escape `*` and `^` (G. Bataille).
+
+  * Markdown writer:
+
+    + In TOC, add links to headers (#829).
+    + Use unicode super/subscripts for digits in plain output
+      (when the `superscripts` and `subscripts` extensions are
+      not enabled).
+
+  * Docx writer:
+
+    + Moved invalid character stripping to `formattedString`.
+      This avoids an inefficient generic traversal (#2356).
+    + Use user data directory for `reference.docx` archive.
+      This allows the test suite to work without installing pandoc first.
+      It also brings the docx writer in line with the odt writer.
+    + Tests:  docx writer tests now use `../data` for data directory.
+      This allows tests to be run without installing first.
+    + Tests: Use real jpg (not empty) for docx tests to avoid warning.
+
+  * LaTeX writer:
+
+    + Fixed detection of 'chapters' from template.
+      If a documentclass isn't specified in metadata, but the
+      template has a hardwired bookish documentclass, act as if
+      `--chapters` was used.  This was the default in earlier
+      versions, but it has been broken for a little while.
+    + Correctly recognize book documentclass in metadata (#2395).
+    + Set language-related variables automatically, depending
+      on the value of the `lang` field, which is now always
+      assumed to be in BCP47 format (mb21, #1614, #2437).
+    + Add `\protect` to `\hyperdef` in inline context.  This way we
+      don't get an error when this is used as a moveable argument (#2136).
+    + Support all frame attributes in Beamer.
+    + Percent-encode more special characters in URLs (#1640, #2377).
+      The special characters are '<','>','|','"','{','}','[',']','^', '`'.
+
+  * HTML writer:
+
+    + Update KaTeX JS and CSS versions (Emily Eisenberg).
+    + For dzslides, add `role="note"` for speaker notes (#1693).
+    + Percent-encode more special characters in URLs (#1640, #2377).
+      The special characters are '<','>','|','"','{','}','[',']','^', '`'.
+    + Render Div with class `section` as `<section>` in HTML5.
+
+  * EPUB writer:
+
+    + In TOC, replace literal `<br/>` with space (#2105).
+    + With `--webtex`, include image file rather than `data:` URI (#2363).
+
+  * Native writer: format Div properly, with blocks separated.
+
+  * Support bidirectional text output with XeLaTeX, ConTeXt and HTML
+    (#2191, mb21).
+
+  * Reference Docx:
+
+    + Add missing Header 6 style (steel blue) (Ophir Lifshitz).
+    + Correct `outlineLvl` for Header styles (Ophir Lifshitz).
+
+  * Templates
+
+    + Beamer:  Add `innertheme`, `outertheme` variables
+      (Guilhem Bonnefille, #121). Add space after colon in figure caption.
+      Integrate recent font and language updates from LaTeX template;
+      allow use of `mainfont` variable for changing the slide text
+      in XeTeX and LuaTeX (Andrew Dunning, #131).
+    + LaTeX:  Add `mainfontoptions`, `sansfontoptions`,
+      `monofontoptions`, `mathfontoptions`, `fontfamilyoptions`
+      (Andrew Dunning, #122).  Support handling of bidirectional
+      text (mb21, #120). Improve reliability of superscripts/subscripts
+      under XeTeX and prevent letters and numbers from appearing on a
+      different baseline by removing use of the `realscripts` package
+      (via `xltxtra`).  To restore use of OpenType characters for these
+      features under XeTeX or LuaTeX, add `\usepackage{realscripts}` to
+      `header-includes` (Andrew Dunning, #130).  Remove redundant
+      reference to `xunicode` (Andrew Dunning, #130).  Add `fontenc`,
+      `indent`, `subparagraph` variables (Andrew Dunning).
+      Allow use of `hidelinks` variable for `hyperref` package (Hugo Roy,
+      #113).  Prevent package clash with `tufte-latex` and other classes that
+      include `hyperref` or `color` (Xavier Olive, #115).
+    + ConTeXt:  Support handling of bidirectional text (mb21, #120).
+    + LaTeX and ConTeXt: Use more specific language variables.
+      Instead of directly using `lang`, we now use `babel-lang` and
+      `polyglossia-lang` and `context-lang`.  These variables are set by
+      the writers to the necessary values, based on the `lang` variable
+      (which now always takes a value in BCP47 format). (mb21, #114, #129).
+    + HTML:  Support handling of bidirectional text (mb21, #120).
+      Move HTML5 shiv after CSS and fix URL (Andrew Dunning).
+      Add dir attribute in html5 (Andrew Dunning).
+    + reveal.js: Add `controls`, `progress` variables (Grégoire Pineau, #127).
+      Add `width`, `height` variables (Anrew Dunning).  Update template
+      from 3.1 source (Andrew Dunning).  All configuration options are now
+      available as variables, but are only be included if set (reveal.js
+      uses defaults otherwise).
+    + man: Added comment stating that the page is autogenerated by pandoc,
+      giving version.  Added `adjusting` and `hyphenate` variables
+      (Alex Vong, #123).
+
+  * epub.css: added selectors for nested emphasis (Pablo Rodriguez).
+
+  * MediaBag:  ensure that `/` is always used as path separator.
+
+  * `sample.lua`: define `CaptionedImage`, add newline at end (#2393).
+
+  * Added `--bash-completion` option.  This generates a bash completion
+    script.  To use: `eval "$(pandoc --bash-completion)"`.
+
+  * Text.Pandoc.Error: Define Typeable and Exception instances
+    for PandocError (#2386).
+
+  * Text.Pandoc.Parsing: `toKey`: strip off outer brackets.
+    This makes keys with extra space at the beginning and end
+    work:  e.g.
+
+        [foo]: bar
+
+        [ foo ]
+
+    will now be a link to bar (it wasn't before).
+
+  * Text.Pandoc: disable `auto_identifiers` for epub.
+    The epub writer inserts its own auto identifiers;
+    this is more complex due to splitting into "chapter" files.
+
+  * Renamed Text.Pandoc.Compat.Locale -> Text.Pandoc.Compat.Time.
+    It now reexports Data.Time.
+
+  * Use custom Prelude to avoid compiler warnings.
+
+    + The (non-exported) prelude is in prelude/Prelude.hs.
+    + It exports Monoid and Applicative, like base 4.8 prelude,
+      but works with older base versions.
+    + It exports (<>) for mappend.
+    + It hides 'catch' on older base versions.
+
+  * Added a `stack.ymal` and stack install instructions to INSTALL.
+
+  * Clarified what is "out of scope" in README and CONTRIBUTING.md.
+
+  * Added note to CONTRIBUTING.md about ghc versions and travis.
+
+  * Clarify docs on block quotes.  The space after `>` is optional (#2346).
+
+  * Removed obsolete reference to default.csl (#2372).
+
+  * List all styles in manual for `--reference-docx` (Chris Black)
+
+  * Don't capitalize header links in man page.
+
+  * Added section on repl to CONTRIBUTING.md.
+
+  * README:  Added space after backslash in image example (#2329).
+
+  * Document details of citation locator terms (Nick Bart).
+
+  * Fixed some internal links in README (#2309).
+
+  * Improve CSL documentation, variables documentations,
+    links, and cross-references in README. (Andrew Dunning)
+
+  * Fix build failure with `--flags=-https` (Sergei Trofimovich).
+
+  * Use `newManager` instead of `withManager` in recent `http-client`.
+    This avoids a deprecation warning.
+
+  * Allow building with latest versions of http-types,
+    HUnit, criterion, syb, aeson.
+
+  * Updated benchmark program for new criterion API.
+
+  * Setup.hs: rewrite so as not to use process, directory, filepath.
+    Using anything outside base is dangerous, since older
+    versions of ghc may link against two different versions.
+
+  * Added appveyor (Windows continuous integration) builds.
+
+  * New `.travis.yml`.  Autgenerated using `make_travis_yml.hs`.
+    This script has been modified in a few ways, e.g. to add `GHCOPTS`.
+    `make .travis.yml` regenerates it based on the tested-with
+    field of the cabal file.
+
+## pandoc 1.15.0.6 (2015-07-15)
+
+  * `--self-contained`: Fixed overaggressive CSS minimization
+    (#2301, 2286). Previously `--self-contained` wiped out all
+    spaces in CSS, including semantically significant spaces.
+    This was a regression from 1.14.x.
+
+  * Markdown reader: don't allow bare URI links or autolinks in link
+    label (#2300).  Added test cases.
+
+  * `Text.Pandoc.Parsing`, `uri`: Improved bare autolink detection (#2299).
+    Previously we disallowed `-` at the end of an autolink,
+    and disallowed the combination `=-`.  This commit liberalizes the
+    rules for allowing punctuation in a bare URI, and adds test cases.
+    One potential drawback is that you can no longer put a bare
+    URI in em dashes like this:
+    `this uri---http://example.com---is an example.`
+    But in this respect we now match github's treatment of bare URIs.
+
+  * HTML writer:  support speaker notes in dzslides.
+    With this change `<div class="notes">` and also `<div class="notes"
+    role="note">` will be output if `-t dzslides` is used. So we can
+    have speaker notes in dzslides too.  Thanks to maybegeek.
+
+  * Updated dzslides template.
+
+  * Improved documentation of options to print system default files (#2298).
+    `--print-default-data-file` and `--print-default-template`.
+
+  * DokuWiki writer: use `$..$` for Math instead of `<math>..</math>`
+    (Tiziano Müller).  MathJax seems currently to be the only maintained
+    math rendering extension for DokuWiki.
+
+  * `Text.Pandoc.Shared`: Changed `hierarchicalize` so it treats references
+    div as top-level header (#2294).  This fixes a bug with `--section-divs`,
+    where the final references section added by pandoc-citeproc, enclosed in
+    its own div, got nested in the div for the section previous to it.
+
+  * Allow vector 0.11.
+
+  * Require cmark > 0.4.
+
+## pandoc 1.15.0.5 (2015-07-10)
+
+  * HTML writer: Fixed email javascript obfuscation with `mailto:`
+    URLs (#2280).  This fixes a potential security issue.  Because
+    single quotes weren't being escaped in the link portion, a
+    specially crafted email address could allow javascript code injection.
+
+  * RST reader:  allow inline formatting in definition list field
+    names (Lars-Dominik Braun).
+
+  * PDF:  Make sure `--latex-engine-opt` goes before the filename
+    on the command line.  LaTeX needs the argument to come after
+    the options (#1779).
+
+  * CommonMark writer: fixed tags used for super/subscript.
+
+  * ConTeXt template:  activate hanging indent for definition lists
+    (mb21).
+
+  * Make cabal require `hsb2hs` >= 0.3.1 if `embed_data_files` specified.
+    This is done by adding `hookedPrograms` in `Setup.hs`, which allows us
+    to include `hsb2hs` in Build-Tools in cabal.
+
+  * Improved Windows installer (thanks to nkalvi).
+
+    + When per-machine installation is chosen, the system path
+      is updated instead of the user's.
+    + An appropriate default is used for per-machine installation
+      directory.
+    + Admin privileges are no longer required for a per-user install
+
+  * Travis:  unpack sdist for build to catch packaging bugs.
+
+  * Improved documentation on where user templates go (#2272).
+
+## pandoc 1.15.0.4 (2015-07-03)
+
+  * Added pandoc.1 man page to the repository.  It is no longer
+    built as part of the cabal build process. (This proved too
+    fragile.)  pandoc.1 can be regenerated (`make man/pandoc.1`)
+    when `README` is changed.
+
+  * Copying of the man page now respects `--destdir` (#2262).
+
+  * Improved error messages for filters.  User is now informed if
+    the filter requires an interpreter that isn't found in the path,
+    or if the filter returns an error status.
+
+## pandoc 1.15.0.3 (2015-07-02)
+
+  * Ensure target directory is created when installing man page.
+
+## pandoc 1.15.0.2 (2015-07-02)
+
+  * Added files needed for building man page to Extra-Source-Files.
+
+## pandoc 1.15.0.1 (2015-07-01)
+
+  * Man page is now built and installed as part of the cabal build
+    process. Removed Makefile target for man page.
+
+## pandoc 1.15 (2015-07-01)
+
+  * Man page changes:
+
+    + Removed `--man1`, `--man5` options (breaking change).
+    + Removed `Text.Pandoc.ManPages` module (breaking API change).
+    + Makefile target for `man/man1/pandoc.1`.  This uses pandoc to
+      create the man page from README using a custom template and filters.
+    + Added `man/` directory with template and filters needed to build
+      man page.
+    + We no longer have two man pages: `pandoc.1` and `pandoc_markdown.5`.
+      Now there is just pandoc.1, which has all the content from README.
+      This change was needed because of the extensive cross-references
+      between parts of the README.
+    + Removed old `data/pandoc.1.template` and
+      `data/pandoc_markdown.5.template`.
+
+  * OpenDocument writer: Do not add a carriage return after a hard
+    line break (Michael Chladek).
+
+  * ConTeXt writer:
+
+    + use `\goto` for internal links.
+    + Added a `%` at end for `\reference` to avoid spurious space.
+
+  * Ignore sandbox on 'make quick'
+
+## pandoc 1.14.1 (2015-06-30)
+
+  * Added `--man1` and `--man5` options to pandoc, allowing
+    pandoc to generate its own man pages. Man pages are no longer
+    automatically generated in the build process (the process for
+    this was too complex and prone to failure, #2190). The
+    `make-pandoc-man-pages` executable has been removed. The
+    `man/` directory has been removed, and man page templates
+    have been moved to `data/`. NOTE TO PACKAGERS: You will no
+    longer find pandoc's man pages in `man/`, but you can
+    generate them using `pandoc --man1 > pandoc.1` and `pandoc
+    --man5 > pandoc_markdown.5`.
+
+  * Added new unexported module:  `Text.Pandoc.ManPages`.
+
+  * `README` now acts like a data file (even though it isn't in
+    `data/`).  So, for example, `pandoc --print-default-data-file README`
+    will produce the README.)  This change was required for the `--man1`
+    and `--man5` options, since the man pages are produced from the
+    README, but it may be useful for other purposes as well.
+
+  * Allow `reference.docx` and `reference.odt` to be used with
+    `--print-default-data-file` and to shadow defaults if placed in
+    the user data directory.  Note that as of 1.14, we no longer
+    include these files as data files; instead, we include their
+    components.  This change causes pandoc to behave as if it has
+    these data files; they are constructed on demand when needed
+    using `getDefaultReferenceDocx` and `getDefaultReferenceODT`.
+
+  * Fixed regression in CSS parsing with `--self-contained` (#2224).
+    Pandoc 1.14.0.x used css-text to parse the CSS, but its parser
+    silently drops big sections of CSS.  This commit replaces the
+    use of css-text with a small but principled CSS preprocessor,
+    which removes whitespace and comments and replaces `url()` with
+    base 64 data when possible.
+
+  * Use `https://` instead of `//` for MathJax and KaTeX CDN URLs (#1920).
+    This will allow math to work when pages are being viewed locally.
+
+  * `Text.Pandoc.Options`:  Export `plainExtensions`.
+    These are the extensions used in `plain` output.
+
+  * LaTeX reader: Don't parse `_` and `^` as sub/superscript outside of
+    math mode; treat them as regular inline text.  Normally these will
+    cause an error in LaTeX, but there are contexts (e.g. `alltt`
+    environments) where they are allowed.
+
+  * HTML reader:  allow `<body>` to close `<head>`.
+
+  * DocBook reader: support `mediaobject`s and `figures` (#2184, mb21).
+
+  * RST reader: Fix reference names with special characters
+    (Lars-Dominik Braun).
+
+  * Textile writer:  escape `+` and `-` as entities (#2225).
+
+  * DokuWiki writer: Use proper `<code>` tags for code blocks (#2213).
+
+  * Plain writer:  don't use symbols for super/subscript (#2237).
+    Simplified code by using `plainExtensions`.
+
+  * InDesign writer: Properly escape URLs containing more than one
+    colon character (gohai).
+
+  * Docx writer: Make sure we use dist version of `reference.docx`
+    (and not the user's version) for certain settings.  Taking some
+    settings values from a user-supplied reference.docx can lead to
+    corruption.  This fixes a regression from the last release (#2249).
+
+  * `Text.Pandoc.Shared`: exports `getDefaultReferenceDocx` and
+    `getDefaultReferenceODT` (API change).  These functions have been
+    removed from the Docx and ODT writers.
+
+  * LaTeX template (Xavier Olive):
+    + Added `CJKmainfont` and `CJKoptions` variables.
+    + Allow dvipsnames (e.g. `MidnightBlue`) for colors (Xavier Olive).
+
+  * Epub templates:  use `author.role`, not `author.type`.
+
+  * Bump cmark version to >= 0.3.4.
+
+  * Improved Windows installer (#2205, thanks to nkalvi).
+    Users can now select a per-user or systemwide install, and can set
+    the installation path.  At the end of installation, the install location
+    is given.  The install location is also now given in the list of
+    installed programs in Control Panel.  Cleaner WiX syntax is used for
+    setting the path.
+
+  * Added `download_stats` target to Makefile.
+
+## pandoc 1.14.0.4 (2015-06-02)
+
+  * Added missing commonmark template.
+
+  * Improved try pandoc (moved button, show raw command).
+
+## pandoc 1.14.0.3 (2015-06-01)
+
+  * Allow compilation with syb 0.5.*.
+
+  * Custom writer:  fixed some compiler warnings for ghc < 7.10.
+
+## pandoc 1.14.0.2 (2015-05-31)
+
+  * Allow building with hslua 0.4.
+
+## pandoc 1.14.0.1 (2015-05-28)
+
+  * Fixed problem with building of `reference.docx` and `reference.odt`
+    when the `embed_data_files` flag is used.  Instead of having a phase
+    of the build where `reference.docx` and `reference.odt` are created
+    from their constituent data files, we now construct these archives
+    from their constituents when a `docx` or `odt` is built.  The
+    constituent files have been moved from `extra-source-files` to
+    `data-files`, and `reference.docx` and `reference.odt` have been
+    removed. Users can create their own `reference.docx` or
+    `reference.odt` by using pandoc to create a simple `docx` or `odt`.
+    `make-reference-files.hs` has been removed, simplifying the build
+    process (#2187)
+
+  * Don't include generated man pages in extra-source-files (#2189).
+
+  * Bumped upper bound for aeson.
+
+  * ConTeXt writer:  create internal link anchors for Div elements with
+    identifiers.  (This is needed for linked citations to work.)
+
+## pandoc 1.14 (2015-05-27)
+
+### New features
+
+  * Added `commonmark` as input and output format.
+
+  * Added `--verbose` flag for debugging output in PDF production (#1840,
+    #1653).
+
+  * Allow wildcards in `--epub-embed-font` arguments (#1939).
+
+  * Added `--latex-engine-opt` option (#969, #1779, Sumit Sahrawat).
+
+  * Added `shortcut_reference_links` extension (Konstantin Zudov, #1977).
+    This is enabled by default for those markdown flavors that
+    support reading shortcut reference links, namely: `markdown`,
+    `markdown_strict`, `markdown_github`, `markdown_php`.
+    If the extension is enabled, the reader parses shortcut reference
+    links like `[foo]`, and the writer creates such links unless doing
+    so would cause problems.  Users of markdown flavors that support
+    shortcut reference links should not notice a difference in reading
+    markdown, but the markdown pandoc produces may differ.
+    If shortcut links are not desired, the extension can be disabled
+    in the normal way.
+
+### Behavior changes
+
+  * `--toc` is now supported for `docx` output (#458, Nikolay Yakimov).
+    A "dirty" TOC is created at the beginning of document.
+    It can be regenerated after the document has been opened.
+
+  * An implicit `--filter pandoc-citeproc` is now triggered only when the
+    `--bibliography` option is used, and not when the `bibliography`
+    field in metadata is specified (#1849).
+
+  * Markdown reader:
+
+    + Reference links with `implicit_header_references` are no longer
+      case-sensitive (#1606).
+    + Definition lists no longer require indentation for first line (#2087).
+      Previously the body of the definition (after the `:` or `~` marker)
+      needed to be in column 4.  This commit relaxes that requirement,
+      to better match the behavior of PHP Markdown Extra.  So, now
+      this is a valid definition list:
+
+            foo
+            : bar
+    + Resolve a potentially ambiguity with table captions:
+
+            foo
+
+              : bar
+
+              -----
+              table
+              -----
+
+      Is "bar" a definition, or the caption for the table?  We'll count
+      it as a caption for the table.
+    + Disallow headerless pipe tables (#1996), to conform to GFM and PHP
+      Markdown Extra.  Note:  If you have been using headerless pipe tables,
+      this change may cause existing tables to break.
+    + Allow pipe tables with header but no body (#2017).
+    + Allow a digit as first character of a citation key (Matthias Troffaes).
+      See https://github.com/jgm/pandoc-citeproc/issues/97
+
+  * LaTeX reader:
+
+    + Don't limit includes to `.tex` extension (#1882).
+      If the extension is not `.tex`, it must be given explicitly in
+      the `\input` or `\include`.
+
+  * Docx reader:
+
+    + Allow numbering in the style file.  This allows inherited styles
+      with numbering (lists) (Jesse Rosenthal).
+
+  * Org reader:
+
+    + Support smart punctuation (Craig Bosma).
+    + Drop trees with a :noexport: tag (Albert Krewinkel). Trees having a
+      `:noexport:` tag set are not exported.  This mirrors org-mode.
+    + Put header tags into empty spans (Albert Krewinkel, #2160).
+      Org mode allows headers to be tagged: `* Headline  :TAG1:TAG2`.
+      Instead of being interpreted as part of the headline, the tags are now
+      put into the attributes of empty spans.  Spans without textual content
+      won't be visible by default, but they are detectable by filters.  They
+      can also be styled using CSS when written as HTML.
+    + Generalize code block result parsing (Albert Krewinkel).
+      Previously, only code blocks were recognized as result blocks;
+      now, any kind of block can be the result.
+
+  * Append newline to the LineBreak in Dokuwiki, HTML, EPUB,
+    LaTeX, MediaWiki, OpenDocument, Texinfo writers (#1924, Tim Lin).
+
+  * HTML writer:
+
+    + Add "inline" or "display" class to math spans (#1914).
+      This allows inline and display math to be styled differently.
+    + Include raw latex blocks if `--mathjax` specified (#1938).
+    + Require highlighting-kate >= 0.5.14 (#1903).
+      This ensures that all code blocks will be wrapped in a `div`
+      with class `sourceCode`.  Also, the default highlighting CSS
+      now adds `div.sourceCode { x-overflow: auto; }`, which means
+      that code blocks (even with line numbers) will acquire a scroll
+      bar on screens too small to display them (e.g. mobile phones).
+      See also jgm/highlighting-kate#65.
+
+  * LaTeX writer:
+
+    + Use a declaration for tight lists (Jose Luis Duran, Joseph
+      Harriott). Previously, pandoc hard-coded some commands to make
+      tight lists in LaTeX.  Now we use a custom command instead,
+      allowing the styling to be changed in a macro in the header.
+      (Note:  existing templates may need to be modified to include
+      the definition of this macro.  See the current template.)
+    + Beamer output: if the header introducing a slide has the
+      class `fragile`, add the `[fragile]` option to the slide (#2119).
+
+  * MediaWiki writer:
+
+    + Use `File:` instead of the deprecated `Image:` for images and
+      other media files (Greg Rundlett).
+
+  * DocBook writer:
+
+    + Render a `Div (id,_,_) [Para _]` element as a `para` element
+      with an `id` attribute.  This makes links to citations work in
+      DocBook with pandoc-citeproc.
+
+  * RST writer:
+
+    + Normalize headings to sequential levels (Nikolay Yakimov).
+      This is pretty much required by docutils.
+    + Treat headings in block quotes, etc as rubrics (Nikolay Yakimov).
+    + Better handling of raw latex inline (#1961).  We use
+      `` :raw-latex:`...` `` and add a definition for this role to
+      the template.
+
+  * EPUB writer:
+
+    + Remove `linear=no` from cover `itemref` (#1609).
+    + Don't use `sup` element for epub footnotes (#1995).
+      Instead, just use an a element with class `footnoteRef`.
+      This allows more styling options, and provides better results
+      in some readers (e.g. iBooks, where anything inside the a
+      tag breaks popup footnotes).
+    + Take TOC title from `toc-title` metadata field.
+
+  * Docx writer:
+
+    + Implemented `FirstParagraph` style (Jesse Rosenthal).
+      Following the ODT writer, we add the `FirstParagraph` style to the
+      first text paragraph following an image, blockquote, table, heading,
+      or beginning of document.  This allows it to be styled differently.
+      The default is for it to be the same as `Normal`.
+    + Added `BodyText` style (Jesse Rosenthal).
+      We apply a `BodyText` style to all unstyled paragraphs. This is,
+      essentially, the same as `Normal`, except that since not everything
+      inherits from `BodyText` (the metadata won't, for example, or
+      the headers or footnote numbers), we can change the text in the body
+      without having to make exceptions for everything.  If we do want to
+      change *everything*, we can still do it through `Normal`.
+    + Altered `Blockquote` style slightly (Jesse Rosenthal).
+      Since `BlockQuote` derives from `BodyText`, we just want to specify
+      by default that it won't indent, regardless of what `BodyText` does.
+      Note that this will not produce any visible difference in the default
+      configuration.
+    + Take TOC title from `toc-title` metadata field (Nikolay Yakimov).
+    + Added a style to figure images (Nikolay Yakimov).
+      Figures with empty captions use style `Figure`.
+      Figures with nonempty captions use style `Figure with Caption`, which
+      is based on `Figure`, and additionally has `keepNext` set.
+
+  * ODT writer:
+
+    + Added figure captions (Nikolay Yakimov). The following styles are
+      used for figures:
+      `Figure` -- for figure with empty caption),
+      `FigureWithCaption` (based on `Figure`) -- for figure with caption,
+      `FigureCaption` (based on `Caption`) -- for figure captions.
+      Also, `TableCaption` (based on `Caption`) is used for table captions.
+
+### API changes
+
+  * New `Text.Pandoc.Error` module with `PandocError` type
+    (Matthew Pickering).
+
+  * All readers now return `Either PandocError Pandoc` instead of `Pandoc`
+    (Matthew Pickering).  This allows better handling of errors.
+
+  * Added `Text.Pandoc.Writers.CommonMark`, exporting `writeCommonMark`.
+
+  * Added `Text.Pandoc.Readers.CommonMark`, exporting `readCommonMark`.
+
+  * Derive `Data` and `Typeable` instances for `MediaBag`, `Extension`,
+    `ReaderOptions`, `EPUBVersion`, `CiteMethod`, `ObfuscationMethod`,
+    `HTMLSlideVariant`, `TrackChanges`, `WriterOptions` (Shabbaz
+    Youssefi).
+
+  * New `Ext_shortcut_reference_links` constructor for `Extension`
+    (Konstantin Zudov).
+
+###  Bug fixes
+
+  * Markdown reader:
+
+    + Allow smart `'` after inline math (#1909, Nikolay Yakimov).
+    + Check for tex macros after indented code (#1973).
+    + Rewrote `charsInBalancedBrackets` for efficiency.
+    + Make sure a closing `</div>` doesn't get included in a
+      definition list item (#2127).
+    + Don't parse bracketed text as citation if it might be a link,
+      image, or footnote (Nikolay Yakimov).
+    + Require space after key in mmd title block (#2026, Nikolay
+      Yakimov).  Require space after key-value delimiter colon in mmd title
+      block.
+    + Require nonempty value in mmd title block (Nikolay Yakimov).
+    + Disable all metadata block extensions when parsing
+      metadata field values (#2026, Nikolay Yakimov).  Otherwise we
+      could get a mmd title block inside YAML metadata, for example.
+
+  * HTML reader:
+
+    + Improve self-closing tag detection in `htmlInBalanced` (#2146).
+    + Handle tables with `<th>` in body rows (#1859, mb21).
+    + Fixed `htmlTag` (#1820).  If the tag parses as a comment, we check
+      to see if the input starts with `<!--`. If not, it's bogus comment
+      mode and we fail `htmlTag`.
+    + Handle `base` tag; if it has an `href` value, this is added to
+      all relative URLs in links and images.
+
+  * DocBook reader:
+
+    + Look inside "info" elements for section titles (#1931).
+
+  * Docx reader:
+
+    + Parse images in deprecated vml format (Jesse Rosenthal).
+    + Allow sub/superscript verbatims (Jesse Rosenthal).
+      Verbatim usually shuts off all other run styles, but we don't want it
+      to shut off sub/superscript.
+
+  * LaTeX reader:
+
+    + Handle `tabular*` environment (#1850).
+      Note that the table width is not actually parsed or taken into
+      account, but pandoc no longer chokes on it.
+    + Ignore options in `\lstinline` rather than raising error (#1997).
+    + Add some test cases for simple tables (Mathias Schenner).
+    + Handle valign argument in tables (Mathias Schenner) (currently
+      we just ignore this).
+    + Allow non-empty colsep in tables (Mathias Schenner).
+      The `tabular` environment allows non-empty column separators
+      with the "@{...}" syntax. Previously, pandoc would fail to
+      parse tables if a non-empty colsep was present. With this
+      commit, these separators are still ignored, but the table gets
+      parsed. A test case is included.
+    + Recognize `\newpage` as a block command.
+    + Allow block content in `\title{}` (#2001).
+    + Check for block-level newcommand aliases in blockCommand (Nikolay
+      Yakimov).
+    + Guard against paragraph starting with inline macro (Nikolay Yakimov).
+    + Properly gobble spaces after `\\` (#2007).
+
+  * Textile reader:
+
+    +  Handle newlines in table cells, and empty cells (#1919).
+
+  * Org reader:
+
+    + Allow image links with non-image targets (Hans-Peter Deifel).
+      This matches behavior of Org-Mode for links like
+      `[[http://example.com][https://www.haskell.org/static/img/logo.png]]`.
+
+  * Docbook writer:
+
+    + Don't print empty id attributes (thanks to Steve Horne).
+
+  * HTML writer:
+
+    + Fixed list-style-type for numbered example lists.
+      Should be "decimal," not "example" (#1902).
+    + Do not omit missing `alt` attribute on `img` tag (#1131,
+      Konstantin Zudov).
+    + Allow multiple colgroups in table (#2122).
+    + In revealjs, ensure that lists in speaker notes don't add "fragment"
+      classes, which can cause additional keypresses to be needed to
+      advance a slide (#1394).
+
+  * LaTeX writer:
+
+    + Don't escape `$` in URL (#1913).
+    + Don't use listings in headers (Matthew Pickering, #1963).
+    + Recognize book documentclass if set in metadata (#1971).
+      This sets `--chapters` implicitly if the documentclass in metadata
+      is a book documentclass.  Previously this was done only if a book
+      documentclass was set in a variable.
+    + Add a `\label` in `\hyperdef` for Div, Span (or links don't work).
+    + Make `mainlang` work when `lang` is in metadata (#2174).
+
+  * Texinfo writer:
+
+    + Fix wrapping by using breakable spaces (Tim Lin).
+
+  * RST writer:
+
+    + Fixed toc depth in RST writer.  Previously the depth was being
+      rendered as a floating point number with a decimal point.
+
+  * Markdown writer:
+
+    + Improved escaping (#2086).  `<` should not be escaped as `\<`, for
+      compatibility with original Markdown.  We now escape `<` and `>`
+      with entities.  Also, we now backslash-escape square brackets.
+    + Avoid introducing spurious list items through wrapping (#1946).
+    + Don't emit span tags if plain or raw HTML disabled.
+
+  * MediaWiki writer:
+
+    + Convert spaces to underscores in wikilink URL (#1982), like MediaWiki.
+
+  * AsciiDoc writer:
+
+    + Insert some needed blank lines (#1860).
+    + Avoid wrapping after list marker (#1858).
+
+  * EPUB writer:
+
+    + Properly handle internal links to IDs in spans, divs (#1884).
+    + Use plain writer for metadata dc: fields (#2121).
+      This gives better results when we have, e.g. multiple paragraphs.
+      Note that tags aren't allowed in these fields.
+    + Properly handle image links without an extension (#1855).
+    + Improved chapter splitting and internal link rewriting (#1887,
+      #2162, #2163).  This will ensure that internal links work and
+      that the references section produced by pandoc-citeproc is
+      in its own chapter.
+    + Fixed handling of svg images (#2183).
+
+  * ICML writer:
+
+    + Better handling of raw blocks and inlines (#1951).
+      Previously these were always escaped and printed verbatim.
+      Now they are ignored unless the format is `icml`, in which
+      case they are passed through unescaped.
+    + Fixed image URIs in ICML output (gohai).
+
+  * Custom writer:
+
+    + Raise error if loadstring returns an error status.
+    + Raise `PandocLuaException` instead of using 'error'.
+      Eventually we'll change the return type so that no exception
+      is involved, but at least this can be trapped.
+    + Use UTF-8 aware bytestring conversion.
+    + Set foreign encoding to UTF-8 (Nikolay Yakimov, #2101, #1634).
+      Also factored out ByteString, since it's only used as an intermediate
+      representation.
+
+  * Docx writer:
+
+    + Copy hyphenation settings from reference.docx (Nikolay Yakimov).
+    + Filter out illegal XML characters (#1992, Matthew Pickering).
+    + Added `noProof` to docx syntax highlighting `SourceCode` style.
+    + Added footnotes id -1 and 0 (Jesse Rosenthal).
+      Word uses, by default, footnotes with id -1 and 0 for separators. If a
+      user modifies `reference.docx`, they will end up with a `settings.xml`
+      file that references these footnotes, but no such footnotes in the
+      document. This will produce a corruption error. Here we add these to the
+      document and `settings.xml` file, so future modifications won't break
+      the file.
+    + Handle lists correctly inside table cells (Jesse Rosenthal).
+      Previously we didn't transform lists inside table cells.
+    + Set firstRow information in tables (Nikolay Yakimov).
+    + Don't replace `SourceCode` style in `reference.docx` if it is defined
+      there (Nikolay Yakimov, #1872).  If `--no-highlight` specified, remove
+      any `SourceCode` and `*Tok` styles in `reference.docx`.
+    + Attempt to match international style names (#1607, Nikolay Yakimov).
+    + Set these styles as custom (Nikolay Yakimov): `Author`, `Abstract`,
+      `Compact`, `Image Caption`, `Table Caption`, `Definition Term`,
+      `Definition`, `First Paragraph`.
+    + Rename these styles to correspond with Word `Normal.dotm` (Nikolay
+      Yakimov): `Block Quote -> Block Text`, `Link -> Hyperlink`,
+      `Footnote Ref -> Footnote Reference`.
+    + Added `Caption` style (Nikolay Yakimov).
+    + Changed these styles' inheritance (Nikolay Yakimov):
+      `Image Caption <- Caption`, `Table Caption <- Caption`.
+    + Remove `SourceCode` style from `reference.docx` (#1872).
+      This is added automatically by the docx writer.
+    + Added toc heading style to `reference.docx` (Nikolay Yakimov).
+
+  * `Text.Pandoc.PDF`
+
+    + Don't suggest "Try xelatex" if xelatex already in use (mb21, #1832).
+    + More comprehensible errors on image conversion (#2067).
+      EPS can't be supported without shelling out to something like
+      ImageMagick, but at least we can avoid mysterious error messages.
+
+  * `Text.Pandoc.Shared`:
+
+    + Make safeRead safe (#1801, Matthew Pickering).
+    + Added `mapLeft`, `hush` (Matthew Pickering).
+
+  * `Text.Pandoc.Pretty`:
+
+    + Remove partial function (Matthew Pickering).
+
+  * `Text.Pandoc.SelfContained`:
+
+    + Add `;charset=utf-8` to script mime type if missing (#1842).
+    + Improved building of data URIs (#1940).  Now base64 is used except
+      for `text/*` mime types.
+    + `cssURLs` no longer tries to fetch fragment URLs (#2121).
+    + Properly handle data URIs in css urls (#2129).
+      Use a proper CSS parser (adds dependency on `text-css`).
+
+  * `Text.Pandoc.UTF8`:
+
+    + Better handling of bare CRs in input files (#2132).
+      Previously we just stripped them out; now we convert
+      other line ending styles to LF line endings.
+
+  * `Text.Pandoc.ImageSize`:
+
+    + Fixed some exif header parsing bugs (#1834).
+    + Make imageSize return an Either, not a Maybe (#1834).
+      Use `runGetOrFail` (with `binary >= 0.7`) to return `Left` on
+      parse failure (rather than `error`).
+    + Improved warnings when image size can't be determined.
+    + Removed error landmines (Matthew Pickering).
+
+  * Added woff2 to MIME types (Alfred Wechselberger).
+
+  * pandoc:  When a binary input format is used, warn that file
+    arguments past the first one are being ignored (Matthew Pickering).
+
+### Template changes
+
+  * LaTeX template:
+
+    + Degrade gracefully if `\paragraph` not defined.
+    + Include `grffile` together with `graphicx` (#2074).
+      This properly handles filenames containing spaces and dots.
+    + Redefine `\paragraph`, `\subparagraph`...  to behave more
+      like section headers (#1658).
+    + Import hyperref before polyglossia to avoid an error with xelatex,
+      "please load package hyperref before bidi package" (Nick Bart).
+    + Added `toccolor` variable to control link color in toc (Kaixhin).
+
+  * LaTeX, Beamer templates:
+
+    + Provide `\tightlist`, which is now used by the LaTeX writer.
+    + Use polyglossia in beamer (#85).
+    + Use `bibliography` instead of `biblio-files`
+      (#1661).  Also use `\addbibresource` instead of `\bibliography` for
+      biblatex.
+    + Added `setotherlanguages` in polyglossia. This uses an `otherlang`
+      variable that is derived from a comma-separated list in `lang`;
+      the last language is `mainlang` and the others are `otherlang`.
+
+  * EPUB templates:
+
+    + Use `div`, not `p`, for "rights" on title page.
+    + Added header-includes, include-before, include-after (#1987).
+
+  * OpenDocument template:
+
+    + Use `text:p` instead of `text:h` for title.
+      Using `text:h` causes problems with numbering.  Closes #2059.
+      Thanks to @nkalvi for diagnosing this.
+
+  * reveal.js template:
+
+    + Link to non-minified css, js.  The minified versions no longer
+      ship with the library.
+    + Correctly include style CSS (#1949).
+    + New configurable options options: `center`, `maxScale`, `slideNuber`
+      (Dmitry Smirnov, pandoc-templates#89).
+    + Moved custom CSS after theme.  This allows custom CSS to modify
+      themes, instead of being replaced by them.
+    + Allow `center` to be set to false.
+
+### Under the hood improvements
+
+  * Removed pre-built `reference.docx` and `reference.odt` (Nikolay
+    Yakimov).  Instead the repository now includes the component text files,
+    and the zipped binaries are built from these using a helper
+    program, `make-reference-files`.  This should make maintenance of
+    these components easier going forward.
+
+  * `Text.Pandoc.Parsing`:
+
+    + Added new `<+?>` combinator (Nikolay Yakimov).
+    + Added `stateHeaderKeys` to `ParserState`.
+
+  * `make_deb.sh` fixes:
+
+    + Detect architecture.
+    + Add Installed-Size to debian package control file (#1900).
+    + Use `fakeroot` to get permissions right.
+    + Use `mkdir` and `cp` instead of `install`.
+    + Set permissions of directories to 755.
+    + Install in `/usr` rather than `/usr/local`.
+    + Compress man pages.
+    + Combine copyright files for `pandoc`, `pandoc-citeproc`.
+
+  * Added `Text.Pandoc.Compat.Locale` and `old-locale` flag
+    to assist with transition to `time` 1.5.
+
+  * Updated CONTRIBUTING.md with information about issue tags (Matthew
+    Pickering).
+
+  * Updated travis installs to the new sudo-less syntax (Tim Lin).
+
+  * Updated dependency version bounds.
+
+  * EPUB tests:  don't use `joinPath`, which varies across platforms.
+    Instead, use a forward-slash to join paths, regardless of the
+    platform. This matches the way `MediaBag` now works.
+
+  * Clarify JSON input and output in usage message (Caleb McDaniel).
+
+  * Improved INSTALL instructions.
+
+  * Always build man pages.  Removed make-pandoc-man-pages flag.
+
+  * Makefile:  removed man target, now that we generate man pages by default.
+
+  * README:
+
+    + Fixed typos (J. Lewis Muir).
+    + Added documentation on backtick_code_blocks (#2135, Nikolay Yakimov).
+    + Added note on in-field markup in biblio databases (Nick Bart).
+    + Fixed misleading example of raw HTML block.
+    + Various minor formatting and consistency fixes for the program
+      options (Andreas Lööw).
+    + Made definition lists for options all "loose" for consistency.
+    + Added YAML biblio format to table, and note on `pandoc-citeproc`'s
+      `--bib2json` and `--bib2yaml` options (Nick Bart).
+    + Removed obsolete reference to `mods2yaml` (Nick Bart).
+    + Added section on syntax highlighting.
+    + Documented `toccolor` variable.
+
+## pandoc 1.13.2.1 (2015-04-15)
+
+  * Updated to build with ghc 7.10.1.
+
+  * Bumped package upper bounds for filepath, blaze-html, blaze-markup.
+
+## pandoc 1.13.2 (2014-12-20)
+
+  * TWiki Reader: add new new twiki reader (API chaneg, Alexander Sulfrian).
+
+  * Markdown reader:
+
+    + Better handling of paragraph in div (#1591).
+      Previously text that ended a div would be parsed as Plain
+      unless there was a blank line before the closing div tag.
+    + Don't treat a citation as a reference link label (#1763).
+    + Fix autolinks with following punctuation (#1811).
+      The price of this is that autolinked bare URIs can no longer
+      contain `>` characters, but this is not a big issue.
+    + Fix `Ext_lists_without_preceding_blankline` bug (#1636, Artyom).
+    + Allow `startnum` to work without `fancy_lists`. Formerly
+      `pandoc -f markdown-fancy_lists+startnum` did not work properly.
+
+  * RST reader (all Daniel Bergey):
+
+    + Parse quoted literal blocks (#65).  RST quoted literal blocks are
+      the same as indented literal blocks (which pandoc already supports)
+      except that the quote character is preserved in each line.
+    + Parse RST class directives. The class directive accepts one or more
+      class names, and creates a Div value with those classes.  If the
+      directive has an indented body, the body is parsed as the children of
+      the Div.  If not, the first block following the directive is made a
+      child of the Div. This differs from the behavior of rst2xml, which
+      does not create a Div element.  Instead, the specified classes are
+      applied to each child of the directive.  However, most Pandoc Block
+      constructors to not take an Attr argument, so we can't duplicate this
+      behavior.
+    + Warn about skipped directives.
+    + Literal role now produces Code. Code role should have "code" class.
+    + Improved support for custom roles
+
+        - Added `sourceCode` to classes for `:code:` role, and anything
+          inheriting from it.
+        - Add the name of the custom role to classes if the Inline
+          constructor supports Attr.
+        - If the custom role directive does not specify a parent role,
+          inherit from the `:span:` role.
+
+      This differs somewhat from the `rst2xml.py` behavior.  If a custom
+      role inherits from another custom role, Pandoc will attach both
+      roles' names as classes.  `rst2xml.py` will only use the class of
+      the directly invoked role (though in the case of inheriting from a
+      `:code:` role with a `:language:` defined, it will also provide the
+      inherited language as a class).
+    + Warn about ignored fields in role directives.
+
+  * LaTeX reader:
+
+    + Parse label after caption into a span instead of
+     inserting an additional paragraph of bracketed text (#1747).
+    + Parse math environments as inline when possible (#1821).
+    + Better handling of `\noindent` and `\greektext` (#1783).
+    + Handle `\texorpdfstring` more gracefully.
+    + Handle `\cref` and `\sep` (Wikiwide).
+    + Support `\smartcite` and `\Smartcite` from biblatex.
+
+  * HTML reader:
+
+    + Retain display type of MathML output (#1719, Matthew Pickering).
+    + Recognise `<br>` tags inside `<pre>` blocks (#1620, Matthew Pickering).
+    + Make `embed` tag either block or inline (#1756).
+
+  * DocBook reader:
+
+    + Handle `keycombo`, `keycap` (#1815).
+    + Get string content in inner tags for literal elements (#1816).
+    + Handle `menuchoice` elements better, with a `>` between (#1817).
+    + Include `id` on section headers (#1818).
+    + Document/test "type" as implemented (Brian O'Sullivan).
+    + Add support for calloutlist and callout (Brian O'Sullivan).
+      We treat a calloutlist as a bulleted list. This works well in practice.
+    + Add support for `classname` (Bryan O'Sullivan).
+
+  * Docx reader:
+
+    + Fix window path for image lookup (Jesse Rosenthal).
+      Don't use os-sensitive "combine", since we always want the paths in our
+      zip-archive to use forward-slashes.
+    + Single-item headers in ordered lists are headers (Jesse Rosenthal).
+      When users number their headers, Word understands that as a single item
+      enumerated list. We make the assumption that such a list is, in fact,
+      a header.
+    + Rewrite rewriteLink to work with new headers (Jesse Rosenthal).
+      There could be new top-level headers after making lists, so we have to
+      rewrite links after that.
+    + Use polyglot header list (Jesse Rosenthal).
+      We're just keeping a list of header formats that different languages
+      use as their default styles. At the moment, we have English, German,
+      Danish, and French. We can continue to add to this.
+      This is simpler than parsing the styles file, and perhaps less
+      error-prone, since there seems to be some variations, even within a
+      language, of how a style file will define headers.
+    + Remove header class properly in other langs (Jesse Rosenthal).
+      When we encounter one of the polyglot header styles, we want to remove
+      that from the par styles after we convert to a header. To do that, we
+      have to keep track of the style name, and remove it appropriately.
+    + Account for external link URLs with anchors. Previously, if a URL
+      had an anchor, the reader would incorrectly identify it as an
+      internal link and return only the anchor as URL. (Caleb McDaniel)
+    + Fix for Issue #1692 (i18n styles) (Nikolay Yakimov).
+
+  * Org reader:
+
+    + Added state changing blanklines (Jesse Rosenthal).
+      This allows us to emphasize at the beginning of a new paragraph (or, in
+      general, after blank lines).
+    + Fixed bug with bulleted lists:
+
+        - a
+        - b
+        * c
+
+      was being parsed as a list, even though an unindented `*`
+      should make a heading.  See
+      <http://orgmode.org/manual/Plain-lists.html#fn-1>.
+    + Org reader: absolute, relative paths in link (#1741, Albert
+      Krewinkel). The org reader was too restrictive when parsing links;
+      some relative links and links to files given as absolute paths
+      were not recognized correctly.
+    + Org reader:  allow empty links (jgm/gitit#471, Albert Krewinkel).
+      This is important for use in gitit, which uses empty links
+      for wikilinks.
+    + Respect indent when parsing Org bullet lists (#1650, Timothy
+      Humphries).  Fixes issue with top-level bullet list parsing.
+    + Fix indent issue for definition lists (Timothy Humphries,
+      see #1650, #1698, #1680).
+    + Parse multi-inline terms correctly in definition list (#1649,
+      Matthew Pickering).
+    + Fix rules for emphasis recognition (Albert Krewinkel).
+      Things like `/hello,/` or `/hi'/` were falsy recognized as emphasised
+      strings.  This is wrong, as `,` and `'` are forbidden border chars and
+      may not occur on the inner border of emphasized text.
+    + Drop COMMENT document trees (Albert Krewinkel).
+      Document trees under a header starting with the word `COMMENT` are
+      comment trees and should not be exported.  Those trees are dropped
+      silently (#1678).
+    + Properly handle links to `file:target` (Albert Krewinkel).
+      Org links like `[[file:target][title]]` were not handled correctly,
+      parsing the link target verbatim.  The org reader is changed such that
+      the leading `file:` is dropped from the link target (see #756, #1812).
+    + Parse LaTeX-style MathML entities (#1657, Albert Krewinkel).
+      Org supports special symbols which can be included using LaTeX syntax,
+      but are actually MathML entities.  Examples for this are
+      `\nbsp` (non-breaking space), `\Aacute` (the letter A with accent acute)
+      or `\copy` (the copyright sign ©)
+
+  * EPUB reader:
+
+    + URI handling improvements. Now we outsource most of the work to
+      `fetchItem'`. Also, do not include queries in file extensions (#1671).
+
+  * LaTeX writer:
+
+    + Use `\texorpdfstring` for section captions when needed (Vaclav Zeman).
+    + Handle consecutive linebreaks (#1733).
+    + Protect graphics in headers (Jesse Rosenthal).
+      Graphics in `\section`/`\subsection` etc titles need to be `\protect`ed.
+    + Put `~` before header in list item text (Jesse Rosenthal).
+      Because of the built-in line skip, LaTeX can't handle a section header
+      as the first element in a list item.
+    + Avoid using reserved characters as `\lstinline` delimiters (#1595).
+    + Better handling of display math in simple tables (#1754).
+      We convert display math to inline math in simple tables,
+      since LaTeX can't deal with display math in simple tables.
+    + Escape spaces in code (#1694, Bjorn Buckwalter).
+
+  * MediaWiki writer:
+
+    + Fixed links with URL = text. Previously these were rendered as bare
+      words, even if the URL was not an absolute URL (#1825).
+
+  * ICML writer:
+
+    + Don't force all citations into footnotes.
+
+  * RTF writer:
+
+    + Add blankline at end of output (#1732, Matthew Pickering).
+
+  * RST writer:
+
+    + Ensure blank line after figure.
+    + Avoid excess whitespace after last list item (#1777).
+    + Wrap line blocks with spaces before continuations (#1656).
+    + Fixed double-rendering of footnotes in RST tables (#1769).
+
+  * DokuWiki writer:
+
+    + Better handling of block quotes. This change ensures that
+      multiple paragraph blockquotes are rendered using native `>`
+      rather than as HTML (#1738).
+    + Fix external images (#1739). Preface relative links with ":",
+      absolute URIs without. (Timothy Humphries)
+
+  * HTML writer:
+
+    + Use protocol-relative URL for mathjax.
+    + Put newline btw img and caption paragraph.
+    + MathML now outputted with tex annotation (#1635, Matthew Pickering).
+    + Add support for KaTeX HTML math (#1626, Matthew Pickering).
+      This adds `KaTeX` to `HTMLMathMethod` (API change).
+    + Don't double render when `email-obfuscation=none` (#1625, Matthew
+      Pickering).
+    + Make header attributes work outside top level (#1711).
+      Previously they only appeared on top level header elements.
+      Now they work e.g. in blockquotes.
+
+  * ODT writer:
+
+    + Correctly handle images without extensions (#1729).
+    + Strip querystring in ODT write (#1682, Todd Sifleet).
+
+  * FB2 writer:
+
+    + Add newline to output.
+
+  * EPUB writer:
+
+    + Don't add `sourceURL` to absolute URIs (#1669).
+    + Don't use unsupported `opf:title-type` for epub2.
+    + Include "landmarks" section in nav document for epub3 (#1757).
+    + Removed playOrder from navpoint elements in ncx file (#1760).
+      These aren't required, and they make manual modification of epubs
+      difficult.
+    + Extract title even from structured title.
+    + Don't include nav node in spine unless `--toc` was requested.
+      Previously we included it in the spine with `linear="no"`, leading
+      to odd results in some readers (#1593).
+    + Fixed absolute URI detection (#1672).
+    + Correctly resolve relative URIs (#1671).
+    + Use regular page template for `nav.xhtml`, including doctype (#1759).
+
+  * Docx writer:
+
+    + Put docx table captions above tables (#1641, Nikolay Yakimov).
+    + Get the page width from the reference docx file, and use
+      it to scale images that are too large to fit (Grégory Bataille).
+    + Partial fix for #1607 (Nikolay Yakimov). International heading styles
+      are inferred based on `<w:name val="heading #">` fallback, if there
+      are no en-US "Heading#" styles
+    + Look in user data dir for archive `reference.docx`.
+    + Renumber header and footer relationships to avoid collisions (Jesse
+      Rosenthal). We previously took the old relationship names of the
+      headers and footer in secptr. That led to collisions. We now make
+      a map of available names in the relationships file, and then rename
+     in secptr.
+
+  * ConTeXt writer:
+
+    + Add function toLabel (Mark Szepieniec).
+      This function can be used to sanitize reference labels so that
+      they do not contain any of the illegal characters \#[]",{}%()|= .
+      Currently only Links have their labels sanitized, because they
+      are the only Elements that use passed labels.
+
+  * `Text.Pandoc.Shared`:
+
+    + Moved import of `toChunks` outside of CPP conditional (#1590).
+    + Fix `inDirectory` to reset to the original directory in case
+      an exception occurs (Freiric Barral).
+
+  * Templates:
+
+    + LaTeX template: load polyglossia before bibtex (jgm/pandoc-templates#70).
+      Thanks to bluebirch.
+    + LaTeX template: Added `\VerbatimFootnotes` if there is verbatim in notes
+      (#1616).
+    + LaTeX template:  Add shorthands=off to babel options (#1648).
+    + EPUB, EPUB3 templates: Added `id="cover"` to body of cover page.
+      This aids styling, making it possible for example to set 0 margins
+      on the title page (#1758).
+    + EPUB, EPUB3 templates:  Handle structured metadata on titlepage.
+      Previously we just expected 'title', 'subtitle', 'author', 'date'.
+      Now we still support those, but also support the format recommended
+      for epub metadata in the pandoc README:
+
+        ---
+        title:
+        - type: main
+          text: My Book
+        - type: subtitle
+          text: An investigation of metadata
+        creator:
+        - role: author
+          text: John Smith
+        - role: editor
+          text: Sarah Jones
+        identifier:
+        - scheme: DOI
+          text: doi:10.234234.234/33
+        publisher:  My Press
+        rights:  (c) 2007 John Smith, CC BY-NC
+        ...
+
+  * `Text.Pandoc.Templates.getDefaultTemplate`:
+    don't fail when called with "fb2" (#1660).
+
+  * `Text.Pandoc.Parsing`:
+
+    + Fixed `inlineMath` so it handles `\text{..}` containing `$`.
+      For example: `$x = \text{the $n$th root of $y$}` (#1677).
+    + Change `parseFromString` to fail if not all input is consumed.
+      (Matthew Pickering)
+    + Moved `addWarning` from Markdown reader to `Parsing`, so it can be
+      used by more readers (API change, Daniel Bergey).
+
+  * `Text.Pandoc.Pretty`:
+
+    +  Improve performance of `realLength` (Matthew Pickering).
+    +  Make CR + BLANKLINE = BLANKLINE. This fixes an extra blank line we
+       were getting at the end of markdown fragments (as well as rst, org,
+       etc.) (#1705).
+
+  * `Text.Pandoc.MIME`:
+
+    + Add mime type for WebVTT (Jason Ronallo).
+    + Changed mime type for `otf` to `application/vnd.ms-opentype` (#1761).
+      This is needed for epub3 validation.
+
+  * `Text.Pandoc.MediaBag`:
+
+    + Fix Windows specific path problems (#1597).
+
+  * `Text.Pandoc.Shared`:
+
+    + Make `collapseFilePath` OS-agnostic (Matthew Pickering).
+
+  * Link the test suite using `-threaded`.
+    This allows the test suite to be run using `+RTS -N`.
+
+  * Added `network` dependency under `network-uri` flag in test section.
+
+  * Give better error messages when someone tries to convert from
+    pdf, doc, odt (#1683).
+
+  * Added `track` to list of tags treated by `--self-contained` (#1664).
+
+
+## pandoc 1.13.1 (2014-08-30)
+
+  * Fixed `--self-contained` with Windows paths (#1558).
+    Previously `C:\foo.js` was being wrongly interpreted as a URI.
+
+  * HTML reader:  improved handling of tags that can be block or inline.
+    Previously a section like this would be enclosed in a paragraph,
+    with RawInline for the video tags (since video is a tag that can
+    be either block or inline):
+
+        <video controls="controls">
+           <source src="../videos/test.mp4" type="video/mp4" />
+           <source src="../videos/test.webm" type="video/webm" />
+           <p>
+              The videos can not be played back on your system.<br/>
+              Try viewing on Youtube (requires Internet connection):
+              <a href="http://youtu.be/etE5urBps_w">Relative Velocity on
+        Youtube</a>.
+           </p>
+        </video>
+
+    This change will cause the video and source tags to be parsed
+    as RawBlock instead, giving better output.
+    The general change is this:  when we're parsing a "plain" sequence
+    of inlines, we don't parse anything that COULD be a block-level tag.
+
+  * Docx reader:
+
+    + Be sensitive to user styles.  Note that "Hyperlink" is
+      "blacklisted," as we don't want the default underline styling to be
+      inherited by all links by default (Jesse Rosenthal).
+    + Read single paragraph in table cell as `Plain` (Jesse Rosenthal).
+      This makes to docx reader's native output fit with the way the markdown
+      reader understands its markdown output.
+
+  * Txt2Tags reader:
+
+    + Header is now parsed only if standalone flag is set (Matthew Pickering).
+    + The header is now parsed as meta information. The first line is the
+      `title`, the second is the `author` and third line is the `date`
+      (Matthew Pickering).
+    + Corrected formatting of `%%mtime` macro (Matthew Pickering).
+    + Fixed crash when reading from stdin.
+
+  * Textile writer:  Extended the range of cases where native textile
+    tables will be used (as opposed to raw HTML):  we now handle any
+    alignment type, but only for simple tables with no captions.
+
+  * EPUB writer:  Don't use page-progression-direction in EPUB2, which
+    doesn't support it.  Also, if page-progression-direction not specified
+    in metadata, don't include the attribute even in EPUB3; not including it
+    is the same as including it with the value "default", as we did before.
+    (#1550)
+
+  * Org writer: Accept example lines with indentation at the beginning
+    (Calvin Beck).
+
+  * DokuWiki writer:
+
+    + Refactor to use Reader monad (Matthew Pickering).
+    + Avoid using raw HTML in table cells; instead, use `\\`
+      instead of newlines (Jesse Rosenthal).
+    + Properly handle HTML table cell alignments, and use spacing
+      to make the tables look prettier (#1566).
+
+  * Docx writer:
+
+    + Bibliography entries get `Bibliography` style (#1559).
+    + Implement change tracking (Jesse Rosenthal).
+
+  * LaTeX writer:
+
+    + Fixed a bug that caused a table caption to repeat across all pages
+      (Jose Luis Duran).
+    + Improved vertical spacing in tables and made it customizable using
+      standard lengths set by booktab.  See
+      <https://groups.google.com/forum/#!msg/pandoc-discuss/qMu6_5lYy0o/ZAU7lzAIKw0J>
+      (Jose Luis Duran).
+    + Added `\strut` to fix spacing in multiline tables (Jose Luis Duran).
+    + Use `\tabularnewline` instead of `\\` in table cells (Jose Luis Duran).
+    + Made horizontal rules more flexible (Jose Luis Duran).
+
+  * Text.Pandoc.MIME:
+
+    + Added `MimeType` (type synonym for `String`) and `getMimeTypeDef`.
+      Code cleanups (Artyom Kazak).
+
+  * Templates:
+
+    + LaTeX template: disable microtype protrusion for typewriter font (#1549,
+      thanks lemzwerg).
+
+  * Improved OSX build procedure.
+
+  * Added `network-uri` flag, to deal with split of `network-uri` from
+    `network`.
+
+  * Fix build dependencies for the `trypandoc` flag, so that they are
+    ignored if `trypandoc` flag is set to False (Gabor Pali).
+
+  * Updated README to remove outdated claim that `--self-contained`
+    looks in the user data directory for missing files.
+
+## pandoc 1.13.0.1 (2014-08-17)
+
+  * Docx writer:
+
+    + Fixed regression which bungled list numbering (#1544), causing
+      all lists to appear as basic ordered lists.
+    + Include row width in table rows (Christoffer Ackelman, Viktor Kronvall).
+      Added a property to all table rows where the sum of column widths
+      is specified in pct (fraction of 5000).  This helps persuade Word
+      to lay out the table with the widths we specify.
+
+  * Fixed a bug in Windows 8 which caused pandoc not to find the
+    `pandoc-citeproc` filter (#1542).
+
+  * Docx reader: miscellaneous under-the-hood improvements (Jesse Rosenthal).
+    Most significantly, the reader now uses Builder, leading to some
+    performance improvements.
+
+  * HTML reader:  Parse appropriately styled span as SmallCaps.
+
+  * Markdown writer: don't escape `$`, `^`, `~` when `tex_math_dollars`,
+    `superscript`, and `subscript` extensions, respectively, are
+    deactivated (#1127).
+
+  * Added `trypandoc` flag to build CGI executable used in the online
+    demo.
+
+  * Makefile:  Added 'quick', 'osxpkg' targets.
+
+  * Updated README in templates to indicate templates license.
+    The templates are dual-licensed, BSD3 and GPL2+.
+
+## pandoc 1.13 (15 August 2014)
+
+### New features
+
+  * Added `docx` as an input format (Jesse Rosenthal).  The docx
+    reader includes conversion of native Word equations to pandoc
+    LaTeX `Math` elements.  Metadata is taken from paragraphs at the
+    beginning of the document with styles `Author`, `Title`, `Subtitle`,
+    `Date`, and `Abstract`.
+
+  * Added `epub` as an input format (Matthew Pickering).  The epub
+    reader includes conversion of MathML to pandoc LaTeX `Math`
+    elements.
+
+  * Added `t2t` (Txt2Tags) as an input format (Matthew Pickering).
+    Txt2tags is a lightweight markup format described at
+    <http://txt2tags.org/>.
+
+  * Added `dokuwiki` as an output format (Clare Macrae).
+
+  * Added `haddock` as an output format.
+
+  * Added `--extract-media` option to extract media contained in a zip
+    container (docx or epub) while adjusting image paths to point to the
+    extracted images.
+
+  * Added a new markdown extension, `compact_definition_lists`, that
+    restores the syntax for definition lists of pandoc 1.12.x, allowing
+    tight definition lists with no blank space between items, and
+    disallowing lazy wrapping.  (See below under behavior changes.)
+
+  * Added an extension `epub_html_exts` for parsing HTML in EPUBs.
+
+  * Added extensions `native_spans` and `native_divs` to activate
+    parsing of material in HTML span or div tags as Pandoc Span
+    inlines or Div blocks.
+
+  * `--trace` now works with the Markdown, HTML, Haddock, EPUB,
+    Textile, and MediaWiki readers.  This is an option intended
+    for debugging parsing problems; ordinary users should not need
+    to use it.
+
+### Behavior changes
+
+  * Changed behavior of the `markdown_attribute` extension, to bring
+    it in line with PHP markdown extra and multimarkdown.  Setting
+    `markdown="1"` on an outer tag affects all contained tags,
+    recursively, until it is reversed with `markdown="0"` (#1378).
+
+  * Revised markdown definition list syntax (#1429).  Both the reader
+    and writer are affected.  This change brings pandoc's definition list
+    syntax into alignment with that used in PHP markdown extra and
+    multimarkdown (with the exception that pandoc is more flexible about
+    the definition markers, allowing tildes as well as colons).  Lazily
+    wrapped definitions are now allowed.  Blank space is required
+    between list items.  The space before a definition is used to determine
+    whether it is a paragraph or a "plain" element.  **WARNING: This change
+    may break existing documents!**  Either check your documents for
+    definition lists without blank space between items, or use
+    `markdown+compact_definition_lists` for the old behavior.
+
+  * `.numberLines` now works in fenced code blocks even if no language
+    is given (#1287, jgm/highlighting-kate#40).
+
+  * Improvements to `--filter`:
+
+    + Don't search PATH for a filter with an explicit path.
+      This fixed a bug wherein `--filter ./caps.py` would run `caps.py` from
+      the system path, even if there was a `caps.py` in the working directory.
+    + Respect shebang if filter is executable (#1389).
+    + Don't print misleading error message.
+      Previously pandoc would say that a filter was not found,
+      even in a case where the filter had a syntax error.
+
+  * HTML reader:
+
+    + Parse `div` and `span` elements even without `--parse-raw`,
+      provided `native_divs` and `native_spans` extensions are set.
+      Motivation:  these now generate native pandoc Div and Span
+      elements, not raw HTML.
+    + Parse EPUB-specific elements if the `epub_html_exts`
+      extension is enabled.  These include `switch`, `footnote`,
+      `rearnote`, `noteref`.
+
+  * Org reader:
+
+    + Support for inline LaTeX.  Inline LaTeX is now accepted and parsed by the
+      org-mode reader.  Both math symbols (like `\tau`) and LaTeX commands (like
+      `\cite{Coffee}`), can be used without any further escaping (Albert
+      Krewinkel).
+
+  * Textile reader and writer:
+
+    + The `raw_tex` extension is no longer set by default.  You can
+      enable it with `textile+raw_tex`.
+
+  * DocBook reader:
+
+    + Support `equation`, `informalequation`, `inlineequation` elements with
+      `mml:math` content.  This is converted into LaTeX and put into a Pandoc
+      Math inline.
+
+  * Revised `plain` output, largely following the style of Project
+    Gutenberg:
+
+    + Emphasis is rendered with `_underscores_`, strong emphasis
+      with ALL CAPS.
+    + Headings are rendered differently, with space to set them off,
+      not with setext style underlines. Level 1 headers are ALL CAPS.
+    + Math is rendered using unicode when possible, but without the
+      distracting emphasis markers around variables.
+    + Footnotes use a regular `[n]` style.
+
+  * Markdown writer:
+
+    + Horizontal rules are now a line across the whole page.
+    + Prettier pipe tables.  Columns are now aligned  (#1323).
+    + Respect the `raw_html` extension.  `pandoc -t markdown-raw_html`
+      no longer emits any raw HTML, including span and div tags
+      generated by Span and Div elements.
+    + Use span with style for `SmallCaps` (#1360).
+
+  * HTML writer:
+
+    + Autolinks now have class `uri`, and email autolinks have class
+      `email`, so they can be styled.
+
+  * Docx writer:
+
+    + Document formatting is carried over from `reference.docx`.
+      This includes margins, page size, page orientation, header,
+      and footer, including images in headers and footers.
+    + Include abstract (if present) with `Abstract` style (#1451).
+    + Include subtitle (if present) with `Subtitle` style, rather
+      than tacking it on to the title (#1451).
+
+  * Org writer:
+
+    + Write empty span elements with an id attribute as org anchors.
+      For example `Span ("uid",[],[]) []` becomes `<<uid>>`.
+
+  * LaTeX writer:
+
+    + Put table captions above tables, to match the conventional
+      standard.  (Previously they appeared below tables.)
+    + Use `\(..\)` instead of `$..$` for inline math (#1464).
+    + Use `\nolinkurl` in email autolinks.  This allows them to be styled
+      using `\urlstyle{tt}`.  Thanks to Ulrike Fischer for the solution.
+    + Use `\textquotesingle` for `'` in inline code.  Otherwise we get
+      curly quotes in the PDF output (#1364).
+    + Use `\footnote<.>{..}` for notes in beamer, so that footnotes
+      do not appear before the overlays in which their markers appear
+      (#1525).
+    + Don't produce a `\label{..}` for a Div or Span element.  Do produce
+      a `\hyperdef{..}` (#1519).
+
+  * EPUB writer:
+
+    + If the metadata includes `page-progression-direction` (which can be
+      `ltr` or `rtl`, the `page-progression-direction` attribute will
+      be set in the EPUB spine (#1455).
+
+  * Custom lua writers:
+
+    + Custom writers now work with `--template`.
+    + Removed HTML header scaffolding from `sample.lua`.
+    + Made citation information available in lua writers.
+
+  * `--normalize` and `Text.Pandoc.Shared.normalize` now consolidate
+    adjacent `RawBlock`s when possible.
+
+### API changes
+
+  * Added `Text.Pandoc.Readers.Docx`, exporting `readDocx` (Jesse Rosenthal).
+
+  * Added `Text.Pandoc.Readers.EPUB`, exporting `readEPUB` (Matthew
+    Pickering).
+
+  * Added `Text.Pandoc.Readers.Txt2Tags`, exporting `readTxt2Tags` (Matthew
+    Pickering).
+
+  * Added `Text.Pandoc.Writers.DokuWiki`, exporting `writeDokuWiki`
+    (Clare Macrae).
+
+  * Added `Text.Pandoc.Writers.Haddock`, exporting `writeHaddock`.
+
+  * Added `Text.Pandoc.MediaBag`, exporting `MediaBag`, `lookupMedia`,
+    `insertMedia`, `mediaDirectory`, `extractMediaBag`.  The docx and epub
+    readers return a pair of a `Pandoc` document and a `MediaBag` with
+    the media resources they contain.  This can be extracted using
+    `--extract-media`.  Writers that incorporate media (PDF, Docx,
+    ODT, EPUB, RTF, or HTML formats with `--self-contained`) will look
+    for resources in the `MediaBag` generated by the reader, in addition to
+    the file system or web.
+
+  * `Text.Pandoc.Readers.TexMath`: Removed deprecated `readTeXMath`.
+    Renamed `readTeXMath'` to `texMathToInlines`.
+
+  * `Text.Pandoc`: Added `Reader` data type (Matthew Pickering).
+    `readers` now associates names of readers with `Reader`
+     structures.  This allows inclusion of readers, like the docx
+     reader, that take binary rather than textual input.
+
+  * `Text.Pandoc.Shared`:
+
+    + Added `capitalize` (Artyom Kazak), and replaced uses of
+      `map toUpper` (which give bad results for many languages).
+    + Added `collapseFilePath`, which removes intermediate `.` and
+      `..` from a path (Matthew Pickering).
+    + Added `fetchItem'`, which works like `fetchItem` but searches
+      a `MediaBag` before looking on the net or file system.
+    + Added `withTempDir`.
+    + Added `removeFormatting`.
+    + Added `extractSpaces` (from HTML reader) and generalized its type
+      so that it can be used by the docx reader (Matthew Pickering).
+    + Added `ordNub`.
+    + Added `normalizeInlines`, `normalizeBlocks`.
+    + `normalize` is now `Pandoc -> Pandoc` instead of
+      `Data a :: a -> a`.  Some users may need to change their uses of
+      `normalize` to the newly exported `normalizeInlines` or
+      `normalizeBlocks`.
+
+  * `Text.Pandoc.Options`:
+
+    + Added `writerMediaBag` to `WriterOptions`.
+    + Removed deprecated and no longer used `readerStrict` in
+      `ReaderOptions`.  This is handled by `readerExtensions` now.
+    + Added `Ext_compact_definition_lists`.
+    + Added `Ext_epub_html_exts`.
+    + Added `Ext_native_divs` and `Ext_native_spans`.
+      This allows users to turn off the default pandoc behavior of
+      parsing contents of div and span tags in markdown and HTML
+      as native pandoc Div blocks and Span inlines.
+
+  * `Text.Pandoc.Parsing`:
+
+    + Generalized `readWith` to `readWithM` (Matthew Pickering).
+    + Export `runParserT` and `Stream` (Matthew Pickering).
+    + Added `HasQuoteContext` type class (Matthew Pickering).
+    + Generalized types of `mathInline`, `smartPunctuation`, `quoted`,
+      `singleQuoted`, `doubleQuoted`, `failIfInQuoteContext`,
+      `applyMacros` (Matthew Pickering).
+    + Added custom `token` (Matthew Pickering).
+    + Added `stateInHtmlBlock` to `ParserState`.  This is used to keep
+      track of the ending tag we're waiting for when we're parsing inside
+      HTML block tags.
+    + Added `stateMarkdownAttribute` to `ParserState`. This is used
+      to keep track of whether the markdown attribute has been set in
+      an enclosing tag.
+    + Generalized type of `registerHeader`, using new type classes
+      `HasReaderOptions`, `HasIdentifierList`, `HasHeaderMap` (Matthew
+      Pickering).  These allow certain common functions to be reused
+      even in parsers that use custom state (instead of `ParserState`),
+      such as the MediaWiki reader.
+    + Moved `inlineMath`, `displayMath` from Markdown reader to Parsing,
+      and generalized their types (Matthew Pickering).
+
+  * `Text.Pandoc.Pretty`:
+
+    + Added `nestle`.
+    + Added `blanklines`, which guarantees a certain number of blank lines
+      (and no more).
+
+### Bug fixes
+
+  * Markdown reader:
+
+    + Fixed parsing of indented code in list items.  Indented code
+      at the beginning of a list item must be indented eight spaces
+      from the margin (or edge of the container), or four spaces
+      from the list marker, whichever is greater.
+    + Fixed small bug in HTML parsing with `markdown_attribute`, which
+      caused incorrect tag nesting for input like
+      `<aside markdown="1">*hi*</aside>`.
+    + Fixed regression with intraword underscores (#1121).
+    + Improved parsing of inline links containing quote characters (#1534).
+    + Slight rewrite of `enclosure`/`emphOrStrong` code.
+    + Revamped raw HTML block parsing in markdown (#1330).
+      We no longer include trailing spaces and newlines in the
+      raw blocks.  We look for closing tags for elements (but without
+      backtracking).  Each block-level tag is its own `RawBlock`;
+      we no longer try to consolidate them (though `--normalize` will do so).
+    + Combine consecutive latex environments.  This helps when you have
+      two minipages which can't have blank lines between them (#690, #1196).
+    + Support smallcaps through span.
+      `<span style="font-variant:small-caps;">foo</span>` will be
+      parsed as a `SmallCaps` inline, and will work in all output
+      formats that support small caps (#1360).
+    + Prevent spurious line breaks after list items (#1137).  When the
+      `hard_line_breaks` option was specified, pandoc would formerly
+      produce a spurious line break after a tight list item.
+    + Fixed table parsing bug (#1333).
+    + Handle `c++` and `objective-c` as language identifiers in
+      github-style fenced blocks (#1318).
+    + Inline math must have nonspace before final `$` (#1313).
+
+  * LaTeX reader:
+
+    + Handle comments at the end of tables.  This resolves the issue
+      illustrated in <http://stackoverflow.com/questions/24009489>.
+    + Correctly handle table rows with too few cells.  LaTeX seems to
+      treat them as if they have empty cells at the end  (#241).
+    + Handle leading/trailing spaces in `\emph` better.
+      `\emph{ hi }` gets parsed as `[Space, Emph [Str "hi"], Space]`
+      so that we don't get things like `* hi *` in markdown output.
+      Also applies to `textbf` and some other constructions (#1146).
+    + Don't assume preamble doesn't contain environments (#1338).
+    + Allow (and discard) optional argument for `\caption` (James Aspnes).
+
+  * HTML reader:
+
+    + Fixed major parsing problem with HTML tables.  Table cells were
+      being combined into one cell (#1341).
+    + Fixed performance issue with malformed HTML tables.
+      We let a `</table>` tag close an open `<tr>` or `<td>` (#1167).
+    + Allow space between `<col>` and `</col>`.
+    + Added `audio` and `source` in `eitherBlockOrInline`.
+    + Moved `video`, `svg`, `progress`, `script`, `noscript`, `svg` from
+      `blockTags` to `eitherBlockOrInline`.
+    + `map` and `object` were mistakenly in both lists; they have been removed
+      from `blockTags`.
+    + Ignore `DOCTYPE` and `xml` declarations.
+
+  * MediaWiki reader:
+
+    + Don't parse backslash escapes inside `<source>` (#1445).
+    + Tightened up template parsing.
+      The opening `{{` must be followed by an alphanumeric or `:`.
+      This prevents the exponential slowdown in #1033.
+    + Support "Bild" for images.
+
+  * DocBook reader:
+
+    + Better handle elements inside code environments.  Pandoc's document
+      model does not allow structure inside code blocks, but at least this way
+      we preserve the text (#1449).
+    + Support `<?asciidoc-br?>` (#1236).
+
+  * Textile reader:
+
+    + Fixed list parsing. Lists can now start without an intervening
+      blank line (#1513).
+    + HTML block-level tags that do not start a line are parsed as
+      inline HTML and do not interrupt paragraphs (as in RedCloth).
+
+  * Org reader:
+
+    + Make tildes create inline code (#1345).  Also relabeled `code` and
+      `verbatim` parsers to accord with the org-mode manual.
+    + Respect `:exports` header argument in code blocks (Craig Bosma).
+    + Fixed tight lists with sublists (#1437).
+
+  * EPUB writer:
+
+    + Avoid excess whitespace in `nav.xhtml`.  This should improve
+      TOC view in iBooks (#1392).
+    + Fixed regression on cover image.
+      In 1.12.4 and 1.12.4.2, the cover image would not appear properly,
+      because the metadata id was not correct.  Now we derive the id from the
+      actual cover image filename, which we preserve rather than using
+      "cover-image."
+    + Keep newlines between block elements.  This allows
+      easier diff-ability (#1424).
+    + Use `stringify` instead of custom `plainify`.
+    + Use `renderTags'` for all tag rendering.  This properly handles tags
+      that should be self-closing.  Previously `<hr/>` would appear in EPUB
+      output as `<hr></hr>` (#1420).
+    + Better handle HTML media tags.
+    + Handle multiple dates with OPF `event` attributes.  Note: in EPUB3 we
+      can have only one dc:date, so only the first one is used.
+
+  * LaTeX writer:
+
+    + Correctly handle figures in notes.  Notes can't contain figures in
+      LaTeX, so we fake it to avoid an error  (#1053).
+    + Fixed strikeout + highlighted code (#1294).
+      Previously strikeout highlighted code caused an error.
+
+  * ConTeXt writer:
+
+    + Improved detection of autolinks with URLs containing escapes.
+
+  * RTF writer:
+
+    + Improved image embedding: `fetchItem'` is now used to get the
+      images, and calculated image sizes are indicated in the RTF.
+    + Avoid extra paragraph tags in metadata (#1421).
+
+  * HTML writer:
+
+    + Deactivate "incremental" inside slide speaker notes (#1394).
+    + Don't include empty items in the table of contents for
+      slide shows.  (These would result from creating a slide
+      using a horizontal rule.)
+
+  * MediaWiki writer:
+
+    + Minor renaming of `st` prefixed names.
+
+  * AsciiDoc writer:
+
+    + Double up emphasis and strong emphasis markers in intraword
+      contexts, as required by asciidoc (#1441).
+
+  * Markdown writer:
+
+    + Avoid wrapping that might start a list, blockquote, or header (#1013).
+    + Use Span instead of (hackish) `SmallCaps` in `plainify`.
+    + Don't use braced attributes for fenced code (#1416).
+      If `Ext_fenced_code_attributes` is not set, the first class
+      attribute will be printed after the opening fence as a bare word.
+    + Separate adjacent lists of the same kind with an HTML comment (#1458).
+
+  * PDF writer:
+
+    + Fixed treatment of data uris for images (#1062).
+
+  * Docx writer:
+
+    + Use Compact style for empty table cells (#1353).
+      Otherwise we get overly tall lines when there are empty
+      table cells and the other cells are compact.
+    + Create overrides per-image for `media/` in reference docx.
+      This should be somewhat more robust and cover more types of images.
+    + Improved `entryFromArchive` to avoid an unneeded parse.
+    + Section numbering carries over from reference.docx (#1305).
+    + Simplified `abstractNumId` numbering.  Instead of sequential numbering,
+      we assign numbers based on the list marker styles.
+
+  * `Text.Pandoc.Options`:
+
+    + Removed `Ext_fenced_code_attributes` from `markdown_github`
+      extensions.
+
+  * `Text.Pandoc.ImageSize`:
+
+    + Use default instead of failing if image size not found
+      in exif header (#1358).
+    + ignore unknown exif header tag rather than crashing.
+      Some images seem to have tag type of 256, which was causing
+      a runtime error.
+
+  * `Text.Pandoc.Shared`:
+
+    + `fetchItem`:  unescape URI encoding before reading local file (#1427).
+    + `fetchItem`:  strip a fragment like `?#iefix` from the extension before
+      doing mime lookup, to improve mime type guessing.
+    + Improved logic of `fetchItem`:  absolute URIs are fetched from the net;
+      other things are treated as relative URIs if `sourceURL` is `Just _`,
+      otherwise as file paths on the local file system.
+    + `fetchItem` now properly handles links without a protocol (#1477).
+    + `fetchItem` now escapes characters not allowed in URIs before trying
+      to parse the URIs.
+    + Fixed runtime error with `compactify'DL` on certain lists (#1452).
+
+  * `pandoc.hs`: Don't strip path off of `writerSourceURL`: the path is
+    needed to resolve relative URLs when we fetch resources (#750).
+
+  * `Text.Pandoc.Parsing`
+
+    + Simplified `dash` and `ellipsis` (#1419).
+    + Removed `(>>~)` in favor of the equivalent `(<*)` (Matthew Pickering).
+    + Generalized functions to use `ParsecT` (Matthew Pickering).
+    + Added `isbn` and `pmid` to list of recognized schemes (Matthew
+      Pickering).
+
+### Template changes
+
+  * Added haddock template.
+  * EPUB3:  Added `type` attribute to `link` tags.  They are supposed to
+    be "advisory" in HTML5, but kindlegen seems to require them.
+  * EPUB3:  Put title page in section with `epub:type="titlepage"`.
+  * LaTeX: Made `\subtitle` work properly (#1327).
+  * LaTeX/Beamer: remove conditional around date (#1321).
+  * LaTeX:  Added `lot` and `lof` variables, which can be set to
+    get `\listoftables` and `\listoffigures` (#1407).  Note that
+    these variables can be set at the command line with `-Vlot -Vlof`
+    or in YAML metadata.
+
+### Under the hood improvements
+
+  * Rewrote normalize for efficiency (#1385).
+
+  * Rewrote Haddock reader to use `haddock-library` (#1346).
+
+    + This brings pandoc's rendering of haddock markup in line
+      with the new haddock.
+    + Fixed line breaks in `@` code blocks.
+    + alex and happy are no longer build-depends.
+
+  * Added `Text.Pandoc.Compat.Directory` to allow building against
+    different versions of the `directory` library.
+
+  + Added `Text.Pandoc.Compat.Except` to allow building against
+    different versions of `mtl`.
+
+  * Code cleanup in some writers, using Reader monad to avoid
+    passing options parameter around (Matej Kollar).
+
+  * Improved readability in `pandoc.hs`.
+
+  * Miscellaneous code cleanups (Artyom Kazak).
+
+  * Avoid `import Prelude hiding (catch)` (#1309, thanks to Michael
+    Thompson).
+
+  * Changed `http-conduit` flag to `https`.  Depend on `http-client`
+    and `http-client-tls` instead of `http-conduit`.  (Note:  pandoc still
+    depends on `conduit` via `yaml`.)
+
+  * Require `highlighting-kate >= 0.5.8.5` (#1271, #1317, Debian #753299).
+    This change to highlighting-kate means that PHP fragments no longer need
+    to start with `<?php`.  It also fixes a serious bug causing failures with
+    ocaml and fsharp.
+
+  * Require latest `texmath`.  This fixes `\tilde{E}` and allows
+    `\left` to be used with `]`, `)` etc. (#1319), among many other
+    improvements.
+
+  * Require latest `zip-archive`.  This has fixes for unicode path names.
+
+  * Added tests for plain writer.
+
+  * `Text.Pandoc.Templates`:
+
+    + Fail informatively on template syntax errors.
+      With the move from parsec to attoparsec, we lost good error
+      reporting.  In fact, since we weren't testing for end of input,
+      malformed templates would fail silently.  Here we revert back to
+      Parsec for better error messages.
+    + Use `ordNub` (#1022).
+
+  * Benchmarks:
+
+    + Made benchmarks compile again (Artyom Kazak).
+    + Fixed so that the failure of one benchmark does not prevent others
+      from running (Artyom Kazak).
+    + Use `nfIO` instead of the `getLength` trick to force full evaluation.
+    + Changed benchmark to use only the test suite, so that benchmarks
+      run more quickly.
+
+  * Windows build script:
+
+    + Add `-windows` to file name.
+    + Use one install command for pandoc, pandoc-citeproc.
+    + Force install of pandoc-citeproc.
+
+  * `make_osx_package`:  Call zip file `pandoc-VERSION-osx.zip`.
+    The zip should not be named `SOMETHING.pkg.zip`, or OSX finder
+    will extract it into a folder named `SOMETHING.pkg`, which it
+    will interpret as a defective package (#1308).
+
+  * `README`:
+
+    + Made headers for all extensions so they have IDs and can be
+      linked to (Beni Cherniavsky-Paskin).
+    + Fixed typos (Phillip Alday).
+    + Fixed documentation of attributes (#1315).
+    + Clarified documentation on small caps (#1360).
+    + Better documentation for `fenced_code_attributes` extension
+      (Caleb McDaniel).
+    + Documented fact that you can put YAML metadata in a separate file
+      (#1412).
+
+
+## pandoc 1.12.4.2 (2014-05-14)
+
+  * Require highlighting-kate >= 0.5.8.  Fixes a performance regression.
+
+  * Shared:  `addMetaValue` now behaves slightly differently:
+    if both the new and old values are lists, it concatenates their
+    contents to form a new list.
+
+  * LaTeX reader:
+
+    + Set `bibliography` in metadata from `\bibliography` or
+      `\addbibresource` command.
+    + Don't error on `%foo` with no trailing newline.
+
+  * Org reader:
+
+    + Support code block headers (`#+BEGIN_SRC ...`) (Albert Krewinkel).
+    + Fix parsing of blank lines within blocks (Albert Krewinkel).
+    + Support pandoc citation extension (Albert Krewinkel).  This can
+      be turned off by specifying `org-citation` as the input format.
+
+  * Markdown reader:
+
+    + `citeKey` moved to `Text.Pandoc.Parsing` so it can be used by
+      other readers (Albert Krewinkel).
+
+  * `Text.Pandoc.Parsing`:
+
+    + Added `citeKey` (see above).
+    + Added `HasLastStrPosition` type class and `updateLastStrPos`
+      and `notAfterString` functions.
+
+  * Updated copyright notices (Albert Krewinkel).
+
+  * Added default.icml to data files so it installs with the package.
+
+  * OSX package:
+
+    + The binary is now built with options to ensure that it can be
+      used with OSX 10.6+.
+    + Moved OSX package materials to osx directory.
+    + Added OSX package uninstall script, included in the zip container
+      (thanks to Daniel T. Staal).
+
+## pandoc 1.12.4 (2014-05-07)
+
+  * Made it possible to run filters that aren't executable
+    (#1096). Pandoc first tries to find the executable (searching
+    the path if path isn't given). If it fails, but the file
+    exists and has a `.py`, `.pl`, `.rb`, `.hs`, or `.php`
+    extension, pandoc runs the filter using the appropriate
+    interpreter. This should make it easier to use filters on
+    Windows, and make it more convenient for everyone.
+
+  * Added Emacs org-mode reader (Albert Krewinkel).
+
+  * Added InDesign ICML Writer (mb21).
+
+  * MediaWiki reader:
+
+    + Accept image links in more languages (Jaime Marquínez Ferrándiz).
+    + Fixed bug in certain nested lists (#1213).  If a level 2 list was
+      followed by a level 1 list, the first item of the level 1 list
+      would be lost.
+    + Handle table rows containing just an HTML comment (#1230).
+
+  * LaTeX reader:
+
+    + Give better location information on errors, pointing to line
+      numbers within included files (#1274).
+    + LaTeX reader:  Better handling of `table` environment (#1204).
+      Positioning options no longer rendered verbatim.
+    + Better handling of figure and table with caption (#1204).
+    + Handle `@{}` and `p{length}` in tabular.  The length is not actually
+      recorded, but at least we get a table (#1180).
+    + Properly handle `\nocite`.  It now adds a `nocite` metadata
+      field.  Citations there will appear in the bibliography but not
+      in the text (unless you explicitly put a `$nocite$` variable
+      in your template).
+
+  * Markdown reader:
+
+    + Ensure that whole numbers in YAML metadata are rendered without
+      decimal points.  (This became necessary with changes to aeson
+      and yaml libraries.  aeson >= 0.7 and yaml >= 0.8.8.2 are now required.)
+    + Fixed regression on line breaks in strict mode (#1203).
+    + Small efficiency improvements.
+    + Improved parsing of nested `div`s.  Formerly a closing `div` tag
+      would be missed if it came right after other block-level tags.
+    + Avoid backtracking when closing `</div>` not found.
+    + Fixed bug in reference link parsing in `markdown_mmd`.
+    + Fixed a bug in list parsing (#1154).  When reading a raw list
+      item, we now strip off up to 4 spaces.
+    + Fixed parsing of empty reference link definitions (#1186).
+    + Made one-column pipe tables work (#1218).
+
+  * Textile reader:
+
+    + Better support for attributes.  Instead of being ignored, attributes
+      are now parsed and included in Span inlines.  The output will be a bit
+      different from stock textile: e.g. for `*(foo)hi*`, we'll get
+      `<em><span class="foo">hi</span></em>` instead of
+      `<em class="foo">hi</em>`.  But at least the data is not lost.
+    + Improved treatment of HTML spans (%) (#1115).
+    + Improved link parsing.  In particular we now pick up on attributes.
+      Since pandoc links can't have attributes, we enclose the whole link in
+      a span if there are attributes (#1008).
+    + Implemented correct parsing rules for inline markup (#1175, Matthew
+      Pickering).
+    + Use Builder (Matthew Pickering).
+
+  * DocBook reader:
+
+    + Better treatment of `formalpara`.  We now emit the title (if present)
+      as a separate paragraph with boldface text (#1215).
+    + Set metadata `author` not `authors`.
+    + Added recognition of `authorgroup` and `releaseinfo` elements (#1214,
+      Matthew Pickering).
+    + Converted current meta information parsing in DocBook to a more
+      extensible version which is aware of the more recent meta
+      representation (Matthew Pickering).
+
+  * HTML reader:
+
+    + Require tagsoup 0.13.1, to fix a bug with parsing of script tags
+      (#1248).
+    + Treat processing instructions & declarations as block.  Previously
+      these were treated as inline, and included in paragraph tags in HTML
+      or DocBook output, which is generally not what is wanted (#1233).
+    + Updated `closes` with rules from HTML5 spec.
+    + Use Builder (Matthew Pickering, #1162).
+
+  * RST reader:
+
+    + Remove duplicate `http` in PEP links (Albert Krewinkel).
+    + Make rst figures true figures (#1168, CasperVector)
+    + Enhanced Pandoc's support for rST roles (Merijn Verstaaten).
+      rST parser now supports: all built-in rST roles, new role definition,
+      role inheritance, though with some limitations.
+    + Use `author` rather than `authors` in metadata.
+    + Better handling of directives.  We now correctly handle field
+      lists that are indented more than three spaces.  We treat an
+      `aafig` directive as a code block with attributes, so it can be
+      processed in a filter (#1212).
+
+  * LaTeX writer:
+
+    + Mark span contents with label if span has an ID (Albert Krewinkel).
+    + Made `--toc-depth` work well with books in latex/pdf output (#1210).
+    + Handle line breaks in simple table cells (#1217).
+    + Workaround for level 4-5 headers in quotes.  These previously produced
+      invalid LaTeX: `\paragraph` or `\subparagraph` in a `quote` environment.
+      This adds an `mbox{}` in these contexts to work around the problem.
+      See <http://tex.stackexchange.com/a/169833/22451> (#1221).
+    + Use `\/` to avoid en-dash ligature instead of `-{}-` (Vaclav Zeman).
+      This is to fix LuaLaTeX output. The `-{}-` sequence does not avoid the
+      ligature with LuaLaTeX but `\/` does.
+    + Fixed string escaping in `hyperref` and `hyperdef` (#1130).
+
+  * ConTeXt writer:  Improved autolinks (#1270).
+
+  * DocBook writer:
+
+    + Improve handling of hard line breaks in Docbook writer
+      (Neil Mayhew).  Use a `<literallayout>` for the entire paragraph, not
+      just for the newline character.
+    + Don't let line breaks inside footnotes influence the enclosing
+      paragraph (Neil Mayhew).
+    + Distinguish tight and loose lists in DocBook output, using
+      `spacing="compact"` (Neil Mayhew, #1250).
+
+  * Docx writer:  When needed files are not present in the user's
+    `reference.docx`, fall back on the versions in the `reference.docx`
+    in pandoc's data files. This fixes a bug that occurs when a
+    `reference.docx` saved by LibreOffice is used. (#1185)
+
+  * EPUB writer:
+
+    + Include extension in epub ids.  This fixes a problem with duplicate
+      extensions for fonts and images with the same base name but different
+      extensions (#1254).
+    + Handle files linked in raw `img` tags (#1170).
+    + Handle media in `audio` source tags (#1170).
+      Note that we now use a `media` directory rather than `images`.
+    + Incorporate files linked in `video` tags (#1170).  `src` and `poster`
+      will both be incorporated into `content.opf` and the epub container.
+
+  * HTML writer:
+
+    + Add colgroup around col tags (#877).  Also affects EPUB writer.
+    + Fixed bug with unnumbered section headings.  Unnumbered section
+      headings (with class `unnumbered`) were getting numbers.
+    + Improved detection of image links. Previously image links with
+      queries were not recognized, causing `<embed>` to be used instead
+      of `<img>`.
+
+  * Man writer:  Ensure that terms in definition lists aren't line wrapped
+    (#1195).
+
+  * Markdown writer:
+
+    + Use proper escapes to avoid unwanted lists (#980).  Previously we used
+      0-width spaces, an ugly hack.
+    + Use longer backtick fences if needed (#1206).  If the content contains a
+      backtick fence and there are attributes, make sure longer fences are
+      used to delimit the code.  Note:  This works well in pandoc, but github
+      markdown is more limited, and will interpret the first string of three
+      or more backticks as ending the code block.
+
+  * RST writer:  Avoid stack overflow with certain tables (#1197).
+
+  * RTF writer:  Fixed table cells containing paragraphs.
+
+  * Custom writer:
+
+    + Correctly handle UTF-8 in custom lua scripts (#1189).
+    + Fix bugs with lua scripts with mixed-case filenames and
+      paths containing `+` or `-` (#1267).  Note that `getWriter`
+      in `Text.Pandoc` no longer returns a custom writer on input
+      `foo.lua`.
+
+  * AsciiDoc writer:  Handle multiblock and empty table cells
+    (#1245, #1246).  Added tests.
+
+  * `Text.Pandoc.Options`: Added `readerTrace` to `ReaderOptions`
+
+  * `Text.Pandoc.Shared`:
+
+    + Added `compactify'DL` (formerly in markdown reader) (Albert Krewinkel).
+    + Fixed bug in `toRomanNumeral`:  numbers ending with '9' would
+      be rendered as Roman numerals ending with 'IXIV' (#1249).  Thanks to
+      Jesse Rosenthal.
+    + `openURL`: set proxy with value of http_proxy env variable (#1211).
+      Note:  proxies with non-root paths are not supported, due to
+      limitations in `http-conduit`.
+
+  * `Text.Pandoc.PDF`:
+
+    + Ensure that temp directories deleted on Windows (#1192).  The PDF is
+      now read as a strict bytestring, ensuring that process ownership will
+      be terminated, so the temp directory can be deleted.
+    + Use `/` as path separators in a few places, even on Windows.
+      This seems to be necessary for texlive (#1151, thanks to Tim Lin).
+    + Use `;` for `TEXINPUTS` separator on Windows (#1151).
+    + Changes to error reporting, to handle non-UTF8 error output.
+
+  * `Text.Pandoc.Templates`:
+
+    + Removed unneeded datatype context (Merijn Verstraaten).
+
+    + YAML objects resolve to "true" in conditionals (#1133).
+      Note:  If `address` is a YAML object and you just have `$address$`
+      in your template, the word `true` will appear, which may be
+      unexpected.  (Previously nothing would appear.)
+
+  * `Text.Pandoc.SelfContained`:  Handle `poster` attribute in `video`
+    tags (#1188).
+
+  * `Text.Pandoc.Parsing`:
+
+    + Made `F` an instance of Applicative (#1138).
+    + Added `stateCaption`.
+    + Added `HasMacros`, simplified other typeclasses.
+      Removed `updateHeaderMap`, `setHeaderMap`, `getHeaderMap`,
+      `updateIdentifierList`, `setIdentifierList`, `getIdentifierList`.
+    + Changed the smart punctuation parser to return `Inlines`
+      rather than `Inline` (Matthew Pickering).
+    + Changed `HasReaderOptions`, `HasHeaderMap`, `HasIdentifierList`
+      from typeclasses of monads to typeclasses of states.  This simplifies
+      the instance definitions and provides more flexibility.  Generalized
+      type of `getOption` and added a default definition.  Removed
+      `askReaderOption`.  Added `extractReaderOption`.  Added
+      `extractHeaderMap` and `updateHeaderMap` in `HasHeaderMap`.
+      Gave default definitions for `getHeaderMap`, `putHeaderMap`,
+      `modifyHeaderMap`.  Added `extractIdentifierList` and
+      `updateIdentifierList` in `HasIdentifierList`.  Gave defaults
+      for `getIdentifierList`, `putIdentifierList`, and
+      `modifyIdentifierList`.  The ultimate goal here is to allow different
+      parsers to use their own, tailored parser states (instead of
+      `ParserState`) while still using shared functions.
+
+  * Template changes:
+
+    + LaTeX template: Use `fontenc` package only with `pdflatex` (#1164).
+    + LaTeX template:  Add `linestretch` and `fontfamily` variables.
+    + LaTeX template:  Conditionalize author and date commands.
+    + Beamer template: Consistent styles for figure and table captions
+      (aaronwolen).
+    + LaTeX and beamer template:  Adjust widths correctly for oversized
+      images.  Use `\setkeys{Gin}{}` to set appropriate defaults for
+      `\includegraphics` (Yihui Xie, Garrick Aden-Buie).  Load
+      `upquote` only after `fontenc` (Yihui Xie).
+    + Beamer template: Added caption package (#1200).
+    + Beamer template:  changes for better unicode handling (KarolS).
+    + DocBook template:  use `authorgroup` if there are authors.
+    + revealjs template: Move `include-after` to end (certainlyakey).
+    + revealjs template: Fixed PDF print function (#1220, kevinkenan).
+
+  * Bumped version bounds of dependencies.
+
+  * Added a `--trace` command line option, for debugging backtracking
+    bugs.  So far this only works with the markdown reader.
+
+  * MathMLinHTML:  Fixed deprecation warning (#362, gwern, Albert Krewinkel).
+
+  * Updated travis script to test with multiple GHC versions.
+
+  * Force failure of a Travis build if GHC produces warnings (Albert
+    Krewinkel).
+
+  * Add `.editorconfig` (Albert Krewinkel).
+    See <http://editorconfig.org/> for details.
+
+  * Give more useful error message if '-t pdf' is specified (#1155).
+
+  * Added `Cite`, `SmallCaps` to `Arbitrary` instance (#1269).
+
+  * Allow `html4` as a synonym of `html` as a reader (it already works
+    as a writer).
+
+  * README:
+
+    + Added an explanation of how to use YAML metadata to
+      force items to appear in the bibliography without citations in
+      the text (like LaTeX `\nocite`).
+    + Added note to `--bibtex/--natbib`: not for use in making PDF
+      (#1194, thanks to nahoj).
+    + Added explanatory notes about `--natbib` and `--biblatex`.
+    + Added specification of legal syntax for citation keys.
+    + Fixed variable defaults documentation (Albert Krewinkel).
+
+  * Removed copyright statements for files that have been removed
+    (Albert Krewinkel).
+
+  * Moved some doc files from `data-files` to `extra-source-files` (#1123).
+    They aren't needed at runtime.  We keep README and COPYRIGHT in data
+    to ensure that they'll be available on all systems on which pandoc
+    is installed.
+
+  * Use cabal sandboxes in Windows build script.
+
+## pandoc 1.12.3.3 (2014-02-03)
+
+  * To changes to source; recompiled tarball with latest alex and
+    happy, so they will work with GHC 7.8.
+
+## pandoc 1.12.3.2 (2014-02-03)
+
+  * Bumped version bounds for blaze-html, blaze-markup.
+
+  * ImageSize:  Avoid use of lookAhead, which is not in binary >= 0.6
+    (#1124).
+
+  * Fixed mediawiki ordered list parsing (#1122).
+
+  * HTML reader:  Fixed bug reading inline math with `$$` (#225).
+
+  * Added support for LaTeX style literate Haskell code blocks in rST
+    (Merijn Verstraaten).
+
+## pandoc 1.12.3.1 (2014-01-14)
+
+  * Relaxed version constraint on binary, allowing the use of binary 0.5.
+
+
+## pandoc 1.12.3 (2014-01-10)
+
+  * The `--bibliography` option now sets the `biblio-files` variable.
+    So, if you're using `--natbib` or `--biblatex`, you can just use
+    `--bibliography=foo.bib` instead of `-V bibliofiles=foo`.
+
+  * Don't run pandoc-citeproc filter if `--bibliography` is
+    used together with `--natbib` or `--biblatex` (Florian Eitel).
+
+  * Template changes:
+
+    + Updated beamer template to include booktabs.
+    + Added `abstract` variable to LaTeX template.
+    + Put `header-includes` after `title` in LaTeX template (#908).
+    + Allow use of `\includegraphics[size]` in beamer.
+      This just required porting a macro definition from the default
+      LaTeX template to the default beamer template.
+
+  * `reference.docx`:  Include `FootnoteText` style.
+    Otherwise Word ignores the style, even when specified in the `pPr`.
+    (#901)
+
+  * `reference.odt`:  Tidied `styles.xml`.
+
+  * Relaxed version bounds for dependencies.
+
+  * Added `withSocketsDo` around http conduit code in `openURL`,
+    so it works on Windows (#1080).
+
+  * Added `Cite` function to `sample.lua`.
+
+  * Markdown reader:
+
+    + Fixed regression in title blocks (#1089).
+      If author field was empty, date was being ignored.
+    + Allow backslash-newline hard line breaks in grid and
+      multiline table cells.
+    + Citation keys may now start with underscores, and may contain
+      underscores adjacent to internal punctuation.
+
+  * LaTeX reader:
+
+    + Add support for `Verb` macro (jrnold) (#1090).
+    + Support babel-style quoting: `` "`..."' ``.
+
+  * Properly handle script blocks in strict mode.  (That is,
+    `markdown-markdown_in_html_blocks`.) Previously a spurious
+    `<p>` tag was being added (#1093).
+
+  * Docbook reader: Avoid failure if `tbody` contains no `tr` or `row`
+    elements.
+
+  * LaTeX writer:
+
+    + Factored out function for table cell creation.
+    + Better treatment of footnotes in tables.
+      Notes now appear in the regular sequence, rather than in the
+      table cell.  (This was a regression in 1.10.)
+
+  * HTML reader: Parse name/content pairs from meta tags as metadata.
+    Closes #1106.
+
+  * Moved `fixDisplayMath` from Docx writer to `Writer.Shared`.
+
+  * OpenDocument writer:  Fixed `RawInline`, `RawBlock` so they don't escape.
+
+  * ODT writer:  Use mathml for proper rendering of formulas.
+    Note:  LibreOffice's support for this seems a bit buggy.  But
+    it should be better than what we had before.
+
+  * RST writer: Ensure no blank line after def in definition list (#992).
+
+  * Markdown writer: Don't use tilde code blocks with braced attributes in
+    `markdown_github` output.  A consequence of this change is that the
+    backtick form will be preferred in general if both are enabled.  That
+    is good, as it is much more widespread than the tilde form.  (#1084)
+
+  * Docx writer:  Fixed problem with some modified reference docx files.
+    Include `word/_rels/settings.xml.rels` if it exists, as well as other
+    `rels` files besides the ones pandoc generates explicitly.
+
+  * HTML writer:
+
+    + With `--toc`, headers no longer link to themselves (#1081).
+    + Omit footnotes from TOC entries.  Otherwise we get doubled
+      footnotes when headers have notes!
+
+  * EPUB writer:
+
+    + Avoid duplicate notes when headings contain notes.
+      This arose because the headings are copied into the metadata
+      "title" field, and the note gets rendered twice.  We strip the
+      note now before putting the heading in "title".
+    + Strip out footnotes from toc entries.
+    + Fixed bug with `--epub-stylesheet`.  Now the contents of
+      `writerEpubStylesheet` (set by `--epub-stylesheet`)
+      should again work, and take precedence over a stylesheet specified
+      in the metadata.
+
+  * `Text.Pandoc.Pretty`:  Added `nestle`.  API change.
+
+  * `Text.Pandoc.MIME`: Added `wmf`, `emf`.
+
+  * `Text.Pandoc.Shared`:  `fetchItem` now handles image URLs beginning
+    with `//`.
+
+  * `Text.Pandoc.ImageSize`:  Parse EXIF format JPEGs.  Previously
+    we could only get size information for JFIF format, which led
+    to squished images in Word documents. Closes #976.
+
+  * Removed old `MarkdownTest_1.0.3` directory (#1104).
+
+
+## pandoc 1.12.2.1 (2013-12-08)
+
+  * Markdown reader:  Fixed regression in list parser, involving
+    continuation lines containing raw HTML (or even verbatim raw HTML).
+
+## pandoc 1.12.2 (2013-12-07)
+
+  * Metadata may now be included in YAML blocks in a markdown document.
+    For example,
+
+        ---
+        title:
+        - type: main
+          text: My Book
+        - type: subtitle
+          text: An investigation of metadata
+        creator:
+        - role: author
+          text: John Smith
+        - role: editor
+          text: Sarah Jones
+        identifier:
+        - scheme: DOI
+          text: doi:10.234234.234/33
+        publisher:  My Press
+        rights:  (c) 2007 John Smith, CC BY-NC
+        cover-image: img/mypic.jpg
+        stylesheet: style.css
+        ...
+
+    Metadata may still be provided using `--epub-metadata`; it will
+    be merged with the metadata in YAML blocks.
+
+  * EPUB writer:
+
+    + `meta` tags are now used instead of `opf` attributes for EPUB3.
+    + Insert "svg" property as needed in opf (EPUB 3).
+    + Simplify `imageTypeOf` using `getMimeType`.
+    + Add properties attribute to `cover-image` item for EPUB 3.
+    + Don't include node for `cover.xhtml` if no cover!
+    + Ensure that same identifier is used throughout (#1044).
+      If an identifier is given in metadata, we use that; otherwise
+      we generate a random uuid.
+    + Add cover reference to guide element (EPUB 2) (Shaun Attfield).
+      Fixes an issue with Calibre putting the cover at the end of the book
+      if the spine has `linear="no"`.  Apparently this is best practice
+      for other converters as well:
+      <http://www.idpf.org/epub/20/spec/OPF_2.0.1_draft.htm#Section2.6>.
+    + Allow `stylesheet` in metadata.  The value is a path to the stylesheet.
+    + Allow partial dates:  `YYYY`, `YYYY-MM`.
+
+  * Markdown writer:  Fix rendering of tight sublists (#1050).
+    Previously a spurious blank line was included after a tight sublist.
+
+  * ODT writer:  Add `draw:name` attribute to `draw:frame` elements (#1069).
+    This is reported to be necessary to avoid an error from recent
+    versions of Libre Office when files contain more than one image
+    Thanks to wmanley for reporting and diagnosing the problem.
+
+  * ConTeXt writer:  Don't hardcode figure/table placement and numbering.
+    Instead, let this be set in the template, using `\setupfloat`.
+    Thanks to on4aa and Aditya Mahajan for the suggestion (#1067).
+
+  * Implemented CSL flipflopping spans in DOCX, LaTeX, and HTML writers.
+
+  * Fixed bug with markdown intraword emphasis.  Closes #1066.
+
+  * Docbook writer:  Hierarchicalize block content in metadata.
+    Previously headers just disappeared from block-level metadata
+    when it was used in templates.  Now we apply the 'hierarchicalize'
+    transformation.  Note that a block headed by a level-2 header will
+    turn into a `<sect1>` element.
+
+  * OpenDocument writer:  Skip raw HTML (#1035).
+    Previously it was erroneously included as verbatim text.
+
+  * HTML/EPUB writer, footnotes:  Put `<sup>` tag inside `<a>` tags.
+    This allows better control of formatting, since the `<a>`
+    tags have a distinguishing class (#1049).
+
+  * Docx writer:
+
+    + Use mime type info returned by fetchItem.
+    + Fixed core metadata (#1046).
+      Don't create empty date nodes if no date given.
+      Don't create multiple `dc:creator` nodes; instead separate by
+      semicolons.
+    + Fix URL for core-properties in `_rels/.rels` (#1046).
+
+  * Plain writer: don't print `<span>` tags.
+
+  * LaTeX writer:
+
+    + Fix definition lists with internal links in terms (#1032).
+      This fix puts braces around a term that contains an internal
+      link, to avoid problems with square brackets.
+    + Properly escape pdftitle, pdfauthor (#1059).
+    + Use booktabs package for tables (thanks to Jose Luis Duran).
+
+  * Updated beamer template.  Now references should work properly
+    (in a slide) when `--biblatex` or `--natbib` is used.
+
+  * LaTeX reader:
+
+    + Parse contents of curly quotes or matched `"` as quotes.
+    + Support `\textnormal` as span with class `nodecor`.
+      This is needed for pandoc-citeproc.
+    + Improved citation parsing.  This fixes a run-time error that occurred
+      with `\citet{}` (empty list of keys).  It also ensures that empty keys
+      don't get produced.
+
+  * MediaWiki reader:  Add automatic header identifiers.
+
+  * HTML reader:
+
+    + Use pandoc `Div` and `Span` for raw `<div>`, `<span>` when
+      `--parse-raw`.
+    + Recognize `svg` tags as block level content (thanks to MinRK).
+    + Parse LaTeX math if appropriate options are set.
+
+  * Markdown reader:
+
+    + Yaml block must start immediately after `---`.  If there's a blank
+      line after `---`, we interpreted it as a horizontal rule.
+    + Correctly handle empty bullet list items.
+    + Stop parsing "list lines" when we hit a block tag.
+      This fixes exponential slowdown in certain input, e.g.
+      a series of lists followed by `</div>`.
+
+   * Slides:  Preserve `<div class="references">` in references slide.
+
+  * `Text.Pandoc.Writer.Shared`:
+
+    + Fixed bug in `tagWithAttrs`.  A space was omitted before key-value
+      attributes, leading to invalid HTML.
+    + `normalizeDate`: Allow dates with year only (thanks to Shaun Attfield).
+    + Fixed bug in `openURL` with `data:` URIs.  Previously the base-64
+      encoded bytestring was returned.  We now decode it so it's a proper
+      image!
+
+  * DocBook reader:  Handle numerical attributes starting with decimal.
+    Also use `safeRead` instead of `read`.
+
+  * `Text.Pandoc.Parsing`:
+
+    + Generalized type of `registerHeader`, using new type classes
+      `HasReadeOptions`, `HasIdentifierList`, `HasHeaderMap`.
+      These allow certain common functions to be reused
+      even in parsers that use custom state (instead of `ParserState`),
+      such as the MediaWiki reader.
+    + Moved inlineMath, displayMath from Markdown reader to Parsing.
+      Generalize their types and export them from Parsing.  (API change.)
+
+  * `Text.Pandoc.Readers.TexMath`: Export `readTeXMath'`, which attends
+    to display/inline.  Deprecate `readTeXMath`, and use `readTeXMath'`
+    in all the writers.  Require `texmath >= 0.6.5.2`.
+
+  * `Text.Pandoc.MIME`:
+
+    + Add entry for `jfif`.
+    + In looking up extensions, drop the encoding info.
+      E.g. for 'image/jpg;base64' we should lookup 'image/jpg'.
+
+  * Templates:  Changed how array variables are resolved.  Previously if
+    `foo` is an array (which might be because multiple values were set on
+    the command line), `$foo$` would resolve to the concatenation of the
+    elements of foo.  This is rarely useful behavior.  It has been changed
+    so that the first value is rendered.  Of course, you can still iterate
+    over the values using `$for(foo)$`.  This has the result that you can
+    override earlier settings using `-V` by putting new values later on the
+    command line, which is useful for many purposes.
+
+  * `Text.Pandoc`:  Don't default to `pandocExtensions` for all writers.
+
+  * Allow "epub2" as synonym for "epub", "html4" for "html".
+
+  * Don't look for slidy files in data files with `--self-contained`.
+
+  * Allow `https:` command line arguments to be downloaded.
+
+  * Fixed `make_osx_package.sh` so data files embedded in `pandoc-citeproc`.
+
+## pandoc 1.12.1 (2013-10-20)
+
+  * `Text.Pandoc.Definition`:  Changed default JSON serialization format.
+    Instead of `{"Str": "foo"}`, for example, we now have `{"t": "Str",
+    "c": "foo"}`.  This new format is easier to work with outside of Haskell.
+    Incidentally, "t" stands for "tag", "c" for "contents".
+
+  * MediaWiki reader: Trim contents of `<math>` tags, to avoid problems
+    when converting to markdown (#1027).
+
+  * LaTeX reader:
+
+    + Ensure that preamble doesn't contribute to the text of
+      the document.
+    + Fixed character escaping in `\url{}`.  Previously `\~` wasn't handled
+      properly, among others.
+    + Parse `{groups}` as `Span`.  This is needed for accurate conversion of
+      bibtex titles, since we need to know what was protected from
+      titlecase conversions.
+
+  * LaTeX writer:
+
+    + Specially escape non-ascii characters in labels.
+      Otherwise we can get compile errors and other bugs when
+      compiled with pdflatex (#1007).  Thanks to begemotv2718 for the fix.
+    + Add link anchors for code blocks with identifiers (#1025).
+
+  * Throughout the code, use `isURI` instead of `isAbsoluteURI`.
+    It allows fragments identifiers.
+
+  * Slide formats:
+
+    + A Div element with class "notes" is treated as speaker
+      notes.  Currently beamer goes to `\note{}`, revealjs to
+      `<aside class="notes">`, and the notes are simply suppressed in
+      other formats  (#925).
+    + Fixed `. . .` (pause) on HTML slide formats.  Closes #1029.
+      The old version caused a pause to be inserted before the first
+      material on a slide. This has been fixed.
+    + Removed data files for s5, slideous, slidy.
+      Users of s5 and slideous will have to download the needed
+      files, as has been documented for some time in the README.
+      By default, slidy code will be sought on the web, as before.
+
+  * HTML writer: Insert command to typeset mathjax only in slideous output
+    (#966, #1012).
+
+  * RST writer:  Skip spaces after display math.  Otherwise we get indentation
+    problems, and part of the next paragraph may be rendered as part of the
+    math.
+
+  * OpenDocument writer:  Fix formatting of strikeout code (#995),
+    thanks to wilx.  don't use `font-face-decls` variable.
+
+  * Fixed test suite so it works with cabal sandboxes.
+
+## pandoc 1.12.0.2 (2013-09-20)
+
+  * Removed an unused dependency (`stringable`) from pandoc.cabal.
+    This will help packagers, but users should not need to upgrade.
+
+## pandoc 1.12.0.1 (2013-09-20)
+
+  * Allow `--metadata` to be repeated for the same key to form a list.
+    This also has the effect that `--bibliography` can be repeated,
+    as before.
+
+  * Handle boolean values in `--metadata`.  Note that anything not parseable
+    as a YAML boolean or string is treated as a literal string.
+    You can get a string value with "yes", or any of the strings interpretable
+    as booleans, by quoting it:
+
+        -M boolvalue=yes -M stringvalue='"yes"'
+
+  * LaTeX writer: Don't print references if `--natbib` or `--biblatex`
+    option used.
+
+  * DOCX writer: Add `settings.xml` to the zip container.  Fixes a bug
+    in which docx files could not be read by some versions of Word
+    and LibreOffice (#990).
+
+  * Fixed a regression involving slide shows with bibliographies.
+    The Div container around references messed up the procedure for carving
+    a document into slides.  So we now remove the surrounding Div in
+    `prepSlides`.
+
+  * More informative error message when a filter is not found in path.
+
+  * Depend on pandoc-types 1.12.1.  This provide `ToJSONFilter`
+    instances for `Data a => a -> [a]` and `Data a => a -> IO [a]`.
+
+  * Don't use unicode_collation in building OSX package:
+    it adds something like 50MB of dependencies to the package.
+
+  * Declare alex and happy as build-tools (#986).
+
+## pandoc 1.12 (2013-09-15)
+
+### New features
+
+  * Much more flexible metadata, including arbitrary fields and structured
+    values.  Metadata can be specified flexibly in pandoc markdown using
+    YAML metadata blocks, which may occur anywhere in the document:
+
+        ---
+        title: Here is my title.
+        abstract: |
+          This is the abstract.
+
+          1. It can contain
+          2. block content
+             and *inline markup*
+
+        tags: [cat, dog, animal]
+        ...
+
+    Metadata fields automatically populate template variables.
+
+  * Added `opml` (OPML) as input and output format.  The `_note` attribute,
+    used in OmniOutliner and supported by multimarkdown, is supported.
+    We treat the contents as markdown blocks under a section header.
+
+  * Added `haddock` (Haddock markup) as input format (David Lazar).
+
+  * Added `revealjs` output format, for reveal.js HTML 5 slide shows.
+    (Thanks to Jamie F. Olson for the initial patch.)
+    Nested vertical stacks are used for hierarchical structure.
+    Results for more than one level of nesting may be odd.
+
+  * Custom writers can now be written in lua.
+
+        pandoc -t data/sample.lua
+
+    will load the script sample.lua and use it as a custom writer.
+    (For a sample, do `pandoc --print-default-data-file sample.lua`.)
+    Note that pandoc embeds a lua interpreter, so lua need not be
+    installed separately.
+
+  * New `--filter/-F` option to make it easier to run "filters"
+    (Pandoc AST transformations that operate on JSON serializations).
+    Filters are always passed the name of the output format, so their
+    behavior can be tailored to it.  The repository
+    <https://github.com/jgm/pandocfilters> contains
+    a python module for writing pandoc filters in python, with
+    a number of examples.
+
+  * Added `--metadata/-M` option.
+    This is like `--variable/-V`, but actually adds to metadata, not
+    just variables.
+
+  * Added `--print-default-data-file` option, which allows printing
+    of any of pandoc's data files. (For example,
+    `pandoc --print-default-data-file reference.odt` will print
+    `reference.odt`.)
+
+  * Added syntax for "pauses" in slide shows:
+
+        This gives
+
+        . . .
+
+        me pause.
+
+  * New markdown extensions:
+
+    + `ignore_line_breaks`:  causes intra-paragraph line breaks to be ignored,
+      rather than being treated as hard line breaks or spaces.  This is useful
+      for some East Asian languages, where spaces aren't used between words,
+      but text is separated into lines for readability.
+    + `yaml_metadata_block`:  Parse YAML metadata blocks.  (Default.)
+    + `ascii_identifiers`: This will force `auto_identifiers` to use ASCII
+       only. (Default for `markdown_github`.) (#807)
+    + `lists_without_preceding_blankline`:  Allow lists to start without
+      preceding blank space.  (Default for `markdown_github`.) (#972)
+
+### Behavior changes
+
+  * `--toc-level` no longer implies `--toc`.
+    Reason: EPUB users who don't want a visible TOC may still want
+    to set the TOC level for in the book navigation.
+
+  * `--help` now prints in and out formats in alphabetical order, and
+    says something about PDF output (#720).
+
+  * `--self-contained` now returns less verbose output (telling you
+    which URLs it is fetching, but not giving the full header).  In
+    addition, there are better error messages when fetching a URL fails.
+
+  * Citation support is no longer baked in to core pandoc. Users who
+    need citations will need to install and use a separate filter
+    (`--filter pandoc-citeproc`).  This filter will take `bibliography`,
+    `csl`, and `citation-abbreviations` from the metadata, though it
+    may still be specified on the command line as before.
+
+  * A `Cite` element is now created in parsing markdown whether or not
+    there is a matching reference.
+
+  * The `pandoc-citeproc` script will put the bibliography at the
+    end of the document, as before.  However, it will be put inside a `Div`
+    element with class "references", allowing users some control
+    over the styling of references.  A final header, if any, will
+    be included in the `Div`.
+
+  * The markdown writer will not print a bibliography if the
+    `citations` extension is enabled.  (If the citations are formatted
+    as markdown citations, it is redundant to have a bibliography,
+    since one will be generated automatically.)
+
+  * Previously we used to store the directory of the first input file,
+    even if it was local, and used this as a base directory for finding
+    images in ODT, EPUB, Docx, and PDF.  This has been confusing to many
+    users.  So we now look for images relative to the current
+    working directory, even if the first file argument is in another
+    directory.   Note that this change may break some existing workflows.
+    If you have been assuming that relative links will be interpreted
+    relative to the directory of the first file argument, you'll need
+    to make that the current directory before running pandoc. (#942)
+
+  * Better error reporting in some readers, due to changes in `readWith`:
+    the line in which the error occurred is printed, with a caret pointing
+    to the column.
+
+  * All slide formats now support incremental slide view for definition lists.
+
+  * Parse `\(..\)` and `\[..\]` as math in MediaWiki reader.
+    Parse `:<math>...</math>` as display math.  These notations are used with
+    the MathJax MediaWiki extension.
+
+  * All writers: template variables are set automatically from metadata
+    fields.  However, variables specified on the command line with
+    `--variable` will completely shadow metadata fields.
+
+  * If `--variable` is used to set many variables with the same name,
+    a list is created.
+
+  * Man writer:  The `title`, `section`, `header`, and `footer` can now
+    all be set individually in metadata.  The `description` variable has been
+    removed.  Quotes have been added so that spaces are allowed in the
+    title.  If you have a title that begins
+
+        COMMAND(1) footer here | header here
+
+    pandoc will still parse it into a title, section, header, and
+    footer.  But you can also specify these elements explicitly (#885).
+
+  * Markdown reader
+
+    + Added support for YAML metadata blocks, which can come anywhere
+      in the document (not just at the beginning).  A document can contain
+      multiple YAML metadata blocks.
+    + HTML span and div tags are parsed as pandoc Span and Div elements.
+
+  * Markdown writer
+
+    + Allow simple tables to be printed as grid tables,
+      if other table options are disabled.  This means you can do
+      `pandoc -t markdown-pipe_tables-simple_tables-multiline_tables`
+      and all tables will render as grid tables.
+    + Support YAML title block (render fields in alphabetical order
+      to make output predictable).
+
+### API changes
+
+  * `Meta` in `Text.Pandoc.Definition` has been changed to allow
+    structured metadata.  (Note:  existing code that pattern-matches
+    on `Meta` will have to be revised.)  Metadata can now contain
+    indefinitely many fields, with content that can be a string,
+    a Boolean, a list of `Inline` elements, a list of `Block`
+    elements, or a map or list of these.
+
+  * A new generic block container (`Div`) has been added to `Block`,
+    and a generic inline container (`Span`) has been added to `Inline`.
+    These can take attributes.  They will render in HTML, Textile,
+    MediaWiki, Org, RST and Markdown (with `markdown_in_html`
+    extension) as HTML `<div>` and `<span>` elements; in other formats
+    they will simply pass through their contents.  But they can be
+    targeted by scripts.
+
+  * `Format` is now a newtype, not an alias for String.
+    Equality comparisons are case-insensitive.
+
+  * Added `Text.Pandoc.Walk`, which exports hand-written tree-walking
+    functions that are much faster than the SYB functions from
+    `Text.Pandoc.Generic`.  These functions are now used where possible
+    in pandoc's code.  (`Tests.Walk` verifies that `walk` and `query`
+    match the generic traversals `bottomUp` and `queryWith`.)
+
+  * Added `Text.Pandoc.JSON`, which provides `ToJSON` and `FromJSON`
+    instances for the basic pandoc types. They use GHC generics and
+    should be faster than the old JSON serialization using
+    `Data.Aeson.Generic`.
+
+  * Added `Text.Pandoc.Process`, exporting `pipeProcess`.
+    This is a souped-up version of `readProcessWithErrorcode` that
+    uses lazy bytestrings instead of strings and allows setting
+    environment variables.  (Used in `Text.Pandoc.PDF`.)
+
+  * New module `Text.Pandoc.Readers.OPML`.
+
+  * New module `Text.Pandoc.Writers.OPML`.
+
+  * New module `Text.Pandoc.Readers.Haddock` (David Lazar).
+    This is based on Haddock's own lexer/parser.
+
+  * New module `Text.Pandoc.Writers.Custom`.
+
+  * In `Text.Pandoc.Shared`, `openURL` and `fetchItem` now return an
+    Either, for better error handling.
+
+  * Made `stringify` polymorphic in `Text.Pandoc.Shared`.
+
+  * Removed `stripTags` from `Text.Pandoc.XML`.
+
+  * `Text.Pandoc.Templates`:
+
+    + Simplified `Template` type to a newtype.
+    + Removed `Empty`.
+    + Changed type of `renderTemplate`: it now takes a JSON context
+      and a compiled template.
+    + Export `compileTemplate`.
+    + Export `renderTemplate'` that takes a string instead of a compiled
+      template.
+    + Export `varListToJSON`.
+
+  * `Text.Pandoc.PDF` exports `makePDF` instead of `tex2pdf`.
+
+  * `Text.Pandoc`:
+
+    + Made `toJsonFilter` an alias for `toJSONFilter` from `Text.Pandoc.JSON`.
+    + Removed `ToJsonFilter` typeclass.  `ToJSONFilter` from
+      `Text.Pandoc.JSON` should be used instead.  (Compiling against
+      pandoc-types instead of pandoc will also produce smaller executables.)
+    * Removed the deprecated `jsonFilter` function.
+    + Added `readJSON`, `writeJSON` to the API (#817).
+
+  * `Text.Pandoc.Options`:
+
+    + Added `Ext_lists_without_preceding_blankline`,
+      `Ext_ascii_identifiers`, `Ext_ignore_line_breaks`,
+      `Ext_yaml_metadataBlock` to `Extension`.
+    + Changed `writerSourceDirectory` to `writerSourceURL` and changed the
+      type to a `Maybe`.  `writerSourceURL` is set to 'Just url' when the
+      first command-line argument is an absolute URL.  (So, relative links
+      will be resolved in relation to the first page.)  Otherwise, 'Nothing'.
+    + All bibliography-related fields have been removed from
+      `ReaderOptions` and `WriterOptions`: `writerBiblioFiles`,
+      `readerReferences`, `readerCitationStyle`.
+
+  * The `Text.Pandoc.Biblio` module has been removed.  Users of the
+    pandoc library who want citation support will need to use
+    `Text.CSL.Pandoc` from `pandoc-citeproc`.
+
+### Bug fixes
+
+  * In markdown, don't autolink a bare URI that is followed by `</a>`
+    (#937).
+
+  * `Text.Pandoc.Shared`
+
+    + `openURL` now follows redirects (#701), properly handles `data:`
+      URIs, and prints diagnostic output to stderr rather than stdout.
+    + `readDefaultDataFile`: normalize the paths.  This fixes bugs in
+      `--self-contained` on pandoc compiled with `embed_data_files` (#833).
+    + Fixed `readDefaultDataFile` so it works on Windows.
+    + Better error messages for `readDefaultDataFile`.  Instead of
+      listing the last path tried, which can confuse people who are
+      using `--self-contained`, so now we just list the data file name.
+    + URL-escape pipe characters.  Even though these are legal, `Network.URI`
+      doesn't regard them as legal in URLs.  So we escape them first (#535).
+
+  * Mathjax in HTML slide shows:  include explicit "Typeset" call.
+    This seems to be needed for some formats (e.g. slideous) and won't
+    hurt in others (#966).
+
+  * `Text.Pandoc.PDF`
+
+    + On Windows, create temdir in working directory, since the system
+      temp directory path may contain tildes, which can cause
+      problems in LaTeX (#777).
+    + Put temporary output directory in `TEXINPUTS` (see #917).
+    + `makePDF` tries to download images that are not found locally,
+      if the first argument is a URL (#917).
+    + If compiling with `pdflatex` yields an encoding error, offer
+      the suggestion to use `--latex-engine=xelatex`.
+
+  * Produce automatic header identifiers in parsing textile, RST,
+    and LaTeX, unless `auto_identifiers` extension is disabled (#967).
+
+  * `Text.Pandoc.SelfContained`:  Strip off fragment, query of relative URL
+     before treating as a filename.  This fixes `--self-contained` when used
+     with CSS files that include web fonts using the method described here:
+      <http://paulirish.com/2009/bulletproof-font-face-implementation-syntax/>
+      (#739).  Handle `src` in `embed`, `audio`, `source`, `input` tags.
+
+  * `Text.Pandoc.Parsing`: `uri` parser no longer treats punctuation before
+    percent-encoding, or a `+` character, as final punctuation.
+
+  * `Text.Pandoc.ImageSize`:  Handle EPS (#903).  This change will make
+    EPS images properly sized on conversion to Word.
+
+  * Slidy:  Use slidy.js rather than slidy.js.gz.
+    Reason:  some browsers have trouble with the gzipped js file,
+    at least on the local file system (#795).
+
+  * Markdown reader
+
+    + Properly handle blank line at beginning of input (#882).
+    + Fixed bug in unmatched reference links.  The input
+      `[*infile*] [*outfile*]` was getting improperly parsed:
+      "infile" was emphasized, but "*outfile*" was literal (#883).
+    + Allow internal `+` in citation identifiers (#856).
+    + Allow `.` or `)` after `#` in ATX headers if no `fancy_lists`.
+    + Do not generate blank title, author, or date metadata elements.
+      Leave these out entirely if they aren't present.
+    + Allow backtick code blocks not to be preceded by blank line (#975).
+
+  * Textile reader:
+
+    + Correctly handle entities.
+    + Improved handling of `<pre>` blocks (#927). Remove internal HTML tags
+      in code blocks, rather than printing them verbatim. Parse attributes
+      on `<pre>` tag for code blocks.
+
+  * HTML reader: Handle non-simple tables (#893).  Column widths are read from
+    `col` tags if present, otherwise divided equally.
+
+  * LaTeX reader
+
+    + Support alltt environment (#892).
+    + Support `\textasciitilde`, `\textasciicircum` (#810).
+    + Treat `\textsl` as emphasized text reader (#850).
+    + Skip positional options after `\begin{figure}`.
+    + Support `\v{}` for hacek (#926).
+    + Don't add spurious ", " to citation suffixes.
+      This is added when needed in pandoc-citeproc.
+    + Allow spaces in alignment spec in tables, e.g. `{ l r c }`.
+    + Improved support for accented characters (thanks to Scott Morrison).
+    + Parse label after section command and set id (#951).
+
+  * RST reader:
+
+    + Don't insert paragraphs where docutils doesn't.
+      `rst2html` doesn't add `<p>` tags to list items (even when they are
+      separated by blank lines) unless there are multiple paragraphs in the
+      list.  This commit changes the RST reader to conform more closely to
+      what docutils does (#880).
+    + Improved metadata.  Treat initial field list as metadata when
+      standalone specified.  Previously ALL fields "title", "author",
+      "date" in field lists were treated as metadata, even if not at
+      the beginning.  Use `subtitle` metadata field for subtitle.
+    + Fixed 'authors' metadata parsing in reST.  Semicolons separate
+      different authors.
+
+  * MediaWiki reader
+
+    + Allow space before table rows.
+    + Fixed regression for `<ref>URL</ref>`.
+      `<` is no longer allowed in URLs, according to the uri parser
+      in `Text.Pandoc.Parsing`.  Added a test case.
+    + Correctly handle indented preformatted text without preceding
+      or following blank line.
+    + Fixed `|` links inside table cells.  Improved attribute parsing.
+    + Skip attributes on table rows.  Previously we just crashed if
+      rows had attributes, now we ignore them.
+    + Ignore attributes on headers.
+    + Allow `Image:` for images (#971).
+    + Parse an image with caption in a paragraph by itself as a figure.
+
+  * LaTeX writer
+
+    + Don't use ligatures in escaping inline code.
+    + Fixed footnote numbers in LaTeX/PDF tables.  This fixes a bug
+      wherein notes were numbered incorrectly in tables (#827).
+    + Always create labels for sections.  Previously the labels were only
+      created when there were links to the section in the document (#871).
+    + Stop escaping `|` in LaTeX math.
+      This caused problems with array environments (#891).
+    + Change `\` to `/` in paths.  `/` works even on Windows in LaTeX.
+      `\` will cause major problems if unescaped.
+    + Write id for code block to label attribute in LaTeX when listings
+      is used (thanks to Florian Eitel).
+    + Scale LaTeX tables so they don't exceed columnwidth.
+    + Avoid problem with footnotes in unnumbered headers (#940).
+
+  * Beamer writer: when creating beamer slides, add `allowframebreaks` option
+      to the slide if it is one of the header classes.  It is recommended
+      that your bibliography slide have this attribute:
+
+        # References {.allowframebreaks}
+
+    This causes multiple slides to be created if necessary, depending
+    on the length of the bibliography.
+
+  * ConTeXt writer: Properly handle tables without captions.  The old output
+    only worked in MkII. This should work in MkIV as well (#837).
+
+  * MediaWiki writer: Use native mediawiki tables instead of HTML (#720).
+
+  * HTML writer:
+
+    + Fixed `--no-highlight` (Alexander Kondratskiy).
+    + Don't convert to lowercase in email obfuscation (#839).
+    + Ensure proper escaping in `<title>` and `<meta>` fields.
+
+  * AsciiDoc writer:
+
+    + Support `--atx-headers` (Max Rydahl Andersen).
+    + Don't print empty identifier blocks `([[]])` on headers (Max
+      Rydahl Andersen).
+
+  * ODT writer:
+
+    + Fixing wrong numbered-list indentation in open document format
+      (Alexander Kondratskiy) (#369).
+    + `reference.odt`: Added pandoc as "generator" in `meta.xml`.
+    + Minor changes for ODF 1.2 conformance (#939). We leave the
+      nonconforming `contextual-spacing` attribute, which is provided by
+      LibreOffice itself and seems well supported.
+
+  * Docx writer:
+
+    + Fixed rendering of display math in lists.
+      In 1.11 and 1.11.1, display math in lists rendered as a new list
+      item.  Now it always appears centered, just as outside of lists,
+      and in proper display math style, no matter how far indented the
+      containing list item is (#784).
+    + Use `w:br` with `w:type` `textWrapping` for linebreaks.
+      Previously we used `w:cr` (#873).
+    + Use Compact style for Plain block elements, to
+      differentiate between tight and loose lists (#775).
+    + Ignore most components of `reference.docx`.
+      We take the `word/styles.xml`, `docProps/app.xml`,
+      `word/theme/theme1.xml`, and `word/fontTable.xml` from
+      `reference.docx`, ignoring everything else.  This should help
+      with the corruption problems caused when different versions of
+      Word resave the reference.docx and reorganize things.
+    +  Made `--no-highlight` work properly.
+
+  * EPUB writer
+
+    + Don't add `dc:creator` tags if present in EPUB metadata.
+    + Add `id="toc-title"` to `h1` in `nav.xhtml` (#799).
+    + Don't put blank title page in reading sequence.
+      Set `linear="no"` if no title block.  Addresses #797.
+    + Download webtex images and include as data URLs.
+      This allows you to use `--webtex` in creating EPUBs.
+      Math with `--webtex` is automatically made self-contained.
+    + In `data/epub.css`, removed highlighting styles (which
+      are no longer needed, since styles are added by the HTML
+      writer according to `--highlighting-style`).  Simplified
+      margin fields.
+    + If resource not found, skip it, as in Docx writer (#916).
+
+  * RTF writer:
+
+    + Properly handle characters above the 0000-FFFF range.
+      Uses surrogate pairs.  Thanks to Hiromi Ishii for the patch.
+    + Fixed regression with RTF table of contents.
+    + Only autolink absolute URIs.  This fixes a regression, #830.
+
+  * Markdown writer:
+
+    + Only autolink absolute URIs.  This fixes a regression, #830.
+    + Don't wrap attributes in fenced code blocks.
+    + Write full metadata in MMD style title blocks.
+    + Put multiple authors on separate lines in pandoc titleblock.
+      Also, don't wrap long author entries, as new lines get treated
+      as new authors.
+
+  * `Text.Pandoc.Templates`:
+
+    + Fixed bug retrieving default template for markdown variants.
+    + Templates can now contain "record lookups" in variables;
+      for example, `author.institution` will retrieve the `institution`
+      field of the `author` variable.
+    + More consistent behavior of `$for$`.  When `foo` is not a list,
+      `$for(foo)$...$endfor$` should behave like $if(foo)$...$endif$.
+      So if `foo` resolves to "", no output should be produced.
+      See pandoc-templates#39.
+
+  * Citation processing improvements (now part of pandoc-citeproc):
+
+    + Fixed `endWithPunct` The new version correctly sees a sentence
+      ending in '.)' as ending with punctuation.  This fixes a bug which
+      led such sentences to receive an extra period at the end: '.).'.
+      Thanks to Steve Petersen for reporting.
+    + Don't interfere with Notes that aren't citation notes.
+      This fixes a bug in which notes not generated from citations were
+      being altered (e.g. first letter capitalized) (#898).
+    + Only capitalize footnote citations when they have a prefix.
+    + Changes in suffix parsing.  A suffix beginning with a digit gets 'p'
+      inserted before it before passing to citeproc-hs, so that bare numbers
+      are treated as page numbers by default.  A suffix not beginning with
+      punctuation has a space added at the beginning (rather than a comma and
+      space, as was done before for not-author-in-text citations).
+      The result is that `\citep[23]{item1}` in LaTeX will be interpreted
+      properly, with '23' treated as a locator of type 'page'.
+    + Many improvements to citation rendering, due to fixes in citeproc-hs
+      (thanks to Andrea Rossato).
+    + Warnings are issued for undefined citations, which are rendered
+      as `???`.
+    + Fixed hanging behavior when locale files cannot be found.
+
+### Template changes
+
+  * DocBook:  Use DocBook 4.5 doctype.
+
+  * Org: '#+TITLE:' is inserted before the title.
+    Previously the writer did this.
+
+  * LaTeX:  Changes to make mathfont work with xelatex.
+    We need the mathspec library, not just fontspec, for this.
+    We also need to set options for setmathfont (#734).
+
+  * LaTeX: Use `tex-ansi` mapping for `monofont`.
+    This ensures that straight quotes appear as straight, rather than
+    being treated as curly.  See #889.
+
+  * Made `\includegraphics` more flexible in LaTeX template.
+    Now it can be used with options, if needed.  Thanks to Bernhard Weichel.
+
+  * LaTeX/Beamer: Added `classoption` variable.
+    This is intended for class options like `oneside`; it may
+    be repeated with different options.  (Thanks to Oliver Matthews.)
+
+  * Beamer: Added `fonttheme` variable.  (Thanks to Luis Osa.)
+
+  * LaTeX: Added `biblio-style` variable (#920).
+
+  * DZSlides: title attribute on title section.
+
+  * HTML5: add meta tag to allow scaling by user (Erik Evenson)
+
+### Under-the-hood improvements
+
+  * Markdown reader:Improved strong/emph parsing, using the strategy of
+    <https://github.com/jgm/Markdown>.  The new parsing algorithm requires
+    no backtracking, and no keeping track of nesting levels.  It will give
+    different results in some edge cases, but these should not affect normal
+    uses.
+
+  * Added `Text.Pandoc.Compat.Monoid`.
+    This allows pandoc to compile with `base` < 4.5, where `Data.Monoid`
+    doesn't export `<>`.  Thanks to Dirk Ullirch for the patch.
+
+  * Added `Text.Pandoc.Compat.TagSoupEntity`.
+    This allows pandoc to compile with `tagsoup` 0.13.x.
+    Thanks to Dirk Ullrich for the patch.
+
+  * Most of `Text.Pandoc.Readers.TeXMath` has been moved to the
+    `texmath` module (0.6.4).  (This allows `pandoc-citeproc` to
+    handle simple math in bibliography fields.)
+
+  * Added `Text.Pandoc.Writers.Shared` for shared functions used
+    only in writers.  `metaToJSON` is used in writers to create a
+    JSON object for use in the templates from the pandoc metadata
+    and variables.  `getField`, `setField`, and `defField` are
+    for working with JSON template contexts.
+
+  * Added `Text.Pandoc.Asciify` utility module.
+    This exports functions to create ASCII-only versions of identifiers.
+
+  * `Text.Pandoc.Parsing`
+
+    + Generalized state type on `readWith` (API change).
+    + Specialize readWith to `String` input. (API change).
+    + In `ParserState`, replace `stateTitle`, `stateAuthors`, `stateDate`
+      with `stateMeta` and `stateMeta'`.
+
+  * `Text.Pandoc.UTF8`: use strict bytestrings in reading.  The use of lazy
+     bytestrings seemed to cause problems using pandoc on 64-bit Windows
+     7/8 (#874).
+
+  * Factored out `registerHeader` from markdown reader, added to
+    `Text.Pandoc.Parsing`.
+
+  * Removed `blaze_html_0_5` flag, require `blaze-html` >= 0.5.
+    Reason:  < 0.5 does not provide a monoid instance for Attribute,
+    which is now needed by the HTML writer (#803).
+
+  * Added `http-conduit` flag, which allows fetching https resources.
+    It also brings in a large number of dependencies (`http-conduit`
+    and its dependencies), which is why for now it is an optional flag
+    (#820).
+
+  * Added CONTRIBUTING.md.
+
+  * Improved INSTALL instructions.
+
+  * `make-windows-installer.bat`: Removed explicit paths for executables.
+
+  * `aeson` is now used instead of `json` for JSON.
+
+  * Set default stack size to 16M.  This is needed for some large
+    conversions, esp. if pandoc is compiled with 64-bit ghc.
+
+  * Various small documentation improvements.
+    Thanks to achalddave and drothlis for patches.
+
+  * Removed comment that chokes recent versions of CPP (#933).
+
+  * Removed support for GHC version < 7.2, since pandoc-types now
+    requires at least GHC 7.2 for GHC generics.
+
+
+## pandoc 1.11.1 (2013-03-17)
+
+  * Markdown reader:
+
+    + Fixed regression in which parentheses were lost in link URLs.
+      Added tests.  Closes #786.
+    + Better handling of unmatched double quotes in `--smart` mode.
+      These occur frequently in fiction, since it is customary not to
+      close quotes in dialogue if the speaker does not change between
+      paragraphs.  The unmatched quotes now get turned into literal
+      left double quotes. (No `Quoted` inline is generated, however.)
+      Closes #99 (again).
+
+  * HTML writer: Fixed numbering mismatch between TOC and sections.
+    `--number-offset` now affects TOC numbering as well
+    as section numbering, as it should have all along.  Closes #789.
+
+  * Markdown writer: Reverted 1.11 change that caused citations to be rendered
+    as markdown citations, even if `--bibliography` was specified, unless
+    `citation` extension is disabled.  Now, formatted citations are always
+    printed if `--bibliography` was specified.  If you want to reformat
+    markdown keeping pandoc markdown citations intact, don't use
+    `--bibliography`.  Note that citations parsed from LaTeX documents will
+    be rendered as pandoc markdown citations when `--bibliography` is not
+    specified.
+
+  * ODT writer: Fixed regression leading to corrupt ODTs.
+    This was due to a change in the `Show` instance for
+    `Text.Pandoc.Pretty.Doc`.  Closes #780.
+
+  * Fixed spacing bugs involving code block attributes in
+    RST reader and Markdown writer. Closes #763.
+
+  * Windows package:  Various improvements due to Fyodor Sheremetyev.
+
+    + Automatically set installation path (Program Files or Local App Data).
+    + Set system PATH environment variable when installing for all users.
+    + Pandoc can installed for all users using the following command.
+      `msiexec /i pandoc-1.11.msi ALLUSERS=1`.
+
+  * Bumped QuickCheck version bound.
+
+## pandoc 1.11 (2013-03-09)
+
+  * Added `--number-offset` option.  (See README for description.)
+
+  * Added `--default-image-extension` option.  (See README for description.)
+
+  * `--number-sections` behavior change: headers with class `unnumbered`
+    will not be numbered.
+
+  * `--version` now reports the default data directory.
+
+  * `Text.Pandoc.Parsing` is no longer exposed. (API change.)
+
+  * `Text.Pandoc.Highlighting` is no longer exposed. (API change.)
+
+  * `Text.Pandoc.Shared`:  Changed type of `Element`.  `Sec` now includes
+    a field for `Attr` rather than just `String`.  (API change.)
+
+  * Added `markdown_github` as input format.  This was an accidental
+    omission in 1.10.
+
+  * Added `readerDefaultImageExtension` field to `ReaderOptions`.  (API
+    change.)
+
+  * Added `writerNumberOffset` field in `WriterOptions`. (API change.)
+
+  * Beamer template:
+
+    + Fixed captions with longtable.  Thanks to Joost Kremers.
+    + Provide `\Oldincludegraphics` as in LaTeX template (Benjamin Bannier).
+
+  * LaTeX template:
+
+    + Load microtype after fonts.  Microtype needs to know
+      what fonts are being used.  Thanks to dfc for the patch.
+    + Set `secnumdepth` to 5 if `--number-sections` specified.
+      This yields behavior equivalent to the other writers, numbering
+      level 4 and 5 headers too.  Closes #753.
+
+  * HTML reader:
+
+    + Handle `<colgroup>` tag.
+    + Preserve all header attributes.
+
+  * LaTeX reader:
+
+    + Parse `\hrule` as `HorizontalRule`.  Closes #746.
+    + Parse starred variants of `\section` etc. as headers with
+      attribute `unnumbered`.
+    + Read optional attributes in `lstlisting` and `Verbatim` environments.
+      We convert these to pandoc standard names, e.g. `numberLines`
+      for `numbers=left`, `startFrom=100` from `firstnumber=100`.
+    + Handle language attribute for lstlistings.
+    + Better support for Verbatim and minted environments.  Closes #763.
+
+  * Markdown reader:
+
+    + `-` in an attribute context = `.unnumbered`.  The point of this
+      is to provide a way to specify unnumbered headers in non-English
+      documents.
+    + Fixed bug parsing key/value attributes.  Parsing failed if you
+      had an unquoted attribute immediately before the final '}'.
+    + Make backslash escape work in attributes.
+    + Fix title block parsing.  Now if `mmd_title_blocks` is specified,
+      pandoc will parse a MMD title block if it sees one, even if
+      `pandoc_title_blocks` is enabled.
+    + Refactoring: `litChar` now includes entities, so we don't need
+      to use `fromEntities` e.g. on titles.
+    + Allow spaces around borders in pipe tables.  Closes #772.
+    + Allow all punctuation in angle-bracket autolinks.  Previously
+      things like `----` were disallowed, because the uri parser
+      treated them as trailing punctuation.  Closes #768.
+    + Make `implicit_header_references` work properly when
+      headers are given explicit identifiers.
+    + Check for tables before line blocks.  Otherwise some pipe
+      tables get treated as line blocks.
+    + Allow `&` in emails (for entities).
+    + Properly handle entities in titles and links.  A markdown link
+      `<http://g&ouml;ogle.com>` should be a link to `http://göogle.com`.
+      Closes #723.
+
+  * Textile reader:
+
+    + Handle attributes on headers.
+
+  * LaTeX reader:
+
+    + Add `fig:` as title for images with captions.
+      This is needed for them to be rendered as figures.  Closes #766.
+    + Never emit an empty paragraph.  See #761.
+    + Handle `\caption` for images in figures.  Closes #766.
+    + Parse `\section*`, etc. as unnumbered sections.
+
+  * HTML writer:
+
+    + Support header attributes.  The attributes go on
+      the enclosing `section` or `div` tag if `--section-divs` is specified.
+    + Fixed a regression (only now noticed) in html+lhs output.
+      Previously the bird tracks were being omitted.
+
+  * LaTeX writer:
+
+    + Omit lists with no items to avoid LaTeX errors.
+    + Support line numbering with `--listings`.
+      If `numberLines` class is present, we add `numbers=left`;
+      if `startFrom` is present, we add `firstnumber=`. (#763)
+
+  * ConTeXt writer:
+
+    + Removed `\placecontent`.  This produced a duplicate toc,
+      in conjunction with `\placelist`.
+    + Use `\title`, `\subject` etc. for headers with
+      `unnumbered` class.
+
+  * Textile writer:
+
+    + Support header attributes.
+
+  * Markdown writer:
+
+    + Use grid tables when needed, and if enabled.  Closes #740.
+    + Render citations as pandoc-markdown citations.
+      Previously citations were rendered as citeproc-formatted citations
+      by default.  Now we render them as pandoc citations, e.g. `[@item1]`,
+      unless the `citations` extension is disabled.
+      If you still want formatted citations in your markdown output,
+      use `pandoc -t markdown-citations`.
+
+  * RST writer:
+
+    + Support `:number-lines:` in code blocks.
+
+  * Docx writer:
+
+    + Better treatment of display math.  Display math inside a
+      paragraph is now put in a separate paragraph, so it will render
+      properly (centered and without extra blank lines around it).
+      Partially addresses #742.
+    + Content types and document rels xml files are now created from
+      scratch, rather than being taken over from `reference.docx`.
+      This fixes problems that arise when you edit the `reference.docx`
+      with Word.
+    + We also now encode mime types for each individual image rather
+      than using defaults.  This should allow us to handle a wider
+      range of image types (including PDF).   Closes #414.
+    + Changed style names in `reference docx`.
+      `FootnoteReference` -> `FootnoteRef`, `Hyperlink` -> `Link`.
+      The old names got changed by Word when the `reference.docx` was
+      edited.  Closes #414.
+
+  * EPUB writer:
+
+    + Fix section numbering.  Previously the numbering restarted from 1
+      in each chapter (with `--number-sections`), though the numbers in
+      the table of contents were correct.
+    + Headers with "unnumbered" attribute are not numbered.  (Nor do they
+      cause an increment in running numbering.) Section numbers now work
+      properly, even when there is material before the first numbered section.
+    + Include HTML TOC, even in epub2.  The TOC is included in `<spine>`,
+      but `linear` is set to `no` unless the `--toc` option is specified.
+      Include `<guide>` element in OPF.  This should allow the TOC to
+      be usable in Kindles when converted with kindlegen. Closes #773.
+
+  * `Text.Pandoc.Parsing`: Optimized `oneOfStringsCI`.
+    This dramatically reduces the speed penalty that comes from enabling the
+    `autolink_bare_uris` extension.  The penalty is still substantial (in one
+    test, from 0.33s to 0.44s), but nowhere near what it used to be.
+    The RST reader is also much faster now, as it autodetects URIs.
+
+  * `Text.Pandoc.Shared`:  `hierarchicalize` will not number section
+    with class "unnumbered".  Unnumbered sections get `[]` for their
+    section number.
+
+  * `Text.Pandoc.Pretty`:
+
+    + Fixed `chomp` so it works inside `Prefixed` elements.
+    + Changed `Show` instance so it is better for debugging.
+
+  * `Text.Pandoc.ImageSize`:  Added `Pdf` to `ImageType`.
+
+  * `Text.Pandoc.UTF8`:  Strip off BOM if present.  Closes #743.
+
+  * Windows installer improvements:
+
+    + The installer is now signed with a certificate (thanks to
+      Fyodor Sheremetyev).
+    + WiX is used instead of InnoSetup.  The installer is now a
+      standard msi file.
+    + The version number is now auto-detected, and need not be
+      updated separately.
+
+  * OSX installer improvements:
+
+    + The package and pandoc executable are now signed with a
+      certificate (thanks to Fyodor Sheremetyev).
+    + RTF version of license is used.
+    + Use full path for sysctl in `InstallationCheck` script (jonahbull).
+      Closes #580.
+
+  * Converted COPYING to markdown.
+
+  * pandoc.cabal:  Require latest versions of highlighting-kate,
+    texmath, citeproc-hs, zip-archive.
+
+## pandoc 1.10.1 (2013-01-23)
+
+  * Markdown reader:  various optimizations, leading to a
+    significant performance boost.
+
+  * RST reader:  Allow anonymous form of inline links:
+    `` `hello <url>`__ `` Closes #724.
+
+  * Mediawiki reader: Don't require newlines after tables.
+    Thanks to jrunningen for the patch. Closes #733.
+
+  * Fixed LaTeX macro parsing.  Now LaTeX macro definitions are preserved
+    when output is LaTeX, and applied when it is another format.
+    Partially addresses #730.
+
+  * Markdown and RST readers:  Added parser to `block` that skips blank
+    lines.  This fixes a subtle regression involving grid tables with
+    empty cells.  Also added test for grid table with empty cells.
+    Closes #732.
+
+  * RST writer:  Use `.. code:: language` for code blocks with language.
+    Closes #721.
+
+  * DocBook writer:  Fixed output for hard line breaks, adding a newline
+    between `<literallayout>` tags.
+
+  * Markdown writer:  Use an autolink when link text matches url.
+    Previously we also checked for a null title, but this
+    test fails for links produced by citeproc-hs in bibliographies.
+    So, if the link has a title, it will be lost on conversion
+    to an autolink, but that seems okay.
+
+  * Markdown writer:  Set title, author, date variables as before.
+    These are no longer used in the default template, since we use
+    titleblock, but we set them anyway for those who use custom templates.
+
+  * LaTeX writer:  Avoid extra space at start/end of table cell.
+    Thanks to Nick Bart for the suggestion of using @{}.
+
+  * `Text.Pandoc.Parsing`:
+
+    + More efficient version of `anyLine`.
+    + Type of `macro` has changed; the parser now returns `Blocks`
+      instead of `Block`.
+
+  * Relaxed old-time version bound, allowing 1.0.*.
+
+  * Removed obsolete `hsmarkdown` script.  Those who need `hsmarkdown`
+    should create a symlink as described in the README.
+
+## pandoc 1.10.0.5 (2013-01-23)
+
+  * Markdown reader: Try `lhsCodeBlock` before `rawTeXBlock`.  Otherwise
+    `\begin{code}...\end{code}` isn't handled properly in markdown+lhs.
+    Thanks to Daniel Miot for noticing the bug and suggesting the fix.
+
+  * Markdown reader: Fixed bug with headerless grid tables.
+    The 1.10 code assumed that each table header cell contains exactly one
+    block. That failed for headerless tables (0) and also for tables with
+    multiple blocks in a header cell.  The code is fixed and tests provided.
+    Thanks to Andrew Lee for pointing out the bug.
+
+  * Markdown reader: Fixed regressions in fenced code blocks. Closes #722.
+
+    + Tilde code fences can again take a bare language string
+      (`~~~ haskell`), not just curly-bracketed attributes
+      (`~~~ {.haskell}`).
+    + Backtick code blocks can take the curly-bracketed attributes.
+    + Backtick code blocks don't *require* a language.
+    + Consolidated code for the two kinds of fenced code blocks.
+
+  * LaTeX template: Use `\urlstyle{same}` to avoid monospace URLs.
+
+  * Markdown writer: Use proportional font for email autolinks with
+    obfuscation.  Closes #714.
+
+  * Corrected name of `blank_before_blockquote` in README.  Closes #718.
+
+  * `Text.Pandoc.Shared`: Fixed bug in `uri` parser.
+    The bug prevented an autolink at the end of a string (e.g.
+    at the end of a line block line) from counting as a link.  Closes #711.
+
+  * Use the `hsb2hs` preprocessor instead of TH for embed_data_files.
+    This should work on Windows, unlike the TH solution with
+    file-embed.
+
+  * Eliminated use of TH in test suite.
+
+  * Added `Text.Pandoc.Data` (non-exported) to hold the association
+    list of embedded data files, if the `embed_data_files` flag is selected.
+    This isolates the code that needs special treatment with file-embed or
+    `hsb2hs`.
+
+  * Changes to `make-windows-installer.bat`.
+
+    + Exit batch file if any of the cabal-dev installs fail.
+    + There's no longer any need to reinstall `highlighting-kate`.
+    + Don't start with a `cabal update`; leave that to the user.
+    + Force reinstall of pandoc.
+
+  * Fixed EPUB writer so it builds with blaze-html 0.4.x. Thanks to
+    Jens Petersen.
+
+## pandoc 1.10.0.4 (2013-01-20)
+
+  * Fixed bug with escaped % in LaTeX reader. Closes #710.
+
+## pandoc 1.10.0.3 (2013-01-20)
+
+  * Added further missing fb2 tests to cabal file.
+
+## pandoc 1.10.0.2 (2013-01-20)
+
+  * Added fb2 tests to cabal file's extra-source-files.
+
+## pandoc 1.10.0.1 (2013-01-20)
+
+  * Bump version bounds on test-framework packages.
+
+## pandoc 1.10 (2013-01-19)
+
+### New features
+
+  * New input formats:  `mediawiki` (MediaWiki markup).
+
+  * New output formats:  `epub3` (EPUB v3 with MathML),
+    `fb2` (FictionBook2 ebooks).
+
+  * New `--toc-depth` option, specifying how many levels of
+    headers to include in a table of contents.
+
+  * New `--epub-chapter-level` option, specifying the header
+    level at which to divide EPUBs into separate files.
+    Note that this normally affects only performance, not the
+    visual presentation of the EPUB in a reader.
+
+  * Removed the `--strict` option.  Instead of using `--strict`,
+    one can now use the format name `markdown_strict` for either input
+    or output.  This gives more fine-grained control that `--strict`
+    did, allowing one to convert from pandoc's markdown to strict
+    markdown or vice versa.
+
+  * It is now possible to enable or disable specific syntax
+    extensions by appending them (with `+` or `-`) to the writer
+    or reader name.  For example,
+
+        pandoc -f markdown-footnotes+hard_line_breaks
+
+    disables footnotes and enables treating newlines as hard
+    line breaks.  The literate Haskell extensions are now implemented
+    this way as well, using either `+lhs` or `+literate_haskell`.
+    For a list of extension names, see the README under
+    "Pandoc's Markdown."
+
+  * The following aliases have been introduced for specific
+    combinations of markdown extensions:  `markdown_phpextra`,
+    `markdown_github`, `markdown_mmd`, `markdown_strict`.  These aliases
+    work just like regular reader and writer names, and can be modified
+    with extension modifiers as described above. (Note that conversion
+    from one markdown dialect to another does not work perfectly,
+    because there are differences in markdown parsers besides
+    just the extensions, and because pandoc's internal document model is
+    not rich enough to capture all of the extensions.)
+
+  * New `--html-q-tags` option.  The previous default was to use `<q>`
+    tags for smart quotes in HTML5.  But `<q>` tags are also valid HTML4.
+    Moreover, they are not a robust way of typesetting quotes, since
+    some user agents don't support them, and some CSS resets (e.g.
+    bootstrap) prevent pandoc's quotes CSS from working properly.
+    We now just insert literal quote characters by default in both
+    `html` and `html5` output, but this option is provided for
+    those who still want `<q>` tags.
+
+  * The markdown reader now prints warnings (to stderr) about
+    duplicate link and note references.  Closes #375.
+
+  * Markdown syntax extensions:
+
+    + Added pipe tables.  Thanks to François Gannaz for the initial patch.
+      These conform to PHP Markdown Extra's pipe table syntax. A subset
+      of org-mode table syntax is also supported, which means that you can
+      use org-mode's nice table editor to create tables.
+
+    + Added support for RST-style line blocks. These are
+      useful for verse and addresses.
+
+    + Attributes can now be specified for headers, using the same
+      syntax as in code blocks.  (However, currently only the
+      identifier has any effect in most writers.)  For example,
+
+            # My header {#foo}
+
+            See [the header above](#foo).
+
+    + Pandoc will now act as if link references have been defined
+      for all headers without explicit identifiers.
+      So, you can do this:
+
+            # My header
+
+            Link to [My header].
+            Another link to [it][My header].
+
+      Closes #691.
+
+  * LaTeX reader:
+
+    + Command macros now work everywhere, including non-math.
+      Environment macros still not supported.
+    + `\input` now works, as well as `\include`.  TEXINPUTS is used.
+      Pandoc looks recursively into included files for more included files.
+
+### Behavior changes
+
+  * The Markdown reader no longer puts the text of autolinks in a
+    `Code` inline.  This means that autolinks will no longer appear
+    in a monospace font.
+
+  * The character `/` can now appear in markdown citation keys.
+
+  * HTML blocks in strict_markdown are no longer required to begin
+    at the left margin.  Technically this is required, according to
+    the markdown syntax document, but `Markdown.pl` and other markdown
+    processors are more liberal.
+
+  * The `-V` option has been changed so that if there are duplicate
+    variables, those specified later on the command line take precedence.
+
+  * Tight lists now work in LaTeX and ConTeXt output.
+
+  * The LaTeX writer no longer relien on the `enumerate` package.
+    Instead, it uses standard LaTeX commands to change the list numbering
+    style.
+
+  * The LaTeX writer now uses `longtable` instead of `ctable`. This allows
+    tables to be split over page boundaries.
+
+  * The RST writer now uses a line block to render paragraphs containing
+    linebreaks (which previously weren't supported at all).
+
+  * The markdown writer now applies the `--id-prefix` to footnote IDs.
+    Closes #614.
+
+  * The plain writer no longer uses backslash-escaped line breaks
+    (which are not very "plain").
+
+  * `Text.Pandoc.UTF8`: Better error message for invalid UTF8.
+    Read bytestring and use `Text`'s decodeUtf8 instead of using
+    `System.IO.hGetContents`.  This way you get a message saying
+    "invalid UTF-8 stream" instead of "invalid byte sequence."
+    You are also told which byte caused the problem.
+
+  * Docx, ODT, and EPUB writers now download images specified by a URL
+    instead of skipping them or raising an error.
+
+  * EPUB writer:
+
+    + The default CSS now left-aligns headers by default, instead of
+      centering.  This is more consistent with the rest of the writers.
+    + A proper multi-level table of contents is now used in `toc.ncx`.
+      There is no longer a subsidiary table of contents at the beginning
+      of each chapter.
+    + Code highlighting now works by default.
+    + Section divs are used by default for better semantic markup.
+    + The title is used instead of "Title Page" in the table of contents.
+      Otherwise we have a hard-coded English string, which looks
+      strange in ebooks written in other languages.  Closes #572.
+
+  * HTML writer:
+
+    + Put mathjax in span with class "math".  Closes #562.
+    + Put citations in a span with class "citation." In HTML5, also include
+      a `data-cite` attribute with a space-separated list of citation
+      keys.
+
+  * `Text.Pandoc.UTF8`:  use universalNewlineMode in reading.
+    This treats both `\r\n` and `\n` as `\n` on input, no matter
+    what platform we're running on.
+
+  * Citation processing is now done in the Markdown and LaTeX
+    readers, not in `pandoc.hs`.  This makes it easier for library users
+    to use citations.
+
+### Template changes
+
+  * HTML: Added css to template to preserve spaces in `<code>` tags.
+    Thanks to Dirk Laurie.
+
+  * Beamer:  Remove English-centric strings in section pages.
+    Section pages used to have "Section" and a number as well as the
+    section title. Now they just have the title.  Similarly for part
+    and subsection.  Closes #566.
+
+  * LaTeX, ConTeXt: Added papersize variable.
+
+  * LaTeX, Beamer templates: Use longtable instead of ctable.
+
+  * LaTeX, Beamer templates: Don't require 'float' package for tables.
+    We don't actually seem to use the '[H]' option.
+
+  * Markdown, plain: Fixed titleblock so it is just a single string.
+    Previously separate title, author, and date variables were used,
+    but this didn't allow different kinds of title blocks.
+
+  * EPUB:
+
+    + Rationalized templates.  Previously there were three different
+      templates involved in epub production. There is now just one
+      template, `default.epub` or `default.epub3`. It can now be
+      overridden using `--template`, just like other templates.
+      The titlepage is now folded into the default template.
+      A `titlepage` variable selects it.
+    + UTF-8, lang tag, meta tags, title element.
+
+  * Added scale-to-width feature to beamer template
+
+### API changes
+
+  * `Text.Pandoc.Definition`: Added `Attr` field to `Header`.
+    Previously header identifiers were autogenerated by the writers.
+    Now they are added in the readers (either automatically or explicitly).
+
+  * `Text.Pandoc.Builder`:
+
+    + `Inlines` and `Blocks` are now synonyms for `Many Inline` and
+      `Many Block`.  `Many` is a newtype wrapper around `Seq`, with
+      custom Monoid instances for `Many Inline` and `Many Block.  This
+      allows `Many` to be made an instance of `Foldable` and `Traversable`.
+    + The old `Listable` class has been removed.
+    + The module now exports `isNull`, `toList`, `fromList`.
+    + The old `Read` and `Show` instances have been removed; derived
+      instances are now used.
+    + Added `headerWith`.
+
+  * The readers now take a `ReaderOptions` rather than a `ParserState`
+    as a parameter.  Indeed, not all parsers use the `ParserState` type;
+    some have a custom state.  The motivation for this change was to separate
+    user-specifiable options from the accounting functions of parser state.
+
+  * New module `Text.Pandoc.Options`.  This includes the `WriterOptions`
+    formerly in `Text.Pandoc.Shared`, and its associated
+    data types.  It also includes a new type `ReaderOptions`, which
+    contains many options formerly in `ParserState`, and its associated
+    data types:
+
+    + `ParserState.stateParseRaw` -> `ReaderOptions.readerParseRaw`.
+    + `ParserState.stateColumns` -> `ReaderOptions.readerColumns`.
+    + `ParserState.stateTabStop` -> `ReaderOptions.readerTabStop`.
+    + `ParserState.stateOldDashes` -> `ReaderOptions.readerOldDashes`.
+    + `ParserState.stateLiterateHaskell` -> `ReaderOptions.readerLiterateHaskell`.
+    + `ParserState.stateCitations` -> `ReaderOptions.readerReferences`.
+    + `ParserState.stateApplyMacros` -> `ReaderOptions.readerApplyMacros`.
+    + `ParserState.stateIndentedCodeClasses` ->
+      `ReaderOptions.readerIndentedCodeClasses`.
+    + Added `ReaderOptions.readerCitationStyle`.
+
+  * `WriterOptions` now includes `writerEpubVersion`, `writerEpubChapterLevel`,
+    `writerEpubStylesheet`, `writerEpubFonts`, `writerReferenceODT`,
+    `writerReferenceDocx`, and `writerTOCDepth`.  `writerEPUBMetadata` has
+    been renamed `writerEpubMetadata` for consistency.
+
+  * Changed signatures of `writeODT`, `writeDocx`, `writeEPUB`, since they no
+    longer stylesheet, fonts, reference files as separate parameters.
+
+  * Removed `writerLiterateHaskell` from `WriterOptions`, and
+    `readerLiterateHaskell` from `ReaderOptions`.  LHS is now handled
+    by an extension (`Ext_literate_haskell`).
+
+  * Removed deprecated `writerXeTeX`.
+
+  * Removed `writerStrict` from `WriterOptions`.  Added `writerExtensions`.
+    Strict is now handled through extensions.
+
+  * `Text.Pandoc.Options` exports `pandocExtensions`, `strictExtensions`,
+    `phpMarkdownExtraExtensions`, `githubMarkdownExtensions`,
+    and `multimarkdownExtensions`, as well as the `Extensions` type.
+
+  * New `Text.Pandoc.Readers.MediaWiki` module, exporting
+    `readMediaWiki`.
+
+  * New `Text.Pandoc.Writers.FB2` module, exporting `writeFB2`
+    (thanks to Sergey Astanin).
+
+  * `Text.Pandoc`:
+
+    + Added `getReader`, `getWriter` to `Text.Pandoc`.
+    + `writers` is now an association list `(String, Writer)`.
+      A `Writer` can be a `PureStringWriter`, an `IOStringWriter`, or
+      an `IOByteStringWriter`.  ALL writers are now in the 'writers'
+      list, including the binary writers and FB2 writer.  This allows
+      code in `pandoc.hs` to be simplified.
+    + Changed type of `readers`, so all readers are in IO.
+      Users who want pure readers can still get them form the reader
+      modules; this just affects the function `getReader` that looks up
+      a reader based on the format name.  The point of this change is to
+      make it possible to print warnings from the parser.
+
+  * `Text.Pandoc.Parsing`:
+
+    + `Text.Parsec` now exports all Parsec functions used in pandoc code.
+      No other module directly imports Parsec.  This will make it easier
+      to change the parsing backend in the future, if we want to.
+    + `Text.Parsec` is used instead of `Text.ParserCombinators.Parsec`.
+    + Export the type synonym `Parser`.
+    + Export `widthsFromIndices`, `NoteTable'`, `KeyTable'`, `Key'`, `toKey'`,
+     `withQuoteContext`, `singleQuoteStart`, `singleQuoteEnd`,
+     `doubleQuoteStart`, `doubleQuoteEnd`, `ellipses`, `apostrophe`,
+     `dash`, `nested`, `F(..)`, `askF`, `asksF`, `runF`, `lineBlockLines`.
+    + `ParserState` is no longer an instance of `Show`.
+    + Added `stateSubstitutions` and `stateWarnings` to `ParserState`.
+    + Generalized type of `withQuoteContext`.
+    + Added `guardEnabled`, `guardDisabled`, `getOption`.
+    + Removed `failIfStrict`.
+    + `lookupKeySrc` and `fromKey` are no longer exported.
+
+  * `Data.Default` instances are now provided for `ReaderOptions`,
+    `WriterOptions`, and `ParserState`.  `Text.Pandoc` re-exports `def`.
+    Now you can use `def` (which is re-exported by `Text.Pandoc`) instead
+    of `defaultWriterOptions` (which is still defined).  Closes #546.
+
+  * `Text.Pandoc.Shared`:
+
+    + Added `safeRead`.
+    + Renamed `removedLeadingTrailingSpace` to `trim`,
+      `removeLeadingSpace` to `triml`, and `removeTrailingSpace` to `trimr`.
+    + Count `\r` as space in `trim` functions.
+    + Moved `renderTags'` from HTML reader and `Text.Pandoc.SelfContained`
+      to `Shared`.
+    + Removed `failUnlessLHS`.
+    + Export `compactify'`, formerly in Markdown reader.
+    + Export `isTightList`.
+    + Do not export `findDataFile`.
+    + `readDataFile` now returns a strict ByteString.
+    + Export `readDataFileUTF8` which returns a String, like the
+      old `readDataFile`.
+    + Export `fetchItem` and `openURL`.
+
+  * `Text.Pandoc.ImageSize`: Use strict, not lazy bytestrings.
+    Removed `readImageSize`.
+
+  * `Text.Pandoc.UTF8`: Export `encodePath`, `decodePath`,
+     `decodeArg`, `toString`, `fromString`, `toStringLazy`,
+     `fromStringLazy`.
+
+  * `Text.Pandoc.UTF8` is now an exposed module.
+
+  * `Text.Pandoc.Biblio`:
+
+    + csl parameter now a `String` rather than a `FilePath`.
+    + Changed type of `processBiblio`.  It is no longer in the IO monad.
+      It now takes a `Maybe Style` argument rather than parameters for CSL
+      and abbrev filenames.  (`pandoc.hs` now calls the functions to parse
+      the style file and add abbreviations.)
+
+  * Markdown reader now exports `readMarkdownWithWarnings`.
+
+  * `Text.Pandoc.RTF` now exports `writeRTFWithEmbeddedImages` instead of
+    `rtfEmbedImage`.
+
+### Bug fixes
+
+  * Make `--ascii` work properly with `--self-contained`.  Closes #568.
+
+  * Markdown reader:
+
+    + Fixed link parser to avoid exponential slowdowns.  Closes #620.
+      Previously the parser would hang on input like this:
+
+            [[[[[[[[[[[[[[[[[[hi
+
+      We fixed this by making the link parser parser characters
+      between balanced brackets (skipping brackets in inline code spans),
+      then parsing the result as an inline list.  One change is that
+
+            [hi *there]* bud](/url)
+
+      is now no longer parsed as a link.  But in this respect pandoc behaved
+      differently from most other implementations anyway, so that seems okay.
+
+    + Look for raw html/latex blocks before tables.
+      Otherwise the following gets parsed as a table:
+
+            \begin{code}
+            --------------
+            -- My comment.
+            \end{code}
+
+      Closes #578.
+
+  * RST reader:
+
+    + Added support for `:target:` on `.. image::` blocks
+      and substitutions.
+    + Field list fixes:
+
+        - Fixed field lists items with body beginning after a new line
+          (Denis Laxalde).
+        - Allow any char but ':' in names of field lists in RST reader
+          (Denis Laxalde).
+        - Don't allow line breaks in field names.
+        - Require whitespace after field list field names.
+        - Don't create empty definition list for metadata field lists.
+          Previously a field list consisting only of metadata fields (author,
+          title, date) would be parsed as an empty DefinitionList, which is
+          not legal in LaTeX and not needed in any format.
+
+    + Don't recognize inline-markup starts inside words.
+      For example, `2*2 = 4*1` should not contain an emphasized
+      section.  Added test case for "Literal symbols".  Closes #569.
+    + Allow dashes as separator in simple tables.  Closes #555.
+    + Added support for `container`, `compound`, `epigraph`,
+      `rubric`, `highlights`, `pull-quote`.
+    + Added support for `.. code::`.
+    + Made directive labels case-insensitive.
+    + Removed requirement that directives begin at left margin.
+      This was (correctly) not in earlier releases; docutils doesn't
+      make the requirement.
+    + Added support for `replace::` and `unicode::` substitutions.
+    + Ignore unknown interpreted roles.
+    + Renamed image parser to `subst`, since it now handles all
+      substitution references.
+
+  * Textile reader:
+
+    + Allow newlines before pipes in table.  Closes #654.
+    + Fixed bug with list items containing line breaks.
+      Now pandoc correctly handles hard line breaks inside list items.
+      Previously they broke list parsing.
+    + Implemented comment blocks.
+    + Fixed bug affected words ending in hyphen.
+    + Properly handle links with surrounding brackets.
+      Square brackets need to be used when the link isn't surrounded by
+      spaces or punctuation, or when the URL ending may be ambiguous.
+      Closes #564.
+    + Removed nullBlock.  Better to know about parsing problems than
+      to skip stuff when we get stuck.
+    + Allow ID attributes on headers.
+    + Textile reader:  Avoid parsing dashes as strikeout.
+      Previously the input
+
+            text--
+            text--
+            text--
+            text--
+
+      would be parsed with strikeouts rather than dashes. This fixes
+      the problem by requiring that a strikeout delimiting - not be
+      followed by a -.  Closes #631.
+    + Expanded list of `stringBreakers`.
+      This fixes a bug on input like "(_hello_)" which should
+      be a parenthesized emphasized "hello".
+      The new list is taken from the PHP source of textile 2.4.
+    + Fixed autolinks.  Previously the textile reader and writer
+      incorrectly implemented RST-style autolinks for URLs and email
+      addresses.  This has been fixed.  Now an autolink is done this way:
+      `"$":http://myurl.com`.
+    + Fixed footnotes bug in textile.  This affected notes occurring
+      before punctuation, e.g. `foo[1].`.  Closes #518.
+
+  * LaTeX reader:
+
+    + Better handling of citation commands.
+    + Better handling of `\noindent`.
+    + Added a 'try' in rawLaTeXBlock, so we can handle `\begin` without `{`.
+      Closes #622.
+    + Made `rawLaTeXInline` try to parse block commands as well.  This
+      is usually what we want, given how `rawLaTeXInline` is used in
+      the markdown and textile readers.  If a block-level LaTeX command
+      is used in the middle of a paragraph (e.g. `\subtitle` inside a title),
+      we can treat it as raw inline LaTeX.
+    + Handle `\slash` command.  Closes #605.
+    + Basic `\enquote` support.
+    + Fixed parsing of paragraphs beginning with a group.  Closes #606.
+    + Use curly quotes for bare straight quotes.
+    + Support obeylines environment.  Closes #604.
+    + Guard against "begin", "end" in inlineCommand and
+      blockCommand.
+    + Better error messages for environments.  Now it should tell you that
+      it was looking for \end{env}, instead of giving "unknown parse error."
+
+  * HTML reader:
+
+    + Added HTML 5 tags to list of block-level tags.
+    + HTML reader: Fixed bug in `htmlBalanced`, which
+      caused hangs in parsing certain markdown input using
+      strict mode.
+    + Parse `<q>` as `Quoted DoubleQuote`.
+    + Handle nested `<q>` tags properly.
+    + Modified `htmlTag` for fewer false positives.
+      A tag must start with `<` followed by `!`,`?`, `/`, or a letter.
+      This makes it more useful in the wikimedia and markdown parsers.
+
+  * DocBook reader: Support title in "figure" element.  Closes #650.
+
+  * MediaWiki writer:
+
+    + Remove newline after `<br/>` in translation of `LineBreak`
+      There's no particular need for a newline (other than making the
+      generated MediaWiki source look nice to a human), and in fact
+      sometimes it is incorrect: in particular, inside an enumeration, list
+      items cannot have embedded newline characters. (Brent Yorgey)
+    + Use `<code>` not `<tt>` for Code.
+
+  * Man writer: Escape `-` as `\-`.
+    Unescaped `-`'s become hyphens, while `\-`'s are left as ascii minus
+    signs.  That is preferable for use with command-line options.  See
+    <http://lintian.debian.org/tags/hyphen-used-as-minus-sign.html>.  Thanks
+    to Andrea Bolognani for bringing the issue to our attention.
+
+  * RST writer:
+
+    + Improved line block output. Use nonbreaking spaces for
+      initial indent (otherwise lost in HTML and LaTeX).
+      Allow multiple paragraphs in a single line block.
+      Allow soft breaks w continuations in line blocks.
+    + Properly handle images with no alt text.  Closes #678.
+    + Fixed bug with links with duplicate text.  We now (a) use anonymous
+      links for links with inline URLs, and (b) use an inline link instead
+      of a reference link if the reference link would require a label that
+      has already been used for a different link.  Closes #511.
+    + Fixed hyperlinked images. Closes #611. Use `:target:`
+      field when you have a simple linked image.
+    + Don't add `:align: center` to figures.
+
+  * Texinfo writer:  Fixed internal cross-references.
+    Now we insert anchors after each header, and use `@ref` instead of `@uref`
+    for links.  Commas are now escaped as `@comma{}` only when needed;
+    previously all commas were escaped.  (This change is needed, in part,
+    because `@ref` commands must be followed by a real comma or period.) Also
+    insert a blank line in from of `@verbatim` environments.
+
+  * DocBook writer:
+
+    + Made --id-prefix work in DocBook as well as HTML.
+      Closes #607.
+    + Don't include empty captions in figures.  Closes #581.
+
+  * LaTeX writer:
+
+    + Use `\hspace*` for nonbreaking space after line break,
+      since `~` spaces after a line break are just ignored.
+      Closes #687.
+    + Don't escape `_` in URLs or hyperref identifiers.
+    + Properly escape strings inside `\url{}`.  Closes #576.
+    + Use `[fragile]` only for slides containing code rendered
+      using listings. Closes #649.
+    + Escape `|` as `\vert` in LaTeX math.  This avoids a clash with
+      highlighting-kate's macros, which redefine `|` as a short verbatim
+      delimiter.  Thanks to Björn Peemöller for raising this issue.
+    + Use minipage rather than parbox for block containers in tables.
+      This allows verbatim code to be included in grid tables.
+      Closes #663.
+    + Prevent paragraphs containing only linebreaks or spaces.
+
+  * HTML writer:
+
+    + Included `highlighting-css` for code spans, too.
+      Previously it was only included if used in a code block.  Closes #653.
+    + Improved line breaks with `<dd>` tags.  We now put a newline between
+      `</dd>` and `<dd>` when there are multiple definitions.
+    + Changed mathjax cdn url so it doesn't use https.  (This caused
+      problems when used with `--self-contained`.) See #609.
+
+  * EPUB writer:
+
+    + `--number-sections` now works properly.
+    + Don't strip meta and link elements in epub metadata.
+      Patch from aberrancy. Closes #589.
+    + Fixed a couple validation bugs.
+    + Use ch001, ch002, etc. for chapter filenames.  This improves sorting
+      of chapters in some readers, which apparently sort ch2 after ch10.
+      Closes #610.
+
+  * ODT writer: properly set title property (Arlo O'Keeffe).
+
+  * Docx writer:
+
+    + Fixed bug with nested lists.  Previously a list like
+
+            1. one
+                - a
+                - b
+            2. two
+
+      would come out with a bullet instead of "2."
+      Thanks to Russell Allen for reporting the bug.
+    + Use `w:cr` in `w:r` instead of `w:br` for linebreaks.
+      This seems to fix a problem viewing pandoc-generated
+      docx files in LibreOffice.
+    + Use integer ids for bookmarks.  Closes #626.
+    + Added nsid to abstractNum elements.  This helps when merging
+      word documents with numbered or bulleted lists.  Closes #627.
+    + Use separate footnotes.xml for notes.
+      This seems to help LibreOffice convert the file, even though
+      it was valid docx before.  Closes #637.
+    + Use rIdNN identifiers for r:embed in images.
+    + Avoid reading image files again when we've already processed them.
+    + Fixed typo in `referenc.docx` that prevented image captions from
+      working. Thanks to Huashan Chen.
+
+  * `Text.Pandoc.Parsing`:
+
+    + Fixed bug in `withRaw`, which didn't correctly handle the case
+      where nothing is parsed.
+    + Made `emailAddress` parser more correct.  Now it is based on RFC 822,
+      though it still doesn't implement quoted strings in email addresses.
+    + Revised URI parser.  It now allows many more schemes, allows
+      uppercase URIs, and better handles trailing punctuation and
+      trailing slashes in bare URIs.  Added many tests.
+    + Simplified and improved singleQuoteStart.  This makes `'s'`, `'l'`,
+      etc. parse properly.  Formerly we had some English-centric heuristics,
+      but they are no longer needed. Closes #698.
+
+  * `Text.Pandoc.Pretty`:  Added wide punctuation range to `charWidth`.
+    This fixes bug with Chinese commas in markdown and reST tables, and
+    a bug that caused combining characters to be dropped.
+
+  * `Text.Pandoc.MIME`: Added MIME types for .wof and .eot.  Closes #640.
+
+  * `Text.Pandoc.Biblio`:
+
+    + Run `mvPunc` and `deNote` on metadata too.
+      This fixed a bug with notes on titles using footnote styles.
+    + Fixed bug in fetching CSL files from CSL data directory.
+
+  * `pandoc.hs`:  Give correct value to `writerSourceDirectory` when a URL
+    is provided.  It should be the URL up to the path.
+
+  * Fixed/simplified diff output for tests.
+    Biblio: Make sure mvPunc and deNote run on metadata too.
+    This fixed a bug with notes on titles using footnote styles.
+
+### Under the hood improvements
+
+  * We no longer depend on `utf8-string`.  Instead we use functions
+    defined in `Text.Pandoc.UTF8` that use `Data.Text`'s conversions.
+
+  * Use `safeRead` instead of using `reads` directly (various modules).
+
+  * "Implicit figures" (images alone in a paragraph) are now handled
+    differently.  The markdown reader gives their titles the prefix `fig:`; the
+    writers look for this before treating the image as a figure.  Though this
+    is a bit of a hack, it has two advantages: (i) implicit figures can be
+    limited to the markdown reader, and (ii) they can be deactivated by turning
+    off the `implicit_figures` extension.
+
+  * `catch` from `Control.Exception` is now used instead of the
+    old Preface `catch`.
+
+  * `Text.Pandoc.Shared`:  Improved algorithm for `normalizeSpaces`
+    and `oneOfStrings` (which is now non-backtracking).
+
+  * `Text.Pandoc.Biblio`: Remove workaround for `toCapital`.
+    Now citeproc-hs is fixed upstream, so this is no longer needed.
+    Closes #531.
+
+  * Textile reader: Improved speed of `hyphenedWords`.
+    This speeds up the textile  reader by about a factor of 4.
+
+  * Use `Text.Pandoc.Builder` in RST reader, for more flexibility,
+    better performance, and automatic normalization.
+
+  * Major rewrite of markdown reader:
+
+    + Use `Text.Pandoc.Builder` instead of lists.  This also
+      means that everything is normalized automatically.
+    + Move to a one-pass parsing strategy, returning values in the reader
+      monad, which are then run (at the end of parsing) against the final
+      parser state.
+
+  * In HTML writer, we now use `toHtml` instead of pre-escaping.
+    We work around the problem that blaze-html unnecessarily escapes `'`
+    by pre-escaping just the `'` characters, instead of the whole string.
+    If blaze-html later stops escaping `'` characters, we can simplify
+    `strToHtml` to `toHtml`.  Closes #629.
+
+  * Moved code for embedding images in RTFs from `pandoc.hs` to the
+    RTF writer (which now exports `writeRTFWithEmbeddedImages`).
+
+  * Moved citation processing from `pandoc.hs` into the readers.
+    This makes things more convenient for library users.
+
+  * The man pages are now built by an executable `make-pandoc-man-pages`,
+    which has its own stanza in the cabal file so that dependencies can be
+    handled by Cabal. Special treatment in `Setup.hs` ensures that this
+    executable never gets installed; it is only used to create the man pages.
+
+  * The cabal file has been modified so that the pandoc library is used
+    in building the pandoc executable.  (This required moving `pandoc.hs`
+    from `src` to `.`.)  This cuts compile time in half.
+
+  * The `executable` and `library` flags have been removed.
+
+  * `-threaded` has been removed from ghc-options.
+
+  * Version bounds of dependencies have been raised, and the
+    `blaze_html_0_5` flag now defaults to True.  Pandoc now compiles on
+    GHC 7.6.
+
+  * We now require base >= 4.2.
+
+  * Integrated the benchmark program into cabal.  One can now do:
+
+        cabal configure --enable-benchmarks && cabal build
+        cabal bench --benchmark-option='markdown' --benchmark-option='-s 20'
+
+    The benchmark now uses README + testsuite, so benchmark results
+    from older versions aren't comparable.
+
+  * Integrated test suite with cabal.
+    To run tests, configure with `--enable-tests`, then `cabal test`.
+    You can specify particular tests using `--test-options='-t markdown'`.
+    No output is shown unless tests fail.  The Haskell test modules
+    have been moved from `src/` to `tests/`.
+
+  * Moved all data files and templates to the `data/` subdirectory.
+
+  * Added an `embed_data_files` cabal flag.  This causes all
+    data files to be embedded in the binary, so that the binary
+    is self-sufficient and can be relocated anywhere, copied on
+    a USB key, etc.  The Windows installer now uses this.
+    (Since we no longer have the option to build the executable
+    without the library, this is the only way to get a relocatable
+    binary on Windows.)
+
+  * Removed pcre3.dll from windows package.
+    It isn't needed unless highlighting-kate is compiled with the
+    `pcre-light` flag. By default, regex-prce-builtin is used.
+
+
+## pandoc 1.9.4.5 (2012-10-21)
+
+  * Raised version bounds on network, base64-bytestring, json,
+    and template-haskell.
+
+## pandoc 1.9.4.4 (2012-10-20)
+
+  * Removed `tests` flag and made test suite into a proper cabal
+    test suite, which can now be enabled using `--enable-tests`
+    and run with `cabal test`.
+
+  * Moved man page creation out of `Setup.hs` and into an
+    executable built by Cabal, but never installed.  This
+    allows dependencies to be specified, and solves a problem
+    with 1.9.4.3, which could only be installed if `data-default`
+    had already been installed.
+
+  * Updated `lhs-latex.tex` test for latest highlighting-kate
+    representation of backticks.
+
+## pandoc 1.9.4.3 (2012-10-20)
+
+  * Removed `-threaded` from default compile flags.
+
+  * Modified modules to compile with GHC 7.6 and latest version of time
+    package.
+
+## pandoc 1.9.4.2 (2012-06-29)
+
+  * Don't encode/decode file paths if base >= 4.4.
+    Prior to base 4.4, filepaths and command line arguments were treated
+    as unencoded lists of bytes, not unicode strings, so we had to work
+    around that by encoding and decoding them. This commit adds CPP
+    checks for the base version that intelligibly enable encoding/decoding
+    when needed. Fixes a bug with multilingual filenames when pandoc was
+    compiled with ghc 7.4 (#540).
+
+  * Don't generate an empty H1 after hrule slide breaks.
+    We now use a slide-level header with contents `[Str "\0"]` to mark
+    an hrule break.  This avoids creation of an empty H1 in these
+    contexts.  Closes #484.
+
+  * Docbook reader: Added support for "bold" emphasis.  Thanks to mb21.
+
+  * In make_osx_package.sh, ensure citeproc-hs is built with the
+    embed_data_files flag.
+
+  * MediaWiki writer: Avoid extra blank lines after sublists (Gavin Beatty).
+
+  * ConTeXt writer: Don't escape `&`, `^`, `<`, `>`, `_`,
+    simplified escapes for `}` and `{` to `\{` and `\}` (Aditya Mahajan).
+
+  * Fixed handling of absolute URLs in CSS imports with `--self-contained`.
+    Closes #535.
+
+  * Added webm to mime types. Closes #543.
+
+  * Added some missing exports and tests to the cabal file
+    (Alexander V Vershilov).
+
+  * Compile with `-rtsopts` and `-threaded` by default.
+
+## pandoc 1.9.4.1 (2012-06-08)
+
+  * Markdown reader: Added `cf.` and `cp.` to list of likely abbreviations.
+
+  * LaTeX template: Added `linkcolor`, `urlcolor` and `links-as-notes`
+    variables.  Make TOC links black.
+
+  * LaTeX template improvements.
+
+    + Don't print date unless one is given explicitly in the document.
+    + Simplified templates.
+    + Use fontenc [T1] by default, and lmodern.
+    + Use microtype if available.
+
+  * Biblio:
+
+    + Add comma to beginning of bare suffix, e.g. `@item1 [50]`.
+      Motivation: `@item1 [50]` should be as close as possible to
+      `[@item1, 50]`.
+    + Added workaround for a bug in citeproc-hs 0.3.4 that causes footnotes
+      beginning with a citation to be empty.  Closes #531.
+
+  * Fixed documentation on mixed lists.  Closes #533.
+
+## pandoc 1.9.4 (2012-06-03)
+
+  * Simplified `Text.Pandoc.Biblio` and fixed bugs with citations inside
+    footnotes and captions.  We now handle note citations by inserting
+    footnotes during initial citation processing, and doing a separate
+    pass later to remove notes inside notes.
+
+  * Added 'zenburn' highlight style from highlighting-kate.
+
+  * Added Slideous writer. Slideous is an HTML + javascript slide show
+    format, similar to Slidy, but works with IE 7. (Jonas Smedegaard)
+
+  * LaTeX writer:
+
+    + Ensure we don't have extra blank lines at ends of cells.
+      This can cause LaTeX errors, as they are interpreted as new paragraphs.
+    + More consistent interblock spacing.
+    + Require highlighting-kate >= 0.5.1, for proper highlighted inline
+      code in LaTeX.  Closes #527.
+    + Ensure that a Verbatim at the end of a footnote is followed by
+      a newline. (Fixes a regression in the previous version.)
+    + In default template, use black for internal links and TOC.
+      Added commented-out code to use footnotes for links, as would
+      be suitable in print output.
+
+  * Beamer writer:  When `--incremental` is used, lists inside
+    a block quote should appear all at once.  (This makes Beamer
+    output consistent with the HTML slide show formats.)
+
+  * ConTeXt writer:
+
+    + Escape `%` as `\letterpercent{}` not `\letterpercent `,
+      to avoid gobbling spaces after the `%` sign.
+    + Ensure space after `\stopformula`.
+
+  * Markdown writer:
+
+    + Use `:` form instead of `~` in definition lists, for better
+      compatibility with other markdown implementations.
+    + Don't wrap the term, because it breaks definition lists.
+    + Use a nonzero space to prevent false recognition
+      of list marker in ordered lists.  Closes #516.
+
+  * Org writer: Add space before language name.  Closes #523.
+
+  * Docx writer: Simplified bullet characters so they work properly
+    with Word 2007. Closes #520.
+
+  * LaTeX reader: Support `\centerline`.
+
+  * RST reader:  handle figures.  Closes #522.
+
+  * Textile reader: fix for `<notextile>` and `==`.  Closes #517.
+    (Paul Rivier)
+
+## pandoc 1.9.3 (2012-05-12)
+
+  * Added docbook reader (with contributions from Mauro Bieg).
+
+  * Fixed bug in `fromEntities`.  The previous version would turn
+    `hi & low you know;` into `hi &`.
+
+  * HTML reader:
+
+    + Don't skip nonbreaking spaces.
+      Previously a paragraph containing just `&nbsp;` would be rendered
+      as an empty paragraph. Thanks to Paul Vorbach for pointing out the bug.
+    + Support `<col>` and `<caption>` in tables. Closes #486.
+
+  * Markdown reader:
+
+    + Don't recognize references inside delimited code blocks.
+    + Allow list items to begin with lists.
+
+  * LaTeX reader:
+
+    + Handle `\bgroup`, `\egroup`, `\begingroup`, `\endgroup`.
+    + Control sequences can't be followed by a letter.
+      This fixes a bug where `\begingroup` was parsed as `\begin`
+      followed by `group`.
+    + Parse 'dimension' arguments to unknown commands.  e.g. `\parindent0pt`
+    + Make `\label` and `\ref` sensitive to `--parse-raw`.
+      If `--parse-raw` is selected, these will be parsed as raw latex
+      inlines, rather than bracketed text.
+    + Don't crash on unknown block commands (like `\vspace{10pt}`)
+      inside `\author`; just skip them.  Closes #505.
+
+  * Textile reader:
+
+    + Implemented literal escapes with `==` and `<notextile>`.  Closes #473.
+    + Added support for LaTeX blocks and inlines (Paul Rivier).
+    + Better conformance to RedCloth inline parsing (Paul Rivier).
+    + Parse '+text+' as emphasized (should be underlined, but this
+      is better than leaving literal plus characters in the output.
+
+  * Docx writer: Fixed multi-paragraph list items.  Previously they each
+    got a list marker.  Closes #457.
+
+  * LaTeX writer:
+
+    + Added `--no-tex-ligatures` option to avoid replacing
+      quotation marks and dashes with TeX ligatures.
+    + Use `fixltx2e` package to provide `\textsubscript`.
+    + Improve spacing around LaTeX block environments:
+      quote, verbatim, itemize, description, enumerate.
+      Closes #502.
+    + Use blue instead of pink for URL links in latex/pdf output.
+
+  * ConTeXt writer: Fixed escaping of `%`.
+    In text, `%` needs to be escaped as `\letterpercent`, not `\%`
+    Inside URLs, `%` needs to be escaped as `\%`
+    Thanks to jmarca and adityam for the fix.  Closes #492.
+
+  * Texinfo writer:  Escape special characters in node titles.
+    This fixes a problem pointed out by Joost Kremers.  Pandoc used
+    to escape an '@' in a chapter title, but not in the corresponding
+    node title, leading to invalid texinfo.
+
+  * Fixed document encoding in texinfo template.
+    Resolves Debian Bug #667816.
+
+  * Markdown writer:
+
+    + Don't force delimited code blocks to be flush left.
+      Fixes bug with delimited code blocks inside lists etc.
+    + Escape `<` and `$`.
+
+  * LaTeX writer: Use `\hyperref[ident]{text}` for internal links.
+    Previously we used `\href{\#ident}{text}`, which didn't work on
+    all systems. Thanks to Dirk Laurie.
+
+  * RST writer: Don't wrap link references.  Closes #487.
+
+  * Updated to use latest versions of blaze-html, mtl.
+
+
+## pandoc 1.9.2 (2012-04-05)
+
+  * LaTeX reader:
+
+    + Made `lstlisting` work as a proper verbatim environment.
+    + Fixed bug parsing LaTeX tables with one column.
+
+  * LaTeX writer:
+
+    + Use `{}` around `ctable` caption, so that formatting can be used.
+    + Don't require eurosym package unless document has a €.
+
+  * LaTeX template: Added variables for `geometry`, `romanfont`,
+    `sansfont`, `mathfont`, `mainfont` so users can more easily
+    customize fonts.
+
+  * PDF writer:
+
+    + Run latex engine at least two times, to ensure
+      that PDFs will have hyperlinked bookmarks.
+    + Added PDF metadata (title,author) in LaTeX standalone + PDF output.
+
+  * Texinfo writer: retain directories in image paths.  (Peter Wang)
+
+  * RST writer:  Better handling of inline formatting, in accord
+    with docutils' "inline markup recognition rules" (though we don't
+    implement the unicode rules fully). Now `hi*there*hi` gets
+    rendered properly as `hi\ *there*\ hi`, and unnecessary
+    `\ ` are avoided around `:math:`, `:sub:`, `:sup:`.
+
+  * RST reader:
+
+    + Parse `\ ` as null, not escaped space.
+    + Allow `` :math:`...` `` even when not followed by blank
+      or `\`.  This does not implement the complex rule docutils follows,
+      but it should be good enough for most purposes.
+    + Add support for the rST default-role directive. (Greg Maslov)
+
+  * Text.Pandoc.Parsing: Added `stateRstDefaultRole` field to `ParserState`.
+    (Greg Maslov)
+
+  * Markdown reader: Properly handle citations nested in other inline
+    elements.
+
+  * Markdown writer:  don't replace empty alt in image with "image".
+
+  * DZSlides:  Updated template.html and styles in default template.
+    Removed bizarre CSS for `q` in dzslides template.
+
+  * Avoid repeated `id` attribute in section and header in HTML slides.
+
+  * README improvements:  new instructions on internal links,
+    removed misleading note on reST math.
+
+  * Build system:
+
+    + Fixed Windows installer so that dzslides works.
+    + Removed stripansi.sh.
+    + Added .travis.yml for Travis continuous integration support..
+    + Fixed upper bound for zlib (Sergei Trofimovich).
+    + Fixed upper bound for test-framework.
+    + Updated haddocks for haddock-2.10 (Sergei Trofimovich).
+
+
+## pandoc 1.9.1.2 (2012-03-09)
+
+  * Added `beamer+lhs` as output format.
+
+  * Don't escape `<` in `<style>` tags with `--self-contained`.
+    This fixes a bug which prevented highlighting from working
+    when using `--self-contained`.
+
+  * PDF: run latex engine three times if `--toc` specified.
+    This fixes page numbers in the table of contents.
+
+  * Docx writer: Added TableNormal style to tables.
+
+  * LaTeX math environment fixes. `aligned` is now used instead of
+    the nonexistent `aligned*`. `multline` instead of the nonexistent
+    `multiline`.
+
+  * LaTeX writer: Use `\textasciitilde` for literal `~`.
+
+  * HTML writer: Don't escape contents of EQ tags with --gladtex.
+    This fixes a regression from 1.8.
+
+  * Use `<q>` tags for Quoted items for HTML5 output.
+    The quote style can be changed by modifying the template
+    or including a css file. A default quote style is included.
+
+  * LaTeX reader: Fixed accents (\~{a}, `\c{c}`).
+    Correctly handle \^{}. Support "minted" as a LaTeX verbatim block.
+
+  * Updated LaTeX template for better language support.
+    Use `polyglossia` instead of `babel` with xetex.
+    Set `lang` as documentclass option.
+    `\setmainlanguage` will use the last of a comma-separated
+    list of languages. Thanks to François Gannaz.
+
+  * Fixed default LaTeX template so `\euro` and `€` work.  The
+    `eurosym` package is needed if you are using pdflatex.
+
+  * Fixed escaping of period in man writer (thanks to Michael Thompson).
+
+  * Fixed list label positions in beamer.
+
+  * Set `mainlang` variable in context writer.
+    This parallels behavior of latex writer.  `mainlang` is the last
+    of a comma-separated list of languages in lang.
+
+  * EPUB language metadat: convert e.g. `en_US` from locale to `en-US`.
+
+  * Changed `-V` so that you can specify a key without a value.
+    Such keys get the value `true`.
+
+  * Fixed permissions on installed man pages - thanks Magnus Therning.
+
+  * Windows installer: require XP or higher.  The installer is
+    now compiled on a Windows 7 machine, which fixes a problem
+    using citation functions on Windows 7.
+
+  * OSX package: Check for 64-bit Intel CPU before installing.
+
+
+## pandoc 1.9.1.1 (2012-02-11)
+
+  * Better handling of raw latex environments in markdown.  Now
+
+        \begin{equation}
+        a_1
+        \end{equation}
+
+    turns into a raw latex block as expected.
+
+  * Improvements to LaTeX reader:
+
+    + Skip options after block commands.
+    + Correctly handle `{\\}` in braced.
+    + Added a needed 'try'.
+    + Citations: add `, ` to suffix if it doesn't start with space or
+      punctuation. Otherwise we get no space between the year and the
+      suffix in author-date styles.
+
+  * Added two needed data files for S5.  This fixes a problem with
+    `pandoc -t s5 --self-contained`.  Also removed `slides.min.js`,
+    which was no longer being used.
+
+  * Fixed some minor problems in `reference.docx`:
+    name on "Date" style, `xCs` instead of `xIs`.
+
+  * Fixed a problem creating docx files using a reference docx
+    modified using Word.  The problem seems to be that Word
+    modifies `_rels/.rels`, changing the Type of the Relationship to
+    `docProps/core.xml`. Pandoc now changes this back to the correct
+    value if it has been altered, fixing the problem.
+
+  * Fixed html5 template so it works properly with highlighting.
+
+## pandoc 1.9.1 (2012-02-09)
+
+  * LaTeX reader:
+
+    + Fixed regression in 1.9; properly handle escaped $ in latex math.
+    + Put LaTeX verse environments in blockquotes.
+
+  * Markdown reader:
+
+    + Limit nesting of strong/emph.  This avoids exponential lookahead
+      in parasitic cases, like `a**a*a**a*a**a*a**a*a**a*a**a*a**a*a**`.
+    + Improved attributes syntax (in code blocks/spans): (1)
+      Attributes can contain line breaks. (2) Values in key-value
+      attributes can be surrounded by either double or single quotes, or
+      left unquoted if they contain no spaces.
+
+  * Headers no longer wrap in markdown or RST writers.
+
+  * Added `stateMaxNestingLevel` to `ParserState`.
+    We set this to 6, so you can still have `Emph` inside `Emph`,
+    just not indefinitely.
+
+  * More efficient implementation of `nowrap` in `Text.Pandoc.Pretty`.
+
+  * `Text.Pandoc.PDF`:  Only run latex twice if `\tableofcontents`
+    is present.
+
+  * Require highlighting-kate >= 0.5.0.2, texmath >= 0.6.0.2.
+
+## pandoc 1.9.0.5 (2012-02-06)
+
+  * Changed cabal file so that build-depends for the test program
+    are not required unless the tests flag is used.
+
+  * LaTeX writer:  insert `{}` between adjacent hyphens so they don't
+    form ligatures (dashes) in code spans.
+
+## pandoc 1.9.0.4 (2012-02-06)
+
+  * Raised version bound on test-framework to avoid problems
+    compiling tests on GHC 7.4.1.
+
+  * LaTeX reader: Use raw LaTeX as fallback inline text for Cites,
+    so citations don't just disappear unless you process with
+    citeproc.  Ignore `\bibliographystyle`, `\nocite`.
+
+  * Simplified tex2pdf; it will always run latex twice to
+    resolve table of contents and hyperrefs.
+
+## pandoc 1.9.0.3 (2012-02-06)
+
+  * Require Cabal >= 1.10.
+
+  * Tweaked cabal file to meet Cabal 1.10 requirements.
+
+## pandoc 1.9.0.2 (2012-02-05)
+
+  * Allow build with json 0.4 or 0.5.  Otherwise we can't build with
+    ghc 6.12.
+
+## pandoc 1.9 (2012-02-05)
+
+### New features
+
+  * Added a Microsoft Word `docx` writer. The writer includes support
+    for highlighted code and for math (which is converted from TeX to OMML,
+    Office's native math markup language, using texmath's new OMML module).
+    A new option `--reference-docx` allows the user to customize the
+    styles.
+
+  * Added an `asciidoc` writer (<http://www.methods.co.nz/asciidoc/>).
+
+  * Better support for slide shows:
+
+    + Added a `dzslides` writer. DZSlides is a lightweight HTML5/javascript
+      slide show format due to Paul Rouget (<http://paulrouget.com/dzslides/>).
+
+    + Added a LaTeX `beamer` writer. Beamer is a LaTeX package for creating
+      slide presentations.
+
+    + New, flexible rules for dividing documents into sections and slides
+      (see the "Structuring the slide show" in the User's Guide).  These
+      are backward-compatible with the old rules, but they allow slide
+      shows to be organized into sections and subsections containing
+      multiple slides.
+
+    + A new `--slide-level` option allows users to override defaults
+      and select a slide level below the first header level with content.
+
+  * A new `--self-contained` option produces HTML output that does not
+    depend on an internet connection or the presence of any external
+    files. Linked images, CSS, and javascript is downloaded (or fetched
+    locally) and encoded in `data:` URIs. This is useful for making portable
+    `HTML slide shows. The --offline` option has been deprecated and is now
+    `treated as a synonym or --self-contained`.
+
+  * Support for PDF output:
+
+    + Removed the old `markdown2pdf`.
+    + `pandoc` can now create PDFs (assuming you have latex and a set of
+      appropriate packages installed): just specify an output file with the
+      `.pdf` extension.
+    + A new option `--latex-engine` allows you to specify `pdflatex`,
+      `xelatex`, or `lualatex` as the processor.
+
+  * Highlighting changes:
+
+    + Syntax highlighting is now a standard feature; the `highlighting`
+      flag is no longer needed when compiling.
+    + A new `--no-highlight` option allows highlighting to be disabled.
+    + Highlighting now works in `docx`, `latex`, and `epub`, as well as
+      `html`, `html5`, `dzslides`, `s5`, and `slidy`.
+    + A new `--highlight-style` option selects between various highlighting
+      color themes.
+
+  * Internal links to sections now work in ConTeXt and LaTeX as well as HTML.
+
+  * LaTeX `\include` and `\usepackage` commands are now processed,
+    provided the files are in the working directory.
+
+  * EPUB improvements:
+
+    + Internal and external links now work in EPUB.
+    + Raw HTML is allowed.
+    + New `--epub-embed-font` option.
+    + Customizable templates for EPUB pages offer more control over
+      formatting: `epub-page.html`, `epub-coverimage.html`,
+      `epub-titlepage.html`.
+
+  * `--mathml` now works with DocBook.
+
+  * Added support for math in RST reader and writer.  Inline math uses the
+    `` :math:`...` `` construct.  Display math uses
+
+        .. math:: ...
+
+    or if the math is multiline,
+
+        .. math::
+
+           ...
+
+    These constructions are now supported now by `rst2latex.py`.
+
+  * Github syntax for fenced code blocks is supported in pandoc's
+    markdown.  You can now write
+
+        ```ruby
+        x = 2
+        ```
+
+    instead of
+
+        ~~~ {.ruby}
+        x = 2
+        ~~~~
+
+  * Easier scripting:  a new `toJsonFilter` function makes it easier to
+    write Haskell scripts to manipulate the Pandoc AST.
+    See [Scripting with pandoc](scripting.html#pandoc-1.9-changes).
+
+### Behavior changes
+
+  * Fixed parsing of consecutive lists in markdown.
+    Pandoc previously behaved like Markdown.pl for consecutive
+    lists of different styles. Thus, the following would be parsed
+    as a single ordered list, rather than an ordered list followed
+    by an unordered list:
+
+        1. one
+        2. two
+
+        - one
+        - two
+
+    This change makes pandoc behave more sensibly, parsing this as
+    two lists.  Any change in list type (ordered/unordered) or in
+    list number style will trigger a new list. Thus, the following
+    will also be parsed as two lists:
+
+        1. one
+        2. two
+
+        a. one
+        b. two
+
+    Since we regard this as a bug in Markdown.pl, and not something
+    anyone would ever rely on, we do not preserve the old behavior
+    even when `--strict` is selected.
+
+  * Dashes work differently with `--smart`: `---` is always em-dash,
+    and `--` is always en-dash.  Pandoc no longer tries to guess when
+    `-` should be en-dash.  *Note:* This may change how existing documents
+    look when processed with pandoc. A new option, `--old-dashes`,
+    is provided for legacy documents.
+
+  * The markdown writer now uses setext headers for levels 1-2.
+    The old behavior (ATX headers for all levels) can be restored
+    using the new `--atx-headers` option.
+
+  * Links are now allowed in markdown image captions.  They are also
+    allowed in links, but will appear there as regular text. So,
+
+        [link with [link](/url)](/url)
+
+    will turn into
+
+        <p><a href="/url">link with link</a></p>
+
+  * Improved handling of citations using `citeproc-hs-0.3.4`.
+    Added `--citation-abbreviations` option.
+
+  * Citation keys can no longer end with a punctuation character.
+    This means that `@item1.` will be parsed as a citation with key
+    'item1', followed by a period, instead of a citation with key
+    'item1.', as was the case previously.
+
+  * In HTML output, citations are now put in a span with class `citation`.
+
+  * The markdown reader now recognizes DocBook block and inline tags.
+    It was always possible to include raw DocBook tags in a markdown
+    document, but now pandoc will be able to distinguish block from
+    inline tags and behave accordingly. Thus, for example,
+
+        <sidebar>
+        hello
+        </sidebar>
+
+    will not be wrapped in `<para>` tags.
+
+  * The LaTeX parser has been completely rewritten; it is now much more
+    accurate, robust, and extensible. However, there are two important
+    changes in how it treats unknown LaTeX. (1) Previously, unknown
+    environments became BlockQuote elements; now, they are treated
+    as "transparent", so `\begin{unknown}xyz\end{unknown}` is the
+    same as `xyz`.  (2) Previously, arguments of unknown commands
+    were passed through with their braces; now the braces are stripped
+    off.
+
+  * `--smart` is no longer selected automatically with `man` output.
+
+  * The deprecated `--xetex` option has been removed.
+
+  * The `--html5`/`-5` option has been deprecated. Use `-t html5`
+    instead. `html5` and `html5+lhs` are now separate output formats.
+
+  * Single quotes are no longer escaped in HTML output.  They do not
+    need to be escaped outside of attributes.
+
+  * Pandoc will no longer transform leading newlines in code
+    blocks to `<br/>` tags.
+
+  * The ODT writer now sizes images appropriately, using the image
+    size and DPI information embedded in the image.
+
+  * `--standalone` is once again implicitly for a non-text output format
+    (ODT, EPUB).  You can again do `pandoc test.txt -o test.odt`
+    and get a standalone ODT file.
+
+  * The Docbook writer now uses `<sect1>`, `<sect2>`, etc. instead of
+    `<section>`.
+
+  * The HTML writer now uses `<del>` for strikeout.
+
+  * In HTML output with `--section-divs`, the classes `section` and
+    `level[1,2,..6]` are put on the `div` tags so they can be styled.
+    In HTML 5 output with `--section-divs`, the classes
+    `level[1,2,...6]` are put on `section` tags.
+
+  * EPUB writer changes:
+
+    + The `lang` variable now sets the language
+      in the metadata (if it is not set, we default to the locale).
+    + EPUB:  UTF-8 is used rather than decimal entities.
+
+  * Added `titleslide` class to title slide in S5 template.
+
+  * In HTML, EPUB, and docx metadata, the date is normalized into
+    YYYY-MM-DD format if possible. (This is required for validation.)
+
+  * Attributes in highlighted code blocks are now preserved in HTML.
+    The container element will have the classes, id, and key-value attributes
+    you specified in the delimited code block. Previously these were stripped
+    off.
+
+  * The reference backlink in the HTML writer no longer has a special
+    `footnoteBacklink` class.
+
+  * The HTML template has been split into `html` and `html5` templates.
+
+  * Author and date are treated more consistently in HTML templates.
+    Authors are now `<h2>`, date `<h3>`.
+
+  * URLs are hyphenated in the ConTeXt writer (B. Scott Michel).
+
+  * In `Text.Pandoc.Builder`, `+++` has been replaced by `<>`.
+
+### Bug fixes
+
+  * Better support for combining characters and East Asian wide characters
+    in markdown and reST.
+
+  * Better handling of single quotes with `--smart`.
+    Previously `D'oh l'*aide*` would be parsed with left and right single
+    quotes instead of apostrophes. This kind of error is now fixed.
+
+  * Highlighting: Use `reads` instead of `read` for better error handling.
+    Fixes crash on `startNum="abc"`.
+
+  * Added blank comment after directives in rst template.
+
+  * Unescape entities in citation `refId`. The `refId`s coming
+    from citeproc contain XML numeric entities, and these don't match with the
+    citation keys parsed by pandoc. Solution is to unescape them.
+
+  * HTML reader: Fixed bug parsing tables with both thead and tbody.
+
+  * Markdown reader:
+
+    + Better handling of escapes in link URLs and titles.
+    + Fixed backslash escapes in reference links.
+    + Fixed bug in table/hrule parsing, by checking that the top
+      line of a table is not followed by a blank line. This bug caused
+      slowdowns on some files with hrules and tables, as pandoc tried to
+      interpret the hrules as the tops of multiline tables.
+    + Fixed bug in code block attribute parser. Previously the ID attribute
+      got lost if it didn't come first. Now attributes can come in any order.
+
+  * RST reader: allow footnotes followed by newline without space characters.
+
+  * LaTeX reader:
+
+    + Ignore empty groups {}, { }.
+    + LaTeX reader: Handle `\@`.
+    + LaTeX reader:  Don't crash on commands like `\itemsep`.
+    + LaTeX reader:  Better handling of letter environments.
+
+  * RST writer: Fixed bug involving empty table cells. isSimple was being
+    calculated in a way that assumed there were no non-empty cells.
+
+  * ConTeXt writer:
+
+    + Made `--toc` work even without `--number-sections`.
+    + Escape # in link URLs.
+    + Use buffering for footnotes containing code blocks.
+    + Changed 'descr' to 'description', fixed alignment.
+
+  * LaTeX writer:
+
+    + Escape euro character.
+    + Don't escape `~` inside `\href{...}`.
+    + Escape `#` in href URLs.
+    + Improved detection of book classes.  We now check the
+      `documentclass` variable, and if that is not set, we look through
+      the template itself.  Also, we have added the KOMA classes scrreprt
+      and scrbook.  You can now make a book using
+      `pandoc -V documentclass:book mybook.txt -o mybook.pdf`
+    + LHS files now set the "listings" variable, so that the definition
+      of the `code` environment will be included in the template.
+    + Links are colored blue by default (this can be changed by
+      modifying `hyperref` settings in the template).
+    + Added `lang` variable to LaTeX template.
+
+  * HTML writer:
+
+    + Fixed bug in HTML template with html5 and mathml.
+    + Don't use self-closing img, br, hr tags for HTML5.
+    + Use `<section>` for footnotes if HTML5.
+    + Update HTML templates to use Content-Style-Type meta tag.
+    + Use separate variables for meta-date, meta-author.
+      This makes footnotes work in author and date fields.
+    + Use 'vertical-align:middle' in WebTeX math for better alignment.
+
+  * S5/slidy writer:  Make footnotes appear on separate slide at end.
+
+  * MIME: Added 'layout-cache' to getMimeType. This ensures that the
+    META-INF/manifest.xml for ODT files will have everything it needs, so
+    that ODT files modified by LibreOffice can be used as `--reference-odt`.
+
+  * `Text.Pandoc.Templates`: Return empty string for json template.
+
+  * `Text.Pandoc.Biblio`:
+
+    + Expand citations recursively inside nested inlines.
+    + Treat `\160` as space when parsing locator and suffix.
+      This fixes a bug with "p. 33" when `--smart` is used. Previously
+      the whole "p. 33" would be included in the suffix, with no locator.
+    + Put whole author-in-text citation in a Cite.  Previously just the
+      date and other info went in the Cite.
+    + Don't add comma+space to prefix if it ends in punctuation.
+
+  * Updated chicago-author-date.csl.  The old version did not work
+    properly for edited volumes with no author.
+
+  * EPUB writer:
+
+    + Add date to EPUB titlepage and metadata.
+    + Added TOC identifier in EPUB page template.
+    + Don't generate superfluous file `cover-image.jpg`.
+
+###  Under the hood improvements
+
+  * Modified `make_osx_package.sh` to use cabal-dev.
+    Items are no longer installed as root.
+    Man pages are zipped and given proper permissions.
+
+  * Modified windows installer generator to use cabal-dev.
+
+  * Setup: Making man pages now works with cabal-dev (at least on OSX). In
+    Setup.hs we now invoke 'runghc' in a way that points it to the correct
+    package databases, instead of always falling back to the default user
+    package db.
+
+  * Updated to work with GHC 7.4.1.
+
+  * Removed dependency on old-time.
+
+  * Removed dependency on dlist.
+
+  * New slidy directory for "self-contained."
+
+  * TeXMath writer:  Use unicode thin spaces for thin spaces.
+
+  * Markdown citations: don't strip off initial space in locator.
+
+### API changes
+
+  * Removed `Apostrophe`, `EmDash`, `EnDash`, and `Ellipses`
+    from the native `Inline` type in pandoc-types.  Now we use `Str`
+    elements with unicode.
+
+  * Improvements to `Text.Pandoc.Builder`:
+
+    + `Inlines` and `Blocks` are now newtypes (not synonyms for
+      sequences).
+    + Instances are defined for `IsString`, `Show`, `Read`, `Monoid`,
+      and a new `Listable` class, which allows these to be manipulated
+      to some extent like lists. Monoid append includes automatic
+      normalization.
+    + `+++` has been replaced by `<>` (mappend).
+
+  * Use blaze-html instead of xhtml for HTML generation.
+    This changes the type of `writeHtml`.
+
+  * `Text.Pandoc.Shared`:
+
+    + Added `warn` and `err`.
+    + Removed `unescapeURI`, modified `escapeURI`.
+      (See under [behavior changes], above.)
+
+  * Changes in URI escaping:  Previously the readers escaped URIs by
+    converting unicode characters to octets and then percent encoding.
+    Now unicode characters are left as they are, and `escapeURI` only
+    percent-encodes space characters.  This gives more readable
+    URIs, and works well with modern user agents. URIs are no longer unescaped
+    at all on conversion to `markdown`, `asciidoc`, `rst`, `org`.
+
+  * New module `Text.Pandoc.SelfContained`.
+
+  * New module `Text.Pandoc.Docx`.
+
+  * New module `Text.Pandoc.PDF`.
+
+  * Added `writerBeamer` to `WriterOptions`.
+
+  * Added `normalizeDate` to `Text.Pandoc.Shared`.
+
+  * Added `splitStringWithIndices` in `Text.Pandoc.Shared`.
+    This is like `splitWithIndices`, but it is sensitive to distinctions
+    between wide, combining, and regular characters.
+
+  * `Text.Pandoc.Pretty`:
+
+    + Added `chomp` combinator.
+    + Added `beforeNonBreak` combinator.  This allows you to include
+      something conditionally on it being before a nonblank.
+      Used for RST inline math.
+    + Added `charWidth` function. All characters marked W or F in the unicode
+      spec EastAsianWidth.txt get width 2.
+    + Added `realLength`, based on `charWidth`. `realLength` is now
+      used in calculating offsets.
+
+  * New module `Text.Pandoc.Slides`, for common functions for breaking
+    a document into slides.
+
+  * Removed `Text.Pandoc.S5`, which is no longer needed.
+
+  * Removed `Text.Pandoc.CharacterReferences`.  Moved
+    `characterReference` to `Text.Pandoc.Parsing`.
+    `decodeCharacterReferences` is replaced by `fromEntities`
+    in `Text.Pandoc.XML`.
+
+  * Added `Text.Pandoc.ImageSize`.  This is intened for use
+    in `docx` and `odt` writers, so the size and dpi of images
+    can be calculated.
+
+  * Removed `writerAscii` in `WriterOptions`.
+
+  * Added `writerHighlight` to `WriterOptions`.
+
+  * Added `DZSlides` to `HTMLSlideVariant`.
+
+  * `writeEPUB` has a new argument for font files to embed.
+
+  * Added `stateLastStrPos` to `ParserState`. This lets us keep track
+    of whether we're parsing the position immediately after a regular
+    (non-space, non-symbol) string, which is useful for distinguishing
+    apostrophes from single quote starts.
+
+  * `Text.Pandoc.Parsing`:
+
+    + `escaped` now returns a `Char`.
+    + Removed `charsInBalanced'`, added a character parser as
+      a parameter of `charsInBalanced`.  This is needed for
+      proper handling of escapes, etc.
+    + Added `withRaw`.
+
+  * Added `toEntities` to `Text.Pandoc.XML`.
+
+  * `Text.Pandoc.Readers.LaTeX`:
+
+    + Export `handleIncludes`.
+    + Export `rawLaTeXBlock` instead of `rawLaTeXEnvironment'`.
+
+  * Added `ToJsonFilter` class and `toJsonFilter` function to
+    `Text.Pandoc`, deprecating the old `jsonFilter` function.
+
+  * `Text.Pandoc.Highlighting`:
+
+     + Removed `highlightHtml`, `defaultHighlightingCss`.
+     + Export `formatLaTeXInline`, `formatLaTeXBlock`, and `highlight`, plus
+       key functions from highlighting-kate.
+     + Changed types of highlighting function.  `highlight` returns a
+       `Maybe`, not an `Either`.
+
+
+## pandoc 1.8.2.1 (2011-08-01)
+
+  * Adjusted Arbitrary instance to help avoid timeouts in tests.
+
+  * Added `Tests.Writers.Markdown` to cabal file.
+
+  * Relaxed version bounds on pandoc-types, test-framework.
+
+## pandoc 1.8.2 (2011-07-30)
+
+  * Added script to produce OS X package.
+
+  * Made `templates` directory a git submodule.  This should make it
+    easier for people to revise their custom templates when the default
+    templates change.
+
+  * Changed template naming scheme: `FORMAT.template` -> `default.FORMAT`.
+    **Note:** If you have existing templates in `~/.pandoc/templates`, you
+    must rename them to conform to the new scheme!
+
+  * Default template improvements:
+
+    + HTML:  Display author and date after title.
+    + HTML:  Made table of contents more customizable.  The container
+      for the TOC is now in the template, so users can insert a header
+      or other styling. (Thanks to Bruce D'Arcus for the suggestion.)
+    + HTML, Slidy, S5:  Enclose scripts in CDATA tags.
+    + Slidy, S5: Added `s5-url` and `slidy-url` variables, instead of
+      hard-coding.  If you want to put your slidy files in the slidy
+      subdirectory, for example, you can do
+      `pandoc -t slidy -V slidy-url=slidy -s`.
+    + LaTeX: Use `\and` to separate authors in LaTeX documents (reader
+      & writer).  Closes #279.
+    + LaTeX: Set `\emergencystretch` to prevent overfull lines.
+    + LaTeX: Use different `hyperref` options for `xetex`, fixing
+      problems with unicode bookmarks (thanks to CircleCode).
+    + LaTeX: Removed `ucs` package, use `utf8` rather than `utf8x`
+      with `inputenc`.  This covers fewer characters but is more
+      robust with other packages, and `ucs` is unmaintained.  Users
+      who need better unicode support should use xelatex or lualatex.
+
+  * If a template specified with `--template` is not found, look for it
+    in `datadir`.  Also, if no extension is provided, supply one based
+    on the writer.  So now you can put your `special.latex` template in
+    `~/.pandoc/templates`, and use it from any directory via
+    `pandoc -t latex --template special`.
+
+  * Added `nonspaceChar` to `Text.Pandoc.Parsing`.
+
+  * Fixed smart quotes bug, now handling `'...hi'` properly.
+
+  * RST reader:
+
+    + Partial support for labeled footnotes.
+    + Improved accuracy of `simpleReferenceName` parser.
+
+  * HTML reader:
+
+    + Substitute correct unicode characters for
+      characters in the 128..159 range, which are often found even in
+      HTML that purports to be UTF-8.
+
+  * LaTeX reader:  Handle `\subtitle` command (a subtitle is added
+    to the title, after a colon and linebreak). Closes #280.
+
+  * Leaner `reference.odt`.
+
+  * Added unexported module `Text.Pandoc.MIME` for use in
+    the ODT writer.
+
+  * ODT writer:  Construct `manifest.xml` based on archive contents.
+    This fixes a bug in ODTs containing images. Recent versions of
+    LibreOffice would reject these as corrupt, because `manifest.xml`
+    did not contain a reference to the image files.
+
+  * LaTeX writer:
+
+    + Make verbatim environments flush to avoid spurious
+      blank lines.  Closes #277.
+    + Use `\texttt` and escapes insntead of `\verb!...!`, which
+      is too fragile (doesn't work in command arguments).
+    + Use `\enquote{}` for quotes if the template includes
+      the `csquotes` package. This provides better support for
+      local quoting styles. (Thanks to Andreas Wagner for the idea.)
+
+  * ConTeXt writer:  Make `\starttyping`/`\stoptyping` flush with
+    margin, preventing spurious blank lines.
+
+  * Slidy writer:
+
+    + Use non-minimized version of `slidy.css` with `--offline`
+      option, so users can more easily edit it.
+    + Also fixed a bug in the CSS that prevented proper centering
+      of title (now reported and fixed upstream).
+
+  * S5 writer:
+
+    + Replaced `s5/default/slides.js.{comment,packed}` with
+      new compressed `s5/default/slides.min.js`.
+    + Use `data:` protocol to embed S5 CSS in `<link>` tags,
+      when `--offline` is specified. Using inline CSS didn't
+      work with Chrome or Safari.  This fixes offline
+      S5 on those browsers.
+
+  * HTML writer:  Removed English title on footnote backlinks.
+    This is incongrous in non-English documents.
+
+  * Docbook writer:
+
+    + Use CALS tables.  (Some older docbook software does not work
+      well with XHTML tables.)  Closes #77.
+    + Use `programlisting` tags (instead of `screen`) for code blocks.
+
+  * `markdown2pdf`:
+
+    + Calls latex with `-halt-on-error -interaction nonstopmode` instead
+      of `-interaction=batchmode`, which essentially just ignored errors,
+      leading to bad results. Better to know when something is wrong.
+    + Fixed issues with non-UTF-8 output of `pdflatex`.
+    + Better error reporting.
+
+  * `--mathjax` now takes an optional URL argument. If it is not
+    provided, pandoc links directly to the (secure) mathjax CDN,
+    as now recommended (thanks to dsanson).
+
+  * Deprecated `--xetex` option in `pandoc`.  It is no longer needed,
+    since the LaTeX writer now produces a file that can be processed by
+    `latex`, `pdflatex`, `lualatex`, or `xelatex`.
+
+  * Introduced `--luatex` option to `markdown2pdf`. This causes `lualatex`
+    to be used to create the PDF.
+
+
+## pandoc 1.8.1.2 (2011-07-16)
+
+  * Added `--epub-cover-image` option.
+
+  * Documented `--biblatex` and `--natbib` options.
+
+  * Allow `--section-divs` with slidy output.  Resolves Issue #296.
+
+  * Disallow notes within notes in reST and markdown.
+    These previously caused infinite looping and stack overflows.
+    For example:
+
+        [^1]
+
+        [^1]: See [^1]
+
+    Note references are allowed in reST notes, so this isn't a full
+    implementation of reST. That can come later. For now we need to
+    prevent the stack overflows.  Partially resolves Issue #297.
+
+  * EPUB writer: Allow non-plain math methods.
+
+  * Forbid ()s in citation item keys.  Resolves Issue #304: problems with
+    `(@item1; @item2)` because the final paren was being parsed as part of
+    the item key.
+
+  * Changed URI parser so it doesn't include trailing punctuation.
+    So, in RST, `http://google.com.` should be parsed as a link followed by a
+    period. The parser is smart enough to recognize balanced parentheses, as
+    often occur in wikipedia links: `http://foo.bar/baz_(bam)`.
+
+  * Markdown+lhs reader: Require space after inverse bird tracks, so that
+    HTML tags can be used freely at the left margin of a markdown+lhs document.
+    Thanks to Conal Elliot for the suggestion.
+
+  * Markdown reader: Fixed bug in footnote order (reported by CircleCode).
+
+  * RST reader:
+      + Fixed bug in in field lists with multi-line items at the
+        end of the list.
+      + Added parentheses to RST `specialChars`, so
+        `(http://google.com)` will be parsed as a link in parens.
+        Resolves Issue #291.
+      + Allow `|` followed by newline in RST line block.
+
+  * LaTeX reader:
+      + Support `\dots`.
+      + Gobble option & space after linebreak `\\[10pt]`.
+
+  * Textile reader:
+      + Make it possible to have colons after links.  (qerub)
+      + Make it possible to have colons after links.  (Christoffer Sawicki)
+
+  * HTML reader:
+      + Skip spaces after `<b>`, `<emph>`, etc.
+      + Handle tbody, thead in simple tables.  Closes #274.
+      + Implicit `Para`s instead of `Plains` in some contexts.
+
+  * OpenDocument writer:  Use special `First paragraph` style for
+    first paragraph after most non-paragraph blocks. This allows users to
+    specify e.g. that only paragraphs after the first paragraph of a block are
+    to be indented. Thanks to Andrea Rossato for the patch. Closes #20.
+
+  * LaTeX writer:  use `deVerb` on table and picture captions.
+    Otherwise LaTeX complains about `\verb` inside command argument.
+    Thanks to bbanier for reporting the bug.
+
+  * Markdown writer: Insert HTML comment btw list and indented code block.
+    This prevents the code block from being interpreted as part of the list.
+
+  * EPUB writer: Add a meta element specify the cover.
+    Some EPUB e-readers, such as the Nook, require a meta element inside the
+    OPF metadata block to ensure the cover image is properly displayed.
+    (Kelsey Hightower)
+
+  * HTML writer: Use embed tag for images with non-image extensions.
+    (e.g.  PDFs).  Closes #264.
+
+  * LaTeX writer: Improved tables.
+
+      + More space between lines, top-align cells.
+      + Use ctable package, which allows footnotes and
+        provides additional options.
+      + Made cell alignments work in multiline tables.
+      + Closes #271, #272.
+
+  * Un-URI-escape image filenames in LaTeX, ConTeXt, RTF, Texinfo.
+    Also do this when copying image files into EPUBs and ODTs.
+    Closes #263.
+
+  * Changed to github issue tracker.
+
+  * Added failing emph/strong markdown test case due to Perry Wagle.
+
+  * Slidy improvements:
+      + Updated to use Slidy2.
+      + Fixed bug, unclosed div tag.
+      + Added `duration` variable in template.
+        Setting this activates the timer.
+      + Use 'titlepage' instead of 'cover' for title div.
+
+
+## pandoc 1.8.1.1 (2011-02-13)
+
+  * `markdown2pdf`:  Removed some debugging lines accidentally included
+    in the 1.8.1 release. With those lines, the temp directory is created
+    in the working directory, and it is not deleted.  This fix restores
+    the original behavior.
+
+## pandoc 1.8.1 (2011-02-13)
+
+  * Added `--ascii` option.  Currently supported only in HTML writer,
+    which it causes to use numerical entities instead of UTF-8.
+
+  * EPUB writer: `--toc` now works to provide a table of contents
+    at the beginning of each chapter.
+
+  * LaTeX writer:  Change figure defaults to `htbp`.
+    This prevents "too many unprocessed floats."  Resolves
+    Issue #285.
+
+  * `Text.Pandoc.UTF8`:  Encode filenames even when using recent
+    base.
+
+  * `markdown2pdf`: Fixed filename encoding issues. With help from Paulo
+    Tanimoto. Resolves Issue #286.
+
+  * HTML writer: Put line breaks in section divs.
+
+  * `Text.Pandoc.Shared`: Make `writerSectionDivs` default to False.
+
+## pandoc 1.8.0.3 (2011-02-05)
+
+  * Fixed Source-repository stanza in cabal file.
+
+## pandoc 1.8.0.2 (2011-02-05)
+
+  * HTML writer:
+
+    + Stringify alt text instead of converting to HTML.
+    + Break lines after block elements, not inside tags.
+      HTML output now closely resembles that of tidy. Resolves Issue #134.
+
+  * Markdown reader: Fixed bug in footnote block parser (pointed out
+    by Jesse Rosenthal).  The problem arose when the blank line
+    at the end of a footnote block contained indenting spaces.
+
+  * Shared: Improved 'normalize' function so it normalizes Spaces too.
+    In normal form, Space elements only occur to separate two non-Space
+    elements.  So, we never have [Space], or [, ..., Space].
+
+  * Tests:
+
+    + Improved Arbitrary instance.
+    + Added timeout for test instances.
+
+  * README:
+
+    + Added section on four-space rule for lists.  Resolves Issue #283.
+    + Clarified optional arguments on math options.
+
+  * markdown2pdf: Fixed bug with output file extensions.
+    Previously `markdown2pdf test.txt -o test.en.pdf` would produce
+    `test.pdf`, not `test.en.pdf`.  Thanks to Paolo Tanimoto for the fix.
+
+## pandoc 1.8.0.1 (2011-01-31)
+
+  * Revised Interact.hs so that it works with the CPP macros
+    in the UTF8 module.
+
+  * Revised Setup.hs so that we don't call MakeManPage.hs unless
+    the man pages are out of date.
+
+## pandoc  1.8 (2011-01-30)
+
+### New features
+
+  * Support for citations using Andrea Rossato's `citeproc-hs` 0.3.
+    You can now write, for example,
+
+        Water is wet [see @doe99, pp. 33-35; also @smith04, ch. 1].
+
+    and, when you process your document using `pandoc`, specifying
+    a citation style using `--csl` and a bibliography using `--bibliography`,
+    the citation will be replaced by an appropriately formatted
+    citation, and a list of works cited will be added to the end
+    of the document.
+
+    This means that you can switch effortlessly between different citation
+    and bibliography styles, including footnote, numerical, and author-date
+    formats. The bibliography can be in any of the following formats: MODS,
+    BibTeX, BibLaTeX, RIS, EndNote, EndNote XML, ISI, MEDLINE, Copac, or JSON.
+    See the README for further details.
+
+    Citations are supported in the markdown reader, using a special
+    syntax, and in the LaTeX reader, using natbib or biblatex syntax.
+    (Thanks to Nathan Gass for the natbib and biblatex support.)
+
+  * New `textile` reader and writer.  Thanks to Paul Rivier for contributing
+    the `textile` reader, an almost complete implementation of the textile
+    syntax used by the ruby [RedCloth library](http://redcloth.org/textile).
+    Resolves Issue #51.
+
+  * New `org` writer, for Emacs Org-mode, contributed by Puneeth Chaganti.
+
+  * New `json` reader and writer, for reading and writing a JSON
+    representation of the native Pandoc AST.  These are much faster
+    than the `native` reader and writer, and should be used for
+    serializing Pandoc to text.  To convert between the JSON representation
+    and native Pandoc, use `encodeJSON` and `decodeJSON` from
+    `Text.JSON.Generic`.
+
+  * A new `jsonFilter` function in `Text.Pandoc` makes it easy
+    to write scripts that transform a JSON-encoded pandoc document.
+    For example:
+
+        -- removelinks.hs - removes links from document
+        import Text.Pandoc
+        main = interact $ jsonFilter $ bottomUp removeLink
+                 where removeLink (Link xs _) = Emph xs
+                       removeLink x = x
+
+    To use this to remove links while translating markdown to LaTeX:
+
+        pandoc -t json | runghc removelinks.hs | pandoc -f json -t latex
+
+  * Attributes are now allowed in inline `Code` elements, for example:
+
+        In this code, `ulist ! [theclass "special"] << elts`{.haskell} is...
+
+    The attribute syntax is the same as for delimited code blocks.
+    `Code` inline has an extra argument place for attributes, just like
+    `CodeBlock`. Inline code will be highlighted in HTML output, if pandoc
+    is compiled with highlighting support. Resolves Issue #119.
+
+  * New `RawBlock` and `RawInline` elements (replacing `RawHtml`,
+    `HtmlInline`, and `TeX`) provide lots of flexibility in writing
+    scripts to transform Pandoc documents. Scripts can now change
+    how each element is rendered in each output format.
+
+  * You can now define LaTeX macros in markdown documents, and pandoc
+    will apply them to TeX math.  For example,
+
+        \newcommand{\plus}[2]{#1 + #2}
+        $\plus{3}{4}$
+
+    yields `3+4`.  Since the macros are applied in the reader, they
+    will work in every output format, not just LaTeX.
+
+  * LaTeX macros can also be used in LaTeX documents (both in math
+    and in non-math contexts).
+
+  * A new `--mathjax` option has been added for displaying
+    math in HTML using MathJax.  Resolves issue #259.
+
+  * Footnotes are now supported in the RST reader. (Note, however,
+    that unlike docutils, pandoc ignores the numeral or symbol used in
+    the note; footnotes are put in an auto-numbered ordered list.)
+    Resolves Issue #258.
+
+  * A new `--normalize` option causes pandoc to normalize the AST
+    before writing the document.  This means that, for example,
+    `*hi**there*` will be rendered as `<em>hithere</em>`
+    instead of `<em>hi</em><em>there</em>`.  This is not the default,
+    because there is a significant performance penalty.
+
+  * A new `--chapters` command-line option causes headers
+    in DocBook, LaTeX, and ConTeXt to start with "chapter" (level one).
+    Resolves Issue #265.
+
+  * In DocBook output, `<chapter>` is now used for top-level
+    headers if the template contains `<book>`. Resolves Issue #265.
+
+  * A new `--listings` option in `pandoc` and `markdown2pdf` causes
+    the LaTeX writer to use the listings package for code blocks.
+    (Thanks to Josef Svennigsson for the pandoc patch, and Etienne
+    Millon for the markdown2pdf patch.)
+
+  * `markdown2pdf` now supports `--data-dir`.
+
+  * URLs in autolinks now have class "url" so they can be styled.
+
+  * Improved prettyprinting in most formats.  Lines will be wrapped
+    more evenly and duplicate blank lines avoided.
+
+  * New `--columns` command-line option sets the column width for
+    line wrapping and relative width calculations for tables.
+
+  * Made `--smart` work in HTML, RST, and Textile readers, as well
+    as markdown.
+
+  * Added `--html5` option for HTML5 output.
+
+  * Added support for listings package in LaTeX reader
+    (Puneeth Chaganti).
+
+  * Added support for simple tables in the LaTeX reader.
+
+  * Added support for simple tables in the HTML reader.
+
+  * Significant performance improvements in many readers and writers.
+
+### API and program changes
+
+  * Moved `Text.Pandoc.Definition` from the `pandoc` package to a new
+    auxiliary package, `pandoc-types`. This will make it possible for other
+    programs to supply output in Pandoc format, without depending on the whole
+    pandoc package.
+
+  * Added `Attr` field to `Code`.
+
+  * Removed `RawHtml`, `HtmlInline`, and `TeX` elements; added generic
+    `RawBlock` and `RawInline`.
+
+  * Moved generic functions to `Text.Pandoc.Generic`. Deprecated
+    `processWith`, replacing it with two functions, `bottomUp` and `topDown`.
+    Removed previously deprecated functions `processPandoc` and `queryPandoc`.
+
+  * Added `Text.Pandoc.Builder`, for building `Pandoc` structures.
+
+  * `Text.Pandoc` now exports association lists `readers` and `writers`.
+
+  * Added `Text.Pandoc.Readers.Native`, which exports `readNative`.
+    `readNative` can now read full pandoc documents, block lists, blocks,
+    inline lists, or inlines.  It will interpret `Str "hi"`
+    as if it were `Pandoc (Meta [] [] []) [Plain [Str "hi"]]`.
+    This should make testing easier.
+
+  * Removed deprecated `-C/--custom-header` option.
+    Use `--template` instead.
+
+  * `--biblio-file` has been replaced by `--bibliography`.
+    `--biblio-format` has been removed; pandoc now guesses the format
+    from the file extension (see README).
+
+  * pandoc will treat an argument as a URI only if it has an
+    `http(s)` scheme.  Previously pandoc would treat some
+    Windows pathnames beginning with `C:/` as URIs.
+
+  * The `--sanitize-html` option and the `stateSanitize` field in
+    `ParserState` have been removed. Sanitization is better done in the
+    resulting HTML using `xss-sanitize`, which is based on pandoc's
+    sanitization, but improved.
+
+  * pandoc now adds a newline to the end of its output in fragment
+    mode (= not `--standalone`).
+
+  * Added support for `lang` in `html` tag in the HTML template,
+    so you can do `pandoc -s -V lang=es`, for example.
+
+  * `highlightHtml` in `Text.Pandoc.Highlighting` now takes
+    a boolean argument that selects between "inline" and
+    "block" HTML.
+
+  * `Text.Pandoc.Writers.RTF` now exports `rtfEmbedImage`.
+    Images are embedded in RTF output when possible (png, jpeg).
+    Resolves Issue #275.
+
+  * Added `Text.Pandoc.Pretty`. This is better suited for pandoc than the
+    `pretty` package.  Changed all writers that used
+    `Text.PrettyPrint.HughesPJ` to use `Text.Pandoc.Pretty` instead.
+
+  * Rewrote `writeNative` using the new prettyprinting module. It is
+    now much faster. The output has been made more consistent and compressed.
+    `writeNative` is also now sensitive to writerStandalone`, and will simply
+    `print a block list if writerStandalone` is False.
+
+  * Removed `Text.Pandoc.Blocks`. `Text.Pandoc.Pretty` allows you to define
+    blocks and concatenate them, so a separate module is no longer needed.
+
+  * `Text.Pandoc.Shared`:
+
+    + Added `writerColumns`, `writerChapters`, and `writerHtml5` to
+      `WriterOptions`.
+    + Added `normalize`.
+    + Removed unneeded prettyprinting functions:
+      `wrapped`, `wrapIfNeeded`, `wrappedTeX`, `wrapTeXIfNeeded`, `hang'`,
+      `BlockWrapper`, `wrappedBlocksToDoc`.
+    + Made `splitBy` take a test instead of an element.
+    + Added `findDataFile`, refactored `readDataFile`.
+    + Added `stringify`. Rewrote `inlineListToIdentifier` using `stringify`.
+    + Fixed `inlineListToIdentifier` to treat `\160` as ' '.
+
+  * `Text.Pandoc.Readers.HTML`:
+
+    + Removed `rawHtmlBlock`, `anyHtmlBlockTag`, `anyHtmlInlineTag`,
+      `anyHtmlTag`, `anyHtmlEndTag`, `htmlEndTag`, `extractTagType`,
+      `htmlBlockElement`, `htmlComment`
+    + Added `htmlTag`, `htmlInBalanced`, `isInlineTag`, `isBlockTag`,
+      `isTextTag`
+
+  * Moved `smartPunctuation` from `Text.Pandoc.Readers.Markdown`
+    to `Text.Pandoc.Readers.Parsing`, and parameterized it with
+    an inline parser.
+
+  * Ellipses are no longer allowed to contain spaces.
+    Previously we allowed '. . .', ' . . . ', etc.  This caused
+    too many complications, and removed author's flexibility in
+    combining ellipses with spaces and periods.
+
+  * Allow linebreaks in URLs (treat as spaces). Also, a string of
+    consecutive spaces or tabs is now parsed as a single space. If you have
+    multiple spaces in your URL, use `%20%20`.
+
+  * `Text.Pandoc.Parsing`:
+
+    + Removed `refsMatch`.
+    + Hid `Key` constructor.
+    + Removed custom `Ord` and `Eq` instances for `Key`.
+    + Added `toKey` and `fromKey` to convert between `Key` and `[Inline]`.
+    + Generalized type on `readWith`.
+
+  * Small change in calculation of relative widths of table columns.
+    If the size of the header > the specified column width, use
+    the header size as 100% for purposes of calculating
+    relative widths of columns.
+
+  * Markdown writer now uses some pandoc-specific features when `--strict`
+    is not specified: `\` newline is used for a hard linebreak instead of
+    two spaces then a newline. And delimited code blocks are used when
+    there are attributes.
+
+  * HTML writer:  improved gladTeX output by setting ENV appropriately
+    for display or inline math (Jonathan Daugherty).
+
+  * LaTeX writer: Use `\paragraph`, `\subparagraph` for level 4,5 headers.
+
+  * LaTeX reader:
+
+    + `\label{foo}` and `\ref{foo}` now become `{foo}` instead of `(foo)`.
+    + `\index{}` commands are skipped.
+
+  * Added `fontsize` variable to default LaTeX template.
+    This makes it easy to set the font size using `markdown2pdf`:
+    `markdown2pdf -V fontsize=12pt input.txt`.
+
+  * Fixed problem with strikeout in LaTeX headers when using
+    hyperref, by adding a command to the default LaTeX template
+    that disables `\sout` inside pdf strings. Thanks to Joost Kremers
+    for the fix.
+
+  * The `COLUMNS` environment variable no longer has any effect.
+
+### Under-the-hood improvements
+
+  * Pandoc now compiles with GHC 7. (This alone leads to a
+    significant performance improvement, 15-20%.)
+
+  * Completely rewrote HTML reader using tagsoup as a lexer. The
+    new reader is faster and more accurate.  Unlike the
+    old reader, it does not get bogged down on some input
+    (Issues #277, 255). And it handles namespaces in tags
+    (Issue #274).
+
+  * Replaced `escapeStringAsXML` with a faster version.
+
+  * Rewrote `spaceChar` and some other parsers in Text.Pandoc.Parsing
+    for a significant performance boost.
+
+  * Improved performance of all readers by rewriting parsers.
+
+  * Simplified Text.Pandoc.CharacterReferences by using
+    entity lookup functions from TagSoup.
+
+  * `Text.Pandoc.UTF8` now uses the unicode-aware IO functions
+    from `System.IO` if base >= 4.2.  This gives support for
+    windows line endings on windows.
+
+  * Remove duplications in documentation by generating the
+    pandoc man page from README, using `MakeManPage.hs`.
+
+  * README now includes a full description of markdown syntax,
+    including non-pandoc-specific parts.  A new `pandoc_markdown`
+    man page is extracted from this, so you can look up markdown
+    syntax by doing `man pandoc_markdown`.
+
+  * Completely revised test framework (with help from Nathan Gass).
+    The new test framework is built when the `tests` Cabal flag is set. It
+    includes the old integration tests, but also some new unit and quickcheck
+    tests. Test output has been much improved, and you can now specify a glob
+    pattern after `cabal test` to indicate which tests should be run;
+    for example `cabal test citations` will run all the citation tests.
+
+  * Added a shell script, `stripansi.sh`, for filtering ANSI control
+    sequences from test output: `cabal test | ./stripansi.sh > test.log`.
+
+  * Added `Interact.hs` to make it easier to use ghci while developing.
+    `Interact.hs` loads `ghci` from the `src` directory, specifying
+    all the options needed to load pandoc modules (including
+    specific package dependencies, which it gets by parsing
+    dist/setup-config).
+
+  * Added `Benchmark.hs`, testing all readers + writers using criterion.
+
+  * Added `stats.sh`, to make it easier to collect and archive
+    benchmark and lines-of-code stats.
+
+  * Added upper bounds to all cabal dependencies.
+
+  * Include man pages in extra-source-files.  This allows users to
+    install pandoc from the tarball without needing to build the man
+    pages.
+
+### Bug fixes
+
+  * Filenames are encoded as UTF8.  Resolves Issue #252.
+
+  * Handle curly quotes better in `--smart` mode. Previously, curly quotes
+    were just parsed literally, leading to problems in some output formats.
+    Now they are parsed as `Quoted` inlines, if `--smart` is specified.
+    Resolves Issue #270.
+
+  * Text.Pandoc.Parsing: Fixed bug in grid table parser.
+    Spaces at end of line were not being stripped properly,
+    resulting in unintended LineBreaks.
+
+  * Markdown reader:
+
+    + Allow HTML comments as inline elements in markdown.
+      So, `aaa <!-- comment --> bbb` can be a single paragraph.
+    + Fixed superscripts with links: `^[link](/foo)^` gets
+      recognized as a superscripted link, not an inline note followed by
+      garbage.
+    + Fixed regression, making markdown reference keys case-insensitive again.
+      Resolves Issue #272.
+    + Properly handle abbreviations (like `Mr.`) at the end of a line.
+    + Better handling of intraword underscores, avoiding exponential
+      slowdowns in some cases.  Resolves Issue #182.
+    + Fixed bug in alignments in tables with blank rows in the header.
+
+  * RST reader:
+
+    + Field lists now allow spaces in field names, and
+      block content in field values. (Thanks to Lachlan Musicman
+      for pointing out the bug.)
+    + Definition list items are now always `Para` instead of
+      `Plain`, matching behavior of `rst2xml.py`.
+    + In image blocks, the description is parsed properly and
+      used for the alt attribute, not also the title.
+    + Skip blank lines at beginning of file. Resolves
+      Debian #611328.
+
+  * LaTeX reader:
+
+    + Improved parsing of preamble.
+      Previously you'd get unexpected behavior on a document that
+      contained `\begin{document}` in, say, a verbatim block.
+    + Allow spaces between `\begin` or `\end` and `{`.
+    + Support `\L` and `\l`.
+    + Skip comments inside paragraphs.
+
+  * LaTeX writer:
+
+    + Escape strings in `\href{..}`.
+    + In nonsimple tables, put cells in `\parbox`.
+
+  * OpenDocument writer:  don't print raw TeX.
+
+  * Markdown writer:
+
+    + Fixed bug in `Image`.  URI was getting unescaped twice!
+    + Avoid printing extra blank lines at the end if there are
+      no notes or references.
+
+  * LaTeX and ConTeXt: Escape `[` and `]` as `{[}` and `{]}`.
+    This avoids unwanted interpretation as an optional argument.
+
+  * ConTeXt writer: Fixed problem with inline code.  Previously
+    `}` would be rendered `\type{}}`. Now we check the string for '}' and '{'.
+    If it contains neither, use `\type{}`; otherwise use `\mono{}`
+    with an escaped version of the string.
+
+  * `:` now allowed in HTML tags. Resolves Issue #274.
+
+
+
+## pandoc  1.6 (2010-07-24)
+
++ New EPUB and HTML Slidy writers. (Issue #122)
+
+    - [EPUB] is a standard ebook format, used in Apple's iBooks for
+      the iPad and iPhone, Barnes and Noble's nook reader, the Sony
+      reader, and many other devices, and by online ebook readers like
+      [bookworm]. (Amazon's Kindle uses a different format, MobiPocket,
+      but EPUB books can easily be converted to Kindle format.) Now you
+      can write your book in markdown and produce an ebook with a single
+      command! I've put up a short [tutorial here].
+    - [Slidy], like S5, is a system for producing HTML+javascript slide shows.
+
++ All input is assumed to be UTF-8, no matter what the locale and ghc
+  version, and all output is UTF-8. This reverts to pre-1.5 behavior.
+  Also, a BOM, if present, is stripped from the input.
+
++ Markdown now supports grid tables, whose cells can contain
+  arbitrary block elements. (Issue #43)
+
++ Sequentially numbered example lists in markdown with `@` marker.
+
++ Markdown table captions can begin with a bare colon and no longer need
+  to include the English word "table." Also, a caption can now occur
+  either before or after the table. (Issue #227)
+
++ New command-line options:
+
+    - `--epub-stylesheet` allows you to specify a CSS file that will
+      be used to style your ebook.
+    - `--epub-metadata` allows you to specify metadata for the ebook.
+    - `--offline` causes the generated HTML slideshow to include all
+      needed scripts and stylesheets.
+    - `--webtex` causes TeX math to be converted to images using the
+      Google Charts API (unless a different URL is specified).
+    - `--section-divs` causes div tags to be added around each section
+      in an HTML document. (Issue #230, 239)
+
++ Default behavior of S5 writer in standalone mode has changed:
+  previously, it would include all needed scripts and stylesheets
+  in the generated HTML; now, only links are included unless
+  the `--offline` option is used.
+
++ Default behavior of HTML writer has changed. Between 1.2 and 1.5,
+  pandoc would enclose sections in div tags with identifiers on the
+  div tags, so that the sections can be manipulated in javascript.
+  This caused undesirable interactions with raw HTML div tags. So,
+  starting with 1.6, the default is to put the identifiers directly
+  on the header tags, and not to include the divs.  The `--section-divs`
+  option selects the 1.2-1.5 behavior.
+
++ API changes:
+
+    - `HTMLMathMethod`: Added `WebTeX`, removed `MimeTeX`.
+    - `WriterOptions`: Added `writerUserDataDir`, `writerSourceDirectory`,
+      `writerEPUBMetadata` fields. Removed `writerIncludeBefore`,
+      `writerIncludeAfter`.
+    - Added `headerShift` to `Text.Pandoc.Shared`.
+    - Moved parsing code and `ParserState` from `Text.Pandoc.Shared`
+      to a new module, `Text.Pandoc.Parsing`.
+    - Added `stateHasChapters` to `ParserState`.
+    - Added `HTMLSlideVariant`.
+    - Made `KeyTable` a map instead of an association list.
+    - Added accessors for `Meta` fields (`docTitle`, `docAuthors`, `docDate`).
+    - `Pandoc`, `Meta`, `Inline`, and `Block` have been given `Ord` instances.
+    - Reference keys now have a type of their own (`Key`), with its
+      own `Ord` instance for case-insensitive comparison.
+    - Added `Text.Pandoc.Writers.EPUB`.
+    - Added `Text.Pandoc.UUID`.
+    - Removed `Text.Pandoc.ODT`, added `Text.Pandoc.Writers.ODT`.
+      Removed `saveOpenDocumentAsODT`, added `writeODT`.
+    - Added `Text.Pandoc.Writers.Native` and `writeNative`.
+      Removed `prettyPandoc`.
+    - Added `Text.Pandoc.UTF8` for portable UTF8 string IO.
+    - Removed `Text.Pandoc.Writers.S5` and the `writeS5` function.
+      Moved `s5Includes` to a new module, `Text.Pandoc.S5`.
+      To write S5, you now use `writeHtml` with `writerSlideVariant`
+      set to `S5Slides` or `SlidySlides`.
+
++ Template changes.  If you use custom templates, please update them,
+  particularly if you use syntax highlighting with pandoc. The old HTML
+  templates hardcoded highlighting CSS that will no longer work with
+  the most recent version of highlighting-kate.
+
+    - HTML template: avoid empty meta tag if no date.
+    - HTML template: Use default highlighting CSS from highlighting-kate
+      instead of hard-coding the CSS into the template.
+    - HTML template: insert-before text goes before the title, and
+      immediately after the `<body>` tag, as documented. (Issue #241)
+    - Added slidy and s5 templates.
+    - Added amssymb to preamble of latex template. (github Issue 1)
+
++ Removed excess newlines at the end of output. Note: because output
+  will not contain an extra newline, you may need to make adjustments
+  if you are inserting pandoc's output into a template.
+
++ In S5 and slidy, horizontal rules now cause a new slide, so you
+  are no longer limited to one slide per section.
+
++ Improved handling of code in man writer. Inline code is now monospace,
+  not bold, and code blocks now use .nf (no fill) and .IP (indented para).
+
++ HTML reader parses `<tt>` as Code. (Issue #247)
+
++ html+lhs output now contains bird tracks, even when compiled without
+  highlighting support. (Issue #242)
+
++ Colons are now no longer allowed in autogenerated XML/HTML identifiers,
+  since they have a special meaning in XML.
+
++ Code improvements in ODT writer.  Remote images are now replaced with
+  their alt text rather than a broken link.
+
++ LaTeX reader improvements:
+
+    - Made latex `\section`, `\chapter` parsers more forgiving of whitespace.
+    - Parse `\chapter{}` in latex.
+    - Changed `rawLaTeXInline` to accept `\section`, `\begin`, etc.
+    - Use new `rawLaTeXInline'` in LaTeX reader, and export `rawLaTeXInline`
+      for use in markdown reader.
+    - Fixes bug wherein `\section{foo}` was not recognized as raw TeX
+      in markdown document.
+
++ LaTeX writer:  images are automatically shrunk if they would extend
+  beyond the page margin.
+
++ Plain, markdown, RST writers now use unicode for smart punctuation.
+
++ Man writer converts math to unicode when possible, as in other writers.
+
++ `markdown2pdf` can now recognize citeproc options.
+
++ Command-line arguments are converted to UTF-8. (Issue #234)
+
++ `Text.Pandoc.TeXMath` has been rewritten to use texmath's parser.
+  This allows it to handle a wider range of formulas. Also, if a formula
+  cannot be converted, it is left in raw TeX; formulas are no longer
+  partially converted.
+
++ Unicode curly quotes are left alone when parsing smart quotes. (Issue #143)
+
++ Cabal file changes:
+
+    - Removed parsec < 3 restriction.
+    - Added 'threaded' flag for architectures where GHC lacks a threaded
+      runtime.
+    - Use 'threaded' only for markdown2pdf; it is not needed for pandoc.
+    - Require highlighting-kate 0.2.7.
+
++ Use explicit imports from `Data.Generics`. Otherwise we have a
+  conflict with the 'empty' symbol, introduced in syb >= 0.2. (Issue #237)
+
++ New data files:  slidy/slidy.min.js, slidy/slidy.min.css, epub.css.
+
+[EPUB]: http://en.wikipedia.org/wiki/EPUB
+[Slidy]: http://www.w3.org/Talks/Tools/Slidy
+[bookworm]: http://bookworm.oreilly.com/
+[tutorial here]: http://johnmacfarlane.net/pandoc/epub.html
+
+## pandoc  1.5.1.1 (2010-03-29)
+
++ Fixed header identifiers (uniqueIdent in Shared) so they
+  work as advertized in README and are guaranteed to be
+  valid XHTML names. Thanks to Xyne for reporting the bug.
+
+## pandoc  1.5.1 (2010-03-23)
+
++ Fixed treatment of unicode characters in URIs.
++ Revised Setup.hs so it works with debian's build process.
++ Fixed bug in OpenDocument writer that led to invalid
+  XML for some input.
+
+## pandoc  1.5.0.1 (2010-03-21)
+
++ HTML writer: Fixed error in math writer (with MathML option)
+  that caused an infinite loop for unparsable MathML.
+
+## pandoc  1.5 (2010-03-20)
+
++ Moved repository to [github](http://github.com/jgm/pandoc).
++ New `--mathml` option, for display of TeX math as MathML.
++ New `--data-dir` option, allowing users to specify a data
+  directory other than `~/.pandoc`.  Files placed in this directory
+  will be used instead of system defaults.
++ New `--base-header-level` option. For example, `--base-header-level=2`
+  changes level 1 headers to level 2, level 2 to level 3, etc.
++ New 'plain' output format: plain text without pictures, hyperlinks,
+  inline formatting, or anything else that looks even vaguely
+  markupish.
++ Titles and authors in title blocks can now span multiple lines,
+  as long as the continuation lines begin with a space character.
++ When given an absolute URI as a parameter, pandoc will fetch
+  the content via HTTP.
++ The HTML reader has been made much more forgiving. It no
+  longer requires well-formed xhtml as input.
++ `html2markdown` has been removed; it is no longer necessary, given
+  the last two changes. `pandoc` can be used by itself to convert
+  web pages to markdown or other formats.
++ `hsmarkdown` has also been removed.  Use `pandoc --strict` instead.
+  Or symlink pandoc's executable to `hsmarkdown`; `pandoc` will then
+  behave like `hsmarkdown` used to.
++ An image in a paragraph by itself is now rendered as a figure
+  in most writers, with the alt text as the caption.
++ Incomplete support for reST tables (simple and grid). Thanks to
+  Eric Kow. Colspans and rowspans not yet supported.
++ In mediawiki, links with relative URLs are now formatted as wikilinks.
+  Also, headers have been promoted: `= head =` is now level 1 instead of
+  level 2.
++ The markdown reader now handles "inverse bird tracks" when parsing
+  literate haskell.  These are used for haskell example code that
+  is not part of the literate program.
++ The `-B` and `-A` options now imply `-s` and no longer work in
+  fragment mode.
++ Headerless tables are now printed properly in all writers.
+  In addition, tbody, thead, and cols are used in HTML and Docbook
+  tables.
++ Improved build system; removed obsolete Makefile.
++ In LaTeX writer, `\chapter` is now used instead of `\section`.
+  when the documentclass is book, report, or memoir.
++ Many small bug fixes. See [changelog] for details.
+
+## pandoc  1.4 (2010-01-02)
+
++ New template system replaces old headers, giving users much
+  more control over pandoc's output in `--standalone` mode.
+  Added `--template` and `--variable` options.  The `--print-default-header`
+  option is now `--print-default-template`.  See README under
+  "Templates" for details.
++ The old `--custom-header` option should still work, but it has
+  been deprecated.
++ New `--reference-odt` option allows users to customize styles
+  in ODT output.
++ Users may now put custom templates, s5 styles, and a reference
+  ODT in the `~/.pandoc` directory, where they will override system
+  defaults. See README for details.
++ Unicode is now used whenever possible in HTML and XML output. Entities
+  are used only where necessary (`&gt;`, `&lt;`, `&quot;`, `&amp;`).
++ Authors and dates may now include formatting and notes.
++ Added `--xetex` option for `pandoc` and `markdown2pdf`.
++ Windows installer now includes highlighting support and
+  `markdown2pdf` and `hsmarkdown` wrappers.
++ Pandoc no longer requires Template Haskell, which should make
+  it more portable.
++ Pandoc can now be built on GHC 6.12, as well as earlier versions.
++ See README for other small improvements and bug fixes.
+
+## pandoc  1.3 (2009-12-10)
+
++ Added `--id-prefix` option to help prevent duplicate
+  identifiers when you're generating HTML fragments.
++ Added `--indented-code-classes` option, which specifies
+  default highlighting syntax for indented code blocks.
++ `--number-sections` now affects HTML output.
++ Improved syntax for markdown definition lists.
++ Better looking simple tables.
++ Markdown tables without headers are now possible.
++ New hard line break syntax:  backslash followed by newline.
++ Improved performance of markdown reader by ~10% by eliminating the
+  need for a separate parsing pass for notes.
++ Improved syntax highlighting for literate Haskell.
++ Support for "..code-block" directive in RST reader.
++ Windows binary now includes highlighting support.
++ Many bug fixes and small improvements. See [changelog]
+  for details.
+
+## pandoc  1.2.1 (2009-07-18)
+
++ Improved the efficiency of the markdown reader's
+  abbreviation parsing (should give a big performance
+  boost with `--smart`).
++ HTML writer now wraps sections in divs with unique
+  identifiers, for easier manipulation.
++ Improved LaTeX reader's coverage of math modes.
++ Added a portable Haskell version of markdown2pdf (thanks
+  to Paolo Tanimoto).
++ Made `--strict` compatible with `--standalone` and `--toc.`
++ Many other small improvements and bug fixes.
+  See [changelog] for details.
+
+## pandoc  1.2 (2009-03-01)
+
++ Added support for literate Haskell. lhs support is triggered by
+  '+lhs' suffixes in formats. For example, 'latex+lhs' is literate
+  Haskell LaTeX. '.lhs' files are treated by default as literate
+  markdown.
++ Added `--email-obfuscation` option.
++ Brought citeproc support up to date for citeproc-hs-0.2.
++ Many bugs fixed. See [changelog] for details.
+
+## pandoc  1.1 (2008-11-06)
+
++ New `--jsmath` option supporting use of pandoc with [jsMath].
++ Classes on HTML table output for better CSS styling.
++ Windows installer no longer requires admin privileges.
++ Many bugs fixed.  See [changelog] for details.
+
+## pandoc  1.0 (2008-09-13)
+
++ New writers for MediaWiki, GNU Texinfo (thanks to Peter Wang),
+  OpenDocument XML (thanks to Andrea Rossato), and ODT (OpenOffice
+  document).
++ New [delimited code blocks](README.html#delimited-code-blocks),
+  with optional syntax highlighting.
++ Reorganized build system:  pandoc can now be built using standard
+  Cabal tools.  It can be compiled on Windows without Cygwin.
+  The tests can also be run without perl or unix tools.
++ LaTeXMathML replaces ASCIIMathML for rendering math in HTML.
++ Support for "displayed" math.
++ Common abbreviations are now handled more intelligently, with
+  a non-breaking space (and not a sentence-ending space) after
+  the period.
++ Code is -Wall clean.
++ Many bug fixes and small improvements.  See [changelog] for
+  full details.
+
+## pandoc  0.46 (2008-01-08)
+
++ Added a `--sanitize-html` option (and a corresponding parameter
+  in `ParserState` for those using the pandoc libraries in programs).
+  This option causes pandoc to sanitize HTML (in HTML or Markdown
+  input) using a whitelist method. Possibly harmful HTML elements
+  are replaced with HTML comments. This should be useful in the
+  context of web applications, where pandoc may be used to convert
+  user input into HTML.
++ Made -H, -A, and -B options cumulative: if they are specified
+  multiple times, multiple files will be included.
++ Many bug fixes and small improvements.  See [changelog] for full
+  details.
+
+## pandoc  0.45 (2007-12-09)
+
++ Many bug fixes and structural improvements.  See [changelog] for
+  full details.
++ Improved treatment of math. Math is now rendered using unicode
+  by default in HTML, RTF, and DocBook output. For more accurate
+  display of math in HTML, `--gladtex`, `--mimetex`, and `--asciimathml`
+  options are provided. See the [User's Guide](README.html#math) for
+  details.
++ Removed support for box-style block quotes in markdown.
++ More idiomatic ConTeXt output.
++ Text wrapping in ConTeXt and LaTeX output.
++ Pandoc now correctly handles all standard line endings
+  (CR, LF, CRLF).
++ New `--no-wrap` option that disables line wrapping and minimizes
+  whitespace in HTML output.
++ Build process is now compatible with both GHC 6.8 and GHC 6.6.
+  GHC and GHC_PKG environment variables may be used to specify
+  which version of the compiler to use, when multiple versions are
+  installed.
+
+## pandoc 0.44 (2007-09-03)
+
+  [ John MacFarlane ]
+
+  * Fixed bug in HTML writer:  when --toc was used, anchors were put around
+    headers, which is invalid XHTML (block content within inline element).
+    Now the anchors are put inside the header tags.  Resolves Issue #23.
+
+  * Added xmlns attribute to html element in html writer tests.
+    This attribute is added by more recent versions of the
+    xhtml library (>= 3000), and is required for valid XHTML.
+
+  [ Recai Oktaş ]
+
+  * On configure, compile 'Setup.hs' to 'setup' and use 'setup' as the build
+    command instead of 'runhaskell', which, on some platforms (such as s390,
+    alpha, m68k), throws the following error:
+
+        runhaskell Setup.hs configure --prefix=/usr
+        ghc-6.6.1: not built for interactive use
+
+    This causes a serious FTBFS bug.  Closes: #440668.
+
+## pandoc 0.43 (2007-09-02)
+
+  [ John MacFarlane ]
+
+  * The focus of this release is performance.  The markdown parser
+    is about five times faster than in 0.42, based on benchmarks
+    with the TextMate manual.
+
+  * Main.hs: Replaced CRFilter and tabFilter with single function
+    tabFilter, which operates on the whole string rather than breaking
+    it into lines, and handles dos-style line-endings as well as tabs.
+
+  * Added separate LaTeX reader and native reader tests; removed
+    round-trip tests.
+
+  * Text.Pandoc.Shared:
+
+    + Removed tabsToSpaces and tabsInLine (they were used only in Main.hs.)
+    + General code cleanup (to elimante warnings when compiling with -Wall.)
+    + Added 'wrapped' function, which helps wrap text into paragraphs,
+      using the prettyprinting library.
+    + Rewrote charsInBalanced and charsInBalanced'.
+        - Documented restriction: open and close must be distinct characters.
+        - Rearranged options for greater efficiency.
+        - Bug fix: Changed inner call to charsInBalanced inside
+          charsInBalanced' to charsInBalanced'.
+    + anyLine now requires that the line end with a newline (not eof).
+      This is a harmless assumption, since we always add newlines to the
+      end of a block before parsing with anyLine, and it yields a 10% speed
+      boost.
+    + Removed unnecessary 'try' in anyLine.
+    + Removed unneeded 'try' from romanNumeral parser.
+    + Use notFollowedBy instead of notFollowedBy' in charsInBalanced.
+    + Removed unneeded 'try' in parseFromString.
+    + Removed unneeded 'try' from stringAnyCase.  (Now it behaves
+      like 'string'.)
+    + Changed definition of 'enclosed' in Text.Pandoc.Shared so that
+      'try' is not automatically applied to the 'end' parser. Added
+      'try' in calls to 'enclosed' where needed. Slight speed increase.
+
+  * Writers:
+
+    + Replaced individual wrapping routines in RST, Man, and Markdown
+      writers with 'wrapped' from Text.Pandoc.Shared.
+    + Rewrote LaTeX writer to use the prettyprinting library,
+      so we get word wrapping, etc.
+    + Modified latex writer tests for new latex writer using prettyprinter.
+    + Fixed bug in LaTeX writer: autolinks would not cause
+      `\usepackage{url}` to be put in the document header. Also, changes
+      to state in enumerated list items would be overwritten.
+    + In Markdown writer, escape paragraphs that begin with ordered list
+      markers, so they don't get interpreted as ordered lists.
+
+  * Text.Pandoc.Reades.LaTeX:
+
+    + Fixed bug in LaTeX reader, which wrongly assumed that the roman
+      numeral after "enum" in "setcounter" would consist entirely of
+      "i"s. 'enumiv' is legitimate.
+    + LaTeX command and environment names can't contain numbers.
+    + Rearranged order of parsers in inline for slight speed improvement.
+    + Added '`' to special characters and 'unescapedChar'.
+
+  * Text.Pandoc.Readers.RST:
+
+    + Removed unneeded try's in RST reader; also minor code cleanup.
+    + Removed tabchar.
+    + Rearranged parsers in inline (doubled speed).
+
+  * Text.Pandoc.Readers.Markdown:
+
+    + Skip notes parsing if running in strict mode. (This yields a nice
+      speed improvement in strict mode.)
+    + Simplify autolink parsing code, using Network.URI to test for
+      URIs. Added dependency on network library to debian/control and
+      pandoc.cabal.
+    + More perspicuous definition of nonindentSpaces.
+    + Removed unneeded 'try' in 'rawLine'.
+    + Combined linebreak and whitespace into a new whitespace parser, to
+      avoid unnecessary reparsing of space characters.
+    + Removed unnecessary 'try' in 'codeBlock', 'ellipses', 'noteMarker',
+      'multilineRow', 'dashedLine', 'rawHtmlBlocks'.
+    + Use lookAhead in parsers for setext headers and definition lists
+      to see if the next line begins appropriately; if not, don't waste
+      any more time parsing.
+    + Don't require blank lines after code block. (It's sufficient to
+      end code block with a nonindented line.)
+    + Changed definition of 'emph': italics with '_' must not
+      be followed by an alphanumeric character. This is to help
+      prevent interpretation of e.g. `[LC_TYPE]: my_type` as
+      `[LC<em>TYPE]:my</em>type`.
+    + Improved Markdown.pl-compatibility in referenceLink: the two parts
+      of a reference-style link may be separated by one space, but not
+      more... [a] [link], [not]    [a link].
+    + Fixed markdown inline code parsing so it better accords with
+      Markdown.pl: the marker for the end of the code section is a clump
+      of the same number of `'s with which the section began, followed
+      by a non-` character. So, for example,
+         ` h ``` i ` -> `<code>h ``` i</code>`.
+    + Split 'title' into 'linkTitle' and 'referenceTitle', since the
+      rules are slightly different.
+    + Rewrote 'para' for greater efficiency.
+    + Rewrote link parsers for greater efficiency.
+    + Removed redundant 'referenceLink' in definition of inline (it's
+      already in 'link').
+    + Refactored escapeChar so it doesn't need 'try'.
+    + Refactored hrule for performance in Markdown reader.
+    + More intelligent rearranging of 'inline' so that most frequently
+      used parsers are tried first.
+    + Removed tabchar parser, as whitespace handles tabs anyway.
+
+  * Text.Pandoc.CharacterReferences:
+
+    + Refactored.
+    + Removed unnecessary 'try's for a speed improvement.
+    + Removed unnecessary '&' and ';' from the entity table.
+
+  * Build process:
+
+    + Makefile: Get VERSION from cabal file, not Main.hs.
+    + Modified MacPorts Portfile:
+        - Depend on haddock
+        - Build and install libraries and library documentation in
+          addition to pandoc executable
+        - Added template item for md5 sum in Portfile.in.
+        - Incorporated changes from MacPorts repository (r28278).
+    + FreeBSD port:  Don't try to generate distinfo in Makefile.
+      It can be made using 'make makesum' in FreeBSD.
+    + Make both freebsd and macports targets depend on tarball.
+
+  * Website and documentation:
+
+    + Updated INSTALL instructions.
+    + Added pandocwiki demo to website.
+    + Removed local references to Portfile, since pandoc is now in the
+      MacPorts repository.
+
+## pandoc 0.42 (2007-08-26)
+
+  [ John MacFarlane ]
+
+  * Main.hs: Use utf8 conversion on the extra files loaded with
+    the -H, -C, -B, and -A options.  This fixes problems with unicode
+    characters in these files.
+
+  * Exposed Text.Pandoc.ASCIIMathML, since it is imported in
+    Text.Pandoc.Readers.HTML and without it we get a linking error when
+    using the library.
+
+  * Markdown reader:
+
+    + Added new rule for enhanced markdown ordered lists: if the list
+      marker is a capital letter followed by a period (including a
+      single-letter capital roman numeral), then it must be followed by
+      at least two spaces. The point of this is to avoid accidentally
+      treating people's initials as list markers: a paragraph might begin,
+      "B. Russell was an English philosopher," and this shouldn't be
+      treated as a list.  Documented change in README.
+    + Blocks that start with "p. " and a digit are no longer treated
+      as ordered lists (it's a page number).
+    + Added a needed 'try' to listItem.
+    + Removed check for a following setext header in endline.
+      A full test is too inefficient (doubles benchmark time), and the
+      substitute we had before is not 100% accurate.
+    + Don't use Code elements for autolinks if --strict specified.
+
+  * LaTeX writer:  When a footnote ends with a Verbatim environment, the
+    close } of the footnote cannot occur on the same line or an error occurs.
+    Fixed this by adding a newline before the closing } of every footnote.
+
+  * HTML writer:
+    + Removed incorrect "{}" around style information in HTML tables.
+      Column widths now work properly in HTML.
+    + If --strict option is specified (and --toc is not), don't include
+      identifiers in headers, for better Markdown compatibility.
+
+  * Build process:
+
+    + Separated $(web_dest) and website targets.
+    + In website, index.txt is now constructed from template index.txt.in.
+    + Added freebsd target to Markefile. This creates the freebsd Makefile
+      from Makefile.in, and creates distinfo.  Removed Makefile and distinfo
+      from the repository.
+    + Added macport target to Makefile. Portfile is built from template
+      Portfile.in.
+    + Removed OSX package targets.  (Too many difficulties involving
+      dependencies on dynamic libraries.)
+    + More complete INSTALL instructions for all architectures.
+
+  * Website:
+    + Added a programming demo, pandocwiki.
+
+  [ Recai Oktaş ]
+
+  * Do not forget to close pandoc's ITP.  Closes: #391666
+
+## pandoc 0.41 (2007-08-19)
+
+  [ John MacFarlane ]
+
+  * Fixed bugs in HTML reader:
+    + Skip material at end *only if* `</html>` is present (previously,
+      only part of the document would be parsed if an error was
+      found; now a proper error message is given).
+    + Added new constant eitherBlockOrInline with elements that may
+      count either as block-level or as inline. Modified isInline and
+      isBlock to take this into account.
+    + Modified rawHtmlBlock to accept any tag (even an inline tag):
+      this is innocuous, because rawHtmlBlock is tried only if a regular
+      inline element can't be parsed.
+    + Added a necessary 'try' in definition of 'para'.
+
+  * Fixed bug in markdown ordered list parsing.  The problem was that
+    anyOrderedListStart did not check for a space following the
+    ordered list marker.  So in 'A.B. 2007' the parser would be
+    expecting a list item, but would not find one, causing an error.
+    Fixed a similar bug in the RST reader.  Resolves Issue #22.
+
+  * Refactored RST and Markdown readers using parseFromString.
+
+  * LaTeX reader will now skip anything after \end{document}.
+
+  * Fixed blockquote output in markdown writer: previously, block
+    quotes in indented contexts would be indented only in the first
+    line.
+
+  * Added note to INSTALL about variations in versions of the xhtml
+    library that can lead to failed tests (thanks to Leif LeBaron).
+
+## pandoc 0.4 (2007-01-16)
+
+  [ John MacFarlane ]
+
+  * Added two new output formats: groff man pages and ConTeXt. By
+    default, output files with extensions ".ctx" and ".context" are
+    assumed to be ConTeXt, and output files with single-digit extensions
+    are assumed to be man pages.
+
+  * Enhanced ordered lists (documented in README, under Lists):
+    + The OrderedList block element now stores information about
+      list number style, list number delimiter, and starting number.
+    + The readers parse this information when possible.
+    + The writers use this information to style ordered lists.
+    + The enhancement can be disabled using the --strict option.
+
+  * Added support for tables (with a new Table block element). Two kinds
+    of tables are supported: a simple table with one-line rows, and a
+    more complex variety with multiline rows. All output formats are
+    supported, but only markdown tables are parsed at the moment. The
+    syntax is documented in README.
+
+  * Added support for definition lists (with a new DefinitionList block
+    element). All output and input formats are supported. The syntax is
+    documented in README.
+
+  * Added support for superscripts and subscripts (with new Superscript
+    and Subscript inline elements).  All input and output
+    formats.  The syntax is documented in README.
+
+  * Added support for strikeout (with a new Strikeout inline element).
+    All input and output formats are supported. Thanks to Bradley Kuhn,
+    who contributed a patch. The syntax is documented in README. Resolves
+    Issue #18.
+
+  * Added a --toc|--table-of-contents option.  This causes an automatically
+    generated table of contents (or an instruction that creates one) to
+    be inserted at the beginning of the document. Not supported in S5,
+    DocBook, or man page writers.
+
+  * Modified the -m|--asciimathml option:
+
+    + If an optional URL argument is provided, a link is inserted
+      instead of the contents of the ASCIIMathML.js script.
+    + Nothing is inserted unless the document actually contains
+      LaTeX math.
+
+  * Removed Blank block element as unnecessary.
+
+  * Removed Key and Note blocks from the Pandoc data structure. All
+    links are now stored as explicit links, and note contents are
+    stored with the (inline) notes.
+
+    + All link Targets are now explicit (URL, title) pairs; there
+      is no longer a 'Ref' target.
+    + Markdown and RST parsers now need to extract data from key and
+      note blocks and insert them into the relevant inline elements.
+      Other parsers have been simplified, since there is no longer any need
+      to construct separate key and note blocks.
+    + Markdown, RST, and HTML writers need to construct lists of
+      notes; Markdown and RST writers need to construct lists of link
+      references (when the --reference-links option is specified); and
+      the RST writer needs to construct a list of image substitution
+      references. All writers have been rewritten to use the State monad
+      when state is required.
+    + Several functions (generateReference, keyTable,
+      replaceReferenceLinks, replaceRefLinksBlockList, and some auxiliaries
+      used by them) have been removed from Text.Pandoc.Shared, since
+      they are no longer needed. New functions and data structures
+      (Reference, isNoteBlock, isKeyBlock, isLineClump) have been
+      added. The functions inTags, selfClosingTag, inTagsSimple, and
+      inTagsIndented have been moved to the DocBook writer, since that
+      is now the only module that uses them. NoteTable is now exported
+      in Text.Pandoc.Shared.
+    + Added stateKeys and stateNotes to ParserState; removed stateKeyBlocks,
+      stateKeysUsed, stateNoteBlocks, stateNoteIdentifiers, stateInlineLinks.
+    + Added writerNotes and writerReferenceLinks to WriterOptions.
+
+  * Added Text.Pandoc module that exports basic readers, writers,
+    definitions, and utility functions. This should export everything
+    needed for most uses of Pandoc libraries. The haddock documentation
+    includes a short example program.
+
+  * Text.Pandoc.ASCIIMathML is no longer an exported module.
+
+  * Added Text.Pandoc.Blocks module to help in printing markdown
+    and RST tables.  This module provides functions for working with
+    fixed-width blocks of text--e.g., placing them side by side, as
+    in a table row.
+
+  * Refactored to avoid reliance on Haskell's Text.Regex library, which
+    (a) is slow, and (b) does not properly handle unicode.  This fixed
+    some strange bugs, e.g. in parsing S-cedilla, and improved performance.
+
+    + Replaced 'gsub' with a general list function  'substitute'
+      that does not rely on Text.Regex.
+    + Rewrote extractTagType in HTML reader so that it doesn't use
+      regexs.
+    + In Markdown reader, replaced email regex test with a custom email
+      autolink parser (autoLinkEmail). Also replaced selfClosingTag regex
+      with a custom function isSelfClosingTag.
+    + Modified Docbook writer so that it doesn't rely on Text.Regex for
+      detecting 'mailto' links.
+    + Removed escapePreservingRegex and reamped entity-handling
+      functions in Text.Pandoc.Shared and Text.Pandoc.CharacterReferences to
+      avoid reliance on Text.Regex (see below on character reference
+      handling changes).
+
+  * Renamed Text.Pandoc.Entities as Text.Pandoc.CharacterReferences.
+
+  * Changed handling of XML entities.  Entities are now parsed (and unicode
+    characters returned) in the Markdown and HTML readers, rather than being
+    handled in the writers.  In HTML and Docbook writers, UTF-8 is now used
+    instead of entities for characters above 128.  This makes the HTML and
+    DocBook output much more readable and more easily editable.
+
+    + Removed sgmlHexEntity, sgmlDecimalEntity, sgmlNamedEntity, and
+      sgmlCharacterEntity regexes from Text.Pandoc.Shared.
+    + Renamed escapeSGMLChar to escapeCharForXML.  Added escapeStringForXML.
+      Moved both functions to Text.Pandoc.Writers.Docbook.
+    + Added characterReference parser to Text.Pandoc.CharacterReferences.
+      This parses a string and return a unicode character.
+    + Rewrote decodeCharacterReferences to use the new parser instead of
+      Text.Regex.
+    + Added new charRef parser for Markdown and HTML, which replaces the
+      old 'entity' parser. Added '&' as a special character in Markdown reader.
+    + Modified HTML and Markdown readers to call decodeEntities on all raw
+      strings (e.g. authors, dates, link titles), to ensure that no
+      unprocessed entities are included in the native representation of
+      the document.  (In the HTML reader, most of this work is done by a
+      change in extractAttributeName.)
+    + In XML and Markdown output, escape unicode nonbreaking space as '&nbsp;',
+      since a unicode non-breaking space is impossible to distinguish visually
+      from a regular space.  (Resolves Issue #3.)
+    + Removed encodeEntitiesNumerical.
+    + Use Data.Map for entityTable and (new) reverseEntityTable, for a
+      slight performance boost over the old association list.
+    + Removed unneeded decodeEntities from 'str' parser in HTML and
+      Markdown readers.
+
+  * Text.Pandoc.UTF8:  Renamed encodeUTF8 to toUTF8, decodeUTF8 to
+    fromUTF8, for clarity.
+
+  * Replaced old haskell98 module names replaced by hierarchical module
+    names, e.g. List by Data.List.  Removed haskell98 from dependencies
+    in pandoc.cabal, and added mtl (needed for state monad). Substituted
+    xhtml for html.
+
+  * Refactored and cleaned up character escaping in writers, using
+    backslashEscapes and escapeStringUsing functions.
+
+  * Instead of adding `\n\n` to the end of an input string in Main.hs,
+    this is now done in the readers. This makes the libraries behave
+    the way you'd expect from the pandoc program. Resolves Issue #10.
+
+  * URLs and email addresses in autolinks are now typeset as Code.
+
+  * In Main.hs, changed putStr to putStrLn -- mainly because MacOS X
+    doesn't display the whole output unless there's a line ending.
+
+  * Major code cleanup in all modules, for greater consistency, concision,
+    and readability.
+
+  * HTML reader:
+
+    + Fixed several bugs (extractTagType, attribute parsing).
+    + Remove Null blocks in lists of blocks when possible.
+    + Allow HTML comments as raw HTML inline.
+
+  * Markdown reader:
+
+    + Ordered list items may no longer begin with uppercase letters, or
+      letters greater than 'n'.  (This prevents first initials and page
+      reference, e.g. 'p. 400', from being parsed as beginning lists.)
+      Also, numbers beginning list items may no longer end with ')',
+      which is now allowed only after letters.  Note: These changes
+      may cause documents to be parsed differently. Users should take
+      care in upgrading.
+    + Changed autoLink parsing to conform better to Markdown.pl's
+      behavior. `<google.com>` is not treated as a link, but
+      `<http://google.com>`, `<ftp://google.com>`, and
+      `<mailto:google@google.com>` are.
+    + Cleaned up handling of embedded quotes in link titles.  Now these are
+      stored as a '"' character, not as '&quot;'.
+    + Use lookAhead parser for the 'first pass' (looking for reference keys),
+      instead of parsing normally, then using setInput to reset input.  This
+      yields a slight performance boost.
+    + Fixed several bugs in smart quote recognition.
+    + Fixed bug in indentSpaces (which didn't properly handle
+      cases with mixed spaces and tabs).
+    + Consolidated 'text', 'special', and 'inline' into 'inline'.
+    + Fixed bug which allowed URL and title to be separated by multiple blank
+      lines in links and reference keys.  They can be on separate lines but
+      can't have blank lines between them.
+    + Correctly handle bracketed text inside inline footnotes and links,using
+      new function inlinesInBalanced.  Resolves Issue #14.
+    + Fixed bug in footnotes: links in footnotes were not being
+      processed. Solution: three-stage parse. First, get all the
+      reference keys and add information to state. Next, get all the
+      notes and add information to state. (Reference keys may be needed
+      at this stage.) Finally, parse everything else.
+    + Replaced named constants like 'emphStart' with literals.
+    + Removed an extra occurrence of escapedChar in definition of inline.
+
+  * RST reader:
+
+    + Allow the URI in a RST hyperlink target to start on the line
+      after the reference key.
+    + Added 'try' in front of 'string', where needed, or used a different
+      parser.  This fixes a bug where ````` would not be correctly parsed as
+      a verbatim `.
+    + Fixed slow performance in parsing inline literals in RST reader.  The
+      problem was that ``#`` was seen by 'inline' as a potential link or image.
+      Fix:  inserted 'notFollowedBy (char '`')' in link parsers.
+      Resolves Issue #8.
+    + Use lookAhead instead of getInput/setInput in RST reader.  Removed
+      unneeded getState call, since lookAhead automatically saves and
+      restores the parser state.
+    + Allow hyperlink target URIs to be split over multiple lines, and
+      to start on the line after the reference. Resolves Issue #7.
+    + Fixed handling of autolinks.
+
+  * LaTeX reader:
+
+    + Replaced `choice [(try (string ...), ...]` idiom with `oneOfStrings`,
+      for clarity.
+    + Added clauses for tilde and caret. Tilde is `\ensuremath{\sim}`, and
+      caret is `\^{}`, not `\^` as before.
+    + Added parsing for `\url`.
+    + Parse `\texttt{}` as code, provided there's nothing fancy inside.
+
+  * HTML writer:
+
+    + Modified HTML writer to use the Text.XHtml library. This results
+      in cleaner, faster code, and it makes it easier to use Pandoc in
+      other projects, like wikis, which use Text.XHtml. Two functions are
+      now provided, writeHtml and writeHtmlString: the former outputs an
+      Html structure, the latter a rendered string. The S5 writer is also
+      changed, in parallel ways (writeS5, writeS5String).
+    + The Html header is now written programmatically, so it has been
+      removed from the 'headers' directory. The S5 header is still
+      needed, but the doctype and some of the meta declarations have
+      been removed, since they are written programmatically. This change
+      introduces a new dependency on the xhtml package.
+    + Fixed two bugs in email obfuscation involving improper escaping
+      of '&' in the `<noscript>` section and in `--strict` mode. Resolves
+      Issue #9.
+    + Fixed another bug in email obfuscation: If the text to be obfuscated
+      contains an entity, this needs to be decoded before obfuscation.
+      Thanks to thsutton for the patch. Resolves Issue #15.
+    + Changed the way the backlink is displayed in HTML footnotes.
+      Instead of appearing on a line by itself, it now generally
+      appears on the last line of the note.  (Exception:  when the
+      note does not end with a Plain or Para block.) This saves space
+      and looks better.
+    + Added automatic unique identifiers to headers:
+      - The identifier is derived from the header via a scheme
+        documented in README.
+      - WriterState now includes a list of header identifiers and a table
+        of contents in addition to notes.
+      - The function uniqueIdentifiers creates a list of unique identifiers
+        from a list of inline lists (e.g. headers).
+      - This list is part of WriterState and gets consumed by blockToHtml
+        each time a header is encountered.
+    + Include CSS for .strikethrough class in header only if strikethrough
+      text appears in the document.
+    + If the 'strict' option is specified, elements that do not appear in
+      standard markdown (like definition lists) are passed through as
+      raw HTML.
+    + Simplified treatment of autolinks, using pattern matching instead of
+      conditionals.
+
+  * Markdown writer:
+
+    + Links in markdown output are now printed as inline links by default,
+      rather than reference links.  A --reference-links option has been added
+      that forces links to be printed as reference links.  Resolves Issue #4.
+    + Use autolinks when possible.  Instead of `[site.com](site.com)`,
+      use `<site.com>`.
+
+  * LaTeX writer:
+
+    + Rewrote to use the State monad. The preamble now includes only those
+      packages that are actually required, given the document's content.
+      Thus, for example, if strikeout is not used, ulem is not required.
+      Modified LaTeXHeader accordingly.
+    + Modified LaTeX writer to insert `\,` between consecutive quotes.
+    + Removed unused function tableRowColumnWidths.
+    + Simplified code for escaping special characters.
+    + Leave extra blank line after `\maketitle`.
+    + Include empty `\author{}` when no author specified to avoid LaTeX
+      errors.
+    + Include fancyvrb code in header only if needed -- that is, only
+      if there is actually code in a footnote.
+    + Use `\url{}` for autolinks.
+    + Include [mathletters] option in ucs package, so that basic unicode
+      Greek letters will work correctly.
+
+  * RST writer:  Force blank line before lists, so that sublists will
+    be handled correctly.
+
+  * Docbook writer:  Fixed a bug:  email links with text, like
+    [foo](me@bar.baz), were being incorrectly treated as autolinks.
+
+  * Removed Text.ParserCombinators.Pandoc and moved all its functions to
+    Text.Pandoc.Shared.
+
+  * Text.Pandoc.Shared:
+
+    + Added defaultWriterOptions.
+    + Added writerTableOfContents to WriterOptions.
+    + Added writerIgnoreNotes option to WriterOptions.  This is needed
+      for processing header blocks for a table of contents, since notes on
+      headers should not appear in the TOC.
+    + Added prettyprinting for native Table format.
+    + Removed some unneeded imports.
+    + Moved escape and nullBlock parsers from
+      Text.ParserCombinators.Pandoc, since the latter is for
+      general-purpose parsers that don't depend on Text.Pandoc.Definition.
+    + Moved isHeaderBlock from Text.Pandoc.Writers.HTML.
+    + Moved Element, headerAtLeast, and hierarchicalize from Docbook
+      writer, because HTML writer now uses these in constructing a table
+      of contents.
+    + Added clauses for new inline elements (Strikeout, Superscript,
+      Subscript) to refsMatch.
+    + Removed backslashEscape; added new functions escapeStringUsing and
+      backslashEscapes.
+    + Moved failIfStrict from markdown reader, since it is now used also
+      by the HTML reader.
+    + Added a 'try' to the definition of indentSpaces.
+    + In definition of 'reference', added check to make sure it's not a note
+      reference.
+    + Added functions: camelCaseToHyphenated, toRomanNumeral,
+      anyOrderedListMarker, orderedListmarker, orderedListMarkers,
+      charsInBalanced', withHorizDisplacement, romanNumeral
+    + Fixed a bug in the anyLine parser. Previously it would parse an empty
+      string "", but it should fail on an empty string, or we get an error
+      when it is used inside "many" combinators.
+    + Removed followedBy' parser, replacing it with the lookAhead parser from
+      Parsec.
+    + Added some needed 'try's before multicharacter parsers, especially in
+      'option' contexts.
+    + Removed the 'try' from the 'end' parser in 'enclosed', so that
+      'enclosed' behaves like 'option', 'manyTill', etc.
+    + Added lineClump parser, which parses a raw line block up to and
+      including any following blank lines.
+    + Renamed parseFromStr to parseFromString.
+    + Added a 'try' to the 'end' parser in 'enclosed'.  This makes errors in
+      the use of 'enclosed' less likely. Removed some now-unnecessary 'try's
+      in calling code.
+    + Removed unneeded 'try' in blanklines.
+    + Removed endsWith function and rewrote calling functions to use
+      isSuffixOf instead.
+    + Added >>~ combinator.
+    + Fixed bug in normalizeSpaces:  Space:Str "":Space should compress to
+      Space.
+
+  * Refactored runtests.pl; added separate tests for tables.
+
+  * Shell scripts:
+
+    + Added -asxhtml flag to tidy in html2markdown. This will
+      perhaps help the parser, which expects closing tags.
+    + Modified markdown2pdf to run pdflatex a second time if --toc or
+      --table-of-contents was specified; otherwise the table of
+      contents won't appear.
+    + Modified markdown2pdf to print a helpful message if the 'ulem'
+      LaTeX package is required and not found.
+
+  * Changes to build process:
+
+    + Dropped support for compilation with GHC 6.4.  GHC 6.6 or higher
+      is now required.
+    + Removed cabalize and Pandoc.cabal.in. The repository now contains
+      pandoc.cabal itself.
+    + Pandoc.cabal has been changed to pandoc.cabal, because HackageDB
+      likes the cabal file to have the same name as the tarball.
+    + Expanded and revised the package description in pandoc.cabal.
+      Revised the package synopsis.
+    + The tarball built by 'make tarball' now contains files built from
+      templates (including man pages and shell scripts), so pandoc can
+      be built directly using Cabal tools, without preprocessing.
+    + Executable binaries are now stripped before installing.
+    + Man pages are now generated from markdown sources, using pandoc's
+      man page writer.
+    + Use HTML version of README (instead of RTF) in Mac OS X installer.
+    + Instead of testing for the existence of a pandoc symlink in build-exec,
+      use ln -f.
+
+  * Documentation:
+
+    + Updated README and man pages with information on new features.
+    + Updated INSTALL instructions with some useful clarifications and
+      links.
+    + Updated web content.
+
+  * Added FreeBSD port.
+
+  [ Recai Oktaş ]
+
+  * debian/control:
+
+    + Changed pandoc's Build-Depends to include libghc6-mtl-dev and
+      libghc6-xhtml-dev.  Removed libghc6-html-dev.
+    + Suggest texlive-latex-recommended | tetex-extra instead of
+      tetex-bin.  This brings in fancyvrb and unicode support.
+
+
+## pandoc 0.3 (2007-01-05)
+
+  [ John MacFarlane ]
+
+  * Changes in pandoc options:
+
+    + Allow options to follow or precede arguments.
+    + Changed '--smartypants' to '--smart' and adjusted symbols accordingly.
+    + Added '--strict' option.
+    + Added '-o/--output' option.
+    + Added '--dump-args' and '--ignore-args' options (for use in wrappers).
+    + Modified '-v' and '-h' output to go to STDERR, not STDOUT, and return
+      error conditions.  This is helpful for writing wrappers.
+    + Added copyright message to '-v' output, modeled after FSF messages.
+    + Reformatted usage message so that it doesn't wrap illegibly.
+    + Removed extra blanks after '-h' and '-D' output.
+
+  * Added docbook writer.
+
+  * Added implicit setting of default input and output format based
+    on input and output filename extensions.  These defaults are
+    overridden if explicit input and output formats are specified using
+    '-t', '-f', '-r', or '-w' options.  Documented in pandoc(1) man page
+    and README.
+
+  * Allow ordered list items to begin with (single) letters, as well
+    as numbers.  The list item marker may now be terminated either by
+    '.' or by ')'.  This extension to standard markdown is documented
+    in README.
+
+  * Revised footnote syntax.  (See README for full details.)  The
+    '[^1]' format now standard in markdown extensions is supported,
+    as are inline footnotes with this syntax: `^[My note.]`.
+    The earlier footnote syntax `^(1)` is no longer supported.
+
+  * Improved HTML representation of footnotes.  All footnotes
+    are now auto-numbered and appear in an ordered list at the
+    end of the HTML document.  Since the default appearance is now
+    acceptable, the old footnote styles have been removed from the
+    HTML header.
+
+  * Bug fixes:
+
+    + Fixed a serious bug in the markdown, LaTeX, and RST readers.
+      These readers ran 'runParser' on processed chunks of text to handle
+      embedded block lists in lists and quotation blocks.  But then
+      any changes made to the parser state in these chunks was lost,
+      as the state is local to the parser.  So, for example, footnotes
+      didn't work in quotes or list items.  The fix:  instead of calling
+      runParser on some raw text, use setInput to make it the input, then
+      parse it, then use setInput to restore the input to what it was
+      before.  This is shorter and more elegant, and it fixes the problem.
+    + Fixed bug in notFollowedBy' combinator (adding 'try' before
+      'parser').  Adjusted code that uses this combinator accordingly.
+    + Fixed bug in RTF writer that caused improper indentation on
+      footnotes occurring in indented blocks like lists.
+    + Fixed parsing of metadata in LaTeX reader.  Now the title, author,
+      and date are parsed correctly.  Everything else in the preamble
+      is skipped.
+    + Modified escapedChar in LaTeX reader to allow a `\` at the end of a
+      line to count as escaped whitespace.
+    + Modified LaTeX reader to produce inline links rather than reference
+      links.  Otherwise, links in footnotes aren't handled properly.
+    + Fixed handling of titles in links in Markdown reader, so that
+      embedded quotation marks are now handled properly.
+    + Fixed Markdown reader's handling of embedded brackets in links.
+    + Fixed Markdown reader so that it only parses bracketed material
+      as a reference link if there is actually a corresponding key.
+    + Revised inline code parsing in Markdown reader to conform to
+      markdown standard.  Now any number of `s can begin inline code,
+      which will end with the same number of `s.  For example, to
+      have two backticks as code, write ``` `` ```.  Modified Markdown
+      writer accordingly.
+    + Fixed bug in text-wrapping routine in Markdown and RST writers.
+      Now LineBreaks no longer cause wrapping problems.
+    + Supported hexadecimal numerical entity references as well as
+      decimal ones.
+    + Fixed bug in Markdown reader's handling of underscores and other
+      inline formatting markers inside reference labels:  for example,
+      in '[A_B]: /url/a_b', the material between underscores was being
+      parsed as emphasized inlines.
+    + Changed Markdown reader's handling of backslash escapes so that
+      only non-alphanumeric characters can be escaped.  Strict mode
+      follows Markdown.pl in only allowing a select group of punctuation
+      characters to be escaped.
+    + Modified HTML reader to skip a newline following a `<br>` tag.
+      Otherwise the newline will be treated as a space at the beginning
+      of the next line.
+
+  * Made handling of code blocks more consistent.  Previously, some
+    readers allowed trailing newlines, while others stripped them.
+    Now, all readers strip trailing newlines in code blocks. Writers
+    insert a newline at the end of code blocks as needed.
+
+  * Modified readers to make spacing at the end of output more consistent.
+
+  * Minor improvements to LaTeX reader:
+
+    + `\thanks` now treated like a footnote.
+    + Simplified parsing of LaTeX command arguments and options.
+      commandArgs now returns a list of arguments OR options (in
+      whatever order they appear).  The brackets are included, and
+      a new stripFirstAndLast function is provided to strip them off
+      when needed.  This fixes a problem in dealing with \newcommand
+      and \newenvironment.
+
+  * Revised RTF writer:
+
+    + Default font is now Helvetica.
+    + An `\f0` is added to each `\pard`, so that font resizing works
+      correctly.
+
+  * Moved handling of "smart typography" from the writers to the Markdown
+    and LaTeX readers.  This allows great simplification of the writers
+    and more accurate smart quotes, dashes, and ellipses.  DocBook can
+    now use `<quote>`.  The '--smart' option now toggles an option in
+    the parser state rather than a writer option.  Several new kinds
+    of inline elements have been added: Quoted, Ellipses, Apostrophe,
+    EmDash, EnDash.
+
+  * Changes in HTML writer:
+
+    + Include title block in header even when title is null.
+    + Made javascript obfuscation of emails even more obfuscatory,
+      by combining it with entity obfuscation.
+
+  * Changed default ASCIIMathML text color to black.
+
+  * Test suite:
+
+    + Added --strip-trailing-cr option to diff in runtests.pl, for
+      compatibility with Windows.
+    + Added regression tests with footnotes in quote blocks and lists.
+
+  * Makefile changes:
+
+    + osx-pkg target creates a Mac OS X package (directory). New osx
+      directory contains files needed for construction of the package.
+    + osx-dmg target creates a compressed disk image containing the package.
+    + win-pkg target creates Windows binary package.
+    + tarball target creates distribution source tarball.
+    + website target generates pandoc's website automatically, including
+      demos.  New 'web' directory contains files needed for construction
+      of the website (which will be created as the 'pandoc' subdirectory
+      of 'web').
+    + Makefile checks to see if we're running Windows/Cygwin; if so,
+      a '.exe' extension is added to each executable in EXECS.
+
+  * Removed all wrappers except markdown2pdf and html2markdown.
+
+  * Added new wrapper hsmarkdown, to be used as a drop-in replacement
+    for Markdown.pl.  hsmarkdown calls pandoc with the '--strict'
+    option and disables other options.
+
+  * Added code to html2markdown that tries to determine the character
+    encoding of an HTML file, by parsing the "Content-type" meta tag.
+
+    + If the encoding can't be determined, then if the content is local,
+      the local encoding is used; if it comes from a URL, UTF-8 is used
+      by default.
+    + If input is from STDIN, don't try to determine character encoding.
+    + Encoding can be specified explicitly using '-e' option.
+
+  * Improved warning messages in wrappers:
+
+    + Print warning if iconv not available
+    + More user-friendly error messages in markdown2pdf, when
+      pdflatex fails.
+
+  * Code cleanup:
+
+    + Renamed 'Text/Pandoc/HtmlEntities' module to
+      'Text/Pandoc/Entities'. Also changed function names so as
+      not to be HTML-specific.
+    + Refactored SGML string escaping functions from HTML and Docbook
+      writers into Text/Pandoc/Shared.  (escapeSGML, stringToSGML)
+    + Removed 'BlockQuoteContext' from ParserContext, as it isn't
+      used anywhere.
+    + Removed splitBySpace and replaced it with a general, polymorphic
+      splitBy function.
+    + Refactored LaTeX reader for clarity (added isArg function).
+    + Converted some CR's to LF's in src/ui/default/print.css.
+    + Added license text to top of source files.
+    + Added module data for haddock to source files.
+    + Reformatted code for consistency.
+
+  * Rewrote documentation and man pages.  Split README into INSTALL
+    and README.
+
+  * Split LICENSE into COPYING and COPYRIGHT.
+
+  * Removed TODO, since we now maintain ToDo on the wiki.
+
+  * Made COPYRIGHT in top level a symlink to debian/copyright, to avoid
+    duplication.
+
+  [ Recai Oktaş ]
+
+  * Revamped build process to conform to debian standards and created
+    a proper debian package.  Closes: #391666.
+
+  * Modified build process to support GHC 6.6.
+
+    + The package can still be compiled using GHC 6.4.2, though because
+      of dependencies the "make deb" target works only with GHC 6.6+.
+    + The script 'cabalize' is used to create an appropriate
+      'Pandoc.cabal' from 'Pandoc.cabal.in', depending on the GHC and
+      Cabal versions.
+
+  * Refactored template processing (fillTemplates.pl).
+
+  * Modified wrapper scripts to make them more robust and portable.
+    To avoid code duplication and ensure consistency, wrappers are
+    generated via a templating system from templates in src/wrappers.
+
+    + Wrappers now accept multiple filenames, when appropriate.
+    + Spaces and tabs allowed in filenames.
+    + getopts shell builtin is used for portable option parsing.
+    + Improved html2markdown's web grabber code, making it more robust,
+      configurable and verbose.  Added '-e', '-g' options.
+
+
+## pandoc 0.2 (2006-08-14)
+
+  * Fixed unicode/utf-8 translation
+
+## pandoc 0.1 (2006-08-14)
+
+  * Initial creation of debian package
+
diff --git a/citeproc/biblatex-localization/UKenglish.lbx.strings b/citeproc/biblatex-localization/UKenglish.lbx.strings
new file mode 100644
--- /dev/null
+++ b/citeproc/biblatex-localization/UKenglish.lbx.strings
diff --git a/citeproc/biblatex-localization/USenglish.lbx.strings b/citeproc/biblatex-localization/USenglish.lbx.strings
new file mode 100644
--- /dev/null
+++ b/citeproc/biblatex-localization/USenglish.lbx.strings
diff --git a/citeproc/biblatex-localization/american.lbx.strings b/citeproc/biblatex-localization/american.lbx.strings
new file mode 100644
--- /dev/null
+++ b/citeproc/biblatex-localization/american.lbx.strings
diff --git a/citeproc/biblatex-localization/australian.lbx.strings b/citeproc/biblatex-localization/australian.lbx.strings
new file mode 100644
--- /dev/null
+++ b/citeproc/biblatex-localization/australian.lbx.strings
diff --git a/citeproc/biblatex-localization/austrian.lbx.strings b/citeproc/biblatex-localization/austrian.lbx.strings
new file mode 100644
--- /dev/null
+++ b/citeproc/biblatex-localization/austrian.lbx.strings
@@ -0,0 +1,1 @@
+january|J\"anner|J\"an\adddot
diff --git a/citeproc/biblatex-localization/brazil.lbx.strings b/citeproc/biblatex-localization/brazil.lbx.strings
new file mode 100644
--- /dev/null
+++ b/citeproc/biblatex-localization/brazil.lbx.strings
diff --git a/citeproc/biblatex-localization/brazilian.lbx.strings b/citeproc/biblatex-localization/brazilian.lbx.strings
new file mode 100644
--- /dev/null
+++ b/citeproc/biblatex-localization/brazilian.lbx.strings
@@ -0,0 +1,233 @@
+bibliography|Bibliografia|Bibliografia
+references|Refer\^encias|Refer\^encias
+shorthands|Lista de abreviaturas|Abreviaturas
+editor|editor|ed\adddot
+editors|editores|ed\adddot
+compiler|compilador|comp\adddot
+compilers|compiladores|comp\adddot
+redactor|redator|red\adddot
+redactors|redatores|red\adddot
+reviser|revisor|rev\adddot
+revisers|revisores|rev\adddot
+founder|fundador|fund\adddot
+founders|fundadores|fund\adddot
+continuator|continuador|cont\adddot
+continuators|continuadores|cont\adddot
+collaborator|colaborador|colab\adddot
+collaborators|colaboradores|colab\adddot
+translator|tradutor|trad\adddot
+translators|tradutores|trad\adddot
+commentator|coment\'ario|coment\adddot
+commentators|coment\'ario|coment\adddot
+annotator|notas|notas
+annotators|notas|notas
+commentary|coment\'ario|coment\adddot
+annotations|notas|notas
+foreword|pref\'acio|pref\adddot
+afterword|posf\'acio|posf\adddot
+organizer|organizador|org\adddot
+organizers|organizadores|org\adddot
+byauthor|por|por
+byeditor|editado por|ed\adddotspace por
+bycompiler|compilado por|comp\adddotspace por
+byredactor|redigido por|red\adddotspace por
+byreviser|revisado por|rev\adddotspace por
+byreviewer|resenhado por|res\adddotspace por
+byfounder|fundado por|fund\adddotspace por
+bycontinuator|continuado por|cont\adddotspace por
+bytranslator|traduzido \lbx@lfromlang\ por|trad\adddot\ \lbx@sfromlang\ por
+bycommentator|comentado por|coment\adddot\ por
+byannotator|anotado por|anot\adddot\ por
+byorganizer|organizado por|org\adddotspace por
+withcommentator|com coment\'ario de|com coment\adddot\ de
+withannotator|com notas de|com notas de
+withforeword|com pref\'acio de|com pref\adddot\ de
+withafterword|com posf\'acio de|com posf\adddot\ de
+and|e|e
+andothers|et\addabbrvspace al\adddot|et\addabbrvspace al\adddot
+andmore|et\addabbrvspace al\adddot|et\addabbrvspace al\adddot
+volume|volume|vol\adddot
+volumes|volumes|vol\adddot
+involumes|em|em
+jourvol|volume|v\adddot
+jourser|s\'erie|s\'er\adddot
+book|livro|livro
+part|parte|parte
+issue|n\'umero|n\'um\adddot
+newseries|nova s\'erie|nova s\'er\adddot
+oldseries|s\'erie antiga|s\'er\adddot\ antiga
+reprint|reimpress\~ao|reimpr\adddot
+reprintof|reimpress\~ao de|reimpr\adddotspace de
+reprintas|reimpresso como|reimpr\adddotspace como
+reprintfrom|reimpresso de|reimpr\adddotspace de
+translationas|traduzido como|trad\adddotspace como
+translationfrom|traduzido do|trad\adddotspace do
+reviewof|resenha de|res\adddotspace de
+origpubas|originalmente publicado como|orig\adddotspace pub\adddotspace como
+origpubin|originalmente publicado em|orig\adddotspace pub\adddotspace em
+astitle|como|como
+bypublisher|por|por
+nodate|sem\space data|s\adddot d\adddot
+page|p\'agina|p\adddot
+pages|p\'aginas|pp\adddot
+column|coluna|col\adddot
+columns|colunas|col\adddot
+line|linha|l\adddot
+lines|linhas|ll\adddot
+verse|verso|v\adddot
+verses|versos|vv\adddot
+paragraph|par\'agrafo|par\adddot
+paragraphs|par\'agrafos|par\adddot
+pagetotal|p\'agina|p\adddot
+pagetotals|p\'aginas|pp\adddot
+columntotal|coluna|col\adddot
+columntotals|colunas|col\adddot
+linetotal|linha|l\adddot
+linetotals|linhas|ll\adddot
+versetotal|verso|v\adddot
+versetotals|versos|vv\adddot
+paragraphtotal|par\'agrafo|par\adddot
+paragraphtotals|par\'agrafos|par\adddot
+in|em|em
+inseries|em|em
+ofseries|de|de
+number|n\'umero|n\adddot
+chapter|cap\'\i tulo|cap\adddot
+bathesis|trabalho de conclus\~ao|trab\adddotspace de conc\adddot
+phdthesis|tese de doutorado|tese de dout\adddot
+candthesis||
+resreport|relat\'orio de pesquisa|rel\adddotspace de pesq\adddot
+techreport|relat\'orio t\'ecnico|rel\adddotspace t\'ecn\adddot
+software|software|software
+datacd|CD-ROM|CD-ROM
+audiocd|CD de \'audio|CD de \'audio
+version|vers\~ao|vers\~ao
+urlfrom|dispon\'ivel em|disp\adddotspace em
+urlseen|acesso em|acesso em
+submitted|submetido|submetido
+inpress|no prelo|no prelo
+prepublished|pr\'e-publicado|pr\'e-publicado
+citedas|doravante citado como|doravante citado como
+thiscite|especialmente|esp\adddot
+seenote|ver nota|ver nota
+quotedin|apud|apud
+idem|idem|idem
+idemsm|idem|idem
+idemsf|eadem|eadem
+idemsn|idem|idem
+idempm|eidem|eidem
+idempf|eaedem|eaedem
+idempn|eadem|eadem
+idempp|eidem|eidem
+ibidem|ibidem|ibid\adddot
+opcit|op\adddotspace cit\adddot|op\adddotspace cit\adddot
+loccit|loc\adddotspace cit\adddot|loc\adddotspace cit\adddot
+confer|cf\adddot|cf\adddot
+sequens|sq\adddot|sq\adddot
+sequentes|sqq\adddot|sqq\adddot
+passim|passim|passim
+see|ver|ver
+seealso|ver tamb\'em|ver tamb\'em
+backrefpage|ver p\'agina|ver p\adddot
+backrefpages|ver p\'aginas|ver pp\adddot
+january|janeiro|jan\adddot
+february|fevereiro|fev\adddot
+april|abril|abr\adddot
+may|maio|mai\adddot
+june|junho|jun\adddot
+july|julho|jul\adddot
+august|agosto|ago\adddot
+september|setembro|set\adddot
+october|outubro|out\adddot
+november|novembro|nov\adddot
+december|dezembro|dez\adddot
+langamerican|ingl\^es|ingl\^es
+langbulgarian|b\'ulgaro|b\'ulgaro
+langcatalan|catal\~ao|catal\~ao
+langcroatian|croata|croata
+langczech|tcheco|tcheco
+langdanish|dinamarqu\^es|dinamarqu\^es
+langenglish|ingl\^es|ingl\^es
+langfinnish|finland\^es|finland\^es
+langestonian|estoniano|estoniano
+langfrench|franc\^es|franc\^es
+langgalician|galego|galego
+langgerman|alem\~ao|alem\~ao
+langgreek|grego|grego
+langhungarian|h\'ungaro|h\'ungaro
+langitalian|italiano|italiano
+langjapanese|japon\^es|japon\^es
+langlatin|latim|latim
+langlatvian|let\~ao|let\~ao
+langlithuanian|lituano|lituano
+langnorwegian|noruegu\^es|noruegu\^es
+langpolish|polon\^es|polon\^es
+langrussian|russo|russo
+langserbian|s\'ervio|s\'ervio
+langslovak|eslovaco|eslovaco
+langslovene|esloveno|esloveno
+langspanish|espanhol|espanhol
+langswedish|sueco|sueco
+langturkish|turco|turco
+langukrainian|ucraniano|ucraniano
+fromamerican|do ingl\^es|do ingl\^es
+frombulgarian|do b\'ulgaro|do b\'ulgaro
+fromcatalan|do catal\~ao|do catal\~ao
+fromcroatian|do croata|do croata
+fromczech|do tcheco|do tcheco
+fromdanish|do dinamarqu\^es|do dinamarqu\^es
+fromenglish|do ingl\^es|do ingl\^es
+fromestonian|do estoniano|do estoniano
+fromfinnish|do finland\^es|do finland\^es
+fromfrench|do franc\^es|do franc\^es
+fromgalician|do galego|do galego
+fromgerman|do alem\~ao|do alem\~ao
+fromgreek|do grego|do grego
+fromhungarian|do h\'ungaro|do h\'ungaro
+fromitalian|do italiano|do italiano
+fromjapanese|do japon\^es|do japon\^es
+fromlatin|do latim|do latim
+fromlatvian|do let\~ao|do let\~ao
+fromlithuanian|do lituano|do lituano
+fromnorwegian|do noruegu\^es|do noruegu\^es
+frompolish|do polon\^es|do polon\^es
+fromrussian|do russo|do russo
+fromserbian|do s\'ervio|do s\'ervio
+fromslovak|do eslovaco|do eslovaco
+fromslovene|do esloveno|do esloveno
+fromspanish|do espanhol|do espanhol
+fromswedish|do sueco|do sueco
+fromturkish|do turco|do turco
+fromukrainian|do ucraniano|do ucraniano
+countryde|Alemanha|DE
+countryeu|Uni\~ao Europeia|EU
+countryep|Uni\~ao Europeia|EP
+countryuk|Reino Unido|GB
+countryus|Estados Unidos|US
+patent|patente|pat\adddot
+patentde|patente alem\~a|pat\adddot\ alem\~a
+patenteu|patente europeia|pat\adddot\ europeia
+patentfr|patente francesa|pat\adddot\ francesa
+patentuk|patente brit\^anica|pat\adddot\ brit\^anica
+patentus|patente americana|pat\adddot\ americana
+patreq|pedido de patente|ped\adddot\ de pat\adddot
+patreqde|pedido de patente alem\~a|ped\adddot\ de pat\adddot\ alem\~a
+patreqeu|pedido de patente europeia|ped\adddot\ de pat\adddot\ europeia
+patreqfr|pedido de patente francesa|ped\adddot\ de pat\adddot\ francesa
+patrequk|pedido de patente brit\^anica|ped\adddot\ de pat\adddot\ brit\^anica
+patrequs|pedido de patente americana|ped\adddot\ de pat\adddot\ americana
+file|arquivo|arquivo
+library|biblioteca|biblioteca
+abstract|resumo|resumo
+annotation|notas|notas
+commonera|Era Comum|EC
+beforecommonera|antes da Era Comum|AEC
+annodomini|depois de Cristo|d\adddot C\adddot
+beforechrist|antes de Cristo|a\adddot C\adddot
+circa|circa|ca\adddot
+spring|primavera|primavera
+summer|ver\~ao|ver\~ao
+autumn|outono|outono
+winter|inverno|inverno
+am|AM|AM
+pm|PM|PM
diff --git a/citeproc/biblatex-localization/british.lbx.strings b/citeproc/biblatex-localization/british.lbx.strings
new file mode 100644
--- /dev/null
+++ b/citeproc/biblatex-localization/british.lbx.strings
@@ -0,0 +1,3 @@
+organizer|organiser|org\adddot
+organizers|organisers|orgs\adddot
+byorganizer|organised by|org\adddotspace by
diff --git a/citeproc/biblatex-localization/bulgarian.lbx.strings b/citeproc/biblatex-localization/bulgarian.lbx.strings
new file mode 100644
--- /dev/null
+++ b/citeproc/biblatex-localization/bulgarian.lbx.strings
@@ -0,0 +1,28 @@
+bibliography|Библиография|Библиография
+references|Литература|Литература
+shorthands|Списък на съкращенията|Съкращения
+editor|редактор|ред\adddot
+editors|редактори|ред\adddot
+compiler|съставител|съст\adddot
+compilers|съставители|съст\adddot
+redactor|редактор|ред\adddot
+redactors|редактори|ред\adddot
+reviser|коректор|кор\adddotspace кор\adddot
+revisers|коректор|кор\adddotspace кор\adddot
+founder|основател|осн\adddot
+founders|основатели|осн\adddot
+continuator|продължител|прод\adddot
+continuators|продължител|прод\adddot
+collaborator|участник|участ\adddot
+collaborators|участници|участ\adddot
+translator|преводач|прев\adddot
+translators|преводачи|прев\adddot
+commentator|коментатор|комент\adddot
+commentators|коментатори|комент\adddot
+annotator|бележки|бел\adddot
+annotators|бележки|бел\adddot
+commentary|комментар|комент\adddot
+annotations|бележки|бел\adddot
+introduction|уводна статия|ув\adddotspace ст\adddot
+foreword|предговор|предг\adddot
+afterword|послеслов|послесл\adddot
diff --git a/citeproc/biblatex-localization/canadian.lbx.strings b/citeproc/biblatex-localization/canadian.lbx.strings
new file mode 100644
--- /dev/null
+++ b/citeproc/biblatex-localization/canadian.lbx.strings
diff --git a/citeproc/biblatex-localization/catalan.lbx.strings b/citeproc/biblatex-localization/catalan.lbx.strings
new file mode 100644
--- /dev/null
+++ b/citeproc/biblatex-localization/catalan.lbx.strings
@@ -0,0 +1,158 @@
+bibliography|Bibliografia|Bibliografia
+references|Refer\`encies|Refer\`encies
+shorthands|Llista d'abreviatures|Abreviatures
+editor|editor|ed\adddot
+editors|editors|ed\adddot
+compiler|compilador|comp\adddot
+compilers|compiladors|comp\adddot
+redactor|redactor|red\adddot
+redactors|redactors|red\adddot
+reviser|revisor|rev\adddot
+revisers|revisors|rev\adddot
+founder|fundador|fund\adddot
+founders|fundadors|fund\adddot
+continuator|continuador|cont\adddot
+continuators|continuadors|cont\adddot
+collaborator|co\l.laborador|co\l.l\adddot
+collaborators|co\l.laboradors|co\l.l\adddot
+translator|traductor|trad\adddot
+translators|traductors|trad\adddot
+commentator|comentarista|com\adddot
+commentators|comentaristes|com\adddot
+annotator|anotador|anot\adddot
+annotators|anotadors|anot\adddot
+commentary|comentari|com\adddot
+annotations|notes|n\adddot
+introduction|introducci\'o|intr\adddot
+foreword|pr\`oleg|pr\`ol\adddot
+editortr|editor i traductor|ed\adddotspace i trad\adddot
+editorstr|editors i traductors|ed\adddotspace i trad\adddot
+editorco|editor i comentarista|ed\adddotspace i com\adddot
+editorsco|editors i comentaristes|ed\adddotspace i com\adddot
+editoran|editor i anotador|ed\adddotspace i anot\adddot
+editorsan|editors i anotadors|ed\adddotspace i anot\adddot
+organizer|organitzador|org\adddot
+organizers|organitzadors|org\adddot
+byorganizer|organitzat per|org\adddotspace per
+byauthor|per|per
+byeditor|edici\'o a cura \smartof|ed\adddotspace\smartof
+bycompiler|compilaci\'o a cura \smartof|comp\adddotspace\smartof
+byredactor|redacci\'o a cura \smartof|red\adddotspace\smartof
+byreviser|revisi\'o a cura \smartof|rev\adddotspace\smartof
+byreviewer|ressenya a cura \smartof|ress\adddotspace\smartof
+byfounder|fundat per|fund\adddotspace per
+bycontinuator|continuat per|cont\adddotspace per
+bycollaborator|amb la co\l.laboraci\'o \smartof|amb la co\l.l\adddotspace\smartof
+bytranslator|traducci\'o \lbx@fromlang\ a cura \smartof|trad\adddotspace\lbx@fromlang\ \smartof
+bycommentator|comentari a cura \smartof|com\adddotspace\smartof
+byannotator|notes a cura \smartof|n\adddotspace\smartof
+withcommentator|amb un comentari a cura \smartof|amb un com\adddotspace\smartof
+withannotator|amb notes a cura \smartof|amb n\adddotspace\smartof
+withintroduction|amb una introducci\'o a cura \smartof|amb una intr\adddotspace\smartof
+withforeword|amb un pr\`oleg a cura \smartof|amb un pr\`ol\adddotspace\smartof
+and|i|i
+andothers|et al\adddot|et al\adddot
+andmore|i m\'es|i m\'es
+volume|volum|vol\adddot
+volumes|volums|vol\adddot
+involumes|en|en
+jourvol|volum|vol\adddot
+jourser|s\`erie|s\`er\adddot
+book|llibre|llib\adddot
+part|part|part
+issue|n\'umero|n\'um\adddot
+newseries|s\`erie nova|s\`erie nova
+oldseries|s\`erie antiga|s\`erie ant\adddot
+edition|edici\'o|ed\adddot
+reprint|reimpressi\'o|reimpr\adddot
+reprintof|reimpressi\'o \smartof|reimpr\adddotspace\smartof
+reprintas|reimpr\`es com|reimpr\adddotspace com
+reprintfrom|reimpr\`es \smartof|reimpr\adddotspace\smartof
+reviewof|ressenya \smartof|ress\adddotspace\smartof
+translationof|traducci\'o \smartof|trad\adddotspace\smartof
+origpubas|publicat origin\`ariament com|pub\adddotspace orig\adddotspace com
+origpubin|publicat origin\`ariament el|pub\adddotspace orig\adddotspace el
+astitle|com|com
+bypublisher|per|per
+page|p\`agina|p\`ag\adddot
+pages|p\`agines|p\`ag\adddot
+column|columna|col\adddot
+columns|columnes|cols\adddot
+nodate|sine data|s\adddotspace d\adddot
+verse|vers|v\adddot
+verses|versos|v\adddot
+section|apartat|\S
+sections|apartats|\S
+paragraph|par\`agraf|\P
+paragraphs|par\`agrafs|\P
+pagetotal|p\`agina|p\`ag\adddot
+pagetotals|p\`agines|p\`ag\adddot
+columntotal|columna|col\adddot
+columntotals|columnes|col\adddot
+versetotal|vers|v\adddot
+versetotals|versos|v\adddot
+sectiontotal|secci\'o|\S
+sectiontotals|seccions|\S
+paragraphtotal|par\`agrafs|\P
+paragraphtotals|par\`agrafs|\P
+in|a|a
+inseries|a|a
+ofseries|\smartof|\smartof
+number|n\'umero|n\'um\adddot
+bathesis|treball final de grau|treb\adddotspace fin\adddotspace de gr\adddot
+mathesis|treball final de m\`aster|treb\adddotspace fin\adddotspace de m\`ast\adddot
+phdthesis|tesi doctoral|tesi doct\adddot
+candthesis|tesi de candidatura|tesi de cand\adddot
+resreport|informe de recerca|inf\adddotspace de rec\adddot
+techreport|informe t\`ecnic|inf\adddotspace t\`ec\adddot
+software|programari|prog\adddot
+datacd|CD de dades|CD de dades
+audiocd|CD d'\`audio|CD d'\`audio
+version|versi\'o|vers\adddot
+urlfrom|disponible a|disp\adddotspace a
+urlseen|consultat|cons\adddot
+inpreparation|en preparaci\'o|en prep\adddot
+inpress|a impremta|a impr\adddot
+prepublished|pre-publicat|pre-publicat
+submitted|enviat a publicar|env\adddotspace a pub\adddot
+forthcoming|properament|prop\adddot
+citedas|d'ara endavant citat com|d'ara end\adddotspace cit\adddotspace com
+thiscite|concretament|concr\adddot
+seenote|vegeu la nota|v\adddotspace la n\adddot
+quotedin|citat a|cit\adddotspace a
+opcit|\`op\adddotspace cit\adddot|\`op\adddotspace cit\adddot
+loccit|loc\adddotspace cit\adddot|loc\adddotspace cit\adddot
+confer|cf\adddot|cf\adddot
+sequens|seq\adddot|seq\adddot
+sequentes|et seq\adddot|et seq\adddot
+passim|p\`assim|p\`assim
+see|vegeu|v\adddot
+seealso|vegeu tamb\'e|v\adddotspace tamb\'e
+backrefpage|vegeu la p\`agina|v\adddotspace la p\`ag\adddot
+backrefpages|vegeu les p\`agines|v\adddotspace les p\`ag\adddot
+january|gener|gen\adddot
+february|febrer|febr\adddot
+april|abril|abr\adddot
+may|maig|maig
+june|juny|juny
+july|juliol|jul\adddot
+august|agost|ag\adddot
+september|setembre|set\adddot
+october|octubre|oct\adddot
+november|novembre|nov\adddot
+december|desembre|des\adddot
+langamerican|angl\`es americ\`a|ang\adddotspace amer\adddot
+langbrazilian|portugu\`es brasiler|port\adddotspace bras\adddot
+langbulgarian|b\'ulgar|b\'ulg\adddot
+langcatalan|catal\`a|cat\adddot
+langczech|txec|txec
+langcroatian|croat|croat
+langdanish|dan\`es|dan\adddot
+langdutch|neerland\`es|neerl\adddot
+langenglish|angl\`es|ang\adddot
+langestonian|estoni\`a|eston\adddot
+langfinnish|fin\`es|fin\adddot
+langfrench|franc\`es|fr\adddot
+langgalician|gallec|gal\adddot
+langgerman|alemany|al\adddot
+langgreek|grec|grec
diff --git a/citeproc/biblatex-localization/croatian.lbx.strings b/citeproc/biblatex-localization/croatian.lbx.strings
new file mode 100644
--- /dev/null
+++ b/citeproc/biblatex-localization/croatian.lbx.strings
@@ -0,0 +1,214 @@
+bibliography|Bibliografija|Bibliografija
+references|Literatura|Literatura
+shorthands|Popis kratica|Kratice
+editor|urednik|ur\adddot
+editors|urednici|ur\adddot
+redactor|redaktor|redaktor
+redactors|redaktori|redaktori
+reviser|korektor|korektor
+revisers|korektori|korektori
+collaborator|suradnik|sur\adddot
+collaborators|suradnici|sur\adddot
+translator|prijevod|prev\adddot
+translators|prijevod|prev\adddot
+commentator|komentator|komentator
+commentators|komentatori|komentatori
+commentary|komentar|komentar
+introduction|uvod|uvod
+foreword|predgovor|predgovor
+afterword|pogovor|pogovor
+editortr|prijevod i obrada|ur\adddotspace i prev\adddot
+editorstr|prijevod i obrada|ur\adddotspace i prev\adddot
+organizer|organizacija|organizacija
+organizers|organizacija|organizacija
+byorganizer|organizacija|organizacija
+byauthor|autor|autor
+byeditor|obrada|ur\adddot
+byredactor|redaktura|red\adddot
+byreviser|korektura|kor\adddot
+byreviewer|recenzija|recenzija
+bycontinuator|nastavio|nastavio
+bycollaborator|u suradnji s|u sur\adddotspace s
+bycommentator|komentari|komentari
+withcommentator|komentari|komentari
+withintroduction|uvod|uvod
+withforeword|predgovor|predgovor
+withafterword|pogovor|pogovor
+and|i|i
+andothers|i drugi|i dr\adddot
+andmore|i drugi|i dr\adddot
+volume|sv\adddot|sv\adddot
+volumes|sv\adddot|sv\adddot
+involumes|u|u
+jourvol|sv\adddot|sv\adddot
+jourser|serija|serija
+book|knjiga|knj\adddot
+part|dio|dio
+issue|izd\adddot|izd\adddot
+newseries|nova serija|nova serija
+oldseries|stara serija|stara serija
+edition|izdanje|izdanje
+reprint|pretisak|pretisak
+reprintof|pretisak|pretisak
+reprintas|iznova otisnuto kao|iznova otisnuto kao
+reprintfrom|iznova otisnut|iznova otisnut
+translationof|prijevod|prijevod
+translationas|prev\adddotspace kao|prev\adddotspace kao
+translationfrom|prijevod|prijevod
+reviewof|osvrt na|osvrt na
+origpubas|izvorno obj\adddotspace kao|izv\adddotspace obj\adddotspace kao
+origpubin|izvorno obj\adddot|izv\adddotspace obj\adddot
+astitle|kao|kao
+bypublisher||
+nodate|bez datuma|bez datuma
+page|stranica|str\adddot
+pages|stranice|str\adddot
+column|stupac|stupac
+columns|stupci|stupci
+line|linija|l\adddot
+lines|linije|ll\adddot
+verse|stih|stih
+verses|stihovi|stihovi
+section|odjeljak|\S
+sections|odjeljci|\S\S
+paragraph|stavak|st\adddot
+paragraphs|stavci|st\adddot
+pagetotal|str\adddot|str\adddot
+pagetotals|str\adddot|str\adddot
+columntotal|stupac|stupac
+columntotals|stupaca|stupaca
+linetotal|linija|lin\adddot
+linetotals|linija|lin\adddot
+versetotal|stih|st\adddot
+versetotals|stihova|st\adddot
+sectiontotal|odjeljak|odj\adddot
+sectiontotals|odjeljaka|odj\adddot
+paragraphtotal|stavak|st\adddot
+paragraphtotals|stavaka|st\adddot
+in||
+inseries|u seriji|u seriji
+ofseries|iz serije|iz serije
+number|broj|br\adddot
+chapter|poglavlje|pogl\adddot
+bathesis|diplomski rad|dipl\adddotspace rad
+mathesis|magistarski rad|mag\adddotspace rad
+phdthesis|doktorska disertacija|disertacija
+software|softver|softver
+datacd|CD-ROM|CD-ROM
+audiocd|audio CD|audio CD
+version|verzija|verzija
+url|adresa|adresa
+urlfrom|dostupno na|dost\adddotspace na
+urlseen|pogledano|pogledano
+inpreparation|u pripremi|u pripremi
+submitted|predan|predan
+inpress|u tisku|u tisku
+prepublished|pred objavom|pred obj\adddot
+citedas|dalje citirano kao|dalje citirano kao
+thiscite|napose|napose
+quotedin|citirano u|citirano u
+idem|idem|idem
+idemsm|idem|idem
+idemsf|eadem|eadem
+idemsn|idem|idem
+idempm|eidem|eidem
+idempf|eaedem|eaedem
+idempn|eadem|eadem
+idempp|eidem|eidem
+ibidem|ibidem|ibid\adddot
+opcit|op\adddotspace cit\adddot|op\adddotspace cit\adddot
+loccit|loc\adddotspace cit\adddot|loc\adddotspace cit\adddot
+confer|usporedi|usp\adddot
+sequens|sq\adddot|sq\adddot
+sequentes|sqq\adddot|sqq\adddot
+passim|passim|pass\adddot
+see|vidi|v\adddot
+seealso|pogledaj i|pogl\adddotspace i
+backrefpage|citirano na stranci|cit\adddotspace na str\adddot
+backrefpages|cited on pages|cit\adddotspace na str\adddot
+april|travanj|travanj
+may|svibanj|svibanj
+june|lipanj|lipanj
+july|srpanj|srpanj
+august|kolovoz|kolovoz
+september|rujan|rujan
+october|listopad|listopad
+november|studeni|studeni
+december|prosinac|prosinac
+dateapril|travnja|travnja
+datemay|svibnja|svibnja
+datejune|lipnja|lipnja
+datejuly|srpnja|srpnja
+dateaugust|kolovoza|kolovoza
+dateseptember|rujna|rujna
+dateoctober|listopada|listopada
+datenovember|studenoga|studenoga
+datedecember|prosinca|prosinca
+langamerican|engleski|engleski
+langbrazilian|portugalski|portugalski
+langbulgarian|bugarski|bugarski
+langcatalan|katalonski|katalonski
+langcroatian|hrvatski|hrvatski
+langdanish|danski|danski
+langdutch|nizozemski|nizozemski
+langenglish|engleski|engleski
+langestonian|estonski|estonski
+langfinnish|finski|finski
+langfrench|francuski|francuski
+langgalician|galicijski|galicijski
+langhungarian|ma\dj arski|ma\dj arski
+langitalian|talijanski|talijanski
+langjapanese|japanski|japanski
+langlatin|latinski|latinski
+langlatvian|letonski|letonski
+langpolish|poljski|poljski
+langportuguese|portugalski|portugalski
+langrussian|ruski|ruski
+langslovene|slovenski|slovenski
+langukrainian|ukrajinski|ukrajinski
+fromamerican|s engleskog|s engleskog
+frombrazilian|s portugalskog|s portugalskog
+frombulgarian|s bugarskog|s bugarskog
+fromcatalan|s katalonskog|s katalonskog
+fromcroatian|s hrvatskog|s hrvatskog
+fromdanish|s danskog|s danskog
+fromdutch|s nizozemskog|s nizozemskog
+fromenglish|s engleskog|s engleskog
+fromestonian|s estonskog|s estonskog
+fromfinnish|s finskog|s finskog
+fromfrench|s francuskog|s francuskog
+fromgalician|s galicijskog|s galicijskog
+fromhungarian|s ma\dj arskog|s ma\dj arskog
+fromitalian|s talijanskog|s talijanskog
+fromjapanese|s japanskog|s japanskog
+fromlatin|s latinskog|s latinskog
+fromlatvian|s letonskog|s letonskog
+frompolish|s poljskog|s poljskog
+fromportuguese|s portugalskog|s portugalskog
+fromrussian|s ruskog|s ruskog
+fromslovene|sa slovenskog|sa slovenskog
+fromukrainian|s ukrajinskog|s ukrajinskog
+countryeu|Europska unija|EU
+countryep|Europska unija|EP
+countryfr|Francuska|FR
+countryuk|Velika Britanija|GB
+patent|patent|pat\adddot
+patenteu|europski patent|europski pat\adddot
+patentfr|francuski patent|francuski pat\adddot
+patentuk|britanski patent|britanski pat\adddot
+patentus|US patent|US pat\adddot
+patreq|patentni zahtjev|pat\adddot\ zahtjev
+patreqeu|europski patentni zahtjev|EU pat\adddotspace zahtjev
+patrequs|US patentni zahtjev|US pat\adddot\ zahtjev
+file|datoteka|datoteka
+library|biblioteka|biblioteka
+commonera|n\adddotspace e\adddot|n\adddotspace e\adddot
+beforecommonera|pr\adddotspace n\adddotspace e\adddot|pr\adddotspace n\adddotspace e\adddot
+annodomini|poslije Krista|p\adddotspace Kr\adddot
+beforechrist|prije Krista|pr\adddotspace Kr\adddot
+circa|oko|cca\adddot
+summer|ljeto|ljeto
+autumn|jesen|jesen
+winter|zima|zima
+am|prije podne|AM
+pm|poslije podne|PM
diff --git a/citeproc/biblatex-localization/czech.lbx.strings b/citeproc/biblatex-localization/czech.lbx.strings
new file mode 100644
--- /dev/null
+++ b/citeproc/biblatex-localization/czech.lbx.strings
@@ -0,0 +1,91 @@
+bibliography|Bibliografie|Bibliografie
+references|Odkazy|Odkazy
+shorthands|Seznam zkratek|Zkratky
+editor|editor|ed\adddot
+compiler|sestavil|sest\adddot
+compilers|sestavili|sest\adddot
+redactor|redaktor|red\adddot
+reviser|korektor|kor\adddot
+founder|zakladatel|zakl\adddot
+annotations|anotace|anot\adddot
+afterword|doslov|dosl\adddot
+byauthor||
+bycompiler|sestaveno|sest\adddot
+withannotator|s\addnbspace anotacemi od|s\addnbspace anot\adddot\ od
+withafterword|s\addnbspace doslovem od|s\addnbspace dosl\adddot\ od
+and|a|a
+andothers|et\addabbrvspace al\adddot|et\addabbrvspace al\adddot
+andmore|et\addabbrvspace al\adddot|et\addabbrvspace al\adddot
+volume|svazek|sv\adddot
+volumes|svazky|sv\adddot
+involumes|in|in
+book|kniha|kniha
+reprint|dotisk|dotisk
+reprintof|dotisk|dotisk
+reprintas|dotisknuto jako|dotisknuto jako
+reprintfrom|dotisknuto z\addnbspace|dotisknuto z\addnbspace
+reviewof|recenze|recenz\adddot
+astitle|jako|jako
+bypublisher||
+page|strana|s\adddot
+pages|strany|s\adddot
+column|sloupec|sl\adddot
+columns|sloupce|sl\adddot
+section|sekce|\S
+sections|sekce|\S\S
+paragraph|odstavec|ods\adddot
+paragraphs|odstavce|ods\adddot
+pagetotal|strana|s\adddot
+pagetotals|strany|s\adddot
+columntotal|sloupec|sl\adddot
+columntotals|sloupce|sl\adddot
+sectiontotal|sekce|\S
+sectiontotals|sekce|\S\S
+paragraphtotal|odstavec|ods\adddot
+paragraphtotals|odstavce|ods\adddot
+in|in|in
+inseries|in|in
+ofseries|z|z
+chapter|kapitola|kap\adddot
+datacd|CD-ROM|CD-ROM
+audiocd|audio CD|audio CD
+version|verze|ver\adddot
+url|URL|URL
+inpress|v\addnbspace tisku|v\addnbspace tisku
+idem|idem|idem
+idemsm|idem|idem
+idemsf|eadem|eadem
+idemsn|idem|idem
+idempm|eidem|eidem
+idempf|eaedem|eaedem
+idempn|eadem|eadem
+idempp|eidem|eidem
+ibidem|ibidem|ibid\adddot
+opcit|op\adddotspace cit\adddot|op\adddotspace cit\adddot
+loccit|loc\adddotspace cit\adddot|loc\adddotspace cit\adddot
+confer|cf\adddot|cf\adddot
+sequens|sq\adddot|sq\adddot
+sequentes|sqq\adddot|sqq\adddot
+passim|passim|pass\adddot
+see|viz|viz
+january|leden|led\adddot
+april|duben|dub\adddot
+august|srpen|srp\adddot
+november|listopad|lis\adddot
+december|prosinec|pros\adddot
+langlatin|latina|lat\adddot
+fromlatin|z\addnbspace latiny|z\addnbspace lat\adddot
+countryfr|Francie|FR
+patent|patent|pat\adddot
+patentus|US patent|US pat\adddot
+file|soubor|soub\adddot
+library|knihovna|knih\adddot
+abstract|abstrakt|abst\adddot
+annotation|anotace|anot\adddot
+annodomini|po Kristu|po Kr\adddot
+circa|cirka|ca\adddot
+spring|jaro|jaro
+autumn|podzim|podzim
+winter|zima|zima
+am|AM|AM
+pm|PM|PM
diff --git a/citeproc/biblatex-localization/danish.lbx.strings b/citeproc/biblatex-localization/danish.lbx.strings
new file mode 100644
--- /dev/null
+++ b/citeproc/biblatex-localization/danish.lbx.strings
@@ -0,0 +1,106 @@
+bibliography|Bibliografi|Bibliografi
+references|Litteraturhenvisninger|Litteratur
+shorthands|Forkortelser|Forkortelser
+editor|redakt\o r|red\adddot
+editors|redakt\o rer|red\adddot
+compiler|kompilator|kompilator
+compilers|kompilatorer|kompilatorer
+redactor|medredakt\o r|medred\adddot
+redactors|medredakt\o rer|medred\adddot
+reviser|revision|rev\adddot
+revisers|revision|rev\adddot
+founder|stifter|stifter
+founders|stiftere|stiftere
+continuator|videref\o rer|videref\adddot
+continuators|videref\o rere|videref\adddot
+collaborator|medarbejder|medarb\adddot
+collaborators|medarbejdere|medarb\adddot
+translator|overs\ae tter|overs\adddot
+translators|overs\ae ttere|overs\adddot
+commentator|kommentator|komm\adddot
+commentators|kommentatorer|komm\adddot
+annotator|kommentator|komm\adddot
+annotators|kommentatorer|komm\adddot
+commentary|kommentar|komm\adddot
+annotations|annoteringer|ann\adddot
+introduction|indledning|indl\adddot
+foreword|forord|forord
+afterword|efterord|efterord
+organizer|organisator|org\adddot
+organizers|organisatorer|org\adddot
+byorganizer|organiseret af|org\adddotspace av
+byauthor|af|af
+byeditor|redigeret af|red\adddotspace af
+bycompiler|kompileret af|komp\adddotspace af
+byredactor|bearbejdet af|bearb\adddotspace af
+byreviser|revideret af|rev\adddotspace af
+byreviewer|bed\o mt af|bed\adddotspace af
+byfounder|stiftet af|stiftet af
+bycontinuator|videref\o rt af|videref\adddotspace af
+bycollaborator|i samarbejde med|i samarb\adddotspace m\adddot
+bycommentator|kommenteret af|komm\adddot\ af
+byannotator|annoteret af|ann\adddot\ af
+withcommentator|med kommentarer af|m\adddotspace komm\adddot\ af
+withannotator|med annoteringer af|m\adddotspace ann\adddot\ af
+withintroduction|med indledning af|m\adddotspace indl\adddot\ af
+withforeword|med forord af|m\adddotspace forord af
+withafterword|med efterord af|m\adddotspace efterord af
+and|og|og
+andothers|med flere|m.fl\adddot
+andmore|med mere|m.m\adddot
+volume|bind|bd\adddot
+volumes|bind|bd\adddot
+involumes|i|i
+jourvol|\aa rgang|\aa rg\adddot
+jourser|r\ae kke|rk\adddot
+book|bog|bog
+part|del|del
+issue|nummer|nr\adddot
+newseries|ny r\ae kke|ny rk\adddot
+oldseries|gammel r\ae kke|gl. rk\adddot
+edition|udgave|udg\adddot
+reprint|genoptryk|genoptr\adddot
+reprintof|genoptryk af|genoptr\adddot\ af
+reprintas|genoptryk under titlen|genoptr\adddot\ under titlen
+reprintfrom|genoptryk fra|genoptr\adddot\ fra
+translationof|overs\ae ttelse af|overs\adddot\ af
+translationas|oversat under titlen|overs\adddotspace\ under titlen
+translationfrom|oversat fra|overs\adddotspace\ fra
+reviewof|bed\o mmelse af|bed\adddotspace af
+origpubas|oprindeligt udgivet som|opr\adddot\ udg\adddot\ som
+origpubin|oprindeligt udgivet i|opr\adddot\ udg\adddot\ i
+astitle|under titlen|under titlen
+bypublisher|af|af
+nodate|uden \aa rstal|u.\aa\adddot
+page|side|s\adddot
+pages|sider|s\adddot
+column|spalte|sp\adddot
+columns|spalter|sp\adddot
+line|linje|l\adddot
+lines|linjer|l\adddot
+verse|vers|v\adddot
+verses|vers|v\adddot
+section|paragraf|par\adddot
+sections|paragraffer|par\adddot
+paragraph|afsnit|afsn\adddot
+paragraphs|afsnit|afsn\adddot
+pagetotal|side|s\adddot
+pagetotals|sider|s\adddot
+columntotal|spalte|sp\adddot
+columntotals|spalter|sp\adddot
+line|linje|l\adddot
+lines|linjer|l\adddot
+verse|vers|v\adddot
+verses|vers|v\adddot
+linetotal|linje|l\adddot
+linetotals|linje|l\adddot
+versetotal|vers|v\adddot
+versetotals|vers|v\adddot
+sectiontotal|paragraf|par\adddot
+sectiontotals|paragraffer|par\adddot
+paragraphtotal|afsnit|afsn\adddot
+paragraphtotals|afsnit|afsn\adddot
+in|i|i
+inseries|i r\ae kken|i rk\adddot
+ofseries|fra r\ae kken|fra rk\adddot
+number|nummer|nr\adddot
diff --git a/citeproc/biblatex-localization/dutch.lbx.strings b/citeproc/biblatex-localization/dutch.lbx.strings
new file mode 100644
--- /dev/null
+++ b/citeproc/biblatex-localization/dutch.lbx.strings
@@ -0,0 +1,23 @@
+bibliography|Bibliografie|Bibliografie
+references|Referenties|Referenties
+shorthands|Lijst van afkortingen|Afkortingen
+editor|redacteur|red\adddot
+editors|redacteurs|red\adddot
+compiler|samensteller|samenst\adddot
+compilers|samenstellers|samenst\adddot
+founder|oprichter|opr\adddot
+founders|oprichters|opr\adddot
+continuator|opvolger|opv\adddot
+continuators|opvolgers|opv\adddot
+redactor|redacteur|red\adddot
+redactors|redacteuren|red\adddot
+reviser|revisor|rev\adddot
+revisers|revisors|rev\adddot
+collaborator|medewerker|med\adddot
+collaborators|medewerkers|med\adddot
+translator|vertaler|vert\adddot
+translators|vertalers|vert\adddot
+commentator|commentator|comm\adddot
+commentators|commentatoren|comm\adddot
+annotator|annotator|annot\adddot
+annotators|annotatoren|annot\adddot
diff --git a/citeproc/biblatex-localization/english.lbx.strings b/citeproc/biblatex-localization/english.lbx.strings
new file mode 100644
--- /dev/null
+++ b/citeproc/biblatex-localization/english.lbx.strings
@@ -0,0 +1,254 @@
+bibliography|Bibliography|Bibliography
+references|References|References
+shorthands|List of Abbreviations|Abbreviations
+editor|editor|ed\adddot
+editors|editors|eds\adddot
+compiler|compiler|comp\adddot
+compilers|compilers|comp\adddot
+redactor|redactor|red\adddot
+redactors|redactors|red\adddot
+reviser|reviser|rev\adddot
+revisers|revisers|rev\adddot
+founder|founder|found\adddot
+founders|founders|found\adddot
+continuator|continued|cont\adddot
+continuators|continued|cont\adddot
+collaborator|collaborator|collab\adddot
+collaborators|collaborators|collab\adddot
+translator|translator|trans\adddot
+translators|translators|trans\adddot
+commentator|commentator|comm\adddot
+commentators|commentators|comm\adddot
+annotator|annotator|annot\adddot
+annotators|annotators|annot\adddot
+commentary|commentary|comm\adddot
+annotations|annotations|annot\adddot
+introduction|introduction|intro\adddot
+foreword|foreword|forew\adddot
+afterword|afterword|afterw\adddot
+organizer|organizer|org\adddot
+organizers|organizers|orgs\adddot
+byorganizer|organized by|org\adddotspace by
+byauthor|by|by
+byeditor|edited by|ed\adddotspace by
+bycompiler|compiled by|comp\adddotspace by
+byredactor|redacted by|red\adddotspace by
+byreviser|revised by|rev\adddotspace by
+byreviewer|reviewed by|rev\adddotspace by
+byfounder|founded by|found\adddotspace by
+bycontinuator|continued by|cont\adddotspace by
+bycollaborator|in collaboration with|in collab\adddotspace with
+bytranslator|translated \lbx@lfromlang\ by|trans\adddot\ \lbx@sfromlang\ by
+bycommentator|commented by|comm\adddot\ by
+byannotator|annotated by|annot\adddot\ by
+withcommentator|with a commentary by|with a comment\adddot\ by
+withannotator|with annotations by|with annots\adddot\ by
+withintroduction|with an introduction by|with an intro\adddot\ by
+withforeword|with a foreword by|with a forew\adddot\ by
+withafterword|with an afterword by|with an afterw\adddot\ by
+and|and|and
+andothers|et\addabbrvspace al\adddot|et\addabbrvspace al\adddot
+andmore|et\addabbrvspace al\adddot|et\addabbrvspace al\adddot
+volume|volume|vol\adddot
+volumes|volumes|vols\adddot
+involumes|in|in
+jourvol|volume|vol\adddot
+jourser|series|ser\adddot
+book|book|book
+part|part|part
+issue|issue|issue
+newseries|new series|new ser\adddot
+oldseries|old series|old ser\adddot
+edition|edition|ed\adddot
+reprint|reprint|repr\adddot
+reprintof|reprint of|repr\adddotspace of
+reprintas|reprinted as|rpt\adddotspace as
+reprintfrom|reprinted from|repr\adddotspace from
+reviewof|review of|rev\adddotspace of
+translationof|translation of|trans\adddotspace of
+translationas|translated as|trans\adddotspace as
+translationfrom|translated from|trans\adddotspace from
+origpubas|originally published as|orig\adddotspace pub\adddotspace as
+origpubin|originally published in|orig\adddotspace pub\adddotspace in
+astitle|as|as
+bypublisher|by|by
+nodate|no date|n\adddot d\adddot
+page|page|p\adddot
+pages|pages|pp\adddot
+column|column|col\adddot
+columns|columns|cols\adddot
+line|line|l\adddot
+lines|lines|ll\adddot
+verse|verse|v\adddot
+verses|verses|vv\adddot
+section|section|\S
+sections|sections|\S\S
+paragraph|paragraph|par\adddot
+paragraphs|paragraphs|par\adddot
+pagetotal|page|p\adddot
+pagetotals|pages|pp\adddot
+columntotal|column|col\adddot
+columntotals|columns|cols\adddot
+linetotal|line|l\adddot
+linetotals|lines|ll\adddot
+versetotal|verse|v\adddot
+versetotals|verses|vv\adddot
+sectiontotal|section|\S
+sectiontotals|sections|\S\S
+paragraphtotal|paragraph|par\adddot
+paragraphtotals|paragraphs|par\adddot
+in|in|in
+inseries|in|in
+ofseries|of|of
+number|number|no\adddot
+chapter|chapter|chap\adddot
+bathesis|Bachelor's thesis|BA\addabbrvspace thesis
+mathesis|Master's thesis|MA\addabbrvspace thesis
+phdthesis|PhD\addabbrvspace thesis|PhD\addabbrvspace thesis
+candthesis|Candidate thesis|Cand\adddotspace thesis
+resreport|research report|research rep\adddot
+techreport|technical report|tech\adddotspace rep\adddot
+software|computer software|comp\adddotspace software
+datacd|CD-ROM|CD-ROM
+audiocd|audio CD|audio CD
+version|version|version
+url|address|address
+urlfrom|available from|available from
+urlseen|visited on|visited on
+inpreparation|in preparation|in preparation
+submitted|submitted|submitted
+forthcoming|forthcoming|forthcoming
+inpress|in press|in press
+prepublished|pre-published|pre-published
+citedas|henceforth cited as|henceforth cited as
+thiscite|especially|esp\adddot
+seenote|see note|see n\adddot
+quotedin|quoted in|qtd\adddotspace in
+idem|idem|idem
+idemsm|idem|idem
+idemsf|eadem|eadem
+idemsn|idem|idem
+idempm|eidem|eidem
+idempf|eaedem|eaedem
+idempn|eadem|eadem
+idempp|eidem|eidem
+ibidem|ibidem|ibid\adddot
+opcit|op\adddotspace cit\adddot|op\adddotspace cit\adddot
+loccit|loc\adddotspace cit\adddot|loc\adddotspace cit\adddot
+confer|cf\adddot|cf\adddot
+sequens|sq\adddot|sq\adddot
+sequentes|sqq\adddot|sqq\adddot
+passim|passim|pass\adddot
+see|see|see
+seealso|see also|see also
+backrefpage|cited on page|cit\adddotspace on p\adddot
+backrefpages|cited on pages|cit\adddotspace on pp\adddot
+january|January|Jan\adddot
+february|February|Feb\adddot
+march|March|Mar\adddot
+april|April|Apr\adddot
+may|May|May
+june|June|June
+july|July|July
+august|August|Aug\adddot
+september|September|Sept\adddot
+october|October|Oct\adddot
+november|November|Nov\adddot
+december|December|Dec\adddot
+langamerican|American|American
+langbrazilian|Brazilian|Brazilian
+langbulgarian|Bulgarian|Bulgarian
+langcatalan|Catalan|Catalan
+langcroatian|Croatian|Croatian
+langczech|Czech|Czech
+langdanish|Danish|Danish
+langdutch|Dutch|Dutch
+langenglish|English|English
+langestonian|Estonian|Estonian
+langfinnish|Finnish|Finnish
+langfrench|French|French
+langgalician|Galician|Galician
+langgerman|German|German
+langgreek|Greek|Greek
+langhungarian|Hungarian|Hungarian
+langitalian|Italian|Italian
+langjapanese|Japanese|Japanese
+langlatin|Latin|Latin
+langlatvian|Latvian|Latvian
+langlithuanian|Lithuanian|Lithuanian
+langnorwegian|Norwegian|Norwegian
+langpolish|Polish|Polish
+langportuguese|Portuguese|Portuguese
+langrussian|Russian|Russian
+langserbian|Serbian|Serbian
+langslovak|Slovak|Slovak
+langslovene|Slovene|Slovene
+langspanish|Spanish|Spanish
+langswedish|Swedish|Swedish
+langturkish|Turkish|Turkish
+langukrainian|Ukrainian|Ukrainian
+fromamerican|from the American|from the American
+frombrazilian|from the Brazilian|from the Brazilian
+frombulgarian|from the Bulgarian|from the Bulgarian
+fromcatalan|from the Catalan|from the Catalan
+fromcroatian|from the Croatian|from the Croatian
+fromczech|from the Czech|from the Czech
+fromdanish|from the Danish|from the Danish
+fromdutch|from the Dutch|from the Dutch
+fromenglish|from the English|from the English
+fromestonian|from the Estonian|from the Estonian
+fromfinnish|from the Finnish|from the Finnish
+fromfrench|from the French|from the French
+fromgalician|from the Galician|from the Galician
+fromgerman|from the German|from the German
+fromgreek|from the Greek|from the Greek
+fromhungarian|from the Hungarian|from the Hungarian
+fromitalian|from the Italian|from the Italian
+fromjapanese|from the Japanese|from the Japanese
+fromlatin|from the Latin|from the Latin
+fromlatvian|from the Latvian|from the Latvian
+fromlithuanian|from the Lithuanian|from the Lithuanian
+fromnorwegian|from the Norwegian|from the Norwegian
+frompolish|from the Polish|from the Polish
+fromportuguese|from the Portuguese|from the Portuguese
+fromrussian|from the Russian|from the Russian
+fromserbian|from the Serbian|from the Serbian
+fromslovak|from the Slovak|from the Slovak
+fromslovene|from the Slovene|from the Slovene
+fromspanish|from the Spanish|from the Spanish
+fromswedish|from the Swedish|from the Swedish
+fromturkish|from the Turkish|from the Turkish
+fromukrainian|from the Ukrainian|from the Ukrainian
+countryde|Germany|DE
+countryeu|European Union|EU
+countryep|European Union|EP
+countryfr|France|FR
+countryuk|United Kingdom|GB
+countryus|United States of America|US
+patent|patent|pat\adddot
+patentde|German patent|German pat\adddot
+patenteu|European patent|European pat\adddot
+patentfr|French patent|French pat\adddot
+patentuk|British patent|British pat\adddot
+patentus|U.S\adddotspace patent|U.S\adddotspace pat\adddot
+patreq|patent request|pat\adddot\ req\adddot
+patreqde|German patent request|German pat\adddot\ req\adddot
+patreqeu|European patent request|European pat\adddot\ req\adddot
+patreqfr|French patent request|French pat\adddot\ req\adddot
+patrequk|British patent request|British pat\adddot\ req\adddot
+patrequs|U.S\adddotspace patent request|U.S\adddotspace pat\adddot\ req\adddot
+file|file|file
+library|library|library
+abstract|abstract|abstract
+annotation|annotations|annotations
+commonera|Common Era|CE
+beforecommonera|Before Common Era|BCE
+annodomini|Anno Domini|AD
+beforechrist|Before Christ|BC
+circa|circa|ca\adddot
+spring|Spring|Spr\adddot
+summer|Summer|Sum\adddot
+autumn|Autumn|Aut\adddot
+winter|Winter|Win\adddot
+am|AM|AM
+pm|PM|PM
diff --git a/citeproc/biblatex-localization/estonian.lbx.strings b/citeproc/biblatex-localization/estonian.lbx.strings
new file mode 100644
--- /dev/null
+++ b/citeproc/biblatex-localization/estonian.lbx.strings
@@ -0,0 +1,178 @@
+bibliography|bibliograafia|bibliograafia
+references|viited|viited
+editor|toimetaja|toim\adddot
+editors|toimetajad|toim\adddot
+compiler|koostaja|koost\adddot
+compilers|koostajad|koost\adddot
+redactor|toimetaja|toim\adddot
+redactors|toimetajad|toim\adddot
+reviser|toimetaja|toim\adddot
+revisers|toimetajad|toim\adddot
+founder|asutaja|asutaja
+founders|asutajad|asutajad
+commentator|kommenteerija|kommenteerija
+commentators|kommenteerijad|kommenteerijad
+annotator|kommenteerija|kommenteerija
+annotators|kommenteerijad|kommenteerijad
+commentary|kommentaarid|kommentaarid
+annotations|kommentaarid|kommentaarid
+introduction|sissejuhatus|sissejuhatus
+organizer|korraldaja|korraldaja
+organizers|korraldajad|korraldajad
+byorganizer|korraldanud|korraldanud
+byauthor|kirjutanud|kirj\adddot
+byeditor|toimetanud|toim\adddot
+bycompiler|koostanud|koost\adddot
+byredactor|toimetanud|toim\adddot
+byreviewer|vaadanud|vaadanud
+byfounder|asutanud|asutanud
+bycommentator|kommenteerinud|kommenteerinud
+byannotator|kommenteerinud|kommenteerinud
+withcommentator|koos kommentaaridega|koos kommentaaridega
+withannotator|koos kommentaaridega|koos kommentaaridega
+withintroduction|koos tutvustusega|koos tutvustusega
+and|ja|ja
+involumes|osas|osas
+jourser|seeria|seeria
+book|raamat|raamat
+part|osa|osa
+issue|number|nr\adddot
+newseries|uus seerias|uus seer\adddot
+oldseries|vana seeria|vana seer\adddot
+reviewof|arvustus teosest|arvustus teosest
+origpubas|algselt avaldatud kui|algselt avaldatud kui
+origpubin|algselt avaldatud aastal|algselt avaldatud aastal
+astitle|pealkirjaga|pealkirjaga
+column|veerg|veerg
+columns|veerud|veerud
+line|rida|rida
+lines|read|read
+verse|salm|salm
+verses|salmid|salmid
+section|jagu|jagu
+sections|jaod|jaod
+columntotal|veerge kokku|veerge kokku
+columntotals|veergusid kokku|veergusid kokku
+linetotal|ridu kokku|ridu kokku
+linetotals|ridasid kokku|ridasid kokku
+versetotal|salmi kokku|salmi kokku
+versetotals|salmesid kokku|salmesid kokku
+sectiontotal|jagusid kokku|jagusid kokku
+sectiontotals|jagusid kokku|jagusid kokku
+in|teoses|teoses
+inseries|sarjas|sarjas
+ofseries|sarjast|sarjast
+number|number|nr
+resreport|uuringuraport|uuringuraport
+techreport|tehniline raport|tehniline raport
+software|tarkvara|tarkvara
+datacd|CD-ROM|CD-ROM
+audiocd|audioplaat|audioplaat
+version|versioon|versioon
+url|aadress|aadress
+urlfrom|saadaval|saadaval
+urlseen|vaadatud|vaadatud
+inpreparation|koostamisel|koostamisel
+submitted|esitatud|esitatud
+forthcoming|tulevases|tulevases
+citedas|edaspidi viidatud kui|edaspidi viidatud kui
+thiscite|eriti|eriti
+quotedin|noteeritud|noteeritud
+see|vaata|vt
+seealso|vaata ka|vt ka
+backrefpage|viidatud lehel|viidatud lehel
+january|jaanuar|jaanuar
+february|veebruar|veebruar
+april|aprill|aprill
+may|mai|mai
+june|juuni|juuni
+july|juuli|juuli
+august|august|august
+september|september|september
+october|oktoober|oktoober
+november|november|november
+december|detsember|detsember
+langamerican|Ameerika inglise keel|Ameerika inglise keel
+langbrazilian|brasiilia keel|brasiilia keel
+langbulgarian|bulgaaria keel|bulgaaria keel
+langcatalan|katalaani keel|katalaani keel
+langcroatian|horvaadi keel|horvaadi keel
+langdanish|taani keel|taani keel
+langdutch|hollandi keel|hollandi keel
+langenglish|inglise keel|inglise keel
+langestonian|eesti keel|eesti keel
+langfinnish|soome keel|soome keel
+langfrench|prantsuse keel|prantsuse keel
+langgalician|galeegi keel|galeegi keel
+langgerman|saksa keel|saksa keel
+langgreek|kreeka keel|kreeka keel
+langhungarian|ungari keel|ungari keel
+langitalian|itaalia keel|itaalia keel
+langjapanese|jaapani keel|jaapani keel
+langlatin|ladina keel|ladina keel
+langnorwegian|norra keel|norra keel
+langpolish|poola keel|poola keel
+langportuguese|portugali keel|portugali keel
+langrussian|vene keel|vene keel
+langslovak|slovakia keel|slovakia keel
+langslovene|sloveeni keel|sloveeni keel
+langspanish|hispaania keel|hispaania keel
+langswedish|rootsi keel|rootsi keel
+langukrainian|ukraina keel|ukraina keel
+fromamerican|Ameerika inglise keelest|Ameerika inglise keelest
+frombrazilian|brasiilia keelest|brasiilia keelest
+frombulgarian|bulgaaria keelest|bulgaaria keelest
+fromcatalan|katalani keelest|kalatalani keelest
+fromcroatian|horvaadi keelest|horvaadi keelest
+fromdanish|taani keelest|taani keelest
+fromdutch|hollandi keelest|hollandi keelest
+fromenglish|inglise keelest|inglise keelest
+fromestonian|eesti keelest|eesti keelest
+fromfinnish|soome keelest|soome keelest
+fromfrench|prantsuse keelest|prantsuse keelest
+fromgalician|galeegi keelest|galeegi keelest
+fromgerman|saksa keelest|saksa keelest
+fromgreek|kreeka keelest|kreeka keelest
+fromhungarian|ungari keelest|ungari keelest
+fromitalian|itaalia keelest|itaalia keelest
+fromjapanese|jaapani keelest|jaapani keelest
+fromlatin|ladina keelest|ladina keelest
+fromnorwegian|norra keelest|norra keelest
+fromportuguese|portugali keelest|portugali keelest
+fromrussian|vene keelest|vene keelest
+fromslovak|slovakia keelest|slovakia keelest
+fromslovene|sloveenia keelest|sloveenia keelest
+fromspanish|hispaania keelest|hispaania keelest
+fromswedish|rootsi keelest|rootsi keelest
+fromukrainian|ukraina keelest|ukraina keelest
+countryde|Saksamaa|DE
+countryeu|Euroopa Liit|EL
+countryep|Euroopa Parlament|EP
+countryfr|Prantsusmaa|FR
+countryuk|Suurbritannia|GB
+countryus|Ameerika|US
+patent|patent|pat\adddot
+patentde|Saksa patent|Saksa pat\adddot
+patenteu|Euroopa patent|Euroopa pat\adddot
+patentfr|Prantsuse patent|Prantsuse pat\adddot
+patentuk|Briti patent|Briti pat\adddot
+patentus|U.S\adddotspace patent|U.S\adddotspace pat\adddot
+patreq|patendi taotlus|pat\adddotspace taotl\adddot
+patreqde|Saksa patendi taotlus|Saksa pat\adddotspace taotl\adddot
+patreqeu|Euroopa patendi taotlus|Euroopa pat\adddotspace taotl\adddot
+patreqfr|Prantsuse patendi taotlus|Prantsuse pat\adddotspace taotl\adddot
+patrequk|Briti patendi taotlus|Briti pat\adddotspace taotl\adddot
+patrequs|U.S\adddotspace patendi taotlus.|U.S\adddotspace pat\adddotspace taotl\adddot
+file|fail|fail
+library|raamatukogu|raamatukogu
+abstract|teesid|teesid
+annotation|kommentaarid|kommentaarid
+commonera|meie ajaarvamise j\"argi|m\adddot a\adddot j
+beforecommonera|enne meie ajaarvamist|e\adddot m\adddot a
+annodomini|p\"arast Kristust|pKr
+beforechrist|enne Kristust|eKr
+spring|kevadel|kevadel
+summer|suvel|suvel
+winter|talvel|talvel
+am|AM|AM
+pm|PM|PM
diff --git a/citeproc/biblatex-localization/finnish.lbx.strings b/citeproc/biblatex-localization/finnish.lbx.strings
new file mode 100644
--- /dev/null
+++ b/citeproc/biblatex-localization/finnish.lbx.strings
@@ -0,0 +1,254 @@
+bibliography|Kirjallisuusluettelo|Kirjallisuus
+references|Viitteet|Viitteet
+shorthands|Lyhenteet|Lyhenteet
+editor|toimittanut|toim\adddot
+editors|toimittaneet|toim\adddot
+compiler|koontanut|koontanut
+compilers|koontaneet|koontaneet
+redactor|toimittanut|toim\adddot
+redactors|toimittaneet|toim\adddot
+reviser|toimittanut|toim\adddot
+revisers|toimittaneet|toim\adddot
+founder|perustaja|perustaja
+founders|perustajat|perustajat
+continuator|jatkaja|jatkaja
+continuators|jatkajat|jatkajat
+collaborator|avustaja|avustaja
+collaborators|avustajat|avustajat
+translator|k\"a\"ant\"anyt|k\"a\"ant\adddot
+translators|k\"a\"ant\"anyt|k\"a\"ant\adddot
+commentator|kommentaarin kirjoittanut|kommentaarin kirjoittanut
+commentators|kommentaarin kirjoittaneet|kommentaarin kirjoittaneet
+annotator|selityksin varustanut|selityksin varustanut
+annotators|selityksin varustaneet|selityksin varustaneet
+commentary|kommentaari|kommentaari
+annotations|selitykset|selitykset
+introduction|johdanto|johdanto
+foreword|esipuhe|esipuhe
+afterword|j\"alkisanat|j\"alkisanat
+organizer|toimittanut|toim\adddot
+organizers|toimittaneet|toim\adddot
+byorganizer|toimittanut|toim\adddot
+byauthor|kirjoittanut|kirj\adddot
+byeditor|toimittanut|toim\adddot
+bycompiler|koontanut|koontanut
+byredactor|toimittanut|toim\adddot
+byreviser|toimittanut|toim\adddot
+byreviewer|toimittanut|toim\adddot
+byfounder|perustanut|perustanut
+bycontinuator|jatkanut|jatkanut
+bycollaborator|yhteisty\"oss\"a|yhteisty\"oss\"a
+bytranslator|\lbx@lfromlang k\"a\"ant\"anyt|\lbx@sfromlang k\"a\"ant\adddot
+bycommentator|kommentaarin kirjoittanut|kommentaarin kirjoittanut
+byannotator|selityksin varustanut|selityksin varustanut
+withcommentator|kommentaarin kirjoittanut|kommentaarin kirjoittanut
+withannotator|selityksin varustanut|selityksin varustanut
+withintroduction|johdannon kirjottanut|johdannon kirjottanut
+withforeword|esipuheen kirjoittanut|esipuheen kirjoittanut
+withafterword|j\"alkisanat kirjoittanut|j\"alkisanat kirjoittanut
+and|ja|ja
+andothers|et\addabbrvspace al\adddot|et\addabbrvspace al\adddot
+andmore|jne\adddot|jne\adddot
+volume|volyymi|vol\adddot
+volumes|volyymit|vol\adddot
+involumes||
+jourvol|volyymi|vol\adddot
+jourser|sarja|sarja
+book|kirja|kirja
+part|osa|osa
+issue|numero|numero
+newseries|uusi sarja|uusi sarja
+oldseries|vanha sarja|vanha sarja
+edition|painos|painos
+reprint|j\"alkipainos|j\"alkipainos
+reprintof|julkaistu aiemmin nimell\"a|julkaistu aiemmin nimell\"a
+reprintas|julkaistu uudelleen nimell\"a|julkaistu uudelleen nimell\"a
+reprintfrom|julkaistu aiemmin nimell\"a|julkaistu aiemmin nimell\"a
+translationof|k\"a\"ann\"os teoksesta|k\"a\"ann\"os teoksesta
+translationas|k\"a\"annetty nimell\"a|k\"a\"annetty nimell\"a
+translationfrom|k\"a\"annetty kielest\"a|k\"a\"annetty kielest\"a
+reviewof|arvostelu teoksesta|arvostelu teoksesta
+origpubas|julkaistu ensi kerran nimell\"a|julkaistu ensi kerran nimell\"a
+origpubin|julkaistu ensi kerran vuonna|julkaistu ensi kerran vuonna
+astitle|nimell\"a|nimell\"a
+bypublisher|julkaissut|julkaissut
+page|sivu|s\adddot
+pages|sivut|s\adddot
+column|palsta|palsta
+columns|palstat|palstat
+line|rivi|rivi
+lines|rivit|rivit
+nodate|ei julkaisup\"aiv\"a\"a|ei julkaisup\"aiv\"a\"a
+verse|s\"ae|s\"ae
+verses|s\"akeet|s\"akeet
+section|kohta|kohta
+sections|kohdat|kohdat
+paragraph|kappale|kappale
+paragraphs|kappaleet|kappaleet
+pagetotal|sivu|s\adddot
+pagetotals|sivut|s\adddot
+columntotal|palsta|palsta
+columntotals|palstat|palstat
+linetotal|rivi|rivi
+linetotals|rivit|rivit
+versetotal|s\"ae|s\"ae
+versetotals|s\"akeet|s\"akeet
+sectiontotal|kohta|kohta
+sectiontotals|kohdat|kohdat
+paragraphtotal|kappale|kappale
+paragraphtotals|kappaleet|kappaleet
+in|teoksessa|teoksessa
+inseries|sarjassa|sarjassa
+ofseries|sarjassa|sarjassa
+number|numero|nro
+chapter|luku|luku
+bathesis|tutkielma|tutkielma
+mathesis|tutkielma|tutkielma
+phdthesis|tohtorinv\"ait\"oskirja|tohtorinv\"ait\"oskirja
+candthesis|kanditaatintutkielma|kanditaatintutkielma
+resreport|tutkimusraportti|tutkimusraportti
+techreport|tekninen raportti|tekninen raportti
+software|ohjelmisto|ohjelmisto
+datacd|data-CD|data-CD
+audiocd|\"a\"ani-CD|\"a\"ani-CD
+version|versio|versio
+url|url|url
+urlfrom|saatavilla osoitteesta|saatavilla osoitteesta
+urlseen|viitattu|viitattu
+inpreparation|valmisteilla|valmisteilla
+submitted|l\"ahetetty|l\"ahetetty
+forthcoming|hyv\"aksytty julkaistavaksi|hyv\"aksytty julkaistavaksi
+inpress|painossa|painossa
+prepublished|esijulkaistu|esijulkaistu
+citedas|jatkossa|jatkossa
+thiscite|sama|sama
+seenote|katso viite|katso viite
+quotedin|lainattu teoksessa|lainattu teoksessa
+idem|idem|id\adddot
+idemsf|idem|id\adddot
+idemsm|idem|id\adddot
+idemsn|idem|id\adddot
+idempf|idem|id\adddot
+idempm|idem|id\adddot
+idempn|idem|id\adddot
+idempp|idem|id\adddot
+ibidem|ibidem|ibid\adddot
+opcit|op\adddotspace cit\adddot|op\adddotspace cit\adddot
+loccit|loc\adddotspace cit\adddot|loc\adddotspace cit\adddot
+confer|cf\adddot|cf\adddot
+sequens|sq\adddot|sq\adddot
+sequentes|sqq\adddot|sqq\adddot
+passim|passim|pass\adddot
+see|katso|ks\adddot
+seealso|katso my\"os|katso my\"os
+backrefpage|katso sivu|ks\adddotspace s\adddot
+backrefpages|katso sivut|ks\adddotspace s\adddot
+january|tammikuuta|tammikuuta
+february|helmikuuta|helmikuuta
+march|maaliskuuta|maaliskuuta
+april|huhtikuuta|huhtikuuta
+may|toukokuuta|toukokuuta
+june|kes\"akuuta|kes\"akuuta
+july|hein\"akuuta|hein\"akuuta
+august|elokuuta|elokuuta
+september|syyskuuta|syyskuuta
+october|lokakuuta|lokakuuta
+november|marraskuuta|marraskuuta
+december|joulukuuta|joulukuuta
+basicjanuary|tammikuu|tammikuu
+basicfebruary|helmikuu|helmikuu
+basicmarch|maaliskuu|maaliskuu
+basicapril|huhtikuu|huhtikuu
+basicmay|toukokuu|toukokuu
+basicjune|kes\"akuu|kes\"akuu
+basicjuly|hein\"akuu|hein\"akuu
+basicaugust|elokuu|elokuu
+basicseptember|syyskuu|syyskuu
+basicoctober|lokakuu|lokakuu
+basicnovember|marraskuu|marraskuu
+basicdecember|joulukuu|joulukuu
+langamerican|amerikanenglanti|amerikanenglanti
+langbrazilian|brasilianportugali|brasilianportugali
+langbulgarian|bulgaria|bulgaria
+langcatalan|katalonia|katalonia
+langcroatian|kroatia|kroatia
+langdanish|tanska|tanska
+langdutch|hollanti|hollanti
+langenglish|englanti|englanti
+langestonian|viro|viro
+langfinnish|suomi|suomi
+langfrench|ranska|ranska
+langgalician|galicia|galicia
+langgerman|saksa|saksa
+langgreek|kreikka|kreikka
+langhungarian|unkari|unkari
+langitalian|italia|italia
+langlatin|latina|latina
+langlatvian|latvia|latvia
+langnorwegian|norja|norja
+langpolish|puola|puola
+langportuguese|portugali|portugali
+langrussian|ven\"aj\"a|ven\"aj\"a
+langslovak|slovakia|slovakia
+langslovene|slovenia|slovenia
+langspanish|espanja|espanja
+langswedish|ruotsi|ruotsi
+fromamerican|englannin kielest\"a|englannin kielest\"a
+frombrazilian|portugalin kielest\"a|portugalin kielest\"a
+frombulgarian|bulgarian kielest\"a|bulgarian kielest\"a
+fromcatalan|katalonian kielest\"a|katalonian kielest\"a
+fromcroatian|kroatian kielest\"a|kroatian kielest\"a
+fromdanish|tanskan kielest\"a|tanskan kielest\"a
+fromdutch|hollannin kielest\"a|hollannin kielest\"a
+fromenglish|englannin kielest\"a|englannin kielest\"a
+fromestonian|viron kielest\"a|viron kielest\"a
+fromfinnish|suomen kielest\"a|suomen kielest\"a
+fromfrench|ranskan kielest\"a|ranskan kielest\"a
+fromgalician|galician kielest\"a|galician kielest\"a
+fromgerman|saksan kielest\"a|saksan kielest\"a
+fromgreek|kreikan kielest\"a|kreikan kielest\"a
+fromhungarian|unkarin kielest\"a|unkarin kielest\"a
+fromitalian|italian kielest\"a|italian kielest\"a
+fromlatin|latinan kielest\"a|latinan kielest\"a
+fromlatvian|latvian kielest\"a|latvian kielest\"a
+fromnorwegian|norjan kielest\"a|norjan kielest\"a
+frompolish|puolan kielest\"a|puolan kielest\"a
+fromportuguese|portugalin kielest\"a|portugalin kielest\"a
+fromrussian|ven\"aj\"an kielest\"a|ven\"aj\"an kielest\"a
+fromslovak|slovakian kielest\"a|slovakian kielest\"a
+fromslovene|slovenian kielest\"a|slovenian kielest\"a
+fromspanish|espanjan kielest\"a|espanjan kielest\"a
+fromswedish|ruotsin kielest\"a|ruotsin kielest\"a
+countryde|Saksa|DE
+countryeu|Euroopan Unioni|EU
+countryep|Euroopan Unioni|EP
+countryfr|Ranska|FR
+countryuk|Iso-Britannia|GB
+countryus|Yhdysvallat|US
+patent|patentti|pat\adddot
+patentde|saksalainen patentti|saksalainen pat\adddot
+patenteu|Euroopan Unionin patentti|Euroopan Unionin pat\adddot
+patentfr|ranskalainen patentti|ranskalainen pat\adddot
+patentuk|isobritannialainen patentti|isobritannialainen pat\adddot
+patentus|yhdysvaltalainen patentti|yhdysvaltalainen pat\adddot
+patreq|patenttihakemus|pat\adddot\ hak\adddot
+patreqde|saksalainen patenttihakemus|saksalainen pat\adddot\ hak\adddot
+patreqeu|Euroopan Unionin patenttihakemus|Euroopan Unionin pat\adddot\ hak\adddot
+patreqfr|ranskalainen patenttihakemus|ranskalainen pat\adddot\ hak\adddot
+patrequk|isobritannialainen patenttihakemus|isobritannialainen pat\adddot\ hak\adddot
+patrequs|yhdysvaltalainen patenttihakemus|yhdysvaltalainen pat\adddot\ hak\adddot
+file|tiedosto|tiedosto
+library|kirjasto|kirjasto
+abstract|tiivistelm\"a|tiivistelm\"a
+annotation|selitykset|selitykset
+commonera|j\"alkeen ajanlaskun alun|jaa\adddot
+beforecommonera|ennen ajanlaskun alkua|eaa\adddot
+annodomini|j\"alkeen Kristuksen syntym\"an|jKr\adddot
+beforechrist|ennen Kristuksen syntym\"a\"a|eKr\adddot
+circa|noin|n\adddot
+spring|kev\"at|kev\"at
+summer|kes\"a|kes\"a
+autumn|syksy|syksy
+winter|talvi|talvi
+am|ap\adddot|ip\adddot
+pm|ip\adddot|ip\adddot
diff --git a/citeproc/biblatex-localization/french.lbx.strings b/citeproc/biblatex-localization/french.lbx.strings
new file mode 100644
--- /dev/null
+++ b/citeproc/biblatex-localization/french.lbx.strings
@@ -0,0 +1,245 @@
+bibliography|Bibliographie|Bibliographie
+references|R\'ef\'erences|R\'ef\'erences
+shorthands|Liste des abr\'eviations|Abr\'eviations
+editor|\'editeur|\'ed\adddot
+editors|\'editeurs|\'ed\adddot
+compiler|compilateur|comp\adddot
+compilers|compilateurs|comp\adddot
+redactor|r\'edacteur|r\'ed\adddot
+redactors|r\'edacteurs|r\'ed\adddot
+reviser|r\'eviseur|r\'ev\adddot
+revisers|r\'eviseurs|r\'ev\adddot
+founder|fondateur|fond\adddot
+founders|fondateurs|fond\adddot
+continuator|continuateur|cont\adddot
+continuators|continuateurs|cont\adddot
+collaborator|collaborateur|coll\adddot
+collaborators|collaborateurs|coll\adddot
+translator|traducteur|trad\adddot
+translators|traducteurs|trad\adddot
+commentator|commentateur|comm\adddot
+commentators|commentateurs|comm\adddot
+annotator|annotateur|annot\adddot
+annotators|annotateurs|annot\adddot
+commentary|commentaires|comment\adddot
+annotations|annotations|annot\adddot
+introduction|introduction|introd\adddot
+foreword|pr\'eface|pr\'ef\adddot
+afterword|postface|postf\adddot
+editortr|\'editeur et traducteur|\'ed\adddotspace et trad\adddot
+editorstr|\'editeurs et traducteurs|\'ed\adddotspace et trad\adddot
+organizer|organisateur|org\adddot
+organizers|organisateurs|org\adddot
+byorganizer|organis\'e par|org\adddotspace par
+byauthor|par|par
+byeditor|sous la direction \smartof|sous la dir\adddotspace\smartof
+bycompiler|compil\'e par|comp\adddotspace par
+byredactor|r\'edig\'e par|r\'ed\adddotspace par
+byreviser|r\'evis\'e par|r\'ev\adddotspace par
+byreviewer|examin\'e par|ex\adddotspace par
+byfounder|d\'ecouvert par|d\'ecouv\adddotspace par
+bycontinuator|continu\'e par|cont\adddotspace par
+bytranslator|traduit \lbx@lfromlang\ par|trad\adddotspace \lbx@sfromlang\ par
+bycommentator|comment\'e par|comm\adddotspace par
+byannotator|annot\'e par|annot\adddotspace par
+withcommentator|avec des commentaires \smartof|avec des comment\adddotspace\smartof
+withannotator|avec des annotations \smartof|avec des annot\adddotspace\smartof
+withintroduction|avec une introduction \smartof|avec une introd\adddotspace\smartof
+withforeword|avec une pr\'eface \smartof|avec une pr\'ef\adddotspace\smartof
+withafterword|avec une postface \smartof|avec une postf\adddotspace\smartof
+and|et|et
+andothers|et\addabbrvspace al\adddot|et\addabbrvspace al\adddot
+andmore|et\addabbrvspace al\adddot|et\addabbrvspace al\adddot
+volume|tome|t\adddot
+volumes|tomes|t\adddot
+involumes|en|en
+jourvol|tome|t\adddot
+jourser|s\'erie|s\'er\adddot
+book|livre|livre
+part|partie|partie
+issue|\'edition|\'ed\adddot
+newseries|nouvelle s\'erie|nouv\adddotspace s\'er\adddot
+oldseries|ancienne s\'erie|anc\adddotspace s\'er\adddot
+edition|\'edition|\'ed\adddot
+reprint|r\'eimpression|r\'eimpr\adddot
+reprintof|r\'eimpression de|r\'eimpr\adddotspace de
+reprintas|r\'eimpression sous le titre|r\'eimpr\adddotspace sous le titre
+reprintfrom|r\'eimpression \`a partir \smartof|r\'eimpr\adddotspace \`a part\adddotspace\smartof
+translationof|traduction de|trad\adddotspace de
+translationas|traduit sous le titre|trad\adddotspace sous le titre
+translationfrom|traduit de|trad\adddotspace de
+reviewof|critique de|crit.\adddotspace de
+origpubas|publi\'e \`a l'origine sous le titre|pub\adddotspace \`a l'orig\adddotspace sous le titre
+origpubin|publi\'e \`a l'origine en|pub\adddotspace \`a l'orig\adddotspace en
+astitle|sous le titre|sous le titre
+bypublisher|par|par
+page|page|p\adddot
+pages|pages|p\adddot
+column|colonne|col\adddot
+columns|colonnes|col\adddot
+line|ligne|l\adddot
+lines|lignes|l\adddot
+verse|vers|v\adddot
+verses|vers|v\adddot
+section|section|sect\adddot
+sections|sections|sect\adddot
+paragraph|paragraphe|\S
+paragraphs|paragraphes|\S
+pagetotal|page|p\adddot
+pagetotals|pages|p\adddot
+columntotal|colonne|col\adddot
+columntotals|colonnes|col\adddot
+linetotal|ligne|l\adddot
+linetotals|lignes|l\adddot
+versetotal|vers|v\adddot
+versetotals|vers|v\adddot
+sectiontotal|section|sect\adddot
+sectiontotals|sections|sect\adddot
+paragraphtotal|paragraphe|\S
+paragraphtotals|paragraphes|\S
+in|in|in
+inseries|in|in
+ofseries|de|de
+number|num\'ero|n\textsuperscript{o
+chapter|chapitre|chap\adddot
+bathesis|m\'emoire de bachelor|m\'em\adddotspace de bach\adddot
+mathesis|m\'emoire de master|m\'em\adddotspace de mast\adddot
+phdthesis|th\`ese de doctorat|th\`ese de doct\adddot
+candthesis|th\`ese de candidature|th\`ese de cand\adddot
+resreport|rapport scientifique|rapp\adddotspace scient\adddot
+techreport|rapport technique|rapp\adddotspace tech\adddot
+software|logiciel|logiciel
+datacd|c\'ed\'erom|c\'ed\'erom
+audiocd|disque compact audio|CD
+version|version|version
+url|adresse|adresse
+urlfrom|disponible \`a l'adresse|disp\adddotspace \`a l'adr\adddot
+urlseen|visit\'e le|visit\'e le
+inpreparation|en pr\'eparation|en pr\'ep\adddot
+submitted|soumis|soumis
+inpress|sous presse|sous presse
+prepublished|pr\'epubli\'e|pr\'epubl\adddot
+citedas|d\'esign\'e ci-apr\`es par|ci-apr\`es
+thiscite|sp\'ecialement|sp\'ec\adddot
+seenote|voir note|cf\adddotspace note
+quotedin|cit\'e dans|cit\'e dans
+idem|idem|idem
+idemsm|idem|idem
+idemsf|eadem|eadem
+idemsn|idem|idem
+idempm|eidem|eidem
+idempf|eaedem|eaedem
+idempn|eadem|eadem
+idempp|eidem|eidem
+ibidem|ibidem|ibid\adddot
+opcit|op\adddotspace cit\adddot|op\adddotspace cit\adddot
+loccit|loc\adddotspace cit\adddot|loc\adddotspace cit\adddot
+confer|cf\adddot|cf\adddot
+sequens|sq\adddot|sq\adddot
+sequentes|sqq\adddot|sqq\adddot
+passim|passim|pass\adddot
+see|cf\adddot|cf\adddot
+seealso|cf\adddotspace aussi|cf\adddotspace aussi
+backrefpage|cf\adddotspace page|cf\adddotspace p\adddot
+backrefpages|cf\adddotspace pages|cf\adddotspace p\adddot
+january|janvier|jan\adddot
+february|f\'evrier|f\'ev\adddot
+march|mars|mars
+april|avril|avr\adddot
+may|mai|mai
+june|juin|juin
+july|juillet|juill\adddot
+august|ao\^ut|ao\^ut
+september|septembre|sept\adddot
+october|octobre|oct\adddot
+november|novembre|nov\adddot
+december|d\'ecembre|d\'ec\adddot
+langamerican|am\'ericain|am\'ericain
+langbrazilian|br\'esilien|br\'esilien
+langbulgarian|bulgare|bulgare
+langcatalan|catalan|catalan
+langcroatian|croate|croate
+langczech|tch\`eque|tch\`eque
+langdanish|danois|danois
+langdutch|n\'eerlandais|n\'eerlandais
+langenglish|anglais|anglais
+langestonian|estonien|estonien
+langfinnish|finnois|finnois
+langgalician|galicien|galicien
+langgerman|allemand|allemand
+langgreek|grec|grec
+langhungarian|hongrois|hongrois
+langitalian|italien|italien
+langjapanese|japonais|japonais
+langlatin|latin|latin
+langlatvian|letton|letton
+langnorwegian|norv\'egien|norv\'egien
+langpolish|polonais|polonais
+langportuguese|portugais|portugais
+langrussian|russe|russe
+langserbian|serbe|serbe
+langslovak|slovaque|slovaque
+langslovene|slov\`ene|slov\`ene
+langspanish|espagnol|espagnol
+langswedish|su\'edois|su\'edois
+langukrainian|ukrainien|ukrainien
+fromamerican|de l'am\'ericain|de l'am\'ericain
+frombrazilian|du br\'esilien|du br\'esilien
+frombulgarian|du bulgare|du bulgare
+fromcatalan|du catalan|du catalan
+fromcroatian|du croate|du croate
+fromczech|du tch\`eque|du tch\`eque
+fromdanish|du danois|du danois
+fromdutch|du n\'eerlandais|du n\'eerlandais
+fromenglish|de l'anglais|de l'anglais
+fromestonian|de l'estonien|de l'estonien
+fromfinnish|du finnois|du finnois
+fromgalician|du galicien|du galicien
+fromgerman|de l'allemand|de l'allemand
+fromgreek|du grec|du grec
+fromhungarian|du hongrois|du hongrois
+fromitalian|de l'italien|de l'italien
+fromjapanese|du japonais|du japonais
+fromlatin|du latin|du latin
+fromlatvian|du letton|du letton
+fromnorwegian|du norv\'egien|du norv\'egien
+frompolish|du polonais|du polonais
+fromportuguese|du portugais|du portugais
+fromrussian|du russe|du russe
+fromserbian|du serbe|du serbe
+fromslovak|du slovaque|du slovaque
+fromslovene|du slov\`ene|du slov\`ene
+fromspanish|de l'espagnol|de l'espagnol
+fromswedish|du su\'edois|du su\'edois
+fromukrainian|de l'ukrainien|de l'ukrainien
+countryde|Allemagne|DE
+countryeu|Union europ\'eenne|EU
+countryep|Union europ\'eenne|EP
+countryfr|France|FR
+countryuk|Royaume-Uni|GB
+countryus|\'Etats-Unis|US
+patent|brevet|brev\adddot
+patentde|brevet allemand|brev\adddotspace allem\adddot
+patenteu|brevet europ\'een|brev\adddotspace europ\adddot
+patentuk|brevet britannique|brev\adddotspace brit\adddot
+patentus|brevet am\'ericain|brev\adddotspace am\'er\adddot
+patreq|demande de brevet|demande de brev\adddot
+patreqde|demande de brevet allemand|demande de brev\adddotspace allem\adddot
+patreqeu|demande de brevet europ\'een|demande de brev\adddotspace europ\adddot
+patrequk|demande de brevet britannique|demande de brev\adddotspace brit\adddot
+patrequs|demande de brevet am\'ericain|demande de brev\adddotspace am\'er\adddot
+file|fichier|fichier
+library|biblioth\`eque|biblioth\adddot
+abstract|r\'esum\'e|r\'es\adddot
+annotation|annotations|annotations
+commonera|de l'\`ere commune|EC
+beforecommonera|avant l'\`ere commune|AEC
+annodomini|apr\`es J\'esus-Christ|apr\adddotspace J\adddot-C\adddot
+beforechrist|avant J\'esus-Christ|av\adddotspace J\adddot-C\adddot
+circa|vers|vers
+spring|printemps|printemps
+summer|\'et\'e|\'et\'e
+autumn|automne|automne
+winter|hiver|hiver
+am|AM|AM
+pm|PM|PM
diff --git a/citeproc/biblatex-localization/galician.lbx.strings b/citeproc/biblatex-localization/galician.lbx.strings
new file mode 100644
--- /dev/null
+++ b/citeproc/biblatex-localization/galician.lbx.strings
@@ -0,0 +1,28 @@
+bibliography|Bibliograf\'ia|Bibliograf\'ia
+references|Referencias|Referencias
+shorthands|Lista de abreviaturas|Abreviaturas
+editor|editor|ed\adddot
+editors|editores|eds\adddot
+compiler|compilador|comp\adddot
+compilers|compiladores|comp\adddot
+redactor|redactor|red\adddot
+redactors|redactores|red\adddot
+reviser|revisor|rev\adddot
+revisers|revisores|revs\adddot
+founder|fundador|fund\adddot
+founders|fundadores|fund\adddot
+continuator|continuador|cont\adddot
+continuators|continuadores|cont\adddot
+collaborator|colaborador|col\adddot
+collaborators|colaboradores|cols\adddot
+translator|tradutor|trad\adddot
+translators|tradutores|trads\adddot
+commentator|comentador|coment\adddot
+commentators|comentadores|coments\adddot
+annotator|anotador|anot\adddot
+annotators|anotadores|anots\adddot
+commentary|comentario|coment\adddot
+annotations|notas|notas
+introduction|introduci\'on|introd\adddot
+foreword|prefacio|pref\adddot
+afterword|posfacio|posf\adddot
diff --git a/citeproc/biblatex-localization/german.lbx.strings b/citeproc/biblatex-localization/german.lbx.strings
new file mode 100644
--- /dev/null
+++ b/citeproc/biblatex-localization/german.lbx.strings
@@ -0,0 +1,28 @@
+bibliography|Literaturverzeichnis|Literatur
+references|Literaturverzeichnis|Literatur
+shorthands|Sigelverzeichnis|Sigel
+editor|Herausgeber|Hrsg\adddot
+editors|Herausgeber|Hrsg\adddot
+compiler|Kompilator|Komp\adddot
+compilers|Kompilatoren|Komp\adddot
+redactor|Bearbeiter|Bearb\adddot
+redactors|Bearbeiter|Bearb\adddot
+reviser|\"Uberarbeiter|\"Uberarb\adddot
+revisers|\"Uberarbeiter|\"Uberarb\adddot
+founder|Begr\"under|Begr\adddot
+founders|Begr\"under|Begr\adddot
+continuator|Fortf\"uhrer|Fortf\adddot
+continuators|Fortf\"uhrer|Fortf\adddot
+collaborator|Mitarbeiter|Mitarb\adddot
+collaborators|Mitarbeiter|Mitarb\adddot
+translator|\"Ubersetzer|\"Ubers\adddot
+translators|\"Ubersetzer|\"Ubers\adddot
+commentator|Kommentator|Komm\adddot
+commentators|Kommentatoren|Komm\adddot
+annotator|Kommentator|Komm\adddot
+annotators|Kommentatoren|Komm\adddot
+commentary|Kommentar|Komm\adddot
+annotations|Erl\"auterungen|Erl\"aut\adddot
+introduction|Einleitung|Einl\adddot
+foreword|Vorwort|Vorw\adddot
+afterword|Nachwort|Nachw\adddot
diff --git a/citeproc/biblatex-localization/greek.lbx.strings b/citeproc/biblatex-localization/greek.lbx.strings
new file mode 100644
--- /dev/null
+++ b/citeproc/biblatex-localization/greek.lbx.strings
@@ -0,0 +1,9 @@
+bibliography|Βιβλιογραφία|Βιβλιογραφία
+references|Αναφορές|Αναφορές
+shorthands|Κατάλογος συντμήσεων|Συντμήσεις
+editor|επιμελητής|επιμελητής
+editors|επιμελητές|επιμελητές
+compiler|συντάκτης|συντάκτης
+compilers|συντάκτες|συντάκτες
+redactor|συντάκτης|συντάκτης
+redactors|συντάκτες|συντάκτες
diff --git a/citeproc/biblatex-localization/hungarian.lbx.strings b/citeproc/biblatex-localization/hungarian.lbx.strings
new file mode 100644
--- /dev/null
+++ b/citeproc/biblatex-localization/hungarian.lbx.strings
diff --git a/citeproc/biblatex-localization/icelandic.lbx.strings b/citeproc/biblatex-localization/icelandic.lbx.strings
new file mode 100644
--- /dev/null
+++ b/citeproc/biblatex-localization/icelandic.lbx.strings
@@ -0,0 +1,7 @@
+bibliography|Heimildaskr\'a|Heimildaskr\'a
+references|Heimildir|Heimildir
+shorthands|Listi yfir skammstafanir|Skammstafanir
+editor|ristj\'ori|ritstj\adddot
+editors|ritstj\'orar|ritstj\adddot
+compiler|samantekt|samantekt
+compilers|samantekt|samantekt
diff --git a/citeproc/biblatex-localization/italian.lbx.strings b/citeproc/biblatex-localization/italian.lbx.strings
new file mode 100644
--- /dev/null
+++ b/citeproc/biblatex-localization/italian.lbx.strings
@@ -0,0 +1,9 @@
+bibliography|Bibliografia|Bibliografia
+references|Riferimenti bibliografici|Riferimenti bibliografici
+shorthands|Elenco delle sigle|Sigle
+editor|curatore|cur\adddot
+editors|curatori|cur\adddot
+compiler|compilatore|comp\adddot
+compilers|compilatori|comp\adddot
+redactor|redattore|red\adddot
+redactors|redattori|red\adddot
diff --git a/citeproc/biblatex-localization/latvian.lbx.strings b/citeproc/biblatex-localization/latvian.lbx.strings
new file mode 100644
--- /dev/null
+++ b/citeproc/biblatex-localization/latvian.lbx.strings
@@ -0,0 +1,75 @@
+redactor|redaktors|redakt\adddot
+redactors|redaktori|radakt\adddot
+reviser|revidents|revid\adddot
+revisers|revidenti|revid\adddot
+introduction|ievads|ievads
+byeditor|izdevis|izdevis
+bytranslator|tulkojis|tulk\adddot
+withintroduction|ar ievadu no|ar ievadu no
+byeditortr|izdevis un tulkojis|izdev\adddotspace un tulk\adddot
+and|un|un
+andothers|un citi|u\adddotspace c\adddot
+jourvol|izdevums|izdev\adddot
+issue|izdevums|izdev\adddot
+edition|izdevums|izdev\adddot
+translationof|tulkojums no|tulk\adddotspace no
+translationfrom|tulkots no|tulk\adddotspace no
+reviewof|recenzija|recenz\adddot
+bypublisher|no|no
+nodate|bez datuma|bez dat\adddot
+page|lappuse|lpp\adddot
+pages|lappuses|lpp\adddot
+column|sleja|sleja
+columns|slejas|slejas
+line|rinda|rinda
+lines|rindas|rindas
+verse|pants|pants
+verses|panti|panti
+paragraph|rindkopa|rindk\adddot
+paragraphs|rindkopas|rindk\adddot
+pagetotal|lappuse|lpp\adddot
+pagetotals|lappuses|lpp\adddot
+columntotal|sleja|sleja
+columntotals|slejas|slejas
+linetotal|rinda|rinda
+linetotals|rindas|rindas
+versetotal|pants|pants
+versetotals|panti|panti
+paragraphtotal|rindkopa|rindk\adddot
+paragraphtotals|rindkopas|rindk\adddot
+in||
+number|numurs|nr\adddot
+datacd|datu CD|datu CD
+audiocd|audio CD|audio CD
+version|versija|versija
+url|pieejams|pieejams
+urlfrom|pieejams no|pieejams no
+inpreparation|tiek gatavots|tiek gatavots
+submitted|iesniegts|iesniegts
+march|marts|marts
+may|maijs|maijs
+august|augusts|aug\adddot
+september|septembris|sept\adddot
+october|oktobris|okt\adddot
+november|novembris|nov\adddot
+december|decembris|dec\adddot
+langfinnish|somu|somu
+langrussian|krievu|krievu
+langswedish|zviedru|zviedru
+fromfinnish|no somu|no somu
+fromrussian|no krievu|no krievu
+fromswedish|no zviedru|no zviedru
+countryep|Eiropas Parlaments|EP
+countryfr|Francija|FR
+patent|patents|patents
+patenteu|Eiropas patents|Eiropas pat\adddot
+patentus|ASV patents|ASV pat\adddot
+file|fails|fails
+circa|ap|ap
+spring|pavasaris|pav\adddot
+summer|vasara|vas\adddot
+autumn|rudens|rud\adddot
+winter|ziema|ziema
+am|AM|AM
+pm|PM|PM
+dateyear|gada|g\adddot
diff --git a/citeproc/biblatex-localization/lithuanian.lbx.strings b/citeproc/biblatex-localization/lithuanian.lbx.strings
new file mode 100644
--- /dev/null
+++ b/citeproc/biblatex-localization/lithuanian.lbx.strings
@@ -0,0 +1,31 @@
+bibliography|Bibliografija|Bibliografija
+references|Literatūros sąrašas|Literatūra
+shorthands|Santrumpų sąrašas|Santrumpos
+editor|sudarytojas|sud\adddot
+editors|sudarytojai|sud\adddot
+compiler|parengėjas|pareng\adddot
+compilers|parengėjai|pareng\adddot
+redactor|redaktorius|red\adddot
+redactors|redaktoriai|red\adddot
+reviser|korektorius|kor\adddot
+revisers|korektoriai|kor\adddot
+founder|pradininkas|prad\adddot
+founders|pradininkai|prad\adddot
+continuator|tęsėjas|tęs\adddot
+continuators|tęsėjai|tęs\adddot
+collaborator|bendradarbis|bendr\adddot
+collaborators|bendradarbiai|bendr\adddot
+translator|vertėjas|vert\adddot
+translators|vertėjai|vert\adddot
+commentator|komentarų autorius|koment\adddotspace aut\adddot
+commentators|komentarų autoriai|koment\adddotspace aut\adddot
+annotator|paaiškinimų autorius|paaišk\adddotspace aut\adddot
+annotators|paaiškinimų autoriai|paaišk\adddotspace aut\adddot
+commentary|komentarai|koment\adddot
+annotations|paaiškinimai|paaišk\adddot
+introduction|įvadas|įv\adddot
+foreword|pratarmė|prat\adddot
+afterword|pabaigos žodis|pab\adddotspace žodis
+organizer|organizatorius|org\adddot
+organizers|organizatoriai|org\adddot
+byorganizer|organizavo|org\adddot
diff --git a/citeproc/biblatex-localization/magyar.lbx.strings b/citeproc/biblatex-localization/magyar.lbx.strings
new file mode 100644
--- /dev/null
+++ b/citeproc/biblatex-localization/magyar.lbx.strings
@@ -0,0 +1,29 @@
+bibliography|Irodalomjegyz\'ek|Irodalom
+references|Hivatkoz\'asok|Hivatkoz\'asok
+shorthands|R\"ovid\'it\'esek jegyz\'eke|R\"ovid\'it\'esek
+compiler|\"ossze\'all\'it\'o|\"ossze\'all\adddot
+compilers|\"ossze\'all\'it\'ok|\"ossze\'all\adddot
+reviser|korrektor|korr\adddot
+revisers|korrektorok|korr\adddot
+founder|alap\'it\'o|alap\adddot
+founders|alap\'it\'ok|alap\adddot
+%continuator||
+%continuators||
+translator|ford\'it\'o|ford\adddot
+translators|ford\'it\'ok|ford\adddot
+commentator|komment\'ator|komm\adddot
+commentators|komment\'atorok|komm\adddot
+annotator|jegyzetek \'ir\'oja|jegyz\adddot
+annotators|jegyzetek \'ir\'oi|jegyz\adddot
+commentary|komment\'ar|komm\adddot
+annotations|jegyzetek|jegyz\adddot
+introduction|bevezet\'es|bev\adddot
+afterword|ut\'osz\'o|ut\'osz\'o
+byorganizer|szervezte|szerv\adddot
+byauthor|\'irta|\'irta
+byeditor|szerkesztette|szerk\adddot
+bycompiler|\"ossze\'all\'itotta|\"ossze\'all\adddot
+byredactor|sajt\'o al\'a rendezte|kiad\adddot
+byreviser|jav\'itotta|jav\adddot
+byreviewer|b\'ir\'alta|b\'ir\adddot
+byfounder|alap\'itotta|alap\adddot
diff --git a/citeproc/biblatex-localization/naustrian.lbx.strings b/citeproc/biblatex-localization/naustrian.lbx.strings
new file mode 100644
--- /dev/null
+++ b/citeproc/biblatex-localization/naustrian.lbx.strings
@@ -0,0 +1,2 @@
+citedas|im Folgenden zitiert als|im Folgenden zit\adddotspace als
+january|J\"anner|J\"an\adddot
diff --git a/citeproc/biblatex-localization/newzealand.lbx.strings b/citeproc/biblatex-localization/newzealand.lbx.strings
new file mode 100644
--- /dev/null
+++ b/citeproc/biblatex-localization/newzealand.lbx.strings
diff --git a/citeproc/biblatex-localization/ngerman.lbx.strings b/citeproc/biblatex-localization/ngerman.lbx.strings
new file mode 100644
--- /dev/null
+++ b/citeproc/biblatex-localization/ngerman.lbx.strings
@@ -0,0 +1,1 @@
+citedas|im Folgenden zitiert als|im Folgenden zit\adddotspace als
diff --git a/citeproc/biblatex-localization/norsk.lbx.strings b/citeproc/biblatex-localization/norsk.lbx.strings
new file mode 100644
--- /dev/null
+++ b/citeproc/biblatex-localization/norsk.lbx.strings
@@ -0,0 +1,98 @@
+bibliography|Bibliografi|Bibliografi
+references|Referanser|Referanser
+shorthands|Forkortelser|Forkortelser
+compiler|kompilator|komp\adddot
+compilers|kompilatorer|komp\adddot
+redactor|bearbeidelse|bearb\adddot
+redactors|bearbeidelse|bearb\adddot
+reviser|revisjon|rev\adddot
+revisers|revisjon|rev\adddot
+founder|grunnlegger|grunnl\adddot
+founders|grunnleggere|grunnl\adddot
+collaborator|samarbeid|samarb\adddot
+collaborators|samarbeid|samarb\adddot
+translator|oversetter|overs\adddot
+translators|oversettere|overs\adddot
+commentator|kommentarer|komm\adddot
+commentators|kommentarer|komm\adddot
+annotator|forklaringer|forkl\adddot
+annotators|forklaringer|forkl\adddot
+commentary|kommentarer|komm\adddot
+annotations|forklaringer|forkl\adddot
+introduction|innledning|innl\adddot
+foreword|forord|forord
+afterword|etterord|etterord
+organizer|organisator|org\adddot
+organizers|organisatorer|org\adddot
+byorganizer|organisert av|org\adddotspace av
+byauthor|av|av
+byeditor|redigert av|red\adddotspace av
+bycompiler|kompilert av|komp\adddotspace av
+byredactor|bearbeidet av|bearb\adddotspace av
+byreviser|revidert av|rev\adddotspace av
+byreviewer|kritikk ved|krit\adddotspace ved
+byfounder|grunnlagt av|grunnl\adddotspace av
+bycollaborator|i samarbeid med|i samarb\adddotspace med
+bytranslator|oversatt \lbx@lfromlang\ av|overs\adddot\ \lbx@sfromlang\ av
+bycommentator|kommentert av|komm\adddot\ av
+byannotator|forklart av|forkl\adddot\ av
+withcommentator|med kommentarer av|med komm\adddot\ av
+withannotator|med forklaringer av|med forkl\adddot\ av
+withintroduction|med innledning av|med innl\adddot\ av
+withforeword|med forord av|med forord av
+withafterword|med etterord av|med etterord av
+and|og|og
+andothers|med flere|mfl\adddot
+andmore|med mer|m.m\adddot
+volume|bind|bd\adddot
+volumes|bind|bd\adddot
+involumes|i|i
+jourser|serie|ser\adddot
+book|bok|bok
+part|del|del
+issue|nummer|nr\adddot
+newseries|ny serie|ny ser\adddot
+oldseries|gammel serie|gl\adddotspace ser\adddot
+edition|utgave|utg\adddot
+reprint|opptrykk|opptr\adddot
+reprintof|opptrykk av|opptr\adddotspace av
+reprintas|trykt om som|tr\adddotspace om som
+reprintfrom|opptrykk fra|opptr\adddotspace fra
+translationof|oversettelse av|overs\adddotspace av
+translationas|oversatt som|overs\adddotspace som
+translationfrom|oversatt fra|overs\adddotspace fra
+reviewof|kritikk av|krit\adddotspace av
+origpubas|opprinnelig utgitt som|oppr\adddot\ utg\adddot\ som
+origpubin|opprinnelig utgitt i|oppr\adddot\ utg\adddot\ i
+astitle|som|som
+bypublisher|av|av
+nodate|udatert|udatert
+page|side|s\adddot
+pages|sider|s\adddot
+column|spalte|sp\adddot
+columns|spalter|sp\adddot
+line|linje|l\adddot
+lines|linjer|l\adddot
+verse|vers|v\adddot
+verses|vers|v\adddot
+section|avsnitt|avsn\adddot
+sections|avsnitt|avsn\adddot
+paragraph|avsnitt|avsn\adddot
+paragraphs|avsnitt|avsn\adddot
+pagetotal|side|s\adddot
+pagetotals|sider|s\adddot
+columntotal|spalte|sp\adddot
+columntotals|spalter|sp\adddot
+linetotal|linje|l\adddot
+linetotals|linjer|l\adddot
+versetotal|vers|v\adddot
+versetotals|vers|v\adddot
+sectiontotal|avsnitt|avsn\adddot
+sectiontotals|avsnitt|avsn\adddot
+paragraphtotal|avsnitt|avsn\adddot
+paragraphtotals|avsnitt|avsn\adddot
+in|i|i
+inseries|i|i
+ofseries|av|av
+number|nummer|nr\adddot
+chapter|kapittel|kap\adddot
diff --git a/citeproc/biblatex-localization/nswissgerman.lbx.strings b/citeproc/biblatex-localization/nswissgerman.lbx.strings
new file mode 100644
--- /dev/null
+++ b/citeproc/biblatex-localization/nswissgerman.lbx.strings
@@ -0,0 +1,2 @@
+citedas|im Folgenden zitiert als|im Folgenden zit\adddotspace als
+countryuk|Grossbritannien|GB
diff --git a/citeproc/biblatex-localization/nynorsk.lbx.strings b/citeproc/biblatex-localization/nynorsk.lbx.strings
new file mode 100644
--- /dev/null
+++ b/citeproc/biblatex-localization/nynorsk.lbx.strings
@@ -0,0 +1,28 @@
+references|Referansar|Referansar
+shorthands|Forkortingar|Forkortingar
+compilers|kompilatorar|komp\adddot
+redactor|omarbeiding|omarb\adddot
+redactors|omarbeiding|omarb\adddot
+founder|grunnleggjar|grunnl\adddot
+founders|grunnleggjarar|grunnl\adddot
+translator|omsetjar|oms\adddot
+translators|omsetjarar|oms\adddot
+commentator|kommentarar|komm\adddot
+commentators|kommentarar|komm\adddot
+annotator|forklaringar|forkl\adddot
+annotators|forklaringar|forkl\adddot
+commentary|kommentarar|komm\adddot
+annotations|forklaringar|forkl\adddot
+introduction|innleiing|innl\adddot
+organizers|organisatorar|org\adddot
+byredactor|omarbeidd av|omarb\adddotspace av
+withcommentator|med kommentarar av|med komm\adddot\ av
+withannotator|med forklaringar av|med forkl\adddot\ av
+withintroduction|med innleiing av|med innl\adddot\ av
+andothers|med fleire|mfl\adddot
+andmore|med meir|m.m\adddot
+oldseries|gamal serie|gl\adddotspace ser\adddot
+translationof|omsetjing av|oms\adddotspace av
+translationas|omsett som|oms\adddotspace som
+origpubas|opphavleg utgitt som|opph\adddot\ utg\adddot\ som
+origpubin|opphavleg utgitt i|opph\adddot\ utg\adddot\ i
diff --git a/citeproc/biblatex-localization/polish.lbx.strings b/citeproc/biblatex-localization/polish.lbx.strings
new file mode 100644
--- /dev/null
+++ b/citeproc/biblatex-localization/polish.lbx.strings
@@ -0,0 +1,100 @@
+bibliography|Bibliografia|Bibliografia
+references|Bibliografia|Bibliografia
+editor|redaktor|red\adddot
+editors|redaktorzy|red\adddot
+compiler|redaktor|red\adddot
+compilers|redaktorzy|red\adddot
+redactor|redaktor|red\adddot
+redactors|redaktorzy|red\adddot
+reviser|korektor|kor\adddot
+revisers|korektorzy|kor\adddot
+collaborator|uczestnik|ucz\adddot
+collaborators|uczestnicy|ucz\adddot
+translator|t\l umacz|t\l um\adddot
+translators|t\l umacze|t\l um\adddot
+commentator|komentator|kom\adddot
+commentators|komentatorzy|kom\adddot
+annotator|uwaga|uw\adddot
+annotators|uwagi|uw\adddot
+commentary|komentarz|kom\adddot
+annotations|komentarze|kom\adddot
+foreword|przedmowa|przedm\adddot
+afterword|pos\l owie|pos\l \adddot
+editortr|redaktor i t\l umacz|red\adddotspace i per\adddot
+editorstr|redaktorzy i t\l umacze|red\adddotspace i per\adddot
+editorco|redaktor i komentator|red\adddotspace i kom\adddot
+translatorco|t\l umacz i komentator|t\l um\adddotspace i kom\adddot
+translatorsco|t\l umacze i komentatorzy|t\l um\adddotspace i kom\adddot
+organizer|organizator|org\adddot
+organizers|organizatorzy|org\adddot
+byorganizer|organizowane|org\adddot
+byauthor|autorstwo|aut\adddot
+byeditor|redagowa\l|red\adddot
+byredactor|zredagowano|zred\adddot
+byreviser|poprawione|popr\adddot
+byreviewer|recenzja|rec\adddot
+bytranslator|t\l umaczenie \lbx@lfromlang|t\l um\adddotspace \lbx@sfromlang
+bycommentator|skomentowane przez|skom\adddot
+byannotator|uwagi od|uw\adddot
+withcommentator|komentarze|kom\adddot
+withannotator|uwagi|uw\adddot
+withforeword|przedmowa|przedm\adddot
+withafterword|pos\l owie|pos\l \adddot
+byeditoran|zredagowany i z uwagami|zredag\adddotspace i z uw\adddot
+byeditoraf|zredagowany, z pos\l owiem|zred., z pos\l \adddot
+byeditorcofo|zredagowany, komentarze i przedmowa|zred., kom\adddotspace i przedm\adddot
+byeditorcoaf|zredagowany, komentarze i pos\l owie|zred., kom\adddotspace i pos\l \adddot
+byeditoranfo|zredagowany, uwagi i przedmowa|zred., uw\adddotspace i przedm\adddot
+byeditoranaf|zredagowany, uwagi i pos\l owie|zred., uw\adddotspace i pos\l \adddot
+and|i|i
+andothers|i inni|i in\adddot
+andmore|i inni|i in\adddot
+volume|tom|t\adddot
+volumes|tomy|t\adddot
+involumes|w|w
+jourvol|tom|t\adddot
+jourser|seria|ser\adddot
+issue|wydanie|wyd\adddot
+newseries|nowa seria|now\adddotspace ser\adddot
+oldseries|stara seria|star\adddotspace ser\adddot
+edition|wydruk|wyd\adddot
+reprint|przedruk|przedr\adddot
+reprintof|przedruk|przedr\adddot
+reprintas|przedrukowano jako|przedr\adddotspace jako
+reprintfrom|przedrukowano z|przedr\adddotspace z
+translationof|t\l umaczenie|t\l um\adddot
+translationas|t\l umaczenie jako|t\l um\adddotspace jako
+translationfrom|t\l umaczenie z|t\l um\adddotspace z
+reviewof|recenzja na\addcolon|rec\adddotspace na\addcolon
+origpubin|pierwodruk wydano w|pierw\adddotspace wyd\adddotspace w
+astitle|pod tytu\l em|pod tyt\adddot
+page|strona|s\adddot
+pages|strony|s\adddot
+column|kolumna|kol\adddot
+columns|kolumny|kol\adddot
+line|linijka|l\adddot
+lines|linijki|l\adddot
+nodate|bez daty|b\adddot d\adddot
+verse|werset|wer\adddot
+verses|wersety|wer\adddot
+section|paragraf|par\adddot
+sections|paragrafy|par\adddot
+paragraph|akapit|akap\adddot
+paragraphs|akapity|akap\adddot
+pagetotal|strona|s\adddot
+pagetotals|strony|s\adddot
+columntotal|kolumna|kol\adddot
+columntotals|kolumny|kol\adddot
+linetotal|wers|wer\adddot
+linetotals|wersy|wer\adddot
+versetotal|wiersz|wier\adddot
+versetotals|wiersze|wier\adddot
+sectiontotal|paragraf|par\adddot
+sectiontotals|paragrafy|par\adddot
+paragraphtotal|akapit|akap\adddot
+paragraphtotals|akapit|akap\adddot
+in|w|w
+inseries|w|w
+ofseries|z|z
+number|numer|nr\adddot
+chapter|rozdzia\l |rozd\adddot
diff --git a/citeproc/biblatex-localization/portuges.lbx.strings b/citeproc/biblatex-localization/portuges.lbx.strings
new file mode 100644
--- /dev/null
+++ b/citeproc/biblatex-localization/portuges.lbx.strings
diff --git a/citeproc/biblatex-localization/portuguese.lbx.strings b/citeproc/biblatex-localization/portuguese.lbx.strings
new file mode 100644
--- /dev/null
+++ b/citeproc/biblatex-localization/portuguese.lbx.strings
@@ -0,0 +1,95 @@
+bibliography|Bibliografia|Bibliografia
+references|Refer\^encias|Refer\^encias
+shorthands|Lista de Abreviaturas|Abreviaturas
+editor|editor|ed\adddot
+editors|editores|eds\adddot
+compiler|compilador|comp\adddot
+compilers|compiladores|comp\adddot
+redactor|redator|red\adddot
+redactors|redatores|red\adddot
+reviser|revisor|rev\adddot
+revisers|revisores|rev\adddot
+founder|fundador|fund\adddot
+founders|fundadores|fund\adddot
+continuator|continuador|cont\adddot
+continuators|continuadores|cont\adddot
+collaborator|colaborador|col\adddot
+collaborators|colaboradores|col\adddot
+translator|tradutor|trad\adddot
+translators|tradutores|trad\adddot
+commentator|comentador|coment\adddot
+commentators|comentadores|coment\adddot
+annotator|anotador|anot\adddot
+annotators|anotadores|anot\adddot
+commentary|coment\'ario|coment\adddot
+annotations|notas|notas
+foreword|pref\'acio|pref\adddot
+afterword|posf\'acio|posf\adddot
+organizer|organizador|org\adddot
+organizers|organizadores|orgs\adddot
+byorganizer|organizado por|org\adddotspace por
+byauthor|por|por
+byeditor|editado por|ed\adddotspace por
+bycompiler|compilado por|comp\adddotspace por
+byredactor|redigido por|red\adddotspace por
+byreviser|revisto por|rev\adddotspace por
+byreviewer|resenhado por|res\adddotspace por
+byfounder|fundado por|fund\adddotspace por
+bycontinuator|continuado por|cont\adddotspace por
+bytranslator|traduzido \lbx@lfromlang\ por|trad\adddot\ \lbx@sfromlang\ por
+bycommentator|comentado por|coment\adddot\ por
+byannotator|notas de|notas de
+withcommentator|com coment\'arios de|com coment\adddot\ de
+withannotator|com notas de|com notas de
+withforeword|com pref\'acio de|com pref\adddot\ de
+withafterword|com posf\'acio de|com posf\adddot\ de
+and|e|e
+andothers|et\addabbrvspace al\adddot|et\addabbrvspace al\adddot
+andmore|et\addabbrvspace al\adddot|et\addabbrvspace al\adddot
+volume|volume|vol\adddot
+volumes|volumes|vols\adddot
+involumes|em|em
+jourvol|volume|vol\adddot
+jourser|s\'erie|s\'er\adddot
+book|livro|livro
+part|parte|parte
+issue|n\'umero|n\'umero
+newseries|nova s\'erie|nova s\'er\adddot
+oldseries|s\'erie antiga|s\'er\adddot\ antiga
+reprint|reimpress\~ao|reimpr\adddot
+reprintof|reimpress\~ao de|reimpr\adddotspace de
+reprintas|reimpresso como|reimpr\adddotspace como
+reprintfrom|reimpresso|reimpr\adddot
+translationas|traduzido como|trad\adddotspace como
+translationfrom|traduzido do|trad\adddotspace do
+reviewof|resenha de|res\adddotspace de
+origpubas|originalmente publicado como|orig\adddotspace pub\adddotspace como
+origpubin|originalmente publicado em|orig\adddotspace pub\adddotspace em
+astitle|como|como
+bypublisher|por|por
+nodate|sem data|s\adddot d\adddot
+page|p\'agina|p\adddot
+pages|p\'aginas|pp\adddot
+column|coluna|col\adddot
+columns|colunas|cols\adddot
+line|linha|l\adddot
+lines|linhas|ll\adddot
+verse|verso|v\adddot
+verses|versos|vv\adddot
+paragraph|par\'agrafo|par\adddot
+paragraphs|par\'agrafo|par\adddot
+pagetotal|p\'agina|p\adddot
+pagetotals|p\'aginas|pp\adddot
+columntotal|coluna|col\adddot
+columntotals|colunas|cols\adddot
+linetotal|linha|l\adddot
+linetotals|linhas|ll\adddot
+versetotal|verso|v\adddot
+versetotals|versos|vv\adddot
+paragraphtotal|par\'agrafo|par\adddot
+paragraphtotals|par\'agrafo|par\adddot
+in|em|em
+inseries|em|em
+ofseries|de|de
+number|n\'umero|n\adddot\textordmasculine
+chapter|cap\'\i tulo|cap\adddot
diff --git a/citeproc/biblatex-localization/russian.lbx.strings b/citeproc/biblatex-localization/russian.lbx.strings
new file mode 100644
--- /dev/null
+++ b/citeproc/biblatex-localization/russian.lbx.strings
@@ -0,0 +1,102 @@
+bibliography|Список литературы|Список литературы
+references|Список литературы|Список литературы
+shorthands|Список сокращений|Сокращения
+editor|редактор|ред\adddot
+editors|редакторы|ред\adddot
+compiler|составитель|сост\adddot
+compilers|составители|сост\adddot
+redactor|редактор|ред\adddot
+redactors|редакторы|ред\adddot
+reviser|ревизионный корректор|ревиз\adddotspace кор\adddot
+revisers|ревизионные корректоры|ревиз\adddotspace кор\adddot
+founder|основатель|осн\adddot
+founders|основатели|осн\adddot
+continuator|продолжатель|прод\adddot
+continuators|продолжатели|прод\adddot
+collaborator|участник|участ\adddot
+collaborators|участники|участ\adddot
+translator|переводчик|пер\adddot
+translators|переводчики|пер\adddot
+commentator|комментатор|коммент\adddot
+commentators|комментаторы|коммент\adddot
+annotator|примечания|примеч\adddot
+annotators|примечания|примеч\adddot
+commentary|комментарий|коммент\adddot
+annotations|примечания|примеч\adddot
+introduction|вступительная статья|вступ\adddotspace ст\adddot
+foreword|предисловие|предисл\adddot
+afterword|послесловие|послесл\adddot
+organizer|организатор|орг\adddot
+organizers|организаторы|орг\adddot
+byorganizer|организатор|орг\adddot
+byauthor||
+byeditor|под редакцией|под\addabbrvspace ред\adddot
+bycompiler|составитель|сост\adddot
+byredactor|под редакцией|под\addabbrvspace ред\adddot
+byreviser|исправлено|испр\adddot
+byreviewer|рецензия|рец\adddot
+byfounder|учредитель|учр\adddot
+bycontinuator|продолжение|продолж\adddot
+bycollaborator|при участии|при\addabbrvspace уч\adddot
+bytranslator|перевод \lbx@lfromlang|пер\adddot\ \lbx@sfromlang
+bycommentator|комментарии|коммент\adddot
+byannotator|примечания|примеч\adddot
+withcommentator|комментарии|коммент\adddot
+withannotator|примечания|примеч\adddot
+withintroduction|вступительная статья|вступ\adddotspace ст\adddot
+withforeword|предисловие|предисл\adddot
+withafterword|послесловие|послесл\adddot
+and|и|и
+andothers|и\addabbrvspace др\adddot|и\addabbrvspace др\adddot
+andmore|и\addabbrvspace др\adddot|и\addabbrvspace др\adddot
+volume|том|т\adddot
+volumes|томах|т\adddot
+involumes|в|в
+jourvol|том|т\adddot
+jourser|серия|сер\adddot
+book|книга|кн\adddot
+part|часть|ч\adddot
+issue|выпуск|вып\adddot
+newseries|новая серия|нов\adddotspace сер\adddot
+oldseries|старая серия|стар\adddotspace сер\adddot
+edition|издание|изд\adddot
+reprint|переиздание|переизд\adddot
+reprintof|переиздание|переизд\adddot
+reprintas|переиздано как|переизд\adddotspace как
+reprintfrom|переиздано с|переизд\adddotspace с
+translationof|перевод по изданию\addcolon|пер\adddotspace по изд\adddot\addcolon
+translationas|перевод\addcolon|пер\adddot\addcolon
+translationfrom|перевод с|пер\adddotspace с
+reviewof|рецензия на\addcolon|рец\adddotspace на\addcolon
+astitle|\addcolon|\addcolon
+bypublisher|\addcomma|\addcomma
+nodate|б\adddot г\adddot|б\adddot г\adddot
+page|страница|с\adddot
+pages|страницы|с\adddot
+column|колонка|кол\adddot
+columns|колонки|кол\adddot
+line|строка|строка
+lines|строки|строка
+verse|стих|стих
+verses|стихи|стихи
+section|параграф|\S
+sections|параграфы|\S\S
+paragraph|абзац|абз\adddot
+paragraphs|абзацы|абз\adddot
+pagetotal|страница|с\adddot
+pagetotals|страницы|с\adddot
+columntotal|колонка|кол\adddot
+columntotals|колонки|кол\adddot
+linetotal|строка|строка
+linetotals|строки|строка
+versetotal|стих|стих
+versetotals|стихи|стихи
+sectiontotal|параграф|\S
+sectiontotals|параграфы|\S\S
+paragraphtotal|абзац|абз\adddot
+paragraphtotals|абзацы|абз\adddot
+in|в|в
+inseries|в|в
+ofseries|из|из
+number|номер|№
+chapter|глава|гл\adddot
diff --git a/citeproc/biblatex-localization/serbian.lbx.strings b/citeproc/biblatex-localization/serbian.lbx.strings
new file mode 100644
--- /dev/null
+++ b/citeproc/biblatex-localization/serbian.lbx.strings
diff --git a/citeproc/biblatex-localization/serbianc.lbx.strings b/citeproc/biblatex-localization/serbianc.lbx.strings
new file mode 100644
--- /dev/null
+++ b/citeproc/biblatex-localization/serbianc.lbx.strings
diff --git a/citeproc/biblatex-localization/slovak.lbx.strings b/citeproc/biblatex-localization/slovak.lbx.strings
new file mode 100644
--- /dev/null
+++ b/citeproc/biblatex-localization/slovak.lbx.strings
@@ -0,0 +1,82 @@
+references|Referencie|Referencie
+shorthands|Zoznam skratiek|Skratky
+editor|editor|ed\adddot
+editors|editori|ed\adddot
+compilers|zostavovatelia|zost\adddot
+redactor|redaktor|red\adddot
+redactors|redaktori|red\adddot
+reviser|korektor|kor\adddot
+revisers|korektori|kor\adddot
+founders|zakladatelia|zakl\adddot
+translators|prekladatelia|prekl\adddot
+foreword|predhovor|predh\adddot
+afterword|doslov|dosl\adddot
+byauthor||
+withforeword|s\addnbspace predhovorom od|s\addnbspace predh\adddot\ od
+withafterword|s\addnbspace doslovom od|s\addnbspace dosl\adddot\ od
+and|a|a
+andothers|et\addabbrvspace al\adddot|et\addabbrvspace al\adddot
+andmore|et\addabbrvspace al\adddot|et\addabbrvspace al\adddot
+involumes|in|in
+book|kniha|kniha
+edition|vydanie|vyd\adddot
+reviewof|recenzia|recenz\adddot
+translationof|preklad|prekl\adddot
+astitle|ako|ako
+bypublisher||
+page|strana|s\adddot
+pages|strany|s\adddot
+line|riadok|r\adddot
+lines|riadky|r\adddot
+section|sekcia|\S
+sections|sekcie|\S\S
+paragraph|odsek|ods\adddot
+paragraphs|odseky|ods\adddot
+pagetotal|strana|s\adddot
+pagetotals|strany|s\adddot
+linetotal|riadok|r\adddot
+linetotals|riadky|r\adddot
+sectiontotal|sekcia|\S
+sectiontotals|sekcie|\S\S
+paragraphtotal|odsek|ods\adddot
+paragraphtotals|odseky|ods\adddot
+in|in|in
+inseries|in|in
+ofseries|z|z
+chapter|kapitola|kap\adddot
+datacd|CD-ROM|CD-ROM
+audiocd|audio CD|audio CD
+version|verzia|ver\adddot
+url|URL|URL
+idem|idem|idem
+idemsm|idem|idem
+idemsf|eadem|eadem
+idemsn|idem|idem
+idempm|eidem|eidem
+idempf|eaedem|eaedem
+idempn|eadem|eadem
+idempp|eidem|eidem
+ibidem|ibidem|ibid\adddot
+opcit|op\adddotspace cit\adddot|op\adddotspace cit\adddot
+loccit|loc\adddotspace cit\adddot|loc\adddotspace cit\adddot
+confer|cf\adddot|cf\adddot
+sequens|sq\adddot|sq\adddot
+sequentes|sqq\adddot|sqq\adddot
+passim|passim|pass\adddot
+march|marec|mar\adddot
+august|august|aug\adddot
+september|september|sept\adddot
+november|november|nov\adddot
+december|december|dec\adddot
+countryde|Nemecko|DE
+patent|patent|pat\adddot
+patentus|US patent|US pat\adddot
+abstract|abstrakt|abst\adddot
+annodomini|po Kristovi|po Kr\adddot
+beforechrist|pred Kristom|pred Kr\adddot
+circa|cirka|ca\adddot
+spring|jar|jar
+summer|leto|leto
+winter|zima|zima
+am|AM|AM
+pm|PM|PM
diff --git a/citeproc/biblatex-localization/slovene.lbx.strings b/citeproc/biblatex-localization/slovene.lbx.strings
new file mode 100644
--- /dev/null
+++ b/citeproc/biblatex-localization/slovene.lbx.strings
@@ -0,0 +1,28 @@
+bibliography|Literatura|Literatura
+references|Literatura|Literatura
+shorthands|Kratice|Kratice
+editor|urednik|ur\adddot
+editors|uredniki|ur\adddot
+compiler|sestavljalec|sest\adddot
+compilers|sestavljalci|sest\adddot
+redactor|redaktor|redaktor
+redactors|redaktorji|redaktorji
+reviser|korektor|korektor
+revisers|korektorji|korektorji
+founder|snovalec|snovalec
+founders|snovalci|snovalci
+continuator|nadaljevalec|nadaljevalec
+continuators|nadaljevalci|nadaljevalci
+collaborator|sodelavec|sod\adddot
+collaborators|sodelavci|sod\adddot
+translator|prevajalec|prev\adddot
+translators|prevajalci|prev\adddot
+commentator|komentator|komentator
+commentators|komentatorji|komentatorji
+annotator|anotator|anotator
+annotators|anotatorji|anotatorji
+commentary|komentar|komentar
+annotations|opombe|op\adddot
+introduction|uvod|uvod
+foreword|predgovor|predg\adddot
+afterword|spremna beseda|spr\adddotspace b\adddot
diff --git a/citeproc/biblatex-localization/slovenian.lbx.strings b/citeproc/biblatex-localization/slovenian.lbx.strings
new file mode 100644
--- /dev/null
+++ b/citeproc/biblatex-localization/slovenian.lbx.strings
diff --git a/citeproc/biblatex-localization/spanish.lbx.strings b/citeproc/biblatex-localization/spanish.lbx.strings
new file mode 100644
--- /dev/null
+++ b/citeproc/biblatex-localization/spanish.lbx.strings
@@ -0,0 +1,190 @@
+references|Referencias|Referencias
+shorthands|Lista de abreviaturas|Abreviaturas
+editor|edici\'on|ed\adddot
+editors|edici\'on|eds\adddot
+commentator|comentario|com\adddot
+commentators|comentarios|coms\adddot
+annotator|anotaciones|anot\adddot
+annotators|anotaciones|anots\adddot
+commentary|comentario|com\adddot
+annotations|notas|notas
+introduction|introducci\'on|intr\adddot
+foreword|pr\'ologo|pr\'ol\adddot
+organizer|organizaci\'on|org\adddot
+organizers|organizaci\'on|orgs\adddot
+byorganizer|organizado por|org\adddotspace por
+byauthor|de|de
+byeditor|editado por|ed\adddotspace por
+bycompiler|compilado por|comp\adddotspace por
+byredactor|redacci\'on de|red\adddotspace de
+byreviser|revisado por|rev\adddotspace por
+byfounder|fundado por|fund\adddotspace por
+bycontinuator|continuado por|cont\adddotspace por
+bytranslator|traducido \lbx@lfromlang\ por|trad\adddot \lbx@sfromlang\ por
+bycommentator|comentado por|com\adddotspace por
+byannotator|anotado por|anot\adddotspace por
+withcommentator|con comentario de|con com\adddotspace de
+withannotator|con notas de|con notas de
+withintroduction|con introduci\'on de|con intr\adddotspace de
+withforeword|con pr\'ologo de|con pr\'ol\adddotspace de
+and|y|y
+andothers|y~col\adddot|y~col\adddot
+andmore|et\adddotspace al\adddot|et\adddotspace al\adddot
+volume|volumen|vol\adddot
+volumes|vol\'umenes|vols\adddot
+involumes|en|en
+jourvol|volumen|vol\adddot
+jourser|\'epoca|\'ep\adddot
+book|libro|libro
+part|parte|parte
+issue|n\'umero|n\'um\adddot
+newseries|nueva \'epoca|n\adddotspace \'ep\adddot
+oldseries|antigua \'epoca|ant\adddotspace \'ep\adddot
+edition|edici\'on|ed\adddot
+reprintas|reimpreso como|reimp\adddotspace como
+translationas|traducido como|trad\adddotspace como
+translationfrom|traducido del|trad\adddotspace del
+origpubas|publicado originalmente como|pub\adddotspace orig\adddotspace como
+origpubin|publicado originalmente en|pub\adddot orig\adddot en
+bypublisher|por la editorial|por la ed\adddot
+page|p\'agina|p\'ag\adddot
+pages|p\'aginas|p\'ags\adddot
+column|columna|col\adddot
+columns|columnas|cols\adddot
+verse|verso|v\adddot
+verses|versos|vv\adddot
+sections|secciones|secs\adddot
+pagetotal|p\'agina|p\'ag\adddot
+pagetotals|p\'aginas|p\'ags\adddot
+columntotal|columna|col\adddot
+columntotals|columnas|cols\adddot
+versetotal|verso|v\adddot
+versetotals|versos|vv\adddot
+sectiontotals|secciones|secs\adddot
+in|en|en
+inseries|en|en
+ofseries|de|de
+number|n\'umero|n\sptext{o
+chapter|cap\'itulo|cap\adddot
+bathesis|Tesis de licenciatura|Tesis de lic\adddot
+phdthesis|Tesis doctoral|Tesis doct\adddot
+candthesis|Tesis de candidatura doctoral|Tesis de cand\adddotspace doct\adddot
+techreport|informe t\'ecnico|inf\adddotspace t\'ec\adddot
+software|programa|prog\adddot
+datacd|disco de datos|CD de datos
+audiocd|disco de audio|CD de audio
+version|versi\'on|ver\adddot
+url|direcci\'on|direcci\'on
+urlfrom|disponible desde|disp\adddotspace desde
+urlseen|visitado|visitado
+submitted|enviado|enviado
+forthcoming|pr\'oximamente|prox\adddot
+inpress|en prensa|en prensa
+prepublished|previamente publicado|prepublicado
+citedas|citado en adelante como|cit\adddotspace en adelante como
+thiscite|especialmente|esp\adddot
+seenote|ver nota|ver n\adddot
+quotedin|citado en|cit\adddotspace en
+loccit|loc\adddotspace cit\adddot|loc\adddot cit\adddot
+confer|cf\adddot|cf\adddot
+sequens|s\adddot|s\adddot
+sequentes|ss\adddot|ss\adddot
+passim|p\'assim|p\'assim
+see|v\'ease|vid\adddot
+seealso|v\'ease tambi\'en|vid\adddotspace tambi\'en
+backrefpage|v\'ease p\'agina|vid\adddotspace p\'ag\adddot
+backrefpages|v\'eanse p\'aginas|vid\adddotspace p\'ags\adddot
+january|enero|ene\adddot
+february|febrero|feb\adddot
+march|marzo|mar\adddot
+april|abril|abr\adddot
+may|mayo|mayo
+june|junio|jun\adddot
+july|julio|jul\adddot
+august|agosto|ago\adddot
+september|septiembre|sep\adddot
+october|octubre|oct\adddot
+november|noviembre|nov\adddot
+december|diciembre|dic\adddot
+langbrazilian|brasile\~no|brasile\~no
+langbulgarian|b\'ulgaro|b\'ulgaro
+langcroatian|croata|croata
+langczech|checo|checo
+langdanish|dan\'es|dan\'es
+langdutch|neerland\'es|neerland\'es
+langenglish|ingl\'es|ingl\'es
+langestonian|estonio|estonio
+langfrench|franc\'es|franc\'es
+langgalician|gallego|gallego
+langgerman|alem\'an|alem\'an
+langgreek|griego|griego
+langhungarian|h\'ungaro|h\'ungaro
+langitalian|italiano|italiano
+langjapanese|japon\'es|japon\'es
+langlatvian|lituano|lituano
+langnorwegian|noruego|noruego
+langpolish|polaco|polaco
+langportuguese|portugu\'es|portugu\'es
+langrussian|ruso|ruso
+langslovak|eslovaco|eslovaco
+langslovene|esloveno|esloveno
+langspanish|espa\~nol|espa\~nol
+langswedish|sueco|sueco
+langukrainian|ucraniano|ucraniano
+frombrazilian|del brasile\~no|del brasile\~no
+frombulgarian|del b\'ulgaro|del b\'ulgaro
+fromcroatian|del croata|del croata
+fromczech|del checo|del checo
+fromdanish|del dan\'es|del dan\'es
+fromdutch|del neerland\'es|del neerland\'es
+fromenglish|del ingl\'es|del ingl\'es
+fromestonian|del estonio|del estonio
+fromfrench|del franc\'es|del franc\'es
+fromgalician|del gallego|del gallego
+fromgerman|del alem\'an|del alem\'an
+fromgreek|del griego|del griego
+fromhungarian|del h\'ungaro|del h\'ungaro
+fromitalian|del italiano|del italiano
+fromjapanese|del japon\'es|del japon\'es
+fromlatvian|del lituano|del lituano
+fromnorwegian|del noruego|del noruego
+frompolish|del polaco|del polaco
+fromportuguese|del portugu\'es|del portugu\'es
+fromrussian|del ruso|del ruso
+fromslovak|del eslovaco|del eslovaco
+fromslovene|del esloveno|del esloveno
+fromspanish|del espa\~nol|del espa\~nol
+fromswedish|del sueco|del sueco
+fromukrainian|del ucraniano|del ucraniano
+countryde|Alemania|DE
+countryeu|Uni\'on Europea|EU
+countryep|Uni\'on Europea|EP
+countryfr|Francia|FR
+countryuk|Reino Unido|GB
+countryus|Estados Unidos|US
+patent|patente|pat\adddot
+patentde|patente alemana|pat\adddotspace alemana
+patenteu|patente europea|pat\adddotspace europea
+patentfr|patente francesa|pat\adddotspace francesa
+patentuk|patente brit\'anica|pat\adddotspace brit\'anica
+patentus|patente estadounidense|pat\adddotspace estadounidense
+patreq|solicitud de patente|sol\adddotspace de pat\adddot
+patreqde|solicitud de patente alemana|sol\adddotspace de pat\adddot alemana
+patreqeu|solicitud de patente europea|sol\adddotspace de pat\adddot europea
+patreqfr|solicitud de patente francesa|sol\adddotspace de pat\adddot francesa
+patrequk|solicitud de patente brit\'anica|sol\adddotspace de pat\adddot brit\'anica
+patrequs|solicitud de patente estadounidense|sol\adddotspace de pat\adddot estadounidense
+file|archivo|archivo
+library|biblioteca|bibl\adddot
+abstract|resumen|resumen
+commonera|era com\'un|e\adddotspace c\adddot
+beforecommonera|antes de la era com\'un|a\adddotspace e\adddotspace c\adddot
+annodomini|despu\'es de Cristo|d\adddotspace C\adddot
+beforechrist|antes de Cristo|a\adddotspace C\adddot
+circa|circa|ca\adddot
+spring|primavera|prim\adddot
+summer|verano|ver\adddot
+autumn|oto\~no|ot\adddot
+winter|invierno|inv\adddot
+am|a\adddotspace m\adddot|a\adddot m\adddot
+pm|p\adddotspace m\adddot|p\adddot m\adddot
diff --git a/citeproc/biblatex-localization/swedish.lbx.strings b/citeproc/biblatex-localization/swedish.lbx.strings
new file mode 100644
--- /dev/null
+++ b/citeproc/biblatex-localization/swedish.lbx.strings
@@ -0,0 +1,9 @@
+bibliography|Litteraturf\"orteckning|Litteratur
+references|Referenser|Referenser
+shorthands|F\"orkortningar|F\"orkortningar
+editor|utgivare|utg\adddot
+editors|utgivare|utg\adddot
+compiler|sammanst\"allare|sammanst\adddot
+compilers|sammanst\"allare|sammanst\adddot
+redactor|redakt\"or|red\adddot
+redactors|redakt\"orer|red\adddot
diff --git a/citeproc/biblatex-localization/swissgerman.lbx.strings b/citeproc/biblatex-localization/swissgerman.lbx.strings
new file mode 100644
--- /dev/null
+++ b/citeproc/biblatex-localization/swissgerman.lbx.strings
@@ -0,0 +1,1 @@
+countryuk|Grossbritannien|GB
diff --git a/citeproc/biblatex-localization/turkish.lbx.strings b/citeproc/biblatex-localization/turkish.lbx.strings
new file mode 100644
--- /dev/null
+++ b/citeproc/biblatex-localization/turkish.lbx.strings
@@ -0,0 +1,157 @@
+references|Kaynaklar|Kaynaklar
+shorthands|K\i saltmalar dizini|K\i saltmalar
+compiler|derleyen|der\adddot
+compilers|derleyenler|der\adddot
+redactor|yay\i na haz\i rlayan|yay\adddot\ haz\adddot
+redactors|yay\i na haz\i rlayanlar|yay\adddot\ haz\adddot
+reviser|tashih eden|tashih\adddot
+revisers|tashih edenler|tashih\adddot
+founder|kurucu|kur\adddot
+founders|kurucular|kur\adddot
+continuator|tamamlayan|tam\adddot
+continuators|tamamlayanlar|tam\adddot
+collaborator|ortak|ortak
+collaborators|ortaklar|ortaklar
+commentator|yorumlayan|yrm\adddot
+commentators|yorumlayanlar|yrm\adddot
+commentary|yorum|yrm\adddot
+byauthor|yazar|yazar
+bycompiler|derleyen|der\adddot
+byredactor|yay\i na haz\i rlayan|yay\adddot\ haz\adddot
+byreviser|tashih|tashih
+byfounder|kurucu|kur\adddot
+bycontinuator|tamamlayan|tam\adddot
+bycommentator|yorumlayan|yrm\adddot
+withcommentator|yorumlar\i yla katk\i da bulunan|yrm\adddot\ kat\adddot\ bul\adddot
+and|ve|ve
+volume|cilt|c\adddot
+volumes|cilt|c\adddot
+jourvol|cilt|c\adddot
+jourser|seri|seri
+book|kitap|kitap
+part|k\i s\i m|k\i s\i m
+issue|say\i|say\i
+newseries|yeni seri|yeni seri
+oldseries|eski seri|eski seri
+edition|bask\i|bs\adddot
+reprint|yeni bask\i s\i|yeni bask\i s\i
+reprintof|yeni bask\i s\i|yeni bask\i s\i
+reprintas|yeni bask\i s\i|yeni bask\i s\i
+reprintfrom|yeni bask\i s\i|yeni bask\i s\i
+reviewof|derlenen eser|der\adddot\ eser
+origpubas|as\i l eser|as\i l eser
+origpubin|as\i l eser yay\i n tarihi|as\i l eser yay\i n tarihi
+bypublisher|yay\i n evi|yay\i n evi
+nodate|tarih yok|t\adddot y\adddot
+page|sayfa|s\adddot
+pages|sayfalar|ss\adddot
+line|sat\i r|sat\adddot
+lines|sat\i rlar|sat\adddot
+verse|m\i sra|m\i s\adddot
+verses|m\i sralar|m\i s\adddot
+paragraph|paragraf|par\adddot
+paragraphs|paragraflar|par\adddot
+pagetotal|toplam sayfa|s\adddot
+pagetotals|toplam sayfalar|ss\adddot
+linetotal|toplam sat\i r|sat\adddot
+linetotals|toplam sat\i rlar|sat\adddot
+versetotal|toplam m\i sra|m\i s\adddot
+versetotals|toplam m\i sralar|m\i s\adddot
+paragraphtotal|toplam paragraf|par\adddot
+paragraphtotals|toplam paragraflar|par\adddot
+inseries|serilerde|serilerde
+ofseries|serilerde|serilerde
+number|numara|no\adddot
+bathesis|lisans tezi|lis\adddot\ tezi
+phdthesis|doktora tezi|dok\adddot\ tezi
+candthesis|aday tezi|aday tezi
+techreport|teknik rapor|tek\adddot\ rap\adddot
+software|bilgisayar yaz\i l\i m\i|bilg\adddot\ yaz\adddot
+datacd|CD|CD
+audiocd|ses CD'si|ses CD'si
+version|versiyon|ver\adddot
+forthcoming|yak\i nda|yak\i nda
+prepublished|taslak bas\i m\i|taslak bas\i m\i
+citedas|at\i f olarak|at\i f olarak
+seenote|nota bak\i n\i z|nota bkz\adddot
+quotedin|al\i nt\i|al\i nt\i
+idem|ayn\i|ayn\i
+idemsm|ayn\i|ayn\i
+idemsf|ayn\i|ayn\i
+idemsn|ayn\i|ayn\i
+idempm|ayn\i lar\i|ayn\i lar\i
+idempf|ayn\i lar\i|ayn\i lar\i
+idempn|ayn\i lar\i|ayn\i lar\i
+idempp|ayn\i lar\i|ayn\i lar\i
+loccit|at\i f yap\i lan yer|at\i f yap\adddot\ yer
+sequens|takip eden|takip eden
+sequentes|takip eden|takip eden
+passim|rastgele|rastgele
+see|bak\i n\i z|bkz\adddot
+seealso|ayr\i ca bak\i n\i z|ayr\i ca bkz\adddot
+january|Ocak|Ocak
+march|Mart|Mar\adddot
+april|Nisan|Nis\adddot
+may|May\i s|May\adddot
+june|Haziran|Haz\adddot
+july|Temmuz|Tem\adddot
+october|Ekim|Ekim
+november|Kas\i m|Kas\adddot
+december|Aral\i k|Ara\adddot
+langamerican|Amerikanca|Amerikanca
+langbrazilian|Brezilyanca|Brezilyanca
+langbulgarian|Bulgarca|Bulgarca
+langcatalan|Katalanca|Katalanca
+langdanish|Danimarkanca|Danimarkanca
+langestonian|Estonca|Estonca
+langfinnish|Fince|Fince
+langfrench|Frans\i zca|Frans\i zca
+langgalician|Galce|Galce
+langgerman|Almanca|Almanca
+langgreek|Yunanca|Yunanca
+langhungarian|Macarca|Macarca
+langjapanese|Japonca|Japonca
+langlatin|Latince|Latince
+langlatvian|Letonca|Letonca
+langlithuanian|Litvanca|Litvanca
+langpolish|Polonyaca|Polonyaca
+langportuguese|Portekizce|Portekizce
+langslovene|Slovence|Slovence
+langukrainian|Ukraynaca|Ukraynaca
+fromamerican|Amerikanca'dan|Amerikanca'dan
+frombrazilian|Brezilyanca'dan|Brezilyanca'dan
+frombulgarian|Bulgarca'dan|Bulgarca'dan
+fromcatalan|Katalanca'dan|Katalanca'dan
+fromdanish|Danimarkanca'dan|Danimarkanca'dan
+fromestonian|Estonyaca'dan|Estonyaca'dan
+fromfinnish|Fince'den|Fince'den
+fromfrench|Frans\i zca'dan|Frans\i zca'dan
+fromgalician|Galyaca'dan|Galyaca'dan
+fromgerman|Almanca'dan|Almanca'dan
+fromgreek|Yunanca'dan|Yunanca'dan
+fromhungarian|Macarca'dan|Macarca'dan
+fromjapanese|Japonca'dan|Japonca'dan
+fromlatin|Latince'den|Latince'den
+fromlatvian|Latvianca'dan|Latvianca'dan
+fromlithuanian|Litvanca'dan|Litvanca'dan
+frompolish|Polonyaca'dan|Polonyaca'dan
+fromportuguese|Portekizce'den|Portekizce'den
+fromslovene|Slovence'den|Slovence'den
+fromukrainian|Ukraynaca'dan|Ukraynaca'dan
+countryde|Almanya|DE
+countryfr|Fransa|FR
+patent|patent|pat\adddot
+patentde|Alman patenti|Alman pat\adddot
+patenteu|Avrupa patenti|Avrupa pat\adddot
+patentfr|Frans\i z patenti|Frans\i z pat\adddot
+patentus|Amerika patenti|Amerika pat\adddot
+patreq|patent beklemede|pat\adddot\ bek\adddot
+patreqde|Alman patenti beklemede|Alman pat\adddot\ bek\adddot
+patreqeu|Avrupa patenti beklemede|Avrupa pat\adddot\ bek\adddot
+patreqfr|Frans\i z patenti beklemede|Frans\i z pat\adddot\ bek\adddot
+patrequs|Amerika patenti beklemede|Amerika pat\adddot\ bek\adddot
+file|dosya|dosya
+commonera|milattan sonra|MS
+annodomini|milattan sonra|MS
+summer|Yaz|Yaz
+autumn|Sonbahar|Sonbahar
diff --git a/citeproc/biblatex-localization/ukrainian.lbx.strings b/citeproc/biblatex-localization/ukrainian.lbx.strings
new file mode 100644
--- /dev/null
+++ b/citeproc/biblatex-localization/ukrainian.lbx.strings
@@ -0,0 +1,102 @@
+bibliography|Перелік літератури|Література
+references|Перелік літератури|Література
+shorthands|Перелік скорочень|Скорочення
+editor|редактор|ред\adddot
+editors|редактори|ред\adddot
+compiler|укладач|уклад\adddot
+compilers|укладачі|уклад\adddot
+redactor|редактор|ред\adddot
+redactors|редактори|ред\adddot
+reviser|ревізійний коректор|ревіз\adddotspace кор\adddot
+revisers|ревізійні коректори|ревіз\adddotspace кор\adddot
+founder|засновник|засн\adddot
+founders|засновник|засн\adddot
+continuator|продовжувач|прод\adddot
+continuators|продовжувачі|прод\adddot
+collaborator|учасник|учас\adddot
+collaborators|учасники|учас\adddot
+translator|перекладач|пер\adddot
+translators|перекладачі|пер\adddot
+commentator|коментатор|комент\adddot
+commentators|коментатори|комент\adddot
+annotator|примітки|прим\adddot
+annotators|примітки|прим\adddot
+commentary|коментар|комент\adddot
+annotations|примітки|прим\adddot
+introduction|вступна стаття|вступ\adddotspace ст\adddot
+foreword|передмова|передм\adddot
+afterword|післямова|післям\adddot
+organizer|організатор|орг\adddot
+organizers|організатори|орг\adddot
+byorganizer|організатор|орг\adddot
+byauthor|згідно автора|згідн\adddot авт\adddot
+byeditor|за редакцією|за\addabbrvspace ред\adddot
+bycompiler|укладач|уклад\adddot
+byredactor|за редакцією|за\addabbrvspace ред\adddot
+byreviser|виправлено|випр\adddot
+byreviewer|рецензія|рец\adddot
+byfounder|засновник|засн\adddot
+bycontinuator|продовження|продовж\adddot
+bycollaborator|за участю|за\addabbrvspace уч\adddot
+bytranslator|переклад \lbx@lfromlang|пер\adddot\ \lbx@sfromlang
+bycommentator|коментарі|комент\adddot
+byannotator|примітки|прим\adddot
+withcommentator|коментарі|комент\adddot
+withannotator|примітки|прим\adddot
+withintroduction|вступна стаття|вступ\adddotspace ст\adddot
+withforeword|передмовие|передм\adddot
+withafterword|післямовие|післям\adddot
+and|та|та
+andothers|та\addabbrvspace ін\adddot|та\addabbrvspace ін\adddot
+andmore|та\addabbrvspace ін\adddot|та\addabbrvspace ін\adddot
+volume|том|т\adddot
+volumes|томах|т\adddot
+involumes|в|в
+jourvol|том|т\adddot
+jourser|серія|сер\adddot
+book|книга|кн\adddot
+part|частина|ч\adddot
+issue|випуск|вип\adddot
+newseries|нова серія|нов\adddotspace сер\adddot
+oldseries|стара серія|стар\adddotspace сер\adddot
+edition|видання|вид\adddot
+reprint|перевидання|перевид\adddot
+reprintof|перевидання|перевид\adddot
+reprintas|перевидано як|перевид\adddotspace як
+reprintfrom|перевидано з|перевид\adddotspace з
+translationof|переклад по виданню\addcolon|пер\adddotspace по вид\adddot\addcolon
+translationas|переклад\addcolon|пер\adddot\addcolon
+translationfrom|переклад з|пер\adddotspace з
+reviewof|рецензія на\addcolon|рец\adddotspace на\addcolon
+astitle|\addcolon|\addcolon
+bypublisher|\addcomma|\addcomma
+nodate|б\adddot р\adddot|б\adddot р\adddot
+page|сторінка|с\adddot
+pages|сторінки|с\adddot
+column|колонка|кол\adddot
+columns|колонки|кол\adddot
+line|рядок|рядок
+lines|рядки|рядки
+verse|вірш|вірш
+verses|вірші|вірші
+section|параграф|\S
+sections|параграфи|\S\S
+paragraph|абзац|абз\adddot
+paragraphs|абзаци|абз\adddot
+pagetotal|сторінка|с\adddot
+pagetotals|сторінки|с\adddot
+columntotal|колонка|кол\adddot
+columntotals|колонки|кол\adddot
+linetotal|рядок|рядок
+linetotals|рядки|рядки
+versetotal|вірш|вірш
+versetotals|вірші|вірші
+sectiontotal|параграф|\S
+sectiontotals|параграфи|\S\S
+paragraphtotal|абзац|абз\adddot
+paragraphtotals|абзаци|абз\adddot
+in|в|в
+inseries|в|в
+ofseries|із|із
+number|номер|№
+chapter|глава|гл\adddot
diff --git a/data/LaTeXMathML.js b/data/LaTeXMathML.js
deleted file mode 100644
--- a/data/LaTeXMathML.js
+++ /dev/null
@@ -1,198 +0,0 @@
-/*
-LaTeXMathML.js from http://math.etsu.edu/LaTeXMathML/
-Adapted by Jeff Knisely and Douglas Woodall from ASCIIMathML.js v. 1.4.7,
-(c) 2005 Peter Jipsen http://www.chapman.edu/~jipsen.
-Released under the GNU General Public License version 2 or later.
-See the GNU General Public License (at http://www.gnu.org/copyleft/gpl.html)
-for more details.
-*/
-var checkForMathML=true;var notifyIfNoMathML=true;var alertIfNoMathML=false;var mathcolor="";var mathfontfamily="";var showasciiformulaonhover=true;var isIE=document.createElementNS==null;if(document.getElementById==null)
-alert("This webpage requires a recent browser such as \nMozilla/Netscape 7+ or Internet Explorer 6+MathPlayer")
-function AMcreateElementXHTML(t){if(isIE)return document.createElement(t);else return document.createElementNS("http://www.w3.org/1999/xhtml",t);}
-function AMnoMathMLNote(){var nd=AMcreateElementXHTML("h3");nd.setAttribute("align","center")
-nd.appendChild(AMcreateElementXHTML("p"));nd.appendChild(document.createTextNode("To view the "));var an=AMcreateElementXHTML("a");an.appendChild(document.createTextNode("LaTeXMathML"));an.setAttribute("href","http://www.maths.nott.ac.uk/personal/drw/lm.html");nd.appendChild(an);nd.appendChild(document.createTextNode(" notation use Internet Explorer 6+"));an=AMcreateElementXHTML("a");an.appendChild(document.createTextNode("MathPlayer"));an.setAttribute("href","http://www.dessci.com/en/products/mathplayer/download.htm");nd.appendChild(an);nd.appendChild(document.createTextNode(" or Netscape/Mozilla/Firefox"));nd.appendChild(AMcreateElementXHTML("p"));return nd;}
-function AMisMathMLavailable(){if(navigator.appName.slice(0,8)=="Netscape")
-if(navigator.appVersion.slice(0,1)>="5")return null;else return AMnoMathMLNote();else if(navigator.appName.slice(0,9)=="Microsoft")
-try{var ActiveX=new ActiveXObject("MathPlayer.Factory.1");return null;}catch(e){return AMnoMathMLNote();}
-else return AMnoMathMLNote();}
-var AMcal=[0xEF35,0x212C,0xEF36,0xEF37,0x2130,0x2131,0xEF38,0x210B,0x2110,0xEF39,0xEF3A,0x2112,0x2133,0xEF3B,0xEF3C,0xEF3D,0xEF3E,0x211B,0xEF3F,0xEF40,0xEF41,0xEF42,0xEF43,0xEF44,0xEF45,0xEF46];var AMfrk=[0xEF5D,0xEF5E,0x212D,0xEF5F,0xEF60,0xEF61,0xEF62,0x210C,0x2111,0xEF63,0xEF64,0xEF65,0xEF66,0xEF67,0xEF68,0xEF69,0xEF6A,0x211C,0xEF6B,0xEF6C,0xEF6D,0xEF6E,0xEF6F,0xEF70,0xEF71,0x2128];var AMbbb=[0xEF8C,0xEF8D,0x2102,0xEF8E,0xEF8F,0xEF90,0xEF91,0x210D,0xEF92,0xEF93,0xEF94,0xEF95,0xEF96,0x2115,0xEF97,0x2119,0x211A,0x211D,0xEF98,0xEF99,0xEF9A,0xEF9B,0xEF9C,0xEF9D,0xEF9E,0x2124];var CONST=0,UNARY=1,BINARY=2,INFIX=3,LEFTBRACKET=4,RIGHTBRACKET=5,SPACE=6,UNDEROVER=7,DEFINITION=8,TEXT=9,BIG=10,LONG=11,STRETCHY=12,MATRIX=13;var AMsqrt={input:"\\sqrt",tag:"msqrt",output:"sqrt",ttype:UNARY},AMroot={input:"\\root",tag:"mroot",output:"root",ttype:BINARY},AMfrac={input:"\\frac",tag:"mfrac",output:"/",ttype:BINARY},AMover={input:"\\stackrel",tag:"mover",output:"stackrel",ttype:BINARY},AMatop={input:"\\atop",tag:"mfrac",output:"",ttype:INFIX},AMchoose={input:"\\choose",tag:"mfrac",output:"",ttype:INFIX},AMsub={input:"_",tag:"msub",output:"_",ttype:INFIX},AMsup={input:"^",tag:"msup",output:"^",ttype:INFIX},AMtext={input:"\\mathrm",tag:"mtext",output:"text",ttype:TEXT},AMmbox={input:"\\mbox",tag:"mtext",output:"mbox",ttype:TEXT};var AMsymbols=[{input:"\\alpha",tag:"mi",output:"\u03B1",ttype:CONST},{input:"\\beta",tag:"mi",output:"\u03B2",ttype:CONST},{input:"\\gamma",tag:"mi",output:"\u03B3",ttype:CONST},{input:"\\delta",tag:"mi",output:"\u03B4",ttype:CONST},{input:"\\epsilon",tag:"mi",output:"\u03B5",ttype:CONST},{input:"\\varepsilon",tag:"mi",output:"\u025B",ttype:CONST},{input:"\\zeta",tag:"mi",output:"\u03B6",ttype:CONST},{input:"\\eta",tag:"mi",output:"\u03B7",ttype:CONST},{input:"\\theta",tag:"mi",output:"\u03B8",ttype:CONST},{input:"\\vartheta",tag:"mi",output:"\u03D1",ttype:CONST},{input:"\\iota",tag:"mi",output:"\u03B9",ttype:CONST},{input:"\\kappa",tag:"mi",output:"\u03BA",ttype:CONST},{input:"\\lambda",tag:"mi",output:"\u03BB",ttype:CONST},{input:"\\mu",tag:"mi",output:"\u03BC",ttype:CONST},{input:"\\nu",tag:"mi",output:"\u03BD",ttype:CONST},{input:"\\xi",tag:"mi",output:"\u03BE",ttype:CONST},{input:"\\pi",tag:"mi",output:"\u03C0",ttype:CONST},{input:"\\varpi",tag:"mi",output:"\u03D6",ttype:CONST},{input:"\\rho",tag:"mi",output:"\u03C1",ttype:CONST},{input:"\\varrho",tag:"mi",output:"\u03F1",ttype:CONST},{input:"\\varsigma",tag:"mi",output:"\u03C2",ttype:CONST},{input:"\\sigma",tag:"mi",output:"\u03C3",ttype:CONST},{input:"\\tau",tag:"mi",output:"\u03C4",ttype:CONST},{input:"\\upsilon",tag:"mi",output:"\u03C5",ttype:CONST},{input:"\\phi",tag:"mi",output:"\u03C6",ttype:CONST},{input:"\\varphi",tag:"mi",output:"\u03D5",ttype:CONST},{input:"\\chi",tag:"mi",output:"\u03C7",ttype:CONST},{input:"\\psi",tag:"mi",output:"\u03C8",ttype:CONST},{input:"\\omega",tag:"mi",output:"\u03C9",ttype:CONST},{input:"\\Gamma",tag:"mo",output:"\u0393",ttype:CONST},{input:"\\Delta",tag:"mo",output:"\u0394",ttype:CONST},{input:"\\Theta",tag:"mo",output:"\u0398",ttype:CONST},{input:"\\Lambda",tag:"mo",output:"\u039B",ttype:CONST},{input:"\\Xi",tag:"mo",output:"\u039E",ttype:CONST},{input:"\\Pi",tag:"mo",output:"\u03A0",ttype:CONST},{input:"\\Sigma",tag:"mo",output:"\u03A3",ttype:CONST},{input:"\\Upsilon",tag:"mo",output:"\u03A5",ttype:CONST},{input:"\\Phi",tag:"mo",output:"\u03A6",ttype:CONST},{input:"\\Psi",tag:"mo",output:"\u03A8",ttype:CONST},{input:"\\Omega",tag:"mo",output:"\u03A9",ttype:CONST},{input:"\\frac12",tag:"mo",output:"\u00BD",ttype:CONST},{input:"\\frac14",tag:"mo",output:"\u00BC",ttype:CONST},{input:"\\frac34",tag:"mo",output:"\u00BE",ttype:CONST},{input:"\\frac13",tag:"mo",output:"\u2153",ttype:CONST},{input:"\\frac23",tag:"mo",output:"\u2154",ttype:CONST},{input:"\\frac15",tag:"mo",output:"\u2155",ttype:CONST},{input:"\\frac25",tag:"mo",output:"\u2156",ttype:CONST},{input:"\\frac35",tag:"mo",output:"\u2157",ttype:CONST},{input:"\\frac45",tag:"mo",output:"\u2158",ttype:CONST},{input:"\\frac16",tag:"mo",output:"\u2159",ttype:CONST},{input:"\\frac56",tag:"mo",output:"\u215A",ttype:CONST},{input:"\\frac18",tag:"mo",output:"\u215B",ttype:CONST},{input:"\\frac38",tag:"mo",output:"\u215C",ttype:CONST},{input:"\\frac58",tag:"mo",output:"\u215D",ttype:CONST},{input:"\\frac78",tag:"mo",output:"\u215E",ttype:CONST},{input:"\\pm",tag:"mo",output:"\u00B1",ttype:CONST},{input:"\\mp",tag:"mo",output:"\u2213",ttype:CONST},{input:"\\triangleleft",tag:"mo",output:"\u22B2",ttype:CONST},{input:"\\triangleright",tag:"mo",output:"\u22B3",ttype:CONST},{input:"\\cdot",tag:"mo",output:"\u22C5",ttype:CONST},{input:"\\star",tag:"mo",output:"\u22C6",ttype:CONST},{input:"\\ast",tag:"mo",output:"\u002A",ttype:CONST},{input:"\\times",tag:"mo",output:"\u00D7",ttype:CONST},{input:"\\div",tag:"mo",output:"\u00F7",ttype:CONST},{input:"\\circ",tag:"mo",output:"\u2218",ttype:CONST},{input:"\\bullet",tag:"mo",output:"\u2022",ttype:CONST},{input:"\\oplus",tag:"mo",output:"\u2295",ttype:CONST},{input:"\\ominus",tag:"mo",output:"\u2296",ttype:CONST},{input:"\\otimes",tag:"mo",output:"\u2297",ttype:CONST},{input:"\\bigcirc",tag:"mo",output:"\u25CB",ttype:CONST},{input:"\\oslash",tag:"mo",output:"\u2298",ttype:CONST},{input:"\\odot",tag:"mo",output:"\u2299",ttype:CONST},{input:"\\land",tag:"mo",output:"\u2227",ttype:CONST},{input:"\\wedge",tag:"mo",output:"\u2227",ttype:CONST},{input:"\\lor",tag:"mo",output:"\u2228",ttype:CONST},{input:"\\vee",tag:"mo",output:"\u2228",ttype:CONST},{input:"\\cap",tag:"mo",output:"\u2229",ttype:CONST},{input:"\\cup",tag:"mo",output:"\u222A",ttype:CONST},{input:"\\sqcap",tag:"mo",output:"\u2293",ttype:CONST},{input:"\\sqcup",tag:"mo",output:"\u2294",ttype:CONST},{input:"\\uplus",tag:"mo",output:"\u228E",ttype:CONST},{input:"\\amalg",tag:"mo",output:"\u2210",ttype:CONST},{input:"\\bigtriangleup",tag:"mo",output:"\u25B3",ttype:CONST},{input:"\\bigtriangledown",tag:"mo",output:"\u25BD",ttype:CONST},{input:"\\dag",tag:"mo",output:"\u2020",ttype:CONST},{input:"\\dagger",tag:"mo",output:"\u2020",ttype:CONST},{input:"\\ddag",tag:"mo",output:"\u2021",ttype:CONST},{input:"\\ddagger",tag:"mo",output:"\u2021",ttype:CONST},{input:"\\lhd",tag:"mo",output:"\u22B2",ttype:CONST},{input:"\\rhd",tag:"mo",output:"\u22B3",ttype:CONST},{input:"\\unlhd",tag:"mo",output:"\u22B4",ttype:CONST},{input:"\\unrhd",tag:"mo",output:"\u22B5",ttype:CONST},{input:"\\sum",tag:"mo",output:"\u2211",ttype:UNDEROVER},{input:"\\prod",tag:"mo",output:"\u220F",ttype:UNDEROVER},{input:"\\bigcap",tag:"mo",output:"\u22C2",ttype:UNDEROVER},{input:"\\bigcup",tag:"mo",output:"\u22C3",ttype:UNDEROVER},{input:"\\bigwedge",tag:"mo",output:"\u22C0",ttype:UNDEROVER},{input:"\\bigvee",tag:"mo",output:"\u22C1",ttype:UNDEROVER},{input:"\\bigsqcap",tag:"mo",output:"\u2A05",ttype:UNDEROVER},{input:"\\bigsqcup",tag:"mo",output:"\u2A06",ttype:UNDEROVER},{input:"\\coprod",tag:"mo",output:"\u2210",ttype:UNDEROVER},{input:"\\bigoplus",tag:"mo",output:"\u2A01",ttype:UNDEROVER},{input:"\\bigotimes",tag:"mo",output:"\u2A02",ttype:UNDEROVER},{input:"\\bigodot",tag:"mo",output:"\u2A00",ttype:UNDEROVER},{input:"\\biguplus",tag:"mo",output:"\u2A04",ttype:UNDEROVER},{input:"\\int",tag:"mo",output:"\u222B",ttype:CONST},{input:"\\oint",tag:"mo",output:"\u222E",ttype:CONST},{input:":=",tag:"mo",output:":=",ttype:CONST},{input:"\\lt",tag:"mo",output:"<",ttype:CONST},{input:"\\gt",tag:"mo",output:">",ttype:CONST},{input:"\\ne",tag:"mo",output:"\u2260",ttype:CONST},{input:"\\neq",tag:"mo",output:"\u2260",ttype:CONST},{input:"\\le",tag:"mo",output:"\u2264",ttype:CONST},{input:"\\leq",tag:"mo",output:"\u2264",ttype:CONST},{input:"\\leqslant",tag:"mo",output:"\u2264",ttype:CONST},{input:"\\ge",tag:"mo",output:"\u2265",ttype:CONST},{input:"\\geq",tag:"mo",output:"\u2265",ttype:CONST},{input:"\\geqslant",tag:"mo",output:"\u2265",ttype:CONST},{input:"\\equiv",tag:"mo",output:"\u2261",ttype:CONST},{input:"\\ll",tag:"mo",output:"\u226A",ttype:CONST},{input:"\\gg",tag:"mo",output:"\u226B",ttype:CONST},{input:"\\doteq",tag:"mo",output:"\u2250",ttype:CONST},{input:"\\prec",tag:"mo",output:"\u227A",ttype:CONST},{input:"\\succ",tag:"mo",output:"\u227B",ttype:CONST},{input:"\\preceq",tag:"mo",output:"\u227C",ttype:CONST},{input:"\\succeq",tag:"mo",output:"\u227D",ttype:CONST},{input:"\\subset",tag:"mo",output:"\u2282",ttype:CONST},{input:"\\supset",tag:"mo",output:"\u2283",ttype:CONST},{input:"\\subseteq",tag:"mo",output:"\u2286",ttype:CONST},{input:"\\supseteq",tag:"mo",output:"\u2287",ttype:CONST},{input:"\\sqsubset",tag:"mo",output:"\u228F",ttype:CONST},{input:"\\sqsupset",tag:"mo",output:"\u2290",ttype:CONST},{input:"\\sqsubseteq",tag:"mo",output:"\u2291",ttype:CONST},{input:"\\sqsupseteq",tag:"mo",output:"\u2292",ttype:CONST},{input:"\\sim",tag:"mo",output:"\u223C",ttype:CONST},{input:"\\simeq",tag:"mo",output:"\u2243",ttype:CONST},{input:"\\approx",tag:"mo",output:"\u2248",ttype:CONST},{input:"\\cong",tag:"mo",output:"\u2245",ttype:CONST},{input:"\\Join",tag:"mo",output:"\u22C8",ttype:CONST},{input:"\\bowtie",tag:"mo",output:"\u22C8",ttype:CONST},{input:"\\in",tag:"mo",output:"\u2208",ttype:CONST},{input:"\\ni",tag:"mo",output:"\u220B",ttype:CONST},{input:"\\owns",tag:"mo",output:"\u220B",ttype:CONST},{input:"\\propto",tag:"mo",output:"\u221D",ttype:CONST},{input:"\\vdash",tag:"mo",output:"\u22A2",ttype:CONST},{input:"\\dashv",tag:"mo",output:"\u22A3",ttype:CONST},{input:"\\models",tag:"mo",output:"\u22A8",ttype:CONST},{input:"\\perp",tag:"mo",output:"\u22A5",ttype:CONST},{input:"\\smile",tag:"mo",output:"\u2323",ttype:CONST},{input:"\\frown",tag:"mo",output:"\u2322",ttype:CONST},{input:"\\asymp",tag:"mo",output:"\u224D",ttype:CONST},{input:"\\notin",tag:"mo",output:"\u2209",ttype:CONST},{input:"\\begin{eqnarray}",output:"X",ttype:MATRIX,invisible:true},{input:"\\begin{array}",output:"X",ttype:MATRIX,invisible:true},{input:"\\\\",output:"}&{",ttype:DEFINITION},{input:"\\end{eqnarray}",output:"}}",ttype:DEFINITION},{input:"\\end{array}",output:"}}",ttype:DEFINITION},{input:"\\big",tag:"mo",output:"X",atval:"1.2",ieval:"2.2",ttype:BIG},{input:"\\Big",tag:"mo",output:"X",atval:"1.6",ieval:"2.6",ttype:BIG},{input:"\\bigg",tag:"mo",output:"X",atval:"2.2",ieval:"3.2",ttype:BIG},{input:"\\Bigg",tag:"mo",output:"X",atval:"2.9",ieval:"3.9",ttype:BIG},{input:"\\left",tag:"mo",output:"X",ttype:LEFTBRACKET},{input:"\\right",tag:"mo",output:"X",ttype:RIGHTBRACKET},{input:"{",output:"{",ttype:LEFTBRACKET,invisible:true},{input:"}",output:"}",ttype:RIGHTBRACKET,invisible:true},{input:"(",tag:"mo",output:"(",atval:"1",ttype:STRETCHY},{input:"[",tag:"mo",output:"[",atval:"1",ttype:STRETCHY},{input:"\\lbrack",tag:"mo",output:"[",atval:"1",ttype:STRETCHY},{input:"\\{",tag:"mo",output:"{",atval:"1",ttype:STRETCHY},{input:"\\lbrace",tag:"mo",output:"{",atval:"1",ttype:STRETCHY},{input:"\\langle",tag:"mo",output:"\u2329",atval:"1",ttype:STRETCHY},{input:"\\lfloor",tag:"mo",output:"\u230A",atval:"1",ttype:STRETCHY},{input:"\\lceil",tag:"mo",output:"\u2308",atval:"1",ttype:STRETCHY},{input:")",tag:"mo",output:")",rtag:"mi",atval:"1",ttype:STRETCHY},{input:"]",tag:"mo",output:"]",rtag:"mi",atval:"1",ttype:STRETCHY},{input:"\\rbrack",tag:"mo",output:"]",rtag:"mi",atval:"1",ttype:STRETCHY},{input:"\\}",tag:"mo",output:"}",rtag:"mi",atval:"1",ttype:STRETCHY},{input:"\\rbrace",tag:"mo",output:"}",rtag:"mi",atval:"1",ttype:STRETCHY},{input:"\\rangle",tag:"mo",output:"\u232A",rtag:"mi",atval:"1",ttype:STRETCHY},{input:"\\rfloor",tag:"mo",output:"\u230B",rtag:"mi",atval:"1",ttype:STRETCHY},{input:"\\rceil",tag:"mo",output:"\u2309",rtag:"mi",atval:"1",ttype:STRETCHY},{input:"|",tag:"mo",output:"\u2223",atval:"1",ttype:STRETCHY},{input:"\\|",tag:"mo",output:"\u2225",atval:"1",ttype:STRETCHY},{input:"\\vert",tag:"mo",output:"\u2223",atval:"1",ttype:STRETCHY},{input:"\\Vert",tag:"mo",output:"\u2225",atval:"1",ttype:STRETCHY},{input:"\\mid",tag:"mo",output:"\u2223",atval:"1",ttype:STRETCHY},{input:"\\parallel",tag:"mo",output:"\u2225",atval:"1",ttype:STRETCHY},{input:"/",tag:"mo",output:"/",atval:"1.01",ttype:STRETCHY},{input:"\\backslash",tag:"mo",output:"\u2216",atval:"1",ttype:STRETCHY},{input:"\\setminus",tag:"mo",output:"\\",ttype:CONST},{input:"\\!",tag:"mspace",atname:"width",atval:"-0.167em",ttype:SPACE},{input:"\\,",tag:"mspace",atname:"width",atval:"0.167em",ttype:SPACE},{input:"\\>",tag:"mspace",atname:"width",atval:"0.222em",ttype:SPACE},{input:"\\:",tag:"mspace",atname:"width",atval:"0.222em",ttype:SPACE},{input:"\\;",tag:"mspace",atname:"width",atval:"0.278em",ttype:SPACE},{input:"~",tag:"mspace",atname:"width",atval:"0.333em",ttype:SPACE},{input:"\\quad",tag:"mspace",atname:"width",atval:"1em",ttype:SPACE},{input:"\\qquad",tag:"mspace",atname:"width",atval:"2em",ttype:SPACE},{input:"\\prime",tag:"mo",output:"\u2032",ttype:CONST},{input:"'",tag:"mo",output:"\u02B9",ttype:CONST},{input:"''",tag:"mo",output:"\u02BA",ttype:CONST},{input:"'''",tag:"mo",output:"\u2034",ttype:CONST},{input:"''''",tag:"mo",output:"\u2057",ttype:CONST},{input:"\\ldots",tag:"mo",output:"\u2026",ttype:CONST},{input:"\\cdots",tag:"mo",output:"\u22EF",ttype:CONST},{input:"\\vdots",tag:"mo",output:"\u22EE",ttype:CONST},{input:"\\ddots",tag:"mo",output:"\u22F1",ttype:CONST},{input:"\\forall",tag:"mo",output:"\u2200",ttype:CONST},{input:"\\exists",tag:"mo",output:"\u2203",ttype:CONST},{input:"\\Re",tag:"mo",output:"\u211C",ttype:CONST},{input:"\\Im",tag:"mo",output:"\u2111",ttype:CONST},{input:"\\aleph",tag:"mo",output:"\u2135",ttype:CONST},{input:"\\hbar",tag:"mo",output:"\u210F",ttype:CONST},{input:"\\ell",tag:"mo",output:"\u2113",ttype:CONST},{input:"\\wp",tag:"mo",output:"\u2118",ttype:CONST},{input:"\\emptyset",tag:"mo",output:"\u2205",ttype:CONST},{input:"\\infty",tag:"mo",output:"\u221E",ttype:CONST},{input:"\\surd",tag:"mo",output:"\\sqrt{}",ttype:DEFINITION},{input:"\\partial",tag:"mo",output:"\u2202",ttype:CONST},{input:"\\nabla",tag:"mo",output:"\u2207",ttype:CONST},{input:"\\triangle",tag:"mo",output:"\u25B3",ttype:CONST},{input:"\\therefore",tag:"mo",output:"\u2234",ttype:CONST},{input:"\\angle",tag:"mo",output:"\u2220",ttype:CONST},{input:"\\diamond",tag:"mo",output:"\u22C4",ttype:CONST},{input:"\\Diamond",tag:"mo",output:"\u25C7",ttype:CONST},{input:"\\neg",tag:"mo",output:"\u00AC",ttype:CONST},{input:"\\lnot",tag:"mo",output:"\u00AC",ttype:CONST},{input:"\\bot",tag:"mo",output:"\u22A5",ttype:CONST},{input:"\\top",tag:"mo",output:"\u22A4",ttype:CONST},{input:"\\square",tag:"mo",output:"\u25AB",ttype:CONST},{input:"\\Box",tag:"mo",output:"\u25A1",ttype:CONST},{input:"\\wr",tag:"mo",output:"\u2240",ttype:CONST},{input:"\\arccos",tag:"mi",output:"arccos",ttype:UNARY,func:true},{input:"\\arcsin",tag:"mi",output:"arcsin",ttype:UNARY,func:true},{input:"\\arctan",tag:"mi",output:"arctan",ttype:UNARY,func:true},{input:"\\arg",tag:"mi",output:"arg",ttype:UNARY,func:true},{input:"\\cos",tag:"mi",output:"cos",ttype:UNARY,func:true},{input:"\\cosh",tag:"mi",output:"cosh",ttype:UNARY,func:true},{input:"\\cot",tag:"mi",output:"cot",ttype:UNARY,func:true},{input:"\\coth",tag:"mi",output:"coth",ttype:UNARY,func:true},{input:"\\csc",tag:"mi",output:"csc",ttype:UNARY,func:true},{input:"\\deg",tag:"mi",output:"deg",ttype:UNARY,func:true},{input:"\\det",tag:"mi",output:"det",ttype:UNARY,func:true},{input:"\\dim",tag:"mi",output:"dim",ttype:UNARY,func:true},{input:"\\exp",tag:"mi",output:"exp",ttype:UNARY,func:true},{input:"\\gcd",tag:"mi",output:"gcd",ttype:UNARY,func:true},{input:"\\hom",tag:"mi",output:"hom",ttype:UNARY,func:true},{input:"\\inf",tag:"mo",output:"inf",ttype:UNDEROVER},{input:"\\ker",tag:"mi",output:"ker",ttype:UNARY,func:true},{input:"\\lg",tag:"mi",output:"lg",ttype:UNARY,func:true},{input:"\\lim",tag:"mo",output:"lim",ttype:UNDEROVER},{input:"\\liminf",tag:"mo",output:"liminf",ttype:UNDEROVER},{input:"\\limsup",tag:"mo",output:"limsup",ttype:UNDEROVER},{input:"\\ln",tag:"mi",output:"ln",ttype:UNARY,func:true},{input:"\\log",tag:"mi",output:"log",ttype:UNARY,func:true},{input:"\\max",tag:"mo",output:"max",ttype:UNDEROVER},{input:"\\min",tag:"mo",output:"min",ttype:UNDEROVER},{input:"\\Pr",tag:"mi",output:"Pr",ttype:UNARY,func:true},{input:"\\sec",tag:"mi",output:"sec",ttype:UNARY,func:true},{input:"\\sin",tag:"mi",output:"sin",ttype:UNARY,func:true},{input:"\\sinh",tag:"mi",output:"sinh",ttype:UNARY,func:true},{input:"\\sup",tag:"mo",output:"sup",ttype:UNDEROVER},{input:"\\tan",tag:"mi",output:"tan",ttype:UNARY,func:true},{input:"\\tanh",tag:"mi",output:"tanh",ttype:UNARY,func:true},{input:"\\gets",tag:"mo",output:"\u2190",ttype:CONST},{input:"\\leftarrow",tag:"mo",output:"\u2190",ttype:CONST},{input:"\\to",tag:"mo",output:"\u2192",ttype:CONST},{input:"\\rightarrow",tag:"mo",output:"\u2192",ttype:CONST},{input:"\\leftrightarrow",tag:"mo",output:"\u2194",ttype:CONST},{input:"\\uparrow",tag:"mo",output:"\u2191",ttype:CONST},{input:"\\downarrow",tag:"mo",output:"\u2193",ttype:CONST},{input:"\\updownarrow",tag:"mo",output:"\u2195",ttype:CONST},{input:"\\Leftarrow",tag:"mo",output:"\u21D0",ttype:CONST},{input:"\\Rightarrow",tag:"mo",output:"\u21D2",ttype:CONST},{input:"\\Leftrightarrow",tag:"mo",output:"\u21D4",ttype:CONST},{input:"\\iff",tag:"mo",output:"~\\Longleftrightarrow~",ttype:DEFINITION},{input:"\\Uparrow",tag:"mo",output:"\u21D1",ttype:CONST},{input:"\\Downarrow",tag:"mo",output:"\u21D3",ttype:CONST},{input:"\\Updownarrow",tag:"mo",output:"\u21D5",ttype:CONST},{input:"\\mapsto",tag:"mo",output:"\u21A6",ttype:CONST},{input:"\\longleftarrow",tag:"mo",output:"\u2190",ttype:LONG},{input:"\\longrightarrow",tag:"mo",output:"\u2192",ttype:LONG},{input:"\\longleftrightarrow",tag:"mo",output:"\u2194",ttype:LONG},{input:"\\Longleftarrow",tag:"mo",output:"\u21D0",ttype:LONG},{input:"\\Longrightarrow",tag:"mo",output:"\u21D2",ttype:LONG},{input:"\\Longleftrightarrow",tag:"mo",output:"\u21D4",ttype:LONG},{input:"\\longmapsto",tag:"mo",output:"\u21A6",ttype:CONST},AMsqrt,AMroot,AMfrac,AMover,AMsub,AMsup,AMtext,AMmbox,AMatop,AMchoose,{input:"\\acute",tag:"mover",output:"\u00B4",ttype:UNARY,acc:true},{input:"\\grave",tag:"mover",output:"\u0060",ttype:UNARY,acc:true},{input:"\\breve",tag:"mover",output:"\u02D8",ttype:UNARY,acc:true},{input:"\\check",tag:"mover",output:"\u02C7",ttype:UNARY,acc:true},{input:"\\dot",tag:"mover",output:".",ttype:UNARY,acc:true},{input:"\\ddot",tag:"mover",output:"..",ttype:UNARY,acc:true},{input:"\\mathring",tag:"mover",output:"\u00B0",ttype:UNARY,acc:true},{input:"\\vec",tag:"mover",output:"\u20D7",ttype:UNARY,acc:true},{input:"\\overrightarrow",tag:"mover",output:"\u20D7",ttype:UNARY,acc:true},{input:"\\overleftarrow",tag:"mover",output:"\u20D6",ttype:UNARY,acc:true},{input:"\\hat",tag:"mover",output:"\u005E",ttype:UNARY,acc:true},{input:"\\widehat",tag:"mover",output:"\u0302",ttype:UNARY,acc:true},{input:"\\tilde",tag:"mover",output:"~",ttype:UNARY,acc:true},{input:"\\widetilde",tag:"mover",output:"\u02DC",ttype:UNARY,acc:true},{input:"\\bar",tag:"mover",output:"\u203E",ttype:UNARY,acc:true},{input:"\\overbrace",tag:"mover",output:"\uFE37",ttype:UNARY,acc:true},{input:"\\overbracket",tag:"mover",output:"\u23B4",ttype:UNARY,acc:true},{input:"\\overline",tag:"mover",output:"\u00AF",ttype:UNARY,acc:true},{input:"\\underbrace",tag:"munder",output:"\uFE38",ttype:UNARY,acc:true},{input:"\\underbracket",tag:"munder",output:"\u23B5",ttype:UNARY,acc:true},{input:"\\underline",tag:"munder",output:"\u00AF",ttype:UNARY,acc:true},{input:"\\displaystyle",tag:"mstyle",atname:"displaystyle",atval:"true",ttype:UNARY},{input:"\\textstyle",tag:"mstyle",atname:"displaystyle",atval:"false",ttype:UNARY},{input:"\\scriptstyle",tag:"mstyle",atname:"scriptlevel",atval:"1",ttype:UNARY},{input:"\\scriptscriptstyle",tag:"mstyle",atname:"scriptlevel",atval:"2",ttype:UNARY},{input:"\\textrm",tag:"mstyle",output:"\\mathrm",ttype:DEFINITION},{input:"\\mathbf",tag:"mstyle",atname:"mathvariant",atval:"bold",ttype:UNARY},{input:"\\textbf",tag:"mstyle",atname:"mathvariant",atval:"bold",ttype:UNARY},{input:"\\mathit",tag:"mstyle",atname:"mathvariant",atval:"italic",ttype:UNARY},{input:"\\textit",tag:"mstyle",atname:"mathvariant",atval:"italic",ttype:UNARY},{input:"\\mathtt",tag:"mstyle",atname:"mathvariant",atval:"monospace",ttype:UNARY},{input:"\\texttt",tag:"mstyle",atname:"mathvariant",atval:"monospace",ttype:UNARY},{input:"\\mathsf",tag:"mstyle",atname:"mathvariant",atval:"sans-serif",ttype:UNARY},{input:"\\mathbb",tag:"mstyle",atname:"mathvariant",atval:"double-struck",ttype:UNARY,codes:AMbbb},{input:"\\mathcal",tag:"mstyle",atname:"mathvariant",atval:"script",ttype:UNARY,codes:AMcal},{input:"\\mathfrak",tag:"mstyle",atname:"mathvariant",atval:"fraktur",ttype:UNARY,codes:AMfrk},{input:"\\textcolor",tag:"mstyle",atname:"mathvariant",atval:"mathcolor",ttype:BINARY},{input:"\\colorbox",tag:"mstyle",atname:"mathvariant",atval:"background",ttype:BINARY}];function compareNames(s1,s2){if(s1.input>s2.input)return 1
-else return-1;}
-var AMnames=[];function AMinitSymbols(){AMsymbols.sort(compareNames);for(i=0;i<AMsymbols.length;i++)AMnames[i]=AMsymbols[i].input;}
-var AMmathml="http://www.w3.org/1998/Math/MathML";function AMcreateElementMathML(t){if(isIE)return document.createElement("m:"+t);else return document.createElementNS(AMmathml,t);}
-function AMcreateMmlNode(t,frag){if(isIE)var node=document.createElement("m:"+t);else var node=document.createElementNS(AMmathml,t);node.appendChild(frag);return node;}
-function newcommand(oldstr,newstr){AMsymbols=AMsymbols.concat([{input:oldstr,tag:"mo",output:newstr,ttype:DEFINITION}]);}
-function AMremoveCharsAndBlanks(str,n){var st;st=str.slice(n);for(var i=0;i<st.length&&st.charCodeAt(i)<=32;i=i+1);return st.slice(i);}
-function AMposition(arr,str,n){if(n==0){var h,m;n=-1;h=arr.length;while(n+1<h){m=(n+h)>>1;if(arr[m]<str)n=m;else h=m;}
-return h;}else
-for(var i=n;i<arr.length&&arr[i]<str;i++);return i;}
-function AMgetSymbol(str){var k=0;var j=0;var mk;var st;var tagst;var match="";var more=true;for(var i=1;i<=str.length&&more;i++){st=str.slice(0,i);j=k;k=AMposition(AMnames,st,j);if(k<AMnames.length&&str.slice(0,AMnames[k].length)==AMnames[k]){match=AMnames[k];mk=k;i=match.length;}
-more=k<AMnames.length&&str.slice(0,AMnames[k].length)>=AMnames[k];}
-AMpreviousSymbol=AMcurrentSymbol;if(match!=""){AMcurrentSymbol=AMsymbols[mk].ttype;return AMsymbols[mk];}
-AMcurrentSymbol=CONST;k=1;st=str.slice(0,1);if("0"<=st&&st<="9")tagst="mn";else tagst=(("A">st||st>"Z")&&("a">st||st>"z")?"mo":"mi");return{input:st,tag:tagst,output:st,ttype:CONST};}
-var AMpreviousSymbol,AMcurrentSymbol;function AMparseSexpr(str){var symbol,node,result,result2,i,st,newFrag=document.createDocumentFragment();str=AMremoveCharsAndBlanks(str,0);symbol=AMgetSymbol(str);if(symbol==null||symbol.ttype==RIGHTBRACKET)
-return[null,str,null];if(symbol.ttype==DEFINITION){str=symbol.output+AMremoveCharsAndBlanks(str,symbol.input.length);symbol=AMgetSymbol(str);if(symbol==null||symbol.ttype==RIGHTBRACKET)
-return[null,str,null];}
-str=AMremoveCharsAndBlanks(str,symbol.input.length);switch(symbol.ttype){case SPACE:node=AMcreateElementMathML(symbol.tag);node.setAttribute(symbol.atname,symbol.atval);return[node,str,symbol.tag];case UNDEROVER:if(isIE){if(symbol.input.substr(0,4)=="\\big"){str="\\"+symbol.input.substr(4)+str;symbol=AMgetSymbol(str);symbol.ttype=UNDEROVER;str=AMremoveCharsAndBlanks(str,symbol.input.length);}}
-return[AMcreateMmlNode(symbol.tag,document.createTextNode(symbol.output)),str,symbol.tag];case CONST:var output=symbol.output;if(isIE){if(symbol.input=="'")
-output="\u2032";else if(symbol.input=="''")
-output="\u2033";else if(symbol.input=="'''")
-output="\u2033\u2032";else if(symbol.input=="''''")
-output="\u2033\u2033";else if(symbol.input=="\\square")
-output="\u25A1";else if(symbol.input.substr(0,5)=="\\frac"){var denom=symbol.input.substr(6,1);if(denom=="5"||denom=="6"){str=symbol.input.replace(/\\frac/,"\\frac ")+str;return[node,str,symbol.tag];}}}
-node=AMcreateMmlNode(symbol.tag,document.createTextNode(output));return[node,str,symbol.tag];case LONG:node=AMcreateMmlNode(symbol.tag,document.createTextNode(symbol.output));node.setAttribute("minsize","1.5");node.setAttribute("maxsize","1.5");node=AMcreateMmlNode("mover",node);node.appendChild(AMcreateElementMathML("mspace"));return[node,str,symbol.tag];case STRETCHY:if(isIE&&symbol.input=="\\backslash")
-symbol.output="\\";node=AMcreateMmlNode(symbol.tag,document.createTextNode(symbol.output));if(symbol.input=="|"||symbol.input=="\\vert"||symbol.input=="\\|"||symbol.input=="\\Vert"){node.setAttribute("lspace","0em");node.setAttribute("rspace","0em");}
-node.setAttribute("maxsize",symbol.atval);if(symbol.rtag!=null)
-return[node,str,symbol.rtag];else
-return[node,str,symbol.tag];case BIG:var atval=symbol.atval;if(isIE)
-atval=symbol.ieval;symbol=AMgetSymbol(str);if(symbol==null)
-return[null,str,null];str=AMremoveCharsAndBlanks(str,symbol.input.length);node=AMcreateMmlNode(symbol.tag,document.createTextNode(symbol.output));if(isIE){var space=AMcreateElementMathML("mspace");space.setAttribute("height",atval+"ex");node=AMcreateMmlNode("mrow",node);node.appendChild(space);}else{node.setAttribute("minsize",atval);node.setAttribute("maxsize",atval);}
-return[node,str,symbol.tag];case LEFTBRACKET:if(symbol.input=="\\left"){symbol=AMgetSymbol(str);if(symbol!=null){if(symbol.input==".")
-symbol.invisible=true;str=AMremoveCharsAndBlanks(str,symbol.input.length);}}
-result=AMparseExpr(str,true,false);if(symbol==null||(typeof symbol.invisible=="boolean"&&symbol.invisible))
-node=AMcreateMmlNode("mrow",result[0]);else{node=AMcreateMmlNode("mo",document.createTextNode(symbol.output));node=AMcreateMmlNode("mrow",node);node.appendChild(result[0]);}
-return[node,result[1],result[2]];case MATRIX:if(symbol.input=="\\begin{array}"){var mask="";symbol=AMgetSymbol(str);str=AMremoveCharsAndBlanks(str,0);if(symbol==null)
-mask="l";else{str=AMremoveCharsAndBlanks(str,symbol.input.length);if(symbol.input!="{")
-mask="l";else do{symbol=AMgetSymbol(str);if(symbol!=null){str=AMremoveCharsAndBlanks(str,symbol.input.length);if(symbol.input!="}")
-mask=mask+symbol.input;}}while(symbol!=null&&symbol.input!=""&&symbol.input!="}");}
-result=AMparseExpr("{"+str,true,true);node=AMcreateMmlNode("mtable",result[0]);mask=mask.replace(/l/g,"left ");mask=mask.replace(/r/g,"right ");mask=mask.replace(/c/g,"center ");node.setAttribute("columnalign",mask);node.setAttribute("displaystyle","false");if(isIE)
-return[node,result[1],null];var lspace=AMcreateElementMathML("mspace");lspace.setAttribute("width","0.167em");var rspace=AMcreateElementMathML("mspace");rspace.setAttribute("width","0.167em");var node1=AMcreateMmlNode("mrow",lspace);node1.appendChild(node);node1.appendChild(rspace);return[node1,result[1],null];}else{result=AMparseExpr("{"+str,true,true);node=AMcreateMmlNode("mtable",result[0]);if(isIE)
-node.setAttribute("columnspacing","0.25em");else
-node.setAttribute("columnspacing","0.167em");node.setAttribute("columnalign","right center left");node.setAttribute("displaystyle","true");node=AMcreateMmlNode("mrow",node);return[node,result[1],null];}
-case TEXT:if(str.charAt(0)=="{")i=str.indexOf("}");else i=0;if(i==-1)
-i=str.length;st=str.slice(1,i);if(st.charAt(0)==" "){node=AMcreateElementMathML("mspace");node.setAttribute("width","0.33em");newFrag.appendChild(node);}
-newFrag.appendChild(AMcreateMmlNode(symbol.tag,document.createTextNode(st)));if(st.charAt(st.length-1)==" "){node=AMcreateElementMathML("mspace");node.setAttribute("width","0.33em");newFrag.appendChild(node);}
-str=AMremoveCharsAndBlanks(str,i+1);return[AMcreateMmlNode("mrow",newFrag),str,null];case UNARY:result=AMparseSexpr(str);if(result[0]==null)return[AMcreateMmlNode(symbol.tag,document.createTextNode(symbol.output)),str];if(typeof symbol.func=="boolean"&&symbol.func){st=str.charAt(0);if(st=="^"||st=="_"||st==","){return[AMcreateMmlNode(symbol.tag,document.createTextNode(symbol.output)),str,symbol.tag];}else{node=AMcreateMmlNode("mrow",AMcreateMmlNode(symbol.tag,document.createTextNode(symbol.output)));if(isIE){var space=AMcreateElementMathML("mspace");space.setAttribute("width","0.167em");node.appendChild(space);}
-node.appendChild(result[0]);return[node,result[1],symbol.tag];}}
-if(symbol.input=="\\sqrt"){if(isIE){var space=AMcreateElementMathML("mspace");space.setAttribute("height","1.2ex");space.setAttribute("width","0em");node=AMcreateMmlNode(symbol.tag,result[0])
-node.appendChild(space);return[node,result[1],symbol.tag];}else
-return[AMcreateMmlNode(symbol.tag,result[0]),result[1],symbol.tag];}else if(typeof symbol.acc=="boolean"&&symbol.acc){node=AMcreateMmlNode(symbol.tag,result[0]);var output=symbol.output;if(isIE){if(symbol.input=="\\hat")
-output="\u0302";else if(symbol.input=="\\widehat")
-output="\u005E";else if(symbol.input=="\\bar")
-output="\u00AF";else if(symbol.input=="\\grave")
-output="\u0300";else if(symbol.input=="\\tilde")
-output="\u0303";}
-var node1=AMcreateMmlNode("mo",document.createTextNode(output));if(symbol.input=="\\vec"||symbol.input=="\\check")
-node1.setAttribute("maxsize","1.2");if(isIE&&symbol.input=="\\bar")
-node1.setAttribute("maxsize","0.5");if(symbol.input=="\\underbrace"||symbol.input=="\\underline")
-node1.setAttribute("accentunder","true");else
-node1.setAttribute("accent","true");node.appendChild(node1);if(symbol.input=="\\overbrace"||symbol.input=="\\underbrace")
-node.ttype=UNDEROVER;return[node,result[1],symbol.tag];}else{if(!isIE&&typeof symbol.codes!="undefined"){for(i=0;i<result[0].childNodes.length;i++)
-if(result[0].childNodes[i].nodeName=="mi"||result[0].nodeName=="mi"){st=(result[0].nodeName=="mi"?result[0].firstChild.nodeValue:result[0].childNodes[i].firstChild.nodeValue);var newst=[];for(var j=0;j<st.length;j++)
-if(st.charCodeAt(j)>64&&st.charCodeAt(j)<91)newst=newst+
-String.fromCharCode(symbol.codes[st.charCodeAt(j)-65]);else newst=newst+st.charAt(j);if(result[0].nodeName=="mi")
-result[0]=AMcreateElementMathML("mo").appendChild(document.createTextNode(newst));else result[0].replaceChild(AMcreateElementMathML("mo").appendChild(document.createTextNode(newst)),result[0].childNodes[i]);}}
-node=AMcreateMmlNode(symbol.tag,result[0]);node.setAttribute(symbol.atname,symbol.atval);if(symbol.input=="\\scriptstyle"||symbol.input=="\\scriptscriptstyle")
-node.setAttribute("displaystyle","false");return[node,result[1],symbol.tag];}
-case BINARY:result=AMparseSexpr(str);if(result[0]==null)return[AMcreateMmlNode("mo",document.createTextNode(symbol.input)),str,null];result2=AMparseSexpr(result[1]);if(result2[0]==null)return[AMcreateMmlNode("mo",document.createTextNode(symbol.input)),str,null];if(symbol.input=="\\textcolor"||symbol.input=="\\colorbox"){var tclr=str.match(/\{\s*([#\w]+)\s*\}/);str=str.replace(/\{\s*[#\w]+\s*\}/,"");if(tclr!=null){if(IsColorName.test(tclr[1].toLowerCase())){tclr=LaTeXColor[tclr[1].toLowerCase()];}else{tclr=tclr[1];}
-node=AMcreateElementMathML("mstyle");node.setAttribute(symbol.atval,tclr);node.appendChild(result2[0]);return[node,result2[1],symbol.tag];}}
-if(symbol.input=="\\root"||symbol.input=="\\stackrel")newFrag.appendChild(result2[0]);newFrag.appendChild(result[0]);if(symbol.input=="\\frac")newFrag.appendChild(result2[0]);return[AMcreateMmlNode(symbol.tag,newFrag),result2[1],symbol.tag];case INFIX:str=AMremoveCharsAndBlanks(str,symbol.input.length);return[AMcreateMmlNode("mo",document.createTextNode(symbol.output)),str,symbol.tag];default:return[AMcreateMmlNode(symbol.tag,document.createTextNode(symbol.output)),str,symbol.tag];}}
-function AMparseIexpr(str){var symbol,sym1,sym2,node,result,tag,underover;str=AMremoveCharsAndBlanks(str,0);sym1=AMgetSymbol(str);result=AMparseSexpr(str);node=result[0];str=result[1];tag=result[2];symbol=AMgetSymbol(str);if(symbol.ttype==INFIX){str=AMremoveCharsAndBlanks(str,symbol.input.length);result=AMparseSexpr(str);if(result[0]==null)
-result[0]=AMcreateMmlNode("mo",document.createTextNode("\u25A1"));str=result[1];tag=result[2];if(symbol.input=="_"||symbol.input=="^"){sym2=AMgetSymbol(str);tag=null;underover=((sym1.ttype==UNDEROVER)||(node.ttype==UNDEROVER));if(symbol.input=="_"&&sym2.input=="^"){str=AMremoveCharsAndBlanks(str,sym2.input.length);var res2=AMparseSexpr(str);str=res2[1];tag=res2[2];node=AMcreateMmlNode((underover?"munderover":"msubsup"),node);node.appendChild(result[0]);node.appendChild(res2[0]);}else if(symbol.input=="_"){node=AMcreateMmlNode((underover?"munder":"msub"),node);node.appendChild(result[0]);}else{node=AMcreateMmlNode((underover?"mover":"msup"),node);node.appendChild(result[0]);}
-node=AMcreateMmlNode("mrow",node);}else{node=AMcreateMmlNode(symbol.tag,node);if(symbol.input=="\\atop"||symbol.input=="\\choose")
-node.setAttribute("linethickness","0ex");node.appendChild(result[0]);if(symbol.input=="\\choose")
-node=AMcreateMmlNode("mfenced",node);}}
-return[node,str,tag];}
-function AMparseExpr(str,rightbracket,matrix){var symbol,node,result,i,tag,newFrag=document.createDocumentFragment();do{str=AMremoveCharsAndBlanks(str,0);result=AMparseIexpr(str);node=result[0];str=result[1];tag=result[2];symbol=AMgetSymbol(str);if(node!=undefined){if((tag=="mn"||tag=="mi")&&symbol!=null&&typeof symbol.func=="boolean"&&symbol.func){var space=AMcreateElementMathML("mspace");space.setAttribute("width","0.167em");node=AMcreateMmlNode("mrow",node);node.appendChild(space);}
-newFrag.appendChild(node);}}while((symbol.ttype!=RIGHTBRACKET)&&symbol!=null&&symbol.output!="");tag=null;if(symbol.ttype==RIGHTBRACKET){if(symbol.input=="\\right"){str=AMremoveCharsAndBlanks(str,symbol.input.length);symbol=AMgetSymbol(str);if(symbol!=null&&symbol.input==".")
-symbol.invisible=true;if(symbol!=null)
-tag=symbol.rtag;}
-if(symbol!=null)
-str=AMremoveCharsAndBlanks(str,symbol.input.length);var len=newFrag.childNodes.length;if(matrix&&len>0&&newFrag.childNodes[len-1].nodeName=="mrow"&&len>1&&newFrag.childNodes[len-2].nodeName=="mo"&&newFrag.childNodes[len-2].firstChild.nodeValue=="&"){var pos=[];var m=newFrag.childNodes.length;for(i=0;matrix&&i<m;i=i+2){pos[i]=[];node=newFrag.childNodes[i];for(var j=0;j<node.childNodes.length;j++)
-if(node.childNodes[j].firstChild.nodeValue=="&")
-pos[i][pos[i].length]=j;}
-var row,frag,n,k,table=document.createDocumentFragment();for(i=0;i<m;i=i+2){row=document.createDocumentFragment();frag=document.createDocumentFragment();node=newFrag.firstChild;n=node.childNodes.length;k=0;for(j=0;j<n;j++){if(typeof pos[i][k]!="undefined"&&j==pos[i][k]){node.removeChild(node.firstChild);row.appendChild(AMcreateMmlNode("mtd",frag));k++;}else frag.appendChild(node.firstChild);}
-row.appendChild(AMcreateMmlNode("mtd",frag));if(newFrag.childNodes.length>2){newFrag.removeChild(newFrag.firstChild);newFrag.removeChild(newFrag.firstChild);}
-table.appendChild(AMcreateMmlNode("mtr",row));}
-return[table,str];}
-if(typeof symbol.invisible!="boolean"||!symbol.invisible){node=AMcreateMmlNode("mo",document.createTextNode(symbol.output));newFrag.appendChild(node);}}
-return[newFrag,str,tag];}
-function AMparseMath(str){var result,node=AMcreateElementMathML("mstyle");var cclr=str.match(/\\color\s*\{\s*([#\w]+)\s*\}/);str=str.replace(/\\color\s*\{\s*[#\w]+\s*\}/g,"");if(cclr!=null){if(IsColorName.test(cclr[1].toLowerCase())){cclr=LaTeXColor[cclr[1].toLowerCase()];}else{cclr=cclr[1];}
-node.setAttribute("mathcolor",cclr);}else{if(mathcolor!="")node.setAttribute("mathcolor",mathcolor);};if(mathfontfamily!="")node.setAttribute("fontfamily",mathfontfamily);node.appendChild(AMparseExpr(str.replace(/^\s+/g,""),false,false)[0]);node=AMcreateMmlNode("math",node);if(showasciiformulaonhover)
-node.setAttribute("title",str.replace(/\s+/g," "));if(false){var fnode=AMcreateElementXHTML("font");fnode.setAttribute("face",mathfontfamily);fnode.appendChild(node);return fnode;}
-return node;}
-function AMstrarr2docFrag(arr,linebreaks){var newFrag=document.createDocumentFragment();var expr=false;for(var i=0;i<arr.length;i++){if(expr)newFrag.appendChild(AMparseMath(arr[i]));else{var arri=(linebreaks?arr[i].split("\n\n"):[arr[i]]);newFrag.appendChild(AMcreateElementXHTML("span").appendChild(document.createTextNode(arri[0])));for(var j=1;j<arri.length;j++){newFrag.appendChild(AMcreateElementXHTML("p"));newFrag.appendChild(AMcreateElementXHTML("span").appendChild(document.createTextNode(arri[j])));}}
-expr=!expr;}
-return newFrag;}
-function AMprocessNodeR(n,linebreaks){var mtch,str,arr,frg,i;if(n.childNodes.length==0){if((n.nodeType!=8||linebreaks)&&n.parentNode.nodeName!="form"&&n.parentNode.nodeName!="FORM"&&n.parentNode.nodeName!="textarea"&&n.parentNode.nodeName!="TEXTAREA"&&n.parentNode.nodeName!="pre"&&n.parentNode.nodeName!="PRE"){str=n.nodeValue;if(!(str==null)){str=str.replace(/\r\n\r\n/g,"\n\n");str=str.replace(/\x20+/g," ");str=str.replace(/\s*\r\n/g," ");mtch=(str.indexOf("\$")==-1?false:true);str=str.replace(/([^\\])\$/g,"$1 \$");str=str.replace(/^\$/," \$");arr=str.split(" \$");for(i=0;i<arr.length;i++)
-arr[i]=arr[i].replace(/\\\$/g,"\$");if(arr.length>1||mtch){if(checkForMathML){checkForMathML=false;var nd=AMisMathMLavailable();AMnoMathML=nd!=null;if(AMnoMathML&&notifyIfNoMathML)
-if(alertIfNoMathML)
-alert("To view the ASCIIMathML notation use Internet Explorer 6 +\nMathPlayer (free from www.dessci.com)\nor Firefox/Mozilla/Netscape");else AMbody.insertBefore(nd,AMbody.childNodes[0]);}
-if(!AMnoMathML){frg=AMstrarr2docFrag(arr,n.nodeType==8);var len=frg.childNodes.length;n.parentNode.replaceChild(frg,n);return len-1;}else return 0;}}}else return 0;}else if(n.nodeName!="math"){for(i=0;i<n.childNodes.length;i++)
-i+=AMprocessNodeR(n.childNodes[i],linebreaks);}
-return 0;}
-function AMprocessNode(n,linebreaks,spanclassAM){var frag,st;if(spanclassAM!=null){frag=document.getElementsByTagName("span")
-for(var i=0;i<frag.length;i++)
-if(frag[i].className=="AM")
-AMprocessNodeR(frag[i],linebreaks);}else{try{st=n.innerHTML;}catch(err){}
-if(st==null||st.indexOf("\$")!=-1)
-AMprocessNodeR(n,linebreaks);}
-if(isIE){frag=document.getElementsByTagName('math');for(var i=0;i<frag.length;i++)frag[i].update()}}
-var inAppendix=false;var sectionCntr=0;var IEcommentWarning=true;var biblist=[];var bibcntr=0;var LaTeXCounter=[];LaTeXCounter["definition"]=0;LaTeXCounter["proposition"]=0;LaTeXCounter["lemma"]=0;LaTeXCounter["theorem"]=0;LaTeXCounter["corollary"]=0;LaTeXCounter["example"]=0;LaTeXCounter["exercise"]=0;LaTeXCounter["subsection"]=0;LaTeXCounter["subsubsection"]=0;LaTeXCounter["figure"]=0;LaTeXCounter["equation"]=0;LaTeXCounter["table"]=0;var LaTeXColor=[];LaTeXColor["greenyellow"]="#D9FF4F";LaTeXColor["yellow"]="#FFFF00";LaTeXColor["goldenrod"]="#FFE529";LaTeXColor["dandelion"]="#FFB529";LaTeXColor["apricot"]="#FFAD7A";LaTeXColor["peach"]="#FF804D";LaTeXColor["melon"]="#FF8A80";LaTeXColor["yelloworange"]="#FF9400";LaTeXColor["orange"]="#FF6321";LaTeXColor["burntorange"]="#FF7D00";LaTeXColor["bittersweet"]="#C20300";LaTeXColor["redorange"]="#FF3B21";LaTeXColor["mahogany"]="#A60000";LaTeXColor["maroon"]="#AD0000";LaTeXColor["brickred"]="#B80000";LaTeXColor["red"]="#FF0000";LaTeXColor["orangered"]="#FF0080";LaTeXColor["rubinered"]="#FF00DE";LaTeXColor["wildstrawberry"]="#FF0A9C";LaTeXColor["salmon"]="#FF789E";LaTeXColor["carnationpink"]="#FF5EFF";LaTeXColor["magenta"]="#FF00FF";LaTeXColor["violetred"]="#FF30FF";LaTeXColor["rhodamine"]="#FF2EFF";LaTeXColor["mulberry"]="#A314FA";LaTeXColor["redviolet"]="#9600A8";LaTeXColor["fuchsia"]="#7303EB";LaTeXColor["lavender"]="#FF85FF";LaTeXColor["thistle"]="#E069FF";LaTeXColor["orchid"]="#AD5CFF";LaTeXColor["darkorchid"]="#9933CC";LaTeXColor["purple"]="#8C24FF";LaTeXColor["plum"]="#8000FF";LaTeXColor["violet"]="#361FFF";LaTeXColor["royalpurple"]="#401AFF";LaTeXColor["blueviolet"]="#1A0DF5";LaTeXColor["periwinkle"]="#6E73FF";LaTeXColor["cadetblue"]="#616EC4";LaTeXColor["cornflowerblue"]="#59DEFF";LaTeXColor["midnightblue"]="#007091";LaTeXColor["navyblue"]="#0F75FF";LaTeXColor["royalblue"]="#0080FF";LaTeXColor["blue"]="#0000FF";LaTeXColor["cerulean"]="#0FE3FF";LaTeXColor["cyan"]="#00FFFF";LaTeXColor["processblue"]="#0AFFFF";LaTeXColor["skyblue"]="#61FFE0";LaTeXColor["turquoise"]="#26FFCC";LaTeXColor["tealblue"]="#1FFAA3";LaTeXColor["aquamarine"]="#2EFFB2";LaTeXColor["bluegreen"]="#26FFAB";LaTeXColor["emerald"]="#00FF80";LaTeXColor["junglegreen"]="#03FF7A";LaTeXColor["seagreen"]="#4FFF80";LaTeXColor["green"]="#00FF00";LaTeXColor["forestgreen"]="#00E000";LaTeXColor["pinegreen"]="#00BF29";LaTeXColor["limegreen"]="#80FF00";LaTeXColor["yellowgreen"]="#8FFF42";LaTeXColor["springgreen"]="#BDFF3D";LaTeXColor["olivegreen"]="#009900";LaTeXColor["rawsienna"]="#8C0000";LaTeXColor["sepia"]="#4D0000";LaTeXColor["brown"]="#660000";LaTeXColor["tan"]="#DB9470";LaTeXColor["gray"]="#808080";LaTeXColor["grey"]="#808080";LaTeXColor["black"]="#000000";LaTeXColor["white"]="#FFFFFF";var IsColorName=/^(?:greenyellow|yellow|goldenrod|dandelion|apricot|peach|melon|yelloworange|orange|burntorange|bittersweet|redorange|mahogany|maroon|brickred|red|orangered|rubinered|wildstrawberry|salmon|carnationpink|magenta|violetred|rhodamine|mulberry|redviolet|fuchsia|lavender|thistle|orchid|darkorchid|purple|plum|violet|royalpurple|blueviolet|periwinkle|cadetblue|cornflowerblue|midnightblue|navyblue|royalblue|blue|cerulean|cyan|processblue|skyblue|turquoise|tealblue|aquamarine|bluegreen|emerald|junglegreen|seagreen|green|forestgreen|pinegreen|limegreen|yellowgreen|springgreen|olivegreen|rawsienna|sepia|brown|tan|gray|grey|black|white)$/;var IsCounter=/^(?:definition|proposition|lemma|theorem|corollary|example|exercise|subsection|subsubsection|figure|equation|table)$/;var IsLaTeXElement=/^(?:displayequation|title|author|address|date|abstract|keyword|section|subsection|subsubsection|ref|cite|thebibliography|definition|proposition|lemma|theorem|corollary|example|exercise|itemize|enumerate|enddefinition|endproposition|endlemma|endtheorem|endcorollary|endexample|endexercise|enditemize|endenumerate|LaTeXMathMLlabel|LaTeXMathML|smallskip|medskip|bigskip|quote|quotation|endquote|endquotation|center|endcenter|description|enddescription|inlinemath)$/;var IsTextOnlyArea=/^(?:form|textarea|pre)$/i;var tableid=0;function makeNumberString(cntr){if(sectionCntr>0){if(inAppendix){return"A"+sectionCntr+"."+cntr;}else{return sectionCntr+"."+cntr;}}else{return""+cntr;}};function LaTeXpreProcess(thebody){var TheBody=thebody;if(TheBody.hasChildNodes()){if(!(IsLaTeXElement.test(TheBody.className)))
-{for(var i=0;i<TheBody.childNodes.length;i++){LaTeXpreProcess(TheBody.childNodes[i])}}}
-else{if(TheBody.nodeType==3&&!(IsTextOnlyArea.test(TheBody.parentNode.nodeName)))
-{var str=TheBody.nodeValue;if(!(str==null)){str=str.replace(/\\%/g,"<per>");str=str.replace(/%[^\n]*(?=\n)/g,"");str=str.replace(/%[^\r]*(?=\r)/g,"");str=str.replace(/%[^\n]*$/,"")
-if(isIE&&str.match(/%/g)!=null&&IEcommentWarning){alert("Comments may not have parsed properly.  Try putting in <pre class='LaTeX><div>..</div></pre> structure.");IEcommentWarning=false;}
-str=str.replace(/<per>/g,"%");if(str.match(/XXX[\s\S]*/)!=null){var tmp=str.match(/XXX[\s\S]*/)[0];var tmpstr=tmp.charCodeAt(7)+"::"+tmp.charCodeAt(8)+"::"+tmp.charCodeAt(9)+"::"+tmp.charCodeAt(10)+"::"+tmp.charCodeAt(11)+"::"+tmp.charCodeAt(12)+"::"+tmp.charCodeAt(13);alert(tmpstr);}
-str=str.replace(/([^\\])\\(\s)/g,"$1\u00A0$2");str=str.replace(/\\quad/g,"\u2001");str=str.replace(/\\qquad/g,"\u2001\u2001");str=str.replace(/\\enspace/g,"\u2002");str=str.replace(/\\;/g,"\u2004");str=str.replace(/\\:/g,"\u2005");str=str.replace(/\\,/g,"\u2006");str=str.replace(/\\thinspace/g,"\u200A");str=str.replace(/([^\\])~/g,"$1\u00A0");str=str.replace(/\\~/g,"~");str=str.replace(/\\\[/g," <DEQ> $\\displaystyle{");str=str.replace(/\\\]/g,"}$ <DEQ> ");str=str.replace(/\$\$/g,"${$<DEQ>$}$");str=str.replace(/\\begin\s*\{\s*array\s*\}/g,"\\begin{array}");str=str.replace(/\\end\s*\{\s*array\s*\}/g,"\\end{array}");str=str.replace(/\\begin\s*\{\s*eqnarray\s*\}/g,"  <DEQ>eqno$\\begin{eqnarray}");str=str.replace(/\\end\s*\{\s*eqnarray\s*\}/g,"\\end{eqnarray}$<DEQ>  ");str=str.replace(/\\begin\s*\{\s*eqnarray\*\s*\}/g,"  <DEQ>$\\begin{eqnarray}");str=str.replace(/\\end\s*\{\s*eqnarray\*\s*\}/g,"\\end{eqnarray}$<DEQ>  ");str=str.replace(/\\begin\s*\{\s*displaymath\s*\}/g," <DEQ> $\\displaystyle{");str=str.replace(/\\end\s*\{\s*displaymath\s*\}/g,"}$ <DEQ> ");str=str.replace(/\\begin\s*\{\s*equation\s*\*\s*\}/g," <DEQ> $\\displaystyle{");str=str.replace(/\\end\s*\{\s*equation\s*\*\s*\}/g,"}$ <DEQ> ");str=str.replace(/\\begin\s*\{\s*equation\s*\}/g," <DEQ>eqno$\\displaystyle{");str=str.replace(/\\end\s*\{\s*equation\s*\}/g,"}$ <DEQ> ");str=str.split("<DEQ>");var newFrag=document.createDocumentFragment();for(var i=0;i<str.length;i++){if(i%2){var DEQtable=document.createElement("table");DEQtable.className='displayequation';var DEQtbody=document.createElement("tbody");var DEQtr=document.createElement("tr");var DEQtdeq=document.createElement("td");DEQtdeq.className='eq';str[i]=str[i].replace(/\$\}\$/g,"$\\displaystyle{");str[i]=str[i].replace(/\$\{\$/g,"}");var lbl=str[i].match(/\\label\s*\{\s*(\w+)\s*\}/);var ISeqno=str[i].match(/^eqno/);str[i]=str[i].replace(/^eqno/," ");str[i]=str[i].replace(/\\label\s*\{\s*\w+\s*\}/," ");DEQtdeq.appendChild(document.createTextNode(str[i]));DEQtr.appendChild(DEQtdeq);str[i]=str[i].replace(/\\nonumber/g,"");if(ISeqno!=null||lbl!=null){var DEQtdno=document.createElement("td");DEQtdno.className='eqno';LaTeXCounter["equation"]++;var eqnoString=makeNumberString(LaTeXCounter["equation"]);var DEQanchor=document.createElement("a");if(lbl!=null){DEQanchor.id=lbl[1]};DEQanchor.className="eqno";var anchorSpan=document.createElement("span");anchorSpan.className="eqno";anchorSpan.style.display="none";anchorSpan.appendChild(document.createTextNode(eqnoString));DEQanchor.appendChild(anchorSpan);DEQtdno.appendChild(DEQanchor);var DEQspan=document.createElement("span");DEQspan.className="eqno";DEQspan.appendChild(document.createTextNode("("+eqnoString+")"));DEQtdno.appendChild(DEQspan);DEQtr.appendChild(DEQtdno);}
-DEQtbody.appendChild(DEQtr);DEQtable.appendChild(DEQtbody);newFrag.appendChild(DEQtable);}
-else{str[i]=str[i].replace(/\$\}\$/g,"");str[i]=str[i].replace(/\$\{\$/g,"");str[i]=str[i].replace(/\\maketitle/g,"");str[i]=str[i].replace(/\\begin\s*\{\s*document\s*\}/g,"");str[i]=str[i].replace(/\\end\s*\{\s*document\s*\}/g,"");str[i]=str[i].replace(/\\documentclass[^\}]*?\}/g,"");str[i]=str[i].replace(/\\usepackage[^\}]*?\}/g,"");str[i]=str[i].replace(/\\noindent/g,"");str[i]=str[i].replace(/\\notag/g,"");str[i]=str[i].replace(/\\ref\s*\{\s*(\w+)\}/g," \\[ref\\]$1\\[ ");str[i]=str[i].replace(/\\url\s*\{\s*([^\}\n]+)\}/g," \\[url\\]$1\\[ ");str[i]=str[i].replace(/\\href\s*\{\s*([^\}]+)\}\s*\{\s*([^\}]+)\}/g," \\[href\\]$1\\]$2\\[ ");str[i]=str[i].replace(/\\cite\s*\{\s*(\w+)\}/g," \\[cite\\]$1\\[ ");str[i]=str[i].replace(/\\qed/g,"\u220E");str[i]=str[i].replace(/\\endproof/g,"\u220E");str[i]=str[i].replace(/\\proof/g,"\\textbf{Proof: }");str[i]=str[i].replace(/\\n(?=\s)/g," \\[br\\] \\[ ");str[i]=str[i].replace(/\\newline/g," \\[br\\] \\[ ");str[i]=str[i].replace(/\\linebreak/g," \\[br\\] \\[ ");str[i]=str[i].replace(/\\smallskip/g," \\[logicalbreak\\]smallskip\\[ ");str[i]=str[i].replace(/\\medskip/g," \\[logicalbreak\\]medskip\\[ ");str[i]=str[i].replace(/\\bigskip/g," \\[logicalbreak\\]bigskip\\[ ");str[i]=str[i].replace(/[\n\r]+[ \f\n\r\t\v\u2028\u2029]*[\n\r]+/g," \\[logicalbreak\\]LaTeXMathML\\[ ");if(isIE){str[i]=str[i].replace(/\r/g," ");}
-str[i]=str[i].replace(/\\bibitem\s*([^\{]*\{\s*\w*\s*\})/g," \\[bibitem\\]$1\\[ ");str[i]=str[i].replace(/\\bibitem\s*/g," \\[bibitem\\] \\[ ");str[i]=str[i].replace(/\\item\s*\[\s*(\w+)\s*\]/g," \\[alistitem\\]$1\\[ ");str[i]=str[i].replace(/\\item\s*/g," \\[alistitem\\] \\[ ");str[i]=str[i].replace(/\\appendix/g," \\[appendix\\] \\[ ");str[i]=str[i].replace(/\\begin\s*\{\s*figure\s*\}([\s\S]+?)\\end\s*\{\s*figure\s*\}/g," \\[figure\\]$1\\[ ");str[i]=str[i].replace(/\\begin\s*\{\s*table\s*\}([\s\S]+?)\\end\s*\{\s*table\s*\}/g," \\[table\\]$1\\[ ");str[i]=str[i].replace(/\\begin\s*\{\s*theorem\s*\}/g," \\[theorem\\]Theorem \\[ ");str[i]=str[i].replace(/\\end\s*\{\s*theorem\s*\}/g," \\[endtheorem\\] \\[ ");str[i]=str[i].replace(/\\begin\s*\{\s*definition\s*\}/g," \\[definition\\]Definition \\[ ");str[i]=str[i].replace(/\\end\s*\{\s*definition\s*\}/g," \\[enddefinition\\] \\[ ");str[i]=str[i].replace(/\\begin\s*\{\s*lemma\s*\}/g," \\[lemma\\]Lemma \\[ ");str[i]=str[i].replace(/\\end\s*\{\s*lemma\s*\}/g," \\[endlemma\\] \\[ ");str[i]=str[i].replace(/\\begin\s*\{\s*corollary\s*\}/g," \\[corollary\\]Corollary \\[ ");str[i]=str[i].replace(/\\end\s*\{\s*corollary\s*\}/g," \\[endcorollary\\] \\[ ");str[i]=str[i].replace(/\\begin\s*\{\s*proposition\s*\}/g," \\[proposition\\]Proposition \\[ ");str[i]=str[i].replace(/\\end\s*\{\s*proposition\s*\}/g," \\[endproposition\\] \\[ ");str[i]=str[i].replace(/\\begin\s*\{\s*example\s*\}/g," \\[example\\]Example \\[ ");str[i]=str[i].replace(/\\end\s*\{\s*example\s*\}/g," \\[endexample\\] \\[ ");str[i]=str[i].replace(/\\begin\s*\{\s*exercise\s*\}/g," \\[exercise\\]Exercise \\[ ");str[i]=str[i].replace(/\\end\s*\{\s*exercise\s*\}/g," \\[endexercise\\] \\[ ");str[i]=str[i].replace(/\\begin\s*\{\s*thebibliography\s*\}\s*\{\s*\w+\s*\}/g," \\[thebibliography\\]References \\[ ");str[i]=str[i].replace(/\\begin\s*\{\s*thebibliography\s*\}/g," \\[thebibliography\\]References \\[ ");str[i]=str[i].replace(/\\end\s*\{\s*thebibliography\s*\}/g," \\[endthebibliography\\]References \\[ ");str[i]=str[i].replace(/\\begin\s*\{\s*proof\s*\}/g," \\[proof\\]Proof: \\[ ");if(isIE){str[i]=str[i].replace(/\\end\s*\{\s*proof\s*\}/g,"\u220E \\[endproof\\] \\[ ");}else{str[i]=str[i].replace(/\\end\s*\{\s*proof\s*\}/g," \\[endproof\\] \\[ ");}
-str[i]=str[i].replace(/\\title\s*\{\s*([^\}]+)\}/g," \\[title\\] \\[$1 \\[endtitle\\] \\[ ");str[i]=str[i].replace(/\\author\s*\{\s*([^\}]+)\}/g," \\[author\\] \\[$1 \\[endauthor\\] \\[ ");str[i]=str[i].replace(/\\address\s*\{\s*([^\}]+)\}/g," \\[address\\] \\[$1 \\[endaddress\\] \\[ ");str[i]=str[i].replace(/\\date\s*\{\s*([^\}]+)\}/g," \\[date\\] \\[$1 \\[enddate\\] \\[ ");str[i]=str[i].replace(/\\begin\s*\{\s*keyword\s*\}/g," \\[keyword\\] \\[ ");str[i]=str[i].replace(/\\end\s*\{\s*keyword\s*\}/g," \\[endkeyword\\] \\[ ");str[i]=str[i].replace(/\\begin\s*\{\s*abstract\s*\}/g," \\[abstract\\] \\[ ");str[i]=str[i].replace(/\\end\s*\{\s*abstract\s*\}/g," \\[endabstract\\] \\[ ");str[i]=str[i].replace(/\\begin\s*\{\s*(?!array|tabular)(\w+)\s*\}/g," \\[$1\\] \\[ ");str[i]=str[i].replace(/\\end\s*\{\s*(?!array|tabular)(\w+)\s*\}/g," \\[end$1\\] \\[ ");var sectionIndex=str[i].search(/\\section\s*\{\s*[\s\S]+\}/);while(sectionIndex>=0){str[i]=str[i].replace(/\\section\s*\{/," \\[section\\]");var delimcnt=1;for(var ii=sectionIndex;ii<str[i].length;ii++){if(str[i].charAt(ii)=="{"){delimcnt++};if(str[i].charAt(ii)=="}"){delimcnt--};if(delimcnt==0){str[i]=str[i].substring(0,ii)+"\\[ "+str[i].substring(ii+1,str[i].length);break;}};sectionIndex=str[i].search(/\\section\s*\{\s*[\s\S]+\}/);}
-sectionIndex=str[i].search(/\\subsection\s*\{\s*[\s\S]+\}/);while(sectionIndex>=0){str[i]=str[i].replace(/\\subsection\s*\{/," \\[subsection\\]");var delimcnt=1;for(var ii=sectionIndex;ii<str[i].length;ii++){if(str[i].charAt(ii)=="{"){delimcnt++};if(str[i].charAt(ii)=="}"){delimcnt--};if(delimcnt==0){str[i]=str[i].substring(0,ii)+"\\[ "+str[i].substring(ii+1,str[i].length);break;}};sectionIndex=str[i].search(/\\subsection\s*\{\s*[\s\S]+\}/);}
-sectionIndex=str[i].search(/\\subsubsection\s*\{\s*[\s\S]+\}/);while(sectionIndex>=0){str[i]=str[i].replace(/\\subsubsection\s*\{/," \\[subsubsection\\]");var delimcnt=1;for(var ii=sectionIndex;ii<str[i].length;ii++){if(str[i].charAt(ii)=="{"){delimcnt++};if(str[i].charAt(ii)=="}"){delimcnt--};if(delimcnt==0){str[i]=str[i].substring(0,ii)+"\\[ "+str[i].substring(ii+1,str[i].length);break;}};sectionIndex=str[i].search(/\\subsubsection\s*\{\s*[\s\S]+\}/);}
-var CatToNextEven="";var strtmp=str[i].split("\\[");for(var j=0;j<strtmp.length;j++){if(j%2){var strtmparray=strtmp[j].split("\\]");switch(strtmparray[0]){case"section":var nodeTmp=document.createElement("H2");nodeTmp.className='section';sectionCntr++;for(var div in LaTeXCounter){LaTeXCounter[div]=0};var nodeAnchor=document.createElement("a");if(inAppendix){nodeAnchor.className='appendixsection';}else{nodeAnchor.className='section';}
-var nodeNumString=makeNumberString("");var anchorSpan=document.createElement("span");anchorSpan.className="section";anchorSpan.style.display="none";anchorSpan.appendChild(document.createTextNode(nodeNumString));nodeAnchor.appendChild(anchorSpan);nodeTmp.appendChild(nodeAnchor);var nodeSpan=document.createElement("span");nodeSpan.className='section';nodeSpan.appendChild(document.createTextNode(nodeNumString+" "));nodeTmp.appendChild(nodeSpan);nodeTmp.appendChild(document.createTextNode(strtmparray[1]));newFrag.appendChild(nodeTmp);break;case"subsection":var nodeTmp=document.createElement("H3");nodeTmp.className='subsection';LaTeXCounter["subsection"]++;LaTeXCounter["subsubsection"]=0;var nodeAnchor=document.createElement("a");nodeAnchor.className='subsection';var nodeNumString=makeNumberString(LaTeXCounter["subsection"]);var anchorSpan=document.createElement("span");anchorSpan.className="subsection";anchorSpan.style.display="none";anchorSpan.appendChild(document.createTextNode(nodeNumString));nodeAnchor.appendChild(anchorSpan);nodeTmp.appendChild(nodeAnchor);var nodeSpan=document.createElement("span");nodeSpan.className='subsection';nodeSpan.appendChild(document.createTextNode(nodeNumString+". "));nodeTmp.appendChild(nodeSpan);nodeTmp.appendChild(document.createTextNode(strtmparray[1]));newFrag.appendChild(nodeTmp);break;case"subsubsection":var nodeTmp=document.createElement("H4");nodeTmp.className='subsubsection';LaTeXCounter["subsubsection"]++;var nodeAnchor=document.createElement("a");nodeAnchor.className='subsubsection';var nodeNumString=makeNumberString(LaTeXCounter["subsection"]+"."+LaTeXCounter["subsubsection"]);var anchorSpan=document.createElement("span");anchorSpan.className="subsubsection";anchorSpan.style.display="none";anchorSpan.appendChild(document.createTextNode(nodeNumString));nodeAnchor.appendChild(anchorSpan);nodeTmp.appendChild(nodeAnchor);var nodeSpan=document.createElement("span");nodeSpan.className='subsubsection';nodeSpan.appendChild(document.createTextNode(nodeNumString+". "));nodeTmp.appendChild(nodeSpan);nodeTmp.appendChild(document.createTextNode(strtmparray[1]));newFrag.appendChild(nodeTmp);break;case"href":var nodeTmp=document.createElement("a");nodeTmp.className='LaTeXMathML';nodeTmp.href=strtmparray[1];nodeTmp.appendChild(document.createTextNode(strtmparray[2]));newFrag.appendChild(nodeTmp);break;case"url":var nodeTmp=document.createElement("a");nodeTmp.className='LaTeXMathML';nodeTmp.href=strtmparray[1];nodeTmp.appendChild(document.createTextNode(strtmparray[1]));newFrag.appendChild(nodeTmp);break;case"figure":var nodeTmp=document.createElement("table");nodeTmp.className='figure';var FIGtbody=document.createElement("tbody");var FIGlbl=strtmparray[1].match(/\\label\s*\{\s*(\w+)\s*\}/);strtmparray[1]=strtmparray[1].replace(/\\label\s*\{\w+\}/g,"");var capIndex=strtmparray[1].search(/\\caption\s*\{[\s\S]+\}/);var FIGcap="";if(capIndex>=0){var tmp=strtmparray[1];var delimcnt=0;var capstart=-1;for(var pos=capIndex;pos<tmp.length;pos++){if(tmp.charAt(pos)=="{"){delimcnt++};if(tmp.charAt(pos)=="}"){delimcnt--};if(delimcnt==1&&capstart<0){capstart=pos+1};if(delimcnt==0&&capstart>0){capend=pos-1;FIGcap=tmp.substring(capstart,pos);break}}}
-var FIGtr2=document.createElement("tr");var FIGtd2=document.createElement("td");FIGtd2.className="caption";var FIGanchor=document.createElement("a");FIGanchor.className="figure";if(FIGlbl!=null){FIGanchor.id=FIGlbl[1];}
-LaTeXCounter["figure"]++;var fignmbr=makeNumberString(LaTeXCounter["figure"]);var anchorSpan=document.createElement("span");anchorSpan.className="figure";anchorSpan.style.display="none";anchorSpan.appendChild(document.createTextNode(fignmbr));FIGanchor.appendChild(anchorSpan);FIGtd2.appendChild(FIGanchor);var FIGspan=document.createElement("span");FIGspan.className="figure";FIGspan.appendChild(document.createTextNode("Figure "+fignmbr+". "));FIGtd2.appendChild(FIGspan);FIGtd2.appendChild(document.createTextNode(""+FIGcap));FIGtr2.appendChild(FIGtd2);FIGtbody.appendChild(FIGtr2);var IsSpecial=false;var FIGinfo=strtmparray[1].match(/\\includegraphics\s*\{([^\}]+)\}/);if(FIGinfo==null){FIGinfo=strtmparray[1].match(/\\includegraphics\s*\[[^\]]*\]\s*\{\s*([^\}]+)\s*\}/);}
-if(FIGinfo==null){FIGinfo=strtmparray[1].match(/\\special\s*\{\s*([^\}]+)\}/);IsSpecial=true};if(FIGinfo!=null){var FIGtr1=document.createElement("tr");var FIGtd1=document.createElement("td");FIGtd1.className="image";var FIGimg=document.createElement("img");var FIGsrc=FIGinfo[1];FIGimg.src=FIGsrc;FIGimg.alt="Figure "+FIGsrc+" did not load";FIGimg.title="Figure "+fignmbr+". "+FIGcap;FIGimg.id="figure"+fignmbr;FIGtd1.appendChild(FIGimg);FIGtr1.appendChild(FIGtd1);FIGtbody.appendChild(FIGtr1);}
-nodeTmp.appendChild(FIGtbody);newFrag.appendChild(nodeTmp);break;case"table":var nodeTmp=document.createElement("table");if(strtmparray[1].search(/\\centering/)>=0){nodeTmp.className='LaTeXtable centered';nodeTmp.align="center";}else{nodeTmp.className='LaTeXtable';};tableid++;nodeTmp.id="LaTeXtable"+tableid;var TABlbl=strtmparray[1].match(/\\label\s*\{\s*(\w+)\s*\}/);strtmparray[1]=strtmparray[1].replace(/\\label\s*\{\w+\}/g,"");var capIndex=strtmparray[1].search(/\\caption\s*\{[\s\S]+\}/);var TABcap="";if(capIndex>=0){var tmp=strtmparray[1];var delimcnt=0;var capstart=-1;for(var pos=capIndex;pos<tmp.length;pos++){if(tmp.charAt(pos)=="{"){delimcnt++};if(tmp.charAt(pos)=="}"){delimcnt--};if(delimcnt==1&&capstart<0){capstart=pos+1};if(delimcnt==0&&capstart>0){capend=pos-1;TABcap=tmp.substring(capstart,pos);break}}}
-if(TABcap!=""){var TABtbody=document.createElement("tbody");var TABcaption=document.createElement("caption");TABcaption.className="LaTeXtable centered";var TABanchor=document.createElement("a");TABanchor.className="LaTeXtable";if(TABlbl!=null){TABanchor.id=TABlbl[1];}
-LaTeXCounter["table"]++;var tabnmbr=makeNumberString(LaTeXCounter["table"]);var anchorSpan=document.createElement("span");anchorSpan.className="LaTeXtable";anchorSpan.style.display="none";anchorSpan.appendChild(document.createTextNode(tabnmbr));TABanchor.appendChild(anchorSpan);TABcaption.appendChild(TABanchor);var TABspan=document.createElement("span");TABspan.className="LaTeXtable";TABspan.appendChild(document.createTextNode("Table "+tabnmbr+". "));TABcaption.appendChild(TABspan);TABcaption.appendChild(document.createTextNode(""+TABcap));nodeTmp.appendChild(TABcaption);}
-var TABinfo=strtmparray[1].match(/\\begin\s*\{\s*tabular\s*\}([\s\S]+)\\end\s*\{\s*tabular\s*\}/);if(TABinfo!=null){var TABtbody=document.createElement('tbody');var TABrow=null;var TABcell=null;var row=0;var col=0;var TABalign=TABinfo[1].match(/^\s*\{([^\}]+)\}/);TABinfo=TABinfo[1].replace(/^\s*\{[^\}]+\}/,"");TABinfo=TABinfo.replace(/\\hline/g,"");TABalign[1]=TABalign[1].replace(/\|/g,"");TABalign[1]=TABalign[1].replace(/\s/g,"");TABinfo=TABinfo.split("\\\\");for(row=0;row<TABinfo.length;row++){TABrow=document.createElement("tr");TABinfo[row]=TABinfo[row].split("&");for(col=0;col<TABinfo[row].length;col++){TABcell=document.createElement("td");switch(TABalign[1].charAt(col)){case"l":TABcell.align="left";break;case"c":TABcell.align="center";break;case"r":TABcell.align="right";break;default:TABcell.align="left";};TABcell.appendChild(document.createTextNode(TABinfo[row][col]));TABrow.appendChild(TABcell);}
-TABtbody.appendChild(TABrow);}
-nodeTmp.appendChild(TABtbody);}
-newFrag.appendChild(nodeTmp);break;case"logicalbreak":var nodeTmp=document.createElement("p");nodeTmp.className=strtmparray[1];nodeTmp.appendChild(document.createTextNode("\u00A0"));newFrag.appendChild(nodeTmp);break;case"appendix":inAppendix=true;sectionCntr=0;break;case"alistitem":var EndDiv=document.createElement("div");EndDiv.className="endlistitem";newFrag.appendChild(EndDiv);var BegDiv=document.createElement("div");BegDiv.className="listitem";if(strtmparray[1]!=" "){var BegSpan=document.createElement("span");BegSpan.className="listitemmarker";var boldBegSpan=document.createElement("b");boldBegSpan.appendChild(document.createTextNode(strtmparray[1]+" "));BegSpan.appendChild(boldBegSpan);BegDiv.appendChild(BegSpan);}
-newFrag.appendChild(BegDiv);break;case"br":newFrag.appendChild(document.createElement("br"));break;case"bibitem":newFrag.appendChild(document.createElement("br"));var nodeTmp=document.createElement("a");nodeTmp.className='bibitem';var nodeSpan=document.createElement("span");nodeSpan.className='bibitem';bibcntr++;var lbl=strtmparray[1].match(/\{\s*(\w+)\s*\}/);strtmparray[1]=strtmparray[1].replace(/\s*\{\s*\w+\s*\}/g,"");strtmparray[1]=strtmparray[1].replace(/^\s*\[/,"");strtmparray[1]=strtmparray[1].replace(/\s*\]$/,"");strtmparray[1]=strtmparray[1].replace(/^\s+|\s+$/g,"");if(lbl==null){biblist[bibcntr]="bibitem"+bibcntr}else{biblist[bibcntr]=lbl[1];};nodeTmp.name=biblist[bibcntr];nodeTmp.id=biblist[bibcntr];if(strtmparray[1]!=""){nodeSpan.appendChild(document.createTextNode(strtmparray[1]));}else{nodeSpan.appendChild(document.createTextNode("["+bibcntr+"]"));}
-nodeTmp.appendChild(nodeSpan);newFrag.appendChild(nodeTmp);break;case"cite":var nodeTmp=document.createElement("a");nodeTmp.className='cite';nodeTmp.name='cite';nodeTmp.href="#"+strtmparray[1];newFrag.appendChild(nodeTmp);break;case"ref":var nodeTmp=document.createElement("a");nodeTmp.className='ref';nodeTmp.name='ref';nodeTmp.href="#"+strtmparray[1];newFrag.appendChild(nodeTmp);break;default:var nodeTmp=document.createElement("div");nodeTmp.className=strtmparray[0];if(IsCounter.test(strtmparray[0])){LaTeXCounter[strtmparray[0]]++;var nodeAnchor=document.createElement("a");nodeAnchor.className=strtmparray[0];var divnum=makeNumberString(LaTeXCounter[strtmparray[0]]);var anchorSpan=document.createElement("span");anchorSpan.className=strtmparray[0];anchorSpan.appendChild(document.createTextNode(divnum));anchorSpan.style.display="none";nodeAnchor.appendChild(anchorSpan);nodeTmp.appendChild(nodeAnchor);var nodeSpan=document.createElement("span");nodeSpan.className=strtmparray[0];nodeSpan.appendChild(document.createTextNode(strtmparray[1]+" "+divnum+". "));nodeTmp.appendChild(nodeSpan);}
-if(isIE){if(strtmparray[0]==("thebibliography"||"abstract"||"keyword"||"proof")){var nodeSpan=document.createElement("span");nodeSpan.className=strtmparray[0];nodeSpan.appendChild(document.createTextNode(strtmparray[1]));nodeTmp.appendChild(nodeSpan);}}
-if(strtmparray[0]=="endenumerate"||strtmparray[0]=="enditemize"||strtmparray[0]=="enddescription"){var endDiv=document.createElement("div");endDiv.className="endlistitem";newFrag.appendChild(endDiv);}
-newFrag.appendChild(nodeTmp);if(strtmparray[0]=="enumerate"||strtmparray[0]=="itemize"||strtmparray[0]=="description"){var endDiv=document.createElement("div");endDiv.className="listitem";newFrag.appendChild(endDiv);}}}else{strtmp[j]=strtmp[j].replace(/\\\$/g,"<per>");strtmp[j]=strtmp[j].replace(/\$([^\$]+)\$/g," \\[$1\\[ ");strtmp[j]=strtmp[j].replace(/<per>/g,"\\$");strtmp[j]=strtmp[j].replace(/\\begin\s*\{\s*math\s*\}([\s\S]+?)\\end\s*\{\s*math\s*\}/g," \\[$1\\[ ");var strtmptmp=strtmp[j].split("\\[");for(var jjj=0;jjj<strtmptmp.length;jjj++){if(jjj%2){var nodeTmp=document.createElement("span");nodeTmp.className='inlinemath';nodeTmp.appendChild(document.createTextNode("$"+strtmptmp[jjj]+"$"));newFrag.appendChild(nodeTmp);}else{var TagIndex=strtmptmp[jjj].search(/\\\w+/);var tmpIndex=TagIndex;while(tmpIndex>-1){if(/^\\textcolor/.test(strtmptmp[jjj].substring(TagIndex,strtmptmp[jjj].length))){strtmptmp[jjj]=strtmptmp[jjj].replace(/\\textcolor\s*\{\s*(\w+)\s*\}\s*/," \\[textcolor\\]$1\\]|");}else{if(/^\\colorbox/.test(strtmptmp[jjj].substring(TagIndex,strtmptmp[jjj].length))){strtmptmp[jjj]=strtmptmp[jjj].replace(/\\colorbox\s*\{\s*(\w+)\s*\}\s*/," \\[colorbox\\]$1\\]|");}else{strtmptmp[jjj]=strtmptmp[jjj].substring(0,TagIndex)+strtmptmp[jjj].substring(TagIndex,strtmptmp[jjj].length).replace(/\\\s*(\w+)\s*/," \\[$1\\]|");}}
-TagIndex+=strtmptmp[jjj].substring(TagIndex,strtmptmp[jjj].length).search(/\|/);TagIndex++;strtmptmp[jjj]=strtmptmp[jjj].replace(/\\\]\|/,"\\] ");if(strtmptmp[jjj].charAt(TagIndex)=="{"){strtmptmp[jjj]=strtmptmp[jjj].substring(0,TagIndex)+strtmptmp[jjj].substring(TagIndex+1,strtmptmp[jjj].length);var delimcnt=1;for(var kk=TagIndex;kk<strtmptmp[jjj].length;kk++){if(strtmptmp[jjj].charAt(kk)=="{"){delimcnt++};if(strtmptmp[jjj].charAt(kk)=="}"){delimcnt--};if(delimcnt==0){break;}}
-strtmptmp[jjj]=strtmptmp[jjj].substring(0,kk)+"\\[ "+strtmptmp[jjj].substring(kk+1,strtmptmp[jjj].length);TagIndex=kk+3;}else{strtmptmp[jjj]=strtmptmp[jjj].substring(0,TagIndex)+"\\[ "+strtmptmp[jjj].substring(TagIndex+1,strtmptmp[jjj].length);TagIndex=TagIndex+3;}
-if(TagIndex<strtmptmp[jjj].length){tmpIndex=strtmptmp[jjj].substring(TagIndex,strtmptmp[jjj].length).search(/\\\w+/);}
-else{tmpIndex=-1};TagIndex+=tmpIndex;}
-strtmptmp[jjj]=strtmptmp[jjj].replace(/\\\\\s*\\\\/g,"\\\\");strtmptmp[jjj]=strtmptmp[jjj].replace(/\\\\/g," \\[br\\] \\[ ");strtmptmp[jjj]=strtmptmp[jjj].replace(/\\label\s*\{\s*(\w+)\s*\}/g," \\[a\\]$1\\[ ");var strlbls=strtmptmp[jjj].split("\\[");for(var jj=0;jj<strlbls.length;jj++){if(jj%2){var strtmparray=strlbls[jj].split("\\]");switch(strtmparray[0]){case"textcolor":var nodeTmp=document.createElement("span");nodeTmp.className='LaTeXColor';if(IsColorName.test(strtmparray[1].toLowerCase())){nodeTmp.style.color=LaTeXColor[strtmparray[1].toLowerCase()];}else{nodeTmp.style.color=strtmparray[1];};nodeTmp.appendChild(document.createTextNode(strtmparray[2]));newFrag.appendChild(nodeTmp);break;case"colorbox":var nodeTmp=document.createElement("span");nodeTmp.className='LaTeXColor';if(IsColorName.test(strtmparray[1].toLowerCase())){nodeTmp.style.background=LaTeXColor[strtmparray[1].toLowerCase()];}else{nodeTmp.style.background=strtmparray[1];};nodeTmp.appendChild(document.createTextNode(strtmparray[2]));newFrag.appendChild(nodeTmp);break;case"br":newFrag.appendChild(document.createElement("br"));break;case"a":var nodeTmp=document.createElement("a");nodeTmp.className='LaTeXMathMLlabel';nodeTmp.id=strtmparray[1];nodeTmp.style.display="none";newFrag.appendChild(nodeTmp);break;default:var nodeTmp=document.createElement("span");nodeTmp.className=strtmparray[0];nodeTmp.appendChild(document.createTextNode(strtmparray[1]))
-newFrag.appendChild(nodeTmp);}}else{newFrag.appendChild(document.createTextNode(strlbls[jj]));}}}}}}}};TheBody.parentNode.replaceChild(newFrag,TheBody);}}}
-return TheBody;}
-function LaTeXDivsAndRefs(thebody){var TheBody=thebody;var EndDivClass=null;var AllDivs=TheBody.getElementsByTagName("div");var lbl2id="";var lblnode=null;for(var i=AllDivs.length-1;i>=0;i--){EndDivClass=AllDivs[i].className.match(/end\w+/);if(EndDivClass!=null){EndDivClass=EndDivClass[0];var DivClass=EndDivClass.substring(3,EndDivClass.length);var EndDivNode=AllDivs[i];break;}}
-while(EndDivClass!=null){var newFrag=document.createDocumentFragment();var RootNode=EndDivNode.parentNode;var ClassCount=1;while(EndDivNode.previousSibling!=null&&ClassCount>0){switch(EndDivNode.previousSibling.className){case EndDivClass:ClassCount++;newFrag.insertBefore(EndDivNode.previousSibling,newFrag.firstChild);break;case DivClass:if(EndDivNode.previousSibling.nodeName=="DIV"){ClassCount--;if(lbl2id!=""){EndDivNode.previousSibling.id=lbl2id;lbl2id=""}
-if(ClassCount==0){RootNode=EndDivNode.previousSibling;}else{newFrag.insertBefore(EndDivNode.previousSibling,newFrag.firstChild);}};break;case'LaTeXMathMLlabel':lbl2id=EndDivNode.previousSibling.id;EndDivNode.parentNode.removeChild(EndDivNode.previousSibling);break;default:newFrag.insertBefore(EndDivNode.previousSibling,newFrag.firstChild);}}
-RootNode.appendChild(newFrag);EndDivNode.parentNode.removeChild(EndDivNode);AllDivs=TheBody.getElementsByTagName("DIV");for(i=AllDivs.length-1;i>=0;i--){EndDivClass=AllDivs[i].className.match(/end\w+/);if(EndDivClass!=null){ClassCount=0;EndDivClass=EndDivClass[0];DivClass=EndDivClass.substring(3,EndDivClass.length);EndDivNode=AllDivs[i];RootNode=EndDivNode.parentNode;break;}}}
-var AllDivs=TheBody.getElementsByTagName("div");var DIV2LI=null;for(var i=0;i<AllDivs.length;i++){if(AllDivs[i].className=="itemize"||AllDivs[i].className=="enumerate"||AllDivs[i].className=="description"){if(AllDivs[i].className=="itemize"){RootNode=document.createElement("UL");}else{RootNode=document.createElement("OL");}
-RootNode.className='LaTeXMathML';if(AllDivs[i].hasChildNodes()){AllDivs[i].removeChild(AllDivs[i].firstChild)};while(AllDivs[i].hasChildNodes()){if(AllDivs[i].firstChild.hasChildNodes()){DIV2LI=document.createElement("LI");while(AllDivs[i].firstChild.hasChildNodes()){DIV2LI.appendChild(AllDivs[i].firstChild.firstChild);}
-if(DIV2LI.firstChild.className=="listitemmarker"){DIV2LI.style.listStyleType="none";}
-RootNode.appendChild(DIV2LI)}
-AllDivs[i].removeChild(AllDivs[i].firstChild);}
-AllDivs[i].appendChild(RootNode);}}
-var AllAnchors=TheBody.getElementsByTagName("a");for(var i=0;i<AllAnchors.length;i++){if(AllAnchors[i].className=="ref"||AllAnchors[i].className=="cite"){var label=AllAnchors[i].href.match(/\#(\w+)/);if(label!=null){var labelNode=document.getElementById(label[1]);if(labelNode!=null){var TheSpans=labelNode.getElementsByTagName("SPAN");if(TheSpans!=null){var refNode=TheSpans[0].cloneNode(true);refNode.style.display="inline"
-refNode.className=AllAnchors[i].className;AllAnchors[i].appendChild(refNode);}}}}}
-return TheBody;}
-var AMbody;var AMnoMathML=false,AMtranslated=false;function translate(spanclassAM){if(!AMtranslated){AMtranslated=true;AMinitSymbols();var LaTeXContainers=[];var AllContainers=document.getElementsByTagName('*');var ExtendName="";for(var k=0,l=0;k<AllContainers.length;k++){ExtendName=" "+AllContainers[k].className+" ";if(ExtendName.match(/\sLaTeX\s/)!=null){LaTeXContainers[l]=AllContainers[k];l++;}};if(LaTeXContainers.length>0){for(var m=0;m<LaTeXContainers.length;m++){AMbody=LaTeXContainers[m];try{AMbody=LaTeXDivsAndRefs(LaTeXpreProcess(AMbody));}catch(err){alert("Unknown Error: Defaulting to Original LaTeXMathML");}
-if(AMbody.tagName=="PRE"){var PreChilds=document.createDocumentFragment();var DivChilds=document.createElement("DIV");while(AMbody.hasChildNodes()){DivChilds.appendChild(AMbody.firstChild);}
-PreChilds.appendChild(DivChilds);AMbody.parentNode.replaceChild(PreChilds,AMbody);AMbody=DivChilds;}
-AMprocessNode(AMbody,false,spanclassAM);}}else{AMbody=document.getElementsByTagName("body")[0];try{AMbody=LaTeXDivsAndRefs(LaTeXpreProcess(AMbody));}catch(err){alert("Unknown Error: Defaulting to Original LaTeXMathML");}
-AMprocessNode(AMbody,false,spanclassAM);}}}
-if(isIE){document.write("<object id=\"mathplayer\" classid=\"clsid:32F66A20-7614-11D4-BD11-00104BD3F987\"></object>");document.write("<?import namespace=\"m\" implementation=\"#mathplayer\"?>");}
-function generic()
-{translate();};if(typeof window.addEventListener!='undefined')
-{window.addEventListener('load',generic,false);}
-else if(typeof document.addEventListener!='undefined')
-{document.addEventListener('load',generic,false);}
-else if(typeof window.attachEvent!='undefined')
-{window.attachEvent('onload',generic);}
-else
-{if(typeof window.onload=='function')
-{var existing=onload;window.onload=function()
-{existing();generic();};}
-else
-{window.onload=generic;}}
diff --git a/data/abbreviations b/data/abbreviations
--- a/data/abbreviations
+++ b/data/abbreviations
@@ -1,23 +1,43 @@
+aet.
+aetat.
 al.
 Apr.
 Aug.
+bk.
 Bros.
+c.
 Capt.
 cf.
 ch.
+chap.
+chs.
 Co.
+col.
 Corp.
 cp.
+d.
 Dec.
 Dr.
 e.g.
+ed.
+eds.
 esp.
+f.
+fasc.
 Feb.
+ff.
+fig.
+fl.
+fol.
+fols.
+Fr.
 Gen.
 Gov.
 Hon.
 i.e.
+ill.
 Inc.
+incl.
 Jan.
 Jr.
 Jul.
@@ -29,6 +49,9 @@
 Mr.
 Mrs.
 Ms.
+n.
+n.b.
+nn.
 No.
 Nov.
 Oct.
@@ -37,8 +60,13 @@
 pp.
 Pres.
 Prof.
+pt.
+q.v.
 Rep.
 Rev.
+s.v.
+s.vv.
+saec.
 sec.
 Sen.
 Sep.
@@ -46,5 +74,7 @@
 Sgt.
 Sr.
 St.
+univ.
+viz.
 vol.
 vs.
diff --git a/data/bash_completion.tpl b/data/bash_completion.tpl
--- a/data/bash_completion.tpl
+++ b/data/bash_completion.tpl
@@ -4,7 +4,7 @@
 
 _pandoc()
 {
-    local cur prev opts lastc informats outformats datadir
+    local cur prev opts lastc informats outformats highlight_styles datafiles
     COMPREPLY=()
     cur="${COMP_WORDS[COMP_CWORD]}"
     prev="${COMP_WORDS[COMP_CWORD-1]}"
@@ -14,7 +14,7 @@
     informats="%s"
     outformats="%s"
     highlight_styles="%s"
-    datadir="%s"
+    datafiles="%s"
 
     case "${prev}" in
          --from|-f|--read|-r)
@@ -29,12 +29,16 @@
              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 tectonic wkhtmltopdf weasyprint prince context pdfroff groff" -- ${cur}) )
              return 0
              ;;
          --print-default-data-file)
-             COMPREPLY=( $(compgen -W "reference.odt reference.docx $(find ${datadir} | sed -e 's/.*\/data\///')" -- ${cur}) )
+             COMPREPLY=( $(compgen -W "${datafiles}" -- ${cur}) )
              return 0
              ;;
          --wrap)
@@ -53,8 +57,16 @@
              COMPREPLY=( $(compgen -W "section chapter part" -- ${cur}) )
              return 0
              ;;
-         --highlight-style)
+         --highlight-style|--print-highlight-style)
              COMPREPLY=( $(compgen -W "${highlight_styles}" -- ${cur}) )
+             return 0
+             ;;
+         --eol)
+             COMPREPLY=( $(compgen -W "crlf lf native" -- ${cur}) )
+             return 0
+             ;;
+         --markdown-headings)
+             COMPREPLY=( $(compgen -W "setext atx" -- ${cur}) )
              return 0
              ;;
          *)
diff --git a/data/creole.lua b/data/creole.lua
new file mode 100644
--- /dev/null
+++ b/data/creole.lua
@@ -0,0 +1,190 @@
+-- A sample custom reader for Creole 1.0 (common wiki markup)
+-- http://www.wikicreole.org/wiki/CheatSheet
+
+-- For better performance we put these functions in local variables:
+local P, S, R, Cf, Cc, Ct, V, Cs, Cg, Cb, B, C, Cmt =
+  lpeg.P, lpeg.S, lpeg.R, lpeg.Cf, lpeg.Cc, lpeg.Ct, lpeg.V,
+  lpeg.Cs, lpeg.Cg, lpeg.Cb, lpeg.B, lpeg.C, lpeg.Cmt
+
+local whitespacechar = S(" \t\r\n")
+local specialchar = S("/*~[]\\{}|")
+local wordchar = (1 - (whitespacechar + specialchar))
+local spacechar = S(" \t")
+local newline = P"\r"^-1 * P"\n"
+local blankline = spacechar^0 * newline
+local endline = newline * #-blankline
+local endequals = spacechar^0 * P"="^0 * spacechar^0 * newline
+local cellsep = spacechar^0 * P"|"
+
+local function trim(s)
+   return (s:gsub("^%s*(.-)%s*$", "%1"))
+end
+
+local function ListItem(lev, ch)
+  local start
+  if ch == nil then
+    start = S"*#"
+  else
+    start = P(ch)
+  end
+  local subitem = function(c)
+    if lev < 6 then
+      return ListItem(lev + 1, c)
+    else
+      return (1 - 1) -- fails
+    end
+  end
+  local parser = spacechar^0
+               * start^lev
+               * #(- start)
+               * spacechar^0
+               * Ct((V"Inline" - (newline * spacechar^0 * S"*#"))^0)
+               * newline
+               * (Ct(subitem("*")^1) / pandoc.BulletList
+                  +
+                  Ct(subitem("#")^1) / pandoc.OrderedList
+                  +
+                  Cc(nil))
+               / function (ils, sublist)
+                   return { pandoc.Plain(ils), sublist }
+                 end
+  return parser
+end
+
+-- Grammar
+G = P{ "Doc",
+  Doc = Ct(V"Block"^0)
+      / pandoc.Pandoc ;
+  Block = blankline^0
+        * ( V"Header"
+          + V"HorizontalRule"
+          + V"CodeBlock"
+          + V"List"
+          + V"Table"
+          + V"Para") ;
+  Para = Ct(V"Inline"^1)
+       * newline
+       / pandoc.Para ;
+  HorizontalRule = spacechar^0
+                 * P"----"
+                 * spacechar^0
+                 * newline
+                 / pandoc.HorizontalRule;
+  Header = (P("=")^1 / string.len)
+         * spacechar^1
+         * Ct((V"Inline" - endequals)^1)
+         * endequals
+         / pandoc.Header;
+  CodeBlock = P"{{{"
+            * blankline
+            * C((1 - (newline * P"}}}"))^0)
+            * newline
+            * P"}}}"
+            / pandoc.CodeBlock;
+  Placeholder = P"<<<"
+              * C(P(1) - P">>>")^0
+              * P">>>"
+              / function() return pandoc.Div({}) end;
+  List = V"BulletList"
+       + V"OrderedList" ;
+  BulletList = Ct(ListItem(1,'*')^1)
+             / pandoc.BulletList ;
+  OrderedList = Ct(ListItem(1,'#')^1)
+             / pandoc.OrderedList ;
+  Table = (V"TableHeader" + Cc{})
+        * Ct(V"TableRow"^1)
+        / function(headrow, bodyrows)
+            local numcolumns = #(bodyrows[1])
+            local aligns = {}
+            local widths = {}
+            for i = 1,numcolumns do
+              aligns[i] = pandoc.AlignDefault
+              widths[i] = 0
+            end
+            return pandoc.utils.from_simple_table(
+              pandoc.SimpleTable({}, aligns, widths, headrow, bodyrows))
+          end ;
+  TableHeader = Ct(V"HeaderCell"^1)
+              * cellsep^-1
+              * spacechar^0
+              * newline ;
+  TableRow   = Ct(V"BodyCell"^1)
+             * cellsep^-1
+             * spacechar^0
+             * newline ;
+  HeaderCell = cellsep
+             * P"="
+             * spacechar^0
+             * Ct((V"Inline" - (newline + cellsep))^0)
+             / function(ils) return { pandoc.Plain(ils) } end ;
+  BodyCell   = cellsep
+             * spacechar^0
+             * Ct((V"Inline" - (newline + cellsep))^0)
+             / function(ils) return { pandoc.Plain(ils) } end ;
+  Inline = V"Emph"
+         + V"Strong"
+         + V"LineBreak"
+         + V"Link"
+         + V"URL"
+         + V"Image"
+         + V"Str"
+         + V"Space"
+         + V"SoftBreak"
+         + V"Escaped"
+         + V"Placeholder"
+         + V"Code"
+         + V"Special" ;
+  Str = wordchar^1
+      / pandoc.Str;
+  Escaped = P"~"
+          * C(P(1))
+          / pandoc.Str ;
+  Special = specialchar
+          / pandoc.Str;
+  Space = spacechar^1
+        / pandoc.Space ;
+  SoftBreak = endline
+            * # -(V"HorizontalRule" + V"CodeBlock")
+            / pandoc.SoftBreak ;
+  LineBreak = P"\\\\"
+            / pandoc.LineBreak ;
+  Code = P"{{{"
+       * C((1 - P"}}}")^0)
+       * P"}}}"
+       / trim / pandoc.Code ;
+  Link = P"[["
+       * C((1 - (P"]]" + P"|"))^0)
+       * (P"|" * Ct((V"Inline" - P"]]")^1))^-1 * P"]]"
+       / function(url, desc)
+           local txt = desc or {pandoc.Str(url)}
+           return pandoc.Link(txt, url)
+         end ;
+  Image = P"{{"
+        * #-P"{"
+        * C((1 - (S"}"))^0)
+        * (P"|" * Ct((V"Inline" - P"}}")^1))^-1
+        * P"}}"
+        / function(url, desc)
+            local txt = desc or ""
+            return pandoc.Image(txt, url)
+          end ;
+  URL = P"http"
+      * P"s"^-1
+      * P":"
+      * (1 - (whitespacechar + (S",.?!:;\"'" * #whitespacechar)))^1
+      / function(url)
+          return pandoc.Link(pandoc.Str(url), url)
+        end ;
+  Emph = P"//"
+       * Ct((V"Inline" - P"//")^1)
+       * P"//"
+       / pandoc.Emph ;
+  Strong = P"**"
+         * Ct((V"Inline" -P"**")^1)
+         * P"**"
+         / pandoc.Strong ;
+}
+
+function Reader(input, reader_options)
+  return lpeg.match(G, tostring(input))
+end
diff --git a/data/default.csl b/data/default.csl
new file mode 100644
--- /dev/null
+++ b/data/default.csl
@@ -0,0 +1,3933 @@
+<?xml version="1.0" encoding="utf-8"?>
+<style xmlns="http://purl.org/net/xbiblio/csl" class="in-text" demote-non-dropping-particle="display-and-sort" page-range-format="chicago-16" version="1.0">
+  <!-- This file was generated by the Style Variant Builder <https://github.com/citation-style-language/style-variant-builder>. To contribute changes, modify the template and regenerate variants. -->
+  <info>
+    <title>Chicago Manual of Style 18th edition (author-date)</title>
+    <title-short>CMOS with Bluebook (author-date [13.102])</title-short>
+    <id>http://www.zotero.org/styles/chicago-author-date</id>
+    <link href="http://www.zotero.org/styles/chicago-author-date" rel="self"/>
+    <link href="http://www.zotero.org/styles/chicago-notes-bibliography" rel="template"/>
+    <link href="https://www.chicagomanualofstyle.org/" rel="documentation"/>
+    <author>
+      <name>Andrew Dunning</name>
+      <uri>https://orcid.org/0000-0003-0464-5036</uri>
+    </author>
+    <category citation-format="author-date"/>
+    <category field="anthropology"/>
+    <category field="communications"/>
+    <category field="generic-base"/>
+    <category field="geography"/>
+    <category field="history"/>
+    <category field="humanities"/>
+    <category field="law"/>
+    <category field="linguistics"/>
+    <category field="literature"/>
+    <category field="philosophy"/>
+    <category field="political_science"/>
+    <category field="science"/>
+    <category field="social_science"/>
+    <category field="sociology"/>
+    <category field="theology"/>
+    <summary>Chicago-style source citations (with Bluebook for legal citations), author-date system</summary>
+    <updated>2025-08-07T00:00:00+00:00</updated>
+    <rights license="http://creativecommons.org/licenses/by-sa/3.0/">This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 License</rights>
+  </info>
+  <locale xml:lang="en">
+    <terms>
+      <!-- Chicago omits 'by' from `verb-short` forms; it abbreviates only the most common roles -->
+      <term name="advance-online-publication">ahead of print</term>
+      <term name="anonymous">unsigned</term>
+      <term form="verb-short" name="collection-editor">ed.</term>
+      <term form="short" name="collection-number">
+        <single>vol.</single>
+        <multiple>vols.</multiple>
+      </term>
+      <term form="verb-short" name="compiler">comp.</term>
+      <term form="verb-short" name="editor">ed.</term>
+      <term form="short" name="editor-translator">
+        <single>ed. and trans.</single>
+        <multiple>eds. and trans.</multiple>
+      </term>
+      <term form="short" name="editortranslator">
+        <single>ed. and trans.</single>
+        <multiple>eds. and trans.</multiple>
+      </term>
+      <term form="verb" name="editor-translator">edited and translated by</term>
+      <term form="verb" name="editortranslator">edited and translated by</term>
+      <term form="verb-short" name="editor-translator">ed. and trans.</term>
+      <term form="verb-short" name="editortranslator">ed. and trans.</term>
+      <term form="verb-short" name="illustrator">ill.</term>
+      <term form="short" name="legislation">Pub. L.</term>
+      <term name="manuscript">unpublished manuscript</term>
+      <term name="original-work-published">originally published as</term>
+      <term form="short" name="paper-conference">paper</term>
+      <!-- 'under' replaces 's.v.' from CMOS17 and earlier (CMOS18 14.130) -->
+      <term name="sub-verbo">under</term>
+      <term form="short" name="sub-verbo">under</term>
+      <term name="timestamp">at</term>
+      <term form="verb-short" name="translator">trans.</term>
+    </terms>
+  </locale>
+  <locale xml:lang="en-GB">
+    <terms>
+      <!-- ensure consistency with other `en-GB` contractions -->
+      <term form="short" name="collection-number">
+        <single>vol.</single>
+        <multiple>vols</multiple>
+      </term>
+      <term form="short" name="editor-translator">
+        <single>ed. and trans.</single>
+        <multiple>eds and trans.</multiple>
+      </term>
+      <term form="short" name="editortranslator">
+        <single>ed. and trans.</single>
+        <multiple>eds and trans.</multiple>
+      </term>
+    </terms>
+  </locale>
+  <!-- Contents:
+    
+       This file interprets Chicago using APA's four basic reference elements
+       (cf. CMOS18 14.2, 14.64, 14.161):
+
+        1. Author (CMOS18 13.74-86)
+        2. Date (author-date system only, CMOS18 13.102)
+        3. Title and descriptions (CMOS18 13.87-101)
+            3.1. Title
+            3.2. Description
+            3.3. Identifiers (edition, contributors, volume)
+        4. Source
+            4.1. Serial sources
+            4.2. Monographic sources
+            4.3. Series
+            4.4. Event
+            4.5. Publisher
+            4.6. Date
+            4.7. Locator (including page references)
+            4.8. Medium
+            4.9. Archival location
+            4.10. URL or persistent identifier
+      
+       Freeform annotations to bibliography entries: 
+        
+        5. Notes
+       
+       Chicago also provides parallel rules for legal references following
+       The Bluebook: A Uniform System of Citation (code shared with APA):
+
+        6. Legal references
+  -->
+  <!-- In this file, macros suffixed `-bib` and `-note` are parallel versions
+       of the same features for the bibliography and notes, and all changes
+       must be applied to both. They should only contain differences of
+       punctuation (periods in bibliography, commas in notes) and capitalization,
+       except where the comments indicate structural changes. -->
+  <!-- Categories of CSL item types:
+
+       Serial
+       : article-journal article-magazine article-newspaper periodical post-weblog review review-book
+
+       Serial or Monographic
+       : interview paper-conference
+
+         Monographic with any of `collection-editor compiler editor editorial-director`.
+         A serial `paper-conference` is unpublished if it lacks any of `issue page supplement-number volume`.
+
+       Monographic
+       : article book broadcast chapter classic collection dataset document
+         entry entry-dictionary entry-encyclopedia event figure
+         graphic manuscript map motion_picture musical_score
+         pamphlet patent performance personal_communication post report
+         software song speech standard thesis webpage
+
+       Legal
+       : bill hearing legal_case legislation regulation treaty
+  -->
+  <!-- Variable labels -->
+  <macro name="label-chapter-number">
+    <group delimiter=" ">
+      <choose>
+        <if is-numeric="chapter-number" type="song">
+          <text value="track"/>
+        </if>
+        <else-if is-numeric="chapter-number">
+          <label form="short" variable="chapter-number"/>
+        </else-if>
+      </choose>
+      <text variable="chapter-number"/>
+    </group>
+  </macro>
+  <macro name="label-chapter-number-capitalized">
+    <group delimiter=" ">
+      <choose>
+        <if is-numeric="chapter-number" type="song">
+          <text text-case="capitalize-first" value="track"/>
+        </if>
+        <else-if is-numeric="chapter-number">
+          <label form="short" text-case="capitalize-first" variable="chapter-number"/>
+        </else-if>
+      </choose>
+      <text text-case="capitalize-first" variable="chapter-number"/>
+    </group>
+  </macro>
+  <macro name="label-collection-number">
+    <group delimiter=" ">
+      <choose>
+        <if is-numeric="collection-number">
+          <label form="short" variable="collection-number"/>
+        </if>
+      </choose>
+      <text variable="collection-number"/>
+    </group>
+  </macro>
+  <macro name="label-edition">
+    <group delimiter=" ">
+      <choose>
+        <if is-numeric="edition">
+          <number form="ordinal" variable="edition"/>
+          <label form="short" variable="edition"/>
+        </if>
+        <else-if match="any" type="article-journal article-magazine article-newspaper periodical post-weblog review review-book">
+          <!-- full label for serial edition (CMOS18 14.89) -->
+          <text variable="edition"/>
+          <label variable="edition"/>
+        </else-if>
+        <else-if match="any" type="interview paper-conference">
+          <choose>
+            <if match="any" variable="collection-editor compiler editor editorial-director">
+              <!-- monographic usage -->
+              <text variable="edition"/>
+            </if>
+            <else>
+              <!-- serial usage -->
+              <text variable="edition"/>
+              <label variable="edition"/>
+            </else>
+          </choose>
+        </else-if>
+        <else>
+          <text variable="edition"/>
+        </else>
+      </choose>
+    </group>
+  </macro>
+  <macro name="label-edition-capitalized">
+    <group delimiter=" ">
+      <choose>
+        <if is-numeric="edition">
+          <number form="ordinal" variable="edition"/>
+          <label form="short" variable="edition"/>
+        </if>
+        <else-if match="any" type="article-journal article-magazine article-newspaper periodical post-weblog review review-book">
+          <!-- full label for serial edition (CMOS18 14.89) -->
+          <text text-case="title" variable="edition"/>
+          <label text-case="capitalize-first" variable="edition"/>
+        </else-if>
+        <else-if match="any" type="interview paper-conference">
+          <choose>
+            <if match="any" variable="collection-editor compiler editor editorial-director">
+              <!-- monographic usage -->
+              <text text-case="capitalize-first" variable="edition"/>
+            </if>
+            <else>
+              <!-- serial usage -->
+              <text text-case="title" variable="edition"/>
+              <label text-case="capitalize-first" variable="edition"/>
+            </else>
+          </choose>
+        </else-if>
+        <else>
+          <text text-case="capitalize-first" variable="edition"/>
+        </else>
+      </choose>
+    </group>
+  </macro>
+  <macro name="label-issue">
+    <group delimiter=" ">
+      <label form="short" variable="issue"/>
+      <text variable="issue"/>
+    </group>
+  </macro>
+  <macro name="label-locator">
+    <group delimiter=" ">
+      <choose>
+        <if locator="page"/>
+        <else-if match="any" type="bill hearing legal_case legislation regulation treaty">
+          <!-- Bluebook-style labels for legal types (CMOS18 14.174) -->
+          <choose>
+            <if locator="chapter paragraph section" match="any">
+              <label form="symbol" variable="locator"/>
+            </if>
+            <else>
+              <label form="short" variable="locator"/>
+            </else>
+          </choose>
+        </else-if>
+        <else-if is-numeric="locator">
+          <choose>
+            <if locator="line">
+              <label variable="locator"/>
+            </if>
+            <else>
+              <label form="short" variable="locator"/>
+            </else>
+          </choose>
+        </else-if>
+        <else-if locator="chapter line verse" match="any"/>
+        <!-- a non-numeric canonical reference is identified by its formatting and does not need a label (CMOS18 14.143-54) -->
+        <else>
+          <label form="short" variable="locator"/>
+        </else>
+      </choose>
+      <text variable="locator"/>
+    </group>
+  </macro>
+  <macro name="label-number-capitalized">
+    <group delimiter=" ">
+      <choose>
+        <if type="standard"/>
+        <else-if is-numeric="number" match="any" type="legislation regulation">
+          <label form="short" text-case="capitalize-first" variable="number"/>
+        </else-if>
+      </choose>
+      <text text-case="capitalize-first" variable="number"/>
+    </group>
+  </macro>
+  <macro name="label-number-of-volumes">
+    <group delimiter=" ">
+      <text variable="number-of-volumes"/>
+      <choose>
+        <if is-numeric="number-of-volumes">
+          <label form="short" variable="number-of-volumes"/>
+        </if>
+      </choose>
+    </group>
+  </macro>
+  <macro name="label-part-number">
+    <group delimiter=" ">
+      <choose>
+        <if is-numeric="part-number">
+          <!-- TODO: Replace with `part-number` label when CSL provides one -->
+          <text form="short" term="part"/>
+        </if>
+      </choose>
+      <text variable="part-number"/>
+    </group>
+  </macro>
+  <macro name="label-part-number-capitalized">
+    <group delimiter=" ">
+      <choose>
+        <if is-numeric="part-number">
+          <!-- TODO: Replace with `part-number` label when CSL provides one -->
+          <text form="short" term="part" text-case="capitalize-first"/>
+        </if>
+      </choose>
+      <text text-case="capitalize-first" variable="part-number"/>
+    </group>
+  </macro>
+  <macro name="label-section-capitalized">
+    <group delimiter=" ">
+      <choose>
+        <if is-numeric="section">
+          <label form="short" text-case="capitalize-first" variable="section"/>
+        </if>
+      </choose>
+      <text text-case="title" variable="section"/>
+    </group>
+  </macro>
+  <macro name="label-section-symbol">
+    <group delimiter=" ">
+      <label form="symbol" variable="section"/>
+      <text variable="section"/>
+    </group>
+  </macro>
+  <macro name="label-supplement-number">
+    <group delimiter=" ">
+      <choose>
+        <!-- TODO: Replace with `supplement-number` label when CSL provides one -->
+        <if is-numeric="supplement-number" variable="volume-title">
+          <!-- if there is a volume title, it is already described as a supplement -->
+          <text form="short" term="issue"/>
+        </if>
+        <else-if is-numeric="supplement-number" type="periodical" variable="title">
+          <text form="short" term="issue"/>
+        </else-if>
+        <else-if is-numeric="supplement-number">
+          <text form="short" term="supplement"/>
+        </else-if>
+      </choose>
+      <text variable="supplement-number"/>
+    </group>
+  </macro>
+  <macro name="label-version">
+    <group delimiter=" ">
+      <choose>
+        <if type="software">
+          <!-- short version label for software (CMOS18 14.169) -->
+          <label form="short" variable="version"/>
+        </if>
+        <else>
+          <label variable="version"/>
+        </else>
+      </choose>
+      <text variable="version"/>
+    </group>
+  </macro>
+  <macro name="label-version-capitalized">
+    <group delimiter=" ">
+      <choose>
+        <if type="software">
+          <!-- short version label for software (CMOS18 14.169) -->
+          <label form="short" text-case="capitalize-first" variable="version"/>
+        </if>
+        <else>
+          <label text-case="capitalize-first" variable="version"/>
+        </else>
+      </choose>
+      <text variable="version"/>
+    </group>
+  </macro>
+  <macro name="label-volume">
+    <group delimiter=" ">
+      <choose>
+        <if is-numeric="volume">
+          <label form="short" variable="volume"/>
+        </if>
+      </choose>
+      <text variable="volume"/>
+    </group>
+  </macro>
+  <macro name="label-volume-capitalized">
+    <group delimiter=" ">
+      <choose>
+        <if is-numeric="volume">
+          <label form="short" text-case="capitalize-first" variable="volume"/>
+        </if>
+      </choose>
+      <text text-case="capitalize-first" variable="volume"/>
+    </group>
+  </macro>
+  <!-- 1. Author (CMOS18 13.74-86) -->
+  <macro name="author-bib">
+    <names variable="composer">
+      <name and="text" delimiter-precedes-last="always" name-as-sort-order="first"/>
+      <label form="short" prefix=", "/>
+      <substitute>
+        <names variable="author"/>
+        <!-- cf. `interview` model (CMOS18 14.110); if it is desired to prioritize `host` over `guest`, the latter could be encoded as a `contributor` -->
+        <names variable="guest"/>
+        <names variable="host"/>
+        <choose>
+          <if type="song">
+            <names variable="performer"/>
+          </if>
+        </choose>
+        <choose>
+          <if type="classic">
+            <!-- contributors fall after the title of `classic` (CMOS18 14.147) -->
+            <text macro="author-title-substitute-bib"/>
+          </if>
+          <else-if type="entry-dictionary" variable="container-title">
+            <!-- contributors fall after the title of unsigned reference entries (CMOS18 14.130) -->
+            <text macro="author-title-substitute-container"/>
+          </else-if>
+          <else-if type="entry-encyclopedia" variable="container-title">
+            <text macro="author-title-substitute-container"/>
+          </else-if>
+        </choose>
+        <names variable="illustrator"/>
+        <choose>
+          <if match="none" type="standard">
+            <names variable="editor-translator"/>
+            <names variable="editor"/>
+            <names variable="translator"/>
+            <names variable="collection-editor"/>
+          </if>
+        </choose>
+        <names variable="director"/>
+        <choose>
+          <!-- serial `broadcast` prioritizes title (CMOS18 14.165, 14.168) -->
+          <if type="broadcast" variable="container-title number title"/>
+          <else>
+            <names variable="producer"/>
+            <names variable="executive-producer"/>
+            <names variable="series-creator"/>
+            <choose>
+              <if type="broadcast">
+                <names variable="contributor"/>
+              </if>
+            </choose>
+          </else>
+        </choose>
+        <names variable="editorial-director"/>
+        <names variable="compiler"/>
+        <choose>
+          <if match="any" type="event performance speech">
+            <names variable="chair"/>
+            <names variable="organizer"/>
+          </if>
+        </choose>
+        <names variable="curator"/>
+        <choose>
+          <if type="software">
+            <!-- `software` listed under the name of the publisher or developer (CMOS18 14.169) -->
+            <text variable="publisher"/>
+          </if>
+          <else-if type="standard">
+            <!-- `standard` listed in bibliography under organization, but note omits this (CMOS18 14.159) -->
+            <text variable="authority"/>
+          </else-if>
+        </choose>
+        <text macro="author-title-substitute-container"/>
+        <text macro="author-title-substitute-bib"/>
+        <choose>
+          <if type="manuscript">
+            <choose>
+              <if match="none" variable="container-title event-date event-place event-title genre title publisher publisher-place">
+                <text macro="source-archive-bib"/>
+              </if>
+            </choose>
+          </if>
+        </choose>
+      </substitute>
+    </names>
+  </macro>
+  <macro name="author-inline">
+    <choose>
+      <if match="any" type="bill hearing legal_case legislation regulation treaty">
+        <text macro="title-and-descriptions-short"/>
+      </if>
+      <else-if match="any" type="interview personal_communication">
+        <text macro="author-inline-and-recipient"/>
+      </else-if>
+      <else>
+        <names variable="composer">
+          <name and="text" form="short" initialize-with=". "/>
+          <substitute>
+            <names variable="author"/>
+            <names variable="guest"/>
+            <names variable="host"/>
+            <choose>
+              <if type="song">
+                <names variable="performer"/>
+              </if>
+            </choose>
+            <choose>
+              <if match="any" type="classic performance">
+                <!-- contributors fall after the title of `classic` (CMOS18 14.147), `performance` (CMOS18 14.166) -->
+                <text macro="author-title-substitute-short"/>
+              </if>
+              <else-if match="any" type="entry entry-dictionary entry-encyclopedia">
+                <!-- contributors fall after the title of unsigned reference entries (CMOS18 14.130) -->
+                <choose>
+                  <if variable="container-title">
+                    <text macro="author-title-substitute-container"/>
+                  </if>
+                </choose>
+              </else-if>
+            </choose>
+            <names variable="illustrator"/>
+            <choose>
+              <if match="none" type="standard">
+                <names variable="editor-translator"/>
+                <names variable="editor"/>
+                <names variable="translator"/>
+                <names variable="collection-editor"/>
+              </if>
+            </choose>
+            <choose>
+              <if type="broadcast" variable="container-title number title"/>
+              <else>
+                <names variable="director"/>
+                <names variable="producer"/>
+                <names variable="executive-producer"/>
+                <names variable="series-creator"/>
+                <choose>
+                  <if type="broadcast">
+                    <names variable="contributor"/>
+                  </if>
+                </choose>
+              </else>
+            </choose>
+            <names variable="editorial-director"/>
+            <names variable="compiler"/>
+            <choose>
+              <if match="any" type="event performance speech">
+                <names variable="chair"/>
+                <names variable="organizer"/>
+              </if>
+            </choose>
+            <names variable="curator"/>
+            <choose>
+              <if type="software">
+                <!-- `software` listed under the name of the publisher or developer (CMOS18 14.169) -->
+                <text variable="publisher"/>
+              </if>
+              <else-if type="standard">
+                <!-- `standard` listed in bibliography under organization, but note omits this (CMOS18 14.159) -->
+                <text variable="authority"/>
+              </else-if>
+            </choose>
+            <text macro="author-title-substitute-container-short"/>
+            <text macro="author-title-substitute-short"/>
+            <choose>
+              <if type="manuscript">
+                <choose>
+                  <if match="none" variable="container-title event-date event-place event-title genre title publisher publisher-place">
+                    <text macro="source-archive-note"/>
+                  </if>
+                </choose>
+              </if>
+            </choose>
+          </substitute>
+        </names>
+      </else>
+    </choose>
+  </macro>
+  <macro name="author-sort">
+    <choose>
+      <if match="any" type="bill hearing legal_case legislation regulation treaty">
+        <text macro="legal-title"/>
+      </if>
+      <else>
+        <text macro="author-bib"/>
+      </else>
+    </choose>
+  </macro>
+  <!-- Author elements -->
+  <macro name="author-inline-and-recipient">
+    <!-- identical to `author-short-and-recipient` but with initialization -->
+    <group delimiter=" ">
+      <choose>
+        <!-- Inaccessible personal commmunication is cited in-text (CMOS18 14.111) -->
+        <if match="none" variable="archive archive-place container-title DOI number publisher references URL">
+          <!-- These variables indicate whether the letter is retrievable by the reader -->
+          <group delimiter=", ">
+            <names variable="author">
+              <name and="text" initialize-with=". "/>
+              <substitute>
+                <text macro="title-and-descriptions-short"/>
+              </substitute>
+            </names>
+          </group>
+          <choose>
+            <if match="none" variable="genre">
+              <names variable="recipient">
+                <label form="verb" suffix=" "/>
+                <name and="text" initialize-with=". "/>
+              </names>
+            </if>
+          </choose>
+        </if>
+        <else-if variable="author recipient">
+          <names variable="author">
+            <label/>
+            <name and="text" form="short" initialize-with=". "/>
+          </names>
+          <choose>
+            <if match="none" variable="genre">
+              <names variable="recipient">
+                <label form="verb" suffix=" "/>
+                <name and="text" form="short" initialize-with=". "/>
+              </names>
+            </if>
+          </choose>
+        </else-if>
+        <else>
+          <names variable="author">
+            <name and="text" form="short" initialize-with=". "/>
+            <substitute>
+              <text macro="title-and-descriptions-short"/>
+            </substitute>
+          </names>
+        </else>
+      </choose>
+    </group>
+  </macro>
+  <macro name="author-title-substitute-bib">
+    <choose>
+      <if match="any" type="review review-book" variable="reviewed-author reviewed-genre reviewed-title">
+        <!-- If a review has no `reviewed-genre` or `reviewed-title`, assume that `title` contains the title of the reviewed work; the description provides it. -->
+        <choose>
+          <if variable="reviewed-genre title">
+            <text macro="title-bib"/>
+          </if>
+          <else-if variable="reviewed-genre reviewed-title title">
+            <text macro="title-bib"/>
+          </else-if>
+          <else>
+            <text macro="title-and-descriptions-bib"/>
+          </else>
+        </choose>
+      </if>
+      <else-if variable="title">
+        <text macro="title-bib"/>
+      </else-if>
+      <else>
+        <!-- If an item has no `title`, substitute with descriptions. -->
+        <text macro="title-and-descriptions-bib"/>
+      </else>
+    </choose>
+  </macro>
+  <macro name="author-title-substitute-short">
+    <choose>
+      <if match="any" type="review review-book" variable="reviewed-author reviewed-genre reviewed-title">
+        <!-- If a review has no `reviewed-genre` or `reviewed-title`, assume that `title` contains the title of the reviewed work; the description provides it. -->
+        <choose>
+          <if variable="reviewed-genre title">
+            <text macro="title-short"/>
+          </if>
+          <else-if variable="reviewed-genre reviewed-title title">
+            <text macro="title-short"/>
+          </else-if>
+          <else>
+            <text macro="title-and-descriptions-short"/>
+          </else>
+        </choose>
+      </if>
+      <else-if variable="title">
+        <text macro="title-short"/>
+      </else-if>
+      <else>
+        <!-- If an item has no `title`, substitute with descriptions and capitalize -->
+        <text macro="title-and-descriptions-bib"/>
+      </else>
+    </choose>
+  </macro>
+  <macro name="author-title-substitute-container">
+    <choose>
+      <if match="none" variable="container-title"/>
+      <else-if match="any" type="article-magazine article-newspaper">
+        <!-- Anonymous magazine and newspaper articles substitute name of publication (CMOS18 14.87, 14.97) -->
+        <text macro="source-serial-name"/>
+      </else-if>
+      <else-if match="any" type="review review-book" variable="reviewed-author reviewed-genre reviewed-title">
+        <!-- Publication name also substituted for unsigned reviews (CMOS18 14.102) -->
+        <text macro="source-serial-name"/>
+      </else-if>
+      <else-if match="any" type="interview paper-conference">
+        <choose>
+          <if match="none" variable="collection-editor compiler editor editorial-director">
+            <!-- serial usage -->
+            <text macro="source-serial-name"/>
+          </if>
+        </choose>
+      </else-if>
+      <else-if match="any" type="entry entry-dictionary entry-encyclopedia">
+        <!-- Anonymous entries in reference works (CMOS18 14.130) -->
+        <text font-style="italic" text-case="title" variable="container-title"/>
+      </else-if>
+      <else-if type="broadcast">
+        <!-- TV broadcasts and podcasts (CMOS18 14.165, 14.168) -->
+        <text font-style="italic" text-case="title" variable="container-title"/>
+      </else-if>
+      <else-if type="webpage">
+        <!-- Website title substituted in bibliography only (CMOS18 14.104) -->
+        <text text-case="title" variable="container-title"/>
+      </else-if>
+    </choose>
+  </macro>
+  <macro name="author-title-substitute-container-short">
+    <choose>
+      <if match="none" variable="container-title"/>
+      <else-if match="any" type="article-magazine article-newspaper">
+        <!-- Anonymous magazine/newspaper articles substitute name of publication (CMOS18 14.87, 14.97) -->
+        <text font-style="italic" text-case="title" variable="container-title"/>
+      </else-if>
+      <else-if match="any" type="review review-book" variable="reviewed-author reviewed-genre reviewed-title">
+        <!-- Publication name also substituted for unsigned reviews (CMOS18 14.102) -->
+        <text font-style="italic" text-case="title" variable="container-title"/>
+      </else-if>
+      <else-if match="any" type="interview paper-conference">
+        <choose>
+          <if match="none" variable="collection-editor compiler editor editorial-director">
+            <!-- serial usage -->
+            <text font-style="italic" text-case="title" variable="container-title"/>
+          </if>
+        </choose>
+      </else-if>
+      <else-if match="any" type="entry entry-dictionary entry-encyclopedia">
+        <!-- Anonymous entries in reference works (CMOS18 14.130) -->
+        <text font-style="italic" text-case="title" variable="container-title"/>
+      </else-if>
+      <else-if type="broadcast">
+        <!-- TV broadcasts and podcasts (CMOS18 14.165, 14.168) -->
+        <text font-style="italic" text-case="title" variable="container-title"/>
+      </else-if>
+      <else-if type="webpage">
+        <!-- Website title substituted in bibliography only (CMOS18 14.104) -->
+        <text text-case="title" variable="container-title"/>
+      </else-if>
+    </choose>
+  </macro>
+  <!-- 2. Date (CMOS18 13.102) -->
+  <macro name="date">
+    <choose>
+      <if variable="issued">
+        <group delimiter=" ">
+          <!-- reprints and earlier editions may give original year in brackets (CMOS18 14.16) -->
+          <text macro="date-original-year" prefix="(" suffix=")"/>
+          <group>
+            <text macro="date-issued-year"/>
+            <text variable="year-suffix"/>
+          </group>
+        </group>
+      </if>
+      <else-if variable="available-date">
+        <date date-parts="year" form="text" variable="available-date"/>
+      </else-if>
+      <else-if variable="event-date">
+        <text macro="date-event-year"/>
+      </else-if>
+      <else-if variable="status">
+        <group>
+          <!-- Print the status variable rather than use generic CSL terms (`in press`, etc.) -->
+          <text text-case="capitalize-first" variable="status"/>
+          <text prefix="-" variable="year-suffix"/>
+        </group>
+      </else-if>
+      <else-if type="collection">
+        <!-- do not give n.d. for archival collections (CMOS18 14.128) -->
+        <text prefix="-" variable="year-suffix"/>
+      </else-if>
+      <else-if type="manuscript">
+        <!-- do not give n.d. with a bare shelfmark -->
+        <choose>
+          <if match="any" variable="container-title event-date event-place event-title genre title publisher publisher-place">
+            <text form="short" term="no date"/>
+            <text prefix="-" variable="year-suffix"/>
+          </if>
+        </choose>
+      </else-if>
+      <else>
+        <text form="short" term="no date"/>
+        <text prefix="-" variable="year-suffix"/>
+      </else>
+    </choose>
+  </macro>
+  <macro name="date-short">
+    <choose>
+      <if variable="issued">
+        <group delimiter=" ">
+          <choose>
+            <if is-uncertain-date="original-date">
+              <!-- Uncertain date already has square brackets -->
+              <text macro="date-original-year"/>
+            </if>
+            <else>
+              <text macro="date-original-year" prefix="[" suffix="]"/>
+            </else>
+          </choose>
+          <group>
+            <choose>
+              <if match="any" type="interview personal_communication">
+                <choose>
+                  <if match="any" variable="archive archive-place container-title DOI number publisher references URL">
+                    <!-- These variables indicate that the communication is retrievable by the reader. If not, then use the in-text-only personal communication format -->
+                    <text macro="date-issued-year"/>
+                  </if>
+                  <else>
+                    <text macro="date-issued-full"/>
+                  </else>
+                </choose>
+              </if>
+              <else>
+                <text macro="date-issued-year"/>
+              </else>
+            </choose>
+            <text variable="year-suffix"/>
+          </group>
+        </group>
+      </if>
+      <else-if variable="available-date">
+        <date date-parts="year" form="text" variable="available-date"/>
+      </else-if>
+      <else-if variable="event-date">
+        <text macro="date-event-year"/>
+      </else-if>
+      <else-if variable="status">
+        <!-- Print the status variable rather than use generic CSL terms (`in press`, etc.) -->
+        <text text-case="lowercase" variable="status"/>
+        <text prefix="-" variable="year-suffix"/>
+      </else-if>
+      <else-if match="any" type="interview personal_communication">
+        <choose>
+          <if match="any" variable="archive archive-place container-title DOI number publisher references URL">
+            <!-- only give n.d. for accessible personal communication (CMOS18 14.111)-->
+            <text form="short" term="no date"/>
+          </if>
+        </choose>
+        <text prefix="-" variable="year-suffix"/>
+      </else-if>
+      <else-if match="any" type="classic collection entry entry-dictionary entry-encyclopedia">
+        <!-- do not give n.d. for archival collections (CMOS18 14.128), `classic` (CMOS18 14.143), or reference entries (CMOS18 14.131) -->
+        <text prefix="-" variable="year-suffix"/>
+      </else-if>
+      <else-if type="manuscript">
+        <!-- do not give n.d. with a bare shelfmark -->
+        <choose>
+          <if match="any" variable="container-title event-date event-place event-title genre title publisher publisher-place">
+            <text form="short" term="no date"/>
+            <text prefix="-" variable="year-suffix"/>
+          </if>
+        </choose>
+      </else-if>
+      <else>
+        <text form="short" term="no date"/>
+        <text prefix="-" variable="year-suffix"/>
+      </else>
+    </choose>
+  </macro>
+  <macro name="date-sort-group">
+    <!-- Sort items with and without dates (CMOS18 14.44):
+
+          1. items with dates (= 0)
+          2. `no date` items (= 1)
+          3. items with `status` (forthcoming, in press, etc.) (= 2) -->
+    <choose>
+      <if variable="issued">
+        <text value="0"/>
+      </if>
+      <else-if variable="status">
+        <text value="2"/>
+      </else-if>
+      <else>
+        <!-- n.d. -->
+        <text value="1"/>
+      </else>
+    </choose>
+  </macro>
+  <macro name="date-sort-year">
+    <!-- while reference lists are to be sorted chronologically (CMOS18 13.112), it appears that only the year is to be taken into account (CMOS18 13.114) -->
+    <choose>
+      <if type="personal_communication" variable="event-date issued">
+        <date date-parts="year" form="text" variable="event-date"/>
+      </if>
+      <else>
+        <text macro="date-issued-year"/>
+      </else>
+    </choose>
+  </macro>
+  <!-- Date elements -->
+  <macro name="date-event-full">
+    <choose>
+      <if is-uncertain-date="issued">
+        <!-- guessed-at date (CMOS18 14.44) -->
+        <date form="text" prefix="[" suffix="?]" variable="event-date"/>
+      </if>
+      <else>
+        <date form="text" variable="event-date"/>
+      </else>
+    </choose>
+  </macro>
+  <macro name="date-event-year">
+    <choose>
+      <if is-uncertain-date="issued">
+        <!-- guessed-at date (CMOS18 14.44) -->
+        <date date-parts="year" form="text" prefix="[" suffix="?]" variable="event-date"/>
+      </if>
+      <else>
+        <date date-parts="year" form="text" variable="event-date"/>
+      </else>
+    </choose>
+  </macro>
+  <macro name="date-issued-full">
+    <choose>
+      <if is-uncertain-date="issued">
+        <!-- guessed-at date (CMOS18 14.44) -->
+        <date form="text" prefix="[" suffix="?]" variable="issued"/>
+      </if>
+      <else>
+        <date form="text" variable="issued"/>
+      </else>
+    </choose>
+  </macro>
+  <macro name="date-issued-month">
+    <date variable="issued">
+      <date-part name="month"/>
+    </date>
+  </macro>
+  <macro name="date-issued-month-day">
+    <date variable="issued">
+      <date-part name="month"/>
+      <date-part name="day" prefix=" "/>
+    </date>
+  </macro>
+  <macro name="date-issued-year">
+    <choose>
+      <if is-uncertain-date="issued">
+        <!-- guessed-at date (CMOS18 14.44) -->
+        <date date-parts="year" form="text" prefix="[" suffix="?]" variable="issued"/>
+      </if>
+      <else>
+        <date date-parts="year" form="text" variable="issued"/>
+      </else>
+    </choose>
+  </macro>
+  <macro name="date-original-month">
+    <date variable="original-date">
+      <date-part name="month"/>
+    </date>
+  </macro>
+  <macro name="date-original-month-day">
+    <date variable="original-date">
+      <date-part name="month"/>
+      <date-part name="day" prefix=" "/>
+    </date>
+  </macro>
+  <macro name="date-original-year">
+    <choose>
+      <if is-uncertain-date="original-date">
+        <date date-parts="year" form="text" prefix="[" suffix="?]" variable="original-date"/>
+      </if>
+      <else>
+        <date date-parts="year" form="text" variable="original-date"/>
+      </else>
+    </choose>
+  </macro>
+  <!-- 3. Title and descriptions (CMOS18 13.87-101) -->
+  <macro name="title-and-descriptions-bib">
+    <group delimiter=". ">
+      <choose>
+        <if variable="title">
+          <text macro="title-bib"/>
+          <text macro="description-bib"/>
+          <text macro="identifier-bib"/>
+        </if>
+        <else-if match="any" type="bill report">
+          <!-- Bills, resolutions, and congressional reports substitute bill number if no title -->
+          <!-- Congressional reports are indistinguishable from other reports -->
+          <text macro="identifier-number-bib"/>
+          <text macro="identifier-bib"/>
+          <text macro="description-bib"/>
+        </else-if>
+        <else>
+          <text macro="description-bib"/>
+          <text macro="identifier-bib"/>
+        </else>
+      </choose>
+    </group>
+  </macro>
+  <macro name="title-and-descriptions-short">
+    <choose>
+      <if variable="title">
+        <text macro="title-short"/>
+      </if>
+      <else-if match="any" type="bill report">
+        <!-- Bills, resolutions, and congressional reports substitute bill number if no title -->
+        <text macro="legal-identifier-bill-report"/>
+      </else-if>
+      <else>
+        <text macro="description-short"/>
+      </else>
+    </choose>
+  </macro>
+  <macro name="title-and-source-bib">
+    <group delimiter=". ">
+      <choose>
+        <if type="broadcast" variable="container-title number title">
+          <!-- Bespoke `broadcast` format (CMOS18 14.165, 14.168) -->
+          <text macro="source-monographic-title-bib"/>
+          <group delimiter=", ">
+            <text macro="identifier-number-bib"/>
+            <text macro="title-bib"/>
+            <text macro="description-bib"/>
+            <text macro="source-monographic-identifier-contributors-bib"/>
+          </group>
+          <text macro="source-series-bib"/>
+          <choose>
+            <!-- show event information here only if not collapsed with `issued` (CMOS18 14.167) -->
+            <if match="any" variable="event-date original-date original-publisher original-publisher-place publisher status">
+              <text macro="source-event-bib"/>
+            </if>
+          </choose>
+        </if>
+        <else-if type="chapter" variable="container-title genre">
+          <!-- 'Introduction to' etc. (CMOS18 14.12, 14.14) -->
+          <group delimiter=" ">
+            <text macro="title-and-descriptions-bib"/>
+            <text macro="source-bib"/>
+          </group>
+        </else-if>
+        <else>
+          <text macro="title-and-descriptions-bib"/>
+          <text macro="source-bib"/>
+        </else>
+      </choose>
+      <group delimiter=", ">
+        <choose>
+          <!-- show event information here only if collapsed with `issued` (CMOS18 14.167) -->
+          <if match="any" variable="event-date original-date original-publisher original-publisher-place publisher status"/>
+          <!-- monographic usage only -->
+          <else-if match="any" type="article-journal article-magazine article-newspaper periodical post-weblog review review-book"/>
+          <else-if match="any" type="interview paper-conference">
+            <choose>
+              <if match="any" variable="collection-editor container-author editor editorial-director">
+                <!-- monographic usage -->
+                <text macro="source-event-bib"/>
+              </if>
+            </choose>
+          </else-if>
+          <else>
+            <text macro="source-event-bib"/>
+          </else>
+        </choose>
+        <text macro="source-monographic-publication-bib"/>
+      </group>
+      <text macro="source-medium-bib"/>
+      <text macro="source-archive-bib"/>
+      <text macro="source-date-accessed-DOI-URL-bib"/>
+    </group>
+  </macro>
+  <!-- 3.1. Title -->
+  <macro name="title-bib">
+    <choose>
+      <if match="any" type="post webpage">
+        <!-- Handle `container-title` on `post` or `webpage` in manner of `publisher` -->
+        <text macro="title-and-part-filter-review-bib"/>
+      </if>
+      <else-if match="any" type="article-journal article-magazine article-newspaper periodical post-weblog review review-book">
+        <text macro="title-and-part-filter-review-bib"/>
+      </else-if>
+      <else-if match="any" type="interview paper-conference">
+        <choose>
+          <if match="any" variable="collection-editor compiler editor editorial-director">
+            <!-- monographic usage -->
+            <text macro="title-monographic-bib"/>
+          </if>
+          <else>
+            <!-- serial usage -->
+            <text macro="title-and-part-filter-review-bib"/>
+          </else>
+        </choose>
+      </else-if>
+      <else>
+        <text macro="title-monographic-bib"/>
+      </else>
+    </choose>
+  </macro>
+  <macro name="title-short">
+    <choose>
+      <if match="any" type="review review-book" variable="reviewed-author reviewed-genre reviewed-title">
+        <!-- If a review has no `reviewed-title`, assume that `title` contains the title of the reviewed work; the description provides it. -->
+        <choose>
+          <if variable="reviewed-genre title">
+            <!-- Quotes, title case -->
+            <text form="short" quotes="true" text-case="title" variable="title"/>
+          </if>
+          <else-if variable="reviewed-genre reviewed-title title">
+            <!-- Quotes, title case -->
+            <text form="short" quotes="true" text-case="title" variable="title"/>
+          </else-if>
+          <else>
+            <text macro="description-short"/>
+          </else>
+        </choose>
+      </if>
+      <else>
+        <text macro="title-primary-short"/>
+      </else>
+    </choose>
+  </macro>
+  <!-- Title elements -->
+  <macro name="title-and-part-filter-review-bib">
+    <choose>
+      <if match="any" type="review review-book" variable="reviewed-author reviewed-genre reviewed-title">
+        <!-- `title` is only the review title if there is a separate `reviewed-genre` or `reviewed-title`; otherwise, it is the title of the reviewed work, printed in the description -->
+        <choose>
+          <if match="any" variable="reviewed-genre reviewed-title">
+            <text macro="title-and-part-title-bib"/>
+          </if>
+        </choose>
+      </if>
+      <else>
+        <text macro="title-and-part-title-bib"/>
+      </else>
+    </choose>
+  </macro>
+  <macro name="title-and-part-title-bib">
+    <group delimiter=". ">
+      <text macro="title-primary"/>
+      <group delimiter=", ">
+        <text macro="label-part-number-capitalized"/>
+        <text macro="title-part"/>
+      </group>
+    </group>
+  </macro>
+  <macro name="title-monographic-bib">
+    <!-- For monographic items, assume `part-number` and `part-title` refer to the book/volume. -->
+    <!-- There is no `title-monographic-note` as notes always open with the primary title. -->
+    <choose>
+      <if variable="container-title">
+        <text macro="title-primary"/>
+      </if>
+      <!-- For monographic items without `container-title`, bibliography entries list `part-title` or `volume-title` first if available -->
+      <else-if variable="part-title">
+        <text macro="title-part"/>
+      </else-if>
+      <else-if variable="volume-title">
+        <text font-style="italic" text-case="title" variable="volume-title"/>
+      </else-if>
+      <else>
+        <text macro="title-primary"/>
+      </else>
+    </choose>
+  </macro>
+  <macro name="title-part">
+    <choose>
+      <if type="patent">
+        <!-- No italics or quotes, sentence case -->
+        <text form="short" text-case="capitalize-first" variable="part-title"/>
+      </if>
+      <else-if match="any" type="bill collection legislation regulation treaty">
+        <!-- No italics or quotes, title case -->
+        <text text-case="title" variable="part-title"/>
+      </else-if>
+      <else-if type="legal_case">
+        <!-- Italicized, sentence case -->
+        <text font-style="italic" variable="part-title"/>
+      </else-if>
+      <else-if match="any" type="book classic graphic hearing map">
+        <!-- Italicized, title case (regardless of `container-title`) -->
+        <text font-style="italic" text-case="title" variable="part-title"/>
+      </else-if>
+      <else-if type="entry-encyclopedia" variable="author container-title">
+        <!-- Signed encyclopedia entry in quotes, title case (CMOS18 14.132) -->
+        <text quotes="true" text-case="title" variable="part-title"/>
+      </else-if>
+      <else-if type="entry-dictionary" variable="container-title">
+        <!-- Quotes, sentence case -->
+        <text quotes="true" variable="part-title"/>
+      </else-if>
+      <else-if type="entry-encyclopedia" variable="container-title">
+        <!-- Quotes, sentence case -->
+        <text quotes="true" variable="part-title"/>
+      </else-if>
+      <else-if type="post">
+        <!-- Quotes, sentence case -->
+        <text quotes="true" variable="part-title"/>
+      </else-if>
+      <!-- Other types are formatted based on presence of `container-title` -->
+      <else-if variable="container-title">
+        <!-- Quotes, title case -->
+        <text quotes="true" text-case="title" variable="part-title"/>
+      </else-if>
+      <else-if match="any" type="article dataset document interview manuscript paper-conference personal_communication speech thesis webpage">
+        <!-- Container-like but not necessarily with `container-title` -->
+        <!-- Quotes, title case -->
+        <text quotes="true" text-case="title" variable="part-title"/>
+      </else-if>
+      <else>
+        <!-- Italicized, title case (default) -->
+        <text font-style="italic" text-case="title" variable="part-title"/>
+      </else>
+    </choose>
+  </macro>
+  <macro name="title-primary">
+    <choose>
+      <if type="patent">
+        <!-- No italics or quotes, sentence case -->
+        <text form="short" text-case="capitalize-first" variable="title"/>
+      </if>
+      <else-if match="any" type="bill collection legislation regulation treaty">
+        <!-- No italics or quotes, title case -->
+        <text text-case="title" variable="title"/>
+      </else-if>
+      <else-if type="legal_case">
+        <!-- Italicized, sentence case -->
+        <text font-style="italic" variable="title"/>
+      </else-if>
+      <else-if match="any" type="book classic graphic hearing map">
+        <!-- Italicized, title case (regardless of `container-title`) -->
+        <text font-style="italic" text-case="title" variable="title"/>
+      </else-if>
+      <else-if type="entry-encyclopedia" variable="author container-title">
+        <!-- Signed encyclopedia entry in quotes, title case (CMOS18 14.132) -->
+        <text quotes="true" text-case="title" variable="title"/>
+      </else-if>
+      <else-if type="entry-dictionary" variable="container-title">
+        <!-- Quotes, sentence case -->
+        <text quotes="true" variable="title"/>
+      </else-if>
+      <else-if type="entry-encyclopedia" variable="container-title">
+        <!-- Quotes, sentence case -->
+        <text quotes="true" variable="title"/>
+      </else-if>
+      <else-if type="post">
+        <!-- Quotes, sentence case -->
+        <text quotes="true" variable="title"/>
+      </else-if>
+      <!-- Other types are formatted based on presence of `container-title` -->
+      <else-if variable="container-title">
+        <!-- Quotes, title case -->
+        <text quotes="true" text-case="title" variable="title"/>
+      </else-if>
+      <else-if match="any" type="article dataset document interview manuscript paper-conference personal_communication speech thesis webpage">
+        <!-- Container-like but not necessarily with `container-title` -->
+        <!-- Quotes, title case -->
+        <text quotes="true" text-case="title" variable="title"/>
+      </else-if>
+      <else>
+        <!-- Italicized, title case (default) -->
+        <text font-style="italic" text-case="title" variable="title"/>
+      </else>
+    </choose>
+  </macro>
+  <macro name="title-primary-short">
+    <choose>
+      <if type="patent">
+        <!-- No italics or quotes, sentence case -->
+        <text form="short" text-case="capitalize-first" variable="title"/>
+      </if>
+      <else-if match="any" type="bill collection legislation regulation treaty">
+        <!-- No italics or quotes, title case -->
+        <text form="short" text-case="title" variable="title"/>
+      </else-if>
+      <else-if type="legal_case">
+        <!-- Italicized, sentence case -->
+        <text font-style="italic" form="short" variable="title"/>
+      </else-if>
+      <else-if match="any" type="book classic graphic hearing map">
+        <!-- Italicized, title case (regardless of `container-title`) -->
+        <text font-style="italic" form="short" text-case="title" variable="title"/>
+      </else-if>
+      <else-if type="entry-encyclopedia" variable="author container-title">
+        <!-- Signed encyclopedia entry in quotes, title case (CMOS18 14.132) -->
+        <text form="short" quotes="true" text-case="title" variable="title"/>
+      </else-if>
+      <else-if type="entry-dictionary" variable="container-title">
+        <!-- Quotes, sentence case -->
+        <text form="short" quotes="true" variable="title"/>
+      </else-if>
+      <else-if type="entry-encyclopedia" variable="container-title">
+        <!-- Quotes, sentence case -->
+        <text form="short" quotes="true" variable="title"/>
+      </else-if>
+      <else-if type="post">
+        <!-- Quotes, sentence case -->
+        <text form="short" quotes="true" variable="title"/>
+      </else-if>
+      <!-- Other types are formatted based on presence of `container-title` -->
+      <else-if variable="container-title">
+        <!-- Quotes, title case -->
+        <text form="short" quotes="true" text-case="title" variable="title"/>
+      </else-if>
+      <else-if match="any" type="article dataset document interview manuscript paper-conference personal_communication speech thesis webpage">
+        <!-- Container-like but not necessarily with `container-title` -->
+        <!-- Quotes, title case -->
+        <text form="short" quotes="true" text-case="title" variable="title"/>
+      </else-if>
+      <else>
+        <!-- Italicized, title case (default) -->
+        <text font-style="italic" form="short" text-case="title" variable="title"/>
+      </else>
+    </choose>
+  </macro>
+  <!-- 3.2. Description -->
+  <macro name="description-bib">
+    <choose>
+      <if match="any" type="interview" variable="interviewer">
+        <text macro="description-interview-bib"/>
+      </if>
+      <else-if match="any" type="review review-book" variable="reviewed-author reviewed-genre reviewed-title">
+        <text macro="description-review-bib"/>
+      </else-if>
+      <else-if type="personal_communication">
+        <text macro="description-letter-bib"/>
+      </else-if>
+      <else-if match="any" type="article-journal article-magazine article-newspaper periodical post-weblog review review-book">
+        <text macro="description-serial-bib"/>
+      </else-if>
+      <else-if type="paper-conference">
+        <text macro="description-paper-conference-bib"/>
+      </else-if>
+      <else-if type="song" variable="composer">
+        <text macro="description-song-bib"/>
+      </else-if>
+      <!-- thesis type appears with university name (CMOS18 14.113) -->
+      <else-if type="thesis"/>
+      <else-if match="none" variable="container-title">
+        <!-- Other description -->
+        <text macro="description-format-bib"/>
+      </else-if>
+      <else>
+        <text macro="description-generic-bib"/>
+      </else>
+    </choose>
+  </macro>
+  <macro name="description-short">
+    <choose>
+      <if match="any" type="interview" variable="interviewer">
+        <text macro="description-interview-short"/>
+      </if>
+      <else-if match="any" type="review review-book" variable="reviewed-author reviewed-genre reviewed-title">
+        <text macro="description-review-short"/>
+      </else-if>
+      <else-if type="personal_communication">
+        <text macro="description-letter-short"/>
+      </else-if>
+      <else-if match="any" type="article-journal article-magazine article-newspaper periodical post-weblog review review-book">
+        <text macro="description-serial-short"/>
+      </else-if>
+      <else-if type="paper-conference">
+        <choose>
+          <if match="any" variable="collection-editor container-author editor editorial-director">
+            <!-- monographic usage -->
+            <text macro="description-format-short"/>
+          </if>
+          <else>
+            <!-- serial usage -->
+            <text macro="description-serial-short"/>
+          </else>
+        </choose>
+      </else-if>
+      <else>
+        <text macro="description-format-short"/>
+      </else>
+    </choose>
+  </macro>
+  <!-- Description elements -->
+  <macro name="description-format-bib">
+    <choose>
+      <if variable="genre number"/>
+      <else-if variable="genre">
+        <text text-case="capitalize-first" variable="genre"/>
+      </else-if>
+      <else-if type="manuscript">
+        <!-- 'unpublished manuscript' if no `genre` (CMOS18 14.114) -->
+        <choose>
+          <if match="none" variable="archive archive-place container-title DOI number publisher references URL">
+            <text term="manuscript" text-case="capitalize-first"/>
+          </if>
+        </choose>
+      </else-if>
+      <else-if type="personal_communication">
+        <!-- 'personal communication' if no `genre` (CMOS18 14.111) -->
+        <choose>
+          <if match="none" variable="archive archive-place container-title DOI number publisher references URL">
+            <text term="personal-communication" text-case="capitalize-first"/>
+          </if>
+        </choose>
+      </else-if>
+    </choose>
+  </macro>
+  <macro name="description-format-short">
+    <choose>
+      <if variable="genre">
+        <text variable="genre"/>
+      </if>
+      <else-if variable="medium">
+        <text variable="medium"/>
+      </else-if>
+      <else-if type="manuscript">
+        <!-- 'unpublished manuscript' if no `genre` (CMOS18 14.114) -->
+        <choose>
+          <if match="none" variable="archive archive-place container-title DOI number publisher references URL">
+            <text term="manuscript"/>
+          </if>
+        </choose>
+      </else-if>
+      <else-if type="personal_communication">
+        <!-- 'pers. comm.' if no `genre` (CMOS18 14.111) -->
+        <choose>
+          <if match="none" variable="archive archive-place container-title DOI number publisher references URL">
+            <text form="short" term="personal-communication"/>
+          </if>
+        </choose>
+      </else-if>
+      <else-if variable="chapter-number">
+        <text macro="label-chapter-number"/>
+      </else-if>
+    </choose>
+  </macro>
+  <macro name="description-generic-bib">
+    <!-- For conference presentations/performances/events, chapters in reports/standards/generic documents, software, place description within the source element -->
+    <choose>
+      <if match="any" type="event paper-conference performance speech">
+        <choose>
+          <if match="any" variable="collection-editor compiler editor editorial-director">
+            <!-- monographic usage -->
+            <text macro="description-format-bib"/>
+          </if>
+        </choose>
+      </if>
+      <else-if match="none" type="document report software standard">
+        <text macro="description-format-bib"/>
+      </else-if>
+    </choose>
+  </macro>
+  <macro name="description-interview-bib">
+    <group delimiter=", ">
+      <choose>
+        <if variable="genre number">
+          <!-- `genre` printed with `number` -->
+          <names variable="interviewer">
+            <label form="verb" suffix=" " text-case="capitalize-first"/>
+            <name and="text"/>
+          </names>
+        </if>
+        <else-if variable="genre">
+          <group delimiter=" ">
+            <text text-case="capitalize-first" variable="genre"/>
+            <group delimiter=" ">
+              <text form="verb" term="container-author"/>
+              <names variable="interviewer"/>
+            </group>
+          </group>
+        </else-if>
+        <else-if variable="interviewer">
+          <names variable="interviewer">
+            <label form="verb" suffix=" " text-case="capitalize-first"/>
+            <name and="text"/>
+          </names>
+        </else-if>
+        <else>
+          <text macro="description-format-bib"/>
+        </else>
+      </choose>
+      <text macro="source-event-place-first"/>
+    </group>
+  </macro>
+  <macro name="description-interview-short">
+    <choose>
+      <if disambiguate="true">
+        <names variable="interviewer">
+          <label form="verb" suffix=" "/>
+          <name and="text"/>
+          <substitute>
+            <text macro="description-format-short"/>
+          </substitute>
+        </names>
+      </if>
+      <else-if match="any" variable="genre medium">
+        <choose>
+          <if match="none" variable="author chair collection-editor compiler composer curator director editor editor-translator editorial-director executive-producer guest host illustrator organizer producer series-creator translator">
+            <!-- capitalize if no author or title -->
+            <text macro="description-format-bib"/>
+          </if>
+          <else>
+            <text macro="description-format-short"/>
+          </else>
+        </choose>
+      </else-if>
+      <else>
+        <!-- generic description for an unpublished interview (CMOS18 14.108) -->
+        <text term="interview"/>
+      </else>
+    </choose>
+  </macro>
+  <macro name="description-letter-bib">
+    <choose>
+      <if variable="recipient">
+        <group delimiter=", ">
+          <choose>
+            <if variable="genre number">
+              <!-- `genre` appears with `number` -->
+              <names variable="recipient">
+                <label form="verb" suffix=" " text-case="capitalize-first"/>
+                <name and="text"/>
+              </names>
+            </if>
+            <else-if variable="genre">
+              <group delimiter=" ">
+                <text macro="description-format-bib"/>
+                <names variable="recipient">
+                  <label form="verb" suffix=" "/>
+                  <name and="text"/>
+                </names>
+              </group>
+            </else-if>
+            <else>
+              <names variable="recipient">
+                <label form="verb" suffix=" " text-case="capitalize-first"/>
+                <name and="text"/>
+              </names>
+            </else>
+          </choose>
+          <text variable="event-place"/>
+          <text macro="date-event-full"/>
+        </group>
+      </if>
+      <else>
+        <text macro="description-format-bib"/>
+      </else>
+    </choose>
+  </macro>
+  <macro name="description-letter-short">
+    <!-- shortened notes ideally give author, recipient, place, and date (CMOS18 14.13) -->
+    <group delimiter=", ">
+      <choose>
+        <if variable="genre recipient">
+          <group delimiter=" ">
+            <text macro="description-format-short"/>
+            <names variable="recipient">
+              <label form="verb" suffix=" "/>
+              <name and="text"/>
+            </names>
+          </group>
+        </if>
+        <else>
+          <text macro="description-format-short"/>
+        </else>
+      </choose>
+      <text variable="event-place"/>
+      <text macro="date-event-full"/>
+    </group>
+  </macro>
+  <macro name="description-paper-conference-bib">
+    <choose>
+      <if match="any" variable="collection-editor container-author editor editorial-director">
+        <!-- monographic usage -->
+        <text macro="description-generic-bib"/>
+      </if>
+      <else>
+        <!-- serial usage -->
+        <group delimiter=". ">
+          <text macro="description-serial-bib"/>
+          <text macro="source-event-bib"/>
+        </group>
+      </else>
+    </choose>
+  </macro>
+  <macro name="description-review-bib">
+    <!-- Reviewed item -->
+    <group delimiter=". ">
+      <group delimiter=", ">
+        <group delimiter=" ">
+          <text macro="description-review-genre-bib"/>
+          <text macro="description-review-title"/>
+        </group>
+        <choose>
+          <if variable="reviewed-genre reviewed-title title">
+            <names variable="reviewed-author">
+              <label form="verb" suffix=" "/>
+              <name and="text"/>
+            </names>
+          </if>
+          <else-if variable="reviewed-genre"/>
+          <else>
+            <names variable="reviewed-author">
+              <label form="verb" suffix=" "/>
+              <name and="text"/>
+            </names>
+          </else>
+        </choose>
+        <text macro="source-event-place-first"/>
+      </group>
+      <text macro="label-section-capitalized"/>
+    </group>
+  </macro>
+  <macro name="description-review-genre-bib">
+    <choose>
+      <if variable="reviewed-genre">
+        <group delimiter=" ">
+          <text macro="description-review-term-unsigned-bib"/>
+          <text variable="reviewed-genre"/>
+          <choose>
+            <if match="none" variable="reviewed-title">
+              <names variable="reviewed-author">
+                <label form="verb" suffix=" "/>
+                <name and="text"/>
+              </names>
+            </if>
+          </choose>
+        </group>
+      </if>
+      <else-if variable="number">
+        <text macro="description-review-term-unsigned-bib"/>
+      </else-if>
+      <!-- If no `reviewed-genre`, assume that `genre` is entered as 'Review of the book' or similar -->
+      <else-if variable="genre">
+        <text text-case="capitalize-first" variable="genre"/>
+      </else-if>
+      <else>
+        <text macro="description-review-term-unsigned-bib"/>
+      </else>
+    </choose>
+  </macro>
+  <macro name="description-review-short">
+    <group delimiter=" ">
+      <text term="review-of"/>
+      <text macro="description-review-title-short"/>
+    </group>
+  </macro>
+  <macro name="description-review-term-unsigned-bib">
+    <!-- Anonymous reviews appear as 'unsigned' (CMOS18 14.102) -->
+    <choose>
+      <if match="any" variable="author chair collection-editor compiler composer curator director editor editor-translator editorial-director executive-producer guest host illustrator organizer producer series-creator translator">
+        <text term="review-of" text-case="capitalize-first"/>
+      </if>
+      <else>
+        <group delimiter=" ">
+          <text term="anonymous" text-case="capitalize-first"/>
+          <text term="review-of"/>
+        </group>
+      </else>
+    </choose>
+  </macro>
+  <macro name="description-review-title">
+    <choose>
+      <if match="any" variable="reviewed-genre reviewed-title">
+        <!-- Not possible to distinguish TV series episode from other reviewed works without a reviewed source title -->
+        <!-- Adapt for `reviewed-container-title` or similar if it becomes available -->
+        <text font-style="italic" text-case="title" variable="reviewed-title"/>
+      </if>
+      <else>
+        <!-- Assume title is title of reviewed work -->
+        <text font-style="italic" text-case="title" variable="title"/>
+      </else>
+    </choose>
+  </macro>
+  <macro name="description-review-title-short">
+    <choose>
+      <if match="any" variable="reviewed-genre reviewed-title">
+        <!-- Not possible to distinguish TV series episode from other reviewed works without a reviewed source title -->
+        <!-- Adapt for `reviewed-container-title` or similar if it becomes available -->
+        <text font-style="italic" form="short" text-case="title" variable="reviewed-title"/>
+      </if>
+      <else>
+        <!-- Assume title is title of reviewed work -->
+        <text font-style="italic" form="short" text-case="title" variable="title"/>
+      </else>
+    </choose>
+  </macro>
+  <macro name="description-serial-bib">
+    <group delimiter=". ">
+      <text macro="description-format-bib"/>
+      <!-- `section` provides magazine departments (CMOS18 14.88) and newspaper column names (CMOS18 14.93) -->
+      <text macro="label-section-capitalized"/>
+    </group>
+  </macro>
+  <macro name="description-serial-short">
+    <choose>
+      <if variable="title"/>
+      <else-if variable="genre">
+        <text macro="description-format-short"/>
+      </else-if>
+      <else>
+        <text variable="section"/>
+      </else>
+    </choose>
+  </macro>
+  <macro name="description-song-bib">
+    <!-- Performer of classical music works -->
+    <!-- TODO: remove when Zotero fixes mapping of performer to `author` -->
+    <group delimiter=" ">
+      <!-- Based on `description-format` macro -->
+      <choose>
+        <if variable="genre">
+          <text text-case="capitalize-first" variable="genre"/>
+          <text form="verb" term="performer"/>
+        </if>
+        <!-- providing 'performed by' label for recorded readings (CMOS18 14.164), but it should be omitted for classical music (CMOS18 14.163) -->
+        <else>
+          <text form="verb" term="performer" text-case="capitalize-first"/>
+        </else>
+      </choose>
+      <names variable="author">
+        <substitute>
+          <names variable="performer"/>
+        </substitute>
+      </names>
+    </group>
+  </macro>
+  <!-- 3.3. Identifier (edition, contributors, volume) -->
+  <macro name="identifier-bib">
+    <group delimiter=". ">
+      <choose>
+        <if type="patent">
+          <text macro="identifier-patent"/>
+        </if>
+        <else-if type="report">
+          <text macro="identifier-report-bib"/>
+        </else-if>
+        <else-if match="any" type="post webpage">
+          <!-- Handle `container-title` on `post` or `webpage` as `publisher` -->
+          <text macro="identifier-number-bib"/>
+          <text macro="label-version-capitalized"/>
+          <text macro="identifier-edition-bib"/>
+          <text macro="identifier-contributors-bib"/>
+          <text macro="identifier-volume-monographic-bib"/>
+        </else-if>
+        <else-if variable="container-title">
+          <choose>
+            <if match="any" type="broadcast graphic map motion_picture">
+              <!-- For audiovisual media, number information comes after `title`, not `container-title`; `song` places album catalogue `number` with `publisher` (CMOS18 14.163-164) -->
+              <text macro="identifier-number-bib"/>
+            </if>
+          </choose>
+          <text macro="identifier-contributors-bib"/>
+        </else-if>
+        <else>
+          <choose>
+            <if match="none" type="song">
+              <text macro="identifier-number-bib"/>
+            </if>
+          </choose>
+          <text macro="label-version-capitalized"/>
+          <text macro="identifier-edition-bib"/>
+          <choose>
+            <if match="any" variable="part-title volume-title">
+              <text macro="identifier-contributors-bib"/>
+            </if>
+            <else-if match="any" variable="number-of-volumes part-number volume">
+              <!-- `collection-editor` belongs with `collection-title` if item is not multivolume -->
+              <choose>
+                <if variable="collection-editor">
+                  <names variable="collection-editor">
+                    <label form="verb" suffix=" " text-case="capitalize-first"/>
+                    <name and="text"/>
+                  </names>
+                </if>
+                <else>
+                  <text macro="identifier-contributors-bib"/>
+                </else>
+              </choose>
+            </else-if>
+            <else>
+              <text macro="identifier-contributors-bib"/>
+            </else>
+          </choose>
+          <text macro="identifier-volume-monographic-bib"/>
+          <choose>
+            <!-- `collection-editor` supplied in `identifier-volume-monographic-bib` if there is a `part-title` or `volume-title` -->
+            <if match="any" variable="part-title volume-title"/>
+            <else-if match="any" variable="number-of-volumes part-number volume">
+              <choose>
+                <if variable="collection-editor">
+                  <text macro="identifier-contributors-bib"/>
+                </if>
+              </choose>
+            </else-if>
+          </choose>
+        </else>
+      </choose>
+    </group>
+  </macro>
+  <!-- Identifier elements -->
+  <macro name="identifier-contributors-bib">
+    <choose>
+      <if match="any" type="article-journal article-magazine article-newspaper periodical post-weblog review review-book">
+        <text macro="identifier-contributors-serial-bib"/>
+      </if>
+      <else-if match="any" type="interview paper-conference">
+        <choose>
+          <if match="any" variable="collection-editor compiler editor editorial-director">
+            <!-- monographic usage -->
+            <text macro="identifier-contributors-monographic-bib"/>
+          </if>
+          <else>
+            <!-- serial usage -->
+            <text macro="identifier-contributors-serial-bib"/>
+          </else>
+        </choose>
+      </else-if>
+      <else>
+        <text macro="identifier-contributors-monographic-bib"/>
+      </else>
+    </choose>
+  </macro>
+  <macro name="identifier-contributors-monographic-bib">
+    <group delimiter=". ">
+      <choose>
+        <if match="any" type="post webpage">
+          <group delimiter=". ">
+            <names variable="container-author">
+              <label form="verb" suffix=" " text-case="capitalize-first"/>
+              <name and="text"/>
+            </names>
+            <names variable="editor-translator">
+              <label form="verb" suffix=" " text-case="capitalize-first"/>
+              <name and="text"/>
+            </names>
+            <names delimiter=". " variable="editor translator">
+              <label form="verb" suffix=" " text-case="capitalize-first"/>
+              <name and="text"/>
+            </names>
+            <names variable="editorial-director">
+              <label form="verb" suffix=" " text-case="capitalize-first"/>
+              <name and="text"/>
+            </names>
+            <names variable="guest">
+              <label form="verb" suffix=" " text-case="capitalize-first"/>
+              <name and="text"/>
+            </names>
+            <names variable="host">
+              <label form="verb" suffix=" " text-case="capitalize-first"/>
+              <name and="text"/>
+            </names>
+            <names variable="illustrator">
+              <label form="verb" suffix=" " text-case="capitalize-first"/>
+              <name and="text"/>
+            </names>
+            <names variable="narrator">
+              <label form="verb" suffix=" " text-case="capitalize-first"/>
+              <name and="text"/>
+            </names>
+            <names delimiter=". " variable="compiler chair organizer curator">
+              <label form="verb" suffix=" " text-case="capitalize-first"/>
+              <name and="text"/>
+            </names>
+            <names delimiter=". " variable="series-creator executive-producer">
+              <label form="verb" suffix=" " text-case="capitalize-first"/>
+              <name and="text"/>
+            </names>
+            <names variable="producer">
+              <label form="verb" suffix=" " text-case="capitalize-first"/>
+              <name and="text"/>
+            </names>
+            <names variable="director">
+              <label form="verb" suffix=" " text-case="capitalize-first"/>
+              <name and="text"/>
+            </names>
+            <choose>
+              <if match="any" type="broadcast performance">
+                <names variable="script-writer">
+                  <label form="verb" suffix=" " text-case="capitalize-first"/>
+                  <name and="text"/>
+                </names>
+              </if>
+            </choose>
+            <names variable="performer">
+              <label form="verb" suffix=" " text-case="capitalize-first"/>
+              <name and="text"/>
+            </names>
+            <choose>
+              <if match="none" type="thesis">
+                <names variable="contributor">
+                  <label form="verb" suffix=" " text-case="capitalize-first"/>
+                  <name and="text"/>
+                </names>
+              </if>
+            </choose>
+          </group>
+        </if>
+        <else>
+          <!-- Handle `container-title` on `post` or `webpage` as `publisher` -->
+          <group delimiter=". ">
+            <choose>
+              <if match="none" variable="container-title">
+                <names variable="container-author">
+                  <label form="verb" suffix=" " text-case="capitalize-first"/>
+                  <name and="text"/>
+                </names>
+                <names variable="editor-translator">
+                  <label form="verb" suffix=" " text-case="capitalize-first"/>
+                  <name and="text"/>
+                </names>
+                <names delimiter=". " variable="editor translator">
+                  <label form="verb" suffix=" " text-case="capitalize-first"/>
+                  <name and="text"/>
+                </names>
+                <names variable="editorial-director">
+                  <label form="verb" suffix=" " text-case="capitalize-first"/>
+                  <name and="text"/>
+                </names>
+                <names variable="guest">
+                  <label form="verb" suffix=" " text-case="capitalize-first"/>
+                  <name and="text"/>
+                </names>
+                <names variable="host">
+                  <label form="verb" suffix=" " text-case="capitalize-first"/>
+                  <name and="text"/>
+                </names>
+              </if>
+            </choose>
+            <names variable="illustrator">
+              <label form="verb" suffix=" " text-case="capitalize-first"/>
+              <name and="text"/>
+            </names>
+            <names variable="narrator">
+              <label form="verb" suffix=" " text-case="capitalize-first"/>
+              <name and="text"/>
+            </names>
+            <choose>
+              <if match="none" variable="container-title">
+                <names delimiter=". " variable="compiler chair organizer curator">
+                  <label form="verb" suffix=" " text-case="capitalize-first"/>
+                  <name and="text"/>
+                </names>
+                <names delimiter=". " variable="series-creator executive-producer">
+                  <label form="verb" suffix=" " text-case="capitalize-first"/>
+                  <name and="text"/>
+                </names>
+                <names variable="producer">
+                  <label form="verb" suffix=" " text-case="capitalize-first"/>
+                  <name and="text"/>
+                </names>
+                <names variable="director">
+                  <label form="verb" suffix=" " text-case="capitalize-first"/>
+                  <name and="text"/>
+                </names>
+                <choose>
+                  <if match="any" type="broadcast performance">
+                    <names variable="script-writer">
+                      <label form="verb" suffix=" " text-case="capitalize-first"/>
+                      <name and="text"/>
+                    </names>
+                  </if>
+                </choose>
+                <names variable="performer">
+                  <label form="verb" suffix=" " text-case="capitalize-first"/>
+                  <name and="text"/>
+                </names>
+                <choose>
+                  <if match="none" type="song thesis">
+                    <names variable="contributor">
+                      <label form="verb" suffix=" " text-case="capitalize-first"/>
+                      <name and="text"/>
+                    </names>
+                  </if>
+                </choose>
+              </if>
+            </choose>
+            <choose>
+              <if type="song">
+                <!-- Song contributors attached to album (CMOS18 14.163) -->
+                <names variable="contributor">
+                  <label form="verb" suffix=" " text-case="capitalize-first"/>
+                  <name and="text"/>
+                </names>
+              </if>
+            </choose>
+          </group>
+        </else>
+      </choose>
+    </group>
+  </macro>
+  <macro name="identifier-contributors-serial-bib">
+    <group delimiter=". ">
+      <names delimiter=". " variable="translator narrator">
+        <label form="verb" suffix=" " text-case="capitalize-first"/>
+        <name and="text"/>
+      </names>
+      <names delimiter=", " variable="compiler chair organizer curator">
+        <label form="verb" suffix=" " text-case="capitalize-first"/>
+        <name and="text"/>
+      </names>
+      <names delimiter=", " variable="series-creator executive-producer">
+        <label form="verb" suffix=" " text-case="capitalize-first"/>
+        <name and="text"/>
+      </names>
+      <names variable="producer">
+        <label form="verb" suffix=" " text-case="capitalize-first"/>
+        <name and="text"/>
+      </names>
+      <names variable="director">
+        <label form="verb" suffix=" " text-case="capitalize-first"/>
+        <name and="text"/>
+      </names>
+      <names variable="script-writer">
+        <label form="verb" suffix=" " text-case="capitalize-first"/>
+        <name and="text"/>
+      </names>
+      <names variable="performer">
+        <label form="verb" suffix=" " text-case="capitalize-first"/>
+        <name and="text"/>
+      </names>
+    </group>
+  </macro>
+  <macro name="identifier-edition-bib">
+    <choose>
+      <if match="none" variable="original-date">
+        <text macro="label-edition-capitalized"/>
+      </if>
+      <else-if variable="original-title">
+        <text macro="label-edition-capitalized"/>
+      </else-if>
+    </choose>
+  </macro>
+  <macro name="identifier-number-bib">
+    <group delimiter=" ">
+      <choose>
+        <if is-numeric="number" type="broadcast" variable="genre">
+          <text text-case="capitalize-first" variable="genre"/>
+          <text variable="number"/>
+        </if>
+        <else-if is-numeric="number" type="broadcast">
+          <text text-case="capitalize-first" value="episode"/>
+          <text variable="number"/>
+        </else-if>
+        <else-if variable="number">
+          <text text-case="title" variable="genre"/>
+          <text macro="label-number-capitalized"/>
+        </else-if>
+      </choose>
+    </group>
+  </macro>
+  <macro name="identifier-patent">
+    <group delimiter=", ">
+      <group delimiter=" ">
+        <!-- `authority`: US ; `genre`: patent ; `number`: 123,445 -->
+        <text form="short" variable="authority"/>
+        <!-- 'US Patent' capitalized in both bibliography and note forms -->
+        <choose>
+          <if variable="genre">
+            <text text-case="capitalize-first" variable="genre"/>
+          </if>
+          <else>
+            <text term="patent" text-case="capitalize-first"/>
+          </else>
+        </choose>
+        <text variable="number"/>
+      </group>
+      <group delimiter=" ">
+        <text value="filed"/>
+        <date form="text" variable="submitted"/>
+      </group>
+      <group delimiter=" ">
+        <choose>
+          <if variable="issued submitted">
+            <text term="and"/>
+          </if>
+        </choose>
+        <text value="issued"/>
+        <!-- Always give full issue date, even in author-date (CMOS18 14.158) -->
+        <text macro="date-issued-full"/>
+      </group>
+    </group>
+  </macro>
+  <macro name="identifier-report-bib">
+    <group delimiter=". ">
+      <choose>
+        <if variable="container-title">
+          <!-- If the report is a chapter in a larger report, then most identifying information is printed in the source. -->
+          <text macro="identifier-contributors-bib"/>
+        </if>
+        <else-if variable="title">
+          <text macro="identifier-number-bib"/>
+          <text macro="label-version-capitalized"/>
+          <text macro="identifier-edition-bib"/>
+          <text macro="identifier-contributors-bib"/>
+          <text macro="identifier-volume-monographic-bib"/>
+        </else-if>
+        <else>
+          <!-- If there is no `title`, then `genre` and `number` are already printed as the title. -->
+          <text macro="label-version-capitalized"/>
+          <text macro="identifier-edition-bib"/>
+          <text macro="identifier-contributors-bib"/>
+          <text macro="identifier-volume-monographic-bib"/>
+        </else>
+      </choose>
+    </group>
+  </macro>
+  <macro name="identifier-volume-bib">
+    <!-- In notes styles, bibliography entries may be listed either under an individual volume title or its series, but the former approach is required for author-date, which is the form that this macro implements (CMOS18 14.21) -->
+    <group delimiter=", ">
+      <choose>
+        <if variable="part-number part-title volume volume-title">
+          <!-- part and title with individual titles -->
+          <group delimiter=" ">
+            <text macro="label-part-number-capitalized"/>
+            <text value="of"/>
+            <text font-style="italic" text-case="title" variable="volume-title"/>
+          </group>
+          <group delimiter=" ">
+            <text macro="label-volume"/>
+            <text value="of"/>
+            <group delimiter=", ">
+              <text macro="title-primary"/>
+              <names variable="collection-editor">
+                <label form="verb" suffix=" "/>
+                <name and="text"/>
+              </names>
+            </group>
+          </group>
+        </if>
+        <else-if match="any" variable="part-title volume-title">
+          <group delimiter=" ">
+            <choose>
+              <if variable="part-number volume">
+                <group delimiter=", ">
+                  <text macro="label-volume-capitalized"/>
+                  <text macro="label-part-number"/>
+                  <text value="of"/>
+                </group>
+              </if>
+              <else-if variable="part-number">
+                <text macro="label-part-number-capitalized"/>
+                <text value="of"/>
+              </else-if>
+              <else-if variable="volume">
+                <text macro="label-volume-capitalized"/>
+                <text value="of"/>
+              </else-if>
+            </choose>
+            <group delimiter=", ">
+              <text macro="title-primary"/>
+              <names variable="collection-editor">
+                <label form="verb" suffix=" "/>
+                <name and="text"/>
+              </names>
+            </group>
+          </group>
+        </else-if>
+        <else-if variable="part-number volume">
+          <text macro="label-volume-capitalized"/>
+          <text macro="label-part-number"/>
+        </else-if>
+        <else-if variable="part-number">
+          <text macro="label-part-number-capitalized"/>
+        </else-if>
+        <else-if variable="volume">
+          <text macro="label-volume-capitalized"/>
+        </else-if>
+        <else>
+          <text macro="label-number-of-volumes"/>
+        </else>
+      </choose>
+    </group>
+  </macro>
+  <macro name="identifier-volume-monographic-bib">
+    <choose>
+      <if match="any" type="article-journal article-magazine article-newspaper periodical post-weblog review review-book"/>
+      <else-if match="any" type="interview paper-conference">
+        <choose>
+          <if match="any" variable="collection-editor compiler editor editorial-director">
+            <!-- monographic usage -->
+            <text macro="identifier-volume-bib"/>
+          </if>
+        </choose>
+      </else-if>
+      <else>
+        <text macro="identifier-volume-bib"/>
+      </else>
+    </choose>
+  </macro>
+  <!-- 4. Source -->
+  <macro name="source-bib">
+    <choose>
+      <if match="any" type="article-journal article-magazine article-newspaper periodical post-weblog review review-book">
+        <!-- serial usage -->
+        <text macro="source-serial-bib"/>
+      </if>
+      <else-if match="any" type="interview paper-conference">
+        <choose>
+          <if match="any" variable="collection-editor container-author editor editorial-director">
+            <!-- monographic usage -->
+            <text macro="source-monographic-bib"/>
+          </if>
+          <else>
+            <!-- serial usage -->
+            <text macro="source-serial-bib"/>
+          </else>
+        </choose>
+      </else-if>
+      <else-if match="any" type="patent post webpage"/>
+      <else>
+        <text macro="source-monographic-bib"/>
+      </else>
+    </choose>
+  </macro>
+  <!-- 4.1. Serial sources -->
+  <macro name="source-serial-bib">
+    <group delimiter=". ">
+      <text macro="source-serial-title-volume-bib"/>
+      <choose>
+        <if type="article-newspaper">
+          <group delimiter=", ">
+            <text macro="source-serial-title-bib"/>
+            <text macro="source-serial-identifier-bib"/>
+          </group>
+        </if>
+        <else-if variable="collection-title volume">
+          <group delimiter=", ">
+            <text macro="source-serial-title-bib"/>
+            <text macro="source-serial-identifier-bib"/>
+          </group>
+        </else-if>
+        <else-if variable="volume">
+          <group delimiter=" ">
+            <text macro="source-serial-title-bib"/>
+            <text macro="source-serial-identifier-bib"/>
+          </group>
+        </else-if>
+        <else>
+          <group delimiter=", ">
+            <text macro="source-serial-title-bib"/>
+            <text macro="source-serial-identifier-bib"/>
+          </group>
+        </else>
+      </choose>
+    </group>
+  </macro>
+  <!-- Serial source title -->
+  <macro name="source-serial-name">
+    <group delimiter=" ">
+      <text font-style="italic" text-case="title" variable="container-title"/>
+      <choose>
+        <!-- TODO: remove conditional when Zotero stops double-mapping `event-place` and `publisher-place` -->
+        <if match="none" variable="event-date event-title">
+          <text prefix="(" suffix=")" variable="publisher-place"/>
+        </if>
+      </choose>
+    </group>
+  </macro>
+  <macro name="source-serial-title-bib">
+    <group delimiter=", ">
+      <choose>
+        <!-- Journal special issues (CMOS18 14.77) and supplements (CMOS18 14.78) -->
+        <if match="none" variable="container-title"/>
+        <else-if match="none" type="periodical" variable="supplement-number volume-title"/>
+        <!-- TODO: use `container-genre` here once available to allow a custom description of the journal volume -->
+        <else-if variable="supplement-number volume-title">
+          <text term="supplement" text-case="capitalize-first"/>
+        </else-if>
+        <else-if type="periodical" variable="supplement-number title">
+          <text term="supplement" text-case="capitalize-first"/>
+        </else-if>
+        <else-if variable="volume-title">
+          <text term="special-issue" text-case="capitalize-first"/>
+        </else-if>
+        <else-if type="periodical" variable="title">
+          <text term="special-issue" text-case="capitalize-first"/>
+        </else-if>
+      </choose>
+      <text macro="source-serial-name"/>
+      <choose>
+        <!-- 'ahead of print' is placed akin to a series (CMOS18 14.75) -->
+        <if match="any" variable="available-date collection-title issue number page status supplement-number volume"/>
+        <else-if type="article-journal" variable="DOI issued">
+          <text term="advance-online-publication"/>
+        </else-if>
+      </choose>
+    </group>
+  </macro>
+  <macro name="source-serial-title-volume-bib">
+    <choose>
+      <if variable="volume-title">
+        <!-- Journal special issues (CMOS18 14.77) and supplements (CMOS18 14.78) -->
+        <group delimiter=", ">
+          <group delimiter=" ">
+            <text macro="source-monographic-preposition-bib"/>
+            <text quotes="true" text-case="title" variable="volume-title"/>
+          </group>
+          <text macro="source-monographic-identifier-contributors-bib"/>
+        </group>
+      </if>
+    </choose>
+  </macro>
+  <!-- Serial source identifier -->
+  <macro name="source-serial-identifier-bib">
+    <choose>
+      <if match="any" variable="issue supplement-number volume">
+        <group delimiter=": ">
+          <text macro="source-serial-identifier-volume-author-date"/>
+          <text macro="source-serial-locator"/>
+        </group>
+      </if>
+      <else>
+        <group delimiter=", ">
+          <group delimiter=". ">
+            <text macro="source-serial-identifier-volume-author-date"/>
+            <!-- periodical edition always capitalized (CMOS18 14.89) -->
+            <text macro="label-edition-capitalized"/>
+          </group>
+          <text macro="source-serial-locator"/>
+        </group>
+      </else>
+      <!-- TODO: If CSL adds `date-part` detection, add two further conditions to address CMOS18 14.74: delimiting with ":" if there is a `volume` and no month or `issue` or `supplement number`; delimiting with ", " or there is an `issue` or `supplement number` and no month -->
+    </choose>
+  </macro>
+  <macro name="source-serial-identifier-volume-author-date">
+    <group delimiter=", ">
+      <choose>
+        <if type="article-newspaper">
+          <!-- newspapers provide the full date in place of volume/issue numbers (CMOS18 14.89) -->
+          <text variable="collection-title"/>
+          <text macro="source-serial-volume-status-bib"/>
+        </if>
+        <else-if match="any" variable="issue supplement-number volume">
+          <choose>
+            <if match="any" type="article-magazine review review-book" variable="reviewed-author reviewed-genre reviewed-title">
+              <!-- date appears first if the magazine or review `container-title` has been substituted for a missing author (CMOS18 14.87, 14.102) -->
+              <choose>
+                <if match="none" variable="author chair collection-editor compiler composer curator director editor editor-translator editorial-director executive-producer guest host illustrator organizer producer series-creator translator">
+                  <choose>
+                    <!-- no extra date details with a volume plus issue/supplement -->
+                    <if variable="issue volume"/>
+                    <else-if variable="supplement-number"/>
+                    <!-- nothing to substitute if there is no issue/supplement/volume -->
+                    <else-if match="none" variable="issue volume"/>
+                    <else>
+                      <text macro="source-date-bib"/>
+                      <!-- for CMOS17 author-date: -->
+                      <!-- <text macro="source-date-issued-month-day"/> -->
+                    </else>
+                  </choose>
+                </if>
+              </choose>
+            </if>
+          </choose>
+          <!-- `collection-title` is for any serial with multiple series (e.g. '4th ser.') -->
+          <text variable="collection-title"/>
+          <group delimiter=" ">
+            <choose>
+              <if variable="volume">
+                <choose>
+                  <if variable="collection-title">
+                    <text macro="label-volume"/>
+                  </if>
+                  <else-if match="any" type="article-magazine review review-book" variable="reviewed-author reviewed-genre reviewed-title">
+                    <!-- provide label if a magazine or review `container-title` has been substituted for a missing author (CMOS18 14.87, 14.102) -->
+                    <choose>
+                      <if match="any" variable="author chair collection-editor compiler composer curator director editor editor-translator editorial-director executive-producer guest host illustrator organizer producer series-creator translator">
+                        <text variable="volume"/>
+                      </if>
+                      <!-- TODO: when CSL provides date part detection, volume should be lowercase if there is a month, but otherwise capitalized -->
+                      <else>
+                        <text macro="label-volume-capitalized"/>
+                      </else>
+                    </choose>
+                  </else-if>
+                  <else>
+                    <text variable="volume"/>
+                  </else>
+                </choose>
+                <group delimiter=", " prefix="(" suffix=")">
+                  <choose>
+                    <if match="any" variable="issue supplement-number">
+                      <text variable="issue"/>
+                      <text macro="label-supplement-number"/>
+                    </if>
+                    <else-if match="any" type="article-magazine review review-book" variable="reviewed-author reviewed-genre reviewed-title">
+                      <!-- date for anonymous magazine and review articles only appears here if it did not earlier (CMOS18 14.87, 14.102) -->
+                      <choose>
+                        <if match="any" variable="author chair collection-editor compiler composer curator director editor editor-translator editorial-director executive-producer guest host illustrator organizer producer series-creator translator">
+                          <text macro="source-date-bib"/>
+                          <!-- for CMOS17 author-date: -->
+                          <!-- <text macro="source-date-issued-month-day"/> -->
+                        </if>
+                      </choose>
+                    </else-if>
+                    <else>
+                      <text macro="source-date-bib"/>
+                      <!-- for CMOS17 author-date: -->
+                      <!-- <text macro="source-date-issued-month-day"/> -->
+                    </else>
+                  </choose>
+                </group>
+              </if>
+              <else-if match="any" variable="issue supplement-number">
+                <group delimiter=" ">
+                  <group delimiter=", ">
+                    <text macro="label-issue"/>
+                    <text macro="label-supplement-number"/>
+                  </group>
+                  <choose>
+                    <if match="any" variable="author chair collection-editor compiler composer curator director editor editor-translator editorial-director executive-producer guest host illustrator organizer producer series-creator translator">
+                      <text macro="source-date-bib" prefix="(" suffix=")"/>
+                      <!-- for CMOS17 author-date: -->
+                      <!-- <text macro="source-date-issued-month-day" prefix="(" suffix=")"/> -->
+                    </if>
+                  </choose>
+                </group>
+              </else-if>
+            </choose>
+          </group>
+        </else-if>
+        <else>
+          <text variable="collection-title"/>
+          <choose>
+            <if match="any" type="interview" variable="interviewer">
+              <!-- publisher possible with `interview` (cf. CMOS18 14.110) -->
+              <text variable="publisher"/>
+            </if>
+          </choose>
+          <text macro="source-serial-volume-status-bib"/>
+        </else>
+      </choose>
+    </group>
+  </macro>
+  <macro name="source-serial-volume-status-bib">
+    <group delimiter=", ">
+      <choose>
+        <if match="none" variable="collection-title issue number page supplement-number volume">
+          <group delimiter=" ">
+            <!-- article accepted for publication and available on publisher website (CMOS18 14.75) -->
+            <!-- TODO: use CSL term for `available-date` when available -->
+            <text value="accepted"/>
+            <date form="text" variable="available-date"/>
+          </group>
+        </if>
+      </choose>
+      <group delimiter=" ">
+        <text macro="source-date-status-bib"/>
+        <text macro="source-date-bib"/>
+        <!-- for CMOS17 author-date: -->
+        <!-- <text macro="source-date-issued-full-serial"/> -->
+      </group>
+    </group>
+  </macro>
+  <!-- Serial source locator -->
+  <macro name="source-serial-locator">
+    <choose>
+      <if match="any" variable="locator number">
+        <group delimiter=", ">
+          <text macro="label-locator"/>
+          <!-- an article ID appears alongside locators in notes (CMOS18 14.71) -->
+          <text variable="number"/>
+        </group>
+      </if>
+      <!-- do not give pages for newspapers (CMOS18 14.89) -->
+      <else-if type="article-newspaper"/>
+      <else>
+        <text variable="page"/>
+      </else>
+    </choose>
+  </macro>
+  <!-- 4.2. Monographic sources -->
+  <macro name="source-monographic-bib">
+    <group delimiter=". ">
+      <!-- Monographic sources repeat main reference elements -->
+      <choose>
+        <if variable="container-title">
+          <group delimiter=", ">
+            <group delimiter=" ">
+              <choose>
+                <if match="none" type="broadcast motion_picture">
+                  <text macro="source-monographic-preposition-bib"/>
+                </if>
+              </choose>
+              <text macro="source-monographic-title-bib"/>
+            </group>
+            <text macro="source-monographic-description-bib"/>
+            <text macro="source-monographic-identifier-bib"/>
+            <text macro="source-monographic-locator"/>
+          </group>
+        </if>
+      </choose>
+      <text macro="source-series-bib"/>
+      <choose>
+        <!-- show event information here only if not collapsed with `issued` (CMOS18 14.167) -->
+        <if match="any" variable="event-date original-date original-publisher original-publisher-place publisher status">
+          <text macro="source-event-bib"/>
+        </if>
+      </choose>
+    </group>
+  </macro>
+  <!-- Monographic source title -->
+  <macro name="source-monographic-preposition-bib">
+    <choose>
+      <if type="chapter" variable="container-title genre">
+        <text value="to"/>
+      </if>
+      <else-if match="any" type="entry entry-dictionary entry-encyclopedia">
+        <choose>
+          <if match="any" variable="author composer">
+            <!-- Give preposition only for signed entries; otherwise, title is substituted -->
+            <text term="in" text-case="capitalize-first"/>
+          </if>
+        </choose>
+      </else-if>
+      <!-- if printing chapter page numbers (CMOS17/classic):
+      <else-if variable="chapter-number page title"><text term="in" text-case="capitalize-first"/></else-if>
+      -->
+      <else-if variable="chapter-number">
+        <group delimiter=" ">
+          <text macro="label-chapter-number-capitalized"/>
+          <choose>
+            <if type="song">
+              <text term="on"/>
+            </if>
+            <else>
+              <text term="in"/>
+            </else>
+          </choose>
+        </group>
+      </else-if>
+      <else>
+        <text term="in" text-case="capitalize-first"/>
+      </else>
+    </choose>
+  </macro>
+  <macro name="source-monographic-title-bib">
+    <choose>
+      <if variable="part-title">
+        <text macro="title-part"/>
+      </if>
+      <else-if variable="volume-title">
+        <text font-style="italic" text-case="title" variable="volume-title"/>
+      </else-if>
+      <else>
+        <text font-style="italic" text-case="title" variable="container-title"/>
+      </else>
+    </choose>
+  </macro>
+  <!-- Monographic source description -->
+  <macro name="source-monographic-description-bib">
+    <choose>
+      <if match="any" type="event paper-conference performance speech">
+        <!-- Conference presentations should describe the session unless published in a proceedings -->
+        <choose>
+          <if match="none" variable="collection-editor compiler editor editorial-director">
+            <!-- serial usage -->
+            <text macro="description-format-bib"/>
+          </if>
+        </choose>
+      </if>
+      <else-if type="software">
+        <!-- For entries in mobile app reference works, place description after `container-title` -->
+        <text macro="description-format-bib"/>
+      </else-if>
+      <else-if match="any" type="document report standard">
+        <!-- For chapters in report, standards, and generic documents, place description after `container-title` -->
+        <text macro="description-format-bib"/>
+      </else-if>
+    </choose>
+  </macro>
+  <!-- Monographic source identifier -->
+  <macro name="source-monographic-identifier-bib">
+    <!-- Based on `identifier-bib` -->
+    <choose>
+      <if variable="container-title">
+        <group delimiter=", ">
+          <choose>
+            <if match="none" type="broadcast graphic map motion_picture song">
+              <!-- For audiovisual media, number information comes after `title`, not `container-title`; `song` places album catalogue `number` with `publisher` (CMOS18 14.163-164) -->
+              <text macro="identifier-number-bib"/>
+            </if>
+          </choose>
+          <text macro="label-version"/>
+          <text macro="label-edition"/>
+          <choose>
+            <if match="any" variable="part-title volume-title">
+              <text macro="source-monographic-identifier-contributors-bib"/>
+            </if>
+            <else-if match="any" variable="number-of-volumes part-number volume">
+              <!-- `collection-editor` belongs with `collection-title` if item is not multivolume -->
+              <choose>
+                <if variable="collection-editor">
+                  <names variable="collection-editor">
+                    <label form="verb" suffix=" "/>
+                    <name and="text"/>
+                  </names>
+                </if>
+                <else>
+                  <text macro="source-monographic-identifier-contributors-bib"/>
+                </else>
+              </choose>
+            </else-if>
+            <else>
+              <text macro="source-monographic-identifier-contributors-bib"/>
+            </else>
+          </choose>
+          <text macro="source-monographic-identifier-volume-bib"/>
+          <choose>
+            <!-- `collection-editor` supplied in `source-monographic-identifier-volume-bib` if there is a `part-title` or `volume-title` -->
+            <if match="any" variable="part-title volume-title"/>
+            <else-if match="any" variable="number-of-volumes part-number volume">
+              <choose>
+                <if variable="collection-editor">
+                  <text macro="source-monographic-identifier-contributors-bib"/>
+                </if>
+              </choose>
+            </else-if>
+          </choose>
+        </group>
+      </if>
+    </choose>
+  </macro>
+  <macro name="source-monographic-identifier-contributors-bib">
+    <group delimiter=", ">
+      <names variable="container-author">
+        <label form="verb" suffix=" "/>
+        <name and="text"/>
+      </names>
+      <names variable="editor-translator">
+        <label form="verb" suffix=" "/>
+        <name and="text"/>
+      </names>
+      <names delimiter=", " variable="editor translator">
+        <label form="verb" suffix=" "/>
+        <name and="text"/>
+      </names>
+      <names variable="guest">
+        <label form="verb" suffix=" "/>
+        <name and="text"/>
+      </names>
+      <names variable="host">
+        <label form="verb" suffix=" "/>
+        <name and="text"/>
+      </names>
+      <names delimiter=", " variable="chair organizer">
+        <label form="verb" suffix=" "/>
+        <name and="text"/>
+      </names>
+      <names delimiter=", " variable="illustrator narrator compiler curator">
+        <label form="verb" suffix=" "/>
+        <name and="text"/>
+      </names>
+      <names delimiter=", " variable="series-creator executive-producer">
+        <label form="verb" suffix=" "/>
+        <name and="text"/>
+      </names>
+      <names variable="producer">
+        <label form="verb" suffix=" "/>
+        <name and="text"/>
+      </names>
+      <names variable="editorial-director">
+        <label form="verb" suffix=" "/>
+        <name and="text"/>
+      </names>
+      <choose>
+        <if match="any" type="broadcast performance">
+          <names variable="script-writer">
+            <label form="verb" suffix=" "/>
+            <name and="text"/>
+          </names>
+        </if>
+      </choose>
+      <names variable="director">
+        <label form="verb" suffix=" "/>
+        <name and="text"/>
+      </names>
+      <names variable="performer">
+        <label form="verb" suffix=" "/>
+        <name and="text"/>
+      </names>
+      <choose>
+        <if match="none" type="song thesis">
+          <!-- Song contributors attached to album (CMOS18 14.163) -->
+          <names variable="contributor">
+            <label form="verb" suffix=" "/>
+            <name and="text"/>
+          </names>
+        </if>
+      </choose>
+    </group>
+  </macro>
+  <macro name="source-monographic-identifier-volume-bib">
+    <!-- Mostly identical to `identifier-volume-bib` but without capitalization; giving `container-title` rather than `title-primary`; and ensuring volume number -->
+    <group delimiter=", ">
+      <choose>
+        <if variable="part-number part-title volume volume-title">
+          <!-- part and title with individual titles -->
+          <group delimiter=" ">
+            <text macro="label-part-number"/>
+            <text value="of"/>
+            <text font-style="italic" text-case="title" variable="volume-title"/>
+          </group>
+          <group delimiter=" ">
+            <text macro="label-volume"/>
+            <text value="of"/>
+            <group delimiter=", ">
+              <text font-style="italic" text-case="title" variable="container-title"/>
+              <names variable="collection-editor">
+                <label form="verb" suffix=" "/>
+                <name and="text"/>
+              </names>
+            </group>
+          </group>
+        </if>
+        <else-if match="any" variable="part-title volume-title">
+          <group delimiter=" ">
+            <choose>
+              <if variable="part-number volume">
+                <group delimiter=", ">
+                  <text macro="label-volume"/>
+                  <text macro="label-part-number"/>
+                  <text value="of"/>
+                </group>
+              </if>
+              <else-if variable="part-number">
+                <text macro="label-part-number"/>
+                <text value="of"/>
+              </else-if>
+              <else-if variable="volume">
+                <text macro="label-volume"/>
+                <text value="of"/>
+              </else-if>
+            </choose>
+            <group delimiter=", ">
+              <text font-style="italic" text-case="title" variable="container-title"/>
+              <names variable="collection-editor">
+                <label form="verb" suffix=" "/>
+                <name and="text"/>
+              </names>
+            </group>
+          </group>
+        </else-if>
+        <else-if match="any" variable="part-number volume">
+          <choose>
+            <if is-numeric="volume" match="none">
+              <text macro="label-volume"/>
+            </if>
+            <else-if variable="container-title">
+              <!-- remove condition in styles that print chapter page numbers (CMOS17/classic) -->
+              <text macro="label-volume"/>
+            </else-if>
+            <else-if is-numeric="volume" variable="page">
+              <choose>
+                <!-- check for variables that might come between the volume and page number -->
+                <if match="any" variable="collection-editor part-number part-title volume-title">
+                  <text macro="label-volume"/>
+                </if>
+              </choose>
+            </else-if>
+            <else>
+              <text macro="label-volume"/>
+            </else>
+          </choose>
+          <text macro="label-part-number"/>
+        </else-if>
+        <else>
+          <text macro="label-number-of-volumes"/>
+        </else>
+      </choose>
+    </group>
+  </macro>
+  <!-- Monographic source locator -->
+  <macro name="source-monographic-locator">
+    <choose>
+      <if is-numeric="volume" locator="page">
+        <group delimiter=":">
+          <choose>
+            <if match="none" variable="collection-editor part-number part-title volume-title">
+              <text variable="volume"/>
+            </if>
+          </choose>
+          <text variable="locator"/>
+        </group>
+      </if>
+      <else-if variable="locator">
+        <text macro="label-locator"/>
+      </else-if>
+      <!-- remove `container-title` condition in styles that print chapter page numbers (CMOS17/classic) -->
+      <else-if variable="container-title"/>
+      <else-if is-numeric="volume" variable="page">
+        <!-- collapse the volume and page number if adjacent -->
+        <group delimiter=":">
+          <choose>
+            <!-- check for variables that might come between the volume and page number -->
+            <if match="none" variable="collection-editor part-number part-title volume-title">
+              <text variable="volume"/>
+            </if>
+          </choose>
+          <text variable="page"/>
+        </group>
+      </else-if>
+      <else>
+        <text variable="page"/>
+      </else>
+    </choose>
+  </macro>
+  <!-- 4.3. Series -->
+  <macro name="source-series-bib">
+    <group delimiter=", ">
+      <choose>
+        <if variable="collection-editor collection-title">
+          <choose>
+            <if match="any" variable="number-of-volumes part-number part-title volume volume-title">
+              <text macro="source-series-title"/>
+            </if>
+            <else>
+              <text text-case="title" variable="collection-title"/>
+              <names variable="collection-editor">
+                <label form="verb" suffix=" "/>
+                <name and="text"/>
+              </names>
+              <text macro="label-collection-number"/>
+              <text macro="label-issue"/>
+            </else>
+          </choose>
+        </if>
+        <else>
+          <text macro="source-series-title"/>
+        </else>
+      </choose>
+    </group>
+  </macro>
+  <macro name="source-series-title">
+    <group delimiter=", ">
+      <choose>
+        <if variable="issue">
+          <text text-case="title" variable="collection-title"/>
+          <text macro="label-collection-number"/>
+          <text macro="label-issue"/>
+        </if>
+        <else-if is-numeric="collection-number" variable="collection-title">
+          <group delimiter=" ">
+            <text text-case="title" variable="collection-title"/>
+            <text variable="collection-number"/>
+          </group>
+        </else-if>
+        <else-if variable="collection-title">
+          <text text-case="title" variable="collection-title"/>
+          <text variable="collection-number"/>
+        </else-if>
+      </choose>
+    </group>
+  </macro>
+  <!-- 4.4. Event -->
+  <macro name="source-event-bib">
+    <group delimiter=" ">
+      <choose>
+        <!-- omit types that provide event information in description  -->
+        <if match="any" type="interview" variable="interviewer"/>
+        <else-if type="personal_communication" variable="recipient"/>
+        <else-if match="any" type="review review-book" variable="reviewed-author reviewed-genre reviewed-title"/>
+        <else-if match="any" variable="event event-date event-title">
+          <!-- TODO: To prevent Zotero from printing `event-place`, due to its double-mapping of `publisher-place` and `event-place`. Remove this when that is changed. -->
+          <choose>
+            <if type="paper-conference">
+              <choose>
+                <if match="none" variable="collection-editor compiler editor editorial-director issue page supplement-number volume">
+                  <!-- Don't print event info for conference papers published in proceedings -->
+                  <text macro="source-event-status-bib"/>
+                  <text macro="source-event-description-bib"/>
+                </if>
+              </choose>
+            </if>
+            <else>
+              <!-- For other item types, print event info even if published (e.g. collection catalogs, performance programs). -->
+              <text macro="source-event-status-bib"/>
+              <text macro="source-event-description-bib"/>
+            </else>
+          </choose>
+        </else-if>
+      </choose>
+    </group>
+  </macro>
+  <macro name="source-event-place-first">
+    <!-- for descriptive elements for interviews, reviews, letters -->
+    <choose>
+      <if match="any" variable="event event-date event-title">
+        <group delimiter=", ">
+          <text variable="event-title"/>
+          <text variable="event-place"/>
+          <text macro="date-event-full"/>
+        </group>
+      </if>
+    </choose>
+  </macro>
+  <macro name="source-event-status-bib">
+    <group delimiter=" ">
+      <choose>
+        <if type="broadcast" variable="status">
+          <!-- 'aired', 'performed', etc. (CMOS18 14.165) -->
+          <text text-case="capitalize-first" variable="status"/>
+        </if>
+        <else-if type="paper-conference">
+          <choose>
+            <if variable="genre">
+              <text text-case="capitalize-first" value="presented"/>
+            </if>
+            <else>
+              <text form="short" term="paper-conference" text-case="capitalize-first"/>
+              <text value="presented"/>
+            </else>
+          </choose>
+          <choose>
+            <if variable="event-title">
+              <text term="at"/>
+            </if>
+          </choose>
+        </else-if>
+        <else-if type="song">
+          <text text-case="capitalize-first" value="recorded"/>
+          <choose>
+            <if variable="event-title">
+              <text term="at"/>
+            </if>
+          </choose>
+        </else-if>
+        <else-if variable="event-date issued"/>
+        <else-if match="none" variable="issued">
+          <text text-case="capitalize-first" variable="status"/>
+        </else-if>
+      </choose>
+    </group>
+  </macro>
+  <macro name="source-event-title">
+    <choose>
+      <!-- TODO: We expect `event-title` to be used, but processors and applications may not be updated yet. This macro ensures that either `event` or `event-title` can be accepted. Remove if processor logic and application adoption can handle this. -->
+      <if variable="event-title">
+        <text variable="event-title"/>
+      </if>
+      <else>
+        <text variable="event"/>
+      </else>
+    </choose>
+  </macro>
+  <macro name="source-event-title-capitalized">
+    <choose>
+      <!-- TODO: We expect `event-title` to be used, but processors and applications may not be updated yet. This macro ensures that either `event` or `event-title` can be accepted. Remove if processor logic and application adoption can handle this. -->
+      <if variable="event-title">
+        <text text-case="capitalize-first" variable="event-title"/>
+      </if>
+      <else>
+        <text text-case="capitalize-first" variable="event"/>
+      </else>
+    </choose>
+  </macro>
+  <macro name="source-event-description-bib">
+    <group delimiter=", ">
+      <choose>
+        <if type="song">
+          <text macro="source-event-title"/>
+        </if>
+        <else-if type="paper-conference" variable="genre">
+          <text macro="source-event-title-capitalized"/>
+        </else-if>
+        <else-if type="paper-conference">
+          <text macro="source-event-title"/>
+        </else-if>
+        <else>
+          <text macro="source-event-title-capitalized"/>
+        </else>
+      </choose>
+      <text macro="date-event-full"/>
+      <text variable="event-place"/>
+    </group>
+  </macro>
+  <!-- 4.5. Facts of publication -->
+  <macro name="source-monographic-publication-bib">
+    <group delimiter=". ">
+      <choose>
+        <!-- Provide only for monographic types -->
+        <if match="any" type="article-journal article-magazine article-newspaper periodical post-weblog review review-book"/>
+        <else-if match="any" type="interview paper-conference">
+          <choose>
+            <if match="any" variable="collection-editor container-author editor editorial-director">
+              <!-- monographic usage -->
+              <text macro="source-publication-and-date-bib"/>
+            </if>
+          </choose>
+        </else-if>
+        <!-- `patent` date in identification (CMOS18 14.158) -->
+        <else-if type="patent"/>
+        <else>
+          <text macro="source-publication-and-date-bib"/>
+        </else>
+      </choose>
+      <text macro="source-publication-original-title-bib"/>
+    </group>
+  </macro>
+  <macro name="source-publication-and-date-bib">
+    <group delimiter=", ">
+      <choose>
+        <if match="any" type="post webpage">
+          <!-- `container-title` functions like a publisher with social media and website sources (CMOS18 14.104-106) -->
+          <text text-case="title" variable="container-title"/>
+        </if>
+      </choose>
+      <choose>
+        <if type="broadcast" variable="DOI">
+          <!-- a podcast publisher appears before the date, whereas the network of an aired show appears after (CMOS18 14.165); unfortunately CSL stores both in `publisher` -->
+          <!-- TODO: `DOI` or `URL` detection is the only way to distinguish radio/TV from podcasts, but it is obviously imprecise; modify if CSL provides a `podcast` type -->
+          <text macro="source-publication-history-bib"/>
+        </if>
+        <else-if type="broadcast" variable="URL">
+          <text macro="source-publication-history-bib"/>
+        </else-if>
+        <else-if type="broadcast"/>
+        <else>
+          <text macro="source-publication-history-bib"/>
+        </else>
+      </choose>
+      <group delimiter=" ">
+        <text macro="source-date-status-bib"/>
+        <text macro="source-date-bib"/>
+      </group>
+      <choose>
+        <if type="broadcast" variable="URL"/>
+        <else-if type="broadcast">
+          <group delimiter=" ">
+            <text term="on"/>
+            <text macro="source-publication-history-bib"/>
+          </group>
+        </else-if>
+      </choose>
+    </group>
+  </macro>
+  <!-- Facts of publication elements -->
+  <macro name="source-publication-description-bib">
+    <choose>
+      <if type="article" variable="genre"/>
+      <else-if type="article">
+        <!-- `preprint` term attached to repository name, but specific working paper descriptors appear in description (CMOS18 14.76, 14.116) -->
+        <text term="preprint" text-case="capitalize-first"/>
+      </else-if>
+      <else-if type="thesis">
+        <!-- thesis type appears with university name (CMOS18 14.113) -->
+        <text macro="description-format-bib"/>
+      </else-if>
+      <else-if match="any" variable="original-publisher original-publisher-place">
+        <choose>
+          <!-- `edition` provides an alternative label to `reprint` (CMOS18 14.16) -->
+          <if match="any" variable="edition original-title"/>
+          <else-if match="none" type="book chapter classic entry entry-dictionary entry-encyclopedia interview musical_score pamphlet paper-conference report thesis"/>
+          <else-if variable="issued original-date">
+            <text text-case="capitalize-first" value="reprint"/>
+          </else-if>
+        </choose>
+      </else-if>
+    </choose>
+  </macro>
+  <macro name="source-publication-history-bib">
+    <choose>
+      <if variable="original-title">
+        <!-- `original-title` is covered in `source-publication-original-title-bib` -->
+        <group delimiter=", ">
+          <text macro="source-publication-description-bib"/>
+          <text macro="source-publication-publisher-bib"/>
+        </group>
+      </if>
+      <else-if match="any" variable="edition original-publisher original-publisher-place">
+        <group delimiter=". ">
+          <!-- full stop to separate original date if `original-publisher` (CMOS18 14.16) -->
+          <group delimiter=", ">
+            <text macro="source-publication-publisher-original-bib"/>
+            <text macro="source-date-original"/>
+          </group>
+          <group delimiter=". ">
+            <choose>
+              <if variable="issued original-date">
+                <text macro="label-edition-capitalized"/>
+              </if>
+            </choose>
+            <group delimiter=", ">
+              <text macro="source-publication-description-bib"/>
+              <text macro="source-publication-publisher-bib"/>
+            </group>
+          </group>
+        </group>
+      </else-if>
+      <else>
+        <group delimiter="; ">
+          <!-- semicolon to separate original date if no publisher (CMOS18 14.165) -->
+          <text macro="source-date-original"/>
+          <group delimiter=", ">
+            <text macro="source-publication-description-bib"/>
+            <text macro="source-publication-publisher-bib"/>
+          </group>
+        </group>
+      </else>
+    </choose>
+  </macro>
+  <macro name="source-publication-original-title-bib">
+    <!-- Work originally published under a different title (CMOS18 13.101) -->
+    <choose>
+      <if variable="original-title">
+        <group delimiter=" ">
+          <text term="original-work-published" text-case="capitalize-first"/>
+          <group delimiter=", ">
+            <names variable="original-author"/>
+            <text font-style="italic" text-case="title" variable="original-title"/>
+          </group>
+          <group delimiter=", " prefix="(" suffix=")">
+            <text macro="source-publication-publisher-original-bib"/>
+            <text macro="source-date-original"/>
+          </group>
+        </group>
+      </if>
+    </choose>
+  </macro>
+  <macro name="source-publication-publisher-bib">
+    <group delimiter=" ">
+      <choose>
+        <if type="thesis" variable="publisher">
+          <text text-case="capitalize-first" variable="publisher"/>
+        </if>
+        <else-if variable="publisher">
+          <group delimiter=": ">
+            <!-- <text text-case="capitalize-first" variable="publisher-place"/> -->
+            <text text-case="capitalize-first" variable="publisher"/>
+          </group>
+        </else-if>
+        <!-- TODO: remove conditional when Zotero fixes double-mapping of `event-place` -->
+        <else-if match="any" variable="event-date event-title"/>
+        <else>
+          <text text-case="capitalize-first" variable="publisher-place"/>
+        </else>
+      </choose>
+      <choose>
+        <if type="song">
+          <!-- Album catalogue number follows label name (CMOS18 14.163-164) -->
+          <text variable="number"/>
+        </if>
+      </choose>
+    </group>
+  </macro>
+  <macro name="source-publication-publisher-original-bib">
+    <choose>
+      <if variable="original-publisher">
+        <group delimiter=": ">
+          <!-- <text text-case="capitalize-first" variable="original-publisher-place"/> -->
+          <text text-case="capitalize-first" variable="original-publisher"/>
+        </group>
+      </if>
+      <else>
+        <text text-case="capitalize-first" variable="original-publisher-place"/>
+      </else>
+    </choose>
+  </macro>
+  <!-- 4.6. Date -->
+  <macro name="source-date-bib">
+    <!-- the date represents the last-mentioned title (CMOS18 14.21) -->
+    <!-- there is no `source-date-note` as the date of a multivolume work is not used in note form -->
+    <choose>
+      <if variable="available-date volume-title">
+        <!-- TODO: Is there a better CSL variable for a date of a multivolume work (CMOS18 14.21)? -->
+        <date date-parts="year" form="text" variable="available-date"/>
+      </if>
+      <else-if variable="available-date part-title">
+        <date date-parts="year" form="text" variable="available-date"/>
+      </else-if>
+      <else>
+        <text macro="source-date-issued-month-day"/>
+      </else>
+    </choose>
+  </macro>
+  <!-- Date elements -->
+  <macro name="source-date-issued-month-day">
+    <!-- Variant for author-date styles -->
+    <!-- Give full date for more ephemeral types -->
+    <!-- NB: any changes must also be applied to `source-date-original-month-day` -->
+    <choose>
+      <if type="personal_communication" variable="event-date issued">
+        <!-- Provide issue date for letters listed under event-date -->
+        <text macro="date-issued-year"/>
+      </if>
+      <else-if match="any" type="article-journal article-magazine article-newspaper periodical post-weblog review review-book">
+        <text macro="source-date-issued-month-day-serial"/>
+      </else-if>
+      <else-if match="any" type="interview paper-conference">
+        <choose>
+          <if match="none" variable="collection-editor compiler editor editorial-director">
+            <!-- serial usage -->
+            <text macro="source-date-issued-month-day-serial"/>
+          </if>
+        </choose>
+      </else-if>
+      <else-if match="any" type="entry entry-dictionary entry-encyclopedia">
+        <choose>
+          <if match="any" variable="DOI URL">
+            <!-- Online reference works use full dates (CMOS18 14.131) -->
+            <text macro="date-issued-month-day"/>
+          </if>
+        </choose>
+      </else-if>
+      <else-if match="any" type="article broadcast collection dataset document event graphic interview manuscript map patent performance personal_communication post software song speech standard webpage">
+        <text macro="date-issued-month-day"/>
+      </else-if>
+    </choose>
+  </macro>
+  <macro name="source-date-issued-month-day-serial">
+    <choose>
+      <if type="article-newspaper">
+        <!-- newspapers provide the full date in place of volume/issue numbers (CMOS18 14.89) -->
+        <text macro="date-issued-month-day"/>
+      </if>
+      <else-if match="any" variable="issue supplement-number volume">
+        <text macro="date-issued-month"/>
+      </else-if>
+      <else>
+        <text macro="date-issued-month-day"/>
+      </else>
+    </choose>
+  </macro>
+  <macro name="source-date-original">
+    <text macro="source-date-original-month-day"/>
+  </macro>
+  <macro name="source-date-original-month-day">
+    <!-- Give full date for more ephemeral types -->
+    <!-- Macro derived from `source-date-issued-month-day` -->
+    <choose>
+      <if type="personal_communication" variable="event-date original-date">
+        <!-- Provide original date for letters listed under event-date -->
+        <text macro="date-original-year"/>
+      </if>
+      <else-if match="any" type="article-journal article-magazine article-newspaper periodical post-weblog review review-book">
+        <choose>
+          <if match="any" variable="issue supplement-number volume">
+            <text macro="date-original-month"/>
+          </if>
+          <else>
+            <text macro="date-original-month-day"/>
+          </else>
+        </choose>
+      </else-if>
+      <else-if match="any" type="interview paper-conference">
+        <choose>
+          <if match="none" variable="collection-editor compiler editor editorial-director">
+            <!-- serial usage -->
+            <choose>
+              <if match="any" variable="issue supplement-number volume">
+                <text macro="date-original-month"/>
+              </if>
+              <else>
+                <text macro="date-original-month-day"/>
+              </else>
+            </choose>
+          </if>
+        </choose>
+      </else-if>
+      <else-if match="any" type="entry entry-dictionary entry-encyclopedia">
+        <choose>
+          <if match="any" variable="DOI URL">
+            <!-- Online reference works use full dates (CMOS18 14.131) -->
+            <text macro="date-original-month-day"/>
+          </if>
+        </choose>
+      </else-if>
+      <else-if match="any" type="article broadcast collection dataset document event graphic interview manuscript map patent performance personal_communication post software song speech standard webpage">
+        <text macro="date-original-month-day"/>
+      </else-if>
+    </choose>
+  </macro>
+  <macro name="source-date-status-bib">
+    <choose>
+      <if type="broadcast" variable="event-title issued status"/>
+      <!-- on a `broadcast`, if there is an `event-title`, `status` appears with `event-date` as part of `source-event` (CMOS18 14.165) -->
+      <else-if variable="issued status">
+        <!-- `status` specifies date type, e.g. 'effective', 'last modified', 'approved' (CMOS18 14.104 for `webpage`; CMOS18 14.159 for `standard`) -->
+        <choose>
+          <if match="any" variable="original-date original-publisher original-publisher-place original-title publisher">
+            <text variable="status"/>
+          </if>
+          <else>
+            <text text-case="capitalize-first" variable="status"/>
+          </else>
+        </choose>
+      </else-if>
+      <else-if type="broadcast" variable="issued URL"/>
+      <else-if type="broadcast" variable="issued">
+        <!-- `status` of a radio or TV broadcast is 'aired' if unspecified (CMOS18 14.165) -->
+        <text text-case="capitalize-first" value="aired"/>
+      </else-if>
+      <else-if type="software" variable="issued publisher">
+        <!-- `status` of software is 'released' if unspecified (CMOS18 14.169) -->
+        <choose>
+          <if match="any" variable="author chair collection-editor compiler composer contributor curator director editor editor-translator editorial-director executive-producer guest host illustrator organizer producer series-creator translator">
+            <!-- lowercase if `publisher` is adjacent -->
+            <text value="released"/>
+          </if>
+          <else>
+            <text text-case="capitalize-first" value="released"/>
+          </else>
+        </choose>
+      </else-if>
+      <else-if type="software" variable="original-date">
+        <!-- lowercase if `original-date` is adjacent -->
+        <text value="released"/>
+      </else-if>
+      <else-if type="software" variable="issued">
+        <!-- capitalize if `publisher` is not present -->
+        <text text-case="capitalize-first" value="released"/>
+      </else-if>
+    </choose>
+  </macro>
+  <!-- 4.7. Locator (including page references) -->
+  <macro name="source-locator-author-date">
+    <choose>
+      <if match="any" type="entry entry-dictionary entry-encyclopedia">
+        <choose>
+          <if match="any" variable="author locator">
+            <text macro="label-locator"/>
+          </if>
+          <else-if variable="container-title title">
+            <!-- unsigned reference entry title appears in the locator (CMOS18 13.130) -->
+            <group delimiter=" ">
+              <choose>
+                <if match="none" variable="DOI URL">
+                  <!-- Only print reference entries use `sub-verbo` (CMOS18 14.131) -->
+                  <text form="short" term="sub-verbo"/>
+                </if>
+              </choose>
+              <text form="short" quotes="true" variable="title"/>
+            </group>
+          </else-if>
+        </choose>
+      </if>
+      <else>
+        <text macro="label-locator"/>
+      </else>
+    </choose>
+  </macro>
+  <!-- 4.8. Medium -->
+  <macro name="source-medium-bib">
+    <group delimiter=", ">
+      <text text-case="capitalize-first" variable="medium"/>
+      <text variable="scale"/>
+      <text variable="dimensions"/>
+    </group>
+  </macro>
+  <!-- 4.9. Archival location -->
+  <macro name="source-archive-bib">
+    <choose>
+      <!-- With `archive_collection` or `archive-place`: physical archives -->
+      <if type="graphic">
+        <text macro="source-archive-name-first"/>
+      </if>
+      <else-if match="any" type="collection document manuscript personal_communication" variable="archive_collection archive-place">
+        <text macro="source-archive-location-first-bib"/>
+      </else-if>
+      <!-- Without `archive_collection` or `archive-place`: digital archives (database and identifier) -->
+      <else>
+        <text macro="source-archive-identifier"/>
+      </else>
+    </choose>
+  </macro>
+  <macro name="source-archive-note">
+    <choose>
+      <!-- With `archive_collection` or `archive-place`: physical archives -->
+      <if type="graphic">
+        <text macro="source-archive-name-first"/>
+      </if>
+      <else-if match="any" type="collection document manuscript personal_communication" variable="archive_collection archive-place">
+        <text macro="source-archive-location-first-note"/>
+      </else-if>
+      <!-- Without `archive_collection` or `archive-place`: digital archives (database and identifier) -->
+      <else>
+        <text macro="source-archive-identifier"/>
+      </else>
+    </choose>
+  </macro>
+  <!-- Archival elements -->
+  <macro name="source-archive-identifier">
+    <choose>
+      <if variable="archive archive_location">
+        <!-- database identifier: the only example is `thesis`, but presumably this is for all types (CMOS18 14.113) -->
+        <group delimiter=" ">
+          <text variable="archive"/>
+          <text prefix="(" suffix=")" variable="archive_location"/>
+        </group>
+      </if>
+      <else>
+        <group delimiter=", ">
+          <text variable="archive"/>
+          <text variable="archive_location"/>
+        </group>
+      </else>
+    </choose>
+  </macro>
+  <macro name="source-archive-location-first-bib">
+    <!-- Order of elements begins with the most specific (CMOS18 14.119, 14.127) -->
+    <!-- In note styles, the bibliography generally provide entries for a `collection` rather than individual items (CMOS18 14.120, 14.128) -->
+    <group delimiter=". ">
+      <group delimiter=", ">
+        <text text-case="capitalize-first" variable="archive_location"/>
+        <text variable="archive_collection"/>
+      </group>
+      <group delimiter=", ">
+        <text variable="archive"/>
+        <text variable="archive-place"/>
+      </group>
+    </group>
+  </macro>
+  <macro name="source-archive-location-first-note">
+    <!-- Order of elements begins with the most specific (CMOS18 14.119, 14.127) -->
+    <!-- In note styles, the bibliography generally provide entries for a `collection` rather than individual items (CMOS18 14.120, 14.128) -->
+    <group delimiter=", ">
+      <group delimiter=", ">
+        <text variable="archive_location"/>
+        <text variable="archive_collection"/>
+      </group>
+      <group delimiter=", ">
+        <text variable="archive"/>
+        <text variable="archive-place"/>
+      </group>
+    </group>
+  </macro>
+  <macro name="source-archive-name-first">
+    <!-- Archive (gallery) name first for art (CMOS18 14.133) -->
+    <group delimiter=", ">
+      <text variable="archive"/>
+      <text variable="archive-place"/>
+      <text variable="archive_collection"/>
+      <text variable="archive_location"/>
+    </group>
+  </macro>
+  <!-- 4.10. URL or persistent identifier -->
+  <macro name="source-date-accessed-DOI-URL-bib">
+    <group delimiter=". ">
+      <choose>
+        <if variable="DOI"/>
+        <else-if match="any" variable="available-date event-date issued status"/>
+        <else-if variable="accessed URL">
+          <group delimiter=" ">
+            <text term="accessed" text-case="capitalize-first"/>
+            <date form="text" variable="accessed"/>
+          </group>
+        </else-if>
+      </choose>
+      <text macro="source-DOI-URL"/>
+    </group>
+  </macro>
+  <macro name="source-DOI-URL">
+    <choose>
+      <if variable="DOI">
+        <text prefix="https://doi.org/" variable="DOI"/>
+      </if>
+      <else-if variable="URL">
+        <text variable="URL"/>
+      </else-if>
+    </choose>
+  </macro>
+  <!-- 5. Notes -->
+  <!-- TODO: add variables for distributor and exhibitions if available in CSL -->
+  <!-- 6. Legal references: Bluebook style (shared with APA) -->
+  <!-- Where APA or Chicago diverge from Bluebook, the official manual is followed -->
+  <macro name="legal-reference">
+    <!-- Type usage:
+
+         `bill`
+         : bills, resolutions, federal reports
+
+         `legal_case`
+         : all legal and court cases
+
+         `hearing`
+         : hearings and testimony
+
+         `legislation`
+         : statutes, constitutional items, and charters
+
+         `regulation`
+         : codified regulations, uncodified regulations, executive orders
+
+         `treaty`
+         : treaties
+    -->
+    <group delimiter=", ">
+      <choose>
+        <if type="treaty">
+          <text macro="legal-title"/>
+          <names variable="author">
+            <!-- Treaty parties should be included at least for bilateral treaties (Bluebook 21.4.2) -->
+            <name delimiter="-" et-al-min="100" et-al-use-first="99" form="short"/>
+          </names>
+          <text macro="legal-date"/>
+          <!-- treaty source/report in addition to URL (Bluebook 21.4.5) -->
+          <text macro="legal-source"/>
+        </if>
+        <else>
+          <group delimiter=" ">
+            <group delimiter=", ">
+              <text macro="legal-title"/>
+              <text macro="legal-source"/>
+            </group>
+            <text macro="legal-date"/>
+            <text macro="legal-identifier"/>
+          </group>
+        </else>
+      </choose>
+      <group delimiter=" ">
+        <!-- locator for use in notes -->
+        <choose>
+          <if locator="page" variable="page">
+            <text term="at"/>
+          </if>
+        </choose>
+        <text macro="label-locator"/>
+      </group>
+    </group>
+  </macro>
+  <!-- 6.1. Legal date -->
+  <macro name="legal-date">
+    <choose>
+      <if type="treaty">
+        <text macro="date-issued-full"/>
+      </if>
+      <else-if type="legal_case">
+        <text macro="legal-date-case"/>
+      </else-if>
+      <else-if match="any" type="bill hearing legislation regulation">
+        <group delimiter=" " prefix="(" suffix=")">
+          <group delimiter=" ">
+            <text macro="date-original-year"/>
+            <text form="symbol" term="and"/>
+          </group>
+          <choose>
+            <if variable="issued">
+              <text macro="date-issued-year"/>
+            </if>
+            <else>
+              <!-- Show proposal date for uncodified regulations. Assume date is entered literally ala "proposed May 23, 2016". -->
+              <!-- TODO: Add `proposed` date here if that becomes available -->
+              <date form="text" variable="submitted"/>
+            </else>
+          </choose>
+        </group>
+      </else-if>
+    </choose>
+  </macro>
+  <macro name="legal-date-case">
+    <group delimiter=" " prefix="(" suffix=")">
+      <text variable="authority"/>
+      <choose>
+        <if variable="container-title">
+          <!-- Print only year for cases published in reporters-->
+          <text macro="date-issued-year"/>
+        </if>
+        <else>
+          <text macro="date-issued-full"/>
+        </else>
+      </choose>
+    </group>
+  </macro>
+  <!-- 6.2.1. Legal title -->
+  <macro name="legal-title">
+    <choose>
+      <if match="any" type="bill legal_case legislation regulation treaty">
+        <text text-case="title" variable="title"/>
+      </if>
+      <else-if type="hearing">
+        <!-- use standard format (Bluebook 13.3) -->
+        <group delimiter=": " font-style="italic">
+          <text text-case="capitalize-first" variable="title"/>
+          <group delimiter=" ">
+            <text term="hearing" text-case="capitalize-first"/>
+            <group delimiter=" ">
+              <group delimiter=" ">
+                <text term="on"/>
+                <text variable="number"/>
+              </group>
+              <group delimiter=" ">
+                <text value="before the"/>
+                <text variable="section"/>
+              </group>
+            </group>
+          </group>
+        </group>
+      </else-if>
+    </choose>
+  </macro>
+  <!-- 6.2.2. Legal identifier -->
+  <macro name="legal-identifier">
+    <choose>
+      <if type="hearing">
+        <group delimiter=" " prefix="(" suffix=")">
+          <!-- Use the 'verb' form of the hearing term to hold 'testimony of' -->
+          <text form="verb" term="hearing"/>
+          <names variable="author">
+            <name and="symbol" initialize="false"/>
+          </names>
+        </group>
+      </if>
+      <else-if match="any" type="bill legislation regulation">
+        <!-- For uncodified regulations, assume future code section is in `status`. -->
+        <text prefix="(" suffix=")" variable="status"/>
+      </else-if>
+    </choose>
+  </macro>
+  <macro name="legal-identifier-bill-report">
+    <group delimiter=" ">
+      <text variable="genre"/>
+      <choose>
+        <if match="any" variable="authority chapter-number container-title">
+          <text variable="number"/>
+        </if>
+        <else>
+          <!-- If there is no legislative body, session number, or code/record title, assume the item is a congressional report and include 'No.' label. -->
+          <text macro="label-number-capitalized"/>
+        </else>
+      </choose>
+    </group>
+  </macro>
+  <!-- 6.3. Legal source -->
+  <macro name="legal-source">
+    <!-- Expect legal item `container-title` to be stored in short form -->
+    <choose>
+      <if type="bill">
+        <text macro="legal-source-bill"/>
+      </if>
+      <else-if type="hearing">
+        <text macro="legal-source-hearing"/>
+      </else-if>
+      <else-if type="legal_case">
+        <text macro="legal-source-case"/>
+      </else-if>
+      <else-if type="legislation">
+        <text macro="legal-source-legislation"/>
+      </else-if>
+      <else-if type="regulation">
+        <text macro="legal-source-regulation"/>
+      </else-if>
+      <else-if type="treaty">
+        <text macro="legal-source-treaty"/>
+      </else-if>
+    </choose>
+  </macro>
+  <!-- Legal source types -->
+  <macro name="legal-source-bill">
+    <group delimiter=", ">
+      <text macro="legal-identifier-bill-report"/>
+      <group delimiter=" ">
+        <text variable="authority"/>
+        <!-- `chapter-number` is a session number -->
+        <text variable="chapter-number"/>
+      </group>
+      <group delimiter=" ">
+        <text variable="volume"/>
+        <text variable="container-title"/>
+        <text variable="page-first"/>
+      </group>
+    </group>
+  </macro>
+  <macro name="legal-source-case">
+    <group delimiter=" ">
+      <choose>
+        <if variable="container-title">
+          <group delimiter=" ">
+            <text variable="volume"/>
+            <text variable="container-title"/>
+            <text macro="label-section-symbol"/>
+            <choose>
+              <if match="any" variable="page page-first">
+                <text variable="page-first"/>
+              </if>
+              <else>
+                <text value="___"/>
+              </else>
+            </choose>
+          </group>
+        </if>
+        <else>
+          <text macro="label-number-capitalized"/>
+        </else>
+      </choose>
+    </group>
+  </macro>
+  <macro name="legal-source-hearing">
+    <group delimiter=" ">
+      <text variable="authority"/>
+      <!-- `chapter-number` is a session number -->
+      <text variable="chapter-number"/>
+    </group>
+  </macro>
+  <macro name="legal-source-legislation">
+    <choose>
+      <if variable="number">
+        <!-- `number` is a public law number -->
+        <group delimiter=", ">
+          <group delimiter=" ">
+            <choose>
+              <if variable="genre">
+                <text text-case="capitalize-first" variable="genre"/>
+              </if>
+              <else>
+                <text form="short" term="legislation" text-case="capitalize-first"/>
+              </else>
+            </choose>
+            <text macro="label-number-capitalized"/>
+          </group>
+          <group delimiter=" ">
+            <text variable="volume"/>
+            <text variable="container-title"/>
+            <text variable="page-first"/>
+          </group>
+        </group>
+      </if>
+      <else>
+        <group delimiter=" ">
+          <text variable="volume"/>
+          <text variable="container-title"/>
+          <choose>
+            <if variable="section">
+              <text macro="label-section-symbol"/>
+            </if>
+            <else>
+              <text variable="page-first"/>
+            </else>
+          </choose>
+        </group>
+      </else>
+    </choose>
+  </macro>
+  <macro name="legal-source-regulation">
+    <group delimiter=", ">
+      <group delimiter=" ">
+        <text variable="genre"/>
+        <text macro="label-number-capitalized"/>
+      </group>
+      <group delimiter=" ">
+        <text variable="volume"/>
+        <text variable="container-title"/>
+        <choose>
+          <if variable="section">
+            <text macro="label-section-symbol"/>
+          </if>
+          <else>
+            <text variable="page-first"/>
+          </else>
+        </choose>
+      </group>
+    </group>
+  </macro>
+  <macro name="legal-source-treaty">
+    <group delimiter=" ">
+      <number variable="volume"/>
+      <text variable="container-title"/>
+      <choose>
+        <if match="any" variable="page page-first">
+          <text variable="page-first"/>
+        </if>
+        <else>
+          <text macro="label-number-capitalized"/>
+        </else>
+      </choose>
+    </group>
+  </macro>
+  <!-- Citation -->
+  <macro name="citation-author-date-item">
+    <group delimiter=", ">
+      <choose>
+        <if type="classic">
+          <text macro="author-inline"/>
+          <choose>
+            <if variable="author">
+              <text macro="title-and-descriptions-short"/>
+            </if>
+          </choose>
+        </if>
+        <else-if match="any" variable="event-date issued">
+          <choose>
+            <if match="any" type="interview personal_communication">
+              <choose>
+                <if match="any" variable="archive archive-place container-title DOI number publisher references URL">
+                  <group delimiter=" ">
+                    <text macro="author-inline"/>
+                    <text macro="date-short"/>
+                  </group>
+                </if>
+                <else>
+                  <!-- unpublished `interview` or `personal_communication` use inline format (CMOS18 14.111) -->
+                  <text macro="author-inline"/>
+                  <text macro="title-and-descriptions-short"/>
+                  <text macro="date-short"/>
+                </else>
+              </choose>
+            </if>
+            <else>
+              <group delimiter=" ">
+                <text macro="author-inline"/>
+                <text macro="date-short"/>
+              </group>
+            </else>
+          </choose>
+        </else-if>
+        <else>
+          <!--- Comma with forthcoming or n.d. -->
+          <text macro="author-inline"/>
+          <choose>
+            <if match="any" type="interview personal_communication">
+              <choose>
+                <if match="none" variable="archive archive-place container-title DOI number publisher references URL">
+                  <!-- unpublished `interview` or `personal_communication` use inline format (CMOS18 14.111) -->
+                  <text macro="title-and-descriptions-short"/>
+                </if>
+              </choose>
+            </if>
+          </choose>
+          <text macro="date-short"/>
+        </else>
+      </choose>
+    </group>
+  </macro>
+  <citation after-collapse-delimiter="; " collapse="year" disambiguate-add-givenname="true" disambiguate-add-names="true" disambiguate-add-year-suffix="true" et-al-min="3" et-al-use-first="1">
+    <layout delimiter="; " prefix="(" suffix=")">
+      <choose>
+        <if type="classic">
+          <!-- with `classic`, a non-numeric canonical reference or identifying number is separated by a space rather than a comma (CMOS18 14.145) -->
+          <choose>
+            <if is-numeric="locator">
+              <group delimiter=", ">
+                <text macro="citation-author-date-item"/>
+                <text macro="source-locator-author-date"/>
+              </group>
+            </if>
+            <else-if locator="chapter line verse" match="any">
+              <group delimiter=" ">
+                <text macro="citation-author-date-item"/>
+                <text macro="source-locator-author-date"/>
+              </group>
+            </else-if>
+            <else>
+              <group delimiter=", ">
+                <text macro="citation-author-date-item"/>
+                <text macro="source-locator-author-date"/>
+              </group>
+            </else>
+          </choose>
+        </if>
+        <else>
+          <group delimiter=", ">
+            <text macro="citation-author-date-item"/>
+            <text macro="source-locator-author-date"/>
+          </group>
+        </else>
+      </choose>
+    </layout>
+  </citation>
+  <!-- Bibliography -->
+  <macro name="bibliography-author-date">
+    <group delimiter=". ">
+      <choose>
+        <if match="any" type="bill hearing legal_case legislation regulation treaty">
+          <!-- Legal items have different orders and delimiters -->
+          <text macro="legal-reference"/>
+          <text macro="source-date-accessed-DOI-URL-bib"/>
+          <text variable="references"/>
+        </if>
+        <else>
+          <text macro="author-bib"/>
+          <text macro="date"/>
+          <text macro="title-and-source-bib"/>
+          <text variable="references"/>
+        </else>
+      </choose>
+    </group>
+  </macro>
+  <bibliography et-al-min="7" et-al-use-first="3" hanging-indent="true">
+    <sort>
+      <key macro="author-sort"/>
+      <key macro="date-sort-group"/>
+      <key macro="date-sort-year"/>
+      <key macro="date"/>
+      <key macro="title-and-descriptions-bib"/>
+      <key macro="source-bib"/>
+      <key variable="volume"/>
+      <key variable="part-number"/>
+      <key variable="event-date"/>
+      <key variable="issued"/>
+      <key macro="source-archive-bib"/>
+    </sort>
+    <layout suffix=".">
+      <choose>
+        <if type="classic">
+          <choose>
+            <if match="any" variable="archive editor translator publisher">
+              <text macro="bibliography-author-date"/>
+            </if>
+          </choose>
+        </if>
+        <else-if match="any" type="entry entry-dictionary entry-encyclopedia">
+          <choose>
+            <if variable="author">
+              <!-- Signed reference entries appear in the bibliography (CMOS18 14.132) -->
+              <text macro="bibliography-author-date"/>
+            </if>
+            <else-if match="any" variable="DOI URL">
+              <!-- Provide a bibliography if necessary identifying information is not in text -->
+              <text macro="bibliography-author-date"/>
+            </else-if>
+          </choose>
+        </else-if>
+        <else-if match="any" type="interview personal_communication">
+          <choose>
+            <if match="any" variable="archive archive-place container-title DOI number publisher references URL">
+              <!-- Personal communications only appear in the bibliography if the reader can retrieve them (CMOS18 14.13, 14.111) -->
+              <text macro="bibliography-author-date"/>
+            </if>
+          </choose>
+        </else-if>
+        <else>
+          <text macro="bibliography-author-date"/>
+        </else>
+      </choose>
+    </layout>
+  </bibliography>
+</style>
diff --git a/data/docbook-entities.txt b/data/docbook-entities.txt
new file mode 100644
--- /dev/null
+++ b/data/docbook-entities.txt
@@ -0,0 +1,2237 @@
+aacgr 03AC
+Aacgr 0386
+aacute 00E1
+Aacute 00C1
+abreve 0103
+Abreve 0102
+ac 223E
+acd 223F
+acE 223E  0333
+acirc 00E2
+Acirc 00C2
+acute 00B4
+acy 0430
+Acy 0410
+aelig 00E6
+AElig 00C6
+af 2061
+afr 1D51E
+Afr 1D504
+agr 03B1
+Agr 0391
+agrave 00E0
+Agrave 00C0
+alefsym 2135
+aleph 2135
+alpha 03B1
+Alpha 0391
+amacr 0101
+Amacr 0100
+amalg 2A3F
+amp 0026
+AMP 0026
+and 2227
+And 2A53
+andand 2A55
+andd 2A5C
+andslope 2A58
+andv 2A5A
+ang 2220
+ange 29A4
+angle 2220
+angmsd 2221
+angmsdaa 29A8
+angmsdab 29A9
+angmsdac 29AA
+angmsdad 29AB
+angmsdae 29AC
+angmsdaf 29AD
+angmsdag 29AE
+angmsdah 29AF
+angrt 221F
+angrtvb 22BE
+angrtvbd 299D
+angsph 2222
+angst 00C5
+angzarr 237C
+aogon 0105
+Aogon 0104
+aopf 1D552
+Aopf 1D538
+ap 2248
+apacir 2A6F
+ape 224A
+apE 2A70
+apid 224B
+apos 0027
+ApplyFunction 2061
+approx 2248
+approxeq 224A
+aring 00E5
+Aring 00C5
+ascr 1D4B6
+Ascr 1D49C
+Assign 2254
+ast 002A
+asymp 2248
+asympeq 224D
+atilde 00E3
+Atilde 00C3
+auml 00E4
+Auml 00C4
+awconint 2233
+awint 2A11
+b.alpha 1D6C2
+b.beta 1D6C3
+b.chi 1D6D8
+b.delta 1D6C5
+b.Delta 1D6AB
+b.epsi 1D6C6
+b.epsiv 1D6DC
+b.eta 1D6C8
+b.gamma 1D6C4
+b.Gamma 1D6AA
+b.gammad 1D7CB
+b.Gammad 1D7CA
+b.iota 1D6CA
+b.kappa 1D6CB
+b.kappav 1D6DE
+b.lambda 1D6CC
+b.Lambda 1D6B2
+b.mu 1D6CD
+b.nu 1D6CE
+b.omega 1D6DA
+b.Omega 1D6C0
+b.phi 1D6D7
+b.Phi 1D6BD
+b.phiv 1D6DF
+b.pi 1D6D1
+b.Pi 1D6B7
+b.piv 1D6E1
+b.psi 1D6D9
+b.Psi 1D6BF
+b.rho 1D6D2
+b.rhov 1D6E0
+b.sigma 1D6D4
+b.Sigma 1D6BA
+b.sigmav 1D6D3
+b.tau 1D6D5
+b.Theta 1D6AF
+b.thetas 1D6C9
+b.thetav 1D6DD
+b.upsi 1D6D6
+b.UpsiUpsilon
+b.xi 1D6CF
+b.Xi 1D6B5
+b.zeta 1D6C7
+backcong 224C
+backepsilon 03F6
+backprime 2035
+backsim 223D
+backsimeq 22CD
+Backslash 2216
+Barv 2AE7
+barvee 22BD
+barwed 2305
+Barwed 2306
+barwedge 2305
+bbrk 23B5
+bbrktbrk 23B6
+bcong 224C
+bcy 0431
+Bcy 0411
+bdquo 201E
+becaus 2235
+because 2235
+Because 2235
+bemptyv 29B0
+bepsi 03F6
+bernou 212C
+Bernoullis 212C
+beta 03B2
+Beta 0392
+beth 2136
+between 226C
+bfr 1D51F
+Bfr 1D505
+bgr 03B2
+Bgr 0392
+bigcap 22C2
+bigcirc 25EF
+bigcup 22C3
+bigodot 2A00
+bigoplus 2A01
+bigotimes 2A02
+bigsqcup 2A06
+bigstarUB starf
+bigtriangledown 25BD
+bigtriangleup 25B3
+biguplus 2A04
+bigvee 22C1
+bigwedge 22C0
+bkarow 290D
+blacklozengeUB lozf
+blacksquare 25AA
+blacktriangleUB utrif
+blacktriangledownUB dtrif
+blacktriangleleftUB ltrif
+blacktrianglerightUB rtrif
+blank 2423
+blk12 2592
+blk14 2591
+blk34 2593
+block 2588
+bne 003D  20E5
+bnequiv 2261  20E5
+bnot 2310
+bNot 2AED
+bopf 1D553
+Bopf 1D539
+bot 22A5
+bottom 22A5
+bowtie 22C8
+boxbox 29C9
+boxdl 2510
+boxdL 2555
+boxDl 2556
+boxDL 2557
+boxdr 250C
+boxdR 2552
+boxDr 2553
+boxDR 2554
+boxh 2500
+boxH 2550
+boxhd 252C
+boxhD 2565
+boxHd 2564
+boxHD 2566
+boxhu 2534
+boxhU 2568
+boxHu 2567
+boxHU 2569
+boxminus 229F
+boxplus 229E
+boxtimes 22A0
+boxul 2518
+boxuL 255B
+boxUl 255C
+boxUL 255D
+boxur 2514
+boxuR 2558
+boxUr 2559
+boxUR 255A
+boxv 2502
+boxV 2551
+boxvh 253C
+boxvH 256A
+boxVh 256B
+boxVH 256C
+boxvl 2524
+boxvL 2561
+boxVl 2562
+boxVL 2563
+boxvr 251C
+boxvR 255E
+boxVr 255F
+boxVR 2560
+bprime 2035
+breve 02D8
+Breve 02D8
+brvbar 00A6
+bscr 1D4B7
+Bscr 212C
+bsemi 204F
+bsim 223D
+bsime 22CD
+bsol 005C
+bsolb 29C5
+bsolhsub 27C8
+bull 2022
+bulletUB bull
+bump 224E
+bumpe 224F
+bumpE 2AAE
+bumpeq 224F
+Bumpeq 224E
+cacute 0107
+Cacute 0106
+cap 2229
+Cap 22D2
+capand 2A44
+capbrcup 2A49
+capcap 2A4B
+capcup 2A47
+capdot 2A40
+CapitalDifferentialD 2145
+caps 2229  FE00
+caret 2041
+caron 02C7
+Cayleys 212D
+ccaps 2A4D
+ccaron 010D
+Ccaron 010C
+ccedil 00E7
+Ccedil 00C7
+ccirc 0109
+Ccirc 0108
+Cconint 2230
+ccups 2A4C
+ccupssm 2A50
+cdot 010B
+Cdot 010A
+cedil 00B8
+Cedilla 00B8
+cemptyv 29B2
+cent 00A2
+centerdotUM middot
+CenterDotUM middot
+cfr 1D520
+Cfr 212D
+chcy 0447
+CHcy 0427
+check 2713
+checkmarkUB check
+chi 03C7
+Chi 03A7
+cir 25CB
+circ 02C6
+circeq 2257
+circlearrowleft 21BA
+circlearrowright 21BB
+circledast 229B
+circledcirc 229A
+circleddash 229D
+CircleDot 2299
+circledRUM reg
+circledS 24C8
+CircleMinus 2296
+CirclePlus 2295
+CircleTimes 2297
+cire 2257
+cirE 29C3
+cirfnint 2A10
+cirmid 2AEF
+cirscir 29C2
+ClockwiseContourIntegral 2232
+CloseCurlyDoubleQuoteUM rdquo
+CloseCurlyQuoteUM rsquo
+clubs 2663
+clubsuitUB clubs
+colon 003A
+Colon 2237
+colone 2254
+Colone 2A74
+coloneq 2254
+comma 002C
+commat 0040
+comp 2201
+compfn 2218
+complement 2201
+complexes 2102
+cong 2245
+congdot 2A6D
+Congruent 2261
+conint 222E
+Conint 222F
+ContourIntegral 222E
+copf 1D554
+Copf 2102
+coprod 2210
+Coproduct 2210
+copy 00A9
+COPY 00A9
+copysr 2117
+CounterClockwiseContourIntegral 2233
+crarr 21B5
+cross 2717
+Cross 2A2F
+cscr 1D4B8
+Cscr 1D49E
+csub 2ACF
+csube 2AD1
+csup 2AD0
+csupe 2AD2
+ctdot 22EF
+cudarrl 2938
+cudarrr 2935
+cuepr 22DE
+cuesc 22DF
+cularr 21B6
+cularrp 293D
+cup 222A
+Cup 22D3
+cupbrcap 2A48
+cupcap 2A46
+CupCap 224D
+cupcup 2A4A
+cupdot 228D
+cupor 2A45
+cups 222A  FE00
+curarr 21B7
+curarrm 293C
+curlyeqprec 22DE
+curlyeqsucc 22DF
+curlyvee 22CE
+curlywedge 22CF
+curren 00A4
+curvearrowleft 21B6
+curvearrowright 21B7
+cuvee 22CE
+cuwed 22CF
+cwconint 2232
+cwint 2231
+cylcty 232D
+dagger 2020
+Dagger 2021
+daleth 2138
+darr 2193
+dArr 21D3
+Darr 21A1
+dash 2010
+dashv 22A3
+Dashv 2AE4
+dbkarow 290F
+dblac 02DD
+dcaron 010F
+Dcaron 010E
+dcy 0434
+Dcy 0414
+dd 2146
+DD 2145
+ddaggerUB Dagger
+ddarr 21CA
+DDotrahd 2911
+ddotseq 2A77
+deg 00B0
+Del 2207
+delta 03B4
+Delta 0394
+demptyv 29B1
+dfisht 297F
+dfr 1D521
+Dfr 1D507
+dgr 03B4
+Dgr 0394
+dHar 2965
+dharl 21C3
+dharr 21C2
+DiacriticalAcute 00B4
+DiacriticalDot 02D9
+DiacriticalDoubleAcute 02DD
+DiacriticalGrave 0060
+DiacriticalTilde 02DC
+diam 22C4
+diamond 22C4
+Diamond 22C4
+diamondsuitUB diams
+diams 2666
+die 00A8
+DifferentialD 2146
+digamma 03DD
+disin 22F2
+divUM divide
+divide 00F7
+divideontimes 22C7
+divonx 22C7
+djcy 0452
+DJcy 0402
+dlcorn 231E
+dlcrop 230D
+dollar 0024
+dopf 1D555
+Dopf 1D53B
+dot 02D9
+Dot 00A8
+DotDot 20DC
+doteq 2250
+doteqdot 2251
+DotEqual 2250
+dotminus 2238
+dotplus 2214
+dotsquare 22A1
+doublebarwedge 2306
+DoubleContourIntegral 222F
+DoubleDot 00A8
+DoubleDownArrow 21D3
+DoubleLeftArrow 21D0
+DoubleLeftRightArrow 21D4
+DoubleLeftTee 2AE4
+DoubleLongLeftArrow 27F8
+DoubleLongLeftRightArrow 27FA
+DoubleLongRightArrow 27F9
+DoubleRightArrow 21D2
+DoubleRightTee 22A8
+DoubleUpArrow 21D1
+DoubleUpDownArrow 21D5
+DoubleVerticalBar 2225
+downarrowUM darr
+Downarrow 21D3
+DownArrowUM darr
+DownArrowBar 2913
+DownArrowUpArrow 21F5
+DownBreve 0311
+downdownarrows 21CA
+downharpoonleft 21C3
+downharpoonright 21C2
+DownLeftRightVector 2950
+DownLeftTeeVector 295E
+DownLeftVector 21BD
+DownLeftVectorBar 2956
+DownRightTeeVector 295F
+DownRightVector 21C1
+DownRightVectorBar 2957
+DownTee 22A4
+DownTeeArrow 21A7
+drbkarow 2910
+drcorn 231F
+drcrop 230C
+dscr 1D4B9
+Dscr 1D49F
+dscy 0455
+DScy 0405
+dsol 29F6
+dstrok 0111
+Dstrok 0110
+dtdot 22F1
+dtri 25BF
+dtrif 25BE
+duarr 21F5
+duhar 296F
+dwangle 29A6
+dzcy 045F
+DZcy 040F
+dzigrarr 27FF
+eacgr 03AD
+Eacgr 0388
+eacute 00E9
+Eacute 00C9
+easter 2A6E
+ecaron 011B
+Ecaron 011A
+ecir 2256
+ecirc 00EA
+Ecirc 00CA
+ecolon 2255
+ecy 044D
+Ecy 042D
+eDDot 2A77
+edot 0117
+eDot 2251
+Edot 0116
+ee 2147
+eeacgr 03AE
+EEacgr 0389
+eegr 03B7
+EEgr 0397
+efDot 2252
+efr 1D522
+Efr 1D508
+eg 2A9A
+egr 03B5
+Egr 0395
+egrave 00E8
+Egrave 00C8
+egs 2A96
+egsdot 2A98
+el 2A99
+Element 2208
+elinters 23E7
+ell 2113
+els 2A95
+elsdot 2A97
+emacr 0113
+Emacr 0112
+empty 2205
+emptyset 2205
+EmptySmallSquare 25FB
+emptyv 2205
+EmptyVerySmallSquare 25AB
+emsp 2003
+emsp13 2004
+emsp14 2005
+eng 014B
+ENG 014A
+ensp 2002
+eogon 0119
+Eogon 0118
+eopf 1D556
+Eopf 1D53C
+epar 22D5
+eparsl 29E3
+eplus 2A71
+epsi 03B5
+epsilon 03B5
+Epsilon 0395
+epsiv 03F5
+eqcirc 2256
+eqcolon 2255
+eqsim 2242
+eqslantgtr 2A96
+eqslantless 2A95
+Equal 2A75
+equals 003D
+EqualTilde 2242
+equest 225F
+Equilibrium 21CC
+equiv 2261
+equivDD 2A78
+eqvparsl 29E5
+erarr 2971
+erDot 2253
+escr 212F
+Escr 2130
+esdot 2250
+esim 2242
+Esim 2A73
+eta 03B7
+Eta 0397
+eth 00F0
+ETH 00D0
+euml 00EB
+Euml 00CB
+euro 20AC
+excl 0021
+exist 2203
+Exists 2203
+expectation 2130
+exponentiale 2147
+ExponentialE 2147
+fallingdotseq 2252
+fcy 0444
+Fcy 0424
+female 2640
+ffilig FB03
+fflig FB00
+ffllig FB04
+ffr 1D523
+Ffr 1D509
+filig FB01
+FilledSmallSquare 25FC
+FilledVerySmallSquare 25AA
+fjlig 0066  006A
+flat 266D
+fllig FB02
+fltns 25B1
+fnof 0192
+fopf 1D557
+Fopf 1D53D
+forall 2200
+ForAll 2200
+fork 22D4
+forkv 2AD9
+Fouriertrf 2131
+fpartint 2A0D
+frac12 00BD
+frac13 2153
+frac14 00BC
+frac15 2155
+frac16 2159
+frac18 215B
+frac23 2154
+frac25 2156
+frac34 00BE
+frac35 2157
+frac38 215C
+frac45 2158
+frac56 215A
+frac58 215D
+frac78 215E
+frasl 2044
+frown 2322
+fscr 1D4BB
+Fscr 2131
+gacute 01F5
+gamma 03B3
+Gamma 0393
+gammad 03DD
+Gammad 03DC
+gap 2A86
+gbreve 011F
+Gbreve 011E
+Gcedil 0122
+gcirc 011D
+Gcirc 011C
+gcy 0433
+Gcy 0413
+gdot 0121
+Gdot 0120
+ge 2265
+gE 2267
+gel 22DB
+gEl 2A8C
+geq 2265
+geqq 2267
+geqslant 2A7E
+ges 2A7E
+gescc 2AA9
+gesdot 2A80
+gesdoto 2A82
+gesdotol 2A84
+gesl 22DB  FE00
+gesles 2A94
+gfr 1D524
+Gfr 1D50A
+gg 226B
+Gg 22D9
+ggg 22D9
+ggr 03B3
+Ggr 0393
+gimel 2137
+gjcy 0453
+GJcy 0403
+gl 2277
+gla 2AA5
+glE 2A92
+glj 2AA4
+gnap 2A8A
+gnapprox 2A8A
+gne 2A88
+gnE 2269
+gneq 2A88
+gneqq 2269
+gnsim 22E7
+gopf 1D558
+Gopf 1D53E
+grave 0060
+GreaterEqual 2265
+GreaterEqualLess 22DB
+GreaterFullEqual 2267
+GreaterGreater 2AA2
+GreaterLess 2277
+GreaterSlantEqual 2A7E
+GreaterTilde 2273
+gscr 210A
+Gscr 1D4A2
+gsim 2273
+gsime 2A8E
+gsiml 2A90
+gt 003E
+Gt 226B
+GT 003E
+gtcc 2AA7
+gtcir 2A7A
+gtdot 22D7
+gtlPar 2995
+gtquest 2A7C
+gtrapprox 2A86
+gtrarr 2978
+gtrdot 22D7
+gtreqless 22DB
+gtreqqless 2A8C
+gtrless 2277
+gtrsim 2273
+gvertneqq 2269  FE00
+gvnE 2269  FE00
+Hacek 02C7
+hairsp 200A
+half 00BD
+hamilt 210B
+hardcy 044A
+HARDcy 042A
+harr 2194
+hArr 21D4
+harrcir 2948
+harrw 21AD
+Hat 005E
+hbar 210F
+hcirc 0125
+Hcirc 0124
+hearts 2665
+heartsuitUB hearts
+hellip 2026
+hercon 22B9
+hfr 1D525
+Hfr 210C
+HilbertSpace 210B
+hksearow 2925
+hkswarow 2926
+hoarr 21FF
+homtht 223B
+hookleftarrow 21A9
+hookrightarrow 21AA
+hopf 1D559
+Hopf 210D
+horbar 2015
+HorizontalLine 2500
+hscr 1D4BD
+Hscr 210B
+hslash 210F
+hstrok 0127
+Hstrok 0126
+HumpDownHump 224E
+HumpEqual 224F
+hybull 2043
+hyphen 2010
+iacgr 03AF
+Iacgr 038A
+iacute 00ED
+Iacute 00CD
+ic 2063
+icirc 00EE
+Icirc 00CE
+icy 0438
+Icy 0418
+idiagr 0390
+idigr 03CA
+Idigr 03AA
+Idot 0130
+iecy 0435
+IEcy 0415
+iexcl 00A1
+iff 21D4
+ifr 1D526
+Ifr 2111
+igr 03B9
+Igr 0399
+igrave 00EC
+Igrave 00CC
+ii 2148
+iiiint 2A0C
+iiint 222D
+iinfin 29DC
+iiota 2129
+ijlig 0133
+IJlig 0132
+Im 2111
+imacr 012B
+Imacr 012A
+image 2111
+ImaginaryI 2148
+imagline 2110
+imagpart 2111
+imath 0131
+imof 22B7
+imped 01B5
+Implies 21D2
+in 2208
+incare 2105
+infin 221E
+infintie 29DD
+inodot 0131
+int 222B
+Int 222C
+intcal 22BA
+integers 2124
+Integral 222B
+intercal 22BA
+Intersection 22C2
+intlarhk 2A17
+intprod 2A3C
+InvisibleComma 2063
+InvisibleTimes 2062
+iocy 0451
+IOcy 0401
+iogon 012F
+Iogon 012E
+iopf 1D55A
+Iopf 1D540
+iota 03B9
+Iota 0399
+iprod 2A3C
+iquest 00BF
+iscr 1D4BE
+Iscr 2110
+isin 2208
+isindot 22F5
+isinE 22F9
+isins 22F4
+isinsv 22F3
+isinv 2208
+it 2062
+itilde 0129
+Itilde 0128
+iukcyUkrainian
+IukcyUkrainian
+iuml 00EF
+Iuml 00CF
+jcirc 0135
+Jcirc 0134
+jcy 0439
+Jcy 0419
+jfr 1D527
+Jfr 1D50D
+jmath 0237
+jopf 1D55B
+Jopf 1D541
+jscr 1D4BF
+Jscr 1D4A5
+jsercy 0458
+Jsercy 0408
+jukcyUkrainian
+JukcyUkrainian
+kappa 03BA
+Kappa 039A
+kappav 03F0
+kcedil 0137
+Kcedil 0136
+kcy 043A
+Kcy 041A
+kfr 1D528
+Kfr 1D50E
+kgr 03BA
+Kgr 039A
+kgreen 0138
+khcy 0445
+KHcy 0425
+khgr 03C7
+KHgr 03A7
+kjcy 045C
+KJcy 040C
+kopf 1D55C
+Kopf 1D542
+kscr 1D4C0
+Kscr 1D4A6
+lAarr 21DA
+lacute 013A
+Lacute 0139
+laemptyv 29B4
+lagran 2112
+lambda 03BB
+Lambda 039B
+lang 27E8
+Lang 27EA
+langd 2991
+langle 27E8
+lap 2A85
+Laplacetrf 2112
+laquo 00AB
+larr 2190
+lArr 21D0
+Larr 219E
+larrb 21E4
+larrbfs 291F
+larrfs 291D
+larrhk 21A9
+larrlp 21AB
+larrpl 2939
+larrsim 2973
+larrtl 21A2
+lat 2AAB
+latail 2919
+lAtail 291B
+late 2AAD
+lates 2AAD  FE00
+lbarr 290C
+lBarr 290E
+lbbrk 2772
+lbraceUM lcub
+lbrackUM lsqb
+lbrke 298B
+lbrksld 298F
+lbrkslu 298D
+lcaron 013E
+Lcaron 013D
+lcedil 013C
+Lcedil 013B
+lceil 2308
+lcub 007B
+lcy 043B
+Lcy 041B
+ldca 2936
+ldquo 201C
+ldquor 201E
+ldrdhar 2967
+ldrushar 294B
+ldsh 21B2
+le 2264
+lE 2266
+LeftAngleBracket 27E8
+leftarrowUM larr
+Leftarrow 21D0
+LeftArrowUM larr
+LeftArrowBar 21E4
+LeftArrowRightArrow 21C6
+leftarrowtail 21A2
+LeftCeiling 2308
+LeftDoubleBracket 27E6
+LeftDownTeeVector 2961
+LeftDownVector 21C3
+LeftDownVectorBar 2959
+LeftFloor 230A
+leftharpoondown 21BD
+leftharpoonup 21BC
+leftleftarrows 21C7
+leftrightarrow 2194
+Leftrightarrow 21D4
+LeftRightArrow 2194
+leftrightarrows 21C6
+leftrightharpoons 21CB
+leftrightsquigarrow 21AD
+LeftRightVector 294E
+LeftTee 22A3
+LeftTeeArrow 21A4
+LeftTeeVector 295A
+leftthreetimes 22CB
+LeftTriangle 22B2
+LeftTriangleBar 29CF
+LeftTriangleEqual 22B4
+LeftUpDownVector 2951
+LeftUpTeeVector 2960
+LeftUpVector 21BF
+LeftUpVectorBar 2958
+LeftVector 21BC
+LeftVectorBar 2952
+leg 22DA
+lEg 2A8B
+leq 2264
+leqq 2266
+leqslant 2A7D
+les 2A7D
+lescc 2AA8
+lesdot 2A7F
+lesdoto 2A81
+lesdotor 2A83
+lesg 22DA  FE00
+lesges 2A93
+lessapprox 2A85
+lessdot 22D6
+lesseqgtr 22DA
+lesseqqgtr 2A8B
+LessEqualGreater 22DA
+LessFullEqual 2266
+LessGreater 2276
+lessgtr 2276
+LessLess 2AA1
+lesssim 2272
+LessSlantEqual 2A7D
+LessTilde 2272
+lfisht 297C
+lfloor 230A
+lfr 1D529
+Lfr 1D50F
+lg 2276
+lgE 2A91
+lgr 03BB
+Lgr 039B
+lHar 2962
+lhard 21BD
+lharu 21BC
+lharul 296A
+lhblk 2584
+ljcy 0459
+LJcy 0409
+ll 226A
+Ll 22D8
+llarr 21C7
+llcorner 231E
+Lleftarrow 21DA
+llhard 296B
+lltri 25FA
+lmidot 0140
+Lmidot 013F
+lmoust 23B0
+lmoustache 23B0
+lnap 2A89
+lnapprox 2A89
+lne 2A87
+lnE 2268
+lneq 2A87
+lneqq 2268
+lnsim 22E6
+loang 27EC
+loarr 21FD
+lobrk 27E6
+longleftarrow 27F5
+Longleftarrow 27F8
+LongLeftArrow 27F5
+longleftrightarrow 27F7
+Longleftrightarrow 27FA
+LongLeftRightArrow 27F7
+longmapsto 27FC
+longrightarrow 27F6
+Longrightarrow 27F9
+LongRightArrow 27F6
+looparrowleft 21AB
+looparrowright 21AC
+lopar 2985
+lopf 1D55D
+Lopf 1D543
+loplus 2A2D
+lotimes 2A34
+lowast 2217
+lowbar 005F
+LowerLeftArrow 2199
+LowerRightArrow 2198
+loz 25CA
+lozengeUB loz
+lozf 29EB
+lpar 0028
+lparlt 2993
+lrarr 21C6
+lrcorner 231F
+lrhar 21CB
+lrhard 296D
+lrm 200E
+lrtri 22BF
+lsaquo 2039
+lscr 1D4C1
+Lscr 2112
+lsh 21B0
+Lsh 21B0
+lsim 2272
+lsime 2A8D
+lsimg 2A8F
+lsqb 005B
+lsquo 2018
+lsquor 201A
+lstrok 0142
+Lstrok 0141
+lt 003C
+Lt 226A
+LT 003C
+ltcc 2AA6
+ltcir 2A79
+ltdot 22D6
+lthree 22CB
+ltimes 22C9
+ltlarr 2976
+ltquest 2A7B
+ltri 25C3
+ltrie 22B4
+ltrif 25C2
+ltrPar 2996
+lurdshar 294A
+luruhar 2966
+lvertneqq 2268  FE00
+lvnE 2268  FE00
+macr 00AF
+male 2642
+malt 2720
+malteseUB malt
+map 21A6
+Map 2905
+mapsto 21A6
+mapstodown 21A7
+mapstoleft 21A4
+mapstoup 21A5
+marker 25AE
+mcomma 2A29
+mcy 043C
+Mcy 041C
+mdash 2014
+mDDot 223A
+measuredangle 2221
+MediumSpace 205F
+Mellintrf 2133
+mfr 1D52A
+Mfr 1D510
+mgr 03BC
+Mgr 039C
+mho 2127
+micro 00B5
+mid 2223
+midast 002A
+midcir 2AF0
+middot 00B7
+minus 2212
+minusb 229F
+minusd 2238
+minusdu 2A2A
+MinusPlus 2213
+mlcp 2ADB
+mldr 2026
+mnplus 2213
+models 22A7
+mopf 1D55E
+Mopf 1D544
+mp 2213
+mscr 1D4C2
+Mscr 2133
+mstpos 223E
+mu 03BC
+Mu 039C
+multimap 22B8
+mumap 22B8
+nabla 2207
+nacute 0144
+Nacute 0143
+nang 2220  20D2
+nap 2249
+napE 2A70  0338
+napid 224B  0338
+napos 0149
+napprox 2249
+natur 266E
+naturalUB natur
+naturals 2115
+nbsp 00A0
+nbump 224E  0338
+nbumpe 224F  0338
+ncap 2A43
+ncaron 0148
+Ncaron 0147
+ncedil 0146
+Ncedil 0145
+ncong 2247
+ncongdot 2A6D  0338
+ncup 2A42
+ncy 043D
+Ncy 041D
+ndash 2013
+ne 2260
+nearhk 2924
+nearr 2197
+neArr 21D7
+nearrow 2197
+nedot 2250  0338
+NegativeMediumSpace 200B
+NegativeThickSpace 200B
+NegativeThinSpace 200B
+NegativeVeryThinSpace 200B
+nequiv 2262
+nesear 2928
+nesim 2242  0338
+NestedGreaterGreater 226B
+NestedLessLess 226A
+NewLine 000A
+nexist 2204
+nexists 2204
+nfr 1D52B
+Nfr 1D511
+nge 2271
+ngE 2267  0338
+ngeq 2271
+ngeqq 2267  0338
+ngeqslant 2A7E  0338
+nges 2A7E  0338
+nGg 22D9  0338
+ngr 03BD
+Ngr 039D
+ngsim 2275
+ngt 226F
+nGt 226B  20D2
+ngtr 226F
+nGtv 226B  0338
+nharr 21AE
+nhArr 21CE
+nhpar 2AF2
+ni 220B
+nis 22FC
+nisd 22FA
+niv 220B
+njcy 045A
+NJcy 040A
+nlarr 219A
+nlArr 21CD
+nldr 2025
+nle 2270
+nlE 2266  0338
+nleftarrow 219A
+nLeftarrow 21CD
+nleftrightarrow 21AE
+nLeftrightarrow 21CE
+nleq 2270
+nleqq 2266  0338
+nleqslant 2A7D  0338
+nles 2A7D  0338
+nless 226E
+nLl 22D8  0338
+nlsim 2274
+nlt 226E
+nLt 226A  20D2
+nltri 22EA
+nltrie 22EC
+nLtv 226A  0338
+nmid 2224
+NoBreak 2060
+NonBreakingSpaceUM nbsp
+nopf 1D55F
+Nopf 2115
+not 00AC
+Not 2AEC
+NotCongruent 2262
+NotCupCap 226D
+NotDoubleVerticalBar 2226
+NotElement 2209
+NotEqual 2260
+NotEqualTilde 2242  0338
+NotExists 2204
+NotGreater 226F
+NotGreaterEqual 2271
+NotGreaterFullEqual 2267  0338
+NotGreaterGreater 226B  0338
+NotGreaterLess 2279
+NotGreaterSlantEqual 2A7E  0338
+NotGreaterTilde 2275
+NotHumpDownHump 224E  0338
+NotHumpEqual 224F  0338
+notin 2209
+notindot 22F5  0338
+notinE 22F9  0338
+notinva 2209
+notinvb 22F7
+notinvc 22F6
+NotLeftTriangle 22EA
+NotLeftTriangleBar 29CF  0338
+NotLeftTriangleEqual 22EC
+NotLess 226E
+NotLessEqual 2270
+NotLessGreater 2278
+NotLessLess 226A  0338
+NotLessSlantEqual 2A7D  0338
+NotLessTilde 2274
+NotNestedGreaterGreater 2AA2  0338
+NotNestedLessLess 2AA1  0338
+notni 220C
+notniva 220C
+notnivb 22FE
+notnivc 22FD
+NotPrecedes 2280
+NotPrecedesEqual 2AAF  0338
+NotPrecedesSlantEqual 22E0
+NotReverseElement 220C
+NotRightTriangle 22EB
+NotRightTriangleBar 29D0  0338
+NotRightTriangleEqual 22ED
+NotSquareSubset 228F  0338
+NotSquareSubsetEqual 22E2
+NotSquareSuperset 2290  0338
+NotSquareSupersetEqual 22E3
+NotSubset 2282  20D2
+NotSubsetEqual 2288
+NotSucceeds 2281
+NotSucceedsEqual 2AB0  0338
+NotSucceedsSlantEqual 22E1
+NotSucceedsTilde 227F  0338
+NotSuperset 2283  20D2
+NotSupersetEqual 2289
+NotTilde 2241
+NotTildeEqual 2244
+NotTildeFullEqual 2247
+NotTildeTilde 2249
+NotVerticalBar 2224
+npar 2226
+nparallel 2226
+nparsl 2AFD  20E5
+npart 2202  0338
+npolint 2A14
+npr 2280
+nprcue 22E0
+npre 2AAF  0338
+nprec 2280
+npreceq 2AAF  0338
+nrarr 219B
+nrArr 21CF
+nrarrc 2933  0338
+nrarrw 219D  0338
+nrightarrow 219B
+nRightarrow 21CF
+nrtri 22EB
+nrtrie 22ED
+nsc 2281
+nsccue 22E1
+nsce 2AB0  0338
+nscr 1D4C3
+Nscr 1D4A9
+nshortmid 2224
+nshortparallel 2226
+nsim 2241
+nsime 2244
+nsimeq 2244
+nsmid 2224
+nspar 2226
+nsqsube 22E2
+nsqsupe 22E3
+nsub 2284
+nsube 2288
+nsubE 2AC5  0338
+nsubset 2282  20D2
+nsubseteq 2288
+nsubseteqq 2AC5  0338
+nsucc 2281
+nsucceq 2AB0  0338
+nsup 2285
+nsupe 2289
+nsupE 2AC6  0338
+nsupset 2283  20D2
+nsupseteq 2289
+nsupseteqq 2AC6  0338
+ntgl 2279
+ntilde 00F1
+Ntilde 00D1
+ntlg 2278
+ntriangleleft 22EA
+ntrianglelefteq 22EC
+ntriangleright 22EB
+ntrianglerighteq 22ED
+nu 03BD
+Nu 039D
+num 0023
+numero 2116
+numsp 2007
+nvap 224D  20D2
+nvdash 22AC
+nvDash 22AD
+nVdash 22AE
+nVDash 22AF
+nvge 2265  20D2
+nvgt 003E  20D2
+nvHarr 2904
+nvinfin 29DE
+nvlArr 2902
+nvle 2264  20D2
+nvlt 003C  20D2
+nvltrie 22B4  20D2
+nvrArr 2903
+nvrtrie 22B5  20D2
+nvsim 223C  20D2
+nwarhk 2923
+nwarr 2196
+nwArr 21D6
+nwarrow 2196
+nwnear 2927
+oacgr 03CC
+Oacgr 038C
+oacute 00F3
+Oacute 00D3
+oast 229B
+ocir 229A
+ocirc 00F4
+Ocirc 00D4
+ocy 043E
+Ocy 041E
+odash 229D
+odblac 0151
+Odblac 0150
+odiv 2A38
+odot 2299
+odsold 29BC
+oelig 0153
+OElig 0152
+ofcir 29BF
+ofr 1D52C
+Ofr 1D512
+ogon 02DB
+ogr 03BF
+Ogr 039F
+ograve 00F2
+Ograve 00D2
+ogt 29C1
+ohacgr 03CE
+OHacgr 038F
+ohbar 29B5
+ohgr 03C9
+OHgr 03A9
+ohm 03A9
+oint 222E
+olarr 21BA
+olcir 29BE
+olcross 29BB
+oline 203E
+olt 29C0
+omacr 014D
+Omacr 014C
+omega 03C9
+Omega 03A9
+omicron 03BF
+Omicron 039F
+omid 29B6
+ominus 2296
+oopf 1D560
+Oopf 1D546
+opar 29B7
+OpenCurlyDoubleQuoteUM ldquo
+OpenCurlyQuoteUM lsquo
+operp 29B9
+oplus 2295
+or 2228
+Or 2A54
+orarr 21BB
+ord 2A5D
+order 2134
+orderof 2134
+ordf 00AA
+ordm 00BA
+origof 22B6
+oror 2A56
+orslope 2A57
+orv 2A5B
+oS 24C8
+oscr 2134
+Oscr 1D4AA
+oslash 00F8
+Oslash 00D8
+osol 2298
+otilde 00F5
+Otilde 00D5
+otimes 2297
+Otimes 2A37
+otimesas 2A36
+ouml 00F6
+Ouml 00D6
+ovbar 233D
+OverBar 203E
+OverBrace 23DE
+OverBracket 23B4
+OverParenthesis 23DC
+par 2225
+para 00B6
+parallel 2225
+parsim 2AF3
+parsl 2AFD
+part 2202
+PartialD 2202
+pcy 043F
+Pcy 041F
+percnt 0025
+period 002E
+permil 2030
+perp 22A5
+pertenk 2031
+pfr 1D52D
+Pfr 1D513
+pgr 03C0
+Pgr 03A0
+phgr 03C6
+PHgr 03A6
+phi 03C6
+Phi 03A6
+phiv 03D5
+phmmat 2133
+phone 260E
+pi 03C0
+Pi 03A0
+pitchfork 22D4
+piv 03D6
+planck 210F
+planckh 210E
+plankv 210F
+plus 002B
+plusacir 2A23
+plusb 229E
+pluscir 2A22
+plusdo 2214
+plusdu 2A25
+pluse 2A72
+PlusMinusUM plusmn
+plusmn 00B1
+plussim 2A26
+plustwo 2A27
+pmUM plusmn
+Poincareplane 210C
+pointint 2A15
+popf 1D561
+Popf 2119
+pound 00A3
+pr 227A
+Pr 2ABB
+prap 2AB7
+prcue 227C
+pre 2AAF
+prE 2AB3
+prec 227A
+precapprox 2AB7
+preccurlyeq 227C
+Precedes 227A
+PrecedesEqual 2AAF
+PrecedesSlantEqual 227C
+PrecedesTilde 227E
+preceq 2AAF
+precnapprox 2AB9
+precneqq 2AB5
+precnsim 22E8
+precsim 227E
+prime 2032
+Prime 2033
+primes 2119
+prnap 2AB9
+prnE 2AB5
+prnsim 22E8
+prod 220F
+Product 220F
+profalar 232E
+profline 2312
+profsurf 2313
+prop 221D
+Proportion 2237
+Proportional 221D
+propto 221D
+prsim 227E
+prurel 22B0
+pscr 1D4C5
+Pscr 1D4AB
+psgr 03C8
+PSgr 03A8
+psi 03C8
+Psi 03A8
+puncsp 2008
+qfr 1D52E
+Qfr 1D514
+qint 2A0C
+qopf 1D562
+Qopf 211A
+qprime 2057
+qscr 1D4C6
+Qscr 1D4AC
+quaternions 210D
+quatint 2A16
+quest 003F
+questeq 225F
+quot 0022
+QUOT 0022
+rAarr 21DB
+race 223D  0331
+racute 0155
+Racute 0154
+radic 221A
+raemptyv 29B3
+rang 27E9
+Rang 27EB
+rangd 2992
+range 29A5
+rangle 27E9
+raquo 00BB
+rarr 2192
+rArr 21D2
+Rarr 21A0
+rarrap 2975
+rarrb 21E5
+rarrbfs 2920
+rarrc 2933
+rarrfs 291E
+rarrhk 21AA
+rarrlp 21AC
+rarrpl 2945
+rarrsim 2974
+rarrtl 21A3
+Rarrtl 2916
+rarrw 219D
+ratail 291A
+rAtail 291C
+ratio 2236
+rationals 211A
+rbarr 290D
+rBarr 290F
+RBarr 2910
+rbbrk 2773
+rbraceUM rcub
+rbrackUM rsqb
+rbrke 298C
+rbrksld 298E
+rbrkslu 2990
+rcaron 0159
+Rcaron 0158
+rcedil 0157
+Rcedil 0156
+rceil 2309
+rcub 007D
+rcy 0440
+Rcy 0420
+rdca 2937
+rdldhar 2969
+rdquo 201D
+rdquor 201D
+rdsh 21B3
+Re 211C
+real 211C
+realine 211B
+realpart 211C
+reals 211D
+rect 25AD
+reg 00AE
+REG 00AE
+ReverseElement 220B
+ReverseEquilibrium 21CB
+ReverseUpEquilibrium 296F
+rfisht 297D
+rfloor 230B
+rfr 1D52F
+Rfr 211C
+rgr 03C1
+Rgr 03A1
+rHar 2964
+rhard 21C1
+rharu 21C0
+rharul 296C
+rho 03C1
+Rho 03A1
+rhov 03F1
+RightAngleBracket 27E9
+rightarrowUM rarr
+Rightarrow 21D2
+RightArrowUM rarr
+RightArrowBar 21E5
+RightArrowLeftArrow 21C4
+rightarrowtail 21A3
+RightCeiling 2309
+RightDoubleBracket 27E7
+RightDownTeeVector 295D
+RightDownVector 21C2
+RightDownVectorBar 2955
+RightFloor 230B
+rightharpoondown 21C1
+rightharpoonup 21C0
+rightleftarrows 21C4
+rightleftharpoons 21CC
+rightrightarrows 21C9
+rightsquigarrow 219D
+RightTee 22A2
+RightTeeArrow 21A6
+RightTeeVector 295B
+rightthreetimes 22CC
+RightTriangle 22B3
+RightTriangleBar 29D0
+RightTriangleEqual 22B5
+RightUpDownVector 294F
+RightUpTeeVector 295C
+RightUpVector 21BE
+RightUpVectorBar 2954
+RightVector 21C0
+RightVectorBar 2953
+ring 02DA
+risingdotseq 2253
+rlarr 21C4
+rlhar 21CC
+rlm 200F
+rmoust 23B1
+rmoustache 23B1
+rnmid 2AEE
+roang 27ED
+roarr 21FE
+robrk 27E7
+ropar 2986
+ropf 1D563
+Ropf 211D
+roplus 2A2E
+rotimes 2A35
+RoundImplies 2970
+rpar 0029
+rpargt 2994
+rppolint 2A12
+rrarr 21C9
+Rrightarrow 21DB
+rsaquo 203A
+rscr 1D4C7
+Rscr 211B
+rsh 21B1
+Rsh 21B1
+rsqb 005D
+rsquo 2019
+rsquor 2019
+rthree 22CC
+rtimes 22CA
+rtri 25B9
+rtrie 22B5
+rtrif 25B8
+rtriltri 29CE
+RuleDelayed 29F4
+ruluhar 2968
+rx 211E
+sacute 015B
+Sacute 015A
+sbquo 201A
+sc 227B
+Sc 2ABC
+scap 2AB8
+scaron 0161
+Scaron 0160
+sccue 227D
+sce 2AB0
+scE 2AB4
+scedil 015F
+Scedil 015E
+scirc 015D
+Scirc 015C
+scnap 2ABA
+scnE 2AB6
+scnsim 22E9
+scpolint 2A13
+scsim 227F
+scy 0441
+Scy 0421
+sdot 22C5
+sdotb 22A1
+sdote 2A66
+searhk 2925
+searr 2198
+seArr 21D8
+searrow 2198
+sect 00A7
+semi 003B
+seswar 2929
+setminus 2216
+setmn 2216
+sext 2736
+sfgr 03C2
+sfr 1D530
+Sfr 1D516
+sfrown 2322
+sgr 03C3
+Sgr 03A3
+sharp 266F
+shchcy 0449
+SHCHcy 0429
+shcy 0448
+SHcy 0428
+ShortDownArrow 2193
+ShortLeftArrow 2190
+shortmid 2223
+shortparallel 2225
+ShortRightArrow 2192
+ShortUpArrow 2191
+shy 00AD
+sigma 03C3
+Sigma 03A3
+sigmaf 03C2
+sigmav 03C2
+sim 223C
+simdot 2A6A
+sime 2243
+simeq 2243
+simg 2A9E
+simgE 2AA0
+siml 2A9D
+simlE 2A9F
+simne 2246
+simplus 2A24
+simrarr 2972
+slarr 2190
+SmallCircle 2218
+smallsetminus 2216
+smashp 2A33
+smeparsl 29E4
+smid 2223
+smile 2323
+smt 2AAA
+smte 2AAC
+smtes 2AAC  FE00
+softcy 044C
+SOFTcy 042C
+sol 002F
+solb 29C4
+solbar 233F
+sopf 1D564
+Sopf 1D54A
+spades 2660
+spadesuitUB spades
+spar 2225
+sqcap 2293
+sqcaps 2293  FE00
+sqcup 2294
+sqcups 2294  FE00
+Sqrt 221A
+sqsub 228F
+sqsube 2291
+sqsubset 228F
+sqsubseteq 2291
+sqsup 2290
+sqsupe 2292
+sqsupset 2290
+sqsupseteq 2292
+squ 25A1
+square 25A1
+Square 25A1
+SquareIntersection 2293
+SquareSubset 228F
+SquareSubsetEqual 2291
+SquareSuperset 2290
+SquareSupersetEqual 2292
+SquareUnion 2294
+squarf 25AA
+squf 25AA
+srarr 2192
+sscr 1D4C8
+Sscr 1D4AE
+ssetmn 2216
+ssmile 2323
+sstarf 22C6
+star 2606
+Star 22C6
+starf 2605
+straightepsilon 03F5
+straightphi 03D5
+strns 00AF
+sub 2282
+Sub 22D0
+subdot 2ABD
+sube 2286
+subE 2AC5
+subedot 2AC3
+submult 2AC1
+subne 228A
+subnE 2ACB
+subplus 2ABF
+subrarr 2979
+subset 2282
+Subset 22D0
+subseteq 2286
+subseteqq 2AC5
+SubsetEqual 2286
+subsetneq 228A
+subsetneqq 2ACB
+subsim 2AC7
+subsub 2AD5
+subsup 2AD3
+succ 227B
+succapprox 2AB8
+succcurlyeq 227D
+Succeeds 227B
+SucceedsEqual 2AB0
+SucceedsSlantEqual 227D
+SucceedsTilde 227F
+succeq 2AB0
+succnapprox 2ABA
+succneqq 2AB6
+succnsim 22E9
+succsim 227F
+SuchThat 220B
+sum 2211
+Sum 2211
+sung 266A
+sup 2283
+Sup 22D1
+sup1 00B9
+sup2 00B2
+sup3 00B3
+supdot 2ABE
+supdsub 2AD8
+supe 2287
+supE 2AC6
+supedot 2AC4
+Superset 2283
+SupersetEqual 2287
+suphsol 27C9
+suphsub 2AD7
+suplarr 297B
+supmult 2AC2
+supne 228B
+supnE 2ACC
+supplus 2AC0
+supset 2283
+Supset 22D1
+supseteq 2287
+supseteqq 2AC6
+supsetneq 228B
+supsetneqq 2ACC
+supsim 2AC8
+supsub 2AD4
+supsup 2AD6
+swarhk 2926
+swarr 2199
+swArr 21D9
+swarrow 2199
+swnwar 292A
+szlig 00DF
+Tab 0009
+target 2316
+tau 03C4
+Tau 03A4
+tbrk 23B4
+tcaron 0165
+Tcaron 0164
+tcedil 0163
+Tcedil 0162
+tcy 0442
+Tcy 0422
+tdot 20DB
+telrec 2315
+tfr 1D531
+Tfr 1D517
+tgr 03C4
+Tgr 03A4
+there4 2234
+therefore 2234
+Therefore 2234
+theta 03B8
+Theta 0398
+thetasym 03D1
+thetav 03D1
+thgr 03B8
+THgr 0398
+thickapprox 2248
+thicksim 223C
+ThickSpace 205F  200A
+thinsp 2009
+ThinSpaceUB thinsp
+thkap 2248
+thksim 223C
+thorn 00FE
+THORN 00DE
+tilde 02DC
+Tilde 223C
+TildeEqual 2243
+TildeFullEqual 2245
+TildeTilde 2248
+times 00D7
+timesb 22A0
+timesbar 2A31
+timesd 2A30
+tint 222D
+toea 2928
+top 22A4
+topbot 2336
+topcir 2AF1
+topf 1D565
+Topf 1D54B
+topfork 2ADA
+tosa 2929
+tprime 2034
+trade 2122
+TRADE 2122
+triangleUB utri
+triangledownUB dtri
+triangleleftUB ltri
+trianglelefteq 22B4
+triangleq 225C
+trianglerightUB rtri
+trianglerighteq 22B5
+tridot 25EC
+trie 225C
+triminus 2A3A
+TripleDot 20DB
+triplus 2A39
+trisb 29CD
+tritime 2A3B
+trpezium 23E2
+tscr 1D4C9
+Tscr 1D4AF
+tscy 0446
+TScy 0426
+tshcy 045B
+TSHcy 040B
+tstrok 0167
+Tstrok 0166
+twixt 226C
+twoheadleftarrow 219E
+twoheadrightarrow 21A0
+uacgr 03CD
+UacgrUpsilon
+uacute 00FA
+UacuteU with acute
+uarr 2191
+uArr 21D1
+Uarr 219F
+Uarrocir 2949
+ubrcy 045E
+UbrcyU
+ubreve 016D
+UbreveU
+ucirc 00FB
+UcircU with circumflex
+ucy 0443
+UcyU
+udarr 21C5
+udblac 0171
+UdblacU
+udhar 296E
+udiagr 03B0
+udigr 03CB
+UdigrUpsilon
+ufisht 297E
+ufr 1D532
+UfrU
+ugr 03C5
+UgrUpsilon
+ugrave 00F9
+UgraveU with grave
+uHar 2963
+uharl 21BF
+uharr 21BE
+uhblk 2580
+ulcorn 231C
+ulcorner 231C
+ulcrop 230F
+ultri 25F8
+umacr 016B
+UmacrU
+uml 00A8
+UnderBar 005F
+UnderBrace 23DF
+UnderBracket 23B5
+UnderParenthesis 23DD
+Union 22C3
+UnionPlus 228E
+uogon 0173
+UogonU
+uopf 1D566
+UopfU
+uparrowUM uarr
+Uparrow 21D1
+UpArrowUM uarr
+UpArrowBar 2912
+UpArrowDownArrow 21C5
+updownarrow 2195
+Updownarrow 21D5
+UpDownArrow 2195
+UpEquilibrium 296E
+upharpoonleft 21BF
+upharpoonright 21BE
+uplus 228E
+UpperLeftArrow 2196
+UpperRightArrow 2197
+upsi 03C5
+UpsiUpsilon capital Upsilon
+upsih 03D2
+upsilon 03C5
+UpsilonUgr
+UpTee 22A5
+UpTeeArrow 21A5
+upuparrows 21C8
+urcorn 231D
+urcorner 231D
+urcrop 230E
+uring 016F
+UringU
+urtri 25F9
+uscr 1D4CA
+UscrU
+utdot 22F0
+utilde 0169
+UtildeU
+utri 25B5
+utrif 25B4
+uuarr 21C8
+uuml 00FC
+UumlU with diaeresis
+uwangle 29A7
+vangrt 299C
+varepsilon 03F5
+varkappa 03F0
+varnothing 2205
+varphi 03D5
+varpi 03D6
+varpropto 221D
+varr 2195
+vArrUpdownarrow A: up&down dbl arrow
+varrho 03F1
+varsigma 03C2
+varsubsetneq 228A  FE00
+varsubsetneqq 2ACB  FE00
+varsupsetneq 228B  FE00
+varsupsetneqq 2ACC  FE00
+vartheta 03D1
+vartriangleleft 22B2
+vartriangleright 22B3
+vBar 2AE8
+Vbar 2AEB
+vBarv 2AE9
+vcy 0432
+Vcy 0412
+vdash 22A2
+vDash 22A8
+Vdash 22A9
+VDash 22AB
+Vdashl 2AE6
+vee 2228
+Vee 22C1
+veebar 22BB
+veeeq 225A
+vellip 22EE
+verbar 007C
+Verbar 2016
+vertUM verbar
+Vert 2016
+VerticalBar 2223
+VerticalLineUM verbar
+VerticalSeparator 2758
+VerticalTilde 2240
+VeryThinSpaceUB hairsp
+vfr 1D533
+Vfr 1D519
+vltri 22B2
+vnsub 2282  20D2
+vnsup 2283  20D2
+vopf 1D567
+Vopf 1D54D
+vprop 221D
+vrtri 22B3
+vscr 1D4CB
+Vscr 1D4B1
+vsubne 228A  FE00
+vsubnE 2ACB  FE00
+vsupne 228B  FE00
+vsupnE 2ACC  FE00
+Vvdash 22AA
+vzigzag 299A
+wcirc 0175
+Wcirc 0174
+wedbar 2A5F
+wedge 2227
+Wedge 22C0
+wedgeq 2259
+weierp 2118
+wfr 1D534
+Wfr 1D51A
+wopf 1D568
+Wopf 1D54E
+wp 2118
+wr 2240
+wreath 2240
+wscr 1D4CC
+Wscr 1D4B2
+xcap 22C2
+xcirc 25EF
+xcup 22C3
+xdtri 25BD
+xfr 1D535
+Xfr 1D51B
+xgr 03BE
+Xgr 039E
+xharr 27F7
+xhArr 27FA
+xi 03BE
+Xi 039E
+xlarr 27F5
+xlArr 27F8
+xmap 27FC
+xnis 22FB
+xodot 2A00
+xopf 1D569
+Xopf 1D54F
+xoplus 2A01
+xotime 2A02
+xrarr 27F6
+xrArr 27F9
+xscr 1D4CD
+Xscr 1D4B3
+xsqcup 2A06
+xuplus 2A04
+xutri 25B3
+xvee 22C1
+xwedge 22C0
+yacute 00FD
+Yacute 00DD
+yacy 044F
+YAcy 042F
+ycirc 0177
+Ycirc 0176
+ycy 044B
+YcyU
+yen 00A5
+yfr 1D536
+Yfr 1D51C
+yicyUkrainian
+YIcyUkrainian
+yopf 1D56A
+Yopf 1D550
+yscr 1D4CE
+Yscr 1D4B4
+yucy 044E
+YUcyU
+yuml 00FF
+Yuml 0178
+zacute 017A
+Zacute 0179
+zcaron 017E
+Zcaron 017D
+zcy 0437
+Zcy 0417
+zdot 017C
+Zdot 017B
+zeetrf 2128
+ZeroWidthSpace 200B
+zeta 03B6
+Zeta 0396
+zfr 1D537
+Zfr 2128
+zgr 03B6
+Zgr 0396
+zhcy 0436
+ZHcy 0416
+zigrarr 21DD
+zopf 1D56B
+Zopf 2124
+zscr 1D4CF
+Zscr 1D4B5
+zwj 200D
+zwnj 200C
diff --git a/data/docx/[Content_Types].xml b/data/docx/[Content_Types].xml
--- a/data/docx/[Content_Types].xml
+++ b/data/docx/[Content_Types].xml
@@ -1,2 +1,2 @@
 <?xml version="1.0" encoding="UTF-8"?>
-<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="xml" ContentType="application/xml" /><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml" /><Override PartName="/word/webSettings.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.webSettings+xml" /><Override PartName="/word/numbering.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml" /><Override PartName="/word/settings.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml" /><Override PartName="/word/theme/theme1.xml" ContentType="application/vnd.openxmlformats-officedocument.theme+xml" /><Override PartName="/word/fontTable.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.fontTable+xml" /><Override PartName="/docProps/app.xml" ContentType="application/vnd.openxmlformats-officedocument.extended-properties+xml" /><Override PartName="/docProps/core.xml" ContentType="application/vnd.openxmlformats-package.core-properties+xml" /><Override PartName="/word/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml" /><Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml" /><Override PartName="/word/comments.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml" /><Override PartName="/word/footnotes.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml" /></Types>
+<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="xml" ContentType="application/xml" /><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml" /><Override PartName="/word/webSettings.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.webSettings+xml" /><Override PartName="/word/numbering.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml" /><Override PartName="/word/settings.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml" /><Override PartName="/word/theme/theme1.xml" ContentType="application/vnd.openxmlformats-officedocument.theme+xml" /><Override PartName="/word/fontTable.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.fontTable+xml" /><Override PartName="/docProps/app.xml" ContentType="application/vnd.openxmlformats-officedocument.extended-properties+xml" /><Override PartName="/docProps/core.xml" ContentType="application/vnd.openxmlformats-package.core-properties+xml" /><Override PartName="/docProps/custom.xml" ContentType="application/vnd.openxmlformats-officedocument.custom-properties+xml"/><Override PartName="/word/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml" /><Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml" /><Override PartName="/word/comments.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml" /><Override PartName="/word/footnotes.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml" /></Types>
diff --git a/data/docx/_rels/.rels b/data/docx/_rels/.rels
--- a/data/docx/_rels/.rels
+++ b/data/docx/_rels/.rels
@@ -1,2 +1,3 @@
 <?xml version="1.0" encoding="UTF-8"?>
-<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml" /><Relationship Id="rId4" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties" Target="docProps/app.xml" /><Relationship Id="rId3" Type="http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties" Target="docProps/core.xml" /></Relationships>
+<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml" /><Relationship Id="rId4" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties" Target="docProps/app.xml" /><Relationship Id="rId3" Type="http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties" Target="docProps/core.xml" /><Relationship Id="rId5" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/custom-properties" Target="docProps/custom.xml"/>
+</Relationships>
diff --git a/data/docx/docProps/custom.xml b/data/docx/docProps/custom.xml
new file mode 100644
--- /dev/null
+++ b/data/docx/docProps/custom.xml
@@ -0,0 +1,2 @@
+<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
+<Properties xmlns="http://schemas.openxmlformats.org/officeDocument/2006/custom-properties" xmlns:vt="http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes"></Properties>
diff --git a/data/docx/word/document.xml b/data/docx/word/document.xml
--- a/data/docx/word/document.xml
+++ b/data/docx/word/document.xml
@@ -15,9 +15,7 @@
         <w:pStyle w:val="Title" />
       </w:pPr>
       <w:r>
-        <w:t xml:space="preserve">
-Title
-</w:t>
+        <w:t xml:space="preserve">Title</w:t>
       </w:r>
     </w:p>
     <w:p>
@@ -25,9 +23,7 @@
         <w:pStyle w:val="Subtitle" />
       </w:pPr>
       <w:r>
-        <w:t xml:space="preserve">
-Subtitle
-</w:t>
+        <w:t xml:space="preserve">Subtitle</w:t>
       </w:r>
     </w:p>
     <w:p>
@@ -35,9 +31,7 @@
         <w:pStyle w:val="Author" />
       </w:pPr>
       <w:r>
-        <w:t xml:space="preserve">
-Author
-</w:t>
+        <w:t xml:space="preserve">Author</w:t>
       </w:r>
     </w:p>
     <w:p>
@@ -45,20 +39,15 @@
         <w:pStyle w:val="Date" />
       </w:pPr>
       <w:r>
-        <w:t xml:space="preserve">
-Date
-</w:t>
+        <w:t xml:space="preserve">Date</w:t>
       </w:r>
     </w:p>
     <w:p>
       <w:pPr>
-        <w:pStyle w:val="Compact" />
         <w:pStyle w:val="Abstract" />
       </w:pPr>
       <w:r>
-        <w:t xml:space="preserve">
-Abstract
-</w:t>
+        <w:t xml:space="preserve">Abstract</w:t>
       </w:r>
     </w:p>
     <w:p>
@@ -67,9 +56,7 @@
       </w:pPr>
       <w:bookmarkStart w:id="21" w:name="heading-1" />
       <w:r>
-        <w:t xml:space="preserve">
-Heading 1
-</w:t>
+        <w:t xml:space="preserve">Heading 1</w:t>
       </w:r>
       <w:bookmarkEnd w:id="21" />
     </w:p>
@@ -79,9 +66,7 @@
       </w:pPr>
       <w:bookmarkStart w:id="22" w:name="heading-2" />
       <w:r>
-        <w:t xml:space="preserve">
-Heading 2
-</w:t>
+        <w:t xml:space="preserve">Heading 2</w:t>
       </w:r>
       <w:bookmarkEnd w:id="22" />
     </w:p>
@@ -91,9 +76,7 @@
       </w:pPr>
       <w:bookmarkStart w:id="23" w:name="heading-3" />
       <w:r>
-        <w:t xml:space="preserve">
-Heading 3
-</w:t>
+        <w:t xml:space="preserve">Heading 3</w:t>
       </w:r>
       <w:bookmarkEnd w:id="23" />
     </w:p>
@@ -103,9 +86,7 @@
       </w:pPr>
       <w:bookmarkStart w:id="24" w:name="heading-4" />
       <w:r>
-        <w:t xml:space="preserve">
-Heading 4
-</w:t>
+        <w:t xml:space="preserve">Heading 4</w:t>
       </w:r>
       <w:bookmarkEnd w:id="24" />
     </w:p>
@@ -115,9 +96,7 @@
       </w:pPr>
       <w:bookmarkStart w:id="25" w:name="heading-5" />
       <w:r>
-        <w:t xml:space="preserve">
-Heading 5
-</w:t>
+        <w:t xml:space="preserve">Heading 5</w:t>
       </w:r>
       <w:bookmarkEnd w:id="25" />
     </w:p>
@@ -127,9 +106,7 @@
       </w:pPr>
       <w:bookmarkStart w:id="26" w:name="heading-6" />
       <w:r>
-        <w:t xml:space="preserve">
-Heading 6
-</w:t>
+        <w:t xml:space="preserve">Heading 6</w:t>
       </w:r>
       <w:bookmarkEnd w:id="26" />
     </w:p>
@@ -139,9 +116,7 @@
       </w:pPr>
       <w:bookmarkStart w:id="27" w:name="heading-7" />
       <w:r>
-        <w:t xml:space="preserve">
-Heading 7
-</w:t>
+        <w:t xml:space="preserve">Heading 7</w:t>
       </w:r>
       <w:bookmarkEnd w:id="27" />
     </w:p>
@@ -151,9 +126,7 @@
       </w:pPr>
       <w:bookmarkStart w:id="28" w:name="heading-8" />
       <w:r>
-        <w:t xml:space="preserve">
-Heading 8
-</w:t>
+        <w:t xml:space="preserve">Heading 8</w:t>
       </w:r>
       <w:bookmarkEnd w:id="28" />
     </w:p>
@@ -163,9 +136,7 @@
       </w:pPr>
       <w:bookmarkStart w:id="29" w:name="heading-9" />
       <w:r>
-        <w:t xml:space="preserve">
-Heading 9
-</w:t>
+        <w:t xml:space="preserve">Heading 9</w:t>
       </w:r>
       <w:bookmarkEnd w:id="29" />
     </w:p>
@@ -174,9 +145,7 @@
         <w:pStyle w:val="FirstParagraph" />
       </w:pPr>
       <w:r>
-        <w:t xml:space="preserve">
-First Paragraph.
-</w:t>
+        <w:t xml:space="preserve">First Paragraph.</w:t>
       </w:r>
     </w:p>
     <w:p>
@@ -184,57 +153,39 @@
         <w:pStyle w:val="BodyText" />
       </w:pPr>
       <w:r>
-        <w:t xml:space="preserve">
-Body Text. Body Text Char.
-</w:t>
+        <w:t xml:space="preserve">Body Text. Body Text Char.</w:t>
       </w:r>
       <w:r>
-        <w:t xml:space="preserve">
- 
-</w:t>
+        <w:t xml:space="preserve"> </w:t>
       </w:r>
       <w:r>
         <w:rPr>
           <w:rStyle w:val="VerbatimChar" />
         </w:rPr>
-        <w:t xml:space="preserve">
-Verbatim Char
-</w:t>
+        <w:t xml:space="preserve">Verbatim Char</w:t>
       </w:r>
       <w:r>
-        <w:t xml:space="preserve">
-.
-</w:t>
+        <w:t xml:space="preserve">.</w:t>
       </w:r>
       <w:r>
-        <w:t xml:space="preserve">
- 
-</w:t>
+        <w:t xml:space="preserve"> </w:t>
       </w:r>
       <w:hyperlink r:id="rId30">
         <w:r>
           <w:rPr>
             <w:rStyle w:val="Hyperlink" />
           </w:rPr>
-          <w:t xml:space="preserve">
-Hyperlink
-</w:t>
+          <w:t xml:space="preserve">Hyperlink</w:t>
         </w:r>
       </w:hyperlink>
       <w:r>
-        <w:t xml:space="preserve">
-.
-</w:t>
+        <w:t xml:space="preserve">.</w:t>
       </w:r>
       <w:r>
-        <w:t xml:space="preserve">
- 
-</w:t>
+        <w:t xml:space="preserve"> </w:t>
       </w:r>
       <w:r>
-        <w:t xml:space="preserve">
-Footnote.
-</w:t>
+        <w:t xml:space="preserve">Footnote.</w:t>
       </w:r>
       <w:r>
         <w:rPr>
@@ -248,9 +199,7 @@
         <w:pStyle w:val="BlockText" />
       </w:pPr>
       <w:r>
-        <w:t xml:space="preserve">
-Block Text.
-</w:t>
+        <w:t xml:space="preserve">Block Text.</w:t>
       </w:r>
     </w:p>
     <w:p>
@@ -258,22 +207,19 @@
         <w:pStyle w:val="TableCaption" />
       </w:pPr>
       <w:r>
-        <w:t xml:space="preserve">
-Table caption.
-</w:t>
+        <w:t xml:space="preserve">Table caption.</w:t>
       </w:r>
     </w:p>
     <w:tbl>
       <w:tblPr>
         <w:tblStyle w:val="Table" />
-        <w:tblW w:type="pct" w:w="0.0" />
         <w:tblLook w:firstRow="1" />
         <w:tblCaption w:val="Table caption." />
       </w:tblPr>
       <w:tblGrid />
       <w:tr>
         <w:trPr>
-          <w:cnfStyle w:firstRow="1" />
+          <w:cnfStyle w:firstRow="1" w:val="100000000000" />
         </w:trPr>
         <w:tc>
           <w:tcPr>
@@ -288,9 +234,7 @@
               <w:jc w:val="left" />
             </w:pPr>
             <w:r>
-              <w:t xml:space="preserve">
-Table
-</w:t>
+              <w:t xml:space="preserve">Table</w:t>
             </w:r>
           </w:p>
         </w:tc>
@@ -307,9 +251,7 @@
               <w:jc w:val="left" />
             </w:pPr>
             <w:r>
-              <w:t xml:space="preserve">
-Table
-</w:t>
+              <w:t xml:space="preserve">Table</w:t>
             </w:r>
           </w:p>
         </w:tc>
@@ -322,9 +264,7 @@
               <w:jc w:val="left" />
             </w:pPr>
             <w:r>
-              <w:t xml:space="preserve">
-1
-</w:t>
+              <w:t xml:space="preserve">1</w:t>
             </w:r>
           </w:p>
         </w:tc>
@@ -335,9 +275,7 @@
               <w:jc w:val="left" />
             </w:pPr>
             <w:r>
-              <w:t xml:space="preserve">
-2
-</w:t>
+              <w:t xml:space="preserve">2</w:t>
             </w:r>
           </w:p>
         </w:tc>
@@ -348,9 +286,7 @@
         <w:pStyle w:val="ImageCaption" />
       </w:pPr>
       <w:r>
-        <w:t xml:space="preserve">
-Image Caption
-</w:t>
+        <w:t xml:space="preserve">Image Caption</w:t>
       </w:r>
     </w:p>
     <w:p>
@@ -358,9 +294,7 @@
         <w:pStyle w:val="DefinitionTerm" />
       </w:pPr>
       <w:r>
-        <w:t xml:space="preserve">
-DefinitionTerm
-</w:t>
+        <w:t xml:space="preserve">DefinitionTerm</w:t>
       </w:r>
     </w:p>
     <w:p>
@@ -368,9 +302,7 @@
         <w:pStyle w:val="Definition" />
       </w:pPr>
       <w:r>
-        <w:t xml:space="preserve">
-Definition
-</w:t>
+        <w:t xml:space="preserve">Definition</w:t>
       </w:r>
     </w:p>
     <w:p>
@@ -378,9 +310,7 @@
         <w:pStyle w:val="DefinitionTerm" />
       </w:pPr>
       <w:r>
-        <w:t xml:space="preserve">
-DefinitionTerm
-</w:t>
+        <w:t xml:space="preserve">DefinitionTerm</w:t>
       </w:r>
     </w:p>
     <w:p>
@@ -388,11 +318,13 @@
         <w:pStyle w:val="Definition" />
       </w:pPr>
       <w:r>
-        <w:t xml:space="preserve">
-Definition
-</w:t>
+        <w:t xml:space="preserve">Definition</w:t>
       </w:r>
     </w:p>
-    <w:sectPr />
+    <w:sectPr>
+      <w:footnotePr>
+        <w:numRestart w:val="eachSect" />
+      </w:footnotePr>
+    </w:sectPr>
   </w:body>
 </w:document>
diff --git a/data/docx/word/fontTable.xml b/data/docx/word/fontTable.xml
--- a/data/docx/word/fontTable.xml
+++ b/data/docx/word/fontTable.xml
@@ -1,52 +1,52 @@
-<?xml version="1.0" encoding="UTF-8"?>
+<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
 <w:fonts xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
-&#9;<w:font w:name="Symbol">
-&#9;&#9;<w:panose1 w:val="02000500000000000000" />
-&#9;&#9;<w:charset w:val="02" />
-&#9;&#9;<w:family w:val="auto" />
-&#9;&#9;<w:pitch w:val="variable" />
-&#9;&#9;<w:sig w:usb0="00000000" w:usb1="00000000" w:usb2="00010000" w:usb3="00000000" w:csb0="80000000" w:csb1="00000000" />
-&#9;</w:font>
-&#9;<w:font w:name="Times New Roman">
-&#9;&#9;<w:panose1 w:val="02020603050405020304" />
-&#9;&#9;<w:charset w:val="00" />
-&#9;&#9;<w:family w:val="auto" />
-&#9;&#9;<w:pitch w:val="variable" />
-&#9;&#9;<w:sig w:usb0="00000003" w:usb1="00000000" w:usb2="00000000" w:usb3="00000000" w:csb0="00000001" w:csb1="00000000" />
-&#9;</w:font>
-&#9;<w:font w:name="Courier New">
-&#9;&#9;<w:panose1 w:val="02070309020205020404" />
-&#9;&#9;<w:charset w:val="00" />
-&#9;&#9;<w:family w:val="auto" />
-&#9;&#9;<w:pitch w:val="variable" />
-&#9;&#9;<w:sig w:usb0="00000003" w:usb1="00000000" w:usb2="00000000" w:usb3="00000000" w:csb0="00000001" w:csb1="00000000" />
-&#9;</w:font>
-&#9;<w:font w:name="Wingdings">
-&#9;&#9;<w:panose1 w:val="05020102010804080708" />
-&#9;&#9;<w:charset w:val="02" />
-&#9;&#9;<w:family w:val="auto" />
-&#9;&#9;<w:pitch w:val="variable" />
-&#9;&#9;<w:sig w:usb0="00000000" w:usb1="00000000" w:usb2="00010000" w:usb3="00000000" w:csb0="80000000" w:csb1="00000000" />
-&#9;</w:font>
-&#9;<w:font w:name="Cambria">
-&#9;&#9;<w:panose1 w:val="02040503050406030204" />
-&#9;&#9;<w:charset w:val="00" />
-&#9;&#9;<w:family w:val="auto" />
-&#9;&#9;<w:pitch w:val="variable" />
-&#9;&#9;<w:sig w:usb0="00000003" w:usb1="00000000" w:usb2="00000000" w:usb3="00000000" w:csb0="00000001" w:csb1="00000000" />
-&#9;</w:font>
-&#9;<w:font w:name="Calibri">
-&#9;&#9;<w:panose1 w:val="020F0502020204030204" />
-&#9;&#9;<w:charset w:val="00" />
-&#9;&#9;<w:family w:val="auto" />
-&#9;&#9;<w:pitch w:val="variable" />
-&#9;&#9;<w:sig w:usb0="00000003" w:usb1="00000000" w:usb2="00000000" w:usb3="00000000" w:csb0="00000001" w:csb1="00000000" />
-&#9;</w:font>
-&#9;<w:font w:name="Arial">
-&#9;&#9;<w:panose1 w:val="020B0604020202020204" />
-&#9;&#9;<w:charset w:val="00" />
-&#9;&#9;<w:family w:val="auto" />
-&#9;&#9;<w:pitch w:val="variable" />
-&#9;&#9;<w:sig w:usb0="00000003" w:usb1="00000000" w:usb2="00000000" w:usb3="00000000" w:csb0="00000001" w:csb1="00000000" />
-&#9;</w:font>
+  <w:font w:name="Aptos">
+    <w:panose1 w:val="020B0004020202020204"/>
+    <w:charset w:val="00"/>
+    <w:family w:val="swiss"/>
+    <w:pitch w:val="variable"/>
+    <w:sig w:usb0="20000287" w:usb1="00000003" w:usb2="00000000" w:usb3="00000000" w:csb0="0000019F" w:csb1="00000000"/>
+  </w:font>
+  <w:font w:name="Times New Roman">
+    <w:panose1 w:val="02020603050405020304"/>
+    <w:charset w:val="00"/>
+    <w:family w:val="roman"/>
+    <w:pitch w:val="variable"/>
+    <w:sig w:usb0="E0002EFF" w:usb1="C000785B" w:usb2="00000009" w:usb3="00000000" w:csb0="000001FF" w:csb1="00000000"/>
+  </w:font>
+  <w:font w:name="Aptos Display">
+    <w:panose1 w:val="020B0004020202020204"/>
+    <w:charset w:val="00"/>
+    <w:family w:val="swiss"/>
+    <w:pitch w:val="variable"/>
+    <w:sig w:usb0="20000287" w:usb1="00000003" w:usb2="00000000" w:usb3="00000000" w:csb0="0000019F" w:csb1="00000000"/>
+  </w:font>
+  <w:font w:name="Cambria Math">
+    <w:panose1 w:val="02040503050406030204"/>
+    <w:charset w:val="00"/>
+    <w:family w:val="roman"/>
+    <w:pitch w:val="variable"/>
+    <w:sig w:usb0="E00002FF" w:usb1="420024FF" w:usb2="00000000" w:usb3="00000000" w:csb0="0000019F" w:csb1="00000000"/>
+  </w:font>
+  <w:font w:name="Courier New">
+    <w:panose1 w:val="02070309020205020404"/>
+    <w:charset w:val="00"/>
+    <w:family w:val="modern"/>
+    <w:pitch w:val="fixed"/>
+    <w:sig w:usb0="E0002AFF" w:usb1="C0007843" w:usb2="00000009" w:usb3="00000000" w:csb0="000001FF" w:csb1="00000000"/>
+  </w:font>
+  <w:font w:name="Cambria">
+    <w:panose1 w:val="02040503050406030204"/>
+    <w:charset w:val="00"/>
+    <w:family w:val="roman"/>
+    <w:pitch w:val="variable"/>
+    <w:sig w:usb0="E00002FF" w:usb1="400004FF" w:usb2="00000000" w:usb3="00000000" w:csb0="0000019F" w:csb1="00000000"/>
+  </w:font>
+  <w:font w:name="Calibri">
+    <w:panose1 w:val="020F0502020204030204"/>
+    <w:charset w:val="00"/>
+    <w:family w:val="swiss"/>
+    <w:pitch w:val="variable"/>
+    <w:sig w:usb0="E0002AFF" w:usb1="C000247B" w:usb2="00000009" w:usb3="00000000" w:csb0="000001FF" w:csb1="00000000"/>
+  </w:font>
 </w:fonts>
diff --git a/data/docx/word/footnotes.xml b/data/docx/word/footnotes.xml
--- a/data/docx/word/footnotes.xml
+++ b/data/docx/word/footnotes.xml
@@ -1,7 +1,21 @@
 <?xml version="1.0" encoding="UTF-8"?>
-<w:footnotes xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:m="http://schemas.openxmlformats.org/officeDocument/2006/math" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:w10="urn:schemas-microsoft-com:office:word" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:pic="http://schemas.openxmlformats.org/drawingml/2006/picture" xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing"><w:footnote w:type="continuationSeparator" w:id="0"><w:p><w:r><w:continuationSeparator /></w:r></w:p></w:footnote><w:footnote w:type="separator" w:id="-1"><w:p><w:r><w:separator /></w:r></w:p></w:footnote><w:footnote w:id="31"><w:p><w:pPr><w:pStyle w:val="FootnoteText" /></w:pPr><w:r>
-  <w:rPr>
-    <w:rStyle w:val="FootnoteReference" />
-  </w:rPr>
-  <w:footnoteRef />
-</w:r><w:r><w:t xml:space="preserve"> </w:t></w:r><w:r><w:t xml:space="preserve">Footnote Text.</w:t></w:r></w:p></w:footnote></w:footnotes>
+<w:footnotes xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:m="http://schemas.openxmlformats.org/officeDocument/2006/math" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:w10="urn:schemas-microsoft-com:office:word" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:pic="http://schemas.openxmlformats.org/drawingml/2006/picture" xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing">
+  <w:footnote w:type="continuationSeparator" w:id="0"><w:p><w:r><w:continuationSeparator /></w:r></w:p></w:footnote>
+  <w:footnote w:type="separator" w:id="-1"><w:p><w:r><w:separator /></w:r></w:p></w:footnote>
+  <w:footnote w:id="31">
+    <w:p>
+      <w:pPr><w:pStyle w:val="FootnoteText" /></w:pPr>
+      <w:r>
+        <w:rPr>
+          <w:rStyle w:val="FootnoteReference" />
+        </w:rPr>
+      <w:footnoteRef />
+      </w:r>
+      <w:r><w:t>Footnote Text.</w:t></w:r>
+    </w:p>
+    <w:p>
+      <w:pPr><w:pStyle w:val="FootnoteBlockText"/></w:pPr>
+      <w:r><w:t>Footnote Block Text</w:t></w:r>
+    </w:p>
+  </w:footnote>
+</w:footnotes>
diff --git a/data/docx/word/settings.xml b/data/docx/word/settings.xml
--- a/data/docx/word/settings.xml
+++ b/data/docx/word/settings.xml
@@ -1,13 +1,9 @@
 <?xml version="1.0" encoding="UTF-8"?>
 <w:settings xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:m="http://schemas.openxmlformats.org/officeDocument/2006/math" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:w10="urn:schemas-microsoft-com:office:word" xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:sl="http://schemas.openxmlformats.org/schemaLibrary/2006/main">
-  <w:zoom w:percent="90" />
+  <w:zoom w:percent="100" />
   <w:embedSystemFonts />
   <w:proofState w:spelling="clean" w:grammar="clean" />
   <w:stylePaneFormatFilter w:val="0004" />
-  <w:footnotePr>
-    <w:footnote w:id="-1" />
-    <w:footnote w:id="0" />
-  </w:footnotePr>
   <w:doNotTrackMoves />
   <w:defaultTabStop w:val="720" />
   <w:drawingGridHorizontalSpacing w:val="360" />
@@ -16,29 +12,23 @@
   <w:displayVerticalDrawingGridEvery w:val="0" />
   <w:characterSpacingControl w:val="doNotCompress" />
   <w:savePreviewPicture />
+  <w:footnotePr>
+    <w:footnote w:id="-1" />
+    <w:footnote w:id="0" />
+  </w:footnotePr>
   <w:rsids>
-    <w:rsidRoot w:val="00590D07" />
-    <w:rsid w:val="00011C8B" />
-    <w:rsid w:val="004E29B3" />
-    <w:rsid w:val="00590D07" />
-    <w:rsid w:val="00784D58" />
-    <w:rsid w:val="008D6863" />
-    <w:rsid w:val="00B86B75" />
-    <w:rsid w:val="00BC48D5" />
-    <w:rsid w:val="00C36279" />
-    <w:rsid w:val="00E315A3" />
   </w:rsids>
   <m:mathPr>
-    <m:mathFont m:val="Lucida Grande" />
+    <m:mathFont m:val="Cambria Math" />
     <m:brkBin m:val="before" />
     <m:brkBinSub m:val="--" />
-    <m:smallFrac m:val="false" />
-    <m:dispDef m:val="false" />
+    <m:smallFrac m:val="0" />
+    <m:dispDef />
     <m:lMargin m:val="0" />
     <m:rMargin m:val="0" />
     <m:wrapRight />
     <m:intLim m:val="subSup" />
-    <m:naryLim m:val="subSup" />
+    <m:naryLim m:val="undOvr" />
   </m:mathPr>
   <w:themeFontLang w:val="en-US" />
   <w:clrSchemeMapping w:bg1="light1" w:t1="dark1" w:bg2="light2" w:t2="dark2" w:accent1="accent1" w:accent2="accent2" w:accent3="accent3" w:accent4="accent4" w:accent5="accent5" w:accent6="accent6" w:hyperlink="hyperlink" w:followedHyperlink="followedHyperlink" />
diff --git a/data/docx/word/styles.xml b/data/docx/word/styles.xml
--- a/data/docx/word/styles.xml
+++ b/data/docx/word/styles.xml
@@ -3,10 +3,10 @@
   <w:docDefaults>
     <w:rPrDefault>
       <w:rPr>
-        <w:rFonts w:asciiTheme="minorHAnsi" w:eastAsiaTheme="minorHAnsi" w:hAnsiTheme="minorHAnsi" w:cstheme="minorBidi" />
+        <w:rFonts w:asciiTheme="minorHAnsi" w:eastAsiaTheme="minorEastAsia" w:hAnsiTheme="minorHAnsi" w:cstheme="minorBidi" />
         <w:sz w:val="24" />
         <w:szCs w:val="24" />
-        <w:lang w:val="en-US" w:eastAsia="en-US" w:bidi="ar-SA" />
+        <w:lang w:val="en-US" w:eastAsia="zh-CN" w:bidi="ar-SA" />
       </w:rPr>
     </w:rPrDefault>
     <w:pPrDefault>
@@ -20,14 +20,14 @@
     <w:name w:val="Normal" />
     <w:qFormat />
   </w:style>
-    <w:style w:type="paragraph" w:styleId="BodyText">
+  <w:style w:type="paragraph" w:styleId="BodyText">
     <w:name w:val="Body Text" />
     <w:basedOn w:val="Normal" />
     <w:link w:val="BodyTextChar" />
+    <w:qFormat />
     <w:pPr>
       <w:spacing w:before="180" w:after="180" />
     </w:pPr>
-    <w:qFormat />
   </w:style>
   <w:style w:type="paragraph" w:customStyle="1" w:styleId="FirstParagraph">
     <w:name w:val="First Paragraph" />
@@ -47,57 +47,120 @@
     <w:name w:val="Title" />
     <w:basedOn w:val="Normal" />
     <w:next w:val="BodyText" />
+    <w:link w:val="TitleChar" />
+    <w:uiPriority w:val="10" />
     <w:qFormat />
+    <w:rsid w:val="00A10FD9" />
     <w:pPr>
-      <w:keepNext />
-      <w:keepLines />
-      <w:spacing w:before="480" w:after="240" />
+      <w:spacing w:after="80" w:line="240" w:lineRule="auto" />
+      <w:contextualSpacing />
       <w:jc w:val="center" />
     </w:pPr>
     <w:rPr>
-      <w:rFonts w:asciiTheme="majorHAnsi" w:eastAsiaTheme="majorEastAsia" w:hAnsiTheme="majorHAnsi" w:cstheme="majorBidi" />
-      <w:b />
-      <w:bCs />
-      <w:color w:val="345A8A" w:themeColor="accent1" w:themeShade="B5" />
-      <w:sz w:val="36" />
-      <w:szCs w:val="36" />
+      <w:rFonts w:asciiTheme="majorHAnsi"
+      w:eastAsiaTheme="majorEastAsia" w:hAnsiTheme="majorHAnsi"
+      w:cstheme="majorBidi" />
+      <w:sz w:val="56" />
+      <w:szCs w:val="56" />
     </w:rPr>
   </w:style>
- <w:style w:type="paragraph" w:styleId="Subtitle">
+  <w:style w:type="character" w:customStyle="1"
+  w:styleId="TitleChar">
+    <w:name w:val="Title Char" />
+    <w:basedOn w:val="DefaultParagraphFont" />
+    <w:link w:val="Title" />
+    <w:uiPriority w:val="10" />
+    <w:rsid w:val="00A10FD9" />
+    <w:rPr>
+      <w:rFonts w:asciiTheme="majorHAnsi"
+      w:eastAsiaTheme="majorEastAsia" w:hAnsiTheme="majorHAnsi"
+      w:cstheme="majorBidi" />
+      <w:sz w:val="56" />
+      <w:szCs w:val="56" />
+    </w:rPr>
+  </w:style>
+  <w:style w:type="paragraph" w:styleId="Subtitle">
     <w:name w:val="Subtitle" />
     <w:basedOn w:val="Title" />
     <w:next w:val="BodyText" />
+    <w:link w:val="SubtitleChar" />
+    <w:uiPriority w:val="11" />
     <w:qFormat />
+    <w:rsid w:val="00A10FD9" />
     <w:pPr>
-      <w:keepNext />
-      <w:keepLines />
-      <w:spacing w:before="240" w:after="240" />
-      <w:jc w:val="center" />
+      <w:numPr>
+        <w:ilvl w:val="1" />
+      </w:numPr>
     </w:pPr>
     <w:rPr>
-      <w:sz w:val="30" />
-      <w:szCs w:val="30" />
+      <w:rFonts w:eastAsiaTheme="majorEastAsia"
+      w:cstheme="majorBidi" />
+      <w:spacing w:val="15" />
+      <w:sz w:val="28" />
+      <w:szCs w:val="28" />
     </w:rPr>
- </w:style>
+  </w:style>
+  <w:style w:type="character" w:customStyle="1"
+  w:styleId="SubtitleChar">
+    <w:name w:val="Subtitle Char" />
+    <w:basedOn w:val="DefaultParagraphFont" />
+    <w:link w:val="Subtitle" />
+    <w:uiPriority w:val="11" />
+    <w:rsid w:val="00A10FD9" />
+    <w:rPr>
+      <w:rFonts w:eastAsiaTheme="majorEastAsia"
+      w:cstheme="majorBidi" />
+      <w:color w:val="595959" w:themeColor="text1"
+      w:themeTint="A6" />
+      <w:spacing w:val="15" />
+      <w:sz w:val="28" />
+      <w:szCs w:val="28" />
+    </w:rPr>
+  </w:style>
   <w:style w:type="paragraph" w:customStyle="1" w:styleId="Author">
     <w:name w:val="Author" />
+    <w:basedOn w:val="Title" />
     <w:next w:val="BodyText" />
     <w:qFormat />
     <w:pPr>
       <w:keepNext />
       <w:keepLines />
-      <w:jc w:val="center" />
     </w:pPr>
+    <w:rPr>
+      <w:sz w:val="24" />
+      <w:szCs w:val="24" />
+    </w:rPr>
   </w:style>
   <w:style w:type="paragraph" w:styleId="Date">
     <w:name w:val="Date" />
+    <w:basedOn w:val="Title" />
     <w:next w:val="BodyText" />
     <w:qFormat />
     <w:pPr>
       <w:keepNext />
       <w:keepLines />
+    </w:pPr>
+    <w:rPr>
+      <w:sz w:val="24" />
+      <w:szCs w:val="24" />
+    </w:rPr>
+  </w:style>
+  <w:style w:type="paragraph" w:customStyle="1" w:styleId="AbstractTitle">
+    <w:name w:val="Abstract Title" />
+    <w:basedOn w:val="Normal" />
+    <w:next w:val="Abstract" />
+    <w:qFormat />
+    <w:pPr>
+      <w:keepNext />
+      <w:keepLines />
+      <w:spacing w:before="300" w:after="0" />
       <w:jc w:val="center" />
     </w:pPr>
+    <w:rPr>
+      <w:b />
+      <w:sz w:val="20" />
+      <w:szCs w:val="20" />
+    </w:rPr>
   </w:style>
   <w:style w:type="paragraph" w:customStyle="1" w:styleId="Abstract">
     <w:name w:val="Abstract" />
@@ -107,7 +170,7 @@
     <w:pPr>
       <w:keepNext />
       <w:keepLines />
-      <w:spacing w:before="300" w:after="300" />
+      <w:spacing w:before="100" w:after="300" />
     </w:pPr>
     <w:rPr>
       <w:sz w:val="20" />
@@ -123,194 +186,371 @@
     <w:rPr />
   </w:style>
   <w:style w:type="paragraph" w:styleId="Heading1">
-    <w:name w:val="Heading 1" />
+    <w:name w:val="heading 1" />
     <w:basedOn w:val="Normal" />
     <w:next w:val="BodyText" />
+    <w:link w:val="Heading1Char" />
     <w:uiPriority w:val="9" />
     <w:qFormat />
+    <w:rsid w:val="00A10FD9" />
     <w:pPr>
       <w:keepNext />
       <w:keepLines />
-      <w:spacing w:before="480" w:after="0" />
+      <w:spacing w:before="360" w:after="80" />
       <w:outlineLvl w:val="0" />
     </w:pPr>
     <w:rPr>
-      <w:rFonts w:asciiTheme="majorHAnsi" w:eastAsiaTheme="majorEastAsia" w:hAnsiTheme="majorHAnsi" w:cstheme="majorBidi" />
-      <w:b />
-      <w:bCs />
-      <w:color w:val="345A8A" w:themeColor="accent1" w:themeShade="B5" />
-      <w:sz w:val="32" />
-      <w:szCs w:val="32" />
+      <w:rFonts w:asciiTheme="majorHAnsi"
+      w:eastAsiaTheme="majorEastAsia" w:hAnsiTheme="majorHAnsi"
+      w:cstheme="majorBidi" />
+      <w:color w:val="0F4761" w:themeColor="accent1"
+      w:themeShade="BF" />
+      <w:sz w:val="40" />
+      <w:szCs w:val="40" />
     </w:rPr>
   </w:style>
   <w:style w:type="paragraph" w:styleId="Heading2">
-    <w:name w:val="Heading 2" />
+    <w:name w:val="heading 2" />
     <w:basedOn w:val="Normal" />
     <w:next w:val="BodyText" />
+    <w:link w:val="Heading2Char" />
     <w:uiPriority w:val="9" />
+    <w:semiHidden />
     <w:unhideWhenUsed />
     <w:qFormat />
+    <w:rsid w:val="00A10FD9" />
     <w:pPr>
       <w:keepNext />
       <w:keepLines />
-      <w:spacing w:before="200" w:after="0" />
+      <w:spacing w:before="160" w:after="80" />
       <w:outlineLvl w:val="1" />
     </w:pPr>
     <w:rPr>
-      <w:rFonts w:asciiTheme="majorHAnsi" w:eastAsiaTheme="majorEastAsia" w:hAnsiTheme="majorHAnsi" w:cstheme="majorBidi" />
-      <w:b />
-      <w:bCs />
-      <w:color w:val="4F81BD" w:themeColor="accent1" />
+      <w:rFonts w:asciiTheme="majorHAnsi"
+      w:eastAsiaTheme="majorEastAsia" w:hAnsiTheme="majorHAnsi"
+      w:cstheme="majorBidi" />
+      <w:color w:val="0F4761" w:themeColor="accent1"
+      w:themeShade="BF" />
       <w:sz w:val="32" />
       <w:szCs w:val="32" />
     </w:rPr>
   </w:style>
   <w:style w:type="paragraph" w:styleId="Heading3">
-    <w:name w:val="Heading 3" />
+    <w:name w:val="heading 3" />
     <w:basedOn w:val="Normal" />
     <w:next w:val="BodyText" />
+    <w:link w:val="Heading3Char" />
     <w:uiPriority w:val="9" />
+    <w:semiHidden />
     <w:unhideWhenUsed />
     <w:qFormat />
+    <w:rsid w:val="00A10FD9" />
     <w:pPr>
       <w:keepNext />
       <w:keepLines />
-      <w:spacing w:before="200" w:after="0" />
+      <w:spacing w:before="160" w:after="80" />
       <w:outlineLvl w:val="2" />
     </w:pPr>
     <w:rPr>
-      <w:rFonts w:asciiTheme="majorHAnsi" w:eastAsiaTheme="majorEastAsia" w:hAnsiTheme="majorHAnsi" w:cstheme="majorBidi" />
-      <w:b />
-      <w:bCs />
-      <w:color w:val="4F81BD" w:themeColor="accent1" />
+      <w:rFonts w:eastAsiaTheme="majorEastAsia"
+      w:cstheme="majorBidi" />
+      <w:color w:val="0F4761" w:themeColor="accent1"
+      w:themeShade="BF" />
       <w:sz w:val="28" />
       <w:szCs w:val="28" />
     </w:rPr>
   </w:style>
   <w:style w:type="paragraph" w:styleId="Heading4">
-    <w:name w:val="Heading 4" />
+    <w:name w:val="heading 4" />
     <w:basedOn w:val="Normal" />
     <w:next w:val="BodyText" />
+    <w:link w:val="Heading4Char" />
     <w:uiPriority w:val="9" />
+    <w:semiHidden />
     <w:unhideWhenUsed />
     <w:qFormat />
+    <w:rsid w:val="00A10FD9" />
     <w:pPr>
       <w:keepNext />
       <w:keepLines />
-      <w:spacing w:before="200" w:after="0" />
+      <w:spacing w:before="80" w:after="40" />
       <w:outlineLvl w:val="3" />
     </w:pPr>
     <w:rPr>
-      <w:rFonts w:asciiTheme="majorHAnsi" w:eastAsiaTheme="majorEastAsia" w:hAnsiTheme="majorHAnsi" w:cstheme="majorBidi" />
-      <w:b />
-      <w:bCs />
-      <w:color w:val="4F81BD" w:themeColor="accent1" />
-      <w:sz w:val="24" />
-      <w:szCs w:val="24" />
+      <w:rFonts w:eastAsiaTheme="majorEastAsia"
+      w:cstheme="majorBidi" />
+      <w:i />
+      <w:iCs />
+      <w:color w:val="0F4761" w:themeColor="accent1"
+      w:themeShade="BF" />
     </w:rPr>
   </w:style>
   <w:style w:type="paragraph" w:styleId="Heading5">
-    <w:name w:val="Heading 5" />
+    <w:name w:val="heading 5" />
     <w:basedOn w:val="Normal" />
     <w:next w:val="BodyText" />
+    <w:link w:val="Heading5Char" />
     <w:uiPriority w:val="9" />
+    <w:semiHidden />
     <w:unhideWhenUsed />
     <w:qFormat />
+    <w:rsid w:val="00A10FD9" />
     <w:pPr>
       <w:keepNext />
       <w:keepLines />
-      <w:spacing w:before="200" w:after="0" />
+      <w:spacing w:before="80" w:after="40" />
       <w:outlineLvl w:val="4" />
     </w:pPr>
     <w:rPr>
-      <w:rFonts w:asciiTheme="majorHAnsi" w:eastAsiaTheme="majorEastAsia" w:hAnsiTheme="majorHAnsi" w:cstheme="majorBidi" />
-      <w:i />
-      <w:iCs />
-      <w:color w:val="4F81BD" w:themeColor="accent1" />
-      <w:sz w:val="24" />
-      <w:szCs w:val="24" />
+      <w:rFonts w:eastAsiaTheme="majorEastAsia"
+      w:cstheme="majorBidi" />
+      <w:color w:val="0F4761" w:themeColor="accent1"
+      w:themeShade="BF" />
     </w:rPr>
   </w:style>
   <w:style w:type="paragraph" w:styleId="Heading6">
-    <w:name w:val="Heading 6" />
+    <w:name w:val="heading 6" />
     <w:basedOn w:val="Normal" />
     <w:next w:val="BodyText" />
+    <w:link w:val="Heading6Char" />
     <w:uiPriority w:val="9" />
+    <w:semiHidden />
     <w:unhideWhenUsed />
     <w:qFormat />
+    <w:rsid w:val="00A10FD9" />
     <w:pPr>
       <w:keepNext />
       <w:keepLines />
-      <w:spacing w:before="200" w:after="0" />
+      <w:spacing w:before="40" w:after="0" />
       <w:outlineLvl w:val="5" />
     </w:pPr>
     <w:rPr>
-      <w:rFonts w:asciiTheme="majorHAnsi" w:eastAsiaTheme="majorEastAsia" w:hAnsiTheme="majorHAnsi" w:cstheme="majorBidi" />
-      <w:color w:val="4F81BD" w:themeColor="accent1" />
-      <w:sz w:val="24" />
-      <w:szCs w:val="24" />
+      <w:rFonts w:eastAsiaTheme="majorEastAsia"
+      w:cstheme="majorBidi" />
+      <w:i />
+      <w:iCs />
+      <w:color w:val="595959" w:themeColor="text1"
+      w:themeTint="A6" />
     </w:rPr>
   </w:style>
   <w:style w:type="paragraph" w:styleId="Heading7">
-    <w:name w:val="Heading 7" />
+    <w:name w:val="heading 7" />
     <w:basedOn w:val="Normal" />
     <w:next w:val="BodyText" />
+    <w:link w:val="Heading7Char" />
     <w:uiPriority w:val="9" />
+    <w:semiHidden />
     <w:unhideWhenUsed />
     <w:qFormat />
+    <w:rsid w:val="00A10FD9" />
     <w:pPr>
       <w:keepNext />
       <w:keepLines />
-      <w:spacing w:before="200" w:after="0" />
+      <w:spacing w:before="40" w:after="0" />
       <w:outlineLvl w:val="6" />
     </w:pPr>
     <w:rPr>
-      <w:rFonts w:asciiTheme="majorHAnsi" w:eastAsiaTheme="majorEastAsia" w:hAnsiTheme="majorHAnsi" w:cstheme="majorBidi" />
-      <w:color w:val="4F81BD" w:themeColor="accent1" />
-      <w:sz w:val="24" />
-      <w:szCs w:val="24" />
+      <w:rFonts w:eastAsiaTheme="majorEastAsia"
+      w:cstheme="majorBidi" />
+      <w:color w:val="595959" w:themeColor="text1"
+      w:themeTint="A6" />
     </w:rPr>
   </w:style>
   <w:style w:type="paragraph" w:styleId="Heading8">
-    <w:name w:val="Heading 8" />
+    <w:name w:val="heading 8" />
     <w:basedOn w:val="Normal" />
     <w:next w:val="BodyText" />
+    <w:link w:val="Heading8Char" />
     <w:uiPriority w:val="9" />
+    <w:semiHidden />
     <w:unhideWhenUsed />
     <w:qFormat />
+    <w:rsid w:val="00A10FD9" />
     <w:pPr>
       <w:keepNext />
       <w:keepLines />
-      <w:spacing w:before="200" w:after="0" />
+      <w:spacing w:after="0" />
       <w:outlineLvl w:val="7" />
     </w:pPr>
     <w:rPr>
-      <w:rFonts w:asciiTheme="majorHAnsi" w:eastAsiaTheme="majorEastAsia" w:hAnsiTheme="majorHAnsi" w:cstheme="majorBidi" />
-      <w:color w:val="4F81BD" w:themeColor="accent1" />
-      <w:sz w:val="24" />
-      <w:szCs w:val="24" />
+      <w:rFonts w:eastAsiaTheme="majorEastAsia"
+      w:cstheme="majorBidi" />
+      <w:i />
+      <w:iCs />
+      <w:color w:val="272727" w:themeColor="text1"
+      w:themeTint="D8" />
     </w:rPr>
   </w:style>
   <w:style w:type="paragraph" w:styleId="Heading9">
-    <w:name w:val="Heading 9" />
+    <w:name w:val="heading 9" />
     <w:basedOn w:val="Normal" />
     <w:next w:val="BodyText" />
+    <w:link w:val="Heading9Char" />
     <w:uiPriority w:val="9" />
+    <w:semiHidden />
     <w:unhideWhenUsed />
     <w:qFormat />
+    <w:rsid w:val="00A10FD9" />
     <w:pPr>
       <w:keepNext />
       <w:keepLines />
-      <w:spacing w:before="200" w:after="0" />
+      <w:spacing w:after="0" />
       <w:outlineLvl w:val="8" />
     </w:pPr>
     <w:rPr>
-      <w:rFonts w:asciiTheme="majorHAnsi" w:eastAsiaTheme="majorEastAsia" w:hAnsiTheme="majorHAnsi" w:cstheme="majorBidi" />
-      <w:color w:val="4F81BD" w:themeColor="accent1" />
-      <w:sz w:val="24" />
-      <w:szCs w:val="24" />
+      <w:rFonts w:eastAsiaTheme="majorEastAsia"
+      w:cstheme="majorBidi" />
+      <w:color w:val="272727" w:themeColor="text1"
+      w:themeTint="D8" />
     </w:rPr>
   </w:style>
+  <w:style w:type="character" w:customStyle="1" w:styleId="Heading1Char">
+    <w:name w:val="Heading 1 Char" />
+    <w:basedOn w:val="DefaultParagraphFont" />
+    <w:link w:val="Heading1" />
+    <w:uiPriority w:val="9" />
+    <w:rsid w:val="00A10FD9" />
+    <w:rPr>
+      <w:rFonts w:asciiTheme="majorHAnsi"
+      w:eastAsiaTheme="majorEastAsia" w:hAnsiTheme="majorHAnsi"
+      w:cstheme="majorBidi" />
+      <w:color w:val="0F4761" w:themeColor="accent1"
+      w:themeShade="BF" />
+      <w:sz w:val="40" />
+      <w:szCs w:val="40" />
+    </w:rPr>
+  </w:style>
+  <w:style w:type="character" w:customStyle="1"
+  w:styleId="Heading2Char">
+    <w:name w:val="Heading 2 Char" />
+    <w:basedOn w:val="DefaultParagraphFont" />
+    <w:link w:val="Heading2" />
+    <w:uiPriority w:val="9" />
+    <w:semiHidden />
+    <w:rsid w:val="00A10FD9" />
+    <w:rPr>
+      <w:rFonts w:asciiTheme="majorHAnsi"
+      w:eastAsiaTheme="majorEastAsia" w:hAnsiTheme="majorHAnsi"
+      w:cstheme="majorBidi" />
+      <w:color w:val="0F4761" w:themeColor="accent1"
+      w:themeShade="BF" />
+      <w:sz w:val="32" />
+      <w:szCs w:val="32" />
+    </w:rPr>
+  </w:style>
+  <w:style w:type="character" w:customStyle="1"
+  w:styleId="Heading3Char">
+    <w:name w:val="Heading 3 Char" />
+    <w:basedOn w:val="DefaultParagraphFont" />
+    <w:link w:val="Heading3" />
+    <w:uiPriority w:val="9" />
+    <w:semiHidden />
+    <w:rsid w:val="00A10FD9" />
+    <w:rPr>
+      <w:rFonts w:eastAsiaTheme="majorEastAsia"
+      w:cstheme="majorBidi" />
+      <w:color w:val="0F4761" w:themeColor="accent1"
+      w:themeShade="BF" />
+      <w:sz w:val="28" />
+      <w:szCs w:val="28" />
+    </w:rPr>
+  </w:style>
+  <w:style w:type="character" w:customStyle="1"
+  w:styleId="Heading4Char">
+    <w:name w:val="Heading 4 Char" />
+    <w:basedOn w:val="DefaultParagraphFont" />
+    <w:link w:val="Heading4" />
+    <w:uiPriority w:val="9" />
+    <w:semiHidden />
+    <w:rsid w:val="00A10FD9" />
+    <w:rPr>
+      <w:rFonts w:eastAsiaTheme="majorEastAsia"
+      w:cstheme="majorBidi" />
+      <w:i />
+      <w:iCs />
+      <w:color w:val="0F4761" w:themeColor="accent1"
+      w:themeShade="BF" />
+    </w:rPr>
+  </w:style>
+  <w:style w:type="character" w:customStyle="1"
+  w:styleId="Heading5Char">
+    <w:name w:val="Heading 5 Char" />
+    <w:basedOn w:val="DefaultParagraphFont" />
+    <w:link w:val="Heading5" />
+    <w:uiPriority w:val="9" />
+    <w:semiHidden />
+    <w:rsid w:val="00A10FD9" />
+    <w:rPr>
+      <w:rFonts w:eastAsiaTheme="majorEastAsia"
+      w:cstheme="majorBidi" />
+      <w:color w:val="0F4761" w:themeColor="accent1"
+      w:themeShade="BF" />
+    </w:rPr>
+  </w:style>
+  <w:style w:type="character" w:customStyle="1"
+  w:styleId="Heading6Char">
+    <w:name w:val="Heading 6 Char" />
+    <w:basedOn w:val="DefaultParagraphFont" />
+    <w:link w:val="Heading6" />
+    <w:uiPriority w:val="9" />
+    <w:semiHidden />
+    <w:rsid w:val="00A10FD9" />
+    <w:rPr>
+      <w:rFonts w:eastAsiaTheme="majorEastAsia"
+      w:cstheme="majorBidi" />
+      <w:i />
+      <w:iCs />
+      <w:color w:val="595959" w:themeColor="text1"
+      w:themeTint="A6" />
+    </w:rPr>
+  </w:style>
+  <w:style w:type="character" w:customStyle="1"
+  w:styleId="Heading7Char">
+    <w:name w:val="Heading 7 Char" />
+    <w:basedOn w:val="DefaultParagraphFont" />
+    <w:link w:val="Heading7" />
+    <w:uiPriority w:val="9" />
+    <w:semiHidden />
+    <w:rsid w:val="00A10FD9" />
+    <w:rPr>
+      <w:rFonts w:eastAsiaTheme="majorEastAsia"
+      w:cstheme="majorBidi" />
+      <w:color w:val="595959" w:themeColor="text1"
+      w:themeTint="A6" />
+    </w:rPr>
+  </w:style>
+  <w:style w:type="character" w:customStyle="1"
+  w:styleId="Heading8Char">
+    <w:name w:val="Heading 8 Char" />
+    <w:basedOn w:val="DefaultParagraphFont" />
+    <w:link w:val="Heading8" />
+    <w:uiPriority w:val="9" />
+    <w:semiHidden />
+    <w:rsid w:val="00A10FD9" />
+    <w:rPr>
+      <w:rFonts w:eastAsiaTheme="majorEastAsia"
+      w:cstheme="majorBidi" />
+      <w:i />
+      <w:iCs />
+      <w:color w:val="272727" w:themeColor="text1"
+      w:themeTint="D8" />
+    </w:rPr>
+  </w:style>
+  <w:style w:type="character" w:customStyle="1"
+  w:styleId="Heading9Char">
+    <w:name w:val="Heading 9 Char" />
+    <w:basedOn w:val="DefaultParagraphFont" />
+    <w:link w:val="Heading9" />
+    <w:uiPriority w:val="9" />
+    <w:semiHidden />
+    <w:rsid w:val="00A10FD9" />
+    <w:rPr>
+      <w:rFonts w:eastAsiaTheme="majorEastAsia"
+      w:cstheme="majorBidi" />
+      <w:color w:val="272727" w:themeColor="text1"
+      w:themeTint="D8" />
+    </w:rPr>
+  </w:style>
   <w:style w:type="paragraph" w:styleId="BlockText">
     <w:name w:val="Block Text" />
     <w:basedOn w:val="BodyText" />
@@ -320,14 +560,8 @@
     <w:qFormat />
     <w:pPr>
       <w:spacing w:before="100" w:after="100" />
-      <w:ind w:firstLine="0" />
+      <w:ind w:firstLine="0" w:left="480" w:right="480" />
     </w:pPr>
-    <w:rPr>
-      <w:rFonts w:asciiTheme="majorHAnsi" w:eastAsiaTheme="majorEastAsia" w:hAnsiTheme="majorHAnsi" w:cstheme="majorBidi" />
-      <w:bCs />
-      <w:sz w:val="20" />
-      <w:szCs w:val="20" />
-    </w:rPr>
   </w:style>
   <w:style w:type="paragraph" w:styleId="FootnoteText">
     <w:name w:val="Footnote Text" />
@@ -337,6 +571,18 @@
     <w:unhideWhenUsed />
     <w:qFormat />
   </w:style>
+  <w:style w:type="paragraph" w:styleId="FootnoteBlockText">
+    <w:name w:val="Footnote Block Text" />
+    <w:basedOn w:val="FootnoteText" />
+    <w:next w:val="FootnoteText" />
+    <w:uiPriority w:val="9" />
+    <w:unhideWhenUsed />
+    <w:qFormat />
+    <w:pPr>
+      <w:spacing w:before="100" w:after="100" />
+      <w:ind w:firstLine="0" w:left="480" w:right="480" />
+    </w:pPr>
+  </w:style>
   <w:style w:type="character" w:default="1" w:styleId="DefaultParagraphFont">
     <w:name w:val="Default Paragraph Font" />
     <w:semiHidden />
@@ -357,6 +603,14 @@
         <w:right w:w="108" w:type="dxa" />
       </w:tblCellMar>
     </w:tblPr>
+    <w:tblStylePr w:type="firstRow">
+      <w:tcPr>
+        <w:tcBorders>
+          <w:bottom w:val="single"/>
+        </w:tcBorders>
+        <w:vAlign w:val="bottom"/>
+      </w:tcPr>
+    </w:tblStylePr>
   </w:style>
   <w:style w:type="paragraph" w:customStyle="1" w:styleId="DefinitionTerm">
     <w:name w:val="Definition Term" />
@@ -420,6 +674,10 @@
       <w:rFonts w:ascii="Consolas" w:hAnsi="Consolas" />
       <w:sz w:val="22" />
     </w:rPr>
+  </w:style>
+  <w:style w:type="character" w:customStyle="1" w:styleId="SectionNumber">
+    <w:name w:val="Section Number" />
+    <w:basedOn w:val="BodyTextChar" />
   </w:style>
   <w:style w:type="character" w:styleId="FootnoteReference">
     <w:name w:val="Footnote Reference" />
diff --git a/data/docx/word/theme/theme1.xml b/data/docx/word/theme/theme1.xml
--- a/data/docx/word/theme/theme1.xml
+++ b/data/docx/word/theme/theme1.xml
@@ -1,2 +1,293 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<a:theme xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" name="Office Theme"><a:themeElements><a:clrScheme name="Office"><a:dk1><a:sysClr val="windowText" lastClr="000000" /></a:dk1><a:lt1><a:sysClr val="window" lastClr="FFFFFF" /></a:lt1><a:dk2><a:srgbClr val="1F497D" /></a:dk2><a:lt2><a:srgbClr val="EEECE1" /></a:lt2><a:accent1><a:srgbClr val="4F81BD" /></a:accent1><a:accent2><a:srgbClr val="C0504D" /></a:accent2><a:accent3><a:srgbClr val="9BBB59" /></a:accent3><a:accent4><a:srgbClr val="8064A2" /></a:accent4><a:accent5><a:srgbClr val="4BACC6" /></a:accent5><a:accent6><a:srgbClr val="F79646" /></a:accent6><a:hlink><a:srgbClr val="0000FF" /></a:hlink><a:folHlink><a:srgbClr val="800080" /></a:folHlink></a:clrScheme><a:fontScheme name="Office"><a:majorFont><a:latin typeface="Calibri" /><a:ea typeface="" /><a:cs typeface="" /><a:font script="Jpan" typeface="ＭＳ ゴシック" /><a:font script="Hang" typeface="맑은 고딕" /><a:font script="Hans" typeface="宋体" /><a:font script="Hant" typeface="新細明體" /><a:font script="Arab" typeface="Times New Roman" /><a:font script="Hebr" typeface="Times New Roman" /><a:font script="Thai" typeface="Angsana New" /><a:font script="Ethi" typeface="Nyala" /><a:font script="Beng" typeface="Vrinda" /><a:font script="Gujr" typeface="Shruti" /><a:font script="Khmr" typeface="MoolBoran" /><a:font script="Knda" typeface="Tunga" /><a:font script="Guru" typeface="Raavi" /><a:font script="Cans" typeface="Euphemia" /><a:font script="Cher" typeface="Plantagenet Cherokee" /><a:font script="Yiii" typeface="Microsoft Yi Baiti" /><a:font script="Tibt" typeface="Microsoft Himalaya" /><a:font script="Thaa" typeface="MV Boli" /><a:font script="Deva" typeface="Mangal" /><a:font script="Telu" typeface="Gautami" /><a:font script="Taml" typeface="Latha" /><a:font script="Syrc" typeface="Estrangelo Edessa" /><a:font script="Orya" typeface="Kalinga" /><a:font script="Mlym" typeface="Kartika" /><a:font script="Laoo" typeface="DokChampa" /><a:font script="Sinh" typeface="Iskoola Pota" /><a:font script="Mong" typeface="Mongolian Baiti" /><a:font script="Viet" typeface="Times New Roman" /><a:font script="Uigh" typeface="Microsoft Uighur" /></a:majorFont><a:minorFont><a:latin typeface="Cambria" /><a:ea typeface="" /><a:cs typeface="" /><a:font script="Jpan" typeface="ＭＳ 明朝" /><a:font script="Hang" typeface="맑은 고딕" /><a:font script="Hans" typeface="宋体" /><a:font script="Hant" typeface="新細明體" /><a:font script="Arab" typeface="Arial" /><a:font script="Hebr" typeface="Arial" /><a:font script="Thai" typeface="Cordia New" /><a:font script="Ethi" typeface="Nyala" /><a:font script="Beng" typeface="Vrinda" /><a:font script="Gujr" typeface="Shruti" /><a:font script="Khmr" typeface="DaunPenh" /><a:font script="Knda" typeface="Tunga" /><a:font script="Guru" typeface="Raavi" /><a:font script="Cans" typeface="Euphemia" /><a:font script="Cher" typeface="Plantagenet Cherokee" /><a:font script="Yiii" typeface="Microsoft Yi Baiti" /><a:font script="Tibt" typeface="Microsoft Himalaya" /><a:font script="Thaa" typeface="MV Boli" /><a:font script="Deva" typeface="Mangal" /><a:font script="Telu" typeface="Gautami" /><a:font script="Taml" typeface="Latha" /><a:font script="Syrc" typeface="Estrangelo Edessa" /><a:font script="Orya" typeface="Kalinga" /><a:font script="Mlym" typeface="Kartika" /><a:font script="Laoo" typeface="DokChampa" /><a:font script="Sinh" typeface="Iskoola Pota" /><a:font script="Mong" typeface="Mongolian Baiti" /><a:font script="Viet" typeface="Arial" /><a:font script="Uigh" typeface="Microsoft Uighur" /></a:minorFont></a:fontScheme><a:fmtScheme name="Office"><a:fillStyleLst><a:solidFill><a:schemeClr val="phClr" /></a:solidFill><a:gradFill rotWithShape="1"><a:gsLst><a:gs pos="0"><a:schemeClr val="phClr"><a:tint val="50000" /><a:satMod val="300000" /></a:schemeClr></a:gs><a:gs pos="35000"><a:schemeClr val="phClr"><a:tint val="37000" /><a:satMod val="300000" /></a:schemeClr></a:gs><a:gs pos="100000"><a:schemeClr val="phClr"><a:tint val="15000" /><a:satMod val="350000" /></a:schemeClr></a:gs></a:gsLst><a:lin ang="16200000" scaled="1" /></a:gradFill><a:gradFill rotWithShape="1"><a:gsLst><a:gs pos="0"><a:schemeClr val="phClr"><a:tint val="100000" /><a:shade val="100000" /><a:satMod val="130000" /></a:schemeClr></a:gs><a:gs pos="100000"><a:schemeClr val="phClr"><a:tint val="50000" /><a:shade val="100000" /><a:satMod val="350000" /></a:schemeClr></a:gs></a:gsLst><a:lin ang="16200000" scaled="0" /></a:gradFill></a:fillStyleLst><a:lnStyleLst><a:ln w="9525" cap="flat" cmpd="sng" algn="ctr"><a:solidFill><a:schemeClr val="phClr"><a:shade val="95000" /><a:satMod val="105000" /></a:schemeClr></a:solidFill><a:prstDash val="solid" /></a:ln><a:ln w="25400" cap="flat" cmpd="sng" algn="ctr"><a:solidFill><a:schemeClr val="phClr" /></a:solidFill><a:prstDash val="solid" /></a:ln><a:ln w="38100" cap="flat" cmpd="sng" algn="ctr"><a:solidFill><a:schemeClr val="phClr" /></a:solidFill><a:prstDash val="solid" /></a:ln></a:lnStyleLst><a:effectStyleLst><a:effectStyle><a:effectLst><a:outerShdw blurRad="40000" dist="20000" dir="5400000" rotWithShape="0"><a:srgbClr val="000000"><a:alpha val="38000" /></a:srgbClr></a:outerShdw></a:effectLst></a:effectStyle><a:effectStyle><a:effectLst><a:outerShdw blurRad="40000" dist="23000" dir="5400000" rotWithShape="0"><a:srgbClr val="000000"><a:alpha val="35000" /></a:srgbClr></a:outerShdw></a:effectLst></a:effectStyle><a:effectStyle><a:effectLst><a:outerShdw blurRad="40000" dist="23000" dir="5400000" rotWithShape="0"><a:srgbClr val="000000"><a:alpha val="35000" /></a:srgbClr></a:outerShdw></a:effectLst><a:scene3d><a:camera prst="orthographicFront"><a:rot lat="0" lon="0" rev="0" /></a:camera><a:lightRig rig="threePt" dir="t"><a:rot lat="0" lon="0" rev="1200000" /></a:lightRig></a:scene3d><a:sp3d><a:bevelT w="63500" h="25400" /></a:sp3d></a:effectStyle></a:effectStyleLst><a:bgFillStyleLst><a:solidFill><a:schemeClr val="phClr" /></a:solidFill><a:gradFill rotWithShape="1"><a:gsLst><a:gs pos="0"><a:schemeClr val="phClr"><a:tint val="40000" /><a:satMod val="350000" /></a:schemeClr></a:gs><a:gs pos="40000"><a:schemeClr val="phClr"><a:tint val="45000" /><a:shade val="99000" /><a:satMod val="350000" /></a:schemeClr></a:gs><a:gs pos="100000"><a:schemeClr val="phClr"><a:shade val="20000" /><a:satMod val="255000" /></a:schemeClr></a:gs></a:gsLst><a:path path="circle"><a:fillToRect l="50000" t="-80000" r="50000" b="180000" /></a:path></a:gradFill><a:gradFill rotWithShape="1"><a:gsLst><a:gs pos="0"><a:schemeClr val="phClr"><a:tint val="80000" /><a:satMod val="300000" /></a:schemeClr></a:gs><a:gs pos="100000"><a:schemeClr val="phClr"><a:shade val="30000" /><a:satMod val="200000" /></a:schemeClr></a:gs></a:gsLst><a:path path="circle"><a:fillToRect l="50000" t="50000" r="50000" b="50000" /></a:path></a:gradFill></a:bgFillStyleLst></a:fmtScheme></a:themeElements><a:objectDefaults><a:spDef><a:spPr /><a:bodyPr /><a:lstStyle /><a:style><a:lnRef idx="1"><a:schemeClr val="accent1" /></a:lnRef><a:fillRef idx="3"><a:schemeClr val="accent1" /></a:fillRef><a:effectRef idx="2"><a:schemeClr val="accent1" /></a:effectRef><a:fontRef idx="minor"><a:schemeClr val="lt1" /></a:fontRef></a:style></a:spDef><a:lnDef><a:spPr /><a:bodyPr /><a:lstStyle /><a:style><a:lnRef idx="2"><a:schemeClr val="accent1" /></a:lnRef><a:fillRef idx="0"><a:schemeClr val="accent1" /></a:fillRef><a:effectRef idx="1"><a:schemeClr val="accent1" /></a:effectRef><a:fontRef idx="minor"><a:schemeClr val="tx1" /></a:fontRef></a:style></a:lnDef></a:objectDefaults><a:extraClrSchemeLst /></a:theme>
+<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
+<a:theme xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" name="Office Theme">
+  <a:themeElements>
+    <a:clrScheme name="Office">
+      <a:dk1>
+        <a:sysClr val="windowText" lastClr="000000"/>
+      </a:dk1>
+      <a:lt1>
+        <a:sysClr val="window" lastClr="FFFFFF"/>
+      </a:lt1>
+      <a:dk2>
+        <a:srgbClr val="0E2841"/>
+      </a:dk2>
+      <a:lt2>
+        <a:srgbClr val="E8E8E8"/>
+      </a:lt2>
+      <a:accent1>
+        <a:srgbClr val="156082"/>
+      </a:accent1>
+      <a:accent2>
+        <a:srgbClr val="E97132"/>
+      </a:accent2>
+      <a:accent3>
+        <a:srgbClr val="196B24"/>
+      </a:accent3>
+      <a:accent4>
+        <a:srgbClr val="0F9ED5"/>
+      </a:accent4>
+      <a:accent5>
+        <a:srgbClr val="A02B93"/>
+      </a:accent5>
+      <a:accent6>
+        <a:srgbClr val="4EA72E"/>
+      </a:accent6>
+      <a:hlink>
+        <a:srgbClr val="467886"/>
+      </a:hlink>
+      <a:folHlink>
+        <a:srgbClr val="96607D"/>
+      </a:folHlink>
+    </a:clrScheme>
+    <a:fontScheme name="Office">
+      <a:majorFont>
+        <a:latin typeface="Aptos Display" panose="02110004020202020204"/>
+        <a:ea typeface=""/>
+        <a:cs typeface=""/>
+        <a:font script="Jpan" typeface="游ゴシック Light"/>
+        <a:font script="Hang" typeface="맑은 고딕"/>
+        <a:font script="Hans" typeface="等线 Light"/>
+        <a:font script="Hant" typeface="新細明體"/>
+        <a:font script="Arab" typeface="Times New Roman"/>
+        <a:font script="Hebr" typeface="Times New Roman"/>
+        <a:font script="Thai" typeface="Angsana New"/>
+        <a:font script="Ethi" typeface="Nyala"/>
+        <a:font script="Beng" typeface="Vrinda"/>
+        <a:font script="Gujr" typeface="Shruti"/>
+        <a:font script="Khmr" typeface="MoolBoran"/>
+        <a:font script="Knda" typeface="Tunga"/>
+        <a:font script="Guru" typeface="Raavi"/>
+        <a:font script="Cans" typeface="Euphemia"/>
+        <a:font script="Cher" typeface="Plantagenet Cherokee"/>
+        <a:font script="Yiii" typeface="Microsoft Yi Baiti"/>
+        <a:font script="Tibt" typeface="Microsoft Himalaya"/>
+        <a:font script="Thaa" typeface="MV Boli"/>
+        <a:font script="Deva" typeface="Mangal"/>
+        <a:font script="Telu" typeface="Gautami"/>
+        <a:font script="Taml" typeface="Latha"/>
+        <a:font script="Syrc" typeface="Estrangelo Edessa"/>
+        <a:font script="Orya" typeface="Kalinga"/>
+        <a:font script="Mlym" typeface="Kartika"/>
+        <a:font script="Laoo" typeface="DokChampa"/>
+        <a:font script="Sinh" typeface="Iskoola Pota"/>
+        <a:font script="Mong" typeface="Mongolian Baiti"/>
+        <a:font script="Viet" typeface="Times New Roman"/>
+        <a:font script="Uigh" typeface="Microsoft Uighur"/>
+        <a:font script="Geor" typeface="Sylfaen"/>
+        <a:font script="Armn" typeface="Arial"/>
+        <a:font script="Bugi" typeface="Leelawadee UI"/>
+        <a:font script="Bopo" typeface="Microsoft JhengHei"/>
+        <a:font script="Java" typeface="Javanese Text"/>
+        <a:font script="Lisu" typeface="Segoe UI"/>
+        <a:font script="Mymr" typeface="Myanmar Text"/>
+        <a:font script="Nkoo" typeface="Ebrima"/>
+        <a:font script="Olck" typeface="Nirmala UI"/>
+        <a:font script="Osma" typeface="Ebrima"/>
+        <a:font script="Phag" typeface="Phagspa"/>
+        <a:font script="Syrn" typeface="Estrangelo Edessa"/>
+        <a:font script="Syrj" typeface="Estrangelo Edessa"/>
+        <a:font script="Syre" typeface="Estrangelo Edessa"/>
+        <a:font script="Sora" typeface="Nirmala UI"/>
+        <a:font script="Tale" typeface="Microsoft Tai Le"/>
+        <a:font script="Talu" typeface="Microsoft New Tai Lue"/>
+        <a:font script="Tfng" typeface="Ebrima"/>
+      </a:majorFont>
+      <a:minorFont>
+        <a:latin typeface="Aptos" panose="02110004020202020204"/>
+        <a:ea typeface=""/>
+        <a:cs typeface=""/>
+        <a:font script="Jpan" typeface="游明朝"/>
+        <a:font script="Hang" typeface="맑은 고딕"/>
+        <a:font script="Hans" typeface="等线"/>
+        <a:font script="Hant" typeface="新細明體"/>
+        <a:font script="Arab" typeface="Arial"/>
+        <a:font script="Hebr" typeface="Arial"/>
+        <a:font script="Thai" typeface="Cordia New"/>
+        <a:font script="Ethi" typeface="Nyala"/>
+        <a:font script="Beng" typeface="Vrinda"/>
+        <a:font script="Gujr" typeface="Shruti"/>
+        <a:font script="Khmr" typeface="DaunPenh"/>
+        <a:font script="Knda" typeface="Tunga"/>
+        <a:font script="Guru" typeface="Raavi"/>
+        <a:font script="Cans" typeface="Euphemia"/>
+        <a:font script="Cher" typeface="Plantagenet Cherokee"/>
+        <a:font script="Yiii" typeface="Microsoft Yi Baiti"/>
+        <a:font script="Tibt" typeface="Microsoft Himalaya"/>
+        <a:font script="Thaa" typeface="MV Boli"/>
+        <a:font script="Deva" typeface="Mangal"/>
+        <a:font script="Telu" typeface="Gautami"/>
+        <a:font script="Taml" typeface="Latha"/>
+        <a:font script="Syrc" typeface="Estrangelo Edessa"/>
+        <a:font script="Orya" typeface="Kalinga"/>
+        <a:font script="Mlym" typeface="Kartika"/>
+        <a:font script="Laoo" typeface="DokChampa"/>
+        <a:font script="Sinh" typeface="Iskoola Pota"/>
+        <a:font script="Mong" typeface="Mongolian Baiti"/>
+        <a:font script="Viet" typeface="Arial"/>
+        <a:font script="Uigh" typeface="Microsoft Uighur"/>
+        <a:font script="Geor" typeface="Sylfaen"/>
+        <a:font script="Armn" typeface="Arial"/>
+        <a:font script="Bugi" typeface="Leelawadee UI"/>
+        <a:font script="Bopo" typeface="Microsoft JhengHei"/>
+        <a:font script="Java" typeface="Javanese Text"/>
+        <a:font script="Lisu" typeface="Segoe UI"/>
+        <a:font script="Mymr" typeface="Myanmar Text"/>
+        <a:font script="Nkoo" typeface="Ebrima"/>
+        <a:font script="Olck" typeface="Nirmala UI"/>
+        <a:font script="Osma" typeface="Ebrima"/>
+        <a:font script="Phag" typeface="Phagspa"/>
+        <a:font script="Syrn" typeface="Estrangelo Edessa"/>
+        <a:font script="Syrj" typeface="Estrangelo Edessa"/>
+        <a:font script="Syre" typeface="Estrangelo Edessa"/>
+        <a:font script="Sora" typeface="Nirmala UI"/>
+        <a:font script="Tale" typeface="Microsoft Tai Le"/>
+        <a:font script="Talu" typeface="Microsoft New Tai Lue"/>
+        <a:font script="Tfng" typeface="Ebrima"/>
+      </a:minorFont>
+    </a:fontScheme>
+    <a:fmtScheme name="Office">
+      <a:fillStyleLst>
+        <a:solidFill>
+          <a:schemeClr val="phClr"/>
+        </a:solidFill>
+        <a:gradFill rotWithShape="1">
+          <a:gsLst>
+            <a:gs pos="0">
+              <a:schemeClr val="phClr">
+                <a:lumMod val="110000"/>
+                <a:satMod val="105000"/>
+                <a:tint val="67000"/>
+              </a:schemeClr>
+            </a:gs>
+            <a:gs pos="50000">
+              <a:schemeClr val="phClr">
+                <a:lumMod val="105000"/>
+                <a:satMod val="103000"/>
+                <a:tint val="73000"/>
+              </a:schemeClr>
+            </a:gs>
+            <a:gs pos="100000">
+              <a:schemeClr val="phClr">
+                <a:lumMod val="105000"/>
+                <a:satMod val="109000"/>
+                <a:tint val="81000"/>
+              </a:schemeClr>
+            </a:gs>
+          </a:gsLst>
+          <a:lin ang="5400000" scaled="0"/>
+        </a:gradFill>
+        <a:gradFill rotWithShape="1">
+          <a:gsLst>
+            <a:gs pos="0">
+              <a:schemeClr val="phClr">
+                <a:satMod val="103000"/>
+                <a:lumMod val="102000"/>
+                <a:tint val="94000"/>
+              </a:schemeClr>
+            </a:gs>
+            <a:gs pos="50000">
+              <a:schemeClr val="phClr">
+                <a:satMod val="110000"/>
+                <a:lumMod val="100000"/>
+                <a:shade val="100000"/>
+              </a:schemeClr>
+            </a:gs>
+            <a:gs pos="100000">
+              <a:schemeClr val="phClr">
+                <a:lumMod val="99000"/>
+                <a:satMod val="120000"/>
+                <a:shade val="78000"/>
+              </a:schemeClr>
+            </a:gs>
+          </a:gsLst>
+          <a:lin ang="5400000" scaled="0"/>
+        </a:gradFill>
+      </a:fillStyleLst>
+      <a:lnStyleLst>
+        <a:ln w="6350" cap="flat" cmpd="sng" algn="ctr">
+          <a:solidFill>
+            <a:schemeClr val="phClr"/>
+          </a:solidFill>
+          <a:prstDash val="solid"/>
+          <a:miter lim="800000"/>
+        </a:ln>
+        <a:ln w="12700" cap="flat" cmpd="sng" algn="ctr">
+          <a:solidFill>
+            <a:schemeClr val="phClr"/>
+          </a:solidFill>
+          <a:prstDash val="solid"/>
+          <a:miter lim="800000"/>
+        </a:ln>
+        <a:ln w="19050" cap="flat" cmpd="sng" algn="ctr">
+          <a:solidFill>
+            <a:schemeClr val="phClr"/>
+          </a:solidFill>
+          <a:prstDash val="solid"/>
+          <a:miter lim="800000"/>
+        </a:ln>
+      </a:lnStyleLst>
+      <a:effectStyleLst>
+        <a:effectStyle>
+          <a:effectLst/>
+        </a:effectStyle>
+        <a:effectStyle>
+          <a:effectLst/>
+        </a:effectStyle>
+        <a:effectStyle>
+          <a:effectLst>
+            <a:outerShdw blurRad="57150" dist="19050" dir="5400000" algn="ctr" rotWithShape="0">
+              <a:srgbClr val="000000">
+                <a:alpha val="63000"/>
+              </a:srgbClr>
+            </a:outerShdw>
+          </a:effectLst>
+        </a:effectStyle>
+      </a:effectStyleLst>
+      <a:bgFillStyleLst>
+        <a:solidFill>
+          <a:schemeClr val="phClr"/>
+        </a:solidFill>
+        <a:solidFill>
+          <a:schemeClr val="phClr">
+            <a:tint val="95000"/>
+            <a:satMod val="170000"/>
+          </a:schemeClr>
+        </a:solidFill>
+        <a:gradFill rotWithShape="1">
+          <a:gsLst>
+            <a:gs pos="0">
+              <a:schemeClr val="phClr">
+                <a:tint val="93000"/>
+                <a:satMod val="150000"/>
+                <a:shade val="98000"/>
+                <a:lumMod val="102000"/>
+              </a:schemeClr>
+            </a:gs>
+            <a:gs pos="50000">
+              <a:schemeClr val="phClr">
+                <a:tint val="98000"/>
+                <a:satMod val="130000"/>
+                <a:shade val="90000"/>
+                <a:lumMod val="103000"/>
+              </a:schemeClr>
+            </a:gs>
+            <a:gs pos="100000">
+              <a:schemeClr val="phClr">
+                <a:shade val="63000"/>
+                <a:satMod val="120000"/>
+              </a:schemeClr>
+            </a:gs>
+          </a:gsLst>
+          <a:lin ang="5400000" scaled="0"/>
+        </a:gradFill>
+      </a:bgFillStyleLst>
+    </a:fmtScheme>
+  </a:themeElements>
+  <a:objectDefaults/>
+  <a:extraClrSchemeLst/>
+  <a:extLst>
+    <a:ext uri="{05A4C25C-085E-4340-85A3-A5531E510DB2}">
+      <thm15:themeFamily xmlns:thm15="http://schemas.microsoft.com/office/thememl/2012/main" name="Office Theme" id="{2E142A2C-CD16-42D6-873A-C26D2A0506FA}" vid="{1BDDFF52-6CD6-40A5-AB3C-68EB2F1E4D0A}"/>
+    </a:ext>
+  </a:extLst>
+</a:theme>
diff --git a/data/epub.css b/data/epub.css
--- a/data/epub.css
+++ b/data/epub.css
@@ -1,18 +1,217 @@
 /* This defines styles and classes used in the book */
-body { margin: 5%; text-align: justify; font-size: medium; }
-code { font-family: monospace; }
-h1 { text-align: left; }
-h2 { text-align: left; }
-h3 { text-align: left; }
-h4 { text-align: left; }
-h5 { text-align: left; }
-h6 { text-align: left; }
+@page {
+  margin: 10px;
+}
+html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p,
+blockquote, pre, a, abbr, acronym, address, big, cite, code, del, dfn, em, img,
+ins, kbd, q, s, samp, small, strike, strong, sub, sup, tt, var, b, u, i, center,
+fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td,
+article, aside, canvas, details, embed, figure, figcaption, footer, header,
+hgroup, menu, nav, output, ruby, section, summary, time, mark, audio, video, ol,
+ul, li, dl, dt, dd {
+  margin: 0;
+  padding: 0;
+  border: 0;
+  font-size: 100%;
+  vertical-align: baseline;
+}
+html {
+  line-height: 1.2;
+  font-family: Georgia, serif;
+  color: #1a1a1a;
+}
+p {
+  text-indent: 0;
+  margin: 1em 0;
+  widows: 2;
+  orphans: 2;
+}
+img {
+  max-width: 100%;
+}
+sup {
+  vertical-align: super;
+  font-size: smaller;
+}
+sub {
+  vertical-align: sub;
+  font-size: smaller;
+}
+h1 {
+  margin: 3em 0 0 0;
+  font-size: 2em;
+  page-break-before: always;
+  line-height: 150%;
+}
+h2 {
+  margin: 1.5em 0 0 0;
+  font-size: 1.5em;
+  line-height: 135%;
+}
+h3 {
+  margin: 1.3em 0 0 0;
+  font-size: 1.3em;
+}
+h4 {
+  margin: 1.2em 0 0 0;
+  font-size: 1.2em;
+}
+h5 {
+  margin: 1.1em 0 0 0;
+  font-size: 1.1em;
+}
+h6 {
+  font-size: 1em;
+}
+h1, h2, h3, h4, h5, h6 {
+  text-indent: 0;
+  text-align: left;
+  font-weight: bold;
+  page-break-after: avoid;
+  page-break-inside: avoid;
+}
+
+ol, ul {
+  margin: 1em 0 0 1.7em;
+}
+li > ol, li > ul {
+  margin-top: 0;
+}
+blockquote {
+  margin: 1em 0 1em 1.7em;
+}
+code {
+  font-family: Menlo, Monaco, 'Lucida Console', Consolas, monospace;
+  font-size: 85%;
+  margin: 0;
+  hyphens: manual;
+}
+pre {
+  margin: 1em 0;
+  overflow: auto;
+}
+pre code {
+  padding: 0;
+  overflow: visible;
+  overflow-wrap: normal;
+}
+.sourceCode {
+  background-color: transparent;
+  overflow: visible;
+}
+hr {
+  background-color: #1a1a1a;
+  border: none;
+  height: 1px;
+  margin: 1em 0;
+}
+table {
+  margin: 1em 0;
+  border-collapse: collapse;
+  width: 100%;
+  overflow-x: auto;
+  display: block;
+}
+table caption {
+  margin-bottom: 0.75em;
+}
+tbody {
+  margin-top: 0.5em;
+  border-top: 1px solid #1a1a1a;
+  border-bottom: 1px solid #1a1a1a;
+}
+th, td {
+  padding: 0.25em 0.5em 0.25em 0.5em;
+}
+th {
+  border-top: 1px solid #1a1a1a;
+}
+header {
+  margin-bottom: 4em;
+  text-align: center;
+}
+#TOC li {
+  list-style: none;
+}
+#TOC ul {
+  padding-left: 1.3em;
+}
+#TOC > ul {
+  padding-left: 0;
+}
+#TOC a:not(:hover) {
+  text-decoration: none;
+}
+code {
+  white-space: pre-wrap;
+}
+span.smallcaps {
+  font-variant: small-caps;
+}
+
+/* This is the most compatible CSS, but it only allows two columns: */
+div.column {
+  display: inline-block;
+  vertical-align: top;
+  width: 50%;
+}
+/* If you can rely on CSS3 support, use this instead: */
+/* div.columns {
+  display: flex;
+  gap: min(4vw, 1.5em);
+}
+div.column {
+  flex: auto;
+  overflow-x: auto;
+} */
+
+div.hanging-indent {
+  margin-left: 1.5em;
+  text-indent: -1.5em;
+}
+ul.task-list {
+  list-style: none;
+}
+ul.task-list li input[type="checkbox"] {
+  width: 0.8em;
+  margin: 0 0.8em 0.2em -1.6em;
+  vertical-align: middle;
+}
+.display.math {
+  display: block;
+  text-align: center;
+  margin: 0.5rem auto;
+}
+
+/* For title, author, and date on the cover page */
 h1.title { }
-h2.author { }
-h3.date { }
-ol.toc { padding: 0; margin-left: 1em; }
-ol.toc li { list-style-type: none; margin: 0; padding: 0; }
-a.footnote-ref { vertical-align: super; }
-em, em em em, em em em em em { font-style: italic;}
-em em, em em em em { font-style: normal; }
+p.author { }
+p.date { }
 
+nav#toc ol, nav#landmarks ol {
+  padding: 0;
+  margin-left: 1em;
+}
+nav#toc ol li, nav#landmarks ol li {
+  list-style-type: none;
+  margin: 0;
+  padding: 0;
+}
+a.footnote-ref {
+  vertical-align: super;
+}
+em, em em em, em em em em em {
+  font-style: italic;
+}
+em em, em em em em {
+  font-style: normal;
+}
+q {
+  quotes: "“" "”" "‘" "’";
+}
+@media screen { /* Workaround for iBooks issue; see #6242 */
+  .sourceCode {
+    overflow: visible !important;
+    white-space: pre-wrap !important;
+  }
+}
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/jats.csl b/data/jats.csl
deleted file mode 100644
--- a/data/jats.csl
+++ /dev/null
@@ -1,205 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<style xmlns="http://purl.org/net/xbiblio/csl" class="in-text" version="1.0" default-locale="en-US">
-  <info>
-    <title>Journal Article Tag Suite</title>
-    <title-short>JATS</title-short>
-    <id>http://www.zotero.org/styles/journal-article-tag-suite</id>
-    <link href="https://github.com/MartinPaulEve/JATS-CSL/blob/master/jats.csl" rel="self"/>
-    <link rel="documentation" href="http://jats.nlm.nih.gov/archiving/tag-library/1.0/index.html"/>
-    <author>
-      <name>Martin Paul Eve</name>
-      <email>martin@martineve.com</email>
-    </author>
-    <category citation-format="numeric"/>
-    <category field="medicine"/>
-    <category field="biology"/>
-    <summary>Use this style to generate bibliographic data in Journal Article Tagging Suite (JATS) 1.0 XML format</summary>
-    <updated>2014-06-21T17:41:26+00:00</updated>
-    <rights license="http://creativecommons.org/licenses/by-sa/3.0/">This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 License. Originally by Martin Fenner.</rights>
-  </info>
-  <locale xml:lang="en">
-    <terms>
-        <term name="et-al">{{jats}}&lt;etal/&gt;{{/jats}}</term>
-    </terms>
-  </locale>
-  <macro name="citation-number">
-    <text variable="citation-number" prefix="{{jats}}id=&quot;ref-{{/jats}}" suffix="{{jats}}&quot;&gt;{{/jats}}"/>
-  </macro>
-  <macro name="author">
-    <names variable="author">
-        <name prefix="{{jats}}&lt;name&gt;{{/jats}}" suffix="{{jats}}&lt;/name&gt;{{/jats}}" name-as-sort-order="all" sort-separator="">
-            <name-part name="family" text-case="capitalize-first" prefix="{{jats}}&lt;surname&gt;{{/jats}}" suffix="{{jats}}&lt;/surname&gt;{{/jats}}"/>
-            <name-part name="given" text-case="capitalize-first" prefix="{{jats}}&lt;given-names&gt;{{/jats}}" suffix="{{jats}}&lt;/given-names&gt;{{/jats}}"/>
-      </name>
-      <substitute>
-        <names variable="editor"/>
-      </substitute>
-    </names>
-  </macro>
-
-  <macro name="editor">
-    <names variable="editor" prefix="{{jats}}&lt;person-group person-group-type=&quot;editor&quot;&gt;{{/jats}}" suffix="{{jats}}&lt;/person-group&gt;{{/jats}}">
-      <name prefix="{{jats}}&lt;name&gt;{{/jats}}" suffix="{{jats}}&lt;/name&gt;{{/jats}}" name-as-sort-order="all" sort-separator="">
-        <name-part name="family" text-case="capitalize-first" prefix="{{jats}}&lt;surname&gt;{{/jats}}" suffix="{{jats}}&lt;/surname&gt;{{/jats}}"/>
-        <name-part name="given" text-case="capitalize-first" prefix="{{jats}}&lt;given-names&gt;{{/jats}}" suffix="{{jats}}&lt;/given-names&gt;{{/jats}}"/>
-      </name>
-      <substitute>
-        <names variable="editor"/>
-      </substitute>
-    </names>
-  </macro>
-
-  <macro name="editor">
-    <group delimiter=": ">
-      <names variable="editor">
-        <name prefix="{{jats}}&lt;name&gt;{{/jats}}" suffix="{{jats}}&lt;/name&gt;{{/jats}}" name-as-sort-order="all" sort-separator="">
-          <name-part name="family" text-case="capitalize-first" prefix="{{jats}}&lt;surname&gt;{{/jats}}" suffix="{{jats}}&lt;/surname&gt;{{/jats}}"/>
-          <name-part name="given" text-case="capitalize-first" prefix="{{jats}}&lt;given-names&gt;{{/jats}}" suffix="{{jats}}&lt;given-names&gt;{{/jats}}"/>
-        </name>
-      </names>
-    </group>
-  </macro>
-  <macro name="title">
-    <choose>
-      <if type="book" match="any">
-        <group prefix="{{jats}}&lt;source&gt;{{/jats}}" suffix="{{jats}}&lt;/source&gt;{{/jats}}">
-	        <text variable="title"/>
-				</group>			
-			</if>
-      <else>
-        <group prefix="{{jats}}&lt;article-title&gt;{{/jats}}" suffix="{{jats}}&lt;/article-title&gt;{{/jats}}">
-	        <text variable="title"/>
-				</group>
-      </else>
-    </choose>
-  </macro>
-  <macro name="container-title">
-    <text variable="container-title" form="short" prefix="{{jats}}&lt;source&gt;{{/jats}}" suffix="{{jats}}&lt;/source&gt;{{/jats}}"/>
-  </macro>
-  <macro name="publisher">
-    <text variable="publisher" prefix="{{jats}}&lt;publisher-name&gt;{{/jats}}" suffix="{{jats}}&lt;/publisher-name&gt;{{/jats}}"/>
-    <text variable="publisher-place" prefix="{{jats}}&lt;publisher-loc&gt;{{/jats}}" suffix="{{jats}}&lt;/publisher-loc&gt;{{/jats}}"/>
-  </macro>
-  <macro name="link">
-    <choose>
-      <if match="any" variable="DOI">
-        <group prefix="{{jats}}&lt;pub-id pub-id-type=&quot;doi&quot;&gt;{{/jats}}" suffix="{{jats}}&lt;/pub-id&gt;{{/jats}}">
-          <text variable="DOI"/>
-        </group>
-      </if>
-    </choose>
-    <choose>
-      <if match="any" variable="PMID">
-        <group prefix="{{jats}}&lt;ext-link ext-link-type=&quot;pmid&quot; {{/jats}}" suffix="{{jats}}&lt;/ext-link&gt;{{/jats}}">
-          <text variable="PMID" prefix="{{jats}}xlink:href=&quot;http://www.ncbi.nlm.nih.gov/pubmed/{{/jats}}" suffix="{{jats}}&quot; xlink:type=&quot;simple&quot;&gt;{{/jats}}"/>
-          <text variable="PMID"/>
-        </group>
-      </if>
-    </choose>
-    <choose>
-      <if variable="URL" match="any">
-        <text variable="URL" />
-      </if>
-    </choose>
-  </macro>
-  <macro name="date">
-    <choose>
-      <if type="article-journal article-magazine article-newspaper report patent book" match="any">
-        <group prefix="{{jats}}&lt;date&gt;{{/jats}}" suffix="{{jats}}&lt;/date&gt;{{/jats}}">
-          <date variable="issued">
-            <date-part name="day" form="numeric-leading-zeros" prefix="{{jats}}&lt;day&gt;{{/jats}}" suffix="{{jats}}&lt;/day&gt;{{/jats}}"/>
-            <date-part name="month" form="numeric-leading-zeros" prefix="{{jats}}&lt;month&gt;{{/jats}}" suffix="{{jats}}&lt;/month&gt;{{/jats}}"/>
-            <date-part name="year" prefix="{{jats}}&lt;year&gt;{{/jats}}" suffix="{{jats}}&lt;/year&gt;{{/jats}}"/>
-          </date>
-        </group>
-      </if>
-      <else>
-        <group prefix="{{jats}}&lt;date-in-citation content-type=&quot;access-date&quot;{{/jats}}" suffix="{{jats}}&lt;/date-in-citation&gt;{{/jats}}">
-          <date variable="accessed" prefix="{{jats}} iso-8601-date=&quot;{{/jats}}" suffix="{{jats}}&quot;&gt;{{/jats}}">
-            <date-part name="year"/>
-            <date-part name="month" form="numeric-leading-zeros" prefix="{{jats}}-{{/jats}}"/>
-            <date-part name="day" form="numeric-leading-zeros" prefix="{{jats}}-{{/jats}}"/>
-          </date>
-          <date variable="accessed">
-            <date-part name="day" prefix="{{jats}}&lt;day&gt;{{/jats}}" suffix="{{jats}}&lt;/day&gt;{{/jats}}"/>
-            <date-part name="month" form="numeric-leading-zeros" prefix="{{jats}}&lt;month&gt;{{/jats}}" suffix="{{jats}}&lt;/month&gt;{{/jats}}"/>
-            <date-part name="year" prefix="{{jats}}&lt;year&gt;{{/jats}}" suffix="{{jats}}&lt;/year&gt;{{/jats}}"/>
-          </date>
-        </group>
-      </else>
-    </choose>
-  </macro>
-  <macro name="location">
-    <choose>
-      <if type="article-journal article-magazine" match="any">
-        <text variable="volume" prefix="{{jats}}&lt;volume&gt;{{/jats}}" suffix="{{jats}}&lt;/volume&gt;{{/jats}}"/>
-        <text variable="issue" prefix="{{jats}}&lt;issue&gt;{{/jats}}" suffix="{{jats}}&lt;/issue&gt;{{/jats}}"/>
-      </if>
-    </choose>
-    <choose>
-      <if type="article-journal article-magazine article-newspaper chapter" match="any">
-        <text variable="page-first" prefix="{{jats}}&lt;fpage&gt;{{/jats}}" suffix="{{jats}}&lt;/fpage&gt;{{/jats}}"/>
-      </if>
-    </choose>
-  </macro>
-  <macro name="publication-type">
-    <group prefix="{{jats}} publication-type=&quot;{{/jats}}" suffix="{{jats}}&quot;&gt;{{/jats}}">
-      <choose>
-        <if type="article-journal article-magazine article-newspaper" match="any">
-          <text value="journal"/>
-        </if>
-        <else-if type="book" match="any">
-          <text value="book"/>
-        </else-if>
-        <else-if type="chapter" match="any">
-          <text value="bookchapter"/>
-        </else-if>
-        <else-if type="dataset" match="any">
-          <text value="dataset"/>
-        </else-if>
-        <else-if type="patent" match="any">
-          <text value="patent"/>
-        </else-if>
-        <else-if type="report" match="any">
-          <text value="report"/>
-        </else-if>
-        <else-if type="review" match="any">
-          <text value="review"/>
-        </else-if>
-        <else>
-          <text value="standard"/>
-        </else>
-      </choose>
-    </group>
-  </macro>
-  <citation collapse="citation-number">
-    <sort>
-      <key variable="citation-number"/>
-    </sort>
-    <layout delimiter=",">
-      <group prefix="{{jats}}&lt;xref ref-type=&quot;bibr&quot; rid=&quot;{{/jats}}" suffix="{{jats}}&lt;/xref&gt;{{/jats}}">
-        <text variable="citation-number" prefix="{{jats}}ref-{{/jats}}" suffix="{{jats}}&quot;&gt;{{/jats}}"/>
-        <text variable="citation-number"/>
-      </group>
-    </layout>
-  </citation>
-  <bibliography sort-separator="">
-    <layout>
-      <group prefix="{{jats}}&lt;ref {{/jats}}" suffix="{{jats}}&lt;/ref&gt;{{/jats}}">
-        <text macro="citation-number"/>
-        <group prefix="{{jats}}&lt;element-citation{{/jats}}" suffix="{{jats}}&lt;/element-citation&gt;{{/jats}}">
-          <text macro="publication-type"/>
-          <text macro="author" prefix="{{jats}}&lt;person-group person-group-type=&quot;author&quot;&gt;{{/jats}}" suffix="{{jats}}&lt;/person-group&gt;{{/jats}}"/>
-          <text macro="title" />
-          <text macro="container-title"/>
-          <text macro="editor"/>
-          <text macro="publisher"/>
-          <text macro="date"/>
-          <text macro="location"/>
-          <text macro="link"/>
-        </group>
-      </group>
-    </layout>
-  </bibliography>
-</style>
-
diff --git a/data/odt/Configurations2/accelerator/current.xml b/data/odt/Configurations2/accelerator/current.xml
deleted file mode 100644
--- a/data/odt/Configurations2/accelerator/current.xml
+++ /dev/null
diff --git a/data/odt/META-INF/manifest.xml b/data/odt/META-INF/manifest.xml
--- a/data/odt/META-INF/manifest.xml
+++ b/data/odt/META-INF/manifest.xml
@@ -1,12 +1,8 @@
 <?xml version="1.0" encoding="UTF-8"?>
-<manifest:manifest xmlns:manifest="urn:oasis:names:tc:opendocument:xmlns:manifest:1.0" manifest:version="1.2">
- <manifest:file-entry manifest:full-path="/" manifest:version="1.2" manifest:media-type="application/vnd.oasis.opendocument.text"/>
+<manifest:manifest xmlns:manifest="urn:oasis:names:tc:opendocument:xmlns:manifest:1.0" manifest:version="1.3">
+ <manifest:file-entry manifest:full-path="/" manifest:version="1.3" manifest:media-type="application/vnd.oasis.opendocument.text"/>
  <manifest:file-entry manifest:full-path="meta.xml" manifest:media-type="text/xml"/>
- <manifest:file-entry manifest:full-path="settings.xml" manifest:media-type="text/xml"/>
  <manifest:file-entry manifest:full-path="content.xml" manifest:media-type="text/xml"/>
- <manifest:file-entry manifest:full-path="Thumbnails/thumbnail.png" manifest:media-type="image/png"/>
  <manifest:file-entry manifest:full-path="manifest.rdf" manifest:media-type="application/rdf+xml"/>
- <manifest:file-entry manifest:full-path="Configurations2/accelerator/current.xml" manifest:media-type=""/>
- <manifest:file-entry manifest:full-path="Configurations2/" manifest:media-type="application/vnd.sun.xml.ui.configuration"/>
  <manifest:file-entry manifest:full-path="styles.xml" manifest:media-type="text/xml"/>
 </manifest:manifest>
diff --git a/data/odt/Thumbnails/thumbnail.png b/data/odt/Thumbnails/thumbnail.png
deleted file mode 100644
Binary files a/data/odt/Thumbnails/thumbnail.png and /dev/null differ
diff --git a/data/odt/content.xml b/data/odt/content.xml
--- a/data/odt/content.xml
+++ b/data/odt/content.xml
@@ -1,2 +1,82 @@
 <?xml version="1.0" encoding="UTF-8"?>
-<office:document-content xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" xmlns:style="urn:oasis:names:tc:opendocument:xmlns:style:1.0" xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0" xmlns:table="urn:oasis:names:tc:opendocument:xmlns:table:1.0" xmlns:draw="urn:oasis:names:tc:opendocument:xmlns:drawing:1.0" xmlns:fo="urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:meta="urn:oasis:names:tc:opendocument:xmlns:meta:1.0" xmlns:number="urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0" xmlns:svg="urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0" xmlns:chart="urn:oasis:names:tc:opendocument:xmlns:chart:1.0" xmlns:dr3d="urn:oasis:names:tc:opendocument:xmlns:dr3d:1.0" xmlns:math="http://www.w3.org/1998/Math/MathML" xmlns:form="urn:oasis:names:tc:opendocument:xmlns:form:1.0" xmlns:script="urn:oasis:names:tc:opendocument:xmlns:script:1.0" xmlns:ooo="http://openoffice.org/2004/office" xmlns:ooow="http://openoffice.org/2004/writer" xmlns:oooc="http://openoffice.org/2004/calc" xmlns:dom="http://www.w3.org/2001/xml-events" xmlns:xforms="http://www.w3.org/2002/xforms" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:rpt="http://openoffice.org/2005/report" xmlns:of="urn:oasis:names:tc:opendocument:xmlns:of:1.2" xmlns:xhtml="http://www.w3.org/1999/xhtml" xmlns:grddl="http://www.w3.org/2003/g/data-view#" xmlns:officeooo="http://openoffice.org/2009/office" xmlns:tableooo="http://openoffice.org/2009/table" xmlns:drawooo="http://openoffice.org/2010/draw" xmlns:calcext="urn:org:documentfoundation:names:experimental:calc:xmlns:calcext:1.0" xmlns:field="urn:openoffice:names:experimental:ooo-ms-interop:xmlns:field:1.0" xmlns:formx="urn:openoffice:names:experimental:ooxml-odf-interop:xmlns:form:1.0" xmlns:css3t="http://www.w3.org/TR/css3-text/" office:version="1.2"><office:scripts/><office:font-face-decls><style:font-face style:name="StarSymbol" svg:font-family="StarSymbol"/><style:font-face style:name="Tahoma1" svg:font-family="Tahoma"/><style:font-face style:name="Courier New" svg:font-family="&apos;Courier New&apos;" style:font-family-generic="modern" style:font-pitch="fixed"/><style:font-face style:name="Times New Roman" svg:font-family="&apos;Times New Roman&apos;" style:font-family-generic="roman" style:font-pitch="variable"/><style:font-face style:name="Arial" svg:font-family="Arial" style:font-family-generic="swiss" style:font-pitch="variable"/><style:font-face style:name="Lucida Sans Unicode" svg:font-family="&apos;Lucida Sans Unicode&apos;" style:font-family-generic="system" style:font-pitch="variable"/><style:font-face style:name="Tahoma" svg:font-family="Tahoma" style:font-family-generic="system" style:font-pitch="variable"/></office:font-face-decls><office:automatic-styles><style:style style:name="P1" style:family="paragraph" style:parent-style-name="Footer"><style:paragraph-properties fo:text-align="center" style:justify-single-word="false"/></style:style></office:automatic-styles><office:body><office:text><text:sequence-decls><text:sequence-decl text:display-outline-level="0" text:name="Illustration"/><text:sequence-decl text:display-outline-level="0" text:name="Table"/><text:sequence-decl text:display-outline-level="0" text:name="Text"/><text:sequence-decl text:display-outline-level="0" text:name="Drawing"/></text:sequence-decls><text:p text:style-name="Standard">Hello World!</text:p></office:text></office:body></office:document-content>
+<office:document-content xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" xmlns:style="urn:oasis:names:tc:opendocument:xmlns:style:1.0" xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0" xmlns:table="urn:oasis:names:tc:opendocument:xmlns:table:1.0" xmlns:draw="urn:oasis:names:tc:opendocument:xmlns:drawing:1.0" xmlns:fo="urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:meta="urn:oasis:names:tc:opendocument:xmlns:meta:1.0" xmlns:number="urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0" xmlns:svg="urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0" xmlns:chart="urn:oasis:names:tc:opendocument:xmlns:chart:1.0" xmlns:dr3d="urn:oasis:names:tc:opendocument:xmlns:dr3d:1.0" xmlns:math="http://www.w3.org/1998/Math/MathML" xmlns:form="urn:oasis:names:tc:opendocument:xmlns:form:1.0" xmlns:script="urn:oasis:names:tc:opendocument:xmlns:script:1.0" xmlns:ooo="http://openoffice.org/2004/office" xmlns:ooow="http://openoffice.org/2004/writer" xmlns:oooc="http://openoffice.org/2004/calc" xmlns:dom="http://www.w3.org/2001/xml-events" xmlns:xforms="http://www.w3.org/2002/xforms" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:rpt="http://openoffice.org/2005/report" xmlns:of="urn:oasis:names:tc:opendocument:xmlns:of:1.2" xmlns:xhtml="http://www.w3.org/1999/xhtml" xmlns:grddl="http://www.w3.org/2003/g/data-view#" xmlns:officeooo="http://openoffice.org/2009/office" xmlns:tableooo="http://openoffice.org/2009/table" xmlns:drawooo="http://openoffice.org/2010/draw" xmlns:calcext="urn:org:documentfoundation:names:experimental:calc:xmlns:calcext:1.0" xmlns:field="urn:openoffice:names:experimental:ooo-ms-interop:xmlns:field:1.0" xmlns:formx="urn:openoffice:names:experimental:ooxml-odf-interop:xmlns:form:1.0" xmlns:css3t="http://www.w3.org/TR/css3-text/" office:version="1.3">
+  <office:scripts/>
+  <office:font-face-decls>
+    <style:font-face style:name="StarSymbol" svg:font-family="StarSymbol"/>
+    <style:font-face style:name="Tahoma1" svg:font-family="Tahoma"/>
+    <style:font-face style:name="Courier New" svg:font-family="&apos;Courier New&apos;" style:font-family-generic="modern" style:font-pitch="fixed"/>
+    <style:font-face style:name="Times New Roman" svg:font-family="&apos;Times New Roman&apos;" style:font-family-generic="roman" style:font-pitch="variable"/>
+    <style:font-face style:name="Arial" svg:font-family="Arial" style:font-family-generic="swiss" style:font-pitch="variable"/>
+    <style:font-face style:name="Lucida Sans Unicode" svg:font-family="&apos;Lucida Sans Unicode&apos;" style:font-family-generic="system" style:font-pitch="variable"/>
+    <style:font-face style:name="Tahoma" svg:font-family="Tahoma" style:font-family-generic="system" style:font-pitch="variable"/>
+  </office:font-face-decls>
+  <office:automatic-styles>
+    <style:style style:name="DemoTable" style:family="table">
+      <style:table-properties style:width="6in" table:align="margins"/>
+    </style:style>
+    <style:style style:name="DemoTable.A" style:family="table-column">
+      <style:table-column-properties style:column-width="3in"/>
+    </style:style>
+  </office:automatic-styles>
+  <office:body>
+    <office:text>
+      <text:sequence-decls>
+        <text:sequence-decl text:display-outline-level="0" text:name="Illustration"/>
+        <text:sequence-decl text:display-outline-level="0" text:name="Table"/>
+        <text:sequence-decl text:display-outline-level="0" text:name="Text"/>
+        <text:sequence-decl text:display-outline-level="0" text:name="Drawing"/>
+      </text:sequence-decls>
+      <text:p text:style-name="Title">Title</text:p>
+      <text:p text:style-name="Subtitle">Subtitle</text:p>
+      <text:p text:style-name="Author">Author</text:p>
+      <text:p text:style-name="Date">Date</text:p>
+      <text:p text:style-name="Abstract">Abstract.</text:p>
+      <text:h text:style-name="Heading_20_1" text:outline-level="1">Heading 1</text:h>
+      <text:h text:style-name="Heading_20_2" text:outline-level="2">Heading 2</text:h>
+      <text:h text:style-name="Heading_20_3" text:outline-level="3">Heading 3</text:h>
+      <text:h text:style-name="Heading_20_4" text:outline-level="4">Heading 4</text:h>
+      <text:h text:style-name="Heading_20_5" text:outline-level="5">Heading 5</text:h>
+      <text:h text:style-name="Heading_20_6" text:outline-level="6">Heading 6</text:h>
+      <text:p text:style-name="First_20_paragraph">First Paragraph.</text:p>
+      <text:p text:style-name="Text_20_body">Body Text. <text:span text:style-name="Emphasis">Emphasis</text:span>. <text:span text:style-name="Strong_20_Emphasis">Strong Emphasis</text:span>. <text:span text:style-name="Strikeout">Strikeout</text:span>. <text:span text:style-name="Superscript">Superscript</text:span>. <text:span text:style-name="Subscript">Subscript</text:span>. <text:span text:style-name="Source_20_Text">Source Text</text:span>. <text:span text:style-name="Highlighted">Highlighted</text:span>. <text:a xlink:type="simple" xlink:href="https://pandoc.org"><text:span text:style-name="Definition">Hyperlink</text:span></text:a>. Footnote.<text:note text:id="ftn1" text:note-class="footnote"><text:note-citation>1</text:note-citation><text:note-body><text:p text:style-name="Footnote">Footnote text.</text:p></text:note-body></text:note></text:p>
+      <text:p text:style-name="Quotations">Block quote.</text:p>
+      <text:p text:style-name="Preformatted_20_Text">Preformatted Text.</text:p>
+      <text:list text:style-name="List_20_1">
+        <text:list-item>
+          <text:p text:style-name="List_20_Bullet">Bullet list item.</text:p>
+        </text:list-item>
+      </text:list>
+      <text:list text:style-name="Numbering_20_1">
+        <text:list-item>
+          <text:p text:style-name="List_20_Number">Numbered list item.</text:p>
+        </text:list-item>
+      </text:list>
+      <text:p text:style-name="TableCaption">Table caption.</text:p>
+      <table:table table:name="DemoTable" table:style-name="DemoTable">
+        <table:table-column table:style-name="DemoTable.A"/>
+        <table:table-column table:style-name="DemoTable.A"/>
+        <table:table-header-rows>
+          <table:table-row>
+            <table:table-cell office:value-type="string">
+              <text:p text:style-name="Table_20_Heading">Table Heading</text:p>
+            </table:table-cell>
+            <table:table-cell office:value-type="string">
+              <text:p text:style-name="Table_20_Heading">Table Heading</text:p>
+            </table:table-cell>
+          </table:table-row>
+        </table:table-header-rows>
+        <table:table-row>
+          <table:table-cell office:value-type="string">
+            <text:p text:style-name="Table_20_Contents">Table Contents</text:p>
+          </table:table-cell>
+          <table:table-cell office:value-type="string">
+            <text:p text:style-name="Table_20_Contents">Table Contents</text:p>
+          </table:table-cell>
+        </table:table-row>
+      </table:table>
+      <text:p text:style-name="FigureCaption">Image caption.</text:p>
+      <text:p text:style-name="Definition_20_Term">Definition Term</text:p>
+      <text:p text:style-name="Definition_20_Definition">Definition.</text:p>
+    </office:text>
+  </office:body>
+</office:document-content>
diff --git a/data/odt/meta.xml b/data/odt/meta.xml
--- a/data/odt/meta.xml
+++ b/data/odt/meta.xml
@@ -6,7 +6,7 @@
     xmlns:meta="urn:oasis:names:tc:opendocument:xmlns:meta:1.0"
     xmlns:ooo="http://openoffice.org/2004/office"
     xmlns:grddl="http://www.w3.org/2003/g/data-view#"
-    office:version="1.2">
+    office:version="1.3">
   <office:meta>
     <meta:document-statistic
       meta:table-count="0" meta:image-count="0" meta:object-count="0"
diff --git a/data/odt/settings.xml b/data/odt/settings.xml
deleted file mode 100644
--- a/data/odt/settings.xml
+++ /dev/null
@@ -1,2 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<office:document-settings xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:config="urn:oasis:names:tc:opendocument:xmlns:config:1.0" xmlns:ooo="http://openoffice.org/2004/office" office:version="1.2"><office:settings><config:config-item-set config:name="ooo:view-settings"><config:config-item config:name="ViewAreaTop" config:type="int">0</config:config-item><config:config-item config:name="ViewAreaLeft" config:type="int">0</config:config-item><config:config-item config:name="ViewAreaWidth" config:type="int">21747</config:config-item><config:config-item config:name="ViewAreaHeight" config:type="int">10874</config:config-item><config:config-item config:name="ShowRedlineChanges" config:type="boolean">true</config:config-item><config:config-item config:name="InBrowseMode" config:type="boolean">false</config:config-item><config:config-item-map-indexed config:name="Views"><config:config-item-map-entry><config:config-item config:name="ViewId" config:type="string">view2</config:config-item><config:config-item config:name="ViewLeft" config:type="int">3041</config:config-item><config:config-item config:name="ViewTop" config:type="int">3041</config:config-item><config:config-item config:name="VisibleLeft" config:type="int">0</config:config-item><config:config-item config:name="VisibleTop" config:type="int">0</config:config-item><config:config-item config:name="VisibleRight" config:type="int">21745</config:config-item><config:config-item config:name="VisibleBottom" config:type="int">10873</config:config-item><config:config-item config:name="ZoomType" config:type="short">0</config:config-item><config:config-item config:name="ViewLayoutColumns" config:type="short">0</config:config-item><config:config-item config:name="ViewLayoutBookMode" config:type="boolean">false</config:config-item><config:config-item config:name="ZoomFactor" config:type="short">100</config:config-item><config:config-item config:name="IsSelectedFrame" config:type="boolean">false</config:config-item></config:config-item-map-entry></config:config-item-map-indexed></config:config-item-set><config:config-item-set config:name="ooo:configuration-settings"><config:config-item config:name="ChartAutoUpdate" config:type="boolean">true</config:config-item><config:config-item config:name="IsLabelDocument" config:type="boolean">false</config:config-item><config:config-item config:name="MathBaselineAlignment" config:type="boolean">false</config:config-item><config:config-item config:name="Rsid" config:type="int">1473719</config:config-item><config:config-item config:name="OutlineLevelYieldsNumbering" config:type="boolean">false</config:config-item><config:config-item config:name="PrintLeftPages" config:type="boolean">true</config:config-item><config:config-item config:name="DoNotJustifyLinesWithManualBreak" config:type="boolean">false</config:config-item><config:config-item config:name="ClippedPictures" config:type="boolean">false</config:config-item><config:config-item config:name="AlignTabStopPosition" config:type="boolean">true</config:config-item><config:config-item config:name="PrintTextPlaceholder" config:type="boolean">false</config:config-item><config:config-item config:name="UseOldNumbering" config:type="boolean">false</config:config-item><config:config-item config:name="CurrentDatabaseCommand" config:type="string"/><config:config-item config:name="ProtectForm" config:type="boolean">false</config:config-item><config:config-item config:name="PrintBlackFonts" config:type="boolean">false</config:config-item><config:config-item config:name="PrintProspectRTL" config:type="boolean">false</config:config-item><config:config-item config:name="BackgroundParaOverDrawings" config:type="boolean">false</config:config-item><config:config-item config:name="FloattableNomargins" config:type="boolean">false</config:config-item><config:config-item config:name="SmallCapsPercentage66" config:type="boolean">false</config:config-item><config:config-item config:name="PrintControls" config:type="boolean">true</config:config-item><config:config-item config:name="EmbedSystemFonts" config:type="boolean">false</config:config-item><config:config-item config:name="CharacterCompressionType" config:type="short">0</config:config-item><config:config-item config:name="PrintHiddenText" config:type="boolean">false</config:config-item><config:config-item config:name="UseFormerTextWrapping" config:type="boolean">false</config:config-item><config:config-item config:name="IsKernAsianPunctuation" config:type="boolean">false</config:config-item><config:config-item config:name="PrintProspect" config:type="boolean">false</config:config-item><config:config-item config:name="PrintEmptyPages" config:type="boolean">false</config:config-item><config:config-item config:name="UnbreakableNumberings" config:type="boolean">false</config:config-item><config:config-item config:name="UseFormerObjectPositioning" config:type="boolean">false</config:config-item><config:config-item config:name="ConsiderTextWrapOnObjPos" config:type="boolean">false</config:config-item><config:config-item config:name="TableRowKeep" config:type="boolean">false</config:config-item><config:config-item config:name="PrintReversed" config:type="boolean">false</config:config-item><config:config-item config:name="TabsRelativeToIndent" config:type="boolean">true</config:config-item><config:config-item config:name="PrintRightPages" config:type="boolean">true</config:config-item><config:config-item config:name="PrintPaperFromSetup" config:type="boolean">false</config:config-item><config:config-item config:name="AddFrameOffsets" config:type="boolean">false</config:config-item><config:config-item config:name="AddParaSpacingToTableCells" config:type="boolean">true</config:config-item><config:config-item config:name="UpdateFromTemplate" config:type="boolean">true</config:config-item><config:config-item config:name="AddExternalLeading" config:type="boolean">true</config:config-item><config:config-item config:name="PrintSingleJobs" config:type="boolean">false</config:config-item><config:config-item config:name="PrinterIndependentLayout" config:type="string">high-resolution</config:config-item><config:config-item config:name="RsidRoot" config:type="int">1473719</config:config-item><config:config-item config:name="LinkUpdateMode" config:type="short">1</config:config-item><config:config-item config:name="PrintAnnotationMode" config:type="short">0</config:config-item><config:config-item config:name="TabOverMargin" config:type="boolean">false</config:config-item><config:config-item config:name="UseOldPrinterMetrics" config:type="boolean">false</config:config-item><config:config-item config:name="RedlineProtectionKey" config:type="base64Binary"/><config:config-item config:name="PrinterSetup" config:type="base64Binary"/><config:config-item config:name="IgnoreFirstLineIndentInNumbering" config:type="boolean">false</config:config-item><config:config-item config:name="CollapseEmptyCellPara" config:type="boolean">true</config:config-item><config:config-item config:name="PrinterName" config:type="string"/><config:config-item config:name="EmbedFonts" config:type="boolean">false</config:config-item><config:config-item config:name="InvertBorderSpacing" config:type="boolean">false</config:config-item><config:config-item config:name="PrintPageBackground" config:type="boolean">true</config:config-item><config:config-item config:name="DoNotCaptureDrawObjsOnPage" config:type="boolean">false</config:config-item><config:config-item config:name="TabOverflow" config:type="boolean">true</config:config-item><config:config-item config:name="ApplyUserData" config:type="boolean">true</config:config-item><config:config-item config:name="TabAtLeftIndentForParagraphsInList" config:type="boolean">false</config:config-item><config:config-item config:name="UnxForceZeroExtLeading" config:type="boolean">false</config:config-item><config:config-item config:name="SaveVersionOnClose" config:type="boolean">false</config:config-item><config:config-item config:name="PrintFaxName" config:type="string"/><config:config-item config:name="StylesNoDefault" config:type="boolean">false</config:config-item><config:config-item config:name="AddParaTableSpacing" config:type="boolean">true</config:config-item><config:config-item config:name="PrintDrawings" config:type="boolean">true</config:config-item><config:config-item config:name="LoadReadonly" config:type="boolean">false</config:config-item><config:config-item config:name="PrintGraphics" config:type="boolean">true</config:config-item><config:config-item config:name="FieldAutoUpdate" config:type="boolean">true</config:config-item><config:config-item config:name="AllowPrintJobCancel" config:type="boolean">true</config:config-item><config:config-item config:name="UseFormerLineSpacing" config:type="boolean">false</config:config-item><config:config-item config:name="SaveGlobalDocumentLinks" config:type="boolean">false</config:config-item><config:config-item config:name="CurrentDatabaseDataSource" config:type="string"/><config:config-item config:name="IgnoreTabsAndBlanksForLineCalculation" config:type="boolean">false</config:config-item><config:config-item config:name="CurrentDatabaseCommandType" config:type="int">0</config:config-item><config:config-item config:name="DoNotResetParaAttrsForNumFont" config:type="boolean">false</config:config-item><config:config-item config:name="ClipAsCharacterAnchoredWriterFlyFrames" config:type="boolean">false</config:config-item><config:config-item config:name="PrintTables" config:type="boolean">true</config:config-item><config:config-item config:name="AddParaTableSpacingAtStart" config:type="boolean">true</config:config-item></config:config-item-set></office:settings></office:document-settings>
diff --git a/data/odt/styles.xml b/data/odt/styles.xml
--- a/data/odt/styles.xml
+++ b/data/odt/styles.xml
@@ -27,7 +27,7 @@
 xmlns:tableooo="http://openoffice.org/2009/table"
 xmlns:drawooo="http://openoffice.org/2010/draw"
 xmlns:calcext="urn:org:documentfoundation:names:experimental:calc:xmlns:calcext:1.0"
-xmlns:css3t="http://www.w3.org/TR/css3-text/" office:version="1.2">
+xmlns:css3t="http://www.w3.org/TR/css3-text/" office:version="1.3">
   <office:font-face-decls>
     <style:font-face style:name="StarSymbol"
     svg:font-family="StarSymbol" />
@@ -73,6 +73,41 @@
       style:font-size-complex="12pt" style:language-complex="zxx"
       style:country-complex="none" />
     </style:default-style>
+    <style:style style:name="Title" style:family="paragraph"
+      style:parent-style-name="Heading" style:next-style-name="Subtitle"
+      style:class="chapter">
+      <style:paragraph-properties fo:text-align="center"
+        style:justify-single-word="false" fo:margin-top="0in"
+        fo:margin-bottom="0.0835in" style:contextual-spacing="false" />
+      <style:text-properties fo:font-size="28pt" fo:font-weight="bold"
+        style:font-size-asian="28pt" style:font-weight-asian="bold"
+        style:font-size-complex="28pt" style:font-weight-complex="bold" />
+    </style:style>
+    <style:style style:name="Subtitle" style:family="paragraph"
+      style:parent-style-name="Heading" style:next-style-name="Text_20_body"
+      style:class="chapter">
+      <style:paragraph-properties fo:text-align="center"
+        style:justify-single-word="false" fo:margin-top="0.0835in"
+        fo:margin-bottom="0.0835in" style:contextual-spacing="false" />
+      <style:text-properties fo:font-size="18pt" fo:font-style="italic"
+        style:font-size-asian="18pt" style:font-style-asian="italic"
+        style:font-size-complex="18pt" style:font-style-complex="italic" />
+    </style:style>
+    <style:style style:name="Author" style:family="paragraph"
+      style:parent-style-name="Standard" style:class="html">
+        <style:paragraph-properties fo:text-align="center" />
+    </style:style>
+    <style:style style:name="Date" style:family="paragraph"
+      style:parent-style-name="Standard" style:class="html">
+        <style:paragraph-properties fo:text-align="center" />
+    </style:style>
+    <style:style style:name="Abstract" style:family="paragraph"
+      style:parent-style-name="Standard" style:class="html">
+      <style:paragraph-properties fo:margin-left="0.3937in"
+      fo:margin-right="0.3937in" fo:margin-top="0.1in"
+      fo:margin-bottom="0.1in" style:contextual-spacing="false"
+      fo:text-indent="0in" style:auto-text-indent="false" />
+    </style:style>
     <style:default-style style:family="paragraph">
       <style:paragraph-properties fo:hyphenation-ladder-count="no-limit"
       style:text-autospace="ideograph-alpha"
@@ -121,6 +156,24 @@
     style:parent-style-name="Text_20_body" style:class="list">
       <style:text-properties style:font-name-complex="Tahoma1" />
     </style:style>
+    <style:style style:name="List_20_Bullet"
+    style:display-name="List Bullet" style:family="paragraph"
+    style:parent-style-name="List" style:class="list" />
+    <style:style style:name="List_20_Bullet_20_Tight"
+    style:display-name="List Bullet Tight" style:family="paragraph"
+    style:parent-style-name="List" style:class="list">
+      <style:paragraph-properties fo:margin-top="0in"
+      fo:margin-bottom="0in" style:contextual-spacing="false" />
+    </style:style>
+    <style:style style:name="List_20_Number"
+    style:display-name="List Number" style:family="paragraph"
+    style:parent-style-name="List" style:class="list" />
+    <style:style style:name="List_20_Number_20_Tight"
+    style:display-name="List Number Tight" style:family="paragraph"
+    style:parent-style-name="List" style:class="list">
+      <style:paragraph-properties fo:margin-top="0in"
+      fo:margin-bottom="0in" style:contextual-spacing="false" />
+    </style:style>
     <style:style style:name="Caption" style:family="paragraph"
     style:parent-style-name="Standard" style:class="extra">
       <style:paragraph-properties fo:margin-top="0.0835in"
@@ -133,6 +186,9 @@
       style:font-size-complex="12pt"
       style:font-style-complex="italic" />
     </style:style>
+    <style:style style:name="TableCaption" style:family="paragraph"
+    style:parent-style-name="Caption" style:class="extra">
+    </style:style>
     <style:style style:name="Table" style:family="paragraph"
     style:parent-style-name="Caption" style:class="extra">
     </style:style>
@@ -232,18 +288,40 @@
       <style:paragraph-properties fo:margin-top="0in"
       fo:margin-bottom="0in" style:contextual-spacing="false" />
       <style:text-properties style:font-name="Courier New"
-      fo:font-size="10pt" style:font-name-asian="Courier New"
+      fo:font-family="&apos;Courier New&apos;"
+      style:font-family-generic="modern"
+      style:font-pitch="fixed"
+      fo:font-size="10pt"
+      style:font-name-asian="Courier New"
+      style:font-family-asian="&apos;Courier New&apos;"
+      style:font-family-generic-asian="modern"
+      style:font-pitch-asian="fixed"
       style:font-size-asian="10pt"
       style:font-name-complex="Courier New"
-      style:font-size-complex="10pt" />
+      style:font-family-complex="&apos;Courier New&apos;"
+      style:font-family-generic-complex="modern"
+      style:font-pitch-complex="fixed"
+      style:font-size-complex="10pt"
+      fo:language="zxx" />
     </style:style>
-    <style:style style:name="Source_Text" style:family="text">
+    <style:style style:name="Source_20_Text" style:display-name="Source Text" style:family="text">
       <style:text-properties style:font-name="Courier New"
-      fo:font-size="10pt" style:font-name-asian="Courier New"
-      style:font-size-asian="10pt"
+      fo:font-family="&apos;Courier New&apos;"
+      style:font-family-generic="modern"
+      style:font-pitch="fixed"
+      style:font-name-asian="Courier New"
+      style:font-family-asian="&apos;Courier New&apos;"
+      style:font-family-generic-asian="modern"
+      style:font-pitch-asian="fixed"
       style:font-name-complex="Courier New"
-      style:font-size-complex="10pt" />
+      style:font-family-complex="&apos;Courier New&apos;"
+      style:font-family-generic-complex="modern"
+      style:font-pitch-complex="fixed"
+      fo:language="zxx" />
     </style:style>
+    <style:style style:name="Highlighted" style:family="text">
+      <style:text-properties fo:background-color="#ffff38" />
+    </style:style>
     <style:style style:name="Definition_20_Term"
     style:display-name="Definition Term" style:family="paragraph"
     style:parent-style-name="Standard"
@@ -319,17 +397,6 @@
       fo:margin-bottom="0in" style:contextual-spacing="false"
       fo:text-indent="0in" style:auto-text-indent="false" />
     </style:style>
-    <style:style style:name="Date" style:family="paragraph"
-    style:parent-style-name="Standard"
-    style:next-style-name="Text_20_body">
-      <style:text-properties fo:font-style="italic" />
-    </style:style>
-    <style:style style:name="Author" style:family="paragraph"
-    style:parent-style-name="Standard" style:next-style-name="Date"
-    style:master-page-name="">
-      <style:paragraph-properties style:page-number="auto" />
-      <style:text-properties fo:font-style="italic" />
-    </style:style>
     <style:style style:name="Horizontal_20_Line"
     style:display-name="Horizontal Line" style:family="paragraph"
     style:parent-style-name="Standard"
@@ -346,7 +413,7 @@
     </style:style>
     <style:style style:name="First_20_paragraph"
     style:display-name="First paragraph" style:family="paragraph"
-    style:parent-style-name="Standard"
+    style:parent-style-name="Text_20_body"
     style:next-style-name="Text_20_body" style:class="text" />
     <style:style style:name="Numbering_20_Symbols"
     style:display-name="Numbering Symbols" style:family="text" />
diff --git a/data/pandoc.List.lua b/data/pandoc.List.lua
deleted file mode 100644
--- a/data/pandoc.List.lua
+++ /dev/null
@@ -1,120 +0,0 @@
---[[
-List.lua
-
-Copyright © 2017 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
-and this permission notice appear in all copies.
-
-THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
-REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
-FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
-INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
-OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
-TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
-THIS SOFTWARE.
-]]
-
---- Pandoc's List type and helper methods
--- @classmod pandoc.List
--- @author Albert Krewinkel
--- @copyright © 2017 Albert Krewinkel
--- @license MIT
-local List = {
-  _VERSION = "0.1.0"
-}
-
-function List:new (o)
-  o = o or {}
-  setmetatable(o, self)
-  self.__index = self
-  return o
-end
-
-function List:__call (o)
-  return self:new(o)
-end
-
---- Concatenates two lists.
--- @param list second list concatenated to the first
--- @return a new list containing all elements from list1 and list2
-function List:__concat (list)
-  local res = List.clone(self)
-  List.extend(res, list)
-  return res
-end
-
---- Returns a (shallow) copy of the list.
-function List:clone ()
-  local lst = setmetatable({}, getmetatable(self))
-  List.extend(lst, self)
-  return lst
-end
-
---- Checks if the list has an item equal to the given needle.
--- @param needle item to search for
--- @param init index at which the search is started
--- @return true if a list item is equal to the needle, false otherwise
-function List:includes (needle, init)
-  return not (List.find(self, needle, init) == nil)
-end
-
---- Returns the value and index of the first occurrence of the given item.
--- @param needle item to search for
--- @param init index at which the search is started
--- @return first item equal to the needle, or nil if no such item exists.
--- @return index of that element
-function List:find (needle, init)
-  return List.find_if(self, function(x) return x == needle end, init)
-end
-
---- Returns the value and index of the first element for which the predicate
---- holds true.
--- @param pred the predicate function
--- @param init index at which the search is started
--- @return first item for which `test` succeeds, or nil if no such item exists.
--- @return index of that element
-function List:find_if (pred, init)
-  init = (init == nil and 1) or (init < 0 and #self - init) or init
-  for i = init, #self do
-    if pred(self[i], i) then
-      return self[i], i
-    end
-  end
-  return nil
-end
-
---- Adds the given list to the end of this list.
--- @param list list to appended
-function List:extend (list)
-  for i = 1, #list do
-    self[#self + 1] = list[i]
-  end
-end
-
---- Returns a copy of the current list by applying the given function to all
--- elements.
--- @param fn function which is applied to all list items.
-function List:map (fn)
-  local res = setmetatable({}, getmetatable(self))
-  for i = 1, #self do
-    res[i] = fn(self[i], i)
-  end
-  return res
-end
-
---- Returns a new list containing all items satisfying a given condition.
--- @param pred condition items must satisfy.
--- @return a new list containing all items for which `test` was true.
-function List:filter (pred)
-  local res = setmetatable({}, getmetatable(self))
-  for i = 1, #self do
-    if pred(self[i], i) then
-      res[#res + 1] = self[i]
-    end
-  end
-  return res
-end
-
-return List
diff --git a/data/pandoc.lua b/data/pandoc.lua
deleted file mode 100644
--- a/data/pandoc.lua
+++ /dev/null
@@ -1,911 +0,0 @@
---[[
-pandoc.lua
-
-Copyright © 2017 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
-and this permission notice appear in all copies.
-
-THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
-REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
-FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
-INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
-OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
-TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
-THIS SOFTWARE.
-]]
-
----
--- Lua functions for pandoc scripts.
---
--- @author Albert Krewinkel
--- @copyright © 2017 Albert Krewinkel
--- @license MIT
-local M = {
-  _VERSION = "0.3.0"
-}
-
-local List = require 'pandoc.List'
-
-------------------------------------------------------------------------
--- The base class for pandoc's AST elements.
--- @type Element
--- @local
-local Element = {}
-
---- Create a new element subtype
--- @local
-function Element:make_subtype(o)
-  o = o or {}
-  setmetatable(o, self)
-  self.__index = self
-  return o
-end
-
---- Create a new element given its tag and arguments
--- @local
-function Element:new(tag, ...)
-  local element = { t = tag }
-  local content = {...}
-  -- special case for unary constructors
-  if #content == 1 then
-    element.c = content[1]
-  -- Don't set 'c' field if no further arguments were given. This is important
-  -- for nullary constructors like `Space` and `HorizontalRule`.
-  elseif #content > 0 then
-    element.c = content
-  end
-  setmetatable(element, self)
-  self.__index = self
-  return element
-end
-
---- Create a new constructor
--- @local
--- @param tag Tag used to identify the constructor
--- @param fn Function to be called when constructing a new element
--- @param accessors names to use as accessors for numerical fields
--- @return function that constructs a new element
-function Element:create_constructor(tag, fn, accessors)
-  local constr = self:make_subtype({tag = tag, getters = {}, setters = {}})
-
-  -- Add accessors to the metatable
-  if type(accessors) == "string" then
-    constr.getters[accessors] = function(elem)
-      return elem.c
-    end
-    constr.setters[accessors] = function(elem, v)
-      elem.c = v
-    end
-  else
-    for i = 1, #(accessors or {}) do
-      if type(accessors[i]) == "string" then
-        constr.getters[accessors[i]] = function(elem)
-          return elem.c[i]
-        end
-        constr.setters[accessors[i]] = function(elem, v)
-          elem.c[i] = v
-        end
-      else -- only two levels of nesting are supported
-        for k, v in ipairs(accessors[i]) do
-          constr.getters[v] = function(elem)
-            return elem.c[i][k]
-          end
-          constr.setters[v] = function(elem, v)
-            elem.c[i][k] = v
-          end
-        end
-      end
-    end
-  end
-
-  function constr:new(...)
-    local obj = fn(...)
-    setmetatable(obj, self)
-    self.__index = function(t, k)
-      if getmetatable(t).getters[k] then
-        return getmetatable(t).getters[k](t)
-      elseif k == "t" then
-        return getmetatable(t)["tag"]
-      else
-        return getmetatable(t)[k]
-      end
-    end
-    self.__newindex = function(t, k, v)
-      if getmetatable(t).setters[k] then
-        getmetatable(t).setters[k](t, v)
-      else
-        rawset(t, k, v)
-      end
-    end
-    return obj
-  end
-  self.constructor = self.constructor or {}
-  self.constructor[tag] = constr
-  return constr
-end
-
---- Calls the constructor, creating a new element.
--- @local
-function Element.__call(t, ...)
-  return t:new(...)
-end
-
-------------------------------------------------------------------------
---- Pandoc Document
--- @section document
-
---- A complete pandoc document
--- @function Pandoc
--- @tparam      {Block,...} blocks      document content
--- @tparam[opt] Meta        meta        document meta data
-function M.Pandoc(blocks, meta)
-  meta = meta or {}
-  return {
-    ["blocks"] = List:new(blocks),
-    ["meta"] = meta,
-    ["pandoc-api-version"] = {1,17,0,5},
-  }
-end
-
--- DEPRECATED synonym:
-M.Doc = M.Pandoc
-
-------------------------------------------------------------------------
--- Meta
--- @section Meta
-
---- Create a new Meta object. It sets the metatable of the given table to
---- `Meta`.
--- @function Meta
--- @tparam meta table table containing document meta information
-M.Meta = {}
-M.Meta.__call = function(t, meta)
-  return setmetatable(meta, t)
-end
-setmetatable(M.Meta, M.Meta)
-
-
-------------------------------------------------------------------------
--- MetaValue
--- @section MetaValue
-M.MetaValue = Element:make_subtype{}
-M.MetaValue.__call = function(t, ...)
-  return t:new(...)
-end
---- Meta blocks
--- @function MetaBlocks
--- @tparam {Block,...} blocks blocks
-
---- Meta inlines
--- @function MetaInlines
--- @tparam {Inline,...} inlines inlines
-
---- Meta list
--- @function MetaList
--- @tparam {MetaValue,...} meta_values list of meta values
-M.meta_value_list_types = {
-  "MetaBlocks",
-  "MetaInlines",
-  "MetaList",
-}
-for i = 1, #M.meta_value_list_types do
-  M[M.meta_value_list_types[i]] = M.MetaValue:create_constructor(
-    M.meta_value_list_types[i],
-    function(content)
-      return List:new(content)
-    end
-  )
-end
-
---- Meta map
--- @function MetaMap
--- @tparam table key_value_map a string-indexed map of meta values
-M.MetaMap = M.MetaValue:create_constructor(
-  "MetaMap",
-  function (mm) return mm end
-)
-
---- Creates string to be used in meta data.
--- Does nothing, lua strings are meta strings.
--- @function MetaString
--- @tparam string str string value
-function M.MetaString(str)
-  return str
-end
-
---- Creates boolean to be used in meta data.
--- Does nothing, lua booleans are meta booleans.
--- @function MetaBool
--- @tparam boolean bool boolean value
-function M.MetaBool(bool)
-  return bool
-end
-
-------------------------------------------------------------------------
--- Blocks
--- @section Block
-
---- Block elements
-M.Block = Element:make_subtype{}
-M.Block.__call = function (t, ...)
-  return t:new(...)
-end
-
---- Creates a block quote element
--- @function BlockQuote
--- @tparam      {Block,...} content     block content
--- @treturn     Block                   block quote element
-M.BlockQuote = M.Block:create_constructor(
-  "BlockQuote",
-  function(content) return {c = content} end,
-  "content"
-)
-
---- Creates a bullet (i.e. unordered) list.
--- @function BulletList
--- @tparam      {{Block,...},...} content     list of items
--- @treturn     Block block quote element
-M.BulletList = M.Block:create_constructor(
-  "BulletList",
-  function(content) return {c = content} end,
-  "content"
-)
-
---- Creates a code block element
--- @function CodeBlock
--- @tparam      string      text        code string
--- @tparam[opt] Attr        attr element attributes
--- @treturn     Block                   code block element
-M.CodeBlock = M.Block:create_constructor(
-  "CodeBlock",
-  function(text, attr) return {c = {attr or M.Attr(), text}} end,
-  {{"identifier", "classes", "attributes"}, "text"}
-)
-
---- Creates a definition list, containing terms and their explanation.
--- @function DefinitionList
--- @tparam      {{{Inline,...},{Block,...}},...} content     list of items
--- @treturn     Block block quote element
-M.DefinitionList = M.Block:create_constructor(
-  "DefinitionList",
-  function(content) return {c = List:new(content)} end,
-  "content"
-)
-
---- Creates a div element
--- @function Div
--- @tparam      {Block,...} content     block content
--- @tparam[opt] Attr        attr  element attributes
--- @treturn     Block                   code block element
-M.Div = M.Block:create_constructor(
-  "Div",
-  function(content, attr)
-    return {c = {attr or M.Attr(), List:new(content)}}
-  end,
-  {{"identifier", "classes", "attributes"}, "content"}
-)
-
---- Creates a block quote element.
--- @function Header
--- @tparam      int          level       header level
--- @tparam      {Inline,...} content     inline content
--- @tparam[opt] Attr         attr element attributes
--- @treturn     Block                    header element
-M.Header = M.Block:create_constructor(
-  "Header",
-  function(level, content, attr)
-    return {c = {level, attr or M.Attr(), content}}
-  end,
-  {"level", {"identifier", "classes", "attributes"}, "content"}
-)
-
---- Creates a horizontal rule.
--- @function HorizontalRule
--- @treturn     Block                   horizontal rule
-M.HorizontalRule = M.Block:create_constructor(
-  "HorizontalRule",
-  function() return {} end
-)
-
---- Creates a line block element.
--- @function LineBlock
--- @tparam      {{Inline,...},...} content    inline content
--- @treturn     Block                   block quote element
-M.LineBlock = M.Block:create_constructor(
-  "LineBlock",
-  function(content) return {c = List:new(content)} end,
-  "content"
-)
-
---- Creates a null element.
--- @function Null
--- @treturn     Block                   null element
-M.Null = M.Block:create_constructor(
-  "Null",
-  function() return {} end
-)
-
---- Creates an ordered list.
--- @function OrderedList
--- @tparam      {{Block,...},...} items list items
--- @param[opt]  listAttributes list parameters
--- @treturn     Block
-M.OrderedList = M.Block:create_constructor(
-  "OrderedList",
-  function(items, listAttributes)
-    listAttributes = listAttributes or {1, M.DefaultStyle, M.DefaultDelim}
-    return {c = {listAttributes, List:new(items)}}
-  end,
-  {{"start", "style", "delimiter"}, "content"}
-)
-
---- Creates a para element.
--- @function Para
--- @tparam      {Inline,...} content    inline content
--- @treturn     Block                   block quote element
-M.Para = M.Block:create_constructor(
-  "Para",
-  function(content) return {c = List:new(content)} end,
-  "content"
-)
-
---- Creates a plain element.
--- @function Plain
--- @tparam      {Inline,...} content    inline content
--- @treturn     Block                   block quote element
-M.Plain = M.Block:create_constructor(
-  "Plain",
-  function(content) return {c = List:new(content)} end,
-  "content"
-)
-
---- Creates a raw content block of the specified format.
--- @function RawBlock
--- @tparam      string      format      format of content
--- @tparam      string      text        string content
--- @treturn     Block                   block quote element
-M.RawBlock = M.Block:create_constructor(
-  "RawBlock",
-  function(format, text) return {c = {format, text}} end,
-  {"format", "text"}
-)
-
---- Creates a table element.
--- @function Table
--- @tparam      {Inline,...} caption    table caption
--- @tparam      {AlignDefault|AlignLeft|AlignRight|AlignCenter,...} aligns alignments
--- @tparam      {int,...}    widths     column widths
--- @tparam      {Block,...}  headers    header row
--- @tparam      {{Block,...}} rows      table rows
--- @treturn     Block                   block quote element
-M.Table = M.Block:create_constructor(
-  "Table",
-  function(caption, aligns, widths, headers, rows)
-    return {
-      c = {
-        List:new(caption),
-        List:new(aligns),
-        List:new(widths),
-        List:new(headers),
-        List:new(rows)
-      }
-    }
-  end,
-  {"caption", "aligns", "widths", "headers", "rows"}
-)
-
-
-------------------------------------------------------------------------
--- Inline
--- @section Inline
-
---- Inline element class
-M.Inline = Element:make_subtype{}
-M.Inline.__call = function (t, ...)
-  return t:new(...)
-end
-
---- Creates a Cite inline element
--- @function Cite
--- @tparam {Inline,...}   content       List of inlines
--- @tparam {Citation,...} citations     List of citations
--- @treturn Inline citations element
-M.Cite = M.Inline:create_constructor(
-  "Cite",
-  function(content, citations)
-    return {c = {List:new(citations), List:new(content)}}
-  end,
-  {"citations", "content"}
-)
-
---- Creates a Code inline element
--- @function Code
--- @tparam      string      text        brief image description
--- @tparam[opt] Attr        attr  additional attributes
--- @treturn Inline code element
-M.Code = M.Inline:create_constructor(
-  "Code",
-  function(text, attr) return {c = {attr or M.Attr(), text}} end,
-  {{"identifier", "classes", "attributes"}, "text"}
-)
-
---- Creates an inline element representing emphasised text.
--- @function Emph
--- @tparam      {Inline,..} content     inline content
--- @treturn Inline emphasis element
-M.Emph = M.Inline:create_constructor(
-  "Emph",
-  function(content) return {c = List:new(content)} end,
-  "content"
-)
-
---- Creates a Image inline element
--- @function Image
--- @tparam      {Inline,..} caption     text used to describe the image
--- @tparam      string      src         path to the image file
--- @tparam[opt] string      title       brief image description
--- @tparam[opt] Attr        attr additional attributes
--- @treturn Inline image element
-M.Image = M.Inline:create_constructor(
-  "Image",
-  function(caption, src, title, attr)
-    title = title or ""
-    attr = attr or M.Attr()
-    return {c = {attr, List:new(caption), {src, title}}}
-  end,
-  {{"identifier", "classes", "attributes"}, "caption", {"src", "title"}}
-)
-
---- Create a LineBreak inline element
--- @function LineBreak
--- @treturn Inline linebreak element
-M.LineBreak = M.Inline:create_constructor(
-  "LineBreak",
-  function() return {} end
-)
-
---- Creates a link inline element, usually a hyperlink.
--- @function Link
--- @tparam      {Inline,..} content     text for this link
--- @tparam      string      target      the link target
--- @tparam[opt] string      title       brief link description
--- @tparam[opt] Attr        attr additional attributes
--- @treturn Inline image element
-M.Link = M.Inline:create_constructor(
-  "Link",
-  function(content, target, title, attr)
-    title = title or ""
-    attr = attr or M.Attr()
-    return {c = {attr, List:new(content), {target, title}}}
-  end,
-  {{"identifier", "classes", "attributes"}, "content", {"target", "title"}}
-)
-
---- Creates a Math element, either inline or displayed.
--- @function Math
--- @tparam      "InlineMath"|"DisplayMath" mathtype rendering specifier
--- @tparam      string      text        Math content
--- @treturn     Inline                  Math element
-M.Math = M.Inline:create_constructor(
-  "Math",
-  function(mathtype, text)
-    return {c = {mathtype, text}}
-  end,
-  {"mathtype", "text"}
-)
---- Creates a DisplayMath element (DEPRECATED).
--- @function DisplayMath
--- @tparam      string      text        Math content
--- @treturn     Inline                  Math element
-M.DisplayMath = M.Inline:create_constructor(
-  "DisplayMath",
-  function(text) return M.Math("DisplayMath", text) end,
-  {"mathtype", "text"}
-)
---- Creates an InlineMath inline element (DEPRECATED).
--- @function InlineMath
--- @tparam      string      text        Math content
--- @treturn     Inline                  Math element
-M.InlineMath = M.Inline:create_constructor(
-  "InlineMath",
-  function(text) return M.Math("InlineMath", text) end,
-  {"mathtype", "text"}
-)
-
---- Creates a Note inline element
--- @function Note
--- @tparam      {Block,...} content     footnote block content
-M.Note = M.Inline:create_constructor(
-  "Note",
-  function(content) return {c = List:new(content)} end,
-  "content"
-)
-
---- Creates a Quoted inline element given the quote type and quoted content.
--- @function Quoted
--- @tparam      "DoubleQuote"|"SingleQuote" quotetype type of quotes to be used
--- @tparam      {Inline,..} content     inline content
--- @treturn     Inline                  quoted element
-M.Quoted = M.Inline:create_constructor(
-  "Quoted",
-  function(quotetype, content) return {c = {quotetype, List:new(content)}} end,
-  {"quotetype", "content"}
-)
---- Creates a single-quoted inline element (DEPRECATED).
--- @function SingleQuoted
--- @tparam      {Inline,..} content     inline content
--- @treturn     Inline                  quoted element
--- @see Quoted
-M.SingleQuoted = M.Inline:create_constructor(
-  "SingleQuoted",
-  function(content) return M.Quoted(M.SingleQuote, content) end,
-  {"quotetype", "content"}
-)
---- Creates a single-quoted inline element (DEPRECATED).
--- @function DoubleQuoted
--- @tparam      {Inline,..} content     inline content
--- @treturn     Inline                  quoted element
--- @see Quoted
-M.DoubleQuoted = M.Inline:create_constructor(
-  "DoubleQuoted",
-  function(content) return M.Quoted("DoubleQuote", content) end,
-  {"quotetype", "content"}
-)
-
---- Creates a RawInline inline element
--- @function RawInline
--- @tparam      string      format      format of the contents
--- @tparam      string      text        string content
--- @treturn     Inline                  raw inline element
-M.RawInline = M.Inline:create_constructor(
-  "RawInline",
-  function(format, text) return {c = {format, text}} end,
-  {"format", "text"}
-)
-
---- Creates text rendered in small caps
--- @function SmallCaps
--- @tparam      {Inline,..} content     inline content
--- @treturn     Inline                  smallcaps element
-M.SmallCaps = M.Inline:create_constructor(
-  "SmallCaps",
-  function(content) return {c = List:new(content)} end,
-  "content"
-)
-
---- Creates a SoftBreak inline element.
--- @function SoftBreak
--- @treturn     Inline                  softbreak element
-M.SoftBreak = M.Inline:create_constructor(
-  "SoftBreak",
-  function() return {} end
-)
-
---- Create a Space inline element
--- @function Space
--- @treturn Inline space element
-M.Space = M.Inline:create_constructor(
-  "Space",
-  function() return {} end
-)
-
---- Creates a Span inline element
--- @function Span
--- @tparam      {Inline,..} content     inline content
--- @tparam[opt] Attr        attr  additional attributes
--- @treturn Inline span element
-M.Span = M.Inline:create_constructor(
-  "Span",
-  function(content, attr)
-    return {c = {attr or M.Attr(), List:new(content)}}
-  end,
-  {{"identifier", "classes", "attributes"}, "content"}
-)
-
---- Creates a Str inline element
--- @function Str
--- @tparam      string      text        content
--- @treturn     Inline                  string element
-M.Str = M.Inline:create_constructor(
-  "Str",
-  function(text) return {c = text} end,
-  "text"
-)
-
---- Creates text which is striked out.
--- @function Strikeout
--- @tparam      {Inline,..} content     inline content
--- @treturn     Inline                  strikeout element
-M.Strikeout = M.Inline:create_constructor(
-  "Strikeout",
-  function(content) return {c = List:new(content)} end,
-  "content"
-)
-
---- Creates a Strong element, whose text is usually displayed in a bold font.
--- @function Strong
--- @tparam      {Inline,..} content     inline content
--- @treturn     Inline                  strong element
-M.Strong = M.Inline:create_constructor(
-  "Strong",
-  function(content) return {c = List:new(content)} end,
-  "content"
-)
-
---- Creates a Subscript inline element
--- @function Subscript
--- @tparam      {Inline,..} content     inline content
--- @treturn     Inline                  subscript element
-M.Subscript = M.Inline:create_constructor(
-  "Subscript",
-  function(content) return {c = List:new(content)} end,
-  "content"
-)
-
---- Creates a Superscript inline element
--- @function Superscript
--- @tparam      {Inline,..} content     inline content
--- @treturn     Inline                  strong element
-M.Superscript = M.Inline:create_constructor(
-  "Superscript",
-  function(content) return {c = List:new(content)} end,
-  "content"
-)
-
-
-------------------------------------------------------------------------
--- Helpers
--- @section helpers
-
-local function assoc_key_equals (x)
-  return function (y) return y[1] == x end
-end
-
--- Lookup a value in an associative list
--- @function lookup
--- @tparam {{key, value},...} alist associative list
--- @param key key for which the associated value is to be looked up
-local function lookup(alist, key)
-  return (List.find_if(alist, assoc_key_equals(key)) or {})[2]
-end
-
---- Return an iterator which returns key-value pairs of an associative list.
--- @function apairs
--- @tparam {{key, value},...} alist associative list
-local apairs = function (alist)
-  local i = 1
-  local cur
-  function nxt ()
-    cur = rawget(alist, i)
-    if cur then
-      i = i + 1
-      return cur[1], cur[2]
-    end
-    return nil
-  end
-  return nxt, nil, nil
-end
-
--- AttributeList, a metatable to allow table-like access to attribute lists
--- represented by associative lists.
-local AttributeList = {
-  __index = function (t, k)
-    if type(k) == "number" then
-      return rawget(t, k)
-    else
-      return lookup(t, k)
-    end
-  end,
-
-  __newindex = function (t, k, v)
-    local cur, idx = List.find_if(t, assoc_key_equals(k))
-    if v == nil then
-      table.remove(t, idx)
-    elseif cur then
-      cur[2] = v
-    elseif type(k) == "number" then
-      rawset(t, k, v)
-    else
-      rawset(t, #t + 1, {k, v})
-    end
-  end,
-
-  __pairs = apairs
-}
-
--- convert a table to an associative list. The order of key-value pairs in the
--- alist is undefined. The table should either contain no numeric keys or
--- already be an associative list.
--- @tparam table associative list or table without numeric keys.
--- @treturn table associative list
-local to_alist = function (tbl)
-  if #tbl ~= 0 or next(tbl) == nil then
-    -- probably already an alist
-    return tbl
-  end
-  local alist = {}
-  local i = 1
-  for k, v in pairs(tbl) do
-    alist[i] = {k, v}
-    i = i + 1
-  end
-  return alist
-end
-
--- Attr
-M.Attr = {}
-M.Attr._field_names = {identifier = 1, classes = 2, attributes = 3}
---- Create a new set of attributes (Attr).
--- @function Attr
--- @tparam[opt] string       identifier element identifier
--- @tparam[opt] {string,...} classes    element classes
--- @tparam[opt] table        attributes table containing string keys and values
--- @return element attributes
-M.Attr.__call = function(t, identifier, classes, attributes)
-  identifier = identifier or ''
-  classes = List:new(classes or {})
-  attributes = setmetatable(to_alist(attributes or {}), AttributeList)
-  local attr = {identifier, classes, attributes}
-  setmetatable(attr, t)
-  return attr
-end
-M.Attr.__index = function(t, k)
-  return rawget(t, k) or
-    rawget(t, M.Attr._field_names[k]) or
-    rawget(getmetatable(t), k)
-end
-M.Attr.__newindex = function(t, k, v)
-  if M.Attr._field_names[k] then
-    rawset(t, M.Attr._field_names[k], v)
-  else
-    rawset(t, k, v)
-  end
-end
-setmetatable(M.Attr, M.Attr)
-
-
---- Creates a single citation.
--- @function Citation
--- @tparam      string       id       citation identifier (like a bibtex key)
--- @tparam      AuthorInText|SuppressAuthor|NormalCitation mode citation mode
--- @tparam[opt] {Inline,...} prefix   citation prefix
--- @tparam[opt] {Inline,...} suffix   citation suffix
--- @tparam[opt] int          note_num note number
--- @tparam[opt] int          hash  hash number
-M.Citation = function(id, mode, prefix, suffix, note_num, hash)
-  prefix = prefix or {}
-  suffix = suffix or {}
-  note_num = note_num or 0
-  hash = hash or 0
-  return {
-    citationId = id,
-    citationPrefix = prefix,
-    citationSuffix = suffix,
-    citationMode = mode,
-    citationNoteNum = note_num,
-    citationHash = hash,
-  }
-end
-
-
-------------------------------------------------------------------------
--- Constants
--- @section constants
-
---- Author name is mentioned in the text.
--- @see Citation
--- @see Cite
-M.AuthorInText = "AuthorInText"
-
---- Author name is suppressed.
--- @see Citation
--- @see Cite
-M.SuppressAuthor = "SuppressAuthor"
-
---- Default citation style is used.
--- @see Citation
--- @see Cite
-M.NormalCitation = "NormalCitation"
-
---- Table cells aligned left.
--- @see Table
-M.AlignLeft = "AlignLeft"
-
---- Table cells right-aligned.
--- @see Table
-M.AlignRight = "AlignRight"
-
---- Table cell content is centered.
--- @see Table
-M.AlignCenter = "AlignCenter"
-
---- Table cells are alignment is unaltered.
--- @see Table
-M.AlignDefault = "AlignDefault"
-
---- Default list number delimiters are used.
--- @see OrderedList
-M.DefaultDelim = "DefaultDelim"
-
---- List numbers are delimited by a period.
--- @see OrderedList
-M.Period = "Period"
-
---- List numbers are delimited by a single parenthesis.
--- @see OrderedList
-M.OneParen = "OneParen"
-
---- List numbers are delimited by a double parentheses.
--- @see OrderedList
-M.TwoParens = "TwoParens"
-
---- List are numbered in the default style
--- @see OrderedList
-M.DefaultStyle = "DefaultStyle"
-
---- List items are numbered as examples.
--- @see OrderedList
-M.Example = "Example"
-
---- List are numbered using decimal integers.
--- @see OrderedList
-M.Decimal = "Decimal"
-
---- List are numbered using lower-case roman numerals.
--- @see OrderedList
-M.LowerRoman = "LowerRoman"
-
---- List are numbered using upper-case roman numerals
--- @see OrderedList
-M.UpperRoman = "UpperRoman"
-
---- List are numbered using lower-case alphabetic characters.
--- @see OrderedList
-M.LowerAlpha = "LowerAlpha"
-
---- List are numbered using upper-case alphabetic characters.
--- @see OrderedList
-M.UpperAlpha = "UpperAlpha"
-
-
-------------------------------------------------------------------------
--- Helper Functions
--- @section helpers
-
---- Use functions defined in the global namespace to create a pandoc filter.
--- All globally defined functions which have names of pandoc elements are
--- collected into a new table.
--- @return A list of filter functions
--- @usage
--- -- within a file defining a pandoc filter:
--- function Str(text)
---   return pandoc.Str(utf8.upper(text))
--- end
---
--- return {pandoc.global_filter()}
--- -- the above is equivallent to
--- -- return {{Str = Str}}
-function M.global_filter()
-  local res = {}
-  function is_filter_function(k)
-    return M.Inline.constructor[k] or
-      M.Block.constructor[k] or
-      k == "Meta" or k == "Doc" or k == "Pandoc" or
-      k == "Block" or k == "Inline"
-  end
-  for k, v in pairs(_G) do
-    if is_filter_function(k) then
-      res[k] = v
-    end
-  end
-  return res
-end
-
-------------------------------------------------------------------------
--- Functions which have moved to different modules
-local utils = require 'pandoc.utils'
-M.sha1 = utils.sha1
-
-return M
diff --git a/data/pptx/[Content_Types].xml b/data/pptx/[Content_Types].xml
--- a/data/pptx/[Content_Types].xml
+++ b/data/pptx/[Content_Types].xml
@@ -1,2 +1,2 @@
 <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
-<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="xml" ContentType="application/xml"/><Default Extension="jpeg" ContentType="image/jpeg"/><Default Extension="bin" ContentType="application/vnd.openxmlformats-officedocument.presentationml.printerSettings"/><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Override PartName="/ppt/presentation.xml" ContentType="application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml"/><Override PartName="/ppt/slideMasters/slideMaster1.xml" ContentType="application/vnd.openxmlformats-officedocument.presentationml.slideMaster+xml"/><Override PartName="/ppt/slides/slide1.xml" ContentType="application/vnd.openxmlformats-officedocument.presentationml.slide+xml"/><Override PartName="/ppt/slides/slide2.xml" ContentType="application/vnd.openxmlformats-officedocument.presentationml.slide+xml"/><Override PartName="/ppt/presProps.xml" ContentType="application/vnd.openxmlformats-officedocument.presentationml.presProps+xml"/><Override PartName="/ppt/viewProps.xml" ContentType="application/vnd.openxmlformats-officedocument.presentationml.viewProps+xml"/><Override PartName="/ppt/theme/theme1.xml" ContentType="application/vnd.openxmlformats-officedocument.theme+xml"/><Override PartName="/ppt/tableStyles.xml" ContentType="application/vnd.openxmlformats-officedocument.presentationml.tableStyles+xml"/><Override PartName="/ppt/slideLayouts/slideLayout1.xml" ContentType="application/vnd.openxmlformats-officedocument.presentationml.slideLayout+xml"/><Override PartName="/ppt/slideLayouts/slideLayout2.xml" ContentType="application/vnd.openxmlformats-officedocument.presentationml.slideLayout+xml"/><Override PartName="/ppt/slideLayouts/slideLayout3.xml" ContentType="application/vnd.openxmlformats-officedocument.presentationml.slideLayout+xml"/><Override PartName="/ppt/slideLayouts/slideLayout4.xml" ContentType="application/vnd.openxmlformats-officedocument.presentationml.slideLayout+xml"/><Override PartName="/ppt/slideLayouts/slideLayout5.xml" ContentType="application/vnd.openxmlformats-officedocument.presentationml.slideLayout+xml"/><Override PartName="/ppt/slideLayouts/slideLayout6.xml" ContentType="application/vnd.openxmlformats-officedocument.presentationml.slideLayout+xml"/><Override PartName="/ppt/slideLayouts/slideLayout7.xml" ContentType="application/vnd.openxmlformats-officedocument.presentationml.slideLayout+xml"/><Override PartName="/ppt/slideLayouts/slideLayout8.xml" ContentType="application/vnd.openxmlformats-officedocument.presentationml.slideLayout+xml"/><Override PartName="/ppt/slideLayouts/slideLayout9.xml" ContentType="application/vnd.openxmlformats-officedocument.presentationml.slideLayout+xml"/><Override PartName="/ppt/slideLayouts/slideLayout10.xml" ContentType="application/vnd.openxmlformats-officedocument.presentationml.slideLayout+xml"/><Override PartName="/ppt/slideLayouts/slideLayout11.xml" ContentType="application/vnd.openxmlformats-officedocument.presentationml.slideLayout+xml"/><Override PartName="/docProps/core.xml" ContentType="application/vnd.openxmlformats-package.core-properties+xml"/><Override PartName="/docProps/app.xml" ContentType="application/vnd.openxmlformats-officedocument.extended-properties+xml"/></Types>
+<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/><Override PartName="/ppt/presentation.xml" ContentType="application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml"/><Override PartName="/ppt/slideMasters/slideMaster1.xml" ContentType="application/vnd.openxmlformats-officedocument.presentationml.slideMaster+xml"/><Override PartName="/ppt/slides/slide1.xml" ContentType="application/vnd.openxmlformats-officedocument.presentationml.slide+xml"/><Override PartName="/ppt/slides/slide2.xml" ContentType="application/vnd.openxmlformats-officedocument.presentationml.slide+xml"/><Override PartName="/ppt/slides/slide3.xml" ContentType="application/vnd.openxmlformats-officedocument.presentationml.slide+xml"/><Override PartName="/ppt/slides/slide4.xml" ContentType="application/vnd.openxmlformats-officedocument.presentationml.slide+xml"/><Override PartName="/ppt/notesMasters/notesMaster1.xml" ContentType="application/vnd.openxmlformats-officedocument.presentationml.notesMaster+xml"/><Override PartName="/ppt/presProps.xml" ContentType="application/vnd.openxmlformats-officedocument.presentationml.presProps+xml"/><Override PartName="/ppt/viewProps.xml" ContentType="application/vnd.openxmlformats-officedocument.presentationml.viewProps+xml"/><Override PartName="/ppt/theme/theme1.xml" ContentType="application/vnd.openxmlformats-officedocument.theme+xml"/><Override PartName="/ppt/tableStyles.xml" ContentType="application/vnd.openxmlformats-officedocument.presentationml.tableStyles+xml"/><Override PartName="/ppt/slideLayouts/slideLayout1.xml" ContentType="application/vnd.openxmlformats-officedocument.presentationml.slideLayout+xml"/><Override PartName="/ppt/slideLayouts/slideLayout2.xml" ContentType="application/vnd.openxmlformats-officedocument.presentationml.slideLayout+xml"/><Override PartName="/ppt/slideLayouts/slideLayout3.xml" ContentType="application/vnd.openxmlformats-officedocument.presentationml.slideLayout+xml"/><Override PartName="/ppt/slideLayouts/slideLayout4.xml" ContentType="application/vnd.openxmlformats-officedocument.presentationml.slideLayout+xml"/><Override PartName="/ppt/slideLayouts/slideLayout5.xml" ContentType="application/vnd.openxmlformats-officedocument.presentationml.slideLayout+xml"/><Override PartName="/ppt/slideLayouts/slideLayout6.xml" ContentType="application/vnd.openxmlformats-officedocument.presentationml.slideLayout+xml"/><Override PartName="/ppt/slideLayouts/slideLayout7.xml" ContentType="application/vnd.openxmlformats-officedocument.presentationml.slideLayout+xml"/><Override PartName="/ppt/slideLayouts/slideLayout8.xml" ContentType="application/vnd.openxmlformats-officedocument.presentationml.slideLayout+xml"/><Override PartName="/ppt/slideLayouts/slideLayout9.xml" ContentType="application/vnd.openxmlformats-officedocument.presentationml.slideLayout+xml"/><Override PartName="/ppt/slideLayouts/slideLayout10.xml" ContentType="application/vnd.openxmlformats-officedocument.presentationml.slideLayout+xml"/><Override PartName="/ppt/slideLayouts/slideLayout11.xml" ContentType="application/vnd.openxmlformats-officedocument.presentationml.slideLayout+xml"/><Override PartName="/ppt/theme/theme2.xml" ContentType="application/vnd.openxmlformats-officedocument.theme+xml"/><Override PartName="/ppt/notesSlides/notesSlide1.xml" ContentType="application/vnd.openxmlformats-officedocument.presentationml.notesSlide+xml"/><Override PartName="/ppt/notesSlides/notesSlide2.xml" ContentType="application/vnd.openxmlformats-officedocument.presentationml.notesSlide+xml"/><Override PartName="/docProps/core.xml" ContentType="application/vnd.openxmlformats-package.core-properties+xml"/><Override PartName="/docProps/app.xml" ContentType="application/vnd.openxmlformats-officedocument.extended-properties+xml"/></Types>
diff --git a/data/pptx/_rels/.rels b/data/pptx/_rels/.rels
--- a/data/pptx/_rels/.rels
+++ b/data/pptx/_rels/.rels
@@ -1,2 +1,2 @@
 <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
-<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId2" Type="http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties" Target="docProps/core.xml"/><Relationship Id="rId3" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties" Target="docProps/app.xml"/><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="ppt/presentation.xml"/></Relationships>
+<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId3" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties" Target="docProps/app.xml"/><Relationship Id="rId2" Type="http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties" Target="docProps/core.xml"/><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="ppt/presentation.xml"/></Relationships>
diff --git a/data/pptx/docProps/app.xml b/data/pptx/docProps/app.xml
--- a/data/pptx/docProps/app.xml
+++ b/data/pptx/docProps/app.xml
@@ -1,2 +1,2 @@
 <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
-<Properties xmlns="http://schemas.openxmlformats.org/officeDocument/2006/extended-properties" xmlns:vt="http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes"><TotalTime>1</TotalTime><Words>8</Words><Application>Microsoft Macintosh PowerPoint</Application><PresentationFormat>On-screen Show (4:3)</PresentationFormat><Paragraphs>4</Paragraphs><Slides>2</Slides><Notes>0</Notes><HiddenSlides>0</HiddenSlides><MMClips>0</MMClips><ScaleCrop>false</ScaleCrop><HeadingPairs><vt:vector size="4" baseType="variant"><vt:variant><vt:lpstr>Theme</vt:lpstr></vt:variant><vt:variant><vt:i4>1</vt:i4></vt:variant><vt:variant><vt:lpstr>Slide Titles</vt:lpstr></vt:variant><vt:variant><vt:i4>2</vt:i4></vt:variant></vt:vector></HeadingPairs><TitlesOfParts><vt:vector size="3" baseType="lpstr"><vt:lpstr>Office Theme</vt:lpstr><vt:lpstr>Title</vt:lpstr><vt:lpstr>Slide Title</vt:lpstr></vt:vector></TitlesOfParts><Company></Company><LinksUpToDate>false</LinksUpToDate><SharedDoc>false</SharedDoc><HyperlinksChanged>false</HyperlinksChanged><AppVersion>14.0000</AppVersion></Properties>
+<Properties xmlns="http://schemas.openxmlformats.org/officeDocument/2006/extended-properties" xmlns:vt="http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes"><TotalTime>2</TotalTime><Words>49</Words><Application>Microsoft Macintosh PowerPoint</Application><PresentationFormat>On-screen Show (16:9)</PresentationFormat><Paragraphs>15</Paragraphs><Slides>4</Slides><Notes>2</Notes><HiddenSlides>0</HiddenSlides><MMClips>0</MMClips><ScaleCrop>false</ScaleCrop><HeadingPairs><vt:vector size="6" baseType="variant"><vt:variant><vt:lpstr>Fonts Used</vt:lpstr></vt:variant><vt:variant><vt:i4>2</vt:i4></vt:variant><vt:variant><vt:lpstr>Theme</vt:lpstr></vt:variant><vt:variant><vt:i4>1</vt:i4></vt:variant><vt:variant><vt:lpstr>Slide Titles</vt:lpstr></vt:variant><vt:variant><vt:i4>4</vt:i4></vt:variant></vt:vector></HeadingPairs><TitlesOfParts><vt:vector size="7" baseType="lpstr"><vt:lpstr>Arial</vt:lpstr><vt:lpstr>Calibri</vt:lpstr><vt:lpstr>Office Theme</vt:lpstr><vt:lpstr>Presentation Title</vt:lpstr><vt:lpstr>Slide Title</vt:lpstr><vt:lpstr>Section header</vt:lpstr><vt:lpstr>Slide Title for Two-Content</vt:lpstr></vt:vector></TitlesOfParts><Company></Company><LinksUpToDate>false</LinksUpToDate><SharedDoc>false</SharedDoc><HyperlinksChanged>false</HyperlinksChanged><AppVersion>16.0000</AppVersion></Properties>
diff --git a/data/pptx/docProps/core.xml b/data/pptx/docProps/core.xml
--- a/data/pptx/docProps/core.xml
+++ b/data/pptx/docProps/core.xml
@@ -1,2 +1,2 @@
 <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
-<cp:coreProperties xmlns:cp="http://schemas.openxmlformats.org/package/2006/metadata/core-properties" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:dcmitype="http://purl.org/dc/dcmitype/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><dc:title>Title</dc:title><dc:creator>Jesse Rosenthal</dc:creator><cp:lastModifiedBy>Jesse Rosenthal</cp:lastModifiedBy><cp:revision>1</cp:revision><dcterms:created xsi:type="dcterms:W3CDTF">2017-06-05T14:10:58Z</dcterms:created><dcterms:modified xsi:type="dcterms:W3CDTF">2017-06-05T14:12:07Z</dcterms:modified></cp:coreProperties>
+<cp:coreProperties xmlns:cp="http://schemas.openxmlformats.org/package/2006/metadata/core-properties" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:dcmitype="http://purl.org/dc/dcmitype/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><dc:title>Title</dc:title><dc:creator>Jesse Rosenthal</dc:creator><cp:lastModifiedBy>Jesse Rosenthal</cp:lastModifiedBy><cp:revision>5</cp:revision><dcterms:created xsi:type="dcterms:W3CDTF">2017-06-05T14:10:58Z</dcterms:created><dcterms:modified xsi:type="dcterms:W3CDTF">2022-01-02T22:49:03Z</dcterms:modified></cp:coreProperties>
diff --git a/data/pptx/docProps/thumbnail.jpeg b/data/pptx/docProps/thumbnail.jpeg
deleted file mode 100644
Binary files a/data/pptx/docProps/thumbnail.jpeg and /dev/null differ
diff --git a/data/pptx/ppt/_rels/presentation.xml.rels b/data/pptx/ppt/_rels/presentation.xml.rels
--- a/data/pptx/ppt/_rels/presentation.xml.rels
+++ b/data/pptx/ppt/_rels/presentation.xml.rels
@@ -1,2 +1,2 @@
 <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
-<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId3" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/slide" Target="slides/slide2.xml"/><Relationship Id="rId4" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/presProps" Target="presProps.xml"/><Relationship Id="rId5" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/viewProps" Target="viewProps.xml"/><Relationship Id="rId6" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme" Target="theme/theme1.xml"/><Relationship Id="rId7" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/tableStyles" Target="tableStyles.xml"/><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/slideMaster" Target="slideMasters/slideMaster1.xml"/><Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/slide" Target="slides/slide1.xml"/></Relationships>
+<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId8" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/viewProps" Target="viewProps.xml"/><Relationship Id="rId3" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/slide" Target="slides/slide2.xml"/><Relationship Id="rId7" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/presProps" Target="presProps.xml"/><Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/slide" Target="slides/slide1.xml"/><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/slideMaster" Target="slideMasters/slideMaster1.xml"/><Relationship Id="rId6" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/notesMaster" Target="notesMasters/notesMaster1.xml"/><Relationship Id="rId5" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/slide" Target="slides/slide4.xml"/><Relationship Id="rId10" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/tableStyles" Target="tableStyles.xml"/><Relationship Id="rId4" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/slide" Target="slides/slide3.xml"/><Relationship Id="rId9" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme" Target="theme/theme1.xml"/></Relationships>
diff --git a/data/pptx/ppt/notesMasters/_rels/notesMaster1.xml.rels b/data/pptx/ppt/notesMasters/_rels/notesMaster1.xml.rels
new file mode 100644
--- /dev/null
+++ b/data/pptx/ppt/notesMasters/_rels/notesMaster1.xml.rels
@@ -0,0 +1,2 @@
+<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
+<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme" Target="../theme/theme2.xml"/></Relationships>
diff --git a/data/pptx/ppt/notesMasters/notesMaster1.xml b/data/pptx/ppt/notesMasters/notesMaster1.xml
new file mode 100644
--- /dev/null
+++ b/data/pptx/ppt/notesMasters/notesMaster1.xml
@@ -0,0 +1,2 @@
+<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
+<p:notesMaster xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main"><p:cSld><p:bg><p:bgRef idx="1001"><a:schemeClr val="bg1"/></p:bgRef></p:bg><p:spTree><p:nvGrpSpPr><p:cNvPr id="1" name=""/><p:cNvGrpSpPr/><p:nvPr/></p:nvGrpSpPr><p:grpSpPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="0" cy="0"/><a:chOff x="0" y="0"/><a:chExt cx="0" cy="0"/></a:xfrm></p:grpSpPr><p:sp><p:nvSpPr><p:cNvPr id="2" name="Header Placeholder 1"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="hdr" sz="quarter"/></p:nvPr></p:nvSpPr><p:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="2971800" cy="458788"/></a:xfrm><a:prstGeom prst="rect"><a:avLst/></a:prstGeom></p:spPr><p:txBody><a:bodyPr vert="horz" lIns="91440" tIns="45720" rIns="91440" bIns="45720" rtlCol="0"/><a:lstStyle><a:lvl1pPr algn="l"><a:defRPr sz="1200"/></a:lvl1pPr></a:lstStyle><a:p><a:endParaRPr lang="en-US"/></a:p></p:txBody></p:sp><p:sp><p:nvSpPr><p:cNvPr id="3" name="Date Placeholder 2"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="dt" idx="1"/></p:nvPr></p:nvSpPr><p:spPr><a:xfrm><a:off x="3884613" y="0"/><a:ext cx="2971800" cy="458788"/></a:xfrm><a:prstGeom prst="rect"><a:avLst/></a:prstGeom></p:spPr><p:txBody><a:bodyPr vert="horz" lIns="91440" tIns="45720" rIns="91440" bIns="45720" rtlCol="0"/><a:lstStyle><a:lvl1pPr algn="r"><a:defRPr sz="1200"/></a:lvl1pPr></a:lstStyle><a:p><a:fld id="{0F9C1CCF-B725-44A7-AA57-5E433BD85C9F}" type="datetimeFigureOut"><a:rPr lang="en-US" smtClean="0"/><a:t>1/2/22</a:t></a:fld><a:endParaRPr lang="en-US"/></a:p></p:txBody></p:sp><p:sp><p:nvSpPr><p:cNvPr id="4" name="Slide Image Placeholder 3"/><p:cNvSpPr><a:spLocks noGrp="1" noRot="1" noChangeAspect="1"/></p:cNvSpPr><p:nvPr><p:ph type="sldImg" idx="2"/></p:nvPr></p:nvSpPr><p:spPr><a:xfrm><a:off x="685800" y="1143000"/><a:ext cx="5486400" cy="3086100"/></a:xfrm><a:prstGeom prst="rect"><a:avLst/></a:prstGeom><a:noFill/><a:ln w="12700"><a:solidFill><a:prstClr val="black"/></a:solidFill></a:ln></p:spPr><p:txBody><a:bodyPr vert="horz" lIns="91440" tIns="45720" rIns="91440" bIns="45720" rtlCol="0" anchor="ctr"/><a:lstStyle/><a:p><a:endParaRPr lang="en-US"/></a:p></p:txBody></p:sp><p:sp><p:nvSpPr><p:cNvPr id="5" name="Notes Placeholder 4"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="body" sz="quarter" idx="3"/></p:nvPr></p:nvSpPr><p:spPr><a:xfrm><a:off x="685800" y="4400550"/><a:ext cx="5486400" cy="3600450"/></a:xfrm><a:prstGeom prst="rect"><a:avLst/></a:prstGeom></p:spPr><p:txBody><a:bodyPr vert="horz" lIns="91440" tIns="45720" rIns="91440" bIns="45720" rtlCol="0"/><a:lstStyle/><a:p><a:pPr lvl="0"/><a:r><a:rPr lang="en-US"/><a:t>Click to edit Master text styles</a:t></a:r></a:p><a:p><a:pPr lvl="1"/><a:r><a:rPr lang="en-US"/><a:t>Second level</a:t></a:r></a:p><a:p><a:pPr lvl="2"/><a:r><a:rPr lang="en-US"/><a:t>Third level</a:t></a:r></a:p><a:p><a:pPr lvl="3"/><a:r><a:rPr lang="en-US"/><a:t>Fourth level</a:t></a:r></a:p><a:p><a:pPr lvl="4"/><a:r><a:rPr lang="en-US"/><a:t>Fifth level</a:t></a:r></a:p></p:txBody></p:sp><p:sp><p:nvSpPr><p:cNvPr id="6" name="Footer Placeholder 5"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="ftr" sz="quarter" idx="4"/></p:nvPr></p:nvSpPr><p:spPr><a:xfrm><a:off x="0" y="8685213"/><a:ext cx="2971800" cy="458787"/></a:xfrm><a:prstGeom prst="rect"><a:avLst/></a:prstGeom></p:spPr><p:txBody><a:bodyPr vert="horz" lIns="91440" tIns="45720" rIns="91440" bIns="45720" rtlCol="0" anchor="b"/><a:lstStyle><a:lvl1pPr algn="l"><a:defRPr sz="1200"/></a:lvl1pPr></a:lstStyle><a:p><a:endParaRPr lang="en-US"/></a:p></p:txBody></p:sp><p:sp><p:nvSpPr><p:cNvPr id="7" name="Slide Number Placeholder 6"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="sldNum" sz="quarter" idx="5"/></p:nvPr></p:nvSpPr><p:spPr><a:xfrm><a:off x="3884613" y="8685213"/><a:ext cx="2971800" cy="458787"/></a:xfrm><a:prstGeom prst="rect"><a:avLst/></a:prstGeom></p:spPr><p:txBody><a:bodyPr vert="horz" lIns="91440" tIns="45720" rIns="91440" bIns="45720" rtlCol="0" anchor="b"/><a:lstStyle><a:lvl1pPr algn="r"><a:defRPr sz="1200"/></a:lvl1pPr></a:lstStyle><a:p><a:fld id="{18BDFEC3-8487-43E8-A154-7C12CBC1FFF2}" type="slidenum"><a:rPr lang="en-US" smtClean="0"/><a:t>‹#›</a:t></a:fld><a:endParaRPr lang="en-US"/></a:p></p:txBody></p:sp></p:spTree><p:extLst><p:ext uri="{BB962C8B-B14F-4D97-AF65-F5344CB8AC3E}"><p14:creationId xmlns:p14="http://schemas.microsoft.com/office/powerpoint/2010/main" val="3782709779"/></p:ext></p:extLst></p:cSld><p:clrMap bg1="lt1" tx1="dk1" bg2="lt2" tx2="dk2" accent1="accent1" accent2="accent2" accent3="accent3" accent4="accent4" accent5="accent5" accent6="accent6" hlink="hlink" folHlink="folHlink"/><p:notesStyle><a:lvl1pPr marL="0" algn="l" defTabSz="914400" rtl="0" eaLnBrk="1" latinLnBrk="0" hangingPunct="1"><a:defRPr sz="1200" kern="1200"><a:solidFill><a:schemeClr val="tx1"/></a:solidFill><a:latin typeface="+mn-lt"/><a:ea typeface="+mn-ea"/><a:cs typeface="+mn-cs"/></a:defRPr></a:lvl1pPr><a:lvl2pPr marL="457200" algn="l" defTabSz="914400" rtl="0" eaLnBrk="1" latinLnBrk="0" hangingPunct="1"><a:defRPr sz="1200" kern="1200"><a:solidFill><a:schemeClr val="tx1"/></a:solidFill><a:latin typeface="+mn-lt"/><a:ea typeface="+mn-ea"/><a:cs typeface="+mn-cs"/></a:defRPr></a:lvl2pPr><a:lvl3pPr marL="914400" algn="l" defTabSz="914400" rtl="0" eaLnBrk="1" latinLnBrk="0" hangingPunct="1"><a:defRPr sz="1200" kern="1200"><a:solidFill><a:schemeClr val="tx1"/></a:solidFill><a:latin typeface="+mn-lt"/><a:ea typeface="+mn-ea"/><a:cs typeface="+mn-cs"/></a:defRPr></a:lvl3pPr><a:lvl4pPr marL="1371600" algn="l" defTabSz="914400" rtl="0" eaLnBrk="1" latinLnBrk="0" hangingPunct="1"><a:defRPr sz="1200" kern="1200"><a:solidFill><a:schemeClr val="tx1"/></a:solidFill><a:latin typeface="+mn-lt"/><a:ea typeface="+mn-ea"/><a:cs typeface="+mn-cs"/></a:defRPr></a:lvl4pPr><a:lvl5pPr marL="1828800" algn="l" defTabSz="914400" rtl="0" eaLnBrk="1" latinLnBrk="0" hangingPunct="1"><a:defRPr sz="1200" kern="1200"><a:solidFill><a:schemeClr val="tx1"/></a:solidFill><a:latin typeface="+mn-lt"/><a:ea typeface="+mn-ea"/><a:cs typeface="+mn-cs"/></a:defRPr></a:lvl5pPr><a:lvl6pPr marL="2286000" algn="l" defTabSz="914400" rtl="0" eaLnBrk="1" latinLnBrk="0" hangingPunct="1"><a:defRPr sz="1200" kern="1200"><a:solidFill><a:schemeClr val="tx1"/></a:solidFill><a:latin typeface="+mn-lt"/><a:ea typeface="+mn-ea"/><a:cs typeface="+mn-cs"/></a:defRPr></a:lvl6pPr><a:lvl7pPr marL="2743200" algn="l" defTabSz="914400" rtl="0" eaLnBrk="1" latinLnBrk="0" hangingPunct="1"><a:defRPr sz="1200" kern="1200"><a:solidFill><a:schemeClr val="tx1"/></a:solidFill><a:latin typeface="+mn-lt"/><a:ea typeface="+mn-ea"/><a:cs typeface="+mn-cs"/></a:defRPr></a:lvl7pPr><a:lvl8pPr marL="3200400" algn="l" defTabSz="914400" rtl="0" eaLnBrk="1" latinLnBrk="0" hangingPunct="1"><a:defRPr sz="1200" kern="1200"><a:solidFill><a:schemeClr val="tx1"/></a:solidFill><a:latin typeface="+mn-lt"/><a:ea typeface="+mn-ea"/><a:cs typeface="+mn-cs"/></a:defRPr></a:lvl8pPr><a:lvl9pPr marL="3657600" algn="l" defTabSz="914400" rtl="0" eaLnBrk="1" latinLnBrk="0" hangingPunct="1"><a:defRPr sz="1200" kern="1200"><a:solidFill><a:schemeClr val="tx1"/></a:solidFill><a:latin typeface="+mn-lt"/><a:ea typeface="+mn-ea"/><a:cs typeface="+mn-cs"/></a:defRPr></a:lvl9pPr></p:notesStyle></p:notesMaster>
diff --git a/data/pptx/ppt/notesSlides/_rels/notesSlide1.xml.rels b/data/pptx/ppt/notesSlides/_rels/notesSlide1.xml.rels
new file mode 100644
--- /dev/null
+++ b/data/pptx/ppt/notesSlides/_rels/notesSlide1.xml.rels
@@ -0,0 +1,2 @@
+<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
+<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/slide" Target="../slides/slide1.xml"/><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/notesMaster" Target="../notesMasters/notesMaster1.xml"/></Relationships>
diff --git a/data/pptx/ppt/notesSlides/_rels/notesSlide2.xml.rels b/data/pptx/ppt/notesSlides/_rels/notesSlide2.xml.rels
new file mode 100644
--- /dev/null
+++ b/data/pptx/ppt/notesSlides/_rels/notesSlide2.xml.rels
@@ -0,0 +1,2 @@
+<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
+<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/slide" Target="../slides/slide2.xml"/><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/notesMaster" Target="../notesMasters/notesMaster1.xml"/></Relationships>
diff --git a/data/pptx/ppt/notesSlides/notesSlide1.xml b/data/pptx/ppt/notesSlides/notesSlide1.xml
new file mode 100644
--- /dev/null
+++ b/data/pptx/ppt/notesSlides/notesSlide1.xml
@@ -0,0 +1,2 @@
+<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
+<p:notes xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main"><p:cSld><p:spTree><p:nvGrpSpPr><p:cNvPr id="1" name=""/><p:cNvGrpSpPr/><p:nvPr/></p:nvGrpSpPr><p:grpSpPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="0" cy="0"/><a:chOff x="0" y="0"/><a:chExt cx="0" cy="0"/></a:xfrm></p:grpSpPr><p:sp><p:nvSpPr><p:cNvPr id="2" name="Slide Image Placeholder 1"/><p:cNvSpPr><a:spLocks noGrp="1" noRot="1" noChangeAspect="1"/></p:cNvSpPr><p:nvPr><p:ph type="sldImg"/></p:nvPr></p:nvSpPr><p:spPr><a:xfrm><a:off x="685800" y="1143000"/><a:ext cx="5486400" cy="3086100"/></a:xfrm></p:spPr></p:sp><p:sp><p:nvSpPr><p:cNvPr id="3" name="Notes Placeholder 2"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="body" idx="1"/></p:nvPr></p:nvSpPr><p:spPr/><p:txBody><a:bodyPr/><a:lstStyle/><a:p><a:r><a:rPr lang="en-US" dirty="0"/><a:t>Here</a:t></a:r><a:r><a:rPr lang="en-US" baseline="0" dirty="0"/><a:t> is a note</a:t></a:r></a:p><a:p><a:endParaRPr lang="en-US" baseline="0" dirty="0"/></a:p><a:p><a:r><a:rPr lang="en-US" baseline="0" dirty="0"/><a:t>With another paragraph.</a:t></a:r><a:endParaRPr lang="en-US" dirty="0"/></a:p></p:txBody></p:sp><p:sp><p:nvSpPr><p:cNvPr id="4" name="Slide Number Placeholder 3"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="sldNum" sz="quarter" idx="10"/></p:nvPr></p:nvSpPr><p:spPr/><p:txBody><a:bodyPr/><a:lstStyle/><a:p><a:fld id="{18BDFEC3-8487-43E8-A154-7C12CBC1FFF2}" type="slidenum"><a:rPr lang="en-US" smtClean="0"/><a:t>1</a:t></a:fld><a:endParaRPr lang="en-US"/></a:p></p:txBody></p:sp></p:spTree><p:extLst><p:ext uri="{BB962C8B-B14F-4D97-AF65-F5344CB8AC3E}"><p14:creationId xmlns:p14="http://schemas.microsoft.com/office/powerpoint/2010/main" val="3171319170"/></p:ext></p:extLst></p:cSld><p:clrMapOvr><a:masterClrMapping/></p:clrMapOvr></p:notes>
diff --git a/data/pptx/ppt/notesSlides/notesSlide2.xml b/data/pptx/ppt/notesSlides/notesSlide2.xml
new file mode 100644
--- /dev/null
+++ b/data/pptx/ppt/notesSlides/notesSlide2.xml
@@ -0,0 +1,2 @@
+<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
+<p:notes xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main"><p:cSld><p:spTree><p:nvGrpSpPr><p:cNvPr id="1" name=""/><p:cNvGrpSpPr/><p:nvPr/></p:nvGrpSpPr><p:grpSpPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="0" cy="0"/><a:chOff x="0" y="0"/><a:chExt cx="0" cy="0"/></a:xfrm></p:grpSpPr><p:sp><p:nvSpPr><p:cNvPr id="2" name="Slide Image Placeholder 1"/><p:cNvSpPr><a:spLocks noGrp="1" noRot="1" noChangeAspect="1"/></p:cNvSpPr><p:nvPr><p:ph type="sldImg"/></p:nvPr></p:nvSpPr><p:spPr><a:xfrm><a:off x="685800" y="1143000"/><a:ext cx="5486400" cy="3086100"/></a:xfrm></p:spPr></p:sp><p:sp><p:nvSpPr><p:cNvPr id="3" name="Notes Placeholder 2"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="body" idx="1"/></p:nvPr></p:nvSpPr><p:spPr/><p:txBody><a:bodyPr/><a:lstStyle/><a:p><a:r><a:rPr lang="en-US" dirty="0"/><a:t>A</a:t></a:r><a:r><a:rPr lang="en-US" baseline="0" dirty="0"/><a:t> speaker note on </a:t></a:r><a:r><a:rPr lang="en-US" baseline="0"/><a:t>this slide too.</a:t></a:r><a:endParaRPr lang="en-US"/></a:p></p:txBody></p:sp><p:sp><p:nvSpPr><p:cNvPr id="4" name="Slide Number Placeholder 3"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="sldNum" sz="quarter" idx="10"/></p:nvPr></p:nvSpPr><p:spPr/><p:txBody><a:bodyPr/><a:lstStyle/><a:p><a:fld id="{18BDFEC3-8487-43E8-A154-7C12CBC1FFF2}" type="slidenum"><a:rPr lang="en-US" smtClean="0"/><a:t>2</a:t></a:fld><a:endParaRPr lang="en-US"/></a:p></p:txBody></p:sp></p:spTree><p:extLst><p:ext uri="{BB962C8B-B14F-4D97-AF65-F5344CB8AC3E}"><p14:creationId xmlns:p14="http://schemas.microsoft.com/office/powerpoint/2010/main" val="3016900036"/></p:ext></p:extLst></p:cSld><p:clrMapOvr><a:masterClrMapping/></p:clrMapOvr></p:notes>
diff --git a/data/pptx/ppt/presProps.xml b/data/pptx/ppt/presProps.xml
--- a/data/pptx/ppt/presProps.xml
+++ b/data/pptx/ppt/presProps.xml
@@ -1,2 +1,2 @@
 <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
-<p:presentationPr xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main"><p:extLst><p:ext uri="{E76CE94A-603C-4142-B9EB-6D1370010A27}"><p14:discardImageEditData xmlns:p14="http://schemas.microsoft.com/office/powerpoint/2010/main" val="0"/></p:ext><p:ext uri="{D31A062A-798A-4329-ABDD-BBA856620510}"><p14:defaultImageDpi xmlns:p14="http://schemas.microsoft.com/office/powerpoint/2010/main" val="0"/></p:ext></p:extLst></p:presentationPr>
+<p:presentationPr xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main"><p:extLst><p:ext uri="{E76CE94A-603C-4142-B9EB-6D1370010A27}"><p14:discardImageEditData xmlns:p14="http://schemas.microsoft.com/office/powerpoint/2010/main" val="0"/></p:ext><p:ext uri="{D31A062A-798A-4329-ABDD-BBA856620510}"><p14:defaultImageDpi xmlns:p14="http://schemas.microsoft.com/office/powerpoint/2010/main" val="0"/></p:ext><p:ext uri="{FD5EFAAD-0ECE-453E-9831-46B23BE46B34}"><p15:chartTrackingRefBased xmlns:p15="http://schemas.microsoft.com/office/powerpoint/2012/main" val="0"/></p:ext></p:extLst></p:presentationPr>
diff --git a/data/pptx/ppt/presentation.xml b/data/pptx/ppt/presentation.xml
--- a/data/pptx/ppt/presentation.xml
+++ b/data/pptx/ppt/presentation.xml
@@ -1,2 +1,2 @@
 <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
-<p:presentation xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main" saveSubsetFonts="1" autoCompressPictures="0"><p:sldMasterIdLst><p:sldMasterId id="2147483648" r:id="rId1"/></p:sldMasterIdLst><p:sldIdLst><p:sldId id="256" r:id="rId2"/><p:sldId id="257" r:id="rId3"/></p:sldIdLst><p:sldSz cx="9144000" cy="6858000" type="screen4x3"/><p:notesSz cx="6858000" cy="9144000"/><p:defaultTextStyle><a:defPPr><a:defRPr lang="en-US"/></a:defPPr><a:lvl1pPr marL="0" algn="l" defTabSz="457200" rtl="0" eaLnBrk="1" latinLnBrk="0" hangingPunct="1"><a:defRPr sz="1800" kern="1200"><a:solidFill><a:schemeClr val="tx1"/></a:solidFill><a:latin typeface="+mn-lt"/><a:ea typeface="+mn-ea"/><a:cs typeface="+mn-cs"/></a:defRPr></a:lvl1pPr><a:lvl2pPr marL="457200" algn="l" defTabSz="457200" rtl="0" eaLnBrk="1" latinLnBrk="0" hangingPunct="1"><a:defRPr sz="1800" kern="1200"><a:solidFill><a:schemeClr val="tx1"/></a:solidFill><a:latin typeface="+mn-lt"/><a:ea typeface="+mn-ea"/><a:cs typeface="+mn-cs"/></a:defRPr></a:lvl2pPr><a:lvl3pPr marL="914400" algn="l" defTabSz="457200" rtl="0" eaLnBrk="1" latinLnBrk="0" hangingPunct="1"><a:defRPr sz="1800" kern="1200"><a:solidFill><a:schemeClr val="tx1"/></a:solidFill><a:latin typeface="+mn-lt"/><a:ea typeface="+mn-ea"/><a:cs typeface="+mn-cs"/></a:defRPr></a:lvl3pPr><a:lvl4pPr marL="1371600" algn="l" defTabSz="457200" rtl="0" eaLnBrk="1" latinLnBrk="0" hangingPunct="1"><a:defRPr sz="1800" kern="1200"><a:solidFill><a:schemeClr val="tx1"/></a:solidFill><a:latin typeface="+mn-lt"/><a:ea typeface="+mn-ea"/><a:cs typeface="+mn-cs"/></a:defRPr></a:lvl4pPr><a:lvl5pPr marL="1828800" algn="l" defTabSz="457200" rtl="0" eaLnBrk="1" latinLnBrk="0" hangingPunct="1"><a:defRPr sz="1800" kern="1200"><a:solidFill><a:schemeClr val="tx1"/></a:solidFill><a:latin typeface="+mn-lt"/><a:ea typeface="+mn-ea"/><a:cs typeface="+mn-cs"/></a:defRPr></a:lvl5pPr><a:lvl6pPr marL="2286000" algn="l" defTabSz="457200" rtl="0" eaLnBrk="1" latinLnBrk="0" hangingPunct="1"><a:defRPr sz="1800" kern="1200"><a:solidFill><a:schemeClr val="tx1"/></a:solidFill><a:latin typeface="+mn-lt"/><a:ea typeface="+mn-ea"/><a:cs typeface="+mn-cs"/></a:defRPr></a:lvl6pPr><a:lvl7pPr marL="2743200" algn="l" defTabSz="457200" rtl="0" eaLnBrk="1" latinLnBrk="0" hangingPunct="1"><a:defRPr sz="1800" kern="1200"><a:solidFill><a:schemeClr val="tx1"/></a:solidFill><a:latin typeface="+mn-lt"/><a:ea typeface="+mn-ea"/><a:cs typeface="+mn-cs"/></a:defRPr></a:lvl7pPr><a:lvl8pPr marL="3200400" algn="l" defTabSz="457200" rtl="0" eaLnBrk="1" latinLnBrk="0" hangingPunct="1"><a:defRPr sz="1800" kern="1200"><a:solidFill><a:schemeClr val="tx1"/></a:solidFill><a:latin typeface="+mn-lt"/><a:ea typeface="+mn-ea"/><a:cs typeface="+mn-cs"/></a:defRPr></a:lvl8pPr><a:lvl9pPr marL="3657600" algn="l" defTabSz="457200" rtl="0" eaLnBrk="1" latinLnBrk="0" hangingPunct="1"><a:defRPr sz="1800" kern="1200"><a:solidFill><a:schemeClr val="tx1"/></a:solidFill><a:latin typeface="+mn-lt"/><a:ea typeface="+mn-ea"/><a:cs typeface="+mn-cs"/></a:defRPr></a:lvl9pPr></p:defaultTextStyle></p:presentation>
+<p:presentation xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main" saveSubsetFonts="1" autoCompressPictures="0"><p:sldMasterIdLst><p:sldMasterId id="2147483648" r:id="rId1"/></p:sldMasterIdLst><p:notesMasterIdLst><p:notesMasterId r:id="rId6"/></p:notesMasterIdLst><p:sldIdLst><p:sldId id="256" r:id="rId2"/><p:sldId id="257" r:id="rId3"/><p:sldId id="258" r:id="rId4"/><p:sldId id="259" r:id="rId5"/></p:sldIdLst><p:sldSz cx="9144000" cy="5143500" type="screen16x9"/><p:notesSz cx="6858000" cy="9144000"/><p:defaultTextStyle><a:defPPr><a:defRPr lang="en-US"/></a:defPPr><a:lvl1pPr marL="0" algn="l" defTabSz="457200" rtl="0" eaLnBrk="1" latinLnBrk="0" hangingPunct="1"><a:defRPr sz="1800" kern="1200"><a:solidFill><a:schemeClr val="tx1"/></a:solidFill><a:latin typeface="+mn-lt"/><a:ea typeface="+mn-ea"/><a:cs typeface="+mn-cs"/></a:defRPr></a:lvl1pPr><a:lvl2pPr marL="457200" algn="l" defTabSz="457200" rtl="0" eaLnBrk="1" latinLnBrk="0" hangingPunct="1"><a:defRPr sz="1800" kern="1200"><a:solidFill><a:schemeClr val="tx1"/></a:solidFill><a:latin typeface="+mn-lt"/><a:ea typeface="+mn-ea"/><a:cs typeface="+mn-cs"/></a:defRPr></a:lvl2pPr><a:lvl3pPr marL="914400" algn="l" defTabSz="457200" rtl="0" eaLnBrk="1" latinLnBrk="0" hangingPunct="1"><a:defRPr sz="1800" kern="1200"><a:solidFill><a:schemeClr val="tx1"/></a:solidFill><a:latin typeface="+mn-lt"/><a:ea typeface="+mn-ea"/><a:cs typeface="+mn-cs"/></a:defRPr></a:lvl3pPr><a:lvl4pPr marL="1371600" algn="l" defTabSz="457200" rtl="0" eaLnBrk="1" latinLnBrk="0" hangingPunct="1"><a:defRPr sz="1800" kern="1200"><a:solidFill><a:schemeClr val="tx1"/></a:solidFill><a:latin typeface="+mn-lt"/><a:ea typeface="+mn-ea"/><a:cs typeface="+mn-cs"/></a:defRPr></a:lvl4pPr><a:lvl5pPr marL="1828800" algn="l" defTabSz="457200" rtl="0" eaLnBrk="1" latinLnBrk="0" hangingPunct="1"><a:defRPr sz="1800" kern="1200"><a:solidFill><a:schemeClr val="tx1"/></a:solidFill><a:latin typeface="+mn-lt"/><a:ea typeface="+mn-ea"/><a:cs typeface="+mn-cs"/></a:defRPr></a:lvl5pPr><a:lvl6pPr marL="2286000" algn="l" defTabSz="457200" rtl="0" eaLnBrk="1" latinLnBrk="0" hangingPunct="1"><a:defRPr sz="1800" kern="1200"><a:solidFill><a:schemeClr val="tx1"/></a:solidFill><a:latin typeface="+mn-lt"/><a:ea typeface="+mn-ea"/><a:cs typeface="+mn-cs"/></a:defRPr></a:lvl6pPr><a:lvl7pPr marL="2743200" algn="l" defTabSz="457200" rtl="0" eaLnBrk="1" latinLnBrk="0" hangingPunct="1"><a:defRPr sz="1800" kern="1200"><a:solidFill><a:schemeClr val="tx1"/></a:solidFill><a:latin typeface="+mn-lt"/><a:ea typeface="+mn-ea"/><a:cs typeface="+mn-cs"/></a:defRPr></a:lvl7pPr><a:lvl8pPr marL="3200400" algn="l" defTabSz="457200" rtl="0" eaLnBrk="1" latinLnBrk="0" hangingPunct="1"><a:defRPr sz="1800" kern="1200"><a:solidFill><a:schemeClr val="tx1"/></a:solidFill><a:latin typeface="+mn-lt"/><a:ea typeface="+mn-ea"/><a:cs typeface="+mn-cs"/></a:defRPr></a:lvl8pPr><a:lvl9pPr marL="3657600" algn="l" defTabSz="457200" rtl="0" eaLnBrk="1" latinLnBrk="0" hangingPunct="1"><a:defRPr sz="1800" kern="1200"><a:solidFill><a:schemeClr val="tx1"/></a:solidFill><a:latin typeface="+mn-lt"/><a:ea typeface="+mn-ea"/><a:cs typeface="+mn-cs"/></a:defRPr></a:lvl9pPr></p:defaultTextStyle><p:extLst><p:ext uri="{EFAFB233-063F-42B5-8137-9DF3F51BA10A}"><p15:sldGuideLst xmlns:p15="http://schemas.microsoft.com/office/powerpoint/2012/main"><p15:guide id="1" orient="horz" pos="1620" userDrawn="1"><p15:clr><a:srgbClr val="A4A3A4"/></p15:clr></p15:guide><p15:guide id="2" pos="2880" userDrawn="1"><p15:clr><a:srgbClr val="A4A3A4"/></p15:clr></p15:guide></p15:sldGuideLst></p:ext></p:extLst></p:presentation>
diff --git a/data/pptx/ppt/slideLayouts/slideLayout1.xml b/data/pptx/ppt/slideLayouts/slideLayout1.xml
--- a/data/pptx/ppt/slideLayouts/slideLayout1.xml
+++ b/data/pptx/ppt/slideLayouts/slideLayout1.xml
@@ -1,2 +1,2 @@
 <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
-<p:sldLayout xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main" type="title" preserve="1"><p:cSld name="Title Slide"><p:spTree><p:nvGrpSpPr><p:cNvPr id="1" name=""/><p:cNvGrpSpPr/><p:nvPr/></p:nvGrpSpPr><p:grpSpPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="0" cy="0"/><a:chOff x="0" y="0"/><a:chExt cx="0" cy="0"/></a:xfrm></p:grpSpPr><p:sp><p:nvSpPr><p:cNvPr id="2" name="Title 1"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="ctrTitle"/></p:nvPr></p:nvSpPr><p:spPr><a:xfrm><a:off x="685800" y="2130425"/><a:ext cx="7772400" cy="1470025"/></a:xfrm></p:spPr><p:txBody><a:bodyPr/><a:lstStyle/><a:p><a:r><a:rPr lang="en-US" smtClean="0"/><a:t>Click to edit Master title style</a:t></a:r><a:endParaRPr lang="en-US"/></a:p></p:txBody></p:sp><p:sp><p:nvSpPr><p:cNvPr id="3" name="Subtitle 2"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="subTitle" idx="1"/></p:nvPr></p:nvSpPr><p:spPr><a:xfrm><a:off x="1371600" y="3886200"/><a:ext cx="6400800" cy="1752600"/></a:xfrm></p:spPr><p:txBody><a:bodyPr/><a:lstStyle><a:lvl1pPr marL="0" indent="0" algn="ctr"><a:buNone/><a:defRPr><a:solidFill><a:schemeClr val="tx1"><a:tint val="75000"/></a:schemeClr></a:solidFill></a:defRPr></a:lvl1pPr><a:lvl2pPr marL="457200" indent="0" algn="ctr"><a:buNone/><a:defRPr><a:solidFill><a:schemeClr val="tx1"><a:tint val="75000"/></a:schemeClr></a:solidFill></a:defRPr></a:lvl2pPr><a:lvl3pPr marL="914400" indent="0" algn="ctr"><a:buNone/><a:defRPr><a:solidFill><a:schemeClr val="tx1"><a:tint val="75000"/></a:schemeClr></a:solidFill></a:defRPr></a:lvl3pPr><a:lvl4pPr marL="1371600" indent="0" algn="ctr"><a:buNone/><a:defRPr><a:solidFill><a:schemeClr val="tx1"><a:tint val="75000"/></a:schemeClr></a:solidFill></a:defRPr></a:lvl4pPr><a:lvl5pPr marL="1828800" indent="0" algn="ctr"><a:buNone/><a:defRPr><a:solidFill><a:schemeClr val="tx1"><a:tint val="75000"/></a:schemeClr></a:solidFill></a:defRPr></a:lvl5pPr><a:lvl6pPr marL="2286000" indent="0" algn="ctr"><a:buNone/><a:defRPr><a:solidFill><a:schemeClr val="tx1"><a:tint val="75000"/></a:schemeClr></a:solidFill></a:defRPr></a:lvl6pPr><a:lvl7pPr marL="2743200" indent="0" algn="ctr"><a:buNone/><a:defRPr><a:solidFill><a:schemeClr val="tx1"><a:tint val="75000"/></a:schemeClr></a:solidFill></a:defRPr></a:lvl7pPr><a:lvl8pPr marL="3200400" indent="0" algn="ctr"><a:buNone/><a:defRPr><a:solidFill><a:schemeClr val="tx1"><a:tint val="75000"/></a:schemeClr></a:solidFill></a:defRPr></a:lvl8pPr><a:lvl9pPr marL="3657600" indent="0" algn="ctr"><a:buNone/><a:defRPr><a:solidFill><a:schemeClr val="tx1"><a:tint val="75000"/></a:schemeClr></a:solidFill></a:defRPr></a:lvl9pPr></a:lstStyle><a:p><a:r><a:rPr lang="en-US" smtClean="0"/><a:t>Click to edit Master subtitle style</a:t></a:r><a:endParaRPr lang="en-US"/></a:p></p:txBody></p:sp><p:sp><p:nvSpPr><p:cNvPr id="4" name="Date Placeholder 3"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="dt" sz="half" idx="10"/></p:nvPr></p:nvSpPr><p:spPr/><p:txBody><a:bodyPr/><a:lstStyle/><a:p><a:fld id="{241EB5C9-1307-BA42-ABA2-0BC069CD8E7F}" type="datetimeFigureOut"><a:rPr lang="en-US" smtClean="0"/><a:t>6/5/17</a:t></a:fld><a:endParaRPr lang="en-US"/></a:p></p:txBody></p:sp><p:sp><p:nvSpPr><p:cNvPr id="5" name="Footer Placeholder 4"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="ftr" sz="quarter" idx="11"/></p:nvPr></p:nvSpPr><p:spPr/><p:txBody><a:bodyPr/><a:lstStyle/><a:p><a:endParaRPr lang="en-US"/></a:p></p:txBody></p:sp><p:sp><p:nvSpPr><p:cNvPr id="6" name="Slide Number Placeholder 5"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="sldNum" sz="quarter" idx="12"/></p:nvPr></p:nvSpPr><p:spPr/><p:txBody><a:bodyPr/><a:lstStyle/><a:p><a:fld id="{C5EF2332-01BF-834F-8236-50238282D533}" type="slidenum"><a:rPr lang="en-US" smtClean="0"/><a:t>‹#›</a:t></a:fld><a:endParaRPr lang="en-US"/></a:p></p:txBody></p:sp></p:spTree><p:extLst><p:ext uri="{BB962C8B-B14F-4D97-AF65-F5344CB8AC3E}"><p14:creationId xmlns:p14="http://schemas.microsoft.com/office/powerpoint/2010/main" val="1444357513"/></p:ext></p:extLst></p:cSld><p:clrMapOvr><a:masterClrMapping/></p:clrMapOvr></p:sldLayout>
+<p:sldLayout xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main" type="title" preserve="1"><p:cSld name="Title Slide"><p:spTree><p:nvGrpSpPr><p:cNvPr id="1" name=""/><p:cNvGrpSpPr/><p:nvPr/></p:nvGrpSpPr><p:grpSpPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="0" cy="0"/><a:chOff x="0" y="0"/><a:chExt cx="0" cy="0"/></a:xfrm></p:grpSpPr><p:sp><p:nvSpPr><p:cNvPr id="2" name="Title 1"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="ctrTitle"/></p:nvPr></p:nvSpPr><p:spPr><a:xfrm><a:off x="685800" y="1597819"/><a:ext cx="7772400" cy="1102519"/></a:xfrm></p:spPr><p:txBody><a:bodyPr/><a:lstStyle/><a:p><a:r><a:rPr lang="en-US"/><a:t>Click to edit Master title style</a:t></a:r></a:p></p:txBody></p:sp><p:sp><p:nvSpPr><p:cNvPr id="3" name="Subtitle 2"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="subTitle" idx="1"/></p:nvPr></p:nvSpPr><p:spPr><a:xfrm><a:off x="1371600" y="2914650"/><a:ext cx="6400800" cy="1314450"/></a:xfrm></p:spPr><p:txBody><a:bodyPr/><a:lstStyle><a:lvl1pPr marL="0" indent="0" algn="ctr"><a:buNone/><a:defRPr><a:solidFill><a:schemeClr val="tx1"><a:tint val="75000"/></a:schemeClr></a:solidFill></a:defRPr></a:lvl1pPr><a:lvl2pPr marL="342900" indent="0" algn="ctr"><a:buNone/><a:defRPr><a:solidFill><a:schemeClr val="tx1"><a:tint val="75000"/></a:schemeClr></a:solidFill></a:defRPr></a:lvl2pPr><a:lvl3pPr marL="685800" indent="0" algn="ctr"><a:buNone/><a:defRPr><a:solidFill><a:schemeClr val="tx1"><a:tint val="75000"/></a:schemeClr></a:solidFill></a:defRPr></a:lvl3pPr><a:lvl4pPr marL="1028700" indent="0" algn="ctr"><a:buNone/><a:defRPr><a:solidFill><a:schemeClr val="tx1"><a:tint val="75000"/></a:schemeClr></a:solidFill></a:defRPr></a:lvl4pPr><a:lvl5pPr marL="1371600" indent="0" algn="ctr"><a:buNone/><a:defRPr><a:solidFill><a:schemeClr val="tx1"><a:tint val="75000"/></a:schemeClr></a:solidFill></a:defRPr></a:lvl5pPr><a:lvl6pPr marL="1714500" indent="0" algn="ctr"><a:buNone/><a:defRPr><a:solidFill><a:schemeClr val="tx1"><a:tint val="75000"/></a:schemeClr></a:solidFill></a:defRPr></a:lvl6pPr><a:lvl7pPr marL="2057400" indent="0" algn="ctr"><a:buNone/><a:defRPr><a:solidFill><a:schemeClr val="tx1"><a:tint val="75000"/></a:schemeClr></a:solidFill></a:defRPr></a:lvl7pPr><a:lvl8pPr marL="2400300" indent="0" algn="ctr"><a:buNone/><a:defRPr><a:solidFill><a:schemeClr val="tx1"><a:tint val="75000"/></a:schemeClr></a:solidFill></a:defRPr></a:lvl8pPr><a:lvl9pPr marL="2743200" indent="0" algn="ctr"><a:buNone/><a:defRPr><a:solidFill><a:schemeClr val="tx1"><a:tint val="75000"/></a:schemeClr></a:solidFill></a:defRPr></a:lvl9pPr></a:lstStyle><a:p><a:r><a:rPr lang="en-US"/><a:t>Click to edit Master subtitle style</a:t></a:r></a:p></p:txBody></p:sp><p:sp><p:nvSpPr><p:cNvPr id="4" name="Date Placeholder 3"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="dt" sz="half" idx="10"/></p:nvPr></p:nvSpPr><p:spPr/><p:txBody><a:bodyPr/><a:lstStyle/><a:p><a:fld id="{241EB5C9-1307-BA42-ABA2-0BC069CD8E7F}" type="datetimeFigureOut"><a:rPr lang="en-US" smtClean="0"/><a:t>1/2/22</a:t></a:fld><a:endParaRPr lang="en-US"/></a:p></p:txBody></p:sp><p:sp><p:nvSpPr><p:cNvPr id="5" name="Footer Placeholder 4"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="ftr" sz="quarter" idx="11"/></p:nvPr></p:nvSpPr><p:spPr/><p:txBody><a:bodyPr/><a:lstStyle/><a:p><a:endParaRPr lang="en-US"/></a:p></p:txBody></p:sp><p:sp><p:nvSpPr><p:cNvPr id="6" name="Slide Number Placeholder 5"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="sldNum" sz="quarter" idx="12"/></p:nvPr></p:nvSpPr><p:spPr/><p:txBody><a:bodyPr/><a:lstStyle/><a:p><a:fld id="{C5EF2332-01BF-834F-8236-50238282D533}" type="slidenum"><a:rPr lang="en-US" smtClean="0"/><a:t>‹#›</a:t></a:fld><a:endParaRPr lang="en-US"/></a:p></p:txBody></p:sp></p:spTree><p:extLst><p:ext uri="{BB962C8B-B14F-4D97-AF65-F5344CB8AC3E}"><p14:creationId xmlns:p14="http://schemas.microsoft.com/office/powerpoint/2010/main" val="1444357513"/></p:ext></p:extLst></p:cSld><p:clrMapOvr><a:masterClrMapping/></p:clrMapOvr></p:sldLayout>
diff --git a/data/pptx/ppt/slideLayouts/slideLayout10.xml b/data/pptx/ppt/slideLayouts/slideLayout10.xml
--- a/data/pptx/ppt/slideLayouts/slideLayout10.xml
+++ b/data/pptx/ppt/slideLayouts/slideLayout10.xml
@@ -1,2 +1,2 @@
 <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
-<p:sldLayout xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main" type="vertTx" preserve="1"><p:cSld name="Title and Vertical Text"><p:spTree><p:nvGrpSpPr><p:cNvPr id="1" name=""/><p:cNvGrpSpPr/><p:nvPr/></p:nvGrpSpPr><p:grpSpPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="0" cy="0"/><a:chOff x="0" y="0"/><a:chExt cx="0" cy="0"/></a:xfrm></p:grpSpPr><p:sp><p:nvSpPr><p:cNvPr id="2" name="Title 1"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="title"/></p:nvPr></p:nvSpPr><p:spPr/><p:txBody><a:bodyPr/><a:lstStyle/><a:p><a:r><a:rPr lang="en-US" smtClean="0"/><a:t>Click to edit Master title style</a:t></a:r><a:endParaRPr lang="en-US"/></a:p></p:txBody></p:sp><p:sp><p:nvSpPr><p:cNvPr id="3" name="Vertical Text Placeholder 2"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="body" orient="vert" idx="1"/></p:nvPr></p:nvSpPr><p:spPr/><p:txBody><a:bodyPr vert="eaVert"/><a:lstStyle/><a:p><a:pPr lvl="0"/><a:r><a:rPr lang="en-US" smtClean="0"/><a:t>Click to edit Master text styles</a:t></a:r></a:p><a:p><a:pPr lvl="1"/><a:r><a:rPr lang="en-US" smtClean="0"/><a:t>Second level</a:t></a:r></a:p><a:p><a:pPr lvl="2"/><a:r><a:rPr lang="en-US" smtClean="0"/><a:t>Third level</a:t></a:r></a:p><a:p><a:pPr lvl="3"/><a:r><a:rPr lang="en-US" smtClean="0"/><a:t>Fourth level</a:t></a:r></a:p><a:p><a:pPr lvl="4"/><a:r><a:rPr lang="en-US" smtClean="0"/><a:t>Fifth level</a:t></a:r><a:endParaRPr lang="en-US"/></a:p></p:txBody></p:sp><p:sp><p:nvSpPr><p:cNvPr id="4" name="Date Placeholder 3"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="dt" sz="half" idx="10"/></p:nvPr></p:nvSpPr><p:spPr/><p:txBody><a:bodyPr/><a:lstStyle/><a:p><a:fld id="{241EB5C9-1307-BA42-ABA2-0BC069CD8E7F}" type="datetimeFigureOut"><a:rPr lang="en-US" smtClean="0"/><a:t>6/5/17</a:t></a:fld><a:endParaRPr lang="en-US"/></a:p></p:txBody></p:sp><p:sp><p:nvSpPr><p:cNvPr id="5" name="Footer Placeholder 4"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="ftr" sz="quarter" idx="11"/></p:nvPr></p:nvSpPr><p:spPr/><p:txBody><a:bodyPr/><a:lstStyle/><a:p><a:endParaRPr lang="en-US"/></a:p></p:txBody></p:sp><p:sp><p:nvSpPr><p:cNvPr id="6" name="Slide Number Placeholder 5"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="sldNum" sz="quarter" idx="12"/></p:nvPr></p:nvSpPr><p:spPr/><p:txBody><a:bodyPr/><a:lstStyle/><a:p><a:fld id="{C5EF2332-01BF-834F-8236-50238282D533}" type="slidenum"><a:rPr lang="en-US" smtClean="0"/><a:t>‹#›</a:t></a:fld><a:endParaRPr lang="en-US"/></a:p></p:txBody></p:sp></p:spTree><p:extLst><p:ext uri="{BB962C8B-B14F-4D97-AF65-F5344CB8AC3E}"><p14:creationId xmlns:p14="http://schemas.microsoft.com/office/powerpoint/2010/main" val="313914798"/></p:ext></p:extLst></p:cSld><p:clrMapOvr><a:masterClrMapping/></p:clrMapOvr></p:sldLayout>
+<p:sldLayout xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main" type="vertTx" preserve="1"><p:cSld name="Title and Vertical Text"><p:spTree><p:nvGrpSpPr><p:cNvPr id="1" name=""/><p:cNvGrpSpPr/><p:nvPr/></p:nvGrpSpPr><p:grpSpPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="0" cy="0"/><a:chOff x="0" y="0"/><a:chExt cx="0" cy="0"/></a:xfrm></p:grpSpPr><p:sp><p:nvSpPr><p:cNvPr id="2" name="Title 1"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="title"/></p:nvPr></p:nvSpPr><p:spPr/><p:txBody><a:bodyPr/><a:lstStyle/><a:p><a:r><a:rPr lang="en-US"/><a:t>Click to edit Master title style</a:t></a:r></a:p></p:txBody></p:sp><p:sp><p:nvSpPr><p:cNvPr id="3" name="Vertical Text Placeholder 2"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="body" orient="vert" idx="1"/></p:nvPr></p:nvSpPr><p:spPr/><p:txBody><a:bodyPr vert="eaVert"/><a:lstStyle/><a:p><a:pPr lvl="0"/><a:r><a:rPr lang="en-US"/><a:t>Click to edit Master text styles</a:t></a:r></a:p><a:p><a:pPr lvl="1"/><a:r><a:rPr lang="en-US"/><a:t>Second level</a:t></a:r></a:p><a:p><a:pPr lvl="2"/><a:r><a:rPr lang="en-US"/><a:t>Third level</a:t></a:r></a:p><a:p><a:pPr lvl="3"/><a:r><a:rPr lang="en-US"/><a:t>Fourth level</a:t></a:r></a:p><a:p><a:pPr lvl="4"/><a:r><a:rPr lang="en-US"/><a:t>Fifth level</a:t></a:r></a:p></p:txBody></p:sp><p:sp><p:nvSpPr><p:cNvPr id="4" name="Date Placeholder 3"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="dt" sz="half" idx="10"/></p:nvPr></p:nvSpPr><p:spPr/><p:txBody><a:bodyPr/><a:lstStyle/><a:p><a:fld id="{241EB5C9-1307-BA42-ABA2-0BC069CD8E7F}" type="datetimeFigureOut"><a:rPr lang="en-US" smtClean="0"/><a:t>1/2/22</a:t></a:fld><a:endParaRPr lang="en-US"/></a:p></p:txBody></p:sp><p:sp><p:nvSpPr><p:cNvPr id="5" name="Footer Placeholder 4"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="ftr" sz="quarter" idx="11"/></p:nvPr></p:nvSpPr><p:spPr/><p:txBody><a:bodyPr/><a:lstStyle/><a:p><a:endParaRPr lang="en-US"/></a:p></p:txBody></p:sp><p:sp><p:nvSpPr><p:cNvPr id="6" name="Slide Number Placeholder 5"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="sldNum" sz="quarter" idx="12"/></p:nvPr></p:nvSpPr><p:spPr/><p:txBody><a:bodyPr/><a:lstStyle/><a:p><a:fld id="{C5EF2332-01BF-834F-8236-50238282D533}" type="slidenum"><a:rPr lang="en-US" smtClean="0"/><a:t>‹#›</a:t></a:fld><a:endParaRPr lang="en-US"/></a:p></p:txBody></p:sp></p:spTree><p:extLst><p:ext uri="{BB962C8B-B14F-4D97-AF65-F5344CB8AC3E}"><p14:creationId xmlns:p14="http://schemas.microsoft.com/office/powerpoint/2010/main" val="313914798"/></p:ext></p:extLst></p:cSld><p:clrMapOvr><a:masterClrMapping/></p:clrMapOvr></p:sldLayout>
diff --git a/data/pptx/ppt/slideLayouts/slideLayout11.xml b/data/pptx/ppt/slideLayouts/slideLayout11.xml
--- a/data/pptx/ppt/slideLayouts/slideLayout11.xml
+++ b/data/pptx/ppt/slideLayouts/slideLayout11.xml
@@ -1,2 +1,2 @@
 <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
-<p:sldLayout xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main" type="vertTitleAndTx" preserve="1"><p:cSld name="Vertical Title and Text"><p:spTree><p:nvGrpSpPr><p:cNvPr id="1" name=""/><p:cNvGrpSpPr/><p:nvPr/></p:nvGrpSpPr><p:grpSpPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="0" cy="0"/><a:chOff x="0" y="0"/><a:chExt cx="0" cy="0"/></a:xfrm></p:grpSpPr><p:sp><p:nvSpPr><p:cNvPr id="2" name="Vertical Title 1"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="title" orient="vert"/></p:nvPr></p:nvSpPr><p:spPr><a:xfrm><a:off x="6629400" y="274638"/><a:ext cx="2057400" cy="5851525"/></a:xfrm></p:spPr><p:txBody><a:bodyPr vert="eaVert"/><a:lstStyle/><a:p><a:r><a:rPr lang="en-US" smtClean="0"/><a:t>Click to edit Master title style</a:t></a:r><a:endParaRPr lang="en-US"/></a:p></p:txBody></p:sp><p:sp><p:nvSpPr><p:cNvPr id="3" name="Vertical Text Placeholder 2"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="body" orient="vert" idx="1"/></p:nvPr></p:nvSpPr><p:spPr><a:xfrm><a:off x="457200" y="274638"/><a:ext cx="6019800" cy="5851525"/></a:xfrm></p:spPr><p:txBody><a:bodyPr vert="eaVert"/><a:lstStyle/><a:p><a:pPr lvl="0"/><a:r><a:rPr lang="en-US" smtClean="0"/><a:t>Click to edit Master text styles</a:t></a:r></a:p><a:p><a:pPr lvl="1"/><a:r><a:rPr lang="en-US" smtClean="0"/><a:t>Second level</a:t></a:r></a:p><a:p><a:pPr lvl="2"/><a:r><a:rPr lang="en-US" smtClean="0"/><a:t>Third level</a:t></a:r></a:p><a:p><a:pPr lvl="3"/><a:r><a:rPr lang="en-US" smtClean="0"/><a:t>Fourth level</a:t></a:r></a:p><a:p><a:pPr lvl="4"/><a:r><a:rPr lang="en-US" smtClean="0"/><a:t>Fifth level</a:t></a:r><a:endParaRPr lang="en-US"/></a:p></p:txBody></p:sp><p:sp><p:nvSpPr><p:cNvPr id="4" name="Date Placeholder 3"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="dt" sz="half" idx="10"/></p:nvPr></p:nvSpPr><p:spPr/><p:txBody><a:bodyPr/><a:lstStyle/><a:p><a:fld id="{241EB5C9-1307-BA42-ABA2-0BC069CD8E7F}" type="datetimeFigureOut"><a:rPr lang="en-US" smtClean="0"/><a:t>6/5/17</a:t></a:fld><a:endParaRPr lang="en-US"/></a:p></p:txBody></p:sp><p:sp><p:nvSpPr><p:cNvPr id="5" name="Footer Placeholder 4"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="ftr" sz="quarter" idx="11"/></p:nvPr></p:nvSpPr><p:spPr/><p:txBody><a:bodyPr/><a:lstStyle/><a:p><a:endParaRPr lang="en-US"/></a:p></p:txBody></p:sp><p:sp><p:nvSpPr><p:cNvPr id="6" name="Slide Number Placeholder 5"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="sldNum" sz="quarter" idx="12"/></p:nvPr></p:nvSpPr><p:spPr/><p:txBody><a:bodyPr/><a:lstStyle/><a:p><a:fld id="{C5EF2332-01BF-834F-8236-50238282D533}" type="slidenum"><a:rPr lang="en-US" smtClean="0"/><a:t>‹#›</a:t></a:fld><a:endParaRPr lang="en-US"/></a:p></p:txBody></p:sp></p:spTree><p:extLst><p:ext uri="{BB962C8B-B14F-4D97-AF65-F5344CB8AC3E}"><p14:creationId xmlns:p14="http://schemas.microsoft.com/office/powerpoint/2010/main" val="2581529045"/></p:ext></p:extLst></p:cSld><p:clrMapOvr><a:masterClrMapping/></p:clrMapOvr></p:sldLayout>
+<p:sldLayout xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main" type="vertTitleAndTx" preserve="1"><p:cSld name="Vertical Title and Text"><p:spTree><p:nvGrpSpPr><p:cNvPr id="1" name=""/><p:cNvGrpSpPr/><p:nvPr/></p:nvGrpSpPr><p:grpSpPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="0" cy="0"/><a:chOff x="0" y="0"/><a:chExt cx="0" cy="0"/></a:xfrm></p:grpSpPr><p:sp><p:nvSpPr><p:cNvPr id="2" name="Vertical Title 1"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="title" orient="vert"/></p:nvPr></p:nvSpPr><p:spPr><a:xfrm><a:off x="6629400" y="205979"/><a:ext cx="2057400" cy="4388644"/></a:xfrm></p:spPr><p:txBody><a:bodyPr vert="eaVert"/><a:lstStyle/><a:p><a:r><a:rPr lang="en-US"/><a:t>Click to edit Master title style</a:t></a:r></a:p></p:txBody></p:sp><p:sp><p:nvSpPr><p:cNvPr id="3" name="Vertical Text Placeholder 2"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="body" orient="vert" idx="1"/></p:nvPr></p:nvSpPr><p:spPr><a:xfrm><a:off x="457200" y="205979"/><a:ext cx="6019800" cy="4388644"/></a:xfrm></p:spPr><p:txBody><a:bodyPr vert="eaVert"/><a:lstStyle/><a:p><a:pPr lvl="0"/><a:r><a:rPr lang="en-US"/><a:t>Click to edit Master text styles</a:t></a:r></a:p><a:p><a:pPr lvl="1"/><a:r><a:rPr lang="en-US"/><a:t>Second level</a:t></a:r></a:p><a:p><a:pPr lvl="2"/><a:r><a:rPr lang="en-US"/><a:t>Third level</a:t></a:r></a:p><a:p><a:pPr lvl="3"/><a:r><a:rPr lang="en-US"/><a:t>Fourth level</a:t></a:r></a:p><a:p><a:pPr lvl="4"/><a:r><a:rPr lang="en-US"/><a:t>Fifth level</a:t></a:r></a:p></p:txBody></p:sp><p:sp><p:nvSpPr><p:cNvPr id="4" name="Date Placeholder 3"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="dt" sz="half" idx="10"/></p:nvPr></p:nvSpPr><p:spPr/><p:txBody><a:bodyPr/><a:lstStyle/><a:p><a:fld id="{241EB5C9-1307-BA42-ABA2-0BC069CD8E7F}" type="datetimeFigureOut"><a:rPr lang="en-US" smtClean="0"/><a:t>1/2/22</a:t></a:fld><a:endParaRPr lang="en-US"/></a:p></p:txBody></p:sp><p:sp><p:nvSpPr><p:cNvPr id="5" name="Footer Placeholder 4"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="ftr" sz="quarter" idx="11"/></p:nvPr></p:nvSpPr><p:spPr/><p:txBody><a:bodyPr/><a:lstStyle/><a:p><a:endParaRPr lang="en-US"/></a:p></p:txBody></p:sp><p:sp><p:nvSpPr><p:cNvPr id="6" name="Slide Number Placeholder 5"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="sldNum" sz="quarter" idx="12"/></p:nvPr></p:nvSpPr><p:spPr/><p:txBody><a:bodyPr/><a:lstStyle/><a:p><a:fld id="{C5EF2332-01BF-834F-8236-50238282D533}" type="slidenum"><a:rPr lang="en-US" smtClean="0"/><a:t>‹#›</a:t></a:fld><a:endParaRPr lang="en-US"/></a:p></p:txBody></p:sp></p:spTree><p:extLst><p:ext uri="{BB962C8B-B14F-4D97-AF65-F5344CB8AC3E}"><p14:creationId xmlns:p14="http://schemas.microsoft.com/office/powerpoint/2010/main" val="2581529045"/></p:ext></p:extLst></p:cSld><p:clrMapOvr><a:masterClrMapping/></p:clrMapOvr></p:sldLayout>
diff --git a/data/pptx/ppt/slideLayouts/slideLayout2.xml b/data/pptx/ppt/slideLayouts/slideLayout2.xml
--- a/data/pptx/ppt/slideLayouts/slideLayout2.xml
+++ b/data/pptx/ppt/slideLayouts/slideLayout2.xml
@@ -1,2 +1,2 @@
 <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
-<p:sldLayout xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main" type="obj" preserve="1"><p:cSld name="Title and Content"><p:spTree><p:nvGrpSpPr><p:cNvPr id="1" name=""/><p:cNvGrpSpPr/><p:nvPr/></p:nvGrpSpPr><p:grpSpPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="0" cy="0"/><a:chOff x="0" y="0"/><a:chExt cx="0" cy="0"/></a:xfrm></p:grpSpPr><p:sp><p:nvSpPr><p:cNvPr id="2" name="Title 1"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="title"/></p:nvPr></p:nvSpPr><p:spPr/><p:txBody><a:bodyPr/><a:lstStyle/><a:p><a:r><a:rPr lang="en-US" smtClean="0"/><a:t>Click to edit Master title style</a:t></a:r><a:endParaRPr lang="en-US"/></a:p></p:txBody></p:sp><p:sp><p:nvSpPr><p:cNvPr id="3" name="Content Placeholder 2"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph idx="1"/></p:nvPr></p:nvSpPr><p:spPr/><p:txBody><a:bodyPr/><a:lstStyle/><a:p><a:pPr lvl="0"/><a:r><a:rPr lang="en-US" smtClean="0"/><a:t>Click to edit Master text styles</a:t></a:r></a:p><a:p><a:pPr lvl="1"/><a:r><a:rPr lang="en-US" smtClean="0"/><a:t>Second level</a:t></a:r></a:p><a:p><a:pPr lvl="2"/><a:r><a:rPr lang="en-US" smtClean="0"/><a:t>Third level</a:t></a:r></a:p><a:p><a:pPr lvl="3"/><a:r><a:rPr lang="en-US" smtClean="0"/><a:t>Fourth level</a:t></a:r></a:p><a:p><a:pPr lvl="4"/><a:r><a:rPr lang="en-US" smtClean="0"/><a:t>Fifth level</a:t></a:r><a:endParaRPr lang="en-US"/></a:p></p:txBody></p:sp><p:sp><p:nvSpPr><p:cNvPr id="4" name="Date Placeholder 3"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="dt" sz="half" idx="10"/></p:nvPr></p:nvSpPr><p:spPr/><p:txBody><a:bodyPr/><a:lstStyle/><a:p><a:fld id="{241EB5C9-1307-BA42-ABA2-0BC069CD8E7F}" type="datetimeFigureOut"><a:rPr lang="en-US" smtClean="0"/><a:t>6/5/17</a:t></a:fld><a:endParaRPr lang="en-US"/></a:p></p:txBody></p:sp><p:sp><p:nvSpPr><p:cNvPr id="5" name="Footer Placeholder 4"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="ftr" sz="quarter" idx="11"/></p:nvPr></p:nvSpPr><p:spPr/><p:txBody><a:bodyPr/><a:lstStyle/><a:p><a:endParaRPr lang="en-US"/></a:p></p:txBody></p:sp><p:sp><p:nvSpPr><p:cNvPr id="6" name="Slide Number Placeholder 5"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="sldNum" sz="quarter" idx="12"/></p:nvPr></p:nvSpPr><p:spPr/><p:txBody><a:bodyPr/><a:lstStyle/><a:p><a:fld id="{C5EF2332-01BF-834F-8236-50238282D533}" type="slidenum"><a:rPr lang="en-US" smtClean="0"/><a:t>‹#›</a:t></a:fld><a:endParaRPr lang="en-US"/></a:p></p:txBody></p:sp></p:spTree><p:extLst><p:ext uri="{BB962C8B-B14F-4D97-AF65-F5344CB8AC3E}"><p14:creationId xmlns:p14="http://schemas.microsoft.com/office/powerpoint/2010/main" val="338346009"/></p:ext></p:extLst></p:cSld><p:clrMapOvr><a:masterClrMapping/></p:clrMapOvr></p:sldLayout>
+<p:sldLayout xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main" type="obj" preserve="1"><p:cSld name="Title and Content"><p:spTree><p:nvGrpSpPr><p:cNvPr id="1" name=""/><p:cNvGrpSpPr/><p:nvPr/></p:nvGrpSpPr><p:grpSpPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="0" cy="0"/><a:chOff x="0" y="0"/><a:chExt cx="0" cy="0"/></a:xfrm></p:grpSpPr><p:sp><p:nvSpPr><p:cNvPr id="2" name="Title 1"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="title"/></p:nvPr></p:nvSpPr><p:spPr/><p:txBody><a:bodyPr/><a:lstStyle/><a:p><a:r><a:rPr lang="en-US"/><a:t>Click to edit Master title style</a:t></a:r></a:p></p:txBody></p:sp><p:sp><p:nvSpPr><p:cNvPr id="3" name="Content Placeholder 2"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph idx="1"/></p:nvPr></p:nvSpPr><p:spPr/><p:txBody><a:bodyPr/><a:lstStyle/><a:p><a:pPr lvl="0"/><a:r><a:rPr lang="en-US"/><a:t>Click to edit Master text styles</a:t></a:r></a:p><a:p><a:pPr lvl="1"/><a:r><a:rPr lang="en-US"/><a:t>Second level</a:t></a:r></a:p><a:p><a:pPr lvl="2"/><a:r><a:rPr lang="en-US"/><a:t>Third level</a:t></a:r></a:p><a:p><a:pPr lvl="3"/><a:r><a:rPr lang="en-US"/><a:t>Fourth level</a:t></a:r></a:p><a:p><a:pPr lvl="4"/><a:r><a:rPr lang="en-US"/><a:t>Fifth level</a:t></a:r></a:p></p:txBody></p:sp><p:sp><p:nvSpPr><p:cNvPr id="4" name="Date Placeholder 3"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="dt" sz="half" idx="10"/></p:nvPr></p:nvSpPr><p:spPr/><p:txBody><a:bodyPr/><a:lstStyle/><a:p><a:fld id="{241EB5C9-1307-BA42-ABA2-0BC069CD8E7F}" type="datetimeFigureOut"><a:rPr lang="en-US" smtClean="0"/><a:t>1/2/22</a:t></a:fld><a:endParaRPr lang="en-US"/></a:p></p:txBody></p:sp><p:sp><p:nvSpPr><p:cNvPr id="5" name="Footer Placeholder 4"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="ftr" sz="quarter" idx="11"/></p:nvPr></p:nvSpPr><p:spPr/><p:txBody><a:bodyPr/><a:lstStyle/><a:p><a:endParaRPr lang="en-US"/></a:p></p:txBody></p:sp><p:sp><p:nvSpPr><p:cNvPr id="6" name="Slide Number Placeholder 5"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="sldNum" sz="quarter" idx="12"/></p:nvPr></p:nvSpPr><p:spPr/><p:txBody><a:bodyPr/><a:lstStyle/><a:p><a:fld id="{C5EF2332-01BF-834F-8236-50238282D533}" type="slidenum"><a:rPr lang="en-US" smtClean="0"/><a:t>‹#›</a:t></a:fld><a:endParaRPr lang="en-US"/></a:p></p:txBody></p:sp></p:spTree><p:extLst><p:ext uri="{BB962C8B-B14F-4D97-AF65-F5344CB8AC3E}"><p14:creationId xmlns:p14="http://schemas.microsoft.com/office/powerpoint/2010/main" val="338346009"/></p:ext></p:extLst></p:cSld><p:clrMapOvr><a:masterClrMapping/></p:clrMapOvr></p:sldLayout>
diff --git a/data/pptx/ppt/slideLayouts/slideLayout3.xml b/data/pptx/ppt/slideLayouts/slideLayout3.xml
--- a/data/pptx/ppt/slideLayouts/slideLayout3.xml
+++ b/data/pptx/ppt/slideLayouts/slideLayout3.xml
@@ -1,2 +1,2 @@
 <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
-<p:sldLayout xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main" type="secHead" preserve="1"><p:cSld name="Section Header"><p:spTree><p:nvGrpSpPr><p:cNvPr id="1" name=""/><p:cNvGrpSpPr/><p:nvPr/></p:nvGrpSpPr><p:grpSpPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="0" cy="0"/><a:chOff x="0" y="0"/><a:chExt cx="0" cy="0"/></a:xfrm></p:grpSpPr><p:sp><p:nvSpPr><p:cNvPr id="2" name="Title 1"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="title"/></p:nvPr></p:nvSpPr><p:spPr><a:xfrm><a:off x="722313" y="4406900"/><a:ext cx="7772400" cy="1362075"/></a:xfrm></p:spPr><p:txBody><a:bodyPr anchor="t"/><a:lstStyle><a:lvl1pPr algn="l"><a:defRPr sz="4000" b="1" cap="all"/></a:lvl1pPr></a:lstStyle><a:p><a:r><a:rPr lang="en-US" smtClean="0"/><a:t>Click to edit Master title style</a:t></a:r><a:endParaRPr lang="en-US"/></a:p></p:txBody></p:sp><p:sp><p:nvSpPr><p:cNvPr id="3" name="Text Placeholder 2"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="body" idx="1"/></p:nvPr></p:nvSpPr><p:spPr><a:xfrm><a:off x="722313" y="2906713"/><a:ext cx="7772400" cy="1500187"/></a:xfrm></p:spPr><p:txBody><a:bodyPr anchor="b"/><a:lstStyle><a:lvl1pPr marL="0" indent="0"><a:buNone/><a:defRPr sz="2000"><a:solidFill><a:schemeClr val="tx1"><a:tint val="75000"/></a:schemeClr></a:solidFill></a:defRPr></a:lvl1pPr><a:lvl2pPr marL="457200" indent="0"><a:buNone/><a:defRPr sz="1800"><a:solidFill><a:schemeClr val="tx1"><a:tint val="75000"/></a:schemeClr></a:solidFill></a:defRPr></a:lvl2pPr><a:lvl3pPr marL="914400" indent="0"><a:buNone/><a:defRPr sz="1600"><a:solidFill><a:schemeClr val="tx1"><a:tint val="75000"/></a:schemeClr></a:solidFill></a:defRPr></a:lvl3pPr><a:lvl4pPr marL="1371600" indent="0"><a:buNone/><a:defRPr sz="1400"><a:solidFill><a:schemeClr val="tx1"><a:tint val="75000"/></a:schemeClr></a:solidFill></a:defRPr></a:lvl4pPr><a:lvl5pPr marL="1828800" indent="0"><a:buNone/><a:defRPr sz="1400"><a:solidFill><a:schemeClr val="tx1"><a:tint val="75000"/></a:schemeClr></a:solidFill></a:defRPr></a:lvl5pPr><a:lvl6pPr marL="2286000" indent="0"><a:buNone/><a:defRPr sz="1400"><a:solidFill><a:schemeClr val="tx1"><a:tint val="75000"/></a:schemeClr></a:solidFill></a:defRPr></a:lvl6pPr><a:lvl7pPr marL="2743200" indent="0"><a:buNone/><a:defRPr sz="1400"><a:solidFill><a:schemeClr val="tx1"><a:tint val="75000"/></a:schemeClr></a:solidFill></a:defRPr></a:lvl7pPr><a:lvl8pPr marL="3200400" indent="0"><a:buNone/><a:defRPr sz="1400"><a:solidFill><a:schemeClr val="tx1"><a:tint val="75000"/></a:schemeClr></a:solidFill></a:defRPr></a:lvl8pPr><a:lvl9pPr marL="3657600" indent="0"><a:buNone/><a:defRPr sz="1400"><a:solidFill><a:schemeClr val="tx1"><a:tint val="75000"/></a:schemeClr></a:solidFill></a:defRPr></a:lvl9pPr></a:lstStyle><a:p><a:pPr lvl="0"/><a:r><a:rPr lang="en-US" smtClean="0"/><a:t>Click to edit Master text styles</a:t></a:r></a:p></p:txBody></p:sp><p:sp><p:nvSpPr><p:cNvPr id="4" name="Date Placeholder 3"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="dt" sz="half" idx="10"/></p:nvPr></p:nvSpPr><p:spPr/><p:txBody><a:bodyPr/><a:lstStyle/><a:p><a:fld id="{241EB5C9-1307-BA42-ABA2-0BC069CD8E7F}" type="datetimeFigureOut"><a:rPr lang="en-US" smtClean="0"/><a:t>6/5/17</a:t></a:fld><a:endParaRPr lang="en-US"/></a:p></p:txBody></p:sp><p:sp><p:nvSpPr><p:cNvPr id="5" name="Footer Placeholder 4"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="ftr" sz="quarter" idx="11"/></p:nvPr></p:nvSpPr><p:spPr/><p:txBody><a:bodyPr/><a:lstStyle/><a:p><a:endParaRPr lang="en-US"/></a:p></p:txBody></p:sp><p:sp><p:nvSpPr><p:cNvPr id="6" name="Slide Number Placeholder 5"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="sldNum" sz="quarter" idx="12"/></p:nvPr></p:nvSpPr><p:spPr/><p:txBody><a:bodyPr/><a:lstStyle/><a:p><a:fld id="{C5EF2332-01BF-834F-8236-50238282D533}" type="slidenum"><a:rPr lang="en-US" smtClean="0"/><a:t>‹#›</a:t></a:fld><a:endParaRPr lang="en-US"/></a:p></p:txBody></p:sp></p:spTree><p:extLst><p:ext uri="{BB962C8B-B14F-4D97-AF65-F5344CB8AC3E}"><p14:creationId xmlns:p14="http://schemas.microsoft.com/office/powerpoint/2010/main" val="1073069076"/></p:ext></p:extLst></p:cSld><p:clrMapOvr><a:masterClrMapping/></p:clrMapOvr></p:sldLayout>
+<p:sldLayout xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main" type="secHead" preserve="1"><p:cSld name="Section Header"><p:spTree><p:nvGrpSpPr><p:cNvPr id="1" name=""/><p:cNvGrpSpPr/><p:nvPr/></p:nvGrpSpPr><p:grpSpPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="0" cy="0"/><a:chOff x="0" y="0"/><a:chExt cx="0" cy="0"/></a:xfrm></p:grpSpPr><p:sp><p:nvSpPr><p:cNvPr id="2" name="Title 1"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="title"/></p:nvPr></p:nvSpPr><p:spPr><a:xfrm><a:off x="722313" y="3305176"/><a:ext cx="7772400" cy="1021556"/></a:xfrm></p:spPr><p:txBody><a:bodyPr anchor="t"/><a:lstStyle><a:lvl1pPr algn="l"><a:defRPr sz="3000" b="1" cap="all"/></a:lvl1pPr></a:lstStyle><a:p><a:r><a:rPr lang="en-US"/><a:t>Click to edit Master title style</a:t></a:r></a:p></p:txBody></p:sp><p:sp><p:nvSpPr><p:cNvPr id="3" name="Text Placeholder 2"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="body" idx="1"/></p:nvPr></p:nvSpPr><p:spPr><a:xfrm><a:off x="722313" y="2180035"/><a:ext cx="7772400" cy="1125140"/></a:xfrm></p:spPr><p:txBody><a:bodyPr anchor="b"/><a:lstStyle><a:lvl1pPr marL="0" indent="0"><a:buNone/><a:defRPr sz="1500"><a:solidFill><a:schemeClr val="tx1"><a:tint val="75000"/></a:schemeClr></a:solidFill></a:defRPr></a:lvl1pPr><a:lvl2pPr marL="342900" indent="0"><a:buNone/><a:defRPr sz="1350"><a:solidFill><a:schemeClr val="tx1"><a:tint val="75000"/></a:schemeClr></a:solidFill></a:defRPr></a:lvl2pPr><a:lvl3pPr marL="685800" indent="0"><a:buNone/><a:defRPr sz="1200"><a:solidFill><a:schemeClr val="tx1"><a:tint val="75000"/></a:schemeClr></a:solidFill></a:defRPr></a:lvl3pPr><a:lvl4pPr marL="1028700" indent="0"><a:buNone/><a:defRPr sz="1050"><a:solidFill><a:schemeClr val="tx1"><a:tint val="75000"/></a:schemeClr></a:solidFill></a:defRPr></a:lvl4pPr><a:lvl5pPr marL="1371600" indent="0"><a:buNone/><a:defRPr sz="1050"><a:solidFill><a:schemeClr val="tx1"><a:tint val="75000"/></a:schemeClr></a:solidFill></a:defRPr></a:lvl5pPr><a:lvl6pPr marL="1714500" indent="0"><a:buNone/><a:defRPr sz="1050"><a:solidFill><a:schemeClr val="tx1"><a:tint val="75000"/></a:schemeClr></a:solidFill></a:defRPr></a:lvl6pPr><a:lvl7pPr marL="2057400" indent="0"><a:buNone/><a:defRPr sz="1050"><a:solidFill><a:schemeClr val="tx1"><a:tint val="75000"/></a:schemeClr></a:solidFill></a:defRPr></a:lvl7pPr><a:lvl8pPr marL="2400300" indent="0"><a:buNone/><a:defRPr sz="1050"><a:solidFill><a:schemeClr val="tx1"><a:tint val="75000"/></a:schemeClr></a:solidFill></a:defRPr></a:lvl8pPr><a:lvl9pPr marL="2743200" indent="0"><a:buNone/><a:defRPr sz="1050"><a:solidFill><a:schemeClr val="tx1"><a:tint val="75000"/></a:schemeClr></a:solidFill></a:defRPr></a:lvl9pPr></a:lstStyle><a:p><a:pPr lvl="0"/><a:r><a:rPr lang="en-US"/><a:t>Click to edit Master text styles</a:t></a:r></a:p></p:txBody></p:sp><p:sp><p:nvSpPr><p:cNvPr id="4" name="Date Placeholder 3"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="dt" sz="half" idx="10"/></p:nvPr></p:nvSpPr><p:spPr/><p:txBody><a:bodyPr/><a:lstStyle/><a:p><a:fld id="{241EB5C9-1307-BA42-ABA2-0BC069CD8E7F}" type="datetimeFigureOut"><a:rPr lang="en-US" smtClean="0"/><a:t>1/2/22</a:t></a:fld><a:endParaRPr lang="en-US"/></a:p></p:txBody></p:sp><p:sp><p:nvSpPr><p:cNvPr id="5" name="Footer Placeholder 4"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="ftr" sz="quarter" idx="11"/></p:nvPr></p:nvSpPr><p:spPr/><p:txBody><a:bodyPr/><a:lstStyle/><a:p><a:endParaRPr lang="en-US"/></a:p></p:txBody></p:sp><p:sp><p:nvSpPr><p:cNvPr id="6" name="Slide Number Placeholder 5"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="sldNum" sz="quarter" idx="12"/></p:nvPr></p:nvSpPr><p:spPr/><p:txBody><a:bodyPr/><a:lstStyle/><a:p><a:fld id="{C5EF2332-01BF-834F-8236-50238282D533}" type="slidenum"><a:rPr lang="en-US" smtClean="0"/><a:t>‹#›</a:t></a:fld><a:endParaRPr lang="en-US"/></a:p></p:txBody></p:sp></p:spTree><p:extLst><p:ext uri="{BB962C8B-B14F-4D97-AF65-F5344CB8AC3E}"><p14:creationId xmlns:p14="http://schemas.microsoft.com/office/powerpoint/2010/main" val="1073069076"/></p:ext></p:extLst></p:cSld><p:clrMapOvr><a:masterClrMapping/></p:clrMapOvr></p:sldLayout>
diff --git a/data/pptx/ppt/slideLayouts/slideLayout4.xml b/data/pptx/ppt/slideLayouts/slideLayout4.xml
--- a/data/pptx/ppt/slideLayouts/slideLayout4.xml
+++ b/data/pptx/ppt/slideLayouts/slideLayout4.xml
@@ -1,2 +1,2 @@
 <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
-<p:sldLayout xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main" type="twoObj" preserve="1"><p:cSld name="Two Content"><p:spTree><p:nvGrpSpPr><p:cNvPr id="1" name=""/><p:cNvGrpSpPr/><p:nvPr/></p:nvGrpSpPr><p:grpSpPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="0" cy="0"/><a:chOff x="0" y="0"/><a:chExt cx="0" cy="0"/></a:xfrm></p:grpSpPr><p:sp><p:nvSpPr><p:cNvPr id="2" name="Title 1"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="title"/></p:nvPr></p:nvSpPr><p:spPr/><p:txBody><a:bodyPr/><a:lstStyle/><a:p><a:r><a:rPr lang="en-US" smtClean="0"/><a:t>Click to edit Master title style</a:t></a:r><a:endParaRPr lang="en-US"/></a:p></p:txBody></p:sp><p:sp><p:nvSpPr><p:cNvPr id="3" name="Content Placeholder 2"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph sz="half" idx="1"/></p:nvPr></p:nvSpPr><p:spPr><a:xfrm><a:off x="457200" y="1600200"/><a:ext cx="4038600" cy="4525963"/></a:xfrm></p:spPr><p:txBody><a:bodyPr/><a:lstStyle><a:lvl1pPr><a:defRPr sz="2800"/></a:lvl1pPr><a:lvl2pPr><a:defRPr sz="2400"/></a:lvl2pPr><a:lvl3pPr><a:defRPr sz="2000"/></a:lvl3pPr><a:lvl4pPr><a:defRPr sz="1800"/></a:lvl4pPr><a:lvl5pPr><a:defRPr sz="1800"/></a:lvl5pPr><a:lvl6pPr><a:defRPr sz="1800"/></a:lvl6pPr><a:lvl7pPr><a:defRPr sz="1800"/></a:lvl7pPr><a:lvl8pPr><a:defRPr sz="1800"/></a:lvl8pPr><a:lvl9pPr><a:defRPr sz="1800"/></a:lvl9pPr></a:lstStyle><a:p><a:pPr lvl="0"/><a:r><a:rPr lang="en-US" smtClean="0"/><a:t>Click to edit Master text styles</a:t></a:r></a:p><a:p><a:pPr lvl="1"/><a:r><a:rPr lang="en-US" smtClean="0"/><a:t>Second level</a:t></a:r></a:p><a:p><a:pPr lvl="2"/><a:r><a:rPr lang="en-US" smtClean="0"/><a:t>Third level</a:t></a:r></a:p><a:p><a:pPr lvl="3"/><a:r><a:rPr lang="en-US" smtClean="0"/><a:t>Fourth level</a:t></a:r></a:p><a:p><a:pPr lvl="4"/><a:r><a:rPr lang="en-US" smtClean="0"/><a:t>Fifth level</a:t></a:r><a:endParaRPr lang="en-US"/></a:p></p:txBody></p:sp><p:sp><p:nvSpPr><p:cNvPr id="4" name="Content Placeholder 3"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph sz="half" idx="2"/></p:nvPr></p:nvSpPr><p:spPr><a:xfrm><a:off x="4648200" y="1600200"/><a:ext cx="4038600" cy="4525963"/></a:xfrm></p:spPr><p:txBody><a:bodyPr/><a:lstStyle><a:lvl1pPr><a:defRPr sz="2800"/></a:lvl1pPr><a:lvl2pPr><a:defRPr sz="2400"/></a:lvl2pPr><a:lvl3pPr><a:defRPr sz="2000"/></a:lvl3pPr><a:lvl4pPr><a:defRPr sz="1800"/></a:lvl4pPr><a:lvl5pPr><a:defRPr sz="1800"/></a:lvl5pPr><a:lvl6pPr><a:defRPr sz="1800"/></a:lvl6pPr><a:lvl7pPr><a:defRPr sz="1800"/></a:lvl7pPr><a:lvl8pPr><a:defRPr sz="1800"/></a:lvl8pPr><a:lvl9pPr><a:defRPr sz="1800"/></a:lvl9pPr></a:lstStyle><a:p><a:pPr lvl="0"/><a:r><a:rPr lang="en-US" smtClean="0"/><a:t>Click to edit Master text styles</a:t></a:r></a:p><a:p><a:pPr lvl="1"/><a:r><a:rPr lang="en-US" smtClean="0"/><a:t>Second level</a:t></a:r></a:p><a:p><a:pPr lvl="2"/><a:r><a:rPr lang="en-US" smtClean="0"/><a:t>Third level</a:t></a:r></a:p><a:p><a:pPr lvl="3"/><a:r><a:rPr lang="en-US" smtClean="0"/><a:t>Fourth level</a:t></a:r></a:p><a:p><a:pPr lvl="4"/><a:r><a:rPr lang="en-US" smtClean="0"/><a:t>Fifth level</a:t></a:r><a:endParaRPr lang="en-US"/></a:p></p:txBody></p:sp><p:sp><p:nvSpPr><p:cNvPr id="5" name="Date Placeholder 4"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="dt" sz="half" idx="10"/></p:nvPr></p:nvSpPr><p:spPr/><p:txBody><a:bodyPr/><a:lstStyle/><a:p><a:fld id="{241EB5C9-1307-BA42-ABA2-0BC069CD8E7F}" type="datetimeFigureOut"><a:rPr lang="en-US" smtClean="0"/><a:t>6/5/17</a:t></a:fld><a:endParaRPr lang="en-US"/></a:p></p:txBody></p:sp><p:sp><p:nvSpPr><p:cNvPr id="6" name="Footer Placeholder 5"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="ftr" sz="quarter" idx="11"/></p:nvPr></p:nvSpPr><p:spPr/><p:txBody><a:bodyPr/><a:lstStyle/><a:p><a:endParaRPr lang="en-US"/></a:p></p:txBody></p:sp><p:sp><p:nvSpPr><p:cNvPr id="7" name="Slide Number Placeholder 6"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="sldNum" sz="quarter" idx="12"/></p:nvPr></p:nvSpPr><p:spPr/><p:txBody><a:bodyPr/><a:lstStyle/><a:p><a:fld id="{C5EF2332-01BF-834F-8236-50238282D533}" type="slidenum"><a:rPr lang="en-US" smtClean="0"/><a:t>‹#›</a:t></a:fld><a:endParaRPr lang="en-US"/></a:p></p:txBody></p:sp></p:spTree><p:extLst><p:ext uri="{BB962C8B-B14F-4D97-AF65-F5344CB8AC3E}"><p14:creationId xmlns:p14="http://schemas.microsoft.com/office/powerpoint/2010/main" val="2619886245"/></p:ext></p:extLst></p:cSld><p:clrMapOvr><a:masterClrMapping/></p:clrMapOvr></p:sldLayout>
+<p:sldLayout xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main" type="twoObj" preserve="1"><p:cSld name="Two Content"><p:spTree><p:nvGrpSpPr><p:cNvPr id="1" name=""/><p:cNvGrpSpPr/><p:nvPr/></p:nvGrpSpPr><p:grpSpPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="0" cy="0"/><a:chOff x="0" y="0"/><a:chExt cx="0" cy="0"/></a:xfrm></p:grpSpPr><p:sp><p:nvSpPr><p:cNvPr id="2" name="Title 1"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="title"/></p:nvPr></p:nvSpPr><p:spPr/><p:txBody><a:bodyPr/><a:lstStyle/><a:p><a:r><a:rPr lang="en-US"/><a:t>Click to edit Master title style</a:t></a:r></a:p></p:txBody></p:sp><p:sp><p:nvSpPr><p:cNvPr id="3" name="Content Placeholder 2"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph sz="half" idx="1"/></p:nvPr></p:nvSpPr><p:spPr><a:xfrm><a:off x="457200" y="1200151"/><a:ext cx="4038600" cy="3394472"/></a:xfrm></p:spPr><p:txBody><a:bodyPr/><a:lstStyle><a:lvl1pPr><a:defRPr sz="2100"/></a:lvl1pPr><a:lvl2pPr><a:defRPr sz="1800"/></a:lvl2pPr><a:lvl3pPr><a:defRPr sz="1500"/></a:lvl3pPr><a:lvl4pPr><a:defRPr sz="1350"/></a:lvl4pPr><a:lvl5pPr><a:defRPr sz="1350"/></a:lvl5pPr><a:lvl6pPr><a:defRPr sz="1350"/></a:lvl6pPr><a:lvl7pPr><a:defRPr sz="1350"/></a:lvl7pPr><a:lvl8pPr><a:defRPr sz="1350"/></a:lvl8pPr><a:lvl9pPr><a:defRPr sz="1350"/></a:lvl9pPr></a:lstStyle><a:p><a:pPr lvl="0"/><a:r><a:rPr lang="en-US"/><a:t>Click to edit Master text styles</a:t></a:r></a:p><a:p><a:pPr lvl="1"/><a:r><a:rPr lang="en-US"/><a:t>Second level</a:t></a:r></a:p><a:p><a:pPr lvl="2"/><a:r><a:rPr lang="en-US"/><a:t>Third level</a:t></a:r></a:p><a:p><a:pPr lvl="3"/><a:r><a:rPr lang="en-US"/><a:t>Fourth level</a:t></a:r></a:p><a:p><a:pPr lvl="4"/><a:r><a:rPr lang="en-US"/><a:t>Fifth level</a:t></a:r></a:p></p:txBody></p:sp><p:sp><p:nvSpPr><p:cNvPr id="4" name="Content Placeholder 3"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph sz="half" idx="2"/></p:nvPr></p:nvSpPr><p:spPr><a:xfrm><a:off x="4648200" y="1200151"/><a:ext cx="4038600" cy="3394472"/></a:xfrm></p:spPr><p:txBody><a:bodyPr/><a:lstStyle><a:lvl1pPr><a:defRPr sz="2100"/></a:lvl1pPr><a:lvl2pPr><a:defRPr sz="1800"/></a:lvl2pPr><a:lvl3pPr><a:defRPr sz="1500"/></a:lvl3pPr><a:lvl4pPr><a:defRPr sz="1350"/></a:lvl4pPr><a:lvl5pPr><a:defRPr sz="1350"/></a:lvl5pPr><a:lvl6pPr><a:defRPr sz="1350"/></a:lvl6pPr><a:lvl7pPr><a:defRPr sz="1350"/></a:lvl7pPr><a:lvl8pPr><a:defRPr sz="1350"/></a:lvl8pPr><a:lvl9pPr><a:defRPr sz="1350"/></a:lvl9pPr></a:lstStyle><a:p><a:pPr lvl="0"/><a:r><a:rPr lang="en-US"/><a:t>Click to edit Master text styles</a:t></a:r></a:p><a:p><a:pPr lvl="1"/><a:r><a:rPr lang="en-US"/><a:t>Second level</a:t></a:r></a:p><a:p><a:pPr lvl="2"/><a:r><a:rPr lang="en-US"/><a:t>Third level</a:t></a:r></a:p><a:p><a:pPr lvl="3"/><a:r><a:rPr lang="en-US"/><a:t>Fourth level</a:t></a:r></a:p><a:p><a:pPr lvl="4"/><a:r><a:rPr lang="en-US"/><a:t>Fifth level</a:t></a:r></a:p></p:txBody></p:sp><p:sp><p:nvSpPr><p:cNvPr id="5" name="Date Placeholder 4"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="dt" sz="half" idx="10"/></p:nvPr></p:nvSpPr><p:spPr/><p:txBody><a:bodyPr/><a:lstStyle/><a:p><a:fld id="{241EB5C9-1307-BA42-ABA2-0BC069CD8E7F}" type="datetimeFigureOut"><a:rPr lang="en-US" smtClean="0"/><a:t>1/2/22</a:t></a:fld><a:endParaRPr lang="en-US"/></a:p></p:txBody></p:sp><p:sp><p:nvSpPr><p:cNvPr id="6" name="Footer Placeholder 5"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="ftr" sz="quarter" idx="11"/></p:nvPr></p:nvSpPr><p:spPr/><p:txBody><a:bodyPr/><a:lstStyle/><a:p><a:endParaRPr lang="en-US"/></a:p></p:txBody></p:sp><p:sp><p:nvSpPr><p:cNvPr id="7" name="Slide Number Placeholder 6"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="sldNum" sz="quarter" idx="12"/></p:nvPr></p:nvSpPr><p:spPr/><p:txBody><a:bodyPr/><a:lstStyle/><a:p><a:fld id="{C5EF2332-01BF-834F-8236-50238282D533}" type="slidenum"><a:rPr lang="en-US" smtClean="0"/><a:t>‹#›</a:t></a:fld><a:endParaRPr lang="en-US"/></a:p></p:txBody></p:sp></p:spTree><p:extLst><p:ext uri="{BB962C8B-B14F-4D97-AF65-F5344CB8AC3E}"><p14:creationId xmlns:p14="http://schemas.microsoft.com/office/powerpoint/2010/main" val="2619886245"/></p:ext></p:extLst></p:cSld><p:clrMapOvr><a:masterClrMapping/></p:clrMapOvr></p:sldLayout>
diff --git a/data/pptx/ppt/slideLayouts/slideLayout5.xml b/data/pptx/ppt/slideLayouts/slideLayout5.xml
--- a/data/pptx/ppt/slideLayouts/slideLayout5.xml
+++ b/data/pptx/ppt/slideLayouts/slideLayout5.xml
@@ -1,2 +1,2 @@
 <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
-<p:sldLayout xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main" type="twoTxTwoObj" preserve="1"><p:cSld name="Comparison"><p:spTree><p:nvGrpSpPr><p:cNvPr id="1" name=""/><p:cNvGrpSpPr/><p:nvPr/></p:nvGrpSpPr><p:grpSpPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="0" cy="0"/><a:chOff x="0" y="0"/><a:chExt cx="0" cy="0"/></a:xfrm></p:grpSpPr><p:sp><p:nvSpPr><p:cNvPr id="2" name="Title 1"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="title"/></p:nvPr></p:nvSpPr><p:spPr/><p:txBody><a:bodyPr/><a:lstStyle><a:lvl1pPr><a:defRPr/></a:lvl1pPr></a:lstStyle><a:p><a:r><a:rPr lang="en-US" smtClean="0"/><a:t>Click to edit Master title style</a:t></a:r><a:endParaRPr lang="en-US"/></a:p></p:txBody></p:sp><p:sp><p:nvSpPr><p:cNvPr id="3" name="Text Placeholder 2"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="body" idx="1"/></p:nvPr></p:nvSpPr><p:spPr><a:xfrm><a:off x="457200" y="1535113"/><a:ext cx="4040188" cy="639762"/></a:xfrm></p:spPr><p:txBody><a:bodyPr anchor="b"/><a:lstStyle><a:lvl1pPr marL="0" indent="0"><a:buNone/><a:defRPr sz="2400" b="1"/></a:lvl1pPr><a:lvl2pPr marL="457200" indent="0"><a:buNone/><a:defRPr sz="2000" b="1"/></a:lvl2pPr><a:lvl3pPr marL="914400" indent="0"><a:buNone/><a:defRPr sz="1800" b="1"/></a:lvl3pPr><a:lvl4pPr marL="1371600" indent="0"><a:buNone/><a:defRPr sz="1600" b="1"/></a:lvl4pPr><a:lvl5pPr marL="1828800" indent="0"><a:buNone/><a:defRPr sz="1600" b="1"/></a:lvl5pPr><a:lvl6pPr marL="2286000" indent="0"><a:buNone/><a:defRPr sz="1600" b="1"/></a:lvl6pPr><a:lvl7pPr marL="2743200" indent="0"><a:buNone/><a:defRPr sz="1600" b="1"/></a:lvl7pPr><a:lvl8pPr marL="3200400" indent="0"><a:buNone/><a:defRPr sz="1600" b="1"/></a:lvl8pPr><a:lvl9pPr marL="3657600" indent="0"><a:buNone/><a:defRPr sz="1600" b="1"/></a:lvl9pPr></a:lstStyle><a:p><a:pPr lvl="0"/><a:r><a:rPr lang="en-US" smtClean="0"/><a:t>Click to edit Master text styles</a:t></a:r></a:p></p:txBody></p:sp><p:sp><p:nvSpPr><p:cNvPr id="4" name="Content Placeholder 3"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph sz="half" idx="2"/></p:nvPr></p:nvSpPr><p:spPr><a:xfrm><a:off x="457200" y="2174875"/><a:ext cx="4040188" cy="3951288"/></a:xfrm></p:spPr><p:txBody><a:bodyPr/><a:lstStyle><a:lvl1pPr><a:defRPr sz="2400"/></a:lvl1pPr><a:lvl2pPr><a:defRPr sz="2000"/></a:lvl2pPr><a:lvl3pPr><a:defRPr sz="1800"/></a:lvl3pPr><a:lvl4pPr><a:defRPr sz="1600"/></a:lvl4pPr><a:lvl5pPr><a:defRPr sz="1600"/></a:lvl5pPr><a:lvl6pPr><a:defRPr sz="1600"/></a:lvl6pPr><a:lvl7pPr><a:defRPr sz="1600"/></a:lvl7pPr><a:lvl8pPr><a:defRPr sz="1600"/></a:lvl8pPr><a:lvl9pPr><a:defRPr sz="1600"/></a:lvl9pPr></a:lstStyle><a:p><a:pPr lvl="0"/><a:r><a:rPr lang="en-US" smtClean="0"/><a:t>Click to edit Master text styles</a:t></a:r></a:p><a:p><a:pPr lvl="1"/><a:r><a:rPr lang="en-US" smtClean="0"/><a:t>Second level</a:t></a:r></a:p><a:p><a:pPr lvl="2"/><a:r><a:rPr lang="en-US" smtClean="0"/><a:t>Third level</a:t></a:r></a:p><a:p><a:pPr lvl="3"/><a:r><a:rPr lang="en-US" smtClean="0"/><a:t>Fourth level</a:t></a:r></a:p><a:p><a:pPr lvl="4"/><a:r><a:rPr lang="en-US" smtClean="0"/><a:t>Fifth level</a:t></a:r><a:endParaRPr lang="en-US"/></a:p></p:txBody></p:sp><p:sp><p:nvSpPr><p:cNvPr id="5" name="Text Placeholder 4"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="body" sz="quarter" idx="3"/></p:nvPr></p:nvSpPr><p:spPr><a:xfrm><a:off x="4645025" y="1535113"/><a:ext cx="4041775" cy="639762"/></a:xfrm></p:spPr><p:txBody><a:bodyPr anchor="b"/><a:lstStyle><a:lvl1pPr marL="0" indent="0"><a:buNone/><a:defRPr sz="2400" b="1"/></a:lvl1pPr><a:lvl2pPr marL="457200" indent="0"><a:buNone/><a:defRPr sz="2000" b="1"/></a:lvl2pPr><a:lvl3pPr marL="914400" indent="0"><a:buNone/><a:defRPr sz="1800" b="1"/></a:lvl3pPr><a:lvl4pPr marL="1371600" indent="0"><a:buNone/><a:defRPr sz="1600" b="1"/></a:lvl4pPr><a:lvl5pPr marL="1828800" indent="0"><a:buNone/><a:defRPr sz="1600" b="1"/></a:lvl5pPr><a:lvl6pPr marL="2286000" indent="0"><a:buNone/><a:defRPr sz="1600" b="1"/></a:lvl6pPr><a:lvl7pPr marL="2743200" indent="0"><a:buNone/><a:defRPr sz="1600" b="1"/></a:lvl7pPr><a:lvl8pPr marL="3200400" indent="0"><a:buNone/><a:defRPr sz="1600" b="1"/></a:lvl8pPr><a:lvl9pPr marL="3657600" indent="0"><a:buNone/><a:defRPr sz="1600" b="1"/></a:lvl9pPr></a:lstStyle><a:p><a:pPr lvl="0"/><a:r><a:rPr lang="en-US" smtClean="0"/><a:t>Click to edit Master text styles</a:t></a:r></a:p></p:txBody></p:sp><p:sp><p:nvSpPr><p:cNvPr id="6" name="Content Placeholder 5"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph sz="quarter" idx="4"/></p:nvPr></p:nvSpPr><p:spPr><a:xfrm><a:off x="4645025" y="2174875"/><a:ext cx="4041775" cy="3951288"/></a:xfrm></p:spPr><p:txBody><a:bodyPr/><a:lstStyle><a:lvl1pPr><a:defRPr sz="2400"/></a:lvl1pPr><a:lvl2pPr><a:defRPr sz="2000"/></a:lvl2pPr><a:lvl3pPr><a:defRPr sz="1800"/></a:lvl3pPr><a:lvl4pPr><a:defRPr sz="1600"/></a:lvl4pPr><a:lvl5pPr><a:defRPr sz="1600"/></a:lvl5pPr><a:lvl6pPr><a:defRPr sz="1600"/></a:lvl6pPr><a:lvl7pPr><a:defRPr sz="1600"/></a:lvl7pPr><a:lvl8pPr><a:defRPr sz="1600"/></a:lvl8pPr><a:lvl9pPr><a:defRPr sz="1600"/></a:lvl9pPr></a:lstStyle><a:p><a:pPr lvl="0"/><a:r><a:rPr lang="en-US" smtClean="0"/><a:t>Click to edit Master text styles</a:t></a:r></a:p><a:p><a:pPr lvl="1"/><a:r><a:rPr lang="en-US" smtClean="0"/><a:t>Second level</a:t></a:r></a:p><a:p><a:pPr lvl="2"/><a:r><a:rPr lang="en-US" smtClean="0"/><a:t>Third level</a:t></a:r></a:p><a:p><a:pPr lvl="3"/><a:r><a:rPr lang="en-US" smtClean="0"/><a:t>Fourth level</a:t></a:r></a:p><a:p><a:pPr lvl="4"/><a:r><a:rPr lang="en-US" smtClean="0"/><a:t>Fifth level</a:t></a:r><a:endParaRPr lang="en-US"/></a:p></p:txBody></p:sp><p:sp><p:nvSpPr><p:cNvPr id="7" name="Date Placeholder 6"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="dt" sz="half" idx="10"/></p:nvPr></p:nvSpPr><p:spPr/><p:txBody><a:bodyPr/><a:lstStyle/><a:p><a:fld id="{241EB5C9-1307-BA42-ABA2-0BC069CD8E7F}" type="datetimeFigureOut"><a:rPr lang="en-US" smtClean="0"/><a:t>6/5/17</a:t></a:fld><a:endParaRPr lang="en-US"/></a:p></p:txBody></p:sp><p:sp><p:nvSpPr><p:cNvPr id="8" name="Footer Placeholder 7"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="ftr" sz="quarter" idx="11"/></p:nvPr></p:nvSpPr><p:spPr/><p:txBody><a:bodyPr/><a:lstStyle/><a:p><a:endParaRPr lang="en-US"/></a:p></p:txBody></p:sp><p:sp><p:nvSpPr><p:cNvPr id="9" name="Slide Number Placeholder 8"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="sldNum" sz="quarter" idx="12"/></p:nvPr></p:nvSpPr><p:spPr/><p:txBody><a:bodyPr/><a:lstStyle/><a:p><a:fld id="{C5EF2332-01BF-834F-8236-50238282D533}" type="slidenum"><a:rPr lang="en-US" smtClean="0"/><a:t>‹#›</a:t></a:fld><a:endParaRPr lang="en-US"/></a:p></p:txBody></p:sp></p:spTree><p:extLst><p:ext uri="{BB962C8B-B14F-4D97-AF65-F5344CB8AC3E}"><p14:creationId xmlns:p14="http://schemas.microsoft.com/office/powerpoint/2010/main" val="2535793967"/></p:ext></p:extLst></p:cSld><p:clrMapOvr><a:masterClrMapping/></p:clrMapOvr></p:sldLayout>
+<p:sldLayout xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main" type="twoTxTwoObj" preserve="1"><p:cSld name="Comparison"><p:spTree><p:nvGrpSpPr><p:cNvPr id="1" name=""/><p:cNvGrpSpPr/><p:nvPr/></p:nvGrpSpPr><p:grpSpPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="0" cy="0"/><a:chOff x="0" y="0"/><a:chExt cx="0" cy="0"/></a:xfrm></p:grpSpPr><p:sp><p:nvSpPr><p:cNvPr id="2" name="Title 1"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="title"/></p:nvPr></p:nvSpPr><p:spPr/><p:txBody><a:bodyPr/><a:lstStyle><a:lvl1pPr><a:defRPr/></a:lvl1pPr></a:lstStyle><a:p><a:r><a:rPr lang="en-US"/><a:t>Click to edit Master title style</a:t></a:r></a:p></p:txBody></p:sp><p:sp><p:nvSpPr><p:cNvPr id="3" name="Text Placeholder 2"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="body" idx="1"/></p:nvPr></p:nvSpPr><p:spPr><a:xfrm><a:off x="457200" y="1151335"/><a:ext cx="4040188" cy="479822"/></a:xfrm></p:spPr><p:txBody><a:bodyPr anchor="b"/><a:lstStyle><a:lvl1pPr marL="0" indent="0"><a:buNone/><a:defRPr sz="1800" b="1"/></a:lvl1pPr><a:lvl2pPr marL="342900" indent="0"><a:buNone/><a:defRPr sz="1500" b="1"/></a:lvl2pPr><a:lvl3pPr marL="685800" indent="0"><a:buNone/><a:defRPr sz="1350" b="1"/></a:lvl3pPr><a:lvl4pPr marL="1028700" indent="0"><a:buNone/><a:defRPr sz="1200" b="1"/></a:lvl4pPr><a:lvl5pPr marL="1371600" indent="0"><a:buNone/><a:defRPr sz="1200" b="1"/></a:lvl5pPr><a:lvl6pPr marL="1714500" indent="0"><a:buNone/><a:defRPr sz="1200" b="1"/></a:lvl6pPr><a:lvl7pPr marL="2057400" indent="0"><a:buNone/><a:defRPr sz="1200" b="1"/></a:lvl7pPr><a:lvl8pPr marL="2400300" indent="0"><a:buNone/><a:defRPr sz="1200" b="1"/></a:lvl8pPr><a:lvl9pPr marL="2743200" indent="0"><a:buNone/><a:defRPr sz="1200" b="1"/></a:lvl9pPr></a:lstStyle><a:p><a:pPr lvl="0"/><a:r><a:rPr lang="en-US"/><a:t>Click to edit Master text styles</a:t></a:r></a:p></p:txBody></p:sp><p:sp><p:nvSpPr><p:cNvPr id="4" name="Content Placeholder 3"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph sz="half" idx="2"/></p:nvPr></p:nvSpPr><p:spPr><a:xfrm><a:off x="457200" y="1631156"/><a:ext cx="4040188" cy="2963466"/></a:xfrm></p:spPr><p:txBody><a:bodyPr/><a:lstStyle><a:lvl1pPr><a:defRPr sz="1800"/></a:lvl1pPr><a:lvl2pPr><a:defRPr sz="1500"/></a:lvl2pPr><a:lvl3pPr><a:defRPr sz="1350"/></a:lvl3pPr><a:lvl4pPr><a:defRPr sz="1200"/></a:lvl4pPr><a:lvl5pPr><a:defRPr sz="1200"/></a:lvl5pPr><a:lvl6pPr><a:defRPr sz="1200"/></a:lvl6pPr><a:lvl7pPr><a:defRPr sz="1200"/></a:lvl7pPr><a:lvl8pPr><a:defRPr sz="1200"/></a:lvl8pPr><a:lvl9pPr><a:defRPr sz="1200"/></a:lvl9pPr></a:lstStyle><a:p><a:pPr lvl="0"/><a:r><a:rPr lang="en-US"/><a:t>Click to edit Master text styles</a:t></a:r></a:p><a:p><a:pPr lvl="1"/><a:r><a:rPr lang="en-US"/><a:t>Second level</a:t></a:r></a:p><a:p><a:pPr lvl="2"/><a:r><a:rPr lang="en-US"/><a:t>Third level</a:t></a:r></a:p><a:p><a:pPr lvl="3"/><a:r><a:rPr lang="en-US"/><a:t>Fourth level</a:t></a:r></a:p><a:p><a:pPr lvl="4"/><a:r><a:rPr lang="en-US"/><a:t>Fifth level</a:t></a:r></a:p></p:txBody></p:sp><p:sp><p:nvSpPr><p:cNvPr id="5" name="Text Placeholder 4"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="body" sz="quarter" idx="3"/></p:nvPr></p:nvSpPr><p:spPr><a:xfrm><a:off x="4645026" y="1151335"/><a:ext cx="4041775" cy="479822"/></a:xfrm></p:spPr><p:txBody><a:bodyPr anchor="b"/><a:lstStyle><a:lvl1pPr marL="0" indent="0"><a:buNone/><a:defRPr sz="1800" b="1"/></a:lvl1pPr><a:lvl2pPr marL="342900" indent="0"><a:buNone/><a:defRPr sz="1500" b="1"/></a:lvl2pPr><a:lvl3pPr marL="685800" indent="0"><a:buNone/><a:defRPr sz="1350" b="1"/></a:lvl3pPr><a:lvl4pPr marL="1028700" indent="0"><a:buNone/><a:defRPr sz="1200" b="1"/></a:lvl4pPr><a:lvl5pPr marL="1371600" indent="0"><a:buNone/><a:defRPr sz="1200" b="1"/></a:lvl5pPr><a:lvl6pPr marL="1714500" indent="0"><a:buNone/><a:defRPr sz="1200" b="1"/></a:lvl6pPr><a:lvl7pPr marL="2057400" indent="0"><a:buNone/><a:defRPr sz="1200" b="1"/></a:lvl7pPr><a:lvl8pPr marL="2400300" indent="0"><a:buNone/><a:defRPr sz="1200" b="1"/></a:lvl8pPr><a:lvl9pPr marL="2743200" indent="0"><a:buNone/><a:defRPr sz="1200" b="1"/></a:lvl9pPr></a:lstStyle><a:p><a:pPr lvl="0"/><a:r><a:rPr lang="en-US"/><a:t>Click to edit Master text styles</a:t></a:r></a:p></p:txBody></p:sp><p:sp><p:nvSpPr><p:cNvPr id="6" name="Content Placeholder 5"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph sz="quarter" idx="4"/></p:nvPr></p:nvSpPr><p:spPr><a:xfrm><a:off x="4645026" y="1631156"/><a:ext cx="4041775" cy="2963466"/></a:xfrm></p:spPr><p:txBody><a:bodyPr/><a:lstStyle><a:lvl1pPr><a:defRPr sz="1800"/></a:lvl1pPr><a:lvl2pPr><a:defRPr sz="1500"/></a:lvl2pPr><a:lvl3pPr><a:defRPr sz="1350"/></a:lvl3pPr><a:lvl4pPr><a:defRPr sz="1200"/></a:lvl4pPr><a:lvl5pPr><a:defRPr sz="1200"/></a:lvl5pPr><a:lvl6pPr><a:defRPr sz="1200"/></a:lvl6pPr><a:lvl7pPr><a:defRPr sz="1200"/></a:lvl7pPr><a:lvl8pPr><a:defRPr sz="1200"/></a:lvl8pPr><a:lvl9pPr><a:defRPr sz="1200"/></a:lvl9pPr></a:lstStyle><a:p><a:pPr lvl="0"/><a:r><a:rPr lang="en-US"/><a:t>Click to edit Master text styles</a:t></a:r></a:p><a:p><a:pPr lvl="1"/><a:r><a:rPr lang="en-US"/><a:t>Second level</a:t></a:r></a:p><a:p><a:pPr lvl="2"/><a:r><a:rPr lang="en-US"/><a:t>Third level</a:t></a:r></a:p><a:p><a:pPr lvl="3"/><a:r><a:rPr lang="en-US"/><a:t>Fourth level</a:t></a:r></a:p><a:p><a:pPr lvl="4"/><a:r><a:rPr lang="en-US"/><a:t>Fifth level</a:t></a:r></a:p></p:txBody></p:sp><p:sp><p:nvSpPr><p:cNvPr id="7" name="Date Placeholder 6"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="dt" sz="half" idx="10"/></p:nvPr></p:nvSpPr><p:spPr/><p:txBody><a:bodyPr/><a:lstStyle/><a:p><a:fld id="{241EB5C9-1307-BA42-ABA2-0BC069CD8E7F}" type="datetimeFigureOut"><a:rPr lang="en-US" smtClean="0"/><a:t>1/2/22</a:t></a:fld><a:endParaRPr lang="en-US"/></a:p></p:txBody></p:sp><p:sp><p:nvSpPr><p:cNvPr id="8" name="Footer Placeholder 7"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="ftr" sz="quarter" idx="11"/></p:nvPr></p:nvSpPr><p:spPr/><p:txBody><a:bodyPr/><a:lstStyle/><a:p><a:endParaRPr lang="en-US"/></a:p></p:txBody></p:sp><p:sp><p:nvSpPr><p:cNvPr id="9" name="Slide Number Placeholder 8"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="sldNum" sz="quarter" idx="12"/></p:nvPr></p:nvSpPr><p:spPr/><p:txBody><a:bodyPr/><a:lstStyle/><a:p><a:fld id="{C5EF2332-01BF-834F-8236-50238282D533}" type="slidenum"><a:rPr lang="en-US" smtClean="0"/><a:t>‹#›</a:t></a:fld><a:endParaRPr lang="en-US"/></a:p></p:txBody></p:sp></p:spTree><p:extLst><p:ext uri="{BB962C8B-B14F-4D97-AF65-F5344CB8AC3E}"><p14:creationId xmlns:p14="http://schemas.microsoft.com/office/powerpoint/2010/main" val="2535793967"/></p:ext></p:extLst></p:cSld><p:clrMapOvr><a:masterClrMapping/></p:clrMapOvr></p:sldLayout>
diff --git a/data/pptx/ppt/slideLayouts/slideLayout6.xml b/data/pptx/ppt/slideLayouts/slideLayout6.xml
--- a/data/pptx/ppt/slideLayouts/slideLayout6.xml
+++ b/data/pptx/ppt/slideLayouts/slideLayout6.xml
@@ -1,2 +1,2 @@
 <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
-<p:sldLayout xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main" type="titleOnly" preserve="1"><p:cSld name="Title Only"><p:spTree><p:nvGrpSpPr><p:cNvPr id="1" name=""/><p:cNvGrpSpPr/><p:nvPr/></p:nvGrpSpPr><p:grpSpPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="0" cy="0"/><a:chOff x="0" y="0"/><a:chExt cx="0" cy="0"/></a:xfrm></p:grpSpPr><p:sp><p:nvSpPr><p:cNvPr id="2" name="Title 1"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="title"/></p:nvPr></p:nvSpPr><p:spPr/><p:txBody><a:bodyPr/><a:lstStyle/><a:p><a:r><a:rPr lang="en-US" smtClean="0"/><a:t>Click to edit Master title style</a:t></a:r><a:endParaRPr lang="en-US"/></a:p></p:txBody></p:sp><p:sp><p:nvSpPr><p:cNvPr id="3" name="Date Placeholder 2"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="dt" sz="half" idx="10"/></p:nvPr></p:nvSpPr><p:spPr/><p:txBody><a:bodyPr/><a:lstStyle/><a:p><a:fld id="{241EB5C9-1307-BA42-ABA2-0BC069CD8E7F}" type="datetimeFigureOut"><a:rPr lang="en-US" smtClean="0"/><a:t>6/5/17</a:t></a:fld><a:endParaRPr lang="en-US"/></a:p></p:txBody></p:sp><p:sp><p:nvSpPr><p:cNvPr id="4" name="Footer Placeholder 3"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="ftr" sz="quarter" idx="11"/></p:nvPr></p:nvSpPr><p:spPr/><p:txBody><a:bodyPr/><a:lstStyle/><a:p><a:endParaRPr lang="en-US"/></a:p></p:txBody></p:sp><p:sp><p:nvSpPr><p:cNvPr id="5" name="Slide Number Placeholder 4"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="sldNum" sz="quarter" idx="12"/></p:nvPr></p:nvSpPr><p:spPr/><p:txBody><a:bodyPr/><a:lstStyle/><a:p><a:fld id="{C5EF2332-01BF-834F-8236-50238282D533}" type="slidenum"><a:rPr lang="en-US" smtClean="0"/><a:t>‹#›</a:t></a:fld><a:endParaRPr lang="en-US"/></a:p></p:txBody></p:sp></p:spTree><p:extLst><p:ext uri="{BB962C8B-B14F-4D97-AF65-F5344CB8AC3E}"><p14:creationId xmlns:p14="http://schemas.microsoft.com/office/powerpoint/2010/main" val="3472721253"/></p:ext></p:extLst></p:cSld><p:clrMapOvr><a:masterClrMapping/></p:clrMapOvr></p:sldLayout>
+<p:sldLayout xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main" type="titleOnly" preserve="1"><p:cSld name="Title Only"><p:spTree><p:nvGrpSpPr><p:cNvPr id="1" name=""/><p:cNvGrpSpPr/><p:nvPr/></p:nvGrpSpPr><p:grpSpPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="0" cy="0"/><a:chOff x="0" y="0"/><a:chExt cx="0" cy="0"/></a:xfrm></p:grpSpPr><p:sp><p:nvSpPr><p:cNvPr id="2" name="Title 1"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="title"/></p:nvPr></p:nvSpPr><p:spPr/><p:txBody><a:bodyPr/><a:lstStyle/><a:p><a:r><a:rPr lang="en-US"/><a:t>Click to edit Master title style</a:t></a:r></a:p></p:txBody></p:sp><p:sp><p:nvSpPr><p:cNvPr id="3" name="Date Placeholder 2"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="dt" sz="half" idx="10"/></p:nvPr></p:nvSpPr><p:spPr/><p:txBody><a:bodyPr/><a:lstStyle/><a:p><a:fld id="{241EB5C9-1307-BA42-ABA2-0BC069CD8E7F}" type="datetimeFigureOut"><a:rPr lang="en-US" smtClean="0"/><a:t>1/2/22</a:t></a:fld><a:endParaRPr lang="en-US"/></a:p></p:txBody></p:sp><p:sp><p:nvSpPr><p:cNvPr id="4" name="Footer Placeholder 3"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="ftr" sz="quarter" idx="11"/></p:nvPr></p:nvSpPr><p:spPr/><p:txBody><a:bodyPr/><a:lstStyle/><a:p><a:endParaRPr lang="en-US"/></a:p></p:txBody></p:sp><p:sp><p:nvSpPr><p:cNvPr id="5" name="Slide Number Placeholder 4"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="sldNum" sz="quarter" idx="12"/></p:nvPr></p:nvSpPr><p:spPr/><p:txBody><a:bodyPr/><a:lstStyle/><a:p><a:fld id="{C5EF2332-01BF-834F-8236-50238282D533}" type="slidenum"><a:rPr lang="en-US" smtClean="0"/><a:t>‹#›</a:t></a:fld><a:endParaRPr lang="en-US"/></a:p></p:txBody></p:sp></p:spTree><p:extLst><p:ext uri="{BB962C8B-B14F-4D97-AF65-F5344CB8AC3E}"><p14:creationId xmlns:p14="http://schemas.microsoft.com/office/powerpoint/2010/main" val="3472721253"/></p:ext></p:extLst></p:cSld><p:clrMapOvr><a:masterClrMapping/></p:clrMapOvr></p:sldLayout>
diff --git a/data/pptx/ppt/slideLayouts/slideLayout7.xml b/data/pptx/ppt/slideLayouts/slideLayout7.xml
--- a/data/pptx/ppt/slideLayouts/slideLayout7.xml
+++ b/data/pptx/ppt/slideLayouts/slideLayout7.xml
@@ -1,2 +1,2 @@
 <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
-<p:sldLayout xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main" type="blank" preserve="1"><p:cSld name="Blank"><p:spTree><p:nvGrpSpPr><p:cNvPr id="1" name=""/><p:cNvGrpSpPr/><p:nvPr/></p:nvGrpSpPr><p:grpSpPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="0" cy="0"/><a:chOff x="0" y="0"/><a:chExt cx="0" cy="0"/></a:xfrm></p:grpSpPr><p:sp><p:nvSpPr><p:cNvPr id="2" name="Date Placeholder 1"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="dt" sz="half" idx="10"/></p:nvPr></p:nvSpPr><p:spPr/><p:txBody><a:bodyPr/><a:lstStyle/><a:p><a:fld id="{241EB5C9-1307-BA42-ABA2-0BC069CD8E7F}" type="datetimeFigureOut"><a:rPr lang="en-US" smtClean="0"/><a:t>6/5/17</a:t></a:fld><a:endParaRPr lang="en-US"/></a:p></p:txBody></p:sp><p:sp><p:nvSpPr><p:cNvPr id="3" name="Footer Placeholder 2"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="ftr" sz="quarter" idx="11"/></p:nvPr></p:nvSpPr><p:spPr/><p:txBody><a:bodyPr/><a:lstStyle/><a:p><a:endParaRPr lang="en-US"/></a:p></p:txBody></p:sp><p:sp><p:nvSpPr><p:cNvPr id="4" name="Slide Number Placeholder 3"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="sldNum" sz="quarter" idx="12"/></p:nvPr></p:nvSpPr><p:spPr/><p:txBody><a:bodyPr/><a:lstStyle/><a:p><a:fld id="{C5EF2332-01BF-834F-8236-50238282D533}" type="slidenum"><a:rPr lang="en-US" smtClean="0"/><a:t>‹#›</a:t></a:fld><a:endParaRPr lang="en-US"/></a:p></p:txBody></p:sp></p:spTree><p:extLst><p:ext uri="{BB962C8B-B14F-4D97-AF65-F5344CB8AC3E}"><p14:creationId xmlns:p14="http://schemas.microsoft.com/office/powerpoint/2010/main" val="2130901097"/></p:ext></p:extLst></p:cSld><p:clrMapOvr><a:masterClrMapping/></p:clrMapOvr></p:sldLayout>
+<p:sldLayout xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main" type="blank" preserve="1"><p:cSld name="Blank"><p:spTree><p:nvGrpSpPr><p:cNvPr id="1" name=""/><p:cNvGrpSpPr/><p:nvPr/></p:nvGrpSpPr><p:grpSpPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="0" cy="0"/><a:chOff x="0" y="0"/><a:chExt cx="0" cy="0"/></a:xfrm></p:grpSpPr><p:sp><p:nvSpPr><p:cNvPr id="2" name="Date Placeholder 1"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="dt" sz="half" idx="10"/></p:nvPr></p:nvSpPr><p:spPr/><p:txBody><a:bodyPr/><a:lstStyle/><a:p><a:fld id="{241EB5C9-1307-BA42-ABA2-0BC069CD8E7F}" type="datetimeFigureOut"><a:rPr lang="en-US" smtClean="0"/><a:t>1/2/22</a:t></a:fld><a:endParaRPr lang="en-US"/></a:p></p:txBody></p:sp><p:sp><p:nvSpPr><p:cNvPr id="3" name="Footer Placeholder 2"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="ftr" sz="quarter" idx="11"/></p:nvPr></p:nvSpPr><p:spPr/><p:txBody><a:bodyPr/><a:lstStyle/><a:p><a:endParaRPr lang="en-US"/></a:p></p:txBody></p:sp><p:sp><p:nvSpPr><p:cNvPr id="4" name="Slide Number Placeholder 3"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="sldNum" sz="quarter" idx="12"/></p:nvPr></p:nvSpPr><p:spPr/><p:txBody><a:bodyPr/><a:lstStyle/><a:p><a:fld id="{C5EF2332-01BF-834F-8236-50238282D533}" type="slidenum"><a:rPr lang="en-US" smtClean="0"/><a:t>‹#›</a:t></a:fld><a:endParaRPr lang="en-US"/></a:p></p:txBody></p:sp></p:spTree><p:extLst><p:ext uri="{BB962C8B-B14F-4D97-AF65-F5344CB8AC3E}"><p14:creationId xmlns:p14="http://schemas.microsoft.com/office/powerpoint/2010/main" val="2130901097"/></p:ext></p:extLst></p:cSld><p:clrMapOvr><a:masterClrMapping/></p:clrMapOvr></p:sldLayout>
diff --git a/data/pptx/ppt/slideLayouts/slideLayout8.xml b/data/pptx/ppt/slideLayouts/slideLayout8.xml
--- a/data/pptx/ppt/slideLayouts/slideLayout8.xml
+++ b/data/pptx/ppt/slideLayouts/slideLayout8.xml
@@ -1,2 +1,2 @@
 <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
-<p:sldLayout xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main" type="objTx" preserve="1"><p:cSld name="Content with Caption"><p:spTree><p:nvGrpSpPr><p:cNvPr id="1" name=""/><p:cNvGrpSpPr/><p:nvPr/></p:nvGrpSpPr><p:grpSpPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="0" cy="0"/><a:chOff x="0" y="0"/><a:chExt cx="0" cy="0"/></a:xfrm></p:grpSpPr><p:sp><p:nvSpPr><p:cNvPr id="2" name="Title 1"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="title"/></p:nvPr></p:nvSpPr><p:spPr><a:xfrm><a:off x="457200" y="273050"/><a:ext cx="3008313" cy="1162050"/></a:xfrm></p:spPr><p:txBody><a:bodyPr anchor="b"/><a:lstStyle><a:lvl1pPr algn="l"><a:defRPr sz="2000" b="1"/></a:lvl1pPr></a:lstStyle><a:p><a:r><a:rPr lang="en-US" smtClean="0"/><a:t>Click to edit Master title style</a:t></a:r><a:endParaRPr lang="en-US"/></a:p></p:txBody></p:sp><p:sp><p:nvSpPr><p:cNvPr id="3" name="Content Placeholder 2"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph idx="1"/></p:nvPr></p:nvSpPr><p:spPr><a:xfrm><a:off x="3575050" y="273050"/><a:ext cx="5111750" cy="5853113"/></a:xfrm></p:spPr><p:txBody><a:bodyPr/><a:lstStyle><a:lvl1pPr><a:defRPr sz="3200"/></a:lvl1pPr><a:lvl2pPr><a:defRPr sz="2800"/></a:lvl2pPr><a:lvl3pPr><a:defRPr sz="2400"/></a:lvl3pPr><a:lvl4pPr><a:defRPr sz="2000"/></a:lvl4pPr><a:lvl5pPr><a:defRPr sz="2000"/></a:lvl5pPr><a:lvl6pPr><a:defRPr sz="2000"/></a:lvl6pPr><a:lvl7pPr><a:defRPr sz="2000"/></a:lvl7pPr><a:lvl8pPr><a:defRPr sz="2000"/></a:lvl8pPr><a:lvl9pPr><a:defRPr sz="2000"/></a:lvl9pPr></a:lstStyle><a:p><a:pPr lvl="0"/><a:r><a:rPr lang="en-US" smtClean="0"/><a:t>Click to edit Master text styles</a:t></a:r></a:p><a:p><a:pPr lvl="1"/><a:r><a:rPr lang="en-US" smtClean="0"/><a:t>Second level</a:t></a:r></a:p><a:p><a:pPr lvl="2"/><a:r><a:rPr lang="en-US" smtClean="0"/><a:t>Third level</a:t></a:r></a:p><a:p><a:pPr lvl="3"/><a:r><a:rPr lang="en-US" smtClean="0"/><a:t>Fourth level</a:t></a:r></a:p><a:p><a:pPr lvl="4"/><a:r><a:rPr lang="en-US" smtClean="0"/><a:t>Fifth level</a:t></a:r><a:endParaRPr lang="en-US"/></a:p></p:txBody></p:sp><p:sp><p:nvSpPr><p:cNvPr id="4" name="Text Placeholder 3"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="body" sz="half" idx="2"/></p:nvPr></p:nvSpPr><p:spPr><a:xfrm><a:off x="457200" y="1435100"/><a:ext cx="3008313" cy="4691063"/></a:xfrm></p:spPr><p:txBody><a:bodyPr/><a:lstStyle><a:lvl1pPr marL="0" indent="0"><a:buNone/><a:defRPr sz="1400"/></a:lvl1pPr><a:lvl2pPr marL="457200" indent="0"><a:buNone/><a:defRPr sz="1200"/></a:lvl2pPr><a:lvl3pPr marL="914400" indent="0"><a:buNone/><a:defRPr sz="1000"/></a:lvl3pPr><a:lvl4pPr marL="1371600" indent="0"><a:buNone/><a:defRPr sz="900"/></a:lvl4pPr><a:lvl5pPr marL="1828800" indent="0"><a:buNone/><a:defRPr sz="900"/></a:lvl5pPr><a:lvl6pPr marL="2286000" indent="0"><a:buNone/><a:defRPr sz="900"/></a:lvl6pPr><a:lvl7pPr marL="2743200" indent="0"><a:buNone/><a:defRPr sz="900"/></a:lvl7pPr><a:lvl8pPr marL="3200400" indent="0"><a:buNone/><a:defRPr sz="900"/></a:lvl8pPr><a:lvl9pPr marL="3657600" indent="0"><a:buNone/><a:defRPr sz="900"/></a:lvl9pPr></a:lstStyle><a:p><a:pPr lvl="0"/><a:r><a:rPr lang="en-US" smtClean="0"/><a:t>Click to edit Master text styles</a:t></a:r></a:p></p:txBody></p:sp><p:sp><p:nvSpPr><p:cNvPr id="5" name="Date Placeholder 4"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="dt" sz="half" idx="10"/></p:nvPr></p:nvSpPr><p:spPr/><p:txBody><a:bodyPr/><a:lstStyle/><a:p><a:fld id="{241EB5C9-1307-BA42-ABA2-0BC069CD8E7F}" type="datetimeFigureOut"><a:rPr lang="en-US" smtClean="0"/><a:t>6/5/17</a:t></a:fld><a:endParaRPr lang="en-US"/></a:p></p:txBody></p:sp><p:sp><p:nvSpPr><p:cNvPr id="6" name="Footer Placeholder 5"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="ftr" sz="quarter" idx="11"/></p:nvPr></p:nvSpPr><p:spPr/><p:txBody><a:bodyPr/><a:lstStyle/><a:p><a:endParaRPr lang="en-US"/></a:p></p:txBody></p:sp><p:sp><p:nvSpPr><p:cNvPr id="7" name="Slide Number Placeholder 6"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="sldNum" sz="quarter" idx="12"/></p:nvPr></p:nvSpPr><p:spPr/><p:txBody><a:bodyPr/><a:lstStyle/><a:p><a:fld id="{C5EF2332-01BF-834F-8236-50238282D533}" type="slidenum"><a:rPr lang="en-US" smtClean="0"/><a:t>‹#›</a:t></a:fld><a:endParaRPr lang="en-US"/></a:p></p:txBody></p:sp></p:spTree><p:extLst><p:ext uri="{BB962C8B-B14F-4D97-AF65-F5344CB8AC3E}"><p14:creationId xmlns:p14="http://schemas.microsoft.com/office/powerpoint/2010/main" val="3540895647"/></p:ext></p:extLst></p:cSld><p:clrMapOvr><a:masterClrMapping/></p:clrMapOvr></p:sldLayout>
+<p:sldLayout xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main" type="objTx" preserve="1"><p:cSld name="Content with Caption"><p:spTree><p:nvGrpSpPr><p:cNvPr id="1" name=""/><p:cNvGrpSpPr/><p:nvPr/></p:nvGrpSpPr><p:grpSpPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="0" cy="0"/><a:chOff x="0" y="0"/><a:chExt cx="0" cy="0"/></a:xfrm></p:grpSpPr><p:sp><p:nvSpPr><p:cNvPr id="2" name="Title 1"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="title"/></p:nvPr></p:nvSpPr><p:spPr><a:xfrm><a:off x="457201" y="204787"/><a:ext cx="3008313" cy="871538"/></a:xfrm></p:spPr><p:txBody><a:bodyPr anchor="b"/><a:lstStyle><a:lvl1pPr algn="l"><a:defRPr sz="1500" b="1"/></a:lvl1pPr></a:lstStyle><a:p><a:r><a:rPr lang="en-US"/><a:t>Click to edit Master title style</a:t></a:r></a:p></p:txBody></p:sp><p:sp><p:nvSpPr><p:cNvPr id="3" name="Content Placeholder 2"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph idx="1"/></p:nvPr></p:nvSpPr><p:spPr><a:xfrm><a:off x="3575050" y="204788"/><a:ext cx="5111750" cy="4389835"/></a:xfrm></p:spPr><p:txBody><a:bodyPr/><a:lstStyle><a:lvl1pPr><a:defRPr sz="2400"/></a:lvl1pPr><a:lvl2pPr><a:defRPr sz="2100"/></a:lvl2pPr><a:lvl3pPr><a:defRPr sz="1800"/></a:lvl3pPr><a:lvl4pPr><a:defRPr sz="1500"/></a:lvl4pPr><a:lvl5pPr><a:defRPr sz="1500"/></a:lvl5pPr><a:lvl6pPr><a:defRPr sz="1500"/></a:lvl6pPr><a:lvl7pPr><a:defRPr sz="1500"/></a:lvl7pPr><a:lvl8pPr><a:defRPr sz="1500"/></a:lvl8pPr><a:lvl9pPr><a:defRPr sz="1500"/></a:lvl9pPr></a:lstStyle><a:p><a:pPr lvl="0"/><a:r><a:rPr lang="en-US"/><a:t>Click to edit Master text styles</a:t></a:r></a:p><a:p><a:pPr lvl="1"/><a:r><a:rPr lang="en-US"/><a:t>Second level</a:t></a:r></a:p><a:p><a:pPr lvl="2"/><a:r><a:rPr lang="en-US"/><a:t>Third level</a:t></a:r></a:p><a:p><a:pPr lvl="3"/><a:r><a:rPr lang="en-US"/><a:t>Fourth level</a:t></a:r></a:p><a:p><a:pPr lvl="4"/><a:r><a:rPr lang="en-US"/><a:t>Fifth level</a:t></a:r></a:p></p:txBody></p:sp><p:sp><p:nvSpPr><p:cNvPr id="4" name="Text Placeholder 3"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="body" sz="half" idx="2"/></p:nvPr></p:nvSpPr><p:spPr><a:xfrm><a:off x="457201" y="1076326"/><a:ext cx="3008313" cy="3518297"/></a:xfrm></p:spPr><p:txBody><a:bodyPr/><a:lstStyle><a:lvl1pPr marL="0" indent="0"><a:buNone/><a:defRPr sz="1050"/></a:lvl1pPr><a:lvl2pPr marL="342900" indent="0"><a:buNone/><a:defRPr sz="900"/></a:lvl2pPr><a:lvl3pPr marL="685800" indent="0"><a:buNone/><a:defRPr sz="750"/></a:lvl3pPr><a:lvl4pPr marL="1028700" indent="0"><a:buNone/><a:defRPr sz="675"/></a:lvl4pPr><a:lvl5pPr marL="1371600" indent="0"><a:buNone/><a:defRPr sz="675"/></a:lvl5pPr><a:lvl6pPr marL="1714500" indent="0"><a:buNone/><a:defRPr sz="675"/></a:lvl6pPr><a:lvl7pPr marL="2057400" indent="0"><a:buNone/><a:defRPr sz="675"/></a:lvl7pPr><a:lvl8pPr marL="2400300" indent="0"><a:buNone/><a:defRPr sz="675"/></a:lvl8pPr><a:lvl9pPr marL="2743200" indent="0"><a:buNone/><a:defRPr sz="675"/></a:lvl9pPr></a:lstStyle><a:p><a:pPr lvl="0"/><a:r><a:rPr lang="en-US"/><a:t>Click to edit Master text styles</a:t></a:r></a:p></p:txBody></p:sp><p:sp><p:nvSpPr><p:cNvPr id="5" name="Date Placeholder 4"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="dt" sz="half" idx="10"/></p:nvPr></p:nvSpPr><p:spPr/><p:txBody><a:bodyPr/><a:lstStyle/><a:p><a:fld id="{241EB5C9-1307-BA42-ABA2-0BC069CD8E7F}" type="datetimeFigureOut"><a:rPr lang="en-US" smtClean="0"/><a:t>1/2/22</a:t></a:fld><a:endParaRPr lang="en-US"/></a:p></p:txBody></p:sp><p:sp><p:nvSpPr><p:cNvPr id="6" name="Footer Placeholder 5"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="ftr" sz="quarter" idx="11"/></p:nvPr></p:nvSpPr><p:spPr/><p:txBody><a:bodyPr/><a:lstStyle/><a:p><a:endParaRPr lang="en-US"/></a:p></p:txBody></p:sp><p:sp><p:nvSpPr><p:cNvPr id="7" name="Slide Number Placeholder 6"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="sldNum" sz="quarter" idx="12"/></p:nvPr></p:nvSpPr><p:spPr/><p:txBody><a:bodyPr/><a:lstStyle/><a:p><a:fld id="{C5EF2332-01BF-834F-8236-50238282D533}" type="slidenum"><a:rPr lang="en-US" smtClean="0"/><a:t>‹#›</a:t></a:fld><a:endParaRPr lang="en-US"/></a:p></p:txBody></p:sp></p:spTree><p:extLst><p:ext uri="{BB962C8B-B14F-4D97-AF65-F5344CB8AC3E}"><p14:creationId xmlns:p14="http://schemas.microsoft.com/office/powerpoint/2010/main" val="3540895647"/></p:ext></p:extLst></p:cSld><p:clrMapOvr><a:masterClrMapping/></p:clrMapOvr></p:sldLayout>
diff --git a/data/pptx/ppt/slideLayouts/slideLayout9.xml b/data/pptx/ppt/slideLayouts/slideLayout9.xml
--- a/data/pptx/ppt/slideLayouts/slideLayout9.xml
+++ b/data/pptx/ppt/slideLayouts/slideLayout9.xml
@@ -1,2 +1,2 @@
 <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
-<p:sldLayout xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main" type="picTx" preserve="1"><p:cSld name="Picture with Caption"><p:spTree><p:nvGrpSpPr><p:cNvPr id="1" name=""/><p:cNvGrpSpPr/><p:nvPr/></p:nvGrpSpPr><p:grpSpPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="0" cy="0"/><a:chOff x="0" y="0"/><a:chExt cx="0" cy="0"/></a:xfrm></p:grpSpPr><p:sp><p:nvSpPr><p:cNvPr id="2" name="Title 1"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="title"/></p:nvPr></p:nvSpPr><p:spPr><a:xfrm><a:off x="1792288" y="4800600"/><a:ext cx="5486400" cy="566738"/></a:xfrm></p:spPr><p:txBody><a:bodyPr anchor="b"/><a:lstStyle><a:lvl1pPr algn="l"><a:defRPr sz="2000" b="1"/></a:lvl1pPr></a:lstStyle><a:p><a:r><a:rPr lang="en-US" smtClean="0"/><a:t>Click to edit Master title style</a:t></a:r><a:endParaRPr lang="en-US"/></a:p></p:txBody></p:sp><p:sp><p:nvSpPr><p:cNvPr id="3" name="Picture Placeholder 2"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="pic" idx="1"/></p:nvPr></p:nvSpPr><p:spPr><a:xfrm><a:off x="1792288" y="612775"/><a:ext cx="5486400" cy="4114800"/></a:xfrm></p:spPr><p:txBody><a:bodyPr/><a:lstStyle><a:lvl1pPr marL="0" indent="0"><a:buNone/><a:defRPr sz="3200"/></a:lvl1pPr><a:lvl2pPr marL="457200" indent="0"><a:buNone/><a:defRPr sz="2800"/></a:lvl2pPr><a:lvl3pPr marL="914400" indent="0"><a:buNone/><a:defRPr sz="2400"/></a:lvl3pPr><a:lvl4pPr marL="1371600" indent="0"><a:buNone/><a:defRPr sz="2000"/></a:lvl4pPr><a:lvl5pPr marL="1828800" indent="0"><a:buNone/><a:defRPr sz="2000"/></a:lvl5pPr><a:lvl6pPr marL="2286000" indent="0"><a:buNone/><a:defRPr sz="2000"/></a:lvl6pPr><a:lvl7pPr marL="2743200" indent="0"><a:buNone/><a:defRPr sz="2000"/></a:lvl7pPr><a:lvl8pPr marL="3200400" indent="0"><a:buNone/><a:defRPr sz="2000"/></a:lvl8pPr><a:lvl9pPr marL="3657600" indent="0"><a:buNone/><a:defRPr sz="2000"/></a:lvl9pPr></a:lstStyle><a:p><a:endParaRPr lang="en-US"/></a:p></p:txBody></p:sp><p:sp><p:nvSpPr><p:cNvPr id="4" name="Text Placeholder 3"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="body" sz="half" idx="2"/></p:nvPr></p:nvSpPr><p:spPr><a:xfrm><a:off x="1792288" y="5367338"/><a:ext cx="5486400" cy="804862"/></a:xfrm></p:spPr><p:txBody><a:bodyPr/><a:lstStyle><a:lvl1pPr marL="0" indent="0"><a:buNone/><a:defRPr sz="1400"/></a:lvl1pPr><a:lvl2pPr marL="457200" indent="0"><a:buNone/><a:defRPr sz="1200"/></a:lvl2pPr><a:lvl3pPr marL="914400" indent="0"><a:buNone/><a:defRPr sz="1000"/></a:lvl3pPr><a:lvl4pPr marL="1371600" indent="0"><a:buNone/><a:defRPr sz="900"/></a:lvl4pPr><a:lvl5pPr marL="1828800" indent="0"><a:buNone/><a:defRPr sz="900"/></a:lvl5pPr><a:lvl6pPr marL="2286000" indent="0"><a:buNone/><a:defRPr sz="900"/></a:lvl6pPr><a:lvl7pPr marL="2743200" indent="0"><a:buNone/><a:defRPr sz="900"/></a:lvl7pPr><a:lvl8pPr marL="3200400" indent="0"><a:buNone/><a:defRPr sz="900"/></a:lvl8pPr><a:lvl9pPr marL="3657600" indent="0"><a:buNone/><a:defRPr sz="900"/></a:lvl9pPr></a:lstStyle><a:p><a:pPr lvl="0"/><a:r><a:rPr lang="en-US" smtClean="0"/><a:t>Click to edit Master text styles</a:t></a:r></a:p></p:txBody></p:sp><p:sp><p:nvSpPr><p:cNvPr id="5" name="Date Placeholder 4"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="dt" sz="half" idx="10"/></p:nvPr></p:nvSpPr><p:spPr/><p:txBody><a:bodyPr/><a:lstStyle/><a:p><a:fld id="{241EB5C9-1307-BA42-ABA2-0BC069CD8E7F}" type="datetimeFigureOut"><a:rPr lang="en-US" smtClean="0"/><a:t>6/5/17</a:t></a:fld><a:endParaRPr lang="en-US"/></a:p></p:txBody></p:sp><p:sp><p:nvSpPr><p:cNvPr id="6" name="Footer Placeholder 5"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="ftr" sz="quarter" idx="11"/></p:nvPr></p:nvSpPr><p:spPr/><p:txBody><a:bodyPr/><a:lstStyle/><a:p><a:endParaRPr lang="en-US"/></a:p></p:txBody></p:sp><p:sp><p:nvSpPr><p:cNvPr id="7" name="Slide Number Placeholder 6"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="sldNum" sz="quarter" idx="12"/></p:nvPr></p:nvSpPr><p:spPr/><p:txBody><a:bodyPr/><a:lstStyle/><a:p><a:fld id="{C5EF2332-01BF-834F-8236-50238282D533}" type="slidenum"><a:rPr lang="en-US" smtClean="0"/><a:t>‹#›</a:t></a:fld><a:endParaRPr lang="en-US"/></a:p></p:txBody></p:sp></p:spTree><p:extLst><p:ext uri="{BB962C8B-B14F-4D97-AF65-F5344CB8AC3E}"><p14:creationId xmlns:p14="http://schemas.microsoft.com/office/powerpoint/2010/main" val="3566899855"/></p:ext></p:extLst></p:cSld><p:clrMapOvr><a:masterClrMapping/></p:clrMapOvr></p:sldLayout>
+<p:sldLayout xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main" type="picTx" preserve="1"><p:cSld name="Picture with Caption"><p:spTree><p:nvGrpSpPr><p:cNvPr id="1" name=""/><p:cNvGrpSpPr/><p:nvPr/></p:nvGrpSpPr><p:grpSpPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="0" cy="0"/><a:chOff x="0" y="0"/><a:chExt cx="0" cy="0"/></a:xfrm></p:grpSpPr><p:sp><p:nvSpPr><p:cNvPr id="2" name="Title 1"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="title"/></p:nvPr></p:nvSpPr><p:spPr><a:xfrm><a:off x="1792288" y="3600450"/><a:ext cx="5486400" cy="425054"/></a:xfrm></p:spPr><p:txBody><a:bodyPr anchor="b"/><a:lstStyle><a:lvl1pPr algn="l"><a:defRPr sz="1500" b="1"/></a:lvl1pPr></a:lstStyle><a:p><a:r><a:rPr lang="en-US"/><a:t>Click to edit Master title style</a:t></a:r></a:p></p:txBody></p:sp><p:sp><p:nvSpPr><p:cNvPr id="3" name="Picture Placeholder 2"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="pic" idx="1"/></p:nvPr></p:nvSpPr><p:spPr><a:xfrm><a:off x="1792288" y="459581"/><a:ext cx="5486400" cy="3086100"/></a:xfrm></p:spPr><p:txBody><a:bodyPr/><a:lstStyle><a:lvl1pPr marL="0" indent="0"><a:buNone/><a:defRPr sz="2400"/></a:lvl1pPr><a:lvl2pPr marL="342900" indent="0"><a:buNone/><a:defRPr sz="2100"/></a:lvl2pPr><a:lvl3pPr marL="685800" indent="0"><a:buNone/><a:defRPr sz="1800"/></a:lvl3pPr><a:lvl4pPr marL="1028700" indent="0"><a:buNone/><a:defRPr sz="1500"/></a:lvl4pPr><a:lvl5pPr marL="1371600" indent="0"><a:buNone/><a:defRPr sz="1500"/></a:lvl5pPr><a:lvl6pPr marL="1714500" indent="0"><a:buNone/><a:defRPr sz="1500"/></a:lvl6pPr><a:lvl7pPr marL="2057400" indent="0"><a:buNone/><a:defRPr sz="1500"/></a:lvl7pPr><a:lvl8pPr marL="2400300" indent="0"><a:buNone/><a:defRPr sz="1500"/></a:lvl8pPr><a:lvl9pPr marL="2743200" indent="0"><a:buNone/><a:defRPr sz="1500"/></a:lvl9pPr></a:lstStyle><a:p><a:endParaRPr lang="en-US"/></a:p></p:txBody></p:sp><p:sp><p:nvSpPr><p:cNvPr id="4" name="Text Placeholder 3"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="body" sz="half" idx="2"/></p:nvPr></p:nvSpPr><p:spPr><a:xfrm><a:off x="1792288" y="4025503"/><a:ext cx="5486400" cy="603647"/></a:xfrm></p:spPr><p:txBody><a:bodyPr/><a:lstStyle><a:lvl1pPr marL="0" indent="0"><a:buNone/><a:defRPr sz="1050"/></a:lvl1pPr><a:lvl2pPr marL="342900" indent="0"><a:buNone/><a:defRPr sz="900"/></a:lvl2pPr><a:lvl3pPr marL="685800" indent="0"><a:buNone/><a:defRPr sz="750"/></a:lvl3pPr><a:lvl4pPr marL="1028700" indent="0"><a:buNone/><a:defRPr sz="675"/></a:lvl4pPr><a:lvl5pPr marL="1371600" indent="0"><a:buNone/><a:defRPr sz="675"/></a:lvl5pPr><a:lvl6pPr marL="1714500" indent="0"><a:buNone/><a:defRPr sz="675"/></a:lvl6pPr><a:lvl7pPr marL="2057400" indent="0"><a:buNone/><a:defRPr sz="675"/></a:lvl7pPr><a:lvl8pPr marL="2400300" indent="0"><a:buNone/><a:defRPr sz="675"/></a:lvl8pPr><a:lvl9pPr marL="2743200" indent="0"><a:buNone/><a:defRPr sz="675"/></a:lvl9pPr></a:lstStyle><a:p><a:pPr lvl="0"/><a:r><a:rPr lang="en-US"/><a:t>Click to edit Master text styles</a:t></a:r></a:p></p:txBody></p:sp><p:sp><p:nvSpPr><p:cNvPr id="5" name="Date Placeholder 4"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="dt" sz="half" idx="10"/></p:nvPr></p:nvSpPr><p:spPr/><p:txBody><a:bodyPr/><a:lstStyle/><a:p><a:fld id="{241EB5C9-1307-BA42-ABA2-0BC069CD8E7F}" type="datetimeFigureOut"><a:rPr lang="en-US" smtClean="0"/><a:t>1/2/22</a:t></a:fld><a:endParaRPr lang="en-US"/></a:p></p:txBody></p:sp><p:sp><p:nvSpPr><p:cNvPr id="6" name="Footer Placeholder 5"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="ftr" sz="quarter" idx="11"/></p:nvPr></p:nvSpPr><p:spPr/><p:txBody><a:bodyPr/><a:lstStyle/><a:p><a:endParaRPr lang="en-US"/></a:p></p:txBody></p:sp><p:sp><p:nvSpPr><p:cNvPr id="7" name="Slide Number Placeholder 6"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="sldNum" sz="quarter" idx="12"/></p:nvPr></p:nvSpPr><p:spPr/><p:txBody><a:bodyPr/><a:lstStyle/><a:p><a:fld id="{C5EF2332-01BF-834F-8236-50238282D533}" type="slidenum"><a:rPr lang="en-US" smtClean="0"/><a:t>‹#›</a:t></a:fld><a:endParaRPr lang="en-US"/></a:p></p:txBody></p:sp></p:spTree><p:extLst><p:ext uri="{BB962C8B-B14F-4D97-AF65-F5344CB8AC3E}"><p14:creationId xmlns:p14="http://schemas.microsoft.com/office/powerpoint/2010/main" val="3566899855"/></p:ext></p:extLst></p:cSld><p:clrMapOvr><a:masterClrMapping/></p:clrMapOvr></p:sldLayout>
diff --git a/data/pptx/ppt/slideMasters/_rels/slideMaster1.xml.rels b/data/pptx/ppt/slideMasters/_rels/slideMaster1.xml.rels
--- a/data/pptx/ppt/slideMasters/_rels/slideMaster1.xml.rels
+++ b/data/pptx/ppt/slideMasters/_rels/slideMaster1.xml.rels
@@ -1,2 +1,2 @@
 <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
-<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId11" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/slideLayout" Target="../slideLayouts/slideLayout11.xml"/><Relationship Id="rId12" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme" Target="../theme/theme1.xml"/><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/slideLayout" Target="../slideLayouts/slideLayout1.xml"/><Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/slideLayout" Target="../slideLayouts/slideLayout2.xml"/><Relationship Id="rId3" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/slideLayout" Target="../slideLayouts/slideLayout3.xml"/><Relationship Id="rId4" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/slideLayout" Target="../slideLayouts/slideLayout4.xml"/><Relationship Id="rId5" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/slideLayout" Target="../slideLayouts/slideLayout5.xml"/><Relationship Id="rId6" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/slideLayout" Target="../slideLayouts/slideLayout6.xml"/><Relationship Id="rId7" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/slideLayout" Target="../slideLayouts/slideLayout7.xml"/><Relationship Id="rId8" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/slideLayout" Target="../slideLayouts/slideLayout8.xml"/><Relationship Id="rId9" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/slideLayout" Target="../slideLayouts/slideLayout9.xml"/><Relationship Id="rId10" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/slideLayout" Target="../slideLayouts/slideLayout10.xml"/></Relationships>
+<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId8" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/slideLayout" Target="../slideLayouts/slideLayout8.xml"/><Relationship Id="rId3" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/slideLayout" Target="../slideLayouts/slideLayout3.xml"/><Relationship Id="rId7" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/slideLayout" Target="../slideLayouts/slideLayout7.xml"/><Relationship Id="rId12" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme" Target="../theme/theme1.xml"/><Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/slideLayout" Target="../slideLayouts/slideLayout2.xml"/><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/slideLayout" Target="../slideLayouts/slideLayout1.xml"/><Relationship Id="rId6" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/slideLayout" Target="../slideLayouts/slideLayout6.xml"/><Relationship Id="rId11" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/slideLayout" Target="../slideLayouts/slideLayout11.xml"/><Relationship Id="rId5" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/slideLayout" Target="../slideLayouts/slideLayout5.xml"/><Relationship Id="rId10" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/slideLayout" Target="../slideLayouts/slideLayout10.xml"/><Relationship Id="rId4" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/slideLayout" Target="../slideLayouts/slideLayout4.xml"/><Relationship Id="rId9" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/slideLayout" Target="../slideLayouts/slideLayout9.xml"/></Relationships>
diff --git a/data/pptx/ppt/slideMasters/slideMaster1.xml b/data/pptx/ppt/slideMasters/slideMaster1.xml
--- a/data/pptx/ppt/slideMasters/slideMaster1.xml
+++ b/data/pptx/ppt/slideMasters/slideMaster1.xml
@@ -1,2 +1,2 @@
 <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
-<p:sldMaster xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main"><p:cSld><p:bg><p:bgRef idx="1001"><a:schemeClr val="bg1"/></p:bgRef></p:bg><p:spTree><p:nvGrpSpPr><p:cNvPr id="1" name=""/><p:cNvGrpSpPr/><p:nvPr/></p:nvGrpSpPr><p:grpSpPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="0" cy="0"/><a:chOff x="0" y="0"/><a:chExt cx="0" cy="0"/></a:xfrm></p:grpSpPr><p:sp><p:nvSpPr><p:cNvPr id="2" name="Title Placeholder 1"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="title"/></p:nvPr></p:nvSpPr><p:spPr><a:xfrm><a:off x="457200" y="274638"/><a:ext cx="8229600" cy="1143000"/></a:xfrm><a:prstGeom prst="rect"><a:avLst/></a:prstGeom></p:spPr><p:txBody><a:bodyPr vert="horz" lIns="91440" tIns="45720" rIns="91440" bIns="45720" rtlCol="0" anchor="ctr"><a:normAutofit/></a:bodyPr><a:lstStyle/><a:p><a:r><a:rPr lang="en-US" smtClean="0"/><a:t>Click to edit Master title style</a:t></a:r><a:endParaRPr lang="en-US"/></a:p></p:txBody></p:sp><p:sp><p:nvSpPr><p:cNvPr id="3" name="Text Placeholder 2"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="body" idx="1"/></p:nvPr></p:nvSpPr><p:spPr><a:xfrm><a:off x="457200" y="1600200"/><a:ext cx="8229600" cy="4525963"/></a:xfrm><a:prstGeom prst="rect"><a:avLst/></a:prstGeom></p:spPr><p:txBody><a:bodyPr vert="horz" lIns="91440" tIns="45720" rIns="91440" bIns="45720" rtlCol="0"><a:normAutofit/></a:bodyPr><a:lstStyle/><a:p><a:pPr lvl="0"/><a:r><a:rPr lang="en-US" smtClean="0"/><a:t>Click to edit Master text styles</a:t></a:r></a:p><a:p><a:pPr lvl="1"/><a:r><a:rPr lang="en-US" smtClean="0"/><a:t>Second level</a:t></a:r></a:p><a:p><a:pPr lvl="2"/><a:r><a:rPr lang="en-US" smtClean="0"/><a:t>Third level</a:t></a:r></a:p><a:p><a:pPr lvl="3"/><a:r><a:rPr lang="en-US" smtClean="0"/><a:t>Fourth level</a:t></a:r></a:p><a:p><a:pPr lvl="4"/><a:r><a:rPr lang="en-US" smtClean="0"/><a:t>Fifth level</a:t></a:r><a:endParaRPr lang="en-US"/></a:p></p:txBody></p:sp><p:sp><p:nvSpPr><p:cNvPr id="4" name="Date Placeholder 3"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="dt" sz="half" idx="2"/></p:nvPr></p:nvSpPr><p:spPr><a:xfrm><a:off x="457200" y="6356350"/><a:ext cx="2133600" cy="365125"/></a:xfrm><a:prstGeom prst="rect"><a:avLst/></a:prstGeom></p:spPr><p:txBody><a:bodyPr vert="horz" lIns="91440" tIns="45720" rIns="91440" bIns="45720" rtlCol="0" anchor="ctr"/><a:lstStyle><a:lvl1pPr algn="l"><a:defRPr sz="1200"><a:solidFill><a:schemeClr val="tx1"><a:tint val="75000"/></a:schemeClr></a:solidFill></a:defRPr></a:lvl1pPr></a:lstStyle><a:p><a:fld id="{241EB5C9-1307-BA42-ABA2-0BC069CD8E7F}" type="datetimeFigureOut"><a:rPr lang="en-US" smtClean="0"/><a:t>6/5/17</a:t></a:fld><a:endParaRPr lang="en-US"/></a:p></p:txBody></p:sp><p:sp><p:nvSpPr><p:cNvPr id="5" name="Footer Placeholder 4"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="ftr" sz="quarter" idx="3"/></p:nvPr></p:nvSpPr><p:spPr><a:xfrm><a:off x="3124200" y="6356350"/><a:ext cx="2895600" cy="365125"/></a:xfrm><a:prstGeom prst="rect"><a:avLst/></a:prstGeom></p:spPr><p:txBody><a:bodyPr vert="horz" lIns="91440" tIns="45720" rIns="91440" bIns="45720" rtlCol="0" anchor="ctr"/><a:lstStyle><a:lvl1pPr algn="ctr"><a:defRPr sz="1200"><a:solidFill><a:schemeClr val="tx1"><a:tint val="75000"/></a:schemeClr></a:solidFill></a:defRPr></a:lvl1pPr></a:lstStyle><a:p><a:endParaRPr lang="en-US"/></a:p></p:txBody></p:sp><p:sp><p:nvSpPr><p:cNvPr id="6" name="Slide Number Placeholder 5"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="sldNum" sz="quarter" idx="4"/></p:nvPr></p:nvSpPr><p:spPr><a:xfrm><a:off x="6553200" y="6356350"/><a:ext cx="2133600" cy="365125"/></a:xfrm><a:prstGeom prst="rect"><a:avLst/></a:prstGeom></p:spPr><p:txBody><a:bodyPr vert="horz" lIns="91440" tIns="45720" rIns="91440" bIns="45720" rtlCol="0" anchor="ctr"/><a:lstStyle><a:lvl1pPr algn="r"><a:defRPr sz="1200"><a:solidFill><a:schemeClr val="tx1"><a:tint val="75000"/></a:schemeClr></a:solidFill></a:defRPr></a:lvl1pPr></a:lstStyle><a:p><a:fld id="{C5EF2332-01BF-834F-8236-50238282D533}" type="slidenum"><a:rPr lang="en-US" smtClean="0"/><a:t>‹#›</a:t></a:fld><a:endParaRPr lang="en-US"/></a:p></p:txBody></p:sp></p:spTree><p:extLst><p:ext uri="{BB962C8B-B14F-4D97-AF65-F5344CB8AC3E}"><p14:creationId xmlns:p14="http://schemas.microsoft.com/office/powerpoint/2010/main" val="3676200875"/></p:ext></p:extLst></p:cSld><p:clrMap bg1="lt1" tx1="dk1" bg2="lt2" tx2="dk2" accent1="accent1" accent2="accent2" accent3="accent3" accent4="accent4" accent5="accent5" accent6="accent6" hlink="hlink" folHlink="folHlink"/><p:sldLayoutIdLst><p:sldLayoutId id="2147483649" r:id="rId1"/><p:sldLayoutId id="2147483650" r:id="rId2"/><p:sldLayoutId id="2147483651" r:id="rId3"/><p:sldLayoutId id="2147483652" r:id="rId4"/><p:sldLayoutId id="2147483653" r:id="rId5"/><p:sldLayoutId id="2147483654" r:id="rId6"/><p:sldLayoutId id="2147483655" r:id="rId7"/><p:sldLayoutId id="2147483656" r:id="rId8"/><p:sldLayoutId id="2147483657" r:id="rId9"/><p:sldLayoutId id="2147483658" r:id="rId10"/><p:sldLayoutId id="2147483659" r:id="rId11"/></p:sldLayoutIdLst><p:txStyles><p:titleStyle><a:lvl1pPr algn="ctr" defTabSz="457200" rtl="0" eaLnBrk="1" latinLnBrk="0" hangingPunct="1"><a:spcBef><a:spcPct val="0"/></a:spcBef><a:buNone/><a:defRPr sz="4400" kern="1200"><a:solidFill><a:schemeClr val="tx1"/></a:solidFill><a:latin typeface="+mj-lt"/><a:ea typeface="+mj-ea"/><a:cs typeface="+mj-cs"/></a:defRPr></a:lvl1pPr></p:titleStyle><p:bodyStyle><a:lvl1pPr marL="342900" indent="-342900" algn="l" defTabSz="457200" rtl="0" eaLnBrk="1" latinLnBrk="0" hangingPunct="1"><a:spcBef><a:spcPct val="20000"/></a:spcBef><a:buFont typeface="Arial"/><a:buChar char="•"/><a:defRPr sz="3200" kern="1200"><a:solidFill><a:schemeClr val="tx1"/></a:solidFill><a:latin typeface="+mn-lt"/><a:ea typeface="+mn-ea"/><a:cs typeface="+mn-cs"/></a:defRPr></a:lvl1pPr><a:lvl2pPr marL="742950" indent="-285750" algn="l" defTabSz="457200" rtl="0" eaLnBrk="1" latinLnBrk="0" hangingPunct="1"><a:spcBef><a:spcPct val="20000"/></a:spcBef><a:buFont typeface="Arial"/><a:buChar char="–"/><a:defRPr sz="2800" kern="1200"><a:solidFill><a:schemeClr val="tx1"/></a:solidFill><a:latin typeface="+mn-lt"/><a:ea typeface="+mn-ea"/><a:cs typeface="+mn-cs"/></a:defRPr></a:lvl2pPr><a:lvl3pPr marL="1143000" indent="-228600" algn="l" defTabSz="457200" rtl="0" eaLnBrk="1" latinLnBrk="0" hangingPunct="1"><a:spcBef><a:spcPct val="20000"/></a:spcBef><a:buFont typeface="Arial"/><a:buChar char="•"/><a:defRPr sz="2400" kern="1200"><a:solidFill><a:schemeClr val="tx1"/></a:solidFill><a:latin typeface="+mn-lt"/><a:ea typeface="+mn-ea"/><a:cs typeface="+mn-cs"/></a:defRPr></a:lvl3pPr><a:lvl4pPr marL="1600200" indent="-228600" algn="l" defTabSz="457200" rtl="0" eaLnBrk="1" latinLnBrk="0" hangingPunct="1"><a:spcBef><a:spcPct val="20000"/></a:spcBef><a:buFont typeface="Arial"/><a:buChar char="–"/><a:defRPr sz="2000" kern="1200"><a:solidFill><a:schemeClr val="tx1"/></a:solidFill><a:latin typeface="+mn-lt"/><a:ea typeface="+mn-ea"/><a:cs typeface="+mn-cs"/></a:defRPr></a:lvl4pPr><a:lvl5pPr marL="2057400" indent="-228600" algn="l" defTabSz="457200" rtl="0" eaLnBrk="1" latinLnBrk="0" hangingPunct="1"><a:spcBef><a:spcPct val="20000"/></a:spcBef><a:buFont typeface="Arial"/><a:buChar char="»"/><a:defRPr sz="2000" kern="1200"><a:solidFill><a:schemeClr val="tx1"/></a:solidFill><a:latin typeface="+mn-lt"/><a:ea typeface="+mn-ea"/><a:cs typeface="+mn-cs"/></a:defRPr></a:lvl5pPr><a:lvl6pPr marL="2514600" indent="-228600" algn="l" defTabSz="457200" rtl="0" eaLnBrk="1" latinLnBrk="0" hangingPunct="1"><a:spcBef><a:spcPct val="20000"/></a:spcBef><a:buFont typeface="Arial"/><a:buChar char="•"/><a:defRPr sz="2000" kern="1200"><a:solidFill><a:schemeClr val="tx1"/></a:solidFill><a:latin typeface="+mn-lt"/><a:ea typeface="+mn-ea"/><a:cs typeface="+mn-cs"/></a:defRPr></a:lvl6pPr><a:lvl7pPr marL="2971800" indent="-228600" algn="l" defTabSz="457200" rtl="0" eaLnBrk="1" latinLnBrk="0" hangingPunct="1"><a:spcBef><a:spcPct val="20000"/></a:spcBef><a:buFont typeface="Arial"/><a:buChar char="•"/><a:defRPr sz="2000" kern="1200"><a:solidFill><a:schemeClr val="tx1"/></a:solidFill><a:latin typeface="+mn-lt"/><a:ea typeface="+mn-ea"/><a:cs typeface="+mn-cs"/></a:defRPr></a:lvl7pPr><a:lvl8pPr marL="3429000" indent="-228600" algn="l" defTabSz="457200" rtl="0" eaLnBrk="1" latinLnBrk="0" hangingPunct="1"><a:spcBef><a:spcPct val="20000"/></a:spcBef><a:buFont typeface="Arial"/><a:buChar char="•"/><a:defRPr sz="2000" kern="1200"><a:solidFill><a:schemeClr val="tx1"/></a:solidFill><a:latin typeface="+mn-lt"/><a:ea typeface="+mn-ea"/><a:cs typeface="+mn-cs"/></a:defRPr></a:lvl8pPr><a:lvl9pPr marL="3886200" indent="-228600" algn="l" defTabSz="457200" rtl="0" eaLnBrk="1" latinLnBrk="0" hangingPunct="1"><a:spcBef><a:spcPct val="20000"/></a:spcBef><a:buFont typeface="Arial"/><a:buChar char="•"/><a:defRPr sz="2000" kern="1200"><a:solidFill><a:schemeClr val="tx1"/></a:solidFill><a:latin typeface="+mn-lt"/><a:ea typeface="+mn-ea"/><a:cs typeface="+mn-cs"/></a:defRPr></a:lvl9pPr></p:bodyStyle><p:otherStyle><a:defPPr><a:defRPr lang="en-US"/></a:defPPr><a:lvl1pPr marL="0" algn="l" defTabSz="457200" rtl="0" eaLnBrk="1" latinLnBrk="0" hangingPunct="1"><a:defRPr sz="1800" kern="1200"><a:solidFill><a:schemeClr val="tx1"/></a:solidFill><a:latin typeface="+mn-lt"/><a:ea typeface="+mn-ea"/><a:cs typeface="+mn-cs"/></a:defRPr></a:lvl1pPr><a:lvl2pPr marL="457200" algn="l" defTabSz="457200" rtl="0" eaLnBrk="1" latinLnBrk="0" hangingPunct="1"><a:defRPr sz="1800" kern="1200"><a:solidFill><a:schemeClr val="tx1"/></a:solidFill><a:latin typeface="+mn-lt"/><a:ea typeface="+mn-ea"/><a:cs typeface="+mn-cs"/></a:defRPr></a:lvl2pPr><a:lvl3pPr marL="914400" algn="l" defTabSz="457200" rtl="0" eaLnBrk="1" latinLnBrk="0" hangingPunct="1"><a:defRPr sz="1800" kern="1200"><a:solidFill><a:schemeClr val="tx1"/></a:solidFill><a:latin typeface="+mn-lt"/><a:ea typeface="+mn-ea"/><a:cs typeface="+mn-cs"/></a:defRPr></a:lvl3pPr><a:lvl4pPr marL="1371600" algn="l" defTabSz="457200" rtl="0" eaLnBrk="1" latinLnBrk="0" hangingPunct="1"><a:defRPr sz="1800" kern="1200"><a:solidFill><a:schemeClr val="tx1"/></a:solidFill><a:latin typeface="+mn-lt"/><a:ea typeface="+mn-ea"/><a:cs typeface="+mn-cs"/></a:defRPr></a:lvl4pPr><a:lvl5pPr marL="1828800" algn="l" defTabSz="457200" rtl="0" eaLnBrk="1" latinLnBrk="0" hangingPunct="1"><a:defRPr sz="1800" kern="1200"><a:solidFill><a:schemeClr val="tx1"/></a:solidFill><a:latin typeface="+mn-lt"/><a:ea typeface="+mn-ea"/><a:cs typeface="+mn-cs"/></a:defRPr></a:lvl5pPr><a:lvl6pPr marL="2286000" algn="l" defTabSz="457200" rtl="0" eaLnBrk="1" latinLnBrk="0" hangingPunct="1"><a:defRPr sz="1800" kern="1200"><a:solidFill><a:schemeClr val="tx1"/></a:solidFill><a:latin typeface="+mn-lt"/><a:ea typeface="+mn-ea"/><a:cs typeface="+mn-cs"/></a:defRPr></a:lvl6pPr><a:lvl7pPr marL="2743200" algn="l" defTabSz="457200" rtl="0" eaLnBrk="1" latinLnBrk="0" hangingPunct="1"><a:defRPr sz="1800" kern="1200"><a:solidFill><a:schemeClr val="tx1"/></a:solidFill><a:latin typeface="+mn-lt"/><a:ea typeface="+mn-ea"/><a:cs typeface="+mn-cs"/></a:defRPr></a:lvl7pPr><a:lvl8pPr marL="3200400" algn="l" defTabSz="457200" rtl="0" eaLnBrk="1" latinLnBrk="0" hangingPunct="1"><a:defRPr sz="1800" kern="1200"><a:solidFill><a:schemeClr val="tx1"/></a:solidFill><a:latin typeface="+mn-lt"/><a:ea typeface="+mn-ea"/><a:cs typeface="+mn-cs"/></a:defRPr></a:lvl8pPr><a:lvl9pPr marL="3657600" algn="l" defTabSz="457200" rtl="0" eaLnBrk="1" latinLnBrk="0" hangingPunct="1"><a:defRPr sz="1800" kern="1200"><a:solidFill><a:schemeClr val="tx1"/></a:solidFill><a:latin typeface="+mn-lt"/><a:ea typeface="+mn-ea"/><a:cs typeface="+mn-cs"/></a:defRPr></a:lvl9pPr></p:otherStyle></p:txStyles></p:sldMaster>
+<p:sldMaster xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main"><p:cSld><p:bg><p:bgRef idx="1001"><a:schemeClr val="bg1"/></p:bgRef></p:bg><p:spTree><p:nvGrpSpPr><p:cNvPr id="1" name=""/><p:cNvGrpSpPr/><p:nvPr/></p:nvGrpSpPr><p:grpSpPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="0" cy="0"/><a:chOff x="0" y="0"/><a:chExt cx="0" cy="0"/></a:xfrm></p:grpSpPr><p:sp><p:nvSpPr><p:cNvPr id="2" name="Title Placeholder 1"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="title"/></p:nvPr></p:nvSpPr><p:spPr><a:xfrm><a:off x="457200" y="205979"/><a:ext cx="8229600" cy="857250"/></a:xfrm><a:prstGeom prst="rect"><a:avLst/></a:prstGeom></p:spPr><p:txBody><a:bodyPr vert="horz" lIns="91440" tIns="45720" rIns="91440" bIns="45720" rtlCol="0" anchor="ctr"><a:normAutofit/></a:bodyPr><a:lstStyle/><a:p><a:r><a:rPr lang="en-US"/><a:t>Click to edit Master title style</a:t></a:r></a:p></p:txBody></p:sp><p:sp><p:nvSpPr><p:cNvPr id="3" name="Text Placeholder 2"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="body" idx="1"/></p:nvPr></p:nvSpPr><p:spPr><a:xfrm><a:off x="457200" y="1200151"/><a:ext cx="8229600" cy="3394472"/></a:xfrm><a:prstGeom prst="rect"><a:avLst/></a:prstGeom></p:spPr><p:txBody><a:bodyPr vert="horz" lIns="91440" tIns="45720" rIns="91440" bIns="45720" rtlCol="0"><a:normAutofit/></a:bodyPr><a:lstStyle/><a:p><a:pPr lvl="0"/><a:r><a:rPr lang="en-US"/><a:t>Click to edit Master text styles</a:t></a:r></a:p><a:p><a:pPr lvl="1"/><a:r><a:rPr lang="en-US"/><a:t>Second level</a:t></a:r></a:p><a:p><a:pPr lvl="2"/><a:r><a:rPr lang="en-US"/><a:t>Third level</a:t></a:r></a:p><a:p><a:pPr lvl="3"/><a:r><a:rPr lang="en-US"/><a:t>Fourth level</a:t></a:r></a:p><a:p><a:pPr lvl="4"/><a:r><a:rPr lang="en-US"/><a:t>Fifth level</a:t></a:r></a:p></p:txBody></p:sp><p:sp><p:nvSpPr><p:cNvPr id="4" name="Date Placeholder 3"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="dt" sz="half" idx="2"/></p:nvPr></p:nvSpPr><p:spPr><a:xfrm><a:off x="457200" y="4767263"/><a:ext cx="2133600" cy="273844"/></a:xfrm><a:prstGeom prst="rect"><a:avLst/></a:prstGeom></p:spPr><p:txBody><a:bodyPr vert="horz" lIns="91440" tIns="45720" rIns="91440" bIns="45720" rtlCol="0" anchor="ctr"/><a:lstStyle><a:lvl1pPr algn="l"><a:defRPr sz="900"><a:solidFill><a:schemeClr val="tx1"><a:tint val="75000"/></a:schemeClr></a:solidFill></a:defRPr></a:lvl1pPr></a:lstStyle><a:p><a:fld id="{241EB5C9-1307-BA42-ABA2-0BC069CD8E7F}" type="datetimeFigureOut"><a:rPr lang="en-US" smtClean="0"/><a:t>1/2/22</a:t></a:fld><a:endParaRPr lang="en-US"/></a:p></p:txBody></p:sp><p:sp><p:nvSpPr><p:cNvPr id="5" name="Footer Placeholder 4"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="ftr" sz="quarter" idx="3"/></p:nvPr></p:nvSpPr><p:spPr><a:xfrm><a:off x="3124200" y="4767263"/><a:ext cx="2895600" cy="273844"/></a:xfrm><a:prstGeom prst="rect"><a:avLst/></a:prstGeom></p:spPr><p:txBody><a:bodyPr vert="horz" lIns="91440" tIns="45720" rIns="91440" bIns="45720" rtlCol="0" anchor="ctr"/><a:lstStyle><a:lvl1pPr algn="ctr"><a:defRPr sz="900"><a:solidFill><a:schemeClr val="tx1"><a:tint val="75000"/></a:schemeClr></a:solidFill></a:defRPr></a:lvl1pPr></a:lstStyle><a:p><a:endParaRPr lang="en-US"/></a:p></p:txBody></p:sp><p:sp><p:nvSpPr><p:cNvPr id="6" name="Slide Number Placeholder 5"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="sldNum" sz="quarter" idx="4"/></p:nvPr></p:nvSpPr><p:spPr><a:xfrm><a:off x="6553200" y="4767263"/><a:ext cx="2133600" cy="273844"/></a:xfrm><a:prstGeom prst="rect"><a:avLst/></a:prstGeom></p:spPr><p:txBody><a:bodyPr vert="horz" lIns="91440" tIns="45720" rIns="91440" bIns="45720" rtlCol="0" anchor="ctr"/><a:lstStyle><a:lvl1pPr algn="r"><a:defRPr sz="900"><a:solidFill><a:schemeClr val="tx1"><a:tint val="75000"/></a:schemeClr></a:solidFill></a:defRPr></a:lvl1pPr></a:lstStyle><a:p><a:fld id="{C5EF2332-01BF-834F-8236-50238282D533}" type="slidenum"><a:rPr lang="en-US" smtClean="0"/><a:t>‹#›</a:t></a:fld><a:endParaRPr lang="en-US"/></a:p></p:txBody></p:sp></p:spTree><p:extLst><p:ext uri="{BB962C8B-B14F-4D97-AF65-F5344CB8AC3E}"><p14:creationId xmlns:p14="http://schemas.microsoft.com/office/powerpoint/2010/main" val="3676200875"/></p:ext></p:extLst></p:cSld><p:clrMap bg1="lt1" tx1="dk1" bg2="lt2" tx2="dk2" accent1="accent1" accent2="accent2" accent3="accent3" accent4="accent4" accent5="accent5" accent6="accent6" hlink="hlink" folHlink="folHlink"/><p:sldLayoutIdLst><p:sldLayoutId id="2147483649" r:id="rId1"/><p:sldLayoutId id="2147483650" r:id="rId2"/><p:sldLayoutId id="2147483651" r:id="rId3"/><p:sldLayoutId id="2147483652" r:id="rId4"/><p:sldLayoutId id="2147483653" r:id="rId5"/><p:sldLayoutId id="2147483654" r:id="rId6"/><p:sldLayoutId id="2147483655" r:id="rId7"/><p:sldLayoutId id="2147483656" r:id="rId8"/><p:sldLayoutId id="2147483657" r:id="rId9"/><p:sldLayoutId id="2147483658" r:id="rId10"/><p:sldLayoutId id="2147483659" r:id="rId11"/></p:sldLayoutIdLst><p:txStyles><p:titleStyle><a:lvl1pPr algn="ctr" defTabSz="342900" rtl="0" eaLnBrk="1" latinLnBrk="0" hangingPunct="1"><a:spcBef><a:spcPct val="0"/></a:spcBef><a:buNone/><a:defRPr sz="3300" kern="1200"><a:solidFill><a:schemeClr val="tx1"/></a:solidFill><a:latin typeface="+mj-lt"/><a:ea typeface="+mj-ea"/><a:cs typeface="+mj-cs"/></a:defRPr></a:lvl1pPr></p:titleStyle><p:bodyStyle><a:lvl1pPr marL="342900" indent="-342900" algn="l" defTabSz="342900" rtl="0" eaLnBrk="1" latinLnBrk="0" hangingPunct="1"><a:spcBef><a:spcPct val="20000"/></a:spcBef><a:buFont typeface="Arial"/><a:buChar char="•"/><a:defRPr sz="2400" kern="1200"><a:solidFill><a:schemeClr val="tx1"/></a:solidFill><a:latin typeface="+mn-lt"/><a:ea typeface="+mn-ea"/><a:cs typeface="+mn-cs"/></a:defRPr></a:lvl1pPr><a:lvl2pPr marL="685800" indent="-342900" algn="l" defTabSz="342900" rtl="0" eaLnBrk="1" latinLnBrk="0" hangingPunct="1"><a:spcBef><a:spcPct val="20000"/></a:spcBef><a:buFont typeface="Arial"/><a:buChar char="–"/><a:defRPr sz="2100" kern="1200"><a:solidFill><a:schemeClr val="tx1"/></a:solidFill><a:latin typeface="+mn-lt"/><a:ea typeface="+mn-ea"/><a:cs typeface="+mn-cs"/></a:defRPr></a:lvl2pPr><a:lvl3pPr marL="1028700" indent="-342900" algn="l" defTabSz="342900" rtl="0" eaLnBrk="1" latinLnBrk="0" hangingPunct="1"><a:spcBef><a:spcPct val="20000"/></a:spcBef><a:buFont typeface="Arial"/><a:buChar char="•"/><a:defRPr sz="1800" kern="1200"><a:solidFill><a:schemeClr val="tx1"/></a:solidFill><a:latin typeface="+mn-lt"/><a:ea typeface="+mn-ea"/><a:cs typeface="+mn-cs"/></a:defRPr></a:lvl3pPr><a:lvl4pPr marL="1371600" indent="-342900" algn="l" defTabSz="342900" rtl="0" eaLnBrk="1" latinLnBrk="0" hangingPunct="1"><a:spcBef><a:spcPct val="20000"/></a:spcBef><a:buFont typeface="Arial"/><a:buChar char="–"/><a:defRPr sz="1500" kern="1200"><a:solidFill><a:schemeClr val="tx1"/></a:solidFill><a:latin typeface="+mn-lt"/><a:ea typeface="+mn-ea"/><a:cs typeface="+mn-cs"/></a:defRPr></a:lvl4pPr><a:lvl5pPr marL="1714500" indent="-342900" algn="l" defTabSz="342900" rtl="0" eaLnBrk="1" latinLnBrk="0" hangingPunct="1"><a:spcBef><a:spcPct val="20000"/></a:spcBef><a:buFont typeface="Arial"/><a:buChar char="»"/><a:defRPr sz="1500" kern="1200"><a:solidFill><a:schemeClr val="tx1"/></a:solidFill><a:latin typeface="+mn-lt"/><a:ea typeface="+mn-ea"/><a:cs typeface="+mn-cs"/></a:defRPr></a:lvl5pPr><a:lvl6pPr marL="2057400" indent="-342900" algn="l" defTabSz="342900" rtl="0" eaLnBrk="1" latinLnBrk="0" hangingPunct="1"><a:spcBef><a:spcPct val="20000"/></a:spcBef><a:buFont typeface="Arial"/><a:buChar char="•"/><a:defRPr sz="1500" kern="1200"><a:solidFill><a:schemeClr val="tx1"/></a:solidFill><a:latin typeface="+mn-lt"/><a:ea typeface="+mn-ea"/><a:cs typeface="+mn-cs"/></a:defRPr></a:lvl6pPr><a:lvl7pPr marL="2400300" indent="-342900" algn="l" defTabSz="342900" rtl="0" eaLnBrk="1" latinLnBrk="0" hangingPunct="1"><a:spcBef><a:spcPct val="20000"/></a:spcBef><a:buFont typeface="Arial"/><a:buChar char="•"/><a:defRPr sz="1500" kern="1200"><a:solidFill><a:schemeClr val="tx1"/></a:solidFill><a:latin typeface="+mn-lt"/><a:ea typeface="+mn-ea"/><a:cs typeface="+mn-cs"/></a:defRPr></a:lvl7pPr><a:lvl8pPr marL="2743200" indent="-342900" algn="l" defTabSz="342900" rtl="0" eaLnBrk="1" latinLnBrk="0" hangingPunct="1"><a:spcBef><a:spcPct val="20000"/></a:spcBef><a:buFont typeface="Arial"/><a:buChar char="•"/><a:defRPr sz="1500" kern="1200"><a:solidFill><a:schemeClr val="tx1"/></a:solidFill><a:latin typeface="+mn-lt"/><a:ea typeface="+mn-ea"/><a:cs typeface="+mn-cs"/></a:defRPr></a:lvl8pPr><a:lvl9pPr marL="3086100" indent="-342900" algn="l" defTabSz="342900" rtl="0" eaLnBrk="1" latinLnBrk="0" hangingPunct="1"><a:spcBef><a:spcPct val="20000"/></a:spcBef><a:buFont typeface="Arial"/><a:buChar char="•"/><a:defRPr sz="1500" kern="1200"><a:solidFill><a:schemeClr val="tx1"/></a:solidFill><a:latin typeface="+mn-lt"/><a:ea typeface="+mn-ea"/><a:cs typeface="+mn-cs"/></a:defRPr></a:lvl9pPr></p:bodyStyle><p:otherStyle><a:defPPr><a:defRPr lang="en-US"/></a:defPPr><a:lvl1pPr marL="0" algn="l" defTabSz="342900" rtl="0" eaLnBrk="1" latinLnBrk="0" hangingPunct="1"><a:defRPr sz="1350" kern="1200"><a:solidFill><a:schemeClr val="tx1"/></a:solidFill><a:latin typeface="+mn-lt"/><a:ea typeface="+mn-ea"/><a:cs typeface="+mn-cs"/></a:defRPr></a:lvl1pPr><a:lvl2pPr marL="342900" algn="l" defTabSz="342900" rtl="0" eaLnBrk="1" latinLnBrk="0" hangingPunct="1"><a:defRPr sz="1350" kern="1200"><a:solidFill><a:schemeClr val="tx1"/></a:solidFill><a:latin typeface="+mn-lt"/><a:ea typeface="+mn-ea"/><a:cs typeface="+mn-cs"/></a:defRPr></a:lvl2pPr><a:lvl3pPr marL="685800" algn="l" defTabSz="342900" rtl="0" eaLnBrk="1" latinLnBrk="0" hangingPunct="1"><a:defRPr sz="1350" kern="1200"><a:solidFill><a:schemeClr val="tx1"/></a:solidFill><a:latin typeface="+mn-lt"/><a:ea typeface="+mn-ea"/><a:cs typeface="+mn-cs"/></a:defRPr></a:lvl3pPr><a:lvl4pPr marL="1028700" algn="l" defTabSz="342900" rtl="0" eaLnBrk="1" latinLnBrk="0" hangingPunct="1"><a:defRPr sz="1350" kern="1200"><a:solidFill><a:schemeClr val="tx1"/></a:solidFill><a:latin typeface="+mn-lt"/><a:ea typeface="+mn-ea"/><a:cs typeface="+mn-cs"/></a:defRPr></a:lvl4pPr><a:lvl5pPr marL="1371600" algn="l" defTabSz="342900" rtl="0" eaLnBrk="1" latinLnBrk="0" hangingPunct="1"><a:defRPr sz="1350" kern="1200"><a:solidFill><a:schemeClr val="tx1"/></a:solidFill><a:latin typeface="+mn-lt"/><a:ea typeface="+mn-ea"/><a:cs typeface="+mn-cs"/></a:defRPr></a:lvl5pPr><a:lvl6pPr marL="1714500" algn="l" defTabSz="342900" rtl="0" eaLnBrk="1" latinLnBrk="0" hangingPunct="1"><a:defRPr sz="1350" kern="1200"><a:solidFill><a:schemeClr val="tx1"/></a:solidFill><a:latin typeface="+mn-lt"/><a:ea typeface="+mn-ea"/><a:cs typeface="+mn-cs"/></a:defRPr></a:lvl6pPr><a:lvl7pPr marL="2057400" algn="l" defTabSz="342900" rtl="0" eaLnBrk="1" latinLnBrk="0" hangingPunct="1"><a:defRPr sz="1350" kern="1200"><a:solidFill><a:schemeClr val="tx1"/></a:solidFill><a:latin typeface="+mn-lt"/><a:ea typeface="+mn-ea"/><a:cs typeface="+mn-cs"/></a:defRPr></a:lvl7pPr><a:lvl8pPr marL="2400300" algn="l" defTabSz="342900" rtl="0" eaLnBrk="1" latinLnBrk="0" hangingPunct="1"><a:defRPr sz="1350" kern="1200"><a:solidFill><a:schemeClr val="tx1"/></a:solidFill><a:latin typeface="+mn-lt"/><a:ea typeface="+mn-ea"/><a:cs typeface="+mn-cs"/></a:defRPr></a:lvl8pPr><a:lvl9pPr marL="2743200" algn="l" defTabSz="342900" rtl="0" eaLnBrk="1" latinLnBrk="0" hangingPunct="1"><a:defRPr sz="1350" kern="1200"><a:solidFill><a:schemeClr val="tx1"/></a:solidFill><a:latin typeface="+mn-lt"/><a:ea typeface="+mn-ea"/><a:cs typeface="+mn-cs"/></a:defRPr></a:lvl9pPr></p:otherStyle></p:txStyles></p:sldMaster>
diff --git a/data/pptx/ppt/slides/_rels/slide1.xml.rels b/data/pptx/ppt/slides/_rels/slide1.xml.rels
--- a/data/pptx/ppt/slides/_rels/slide1.xml.rels
+++ b/data/pptx/ppt/slides/_rels/slide1.xml.rels
@@ -1,2 +1,2 @@
 <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
-<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/slideLayout" Target="../slideLayouts/slideLayout1.xml"/></Relationships>
+<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/notesSlide" Target="../notesSlides/notesSlide1.xml"/><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/slideLayout" Target="../slideLayouts/slideLayout1.xml"/></Relationships>
diff --git a/data/pptx/ppt/slides/_rels/slide2.xml.rels b/data/pptx/ppt/slides/_rels/slide2.xml.rels
--- a/data/pptx/ppt/slides/_rels/slide2.xml.rels
+++ b/data/pptx/ppt/slides/_rels/slide2.xml.rels
@@ -1,2 +1,2 @@
 <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
-<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/slideLayout" Target="../slideLayouts/slideLayout2.xml"/></Relationships>
+<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/notesSlide" Target="../notesSlides/notesSlide2.xml"/><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/slideLayout" Target="../slideLayouts/slideLayout2.xml"/></Relationships>
diff --git a/data/pptx/ppt/slides/_rels/slide3.xml.rels b/data/pptx/ppt/slides/_rels/slide3.xml.rels
new file mode 100644
--- /dev/null
+++ b/data/pptx/ppt/slides/_rels/slide3.xml.rels
@@ -0,0 +1,2 @@
+<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
+<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/slideLayout" Target="../slideLayouts/slideLayout3.xml"/></Relationships>
diff --git a/data/pptx/ppt/slides/_rels/slide4.xml.rels b/data/pptx/ppt/slides/_rels/slide4.xml.rels
new file mode 100644
--- /dev/null
+++ b/data/pptx/ppt/slides/_rels/slide4.xml.rels
@@ -0,0 +1,2 @@
+<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
+<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/slideLayout" Target="../slideLayouts/slideLayout4.xml"/></Relationships>
diff --git a/data/pptx/ppt/slides/slide1.xml b/data/pptx/ppt/slides/slide1.xml
--- a/data/pptx/ppt/slides/slide1.xml
+++ b/data/pptx/ppt/slides/slide1.xml
@@ -1,2 +1,2 @@
 <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
-<p:sld xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main"><p:cSld><p:spTree><p:nvGrpSpPr><p:cNvPr id="1" name=""/><p:cNvGrpSpPr/><p:nvPr/></p:nvGrpSpPr><p:grpSpPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="0" cy="0"/><a:chOff x="0" y="0"/><a:chExt cx="0" cy="0"/></a:xfrm></p:grpSpPr><p:sp><p:nvSpPr><p:cNvPr id="2" name="Title 1"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="ctrTitle"/></p:nvPr></p:nvSpPr><p:spPr/><p:txBody><a:bodyPr/><a:lstStyle/><a:p><a:r><a:rPr lang="en-US" dirty="0" smtClean="0"/><a:t>Title</a:t></a:r><a:endParaRPr lang="en-US" dirty="0"/></a:p></p:txBody></p:sp><p:sp><p:nvSpPr><p:cNvPr id="3" name="Subtitle 2"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="subTitle" idx="1"/></p:nvPr></p:nvSpPr><p:spPr/><p:txBody><a:bodyPr/><a:lstStyle/><a:p><a:r><a:rPr lang="en-US" dirty="0" smtClean="0"/><a:t>Subtitle</a:t></a:r><a:endParaRPr lang="en-US" dirty="0"/></a:p></p:txBody></p:sp></p:spTree><p:extLst><p:ext uri="{BB962C8B-B14F-4D97-AF65-F5344CB8AC3E}"><p14:creationId xmlns:p14="http://schemas.microsoft.com/office/powerpoint/2010/main" val="392669009"/></p:ext></p:extLst></p:cSld><p:clrMapOvr><a:masterClrMapping/></p:clrMapOvr></p:sld>
+<p:sld xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main"><p:cSld><p:spTree><p:nvGrpSpPr><p:cNvPr id="1" name=""/><p:cNvGrpSpPr/><p:nvPr/></p:nvGrpSpPr><p:grpSpPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="0" cy="0"/><a:chOff x="0" y="0"/><a:chExt cx="0" cy="0"/></a:xfrm></p:grpSpPr><p:sp><p:nvSpPr><p:cNvPr id="2" name="Title 1"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="ctrTitle"/></p:nvPr></p:nvSpPr><p:spPr/><p:txBody><a:bodyPr/><a:lstStyle/><a:p><a:r><a:rPr lang="en-US" dirty="0"/><a:t>Presentation Title</a:t></a:r></a:p></p:txBody></p:sp><p:sp><p:nvSpPr><p:cNvPr id="3" name="Subtitle 2"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="subTitle" idx="1"/></p:nvPr></p:nvSpPr><p:spPr/><p:txBody><a:bodyPr/><a:lstStyle/><a:p><a:r><a:rPr lang="en-US" dirty="0"/><a:t>Presentation Subtitle</a:t></a:r></a:p></p:txBody></p:sp></p:spTree><p:extLst><p:ext uri="{BB962C8B-B14F-4D97-AF65-F5344CB8AC3E}"><p14:creationId xmlns:p14="http://schemas.microsoft.com/office/powerpoint/2010/main" val="392669009"/></p:ext></p:extLst></p:cSld><p:clrMapOvr><a:masterClrMapping/></p:clrMapOvr></p:sld>
diff --git a/data/pptx/ppt/slides/slide2.xml b/data/pptx/ppt/slides/slide2.xml
--- a/data/pptx/ppt/slides/slide2.xml
+++ b/data/pptx/ppt/slides/slide2.xml
@@ -1,2 +1,2 @@
 <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
-<p:sld xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main"><p:cSld><p:spTree><p:nvGrpSpPr><p:cNvPr id="1" name=""/><p:cNvGrpSpPr/><p:nvPr/></p:nvGrpSpPr><p:grpSpPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="0" cy="0"/><a:chOff x="0" y="0"/><a:chExt cx="0" cy="0"/></a:xfrm></p:grpSpPr><p:sp><p:nvSpPr><p:cNvPr id="2" name="Title 1"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="title"/></p:nvPr></p:nvSpPr><p:spPr/><p:txBody><a:bodyPr/><a:lstStyle/><a:p><a:r><a:rPr lang="en-US" dirty="0" smtClean="0"/><a:t>Slide Title</a:t></a:r><a:endParaRPr lang="en-US" dirty="0"/></a:p></p:txBody></p:sp><p:sp><p:nvSpPr><p:cNvPr id="3" name="Content Placeholder 2"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph idx="1"/></p:nvPr></p:nvSpPr><p:spPr/><p:txBody><a:bodyPr/><a:lstStyle/><a:p><a:pPr marL="0" indent="0"><a:buNone/></a:pPr><a:r><a:rPr lang="en-US" dirty="0" smtClean="0"/><a:t>Hello</a:t></a:r><a:r><a:rPr lang="en-US" smtClean="0"/><a:t>, world.</a:t></a:r><a:endParaRPr lang="en-US"/></a:p></p:txBody></p:sp></p:spTree><p:extLst><p:ext uri="{BB962C8B-B14F-4D97-AF65-F5344CB8AC3E}"><p14:creationId xmlns:p14="http://schemas.microsoft.com/office/powerpoint/2010/main" val="572707455"/></p:ext></p:extLst></p:cSld><p:clrMapOvr><a:masterClrMapping/></p:clrMapOvr></p:sld>
+<p:sld xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main"><p:cSld><p:spTree><p:nvGrpSpPr><p:cNvPr id="1" name=""/><p:cNvGrpSpPr/><p:nvPr/></p:nvGrpSpPr><p:grpSpPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="0" cy="0"/><a:chOff x="0" y="0"/><a:chExt cx="0" cy="0"/></a:xfrm></p:grpSpPr><p:sp><p:nvSpPr><p:cNvPr id="2" name="Title 1"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="title"/></p:nvPr></p:nvSpPr><p:spPr/><p:txBody><a:bodyPr/><a:lstStyle/><a:p><a:r><a:rPr lang="en-US" dirty="0"/><a:t>Slide Title</a:t></a:r></a:p></p:txBody></p:sp><p:sp><p:nvSpPr><p:cNvPr id="3" name="Content Placeholder 2"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph idx="1"/></p:nvPr></p:nvSpPr><p:spPr/><p:txBody><a:bodyPr/><a:lstStyle/><a:p><a:pPr marL="0" indent="0"><a:buNone/></a:pPr><a:r><a:rPr lang="en-US" dirty="0"/><a:t>Hello</a:t></a:r><a:r><a:rPr lang="en-US"/><a:t>, world.</a:t></a:r></a:p></p:txBody></p:sp></p:spTree><p:extLst><p:ext uri="{BB962C8B-B14F-4D97-AF65-F5344CB8AC3E}"><p14:creationId xmlns:p14="http://schemas.microsoft.com/office/powerpoint/2010/main" val="572707455"/></p:ext></p:extLst></p:cSld><p:clrMapOvr><a:masterClrMapping/></p:clrMapOvr></p:sld>
diff --git a/data/pptx/ppt/slides/slide3.xml b/data/pptx/ppt/slides/slide3.xml
new file mode 100644
--- /dev/null
+++ b/data/pptx/ppt/slides/slide3.xml
@@ -0,0 +1,2 @@
+<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
+<p:sld xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main"><p:cSld><p:spTree><p:nvGrpSpPr><p:cNvPr id="1" name=""/><p:cNvGrpSpPr/><p:nvPr/></p:nvGrpSpPr><p:grpSpPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="0" cy="0"/><a:chOff x="0" y="0"/><a:chExt cx="0" cy="0"/></a:xfrm></p:grpSpPr><p:sp><p:nvSpPr><p:cNvPr id="2" name="Title 1"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="title"/></p:nvPr></p:nvSpPr><p:spPr/><p:txBody><a:bodyPr/><a:lstStyle/><a:p><a:r><a:rPr lang="en-US" dirty="0"/><a:t>Section header</a:t></a:r></a:p></p:txBody></p:sp><p:sp><p:nvSpPr><p:cNvPr id="3" name="Text Placeholder 2"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="body" idx="1"/></p:nvPr></p:nvSpPr><p:spPr/></p:sp></p:spTree><p:extLst><p:ext uri="{BB962C8B-B14F-4D97-AF65-F5344CB8AC3E}"><p14:creationId xmlns:p14="http://schemas.microsoft.com/office/powerpoint/2010/main" val="3996781534"/></p:ext></p:extLst></p:cSld><p:clrMapOvr><a:masterClrMapping/></p:clrMapOvr></p:sld>
diff --git a/data/pptx/ppt/slides/slide4.xml b/data/pptx/ppt/slides/slide4.xml
new file mode 100644
--- /dev/null
+++ b/data/pptx/ppt/slides/slide4.xml
@@ -0,0 +1,2 @@
+<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
+<p:sld xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main"><p:cSld><p:spTree><p:nvGrpSpPr><p:cNvPr id="1" name=""/><p:cNvGrpSpPr/><p:nvPr/></p:nvGrpSpPr><p:grpSpPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="0" cy="0"/><a:chOff x="0" y="0"/><a:chExt cx="0" cy="0"/></a:xfrm></p:grpSpPr><p:sp><p:nvSpPr><p:cNvPr id="4" name="Title 3"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="title"/></p:nvPr></p:nvSpPr><p:spPr/><p:txBody><a:bodyPr/><a:lstStyle/><a:p><a:r><a:rPr lang="en-US" dirty="0"/><a:t>Slide Title for Two-Content</a:t></a:r></a:p></p:txBody></p:sp><p:sp><p:nvSpPr><p:cNvPr id="5" name="Content Placeholder 4"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph sz="half" idx="1"/></p:nvPr></p:nvSpPr><p:spPr/><p:txBody><a:bodyPr/><a:lstStyle/><a:p><a:r><a:rPr lang="en-US" dirty="0"/><a:t>Some content on </a:t></a:r><a:r><a:rPr lang="en-US"/><a:t>the left.</a:t></a:r><a:endParaRPr lang="en-US" dirty="0"/></a:p><a:p><a:pPr marL="0" indent="0"><a:buNone/></a:pPr><a:endParaRPr lang="en-US" dirty="0"/></a:p></p:txBody></p:sp><p:sp><p:nvSpPr><p:cNvPr id="6" name="Content Placeholder 5"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph sz="half" idx="2"/></p:nvPr></p:nvSpPr><p:spPr/><p:txBody><a:bodyPr/><a:lstStyle/><a:p><a:r><a:rPr lang="en-US" dirty="0"/><a:t>Some content on the right.</a:t></a:r></a:p></p:txBody></p:sp></p:spTree><p:extLst><p:ext uri="{BB962C8B-B14F-4D97-AF65-F5344CB8AC3E}"><p14:creationId xmlns:p14="http://schemas.microsoft.com/office/powerpoint/2010/main" val="1324621109"/></p:ext></p:extLst></p:cSld><p:clrMapOvr><a:masterClrMapping/></p:clrMapOvr></p:sld>
diff --git a/data/pptx/ppt/theme/theme2.xml b/data/pptx/ppt/theme/theme2.xml
new file mode 100644
--- /dev/null
+++ b/data/pptx/ppt/theme/theme2.xml
@@ -0,0 +1,2 @@
+<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
+<a:theme xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" name="Office Theme"><a:themeElements><a:clrScheme name="Office"><a:dk1><a:sysClr val="windowText" lastClr="000000"/></a:dk1><a:lt1><a:sysClr val="window" lastClr="FFFFFF"/></a:lt1><a:dk2><a:srgbClr val="44546A"/></a:dk2><a:lt2><a:srgbClr val="E7E6E6"/></a:lt2><a:accent1><a:srgbClr val="5B9BD5"/></a:accent1><a:accent2><a:srgbClr val="ED7D31"/></a:accent2><a:accent3><a:srgbClr val="A5A5A5"/></a:accent3><a:accent4><a:srgbClr val="FFC000"/></a:accent4><a:accent5><a:srgbClr val="4472C4"/></a:accent5><a:accent6><a:srgbClr val="70AD47"/></a:accent6><a:hlink><a:srgbClr val="0563C1"/></a:hlink><a:folHlink><a:srgbClr val="954F72"/></a:folHlink></a:clrScheme><a:fontScheme name="Office"><a:majorFont><a:latin typeface="Calibri Light" panose="020F0302020204030204"/><a:ea typeface=""/><a:cs typeface=""/><a:font script="Jpan" typeface="ＭＳ Ｐゴシック"/><a:font script="Hang" typeface="맑은 고딕"/><a:font script="Hans" typeface="宋体"/><a:font script="Hant" typeface="新細明體"/><a:font script="Arab" typeface="Times New Roman"/><a:font script="Hebr" typeface="Times New Roman"/><a:font script="Thai" typeface="Angsana New"/><a:font script="Ethi" typeface="Nyala"/><a:font script="Beng" typeface="Vrinda"/><a:font script="Gujr" typeface="Shruti"/><a:font script="Khmr" typeface="MoolBoran"/><a:font script="Knda" typeface="Tunga"/><a:font script="Guru" typeface="Raavi"/><a:font script="Cans" typeface="Euphemia"/><a:font script="Cher" typeface="Plantagenet Cherokee"/><a:font script="Yiii" typeface="Microsoft Yi Baiti"/><a:font script="Tibt" typeface="Microsoft Himalaya"/><a:font script="Thaa" typeface="MV Boli"/><a:font script="Deva" typeface="Mangal"/><a:font script="Telu" typeface="Gautami"/><a:font script="Taml" typeface="Latha"/><a:font script="Syrc" typeface="Estrangelo Edessa"/><a:font script="Orya" typeface="Kalinga"/><a:font script="Mlym" typeface="Kartika"/><a:font script="Laoo" typeface="DokChampa"/><a:font script="Sinh" typeface="Iskoola Pota"/><a:font script="Mong" typeface="Mongolian Baiti"/><a:font script="Viet" typeface="Times New Roman"/><a:font script="Uigh" typeface="Microsoft Uighur"/><a:font script="Geor" typeface="Sylfaen"/></a:majorFont><a:minorFont><a:latin typeface="Calibri" panose="020F0502020204030204"/><a:ea typeface=""/><a:cs typeface=""/><a:font script="Jpan" typeface="ＭＳ Ｐゴシック"/><a:font script="Hang" typeface="맑은 고딕"/><a:font script="Hans" typeface="宋体"/><a:font script="Hant" typeface="新細明體"/><a:font script="Arab" typeface="Arial"/><a:font script="Hebr" typeface="Arial"/><a:font script="Thai" typeface="Cordia New"/><a:font script="Ethi" typeface="Nyala"/><a:font script="Beng" typeface="Vrinda"/><a:font script="Gujr" typeface="Shruti"/><a:font script="Khmr" typeface="DaunPenh"/><a:font script="Knda" typeface="Tunga"/><a:font script="Guru" typeface="Raavi"/><a:font script="Cans" typeface="Euphemia"/><a:font script="Cher" typeface="Plantagenet Cherokee"/><a:font script="Yiii" typeface="Microsoft Yi Baiti"/><a:font script="Tibt" typeface="Microsoft Himalaya"/><a:font script="Thaa" typeface="MV Boli"/><a:font script="Deva" typeface="Mangal"/><a:font script="Telu" typeface="Gautami"/><a:font script="Taml" typeface="Latha"/><a:font script="Syrc" typeface="Estrangelo Edessa"/><a:font script="Orya" typeface="Kalinga"/><a:font script="Mlym" typeface="Kartika"/><a:font script="Laoo" typeface="DokChampa"/><a:font script="Sinh" typeface="Iskoola Pota"/><a:font script="Mong" typeface="Mongolian Baiti"/><a:font script="Viet" typeface="Arial"/><a:font script="Uigh" typeface="Microsoft Uighur"/><a:font script="Geor" typeface="Sylfaen"/></a:minorFont></a:fontScheme><a:fmtScheme name="Office"><a:fillStyleLst><a:solidFill><a:schemeClr val="phClr"/></a:solidFill><a:gradFill rotWithShape="1"><a:gsLst><a:gs pos="0"><a:schemeClr val="phClr"><a:lumMod val="110000"/><a:satMod val="105000"/><a:tint val="67000"/></a:schemeClr></a:gs><a:gs pos="50000"><a:schemeClr val="phClr"><a:lumMod val="105000"/><a:satMod val="103000"/><a:tint val="73000"/></a:schemeClr></a:gs><a:gs pos="100000"><a:schemeClr val="phClr"><a:lumMod val="105000"/><a:satMod val="109000"/><a:tint val="81000"/></a:schemeClr></a:gs></a:gsLst><a:lin ang="5400000" scaled="0"/></a:gradFill><a:gradFill rotWithShape="1"><a:gsLst><a:gs pos="0"><a:schemeClr val="phClr"><a:satMod val="103000"/><a:lumMod val="102000"/><a:tint val="94000"/></a:schemeClr></a:gs><a:gs pos="50000"><a:schemeClr val="phClr"><a:satMod val="110000"/><a:lumMod val="100000"/><a:shade val="100000"/></a:schemeClr></a:gs><a:gs pos="100000"><a:schemeClr val="phClr"><a:lumMod val="99000"/><a:satMod val="120000"/><a:shade val="78000"/></a:schemeClr></a:gs></a:gsLst><a:lin ang="5400000" scaled="0"/></a:gradFill></a:fillStyleLst><a:lnStyleLst><a:ln w="6350" cap="flat" cmpd="sng" algn="ctr"><a:solidFill><a:schemeClr val="phClr"/></a:solidFill><a:prstDash val="solid"/><a:miter lim="800000"/></a:ln><a:ln w="12700" cap="flat" cmpd="sng" algn="ctr"><a:solidFill><a:schemeClr val="phClr"/></a:solidFill><a:prstDash val="solid"/><a:miter lim="800000"/></a:ln><a:ln w="19050" cap="flat" cmpd="sng" algn="ctr"><a:solidFill><a:schemeClr val="phClr"/></a:solidFill><a:prstDash val="solid"/><a:miter lim="800000"/></a:ln></a:lnStyleLst><a:effectStyleLst><a:effectStyle><a:effectLst/></a:effectStyle><a:effectStyle><a:effectLst/></a:effectStyle><a:effectStyle><a:effectLst><a:outerShdw blurRad="57150" dist="19050" dir="5400000" algn="ctr" rotWithShape="0"><a:srgbClr val="000000"><a:alpha val="63000"/></a:srgbClr></a:outerShdw></a:effectLst></a:effectStyle></a:effectStyleLst><a:bgFillStyleLst><a:solidFill><a:schemeClr val="phClr"/></a:solidFill><a:solidFill><a:schemeClr val="phClr"><a:tint val="95000"/><a:satMod val="170000"/></a:schemeClr></a:solidFill><a:gradFill rotWithShape="1"><a:gsLst><a:gs pos="0"><a:schemeClr val="phClr"><a:tint val="93000"/><a:satMod val="150000"/><a:shade val="98000"/><a:lumMod val="102000"/></a:schemeClr></a:gs><a:gs pos="50000"><a:schemeClr val="phClr"><a:tint val="98000"/><a:satMod val="130000"/><a:shade val="90000"/><a:lumMod val="103000"/></a:schemeClr></a:gs><a:gs pos="100000"><a:schemeClr val="phClr"><a:shade val="63000"/><a:satMod val="120000"/></a:schemeClr></a:gs></a:gsLst><a:lin ang="5400000" scaled="0"/></a:gradFill></a:bgFillStyleLst></a:fmtScheme></a:themeElements><a:objectDefaults/><a:extraClrSchemeLst/><a:extLst><a:ext uri="{05A4C25C-085E-4340-85A3-A5531E510DB2}"><thm15:themeFamily xmlns:thm15="http://schemas.microsoft.com/office/thememl/2012/main" name="Office Theme" id="{62F939B6-93AF-4DB8-9C6B-D6C7DFDC589F}" vid="{4A3C46E8-61CC-4603-A589-7422A47A8E4A}"/></a:ext></a:extLst></a:theme>
diff --git a/data/pptx/ppt/viewProps.xml b/data/pptx/ppt/viewProps.xml
--- a/data/pptx/ppt/viewProps.xml
+++ b/data/pptx/ppt/viewProps.xml
@@ -1,2 +1,2 @@
 <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
-<p:viewPr xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main"><p:normalViewPr><p:restoredLeft sz="15633" autoAdjust="0"/><p:restoredTop sz="94711" autoAdjust="0"/></p:normalViewPr><p:slideViewPr><p:cSldViewPr snapToGrid="0" snapToObjects="1"><p:cViewPr varScale="1"><p:scale><a:sx n="101" d="100"/><a:sy n="101" d="100"/></p:scale><p:origin x="-1112" y="-112"/></p:cViewPr><p:guideLst><p:guide orient="horz" pos="2160"/><p:guide pos="2880"/></p:guideLst></p:cSldViewPr></p:slideViewPr><p:outlineViewPr><p:cViewPr><p:scale><a:sx n="33" d="100"/><a:sy n="33" d="100"/></p:scale><p:origin x="0" y="0"/></p:cViewPr></p:outlineViewPr><p:notesTextViewPr><p:cViewPr><p:scale><a:sx n="100" d="100"/><a:sy n="100" d="100"/></p:scale><p:origin x="0" y="0"/></p:cViewPr></p:notesTextViewPr><p:gridSpacing cx="76200" cy="76200"/></p:viewPr>
+<p:viewPr xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main" lastView="sldThumbnailView"><p:normalViewPr><p:restoredLeft sz="15643" autoAdjust="0"/><p:restoredTop sz="94694" autoAdjust="0"/></p:normalViewPr><p:slideViewPr><p:cSldViewPr snapToGrid="0" snapToObjects="1"><p:cViewPr varScale="1"><p:scale><a:sx n="161" d="100"/><a:sy n="161" d="100"/></p:scale><p:origin x="560" y="200"/></p:cViewPr><p:guideLst><p:guide orient="horz" pos="1620"/><p:guide pos="2880"/></p:guideLst></p:cSldViewPr></p:slideViewPr><p:outlineViewPr><p:cViewPr><p:scale><a:sx n="33" d="100"/><a:sy n="33" d="100"/></p:scale><p:origin x="0" y="0"/></p:cViewPr></p:outlineViewPr><p:notesTextViewPr><p:cViewPr><p:scale><a:sx n="100" d="100"/><a:sy n="100" d="100"/></p:scale><p:origin x="0" y="0"/></p:cViewPr></p:notesTextViewPr><p:gridSpacing cx="76200" cy="76200"/></p:viewPr>
diff --git a/data/sample.lua b/data/sample.lua
deleted file mode 100644
--- a/data/sample.lua
+++ /dev/null
@@ -1,343 +0,0 @@
--- This is a sample custom writer for pandoc.  It produces output
--- that is very similar to that of pandoc's HTML writer.
--- There is one new feature: code blocks marked with class 'dot'
--- are piped through graphviz and images are included in the HTML
--- output using 'data:' URLs.
---
--- Invoke with: pandoc -t sample.lua
---
--- Note:  you need not have lua installed on your system to use this
--- custom writer.  However, if you do have lua installed, you can
--- use it to test changes to the script.  'lua sample.lua' will
--- produce informative error messages if your code contains
--- syntax errors.
-
--- Character escaping
-local function escape(s, in_attribute)
-  return s:gsub("[<>&\"']",
-    function(x)
-      if x == '<' then
-        return '&lt;'
-      elseif x == '>' then
-        return '&gt;'
-      elseif x == '&' then
-        return '&amp;'
-      elseif x == '"' then
-        return '&quot;'
-      elseif x == "'" then
-        return '&#39;'
-      else
-        return x
-      end
-    end)
-end
-
--- Helper function to convert an attributes table into
--- a string that can be put into HTML tags.
-local function attributes(attr)
-  local attr_table = {}
-  for x,y in pairs(attr) do
-    if y and y ~= "" then
-      table.insert(attr_table, ' ' .. x .. '="' .. escape(y,true) .. '"')
-    end
-  end
-  return table.concat(attr_table)
-end
-
--- Run cmd on a temporary file containing inp and return result.
-local function pipe(cmd, inp)
-  local tmp = os.tmpname()
-  local tmph = io.open(tmp, "w")
-  tmph:write(inp)
-  tmph:close()
-  local outh = io.popen(cmd .. " " .. tmp,"r")
-  local result = outh:read("*all")
-  outh:close()
-  os.remove(tmp)
-  return result
-end
-
--- Table to store footnotes, so they can be included at the end.
-local notes = {}
-
--- Blocksep is used to separate block elements.
-function Blocksep()
-  return "\n\n"
-end
-
--- This function is called once for the whole document. Parameters:
--- body is a string, metadata is a table, variables is a table.
--- This gives you a fragment.  You could use the metadata table to
--- fill variables in a custom lua template.  Or, pass `--template=...`
--- to pandoc, and pandoc will add do the template processing as
--- usual.
-function Doc(body, metadata, variables)
-  local buffer = {}
-  local function add(s)
-    table.insert(buffer, s)
-  end
-  add(body)
-  if #notes > 0 then
-    add('<ol class="footnotes">')
-    for _,note in pairs(notes) do
-      add(note)
-    end
-    add('</ol>')
-  end
-  return table.concat(buffer,'\n') .. '\n'
-end
-
--- The functions that follow render corresponding pandoc elements.
--- s is always a string, attr is always a table of attributes, and
--- items is always an array of strings (the items in a list).
--- Comments indicate the types of other variables.
-
-function Str(s)
-  return escape(s)
-end
-
-function Space()
-  return " "
-end
-
-function SoftBreak()
-  return "\n"
-end
-
-function LineBreak()
-  return "<br/>"
-end
-
-function Emph(s)
-  return "<em>" .. s .. "</em>"
-end
-
-function Strong(s)
-  return "<strong>" .. s .. "</strong>"
-end
-
-function Subscript(s)
-  return "<sub>" .. s .. "</sub>"
-end
-
-function Superscript(s)
-  return "<sup>" .. s .. "</sup>"
-end
-
-function SmallCaps(s)
-  return '<span style="font-variant: small-caps;">' .. s .. '</span>'
-end
-
-function Strikeout(s)
-  return '<del>' .. s .. '</del>'
-end
-
-function Link(s, src, tit, attr)
-  return "<a href='" .. escape(src,true) .. "' title='" ..
-         escape(tit,true) .. "'>" .. s .. "</a>"
-end
-
-function Image(s, src, tit, attr)
-  return "<img src='" .. escape(src,true) .. "' title='" ..
-         escape(tit,true) .. "'/>"
-end
-
-function Code(s, attr)
-  return "<code" .. attributes(attr) .. ">" .. escape(s) .. "</code>"
-end
-
-function InlineMath(s)
-  return "\\(" .. escape(s) .. "\\)"
-end
-
-function DisplayMath(s)
-  return "\\[" .. escape(s) .. "\\]"
-end
-
-function Note(s)
-  local num = #notes + 1
-  -- insert the back reference right before the final closing tag.
-  s = string.gsub(s,
-          '(.*)</', '%1 <a href="#fnref' .. num ..  '">&#8617;</a></')
-  -- add a list item with the note to the note table.
-  table.insert(notes, '<li id="fn' .. num .. '">' .. s .. '</li>')
-  -- return the footnote reference, linked to the note.
-  return '<a id="fnref' .. num .. '" href="#fn' .. num ..
-            '"><sup>' .. num .. '</sup></a>'
-end
-
-function Span(s, attr)
-  return "<span" .. attributes(attr) .. ">" .. s .. "</span>"
-end
-
-function RawInline(format, str)
-  if format == "html" then
-    return str
-  else
-    return ''
-  end
-end
-
-function Cite(s, cs)
-  local ids = {}
-  for _,cit in ipairs(cs) do
-    table.insert(ids, cit.citationId)
-  end
-  return "<span class=\"cite\" data-citation-ids=\"" .. table.concat(ids, ",") ..
-    "\">" .. s .. "</span>"
-end
-
-function Plain(s)
-  return s
-end
-
-function Para(s)
-  return "<p>" .. s .. "</p>"
-end
-
--- lev is an integer, the header level.
-function Header(lev, s, attr)
-  return "<h" .. lev .. attributes(attr) ..  ">" .. s .. "</h" .. lev .. ">"
-end
-
-function BlockQuote(s)
-  return "<blockquote>\n" .. s .. "\n</blockquote>"
-end
-
-function HorizontalRule()
-  return "<hr/>"
-end
-
-function LineBlock(ls)
-  return '<div style="white-space: pre-line;">' .. table.concat(ls, '\n') ..
-         '</div>'
-end
-
-function CodeBlock(s, attr)
-  -- If code block has class 'dot', pipe the contents through dot
-  -- and base64, and include the base64-encoded png as a data: URL.
-  if attr.class and string.match(' ' .. attr.class .. ' ',' dot ') then
-    local png = pipe("base64", pipe("dot -Tpng", s))
-    return '<img src="data:image/png;base64,' .. png .. '"/>'
-  -- otherwise treat as code (one could pipe through a highlighter)
-  else
-    return "<pre><code" .. attributes(attr) .. ">" .. escape(s) ..
-           "</code></pre>"
-  end
-end
-
-function BulletList(items)
-  local buffer = {}
-  for _, item in pairs(items) do
-    table.insert(buffer, "<li>" .. item .. "</li>")
-  end
-  return "<ul>\n" .. table.concat(buffer, "\n") .. "\n</ul>"
-end
-
-function OrderedList(items)
-  local buffer = {}
-  for _, item in pairs(items) do
-    table.insert(buffer, "<li>" .. item .. "</li>")
-  end
-  return "<ol>\n" .. table.concat(buffer, "\n") .. "\n</ol>"
-end
-
-function DefinitionList(items)
-  local buffer = {}
-  for _,item in pairs(items) do
-    local k, v = next(item)
-    table.insert(buffer, "<dt>" .. k .. "</dt>\n<dd>" ..
-                   table.concat(v, "</dd>\n<dd>") .. "</dd>")
-  end
-  return "<dl>\n" .. table.concat(buffer, "\n") .. "\n</dl>"
-end
-
--- Convert pandoc alignment to something HTML can use.
--- align is AlignLeft, AlignRight, AlignCenter, or AlignDefault.
-function html_align(align)
-  if align == 'AlignLeft' then
-    return 'left'
-  elseif align == 'AlignRight' then
-    return 'right'
-  elseif align == 'AlignCenter' then
-    return 'center'
-  else
-    return 'left'
-  end
-end
-
-function CaptionedImage(src, tit, caption, attr)
-   return '<div class="figure">\n<img src="' .. escape(src,true) ..
-      '" title="' .. escape(tit,true) .. '"/>\n' ..
-      '<p class="caption">' .. caption .. '</p>\n</div>'
-end
-
--- Caption is a string, aligns is an array of strings,
--- widths is an array of floats, headers is an array of
--- strings, rows is an array of arrays of strings.
-function Table(caption, aligns, widths, headers, rows)
-  local buffer = {}
-  local function add(s)
-    table.insert(buffer, s)
-  end
-  add("<table>")
-  if caption ~= "" then
-    add("<caption>" .. caption .. "</caption>")
-  end
-  if widths and widths[1] ~= 0 then
-    for _, w in pairs(widths) do
-      add('<col width="' .. string.format("%.0f%%", w * 100) .. '" />')
-    end
-  end
-  local header_row = {}
-  local empty_header = true
-  for i, h in pairs(headers) do
-    local align = html_align(aligns[i])
-    table.insert(header_row,'<th align="' .. align .. '">' .. h .. '</th>')
-    empty_header = empty_header and h == ""
-  end
-  if empty_header then
-    head = ""
-  else
-    add('<tr class="header">')
-    for _,h in pairs(header_row) do
-      add(h)
-    end
-    add('</tr>')
-  end
-  local class = "even"
-  for _, row in pairs(rows) do
-    class = (class == "even" and "odd") or "even"
-    add('<tr class="' .. class .. '">')
-    for i,c in pairs(row) do
-      add('<td align="' .. html_align(aligns[i]) .. '">' .. c .. '</td>')
-    end
-    add('</tr>')
-  end
-  add('</table')
-  return table.concat(buffer,'\n')
-end
-
-function RawBlock(format, str)
-  if format == "html" then
-    return str
-  else
-    return ''
-  end
-end
-
-function Div(s, attr)
-  return "<div" .. attributes(attr) .. ">\n" .. s .. "</div>"
-end
-
--- The following code will produce runtime warnings when you haven't defined
--- all of the functions you need for the custom writer, so it's useful
--- to include when you're working on a writer.
-local meta = {}
-meta.__index =
-  function(_, key)
-    io.stderr:write(string.format("WARNING: Undefined function '%s'\n",key))
-    return function() return "" end
-  end
-setmetatable(_G, meta)
-
diff --git a/data/templates/affiliations.jats b/data/templates/affiliations.jats
new file mode 100644
--- /dev/null
+++ b/data/templates/affiliations.jats
@@ -0,0 +1,36 @@
+$--
+$-- Affiliations
+$--
+<aff id="aff-$it.id$">
+$-- wrap affiliation if it has a known institution identifier
+$if(it.group)$
+<institution content-type="group">${it.group}</institution>
+$endif$
+$if(it.department)$
+<institution content-type="dept">${it.department}</institution>
+$endif$
+<institution-wrap>
+$if(it.organization)$
+<institution>${it.organization}</institution>
+$else$
+<institution>${it.name}</institution>
+$endif$
+$if(it.isni)$
+<institution-id institution-id-type="ISNI">${it.isni}</institution-id>
+$endif$
+$if(it.ringgold)$
+<institution-id institution-id-type="Ringgold">${it.ringgold}</institution-id>
+$endif$
+$if(it.ror)$
+<institution-id institution-id-type="ROR">${it.ror}</institution-id>
+$endif$
+$for(it.pid)$
+<institution-id institution-id-type="${it.type}">${it.id}</institution-id>
+$endfor$
+</institution-wrap>$if(it.street-address)$,
+$for(it.street-address)$
+<addr-line>${it}</addr-line>$sep$,
+$endfor$
+$else$$if(it.city)$, <city>$it.city$</city>$endif$$endif$$if(it.country)$,
+<country$if(it.country-code)$ country="$it.country-code$"$endif$>$it.country$</country>$endif$
+</aff>
diff --git a/data/templates/after-header-includes.latex b/data/templates/after-header-includes.latex
new file mode 100644
--- /dev/null
+++ b/data/templates/after-header-includes.latex
@@ -0,0 +1,10 @@
+\usepackage{bookmark}
+\IfFileExists{xurl.sty}{\usepackage{xurl}}{} % add URL line breaks if available
+\urlstyle{$if(urlstyle)$$urlstyle$$else$same$endif$}
+$if(links-as-notes)$
+% Make links footnotes instead of hotlinks:
+\DeclareRobustCommand{\href}[2]{#2\footnote{\url{#1}}}
+$endif$
+$if(verbatim-in-note)$
+\VerbatimFootnotes % allow verbatim text in footnotes
+$endif$
diff --git a/data/templates/article.jats_publishing b/data/templates/article.jats_publishing
new file mode 100644
--- /dev/null
+++ b/data/templates/article.jats_publishing
@@ -0,0 +1,252 @@
+$if(article.type)$
+<article xmlns:mml="http://www.w3.org/1998/Math/MathML" xmlns:xlink="http://www.w3.org/1999/xlink" dtd-version="1.2" article-type="$article.type$">
+$else$
+<article xmlns:mml="http://www.w3.org/1998/Math/MathML" xmlns:xlink="http://www.w3.org/1999/xlink" dtd-version="1.2" article-type="other">
+$endif$
+<front>
+<journal-meta>
+$if(journal.publisher-id)$
+<journal-id journal-id-type="publisher-id">$journal.publisher-id$</journal-id>
+$endif$
+$if(journal.nlm-ta)$
+<journal-id journal-id-type="nlm-ta">$journal.nlm-ta$</journal-id>
+$endif$
+$if(journal.pmc)$
+<journal-id journal-id-type="pmc">$journal.pmc$</journal-id>
+$endif$
+$-- Fallback: an empty journal-id in case none is available.
+$if(journal.publisher-id)$
+$elseif(journal.nlm-ta)$
+$elseif(journal.pmc)$
+$else$
+<journal-id></journal-id>
+$endif$
+<journal-title-group>
+$if(journal.title)$
+<journal-title>$journal.title$</journal-title>
+$endif$
+$if(journal.abbrev-title)$
+<abbrev-journal-title>$journal.abbrev-title$</abbrev-journal-title>
+$endif$
+</journal-title-group>
+$if(journal.pissn)$
+<issn publication-format="print">$journal.pissn$</issn>
+$endif$
+$if(journal.eissn)$
+<issn publication-format="electronic">$journal.eissn$</issn>
+$endif$
+$-- At least one issn element is required; use empty issn as fallback
+$if(journal.pissn)$
+$elseif(journal.eissn)$
+$else$
+<issn></issn>
+$endif$
+<publisher>
+<publisher-name>$journal.publisher-name$</publisher-name>
+$if(journal.publisher-loc)$
+<publisher-loc>$journal.publisher-loc$</publisher-loc>
+$endif$
+</publisher>
+</journal-meta>
+<article-meta>
+$if(article.publisher-id)$
+<article-id pub-id-type="publisher-id">$article.publisher-id$</article-id>
+$endif$
+$if(article.doi)$
+<article-id pub-id-type="doi">$article.doi$</article-id>
+$endif$
+$if(article.pmid)$
+<article-id pub-id-type="pmid">$article.pmid$</article-id>
+$endif$
+$if(article.pmcid)$
+<article-id pub-id-type="pmcid">$article.pmcid$</article-id>
+$endif$
+$if(article.art-access-id)$
+<article-id pub-id-type="art-access-id">$article.art-access-id$</article-id>
+$endif$
+$if(article.heading)$
+<article-categories>
+<subj-group subj-group-type="heading">
+<subject>$article.heading$</subject>
+</subj-group>
+$if(article.categories)$
+<subj-group subj-group-type="categories">
+$for(article.categories)$
+<subject>$article.categories$</subject>
+$endfor$
+</subj-group>
+$endif$
+</article-categories>
+$endif$
+$if(title)$
+<title-group>
+<article-title>$title$</article-title>
+$if(subtitle)$
+<subtitle>${subtitle}</subtitle>
+$endif$
+</title-group>
+$endif$
+$if(author)$
+<contrib-group>
+$for(author)$
+<contrib contrib-type="author"$if(author.equal-contrib)$ equal-contrib="yes"$endif$$if(author.cor-id)$ corresp="yes"$endif$>
+$if(author.orcid)$
+<contrib-id contrib-id-type="orcid">$author.orcid$</contrib-id>
+$endif$
+$if(author.surname)$
+<name>
+<surname>$if(author.non-dropping-particle)$${author.non-dropping-particle} $endif$$author.surname$</surname>
+<given-names>$author.given-names$$if(author.dropping-particle)$ ${author.dropping-particle}$endif$</given-names>
+$if(author.prefix)$
+<prefix>${author.prefix}</prefix>
+$endif$
+$if(author.suffix)$
+<suffix>${author.suffix}</suffix>
+$endif$
+</name>
+$elseif(author.name)$
+<string-name>$author.name$</string-name>
+$else$
+<string-name>$author$</string-name>
+$endif$
+$for(author.roles)$
+$if(it.credit)$
+<role vocab="credit"$if(it.degree)$ degree-contribution="$it.degree$"$endif$
+      vocab-identifier="https://credit.niso.org/"
+      vocab-term-identifier="https://credit.niso.org/contributor-roles/$it.credit$/"
+      vocab-term="$it.credit-name$"
+>$if(it.name)$$it.name$$else$$it.credit-name$$endif$</role>
+$elseif(it.name)$
+<role>$it.name$</role>
+$endif$
+$endfor$
+$if(author.email)$
+<email>$author.email$</email>
+$endif$
+$-- if affiliations are listed separately, then create links. Otherwise
+$-- include them here.
+$if(affiliation)$
+$for(author.affiliation)$
+<xref ref-type="aff" rid="aff-$author.affiliation$"/>
+$endfor$
+$else$
+$for(author.affiliation)$
+${ it:affiliations.jats() }
+$endfor$
+$endif$
+$if(author.cor-id)$
+<xref ref-type="corresp" rid="cor-$author.cor-id$"><sup>*</sup></xref>
+$endif$
+</contrib>
+$endfor$
+$for(affiliation)$
+${ it:affiliations.jats() }
+$endfor$
+</contrib-group>
+$endif$
+$if(article.author-notes)$
+<author-notes>
+$if(article.author-notes.corresp)$
+$for(article.author-notes.corresp)$
+<corresp id="cor-$article.author-notes.corresp.id$">* E-mail: <email>$article.author-notes.corresp.email$</email></corresp>
+$endfor$
+$endif$
+$if(article.author-notes.conflict)$
+<fn fn-type="conflict"><p>$article.author-notes.conflict$</p></fn>
+$endif$
+$if(article.author-notes.con)$
+<fn fn-type="con"><p>$article.author-notes.con$</p></fn>
+$endif$
+</author-notes>
+$endif$
+$if(date)$
+<pub-date date-type="$if(date.type)$$date.type$$else$pub$endif$" publication-format="electronic"$if(date.iso-8601)$ iso-8601-date="$date.iso-8601$"$endif$>
+$if(date.day)$
+<day>$date.day$</day>
+$endif$
+$if(date.month)$
+<month>$date.month$</month>
+$endif$
+<year>$date.year$</year>
+</pub-date>
+$endif$
+$if(article.volume)$
+<volume>$article.volume$</volume>
+$endif$
+$if(article.issue)$
+<issue>$article.issue$</issue>
+$endif$
+$if(article.fpage)$
+<fpage>$article.fpage$</fpage>
+$endif$
+$if(article.lpage)$
+<lpage>$article.lpage$</lpage>
+$endif$
+$if(article.elocation-id)$
+<elocation-id>$article.elocation-id$</elocation-id>
+$endif$
+$if(history)$
+<history>
+</history>
+$endif$
+<permissions>
+$for(copyright.statement)$
+<copyright-statement>$copyright.statement$</copyright-statement>
+$endfor$
+$for(copyright.year)$
+<copyright-year>$copyright.year$</copyright-year>
+$endfor$
+$for(copyright.holder)$
+<copyright-holder>$copyright.holder$</copyright-holder>
+$endfor$
+$if(copyright.text)$
+<license license-type="$copyright.type$" xlink:href="$copyright.link$">
+<license-p>$copyright.text$</license-p>
+</license>
+$endif$
+$for(license)$
+<license$if(it.type)$ license-type="${it.type}"$endif$>
+$if(it.link)$
+<ali:license_ref xmlns:ali="http://www.niso.org/schemas/ali/1.0/">${it.link}</ali:license_ref>
+$endif$
+<license-p>$if(it.text)$${it.text}$else$${it}$endif$</license-p>
+</license>
+$endfor$
+</permissions>
+$if(abstract)$
+<abstract>
+$abstract$
+</abstract>
+$endif$
+$if(tags)$
+<kwd-group kwd-group-type="author">
+$for(tags)$
+<kwd>$tags$</kwd>
+$endfor$
+</kwd-group>
+$endif$
+$if(article.funding-statement)$
+<funding-group>
+<funding-statement>$article.funding-statement$</funding-statement>
+</funding-group>
+$endif$
+</article-meta>
+$if(notes)$
+<notes>$notes$</notes>
+$endif$
+</front>
+<body>
+$body$
+</body>
+<back>
+$if(back)$
+$back$
+$endif$
+</back>
+$if(floats-group)$
+<floats-group>
+$floats-group$
+</floats-group>
+$endif$
+</article>
+
diff --git a/data/templates/common.latex b/data/templates/common.latex
new file mode 100644
--- /dev/null
+++ b/data/templates/common.latex
@@ -0,0 +1,263 @@
+$if(linestretch)$
+\usepackage{setspace}
+$endif$
+$--
+$-- paragraph formatting
+$--
+$if(indent)$
+$else$
+\makeatletter
+\@ifundefined{KOMAClassName}{% if non-KOMA class
+  \IfFileExists{parskip.sty}{%
+    \usepackage{parskip}
+  }{% else
+    \setlength{\parindent}{0pt}
+    \setlength{\parskip}{6pt plus 2pt minus 1pt}}
+}{% if KOMA class
+  \KOMAoptions{parskip=half}}
+\makeatother
+$endif$
+$if(beamer)$
+$else$
+$if(block-headings)$
+% Make \paragraph and \subparagraph free-standing
+\makeatletter
+\ifx\paragraph\undefined\else
+  \let\oldparagraph\paragraph
+  \renewcommand{\paragraph}{
+    \@ifstar
+      \xxxParagraphStar
+      \xxxParagraphNoStar
+  }
+  \newcommand{\xxxParagraphStar}[1]{\oldparagraph*{#1}\mbox{}}
+  \newcommand{\xxxParagraphNoStar}[1]{\oldparagraph{#1}\mbox{}}
+\fi
+\ifx\subparagraph\undefined\else
+  \let\oldsubparagraph\subparagraph
+  \renewcommand{\subparagraph}{
+    \@ifstar
+      \xxxSubParagraphStar
+      \xxxSubParagraphNoStar
+  }
+  \newcommand{\xxxSubParagraphStar}[1]{\oldsubparagraph*{#1}\mbox{}}
+  \newcommand{\xxxSubParagraphNoStar}[1]{\oldsubparagraph{#1}\mbox{}}
+\fi
+\makeatother
+$endif$
+$endif$
+$--
+$-- verbatim in notes
+$--
+$if(verbatim-in-note)$
+\usepackage{fancyvrb}
+$endif$
+$-- highlighting
+$if(listings)$
+\usepackage{listings}
+\newcommand{\passthrough}[1]{#1}
+\lstset{defaultdialect=[5.3]Lua}
+\lstset{defaultdialect=[x86masm]Assembler}
+$endif$
+$if(lhs)$
+\lstnewenvironment{code}{\lstset{language=Haskell,basicstyle=\small\ttfamily}}{}
+$endif$
+$if(highlighting-macros)$
+$highlighting-macros$
+$endif$
+$--
+$-- tables
+$--
+$if(tables)$
+\usepackage{longtable,booktabs,array}
+\newcounter{none} % for unnumbered tables
+$if(multirow)$
+\usepackage{multirow}
+$endif$
+\usepackage{calc} % for calculating minipage widths
+$if(beamer)$
+\usepackage{caption}
+% Make caption package work with longtable
+\makeatletter
+\def\fnum@table{\tablename~\thetable}
+\makeatother
+$else$
+% Correct order of tables after \paragraph or \subparagraph
+\usepackage{etoolbox}
+\makeatletter
+\patchcmd\longtable{\par}{\if@noskipsec\mbox{}\fi\par}{}{}
+\makeatother
+% Allow footnotes in longtable head/foot
+\IfFileExists{footnotehyper.sty}{\usepackage{footnotehyper}}{\usepackage{footnote}}
+\makesavenoteenv{longtable}
+$endif$
+$endif$
+$--
+$-- graphics
+$--
+$if(graphics)$
+\usepackage{graphicx}
+\makeatletter
+\newsavebox\pandoc@box
+\newcommand*\pandocbounded[1]{% scales image to fit in text height/width
+  \sbox\pandoc@box{#1}%
+  \Gscale@div\@tempa{\textheight}{\dimexpr\ht\pandoc@box+\dp\pandoc@box\relax}%
+  \Gscale@div\@tempb{\linewidth}{\wd\pandoc@box}%
+  \ifdim\@tempb\p@<\@tempa\p@\let\@tempa\@tempb\fi% select the smaller of both
+  \ifdim\@tempa\p@<\p@\scalebox{\@tempa}{\usebox\pandoc@box}%
+  \else\usebox{\pandoc@box}%
+  \fi%
+}
+% Set default figure placement to htbp
+\def\fps@figure{htbp}
+\makeatother
+$endif$
+$if(svg)$
+\usepackage{svg}
+$endif$
+$--
+$-- strikeout/underline
+$--
+$if(strikeout)$
+\ifLuaTeX
+  \usepackage{luacolor}
+  \usepackage[soul]{lua-ul}
+\else
+  \usepackage{soul}
+$if(beamer)$
+  \makeatletter
+  \let\HL\hl
+  \renewcommand\hl{% fix for beamer highlighting
+    \let\set@color\beamerorig@set@color
+    \let\reset@color\beamerorig@reset@color
+    \HL}
+  \makeatother
+$endif$
+$if(CJKmainfont)$
+  \ifXeTeX
+    % soul's \st doesn't work for CJK:
+    \usepackage{xeCJKfntef}
+    \renewcommand{\st}[1]{\sout{#1}}
+  \fi
+$endif$
+\fi
+$endif$
+$--
+$-- CSL citations
+$--
+$if(csl-refs)$
+% definitions for citeproc citations
+\NewDocumentCommand\citeproctext{}{}
+\NewDocumentCommand\citeproc{mm}{%
+  \begingroup\def\citeproctext{#2}\cite{#1}\endgroup}
+\makeatletter
+ % allow citations to break across lines
+ \let\@cite@ofmt\@firstofone
+ % avoid brackets around text for \cite:
+ \def\@biblabel#1{}
+ \def\@cite#1#2{{#1\if@tempswa , #2\fi}}
+\makeatother
+\newlength{\cslhangindent}
+\setlength{\cslhangindent}{1.5em}
+\newlength{\csllabelwidth}
+\setlength{\csllabelwidth}{3em}
+\newenvironment{CSLReferences}[2] % #1 hanging-indent, #2 entry-spacing
+ {\begin{list}{}{%
+  \setlength{\itemindent}{0pt}
+  \setlength{\leftmargin}{0pt}
+  \setlength{\parsep}{0pt}
+  % turn on hanging indent if param 1 is 1
+  \ifodd #1
+   \setlength{\leftmargin}{\cslhangindent}
+   \setlength{\itemindent}{-1\cslhangindent}
+  \fi
+  % set entry spacing
+  \setlength{\itemsep}{#2\baselineskip}}}
+ {\end{list}}
+\usepackage{calc}
+\newcommand{\CSLBlock}[1]{\hfill\break\parbox[t]{\linewidth}{\strut\ignorespaces#1\strut}}
+\newcommand{\CSLLeftMargin}[1]{\parbox[t]{\csllabelwidth}{\strut#1\strut}}
+\newcommand{\CSLRightInline}[1]{\parbox[t]{\linewidth - \csllabelwidth}{\strut#1\strut}}
+\newcommand{\CSLIndent}[1]{\hspace{\cslhangindent}#1}
+$endif$
+$--
+$-- Babel language support
+$--
+$if(lang)$
+\ifLuaTeX
+\usepackage[bidi=basic$if(shorthands)$$else$,shorthands=off$endif$$for(babeloptions)$,$babeloptions$$endfor$]{babel}
+\else
+\usepackage[bidi=default$if(shorthands)$$else$,shorthands=off$endif$$for(babeloptions)$,$babeloptions$$endfor$]{babel}
+\fi
+$if(babel-lang)$
+$if(mainfont)$
+\ifPDFTeX
+\else
+\babelfont{rm}[$for(mainfontoptions)$$mainfontoptions$$sep$,$endfor$$if(mainfontfallback)$,RawFeature={fallback=mainfontfallback}$endif$]{$mainfont$}
+\fi
+$endif$
+$endif$
+$for(babelfonts/pairs)$
+\babelfont[$babelfonts.key$]{rm}{$babelfonts.value$}
+$endfor$
+\ifLuaTeX
+  \usepackage{selnolig} % disable illegal ligatures
+\fi
+$endif$
+$--
+$-- pagestyle
+$--
+$if(pagestyle)$
+\pagestyle{$pagestyle$}
+$endif$
+$--
+$-- prevent overfull lines
+$--
+\setlength{\emergencystretch}{3em} % prevent overfull lines
+$--
+$-- tight lists
+$--
+\providecommand{\tightlist}{%
+  \setlength{\itemsep}{0pt}\setlength{\parskip}{0pt}}
+$--
+$-- subfigure support
+$--
+$if(subfigure)$
+\usepackage{subcaption}
+$endif$
+$--
+$-- text direction support for pdftex
+$--
+$if(dir)$
+\ifPDFTeX
+  \TeXXeTstate=1
+  \newcommand{\RL}[1]{\beginR #1\endR}
+  \newcommand{\LR}[1]{\beginL #1\endL}
+  \newenvironment{RTL}{\beginR}{\endR}
+  \newenvironment{LTR}{\beginL}{\endL}
+\fi
+\ifluatex
+  \newcommand{\RL}[1]{\bgroup\textdir TRT#1\egroup}
+  \newcommand{\LR}[1]{\bgroup\textdir TLT#1\egroup}
+  \newenvironment{RTL}{\textdir TRT\pardir TRT\bodydir TRT}{}
+  \newenvironment{LTR}{\textdir TLT\pardir TLT\bodydir TLT}{}
+\fi
+$endif$
+$--
+$-- bibliography support support for natbib and biblatex
+$--
+$if(natbib)$
+\usepackage[$natbiboptions$]{natbib}
+\bibliographystyle{$if(biblio-style)$$biblio-style$$else$plainnat$endif$}
+$endif$
+$if(biblatex)$
+\usepackage[$if(biblio-style)$style=$biblio-style$,$endif$$for(biblatexoptions)$$biblatexoptions$$sep$,$endfor$]{biblatex}
+$for(bibliography)$
+\addbibresource{$bibliography$}
+$endfor$
+$endif$
+$--
+$-- csquotes
+$--
+$if(csquotes)$
+\usepackage[$for(csquotesoptions)$$csquotesoptions$$sep$,$endfor$]{csquotes}
+$endif$
diff --git a/data/templates/default.ansi b/data/templates/default.ansi
new file mode 100644
--- /dev/null
+++ b/data/templates/default.ansi
@@ -0,0 +1,21 @@
+$if(titleblock)$
+$titleblock$
+
+$endif$
+$for(header-includes)$
+$header-includes$
+
+$endfor$
+$for(include-before)$
+$include-before$
+
+$endfor$
+$if(toc)$
+$table-of-contents$
+
+$endif$
+$body$
+$for(include-after)$
+
+$include-after$
+$endfor$
diff --git a/data/templates/default.asciidoc b/data/templates/default.asciidoc
--- a/data/templates/default.asciidoc
+++ b/data/templates/default.asciidoc
@@ -1,16 +1,24 @@
 $if(titleblock)$
-$title$
+= $title$
 $if(author)$
 $for(author)$$author$$sep$; $endfor$
-$endif$
 $if(date)$
 $date$
 $endif$
+$elseif(date)$
+:revdate: $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$
diff --git a/data/templates/default.bbcode b/data/templates/default.bbcode
new file mode 100644
--- /dev/null
+++ b/data/templates/default.bbcode
@@ -0,0 +1,1 @@
+$body$
diff --git a/data/templates/default.beamer b/data/templates/default.beamer
new file mode 100644
--- /dev/null
+++ b/data/templates/default.beamer
@@ -0,0 +1,204 @@
+$passoptions.latex()$
+\documentclass[
+$if(fontsize)$
+  $fontsize$,
+$endif$
+  ignorenonframetext,
+$if(handout)$
+  handout,
+$endif$
+$if(aspectratio)$
+  aspectratio=$aspectratio$,
+$endif$
+$if(babel-lang)$
+  $babel-lang$,
+$endif$
+$for(classoption)$
+  $classoption$$sep$,
+$endfor$
+]{$documentclass$}
+$if(geometry)$
+\geometry{$for(geometry)$$geometry$$sep$,$endfor$}
+$endif$
+\newif\ifbibliography
+$if(background-image)$
+\usebackgroundtemplate{%
+  \includegraphics[width=\paperwidth]{$background-image$}%
+}
+% In beamer background-image does not work well when other images are used, so this is the workaround
+\pgfdeclareimage[width=\paperwidth,height=\paperheight]{background}{$background-image$}
+\usebackgroundtemplate{\pgfuseimage{background}}
+$endif$
+\usepackage{pgfpages}
+\setbeamertemplate{caption}[numbered]
+\setbeamertemplate{caption label separator}{: }
+\setbeamercolor{caption name}{fg=normal text.fg}
+\beamertemplatenavigationsymbols$if(navigation)$$navigation$$else$empty$endif$
+$--
+$-- section numbering
+$--
+$if(numbersections)$
+$else$
+% remove section numbering
+\setbeamertemplate{part page}{
+  \centering
+  \begin{beamercolorbox}[sep=16pt,center]{part title}
+    \usebeamerfont{part title}\insertpart\par
+  \end{beamercolorbox}
+}
+\setbeamertemplate{section page}{
+  \centering
+  \begin{beamercolorbox}[sep=12pt,center]{section title}
+    \usebeamerfont{section title}\insertsection\par
+  \end{beamercolorbox}
+}
+\setbeamertemplate{subsection page}{
+  \centering
+  \begin{beamercolorbox}[sep=8pt,center]{subsection title}
+    \usebeamerfont{subsection title}\insertsubsection\par
+  \end{beamercolorbox}
+}
+$endif$
+$for(beameroption)$
+\setbeameroption{$beameroption$}
+$endfor$
+% Prevent slide breaks in the middle of a paragraph
+\widowpenalties 1 10000
+\raggedbottom
+$if(section-titles)$
+\AtBeginPart{
+  \frame{\partpage}
+}
+\AtBeginSection{
+  \ifbibliography
+  \else
+    \frame{\sectionpage}
+  \fi
+}
+\AtBeginSubsection{
+  \frame{\subsectionpage}
+}
+$endif$
+$fonts.latex()$
+$-- Set Beamer theme before user font settings so they can override theme
+$if(theme)$
+\usetheme[$for(themeoptions)$$themeoptions$$sep$,$endfor$]{$theme$}
+$endif$
+$if(colortheme)$
+\usecolortheme[$for(colorthemeoptions)$$colorthemeoptions$$sep$,$endfor$]{$colortheme$}
+$endif$
+$if(fonttheme)$
+\usefonttheme[$for(fontthemeoptions)$$fontthemeoptions$$sep$,$endfor$]{$fonttheme$}
+$endif$
+$if(mainfont)$
+\usefonttheme{serif} % use mainfont rather than sansfont for slide text
+$endif$
+$if(innertheme)$
+\useinnertheme[$for(innerthemeoptions)$$innerthemeoptions$$sep$,$endfor$]{$innertheme$}
+$endif$
+$if(outertheme)$
+\useoutertheme[$for(outerthemeoptions)$$outerthemeoptions$$sep$,$endfor$]{$outertheme$}
+$endif$
+$font-settings.latex()$
+$common.latex()$
+$for(header-includes)$
+$header-includes$
+$endfor$
+$after-header-includes.latex()$
+$hypersetup.latex()$
+
+$if(title)$
+\title$if(shorttitle)$[$shorttitle$]$endif${\texorpdfstring{$title$}{$title-meta$}$if(thanks)$\thanks{$thanks$}$endif$}
+$endif$
+$if(subtitle)$
+\subtitle$if(shortsubtitle)$[$shortsubtitle$]$endif${\texorpdfstring{$subtitle$}{$subtitle-meta$}}
+$endif$
+\author$if(shortauthor)$[$shortauthor$]$endif${\texorpdfstring{$for(author)$$author$$sep$ \and $endfor$}{$author-meta$}}
+\date$if(shortdate)$[$shortdate$]$endif${$date$}
+$if(institute)$
+\institute$if(shortinstitute)$[$shortinstitute$]$endif${$for(institute)$$institute$$sep$ \and $endfor$}
+$endif$
+$if(titlegraphic)$
+\titlegraphic{
+$for(titlegraphic)$
+  \includegraphics$if(titlegraphicoptions)$[$for(titlegraphicoptions)$$titlegraphicoptions$$sep$, $endfor$]$endif${$titlegraphic$}$sep$\enspace
+$endfor$}
+$endif$
+$if(logo)$
+\logo{\includegraphics$if(logooptions)$[$for(logooptions)$$logooptions$$sep$, $endfor$]$endif${$logo$}}
+$endif$
+
+\begin{document}
+$if(title)$
+\frame{\titlepage}
+$if(abstract)$
+\begin{abstract}
+$abstract$
+\end{abstract}
+$endif$
+$endif$
+
+$for(include-before)$
+$include-before$
+
+$endfor$
+$if(toc)$
+$if(toc-title)$
+\renewcommand*\contentsname{$toc-title$}
+$endif$
+\begin{frame}[allowframebreaks]
+$if(toc-title)$
+  \frametitle{$toc-title$}
+$endif$
+  \setcounter{tocdepth}{$toc-depth$}
+  \tableofcontents
+\end{frame}
+\setcounter{tocdepth}{$toc-depth$}
+\tableofcontents
+}
+$endif$
+$if(lof)$
+\listoffigures
+$endif$
+$if(lot)$
+\listoftables
+$endif$
+$if(linestretch)$
+\setstretch{$linestretch$}
+$endif$
+$body$
+
+$if(natbib)$
+$if(bibliography)$
+$if(biblio-title)$
+$if(has-chapters)$
+\renewcommand\bibname{$biblio-title$}
+$else$
+\renewcommand\refname{$biblio-title$}
+$endif$
+$endif$
+\begin{frame}[allowframebreaks]{$biblio-title$}
+$if(nocite-ids)$
+  \nocite{$for(nocite-ids)$$it$$sep$, $endfor$}
+$endif$
+  \bibliographytrue
+  \bibliography{$for(bibliography)$$bibliography$$sep$,$endfor$}
+\end{frame}
+
+$endif$
+$endif$
+$if(biblatex)$
+\begin{frame}[allowframebreaks]{$biblio-title$}
+$if(nocite-ids)$
+  \nocite{$for(nocite-ids)$$it$$sep$, $endfor$}
+$endif$
+  \bibliographytrue
+  \printbibliography[heading=none]
+\end{frame}
+
+$endif$
+$for(include-after)$
+$include-after$
+
+$endfor$
+\end{document}
diff --git a/data/templates/default.biblatex b/data/templates/default.biblatex
new file mode 100644
--- /dev/null
+++ b/data/templates/default.biblatex
@@ -0,0 +1,10 @@
+$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.bibtex b/data/templates/default.bibtex
new file mode 100644
--- /dev/null
+++ b/data/templates/default.bibtex
@@ -0,0 +1,10 @@
+$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.chunkedhtml b/data/templates/default.chunkedhtml
new file mode 100644
--- /dev/null
+++ b/data/templates/default.chunkedhtml
@@ -0,0 +1,103 @@
+<!DOCTYPE html>
+<html xmlns="http://www.w3.org/1999/xhtml" lang="$lang$" xml:lang="$lang$"$if(dir)$ dir="$dir$"$endif$>
+<head>
+  <meta charset="utf-8" />
+  <meta name="generator" content="pandoc" />
+  <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes" />
+$for(author-meta)$
+  <meta name="author" content="$author-meta$" />
+$endfor$
+$if(date-meta)$
+  <meta name="dcterms.date" content="$date-meta$" />
+$endif$
+$if(keywords)$
+  <meta name="keywords" content="$for(keywords)$$keywords$$sep$, $endfor$" />
+$endif$
+$if(description-meta)$
+  <meta name="description" content="$description-meta$" />
+$endif$
+  <title>$if(title-prefix)$$title-prefix$ – $endif$$pagetitle$</title>
+  <style>
+    div.sitenav { display: flex; flex-direction: row; flex-wrap: wrap; }
+    span.navlink { flex: 1; }
+    span.navlink-label { display: inline-block; min-width: 4em; }
+    $styles.html()$
+  </style>
+$for(css)$
+  <link rel="stylesheet" href="$css$" />
+$endfor$
+$for(header-includes)$
+  $header-includes$
+$endfor$
+$if(math)$
+  $math$
+$endif$
+</head>
+<body>
+$for(include-before)$
+$include-before$
+$endfor$
+<nav id="sitenav">
+<div class="sitenav">
+<span class="navlink">
+$if(up.url)$
+<span class="navlink-label">Up:</span> <a href="$up.url$" accesskey="u" rel="up">$up.title$</a>
+$endif$
+</span>
+<span class="navlink">
+$if(top)$
+<span class="navlink-label">Top:</span> <a href="$top.url$" accesskey="t" rel="top">$top.title$</a>
+$endif$
+</span>
+</div>
+<div class="sitenav">
+<span class="navlink">
+$if(next.url)$
+<span class="navlink-label">Next:</span> <a href="$next.url$" accesskey="n" rel="next">$next.title$</a>
+$endif$
+</span>
+<span class="navlink">
+$if(previous.url)$
+<span class="navlink-label">Previous:</span> <a href="$previous.url$" accesskey="p" rel="previous">$previous.title$</a>
+$endif$
+</span>
+</div>
+</nav>
+$if(top)$
+$-- only print title block if this is NOT the top page
+$else$
+$if(title)$
+<header id="title-block-header">
+<h1 class="title">$title$</h1>
+$if(subtitle)$
+<p class="subtitle">$subtitle$</p>
+$endif$
+$for(author)$
+<p class="author">$author$</p>
+$endfor$
+$if(date)$
+<p class="date">$date$</p>
+$endif$
+$if(abstract)$
+<div class="abstract">
+<div class="abstract-title">$abstract-title$</div>
+$abstract$
+</div>
+$endif$
+$endif$
+</header>
+$endif$
+$if(toc)$
+<nav id="$idprefix$TOC" role="doc-toc">
+$if(toc-title)$
+<h2 id="$idprefix$toc-title">$toc-title$</h2>
+$endif$
+$table-of-contents$
+</nav>
+$endif$
+$body$
+$for(include-after)$
+$include-after$
+$endfor$
+</body>
+</html>
diff --git a/data/templates/default.context b/data/templates/default.context
--- a/data/templates/default.context
+++ b/data/templates/default.context
@@ -1,3 +1,8 @@
+$if(tagging)$
+\setupbackend[format=pdf/ua-2]
+\enabledirectives[backend.usetags=mkiv]
+\setuptagging[state=start]
+$endif$
 $if(context-lang)$
 \mainlanguage[$context-lang$]
 $endif$
@@ -23,11 +28,11 @@
   style=$linkstyle$,
   color=$linkcolor$,
   contrastcolor=$linkcontrastcolor$]
+\setupurl[style=$urlstyle$]
 
 % make chapter, section bookmarks visible when opening document
 \placebookmarks[chapter, section, subsection, subsubsection, subsubsubsection, subsubsubsubsection][chapter, section]
-\setupinteractionscreen[option=bookmark]
-\setuptagging[state=start]
+\setupinteractionscreen[option={bookmark,title}]
 
 $if(papersize)$
 \setuppapersize[$for(papersize)$$papersize$$sep$,$endfor$]
@@ -37,21 +42,42 @@
 $endif$
 $if(pagenumbering)$
 \setuppagenumbering[$for(pagenumbering)$$pagenumbering$$sep$,$endfor$]
+$else$
+\setuppagenumbering[location={footer,middle}]
 $endif$
+$if(pdfa)$
+% attempt to generate PDF/A
+\setupbackend
+  [format=PDF/A-$pdfa$,
+   profile={$if(pdfaiccprofile)$$for(pdfaiccprofile)$$pdfaiccprofile$$sep$,$endfor$$else$sRGB.icc$endif$},
+   intent=$if(pdfaintent)$$pdfaintent$$else$sRGB IEC61966-2.1$endif$]
+$endif$
+\setupstructure[state=start,method=auto]
 
 % use microtypography
 \definefontfeature[default][default][script=latn, protrusion=quality, expansion=quality, itlc=yes, textitalics=yes, onum=yes, pnum=yes]
+\definefontfeature[default:tnum][default][tnum=yes, pnum=no]
 \definefontfeature[smallcaps][script=latn, protrusion=quality, expansion=quality, smcp=yes, onum=yes, pnum=yes]
 \setupalign[hz,hanging]
 \setupitaliccorrection[global, always]
 
 \setupbodyfontenvironment[default][em=italic] % use italic as em, not slanted
 
-\definefallbackfamily[mainface][rm][DejaVu Serif][preset=range:greek, force=yes]
-\definefontfamily[mainface][rm][$if(mainfont)$$mainfont$$else$Latin Modern Roman$endif$]
-\definefontfamily[mainface][mm][$if(mathfont)$$mathfont$$else$Latin Modern Math$endif$]
-\definefontfamily[mainface][ss][$if(sansfont)$$sansfont$$else$Latin Modern Sans$endif$]
-\definefontfamily[mainface][tt][$if(monofont)$$monofont$$else$Latin Modern Typewriter$endif$][features=none]
+$-- set up font fallbacks
+$for(mainfontfallback)$
+\definefallbackfamily[mainface][rm][$mainfontfallback/nowrap$][range=0x0000-0xFFFF, check=yes, force=no]
+$endfor$
+$for(sansfontfallback)$
+\definefallbackfamily[mainface][ss][$sansfontfallback/nowrap$][range=0x0000-0xFFFF, check=yes, force=no]
+$endfor$
+$for(monofontfallback)$
+\definefallbackfamily[mainface][tt][$monofontfallback/nowrap$][range=0x0000-0xFFFF, check=yes, force=no]
+$endfor$
+\definefallbackfamily[mainface][rm][CMU Serif][preset=range:greek, force=yes]
+\definefontfamily[mainface][rm][$if(mainfont)$$mainfont/nowrap$$else$Latin Modern Roman$endif$]
+\definefontfamily[mainface][mm][$if(mathfont)$$mathfont/nowrap$$else$Latin Modern Math$endif$]
+\definefontfamily[mainface][ss][$if(sansfont)$$sansfont/nowrap$$else$Latin Modern Sans$endif$]
+\definefontfamily[mainface][tt][$if(monofont)$$monofont/nowrap$$else$Latin Modern Typewriter$endif$][features=none]
 \setupbodyfont[mainface$if(fontsize)$,$fontsize$$endif$]
 
 \setupwhitespace[$if(whitespace)$$whitespace$$else$medium$endif$]
@@ -62,13 +88,17 @@
 \setupinterlinespace[$for(interlinespace)$$interlinespace$$sep$,$endfor$]
 $endif$
 
-\setuphead[chapter]            [style=\tfd,header=empty]
-\setuphead[section]            [style=\tfc]
-\setuphead[subsection]         [style=\tfb]
+\setuphead[chapter]            [style=\tfd\setupinterlinespace,header=empty]
+\setuphead[section]            [style=\tfc\setupinterlinespace]
+\setuphead[subsection]         [style=\tfb\setupinterlinespace]
 \setuphead[subsubsection]      [style=\bf]
 \setuphead[subsubsubsection]   [style=\sc]
 \setuphead[subsubsubsubsection][style=\it]
 
+\definesectionlevels
+   [default]
+   [section, subsection, subsubsection, subsubsubsection, subsubsubsubsection]
+
 $if(headertext)$
 \setupheadertexts$for(headertext)$[$headertext$]$endfor$
 $endif$
@@ -87,11 +117,43 @@
 \setupitemize[autointro]    % prevent orphan list intro
 \setupitemize[indentnext=no]
 
+\defineitemgroup[enumerate]
+\setupenumerate[each][fit][itemalign=left,distance=.5em,style={\feature[+][default:tnum]}]
+
 \setupfloat[figure][default={here,nonumber}]
 \setupfloat[table][default={here,nonumber}]
 
-\setupthinrules[width=15em] % width of horizontal rules
+\setupxtable[frame=off]
+\setupxtable[head][topframe=on]
+\setupxtable[body][]
+\setupxtable[foot][]
+\setupxtable[lastrow][bottomframe=on]
 
+$if(emphasis-commands)$
+$emphasis-commands$
+$endif$
+$if(highlighting-commands)$
+$highlighting-commands$
+$endif$
+$if(csl-refs)$
+\definemeasure[cslhangindent][1.5em]
+\definenarrower[hangingreferences][left=\measure{cslhangindent}]
+\definestartstop [cslreferences] [
+	$if(csl-hanging-indent)$
+	before={%
+	  \starthangingreferences[left]
+      \setupindenting[-\leftskip,yes,first]
+      \doindentation
+  	},
+  	after=\stophangingreferences,
+	$endif$
+]
+$endif$
+$if(includesource)$
+$for(sourcefile)$
+\attachment[file=$curdir$/$sourcefile$,method=hidden]
+$endfor$
+$endif$
 $for(header-includes)$
 $header-includes$
 $endfor$
@@ -99,18 +161,18 @@
 \starttext
 $if(title)$
 \startalignment[middle]
-  {\tfd $title$}
+  {\tfd\setupinterlinespace $title$}
 $if(subtitle)$
   \smallskip
-  {\tfa $subtitle$}
+  {\tfa\setupinterlinespace $subtitle$}
 $endif$
 $if(author)$
   \smallskip
-  {\tfa $for(author)$$author$$sep$\crlf $endfor$}
+  {\tfa\setupinterlinespace $for(author)$$author$$sep$\crlf $endfor$}
 $endif$
 $if(date)$
   \smallskip
-  {\tfa $date$}
+  {\tfa\setupinterlinespace $date$}
 $endif$
   \bigskip
 \stopalignment
@@ -128,11 +190,11 @@
 $if(toc)$
 \completecontent
 $endif$
-$if(lot)$
-\completelistoftables
-$endif$
 $if(lof)$
 \completelistoffigures
+$endif$
+$if(lot)$
+\completelistoftables
 $endif$
 
 $body$
diff --git a/data/templates/default.djot b/data/templates/default.djot
new file mode 100644
--- /dev/null
+++ b/data/templates/default.djot
@@ -0,0 +1,27 @@
+$if(title)$
+# $title$
+
+$endif$
+$if(author)$
+$for(author)$
+$author$
+$endfor$
+
+$endif$
+$if(date)$
+$date$
+
+$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.docbook4 b/data/templates/default.docbook4
--- a/data/templates/default.docbook4
+++ b/data/templates/default.docbook4
@@ -23,10 +23,10 @@
 $endif$
   </articleinfo>
 $for(include-before)$
-$include-before$
+  $include-before$
 $endfor$
-$body$
+  $body$
 $for(include-after)$
-$include-after$
+  $include-after$
 $endfor$
 </article>
diff --git a/data/templates/default.docbook5 b/data/templates/default.docbook5
--- a/data/templates/default.docbook5
+++ b/data/templates/default.docbook5
@@ -28,10 +28,10 @@
 $endif$
   </info>
 $for(include-before)$
-$include-before$
+  $include-before$
 $endfor$
-$body$
+  $body$
 $for(include-after)$
-$include-after$
+  $include-after$
 $endfor$
 </article>
diff --git a/data/templates/default.dzslides b/data/templates/default.dzslides
--- a/data/templates/default.dzslides
+++ b/data/templates/default.dzslides
@@ -12,20 +12,9 @@
   <meta name="keywords" content="$for(keywords)$$keywords$$sep$, $endfor$">
 $endif$
   <title>$if(title-prefix)$$title-prefix$ – $endif$$pagetitle$</title>
-  <style type="text/css">
-      code{white-space: pre-wrap;}
-      span.smallcaps{font-variant: small-caps;}
-      span.underline{text-decoration: underline;}
-      div.column{display: inline-block; vertical-align: top; width: 50%;}
-$if(quotes)$
-      q { quotes: "“" "”" "‘" "’"; }
-$endif$
-  </style>
-$if(highlighting-css)$
-  <style type="text/css">
-$highlighting-css$
+  <style>
+    $styles.html()$
   </style>
-$endif$
 $if(css)$
 $for(css)$
   <link rel="stylesheet" href="$css$">
@@ -182,7 +171,7 @@
   <h1 class="subtitle">$subtitle$</h1>
 $endif$
   <footer>
-    $if(author)$<span class="author">$for(author)$$author$$sep$, $endfor$</span>$endif$ · $if(date)$<span class="date">$date$</span>$endif$
+    $if(author)$<span class="author">$for(author)$$author$$sep$, $endfor$</span> · $endif$$if(institute)$<span class="institute">$for(institute)$$institute$$sep$, $endfor$</span> · $endif$$if(date)$<span class="date">$date$</span>$endif$
   </footer>
 </section>
 $endif$
diff --git a/data/templates/default.epub2 b/data/templates/default.epub2
--- a/data/templates/default.epub2
+++ b/data/templates/default.epub2
@@ -1,25 +1,20 @@
 <?xml version="1.0" encoding="UTF-8"?>
 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
-<html xmlns="http://www.w3.org/1999/xhtml"$if(lang)$ xml:lang="$lang$"$endif$>
+<html xmlns="http://www.w3.org/1999/xhtml"$if(lang)$ lang="$lang$" xml:lang="$lang$"$endif$$if(dir)$ dir="$dir$"$endif$>
 <head>
   <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
   <meta http-equiv="Content-Style-Type" content="text/css" />
   <meta name="generator" content="pandoc" />
   <title>$pagetitle$</title>
   <style type="text/css">
-      code{white-space: pre-wrap;}
-      span.smallcaps{font-variant: small-caps;}
-      span.underline{text-decoration: underline;}
-      div.column{display: inline-block; vertical-align: top; width: 50%;}
-$if(quotes)$
-      q { quotes: "“" "”" "‘" "’"; }
+$if(csl-css)$
+    $styles.citations.html()$
 $endif$
-  </style>
 $if(highlighting-css)$
-  <style type="text/css">
-$highlighting-css$
-  </style>
+    /* CSS for syntax highlighting */
+    $highlighting-css$
 $endif$
+  </style>
 $for(css)$
   <link rel="stylesheet" type="text/css" href="$css$" />
 $endfor$
@@ -54,7 +49,20 @@
 $if(rights)$
   <div class="rights">$rights$</div>
 $endif$
+$if(abstract)$
+<div class="abstract">
+<div class="abstract-title">$abstract-title$</div>
+$abstract$
+</div>
+$endif$
 $else$
+$if(coverpage)$
+<div id="cover-image">
+<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" width="100%" height="100%" viewBox="0 0 $cover-image-width$ $cover-image-height$" preserveAspectRatio="xMidYMid">
+<image width="$cover-image-width$" height="$cover-image-height$" xlink:href="../media/$cover-image$" />
+</svg>
+</div>
+$else$
 $for(include-before)$
 $include-before$
 $endfor$
@@ -62,6 +70,7 @@
 $for(include-after)$
 $include-after$
 $endfor$
+$endif$
 $endif$
 </body>
 </html>
diff --git a/data/templates/default.epub3 b/data/templates/default.epub3
--- a/data/templates/default.epub3
+++ b/data/templates/default.epub3
@@ -1,24 +1,19 @@
 <?xml version="1.0" encoding="UTF-8"?>
 <!DOCTYPE html>
-<html xmlns="http://www.w3.org/1999/xhtml" xmlns:epub="http://www.idpf.org/2007/ops"$if(lang)$ xml:lang="$lang$"$endif$>
+<html xmlns="http://www.w3.org/1999/xhtml" xmlns:epub="http://www.idpf.org/2007/ops"$if(lang)$ lang="$lang$" xml:lang="$lang$"$endif$$if(dir)$ dir="$dir$"$endif$>
 <head>
   <meta charset="utf-8" />
   <meta name="generator" content="pandoc" />
   <title>$pagetitle$</title>
-  <style type="text/css">
-      code{white-space: pre-wrap;}
-      span.smallcaps{font-variant: small-caps;}
-      span.underline{text-decoration: underline;}
-      div.column{display: inline-block; vertical-align: top; width: 50%;}
-$if(quotes)$
-      q { quotes: "“" "”" "‘" "’"; }
+  <style>
+$if(csl-css)$
+    $styles.citations.html()$
 $endif$
-  </style>
 $if(highlighting-css)$
-  <style type="text/css">
-$highlighting-css$
-  </style>
+    /* CSS for syntax highlighting */
+    $highlighting-css$
 $endif$
+  </style>
 $for(css)$
   <link rel="stylesheet" type="text/css" href="$css$" />
 $endfor$
@@ -26,9 +21,9 @@
   $header-includes$
 $endfor$
 </head>
-<body$if(coverpage)$ id="cover"$endif$>
+<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>
@@ -54,8 +49,21 @@
 $if(rights)$
   <div class="rights">$rights$</div>
 $endif$
+$if(abstract)$
+<div class="abstract">
+<div class="abstract-title">$abstract-title$</div>
+$abstract$
+</div>
+$endif$
 </section>
 $else$
+$if(coverpage)$
+<div id="cover-image">
+<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" width="100%" height="100%" viewBox="0 0 $cover-image-width$ $cover-image-height$" preserveAspectRatio="xMidYMid">
+<image width="$cover-image-width$" height="$cover-image-height$" xlink:href="../media/$cover-image$" />
+</svg>
+</div>
+$else$
 $for(include-before)$
 $include-before$
 $endfor$
@@ -63,6 +71,7 @@
 $for(include-after)$
 $include-after$
 $endfor$
+$endif$
 $endif$
 </body>
 </html>
diff --git a/data/templates/default.html4 b/data/templates/default.html4
--- a/data/templates/default.html4
+++ b/data/templates/default.html4
@@ -3,7 +3,7 @@
 <head>
   <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
   <meta http-equiv="Content-Style-Type" content="text/css" />
-  <meta name="generator" content="pandoc" />
+  <meta name="generator" content="pandoc $pandoc-version$" />
 $for(author-meta)$
   <meta name="author" content="$author-meta$" />
 $endfor$
@@ -13,30 +13,22 @@
 $if(keywords)$
   <meta name="keywords" content="$for(keywords)$$keywords$$sep$, $endfor$" />
 $endif$
-  <title>$if(title-prefix)$$title-prefix$ – $endif$$pagetitle$</title>
-  <style type="text/css">
-      code{white-space: pre-wrap;}
-      span.smallcaps{font-variant: small-caps;}
-      span.underline{text-decoration: underline;}
-      div.column{display: inline-block; vertical-align: top; width: 50%;}
-$if(quotes)$
-      q { quotes: "“" "”" "‘" "’"; }
+$if(description-meta)$
+  <meta name="description" content="$description-meta$" />
 $endif$
-  </style>
-$if(highlighting-css)$
+  <title>$if(title-prefix)$$title-prefix$ – $endif$$pagetitle$</title>
   <style type="text/css">
-$highlighting-css$
+    $styles.html()$
   </style>
-$endif$
 $for(css)$
   <link rel="stylesheet" href="$css$" type="text/css" />
 $endfor$
-$if(math)$
-  $math$
-$endif$
 $for(header-includes)$
   $header-includes$
 $endfor$
+$if(math)$
+  $math$
+$endif$
 </head>
 <body>
 $for(include-before)$
@@ -54,10 +46,19 @@
 $if(date)$
 <h3 class="date">$date$</h3>
 $endif$
+$if(abstract)$
+<div class="abstract">
+<div class="abstract-title">$abstract-title$</div>
+$abstract$
 </div>
 $endif$
+</div>
+$endif$
 $if(toc)$
 <div id="$idprefix$TOC">
+$if(toc-title)$
+<h2 id="$idprefix$toc-title">$toc-title$</h2>
+$endif$
 $table-of-contents$
 </div>
 $endif$
diff --git a/data/templates/default.html5 b/data/templates/default.html5
--- a/data/templates/default.html5
+++ b/data/templates/default.html5
@@ -1,8 +1,8 @@
 <!DOCTYPE html>
-<html xmlns="http://www.w3.org/1999/xhtml" lang="$lang$" xml:lang="$lang$"$if(dir)$ dir="$dir$"$endif$>
+<html xmlns="http://www.w3.org/1999/xhtml"$if(lang)$ lang="$lang$" xml:lang="$lang$"$endif$$if(dir)$ dir="$dir$"$endif$>
 <head>
   <meta charset="utf-8" />
-  <meta name="generator" content="pandoc" />
+  <meta name="generator" content="pandoc $pandoc-version$" />
   <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes" />
 $for(author-meta)$
   <meta name="author" content="$author-meta$" />
@@ -13,40 +13,29 @@
 $if(keywords)$
   <meta name="keywords" content="$for(keywords)$$keywords$$sep$, $endfor$" />
 $endif$
-  <title>$if(title-prefix)$$title-prefix$ – $endif$$pagetitle$</title>
-  <style type="text/css">
-      code{white-space: pre-wrap;}
-      span.smallcaps{font-variant: small-caps;}
-      span.underline{text-decoration: underline;}
-      div.column{display: inline-block; vertical-align: top; width: 50%;}
-$if(quotes)$
-      q { quotes: "“" "”" "‘" "’"; }
+$if(description-meta)$
+  <meta name="description" content="$description-meta$" />
 $endif$
-  </style>
-$if(highlighting-css)$
-  <style type="text/css">
-$highlighting-css$
+  <title>$if(title-prefix)$$title-prefix$ – $endif$$pagetitle$</title>
+  <style>
+    $styles.html()$
   </style>
-$endif$
 $for(css)$
-  <link rel="stylesheet" href="$css$">
+  <link rel="stylesheet" href="$css$" />
 $endfor$
-$if(math)$
-  $math$
-$endif$
-  <!--[if lt IE 9]>
-    <script src="//cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.3/html5shiv-printshiv.min.js"></script>
-  <![endif]-->
 $for(header-includes)$
   $header-includes$
 $endfor$
+$if(math)$
+  $math$
+$endif$
 </head>
 <body>
 $for(include-before)$
 $include-before$
 $endfor$
 $if(title)$
-<header>
+<header id="title-block-header">
 <h1 class="title">$title$</h1>
 $if(subtitle)$
 <p class="subtitle">$subtitle$</p>
@@ -57,10 +46,19 @@
 $if(date)$
 <p class="date">$date$</p>
 $endif$
+$if(abstract)$
+<div class="abstract">
+<div class="abstract-title">$abstract-title$</div>
+$abstract$
+</div>
+$endif$
 </header>
 $endif$
 $if(toc)$
-<nav id="$idprefix$TOC">
+<nav id="$idprefix$TOC" role="doc-toc">
+$if(toc-title)$
+<h2 id="$idprefix$toc-title">$toc-title$</h2>
+$endif$
 $table-of-contents$
 </nav>
 $endif$
diff --git a/data/templates/default.icml b/data/templates/default.icml
--- a/data/templates/default.icml
+++ b/data/templates/default.icml
@@ -4,7 +4,7 @@
 <Document DOMVersion="8.0" Self="pandoc_doc">
     <RootCharacterStyleGroup Self="pandoc_character_styles">
       <CharacterStyle Self="$$ID/NormalCharacterStyle" Name="Default" />
-      $charStyles$ 
+      $charStyles$
     </RootCharacterStyleGroup>
     <RootParagraphStyleGroup Self="pandoc_paragraph_styles">
       <ParagraphStyle Self="$$ID/NormalParagraphStyle" Name="$$ID/NormalParagraphStyle"
@@ -20,7 +20,7 @@
           </TabList>
         </Properties>
       </ParagraphStyle>
-      $parStyles$ 
+      $parStyles$
     </RootParagraphStyleGroup>
     <RootTableStyleGroup Self="pandoc_table_styles">
       <TableStyle Self="TableStyle/Table" Name="Table" />
@@ -28,6 +28,11 @@
     <RootCellStyleGroup Self="pandoc_cell_styles">
       <CellStyle Self="CellStyle/Cell" AppliedParagraphStyle="ParagraphStyle/$$ID/[No paragraph style]" Name="Cell" />
     </RootCellStyleGroup>
+$if(objectStyles)$
+    <RootObjectStyleGroup Self="pandoc_object_styles">
+      $objectStyles$
+    </RootObjectStyleGroup>
+$endif$
   <Story Self="pandoc_story"
       TrackChanges="false"
       StoryTitle="$if(title-prefix)$$title-prefix$ – $endif$$pagetitle$"
diff --git a/data/templates/default.jats b/data/templates/default.jats
deleted file mode 100644
--- a/data/templates/default.jats
+++ /dev/null
@@ -1,203 +0,0 @@
-<?xml version="1.0" encoding="utf-8" ?>
-$if(xml-stylesheet)$
-<?xml-stylesheet type="text/xsl" href="$xml-stylesheet$"?>
-$endif$
-<!DOCTYPE article PUBLIC "-//NLM//DTD JATS (Z39.96) Journal Publishing DTD v1.0 20120330//EN"
-                  "JATS-journalpublishing1.dtd">
-$if(article.type)$
-<article xmlns:mml="http://www.w3.org/1998/Math/MathML" xmlns:xlink="http://www.w3.org/1999/xlink" dtd-version="1.0" article-type="$article.type$">
-$else$
-<article xmlns:mml="http://www.w3.org/1998/Math/MathML" xmlns:xlink="http://www.w3.org/1999/xlink" dtd-version="1.0" article-type="other">
-$endif$
-<front>
-<journal-meta>
-$if(journal.publisher-id)$
-<journal-id journal-id-type="publisher-id">$journal.publisher-id$</journal-id>
-$endif$
-$if(journal.nlm-ta)$
-<journal-id journal-id-type="nlm-ta">$journal.nlm-ta$</journal-id>
-$endif$
-$if(journal.pmc)$
-<journal-id journal-id-type="pmc">$journal.pmc$</journal-id>
-$endif$
-<journal-title-group>
-$if(journal.title)$
-<journal-title>$journal.title$</journal-title>
-$endif$
-$if(journal.abbrev-title)$
-<abbrev-journal-title>$journal.abbrev-title$</abbrev-journal-title>
-$endif$
-</journal-title-group>
-$if(journal.pissn)$
-<issn pub-type="ppub">$journal.pissn$</issn>
-$endif$
-$if(journal.eissn)$
-<issn pub-type="epub">$journal.eissn$</issn>
-$endif$
-<publisher>
-<publisher-name>$journal.publisher-name$</publisher-name>
-$if(journal.publisher-loc)$
-<publisher-loc>$journal.publisher-loc$</publisher-loc>
-$endif$
-</publisher>
-</journal-meta>
-<article-meta>
-$if(article.publisher-id)$
-<article-id pub-id-type="publisher-id">$article.publisher-id$</article-id>
-$endif$
-$if(article.doi)$
-<article-id pub-id-type="doi">$article.doi$</article-id>
-$endif$
-$if(article.pmid)$
-<article-id pub-id-type="pmid">$article.pmid$</article-id>
-$endif$
-$if(article.pmcid)$
-<article-id pub-id-type="pmcid">$article.pmcid$</article-id>
-$endif$
-$if(article.art-access-id)$
-<article-id pub-id-type="art-access-id">$article.art-access-id$</article-id>
-$endif$
-$if(article.heading)$
-<article-categories>
-<subj-group subj-group-type="heading">
-<subject>$article.heading$</subject>
-</subj-group>
-$if(article.categories)$
-<subj-group subj-group-type="categories">
-$for(article.categories)$
-<subject>$article.categories$</subject>
-$endfor$
-</subj-group>
-$endif$
-</article-categories>
-$endif$
-$if(title)$
-<title-group>
-<article-title>$title$</article-title>
-</title-group>
-$endif$
-$if(author)$
-<contrib-group>
-$for(author)$
-<contrib contrib-type="author">
-$if(author.orcid)$
-<contrib-id contrib-id-type="orcid">$author.orcid$</contrib-id>
-$endif$
-<name>
-$if(author.surname)$
-<surname>$author.surname$</surname>
-<given-names>$author.given-names$</given-names>
-$else$
-<string-name>$author$</string-name>
-$endif$
-</name>
-$if(author.email)$
-<email>$author.email$</email>
-$endif$
-$if(author.aff-id)$
-<xref ref-type="aff" rid="aff-$contrib.aff-id$"/>
-$endif$
-$if(author.cor-id)$
-<xref ref-type="corresp" rid="cor-$author.cor-id$"><sup>*</sup></xref>
-$endif$
-</contrib>
-$endfor$
-</contrib-group>
-$endif$
-$if(article.author-notes)$
-<author-notes>
-$if(article.author-notes.corresp)$
-$for(article.author-notes.corresp)$
-<corresp id="cor-$article.author-notes.corresp.id$">* E-mail: <email>$article.author-notes.corresp.email$</email></corresp>
-$endfor$
-$endif$
-$if(article.author-notes.conflict)$
-<fn fn-type="conflict"><p>$article.author-notes.conflict$</p></fn>
-$endif$
-$if(article.author-notes.con)$
-<fn fn-type="con"><p>$article.author-notes.con$</p></fn>
-$endif$
-</author-notes>
-$endif$
-$if(date)$
-$if(date.iso-8601)$
-<pub-date pub-type="epub" iso-8601-date="$date.iso-8601$">
-$else$
-<pub-date pub-type="epub">
-$endif$
-$if(date.day)$
-<day>$pub-date.day$</day>
-$endif$
-$if(date.month)$
-<month>$pub-date.month$</month>
-$endif$
-$if(date.year)$
-<year>$pub-date.year$</year>
-$else$
-<string-date>$date$</string-date>
-$endif$
-</pub-date>
-$endif$
-$if(article.volume)$
-<volume>$article.volume$</volume>
-$endif$
-$if(article.issue)$
-<issue>$article.issue$</issue>
-$endif$
-$if(article.fpage)$
-<fpage>$article.fpage$</fpage>
-$endif$
-$if(article.lpage)$
-<lpage>$article.lpage$</lpage>
-$endif$
-$if(article.elocation-id)$
-<elocation-id>$article.elocation-id$</elocation-id>
-$endif$
-$if(history)$
-<history>
-</history>
-$endif$
-$if(copyright)$
-<permissions>
-$if(copyright.statement)$
-<copyright-statement>$copyright.statement$</copyright-statement>
-$endif$
-$if(copyright.year)$
-<copyright-year>$copyright.year$</copyright-year>
-$endif$
-$if(copyright.holder)$
-<copyright-holder>$copyright.holder$</copyright-holder>
-$endif$
-$if(copyright.text)$
-<license license-type="$copyright.type$" xlink:href="$copyright.link$">
-<license-p>$copyright.text$</license-p>
-</license>
-</permissions>
-$endif$
-$endif$
-$if(tags)$
-<kwd-group kwd-group-type="author">
-$for(tags)$
-<kwd>$tags$</kwd>
-$endfor$
-</kwd-group>
-$endif$
-$if(article.funding-statement)$
-<funding-group>
-<funding-statement>$article.funding-statement$</funding-statement>
-</funding-group>
-$endif$
-</article-meta>
-$if(notes)$
-<notes>$notes$</notes>
-$endif$
-</front>
-<body>
-$body$
-</body>
-<back>
-$if(back)$
-$back$
-$endif$
-</back>
-</article>
diff --git a/data/templates/default.jats_archiving b/data/templates/default.jats_archiving
new file mode 100644
--- /dev/null
+++ b/data/templates/default.jats_archiving
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="utf-8" ?>
+$if(xml-stylesheet)$
+<?xml-stylesheet type="text/xsl" href="$xml-stylesheet$"?>
+$endif$
+<!DOCTYPE article PUBLIC "-//NLM//DTD JATS (Z39.96) Journal Archiving and Interchange DTD v1.2 20190208//EN"
+                  "JATS-archivearticle1.dtd">
+${ article.jats_publishing() }
diff --git a/data/templates/default.jats_articleauthoring b/data/templates/default.jats_articleauthoring
new file mode 100644
--- /dev/null
+++ b/data/templates/default.jats_articleauthoring
@@ -0,0 +1,109 @@
+<?xml version="1.0" encoding="utf-8" ?>
+$if(xml-stylesheet)$
+<?xml-stylesheet type="text/xsl" href="$xml-stylesheet$"?>
+$endif$
+<!DOCTYPE article PUBLIC "-//NLM//DTD JATS (Z39.96) Article Authoring DTD v1.2 20190208//EN"
+                  "JATS-articleauthoring1.dtd">
+$if(article.type)$
+<article xmlns:mml="http://www.w3.org/1998/Math/MathML" xmlns:xlink="http://www.w3.org/1999/xlink" dtd-version="1.2" article-type="$article.type$">
+$else$
+<article xmlns:mml="http://www.w3.org/1998/Math/MathML" xmlns:xlink="http://www.w3.org/1999/xlink" dtd-version="1.2" article-type="other">
+$endif$
+<front>
+<article-meta>
+$if(title)$
+<title-group>
+<article-title>$title$</article-title>
+$if(subtitle)$
+<subtitle>${subtitle}</subtitle>
+$endif$
+</title-group>
+$endif$
+$if(author)$
+<contrib-group>
+$for(author)$
+<contrib contrib-type="author"$if(author.equal-contrib)$ equal-contrib="yes"$endif$$if(author.cor-id)$ corresp="yes"$endif$>
+$if(author.orcid)$
+<contrib-id contrib-id-type="orcid">$author.orcid$</contrib-id>
+$endif$
+$if(author.surname)$
+<name>
+<surname>$if(author.non-dropping-particle)$${author.non-dropping-particle} $endif$${author.surname}</surname>
+<given-names>${author.given-names}$if(author.dropping-particle)$ ${author.dropping-particle}$endif$</given-names>
+$if(author.prefix)$
+<prefix>${author.prefix}</prefix>
+$endif$
+$if(author.suffix)$
+<suffix>${author.suffix}</suffix>
+$endif$
+</name>
+$elseif(author.name)$
+<string-name>$author.name$</string-name>
+$else$
+<string-name>$author$</string-name>
+$endif$
+$for(author.affiliation)$
+${ it:affiliations.jats() }
+$endfor$
+$if(author.email)$
+<email>$author.email$</email>
+$endif$
+$if(author.cor-id)$
+<xref ref-type="corresp" rid="cor-$author.cor-id$"><sup>*</sup></xref>
+$endif$
+</contrib>
+$endfor$
+</contrib-group>
+$endif$
+<permissions>
+$for(copyright.statement)$
+<copyright-statement>$copyright.statement$</copyright-statement>
+$endfor$
+$for(copyright.year)$
+<copyright-year>$copyright.year$</copyright-year>
+$endfor$
+$for(copyright.holder)$
+<copyright-holder>$copyright.holder$</copyright-holder>
+$endfor$
+$if(copyright.text)$
+<license license-type="$copyright.type$" xlink:href="$copyright.link$">
+<license-p>$copyright.text$</license-p>
+</license>
+$endif$
+$for(license)$
+<license$if(it.type)$ license-type="${it.type}"$endif$$if(it.link)$ xlink:href="${it.link}"$endif$>
+<license-p>$if(it.text)$${it.text}$else$${it}$endif$</license-p>
+</license>
+$endfor$
+</permissions>
+<abstract>
+$abstract$
+</abstract>
+$if(tags)$
+<kwd-group kwd-group-type="author">
+$for(tags)$
+<kwd>$tags$</kwd>
+$endfor$
+</kwd-group>
+$endif$
+$if(article.funding-statement)$
+<funding-group>
+<funding-statement>$article.funding-statement$</funding-statement>
+</funding-group>
+$endif$
+$if(supplementary-material)$
+<supplementary-material>
+$supplementary-material$
+</supplementary-material>
+$endif$
+</article-meta>
+</front>
+<body>
+$body$
+</body>
+<back>
+$if(back)$
+$back$
+$endif$
+</back>
+</article>
diff --git a/data/templates/default.jats_publishing b/data/templates/default.jats_publishing
new file mode 100644
--- /dev/null
+++ b/data/templates/default.jats_publishing
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="utf-8" ?>
+$if(xml-stylesheet)$
+<?xml-stylesheet type="text/xsl" href="$xml-stylesheet$"?>
+$endif$
+<!DOCTYPE article PUBLIC "-//NLM//DTD JATS (Z39.96) Journal Publishing DTD v1.2 20190208//EN"
+                  "JATS-publishing1.dtd">
+${ article.jats_publishing() }
diff --git a/data/templates/default.jira b/data/templates/default.jira
new file mode 100644
--- /dev/null
+++ b/data/templates/default.jira
@@ -0,0 +1,9 @@
+$for(include-before)$
+$include-before$
+
+$endfor$
+$body$
+$for(include-after)$
+
+$include-after$
+$endfor$
diff --git a/data/templates/default.latex b/data/templates/default.latex
--- a/data/templates/default.latex
+++ b/data/templates/default.latex
@@ -1,348 +1,84 @@
-\PassOptionsToPackage{unicode=true}{hyperref} % options for packages loaded elsewhere
-\PassOptionsToPackage{hyphens}{url}
-$if(colorlinks)$
-\PassOptionsToPackage{dvipsnames,svgnames*,x11names*}{xcolor}
-$endif$
-%
-\documentclass[$if(fontsize)$$fontsize$,$endif$$if(lang)$$babel-lang$,$endif$$if(papersize)$$papersize$paper,$endif$$if(beamer)$ignorenonframetext,$if(handout)$handout,$endif$$if(aspectratio)$aspectratio=$aspectratio$,$endif$$endif$$for(classoption)$$classoption$$sep$,$endfor$]{$documentclass$}
-$if(beamer)$
-\setbeamertemplate{caption}[numbered]
-\setbeamertemplate{caption label separator}{: }
-\setbeamercolor{caption name}{fg=normal text.fg}
-\beamertemplatenavigationsymbols$if(navigation)$$navigation$$else$empty$endif$
-$endif$
-$if(beamerarticle)$
-\usepackage{beamerarticle} % needs to be loaded first
-$endif$
-$if(fontfamily)$
-\usepackage[$for(fontfamilyoptions)$$fontfamilyoptions$$sep$,$endfor$]{$fontfamily$}
-$else$
-\usepackage{lmodern}
-$endif$
-$if(linestretch)$
-\usepackage{setspace}
-\setstretch{$linestretch$}
-$endif$
-\usepackage{amssymb,amsmath}
-\usepackage{ifxetex,ifluatex}
-\usepackage{fixltx2e} % provides \textsubscript
-\ifnum 0\ifxetex 1\fi\ifluatex 1\fi=0 % if pdftex
-  \usepackage[$if(fontenc)$$fontenc$$else$T1$endif$]{fontenc}
-  \usepackage[utf8]{inputenc}
-  \usepackage{textcomp} % provides euro and other symbols
-\else % if luatex or xelatex
-$if(mathspec)$
-  \ifxetex
-    \usepackage{mathspec}
-  \else
-    \usepackage{unicode-math}
-  \fi
-$else$
-  \usepackage{unicode-math}
-$endif$
-  \defaultfontfeatures{Ligatures=TeX,Scale=MatchLowercase}
-$for(fontfamilies)$
-  \newfontfamily{$fontfamilies.name$}[$fontfamilies.options$]{$fontfamilies.font$}
+$document-metadata.latex()$
+$passoptions.latex()$
+\documentclass[
+$for(babel-otherlangs)$
+  $babel-otherlangs$,
 $endfor$
-$if(mainfont)$
-    \setmainfont[$for(mainfontoptions)$$mainfontoptions$$sep$,$endfor$]{$mainfont$}
-$endif$
-$if(sansfont)$
-    \setsansfont[$for(sansfontoptions)$$sansfontoptions$$sep$,$endfor$]{$sansfont$}
-$endif$
-$if(monofont)$
-    \setmonofont[Mapping=tex-ansi$if(monofontoptions)$,$for(monofontoptions)$$monofontoptions$$sep$,$endfor$$endif$]{$monofont$}
-$endif$
-$if(mathfont)$
-$if(mathspec)$
-  \ifxetex
-    \setmathfont(Digits,Latin,Greek)[$for(mathfontoptions)$$mathfontoptions$$sep$,$endfor$]{$mathfont$}
-  \else
-    \setmathfont[$for(mathfontoptions)$$mathfontoptions$$sep$,$endfor$]{$mathfont$}
-  \fi
-$else$
-  \setmathfont[$for(mathfontoptions)$$mathfontoptions$$sep$,$endfor$]{$mathfont$}
-$endif$
-$endif$
-$if(CJKmainfont)$
-  \ifxetex
-    \usepackage{xeCJK}
-    \setCJKmainfont[$for(CJKoptions)$$CJKoptions$$sep$,$endfor$]{$CJKmainfont$}
-  \fi
-$endif$
-$if(luatexjapresetoptions)$
-  \ifluatex
-    \usepackage[$for(luatexjapresetoptions)$$luatexjapresetoptions$$sep$,$endfor$]{luatexja-preset}
-  \fi
-$endif$
-$if(CJKmainfont)$
-  \ifluatex
-    \usepackage[$for(luatexjafontspecoptions)$$luatexjafontspecoptions$$sep$,$endfor$]{luatexja-fontspec}
-    \setmainjfont[$for(CJKoptions)$$CJKoptions$$sep$,$endfor$]{$CJKmainfont$}
-  \fi
-$endif$
-\fi
-$if(beamer)$
-$if(theme)$
-\usetheme[$for(themeoptions)$$themeoptions$$sep$,$endfor$]{$theme$}
-$endif$
-$if(colortheme)$
-\usecolortheme{$colortheme$}
-$endif$
-$if(fonttheme)$
-\usefonttheme{$fonttheme$}
-$endif$
-$if(mainfont)$
-\usefonttheme{serif} % use mainfont rather than sansfont for slide text
-$endif$
-$if(innertheme)$
-\useinnertheme{$innertheme$}
-$endif$
-$if(outertheme)$
-\useoutertheme{$outertheme$}
+$if(babel-lang)$
+  $babel-lang$,
 $endif$
+$if(fontsize)$
+  $fontsize$,
 $endif$
-% use upquote if available, for straight quotes in verbatim environments
-\IfFileExists{upquote.sty}{\usepackage{upquote}}{}
-% use microtype if available
-\IfFileExists{microtype.sty}{%
-\usepackage[$for(microtypeoptions)$$microtypeoptions$$sep$,$endfor$]{microtype}
-\UseMicrotypeSet[protrusion]{basicmath} % disable protrusion for tt fonts
-}{}
-$if(indent)$
-$else$
-\IfFileExists{parskip.sty}{%
-\usepackage{parskip}
-}{% else
-\setlength{\parindent}{0pt}
-\setlength{\parskip}{6pt plus 2pt minus 1pt}
-}
+$if(papersize)$
+  $papersize$paper,
 $endif$
-$if(verbatim-in-note)$
-\usepackage{fancyvrb}
+$for(classoption)$
+  $classoption$$sep$,
+$endfor$
+]{$documentclass$}
+$if(beamerarticle)$
+\usepackage{beamerarticle} % needs to be loaded first
 $endif$
-$if(colorlinks)$
 \usepackage{xcolor}
-$endif$
-\usepackage{hyperref}
-\hypersetup{
-$if(title-meta)$
-            pdftitle={$title-meta$},
-$endif$
-$if(author-meta)$
-            pdfauthor={$author-meta$},
-$endif$
-$if(keywords)$
-            pdfkeywords={$for(keywords)$$keywords$$sep$, $endfor$},
-$endif$
-$if(colorlinks)$
-            colorlinks=true,
-            linkcolor=$if(linkcolor)$$linkcolor$$else$Maroon$endif$,
-            citecolor=$if(citecolor)$$citecolor$$else$Blue$endif$,
-            urlcolor=$if(urlcolor)$$urlcolor$$else$Blue$endif$,
-$else$
-            pdfborder={0 0 0},
-$endif$
-            breaklinks=true}
-\urlstyle{same}  % don't use monospace font for urls
-$if(verbatim-in-note)$
-\VerbatimFootnotes % allows verbatim text in footnotes
-$endif$
 $if(geometry)$
 \usepackage[$for(geometry)$$geometry$$sep$,$endfor$]{geometry}
 $endif$
-$if(beamer)$
-\newif\ifbibliography
-$endif$
-$if(listings)$
-\usepackage{listings}
-\newcommand{\passthrough}[1]{#1}
-$endif$
-$if(lhs)$
-\lstnewenvironment{code}{\lstset{language=Haskell,basicstyle=\small\ttfamily}}{}
-$endif$
-$if(highlighting-macros)$
-$highlighting-macros$
-$endif$
-$if(tables)$
-\usepackage{longtable,booktabs}
-$if(beamer)$
-\usepackage{caption}
-% These lines are needed to make table captions work with longtable:
-\makeatletter
-\def\fnum@table{\tablename~\thetable}
-\makeatother
-$else$
-% Fix footnotes in tables (requires footnote package)
-\IfFileExists{footnote.sty}{\usepackage{footnote}\makesavenoteenv{longtable}}{}
-$endif$
-$endif$
-$if(graphics)$
-\usepackage{graphicx,grffile}
-\makeatletter
-\def\maxwidth{\ifdim\Gin@nat@width>\linewidth\linewidth\else\Gin@nat@width\fi}
-\def\maxheight{\ifdim\Gin@nat@height>\textheight\textheight\else\Gin@nat@height\fi}
-\makeatother
-% Scale images if necessary, so that they will not overflow the page
-% margins by default, and it is still possible to overwrite the defaults
-% using explicit options in \includegraphics[width, height, ...]{}
-\setkeys{Gin}{width=\maxwidth,height=\maxheight,keepaspectratio}
-$endif$
-$if(beamer)$
-% Prevent slide breaks in the middle of a paragraph:
-\widowpenalties 1 10000
-\raggedbottom
-$if(section-titles)$
-\setbeamertemplate{part page}{
-\centering
-\begin{beamercolorbox}[sep=16pt,center]{part title}
-  \usebeamerfont{part title}\insertpart\par
-\end{beamercolorbox}
-}
-\setbeamertemplate{section page}{
-\centering
-\begin{beamercolorbox}[sep=12pt,center]{part title}
-  \usebeamerfont{section title}\insertsection\par
-\end{beamercolorbox}
-}
-\setbeamertemplate{subsection page}{
-\centering
-\begin{beamercolorbox}[sep=8pt,center]{part title}
-  \usebeamerfont{subsection title}\insertsubsection\par
-\end{beamercolorbox}
-}
-\AtBeginPart{
-  \frame{\partpage}
-}
-\AtBeginSection{
-  \ifbibliography
-  \else
-    \frame{\sectionpage}
-  \fi
-}
-\AtBeginSubsection{
-  \frame{\subsectionpage}
-}
-$endif$
-$endif$
-$if(links-as-notes)$
-% Make links footnotes instead of hotlinks:
-\DeclareRobustCommand{\href}[2]{#2\footnote{\url{#1}}}
-$endif$
-$if(strikeout)$
-\usepackage[normalem]{ulem}
-% avoid problems with \sout in headers with hyperref:
-\pdfstringdefDisableCommands{\renewcommand{\sout}{}}
+\usepackage{amsmath,amssymb}
+$if(cancel)$
+\usepackage{cancel}
 $endif$
-\setlength{\emergencystretch}{3em}  % prevent overfull lines
-\providecommand{\tightlist}{%
-  \setlength{\itemsep}{0pt}\setlength{\parskip}{0pt}}
+$--
+$-- section numbering
+$--
 $if(numbersections)$
 \setcounter{secnumdepth}{$if(secnumdepth)$$secnumdepth$$else$5$endif$}
 $else$
-\setcounter{secnumdepth}{0}
-$endif$
-$if(beamer)$
-$else$
-$if(subparagraph)$
-$else$
-% Redefines (sub)paragraphs to behave more like sections
-\ifx\paragraph\undefined\else
-\let\oldparagraph\paragraph
-\renewcommand{\paragraph}[1]{\oldparagraph{#1}\mbox{}}
-\fi
-\ifx\subparagraph\undefined\else
-\let\oldsubparagraph\subparagraph
-\renewcommand{\subparagraph}[1]{\oldsubparagraph{#1}\mbox{}}
-\fi
-$endif$
-$endif$
-$if(pagestyle)$
-\pagestyle{$pagestyle$}
+\setcounter{secnumdepth}{-\maxdimen} % remove section numbering
 $endif$
-
-% set default figure placement to htbp
-\makeatletter
-\def\fps@figure{htbp}
-\makeatother
-
+$fonts.latex()$
+$font-settings.latex()$
+$common.latex()$
 $for(header-includes)$
 $header-includes$
 $endfor$
-$if(lang)$
-\ifnum 0\ifxetex 1\fi\ifluatex 1\fi=0 % if pdftex
-  \usepackage[shorthands=off,$for(babel-otherlangs)$$babel-otherlangs$,$endfor$main=$babel-lang$]{babel}
-$if(babel-newcommands)$
-  $babel-newcommands$
-$endif$
-\else
-  % load polyglossia as late as possible as it *could* call bidi if RTL lang (e.g. Hebrew or Arabic)
-  \usepackage{polyglossia}
-  \setmainlanguage[$polyglossia-lang.options$]{$polyglossia-lang.name$}
-$for(polyglossia-otherlangs)$
-  \setotherlanguage[$polyglossia-otherlangs.options$]{$polyglossia-otherlangs.name$}
-$endfor$
+$after-header-includes.latex()$
+$hypersetup.latex()$
+$if(pdf-trailer-id)$
+
+\ifXeTeX
+\special{pdf:trailerid [ $pdf-trailer-id$ ]}
 \fi
-$endif$
-$if(dir)$
-\ifxetex
-  % load bidi as late as possible as it modifies e.g. graphicx
-  $if(latex-dir-rtl)$
-  \usepackage[RTLdocument]{bidi}
-  $else$
-  \usepackage{bidi}
-  $endif$
+\ifPDFTeX
+\pdftrailerid{}
+\pdftrailer{/ID [ $pdf-trailer-id$ ]}
 \fi
-\ifnum 0\ifxetex 1\fi\ifluatex 1\fi=0 % if pdftex
-  \TeXXeTstate=1
-  \newcommand{\RL}[1]{\beginR #1\endR}
-  \newcommand{\LR}[1]{\beginL #1\endL}
-  \newenvironment{RTL}{\beginR}{\endR}
-  \newenvironment{LTR}{\beginL}{\endL}
+\ifLuaTeX
+\pdfvariable trailerid {[ $pdf-trailer-id$ ]}
 \fi
 $endif$
-$if(natbib)$
-\usepackage[$natbiboptions$]{natbib}
-\bibliographystyle{$if(biblio-style)$$biblio-style$$else$plainnat$endif$}
-$endif$
-$if(biblatex)$
-\usepackage[$if(biblio-style)$style=$biblio-style$,$endif$$for(biblatexoptions)$$biblatexoptions$$sep$,$endfor$]{biblatex}
-$for(bibliography)$
-\addbibresource{$bibliography$}
-$endfor$
-$endif$
 
 $if(title)$
 \title{$title$$if(thanks)$\thanks{$thanks$}$endif$}
 $endif$
 $if(subtitle)$
-\providecommand{\subtitle}[1]{}
+\usepackage{etoolbox}
+\makeatletter
+\providecommand{\subtitle}[1]{% add subtitle to \maketitle
+  \apptocmd{\@title}{\par {\large #1 \par}}{}{}
+}
+\makeatother
 \subtitle{$subtitle$}
 $endif$
-$if(author)$
 \author{$for(author)$$author$$sep$ \and $endfor$}
-$endif$
-$if(institute)$
-\providecommand{\institute}[1]{}
-\institute{$for(institute)$$institute$$sep$ \and $endfor$}
-$endif$
 \date{$date$}
-$if(beamer)$
-$if(titlegraphic)$
-\titlegraphic{\includegraphics{$titlegraphic$}}
-$endif$
-$if(logo)$
-\logo{\includegraphics{$logo$}}
-$endif$
-$endif$
 
 \begin{document}
+$if(has-frontmatter)$
+\frontmatter
+$endif$
 $if(title)$
-$if(beamer)$
-\frame{\titlepage}
-$else$
 \maketitle
-$endif$
 $if(abstract)$
 \begin{abstract}
 $abstract$
@@ -355,57 +91,54 @@
 
 $endfor$
 $if(toc)$
-$if(beamer)$
-\begin{frame}
-\tableofcontents[hideallsubsections]
-\end{frame}
-$else$
+$if(toc-title)$
+\renewcommand*\contentsname{$toc-title$}
+$endif$
 {
 $if(colorlinks)$
-\hypersetup{linkcolor=$if(toccolor)$$toccolor$$else$$endif$}
+$if(toccolor)$
+\hypersetup{linkcolor=$toccolor$}
 $endif$
+$endif$
 \setcounter{tocdepth}{$toc-depth$}
 \tableofcontents
 }
 $endif$
+$if(lof)$
+\listoffigures
 $endif$
 $if(lot)$
 \listoftables
 $endif$
-$if(lof)$
-\listoffigures
+$if(linestretch)$
+\setstretch{$linestretch$}
 $endif$
+$if(has-frontmatter)$
+\mainmatter
+$endif$
 $body$
 
+$if(has-frontmatter)$
+\backmatter
+$endif$
+$if(nocite-ids)$
+\nocite{$for(nocite-ids)$$it$$sep$, $endfor$}
+$endif$
 $if(natbib)$
 $if(bibliography)$
 $if(biblio-title)$
-$if(book-class)$
+$if(has-chapters)$
 \renewcommand\bibname{$biblio-title$}
 $else$
 \renewcommand\refname{$biblio-title$}
 $endif$
 $endif$
-$if(beamer)$
-\begin{frame}[allowframebreaks]{$biblio-title$}
-\bibliographytrue
-$endif$
 \bibliography{$for(bibliography)$$bibliography$$sep$,$endfor$}
-$if(beamer)$
-\end{frame}
-$endif$
 
 $endif$
 $endif$
 $if(biblatex)$
-$if(beamer)$
-\begin{frame}[allowframebreaks]{$biblio-title$}
-\bibliographytrue
-\printbibliography[heading=none]
-\end{frame}
-$else$
 \printbibliography$if(biblio-title)$[title=$biblio-title$]$endif$
-$endif$
 
 $endif$
 $for(include-after)$
diff --git a/data/templates/default.man b/data/templates/default.man
--- a/data/templates/default.man
+++ b/data/templates/default.man
@@ -1,5 +1,5 @@
 $if(has-tables)$
-.\"t
+'\" t
 $endif$
 $if(pandoc-version)$
 .\" Automatically generated by Pandoc $pandoc-version$
@@ -8,12 +8,7 @@
 $if(adjusting)$
 .ad $adjusting$
 $endif$
-.TH "$title$" "$section$" "$date$" "$footer$" "$header$"
-$if(hyphenate)$
-.hy
-$else$
-.nh \" Turn off hyphenation by default.
-$endif$
+.TH "$title/nowrap$" "$section/nowrap$" "$date/nowrap$" "$footer/nowrap$"$if(header)$ "$header/nowrap$"$endif$
 $for(header-includes)$
 $header-includes$
 $endfor$
diff --git a/data/templates/default.markua b/data/templates/default.markua
new file mode 100644
--- /dev/null
+++ b/data/templates/default.markua
@@ -0,0 +1,21 @@
+$if(titleblock)$
+$titleblock$
+
+$endif$
+$for(header-includes)$
+$header-includes$
+
+$endfor$
+$for(include-before)$
+$include-before$
+
+$endfor$
+$if(toc)$
+$table-of-contents$
+
+$endif$
+$body$
+$for(include-after)$
+
+$include-after$
+$endfor$
diff --git a/data/templates/default.ms b/data/templates/default.ms
--- a/data/templates/default.ms
+++ b/data/templates/default.ms
@@ -1,3 +1,7 @@
+$if(pandoc-version)$
+.\" Automatically generated by Pandoc $pandoc-version$
+.\"
+$endif$
 .\" **** Custom macro definitions *********************************
 .\" * Super/subscript
 .\" (https://lists.gnu.org/archive/html/groff/2012-07/msg00046.html)
@@ -33,19 +37,19 @@
 .\" font family: A, BM, H, HN, N, P, T, ZCM
 .fam $if(fontfamily)$$fontfamily$$else$T$endif$
 .\" paragraph indent
-.nr PI $if(indent)$$indent$$else$2m$endif$
+.nr PI $if(indent)$$indent$$else$0m$endif$
 .\" interparagraph space
-.nr PD 0.33v
+.nr PD 0.4v
 .\" footnote width
 .nr FL \n[LL]
 .\" footnote point size
 .nr FPS (\n[PS] - 2000)
+$if(papersize)$
+.\" paper size
+.ds paper $papersize$
+$endif$
 .\" color used for strikeout
 .defcolor strikecolor rgb 0.7 0.7 0.7
-.\" color for links (rgb)
-.ds PDFHREF.COLOUR   0.35 0.00 0.60
-.\" border for links (default none)
-.ds PDFHREF.BORDER   0 0 0
 .\" point size difference between heading levels
 .nr PSINCR 1p
 .\" heading level above which point size no longer changes
@@ -53,27 +57,36 @@
 .\" comment these out if you want a dot after section numbers:
 .als SN SN-NO-DOT
 .als SN-STYLE SN-NO-DOT
-.\" pdf outline fold level
-.nr PDFOUTLINE.FOLDLEVEL 3
-.\" start out in outline view
-.pdfview /PageMode /UseOutlines
-.\" ***************************************************************
-.\" PDF metadata
-.pdfinfo /Title "$title-meta$"
-.pdfinfo /Author "$author-meta$"
+.\" page numbers in footer, centered
+.ds CH
+.ds CF %
 $if(adjusting)$
 .ad $adjusting$
 $endif$
 $if(hyphenate)$
 .hy
 $else$
-.nh \" Turn off hyphenation by default.
+.nh
 $endif$
 $if(has-inline-math)$
 .EQ
 delim @@
 .EN
 $endif$
+$if(pdf-engine)$
+.\" color for links (rgb)
+.ds PDFHREF.COLOUR   0.35 0.00 0.60
+.\" border for links (default none)
+.ds PDFHREF.BORDER   0 0 0
+.\" pdf outline fold level
+.nr PDFOUTLINE.FOLDLEVEL 3
+.\" start out in outline view
+.pdfview /PageMode /UseOutlines
+.\" ***************************************************************
+.\" PDF metadata
+.pdfinfo /Title "$title-meta$"
+.pdfinfo /Author "$author-meta$"
+$endif$
 $for(header-includes)$
 $header-includes$
 $endfor$
@@ -86,7 +99,10 @@
 $author$
 $endfor$
 $if(date)$
-.ND "$date$"
+.AU
+.sp 0.5
+.ft R
+$date$
 $endif$
 $if(abstract)$
 .AB
diff --git a/data/templates/default.muse b/data/templates/default.muse
--- a/data/templates/default.muse
+++ b/data/templates/default.muse
@@ -1,5 +1,5 @@
 $if(author)$
-#author $author$
+#author $for(author)$$author$$sep$; $endfor$
 $endif$
 $if(title)$
 #title $title$
diff --git a/data/templates/default.opendocument b/data/templates/default.opendocument
--- a/data/templates/default.opendocument
+++ b/data/templates/default.opendocument
@@ -1,5 +1,5 @@
 <?xml version="1.0" encoding="utf-8" ?>
-<office:document-content xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" xmlns:style="urn:oasis:names:tc:opendocument:xmlns:style:1.0" xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0" xmlns:table="urn:oasis:names:tc:opendocument:xmlns:table:1.0" xmlns:draw="urn:oasis:names:tc:opendocument:xmlns:drawing:1.0" xmlns:fo="urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:meta="urn:oasis:names:tc:opendocument:xmlns:meta:1.0" xmlns:number="urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0" xmlns:svg="urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0" xmlns:chart="urn:oasis:names:tc:opendocument:xmlns:chart:1.0" xmlns:dr3d="urn:oasis:names:tc:opendocument:xmlns:dr3d:1.0" xmlns:math="http://www.w3.org/1998/Math/MathML" xmlns:form="urn:oasis:names:tc:opendocument:xmlns:form:1.0" xmlns:script="urn:oasis:names:tc:opendocument:xmlns:script:1.0" xmlns:ooo="http://openoffice.org/2004/office" xmlns:ooow="http://openoffice.org/2004/writer" xmlns:oooc="http://openoffice.org/2004/calc" xmlns:dom="http://www.w3.org/2001/xml-events" xmlns:xforms="http://www.w3.org/2002/xforms" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" office:version="1.2">
+<office:document-content xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" xmlns:style="urn:oasis:names:tc:opendocument:xmlns:style:1.0" xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0" xmlns:table="urn:oasis:names:tc:opendocument:xmlns:table:1.0" xmlns:draw="urn:oasis:names:tc:opendocument:xmlns:drawing:1.0" xmlns:fo="urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:meta="urn:oasis:names:tc:opendocument:xmlns:meta:1.0" xmlns:number="urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0" xmlns:svg="urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0" xmlns:chart="urn:oasis:names:tc:opendocument:xmlns:chart:1.0" xmlns:dr3d="urn:oasis:names:tc:opendocument:xmlns:dr3d:1.0" xmlns:math="http://www.w3.org/1998/Math/MathML" xmlns:form="urn:oasis:names:tc:opendocument:xmlns:form:1.0" xmlns:script="urn:oasis:names:tc:opendocument:xmlns:script:1.0" xmlns:ooo="http://openoffice.org/2004/office" xmlns:ooow="http://openoffice.org/2004/writer" xmlns:oooc="http://openoffice.org/2004/calc" xmlns:dom="http://www.w3.org/2001/xml-events" xmlns:xforms="http://www.w3.org/2002/xforms" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" office:version="1.3">
   <office:font-face-decls>
     <style:font-face style:name="Courier New" style:font-family-generic="modern" style:font-pitch="fixed" svg:font-family="'Courier New'" />
   </office:font-face-decls>
@@ -14,21 +14,25 @@
 $if(title)$
 <text:p text:style-name="Title">$title$</text:p>
 $endif$
+$if(subtitle)$
+<text:p text:style-name="Subtitle">$subtitle$</text:p>
+$endif$
 $for(author)$
 <text:p text:style-name="Author">$author$</text:p>
 $endfor$
 $if(date)$
 <text:p text:style-name="Date">$date$</text:p>
 $endif$
+$if(abstract)$
+$abstract$
+$endif$
 $for(include-before)$
 $include-before$
 $endfor$
 $if(toc)$
 <text:table-of-content>
-  <text:table-of-content-source text:outline-level="10">
-    <text:index-title-template text:style-name="Contents_20_Heading">
-        $toc-title$
-    </text:index-title-template>
+  <text:table-of-content-source text:outline-level="$toc-depth$">
+    <text:index-title-template text:style-name="Contents_20_Heading">$toc-title$</text:index-title-template>
     <text:table-of-content-entry-template text:outline-level="1"
     text:style-name="Contents_20_1">
       <text:index-entry-link-start text:style-name="Internet_20_link" />
diff --git a/data/templates/default.openxml b/data/templates/default.openxml
new file mode 100644
--- /dev/null
+++ b/data/templates/default.openxml
@@ -0,0 +1,65 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:m="http://schemas.openxmlformats.org/officeDocument/2006/math" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:w10="urn:schemas-microsoft-com:office:word" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:pic="http://schemas.openxmlformats.org/drawingml/2006/picture" xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing">
+<w:body>
+$if(title)$
+    <w:p>
+      <w:pPr>
+        <w:pStyle w:val="$title-style-id$" />
+      </w:pPr>
+      $title$
+    </w:p>
+$endif$
+$if(subtitle)$
+    <w:p>
+      <w:pPr>
+        <w:pStyle w:val="$subtitle-style-id$" />
+      </w:pPr>
+      $subtitle$
+    </w:p>
+$endif$
+$for(author)$
+    <w:p>
+      <w:pPr>
+        <w:pStyle w:val="$author-style-id$" />
+      </w:pPr>
+      $author$
+    </w:p>
+$endfor$
+$if(date)$
+    <w:p>
+      <w:pPr>
+        <w:pStyle w:val="$date-style-id$" />
+      </w:pPr>
+      $date$
+    </w:p>
+$endif$
+$if(abstract)$
+$if(abstract-title)$
+    <w:p>
+      <w:pPr>
+        <w:pStyle w:val="$abstract-title-style-id$" />
+      </w:pPr>
+      <w:r><w:t xml:space="preserve">$abstract-title$</w:t></w:r>
+    </w:p>
+$endif$
+    $abstract$
+$endif$
+$for(include-before)$
+    $include-before$
+$endfor$
+$if(toc)$
+    $toc$
+$endif$
+$if(lof)$
+    $lof$
+$endif$
+$if(lot)$
+    $lot$
+$endif$
+    $body$
+$for(include-after)$
+    $include-after$
+$endfor$
+    $sectpr$
+  </w:body>
+</w:document>
diff --git a/data/templates/default.org b/data/templates/default.org
--- a/data/templates/default.org
+++ b/data/templates/default.org
@@ -1,18 +1,29 @@
 $if(title)$
-#+TITLE: $title$
+#+title: $title$
 
 $endif$
 $if(author)$
-#+AUTHOR: $for(author)$$author$$sep$; $endfor$
+#+author: $for(author)$$author$$sep$; $endfor$
 $endif$
 $if(date)$
-#+DATE: $date$
+#+date: $date$
 
 $endif$
+$if(options/pairs)$
+$for(options/pairs)$
+#+options: ${it.key}:${it.value}
+$endfor$
+
+$endif$
 $for(header-includes)$
 $header-includes$
 
 $endfor$
+$if(abstract)$
+#+begin_abstract
+$abstract$
+#+end_abstract
+$endif$
 $for(include-before)$
 $include-before$
 
diff --git a/data/templates/default.revealjs b/data/templates/default.revealjs
--- a/data/templates/default.revealjs
+++ b/data/templates/default.revealjs
@@ -16,40 +16,25 @@
   <meta name="apple-mobile-web-app-capable" content="yes">
   <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
   <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, minimal-ui">
-  <link rel="stylesheet" href="$revealjs-url$/css/reveal.css">
-  <style type="text/css">
-      code{white-space: pre-wrap;}
-      span.smallcaps{font-variant: small-caps;}
-      span.underline{text-decoration: underline;}
-      div.column{display: inline-block; vertical-align: top; width: 50%;}
-$if(quotes)$
-      q { quotes: "“" "”" "‘" "’"; }
-$endif$
-  </style>
-$if(highlighting-css)$
-  <style type="text/css">
-$highlighting-css$
+  <link rel="stylesheet" href="$revealjs-url$/dist/reset.css">
+  <link rel="stylesheet" href="$revealjs-url$/dist/reveal.css">
+  <style>
+    .reveal .sourceCode {  /* see #7635 */
+      overflow: visible;
+    }
+    $styles.html()$
   </style>
-$endif$
 $if(theme)$
-  <link rel="stylesheet" href="$revealjs-url$/css/theme/$theme$.css" id="theme">
+  <link rel="stylesheet" href="$revealjs-url$/dist/theme/$theme$.css" id="theme">
 $else$
-  <link rel="stylesheet" href="$revealjs-url$/css/theme/black.css" id="theme">
+  <link rel="stylesheet" href="$revealjs-url$/dist/theme/black.css" id="theme">
 $endif$
+$if(highlight-js)$
+  <link rel="stylesheet" href="$revealjs-url$/plugin/highlight/$highlightjs-theme$.css">
+$endif$
 $for(css)$
   <link rel="stylesheet" href="$css$"/>
 $endfor$
-  <!-- Printing and PDF exports -->
-  <script>
-    var link = document.createElement( 'link' );
-    link.rel = 'stylesheet';
-    link.type = 'text/css';
-    link.href = window.location.search.match( /print-pdf/gi ) ? '$revealjs-url$/css/print/pdf.css' : '$revealjs-url$/css/print/paper.css';
-    document.getElementsByTagName( 'head' )[0].appendChild( link );
-  </script>
-  <!--[if lt IE 9]>
-  <script src="$revealjs-url$/lib/js/html5shiv.js"></script>
-  <![endif]-->
 $if(math)$
   $math$
 $endif$
@@ -65,7 +50,7 @@
     <div class="slides">
 
 $if(title)$
-<section id="$idprefix$title-slide">
+<section id="$idprefix$title-slide"$for(title-slide-attributes/pairs)$ $it.key$="$it.value$"$endfor$>
   <h1 class="title">$title$</h1>
 $if(subtitle)$
   <p class="subtitle">$subtitle$</p>
@@ -73,6 +58,9 @@
 $for(author)$
   <p class="author">$author$</p>
 $endfor$
+$for(institute)$
+  <p class="institute">$institute$</p>
+$endfor$
 $if(date)$
   <p class="date">$date$</p>
 $endif$
@@ -80,7 +68,12 @@
 $endif$
 $if(toc)$
 <section id="$idprefix$TOC">
+<nav role="doc-toc"> 
+$if(toc-title)$
+<h2 id="$idprefix$toc-title">$toc-title$</h2>
+$endif$
 $table-of-contents$
+</nav>
 </section>
 $endif$
 
@@ -88,151 +81,241 @@
     </div>
   </div>
 
-  <script src="$revealjs-url$/lib/js/head.min.js"></script>
-  <script src="$revealjs-url$/js/reveal.js"></script>
+  <script src="$revealjs-url$/dist/reveal.js"></script>
 
+  <!-- reveal.js plugins -->
+  <script src="$revealjs-url$/plugin/notes/notes.js"></script>
+  <script src="$revealjs-url$/plugin/search/search.js"></script>
+  <script src="$revealjs-url$/plugin/zoom/zoom.js"></script>
+$if(mathjax)$
+  <script src="$revealjs-url$/plugin/math/math.js"></script>
+$endif$
+$if(highlight-js)$
+  <script src="$revealjs-url$/plugin/highlight/highlight.js"></script>
+$endif$
+
   <script>
 
       // Full list of configuration options available at:
-      // https://github.com/hakimel/reveal.js#configuration
+      // https://revealjs.com/config/
       Reveal.initialize({
-$if(controls)$
         // Display controls in the bottom right corner
         controls: $controls$,
-$endif$
-$if(progress)$
+
+        // Help the user learn the controls by providing hints, for example by
+        // bouncing the down arrow when they first encounter a vertical slide
+        controlsTutorial: $controlsTutorial$,
+
+        // Determines where controls appear, "edges" or "bottom-right"
+        controlsLayout: '$controlsLayout$',
+
+        // Visibility rule for backwards navigation arrows; "faded", "hidden"
+        // or "visible"
+        controlsBackArrows: '$controlsBackArrows$',
+
         // Display a presentation progress bar
         progress: $progress$,
-$endif$
-$if(slideNumber)$
+
         // Display the page number of the current slide
         slideNumber: $slideNumber$,
-$endif$
+
+        // 'all', 'print', or 'speaker'
+        showSlideNumber: '$showSlideNumber$',
+
+        // Add the current slide number to the URL hash so that reloading the
+        // page/copying the URL will return you to the same slide
+        hash: $hash$,
+
+        // Start with 1 for the hash rather than 0
+        hashOneBasedIndex: $hashOneBasedIndex$,
+
+        // Flags if we should monitor the hash and change slides accordingly
+        respondToHashChanges: $respondToHashChanges$,
+
         // Push each slide change to the browser history
-$if(history)$
         history: $history$,
-$else$
-        history: true,
-$endif$
-$if(keyboard)$
+
         // Enable keyboard shortcuts for navigation
         keyboard: $keyboard$,
-$endif$
-$if(overview)$
+
         // Enable the slide overview mode
         overview: $overview$,
-$endif$
-$if(center)$
+
+        // Disables the default reveal.js slide layout (scaling and centering)
+        // so that you can use custom CSS layout
+        disableLayout: $disableLayout$,
+
         // Vertical centering of slides
         center: $center$,
-$endif$
-$if(touch)$
+
         // Enables touch navigation on devices with touch input
         touch: $touch$,
-$endif$
-$if(loop)$
+
         // Loop the presentation
         loop: $loop$,
-$endif$
-$if(rtl)$
+
         // Change the presentation direction to be RTL
         rtl: $rtl$,
-$endif$
-$if(fragments)$
+
+        // see https://revealjs.com/vertical-slides/#navigation-mode
+        navigationMode: '$navigationMode$',
+
+        // Randomizes the order of slides each time the presentation loads
+        shuffle: $shuffle$,
+
         // Turns fragments on and off globally
         fragments: $fragments$,
-$endif$
-$if(embedded)$
+
+        // Flags whether to include the current fragment in the URL,
+        // so that reloading brings you to the same fragment position
+        fragmentInURL: $fragmentInURL$,
+
         // Flags if the presentation is running in an embedded mode,
         // i.e. contained within a limited portion of the screen
         embedded: $embedded$,
-$endif$
-$if(help)$
+
         // Flags if we should show a help overlay when the questionmark
         // key is pressed
         help: $help$,
-$endif$
-$if(showNotes)$
+
+        // Flags if it should be possible to pause the presentation (blackout)
+        pause: $pause$,
+
         // Flags if speaker notes should be visible to all viewers
         showNotes: $showNotes$,
-$endif$
-$if(autoSlide)$
+
+        // Global override for autoplaying embedded media (null/true/false)
+        autoPlayMedia: $autoPlayMedia$,
+
+        // Global override for preloading lazy-loaded iframes (null/true/false)
+        preloadIframes: $preloadIframes$,
+
         // Number of milliseconds between automatically proceeding to the
         // next slide, disabled when set to 0, this value can be overwritten
         // by using a data-autoslide attribute on your slides
         autoSlide: $autoSlide$,
-$endif$
-$if(autoSlideStoppable)$
+
         // Stop auto-sliding after user input
         autoSlideStoppable: $autoSlideStoppable$,
-$endif$
-$if(mouseWheel)$
+
+        // Use this method for navigation when auto-sliding
+        autoSlideMethod: $autoSlideMethod$,
+
+        // Specify the average time in seconds that you think you will spend
+        // presenting each slide. This is used to show a pacing timer in the
+        // speaker view
+        defaultTiming: $defaultTiming$,
+
         // Enable slide navigation via mouse wheel
         mouseWheel: $mouseWheel$,
-$endif$
-$if(hideAddressBar)$
-        // Hides the address bar on mobile devices
-        hideAddressBar: $hideAddressBar$,
-$endif$
-$if(previewLinks)$
+
+        // The display mode that will be used to show slides
+        display: '$display$',
+
+        // Hide cursor if inactive
+        hideInactiveCursor: $hideInactiveCursor$,
+
+        // Time before the cursor is hidden (in ms)
+        hideCursorTime: $hideCursorTime$,
+
         // Opens links in an iframe preview overlay
         previewLinks: $previewLinks$,
-$endif$
-$if(transition)$
-        // Transition style
-        transition: '$transition$', // none/fade/slide/convex/concave/zoom
-$endif$
-$if(transitionSpeed)$
-        // Transition speed
-        transitionSpeed: '$transitionSpeed$', // default/fast/slow
-$endif$
-$if(backgroundTransition)$
+
+        // Transition style (none/fade/slide/convex/concave/zoom)
+        transition: '$transition$',
+
+        // Transition speed (default/fast/slow)
+        transitionSpeed: '$transitionSpeed$',
+
         // Transition style for full page slide backgrounds
-        backgroundTransition: '$backgroundTransition$', // none/fade/slide/convex/concave/zoom
-$endif$
-$if(viewDistance)$
+        // (none/fade/slide/convex/concave/zoom)
+        backgroundTransition: '$backgroundTransition$',
+
         // Number of slides away from the current that are visible
         viewDistance: $viewDistance$,
+
+        // Number of slides away from the current that are visible on mobile
+        // devices. It is advisable to set this to a lower number than
+        // viewDistance in order to save resources.
+        mobileViewDistance: $mobileViewDistance$,
+$if(view)$
+
+        // Enable scroll view
+        view: '$view/nowrap$',
+        // see https://revealjs.com/scroll-view/#scrollbar
+$if(scrollProgressAuto)$
+        scrollProgress: 'auto',
+$elseif(scrollProgress)$
+        scrollProgress: $scrollProgress$,
+$else$
+        scrollProgress: false,
 $endif$
+        // see https://revealjs.com/scroll-view/#url-activation
+        scrollActivationWidth: $scrollActivationWidth$,
+        // see https://revealjs.com/scroll-view/#scroll-snapping
+$if(scrollSnap)$
+        scrollSnap: '$scrollSnap/nowrap$',
+$else$
+        scrollSnap: false,
+$endif$
+        // Experimental. see https://revealjs.com/scroll-view/#scroll-snapping
+        scrollLayout: '$scrollLayout/nowrap$',
+$endif$
 $if(parallaxBackgroundImage)$
+
         // Parallax background image
-        parallaxBackgroundImage: '$parallaxBackgroundImage$', // e.g. "'https://s3.amazonaws.com/hakim-static/reveal-js/reveal-parallax-1.jpg'"
+        parallaxBackgroundImage: '$parallaxBackgroundImage/nowrap$', // e.g. "'https://s3.amazonaws.com/hakim-static/reveal-js/reveal-parallax-1.jpg'"
+$else$
+$if(background-image)$
+
+       // Parallax background image
+       parallaxBackgroundImage: '$background-image/nowrap$', // e.g. "'https://s3.amazonaws.com/hakim-static/reveal-js/reveal-parallax-1.jpg'"
 $endif$
+$endif$
 $if(parallaxBackgroundSize)$
+
         // Parallax background size
-        parallaxBackgroundSize: '$parallaxBackgroundSize$', // CSS syntax, e.g. "2100px 900px"
+        parallaxBackgroundSize: '$parallaxBackgroundSize/nowrap$', // CSS syntax, e.g. "2100px 900px"
 $endif$
 $if(parallaxBackgroundHorizontal)$
+
         // Amount to move parallax background (horizontal and vertical) on slide change
         // Number, e.g. 100
-        parallaxBackgroundHorizontal: $parallaxBackgroundHorizontal$,
+        parallaxBackgroundHorizontal: $parallaxBackgroundHorizontal/nowrap$,
 $endif$
 $if(parallaxBackgroundVertical)$
-        parallaxBackgroundVertical: $parallaxBackgroundVertical$,
+
+        parallaxBackgroundVertical: $parallaxBackgroundVertical/nowrap$,
 $endif$
 $if(width)$
+
         // The "normal" size of the presentation, aspect ratio will be preserved
         // when the presentation is scaled to fit different resolutions. Can be
         // specified using percentage units.
         width: $width$,
 $endif$
 $if(height)$
+
         height: $height$,
 $endif$
 $if(margin)$
+
         // Factor of the display size that should remain empty around the content
         margin: $margin$,
 $endif$
 $if(minScale)$
+
         // Bounds for smallest/largest possible scale to apply to content
         minScale: $minScale$,
 $endif$
 $if(maxScale)$
+
         maxScale: $maxScale$,
 $endif$
 $if(mathjax)$
+
         math: {
-          mathjax: 'https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.0/MathJax.js',
+          mathjax: '$mathjaxurl$',
           config: 'TeX-AMS_HTML-full',
           tex2jax: {
             inlineMath: [['\\(','\\)']],
@@ -249,18 +332,17 @@
         },
 $endif$
 
-        // Optional reveal.js plugins
-        dependencies: [
-          { src: '$revealjs-url$/lib/js/classList.js', condition: function() { return !document.body.classList; } },
-          { src: '$revealjs-url$/plugin/zoom-js/zoom.js', async: true },
-$if(notes-server)$
-          { src: '$revealjs-url$/socket.io/socker.io.js', async: true },
-          { src: '$revealjs-url$/plugin/notes-server/client.js', async: true },
-$endif$
+        // reveal.js plugins
+        plugins: [
 $if(mathjax)$
-          { src: '$revealjs-url$/plugin/math/math.js', async: true },
+          RevealMath,
 $endif$
-          { src: '$revealjs-url$/plugin/notes/notes.js', async: true }
+$if(highlight-js)$
+          RevealHighlight,
+$endif$
+          RevealNotes,
+          RevealSearch,
+          RevealZoom
         ]
       });
     </script>
diff --git a/data/templates/default.rst b/data/templates/default.rst
--- a/data/templates/default.rst
+++ b/data/templates/default.rst
@@ -1,24 +1,44 @@
-$if(title)$
-$title$
+$if(titleblock)$
+$titleblock$
 
-$endif$
 $for(author)$
-:Author: $author$
+:Author: $^$$author$
 $endfor$
-$if(date)$
-:Date:   $date$
+$if(authors)$
+:Authors:
+   $author$
 $endif$
-$if(author)$
-
-$else$
 $if(date)$
-
+:Date: $^$$date$
 $endif$
+$if(address)$
+:Address: $^$$address$
 $endif$
-$if(math)$
-.. role:: math(raw)
-   :format: html latex
-..
+$if(contact)$
+:Contact: $^$$contact$
+$endif$
+$if(copyright)$
+:Copyright: $^$$copyright$
+$endif$
+$if(dedication)$
+:Dedication: $^$$dedication$
+$endif$
+$if(organization)$
+:Organization: $^$$organization$
+$endif$
+$if(revision)$
+:Revision: $^$$revision$
+$endif$
+$if(status)$
+:Status: $^$$status$
+$endif$
+$if(version)$
+:Version: $^$$version$
+$endif$
+$if(abstract)$
+:Abstract:
+   $abstract$
+$endif$
 
 $endif$
 $if(rawtex)$
@@ -35,6 +55,10 @@
 .. contents::
    :depth: $toc-depth$
 ..
+
+$endif$
+$if(number-sections)$
+.. section-numbering::
 
 $endif$
 $for(header-includes)$
diff --git a/data/templates/default.rtf b/data/templates/default.rtf
--- a/data/templates/default.rtf
+++ b/data/templates/default.rtf
@@ -1,4 +1,4 @@
-{\rtf1\ansi\deff0{\fonttbl{\f0 \fswiss Helvetica;}{\f1 Courier;}}
+{\rtf1\ansi\deff0{\fonttbl{\f0 \fswiss Helvetica;}{\f1 \fmodern Courier;}}
 {\colortbl;\red255\green0\blue0;\red0\green0\blue255;}
 \widowctrl\hyphauto
 $for(header-includes)$
diff --git a/data/templates/default.s5 b/data/templates/default.s5
--- a/data/templates/default.s5
+++ b/data/templates/default.s5
@@ -16,22 +16,11 @@
 $endif$
   <title>$if(title-prefix)$$title-prefix$ – $endif$$pagetitle$</title>
   <style type="text/css">
-      code{white-space: pre-wrap;}
-      span.smallcaps{font-variant: small-caps;}
-      span.underline{text-decoration: underline;}
-      div.column{display: inline-block; vertical-align: top; width: 50%;}
-$if(quotes)$
-      q { quotes: "“" "”" "‘" "’"; }
-$endif$
+    $styles.html()$
   </style>
   <!-- configuration parameters -->
   <meta name="defaultView" content="slideshow" />
   <meta name="controlVis" content="hidden" />
-$if(highlighting-css)$
-  <style type="text/css">
-$highlighting-css$
-  </style>
-$endif$
 $for(css)$
   <link rel="stylesheet" href="$css$" type="text/css" />
 $endfor$
@@ -71,6 +60,9 @@
 $endif$
 $if(author)$
   <h3 class="author">$for(author)$$author$$sep$<br/>$endfor$</h3>
+$endif$
+$if(institute)$
+  <h3 class="institute">$for(institute)$$institute$$sep$<br/>$endfor$</h3>
 $endif$
 $if(date)$
   <h4 class="date">$date$</h4>
diff --git a/data/templates/default.slideous b/data/templates/default.slideous
--- a/data/templates/default.slideous
+++ b/data/templates/default.slideous
@@ -17,19 +17,8 @@
 $endif$
   <title>$if(title-prefix)$$title-prefix$ – $endif$$pagetitle$</title>
   <style type="text/css">
-      code{white-space: pre-wrap;}
-      span.smallcaps{font-variant: small-caps;}
-      span.underline{text-decoration: underline;}
-      div.column{display: inline-block; vertical-align: top; width: 50%;}
-$if(quotes)$
-      q { quotes: "“" "”" "‘" "’"; }
-$endif$
-  </style>
-$if(highlighting-css)$
-  <style type="text/css">
-$highlighting-css$
+    $styles.html()$
   </style>
-$endif$
   <link rel="stylesheet" type="text/css" media="screen, projection, print"
     href="$slideous-url$/slideous.css" />
 $for(css)$
@@ -74,9 +63,16 @@
 $if(subtitle)$
   <h1 class="subtitle">$subtitle$</h1>
 $endif$
+$if(author)$
   <p class="author">
 $for(author)$$author$$sep$<br/>$endfor$
   </p>
+$endif$
+$if(institute)$
+  <p class="institute">
+$for(institute)$$institute$$sep$<br/>$endfor$
+  </p>
+$endif$
 $if(date)$
   <p class="date">$date$</p>
 $endif$
diff --git a/data/templates/default.slidy b/data/templates/default.slidy
--- a/data/templates/default.slidy
+++ b/data/templates/default.slidy
@@ -17,19 +17,8 @@
 $endif$
   <title>$if(title-prefix)$$title-prefix$ – $endif$$pagetitle$</title>
   <style type="text/css">
-      code{white-space: pre-wrap;}
-      span.smallcaps{font-variant: small-caps;}
-      span.underline{text-decoration: underline;}
-      div.column{display: inline-block; vertical-align: top; width: 50%;}
-$if(quotes)$
-      q { quotes: "“" "”" "‘" "’"; }
-$endif$
-  </style>
-$if(highlighting-css)$
-  <style type="text/css">
-$highlighting-css$
+    $styles.html()$
   </style>
-$endif$
   <link rel="stylesheet" type="text/css" media="screen, projection, print"
     href="$slidy-url$/styles/slidy.css" />
 $for(css)$
@@ -61,6 +50,11 @@
 $if(author)$
   <p class="author">
 $for(author)$$author$$sep$<br/>$endfor$
+  </p>
+$endif$
+$if(institute)$
+  <p class="institute">
+$for(institute)$$institute$$sep$<br/>$endfor$
   </p>
 $endif$
 $if(date)$
diff --git a/data/templates/default.tei b/data/templates/default.tei
--- a/data/templates/default.tei
+++ b/data/templates/default.tei
@@ -3,17 +3,29 @@
 <teiHeader>
   <fileDesc>
     <titleStmt>
-$if(title)$
       <title>$title$</title>
-$endif$
 $for(author)$
-      $author$
+      <author>$author$</author>
 $endfor$
     </titleStmt>
     <publicationStmt>
+$if(publicationStmt)$
       <p>$if(publicationStmt)$$publicationStmt$$endif$</p>
-      $if(license)$
+$endif$
+$if(license)$
       <availability><licence>$license$</licence></availability>
+$endif$
+$if(publisher)$
+      <publisher>$publisher$</publisher>
+$endif$
+$if(pubPlace)$
+      <pubPlace>$pubPlace$</pubPlace>
+$endif$
+$if(address)$
+      <address>$address$</address>
+$endif$
+$if(date)$
+      <date>$date$</date>
 $endif$
     </publicationStmt>
     <sourceDesc>
diff --git a/data/templates/default.texinfo b/data/templates/default.texinfo
--- a/data/templates/default.texinfo
+++ b/data/templates/default.texinfo
@@ -1,4 +1,11 @@
-\input texinfo
+\input texinfo  @c -*-texinfo-*-
+$if(filename)$
+@setfilename $filename$
+$endif$
+$if(title)$
+@settitle $title$$if(version)$ $version$$endif$
+$endif$
+
 @documentencoding UTF-8
 $for(header-includes)$
 $header-includes$
@@ -10,34 +17,15 @@
 @end macro
 
 $endif$
-$if(subscript)$
-@macro textsubscript{text}
-@iftex
-@textsubscript{\text\}
-@end iftex
 @ifnottex
-_@{\text\@}
-@end ifnottex
-@end macro
-
-$endif$
-$if(superscript)$
-@macro textsuperscript{text}
-@iftex
-@textsuperscript{\text\}
-@end iftex
-@ifnottex
-^@{\text\@}
-@end ifnottex
-@end macro
-
-$endif$
-@ifnottex
 @paragraphindent 0
 @end ifnottex
 $if(titlepage)$
 @titlepage
 @title $title$
+$if(version)$
+@subtitle $version$
+$endif$
 $for(author)$
 @author $author$
 $endfor$
diff --git a/data/templates/default.typst b/data/templates/default.typst
new file mode 100644
--- /dev/null
+++ b/data/templates/default.typst
@@ -0,0 +1,154 @@
+#let horizontalrule = line(start: (25%,0%), end: (75%,0%))
+
+#show terms.item: it => block(breakable: false)[
+  #text(weight: "bold")[#it.term]
+  #block(inset: (left: 1.5em, top: -0.4em))[#it.description]
+]
+
+#set table(
+  inset: 6pt,
+  stroke: none
+)
+
+#show figure.where(
+  kind: table
+): set figure.caption(position: $if(table-caption-position)$$table-caption-position$$else$top$endif$)
+
+#show figure.where(
+  kind: image
+): set figure.caption(position: $if(figure-caption-position)$$figure-caption-position$$else$bottom$endif$)
+
+$if(highlighting-definitions)$
+// syntax highlighting functions from skylighting:
+$highlighting-definitions$
+
+$endif$
+$if(template)$
+#import "$template$": conf
+$else$
+$template.typst()$
+$endif$
+
+$if(smart)$
+$else$
+#set smartquote(enabled: false)
+
+$endif$
+$for(header-includes)$
+$header-includes$
+
+$endfor$
+#show: doc => conf(
+$if(title)$
+  title: [$title$],
+$endif$
+$if(subtitle)$
+  subtitle: [$subtitle$],
+$endif$
+$if(author)$
+  authors: (
+$for(author)$
+$if(author.name)$
+    ( name: [$author.name$],
+      affiliation: [$author.affiliation$],
+      email: [$author.email$] ),
+$else$
+    ( name: [$author$],
+      affiliation: "",
+      email: "" ),
+$endif$
+$endfor$
+    ),
+$endif$
+$if(keywords)$
+  keywords: ($for(keywords)$$keywords$$sep$,$endfor$),
+$endif$
+$if(date)$
+  date: [$date$],
+$endif$
+$if(lang)$
+  lang: "$lang$",
+$endif$
+$if(region)$
+  region: "$region$",
+$endif$
+$if(abstract-title)$
+  abstract-title: [$abstract-title$],
+$endif$
+$if(abstract)$
+  abstract: [$abstract$],
+$endif$
+$if(thanks)$
+  thanks: [$thanks$],
+$endif$
+$if(margin)$
+  margin: ($for(margin/pairs)$$margin.key$: $margin.value$,$endfor$),
+$endif$
+$if(papersize)$
+  paper: "$papersize$",
+$endif$
+$if(mainfont)$
+  font: ("$mainfont$",),
+$endif$
+$if(fontsize)$
+  fontsize: $fontsize$,
+$endif$
+$if(mathfont)$
+  mathfont: ($for(mathfont)$"$mathfont$",$endfor$),
+$endif$
+$if(codefont)$
+  codefont: ($for(codefont)$"$codefont$",$endfor$),
+$endif$
+$if(linestretch)$
+  linestretch: $linestretch$,
+$endif$
+$if(section-numbering)$
+  sectionnumbering: "$section-numbering$",
+$endif$
+  pagenumbering: $if(page-numbering)$"$page-numbering$"$else$none$endif$,
+$if(linkcolor)$
+  linkcolor: [$linkcolor$],
+$endif$
+$if(citecolor)$
+  citecolor: [$citecolor$],
+$endif$
+$if(filecolor)$
+  filecolor: [$filecolor$],
+$endif$
+  cols: $if(columns)$$columns$$else$1$endif$,
+  doc,
+)
+
+$for(include-before)$
+$include-before$
+
+$endfor$
+$if(toc)$
+#outline(
+  title: auto,
+  depth: $toc-depth$
+);
+$endif$
+
+$body$
+
+$if(citations)$
+$for(nocite-ids)$
+#cite(label("${it}"), form: none)
+$endfor$
+$if(csl)$
+
+#set bibliography(style: "$csl$")
+$elseif(bibliographystyle)$
+
+#set bibliography(style: "$bibliographystyle$")
+$endif$
+$if(bibliography)$
+
+#bibliography(($for(bibliography)$"$bibliography$"$sep$,$endfor$)$if(full-bibliography)$, full: true$endif$)
+$endif$
+$endif$
+$for(include-after)$
+
+$include-after$
+$endfor$
diff --git a/data/templates/default.vimdoc b/data/templates/default.vimdoc
new file mode 100644
--- /dev/null
+++ b/data/templates/default.vimdoc
@@ -0,0 +1,16 @@
+$if(filename)$*${filename}*	$endif$$if(abstract)$${abstract}$endif$$if(filename)$
+
+
+$endif$$if(combined-title)$${combined-title}
+
+
+$endif$$toc-reminder$
+
+$if(toc)$
+$toc$
+
+$endif$
+
+$body$
+
+ $modeline$
diff --git a/data/templates/default.xwiki b/data/templates/default.xwiki
new file mode 100644
--- /dev/null
+++ b/data/templates/default.xwiki
@@ -0,0 +1,13 @@
+$for(include-before)$
+$include-before$
+
+$endfor$
+$if(toc)$
+{{toc /}}
+
+$endif$
+$body$
+$for(include-after)$
+
+$include-after$
+$endfor$
diff --git a/data/templates/document-metadata.latex b/data/templates/document-metadata.latex
new file mode 100644
--- /dev/null
+++ b/data/templates/document-metadata.latex
@@ -0,0 +1,20 @@
+$--
+$-- PDF standard support (PDF/A, PDF/UA, PDF/X)
+$-- Requires LuaLaTeX and recent LaTeX (2023+)
+$--
+$if(pdfstandard)$
+\DocumentMetadata{
+$if(pdfstandard.version)$
+  pdfversion=$pdfstandard.version$,
+$endif$
+$if(pdfstandard.standards)$
+  pdfstandard={$for(pdfstandard.standards)$$it$$sep$,$endfor$},
+$endif$
+$if(pdfstandard.tagging)$
+  tagging=on,
+$endif$
+$if(lang)$
+  lang=$lang$,
+$endif$
+  xmp=true}
+$endif$
diff --git a/data/templates/font-settings.latex b/data/templates/font-settings.latex
new file mode 100644
--- /dev/null
+++ b/data/templates/font-settings.latex
@@ -0,0 +1,103 @@
+$-- User font settings (must come after default font and Beamer theme)
+$if(fontfamily)$
+\usepackage[$for(fontfamilyoptions)$$fontfamilyoptions$$sep$,$endfor$]{$fontfamily$}
+$endif$
+\ifPDFTeX\else
+  % xetex/luatex font selection
+$if(mainfont)$
+$if(mainfontfallback)$
+  \ifLuaTeX
+    \usepackage{luaotfload}
+    \directlua{luaotfload.add_fallback("mainfontfallback",{
+      $for(mainfontfallback)$"$mainfontfallback$"$sep$,$endfor$
+    })}
+  \fi
+$endif$
+  \setmainfont[$for(mainfontoptions)$$mainfontoptions$$sep$,$endfor$$if(mainfontfallback)$,RawFeature={fallback=mainfontfallback}$endif$]{$mainfont$}
+$endif$
+$if(sansfont)$
+$if(sansfontfallback)$
+  \ifLuaTeX
+    \usepackage{luaotfload}
+    \directlua{luaotfload.add_fallback("sansfontfallback",{
+      $for(sansfontfallback)$"$sansfontfallback$"$sep$,$endfor$
+    })}
+  \fi
+$endif$
+  \setsansfont[$for(sansfontoptions)$$sansfontoptions$$sep$,$endfor$$if(sansfontfallback)$,RawFeature={fallback=sansfontfallback}$endif$]{$sansfont$}
+$endif$
+$if(monofont)$
+$if(monofontfallback)$
+  \ifLuaTeX
+    \usepackage{luaotfload}
+    \directlua{luaotfload.add_fallback("monofontfallback",{
+      $for(monofontfallback)$"$monofontfallback$"$sep$,$endfor$
+    })}
+  \fi
+$endif$
+  \setmonofont[$for(monofontoptions)$$monofontoptions$$sep$,$endfor$$if(monofontfallback)$,RawFeature={fallback=monofontfallback}$endif$]{$monofont$}
+$endif$
+$for(fontfamilies)$
+  \newfontfamily{$fontfamilies.name$}[$for(fontfamilies.options)$$fontfamilies.options$$sep$,$endfor$]{$fontfamilies.font$}
+$endfor$
+$if(mathfont)$
+$if(mathspec)$
+  \ifXeTeX
+    \setmathfont(Digits,Latin,Greek)[$for(mathfontoptions)$$mathfontoptions$$sep$,$endfor$]{$mathfont$}
+  \else
+    \setmathfont[$for(mathfontoptions)$$mathfontoptions$$sep$,$endfor$]{$mathfont$}
+  \fi
+$else$
+  \setmathfont[$for(mathfontoptions)$$mathfontoptions$$sep$,$endfor$]{$mathfont$}
+$endif$
+$endif$
+$if(CJKmainfont)$
+  \ifXeTeX
+    \usepackage{xeCJK}
+    \setCJKmainfont[$for(CJKoptions)$$CJKoptions$$sep$,$endfor$]{$CJKmainfont$}
+$if(CJKsansfont)$
+    \setCJKsansfont[$for(CJKoptions)$$CJKoptions$$sep$,$endfor$]{$CJKsansfont$}
+$endif$
+$if(CJKmonofont)$
+    \setCJKmonofont[$for(CJKoptions)$$CJKoptions$$sep$,$endfor$]{$CJKmonofont$}
+$endif$
+  \fi
+$endif$
+$if(luatexjapresetoptions)$
+  \ifLuaTeX
+    \usepackage[$for(luatexjapresetoptions)$$luatexjapresetoptions$$sep$,$endfor$]{luatexja-preset}
+  \fi
+$endif$
+$if(CJKmainfont)$
+  \ifLuaTeX
+    \usepackage[$for(luatexjafontspecoptions)$$luatexjafontspecoptions$$sep$,$endfor$]{luatexja-fontspec}
+    \setmainjfont[$for(CJKoptions)$$CJKoptions$$sep$,$endfor$]{$CJKmainfont$}
+  \fi
+$endif$
+\fi
+$if(zero-width-non-joiner)$
+%% Support for zero-width non-joiner characters.
+\makeatletter
+\def\zerowidthnonjoiner{%
+  % Prevent ligatures and adjust kerning, but still support hyphenating.
+  \texorpdfstring{%
+    \TextOrMath{\nobreak\discretionary{-}{}{\kern.03em}%
+      \ifvmode\else\nobreak\hskip\z@skip\fi}{}%
+  }{}%
+}
+\makeatother
+\ifPDFTeX
+  \DeclareUnicodeCharacter{200C}{\zerowidthnonjoiner}
+\else
+  \catcode`^^^^200c=\active
+  \protected\def ^^^^200c{\zerowidthnonjoiner}
+\fi
+%% End of ZWNJ support
+$endif$
+% Use upquote if available, for straight quotes in verbatim environments
+\IfFileExists{upquote.sty}{\usepackage{upquote}}{}
+\IfFileExists{microtype.sty}{% use microtype if available
+  \usepackage[$for(microtypeoptions)$$microtypeoptions$$sep$,$endfor$]{microtype}
+  \UseMicrotypeSet[protrusion]{basicmath} % disable protrusion for tt fonts
+}{}
+
diff --git a/data/templates/fonts.latex b/data/templates/fonts.latex
new file mode 100644
--- /dev/null
+++ b/data/templates/fonts.latex
@@ -0,0 +1,23 @@
+\usepackage{iftex}
+\ifPDFTeX
+  \usepackage[$if(fontenc)$$fontenc$$else$T1$endif$]{fontenc}
+  \usepackage[utf8]{inputenc}
+  \usepackage{textcomp} % provide euro and other symbols
+\else % if luatex or xetex
+$if(mathspec)$
+  \ifXeTeX
+    \usepackage{mathspec} % this also loads fontspec
+  \else
+    \usepackage{unicode-math} % this also loads fontspec
+  \fi
+$else$
+  \usepackage{unicode-math} % this also loads fontspec
+$endif$
+  \defaultfontfeatures{Scale=MatchLowercase}$-- must come before Beamer theme
+  \defaultfontfeatures[\rmfamily]{Ligatures=TeX,Scale=1}
+\fi
+$if(fontfamily)$
+$else$
+$-- Set default font before Beamer theme so the theme can override it
+\usepackage{lmodern}
+$endif$
diff --git a/data/templates/hypersetup.latex b/data/templates/hypersetup.latex
new file mode 100644
--- /dev/null
+++ b/data/templates/hypersetup.latex
@@ -0,0 +1,34 @@
+% fallback for those not using the hyperref driver hyperxmp:
+\makeatletter
+\@ifundefined{xmpquote}{\newcommand{\xmpquote}[1]{#1}}{}
+\makeatother
+\hypersetup{
+$if(title-meta)$
+  pdftitle={$title-meta$},
+$endif$
+$if(author-meta)$
+  pdfauthor={$author-meta$},
+$endif$
+$if(lang)$
+  pdflang={$lang$},
+$endif$
+$if(subject)$
+  pdfsubject={$subject$},
+$endif$
+$if(keywords)$
+  pdfkeywords={$for(keywords)$\xmpquote{$keywords$}$sep$, $endfor$},
+$endif$
+$if(colorlinks)$
+  colorlinks=true,
+  linkcolor={$if(linkcolor)$$linkcolor$$else$Maroon$endif$},
+  filecolor={$if(filecolor)$$filecolor$$else$Maroon$endif$},
+  citecolor={$if(citecolor)$$citecolor$$else$Blue$endif$},
+  urlcolor={$if(urlcolor)$$urlcolor$$else$Blue$endif$},
+$else$
+$if(boxlinks)$
+$else$
+  hidelinks,
+$endif$
+$endif$
+  pdfcreator={LaTeX via pandoc}}
+
diff --git a/data/templates/passoptions.latex b/data/templates/passoptions.latex
new file mode 100644
--- /dev/null
+++ b/data/templates/passoptions.latex
@@ -0,0 +1,9 @@
+% Options for packages loaded elsewhere
+\PassOptionsToPackage{unicode$for(hyperrefoptions)$,$hyperrefoptions$$endfor$}{hyperref}
+\PassOptionsToPackage{hyphens}{url}
+$if(colorlinks)$
+\PassOptionsToPackage{dvipsnames,svgnames,x11names}{xcolor}
+$endif$
+$if(CJKmainfont)$
+\PassOptionsToPackage{space}{xeCJK}
+$endif$
diff --git a/data/templates/styles.citations.html b/data/templates/styles.citations.html
new file mode 100644
--- /dev/null
+++ b/data/templates/styles.citations.html
@@ -0,0 +1,23 @@
+/* CSS for citations */
+div.csl-bib-body { }
+div.csl-entry {
+  clear: both;
+$if(csl-entry-spacing)$
+  margin-bottom: $csl-entry-spacing$;
+$endif$
+}
+.hanging-indent div.csl-entry {
+  margin-left:2em;
+  text-indent:-2em;
+}
+div.csl-left-margin {
+  min-width:2em;
+  float:left;
+}
+div.csl-right-inline {
+  margin-left:2em;
+  padding-left:1em;
+}
+div.csl-indent {
+  margin-left: 2em;
+}
diff --git a/data/templates/styles.html b/data/templates/styles.html
new file mode 100644
--- /dev/null
+++ b/data/templates/styles.html
@@ -0,0 +1,216 @@
+/* Default styles provided by pandoc.
+** See https://pandoc.org/MANUAL.html#variables-for-html for config info.
+*/
+$if(document-css)$
+html {
+$if(mainfont)$
+  font-family: $mainfont$;
+$endif$
+$if(fontsize)$
+  font-size: $fontsize$;
+$endif$
+$if(linestretch)$
+  line-height: $linestretch$;
+$endif$
+  color: $if(fontcolor)$$fontcolor$$else$#1a1a1a$endif$;
+  background-color: $if(backgroundcolor)$$backgroundcolor$$else$#fdfdfd$endif$;
+}
+body {
+  margin: 0 auto;
+  max-width: $if(maxwidth)$$maxwidth$$else$36em$endif$;
+  padding-left: $if(margin-left)$$margin-left$$else$50px$endif$;
+  padding-right: $if(margin-right)$$margin-right$$else$50px$endif$;
+  padding-top: $if(margin-top)$$margin-top$$else$50px$endif$;
+  padding-bottom: $if(margin-bottom)$$margin-bottom$$else$50px$endif$;
+  hyphens: auto;
+  overflow-wrap: break-word;
+  text-rendering: optimizeLegibility;
+  font-kerning: normal;
+}
+@media (max-width: 600px) {
+  body {
+    font-size: 0.9em;
+    padding: 12px;
+  }
+  h1 {
+    font-size: 1.8em;
+  }
+}
+@media print {
+  html {
+    background-color: $if(backgroundcolor)$$backgroundcolor$$else$white$endif$;
+  }
+  body {
+    background-color: transparent;
+    color: black;
+    font-size: 12pt;
+  }
+  p, h2, h3 {
+    orphans: 3;
+    widows: 3;
+  }
+  h2, h3, h4 {
+    page-break-after: avoid;
+  }
+}
+p {
+  margin: 1em 0;
+}
+a {
+  color: $if(linkcolor)$$linkcolor$$else$#1a1a1a$endif$;
+}
+a:visited {
+  color: $if(linkcolor)$$linkcolor$$else$#1a1a1a$endif$;
+}
+img {
+  max-width: 100%;
+}
+svg {
+  height: auto;
+  max-width: 100%;
+}
+h1, h2, h3, h4, h5, h6 {
+  margin-top: 1.4em;
+}
+h5, h6 {
+  font-size: 1em;
+  font-style: italic;
+}
+h6 {
+  font-weight: normal;
+}
+ol, ul {
+  padding-left: 1.7em;
+  margin-top: 1em;
+}
+li > ol, li > ul {
+  margin-top: 0;
+}
+blockquote {
+  margin: 1em 0 1em 1.7em;
+  padding-left: 1em;
+  border-left: 2px solid #e6e6e6;
+  color: #606060;
+}
+$if(abstract)$
+div.abstract {
+  margin: 2em 2em 2em 2em;
+  text-align: left;
+  font-size: 85%;
+}
+div.abstract-title {
+  font-weight: bold;
+  text-align: center;
+  padding: 0;
+  margin-bottom: 0.5em;
+}
+$endif$
+code {
+  white-space: pre-wrap;
+  font-family: $if(monofont)$$monofont$$else$Menlo, Monaco, Consolas, 'Lucida Console', monospace$endif$;
+$if(monobackgroundcolor)$
+  background-color: $monobackgroundcolor$;
+  padding: .2em .4em;
+$endif$
+  font-size: 85%;
+  margin: 0;
+  hyphens: manual;
+}
+pre {
+  margin: 1em 0;
+$if(monobackgroundcolor)$
+  background-color: $monobackgroundcolor$;
+  padding: 1em;
+$endif$
+  overflow: auto;
+}
+pre code {
+  padding: 0;
+  overflow: visible;
+  overflow-wrap: normal;
+}
+.sourceCode {
+ background-color: transparent;
+ overflow: visible;
+}
+hr {
+  border: none;
+  border-top: 1px solid #1a1a1a;
+  height: 1px;
+  margin: 1em 0;
+}
+table {
+  margin: 1em 0;
+  border-collapse: collapse;
+  width: 100%;
+  overflow-x: auto;
+  display: block;
+  font-variant-numeric: lining-nums tabular-nums;
+}
+table caption {
+$if(table-caption-below)$
+  caption-side: bottom;
+  margin-top: 0.75em;
+$else$
+  margin-bottom: 0.75em;
+$endif$
+}
+tbody {
+  margin-top: 0.5em;
+  border-top: 1px solid $if(fontcolor)$$fontcolor$$else$#1a1a1a$endif$;
+  border-bottom: 1px solid $if(fontcolor)$$fontcolor$$else$#1a1a1a$endif$;
+}
+th {
+  border-top: 1px solid $if(fontcolor)$$fontcolor$$else$#1a1a1a$endif$;
+  padding: 0.25em 0.5em 0.25em 0.5em;
+}
+td {
+  padding: 0.125em 0.5em 0.25em 0.5em;
+}
+header {
+  margin-bottom: 4em;
+  text-align: center;
+}
+#TOC li {
+  list-style: none;
+}
+#TOC ul {
+  padding-left: 1.3em;
+}
+#TOC > ul {
+  padding-left: 0;
+}
+#TOC a:not(:hover) {
+  text-decoration: none;
+}
+$endif$
+span.smallcaps{font-variant: small-caps;}
+div.columns{display: flex; gap: 1.5em;}
+div.column{flex: auto;}
+@media screen {
+div.columns{gap: min(4vw, 1.5em);}
+div.column{overflow-x: auto;}
+}
+div.hanging-indent{margin-left: 1.5em; text-indent: -1.5em;}
+/* The extra [class] is a hack that increases specificity enough to
+   override a similar rule in reveal.js */
+ul.task-list[class]{list-style: none;}
+ul.task-list li input[type="checkbox"] {
+  font-size: inherit;
+  width: 0.8em;
+  margin: 0 0.8em 0.2em -1.6em;
+  vertical-align: middle;
+}
+$if(quotes)$
+q { quotes: "“" "”" "‘" "’"; }
+$endif$
+$if(displaymath-css)$
+.display.math{display: block; text-align: center; margin: 0.5rem auto;}
+$endif$
+$if(highlighting-css)$
+/* CSS for syntax highlighting */
+$highlighting-css$
+$endif$
+$if(csl-css)$
+$styles.citations.html()$
+$endif$
diff --git a/data/templates/template.typst b/data/templates/template.typst
new file mode 100644
--- /dev/null
+++ b/data/templates/template.typst
@@ -0,0 +1,120 @@
+#let content-to-string(content) = {
+  if content.has("text") {
+    content.text
+  } else if content.has("children") {
+    content.children.map(content-to-string).join("")
+  } else if content.has("body") {
+    content-to-string(content.body)
+  } else if content == [ ] {
+    " "
+  }
+}
+#let conf(
+  title: none,
+  subtitle: none,
+  authors: (),
+  keywords: (),
+  date: none,
+  abstract-title: none,
+  abstract: none,
+  thanks: none,
+  cols: 1,
+  margin: (x: 1.25in, y: 1.25in),
+  paper: "us-letter",
+  lang: "en",
+  region: "US",
+  font: none,
+  fontsize: 11pt,
+  mathfont: none,
+  codefont: none,
+  linestretch: 1,
+  sectionnumbering: none,
+  linkcolor: none,
+  citecolor: none,
+  filecolor: none,
+  pagenumbering: "1",
+  doc,
+) = {
+  set document(
+    title: title,
+    keywords: keywords,
+  )
+  set document(
+      author: authors.map(author => content-to-string(author.name)).join(", ", last: " & "),
+  ) if authors != none and authors != ()
+  set page(
+    paper: paper,
+    margin: margin,
+    numbering: pagenumbering,
+    columns: cols
+  )
+
+  set par(
+    justify: true,
+    leading: linestretch * 0.65em
+  )
+  set text(lang: lang,
+           region: region,
+           size: fontsize)
+
+  set text(font: font) if font != none
+  show math.equation: set text(font: mathfont) if mathfont != none
+  show raw: set text(font: codefont) if codefont != none
+
+  set heading(numbering: sectionnumbering)
+
+  show link: set text(fill: rgb(content-to-string(linkcolor))) if linkcolor != none
+  show ref: set text(fill: rgb(content-to-string(citecolor))) if citecolor != none
+  show link: this => {
+    if filecolor != none and type(this.dest) == label {
+      text(this, fill: rgb(content-to-string(filecolor)))
+    } else {
+      text(this)
+    }
+  }
+
+  if title != none {
+    place(top, float: true, scope: "parent", clearance: 4mm, block(below: 1em, width: 100%)[
+      #if title != none {
+        align(center, block[
+            #text(weight: "bold", size: 1.5em, hyphenate: false)[#title #if thanks != none {
+                footnote(thanks, numbering: "*")
+                counter(footnote).update(n => n - 1)
+              }]
+            #(
+              if subtitle != none {
+                parbreak()
+                text(weight: "bold", size: 1.25em, hyphenate: false)[#subtitle]
+              }
+             )])
+      }
+
+      #if authors != none and authors != [] {
+        let count = authors.len()
+        let ncols = calc.min(count, 3)
+        grid(
+          columns: (1fr,) * ncols,
+          row-gutter: 1.5em,
+          ..authors.map(author => align(center)[
+            #author.name \
+            #author.affiliation \
+            #author.email
+          ])
+        )
+      }
+
+      #if date != none {
+        align(center)[#block(inset: 1em)[
+            #date
+          ]]
+      }
+
+      #if abstract != none {
+        block(inset: 2em)[
+          #text(weight: "semibold")[#abstract-title] #h(1em) #abstract
+        ]
+      }
+    ])
+  }
+  doc
+}
diff --git a/data/translations/af.yaml b/data/translations/af.yaml
new file mode 100644
--- /dev/null
+++ b/data/translations/af.yaml
@@ -0,0 +1,20 @@
+Abstract: Samevatting
+Appendix: Bylae
+Bibliography: Bibliografie
+Cc: a.a.
+Chapter: Hoofstuk
+Contents: Inhoudsopgawe
+Encl: Bylae(n)
+Figure: Figuur
+Index: Inhoud
+ListOfFigures: Lys van figure
+ListOfTables: Lys van tabelle
+Page: Bladsy
+Part: Deel
+Preface: Voorwoord
+Proof: Bewys
+References: Verwysings
+See: sien
+SeeAlso: sien ook
+Table: Tabel
+To: Aan
diff --git a/data/translations/alt.yaml b/data/translations/alt.yaml
new file mode 100644
--- /dev/null
+++ b/data/translations/alt.yaml
@@ -0,0 +1,5 @@
+Chapter: Бажалык
+Contents: Бажалыктар
+Figure: Јурук
+Glossary: Сӧзлик
+Preface: Сӧс бажы
diff --git a/data/translations/ar.yaml b/data/translations/ar.yaml
--- a/data/translations/ar.yaml
+++ b/data/translations/ar.yaml
@@ -1,20 +1,21 @@
-Preface: ﻡﺪﺨﻟ
-References: ﺎﻠﻣﺭﺎﺠﻋ
-Abstract: ﻢﻠﺨﺻ
-Bibliography: ﺎﻠﻤﺻﺍﺩﺭ
-Chapter: ﺏﺎﺑ
-Appendix: ﺎﻠﻣﻼﺤﻗ
-Contents: ﺎﻠﻤﺤﺗﻮﻳﺎﺗ
-ListOfFigures: ﻕﺎﺌﻣﺓ ﺍﻸﺸﻛﺎﻟ
-ListOfTables: ﻕﺎﺌﻣﺓ ﺎﻠﺟﺩﺍﻮﻟ
-Index: ﺎﻠﻔﻫﺮﺳ
-Figure: ﺶﻜﻟ
-Table: ﺝﺩﻮﻟ
-Part: ﺎﻠﻘﺴﻣ
-Encl: ﺎﻠﻣﺮﻔﻗﺎﺗ
-To: ﺈﻟﻯ
-Page: ﺺﻔﺣﺓ
-See: ﺭﺎﺠﻋ
-SeeAlso: ﺭﺎﺠﻋ ﺄﻴﺿًﺍ
-Proof: ﺏﺮﻫﺎﻧ
-Glossary: ﻕﺎﻣﻮﺳ
+Abstract: ملخص
+Appendix: الملاحق
+Bibliography: المصادر
+Cc: نسخة ل‬
+Chapter: باب
+Contents: المحتويات
+Encl: المرفقات
+Figure: شكل
+Glossary: قاموس
+Index: الفهرس
+ListOfFigures: قائمة الأشكال
+ListOfTables: قائمة الجداول
+Page: صفحة
+Part: القسم
+Preface: مدخل
+Proof: برهان
+References: المراجع
+See: راجع
+SeeAlso: راجع أيضًا
+Table: جدول
+To: إلى
diff --git a/data/translations/as.yaml b/data/translations/as.yaml
new file mode 100644
--- /dev/null
+++ b/data/translations/as.yaml
@@ -0,0 +1,21 @@
+Abstract: মূলভাৱ
+Appendix: পৰিশিষ্ট
+Bibliography: তথ্যসূত্ৰ
+Cc: প্ৰতিলিপি
+Chapter: অধ্যায়
+Contents: সমল
+Encl: সংযোজিত
+Figure: চিত্ৰ
+Glossary: অৰ্থকোষ
+Index: বিষয়সূচী
+ListOfFigures: চিত্ৰসূচী
+ListOfTables: তালিকাসূচী
+Page: পৃষ্ঠা
+Part: অংশ
+Preface: পাতনি
+Proof: প্ৰমাণ
+References: প্ৰসংগ
+See: চাওক
+SeeAlso: ও
+Table: তালিকা
+To: মুখে
diff --git a/data/translations/ast.yaml b/data/translations/ast.yaml
new file mode 100644
--- /dev/null
+++ b/data/translations/ast.yaml
@@ -0,0 +1,21 @@
+Abstract: Sumariu
+Appendix: Apéndiz
+Bibliography: Bibliografía
+Cc: cc
+Chapter: Capítulu
+Contents: Conteníu
+Encl: incl.
+Figure: Figura
+Glossary: Glosariu
+Index: Índiz
+ListOfFigures: Llista de figures
+ListOfTables: Llista de tables
+Page: Páxina
+Part: Parte
+Preface: Entamu
+Proof: Demostración
+References: Referencies
+See: ver
+SeeAlso: ver tamién
+Table: Tabla
+To: Pa
diff --git a/data/translations/az.yaml b/data/translations/az.yaml
new file mode 100644
--- /dev/null
+++ b/data/translations/az.yaml
@@ -0,0 +1,21 @@
+Abstract: Annotasiya
+Appendix: Əlavə
+Bibliography: Ədəbiyyat
+Cc: cc
+Chapter: Fəsil
+Contents: Mündəricat
+Encl: encl
+Figure: Şəkil
+Glossary: Terminlər lüğəti
+Index: Mövzu göstəricisi
+ListOfFigures: Şəkillərin siyahısı
+ListOfTables: Cədvəllərin siyahısı
+Page: səh.
+Part: Hissə
+Preface: Ön söz
+Proof: İsbatı
+References: Ədəbiyyat
+See: baxın
+SeeAlso: həmçinin baxın
+Table: Cədvəl
+To: To
diff --git a/data/translations/be.yaml b/data/translations/be.yaml
new file mode 100644
--- /dev/null
+++ b/data/translations/be.yaml
@@ -0,0 +1,21 @@
+Abstract: Анатацыя
+Appendix: Дадатак
+Bibliography: Літаратура
+Cc: зых.
+Chapter: Глава
+Contents: Зьмест
+Encl: укл.
+Figure: Рыс.
+Glossary: Слоўнік тэрмінаў
+Index: Прадметны паказальнік
+ListOfFigures: Сьпіс ілюстрацый
+ListOfTables: Сьпіс табліц
+Page: с.
+Part: Частка
+Preface: Прадмова
+Proof: Доказ
+References: Сьпіс літаратуры
+See: гл.
+SeeAlso: гл. таксама
+Table: Табліца
+To: вх.
diff --git a/data/translations/bg.yaml b/data/translations/bg.yaml
--- a/data/translations/bg.yaml
+++ b/data/translations/bg.yaml
@@ -6,14 +6,16 @@
 Contents: Съдържание
 Encl: Приложения
 Figure: Фигура
-Glossary: Glossary
+Glossary: Притурка
 Index: Азбучен указател
 ListOfFigures: Списък на фигурите
 ListOfTables: Списък на таблиците
 Page: Стр.
+Part: Част
 Preface: Предговор
-Proof: Proof
+Proof: Доказателство
 References: Литература
 See: вж.
-SeeAlso: вж. също и
+SeeAlso: вж. също и
 Table: Таблица
+To: За
diff --git a/data/translations/bo.yaml b/data/translations/bo.yaml
new file mode 100644
--- /dev/null
+++ b/data/translations/bo.yaml
@@ -0,0 +1,14 @@
+Abstract: གནད་བསྡུས།
+Appendix: ཞར་བྱུང་།
+Bibliography: དཔེ་ཆའི་ཐོ་གཞུང་།
+Cc: འདྲ་བཤུས་ལེན་མཁན་
+Chapter: ལེའུ་
+Contents: དཀར་ཆག།
+Figure: པར་རིས་
+Glossary: མིང་ཚིག་རེའུ་མིག།
+Index: གསུལ་བྱང་།
+Page: ཤོག་
+Part: ཆ་ཤས་
+Preface: དཔེ་དེབ་ཀྱི་གླེང་བརྗོད།
+Proof: བདེན་དཔང་།
+Table: རེའུ་མིག་
diff --git a/data/translations/br.yaml b/data/translations/br.yaml
new file mode 100644
--- /dev/null
+++ b/data/translations/br.yaml
@@ -0,0 +1,21 @@
+Abstract: Dvierrañ
+Appendix: Stagadenn
+Bibliography: Lennadurezh
+Cc: Eilskrid da
+Chapter: Pennad
+Contents: Taolenn
+Encl: Dielloù kevret
+Figure: Figurenn
+Glossary: Glossary
+Index: Meneger
+ListOfFigures: Listenn ar Figurennoù
+ListOfTables: Listenn an taolennoù
+Page: Pajenn
+Part: Lodenn
+Preface: Rakskrid
+Proof: Proof
+References: Daveennoù
+See: Gwelout
+SeeAlso: Gwelout ivez
+Table: Taolenn
+To: evit
diff --git a/data/translations/bs.yaml b/data/translations/bs.yaml
new file mode 100644
--- /dev/null
+++ b/data/translations/bs.yaml
@@ -0,0 +1,21 @@
+Abstract: Sažetak
+Appendix: Dodatak
+Bibliography: Bibliografija
+Cc: Kopija
+Chapter: Poglavlje
+Contents: Sadržaj
+Encl: Prilozi
+Figure: Slika
+Glossary: Rječnik
+Index: Indeks
+ListOfFigures: Popis slika
+ListOfTables: Popis tabela
+Page: Stranica
+Part: Dio
+Preface: Predgovor
+Proof: Dokaz
+References: Literatura
+See: Vidjeti
+SeeAlso: Također vidjeti
+Table: Tabela
+To: Prima
diff --git a/data/translations/bua.yaml b/data/translations/bua.yaml
new file mode 100644
--- /dev/null
+++ b/data/translations/bua.yaml
@@ -0,0 +1,17 @@
+Abstract: Тобшолол
+Appendix: Хабсаралта
+Bibliography: Ном зүй
+Chapter: Бүлэг
+Contents: Гаршаг
+Encl: Оруулаха
+Figure: Зураг
+Index: Бүгэд хэлхээс
+ListOfFigures: Зурагай жагсаалт
+ListOfTables: Хүснэгэтэй жагсаалт
+Page: Хуудаһан
+Part: Бүлэг
+Preface: Оршол
+References: Ашаглаһан ном
+See: Үз
+SeeAlso: Mүн үз
+Table: Хүсэнэгт
diff --git a/data/translations/ckb-Arab.yaml b/data/translations/ckb-Arab.yaml
new file mode 100644
--- /dev/null
+++ b/data/translations/ckb-Arab.yaml
@@ -0,0 +1,21 @@
+Abstract: پوختە
+Appendix: پاشکۆ
+Bibliography: کتێبنامە
+Cc: ڕوونووس
+Chapter: بەندی
+Contents: نێوەڕۆک
+Encl: هاوپێچ
+Figure: وێنەی
+Glossary: فەرهەنگۆک
+Index: پێنوێن
+ListOfFigures: لیستی وێنەکان
+ListOfTables: لیستی خشتەکان
+Page: لاپەڕە
+Part: بەشی
+Preface: پێشەكی
+Proof: سەلماندن
+References: سەرچاوەکان
+See: چاو لێکەن
+SeeAlso: هەروەها چاو لێکەن
+Table: خشتەی
+To: بۆ
diff --git a/data/translations/ckb-Latn.yaml b/data/translations/ckb-Latn.yaml
new file mode 100644
--- /dev/null
+++ b/data/translations/ckb-Latn.yaml
@@ -0,0 +1,21 @@
+Abstract: Puxte
+Appendix: Paşko
+Bibliography: Kitêbname
+Cc: Rûnûs
+Chapter: Bendî
+Contents: Nêwerrok
+Encl: Hawpêç
+Figure: Wêney
+Glossary: Ferhengok
+Index: Pêrrist
+ListOfFigures: Lîstî Wênekan
+ListOfTables: Lîstî Xiştekan
+Page: Laperre
+Part: Beşî
+Preface: Pêşekî
+Proof: Selmandin
+References: Serçawekan
+See: Çaw lêken
+SeeAlso: Herweha çaw lêken
+Table: Xiştey
+To: Bo
diff --git a/data/translations/cs.yaml b/data/translations/cs.yaml
--- a/data/translations/cs.yaml
+++ b/data/translations/cs.yaml
@@ -1,13 +1,13 @@
 Abstract: Abstrakt
-Appendix: Dodatek
+Appendix: Příloha
 Bibliography: Literatura
-Cc: Na vědomí:
+Cc: Na vědomí
 Chapter: Kapitola
 Contents: Obsah
 Encl: Příloha
 Figure: Obrázek
 Glossary: Slovník
-Index: Index
+Index: Rejstřík
 ListOfFigures: Seznam obrázků
 ListOfTables: Seznam tabulek
 Page: Strana
@@ -16,6 +16,6 @@
 Proof: Důkaz
 References: Reference
 See: viz
-SeeAlso: viz
+SeeAlso: viz také
 Table: Tabulka
 To: Komu
diff --git a/data/translations/cu.yaml b/data/translations/cu.yaml
new file mode 100644
--- /dev/null
+++ b/data/translations/cu.yaml
@@ -0,0 +1,21 @@
+Abstract: Аннотация
+Appendix: Приложение
+Bibliography: Литература
+Cc: исх.
+Chapter: Глава
+Contents: Содержание
+Encl: вкл.
+Figure: Рис.
+Glossary: Словарь терминов
+Index: Предметный указатель
+ListOfFigures: Список иллюстраций
+ListOfTables: Список таблиц
+Page: с.
+Part: Часть
+Preface: Предисловие
+Proof: Доказательство
+References: Список литературы
+See: см.
+SeeAlso: см. также
+Table: Таблица
+To: вх.
diff --git a/data/translations/cy.yaml b/data/translations/cy.yaml
new file mode 100644
--- /dev/null
+++ b/data/translations/cy.yaml
@@ -0,0 +1,21 @@
+Abstract: Crynodeb
+Appendix: Atodiad
+Bibliography: Llyfryddiaeth
+Cc: copïau
+Chapter: Pennod
+Contents: Cynnwys
+Encl: amgaeëdig
+Figure: Darlun
+Glossary: Rhestr termau
+Index: Mynegai
+ListOfFigures: Rhestr Ddarluniau
+ListOfTables: Rhestr Dablau
+Page: tudalen
+Part: Rhan
+Preface: Rhagair
+Proof: Prawf
+References: Cyfeiriadau
+See: gweler
+SeeAlso: gweler hefyd
+Table: Taflen
+To: At
diff --git a/data/translations/cz.yaml b/data/translations/cz.yaml
new file mode 100644
--- /dev/null
+++ b/data/translations/cz.yaml
@@ -0,0 +1,21 @@
+Abstract: Abstrakt
+Appendix: Dodatek
+Bibliography: Literatura
+Cc: Na vědomí
+Chapter: Kapitola
+Contents: Obsah
+Encl: Příloha
+Figure: Obrázek
+Glossary: Slovník
+Index: Index
+ListOfFigures: Seznam obrázků
+ListOfTables: Seznam tabulek
+Page: Strana
+Part: Část
+Preface: Předmluva
+Proof: Důkaz
+References: Reference
+See: viz
+SeeAlso: viz
+Table: Tabulka
+To: Komu
diff --git a/data/translations/da.yaml b/data/translations/da.yaml
--- a/data/translations/da.yaml
+++ b/data/translations/da.yaml
@@ -1,7 +1,7 @@
 Abstract: Resumé
 Appendix: Bilag
 Bibliography: Litteratur
-Cc: Kopi til}
+Cc: Kopi til
 Chapter: Kapitel
 Contents: Indhold
 Encl: Vedlagt
@@ -18,4 +18,4 @@
 See: Se
 SeeAlso: Se også
 Table: Tabel
-To: Til}
+To: Til
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/dsb.yaml b/data/translations/dsb.yaml
new file mode 100644
--- /dev/null
+++ b/data/translations/dsb.yaml
@@ -0,0 +1,21 @@
+Abstract: Abstrakt
+Appendix: Dodawki
+Bibliography: Literatura
+Cc: CC
+Chapter: Kapitl
+Contents: Wopśimjeśe
+Encl: Pśiłoga
+Figure: Wobraz
+Glossary: Glossary
+Index: Indeks
+ListOfFigures: Zapis wobrazow
+ListOfTables: Zapis tabulkow
+Page: Strona
+Part: Źěl
+Preface: Zawod
+Proof: Proof
+References: Referency
+See: gl.
+SeeAlso: gl.~teke
+Table: Tabulka
+To: Komu
diff --git a/data/translations/el.yaml b/data/translations/el.yaml
--- a/data/translations/el.yaml
+++ b/data/translations/el.yaml
@@ -8,8 +8,8 @@
 Figure: Σχήμα
 Glossary: Γλωσσάρι
 Index: Ευρετήριο
-ListOfFigures: Κατάλογος σχημάτων
-ListOfTables: Κατάλογος πινάκων
+ListOfFigures: Κατάλογος Σχημάτων
+ListOfTables: Κατάλογος Πινάκων
 Page: Σελίδα
 Part: Μέρος
 Preface: Πρόλογος
diff --git a/data/translations/en.yaml b/data/translations/en.yaml
--- a/data/translations/en.yaml
+++ b/data/translations/en.yaml
@@ -8,8 +8,9 @@
 Figure: Figure
 Glossary: Glossary
 Index: Index
-ListOfFigures: ListOfFigures
-ListOfTables: ListOfTables
+Listing: Listing
+ListOfFigures: List of Figures
+ListOfTables: List of Tables
 Page: page
 Part: Part
 Preface: Preface
@@ -19,4 +20,3 @@
 SeeAlso: see also
 Table: Table
 To: To
-Listing: Listing
diff --git a/data/translations/eo.yaml b/data/translations/eo.yaml
--- a/data/translations/eo.yaml
+++ b/data/translations/eo.yaml
@@ -11,10 +11,11 @@
 ListOfFigures: Listo de figuroj
 ListOfTables: Listo de tabeloj
 Page: Paĝo
+Part: Parto
 Preface: Antaŭparolo
 Proof: Pruvo
 References: Citaĵoj
 See: vidu
-SeeAlso: Parto
+SeeAlso: vidu ankaŭ
 Table: Tabelo
 To: Al
diff --git a/data/translations/es-ES.yaml b/data/translations/es-ES.yaml
new file mode 100644
--- /dev/null
+++ b/data/translations/es-ES.yaml
@@ -0,0 +1,21 @@
+Abstract: Resumen
+Appendix: Apéndice
+Bibliography: Bibliografía
+Cc: Copia a
+Chapter: Capítulo
+Contents: Índice general
+Encl: Adjunto(s)
+Figure: Figura
+Glossary: Glosario
+Index: Índice alfabético
+ListOfFigures: Índice de figuras
+ListOfTables: Índice de cuadros
+Page: Página
+Part: Parte
+Preface: Prefacio
+Proof: Prueba
+References: Referencias
+See: véase
+SeeAlso: véase también
+Table: Cuadro
+To: A
diff --git a/data/translations/es-MX.yaml b/data/translations/es-MX.yaml
new file mode 100644
--- /dev/null
+++ b/data/translations/es-MX.yaml
@@ -0,0 +1,21 @@
+Abstract: Resumen
+Appendix: Apéndice
+Bibliography: Bibliografía
+Cc: Copia a
+Chapter: Capítulo
+Contents: Índice
+Encl: Anexo
+Figure: Figura
+Glossary: Glosario
+Index: Índice Alfabético
+ListOfFigures: Índice de Figuras
+ListOfTables: Índice de Cuadros
+Page: Página
+Part: Parte
+Preface: Prefacio
+Proof: Demostración
+References: Referencias
+See: véase
+SeeAlso: véase también
+Table: Cuadro
+To: A
diff --git a/data/translations/es.yaml b/data/translations/es.yaml
--- a/data/translations/es.yaml
+++ b/data/translations/es.yaml
@@ -3,17 +3,17 @@
 Bibliography: Bibliografía
 Cc: Copia a
 Chapter: Capítulo
-Contents: Índice general
-Encl: Adjunto(s)
+Contents: Índice
+Encl: Adjunto
 Figure: Figura
 Glossary: Glosario
 Index: Índice alfabético
 ListOfFigures: Índice de figuras
 ListOfTables: Índice de cuadros
-Page: Página
+Page: página
 Part: Parte
 Preface: Prefacio
-Proof: Prueba
+Proof: Demostración
 References: Referencias
 See: véase
 SeeAlso: véase también
diff --git a/data/translations/et.yaml b/data/translations/et.yaml
--- a/data/translations/et.yaml
+++ b/data/translations/et.yaml
@@ -6,8 +6,9 @@
 Contents: Sisukord
 Encl: Lisa(d)
 Figure: Joonis
-Glossary: Glossary
+Glossary: Sõnastik
 Index: Indeks
+Listing: Kood
 ListOfFigures: Joonised
 ListOfTables: Tabelid
 Page: Lk.
@@ -18,3 +19,4 @@
 See: vt.
 SeeAlso: vt. ka
 Table: Tabel
+To: Saaja
diff --git a/data/translations/fa.yaml b/data/translations/fa.yaml
--- a/data/translations/fa.yaml
+++ b/data/translations/fa.yaml
@@ -1,21 +1,21 @@
-Abstract: چکیﺪﻫ
-Appendix: پیﻮﺴﺗ
-Bibliography: کﺕﺎﺑc>ﻧﺎﻤﻫ
-Cc: ﺭﻮﻧﻮﺸﺗ
-Chapter: ﻒﺼﻟ
-Contents: ﻒﻫﺮﺴﺗ ﻢﻃﺎﻠﺑ
-Encl: پیﻮﺴﺗ
-Figure: ﺶﻜﻟ
-Glossary: ﺩﺎﻨﺷc>ﻧﺎﻤﻫ
-Index: ﻦﻣﺍیﻩ
-ListOfFigures: ﻝیﺲﺗ ﺖﺻﺍﻭیﺭ
-ListOfTables: ﻝیﺲﺗ ﺝﺩﺍﻮﻟ
-Page: ﺺﻔﺣﺓ
-Part: ﺐﺨﺷ
-Preface: پیﺵگﻒﺗﺍﺭ
-Proof: ﺏﺮﻫﺎﻧ
-References: ﻡﺭﺎﺠﻋ
-See: ﺐﺑیﻥیﺩ
-SeeAlso: ﻥیﺯ ﺐﺑیﻥیﺩ
-Table: ﺝﺩﻮﻟ
-To: ﺐﻫ
+Abstract: چکیده
+Appendix: پیوست
+Bibliography: کتاب‌نامه
+Cc: رونوشت
+Chapter: فصل
+Contents: فهرست
+Encl: پیوست
+Figure: شكل
+Glossary: فرهنگ‌نامه
+Index: نمایه
+ListOfFigures: فهرست شکل‌ها
+ListOfTables: فهرست جدول‌ها
+Page: صفحه
+Part: بخش
+Preface: پیش‌گفتار
+Proof: اثبات
+References: مرجع‌ها
+See: ببینید
+SeeAlso: نیز ببینید
+Table: جدول
+To: به
diff --git a/data/translations/fi.yaml b/data/translations/fi.yaml
--- a/data/translations/fi.yaml
+++ b/data/translations/fi.yaml
@@ -3,7 +3,7 @@
 Bibliography: Kirjallisuutta
 Cc: Jakelu
 Chapter: Luku
-Contents: Sisältö
+Contents: Sisällys
 Encl: Liitteet
 Figure: Kuva
 Glossary: Sanasto
diff --git a/data/translations/fil.yaml b/data/translations/fil.yaml
new file mode 100644
--- /dev/null
+++ b/data/translations/fil.yaml
@@ -0,0 +1,18 @@
+Abstract: Abstrak
+Appendix: Hugpong
+Bibliography: Talaaklatan
+Chapter: Kabanata
+Contents: Talalamanan
+Figure: Laraw
+Glossary: Glosaryo
+Index: Talatuntunan
+ListOfFigures: Talalarawan
+ListOfTables: Talatalayan
+Page: Pahina
+Part: Bahagi
+Preface: Paunang Salita
+Proof: Patunay
+References: Talasanggunian
+See: tignan ang
+SeeAlso: tignan din
+Table: Talay
diff --git a/data/translations/fr.yaml b/data/translations/fr.yaml
--- a/data/translations/fr.yaml
+++ b/data/translations/fr.yaml
@@ -1,20 +1,20 @@
 Abstract: Résumé
 Appendix: Annexe
 Bibliography: Bibliographie
-Cc: Copie à
-Chapter: Chaptire
+Cc: Cc
+Chapter: Chapitre
 Contents: Table des matières
-Figure: Fig.
-Glossary:
+Figure: Figure
+Glossary: Glossaire
 Index: Index
 ListOfFigures: Table des figures
 ListOfTables: Liste des tableaux
-Page: page
-Part: partie
+Page: Page
+Part: Partie
 Preface: Préface
 Proof: Démonstration
 References: Références
-See: voir
-SeeAlso: voir aussi
-Table: Tab.
-To:
+See: Voir
+SeeAlso: Voir aussi
+Table: Tableau
+To: À
diff --git a/data/translations/fur.yaml b/data/translations/fur.yaml
new file mode 100644
--- /dev/null
+++ b/data/translations/fur.yaml
@@ -0,0 +1,21 @@
+Abstract: Somari
+Appendix: Zonte
+Bibliography: Bibliografie
+Cc: Cun copie a
+Chapter: Cjapitul
+Contents: Tabele gjenerâl
+Encl: Zonte(is)
+Figure: Figure
+Glossary: Glossari
+Index: Tabele analitiche
+ListOfFigures: Liste des figuris
+ListOfTables: Liste des tabelis
+Page: Pagjine
+Part: Part
+Preface: Prefazion
+Proof: Dimostrazion
+References: Riferiments
+See: cjale
+SeeAlso: cjale ancje
+Table: Tabele
+To: Par
diff --git a/data/translations/ga.yaml b/data/translations/ga.yaml
new file mode 100644
--- /dev/null
+++ b/data/translations/ga.yaml
@@ -0,0 +1,21 @@
+Abstract: Achoimre
+Appendix: Aguisín
+Bibliography: Leabharliosta
+Cc: cc
+Chapter: Caibidil
+Contents: Clár Ábhair
+Encl: faoi iamh
+Figure: Léaráid
+Glossary: Glossary
+Index: Innéacs
+ListOfFigures: Léaráidí
+ListOfTables: Táblaí
+Page: Leathanach
+Part: Cuid
+Preface: Réamhrá
+Proof: Cruthúnas
+References: Tagairtí
+See: féach
+SeeAlso: féach freisin
+Table: Tábla
+To: Go
diff --git a/data/translations/gd.yaml b/data/translations/gd.yaml
new file mode 100644
--- /dev/null
+++ b/data/translations/gd.yaml
@@ -0,0 +1,21 @@
+Abstract: Brìgh
+Appendix: Ath-sgr`ıobhadh
+Bibliography: Leabhraichean
+Cc: lethbhreac gu
+Chapter: Caibideil
+Contents: Clàr-obrach
+Encl: a-staigh
+Figure: Dealbh
+Glossary: Glossary
+Index: Clàr-innse
+ListOfFigures: Liosta Dhealbh
+ListOfTables: Liosta Chlàr
+Page: t.d.
+Part: Cuid
+Preface: Preface
+Proof: Proof
+References: Iomraidh
+See: see
+SeeAlso: see also
+Table: Clàr
+To: gu
diff --git a/data/translations/gl.yaml b/data/translations/gl.yaml
new file mode 100644
--- /dev/null
+++ b/data/translations/gl.yaml
@@ -0,0 +1,21 @@
+Abstract: Resumo
+Appendix: Apéndice
+Bibliography: Bibliografía
+Cc: Copia a
+Chapter: Capítulo
+Contents: Índice
+Encl: Adxunto
+Figure: Figura
+Glossary: Glosario
+Index: Índice alfabético
+ListOfFigures: Índice de figuras
+ListOfTables: Índice de cadros
+Page: Páxina
+Part: Parte
+Preface: Prefacio
+Proof: Demostración
+References: Referencias
+See: véxase
+SeeAlso: véxase tamén
+Table: Cadro
+To: A
diff --git a/data/translations/grc.yaml b/data/translations/grc.yaml
new file mode 100644
--- /dev/null
+++ b/data/translations/grc.yaml
@@ -0,0 +1,21 @@
+Abstract: Περίληψις
+Appendix: Παράρτημα
+Bibliography: Βιβλιογραφία
+Cc: Κοινοποίησις
+Chapter: Κεφάλαιον
+Contents: Περιεχόμενα
+Encl: Συνημμένως
+Figure: Σχῆμα
+Glossary: Γλωσσάριον
+Index: Εὑρετήριον
+ListOfFigures: Κατάλογος σχημάτων
+ListOfTables: Κατάλογος πινάκων
+Page: Σελὶς
+Part: Μέρος
+Preface: Προοίμιον
+Proof: Ἀπόδειξις
+References: Ἀναφοραὶ
+See: ὃρα
+SeeAlso: ὃρα ὡσαύτως
+Table: Πίναξ
+To: Πρὸς
diff --git a/data/translations/gu.yaml b/data/translations/gu.yaml
new file mode 100644
--- /dev/null
+++ b/data/translations/gu.yaml
@@ -0,0 +1,9 @@
+Appendix: અનુસૂચિ
+Chapter: પ્રકરણ
+Index: અનુક્રમણિકા
+Page: પાનુ
+Part: ભાગ
+Proof: પુરાવો
+See: જુવો
+SeeAlso: ઉપરાંત
+Table: ટેબલ
diff --git a/data/translations/ha.yaml b/data/translations/ha.yaml
new file mode 100644
--- /dev/null
+++ b/data/translations/ha.yaml
@@ -0,0 +1,21 @@
+Abstract: Taƙaitawa
+Appendix: Ƙarin bayani
+Bibliography: Fahirinsa
+Cc: cc
+Chapter: Babi
+Contents: Abin da ke ciki
+Encl: saƙe
+Figure: Addadi
+Glossary: Ƙamus
+Index: Fihirinsa
+ListOfFigures: Tsarin Addadi
+ListOfTables: Tsarin tabili
+Page: Shafi
+Part: Kashi
+Preface: Gabatarwa
+Proof: Shaida
+References: Nassoshi
+See: duba
+SeeAlso: kuma
+Table: tabili
+To: je
diff --git a/data/translations/he.yaml b/data/translations/he.yaml
--- a/data/translations/he.yaml
+++ b/data/translations/he.yaml
@@ -6,17 +6,16 @@
 Contents: תוכן העניינים
 Encl: רצ"ב
 Figure: איור
-Glossary: מילון מונחים}
+Glossary: מילון מונחים
 Index: מפתח
 ListOfFigures: רשימת האיורים
 ListOfTables: רשימת הטבלאות
 Page: עמוד
 Part: חלק
 Preface: מבוא
-Proof: הוכחה}
-Ps: נ.ב.
+Proof: הוכחה
 References: מקורות
 See: ראה
-SeeAlso: ראה גם}
+SeeAlso: ראה גם
 Table: טבלה
 To: אל
diff --git a/data/translations/hi.yaml b/data/translations/hi.yaml
--- a/data/translations/hi.yaml
+++ b/data/translations/hi.yaml
@@ -1,20 +1,18 @@
 Abstract: सारांश
 Appendix: परिशिष्ट
-Bibliography: संदर ग्रन्थ}
-Cc: 
+Bibliography: संदर्भ-ग्रन्थ
 Chapter: अध्याय
-Contents: विषय सूची
-Encl: 
-Figure: चित्र}
-Headpage: पृषठ
+Contents: अनुक्रम
+Figure: चित्र
+Glossary: शब्दार्थ सूची
 Index: सूची
 ListOfFigures: चित्रों की सूची
 ListOfTables: तालिकाओं की सूची
-Page: पृषठ
-Part: खणड
-Preface: प्रस्तावना}
+Page: पृष्ठ
+Part: खण्ड
+Preface: प्रस्तावना
+Proof: प्रमाण
 References: हवाले
 See: देखिए
 SeeAlso: और देखिए
 Table: तालिका
-To: 
diff --git a/data/translations/hsb.yaml b/data/translations/hsb.yaml
new file mode 100644
--- /dev/null
+++ b/data/translations/hsb.yaml
@@ -0,0 +1,21 @@
+Abstract: Abstrakt
+Appendix: Dodawki
+Bibliography: Literatura
+Cc: CC
+Chapter: Kapitl
+Contents: Wobsah
+Encl: Přłoha
+Figure: Wobraz
+Glossary: Glossary
+Index: Indeks
+ListOfFigures: Zapis wobrazow
+ListOfTables: Zapis tabulkow
+Page: Strona
+Part: Dźěl
+Preface: Zawod
+Proof: Proof
+References: Referency
+See: hl.
+SeeAlso: hl.~tež
+Table: Tabulka
+To: Komu
diff --git a/data/translations/hu.yaml b/data/translations/hu.yaml
--- a/data/translations/hu.yaml
+++ b/data/translations/hu.yaml
@@ -1,5 +1,5 @@
 Abstract: Kivonat
-Appendix: Függelék
+Appendix: függelék
 Bibliography: Irodalomjegyzék
 Cc: Körlevél–címzettek
 Chapter: fejezet
diff --git a/data/translations/hy.yaml b/data/translations/hy.yaml
new file mode 100644
--- /dev/null
+++ b/data/translations/hy.yaml
@@ -0,0 +1,20 @@
+Abstract: Սեղմագիր
+Appendix: Հավելված
+Bibliography: Գրականություն
+Cc: Կրկնօրինակը՝
+Chapter: Գլուխ
+Contents: Բովանդակություն
+Encl: Կից՝
+Figure: Նկար
+Glossary: Տերմինների ցանկ
+Index: Առարկայական ցանկ
+ListOfFigures: Նկարների ցանկ
+ListOfTables: Աղյուսակների ցանկ
+Page: էջ
+Part: Մաս
+Preface: Նախաբան
+Proof: Ապացույց
+References: Հղումներ
+See: տե՛ս
+SeeAlso: տե՛ս նաև
+Table: Աղյուսակ
diff --git a/data/translations/ia.yaml b/data/translations/ia.yaml
new file mode 100644
--- /dev/null
+++ b/data/translations/ia.yaml
@@ -0,0 +1,21 @@
+Abstract: Summario
+Appendix: Appendice
+Bibliography: Bibliographia
+Cc: Copia
+Chapter: Capitulo
+Contents: Contento
+Encl: Incluso
+Figure: Figura
+Glossary: Glossario
+Index: Indice
+ListOfFigures: Lista de figuras
+ListOfTables: Lista de tabellas
+Page: Pagina
+Part: Parte
+Preface: Prefacio
+Proof: Prova
+References: Referentias
+See: vide
+SeeAlso: vide etiam
+Table: Tabella
+To: A
diff --git a/data/translations/id.yaml b/data/translations/id.yaml
new file mode 100644
--- /dev/null
+++ b/data/translations/id.yaml
@@ -0,0 +1,21 @@
+Abstract: Ringkasan
+Appendix: Lampiran
+Bibliography: Bibliografi
+Cc: cc
+Chapter: Bab
+Contents: Daftar Isi
+Encl: Lampiran
+Figure: Gambar
+Glossary: Daftar Istilah
+Index: Indeks
+ListOfFigures: Daftar Gambar
+ListOfTables: Daftar Tabel
+Page: Halaman
+Part: Bagian
+Preface: Pendahuluan
+Proof: Bukti
+References: Pustaka
+See: lihat
+SeeAlso: lihat juga
+Table: Tabel
+To: Kepada
diff --git a/data/translations/is.yaml b/data/translations/is.yaml
--- a/data/translations/is.yaml
+++ b/data/translations/is.yaml
@@ -18,4 +18,4 @@
 See: Sjá
 SeeAlso: Sjá einnig
 Table: Tafla
-To: Til:
+To: Til
diff --git a/data/translations/it.yaml b/data/translations/it.yaml
--- a/data/translations/it.yaml
+++ b/data/translations/it.yaml
@@ -1,7 +1,7 @@
 Abstract: Sommario
 Appendix: Appendice
 Bibliography: Bibliografia
-Cc: e p. c.
+Cc: e~p.~c.
 Chapter: Capitolo
 Contents: Indice
 Encl: Allegati
diff --git a/data/translations/ja.yaml b/data/translations/ja.yaml
new file mode 100644
--- /dev/null
+++ b/data/translations/ja.yaml
@@ -0,0 +1,21 @@
+Abstract: 概要
+Appendix: 付録
+Bibliography: 文献目録
+Cc: 同報
+Chapter: 章
+Contents: 目次
+Encl: 添付
+Figure: 図
+Glossary: 用語集
+Index: 索引
+ListOfFigures: 図目次
+ListOfTables: 表目次
+Page: 頁
+Part: 部
+Preface: 端書き
+Proof: 証明
+References: 参考文献
+See: 参照
+SeeAlso: 参照
+Table: 表
+To: 宛先
diff --git a/data/translations/ka.yaml b/data/translations/ka.yaml
new file mode 100644
--- /dev/null
+++ b/data/translations/ka.yaml
@@ -0,0 +1,21 @@
+Abstract: ანოტაცია
+Appendix: დანართი
+Bibliography: ლიტერატურა
+Cc: წყარ.
+Chapter: თავი
+Contents: შინაარსი
+Encl: ჩათვ.
+Figure: სურ.
+Glossary: ტერმინები
+Index: საძიებელი
+ListOfFigures: სურათი
+ListOfTables: ცხრილი
+Page: გვ.
+Part: ნაწილი
+Preface: წინასიტყვაობა
+Proof: დამტკიცება
+References: ლიტერატურა
+See: იხ.
+SeeAlso: იხ. ასევე
+Table: ცხრ.
+To: შ.
diff --git a/data/translations/kmr-Arab.yaml b/data/translations/kmr-Arab.yaml
new file mode 100644
--- /dev/null
+++ b/data/translations/kmr-Arab.yaml
@@ -0,0 +1,21 @@
+Abstract: کورتەبیر
+Appendix: پاشکۆ
+Bibliography: چاڤکانییا پرتووکان
+Cc: بەلاڤکەر
+Chapter: سەرێ
+Contents: ناڤێرۆک
+Encl: دوماهک
+Figure: دیمەنێ
+Glossary: چاڤکانییا لێکۆلینێ
+Index: پێرست
+ListOfFigures: هەژمارا دیمەنا
+ListOfTables: هەژمارا کەڤالێن
+Page: رووپەلێ
+Part: بەشا
+Preface: پێشگۆتن
+Proof: دەلیل
+References: پرتووکێن بژارتی
+See: بنێرا
+SeeAlso: لە ڤێیا ژ بنێرا
+Table: کەڤالا
+To: ژ بۆ
diff --git a/data/translations/kmr-Latn.yaml b/data/translations/kmr-Latn.yaml
new file mode 100644
--- /dev/null
+++ b/data/translations/kmr-Latn.yaml
@@ -0,0 +1,21 @@
+Abstract: Kurtebîr
+Appendix: Tebînîya
+Bibliography: Çavkanîya Pirtukan
+Cc: Belavker
+Chapter: Serê
+Contents: Navêrok
+Encl: Dumahik
+Figure: Dimenê
+Glossary: Çavkanîya lêkolînê
+Index: Endeks
+ListOfFigures: Hejmara Dimena
+ListOfTables: Hejmara Kevalen
+Page: Rûpelê
+Part: Bêşa
+Preface: Peşgotin
+Proof: Delîl
+References: Pirtuken bijartî
+See: binêra
+SeeAlso: le vêya ji binêra
+Table: Kevala
+To: Ji bo
diff --git a/data/translations/kn.yaml b/data/translations/kn.yaml
new file mode 100644
--- /dev/null
+++ b/data/translations/kn.yaml
@@ -0,0 +1,20 @@
+Abstract: ಸಾರಾಂಶ
+Appendix: ಅನುಬಂಧ
+Bibliography: ಗ್ರಂಥಸೂಚಿ
+Cc: cc
+Chapter: ಅಧ್ಯಾಯ
+Contents: ವಿಷಯಗಳು
+Encl: encl
+Figure: ಚಿತ್ರ
+Index: ಸೂಚಿ
+ListOfFigures: ಚಿತ್ರಗಳ ಪಟ್ಟಿ
+ListOfTables: ಕೋಷ್ಟಕಗಳ ಪಟ್ಟಿ
+Page: ಪುಟ
+Part: ಭಾಗ
+Preface: ಮುನ್ನುಡಿ
+Proof: ಕರಡುಪ್ರತಿ
+References: ಉಲ್ಲೇಖಗಳು
+See: ನೋಡು
+SeeAlso: ಇದನ್ನೂ ಸಹ ನೋಡು
+Table: ಕೋಷ್ಟಕ
+To: ಗೆ
diff --git a/data/translations/ko.yaml b/data/translations/ko.yaml
--- a/data/translations/ko.yaml
+++ b/data/translations/ko.yaml
@@ -14,4 +14,4 @@
 Proof: 증명
 References: 참고문헌
 Table: 표
-To: 수신:
+To: 수신
diff --git a/data/translations/la.yaml b/data/translations/la.yaml
new file mode 100644
--- /dev/null
+++ b/data/translations/la.yaml
@@ -0,0 +1,20 @@
+Abstract: Summarium
+Appendix: Additamentum
+Bibliography: Conspectus librorum
+Cc: Exemplar
+Chapter: Caput
+Contents: Index
+Encl: Additur
+Figure: Descriptio
+Glossary: Glossarium
+Index: Index rerum notabilium
+ListOfFigures: Conspectus descriptionum
+ListOfTables: Conspectus tabularum
+Page: charta
+Part: Pars
+Preface: Praefatio
+Proof: Demonstratio
+References: Conspectus librorum
+See: cfr.
+SeeAlso: cfr.
+Table: Tabula
diff --git a/data/translations/lb.yaml b/data/translations/lb.yaml
new file mode 100644
--- /dev/null
+++ b/data/translations/lb.yaml
@@ -0,0 +1,21 @@
+Abstract: Resümee
+Appendix: Annex
+Bibliography: Bibliographie
+Cc: Distributeur
+Chapter: Kapitel
+Contents: Contenue
+Encl: Annex(en)
+Figure: Bild
+Glossary: Glossär
+Index: Index
+ListOfFigures: Lëscht vun de Biller
+ListOfTables: Lëscht vun den Tabellen
+Page: Säit
+Part: Deel
+Preface: Virwuert
+Proof: Beweis
+References: Literatur
+See: kuck
+SeeAlso: kuck och
+Table: Tabell
+To: Un
diff --git a/data/translations/lv.yaml b/data/translations/lv.yaml
--- a/data/translations/lv.yaml
+++ b/data/translations/lv.yaml
@@ -1,12 +1,12 @@
 Abstract: Anotācija
 Appendix: Pielikums
 Bibliography: Literatūra
-Cc: cc
+Cc: Kopija(s)
 Chapter: Nodaļa
 Contents: Saturs
-Encl: encl
+Encl: Pielikumā
 Figure: Att.
-Index: Index
+Index: Priekšmetu rādītājs
 ListOfFigures: Attēlu saraksts
 ListOfTables: Tabulu saraksts
 Page: lpp.
diff --git a/data/translations/mk.yaml b/data/translations/mk.yaml
new file mode 100644
--- /dev/null
+++ b/data/translations/mk.yaml
@@ -0,0 +1,21 @@
+Abstract: Апстракт
+Appendix: Прилог
+Bibliography: Библиографиjа
+Cc: копиjа
+Chapter: Глава
+Contents: Содржина
+Encl: Прилози
+Figure: Слика
+Glossary: Речник
+Index: Индекс на термини
+ListOfFigures: Листа на слики
+ListOfTables: Листа на табели
+Page: стр.
+Part: Дел
+Preface: Предговор
+Proof: доказ
+References: Литература
+See: види
+SeeAlso: види исто така
+Table: Табела
+To: За
diff --git a/data/translations/ml.yaml b/data/translations/ml.yaml
new file mode 100644
--- /dev/null
+++ b/data/translations/ml.yaml
@@ -0,0 +1,12 @@
+Abstract: സാരാംശം
+Appendix: ശിഷ്ടം
+Chapter: അദ്ധ്യായം
+Contents: ഉള്ളടക്കം
+Figure: ചിത്രം
+Index: സൂചിക
+ListOfFigures: ചിത്രസൂചിക
+ListOfTables: പട്ടികകളുടെ സൂചിക
+Part: ഭാഗം
+See: കാണുക
+SeeAlso: ഇതും കാണുക
+Table: പട്ടിക
diff --git a/data/translations/mn.yaml b/data/translations/mn.yaml
new file mode 100644
--- /dev/null
+++ b/data/translations/mn.yaml
@@ -0,0 +1,19 @@
+Abstract: Удиртгал
+Appendix: Хавсралт
+Bibliography: Номзүй
+Cc: э.с.
+Chapter: Бүлэг
+Contents: Гарчиг
+Encl: Ишлэл
+Figure: Зураг
+Index: Товъёг
+ListOfFigures: Зургийн жагсаалт
+ListOfTables: Хүснэгтийн жагсаалт
+Page: тал
+Part: Хэсэг
+Preface: Өмнөх үг
+Proof: Баталгаа
+References: Ашигласан ном
+See: талд үз
+SeeAlso: мөн талд үз
+Table: Хүснэгт
diff --git a/data/translations/mr.yaml b/data/translations/mr.yaml
new file mode 100644
--- /dev/null
+++ b/data/translations/mr.yaml
@@ -0,0 +1,21 @@
+Abstract: सारांश
+Appendix: परिशिष्ट
+Bibliography: संदर्भसूची
+Cc: प्रत
+Chapter: प्रकरण
+Contents: अनुक्रमणिका
+Encl: समाविष्ट
+Figure: आकृती
+Glossary: संज्ञासूची
+Index: सूची
+ListOfFigures: आकृत्यांची सूची
+ListOfTables: कोष्टकसूची
+Page: पृष्ठ
+Part: खंड
+Preface: प्रस्तावना
+Proof: सिद्धता
+References: संदर्भ
+See: पाहा
+SeeAlso: हेदेखील पाहा
+Table: कोष्टक
+To: प्रति
diff --git a/data/translations/ms.yaml b/data/translations/ms.yaml
new file mode 100644
--- /dev/null
+++ b/data/translations/ms.yaml
@@ -0,0 +1,21 @@
+Abstract: Abstrak
+Appendix: Lampiran
+Bibliography: Bibliografi
+Cc: sk
+Chapter: Bab
+Contents: Kandungan
+Encl: Lampiran
+Figure: Gambar
+Glossary: Istilah
+Index: Indeks
+ListOfFigures: Senarai Gambar
+ListOfTables: Senarai Jadual
+Page: Halaman
+Part: Bahagian
+Preface: Prakata
+Proof: Bukti
+References: Rujukan
+See: sila rujuk
+SeeAlso: rujuk juga
+Table: Jadual
+To: Kepada
diff --git a/data/translations/nb.yaml b/data/translations/nb.yaml
new file mode 100644
--- /dev/null
+++ b/data/translations/nb.yaml
@@ -0,0 +1,21 @@
+Abstract: Sammendrag
+Appendix: Tillegg
+Bibliography: Bibliografi
+Cc: Kopi sendt
+Chapter: Kapittel
+Contents: Innhold
+Encl: Vedlegg
+Figure: Figur
+Glossary: Ordliste
+Index: Register
+ListOfFigures: Figurer
+ListOfTables: Tabeller
+Page: Side
+Part: Del
+Preface: Forord
+Proof: Bevis
+References: Referanser
+See: Se
+SeeAlso: Se også
+Table: Tabell
+To: Til
diff --git a/data/translations/nko.yaml b/data/translations/nko.yaml
new file mode 100644
--- /dev/null
+++ b/data/translations/nko.yaml
@@ -0,0 +1,21 @@
+Abstract: ߓߊߕߐߡߐ߲
+Appendix: ߘߋ߬ߙߋ
+Bibliography: ߟߍߙߊߥߙߍߟߐ߲߲
+Cc: ߓߊ ߘߏ߫ ߘߌ߫
+Chapter: ߛߌ߰ߘߊ
+Contents: ߞߣߐߘߐ
+Encl: ߝߍ߬ߕߊ
+Figure: ߢߊ
+Glossary: ߞߘߐߝߐߟߊ߲
+Index: ߛߙߍߘߍ
+ListOfFigures: ߢߊ ߟߎ߬ ߛߙߍߘߍ
+ListOfTables: ߦߌ߬ߘߊ߬ߥߟߊ ߟߎ߬ ߛߙߍߘߍ
+Page: ߞߐߜߍ
+Part: ߛߌ߰ߘߊ߬ߙߋ߲
+Preface: ߢߍߛߓߍ
+Proof: ߦߌ߬ߘߊ߬ߞߏ
+References: ߞߐߡߊߛߙߋ
+See: ߡߊߝߟߍ߫
+SeeAlso: ߝߟߍߡߊߛߊ߬ߦߌ߬
+Table: ߦߌ߬ߘߊ߬ߥߟߊ
+To: ߞߊߕߙߍ߬
diff --git a/data/translations/nl.yaml b/data/translations/nl.yaml
--- a/data/translations/nl.yaml
+++ b/data/translations/nl.yaml
@@ -1,19 +1,19 @@
 Abstract: Samenvatting
-Appendix: Bijlage
+Appendix: Bĳlage
 Bibliography: Bibliografie
 Cc: cc
 Chapter: Hoofdstuk
 Contents: Inhoudsopgave
-Encl: Bijlage(n)
+Encl: Bĳlage(n)
 Figure: Figuur
-Glossary: Verklarende woordenlijst
+Glossary: Verklarende Woordenlĳst
 Index: Index
-ListOfFigures: Lijst van figuren
-ListOfTables: Lijst van tabellen
+ListOfFigures: Lĳst van figuren
+ListOfTables: Lĳst van tabellen
 Page: Pagina
 Part: Deel
 Preface: Voorwoord
-Proof: Bewijs
+Proof: Bewĳs
 References: Referenties
 See: zie
 SeeAlso: zie ook
diff --git a/data/translations/nn.yaml b/data/translations/nn.yaml
new file mode 100644
--- /dev/null
+++ b/data/translations/nn.yaml
@@ -0,0 +1,21 @@
+Abstract: Samandrag
+Appendix: Tillegg
+Bibliography: Litteratur
+Cc: Kopi til
+Chapter: Kapittel
+Contents: Innhald
+Encl: Vedlegg
+Figure: Figur
+Glossary: Ordliste
+Index: Register
+ListOfFigures: Figurar
+ListOfTables: Tabellar
+Page: Side
+Part: Del
+Preface: Forord
+Proof: Bevis
+References: Referansar
+See: Sjå
+SeeAlso: Sjå òg
+Table: Tabell
+To: Til
diff --git a/data/translations/oc.yaml b/data/translations/oc.yaml
new file mode 100644
--- /dev/null
+++ b/data/translations/oc.yaml
@@ -0,0 +1,21 @@
+Abstract: Resumit
+Appendix: Annèx
+Bibliography: Bibliografia
+Cc: còpia a
+Chapter: Capítol
+Contents: Ensenhador
+Encl: Pèça junta
+Figure: Figura
+Glossary: Glossari
+Index: Indèx
+ListOfFigures: Taula de las figuras
+ListOfTables: Taula dels tablèus
+Page: Pagina
+Part: Partida
+Preface: Prefàcia
+Proof: Demostracion
+References: Referéncias
+See: vejatz
+SeeAlso: vejatz tanben
+Table: Tablèu
+To: A
diff --git a/data/translations/or.yaml b/data/translations/or.yaml
new file mode 100644
--- /dev/null
+++ b/data/translations/or.yaml
@@ -0,0 +1,21 @@
+Abstract: ସାରାଂଶ
+Appendix: ପରିଶିଷ୍ଟ
+Bibliography: ସୂଚନା
+Cc: କପି କରନ୍ତୁ
+Chapter: ଅଧ୍ୟାୟ
+Contents: ସୁଚୀ ପତ୍ର
+Encl: ସଂଲଗ୍ନ
+Figure: ପ୍ରତିଛବି
+Glossary: ଶବ୍ଦର ଶବ୍ଦକୋଷ
+Index: ସୂଚକାଙ୍କ
+ListOfFigures: ପ୍ରତିଛବି ତାଲିକା
+ListOfTables: ଟେବୁଲ ତାଲିକା
+Page: ପୃଷ୍ଠା
+Part: ବିଭାଗ
+Preface: ପ୍ରାରମ୍ଭ
+Proof: ପ୍ରମାଣ
+References: ସନ୍ଦର୍ଭ
+See: ଦେଖନ୍ତୁ
+SeeAlso: ଅଧିକ ଦେଖନ୍ତୁ
+Table: ଟେବୁଲ୍
+To: ପ୍ରତି
diff --git a/data/translations/pa.yaml b/data/translations/pa.yaml
new file mode 100644
--- /dev/null
+++ b/data/translations/pa.yaml
@@ -0,0 +1,20 @@
+Abstract: ਨਿਚੋੜ
+Appendix: ਲੜੀਵਾਰ
+Bibliography: ਸੰਬੰਧਤ ਹਵਾਲੇ
+Cc: ਕਾਪੀ
+Chapter: ਪਾਠ
+Contents: ਸਮਗਰੀ
+Encl: ਨੱਥੀ
+Figure: ਸ਼ਕਲ
+Glossary: ਕੁੰਜੀ
+Index: ਸੂਚੀ
+ListOfFigures: ਸ਼ਕਲਾਂ ਦੀ ਲੜੀ
+ListOfTables: ਲੜੀਆਂ ਦਾ ਲੇਖਾ
+Page: ਵਰਕਾ
+Part: ਹਿੱਸਾ
+Preface: ਮੁੱਖਬੰਦ
+Proof: ਪਰਮਾਣ
+References: ਹਵਾਲਾ
+See: ਵੇਖੋ
+SeeAlso: ਹੋਰ
+Table: ਲੇਖਾ
diff --git a/data/translations/pl.yaml b/data/translations/pl.yaml
--- a/data/translations/pl.yaml
+++ b/data/translations/pl.yaml
@@ -1,7 +1,7 @@
 Abstract: Streszczenie
 Appendix: Dodatek
 Bibliography: Bibliografia
-Cc: Kopie:
+Cc: Kopie
 Chapter: Rozdział
 Contents: Spis treści
 Encl: Załącznik
diff --git a/data/translations/pms.yaml b/data/translations/pms.yaml
new file mode 100644
--- /dev/null
+++ b/data/translations/pms.yaml
@@ -0,0 +1,21 @@
+Abstract: Somari
+Appendix: Gionta
+Bibliography: Bibliografìa
+Cc: Con còpia a
+Chapter: Capìtol
+Contents: Tàula
+Encl: Gionta/e
+Figure: Figura
+Glossary: Glossari
+Index: Tàula analìtica
+ListOfFigures: Lista dle figure
+ListOfTables: Lista dle tabele
+Page: Pàgina
+Part: Part
+Preface: Prefassion
+Proof: Dimostrassion
+References: Riferiment
+See: vëd
+SeeAlso: vëd anche
+Table: Tabela
+To: Për
diff --git a/data/translations/pt-BR.yaml b/data/translations/pt-BR.yaml
new file mode 100644
--- /dev/null
+++ b/data/translations/pt-BR.yaml
@@ -0,0 +1,21 @@
+Abstract: Resumo
+Appendix: Apêndice
+Bibliography: Referências Bibliográficas
+Cc: Cópia para
+Chapter: Capítulo
+Contents: Sumário
+Encl: Anexo
+Figure: Figura
+Glossary: Glossário
+Index: Índice Remissivo
+ListOfFigures: Lista de Figuras
+ListOfTables: Lista de Tabelas
+Page: Página
+Part: Parte
+Preface: Prefácio
+Proof: Demonstração
+References: Referências
+See: veja
+SeeAlso: veja também
+Table: Tabela
+To: Para
diff --git a/data/translations/pt-PT.yaml b/data/translations/pt-PT.yaml
new file mode 100644
--- /dev/null
+++ b/data/translations/pt-PT.yaml
@@ -0,0 +1,21 @@
+Abstract: Resumo
+Appendix: Apêndice
+Bibliography: Bibliografia
+Cc: Com cópia a
+Chapter: Capítulo
+Contents: Conteúdo
+Encl: Anexo
+Figure: Figura
+Glossary: Glossário
+Index: Índice
+ListOfFigures: Lista de Figuras
+ListOfTables: Lista de Tabelas
+Page: Página
+Part: Parte
+Preface: Prefácio
+Proof: Demonstração
+References: Referências
+See: ver
+SeeAlso: ver também
+Table: Tabela
+To: Para
diff --git a/data/translations/ro.yaml b/data/translations/ro.yaml
--- a/data/translations/ro.yaml
+++ b/data/translations/ro.yaml
@@ -12,8 +12,8 @@
 ListOfTables: Listă de tabele
 Page: Pagina
 Part: Partea
-Preface: Prefață
-Proof: Demonstrație
+Preface: Prefaţă
+Proof: Demonstraţie
 References: Bibliografie
 See: Vezi
 SeeAlso: Vezi de asemenea
diff --git a/data/translations/ru.yaml b/data/translations/ru.yaml
--- a/data/translations/ru.yaml
+++ b/data/translations/ru.yaml
@@ -1,21 +1,21 @@
-Abstract: Аннотація
-Appendix: Приложеніе
-Author: Именной указатель
-Bibliography: Библіографія
+Abstract: Аннотация
+Appendix: Приложение
+Bibliography: Литература
 Cc: исх.
 Chapter: Глава
-Contents: Оглавленіе
+Contents: Содержание
 Encl: вкл.
 Figure: Рис.
-Index: Предмѣтный указатель
-ListOfFigures: Списокъ иллюстрацій
-ListOfTables: Списокъ таблицъ
+Glossary: Словарь терминов
+Index: Предметный указатель
+ListOfFigures: Список иллюстраций
+ListOfTables: Список таблиц
 Page: с.
 Part: Часть
-Preface: Предисловіе
+Preface: Предисловие
 Proof: Доказательство
-References: Примѣчанія
+References: Список литературы
 See: см.
-SeeAlso: см. также
+SeeAlso: см. также
 Table: Таблица
 To: вх.
diff --git a/data/translations/se.yaml b/data/translations/se.yaml
new file mode 100644
--- /dev/null
+++ b/data/translations/se.yaml
@@ -0,0 +1,21 @@
+Abstract: Čoahkkáigeassu
+Appendix: Čuovus
+Bibliography: Girjjálašvuohta
+Cc: Kopia sáddejuvvon
+Chapter: Kapihttal
+Contents: Sisdoallu
+Encl: Mielddus
+Figure: Govus
+Glossary: Sátnelistu
+Index: Registtar
+ListOfFigures: Govvosat
+ListOfTables: Tabeallat
+Page: Siidu
+Part: Oassi
+Preface: Ovdasátni
+Proof: Duođaštus
+References: Čujuhusat
+See: geahča
+SeeAlso: geahča maiddái
+Table: Tabealla
+To: Vuostáiváldi
diff --git a/data/translations/si.yaml b/data/translations/si.yaml
new file mode 100644
--- /dev/null
+++ b/data/translations/si.yaml
@@ -0,0 +1,21 @@
+Abstract: සංක්ෂෙපය
+Appendix: උපග්‍රන්ථය
+Bibliography: ග්‍රන්ථ නාමාවලිය
+Cc: පිටපත්
+Chapter: පරිච්ඡේදය
+Contents: පටුන
+Encl: ඇමුණුම
+Figure: සටහන
+Glossary: පදමාලාව
+Index: සූචිය
+ListOfFigures: සටහන් ලේඛනය
+ListOfTables: වගු ලේඛනය
+Page: පිට
+Part: කොටස
+Preface: පෙරවදන
+Proof: සාධනය
+References: යොමුව
+See: බලනු
+SeeAlso: තවද
+Table: වගුව
+To: වෙත
diff --git a/data/translations/sk.yaml b/data/translations/sk.yaml
--- a/data/translations/sk.yaml
+++ b/data/translations/sk.yaml
@@ -4,17 +4,17 @@
 Cc: cc.
 Chapter: Kapitola
 Contents: Obsah
-Encl: Prílohy
-Figure: Obrázok
+Encl: Príloha
+Figure: Obr.
 Glossary: Slovník
-Index: Index
+Index: Register
 ListOfFigures: Zoznam obrázkov
 ListOfTables: Zoznam tabuliek
-Page: Strana
+Page: Str.
 Part: Časť
-Preface: Úvod
+Preface: Predhovor
 Proof: Dôkaz
-References: Referencie
+References: Literatúra
 See: viď
 SeeAlso: viď tiež
 Table: Tabuľka
diff --git a/data/translations/sq.yaml b/data/translations/sq.yaml
--- a/data/translations/sq.yaml
+++ b/data/translations/sq.yaml
@@ -1,8 +1,10 @@
 Abstract: Përmbledhja
 Appendix: Shtesa
 Bibliography: Bibliografia
+Cc: Kopja
 Chapter: Kapitulli
-Contents: Përmbajta
+Contents: Përmbajtja
+Encl: Lidhja
 Figure: Figura
 Glossary: Përhasja e Fjalëve
 Index: Indeksi
@@ -16,3 +18,4 @@
 See: shiko
 SeeAlso: shiko dhe
 Table: Tabela
+To: Për
diff --git a/data/translations/sr-Cyrl.yaml b/data/translations/sr-Cyrl.yaml
new file mode 100644
--- /dev/null
+++ b/data/translations/sr-Cyrl.yaml
@@ -0,0 +1,21 @@
+Abstract: Сажетак
+Appendix: Додатак
+Bibliography: Библиографиjа
+Cc: Копиjе
+Chapter: Глава
+Contents: Садржаj
+Encl: Прилози
+Figure: Слика
+Glossary: Речник
+Index: Индекс
+ListOfFigures: Списак слика
+ListOfTables: Списак табела
+Page: страна
+Part: Део
+Preface: Предговор
+Proof: Доказ
+References: Литература
+See: види
+SeeAlso: видитакође
+Table: Табела
+To: Прима
diff --git a/data/translations/sr-Latn.yaml b/data/translations/sr-Latn.yaml
new file mode 100644
--- /dev/null
+++ b/data/translations/sr-Latn.yaml
@@ -0,0 +1,21 @@
+Abstract: Sažetak
+Appendix: Dodatak
+Bibliography: Bibliografija
+Cc: Kopije
+Chapter: Glava
+Contents: Sadržaj
+Encl: Prilozi
+Figure: Slika
+Glossary: Rečnik
+Index: Indeks
+ListOfFigures: Spisak slika
+ListOfTables: Spisak tabela
+Page: strana
+Part: Deo
+Preface: Predgovor
+Proof: Dokaz
+References: Literatura
+See: vidi
+SeeAlso: vidi takođe
+Table: Tabela
+To: Prima
diff --git a/data/translations/sr-cyrl.yaml b/data/translations/sr-cyrl.yaml
deleted file mode 100644
--- a/data/translations/sr-cyrl.yaml
+++ /dev/null
@@ -1,21 +0,0 @@
-Abstract: Сажетак
-Appendix: Додатак
-Bibliography: Литература
-Cc: Копије
-Chapter: Глава
-Contents: Садржај
-Encl: Прилози
-Figure: Слика
-Glossary: Речник непознатих речи
-Index: Регистар
-ListOfFigures: Списак слика
-ListOfTables: Списак табела
-Page: Страна
-Part: Део
-Preface: Предговор
-Proof: Доказ
-References: Библиографија
-See: Види
-SeeAlso: Види такође
-Table: Табела
-To: Прима
diff --git a/data/translations/sr.yaml b/data/translations/sr.yaml
--- a/data/translations/sr.yaml
+++ b/data/translations/sr.yaml
@@ -1,21 +1,21 @@
-Abstract: Sažetak
-Appendix: Dodatak
-Bibliography: Literatura
-Cc: Kopije
-Chapter: Glava
-Contents: Sadržaj
-Encl: Prilozi
-Figure: Slika
-Glossary: Rečnik nepoznatih reči
-Index: Registar
-ListOfFigures: Spisak slika
-ListOfTables: Spisak tabela
-Page: Strana
-Part: Deo
-Preface: Predgovor
-Proof: Dokaz
-References: Bibliografija
-See: Vidi
-SeeAlso: Vidi takođe
-Table: Tabela
-To: Prima
+Abstract: Сажетак
+Appendix: Додатак
+Bibliography: Библиографиjа
+Cc: Копиjе
+Chapter: Глава
+Contents: Садржаj
+Encl: Прилози
+Figure: Слика
+Glossary: Речник
+Index: Индекс
+ListOfFigures: Списак слика
+ListOfTables: Списак табела
+Page: страна
+Part: Део
+Preface: Предговор
+Proof: Доказ
+References: Литература
+See: види
+SeeAlso: видитакође
+Table: Табела
+To: Прима
diff --git a/data/translations/ta.yaml b/data/translations/ta.yaml
new file mode 100644
--- /dev/null
+++ b/data/translations/ta.yaml
@@ -0,0 +1,11 @@
+Abstract: சாராம்சம்
+Appendix: பிற்சேர்க்கை
+Chapter: அத்தியாயம்
+Contents: உள்ளே
+Figure: படம்
+Index: சுட்டி
+ListOfFigures: படங்களின் பட்டியல்
+ListOfTables: அட்டவணை பட்டியல்
+Part: பகுதி
+See: பார்க்க
+Table: அட்டவணை
diff --git a/data/translations/te.yaml b/data/translations/te.yaml
new file mode 100644
--- /dev/null
+++ b/data/translations/te.yaml
@@ -0,0 +1,21 @@
+Abstract: సారాంశం
+Appendix: అదనంగా
+Bibliography: గ్రంథాల జాబితా
+Cc: సిసి
+Chapter: అధ్యాయము
+Contents: విషయాలు
+Encl: ఎంక్లోజర్*
+Figure: ఆకృతి
+Glossary: నిఘంటువు
+Index: విషయ సూచిక
+ListOfFigures: ఆకృతుల జాబితా
+ListOfTables: పట్టికల జాబితా
+Page: పేజి
+Part: భాగం
+Preface: ముందుమాట
+Proof: రుజువు
+References: ఆధారాలు
+See: చూడండి
+SeeAlso: కూడా చూడండి
+Table: పట్టిక
+To: కి
diff --git a/data/translations/th.yaml b/data/translations/th.yaml
--- a/data/translations/th.yaml
+++ b/data/translations/th.yaml
@@ -11,7 +11,7 @@
 ListOfTables: สารบัญตาราง
 Page: หน้า
 Part: ภาค
-Preface: คำนำ
+Preface: บทนำ
 Proof: พิสูจน์
 References: หนังสืออ้างอิง
 See: ดู
diff --git a/data/translations/tk.yaml b/data/translations/tk.yaml
new file mode 100644
--- /dev/null
+++ b/data/translations/tk.yaml
@@ -0,0 +1,21 @@
+Abstract: Gysgaça manysy
+Appendix: Goşmaça
+Bibliography: Çeşmeler
+Cc: Iberilenler
+Chapter: Bap
+Contents: Mazmuny
+Encl: Goşmaça
+Figure: Surat
+Glossary: Sözlük
+Index: Indeks
+ListOfFigures: Suratlaryň sanawy
+ListOfTables: Tablisalaryň sanawy
+Page: Sahypa
+Part: Bölüm
+Preface: Sözbaşy
+Proof: Delil
+References: Çeşmeler
+See: ser.
+SeeAlso: şuňa-da ser.
+Table: Tablisa
+To: Kime
diff --git a/data/translations/tr.yaml b/data/translations/tr.yaml
--- a/data/translations/tr.yaml
+++ b/data/translations/tr.yaml
@@ -17,6 +17,5 @@
 References: Kaynaklar
 See: bkz.
 SeeAlso: ayrıca bkz.
-Subject: İlgili
 Table: Tablo
 To: Alıcı
diff --git a/data/translations/ua.yaml b/data/translations/ua.yaml
new file mode 100644
--- /dev/null
+++ b/data/translations/ua.yaml
@@ -0,0 +1,22 @@
+Abstract: Резюме
+Appendix: Додаток
+Bibliography: Бібліографія
+Cc: Розповсюджувач
+Chapter: Розділ
+Contents: Зміст
+Encl: Додаток(и)
+Figure: Ілюстрація
+Glossary: Глосарій
+Index: Індекс
+Listing: Список
+ListOfFigures: Список рисунків
+ListOfTables: Список таблиць
+Page: Сторінка
+Part: Частина
+Preface: Передмова
+Proof: Докази
+References: Література
+See: див.
+SeeAlso: див. також
+Table: Таблиця
+To: До
diff --git a/data/translations/ug.yaml b/data/translations/ug.yaml
new file mode 100644
--- /dev/null
+++ b/data/translations/ug.yaml
@@ -0,0 +1,21 @@
+Abstract: ئابستراكت
+Appendix: قوشۇمچە
+Bibliography: پايدىلانما
+Cc: باشقا تاپشۇرۇۋالغۇچى
+Chapter: باب
+Contents: مۇندەرىجە
+Encl: قوشۇمچە ھۆججەت
+Figure: رەسىم
+Glossary: لۇغەت
+Index: ئىندېكىس
+ListOfFigures: رەسىملەر
+ListOfTables: جەدۋەللەر
+Page: بەت
+Part: قىسىم
+Preface: كىرىش سۆز
+Proof: ئىسپات
+References: پايدىلانما
+See: قاراڭ
+SeeAlso: ئايرىم قاراڭ
+Table: جەدۋەل
+To: تاپشۇرۇۋالغۇچى
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: Розділ
@@ -17,6 +16,6 @@
 Proof: Доведення
 References: Література
 See: див.
-SeeAlso: див. також
+SeeAlso: див. також
 Table: Табл.
 To: До
diff --git a/data/translations/ur.yaml b/data/translations/ur.yaml
--- a/data/translations/ur.yaml
+++ b/data/translations/ur.yaml
@@ -1,22 +1,21 @@
-Abstract: ﻢﻠﺨّﺻ
-Appendix: ﺾﻣیﻡہ
-Bibliography: کﺕﺎﺑیﺎﺗ
-Cc: ﻦﻘﻟ
-Chapter: ﺏﺎﺑ
-Contents: ﻑہﺮﺴﺗ ﻊﻧﻭﺎﻧﺎﺗ
-Encl: ﻢﻨﺴﻟک
-Figure: ﺶﻜﻟ
-Glossary: ﻞﻐﺗ
-Index: ﺎﺷﺍﺭیہ
-ListOfFigures: ﻑہﺮﺴﺗ ﺎﺷکﺎﻟ
-ListOfTables: ﻑہﺮﺴﺗ ﺝﺩﺍﻮﻟ
-Page: ﺺﻔﺣہ
-Part: ﺢﺻّہ
-Preface: ﺩیﺏﺍچہ
-Proof: ﺚﺑﻮﺗ
-References: ﺡﻭﺎﻟہ ﺝﺎﺗ
-Section: ﻒﺼﻟ
-See: ﻡﻼﺤﻇہ ہﻭ
-SeeAlso: ﺍیﺽﺍً
-Table: ﺝﺩﻮﻟ
-To: ﺐﻣﻼﺤﻇہ
+Abstract: ملخّص
+Appendix: ضمیمہ
+Bibliography: کتابیات
+Cc: نقل
+Chapter: باب
+Contents: فہرست عنوانات
+Encl: منسلک
+Figure: شكل
+Glossary: لغت
+Index: اشاریہ
+ListOfFigures: فہرست اشکال
+ListOfTables: فہرست جداول
+Page: صفحہ
+Part: حصّہ
+Preface: دیباچہ
+Proof: ثبوت
+References: حوالہ جات
+See: ملاحظہ ہو
+SeeAlso: ایضاً
+Table: جدول
+To: بملاحظہ
diff --git a/data/translations/vi.yaml b/data/translations/vi.yaml
--- a/data/translations/vi.yaml
+++ b/data/translations/vi.yaml
@@ -1,21 +1,21 @@
 Abstract: Tóm tắt nội dung
-Also: Xem thêm
 Appendix: Phụ lục
-Bib: Tài liệu tham khảo
+Bibliography: Tài liệu tham khảo
 Cc: Cùng gửi
 Chapter: Chương
 Contents: Mục lục
 Encl: Kèm theo
 Figure: Hình
 Glossary: Từ điển chú giải
-Headto: Gửi
 Index: Chỉ mục
-Listfigure: Danh sách hình vẽ
-Listtable: Danh sách bẳng
+ListOfFigures: Danh sách hình vẽ
+ListOfTables: Danh sách bảng
 Page: Trang
 Part: Phần
 Preface: Lời nói đầu
 Proof: Chứng minh
 References: Tài liệu
 See: Xem
-Table: Bẳng
+SeeAlso: Xem thêm
+Table: Bảng
+To: Gửi
diff --git a/data/translations/zh-Hans.yaml b/data/translations/zh-Hans.yaml
new file mode 100644
--- /dev/null
+++ b/data/translations/zh-Hans.yaml
@@ -0,0 +1,22 @@
+Abstract: 摘要
+Appendix: 附录
+Bibliography: 文献目录
+Cc: 副本
+Chapter: 章
+Contents: 目录
+Encl: 附件
+Figure: 图
+Glossary: 术语
+Index: 索引
+Listing: 列表
+ListOfFigures: 附图目录
+ListOfTables: 表格索引
+Page: 页
+Part: 段
+Preface: 序
+Proof: 校对
+References: 参考文献
+See: 见
+SeeAlso: 参见
+Table: 表
+To: 到
diff --git a/data/translations/zh-Hant.yaml b/data/translations/zh-Hant.yaml
new file mode 100644
--- /dev/null
+++ b/data/translations/zh-Hant.yaml
@@ -0,0 +1,22 @@
+Abstract: 摘要
+Appendix: 附錄
+Bibliography: 文獻目錄
+Cc: 副本
+Chapter: 章
+Contents: 目錄
+Encl: 附件
+Figure: 圖
+Glossary: 術語
+Index: 索引
+Listing: 列表
+ListOfFigures: 附圖目錄
+ListOfTables: 表格索引
+Page: 頁
+Part: 段
+Preface: 序
+Proof: 校對
+References: 參考文獻
+See: 見
+SeeAlso: 參見
+Table: 表
+To: 到
diff --git a/man/manfilter.lua b/man/manfilter.lua
deleted file mode 100644
--- a/man/manfilter.lua
+++ /dev/null
@@ -1,22 +0,0 @@
--- we use preloaded text to get a UTF-8 aware 'upper' function
-local text = require('text')
-
--- capitalize level 1 headers
-function Header(el)
-    if el.level == 1 then
-      return pandoc.walk_block(el, {
-        Str = function(el)
-            return pandoc.Str(text.upper(el.text))
-        end })
-    end
-end
-
--- replace links with link text
-function Link(el)
-    return el.content
-end
-
--- remove notes
-function Note(el)
-    return {}
-end
diff --git a/man/pandoc.1 b/man/pandoc.1
deleted file mode 100644
--- a/man/pandoc.1
+++ /dev/null
@@ -1,5596 +0,0 @@
-.\"t
-.TH PANDOC 1 "December 27, 2017" "pandoc 2.0.6"
-.SH NAME
-pandoc - general markup converter
-.SH SYNOPSIS
-.PP
-\f[C]pandoc\f[] [\f[I]options\f[]] [\f[I]input\-file\f[]]...
-.SH DESCRIPTION
-.PP
-Pandoc is a Haskell library for converting from one markup format to
-another, and a command\-line tool that uses this library.
-It can read Markdown, CommonMark, PHP Markdown Extra, GitHub\-Flavored
-Markdown, MultiMarkdown, and (subsets of) Textile, reStructuredText,
-HTML, LaTeX, MediaWiki markup, TWiki markup, TikiWiki markup, Creole
-1.0, Haddock markup, OPML, Emacs Org mode, DocBook, JATS, Muse,
-txt2tags, Vimwiki, EPUB, ODT, and Word docx; and it can write plain
-text, Markdown, CommonMark, PHP Markdown Extra, GitHub\-Flavored
-Markdown, MultiMarkdown, reStructuredText, XHTML, HTML5, LaTeX
-(including \f[C]beamer\f[] slide shows), ConTeXt, RTF, OPML, DocBook,
-JATS, OpenDocument, ODT, Word docx, GNU Texinfo, MediaWiki markup,
-DokuWiki markup, ZimWiki markup, Haddock markup, EPUB (v2 or v3),
-FictionBook2, Textile, groff man, groff ms, Emacs Org mode, AsciiDoc,
-InDesign ICML, TEI Simple, Muse, PowerPoint slide shows and Slidy,
-Slideous, DZSlides, reveal.js or S5 HTML slide shows.
-It can also produce PDF output on systems where LaTeX, ConTeXt,
-\f[C]pdfroff\f[], \f[C]wkhtmltopdf\f[], \f[C]prince\f[], or
-\f[C]weasyprint\f[] is installed.
-.PP
-Pandoc\[aq]s enhanced version of Markdown includes syntax for footnotes,
-tables, flexible ordered lists, definition lists, fenced code blocks,
-superscripts and subscripts, strikeout, metadata blocks, automatic
-tables of contents, embedded LaTeX math, citations, and Markdown inside
-HTML block elements.
-(These enhancements, described further under Pandoc\[aq]s Markdown, can
-be disabled using the \f[C]markdown_strict\f[] input or output format.)
-.PP
-In contrast to most existing tools for converting Markdown to HTML,
-which use regex substitutions, pandoc has a modular design: it consists
-of a set of readers, which parse text in a given format and produce a
-native representation of the document, and a set of writers, which
-convert this native representation into a target format.
-Thus, adding an input or output format requires only adding a reader or
-writer.
-.PP
-Because pandoc\[aq]s intermediate representation of a document is less
-expressive than many of the formats it converts between, one should not
-expect perfect conversions between every format and every other.
-Pandoc attempts to preserve the structural elements of a document, but
-not formatting details such as margin size.
-And some document elements, such as complex tables, may not fit into
-pandoc\[aq]s simple document model.
-While conversions from pandoc\[aq]s Markdown to all formats aspire to be
-perfect, conversions from formats more expressive than pandoc\[aq]s
-Markdown can be expected to be lossy.
-.SS Using \f[C]pandoc\f[]
-.PP
-If no \f[I]input\-file\f[] is specified, input is read from
-\f[I]stdin\f[].
-Otherwise, the \f[I]input\-files\f[] are concatenated (with a blank line
-between each) and used as input.
-Output goes to \f[I]stdout\f[] by default (though output to the terminal
-is disabled for the \f[C]odt\f[], \f[C]docx\f[], \f[C]epub2\f[], and
-\f[C]epub3\f[] output formats, unless it is forced using
-\f[C]\-o\ \-\f[]).
-For output to a file, use the \f[C]\-o\f[] option:
-.IP
-.nf
-\f[C]
-pandoc\ \-o\ output.html\ input.txt
-\f[]
-.fi
-.PP
-By default, pandoc produces a document fragment, not a standalone
-document with a proper header and footer.
-To produce a standalone document, use the \f[C]\-s\f[] or
-\f[C]\-\-standalone\f[] flag:
-.IP
-.nf
-\f[C]
-pandoc\ \-s\ \-o\ output.html\ input.txt
-\f[]
-.fi
-.PP
-For more information on how standalone documents are produced, see
-Templates, below.
-.PP
-Instead of a file, an absolute URI may be given.
-In this case pandoc will fetch the content using HTTP:
-.IP
-.nf
-\f[C]
-pandoc\ \-f\ html\ \-t\ markdown\ http://www.fsf.org
-\f[]
-.fi
-.PP
-It is possible to supply a custom User\-Agent string or other header
-when requesting a document from a URL:
-.IP
-.nf
-\f[C]
-pandoc\ \-f\ html\ \-t\ markdown\ \-\-request\-header\ User\-Agent:"Mozilla/5.0"\ \\
-\ \ http://www.fsf.org
-\f[]
-.fi
-.PP
-If multiple input files are given, \f[C]pandoc\f[] will concatenate them
-all (with blank lines between them) before parsing.
-This feature is disabled for binary input formats such as \f[C]EPUB\f[],
-\f[C]odt\f[], and \f[C]docx\f[].
-.PP
-The format of the input and output can be specified explicitly using
-command\-line options.
-The input format can be specified using the \f[C]\-r/\-\-read\f[] or
-\f[C]\-f/\-\-from\f[] options, the output format using the
-\f[C]\-w/\-\-write\f[] or \f[C]\-t/\-\-to\f[] options.
-Thus, to convert \f[C]hello.txt\f[] from Markdown to LaTeX, you could
-type:
-.IP
-.nf
-\f[C]
-pandoc\ \-f\ markdown\ \-t\ latex\ hello.txt
-\f[]
-.fi
-.PP
-To convert \f[C]hello.html\f[] from HTML to Markdown:
-.IP
-.nf
-\f[C]
-pandoc\ \-f\ html\ \-t\ markdown\ hello.html
-\f[]
-.fi
-.PP
-Supported output formats are listed below under the \f[C]\-t/\-\-to\f[]
-option.
-Supported input formats are listed below under the \f[C]\-f/\-\-from\f[]
-option.
-Note that the \f[C]rst\f[], \f[C]textile\f[], \f[C]latex\f[], and
-\f[C]html\f[] readers are not complete; there are some constructs that
-they do not parse.
-.PP
-If the input or output format is not specified explicitly,
-\f[C]pandoc\f[] will attempt to guess it from the extensions of the
-input and output filenames.
-Thus, for example,
-.IP
-.nf
-\f[C]
-pandoc\ \-o\ hello.tex\ hello.txt
-\f[]
-.fi
-.PP
-will convert \f[C]hello.txt\f[] from Markdown to LaTeX.
-If no output file is specified (so that output goes to \f[I]stdout\f[]),
-or if the output file\[aq]s extension is unknown, the output format will
-default to HTML.
-If no input file is specified (so that input comes from \f[I]stdin\f[]),
-or if the input files\[aq] extensions are unknown, the input format will
-be assumed to be Markdown unless explicitly specified.
-.PP
-Pandoc uses the UTF\-8 character encoding for both input and output.
-If your local character encoding is not UTF\-8, you should pipe input
-and output through \f[C]iconv\f[]:
-.IP
-.nf
-\f[C]
-iconv\ \-t\ utf\-8\ input.txt\ |\ pandoc\ |\ iconv\ \-f\ utf\-8
-\f[]
-.fi
-.PP
-Note that in some output formats (such as HTML, LaTeX, ConTeXt, RTF,
-OPML, DocBook, and Texinfo), information about the character encoding is
-included in the document header, which will only be included if you use
-the \f[C]\-s/\-\-standalone\f[] option.
-.SS Creating a PDF
-.PP
-To produce a PDF, specify an output file with a \f[C]\&.pdf\f[]
-extension.
-By default, pandoc will use LaTeX to create the PDF:
-.IP
-.nf
-\f[C]
-pandoc\ test.txt\ \-o\ test.pdf
-\f[]
-.fi
-.PP
-Production of a PDF requires that a LaTeX engine be installed (see
-\f[C]\-\-pdf\-engine\f[], below), and assumes that the following LaTeX
-packages are available: \f[C]amsfonts\f[], \f[C]amsmath\f[],
-\f[C]lm\f[], \f[C]unicode\-math\f[], \f[C]ifxetex\f[],
-\f[C]ifluatex\f[], \f[C]listings\f[] (if the \f[C]\-\-listings\f[]
-option is used), \f[C]fancyvrb\f[], \f[C]longtable\f[],
-\f[C]booktabs\f[], \f[C]graphicx\f[] and \f[C]grffile\f[] (if the
-document contains images), \f[C]hyperref\f[], \f[C]xcolor\f[] (with
-\f[C]colorlinks\f[]), \f[C]ulem\f[], \f[C]geometry\f[] (with the
-\f[C]geometry\f[] variable set), \f[C]setspace\f[] (with
-\f[C]linestretch\f[]), and \f[C]babel\f[] (with \f[C]lang\f[]).
-The use of \f[C]xelatex\f[] or \f[C]lualatex\f[] as the LaTeX engine
-requires \f[C]fontspec\f[].
-\f[C]xelatex\f[] uses \f[C]polyglossia\f[] (with \f[C]lang\f[]),
-\f[C]xecjk\f[], and \f[C]bidi\f[] (with the \f[C]dir\f[] variable set).
-If the \f[C]mathspec\f[] variable is set, \f[C]xelatex\f[] will use
-\f[C]mathspec\f[] instead of \f[C]unicode\-math\f[].
-The \f[C]upquote\f[] and \f[C]microtype\f[] packages are used if
-available, and \f[C]csquotes\f[] will be used for typography if added to
-the template or included in any header file.
-The \f[C]natbib\f[], \f[C]biblatex\f[], \f[C]bibtex\f[], and
-\f[C]biber\f[] packages can optionally be used for citation rendering.
-These are included with all recent versions of TeX Live.
-.PP
-Alternatively, pandoc can use ConTeXt, \f[C]pdfroff\f[], or any of the
-following HTML/CSS\-to\-PDF\-engines, to create a PDF:
-\f[C]wkhtmltopdf\f[], \f[C]weasyprint\f[] or \f[C]prince\f[].
-To do this, specify an output file with a \f[C]\&.pdf\f[] extension, as
-before, but add the \f[C]\-\-pdf\-engine\f[] option or
-\f[C]\-t\ context\f[], \f[C]\-t\ html\f[], or \f[C]\-t\ ms\f[] to the
-command line (\f[C]\-t\ html\f[] defaults to
-\f[C]\-\-pdf\-engine=wkhtmltopdf\f[]).
-.PP
-PDF output can be controlled using variables for LaTeX (if LaTeX is
-used) and variables for ConTeXt (if ConTeXt is used).
-When using an HTML/CSS\-to\-PDF\-engine, \f[C]\-\-css\f[] affects the
-output.
-If \f[C]wkhtmltopdf\f[] is used, then the variables
-\f[C]margin\-left\f[], \f[C]margin\-right\f[], \f[C]margin\-top\f[],
-\f[C]margin\-bottom\f[], and \f[C]papersize\f[] will affect the output.
-.SH OPTIONS
-.SS General options
-.TP
-.B \f[C]\-f\f[] \f[I]FORMAT\f[], \f[C]\-r\f[] \f[I]FORMAT\f[], \f[C]\-\-from=\f[]\f[I]FORMAT\f[], \f[C]\-\-read=\f[]\f[I]FORMAT\f[]
-Specify input format.
-\f[I]FORMAT\f[] can be \f[C]native\f[] (native Haskell), \f[C]json\f[]
-(JSON version of native AST), \f[C]markdown\f[] (pandoc\[aq]s extended
-Markdown), \f[C]markdown_strict\f[] (original unextended Markdown),
-\f[C]markdown_phpextra\f[] (PHP Markdown Extra), \f[C]markdown_mmd\f[]
-(MultiMarkdown), \f[C]gfm\f[] (GitHub\-Flavored Markdown),
-\f[C]commonmark\f[] (CommonMark Markdown), \f[C]textile\f[] (Textile),
-\f[C]rst\f[] (reStructuredText), \f[C]html\f[] (HTML), \f[C]docbook\f[]
-(DocBook), \f[C]t2t\f[] (txt2tags), \f[C]docx\f[] (docx), \f[C]odt\f[]
-(ODT), \f[C]epub\f[] (EPUB), \f[C]opml\f[] (OPML), \f[C]org\f[] (Emacs
-Org mode), \f[C]mediawiki\f[] (MediaWiki markup), \f[C]twiki\f[] (TWiki
-markup), \f[C]tikiwiki\f[] (TikiWiki markup), \f[C]creole\f[] (Creole
-1.0), \f[C]haddock\f[] (Haddock markup), or \f[C]latex\f[] (LaTeX).
-(\f[C]markdown_github\f[] provides deprecated and less accurate support
-for Github\-Flavored Markdown; please use \f[C]gfm\f[] instead, unless
-you need to use extensions other than \f[C]smart\f[].) Extensions can be
-individually enabled or disabled by appending \f[C]+EXTENSION\f[] or
-\f[C]\-EXTENSION\f[] to the format name.
-See Extensions below, for a list of extensions and their names.
-See \f[C]\-\-list\-input\-formats\f[] and \f[C]\-\-list\-extensions\f[],
-below.
-.RS
-.RE
-.TP
-.B \f[C]\-t\f[] \f[I]FORMAT\f[], \f[C]\-w\f[] \f[I]FORMAT\f[], \f[C]\-\-to=\f[]\f[I]FORMAT\f[], \f[C]\-\-write=\f[]\f[I]FORMAT\f[]
-Specify output format.
-\f[I]FORMAT\f[] can be \f[C]native\f[] (native Haskell), \f[C]json\f[]
-(JSON version of native AST), \f[C]plain\f[] (plain text),
-\f[C]markdown\f[] (pandoc\[aq]s extended Markdown),
-\f[C]markdown_strict\f[] (original unextended Markdown),
-\f[C]markdown_phpextra\f[] (PHP Markdown Extra), \f[C]markdown_mmd\f[]
-(MultiMarkdown), \f[C]gfm\f[] (GitHub\-Flavored Markdown),
-\f[C]commonmark\f[] (CommonMark Markdown), \f[C]rst\f[]
-(reStructuredText), \f[C]html4\f[] (XHTML 1.0 Transitional),
-\f[C]html\f[] or \f[C]html5\f[] (HTML5/XHTML polyglot markup),
-\f[C]latex\f[] (LaTeX), \f[C]beamer\f[] (LaTeX beamer slide show),
-\f[C]context\f[] (ConTeXt), \f[C]man\f[] (groff man), \f[C]mediawiki\f[]
-(MediaWiki markup), \f[C]dokuwiki\f[] (DokuWiki markup),
-\f[C]zimwiki\f[] (ZimWiki markup), \f[C]textile\f[] (Textile),
-\f[C]org\f[] (Emacs Org mode), \f[C]texinfo\f[] (GNU Texinfo),
-\f[C]opml\f[] (OPML), \f[C]docbook\f[] or \f[C]docbook4\f[] (DocBook 4),
-\f[C]docbook5\f[] (DocBook 5), \f[C]jats\f[] (JATS XML),
-\f[C]opendocument\f[] (OpenDocument), \f[C]odt\f[] (OpenOffice text
-document), \f[C]docx\f[] (Word docx), \f[C]haddock\f[] (Haddock markup),
-\f[C]rtf\f[] (rich text format), \f[C]epub2\f[] (EPUB v2 book),
-\f[C]epub\f[] or \f[C]epub3\f[] (EPUB v3), \f[C]fb2\f[] (FictionBook2
-e\-book), \f[C]asciidoc\f[] (AsciiDoc), \f[C]icml\f[] (InDesign ICML),
-\f[C]tei\f[] (TEI Simple), \f[C]slidy\f[] (Slidy HTML and JavaScript
-slide show), \f[C]slideous\f[] (Slideous HTML and JavaScript slide
-show), \f[C]dzslides\f[] (DZSlides HTML5 + JavaScript slide show),
-\f[C]revealjs\f[] (reveal.js HTML5 + JavaScript slide show), \f[C]s5\f[]
-(S5 HTML and JavaScript slide show), \f[C]pptx\f[] (PowerPoint slide
-show) or the path of a custom lua writer (see Custom writers, below).
-(\f[C]markdown_github\f[] provides deprecated and less accurate support
-for Github\-Flavored Markdown; please use \f[C]gfm\f[] instead, unless
-you use extensions that do not work with \f[C]gfm\f[].) Note that
-\f[C]odt\f[], \f[C]epub\f[], and \f[C]epub3\f[] output will not be
-directed to \f[I]stdout\f[]; an output filename must be specified using
-the \f[C]\-o/\-\-output\f[] option.
-Extensions can be individually enabled or disabled by appending
-\f[C]+EXTENSION\f[] or \f[C]\-EXTENSION\f[] to the format name.
-See Extensions below, for a list of extensions and their names.
-See \f[C]\-\-list\-output\-formats\f[] and
-\f[C]\-\-list\-extensions\f[], below.
-.RS
-.RE
-.TP
-.B \f[C]\-o\f[] \f[I]FILE\f[], \f[C]\-\-output=\f[]\f[I]FILE\f[]
-Write output to \f[I]FILE\f[] instead of \f[I]stdout\f[].
-If \f[I]FILE\f[] is \f[C]\-\f[], output will go to \f[I]stdout\f[], even
-if a non\-textual format (\f[C]docx\f[], \f[C]odt\f[], \f[C]epub2\f[],
-\f[C]epub3\f[]) is specified.
-.RS
-.RE
-.TP
-.B \f[C]\-\-data\-dir=\f[]\f[I]DIRECTORY\f[]
-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[]
-.fi
-.PP
-in Windows XP:
-.IP
-.nf
-\f[C]
-C:\\Documents\ And\ Settings\\USERNAME\\Application\ Data\\pandoc
-\f[]
-.fi
-.PP
-and in Windows Vista or later:
-.IP
-.nf
-\f[C]
-C:\\Users\\USERNAME\\AppData\\Roaming\\pandoc
-\f[]
-.fi
-.PP
-You can find the default user data directory on your system by looking
-at the output of \f[C]pandoc\ \-\-version\f[].
-A \f[C]reference.odt\f[], \f[C]reference.docx\f[], \f[C]epub.css\f[],
-\f[C]templates\f[], \f[C]slidy\f[], \f[C]slideous\f[], or \f[C]s5\f[]
-directory placed in this directory will override pandoc\[aq]s normal
-defaults.
-.RE
-.TP
-.B \f[C]\-\-bash\-completion\f[]
-Generate a bash completion script.
-To enable bash completion with pandoc, add this to your
-\f[C]\&.bashrc\f[]:
-.RS
-.IP
-.nf
-\f[C]
-\ eval\ "$(pandoc\ \-\-bash\-completion)"
-\f[]
-.fi
-.RE
-.TP
-.B \f[C]\-\-verbose\f[]
-Give verbose debugging output.
-Currently this only has an effect with PDF output.
-.RS
-.RE
-.TP
-.B \f[C]\-\-quiet\f[]
-Suppress warning messages.
-.RS
-.RE
-.TP
-.B \f[C]\-\-fail\-if\-warnings\f[]
-Exit with error status if there are any warnings.
-.RS
-.RE
-.TP
-.B \f[C]\-\-log=\f[]\f[I]FILE\f[]
-Write log messages in machine\-readable JSON format to \f[I]FILE\f[].
-All messages above DEBUG level will be written, regardless of verbosity
-settings (\f[C]\-\-verbose\f[], \f[C]\-\-quiet\f[]).
-.RS
-.RE
-.TP
-.B \f[C]\-\-list\-input\-formats\f[]
-List supported input formats, one per line.
-.RS
-.RE
-.TP
-.B \f[C]\-\-list\-output\-formats\f[]
-List supported output formats, one per line.
-.RS
-.RE
-.TP
-.B \f[C]\-\-list\-extensions\f[][\f[C]=\f[]\f[I]FORMAT\f[]]
-List supported Markdown extensions, one per line, preceded by a
-\f[C]+\f[] or \f[C]\-\f[] indicating whether it is enabled by default in
-\f[I]FORMAT\f[].
-If \f[I]FORMAT\f[] is not specified, defaults for pandoc\[aq]s Markdown
-are given.
-.RS
-.RE
-.TP
-.B \f[C]\-\-list\-highlight\-languages\f[]
-List supported languages for syntax highlighting, one per line.
-.RS
-.RE
-.TP
-.B \f[C]\-\-list\-highlight\-styles\f[]
-List supported styles for syntax highlighting, one per line.
-See \f[C]\-\-highlight\-style\f[].
-.RS
-.RE
-.TP
-.B \f[C]\-v\f[], \f[C]\-\-version\f[]
-Print version.
-.RS
-.RE
-.TP
-.B \f[C]\-h\f[], \f[C]\-\-help\f[]
-Show usage message.
-.RS
-.RE
-.SS Reader options
-.TP
-.B \f[C]\-\-base\-header\-level=\f[]\f[I]NUMBER\f[]
-Specify the base level for headers (defaults to 1).
-.RS
-.RE
-.TP
-.B \f[C]\-\-strip\-empty\-paragraphs\f[]
-\f[I]Deprecated. Use the \f[CI]+empty_paragraphs\f[I] extension
-instead.\f[] Ignore paragraphs with no content.
-This option is useful for converting word processing documents where
-users have used empty paragraphs to create inter\-paragraph space.
-.RS
-.RE
-.TP
-.B \f[C]\-\-indented\-code\-classes=\f[]\f[I]CLASSES\f[]
-Specify classes to use for indented code blocks\-\-for example,
-\f[C]perl,numberLines\f[] or \f[C]haskell\f[].
-Multiple classes may be separated by spaces or commas.
-.RS
-.RE
-.TP
-.B \f[C]\-\-default\-image\-extension=\f[]\f[I]EXTENSION\f[]
-Specify a default extension to use when image paths/URLs have no
-extension.
-This allows you to use the same source for formats that require
-different kinds of images.
-Currently this option only affects the Markdown and LaTeX readers.
-.RS
-.RE
-.TP
-.B \f[C]\-\-file\-scope\f[]
-Parse each file individually before combining for multifile documents.
-This will allow footnotes in different files with the same identifiers
-to work as expected.
-If this option is set, footnotes and links will not work across files.
-Reading binary files (docx, odt, epub) implies \f[C]\-\-file\-scope\f[].
-.RS
-.RE
-.TP
-.B \f[C]\-\-filter=\f[]\f[I]PROGRAM\f[]
-Specify an executable to be used as a filter transforming the pandoc AST
-after the input is parsed and before the output is written.
-The executable should read JSON from stdin and write JSON to stdout.
-The JSON must be formatted like pandoc\[aq]s own JSON input and output.
-The name of the output format will be passed to the filter as the first
-argument.
-Hence,
-.RS
-.IP
-.nf
-\f[C]
-pandoc\ \-\-filter\ ./caps.py\ \-t\ latex
-\f[]
-.fi
-.PP
-is equivalent to
-.IP
-.nf
-\f[C]
-pandoc\ \-t\ json\ |\ ./caps.py\ latex\ |\ pandoc\ \-f\ json\ \-t\ latex
-\f[]
-.fi
-.PP
-The latter form may be useful for debugging filters.
-.PP
-Filters may be written in any language.
-\f[C]Text.Pandoc.JSON\f[] exports \f[C]toJSONFilter\f[] to facilitate
-writing filters in Haskell.
-Those who would prefer to write filters in python can use the module
-\f[C]pandocfilters\f[], installable from PyPI.
-There are also pandoc filter libraries in PHP, perl, and
-JavaScript/node.js.
-.PP
-In order of preference, pandoc will look for filters in
-.IP "1." 3
-a specified full or relative path (executable or non\-executable)
-.IP "2." 3
-\f[C]$DATADIR/filters\f[] (executable or non\-executable) where
-\f[C]$DATADIR\f[] is the user data directory (see
-\f[C]\-\-data\-dir\f[], above).
-.IP "3." 3
-\f[C]$PATH\f[] (executable only)
-.RE
-.TP
-.B \f[C]\-\-lua\-filter=\f[]\f[I]SCRIPT\f[]
-Transform the document in a similar fashion as JSON filters (see
-\f[C]\-\-filter\f[]), but use pandoc\[aq]s build\-in lua filtering
-system.
-The given lua script is expected to return a list of lua filters which
-will be applied in order.
-Each lua filter must contain element\-transforming functions indexed by
-the name of the AST element on which the filter function should be
-applied.
-.RS
-.PP
-The \f[C]pandoc\f[] lua module provides helper functions for element
-creation.
-It is always loaded into the script\[aq]s lua environment.
-.PP
-The following is an example lua script for macro\-expansion:
-.IP
-.nf
-\f[C]
-function\ expand_hello_world(inline)
-\ \ if\ inline.c\ ==\ \[aq]{{helloworld}}\[aq]\ then
-\ \ \ \ return\ pandoc.Emph{\ pandoc.Str\ "Hello,\ World"\ }
-\ \ else
-\ \ \ \ return\ inline
-\ \ end
-end
-
-return\ {{Str\ =\ expand_hello_world}}
-\f[]
-.fi
-.RE
-.TP
-.B \f[C]\-M\f[] \f[I]KEY\f[][\f[C]=\f[]\f[I]VAL\f[]], \f[C]\-\-metadata=\f[]\f[I]KEY\f[][\f[C]:\f[]\f[I]VAL\f[]]
-Set the metadata field \f[I]KEY\f[] to the value \f[I]VAL\f[].
-A value specified on the command line overrides a value specified in the
-document.
-Values will be parsed as YAML boolean or string values.
-If no value is specified, the value will be treated as Boolean true.
-Like \f[C]\-\-variable\f[], \f[C]\-\-metadata\f[] causes template
-variables to be set.
-But unlike \f[C]\-\-variable\f[], \f[C]\-\-metadata\f[] affects the
-metadata of the underlying document (which is accessible from filters
-and may be printed in some output formats).
-.RS
-.RE
-.TP
-.B \f[C]\-p\f[], \f[C]\-\-preserve\-tabs\f[]
-Preserve tabs instead of converting them to spaces (the default).
-Note that this will only affect tabs in literal code spans and code
-blocks; tabs in regular text will be treated as spaces.
-.RS
-.RE
-.TP
-.B \f[C]\-\-tab\-stop=\f[]\f[I]NUMBER\f[]
-Specify the number of spaces per tab (default is 4).
-.RS
-.RE
-.TP
-.B \f[C]\-\-track\-changes=accept\f[]|\f[C]reject\f[]|\f[C]all\f[]
-Specifies what to do with insertions, deletions, and comments produced
-by the MS Word "Track Changes" feature.
-\f[C]accept\f[] (the default), inserts all insertions, and ignores all
-deletions.
-\f[C]reject\f[] inserts all deletions and ignores insertions.
-Both \f[C]accept\f[] and \f[C]reject\f[] ignore comments.
-\f[C]all\f[] puts in insertions, deletions, and comments, wrapped in
-spans with \f[C]insertion\f[], \f[C]deletion\f[],
-\f[C]comment\-start\f[], and \f[C]comment\-end\f[] classes,
-respectively.
-The author and time of change is included.
-\f[C]all\f[] is useful for scripting: only accepting changes from a
-certain reviewer, say, or before a certain date.
-This option only affects the docx reader.
-.RS
-.RE
-.TP
-.B \f[C]\-\-extract\-media=\f[]\f[I]DIR\f[]
-Extract images and other media contained in or linked from the source
-document to the path \f[I]DIR\f[], creating it if necessary, and adjust
-the images references in the document so they point to the extracted
-files.
-If the source format is a binary container (docx, epub, or odt), the
-media is extracted from the container and the original filenames are
-used.
-Otherwise the media is read from the file system or downloaded, and new
-filenames are constructed based on SHA1 hashes of the contents.
-.RS
-.RE
-.TP
-.B \f[C]\-\-abbreviations=\f[]\f[I]FILE\f[]
-Specifies a custom abbreviations file, with abbreviations one to a line.
-If this option is not specified, pandoc will read the data file
-\f[C]abbreviations\f[] from the user data directory or fall back on a
-system default.
-To see the system default, use
-\f[C]pandoc\ \-\-print\-default\-data\-file=abbreviations\f[].
-The only use pandoc makes of this list is in the Markdown reader.
-Strings ending in a period that are found in this list will be followed
-by a nonbreaking space, so that the period will not produce
-sentence\-ending space in formats like LaTeX.
-.RS
-.RE
-.SS General writer options
-.TP
-.B \f[C]\-s\f[], \f[C]\-\-standalone\f[]
-Produce output with an appropriate header and footer (e.g.
-a standalone HTML, LaTeX, TEI, or RTF file, not a fragment).
-This option is set automatically for \f[C]pdf\f[], \f[C]epub\f[],
-\f[C]epub3\f[], \f[C]fb2\f[], \f[C]docx\f[], and \f[C]odt\f[] output.
-.RS
-.RE
-.TP
-.B \f[C]\-\-template=\f[]\f[I]FILE\f[]
-Use \f[I]FILE\f[] as a custom template for the generated document.
-Implies \f[C]\-\-standalone\f[].
-See Templates, below, for a description of template syntax.
-If no extension is specified, an extension corresponding to the writer
-will be added, so that \f[C]\-\-template=special\f[] looks for
-\f[C]special.html\f[] for HTML output.
-If the template is not found, pandoc will search for it in the
-\f[C]templates\f[] subdirectory of the user data directory (see
-\f[C]\-\-data\-dir\f[]).
-If this option is not used, a default template appropriate for the
-output format will be used (see
-\f[C]\-D/\-\-print\-default\-template\f[]).
-.RS
-.RE
-.TP
-.B \f[C]\-V\f[] \f[I]KEY\f[][\f[C]=\f[]\f[I]VAL\f[]], \f[C]\-\-variable=\f[]\f[I]KEY\f[][\f[C]:\f[]\f[I]VAL\f[]]
-Set the template variable \f[I]KEY\f[] to the value \f[I]VAL\f[] when
-rendering the document in standalone mode.
-This is generally only useful when the \f[C]\-\-template\f[] option is
-used to specify a custom template, since pandoc automatically sets the
-variables used in the default templates.
-If no \f[I]VAL\f[] is specified, the key will be given the value
-\f[C]true\f[].
-.RS
-.RE
-.TP
-.B \f[C]\-D\f[] \f[I]FORMAT\f[], \f[C]\-\-print\-default\-template=\f[]\f[I]FORMAT\f[]
-Print the system default template for an output \f[I]FORMAT\f[].
-(See \f[C]\-t\f[] for a list of possible \f[I]FORMAT\f[]s.) Templates in
-the user data directory are ignored.
-.RS
-.RE
-.TP
-.B \f[C]\-\-print\-default\-data\-file=\f[]\f[I]FILE\f[]
-Print a system default data file.
-Files in the user data directory are ignored.
-.RS
-.RE
-.TP
-.B \f[C]\-\-eol=crlf\f[]|\f[C]lf\f[]|\f[C]native\f[]
-Manually specify line endings: \f[C]crlf\f[] (Windows), \f[C]lf\f[]
-(macOS/Linux/UNIX), or \f[C]native\f[] (line endings appropriate to the
-OS on which pandoc is being run).
-The default is \f[C]native\f[].
-.RS
-.RE
-.TP
-.B \f[C]\-\-dpi\f[]=\f[I]NUMBER\f[]
-Specify the dpi (dots per inch) value for conversion from pixels to
-inch/centimeters and vice versa.
-The default is 96dpi.
-Technically, the correct term would be ppi (pixels per inch).
-.RS
-.RE
-.TP
-.B \f[C]\-\-wrap=auto\f[]|\f[C]none\f[]|\f[C]preserve\f[]
-Determine how text is wrapped in the output (the source code, not the
-rendered version).
-With \f[C]auto\f[] (the default), pandoc will attempt to wrap lines to
-the column width specified by \f[C]\-\-columns\f[] (default 72).
-With \f[C]none\f[], pandoc will not wrap lines at all.
-With \f[C]preserve\f[], pandoc will attempt to preserve the wrapping
-from the source document (that is, where there are nonsemantic newlines
-in the source, there will be nonsemantic newlines in the output as
-well).
-Automatic wrapping does not currently work in HTML output.
-.RS
-.RE
-.TP
-.B \f[C]\-\-columns=\f[]\f[I]NUMBER\f[]
-Specify length of lines in characters.
-This affects text wrapping in the generated source code (see
-\f[C]\-\-wrap\f[]).
-It also affects calculation of column widths for plain text tables (see
-Tables below).
-.RS
-.RE
-.TP
-.B \f[C]\-\-toc\f[], \f[C]\-\-table\-of\-contents\f[]
-Include an automatically generated table of contents (or, in the case of
-\f[C]latex\f[], \f[C]context\f[], \f[C]docx\f[], \f[C]odt\f[],
-\f[C]opendocument\f[], \f[C]rst\f[], or \f[C]ms\f[], an instruction to
-create one) in the output document.
-This option has no effect on \f[C]man\f[], \f[C]docbook4\f[],
-\f[C]docbook5\f[], or \f[C]jats\f[] output.
-.RS
-.RE
-.TP
-.B \f[C]\-\-toc\-depth=\f[]\f[I]NUMBER\f[]
-Specify the number of section levels to include in the table of
-contents.
-The default is 3 (which means that level 1, 2, and 3 headers will be
-listed in the contents).
-.RS
-.RE
-.TP
-.B \f[C]\-\-strip\-comments\f[]
-Strip out HTML comments in the Markdown or Textile source, rather than
-passing them on to Markdown, Textile or HTML output as raw HTML.
-This does not apply to HTML comments inside raw HTML blocks when the
-\f[C]markdown_in_html_blocks\f[] extension is not set.
-.RS
-.RE
-.TP
-.B \f[C]\-\-no\-highlight\f[]
-Disables syntax highlighting for code blocks and inlines, even when a
-language attribute is given.
-.RS
-.RE
-.TP
-.B \f[C]\-\-highlight\-style=\f[]\f[I]STYLE\f[]|\f[I]FILE\f[]
-Specifies the coloring style to be used in highlighted source code.
-Options are \f[C]pygments\f[] (the default), \f[C]kate\f[],
-\f[C]monochrome\f[], \f[C]breezeDark\f[], \f[C]espresso\f[],
-\f[C]zenburn\f[], \f[C]haddock\f[], and \f[C]tango\f[].
-For more information on syntax highlighting in pandoc, see Syntax
-highlighting, below.
-See also \f[C]\-\-list\-highlight\-styles\f[].
-.RS
-.PP
-Instead of a \f[I]STYLE\f[] name, a JSON file with extension
-\f[C]\&.theme\f[] may be supplied.
-This will be parsed as a KDE syntax highlighting theme and (if valid)
-used as the highlighting style.
-.PP
-To generate the JSON version of an existing style, use
-\f[C]\-\-print\-highlight\-style\f[].
-.RE
-.TP
-.B \f[C]\-\-print\-highlight\-style=\f[]\f[I]STYLE\f[]|\f[I]FILE\f[]
-Prints a JSON version of a highlighting style, which can be modified,
-saved with a \f[C]\&.theme\f[] extension, and used with
-\f[C]\-\-highlight\-style\f[].
-.RS
-.RE
-.TP
-.B \f[C]\-\-syntax\-definition=\f[]\f[I]FILE\f[]
-Instructs pandoc to load a KDE XML syntax definition file, which will be
-used for syntax highlighting of appropriately marked code blocks.
-This can be used to add support for new languages or to use altered
-syntax definitions for existing languages.
-.RS
-.RE
-.TP
-.B \f[C]\-H\f[] \f[I]FILE\f[], \f[C]\-\-include\-in\-header=\f[]\f[I]FILE\f[]
-Include contents of \f[I]FILE\f[], verbatim, at the end of the header.
-This can be used, for example, to include special CSS or JavaScript in
-HTML documents.
-This option can be used repeatedly to include multiple files in the
-header.
-They will be included in the order specified.
-Implies \f[C]\-\-standalone\f[].
-.RS
-.RE
-.TP
-.B \f[C]\-B\f[] \f[I]FILE\f[], \f[C]\-\-include\-before\-body=\f[]\f[I]FILE\f[]
-Include contents of \f[I]FILE\f[], verbatim, at the beginning of the
-document body (e.g.
-after the \f[C]<body>\f[] tag in HTML, or the \f[C]\\begin{document}\f[]
-command in LaTeX).
-This can be used to include navigation bars or banners in HTML
-documents.
-This option can be used repeatedly to include multiple files.
-They will be included in the order specified.
-Implies \f[C]\-\-standalone\f[].
-.RS
-.RE
-.TP
-.B \f[C]\-A\f[] \f[I]FILE\f[], \f[C]\-\-include\-after\-body=\f[]\f[I]FILE\f[]
-Include contents of \f[I]FILE\f[], verbatim, at the end of the document
-body (before the \f[C]</body>\f[] tag in HTML, or the
-\f[C]\\end{document}\f[] command in LaTeX).
-This option can be used repeatedly to include multiple files.
-They will be included in the order specified.
-Implies \f[C]\-\-standalone\f[].
-.RS
-.RE
-.TP
-.B \f[C]\-\-resource\-path=\f[]\f[I]SEARCHPATH\f[]
-List of paths to search for images and other resources.
-The paths should be separated by \f[C]:\f[] on Linux, UNIX, and macOS
-systems, and by \f[C];\f[] on Windows.
-If \f[C]\-\-resource\-path\f[] is not specified, the default resource
-path is the working directory.
-Note that, if \f[C]\-\-resource\-path\f[] is specified, the working
-directory must be explicitly listed or it will not be searched.
-For example: \f[C]\-\-resource\-path=.:test\f[] will search the working
-directory and the \f[C]test\f[] subdirectory, in that order.
-.RS
-.RE
-.TP
-.B \f[C]\-\-request\-header=\f[]\f[I]NAME\f[]\f[C]:\f[]\f[I]VAL\f[]
-Set the request header \f[I]NAME\f[] to the value \f[I]VAL\f[] when
-making HTTP requests (for example, when a URL is given on the command
-line, or when resources used in a document must be downloaded).
-.RS
-.RE
-.SS Options affecting specific writers
-.TP
-.B \f[C]\-\-self\-contained\f[]
-Produce a standalone HTML file with no external dependencies, using
-\f[C]data:\f[] URIs to incorporate the contents of linked scripts,
-stylesheets, images, and videos.
-The resulting file should be "self\-contained," in the sense that it
-needs no external files and no net access to be displayed properly by a
-browser.
-This option works only with HTML output formats, including
-\f[C]html4\f[], \f[C]html5\f[], \f[C]html+lhs\f[], \f[C]html5+lhs\f[],
-\f[C]s5\f[], \f[C]slidy\f[], \f[C]slideous\f[], \f[C]dzslides\f[], and
-\f[C]revealjs\f[].
-Scripts, images, and stylesheets at absolute URLs will be downloaded;
-those at relative URLs will be sought relative to the working directory
-(if the first source file is local) or relative to the base URL (if the
-first source file is remote).
-Elements with the attribute \f[C]data\-external="1"\f[] will be left
-alone; the documents they link to will not be incorporated in the
-document.
-Limitation: resources that are loaded dynamically through JavaScript
-cannot be incorporated; as a result, \f[C]\-\-self\-contained\f[] does
-not work with \f[C]\-\-mathjax\f[], and some advanced features (e.g.
-zoom or speaker notes) may not work in an offline "self\-contained"
-\f[C]reveal.js\f[] slide show.
-.RS
-.RE
-.TP
-.B \f[C]\-\-html\-q\-tags\f[]
-Use \f[C]<q>\f[] tags for quotes in HTML.
-.RS
-.RE
-.TP
-.B \f[C]\-\-ascii\f[]
-Use only ASCII characters in output.
-Currently supported only for HTML and DocBook output (which uses
-numerical entities instead of UTF\-8 when this option is selected).
-.RS
-.RE
-.TP
-.B \f[C]\-\-reference\-links\f[]
-Use reference\-style links, rather than inline links, in writing
-Markdown or reStructuredText.
-By default inline links are used.
-The placement of link references is affected by the
-\f[C]\-\-reference\-location\f[] option.
-.RS
-.RE
-.TP
-.B \f[C]\-\-reference\-location\ =\ block\f[]|\f[C]section\f[]|\f[C]document\f[]
-Specify whether footnotes (and references, if \f[C]reference\-links\f[]
-is set) are placed at the end of the current (top\-level) block, the
-current section, or the document.
-The default is \f[C]document\f[].
-Currently only affects the markdown writer.
-.RS
-.RE
-.TP
-.B \f[C]\-\-atx\-headers\f[]
-Use ATX\-style headers in Markdown and AsciiDoc output.
-The default is to use setext\-style headers for levels 1\-2, and then
-ATX headers.
-(Note: for \f[C]gfm\f[] output, ATX headers are always used.)
-.RS
-.RE
-.TP
-.B \f[C]\-\-top\-level\-division=[default|section|chapter|part]\f[]
-Treat top\-level headers as the given division type in LaTeX, ConTeXt,
-DocBook, and TEI output.
-The hierarchy order is part, chapter, then section; all headers are
-shifted such that the top\-level header becomes the specified type.
-The default behavior is to determine the best division type via
-heuristics: unless other conditions apply, \f[C]section\f[] is chosen.
-When the LaTeX document class is set to \f[C]report\f[], \f[C]book\f[],
-or \f[C]memoir\f[] (unless the \f[C]article\f[] option is specified),
-\f[C]chapter\f[] is implied as the setting for this option.
-If \f[C]beamer\f[] is the output format, specifying either
-\f[C]chapter\f[] or \f[C]part\f[] will cause top\-level headers to
-become \f[C]\\part{..}\f[], while second\-level headers remain as their
-default type.
-.RS
-.RE
-.TP
-.B \f[C]\-N\f[], \f[C]\-\-number\-sections\f[]
-Number section headings in LaTeX, ConTeXt, HTML, or EPUB output.
-By default, sections are not numbered.
-Sections with class \f[C]unnumbered\f[] will never be numbered, even if
-\f[C]\-\-number\-sections\f[] is specified.
-.RS
-.RE
-.TP
-.B \f[C]\-\-number\-offset=\f[]\f[I]NUMBER\f[][\f[C],\f[]\f[I]NUMBER\f[]\f[C],\f[]\f[I]...\f[]]
-Offset for section headings in HTML output (ignored in other output
-formats).
-The first number is added to the section number for top\-level headers,
-the second for second\-level headers, and so on.
-So, for example, if you want the first top\-level header in your
-document to be numbered "6", specify \f[C]\-\-number\-offset=5\f[].
-If your document starts with a level\-2 header which you want to be
-numbered "1.5", specify \f[C]\-\-number\-offset=1,4\f[].
-Offsets are 0 by default.
-Implies \f[C]\-\-number\-sections\f[].
-.RS
-.RE
-.TP
-.B \f[C]\-\-listings\f[]
-Use the \f[C]listings\f[] package for LaTeX code blocks
-.RS
-.RE
-.TP
-.B \f[C]\-i\f[], \f[C]\-\-incremental\f[]
-Make list items in slide shows display incrementally (one by one).
-The default is for lists to be displayed all at once.
-.RS
-.RE
-.TP
-.B \f[C]\-\-slide\-level=\f[]\f[I]NUMBER\f[]
-Specifies that headers with the specified level create slides (for
-\f[C]beamer\f[], \f[C]s5\f[], \f[C]slidy\f[], \f[C]slideous\f[],
-\f[C]dzslides\f[]).
-Headers above this level in the hierarchy are used to divide the slide
-show into sections; headers below this level create subheads within a
-slide.
-Note that content that is not contained under slide\-level headers will
-not appear in the slide show.
-The default is to set the slide level based on the contents of the
-document; see Structuring the slide show.
-.RS
-.RE
-.TP
-.B \f[C]\-\-section\-divs\f[]
-Wrap sections in \f[C]<section>\f[] tags (or \f[C]<div>\f[] tags for
-\f[C]html4\f[]), and attach identifiers to the enclosing
-\f[C]<section>\f[] (or \f[C]<div>\f[]) rather than the header itself.
-See Header identifiers, below.
-.RS
-.RE
-.TP
-.B \f[C]\-\-email\-obfuscation=none\f[]|\f[C]javascript\f[]|\f[C]references\f[]
-Specify a method for obfuscating \f[C]mailto:\f[] links in HTML
-documents.
-\f[C]none\f[] leaves \f[C]mailto:\f[] links as they are.
-\f[C]javascript\f[] obfuscates them using JavaScript.
-\f[C]references\f[] obfuscates them by printing their letters as decimal
-or hexadecimal character references.
-The default is \f[C]none\f[].
-.RS
-.RE
-.TP
-.B \f[C]\-\-id\-prefix=\f[]\f[I]STRING\f[]
-Specify a prefix to be added to all identifiers and internal links in
-HTML and DocBook output, and to footnote numbers in Markdown and Haddock
-output.
-This is useful for preventing duplicate identifiers when generating
-fragments to be included in other pages.
-.RS
-.RE
-.TP
-.B \f[C]\-T\f[] \f[I]STRING\f[], \f[C]\-\-title\-prefix=\f[]\f[I]STRING\f[]
-Specify \f[I]STRING\f[] as a prefix at the beginning of the title that
-appears in the HTML header (but not in the title as it appears at the
-beginning of the HTML body).
-Implies \f[C]\-\-standalone\f[].
-.RS
-.RE
-.TP
-.B \f[C]\-c\f[] \f[I]URL\f[], \f[C]\-\-css=\f[]\f[I]URL\f[]
-Link to a CSS style sheet.
-This option can be used repeatedly to include multiple files.
-They will be included in the order specified.
-.RS
-.PP
-A stylesheet is required for generating EPUB.
-If none is provided using this option (or the \f[C]stylesheet\f[]
-metadata field), pandoc will look for a file \f[C]epub.css\f[] in the
-user data directory (see \f[C]\-\-data\-dir\f[]).
-If it is not found there, sensible defaults will be used.
-.RE
-.TP
-.B \f[C]\-\-reference\-doc=\f[]\f[I]FILE\f[]
-Use the specified file as a style reference in producing a docx or ODT
-file.
-.RS
-.TP
-.B Docx
-For best results, the reference docx should be a modified version of a
-docx file produced using pandoc.
-The contents of the reference docx are ignored, but its stylesheets and
-document properties (including margins, page size, header, and footer)
-are used in the new docx.
-If no reference docx is specified on the command line, pandoc will look
-for a file \f[C]reference.docx\f[] in the user data directory (see
-\f[C]\-\-data\-dir\f[]).
-If this is not found either, sensible defaults will be used.
-.RS
-.PP
-To produce a custom \f[C]reference.docx\f[], first get a copy of the
-default \f[C]reference.docx\f[]:
-\f[C]pandoc\ \-\-print\-default\-data\-file\ reference.docx\ >\ custom\-reference.docx\f[].
-Then open \f[C]custom\-reference.docx\f[] 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] Normal, Body Text, First
-Paragraph, Compact, Title, Subtitle, Author, Date, Abstract,
-Bibliography, Heading 1, Heading 2, Heading 3, Heading 4, Heading 5,
-Heading 6, Heading 7, Heading 8, Heading 9, Block Text, Footnote Text,
-Definition Term, Definition, Caption, Table Caption, Image Caption,
-Figure, Captioned Figure, TOC Heading; [character] Default Paragraph
-Font, Body Text Char, Verbatim Char, Footnote Reference, Hyperlink;
-[table] Table.
-.RE
-.TP
-.B ODT
-For best results, the reference ODT should be a modified version of an
-ODT produced using pandoc.
-The contents of the reference ODT are ignored, but its stylesheets are
-used in the new ODT.
-If no reference ODT is specified on the command line, pandoc will look
-for a file \f[C]reference.odt\f[] in the user data directory (see
-\f[C]\-\-data\-dir\f[]).
-If this is not found either, sensible defaults will be used.
-.RS
-.PP
-To produce a custom \f[C]reference.odt\f[], first get a copy of the
-default \f[C]reference.odt\f[]:
-\f[C]pandoc\ \-\-print\-default\-data\-file\ reference.odt\ >\ custom\-reference.odt\f[].
-Then open \f[C]custom\-reference.odt\f[] in LibreOffice, modify the
-styles as you wish, and save the file.
-.RE
-.RE
-.TP
-.B \f[C]\-\-epub\-cover\-image=\f[]\f[I]FILE\f[]
-Use the specified image as the EPUB cover.
-It is recommended that the image be less than 1000px in width and
-height.
-Note that in a Markdown source document you can also specify
-\f[C]cover\-image\f[] in a YAML metadata block (see EPUB Metadata,
-below).
-.RS
-.RE
-.TP
-.B \f[C]\-\-epub\-metadata=\f[]\f[I]FILE\f[]
-Look in the specified XML file for metadata for the EPUB.
-The file should contain a series of Dublin Core elements.
-For example:
-.RS
-.IP
-.nf
-\f[C]
-\ <dc:rights>Creative\ Commons</dc:rights>
-\ <dc:language>es\-AR</dc:language>
-\f[]
-.fi
-.PP
-By default, pandoc will include the following metadata elements:
-\f[C]<dc:title>\f[] (from the document title), \f[C]<dc:creator>\f[]
-(from the document authors), \f[C]<dc:date>\f[] (from the document date,
-which should be in ISO 8601 format), \f[C]<dc:language>\f[] (from the
-\f[C]lang\f[] variable, or, if is not set, the locale), and
-\f[C]<dc:identifier\ id="BookId">\f[] (a randomly generated UUID).
-Any of these may be overridden by elements in the metadata file.
-.PP
-Note: if the source document is Markdown, a YAML metadata block in the
-document can be used instead.
-See below under EPUB Metadata.
-.RE
-.TP
-.B \f[C]\-\-epub\-embed\-font=\f[]\f[I]FILE\f[]
-Embed the specified font in the EPUB.
-This option can be repeated to embed multiple fonts.
-Wildcards can also be used: for example, \f[C]DejaVuSans\-*.ttf\f[].
-However, if you use wildcards on the command line, be sure to escape
-them or put the whole filename in single quotes, to prevent them from
-being interpreted by the shell.
-To use the embedded fonts, you will need to add declarations like the
-following to your CSS (see \f[C]\-\-css\f[]):
-.RS
-.IP
-.nf
-\f[C]
-\@font\-face\ {
-font\-family:\ DejaVuSans;
-font\-style:\ normal;
-font\-weight:\ normal;
-src:url("DejaVuSans\-Regular.ttf");
-}
-\@font\-face\ {
-font\-family:\ DejaVuSans;
-font\-style:\ normal;
-font\-weight:\ bold;
-src:url("DejaVuSans\-Bold.ttf");
-}
-\@font\-face\ {
-font\-family:\ DejaVuSans;
-font\-style:\ italic;
-font\-weight:\ normal;
-src:url("DejaVuSans\-Oblique.ttf");
-}
-\@font\-face\ {
-font\-family:\ DejaVuSans;
-font\-style:\ italic;
-font\-weight:\ bold;
-src:url("DejaVuSans\-BoldOblique.ttf");
-}
-body\ {\ font\-family:\ "DejaVuSans";\ }
-\f[]
-.fi
-.RE
-.TP
-.B \f[C]\-\-epub\-chapter\-level=\f[]\f[I]NUMBER\f[]
-Specify the header level at which to split the EPUB into separate
-"chapter" files.
-The default is to split into chapters at level 1 headers.
-This option only affects the internal composition of the EPUB, not the
-way chapters and sections are displayed to users.
-Some readers may be slow if the chapter files are too large, so for
-large documents with few level 1 headers, one might want to use a
-chapter level of 2 or 3.
-.RS
-.RE
-.TP
-.B \f[C]\-\-epub\-subdirectory=\f[]\f[I]DIRNAME\f[]
-Specify the subdirectory in the OCF container that is to hold the
-EPUB\-specific contents.
-The default is \f[C]EPUB\f[].
-To put the EPUB contents in the top level, use an empty string.
-.RS
-.RE
-.TP
-.B \f[C]\-\-pdf\-engine=pdflatex\f[]|\f[C]lualatex\f[]|\f[C]xelatex\f[]|\f[C]wkhtmltopdf\f[]|\f[C]weasyprint\f[]|\f[C]prince\f[]|\f[C]context\f[]|\f[C]pdfroff\f[]
-Use the specified engine when producing PDF output.
-The default is \f[C]pdflatex\f[].
-If the engine is not in your PATH, the full path of the engine may be
-specified here.
-.RS
-.RE
-.TP
-.B \f[C]\-\-pdf\-engine\-opt=\f[]\f[I]STRING\f[]
-Use the given string as a command\-line argument to the
-\f[C]pdf\-engine\f[].
-If used multiple times, the arguments are provided with spaces between
-them.
-Note that no check for duplicate options is done.
-.RS
-.RE
-.SS Citation rendering
-.TP
-.B \f[C]\-\-bibliography=\f[]\f[I]FILE\f[]
-Set the \f[C]bibliography\f[] field in the document\[aq]s metadata to
-\f[I]FILE\f[], overriding any value set in the metadata, and process
-citations using \f[C]pandoc\-citeproc\f[].
-(This is equivalent to
-\f[C]\-\-metadata\ bibliography=FILE\ \-\-filter\ pandoc\-citeproc\f[].)
-If \f[C]\-\-natbib\f[] or \f[C]\-\-biblatex\f[] is also supplied,
-\f[C]pandoc\-citeproc\f[] is not used, making this equivalent to
-\f[C]\-\-metadata\ bibliography=FILE\f[].
-If you supply this argument multiple times, each \f[I]FILE\f[] will be
-added to bibliography.
-.RS
-.RE
-.TP
-.B \f[C]\-\-csl=\f[]\f[I]FILE\f[]
-Set the \f[C]csl\f[] field in the document\[aq]s metadata to
-\f[I]FILE\f[], overriding any value set in the metadata.
-(This is equivalent to \f[C]\-\-metadata\ csl=FILE\f[].) This option is
-only relevant with \f[C]pandoc\-citeproc\f[].
-.RS
-.RE
-.TP
-.B \f[C]\-\-citation\-abbreviations=\f[]\f[I]FILE\f[]
-Set the \f[C]citation\-abbreviations\f[] field in the document\[aq]s
-metadata to \f[I]FILE\f[], overriding any value set in the metadata.
-(This is equivalent to
-\f[C]\-\-metadata\ citation\-abbreviations=FILE\f[].) This option is
-only relevant with \f[C]pandoc\-citeproc\f[].
-.RS
-.RE
-.TP
-.B \f[C]\-\-natbib\f[]
-Use \f[C]natbib\f[] for citations in LaTeX output.
-This option is not for use with the \f[C]pandoc\-citeproc\f[] filter or
-with PDF output.
-It is intended for use in producing a LaTeX file that can be processed
-with \f[C]bibtex\f[].
-.RS
-.RE
-.TP
-.B \f[C]\-\-biblatex\f[]
-Use \f[C]biblatex\f[] for citations in LaTeX output.
-This option is not for use with the \f[C]pandoc\-citeproc\f[] filter or
-with PDF output.
-It is intended for use in producing a LaTeX file that can be processed
-with \f[C]bibtex\f[] or \f[C]biber\f[].
-.RS
-.RE
-.SS Math rendering in HTML
-.PP
-The default is to render TeX math as far as possible using Unicode
-characters.
-Formulas are put inside a \f[C]span\f[] with \f[C]class="math"\f[], so
-that they may be styled differently from the surrounding text if needed.
-However, this gives acceptable results only for basic math, usually you
-will want to use \f[C]\-\-mathjax\f[] or another of the following
-options.
-.TP
-.B \f[C]\-\-mathjax\f[][\f[C]=\f[]\f[I]URL\f[]]
-Use MathJax to display embedded TeX math in HTML output.
-TeX math will be put between \f[C]\\(...\\)\f[] (for inline math) or
-\f[C]\\[...\\]\f[] (for display math) and wrapped in \f[C]<span>\f[]
-tags with class \f[C]math\f[].
-Then the MathJax JavaScript will render it.
-The \f[I]URL\f[] should point to the \f[C]MathJax.js\f[] load script.
-If a \f[I]URL\f[] is not provided, a link to the Cloudflare CDN will be
-inserted.
-.RS
-.RE
-.TP
-.B \f[C]\-\-mathml\f[]
-Convert TeX math to MathML (in \f[C]epub3\f[], \f[C]docbook4\f[],
-\f[C]docbook5\f[], \f[C]jats\f[], \f[C]html4\f[] and \f[C]html5\f[]).
-This is the default in \f[C]odt\f[] output.
-Note that currently only Firefox and Safari (and select e\-book readers)
-natively support MathML.
-.RS
-.RE
-.TP
-.B \f[C]\-\-webtex\f[][\f[C]=\f[]\f[I]URL\f[]]
-Convert TeX formulas to \f[C]<img>\f[] tags that link to an external
-script that converts formulas to images.
-The formula will be URL\-encoded and concatenated with the URL provided.
-For SVG images you can for example use
-\f[C]\-\-webtex\ https://latex.codecogs.com/svg.latex?\f[].
-If no URL is specified, the CodeCogs URL generating PNGs will be used
-(\f[C]https://latex.codecogs.com/png.latex?\f[]).
-Note: the \f[C]\-\-webtex\f[] option will affect Markdown output as well
-as HTML, which is useful if you\[aq]re targeting a version of Markdown
-without native math support.
-.RS
-.RE
-.TP
-.B \f[C]\-\-katex\f[][\f[C]=\f[]\f[I]URL\f[]]
-Use KaTeX to display embedded TeX math in HTML output.
-The \f[I]URL\f[] is the base URL for the KaTeX library.
-If a \f[I]URL\f[] is not provided, a link to the KaTeX CDN will be
-inserted.
-.RS
-.RE
-.TP
-.B \f[C]\-\-katex\-stylesheet=\f[]\f[I]URL\f[]
-The \f[I]URL\f[] should point to the \f[C]katex.css\f[] stylesheet.
-If this option is not specified, a link to the KaTeX CDN will be
-inserted.
-Note that this option does not imply \f[C]\-\-katex\f[].
-.RS
-.RE
-.TP
-.B \f[C]\-m\f[] [\f[I]URL\f[]], \f[C]\-\-latexmathml\f[][\f[C]=\f[]\f[I]URL\f[]]
-\f[I]Deprecated.\f[] Use the LaTeXMathML script to display embedded TeX
-math in HTML output.
-TeX math will be displayed between \f[C]$\f[] or \f[C]$$\f[] characters
-and put in \f[C]<span>\f[] tags with class \f[C]LaTeX\f[].
-The LaTeXMathML JavaScript will then change it to MathML.
-Note that currently only Firefox and Safari (and select e\-book readers)
-natively support MathML.
-To insert a link the \f[C]LaTeXMathML.js\f[] script, provide a
-\f[I]URL\f[].
-.RS
-.RE
-.TP
-.B \f[C]\-\-jsmath\f[][\f[C]=\f[]\f[I]URL\f[]]
-\f[I]Deprecated.\f[] Use jsMath (the predecessor of MathJax) to display
-embedded TeX math in HTML output.
-TeX math will be put inside \f[C]<span>\f[] tags (for inline math) or
-\f[C]<div>\f[] tags (for display math) with class \f[C]math\f[] and
-rendered by the jsMath script.
-The \f[I]URL\f[] should point to the script (e.g.
-\f[C]jsMath/easy/load.js\f[]); if provided, it will be linked to in the
-header of standalone HTML documents.
-If a \f[I]URL\f[] is not provided, no link to the jsMath load script
-will be inserted; it is then up to the author to provide such a link in
-the HTML template.
-.RS
-.RE
-.TP
-.B \f[C]\-\-gladtex\f[]
-\f[I]Deprecated.\f[] Enclose TeX math in \f[C]<eq>\f[] tags in HTML
-output.
-The resulting HTML can then be processed by gladTeX to produce images of
-the typeset formulas and an HTML file with links to these images.
-So, the procedure is:
-.RS
-.IP
-.nf
-\f[C]
-pandoc\ \-s\ \-\-gladtex\ input.md\ \-o\ myfile.htex
-gladtex\ \-d\ myfile\-images\ myfile.htex
-#\ produces\ myfile.html\ and\ images\ in\ myfile\-images
-\f[]
-.fi
-.RE
-.TP
-.B \f[C]\-\-mimetex\f[][\f[C]=\f[]\f[I]URL\f[]]
-\f[I]Deprecated.\f[] Render TeX math using the mimeTeX CGI script, which
-generates an image for each TeX formula.
-This should work in all browsers.
-If \f[I]URL\f[] is not specified, it is assumed that the script is at
-\f[C]/cgi\-bin/mimetex.cgi\f[].
-.RS
-.RE
-.SS Options for wrapper scripts
-.TP
-.B \f[C]\-\-dump\-args\f[]
-Print information about command\-line arguments to \f[I]stdout\f[], then
-exit.
-This option is intended primarily for use in wrapper scripts.
-The first line of output contains the name of the output file specified
-with the \f[C]\-o\f[] option, or \f[C]\-\f[] (for \f[I]stdout\f[]) if no
-output file was specified.
-The remaining lines contain the command\-line arguments, one per line,
-in the order they appear.
-These do not include regular pandoc options and their arguments, but do
-include any options appearing after a \f[C]\-\-\f[] separator at the end
-of the line.
-.RS
-.RE
-.TP
-.B \f[C]\-\-ignore\-args\f[]
-Ignore command\-line arguments (for use in wrapper scripts).
-Regular pandoc options are not ignored.
-Thus, for example,
-.RS
-.IP
-.nf
-\f[C]
-pandoc\ \-\-ignore\-args\ \-o\ foo.html\ \-s\ foo.txt\ \-\-\ \-e\ latin1
-\f[]
-.fi
-.PP
-is equivalent to
-.IP
-.nf
-\f[C]
-pandoc\ \-o\ foo.html\ \-s
-\f[]
-.fi
-.RE
-.SH TEMPLATES
-.PP
-When the \f[C]\-s/\-\-standalone\f[] option is used, pandoc uses a
-template to add header and footer material that is needed for a
-self\-standing document.
-To see the default template that is used, just type
-.IP
-.nf
-\f[C]
-pandoc\ \-D\ *FORMAT*
-\f[]
-.fi
-.PP
-where \f[I]FORMAT\f[] is the name of the output format.
-A custom template can be specified using the \f[C]\-\-template\f[]
-option.
-You can also override the system default templates for a given output
-format \f[I]FORMAT\f[] by putting a file
-\f[C]templates/default.*FORMAT*\f[] in the user data directory (see
-\f[C]\-\-data\-dir\f[], above).
-\f[I]Exceptions:\f[]
-.IP \[bu] 2
-For \f[C]odt\f[] output, customize the \f[C]default.opendocument\f[]
-template.
-.IP \[bu] 2
-For \f[C]pdf\f[] output, customize the \f[C]default.latex\f[] template
-(or the \f[C]default.context\f[] template, if you use
-\f[C]\-t\ context\f[], or the \f[C]default.ms\f[] template, if you use
-\f[C]\-t\ ms\f[], or the \f[C]default.html5\f[] template, if you use
-\f[C]\-t\ html5\f[]).
-.IP \[bu] 2
-\f[C]docx\f[] has no template (however, you can use
-\f[C]\-\-reference\-doc\f[] to customize the output).
-.PP
-Templates contain \f[I]variables\f[], which allow for the inclusion of
-arbitrary information at any point in the file.
-Variables may be set within the document using YAML metadata blocks.
-They may also be set at the command line using the
-\f[C]\-V/\-\-variable\f[] option: variables set in this way override
-metadata fields with the same name.
-.SS Variables set by pandoc
-.PP
-Some variables are set automatically by pandoc.
-These vary somewhat depending on the output format, but include metadata
-fields as well as the following:
-.TP
-.B \f[C]sourcefile\f[], \f[C]outputfile\f[]
-source and destination filenames, as given on the command line.
-\f[C]sourcefile\f[] can also be a list if input comes from multiple
-files, or empty if input is from stdin.
-You can use the following snippet in your template to distinguish them:
-.RS
-.IP
-.nf
-\f[C]
-$if(sourcefile)$
-$for(sourcefile)$
-$sourcefile$
-$endfor$
-$else$
-(stdin)
-$endif$
-\f[]
-.fi
-.PP
-Similarly, \f[C]outputfile\f[] can be \f[C]\-\f[] if output goes to the
-terminal.
-.RE
-.TP
-.B \f[C]title\f[], \f[C]author\f[], \f[C]date\f[]
-allow identification of basic aspects of the document.
-Included in PDF metadata through LaTeX and ConTeXt.
-These can be set through a pandoc title block, which allows for multiple
-authors, or through a YAML metadata block:
-.RS
-.IP
-.nf
-\f[C]
-\-\-\-
-author:
-\-\ Aristotle
-\-\ Peter\ Abelard
-\&...
-\f[]
-.fi
-.RE
-.TP
-.B \f[C]subtitle\f[]
-document subtitle, included in HTML, EPUB, LaTeX, ConTeXt, and Word
-docx; renders in LaTeX only when using a document class that supports
-\f[C]\\subtitle\f[], such as \f[C]beamer\f[] or the KOMA\-Script series
-(\f[C]scrartcl\f[], \f[C]scrreprt\f[], \f[C]scrbook\f[]).
-.RS
-.RE
-.TP
-.B \f[C]institute\f[]
-author affiliations (in LaTeX and Beamer only).
-Can be a list, when there are multiple authors.
-.RS
-.RE
-.TP
-.B \f[C]abstract\f[]
-document summary, included in LaTeX, ConTeXt, AsciiDoc, and Word docx
-.RS
-.RE
-.TP
-.B \f[C]keywords\f[]
-list of keywords to be included in HTML, PDF, and AsciiDoc metadata; may
-be repeated as for \f[C]author\f[], above
-.RS
-.RE
-.TP
-.B \f[C]header\-includes\f[]
-contents specified by \f[C]\-H/\-\-include\-in\-header\f[] (may have
-multiple values)
-.RS
-.RE
-.TP
-.B \f[C]toc\f[]
-non\-null value if \f[C]\-\-toc/\-\-table\-of\-contents\f[] was
-specified
-.RS
-.RE
-.TP
-.B \f[C]toc\-title\f[]
-title of table of contents (works only with EPUB, opendocument, odt,
-docx)
-.RS
-.RE
-.TP
-.B \f[C]include\-before\f[]
-contents specified by \f[C]\-B/\-\-include\-before\-body\f[] (may have
-multiple values)
-.RS
-.RE
-.TP
-.B \f[C]include\-after\f[]
-contents specified by \f[C]\-A/\-\-include\-after\-body\f[] (may have
-multiple values)
-.RS
-.RE
-.TP
-.B \f[C]body\f[]
-body of document
-.RS
-.RE
-.TP
-.B \f[C]meta\-json\f[]
-JSON representation of all of the document\[aq]s metadata.
-Field values are transformed to the selected output format.
-.RS
-.RE
-.SS Language variables
-.TP
-.B \f[C]lang\f[]
-identifies the main language of the document, using a code according to
-BCP 47 (e.g.
-\f[C]en\f[] or \f[C]en\-GB\f[]).
-For some output formats, pandoc will convert it to an appropriate format
-stored in the additional variables \f[C]babel\-lang\f[],
-\f[C]polyglossia\-lang\f[] (LaTeX) and \f[C]context\-lang\f[] (ConTeXt).
-.RS
-.PP
-Native pandoc \f[C]span\f[]s and \f[C]div\f[]s with the lang attribute
-(value in BCP 47) can be used to switch the language in that range.
-.RE
-.TP
-.B \f[C]otherlangs\f[]
-a list of other languages used in the document in the YAML metadata,
-according to BCP 47.
-For example: \f[C]otherlangs:\ [en\-GB,\ fr]\f[].
-This is automatically generated from the \f[C]lang\f[] attributes in all
-\f[C]span\f[]s and \f[C]div\f[]s but can be overridden.
-Currently only used by LaTeX through the generated
-\f[C]babel\-otherlangs\f[] and \f[C]polyglossia\-otherlangs\f[]
-variables.
-The LaTeX writer outputs polyglossia commands in the text but the
-\f[C]babel\-newcommands\f[] variable contains mappings for them to the
-corresponding babel.
-.RS
-.RE
-.TP
-.B \f[C]dir\f[]
-the base direction of the document, either \f[C]rtl\f[]
-(right\-to\-left) or \f[C]ltr\f[] (left\-to\-right).
-.RS
-.PP
-For bidirectional documents, native pandoc \f[C]span\f[]s and
-\f[C]div\f[]s with the \f[C]dir\f[] attribute (value \f[C]rtl\f[] or
-\f[C]ltr\f[]) can be used to override the base direction in some output
-formats.
-This may not always be necessary if the final renderer (e.g.
-the browser, when generating HTML) supports the Unicode Bidirectional
-Algorithm.
-.PP
-When using LaTeX for bidirectional documents, only the \f[C]xelatex\f[]
-engine is fully supported (use \f[C]\-\-pdf\-engine=xelatex\f[]).
-.RE
-.SS Variables for slides
-.PP
-Variables are available for producing slide shows with pandoc, including
-all reveal.js configuration options.
-.TP
-.B \f[C]titlegraphic\f[]
-title graphic for Beamer documents
-.RS
-.RE
-.TP
-.B \f[C]logo\f[]
-logo for Beamer documents
-.RS
-.RE
-.TP
-.B \f[C]slidy\-url\f[]
-base URL for Slidy documents (defaults to
-\f[C]https://www.w3.org/Talks/Tools/Slidy2\f[])
-.RS
-.RE
-.TP
-.B \f[C]slideous\-url\f[]
-base URL for Slideous documents (defaults to \f[C]slideous\f[])
-.RS
-.RE
-.TP
-.B \f[C]s5\-url\f[]
-base URL for S5 documents (defaults to \f[C]s5/default\f[])
-.RS
-.RE
-.TP
-.B \f[C]revealjs\-url\f[]
-base URL for reveal.js documents (defaults to \f[C]reveal.js\f[])
-.RS
-.RE
-.TP
-.B \f[C]theme\f[], \f[C]colortheme\f[], \f[C]fonttheme\f[], \f[C]innertheme\f[], \f[C]outertheme\f[]
-themes for LaTeX \f[C]beamer\f[] documents
-.RS
-.RE
-.TP
-.B \f[C]themeoptions\f[]
-options for LaTeX beamer themes (a list).
-.RS
-.RE
-.TP
-.B \f[C]navigation\f[]
-controls navigation symbols in \f[C]beamer\f[] documents (default is
-\f[C]empty\f[] for no navigation symbols; other valid values are
-\f[C]frame\f[], \f[C]vertical\f[], and \f[C]horizontal\f[]).
-.RS
-.RE
-.TP
-.B \f[C]section\-titles\f[]
-enables on "title pages" for new sections in \f[C]beamer\f[] documents
-(default = true).
-.RS
-.RE
-.TP
-.B \f[C]beamerarticle\f[]
-when true, the \f[C]beamerarticle\f[] package is loaded (for producing
-an article from beamer slides).
-.RS
-.RE
-.TP
-.B \f[C]aspectratio\f[]
-aspect ratio of slides (for beamer only, \f[C]1610\f[] for 16:10,
-\f[C]169\f[] for 16:9, \f[C]149\f[] for 14:9, \f[C]141\f[] for 1.41:1,
-\f[C]54\f[] for 5:4, \f[C]43\f[] for 4:3 which is the default, and
-\f[C]32\f[] for 3:2).
-.RS
-.RE
-.SS Variables for LaTeX
-.PP
-LaTeX variables are used when creating a PDF.
-.TP
-.B \f[C]papersize\f[]
-paper size, e.g.
-\f[C]letter\f[], \f[C]a4\f[]
-.RS
-.RE
-.TP
-.B \f[C]fontsize\f[]
-font size for body text (e.g.
-\f[C]10pt\f[], \f[C]12pt\f[])
-.RS
-.RE
-.TP
-.B \f[C]documentclass\f[]
-document class, e.g.
-\f[C]article\f[], \f[C]report\f[], \f[C]book\f[], \f[C]memoir\f[]
-.RS
-.RE
-.TP
-.B \f[C]classoption\f[]
-option for document class, e.g.
-\f[C]oneside\f[]; may be repeated for multiple options
-.RS
-.RE
-.TP
-.B \f[C]geometry\f[]
-option for \f[C]geometry\f[] package, e.g.
-\f[C]margin=1in\f[]; may be repeated for multiple options
-.RS
-.RE
-.TP
-.B \f[C]margin\-left\f[], \f[C]margin\-right\f[], \f[C]margin\-top\f[], \f[C]margin\-bottom\f[]
-sets margins, if \f[C]geometry\f[] is not used (otherwise
-\f[C]geometry\f[] overrides these)
-.RS
-.RE
-.TP
-.B \f[C]linestretch\f[]
-adjusts line spacing using the \f[C]setspace\f[] package, e.g.
-\f[C]1.25\f[], \f[C]1.5\f[]
-.RS
-.RE
-.TP
-.B \f[C]fontfamily\f[]
-font package for use with \f[C]pdflatex\f[]: TeX Live includes many
-options, documented in the LaTeX Font Catalogue.
-The default is Latin Modern.
-.RS
-.RE
-.TP
-.B \f[C]fontfamilyoptions\f[]
-options for package used as \f[C]fontfamily\f[]: e.g.
-\f[C]osf,sc\f[] with \f[C]fontfamily\f[] set to \f[C]mathpazo\f[]
-provides Palatino with old\-style figures and true small caps; may be
-repeated for multiple options
-.RS
-.RE
-.TP
-.B \f[C]mainfont\f[], \f[C]sansfont\f[], \f[C]monofont\f[], \f[C]mathfont\f[], \f[C]CJKmainfont\f[]
-font families for use with \f[C]xelatex\f[] or \f[C]lualatex\f[]: take
-the name of any system font, using the \f[C]fontspec\f[] package.
-Note that if \f[C]CJKmainfont\f[] is used, the \f[C]xecjk\f[] package
-must be available.
-.RS
-.RE
-.TP
-.B \f[C]mainfontoptions\f[], \f[C]sansfontoptions\f[], \f[C]monofontoptions\f[], \f[C]mathfontoptions\f[], \f[C]CJKoptions\f[]
-options to use with \f[C]mainfont\f[], \f[C]sansfont\f[],
-\f[C]monofont\f[], \f[C]mathfont\f[], \f[C]CJKmainfont\f[] in
-\f[C]xelatex\f[] and \f[C]lualatex\f[].
-Allow for any choices available through \f[C]fontspec\f[], such as the
-OpenType features \f[C]Numbers=OldStyle,Numbers=Proportional\f[].
-May be repeated for multiple options.
-.RS
-.RE
-.TP
-.B \f[C]fontenc\f[]
-allows font encoding to be specified through \f[C]fontenc\f[] package
-(with \f[C]pdflatex\f[]); default is \f[C]T1\f[] (see guide to LaTeX
-font encodings)
-.RS
-.RE
-.TP
-.B \f[C]microtypeoptions\f[]
-options to pass to the microtype package
-.RS
-.RE
-.TP
-.B \f[C]colorlinks\f[]
-add color to link text; automatically enabled if any of
-\f[C]linkcolor\f[], \f[C]citecolor\f[], \f[C]urlcolor\f[], or
-\f[C]toccolor\f[] are set
-.RS
-.RE
-.TP
-.B \f[C]linkcolor\f[], \f[C]citecolor\f[], \f[C]urlcolor\f[], \f[C]toccolor\f[]
-color for internal links, citation links, external links, and links in
-table of contents: uses options allowed by \f[C]xcolor\f[], including
-the \f[C]dvipsnames\f[], \f[C]svgnames\f[], and \f[C]x11names\f[] lists
-.RS
-.RE
-.TP
-.B \f[C]links\-as\-notes\f[]
-causes links to be printed as footnotes
-.RS
-.RE
-.TP
-.B \f[C]indent\f[]
-uses document class settings for indentation (the default LaTeX template
-otherwise removes indentation and adds space between paragraphs)
-.RS
-.RE
-.TP
-.B \f[C]subparagraph\f[]
-disables default behavior of LaTeX template that redefines
-(sub)paragraphs as sections, changing the appearance of nested headings
-in some classes
-.RS
-.RE
-.TP
-.B \f[C]thanks\f[]
-specifies contents of acknowledgments footnote after document title.
-.RS
-.RE
-.TP
-.B \f[C]toc\f[]
-include table of contents (can also be set using
-\f[C]\-\-toc/\-\-table\-of\-contents\f[])
-.RS
-.RE
-.TP
-.B \f[C]toc\-depth\f[]
-level of section to include in table of contents
-.RS
-.RE
-.TP
-.B \f[C]secnumdepth\f[]
-numbering depth for sections, if sections are numbered
-.RS
-.RE
-.TP
-.B \f[C]lof\f[], \f[C]lot\f[]
-include list of figures, list of tables
-.RS
-.RE
-.TP
-.B \f[C]bibliography\f[]
-bibliography to use for resolving references
-.RS
-.RE
-.TP
-.B \f[C]biblio\-style\f[]
-bibliography style, when used with \f[C]\-\-natbib\f[] and
-\f[C]\-\-biblatex\f[].
-.RS
-.RE
-.TP
-.B \f[C]biblio\-title\f[]
-bibliography title, when used with \f[C]\-\-natbib\f[] and
-\f[C]\-\-biblatex\f[].
-.RS
-.RE
-.TP
-.B \f[C]biblatexoptions\f[]
-list of options for biblatex.
-.RS
-.RE
-.TP
-.B \f[C]natbiboptions\f[]
-list of options for natbib.
-.RS
-.RE
-.TP
-.B \f[C]pagestyle\f[]
-An option for LaTeX\[aq]s \f[C]\\pagestyle{}\f[].
-The default article class supports \[aq]plain\[aq] (default),
-\[aq]empty\[aq], and \[aq]headings\[aq]; headings puts section titles in
-the header.
-.RS
-.RE
-.SS Variables for ConTeXt
-.TP
-.B \f[C]papersize\f[]
-paper size, e.g.
-\f[C]letter\f[], \f[C]A4\f[], \f[C]landscape\f[] (see ConTeXt Paper
-Setup); may be repeated for multiple options
-.RS
-.RE
-.TP
-.B \f[C]layout\f[]
-options for page margins and text arrangement (see ConTeXt Layout); may
-be repeated for multiple options
-.RS
-.RE
-.TP
-.B \f[C]margin\-left\f[], \f[C]margin\-right\f[], \f[C]margin\-top\f[], \f[C]margin\-bottom\f[]
-sets margins, if \f[C]layout\f[] is not used (otherwise \f[C]layout\f[]
-overrides these)
-.RS
-.RE
-.TP
-.B \f[C]fontsize\f[]
-font size for body text (e.g.
-\f[C]10pt\f[], \f[C]12pt\f[])
-.RS
-.RE
-.TP
-.B \f[C]mainfont\f[], \f[C]sansfont\f[], \f[C]monofont\f[], \f[C]mathfont\f[]
-font families: take the name of any system font (see ConTeXt Font
-Switching)
-.RS
-.RE
-.TP
-.B \f[C]linkcolor\f[], \f[C]contrastcolor\f[]
-color for links outside and inside a page, e.g.
-\f[C]red\f[], \f[C]blue\f[] (see ConTeXt Color)
-.RS
-.RE
-.TP
-.B \f[C]linkstyle\f[]
-typeface style for links, e.g.
-\f[C]normal\f[], \f[C]bold\f[], \f[C]slanted\f[], \f[C]boldslanted\f[],
-\f[C]type\f[], \f[C]cap\f[], \f[C]small\f[]
-.RS
-.RE
-.TP
-.B \f[C]indenting\f[]
-controls indentation of paragraphs, e.g.
-\f[C]yes,small,next\f[] (see ConTeXt Indentation); may be repeated for
-multiple options
-.RS
-.RE
-.TP
-.B \f[C]whitespace\f[]
-spacing between paragraphs, e.g.
-\f[C]none\f[], \f[C]small\f[] (using \f[C]setupwhitespace\f[])
-.RS
-.RE
-.TP
-.B \f[C]interlinespace\f[]
-adjusts line spacing, e.g.
-\f[C]4ex\f[] (using \f[C]setupinterlinespace\f[]); may be repeated for
-multiple options
-.RS
-.RE
-.TP
-.B \f[C]headertext\f[], \f[C]footertext\f[]
-text to be placed in running header or footer (see ConTeXt Headers and
-Footers); may be repeated up to four times for different placement
-.RS
-.RE
-.TP
-.B \f[C]pagenumbering\f[]
-page number style and location (using \f[C]setuppagenumbering\f[]); may
-be repeated for multiple options
-.RS
-.RE
-.TP
-.B \f[C]toc\f[]
-include table of contents (can also be set using
-\f[C]\-\-toc/\-\-table\-of\-contents\f[])
-.RS
-.RE
-.TP
-.B \f[C]lof\f[], \f[C]lot\f[]
-include list of figures, list of tables
-.RS
-.RE
-.SS Variables for man pages
-.TP
-.B \f[C]section\f[]
-section number in man pages
-.RS
-.RE
-.TP
-.B \f[C]header\f[]
-header in man pages
-.RS
-.RE
-.TP
-.B \f[C]footer\f[]
-footer in man pages
-.RS
-.RE
-.TP
-.B \f[C]adjusting\f[]
-adjusts text to left (\f[C]l\f[]), right (\f[C]r\f[]), center
-(\f[C]c\f[]), or both (\f[C]b\f[]) margins
-.RS
-.RE
-.TP
-.B \f[C]hyphenate\f[]
-if \f[C]true\f[] (the default), hyphenation will be used
-.RS
-.RE
-.SS Variables for ms
-.TP
-.B \f[C]pointsize\f[]
-point size (e.g.
-\f[C]10p\f[])
-.RS
-.RE
-.TP
-.B \f[C]lineheight\f[]
-line height (e.g.
-\f[C]12p\f[])
-.RS
-.RE
-.TP
-.B \f[C]fontfamily\f[]
-font family (e.g.
-\f[C]T\f[] or \f[C]P\f[])
-.RS
-.RE
-.TP
-.B \f[C]indent\f[]
-paragraph indent (e.g.
-\f[C]2m\f[])
-.RS
-.RE
-.SS Using variables in templates
-.PP
-Variable names are sequences of alphanumerics, \f[C]\-\f[], and
-\f[C]_\f[], starting with a letter.
-A variable name surrounded by \f[C]$\f[] signs will be replaced by its
-value.
-For example, the string \f[C]$title$\f[] in
-.IP
-.nf
-\f[C]
-<title>$title$</title>
-\f[]
-.fi
-.PP
-will be replaced by the document title.
-.PP
-To write a literal \f[C]$\f[] in a template, use \f[C]$$\f[].
-.PP
-Templates may contain conditionals.
-The syntax is as follows:
-.IP
-.nf
-\f[C]
-$if(variable)$
-X
-$else$
-Y
-$endif$
-\f[]
-.fi
-.PP
-This will include \f[C]X\f[] in the template if \f[C]variable\f[] has a
-non\-null value; otherwise it will include \f[C]Y\f[].
-\f[C]X\f[] and \f[C]Y\f[] are placeholders for any valid template text,
-and may include interpolated variables or other conditionals.
-The \f[C]$else$\f[] section may be omitted.
-.PP
-When variables can have multiple values (for example, \f[C]author\f[] in
-a multi\-author document), you can use the \f[C]$for$\f[] keyword:
-.IP
-.nf
-\f[C]
-$for(author)$
-<meta\ name="author"\ content="$author$"\ />
-$endfor$
-\f[]
-.fi
-.PP
-You can optionally specify a separator to be used between consecutive
-items:
-.IP
-.nf
-\f[C]
-$for(author)$$author$$sep$,\ $endfor$
-\f[]
-.fi
-.PP
-A dot can be used to select a field of a variable that takes an object
-as its value.
-So, for example:
-.IP
-.nf
-\f[C]
-$author.name$\ ($author.affiliation$)
-\f[]
-.fi
-.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
-modifying your custom templates accordingly.
-An easy way to do this is to fork the pandoc\-templates repository and
-merge in changes after each pandoc release.
-.PP
-Templates may contain comments: anything on a line after \f[C]$\-\-\f[]
-will be treated as a comment and ignored.
-.SH EXTENSIONS
-.PP
-The behavior of some of the readers and writers can be adjusted by
-enabling or disabling various extensions.
-.PP
-An extension can be enabled by adding \f[C]+EXTENSION\f[] to the format
-name and disabled by adding \f[C]\-EXTENSION\f[].
-For example, \f[C]\-\-from\ markdown_strict+footnotes\f[] is strict
-Markdown with footnotes enabled, while
-\f[C]\-\-from\ markdown\-footnotes\-pipe_tables\f[] is pandoc\[aq]s
-Markdown without footnotes or pipe tables.
-.PP
-The markdown reader and writer make by far the most use of extensions.
-Extensions only used by them are therefore covered in the section
-Pandoc\[aq]s Markdown below (See Markdown variants for
-\f[C]commonmark\f[] and \f[C]gfm\f[].) In the following, extensions that
-also work for other formats are covered.
-.SS Typography
-.SS Extension: \f[C]smart\f[]
-.PP
-Interpret straight quotes as curly quotes, \f[C]\-\-\-\f[] as
-em\-dashes, \f[C]\-\-\f[] as en\-dashes, and \f[C]\&...\f[] as ellipses.
-Nonbreaking spaces are inserted after certain abbreviations, such as
-"Mr."
-.PP
-This extension can be enabled/disabled for the following formats:
-.TP
-.B input formats
-\f[C]markdown\f[], \f[C]commonmark\f[], \f[C]latex\f[],
-\f[C]mediawiki\f[], \f[C]org\f[], \f[C]rst\f[], \f[C]twiki\f[]
-.RS
-.RE
-.TP
-.B output formats
-\f[C]markdown\f[], \f[C]latex\f[], \f[C]context\f[], \f[C]rst\f[]
-.RS
-.RE
-.TP
-.B enabled by default in
-\f[C]markdown\f[], \f[C]latex\f[], \f[C]context\f[] (both input and
-output)
-.RS
-.RE
-.PP
-Note: If you are \f[I]writing\f[] Markdown, then the \f[C]smart\f[]
-extension has the reverse effect: what would have been curly quotes
-comes out straight.
-.PP
-In LaTeX, \f[C]smart\f[] means to use the standard TeX ligatures for
-quotation marks (\f[C]``\f[] and \f[C]\[aq]\[aq]\f[] for double quotes,
-\f[C]`\f[] and \f[C]\[aq]\f[] for single quotes) and dashes
-(\f[C]\-\-\f[] for en\-dash and \f[C]\-\-\-\f[] for em\-dash).
-If \f[C]smart\f[] is disabled, then in reading LaTeX pandoc will parse
-these characters literally.
-In writing LaTeX, enabling \f[C]smart\f[] tells pandoc to use the
-ligatures when possible; if \f[C]smart\f[] is disabled pandoc will use
-unicode quotation mark and dash characters.
-.SS Headers and sections
-.SS Extension: \f[C]auto_identifiers\f[]
-.PP
-A header without an explicitly specified identifier will be
-automatically assigned a unique identifier based on the header text.
-.PP
-This extension can be enabled/disabled for the following formats:
-.TP
-.B input formats
-\f[C]markdown\f[], \f[C]latex\f[], \f[C]rst\f[], \f[C]mediawiki\f[],
-\f[C]textile\f[]
-.RS
-.RE
-.TP
-.B output formats
-\f[C]markdown\f[], \f[C]muse\f[]
-.RS
-.RE
-.TP
-.B enabled by default in
-\f[C]markdown\f[], \f[C]muse\f[]
-.RS
-.RE
-.PP
-The algorithm used to derive the identifier from the header text is:
-.IP \[bu] 2
-Remove all formatting, links, etc.
-.IP \[bu] 2
-Remove all footnotes.
-.IP \[bu] 2
-Remove all punctuation, except underscores, hyphens, and periods.
-.IP \[bu] 2
-Replace all spaces and newlines with hyphens.
-.IP \[bu] 2
-Convert all alphabetic characters to lowercase.
-.IP \[bu] 2
-Remove everything up to the first letter (identifiers may not begin with
-a number or punctuation mark).
-.IP \[bu] 2
-If nothing is left after this, use the identifier \f[C]section\f[].
-.PP
-Thus, for example,
-.PP
-.TS
-tab(@);
-l l.
-T{
-Header
-T}@T{
-Identifier
-T}
-_
-T{
-\f[C]Header\ identifiers\ in\ HTML\f[]
-T}@T{
-\f[C]header\-identifiers\-in\-html\f[]
-T}
-T{
-\f[C]*Dogs*?\-\-in\ *my*\ house?\f[]
-T}@T{
-\f[C]dogs\-\-in\-my\-house\f[]
-T}
-T{
-\f[C][HTML],\ [S5],\ or\ [RTF]?\f[]
-T}@T{
-\f[C]html\-s5\-or\-rtf\f[]
-T}
-T{
-\f[C]3.\ Applications\f[]
-T}@T{
-\f[C]applications\f[]
-T}
-T{
-\f[C]33\f[]
-T}@T{
-\f[C]section\f[]
-T}
-.TE
-.PP
-These rules should, in most cases, allow one to determine the identifier
-from the header text.
-The exception is when several headers have the same text; in this case,
-the first will get an identifier as described above; the second will get
-the same identifier with \f[C]\-1\f[] appended; the third with
-\f[C]\-2\f[]; and so on.
-.PP
-These identifiers are used to provide link targets in the table of
-contents generated by the \f[C]\-\-toc|\-\-table\-of\-contents\f[]
-option.
-They also make it easy to provide links from one section of a document
-to another.
-A link to this section, for example, might look like this:
-.IP
-.nf
-\f[C]
-See\ the\ section\ on
-[header\ identifiers](#header\-identifiers\-in\-html\-latex\-and\-context).
-\f[]
-.fi
-.PP
-Note, however, that this method of providing links to sections works
-only in HTML, LaTeX, and ConTeXt formats.
-.PP
-If the \f[C]\-\-section\-divs\f[] option is specified, then each section
-will be wrapped in a \f[C]section\f[] (or a \f[C]div\f[], if
-\f[C]html4\f[] was specified), and the identifier will be attached to
-the enclosing \f[C]<section>\f[] (or \f[C]<div>\f[]) tag rather than the
-header itself.
-This allows entire sections to be manipulated using JavaScript or
-treated differently in CSS.
-.SS Extension: \f[C]ascii_identifiers\f[]
-.PP
-Causes the identifiers produced by \f[C]auto_identifiers\f[] to be pure
-ASCII.
-Accents are stripped off of accented Latin letters, and non\-Latin
-letters are omitted.
-.SS Math Input
-.PP
-The extensions \f[C]tex_math_dollars\f[],
-\f[C]tex_math_single_backslash\f[], and
-\f[C]tex_math_double_backslash\f[] are described in the section about
-Pandoc\[aq]s Markdown.
-.PP
-However, they can also be used with HTML input.
-This is handy for reading web pages formatted using MathJax, for
-example.
-.SS Raw HTML/TeX
-.PP
-The following extensions (especially how they affect Markdown
-input/output) are also described in more detail in their respective
-sections of Pandoc\[aq]s Markdown.
-.SS Extension: \f[C]raw_html\f[]
-.PP
-When converting from HTML, parse elements to raw HTML which are not
-representable in pandoc\[aq]s AST.
-By default, this is disabled for HTML input.
-.SS Extension: \f[C]raw_tex\f[]
-.PP
-Allows raw LaTeX, TeX, and ConTeXt to be included in a document.
-.PP
-This extension can be enabled/disabled for the following formats (in
-addition to \f[C]markdown\f[]):
-.TP
-.B input formats
-\f[C]latex\f[], \f[C]org\f[], \f[C]textile\f[]
-.RS
-.RE
-.TP
-.B output formats
-\f[C]textile\f[]
-.RS
-.RE
-.SS Extension: \f[C]native_divs\f[]
-.PP
-This extension is enabled by default for HTML input.
-This means that \f[C]div\f[]s are parsed to pandoc native elements.
-(Alternatively, you can parse them to raw HTML using
-\f[C]\-f\ html\-native_divs+raw_html\f[].)
-.PP
-When converting HTML to Markdown, for example, you may want to drop all
-\f[C]div\f[]s and \f[C]span\f[]s:
-.IP
-.nf
-\f[C]
-pandoc\ \-f\ html\-native_divs\-native_spans\ \-t\ markdown
-\f[]
-.fi
-.SS Extension: \f[C]native_spans\f[]
-.PP
-Analogous to \f[C]native_divs\f[] above.
-.SS Literate Haskell support
-.SS Extension: \f[C]literate_haskell\f[]
-.PP
-Treat the document as literate Haskell source.
-.PP
-This extension can be enabled/disabled for the following formats:
-.TP
-.B input formats
-\f[C]markdown\f[], \f[C]rst\f[], \f[C]latex\f[]
-.RS
-.RE
-.TP
-.B output formats
-\f[C]markdown\f[], \f[C]rst\f[], \f[C]latex\f[], \f[C]html\f[]
-.RS
-.RE
-.PP
-If you append \f[C]+lhs\f[] (or \f[C]+literate_haskell\f[]) to one of
-the formats above, pandoc will treat the document as literate Haskell
-source.
-This means that
-.IP \[bu] 2
-In Markdown input, "bird track" sections will be parsed as Haskell code
-rather than block quotations.
-Text between \f[C]\\begin{code}\f[] and \f[C]\\end{code}\f[] will also
-be treated as Haskell code.
-For ATX\-style headers the character \[aq]=\[aq] will be used instead of
-\[aq]#\[aq].
-.IP \[bu] 2
-In Markdown output, code blocks with classes \f[C]haskell\f[] and
-\f[C]literate\f[] will be rendered using bird tracks, and block
-quotations will be indented one space, so they will not be treated as
-Haskell code.
-In addition, headers will be rendered setext\-style (with underlines)
-rather than ATX\-style (with \[aq]#\[aq] characters).
-(This is because ghc treats \[aq]#\[aq] characters in column 1 as
-introducing line numbers.)
-.IP \[bu] 2
-In restructured text input, "bird track" sections will be parsed as
-Haskell code.
-.IP \[bu] 2
-In restructured text output, code blocks with class \f[C]haskell\f[]
-will be rendered using bird tracks.
-.IP \[bu] 2
-In LaTeX input, text in \f[C]code\f[] environments will be parsed as
-Haskell code.
-.IP \[bu] 2
-In LaTeX output, code blocks with class \f[C]haskell\f[] will be
-rendered inside \f[C]code\f[] environments.
-.IP \[bu] 2
-In HTML output, code blocks with class \f[C]haskell\f[] will be rendered
-with class \f[C]literatehaskell\f[] and bird tracks.
-.PP
-Examples:
-.IP
-.nf
-\f[C]
-pandoc\ \-f\ markdown+lhs\ \-t\ html
-\f[]
-.fi
-.PP
-reads literate Haskell source formatted with Markdown conventions and
-writes ordinary HTML (without bird tracks).
-.IP
-.nf
-\f[C]
-pandoc\ \-f\ markdown+lhs\ \-t\ html+lhs
-\f[]
-.fi
-.PP
-writes HTML with the Haskell code in bird tracks, so it can be copied
-and pasted as literate Haskell source.
-.PP
-Note that GHC expects the bird tracks in the first column, so indentend
-literate code blocks (e.g.
-inside an itemized environment) will not be picked up by the Haskell
-compiler.
-.SS Other extensions
-.SS Extension: \f[C]empty_paragraphs\f[]
-.PP
-Allows empty paragraphs.
-By default empty paragraphs are omitted.
-.PP
-This extension can be enabled/disabled for the following formats:
-.TP
-.B input formats
-\f[C]docx\f[], \f[C]html\f[]
-.RS
-.RE
-.TP
-.B output formats
-\f[C]markdown\f[], \f[C]docx\f[], \f[C]odt\f[], \f[C]opendocument\f[],
-\f[C]html\f[]
-.RS
-.RE
-.SS Extension: \f[C]amuse\f[]
-.PP
-In the \f[C]muse\f[] input format, this enables Text::Amuse extensions
-to Emacs Muse markup.
-.SS Extension: \f[C]citations\f[]
-.PP
-Some aspects of Pandoc\[aq]s Markdown citation syntax are also accepted
-in \f[C]org\f[] input.
-.SH PANDOC\[aq]S MARKDOWN
-.PP
-Pandoc understands an extended and slightly revised version of John
-Gruber\[aq]s Markdown syntax.
-This document explains the syntax, noting differences from standard
-Markdown.
-Except where noted, these differences can be suppressed by using the
-\f[C]markdown_strict\f[] format instead of \f[C]markdown\f[].
-Extensions can be enabled or disabled to specify the behavior more
-granularly.
-They are described in the following.
-See also Extensions above, for extensions that work also on other
-formats.
-.SS Philosophy
-.PP
-Markdown is designed to be easy to write, and, even more importantly,
-easy to read:
-.RS
-.PP
-A Markdown\-formatted document should be publishable as\-is, as plain
-text, without looking like it\[aq]s been marked up with tags or
-formatting instructions.
-\-\- John Gruber
-.RE
-.PP
-This principle has guided pandoc\[aq]s decisions in finding syntax for
-tables, footnotes, and other extensions.
-.PP
-There is, however, one respect in which pandoc\[aq]s aims are different
-from the original aims of Markdown.
-Whereas Markdown was originally designed with HTML generation in mind,
-pandoc is designed for multiple output formats.
-Thus, while pandoc allows the embedding of raw HTML, it discourages it,
-and provides other, non\-HTMLish ways of representing important document
-elements like definition lists, tables, mathematics, and footnotes.
-.SS Paragraphs
-.PP
-A paragraph is one or more lines of text followed by one or more blank
-lines.
-Newlines are treated as spaces, so you can reflow your paragraphs as you
-like.
-If you need a hard line break, put two or more spaces at the end of a
-line.
-.SS Extension: \f[C]escaped_line_breaks\f[]
-.PP
-A backslash followed by a newline is also a hard line break.
-Note: in multiline and grid table cells, this is the only way to create
-a hard line break, since trailing spaces in the cells are ignored.
-.SS Headers
-.PP
-There are two kinds of headers: Setext and ATX.
-.SS Setext\-style headers
-.PP
-A setext\-style header is a line of text "underlined" with a row of
-\f[C]=\f[] signs (for a level one header) or \f[C]\-\f[] signs (for a
-level two header):
-.IP
-.nf
-\f[C]
-A\ level\-one\ header
-==================
-
-A\ level\-two\ header
-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-
-\f[]
-.fi
-.PP
-The header text can contain inline formatting, such as emphasis (see
-Inline formatting, below).
-.SS ATX\-style headers
-.PP
-An ATX\-style header consists of one to six \f[C]#\f[] signs and a line
-of text, optionally followed by any number of \f[C]#\f[] signs.
-The number of \f[C]#\f[] signs at the beginning of the line is the
-header level:
-.IP
-.nf
-\f[C]
-##\ A\ level\-two\ header
-
-###\ A\ level\-three\ header\ ###
-\f[]
-.fi
-.PP
-As with setext\-style headers, the header text can contain formatting:
-.IP
-.nf
-\f[C]
-#\ A\ level\-one\ header\ with\ a\ [link](/url)\ and\ *emphasis*
-\f[]
-.fi
-.SS Extension: \f[C]blank_before_header\f[]
-.PP
-Standard Markdown syntax does not require a blank line before a header.
-Pandoc does require this (except, of course, at the beginning of the
-document).
-The reason for the requirement is that it is all too easy for a
-\f[C]#\f[] to end up at the beginning of a line by accident (perhaps
-through line wrapping).
-Consider, for example:
-.IP
-.nf
-\f[C]
-I\ like\ several\ of\ their\ flavors\ of\ ice\ cream:
-#22,\ for\ example,\ and\ #5.
-\f[]
-.fi
-.SS Extension: \f[C]space_in_atx_header\f[]
-.PP
-Many Markdown implementations do not require a space between the opening
-\f[C]#\f[]s of an ATX header and the header text, so that
-\f[C]#5\ bolt\f[] and \f[C]#hashtag\f[] count as headers.
-With this extension, pandoc does require the space.
-.SS Header identifiers
-.PP
-See also the \f[C]auto_identifiers\f[] extension above.
-.SS Extension: \f[C]header_attributes\f[]
-.PP
-Headers can be assigned attributes using this syntax at the end of the
-line containing the header text:
-.IP
-.nf
-\f[C]
-{#identifier\ .class\ .class\ key=value\ key=value}
-\f[]
-.fi
-.PP
-Thus, for example, the following headers will all be assigned the
-identifier \f[C]foo\f[]:
-.IP
-.nf
-\f[C]
-#\ My\ header\ {#foo}
-
-##\ My\ header\ ##\ \ \ \ {#foo}
-
-My\ other\ header\ \ \ {#foo}
-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-
-\f[]
-.fi
-.PP
-(This syntax is compatible with PHP Markdown Extra.)
-.PP
-Note that although this syntax allows assignment of classes and
-key/value attributes, writers generally don\[aq]t use all of this
-information.
-Identifiers, classes, and key/value attributes are used in HTML and
-HTML\-based formats such as EPUB and slidy.
-Identifiers are used for labels and link anchors in the LaTeX, ConTeXt,
-Textile, and AsciiDoc writers.
-.PP
-Headers with the class \f[C]unnumbered\f[] will not be numbered, even if
-\f[C]\-\-number\-sections\f[] is specified.
-A single hyphen (\f[C]\-\f[]) in an attribute context is equivalent to
-\f[C]\&.unnumbered\f[], and preferable in non\-English documents.
-So,
-.IP
-.nf
-\f[C]
-#\ My\ header\ {\-}
-\f[]
-.fi
-.PP
-is just the same as
-.IP
-.nf
-\f[C]
-#\ My\ header\ {.unnumbered}
-\f[]
-.fi
-.SS Extension: \f[C]implicit_header_references\f[]
-.PP
-Pandoc behaves as if reference links have been defined for each header.
-So, to link to a header
-.IP
-.nf
-\f[C]
-#\ Header\ identifiers\ in\ HTML
-\f[]
-.fi
-.PP
-you can simply write
-.IP
-.nf
-\f[C]
-[Header\ identifiers\ in\ HTML]
-\f[]
-.fi
-.PP
-or
-.IP
-.nf
-\f[C]
-[Header\ identifiers\ in\ HTML][]
-\f[]
-.fi
-.PP
-or
-.IP
-.nf
-\f[C]
-[the\ section\ on\ header\ identifiers][header\ identifiers\ in
-HTML]
-\f[]
-.fi
-.PP
-instead of giving the identifier explicitly:
-.IP
-.nf
-\f[C]
-[Header\ identifiers\ in\ HTML](#header\-identifiers\-in\-html)
-\f[]
-.fi
-.PP
-If there are multiple headers with identical text, the corresponding
-reference will link to the first one only, and you will need to use
-explicit links to link to the others, as described above.
-.PP
-Like regular reference links, these references are case\-insensitive.
-.PP
-Explicit link reference definitions always take priority over implicit
-header references.
-So, in the following example, the link will point to \f[C]bar\f[], not
-to \f[C]#foo\f[]:
-.IP
-.nf
-\f[C]
-#\ Foo
-
-[foo]:\ bar
-
-See\ [foo]
-\f[]
-.fi
-.SS Block quotations
-.PP
-Markdown uses email conventions for quoting blocks of text.
-A block quotation is one or more paragraphs or other block elements
-(such as lists or headers), with each line preceded by a \f[C]>\f[]
-character and an optional space.
-(The \f[C]>\f[] need not start at the left margin, but it should not be
-indented more than three spaces.)
-.IP
-.nf
-\f[C]
->\ This\ is\ a\ block\ quote.\ This
->\ paragraph\ has\ two\ lines.
->
->\ 1.\ This\ is\ a\ list\ inside\ a\ block\ quote.
->\ 2.\ Second\ item.
-\f[]
-.fi
-.PP
-A "lazy" form, which requires the \f[C]>\f[] character only on the first
-line of each block, is also allowed:
-.IP
-.nf
-\f[C]
->\ This\ is\ a\ block\ quote.\ This
-paragraph\ has\ two\ lines.
-
->\ 1.\ This\ is\ a\ list\ inside\ a\ block\ quote.
-2.\ Second\ item.
-\f[]
-.fi
-.PP
-Among the block elements that can be contained in a block quote are
-other block quotes.
-That is, block quotes can be nested:
-.IP
-.nf
-\f[C]
->\ This\ is\ a\ block\ quote.
->
->\ >\ A\ block\ quote\ within\ a\ block\ quote.
-\f[]
-.fi
-.PP
-If the \f[C]>\f[] character is followed by an optional space, that space
-will be considered part of the block quote marker and not part of the
-indentation of the contents.
-Thus, to put an indented code block in a block quote, you need five
-spaces after the \f[C]>\f[]:
-.IP
-.nf
-\f[C]
->\ \ \ \ \ code
-\f[]
-.fi
-.SS Extension: \f[C]blank_before_blockquote\f[]
-.PP
-Standard Markdown syntax does not require a blank line before a block
-quote.
-Pandoc does require this (except, of course, at the beginning of the
-document).
-The reason for the requirement is that it is all too easy for a
-\f[C]>\f[] to end up at the beginning of a line by accident (perhaps
-through line wrapping).
-So, unless the \f[C]markdown_strict\f[] format is used, the following
-does not produce a nested block quote in pandoc:
-.IP
-.nf
-\f[C]
->\ This\ is\ a\ block\ quote.
->>\ Nested.
-\f[]
-.fi
-.SS Verbatim (code) blocks
-.SS Indented code blocks
-.PP
-A block of text indented four spaces (or one tab) is treated as verbatim
-text: that is, special characters do not trigger special formatting, and
-all spaces and line breaks are preserved.
-For example,
-.IP
-.nf
-\f[C]
-\ \ \ \ if\ (a\ >\ 3)\ {
-\ \ \ \ \ \ moveShip(5\ *\ gravity,\ DOWN);
-\ \ \ \ }
-\f[]
-.fi
-.PP
-The initial (four space or one tab) indentation is not considered part
-of the verbatim text, and is removed in the output.
-.PP
-Note: blank lines in the verbatim text need not begin with four spaces.
-.SS Fenced code blocks
-.SS Extension: \f[C]fenced_code_blocks\f[]
-.PP
-In addition to standard indented code blocks, pandoc supports
-\f[I]fenced\f[] code blocks.
-These begin with a row of three or more tildes (\f[C]~\f[]) and end with
-a row of tildes that must be at least as long as the starting row.
-Everything between these lines is treated as code.
-No indentation is necessary:
-.IP
-.nf
-\f[C]
-~~~~~~~
-if\ (a\ >\ 3)\ {
-\ \ moveShip(5\ *\ gravity,\ DOWN);
-}
-~~~~~~~
-\f[]
-.fi
-.PP
-Like regular code blocks, fenced code blocks must be separated from
-surrounding text by blank lines.
-.PP
-If the code itself contains a row of tildes or backticks, just use a
-longer row of tildes or backticks at the start and end:
-.IP
-.nf
-\f[C]
-~~~~~~~~~~~~~~~~
-~~~~~~~~~~
-code\ including\ tildes
-~~~~~~~~~~
-~~~~~~~~~~~~~~~~
-\f[]
-.fi
-.SS Extension: \f[C]backtick_code_blocks\f[]
-.PP
-Same as \f[C]fenced_code_blocks\f[], but uses backticks (\f[C]`\f[])
-instead of tildes (\f[C]~\f[]).
-.SS Extension: \f[C]fenced_code_attributes\f[]
-.PP
-Optionally, you may attach attributes to fenced or backtick code block
-using this syntax:
-.IP
-.nf
-\f[C]
-~~~~\ {#mycode\ .haskell\ .numberLines\ startFrom="100"}
-qsort\ []\ \ \ \ \ =\ []
-qsort\ (x:xs)\ =\ qsort\ (filter\ (<\ x)\ xs)\ ++\ [x]\ ++
-\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ qsort\ (filter\ (>=\ x)\ xs)
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-\f[]
-.fi
-.PP
-Here \f[C]mycode\f[] is an identifier, \f[C]haskell\f[] and
-\f[C]numberLines\f[] are classes, and \f[C]startFrom\f[] is an attribute
-with value \f[C]100\f[].
-Some output formats can use this information to do syntax highlighting.
-Currently, the only output formats that uses this information are HTML,
-LaTeX, Docx, and Ms.
-If highlighting is supported for your output format and language, then
-the code block above will appear highlighted, with numbered lines.
-(To see which languages are supported, type
-\f[C]pandoc\ \-\-list\-highlight\-languages\f[].) Otherwise, the code
-block above will appear as follows:
-.IP
-.nf
-\f[C]
-<pre\ id="mycode"\ class="haskell\ numberLines"\ startFrom="100">
-\ \ <code>
-\ \ ...
-\ \ </code>
-</pre>
-\f[]
-.fi
-.PP
-The \f[C]numberLines\f[] (or \f[C]number\-lines\f[]) class will cause
-the lines of the code block to be numbered, starting with \f[C]1\f[] or
-the value of the \f[C]startFrom\f[] attribute.
-The \f[C]lineAnchors\f[] (or \f[C]line\-anchors\f[]) class will cause
-the lines to be clickable anchors in HTML output.
-.PP
-A shortcut form can also be used for specifying the language of the code
-block:
-.IP
-.nf
-\f[C]
-```haskell
-qsort\ []\ =\ []
-```
-\f[]
-.fi
-.PP
-This is equivalent to:
-.IP
-.nf
-\f[C]
-```\ {.haskell}
-qsort\ []\ =\ []
-```
-\f[]
-.fi
-.PP
-If the \f[C]fenced_code_attributes\f[] extension is disabled, but input
-contains class attribute(s) for the code block, the first class
-attribute will be printed after the opening fence as a bare word.
-.PP
-To prevent all highlighting, use the \f[C]\-\-no\-highlight\f[] flag.
-To set the highlighting style, use \f[C]\-\-highlight\-style\f[].
-For more information on highlighting, see Syntax highlighting, below.
-.SS Line blocks
-.SS Extension: \f[C]line_blocks\f[]
-.PP
-A line block is a sequence of lines beginning with a vertical bar
-(\f[C]|\f[]) followed by a space.
-The division into lines will be preserved in the output, as will any
-leading spaces; otherwise, the lines will be formatted as Markdown.
-This is useful for verse and addresses:
-.IP
-.nf
-\f[C]
-|\ The\ limerick\ packs\ laughs\ anatomical
-|\ In\ space\ that\ is\ quite\ economical.
-|\ \ \ \ But\ the\ good\ ones\ I\[aq]ve\ seen
-|\ \ \ \ So\ seldom\ are\ clean
-|\ And\ the\ clean\ ones\ so\ seldom\ are\ comical
-
-|\ 200\ Main\ St.
-|\ Berkeley,\ CA\ 94718
-\f[]
-.fi
-.PP
-The lines can be hard\-wrapped if needed, but the continuation line must
-begin with a space.
-.IP
-.nf
-\f[C]
-|\ The\ Right\ Honorable\ Most\ Venerable\ and\ Righteous\ Samuel\ L.
-\ \ Constable,\ Jr.
-|\ 200\ Main\ St.
-|\ Berkeley,\ CA\ 94718
-\f[]
-.fi
-.PP
-This syntax is borrowed from reStructuredText.
-.SS Lists
-.SS Bullet lists
-.PP
-A bullet list is a list of bulleted list items.
-A bulleted list item begins with a bullet (\f[C]*\f[], \f[C]+\f[], or
-\f[C]\-\f[]).
-Here is a simple example:
-.IP
-.nf
-\f[C]
-*\ one
-*\ two
-*\ three
-\f[]
-.fi
-.PP
-This will produce a "compact" list.
-If you want a "loose" list, in which each item is formatted as a
-paragraph, put spaces between the items:
-.IP
-.nf
-\f[C]
-*\ one
-
-*\ two
-
-*\ three
-\f[]
-.fi
-.PP
-The bullets need not be flush with the left margin; they may be indented
-one, two, or three spaces.
-The bullet must be followed by whitespace.
-.PP
-List items look best if subsequent lines are flush with the first line
-(after the bullet):
-.IP
-.nf
-\f[C]
-*\ here\ is\ my\ first
-\ \ list\ item.
-*\ and\ my\ second.
-\f[]
-.fi
-.PP
-But Markdown also allows a "lazy" format:
-.IP
-.nf
-\f[C]
-*\ here\ is\ my\ first
-list\ item.
-*\ and\ my\ second.
-\f[]
-.fi
-.SS Block content in list items
-.PP
-A list item may contain multiple paragraphs and other block\-level
-content.
-However, subsequent paragraphs must be preceded by a blank line and
-indented to line up with the first non\-space content after the list
-marker.
-.IP
-.nf
-\f[C]
-\ \ *\ First\ paragraph.
-
-\ \ \ \ Continued.
-
-\ \ *\ Second\ paragraph.\ With\ a\ code\ block,\ which\ must\ be\ indented
-\ \ \ \ eight\ spaces:
-
-\ \ \ \ \ \ \ \ {\ code\ }
-\f[]
-.fi
-.PP
-Exception: if the list marker is followed by an indented code block,
-which must begin 5 spaces after the list marker, then subsequent
-paragraphs must begin two columns after the last character of the list
-marker:
-.IP
-.nf
-\f[C]
-*\ \ \ \ \ code
-
-\ \ continuation\ paragraph
-\f[]
-.fi
-.PP
-List items may include other lists.
-In this case the preceding blank line is optional.
-The nested list must be indented to line up with the first non\-space
-character after the list marker of the containing list item.
-.IP
-.nf
-\f[C]
-*\ fruits
-\ \ +\ apples
-\ \ \ \ \-\ macintosh
-\ \ \ \ \-\ red\ delicious
-\ \ +\ pears
-\ \ +\ peaches
-*\ vegetables
-\ \ +\ broccoli
-\ \ +\ chard
-\f[]
-.fi
-.PP
-As noted above, Markdown allows you to write list items "lazily,"
-instead of indenting continuation lines.
-However, if there are multiple paragraphs or other blocks in a list
-item, the first line of each must be indented.
-.IP
-.nf
-\f[C]
-+\ A\ lazy,\ lazy,\ list
-item.
-
-+\ Another\ one;\ this\ looks
-bad\ but\ is\ legal.
-
-\ \ \ \ Second\ paragraph\ of\ second
-list\ item.
-\f[]
-.fi
-.SS Ordered lists
-.PP
-Ordered lists work just like bulleted lists, except that the items begin
-with enumerators rather than bullets.
-.PP
-In standard Markdown, enumerators are decimal numbers followed by a
-period and a space.
-The numbers themselves are ignored, so there is no difference between
-this list:
-.IP
-.nf
-\f[C]
-1.\ \ one
-2.\ \ two
-3.\ \ three
-\f[]
-.fi
-.PP
-and this one:
-.IP
-.nf
-\f[C]
-5.\ \ one
-7.\ \ two
-1.\ \ three
-\f[]
-.fi
-.SS Extension: \f[C]fancy_lists\f[]
-.PP
-Unlike standard Markdown, pandoc allows ordered list items to be marked
-with uppercase and lowercase letters and roman numerals, in addition to
-Arabic numerals.
-List markers may be enclosed in parentheses or followed by a single
-right\-parentheses or period.
-They must be separated from the text that follows by at least one space,
-and, if the list marker is a capital letter with a period, by at least
-two spaces.
-.PP
-The \f[C]fancy_lists\f[] extension also allows \[aq]\f[C]#\f[]\[aq] to
-be used as an ordered list marker in place of a numeral:
-.IP
-.nf
-\f[C]
-#.\ one
-#.\ two
-\f[]
-.fi
-.SS Extension: \f[C]startnum\f[]
-.PP
-Pandoc also pays attention to the type of list marker used, and to the
-starting number, and both of these are preserved where possible in the
-output format.
-Thus, the following yields a list with numbers followed by a single
-parenthesis, starting with 9, and a sublist with lowercase roman
-numerals:
-.IP
-.nf
-\f[C]
-\ 9)\ \ Ninth
-10)\ \ Tenth
-11)\ \ Eleventh
-\ \ \ \ \ \ \ i.\ subone
-\ \ \ \ \ \ ii.\ subtwo
-\ \ \ \ \ iii.\ subthree
-\f[]
-.fi
-.PP
-Pandoc will start a new list each time a different type of list marker
-is used.
-So, the following will create three lists:
-.IP
-.nf
-\f[C]
-(2)\ Two
-(5)\ Three
-1.\ \ Four
-*\ \ \ Five
-\f[]
-.fi
-.PP
-If default list markers are desired, use \f[C]#.\f[]:
-.IP
-.nf
-\f[C]
-#.\ \ one
-#.\ \ two
-#.\ \ three
-\f[]
-.fi
-.SS Definition lists
-.SS Extension: \f[C]definition_lists\f[]
-.PP
-Pandoc supports definition lists, using the syntax of PHP Markdown Extra
-with some extensions.
-.IP
-.nf
-\f[C]
-Term\ 1
-
-:\ \ \ Definition\ 1
-
-Term\ 2\ with\ *inline\ markup*
-
-:\ \ \ Definition\ 2
-
-\ \ \ \ \ \ \ \ {\ some\ code,\ part\ of\ Definition\ 2\ }
-
-\ \ \ \ Third\ paragraph\ of\ definition\ 2.
-\f[]
-.fi
-.PP
-Each term must fit on one line, which may optionally be followed by a
-blank line, and must be followed by one or more definitions.
-A definition begins with a colon or tilde, which may be indented one or
-two spaces.
-.PP
-A term may have multiple definitions, and each definition may consist of
-one or more block elements (paragraph, code block, list, etc.), each
-indented four spaces or one tab stop.
-The body of the definition (including the first line, aside from the
-colon or tilde) should be indented four spaces.
-However, as with other Markdown lists, you can "lazily" omit indentation
-except at the beginning of a paragraph or other block element:
-.IP
-.nf
-\f[C]
-Term\ 1
-
-:\ \ \ Definition
-with\ lazy\ continuation.
-
-\ \ \ \ Second\ paragraph\ of\ the\ definition.
-\f[]
-.fi
-.PP
-If you leave space before the definition (as in the example above), the
-text of the definition will be treated as a paragraph.
-In some output formats, this will mean greater spacing between
-term/definition pairs.
-For a more compact definition list, omit the space before the
-definition:
-.IP
-.nf
-\f[C]
-Term\ 1
-\ \ ~\ Definition\ 1
-
-Term\ 2
-\ \ ~\ Definition\ 2a
-\ \ ~\ Definition\ 2b
-\f[]
-.fi
-.PP
-Note that space between items in a definition list is required.
-(A variant that loosens this requirement, but disallows "lazy" hard
-wrapping, can be activated with \f[C]compact_definition_lists\f[]: see
-Non\-pandoc extensions, below.)
-.SS Numbered example lists
-.SS Extension: \f[C]example_lists\f[]
-.PP
-The special list marker \f[C]\@\f[] can be used for sequentially
-numbered examples.
-The first list item with a \f[C]\@\f[] marker will be numbered
-\[aq]1\[aq], the next \[aq]2\[aq], and so on, throughout the document.
-The numbered examples need not occur in a single list; each new list
-using \f[C]\@\f[] will take up where the last stopped.
-So, for example:
-.IP
-.nf
-\f[C]
-(\@)\ \ My\ first\ example\ will\ be\ numbered\ (1).
-(\@)\ \ My\ second\ example\ will\ be\ numbered\ (2).
-
-Explanation\ of\ examples.
-
-(\@)\ \ My\ third\ example\ will\ be\ numbered\ (3).
-\f[]
-.fi
-.PP
-Numbered examples can be labeled and referred to elsewhere in the
-document:
-.IP
-.nf
-\f[C]
-(\@good)\ \ This\ is\ a\ good\ example.
-
-As\ (\@good)\ illustrates,\ ...
-\f[]
-.fi
-.PP
-The label can be any string of alphanumeric characters, underscores, or
-hyphens.
-.PP
-Note: continuation paragraphs in example lists must always be indented
-four spaces, regardless of the length of the list marker.
-That is, example lists always behave as if the \f[C]four_space_rule\f[]
-extension is set.
-This is because example labels tend to be long, and indenting content to
-the first non\-space character after the label would be awkward.
-.SS Compact and loose lists
-.PP
-Pandoc behaves differently from \f[C]Markdown.pl\f[] on some "edge
-cases" involving lists.
-Consider this source:
-.IP
-.nf
-\f[C]
-+\ \ \ First
-+\ \ \ Second:
-\ \ \ \ \-\ \ \ Fee
-\ \ \ \ \-\ \ \ Fie
-\ \ \ \ \-\ \ \ Foe
-
-+\ \ \ Third
-\f[]
-.fi
-.PP
-Pandoc transforms this into a "compact list" (with no \f[C]<p>\f[] tags
-around "First", "Second", or "Third"), while Markdown puts \f[C]<p>\f[]
-tags around "Second" and "Third" (but not "First"), because of the blank
-space around "Third".
-Pandoc follows a simple rule: if the text is followed by a blank line,
-it is treated as a paragraph.
-Since "Second" is followed by a list, and not a blank line, it isn\[aq]t
-treated as a paragraph.
-The fact that the list is followed by a blank line is irrelevant.
-(Note: Pandoc works this way even when the \f[C]markdown_strict\f[]
-format is specified.
-This behavior is consistent with the official Markdown syntax
-description, even though it is different from that of
-\f[C]Markdown.pl\f[].)
-.SS Ending a list
-.PP
-What if you want to put an indented code block after a list?
-.IP
-.nf
-\f[C]
-\-\ \ \ item\ one
-\-\ \ \ item\ two
-
-\ \ \ \ {\ my\ code\ block\ }
-\f[]
-.fi
-.PP
-Trouble! Here pandoc (like other Markdown implementations) will treat
-\f[C]{\ my\ code\ block\ }\f[] as the second paragraph of item two, and
-not as a code block.
-.PP
-To "cut off" the list after item two, you can insert some non\-indented
-content, like an HTML comment, which won\[aq]t produce visible output in
-any format:
-.IP
-.nf
-\f[C]
-\-\ \ \ item\ one
-\-\ \ \ item\ two
-
-<!\-\-\ end\ of\ list\ \-\->
-
-\ \ \ \ {\ my\ code\ block\ }
-\f[]
-.fi
-.PP
-You can use the same trick if you want two consecutive lists instead of
-one big list:
-.IP
-.nf
-\f[C]
-1.\ \ one
-2.\ \ two
-3.\ \ three
-
-<!\-\-\ \-\->
-
-1.\ \ uno
-2.\ \ dos
-3.\ \ tres
-\f[]
-.fi
-.SS Horizontal rules
-.PP
-A line containing a row of three or more \f[C]*\f[], \f[C]\-\f[], or
-\f[C]_\f[] characters (optionally separated by spaces) produces a
-horizontal rule:
-.IP
-.nf
-\f[C]
-*\ \ *\ \ *\ \ *
-
-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-
-\f[]
-.fi
-.SS Tables
-.PP
-Four kinds of tables may be used.
-The first three kinds presuppose the use of a fixed\-width font, such as
-Courier.
-The fourth kind can be used with proportionally spaced fonts, as it does
-not require lining up columns.
-.SS Extension: \f[C]table_captions\f[]
-.PP
-A caption may optionally be provided with all 4 kinds of tables (as
-illustrated in the examples below).
-A caption is a paragraph beginning with the string \f[C]Table:\f[] (or
-just \f[C]:\f[]), which will be stripped off.
-It may appear either before or after the table.
-.SS Extension: \f[C]simple_tables\f[]
-.PP
-Simple tables look like this:
-.IP
-.nf
-\f[C]
-\ \ Right\ \ \ \ \ Left\ \ \ \ \ Center\ \ \ \ \ Default
-\-\-\-\-\-\-\-\ \ \ \ \ \-\-\-\-\-\-\ \-\-\-\-\-\-\-\-\-\-\ \ \ \-\-\-\-\-\-\-
-\ \ \ \ \ 12\ \ \ \ \ 12\ \ \ \ \ \ \ \ 12\ \ \ \ \ \ \ \ \ \ \ \ 12
-\ \ \ \ 123\ \ \ \ \ 123\ \ \ \ \ \ \ 123\ \ \ \ \ \ \ \ \ \ 123
-\ \ \ \ \ \ 1\ \ \ \ \ 1\ \ \ \ \ \ \ \ \ \ 1\ \ \ \ \ \ \ \ \ \ \ \ \ 1
-
-Table:\ \ Demonstration\ of\ simple\ table\ syntax.
-\f[]
-.fi
-.PP
-The headers and table rows must each fit on one line.
-Column alignments are determined by the position of the header text
-relative to the dashed line below it:
-.IP \[bu] 2
-If the dashed line is flush with the header text on the right side but
-extends beyond it on the left, the column is right\-aligned.
-.IP \[bu] 2
-If the dashed line is flush with the header text on the left side but
-extends beyond it on the right, the column is left\-aligned.
-.IP \[bu] 2
-If the dashed line extends beyond the header text on both sides, the
-column is centered.
-.IP \[bu] 2
-If the dashed line is flush with the header text on both sides, the
-default alignment is used (in most cases, this will be left).
-.PP
-The table must end with a blank line, or a line of dashes followed by a
-blank line.
-.PP
-The column headers may be omitted, provided a dashed line is used to end
-the table.
-For example:
-.IP
-.nf
-\f[C]
-\-\-\-\-\-\-\-\ \ \ \ \ \-\-\-\-\-\-\ \-\-\-\-\-\-\-\-\-\-\ \ \ \-\-\-\-\-\-\-
-\ \ \ \ \ 12\ \ \ \ \ 12\ \ \ \ \ \ \ \ 12\ \ \ \ \ \ \ \ \ \ \ \ \ 12
-\ \ \ \ 123\ \ \ \ \ 123\ \ \ \ \ \ \ 123\ \ \ \ \ \ \ \ \ \ \ 123
-\ \ \ \ \ \ 1\ \ \ \ \ 1\ \ \ \ \ \ \ \ \ \ 1\ \ \ \ \ \ \ \ \ \ \ \ \ \ 1
-\-\-\-\-\-\-\-\ \ \ \ \ \-\-\-\-\-\-\ \-\-\-\-\-\-\-\-\-\-\ \ \ \-\-\-\-\-\-\-
-\f[]
-.fi
-.PP
-When headers are omitted, column alignments are determined on the basis
-of the first line of the table body.
-So, in the tables above, the columns would be right, left, center, and
-right aligned, respectively.
-.SS Extension: \f[C]multiline_tables\f[]
-.PP
-Multiline tables allow headers and table rows to span multiple lines of
-text (but cells that span multiple columns or rows of the table are not
-supported).
-Here is an example:
-.IP
-.nf
-\f[C]
-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-
-\ Centered\ \ \ Default\ \ \ \ \ \ \ \ \ \ \ Right\ Left
-\ \ Header\ \ \ \ Aligned\ \ \ \ \ \ \ \ \ Aligned\ Aligned
-\-\-\-\-\-\-\-\-\-\-\-\ \-\-\-\-\-\-\-\ \-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\ \-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-
-\ \ \ First\ \ \ \ row\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ 12.0\ Example\ of\ a\ row\ that
-\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ spans\ multiple\ lines.
-
-\ \ Second\ \ \ \ row\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ 5.0\ Here\[aq]s\ another\ one.\ Note
-\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ the\ blank\ line\ between
-\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ rows.
-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-
-
-Table:\ Here\[aq]s\ the\ caption.\ It,\ too,\ may\ span
-multiple\ lines.
-\f[]
-.fi
-.PP
-These work like simple tables, but with the following differences:
-.IP \[bu] 2
-They must begin with a row of dashes, before the header text (unless the
-headers are omitted).
-.IP \[bu] 2
-They must end with a row of dashes, then a blank line.
-.IP \[bu] 2
-The rows must be separated by blank lines.
-.PP
-In multiline tables, the table parser pays attention to the widths of
-the columns, and the writers try to reproduce these relative widths in
-the output.
-So, if you find that one of the columns is too narrow in the output, try
-widening it in the Markdown source.
-.PP
-Headers may be omitted in multiline tables as well as simple tables:
-.IP
-.nf
-\f[C]
-\-\-\-\-\-\-\-\-\-\-\-\ \-\-\-\-\-\-\-\ \-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\ \-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-
-\ \ \ First\ \ \ \ row\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ 12.0\ Example\ of\ a\ row\ that
-\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ spans\ multiple\ lines.
-
-\ \ Second\ \ \ \ row\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ 5.0\ Here\[aq]s\ another\ one.\ Note
-\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ the\ blank\ line\ between
-\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ rows.
-\-\-\-\-\-\-\-\-\-\-\-\ \-\-\-\-\-\-\-\ \-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\ \-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-
-
-:\ Here\[aq]s\ a\ multiline\ table\ without\ headers.
-\f[]
-.fi
-.PP
-It is possible for a multiline table to have just one row, but the row
-should be followed by a blank line (and then the row of dashes that ends
-the table), or the table may be interpreted as a simple table.
-.SS Extension: \f[C]grid_tables\f[]
-.PP
-Grid tables look like this:
-.IP
-.nf
-\f[C]
-:\ Sample\ grid\ table.
-
-+\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+
-|\ Fruit\ \ \ \ \ \ \ \ \ |\ Price\ \ \ \ \ \ \ \ \ |\ Advantages\ \ \ \ \ \ \ \ \ |
-+===============+===============+====================+
-|\ Bananas\ \ \ \ \ \ \ |\ $1.34\ \ \ \ \ \ \ \ \ |\ \-\ built\-in\ wrapper\ |
-|\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ |\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ |\ \-\ bright\ color\ \ \ \ \ |
-+\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+
-|\ Oranges\ \ \ \ \ \ \ |\ $2.10\ \ \ \ \ \ \ \ \ |\ \-\ cures\ scurvy\ \ \ \ \ |
-|\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ |\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ |\ \-\ tasty\ \ \ \ \ \ \ \ \ \ \ \ |
-+\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+
-\f[]
-.fi
-.PP
-The row of \f[C]=\f[]s separates the header from the table body, and can
-be omitted for a headerless table.
-The cells of grid tables may contain arbitrary block elements (multiple
-paragraphs, code blocks, lists, etc.).
-Cells that span multiple columns or rows are not supported.
-Grid tables can be created easily using Emacs table mode.
-.PP
-Alignments can be specified as with pipe tables, by putting colons at
-the boundaries of the separator line after the header:
-.IP
-.nf
-\f[C]
-+\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+
-|\ Right\ \ \ \ \ \ \ \ \ |\ Left\ \ \ \ \ \ \ \ \ \ |\ Centered\ \ \ \ \ \ \ \ \ \ \ |
-+==============:+:==============+:==================:+
-|\ Bananas\ \ \ \ \ \ \ |\ $1.34\ \ \ \ \ \ \ \ \ |\ built\-in\ wrapper\ \ \ |
-+\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+
-\f[]
-.fi
-.PP
-For headerless tables, the colons go on the top line instead:
-.IP
-.nf
-\f[C]
-+\-\-\-\-\-\-\-\-\-\-\-\-\-\-:+:\-\-\-\-\-\-\-\-\-\-\-\-\-\-+:\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-:+
-|\ Right\ \ \ \ \ \ \ \ \ |\ Left\ \ \ \ \ \ \ \ \ \ |\ Centered\ \ \ \ \ \ \ \ \ \ \ |
-+\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+
-\f[]
-.fi
-.SS Grid Table Limitations
-.PP
-Pandoc does not support grid tables with row spans or column spans.
-This means that neither variable numbers of columns across rows nor
-variable numbers of rows across columns are supported by Pandoc.
-All grid tables must have the same number of columns in each row, and
-the same number of rows in each column.
-For example, the Docutils sample grid tables will not render as expected
-with Pandoc.
-.SS Extension: \f[C]pipe_tables\f[]
-.PP
-Pipe tables look like this:
-.IP
-.nf
-\f[C]
-|\ Right\ |\ Left\ |\ Default\ |\ Center\ |
-|\-\-\-\-\-\-:|:\-\-\-\-\-|\-\-\-\-\-\-\-\-\-|:\-\-\-\-\-\-:|
-|\ \ \ 12\ \ |\ \ 12\ \ |\ \ \ \ 12\ \ \ |\ \ \ \ 12\ \ |
-|\ \ 123\ \ |\ \ 123\ |\ \ \ 123\ \ \ |\ \ \ 123\ \ |
-|\ \ \ \ 1\ \ |\ \ \ \ 1\ |\ \ \ \ \ 1\ \ \ |\ \ \ \ \ 1\ \ |
-
-\ \ :\ Demonstration\ of\ pipe\ table\ syntax.
-\f[]
-.fi
-.PP
-The syntax is identical to PHP Markdown Extra tables.
-The beginning and ending pipe characters are optional, but pipes are
-required between all columns.
-The colons indicate column alignment as shown.
-The header cannot be omitted.
-To simulate a headerless table, include a header with blank cells.
-.PP
-Since the pipes indicate column boundaries, columns need not be
-vertically aligned, as they are in the above example.
-So, this is a perfectly legal (though ugly) pipe table:
-.IP
-.nf
-\f[C]
-fruit|\ price
-\-\-\-\-\-|\-\-\-\-\-:
-apple|2.05
-pear|1.37
-orange|3.09
-\f[]
-.fi
-.PP
-The cells of pipe tables cannot contain block elements like paragraphs
-and lists, and cannot span multiple lines.
-If a pipe table contains a row whose printable content is wider than the
-column width (see \f[C]\-\-columns\f[]), then the cell contents will
-wrap, with the relative cell widths determined by the widths of the
-separator lines.
-(In this case, the table will take up the full text width.) If no lines
-are wider than column width, then cell contents will not be wrapped, and
-the cells will be sized to their contents.
-.PP
-Note: pandoc also recognizes pipe tables of the following form, as can
-be produced by Emacs\[aq] orgtbl\-mode:
-.IP
-.nf
-\f[C]
-|\ One\ |\ Two\ \ \ |
-|\-\-\-\-\-+\-\-\-\-\-\-\-|
-|\ my\ \ |\ table\ |
-|\ is\ \ |\ nice\ \ |
-\f[]
-.fi
-.PP
-The difference is that \f[C]+\f[] is used instead of \f[C]|\f[].
-Other orgtbl features are not supported.
-In particular, to get non\-default column alignment, you\[aq]ll need to
-add colons as above.
-.SS Metadata blocks
-.SS Extension: \f[C]pandoc_title_block\f[]
-.PP
-If the file begins with a title block
-.IP
-.nf
-\f[C]
-%\ title
-%\ author(s)\ (separated\ by\ semicolons)
-%\ date
-\f[]
-.fi
-.PP
-it will be parsed as bibliographic information, not regular text.
-(It will be used, for example, in the title of standalone LaTeX or HTML
-output.) The block may contain just a title, a title and an author, or
-all three elements.
-If you want to include an author but no title, or a title and a date but
-no author, you need a blank line:
-.IP
-.nf
-\f[C]
-%
-%\ Author
-
-%\ My\ title
-%
-%\ June\ 15,\ 2006
-\f[]
-.fi
-.PP
-The title may occupy multiple lines, but continuation lines must begin
-with leading space, thus:
-.IP
-.nf
-\f[C]
-%\ My\ title
-\ \ on\ multiple\ lines
-\f[]
-.fi
-.PP
-If a document has multiple authors, the authors may be put on separate
-lines with leading space, or separated by semicolons, or both.
-So, all of the following are equivalent:
-.IP
-.nf
-\f[C]
-%\ Author\ One
-\ \ Author\ Two
-
-%\ Author\ One;\ Author\ Two
-
-%\ Author\ One;
-\ \ Author\ Two
-\f[]
-.fi
-.PP
-The date must fit on one line.
-.PP
-All three metadata fields may contain standard inline formatting
-(italics, links, footnotes, etc.).
-.PP
-Title blocks will always be parsed, but they will affect the output only
-when the \f[C]\-\-standalone\f[] (\f[C]\-s\f[]) option is chosen.
-In HTML output, titles will appear twice: once in the document head \-\-
-this is the title that will appear at the top of the window in a browser
-\-\- and once at the beginning of the document body.
-The title in the document head can have an optional prefix attached
-(\f[C]\-\-title\-prefix\f[] or \f[C]\-T\f[] option).
-The title in the body appears as an H1 element with class "title", so it
-can be suppressed or reformatted with CSS.
-If a title prefix is specified with \f[C]\-T\f[] and no title block
-appears in the document, the title prefix will be used by itself as the
-HTML title.
-.PP
-The man page writer extracts a title, man page section number, and other
-header and footer information from the title line.
-The title is assumed to be the first word on the title line, which may
-optionally end with a (single\-digit) section number in parentheses.
-(There should be no space between the title and the parentheses.)
-Anything after this is assumed to be additional footer and header text.
-A single pipe character (\f[C]|\f[]) should be used to separate the
-footer text from the header text.
-Thus,
-.IP
-.nf
-\f[C]
-%\ PANDOC(1)
-\f[]
-.fi
-.PP
-will yield a man page with the title \f[C]PANDOC\f[] and section 1.
-.IP
-.nf
-\f[C]
-%\ PANDOC(1)\ Pandoc\ User\ Manuals
-\f[]
-.fi
-.PP
-will also have "Pandoc User Manuals" in the footer.
-.IP
-.nf
-\f[C]
-%\ PANDOC(1)\ Pandoc\ User\ Manuals\ |\ Version\ 4.0
-\f[]
-.fi
-.PP
-will also have "Version 4.0" in the header.
-.SS Extension: \f[C]yaml_metadata_block\f[]
-.PP
-A YAML metadata block is a valid YAML object, delimited by a line of
-three hyphens (\f[C]\-\-\-\f[]) at the top and a line of three hyphens
-(\f[C]\-\-\-\f[]) or three dots (\f[C]\&...\f[]) at the bottom.
-A YAML metadata block may occur anywhere in the document, but if it is
-not at the beginning, it must be preceded by a blank line.
-(Note that, because of the way pandoc concatenates input files when
-several are provided, you may also keep the metadata in a separate YAML
-file and pass it to pandoc as an argument, along with your Markdown
-files:
-.IP
-.nf
-\f[C]
-pandoc\ chap1.md\ chap2.md\ chap3.md\ metadata.yaml\ \-s\ \-o\ book.html
-\f[]
-.fi
-.PP
-Just be sure that the YAML file begins with \f[C]\-\-\-\f[] and ends
-with \f[C]\-\-\-\f[] or \f[C]\&...\f[].)
-.PP
-Metadata will be taken from the fields of the YAML object and added to
-any existing document metadata.
-Metadata can contain lists and objects (nested arbitrarily), but all
-string scalars will be interpreted as Markdown.
-Fields with names ending in an underscore will be ignored by pandoc.
-(They may be given a role by external processors.)
-.PP
-A document may contain multiple metadata blocks.
-The metadata fields will be combined through a \f[I]left\-biased
-union\f[]: if two metadata blocks attempt to set the same field, the
-value from the first block will be taken.
-.PP
-When pandoc is used with \f[C]\-t\ markdown\f[] to create a Markdown
-document, a YAML metadata block will be produced only if the
-\f[C]\-s/\-\-standalone\f[] option is used.
-All of the metadata will appear in a single block at the beginning of
-the document.
-.PP
-Note that YAML escaping rules must be followed.
-Thus, for example, if a title contains a colon, it must be quoted.
-The pipe character (\f[C]|\f[]) can be used to begin an indented block
-that will be interpreted literally, without need for escaping.
-This form is necessary when the field contains blank lines or
-block\-level formatting:
-.IP
-.nf
-\f[C]
-\-\-\-
-title:\ \ \[aq]This\ is\ the\ title:\ it\ contains\ a\ colon\[aq]
-author:
-\-\ Author\ One
-\-\ Author\ Two
-tags:\ [nothing,\ nothingness]
-abstract:\ |
-\ \ This\ is\ the\ abstract.
-
-\ \ It\ consists\ of\ two\ paragraphs.
-\&...
-\f[]
-.fi
-.PP
-Template variables will be set automatically from the metadata.
-Thus, for example, in writing HTML, the variable \f[C]abstract\f[] will
-be set to the HTML equivalent of the Markdown in the \f[C]abstract\f[]
-field:
-.IP
-.nf
-\f[C]
-<p>This\ is\ the\ abstract.</p>
-<p>It\ consists\ of\ two\ paragraphs.</p>
-\f[]
-.fi
-.PP
-Variables can contain arbitrary YAML structures, but the template must
-match this structure.
-The \f[C]author\f[] variable in the default templates expects a simple
-list or string, but can be changed to support more complicated
-structures.
-The following combination, for example, would add an affiliation to the
-author if one is given:
-.IP
-.nf
-\f[C]
-\-\-\-
-title:\ The\ document\ title
-author:
-\-\ name:\ Author\ One
-\ \ affiliation:\ University\ of\ Somewhere
-\-\ name:\ Author\ Two
-\ \ affiliation:\ University\ of\ Nowhere
-\&...
-\f[]
-.fi
-.PP
-To use the structured authors in the example above, you would need a
-custom template:
-.IP
-.nf
-\f[C]
-$for(author)$
-$if(author.name)$
-$author.name$$if(author.affiliation)$\ ($author.affiliation$)$endif$
-$else$
-$author$
-$endif$
-$endfor$
-\f[]
-.fi
-.SS Backslash escapes
-.SS Extension: \f[C]all_symbols_escapable\f[]
-.PP
-Except inside a code block or inline code, any punctuation or space
-character preceded by a backslash will be treated literally, even if it
-would normally indicate formatting.
-Thus, for example, if one writes
-.IP
-.nf
-\f[C]
-*\\*hello\\**
-\f[]
-.fi
-.PP
-one will get
-.IP
-.nf
-\f[C]
-<em>*hello*</em>
-\f[]
-.fi
-.PP
-instead of
-.IP
-.nf
-\f[C]
-<strong>hello</strong>
-\f[]
-.fi
-.PP
-This rule is easier to remember than standard Markdown\[aq]s rule, which
-allows only the following characters to be backslash\-escaped:
-.IP
-.nf
-\f[C]
-\\`*_{}[]()>#+\-.!
-\f[]
-.fi
-.PP
-(However, if the \f[C]markdown_strict\f[] format is used, the standard
-Markdown rule will be used.)
-.PP
-A backslash\-escaped space is parsed as a nonbreaking space.
-It will appear in TeX output as \f[C]~\f[] and in HTML and XML as
-\f[C]\\&#160;\f[] or \f[C]\\&nbsp;\f[].
-.PP
-A backslash\-escaped newline (i.e.
-a backslash occurring at the end of a line) is parsed as a hard line
-break.
-It will appear in TeX output as \f[C]\\\\\f[] and in HTML as
-\f[C]<br\ />\f[].
-This is a nice alternative to Markdown\[aq]s "invisible" way of
-indicating hard line breaks using two trailing spaces on a line.
-.PP
-Backslash escapes do not work in verbatim contexts.
-.SS Inline formatting
-.SS Emphasis
-.PP
-To \f[I]emphasize\f[] some text, surround it with \f[C]*\f[]s or
-\f[C]_\f[], like this:
-.IP
-.nf
-\f[C]
-This\ text\ is\ _emphasized\ with\ underscores_,\ and\ this
-is\ *emphasized\ with\ asterisks*.
-\f[]
-.fi
-.PP
-Double \f[C]*\f[] or \f[C]_\f[] produces \f[B]strong emphasis\f[]:
-.IP
-.nf
-\f[C]
-This\ is\ **strong\ emphasis**\ and\ __with\ underscores__.
-\f[]
-.fi
-.PP
-A \f[C]*\f[] or \f[C]_\f[] character surrounded by spaces, or
-backslash\-escaped, will not trigger emphasis:
-.IP
-.nf
-\f[C]
-This\ is\ *\ not\ emphasized\ *,\ and\ \\*neither\ is\ this\\*.
-\f[]
-.fi
-.SS Extension: \f[C]intraword_underscores\f[]
-.PP
-Because \f[C]_\f[] is sometimes used inside words and identifiers,
-pandoc does not interpret a \f[C]_\f[] surrounded by alphanumeric
-characters as an emphasis marker.
-If you want to emphasize just part of a word, use \f[C]*\f[]:
-.IP
-.nf
-\f[C]
-feas*ible*,\ not\ feas*able*.
-\f[]
-.fi
-.SS Strikeout
-.SS Extension: \f[C]strikeout\f[]
-.PP
-To strikeout a section of text with a horizontal line, begin and end it
-with \f[C]~~\f[].
-Thus, for example,
-.IP
-.nf
-\f[C]
-This\ ~~is\ deleted\ text.~~
-\f[]
-.fi
-.SS Superscripts and subscripts
-.SS Extension: \f[C]superscript\f[], \f[C]subscript\f[]
-.PP
-Superscripts may be written by surrounding the superscripted text by
-\f[C]^\f[] characters; subscripts may be written by surrounding the
-subscripted text by \f[C]~\f[] characters.
-Thus, for example,
-.IP
-.nf
-\f[C]
-H~2~O\ is\ a\ liquid.\ \ 2^10^\ is\ 1024.
-\f[]
-.fi
-.PP
-If the superscripted or subscripted text contains spaces, these spaces
-must be escaped with backslashes.
-(This is to prevent accidental superscripting and subscripting through
-the ordinary use of \f[C]~\f[] and \f[C]^\f[].) Thus, if you want the
-letter P with \[aq]a cat\[aq] in subscripts, use \f[C]P~a\\\ cat~\f[],
-not \f[C]P~a\ cat~\f[].
-.SS Verbatim
-.PP
-To make a short span of text verbatim, put it inside backticks:
-.IP
-.nf
-\f[C]
-What\ is\ the\ difference\ between\ `>>=`\ and\ `>>`?
-\f[]
-.fi
-.PP
-If the verbatim text includes a backtick, use double backticks:
-.IP
-.nf
-\f[C]
-Here\ is\ a\ literal\ backtick\ ``\ `\ ``.
-\f[]
-.fi
-.PP
-(The spaces after the opening backticks and before the closing backticks
-will be ignored.)
-.PP
-The general rule is that a verbatim span starts with a string of
-consecutive backticks (optionally followed by a space) and ends with a
-string of the same number of backticks (optionally preceded by a space).
-.PP
-Note that backslash\-escapes (and other Markdown constructs) do not work
-in verbatim contexts:
-.IP
-.nf
-\f[C]
-This\ is\ a\ backslash\ followed\ by\ an\ asterisk:\ `\\*`.
-\f[]
-.fi
-.SS Extension: \f[C]inline_code_attributes\f[]
-.PP
-Attributes can be attached to verbatim text, just as with fenced code
-blocks:
-.IP
-.nf
-\f[C]
-`<$>`{.haskell}
-\f[]
-.fi
-.SS Small caps
-.PP
-To write small caps, use the \f[C]smallcaps\f[] class:
-.IP
-.nf
-\f[C]
-[Small\ caps]{.smallcaps}
-\f[]
-.fi
-.PP
-Or, without the \f[C]bracketed_spans\f[] extension:
-.IP
-.nf
-\f[C]
-<span\ class="smallcaps">Small\ caps</span>
-\f[]
-.fi
-.PP
-For compatibility with other Markdown flavors, CSS is also supported:
-.IP
-.nf
-\f[C]
-<span\ style="font\-variant:small\-caps;">Small\ caps</span>
-\f[]
-.fi
-.PP
-This will work in all output formats that support small caps.
-.SS Math
-.SS Extension: \f[C]tex_math_dollars\f[]
-.PP
-Anything between two \f[C]$\f[] characters will be treated as TeX math.
-The opening \f[C]$\f[] must have a non\-space character immediately to
-its right, while the closing \f[C]$\f[] must have a non\-space character
-immediately to its left, and must not be followed immediately by a
-digit.
-Thus, \f[C]$20,000\ and\ $30,000\f[] won\[aq]t parse as math.
-If for some reason you need to enclose text in literal \f[C]$\f[]
-characters, backslash\-escape them and they won\[aq]t be treated as math
-delimiters.
-.PP
-TeX math will be printed in all output formats.
-How it is rendered depends on the output format:
-.TP
-.B Markdown, LaTeX, Emacs Org mode, ConTeXt, ZimWiki
-It will appear verbatim between \f[C]$\f[] characters.
-.RS
-.RE
-.TP
-.B reStructuredText
-It will be rendered using an interpreted text role \f[C]:math:\f[].
-.RS
-.RE
-.TP
-.B AsciiDoc
-It will be rendered as \f[C]latexmath:[...]\f[].
-.RS
-.RE
-.TP
-.B Texinfo
-It will be rendered inside a \f[C]\@math\f[] command.
-.RS
-.RE
-.TP
-.B groff man
-It will be rendered verbatim without \f[C]$\f[]\[aq]s.
-.RS
-.RE
-.TP
-.B MediaWiki, DokuWiki
-It will be rendered inside \f[C]<math>\f[] tags.
-.RS
-.RE
-.TP
-.B Textile
-It will be rendered inside \f[C]<span\ class="math">\f[] tags.
-.RS
-.RE
-.TP
-.B RTF, OpenDocument
-It will be rendered, if possible, using Unicode characters, and will
-otherwise appear verbatim.
-.RS
-.RE
-.TP
-.B ODT
-It will be rendered, if possible, using MathML.
-.RS
-.RE
-.TP
-.B DocBook
-If the \f[C]\-\-mathml\f[] flag is used, it will be rendered using
-MathML in an \f[C]inlineequation\f[] or \f[C]informalequation\f[] tag.
-Otherwise it will be rendered, if possible, using Unicode characters.
-.RS
-.RE
-.TP
-.B Docx
-It will be rendered using OMML math markup.
-.RS
-.RE
-.TP
-.B FictionBook2
-If the \f[C]\-\-webtex\f[] option is used, formulas are rendered as
-images using CodeCogs or other compatible web service, downloaded and
-embedded in the e\-book.
-Otherwise, they will appear verbatim.
-.RS
-.RE
-.TP
-.B HTML, Slidy, DZSlides, S5, EPUB
-The way math is rendered in HTML will depend on the command\-line
-options selected.
-Therefore see Math rendering in HTML above.
-.RS
-.RE
-.SS Raw HTML
-.SS Extension: \f[C]raw_html\f[]
-.PP
-Markdown allows you to insert raw HTML (or DocBook) anywhere in a
-document (except verbatim contexts, where \f[C]<\f[], \f[C]>\f[], and
-\f[C]&\f[] are interpreted literally).
-(Technically this is not an extension, since standard Markdown allows
-it, but it has been made an extension so that it can be disabled if
-desired.)
-.PP
-The raw HTML is passed through unchanged in HTML, S5, Slidy, Slideous,
-DZSlides, EPUB, Markdown, Emacs Org mode, and Textile output, and
-suppressed in other formats.
-.SS Extension: \f[C]markdown_in_html_blocks\f[]
-.PP
-Standard Markdown allows you to include HTML "blocks": blocks of HTML
-between balanced tags that are separated from the surrounding text with
-blank lines, and start and end at the left margin.
-Within these blocks, everything is interpreted as HTML, not Markdown; so
-(for example), \f[C]*\f[] does not signify emphasis.
-.PP
-Pandoc behaves this way when the \f[C]markdown_strict\f[] format is
-used; but by default, pandoc interprets material between HTML block tags
-as Markdown.
-Thus, for example, pandoc will turn
-.IP
-.nf
-\f[C]
-<table>
-<tr>
-<td>*one*</td>
-<td>[a\ link](http://google.com)</td>
-</tr>
-</table>
-\f[]
-.fi
-.PP
-into
-.IP
-.nf
-\f[C]
-<table>
-<tr>
-<td><em>one</em></td>
-<td><a\ href="http://google.com">a\ link</a></td>
-</tr>
-</table>
-\f[]
-.fi
-.PP
-whereas \f[C]Markdown.pl\f[] will preserve it as is.
-.PP
-There is one exception to this rule: text between \f[C]<script>\f[] and
-\f[C]<style>\f[] tags is not interpreted as Markdown.
-.PP
-This departure from standard Markdown should make it easier to mix
-Markdown with HTML block elements.
-For example, one can surround a block of Markdown text with
-\f[C]<div>\f[] tags without preventing it from being interpreted as
-Markdown.
-.SS Extension: \f[C]native_divs\f[]
-.PP
-Use native pandoc \f[C]Div\f[] blocks for content inside \f[C]<div>\f[]
-tags.
-For the most part this should give the same output as
-\f[C]markdown_in_html_blocks\f[], but it makes it easier to write pandoc
-filters to manipulate groups of blocks.
-.SS Extension: \f[C]native_spans\f[]
-.PP
-Use native pandoc \f[C]Span\f[] blocks for content inside
-\f[C]<span>\f[] tags.
-For the most part this should give the same output as \f[C]raw_html\f[],
-but it makes it easier to write pandoc filters to manipulate groups of
-inlines.
-.SS Extension: \f[C]fenced_divs\f[]
-.PP
-Allow special fenced syntax for native \f[C]Div\f[] blocks.
-A Div starts with a fence containing at least three consecutive colons
-plus some attributes.
-The attributes may optionally be followed by another string of
-consecutive colons.
-The attribute syntax is exactly as in fenced code blocks (see Extension:
-\f[C]fenced_code_attributes\f[]).
-As with fenced code blocks, one can use either attributes in curly
-braces or a single unbraced word, which will be treated as a class name.
-The Div ends with another line containing a string of at least three
-consecutive colons.
-The fenced Div should be separated by blank lines from preceding and
-following blocks.
-.PP
-Example:
-.IP
-.nf
-\f[C]
-:::::\ {#special\ .sidebar}
-Here\ is\ a\ paragraph.
-
-And\ another.
-:::::
-\f[]
-.fi
-.PP
-Fenced divs can be nested.
-Opening fences are distinguished because they \f[I]must\f[] have
-attributes:
-.IP
-.nf
-\f[C]
-:::\ Warning\ ::::::
-This\ is\ a\ warning.
-
-:::\ Danger
-This\ is\ a\ warning\ within\ a\ warning.
-:::
-::::::::::::::::::
-\f[]
-.fi
-.PP
-Fences without attributes are always closing fences.
-Unlike with fenced code blocks, the number of colons in the closing
-fence need not match the number in the opening fence.
-However, it can be helpful for visual clarity to use fences of different
-lengths to distinguish nested divs from their parents.
-.SS Extension: \f[C]raw_tex\f[]
-.PP
-In addition to raw HTML, pandoc allows raw LaTeX, TeX, and ConTeXt to be
-included in a document.
-Inline TeX commands will be preserved and passed unchanged to the LaTeX
-and ConTeXt writers.
-Thus, for example, you can use LaTeX to include BibTeX citations:
-.IP
-.nf
-\f[C]
-This\ result\ was\ proved\ in\ \\cite{jones.1967}.
-\f[]
-.fi
-.PP
-Note that in LaTeX environments, like
-.IP
-.nf
-\f[C]
-\\begin{tabular}{|l|l|}\\hline
-Age\ &\ Frequency\ \\\\\ \\hline
-18\-\-25\ \ &\ 15\ \\\\
-26\-\-35\ \ &\ 33\ \\\\
-36\-\-45\ \ &\ 22\ \\\\\ \\hline
-\\end{tabular}
-\f[]
-.fi
-.PP
-the material between the begin and end tags will be interpreted as raw
-LaTeX, not as Markdown.
-.PP
-Inline LaTeX is ignored in output formats other than Markdown, LaTeX,
-Emacs Org mode, and ConTeXt.
-.SS Generic raw attribute
-.SS Extension: \f[C]raw_attribute\f[]
-.PP
-Inline spans and fenced code blocks with a special kind of attribute
-will be parsed as raw content with the designated format.
-For example, the following produces a raw groff \f[C]ms\f[] block:
-.IP
-.nf
-\f[C]
-```{=ms}
-\&.MYMACRO
-blah\ blah
-```
-\f[]
-.fi
-.PP
-And the following produces a raw \f[C]html\f[] inline element:
-.IP
-.nf
-\f[C]
-This\ is\ `<a>html</a>`{=html}
-\f[]
-.fi
-.PP
-The format name should match the target format name (see
-\f[C]\-t/\-\-to\f[], above, for a list, or use
-\f[C]pandoc\ \-\-list\-output\-formats\f[]).
-.PP
-This extension presupposes that the relevant kind of inline code or
-fenced code block is enabled.
-Thus, for example, to use a raw attribute with a backtick code block,
-\f[C]backtick_code_blocks\f[] must be enabled.
-.PP
-The raw attribute cannot be combined with regular attributes.
-.SS LaTeX macros
-.SS Extension: \f[C]latex_macros\f[]
-.PP
-For output formats other than LaTeX, pandoc will parse LaTeX macro
-definitions and apply the resulting macros to all LaTeX math and raw
-LaTeX.
-So, for example, the following will work in all output formats, not just
-LaTeX:
-.IP
-.nf
-\f[C]
-\\newcommand{\\tuple}[1]{\\langle\ #1\ \\rangle}
-
-$\\tuple{a,\ b,\ c}$
-\f[]
-.fi
-.PP
-In LaTeX output, the macro definitions will not be passed through as raw
-LaTeX.
-.PP
-When \f[C]latex_macros\f[] is disabled, the macro definitions will be
-passed through as raw LaTeX, and the raw LaTeX and math will not have
-macros applied.
-This is usually a better approach when you are targeting LaTeX or PDF.
-.SS Links
-.PP
-Markdown allows links to be specified in several ways.
-.SS Automatic links
-.PP
-If you enclose a URL or email address in pointy brackets, it will become
-a link:
-.IP
-.nf
-\f[C]
-<http://google.com>
-<sam\@green.eggs.ham>
-\f[]
-.fi
-.SS Inline links
-.PP
-An inline link consists of the link text in square brackets, followed by
-the URL in parentheses.
-(Optionally, the URL can be followed by a link title, in quotes.)
-.IP
-.nf
-\f[C]
-This\ is\ an\ [inline\ link](/url),\ and\ here\[aq]s\ [one\ with
-a\ title](http://fsf.org\ "click\ here\ for\ a\ good\ time!").
-\f[]
-.fi
-.PP
-There can be no space between the bracketed part and the parenthesized
-part.
-The link text can contain formatting (such as emphasis), but the title
-cannot.
-.PP
-Email addresses in inline links are not autodetected, so they have to be
-prefixed with \f[C]mailto\f[]:
-.IP
-.nf
-\f[C]
-[Write\ me!](mailto:sam\@green.eggs.ham)
-\f[]
-.fi
-.SS Reference links
-.PP
-An \f[I]explicit\f[] reference link has two parts, the link itself and
-the link definition, which may occur elsewhere in the document (either
-before or after the link).
-.PP
-The link consists of link text in square brackets, followed by a label
-in square brackets.
-(There cannot be space between the two unless the
-\f[C]spaced_reference_links\f[] extension is enabled.) The link
-definition consists of the bracketed label, followed by a colon and a
-space, followed by the URL, and optionally (after a space) a link title
-either in quotes or in parentheses.
-The label must not be parseable as a citation (assuming the
-\f[C]citations\f[] extension is enabled): citations take precedence over
-link labels.
-.PP
-Here are some examples:
-.IP
-.nf
-\f[C]
-[my\ label\ 1]:\ /foo/bar.html\ \ "My\ title,\ optional"
-[my\ label\ 2]:\ /foo
-[my\ label\ 3]:\ http://fsf.org\ (The\ free\ software\ foundation)
-[my\ label\ 4]:\ /bar#special\ \ \[aq]A\ title\ in\ single\ quotes\[aq]
-\f[]
-.fi
-.PP
-The URL may optionally be surrounded by angle brackets:
-.IP
-.nf
-\f[C]
-[my\ label\ 5]:\ <http://foo.bar.baz>
-\f[]
-.fi
-.PP
-The title may go on the next line:
-.IP
-.nf
-\f[C]
-[my\ label\ 3]:\ http://fsf.org
-\ \ "The\ free\ software\ foundation"
-\f[]
-.fi
-.PP
-Note that link labels are not case sensitive.
-So, this will work:
-.IP
-.nf
-\f[C]
-Here\ is\ [my\ link][FOO]
-
-[Foo]:\ /bar/baz
-\f[]
-.fi
-.PP
-In an \f[I]implicit\f[] reference link, the second pair of brackets is
-empty:
-.IP
-.nf
-\f[C]
-See\ [my\ website][].
-
-[my\ website]:\ http://foo.bar.baz
-\f[]
-.fi
-.PP
-Note: In \f[C]Markdown.pl\f[] and most other Markdown implementations,
-reference link definitions cannot occur in nested constructions such as
-list items or block quotes.
-Pandoc lifts this arbitrary seeming restriction.
-So the following is fine in pandoc, though not in most other
-implementations:
-.IP
-.nf
-\f[C]
->\ My\ block\ [quote].
->
->\ [quote]:\ /foo
-\f[]
-.fi
-.SS Extension: \f[C]shortcut_reference_links\f[]
-.PP
-In a \f[I]shortcut\f[] reference link, the second pair of brackets may
-be omitted entirely:
-.IP
-.nf
-\f[C]
-See\ [my\ website].
-
-[my\ website]:\ http://foo.bar.baz
-\f[]
-.fi
-.SS Internal links
-.PP
-To link to another section of the same document, use the automatically
-generated identifier (see Header identifiers).
-For example:
-.IP
-.nf
-\f[C]
-See\ the\ [Introduction](#introduction).
-\f[]
-.fi
-.PP
-or
-.IP
-.nf
-\f[C]
-See\ the\ [Introduction].
-
-[Introduction]:\ #introduction
-\f[]
-.fi
-.PP
-Internal links are currently supported for HTML formats (including HTML
-slide shows and EPUB), LaTeX, and ConTeXt.
-.SS Images
-.PP
-A link immediately preceded by a \f[C]!\f[] will be treated as an image.
-The link text will be used as the image\[aq]s alt text:
-.IP
-.nf
-\f[C]
-![la\ lune](lalune.jpg\ "Voyage\ to\ the\ moon")
-
-![movie\ reel]
-
-[movie\ reel]:\ movie.gif
-\f[]
-.fi
-.SS Extension: \f[C]implicit_figures\f[]
-.PP
-An image with nonempty alt text, occurring by itself in a paragraph,
-will be rendered as a figure with a caption.
-The image\[aq]s alt text will be used as the caption.
-.IP
-.nf
-\f[C]
-![This\ is\ the\ caption](/url/of/image.png)
-\f[]
-.fi
-.PP
-How this is rendered depends on the output format.
-Some output formats (e.g.
-RTF) do not yet support figures.
-In those formats, you\[aq]ll just get an image in a paragraph by itself,
-with no caption.
-.PP
-If you just want a regular inline image, just make sure it is not the
-only thing in the paragraph.
-One way to do this is to insert a nonbreaking space after the image:
-.IP
-.nf
-\f[C]
-![This\ image\ won\[aq]t\ be\ a\ figure](/url/of/image.png)\\\ 
-\f[]
-.fi
-.PP
-Note that in reveal.js slide shows, an image in a paragraph by itself
-that has the \f[C]stretch\f[] class will fill the screen, and the
-caption and figure tags will be omitted.
-.SS Extension: \f[C]link_attributes\f[]
-.PP
-Attributes can be set on links and images:
-.IP
-.nf
-\f[C]
-An\ inline\ ![image](foo.jpg){#id\ .class\ width=30\ height=20px}
-and\ a\ reference\ ![image][ref]\ with\ attributes.
-
-[ref]:\ foo.jpg\ "optional\ title"\ {#id\ .class\ key=val\ key2="val\ 2"}
-\f[]
-.fi
-.PP
-(This syntax is compatible with PHP Markdown Extra when only
-\f[C]#id\f[] and \f[C]\&.class\f[] are used.)
-.PP
-For HTML and EPUB, all attributes except \f[C]width\f[] and
-\f[C]height\f[] (but including \f[C]srcset\f[] and \f[C]sizes\f[]) are
-passed through as is.
-The other writers ignore attributes that are not supported by their
-output format.
-.PP
-The \f[C]width\f[] and \f[C]height\f[] attributes on images are treated
-specially.
-When used without a unit, the unit is assumed to be pixels.
-However, any of the following unit identifiers can be used: \f[C]px\f[],
-\f[C]cm\f[], \f[C]mm\f[], \f[C]in\f[], \f[C]inch\f[] and \f[C]%\f[].
-There must not be any spaces between the number and the unit.
-For example:
-.IP
-.nf
-\f[C]
-![](file.jpg){\ width=50%\ }
-\f[]
-.fi
-.IP \[bu] 2
-Dimensions are converted to inches for output in page\-based formats
-like LaTeX.
-Dimensions are converted to pixels for output in HTML\-like formats.
-Use the \f[C]\-\-dpi\f[] option to specify the number of pixels per
-inch.
-The default is 96dpi.
-.IP \[bu] 2
-The \f[C]%\f[] unit is generally relative to some available space.
-For example the above example will render to
-\f[C]<img\ href="file.jpg"\ style="width:\ 50%;"\ />\f[] (HTML),
-\f[C]\\includegraphics[width=0.5\\textwidth]{file.jpg}\f[] (LaTeX), or
-\f[C]\\externalfigure[file.jpg][width=0.5\\textwidth]\f[] (ConTeXt).
-.IP \[bu] 2
-Some output formats have a notion of a class (ConTeXt) or a unique
-identifier (LaTeX \f[C]\\caption\f[]), or both (HTML).
-.IP \[bu] 2
-When no \f[C]width\f[] or \f[C]height\f[] attributes are specified, the
-fallback is to look at the image resolution and the dpi metadata
-embedded in the image file.
-.SS Spans
-.SS Extension: \f[C]bracketed_spans\f[]
-.PP
-A bracketed sequence of inlines, as one would use to begin a link, will
-be treated as a span with attributes if it is followed immediately by
-attributes:
-.IP
-.nf
-\f[C]
-[This\ is\ *some\ text*]{.class\ key="val"}
-\f[]
-.fi
-.SS Footnotes
-.SS Extension: \f[C]footnotes\f[]
-.PP
-Pandoc\[aq]s Markdown allows footnotes, using the following syntax:
-.IP
-.nf
-\f[C]
-Here\ is\ a\ footnote\ reference,[^1]\ and\ another.[^longnote]
-
-[^1]:\ Here\ is\ the\ footnote.
-
-[^longnote]:\ Here\[aq]s\ one\ with\ multiple\ blocks.
-
-\ \ \ \ Subsequent\ paragraphs\ are\ indented\ to\ show\ that\ they
-belong\ to\ the\ previous\ footnote.
-
-\ \ \ \ \ \ \ \ {\ some.code\ }
-
-\ \ \ \ The\ whole\ paragraph\ can\ be\ indented,\ or\ just\ the\ first
-\ \ \ \ line.\ \ In\ this\ way,\ multi\-paragraph\ footnotes\ work\ like
-\ \ \ \ multi\-paragraph\ list\ items.
-
-This\ paragraph\ won\[aq]t\ be\ part\ of\ the\ note,\ because\ it
-isn\[aq]t\ indented.
-\f[]
-.fi
-.PP
-The identifiers in footnote references may not contain spaces, tabs, or
-newlines.
-These identifiers are used only to correlate the footnote reference with
-the note itself; in the output, footnotes will be numbered sequentially.
-.PP
-The footnotes themselves need not be placed at the end of the document.
-They may appear anywhere except inside other block elements (lists,
-block quotes, tables, etc.).
-Each footnote should be separated from surrounding content (including
-other footnotes) by blank lines.
-.SS Extension: \f[C]inline_notes\f[]
-.PP
-Inline footnotes are also allowed (though, unlike regular notes, they
-cannot contain multiple paragraphs).
-The syntax is as follows:
-.IP
-.nf
-\f[C]
-Here\ is\ an\ inline\ note.^[Inlines\ notes\ are\ easier\ to\ write,\ since
-you\ don\[aq]t\ have\ to\ pick\ an\ identifier\ and\ move\ down\ to\ type\ the
-note.]
-\f[]
-.fi
-.PP
-Inline and regular footnotes may be mixed freely.
-.SS Citations
-.SS Extension: \f[C]citations\f[]
-.PP
-Using an external filter, \f[C]pandoc\-citeproc\f[], pandoc can
-automatically generate citations and a bibliography in a number of
-styles.
-Basic usage is
-.IP
-.nf
-\f[C]
-pandoc\ \-\-filter\ pandoc\-citeproc\ myinput.txt
-\f[]
-.fi
-.PP
-In order to use this feature, you will need to specify a bibliography
-file using the \f[C]bibliography\f[] metadata field in a YAML metadata
-section, or \f[C]\-\-bibliography\f[] command line argument.
-You can supply multiple \f[C]\-\-bibliography\f[] arguments or set
-\f[C]bibliography\f[] metadata field to YAML array, if you want to use
-multiple bibliography files.
-The bibliography may have any of these formats:
-.PP
-.TS
-tab(@);
-l l.
-T{
-Format
-T}@T{
-File extension
-T}
-_
-T{
-BibLaTeX
-T}@T{
-\&.bib
-T}
-T{
-BibTeX
-T}@T{
-\&.bibtex
-T}
-T{
-Copac
-T}@T{
-\&.copac
-T}
-T{
-CSL JSON
-T}@T{
-\&.json
-T}
-T{
-CSL YAML
-T}@T{
-\&.yaml
-T}
-T{
-EndNote
-T}@T{
-\&.enl
-T}
-T{
-EndNote XML
-T}@T{
-\&.xml
-T}
-T{
-ISI
-T}@T{
-\&.wos
-T}
-T{
-MEDLINE
-T}@T{
-\&.medline
-T}
-T{
-MODS
-T}@T{
-\&.mods
-T}
-T{
-RIS
-T}@T{
-\&.ris
-T}
-.TE
-.PP
-Note that \f[C]\&.bib\f[] can be used with both BibTeX and BibLaTeX
-files; use \f[C]\&.bibtex\f[] to force BibTeX.
-.PP
-Note that \f[C]pandoc\-citeproc\ \-\-bib2json\f[] and
-\f[C]pandoc\-citeproc\ \-\-bib2yaml\f[] can produce \f[C]\&.json\f[] and
-\f[C]\&.yaml\f[] files from any of the supported formats.
-.PP
-In\-field markup: In BibTeX and BibLaTeX databases, pandoc\-citeproc
-parses a subset of LaTeX markup; in CSL YAML databases, pandoc Markdown;
-and in CSL JSON databases, an HTML\-like markup:
-.TP
-.B \f[C]<i>...</i>\f[]
-italics
-.RS
-.RE
-.TP
-.B \f[C]<b>...</b>\f[]
-bold
-.RS
-.RE
-.TP
-.B \f[C]<span\ style="font\-variant:small\-caps;">...</span>\f[] or \f[C]<sc>...</sc>\f[]
-small capitals
-.RS
-.RE
-.TP
-.B \f[C]<sub>...</sub>\f[]
-subscript
-.RS
-.RE
-.TP
-.B \f[C]<sup>...</sup>\f[]
-superscript
-.RS
-.RE
-.TP
-.B \f[C]<span\ class="nocase">...</span>\f[]
-prevent a phrase from being capitalized as title case
-.RS
-.RE
-.PP
-\f[C]pandoc\-citeproc\ \-j\f[] and \f[C]\-y\f[] interconvert the CSL
-JSON and CSL YAML formats as far as possible.
-.PP
-As an alternative to specifying a bibliography file using
-\f[C]\-\-bibliography\f[] or the YAML metadata field
-\f[C]bibliography\f[], you can include the citation data directly in the
-\f[C]references\f[] field of the document\[aq]s YAML metadata.
-The field should contain an array of YAML\-encoded references, for
-example:
-.IP
-.nf
-\f[C]
-\-\-\-
-references:
-\-\ type:\ article\-journal
-\ \ id:\ WatsonCrick1953
-\ \ author:
-\ \ \-\ family:\ Watson
-\ \ \ \ given:\ J.\ D.
-\ \ \-\ family:\ Crick
-\ \ \ \ given:\ F.\ H.\ C.
-\ \ issued:
-\ \ \ \ date\-parts:
-\ \ \ \ \-\ \-\ 1953
-\ \ \ \ \ \ \-\ 4
-\ \ \ \ \ \ \-\ 25
-\ \ title:\ \[aq]Molecular\ structure\ of\ nucleic\ acids:\ a\ structure\ for\ deoxyribose
-\ \ \ \ nucleic\ acid\[aq]
-\ \ title\-short:\ Molecular\ structure\ of\ nucleic\ acids
-\ \ container\-title:\ Nature
-\ \ volume:\ 171
-\ \ issue:\ 4356
-\ \ page:\ 737\-738
-\ \ DOI:\ 10.1038/171737a0
-\ \ URL:\ http://www.nature.com/nature/journal/v171/n4356/abs/171737a0.html
-\ \ language:\ en\-GB
-\&...
-\f[]
-.fi
-.PP
-(\f[C]pandoc\-citeproc\ \-\-bib2yaml\f[] can produce these from a
-bibliography file in one of the supported formats.)
-.PP
-Citations and references can be formatted using any style supported by
-the Citation Style Language, listed in the Zotero Style Repository.
-These files are specified using the \f[C]\-\-csl\f[] option or the
-\f[C]csl\f[] metadata field.
-By default, \f[C]pandoc\-citeproc\f[] will use the Chicago Manual of
-Style author\-date format.
-The CSL project provides further information on finding and editing
-styles.
-.PP
-To make your citations hyperlinks to the corresponding bibliography
-entries, add \f[C]link\-citations:\ true\f[] to your YAML metadata.
-.PP
-Citations go inside square brackets and are separated by semicolons.
-Each citation must have a key, composed of \[aq]\@\[aq] + the citation
-identifier from the database, and may optionally have a prefix, a
-locator, and a suffix.
-The citation key must begin with a letter, digit, or \f[C]_\f[], and may
-contain alphanumerics, \f[C]_\f[], and internal punctuation characters
-(\f[C]:.#$%&\-+?<>~/\f[]).
-Here are some examples:
-.IP
-.nf
-\f[C]
-Blah\ blah\ [see\ \@doe99,\ pp.\ 33\-35;\ also\ \@smith04,\ chap.\ 1].
-
-Blah\ blah\ [\@doe99,\ pp.\ 33\-35,\ 38\-39\ and\ *passim*].
-
-Blah\ blah\ [\@smith04;\ \@doe99].
-\f[]
-.fi
-.PP
-\f[C]pandoc\-citeproc\f[] detects locator terms in the CSL locale files.
-Either abbreviated or unabbreviated forms are accepted.
-In the \f[C]en\-US\f[] locale, locator terms can be written in either
-singular or plural forms, as \f[C]book\f[], \f[C]bk.\f[]/\f[C]bks.\f[];
-\f[C]chapter\f[], \f[C]chap.\f[]/\f[C]chaps.\f[]; \f[C]column\f[],
-\f[C]col.\f[]/\f[C]cols.\f[]; \f[C]figure\f[],
-\f[C]fig.\f[]/\f[C]figs.\f[]; \f[C]folio\f[],
-\f[C]fol.\f[]/\f[C]fols.\f[]; \f[C]number\f[],
-\f[C]no.\f[]/\f[C]nos.\f[]; \f[C]line\f[], \f[C]l.\f[]/\f[C]ll.\f[];
-\f[C]note\f[], \f[C]n.\f[]/\f[C]nn.\f[]; \f[C]opus\f[],
-\f[C]op.\f[]/\f[C]opp.\f[]; \f[C]page\f[], \f[C]p.\f[]/\f[C]pp.\f[];
-\f[C]paragraph\f[], \f[C]para.\f[]/\f[C]paras.\f[]; \f[C]part\f[],
-\f[C]pt.\f[]/\f[C]pts.\f[]; \f[C]section\f[],
-\f[C]sec.\f[]/\f[C]secs.\f[]; \f[C]sub\ verbo\f[],
-\f[C]s.v.\f[]/\f[C]s.vv.\f[]; \f[C]verse\f[], \f[C]v.\f[]/\f[C]vv.\f[];
-\f[C]volume\f[], \f[C]vol.\f[]/\f[C]vols.\f[]; \f[C]¶\f[]/\f[C]¶¶\f[];
-\f[C]§\f[]/\f[C]§§\f[].
-If no locator term is used, "page" is assumed.
-.PP
-A minus sign (\f[C]\-\f[]) before the \f[C]\@\f[] will suppress mention
-of the author in the citation.
-This can be useful when the author is already mentioned in the text:
-.IP
-.nf
-\f[C]
-Smith\ says\ blah\ [\-\@smith04].
-\f[]
-.fi
-.PP
-You can also write an in\-text citation, as follows:
-.IP
-.nf
-\f[C]
-\@smith04\ says\ blah.
-
-\@smith04\ [p.\ 33]\ says\ blah.
-\f[]
-.fi
-.PP
-If the style calls for a list of works cited, it will be placed at the
-end of the document.
-Normally, you will want to end your document with an appropriate header:
-.IP
-.nf
-\f[C]
-last\ paragraph...
-
-#\ References
-\f[]
-.fi
-.PP
-The bibliography will be inserted after this header.
-Note that the \f[C]unnumbered\f[] class will be added to this header, so
-that the section will not be numbered.
-.PP
-If you want to include items in the bibliography without actually citing
-them in the body text, you can define a dummy \f[C]nocite\f[] metadata
-field and put the citations there:
-.IP
-.nf
-\f[C]
-\-\-\-
-nocite:\ |
-\ \ \@item1,\ \@item2
-\&...
-
-\@item3
-\f[]
-.fi
-.PP
-In this example, the document will contain a citation for \f[C]item3\f[]
-only, but the bibliography will contain entries for \f[C]item1\f[],
-\f[C]item2\f[], and \f[C]item3\f[].
-.PP
-It is possible to create a bibliography with all the citations, whether
-or not they appear in the document, by using a wildcard:
-.IP
-.nf
-\f[C]
-\-\-\-
-nocite:\ |
-\ \ \@*
-\&...
-\f[]
-.fi
-.PP
-For LaTeX or PDF output, you can also use \f[C]natbib\f[] or
-\f[C]biblatex\f[] to render bibliography.
-In order to do so, specify bibliography files as outlined above, and add
-\f[C]\-\-natbib\f[] or \f[C]\-\-biblatex\f[] argument to \f[C]pandoc\f[]
-invocation.
-Bear in mind that bibliography files have to be in respective format
-(either BibTeX or BibLaTeX).
-.PP
-For more information, see the pandoc\-citeproc man page.
-.SS Non\-pandoc extensions
-.PP
-The following Markdown syntax extensions are not enabled by default in
-pandoc, but may be enabled by adding \f[C]+EXTENSION\f[] to the format
-name, where \f[C]EXTENSION\f[] is the name of the extension.
-Thus, for example, \f[C]markdown+hard_line_breaks\f[] is Markdown with
-hard line breaks.
-.SS Extension: \f[C]old_dashes\f[]
-.PP
-Selects the pandoc <= 1.8.2.1 behavior for parsing smart dashes:
-\f[C]\-\f[] before a numeral is an en\-dash, and \f[C]\-\-\f[] is an
-em\-dash.
-This option only has an effect if \f[C]smart\f[] is enabled.
-It is selected automatically for \f[C]textile\f[] input.
-.SS Extension: \f[C]angle_brackets_escapable\f[]
-.PP
-Allow \f[C]<\f[] and \f[C]>\f[] to be backslash\-escaped, as they can be
-in GitHub flavored Markdown but not original Markdown.
-This is implied by pandoc\[aq]s default \f[C]all_symbols_escapable\f[].
-.SS Extension: \f[C]lists_without_preceding_blankline\f[]
-.PP
-Allow a list to occur right after a paragraph, with no intervening blank
-space.
-.SS Extension: \f[C]four_space_rule\f[]
-.PP
-Selects the pandoc <= 2.0 behavior for parsing lists, so that four
-spaces indent are needed for list item continuation paragraphs.
-.SS Extension: \f[C]spaced_reference_links\f[]
-.PP
-Allow whitespace between the two components of a reference link, for
-example,
-.IP
-.nf
-\f[C]
-[foo]\ [bar].
-\f[]
-.fi
-.SS Extension: \f[C]hard_line_breaks\f[]
-.PP
-Causes all newlines within a paragraph to be interpreted as hard line
-breaks instead of spaces.
-.SS Extension: \f[C]ignore_line_breaks\f[]
-.PP
-Causes newlines within a paragraph to be ignored, rather than being
-treated as spaces or as hard line breaks.
-This option is intended for use with East Asian languages where spaces
-are not used between words, but text is divided into lines for
-readability.
-.SS Extension: \f[C]east_asian_line_breaks\f[]
-.PP
-Causes newlines within a paragraph to be ignored, rather than being
-treated as spaces or as hard line breaks, when they occur between two
-East Asian wide characters.
-This is a better choice than \f[C]ignore_line_breaks\f[] for texts that
-include a mix of East Asian wide characters and other characters.
-.SS Extension: \f[C]emoji\f[]
-.PP
-Parses textual emojis like \f[C]:smile:\f[] as Unicode emoticons.
-.SS Extension: \f[C]tex_math_single_backslash\f[]
-.PP
-Causes anything between \f[C]\\(\f[] and \f[C]\\)\f[] to be interpreted
-as inline TeX math, and anything between \f[C]\\[\f[] and \f[C]\\]\f[]
-to be interpreted as display TeX math.
-Note: a drawback of this extension is that it precludes escaping
-\f[C](\f[] and \f[C][\f[].
-.SS Extension: \f[C]tex_math_double_backslash\f[]
-.PP
-Causes anything between \f[C]\\\\(\f[] and \f[C]\\\\)\f[] to be
-interpreted as inline TeX math, and anything between \f[C]\\\\[\f[] and
-\f[C]\\\\]\f[] to be interpreted as display TeX math.
-.SS Extension: \f[C]markdown_attribute\f[]
-.PP
-By default, pandoc interprets material inside block\-level tags as
-Markdown.
-This extension changes the behavior so that Markdown is only parsed
-inside block\-level tags if the tags have the attribute
-\f[C]markdown=1\f[].
-.SS Extension: \f[C]mmd_title_block\f[]
-.PP
-Enables a MultiMarkdown style title block at the top of the document,
-for example:
-.IP
-.nf
-\f[C]
-Title:\ \ \ My\ title
-Author:\ \ John\ Doe
-Date:\ \ \ \ September\ 1,\ 2008
-Comment:\ This\ is\ a\ sample\ mmd\ title\ block,\ with
-\ \ \ \ \ \ \ \ \ a\ field\ spanning\ multiple\ lines.
-\f[]
-.fi
-.PP
-See the MultiMarkdown documentation for details.
-If \f[C]pandoc_title_block\f[] or \f[C]yaml_metadata_block\f[] is
-enabled, it will take precedence over \f[C]mmd_title_block\f[].
-.SS Extension: \f[C]abbreviations\f[]
-.PP
-Parses PHP Markdown Extra abbreviation keys, like
-.IP
-.nf
-\f[C]
-*[HTML]:\ Hypertext\ Markup\ Language
-\f[]
-.fi
-.PP
-Note that the pandoc document model does not support abbreviations, so
-if this extension is enabled, abbreviation keys are simply skipped (as
-opposed to being parsed as paragraphs).
-.SS Extension: \f[C]autolink_bare_uris\f[]
-.PP
-Makes all absolute URIs into links, even when not surrounded by pointy
-braces \f[C]<...>\f[].
-.SS Extension: \f[C]mmd_link_attributes\f[]
-.PP
-Parses multimarkdown style key\-value attributes on link and image
-references.
-This extension should not be confused with the \f[C]link_attributes\f[]
-extension.
-.IP
-.nf
-\f[C]
-This\ is\ a\ reference\ ![image][ref]\ with\ multimarkdown\ attributes.
-
-[ref]:\ http://path.to/image\ "Image\ title"\ width=20px\ height=30px
-\ \ \ \ \ \ \ id=myId\ class="myClass1\ myClass2"
-\f[]
-.fi
-.SS Extension: \f[C]mmd_header_identifiers\f[]
-.PP
-Parses multimarkdown style header identifiers (in square brackets, after
-the header but before any trailing \f[C]#\f[]s in an ATX header).
-.SS Extension: \f[C]compact_definition_lists\f[]
-.PP
-Activates the definition list syntax of pandoc 1.12.x and earlier.
-This syntax differs from the one described above under Definition lists
-in several respects:
-.IP \[bu] 2
-No blank line is required between consecutive items of the definition
-list.
-.IP \[bu] 2
-To get a "tight" or "compact" list, omit space between consecutive
-items; the space between a term and its definition does not affect
-anything.
-.IP \[bu] 2
-Lazy wrapping of paragraphs is not allowed: the entire definition must
-be indented four spaces.
-.SS Markdown variants
-.PP
-In addition to pandoc\[aq]s extended Markdown, the following Markdown
-variants are supported:
-.TP
-.B \f[C]markdown_phpextra\f[] (PHP Markdown Extra)
-\f[C]footnotes\f[], \f[C]pipe_tables\f[], \f[C]raw_html\f[],
-\f[C]markdown_attribute\f[], \f[C]fenced_code_blocks\f[],
-\f[C]definition_lists\f[], \f[C]intraword_underscores\f[],
-\f[C]header_attributes\f[], \f[C]link_attributes\f[],
-\f[C]abbreviations\f[], \f[C]shortcut_reference_links\f[],
-\f[C]spaced_reference_links\f[].
-.RS
-.RE
-.TP
-.B \f[C]markdown_github\f[] (deprecated GitHub\-Flavored Markdown)
-\f[C]pipe_tables\f[], \f[C]raw_html\f[], \f[C]fenced_code_blocks\f[],
-\f[C]gfm_auto_identifiers\f[], \f[C]ascii_identifiers\f[],
-\f[C]backtick_code_blocks\f[], \f[C]autolink_bare_uris\f[],
-\f[C]space_in_atx_header\f[], \f[C]intraword_underscores\f[],
-\f[C]strikeout\f[], \f[C]emoji\f[], \f[C]shortcut_reference_links\f[],
-\f[C]angle_brackets_escapable\f[],
-\f[C]lists_without_preceding_blankline\f[].
-.RS
-.RE
-.TP
-.B \f[C]markdown_mmd\f[] (MultiMarkdown)
-\f[C]pipe_tables\f[], \f[C]raw_html\f[], \f[C]markdown_attribute\f[],
-\f[C]mmd_link_attributes\f[], \f[C]tex_math_double_backslash\f[],
-\f[C]intraword_underscores\f[], \f[C]mmd_title_block\f[],
-\f[C]footnotes\f[], \f[C]definition_lists\f[],
-\f[C]all_symbols_escapable\f[], \f[C]implicit_header_references\f[],
-\f[C]auto_identifiers\f[], \f[C]mmd_header_identifiers\f[],
-\f[C]shortcut_reference_links\f[], \f[C]implicit_figures\f[],
-\f[C]superscript\f[], \f[C]subscript\f[], \f[C]backtick_code_blocks\f[],
-\f[C]spaced_reference_links\f[], \f[C]raw_attribute\f[].
-.RS
-.RE
-.TP
-.B \f[C]markdown_strict\f[] (Markdown.pl)
-\f[C]raw_html\f[], \f[C]shortcut_reference_links\f[],
-\f[C]spaced_reference_links\f[].
-.RS
-.RE
-.PP
-We also support \f[C]commonmark\f[] and \f[C]gfm\f[] (GitHub\-Flavored
-Markdown, which is implemented as a set of extensions on
-\f[C]commonmark\f[]).
-.PP
-Note, however, that \f[C]commonmark\f[] and \f[C]gfm\f[] have limited
-support for extensions.
-Only those listed below (and \f[C]smart\f[] and \f[C]raw_tex\f[]) will
-work.
-The extensions can, however, all be individually disabled.
-Also, \f[C]raw_tex\f[] only affects \f[C]gfm\f[] output, not input.
-.TP
-.B \f[C]gfm\f[] (GitHub\-Flavored Markdown)
-\f[C]pipe_tables\f[], \f[C]raw_html\f[], \f[C]fenced_code_blocks\f[],
-\f[C]auto_identifiers\f[], \f[C]ascii_identifiers\f[],
-\f[C]backtick_code_blocks\f[], \f[C]autolink_bare_uris\f[],
-\f[C]intraword_underscores\f[], \f[C]strikeout\f[],
-\f[C]hard_line_breaks\f[], \f[C]emoji\f[],
-\f[C]shortcut_reference_links\f[], \f[C]angle_brackets_escapable\f[].
-.RS
-.RE
-.SH PRODUCING SLIDE SHOWS WITH PANDOC
-.PP
-You can use pandoc to produce an HTML + JavaScript slide presentation
-that can be viewed via a web browser.
-There are five ways to do this, using S5, DZSlides, Slidy, Slideous, or
-reveal.js.
-You can also produce a PDF slide show using LaTeX \f[C]beamer\f[], or
-slides shows in Microsoft PowerPoint format.
-.PP
-Here\[aq]s the Markdown source for a simple slide show,
-\f[C]habits.txt\f[]:
-.IP
-.nf
-\f[C]
-%\ Habits
-%\ John\ Doe
-%\ March\ 22,\ 2005
-
-#\ In\ the\ morning
-
-##\ Getting\ up
-
-\-\ Turn\ off\ alarm
-\-\ Get\ out\ of\ bed
-
-##\ Breakfast
-
-\-\ Eat\ eggs
-\-\ Drink\ coffee
-
-#\ In\ the\ evening
-
-##\ Dinner
-
-\-\ Eat\ spaghetti
-\-\ Drink\ wine
-
-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-
-
-![picture\ of\ spaghetti](images/spaghetti.jpg)
-
-##\ Going\ to\ sleep
-
-\-\ Get\ in\ bed
-\-\ Count\ sheep
-\f[]
-.fi
-.PP
-To produce an HTML/JavaScript slide show, simply type
-.IP
-.nf
-\f[C]
-pandoc\ \-t\ FORMAT\ \-s\ habits.txt\ \-o\ habits.html
-\f[]
-.fi
-.PP
-where \f[C]FORMAT\f[] is either \f[C]s5\f[], \f[C]slidy\f[],
-\f[C]slideous\f[], \f[C]dzslides\f[], or \f[C]revealjs\f[].
-.PP
-For Slidy, Slideous, reveal.js, and S5, the file produced by pandoc with
-the \f[C]\-s/\-\-standalone\f[] option embeds a link to JavaScript and
-CSS files, which are assumed to be available at the relative path
-\f[C]s5/default\f[] (for S5), \f[C]slideous\f[] (for Slideous),
-\f[C]reveal.js\f[] (for reveal.js), or at the Slidy website at
-\f[C]w3.org\f[] (for Slidy).
-(These paths can be changed by setting the \f[C]slidy\-url\f[],
-\f[C]slideous\-url\f[], \f[C]revealjs\-url\f[], or \f[C]s5\-url\f[]
-variables; see Variables for slides, above.) For DZSlides, the
-(relatively short) JavaScript and CSS are included in the file by
-default.
-.PP
-With all HTML slide formats, the \f[C]\-\-self\-contained\f[] option can
-be used to produce a single file that contains all of the data necessary
-to display the slide show, including linked scripts, stylesheets,
-images, and videos.
-.PP
-To produce a PDF slide show using beamer, type
-.IP
-.nf
-\f[C]
-pandoc\ \-t\ beamer\ habits.txt\ \-o\ habits.pdf
-\f[]
-.fi
-.PP
-Note that a reveal.js slide show can also be converted to a PDF by
-printing it to a file from the browser.
-.PP
-To produce a Powerpoint slide show, type
-.IP
-.nf
-\f[C]
-pandoc\ habits.txt\ \-o\ habits.pptx
-\f[]
-.fi
-.SS Structuring the slide show
-.PP
-By default, the \f[I]slide level\f[] is the highest header level in the
-hierarchy that is followed immediately by content, and not another
-header, somewhere in the document.
-In the example above, level 1 headers are always followed by level 2
-headers, which are followed by content, so 2 is the slide level.
-This default can be overridden using the \f[C]\-\-slide\-level\f[]
-option.
-.PP
-The document is carved up into slides according to the following rules:
-.IP \[bu] 2
-A horizontal rule always starts a new slide.
-.IP \[bu] 2
-A header at the slide level always starts a new slide.
-.IP \[bu] 2
-Headers \f[I]below\f[] the slide level in the hierarchy create headers
-\f[I]within\f[] a slide.
-.IP \[bu] 2
-Headers \f[I]above\f[] the slide level in the hierarchy create "title
-slides," which just contain the section title and help to break the
-slide show into sections.
-.IP \[bu] 2
-Content \f[I]above\f[] the slide level will not appear in the slide
-show.
-.IP \[bu] 2
-A title page is constructed automatically from the document\[aq]s title
-block, if present.
-(In the case of beamer, this can be disabled by commenting out some
-lines in the default template.)
-.PP
-These rules are designed to support many different styles of slide show.
-If you don\[aq]t care about structuring your slides into sections and
-subsections, you can just use level 1 headers for all each slide.
-(In that case, level 1 will be the slide level.) But you can also
-structure the slide show into sections, as in the example above.
-.PP
-Note: in reveal.js slide shows, if slide level is 2, a two\-dimensional
-layout will be produced, with level 1 headers building horizontally and
-level 2 headers building vertically.
-It is not recommended that you use deeper nesting of section levels with
-reveal.js.
-.SS Incremental lists
-.PP
-By default, these writers produce lists that display "all at once." If
-you want your lists to display incrementally (one item at a time), use
-the \f[C]\-i\f[] option.
-If you want a particular list to depart from the default (that is, to
-display incrementally without the \f[C]\-i\f[] option and all at once
-with the \f[C]\-i\f[] option), put it in a block quote:
-.IP
-.nf
-\f[C]
->\ \-\ Eat\ spaghetti
->\ \-\ Drink\ wine
-\f[]
-.fi
-.PP
-In this way incremental and nonincremental lists can be mixed in a
-single document.
-.SS Inserting pauses
-.PP
-You can add "pauses" within a slide by including a paragraph containing
-three dots, separated by spaces:
-.IP
-.nf
-\f[C]
-#\ Slide\ with\ a\ pause
-
-content\ before\ the\ pause
-
-\&.\ .\ .
-
-content\ after\ the\ pause
-\f[]
-.fi
-.SS Styling the slides
-.PP
-You can change the style of HTML slides by putting customized CSS files
-in \f[C]$DATADIR/s5/default\f[] (for S5), \f[C]$DATADIR/slidy\f[] (for
-Slidy), or \f[C]$DATADIR/slideous\f[] (for Slideous), where
-\f[C]$DATADIR\f[] is the user data directory (see
-\f[C]\-\-data\-dir\f[], above).
-The originals may be found in pandoc\[aq]s system data directory
-(generally \f[C]$CABALDIR/pandoc\-VERSION/s5/default\f[]).
-Pandoc will look there for any files it does not find in the user data
-directory.
-.PP
-For dzslides, the CSS is included in the HTML file itself, and may be
-modified there.
-.PP
-All reveal.js configuration options can be set through variables.
-For example, themes can be used by setting the \f[C]theme\f[] variable:
-.IP
-.nf
-\f[C]
-\-V\ theme=moon
-\f[]
-.fi
-.PP
-Or you can specify a custom stylesheet using the \f[C]\-\-css\f[]
-option.
-.PP
-To style beamer slides, you can specify a \f[C]theme\f[],
-\f[C]colortheme\f[], \f[C]fonttheme\f[], \f[C]innertheme\f[], and
-\f[C]outertheme\f[], using the \f[C]\-V\f[] option:
-.IP
-.nf
-\f[C]
-pandoc\ \-t\ beamer\ habits.txt\ \-V\ theme:Warsaw\ \-o\ habits.pdf
-\f[]
-.fi
-.PP
-Note that header attributes will turn into slide attributes (on a
-\f[C]<div>\f[] or \f[C]<section>\f[]) in HTML slide formats, allowing
-you to style individual slides.
-In beamer, the only header attribute that affects slides is the
-\f[C]allowframebreaks\f[] class, which sets the
-\f[C]allowframebreaks\f[] option, causing multiple slides to be created
-if the content overfills the frame.
-This is recommended especially for bibliographies:
-.IP
-.nf
-\f[C]
-#\ References\ {.allowframebreaks}
-\f[]
-.fi
-.SS Speaker notes
-.PP
-reveal.js has good support for speaker notes.
-You can add notes to your Markdown document thus:
-.IP
-.nf
-\f[C]
-:::\ notes
-
-This\ is\ my\ note.
-
-\-\ It\ can\ contain\ Markdown
-\-\ like\ this\ list
-
-:::
-\f[]
-.fi
-.PP
-To show the notes window, press \f[C]s\f[] while viewing the
-presentation.
-Notes are not yet supported for other slide formats, but the notes will
-not appear on the slides themselves.
-.SS Columns
-.PP
-To put material in side by side columns, you can use a native div
-container with class \f[C]columns\f[], containing two or more div
-containers with class \f[C]column\f[] and a \f[C]width\f[] attribute:
-.IP
-.nf
-\f[C]
-::::::::::::::\ {.columns}
-:::\ {.column\ width="40%"}
-contents...
-:::
-:::\ {.column\ width="60%"}
-contents...
-:::
-::::::::::::::
-\f[]
-.fi
-.SS Frame attributes in beamer
-.PP
-Sometimes it is necessary to add the LaTeX \f[C][fragile]\f[] option to
-a frame in beamer (for example, when using the \f[C]minted\f[]
-environment).
-This can be forced by adding the \f[C]fragile\f[] class to the header
-introducing the slide:
-.IP
-.nf
-\f[C]
-#\ Fragile\ slide\ {.fragile}
-\f[]
-.fi
-.PP
-All of the other frame attributes described in Section 8.1 of the Beamer
-User\[aq]s Guide may also be used: \f[C]allowdisplaybreaks\f[],
-\f[C]allowframebreaks\f[], \f[C]b\f[], \f[C]c\f[], \f[C]t\f[],
-\f[C]environment\f[], \f[C]label\f[], \f[C]plain\f[], \f[C]shrink\f[].
-.SH CREATING EPUBS WITH PANDOC
-.SS EPUB Metadata
-.PP
-EPUB metadata may be specified using the \f[C]\-\-epub\-metadata\f[]
-option, but if the source document is Markdown, it is better to use a
-YAML metadata block.
-Here is an example:
-.IP
-.nf
-\f[C]
-\-\-\-
-title:
-\-\ type:\ main
-\ \ text:\ My\ Book
-\-\ type:\ subtitle
-\ \ text:\ An\ investigation\ of\ metadata
-creator:
-\-\ role:\ author
-\ \ text:\ John\ Smith
-\-\ role:\ editor
-\ \ text:\ Sarah\ Jones
-identifier:
-\-\ scheme:\ DOI
-\ \ text:\ doi:10.234234.234/33
-publisher:\ \ My\ Press
-rights:\ ©\ 2007\ John\ Smith,\ CC\ BY\-NC
-ibooks:
-\ \ version:\ 1.3.4
-\&...
-\f[]
-.fi
-.PP
-The following fields are recognized:
-.TP
-.B \f[C]identifier\f[]
-Either a string value or an object with fields \f[C]text\f[] and
-\f[C]scheme\f[].
-Valid values for \f[C]scheme\f[] are \f[C]ISBN\-10\f[],
-\f[C]GTIN\-13\f[], \f[C]UPC\f[], \f[C]ISMN\-10\f[], \f[C]DOI\f[],
-\f[C]LCCN\f[], \f[C]GTIN\-14\f[], \f[C]ISBN\-13\f[],
-\f[C]Legal\ deposit\ number\f[], \f[C]URN\f[], \f[C]OCLC\f[],
-\f[C]ISMN\-13\f[], \f[C]ISBN\-A\f[], \f[C]JP\f[], \f[C]OLCC\f[].
-.RS
-.RE
-.TP
-.B \f[C]title\f[]
-Either a string value, or an object with fields \f[C]file\-as\f[] and
-\f[C]type\f[], or a list of such objects.
-Valid values for \f[C]type\f[] are \f[C]main\f[], \f[C]subtitle\f[],
-\f[C]short\f[], \f[C]collection\f[], \f[C]edition\f[],
-\f[C]extended\f[].
-.RS
-.RE
-.TP
-.B \f[C]creator\f[]
-Either a string value, or an object with fields \f[C]role\f[],
-\f[C]file\-as\f[], and \f[C]text\f[], or a list of such objects.
-Valid values for \f[C]role\f[] are MARC relators, but pandoc will
-attempt to translate the human\-readable versions (like "author" and
-"editor") to the appropriate marc relators.
-.RS
-.RE
-.TP
-.B \f[C]contributor\f[]
-Same format as \f[C]creator\f[].
-.RS
-.RE
-.TP
-.B \f[C]date\f[]
-A string value in \f[C]YYYY\-MM\-DD\f[] format.
-(Only the year is necessary.) Pandoc will attempt to convert other
-common date formats.
-.RS
-.RE
-.TP
-.B \f[C]lang\f[] (or legacy: \f[C]language\f[])
-A string value in BCP 47 format.
-Pandoc will default to the local language if nothing is specified.
-.RS
-.RE
-.TP
-.B \f[C]subject\f[]
-A string value or a list of such values.
-.RS
-.RE
-.TP
-.B \f[C]description\f[]
-A string value.
-.RS
-.RE
-.TP
-.B \f[C]type\f[]
-A string value.
-.RS
-.RE
-.TP
-.B \f[C]format\f[]
-A string value.
-.RS
-.RE
-.TP
-.B \f[C]relation\f[]
-A string value.
-.RS
-.RE
-.TP
-.B \f[C]coverage\f[]
-A string value.
-.RS
-.RE
-.TP
-.B \f[C]rights\f[]
-A string value.
-.RS
-.RE
-.TP
-.B \f[C]cover\-image\f[]
-A string value (path to cover image).
-.RS
-.RE
-.TP
-.B \f[C]stylesheet\f[]
-A string value (path to CSS stylesheet).
-.RS
-.RE
-.TP
-.B \f[C]page\-progression\-direction\f[]
-Either \f[C]ltr\f[] or \f[C]rtl\f[].
-Specifies the \f[C]page\-progression\-direction\f[] attribute for the
-\f[C]spine\f[] element.
-.RS
-.RE
-.TP
-.B \f[C]ibooks\f[]
-iBooks\-specific metadata, with the following fields:
-.RS
-.IP \[bu] 2
-\f[C]version\f[]: (string)
-.IP \[bu] 2
-\f[C]specified\-fonts\f[]: \f[C]true\f[]|\f[C]false\f[] (default
-\f[C]false\f[])
-.IP \[bu] 2
-\f[C]ipad\-orientation\-lock\f[]:
-\f[C]portrait\-only\f[]|\f[C]landscape\-only\f[]
-.IP \[bu] 2
-\f[C]iphone\-orientation\-lock\f[]:
-\f[C]portrait\-only\f[]|\f[C]landscape\-only\f[]
-.IP \[bu] 2
-\f[C]binding\f[]: \f[C]true\f[]|\f[C]false\f[] (default \f[C]true\f[])
-.IP \[bu] 2
-\f[C]scroll\-axis\f[]:
-\f[C]vertical\f[]|\f[C]horizontal\f[]|\f[C]default\f[]
-.RE
-.SS Linked media
-.PP
-By default, pandoc will download linked media (including audio and
-video) and include it in the EPUB container, yielding a completely
-self\-contained EPUB.
-If you want to link to external media resources instead, use raw HTML in
-your source and add \f[C]data\-external="1"\f[] to the tag with the
-\f[C]src\f[] attribute.
-For example:
-.IP
-.nf
-\f[C]
-<audio\ controls="1">
-\ \ <source\ src="http://example.com/music/toccata.mp3"
-\ \ \ \ \ \ \ \ \ \ data\-external="1"\ type="audio/mpeg">
-\ \ </source>
-</audio>
-\f[]
-.fi
-.SH SYNTAX HIGHLIGHTING
-.PP
-Pandoc will automatically highlight syntax in fenced code blocks that
-are marked with a language name.
-The Haskell library skylighting is used for highlighting, which works in
-HTML, Docx, Ms, and LaTeX/PDF output.
-To see a list of language names that pandoc will recognize, type
-\f[C]pandoc\ \-\-list\-highlight\-languages\f[].
-.PP
-The color scheme can be selected using the \f[C]\-\-highlight\-style\f[]
-option.
-The default color scheme is \f[C]pygments\f[], which imitates the
-default color scheme used by the Python library pygments (though
-pygments is not actually used to do the highlighting).
-To see a list of highlight styles, type
-\f[C]pandoc\ \-\-list\-highlight\-styles\f[].
-.PP
-To disable highlighting, use the \f[C]\-\-no\-highlight\f[] option.
-.SH CUSTOM STYLES IN DOCX OUTPUT
-.PP
-By default, pandoc\[aq]s docx 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[] 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[]s and \f[C]span\f[]s, respectively.
-.PP
-If you define a \f[C]div\f[] or \f[C]span\f[] with the attribute
-\f[C]custom\-style\f[], pandoc will apply your specified style to the
-contained elements.
-So, for example using the \f[C]bracketed_spans\f[] syntax,
-.IP
-.nf
-\f[C]
-[Get\ out]{custom\-style="Emphatically"},\ he\ said.
-\f[]
-.fi
-.PP
-would produce a docx file with "Get out" styled with character style
-\f[C]Emphatically\f[].
-Similarly, using the \f[C]fenced_divs\f[] syntax,
-.IP
-.nf
-\f[C]
-Dickinson\ starts\ the\ poem\ simply:
-
-:::\ {custom\-style="Poetry"}
-|\ A\ Bird\ came\ down\ the\ Walk\-\-\-
-|\ He\ did\ not\ know\ I\ saw\-\-\-
-:::
-\f[]
-.fi
-.PP
-would style the two contained lines with the \f[C]Poetry\f[] paragraph
-style.
-.PP
-If the styles are not yet in your reference.docx, they will be defined
-in the output file as inheriting from normal text.
-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[]
-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[] custom\-style \f[C]span\f[].
-.SH CUSTOM WRITERS
-.PP
-Pandoc can be extended with custom writers written in lua.
-(Pandoc includes a lua interpreter, so lua need not be installed
-separately.)
-.PP
-To use a custom writer, simply specify the path to the lua script in
-place of the output format.
-For example:
-.IP
-.nf
-\f[C]
-pandoc\ \-t\ data/sample.lua
-\f[]
-.fi
-.PP
-Creating a custom writer requires writing a lua function for each
-possible element in a pandoc document.
-To get a documented example which you can modify according to your
-needs, do
-.IP
-.nf
-\f[C]
-pandoc\ \-\-print\-default\-data\-file\ sample.lua
-\f[]
-.fi
-.SH AUTHORS
-.PP
-Copyright 2006\-2017 John MacFarlane (jgm\@berkeley.edu).
-Released under the GPL, version 2 or greater.
-This software carries no warranty of any kind.
-(See COPYRIGHT for full copyright and warranty notices.) For a full list
-of contributors, see the file AUTHORS.md in the pandoc source code.
-.PP
-The Pandoc source code and all documentation may be downloaded
-from <http://pandoc.org>.
diff --git a/man/pandoc.1.template b/man/pandoc.1.template
deleted file mode 100644
--- a/man/pandoc.1.template
+++ /dev/null
@@ -1,10 +0,0 @@
-$if(has-tables)$
-.\"t
-$endif$
-.TH PANDOC 1 "$date$" "$version$"
-.SH NAME
-pandoc - general markup converter
-$body$
-.PP
-The Pandoc source code and all documentation may be downloaded
-from <http://pandoc.org>.
diff --git a/pandoc.cabal b/pandoc.cabal
--- a/pandoc.cabal
+++ b/pandoc.cabal
@@ -1,55 +1,78 @@
+cabal-version:   2.4
 name:            pandoc
-version:         2.0.6
-cabal-version:   >= 1.10
-build-type:      Custom
-license:         GPL
+version:         3.10
+build-type:      Simple
+license:         GPL-2.0-or-later
 license-file:    COPYING.md
-copyright:       (c) 2006-2017 John MacFarlane
+copyright:       (c) 2006-2024 John MacFarlane
 author:          John MacFarlane <jgm@berkeley.edu>
 maintainer:      John MacFarlane <jgm@berkeley.edu>
 bug-reports:     https://github.com/jgm/pandoc/issues
 stability:       alpha
-homepage:        http://pandoc.org
+homepage:        https://pandoc.org
 category:        Text
-tested-with:     GHC == 7.8.4, GHC == 7.10.3, GHC == 8.0.2, GHC == 8.2.2
+tested-with:     GHC == 9.6.7, GHC == 9.8.4, GHC == 9.10.3, GHC == 9.12.2
 synopsis:        Conversion between markup formats
 description:     Pandoc is a Haskell library for converting from one markup
-                 format to another, and a command-line tool that uses
-                 this library. It can read several dialects of Markdown and
-                 (subsets of) HTML, reStructuredText, LaTeX, DocBook, JATS,
-                 MediaWiki markup, TWiki markup, TikiWiki markup, Creole 1.0,
-                 Haddock markup, OPML, Emacs Org-Mode, Emacs Muse, txt2tags,
-                 Vimwiki, Word Docx, ODT, and Textile, and it can write
-                 Markdown, reStructuredText, XHTML, HTML 5, LaTeX, ConTeXt,
-                 DocBook, JATS, OPML, TEI, OpenDocument, ODT, Word docx,
-                 RTF, MediaWiki, DokuWiki, ZimWiki, Textile, groff man,
-                 groff ms, plain text, Emacs Org-Mode, AsciiDoc,
-                 Haddock markup, EPUB (v2 and v3), FictionBook2, InDesign
-                 ICML, Muse, LaTeX beamer slides, PowerPoint, and several
-                 kinds of HTML/JavaScript slide shows (S5, Slidy, Slideous,
-                 DZSlides, reveal.js).
+                 format to another.  The formats it can handle include
                  .
-                 In contrast to most existing tools for converting Markdown
-                 to HTML, pandoc has a modular design: it consists of a set of
-                 readers, which parse text in a given format and produce a
-                 native representation of the document, and a set of writers,
-                 which convert this native representation into a target
-                 format. Thus, adding an input or output format requires
-                 only adding a reader or writer.
+                 - light markup formats (many variants of Markdown,
+                   reStructuredText, AsciiDoc, Org-mode, Muse, Textile,
+                   txt2tags, djot)
+                 - HTML formats (HTML 4 and 5)
+                 - Ebook formats (EPUB v2 and v3, FB2)
+                 - Documentation formats (GNU TexInfo, Haddock, Vimdoc)
+                 - Roff formats (man, ms)
+                 - TeX formats (LaTeX, ConTeXt)
+                 - Typst
+                 - XML formats (DocBook 4 and 5, JATS, TEI Simple, OpenDocument)
+                 - Outline formats (OPML)
+                 - Bibliography formats (BibTeX, BibLaTeX, CSL JSON, CSL YAML,
+                   RIS)
+                 - Word processor formats (Docx, RTF, ODT)
+                 - Interactive notebook formats (Jupyter notebook ipynb)
+                 - Page layout formats (InDesign ICML)
+                 - Wiki markup formats (MediaWiki, DokuWiki, TikiWiki, TWiki,
+                   Vimwiki, XWiki, ZimWiki, Jira wiki, Creole)
+                 - Slide show formats (LaTeX Beamer, PowerPoint, Slidy,
+                   reveal.js, Slideous, S5, DZSlides)
+                 - Data formats (CSV and TSV tables, Excel spreadsheets)
+                 - PDF (via external programs such as pdflatex or wkhtmltopdf)
+                 .
+                 Pandoc can convert mathematical content in documents
+                 between TeX, MathML, Word equations, roff eqn, typst,
+                 and plain text. It includes a powerful system for automatic
+                 citations and bibliographies, and it can be customized
+                 extensively using templates, filters, and custom readers
+                 and writers written in Lua.
+                 .
+                 For the pandoc command-line program, see the
+                 @pandoc-cli@ package.
 data-files:
                  -- templates
+                 data/templates/styles.html
+                 data/templates/styles.citations.html
                  data/templates/default.html4
                  data/templates/default.html5
+                 data/templates/default.chunkedhtml
+                 data/templates/default.djot
                  data/templates/default.docbook4
                  data/templates/default.docbook5
-                 data/templates/default.jats
+                 data/templates/default.jats_archiving
+                 data/templates/default.jats_articleauthoring
+                 data/templates/default.jats_publishing
                  data/templates/default.tei
                  data/templates/default.opendocument
+                 data/templates/default.openxml
                  data/templates/default.icml
                  data/templates/default.opml
+                 data/templates/default.beamer
                  data/templates/default.latex
+                 data/templates/default.bibtex
+                 data/templates/default.biblatex
                  data/templates/default.context
                  data/templates/default.texinfo
+                 data/templates/default.jira
                  data/templates/default.man
                  data/templates/default.ms
                  data/templates/default.markdown
@@ -59,6 +82,7 @@
                  data/templates/default.plain
                  data/templates/default.mediawiki
                  data/templates/default.dokuwiki
+                 data/templates/default.xwiki
                  data/templates/default.zimwiki
                  data/templates/default.rtf
                  data/templates/default.s5
@@ -72,13 +96,32 @@
                  data/templates/default.org
                  data/templates/default.epub2
                  data/templates/default.epub3
+                 data/templates/default.ansi
+                 data/templates/article.jats_publishing
+                 data/templates/affiliations.jats
+                 data/templates/default.markua
+                 data/templates/default.typst
+                 data/templates/document-metadata.latex
+                 data/templates/template.typst
+                 data/templates/common.latex
+                 data/templates/hypersetup.latex
+                 data/templates/passoptions.latex
+                 data/templates/fonts.latex
+                 data/templates/font-settings.latex
+                 data/templates/after-header-includes.latex
+                 data/templates/default.vimdoc
+                 data/templates/default.bbcode
+
                  -- translations
                  data/translations/*.yaml
+                 -- entities
+                 data/docbook-entities.txt
                  -- source files for reference.docx
                  data/docx/[Content_Types].xml
                  data/docx/_rels/.rels
                  data/docx/docProps/app.xml
                  data/docx/docProps/core.xml
+                 data/docx/docProps/custom.xml
                  data/docx/word/document.xml
                  data/docx/word/fontTable.xml
                  data/docx/word/comments.xml
@@ -96,13 +139,9 @@
                  data/odt/styles.xml
                  data/odt/content.xml
                  data/odt/meta.xml
-                 data/odt/settings.xml
-                 data/odt/Configurations2/accelerator/current.xml
-                 data/odt/Thumbnails/thumbnail.png
                  data/odt/META-INF/manifest.xml
                  -- source files for reference.pptx
                  data/pptx/_rels/.rels
-                 data/pptx/docProps/thumbnail.jpeg
                  data/pptx/docProps/app.xml
                  data/pptx/docProps/core.xml
                  data/pptx/ppt/slideLayouts/_rels/slideLayout1.xml.rels
@@ -134,75 +173,134 @@
                  data/pptx/ppt/slides/_rels/slide2.xml.rels
                  data/pptx/ppt/slides/slide2.xml
                  data/pptx/ppt/slides/slide1.xml
+                 data/pptx/ppt/slides/_rels/slide3.xml.rels
+                 data/pptx/ppt/slides/_rels/slide4.xml.rels
+                 data/pptx/ppt/slides/slide3.xml
+                 data/pptx/ppt/slides/slide4.xml
                  data/pptx/ppt/viewProps.xml
                  data/pptx/ppt/tableStyles.xml
                  data/pptx/ppt/slideMasters/_rels/slideMaster1.xml.rels
                  data/pptx/ppt/slideMasters/slideMaster1.xml
                  data/pptx/ppt/presentation.xml
+                 data/pptx/ppt/notesMasters/_rels/notesMaster1.xml.rels
+                 data/pptx/ppt/notesMasters/notesMaster1.xml
+                 data/pptx/ppt/notesSlides/_rels/notesSlide1.xml.rels
+                 data/pptx/ppt/notesSlides/notesSlide1.xml
+                 data/pptx/ppt/notesSlides/_rels/notesSlide2.xml.rels
+                 data/pptx/ppt/notesSlides/notesSlide2.xml
+                 data/pptx/ppt/theme/theme2.xml
                  data/pptx/[Content_Types].xml
                   -- stylesheet for EPUB writer
                  data/epub.css
-                 -- data for LaTeXMathML writer
-                 data/LaTeXMathML.js
                  -- data for dzslides writer
                  data/dzslides/template.html
                  -- default abbreviations file
                  data/abbreviations
-                 -- sample lua custom writer
-                 data/sample.lua
+                 -- sample lua custom reader
+                 data/creole.lua
                  -- lua init script
                  data/init.lua
-                 -- pandoc lua module
-                 data/pandoc.lua
-                 -- lua List module
-                 data/pandoc.List.lua
                  -- bash completion template
                  data/bash_completion.tpl
-                 -- jats csl
-                 data/jats.csl
+                 -- citeproc
+                 data/default.csl
+                 citeproc/biblatex-localization/*.lbx.strings
                  -- documentation
                  MANUAL.txt, COPYRIGHT
+extra-doc-files: changelog.md,
+                 AUTHORS.md,
+                 INSTALL.md,
+                 README.md,
+                 CONTRIBUTING.md,
+                 BUGS
 extra-source-files:
-                 -- documentation
-                 INSTALL.md, AUTHORS.md, README.md,
-                 CONTRIBUTING.md, BUGS, changelog,
-                 man/pandoc.1
-                 -- stack build plan
-                 stack.yaml
-                 -- files needed to build man page
-                 man/manfilter.lua
-                 man/pandoc.1.template
-                 -- trypandoc
-                 trypandoc/Makefile
-                 trypandoc/index.html
                  -- tests
                  test/bodybg.gif
                  test/*.native
                  test/command/*.md
+                 test/command/*.csl
+                 test/command/*.svg
+                 test/command/7691.docx
+                 test/command/9391.docx
+                 test/command/9358.docx
+                 test/command/9002.docx
+                 test/command/9603.docx
+                 test/command/11113.docx
+                 test/command/biblio.bib
+                 test/command/averroes.bib
+                 test/command/A.txt
+                 test/command/B.txt
+                 test/command/C.txt
+                 test/command/D.txt
+                 test/command/file1.txt
+                 test/command/file2.txt
+                 test/command/three.txt
+                 test/command/11090/ch1.typ
+                 test/command/01.csv
+                 test/command/chap1/spider.png
+                 test/command/chap2/spider.png
+                 test/command/chap1/text.md
+                 test/command/chap2/text.md
+                 test/command/defaults1.yaml
+                 test/command/defaults2.yaml
+                 test/command/defaults3.yaml
+                 test/command/defaults4.yaml
+                 test/command/defaults5.yaml
+                 test/command/defaults6.yaml
+                 test/command/defaults7.yaml
+                 test/command/defaults8.yaml
+                 test/command/defaults9.yaml
+                 test/command/8024a.yaml
+                 test/command/8024b.yaml
                  test/command/3533-rst-csv-tables.csv
                  test/command/3880.txt
+                 test/command/5182.txt
+                 test/command/5700-metadata-file-1.yml
+                 test/command/5700-metadata-file-2.yml
                  test/command/abbrevs
-                 test/command/SVG_logo-without-xml-declaration.svg
-                 test/command/SVG_logo.svg
-                 test/command/corrupt.svg
-                 test/command/inkscape-cube.svg
                  test/command/sub-file-chapter-1.tex
                  test/command/sub-file-chapter-2.tex
+                 test/command/bar.tex
+                 test/command/bar-endinput.tex
+                 test/command/yaml-metadata.yaml
+                 test/command/7813-meta.yaml
                  test/command/3510-subdoc.org
                  test/command/3510-export.latex
                  test/command/3510-src.hs
                  test/command/3971b.tex
+                 test/command/5876.yaml
+                 test/command/5876/metadata/5876.yaml
+                 test/command/5876/metadata/command/5876.yaml
+                 test/command/6466-beg.hs
+                 test/command/6466-end.hs
+                 test/command/6466-mid.hs
+                 test/command/6466-whole.hs
+                 test/command/7861.yaml
+                 test/command/7861/metadata/placeholder
+                 test/command/11486/scroll.revealjs
+                 test/command/11498.png
+                 test/asciidoc-reader.adoc
+                 test/asciidoc-reader.native
+                 test/asciidoc-reader-include.rb
+                 test/asciidoc-reader-include.adoc
+                 test/docbook-chapter.docbook
                  test/docbook-reader.docbook
                  test/docbook-xref.docbook
+                 test/endnotexml-reader.xml
                  test/html-reader.html
                  test/opml-reader.opml
+                 test/org-select-tags.org
                  test/haddock-reader.haddock
                  test/insert
                  test/lalune.jpg
+                 test/man-reader.man
                  test/movie.jpg
                  test/media/rId25.jpg
                  test/media/rId26.jpg
                  test/media/rId27.jpg
+                 test/typst-reader.typ
+                 test/undergradmath.typ
+                 test/djot-reader.djot
                  test/latex-reader.latex
                  test/textile-reader.textile
                  test/markdown-reader-more.txt
@@ -211,9 +309,9 @@
                  test/mediawiki-reader.wiki
                  test/vimwiki-reader.wiki
                  test/creole-reader.txt
-                 test/creole-reader.native
                  test/rst-reader.rst
                  test/jats-reader.xml
+                 test/jira-reader.jira
                  test/s5-basic.html
                  test/s5-fancy.html
                  test/s5-fragment.html
@@ -221,7 +319,11 @@
                  test/tables.context
                  test/tables.docbook4
                  test/tables.docbook5
-                 test/tables.jats
+                 test/tables.jats_archiving
+                 test/tables.jats_articleauthoring
+                 test/tables.jats_publishing
+                 test/tables.jira
+                 test/tables.djot
                  test/tables.dokuwiki
                  test/tables.zimwiki
                  test/tables.icml
@@ -232,37 +334,58 @@
                  test/tables.ms
                  test/tables.plain
                  test/tables.markdown
+                 test/tables.markua
                  test/tables.mediawiki
                  test/tables.tei
                  test/tables.textile
                  test/tables.opendocument
                  test/tables.org
                  test/tables.asciidoc
+                 test/tables.asciidoc_legacy
                  test/tables.haddock
                  test/tables.texinfo
+                 test/tables.typst
                  test/tables.rst
                  test/tables.rtf
                  test/tables.txt
                  test/tables.fb2
                  test/tables.muse
-                 test/tables.custom
+                 test/tables.vimdoc
+                 test/tables.bbcode
+                 test/tables.xwiki
+                 test/tables/*.html4
+                 test/tables/*.html5
+                 test/tables/*.latex
+                 test/tables/*.typst
+                 test/tables/*.native
+                 test/tables/*.mediawiki
+                 test/tables/*.jats_archiving
+                 test/tables/*.markdown
                  test/testsuite.txt
+                 test/ansi-test.txt
                  test/writer.latex
                  test/writer.context
+                 test/writer.djot
                  test/writer.docbook4
                  test/writer.docbook5
-                 test/writer.jats
+                 test/writer.jats_archiving
+                 test/writer.jats_articleauthoring
+                 test/writer.jats_publishing
+                 test/writer.jira
                  test/writer.html4
                  test/writer.html5
                  test/writer.man
                  test/writer.ms
                  test/writer.markdown
+                 test/writer.markua
                  test/writer.plain
                  test/writer.mediawiki
                  test/writer.textile
+                 test/writer.typst
                  test/writer.opendocument
                  test/writer.org
                  test/writer.asciidoc
+                 test/writer.asciidoc_legacy
                  test/writer.haddock
                  test/writer.rst
                  test/writer.icml
@@ -273,8 +396,11 @@
                  test/writer.opml
                  test/writer.dokuwiki
                  test/writer.zimwiki
+                 test/writer.xwiki
                  test/writer.muse
-                 test/writer.custom
+                 test/writer.vimdoc
+                 test/writer.bbcode
+                 test/ansi-test.ansi
                  test/writers-lang-and-dir.latex
                  test/writers-lang-and-dir.context
                  test/dokuwiki_inline_formatting.dokuwiki
@@ -289,156 +415,213 @@
                  test/lhs-test.fragment.html+lhs
                  test/pipe-tables.txt
                  test/dokuwiki_external_images.dokuwiki
-                 test/dokuwiki_external_images.native
                  test/dokuwiki_multiblock_table.dokuwiki
-                 test/dokuwiki_multiblock_table.native
                  test/fb2/*.markdown
                  test/fb2/*.fb2
                  test/fb2/images-embedded.html
                  test/fb2/images-embedded.fb2
                  test/fb2/test-small.png
+                 test/fb2/reader/*.fb2
+                 test/fb2/reader/*.native
                  test/fb2/test.jpg
                  test/docx/*.docx
+                 test/docx/golden/*.docx
                  test/docx/*.native
                  test/epub/*.epub
                  test/epub/*.native
+                 test/rtf/*.native
+                 test/rtf/*.rtf
+                 test/pptx/*.pptx
+                 test/pptx/**/*.pptx
+                 test/pptx/**/*.native
+                 test/pptx-reader/basic.pptx
+                 test/pptx-reader/basic.native
+                 test/ipynb/*.native
+                 test/ipynb/*.in.native
+                 test/ipynb/*.out.native
+                 test/ipynb/*.ipynb
+                 test/ipynb/*.out.ipynb
+                 test/ipynb/*.out.html
                  test/txt2tags.t2t
                  test/twiki-reader.twiki
                  test/tikiwiki-reader.tikiwiki
                  test/odt/odt/*.odt
                  test/odt/markdown/*.md
                  test/odt/native/*.native
-                 test/lua/*.lua
+                 test/xlsx-reader/*.xlsx
+                 test/xlsx-reader/*.native
+                 test/pod-reader.pod
+                 test/vimdoc/*.markdown
+                 test/vimdoc/*.vimdoc
 source-repository head
   type:          git
-  location:      git://github.com/jgm/pandoc.git
-
-flag static
-  Description:   Use static linking for pandoc executable.
-  Default:       False
+  location:      https://github.com/jgm/pandoc.git
 
 flag embed_data_files
   Description:   Embed data files in binary for relocatable executable.
   Default:       False
 
-flag trypandoc
-  Description:   Build trypandoc cgi executable.
-  Default:       False
-
-flag weigh-pandoc
-  Description:   Build weigh-pandoc to measure memory usage.
-  Default:       False
-
-flag network-uri
-  Description:   Get Network.URI from the network-uri package
+flag http
+  Description:   Support for fetching resources using HTTP.
   Default:       True
 
-flag old-locale
-  Description:   Use old-locale and time < 1.5
-  Default:       False
+common common-options
+  default-language: Haskell2010
+  build-depends:    base         >= 4.18 && < 5
+  ghc-options:      -Wall -fno-warn-unused-do-bind
+                    -Wincomplete-record-updates
+                    -Wnoncanonical-monad-instances
+                    -Wcpp-undef
+                    -Wincomplete-uni-patterns
+                    -Widentities
+                    -Wpartial-fields
+                    -Wmissing-signatures
+                    -fhide-source-paths
+                    -Wmissing-export-lists
+                    -Wunused-packages
+                    -Winvalid-haddock
 
-custom-setup
-  setup-depends: base, Cabal
+  if impl(ghc >= 9.12)
+    ghc-options:    -Wno-deriving-typeable
 
-library
-  build-depends: base >= 4.7 && < 5,
-                 syb >= 0.1 && < 0.8,
-                 containers >= 0.4.2.1 && < 0.6,
-                 unordered-containers >= 0.2 && < 0.3,
-                 parsec >= 3.1 && < 3.2,
-                 mtl >= 2.2 && < 2.3,
-                 filepath >= 1.1 && < 1.5,
-                 process >= 1.2.3 && < 1.7,
-                 directory >= 1 && < 1.4,
-                 bytestring >= 0.9 && < 0.11,
-                 text >= 0.11 && < 1.3,
-                 safe >= 0.3 && < 0.4,
-                 zip-archive >= 0.2.3.4 && < 0.4,
-                 HTTP >= 4000.0.5 && < 4000.4,
-                 texmath >= 0.10 && < 0.11,
-                 xml >= 1.3.12 && < 1.4,
-                 split >= 0.2 && < 0.3,
-                 random >= 1 && < 1.2,
-                 pandoc-types >= 1.17.3 && < 1.18,
-                 aeson >= 0.7 && < 1.3,
-                 aeson-pretty >= 0.8 && < 0.9,
-                 tagsoup >= 0.14.2 && < 0.15,
-                 base64-bytestring >= 0.1 && < 1.1,
-                 zlib >= 0.5 && < 0.7,
-                 skylighting >= 0.5 && < 0.6,
-                 data-default >= 0.4 && < 0.8,
-                 temporary >= 1.1 && < 1.3,
-                 blaze-html >= 0.5 && < 0.10,
-                 blaze-markup >= 0.5.1 && < 0.9,
-                 yaml >= 0.8.8.2 && < 0.9,
-                 scientific >= 0.2 && < 0.4,
-                 vector >= 0.10 && < 0.13,
-                 hslua >= 0.9.3 && < 0.10,
-                 hslua-module-text >= 0.1.2 && < 0.2,
-                 binary >= 0.5 && < 0.10,
-                 SHA >= 1.6 && < 1.7,
-                 haddock-library >= 1.1 && < 1.5,
-                 deepseq >= 1.3 && < 1.5,
-                 JuicyPixels >= 3.1.6.1 && < 3.3,
-                 Glob >= 0.7 && < 0.10,
-                 cmark-gfm >= 0.1.1 && < 0.2,
-                 doctemplates >= 0.2.1 && < 0.3,
-                 http-client >= 0.4.30 && < 0.6,
-                 http-client-tls >= 0.2.4 && < 0.4,
-                 http-types >= 0.8 && < 0.12,
-                 case-insensitive >= 1.2 && < 1.3
   if os(windows)
     cpp-options:      -D_WINDOWS
-  else
-    build-depends:  unix >= 2.4 && < 2.8
-  if flag(old-locale)
-     build-depends: old-locale >= 1 && < 1.1,
-                    time >= 1.2 && < 1.5
-  else
-     build-depends: time >= 1.5 && < 1.9
-  if flag(network-uri)
-     build-depends: network-uri >= 2.6 && < 2.7, network >= 2.6
-  else
-     build-depends: network >= 2 && < 2.6
+
+common common-executable
+  import:           common-options
+  build-depends:    pandoc
+  ghc-options:      -rtsopts -with-rtsopts=-A8m -threaded
+
+library xml-light
+  import:        common-options
+  build-depends: xml                   >= 1.3.12   && < 1.4,
+                 xml-conduit           >= 1.9.1.1  && < 1.11,
+                 xml-types             >= 0.3      && < 0.4,
+                 containers            >= 0.6.0.1  && < 0.9,
+                 text                  >= 1.1.1.0  && < 2.2
+
+  hs-source-dirs:  xml-light
+  exposed-modules: Text.Pandoc.XML.Light,
+                   Text.Pandoc.XML.Light.Types,
+                   Text.Pandoc.XML.Light.Proc,
+                   Text.Pandoc.XML.Light.Output
+
+library
+  import:        common-options
+  build-depends: xml-light,
+                 Glob                  >= 0.7      && < 0.11,
+                 JuicyPixels           >= 3.1.6.1  && < 3.4,
+                 aeson                 >= 2.0.1.0  && < 2.4,
+                 aeson-pretty          >= 0.8.9    && < 0.9,
+                 array                 >= 0.5      && < 0.6,
+                 attoparsec            >= 0.12     && < 0.15,
+                 base64-bytestring     >= 0.1      && < 1.3,
+                 binary                >= 0.7      && < 0.11,
+                 blaze-html            >= 0.9      && < 0.10,
+                 blaze-markup          >= 0.8      && < 0.9,
+                 bytestring            >= 0.9      && < 0.13,
+                 case-insensitive      >= 1.2      && < 1.3,
+                 citeproc              >= 0.13.0.1 && < 0.14,
+                 commonmark            >= 0.3      && < 0.4,
+                 commonmark-extensions >= 0.2.7    && < 0.3,
+                 commonmark-pandoc     >= 0.3      && < 0.4,
+                 containers            >= 0.6.0.1  && < 0.9,
+                 crypton               >= 0.30     && < 1.2,
+                 data-default          >= 0.4      && < 0.9,
+                 deepseq               >= 1.3      && < 1.6,
+                 directory             >= 1.2.3    && < 1.4,
+                 doclayout             >= 0.5.0.1  && < 0.6,
+                 doctemplates          >= 0.11     && < 0.12,
+                 emojis                >= 0.1.4.1  && < 0.2,
+                 exceptions            >= 0.8      && < 0.11,
+                 file-embed            >= 0.0      && < 0.1,
+                 filepath              >= 1.1      && < 1.6,
+                 gridtables            >= 0.1      && < 0.2,
+                 haddock-library       >= 1.10     && < 1.12,
+                 http-types            >= 0.8      && < 0.13,
+                 ipynb                 >= 0.2      && < 0.3,
+                 jira-wiki-markup      >= 1.5.1    && < 1.6,
+                 mime-types            >= 0.1.1    && < 0.2,
+                 mtl                   >= 2.2      && < 2.4,
+                 network-uri           >= 2.6      && < 2.8,
+                 pandoc-types          >= 1.23.1   && < 1.24,
+                 parsec                >= 3.1      && < 3.2,
+                 pretty                >= 1.1      && < 1.2,
+                 pretty-show           >= 1.10     && < 1.11,
+                 process               >= 1.2.3    && < 1.7,
+                 random                >= 1.2      && < 1.4,
+                 safe                  >= 0.3.18   && < 0.4,
+                 scientific            >= 0.3      && < 0.4,
+                 skylighting           >= 0.14.7   && < 0.15,
+                 skylighting-core      >= 0.14.7   && < 0.15,
+                 split                 >= 0.2      && < 0.3,
+                 syb                   >= 0.1      && < 0.8,
+                 tagsoup               >= 0.14.6   && < 0.15,
+                 temporary             >= 1.1      && < 1.4,
+                 texmath               >= 0.13.1.2 && < 0.14,
+                 text                  >= 1.1.1.0  && < 2.2,
+                 text-conversions      >= 0.3      && < 0.4,
+                 time                  >= 1.5      && < 1.17,
+                 unicode-collation     >= 0.1.1    && < 0.2,
+                 unicode-data          >= 0.6      && < 0.9,
+                 unicode-transforms    >= 0.3      && < 0.5,
+                 yaml                  >= 0.11     && < 0.12,
+                 libyaml               >= 0.1.4    && < 0.2,
+                 zip-archive           >= 0.4.3.1  && < 0.5,
+                 zlib                  >= 0.5      && < 0.8,
+                 xml                   >= 1.3.12   && < 1.4,
+                 typst                 >= 0.10     && < 0.11,
+                 vector                >= 0.12     && < 0.14,
+                 djot                  >= 0.1.4    && < 0.2,
+                 asciidoc              >= 0.1.0.3  && < 0.2
+
+  if !os(windows)
+    build-depends:  unix >= 2.4 && < 2.9
   if flag(embed_data_files)
      cpp-options:   -DEMBED_DATA_FILES
-     build-depends: file-embed >= 0.0 && < 0.1
-     other-modules: Text.Pandoc.Data
-  if os(windows)
-    cpp-options:      -D_WINDOWS
-  ghc-options:   -Wall -fno-warn-unused-do-bind
-  ghc-prof-options: -fprof-auto-exported
-  default-language: Haskell98
-  other-extensions:   PatternGuards, OverloadedStrings,
-                      ScopedTypeVariables, GeneralizedNewtypeDeriving,
-                      RelaxedPolyRec, DeriveDataTypeable, TypeSynonymInstances,
-                      FlexibleInstances
+     other-modules: Text.Pandoc.Data.BakedIn
+  if flag(http)
+     cpp-options:   -DPANDOC_HTTP_SUPPORT
+     build-depends:
+                 crypton-connection    >= 0.3.1    && < 0.5,
+                 crypton-x509-system   >= 1.6.7    && < 1.10,
+                 http-client           >= 0.4.30   && < 0.8,
+                 http-client-tls       >= 0.2.4    && < 0.5,
+                 network               >= 2.6      && < 3.3,
+                 tls                   >= 2.0.1    && < 2.5
   hs-source-dirs:  src
-  if impl(ghc < 7.10)
-     hs-source-dirs: prelude
-     other-modules:  Prelude
 
   exposed-modules: Text.Pandoc,
                    Text.Pandoc.App,
+                   Text.Pandoc.Data,
                    Text.Pandoc.Options,
                    Text.Pandoc.Extensions,
-                   Text.Pandoc.Pretty,
+                   Text.Pandoc.Format,
                    Text.Pandoc.Shared,
+                   Text.Pandoc.Sources,
                    Text.Pandoc.MediaBag,
                    Text.Pandoc.Error,
+                   Text.Pandoc.Filter,
+                   Text.Pandoc.Translations,
+                   Text.Pandoc.Translations.Types,
                    Text.Pandoc.Readers,
+                   Text.Pandoc.Readers.AsciiDoc,
                    Text.Pandoc.Readers.HTML,
                    Text.Pandoc.Readers.LaTeX,
-                   Text.Pandoc.Readers.LaTeX.Types,
                    Text.Pandoc.Readers.Markdown,
                    Text.Pandoc.Readers.CommonMark,
                    Text.Pandoc.Readers.Creole,
+                   Text.Pandoc.Readers.BibTeX,
+                   Text.Pandoc.Readers.EndNote,
+                   Text.Pandoc.Readers.RIS,
+                   Text.Pandoc.Readers.CslJson,
                    Text.Pandoc.Readers.MediaWiki,
                    Text.Pandoc.Readers.Vimwiki,
                    Text.Pandoc.Readers.RST,
                    Text.Pandoc.Readers.Org,
                    Text.Pandoc.Readers.DocBook,
                    Text.Pandoc.Readers.JATS,
+                   Text.Pandoc.Readers.Jira,
                    Text.Pandoc.Readers.OPML,
                    Text.Pandoc.Readers.Textile,
                    Text.Pandoc.Readers.Native,
@@ -447,18 +630,36 @@
                    Text.Pandoc.Readers.TikiWiki,
                    Text.Pandoc.Readers.Txt2Tags,
                    Text.Pandoc.Readers.Docx,
-                   Text.Pandoc.Readers.Odt,
+                   Text.Pandoc.Readers.Pptx,
+                   Text.Pandoc.Readers.Xlsx,
+                   Text.Pandoc.Readers.ODT,
                    Text.Pandoc.Readers.EPUB,
                    Text.Pandoc.Readers.Muse,
+                   Text.Pandoc.Readers.Man,
+                   Text.Pandoc.Readers.Mdoc,
+                   Text.Pandoc.Readers.FB2,
+                   Text.Pandoc.Readers.DokuWiki,
+                   Text.Pandoc.Readers.Ipynb,
+                   Text.Pandoc.Readers.CSV,
+                   Text.Pandoc.Readers.RTF,
+                   Text.Pandoc.Readers.Typst,
+                   Text.Pandoc.Readers.Djot,
+                   Text.Pandoc.Readers.Pod,
                    Text.Pandoc.Writers,
                    Text.Pandoc.Writers.Native,
-                   Text.Pandoc.Writers.Docbook,
+                   Text.Pandoc.Writers.XML,
+                   Text.Pandoc.Writers.DocBook,
                    Text.Pandoc.Writers.JATS,
                    Text.Pandoc.Writers.OPML,
                    Text.Pandoc.Writers.HTML,
+                   Text.Pandoc.Writers.ChunkedHTML,
+                   Text.Pandoc.Writers.Ipynb,
                    Text.Pandoc.Writers.ICML,
+                   Text.Pandoc.Writers.Jira,
                    Text.Pandoc.Writers.LaTeX,
                    Text.Pandoc.Writers.ConTeXt,
+                   Text.Pandoc.Writers.Djot,
+                   Text.Pandoc.Writers.Typst,
                    Text.Pandoc.Writers.OpenDocument,
                    Text.Pandoc.Writers.Texinfo,
                    Text.Pandoc.Writers.Man,
@@ -469,10 +670,10 @@
                    Text.Pandoc.Writers.RST,
                    Text.Pandoc.Writers.Org,
                    Text.Pandoc.Writers.AsciiDoc,
-                   Text.Pandoc.Writers.Custom,
                    Text.Pandoc.Writers.Textile,
                    Text.Pandoc.Writers.MediaWiki,
                    Text.Pandoc.Writers.DokuWiki,
+                   Text.Pandoc.Writers.XWiki,
                    Text.Pandoc.Writers.ZimWiki,
                    Text.Pandoc.Writers.RTF,
                    Text.Pandoc.Writers.ODT,
@@ -482,12 +683,19 @@
                    Text.Pandoc.Writers.FB2,
                    Text.Pandoc.Writers.TEI,
                    Text.Pandoc.Writers.Muse,
+                   Text.Pandoc.Writers.CslJson,
                    Text.Pandoc.Writers.Math,
                    Text.Pandoc.Writers.Shared,
                    Text.Pandoc.Writers.OOXML,
-                   Text.Pandoc.Lua,
+                   Text.Pandoc.Writers.AnnotatedTable,
+                   Text.Pandoc.Writers.BibTeX,
+                   Text.Pandoc.Writers.ANSI,
+                   Text.Pandoc.Writers.Vimdoc,
+                   Text.Pandoc.Writers.BBCode,
                    Text.Pandoc.PDF,
                    Text.Pandoc.UTF8,
+                   Text.Pandoc.Scripting,
+                   Text.Pandoc.Slides,
                    Text.Pandoc.Templates,
                    Text.Pandoc.XML,
                    Text.Pandoc.SelfContained,
@@ -499,24 +707,75 @@
                    Text.Pandoc.Asciify,
                    Text.Pandoc.Emoji,
                    Text.Pandoc.ImageSize,
-                   Text.Pandoc.BCP47,
-                   Text.Pandoc.Class
-  other-modules:   Text.Pandoc.Readers.Docx.Lists,
+                   Text.Pandoc.Class,
+                   Text.Pandoc.Class.IO,
+                   Text.Pandoc.Citeproc,
+                   Text.Pandoc.Chunks,
+                   Text.Pandoc.Transforms,
+                   Text.Pandoc.Version
+  other-modules:   Text.Pandoc.App.CommandLineOptions,
+                   Text.Pandoc.App.Input,
+                   Text.Pandoc.App.Opt,
+                   Text.Pandoc.App.OutputSettings,
+                   Text.Pandoc.Class.CommonState,
+                   Text.Pandoc.Class.PandocMonad,
+                   Text.Pandoc.Class.PandocIO,
+                   Text.Pandoc.Class.PandocPure,
+                   Text.Pandoc.Class.Sandbox,
+                   Text.Pandoc.Filter.Environment,
+                   Text.Pandoc.Filter.JSON,
+                   Text.Pandoc.Parsing.Capabilities,
+                   Text.Pandoc.Parsing.Citations,
+                   Text.Pandoc.Parsing.General,
+                   Text.Pandoc.Parsing.GridTable,
+                   Text.Pandoc.Parsing.Lists,
+                   Text.Pandoc.Parsing.Math,
+                   Text.Pandoc.Parsing.Smart,
+                   Text.Pandoc.Parsing.State,
+                   Text.Pandoc.Parsing.Future,
+                   Text.Pandoc.Readers.Docx.Lists,
                    Text.Pandoc.Readers.Docx.Combine,
                    Text.Pandoc.Readers.Docx.Parse,
+                   Text.Pandoc.Readers.Docx.Parse.Styles,
                    Text.Pandoc.Readers.Docx.Util,
-                   Text.Pandoc.Readers.Docx.StyleMap,
-                   Text.Pandoc.Readers.Odt.Base,
-                   Text.Pandoc.Readers.Odt.Namespaces,
-                   Text.Pandoc.Readers.Odt.StyleReader,
-                   Text.Pandoc.Readers.Odt.ContentReader,
-                   Text.Pandoc.Readers.Odt.Generic.Fallible,
-                   Text.Pandoc.Readers.Odt.Generic.SetMap,
-                   Text.Pandoc.Readers.Odt.Generic.Utils,
-                   Text.Pandoc.Readers.Odt.Generic.Namespaces,
-                   Text.Pandoc.Readers.Odt.Generic.XMLConverter,
-                   Text.Pandoc.Readers.Odt.Arrows.State,
-                   Text.Pandoc.Readers.Odt.Arrows.Utils,
+                   Text.Pandoc.Readers.Docx.Symbols,
+                   Text.Pandoc.Readers.Docx.Fields,
+                   Text.Pandoc.Readers.OOXML.Shared,
+                   Text.Pandoc.Readers.Pptx.Parse,
+                   Text.Pandoc.Readers.Pptx.Shapes,
+                   Text.Pandoc.Readers.Pptx.Slides,
+                   Text.Pandoc.Readers.Pptx.SmartArt,
+                   Text.Pandoc.Readers.Xlsx.Parse,
+                   Text.Pandoc.Readers.Xlsx.Cells,
+                   Text.Pandoc.Readers.Xlsx.Sheets,
+                   Text.Pandoc.Readers.HTML.Parsing,
+                   Text.Pandoc.Readers.HTML.Table,
+                   Text.Pandoc.Readers.HTML.TagCategories,
+                   Text.Pandoc.Readers.HTML.Types,
+                   Text.Pandoc.Readers.LaTeX.Inline,
+                   Text.Pandoc.Readers.LaTeX.Citation,
+                   Text.Pandoc.Readers.LaTeX.Lang,
+                   Text.Pandoc.Readers.LaTeX.Macro,
+                   Text.Pandoc.Readers.LaTeX.Math,
+                   Text.Pandoc.Readers.LaTeX.Parsing,
+                   Text.Pandoc.Readers.LaTeX.SIunitx,
+                   Text.Pandoc.Readers.LaTeX.Table,
+                   Text.Pandoc.Readers.Mdoc.Lex,
+                   Text.Pandoc.Readers.Mdoc.Macros,
+                   Text.Pandoc.Readers.Mdoc.Standards,
+                   Text.Pandoc.Readers.Typst.Parsing,
+                   Text.Pandoc.Readers.Typst.Math,
+                   Text.Pandoc.Readers.ODT.Base,
+                   Text.Pandoc.Readers.ODT.Namespaces,
+                   Text.Pandoc.Readers.ODT.StyleReader,
+                   Text.Pandoc.Readers.ODT.ContentReader,
+                   Text.Pandoc.Readers.ODT.Generic.Fallible,
+                   Text.Pandoc.Readers.ODT.Generic.SetMap,
+                   Text.Pandoc.Readers.ODT.Generic.Utils,
+                   Text.Pandoc.Readers.ODT.Generic.Namespaces,
+                   Text.Pandoc.Readers.ODT.Generic.XMLConverter,
+                   Text.Pandoc.Readers.ODT.Arrows.State,
+                   Text.Pandoc.Readers.ODT.Arrows.Utils,
                    Text.Pandoc.Readers.Org.BlockStarts,
                    Text.Pandoc.Readers.Org.Blocks,
                    Text.Pandoc.Readers.Org.DocumentTree,
@@ -526,116 +785,87 @@
                    Text.Pandoc.Readers.Org.ParserState,
                    Text.Pandoc.Readers.Org.Parsing,
                    Text.Pandoc.Readers.Org.Shared,
-                   Text.Pandoc.Lua.Filter,
-                   Text.Pandoc.Lua.Init,
-                   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.Readers.Metadata,
+                   Text.Pandoc.Readers.Roff,
+                   Text.Pandoc.Readers.Roff.Escape,
+                   Text.Pandoc.Readers.XML,
+                   Text.Pandoc.Writers.Docx.OpenXML,
+                   Text.Pandoc.Writers.Docx.StyleMap,
+                   Text.Pandoc.Writers.Docx.Table,
+                   Text.Pandoc.Writers.Docx.Types,
+                   Text.Pandoc.Writers.GridTable
+                   Text.Pandoc.Writers.JATS.References,
+                   Text.Pandoc.Writers.JATS.Table,
+                   Text.Pandoc.Writers.JATS.Types,
+                   Text.Pandoc.Writers.LaTeX.Caption,
+                   Text.Pandoc.Writers.LaTeX.Notes,
+                   Text.Pandoc.Writers.LaTeX.Table,
+                   Text.Pandoc.Writers.LaTeX.Lang,
+                   Text.Pandoc.Writers.LaTeX.Types,
+                   Text.Pandoc.Writers.LaTeX.Citation,
+                   Text.Pandoc.Writers.LaTeX.Util,
+                   Text.Pandoc.Writers.Markdown.Table,
+                   Text.Pandoc.Writers.Markdown.Types,
+                   Text.Pandoc.Writers.Markdown.Inline,
+                   Text.Pandoc.Writers.Roff,
+                   Text.Pandoc.Writers.Blaze,
+                   Text.Pandoc.Writers.Powerpoint.Presentation,
+                   Text.Pandoc.Writers.Powerpoint.Output,
+                   Text.Pandoc.Char,
+                   Text.Pandoc.TeX,
+                   Text.Pandoc.URI,
+                   Text.Pandoc.XMLFormat,
                    Text.Pandoc.CSS,
                    Text.Pandoc.CSV,
+                   Text.Pandoc.RoffChar,
                    Text.Pandoc.UUID,
-                   Text.Pandoc.Translations,
-                   Text.Pandoc.Slides,
-                   Text.Pandoc.Compat.Time,
+                   Text.Pandoc.Image,
+                   Text.Pandoc.Citeproc.BibTeX,
+                   Text.Pandoc.Citeproc.Name,
+                   Text.Pandoc.Citeproc.CslJson,
+                   Text.Pandoc.Citeproc.Data,
+                   Text.Pandoc.Citeproc.Locator,
+                   Text.Pandoc.Citeproc.MetaValue,
+                   Text.Pandoc.Citeproc.Util,
                    Paths_pandoc
-
+  autogen-modules: Paths_pandoc
   buildable:       True
 
-executable pandoc
-  build-depends: pandoc, base >= 4.7 && < 5
-  ghc-options:   -rtsopts -with-rtsopts=-K16m -Wall -fno-warn-unused-do-bind -threaded
-  ghc-prof-options: -fprof-auto-exported -rtsopts -with-rtsopts=-K16m
-  if flag(static)
-    ld-options:     -static
-  default-language: Haskell98
-  other-extensions: PatternGuards, OverloadedStrings,
-                    ScopedTypeVariables, GeneralizedNewtypeDeriving,
-                    RelaxedPolyRec, DeriveDataTypeable, TypeSynonymInstances,
-                    FlexibleInstances
-  hs-source-dirs:  .
-  if impl(ghc < 7.10)
-     hs-source-dirs: prelude
-     other-modules:  Prelude
-  main-is:         pandoc.hs
-  buildable:       True
-  other-modules:   Paths_pandoc
-
-executable trypandoc
-  main-is:         trypandoc.hs
-  hs-source-dirs:  trypandoc
-  if impl(ghc < 7.10)
-     hs-source-dirs: prelude
-     other-modules:  Prelude
-  default-language: Haskell2010
-  if flag(trypandoc)
-    build-depends: base, aeson, pandoc,
-                   text, wai-extra, wai >= 0.3, http-types
-    buildable:     True
-  else
-    buildable:     False
-
-executable weigh-pandoc
-  main-is:         weigh-pandoc.hs
-  hs-source-dirs:  benchmark
-  if impl(ghc < 7.10)
-     hs-source-dirs: prelude
-     other-modules:  Prelude
-  if flag(weigh-pandoc)
-     build-depends:   pandoc,
-                      base >= 4.2 && < 5,
-                      text,
-                      weigh >= 0.0 && < 0.1,
-                      mtl >= 2.2 && < 2.3
-     buildable:       True
-  else
-    buildable:     False
-  ghc-options:   -rtsopts -Wall -fno-warn-unused-do-bind
-  default-language: Haskell98
-
 test-suite test-pandoc
+  import:         common-executable
   type:           exitcode-stdio-1.0
   main-is:        test-pandoc.hs
   hs-source-dirs: test
-  if impl(ghc < 7.10)
-     hs-source-dirs: prelude
-     other-modules:  Prelude
-  build-depends:  base >= 4.2 && < 5,
-                  pandoc,
-                  pandoc-types >= 1.17.3 && < 1.18,
-                  bytestring >= 0.9 && < 0.11,
-                  base64-bytestring >= 0.1 && < 1.1,
-                  text >= 0.11 && < 1.3,
-                  time >= 1.5 && < 1.9,
-                  directory >= 1 && < 1.4,
-                  filepath >= 1.1 && < 1.5,
-                  hslua >= 0.9 && < 0.10,
-                  process >= 1.2.3 && < 1.7,
-                  temporary >= 1.1 && < 1.3,
-                  Diff >= 0.2 && < 0.4,
-                  tasty >= 0.11 && < 0.13,
-                  tasty-hunit >= 0.9 && < 0.11,
-                  tasty-quickcheck >= 0.8 && < 0.10,
-                  tasty-golden >= 2.3 && < 2.4,
-                  QuickCheck >= 2.4 && < 2.11,
-                  containers >= 0.4.2.1 && < 0.6,
-                  executable-path >= 0.0 && < 0.1,
-                  zip-archive >= 0.2.3.4 && < 0.4
-  if flag(old-locale)
-     build-depends: old-locale >= 1 && < 1.1,
-                    time >= 1.2 && < 1.5
-  else
-     build-depends: time >= 1.5 && < 1.9
+  build-depends:  pandoc,
+                  Diff              >= 0.2     && < 1.1,
+                  Glob              >= 0.7     && < 0.11,
+                  bytestring        >= 0.9     && < 0.13,
+                  containers        >= 0.4.2.1 && < 0.9,
+                  directory         >= 1.2.3   && < 1.4,
+                  doctemplates      >= 0.11    && < 0.12,
+                  filepath          >= 1.1     && < 1.6,
+                  mtl               >= 2.2     && < 2.4,
+                  pandoc-types      >= 1.23.1  && < 1.24,
+                  process           >= 1.2.3   && < 1.7,
+                  tasty             >= 0.11    && < 1.6,
+                  tasty-golden      >= 2.3     && < 2.4,
+                  tasty-hunit       >= 0.9     && < 0.11,
+                  tasty-quickcheck  >= 0.8     && < 0.12,
+                  text              >= 1.1.1.0 && < 2.2,
+                  temporary         >= 1.1     && < 1.4,
+                  time              >= 1.5     && < 1.17,
+                  xml               >= 1.3.12  && < 1.4,
+                  zip-archive       >= 0.4.3   && < 0.5
   other-modules:  Tests.Old
                   Tests.Command
                   Tests.Helpers
-                  Tests.Lua
                   Tests.Shared
+                  Tests.MediaBag
+                  Tests.XML
                   Tests.Readers.LaTeX
                   Tests.Readers.HTML
                   Tests.Readers.JATS
+                  Tests.Readers.Jira
                   Tests.Readers.Markdown
                   Tests.Readers.Org
                   Tests.Readers.Org.Block
@@ -646,22 +876,32 @@
                   Tests.Readers.Org.Block.Table
                   Tests.Readers.Org.Directive
                   Tests.Readers.Org.Inline
+                  Tests.Readers.Org.Inline.Citation
                   Tests.Readers.Org.Inline.Note
                   Tests.Readers.Org.Inline.Smart
                   Tests.Readers.Org.Meta
                   Tests.Readers.Org.Shared
                   Tests.Readers.RST
+                  Tests.Readers.RTF
                   Tests.Readers.Docx
-                  Tests.Readers.Odt
+                  Tests.Readers.Pptx
+                  Tests.Readers.Xlsx
+                  Tests.Readers.ODT
                   Tests.Readers.Txt2Tags
                   Tests.Readers.EPUB
                   Tests.Readers.Muse
                   Tests.Readers.Creole
+                  Tests.Readers.Man
+                  Tests.Readers.Mdoc
+                  Tests.Readers.FB2
+                  Tests.Readers.Pod
+                  Tests.Readers.DokuWiki
                   Tests.Writers.Native
                   Tests.Writers.ConTeXt
-                  Tests.Writers.Docbook
+                  Tests.Writers.DocBook
                   Tests.Writers.HTML
                   Tests.Writers.JATS
+                  Tests.Writers.Jira
                   Tests.Writers.Markdown
                   Tests.Writers.Org
                   Tests.Writers.Plain
@@ -670,23 +910,24 @@
                   Tests.Writers.Docx
                   Tests.Writers.RST
                   Tests.Writers.TEI
+                  Tests.Writers.Markua
                   Tests.Writers.Muse
                   Tests.Writers.FB2
                   Tests.Writers.Powerpoint
-  ghc-options:  -rtsopts -Wall -fno-warn-unused-do-bind -threaded
-  default-language: Haskell98
+                  Tests.Writers.OOXML
+                  Tests.Writers.Ms
+                  Tests.Writers.AnnotatedTable
+                  Tests.Writers.BBCode
 
 benchmark benchmark-pandoc
+  import:          common-executable
   type:            exitcode-stdio-1.0
   main-is:         benchmark-pandoc.hs
   hs-source-dirs:  benchmark
-  if impl(ghc < 7.10)
-     hs-source-dirs: prelude
-     other-modules:  Prelude
-  build-depends:   pandoc,
-                   time, bytestring, containers,
-                   base >= 4.2 && < 5,
-                   text >= 0.11 && < 1.3,
-                   criterion >= 1.0 && < 1.3
-  ghc-options:   -rtsopts -Wall -fno-warn-unused-do-bind
-  default-language: Haskell98
+  build-depends:   bytestring,
+                   tasty-bench >= 0.4     && <= 0.5,
+                   mtl         >= 2.2     && < 2.4,
+                   text        >= 1.1.1.0 && < 2.2,
+                   deepseq
+  -- we increase heap size to avoid benchmarking garbage collection:
+  ghc-options:     -rtsopts -with-rtsopts=-A8m -threaded
diff --git a/pandoc.hs b/pandoc.hs
deleted file mode 100644
--- a/pandoc.hs
+++ /dev/null
@@ -1,38 +0,0 @@
-{-
-Copyright (C) 2006-2017 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-2017 John MacFarlane
-   License     : GNU GPL, version 2 or above
-
-   Maintainer  : John MacFarlane <jgm@berkeley@edu>
-   Stability   : alpha
-   Portability : portable
-
-Parses command-line options and calls the appropriate readers and
-writers.
--}
-module Main where
-import qualified Control.Exception as E
-import Text.Pandoc.App (convertWithOpts, defaultOpts, options, parseOptions)
-import Text.Pandoc.Error (handleError)
-
-main :: IO ()
-main = E.catch (parseOptions options defaultOpts >>= convertWithOpts)
-          (handleError . Left)
diff --git a/prelude/Prelude.hs b/prelude/Prelude.hs
deleted file mode 100644
--- a/prelude/Prelude.hs
+++ /dev/null
@@ -1,26 +0,0 @@
-{-# LANGUAGE PackageImports #-}
-{-# LANGUAGE CPP #-}
-
--- This custom Prelude emulates the API of the prelude
--- with base 4.8.
-
-module Prelude
-(
-  module P
-#if MIN_VERSION_base(4,8,0)
-#else
-, Monoid(..)
-, Applicative(..)
-, (<$>)
-, (<$)
-#endif
-)
-where
-
-#if MIN_VERSION_base(4,8,0)
-import "base" Prelude as P
-#else
-import "base" Prelude as P
-import Control.Applicative
-import Data.Monoid
-#endif
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-2017 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-2017 John MacFarlane
+   Copyright   : Copyright (C) 2006-2024 John MacFarlane
    License     : GNU GPL, version 2 or above
 
    Maintainer  : John MacFarlane <jgm@berkeley.edu>
@@ -46,7 +28,6 @@
 > mdToRST txt = runIOorExplode $
 >   readMarkdown def txt
 >   >>= writeRST def{ writerReferenceLinks = True }
-
 >
 > main :: IO ()
 > main = do
@@ -66,6 +47,8 @@
                , module Text.Pandoc.Logging
                -- * Typeclass
                , module Text.Pandoc.Class
+               -- * Internal data files
+               , module Text.Pandoc.Data
                -- * Error handling
                , module Text.Pandoc.Error
                -- * Readers: converting /to/ Pandoc format
@@ -74,17 +57,23 @@
                , module Text.Pandoc.Writers
                -- * Rendering templates and default templates
                , module Text.Pandoc.Templates
-               -- * Miscellaneous
+               -- * Localization
+               , setTranslations
+               , translateTerm
+               -- * Version information
                , pandocVersion
+               , pandocVersionText
              ) where
 
 import Text.Pandoc.Class
 import Text.Pandoc.Definition
+import Text.Pandoc.Data
 import Text.Pandoc.Error
 import Text.Pandoc.Generic
 import Text.Pandoc.Logging
 import Text.Pandoc.Options
 import Text.Pandoc.Readers
-import Text.Pandoc.Shared (pandocVersion)
+import Text.Pandoc.Version (pandocVersion, pandocVersionText)
 import Text.Pandoc.Templates
+import Text.Pandoc.Translations (setTranslations, translateTerm)
 import Text.Pandoc.Writers
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,1723 +1,427 @@
-{-# LANGUAGE CPP                 #-}
-{-# LANGUAGE DeriveGeneric       #-}
-{-# LANGUAGE ScopedTypeVariables #-}
-{-# LANGUAGE TemplateHaskell     #-}
-{-# LANGUAGE TupleSections       #-}
-{-
-Copyright (C) 2006-2017 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-2017 John MacFarlane
-   License     : GNU GPL, version 2 or above
-
-   Maintainer  : John MacFarlane <jgm@berkeley@edu>
-   Stability   : alpha
-   Portability : portable
-
-Does a pandoc conversion based on command-line options.
--}
-module Text.Pandoc.App (
-            convertWithOpts
-          , Opt(..)
-          , defaultOpts
-          , parseOptions
-          , options
-          , applyFilters
-          , applyLuaFilters
-          ) where
-import qualified Control.Exception as E
-import Control.Monad
-import Control.Monad.Except (catchError, throwError)
-import Control.Monad.Trans
-import Data.Aeson (defaultOptions, eitherDecode', encode)
-import Data.Aeson.TH (deriveJSON)
-import qualified Data.ByteString as BS
-import qualified Data.ByteString.Lazy as B
-import Data.Char (toLower, toUpper)
-import Data.Foldable (foldrM)
-import Data.List (find, intercalate, isPrefixOf, isSuffixOf, sort)
-import qualified Data.Map as M
-import Data.Maybe (fromMaybe, isJust, isNothing)
-import Data.Monoid
-import qualified Data.Set as Set
-import Data.Text (Text)
-import qualified Data.Text as T
-import qualified Data.Text.Lazy as TL
-import qualified Data.Text.Lazy.Encoding as TE
-import qualified Data.Text.Encoding.Error as TE
-import Data.Yaml (decode)
-import qualified Data.Yaml as Yaml
-import GHC.Generics
-import Network.URI (URI (..), parseURI)
-import Paths_pandoc (getDataDir)
-import Data.Aeson.Encode.Pretty (encodePretty', Config(..), keyOrder,
-         defConfig, Indent(..), NumberFormat(..))
-import Skylighting (Style, Syntax (..), defaultSyntaxMap, parseTheme,
-                    pygments)
-import Skylighting.Parser (addSyntaxDefinition, missingIncludes,
-                           parseSyntaxDefinition)
-import System.Console.GetOpt
-import System.Directory (Permissions (..), doesFileExist, findExecutable,
-                         getAppUserDataDirectory, getPermissions)
-import System.Environment (getArgs, getEnvironment, getProgName)
-import System.Exit (ExitCode (..), exitSuccess)
-import System.FilePath
-import System.IO (nativeNewline, stdout)
-import qualified System.IO as IO (Newline (..))
-import System.IO.Error (isDoesNotExistError)
-import Text.Pandoc
-import Text.Pandoc.BCP47 (Lang (..), parseBCP47)
-import Text.Pandoc.Builder (setMeta, deleteMeta)
-import Text.Pandoc.Highlighting (highlightingStyles)
-import Text.Pandoc.Lua (LuaException (..), runLuaFilter)
-import Text.Pandoc.PDF (makePDF)
-import Text.Pandoc.Process (pipeProcess)
-import Text.Pandoc.SelfContained (makeDataURI, makeSelfContained)
-import Text.Pandoc.Shared (eastAsianLineBreakFilter, stripEmptyParagraphs,
-         headerShift, isURI, ordNub, safeRead, tabFilter)
-import qualified Text.Pandoc.UTF8 as UTF8
-import Text.Pandoc.Writers.Math (defaultKaTeXURL, defaultMathJaxURL)
-import Text.Pandoc.XML (toEntities)
-import Text.Printf
-#ifndef _WINDOWS
-import System.Posix.IO (stdOutput)
-import System.Posix.Terminal (queryTerminal)
-#endif
-
-data LineEnding = LF | CRLF | Native deriving (Show, Generic)
-
-parseOptions :: [OptDescr (Opt -> IO Opt)] -> Opt -> IO Opt
-parseOptions options' defaults = do
-  rawArgs <- map UTF8.decodeArg <$> getArgs
-  prg <- getProgName
-
-  let (actions, args, unrecognizedOpts, errors) =
-           getOpt' Permute options' rawArgs
-
-  let unknownOptionErrors =
-       foldr (handleUnrecognizedOption . takeWhile (/= '=')) []
-       unrecognizedOpts
-
-  unless (null errors && null unknownOptionErrors) $
-     E.throwIO $ PandocOptionError $
-        concat errors ++ unlines unknownOptionErrors ++
-        ("Try " ++ prg ++ " --help for more information.")
-
-  -- thread option data structure through all supplied option actions
-  opts <- foldl (>>=) (return defaults) actions
-  return (opts{ optInputFiles = args })
-
-latexEngines :: [String]
-latexEngines  = ["pdflatex", "lualatex", "xelatex"]
-
-htmlEngines :: [String]
-htmlEngines  = ["wkhtmltopdf", "weasyprint", "prince"]
-
-engines :: [(String, String)]
-engines = map ("html",) htmlEngines ++
-          map ("html5",) htmlEngines ++
-          map ("latex",) latexEngines ++
-          map ("beamer",) latexEngines ++
-          [ ("ms", "pdfroff")
-          , ("context", "context")
-          ]
-
-pdfEngines :: [String]
-pdfEngines = ordNub $ map snd engines
-
-pdfWriterAndProg :: Maybe String              -- ^ user-specified writer name
-                 -> Maybe String              -- ^ user-specified pdf-engine
-                 -> IO (String, Maybe String) -- ^ IO (writerName, maybePdfEngineProg)
-pdfWriterAndProg mWriter mEngine = do
-  let panErr msg = liftIO $ E.throwIO $ PandocAppError msg
-  case go mWriter mEngine of
-      Right (writ, prog) -> return (writ, Just prog)
-      Left err           -> panErr err
-    where
-      go Nothing Nothing       = Right ("latex", "pdflatex")
-      go (Just writer) Nothing = (writer,) <$> engineForWriter writer
-      go Nothing (Just engine) = (,engine) <$> writerForEngine engine
-      go (Just writer) (Just engine) =
-           case find (== (baseWriterName writer, engine)) engines of
-                Just _  -> Right (writer, engine)
-                Nothing -> Left $ "pdf-engine " ++ engine ++
-                           " is not compatible with output format " ++ writer
-
-      writerForEngine eng = case [f | (f,e) <- engines, e == eng] of
-                                 fmt : _ -> Right fmt
-                                 []      -> Left $
-                                   "pdf-engine " ++ eng ++ " not known"
-
-      engineForWriter w = case [e |  (f,e) <- engines, f == baseWriterName w] of
-                                eng : _ -> Right eng
-                                []      -> Left $
-                                   "cannot produce pdf output from " ++ w
-
-convertWithOpts :: Opt -> IO ()
-convertWithOpts opts = do
-  let outputFile = fromMaybe "-" (optOutputFile opts)
-  let filters = optFilters opts
-  let verbosity = optVerbosity opts
-
-  when (optDumpArgs opts) $
-    do UTF8.hPutStrLn stdout outputFile
-       mapM_ (UTF8.hPutStrLn stdout) (optInputFiles opts)
-       exitSuccess
-
-  epubMetadata <- case optEpubMetadata opts of
-                         Nothing -> return Nothing
-                         Just fp -> Just <$> UTF8.readFile fp
-
-  -- --bibliography implies -F pandoc-citeproc for backwards compatibility:
-  let needsCiteproc = isJust (lookup "bibliography" (optMetadata opts)) &&
-                      optCiteMethod opts `notElem` [Natbib, Biblatex] &&
-                      "pandoc-citeproc" `notElem` map takeBaseName filters
-  let filters' = if needsCiteproc then "pandoc-citeproc" : filters
-                                  else filters
-
-  let sources = case optInputFiles opts of
-                     []  -> ["-"]
-                     xs | optIgnoreArgs opts -> ["-"]
-                        | otherwise  -> xs
-
-  datadir <- case optDataDir opts of
-                  Nothing   -> E.catch
-                                 (Just <$> getAppUserDataDirectory "pandoc")
-                                 (\e -> let _ = (e :: E.SomeException)
-                                        in  return Nothing)
-                  Just _    -> return $ optDataDir opts
-
-  -- assign reader and writer based on options and filenames
-  let readerName =  fromMaybe ( defaultReaderName
-                  (if any isURI sources
-                      then "html"
-                      else "markdown") sources) (optReader opts)
-
-  let nonPdfWriterName Nothing  = defaultWriterName outputFile
-      nonPdfWriterName (Just x) = x
-
-  let pdfOutput = map toLower (takeExtension outputFile) == ".pdf"
-  (writerName, maybePdfProg) <-
-    if pdfOutput
-       then pdfWriterAndProg (optWriter opts) (optPdfEngine opts)
-       else return (nonPdfWriterName $ optWriter opts, Nothing)
-
-  let format = baseWriterName
-                 $ takeFileName writerName  -- in case path to lua script
-
-  -- disabling the custom writer for now
-  (writer, writerExts) <-
-            if ".lua" `isSuffixOf` format
-               -- note:  use non-lowercased version writerName
-               then return (TextWriter
-                       (\o d -> writeCustom writerName o d)
-                               :: Writer PandocIO, mempty)
-               else case getWriter writerName of
-                         Left e  -> E.throwIO $ PandocAppError $
-                           if format == "pdf"
-                              then e ++
-                               "\nTo create a pdf using pandoc, use " ++
-                               "-t latex|beamer|context|ms|html5" ++
-                               "\nand specify an output file with " ++
-                               ".pdf extension (-o filename.pdf)."
-                              else e
-                         Right (w, es) -> return (w :: Writer PandocIO, es)
-
-  -- TODO: we have to get the input and the output into the state for
-  -- the sake of the text2tags reader.
-  (reader, readerExts) <-
-           case getReader readerName of
-                Right (r, es) -> return (r :: Reader PandocIO, es)
-                Left e   -> E.throwIO $ PandocAppError e'
-                  where e' = case readerName of
-                                  "pdf" -> e ++
-                                     "\nPandoc can convert to PDF, but not from PDF."
-                                  "doc" -> e ++
-                                     "\nPandoc can convert from DOCX, but not from DOC.\nTry using Word to save your DOC file as DOCX, and convert that with pandoc."
-                                  _ -> e
-
-  let standalone = optStandalone opts || not (isTextFormat format) || pdfOutput
-  let addStringAsVariable varname s vars = return $ (varname, s) : vars
-
-  highlightStyle <- lookupHighlightStyle $ optHighlightStyle opts
-  let addSyntaxMap existingmap f = do
-        res <- parseSyntaxDefinition f
-        case res of
-              Left errstr -> E.throwIO $ PandocSyntaxMapError errstr
-              Right syn   -> return $ addSyntaxDefinition syn existingmap
-
-  syntaxMap <- foldM addSyntaxMap defaultSyntaxMap
-                     (optSyntaxDefinitions opts)
-
-  case missingIncludes (M.elems syntaxMap) of
-       [] -> return ()
-       xs -> E.throwIO $ PandocSyntaxMapError $
-                "Missing syntax definitions:\n" ++
-                unlines (map
-                  (\(syn,dep) -> (T.unpack syn ++ " requires " ++
-                    T.unpack dep ++ " through IncludeRules.")) xs)
-
-  -- We don't want to send output to the terminal if the user
-  -- does 'pandoc -t docx input.txt'; though we allow them to
-  -- force this with '-o -'.  On posix systems, we detect
-  -- when stdout is being piped and allow output to stdout
-  -- in that case, but on Windows we can't.
-#ifdef _WINDOWS
-  let istty = True
-#else
-  istty <- queryTerminal stdOutput
-#endif
-  when (not (isTextFormat format) && istty && isNothing ( optOutputFile opts)) $
-    E.throwIO $ PandocAppError $
-            "Cannot write " ++ format ++ " output to terminal.\n" ++
-            "Specify an output file using the -o option, or " ++
-            "use '-o -' to force output to stdout."
-
-  let convertTabs = tabFilter (if optPreserveTabs opts || readerName == "t2t"
-                                  then 0
-                                  else optTabStop opts)
-
-      readSources :: [FilePath] -> PandocIO Text
-      readSources srcs = convertTabs . T.intercalate (T.pack "\n") <$>
-                            mapM readSource srcs
-
-  let runIO' :: PandocIO a -> IO a
-      runIO' f = do
-        (res, reports) <- runIOorExplode $ do
-                             setTrace (optTrace opts)
-                             setVerbosity verbosity
-                             x <- f
-                             rs <- getLog
-                             return (x, rs)
-        case optLogFile opts of
-             Nothing      -> return ()
-             Just logfile -> B.writeFile logfile (encodeLogMessages reports)
-        let isWarning msg = messageVerbosity msg == WARNING
-        when (optFailIfWarnings opts && any isWarning reports) $
-            E.throwIO PandocFailOnWarningError
-        return res
-
-  let eol = case optEol opts of
-                 CRLF   -> IO.CRLF
-                 LF     -> IO.LF
-                 Native -> nativeNewline
-
-  -- note: this reverses the list constructed in option parsing,
-  -- which in turn was reversed from the command-line order,
-  -- so we end up with the correct order in the variable list:
-  let withList _ [] vars     = return vars
-      withList f (x:xs) vars = f x vars >>= withList f xs
-
-  let addContentsAsVariable varname fp vars = do
-             s <- UTF8.toString <$> readFileStrict fp
-             return $ (varname, s) : vars
-
-  runIO' $ do
-    setUserDataDir datadir
-    setInputFiles (optInputFiles opts)
-    setOutputFile (optOutputFile opts)
-
-    variables <-
-        withList (addStringAsVariable "sourcefile")
-                 (reverse $ optInputFiles opts)
-                 (("outputfile", fromMaybe "-" (optOutputFile opts))
-                  : optVariables opts)
-                 -- we reverse this list because, unlike
-                 -- the other option lists here, it is
-                 -- not reversed when parsed from CLI arguments.
-                 -- See withList, above.
-        >>=
-        withList (addContentsAsVariable "include-before")
-                 (optIncludeBeforeBody opts)
-        >>=
-        withList (addContentsAsVariable "include-after")
-                 (optIncludeAfterBody opts)
-        >>=
-        withList (addContentsAsVariable "header-includes")
-                 (optIncludeInHeader opts)
-        >>=
-        withList (addStringAsVariable "css") (optCss opts)
-        >>=
-        maybe return (addStringAsVariable "title-prefix")
-                     (optTitlePrefix opts)
-        >>=
-        maybe return (addStringAsVariable "epub-cover-image")
-                     (optEpubCoverImage opts)
-        >>=
-        (\vars -> case optHTMLMathMethod opts of
-                       LaTeXMathML Nothing -> do
-                          s <- UTF8.toString <$> readDataFile "LaTeXMathML.js"
-                          return $ ("mathml-script", s) : vars
-                       _ -> return vars)
-        >>=
-        (\vars ->  if format == "dzslides"
-                      then do
-                          dztempl <- UTF8.toString <$> readDataFile
-                                       ("dzslides" </> "template.html")
-                          let dzline = "<!-- {{{{ dzslides core"
-                          let dzcore = unlines
-                                     $ dropWhile (not . (dzline `isPrefixOf`))
-                                     $ lines dztempl
-                          return $ ("dzslides-core", dzcore) : vars
-                      else return vars)
-
-    abbrevs <- (Set.fromList . filter (not . null) . lines) <$>
-               case optAbbreviations opts of
-                    Nothing -> UTF8.toString <$> readDataFile "abbreviations"
-                    Just f  -> UTF8.toString <$> readFileStrict f
-
-    templ <- case optTemplate opts of
-                    _ | not standalone -> return Nothing
-                    Nothing -> Just <$> getDefaultTemplate format
-                    Just tp -> do
-                      -- strip off extensions
-                      let tp' = case takeExtension tp of
-                                     "" -> tp <.> format
-                                     _  -> tp
-                      Just . UTF8.toString <$>
-                            (readFileStrict tp' `catchError`
-                             (\e ->
-                                 case e of
-                                      PandocIOError _ e' |
-                                        isDoesNotExistError e' ->
-                                         readDataFile ("templates" </> tp')
-                                      _ -> throwError e))
-
-    metadata <- if format == "jats" &&
-                   isNothing (lookup "csl" (optMetadata opts)) &&
-                   isNothing (lookup "citation-style" (optMetadata opts))
-                   then do
-                     jatsCSL <- readDataFile "jats.csl"
-                     let jatsEncoded = makeDataURI
-                                         ("application/xml", jatsCSL)
-                     return $ ("csl", jatsEncoded) : optMetadata opts
-                   else return $ optMetadata opts
-
-    case lookup "lang" (optMetadata opts) of
-           Just l  -> case parseBCP47 l of
-                           Left _   -> return ()
-                           Right l' -> setTranslations l'
-           Nothing -> setTranslations $ Lang "en" "" "US" []
-
-    let writerOptions = def {
-            writerTemplate         = templ
-          , writerVariables        = variables
-          , writerTabStop          = optTabStop opts
-          , writerTableOfContents  = optTableOfContents opts
-          , writerHTMLMathMethod   = optHTMLMathMethod opts
-          , writerIncremental      = optIncremental opts
-          , writerCiteMethod       = optCiteMethod opts
-          , writerNumberSections   = optNumberSections opts
-          , writerNumberOffset     = optNumberOffset opts
-          , writerSectionDivs      = optSectionDivs opts
-          , writerExtensions       = writerExts
-          , writerReferenceLinks   = optReferenceLinks opts
-          , writerReferenceLocation = optReferenceLocation opts
-          , writerDpi              = optDpi opts
-          , writerWrapText         = optWrapText opts
-          , writerColumns          = optColumns opts
-          , writerEmailObfuscation = optEmailObfuscation opts
-          , writerIdentifierPrefix = optIdentifierPrefix opts
-          , writerHtmlQTags        = optHtmlQTags opts
-          , writerTopLevelDivision = optTopLevelDivision opts
-          , writerListings         = optListings opts
-          , writerSlideLevel       = optSlideLevel opts
-          , writerHighlightStyle   = highlightStyle
-          , writerSetextHeaders    = optSetextHeaders opts
-          , writerEpubSubdirectory = optEpubSubdirectory opts
-          , writerEpubMetadata     = epubMetadata
-          , writerEpubFonts        = optEpubFonts opts
-          , writerEpubChapterLevel = optEpubChapterLevel opts
-          , writerTOCDepth         = optTOCDepth opts
-          , writerReferenceDoc     = optReferenceDoc opts
-          , writerSyntaxMap        = syntaxMap
-          }
-
-    let readerOpts = def{
-            readerStandalone = standalone
-          , readerColumns = optColumns opts
-          , readerTabStop = optTabStop opts
-          , readerIndentedCodeClasses = optIndentedCodeClasses opts
-          , readerDefaultImageExtension =
-             optDefaultImageExtension opts
-          , readerTrackChanges = optTrackChanges opts
-          , readerAbbreviations = abbrevs
-          , readerExtensions = readerExts
-          , readerStripComments = optStripComments opts
-          }
-
-    let transforms = (case optBaseHeaderLevel opts of
-                          x | x > 1     -> (headerShift (x - 1) :)
-                            | otherwise -> id) .
-                     (if optStripEmptyParagraphs opts
-                         then (stripEmptyParagraphs :)
-                         else id) .
-                     (if extensionEnabled Ext_east_asian_line_breaks
-                            readerExts &&
-                         not (extensionEnabled Ext_east_asian_line_breaks
-                              writerExts &&
-                              writerWrapText writerOptions == WrapPreserve)
-                         then (eastAsianLineBreakFilter :)
-                         else id) $
-                     []
-
-    let sourceToDoc :: [FilePath] -> PandocIO Pandoc
-        sourceToDoc sources' =
-           case reader of
-                TextReader r
-                  | optFileScope opts || readerName == "json" ->
-                      mconcat <$> mapM (readSource >=> r readerOpts) sources
-                  | otherwise ->
-                      readSources sources' >>= r readerOpts
-                ByteStringReader r ->
-                  mconcat <$> mapM (readFile' >=> r readerOpts) sources
-
-
-    when (readerName == "markdown_github" ||
-          writerName == "markdown_github") $
-      report $ Deprecated "markdown_github" "Use gfm instead."
-
-    setResourcePath (optResourcePath opts)
-    mapM_ (uncurry setRequestHeader) (optRequestHeaders opts)
-
-    doc <- sourceToDoc sources >>=
-              (   (if isJust (optExtractMedia opts)
-                      then fillMediaBag
-                      else return)
-              >=> return . addMetadata metadata
-              >=> applyLuaFilters datadir (optLuaFilters opts) format
-              >=> maybe return extractMedia (optExtractMedia opts)
-              >=> applyTransforms transforms
-              >=> applyFilters readerOpts datadir filters' [format]
-              )
-
-    case writer of
-      ByteStringWriter f -> f writerOptions doc >>= writeFnBinary outputFile
-      TextWriter f -> case maybePdfProg of
-        Just pdfProg -> do
-                res <- makePDF pdfProg (optPdfEngineArgs opts) f
-                        writerOptions doc
-                case res of
-                     Right pdf -> writeFnBinary outputFile pdf
-                     Left err' -> liftIO $
-                       E.throwIO $ PandocPDFError $
-                                     TL.unpack (TE.decodeUtf8With TE.lenientDecode err')
-
-        Nothing -> do
-                let htmlFormat = format `elem`
-                      ["html","html4","html5","s5","slidy",
-                       "slideous","dzslides","revealjs"]
-                    handleEntities = if (htmlFormat ||
-                                         format == "docbook4" ||
-                                         format == "docbook5" ||
-                                         format == "docbook") && optAscii opts
-                                     then toEntities
-                                     else id
-                    addNl = if standalone
-                               then id
-                               else (<> T.singleton '\n')
-                output <- (addNl . handleEntities) <$> f writerOptions doc
-                writerFn eol outputFile =<<
-                  if optSelfContained opts && htmlFormat
-                     -- 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
-
-isTextFormat :: String -> Bool
-isTextFormat s = s `notElem` ["odt","docx","epub2","epub3","epub","pptx"]
-
-externalFilter :: MonadIO m
-               => ReaderOptions -> FilePath -> [String] -> Pandoc -> m Pandoc
-externalFilter ropts f args' d = liftIO $ do
-  exists <- doesFileExist f
-  isExecutable <- if exists
-                     then executable <$> getPermissions f
-                     else return True
-  let (f', args'') = if exists
-                        then case map toLower (takeExtension f) of
-                                  _      | isExecutable -> ("." </> f, args')
-                                  ".py"  -> ("python", f:args')
-                                  ".hs"  -> ("runhaskell", f:args')
-                                  ".pl"  -> ("perl", f:args')
-                                  ".rb"  -> ("ruby", f:args')
-                                  ".php" -> ("php", f:args')
-                                  ".js"  -> ("node", f:args')
-                                  ".r"   -> ("Rscript", f:args')
-                                  _      -> (f, args')
-                        else (f, args')
-  unless (exists && isExecutable) $ do
-    mbExe <- findExecutable f'
-    when (isNothing mbExe) $
-      E.throwIO $ PandocFilterError f ("Could not find executable " ++ f')
-  env <- getEnvironment
-  let env' = Just
-           ( ("PANDOC_VERSION", pandocVersion)
-           : ("PANDOC_READER_OPTIONS", UTF8.toStringLazy (encode ropts))
-           : env )
-  (exitcode, outbs) <- E.handle filterException $
-                              pipeProcess env' f' args'' $ encode d
-  case exitcode of
-       ExitSuccess    -> either (E.throwIO . PandocFilterError f)
-                                   return $ eitherDecode' outbs
-       ExitFailure ec -> E.throwIO $ PandocFilterError f
-                           ("Filter returned error status " ++ show ec)
- where filterException :: E.SomeException -> IO a
-       filterException e = E.throwIO $ PandocFilterError f (show e)
-
--- | Data structure for command line options.
-data Opt = Opt
-    { optTabStop               :: Int     -- ^ Number of spaces per tab
-    , optPreserveTabs          :: Bool    -- ^ Preserve tabs instead of converting to spaces
-    , optStandalone            :: Bool    -- ^ Include header, footer
-    , optReader                :: Maybe String  -- ^ Reader format
-    , optWriter                :: Maybe String  -- ^ Writer format
-    , optTableOfContents       :: Bool    -- ^ Include table of contents
-    , optBaseHeaderLevel       :: Int     -- ^ Base header level
-    , optTemplate              :: Maybe FilePath  -- ^ Custom template
-    , optVariables             :: [(String,String)] -- ^ Template variables to set
-    , optMetadata              :: [(String, String)] -- ^ Metadata fields to set
-    , optOutputFile            :: Maybe FilePath  -- ^ Name of output file
-    , optInputFiles            :: [FilePath] -- ^ Names of input files
-    , optNumberSections        :: Bool    -- ^ Number sections in LaTeX
-    , optNumberOffset          :: [Int]   -- ^ Starting number for sections
-    , optSectionDivs           :: Bool    -- ^ Put sections in div tags in HTML
-    , optIncremental           :: Bool    -- ^ Use incremental lists in Slidy/Slideous/S5
-    , optSelfContained         :: Bool    -- ^ Make HTML accessible offline
-    , optHtmlQTags             :: Bool    -- ^ Use <q> tags in HTML
-    , optHighlightStyle        :: Maybe String -- ^ Style to use for highlighted code
-    , optSyntaxDefinitions     :: [FilePath]  -- ^ xml syntax defs to load
-    , optTopLevelDivision      :: TopLevelDivision -- ^ Type of the top-level divisions
-    , optHTMLMathMethod        :: HTMLMathMethod -- ^ Method to print HTML math
-    , optAbbreviations         :: Maybe FilePath -- ^ Path to abbrevs file
-    , optReferenceDoc          :: Maybe FilePath -- ^ Path of reference doc
-    , optEpubSubdirectory      :: String -- ^ EPUB subdir in OCF container
-    , optEpubMetadata          :: Maybe FilePath   -- ^ EPUB metadata
-    , optEpubFonts             :: [FilePath] -- ^ EPUB fonts to embed
-    , optEpubChapterLevel      :: Int     -- ^ Header level at which to split chapters
-    , optEpubCoverImage        :: Maybe FilePath -- ^ Cover image for epub
-    , optTOCDepth              :: Int     -- ^ Number of levels to include in TOC
-    , optDumpArgs              :: Bool    -- ^ Output command-line arguments
-    , optIgnoreArgs            :: Bool    -- ^ Ignore command-line arguments
-    , optVerbosity             :: Verbosity  -- ^ Verbosity of diagnostic output
-    , optTrace                 :: Bool  -- ^ Enable tracing
-    , optLogFile               :: Maybe FilePath -- ^ File to write JSON log output
-    , optFailIfWarnings        :: Bool    -- ^ Fail on warnings
-    , optReferenceLinks        :: Bool    -- ^ Use reference links in writing markdown, rst
-    , optReferenceLocation     :: ReferenceLocation -- ^ location for footnotes and link references in markdown output
-    , optDpi                   :: Int     -- ^ Dpi
-    , optWrapText              :: WrapOption  -- ^ Options for wrapping text
-    , optColumns               :: Int     -- ^ Line length in characters
-    , optFilters               :: [FilePath] -- ^ Filters to apply
-    , optLuaFilters            :: [FilePath] -- ^ Lua filters to apply
-    , optEmailObfuscation      :: ObfuscationMethod
-    , optIdentifierPrefix      :: String
-    , optStripEmptyParagraphs  :: Bool -- ^ Strip empty paragraphs
-    , optIndentedCodeClasses   :: [String] -- ^ Default classes for indented code blocks
-    , optDataDir               :: Maybe FilePath
-    , optCiteMethod            :: CiteMethod -- ^ Method to output cites
-    , optListings              :: Bool       -- ^ Use listings package for code blocks
-    , optPdfEngine             :: Maybe String -- ^ Program to use for latex/html -> pdf
-    , optPdfEngineArgs         :: [String]   -- ^ Flags to pass to the engine
-    , optSlideLevel            :: Maybe Int  -- ^ Header level that creates slides
-    , optSetextHeaders         :: Bool       -- ^ Use atx headers for markdown level 1-2
-    , optAscii                 :: Bool       -- ^ Use ascii characters only in html
-    , optDefaultImageExtension :: String -- ^ Default image extension
-    , optExtractMedia          :: Maybe FilePath -- ^ Path to extract embedded media
-    , optTrackChanges          :: TrackChanges -- ^ Accept or reject MS Word track-changes.
-    , optFileScope             :: Bool         -- ^ Parse input files before combining
-    , optTitlePrefix           :: Maybe String     -- ^ Prefix for title
-    , optCss                   :: [FilePath]       -- ^ CSS files to link to
-    , optIncludeBeforeBody     :: [FilePath]       -- ^ Files to include before
-    , optIncludeAfterBody      :: [FilePath]       -- ^ Files to include after body
-    , optIncludeInHeader       :: [FilePath]       -- ^ Files to include in header
-    , optResourcePath          :: [FilePath] -- ^ Path to search for images etc
-    , optRequestHeaders        :: [(String, String)] -- ^ Headers for HTTP requests
-    , optEol                   :: LineEnding -- ^ Style of line-endings to use
-    , optStripComments         :: Bool       -- ^ Skip HTML comments
-    } deriving (Generic, Show)
-
--- | Defaults for command-line options.
-defaultOpts :: Opt
-defaultOpts = Opt
-    { optTabStop               = 4
-    , optPreserveTabs          = False
-    , optStandalone            = False
-    , optReader                = Nothing
-    , optWriter                = Nothing
-    , optTableOfContents       = False
-    , optBaseHeaderLevel       = 1
-    , optTemplate              = Nothing
-    , optVariables             = []
-    , optMetadata              = []
-    , optOutputFile            = Nothing
-    , optInputFiles            = []
-    , optNumberSections        = False
-    , optNumberOffset          = [0,0,0,0,0,0]
-    , optSectionDivs           = False
-    , optIncremental           = False
-    , optSelfContained         = False
-    , optHtmlQTags             = False
-    , optHighlightStyle        = Just "pygments"
-    , optSyntaxDefinitions     = []
-    , optTopLevelDivision      = TopLevelDefault
-    , optHTMLMathMethod        = PlainMath
-    , optAbbreviations         = Nothing
-    , optReferenceDoc          = Nothing
-    , optEpubSubdirectory      = "EPUB"
-    , optEpubMetadata          = Nothing
-    , optEpubFonts             = []
-    , optEpubChapterLevel      = 1
-    , optEpubCoverImage        = Nothing
-    , optTOCDepth              = 3
-    , optDumpArgs              = False
-    , optIgnoreArgs            = False
-    , optVerbosity             = WARNING
-    , optTrace                 = False
-    , optLogFile               = Nothing
-    , optFailIfWarnings        = False
-    , optReferenceLinks        = False
-    , optReferenceLocation     = EndOfDocument
-    , optDpi                   = 96
-    , optWrapText              = WrapAuto
-    , optColumns               = 72
-    , optFilters               = []
-    , optLuaFilters            = []
-    , optEmailObfuscation      = NoObfuscation
-    , optIdentifierPrefix      = ""
-    , optStripEmptyParagraphs  = False
-    , optIndentedCodeClasses   = []
-    , optDataDir               = Nothing
-    , optCiteMethod            = Citeproc
-    , optListings              = False
-    , optPdfEngine             = Nothing
-    , optPdfEngineArgs         = []
-    , optSlideLevel            = Nothing
-    , optSetextHeaders         = True
-    , optAscii                 = False
-    , optDefaultImageExtension = ""
-    , optExtractMedia          = Nothing
-    , optTrackChanges          = AcceptChanges
-    , optFileScope             = False
-    , optTitlePrefix           = Nothing
-    , optCss                   = []
-    , optIncludeBeforeBody     = []
-    , optIncludeAfterBody      = []
-    , optIncludeInHeader       = []
-    , optResourcePath          = ["."]
-    , optRequestHeaders        = []
-    , optEol                   = Native
-    , optStripComments          = False
-    }
-
-addMetadata :: [(String, String)] -> Pandoc -> Pandoc
-addMetadata kvs pdc = foldr addMeta (removeMetaKeys kvs pdc) kvs
-
-addMeta :: (String, String) -> Pandoc -> Pandoc
-addMeta (k, v) (Pandoc meta bs) = Pandoc meta' bs
-  where meta' = case lookupMeta k meta of
-                      Nothing -> setMeta k v' meta
-                      Just (MetaList xs) ->
-                                 setMeta k (MetaList (xs ++ [v'])) meta
-                      Just x  -> setMeta k (MetaList [x, v']) meta
-        v' = readMetaValue v
-
-removeMetaKeys :: [(String,String)] -> Pandoc -> Pandoc
-removeMetaKeys kvs pdc = foldr (deleteMeta . fst) pdc kvs
-
-readMetaValue :: String -> MetaValue
-readMetaValue s = case decode (UTF8.fromString s) of
-                       Just (Yaml.String t) -> MetaString $ T.unpack t
-                       Just (Yaml.Bool b)   -> MetaBool b
-                       _                    -> MetaString s
-
--- Determine default reader based on source file extensions
-defaultReaderName :: String -> [FilePath] -> String
-defaultReaderName fallback [] = fallback
-defaultReaderName fallback (x:xs) =
-  case takeExtension (map toLower x) of
-    ".xhtml"    -> "html"
-    ".html"     -> "html"
-    ".htm"      -> "html"
-    ".md"       -> "markdown"
-    ".markdown" -> "markdown"
-    ".muse"     -> "muse"
-    ".tex"      -> "latex"
-    ".latex"    -> "latex"
-    ".ltx"      -> "latex"
-    ".rst"      -> "rst"
-    ".org"      -> "org"
-    ".lhs"      -> "markdown+lhs"
-    ".db"       -> "docbook"
-    ".opml"     -> "opml"
-    ".wiki"     -> "mediawiki"
-    ".dokuwiki" -> "dokuwiki"
-    ".textile"  -> "textile"
-    ".native"   -> "native"
-    ".json"     -> "json"
-    ".docx"     -> "docx"
-    ".t2t"      -> "t2t"
-    ".epub"     -> "epub"
-    ".odt"      -> "odt"
-    ".pdf"      -> "pdf"  -- so we get an "unknown reader" error
-    ".doc"      -> "doc"  -- so we get an "unknown reader" error
-    _           -> defaultReaderName fallback xs
-
--- Determine default writer based on output file extension
-defaultWriterName :: FilePath -> String
-defaultWriterName "-" = "html" -- no output file
-defaultWriterName x =
-  case takeExtension (map toLower x) of
-    ""          -> "markdown" -- empty extension
-    ".tex"      -> "latex"
-    ".latex"    -> "latex"
-    ".ltx"      -> "latex"
-    ".context"  -> "context"
-    ".ctx"      -> "context"
-    ".rtf"      -> "rtf"
-    ".rst"      -> "rst"
-    ".s5"       -> "s5"
-    ".native"   -> "native"
-    ".json"     -> "json"
-    ".txt"      -> "markdown"
-    ".text"     -> "markdown"
-    ".md"       -> "markdown"
-    ".muse"     -> "muse"
-    ".markdown" -> "markdown"
-    ".textile"  -> "textile"
-    ".lhs"      -> "markdown+lhs"
-    ".texi"     -> "texinfo"
-    ".texinfo"  -> "texinfo"
-    ".db"       -> "docbook"
-    ".odt"      -> "odt"
-    ".docx"     -> "docx"
-    ".epub"     -> "epub"
-    ".org"      -> "org"
-    ".asciidoc" -> "asciidoc"
-    ".adoc"     -> "asciidoc"
-    ".fb2"      -> "fb2"
-    ".opml"     -> "opml"
-    ".icml"     -> "icml"
-    ".tei.xml"  -> "tei"
-    ".tei"      -> "tei"
-    ".ms"       -> "ms"
-    ".roff"     -> "ms"
-    ".pptx"     -> "pptx"
-    ['.',y]     | y `elem` ['1'..'9'] -> "man"
-    _           -> "html"
-
--- Transformations of a Pandoc document post-parsing:
-
-applyTransforms :: Monad m => [Transform] -> Pandoc -> m Pandoc
-applyTransforms transforms d = return $ foldr ($) d transforms
-
-  -- First we check to see if a filter is found.  If not, and if it's
-  -- not an absolute path, we check to see whether it's in `userdir/filters`.
-  -- If not, we leave it unchanged.
-expandFilterPath :: MonadIO m => Maybe FilePath -> FilePath -> m FilePath
-expandFilterPath mbDatadir fp = liftIO $ do
-  fpExists <- doesFileExist fp
-  if fpExists
-     then return fp
-     else case mbDatadir of
-               Just datadir | isRelative fp -> do
-                 let filterPath = datadir </> "filters" </> fp
-                 filterPathExists <- doesFileExist filterPath
-                 if filterPathExists
-                    then return filterPath
-                    else return fp
-               _ -> return fp
-
-applyLuaFilters :: Maybe FilePath -> [FilePath] -> String -> Pandoc
-                -> PandocIO Pandoc
-applyLuaFilters mbDatadir filters format d = do
-  expandedFilters <- mapM (expandFilterPath mbDatadir) filters
-  let go f d' = do
-        res <- runLuaFilter f format d'
-        case res of
-          Right x               -> return x
-          Left (LuaException s) -> E.throw (PandocFilterError f s)
-  foldrM ($) d $ map go expandedFilters
-
-applyFilters :: MonadIO m
-             => ReaderOptions
-             -> Maybe FilePath
-             -> [FilePath]
-             -> [String]
-             -> Pandoc
-             -> m Pandoc
-applyFilters ropts mbDatadir filters args d = do
-  expandedFilters <- mapM (expandFilterPath mbDatadir) filters
-  foldrM ($) d $ map (flip (externalFilter ropts) args) expandedFilters
-
-readSource :: FilePath -> PandocIO Text
-readSource "-" = liftIO (UTF8.toText <$> BS.getContents)
-readSource src = case parseURI src of
-                      Just u | uriScheme u `elem` ["http:","https:"] ->
-                                 readURI src
-                             | uriScheme u == "file:" ->
-                                 liftIO $ UTF8.toText <$>
-                                    BS.readFile (uriPath u)
-                      _       -> liftIO $ UTF8.toText <$>
-                                    BS.readFile src
-
-readURI :: FilePath -> PandocIO Text
-readURI src = UTF8.toText . fst <$> openURL src
-
-readFile' :: MonadIO m => FilePath -> m B.ByteString
-readFile' "-" = liftIO B.getContents
-readFile' f   = liftIO $ B.readFile f
-
-writeFnBinary :: MonadIO m => FilePath -> B.ByteString -> m ()
-writeFnBinary "-" = liftIO . B.putStr
-writeFnBinary f   = liftIO . B.writeFile (UTF8.encodePath f)
-
-writerFn :: MonadIO m => IO.Newline -> FilePath -> Text -> m ()
--- TODO this implementation isn't maximally efficient:
-writerFn eol "-" = liftIO . UTF8.putStrWith eol . T.unpack
-writerFn eol f   = liftIO . UTF8.writeFileWith eol f . T.unpack
-
-lookupHighlightStyle :: Maybe String -> IO (Maybe Style)
-lookupHighlightStyle Nothing = return Nothing
-lookupHighlightStyle (Just s)
-  | takeExtension s == ".theme" = -- attempt to load KDE theme
-    do contents <- B.readFile s
-       case parseTheme contents of
-            Left _    -> E.throwIO $ PandocOptionError $
-                           "Could not read highlighting theme " ++ s
-            Right sty -> return (Just sty)
-  | otherwise =
-  case lookup (map toLower s) highlightingStyles of
-       Just sty -> return (Just sty)
-       Nothing  -> E.throwIO $ PandocOptionError $
-                      "Unknown highlight-style " ++ s
-
--- | A list of functions, each transforming the options data structure
---   in response to a command-line option.
-options :: [OptDescr (Opt -> IO Opt)]
-options =
-    [ Option "fr" ["from","read"]
-                 (ReqArg
-                  (\arg opt -> return opt { optReader =
-                                              Just (map toLower arg) })
-                  "FORMAT")
-                 ""
-
-    , Option "tw" ["to","write"]
-                 (ReqArg
-                  (\arg opt -> return opt { optWriter =
-                                              Just (map toLower arg) })
-                  "FORMAT")
-                 ""
-
-    , Option "o" ["output"]
-                 (ReqArg
-                  (\arg opt -> return opt { optOutputFile = Just arg })
-                  "FILE")
-                 "" -- "Name of output file"
-
-    , Option "" ["data-dir"]
-                 (ReqArg
-                  (\arg opt -> return opt { optDataDir = Just 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 = arg : optFilters opt })
-                  "PROGRAM")
-                 "" -- "External JSON filter"
-
-    , Option "" ["lua-filter"]
-                 (ReqArg
-                  (\arg opt -> return opt { optLuaFilters = arg : optLuaFilters 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"]
-                 (ReqArg
-                  (\arg opt ->
-                    return opt { optExtractMedia = Just arg })
-                  "PATH")
-                 "" -- "Directory to which to extract embedded media"
-
-    , Option "s" ["standalone"]
-                 (NoArg
-                  (\opt -> return opt { optStandalone = True }))
-                 "" -- "Include needed header and footer on output"
-
-    , Option "" ["template"]
-                 (ReqArg
-                  (\arg opt ->
-                     return opt{ optTemplate = Just arg,
-                                 optStandalone = True })
-                  "FILE")
-                 "" -- "Use custom template"
-
-    , Option "M" ["metadata"]
-                 (ReqArg
-                  (\arg opt -> do
-                     let (key, val) = splitField arg
-                     return opt{ optMetadata = (key, val) : optMetadata opt })
-                  "KEY[:VALUE]")
-                 ""
-
-    , Option "V" ["variable"]
-                 (ReqArg
-                  (\arg opt -> do
-                     let (key, val) = splitField arg
-                     return opt{ optVariables = (key, val) : optVariables opt })
-                  "KEY[:VALUE]")
-                 ""
-
-    , Option "D" ["print-default-template"]
-                 (ReqArg
-                  (\arg _ -> do
-                     templ <- runIO $ do
-                                setUserDataDir Nothing
-                                getDefaultTemplate arg
-                     case templ of
-                          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 (Just 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 "" ["dpi"]
-                 (ReqArg
-                  (\arg opt ->
-                    case safeRead arg of
-                         Just t | t > 0 -> return opt { optDpi = t }
-                         _              -> E.throwIO $ PandocOptionError
-                                        "dpi must be a number greater than 0")
-                  "NUMBER")
-                 "" -- "Dpi (default 96)"
-
-    , Option "" ["eol"]
-                 (ReqArg
-                  (\arg opt ->
-                    case toLower <$> arg of
-                      "crlf"   -> return opt { optEol = CRLF }
-                      "lf"     -> return opt { optEol = LF }
-                      "native" -> return opt { optEol = Native }
-                      -- mac-syntax (cr) is not supported in ghc-base.
-                      _      -> E.throwIO $ PandocOptionError
-                                "--eol must be crlf, lf, or native")
-                  "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 ->
-                      case safeRead arg of
-                           Just t | t > 0 -> return opt { optColumns = t }
-                           _              -> E.throwIO $ PandocOptionError
-                                   "columns must be a number greater than 0")
-                 "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 "" ["toc-depth"]
-                 (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 -> return opt{ optHighlightStyle = Just arg })
-                 "STYLE|FILE")
-                 "" -- "Style for highlighted code"
-
-    , Option "" ["syntax-definition"]
-                (ReqArg
-                 (\arg opt -> return opt{ optSyntaxDefinitions = arg :
-                                             optSyntaxDefinitions opt })
-                 "FILE")
-                "" -- "Syntax definition (xml) file"
-
-    , Option "H" ["include-in-header"]
-                 (ReqArg
-                  (\arg opt -> return opt{ optIncludeInHeader =
-                                              arg : optIncludeInHeader opt,
-                                            optStandalone = True })
-                  "FILE")
-                 "" -- "File to include at end of header (implies -s)"
-
-    , Option "B" ["include-before-body"]
-                 (ReqArg
-                  (\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 "" ["resource-path"]
-                (ReqArg
-                  (\arg opt -> return opt { optResourcePath =
-                                   splitSearchPath arg })
-                   "SEARCHPATH")
-                  "" -- "Paths to search for images and other resources"
-
-    , Option "" ["request-header"]
-                 (ReqArg
-                  (\arg opt -> do
-                     let (key, val) = splitField arg
-                     return opt{ optRequestHeaders =
-                       (key, val) : optRequestHeaders opt })
-                  "NAME:VALUE")
-                 ""
-
-    , Option "" ["self-contained"]
-                 (NoArg
-                  (\opt -> return opt { optSelfContained = True,
-                                        optStandalone = True }))
-                 "" -- "Make slide shows include all the needed js and css"
-
-    , Option "" ["html-q-tags"]
-                 (NoArg
-                  (\opt ->
-                     return opt { optHtmlQTags = True }))
-                 "" -- "Use <q> tags for quotes in HTML"
-
-    , Option "" ["ascii"]
-                 (NoArg
-                  (\opt -> return opt { optAscii = True }))
-                 ""  -- "Use ascii characters only in HTML output"
-
-    , Option "" ["reference-links"]
-                 (NoArg
-                  (\opt -> return opt { optReferenceLinks = True } ))
-                 "" -- "Use reference links in parsing HTML"
-
-    , Option "" ["reference-location"]
-                 (ReqArg
-                  (\arg opt -> do
-                     action <- case arg of
-                            "block"    -> return EndOfBlock
-                            "section"  -> return EndOfSection
-                            "document" -> return EndOfDocument
-                            _        -> E.throwIO $ PandocOptionError
-                               ("Unknown option for reference-location: " ++ arg)
-                     return opt { optReferenceLocation = action })
-                  "block|section|document")
-                 "" -- "Accepting or reject MS Word track-changes.""
-
-    , Option "" ["atx-headers"]
-                 (NoArg
-                  (\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 }))
-                 "" -- "Use listings package for LaTeX code blocks"
-
-    , Option "i" ["incremental"]
-                 (NoArg
-                  (\opt -> return opt { optIncremental = True }))
-                 "" -- "Make list items display incrementally in Slidy/Slideous/S5"
-
-    , Option "" ["slide-level"]
-                 (ReqArg
-                  (\arg opt ->
-                      case safeRead arg of
-                           Just t | t >= 1 && t <= 6 ->
-                                    return opt { optSlideLevel = Just t }
-                           _      -> E.throwIO $ PandocOptionError
-                                    "slide level must be a number between 1 and 6")
-                 "NUMBER")
-                 "" -- "Force header level for slides"
-
-    , Option "" ["section-divs"]
-                 (NoArg
-                  (\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 "" ["email-obfuscation"]
-                 (ReqArg
-                  (\arg opt -> do
-                     method <- case arg of
-                            "references" -> return ReferenceObfuscation
-                            "javascript" -> return JavascriptObfuscation
-                            "none"       -> return NoObfuscation
-                            _            -> E.throwIO $ PandocOptionError
-                               ("Unknown obfuscation method: " ++ arg)
-                     return opt { optEmailObfuscation = method })
-                  "none|javascript|references")
-                 "" -- "Method for obfuscating email in HTML"
-
-     , Option "" ["id-prefix"]
-                  (ReqArg
-                   (\arg opt -> return opt { optIdentifierPrefix = arg })
-                   "STRING")
-                  "" -- "Prefix to add to automatically generated HTML identifiers"
-
-    , Option "T" ["title-prefix"]
-                 (ReqArg
-                  (\arg opt -> do
-                    let newvars = ("title-prefix", arg) : optVariables opt
-                    return opt { optVariables = newvars,
-                                 optStandalone = True })
-                  "STRING")
-                 "" -- "String to prefix to HTML window title"
-
-    , Option "c" ["css"]
-                 (ReqArg
-                  (\arg opt -> return opt{ optCss = arg : optCss opt })
-                  -- add new link to end, so it is included in proper order
-                  "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 ->
-                     return opt { optEpubSubdirectory = arg })
-                  "DIRNAME")
-                 "" -- "Name of subdirectory for epub content in OCF container"
-
-    , Option "" ["epub-cover-image"]
-                 (ReqArg
-                  (\arg opt ->
-                     return opt { optVariables =
-                                 ("epub-cover-image", arg) : optVariables opt })
-                  "FILE")
-                 "" -- "Path of epub cover image"
-
-    , Option "" ["epub-metadata"]
-                 (ReqArg
-                  (\arg opt -> return opt { optEpubMetadata = Just arg })
-                  "FILE")
-                 "" -- "Path of epub metadata file"
-
-    , Option "" ["epub-embed-font"]
-                 (ReqArg
-                  (\arg opt ->
-                     return opt{ optEpubFonts = arg : optEpubFonts opt })
-                  "FILE")
-                 "" -- "Directory of fonts to embed"
-
-    , Option "" ["epub-chapter-level"]
-                 (ReqArg
-                  (\arg opt ->
-                      case safeRead arg of
-                           Just t | t >= 1 && t <= 6 ->
-                                    return opt { optEpubChapterLevel = t }
-                           _      -> E.throwIO $ PandocOptionError
-                                    "chapter level must be a number between 1 and 6")
-                 "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"]
-                 (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"
-
-    , Option "" ["bibliography"]
-                 (ReqArg
-                  (\arg opt -> return opt{ optMetadata =
-                                 ("bibliography", arg) : optMetadata opt })
-                   "FILE")
-                 ""
-
-     , Option "" ["csl"]
-                 (ReqArg
-                  (\arg opt ->
-                     return opt{ optMetadata =
-                                   ("csl", arg) : optMetadata opt })
-                   "FILE")
-                 ""
-
-     , Option "" ["citation-abbreviations"]
-                 (ReqArg
-                  (\arg opt ->
-                     return opt{ optMetadata =
-                              ("citation-abbreviations", arg): optMetadata opt })
-                   "FILE")
-                 ""
-
-    , Option "" ["natbib"]
-                 (NoArg
-                  (\opt -> return opt { optCiteMethod = Natbib }))
-                 "" -- "Use natbib cite commands in LaTeX output"
-
-    , Option "" ["biblatex"]
-                 (NoArg
-                  (\opt -> return opt { optCiteMethod = Biblatex }))
-                 "" -- "Use biblatex cite commands in LaTeX output"
-
-    , Option "" ["mathml"]
-                 (NoArg
-                  (\opt ->
-                      return opt { optHTMLMathMethod = MathML }))
-                 "" -- "Use mathml for HTML math"
-
-    , Option "" ["webtex"]
-                 (OptArg
-                  (\arg opt -> do
-                      let url' = fromMaybe "https://latex.codecogs.com/png.latex?" arg
-                      return opt { optHTMLMathMethod = WebTeX url' })
-                  "URL")
-                 "" -- "Use web service for HTML math"
-
-    , Option "" ["mathjax"]
-                 (OptArg
-                  (\arg opt -> do
-                      let url' = fromMaybe (defaultMathJaxURL ++
-                                  "MathJax.js?config=TeX-AMS_CHTML-full") arg
-                      return opt { optHTMLMathMethod = MathJax url'})
-                  "URL")
-                 "" -- "Use MathJax for HTML math"
-
-    , Option "" ["katex"]
-                 (OptArg
-                  (\arg opt ->
-                      return opt
-                        { optHTMLMathMethod = KaTeX $
-                           fromMaybe defaultKaTeXURL arg })
-                  "URL")
-                  "" -- Use KaTeX for HTML Math
-
-    , Option "m" ["latexmathml", "asciimathml"]
-                 (OptArg
-                  (\arg opt -> do
-                      deprecatedOption "--latexmathml, --asciimathml, -m" ""
-                      return opt { optHTMLMathMethod = LaTeXMathML arg })
-                  "URL")
-                 "" -- "Use LaTeXMathML script in html output"
-
-    , Option "" ["mimetex"]
-                 (OptArg
-                  (\arg opt -> do
-                      deprecatedOption "--mimetex" ""
-                      let url' = case arg of
-                                      Just u  -> u ++ "?"
-                                      Nothing -> "/cgi-bin/mimetex.cgi?"
-                      return opt { optHTMLMathMethod = WebTeX url' })
-                  "URL")
-                 "" -- "Use mimetex for HTML math"
-
-    , Option "" ["jsmath"]
-                 (OptArg
-                  (\arg opt -> do
-                      deprecatedOption "--jsmath" ""
-                      return opt { optHTMLMathMethod = JsMath arg})
-                  "URL")
-                 "" -- "Use jsMath for HTML math"
-
-    , Option "" ["gladtex"]
-                 (NoArg
-                  (\opt -> do
-                      deprecatedOption "--gladtex" ""
-                      return opt { optHTMLMathMethod = GladTeX }))
-                 "" -- "Use gladtex for HTML math"
-
-    , Option "" ["abbreviations"]
-                (ReqArg
-                 (\arg opt -> return opt { optAbbreviations = Just arg })
-                "FILE")
-                "" -- "Specify file for custom abbreviations"
-
-    , Option "" ["trace"]
-                 (NoArg
-                  (\opt -> return opt { optTrace = True }))
-                 "" -- "Turn on diagnostic tracing in readers."
-
-    , Option "" ["dump-args"]
-                 (NoArg
-                  (\opt -> return opt { optDumpArgs = True }))
-                 "" -- "Print output filename and arguments to stdout."
-
-    , Option "" ["ignore-args"]
-                 (NoArg
-                  (\opt -> return opt { optIgnoreArgs = True }))
-                 "" -- "Ignore command-line arguments."
-
-    , Option "" ["verbose"]
-                 (NoArg
-                  (\opt -> return opt { optVerbosity = INFO }))
-                 "" -- "Verbose diagnostic output."
-
-    , Option "" ["quiet"]
-                 (NoArg
-                  (\opt -> return opt { optVerbosity = ERROR }))
-                 "" -- "Suppress warnings."
-
-    , Option "" ["fail-if-warnings"]
-                 (NoArg
-                  (\opt -> return opt { optFailIfWarnings = True }))
-                 "" -- "Exit with error status if there were  warnings."
-
-    , Option "" ["log"]
-                 (ReqArg
-                  (\arg opt -> return opt{ optLogFile = Just arg })
-                "FILE")
-                "" -- "Log messages in JSON format to this file."
-
-    , Option "" ["bash-completion"]
-                 (NoArg
-                  (\_ -> do
-                     ddir <- getDataDir
-                     tpl <- runIOorExplode $
-                              UTF8.toString <$>
-                                readDefaultDataFile "bash_completion.tpl"
-                     let optnames (Option shorts longs _ _) =
-                           map (\c -> ['-',c]) shorts ++
-                           map ("--" ++) longs
-                     let allopts = unwords (concatMap optnames options)
-                     UTF8.hPutStrLn stdout $ printf tpl allopts
-                         (unwords readersNames)
-                         (unwords writersNames)
-                         (unwords $ map fst highlightingStyles)
-                         ddir
-                     exitSuccess ))
-                 "" -- "Print bash completion script"
-
-    , Option "" ["list-input-formats"]
-                 (NoArg
-                  (\_ -> do
-                     mapM_ (UTF8.hPutStrLn stdout) readersNames
-                     exitSuccess ))
-                 ""
-
-    , Option "" ["list-output-formats"]
-                 (NoArg
-                  (\_ -> do
-                     mapM_ (UTF8.hPutStrLn stdout) writersNames
-                     exitSuccess ))
-                 ""
-
-    , Option "" ["list-extensions"]
-                 (OptArg
-                  (\arg _ -> do
-                     let exts = getDefaultExtensions (fromMaybe "markdown" arg)
-                     let showExt x = (if extensionEnabled x exts
-                                         then '+'
-                                         else '-') : drop 4 (show x)
-                     mapM_ (UTF8.hPutStrLn stdout . showExt)
-                               ([minBound..maxBound] :: [Extension])
-                     exitSuccess )
-                  "FORMAT")
-                 ""
-
-    , Option "" ["list-highlight-languages"]
-                 (NoArg
-                  (\_ -> do
-                     let langs = [ T.unpack (T.toLower (sShortname s))
-                                 | s <- M.elems defaultSyntaxMap
-                                 , sShortname s `notElem`
-                                    [T.pack "Alert", T.pack "Alert_indent"]
-                                 ]
-                     mapM_ (UTF8.hPutStrLn stdout) langs
-                     exitSuccess ))
-                 ""
-
-    , Option "" ["list-highlight-styles"]
-                 (NoArg
-                  (\_ -> do
-                     mapM_ (UTF8.hPutStrLn stdout . fst) highlightingStyles
-                     exitSuccess ))
-                 ""
-
-    , Option "v" ["version"]
-                 (NoArg
-                  (\_ -> do
-                     prg <- getProgName
-                     defaultDatadir <- E.catch
-                            (getAppUserDataDirectory "pandoc")
-                            (\e -> let _ = (e :: E.SomeException)
-                                   in  return "")
-                     UTF8.hPutStrLn stdout (prg ++ " " ++ pandocVersion ++
-                       compileInfo ++ "\nDefault user data directory: " ++
-                       defaultDatadir ++ copyrightMessage)
-                     exitSuccess ))
-                 "" -- "Print version"
-
-    , Option "h" ["help"]
-                 (NoArg
-                  (\_ -> do
-                     prg <- getProgName
-                     UTF8.hPutStr stdout (usageMessage prg options)
-                     exitSuccess ))
-                 "" -- "Show help"
-
-    ]
-
--- Returns usage message
-usageMessage :: String -> [OptDescr (Opt -> IO Opt)] -> String
-usageMessage programName = usageInfo (programName ++ " [OPTIONS] [FILES]")
-
-copyrightMessage :: String
-copyrightMessage = intercalate "\n" [
-  "",
-  "Copyright (C) 2006-2017 John MacFarlane",
-  "Web:  http://pandoc.org",
-  "This is free software; see the source for copying conditions.",
-  "There is no warranty, not even for merchantability or fitness",
-  "for a particular purpose." ]
-
-compileInfo :: String
-compileInfo =
-  "\nCompiled with pandoc-types " ++ VERSION_pandoc_types ++ ", texmath " ++
-  VERSION_texmath ++ ", skylighting " ++ VERSION_skylighting
-
-handleUnrecognizedOption :: String -> [String] -> [String]
-handleUnrecognizedOption "--smart" =
-  (("--smart/-S has been removed.  Use +smart or -smart extension instead.\n" ++
-    "For example: pandoc -f markdown+smart -t markdown-smart.") :)
-handleUnrecognizedOption "--normalize" =
-  ("--normalize has been removed.  Normalization is now automatic." :)
-handleUnrecognizedOption "-S" = handleUnrecognizedOption "--smart"
-handleUnrecognizedOption "--old-dashes" =
-  ("--old-dashes has been removed.  Use +old_dashes extension instead." :)
-handleUnrecognizedOption "--no-wrap" =
-  ("--no-wrap has been removed.  Use --wrap=none instead." :)
-handleUnrecognizedOption "--latex-engine" =
-  ("--latex-engine has been removed.  Use --pdf-engine instead." :)
-handleUnrecognizedOption "--latex-engine-opt" =
-  ("--latex-engine-opt has been removed.  Use --pdf-engine-opt instead." :)
-handleUnrecognizedOption "--chapters" =
-  ("--chapters has been removed. Use --top-level-division=chapter instead." :)
-handleUnrecognizedOption "--reference-docx" =
-  ("--reference-docx has been removed. Use --reference-doc instead." :)
-handleUnrecognizedOption "--reference-odt" =
-  ("--reference-odt has been removed. Use --reference-doc instead." :)
-handleUnrecognizedOption "--parse-raw" =
-  ("--parse-raw/-R has been removed. Use +raw_html or +raw_tex extension.\n" :)
-handleUnrecognizedOption "--epub-stylesheet" =
-  ("--epub-stylesheet has been removed. Use --css instead.\n" :)
-handleUnrecognizedOption "-R" = handleUnrecognizedOption "--parse-raw"
-handleUnrecognizedOption x =
-  (("Unknown option " ++ x ++ ".") :)
-
-uppercaseFirstLetter :: String -> String
-uppercaseFirstLetter (c:cs) = toUpper c : cs
-uppercaseFirstLetter []     = []
-
-readersNames :: [String]
-readersNames = sort (map fst (readers :: [(String, Reader PandocIO)]))
-
-writersNames :: [String]
-writersNames = sort (map fst (writers :: [(String, Writer PandocIO)]))
-
-splitField :: String -> (String, String)
-splitField s =
-  case break (`elem` ":=") s of
-       (k,_:v) -> (k,v)
-       (k,[])  -> (k,"true")
-
-baseWriterName :: String -> String
-baseWriterName = takeWhile (\c -> c /= '+' && c /= '-')
-
-deprecatedOption :: String -> String -> IO ()
-deprecatedOption o msg =
-  runIO (report $ Deprecated o msg) >>=
-    \r -> case r of
-       Right () -> return ()
-       Left e   -> E.throwIO e
-
--- see https://github.com/jgm/pandoc/pull/4083
--- using generic deriving caused long compilation times
-$(deriveJSON defaultOptions ''LineEnding)
-$(deriveJSON defaultOptions ''Opt)
+{-# LANGUAGE LambdaCase          #-}
+{-# LANGUAGE OverloadedStrings   #-}
+{-# LANGUAGE CPP                 #-}
+{-# LANGUAGE ScopedTypeVariables #-}
+{- |
+   Module      : Text.Pandoc.App
+   Copyright   : Copyright (C) 2006-2024 John MacFarlane
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : John MacFarlane <jgm@berkeley@edu>
+   Stability   : alpha
+   Portability : portable
+
+Does a pandoc conversion based on command-line options.
+-}
+module Text.Pandoc.App (
+            convertWithOpts
+          , handleOptInfo
+          , Opt(..)
+          , OptInfo(..)
+          , LineEnding(..)
+          , IpynbOutput (..)
+          , Filter(..)
+          , defaultOpts
+          , parseOptions
+          , parseOptionsFromArgs
+          , options
+          , applyFilters
+          , versionInfo
+          ) where
+import qualified Control.Exception as E
+import Control.Monad ( (>=>), when, forM, forM_ )
+import Control.Monad.Trans ( MonadIO(..) )
+import Control.Monad.Catch ( MonadMask )
+import Control.Monad.Except (throwError)
+import qualified Data.ByteString.Lazy as BL
+import Data.Maybe (fromMaybe, isJust, isNothing)
+import qualified Data.Set as Set
+import Data.Text (Text)
+import qualified Data.Text as T
+import qualified Data.Text.Lazy as TL
+import qualified Data.Text.Lazy.Encoding as TE
+import qualified Data.Text.Encoding.Error as TE
+import Data.Char (toLower)
+import System.Directory (doesDirectoryExist, createDirectory,
+                         createDirectoryIfMissing)
+import Codec.Archive.Zip (toArchiveOrFail,
+                          extractFilesFromArchive, ZipOption(..))
+import System.Exit (exitSuccess)
+import System.FilePath ( takeBaseName, takeExtension, takeDirectory)
+import System.IO (nativeNewline, stdout)
+import qualified System.IO as IO (Newline (..))
+import Data.Version (showVersion)
+import Text.Pandoc
+import Text.Pandoc.Builder (setMeta)
+import Text.Pandoc.MediaBag (mediaItems)
+import Text.Pandoc.Image (svgToPng)
+import Text.Pandoc.App.Opt (Opt (..), LineEnding (..), defaultOpts,
+                            IpynbOutput (..), OptInfo(..))
+import Text.Pandoc.App.CommandLineOptions (parseOptions, parseOptionsFromArgs,
+                                           options, handleOptInfo, versionInfo)
+import Text.Pandoc.App.Input (InputParameters (..), readInput)
+import Text.Pandoc.App.OutputSettings (OutputSettings (..), optToOutputSettings,
+                                       sandbox')
+import Text.Pandoc.Transforms (applyTransforms, filterIpynbOutput,
+                               headerShift, eastAsianLineBreakFilter)
+import Text.Collate.Lang (Lang (..), parseLang)
+import Text.Pandoc.Filter (Filter (JSONFilter, LuaFilter), Environment (..),
+                           applyFilters)
+import qualified Text.Pandoc.Format as Format
+import Text.Pandoc.PDF (makePDF)
+import Text.Pandoc.Scripting (ScriptingEngine (..), CustomComponents(..))
+import Text.Pandoc.SelfContained (makeSelfContained)
+import Text.Pandoc.Shared (tshow)
+import Text.Pandoc.Writers.Shared (lookupMetaString)
+import Text.Pandoc.Readers.Markdown (yamlToMeta)
+import qualified Text.Pandoc.UTF8 as UTF8
+#ifndef _WINDOWS
+import System.Posix.IO (stdOutput)
+import System.Posix.Terminal (queryTerminal)
+#endif
+
+convertWithOpts :: ScriptingEngine -> Opt -> IO ()
+convertWithOpts scriptingEngine opts = do
+  let outputFile = fromMaybe "-" (optOutputFile opts)
+  datadir <- case optDataDir opts of
+                  Nothing   -> do
+                    d <- defaultUserDataDir
+                    exists <- doesDirectoryExist d
+                    return $ if exists
+                                then Just d
+                                else Nothing
+                  mdatadir  -> return mdatadir
+
+  when (optDumpArgs opts) $
+    do UTF8.hPutStrLn stdout (T.pack outputFile)
+       mapM_ (UTF8.hPutStrLn stdout . T.pack)
+             (fromMaybe ["-"] $ optInputFiles opts)
+       exitSuccess
+
+#ifdef _WINDOWS
+  let istty = True
+#else
+  istty <- liftIO $ queryTerminal stdOutput
+#endif
+
+  res <- runIO $ convertWithOpts' scriptingEngine istty datadir opts
+  case res of
+    Left e -> E.throwIO e
+    Right (output, reports) -> do
+      case optLogFile opts of
+           Nothing      -> return ()
+           Just logfile -> BL.writeFile logfile (encodeLogMessages reports)
+      let isWarning msg = messageVerbosity msg == WARNING
+      when (optFailIfWarnings opts && any isWarning reports) $
+          E.throwIO PandocFailOnWarningError
+      let eol = case optEol opts of
+                     CRLF   -> IO.CRLF
+                     LF     -> IO.LF
+                     Native -> nativeNewline
+      let outputFileDir = takeDirectory outputFile
+      createDirectoryIfMissing True outputFileDir
+      case output of
+        TextOutput t    -> writerFn eol outputFile t
+        BinaryOutput bs -> writeFnBinary outputFile bs
+        ZipOutput bs
+          | null (takeExtension outputFile)
+          , outputFile /= "-" -> do
+             -- create directory and unzip
+             createDirectory outputFile -- will fail if directory exists
+             let zipopts = [OptRecursive, OptDestination outputFile] ++
+                           [OptVerbose | optVerbosity opts == INFO]
+             case toArchiveOrFail bs of
+               Right archive -> extractFilesFromArchive zipopts archive
+               Left e -> E.throwIO $ PandocShouldNeverHappenError $ T.pack e
+          | otherwise -> writeFnBinary outputFile bs
+
+convertWithOpts' :: (PandocMonad m, MonadIO m, MonadMask m)
+                 => ScriptingEngine
+                 -> Bool
+                 -> Maybe FilePath
+                 -> Opt
+                 -> m (PandocOutput, [LogMessage])
+convertWithOpts' scriptingEngine istty datadir opts = do
+  configureCommonState datadir opts
+  let outputFile = fromMaybe "-" (optOutputFile opts)
+  let filters = optFilters opts
+  let sources = case optInputFiles opts of
+                     Just xs | not (optIgnoreArgs opts) -> xs
+                     _ -> ["-"]
+
+  let defFlavor fmt = Format.FlavoredFormat fmt mempty
+  -- assign reader and writer based on options and filenames
+  flvrd@(Format.FlavoredFormat readerNameBase _extsDiff) <-
+    case optFrom opts of
+      Just f  -> Format.parseFlavoredFormat f
+      Nothing -> case Format.formatFromFilePaths sources of
+        Just f' -> return f'
+        Nothing | sources == ["-"] -> return $ defFlavor "markdown"
+                | otherwise -> do
+                    report $ CouldNotDeduceFormat
+                      (map (T.pack . takeExtension) sources) "markdown"
+                    return $ defFlavor "markdown"
+
+  let makeSandboxed pureReader =
+       case pureReader of
+            TextReader r
+              -> TextReader $ \o t -> sandbox' opts (r o t)
+            ByteStringReader r
+              -> ByteStringReader $ \o t -> sandbox' opts (r o t)
+
+  (reader, readerExts) <-
+    if ".lua" `T.isSuffixOf` readerNameBase
+       then do
+            let scriptPath = T.unpack readerNameBase
+            components <- engineLoadCustom scriptingEngine scriptPath
+            r <- case customReader components of
+                   Nothing -> throwError $ PandocAppError $
+                               readerNameBase <> " does not contain a custom reader"
+                   Just r -> return r
+            let extsConf = fromMaybe mempty (customExtensions components)
+            rexts <- Format.applyExtensionsDiff extsConf flvrd
+            return (r, rexts)
+       else if optSandbox opts
+               then case runPure (getReader flvrd) of
+                      Left e -> throwError e
+                      Right (r, rexts) -> return (makeSandboxed r, rexts)
+               else getReader flvrd
+
+  outputSettings <- optToOutputSettings scriptingEngine opts
+  let format = outputFormat outputSettings
+  let writer = outputWriter outputSettings
+  let writerOptions = outputWriterOptions outputSettings
+
+  -- whether we are targeting PDF.
+  let pdfOutput = map toLower (takeExtension outputFile) == ".pdf" ||
+                  optTo opts == Just "pdf"
+  -- whether standalone output should be produced.
+  let bibOutput = format `elem` ["bibtex", "biblatex", "csljson"]
+  let standalone = isJust (writerTemplate writerOptions) || bibOutput
+
+  --
+  -- Sanity checks
+  --
+  when (pdfOutput && readerNameBase == "latex") $
+    case optInputFiles opts of
+      Just (inputFile:_) -> report $ UnusualConversion $ T.pack $
+        "to convert a .tex file to PDF, you get better results by using pdflatex "
+          <> "(or lualatex or xelatex) directly, try `pdflatex " <> inputFile
+          <> "` instead of `pandoc " <> inputFile <> " -o " <> outputFile <> "`."
+      _ -> return ()
+
+  -- We don't want to send output to the terminal if the user
+  -- does 'pandoc -t docx input.txt'; though we allow them to
+  -- force this with '-o -'.  On posix systems, we detect
+  -- when stdout is being piped and allow output to stdout
+  -- in that case, but on Windows we can't.
+  when ((pdfOutput || not (isTextFormat format)) &&
+           istty && isNothing ( optOutputFile opts)) $
+    throwError $ PandocAppError $
+            "Cannot write " <> (if pdfOutput then "pdf" else format) <>
+            " output to terminal.\n" <>
+            "Specify an output file using the -o option, or " <>
+            "use '-o -' to force output to stdout."
+
+  when (readerNameBase == "markdown_github" ||
+        format == "markdown_github") $
+    report $ Deprecated "markdown_github" "Use gfm instead."
+
+  abbrevs <- readAbbreviations (optAbbreviations opts)
+  let readerOpts = def{
+          readerStandalone = standalone
+        , readerColumns = optColumns opts
+        , readerTabStop = optTabStop opts
+        , readerIndentedCodeClasses = optIndentedCodeClasses opts
+        , readerDefaultImageExtension = optDefaultImageExtension opts
+        , readerTrackChanges = optTrackChanges opts
+        , readerAbbreviations = abbrevs
+        , readerExtensions = readerExts
+        , readerStripComments = optStripComments opts
+        , readerTypstInputs = optTypstInputs opts
+        }
+
+  metadataFromFile <- getMetadataFromFiles readerNameBase readerOpts
+                         (optMetadataFiles opts)
+
+  let transforms = (case optShiftHeadingLevelBy opts of
+                        0             -> id
+                        x             -> (headerShift x :)) .
+                   (if extensionEnabled Ext_east_asian_line_breaks
+                          readerExts &&
+                       not (extensionEnabled Ext_east_asian_line_breaks
+                            (writerExtensions writerOptions) &&
+                            writerWrapText writerOptions == WrapPreserve)
+                       then (eastAsianLineBreakFilter :)
+                       else id) .
+                   (case optIpynbOutput opts of
+                     _ | readerNameBase /= "ipynb" -> id
+                     IpynbOutputAll  -> id
+                     IpynbOutputNone -> (filterIpynbOutput Nothing :)
+                     IpynbOutputBest -> (filterIpynbOutput (Just $
+                                   if htmlFormat format
+                                      then Format "html"
+                                      else
+                                        case format of
+                                          "latex"  -> Format "latex"
+                                          "beamer" -> Format "latex"
+                                          _        -> Format format) :))
+                   $ []
+
+  let isPandocCiteproc (JSONFilter f) = takeBaseName f == "pandoc-citeproc"
+      isPandocCiteproc _              = False
+
+  when (any isPandocCiteproc filters) $
+    report $ Deprecated "pandoc-citeproc filter"
+             "Use --citeproc instead."
+
+  let cslMetadata =
+        maybe id (setMeta "csl") (optCSL opts) .
+        (case optBibliography opts of
+           [] -> id
+           xs -> setMeta "bibliography" xs) .
+        maybe id (setMeta "citation-abbreviations")
+                       (optCitationAbbreviations opts) $ mempty
+
+  let filterEnv = Environment readerOpts writerOptions
+
+  let inputParams = InputParameters
+        { inputReader = reader
+        , inputReaderName = readerNameBase
+        , inputReaderOptions = readerOpts
+        , inputSources = sources
+        , inputFileScope = optFileScope opts
+        , inputSpacesPerTab = if optPreserveTabs opts
+                              then Nothing
+                              else Just (optTabStop opts)
+        }
+
+  doc <- readInput inputParams
+          >>= ( return . adjustMetadata (metadataFromFile <>)
+            >=> return . adjustMetadata (<> optMetadata opts)
+            >=> return . adjustMetadata (<> cslMetadata)
+            >=> applyFilters scriptingEngine filterEnv filters [T.unpack format]
+            >=> applyTransforms transforms
+            >=> (if not (optSandbox opts) &&
+                    (isJust (optExtractMedia opts)
+                     || format == "docx") -- for fallback pngs
+                 then fillMediaBag
+                 else return)
+            >=> maybe return extractMedia (optExtractMedia opts)
+            )
+
+  when (format == "docx" && not (optSandbox opts)) $ do
+    createPngFallbacks (writerDpi writerOptions)
+
+  output <- case writer of
+    ByteStringWriter f
+      | format == "chunkedhtml" -> ZipOutput <$> f writerOptions doc
+      | otherwise -> BinaryOutput <$> f writerOptions doc
+    TextWriter f -> case outputPdfProgram outputSettings of
+      Just pdfProg | pdfOutput -> do
+              res <- makePDF pdfProg (optPdfEngineOpts opts) f
+                      writerOptions doc
+              case res of
+                   Right pdf -> return $ BinaryOutput pdf
+                   Left err' -> throwError $ PandocPDFError $
+                                   TL.toStrict (TE.decodeUtf8With TE.lenientDecode err')
+
+      _ -> do
+              let ensureNl t
+                    | standalone = t
+                    | T.null t || T.last t /= '\n' = t <> T.singleton '\n'
+                    | otherwise = t
+              textOutput <- ensureNl <$> f writerOptions doc
+              if htmlFormat format &&
+                  (optSelfContained opts || optEmbedResources opts)
+                 then if optSandbox opts
+                         then sandbox' opts $
+                              TextOutput <$> makeSelfContained textOutput
+                         else TextOutput <$> makeSelfContained textOutput
+                 else return $ TextOutput textOutput
+  reports <- getLog
+  return (output, reports)
+
+data PandocOutput =
+      TextOutput Text
+    | BinaryOutput BL.ByteString
+    | ZipOutput BL.ByteString
+  deriving (Show)
+
+-- | Configure the common state
+configureCommonState :: PandocMonad m => Maybe FilePath -> Opt -> m ()
+configureCommonState datadir opts = do
+  setUserDataDir datadir
+  setTrace (optTrace opts)
+  setVerbosity (optVerbosity opts)
+  setResourcePath (optResourcePath opts)
+  setInputFiles (fromMaybe ["-"] (optInputFiles opts))
+  setOutputFile (optOutputFile opts)
+  setNoCheckCertificate (optNoCheckCertificate opts)
+
+  setRequestHeader "User-Agent" ("pandoc/" <> T.pack (showVersion pandocVersion))
+  mapM_ (uncurry setRequestHeader) (optRequestHeaders opts)
+
+  case lookupMetaString "lang" (optMetadata opts) of
+    ""      -> setTranslations $ Lang "en" Nothing (Just "US") [] [] []
+    l       -> case parseLang l of
+                 Left _   -> report $ InvalidLang l
+                 Right l' -> setTranslations l'
+
+-- | Retrieves the set of abbreviations to be used by pandoc. These currently
+-- only affect the Markdown reader.
+readAbbreviations :: PandocMonad m => Maybe FilePath -> m (Set.Set Text)
+readAbbreviations mbfilepath =
+  (case mbfilepath of
+    Nothing -> readDataFile "abbreviations"
+    Just f  -> readFileStrict f)
+    >>= fmap (Set.fromList . filter (not . T.null) . T.lines) .
+         toTextM (fromMaybe mempty mbfilepath)
+
+createPngFallbacks :: (PandocMonad m, MonadIO m) => Int -> m ()
+createPngFallbacks dpi = do
+  -- create fallback pngs for svgs
+  items <- mediaItems <$> getMediaBag
+  forM_ items $ \(fp, mt, bs) ->
+    case T.takeWhile (/=';') mt of
+      "image/svg+xml" -> do
+        res <- svgToPng dpi bs
+        case res of
+          Right bs' -> do
+            let fp' = fp <> ".png"
+            insertMedia fp' (Just "image/png") bs'
+          Left e -> report $ CouldNotConvertImage (T.pack fp) (tshow e)
+      _ -> return ()
+
+getMetadataFromFiles :: PandocMonad m
+                     => Text -> ReaderOptions -> [FilePath] -> m Meta
+getMetadataFromFiles readerFormat readerOpts = \case
+  []    -> return mempty
+  paths -> mconcat <$> do
+    -- If format is markdown or commonmark, use the enabled extensions,
+    -- otherwise treat metadata as pandoc markdown (see #7926, #6832)
+    let readerOptsMeta =
+          if readerFormat `elem` ["markdown", "commonmark"]
+          then readerOpts
+          else readerOpts{ readerExtensions = pandocExtensions }
+    forM paths $ \path -> do
+      raw <- readMetadataFile path
+      yamlToMeta readerOptsMeta (Just path) raw
+
+htmlFormat :: Text -> Bool
+htmlFormat = (`elem` ["html","html4","html5","s5","slidy",
+                      "slideous","dzslides","revealjs"])
+
+isTextFormat :: Text -> Bool
+isTextFormat s = s `notElem` ["odt","docx","epub2","epub3","epub","pptx"]
+
+adjustMetadata :: (Meta -> Meta) -> Pandoc -> Pandoc
+adjustMetadata f (Pandoc meta bs) = Pandoc (f meta) bs
+
+writeFnBinary :: FilePath -> BL.ByteString -> IO ()
+writeFnBinary "-" = BL.putStr
+writeFnBinary f   = BL.writeFile (UTF8.encodePath f)
+
+writerFn :: IO.Newline -> FilePath -> Text -> IO ()
+writerFn eol "-" = UTF8.putStrWith eol
+writerFn eol f   = UTF8.writeFileWith eol f
diff --git a/src/Text/Pandoc/App/CommandLineOptions.hs b/src/Text/Pandoc/App/CommandLineOptions.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/App/CommandLineOptions.hs
@@ -0,0 +1,1315 @@
+{-# LANGUAGE CPP                 #-}
+{-# LANGUAGE ScopedTypeVariables #-}
+{-# LANGUAGE TupleSections       #-}
+{-# LANGUAGE OverloadedStrings   #-}
+{-# LANGUAGE FlexibleContexts    #-}
+{- |
+   Module      : Text.Pandoc.App.CommandLineOptions
+   Copyright   : Copyright (C) 2006-2024 John MacFarlane
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : John MacFarlane <jgm@berkeley@edu>
+   Stability   : alpha
+   Portability : portable
+
+Does a pandoc conversion based on command-line options.
+-}
+module Text.Pandoc.App.CommandLineOptions (
+            parseOptions
+          , parseOptionsFromArgs
+          , handleOptInfo
+          , options
+          , engines
+          , setVariable
+          , versionInfo
+          ) where
+import Control.Monad.Trans
+import Control.Monad.State.Strict
+import Data.Containers.ListUtils (nubOrd)
+import Data.Aeson (eitherDecode)
+import Data.Aeson.Encode.Pretty (encodePretty', Config(..), keyOrder,
+         defConfig, Indent(..), NumberFormat(..))
+import Data.Bifunctor (second)
+import Data.Char (toLower)
+import Data.List (intercalate, sort)
+import qualified Data.List as L
+#ifdef _WINDOWS
+import Data.List (isPrefixOf)
+#endif
+import Data.Maybe (fromMaybe, isJust)
+import Data.Text (Text)
+import Safe (tailDef)
+import Skylighting (Syntax (..), defaultSyntaxMap)
+import System.Console.GetOpt
+import System.Environment (getArgs, getProgName)
+import System.Exit (exitSuccess)
+import System.FilePath
+import System.IO (stdout)
+import Text.DocTemplates (Context (..), ToContext (toVal), Val (..))
+import Text.Pandoc
+import Text.Pandoc.Builder (setMeta)
+import Data.Version (showVersion)
+import Text.Pandoc.App.Opt (Opt (..), LineEnding (..), IpynbOutput (..),
+                            DefaultsState (..), applyDefaults,
+                            fullDefaultsPath, OptInfo(..))
+import Text.Pandoc.Filter (Filter (..))
+import Text.Pandoc.Highlighting (highlightingStyles, lookupHighlightingStyle)
+import Text.Pandoc.Scripting (ScriptingEngine (..), customTemplate)
+import Text.Pandoc.Shared (safeStrRead)
+import Text.Printf
+import qualified Control.Exception as E
+import Control.Monad.Except (ExceptT(..), runExceptT, throwError)
+import qualified Data.ByteString as BS
+import qualified Data.ByteString.Lazy as B
+import qualified Data.Map as M
+import qualified Data.Set as Set
+import qualified Data.Text as T
+import qualified Text.Pandoc.UTF8 as UTF8
+
+parseOptions :: [OptDescr (Opt -> ExceptT OptInfo IO Opt)]
+             -> Opt -> IO (Either OptInfo Opt)
+parseOptions options' defaults = do
+  rawArgs <- liftIO getArgs
+  prg <- liftIO getProgName
+  parseOptionsFromArgs options' defaults prg rawArgs
+
+parseOptionsFromArgs
+  :: [OptDescr (Opt -> ExceptT OptInfo IO Opt)]
+  -> Opt -> String -> [String] -> IO (Either OptInfo Opt)
+parseOptionsFromArgs options' defaults prg rawArgs = do
+  let (actions, args, unrecognizedOpts, errors) =
+           getOpt' Permute options' (preprocessArgs rawArgs)
+
+  let unknownOptionErrors =
+       foldr (handleUnrecognizedOption . takeWhile (/= '=')) []
+       unrecognizedOpts
+
+  let mbArgs = case args of
+                 [] -> Nothing
+                 xs -> Just xs
+
+  let adjustOpts opts =
+           opts{ optInputFiles =
+                   map normalizePath <$> (optInputFiles opts <> mbArgs)
+               , optStandalone = -- certain other options imply standalone
+                   optStandalone opts ||
+                     isJust (optTemplate opts) ||
+                     optSelfContained opts ||
+                     not (null (optIncludeInHeader opts)) ||
+                     not (null (optIncludeBeforeBody opts)) ||
+                     not (null (optIncludeAfterBody opts)) }
+
+  if (null errors && null unknownOptionErrors)
+     then -- thread option data structure through all supplied option actions
+       runExceptT $ adjustOpts <$> (L.foldl' (>>=) (return defaults) actions)
+     else return $ Left $ OptError $ PandocOptionError $ T.pack $
+             concat errors ++ unlines unknownOptionErrors ++
+             ("Try " ++ prg ++ " --help for more information.")
+
+-- | React to an 'OptInfo' by printing the requested information
+-- and exiting or (if there was a parsing error) raising an error.
+handleOptInfo :: ScriptingEngine -> OptInfo -> IO ()
+handleOptInfo engine info = E.handle (handleError . Left) $ do
+  case info of
+    BashCompletion -> do
+      datafiles <- getDataFileNames
+      tpl <- runIOorExplode $
+               UTF8.toString <$>
+                 readDefaultDataFile "bash_completion.tpl"
+      let optnames (Option shorts longs _ _) =
+            map (\c -> ['-',c]) shorts ++
+            map ("--" ++) longs
+      let allopts = unwords (concatMap optnames options)
+      UTF8.hPutStrLn stdout $ T.pack $ printf tpl allopts
+          (T.unpack $ T.unwords readersNames)
+          (T.unpack $ T.unwords writersNames)
+          (T.unpack $ T.unwords $ map fst highlightingStyles)
+          (unwords datafiles)
+    ListInputFormats -> mapM_ (UTF8.hPutStrLn stdout) readersNames
+    ListOutputFormats -> mapM_ (UTF8.hPutStrLn stdout) writersNames
+    ListExtensions mbfmt -> do
+      let formatName = fromMaybe "markdown" mbfmt
+      let allExts = getAllExtensions formatName
+      if formatName `notElem`
+          (map fst (readers :: [(Text, Reader PandocPure)]) ++
+           map fst (writers :: [(Text, Writer PandocPure)]))
+         then E.throwIO $ PandocOptionError $ formatName <>
+                " is not a recognized reader or writer format"
+         else do
+           let defExts = getDefaultExtensions formatName
+           let showExt x =
+                (if extensionEnabled x defExts
+                    then '+'
+                    else if extensionEnabled x allExts
+                            then '-'
+                            else ' ') : drop 4 (show x)
+           mapM_ (UTF8.hPutStrLn stdout . T.pack . showExt)
+              (extensionsToList allExts)
+    ListHighlightLanguages -> do
+      let langs = [ T.unpack (T.toLower (sShortname s))
+                  | s <- M.elems defaultSyntaxMap
+                  , sShortname s `notElem`
+                     [T.pack "Alert", T.pack "Alert_indent"]
+                  ]
+      mapM_ (UTF8.hPutStrLn stdout . T.pack) (sort langs)
+    ListHighlightStyles -> do
+      mapM_ (UTF8.hPutStrLn stdout . fst) highlightingStyles
+    PrintDefaultTemplate mbout fmt -> do
+      let write = maybe (UTF8.hPutStr stdout) (UTF8.writeFile) mbout
+
+      templ <- runIO $
+               case splitExtension (T.unpack fmt) of
+                    (_, "") -> do
+                      -- built-in format
+                      setUserDataDir Nothing
+                      getDefaultTemplate fmt
+                    _ -> do
+                      -- format looks like a filepath => custom writer
+                      components <- engineLoadCustom engine (T.unpack fmt)
+                      case customTemplate components of
+                        Just t  -> pure t
+                        Nothing -> E.throw $ PandocNoTemplateError fmt
+      case templ of
+           Right t
+             | T.null t -> -- e.g. for docx, odt, json:
+                 E.throwIO $ PandocCouldNotFindDataFileError $ T.pack
+                   ("templates/default." ++ T.unpack fmt)
+             | otherwise -> write t
+           Left e  -> E.throwIO e
+    PrintDefaultDataFile mbout f -> do
+      let write = maybe BS.putStr BS.writeFile mbout
+      runIOorExplode $ readDefaultDataFile (T.unpack f) >>= liftIO . write
+    PrintHighlightStyle mbout styleName -> do
+       let write = maybe B.putStr B.writeFile mbout
+       sty <- runIOorExplode $ lookupHighlightingStyle (T.unpack styleName)
+       write $ 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
+    VersionInfo -> versionInfo [] Nothing ""
+    Help -> do
+      prg <- getProgName
+      mapM_ (UTF8.hPutStrLn stdout . T.stripEnd . T.pack) $
+        lines $ usageMessage prg options
+    OptError e -> E.throwIO e
+  exitSuccess
+
+-- | Supported LaTeX engines; the first item is used as default engine
+-- when going through LaTeX.
+latexEngines :: [String]
+latexEngines  = [ "pdflatex", "lualatex", "xelatex", "latexmk", "tectonic"
+                , "pdflatex-dev", "lualatex-dev" ]
+
+-- | Supported HTML PDF engines; the first item is used as default
+-- engine when going through HTML.
+htmlEngines :: [String]
+htmlEngines  = ["weasyprint", "wkhtmltopdf", "pagedjs-cli", "prince"]
+
+engines :: [(Text, String)]
+engines = map ("html",) htmlEngines ++
+          map ("html5",) htmlEngines ++
+          map ("latex",) latexEngines ++
+          map ("beamer",) latexEngines ++
+          [ ("ms", "groff")
+          , ("ms", "pdfroff")
+          , ("typst", "typst")
+          , ("context", "context")
+          ]
+
+pdfEngines :: [String]
+pdfEngines = nubOrd $ map snd engines
+
+-- For motivation see #8956.  We want to allow things like `-si` without
+-- causing the `i` to be parsed as an optional boolean argument of `-s`.
+-- This is for backwards compatibility given the addition of optional
+-- boolean arguments in #8879.
+preprocessArgs :: [String] -> [String]
+preprocessArgs [] = []
+preprocessArgs ("--":xs) = "--" : xs -- a bare '--' ends option parsing
+-- note that -strue is interpreted as -strue while
+-- -stmarkdown is interpreted as -s -tmarkdown
+preprocessArgs (('-':c:d:cs):xs)
+  | isShortBooleanOpt c
+  , case toLower <$> (d:cs) of
+      "true" -> True
+      "false" -> True
+      _ -> False
+    = ('-':c:d:cs) : preprocessArgs xs
+  | isShortBooleanOpt c
+  , isShortOpt d = splitArg (c:d:cs) ++ preprocessArgs xs
+preprocessArgs (x:xs) = x : preprocessArgs xs
+
+isShortBooleanOpt :: Char -> Bool
+isShortBooleanOpt = (`Set.member` shortBooleanOpts)
+ where
+  shortBooleanOpts =
+     Set.fromList [c | Option [c] _ (OptArg _ "true|false") _ <- options]
+
+isShortOpt :: Char -> Bool
+isShortOpt = (`Set.member` shortOpts)
+ where
+  shortOpts = Set.fromList $ concat [cs | Option cs _ _ _ <- options]
+
+splitArg :: String -> [String]
+splitArg (c:d:cs)
+  | isShortBooleanOpt c
+  , isShortOpt d
+  = ['-',c] : splitArg (d:cs)
+splitArg (c:cs) = ['-':c:cs]
+splitArg [] = []
+
+-- | A list of functions, each transforming the options data structure
+--   in response to a command-line option.
+options :: [OptDescr (Opt -> ExceptT OptInfo IO Opt)]
+options =
+    [ Option "fr" ["from","read"]
+                 (ReqArg
+                  (\arg opt -> return opt { optFrom = Just $ T.pack arg })
+                  "FORMAT")
+                 ""
+
+    , Option "tw" ["to","write"]
+                 (ReqArg
+                  (\arg opt -> return opt { optTo = Just $ T.pack arg })
+                  "FORMAT")
+                 ""
+
+    , Option "o" ["output"]
+                 (ReqArg
+                  (\arg opt -> return opt { optOutputFile =
+                                             Just (normalizePath arg) })
+                  "FILE")
+                 "" -- "Name of output file"
+
+    , 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
+                     let (key, val) = splitField arg
+                     return opt{ optMetadata = addMeta key val $
+                                                 optMetadata opt })
+                  "KEY[=VALUE]")
+                 ""
+
+    , Option "" ["metadata-file"]
+                 (ReqArg
+                  (\arg opt -> return opt{ optMetadataFiles =
+                      optMetadataFiles opt ++ [normalizePath arg] })
+                  "FILE")
+                 ""
+
+    , Option "d" ["defaults"]
+                 (ReqArg
+                  (\arg opt -> do
+                     res <- liftIO $ runIO $ do
+                       let defsState =
+                             DefaultsState { curDefaults = Nothing,
+                                             inheritanceGraph = [] }
+                       fp <- fullDefaultsPath (optDataDir opt) arg
+                       evalStateT (applyDefaults opt fp) defsState
+                     case res of
+                       Left e -> optError e
+                       Right x -> return x
+                  )
+                  "FILE")
+                ""
+
+    , Option "" ["file-scope"]
+                 (OptArg
+                  (\arg opt -> do
+                        boolValue <- readBoolFromOptArg "--file-scope" arg
+                        return opt { optFileScope = boolValue })
+                  "true|false")
+                 "" -- "Parse input files before combining"
+
+    , Option "" ["sandbox"]
+                 (OptArg
+                  (\arg opt -> do
+                        boolValue <- readBoolFromOptArg "--sandbox" arg
+                        return opt { optSandbox = boolValue })
+                  "true|false")
+                 ""
+
+     , Option "s" ["standalone"]
+                 (OptArg
+                  (\arg opt -> do
+                        boolValue <- readBoolFromOptArg "--standalone/-s" arg
+                        return opt { optStandalone = boolValue })
+                  "true|false")
+                 "" -- "Include needed header and footer on output"
+
+    , Option "" ["template"]
+                 (ReqArg
+                  (\arg opt ->
+                     return opt{ optTemplate = Just (normalizePath arg) })
+                  "FILE")
+                 "" -- "Use custom template"
+
+    , Option "V" ["variable"]
+                 (ReqArg
+                  (\arg opt -> do
+                     let (key, val) = splitField arg
+                     return opt{ optVariables =
+                                  setVariable (T.pack key) (T.pack val) $
+                                    optVariables opt })
+                  "KEY[=VALUE]")
+                 ""
+
+    , Option "" ["variable-json"]
+                 (ReqArg
+                  (\arg opt -> do
+                     let (key, json) = splitField arg
+                     case eitherDecode (B.fromStrict . UTF8.fromString $ json) of
+                       Right (val :: Val Text) ->
+                         return opt{ optVariables =
+                                      let Context m = optVariables opt
+                                       in Context $ M.insert (T.pack key) val m }
+                           -- note that this replaces any existing value, which
+                           -- is different from what --variable does
+                       Left err'  -> optError $ PandocOptionError $
+                          "Could not parse '" <> T.pack json <> "' as JSON:\n" <>
+                           T.pack err')
+                  "KEY[:JSON]")
+                 ""
+
+    , Option "" ["wrap"]
+                 (ReqArg
+                  (\arg opt ->
+                    case arg of
+                      "auto" -> return opt{ optWrap = WrapAuto }
+                      "none" -> return opt{ optWrap = WrapNone }
+                      "preserve" -> return opt{ optWrap = WrapPreserve }
+                      _      -> optError $ PandocOptionError
+                                 "--wrap must be auto, none, or preserve")
+                 "auto|none|preserve")
+                 "" -- "Option for wrapping text in output"
+
+    , Option "" ["ascii"]
+                 (OptArg
+                  (\arg opt -> do
+                        boolValue <- readBoolFromOptArg "--ascii" arg
+                        return opt { optAscii = boolValue })
+                  "true|false")
+                 ""  -- "Prefer ASCII output"
+
+    , Option "" ["toc", "table-of-contents"]
+                (OptArg
+                 (\arg opt -> do
+                        boolValue <- readBoolFromOptArg "--toc/--table-of-contents" arg
+                        return opt { optTableOfContents = boolValue })
+                 "true|false")
+               "" -- "Include table of contents"
+
+    , Option "" ["toc-depth"]
+                 (ReqArg
+                  (\arg opt ->
+                      case safeStrRead arg of
+                           Just t | t >= 1 && t <= 6 ->
+                                    return opt { optTOCDepth = t }
+                           _ -> optError $ PandocOptionError
+                                "Argument of --toc-depth must be a number 1-6")
+                 "NUMBER")
+                 "" -- "Number of levels to include in TOC"
+
+    , Option "" ["lof", "list-of-figures"]
+                (OptArg
+                 (\arg opt -> do
+                        boolValue <- readBoolFromOptArg "--lof/--list-of-figures" arg
+                        return opt { optListOfFigures = boolValue })
+                 "true|false")
+               "" -- "Include list of figures"
+
+    , Option "" ["lot", "list-of-tables"]
+                (OptArg
+                 (\arg opt -> do
+                        boolValue <- readBoolFromOptArg "--lot/--list-of-tables" arg
+                        return opt { optListOfTables = boolValue })
+                 "true|false")
+               "" -- "Include list of tables"
+
+    , Option "N" ["number-sections"]
+                  (OptArg
+                   (\arg opt -> do
+                        boolValue <- readBoolFromOptArg "--number-sections/-N" arg
+                        return opt { optNumberSections = boolValue })
+                  "true|false")
+                 "" -- "Number sections"
+
+    , Option "" ["number-offset"]
+                 (ReqArg
+                  (\arg opt ->
+                      case safeStrRead ("[" <> arg <> "]") of
+                           Just ns -> return opt { optNumberOffset = ns,
+                                                   optNumberSections = True }
+                           _      -> optError $ PandocOptionError
+                                       "could not parse argument of --number-offset")
+                 "NUMBERS")
+                 "" -- "Starting number for sections, subsections, etc."
+
+    , Option "" ["top-level-division"]
+                 (ReqArg
+                  (\arg opt ->
+                      case arg of
+                        "section" -> return opt{ optTopLevelDivision =
+                                        TopLevelSection }
+                        "chapter" -> return opt{ optTopLevelDivision =
+                                        TopLevelChapter }
+                        "part"    -> return opt{ optTopLevelDivision =
+                                        TopLevelPart }
+                        "default" -> return opt{ optTopLevelDivision =
+                                        TopLevelDefault }
+                        _ -> optError $ PandocOptionError $
+                                "Argument of --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 ++
+                                    optResourcePath opt })
+                   "SEARCHPATH")
+                  "" -- "Paths to search for images and other resources"
+
+    , Option "H" ["include-in-header"]
+                 (ReqArg
+                  (\arg opt -> return opt{ optIncludeInHeader =
+                                             optIncludeInHeader opt ++
+                                             [normalizePath arg] })
+                  "FILE")
+                 "" -- "File to include at end of header (implies -s)"
+
+    , Option "B" ["include-before-body"]
+                 (ReqArg
+                  (\arg opt -> return opt{ optIncludeBeforeBody =
+                                            optIncludeBeforeBody opt ++
+                                            [normalizePath arg] })
+                  "FILE")
+                 "" -- "File to include before document body"
+
+    , Option "A" ["include-after-body"]
+                 (ReqArg
+                  (\arg opt -> return opt{ optIncludeAfterBody =
+                                            optIncludeAfterBody opt ++
+                                            [normalizePath arg] })
+                  "FILE")
+                 "" -- "File to include after document body"
+
+    , Option "" ["no-highlight"]
+                (NoArg
+                 (\opt -> do
+                     deprecatedOption "--no-highlight"
+                       "Use --syntax-highlighting=none instead."
+                     return opt { optSyntaxHighlighting = NoHighlightingString }))
+                 "" -- "Don't highlight source code"
+
+    , Option "" ["highlight-style"]
+                (ReqArg
+                 (\arg opt -> do
+                     deprecatedOption "--highlight-style"
+                       "Use --syntax-highlighting instead."
+                     return opt{ optSyntaxHighlighting =
+                                 T.pack $ normalizePath arg })
+                 "STYLE|FILE")
+                 "" -- "Style for highlighted code"
+
+    , Option "" ["syntax-definition"]
+                (ReqArg
+                 (\arg opt ->
+                   return opt{ optSyntaxDefinitions = normalizePath arg :
+                                optSyntaxDefinitions opt })
+                 "FILE")
+                "" -- "Syntax definition (xml) file"
+
+    , Option "" ["syntax-highlighting"]
+                (ReqArg
+                 (\arg opt -> return opt{ optSyntaxHighlighting =
+                                 T.pack $ normalizePath arg })
+                 "none|default|idiomatic|<stylename>|<themepath>")
+                 "" -- "syntax highlighting method for code"
+
+
+    , Option "" ["dpi"]
+                 (ReqArg
+                  (\arg opt ->
+                    case safeStrRead arg of
+                         Just t | t > 0 -> return opt { optDpi = t }
+                         _              -> optError $ PandocOptionError
+                                        "Argument of --dpi must be a number greater than 0")
+                  "NUMBER")
+                 "" -- "Dpi (default 96)"
+
+    , Option "" ["eol"]
+                 (ReqArg
+                  (\arg opt ->
+                    case toLower <$> arg of
+                      "crlf"   -> return opt { optEol = CRLF }
+                      "lf"     -> return opt { optEol = LF }
+                      "native" -> return opt { optEol = Native }
+                      -- mac-syntax (cr) is not supported in ghc-base.
+                      _      -> optError $ PandocOptionError
+                                "Argument of --eol must be crlf, lf, or native")
+                  "crlf|lf|native")
+                 "" -- "EOL (default OS-dependent)"
+
+    , Option "" ["columns"]
+                 (ReqArg
+                  (\arg opt ->
+                      case safeStrRead arg of
+                           Just t | t > 0 -> return opt { optColumns = t }
+                           _              -> optError $ PandocOptionError
+                                   "Argument of --columns must be a number greater than 0")
+                 "NUMBER")
+                 "" -- "Length of line in characters"
+
+    , Option "p" ["preserve-tabs"]
+                 (OptArg
+                  (\arg opt -> do
+                        boolValue <- readBoolFromOptArg "--preserve-tabs/-p" arg
+                        return opt { optPreserveTabs = boolValue })
+                  "true|false")
+                 "" -- "Preserve tabs instead of converting to spaces"
+
+    , Option "" ["tab-stop"]
+                 (ReqArg
+                  (\arg opt ->
+                      case safeStrRead arg of
+                           Just t | t > 0 -> return opt { optTabStop = t }
+                           _              -> optError $ PandocOptionError
+                                  "Argument of --tab-stop must be a number greater than 0")
+                  "NUMBER")
+                 "" -- "Tab stop (default 4)"
+
+    , Option "" ["pdf-engine"]
+                 (ReqArg
+                  (\arg opt -> do
+                     let b = takeBaseName arg
+                     if b `elem` pdfEngines
+                        then return opt { optPdfEngine = Just arg }
+                        else optError $
+                              PandocOptionError $ T.pack $
+                              "Argument of --pdf-engine must be one of\n"
+                               ++ concatMap (\e -> "\t" <> e <> "\n") pdfEngines)
+                  "PROGRAM")
+                 "" -- "Name of program to use in generating PDF"
+
+    , Option "" ["pdf-engine-opt"]
+                 (ReqArg
+                  (\arg opt -> do
+                      let oldArgs = optPdfEngineOpts opt
+                      return opt { optPdfEngineOpts = oldArgs ++ [arg]})
+                  "STRING")
+                 "" -- "Flags to pass to the PDF-engine, all instances of this option are accumulated and used"
+
+    , Option "" ["reference-doc"]
+                 (ReqArg
+                  (\arg opt ->
+                    return opt { optReferenceDoc = Just $ normalizePath arg })
+                  "FILE")
+                 "" -- "Path of custom reference doc"
+
+    , Option "" ["self-contained"]
+                 (OptArg
+                  (\arg opt -> do
+                        deprecatedOption "--self-contained" "use --embed-resources --standalone"
+                        boolValue <- readBoolFromOptArg "--self-contained" arg
+                        return opt { optSelfContained = boolValue })
+                    "true|false")
+                 "" -- "Make slide shows include all the needed js and css (deprecated)"
+
+    , Option "" ["embed-resources"] -- maybe True (\argStr -> argStr == "true") arg
+                 (OptArg
+                  (\arg opt -> do
+                        boolValue <- readBoolFromOptArg "--embed-resources" arg
+                        return opt { optEmbedResources =  boolValue })
+                  "true|false")
+                 "" -- "Make slide shows include all the needed js and css"
+
+    , Option "" ["link-images"] -- maybe True (\argStr -> argStr == "true") arg
+                 (OptArg
+                  (\arg opt -> do
+                        boolValue <- readBoolFromOptArg "--link-images" arg
+                        return opt { optLinkImages =  boolValue })
+                  "true|false")
+                 "" -- "Link images in ODT rather than embedding them"
+
+    , Option "" ["request-header"]
+                 (ReqArg
+                  (\arg opt -> do
+                     let (key, val) = splitField arg
+                     return opt{ optRequestHeaders =
+                       (T.pack key, T.pack val) : optRequestHeaders opt })
+                  "NAME=VALUE")
+                 ""
+
+    , Option "" ["no-check-certificate"]
+                (OptArg
+                 (\arg opt -> do
+                        boolValue <- readBoolFromOptArg "--no-check-certificate" arg
+                        return opt { optNoCheckCertificate = boolValue })
+                 "true|false")
+                "" -- "Disable certificate validation"
+
+    , Option "" ["abbreviations"]
+                (ReqArg
+                 (\arg opt -> return opt { optAbbreviations =
+                                            Just $ normalizePath arg })
+                "FILE")
+                "" -- "Specify file for custom abbreviations"
+
+    , Option "" ["typst-input"]
+                 (ReqArg
+                  (\arg opt -> do
+                     let (key, val) = splitField arg
+                     return opt{ optTypstInputs = (T.pack key, T.pack val) : optTypstInputs opt })
+                  "KEY=VALUE")
+                 ""
+
+    , Option "" ["indented-code-classes"]
+                  (ReqArg
+                   (\arg opt -> return opt { optIndentedCodeClasses = T.words $
+                                             T.map (\c -> if c == ',' then ' ' else c) $
+                                             T.pack arg })
+                   "STRING")
+                  "" -- "Classes (whitespace- or comma-separated) to use for indented code-blocks"
+
+    , Option "" ["default-image-extension"]
+                 (ReqArg
+                  (\arg opt -> return opt { optDefaultImageExtension = T.pack arg })
+                   "extension")
+                  "" -- "Default extension for extensionless images"
+
+    , Option "F" ["filter"]
+                 (ReqArg
+                  (\arg opt -> return opt { optFilters =
+                      optFilters opt ++ [JSONFilter (normalizePath arg)] })
+                  "PROGRAM")
+                 "" -- "External JSON filter"
+
+    , Option "L" ["lua-filter"]
+                 (ReqArg
+                  (\arg opt -> return opt { optFilters =
+                      optFilters opt ++ [LuaFilter (normalizePath arg)] })
+                  "SCRIPTPATH")
+                 "" -- "Lua filter"
+
+    , Option "" ["shift-heading-level-by"]
+                 (ReqArg
+                  (\arg opt ->
+                      case safeStrRead arg of
+                           Just t ->
+                               return opt{ optShiftHeadingLevelBy = t }
+                           _              -> optError $ PandocOptionError
+                                               "Argument of --shift-heading-level-by must be an integer")
+                  "NUMBER")
+                 "" -- "Shift heading level"
+
+    , Option "" ["base-header-level"]
+                 (ReqArg
+                  (\arg opt -> do
+                      deprecatedOption "--base-header-level"
+                        "Use --shift-heading-level-by instead."
+                      case safeStrRead arg of
+                           Just t | t > 0 && t < 6 ->
+                               return opt{ optShiftHeadingLevelBy = t - 1 }
+                           _              -> optError $ PandocOptionError
+                                               "Argument of --base-header-level must be 1-5")
+                  "NUMBER")
+                 "" -- "Headers base level"
+
+    , Option "" ["track-changes"]
+                 (ReqArg
+                  (\arg opt -> do
+                     action <- case arg of
+                            "accept" -> return AcceptChanges
+                            "reject" -> return RejectChanges
+                            "all"    -> return AllChanges
+                            _        -> optError $ PandocOptionError $ T.pack
+                               "Argument of --track-changes must be accept, reject, or all"
+                     return opt { optTrackChanges = action })
+                  "accept|reject|all")
+                 "" -- "Accepting or reject MS Word track-changes.""
+
+    , Option "" ["strip-comments"]
+                (OptArg
+                 (\arg opt -> do
+                        boolValue <- readBoolFromOptArg "--strip-comments" arg
+                        return opt { optStripComments = boolValue })
+                 "true|false")
+               "" -- "Strip HTML comments"
+
+    , Option "" ["reference-links"]
+                 (OptArg
+                  (\arg opt -> do
+                        boolValue <- readBoolFromOptArg "--reference-links" arg
+                        return opt { optReferenceLinks = boolValue })
+                  "true|false")
+                 "" -- "Use reference links in parsing HTML"
+
+    , Option "" ["reference-location"]
+                 (ReqArg
+                  (\arg opt -> do
+                     action <- case arg of
+                            "block"    -> return EndOfBlock
+                            "section"  -> return EndOfSection
+                            "document" -> return EndOfDocument
+                            _        -> optError $ PandocOptionError $ T.pack
+                               "Argument of --reference-location must be block, section, or document"
+                     return opt { optReferenceLocation = action })
+                  "block|section|document")
+                 "" -- "Specify where reference links and footnotes go"
+
+    , Option "" ["figure-caption-position"]
+                 (ReqArg
+                  (\arg opt -> do
+                     pos <- case arg of
+                            "above"  -> return CaptionAbove
+                            "below"  -> return CaptionBelow
+                            _        -> optError $ PandocOptionError $ T.pack
+                               "Argument of --figure-caption-position must be above or below"
+                     return opt { optFigureCaptionPosition = pos })
+                  "above|below")
+                 "" -- "Specify where figure captions go"
+
+    , Option "" ["table-caption-position"]
+                 (ReqArg
+                  (\arg opt -> do
+                     pos <- case arg of
+                            "above"  -> return CaptionAbove
+                            "below"  -> return CaptionBelow
+                            _        -> optError $ PandocOptionError $ T.pack
+                               "Argument of --table-caption-position must be above or below"
+                     return opt { optTableCaptionPosition = pos })
+                  "above|below")
+                 "" -- "Specify where table captions go"
+
+    , Option "" ["markdown-headings"]
+                  (ReqArg
+                    (\arg opt -> do
+                      headingFormat <- case arg of
+                        "setext" -> pure True
+                        "atx" -> pure False
+                        _ -> optError $ PandocOptionError $ T.pack
+                          "Argument of --markdown-headings must be setext or atx"
+                      pure opt { optSetextHeaders = headingFormat }
+                    )
+                  "setext|atx")
+                  ""
+
+    , Option "" ["list-tables"]
+                 (OptArg
+                  (\arg opt -> do
+                        boolValue <- readBoolFromOptArg "--list-tables" arg
+                        return opt { optListTables = boolValue })
+                  "true|false")
+                 "" -- "Use list tables for RST"
+
+    , Option "" ["listings"]
+                 (OptArg
+                  (\arg opt -> do
+                      deprecatedOption "--listings"
+                        "Use --syntax-highlighting=idiomatic instead."
+                      boolValue <- readBoolFromOptArg "--listings" arg
+                      return $
+                        if boolValue
+                        then opt { optSyntaxHighlighting =
+                                   IdiomaticHighlightingString }
+                        else opt)
+                  "true|false")
+                 "" -- "Use listings package for LaTeX code blocks"
+
+    , Option "i" ["incremental"]
+                 (OptArg
+                  (\arg opt -> do
+                        boolValue <- readBoolFromOptArg "--incremental/-i" arg
+                        return opt { optIncremental = boolValue })
+                  "true|false")
+                 "" -- "Make list items display incrementally in Slidy/Slideous/S5"
+
+    , Option "" ["slide-level"]
+                 (ReqArg
+                  (\arg opt ->
+                      case safeStrRead arg of
+                           Just t | t >= 0 && t <= 6 ->
+                                    return opt { optSlideLevel = Just t }
+                           _      -> optError $ PandocOptionError
+                                    "Argument of --slide-level must be a number between 0 and 6")
+                 "NUMBER")
+                 "" -- "Force header level for slides"
+
+    , Option "" ["section-divs"]
+                 (OptArg
+                  (\arg opt -> do
+                        boolValue <- readBoolFromOptArg "--section-divs" arg
+                        return opt { optSectionDivs = boolValue })
+                  "true|false")
+                 "" -- "Put sections in div tags in HTML"
+
+    , Option "" ["html-q-tags"]
+                 (OptArg
+                  (\arg opt -> do
+                        boolValue <- readBoolFromOptArg "--html-q-tags" arg
+                        return opt { optHtmlQTags = boolValue })
+                  "true|false")
+                 "" -- "Use <q> tags for quotes in HTML"
+
+    , Option "" ["email-obfuscation"]
+                 (ReqArg
+                  (\arg opt -> do
+                     method <- case arg of
+                            "references" -> return ReferenceObfuscation
+                            "javascript" -> return JavascriptObfuscation
+                            "none"       -> return NoObfuscation
+                            _            -> optError $ PandocOptionError $ T.pack
+                               "Argument of --email-obfuscation must be references, javascript, or none"
+                     return opt { optEmailObfuscation = method })
+                  "none|javascript|references")
+                 "" -- "Method for obfuscating email in HTML"
+
+     , Option "" ["id-prefix"]
+                  (ReqArg
+                   (\arg opt -> return opt { optIdentifierPrefix = T.pack arg })
+                   "STRING")
+                  "" -- "Prefix to add to automatically generated HTML identifiers"
+
+    , Option "T" ["title-prefix"]
+                 (ReqArg
+                  (\arg opt ->
+                    return opt {
+                       optVariables =
+                         setVariable "title-prefix" (T.pack arg) $
+                           optVariables opt,
+                       optStandalone = True })
+                  "STRING")
+                 "" -- "String to prefix to HTML window title"
+
+    , Option "c" ["css"]
+                 (ReqArg
+                  (\arg opt -> return opt{ optCss = optCss opt ++ [arg] })
+                  -- add new link to end, so it is included in proper order
+                  "URL")
+                 "" -- "Link to CSS style sheet"
+
+    , Option "" ["epub-subdirectory"]
+             (ReqArg
+                  (\arg opt ->
+                     return opt { optEpubSubdirectory = arg })
+                  "DIRNAME")
+                 "" -- "Name of subdirectory for epub content in OCF container"
+
+    , Option "" ["epub-cover-image"]
+                 (ReqArg
+                  (\arg opt ->
+                     return opt { optVariables =
+                       setVariable "epub-cover-image"
+                         (T.pack $ normalizePath arg) $
+                         optVariables opt })
+                  "FILE")
+                 "" -- "Path of epub cover image"
+
+    , Option "" ["epub-title-page"]
+                 (OptArg
+                  (\arg opt -> do
+                     boolValue <- readBoolFromOptArg "--epub-title-page" arg
+                     return opt{ optEpubTitlePage = boolValue })
+                 "true|false")
+                 ""
+
+    , Option "" ["epub-metadata"]
+                 (ReqArg
+                  (\arg opt -> return opt { optEpubMetadata = Just $
+                                             normalizePath arg })
+                  "FILE")
+                 "" -- "Path of epub metadata file"
+
+    , Option "" ["epub-embed-font"]
+                 (ReqArg
+                  (\arg opt ->
+                     return opt{ optEpubFonts = normalizePath arg :
+                                                optEpubFonts opt })
+                  "FILE")
+                 "" -- "Directory of fonts to embed"
+
+    , Option "" ["split-level"]
+                 (ReqArg
+                  (\arg opt ->
+                      case safeStrRead arg of
+                           Just t | t >= 1 && t <= 6 ->
+                                    return opt { optSplitLevel = t }
+                           _      -> optError $ PandocOptionError
+                                    "Argument of --split-level must be a number between 1 and 6")
+                 "NUMBER")
+                 "" -- "Header level at which to split documents in chunked HTML or EPUB"
+
+    , Option "" ["chunk-template"]
+                 (ReqArg
+                  (\arg opt ->
+                     return opt{ optChunkTemplate = Just (T.pack arg) })
+                 "PATHTEMPLATE")
+                 "" -- "Template for file paths in chunkedhtml"
+
+    , Option "" ["epub-chapter-level"]
+                 (ReqArg
+                  (\arg opt -> do
+                      deprecatedOption "--epub-chapter-level"
+                                       "use --split-level"
+                      case safeStrRead arg of
+                           Just t | t >= 1 && t <= 6 ->
+                                    return opt { optSplitLevel = t }
+                           _      -> optError $ PandocOptionError
+                                    "Argument of --epub-chapter-level must be a number between 1 and 6")
+                 "NUMBER")
+                 "" -- "Header level at which to split documents in chunked HTML or EPUB"
+
+    , Option "" ["ipynb-output"]
+                 (ReqArg
+                  (\arg opt ->
+                    case arg of
+                      "all" -> return opt{ optIpynbOutput = IpynbOutputAll }
+                      "best" -> return opt{ optIpynbOutput = IpynbOutputBest }
+                      "none" -> return opt{ optIpynbOutput = IpynbOutputNone }
+                      _ -> optError $ PandocOptionError
+                             "Argument of --ipynb-output must be all, none, or best")
+                 "all|none|best")
+                 "" -- "Starting number for sections, subsections, etc."
+
+    , Option "C" ["citeproc"]
+                 (NoArg
+                  (\opt -> return opt { optFilters =
+                      optFilters opt ++ [CiteprocFilter] }))
+                 "" -- "Process citations"
+
+    , Option "" ["bibliography"]
+                 (ReqArg
+                  (\arg opt -> return opt{ optMetadata =
+                                            addMeta "bibliography"
+                                              (normalizePath arg) $
+                                              optMetadata opt })
+                   "FILE")
+                 ""
+
+     , Option "" ["csl"]
+                 (ReqArg
+                  (\arg opt -> do
+                    case lookupMeta (T.pack "csl") $ optMetadata opt of
+                      Just _ -> optError $ PandocOptionError
+                                   "--csl option can only be used once"
+                      Nothing -> return opt{ optMetadata = addMeta "csl" (normalizePath arg) $
+                      optMetadata opt })
+                   "FILE")
+                 ""
+
+     , Option "" ["citation-abbreviations"]
+                 (ReqArg
+                  (\arg opt ->
+                     return opt{ optMetadata =
+                                  addMeta "citation-abbreviations"
+                                    (normalizePath arg) $ optMetadata opt })
+                   "FILE")
+                 ""
+
+    , Option "" ["natbib"]
+                 (NoArg
+                  (\opt -> return opt { optCiteMethod = Natbib }))
+                 "" -- "Use natbib cite commands in LaTeX output"
+
+    , Option "" ["biblatex"]
+                 (NoArg
+                  (\opt -> return opt { optCiteMethod = Biblatex }))
+                 "" -- "Use biblatex cite commands in LaTeX output"
+
+    , Option "" ["mathml"]
+                 (NoArg
+                  (\opt ->
+                      return opt { optHTMLMathMethod = MathML }))
+                 "" -- "Use mathml for HTML math"
+
+    , Option "" ["webtex"]
+                 (OptArg
+                  (\arg opt -> do
+                      let url' = maybe defaultWebTeXURL T.pack arg
+                      return opt { optHTMLMathMethod = WebTeX url' })
+                  "URL")
+                 "" -- "Use web service for HTML math"
+
+    , Option "" ["mathjax"]
+                 (OptArg
+                  (\arg opt -> do
+                      let url' = maybe defaultMathJaxURL T.pack arg
+                      return opt { optHTMLMathMethod = MathJax url'})
+                  "URL")
+                 "" -- "Use MathJax for HTML math"
+
+    , Option "" ["katex"]
+                 (OptArg
+                  (\arg opt ->
+                      return opt
+                        { optHTMLMathMethod = KaTeX $
+                           maybe defaultKaTeXURL T.pack arg })
+                  "URL")
+                  "" -- Use KaTeX for HTML Math
+
+    , Option "" ["gladtex"]
+                 (NoArg
+                  (\opt ->
+                      return opt { optHTMLMathMethod = GladTeX }))
+                 "" -- "Use gladtex for HTML math"
+
+    , Option "" ["trace"]
+                 (OptArg
+                  (\arg opt -> do
+                        boolValue <- readBoolFromOptArg "--trace" arg
+                        return opt { optTrace = boolValue })
+                  "true|false")
+                 "" -- "Turn on diagnostic tracing in readers."
+
+    , Option "" ["dump-args"]
+                 (OptArg
+                  (\arg opt -> do
+                        boolValue <- readBoolFromOptArg "--dump-args" arg
+                        return opt { optDumpArgs = boolValue })
+                  "true|false")
+                 "" -- "Print output filename and arguments to stdout."
+
+    , Option "" ["ignore-args"]
+                 (OptArg
+                  (\arg opt -> do
+                        boolValue <- readBoolFromOptArg "--ignore-args" arg
+                        return opt { optIgnoreArgs = boolValue })
+                  "true|false")
+                 "" -- "Ignore command-line arguments."
+
+    , Option "" ["verbose"]
+                 (NoArg
+                  (\opt -> return opt { optVerbosity = INFO }))
+                 "" -- "Verbose diagnostic output."
+
+    , Option "" ["quiet"]
+                 (NoArg
+                  (\opt -> return opt { optVerbosity = ERROR }))
+                 "" -- "Suppress warnings."
+
+    , Option "" ["fail-if-warnings"]
+                 (OptArg
+                  (\arg opt -> do
+                        boolValue <- readBoolFromOptArg "--fail-if-warnings" arg
+                        return opt { optFailIfWarnings = boolValue })
+                  "true|false")
+                 "" -- "Exit with error status if there were  warnings."
+
+    , Option "" ["log"]
+                 (ReqArg
+                  (\arg opt -> return opt{ optLogFile = Just $
+                                            normalizePath arg })
+                "FILE")
+                "" -- "Log messages in JSON format to this file."
+
+    , Option "" ["bash-completion"]
+                 (NoArg (\_ -> optInfo BashCompletion))
+                 "" -- "Print bash completion script"
+
+    , Option "" ["list-input-formats"]
+                 (NoArg (\_ -> optInfo ListInputFormats))
+                 ""
+
+    , Option "" ["list-output-formats"]
+                 (NoArg (\_ -> optInfo ListOutputFormats))
+                 ""
+
+    , Option "" ["list-extensions"]
+                 (OptArg (\arg _ -> optInfo $ ListExtensions $ T.pack <$> arg)
+                 "FORMAT")
+                 ""
+
+    , Option "" ["list-highlight-languages"]
+                 (NoArg (\_ -> optInfo ListHighlightLanguages))
+                 ""
+
+    , Option "" ["list-highlight-styles"]
+                 (NoArg (\_ -> optInfo ListHighlightStyles))
+                 ""
+
+    , Option "D" ["print-default-template"]
+                 (ReqArg
+                  (\arg opts -> optInfo $
+                    PrintDefaultTemplate (optOutputFile opts) (T.pack arg))
+                 "FORMAT")
+                 "" -- "Print default template for FORMAT"
+
+    , Option "" ["print-default-data-file"]
+                 (ReqArg
+                  (\arg opts -> optInfo $
+                    PrintDefaultDataFile (optOutputFile opts) (T.pack arg))
+                 "FILE")
+                  "" -- "Print default data file"
+
+    , Option "" ["print-highlight-style"]
+                 (ReqArg
+                  (\arg opts ->
+                    optInfo $ PrintHighlightStyle (optOutputFile opts)
+                               (T.pack arg))
+                  "STYLE|FILE")
+                 "" -- "Print default template for FORMAT"
+
+    , Option "v" ["version"]
+                 (NoArg (\_ -> optInfo VersionInfo))
+                 "" -- "Print version"
+
+    , Option "h" ["help"]
+                 (NoArg (\_ -> optInfo Help))
+                 "" -- "Show help"
+    ]
+
+optError :: PandocError -> ExceptT OptInfo IO a
+optError = throwError . OptError
+
+optInfo :: OptInfo -> ExceptT OptInfo IO a
+optInfo = throwError
+
+-- Returns usage message
+usageMessage :: String -> [OptDescr (Opt -> ExceptT OptInfo IO Opt)] -> String
+usageMessage programName = usageInfo (programName ++ " [OPTIONS] [FILES]")
+
+copyrightMessage :: String
+copyrightMessage = intercalate "\n" [
+ "Copyright (C) 2006-2025 John MacFarlane. Web:  https://pandoc.org",
+ "This is free software; see the source for copying conditions. There is no",
+ "warranty, not even for merchantability or fitness for a particular purpose." ]
+
+handleUnrecognizedOption :: String -> [String] -> [String]
+handleUnrecognizedOption "--smart" =
+  (("--smart/-S has been removed.  Use +smart or -smart extension instead.\n" ++
+    "For example: pandoc -f markdown+smart -t markdown-smart.") :)
+handleUnrecognizedOption "--normalize" =
+  ("--normalize has been removed.  Normalization is now automatic." :)
+handleUnrecognizedOption "-S" = handleUnrecognizedOption "--smart"
+handleUnrecognizedOption "--old-dashes" =
+  ("--old-dashes has been removed.  Use +old_dashes extension instead." :)
+handleUnrecognizedOption "--no-wrap" =
+  ("--no-wrap has been removed.  Use --wrap=none instead." :)
+handleUnrecognizedOption "--latex-engine" =
+  ("--latex-engine has been removed.  Use --pdf-engine instead." :)
+handleUnrecognizedOption "--latex-engine-opt" =
+  ("--latex-engine-opt has been removed.  Use --pdf-engine-opt instead." :)
+handleUnrecognizedOption "--chapters" =
+  ("--chapters has been removed. Use --top-level-division=chapter instead." :)
+handleUnrecognizedOption "--reference-docx" =
+  ("--reference-docx has been removed. Use --reference-doc instead." :)
+handleUnrecognizedOption "--reference-odt" =
+  ("--reference-odt has been removed. Use --reference-doc instead." :)
+handleUnrecognizedOption "--parse-raw" =
+  ("--parse-raw/-R has been removed. Use +raw_html or +raw_tex extension.\n" :)
+handleUnrecognizedOption "--epub-stylesheet" =
+  ("--epub-stylesheet has been removed. Use --css instead.\n" :)
+handleUnrecognizedOption "-R" = handleUnrecognizedOption "--parse-raw"
+handleUnrecognizedOption x =
+  (("Unknown option " ++ x ++ ".") :)
+
+readersNames :: [Text]
+readersNames = sort (map fst (readers :: [(Text, Reader PandocIO)]))
+
+writersNames :: [Text]
+writersNames = sort
+  ("pdf" : map fst (writers :: [(Text, Writer PandocIO)]))
+
+splitField :: String -> (String, String)
+splitField = second (tailDef "true") . break (\c -> c == ':' || c == '=')
+
+deprecatedOption :: String -> String -> ExceptT OptInfo IO ()
+deprecatedOption o msg = do
+  res <- liftIO $ runIO (report $ Deprecated (T.pack o) (T.pack msg))
+  case res of
+       Right () -> return ()
+       Left e   -> optError e
+
+-- | Set text value in text context.  Create list if it has a value already,
+-- or add to a list value.
+setVariable :: Text -> Text -> Context Text -> Context Text
+setVariable key val (Context ctx) = Context $ M.alter go key ctx
+  where go Nothing             = Just $ toVal val
+        go (Just (ListVal xs)) = Just $ ListVal $ xs ++ [toVal val]
+        go (Just x)            = Just $ ListVal [x, toVal val]
+
+addMeta :: String -> String -> Meta -> Meta
+addMeta k v meta =
+  case lookupMeta k' meta of
+       Nothing -> setMeta k' v' meta
+       Just (MetaList xs) ->
+                  setMeta k' (MetaList (xs ++ [v'])) meta
+       Just x  -> setMeta k' (MetaList [x, v']) meta
+ where
+  v' = readMetaValue v
+  k' = T.pack k
+
+readMetaValue :: String -> MetaValue
+readMetaValue s
+  | s == "true"  = MetaBool True
+  | s == "True"  = MetaBool True
+  | s == "TRUE"  = MetaBool True
+  | s == "false" = MetaBool False
+  | s == "False" = MetaBool False
+  | s == "FALSE" = MetaBool False
+  | otherwise    = MetaString $ T.pack s
+
+readBoolFromOptArg ::  Text -> Maybe String -> ExceptT OptInfo IO Bool
+readBoolFromOptArg opt = maybe (return True) readBoolFromArg
+    where readBoolFromArg arg = case toLower <$> arg of
+            "true"  -> return True
+            "false" -> return False
+            _       -> optError $ PandocOptionError $
+                        "Argument of " <> opt <> " must be either true or false"
+
+-- On Windows with ghc 8.6+, we need to rewrite paths
+-- beginning with \\ to \\?\UNC\. -- See #5127.
+normalizePath :: FilePath -> FilePath
+#ifdef _WINDOWS
+normalizePath fp =
+  if "\\\\" `isPrefixOf` fp && not ("\\\\?\\" `isPrefixOf` fp)
+    then "\\\\?\\UNC\\" ++ drop 2 fp
+    else fp
+#else
+normalizePath = id
+#endif
+
+-- | Print version information with customizable features and scripting engine
+versionInfo :: [String] -> Maybe String -> String -> IO ()
+versionInfo features mbScriptingEngineName suffix = do
+  defaultDatadir <- defaultUserDataDir
+  let featuresLine = if null features
+                       then []
+                       else ["Features: " ++ unwords features]
+  let scriptingLine = case mbScriptingEngineName of
+                        Nothing -> []
+                        Just name -> ["Scripting engine: " ++ name]
+  UTF8.putStr $ T.unlines $ map T.pack $
+    ["pandoc " ++ showVersion pandocVersion ++ suffix] ++
+    featuresLine ++
+    scriptingLine ++
+    ["User data directory: " ++ defaultDatadir,
+     copyrightMessage]
+  exitSuccess
diff --git a/src/Text/Pandoc/App/Input.hs b/src/Text/Pandoc/App/Input.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/App/Input.hs
@@ -0,0 +1,138 @@
+{-# LANGUAGE LambdaCase          #-}
+{-# LANGUAGE OverloadedStrings   #-}
+{-# LANGUAGE TupleSections       #-}
+{- |
+   Module      : Text.Pandoc.App.Input
+   Copyright   : © 2006-2024 John MacFarlane
+   License     : GPL-2.0-or-later
+   Maintainer  : John MacFarlane <jgm@berkeley@edu>
+
+Read from the file system into a pandoc document.
+-}
+module Text.Pandoc.App.Input
+  ( InputParameters (..)
+  , readInput
+  ) where
+
+import Control.Monad ((>=>), when)
+import Control.Monad.Except (throwError, catchError)
+import Data.Text (Text)
+import Network.URI (URI (..), parseURI)
+import Text.Pandoc.Transforms (adjustLinksAndIds)
+import Text.Pandoc.Class ( PandocMonad, openURL, toTextM
+                         , readFileStrict, readStdinStrict, report)
+import Text.Pandoc.Definition (Pandoc)
+import Text.Pandoc.Error (PandocError (..))
+import Text.Pandoc.Logging (LogMessage (..))
+import Text.Pandoc.MIME (getCharset, MimeType)
+import Text.Pandoc.Options (ReaderOptions (..))
+import Text.Pandoc.Readers (Reader (..))
+import Text.Pandoc.Shared (tabFilter)
+import Text.Pandoc.URI (uriPathToPath)
+import qualified Data.ByteString as BS
+import qualified Data.ByteString.Char8 as B8
+import qualified Data.ByteString.Lazy as BL
+import qualified Data.Text as T
+
+-- | Settings specifying how and which input should be processed.
+data InputParameters m = InputParameters
+  { inputReader         :: Reader m
+  , inputReaderName     :: Text
+  , inputReaderOptions  :: ReaderOptions
+  , inputSources        :: [FilePath]
+  , inputSpacesPerTab   :: Maybe Int
+  , inputFileScope      :: Bool
+  }
+
+-- | Read all input into a pandoc document.
+readInput :: PandocMonad m => InputParameters m -> m Pandoc
+readInput params = do
+  let sources = inputSources params
+  let readerName = inputReaderName params
+  let readerOpts = inputReaderOptions params
+  let convertTabs :: Text -> Text
+      convertTabs = tabFilter $ case inputSpacesPerTab params of
+        Nothing -> 0
+        Just ts -> if readerName `elem` ["t2t", "man", "tsv"]
+                   then 0
+                   else ts
+
+  inputs <- readSources sources
+
+  case inputReader params of
+    TextReader r
+      | readerName == "json" ->
+          mconcat <$> mapM (inputToText convertTabs >=> r readerOpts . (:[]))
+                           inputs
+      | inputFileScope params ->
+          mconcat <$> mapM
+              (\source -> do
+                  (fp, txt) <- inputToText convertTabs source
+                  adjustLinksAndIds (readerExtensions readerOpts)
+                    (T.pack fp) (map (T.pack . fst) inputs)
+                    <$> r readerOpts [(fp, txt)])
+              inputs
+      | otherwise -> mapM (inputToText convertTabs) inputs >>= r readerOpts
+    ByteStringReader r ->
+      mconcat <$> mapM (r readerOpts . inputToLazyByteString) inputs
+
+readSources :: PandocMonad m
+            => [FilePath] -> m [(FilePath, (BS.ByteString, Maybe MimeType))]
+readSources srcs =
+  mapM (\fp -> do t <- readSource fp
+                  return (if fp == "-" then "" else fp, t)) srcs
+
+-- | Read input from a resource, i.e., either a file, a URL, or stdin
+-- (@-@).
+readSource :: PandocMonad m
+           => FilePath -> m (BS.ByteString, Maybe MimeType)
+readSource "-" = (,Nothing) <$> readStdinStrict
+readSource src =
+  case parseURI src of
+    Just u | uriScheme u `elem` ["http:","https:"] -> openURL (T.pack src)
+           | uriScheme u == "file:" ->
+               (,Nothing) <$>
+                 readFileStrict (uriPathToPath $ T.pack $ uriPath u)
+    _       -> (,Nothing) <$> readFileStrict src
+
+inputToText :: PandocMonad m
+            => (Text -> Text)
+            -> (FilePath, (BS.ByteString, Maybe MimeType))
+            -> m (FilePath, Text)
+inputToText convTabs (fp, (bs,mt)) =
+  (fp,) . convTabs . T.filter (/='\r') <$>
+  case mt >>= getCharset of
+    Just "UTF-8"      -> toTextM fp bs
+    Just "ISO-8859-1" -> return $ T.pack $ B8.unpack bs
+    Just charset      -> throwError $ PandocUnsupportedCharsetError charset
+    Nothing           -> catchError
+                           (toTextM fp bs)
+                           (\case
+                              PandocUTF8DecodingError{} -> do
+                                when (hasKnownSignature bs) $
+                                  throwError $
+                                    PandocInputNotTextError (T.pack fp)
+                                report $ NotUTF8Encoded
+                                  (if null fp
+                                      then "input"
+                                      else fp)
+                                return $ T.pack $ B8.unpack bs
+                              e -> throwError e)
+ where
+  -- "50 4B 03 04" is zip file signature
+  isZip bs' = "\x50\x4B\x03\x04" `BS.isPrefixOf` bs'
+  -- "25 50 44 46 2D" is PDF file signature
+  isPDF bs' = "\x25\x50\x44\x46\x2D" `BS.isPrefixOf` bs'
+  -- "D0 CF 11 E0 A1 B1 1A E1" is Compound File Binary Format signature used in
+  -- variety of old Microsoft formats (.doc and .xls among others)
+  isCFBF bs' = "\xD0\xCF\x11\xE0\xA1\xB1\x1A\xE1" `BS.isPrefixOf` bs'
+  -- "41 54 26 54 46 4F 52 4D ?? ?? ?? ?? 44 4A 56" is DjVu signature
+  isDjVu bs' = case BS.stripPrefix "\x41\x54\x26\x54\x46\x4F\x52\x4D" bs' of
+    Nothing -> False
+    Just x -> BS.isPrefixOf "\x44\x4A\x56" $ BS.drop 4 x
+
+  hasKnownSignature bs' = any ($ bs') [isZip, isPDF, isCFBF, isDjVu]
+
+inputToLazyByteString :: (FilePath, (BS.ByteString, Maybe MimeType))
+                      -> BL.ByteString
+inputToLazyByteString (_, (bs,_)) = BL.fromStrict bs
diff --git a/src/Text/Pandoc/App/Opt.hs b/src/Text/Pandoc/App/Opt.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/App/Opt.hs
@@ -0,0 +1,921 @@
+{-# LANGUAGE ScopedTypeVariables #-}
+{-# LANGUAGE OverloadedStrings   #-}
+{-# LANGUAGE CPP                 #-}
+{-# LANGUAGE DeriveGeneric       #-}
+{-# LANGUAGE PatternSynonyms     #-}
+{-# LANGUAGE TemplateHaskell     #-}
+{-# LANGUAGE FlexibleInstances   #-}
+{-# LANGUAGE FlexibleContexts    #-}
+{- |
+   Module      : Text.Pandoc.App.Opt
+   Copyright   : Copyright (C) 2006-2024 John MacFarlane
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : John MacFarlane <jgm@berkeley@edu>
+   Stability   : alpha
+   Portability : portable
+
+Options for pandoc when used as an app.
+-}
+module Text.Pandoc.App.Opt (
+            Opt(..)
+          , OptInfo(..)
+          , LineEnding (..)
+          , IpynbOutput (..)
+          , DefaultsState (..)
+          , defaultOpts
+          , applyDefaults
+          , fullDefaultsPath
+          ) where
+import Control.Monad.Except (throwError)
+import Control.Monad.Trans (MonadIO, liftIO, lift)
+import Control.Monad ((>=>), foldM)
+import Control.Monad.State.Strict (StateT, modify, gets)
+import System.FilePath ( addExtension, (</>), takeExtension, takeDirectory )
+import System.Directory ( canonicalizePath )
+import Data.Char (toLower, isSpace)
+import Data.Maybe (fromMaybe)
+import GHC.Generics hiding (Meta)
+import Text.Pandoc.Filter (Filter (..))
+import Text.Pandoc.Logging (Verbosity (WARNING), LogMessage(..))
+import Text.Pandoc.Options (TopLevelDivision (TopLevelDefault),
+                            TrackChanges (AcceptChanges),
+                            WrapOption (WrapAuto), HTMLMathMethod (PlainMath),
+                            ReferenceLocation (EndOfDocument),
+                            CaptionPosition (..),
+                            ObfuscationMethod (NoObfuscation),
+                            CiteMethod (Citeproc),
+                            pattern DefaultHighlightingString)
+import Text.Pandoc.Class (readFileStrict, fileExists, setVerbosity, report,
+                          PandocMonad(lookupEnv), getUserDataDir)
+import Text.Pandoc.Error (PandocError (PandocParseError, PandocSomeError))
+import Data.Containers.ListUtils (nubOrd)
+import Text.Pandoc.Data (defaultUserDataDir)
+import qualified Text.Pandoc.Parsing as P
+import Text.Pandoc.Readers.Metadata (yamlMap)
+import Text.Pandoc.Class.PandocPure
+import Text.DocTemplates (Context(..))
+import Data.Text (Text, unpack)
+import Data.Default (def)
+import qualified Data.Text as T
+import qualified Data.Map as M
+import qualified Data.ByteString.Char8 as B8
+import Text.Pandoc.Definition (Meta(..), MetaValue(..))
+import Data.Aeson (defaultOptions, Options(..), Result(..),
+                   genericToJSON, fromJSON, camelTo2, eitherDecodeStrict)
+import Data.Aeson.TH (deriveJSON)
+import Control.Applicative ((<|>))
+import Data.Yaml
+
+-- | The type of line-endings to be used when writing plain-text.
+data LineEnding = LF | CRLF | Native deriving (Show, Generic)
+
+-- see https://github.com/jgm/pandoc/pull/4083
+-- using generic deriving caused long compilation times
+$(deriveJSON
+   defaultOptions{ constructorTagModifier = map toLower } ''LineEnding)
+
+-- | How to handle output blocks in ipynb.
+data IpynbOutput =
+    IpynbOutputAll
+  | IpynbOutputNone
+  | IpynbOutputBest
+  deriving (Show, Generic)
+
+$(deriveJSON
+   defaultOptions{ fieldLabelModifier = map toLower . drop 11 } ''IpynbOutput)
+
+-- | Option parser results requesting informational output.
+data OptInfo =
+     BashCompletion
+   | ListInputFormats
+   | ListOutputFormats
+   | ListExtensions (Maybe Text)
+   | ListHighlightLanguages
+   | ListHighlightStyles
+   | PrintDefaultTemplate (Maybe FilePath) Text
+   | PrintDefaultDataFile (Maybe FilePath) Text
+   | PrintHighlightStyle (Maybe FilePath) Text
+   | VersionInfo
+   | Help
+   | OptError PandocError
+   deriving (Show, Generic)
+
+-- | Data structure for command line options.
+data Opt = Opt
+    { optTabStop               :: Int     -- ^ Number of spaces per tab
+    , optPreserveTabs          :: Bool    -- ^ Preserve tabs instead of converting to spaces
+    , optStandalone            :: Bool    -- ^ Include header, footer
+    , optFrom                  :: Maybe Text  -- ^ Reader format
+    , optTo                    :: Maybe Text  -- ^ Writer format
+    , optTableOfContents       :: Bool    -- ^ Include table of contents
+    , optListOfFigures         :: Bool    -- ^ Include list of figures
+    , optListOfTables          :: Bool    -- ^ Include list of tables
+    , optShiftHeadingLevelBy   :: Int     -- ^ Shift heading level by
+    , optTemplate              :: Maybe FilePath  -- ^ Custom template
+    , optVariables             :: Context Text    -- ^ Template variables to set
+    , optMetadata              :: Meta -- ^ Metadata fields to set
+    , optMetadataFiles         :: [FilePath]  -- ^ Name of YAML metadata files
+    , optOutputFile            :: Maybe FilePath  -- ^ Name of output file
+    , optInputFiles            :: Maybe [FilePath] -- ^ Names of input files
+    , optNumberSections        :: Bool    -- ^ Number sections in LaTeX
+    , optNumberOffset          :: [Int]   -- ^ Starting number for sections
+    , optSectionDivs           :: Bool    -- ^ Put sections in div tags in HTML
+    , optIncremental           :: Bool    -- ^ Use incremental lists in Slidy/Slideous/S5
+    , optSelfContained         :: Bool    -- ^ Make HTML accessible offline (deprecated)
+    , optEmbedResources        :: Bool    -- ^ Make HTML accessible offline
+    , optLinkImages            :: Bool    -- ^ Link ODT images rather than embedding
+    , optHtmlQTags             :: Bool    -- ^ Use <q> tags in HTML
+    , optSyntaxDefinitions     :: [FilePath]  -- ^ xml syntax defs to load
+    , optSyntaxHighlighting    :: Text -- ^ Syntax highlighting method for code
+    , optTopLevelDivision      :: TopLevelDivision -- ^ Type of the top-level divisions
+    , optHTMLMathMethod        :: HTMLMathMethod -- ^ Method to print HTML math
+    , optAbbreviations         :: Maybe FilePath -- ^ Path to abbrevs file
+    , optReferenceDoc          :: Maybe FilePath -- ^ Path of reference doc
+    , optSplitLevel            :: Int     -- ^ Header level at which to split documents in epub and chunkedhtml
+    , optChunkTemplate         :: Maybe Text -- ^ Template to use for chunk filenames
+    , optEpubSubdirectory      :: String -- ^ EPUB subdir in OCF container
+    , optEpubMetadata          :: Maybe FilePath   -- ^ EPUB metadata
+    , optEpubFonts             :: [FilePath] -- ^ EPUB fonts to embed
+    , optEpubCoverImage        :: Maybe FilePath -- ^ Cover image for epub
+    , optEpubTitlePage         :: Bool -- ^ INclude title page in EPUB
+    , optTOCDepth              :: Int     -- ^ Number of levels to include in TOC
+    , optDumpArgs              :: Bool    -- ^ Output command-line arguments
+    , optIgnoreArgs            :: Bool    -- ^ Ignore command-line arguments
+    , optVerbosity             :: Verbosity  -- ^ Verbosity of diagnostic output
+    , optTrace                 :: Bool  -- ^ Enable tracing
+    , optLogFile               :: Maybe FilePath -- ^ File to write JSON log output
+    , optFailIfWarnings        :: Bool    -- ^ Fail on warnings
+    , optReferenceLinks        :: Bool    -- ^ Use reference links in writing markdown, rst
+    , optReferenceLocation     :: ReferenceLocation -- ^ location for footnotes and link references in markdown output
+    , optFigureCaptionPosition :: CaptionPosition -- ^ position for figure caption
+    , optTableCaptionPosition  :: CaptionPosition -- ^ position for table caption
+    , optDpi                   :: Int     -- ^ Dpi
+    , optWrap                  :: WrapOption  -- ^ Options for wrapping text
+    , optColumns               :: Int     -- ^ Line length in characters
+    , optFilters               :: [Filter] -- ^ Filters to apply
+    , optEmailObfuscation      :: ObfuscationMethod
+    , optIdentifierPrefix      :: Text
+    , optIndentedCodeClasses   :: [Text] -- ^ Default classes for indented code blocks
+    , optDataDir               :: Maybe FilePath
+    , optCiteMethod            :: CiteMethod -- ^ Method to output cites
+    , optPdfEngine             :: Maybe String -- ^ Program to use for latex/html -> pdf
+    , optPdfEngineOpts         :: [String]   -- ^ Flags to pass to the engine
+    , optSlideLevel            :: Maybe Int  -- ^ Header level that creates slides
+    , optSetextHeaders         :: Bool       -- ^ Use atx headers for markdown level 1-2
+    , optListTables            :: Bool       -- ^ Use list tables for RST
+    , optAscii                 :: Bool       -- ^ Prefer ascii output
+    , optDefaultImageExtension :: Text       -- ^ Default image extension
+    , optExtractMedia          :: Maybe FilePath -- ^ Path to extract embedded media
+    , optTrackChanges          :: TrackChanges -- ^ Accept or reject MS Word track-changes.
+    , optFileScope             :: Bool         -- ^ Parse input files before combining
+    , optTitlePrefix           :: Maybe Text     -- ^ Prefix for title
+    , optCss                   :: [FilePath]       -- ^ CSS files to link to
+    , optIpynbOutput           :: IpynbOutput      -- ^ How to treat ipynb output blocks
+    , optIncludeBeforeBody     :: [FilePath]       -- ^ Files to include before
+    , optIncludeAfterBody      :: [FilePath]       -- ^ Files to include after body
+    , optIncludeInHeader       :: [FilePath]       -- ^ Files to include in header
+    , optResourcePath          :: [FilePath] -- ^ Path to search for images etc
+    , optRequestHeaders        :: [(Text, Text)] -- ^ Headers for HTTP requests
+    , optNoCheckCertificate    :: Bool       -- ^ Disable certificate validation
+    , optEol                   :: LineEnding -- ^ Style of line-endings to use
+    , optStripComments         :: Bool       -- ^ Skip HTML comments
+    , optCSL                   :: Maybe FilePath -- ^ CSL stylesheet
+    , optBibliography          :: [FilePath]  -- ^ Bibliography files
+    , optCitationAbbreviations :: Maybe FilePath -- ^ Citation abbreviations
+    , optSandbox               :: Bool
+    , optTypstInputs           :: [(Text, Text)] -- ^ List of parameter values for typst
+    } deriving (Generic, Show)
+
+instance FromJSON Opt where
+   parseJSON = withObject "Opt" $ \o ->
+     Opt
+       <$> o .:? "tab-stop" .!= optTabStop defaultOpts
+       <*> o .:? "preserve-tabs" .!= optPreserveTabs defaultOpts
+       <*> o .:? "standalone" .!= optStandalone defaultOpts
+       <*> o .:? "from"
+       <*> o .:? "to"
+       <*> o .:? "table-of-contents" .!= optTableOfContents defaultOpts
+       <*> o .:? "list-of-figures" .!= optListOfFigures defaultOpts
+       <*> o .:? "list-of-tables" .!= optListOfTables defaultOpts
+       <*> o .:? "shift-heading-level-by" .!= optShiftHeadingLevelBy defaultOpts
+       <*> o .:? "template"
+       <*> o .:? "variables" .!= optVariables defaultOpts
+       <*> o .:? "metadata" .!= optMetadata defaultOpts
+       <*> o .:? "metadata-files" .!= optMetadataFiles defaultOpts
+       <*> o .:? "output-file"
+       <*> o .:? "input-files"
+       <*> o .:? "number-sections" .!= optNumberSections defaultOpts
+       <*> o .:? "number-offset" .!= optNumberOffset defaultOpts
+       <*> o .:? "section-divs" .!= optSectionDivs defaultOpts
+       <*> o .:? "incremental" .!= optIncremental defaultOpts
+       <*> o .:? "self-contained" .!= optSelfContained defaultOpts
+       <*> o .:? "embed-resources" .!= optEmbedResources defaultOpts
+       <*> o .:? "link-images" .!= optLinkImages defaultOpts
+       <*> o .:? "html-q-tags" .!= optHtmlQTags defaultOpts
+       <*> o .:? "syntax-definitions" .!= optSyntaxDefinitions defaultOpts
+       <*> o .:? "syntax-highlighting" .!= optSyntaxHighlighting defaultOpts
+       <*> o .:? "top-level-division" .!= optTopLevelDivision defaultOpts
+       <*> o .:? "html-math-method" .!= optHTMLMathMethod defaultOpts
+       <*> o .:? "abbreviations"
+       <*> o .:? "reference-doc"
+       <*> ((o .:? "split-level") <|> (o .:? "epub-chapter-level"))
+             .!= optSplitLevel defaultOpts
+       <*> o .:? "chunk-template"
+       <*> o .:? "epub-subdirectory" .!= optEpubSubdirectory defaultOpts
+       <*> o .:? "epub-metadata"
+       <*> o .:? "epub-fonts" .!= optEpubFonts defaultOpts
+       <*> o .:? "epub-cover-image"
+       <*> o .:? "epub-title-page" .!= optEpubTitlePage defaultOpts
+       <*> o .:? "toc-depth" .!= optTOCDepth defaultOpts
+       <*> o .:? "dump-args" .!= optDumpArgs defaultOpts
+       <*> o .:? "ignore-args" .!= optIgnoreArgs defaultOpts
+       <*> o .:? "verbosity" .!= optVerbosity defaultOpts
+       <*> o .:? "trace" .!= optTrace defaultOpts
+       <*> o .:? "log-file"
+       <*> o .:? "fail-if-warnings" .!= optFailIfWarnings defaultOpts
+       <*> o .:? "reference-links" .!= optReferenceLinks defaultOpts
+       <*> o .:? "reference-location" .!= optReferenceLocation defaultOpts
+       <*> o .:? "figure-caption-position" .!= optFigureCaptionPosition defaultOpts
+       <*> o .:? "table-caption-position" .!= optTableCaptionPosition defaultOpts
+       <*> o .:? "dpi" .!= optDpi defaultOpts
+       <*> o .:? "wrap" .!= optWrap defaultOpts
+       <*> o .:? "columns" .!= optColumns defaultOpts
+       <*> o .:? "filters" .!= optFilters defaultOpts
+       <*> o .:? "email-obfuscation" .!= optEmailObfuscation defaultOpts
+       <*> o .:? "identifier-prefix" .!= optIdentifierPrefix defaultOpts
+       <*> o .:? "indented-code-classes" .!= optIndentedCodeClasses defaultOpts
+       <*> o .:? "data-dir"
+       <*> o .:? "cite-method" .!= optCiteMethod defaultOpts
+       <*> o .:? "pdf-engine"
+       <*> o .:? "pdf-engine-opts" .!= optPdfEngineOpts defaultOpts
+       <*> o .:? "slide-level"
+       <*> o .:? "setext-headers" .!= optSetextHeaders defaultOpts
+       <*> o .:? "list-tables" .!= optListTables defaultOpts
+       <*> o .:? "ascii" .!= optAscii defaultOpts
+       <*> o .:? "default-image-extension" .!= optDefaultImageExtension defaultOpts
+       <*> o .:? "extract-media"
+       <*> o .:? "track-changes" .!= optTrackChanges defaultOpts
+       <*> o .:? "file-scope" .!= optFileScope defaultOpts
+       <*> o .:? "title-prefix" .!= optTitlePrefix defaultOpts
+       <*> o .:? "css" .!= optCss defaultOpts
+       <*> o .:? "ipynb-output" .!= optIpynbOutput defaultOpts
+       <*> o .:? "include-before-body" .!= optIncludeBeforeBody defaultOpts
+       <*> o .:? "include-after-body" .!= optIncludeAfterBody defaultOpts
+       <*> o .:? "include-in-header" .!= optIncludeInHeader defaultOpts
+       <*> o .:? "resource-path" .!= optResourcePath defaultOpts
+       <*> o .:? "request-headers" .!= optRequestHeaders defaultOpts
+       <*> o .:? "no-check-certificate" .!= optNoCheckCertificate defaultOpts
+       <*> o .:? "eol" .!= optEol defaultOpts
+       <*> o .:? "strip-comments" .!= optStripComments defaultOpts
+       <*> o .:? "csl"
+       <*> o .:? "bibliography" .!= optBibliography defaultOpts
+       <*> o .:? "citation-abbreviations"
+       <*> o .:? "sandbox" .!= optSandbox defaultOpts
+       <*> o .:? "typst-inputs" .!= optTypstInputs defaultOpts
+
+instance ToJSON Opt where
+ toJSON = genericToJSON defaultOptions{
+                                 fieldLabelModifier = camelTo2 '-' . drop 3,
+                                 omitNothingFields = True }
+
+
+instance FromJSON (Opt -> Opt) where
+  parseJSON (Object m) =
+    case fromJSON (Object m) of
+      Error err' -> fail err'
+      Success (m' :: M.Map Text Value) -> chain doOpt (M.toList m')
+  parseJSON _ = fail "Expected a mapping"
+
+data DefaultsState = DefaultsState
+    {
+      curDefaults      :: Maybe FilePath -- currently parsed file
+    , inheritanceGraph :: [[FilePath]]   -- defaults file inheritance graph
+    } deriving (Show)
+
+instance (PandocMonad m, MonadIO m)
+      => FromJSON (Opt -> StateT DefaultsState m Opt) where
+  parseJSON (Object o) =
+    case fromJSON (Object o) of
+      Error err' -> fail err'
+      Success (opts :: M.Map Text Value) -> do
+        dataDir <- case M.lookup "data-dir" opts of
+          Nothing -> return Nothing
+          Just v -> Just . unpack <$> parseJSON v
+        f <- parseOptions (M.toList opts)
+        case M.lookup "defaults" opts of
+          Just v -> do
+            g <- parseDefaults v dataDir
+            return  $ g >=> f >=> resolveVarsInOpt
+          Nothing -> return $ f >=> resolveVarsInOpt
+  parseJSON _ = fail "Expected a mapping"
+
+resolveVarsInOpt :: forall m. (PandocMonad m, MonadIO m)
+                 => Opt -> StateT DefaultsState m Opt
+resolveVarsInOpt
+    opt@Opt
+    { optTo                    = oTo
+    , optFrom                  = oFrom
+    , optTemplate              = oTemplate
+    , optMetadataFiles         = oMetadataFiles
+    , optOutputFile            = oOutputFile
+    , optInputFiles            = oInputFiles
+    , optSyntaxDefinitions     = oSyntaxDefinitions
+    , optSyntaxHighlighting    = oSyntaxHighlighting
+    , optAbbreviations         = oAbbreviations
+    , optReferenceDoc          = oReferenceDoc
+    , optEpubMetadata          = oEpubMetadata
+    , optEpubFonts             = oEpubFonts
+    , optEpubCoverImage        = oEpubCoverImage
+    , optLogFile               = oLogFile
+    , optFilters               = oFilters
+    , optDataDir               = oDataDir
+    , optExtractMedia          = oExtractMedia
+    , optCss                   = oCss
+    , optIncludeBeforeBody     = oIncludeBeforeBody
+    , optIncludeAfterBody      = oIncludeAfterBody
+    , optIncludeInHeader       = oIncludeInHeader
+    , optResourcePath          = oResourcePath
+    , optCSL                   = oCSL
+    , optBibliography          = oBibliography
+    , optCitationAbbreviations = oCitationAbbreviations
+    , optPdfEngine             = oPdfEngine
+    }
+  = do
+      oTo' <- mapM (fmap T.pack . resolveVars . T.unpack) oTo
+      oFrom' <- mapM (fmap T.pack . resolveVars . T.unpack) oFrom
+      oTemplate' <- mapM resolveVars oTemplate
+      oMetadataFiles' <- mapM resolveVars oMetadataFiles
+      oOutputFile' <- mapM resolveVars oOutputFile
+      oInputFiles' <- mapM (mapM resolveVars) oInputFiles
+      oSyntaxDefinitions' <- mapM resolveVars oSyntaxDefinitions
+      oAbbreviations' <- mapM resolveVars oAbbreviations
+      oReferenceDoc' <- mapM resolveVars oReferenceDoc
+      oEpubMetadata' <- mapM resolveVars oEpubMetadata
+      oEpubFonts' <- mapM resolveVars oEpubFonts
+      oEpubCoverImage' <- mapM resolveVars oEpubCoverImage
+      oLogFile' <- mapM resolveVars oLogFile
+      oFilters' <- mapM resolveVarsInFilter oFilters
+      oDataDir' <- mapM resolveVars oDataDir
+      oExtractMedia' <- mapM resolveVars oExtractMedia
+      oCss' <- mapM resolveVars oCss
+      oIncludeBeforeBody' <- mapM resolveVars oIncludeBeforeBody
+      oIncludeAfterBody' <- mapM resolveVars oIncludeAfterBody
+      oIncludeInHeader' <- mapM resolveVars oIncludeInHeader
+      oResourcePath' <- mapM resolveVars oResourcePath
+      oCSL' <- mapM resolveVars oCSL
+      oBibliography' <- mapM resolveVars oBibliography
+      oCitationAbbreviations' <- mapM resolveVars oCitationAbbreviations
+      oPdfEngine' <- mapM resolveVars oPdfEngine
+      oSyntaxHighlighting' <- T.pack <$> resolveVars (T.unpack oSyntaxHighlighting)
+      return opt{ optTo                    = oTo'
+                , optFrom                  = oFrom'
+                , optTemplate              = oTemplate'
+                , optMetadataFiles         = oMetadataFiles'
+                , optOutputFile            = oOutputFile'
+                , optInputFiles            = oInputFiles'
+                , optSyntaxDefinitions     = oSyntaxDefinitions'
+                , optSyntaxHighlighting    = oSyntaxHighlighting'
+                , optAbbreviations         = oAbbreviations'
+                , optReferenceDoc          = oReferenceDoc'
+                , optEpubMetadata          = oEpubMetadata'
+                , optEpubFonts             = oEpubFonts'
+                , optEpubCoverImage        = oEpubCoverImage'
+                , optLogFile               = oLogFile'
+                , optFilters               = oFilters'
+                , optDataDir               = oDataDir'
+                , optExtractMedia          = oExtractMedia'
+                , optCss                   = oCss'
+                , optIncludeBeforeBody     = oIncludeBeforeBody'
+                , optIncludeAfterBody      = oIncludeAfterBody'
+                , optIncludeInHeader       = oIncludeInHeader'
+                , optResourcePath          = oResourcePath'
+                , optCSL                   = oCSL'
+                , optBibliography          = oBibliography'
+                , optCitationAbbreviations = oCitationAbbreviations'
+                , optPdfEngine             = oPdfEngine'
+                }
+
+ where
+  resolveVars = expandVars (optDataDir opt)
+  resolveVarsInFilter (JSONFilter fp) =
+    JSONFilter <$> resolveVars fp
+  resolveVarsInFilter (LuaFilter fp) =
+    LuaFilter <$> resolveVars fp
+  resolveVarsInFilter CiteprocFilter = return CiteprocFilter
+
+
+expandVars :: (PandocMonad m, MonadIO m)
+           => Maybe FilePath
+           -> FilePath
+           -> StateT DefaultsState m FilePath
+expandVars _ [] = return []
+expandVars mbDataDir ('$':'{':xs) =
+    let (ys, zs) = break (=='}') xs
+     in if null zs
+           then return $ '$':'{':xs
+           else do
+             val <- expandEnv mbDataDir ys
+             (val ++) <$> expandVars mbDataDir (drop 1 zs)
+expandVars mbDataDir (c:cs) = (c:) <$> expandVars mbDataDir cs
+
+expandEnv :: (PandocMonad m, MonadIO m)
+          => Maybe FilePath
+          -> String
+          -> StateT DefaultsState m String
+expandEnv _ "." = do
+    mbCurDefaults <- gets curDefaults
+    maybe (return "")
+          (fmap takeDirectory . liftIO . canonicalizePath)
+          mbCurDefaults
+expandEnv mbDataDir "USERDATA" = do
+    mbodatadir <- mapM (expandVars mbDataDir) mbDataDir
+    mbdatadir'  <- getUserDataDir
+    defdatadir <- liftIO defaultUserDataDir
+    return $ fromMaybe defdatadir (mbodatadir <|> mbdatadir')
+expandEnv _ v = do
+    mbval <- fmap T.unpack <$> lookupEnv (T.pack v)
+    case mbval of
+      Nothing -> do
+        report $ EnvironmentVariableUndefined (T.pack v)
+        return mempty
+      Just x  -> return x
+
+
+
+parseDefaults :: (PandocMonad m, MonadIO m)
+              => Value
+              -> Maybe FilePath
+              -> Parser (Opt -> StateT DefaultsState m Opt)
+parseDefaults n dataDir = parseDefsNames n >>= \ds -> return $ \o -> do
+  -- get parent defaults:
+  defsParent <- gets $ fromMaybe "" . curDefaults
+  expandedDataDir <- mapM (expandVars dataDir) dataDir
+  -- get child defaults:
+  defsChildren <- mapM (\d -> expandVars expandedDataDir d >>= lift . fullDefaultsPath expandedDataDir) ds
+  -- expand parent in defaults inheritance graph by children:
+  defsGraph <- gets inheritanceGraph
+  let defsGraphExp = expand defsGraph defsChildren defsParent
+  modify $ \defsState -> defsState{ inheritanceGraph = defsGraphExp }
+  -- check for cyclic inheritance:
+  if cyclic defsGraphExp
+    then throwError $
+      PandocSomeError $ T.pack $
+        "Error: Circular defaults file reference in " ++
+        "'" ++ defsParent ++ "'"
+    else foldM applyDefaults o defsChildren
+  where parseDefsNames x = (parseJSON x >>= \xs -> return $ map unpack xs)
+                       <|> (parseJSON x >>= \x' -> return [unpack x'])
+
+parseOptions :: Monad m
+             => [(Text, Value)]
+             -> Parser (Opt -> StateT DefaultsState m Opt)
+parseOptions ns = do
+  f <- chain doOpt' ns
+  return $ return . f
+
+chain :: Monad m => (a -> m (b -> b)) -> [a] -> m (b -> b)
+chain f = foldM g id
+  where g o n = f n >>= \o' -> return $ o' . o
+
+doOpt' :: (Text, Value) -> Parser (Opt -> Opt)
+doOpt' (k,v) = do
+  case k of
+    "defaults" -> return id
+    _ -> doOpt (k,v)
+
+doOpt :: (Text, Value) -> Parser (Opt -> Opt)
+doOpt (k,v) = do
+  case k of
+    "tab-stop" ->
+      parseJSON v >>= \x -> return (\o -> o{ optTabStop = x })
+    "preserve-tabs" ->
+      parseJSON v >>= \x -> return (\o -> o{ optPreserveTabs = x })
+    "standalone" ->
+      parseJSON v >>= \x -> return (\o -> o{ optStandalone = x })
+    "table-of-contents" ->
+      parseJSON v >>= \x -> return (\o -> o{ optTableOfContents = x })
+    "toc" ->
+      parseJSON v >>= \x -> return (\o -> o{ optTableOfContents = x })
+    "list-of-figures" ->
+      parseJSON v >>= \x -> return (\o -> o{ optListOfFigures = x })
+    "lof" ->
+      parseJSON v >>= \x -> return (\o -> o{ optListOfFigures = x })
+    "list-of-tables" ->
+      parseJSON v >>= \x -> return (\o -> o{ optListOfTables = x })
+    "lot" ->
+      parseJSON v >>= \x -> return (\o -> o{ optListOfTables = x })
+    "from" ->
+      parseJSON v >>= \x -> return (\o -> o{ optFrom = x })
+    "reader" ->
+      parseJSON v >>= \x -> return (\o -> o{ optFrom = x })
+    "to" ->
+      parseJSON v >>= \x -> return (\o -> o{ optTo = x })
+    "writer" ->
+      parseJSON v >>= \x -> return (\o -> o{ optTo = x })
+    "shift-heading-level-by" ->
+      parseJSON v >>= \x -> return (\o -> o{ optShiftHeadingLevelBy = x })
+    "template" ->
+      parseJSON v >>= \x -> return (\o -> o{ optTemplate = unpack <$> x })
+    "variables" ->
+      parseJSON v >>= \x -> return (\o -> o{ optVariables =
+                                               x <> optVariables o })
+      -- Note: x comes first because <> for Context is left-biased union
+      -- and we want to favor later default files. See #5988.
+    "metadata" ->
+      yamlToMeta v >>= \x -> return (\o -> o{ optMetadata = optMetadata o <> x })
+    "metadata-files" ->
+      parseJSON v >>= \x ->
+                        return (\o -> o{ optMetadataFiles =
+                                           optMetadataFiles o <>
+                                           map unpack x })
+    "metadata-file" -> -- allow either a list or a single value
+      (parseJSON v >>= \x -> return (\o -> o{ optMetadataFiles =
+                                                optMetadataFiles o <>
+                                                map unpack x }))
+      <|>
+      (parseJSON v >>= \x ->
+                        return (\o -> o{ optMetadataFiles =
+                                           optMetadataFiles o <>[unpack x] }))
+    "output-file" ->
+      parseJSON v >>= \x -> return (\o -> o{ optOutputFile = unpack <$> x })
+    "input-files" ->
+      parseJSON v >>= \x -> return (\o -> o{ optInputFiles =
+                                              optInputFiles o <>
+                                                (map unpack <$> x) })
+    "input-file" -> -- allow either a list or a single value
+      (parseJSON v >>= \x -> return (\o -> o{ optInputFiles =
+                                                optInputFiles o <>
+                                                  (map unpack <$> x) }))
+      <|>
+      (parseJSON v >>= \x -> return (\o -> o{ optInputFiles =
+                                                optInputFiles o <>
+                                                ((\z -> [unpack z]) <$> x)
+                                            }))
+    "number-sections" ->
+      parseJSON v >>= \x -> return (\o -> o{ optNumberSections = x })
+    "number-offset" ->
+      parseJSON v >>= \x -> return (\o -> o{ optNumberOffset = x })
+    "section-divs" ->
+      parseJSON v >>= \x -> return (\o -> o{ optSectionDivs = x })
+    "incremental" ->
+      parseJSON v >>= \x -> return (\o -> o{ optIncremental = x })
+    "self-contained" ->
+      parseJSON v >>= \x -> return (\o -> o{ optSelfContained = x })
+    "embed-resources" ->
+      parseJSON v >>= \x -> return (\o -> o{ optEmbedResources = x })
+    "link-images" ->
+      parseJSON v >>= \x -> return (\o -> o{ optLinkImages = x })
+    "html-q-tags" ->
+      parseJSON v >>= \x -> return (\o -> o{ optHtmlQTags = x })
+    -- Deprecated
+    "highlight-style" ->
+      parseJSON v >>= \x -> return (\o -> o{ optSyntaxHighlighting = x })
+    "syntax-definition" ->
+      (parseJSON v >>= \x ->
+                return (\o -> o{ optSyntaxDefinitions =
+                                   optSyntaxDefinitions o <> map unpack x }))
+      <|>
+      (parseJSON v >>= \x ->
+             return (\o -> o{ optSyntaxDefinitions =
+                                 optSyntaxDefinitions o <> [unpack x] }))
+    "syntax-definitions" ->
+      parseJSON v >>= \x ->
+             return (\o -> o{ optSyntaxDefinitions =
+                                optSyntaxDefinitions o <> map unpack x })
+    "syntax-highlighting" ->
+      parseJSON v >>= \x -> return (\o -> o{ optSyntaxHighlighting = x })
+    "top-level-division" ->
+      parseJSON v >>= \x -> return (\o -> o{ optTopLevelDivision = x })
+    "html-math-method" ->
+      parseJSON v >>= \x -> return (\o -> o{ optHTMLMathMethod = x })
+    "abbreviations" ->
+      parseJSON v >>= \x ->
+             return (\o -> o{ optAbbreviations = unpack <$> x })
+    "reference-doc" ->
+      parseJSON v >>= \x ->
+             return (\o -> o{ optReferenceDoc = unpack <$> x })
+    "epub-subdirectory" ->
+      parseJSON v >>= \x ->
+             return (\o -> o{ optEpubSubdirectory = unpack x })
+    "epub-metadata" ->
+      parseJSON v >>= \x ->
+             return (\o -> o{ optEpubMetadata = unpack <$> x })
+    "epub-fonts" ->
+      parseJSON v >>= \x -> return (\o -> o{ optEpubFonts = optEpubFonts o <>
+                                               map unpack x })
+    "epub-chapter-level" ->
+      parseJSON v >>= \x -> return (\o -> o{ optSplitLevel = x })
+    "split-level" ->
+      parseJSON v >>= \x -> return (\o -> o{ optSplitLevel = x })
+    "chunk-template" ->
+      parseJSON v >>= \x -> return (\o -> o{ optChunkTemplate = Just x })
+    "epub-cover-image" ->
+      parseJSON v >>= \x ->
+             return (\o -> o{ optEpubCoverImage = unpack <$> x })
+    "epub-title-page" ->
+      parseJSON v >>= \x -> return (\o -> o{ optEpubTitlePage = x })
+    "toc-depth" ->
+      parseJSON v >>= \x -> return (\o -> o{ optTOCDepth = x })
+    "dump-args" ->
+      parseJSON v >>= \x -> return (\o -> o{ optDumpArgs = x })
+    "ignore-args" ->
+      parseJSON v >>= \x -> return (\o -> o{ optIgnoreArgs = x })
+    "verbosity" ->
+      parseJSON v >>= \x -> return (\o -> o{ optVerbosity = x })
+    "trace" ->
+      parseJSON v >>= \x -> return (\o -> o{ optTrace = x })
+    "log-file" ->
+      parseJSON v >>= \x -> return (\o -> o{ optLogFile = unpack <$> x })
+    "fail-if-warnings" ->
+      parseJSON v >>= \x -> return (\o -> o{ optFailIfWarnings = x })
+    "reference-links" ->
+      parseJSON v >>= \x -> return (\o -> o{ optReferenceLinks = x })
+    "reference-location" ->
+      parseJSON v >>= \x -> return (\o -> o{ optReferenceLocation = x })
+    "figure-caption-position" ->
+      parseJSON v >>= \x -> return (\o -> o{ optFigureCaptionPosition = x })
+    "table-caption-position" ->
+      parseJSON v >>= \x -> return (\o -> o{ optTableCaptionPosition = x })
+    "dpi" ->
+      parseJSON v >>= \x -> return (\o -> o{ optDpi = x })
+    "wrap" ->
+      parseJSON v >>= \x -> return (\o -> o{ optWrap = x })
+    "columns" ->
+      parseJSON v >>= \x -> return (\o -> o{ optColumns = x })
+    "filters" ->
+      parseJSON v >>= \x -> return (\o -> o{ optFilters = optFilters o <> x })
+    "citeproc" ->
+      parseJSON v >>= \x ->
+        if x
+           then return (\o -> o{ optFilters = CiteprocFilter : optFilters o })
+           else return id
+    "email-obfuscation" ->
+      parseJSON v >>= \x -> return (\o -> o{ optEmailObfuscation = x })
+    "identifier-prefix" ->
+      parseJSON v >>= \x ->
+             return (\o -> o{ optIdentifierPrefix = x })
+    "indented-code-classes" ->
+      parseJSON v >>= \x ->
+             return (\o -> o{ optIndentedCodeClasses = x })
+    "data-dir" ->
+      parseJSON v >>= \x -> return (\o -> o{ optDataDir = unpack <$> x })
+    "cite-method" ->
+      parseJSON v >>= \x -> return (\o -> o{ optCiteMethod = x })
+    "listings" ->
+      parseJSON v >>= \x ->
+        if x
+        then return (\o -> o{ optSyntaxHighlighting = "idiomatic" })
+        else return id
+    "pdf-engine" ->
+      parseJSON v >>= \x -> return (\o -> o{ optPdfEngine = unpack <$> x })
+    "pdf-engine-opts" ->
+      parseJSON v >>= \x ->
+             return (\o -> o{ optPdfEngineOpts = map unpack x })
+    "pdf-engine-opt" ->
+      (parseJSON v >>= \x ->
+             return (\o -> o{ optPdfEngineOpts = map unpack x }))
+      <|>
+      (parseJSON v >>= \x ->
+             return (\o -> o{ optPdfEngineOpts = [unpack x] }))
+    "slide-level" ->
+      parseJSON v >>= \x -> return (\o -> o{ optSlideLevel = x })
+    "markdown-headings" ->
+      parseJSON v >>= \x -> return (\o ->
+        case T.toLower x of
+          "atx"    -> o{ optSetextHeaders = False }
+          "setext" -> o{ optSetextHeaders = True }
+          _        -> o)
+    "list-tables" ->
+      parseJSON v >>= \x -> return (\o -> o{ optListTables = x })
+    "ascii" ->
+      parseJSON v >>= \x -> return (\o -> o{ optAscii = x })
+    "default-image-extension" ->
+      parseJSON v >>= \x ->
+             return (\o -> o{ optDefaultImageExtension = x })
+    "extract-media" ->
+      parseJSON v >>= \x ->
+             return (\o -> o{ optExtractMedia = unpack <$> x })
+    "track-changes" ->
+      parseJSON v >>= \x -> return (\o -> o{ optTrackChanges = x })
+    "file-scope" ->
+      parseJSON v >>= \x -> return (\o -> o{ optFileScope = x })
+    "title-prefix" ->
+      parseJSON v >>= \x -> return (\o -> o{ optTitlePrefix = x,
+                                             optStandalone = True })
+    "css" ->
+      (parseJSON v >>= \x -> return (\o -> o{ optCss = optCss o <>
+                                                 map unpack x }))
+      <|>
+      (parseJSON v >>= \x -> return (\o -> o{ optCss = optCss o <>
+                                                [unpack x] }))
+    "bibliography" ->
+      (parseJSON v >>= \x -> return (\o ->
+                               o{ optBibliography = optBibliography o <>
+                                                      map unpack x }))
+      <|>
+      (parseJSON v >>= \x -> return (\o ->
+                               o{ optBibliography = optBibliography o <>
+                                                       [unpack x] }))
+    "csl" ->
+      parseJSON v >>= \x -> return (\o -> o{ optCSL = unpack <$> x })
+    "citation-abbreviations" ->
+      parseJSON v >>= \x -> return (\o -> o{ optCitationAbbreviations =
+                                                  unpack <$> x })
+    "ipynb-output" ->
+      parseJSON v >>= \x -> return (\o -> o{ optIpynbOutput = x })
+    "include-before-body" ->
+      (parseJSON v >>= \x ->
+             return (\o -> o{ optIncludeBeforeBody =
+                                optIncludeBeforeBody o <> map unpack x }))
+      <|>
+      (parseJSON v >>= \x ->
+             return (\o -> o{ optIncludeBeforeBody =
+                                optIncludeBeforeBody o <> [unpack x] }))
+    "include-after-body" ->
+      (parseJSON v >>= \x ->
+             return (\o -> o{ optIncludeAfterBody =
+                                optIncludeAfterBody o <> map unpack x }))
+      <|>
+      (parseJSON v >>= \x ->
+             return (\o -> o{ optIncludeAfterBody =
+                                optIncludeAfterBody o <> [unpack x] }))
+    "include-in-header" ->
+      (parseJSON v >>= \x ->
+             return (\o -> o{ optIncludeInHeader =
+                                optIncludeInHeader o <> map unpack x }))
+      <|>
+      (parseJSON v >>= \x ->
+             return (\o -> o{ optIncludeInHeader =
+                                optIncludeInHeader o <> [unpack x] }))
+    "resource-path" ->
+      parseJSON v >>= \x ->
+             return (\o -> o{ optResourcePath = map unpack x <>
+                                 optResourcePath o })
+    "request-headers" ->
+      parseJSON v >>= \x ->
+             return (\o -> o{ optRequestHeaders = x })
+    "no-check-certificate" ->
+      parseJSON v >>= \x ->
+             return (\o -> o{ optNoCheckCertificate = x })
+    "eol" ->
+      parseJSON v >>= \x -> return (\o -> o{ optEol = x })
+    "strip-comments" ->
+      parseJSON v >>= \x -> return (\o -> o  { optStripComments = x })
+    "sandbox" ->
+      parseJSON v >>= \x -> return (\o -> o  { optSandbox = x })
+    _ -> fail $ "Unknown option " ++ show k
+
+-- | Defaults for command-line options.
+defaultOpts :: Opt
+defaultOpts = Opt
+    { optTabStop               = 4
+    , optPreserveTabs          = False
+    , optStandalone            = False
+    , optFrom                  = Nothing
+    , optTo                    = Nothing
+    , optTableOfContents       = False
+    , optListOfFigures         = False
+    , optListOfTables          = False
+    , optShiftHeadingLevelBy   = 0
+    , optTemplate              = Nothing
+    , optVariables             = mempty
+    , optMetadata              = mempty
+    , optMetadataFiles         = []
+    , optOutputFile            = Nothing
+    , optInputFiles            = Nothing
+    , optNumberSections        = False
+    , optNumberOffset          = []
+    , optSectionDivs           = False
+    , optIncremental           = False
+    , optSelfContained         = False
+    , optEmbedResources        = False
+    , optLinkImages            = False
+    , optHtmlQTags             = False
+    , optSyntaxDefinitions     = []
+    , optSyntaxHighlighting    = DefaultHighlightingString
+    , optTopLevelDivision      = TopLevelDefault
+    , optHTMLMathMethod        = PlainMath
+    , optAbbreviations         = Nothing
+    , optReferenceDoc          = Nothing
+    , optSplitLevel            = 1
+    , optChunkTemplate         = Nothing
+    , optEpubSubdirectory      = "EPUB"
+    , optEpubMetadata          = Nothing
+    , optEpubFonts             = []
+    , optEpubCoverImage        = Nothing
+    , optEpubTitlePage         = True
+    , optTOCDepth              = 3
+    , optDumpArgs              = False
+    , optIgnoreArgs            = False
+    , optVerbosity             = WARNING
+    , optTrace                 = False
+    , optLogFile               = Nothing
+    , optFailIfWarnings        = False
+    , optReferenceLinks        = False
+    , optReferenceLocation     = EndOfDocument
+    , optFigureCaptionPosition = CaptionBelow
+    , optTableCaptionPosition  = CaptionAbove
+    , optDpi                   = 96
+    , optWrap                  = WrapAuto
+    , optColumns               = 72
+    , optFilters               = []
+    , optEmailObfuscation      = NoObfuscation
+    , optIdentifierPrefix      = ""
+    , optIndentedCodeClasses   = []
+    , optDataDir               = Nothing
+    , optCiteMethod            = Citeproc
+    , optPdfEngine             = Nothing
+    , optPdfEngineOpts         = []
+    , optSlideLevel            = Nothing
+    , optSetextHeaders         = False
+    , optListTables            = False
+    , optAscii                 = False
+    , optDefaultImageExtension = ""
+    , optExtractMedia          = Nothing
+    , optTrackChanges          = AcceptChanges
+    , optFileScope             = False
+    , optTitlePrefix           = Nothing
+    , optCss                   = []
+    , optIpynbOutput           = IpynbOutputBest
+    , optIncludeBeforeBody     = []
+    , optIncludeAfterBody      = []
+    , optIncludeInHeader       = []
+    , optResourcePath          = ["."]
+    , optRequestHeaders        = []
+    , optNoCheckCertificate    = False
+    , optEol                   = Native
+    , optStripComments         = False
+    , optCSL                   = Nothing
+    , optBibliography          = []
+    , optCitationAbbreviations = Nothing
+    , optSandbox               = False
+    , optTypstInputs           = []
+    }
+
+yamlToMeta :: Value -> Parser Meta
+yamlToMeta (Object o) =
+  either (fail . show) return $ runEverything (yamlMap pMetaString o)
+ where
+  pMetaString = pure . MetaString <$> P.manyChar P.anyChar
+  runEverything p =
+      runPure (P.readWithM p (def :: P.ParserState) ("" :: Text))
+      >>= fmap (Meta . flip P.runF def)
+yamlToMeta _ = return mempty
+
+-- | Apply defaults from --defaults file.
+applyDefaults :: (PandocMonad m, MonadIO m)
+              => Opt
+              -> FilePath
+              -> StateT DefaultsState m Opt
+applyDefaults opt file = do
+  setVerbosity $ optVerbosity opt
+  modify $ \defsState -> defsState{ curDefaults = Just file }
+  inp <- readFileStrict file
+  let isJSON = B8.take 1 (B8.dropWhile isSpace inp) == "{"
+  if isJSON
+     then
+       case eitherDecodeStrict inp of
+         Right f -> f opt
+         Left err' -> throwError $ PandocParseError $ T.pack $
+            "Error parsing " <> file <> ":\n" <> err'
+     else
+       case decodeEither' (B8.unlines . takeWhile (/= "...") . B8.lines $ inp) of
+           Right f -> f opt
+           Left err'  -> throwError $ PandocParseError $ T.pack $
+                  "Error parsing " <> file <> ":\n" <>
+                  Data.Yaml.prettyPrintParseException err'
+
+fullDefaultsPath :: (PandocMonad m, MonadIO m)
+                 => Maybe FilePath
+                 -> FilePath
+                 -> m FilePath
+fullDefaultsPath dataDir file = do
+  let fp = if null (takeExtension file)
+              then addExtension file "yaml"
+              else file
+  defaultDataDir <- liftIO defaultUserDataDir
+  let defaultFp = fromMaybe defaultDataDir dataDir </> "defaults" </> fp
+  fpExists <- fileExists fp
+  if fpExists
+     then return fp
+     else do
+       defaultFpExists <- fileExists defaultFp
+       if defaultFpExists
+          then return defaultFp
+          else return fp
+
+-- | In a list of lists, append another list in front of every list which
+-- starts with specific element.
+expand :: Ord a => [[a]] -> [a] -> a -> [[a]]
+expand [] ns n = fmap (\x -> x : [n]) ns
+expand ps ns n = concatMap (ext n ns) ps
+  where
+    ext x xs p = case p of
+      (l : _) | x == l -> fmap (: p) xs
+      _ -> [p]
+
+cyclic :: Ord a => [[a]] -> Bool
+cyclic = any hasDuplicate
+  where
+    hasDuplicate xs = length (nubOrd xs) /= length xs
diff --git a/src/Text/Pandoc/App/OutputSettings.hs b/src/Text/Pandoc/App/OutputSettings.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/App/OutputSettings.hs
@@ -0,0 +1,343 @@
+{-# LANGUAGE CPP                 #-}
+{-# LANGUAGE FlexibleContexts    #-}
+{-# LANGUAGE LambdaCase          #-}
+{-# LANGUAGE OverloadedStrings   #-}
+{-# LANGUAGE PatternSynonyms     #-}
+{-# LANGUAGE ScopedTypeVariables #-}
+{-# LANGUAGE TupleSections       #-}
+{- |
+   Module      : Text.Pandoc.App
+   Copyright   : Copyright (C) 2006-2024 John MacFarlane
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : John MacFarlane <jgm@berkeley@edu>
+   Stability   : alpha
+   Portability : portable
+
+Does a pandoc conversion based on command-line options.
+-}
+module Text.Pandoc.App.OutputSettings
+  ( OutputSettings (..)
+  , optToOutputSettings
+  , sandbox'
+  ) where
+import qualified Data.Map as M
+import qualified Data.Text as T
+import Text.DocTemplates (toVal, Context(..), Val(..))
+import qualified Control.Exception as E
+import Control.Monad
+import Control.Monad.Except (throwError, catchError)
+import Control.Monad.Trans
+import Data.Char (toLower)
+import Data.List (find)
+import Data.Maybe (catMaybes, fromMaybe)
+import Skylighting (defaultSyntaxMap)
+import Skylighting.Parser (addSyntaxDefinition, parseSyntaxDefinition)
+import System.Directory (getCurrentDirectory)
+import System.Exit (exitSuccess)
+import System.FilePath
+import System.IO (stdout)
+import Text.Pandoc.Chunks (PathTemplate(..))
+import Text.Pandoc
+import Text.Pandoc.Filter (Filter(CiteprocFilter))
+import Text.Pandoc.App.Opt (Opt (..))
+import Text.Pandoc.App.CommandLineOptions (engines)
+import Text.Pandoc.Format (FlavoredFormat (..), applyExtensionsDiff,
+                           parseFlavoredFormat, formatFromFilePaths)
+import Text.Pandoc.Highlighting (lookupHighlightingStyle)
+import Text.Pandoc.Scripting (ScriptingEngine (engineLoadCustom),
+                              CustomComponents(..))
+import qualified Text.Pandoc.UTF8 as UTF8
+
+readUtf8File :: PandocMonad m => FilePath -> m T.Text
+readUtf8File fp = readFileStrict fp >>= toTextM fp
+
+-- | Settings specifying how document output should be produced.
+data OutputSettings m = OutputSettings
+  { outputFormat :: T.Text
+  , outputWriter :: Writer m
+  , outputWriterOptions :: WriterOptions
+  , outputPdfProgram :: Maybe String
+  }
+
+-- | Get output settings from command line options.
+optToOutputSettings :: (PandocMonad m, MonadIO m)
+                    => ScriptingEngine -> Opt -> m (OutputSettings m)
+optToOutputSettings scriptingEngine opts = do
+  let outputFile = fromMaybe "-" (optOutputFile opts)
+
+  when (optDumpArgs opts) . liftIO $ do
+    UTF8.hPutStrLn stdout (T.pack outputFile)
+    mapM_ (UTF8.hPutStrLn stdout . T.pack) (fromMaybe [] $ optInputFiles opts)
+    exitSuccess
+
+  epubMetadata <- traverse readUtf8File $ optEpubMetadata opts
+
+  let pdfOutput = map toLower (takeExtension outputFile) == ".pdf" ||
+                  optTo opts == Just "pdf"
+  let defaultOutput = "html"
+  defaultOutputFlavor <- parseFlavoredFormat defaultOutput
+  (flvrd@(FlavoredFormat format _extsDiff), maybePdfProg) <-
+    if pdfOutput
+       then do
+         outflavor <- case optTo opts of
+                        Just x | x /= "pdf" -> Just <$> parseFlavoredFormat x
+                        _ -> pure Nothing
+         liftIO $ pdfWriterAndProg outflavor (optPdfEngine opts)
+       else case optTo opts of
+              Just f -> (, optPdfEngine opts) <$> parseFlavoredFormat f
+              Nothing
+               | outputFile == "-" ->
+                   return (defaultOutputFlavor, optPdfEngine opts)
+               | otherwise -> case formatFromFilePaths [outputFile] of
+                   Nothing -> do
+                     report $ CouldNotDeduceFormat
+                       [T.pack $ takeExtension outputFile] defaultOutput
+                     return (defaultOutputFlavor, optPdfEngine opts)
+                   Just f  -> return (f, optPdfEngine opts)
+
+  when (format == "asciidoctor") $ do
+    report $ Deprecated "asciidoctor" "use asciidoc instead"
+
+  let makeSandboxed pureWriter =
+        case pureWriter of
+             TextWriter w -> TextWriter $ \o d -> sandbox' opts (w o d)
+             ByteStringWriter w -> ByteStringWriter $ \o d -> sandbox' opts (w o d)
+
+  let standalone = optStandalone opts || isBinaryFormat format || pdfOutput
+  let templateOrThrow = \case
+        Left  e -> throwError $ PandocTemplateError (T.pack e)
+        Right t -> pure t
+  let processCustomTemplate getDefault =
+        case optTemplate opts of
+          _ | not standalone -> return Nothing
+          Nothing -> Just <$> getDefault
+          Just tp -> do
+            let getAndCompile fp =
+                   getTemplate fp >>= runWithPartials . compileTemplate fp >>=
+                      fmap Just . templateOrThrow
+            catchError
+              (getAndCompile tp)
+              (\e ->
+                  if null (takeExtension tp)
+                     then getAndCompile (tp <.> T.unpack format)
+                     else throwError e)
+
+  (writer, writerExts', mtemplate) <-
+    if "lua" `T.isSuffixOf` format
+    then do
+      let path = T.unpack format
+      components <- engineLoadCustom scriptingEngine path
+      w <- case customWriter components of
+             Nothing -> throwError $ PandocAppError $
+                         format <> " does not contain a custom writer"
+             Just w -> return w
+      let extsConf = fromMaybe mempty $ customExtensions components
+      wexts <- applyExtensionsDiff extsConf flvrd
+      templ <- processCustomTemplate $
+               case customTemplate components of
+                 Nothing -> throwError $ PandocNoTemplateError format
+                 Just t -> runWithDefaultPartials (compileTemplate path t) >>=
+                           templateOrThrow
+      return (w, wexts, templ)
+    else
+      if optSandbox opts
+      then do
+        tmpl <- processCustomTemplate (compileDefaultTemplate format)
+        case runPure (getWriter flvrd) of
+             Right (w, wexts) -> return (makeSandboxed w, wexts, tmpl)
+             Left e           -> throwError e
+      else do
+        (w, wexts) <- getWriter flvrd
+        tmpl <- processCustomTemplate (compileDefaultTemplate format)
+        return (w, wexts, tmpl)
+
+  -- see #10662:
+  let writerExts = if CiteprocFilter `elem` optFilters opts
+                      then disableExtension Ext_citations writerExts'
+                      else writerExts'
+
+  let addSyntaxMap existingmap f = do
+        res <- liftIO (parseSyntaxDefinition f)
+        case res of
+              Left errstr -> throwError $ PandocSyntaxMapError $ T.pack errstr
+              Right syn   -> return $ addSyntaxDefinition syn existingmap
+
+  syntaxMap <- foldM addSyntaxMap defaultSyntaxMap
+                     (optSyntaxDefinitions opts)
+
+  hlStyle <- case optSyntaxHighlighting opts of
+    NoHighlightingString        -> pure NoHighlighting
+    DefaultHighlightingString   -> pure DefaultHighlighting
+    IdiomaticHighlightingString -> pure IdiomaticHighlighting
+    style       -> Skylighting <$> lookupHighlightingStyle (T.unpack style)
+
+  let setListVariableM _ [] ctx = return ctx
+      setListVariableM k vs ctx = do
+        let ctxMap = unContext ctx
+        return $ Context $
+          case M.lookup k ctxMap of
+              Just (ListVal xs) -> M.insert k
+                                  (ListVal $ xs ++ map toVal vs) ctxMap
+              Just v -> M.insert k
+                         (ListVal $ v : map toVal vs) ctxMap
+              Nothing -> M.insert k (toVal vs) ctxMap
+
+  let getTextContents fp = (fst <$> fetchItem (T.pack fp)) >>= toTextM fp
+
+  let setFilesVariableM k fps ctx = do
+        xs <- mapM getTextContents fps
+        setListVariableM k xs ctx
+
+  curdir <- liftIO getCurrentDirectory
+
+  variables <-
+    return (optVariables opts)
+    >>=
+    setListVariableM "sourcefile"
+      (maybe ["-"] (fmap T.pack) (optInputFiles opts))
+    >>=
+    setVariableM "outputfile" (T.pack outputFile)
+    >>=
+    setVariableM "pandoc-version" pandocVersionText
+    >>=
+    maybe return (setVariableM "pdf-engine" . T.pack) maybePdfProg
+    >>=
+    setFilesVariableM "include-before" (optIncludeBeforeBody opts)
+    >>=
+    setFilesVariableM "include-after" (optIncludeAfterBody opts)
+    >>=
+    setFilesVariableM "header-includes" (optIncludeInHeader opts)
+    >>=
+    setListVariableM "css" (map T.pack $ optCss opts)
+    >>=
+    maybe return (setVariableM "title-prefix") (optTitlePrefix opts)
+    >>=
+    maybe return (setVariableM "epub-cover-image" . T.pack)
+                 (optEpubCoverImage opts)
+    >>=
+    setVariableM "curdir" (T.pack curdir)
+    >>=
+    (\vars ->  if format == "dzslides"
+                  then do
+                      dztempl <-
+                        let fp = "dzslides" </> "template.html"
+                         in readDataFile fp >>= toTextM fp
+                      let dzline = "<!-- {{{{ dzslides core"
+                      let dzcore = T.unlines
+                                 $ dropWhile (not . (dzline `T.isPrefixOf`))
+                                 $ T.lines dztempl
+                      setVariableM "dzslides-core" dzcore vars
+                  else return vars)
+
+  let writerOpts = WriterOptions
+        { writerTemplate         = mtemplate
+        , writerVariables        = variables
+        , writerTabStop          = optTabStop opts
+        , writerTableOfContents  = optTableOfContents opts
+        , writerListOfFigures    = optListOfFigures opts
+        , writerListOfTables     = optListOfTables opts
+        , writerHTMLMathMethod   = optHTMLMathMethod opts
+        , writerIncremental      = optIncremental opts
+        , writerCiteMethod       = optCiteMethod opts
+        , writerNumberSections   = optNumberSections opts
+        , writerNumberOffset     = optNumberOffset opts
+        , writerSectionDivs      = optSectionDivs opts
+        , writerExtensions       = writerExts
+        , writerReferenceLinks   = optReferenceLinks opts
+        , writerReferenceLocation = optReferenceLocation opts
+        , writerFigureCaptionPosition = optFigureCaptionPosition opts
+        , writerTableCaptionPosition = optTableCaptionPosition opts
+        , writerDpi              = optDpi opts
+        , writerWrapText         = optWrap opts
+        , writerColumns          = optColumns opts
+        , writerEmailObfuscation = optEmailObfuscation opts
+        , writerIdentifierPrefix = optIdentifierPrefix opts
+        , writerHtmlQTags        = optHtmlQTags opts
+        , writerTopLevelDivision = optTopLevelDivision opts
+        , writerSlideLevel       = optSlideLevel opts
+        , writerHighlightMethod  = hlStyle
+        , writerSetextHeaders    = optSetextHeaders opts
+        , writerListTables       = optListTables opts
+        , writerEpubSubdirectory = T.pack $ optEpubSubdirectory opts
+        , writerEpubMetadata     = epubMetadata
+        , writerEpubFonts        = optEpubFonts opts
+        , writerEpubTitlePage    = optEpubTitlePage opts
+        , writerSplitLevel       = optSplitLevel opts
+        , writerChunkTemplate    = maybe (PathTemplate "%s-%i.html")
+                                     PathTemplate
+                                     (optChunkTemplate opts)
+        , writerTOCDepth         = optTOCDepth opts
+        , writerReferenceDoc     = optReferenceDoc opts
+        , writerSyntaxMap        = syntaxMap
+        , writerPreferAscii      = optAscii opts
+        , writerLinkImages       = optLinkImages opts
+        }
+  return $ OutputSettings
+    { outputFormat = format
+    , outputWriter = writer
+    , outputWriterOptions = writerOpts
+    , outputPdfProgram = maybePdfProg
+    }
+
+-- | Set text value in text context unless it is already set.
+setVariableM :: Monad m
+             => T.Text -> T.Text -> Context T.Text -> m (Context T.Text)
+setVariableM key val (Context ctx) = return $ Context $ M.alter go key ctx
+  where go Nothing             = Just $ toVal val
+        go (Just x)            = Just x
+
+pdfWriterAndProg :: Maybe FlavoredFormat      -- ^ user-specified format
+                 -> Maybe String              -- ^ user-specified pdf-engine
+                 -> IO (FlavoredFormat, Maybe String) -- ^ format, pdf-engine
+pdfWriterAndProg mWriter mEngine =
+  case go mWriter mEngine of
+      Right (writ, prog) -> return (writ, Just prog)
+      Left err           -> liftIO $ E.throwIO $ PandocAppError err
+    where
+      go Nothing Nothing       = Right
+                                 (FlavoredFormat "latex" mempty, "pdflatex")
+      go (Just writer) Nothing = (writer,) <$> engineForWriter writer
+      go Nothing (Just engine) = (,engine) <$> writerForEngine (takeBaseName engine)
+      go (Just writer) (Just engine) | isCustomWriter writer =
+           -- custom writers can produce any format, so assume the user knows
+           -- what they are doing.
+           Right (writer, engine)
+      go (Just writer) (Just engine) =
+           case find (== (formatName writer, takeBaseName engine)) engines of
+                Just _  -> Right (writer, engine)
+                Nothing -> Left $ "pdf-engine " <> T.pack engine <>
+                           " is not compatible with output format " <>
+                           formatName writer
+
+      writerForEngine eng = case [f | (f,e) <- engines, e == eng] of
+                                 fmt : _ -> Right (FlavoredFormat fmt mempty)
+                                 []      -> Left $
+                                   "pdf-engine " <> T.pack eng <> " not known"
+
+      engineForWriter (FlavoredFormat "pdf" _) = Left "pdf writer"
+      engineForWriter w = case [e | (f,e) <- engines, f == formatName w] of
+                                eng : _ -> Right eng
+                                []      -> Left $
+                                   "cannot produce pdf output from " <>
+                                   formatName w
+
+      isCustomWriter w = ".lua" `T.isSuffixOf` formatName w
+
+isBinaryFormat :: T.Text -> Bool
+isBinaryFormat s =
+  s `elem` ["odt","docx","epub2","epub3","epub","pptx","pdf","chunkedhtml"]
+
+-- Like 'sandbox', but computes the list of files to preserve from
+-- 'Opt'.
+sandbox' :: (PandocMonad m, MonadIO m) => Opt -> PandocPure a -> m a
+sandbox' opts = sandbox sandboxedFiles
+ where
+   sandboxedFiles = catMaybes [ optReferenceDoc opts
+                              , optEpubMetadata opts
+                              , optEpubCoverImage opts
+                              , optCSL opts
+                              , optCitationAbbreviations opts
+                              ] ++
+                    optEpubFonts opts ++
+                    optBibliography opts
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,24 +1,6 @@
-{-
-Copyright (C) 2013-2017 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-2017 John MacFarlane
+   Copyright   : Copyright (C) 2013-2024 John MacFarlane
    License     : GNU GPL, version 2 or above
 
    Maintainer  : John MacFarlane <jgm@berkeley.edu>
@@ -28,395 +10,23 @@
 Function to convert accented latin letters to their unaccented
 ascii equivalents (used in constructing HTML identifiers).
 -}
-module Text.Pandoc.Asciify (toAsciiChar)
+module Text.Pandoc.Asciify (toAsciiChar, toAsciiText)
 where
-import Data.Char (isAscii)
-import qualified Data.Map as M
+import Data.Char (isAscii, isMark)
+import qualified Data.Text.Normalize as TN
+import Data.Text (Text)
+import qualified Data.Text as T
 
-toAsciiChar :: Char -> Maybe Char
-toAsciiChar c | isAscii c = Just c
-              | otherwise = M.lookup c asciiMap
+toAsciiText :: Text -> Text
+toAsciiText = T.filter isAscii . T.map specialCase . TN.normalize (TN.NFD)
+ where
+  specialCase '\x131' = 'i' -- Turkish undotted i
+  specialCase c = c
 
-asciiMap :: M.Map Char Char
-asciiMap = M.fromList
-  [('\192','A')
-  ,('\193','A')
-  ,('\194','A')
-  ,('\195','A')
-  ,('\196','A')
-  ,('\197','A')
-  ,('\199','C')
-  ,('\200','E')
-  ,('\201','E')
-  ,('\202','E')
-  ,('\203','E')
-  ,('\204','I')
-  ,('\205','I')
-  ,('\206','I')
-  ,('\207','I')
-  ,('\209','N')
-  ,('\210','O')
-  ,('\211','O')
-  ,('\212','O')
-  ,('\213','O')
-  ,('\214','O')
-  ,('\217','U')
-  ,('\218','U')
-  ,('\219','U')
-  ,('\220','U')
-  ,('\221','Y')
-  ,('\224','a')
-  ,('\225','a')
-  ,('\226','a')
-  ,('\227','a')
-  ,('\228','a')
-  ,('\229','a')
-  ,('\231','c')
-  ,('\232','e')
-  ,('\233','e')
-  ,('\234','e')
-  ,('\235','e')
-  ,('\236','i')
-  ,('\237','i')
-  ,('\238','i')
-  ,('\239','i')
-  ,('\241','n')
-  ,('\242','o')
-  ,('\243','o')
-  ,('\244','o')
-  ,('\245','o')
-  ,('\246','o')
-  ,('\249','u')
-  ,('\250','u')
-  ,('\251','u')
-  ,('\252','u')
-  ,('\253','y')
-  ,('\255','y')
-  ,('\256','A')
-  ,('\257','a')
-  ,('\258','A')
-  ,('\259','a')
-  ,('\260','A')
-  ,('\261','a')
-  ,('\262','C')
-  ,('\263','c')
-  ,('\264','C')
-  ,('\265','c')
-  ,('\266','C')
-  ,('\267','c')
-  ,('\268','C')
-  ,('\269','c')
-  ,('\270','D')
-  ,('\271','d')
-  ,('\274','E')
-  ,('\275','e')
-  ,('\276','E')
-  ,('\277','e')
-  ,('\278','E')
-  ,('\279','e')
-  ,('\280','E')
-  ,('\281','e')
-  ,('\282','E')
-  ,('\283','e')
-  ,('\284','G')
-  ,('\285','g')
-  ,('\286','G')
-  ,('\287','g')
-  ,('\288','G')
-  ,('\289','g')
-  ,('\290','G')
-  ,('\291','g')
-  ,('\292','H')
-  ,('\293','h')
-  ,('\296','I')
-  ,('\297','i')
-  ,('\298','I')
-  ,('\299','i')
-  ,('\300','I')
-  ,('\301','i')
-  ,('\302','I')
-  ,('\303','i')
-  ,('\304','I')
-  ,('\308','J')
-  ,('\309','j')
-  ,('\310','K')
-  ,('\311','k')
-  ,('\313','L')
-  ,('\314','l')
-  ,('\315','L')
-  ,('\316','l')
-  ,('\317','L')
-  ,('\318','l')
-  ,('\323','N')
-  ,('\324','n')
-  ,('\325','N')
-  ,('\326','n')
-  ,('\327','N')
-  ,('\328','n')
-  ,('\332','O')
-  ,('\333','o')
-  ,('\334','O')
-  ,('\335','o')
-  ,('\336','O')
-  ,('\337','o')
-  ,('\340','R')
-  ,('\341','r')
-  ,('\342','R')
-  ,('\343','r')
-  ,('\344','R')
-  ,('\345','r')
-  ,('\346','S')
-  ,('\347','s')
-  ,('\348','S')
-  ,('\349','s')
-  ,('\350','S')
-  ,('\351','s')
-  ,('\352','S')
-  ,('\353','s')
-  ,('\354','T')
-  ,('\355','t')
-  ,('\356','T')
-  ,('\357','t')
-  ,('\360','U')
-  ,('\361','u')
-  ,('\362','U')
-  ,('\363','u')
-  ,('\364','U')
-  ,('\365','u')
-  ,('\366','U')
-  ,('\367','u')
-  ,('\368','U')
-  ,('\369','u')
-  ,('\370','U')
-  ,('\371','u')
-  ,('\372','W')
-  ,('\373','w')
-  ,('\374','Y')
-  ,('\375','y')
-  ,('\376','Y')
-  ,('\377','Z')
-  ,('\378','z')
-  ,('\379','Z')
-  ,('\380','z')
-  ,('\381','Z')
-  ,('\382','z')
-  ,('\416','O')
-  ,('\417','o')
-  ,('\431','U')
-  ,('\432','u')
-  ,('\461','A')
-  ,('\462','a')
-  ,('\463','I')
-  ,('\464','i')
-  ,('\465','O')
-  ,('\466','o')
-  ,('\467','U')
-  ,('\468','u')
-  ,('\486','G')
-  ,('\487','g')
-  ,('\488','K')
-  ,('\489','k')
-  ,('\490','O')
-  ,('\491','o')
-  ,('\496','j')
-  ,('\500','G')
-  ,('\501','g')
-  ,('\504','N')
-  ,('\505','n')
-  ,('\512','A')
-  ,('\513','a')
-  ,('\514','A')
-  ,('\515','a')
-  ,('\516','E')
-  ,('\517','e')
-  ,('\518','E')
-  ,('\519','e')
-  ,('\520','I')
-  ,('\521','i')
-  ,('\522','I')
-  ,('\523','i')
-  ,('\524','O')
-  ,('\525','o')
-  ,('\526','O')
-  ,('\527','o')
-  ,('\528','R')
-  ,('\529','r')
-  ,('\530','R')
-  ,('\531','r')
-  ,('\532','U')
-  ,('\533','u')
-  ,('\534','U')
-  ,('\535','u')
-  ,('\536','S')
-  ,('\537','s')
-  ,('\538','T')
-  ,('\539','t')
-  ,('\542','H')
-  ,('\543','h')
-  ,('\550','A')
-  ,('\551','a')
-  ,('\552','E')
-  ,('\553','e')
-  ,('\558','O')
-  ,('\559','o')
-  ,('\562','Y')
-  ,('\563','y')
-  ,('\894',';')
-  ,('\7680','A')
-  ,('\7681','a')
-  ,('\7682','B')
-  ,('\7683','b')
-  ,('\7684','B')
-  ,('\7685','b')
-  ,('\7686','B')
-  ,('\7687','b')
-  ,('\7690','D')
-  ,('\7691','d')
-  ,('\7692','D')
-  ,('\7693','d')
-  ,('\7694','D')
-  ,('\7695','d')
-  ,('\7696','D')
-  ,('\7697','d')
-  ,('\7698','D')
-  ,('\7699','d')
-  ,('\7704','E')
-  ,('\7705','e')
-  ,('\7706','E')
-  ,('\7707','e')
-  ,('\7710','F')
-  ,('\7711','f')
-  ,('\7712','G')
-  ,('\7713','g')
-  ,('\7714','H')
-  ,('\7715','h')
-  ,('\7716','H')
-  ,('\7717','h')
-  ,('\7718','H')
-  ,('\7719','h')
-  ,('\7720','H')
-  ,('\7721','h')
-  ,('\7722','H')
-  ,('\7723','h')
-  ,('\7724','I')
-  ,('\7725','i')
-  ,('\7728','K')
-  ,('\7729','k')
-  ,('\7730','K')
-  ,('\7731','k')
-  ,('\7732','K')
-  ,('\7733','k')
-  ,('\7734','L')
-  ,('\7735','l')
-  ,('\7738','L')
-  ,('\7739','l')
-  ,('\7740','L')
-  ,('\7741','l')
-  ,('\7742','M')
-  ,('\7743','m')
-  ,('\7744','M')
-  ,('\7745','m')
-  ,('\7746','M')
-  ,('\7747','m')
-  ,('\7748','N')
-  ,('\7749','n')
-  ,('\7750','N')
-  ,('\7751','n')
-  ,('\7752','N')
-  ,('\7753','n')
-  ,('\7754','N')
-  ,('\7755','n')
-  ,('\7764','P')
-  ,('\7765','p')
-  ,('\7766','P')
-  ,('\7767','p')
-  ,('\7768','R')
-  ,('\7769','r')
-  ,('\7770','R')
-  ,('\7771','r')
-  ,('\7774','R')
-  ,('\7775','r')
-  ,('\7776','S')
-  ,('\7777','s')
-  ,('\7778','S')
-  ,('\7779','s')
-  ,('\7786','T')
-  ,('\7787','t')
-  ,('\7788','T')
-  ,('\7789','t')
-  ,('\7790','T')
-  ,('\7791','t')
-  ,('\7792','T')
-  ,('\7793','t')
-  ,('\7794','U')
-  ,('\7795','u')
-  ,('\7796','U')
-  ,('\7797','u')
-  ,('\7798','U')
-  ,('\7799','u')
-  ,('\7804','V')
-  ,('\7805','v')
-  ,('\7806','V')
-  ,('\7807','v')
-  ,('\7808','W')
-  ,('\7809','w')
-  ,('\7810','W')
-  ,('\7811','w')
-  ,('\7812','W')
-  ,('\7813','w')
-  ,('\7814','W')
-  ,('\7815','w')
-  ,('\7816','W')
-  ,('\7817','w')
-  ,('\7818','X')
-  ,('\7819','x')
-  ,('\7820','X')
-  ,('\7821','x')
-  ,('\7822','Y')
-  ,('\7823','y')
-  ,('\7824','Z')
-  ,('\7825','z')
-  ,('\7826','Z')
-  ,('\7827','z')
-  ,('\7828','Z')
-  ,('\7829','z')
-  ,('\7830','h')
-  ,('\7831','t')
-  ,('\7832','w')
-  ,('\7833','y')
-  ,('\7840','A')
-  ,('\7841','a')
-  ,('\7842','A')
-  ,('\7843','a')
-  ,('\7864','E')
-  ,('\7865','e')
-  ,('\7866','E')
-  ,('\7867','e')
-  ,('\7868','E')
-  ,('\7869','e')
-  ,('\7880','I')
-  ,('\7881','i')
-  ,('\7882','I')
-  ,('\7883','i')
-  ,('\7884','O')
-  ,('\7885','o')
-  ,('\7886','O')
-  ,('\7887','o')
-  ,('\7908','U')
-  ,('\7909','u')
-  ,('\7910','U')
-  ,('\7911','u')
-  ,('\7922','Y')
-  ,('\7923','y')
-  ,('\7924','Y')
-  ,('\7925','y')
-  ,('\7926','Y')
-  ,('\7927','y')
-  ,('\7928','Y')
-  ,('\7929','y')
-  ,('\8175','`')
-  ,('\8490','K')
-  ,('\8800','=')
-  ,('\8814','<')
-  ,('\8815','>')
-  ]
+toAsciiChar :: Char -> Maybe Char
+toAsciiChar c = case T.unpack (TN.normalize TN.NFD (T.singleton c)) of
+                  (x:xs) | isAscii x
+                         , all isMark xs
+                         -> Just x
+                  ['\x131'] -> Just 'i'  -- Turkish undotted i
+                  _      -> Nothing
diff --git a/src/Text/Pandoc/BCP47.hs b/src/Text/Pandoc/BCP47.hs
deleted file mode 100644
--- a/src/Text/Pandoc/BCP47.hs
+++ /dev/null
@@ -1,125 +0,0 @@
-{-
-Copyright (C) 2017 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 John MacFarlane
-   License     : GNU GPL, version 2 or above
-
-   Maintainer  : John MacFarlane <jgm@berkeley.edu>
-   Stability   : alpha
-   Portability : portable
-
-Functions for parsing and rendering BCP47 language identifiers.
--}
-module Text.Pandoc.BCP47 (
-                       getLang
-                     , parseBCP47
-                     , Lang(..)
-                     , renderLang
-                     )
-where
-import Control.Monad (guard)
-import Data.Char (isAlphaNum, isAscii, isLetter, isLower, isUpper, toLower,
-                  toUpper)
-import Data.List (intercalate)
-import Text.Pandoc.Definition
-import Text.Pandoc.Options
-import qualified Text.Parsec as P
-
--- | Represents BCP 47 language/country code.
-data Lang = Lang{ langLanguage :: String
-                , langScript   :: String
-                , langRegion   :: String
-                , langVariants :: [String] }
-                deriving (Eq, Ord, Show)
-
--- | Render a Lang as BCP 47.
-renderLang :: Lang -> String
-renderLang lang = intercalate "-" (langLanguage lang : filter (not . null)
-                    ([langScript lang, langRegion lang] ++ langVariants lang))
-
--- | Get the contents of the `lang` metadata field or variable.
-getLang :: WriterOptions -> Meta -> Maybe String
-getLang opts meta =
-  case lookup "lang" (writerVariables opts) of
-        Just s -> Just s
-        _      ->
-          case lookupMeta "lang" meta of
-               Just (MetaInlines [Str s]) -> Just s
-               Just (MetaString s)        -> Just s
-               _                          -> Nothing
-
--- | Parse a BCP 47 string as a Lang.  Currently we parse
--- extensions and private-use fields as "variants," even
--- though officially they aren't.
-parseBCP47 :: String -> Either String Lang
-parseBCP47 lang =
-  case P.parse bcp47 "lang" lang of
-       Right r -> Right r
-       Left e  -> Left $ show e
-  where bcp47 = do
-          language <- pLanguage
-          script <- P.option "" pScript
-          region <- P.option "" pRegion
-          variants <- P.many (pVariant P.<|> pExtension P.<|> pPrivateUse)
-          P.eof
-          return Lang{   langLanguage = language
-                       , langScript = script
-                       , langRegion = region
-                       , langVariants = variants }
-        asciiLetter = P.satisfy (\c -> isAscii c && isLetter c)
-        pLanguage = do
-          cs <- P.many1 asciiLetter
-          let lcs = length cs
-          guard $ lcs == 2 || lcs == 3
-          return $ map toLower cs
-        pScript = P.try $ do
-          P.char '-'
-          x <- P.satisfy (\c -> isAscii c && isLetter c && isUpper c)
-          xs <- P.count 3
-                 (P.satisfy (\c -> isAscii c && isLetter c && isLower c))
-          return $ map toLower (x:xs)
-        pRegion = P.try $ do
-          P.char '-'
-          cs <- P.many1 asciiLetter
-          let lcs = length cs
-          guard $ lcs == 2 || lcs == 3
-          return $ map toUpper cs
-        pVariant = P.try $ do
-          P.char '-'
-          ds <- P.option "" (P.count 1 P.digit)
-          cs <- P.many1 asciiLetter
-          let var = ds ++ cs
-          guard $ if null ds
-                     then length var >= 5 && length var <= 8
-                     else length var == 4
-          return $ map toLower var
-        pExtension = P.try $ do
-          P.char '-'
-          cs <- P.many1 $ P.satisfy (\c -> isAscii c && isAlphaNum c)
-          guard $ length cs >= 2 && length cs <= 8
-          return $ map toLower cs
-        pPrivateUse = P.try $ do
-          P.char '-'
-          P.char 'x'
-          P.char '-'
-          cs <- P.many1 $ P.satisfy (\c -> isAscii c && isAlphaNum c)
-          guard $ not (null cs) && length cs <= 8
-          let var = "x-" ++ cs
-          return $ map toLower var
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,43 +1,55 @@
-module Text.Pandoc.CSS ( foldOrElse
-                       , pickStyleAttrProps
-                       , pickStylesToKVs
-                       )
+{- |
+Module      : Text.Pandoc.CSS
+Copyright   : © 2006-2024 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
+  ( cssAttributes
+  , pickStyleAttrProps
+  , pickStylesToKVs
+  )
 where
 
+import Data.Either (fromRight)
+import Data.Maybe (mapMaybe, listToMaybe)
+import Data.Text (Text, pack)
 import Text.Pandoc.Shared (trim)
-import Text.Parsec
-import Text.Parsec.String
+import Text.Pandoc.Parsing
 
-ruleParser :: Parser (String, String)
+type Parser = Parsec Text ()
+
+ruleParser :: Parser (Text, Text)
 ruleParser = do
     p <- many1 (noneOf ":")  <* char ':'
     v <- many1 (noneOf ":;") <* optional (char ';') <* spaces
-    return (trim p, trim v)
+    return (trim $ pack p, trim $ pack v)
 
-styleAttrParser :: Parser [(String, String)]
+styleAttrParser :: Parser [(Text, Text)]
 styleAttrParser = many1 ruleParser
 
-orElse :: Eq a => a -> a -> a -> a
-orElse v x y = if v == x then y else x
-
-foldOrElse :: Eq a => a -> [a] -> a
-foldOrElse v xs = foldr (orElse v) v xs
-
-eitherToMaybe :: Either a b -> Maybe b
-eitherToMaybe (Right x) = Just x
-eitherToMaybe _         = Nothing
+-- | Parses a style string, returning the CSS attributes.
+-- Returns an empty list on failure.
+cssAttributes :: Text -> [(Text, Text)]
+cssAttributes styleString =
+  fromRight [] $ parse styleAttrParser "" styleString
 
 -- | takes a list of keys/properties and a CSS string and
 -- returns the corresponding key-value-pairs.
-pickStylesToKVs :: [String] -> String -> [(String, String)]
+pickStylesToKVs :: [Text] -> Text -> [(Text, Text)]
 pickStylesToKVs props styleAttr =
-  case parse styleAttrParser "" styleAttr of
-    Left _       -> []
-    Right styles -> filter (\s -> fst s `elem` props) styles
+  filter (\s -> fst s `elem` props) $ cssAttributes styleAttr
 
 -- | takes a list of key/property synonyms and a CSS string and maybe
 -- returns the value of the first match (in order of the supplied list)
-pickStyleAttrProps :: [String] -> String -> Maybe String
+pickStyleAttrProps :: [Text] -> Text -> Maybe Text
 pickStyleAttrProps lookupProps styleAttr = do
-    styles <- eitherToMaybe $ parse styleAttrParser "" styleAttr
-    foldOrElse Nothing $ map (`lookup` styles) lookupProps
+    styles <- either (const Nothing) Just $ parse styleAttrParser "" styleAttr
+    listToMaybe $ mapMaybe (`lookup` styles) lookupProps
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,24 +1,6 @@
-{-
-Copyright (C) 2017 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 John MacFarlane <jgm@berkeley.edu>
+   Copyright   : Copyright (C) 2017-2024 John MacFarlane <jgm@berkeley.edu>
    License     : GNU GPL, version 2 or above
    Maintainer  : John MacFarlane <jgm@berkeley.edu>
    Stability   : alpha
@@ -34,15 +16,16 @@
   ParseError
 ) where
 
-import Control.Monad (void)
+import Control.Monad (unless, void, mzero)
 import Data.Text (Text)
 import qualified Data.Text as T
-import Text.Parsec
-import Text.Parsec.Text (Parser)
+import Text.Pandoc.Parsing hiding (escaped)
 
+type Parser = Parsec Text ()
+
 data CSVOptions = CSVOptions{
     csvDelim     :: Char
-  , csvQuote     :: Char
+  , csvQuote     :: Maybe Char
   , csvKeepSpace :: Bool -- treat whitespace following delim as significant
   , csvEscape    :: Maybe Char -- default is to double up quote
 } deriving (Read, Show)
@@ -50,7 +33,7 @@
 defaultCSVOptions :: CSVOptions
 defaultCSVOptions = CSVOptions{
     csvDelim = ','
-  , csvQuote = '"'
+  , csvQuote = Just '"'
   , csvKeepSpace = False
   , csvEscape = Nothing }
 
@@ -62,39 +45,45 @@
   (pCSVRow opts `sepEndBy` endline) <* (spaces *> eof)
 
 pCSVRow :: CSVOptions -> Parser [Text]
-pCSVRow opts = notFollowedBy blank >> pCSVCell opts `sepBy` pCSVDelim opts
-
-blank :: Parser ()
-blank = try $ spaces >> (() <$ endline <|> eof)
+pCSVRow opts = do
+  x <- pCSVCell opts
+  xs <- (if T.null x then many1 else many) $ pCSVDelim opts *> pCSVCell opts
+  return (x:xs)
 
 pCSVCell :: CSVOptions -> Parser Text
 pCSVCell opts = pCSVQuotedCell opts <|> pCSVUnquotedCell opts
 
 pCSVQuotedCell :: CSVOptions -> Parser Text
-pCSVQuotedCell opts = do
-  char (csvQuote opts)
-  res <- many (satisfy (\c -> c /= csvQuote opts &&
-                              Just c /= csvEscape opts) <|> escaped opts)
-  char (csvQuote opts)
-  return $ T.pack res
+pCSVQuotedCell opts =
+  case csvQuote opts of
+    Nothing -> mzero
+    Just quotechar -> do
+      char quotechar
+      res <- many (satisfy (\c -> c /= quotechar &&
+                                  Just c /= csvEscape opts) <|> escaped opts)
+      char quotechar
+      return $ T.pack res
 
 escaped :: CSVOptions -> Parser Char
 escaped opts =
   case csvEscape opts of
-       Nothing -> try $ char (csvQuote opts) >> char (csvQuote opts)
-       Just c  -> try $ char c >> noneOf "\r\n"
+    Nothing ->
+      case csvQuote opts of
+        Nothing -> mzero
+        Just q -> try $ char q >> char q
+    Just c  -> try $ char c >> noneOf "\r\n"
 
 pCSVUnquotedCell :: CSVOptions -> Parser Text
 pCSVUnquotedCell opts = T.pack <$>
-  many (satisfy (\c -> c /= csvDelim opts && c /= '\r' && c /= '\n'
-                  && c /= csvQuote opts))
+  many (satisfy (\c -> c /= csvDelim opts && c /= '\r' && c /= '\n'))
 
 pCSVDelim :: CSVOptions -> Parser ()
 pCSVDelim opts = do
   char (csvDelim opts)
-  if csvKeepSpace opts
-     then return ()
-     else skipMany (oneOf " \t")
+  let sp = case csvDelim opts of
+              '\t' -> char ' '
+              _    -> oneOf " \t"
+  unless (csvKeepSpace opts) $ skipMany sp
 
 endline :: Parser ()
 endline = do
diff --git a/src/Text/Pandoc/Char.hs b/src/Text/Pandoc/Char.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Char.hs
@@ -0,0 +1,59 @@
+{- |
+   Module      : Text.Pandoc.Char
+   Copyright   : Copyright (C) 2024 John MacFarlane
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : John MacFarlane <jgm@berkeley.edu>
+   Stability   : alpha
+   Portability : portable
+
+Character functions not defined in Data.Char.
+-}
+module Text.Pandoc.Char ( isCJK )
+where
+
+-- | Returns True if character is CJK. Matches anything in:
+--
+-- * CJK Unified Ideographs Basic Block: U+4E00 - U+9FFF
+-- * CJK Unified Ideographs Extension A: U+3400 - U+4DBF
+-- * CJK Unified Ideographs Extension B: U+20000 - U+2A6DF
+-- * CJK Unified Ideographs Extension C: U+2A700 - U+2B73F
+-- * CJK Unified Ideographs Extension D: U+2B740 - U+2B81F
+-- * CJK Compatibility Ideographs: U+F900 - U+FAFF
+-- * CJK Compatibility Ideographs Supplement: U+2F800 - U+2FA1F
+isCJK :: Char -> Bool
+isCJK c =
+  c >= '\x4e00' &&
+  (    (c >= '\x2e80' && c <= '\x2eff') -- CJK Radicals Supplement
+    || (c >= '\x2f00' && c <= '\x2fdf') -- Kangxi Radicals
+    || (c >= '\x2ff0' && c <= '\x2fff') -- Ideographic Description Characters
+    || (c >= '\x3000' && c <= '\x303f') -- JK Symbols and Punctuation
+    || (c >= '\x3040' && c <= '\x309f') -- Hiragana
+    || (c >= '\x30a0' && c <= '\x30ff') -- Katakana
+    || (c >= '\x3100' && c <= '\x312f') -- Bopomofo
+    || (c >= '\x3130' && c <= '\x318f') -- Kanbun
+    || (c >= '\x3190' && c <= '\x319f') -- Kanbun
+    || (c >= '\x31c0' && c <= '\x31ef') -- CJK Strokes
+    || (c >= '\x31f0' && c <= '\x31ff') -- Katakana Phonetic Extensions
+    || (c >= '\x3200' && c <= '\x32ff') -- Enclosed CJK Letters & Months
+    || (c >= '\x3300' && c <= '\x33ff') -- CJK Compatibility
+    || (c >= '\x3400' && c <= '\x4dbf') -- CJK Unified Ideographs Extension A
+    || (c >= '\x4e00' && c <= '\x9fff') -- CJK Unified Ideographs
+    || (c >= '\xa000' && c <= '\xa48f') -- Yi Syllables
+    || (c >= '\xa490' && c <= '\xa4cf') -- Yi Radicals
+    || (c >= '\xf900' && c <= '\xfaff') -- CJK Compatibility Ideographs
+    || (c >= '\xfe10' && c <= '\xfe1f') -- Vertical forms
+    || (c >= '\xfe30' && c <= '\xfe4f') -- CJK Compatibility Forms
+    || (c >= '\xFE50' && c <= '\xFE6F') -- Small Form Variants
+    || (c >= '\xFF00' && c <= '\xFFEE') -- Halfwidth and Fullwidth Forms
+    || (c >= '\x1B000' && c <= '\x1B0FF') -- Kana Supplement
+    || (c >= '\x1B100' && c <= '\x1B12F') -- Kana Extended-A
+    || (c >= '\x1B130' && c <= '\x1B16F') -- Small Kana Extension
+    || (c >= '\x20000' && c <= '\x2A6DF') -- CJK Unified Ideographs Extension B
+    || (c >= '\x2A700' && c <= '\x2B73F') -- CJK Unified Ideographs Extension C
+    || (c >= '\x2B740' && c <= '\x2B81F') -- CJK Unified Ideographs Extension D
+    || (c >= '\x2B820' && c <= '\x2CEAF') -- CJK Unified Ideographs Extension E
+    || (c >= '\x2CEB0' && c <= '\x2EBEF') -- CJK Unified Ideographs Extension F
+    || (c >= '\x2F800' && c <= '\x2FA1F') -- CJK Compatibility Ideographs Supp
+    || (c >= '\x30000' && c <= '\x3134F') -- CJK Unified Ideographs Exten
+  )
diff --git a/src/Text/Pandoc/Chunks.hs b/src/Text/Pandoc/Chunks.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Chunks.hs
@@ -0,0 +1,444 @@
+{-# LANGUAGE OverloadedStrings #-}
+{-# LANGUAGE MultiParamTypeClasses #-}
+{-# LANGUAGE FlexibleInstances #-}
+{-# LANGUAGE FlexibleContexts #-}
+{-# LANGUAGE GeneralizedNewtypeDeriving #-}
+{-# LANGUAGE DeriveDataTypeable #-}
+{-# LANGUAGE DeriveGeneric #-}
+{- |
+   Module      : Text.Pandoc.Chunks
+   Copyright   : Copyright (C) 2022-2024 John MacFarlane
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : John MacFarlane <jgm@berkeley.edu>
+   Stability   : alpha
+   Portability : portable
+
+Functions and types for splitting a Pandoc into subdocuments,
+e.g. for conversion into a set of HTML pages.
+-}
+module Text.Pandoc.Chunks
+  ( Chunk(..)
+  , ChunkedDoc(..)
+  , PathTemplate(..)
+  , splitIntoChunks
+  , toTOCTree
+  , tocToList
+  , SecInfo(..)
+  ) where
+
+import Text.Pandoc.Definition
+import Text.Pandoc.Shared (makeSections, stringify, inlineListToIdentifier,
+                           tshow, uniqueIdent)
+import Text.Pandoc.Walk (Walkable(..), query)
+import Data.Aeson (FromJSON, ToJSON)
+import Data.Text (Text)
+import Text.Printf (printf)
+import Data.Maybe (fromMaybe, isNothing)
+import qualified Data.Map as M
+import qualified Data.Text as T
+import Data.String (IsString)
+import GHC.Generics (Generic)
+import Text.HTML.TagSoup (Tag (TagOpen), fromAttrib, parseTags)
+import Data.Tree (Tree(..))
+import Data.Data (Data)
+import Data.Typeable (Typeable)
+import qualified Data.Set as Set
+import Control.Monad.State
+
+-- | Split 'Pandoc' into 'Chunk's, e.g. for conversion into
+-- a set of HTML pages or EPUB chapters.
+splitIntoChunks :: PathTemplate -- ^ Template for filepath
+                -> Bool -- ^ Number sections
+                -> Maybe Int -- ^ Base heading level
+                -> Int -- ^ Chunk level -- level of section to split at
+                -> Pandoc
+                -> ChunkedDoc
+splitIntoChunks pathTemplate numberSections mbBaseLevel
+                chunklev (Pandoc meta blocks) =
+   addNav .
+   fixInternalReferences .
+   walk rmNavAttrs $
+   ChunkedDoc{ chunkedMeta = meta
+             , chunkedChunks = chunks
+             , chunkedTOC = tocTree }
+ where
+  tocTree = fixTOCTreePaths chunks $ toTOCTree sections
+  chunks = makeChunks chunklev pathTemplate meta $ sections
+  sections = ensureIds $ makeSections numberSections mbBaseLevel blocks
+
+-- The TOC won't work if we don't have unique identifiers for all sections.
+ensureIds :: [Block] -> [Block]
+ensureIds bs = evalState (walkM go bs) mempty
+ where
+   go :: Block -> State (Set.Set Text) Block
+   go b@(Div (ident,"section":cls,kvs) bs'@(Header _ _ ils : _))
+     | T.null ident
+       = do ids <- get
+            let newid = uniqueIdent mempty ils ids
+            modify $ Set.insert newid
+            pure $ Div (newid,"section":cls,kvs) bs'
+     | otherwise
+       = do modify $ Set.insert ident
+            pure b
+   go b = pure b
+
+-- | Add chunkNext, chunkPrev, chunkUp
+addNav :: ChunkedDoc -> ChunkedDoc
+addNav chunkedDoc =
+  chunkedDoc{ chunkedChunks =
+     addNext . addPrev . addUp $ chunkedChunks chunkedDoc }
+
+addUp :: [Chunk] -> [Chunk]
+addUp (c : d : ds)
+  | chunkLevel c < chunkLevel d
+    = c : addUp (d{ chunkUp = Just c } : ds)
+  | chunkLevel c == chunkLevel d
+    = c : addUp (d{ chunkUp = chunkUp c} : ds)
+addUp (c:cs) = c : addUp cs
+addUp [] = []
+
+addNext :: [Chunk] -> [Chunk]
+addNext cs = zipWith go cs (map Just (drop 1 cs) ++ [Nothing])
+ where
+  go c nxt = c{ chunkNext = nxt }
+
+addPrev :: [Chunk] -> [Chunk]
+addPrev cs = zipWith go cs (Nothing : map Just cs)
+ where
+  go c prev = c{ chunkPrev = prev }
+
+-- | Fix internal references so they point to the path of the chunk.
+fixInternalReferences :: ChunkedDoc -> ChunkedDoc
+fixInternalReferences chunkedDoc = walk fixInternalRefs chunkedDoc
+ where
+  fixInternalRefs :: Inline -> Inline
+  fixInternalRefs il@(Link attr ils (src,tit))
+    = case T.uncons src of
+        Just ('#', ident) -> Link attr ils (src', tit)
+          where src' = case M.lookup ident refMap of
+                         Just chunk -> T.pack (chunkPath chunk) <> src
+                         Nothing -> src
+        _ -> il
+  fixInternalRefs il = il
+
+  refMap = foldr chunkToRefs mempty (chunkedChunks chunkedDoc)
+
+  chunkToRefs chunk m =
+    let idents = chunkId chunk : getIdents (chunkContents chunk)
+    in  foldr (\ident -> M.insert ident chunk) m idents
+
+  getIdents bs = query getBlockIdent bs ++ query getInlineIdent bs
+
+  getBlockIdent :: Block -> [Text]
+  getBlockIdent (Div (ident, _, _) _)
+    | not (T.null ident) = [ident]
+  getBlockIdent (Header _ (ident, _, _) _)
+    | not (T.null ident) = [ident]
+  getBlockIdent (Table (ident,_,_) _ _ _ _ _)
+    | not (T.null ident) = [ident]
+  getBlockIdent (RawBlock fmt raw)
+    | isHtmlFormat fmt
+    = foldr (\tag ->
+                case tag of
+                  TagOpen{} ->
+                    case fromAttrib "id" tag of
+                      "" -> id
+                      x  -> (x:)
+                  _ -> id)
+        [] (parseTags raw)
+  getBlockIdent _ = []
+
+  getInlineIdent :: Inline -> [Text]
+  getInlineIdent (Span (ident, _, _) _)
+    | not (T.null ident) = [ident]
+  getInlineIdent (Link (ident, _, _) _ _)
+    | not (T.null ident) = [ident]
+  getInlineIdent (Image (ident, _, _) _ _)
+    | not (T.null ident) = [ident]
+  getInlineIdent (RawInline fmt raw)
+    | isHtmlFormat fmt
+    = foldr (\tag ->
+                case tag of
+                  TagOpen{} ->
+                    case fromAttrib "id" tag of
+                      "" -> id
+                      x  -> (x:)
+                  _ -> id)
+        [] (parseTags raw)
+  getInlineIdent _ = []
+
+  isHtmlFormat :: Format -> Bool
+  isHtmlFormat (Format "html") = True
+  isHtmlFormat (Format "html4") = True
+  isHtmlFormat (Format "html5") = True
+  isHtmlFormat _ = False
+
+
+makeChunks :: Int -> PathTemplate -> Meta -> [Block] -> [Chunk]
+makeChunks chunklev pathTemplate meta = secsToChunks 1
+ where
+  isChunkHeader :: Block -> Bool
+  isChunkHeader (Div (_,"section":_,_) (Header n _ _:_)) = n <= chunklev
+  isChunkHeader _ = False
+
+  secsToChunks :: Int -> [Block] -> [Chunk]
+  secsToChunks chunknum bs =
+    case break isChunkHeader bs of
+      ([], []) -> []
+      ([], (d@(Div attr@(_,"section":_,_) (h@(Header lvl _ _) : bs')) : rest))
+        | chunklev == lvl ->
+          -- If the header is of the same level as chunks, create a chunk
+          toChunk chunknum d :
+            secsToChunks (chunknum + 1) rest
+        | chunklev > lvl ->
+          case break isChunkHeader bs' of
+            (xs, ys) -> toChunk chunknum (Div attr (h:xs)) :
+                          secsToChunks (chunknum + 1) (ys ++ rest)
+      (xs, ys) -> toChunk chunknum
+                     (Div ("",["preamble"],[]) xs) :
+                    secsToChunks (chunknum + 1) ys
+
+  toChunk :: Int -> Block -> Chunk
+  toChunk chunknum
+    (Div (divid,"section":classes,kvs) (h@(Header lvl _ ils) : bs)) =
+    Chunk
+      { chunkHeading = ils
+      , chunkId = divid
+      , chunkLevel = lvl
+      , chunkNumber = chunknum
+      , chunkSectionNumber = secnum
+      , chunkPath = chunkpath
+      , chunkUp = Nothing
+      , chunkNext = Nothing
+      , chunkPrev = Nothing
+      , chunkUnlisted = "unlisted" `elem` classes
+      , chunkContents =
+         [Div (divid,"section":classes,kvs') (h : bs)]
+      }
+     where kvs' = kvs ++ [("nav-path", T.pack chunkpath)]
+           secnum = lookup "number" kvs
+           chunkpath = resolvePathTemplate pathTemplate chunknum
+                        (stringify ils)
+                        divid
+                        (fromMaybe "" secnum)
+  toChunk chunknum (Div ("",["preamble"],[]) bs) =
+      Chunk
+      { chunkHeading = docTitle meta
+      , chunkId = chunkid
+      , chunkLevel = 0
+      , chunkNumber = chunknum
+      , chunkSectionNumber = Nothing
+      , chunkPath = chunkpath
+      , chunkUp = Nothing
+      , chunkPrev = Nothing
+      , chunkNext = Nothing
+      , chunkUnlisted = False
+      , chunkContents = bs
+      }
+    where
+      chunkpath = resolvePathTemplate pathTemplate chunknum
+                        (stringify (docTitle meta))
+                        chunkid
+                        "0"
+      chunkid = inlineListToIdentifier mempty (docTitle meta) <>
+                      "-" <> tshow chunknum
+  toChunk _ b = error $ "toChunk called on inappropriate block " <> show b
+  -- should not happen
+
+
+-- Remove some attributes we added just to construct chunkNext etc.
+rmNavAttrs :: Block -> Block
+rmNavAttrs (Div (ident,classes,kvs) bs) =
+  Div (ident,classes,filter (not . isNavAttr) kvs) bs
+ where
+  isNavAttr (k,_) = "nav-" `T.isPrefixOf` k
+rmNavAttrs b = b
+
+resolvePathTemplate :: PathTemplate
+                    -> Int -- ^ Chunk number
+                    -> Text -- ^ Stringified heading text
+                    -> Text -- ^ Section identifier
+                    -> Text -- ^ Section number
+                    -> FilePath
+resolvePathTemplate (PathTemplate templ) chunknum headingText ident secnum =
+  T.unpack .
+  T.filter (\c -> c /= '/' && c /= '\\') .
+  T.replace "%n" (T.pack $ printf "%03d" chunknum) .
+  T.replace "%s" secnum .
+  T.replace "%h" headingText .
+  T.replace "%i" ident $
+  templ
+
+-- | A 'PathTemplate' is a FilePath in which certain codes
+-- will be substituted with information from a 'Chunk'.
+-- @%n@ will be replaced with the chunk number
+-- (padded with leading 0s to 3 digits),
+-- @%s@ with the section number of the heading,
+-- @%h@ with the (stringified) heading text,
+-- @%i@ with the section identifier.
+-- For example, @"section-%s-%i.html"@ might be resolved to
+-- @"section-1.2-introduction.html"@.
+newtype PathTemplate =
+  PathTemplate { unPathTemplate :: Text }
+  deriving (Show, IsString, Data, Typeable, Generic, ToJSON, FromJSON)
+
+-- | A part of a document (typically a chapter or section, or
+-- the part of a section before its subsections).
+data Chunk =
+  Chunk
+  { chunkHeading :: [Inline]
+  , chunkId :: Text
+  , chunkLevel :: Int
+  , chunkNumber :: Int
+  , chunkSectionNumber :: Maybe Text
+  , chunkPath :: FilePath
+  , chunkUp :: Maybe Chunk
+  , chunkPrev :: Maybe Chunk
+  , chunkNext :: Maybe Chunk
+  , chunkUnlisted :: Bool
+  , chunkContents :: [Block]
+  }
+  deriving (Show, Eq, Generic)
+
+instance Walkable Inline Chunk where
+  query f chunk = query f (chunkContents chunk)
+  walk f chunk = chunk{ chunkContents = walk f (chunkContents chunk) }
+  walkM f chunk = do
+    contents <- walkM f (chunkContents chunk)
+    return chunk{ chunkContents = contents }
+
+instance Walkable Block Chunk where
+  query f chunk = query f (chunkContents chunk)
+  walk f chunk = chunk{ chunkContents = walk f (chunkContents chunk) }
+  walkM f chunk = do
+    contents <- walkM f (chunkContents chunk)
+    return chunk{ chunkContents = contents }
+
+-- | A 'Pandoc' broken into 'Chunk's for writing to separate files.
+data ChunkedDoc =
+  ChunkedDoc
+  { chunkedMeta :: Meta
+  , chunkedTOC :: Tree SecInfo
+  , chunkedChunks :: [Chunk]
+  } deriving (Show, Eq, Generic)
+
+instance Walkable Inline ChunkedDoc where
+  query f doc = query f (chunkedChunks doc) <> query f (chunkedMeta doc)
+  walk f doc = doc{ chunkedMeta = walk f (chunkedMeta doc)
+                  , chunkedChunks = walk f (chunkedChunks doc)
+                  }
+  walkM f doc = do
+    meta' <- walkM f (chunkedMeta doc)
+    chunks' <- walkM f (chunkedChunks doc)
+    return $ doc{ chunkedMeta = meta'
+                , chunkedChunks = chunks' }
+
+instance Walkable Block ChunkedDoc where
+  query f doc = query f (chunkedChunks doc) <> query f (chunkedMeta doc)
+  walk f doc = doc{ chunkedMeta = walk f (chunkedMeta doc)
+                  , chunkedChunks = walk f (chunkedChunks doc)
+                  }
+  walkM f doc = do
+    meta' <- walkM f (chunkedMeta doc)
+    chunks' <- walkM f (chunkedChunks doc)
+    return $ doc{ chunkedMeta = meta'
+                , chunkedChunks = chunks' }
+
+-- | Data for a section in a hierarchical document.
+data SecInfo =
+  SecInfo
+  { secTitle :: [Inline]
+  , secNumber :: Maybe Text
+  , secId :: Text
+  , secPath :: Text -- including fragment, e.g. chunk001.html#section-one
+  , secLevel :: Int
+  } deriving (Show, Eq, Generic)
+
+instance Walkable Inline SecInfo where
+  query f sec = query f (secTitle sec)
+  walk f sec = sec{ secTitle = walk f (secTitle sec) }
+  walkM f sec = do
+    st <- walkM f (secTitle sec)
+    return sec{ secTitle = st }
+
+-- | Create tree of sections with titles, links, and numbers,
+-- in a form that can be turned into a table of contents.
+-- Presupposes that the '[Block]' is the output of 'makeSections'.
+toTOCTree :: [Block] -> Tree SecInfo
+toTOCTree =
+  Node SecInfo{ secTitle = []
+              , secNumber = Nothing
+              , secId = ""
+              , secPath = ""
+              , secLevel = 0 } . foldr go []
+ where
+  go :: Block -> [Tree SecInfo] -> [Tree SecInfo]
+  go (Div (ident,_,_) (Header lev (_,classes,kvs) ils : subsecs))
+    | not (isNothing (lookup "number" kvs) && "unlisted" `elem` classes)
+    = ((Node SecInfo{ secTitle = ils
+                    , secNumber = lookup "number" kvs
+                    , secId = ident
+                    , secPath = ""
+                    , secLevel = lev } (foldr go [] subsecs)) :)
+  go (Div _ [d@Div{}]) = go d -- #8402
+  go _ = id
+
+-- | Adjusts paths in the TOC tree generated by 'toTOCTree'
+-- to reflect division into Chunks.
+fixTOCTreePaths :: [Chunk] -> Tree SecInfo -> Tree SecInfo
+fixTOCTreePaths chunks = go ""
+ where
+  idMap = foldr (\chunk m ->
+                   let ids = filter (not . T.null)
+                               (chunkId chunk :
+                                  query getIds (chunkContents chunk))
+                    in foldr (\i -> M.insert i (chunkPath chunk)) m ids)
+                mempty chunks
+  getIds :: Block -> [Text]
+  getIds (Div (i,"section":_,_) _) = [i]
+  getIds _ = []
+  go :: FilePath -> Tree SecInfo -> Tree SecInfo
+  go fp (Node secinfo subtrees) =
+    let newpath = M.lookup (secId secinfo) idMap
+        fp' = fromMaybe fp newpath
+        fragment = "#" <> secId secinfo
+     in Node secinfo{ secPath = T.pack fp' <> fragment }
+             (map (go fp') subtrees)
+
+-- | Creates a TOC link to the respective document section.
+tocEntryToLink :: Bool -> SecInfo -> [Inline]
+tocEntryToLink includeNumbers secinfo = headerLink
+ where
+  addNumber  = case secNumber secinfo of
+                 Just num | includeNumbers
+                        -> (Span ("",["toc-section-number"],[])
+                               [Str num] :) . (Space :)
+                 _ -> id
+  clean (Link _ xs _) = xs
+  clean (Note _) = []
+  clean x = [x]
+  anchor = if T.null (secPath secinfo)
+              then if T.null (secId secinfo)
+                      then ""
+                      else "#" <> secId secinfo
+              else secPath secinfo
+  headerText = addNumber $ walk (concatMap clean) (secTitle secinfo)
+  headerLink = if T.null anchor
+                  then headerText
+                  else [Link ((if T.null (secId secinfo)
+                                  then ""
+                                  else "toc-" <> secId secinfo), [], [])
+                         headerText (anchor, "")]
+
+-- | Generate a table of contents of the given depth.
+tocToList :: Bool -> Int -> Tree SecInfo -> Block
+tocToList includeNumbers tocDepth (Node _ subtrees) = BulletList (toItems subtrees)
+ where
+  toItems = map go . filter isBelowTocDepth
+  isBelowTocDepth (Node sec _) = secLevel sec <= tocDepth
+  go (Node secinfo xs) =
+    Plain (tocEntryToLink includeNumbers secinfo) :
+      case toItems xs of
+        [] -> []
+        ys -> [BulletList ys]
diff --git a/src/Text/Pandoc/Citeproc.hs b/src/Text/Pandoc/Citeproc.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Citeproc.hs
@@ -0,0 +1,667 @@
+{-# LANGUAGE ScopedTypeVariables #-}
+{-# LANGUAGE FlexibleContexts #-}
+{-# LANGUAGE StrictData #-}
+{-# LANGUAGE MultiParamTypeClasses #-}
+{-# LANGUAGE FlexibleInstances #-}
+{-# LANGUAGE OverloadedStrings #-}
+module Text.Pandoc.Citeproc
+  ( processCitations,
+    getReferences,
+  )
+where
+
+import Citeproc
+import Citeproc.Pandoc ()
+import Text.Pandoc.Citeproc.Locator (parseLocator, toLocatorMap,
+                                     LocatorInfo(..))
+import Text.Pandoc.Citeproc.CslJson (cslJsonToReferences)
+import Text.Pandoc.Citeproc.BibTeX (readBibtexString, Variant(..))
+import Text.Pandoc.MIME (MimeType)
+import Text.Pandoc.Readers.RIS (readRIS)
+import Text.Pandoc.Citeproc.MetaValue (metaValueToReference, metaValueToText)
+import Text.Pandoc.Readers.Markdown (yamlToRefs)
+import Text.Pandoc.Builder (Inlines, Many(..), deleteMeta, setMeta)
+import qualified Text.Pandoc.Builder as B
+import Text.Pandoc.Definition as Pandoc
+import Text.Pandoc.Class (PandocMonad(..), getResourcePath, getUserDataDir,
+                          fetchItem, report, setResourcePath, toTextM)
+import Text.Pandoc.Data (readDataFile)
+import Text.Pandoc.Error (PandocError(..))
+import Text.Pandoc.Extensions (pandocExtensions)
+import Text.Pandoc.Logging (LogMessage(..))
+import Text.Pandoc.Options (ReaderOptions(..))
+import Text.Pandoc.Shared (stringify, tshow, makeSections)
+import Data.Containers.ListUtils (nubOrd)
+import Text.Pandoc.Walk (query, walk, walkM)
+import Control.Applicative ((<|>))
+import Control.Monad.Except (catchError, throwError)
+import Control.Monad.State (State, evalState, get, put, runState)
+import Data.Aeson (eitherDecode)
+import Data.ByteString (ByteString)
+import qualified Data.ByteString.Lazy as L
+import Data.Char (isPunctuation, isUpper)
+import Data.Default (Default(def))
+import qualified Data.Foldable as Foldable
+import qualified Data.Map as M
+import Data.Maybe (mapMaybe, fromMaybe)
+import Data.Ord ()
+import qualified Data.Sequence as Seq
+import qualified Data.Set as Set
+import Data.Text (Text)
+import qualified Data.Text as T
+import System.FilePath (takeExtension)
+import Safe (lastMay, initSafe)
+
+processCitations  :: PandocMonad m => Pandoc -> m Pandoc
+processCitations (Pandoc meta bs) = do
+  style <- getStyle (Pandoc meta bs)
+  mblang <- getCiteprocLang meta
+  let locale = Citeproc.mergeLocales mblang style
+
+  let addQuoteSpan (Quoted _ xs) = Span ("",["csl-quoted"],[]) xs
+      addQuoteSpan x = x
+  refs <- map (walk addQuoteSpan) <$>
+          getReferences (Just locale) (Pandoc meta bs)
+
+  let otherIdsMap = foldr (\ref m ->
+                             case T.words . extractText <$>
+                                  M.lookup "other-ids"
+                                      (referenceVariables ref) of
+                                Nothing  -> m
+                                Just ids -> foldr
+                                  (\id' ->
+                                    M.insert id' (referenceId ref)) m ids)
+                          M.empty refs
+  let meta' = deleteMeta "nocite" meta
+  let citations = getCitations locale otherIdsMap $ Pandoc meta' bs
+
+
+  let linkCites = maybe False truish (lookupMeta "link-citations" meta) &&
+                  -- don't link citations if no bibliography to link to:
+             not (maybe False truish (lookupMeta "suppress-bibliography" meta))
+  let linkBib = maybe True truish $ lookupMeta "link-bibliography" meta
+  let opts = defaultCiteprocOptions{ linkCitations = linkCites
+                                   , linkBibliography = linkBib }
+  let result = Citeproc.citeproc opts style mblang refs citations
+  mapM_ (report . CiteprocWarning) (resultWarnings result)
+  let sopts = styleOptions style
+  let classes = "references" : -- TODO remove this or keep for compatibility?
+                "csl-bib-body" :
+                ["hanging-indent" | styleHangingIndent sopts]
+  let refkvs = (case styleEntrySpacing sopts of
+                   Just es -> (("entry-spacing",T.pack $ show es):)
+                   _ -> id) .
+               (case styleLineSpacing sopts of
+                   Just ls | ls > 1 -> (("line-spacing",T.pack $ show ls):)
+                   _ -> id) $ []
+  let bibs = mconcat $ map (\(ident, out) ->
+                     B.divWith ("ref-" <> ident,["csl-entry"],[]) . B.para .
+                         insertSpace $ out)
+                      (resultBibliography result)
+  let moveNotes = maybe (styleIsNoteStyle sopts) truish
+                   (lookupMeta "notes-after-punctuation" meta)
+  let cits = resultCitations result
+
+  let metanocites = lookupMeta "nocite" meta
+  let Pandoc meta'' bs' =
+         maybe id (setMeta "nocite") metanocites .
+         walk (mvPunct moveNotes locale) .
+         (if styleIsNoteStyle sopts
+             then walk addNote .  walk deNote
+             else id) .
+         evalState (walkM insertResolvedCitations $ Pandoc meta' bs)
+         $ cits
+  return $ walk removeQuoteSpan
+         $ insertRefs refkvs classes (B.toList bibs)
+         $ Pandoc meta'' bs'
+
+removeQuoteSpan :: Inline -> Inline
+removeQuoteSpan (Span ("",["csl-quoted"],[]) xs) = Span nullAttr xs
+removeQuoteSpan x = x
+
+-- | Retrieve the CSL style specified by the csl or citation-style
+-- metadata field in a pandoc document, or the default CSL style
+-- if none is specified.  Retrieve the parent style
+-- if the style is a dependent style.  Add abbreviations defined
+-- in an abbreviation file if one has been specified.
+getStyle :: PandocMonad m => Pandoc -> m (Style Inlines)
+getStyle (Pandoc meta _) = do
+  let cslfile = (lookupMeta "csl" meta <|> lookupMeta "citation-style" meta)
+                >>= metaValueToText
+
+  let getFile defaultExtension fp = do
+        oldRp <- getResourcePath
+        mbUdd <- getUserDataDir
+        setResourcePath $ oldRp ++ maybe []
+                                   (\u -> [u <> "/csl",
+                                           u <> "/csl/dependent"]) mbUdd
+        let fp' = if T.any (=='.') fp || "data:" `T.isPrefixOf` fp
+                     then fp
+                     else fp <> defaultExtension
+        (result, _) <- fetchItem fp'
+        setResourcePath oldRp
+        return result
+
+  let getCslDefault = readDataFile "default.csl"
+
+  cslContents <- maybe getCslDefault (getFile ".csl") cslfile >>=
+                   toTextM (maybe mempty T.unpack cslfile)
+
+  let abbrevFile = lookupMeta "citation-abbreviations" meta >>= metaValueToText
+
+  mbAbbrevs <- case abbrevFile of
+                 Nothing -> return Nothing
+                 Just fp -> do
+                   rawAbbr <- getFile ".json" fp
+                   case eitherDecode (L.fromStrict rawAbbr) of
+                     Left err -> throwError $ PandocCiteprocError $
+                                 CiteprocParseError $
+                                 "Could not parse abbreviations file " <> fp
+                                 <> "\n" <> T.pack err
+                     Right abbr -> return $ Just abbr
+
+  let getParentStyle url = do
+        -- first, try to retrieve the style locally, then use HTTP.
+        let basename = T.takeWhileEnd (/='/') url
+        catchError (getFile ".csl" basename) (\_ -> fst <$> fetchItem url)
+          >>= toTextM (T.unpack url)
+
+  styleRes <- Citeproc.parseStyle getParentStyle cslContents
+  case styleRes of
+     Left err    -> throwError $ PandocAppError $ prettyCiteprocError err
+     Right style -> return style{ styleAbbreviations = mbAbbrevs }
+
+
+-- Retrieve citeproc lang based on metadata.
+getCiteprocLang :: PandocMonad m => Meta -> m (Maybe Lang)
+getCiteprocLang meta = maybe (return Nothing) bcp47LangToIETF
+  ((lookupMeta "lang" meta <|> lookupMeta "locale" meta) >>= metaValueToText)
+
+-- | Get references defined inline in the metadata and via an external
+-- bibliography.  Only references that are actually cited in the document
+-- (either with a genuine citation or with `nocite`) are returned.
+-- URL variables are converted to links.
+getReferences :: PandocMonad m
+              => Maybe Locale -> Pandoc -> m [Reference Inlines]
+getReferences mblocale (Pandoc meta bs) = do
+  locale <- case mblocale of
+                Just l  -> return l
+                Nothing -> do
+                  mblang <- getCiteprocLang meta
+                  case mblang of
+                    Just lang -> return $ either mempty id $ getLocale lang
+                    Nothing   -> return mempty
+
+  let getCiteId (Cite cs _) = Set.fromList $ map B.citationId cs
+      getCiteId _ = mempty
+  let metanocites = lookupMeta "nocite" meta
+  let nocites = maybe mempty (query getCiteId) metanocites
+  let citeIds = query getCiteId (Pandoc meta bs)
+  let idpred = if "*" `Set.member` nocites
+                  then const True
+                  else (`Set.member` citeIds)
+  let inlineRefs = case lookupMeta "references" meta of
+                    Just (MetaList rs) ->
+                      filter (idpred . unItemId . referenceId)
+                         $  mapMaybe metaValueToReference rs
+                    _                  -> []
+  externalRefs <- case lookupMeta "bibliography" meta of
+                    Just (MetaList xs) ->
+                      mconcat <$>
+                        mapM (getRefsFromBib locale idpred)
+                          (mapMaybe metaValueToText xs)
+                    Just x ->
+                      case metaValueToText x of
+                        Just fp -> getRefsFromBib locale idpred fp
+                        Nothing -> return []
+                    Nothing -> return []
+  return $ map legacyDateRanges (externalRefs ++ inlineRefs)
+            -- note that inlineRefs can override externalRefs
+
+
+
+-- If we have a span.csl-left-margin followed by span.csl-right-inline,
+-- we insert a space. This ensures that they will be separated by a space,
+-- even in formats that don't have special handling for the display spans.
+insertSpace :: Inlines -> Inlines
+insertSpace ils =
+  case Seq.viewl (unMany ils) of
+    (Span ("",["csl-left-margin"],[]) xs) Seq.:< rest ->
+      case Seq.lookup 0 rest of
+        Just (Span ("",["csl-right-inline"],[]) _) ->
+          Many $
+            Span ("",["csl-left-margin"],[]) (xs ++ case lastMay xs of
+                                                      Just Space -> []
+                                                      _          -> [Space])
+            Seq.<| rest
+        _ -> ils
+    _ -> ils
+
+getRefsFromBib :: PandocMonad m
+               => Locale -> (Text -> Bool) -> Text -> m [Reference Inlines]
+getRefsFromBib locale idpred fp = do
+  (raw, mt) <- fetchItem fp
+  case getBibliographyFormat (T.unpack fp) mt of
+    Just f -> getRefs locale f idpred (Just fp) raw
+    Nothing -> throwError $ PandocAppError $
+                 "Could not determine bibliography format for " <> fp
+
+getRefs :: PandocMonad m
+        => Locale
+        -> BibFormat
+        -> (Text -> Bool)
+        -> Maybe Text
+        -> ByteString
+        -> m [Reference Inlines]
+getRefs locale format idpred mbfp raw = do
+  let err' = throwError .
+             PandocBibliographyError (fromMaybe mempty mbfp)
+  let fp = maybe mempty T.unpack mbfp
+  case format of
+    Format_bibtex ->
+      toTextM fp raw >>=
+        either (err' . tshow) return . readBibtexString Bibtex locale idpred
+    Format_biblatex ->
+      toTextM fp raw >>=
+      either (err' . tshow) return . readBibtexString Biblatex locale idpred
+    Format_json ->
+      either (err' . T.pack)
+             (return . filter (idpred . unItemId . referenceId)) .
+        cslJsonToReferences $ raw
+    Format_yaml -> do
+      rs <- yamlToRefs idpred
+              def{ readerExtensions = pandocExtensions }
+              (T.unpack <$> mbfp)
+              raw
+      return $ mapMaybe metaValueToReference rs
+    Format_ris -> do
+      Pandoc meta _ <- toTextM fp raw >>= readRIS def
+      case lookupMeta "references" meta of
+        Just (MetaList rs) -> return $ mapMaybe metaValueToReference rs
+        _ -> return []
+
+-- assumes we walk in same order as query
+insertResolvedCitations :: Inline -> State [Inlines] Inline
+insertResolvedCitations (Cite cs ils) = do
+  resolved <- get
+  case resolved of
+    [] -> return (Cite cs ils)
+    (x:xs) -> do
+      put xs
+      return $ Cite cs (B.toList x)
+insertResolvedCitations x = return x
+
+getCitations :: Locale
+             -> M.Map Text ItemId
+             -> Pandoc
+             -> [Citeproc.Citation Inlines]
+getCitations locale otherIdsMap (Pandoc meta blocks) =
+  Foldable.toList (query getCitation meta <>
+                   foldMap handleBlock (makeSections False Nothing blocks))
+ where
+  handleBlock :: Block -> Seq.Seq (Citeproc.Citation Inlines)
+  handleBlock b@(Div (_,cls,_) _)
+    | "section" `elem` cls
+    , "reset-citation-positions" `elem` cls =
+      case Seq.viewl (query getCitation b) of
+        x Seq.:< xs -> addResetTo x Seq.<| xs
+        Seq.EmptyL -> mempty
+  handleBlock b = query getCitation b
+  addResetTo citation = citation{ Citeproc.citationResetPosition = True }
+  getCitation (Cite cs _fallback) = Seq.singleton $
+    Citeproc.Citation { Citeproc.citationId = Nothing
+                      , Citeproc.citationResetPosition = False
+                      , Citeproc.citationPrefix = Nothing
+                      , Citeproc.citationSuffix = Nothing
+                      , Citeproc.citationNoteNumber =
+                          case cs of
+                            []    -> Nothing
+                            (Pandoc.Citation{ Pandoc.citationNoteNum = n }:
+                               _) | n > 0     -> Just n
+                                  | otherwise -> Nothing
+                      , Citeproc.citationItems =
+                           fromPandocCitations locale otherIdsMap cs
+                      }
+  getCitation _ = mempty
+
+fromPandocCitations :: Locale
+                    -> M.Map Text ItemId
+                    -> [Pandoc.Citation]
+                    -> [CitationItem Inlines]
+fromPandocCitations locale otherIdsMap = concatMap go
+ where
+  locmap = toLocatorMap locale
+  go c =
+    let (mblocinfo, suffix) = parseLocator locmap (Pandoc.citationSuffix c)
+        cit = CitationItem
+               { citationItemId = fromMaybe
+                   (ItemId $ Pandoc.citationId c)
+                   (M.lookup (Pandoc.citationId c) otherIdsMap)
+               , citationItemLabel = locatorLabel <$> mblocinfo
+               , citationItemLocator = locatorLoc <$> mblocinfo
+               , citationItemType = NormalCite
+               , citationItemPrefix = case Pandoc.citationPrefix c of
+                                        [] -> Nothing
+                                        ils -> Just $ B.fromList ils <>
+                                                      B.space
+               , citationItemSuffix = case suffix of
+                                        [] -> Nothing
+                                        ils -> Just $ B.fromList ils
+               , citationItemData = Nothing }
+     in if Pandoc.citationId c == "*"
+           then []
+           else
+             case citationMode c of
+                  AuthorInText   -> [ cit{ citationItemType = AuthorOnly
+                                         , citationItemSuffix = Nothing }
+                                    , cit{ citationItemType =
+                                              Citeproc.SuppressAuthor
+                                         , citationItemPrefix = Nothing } ]
+                  NormalCitation -> [ cit ]
+                  Pandoc.SuppressAuthor
+                                 -> [ cit{ citationItemType =
+                                              Citeproc.SuppressAuthor } ]
+
+
+
+data BibFormat =
+    Format_biblatex
+  | Format_bibtex
+  | Format_json
+  | Format_yaml
+  | Format_ris
+  deriving (Show, Eq, Ord)
+
+getBibliographyFormat :: FilePath -> Maybe MimeType -> Maybe BibFormat
+getBibliographyFormat fp mbmime = do
+  let ext = takeExtension fp
+  case ext of
+    ".biblatex" -> pure Format_biblatex
+    ".bibtex"   -> pure Format_bibtex
+    ".bib"      -> pure Format_biblatex
+    ".json"     -> pure Format_json
+    ".yaml"     -> pure Format_yaml
+    ".yml"      -> pure Format_yaml
+    ".ris"      -> pure Format_ris
+    _ -> do
+      mime <- mbmime
+      case T.takeWhile (/= ';') mime of
+            "application/x-bibtex" -> pure Format_biblatex
+            "application/x-reseach-info-systems" -> pure Format_ris
+            "application/vnd.citationstyles.csl+json" -> pure Format_json
+            "application/json" -> pure Format_json
+            "application/x-yaml" -> pure Format_yaml
+            "text/x-yaml" -> pure Format_yaml
+            "text/yaml" -> pure Format_yaml
+            _ -> Nothing
+
+isNote :: Inline -> Bool
+isNote (Note _) = True
+-- the following allows citation styles that are "in-text" but use superscript
+-- references to be treated as if they are "notes" for the purposes of moving
+-- the citations after trailing punctuation (see <https://github.com/jgm/pandoc-citeproc/issues/382>):
+isNote (Superscript _) = True
+isNote _ = False
+
+isSpacy :: Inline -> Bool
+isSpacy Space     = True
+isSpacy SoftBreak = True
+isSpacy _         = False
+
+movePunctInsideQuotes :: Locale -> [Inline] -> [Inline]
+movePunctInsideQuotes locale
+  | localePunctuationInQuote locale == Just True
+    = B.toList . movePunctuationInsideQuotes . B.fromList
+  | otherwise
+    = id
+
+mvPunct :: Bool -> Locale -> [Inline] -> [Inline]
+mvPunct moveNotes locale (x : xs)
+  | isSpacy x = x : mvPunct moveNotes locale xs
+-- 'x [^1],' -> 'x,[^1]'
+mvPunct moveNotes locale (q : s : x@(Cite _ [il]) : ys)
+  | isSpacy s
+  , isNote il
+  = let spunct = T.takeWhile isPunct $ stringify ys
+    in  if moveNotes
+           then if T.null spunct
+                   then q : x : mvPunct moveNotes locale ys
+                   else movePunctInsideQuotes locale
+                        [q , Str spunct , x] ++ mvPunct moveNotes locale
+                        (B.toList
+                          (dropTextWhile isPunct (B.fromList ys)))
+           else q : x : mvPunct moveNotes locale ys
+-- 'x[^1],' -> 'x,[^1]'
+mvPunct moveNotes locale (Cite cs ils@(_:_) : ys)
+   | isNote (last ils)
+   , startWithPunct ys
+   , moveNotes
+   = let s = stringify ys
+         spunct = T.takeWhile isPunct s
+     in  Cite cs (movePunctInsideQuotes locale $
+                    init ils
+                    ++ [Str spunct | not (endWithPunct False (init ils))]
+                    ++ [last ils]) :
+         mvPunct moveNotes locale
+           (B.toList (dropTextWhile isPunct (B.fromList ys)))
+mvPunct moveNotes locale (s : x@(Cite _ [il]) : ys)
+  | isSpacy s
+  , isNote il
+  = x : mvPunct moveNotes locale ys
+mvPunct moveNotes locale (s : x@(Cite _ (Superscript _ : _)) : ys)
+  | isSpacy s = x : mvPunct moveNotes locale ys
+mvPunct moveNotes locale (Cite cs ils : Str "." : ys)
+  | "." `T.isSuffixOf` (stringify ils)
+  = Cite cs ils : mvPunct moveNotes locale ys
+mvPunct moveNotes locale (x:xs) = x : mvPunct moveNotes locale xs
+mvPunct _ _ [] = []
+
+-- We don't treat an em-dash or en-dash as punctuation here, because we don't
+-- want notes and quotes to move around them.
+isPunct :: Char -> Bool
+isPunct c = isPunctuation c && c /= '\x2014' && c /= '\x2013'
+
+endWithPunct :: Bool -> [Inline] -> Bool
+endWithPunct _ [] = False
+endWithPunct onlyFinal xs@(_:_) =
+  case reverse (T.unpack $ stringify xs) of
+       []                       -> True
+       -- covers .), .", etc.:
+       (d:c:_) | isPunct d
+                 && not onlyFinal
+                 && isEndPunct c -> True
+       (c:_) | isEndPunct c      -> True
+             | otherwise         -> False
+  where isEndPunct c = c `elem` (".,;:!?" :: String)
+
+
+
+startWithPunct :: [Inline] -> Bool
+startWithPunct ils =
+  case T.uncons (stringify ils) of
+    Just (c,_) -> c `elem` (".,;:!?" :: [Char])
+    Nothing -> False
+
+truish :: MetaValue -> Bool
+truish (MetaBool t) = t
+truish (MetaString s) = isYesValue (T.toLower s)
+truish (MetaInlines ils) = isYesValue (T.toLower (stringify ils))
+truish (MetaBlocks [Plain ils]) = isYesValue (T.toLower (stringify ils))
+truish _ = False
+
+isYesValue :: Text -> Bool
+isYesValue "t" = True
+isYesValue "true" = True
+isYesValue "yes" = True
+isYesValue _ = False
+
+-- if document contains a Div with id="refs", insert
+-- references as its contents.  Otherwise, insert references
+-- at the end of the document in a Div with id="refs" or
+-- id=".*__refs" (where .* stands for any string -- this is
+-- because --file-scope will add such a prefix based on the filename,
+-- see #11072.)
+insertRefs :: [(Text,Text)] -> [Text] -> [Block] -> Pandoc -> Pandoc
+insertRefs _ _ [] d = d
+insertRefs refkvs refclasses refs (Pandoc meta bs) =
+  case lookupMeta "suppress-bibliography" meta of
+    Just x | truish x -> Pandoc meta bs
+    _ -> case runState (walkM go (Pandoc meta bs)) False of
+               (d', True) -> d'
+               (Pandoc meta' bs', False)
+                 -> Pandoc meta' $
+                    case refTitle meta of
+                      Nothing ->
+                        case reverse bs' of
+                          Header lev (id',classes,kvs) ys : xs ->
+                            reverse xs ++
+                            [Header lev (id',addUnNumbered classes,kvs) ys,
+                             Div ("refs",refclasses,refkvs) refs]
+                          _ -> bs' ++ [refDiv]
+                      Just ils -> bs' ++
+                        [Header 1 ("bibliography", ["unnumbered"], []) ils,
+                         refDiv]
+  where
+   refDiv = Div ("refs", refclasses, refkvs) refs
+   addUnNumbered cs = "unnumbered" : [c | c <- cs, c /= "unnumbered"]
+   go :: Block -> State Bool Block
+   go (Div (ident,cs,kvs) xs)
+     | ident == "refs" || "__refs" `T.isSuffixOf` ident = do
+       put True
+       -- refHeader isn't used if you have an explicit references div
+       let cs' = nubOrd $ cs ++ refclasses
+       let kvs' = nubOrd $ kvs ++ refkvs
+       return $ Div (ident,cs',kvs') (xs ++ refs)
+   go x = return x
+
+refTitle :: Meta -> Maybe [Inline]
+refTitle meta =
+  case lookupMeta "reference-section-title" meta of
+    Just (MetaString s)           -> Just [Str s]
+    Just (MetaInlines ils)        -> Just ils
+    Just (MetaBlocks [Plain ils]) -> Just ils
+    Just (MetaBlocks [Para ils])  -> Just ils
+    _                             -> Nothing
+
+legacyDateRanges :: Reference Inlines -> Reference Inlines
+legacyDateRanges ref =
+  ref{ referenceVariables = M.map go $ referenceVariables ref }
+ where
+  go (DateVal d)
+    | null (dateParts d)
+    , Just lit <- dateLiteral d
+    = case T.splitOn "_" lit of
+        [x,y] -> case Citeproc.rawDateEDTF (x <> "/" <> y) of
+                   Just d' -> DateVal d'
+                   Nothing -> DateVal d
+        _ -> DateVal d
+  go x = x
+
+extractText :: Val Inlines -> Text
+extractText (TextVal x)  = x
+extractText (FancyVal x) = toText x
+extractText (NumVal n)   = T.pack (show n)
+extractText _            = mempty
+
+-- Here we take the Spans with class csl-note that are left
+-- after deNote has removed nested ones, and convert them
+-- into real notes.
+addNote :: Inline -> Inline
+addNote (Span ("",["csl-note"],[]) ils) =
+  Note [Para $
+         B.toList . addTextCase Nothing CapitalizeFirst . B.fromList $ ils]
+addNote x = x
+
+-- Here we handle citation notes that occur inside footnotes
+-- or other citation notes, in a note style.  We don't want
+-- notes inside notes, so we convert these to parenthesized
+-- or comma-separated citations.
+deNote :: Inline -> Inline
+deNote (Note bs) =
+  case bs of
+    [Para (cit@(Cite (c:_) _) : ils)]
+       | citationMode c /= AuthorInText ->
+         -- if citation is first in note, no need to parenthesize.
+         Note [Para (walk removeNotes $ cit : walk addParens ils)]
+    _ -> Note (walk removeNotes . walk addParens $ bs)
+
+ where
+  addParens [] = []
+  addParens (Cite (c:cs) ils : zs)
+    | citationMode c == AuthorInText
+      = Cite (c:cs) (addCommas (needsPeriod zs) ils) :
+        addParens zs
+    | otherwise
+      = Cite (c:cs) (dropWhile (== Space) (concatMap noteInParens ils))
+         : addParens zs
+  addParens (x:xs) = x : addParens xs
+
+  removeNotes (Span ("",["csl-note"],[]) ils) = Span ("",[],[]) ils
+  removeNotes x = x
+
+  needsPeriod [] = True
+  needsPeriod (Str t:_) = case T.uncons t of
+                            Nothing    -> False
+                            Just (c,_) -> isUpper c
+  needsPeriod (Space:zs) = needsPeriod zs
+  needsPeriod _ = False
+
+  noteInParens (Span ("",["csl-note"],[]) ils)
+       = Space : Str "(" :
+         removeFinalPeriod ils ++ [Str ")"]
+  noteInParens x = [x]
+
+  -- We want to add a comma before a CSL note citation, but not
+  -- before the author name, and not before the first citation
+  -- if it doesn't begin with an author name.
+  addCommas = addCommas' True -- boolean == "at beginning"
+
+  addCommas' _ _ [] = []
+  addCommas' atBeginning needsPer
+    (Span ("",["csl-note"],[]) ils : rest)
+      | not (null ils)
+       = (if atBeginning then id else ([Str "," , Space] ++)) $
+         (if needsPer then ils else removeFinalPeriod ils) ++
+         addCommas' False needsPer rest
+  addCommas' _ needsPer (il : rest) = il : addCommas' False needsPer rest
+
+deNote x = x
+
+-- Note: we can't use dropTextWhileEnd indiscriminately,
+-- because this would remove the final period on abbreviations like Ibid.
+-- But it turns out that when the note citation ends with Ibid.
+-- (or Ed. etc.), the last inline will be Str "" as a result of
+-- the punctuation-fixing mechanism that removes the double '.'.
+removeFinalPeriod :: [Inline] -> [Inline]
+removeFinalPeriod ils =
+  case lastMay ils of
+    Just (Span attr ils')
+      -> initSafe ils ++ [Span attr (removeFinalPeriod ils')]
+    Just (Emph ils')
+      -> initSafe ils ++ [Emph (removeFinalPeriod ils')]
+    Just (Strong ils')
+      -> initSafe ils ++ [Strong (removeFinalPeriod ils')]
+    Just (SmallCaps ils')
+      -> initSafe ils ++ [SmallCaps (removeFinalPeriod ils')]
+    Just (Str t)
+      | T.takeEnd 1 t == "." -> initSafe ils ++ [Str (T.dropEnd 1 t)]
+      | isRightQuote (T.takeEnd 1 t)
+        -> removeFinalPeriod
+             (initSafe ils ++ [Str tInit | not (T.null tInit)]) ++ [Str tEnd]
+             where
+               tEnd  = T.takeEnd 1 t
+               tInit = T.dropEnd 1 t
+    _ -> ils
+ where
+  isRightQuote "\8221" = True
+  isRightQuote "\8217" = True
+  isRightQuote "\187"  = True
+  isRightQuote _       = False
+
+bcp47LangToIETF :: PandocMonad m => Text -> m (Maybe Lang)
+bcp47LangToIETF bcplang =
+  case parseLang bcplang of
+    Left _ -> do
+      report $ InvalidLang bcplang
+      return Nothing
+    Right lang -> return $ Just lang
diff --git a/src/Text/Pandoc/Citeproc/BibTeX.hs b/src/Text/Pandoc/Citeproc/BibTeX.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Citeproc/BibTeX.hs
@@ -0,0 +1,1374 @@
+{-# LANGUAGE ViewPatterns      #-}
+{-# LANGUAGE LambdaCase #-}
+{-# LANGUAGE OverloadedStrings #-}
+{-# LANGUAGE ScopedTypeVariables #-}
+{-# LANGUAGE FlexibleContexts #-}
+{-# OPTIONS_GHC -fno-warn-unused-do-bind #-}
+-----------------------------------------------------------------------------
+-- |
+-- Module      :  Text.CSL.Input.Bibtex
+-- Copyright   :  (c) John MacFarlane
+-- License     :  BSD-style (see LICENSE)
+--
+-- Maintainer  :  John MacFarlane <fiddlosopher@gmail.com>
+-- Stability   :  unstable
+-- Portability :  portable
+--
+-----------------------------------------------------------------------------
+
+module Text.Pandoc.Citeproc.BibTeX
+    ( Variant(..)
+    , readBibtexString
+    , writeBibtexString
+    )
+    where
+
+import Text.Pandoc.Definition
+import Text.Pandoc.Builder as B
+import Text.Pandoc.Readers.LaTeX (readLaTeX)
+import Text.Pandoc.Extensions (Extension(..), extensionsFromList)
+import Text.Pandoc.Options (ReaderOptions(..), WriterOptions)
+import Text.Pandoc.Error (PandocError)
+import Text.Pandoc.Shared (stringify)
+import Text.Pandoc.Writers.LaTeX (writeLaTeX)
+import Text.Pandoc.Class (runPure)
+import qualified Text.Pandoc.Walk       as Walk
+import Citeproc.Types
+import Citeproc.Pandoc ()
+import Data.List.Split (splitOn)
+import Text.Pandoc.Citeproc.Util (toIETF, splitStrWhen)
+import Text.Pandoc.Citeproc.Data (biblatexStringMap)
+import Text.Pandoc.Citeproc.Name (toName, NameOpts(..), emptyName)
+import Data.Default
+import           Data.Text              (Text)
+import qualified Data.Text              as T
+import qualified Data.Map               as Map
+import           Data.Maybe
+import           Text.Pandoc.Parsing hiding ((<|>), many)
+import           Control.Applicative
+import           Control.Monad ( guard, MonadPlus(..), void )
+import Control.Monad.RWS ( asks, RWST, gets, modify, evalRWST )
+import qualified Data.Sequence          as Seq
+import           Data.Char              (isAlphaNum, isDigit, isLetter,
+                                         isUpper, toLower, toUpper,
+                                         isLower, isPunctuation, isSpace)
+import           Data.List              (intercalate, intersperse)
+import qualified Data.List as L
+import           Safe                   (readMay)
+import           Text.Printf            (printf)
+import           Text.DocLayout         (literal, hsep, nest, hang, Doc(..),
+                                         braces, ($$), cr)
+
+data Variant = Bibtex | Biblatex
+  deriving (Show, Eq, Ord)
+
+-- | Parse BibTeX or BibLaTeX into a list of 'Reference's.
+readBibtexString :: ToSources a
+                 => Variant           -- ^ bibtex or biblatex
+                 -> Locale            -- ^ Locale
+                 -> (Text -> Bool)    -- ^ Filter on citation ids
+                 -> a                 -- ^ bibtex/biblatex text
+                 -> Either ParseError [Reference Inlines]
+readBibtexString variant locale idpred contents = do
+  case runParser (((resolveCrossRefs variant <$> bibEntries) <* eof) >>=
+                   mapM (itemToReference locale variant) .
+                      filter (\item -> idpred (identifier item) &&
+                                        entryType item /= "xdata"))
+           (fromMaybe defaultLang $ localeLanguage locale, Map.empty)
+           (initialSourceName sources) sources of
+          Left err -> Left err
+          Right xs -> return xs
+ where
+  sources = toSources contents
+
+-- | Write BibTeX or BibLaTeX given given a 'Reference'.
+writeBibtexString :: WriterOptions       -- ^ options (for writing LaTex)
+                  -> Variant             -- ^ bibtex or biblatex
+                  -> Maybe Lang          -- ^ Language
+                  -> Reference Inlines   -- ^ Reference to write
+                  -> Doc Text
+writeBibtexString opts variant mblang ref =
+  "@" <> bibtexType <> "{" <> literal (unItemId (referenceId ref)) <> ","
+  $$ nest 2 (renderFields fs)
+  $$ "}" <> cr
+
+ where
+  bibtexType =
+    case referenceType ref of
+      "article-magazine"  -> "article"
+      "article-newspaper" -> "article"
+      "article-journal"   -> "article"
+      "book"              -> "book"
+      "pamphlet"          -> "booklet"
+      "dataset" | variant == Biblatex -> "dataset"
+      "webpage" | variant == Biblatex -> "online"
+      "chapter"           -> case getVariable "editor" of
+                                Just _  -> "incollection"
+                                Nothing -> "inbook"
+      "entry-encyclopedia" | variant == Biblatex -> "inreference"
+                           | otherwise -> "inbook"
+      "paper-conference"  -> "inproceedings"
+      "thesis" -> case getVariableAsText "genre" of
+                    Just "mathesis" -> "mastersthesis"
+                    _               -> "phdthesis"
+      "patent"            | variant == Biblatex -> "patent"
+      "report"            | variant == Biblatex -> "report"
+                          | otherwise -> "techreport"
+      "speech"            -> "unpublished"
+      "manuscript"        -> "unpublished"
+      "graphic"           | variant == Biblatex -> "artwork"
+      "song"              | variant == Biblatex -> "music"
+      "legal_case"        | variant == Biblatex -> "jurisdiction"
+      "legislation"       | variant == Biblatex -> "legislation"
+      "treaty"            | variant == Biblatex -> "legal"
+      "personal_communication" | variant == Biblatex -> "letter"
+      "motion_picture"    | variant == Biblatex -> "movie"
+      "review"            | variant == Biblatex -> "review"
+      "software"          | variant == Biblatex -> "software"
+      _                   -> "misc"
+
+  mbSubtype =
+    case referenceType ref of
+      "article-magazine"  -> Just "magazine"
+      "article-newspaper" -> Just "newspaper"
+      _ -> Nothing
+
+  fs =
+    case variant of
+      Biblatex ->
+           [ "author"
+           , "editor"
+           , "translator"
+           , "publisher"
+           , "title"
+           , "booktitle"
+           , "journal"
+           , "series"
+           , "edition"
+           , "volume"
+           , "volumes"
+           , "number"
+           , "pages"
+           , "pagetotal"
+           , "version"
+           , "date"
+           , "eventdate"
+           , "urldate"
+           , "address"
+           , "url"
+           , "doi"
+           , "isbn"
+           , "issn"
+           , "type"
+           , "entrysubtype"
+           , "note"
+           , "langid"
+           , "abstract"
+           , "keywords"
+           , "annote"
+           ]
+      Bibtex ->
+           [ "author"
+           , "editor"
+           , "translator"
+           , "publisher"
+           , "title"
+           , "booktitle"
+           , "journal"
+           , "series"
+           , "edition"
+           , "volume"
+           , "number"
+           , "pages"
+           , "year"
+           , "month"
+           , "address"
+           , "type"
+           , "note"
+           , "annote"
+           , "url" -- not officially supported, but supported by
+                   -- some styles (#8287)
+           , "doi"
+           ]
+
+  valToInlines (TextVal t) = B.text t
+  valToInlines (FancyVal ils) = ils
+  valToInlines (NumVal n) = B.text (T.pack $ show n)
+  valToInlines (NamesVal names) =
+    mconcat $ intersperse (B.space <> B.text "and" <> B.space)
+            $ map renderName names
+  valToInlines (DateVal date) = B.text $
+    case dateLiteral date of
+      Just t  -> t
+      Nothing -> T.intercalate "/" (map renderDatePart (dateParts date)) <>
+                    (if dateCirca date then "~" else mempty)
+  valToInlines SubstitutedVal = mempty
+
+  renderDatePart (DateParts xs) = T.intercalate "-" $
+                                    map (T.pack . printf "%02d") xs
+
+  renderName name =
+    case nameLiteral name of
+      Just t  -> B.spanWith ("",[],[]) $ B.text t
+      Nothing -> spacedMaybes
+                  [ nameNonDroppingParticle name
+                  , nameFamily name
+                  , if nameCommaSuffix name
+                        then (", " <>) <$> nameSuffix name
+                        else nameSuffix name ]
+                  <>
+                  spacedMaybes
+                   [ (", " <>) <$> nameGiven name,
+                     nameDroppingParticle name ]
+
+  mblang' = case getVariableAsText "language" of
+              Just l  -> either (const Nothing) Just $ parseLang l
+              Nothing -> mblang
+
+  titlecase = case mblang' of
+                Just lang | langLanguage lang == "en"
+                                   -> titlecase'
+                Nothing            -> titlecase'
+                _                  ->
+                  case variant of
+                    Bibtex         -> B.spanWith nullAttr
+                     -- BibTex lacks a language field, so we wrap non-English
+                     -- titles in {} to protect case.
+                    Biblatex       -> id
+
+  titlecase' = addTextCase mblang' TitleCase .
+    (\ils -> B.fromList
+               (case B.toList ils of
+                  Str t : xs -> Str t : Walk.walk spanAroundCapitalizedWords xs
+                  xs         -> Walk.walk spanAroundCapitalizedWords xs))
+
+  -- protect capitalized words when we titlecase
+  spanAroundCapitalizedWords (Str t)
+    | not (T.all (\c -> isLower c || not (isLetter c)) t) =
+       Span ("",["nocase"],[]) [Str t]
+  spanAroundCapitalizedWords x = x
+
+  spacedMaybes = mconcat . intersperse B.space . mapMaybe (fmap B.text)
+
+  toLaTeX x =
+    case runPure (writeLaTeX opts $ doc (B.plain x)) of
+           Left _  -> Nothing
+           Right t -> Just $ hsep . map literal $ T.words t
+
+  renderField :: Text -> Maybe (Doc Text)
+  renderField name =
+    (((literal name) <>) . hang 2 " = " . braces)
+      <$> getContentsFor name
+
+  getVariable v = lookupVariable (toVariable v) ref
+
+  getVariableAsText v = (stringify . valToInlines) <$> getVariable v
+
+  getYear val =
+    case val of
+       DateVal date ->
+         case dateLiteral date of
+           Just t -> toLaTeX (B.text t)
+           Nothing ->
+             case dateParts date of
+               [DateParts (y1:_), DateParts (y2:_)] ->
+                 Just $ literal (T.pack (printf "%04d" y1) <> "--" <>
+                        T.pack (printf "%04d" y2))
+               [DateParts (y1:_)] ->
+                 Just $ literal (T.pack (printf "%04d" y1))
+               _ -> Nothing
+       _ -> Nothing
+
+  toMonth 1 = "jan"
+  toMonth 2 = "feb"
+  toMonth 3 = "mar"
+  toMonth 4 = "apr"
+  toMonth 5 = "may"
+  toMonth 6 = "jun"
+  toMonth 7 = "jul"
+  toMonth 8 = "aug"
+  toMonth 9 = "sep"
+  toMonth 10 = "oct"
+  toMonth 11 = "nov"
+  toMonth 12 = "dec"
+  toMonth x  = T.pack $ show x
+
+  getMonth val =
+    case val of
+       DateVal date ->
+         case dateParts date of
+           [DateParts (_:m1:_), DateParts (_:m2:_)] ->
+             Just $ literal (toMonth m1 <> "--" <> toMonth m2)
+           [DateParts (_:m1:_)] -> Just $ literal (toMonth m1)
+           _ -> Nothing
+       _ -> Nothing
+
+  getContentsFor :: Text -> Maybe (Doc Text)
+  getContentsFor "type" =
+    getVariableAsText "genre" >>=
+       \case
+          "mathesis"  -> Just "mastersthesis"
+          "phdthesis" -> Just "phdthesis"
+          _           -> Nothing
+  getContentsFor "entrysubtype" = literal <$> mbSubtype
+  getContentsFor "journal"
+    | bibtexType `elem` ["article", "periodical", "suppperiodical", "review"]
+      = getVariable "container-title" >>= toLaTeX . valToInlines
+    | otherwise = Nothing
+  getContentsFor "booktitle"
+    | bibtexType `elem`
+       ["inbook","incollection","inproceedings","inreference","bookinbook"]
+    = (getVariable "volume-title" <|> getVariable "container-title")
+                               >>= toLaTeX . valToInlines
+    | otherwise = Nothing
+  getContentsFor "series" = getVariable "collection-title"
+                               >>= toLaTeX . valToInlines
+  getContentsFor "address" = getVariable "publisher-place"
+                               >>= toLaTeX . valToInlines
+  getContentsFor "date"  = getVariable "issued" >>= toLaTeX . valToInlines
+  getContentsFor "eventdate" = getVariable "event-date" >>= toLaTeX . valToInlines
+  getContentsFor "urldate"  = getVariable "accessed" >>= toLaTeX . valToInlines
+  getContentsFor "year"  = getVariable "issued" >>= getYear
+  getContentsFor "month"  = getVariable "issued" >>= getMonth
+  getContentsFor "pages"  = getVariable "page" >>= toLaTeX . valToInlines
+  getContentsFor "pagetotal" = getVariable "number-of-pages"
+                                  >>= toLaTeX . valToInlines
+  getContentsFor "langid"  = getVariable "language" >>= toLaTeX . valToInlines
+  getContentsFor "number" = (getVariable "number"
+                         <|> getVariable "collection-number"
+                         <|> getVariable "issue") >>= toLaTeX . valToInlines
+
+  getContentsFor x = getVariable x >>=
+    if isURL x
+       then Just . literal . stringify . valToInlines
+       else toLaTeX .
+            (if x == "title"
+                then titlecase
+                else id) .
+            valToInlines
+
+  isURL x = x `elem` ["url","doi","issn","isbn"]
+
+  renderFields = mconcat . intersperse ("," <> cr) . mapMaybe renderField
+
+defaultLang :: Lang
+defaultLang = Lang "en" Nothing (Just "US") [] [] []
+
+-- a map of bibtex "string" macros
+type StringMap = Map.Map Text Text
+
+type BibParser = Parsec Sources (Lang, StringMap)
+
+data Item = Item{ identifier :: Text
+                , sourcePos  :: SourcePos
+                , entryType  :: Text
+                , fields     :: Map.Map Text Text
+                }
+                deriving (Show, Ord, Eq)
+
+itemToReference :: Locale -> Variant -> Item -> BibParser (Reference Inlines)
+itemToReference locale variant item = do
+  setPosition (sourcePos item)
+  bib item $ do
+    let lang = fromMaybe defaultLang $ localeLanguage locale
+    modify $ \st -> st{ localeLang = lang,
+                        untitlecase = langLanguage lang == "en" }
+
+    id' <- asks identifier
+    otherIds <- (Just <$> getRawField "ids")
+                  <|> return Nothing
+    (reftype, genre) <- getTypeAndGenre
+    -- hyphenation:
+    let getLangId = do
+             langid <- T.strip . T.toLower <$> getRawField "langid"
+             idopts <- T.strip . T.toLower . stringify <$>
+                           getField "langidopts" <|> return ""
+             case (langid, idopts) of
+                  ("english","variant=british")    -> return "british"
+                  ("english","variant=american")   -> return "american"
+                  ("english","variant=us")         -> return "american"
+                  ("english","variant=usmax")      -> return "american"
+                  ("english","variant=uk")         -> return "british"
+                  ("english","variant=australian") -> return "australian"
+                  ("english","variant=newzealand") -> return "newzealand"
+                  (x,_)                            -> return x
+    hyphenation <- (Just . toIETF . T.toLower <$>
+                     (getLangId <|> getRawField "hyphenation"))
+                  <|> return Nothing
+    modify $ \s -> s{ untitlecase = untitlecase s &&
+                                      case hyphenation of
+                                        Just x ->
+                                          "en-" `T.isPrefixOf` x || x == "en"
+                                        _ -> True }
+
+
+    opts <- (parseOptions <$> getRawField "options") <|> return []
+
+    et <- asks entryType
+
+    -- titles
+    let isArticle = et `elem`
+                     ["article", "periodical", "suppperiodical", "review"]
+    let isPeriodical = et == "periodical"
+    let isChapterlike = et `elem`
+           ["inbook","incollection","inproceedings","inreference","bookinbook"]
+
+    let getFieldMaybe f = (Just <$> getField f) <|> return Nothing
+
+    -- names
+    let getNameList' f = Just <$>
+         getNameList opts f
+
+    author' <- getNameList' "author" <|> return Nothing
+    containerAuthor' <- getNameList' "bookauthor" <|> return Nothing
+    translator' <- getNameList' "translator" <|> return Nothing
+    editortype <- getRawField "editortype" <|> return mempty
+    editor'' <- getNameList' "editor" <|> return Nothing
+    director'' <- getNameList' "director" <|> return Nothing
+    let (editor', director') = case editortype of
+                                    "director" -> (Nothing, editor'')
+                                    _          -> (editor'', director'')
+    -- FIXME: add same for editora, editorb, editorc
+
+    -- dates
+    issued' <- (Just <$> (getDate "date" <|> getOldDate mempty)) <|>
+               return Nothing
+    eventDate' <- (Just <$> (getDate "eventdate" <|> getOldDate "event")) <|>
+                   return Nothing
+    origDate' <- (Just <$> (getDate "origdate" <|> getOldDate "orig")) <|>
+                   return Nothing
+    accessed' <- (Just <$> (getDate "urldate" <|> getOldDate "url")) <|>
+                    return Nothing
+
+    -- locators
+    pages' <- getFieldMaybe "pages"
+    volume' <- getFieldMaybe "volume"
+    part' <- getFieldMaybe "part"
+    volumes' <- getFieldMaybe "volumes"
+    pagetotal' <- getFieldMaybe "pagetotal"
+    chapter' <- getFieldMaybe "chapter"
+    edition' <- getFieldMaybe "edition"
+    version' <- getFieldMaybe "version"
+    (number', collectionNumber', issue') <-
+       (getField "number" >>= \x ->
+         if et `elem` ["book","collection","proceedings","reference",
+                       "mvbook","mvcollection","mvproceedings", "mvreference",
+                       "bookinbook","inbook", "incollection","inproceedings",
+                       "inreference", "suppbook","suppcollection"]
+         then return (Nothing, Just x, Nothing)
+         else if isArticle
+              then (getField "issue" >>= \y ->
+                      return (Nothing, Nothing, Just $ concatWith ',' [x,y]))
+                 <|> return (Nothing, Nothing, Just x)
+              else return (Just x, Nothing, Nothing))
+        <|> return (Nothing, Nothing, Nothing)
+
+    -- titles
+    hasMaintitle <- (True <$ getRawField "maintitle") <|> return False
+
+    title' <- Just <$>
+              ((guard isPeriodical >> getTitle "issuetitle")
+              <|> (guard hasMaintitle >>
+                   guard (not isChapterlike) >>
+                   getTitle "maintitle")
+              <|> getTitle "title")
+              <|> return Nothing
+
+    subtitle' <- (guard isPeriodical >> getTitle "issuesubtitle")
+                  <|> (guard hasMaintitle >>
+                       guard (not isChapterlike) >>
+                       getTitle "mainsubtitle" <|> return mempty)
+                  <|> getTitle "subtitle"
+                  <|> return mempty
+    titleaddon' <- (guard hasMaintitle >>
+                     guard (not isChapterlike) >>
+                     getTitle "maintitleaddon" <|> return mempty)
+                    <|> getTitle "titleaddon"
+                    <|> return mempty
+
+    volumeTitle' <- Just <$>
+                    ((guard hasMaintitle >>
+                      guard (not isChapterlike) >>
+                      getTitle "title")
+                     <|> (guard hasMaintitle >>
+                          guard isChapterlike >>
+                          getTitle "booktitle"))
+                    <|> return Nothing
+    volumeSubtitle' <- (guard hasMaintitle >>
+                        guard (not isChapterlike) >>
+                        getTitle "subtitle")
+                       <|> (guard hasMaintitle >>
+                            guard isChapterlike >>
+                            getTitle "booksubtitle")
+                       <|> return mempty
+    volumeTitleAddon' <- (guard hasMaintitle >>
+                          guard (not isChapterlike) >>
+                          getTitle "titleaddon")
+                         <|> (guard hasMaintitle >>
+                              guard isChapterlike >>
+                              getTitle "booktitleaddon")
+                         <|> return mempty
+
+    containerTitle' <- Just <$>
+                       ((guard isPeriodical >> getPeriodicalTitle "title")
+                       <|> (guard isChapterlike >> getTitle "maintitle")
+                       <|> (guard isChapterlike >> getTitle "booktitle")
+                       <|> getPeriodicalTitle "journaltitle"
+                       <|> getPeriodicalTitle "journal")
+                       <|> return Nothing
+    containerSubtitle' <- (guard isPeriodical >> getPeriodicalTitle "subtitle")
+                          <|> (guard isChapterlike >> getTitle "mainsubtitle")
+                          <|> (guard isChapterlike >> getTitle "booksubtitle")
+                          <|> getPeriodicalTitle "journalsubtitle"
+                          <|> return mempty
+    containerTitleAddon' <- (guard isPeriodical >>
+                             getPeriodicalTitle "titleaddon")
+                            <|> (guard isChapterlike >>
+                                 getTitle "maintitleaddon")
+                            <|> (guard isChapterlike >>
+                                 getTitle "booktitleaddon")
+                            <|> return mempty
+    containerTitleShort' <- Just <$>
+                            ((guard isPeriodical >>
+                              guard (not hasMaintitle) >>
+                              getField "shorttitle")
+                            <|> getPeriodicalTitle "shortjournal")
+                           <|> return Nothing
+
+    -- change numerical series title to e.g. 'series 3'
+    let fixSeriesTitle [Str xs] | isNumber xs =
+          [Str (ordinalize locale xs), Space, Str (resolveKey' lang "jourser")]
+        fixSeriesTitle xs = xs
+
+    seriesTitle' <- (Just . B.fromList . fixSeriesTitle . B.toList
+                       <$> getTitle "series") <|>
+                    return Nothing
+    shortTitle' <- (Just <$> (guard (not hasMaintitle || isChapterlike) >>
+                              getTitle "shorttitle"))
+                 <|> (if (subtitle' /= mempty || titleaddon' /= mempty) &&
+                          not hasMaintitle
+                          then getShortTitle False "title"
+                          else getShortTitle True  "title")
+                 <|> return Nothing
+
+    eventTitle' <- Just <$> getTitle "eventtitle" <|> return Nothing
+    origTitle' <- Just <$> getTitle "origtitle" <|> return Nothing
+
+    -- publisher
+    pubfields <- mapM (\f -> Just `fmap`
+                         (if variant == Bibtex || f == "howpublished"
+                          then getField f
+                          else getLiteralList' f)
+                        <|> return Nothing)
+           ["school","institution","organization", "howpublished","publisher"]
+    let publisher' = case catMaybes pubfields of
+                       [] -> Nothing
+                       xs -> Just $ concatWith ';' xs
+    origpublisher' <- (Just <$> getField "origpublisher") <|> return Nothing
+
+    -- places
+    venue' <- (Just <$> getField "venue") <|> return Nothing
+    address' <- Just <$>
+                  (if variant == Bibtex
+                      then getField "address"
+                      else getLiteralList' "address"
+                         <|> (guard (et /= "patent") >>
+                              getLiteralList' "location"))
+                <|> return Nothing
+    origLocation' <- Just <$>
+                  (if variant == Bibtex
+                      then getField "origlocation"
+                      else getLiteralList' "origlocation")
+                    <|> return Nothing
+    jurisdiction' <- if reftype == "patent"
+                     then Just <$>
+                        (concatWith ';' . map (resolveKey lang) <$>
+                             getLiteralList "location") <|> return Nothing
+                     else return Nothing
+
+    -- url, doi, isbn, etc.:
+    -- note that with eprinttype = arxiv, we take eprint to be a partial url
+    -- archivePrefix is an alias for eprinttype
+    url' <- (guard (et == "online" || lookup "url" opts /= Just "false")
+             >> Just <$> getRawField "url")
+         <|> (do etype <- getRawField "eprinttype"
+                 eprint <- getRawField "eprint"
+                 let baseUrl =
+                       case T.toLower etype of
+                         "arxiv"       -> "https://arxiv.org/abs/"
+                         "jstor"       -> "https://www.jstor.org/stable/"
+                         "pubmed"      -> "https://www.ncbi.nlm.nih.gov/pubmed/"
+                         "googlebooks" -> "https://books.google.com?id="
+                         _             -> ""
+                 if T.null baseUrl
+                    then mzero
+                    else return $ Just $ baseUrl <> eprint)
+         <|> return Nothing
+    doi' <- (guard (lookup "doi" opts /= Just "false") >>
+             Just <$> getRawField "doi")
+           <|> return Nothing
+    isbn' <- Just <$> getRawField "isbn" <|> return Nothing
+    issn' <- Just <$> getRawField "issn" <|> return Nothing
+    pmid' <- Just <$> getRawField  "pmid" <|> return Nothing
+    pmcid' <- Just <$> getRawField "pmcid" <|> return Nothing
+    callNumber' <- Just <$> getRawField "library" <|> return Nothing
+
+    -- notes
+    annotation' <- Just <$>
+                   (getField "annotation" <|> getField "annote")
+                     <|> return Nothing
+    abstract' <- Just <$> getField "abstract" <|> return Nothing
+    keywords' <- Just <$> getField "keywords" <|> return Nothing
+    note' <- if et == "periodical"
+             then return Nothing
+             else Just <$> getField "note" <|> return Nothing
+    addendum' <- if variant == Bibtex
+                    then return Nothing
+                    else Just <$> getField "addendum"
+                 <|> return Nothing
+    pubstate' <- (  (Just . resolveKey lang <$> getField "pubstate")
+                  <|> case dateLiteral <$> issued' of
+                           Just (Just "forthcoming") ->
+                             return $ Just $ B.str "forthcoming"
+                           _ -> return Nothing
+                   )
+
+
+
+
+    let addField (_, Nothing) = id
+        addField (f, Just x)  = Map.insert f x
+    let vars = foldr addField mempty
+                [ ("other-ids", TextVal <$> otherIds)
+                , ("genre", TextVal <$> genre)
+                , ("language", TextVal <$> hyphenation)
+                -- dates
+                , ("accessed", DateVal <$> accessed')
+                , ("event-date", DateVal <$> eventDate')
+                , ("issued", DateVal <$> issued')
+                , ("original-date", DateVal <$> origDate')
+                -- names
+                , ("author", NamesVal <$> author')
+                , ("editor", NamesVal <$> editor')
+                , ("translator", NamesVal <$> translator')
+                , ("director", NamesVal <$> director')
+                , ("container-author", NamesVal <$> containerAuthor')
+                -- locators
+                , ("page", FancyVal . Walk.walk convertEnDash <$> pages')
+                , ("number-of-pages", FancyVal <$> pagetotal')
+                , ("volume", case (volume', part') of
+                               (Nothing, Nothing) -> Nothing
+                               (Just v, Nothing) -> Just $ FancyVal v
+                               (Nothing, Just p) -> Just $ FancyVal p
+                               (Just v, Just p)  ->
+                                 Just $ FancyVal $ v <> B.str "." <> p)
+                , ("number-of-volumes", FancyVal <$> volumes')
+                , ("chapter-number", FancyVal <$> chapter')
+                , ("edition", FancyVal <$> edition')
+                , ("version", FancyVal <$> version')
+                , ("number", FancyVal <$> number')
+                , ("collection-number", FancyVal <$> collectionNumber')
+                , ("issue", FancyVal <$> issue')
+                -- title
+                , ("original-title", FancyVal <$> origTitle')
+                , ("event", FancyVal <$> eventTitle')
+                , ("title", case title' of
+                              Just t -> Just $ FancyVal $
+                                         concatWith '.' [
+                                             concatWith ':' [t, subtitle']
+                                           , titleaddon' ]
+                              Nothing -> Nothing)
+                , ("volume-title",
+                            case volumeTitle' of
+                              Just t -> Just $ FancyVal $
+                                         concatWith '.' [
+                                             concatWith ':' [t, volumeSubtitle']
+                                           , volumeTitleAddon' ]
+                              Nothing -> Nothing)
+                , ("container-title",
+                            case containerTitle' of
+                              Just t -> Just $ FancyVal $
+                                         concatWith '.' [
+                                             concatWith ':' [t,
+                                               containerSubtitle']
+                                           , containerTitleAddon' ]
+                              Nothing -> Nothing)
+                , ("container-title-short", FancyVal <$> containerTitleShort')
+                , ("collection-title", FancyVal <$> seriesTitle')
+                , ("title-short", FancyVal <$> shortTitle')
+                -- publisher
+                , ("publisher", FancyVal <$> publisher')
+                , ("original-publisher", FancyVal <$> origpublisher')
+                -- places
+                , ("jurisdiction", FancyVal <$> jurisdiction')
+                , ("event-place",  FancyVal <$> venue')
+                , ("publisher-place", FancyVal <$> address')
+                , ("original-publisher-place", FancyVal <$> origLocation')
+                -- urls
+                , ("url", TextVal <$> url')
+                , ("doi", TextVal <$> doi')
+                , ("isbn", TextVal <$> isbn')
+                , ("issn", TextVal <$> issn')
+                , ("pmcid", TextVal <$> pmcid')
+                , ("pmid", TextVal <$> pmid')
+                , ("call-number", TextVal <$> callNumber')
+                -- notes
+                , ("note", case catMaybes [note', addendum'] of
+                             [] -> Nothing
+                             xs -> return $ FancyVal $ concatWith '.' xs)
+                , ("annote", FancyVal <$> annotation')
+                , ("abstract", FancyVal <$> abstract')
+                , ("keyword", FancyVal <$> keywords')
+                , ("status", FancyVal <$> pubstate')
+                ]
+    return $ Reference
+      { referenceId             = ItemId id'
+      , referenceType           = reftype
+      , referenceDisambiguation = Nothing
+      , referenceVariables      = vars }
+
+
+bib :: Item -> Bib a -> BibParser a
+bib entry m = fst <$> evalRWST m entry (BibState True defaultLang)
+
+resolveCrossRefs :: Variant -> [Item] -> [Item]
+resolveCrossRefs variant entries =
+  map (resolveCrossRef variant entries) entries
+
+resolveCrossRef :: Variant -> [Item] -> Item -> Item
+resolveCrossRef variant entries entry =
+  Map.foldrWithKey go entry (fields entry)
+  where go key val entry' =
+          if key == "crossref" || key == "xdata"
+          then entry'{ fields = fields entry' <>
+                          Map.fromList (getXrefFields variant
+                                        entry entries val) }
+          else entry'
+
+getXrefFields :: Variant -> Item -> [Item] -> Text -> [(Text, Text)]
+getXrefFields variant baseEntry entries keys = do
+  let keys' = splitKeys keys
+  xrefEntry <- [e | e <- entries, identifier e `elem` keys']
+  (k, v) <- Map.toList $ fields xrefEntry
+  if k == "crossref" || k == "xdata"
+     then do
+       xs <- mapM (getXrefFields variant baseEntry entries)
+                   (splitKeys v)
+       (x, y) <- xs
+       guard $ isNothing $ Map.lookup x $ fields xrefEntry
+       return (x, y)
+     else do
+       k' <- case variant of
+               Bibtex -> return k
+               Biblatex -> transformKey
+                            (entryType xrefEntry) (entryType baseEntry) k
+       guard $ isNothing $ Map.lookup k' $ fields baseEntry
+       return (k',v)
+
+
+
+data BibState = BibState{
+           untitlecase    :: Bool
+         , localeLang     :: Lang
+         }
+
+type Bib = RWST Item () BibState BibParser
+
+blocksToInlines :: [Block] -> Inlines
+blocksToInlines bs =
+  case bs of
+       [Plain xs] -> B.fromList xs
+       [Para  xs] -> B.fromList xs
+       _          -> B.fromList $ Walk.query (:[]) bs
+
+adjustSpans :: Lang -> Inline -> Inline
+adjustSpans lang (Span ("",[],[("bibstring",s)]) _) = Str $ resolveKey' lang s
+adjustSpans _ SoftBreak = Space
+adjustSpans _ x = x
+
+latex' :: Text -> Bib [Block]
+latex' t = do
+  lang <- gets localeLang
+  case parseLaTeX lang t of
+    Left _   -> mzero
+    Right bs -> return bs
+
+parseLaTeX :: Lang -> Text -> Either PandocError [Block]
+parseLaTeX lang t =
+  case runPure (readLaTeX
+                def{ readerExtensions =
+                      extensionsFromList [Ext_raw_tex, Ext_smart] } t) of
+    Left e              -> Left e
+    Right (Pandoc _ bs) -> Right $ Walk.walk (adjustSpans lang) bs
+
+latex :: Text -> Bib Inlines
+latex = fmap blocksToInlines . latex' . T.strip
+
+bibEntries :: BibParser [Item]
+bibEntries = do
+  skipMany nonEntry
+  many (bibItem <* skipMany nonEntry)
+ where nonEntry = bibSkip <|>
+                  comment <|>
+                  try (char '@' >>
+                       (bibComment <|> bibPreamble <|> bibString))
+
+bibSkip :: BibParser ()
+bibSkip = skipMany1 (satisfy (\c -> c /='@' && c /='%'))
+
+comment :: BibParser ()
+comment = char '%' *> void anyLine
+
+bibComment :: BibParser ()
+bibComment = do
+  cistring "comment"
+  spaces'
+  void inBraces
+
+bibPreamble :: BibParser ()
+bibPreamble = do
+  cistring "preamble"
+  spaces'
+  void inBraces
+
+bibString :: BibParser ()
+bibString = do
+  cistring "string"
+  spaces'
+  char '{'
+  spaces'
+  (k,v) <- entField
+  char '}'
+  updateState (\(l,m) -> (l, Map.insert k v m))
+  return ()
+
+take1WhileP :: Monad m => (Char -> Bool) -> ParsecT Sources u m Text
+take1WhileP f = T.pack <$> many1 (satisfy f)
+
+inBraces :: BibParser Text
+inBraces = do
+  char '{'
+  res <- manyTill
+         (  take1WhileP (\c -> c /= '{' && c /= '}' && c /= '\\')
+        <|> (char '\\' >> T.cons '\\' . T.singleton <$> anyChar)
+        <|> (braced <$> inBraces)
+         ) (char '}')
+  return $ T.concat res
+
+braced :: Text -> Text
+braced = T.cons '{' . flip T.snoc '}'
+
+inQuotes :: BibParser Text
+inQuotes = do
+  char '"'
+  T.concat <$> manyTill
+             ( take1WhileP (\c -> c /= '{' && c /= '"' && c /= '\\')
+               <|> (char '\\' >> T.cons '\\' . T.singleton <$> anyChar)
+               <|> braced <$> inBraces
+            ) (char '"')
+
+fieldName :: BibParser Text
+fieldName = resolveAlias . T.toLower
+  <$> take1WhileP (\c ->
+         isAlphaNum c || c == '-' || c == '_' || c == ':' || c == '+')
+
+isBibtexKeyChar :: Char -> Bool
+isBibtexKeyChar c =
+  isAlphaNum c || c `elem` (".:;?!`'()$/*@_+=-[]*&" :: [Char])
+
+spaces' :: BibParser ()
+spaces' = skipMany (void (satisfy isSpace) <|> comment)
+
+bibItem :: BibParser Item
+bibItem = do
+  char '@'
+  pos <- getPosition
+  enttype <- T.toLower <$> take1WhileP isLetter
+  spaces'
+  char '{'
+  spaces'
+  entid <- take1WhileP isBibtexKeyChar
+  spaces'
+  char ','
+  spaces'
+  entfields <- entField `sepEndBy` (char ',' >> spaces')
+  spaces'
+  char '}'
+  return $ Item entid pos enttype (Map.fromList entfields)
+
+entField :: BibParser (Text, Text)
+entField = do
+  k <- fieldName
+  spaces'
+  char '='
+  spaces'
+  vs <- (expandString <|> inQuotes <|> inBraces <|> rawWord) `sepBy`
+            try (spaces' >> char '#' >> spaces')
+  spaces'
+  return (k, T.concat vs)
+
+resolveAlias :: Text -> Text
+resolveAlias "archiveprefix" = "eprinttype"
+resolveAlias "primaryclass" = "eprintclass"
+resolveAlias s = s
+
+rawWord :: BibParser Text
+rawWord = take1WhileP isAlphaNum
+
+expandString :: BibParser Text
+expandString = do
+  k <- fieldName
+  (lang, strs) <- getState
+  case Map.lookup k strs of
+       Just v  -> return v
+       Nothing -> return $ resolveKey' lang k
+
+cistring :: Text -> BibParser Text
+cistring s = try (go s)
+ where go t = case T.uncons t of
+         Nothing     -> return ""
+         Just (c,cs) -> do
+           x <- char (toLower c) <|> char (toUpper c)
+           xs <- go cs
+           return (T.cons x xs)
+
+splitKeys :: Text -> [Text]
+splitKeys = filter (not . T.null) . T.split (\c -> c == ' ' || c == ',')
+
+-- Biblatex Localization Keys (see Biblatex manual)
+-- Currently we only map a subset likely to be used in Biblatex *databases*
+-- (in fields such as `type`, and via `\bibstring{}` commands).
+
+parseMonth :: Text -> Maybe Int
+parseMonth s =
+  case T.toLower s of
+         "jan" -> Just 1
+         "feb" -> Just 2
+         "mar" -> Just 3
+         "apr" -> Just 4
+         "may" -> Just 5
+         "jun" -> Just 6
+         "jul" -> Just 7
+         "aug" -> Just 8
+         "sep" -> Just 9
+         "oct" -> Just 10
+         "nov" -> Just 11
+         "dec" -> Just 12
+         _     -> readMay (T.unpack s)
+
+notFound :: Text -> Bib a
+notFound f = Prelude.fail $ T.unpack f ++ " not found"
+
+getField :: Text -> Bib Inlines
+getField f = do
+  fs <- asks fields
+  case Map.lookup f fs of
+       Just x  -> latex x
+       Nothing -> notFound f
+
+
+getPeriodicalTitle :: Text -> Bib Inlines
+getPeriodicalTitle f = do
+  ils <- getField f
+  return $ protectCase id ils
+
+protectCase :: (Inlines -> Inlines) -> (Inlines -> Inlines)
+protectCase f = Walk.walk unprotect . f . Walk.walk protect
+ where
+  protect (Span ("",[],[]) xs) = Span ("",["nocase"],[]) xs
+  protect  x = x
+  unprotect (Span ("",["nocase"],[]) xs)
+    | hasLowercaseWord xs = Span ("",["nocase"],[]) xs
+    | otherwise           = Span ("",[],[]) xs
+  unprotect x = x
+  hasLowercaseWord = any startsWithLowercase . splitStrWhen isPunctuation
+  startsWithLowercase (Str (T.uncons -> Just (x,_))) = isLower x
+  startsWithLowercase _           = False
+
+unTitlecase :: Maybe Lang -> Inlines -> Inlines
+unTitlecase mblang = protectCase (addTextCase mblang SentenceCase)
+
+getTitle :: Text -> Bib Inlines
+getTitle f = do
+  ils <- getField f
+  utc <- gets untitlecase
+  lang <- gets localeLang
+  let ils' =
+        if f == "series"
+           then resolveKey lang ils
+           else ils
+  let processTitle = if utc then unTitlecase (Just lang) else id
+  return $ processTitle ils'
+
+getShortTitle :: Bool -> Text -> Bib (Maybe Inlines)
+getShortTitle requireColon f = do
+  ils <- splitStrWhen (==':') . B.toList <$> getTitle f
+  if not requireColon || containsColon ils
+     then return $ Just $ B.fromList $ upToColon ils
+     else return Nothing
+
+containsColon :: [Inline] -> Bool
+containsColon xs = Str ":" `elem` xs
+
+upToColon :: [Inline] -> [Inline]
+upToColon xs = takeWhile (/= Str ":") xs
+
+isNumber :: Text -> Bool
+isNumber t = case T.uncons t of
+  Just ('-', ds) -> T.all isDigit ds
+  Just _         -> T.all isDigit t
+  Nothing        -> False
+
+getDate :: Text -> Bib Date
+getDate f = do
+  -- the ~ can used for approx dates, but the latex reader
+  -- parses this as a nonbreaking space, so we need to convert it back!
+  let nbspToTilde '\160' = '~'
+      nbspToTilde c      = c
+  mbd <- rawDateEDTF . T.map nbspToTilde <$> getRawField f
+  case mbd of
+    Nothing -> Prelude.fail "expected date"
+    Just d  -> return d
+
+-- A negative (BC) year might be written with -- or --- in bibtex:
+fixLeadingDash :: Text -> Text
+fixLeadingDash t = case T.uncons t of
+  Just (c, ds) | (c == '–' || c == '—') && firstIsDigit ds -> T.cons '–' ds
+  _ -> t
+ where firstIsDigit = maybe False (isDigit . fst) . T.uncons
+
+getOldDate :: Text -> Bib Date
+getOldDate prefix = do
+  year' <- (readMay . T.unpack . fixLeadingDash . stringify
+              <$> getField (prefix <> "year")) <|> return Nothing
+  month' <- (parseMonth <$> getRawField (prefix <> "month"))
+            <|> return Nothing
+  day' <- (readMay . T.unpack <$> getRawField (prefix <> "day"))
+          <|> return Nothing
+  endyear' <- (readMay . T.unpack . fixLeadingDash . stringify
+              <$> getField (prefix <> "endyear")) <|> return Nothing
+  endmonth' <- (parseMonth . stringify
+                 <$> getField (prefix <> "endmonth")) <|> return Nothing
+  endday' <- (readMay . T.unpack . stringify <$>
+                 getField (prefix <> "endday")) <|> return Nothing
+  let toDateParts (y', m', d') =
+              DateParts $
+                 case y' of
+                   Nothing -> []
+                   Just y  ->
+                     case m' of
+                       Nothing -> [y]
+                       Just m  ->
+                         case d' of
+                           Nothing -> [y,m]
+                           Just d  -> [y,m,d]
+  let dateparts = filter (\x -> x /= DateParts [])
+                  $ map toDateParts [(year',month',day'),
+                                     (endyear',endmonth',endday')]
+  literal' <- if null dateparts
+                 then Just <$> getRawField (prefix <> "year")
+                 else return Nothing
+  return $
+    Date { dateParts = dateparts
+         , dateCirca = False
+         , dateSeason = Nothing
+         , dateLiteral = literal' }
+
+getRawField :: Text -> Bib Text
+getRawField f = do
+  fs <- asks fields
+  case Map.lookup f fs of
+       Just x  -> return x
+       Nothing -> notFound f
+
+getLiteralList :: Text -> Bib [Inlines]
+getLiteralList f = do
+  fs <- asks fields
+  case Map.lookup f fs of
+       Just x  -> latex' x >>= toLiteralList
+       Nothing -> notFound f
+
+-- separates items with semicolons
+getLiteralList' :: Text -> Bib Inlines
+getLiteralList' f = do
+  fs <- asks fields
+  case Map.lookup f fs of
+    Just x    -> do
+      x' <- latex' x
+      case x' of
+        [Para xs]  ->
+          return $ B.fromList
+                 $ intercalate [Str ";", Space]
+                 $ splitByAnd xs
+        [Plain xs] ->
+          return $ B.fromList
+                 $ intercalate [Str ";", Space]
+                 $ splitByAnd xs
+        _          -> mzero
+    Nothing   -> notFound f
+
+splitByAnd :: [Inline] -> [[Inline]]
+splitByAnd = splitOn [Space, Str "and", Space]
+
+toLiteralList :: [Block] -> Bib [Inlines]
+toLiteralList [Para xs] =
+  return $ map B.fromList $ splitByAnd xs
+toLiteralList [Plain xs] = toLiteralList [Para xs]
+toLiteralList _ = mzero
+
+concatWith :: Char -> [Inlines] -> Inlines
+concatWith sep = L.foldl' go mempty
+  where go :: Inlines -> Inlines -> Inlines
+        go accum s
+          | s == mempty = accum
+          | otherwise   =
+              case Seq.viewr (B.unMany accum) of
+                     Seq.EmptyR -> s
+                     _ Seq.:> Str x
+                       | not (T.null x) &&
+                         T.last x `elem` ("!?.,:;" :: String)
+                                    -> accum <> B.space <> s
+                     _ -> accum <> B.str (T.singleton sep) <>
+                                                B.space <> s
+
+
+parseOptions :: Text -> [(Text, Text)]
+parseOptions = map breakOpt . T.splitOn ","
+  where breakOpt x = case T.break (=='=') x of
+                          (w,v) -> (T.toLower $ T.strip w,
+                                    T.toLower $ T.strip $ T.drop 1 v)
+
+optionSet :: Text -> [(Text, Text)] -> Bool
+optionSet key opts = case lookup key opts of
+                      Just "true" -> True
+                      Just s      -> s == mempty
+                      _           -> False
+
+getNameList :: [(Text, Text)] -> Text -> Bib [Name]
+getNameList opts  f = do
+  fs <- asks fields
+  case Map.lookup f fs of
+       Just x  -> latexNames nameopts x
+       Nothing -> notFound f
+ where
+  nameopts = NameOpts{
+                 nameOptsPrefixIsNonDroppingParticle = optionSet "useprefix" opts,
+                 nameOptsUseJuniorComma = optionSet "juniorcomma" opts}
+
+toNameList :: NameOpts -> [Block] -> Bib [Name]
+toNameList opts [Para xs] =
+  filter (/= emptyName) <$> mapM (toName opts . addSpaceAfterPeriod)
+                                    (splitByAnd xs)
+toNameList opts [Plain xs] = toNameList opts [Para xs]
+toNameList _ _ = mzero
+
+latexNames :: NameOpts -> Text -> Bib [Name]
+latexNames opts t = latex' (T.strip t) >>= toNameList opts
+
+-- see issue 392 for motivation.  We want to treat
+-- "J.G. Smith" and "J. G. Smith" the same.
+addSpaceAfterPeriod :: [Inline] -> [Inline]
+addSpaceAfterPeriod = go . splitStrWhen (=='.')
+  where
+    go [] = []
+    go (Str (T.unpack -> [c]):Str ".":Str (T.unpack -> [d]):xs)
+      | isLetter d
+      , isLetter c
+      , isUpper c
+      , isUpper d
+        = Str (T.singleton c):Str ".":Space:go (Str (T.singleton d):xs)
+    go (x:xs) = x:go xs
+
+ordinalize :: Locale -> Text -> Text
+ordinalize locale n =
+  let terms = localeTerms locale
+      pad0 t = case T.length t of
+                 0 -> "00"
+                 1 -> "0" <> t
+                 _ -> t
+   in case Map.lookup ("ordinal-" <> pad0 n) terms <|>
+           Map.lookup "ordinal" terms of
+        Nothing    -> n
+        Just []    -> n
+        Just (t:_) -> n <> snd t
+
+getTypeAndGenre :: Bib (Text, Maybe Text)
+getTypeAndGenre = do
+  lang <- gets localeLang
+  et <- asks entryType
+  reftype' <- resolveKey' lang <$> getRawField "type"
+         <|> return mempty
+  st <- getRawField "entrysubtype" <|> return mempty
+  isEvent <- (True <$ (getRawField "eventdate"
+                     <|> getRawField "eventtitle"
+                     <|> getRawField "venue")) <|> return False
+  let reftype =
+        case et of
+           "article"
+             | st == "magazine"  -> "article-magazine"
+             | st == "newspaper" -> "article-newspaper"
+             | otherwise         -> "article-journal"
+           "book"                -> "book"
+           "booklet"             -> "pamphlet"
+           "bookinbook"          -> "book"
+           "collection"          -> "book"
+           "dataset"             -> "dataset"
+           "electronic"          -> "webpage"
+           "inbook"              -> "chapter"
+           "incollection"        -> "chapter"
+           "inreference"         -> "entry-encyclopedia"
+           "inproceedings"       -> "paper-conference"
+           "manual"              -> "book"
+           "mastersthesis"       -> "thesis"
+           "misc"                -> ""
+           "mvbook"              -> "book"
+           "mvcollection"        -> "book"
+           "mvproceedings"       -> "book"
+           "mvreference"         -> "book"
+           "online"              -> "webpage"
+           "patent"              -> "patent"
+           "periodical"
+             | st == "magazine"  -> "article-magazine"
+             | st == "newspaper" -> "article-newspaper"
+             | otherwise         -> "article-journal"
+           "phdthesis"           -> "thesis"
+           "proceedings"         -> "book"
+           "reference"           -> "book"
+           "report"              -> "report"
+           "software"            -> "software"
+           "suppbook"            -> "chapter"
+           "suppcollection"      -> "chapter"
+           "suppperiodical"
+             | st == "magazine"  -> "article-magazine"
+             | st == "newspaper" -> "article-newspaper"
+             | otherwise         -> "article-journal"
+           "techreport"          -> "report"
+           "thesis"              -> "thesis"
+           "unpublished"         -> if isEvent then "speech" else "manuscript"
+           "www"                 -> "webpage"
+           -- biblatex, "unsupported"
+           "artwork"             -> "graphic"
+           "audio"               -> "song"    -- for audio *recordings*
+           "commentary"          -> "book"
+           "image"               -> "graphic"   -- or "figure" ?
+           "jurisdiction"        -> "legal_case"
+           "legislation"         -> "legislation"  -- or "bill" ?
+           "legal"               -> "treaty"
+           "letter"              -> "personal_communication"
+           "movie"               -> "motion_picture"
+           "music"               -> "song"        -- for musical *recordings*
+           "performance"         -> "speech"
+           "review"              -> "review"      -- or "review-book" ?
+           "standard"            -> "legislation"
+           "video"               -> "motion_picture"
+           -- biblatex-apa:
+           "data"                -> "dataset"
+           "letters"             -> "personal_communication"
+           "newsarticle"         -> "article-newspaper"
+           _                     -> ""
+
+  let refgenre =
+        case et of
+          "mastersthesis"  -> if T.null reftype'
+                                 then Just $ resolveKey' lang "mathesis"
+                                 else Just reftype'
+          "phdthesis"      -> if T.null reftype'
+                                 then Just $ resolveKey' lang "phdthesis"
+                                 else Just reftype'
+          _                -> if T.null reftype'
+                                 then Nothing
+                                 else Just reftype'
+  return (reftype, refgenre)
+
+
+-- transformKey source target key
+-- derived from Appendix C of bibtex manual
+transformKey :: Text -> Text -> Text -> [Text]
+transformKey _ _ "ids"            = []
+transformKey _ _ "crossref"       = []
+transformKey _ _ "xref"           = []
+transformKey _ _ "entryset"       = []
+transformKey _ _ "entrysubtype"   = []
+transformKey _ _ "execute"        = []
+transformKey _ _ "label"          = []
+transformKey _ _ "options"        = []
+transformKey _ _ "presort"        = []
+transformKey _ _ "related"        = []
+transformKey _ _ "relatedoptions" = []
+transformKey _ _ "relatedstring"  = []
+transformKey _ _ "relatedtype"    = []
+transformKey _ _ "shorthand"      = []
+transformKey _ _ "shorthandintro" = []
+transformKey _ _ "sortkey"        = []
+transformKey x y "author"
+  | x `elem` ["mvbook", "book"] &&
+    y `elem` ["inbook", "bookinbook", "suppbook"] = ["bookauthor", "author"]
+-- note: this next clause is not in the biblatex manual, but it makes
+-- sense in the context of CSL conversion:
+transformKey x y "author"
+  | x == "mvbook" && y == "book" = ["bookauthor", "author"]
+transformKey "mvbook" y z
+  | y `elem` ["book", "inbook", "bookinbook", "suppbook"] = standardTrans z
+transformKey x y z
+  | x `elem` ["mvcollection", "mvreference"] &&
+    y `elem` ["collection", "reference", "incollection", "inreference",
+               "suppcollection"] = standardTrans z
+transformKey "mvproceedings" y z
+  | y `elem` ["proceedings", "inproceedings"] = standardTrans z
+transformKey "book" y z
+  | y `elem` ["inbook", "bookinbook", "suppbook"] = bookTrans z
+transformKey x y z
+  | x `elem` ["collection", "reference"] &&
+    y `elem` ["incollection", "inreference", "suppcollection"] = bookTrans z
+transformKey "proceedings" "inproceedings" z = bookTrans z
+transformKey "periodical" y z
+  | y `elem` ["article", "suppperiodical"] =
+  case z of
+       "title"          -> ["journaltitle"]
+       "subtitle"       -> ["journalsubtitle"]
+       "shorttitle"     -> []
+       "sorttitle"      -> []
+       "indextitle"     -> []
+       "indexsorttitle" -> []
+       _                -> [z]
+transformKey _ _ x                = [x]
+
+standardTrans :: Text -> [Text]
+standardTrans z =
+  case z of
+       "title"          -> ["maintitle"]
+       "subtitle"       -> ["mainsubtitle"]
+       "titleaddon"     -> ["maintitleaddon"]
+       "shorttitle"     -> []
+       "sorttitle"      -> []
+       "indextitle"     -> []
+       "indexsorttitle" -> []
+       _                -> [z]
+
+bookTrans :: Text -> [Text]
+bookTrans z =
+  case z of
+       "title"          -> ["booktitle"]
+       "subtitle"       -> ["booksubtitle"]
+       "titleaddon"     -> ["booktitleaddon"]
+       "shorttitle"     -> []
+       "sorttitle"      -> []
+       "indextitle"     -> []
+       "indexsorttitle" -> []
+       _                -> [z]
+
+resolveKey :: Lang -> Inlines -> Inlines
+resolveKey lang (Many ils) = Many $ fmap go ils
+  where go (Str s) = Str $ resolveKey' lang s
+        go x       = x
+
+resolveKey' :: Lang -> Text -> Text
+resolveKey' lang k =
+  case Map.lookup (langLanguage lang) biblatexStringMap >>=
+        Map.lookup k of
+    Nothing     -> k
+    Just (x, _) -> either (const k) stringify $ parseLaTeX lang x
+
+convertEnDash :: Inline -> Inline
+convertEnDash (Str s) = Str (T.map (\c -> if c == '–' then '-' else c) s)
+convertEnDash x       = x
diff --git a/src/Text/Pandoc/Citeproc/CslJson.hs b/src/Text/Pandoc/Citeproc/CslJson.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Citeproc/CslJson.hs
@@ -0,0 +1,42 @@
+{-# LANGUAGE OverloadedStrings #-}
+module Text.Pandoc.Citeproc.CslJson
+  ( cslJsonToReferences )
+where
+
+import Citeproc.CslJson
+import Citeproc.Types
+import Control.Monad.Identity (runIdentity)
+import Data.Aeson (eitherDecodeStrict', FromJSON(parseJSON), (.:), Value(..))
+import Data.Aeson.Types (parseEither)
+import Data.ByteString (ByteString)
+import Text.Pandoc.Builder as B
+import Data.Text (Text)
+
+fromCslJson :: CslJson Text -> Inlines
+fromCslJson (CslText t) = B.text t
+fromCslJson CslEmpty = mempty
+fromCslJson (CslConcat x y) = fromCslJson x <> fromCslJson y
+fromCslJson (CslQuoted x) = B.doubleQuoted (fromCslJson x)
+fromCslJson (CslItalic x) = B.emph (fromCslJson x)
+fromCslJson (CslNormal x) = fromCslJson x  -- TODO?
+fromCslJson (CslBold x) = B.strong (fromCslJson x)
+fromCslJson (CslUnderline x) = B.underline (fromCslJson x)
+fromCslJson (CslNoDecoration x) =
+  B.spanWith ("",["nodecoration"],[]) (fromCslJson x)
+fromCslJson (CslSmallCaps x) = B.smallcaps (fromCslJson x)
+fromCslJson (CslBaseline x) = fromCslJson x
+fromCslJson (CslSub x) = B.subscript (fromCslJson x)
+fromCslJson (CslSup x) = B.superscript (fromCslJson x)
+fromCslJson (CslNoCase x) = B.spanWith ("",["nocase"],[]) (fromCslJson x)
+fromCslJson (CslDiv t x) = B.spanWith ("",["csl-" <> t],[]) (fromCslJson x)
+fromCslJson (CslLink u x) = B.link u "" (fromCslJson x)
+
+cslJsonToReferences :: ByteString -> Either String [Reference Inlines]
+cslJsonToReferences raw = do
+  items <-
+    case eitherDecodeStrict' raw of
+      Left e -> Left e
+      Right (Object o) -> parseEither (.: "items") o
+      Right val@(Array _) -> parseEither parseJSON val
+      Right _ -> Left "expecting Object or Array"
+  pure $ map (runIdentity . traverse (return . fromCslJson)) items
diff --git a/src/Text/Pandoc/Citeproc/Data.hs b/src/Text/Pandoc/Citeproc/Data.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Citeproc/Data.hs
@@ -0,0 +1,32 @@
+{-# LANGUAGE OverloadedStrings #-}
+{-# LANGUAGE TemplateHaskell #-}
+module Text.Pandoc.Citeproc.Data
+  (biblatexStringMap)
+where
+import Data.FileEmbed
+import Data.ByteString (ByteString)
+import qualified Data.Map as M
+import qualified Data.Text.Encoding as TE
+import qualified Data.Text as T
+import Data.Text (Text)
+import Text.Pandoc.Citeproc.Util (toIETF)
+import Text.Collate.Lang (Lang(..), parseLang)
+
+biblatexLocalizations :: [(FilePath, ByteString)]
+biblatexLocalizations = $(embedDir "citeproc/biblatex-localization")
+
+-- biblatex localization keys, from files at
+-- http://github.com/plk/biblatex/tree/master/tex/latex/biblatex/lbx
+biblatexStringMap :: M.Map Text (M.Map Text (Text, Text))
+biblatexStringMap = foldr go mempty biblatexLocalizations
+ where
+  go (fp, bs) =
+    let ls = T.lines $ TE.decodeUtf8 bs
+     in case parseLang (toIETF $ T.takeWhile (/= '.') $ T.pack fp) of
+          Right lang | length ls > 4
+            -> M.insert (langLanguage lang)
+                        (toStringMap $ map (T.splitOn "|") ls)
+          _ -> id
+  toStringMap = foldr go' mempty
+  go' [term, x, y] = M.insert term (x, y)
+  go' _ = id
diff --git a/src/Text/Pandoc/Citeproc/Locator.hs b/src/Text/Pandoc/Citeproc/Locator.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Citeproc/Locator.hs
@@ -0,0 +1,334 @@
+{-# LANGUAGE TupleSections #-}
+{-# LANGUAGE ViewPatterns #-}
+{-# LANGUAGE OverloadedStrings #-}
+module Text.Pandoc.Citeproc.Locator
+  ( parseLocator
+  , toLocatorMap
+  , LocatorInfo(..)
+  , LocatorMap(..) )
+where
+import Citeproc.Types
+import Text.Pandoc.Citeproc.Util (splitStrWhen)
+import Data.Text (Text)
+import qualified Data.Text as T
+import qualified Data.List as L
+import Text.Pandoc.Definition
+import Text.Pandoc.Parsing
+import Text.Pandoc.Shared (stringify)
+import Control.Monad (mzero)
+import qualified Data.Map as M
+import Data.Char (isSpace, isPunctuation, isDigit)
+
+
+data LocatorInfo =
+  LocatorInfo{ locatorRaw :: Text
+             , locatorLabel :: Text
+             , locatorLoc :: Text
+             }
+  deriving (Show)
+
+parseLocator :: LocatorMap -> [Inline] -> (Maybe LocatorInfo, [Inline])
+parseLocator locmap inp =
+  case parse (pLocatorWords locmap) "suffix" $ splitInp inp of
+       Right r -> r
+       Left _  -> (Nothing, maybeAddComma inp)
+
+splitInp :: [Inline] -> [Inline]
+splitInp = splitStrWhen (\c -> isSpace c || (isPunctuation c && c /= ':'))
+
+--
+-- Locator parsing
+--
+
+type LocatorParser = Parsec [Inline] ()
+
+pLocatorWords :: LocatorMap
+              -> LocatorParser (Maybe LocatorInfo, [Inline])
+pLocatorWords locMap = do
+  optional $ pMatchChar "," (== ',')
+  optional pSpace
+  info <- pLocatorDelimited locMap <|> pLocatorIntegrated locMap
+  s <- getInput -- rest is suffix
+  return $
+    if T.null (locatorLabel info) && T.null (locatorLoc info)
+       then (Nothing, maybeAddComma s)
+       else (Just info, s)
+
+maybeAddComma :: [Inline] -> [Inline]
+maybeAddComma [] = []
+maybeAddComma ils@(Space : _) = ils
+maybeAddComma ils@(Str t : _)
+  | Just (c, _) <- T.uncons t
+  , isPunctuation c = ils
+maybeAddComma ils = Str "," : Space : ils
+
+pLocatorDelimited :: LocatorMap -> LocatorParser LocatorInfo
+pLocatorDelimited locMap = try $ do
+  _ <- pMatchChar "{" (== '{')
+  skipMany pSpace -- gobble pre-spaces so label doesn't try to include them
+  (rawlab, la, _) <- pLocatorLabelDelimited locMap
+  -- we only care about balancing {} and [] (because of the outer [] scope);
+  -- the rest can be anything
+  let inner = do { t <- anyToken; return (True, cslJsonify t) }
+  gs <- many (pBalancedBraces [('{','}'), ('[',']')] inner)
+  _ <- pMatchChar "}" (== '}')
+  let lo = mconcat $ map snd gs
+  return $ LocatorInfo{ locatorLoc = lo,
+                        locatorLabel = la,
+                        locatorRaw = rawlab <> "{" <> lo <> "}" }
+
+-- a variant of stringify that preserves formatting using CSL JSON
+-- conventions
+cslJsonify :: Inline -> Text
+cslJsonify = go
+  where goMany :: [Inline] -> T.Text
+        goMany = mconcat . map go
+        go :: Inline -> T.Text
+        go (Str t) = t
+        go Space = " "
+        go SoftBreak = " "
+        go LineBreak = " "
+        go (Emph ils) = "<i>" <> goMany ils <> "</i>"
+        go (Underline ils) = "<u>" <> goMany ils <> "</u>"
+        go (Strong ils) = "<b>" <> goMany ils <> "</b>"
+        go (Strikeout ils) = goMany ils
+        go (Superscript ils) = "<sup>" <> goMany ils <> "</sup>"
+        go (Subscript ils) = "<sub>" <> goMany ils <> "</sub>"
+        go (SmallCaps ils) = "<span style=\"font-variant:small-caps;\">" <>
+                              goMany ils <> "</span>"
+        go (Quoted SingleQuote ils) = "'" <> goMany ils <> "'"
+        go (Quoted DoubleQuote ils) = "\"" <> goMany ils <> "\""
+        go (Cite _ ils) = goMany ils
+        go (Code _ t) = t
+        go (Math _ t) = t
+        go (RawInline _ _) = ""
+        go (Link _ ils _) = goMany ils
+        go (Image _ ils _) = goMany ils
+        go (Note _) = ""
+        go (Span (_,cls@(_:_),_) ils) =
+          "<span class=\"" <> T.unwords cls <> "\">" <> goMany ils <> "</span>"
+        go (Span (_,[],[("style","baseline")]) ils) =
+          "<span style=\"baseline\">" <> goMany ils <> "</span>"
+        go (Span _ ils) = goMany ils
+
+pLocatorLabelDelimited :: LocatorMap -> LocatorParser (Text, Text, Bool)
+pLocatorLabelDelimited locMap
+  = pLocatorLabel' locMap (stringify <$> anyToken)
+      <|> (("", "page", True) <$ lookAhead (pMatchChar "digit" isDigit))
+      <|> (pure ("", "", True))
+
+pLocatorIntegrated :: LocatorMap -> LocatorParser LocatorInfo
+pLocatorIntegrated locMap = try $ do
+  (rawlab, la, wasImplicit) <- pLocatorLabelIntegrated locMap
+  -- if we got the label implicitly, we have presupposed the first one is
+  -- going to have a digit, so guarantee that. You _can_ have p. (a)
+  -- because you specified it.
+  let modifier = if wasImplicit
+                    then requireDigits
+                    else requireRomansOrDigits
+  g <- try $ pLocatorWordIntegrated (not wasImplicit) >>= modifier
+  gs <- many (try $ pLocatorWordIntegrated False >>= modifier)
+  let lo = T.concat (g:gs)
+  return $ LocatorInfo{ locatorLabel = la,
+                        locatorLoc = lo,
+                        locatorRaw = rawlab <> lo }
+
+pLocatorLabelIntegrated :: LocatorMap -> LocatorParser (Text, Text, Bool)
+pLocatorLabelIntegrated locMap
+  = pLocatorLabel' locMap lim <|>
+     (lookAhead digital >> return ("", "page", True))
+    where
+      lim = try $ pLocatorWordIntegrated True >>= requireRomansOrDigits
+      digital = try $ pLocatorWordIntegrated True >>= requireDigits
+
+pLocatorLabel' :: LocatorMap -> LocatorParser Text
+               -> LocatorParser (Text, Text, Bool)
+pLocatorLabel' locMap lim = go ""
+    where
+      -- grow the match string until we hit the end
+      -- trying to find the largest match for a label
+      go acc = try $ do
+          -- advance at least one token each time
+          -- the pathological case is "p.3"
+          t <- anyToken
+          ts <- manyTill anyToken (try $ lookAhead lim)
+          let s = acc <> stringify (t:ts)
+          case M.lookup (T.toCaseFold $ T.strip s) (unLocatorMap locMap) of
+            -- try to find a longer one, or return this one
+            Just l -> go s <|> return (s, l, False)
+            Nothing -> go s
+
+-- hard requirement for a locator to have some real digits in it
+requireDigits :: (Bool, Text) -> LocatorParser Text
+requireDigits (_, s) = if not (T.any isDigit s)
+                          then Prelude.fail "requireDigits"
+                          else return s
+
+-- soft requirement for a sequence with some roman or arabic parts
+-- (a)(iv) -- because iv is roman
+-- 1(a)  -- because 1 is an actual digit
+-- NOT: a, (a)-(b), hello, (some text in brackets)
+requireRomansOrDigits :: (Bool, Text) -> LocatorParser Text
+requireRomansOrDigits (d, s) = if not d
+                                  then Prelude.fail "requireRomansOrDigits"
+                                  else return s
+
+pLocatorWordIntegrated :: Bool -> LocatorParser (Bool, Text)
+pLocatorWordIntegrated isFirst = try $ do
+  punct <- if isFirst
+              then return ""
+              else (stringify <$> pLocatorSep) <|> return ""
+  sp <- option "" (pSpace >> return " ")
+  (dig, s) <- pBalancedBraces [('(',')'), ('[',']'), ('{','}')] pPageSeq
+  return (dig, punct <> sp <> s)
+
+-- we want to capture:  123, 123A, C22, XVII, 33-44, 22-33; 22-11
+--                      34(1), 34A(A), 34(1)(i)(i), (1)(a)
+--                      [17], [17]-[18], '591 [84]'
+--                      (because CSL cannot pull out individual pages/sections
+--                      to wrap in braces on a per-style basis)
+pBalancedBraces :: [(Char, Char)]
+                -> LocatorParser (Bool, Text)
+                -> LocatorParser (Bool, Text)
+pBalancedBraces braces p = try $ do
+  ss <- many1 surround
+  return $ anyWereDigitLike ss
+  where
+      except = notFollowedBy pBraces >> p
+      -- outer and inner
+      surround = L.foldl' (\a (open, close) -> sur open close except <|> a)
+                       except
+                       braces
+
+      isc c = stringify <$> pMatchChar [c] (== c)
+
+      sur c c' m = try $ do
+          (d, mid) <- isc c *> option (False, "") m <* isc c'
+          return (d, T.cons c . flip T.snoc c' $  mid)
+
+      flattened = concatMap (\(o, c) -> [o, c]) braces
+      pBraces = pMatchChar "braces" (`elem` flattened)
+
+
+-- YES 1, 1.2, 1.2.3
+-- NO  1., 1.2. a.6
+-- can't use sepBy because we want to leave trailing .s
+pPageSeq :: LocatorParser (Bool, Text)
+pPageSeq = oneDotTwo <|> withPeriod
+  where
+      oneDotTwo = do
+          u <- pPageUnit
+          us <- many withPeriod
+          return $ anyWereDigitLike (u:us)
+      withPeriod = try $ do
+          -- .2
+          p <- pMatchChar "." (== '.')
+          u <- try pPageUnit
+          return (fst u, stringify p <> snd u)
+
+anyWereDigitLike :: [(Bool, Text)] -> (Bool, Text)
+anyWereDigitLike as = (any fst as, T.concat $ map snd as)
+
+pPageUnit :: LocatorParser (Bool, Text)
+pPageUnit = roman <|> plainUnit
+  where
+      -- roman is a 'digit'
+      roman = (True,) <$> pRoman
+      plainUnit = do
+          ts <- many1 (notFollowedBy pSpace >>
+                       notFollowedBy pLocatorPunct >>
+                       notFollowedBy pMath >>
+                       anyToken)
+          let s = stringify ts
+          -- otherwise look for actual digits or -s
+          return (T.any isDigit s, s)
+
+pRoman :: LocatorParser Text
+pRoman = try $ do
+  tok <- anyToken
+  case tok of
+       Str t -> case parse (romanNumeral True *> eof)
+                   "roman numeral" (T.toUpper t) of
+                      Left _    -> mzero
+                      Right ()  -> return t
+       _      -> mzero
+
+pLocatorPunct :: LocatorParser Inline
+pLocatorPunct = pMatchChar "punctuation" isLocatorPunct
+
+pLocatorSep :: LocatorParser Inline
+pLocatorSep = pMatchChar "locator separator" isLocatorSep
+
+pMatchChar :: String -> (Char -> Bool) -> LocatorParser Inline
+pMatchChar msg f = satisfyTok f' <?> msg
+    where
+        f' (Str (T.unpack -> [c])) = f c
+        f' _                       = False
+
+pSpace :: LocatorParser Inline
+pSpace = satisfyTok (\t -> isSpacey t || t == Str "\160") <?> "space"
+
+pMath :: LocatorParser Inline
+pMath = satisfyTok isMath
+ where
+  isMath (Math{}) = True
+  isMath _ = False
+
+satisfyTok :: (Inline -> Bool) -> LocatorParser Inline
+satisfyTok f = tokenPrim show (\sp _ _ -> sp) (\tok -> if f tok
+                                                          then Just tok
+                                                          else Nothing)
+
+isSpacey :: Inline -> Bool
+isSpacey Space     = True
+isSpacey SoftBreak = True
+isSpacey _         = False
+
+isLocatorPunct :: Char -> Bool
+isLocatorPunct '-' = False -- page range
+isLocatorPunct '–' = False -- page range, en dash
+isLocatorPunct ':' = False -- vol:page-range hack
+isLocatorPunct c   = isPunctuation c -- includes [{()}]
+
+isLocatorSep :: Char -> Bool
+isLocatorSep ',' = True
+isLocatorSep ';' = True
+isLocatorSep _   = False
+
+--
+-- Locator Map
+--
+
+newtype LocatorMap = LocatorMap { unLocatorMap :: M.Map Text Text }
+  deriving (Show)
+
+toLocatorMap :: Locale -> LocatorMap
+toLocatorMap locale =
+  LocatorMap $ foldr go mempty locatorTerms
+ where
+  go tname locmap =
+    case M.lookup tname (localeTerms locale) of
+      Nothing -> locmap
+      Just ts -> foldr (\x -> M.insert (T.toCaseFold $ snd x) tname) locmap ts
+-- we store keys in "case-folded" (lowercase) form, so that both
+-- "Chap." and "chap." will match, for example.
+
+locatorTerms :: [Text]
+locatorTerms =
+  [ "book"
+  , "chapter"
+  , "column"
+  , "figure"
+  , "folio"
+  , "issue"
+  , "line"
+  , "note"
+  , "opus"
+  , "page"
+  , "number-of-pages"
+  , "paragraph"
+  , "part"
+  , "section"
+  , "sub-verbo"
+  , "verse"
+  , "volume" ]
diff --git a/src/Text/Pandoc/Citeproc/MetaValue.hs b/src/Text/Pandoc/Citeproc/MetaValue.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Citeproc/MetaValue.hs
@@ -0,0 +1,251 @@
+{-# LANGUAGE OverloadedStrings #-}
+module Text.Pandoc.Citeproc.MetaValue
+  ( referenceToMetaValue
+  , metaValueToReference
+  , metaValueToText
+  )
+where
+
+import Citeproc.Types
+import Text.Pandoc.Definition
+import Text.Pandoc.Builder as B
+import Text.Pandoc.Shared (stringify, blocksToInlines')
+import Data.Maybe
+import Safe
+import qualified Data.Set as Set
+import qualified Data.Map as M
+import qualified Data.Text as T
+import Data.Text (Text)
+import Text.Printf (printf)
+import Control.Applicative ((<|>))
+
+metaValueToText :: MetaValue -> Maybe Text
+metaValueToText (MetaString t) = Just t
+metaValueToText (MetaInlines ils) = Just $ stringify ils
+metaValueToText (MetaBlocks bls) = Just $ stringify bls
+metaValueToText (MetaList xs) = T.unwords <$> mapM metaValueToText xs
+metaValueToText _ = Nothing
+
+metaValueToBool :: MetaValue -> Maybe Bool
+metaValueToBool (MetaBool b) = Just b
+metaValueToBool (MetaString "true") = Just True
+metaValueToBool (MetaString "false") = Just False
+metaValueToBool (MetaInlines ils) =
+  metaValueToBool (MetaString (stringify ils))
+metaValueToBool _ = Nothing
+
+referenceToMetaValue :: Reference Inlines -> MetaValue
+referenceToMetaValue ref =
+  let ItemId id' = referenceId ref
+      type' = referenceType ref
+   in MetaMap $ M.insert "id" (MetaString id')
+              $ M.insert "type" (MetaString type')
+              $ M.map valToMetaValue
+              $ M.mapKeys fromVariable
+              $ referenceVariables ref
+
+
+valToMetaValue :: Val Inlines -> MetaValue
+valToMetaValue (TextVal t) = MetaString t
+valToMetaValue (FancyVal ils) = MetaInlines (B.toList ils)
+valToMetaValue (NumVal n) = MetaString (T.pack $ show n)
+valToMetaValue (NamesVal ns) = MetaList $ map nameToMetaValue ns
+valToMetaValue (DateVal d) = dateToMetaValue d
+valToMetaValue _ = MetaString mempty
+
+nameToMetaValue :: Name -> MetaValue
+nameToMetaValue name =
+  MetaMap $
+    (maybe id (M.insert "family" . MetaString) (nameFamily name)) .
+    (maybe id (M.insert "given" . MetaString) (nameGiven name)) .
+    (maybe id (M.insert "dropping-particle" . MetaString)
+       (nameDroppingParticle name)) .
+    (maybe id (M.insert "non-dropping-particle" . MetaString)
+       (nameNonDroppingParticle name)) .
+    (maybe id (M.insert "suffix" . MetaString) (nameSuffix name)) .
+    (maybe id (M.insert "literal" . MetaString) (nameLiteral name)) .
+    (if nameCommaSuffix name
+        then M.insert "comma-suffix" (MetaBool True)
+        else id) .
+    (if nameStaticOrdering name
+        then M.insert "static-ordering" (MetaBool True)
+        else id)
+    $ mempty
+
+dateToMetaValue :: Date -> MetaValue
+dateToMetaValue date =
+  MetaString $
+    (case dateLiteral date of
+       Just l  -> l
+       Nothing -> T.intercalate "/" $ map datePartsToEDTF $ dateParts date)
+    <> (if dateCirca date then "~" else "")
+ where
+  datePartsToEDTF (DateParts dps) =
+    T.pack $
+     (case dps of
+        (y:_) | y > 9999 || y < -10000 -> ('y':)
+        _ -> id) $
+    case dps of
+      (y:m:d:_)
+       | y < -1     -> printf "%05d-%02d-%02d" (y+1) m d
+       | otherwise  -> printf "%04d-%02d-%02d" y m d
+      (y:m:[])
+       | y < -1     -> printf "%05d-%02d" (y+1) m
+       | otherwise  -> printf "%04d-%02d" y m
+      (y:[])
+       | y == 0     -> printf "" -- used for open range
+       | y < -1     -> printf "%05d" (y+1)
+       | otherwise  -> printf "%04d" y
+      _             -> mempty
+
+metaValueToReference :: MetaValue
+                     -> Maybe (Reference Inlines)
+metaValueToReference (MetaMap m) = do
+  let m' = M.mapKeys normalizeKey m
+  id' <- M.lookup "id" m' >>= metaValueToText
+  type' <- (M.lookup "type" m' >>= metaValueToText) <|> pure ""
+  let m'' = M.delete "id" $ M.delete "type" m'
+  let vars = M.mapKeys toVariable $ M.mapWithKey metaValueToVal m''
+  return $ Reference { referenceId = ItemId id'
+                     , referenceType = type'
+                     , referenceDisambiguation = Nothing
+                     , referenceVariables = vars }
+metaValueToReference _ = Nothing
+
+metaValueToVal :: Text -> MetaValue -> Val Inlines
+metaValueToVal k v
+  | k `Set.member` dateVariables
+       = DateVal $ metaValueToDate v
+  | k `Set.member` nameVariables
+       = NamesVal $ metaValueToNames v
+  | k == "other-ids"
+       = TextVal $ fromMaybe mempty $ metaValueToText v
+         -- will create space-separated list
+  | otherwise =
+    case v of
+      MetaString t -> TextVal t
+      MetaInlines ils -> FancyVal (B.fromList ils)
+      MetaBlocks bs   -> FancyVal (blocksToInlines' bs)
+      MetaBool b   -> TextVal (if b then "true" else "false")
+      MetaList _   -> TextVal mempty
+      MetaMap  _   -> TextVal mempty
+
+metaValueToDate :: MetaValue -> Date
+metaValueToDate (MetaMap m) = fromMaybe
+  (Date
+   { dateParts = dateparts
+   , dateCirca = circa
+   , dateSeason = season
+   , dateLiteral = literal })
+  rawdate
+ where
+  dateparts = case M.lookup "date-parts" m of
+                Just (MetaList xs) ->
+                  mapMaybe metaValueToDateParts xs
+                Just _ -> []
+                Nothing ->
+                  maybeToList $ metaValueToDateParts (MetaMap m)
+  circa = fromMaybe False $
+            M.lookup "circa" m >>= metaValueToBool
+  season = M.lookup "season" m >>= metaValueToInt
+  literal = M.lookup "literal" m >>= metaValueToText
+  rawdate = M.lookup "raw" m >>= metaValueToText >>= rawDateEDTF
+metaValueToDate (MetaList xs) =
+  Date{ dateParts = mapMaybe metaValueToDateParts xs
+      , dateCirca = False
+      , dateSeason = Nothing
+      , dateLiteral = Nothing }
+metaValueToDate x =
+  fromMaybe emptyDate $ metaValueToText x >>= rawDateEDTF
+
+
+metaValueToInt :: MetaValue -> Maybe Int
+metaValueToInt x = metaValueToText x >>= readMay . T.unpack
+
+metaValueToDateParts :: MetaValue -> Maybe DateParts
+metaValueToDateParts (MetaList xs) =
+  Just $ DateParts $ map (fromMaybe 0 . metaValueToInt) xs
+metaValueToDateParts (MetaMap m) =
+  case (M.lookup "year" m >>= metaValueToInt,
+        ((M.lookup "month" m >>= metaValueToInt)
+          <|>
+        ((+ 20) <$> (M.lookup "season" m >>= metaValueToInt))),
+        M.lookup "day" m >>= metaValueToInt) of
+    (Just y, Just mo, Just d)  -> Just $ DateParts [y, mo, d]
+    (Just y, Just mo, Nothing) -> Just $ DateParts [y, mo]
+    (Just y, Nothing, _)       -> Just $ DateParts [y]
+    _                          -> Nothing
+metaValueToDateParts _ = Nothing
+
+emptyDate :: Date
+emptyDate = Date { dateParts = []
+                 , dateCirca = False
+                 , dateSeason = Nothing
+                 , dateLiteral = Nothing }
+
+metaValueToNames :: MetaValue -> [Name]
+metaValueToNames (MetaList xs) = mapMaybe metaValueToName xs
+metaValueToNames x = maybeToList $ metaValueToName x
+
+metaValueToName :: MetaValue -> Maybe Name
+metaValueToName (MetaMap m) = extractParticles <$>
+  Just Name
+    { nameFamily = family
+    , nameGiven = given
+    , nameDroppingParticle = dropping
+    , nameNonDroppingParticle = nondropping
+    , nameSuffix = suffix
+    , nameCommaSuffix = commasuffix
+    , nameStaticOrdering = staticordering
+    , nameLiteral = literal
+    }
+ where
+  family = M.lookup "family" m >>= metaValueToText
+  given  = M.lookup "given" m >>= metaValueToText
+  dropping = M.lookup "dropping-particle" m
+                >>= metaValueToText
+  nondropping = M.lookup "non-dropping-particle" m
+                >>= metaValueToText
+  suffix = M.lookup "suffix" m >>= metaValueToText
+  commasuffix = fromMaybe False $
+    M.lookup "comma-suffix" m >>= metaValueToBool
+  staticordering = fromMaybe False $
+    M.lookup "static-ordering" m >>= metaValueToBool
+  literal = M.lookup "literal" m >>= metaValueToText
+metaValueToName x = extractParticles <$>
+  case metaValueToText x of
+    Nothing -> Nothing
+    Just lit -> Just Name
+                     { nameFamily = Nothing
+                     , nameGiven = Nothing
+                     , nameDroppingParticle = Nothing
+                     , nameNonDroppingParticle = Nothing
+                     , nameSuffix = Nothing
+                     , nameCommaSuffix = False
+                     , nameStaticOrdering = False
+                     , nameLiteral = Just lit }
+
+dateVariables :: Set.Set Text
+dateVariables = Set.fromList
+  [ "accessed", "container", "event-date", "issued",
+    "original-date", "submitted" ]
+
+nameVariables :: Set.Set Text
+nameVariables = Set.fromList
+  [ "author", "collection-editor", "composer",
+    "container-author", "director", "editor",
+    "editorial-director", "illustrator",
+    "interviewer", "original-author",
+    "recipient", "reviewed-author",
+    "translator" ]
+
+normalizeKey :: Text -> Text
+normalizeKey k =
+  case T.toLower k of
+    "doi"   -> "DOI"
+    "isbn"  -> "ISBN"
+    "issn"  -> "ISSN"
+    "pmcid" -> "PMCID"
+    "pmid"  -> "PMID"
+    "url"   -> "URL"
+    x       -> x
diff --git a/src/Text/Pandoc/Citeproc/Name.hs b/src/Text/Pandoc/Citeproc/Name.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Citeproc/Name.hs
@@ -0,0 +1,153 @@
+{-# LANGUAGE ViewPatterns      #-}
+{-# LANGUAGE OverloadedStrings #-}
+{-# LANGUAGE ScopedTypeVariables #-}
+{-# LANGUAGE FlexibleContexts #-}
+{-# OPTIONS_GHC -fno-warn-unused-do-bind #-}
+-----------------------------------------------------------------------------
+-- |
+-- Module      :  Text.CSL.Input.Name
+-- Copyright   :  (c) John MacFarlane
+-- License     :  BSD-style (see LICENSE)
+--
+-- Maintainer  :  John MacFarlane <fiddlosopher@gmail.com>
+-- Stability   :  unstable
+-- Portability :  portable
+--
+-----------------------------------------------------------------------------
+
+module Text.Pandoc.Citeproc.Name
+    ( toName
+    , NameOpts(..)
+    , emptyName
+    )
+    where
+
+import Text.Pandoc.Definition
+import Text.Pandoc.Shared (stringify)
+import Citeproc.Types
+import Citeproc.Pandoc ()
+import Text.Pandoc.Citeproc.Util (splitStrWhen)
+import qualified Data.Text              as T
+import           Data.List.Split        (splitWhen, wordsBy)
+import Data.Char (isUpper, isDigit)
+import qualified Data.List as L
+
+emptyName :: Name
+emptyName =
+    Name {  nameFamily              = Nothing
+          , nameGiven               = Nothing
+          , nameDroppingParticle    = Nothing
+          , nameNonDroppingParticle = Nothing
+          , nameSuffix              = Nothing
+          , nameLiteral             = Nothing
+          , nameCommaSuffix         = False
+          , nameStaticOrdering      = False
+          }
+
+-- | Options for 'toName'.
+data NameOpts =
+  NameOpts
+    { nameOptsPrefixIsNonDroppingParticle :: Bool
+        -- ^ Treat a prefix on the last name as a non-dropping particle
+        -- (default is to treat it as a dropping particle). This corresponds
+        -- to the biblatex option @useprefix@.
+    , nameOptsUseJuniorComma              :: Bool
+        -- ^ Put a comma before a suffix like "Jr." This corresponds to the
+        -- biblatex option @juniorcomma@.
+    } deriving (Show)
+
+-- | Parse a list of 'Inline's into a citeproc 'Name', identifying
+-- first and last name, particles, suffixes.
+toName :: Monad m => NameOpts -> [Inline] -> m Name
+toName _ [Str "others"] =
+  return emptyName{ nameLiteral = Just "others" }
+toName _ [Span ("",[],[]) ils] = -- corporate author
+  return emptyName{ nameLiteral = Just $ stringify ils }
+-- extended BibLaTeX name format - see #266
+toName _ ils@(Str ys:_) | T.any (== '=') ys = do
+  let commaParts = splitWhen (== Str ",")
+                   . splitStrWhen (\c -> c == ',' || c == '=' || c == '\160')
+                   $ ils
+  let addPart ag (Str "given" : Str "=" : xs) =
+        ag{ nameGiven = case nameGiven ag of
+                          Nothing -> Just $ stringify xs
+                          Just t  -> Just $ t <> " " <> stringify xs }
+      addPart ag (Str "family" : Str "=" : xs) =
+        ag{ nameFamily = Just $ stringify xs }
+      addPart ag (Str "prefix" : Str "=" : xs) =
+        ag{ nameDroppingParticle =  Just $ stringify xs }
+      addPart ag (Str "useprefix" : Str "=" : Str "true" : _) =
+        ag{ nameNonDroppingParticle = nameDroppingParticle ag
+          , nameDroppingParticle    = Nothing }
+      addPart ag (Str "suffix" : Str "=" : xs) =
+        ag{ nameSuffix = Just $ stringify xs }
+      addPart ag (Space : xs) = addPart ag xs
+      addPart ag _ = ag
+  return $ L.foldl' addPart emptyName commaParts
+-- First von Last
+-- von Last, First
+-- von Last, Jr ,First
+-- NOTE: biblatex and bibtex differ on:
+-- Drummond de Andrade, Carlos
+-- bibtex takes "Drummond de" as the von;
+-- biblatex takes the whole as a last name.
+-- See https://github.com/plk/biblatex/issues/236
+-- Here we implement the more sensible biblatex behavior.
+toName opts ils = do
+  let words' = wordsBy (\x -> x == Space || x == Str "\160")
+  let commaParts = map words' $ splitWhen (== Str ",")
+                              $ splitStrWhen
+                                   (\c -> c == ',' || c == '\160') ils
+  let (first, vonlast, jr) =
+          case commaParts of
+               --- First is the longest sequence of white-space separated
+               -- words starting with an uppercase and that is not the
+               -- whole string. von is the longest sequence of whitespace
+               -- separated words whose last word starts with lower case
+               -- and that is not the whole string.
+               [fvl]      -> let (caps', rest') = span isCapitalized fvl
+                             in  if null rest' && not (null caps')
+                                 then (init caps', [last caps'], [])
+                                 else (caps', rest', [])
+               [vl,f]     -> (f, vl, [])
+               (vl:j:f:_) -> (f, vl, j )
+               []         -> ([], [], [])
+
+  let (von, lastname) =
+                 case break isCapitalized vonlast of
+                        (vs@(_:_), []) -> (init vs, [last vs])
+                        (vs, ws)       -> (vs, ws)
+  let prefix = T.unwords $ map stringify von
+  let family = T.unwords $ map stringify lastname
+  let suffix = T.unwords $ map stringify jr
+  let given = T.unwords $ map stringify first
+  return
+    Name {  nameFamily              = if T.null family
+                                         then Nothing
+                                         else Just family
+          , nameGiven               = if T.null given
+                                         then Nothing
+                                         else Just given
+          , nameDroppingParticle    = if nameOptsPrefixIsNonDroppingParticle opts ||
+                                          T.null prefix
+                                         then Nothing
+                                         else Just prefix
+          , nameNonDroppingParticle = if nameOptsPrefixIsNonDroppingParticle opts &&
+                                          not (T.null prefix)
+                                         then Just prefix
+                                         else Nothing
+          , nameSuffix              = if T.null suffix
+                                         then Nothing
+                                         else Just suffix
+          , nameLiteral             = Nothing
+          , nameCommaSuffix         = nameOptsUseJuniorComma opts
+          , nameStaticOrdering      = False
+          }
+
+isCapitalized :: [Inline] -> Bool
+isCapitalized (Str (T.uncons -> Just (c,cs)) : rest)
+  | isUpper c = True
+  | isDigit c = isCapitalized (Str cs : rest)
+  | otherwise = False
+isCapitalized (_:rest) = isCapitalized rest
+isCapitalized [] = True
diff --git a/src/Text/Pandoc/Citeproc/Util.hs b/src/Text/Pandoc/Citeproc/Util.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Citeproc/Util.hs
@@ -0,0 +1,82 @@
+{-# LANGUAGE FlexibleContexts #-}
+{-# LANGUAGE OverloadedStrings #-}
+module Text.Pandoc.Citeproc.Util
+ ( splitStrWhen
+ , toIETF )
+where
+import qualified Data.Text as T
+import Data.Text (Text)
+import Text.Pandoc.Definition
+
+-- Split Str elements so that characters satisfying the
+-- predicate each have their own Str.
+splitStrWhen :: (Char -> Bool) -> [Inline] -> [Inline]
+splitStrWhen p = foldr go []
+ where
+  go (Str t) = (map Str (T.groupBy goesTogether t) ++)
+  go x = (x :)
+  goesTogether c d   = not (p c || p d)
+
+toIETF :: Text -> Text
+toIETF "english"         = "en-US" -- "en-EN" unavailable in CSL
+toIETF "usenglish"       = "en-US"
+toIETF "american"        = "en-US"
+toIETF "british"         = "en-GB"
+toIETF "ukenglish"       = "en-GB"
+toIETF "canadian"        = "en-US" -- "en-CA" unavailable in CSL
+toIETF "australian"      = "en-GB" -- "en-AU" unavailable in CSL
+toIETF "newzealand"      = "en-GB" -- "en-NZ" unavailable in CSL
+toIETF "afrikaans"       = "af-ZA"
+toIETF "arabic"          = "ar"
+toIETF "basque"          = "eu"
+toIETF "bulgarian"       = "bg-BG"
+toIETF "catalan"         = "ca-AD"
+toIETF "croatian"        = "hr-HR"
+toIETF "czech"           = "cs-CZ"
+toIETF "danish"          = "da-DK"
+toIETF "dutch"           = "nl-NL"
+toIETF "estonian"        = "et-EE"
+toIETF "finnish"         = "fi-FI"
+toIETF "canadien"        = "fr-CA"
+toIETF "acadian"         = "fr-CA"
+toIETF "french"          = "fr-FR"
+toIETF "francais"        = "fr-FR"
+toIETF "austrian"        = "de-AT"
+toIETF "naustrian"       = "de-AT"
+toIETF "german"          = "de-DE"
+toIETF "germanb"         = "de-DE"
+toIETF "ngerman"         = "de-DE"
+toIETF "greek"           = "el-GR"
+toIETF "polutonikogreek" = "el-GR"
+toIETF "polytonicgreek"  = "el-GR"
+toIETF "hebrew"          = "he-IL"
+toIETF "hungarian"       = "hu-HU"
+toIETF "icelandic"       = "is-IS"
+toIETF "italian"         = "it-IT"
+toIETF "japanese"        = "ja-JP"
+toIETF "latvian"         = "lv-LV"
+toIETF "lithuanian"      = "lt-LT"
+toIETF "magyar"          = "hu-HU"
+toIETF "mongolian"       = "mn-MN"
+toIETF "norsk"           = "nb-NO"
+toIETF "nynorsk"         = "nn-NO"
+toIETF "farsi"           = "fa-IR"
+toIETF "polish"          = "pl-PL"
+toIETF "brazil"          = "pt-BR"
+toIETF "brazilian"       = "pt-BR"
+toIETF "portugues"       = "pt-PT"
+toIETF "portuguese"      = "pt-PT"
+toIETF "romanian"        = "ro-RO"
+toIETF "russian"         = "ru-RU"
+toIETF "serbian"         = "sr-RS"
+toIETF "serbianc"        = "sr-RS"
+toIETF "slovak"          = "sk-SK"
+toIETF "slovene"         = "sl-SL"
+toIETF "spanish"         = "es-ES"
+toIETF "swedish"         = "sv-SE"
+toIETF "thai"            = "th-TH"
+toIETF "turkish"         = "tr-TR"
+toIETF "ukrainian"       = "uk-UA"
+toIETF "vietnamese"      = "vi-VN"
+toIETF "latin"           = "la"
+toIETF x                 = x
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
@@ -1,1074 +1,33 @@
-{-# LANGUAGE CPP #-}
-{-# LANGUAGE PatternGuards #-}
-{-# LANGUAGE DeriveFunctor #-}
-{-# LANGUAGE TypeSynonymInstances #-}
-{-# LANGUAGE MultiParamTypeClasses #-}
-{-# LANGUAGE FlexibleInstances #-}
-{-# LANGUAGE GeneralizedNewtypeDeriving #-}
-{-# LANGUAGE FlexibleContexts #-}
-{-# LANGUAGE UndecidableInstances #-}
-{-# LANGUAGE ScopedTypeVariables #-}
-#if MIN_VERSION_base(4,8,0)
-#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
-   License     : GNU GPL, version 2 or above
-
-   Maintainer  : Jesse Rosenthal <jrosenthal@jhu.edu>
-   Stability   : alpha
-   Portability : portable
-
-This module defines a type class, 'PandocMonad', for pandoc readers
-and writers. A pure instance 'PandocPure' and an impure instance
-'PandocIO' are provided.  This allows users of the library to choose
-whether they want conversions to perform IO operations (such as
-reading include files or images).
--}
-
-module Text.Pandoc.Class ( PandocMonad(..)
-                         , CommonState(..)
-                         , PureState(..)
-                         , getPureState
-                         , getsPureState
-                         , putPureState
-                         , modifyPureState
-                         , getPOSIXTime
-                         , getZonedTime
-                         , readFileFromDirs
-                         , report
-                         , setTrace
-                         , setRequestHeader
-                         , getLog
-                         , setVerbosity
-                         , getVerbosity
-                         , getMediaBag
-                         , setMediaBag
-                         , insertMedia
-                         , setUserDataDir
-                         , getUserDataDir
-                         , fetchItem
-                         , getInputFiles
-                         , setInputFiles
-                         , getOutputFile
-                         , setOutputFile
-                         , setResourcePath
-                         , getResourcePath
-                         , PandocIO(..)
-                         , PandocPure(..)
-                         , FileTree(..)
-                         , FileInfo(..)
-                         , addToFileTree
-                         , insertInFileTree
-                         , runIO
-                         , runIOorExplode
-                         , runPure
-                         , readDefaultDataFile
-                         , readDataFile
-                         , fetchMediaResource
-                         , fillMediaBag
-                         , extractMedia
-                         , toLang
-                         , setTranslations
-                         , translateTerm
-                         , Translations
-                         ) where
-
-import Prelude hiding (readFile)
-import System.Random (StdGen, next, mkStdGen)
-import qualified System.Random as IO (newStdGen)
-import Codec.Archive.Zip
-import qualified Data.CaseInsensitive as CI
-import Data.Unique (hashUnique)
-import Data.List (stripPrefix)
-import qualified Data.Unique as IO (newUnique)
-import qualified Text.Pandoc.UTF8 as UTF8
-import qualified System.Directory as Directory
-import Text.Pandoc.Compat.Time (UTCTime)
-import Text.Pandoc.Logging
-import Text.Parsec (ParsecT, getPosition, sourceLine, sourceName)
-import qualified Text.Pandoc.Compat.Time as IO (getCurrentTime)
-import Text.Pandoc.MIME (MimeType, getMimeType, extensionFromMimeType)
-import Text.Pandoc.Definition
-import Data.Digest.Pure.SHA (sha1, showDigest)
-import Data.Maybe (fromMaybe)
-import Data.Time.Clock.POSIX ( utcTimeToPOSIXSeconds
-                             , posixSecondsToUTCTime
-                             , POSIXTime )
-import Data.Time.LocalTime (TimeZone, ZonedTime, utcToZonedTime, utc)
-import Data.ByteString.Base64 (decodeLenient)
-import Network.URI ( escapeURIString, nonStrictRelativeTo,
-                     unEscapeString, parseURIReference, isAllowedInURI,
-                     parseURI, URI(..) )
-import Network.HTTP.Client
-       (httpLbs, responseBody, responseHeaders,
-        Request(port, host, requestHeaders), parseRequest, newManager)
-import Network.HTTP.Client.Internal (addProxy)
-import Network.HTTP.Client.TLS (tlsManagerSettings)
-import System.Environment (getEnv)
-import Network.HTTP.Types.Header ( hContentType )
-import Network (withSocketsDo)
-import Data.ByteString.Lazy (toChunks)
-import qualified Control.Exception as E
-import qualified Data.Time.LocalTime as IO (getCurrentTimeZone)
-import Text.Pandoc.MediaBag (MediaBag, lookupMedia, mediaDirectory)
-import Text.Pandoc.Walk (walkM, walk)
-import qualified Text.Pandoc.MediaBag as MB
-import qualified Data.ByteString as B
-import qualified Data.ByteString.Lazy as BL
-import qualified System.Environment as IO (lookupEnv)
-import System.FilePath.Glob (match, compile)
-import System.Directory (createDirectoryIfMissing, getDirectoryContents,
-                          doesDirectoryExist)
-import System.FilePath ((</>), (<.>), takeDirectory,
-         takeExtension, dropExtension, isRelative, normalise)
-import qualified System.FilePath.Glob as IO (glob)
-import qualified System.FilePath.Posix as Posix
-import System.FilePath (splitDirectories)
-import qualified System.Directory as IO (getModificationTime)
-import Control.Monad as M (fail)
-import Control.Monad.State.Strict
-import Control.Monad.Except
-import Data.Word (Word8)
-import Data.Default
-import System.IO.Error
-import System.IO (stderr)
-import qualified Data.Map as M
-import Text.Pandoc.Error
-import Text.Pandoc.BCP47 (Lang(..), parseBCP47, renderLang)
-import Text.Pandoc.Translations (Term(..), Translations, lookupTerm,
-                                 readTranslations)
-import qualified Debug.Trace
-#ifdef EMBED_DATA_FILES
-import Text.Pandoc.Data (dataFiles)
-#else
-import qualified Paths_pandoc as Paths
-#endif
-
--- | The PandocMonad typeclass contains all the potentially
--- IO-related functions used in pandoc's readers and writers.
--- Instances of this typeclass may implement these functions
--- in IO (as in 'PandocIO') or using an internal state that
--- represents a file system, time, and so on (as in 'PandocPure').
-class (Functor m, Applicative m, Monad m, MonadError PandocError m)
-      => PandocMonad m where
-  -- | Lookup an environment variable.
-  lookupEnv :: String -> m (Maybe String)
-  -- | Get the current (UTC) time.
-  getCurrentTime :: m UTCTime
-  -- | Get the locale's time zone.
-  getCurrentTimeZone :: m TimeZone
-  -- | Return a new generator for random numbers.
-  newStdGen :: m StdGen
-  -- | Return a new unique integer.
-  newUniqueHash :: m Int
-  -- | Retrieve contents and mime type from a URL, raising
-  -- an error on failure.
-  openURL :: String -> m (B.ByteString, Maybe MimeType)
-  -- | Read the lazy ByteString contents from a file path,
-  -- raising an error on failure.
-  readFileLazy :: FilePath -> m BL.ByteString
-  -- | Read the strict ByteString contents from a file path,
-  -- raising an error on failure.
-  readFileStrict :: FilePath -> m B.ByteString
-  -- | Return a list of paths that match a glob, relative to
-  -- the working directory.  See 'System.FilePath.Glob' for
-  -- the glob syntax.
-  glob :: String -> m [FilePath]
-  -- | Returns True if file exists.
-  fileExists :: FilePath -> m Bool
-  -- | Returns the path of data file.
-  getDataFileName :: FilePath -> m FilePath
-  -- | Return the modification time of a file.
-  getModificationTime :: FilePath -> m UTCTime
-  -- | Get the value of the 'CommonState' used by all instances
-  -- of 'PandocMonad'.
-  getCommonState :: m CommonState
-  -- | Set the value of the 'CommonState' used by all instances
-  -- of 'PandocMonad'.
-  -- | Get the value of a specific field of 'CommonState'.
-  putCommonState :: CommonState -> m ()
-  -- | Get the value of a specific field of 'CommonState'.
-  getsCommonState :: (CommonState -> a) -> m a
-  getsCommonState f = f <$> getCommonState
-  -- | Modify the 'CommonState'.
-  modifyCommonState :: (CommonState -> CommonState) -> m ()
-  modifyCommonState f = getCommonState >>= putCommonState . f
-  -- Output a log message.
-  logOutput :: LogMessage -> m ()
-  -- Output a debug message to sterr, using 'Debug.Trace.trace',
-  -- if tracing is enabled.  Note: this writes to stderr even in
-  -- pure instances.
-  trace :: String -> m ()
-  trace msg = do
-    tracing <- getsCommonState stTrace
-    when tracing $ Debug.Trace.trace ("[trace] " ++ msg) (return ())
-
--- * Functions defined for all PandocMonad instances
-
--- | Set the verbosity level.
-setVerbosity :: PandocMonad m => Verbosity -> m ()
-setVerbosity verbosity =
-  modifyCommonState $ \st -> st{ stVerbosity = verbosity }
-
--- | Get the verbosity level.
-getVerbosity :: PandocMonad m => m Verbosity
-getVerbosity = getsCommonState stVerbosity
-
--- Get the accomulated log messages (in temporal order).
-getLog :: PandocMonad m => m [LogMessage]
-getLog = reverse <$> getsCommonState stLog
-
--- | Log a message using 'logOutput'.  Note that 'logOutput' is
--- called only if the verbosity level exceeds the level of the
--- message, but the message is added to the list of log messages
--- that will be retrieved by 'getLog' regardless of its verbosity level.
-report :: PandocMonad m => LogMessage -> m ()
-report msg = do
-  verbosity <- getsCommonState stVerbosity
-  let level = messageVerbosity msg
-  when (level <= verbosity) $ logOutput msg
-  modifyCommonState $ \st -> st{ stLog = msg : stLog st }
-
--- | Determine whether tracing is enabled.  This affects
--- the behavior of 'trace'.  If tracing is not enabled,
--- 'trace' does nothing.
-setTrace :: PandocMonad m => Bool -> m ()
-setTrace useTracing = modifyCommonState $ \st -> st{stTrace = useTracing}
-
--- | Set request header to use in HTTP requests.
-setRequestHeader :: PandocMonad m
-                 => String  -- ^ Header name
-                 -> String  -- ^ Value
-                 -> m ()
-setRequestHeader name val = modifyCommonState $ \st ->
-  st{ stRequestHeaders =
-       (name, val) : filter (\(n,_) -> n /= name) (stRequestHeaders st)  }
-
--- | Initialize the media bag.
-setMediaBag :: PandocMonad m => MediaBag -> m ()
-setMediaBag mb = modifyCommonState $ \st -> st{stMediaBag = mb}
-
--- Retrieve the media bag.
-getMediaBag :: PandocMonad m => m MediaBag
-getMediaBag = getsCommonState stMediaBag
-
--- Insert an item into the media bag.
-insertMedia :: PandocMonad m => FilePath -> Maybe MimeType -> BL.ByteString -> m ()
-insertMedia fp mime bs = do
-  mb <- getMediaBag
-  let mb' = MB.insertMedia fp mime bs mb
-  setMediaBag mb'
-
--- Retrieve the input filenames.
-getInputFiles :: PandocMonad m => m [FilePath]
-getInputFiles = getsCommonState stInputFiles
-
--- Set the input filenames.
-setInputFiles :: PandocMonad m => [FilePath] -> m ()
-setInputFiles fs = do
-  let sourceURL = case fs of
-                    []    -> Nothing
-                    (x:_) -> case parseURI x of
-                                Just u
-                                  | uriScheme u `elem` ["http:","https:"] ->
-                                      Just $ show u{ uriQuery = "",
-                                                     uriFragment = "" }
-                                _ -> Nothing
-
-  modifyCommonState $ \st -> st{ stInputFiles = fs
-                               , stSourceURL = sourceURL }
-
--- Retrieve the output filename.
-getOutputFile :: PandocMonad m => m (Maybe FilePath)
-getOutputFile = getsCommonState stOutputFile
-
--- Set the output filename.
-setOutputFile :: PandocMonad m => Maybe FilePath -> m ()
-setOutputFile mbf = modifyCommonState $ \st -> st{ stOutputFile = mbf }
-
--- Retrieve the resource path searched by 'fetchItem'.
-getResourcePath :: PandocMonad m => m [FilePath]
-getResourcePath = getsCommonState stResourcePath
-
--- Set the resource path searched by 'fetchItem'.
-setResourcePath :: PandocMonad m => [FilePath] -> m ()
-setResourcePath ps = modifyCommonState $ \st -> st{stResourcePath = ps}
-
--- Get the POSIX time.
-getPOSIXTime :: PandocMonad m => m POSIXTime
-getPOSIXTime = utcTimeToPOSIXSeconds <$> getCurrentTime
-
--- Get the zoned time.
-getZonedTime :: PandocMonad m => m ZonedTime
-getZonedTime = do
-  t <- getCurrentTime
-  tz <- getCurrentTimeZone
-  return $ utcToZonedTime tz t
-
--- | Read file, checking in any number of directories.
-readFileFromDirs :: PandocMonad m => [FilePath] -> FilePath -> m (Maybe String)
-readFileFromDirs [] _ = return Nothing
-readFileFromDirs (d:ds) f = catchError
-    ((Just . UTF8.toStringLazy) <$> readFileLazy (d </> f))
-    (\_ -> readFileFromDirs ds f)
-
---
-
--- | 'CommonState' represents state that is used by all
--- instances of 'PandocMonad'.  Normally users should not
--- need to interact with it directly; instead, auxiliary
--- functions like 'setVerbosity' and 'withMediaBag' should be used.
-data CommonState = CommonState { stLog          :: [LogMessage]
-                                 -- ^ A list of log messages in reverse order
-                               , stUserDataDir  :: Maybe FilePath
-                                 -- ^ Directory to search for data files
-                               , stSourceURL    :: Maybe String
-                                 -- ^ Absolute URL + dir of 1st source file
-                               , stRequestHeaders :: [(String, String)]
-                                 -- ^ Headers to add for HTTP requests
-                               , stMediaBag     :: MediaBag
-                                 -- ^ Media parsed from binary containers
-                               , stTranslations :: Maybe
-                                                  (Lang, Maybe Translations)
-                                 -- ^ Translations for localization
-                               , stInputFiles   :: [FilePath]
-                                 -- ^ List of input files from command line
-                               , stOutputFile   :: Maybe FilePath
-                                 -- ^ Output file from command line
-                               , stResourcePath :: [FilePath]
-                                 -- ^ Path to search for resources like
-                                 -- included images
-                               , stVerbosity    :: Verbosity
-                                 -- ^ Verbosity level
-                               , stTrace        :: Bool
-                                 -- ^ Controls whether tracing messages are
-                                 -- issued.
-                               }
-
-instance Default CommonState where
-  def = CommonState { stLog = []
-                    , stUserDataDir = Nothing
-                    , stSourceURL = Nothing
-                    , stRequestHeaders = []
-                    , stMediaBag = mempty
-                    , stTranslations = Nothing
-                    , stInputFiles = []
-                    , stOutputFile = Nothing
-                    , stResourcePath = ["."]
-                    , stVerbosity = WARNING
-                    , stTrace = False
-                    }
-
--- | Convert BCP47 string to a Lang, issuing warning
--- if there are problems.
-toLang :: PandocMonad m => Maybe String -> m (Maybe Lang)
-toLang Nothing = return Nothing
-toLang (Just s) =
-  case parseBCP47 s of
-       Left _ -> do
-         report $ InvalidLang s
-         return Nothing
-       Right l -> return (Just l)
-
--- | Select the language to use with 'translateTerm'.
--- Note that this does not read a translation file;
--- that is only done the first time 'translateTerm' is
--- used.
-setTranslations :: PandocMonad m => Lang -> m ()
-setTranslations lang =
-  modifyCommonState $ \st -> st{ stTranslations = Just (lang, Nothing) }
-
--- | Load term map.
-getTranslations :: PandocMonad m => m Translations
-getTranslations = do
-  mbtrans <- getsCommonState stTranslations
-  case mbtrans of
-       Nothing -> return mempty  -- no language defined
-       Just (_, Just t) -> return t
-       Just (lang, Nothing) -> do  -- read from file
-         let translationFile = "translations/" ++ renderLang lang ++ ".yaml"
-         let fallbackFile = "translations/" ++ langLanguage lang ++ ".yaml"
-         let getTrans fp = do
-               bs <- readDataFile fp
-               case readTranslations (UTF8.toString bs) of
-                    Left e   -> do
-                      report $ CouldNotLoadTranslations (renderLang lang)
-                        (fp ++ ": " ++ e)
-                      -- make sure we don't try again...
-                      modifyCommonState $ \st ->
-                        st{ stTranslations = Nothing }
-                      return mempty
-                    Right t -> do
-                      modifyCommonState $ \st ->
-                                  st{ stTranslations = Just (lang, Just t) }
-                      return t
-         catchError (getTrans translationFile)
-           (\_ ->
-             catchError (getTrans fallbackFile)
-               (\e -> do
-                 report $ CouldNotLoadTranslations (renderLang lang)
-                          $ case e of
-                               PandocCouldNotFindDataFileError _ ->
-                                 "data file " ++ fallbackFile ++ " not found"
-                               _ -> ""
-                 -- make sure we don't try again...
-                 modifyCommonState $ \st -> st{ stTranslations = Nothing }
-                 return mempty))
-
--- | Get a translation from the current term map.
--- Issue a warning if the term is not defined.
-translateTerm :: PandocMonad m => Term -> m String
-translateTerm term = do
-  translations <- getTranslations
-  case lookupTerm term translations of
-       Just s -> return s
-       Nothing -> do
-         report $ NoTranslation (show term)
-         return ""
-
--- | Evaluate a 'PandocIO' operation.
-runIO :: PandocIO a -> IO (Either PandocError a)
-runIO ma = flip evalStateT def $ runExceptT $ unPandocIO ma
-
--- | Evaluate a 'PandocIO' operation, handling any errors
--- by exiting with an appropriate message and error status.
-runIOorExplode :: PandocIO a -> IO a
-runIOorExplode ma = runIO ma >>= handleError
-
-newtype PandocIO a = PandocIO {
-  unPandocIO :: ExceptT PandocError (StateT CommonState IO) a
-  } deriving ( MonadIO
-             , Functor
-             , Applicative
-             , Monad
-             , MonadError PandocError
-             )
-
--- | Utility function to lift IO errors into 'PandocError's.
-liftIOError :: (String -> IO a) -> String -> PandocIO a
-liftIOError f u = do
-  res <- liftIO $ tryIOError $ f u
-  case res of
-         Left e  -> throwError $ PandocIOError u e
-         Right r -> return r
-
-instance PandocMonad PandocIO where
-  lookupEnv = liftIO . IO.lookupEnv
-  getCurrentTime = liftIO IO.getCurrentTime
-  getCurrentTimeZone = liftIO IO.getCurrentTimeZone
-  newStdGen = liftIO IO.newStdGen
-  newUniqueHash = hashUnique <$> liftIO IO.newUnique
-
-  openURL u
-   | Just u'' <- stripPrefix "data:" u = do
-       let mime     = takeWhile (/=',') u''
-       let contents = UTF8.fromString $
-                       unEscapeString $ drop 1 $ dropWhile (/=',') u''
-       return (decodeLenient contents, Just mime)
-   | otherwise = do
-       let toReqHeader (n, v) = (CI.mk (UTF8.fromString n), UTF8.fromString v)
-       customHeaders <- map toReqHeader <$> getsCommonState stRequestHeaders
-       report $ Fetching u
-       res <- liftIO $ E.try $ withSocketsDo $ do
-         let parseReq = parseRequest
-         proxy <- tryIOError (getEnv "http_proxy")
-         let addProxy' x = case proxy of
-                              Left _ -> return x
-                              Right pr -> parseReq pr >>= \r ->
-                                  return (addProxy (host r) (port r) x)
-         req <- parseReq u >>= addProxy'
-         let req' = req{requestHeaders = customHeaders ++ requestHeaders req}
-         resp <- newManager tlsManagerSettings >>= httpLbs req'
-         return (B.concat $ toChunks $ responseBody resp,
-                 UTF8.toString `fmap` lookup hContentType (responseHeaders resp))
-
-       case res of
-            Right r -> return r
-            Left e  -> throwError $ PandocHttpError u e
-
-  readFileLazy s = liftIOError BL.readFile s
-  readFileStrict s = liftIOError B.readFile s
-
-  glob = liftIOError IO.glob
-  fileExists = liftIOError Directory.doesFileExist
-#ifdef EMBED_DATA_FILES
-  getDataFileName = return
-#else
-  getDataFileName = liftIOError Paths.getDataFileName
-#endif
-  getModificationTime = liftIOError IO.getModificationTime
-  getCommonState = PandocIO $ lift get
-  putCommonState x = PandocIO $ lift $ put x
-  logOutput msg = liftIO $ do
-    UTF8.hPutStr stderr $
-        "[" ++ show (messageVerbosity msg) ++ "] "
-    alertIndent $ lines $ showLogMessage msg
-
-alertIndent :: [String] -> IO ()
-alertIndent [] = return ()
-alertIndent (l:ls) = do
-  UTF8.hPutStrLn stderr l
-  mapM_ go ls
-  where go l' = do UTF8.hPutStr stderr "  "
-                   UTF8.hPutStrLn stderr l'
-
--- | Specialized version of parseURIReference that disallows
--- single-letter schemes.  Reason:  these are usually windows absolute
--- paths.
-parseURIReference' :: String -> Maybe URI
-parseURIReference' s =
-  case parseURIReference s of
-       Just u
-         | length (uriScheme u) > 2  -> Just u
-         | null (uriScheme u)        -> Just u  -- protocol-relative
-       _                             -> Nothing
-
--- | Set the user data directory in common state.
-setUserDataDir :: PandocMonad m
-               => Maybe FilePath
-               -> m ()
-setUserDataDir mbfp = modifyCommonState $ \st -> st{ stUserDataDir = mbfp }
-
--- | Get the user data directory from common state.
-getUserDataDir :: PandocMonad m
-               => m (Maybe FilePath)
-getUserDataDir = getsCommonState stUserDataDir
-
--- | Fetch an image or other item from the local filesystem or the net.
--- Returns raw content and maybe mime type.
-fetchItem :: PandocMonad m
-          => String
-          -> m (B.ByteString, Maybe MimeType)
-fetchItem s = do
-  mediabag <- getMediaBag
-  case lookupMedia s mediabag of
-    Just (mime, bs) -> return (BL.toStrict bs, Just mime)
-    Nothing -> downloadOrRead s
-
-downloadOrRead :: PandocMonad m
-               => String
-               -> m (B.ByteString, Maybe MimeType)
-downloadOrRead s = do
-  sourceURL <- getsCommonState stSourceURL
-  case (sourceURL >>= parseURIReference' .
-                       ensureEscaped, ensureEscaped s) of
-    (Just u, s') -> -- try fetching from relative path at source
-       case parseURIReference' s' of
-            Just u' -> openURL $ show $ u' `nonStrictRelativeTo` u
-            Nothing -> openURL s' -- will throw error
-    (Nothing, s'@('/':'/':_)) ->  -- protocol-relative URI
-       case parseURIReference' s' of
-            Just u' -> openURL $ show $ u' `nonStrictRelativeTo` httpcolon
-            Nothing -> openURL s' -- will throw error
-    (Nothing, s') ->
-       case parseURI s' of  -- requires absolute URI
-            -- We don't want to treat C:/ as a scheme:
-            Just u' | length (uriScheme u') > 2 -> openURL (show u')
-            Just u' | uriScheme u' == "file:" ->
-                 readLocalFile $ dropWhile (=='/') (uriPath u')
-            _ -> readLocalFile fp -- get from local file system
-   where readLocalFile f = do
-             resourcePath <- getResourcePath
-             cont <- if isRelative f
-                        then withPaths resourcePath readFileStrict f
-                        else readFileStrict f
-             return (cont, mime)
-         httpcolon = URI{ uriScheme = "http:",
-                          uriAuthority = Nothing,
-                          uriPath = "",
-                          uriQuery = "",
-                          uriFragment = "" }
-         dropFragmentAndQuery = takeWhile (\c -> c /= '?' && c /= '#')
-         fp = unEscapeString $ dropFragmentAndQuery s
-         mime = case takeExtension fp of
-                     ".gz" -> getMimeType $ dropExtension fp
-                     ".svgz" -> getMimeType $ dropExtension fp ++ ".svg"
-                     x     -> getMimeType x
-         ensureEscaped = escapeURIString isAllowedInURI . map convertSlash
-         convertSlash '\\' = '/'
-         convertSlash x    = x
-
--- Retrieve default reference.docx.
-getDefaultReferenceDocx :: PandocMonad m => m Archive
-getDefaultReferenceDocx = do
-  let paths = ["[Content_Types].xml",
-               "_rels/.rels",
-               "docProps/app.xml",
-               "docProps/core.xml",
-               "word/document.xml",
-               "word/fontTable.xml",
-               "word/footnotes.xml",
-               "word/comments.xml",
-               "word/numbering.xml",
-               "word/settings.xml",
-               "word/webSettings.xml",
-               "word/styles.xml",
-               "word/_rels/document.xml.rels",
-               "word/_rels/footnotes.xml.rels",
-               "word/theme/theme1.xml"]
-  let toLazy = BL.fromChunks . (:[])
-  let pathToEntry path = do
-        epochtime <- (floor . utcTimeToPOSIXSeconds) <$> getCurrentTime
-        contents <- toLazy <$> readDataFile ("docx/" ++ path)
-        return $ toEntry path epochtime contents
-  datadir <- getUserDataDir
-  mbArchive <- case datadir of
-                    Nothing   -> return Nothing
-                    Just d    -> do
-                       exists <- fileExists (d </> "reference.docx")
-                       if exists
-                          then return (Just (d </> "reference.docx"))
-                          else return Nothing
-  case mbArchive of
-     Just arch -> toArchive <$> readFileLazy arch
-     Nothing   -> foldr addEntryToArchive emptyArchive <$>
-                     mapM pathToEntry paths
-
--- Retrieve default reference.odt.
-getDefaultReferenceODT :: PandocMonad m => m Archive
-getDefaultReferenceODT = do
-  let paths = ["mimetype",
-               "manifest.rdf",
-               "styles.xml",
-               "content.xml",
-               "meta.xml",
-               "settings.xml",
-               "Configurations2/accelerator/current.xml",
-               "Thumbnails/thumbnail.png",
-               "META-INF/manifest.xml"]
-  let pathToEntry path = do epochtime <- floor `fmap` getPOSIXTime
-                            contents <- (BL.fromChunks . (:[])) `fmap`
-                                          readDataFile ("odt/" ++ path)
-                            return $ toEntry path epochtime contents
-  datadir <- getUserDataDir
-  mbArchive <- case datadir of
-                    Nothing   -> return Nothing
-                    Just d    -> do
-                       exists <- fileExists (d </> "reference.odt")
-                       if exists
-                          then return (Just (d </> "reference.odt"))
-                          else return Nothing
-  case mbArchive of
-     Just arch -> toArchive <$> readFileLazy arch
-     Nothing   -> foldr addEntryToArchive emptyArchive <$>
-                     mapM pathToEntry paths
-
-getDefaultReferencePptx :: PandocMonad m => m Archive
-getDefaultReferencePptx = do
-  -- We're going to narrow this down substantially once we get it
-  -- working.
-  let paths = [ "[Content_Types].xml"
-              , "_rels/.rels"
-              , "docProps/app.xml"
-              , "docProps/core.xml"
-              , "ppt/_rels/presentation.xml.rels"
-              , "ppt/presProps.xml"
-              , "ppt/presentation.xml"
-              , "ppt/slideLayouts/_rels/slideLayout1.xml.rels"
-              , "ppt/slideLayouts/_rels/slideLayout2.xml.rels"
-              , "ppt/slideLayouts/_rels/slideLayout3.xml.rels"
-              , "ppt/slideLayouts/_rels/slideLayout4.xml.rels"
-              , "ppt/slideLayouts/_rels/slideLayout5.xml.rels"
-              , "ppt/slideLayouts/_rels/slideLayout6.xml.rels"
-              , "ppt/slideLayouts/_rels/slideLayout7.xml.rels"
-              , "ppt/slideLayouts/_rels/slideLayout8.xml.rels"
-              , "ppt/slideLayouts/_rels/slideLayout9.xml.rels"
-              , "ppt/slideLayouts/_rels/slideLayout10.xml.rels"
-              , "ppt/slideLayouts/_rels/slideLayout11.xml.rels"
-              , "ppt/slideLayouts/slideLayout1.xml"
-              , "ppt/slideLayouts/slideLayout10.xml"
-              , "ppt/slideLayouts/slideLayout11.xml"
-              , "ppt/slideLayouts/slideLayout2.xml"
-              , "ppt/slideLayouts/slideLayout3.xml"
-              , "ppt/slideLayouts/slideLayout4.xml"
-              , "ppt/slideLayouts/slideLayout5.xml"
-              , "ppt/slideLayouts/slideLayout6.xml"
-              , "ppt/slideLayouts/slideLayout7.xml"
-              , "ppt/slideLayouts/slideLayout8.xml"
-              , "ppt/slideLayouts/slideLayout9.xml"
-              , "ppt/slideMasters/_rels/slideMaster1.xml.rels"
-              , "ppt/slideMasters/slideMaster1.xml"
-              , "ppt/slides/_rels/slide1.xml.rels"
-              , "ppt/slides/slide1.xml"
-              , "ppt/slides/_rels/slide2.xml.rels"
-              , "ppt/slides/slide2.xml"
-              , "ppt/tableStyles.xml"
-              , "ppt/theme/theme1.xml"
-              , "ppt/viewProps.xml"
-              ]
-  let toLazy = BL.fromChunks . (:[])
-  let pathToEntry path = do
-        epochtime <- (floor . utcTimeToPOSIXSeconds) <$> getCurrentTime
-        contents <- toLazy <$> readDataFile ("pptx/" ++ path)
-        return $ toEntry path epochtime contents
-  datadir <- getUserDataDir
-  mbArchive <- case datadir of
-                    Nothing   -> return Nothing
-                    Just d    -> do
-                       exists <- fileExists (d </> "reference.pptx")
-                       if exists
-                          then return (Just (d </> "reference.pptx"))
-                          else return Nothing
-  case mbArchive of
-     Just arch -> toArchive <$> readFileLazy arch
-     Nothing   -> foldr addEntryToArchive emptyArchive <$>
-                     mapM pathToEntry paths
-
-
--- | Read file from user data directory or,
--- if not found there, from Cabal data directory.
-readDataFile :: PandocMonad m => FilePath -> m B.ByteString
-readDataFile fname = do
-  datadir <- getUserDataDir
-  case datadir of
-       Nothing -> readDefaultDataFile fname
-       Just userDir -> do
-         exists <- fileExists (userDir </> fname)
-         if exists
-            then readFileStrict (userDir </> fname)
-            else readDefaultDataFile fname
-
--- | Read file from from Cabal data directory.
-readDefaultDataFile :: PandocMonad m => FilePath -> m B.ByteString
-readDefaultDataFile "reference.docx" =
-  (B.concat . BL.toChunks . fromArchive) <$> getDefaultReferenceDocx
-readDefaultDataFile "reference.pptx" =
-  (B.concat . BL.toChunks . fromArchive) <$> getDefaultReferencePptx
-readDefaultDataFile "reference.odt" =
-  (B.concat . BL.toChunks . fromArchive) <$> getDefaultReferenceODT
-readDefaultDataFile fname =
-#ifdef EMBED_DATA_FILES
-  case lookup (makeCanonical fname) dataFiles of
-    Nothing       -> throwError $ PandocCouldNotFindDataFileError fname
-    Just contents -> return contents
-#else
-  getDataFileName fname' >>= checkExistence >>= readFileStrict
-    where fname' = if fname == "MANUAL.txt" then fname else "data" </> fname
-
-checkExistence :: PandocMonad m => FilePath -> m FilePath
-checkExistence fn = do
-  exists <- fileExists fn
-  if exists
-     then return fn
-     else throwError $ PandocCouldNotFindDataFileError fn
-#endif
-
-makeCanonical :: FilePath -> FilePath
-makeCanonical = Posix.joinPath . transformPathParts . splitDirectories
- where  transformPathParts = reverse . foldl go []
-        go as     "."  = as
-        go (_:as) ".." = as
-        go as     x    = x : as
-
-withPaths :: PandocMonad m => [FilePath] -> (FilePath -> m a) -> FilePath -> m a
-withPaths [] _ fp = throwError $ PandocResourceNotFound fp
-withPaths (p:ps) action fp =
-  catchError (action (p </> fp))
-             (\_ -> withPaths ps action fp)
-
--- | Fetch local or remote resource (like an image) and provide data suitable
--- for adding it to the MediaBag.
-fetchMediaResource :: PandocMonad m
-              => String -> m (FilePath, Maybe MimeType, BL.ByteString)
-fetchMediaResource src = do
-  (bs, mt) <- downloadOrRead src
-  let ext = fromMaybe (takeExtension src)
-                      (mt >>= extensionFromMimeType)
-  let bs' = BL.fromChunks [bs]
-  let basename = showDigest $ sha1 bs'
-  let fname = basename <.> ext
-  return (fname, mt, bs')
-
--- | Traverse tree, filling media bag for any images that
--- aren't already in the media bag.
-fillMediaBag :: PandocMonad m => Pandoc -> m Pandoc
-fillMediaBag d = walkM handleImage d
-  where handleImage :: PandocMonad m => Inline -> m Inline
-        handleImage (Image attr lab (src, tit)) = catchError
-          (do mediabag <- getMediaBag
-              case lookupMedia src mediabag of
-                Just (_, _) -> return $ Image attr lab (src, tit)
-                Nothing -> do
-                  (fname, mt, bs) <- fetchMediaResource src
-                  insertMedia fname mt bs
-                  return $ Image attr lab (fname, tit))
-          (\e ->
-              case e of
-                PandocResourceNotFound _ -> do
-                  report $ CouldNotFetchResource src
-                            "replacing image with description"
-                  -- emit alt text
-                  return $ Span ("",["image"],[]) lab
-                PandocHttpError u er -> do
-                  report $ CouldNotFetchResource u
-                            (show er ++ "\rReplacing image with description.")
-                  -- emit alt text
-                  return $ Span ("",["image"],[]) lab
-                _ -> throwError e)
-        handleImage x = return x
-
--- | Extract media from the mediabag into a directory.
-extractMedia :: FilePath -> Pandoc -> PandocIO Pandoc
-extractMedia dir d = do
-  media <- getMediaBag
-  case [fp | (fp, _, _) <- mediaDirectory media] of
-        []  -> return d
-        fps -> do
-          mapM_ (writeMedia dir media) fps
-          return $ walk (adjustImagePath dir fps) d
-
--- Write the contents of a media bag to a path.
-writeMedia :: FilePath -> MediaBag -> FilePath -> PandocIO ()
-writeMedia dir mediabag subpath = do
-  -- we join and split to convert a/b/c to a\b\c on Windows;
-  -- in zip containers all paths use /
-  let fullpath = dir </> normalise subpath
-  let mbcontents = lookupMedia subpath mediabag
-  case mbcontents of
-       Nothing -> throwError $ PandocResourceNotFound subpath
-       Just (_, bs) -> do
-         report $ Extracting fullpath
-         liftIOError (createDirectoryIfMissing True) (takeDirectory fullpath)
-         liftIOError (\p -> BL.writeFile p bs) fullpath
-
-adjustImagePath :: FilePath -> [FilePath] -> Inline -> Inline
-adjustImagePath dir paths (Image attr lab (src, tit))
-   | src `elem` paths = Image attr lab (dir ++ "/" ++ src, tit)
-adjustImagePath _ _ x = x
-
--- | The 'PureState' contains ersatz representations
--- of things that would normally be obtained through IO.
-data PureState = PureState { stStdGen     :: StdGen
-                           , stWord8Store :: [Word8] -- should be
-                                                     -- inifinite,
-                                                     -- i.e. [1..]
-                           , stUniqStore  :: [Int] -- should be
-                                                   -- inifinite and
-                                                   -- contain every
-                                                   -- element at most
-                                                   -- once, e.g. [1..]
-                           , stEnv :: [(String, String)]
-                           , stTime :: UTCTime
-                           , stTimeZone :: TimeZone
-                           , stReferenceDocx :: Archive
-                           , stReferencePptx :: Archive
-                           , stReferenceODT :: Archive
-                           , stFiles :: FileTree
-                           , stUserDataFiles :: FileTree
-                           , stCabalDataFiles :: FileTree
-                           }
-
-instance Default PureState where
-  def = PureState { stStdGen = mkStdGen 1848
-                  , stWord8Store = [1..]
-                  , stUniqStore = [1..]
-                  , stEnv = [("USER", "pandoc-user")]
-                  , stTime = posixSecondsToUTCTime 0
-                  , stTimeZone = utc
-                  , stReferenceDocx = emptyArchive
-                  , stReferencePptx = emptyArchive
-                  , stReferenceODT = emptyArchive
-                  , stFiles = mempty
-                  , stUserDataFiles = mempty
-                  , stCabalDataFiles = mempty
-                  }
-
-
-getPureState :: PandocPure PureState
-getPureState = PandocPure $ lift $ lift get
-
-getsPureState :: (PureState -> a) -> PandocPure a
-getsPureState f = f <$> getPureState
-
-putPureState :: PureState -> PandocPure ()
-putPureState ps= PandocPure $ lift $ lift $ put ps
-
-modifyPureState :: (PureState -> PureState) -> PandocPure ()
-modifyPureState f = PandocPure $ lift $ lift $ modify f
-
-
-data FileInfo = FileInfo { infoFileMTime :: UTCTime
-                         , infoFileContents :: B.ByteString
-                         }
-
-newtype FileTree = FileTree {unFileTree :: M.Map FilePath FileInfo}
-  deriving (Monoid)
-
-getFileInfo :: FilePath -> FileTree -> Maybe FileInfo
-getFileInfo fp tree =
-  M.lookup (makeCanonical fp) (unFileTree tree)
-
--- | Add the specified file to the FileTree. If file
--- is a directory, add its contents recursively.
-addToFileTree :: FileTree -> FilePath -> IO FileTree
-addToFileTree tree fp = do
-  isdir <- doesDirectoryExist fp
-  if isdir
-     then do -- recursively add contents of directories
-       let isSpecial ".." = True
-           isSpecial "."  = True
-           isSpecial _    = False
-       fs <- (map (fp </>) . filter (not . isSpecial)) <$> getDirectoryContents fp
-       foldM addToFileTree tree fs
-     else do
-       contents <- B.readFile fp
-       mtime <- IO.getModificationTime fp
-       return $ insertInFileTree fp FileInfo{ infoFileMTime = mtime
-                                            , infoFileContents = contents } tree
-
--- | Insert an ersatz file into the 'FileTree'.
-insertInFileTree :: FilePath -> FileInfo -> FileTree -> FileTree
-insertInFileTree fp info (FileTree treemap) =
-  FileTree $ M.insert (makeCanonical fp) info treemap
-
-newtype PandocPure a = PandocPure {
-  unPandocPure :: ExceptT PandocError
-                  (StateT CommonState (State PureState)) a
-  } deriving ( Functor
-             , Applicative
-             , Monad
-             , MonadError PandocError
-             )
-
--- Run a 'PandocPure' operation.
-runPure :: PandocPure a -> Either PandocError a
-runPure x = flip evalState def $
-            flip evalStateT def $
-            runExceptT $
-            unPandocPure x
-
-instance PandocMonad PandocPure where
-  lookupEnv s = do
-    env <- getsPureState stEnv
-    return (lookup s env)
-
-  getCurrentTime = getsPureState stTime
-
-  getCurrentTimeZone = getsPureState stTimeZone
-
-  newStdGen = do
-    g <- getsPureState stStdGen
-    let (_, nxtGen) = next g
-    modifyPureState $ \st -> st { stStdGen = nxtGen }
-    return g
-
-  newUniqueHash = do
-    uniqs <- getsPureState stUniqStore
-    case uniqs of
-      u : us -> do
-        modifyPureState $ \st -> st { stUniqStore = us }
-        return u
-      _ -> M.fail "uniq store ran out of elements"
-  openURL u = throwError $ PandocResourceNotFound u
-  readFileLazy fp = do
-    fps <- getsPureState stFiles
-    case infoFileContents <$> getFileInfo fp fps of
-      Just bs -> return (BL.fromStrict bs)
-      Nothing -> throwError $ PandocResourceNotFound fp
-  readFileStrict fp = do
-    fps <- getsPureState stFiles
-    case infoFileContents <$> getFileInfo fp fps of
-      Just bs -> return bs
-      Nothing -> throwError $ PandocResourceNotFound fp
-
-  glob s = do
-    FileTree ftmap <- getsPureState stFiles
-    return $ filter (match (compile s)) $ M.keys ftmap
-
-  fileExists fp = do
-    fps <- getsPureState stFiles
-    case getFileInfo fp fps of
-         Nothing -> return False
-         Just _  -> return True
-
-  getDataFileName fp = return $ "data/" ++ fp
-
-  getModificationTime fp = do
-    fps <- getsPureState stFiles
-    case infoFileMTime <$> getFileInfo fp fps of
-      Just tm -> return tm
-      Nothing -> throwError $ PandocIOError fp
-                    (userError "Can't get modification time")
-
-  getCommonState = PandocPure $ lift get
-  putCommonState x = PandocPure $ lift $ put x
-
-  logOutput _msg = return ()
-
--- This requires UndecidableInstances.  We could avoid that
--- by repeating the definitions below for every monad transformer
--- we use: ReaderT, WriterT, StateT, RWST.  But this seems to
--- be harmless.
-instance (MonadTrans t, PandocMonad m, Functor (t m),
-          MonadError PandocError (t m), Monad (t m),
-          Applicative (t m)) => PandocMonad (t m) where
-  lookupEnv = lift . lookupEnv
-  getCurrentTime = lift getCurrentTime
-  getCurrentTimeZone = lift getCurrentTimeZone
-  newStdGen = lift newStdGen
-  newUniqueHash = lift newUniqueHash
-  openURL = lift . openURL
-  readFileLazy = lift . readFileLazy
-  readFileStrict = lift . readFileStrict
-  glob = lift . glob
-  fileExists = lift . fileExists
-  getDataFileName = lift . getDataFileName
-  getModificationTime = lift . getModificationTime
-  getCommonState = lift getCommonState
-  putCommonState = lift . putCommonState
-  logOutput = lift . logOutput
-
-#if MIN_VERSION_base(4,8,0)
-instance {-# OVERLAPS #-} PandocMonad m => PandocMonad (ParsecT s st m) where
-#else
-instance PandocMonad m => PandocMonad (ParsecT s st m) where
-#endif
-  lookupEnv = lift . lookupEnv
-  getCurrentTime = lift getCurrentTime
-  getCurrentTimeZone = lift getCurrentTimeZone
-  newStdGen = lift newStdGen
-  newUniqueHash = lift newUniqueHash
-  openURL = lift . openURL
-  readFileLazy = lift . readFileLazy
-  readFileStrict = lift . readFileStrict
-  glob = lift . glob
-  fileExists = lift . fileExists
-  getDataFileName = lift . getDataFileName
-  getModificationTime = lift . getModificationTime
-  getCommonState = lift getCommonState
-  putCommonState = lift . putCommonState
-  trace msg = do
-    tracing <- getsCommonState stTrace
-    when tracing $ do
-      pos <- getPosition
-      Debug.Trace.trace
-        ("[trace] Parsed " ++ msg ++ " at line " ++
-            show (sourceLine pos) ++
-            if sourceName pos == "chunk"
-               then " of chunk"
-               else "")
-        (return ())
-  logOutput = lift . logOutput
+{- |
+   Module      : Text.Pandoc.Class
+   Copyright   : Copyright (C) 2016-2020 Jesse Rosenthal, John MacFarlane
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : Jesse Rosenthal <jrosenthal@jhu.edu>
+   Stability   : alpha
+   Portability : portable
+
+This module defines a type class, 'PandocMonad', for pandoc readers
+and writers. A pure instance 'PandocPure' and an impure instance
+'PandocIO' are provided.  This allows users of the library to choose
+whether they want conversions to perform IO operations (such as
+reading include files or images).
+-}
+
+module Text.Pandoc.Class
+  ( module Text.Pandoc.Class.CommonState
+  , module Text.Pandoc.Class.PandocIO
+  , module Text.Pandoc.Class.PandocMonad
+  , module Text.Pandoc.Class.PandocPure
+  , module Text.Pandoc.Class.Sandbox
+  , Translations
+  ) where
+
+-- We export CommonState as an opaque object.  Accessors for
+-- its fields are provided in Text.Pandoc.Class.PandocMonad.
+import Text.Pandoc.Class.CommonState (CommonState)
+import Text.Pandoc.Class.PandocMonad
+import Text.Pandoc.Class.PandocIO
+import Text.Pandoc.Class.PandocPure
+import Text.Pandoc.Translations.Types (Translations)
+import Text.Pandoc.Class.Sandbox
diff --git a/src/Text/Pandoc/Class/CommonState.hs b/src/Text/Pandoc/Class/CommonState.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Class/CommonState.hs
@@ -0,0 +1,95 @@
+{-# LANGUAGE CPP #-}
+{- |
+Module      : Text.Pandoc.Class.CommonState
+Copyright   : Copyright (C) 2016-2020 Jesse Rosenthal, John MacFarlane
+License     : GNU GPL, version 2 or above
+
+Maintainer  : Jesse Rosenthal <jrosenthal@jhu.edu>
+Stability   : alpha
+Portability : portable
+
+Common state shared by all pandoc-specific operations, including
+those in readers, writers, and Lua filters.
+-}
+
+module Text.Pandoc.Class.CommonState
+  ( CommonState(..)
+  , defaultCommonState
+  )
+where
+
+import Data.Default (Default (def))
+import Data.Text (Text)
+import Text.Collate.Lang (Lang)
+import Text.Pandoc.MediaBag (MediaBag)
+import Text.Pandoc.Logging (LogMessage, Verbosity (WARNING))
+import Text.Pandoc.Translations.Types (Translations)
+#ifdef PANDOC_HTTP_SUPPORT
+import Network.HTTP.Client (Manager)
+#endif
+
+-- | 'CommonState' represents state that is used by all
+-- instances of 'PandocMonad'.  Normally users should not
+-- need to interact with it directly; instead, auxiliary
+-- functions like 'setVerbosity' and 'withMediaBag' should be used.
+data CommonState = CommonState
+  { stLog          :: [LogMessage]
+    -- ^ A list of log messages in reverse order
+  , stUserDataDir  :: Maybe FilePath
+    -- ^ Directory to search for data files
+  , stSourceURL    :: Maybe Text
+    -- ^ Absolute URL + dir of 1st source file
+  , stRequestHeaders :: [(Text, Text)]
+    -- ^ Headers to add for HTTP requests
+  , stNoCheckCertificate :: Bool
+    -- ^ Controls whether certificate validation is disabled
+  , stMediaBag     :: MediaBag
+    -- ^ Media parsed from binary containers
+  , stTranslations :: Maybe (Lang, Maybe Translations)
+    -- ^ Translations for localization
+  , stInputFiles   :: [FilePath]
+    -- ^ List of input files from command line
+  , stOutputFile   :: Maybe FilePath
+    -- ^ Output file from command line
+  , stResourcePath :: [FilePath]
+    -- ^ Path to search for resources like
+    -- included images
+#ifdef PANDOC_HTTP_SUPPORT
+  , stManager      :: Maybe Manager
+    -- ^ Manager for HTTP client; this needs to persist across many requests
+    -- for efficiency.
+#endif
+  , stVerbosity    :: Verbosity
+    -- ^ Verbosity level
+  , stTrace        :: Bool
+    -- ^ Controls whether tracing messages are
+    -- issued.
+  }
+
+-- | The default @'CommonState'@. All fields are initialized as the
+-- monoid identity of their resprective type, except for:
+--
+--   * @'stResourcePath'@, which is set to @["."]@,
+--   * @'stTrace'@, which is set to @'False'@, and
+--   * @'stVerbosity'@, which is set to @WARNING@.
+defaultCommonState :: CommonState
+defaultCommonState = CommonState
+  { stLog = []
+  , stUserDataDir = Nothing
+  , stSourceURL = Nothing
+  , stRequestHeaders = []
+  , stNoCheckCertificate = False
+  , stMediaBag = mempty
+  , stTranslations = Nothing
+  , stInputFiles = []
+  , stOutputFile = Nothing
+  , stResourcePath = ["."]
+#ifdef PANDOC_HTTP_SUPPORT
+  , stManager = Nothing
+#endif
+  , stVerbosity = WARNING
+  , stTrace = False
+  }
+
+instance Default CommonState where
+  def = defaultCommonState
diff --git a/src/Text/Pandoc/Class/IO.hs b/src/Text/Pandoc/Class/IO.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Class/IO.hs
@@ -0,0 +1,296 @@
+{-# LANGUAGE CPP #-}
+{-# LANGUAGE ScopedTypeVariables #-}
+{-# LANGUAGE OverloadedStrings #-}
+{- |
+Module      : Text.Pandoc.Class.IO
+Copyright   : Copyright (C) 2016-2020 Jesse Rosenthal, John MacFarlane
+License     : GNU GPL, version 2 or above
+
+Maintainer  : Jesse Rosenthal <jrosenthal@jhu.edu>
+Stability   : alpha
+Portability : portable
+
+Default ways to perform @'PandocMonad'@ actions in a @'MonadIO'@ type.
+
+These functions are used to make the @'PandocIO'@ type an instance of
+@'PandocMonad'@, but can be reused for any other MonadIO-conforming
+types.
+-}
+module Text.Pandoc.Class.IO
+  ( fileExists
+  , getCurrentTime
+  , getCurrentTimeZone
+  , getDataFileName
+  , getModificationTime
+  , glob
+  , logOutput
+  , logIOError
+  , lookupEnv
+  , newStdGen
+  , newUniqueHash
+  , openURL
+  , readFileLazy
+  , readFileStrict
+  , readStdinStrict
+  , extractMedia
+  , writeMedia
+ ) where
+
+import Control.Monad.Except (throwError)
+import Control.Monad.IO.Class (MonadIO, liftIO)
+import Data.Text (Text, pack, unpack)
+import Data.Time (TimeZone, UTCTime)
+import Data.Unique (hashUnique)
+#ifdef PANDOC_HTTP_SUPPORT
+import Data.ByteString.Lazy (toChunks)
+import System.Environment (getEnv)
+import Data.Default (def)
+import Network.Connection (TLSSettings(..))
+import qualified Network.TLS as TLS
+import qualified Network.TLS.Extra as TLS
+import System.X509 (getSystemCertificateStore)
+import Network.HTTP.Client
+       (httpLbs, Manager, responseBody, responseHeaders,
+        Request(port, host, requestHeaders), parseUrlThrow, newManager, HttpException)
+import Network.HTTP.Client.Internal (addProxy)
+import Network.HTTP.Client.TLS (mkManagerSettings)
+import Network.HTTP.Types.Header ( hContentType )
+import Network.Socket (withSocketsDo)
+import Text.Pandoc.Class.CommonState (CommonState (..))
+import Text.Pandoc.Class.PandocMonad ( getsCommonState, modifyCommonState )
+import qualified Data.CaseInsensitive as CI
+#endif
+import Network.URI (URI(..), parseURI, unEscapeString)
+import System.Directory (createDirectoryIfMissing)
+import System.FilePath ((</>), takeDirectory, takeFileName, normalise, takeExtension)
+import qualified System.FilePath.Posix as Posix
+import System.IO (stderr)
+import System.IO.Error
+import System.Random (StdGen)
+import Text.Pandoc.Class.PandocMonad
+       (PandocMonad,
+        getMediaBag, report, extractURIData)
+import Text.Pandoc.Definition (Pandoc, Inline (Image))
+import Text.Pandoc.Error (PandocError (..))
+import Text.Pandoc.Logging (LogMessage (..), messageVerbosity, showLogMessage)
+import Text.Pandoc.MIME (MimeType)
+import Text.Pandoc.MediaBag (MediaBag, MediaItem(..), lookupMedia, mediaItems)
+import Text.Pandoc.Walk (walk)
+import qualified Control.Exception as E
+import qualified Data.ByteString as B
+import qualified Data.ByteString.Lazy as BL
+import qualified Data.Text as T
+import qualified Data.Time
+import qualified Data.Time.LocalTime
+import qualified Data.Unique
+import qualified System.Directory
+import qualified System.Environment as Env
+import qualified System.FilePath.Glob
+import qualified System.Random
+import qualified Text.Pandoc.UTF8 as UTF8
+import Codec.Archive.Zip
+#ifndef EMBED_DATA_FILES
+import qualified Paths_pandoc as Paths
+#endif
+
+-- | Utility function to lift IO errors into 'PandocError's.
+liftIOError :: (PandocMonad m, MonadIO m) => (String -> IO a) -> String -> m a
+liftIOError f u = do
+  res <- liftIO $ tryIOError $ f u
+  case res of
+         Left e  -> throwError $ PandocIOError (pack u) e
+         Right r -> return r
+
+-- | Show potential IO errors to the user continuing execution anyway
+logIOError :: (PandocMonad m, MonadIO m) => IO () -> m ()
+logIOError f = do
+  res <- liftIO $ tryIOError f
+  case res of
+    Left e -> report $ IgnoredIOError $ pack $ E.displayException e
+    Right _ -> pure ()
+
+-- | Lookup an environment variable in the programs environment.
+lookupEnv :: MonadIO m => Text -> m (Maybe Text)
+lookupEnv = fmap (fmap pack) . liftIO . Env.lookupEnv . unpack
+
+-- | Get the current (UTC) time.
+getCurrentTime :: MonadIO m => m UTCTime
+getCurrentTime = liftIO Data.Time.getCurrentTime
+
+-- | Get the locale's time zone.
+getCurrentTimeZone :: MonadIO m => m TimeZone
+getCurrentTimeZone = liftIO Data.Time.LocalTime.getCurrentTimeZone
+
+-- | Return a new generator for random numbers.
+newStdGen :: MonadIO m => m StdGen
+newStdGen = liftIO System.Random.newStdGen
+
+-- | Return a new unique integer.
+newUniqueHash :: MonadIO m => m Int
+newUniqueHash = hashUnique <$> liftIO Data.Unique.newUnique
+
+#ifdef PANDOC_HTTP_SUPPORT
+getManager :: (PandocMonad m, MonadIO m) => m Manager
+getManager = do
+  mbManager <- getsCommonState stManager
+  disableCertificateValidation <- getsCommonState stNoCheckCertificate
+  case mbManager of
+    Just manager -> pure manager
+    Nothing -> do
+      manager <- liftIO $ do
+        certificateStore <- getSystemCertificateStore
+        let tlsSettings = TLSSettings $
+               (TLS.defaultParamsClient "localhost.localdomain" "80")
+                  { TLS.clientSupported = def{ TLS.supportedCiphers =
+                                               TLS.ciphersuite_default
+                                             , TLS.supportedExtendedMainSecret =
+                                                TLS.AllowEMS }
+                  , TLS.clientShared = def
+                      { TLS.sharedCAStore = certificateStore
+                      , TLS.sharedValidationCache =
+                          if disableCertificateValidation
+                             then TLS.ValidationCache
+                                   (\_ _ _ -> return TLS.ValidationCachePass)
+                                   (\_ _ _ -> return ())
+                             else def
+                      }
+                  }
+        let tlsManagerSettings = mkManagerSettings tlsSettings  Nothing
+        newManager tlsManagerSettings
+      modifyCommonState $ \st -> st{ stManager = Just manager }
+      pure manager
+#endif
+
+openURL :: (PandocMonad m, MonadIO m) => Text -> m (B.ByteString, Maybe MimeType)
+openURL u
+ | Just (URI{ uriScheme = "data:",
+              uriPath = upath }) <- parseURI (T.unpack u)
+     = pure $ extractURIData upath
+#ifdef PANDOC_HTTP_SUPPORT
+ | otherwise = do
+     let toReqHeader (n, v) = (CI.mk (UTF8.fromText n), UTF8.fromText v)
+     customHeaders <- map toReqHeader <$> getsCommonState stRequestHeaders
+     report $ Fetching u
+     manager <- getManager
+     res <- liftIO $ E.try $ withSocketsDo $ do
+       proxy <- tryIOError (getEnv "http_proxy")
+       let addProxy' x = case proxy of
+                            Left _ -> return x
+                            Right pr -> parseUrlThrow pr >>= \r ->
+                                return (addProxy (host r) (port r) x)
+       req <- parseUrlThrow (unpack u) >>= addProxy'
+       let req' = req{requestHeaders = customHeaders ++ requestHeaders req}
+       resp <- httpLbs req' manager
+       return (B.concat $ toChunks $ responseBody resp,
+               UTF8.toText `fmap` lookup hContentType (responseHeaders resp))
+
+     case res of
+          Right r -> return r
+          Left (e :: HttpException)
+                  -> throwError $ PandocHttpError u (T.pack (show e))
+#else
+ | otherwise =
+     throwError $ PandocHttpError u "pandoc was compiled without HTTP support"
+#endif
+
+-- | Read the lazy ByteString contents from a file path, raising an error on
+-- failure.
+readFileLazy :: (PandocMonad m, MonadIO m) => FilePath -> m BL.ByteString
+readFileLazy s = liftIOError BL.readFile s
+
+-- | Read the strict ByteString contents from a file path,
+-- raising an error on failure.
+readFileStrict :: (PandocMonad m, MonadIO m) => FilePath -> m B.ByteString
+readFileStrict s = liftIOError B.readFile s
+
+-- | Read the strict ByteString contents from stdin, raising
+-- an error on failure.
+readStdinStrict :: (PandocMonad m, MonadIO m) => m B.ByteString
+readStdinStrict = liftIOError (const B.getContents) "stdin"
+
+-- | Return a list of paths that match a glob, relative to the working
+-- directory. See 'System.FilePath.Glob' for the glob syntax.
+glob :: (PandocMonad m, MonadIO m) => String -> m [FilePath]
+glob = liftIOError System.FilePath.Glob.glob
+
+-- | Returns True if file exists.
+fileExists :: (PandocMonad m, MonadIO m) => FilePath -> m Bool
+fileExists = liftIOError System.Directory.doesFileExist
+
+-- | Returns the path of data file.
+getDataFileName :: (PandocMonad m, MonadIO m) => FilePath -> m FilePath
+#ifdef EMBED_DATA_FILES
+getDataFileName = return
+#else
+getDataFileName = liftIOError Paths.getDataFileName
+#endif
+
+-- | Return the modification time of a file.
+getModificationTime :: (PandocMonad m, MonadIO m) => FilePath -> m UTCTime
+getModificationTime = liftIOError System.Directory.getModificationTime
+
+-- | Output a log message.
+logOutput :: (PandocMonad m, MonadIO m) => LogMessage -> m ()
+logOutput msg = liftIO $ do
+  UTF8.hPutStr stderr $
+      "[" <> T.pack (show (messageVerbosity msg)) <> "] "
+  alertIndent $ T.lines $ showLogMessage msg
+
+-- | Prints the list of lines to @stderr@, indenting every but the first
+-- line by two spaces.
+alertIndent :: [Text] -> IO ()
+alertIndent [] = return ()
+alertIndent (l:ls) = do
+  UTF8.hPutStrLn stderr l
+  mapM_ go ls
+  where go l' = do UTF8.hPutStr stderr "  "
+                   UTF8.hPutStrLn stderr l'
+
+-- | Extract media from the mediabag into a directory (or a zip archive if the
+-- path supplied ends in @.zip@.
+extractMedia :: (PandocMonad m, MonadIO m) => FilePath -> Pandoc -> m Pandoc
+extractMedia path d = do
+  media <- getMediaBag
+  let items = mediaItems media
+  let (dir, mbZip) = case takeExtension path of
+                       ".zip" -> (takeDirectory path, Just (takeFileName path))
+                       _ -> (path, Nothing)
+  if null items
+    then return d
+    else do
+      let archive = foldr addEntry emptyArchive items
+      case mbZip of
+        Just fname -> writeMedia dir
+                        (fname, "application/zip", fromArchive archive)
+        Nothing -> mapM_ (writeMedia dir) items
+      return $ walk (adjustImagePath dir media) d
+ where
+  addEntry (fp, _mime, content) = addEntryToArchive (toEntry fp 0 content)
+
+-- | Write the contents of a media bag to a path.
+-- If the path contains URI escape sequences (percent-encoding),
+-- these are resolved.
+writeMedia :: (PandocMonad m, MonadIO m)
+           => FilePath
+           -> (FilePath, MimeType, BL.ByteString)
+           -> m ()
+writeMedia dir (fp, _mt, bs) = do
+  -- we normalize to get proper path separators for the platform
+  -- we unescape URI encoding, but given how insertMedia
+  -- is written, we shouldn't have any % in a canonical media name...
+  let fullpath = normalise $ dir </> unEscapeString fp
+  liftIOError (createDirectoryIfMissing True) (takeDirectory fullpath)
+  report $ Extracting (T.pack fullpath)
+  logIOError $ BL.writeFile fullpath bs
+
+-- | If the given Inline element is an image with a @src@ path equal to
+-- one in the list of @paths@, then prepends @dir@ to the image source;
+-- returns the element unchanged otherwise.
+adjustImagePath :: FilePath -> MediaBag -> Inline -> Inline
+adjustImagePath dir mediabag (Image attr lab (src, tit)) =
+  case lookupMedia (T.unpack src) mediabag of
+    Nothing -> Image attr lab (src, tit)
+    Just item ->
+      let fullpath = dir Posix.</> mediaPath item
+      in  Image attr lab (T.pack fullpath, tit)
+adjustImagePath _ _ x = x
diff --git a/src/Text/Pandoc/Class/PandocIO.hs b/src/Text/Pandoc/Class/PandocIO.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Class/PandocIO.hs
@@ -0,0 +1,79 @@
+{-# LANGUAGE DeriveFunctor #-}
+{-# LANGUAGE GeneralizedNewtypeDeriving #-}
+{- |
+Module      : Text.Pandoc.Class.PandocIO
+Copyright   : Copyright (C) 2016-2020 Jesse Rosenthal, John MacFarlane
+License     : GNU GPL, version 2 or above
+
+Maintainer  : Jesse Rosenthal <jrosenthal@jhu.edu>
+Stability   : alpha
+Portability : portable
+
+This module defines @'PandocIO'@, an IO-based instance of the
+@'PandocMonad'@ type class. File, data, and network access all are run
+using IO operators.
+-}
+module Text.Pandoc.Class.PandocIO
+  ( PandocIO(..)
+  , runIO
+  , runIOorExplode
+  , extractMedia
+ ) where
+
+import Control.Monad.Except (ExceptT, MonadError, runExceptT)
+import Control.Monad.IO.Class (MonadIO)
+import Control.Monad.State (StateT, evalStateT, lift, get, put)
+import Data.Default (Default (def))
+import Text.Pandoc.Class.CommonState (CommonState (..))
+import Text.Pandoc.Class.PandocMonad
+import Text.Pandoc.Definition
+import Text.Pandoc.Error
+import qualified Text.Pandoc.Class.IO as IO
+import Control.Monad.Catch (MonadCatch, MonadMask, MonadThrow)
+
+-- | Evaluate a 'PandocIO' operation.
+runIO :: PandocIO a -> IO (Either PandocError a)
+runIO ma = flip evalStateT def $ runExceptT $ unPandocIO ma
+
+-- | Evaluate a 'PandocIO' operation, handling any errors
+-- by exiting with an appropriate message and error status.
+runIOorExplode :: PandocIO a -> IO a
+runIOorExplode ma = runIO ma >>= handleError
+
+newtype PandocIO a = PandocIO {
+  unPandocIO :: ExceptT PandocError (StateT CommonState IO) a
+  } deriving ( MonadIO
+             , Functor
+             , Applicative
+             , Monad
+             , MonadCatch
+             , MonadMask
+             , MonadThrow
+             , MonadError PandocError
+             )
+
+instance PandocMonad PandocIO where
+  lookupEnv = IO.lookupEnv
+  getCurrentTime = IO.getCurrentTime
+  getCurrentTimeZone = IO.getCurrentTimeZone
+  newStdGen = IO.newStdGen
+  newUniqueHash = IO.newUniqueHash
+
+  openURL = IO.openURL
+  readFileLazy = IO.readFileLazy
+  readFileStrict = IO.readFileStrict
+  readStdinStrict = IO.readStdinStrict
+
+  glob = IO.glob
+  fileExists = IO.fileExists
+  getDataFileName = IO.getDataFileName
+  getModificationTime = IO.getModificationTime
+
+  getCommonState = PandocIO $ lift get
+  putCommonState = PandocIO . lift . put
+
+  logOutput = IO.logOutput
+
+-- | Extract media from the mediabag into a directory.
+extractMedia :: (PandocMonad m, MonadIO m) => FilePath -> Pandoc -> m Pandoc
+extractMedia = IO.extractMedia
diff --git a/src/Text/Pandoc/Class/PandocMonad.hs b/src/Text/Pandoc/Class/PandocMonad.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Class/PandocMonad.hs
@@ -0,0 +1,603 @@
+{-# LANGUAGE CPP #-}
+{-# LANGUAGE TupleSections #-}
+{-# LANGUAGE FlexibleContexts #-}
+{-# LANGUAGE FlexibleInstances #-}
+{-# LANGUAGE LambdaCase #-}
+{-# LANGUAGE MultiParamTypeClasses #-}
+{-# LANGUAGE OverloadedStrings #-}
+{-# LANGUAGE ScopedTypeVariables #-}
+{-# LANGUAGE UndecidableInstances #-}
+{-# LANGUAGE ViewPatterns #-}
+{- |
+Module      : Text.Pandoc.Class.PandocMonad
+Copyright   : Copyright (C) 2016-2020 Jesse Rosenthal, John MacFarlane
+License     : GNU GPL, version 2 or above
+
+Maintainer  : Jesse Rosenthal <jrosenthal@jhu.edu>
+Stability   : alpha
+Portability : portable
+
+This module defines a type class, 'PandocMonad', for pandoc readers
+and writers.
+-}
+
+module Text.Pandoc.Class.PandocMonad
+  ( PandocMonad(..)
+  , getTimestamp
+  , getPOSIXTime
+  , getZonedTime
+  , readFileFromDirs
+  , report
+  , runSilently
+  , setRequestHeader
+  , setNoCheckCertificate
+  , getLog
+  , setVerbosity
+  , getVerbosity
+  , setTrace
+  , getTrace
+  , getMediaBag
+  , setMediaBag
+  , insertMedia
+  , setUserDataDir
+  , getUserDataDir
+  , fetchItem
+  , extractURIData
+  , getInputFiles
+  , setInputFiles
+  , getOutputFile
+  , setOutputFile
+  , setResourcePath
+  , getResourcePath
+  , setRequestHeaders
+  , getRequestHeaders
+  , getSourceURL
+  , readMetadataFile
+  , toTextM
+  , fillMediaBag
+  , toLang
+  , makeCanonical
+  , findFileWithDataFallback
+  , checkUserDataDir
+  ) where
+
+import Control.Monad.Except (MonadError (catchError, throwError))
+import Control.Monad.Trans (MonadTrans, lift)
+import Control.Monad (when)
+import Data.Time (UTCTime)
+import Data.Time.Clock.POSIX (POSIXTime, utcTimeToPOSIXSeconds,
+                             posixSecondsToUTCTime)
+import Data.Time.LocalTime (TimeZone, ZonedTime, utcToZonedTime)
+import Network.URI ( escapeURIString, nonStrictRelativeTo,
+                     unEscapeString, parseURIReference, isAllowedInURI,
+                     parseURI, URI(..) )
+import System.FilePath ((</>), takeExtension, dropExtension,
+                        isRelative, makeRelative)
+import System.Random (StdGen)
+import Text.Collate.Lang (Lang(..), parseLang)
+import Text.Pandoc.Class.CommonState (CommonState (..))
+import Text.Pandoc.Definition
+import Text.Pandoc.Error
+import Text.Pandoc.Logging
+import Text.Pandoc.MIME (MimeType, getMimeType)
+import Text.Pandoc.MediaBag (MediaBag, lookupMedia, MediaItem(..))
+import Text.Pandoc.Shared (safeRead, makeCanonical, tshow)
+import Text.Pandoc.URI (uriPathToPath, pBase64DataURI)
+import qualified Data.Attoparsec.Text as A
+import Text.Pandoc.Walk (walkM)
+import qualified Text.Pandoc.UTF8 as UTF8
+import Data.ByteString.Base64 (decodeLenient)
+import Text.Parsec (ParsecT, getPosition, sourceLine, sourceName)
+import qualified Data.ByteString as B
+import qualified Data.ByteString.Lazy as BL
+import qualified Data.Text as T
+import qualified Debug.Trace
+import qualified Text.Pandoc.MediaBag as MB
+import qualified Data.Text.Encoding as TSE
+import qualified Data.Text.Encoding.Error as TSE
+
+-- | The PandocMonad typeclass contains all the potentially
+-- IO-related functions used in pandoc's readers and writers.
+-- Instances of this typeclass may implement these functions
+-- in IO (as in 'PandocIO') or using an internal state that
+-- represents a file system, time, and so on (as in 'PandocPure').
+class (Functor m, Applicative m, Monad m, MonadError PandocError m)
+      => PandocMonad m where
+  -- | Lookup an environment variable.
+  lookupEnv :: T.Text -> m (Maybe T.Text)
+  -- | Get the current (UTC) time.
+  getCurrentTime :: m UTCTime
+  -- | Get the locale's time zone.
+  getCurrentTimeZone :: m TimeZone
+  -- | Return a new generator for random numbers.
+  newStdGen :: m StdGen
+  -- | Return a new unique integer.
+  newUniqueHash :: m Int
+  -- | Retrieve contents and mime type from a URL, raising
+  -- an error on failure.
+  openURL :: T.Text -> m (B.ByteString, Maybe MimeType)
+  -- | Read the lazy ByteString contents from a file path,
+  -- raising an error on failure.
+  readFileLazy :: FilePath -> m BL.ByteString
+  -- | Read the strict ByteString contents from a file path,
+  -- raising an error on failure.
+  readFileStrict :: FilePath -> m B.ByteString
+  -- | Read the contents of stdin as a strict ByteString, raising
+  -- an error on failure.
+  readStdinStrict :: m B.ByteString
+  -- | Return a list of paths that match a glob, relative to
+  -- the working directory.  See 'System.FilePath.Glob' for
+  -- the glob syntax.
+  glob :: String -> m [FilePath]
+  -- | Returns True if file exists.
+  fileExists :: FilePath -> m Bool
+  -- | Returns the path of data file.
+  getDataFileName :: FilePath -> m FilePath
+  -- | Return the modification time of a file.
+  getModificationTime :: FilePath -> m UTCTime
+  -- | Get the value of the 'CommonState' used by all instances
+  -- of 'PandocMonad'.
+  getCommonState :: m CommonState
+  -- | Set the value of the 'CommonState' used by all instances
+  -- of 'PandocMonad'.
+  -- | Get the value of a specific field of 'CommonState'.
+  putCommonState :: CommonState -> m ()
+  -- | Get the value of a specific field of 'CommonState'.
+  getsCommonState :: (CommonState -> a) -> m a
+  getsCommonState f = f <$> getCommonState
+  -- | Modify the 'CommonState'.
+  modifyCommonState :: (CommonState -> CommonState) -> m ()
+  modifyCommonState f = getCommonState >>= putCommonState . f
+  -- | Output a log message.
+  logOutput :: LogMessage -> m ()
+  -- | Output a debug message to sterr, using 'Debug.Trace.trace',
+  -- if tracing is enabled.  Note: this writes to stderr even in
+  -- pure instances.
+  trace :: T.Text -> m ()
+  trace msg = do
+    tracing <- getsCommonState stTrace
+    when tracing $ Debug.Trace.trace ("[trace] " ++ T.unpack msg) (return ())
+
+-- * Functions defined for all PandocMonad instances
+
+-- | Set the verbosity level.
+setVerbosity :: PandocMonad m => Verbosity -> m ()
+setVerbosity verbosity =
+  modifyCommonState $ \st -> st{ stVerbosity = verbosity }
+
+-- | Get the verbosity level.
+getVerbosity :: PandocMonad m => m Verbosity
+getVerbosity = getsCommonState stVerbosity
+
+-- | Set tracing. This affects the behavior of 'trace'. If tracing
+-- is not enabled, 'trace' does nothing.
+setTrace :: PandocMonad m => Bool -> m ()
+setTrace enabled = modifyCommonState $ \st -> st{ stTrace = enabled }
+
+-- | Get tracing status.
+getTrace :: PandocMonad m => m Bool
+getTrace = getsCommonState stTrace
+
+-- | Get the accumulated log messages (in temporal order).
+getLog :: PandocMonad m => m [LogMessage]
+getLog = reverse <$> getsCommonState stLog
+
+-- | Log a message using 'logOutput'.  Note that 'logOutput' is
+-- called only if the verbosity level exceeds the level of the
+-- message, but the message is added to the list of log messages
+-- that will be retrieved by 'getLog' regardless of its verbosity level.
+report :: PandocMonad m => LogMessage -> m ()
+report msg = do
+  verbosity <- getsCommonState stVerbosity
+  let level = messageVerbosity msg
+  when (level <= verbosity) $ logOutput msg
+  modifyCommonState $ \st -> st{ stLog = msg : stLog st }
+
+-- | Run an action, but suppress the output of any log messages;
+-- instead, all messages reported by @action@ are returned separately
+-- and not added to the main log.
+runSilently :: PandocMonad m => m a -> m (a, [LogMessage])
+runSilently action = do
+  -- get current settings
+  origLog <- getsCommonState stLog
+  origVerbosity <- getVerbosity
+  -- reset log level and set verbosity to the minimum
+  modifyCommonState (\st -> st { stVerbosity = ERROR, stLog = []})
+  result <- action
+  -- get log messages reported while running `action`
+  newLog <- getsCommonState stLog
+  modifyCommonState (\st -> st { stVerbosity = origVerbosity, stLog = origLog})
+
+  return (result, newLog)
+
+-- | Set request header to use in HTTP requests.
+setRequestHeader :: PandocMonad m
+                 => T.Text  -- ^ Header name
+                 -> T.Text  -- ^ Value
+                 -> m ()
+setRequestHeader name val = modifyCommonState $ \st ->
+  st{ stRequestHeaders =
+       (name, val) : filter (\(n,_) -> n /= name) (stRequestHeaders st)  }
+
+-- | Determine whether certificate validation is disabled
+setNoCheckCertificate :: PandocMonad m => Bool -> m ()
+setNoCheckCertificate noCheckCertificate = modifyCommonState $ \st -> st{stNoCheckCertificate = noCheckCertificate}
+
+-- | Initialize the media bag.
+setMediaBag :: PandocMonad m => MediaBag -> m ()
+setMediaBag mb = modifyCommonState $ \st -> st{stMediaBag = mb}
+
+-- | Retrieve the media bag.
+getMediaBag :: PandocMonad m => m MediaBag
+getMediaBag = getsCommonState stMediaBag
+
+-- | Insert an item into the media bag.
+insertMedia :: PandocMonad m => FilePath -> Maybe MimeType -> BL.ByteString -> m ()
+insertMedia fp mime bs = do
+  mb <- getMediaBag
+  let mb' = MB.insertMedia fp mime bs mb
+  setMediaBag mb'
+
+-- | Retrieve the input filenames.
+getInputFiles :: PandocMonad m => m [FilePath]
+getInputFiles = getsCommonState stInputFiles
+
+-- | Set the input filenames.
+setInputFiles :: PandocMonad m => [FilePath] -> m ()
+setInputFiles fs = do
+  let sourceURL = case fs of
+                    []    -> Nothing
+                    (x:_) -> case parseURI x of
+                                Just u
+                                  | uriScheme u `elem` ["http:","https:"] ->
+                                      Just $ show u{ uriQuery = "",
+                                                     uriFragment = "" }
+                                _ -> Nothing
+
+  modifyCommonState $ \st -> st{ stInputFiles = fs
+                               , stSourceURL = T.pack <$> sourceURL }
+
+-- | Retrieve the output filename.
+getOutputFile :: PandocMonad m => m (Maybe FilePath)
+getOutputFile = getsCommonState stOutputFile
+
+-- | Set the output filename.
+setOutputFile :: PandocMonad m => Maybe FilePath -> m ()
+setOutputFile mbf = modifyCommonState $ \st -> st{ stOutputFile = mbf }
+
+-- | Retrieve the resource path searched by 'fetchItem'.
+getResourcePath :: PandocMonad m => m [FilePath]
+getResourcePath = getsCommonState stResourcePath
+
+-- | Set the resource path searched by 'fetchItem'.
+setResourcePath :: PandocMonad m => [FilePath] -> m ()
+setResourcePath ps = modifyCommonState $ \st -> st{stResourcePath = ps}
+
+-- | Retrieve the request headers to add for HTTP requests.
+getRequestHeaders :: PandocMonad m => m [(T.Text, T.Text)]
+getRequestHeaders = getsCommonState stRequestHeaders
+
+-- | Set the request headers to add for HTTP requests.
+setRequestHeaders :: PandocMonad m => [(T.Text, T.Text)] -> m ()
+setRequestHeaders hs = modifyCommonState $ \st -> st{ stRequestHeaders = hs }
+
+-- | Get the absolute UL or directory of first source file.
+getSourceURL :: PandocMonad m => m (Maybe T.Text)
+getSourceURL = getsCommonState stSourceURL
+
+-- | Get the current UTC time. If the @SOURCE_DATE_EPOCH@ environment
+-- variable is set to a unix time (number of seconds since midnight
+-- Jan 01 1970 UTC), it is used instead of the current time, to support
+-- reproducible builds.
+getTimestamp :: PandocMonad m => m UTCTime
+getTimestamp = do
+  mbSourceDateEpoch <- lookupEnv "SOURCE_DATE_EPOCH"
+  case mbSourceDateEpoch >>= safeRead of
+    Just (epoch :: Integer) ->
+      return $ posixSecondsToUTCTime $ fromIntegral epoch
+    Nothing -> getCurrentTime
+
+-- | Get the POSIX time. If @SOURCE_DATE_EPOCH@ is set to a unix time,
+-- it is used instead of the current time.
+getPOSIXTime :: PandocMonad m => m POSIXTime
+getPOSIXTime = utcTimeToPOSIXSeconds <$> getTimestamp
+
+-- | Get the zoned time. If @SOURCE_DATE_EPOCH@ is set to a unix time,
+-- value (POSIX time), it is used instead of the current time.
+getZonedTime :: PandocMonad m => m ZonedTime
+getZonedTime = do
+  t <- getTimestamp
+  tz <- getCurrentTimeZone
+  return $ utcToZonedTime tz t
+
+-- | Read file, checking in any number of directories.
+readFileFromDirs :: PandocMonad m => [FilePath] -> FilePath -> m (Maybe T.Text)
+readFileFromDirs [] _ = return Nothing
+readFileFromDirs (d:ds) f = catchError
+    (Just <$> (readFileStrict (d </> f) >>= toTextM (d </> f)))
+    (\_ -> readFileFromDirs ds f)
+
+-- | Convert BCP47 string to a Lang, issuing warning
+-- if there are problems.
+toLang :: PandocMonad m => Maybe T.Text -> m (Maybe Lang)
+toLang Nothing = return Nothing
+toLang (Just s) =
+  case parseLang s of
+       Left _ -> do
+         report $ InvalidLang s
+         return Nothing
+       Right l -> return (Just l)
+
+-- | Specialized version of parseURIReference that disallows
+-- single-letter schemes.  Reason:  these are usually windows absolute
+-- paths.
+parseURIReference' :: T.Text -> Maybe URI
+parseURIReference' s = do
+  u <- parseURIReference (T.unpack s)
+  case uriScheme u of
+       [_] -> Nothing
+       _   -> Just u
+
+-- | Set the user data directory in common state.
+setUserDataDir :: PandocMonad m
+               => Maybe FilePath
+               -> m ()
+setUserDataDir mbfp = modifyCommonState $ \st -> st{ stUserDataDir = mbfp }
+
+-- | Get the user data directory from common state.
+getUserDataDir :: PandocMonad m
+               => m (Maybe FilePath)
+getUserDataDir = getsCommonState stUserDataDir
+
+-- | Fetch an image or other item from the local filesystem or the net.
+-- Returns raw content and maybe mime type.
+fetchItem :: PandocMonad m
+          => T.Text
+          -> m (B.ByteString, Maybe MimeType)
+fetchItem s = do
+  mediabag <- getMediaBag
+  case lookupMedia (T.unpack s) mediabag of
+    Just item -> return (BL.toStrict (mediaContents item),
+                         Just (mediaMimeType item))
+    Nothing -> downloadOrRead s
+
+-- | Returns the content and, if available, the MIME type of a resource.
+-- If the given resource location is a valid URI, then download the
+-- resource from that URI. Otherwise, treat the resource identifier as a
+-- local file name.
+--
+-- Note that resources are treated relative to the URL of the first
+-- input source, if any.
+downloadOrRead :: PandocMonad m
+               => T.Text
+               -> m (B.ByteString, Maybe MimeType)
+downloadOrRead s
+ | "data:" `T.isPrefixOf` s,
+   Right (bs, mt) <- A.parseOnly (pBase64DataURI <* A.endOfInput) s
+   = pure (bs, Just mt)
+ | otherwise = do
+  sourceURL <- getsCommonState stSourceURL
+  case (sourceURL >>= parseURIReference' . ensureEscaped, ensureEscaped s) of
+    (Just u, s') -> -- try fetching from relative path at source
+       case parseURIReference' s' of
+            Just u' -> openURL $ T.pack $ show $ u' `nonStrictRelativeTo` u
+            Nothing -> openURL s' -- will throw error
+    (Nothing, s'@(T.unpack -> ('/':'/':c:_))) | c /= '?' ->  -- protocol-relative URI
+                -- we exclude //? because of //?UNC/ on Windows
+       case parseURIReference' s' of
+            Just u' -> openURL $ T.pack $ show $ u' `nonStrictRelativeTo` httpcolon
+            Nothing -> openURL s' -- will throw error
+    (Nothing, s') ->
+       case parseURI (T.unpack s') of  -- requires absolute URI
+            Just URI{ uriScheme = "file:", uriPath = upath}
+              -> readLocalFile $ uriPathToPath (T.pack upath)
+            Just URI{ uriScheme = "data:", uriPath = upath}
+              -> pure $ extractURIData upath
+            -- We don't want to treat C:/ as a scheme:
+            Just u' | length (uriScheme u') > 2 -> openURL (T.pack $ show u')
+            _ -> readLocalFile fp -- get from local file system
+   where readLocalFile f = do
+             resourcePath <- getResourcePath
+             (fp', cont) <- if isRelative f
+                               then withPaths resourcePath readFileStrict f
+                               else (f,) <$> readFileStrict f
+             report $ LoadedResource f (makeRelative "." fp')
+             return (cont, mime)
+         httpcolon = URI{ uriScheme = "http:",
+                          uriAuthority = Nothing,
+                          uriPath = "",
+                          uriQuery = "",
+                          uriFragment = "" }
+         fp = unEscapeString $ T.unpack s
+         mime = getMimeType $ case takeExtension fp of
+                     ".gz" -> dropExtension fp
+                     ".svgz" -> dropExtension fp ++ ".svg"
+                     x     -> x
+         ensureEscaped = T.pack . escapeURIString isAllowedInURI . T.unpack . T.map convertSlash
+         convertSlash '\\' = '/'
+         convertSlash x    = x
+
+-- Extract data from a data URI's path component.
+extractURIData :: String -> (B.ByteString, Maybe MimeType)
+extractURIData upath =
+  case break (== ';') (filter (/= ' ') mimespec) of
+     (mime', ";base64") -> (decodeLenient contents, Just (T.pack mime'))
+     (mime', _) -> (contents, Just (T.pack mime'))
+  where
+    (mimespec, rest) = break (== ',') $ unEscapeString upath
+    contents = UTF8.fromString $ drop 1 rest
+
+-- | Checks if the file path is relative to a parent directory.
+isRelativeToParentDir :: FilePath -> Bool
+isRelativeToParentDir fname =
+  let canonical = makeCanonical fname
+   in length canonical >= 2 && take 2 canonical == ".."
+
+-- | Returns possible user data directory if the file path refers to a file or
+-- subdirectory within it.
+checkUserDataDir :: PandocMonad m => FilePath -> m (Maybe FilePath)
+checkUserDataDir fname =
+  if isRelative fname && not (isRelativeToParentDir fname)
+     then getUserDataDir
+     else return Nothing
+
+-- | Read metadata file from the working directory or, if not found there, from
+-- the metadata subdirectory of the user data directory.
+readMetadataFile :: PandocMonad m => FilePath -> m B.ByteString
+readMetadataFile fname = findFileWithDataFallback "metadata" fname >>= \case
+  Nothing -> throwError $ PandocCouldNotFindMetadataFileError (T.pack fname)
+  Just metadataFile -> readFileStrict metadataFile
+
+-- | Tries to run an action on a file: for each directory given, a
+-- filepath is created from the given filename, and the action is run on
+-- that filepath. Returns the result of the first successful execution
+-- of the action, or throws a @PandocResourceNotFound@ exception if the
+-- action errors for all filepaths.
+withPaths :: PandocMonad m
+          => [FilePath] -> (FilePath -> m a) -> FilePath -> m (FilePath, a)
+withPaths [] _ fp = throwError $ PandocResourceNotFound $ T.pack fp
+withPaths (p:ps) action fp =
+  catchError ((p </> fp,) <$> action (p </> fp))
+             (\_ -> withPaths ps action fp)
+
+-- | A variant of Text.Pandoc.UTF8.toText that takes a FilePath
+-- as well as the file's contents as parameter, and traps UTF8
+-- decoding errors so it can issue a more informative PandocUTF8DecodingError
+-- with source position.
+toTextM :: PandocMonad m => FilePath -> B.ByteString -> m T.Text
+toTextM fp bs =
+  case TSE.decodeUtf8' . filterCRs . dropBOM $ bs of
+    Left (TSE.DecodeError _ (Just w)) ->
+      case B.elemIndex w bs of
+        Just offset ->
+          throwError $ PandocUTF8DecodingError (T.pack fp) offset w
+        Nothing -> throwError $ PandocUTF8DecodingError (T.pack fp) 0 w
+    Left e -> throwError $ PandocAppError (tshow e)
+    Right t -> return t
+ where
+   dropBOM bs' =
+     if "\xEF\xBB\xBF" `B.isPrefixOf` bs'
+        then B.drop 3 bs'
+        else bs'
+   filterCRs = B.filter (/=13)
+
+-- | Returns @fp@ if the file exists in the current directory; otherwise
+-- searches for the data file relative to @/subdir/@. Returns @Nothing@
+-- if neither file exists.
+findFileWithDataFallback :: PandocMonad m
+                         => FilePath  -- ^ subdir
+                         -> FilePath  -- ^ fp
+                         -> m (Maybe FilePath)
+findFileWithDataFallback subdir fp = do
+  -- First we check to see if the file is found. If not, and if it's not
+  -- an absolute path, we check to see whether it's in @userdir/@. If
+  -- not, we leave it unchanged.
+  existsInWorkingDir <- fileExists fp
+  if existsInWorkingDir
+     then return $ Just fp
+     else do
+       mbDataDir <- checkUserDataDir fp
+       case mbDataDir of
+         Nothing -> return Nothing
+         Just datadir -> do
+           let datafp = datadir </> subdir </> fp
+           existsInDataDir <- fileExists datafp
+           return $ if existsInDataDir
+                    then Just datafp
+                    else Nothing
+
+-- | Traverse tree, filling media bag for any images that
+-- aren't already in the media bag.
+fillMediaBag :: PandocMonad m => Pandoc -> m Pandoc
+fillMediaBag d = walkM handleImage d
+  where handleImage :: PandocMonad m => Inline -> m Inline
+        handleImage (Image attr lab (src, tit)) = catchError
+          (do mediabag <- getMediaBag
+              let fp = T.unpack src
+              case lookupMedia fp mediabag of
+                Just _ -> return ()
+                Nothing -> do
+                  (bs, mt) <- fetchItem src
+                  insertMedia fp mt (BL.fromStrict bs)
+              return $ Image attr lab (src, tit))
+          (\e ->
+              case e of
+                PandocIOError text err -> do
+                  report $ CouldNotFetchResource text . T.pack $
+                            (show err ++ "\nReplacing image with description.")
+                  -- emit alt text
+                  return $ replacementSpan attr src tit lab
+                PandocResourceNotFound _ -> do
+                  report $ CouldNotFetchResource src
+                            "replacing image with description"
+                  -- emit alt text
+                  return $ replacementSpan attr src tit lab
+                PandocHttpError u er -> do
+                  report $ CouldNotFetchResource u
+                            (er <> "\nReplacing image with description.")
+                  -- emit alt text
+                  return $ replacementSpan attr src tit lab
+                _ -> throwError e)
+        handleImage x = return x
+
+        replacementSpan (ident, classes, attribs) src title descr =
+          Span ( ident
+               , "image":"placeholder":classes
+               , ("original-image-src", src) :
+                 ("original-image-title", title) :
+                 attribs
+               )
+               descr
+
+-- This requires UndecidableInstances.  We could avoid that
+-- by repeating the definitions below for every monad transformer
+-- we use: ReaderT, WriterT, StateT, RWST.  But this seems to
+-- be harmless.
+instance (MonadTrans t, PandocMonad m, Functor (t m),
+          MonadError PandocError (t m), Monad (t m),
+          Applicative (t m)) => PandocMonad (t m) where
+  lookupEnv = lift . lookupEnv
+  getCurrentTime = lift getCurrentTime
+  getCurrentTimeZone = lift getCurrentTimeZone
+  newStdGen = lift newStdGen
+  newUniqueHash = lift newUniqueHash
+  openURL = lift . openURL
+  readFileLazy = lift . readFileLazy
+  readFileStrict = lift . readFileStrict
+  readStdinStrict = lift readStdinStrict
+  glob = lift . glob
+  fileExists = lift . fileExists
+  getDataFileName = lift . getDataFileName
+  getModificationTime = lift . getModificationTime
+  getCommonState = lift getCommonState
+  putCommonState = lift . putCommonState
+  logOutput = lift . logOutput
+
+instance {-# OVERLAPS #-} PandocMonad m => PandocMonad (ParsecT s st m) where
+  lookupEnv = lift . lookupEnv
+  getCurrentTime = lift getCurrentTime
+  getCurrentTimeZone = lift getCurrentTimeZone
+  newStdGen = lift newStdGen
+  newUniqueHash = lift newUniqueHash
+  openURL = lift . openURL
+  readFileLazy = lift . readFileLazy
+  readFileStrict = lift . readFileStrict
+  readStdinStrict = lift readStdinStrict
+  glob = lift . glob
+  fileExists = lift . fileExists
+  getDataFileName = lift . getDataFileName
+  getModificationTime = lift . getModificationTime
+  getCommonState = lift getCommonState
+  putCommonState = lift . putCommonState
+  trace msg = do
+    tracing <- getsCommonState stTrace
+    when tracing $ do
+      pos <- getPosition
+      Debug.Trace.trace
+        ("[trace] Parsed " ++ T.unpack msg ++ " at line " ++
+            show (sourceLine pos) ++
+            if sourceName pos == "chunk"
+               then " of chunk"
+               else "")
+        (return ())
+  logOutput = lift . logOutput
diff --git a/src/Text/Pandoc/Class/PandocPure.hs b/src/Text/Pandoc/Class/PandocPure.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Class/PandocPure.hs
@@ -0,0 +1,241 @@
+{-# LANGUAGE CPP #-}
+{-# LANGUAGE DeriveFunctor #-}
+{-# LANGUAGE GeneralizedNewtypeDeriving #-}
+{-# LANGUAGE OverloadedStrings #-}
+{- |
+Module      : Text.Pandoc.Class.PandocPure
+Copyright   : Copyright (C) 2016-2020 Jesse Rosenthal, John MacFarlane
+License     : GNU GPL, version 2 or above
+
+Maintainer  : Jesse Rosenthal <jrosenthal@jhu.edu>
+Stability   : alpha
+Portability : portable
+
+This module defines a pure instance 'PandocPure' of the @'PandocMonad'@
+typeclass. This instance is useful for testing, or when all IO access is
+prohibited for security reasons.
+-}
+module Text.Pandoc.Class.PandocPure
+  ( PureState(..)
+  , getPureState
+  , getsPureState
+  , putPureState
+  , modifyPureState
+  , PandocPure(..)
+  , FileTree
+  , FileInfo(..)
+  , addToFileTree
+  , insertInFileTree
+  , runPure
+  ) where
+
+import Codec.Archive.Zip
+import Control.Monad.Trans ( MonadTrans(lift) )
+import Control.Monad.Except
+    ( ExceptT(..), MonadError(throwError), runExceptT )
+import Control.Monad.State.Strict
+    ( StateT(StateT),
+      State,
+      MonadState(put, get),
+      modify,
+      evalState,
+      evalStateT )
+import Control.Monad (foldM)
+import Data.Default
+import Data.Text (Text)
+import Data.Time (UTCTime)
+import Data.Time.Clock.POSIX ( posixSecondsToUTCTime )
+import Data.Time.LocalTime (TimeZone, utc)
+import Data.Word (Word8)
+import System.Directory (doesDirectoryExist, getDirectoryContents)
+import System.FilePath ((</>))
+import System.FilePath.Glob (match, compile)
+import System.Random (StdGen, mkStdGen)
+import Text.Pandoc.Class.CommonState (CommonState (..))
+import Text.Pandoc.Class.PandocMonad
+import Text.Pandoc.Error
+import qualified Data.ByteString as B
+import qualified Data.ByteString.Lazy as BL
+import qualified Data.Map as M
+import qualified Data.Text as T
+import qualified System.Directory as Directory (getModificationTime)
+
+#if MIN_VERSION_random(1,3,0)
+import System.Random (splitGen, SplitGen)
+
+split :: SplitGen g => g -> (g, g)
+split = splitGen
+#else
+import System.Random (split)
+#endif
+
+-- | The 'PureState' contains ersatz representations
+-- of things that would normally be obtained through IO.
+data PureState = PureState
+  { stStdGen     :: StdGen
+  , stWord8Store :: [Word8]    -- ^ should be infinite, i.e. [1..]
+  , stUniqStore  :: [Int]      -- ^ should be infinite and contain every
+                               -- element at most once, e.g. [1..]
+  , stEnv :: [(Text, Text)]
+  , stTime :: UTCTime
+  , stTimeZone :: TimeZone
+  , stReferenceDocx :: Archive
+  , stReferencePptx :: Archive
+  , stReferenceODT :: Archive
+  , stFiles :: FileTree
+  , stStdin :: B.ByteString
+  , stUserDataFiles :: FileTree
+  , stCabalDataFiles :: FileTree
+  }
+
+instance Default PureState where
+  def = PureState
+        { stStdGen = mkStdGen 1848
+        , stWord8Store = [1..]
+        , stUniqStore = [1..]
+        , stEnv = [("USER", "pandoc-user")]
+        , stTime = posixSecondsToUTCTime 0
+        , stTimeZone = utc
+        , stReferenceDocx = emptyArchive
+        , stReferencePptx = emptyArchive
+        , stReferenceODT = emptyArchive
+        , stFiles = mempty
+        , stStdin = mempty
+        , stUserDataFiles = mempty
+        , stCabalDataFiles = mempty
+        }
+
+
+-- | Retrieve the underlying state of the @'PandocPure'@ type.
+getPureState :: PandocPure PureState
+getPureState = PandocPure $ lift $ lift get
+
+-- | Retrieve a value from the underlying state of the @'PandocPure'@
+-- type.
+getsPureState :: (PureState -> a) -> PandocPure a
+getsPureState f = f <$> getPureState
+
+-- | Set a new state for the @'PandocPure'@ type.
+putPureState :: PureState -> PandocPure ()
+putPureState ps= PandocPure $ lift $ lift $ put ps
+
+-- | Modify the underlying state of the @'PandocPure'@ type.
+modifyPureState :: (PureState -> PureState) -> PandocPure ()
+modifyPureState f = PandocPure $ lift $ lift $ modify f
+
+-- | Captures all file-level information necessary for a @'PandocMonad'@
+-- conforming mock file system.
+data FileInfo = FileInfo
+  { infoFileMTime :: UTCTime
+  , infoFileContents :: B.ByteString
+  }
+
+-- | Basis of the mock file system used by @'PandocPure'@.
+newtype FileTree = FileTree { unFileTree :: M.Map FilePath FileInfo }
+  deriving (Semigroup, Monoid)
+
+-- | Retrieve @'FileInfo'@ of the given @'FilePath'@ from a
+-- @'FileTree'@.
+getFileInfo :: FilePath -> FileTree -> Maybe FileInfo
+getFileInfo fp tree =
+  M.lookup (makeCanonical fp) (unFileTree tree)
+
+-- | Add the specified file to the FileTree. If file
+-- is a directory, add its contents recursively.
+addToFileTree :: FileTree -> FilePath -> IO FileTree
+addToFileTree tree fp = do
+  isdir <- doesDirectoryExist fp
+  if isdir
+     then do -- recursively add contents of directories
+       let isSpecial ".." = True
+           isSpecial "."  = True
+           isSpecial _    = False
+       fs <- map (fp </>) . filter (not . isSpecial) <$> getDirectoryContents fp
+       foldM addToFileTree tree fs
+     else do
+       contents <- B.readFile fp
+       mtime <- Directory.getModificationTime fp
+       return $ insertInFileTree fp FileInfo{ infoFileMTime = mtime
+                                            , infoFileContents = contents } tree
+
+-- | Insert an ersatz file into the 'FileTree'.
+insertInFileTree :: FilePath -> FileInfo -> FileTree -> FileTree
+insertInFileTree fp info (FileTree treemap) =
+  FileTree $ M.insert (makeCanonical fp) info treemap
+
+newtype PandocPure a = PandocPure {
+  unPandocPure :: ExceptT PandocError
+                  (StateT CommonState (State PureState)) a
+  } deriving ( Functor
+             , Applicative
+             , Monad
+             , MonadError PandocError
+             )
+
+-- | Run a 'PandocPure' operation.
+runPure :: PandocPure a -> Either PandocError a
+runPure x = flip evalState def $
+            flip evalStateT def $
+            runExceptT $
+            unPandocPure x
+
+instance PandocMonad PandocPure where
+  lookupEnv s = do
+    env <- getsPureState stEnv
+    return (lookup s env)
+
+  getCurrentTime = getsPureState stTime
+
+  getCurrentTimeZone = getsPureState stTimeZone
+
+  newStdGen = do
+    oldGen <- getsPureState stStdGen
+    let (genToStore, genToReturn) = split oldGen
+    modifyPureState $ \st -> st { stStdGen = genToStore }
+    return genToReturn
+
+  newUniqueHash = do
+    uniqs <- getsPureState stUniqStore
+    case uniqs of
+      u : us -> do
+        modifyPureState $ \st -> st { stUniqStore = us }
+        return u
+      _ -> throwError $ PandocShouldNeverHappenError
+                        "uniq store ran out of elements"
+  openURL u = throwError $ PandocResourceNotFound u
+  readFileLazy fp = do
+    fps <- getsPureState stFiles
+    case infoFileContents <$> getFileInfo fp fps of
+      Just bs -> return (BL.fromStrict bs)
+      Nothing -> throwError $ PandocResourceNotFound $ T.pack fp
+  readFileStrict fp = do
+    fps <- getsPureState stFiles
+    case infoFileContents <$> getFileInfo fp fps of
+      Just bs -> return bs
+      Nothing -> throwError $ PandocResourceNotFound $ T.pack fp
+
+  readStdinStrict = getsPureState stStdin
+
+  glob s = do
+    FileTree ftmap <- getsPureState stFiles
+    return $ filter (match (compile s)) $ M.keys ftmap
+
+  fileExists fp = do
+    fps <- getsPureState stFiles
+    case getFileInfo fp fps of
+         Nothing -> return False
+         Just _  -> return True
+
+  getDataFileName fp = return $ "data/" ++ fp
+
+  getModificationTime fp = do
+    fps <- getsPureState stFiles
+    case infoFileMTime <$> getFileInfo fp fps of
+      Just tm -> return tm
+      Nothing -> throwError $ PandocIOError (T.pack fp)
+                    (userError "Can't get modification time")
+
+  getCommonState = PandocPure $ lift get
+  putCommonState x = PandocPure $ lift $ put x
+
+  logOutput _msg = return ()
diff --git a/src/Text/Pandoc/Class/Sandbox.hs b/src/Text/Pandoc/Class/Sandbox.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Class/Sandbox.hs
@@ -0,0 +1,61 @@
+{- |
+Module      : Text.Pandoc.Class.Sandbox
+Copyright   : Copyright (C) 2021-2024 John MacFarlane
+License     : GNU GPL, version 2 or above
+
+Maintainer  : John MacFarlane (<jgm@berkeley.edu>)
+Stability   : alpha
+Portability : portable
+
+This module provides a way to run PandocMonad actions in a sandbox
+(pure context, with no IO allowed and access only to designated files).
+-}
+
+module Text.Pandoc.Class.Sandbox
+  ( sandbox
+  , sandboxWithFileTree
+  )
+where
+
+import Control.Monad (foldM)
+import Control.Monad.Except (throwError)
+import Control.Monad.IO.Class (MonadIO (liftIO))
+import Text.Pandoc.Class.PandocMonad
+import Text.Pandoc.Class.PandocPure
+import Text.Pandoc.Class.CommonState (CommonState(..))
+import Text.Pandoc.Logging (messageVerbosity)
+
+-- | Lift a PandocPure action into any instance of PandocMonad.
+-- The main computation is done purely, but CommonState is preserved
+-- continuously, and warnings are emitted after the action completes.
+-- The parameter is a list of FilePaths which will be added to the
+-- ersatz file system and be available for reading.
+sandbox :: (PandocMonad m, MonadIO m) => [FilePath] -> PandocPure a -> m a
+sandbox files action = do
+  tree <- liftIO $ foldM addToFileTree mempty files
+  sandboxWithFileTree tree action
+
+-- | Lift a PandocPure action into any instance of PandocMonad.
+-- The main computation is done purely, but CommonState is preserved
+-- continuously, and warnings are emitted after the action completes.
+-- The parameter is an ersatz file system which will be available for
+-- reading.
+sandboxWithFileTree :: (PandocMonad m, MonadIO m)
+                    => FileTree -> PandocPure a -> m a
+sandboxWithFileTree tree action = do
+  oldState <- getCommonState
+  case runPure (do putCommonState oldState
+                   modifyPureState $ \ps -> ps{ stFiles = tree }
+                   result <- action
+                   st <- getCommonState
+                   return (st, result)) of
+          Left e -> throwError e
+          Right (st, result) -> do
+            putCommonState st
+            let verbosity = stVerbosity st
+            -- emit warnings, since these are not printed in runPure
+            let newMessages = reverse $ take
+                  (length (stLog st) - length (stLog oldState)) (stLog st)
+            mapM_ logOutput
+              (filter ((<= verbosity) . messageVerbosity) newMessages)
+            return result
diff --git a/src/Text/Pandoc/Compat/Time.hs b/src/Text/Pandoc/Compat/Time.hs
deleted file mode 100644
--- a/src/Text/Pandoc/Compat/Time.hs
+++ /dev/null
@@ -1,30 +0,0 @@
-{-# LANGUAGE CPP #-}
-
-{-
-This compatibility module is needed because, in time 1.5, the
-`defaultTimeLocale` function was moved from System.Locale (in the
-old-locale library) into Data.Time.
-
-We support both behaviors because time 1.4 is a boot library for GHC
-7.8. time 1.5 is a boot library for GHC 7.10.
-
-When support is dropped for GHC 7.8, this module may be obsoleted.
--}
-
-#if MIN_VERSION_time(1,5,0)
-module Text.Pandoc.Compat.Time (
-  module Data.Time
-)
-where
-import Data.Time
-
-#else
-module Text.Pandoc.Compat.Time (
-  module Data.Time,
-  defaultTimeLocale
-)
-where
-import Data.Time
-import System.Locale ( defaultTimeLocale )
-
-#endif
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,22 +1,245 @@
+{-# LANGUAGE CPP #-}
+{-# LANGUAGE ScopedTypeVariables #-}
+#ifdef EMBED_DATA_FILES
 {-# LANGUAGE TemplateHaskell #-}
+#endif
+{- |
+Module      : Text.Pandoc.Data
+Copyright   : Copyright (C) 2013-2024 John MacFarlane
+License     : GNU GPL, version 2 or above
 
-module Text.Pandoc.Data (dataFiles) where
+Maintainer  : John MacFarlane <jgm@berkeley@edu>
+Stability   : alpha
+Portability : portable
 
+Access to pandoc's data files.
+-}
+module Text.Pandoc.Data ( readDefaultDataFile
+                        , readDataFile
+                        , getDataFileNames
+                        , defaultUserDataDir
+                        ) where
+import Text.Pandoc.Class (PandocMonad(..), checkUserDataDir, getTimestamp,
+                          getUserDataDir, getPOSIXTime)
+import Data.Time.Clock.POSIX (utcTimeToPOSIXSeconds)
+import qualified Data.ByteString.Lazy as BL
 import qualified Data.ByteString as B
-import Data.FileEmbed
-import System.FilePath (splitDirectories)
-import qualified System.FilePath.Posix as Posix
+import Codec.Archive.Zip
+import qualified Data.Text as T
+import Control.Monad.Except (throwError)
+import Text.Pandoc.Error (PandocError(..))
+import System.FilePath
+import System.Directory
+import qualified Control.Exception as E
+#ifdef EMBED_DATA_FILES
+import Text.Pandoc.Data.BakedIn (dataFiles)
+import Text.Pandoc.Shared (makeCanonical)
+#else
+import Paths_pandoc (getDataDir)
+#endif
 
--- We ensure that the data files are stored using Posix
--- path separators (/), even on Windows.
-dataFiles :: [(FilePath, B.ByteString)]
-dataFiles = map (\(fp, contents) ->
-  (Posix.joinPath (splitDirectories fp), contents)) dataFiles'
+-- | Read file from the default data files.
+readDefaultDataFile :: PandocMonad m => FilePath -> m B.ByteString
+readDefaultDataFile "reference.docx" =
+  B.concat . BL.toChunks . fromArchive <$> getDefaultReferenceDocx
+readDefaultDataFile "reference.pptx" =
+  B.concat . BL.toChunks . fromArchive <$> getDefaultReferencePptx
+readDefaultDataFile "reference.odt" =
+  B.concat . BL.toChunks . fromArchive <$> getDefaultReferenceODT
+readDefaultDataFile fname =
+#ifdef EMBED_DATA_FILES
+  case lookup (makeCanonical fname) dataFiles of
+    Nothing       -> throwError $ PandocCouldNotFindDataFileError $ T.pack fname
+    Just contents -> return contents
+#else
+  getDataFileName fname' >>= checkExistence >>= readFileStrict
+    where fname' = if fname == "MANUAL.txt" then fname else "data" </> fname
 
-dataFiles' :: [(FilePath, B.ByteString)]
-dataFiles' = ("MANUAL.txt", $(embedFile "MANUAL.txt")) :
-             -- handle the hidden file separately, since embedDir doesn't
-             -- include it:
-             ("docx/_rels/.rels", $(embedFile "data/docx/_rels/.rels")) :
-             ("pptx/_rels/.rels", $(embedFile "data/pptx/_rels/.rels")) :
-             $(embedDir "data")
+-- | Returns the input filename unchanged if the file exits, and throws
+-- a `PandocCouldNotFindDataFileError` if it doesn't.
+checkExistence :: PandocMonad m => FilePath -> m FilePath
+checkExistence fn = do
+  exists <- fileExists fn
+  if exists
+     then return fn
+     else throwError $ PandocCouldNotFindDataFileError $ T.pack fn
+#endif
+
+--- | Read file from user data directory or,
+--- if not found there, from the default data files.
+readDataFile :: PandocMonad m => FilePath -> m B.ByteString
+readDataFile fname = do
+  datadir <- checkUserDataDir fname
+  case datadir of
+       Nothing -> readDefaultDataFile fname
+       Just userDir -> do
+         exists <- fileExists (userDir </> fname)
+         if exists
+            then readFileStrict (userDir </> fname)
+            else readDefaultDataFile fname
+
+-- | Retrieve default reference.docx.
+getDefaultReferenceDocx :: PandocMonad m => m Archive
+getDefaultReferenceDocx = do
+  let paths = ["[Content_Types].xml",
+               "_rels/.rels",
+               "docProps/app.xml",
+               "docProps/core.xml",
+               "docProps/custom.xml",
+               "word/document.xml",
+               "word/fontTable.xml",
+               "word/footnotes.xml",
+               "word/comments.xml",
+               "word/numbering.xml",
+               "word/settings.xml",
+               "word/webSettings.xml",
+               "word/styles.xml",
+               "word/_rels/document.xml.rels",
+               "word/_rels/footnotes.xml.rels",
+               "word/theme/theme1.xml"]
+  let toLazy = BL.fromChunks . (:[])
+  let pathToEntry path = do
+        epochtime <- floor . utcTimeToPOSIXSeconds <$> getTimestamp
+        contents <- toLazy <$> readDataFile ("docx/" ++ path)
+        return $ toEntry path epochtime contents
+  datadir <- getUserDataDir
+  mbArchive <- case datadir of
+                    Nothing   -> return Nothing
+                    Just d    -> do
+                       exists <- fileExists (d </> "reference.docx")
+                       if exists
+                          then return (Just (d </> "reference.docx"))
+                          else return Nothing
+  case mbArchive of
+     Just arch -> toArchive <$> readFileLazy arch
+     Nothing   -> foldr addEntryToArchive emptyArchive <$>
+                     mapM pathToEntry paths
+
+-- | Retrieve default reference.odt.
+getDefaultReferenceODT :: PandocMonad m => m Archive
+getDefaultReferenceODT = do
+  let paths = ["mimetype",
+               "manifest.rdf",
+               "styles.xml",
+               "content.xml",
+               "meta.xml",
+               "META-INF/manifest.xml"]
+  let pathToEntry path = do epochtime <- floor `fmap` getPOSIXTime
+                            contents <- (BL.fromChunks . (:[])) `fmap`
+                                          readDataFile ("odt/" ++ path)
+                            return $ toEntry path epochtime contents
+  datadir <- getUserDataDir
+  mbArchive <- case datadir of
+                    Nothing   -> return Nothing
+                    Just d    -> do
+                       exists <- fileExists (d </> "reference.odt")
+                       if exists
+                          then return (Just (d </> "reference.odt"))
+                          else return Nothing
+  case mbArchive of
+     Just arch -> toArchive <$> readFileLazy arch
+     Nothing   -> foldr addEntryToArchive emptyArchive <$>
+                     mapM pathToEntry paths
+
+-- | Retrieve default reference.pptx.
+getDefaultReferencePptx :: PandocMonad m => m Archive
+getDefaultReferencePptx = do
+  -- We're going to narrow this down substantially once we get it
+  -- working.
+  let paths = [ "[Content_Types].xml"
+              , "_rels/.rels"
+              , "docProps/app.xml"
+              , "docProps/core.xml"
+              , "ppt/_rels/presentation.xml.rels"
+              , "ppt/presProps.xml"
+              , "ppt/presentation.xml"
+              , "ppt/slideLayouts/_rels/slideLayout1.xml.rels"
+              , "ppt/slideLayouts/_rels/slideLayout2.xml.rels"
+              , "ppt/slideLayouts/_rels/slideLayout3.xml.rels"
+              , "ppt/slideLayouts/_rels/slideLayout4.xml.rels"
+              , "ppt/slideLayouts/_rels/slideLayout5.xml.rels"
+              , "ppt/slideLayouts/_rels/slideLayout6.xml.rels"
+              , "ppt/slideLayouts/_rels/slideLayout7.xml.rels"
+              , "ppt/slideLayouts/_rels/slideLayout8.xml.rels"
+              , "ppt/slideLayouts/_rels/slideLayout9.xml.rels"
+              , "ppt/slideLayouts/_rels/slideLayout10.xml.rels"
+              , "ppt/slideLayouts/_rels/slideLayout11.xml.rels"
+              , "ppt/slideLayouts/slideLayout1.xml"
+              , "ppt/slideLayouts/slideLayout10.xml"
+              , "ppt/slideLayouts/slideLayout11.xml"
+              , "ppt/slideLayouts/slideLayout2.xml"
+              , "ppt/slideLayouts/slideLayout3.xml"
+              , "ppt/slideLayouts/slideLayout4.xml"
+              , "ppt/slideLayouts/slideLayout5.xml"
+              , "ppt/slideLayouts/slideLayout6.xml"
+              , "ppt/slideLayouts/slideLayout7.xml"
+              , "ppt/slideLayouts/slideLayout8.xml"
+              , "ppt/slideLayouts/slideLayout9.xml"
+              , "ppt/slideMasters/_rels/slideMaster1.xml.rels"
+              , "ppt/slideMasters/slideMaster1.xml"
+              , "ppt/slides/_rels/slide1.xml.rels"
+              , "ppt/slides/slide1.xml"
+              , "ppt/slides/_rels/slide2.xml.rels"
+              , "ppt/slides/slide2.xml"
+              , "ppt/slides/_rels/slide3.xml.rels"
+              , "ppt/slides/slide3.xml"
+              , "ppt/slides/_rels/slide4.xml.rels"
+              , "ppt/slides/slide4.xml"
+              , "ppt/tableStyles.xml"
+              , "ppt/theme/theme1.xml"
+              , "ppt/viewProps.xml"
+              -- These relate to notes slides.
+              , "ppt/notesMasters/notesMaster1.xml"
+              , "ppt/notesMasters/_rels/notesMaster1.xml.rels"
+              , "ppt/notesSlides/notesSlide1.xml"
+              , "ppt/notesSlides/_rels/notesSlide1.xml.rels"
+              , "ppt/notesSlides/notesSlide2.xml"
+              , "ppt/notesSlides/_rels/notesSlide2.xml.rels"
+              , "ppt/theme/theme2.xml"
+              ]
+  let toLazy = BL.fromChunks . (:[])
+  let pathToEntry path = do
+        epochtime <- floor <$> getPOSIXTime
+        contents <- toLazy <$> readDataFile ("pptx/" ++ path)
+        return $ toEntry path epochtime contents
+  datadir <- getUserDataDir
+  mbArchive <- case datadir of
+                    Nothing   -> return Nothing
+                    Just d    -> do
+                       exists <- fileExists (d </> "reference.pptx")
+                       if exists
+                          then return (Just (d </> "reference.pptx"))
+                          else return Nothing
+  case mbArchive of
+     Just arch -> toArchive <$> readFileLazy arch
+     Nothing   -> foldr addEntryToArchive emptyArchive <$>
+                     mapM pathToEntry paths
+
+getDataFileNames :: IO [FilePath]
+getDataFileNames = do
+#ifdef EMBED_DATA_FILES
+  let allDataFiles = map fst dataFiles
+#else
+  allDataFiles <- filter (\x -> x /= "." && x /= "..") <$>
+                      (getDataDir >>= getDirectoryContents)
+#endif
+  return $ "reference.docx" : "reference.odt" : "reference.pptx" : allDataFiles
+
+-- | Return appropriate user data directory for platform.  We use
+-- XDG_DATA_HOME (or its default value), but for backwards compatibility,
+-- we fall back to the legacy user data directory ($HOME/.pandoc on *nix)
+-- if the XDG_DATA_HOME is missing and this exists.  If neither directory
+-- is present, we return the XDG data directory.  If the XDG data directory
+-- is not defined (e.g. because we are in an environment where $HOME is
+-- not defined), we return the empty string.
+defaultUserDataDir :: IO FilePath
+defaultUserDataDir = do
+  xdgDir <- E.catch (getXdgDirectory XdgData "pandoc")
+               (\(_ :: E.SomeException) -> return mempty)
+  xdgExists <- doesDirectoryExist xdgDir
+  legacyDir <- E.catch (getAppUserDataDirectory "pandoc")
+                (\(_ :: E.SomeException) -> return mempty)
+  legacyDirExists <- doesDirectoryExist legacyDir
+  if not xdgExists && legacyDirExists
+     then return legacyDir
+     else return xdgDir
diff --git a/src/Text/Pandoc/Data/BakedIn.hs b/src/Text/Pandoc/Data/BakedIn.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Data/BakedIn.hs
@@ -0,0 +1,32 @@
+{-# LANGUAGE TemplateHaskell #-}
+{- |
+Module      : Text.Pandoc.Data.BakedIn
+Copyright   : Copyright (C) 2013-2024 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.BakedIn (dataFiles) where
+
+import qualified Data.ByteString as B
+import Data.FileEmbed
+import System.FilePath (splitDirectories)
+import qualified System.FilePath.Posix as Posix
+
+-- We ensure that the data files are stored using Posix
+-- path separators (/), even on Windows.
+dataFiles :: [(FilePath, B.ByteString)]
+dataFiles = map (\(fp, contents) ->
+  (Posix.joinPath (splitDirectories fp), contents)) dataFiles'
+
+dataFiles' :: [(FilePath, B.ByteString)]
+dataFiles' = ("MANUAL.txt", $(embedFile "MANUAL.txt")) :
+             -- handle the hidden file separately, since embedDir doesn't
+             -- include it:
+             ("docx/_rels/.rels", $(embedFile "data/docx/_rels/.rels")) :
+             ("pptx/_rels/.rels", $(embedFile "data/pptx/_rels/.rels")) :
+             $(embedDir "data")
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,21 +1,4 @@
-{-
-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
--}
-
+{-# LANGUAGE OverloadedStrings #-}
 {- |
    Module      : Text.Pandoc.Emoji
    Copyright   : Copyright (C) 2015 John MacFarlane
@@ -27,879 +10,15 @@
 
 Emoji symbol lookup from canonical string identifier.
 -}
-module Text.Pandoc.Emoji ( emojis ) where
+module Text.Pandoc.Emoji ( emojis, emojiToInline ) where
+import qualified Text.Emoji as E
+import Text.Pandoc.Definition (Inline (Span, Str))
+import Data.Text (Text)
 import qualified Data.Map as M
 
-emojis :: M.Map String String
-emojis = M.fromList
-  [("+1","\128077")
-  ,("-1","\128078")
-  ,("100","\128175")
-  ,("1234","\128290")
-  ,("8ball","\127921")
-  ,("a","\127344\65039")
-  ,("ab","\127374")
-  ,("abc","\128292")
-  ,("abcd","\128289")
-  ,("accept","\127569")
-  ,("aerial_tramway","\128673")
-  ,("airplane","\9992\65039")
-  ,("alarm_clock","\9200")
-  ,("alien","\128125")
-  ,("ambulance","\128657")
-  ,("anchor","\9875")
-  ,("angel","\128124")
-  ,("anger","\128162")
-  ,("angry","\128544")
-  ,("anguished","\128551")
-  ,("ant","\128028")
-  ,("apple","\127822")
-  ,("aquarius","\9810")
-  ,("aries","\9800")
-  ,("arrow_backward","\9664\65039")
-  ,("arrow_double_down","\9196")
-  ,("arrow_double_up","\9195")
-  ,("arrow_down","\11015\65039")
-  ,("arrow_down_small","\128317")
-  ,("arrow_forward","\9654\65039")
-  ,("arrow_heading_down","\10549\65039")
-  ,("arrow_heading_up","\10548\65039")
-  ,("arrow_left","\11013\65039")
-  ,("arrow_lower_left","\8601\65039")
-  ,("arrow_lower_right","\8600\65039")
-  ,("arrow_right","\10145\65039")
-  ,("arrow_right_hook","\8618\65039")
-  ,("arrow_up","\11014\65039")
-  ,("arrow_up_down","\8597\65039")
-  ,("arrow_up_small","\128316")
-  ,("arrow_upper_left","\8598\65039")
-  ,("arrow_upper_right","\8599\65039")
-  ,("arrows_clockwise","\128259")
-  ,("arrows_counterclockwise","\128260")
-  ,("art","\127912")
-  ,("articulated_lorry","\128667")
-  ,("astonished","\128562")
-  ,("athletic_shoe","\128095")
-  ,("atm","\127975")
-  ,("b","\127345\65039")
-  ,("baby","\128118")
-  ,("baby_bottle","\127868")
-  ,("baby_chick","\128036")
-  ,("baby_symbol","\128700")
-  ,("back","\128281")
-  ,("baggage_claim","\128708")
-  ,("balloon","\127880")
-  ,("ballot_box_with_check","\9745\65039")
-  ,("bamboo","\127885")
-  ,("banana","\127820")
-  ,("bangbang","\8252\65039")
-  ,("bank","\127974")
-  ,("bar_chart","\128202")
-  ,("barber","\128136")
-  ,("baseball","\9918\65039")
-  ,("basketball","\127936")
-  ,("bath","\128704")
-  ,("bathtub","\128705")
-  ,("battery","\128267")
-  ,("bear","\128059")
-  ,("bee","\128029")
-  ,("beer","\127866")
-  ,("beers","\127867")
-  ,("beetle","\128030")
-  ,("beginner","\128304")
-  ,("bell","\128276")
-  ,("bento","\127857")
-  ,("bicyclist","\128692")
-  ,("bike","\128690")
-  ,("bikini","\128089")
-  ,("bird","\128038")
-  ,("birthday","\127874")
-  ,("black_circle","\9899")
-  ,("black_joker","\127183")
-  ,("black_large_square","\11035")
-  ,("black_medium_small_square","\9726")
-  ,("black_medium_square","\9724\65039")
-  ,("black_nib","\10002\65039")
-  ,("black_small_square","\9642\65039")
-  ,("black_square_button","\128306")
-  ,("blossom","\127804")
-  ,("blowfish","\128033")
-  ,("blue_book","\128216")
-  ,("blue_car","\128665")
-  ,("blue_heart","\128153")
-  ,("blush","\128522")
-  ,("boar","\128023")
-  ,("boat","\9973")
-  ,("bomb","\128163")
-  ,("book","\128214")
-  ,("bookmark","\128278")
-  ,("bookmark_tabs","\128209")
-  ,("books","\128218")
-  ,("boom","\128165")
-  ,("boot","\128098")
-  ,("bouquet","\128144")
-  ,("bow","\128583")
-  ,("bowling","\127923")
-  ,("boy","\128102")
-  ,("bread","\127838")
-  ,("bride_with_veil","\128112")
-  ,("bridge_at_night","\127753")
-  ,("briefcase","\128188")
-  ,("broken_heart","\128148")
-  ,("bug","\128027")
-  ,("bulb","\128161")
-  ,("bullettrain_front","\128645")
-  ,("bullettrain_side","\128644")
-  ,("bus","\128652")
-  ,("busstop","\128655")
-  ,("bust_in_silhouette","\128100")
-  ,("busts_in_silhouette","\128101")
-  ,("cactus","\127797")
-  ,("cake","\127856")
-  ,("calendar","\128198")
-  ,("calling","\128242")
-  ,("camel","\128043")
-  ,("camera","\128247")
-  ,("cancer","\9803")
-  ,("candy","\127852")
-  ,("capital_abcd","\128288")
-  ,("capricorn","\9809")
-  ,("car","\128663")
-  ,("card_index","\128199")
-  ,("carousel_horse","\127904")
-  ,("cat","\128049")
-  ,("cat2","\128008")
-  ,("cd","\128191")
-  ,("chart","\128185")
-  ,("chart_with_downwards_trend","\128201")
-  ,("chart_with_upwards_trend","\128200")
-  ,("checkered_flag","\127937")
-  ,("cherries","\127826")
-  ,("cherry_blossom","\127800")
-  ,("chestnut","\127792")
-  ,("chicken","\128020")
-  ,("children_crossing","\128696")
-  ,("chocolate_bar","\127851")
-  ,("christmas_tree","\127876")
-  ,("church","\9962")
-  ,("cinema","\127910")
-  ,("circus_tent","\127914")
-  ,("city_sunrise","\127751")
-  ,("city_sunset","\127750")
-  ,("cl","\127377")
-  ,("clap","\128079")
-  ,("clapper","\127916")
-  ,("clipboard","\128203")
-  ,("clock1","\128336")
-  ,("clock10","\128345")
-  ,("clock1030","\128357")
-  ,("clock11","\128346")
-  ,("clock1130","\128358")
-  ,("clock12","\128347")
-  ,("clock1230","\128359")
-  ,("clock130","\128348")
-  ,("clock2","\128337")
-  ,("clock230","\128349")
-  ,("clock3","\128338")
-  ,("clock330","\128350")
-  ,("clock4","\128339")
-  ,("clock430","\128351")
-  ,("clock5","\128340")
-  ,("clock530","\128352")
-  ,("clock6","\128341")
-  ,("clock630","\128353")
-  ,("clock7","\128342")
-  ,("clock730","\128354")
-  ,("clock8","\128343")
-  ,("clock830","\128355")
-  ,("clock9","\128344")
-  ,("clock930","\128356")
-  ,("closed_book","\128213")
-  ,("closed_lock_with_key","\128272")
-  ,("closed_umbrella","\127746")
-  ,("cloud","\9729\65039")
-  ,("clubs","\9827\65039")
-  ,("cn","\127464\127475")
-  ,("cocktail","\127864")
-  ,("coffee","\9749")
-  ,("cold_sweat","\128560")
-  ,("collision","\128165")
-  ,("computer","\128187")
-  ,("confetti_ball","\127882")
-  ,("confounded","\128534")
-  ,("confused","\128533")
-  ,("congratulations","\12951\65039")
-  ,("construction","\128679")
-  ,("construction_worker","\128119")
-  ,("convenience_store","\127978")
-  ,("cookie","\127850")
-  ,("cool","\127378")
-  ,("cop","\128110")
-  ,("copyright","\169\65039")
-  ,("corn","\127805")
-  ,("couple","\128107")
-  ,("couple_with_heart","\128145")
-  ,("couplekiss","\128143")
-  ,("cow","\128046")
-  ,("cow2","\128004")
-  ,("credit_card","\128179")
-  ,("crescent_moon","\127769")
-  ,("crocodile","\128010")
-  ,("crossed_flags","\127884")
-  ,("crown","\128081")
-  ,("cry","\128546")
-  ,("crying_cat_face","\128575")
-  ,("crystal_ball","\128302")
-  ,("cupid","\128152")
-  ,("curly_loop","\10160")
-  ,("currency_exchange","\128177")
-  ,("curry","\127835")
-  ,("custard","\127854")
-  ,("customs","\128707")
-  ,("cyclone","\127744")
-  ,("dancer","\128131")
-  ,("dancers","\128111")
-  ,("dango","\127841")
-  ,("dart","\127919")
-  ,("dash","\128168")
-  ,("date","\128197")
-  ,("de","\127465\127466")
-  ,("deciduous_tree","\127795")
-  ,("department_store","\127980")
-  ,("diamond_shape_with_a_dot_inside","\128160")
-  ,("diamonds","\9830\65039")
-  ,("disappointed","\128542")
-  ,("disappointed_relieved","\128549")
-  ,("dizzy","\128171")
-  ,("dizzy_face","\128565")
-  ,("do_not_litter","\128687")
-  ,("dog","\128054")
-  ,("dog2","\128021")
-  ,("dollar","\128181")
-  ,("dolls","\127886")
-  ,("dolphin","\128044")
-  ,("door","\128682")
-  ,("doughnut","\127849")
-  ,("dragon","\128009")
-  ,("dragon_face","\128050")
-  ,("dress","\128087")
-  ,("dromedary_camel","\128042")
-  ,("droplet","\128167")
-  ,("dvd","\128192")
-  ,("e-mail","\128231")
-  ,("ear","\128066")
-  ,("ear_of_rice","\127806")
-  ,("earth_africa","\127757")
-  ,("earth_americas","\127758")
-  ,("earth_asia","\127759")
-  ,("egg","\127859")
-  ,("eggplant","\127814")
-  ,("eight","8\65039\8419")
-  ,("eight_pointed_black_star","\10036\65039")
-  ,("eight_spoked_asterisk","\10035\65039")
-  ,("electric_plug","\128268")
-  ,("elephant","\128024")
-  ,("email","\9993\65039")
-  ,("end","\128282")
-  ,("envelope","\9993\65039")
-  ,("envelope_with_arrow","\128233")
-  ,("es","\127466\127480")
-  ,("euro","\128182")
-  ,("european_castle","\127984")
-  ,("european_post_office","\127972")
-  ,("evergreen_tree","\127794")
-  ,("exclamation","\10071")
-  ,("expressionless","\128529")
-  ,("eyeglasses","\128083")
-  ,("eyes","\128064")
-  ,("facepunch","\128074")
-  ,("factory","\127981")
-  ,("fallen_leaf","\127810")
-  ,("family","\128106")
-  ,("fast_forward","\9193")
-  ,("fax","\128224")
-  ,("fearful","\128552")
-  ,("feet","\128062")
-  ,("ferris_wheel","\127905")
-  ,("file_folder","\128193")
-  ,("fire","\128293")
-  ,("fire_engine","\128658")
-  ,("fireworks","\127878")
-  ,("first_quarter_moon","\127763")
-  ,("first_quarter_moon_with_face","\127771")
-  ,("fish","\128031")
-  ,("fish_cake","\127845")
-  ,("fishing_pole_and_fish","\127907")
-  ,("fist","\9994")
-  ,("five","5\65039\8419")
-  ,("flags","\127887")
-  ,("flashlight","\128294")
-  ,("flipper","\128044")
-  ,("floppy_disk","\128190")
-  ,("flower_playing_cards","\127924")
-  ,("flushed","\128563")
-  ,("foggy","\127745")
-  ,("football","\127944")
-  ,("footprints","\128099")
-  ,("fork_and_knife","\127860")
-  ,("fountain","\9970")
-  ,("four","4\65039\8419")
-  ,("four_leaf_clover","\127808")
-  ,("fr","\127467\127479")
-  ,("free","\127379")
-  ,("fried_shrimp","\127844")
-  ,("fries","\127839")
-  ,("frog","\128056")
-  ,("frowning","\128550")
-  ,("fuelpump","\9981")
-  ,("full_moon","\127765")
-  ,("full_moon_with_face","\127773")
-  ,("game_die","\127922")
-  ,("gb","\127468\127463")
-  ,("gem","\128142")
-  ,("gemini","\9802")
-  ,("ghost","\128123")
-  ,("gift","\127873")
-  ,("gift_heart","\128157")
-  ,("girl","\128103")
-  ,("globe_with_meridians","\127760")
-  ,("goat","\128016")
-  ,("golf","\9971")
-  ,("grapes","\127815")
-  ,("green_apple","\127823")
-  ,("green_book","\128215")
-  ,("green_heart","\128154")
-  ,("grey_exclamation","\10069")
-  ,("grey_question","\10068")
-  ,("grimacing","\128556")
-  ,("grin","\128513")
-  ,("grinning","\128512")
-  ,("guardsman","\128130")
-  ,("guitar","\127928")
-  ,("gun","\128299")
-  ,("haircut","\128135")
-  ,("hamburger","\127828")
-  ,("hammer","\128296")
-  ,("hamster","\128057")
-  ,("hand","\9995")
-  ,("handbag","\128092")
-  ,("hankey","\128169")
-  ,("hash","#\65039\8419")
-  ,("hatched_chick","\128037")
-  ,("hatching_chick","\128035")
-  ,("headphones","\127911")
-  ,("hear_no_evil","\128585")
-  ,("heart","\10084\65039")
-  ,("heart_decoration","\128159")
-  ,("heart_eyes","\128525")
-  ,("heart_eyes_cat","\128571")
-  ,("heartbeat","\128147")
-  ,("heartpulse","\128151")
-  ,("hearts","\9829\65039")
-  ,("heavy_check_mark","\10004\65039")
-  ,("heavy_division_sign","\10135")
-  ,("heavy_dollar_sign","\128178")
-  ,("heavy_exclamation_mark","\10071")
-  ,("heavy_minus_sign","\10134")
-  ,("heavy_multiplication_x","\10006\65039")
-  ,("heavy_plus_sign","\10133")
-  ,("helicopter","\128641")
-  ,("herb","\127807")
-  ,("hibiscus","\127802")
-  ,("high_brightness","\128262")
-  ,("high_heel","\128096")
-  ,("hocho","\128298")
-  ,("honey_pot","\127855")
-  ,("honeybee","\128029")
-  ,("horse","\128052")
-  ,("horse_racing","\127943")
-  ,("hospital","\127973")
-  ,("hotel","\127976")
-  ,("hotsprings","\9832\65039")
-  ,("hourglass","\8987")
-  ,("hourglass_flowing_sand","\9203")
-  ,("house","\127968")
-  ,("house_with_garden","\127969")
-  ,("hushed","\128559")
-  ,("ice_cream","\127848")
-  ,("icecream","\127846")
-  ,("id","\127380")
-  ,("ideograph_advantage","\127568")
-  ,("imp","\128127")
-  ,("inbox_tray","\128229")
-  ,("incoming_envelope","\128232")
-  ,("information_desk_person","\128129")
-  ,("information_source","\8505\65039")
-  ,("innocent","\128519")
-  ,("interrobang","\8265\65039")
-  ,("iphone","\128241")
-  ,("it","\127470\127481")
-  ,("izakaya_lantern","\127982")
-  ,("jack_o_lantern","\127875")
-  ,("japan","\128510")
-  ,("japanese_castle","\127983")
-  ,("japanese_goblin","\128122")
-  ,("japanese_ogre","\128121")
-  ,("jeans","\128086")
-  ,("joy","\128514")
-  ,("joy_cat","\128569")
-  ,("jp","\127471\127477")
-  ,("key","\128273")
-  ,("keycap_ten","\128287")
-  ,("kimono","\128088")
-  ,("kiss","\128139")
-  ,("kissing","\128535")
-  ,("kissing_cat","\128573")
-  ,("kissing_closed_eyes","\128538")
-  ,("kissing_heart","\128536")
-  ,("kissing_smiling_eyes","\128537")
-  ,("knife","\128298")
-  ,("koala","\128040")
-  ,("koko","\127489")
-  ,("kr","\127472\127479")
-  ,("lantern","\127982")
-  ,("large_blue_circle","\128309")
-  ,("large_blue_diamond","\128311")
-  ,("large_orange_diamond","\128310")
-  ,("last_quarter_moon","\127767")
-  ,("last_quarter_moon_with_face","\127772")
-  ,("laughing","\128518")
-  ,("leaves","\127811")
-  ,("ledger","\128210")
-  ,("left_luggage","\128709")
-  ,("left_right_arrow","\8596\65039")
-  ,("leftwards_arrow_with_hook","\8617\65039")
-  ,("lemon","\127819")
-  ,("leo","\9804")
-  ,("leopard","\128006")
-  ,("libra","\9806")
-  ,("light_rail","\128648")
-  ,("link","\128279")
-  ,("lips","\128068")
-  ,("lipstick","\128132")
-  ,("lock","\128274")
-  ,("lock_with_ink_pen","\128271")
-  ,("lollipop","\127853")
-  ,("loop","\10175")
-  ,("loud_sound","\128266")
-  ,("loudspeaker","\128226")
-  ,("love_hotel","\127977")
-  ,("love_letter","\128140")
-  ,("low_brightness","\128261")
-  ,("m","\9410\65039")
-  ,("mag","\128269")
-  ,("mag_right","\128270")
-  ,("mahjong","\126980")
-  ,("mailbox","\128235")
-  ,("mailbox_closed","\128234")
-  ,("mailbox_with_mail","\128236")
-  ,("mailbox_with_no_mail","\128237")
-  ,("man","\128104")
-  ,("man_with_gua_pi_mao","\128114")
-  ,("man_with_turban","\128115")
-  ,("mans_shoe","\128094")
-  ,("maple_leaf","\127809")
-  ,("mask","\128567")
-  ,("massage","\128134")
-  ,("meat_on_bone","\127830")
-  ,("mega","\128227")
-  ,("melon","\127816")
-  ,("memo","\128221")
-  ,("mens","\128697")
-  ,("metro","\128647")
-  ,("microphone","\127908")
-  ,("microscope","\128300")
-  ,("milky_way","\127756")
-  ,("minibus","\128656")
-  ,("minidisc","\128189")
-  ,("mobile_phone_off","\128244")
-  ,("money_with_wings","\128184")
-  ,("moneybag","\128176")
-  ,("monkey","\128018")
-  ,("monkey_face","\128053")
-  ,("monorail","\128669")
-  ,("moon","\127764")
-  ,("mortar_board","\127891")
-  ,("mount_fuji","\128507")
-  ,("mountain_bicyclist","\128693")
-  ,("mountain_cableway","\128672")
-  ,("mountain_railway","\128670")
-  ,("mouse","\128045")
-  ,("mouse2","\128001")
-  ,("movie_camera","\127909")
-  ,("moyai","\128511")
-  ,("muscle","\128170")
-  ,("mushroom","\127812")
-  ,("musical_keyboard","\127929")
-  ,("musical_note","\127925")
-  ,("musical_score","\127932")
-  ,("mute","\128263")
-  ,("nail_care","\128133")
-  ,("name_badge","\128219")
-  ,("necktie","\128084")
-  ,("negative_squared_cross_mark","\10062")
-  ,("neutral_face","\128528")
-  ,("new","\127381")
-  ,("new_moon","\127761")
-  ,("new_moon_with_face","\127770")
-  ,("newspaper","\128240")
-  ,("ng","\127382")
-  ,("night_with_stars","\127747")
-  ,("nine","9\65039\8419")
-  ,("no_bell","\128277")
-  ,("no_bicycles","\128691")
-  ,("no_entry","\9940")
-  ,("no_entry_sign","\128683")
-  ,("no_good","\128581")
-  ,("no_mobile_phones","\128245")
-  ,("no_mouth","\128566")
-  ,("no_pedestrians","\128695")
-  ,("no_smoking","\128685")
-  ,("non-potable_water","\128689")
-  ,("nose","\128067")
-  ,("notebook","\128211")
-  ,("notebook_with_decorative_cover","\128212")
-  ,("notes","\127926")
-  ,("nut_and_bolt","\128297")
-  ,("o","\11093")
-  ,("o2","\127358\65039")
-  ,("ocean","\127754")
-  ,("octopus","\128025")
-  ,("oden","\127842")
-  ,("office","\127970")
-  ,("ok","\127383")
-  ,("ok_hand","\128076")
-  ,("ok_woman","\128582")
-  ,("older_man","\128116")
-  ,("older_woman","\128117")
-  ,("on","\128283")
-  ,("oncoming_automobile","\128664")
-  ,("oncoming_bus","\128653")
-  ,("oncoming_police_car","\128660")
-  ,("oncoming_taxi","\128662")
-  ,("one","1\65039\8419")
-  ,("open_book","\128214")
-  ,("open_file_folder","\128194")
-  ,("open_hands","\128080")
-  ,("open_mouth","\128558")
-  ,("ophiuchus","\9934")
-  ,("orange_book","\128217")
-  ,("outbox_tray","\128228")
-  ,("ox","\128002")
-  ,("package","\128230")
-  ,("page_facing_up","\128196")
-  ,("page_with_curl","\128195")
-  ,("pager","\128223")
-  ,("palm_tree","\127796")
-  ,("panda_face","\128060")
-  ,("paperclip","\128206")
-  ,("parking","\127359\65039")
-  ,("part_alternation_mark","\12349\65039")
-  ,("partly_sunny","\9925")
-  ,("passport_control","\128706")
-  ,("paw_prints","\128062")
-  ,("peach","\127825")
-  ,("pear","\127824")
-  ,("pencil","\128221")
-  ,("pencil2","\9999\65039")
-  ,("penguin","\128039")
-  ,("pensive","\128532")
-  ,("performing_arts","\127917")
-  ,("persevere","\128547")
-  ,("person_frowning","\128589")
-  ,("person_with_blond_hair","\128113")
-  ,("person_with_pouting_face","\128590")
-  ,("phone","\9742\65039")
-  ,("pig","\128055")
-  ,("pig2","\128022")
-  ,("pig_nose","\128061")
-  ,("pill","\128138")
-  ,("pineapple","\127821")
-  ,("pisces","\9811")
-  ,("pizza","\127829")
-  ,("point_down","\128071")
-  ,("point_left","\128072")
-  ,("point_right","\128073")
-  ,("point_up","\9757\65039")
-  ,("point_up_2","\128070")
-  ,("police_car","\128659")
-  ,("poodle","\128041")
-  ,("poop","\128169")
-  ,("post_office","\127971")
-  ,("postal_horn","\128239")
-  ,("postbox","\128238")
-  ,("potable_water","\128688")
-  ,("pouch","\128093")
-  ,("poultry_leg","\127831")
-  ,("pound","\128183")
-  ,("pouting_cat","\128574")
-  ,("pray","\128591")
-  ,("princess","\128120")
-  ,("punch","\128074")
-  ,("purple_heart","\128156")
-  ,("purse","\128091")
-  ,("pushpin","\128204")
-  ,("put_litter_in_its_place","\128686")
-  ,("question","\10067")
-  ,("rabbit","\128048")
-  ,("rabbit2","\128007")
-  ,("racehorse","\128014")
-  ,("radio","\128251")
-  ,("radio_button","\128280")
-  ,("rage","\128545")
-  ,("railway_car","\128643")
-  ,("rainbow","\127752")
-  ,("raised_hand","\9995")
-  ,("raised_hands","\128588")
-  ,("raising_hand","\128587")
-  ,("ram","\128015")
-  ,("ramen","\127836")
-  ,("rat","\128000")
-  ,("recycle","\9851\65039")
-  ,("red_car","\128663")
-  ,("red_circle","\128308")
-  ,("registered","\174\65039")
-  ,("relaxed","\9786\65039")
-  ,("relieved","\128524")
-  ,("repeat","\128257")
-  ,("repeat_one","\128258")
-  ,("restroom","\128699")
-  ,("revolving_hearts","\128158")
-  ,("rewind","\9194")
-  ,("ribbon","\127872")
-  ,("rice","\127834")
-  ,("rice_ball","\127833")
-  ,("rice_cracker","\127832")
-  ,("rice_scene","\127889")
-  ,("ring","\128141")
-  ,("rocket","\128640")
-  ,("roller_coaster","\127906")
-  ,("rooster","\128019")
-  ,("rose","\127801")
-  ,("rotating_light","\128680")
-  ,("round_pushpin","\128205")
-  ,("rowboat","\128675")
-  ,("ru","\127479\127482")
-  ,("rugby_football","\127945")
-  ,("runner","\127939")
-  ,("running","\127939")
-  ,("running_shirt_with_sash","\127933")
-  ,("sa","\127490\65039")
-  ,("sagittarius","\9808")
-  ,("sailboat","\9973")
-  ,("sake","\127862")
-  ,("sandal","\128097")
-  ,("santa","\127877")
-  ,("satellite","\128225")
-  ,("satisfied","\128518")
-  ,("saxophone","\127927")
-  ,("school","\127979")
-  ,("school_satchel","\127890")
-  ,("scissors","\9986\65039")
-  ,("scorpius","\9807")
-  ,("scream","\128561")
-  ,("scream_cat","\128576")
-  ,("scroll","\128220")
-  ,("seat","\128186")
-  ,("secret","\12953\65039")
-  ,("see_no_evil","\128584")
-  ,("seedling","\127793")
-  ,("seven","7\65039\8419")
-  ,("shaved_ice","\127847")
-  ,("sheep","\128017")
-  ,("shell","\128026")
-  ,("ship","\128674")
-  ,("shirt","\128085")
-  ,("shit","\128169")
-  ,("shoe","\128094")
-  ,("shower","\128703")
-  ,("signal_strength","\128246")
-  ,("six","6\65039\8419")
-  ,("six_pointed_star","\128303")
-  ,("ski","\127935")
-  ,("skull","\128128")
-  ,("sleeping","\128564")
-  ,("sleepy","\128554")
-  ,("slot_machine","\127920")
-  ,("small_blue_diamond","\128313")
-  ,("small_orange_diamond","\128312")
-  ,("small_red_triangle","\128314")
-  ,("small_red_triangle_down","\128315")
-  ,("smile","\128516")
-  ,("smile_cat","\128568")
-  ,("smiley","\128515")
-  ,("smiley_cat","\128570")
-  ,("smiling_imp","\128520")
-  ,("smirk","\128527")
-  ,("smirk_cat","\128572")
-  ,("smoking","\128684")
-  ,("snail","\128012")
-  ,("snake","\128013")
-  ,("snowboarder","\127938")
-  ,("snowflake","\10052\65039")
-  ,("snowman","\9924")
-  ,("sob","\128557")
-  ,("soccer","\9917")
-  ,("soon","\128284")
-  ,("sos","\127384")
-  ,("sound","\128265")
-  ,("space_invader","\128126")
-  ,("spades","\9824\65039")
-  ,("spaghetti","\127837")
-  ,("sparkle","\10055\65039")
-  ,("sparkler","\127879")
-  ,("sparkles","\10024")
-  ,("sparkling_heart","\128150")
-  ,("speak_no_evil","\128586")
-  ,("speaker","\128264")
-  ,("speech_balloon","\128172")
-  ,("speedboat","\128676")
-  ,("star","\11088")
-  ,("star2","\127775")
-  ,("stars","\127776")
-  ,("station","\128649")
-  ,("statue_of_liberty","\128509")
-  ,("steam_locomotive","\128642")
-  ,("stew","\127858")
-  ,("straight_ruler","\128207")
-  ,("strawberry","\127827")
-  ,("stuck_out_tongue","\128539")
-  ,("stuck_out_tongue_closed_eyes","\128541")
-  ,("stuck_out_tongue_winking_eye","\128540")
-  ,("sun_with_face","\127774")
-  ,("sunflower","\127803")
-  ,("sunglasses","\128526")
-  ,("sunny","\9728\65039")
-  ,("sunrise","\127749")
-  ,("sunrise_over_mountains","\127748")
-  ,("surfer","\127940")
-  ,("sushi","\127843")
-  ,("suspension_railway","\128671")
-  ,("sweat","\128531")
-  ,("sweat_drops","\128166")
-  ,("sweat_smile","\128517")
-  ,("sweet_potato","\127840")
-  ,("swimmer","\127946")
-  ,("symbols","\128291")
-  ,("syringe","\128137")
-  ,("tada","\127881")
-  ,("tanabata_tree","\127883")
-  ,("tangerine","\127818")
-  ,("taurus","\9801")
-  ,("taxi","\128661")
-  ,("tea","\127861")
-  ,("telephone","\9742\65039")
-  ,("telephone_receiver","\128222")
-  ,("telescope","\128301")
-  ,("tennis","\127934")
-  ,("tent","\9978")
-  ,("thought_balloon","\128173")
-  ,("three","3\65039\8419")
-  ,("thumbsdown","\128078")
-  ,("thumbsup","\128077")
-  ,("ticket","\127915")
-  ,("tiger","\128047")
-  ,("tiger2","\128005")
-  ,("tired_face","\128555")
-  ,("tm","\8482\65039")
-  ,("toilet","\128701")
-  ,("tokyo_tower","\128508")
-  ,("tomato","\127813")
-  ,("tongue","\128069")
-  ,("top","\128285")
-  ,("tophat","\127913")
-  ,("tractor","\128668")
-  ,("traffic_light","\128677")
-  ,("train","\128651")
-  ,("train2","\128646")
-  ,("tram","\128650")
-  ,("triangular_flag_on_post","\128681")
-  ,("triangular_ruler","\128208")
-  ,("trident","\128305")
-  ,("triumph","\128548")
-  ,("trolleybus","\128654")
-  ,("trophy","\127942")
-  ,("tropical_drink","\127865")
-  ,("tropical_fish","\128032")
-  ,("truck","\128666")
-  ,("trumpet","\127930")
-  ,("tshirt","\128085")
-  ,("tulip","\127799")
-  ,("turtle","\128034")
-  ,("tv","\128250")
-  ,("twisted_rightwards_arrows","\128256")
-  ,("two","2\65039\8419")
-  ,("two_hearts","\128149")
-  ,("two_men_holding_hands","\128108")
-  ,("two_women_holding_hands","\128109")
-  ,("u5272","\127545")
-  ,("u5408","\127540")
-  ,("u55b6","\127546")
-  ,("u6307","\127535")
-  ,("u6708","\127543\65039")
-  ,("u6709","\127542")
-  ,("u6e80","\127541")
-  ,("u7121","\127514")
-  ,("u7533","\127544")
-  ,("u7981","\127538")
-  ,("u7a7a","\127539")
-  ,("uk","\127468\127463")
-  ,("umbrella","\9748")
-  ,("unamused","\128530")
-  ,("underage","\128286")
-  ,("unlock","\128275")
-  ,("up","\127385")
-  ,("us","\127482\127480")
-  ,("v","\9996\65039")
-  ,("vertical_traffic_light","\128678")
-  ,("vhs","\128252")
-  ,("vibration_mode","\128243")
-  ,("video_camera","\128249")
-  ,("video_game","\127918")
-  ,("violin","\127931")
-  ,("virgo","\9805")
-  ,("volcano","\127755")
-  ,("vs","\127386")
-  ,("walking","\128694")
-  ,("waning_crescent_moon","\127768")
-  ,("waning_gibbous_moon","\127766")
-  ,("warning","\9888\65039")
-  ,("watch","\8986")
-  ,("water_buffalo","\128003")
-  ,("watermelon","\127817")
-  ,("wave","\128075")
-  ,("wavy_dash","\12336\65039")
-  ,("waxing_crescent_moon","\127762")
-  ,("waxing_gibbous_moon","\127764")
-  ,("wc","\128702")
-  ,("weary","\128553")
-  ,("wedding","\128146")
-  ,("whale","\128051")
-  ,("whale2","\128011")
-  ,("wheelchair","\9855")
-  ,("white_check_mark","\9989")
-  ,("white_circle","\9898")
-  ,("white_flower","\128174")
-  ,("white_large_square","\11036")
-  ,("white_medium_small_square","\9725")
-  ,("white_medium_square","\9723\65039")
-  ,("white_small_square","\9643\65039")
-  ,("white_square_button","\128307")
-  ,("wind_chime","\127888")
-  ,("wine_glass","\127863")
-  ,("wink","\128521")
-  ,("wolf","\128058")
-  ,("woman","\128105")
-  ,("womans_clothes","\128090")
-  ,("womans_hat","\128082")
-  ,("womens","\128698")
-  ,("worried","\128543")
-  ,("wrench","\128295")
-  ,("x","\10060")
-  ,("yellow_heart","\128155")
-  ,("yen","\128180")
-  ,("yum","\128523")
-  ,("zap","\9889")
-  ,("zero","0\65039\8419")
-  ,("zzz","\128164")
-  ]
+emojis :: M.Map Text Text
+emojis = M.fromList E.emojis
+
+emojiToInline :: Text -> Maybe Inline
+emojiToInline emojikey = makeSpan <$> E.emojiFromAlias emojikey
+  where makeSpan = Span ("", ["emoji"], [("data-emoji", emojikey)]) . (:[]) . Str
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,122 +1,207 @@
 {-# LANGUAGE DeriveDataTypeable #-}
 {-# LANGUAGE DeriveGeneric      #-}
-{-
-Copyright (C) 2006-2017 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 OverloadedStrings  #-}
 {- |
    Module      : Text.Pandoc.Error
-   Copyright   : Copyright (C) 2006-2017 John MacFarlane
+   Copyright   : Copyright (C) 2006-2024 John MacFarlane
    License     : GNU GPL, version 2 or above
 
    Maintainer  : John MacFarlane <jgm@berkeley.edu>
    Stability   : alpha
    Portability : portable
 
-This module provides a standard way to deal with possible errors encounted
-during parsing.
+This module provides a standard way to deal with possible errors
+encountered during parsing.
 
 -}
 module Text.Pandoc.Error (
   PandocError(..),
+  renderError,
   handleError) where
 
-import Control.Exception (Exception)
+import Control.Exception (Exception, displayException)
 import Data.Typeable (Typeable)
+import Data.Word (Word8)
+import Data.Text (Text)
+import qualified Data.Text as T
 import GHC.Generics (Generic)
-import Network.HTTP.Client (HttpException)
 import System.Exit (ExitCode (..), exitWith)
 import System.IO (stderr)
 import qualified Text.Pandoc.UTF8 as UTF8
-import Text.Parsec.Error
-import Text.Parsec.Pos hiding (Line)
-
-type Input = String
+import Text.Printf (printf)
+import Text.Pandoc.Shared (tshow)
+import Citeproc (CiteprocError, prettyCiteprocError)
 
-data PandocError = PandocIOError String IOError
-                 | PandocHttpError String HttpException
-                 | PandocShouldNeverHappenError String
-                 | PandocSomeError String
-                 | PandocParseError String
-                 | PandocParsecError Input ParseError
-                 | PandocMakePDFError String
-                 | PandocOptionError String
-                 | PandocSyntaxMapError String
+data PandocError = PandocIOError Text IOError
+                 | PandocHttpError Text Text
+                 | PandocShouldNeverHappenError Text
+                 | PandocSomeError Text
+                 | PandocParseError Text
+                 | PandocMakePDFError Text
+                 | PandocOptionError Text
+                 | PandocSyntaxMapError Text
                  | PandocFailOnWarningError
-                 | PandocPDFProgramNotFoundError String
-                 | PandocPDFError String
-                 | PandocFilterError String String
-                 | PandocCouldNotFindDataFileError String
-                 | PandocResourceNotFound String
-                 | PandocTemplateError String
-                 | PandocAppError String
-                 | PandocEpubSubdirectoryError String
-                 | PandocMacroLoop String
+                 | PandocPDFProgramNotFoundError Text
+                 | PandocPDFError Text
+                 | PandocXMLError Text Text
+                 | PandocFilterError Text Text
+                 | PandocLuaError Text
+                 | PandocNoScriptingEngine
+                 | PandocCouldNotFindDataFileError Text
+                 | PandocCouldNotFindMetadataFileError Text
+                 | PandocResourceNotFound Text
+                 | PandocTemplateError Text
+                 | PandocNoTemplateError Text
+                 | PandocAppError Text
+                 | PandocEpubSubdirectoryError Text
+                 | PandocMacroLoop Text
+                 | PandocUTF8DecodingError Text Int Word8
+                 | PandocIpynbDecodingError Text
+                 | PandocUnsupportedCharsetError Text
+                 | PandocFormatError Text Text
+                 | PandocUnknownReaderError Text
+                 | PandocUnknownWriterError Text
+                 | PandocUnsupportedExtensionError Text Text
+                 | PandocCiteprocError CiteprocError
+                 | PandocBibliographyError Text Text
+                 | PandocInputNotTextError Text
                  deriving (Show, Typeable, Generic)
 
 instance Exception PandocError
+ where
+   displayException = T.unpack . renderError
 
+renderError :: PandocError -> Text
+renderError e =
+  case e of
+    PandocIOError _ err' -> T.pack $ displayException err'
+    PandocHttpError u err' -> "Could not fetch " <> u <> "\n" <> err'
+    PandocShouldNeverHappenError s ->
+      "Something we thought was impossible happened!\n" <>
+      "Please report this to pandoc's developers: " <> s
+    PandocSomeError s -> s
+    PandocParseError s -> s
+    PandocMakePDFError s -> s
+    PandocOptionError s -> s
+    PandocSyntaxMapError s -> s
+    PandocFailOnWarningError -> "Failing because there were warnings."
+    PandocPDFProgramNotFoundError pdfprog ->
+        quote pdfprog <> " not found. Please select a different --pdf-engine or install "
+        <> quote pdfprog
+    PandocPDFError logmsg -> "Error producing PDF.\n" <> logmsg
+    PandocXMLError fp logmsg -> "Invalid XML" <>
+        (if T.null fp then "" else " in " <> quote fp) <> ":\n" <> logmsg
+    PandocFilterError filtername msg -> "Error running filter " <>
+        quote filtername <> ":\n" <> msg
+    PandocLuaError msg -> "Error running Lua:\n" <> msg
+    PandocNoScriptingEngine -> "This version of pandoc has been compiled " <>
+                               "without Lua support."
+    PandocCouldNotFindDataFileError fn ->
+        "Could not find data file " <> quote fn
+    PandocCouldNotFindMetadataFileError fn ->
+        "Could not find metadata file " <> quote fn
+    PandocResourceNotFound fn ->
+        "File " <> quote fn <> " not found in resource path"
+    PandocTemplateError s -> "Error compiling template " <> quote s
+    PandocNoTemplateError fp -> "No template defined in " <> quote fp
+    PandocAppError s -> s
+    PandocEpubSubdirectoryError s ->
+      "EPUB subdirectory name " <> quote s <> " contains illegal characters"
+    PandocMacroLoop s ->
+      "Loop encountered in expanding macro " <> s
+    PandocUTF8DecodingError f offset w ->
+      "UTF-8 decoding error in " <> quote f <> " at byte offset "
+       <> tshow offset <> " (" <> T.pack (printf "%2x" w) <> ").\n"
+       <> "The input must be a UTF-8 encoded text."
+    PandocIpynbDecodingError w ->
+      "ipynb decoding error: " <> w
+    PandocUnsupportedCharsetError charset ->
+      "Unsupported charset " <> quote charset
+    PandocFormatError format s ->
+      "Error parsing format " <> quote format <> ": " <> s
+    PandocUnknownReaderError r ->
+      "Unknown input format " <> quote r <>
+      case r of
+        "doc" -> "\nPandoc can convert from DOCX, but not from DOC." <>
+                 "\nTry using Word to save your DOC file as DOCX," <>
+                 " and convert that with pandoc."
+        "pdf" -> "\nPandoc can convert to PDF, but not from PDF."
+        _     -> ""
+    PandocUnknownWriterError w ->
+       "Unknown output format " <> quote w <>
+       case w of
+         "pdf" -> "To create a pdf using pandoc, use" <>
+                  " -t latex|beamer|context|ms|html5|typst" <>
+                 "\nand specify an output file with " <>
+                 ".pdf extension (-o filename.pdf)."
+         "doc" -> "\nPandoc can convert to DOCX, but not to DOC."
+         _     -> ""
+    PandocUnsupportedExtensionError ext f ->
+      "The extension " <> quote ext <> " is not supported " <>
+      "for " <> f <> ".\nUse --list-extensions=" <> f <> " to " <>
+      "list supported extensions."
+    PandocCiteprocError e' ->
+      prettyCiteprocError e'
+    PandocBibliographyError fp msg ->
+      "Error reading bibliography file " <> quote fp <> ":\n" <> msg
+    PandocInputNotTextError fp ->
+      "Expected text as an input, but received binary data from " <>
+      (if T.null fp
+        then "stdin"
+        else "file " <> quote fp) <>
+      ".\nIf you intended to convert from binary format, verify that it's " <>
+      "supported and use\nexplicit -f FORMAT."
+
+quote :: Text -> Text
+quote s = "'" <> s <> "'"
+
 -- | Handle PandocError by exiting with an error message.
 handleError :: Either PandocError a -> IO a
 handleError (Right r) = return r
 handleError (Left e) =
   case e of
-    PandocIOError _ err' -> ioError err'
-    PandocHttpError u err' -> err 61 $
-      "Could not fetch " ++ u ++ "\n" ++ show err'
-    PandocShouldNeverHappenError s -> err 62 s
-    PandocSomeError s -> err 63 s
-    PandocParseError s -> err 64 s
-    PandocParsecError input err' ->
-        let errPos = errorPos err'
-            errLine = sourceLine errPos
-            errColumn = sourceColumn errPos
-            ls = lines input ++ [""]
-            errorInFile = if length ls > errLine - 1
-                            then concat ["\n", ls !! (errLine - 1)
-                                        ,"\n", replicate (errColumn - 1) ' '
-                                        ,"^"]
-                        else ""
-        in  err 65 $ "\nError at " ++ show  err' ++
-                     -- if error comes from a chunk or included file,
-                     -- then we won't get the right text this way:
-                     if sourceName errPos == "source"
-                        then errorInFile
-                        else ""
-    PandocMakePDFError s -> err 65 s
-    PandocOptionError s -> err 2 s
-    PandocSyntaxMapError s -> err 67 s
-    PandocFailOnWarningError -> err 3 "Failing because there were warnings."
-    PandocPDFProgramNotFoundError pdfprog -> err 47 $
-        pdfprog ++ " not found. Please select a different --pdf-engine or install " ++ pdfprog
-    PandocPDFError logmsg -> err 43 $ "Error producing PDF.\n" ++ logmsg
-    PandocFilterError filtername msg -> err 83 $ "Error running filter " ++
-        filtername ++ ":\n" ++ msg
-    PandocCouldNotFindDataFileError fn -> err 97 $
-        "Could not find data file " ++ fn
-    PandocResourceNotFound fn -> err 99 $
-        "File " ++ fn ++ " not found in resource path"
-    PandocTemplateError s -> err 5 s
-    PandocAppError s -> err 1 s
-    PandocEpubSubdirectoryError s -> err 31 $
-      "EPUB subdirectory name '" ++ s ++ "' contains illegal characters"
-    PandocMacroLoop s -> err 91 $
-      "Loop encountered in expanding macro " ++ s
+    PandocIOError _ err' -> do
+      putStrLn $ displayException err'
+      exitWith (ExitFailure 1)
+    _ -> err exitCode (renderError e)
+ where
+  exitCode =
+    case e of
+      PandocIOError{} -> 1
+      PandocFailOnWarningError{} -> 3
+      PandocAppError{} -> 4
+      PandocTemplateError{} -> 5
+      PandocOptionError{} -> 6
+      PandocFormatError{} -> 20
+      PandocUnknownReaderError{} -> 21
+      PandocUnknownWriterError{} -> 22
+      PandocUnsupportedExtensionError{} -> 23
+      PandocCiteprocError{} -> 24
+      PandocBibliographyError{} -> 25
+      PandocEpubSubdirectoryError{} -> 31
+      PandocPDFError{} -> 43
+      PandocXMLError{} -> 44
+      PandocPDFProgramNotFoundError{} -> 47
+      PandocHttpError{} -> 61
+      PandocShouldNeverHappenError{} -> 62
+      PandocSomeError{} -> 63
+      PandocParseError{} -> 64
+      PandocMakePDFError{} -> 66
+      PandocSyntaxMapError{} -> 67
+      PandocFilterError{} -> 83
+      PandocLuaError{} -> 84
+      PandocNoTemplateError{} -> 87
+      PandocNoScriptingEngine -> 89
+      PandocMacroLoop{} -> 91
+      PandocUTF8DecodingError{} -> 92
+      PandocIpynbDecodingError{} -> 93
+      PandocUnsupportedCharsetError{} -> 94
+      PandocInputNotTextError{} -> 95
+      PandocCouldNotFindDataFileError{} -> 97
+      PandocCouldNotFindMetadataFileError{} -> 98
+      PandocResourceNotFound{} -> 99
 
-err :: Int -> String -> IO a
+err :: Int -> Text -> IO a
 err exitCode msg = do
   UTF8.hPutStrLn stderr msg
   exitWith $ ExitFailure exitCode
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
@@ -1,28 +1,10 @@
-{-
-Copyright (C) 2012-2017 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 CPP                        #-}
 {-# LANGUAGE DeriveDataTypeable         #-}
 {-# LANGUAGE DeriveGeneric              #-}
-{-# LANGUAGE GeneralizedNewtypeDeriving #-}
-{-# LANGUAGE TemplateHaskell            #-}
-
+{-# LANGUAGE OverloadedStrings          #-}
 {- |
    Module      : Text.Pandoc.Extensions
-   Copyright   : Copyright (C) 2012-2017 John MacFarlane
+   Copyright   : Copyright (C) 2012-2024 John MacFarlane
    License     : GNU GPL, version 2 or above
 
    Maintainer  : John MacFarlane <jgm@berkeley.edu>
@@ -32,14 +14,18 @@
 Data structures and functions for representing markup extensions.
 -}
 module Text.Pandoc.Extensions ( Extension(..)
+                              , readExtension
+                              , showExtension
                               , Extensions
                               , emptyExtensions
                               , extensionsFromList
-                              , parseFormatSpec
+                              , extensionsToList
                               , extensionEnabled
                               , enableExtension
                               , disableExtension
+                              , disableExtensions
                               , getDefaultExtensions
+                              , getAllExtensions
                               , pandocExtensions
                               , plainExtensions
                               , strictExtensions
@@ -47,44 +33,25 @@
                               , githubMarkdownExtensions
                               , multimarkdownExtensions )
 where
-import Data.Aeson (FromJSON (..), ToJSON (..), defaultOptions)
-import Data.Aeson.TH (deriveJSON)
-import Data.Bits (clearBit, setBit, testBit, (.|.))
 import Data.Data (Data)
+import qualified Data.Text as T
 import Data.Typeable (Typeable)
 import GHC.Generics (Generic)
-import Text.Pandoc.Shared (safeRead)
-import Text.Parsec
-
-newtype Extensions = Extensions Integer
-  deriving (Show, Read, Eq, Ord, Data, Typeable, Generic, ToJSON, FromJSON)
-
-instance Monoid Extensions where
-  mempty = Extensions 0
-  mappend (Extensions a) (Extensions b) = Extensions (a .|. b)
-
-extensionsFromList :: [Extension] -> Extensions
-extensionsFromList = foldr enableExtension emptyExtensions
-
-emptyExtensions :: Extensions
-emptyExtensions = Extensions 0
-
-extensionEnabled :: Extension -> Extensions -> Bool
-extensionEnabled x (Extensions exts) = testBit exts (fromEnum x)
-
-enableExtension :: Extension -> Extensions -> Extensions
-enableExtension x (Extensions exts) = Extensions (setBit exts (fromEnum x))
-
-disableExtension :: Extension -> Extensions -> Extensions
-disableExtension x (Extensions exts) = Extensions (clearBit exts (fromEnum x))
+import Text.Read (readMaybe)
+import Data.Aeson
+import Data.List (sort)
+import qualified Data.Set as Set
 
 -- | Individually selectable syntax extensions.
 data Extension =
       Ext_abbreviations       -- ^ PHP markdown extra abbreviation definitions
+    | Ext_alerts              -- ^ Special block quotes become alerts
     | Ext_all_symbols_escapable  -- ^ Make all non-alphanumerics escapable
     | Ext_amuse -- ^ Enable Text::Amuse extensions to Emacs Muse markup
     | Ext_angle_brackets_escapable  -- ^ Make < and > escapable
-    | Ext_ascii_identifiers   -- ^ ascii-only identifiers for headers
+    | Ext_ascii_identifiers   -- ^ ascii-only identifiers for headers;
+                              -- presupposes Ext_auto_identifiers
+    | Ext_attributes          -- ^ Generic attribute syntax
     | Ext_auto_identifiers    -- ^ Automatic identifiers for headers
     | Ext_autolink_bare_uris  -- ^ Make all absolute URIs into links
     | Ext_backtick_code_blocks    -- ^ GitHub style ``` code blocks
@@ -92,11 +59,13 @@
     | Ext_blank_before_header     -- ^ Require blank line before a header
     | Ext_bracketed_spans         -- ^ Bracketed spans with attributes
     | Ext_citations           -- ^ Pandoc/citeproc citations
-    | Ext_compact_definition_lists  -- ^ Definition lists without space between items,
-                                    --   and disallow laziness
     | Ext_definition_lists    -- ^ Definition lists as in pandoc, mmd, php
     | Ext_east_asian_line_breaks  -- ^ Newlines in paragraphs are ignored between
-                                  --   East Asian wide characters
+                                  --   East Asian wide characters. Note: this extension
+                                  --   does not affect readers/writers directly; it causes
+                                  --   the eastAsianLineBreakFilter to be applied after
+                                  --   parsing, in Text.Pandoc.App.convertWithOpts.
+    | Ext_element_citations   -- ^ Use element-citation elements for JATS citations
     | Ext_emoji               -- ^ Support emoji like :smile:
     | Ext_empty_paragraphs -- ^ Allow empty paragraphs
     | Ext_epub_html_exts      -- ^ Recognise the EPUB extended version of HTML
@@ -106,13 +75,16 @@
     | Ext_fenced_code_attributes  -- ^ Allow attributes on fenced code blocks
     | Ext_fenced_code_blocks  -- ^ Parse fenced code blocks
     | Ext_fenced_divs             -- ^ Allow fenced div syntax :::
-    | Ext_footnotes           -- ^ Pandoc/PHP/MMD style footnotes
+    | Ext_footnotes           -- ^ Pandoc\/PHP\/MMD style footnotes
     | Ext_four_space_rule     -- ^ Require 4-space indent for list contents
-    | Ext_gfm_auto_identifiers  -- ^ Automatic identifiers for headers, using
-                                --  GitHub's method for generating identifiers
+    | Ext_gfm_auto_identifiers  -- ^ Use GitHub's method for generating
+                              -- header identifiers; presupposes
+                              -- Ext_auto_identifiers
     | Ext_grid_tables         -- ^ Grid tables (pandoc, reST)
+    | Ext_gutenberg           -- ^ Use Project Gutenberg conventions for plain
     | Ext_hard_line_breaks    -- ^ All newlines become hard line breaks
     | Ext_header_attributes   -- ^ Explicit header attributes {#id .class k=v}
+    | Ext_table_attributes    -- ^ Explicit table attributes after caption
     | Ext_ignore_line_breaks  -- ^ Newlines in paragraphs are ignored
     | Ext_implicit_figures    -- ^ A paragraph with just an image is a figure
     | Ext_implicit_header_references -- ^ Implicit reference links for headers
@@ -124,6 +96,7 @@
     | Ext_link_attributes         -- ^ link and image attributes
     | Ext_lists_without_preceding_blankline -- ^ Allow lists without preceding blank
     | Ext_literate_haskell    -- ^ Enable literate Haskell conventions
+    | Ext_mark                -- ^ Enable ==mark== syntax to highlight text
     | Ext_markdown_attribute      -- ^ Interpret text inside HTML as markdown iff
                                   --   container has attribute 'markdown'
     | Ext_markdown_in_html_blocks -- ^ Interpret as markdown inside HTML blocks
@@ -133,28 +106,110 @@
     | Ext_multiline_tables    -- ^ Pandoc-style multiline tables
     | Ext_native_divs             -- ^ Use Div blocks for contents of <div> tags
     | Ext_native_spans            -- ^ Use Span inlines for contents of <span>
+    | Ext_native_numbering    -- ^ Use output format's native numbering for figures and tables
+    | Ext_ntb                 -- ^ ConTeXt Natural Tables
     | Ext_old_dashes          -- ^ -- = em, - before number = en
     | Ext_pandoc_title_block  -- ^ Pandoc title block
     | Ext_pipe_tables         -- ^ Pipe tables (as in PHP markdown extra)
     | Ext_raw_attribute           -- ^ Allow explicit raw blocks/inlines
     | Ext_raw_html            -- ^ Allow raw HTML
     | Ext_raw_tex             -- ^ Allow raw TeX (other than math)
+    | Ext_raw_markdown        -- ^ Parse markdown in ipynb as raw markdown
+    | Ext_rebase_relative_paths -- ^ Rebase relative image and link paths,
+                                -- relative to directory of containing file
+    | Ext_short_subsuperscripts -- ^ sub-&superscripts w/o closing char (v~i)
     | Ext_shortcut_reference_links -- ^ Shortcut reference links
     | Ext_simple_tables       -- ^ Pandoc-style simple tables
     | Ext_smart               -- ^ "Smart" quotes, apostrophes, ellipses, dashes
+    | Ext_smart_quotes        -- ^ "Smart" quotes
+    | Ext_special_strings     -- ^ Treat certain strings like special characters
+    | Ext_sourcepos           -- ^ Include source position attributes
     | Ext_space_in_atx_header -- ^ Require space between # and header text
     | Ext_spaced_reference_links -- ^ Allow space between two parts of ref link
     | Ext_startnum            -- ^ Make start number of ordered list significant
     | Ext_strikeout           -- ^ Strikeout using ~~this~~ syntax
     | Ext_subscript           -- ^ Subscript using ~this~ syntax
     | Ext_superscript         -- ^ Superscript using ^this^ syntax
+    | Ext_styles              -- ^ Read styles that pandoc doesn't know
+    | Ext_tagging             -- ^ Output optimized for PDF tagging
+    | Ext_task_lists          -- ^ Parse certain list items as task list items
     | Ext_table_captions      -- ^ Pandoc-style table captions
     | Ext_tex_math_dollars    -- ^ TeX math between $..$ or $$..$$
+    | Ext_tex_math_gfm        -- ^ Additional TeX math style used in GFM
     | Ext_tex_math_double_backslash  -- ^ TeX math btw \\(..\\) \\[..\\]
     | Ext_tex_math_single_backslash  -- ^ TeX math btw \(..\) \[..\]
+    | Ext_wikilinks_title_after_pipe -- ^ Support wikilinks of style
+                                     -- [[target|title]]
+    | Ext_wikilinks_title_before_pipe  -- ^ Support wikilinks of style
+                                       -- [[title|target]]
+    | Ext_xrefs_name          -- ^ Use xrefs with names
+    | Ext_xrefs_number        -- ^ Use xrefs with numbers
     | Ext_yaml_metadata_block -- ^ YAML metadata block
-    deriving (Show, Read, Enum, Eq, Ord, Bounded, Data, Typeable, Generic)
+    | CustomExtension T.Text  -- ^ Custom extension
+    deriving (Show, Read, Eq, Ord, Data, Typeable, Generic)
 
+instance FromJSON Extension where
+  parseJSON = withText "Extension" (pure . readExtension . T.unpack)
+
+instance ToJSON Extension where
+ toJSON = String . showExtension
+
+newtype Extensions = Extensions (Set.Set Extension)
+  deriving (Show, Read, Eq, Ord, Data, Typeable, Generic)
+
+instance Semigroup Extensions where
+  (Extensions a) <> (Extensions b) = Extensions (a <> b)
+instance Monoid Extensions where
+  mempty = Extensions mempty
+  mappend = (<>)
+
+instance FromJSON Extensions where
+  parseJSON = fmap extensionsFromList . parseJSON
+
+instance ToJSON Extensions where
+  toJSON (Extensions exts) = toJSON exts
+
+-- | Reads a single extension from a string.
+readExtension :: String -> Extension
+readExtension "lhs" = Ext_literate_haskell
+readExtension name =
+  case readMaybe ("Ext_" ++ name) of
+    Just ext -> ext
+    Nothing -> CustomExtension (T.pack name)
+
+-- | Show an extension in human-readable form.
+showExtension :: Extension -> T.Text
+showExtension ext =
+  case ext of
+    CustomExtension t -> t
+    _ -> T.drop 4 $ T.pack $ show ext
+
+extensionsFromList :: [Extension] -> Extensions
+extensionsFromList = Extensions . Set.fromList
+
+extensionsToList :: Extensions -> [Extension]
+extensionsToList (Extensions extset) = sort $ Set.toList extset
+
+emptyExtensions :: Extensions
+emptyExtensions = Extensions mempty
+
+extensionEnabled :: Extension -> Extensions -> Bool
+extensionEnabled x (Extensions exts) = x `Set.member` exts
+
+enableExtension :: Extension -> Extensions -> Extensions
+enableExtension x (Extensions exts) = Extensions (Set.insert x exts)
+
+disableExtension :: Extension -> Extensions -> Extensions
+disableExtension x (Extensions exts) = Extensions (Set.delete x exts)
+
+-- | Removes the extensions in the second set from those in the first.
+disableExtensions :: Extensions  -- ^ base set
+                  -> Extensions  -- ^ extensions to remove
+                  -> Extensions
+disableExtensions (Extensions base) (Extensions remove) = Extensions $
+  -- keep only those extensions that are in `base` but not in `remove`.
+  base `Set.difference` remove
+
 -- | Extensions to be used with pandoc-flavored markdown.
 pandocExtensions :: Extensions
 pandocExtensions = extensionsFromList
@@ -196,8 +251,10 @@
   , Ext_strikeout
   , Ext_superscript
   , Ext_subscript
+  , Ext_task_lists
   , Ext_auto_identifiers
   , Ext_header_attributes
+  , Ext_table_attributes
   , Ext_link_attributes
   , Ext_implicit_header_references
   , Ext_line_blocks
@@ -224,7 +281,7 @@
   , Ext_strikeout
   ]
 
--- | Extensions to be used with github-flavored markdown.
+-- | Extensions to be used with PHP Markdown Extra.
 phpMarkdownExtraExtensions :: Extensions
 phpMarkdownExtraExtensions = extensionsFromList
   [ Ext_footnotes
@@ -244,20 +301,18 @@
 -- | Extensions to be used with github-flavored markdown.
 githubMarkdownExtensions :: Extensions
 githubMarkdownExtensions = extensionsFromList
-  [ Ext_angle_brackets_escapable
-  , Ext_pipe_tables
+  [ Ext_pipe_tables
   , Ext_raw_html
-  , Ext_fenced_code_blocks
+  , Ext_auto_identifiers
   , Ext_gfm_auto_identifiers
-  , Ext_ascii_identifiers
-  , Ext_backtick_code_blocks
   , Ext_autolink_bare_uris
-  , Ext_space_in_atx_header
-  , Ext_intraword_underscores
   , Ext_strikeout
+  , Ext_task_lists
   , Ext_emoji
-  , Ext_lists_without_preceding_blankline
-  , Ext_shortcut_reference_links
+  , Ext_fenced_code_blocks
+  , Ext_backtick_code_blocks
+  , Ext_footnotes
+  , Ext_alerts
   ]
 
 -- | Extensions to be used with multimarkdown.
@@ -271,6 +326,7 @@
   -- Note: MMD's raw TeX syntax requires raw TeX to be
   -- enclosed in HTML comment
   , Ext_tex_math_double_backslash
+  , Ext_tex_math_dollars
   , Ext_intraword_underscores
   , Ext_mmd_title_block
   , Ext_footnotes
@@ -281,14 +337,9 @@
   , Ext_auto_identifiers
   , Ext_mmd_header_identifiers
   , Ext_implicit_figures
-  -- Note: MMD's syntax for superscripts and subscripts
-  -- is a bit more permissive than pandoc's, allowing
-  -- e^2 and a~1 instead of e^2^ and a~1~, so even with
-  -- these options we don't have full support for MMD
-  -- superscripts and subscripts, but there's no reason
-  -- not to include these:
-  , Ext_superscript
+  , Ext_short_subsuperscripts
   , Ext_subscript
+  , Ext_superscript
   , Ext_backtick_code_blocks
   , Ext_spaced_reference_links
   -- So far only in dev version of mmd:
@@ -304,19 +355,86 @@
   ]
 
 -- | Default extensions from format-describing string.
-getDefaultExtensions :: String -> Extensions
-getDefaultExtensions "markdown_strict" = strictExtensions
+getDefaultExtensions :: T.Text -> Extensions
+getDefaultExtensions "markdown_strict"   = strictExtensions
 getDefaultExtensions "markdown_phpextra" = phpMarkdownExtraExtensions
-getDefaultExtensions "markdown_mmd" = multimarkdownExtensions
-getDefaultExtensions "markdown_github" = githubMarkdownExtensions
-getDefaultExtensions "markdown"        = pandocExtensions
+getDefaultExtensions "markdown_mmd"      = multimarkdownExtensions
+getDefaultExtensions "markdown_github"   = githubMarkdownExtensions <>
+  extensionsFromList
+    [ Ext_all_symbols_escapable
+    , Ext_backtick_code_blocks
+    , Ext_fenced_code_blocks
+    , Ext_space_in_atx_header
+    , Ext_intraword_underscores
+    , Ext_lists_without_preceding_blankline
+    , Ext_shortcut_reference_links
+    ]
+getDefaultExtensions "markdown"          = pandocExtensions
+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]
 getDefaultExtensions "plain"           = plainExtensions
-getDefaultExtensions "gfm"             = githubMarkdownExtensions
+getDefaultExtensions "gfm"             = extensionsFromList
+  [ Ext_pipe_tables
+  , Ext_raw_html
+  , Ext_auto_identifiers
+  , Ext_gfm_auto_identifiers
+  , Ext_autolink_bare_uris
+  , Ext_strikeout
+  , Ext_task_lists
+  , Ext_emoji
+  , Ext_yaml_metadata_block
+  , Ext_footnotes
+  , Ext_tex_math_dollars
+  , Ext_tex_math_gfm
+  , Ext_alerts
+  ]
+getDefaultExtensions "commonmark"      = extensionsFromList
+                                          [Ext_raw_html]
+getDefaultExtensions "commonmark_x"    = extensionsFromList
+  [ Ext_pipe_tables
+  , Ext_raw_html
+  , Ext_gfm_auto_identifiers
+  , Ext_strikeout
+  , Ext_task_lists
+  , Ext_emoji
+  , Ext_smart
+  , Ext_tex_math_dollars
+  , Ext_superscript
+  , Ext_subscript
+  , Ext_definition_lists
+  , Ext_footnotes
+  , Ext_fancy_lists
+  , Ext_fenced_divs
+  , Ext_bracketed_spans
+  , Ext_raw_attribute
+  , Ext_implicit_header_references
+  , Ext_attributes
+  , Ext_alerts
+  , Ext_yaml_metadata_block
+  ]
 getDefaultExtensions "org"             = extensionsFromList
                                           [Ext_citations,
+                                           Ext_special_strings,
+                                           Ext_task_lists,
                                            Ext_auto_identifiers]
 getDefaultExtensions "html"            = extensionsFromList
                                           [Ext_auto_identifiers,
@@ -336,6 +454,10 @@
                                           [Ext_smart,
                                            Ext_latex_macros,
                                            Ext_auto_identifiers]
+getDefaultExtensions "beamer"          = extensionsFromList
+                                          [Ext_smart,
+                                           Ext_latex_macros,
+                                           Ext_auto_identifiers]
 getDefaultExtensions "context"         = extensionsFromList
                                           [Ext_smart,
                                            Ext_auto_identifiers]
@@ -344,31 +466,203 @@
                                            Ext_smart,
                                            Ext_raw_html,
                                            Ext_auto_identifiers]
+getDefaultExtensions "jats"            = extensionsFromList
+                                          [Ext_auto_identifiers]
+getDefaultExtensions "jats_archiving"  = getDefaultExtensions "jats"
+getDefaultExtensions "jats_publishing" = getDefaultExtensions "jats"
+getDefaultExtensions "jats_articleauthoring" = getDefaultExtensions "jats"
 getDefaultExtensions "opml"            = pandocExtensions -- affects notes
+getDefaultExtensions "markua"          = extensionsFromList
+                                          []
+getDefaultExtensions "typst"           = extensionsFromList [Ext_citations,
+                                                             Ext_smart]
+getDefaultExtensions "dokuwiki"        = extensionsFromList [Ext_smart]
 getDefaultExtensions _                 = extensionsFromList
                                           [Ext_auto_identifiers]
 
--- | Parse a format-specifying string into a markup format and a function that
--- takes Extensions and enables and disables extensions as defined in the format
--- spec.
-parseFormatSpec :: String
-                -> Either ParseError (String, Extensions -> Extensions)
-parseFormatSpec = parse formatSpec ""
-  where formatSpec = do
-          name <- formatName
-          extMods <- many extMod
-          return (name, \x -> foldl (flip ($)) x extMods)
-        formatName = many1 $ noneOf "-+"
-        extMod = do
-          polarity <- oneOf "-+"
-          name <- many $ noneOf "-+"
-          ext <- case safeRead ("Ext_" ++ name) of
-                       Just n  -> return n
-                       Nothing
-                         | name == "lhs" -> return Ext_literate_haskell
-                         | otherwise -> fail $ "Unknown extension: " ++ name
-          return $ case polarity of
-                        '-' -> disableExtension ext
-                        _   -> enableExtension ext
 
-$(deriveJSON defaultOptions ''Extension)
+-- | Get all valid extensions for a format. This is used
+-- mainly in checking format specifications for validity.
+getAllExtensions :: T.Text -> Extensions
+getAllExtensions f = universalExtensions <> getAll f
+ where
+  autoIdExtensions           = extensionsFromList
+    [ Ext_auto_identifiers
+    , Ext_gfm_auto_identifiers
+    , Ext_ascii_identifiers
+    ]
+  universalExtensions        = extensionsFromList
+    [ Ext_east_asian_line_breaks ]
+  allMarkdownExtensions =
+    pandocExtensions <> autoIdExtensions <>
+      extensionsFromList
+       [ Ext_old_dashes
+       , Ext_angle_brackets_escapable
+       , Ext_lists_without_preceding_blankline
+       , Ext_four_space_rule
+       , Ext_spaced_reference_links
+       , Ext_hard_line_breaks
+       , Ext_ignore_line_breaks
+       , Ext_east_asian_line_breaks
+       , Ext_emoji
+       , Ext_tex_math_single_backslash
+       , Ext_tex_math_double_backslash
+       , Ext_markdown_attribute
+       , Ext_mmd_title_block
+       , Ext_abbreviations
+       , Ext_autolink_bare_uris
+       , Ext_mark
+       , Ext_mmd_link_attributes
+       , Ext_mmd_header_identifiers
+       , Ext_gutenberg
+       , Ext_smart
+       , Ext_literate_haskell
+       , Ext_short_subsuperscripts
+       , Ext_rebase_relative_paths
+       , Ext_wikilinks_title_after_pipe
+       , Ext_wikilinks_title_before_pipe
+       , Ext_alerts
+       ]
+  getAll "markdown_strict"   = allMarkdownExtensions
+  getAll "markdown_phpextra" = allMarkdownExtensions
+  getAll "markdown_mmd"      = allMarkdownExtensions
+  getAll "markdown_github"   = allMarkdownExtensions
+  getAll "markdown"          = allMarkdownExtensions
+  getAll "ipynb"             = allMarkdownExtensions <> extensionsFromList
+    [ Ext_raw_markdown ]
+  getAll "docx"            = autoIdExtensions <> extensionsFromList
+    [ Ext_empty_paragraphs
+    , Ext_native_numbering
+    , Ext_styles
+    , Ext_citations
+    ]
+  getAll "opendocument"    = extensionsFromList
+    [ Ext_empty_paragraphs
+    , Ext_native_numbering
+    , Ext_xrefs_name
+    , Ext_xrefs_number
+    ]
+  getAll "odt"             = getAll "opendocument" <> autoIdExtensions
+  getAll "muse"            = autoIdExtensions <>
+    extensionsFromList
+    [ Ext_amuse ]
+  getAll "asciidoc"        = autoIdExtensions
+  getAll "plain"           = allMarkdownExtensions
+  getAll "gfm"             = getAll "commonmark"
+  getAll "commonmark"      =
+    extensionsFromList
+    [ Ext_gfm_auto_identifiers
+    , Ext_ascii_identifiers
+    , Ext_pipe_tables
+    , Ext_autolink_bare_uris
+    , Ext_strikeout
+    , Ext_task_lists
+    , Ext_emoji
+    , Ext_raw_html
+    , Ext_alerts
+    , Ext_implicit_figures
+    , Ext_hard_line_breaks
+    , Ext_smart
+    , Ext_tex_math_dollars
+    , Ext_tex_math_gfm
+    , Ext_superscript
+    , Ext_subscript
+    , Ext_definition_lists
+    , Ext_footnotes
+    , Ext_fancy_lists
+    , Ext_fenced_divs
+    , Ext_bracketed_spans
+    , Ext_raw_attribute
+    , Ext_implicit_header_references
+    , Ext_attributes
+    , Ext_sourcepos
+    , Ext_wikilinks_title_after_pipe
+    , Ext_wikilinks_title_before_pipe
+    , Ext_yaml_metadata_block
+    , Ext_rebase_relative_paths
+    ]
+  getAll "commonmark_x"    = getAll "commonmark"
+  getAll "org"             = autoIdExtensions <>
+    extensionsFromList
+    [ Ext_citations
+    , Ext_smart
+    , Ext_smart_quotes
+    , Ext_special_strings
+    , Ext_fancy_lists
+    , Ext_task_lists
+    ]
+  getAll "html"            = autoIdExtensions <>
+    extensionsFromList
+    [ Ext_native_divs
+    , Ext_line_blocks
+    , Ext_native_spans
+    , Ext_empty_paragraphs
+    , Ext_raw_html
+    , Ext_raw_tex
+    , Ext_task_lists
+    , Ext_tex_math_dollars
+    , Ext_tex_math_single_backslash
+    , Ext_tex_math_double_backslash
+    , Ext_literate_haskell
+    , Ext_epub_html_exts
+    , Ext_smart
+    ]
+  getAll "html4"           = getAll "html"
+  getAll "html5"           = getAll "html"
+  getAll "epub"            = getAll "html"
+  getAll "epub2"           = getAll "epub"
+  getAll "epub3"           = getAll "epub"
+  getAll "latex"           = autoIdExtensions <>
+    extensionsFromList
+    [ Ext_smart
+    , Ext_latex_macros
+    , Ext_raw_tex
+    , Ext_task_lists
+    , Ext_literate_haskell
+    , Ext_empty_paragraphs
+    ]
+  getAll "beamer"          = getAll "latex"
+  getAll "context"         = autoIdExtensions <>
+    extensionsFromList
+    [ Ext_smart
+    , Ext_raw_tex
+    , Ext_ntb
+    , Ext_tagging
+    ]
+  getAll "textile"         = autoIdExtensions <>
+    extensionsFromList
+    [ Ext_old_dashes
+    , Ext_smart
+    , Ext_raw_tex
+    ]
+  getAll "jats"            =
+    extensionsFromList
+    [ Ext_auto_identifiers
+    , Ext_element_citations
+    ]
+  getAll "jats_archiving"  = getAll "jats"
+  getAll "jats_publishing" = getAll "jats"
+  getAll "jats_articleauthoring" = getAll "jats"
+  getAll "opml"            = allMarkdownExtensions -- affects notes
+  getAll "twiki"           = autoIdExtensions <>
+    extensionsFromList
+    [ Ext_smart ]
+  getAll "vimwiki"         = autoIdExtensions
+  getAll "dokuwiki"        = autoIdExtensions <>
+    extensionsFromList
+    [ Ext_tex_math_dollars
+    , Ext_raw_html
+    , Ext_smart ]
+  getAll "tikiwiki"        = autoIdExtensions
+  getAll "rst"             = autoIdExtensions <>
+    extensionsFromList
+    [ Ext_smart
+    , Ext_literate_haskell
+    ]
+  getAll "mediawiki"       = autoIdExtensions <>
+    extensionsFromList
+    [ Ext_smart ]
+  getAll "typst"           = extensionsFromList [Ext_citations, Ext_smart]
+  getAll "djot"            = extensionsFromList [Ext_sourcepos]
+  getAll "man"             = autoIdExtensions
+  getAll _                 = mempty
diff --git a/src/Text/Pandoc/Filter.hs b/src/Text/Pandoc/Filter.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Filter.hs
@@ -0,0 +1,118 @@
+{-# LANGUAGE CPP               #-}
+{-# LANGUAGE DeriveGeneric     #-}
+{-# LANGUAGE OverloadedStrings #-}
+{- |
+   Module      : Text.Pandoc.Filter
+   Copyright   : Copyright (C) 2006-2024 John MacFarlane
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : John MacFarlane <jgm@berkeley@edu>
+   Stability   : alpha
+   Portability : portable
+
+Programmatically modifications of pandoc documents.
+-}
+module Text.Pandoc.Filter
+  ( Filter (..)
+  , Environment (..)
+  , applyFilters
+  , applyJSONFilter
+  ) where
+
+import System.CPUTime (getCPUTime)
+import Data.Aeson
+import Data.Maybe (fromMaybe)
+import GHC.Generics (Generic)
+import Text.Pandoc.Class (PandocMonad, findFileWithDataFallback, getVerbosity,
+                          report)
+import Text.Pandoc.Definition (Pandoc)
+import Text.Pandoc.Filter.Environment (Environment (..))
+import Text.Pandoc.Logging
+import Text.Pandoc.Citeproc (processCitations)
+import Text.Pandoc.Scripting (ScriptingEngine (engineApplyFilter))
+import qualified Text.Pandoc.Filter.JSON as JSONFilter
+import qualified Data.Text as T
+import System.FilePath (takeExtension)
+import Control.Applicative ((<|>))
+import Control.Monad.Trans (MonadIO (liftIO))
+import Control.Monad (foldM, when)
+
+-- | Type of filter and path to filter file.
+data Filter = LuaFilter FilePath
+            | JSONFilter FilePath
+            | CiteprocFilter -- built-in citeproc
+            deriving (Show, Generic, Eq)
+
+instance FromJSON Filter where
+ parseJSON node =
+  (withObject "Filter" $ \m -> do
+    ty <- m .: "type"
+    fp <- m .:? "path"
+    let missingPath = fail $ "Expected 'path' for filter of type " ++ show ty
+    let filterWithPath constr = maybe missingPath (return . constr . T.unpack)
+    case ty of
+      "citeproc" -> return CiteprocFilter
+      "lua"  -> filterWithPath LuaFilter fp
+      "json" -> filterWithPath JSONFilter fp
+      _      -> fail $ "Unknown filter type " ++ show (ty :: T.Text)) node
+  <|>
+  (withText "Filter" $ \t -> do
+    let fp = T.unpack t
+    if fp == "citeproc"
+       then return CiteprocFilter
+       else return $
+         case takeExtension fp of
+           ".lua"  -> LuaFilter fp
+           _       -> JSONFilter fp) node
+
+instance ToJSON Filter where
+ toJSON CiteprocFilter = object [ "type" .= String "citeproc" ]
+ toJSON (LuaFilter fp) = object [ "type" .= String "lua",
+                                  "path" .= String (T.pack fp) ]
+ toJSON (JSONFilter fp) = object [ "type" .= String "json",
+                                   "path" .= String (T.pack fp) ]
+
+-- | Modify the given document using a filter.
+applyFilters :: (PandocMonad m, MonadIO m)
+             => ScriptingEngine
+             -> Environment
+             -> [Filter]
+             -> [String]
+             -> Pandoc
+             -> m Pandoc
+applyFilters scrngin fenv filters args d = do
+  expandedFilters <- mapM expandFilterPath filters
+  foldM applyFilter d expandedFilters
+ where
+  applyFilter doc (JSONFilter f) =
+    withMessages f $ JSONFilter.apply fenv args f doc
+  applyFilter doc (LuaFilter f)  =
+    withMessages f $ engineApplyFilter scrngin fenv args f doc
+  applyFilter doc CiteprocFilter =
+    withMessages "citeproc" $ processCitations doc
+  withMessages f action = do
+    verbosity <- getVerbosity
+    when (verbosity == INFO) $ report $ RunningFilter f
+    starttime <- liftIO getCPUTime
+    res <- action
+    endtime <- liftIO getCPUTime
+    when (verbosity == INFO) $ report $ FilterCompleted f $ toMilliseconds $ endtime - starttime
+    return res
+  toMilliseconds picoseconds = picoseconds `div` 1000000000
+
+-- | Expand paths of filters, searching the data directory.
+expandFilterPath :: (PandocMonad m, MonadIO m) => Filter -> m Filter
+expandFilterPath (LuaFilter fp) = LuaFilter <$> filterPath fp
+expandFilterPath (JSONFilter fp) = JSONFilter <$> filterPath fp
+expandFilterPath CiteprocFilter = return CiteprocFilter
+
+filterPath :: PandocMonad m => FilePath -> m FilePath
+filterPath fp = fromMaybe fp <$> findFileWithDataFallback "filters" fp
+
+applyJSONFilter :: MonadIO m
+                => Environment
+                -> [String]
+                -> FilePath
+                -> Pandoc
+                -> m Pandoc
+applyJSONFilter = JSONFilter.apply
diff --git a/src/Text/Pandoc/Filter/Environment.hs b/src/Text/Pandoc/Filter/Environment.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Filter/Environment.hs
@@ -0,0 +1,27 @@
+{- |
+   Module      : Text.Pandoc.Filter.Environment
+   Copyright   : ©2020-2021 Albert Krewinkel
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : Albert Krewinkel <albert+pandoc@tarleb.com>
+   Stability   : alpha
+   Portability : portable
+
+Environment for pandoc filters.
+-}
+module Text.Pandoc.Filter.Environment
+  ( Environment (..)
+  ) where
+
+import Data.Default (Default (def))
+import Text.Pandoc.Options (ReaderOptions, WriterOptions)
+
+-- | Environment in which a filter is run. This includes reader and
+-- writer options.
+data Environment = Environment
+  { envReaderOptions :: ReaderOptions
+  , envWriterOptions :: WriterOptions
+  }
+
+instance Default Environment where
+  def = Environment def def
diff --git a/src/Text/Pandoc/Filter/JSON.hs b/src/Text/Pandoc/Filter/JSON.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Filter/JSON.hs
@@ -0,0 +1,82 @@
+{-# LANGUAGE OverloadedStrings #-}
+{- |
+   Module      : Text.Pandoc.Filter
+   Copyright   : Copyright (C) 2006-2024 John MacFarlane
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : John MacFarlane <jgm@berkeley@edu>
+   Stability   : alpha
+   Portability : portable
+
+Programmatically modifications of pandoc documents via JSON filters.
+-}
+module Text.Pandoc.Filter.JSON (apply) where
+
+import Control.Monad (unless, when)
+import Control.Monad.Trans (MonadIO (liftIO))
+import Data.Aeson (eitherDecode', encode)
+import Data.Char (toLower)
+import Data.Maybe (isNothing)
+import qualified Data.Text as T
+import System.Directory (executable, doesFileExist, findExecutable,
+                         getPermissions)
+import System.Environment (getEnvironment)
+import System.Exit (ExitCode (..))
+import System.FilePath ((</>), takeExtension)
+import Text.Pandoc.Definition (Pandoc)
+import Text.Pandoc.Error (PandocError (PandocFilterError))
+import Text.Pandoc.Filter.Environment (Environment (..))
+import Text.Pandoc.Process (pipeProcess)
+import Text.Pandoc.Version (pandocVersionText)
+import Text.Pandoc.Shared (tshow)
+import qualified Control.Exception as E
+import qualified Text.Pandoc.UTF8 as UTF8
+
+apply :: MonadIO m
+      => Environment
+      -> [String]
+      -> FilePath
+      -> Pandoc
+      -> m Pandoc
+apply ropts args f = liftIO . externalFilter ropts f args
+
+externalFilter :: MonadIO m
+               => Environment -> FilePath -> [String] -> Pandoc -> m Pandoc
+externalFilter fenv f args' d = liftIO $ do
+  exists <- doesFileExist f
+  isExecutable <- if exists
+                     then executable <$> getPermissions f
+                     else return True
+  let (f', args'') = if exists
+                        then case map toLower (takeExtension f) of
+                                  _      | isExecutable -> ("." </> f, args')
+                                  ".py"  -> ("python", f:args')
+                                  ".hs"  -> ("runhaskell", f:args')
+                                  ".pl"  -> ("perl", f:args')
+                                  ".rb"  -> ("ruby", f:args')
+                                  ".php" -> ("php", f:args')
+                                  ".js"  -> ("node", f:args')
+                                  ".r"   -> ("Rscript", f:args')
+                                  _      -> (f, args')
+                        else (f, args')
+  unless (exists && isExecutable) $ do
+    mbExe <- findExecutable f'
+    when (isNothing mbExe) $
+      E.throwIO $ PandocFilterError fText (T.pack $ "Could not find executable " <> f')
+  let ropts = envReaderOptions fenv
+  env <- getEnvironment
+  let env' = Just
+           ( ("PANDOC_VERSION", T.unpack pandocVersionText)
+           : ("PANDOC_READER_OPTIONS", UTF8.toStringLazy (encode ropts))
+           : env )
+  (exitcode, outbs) <- E.handle filterException $
+                              pipeProcess env' f' args'' $ encode d
+  case exitcode of
+       ExitSuccess    -> either (E.throwIO . PandocFilterError fText . T.pack)
+                                   return $ eitherDecode' outbs
+       ExitFailure ec -> E.throwIO $ PandocFilterError fText
+                           ("Filter returned error status " <> tshow ec)
+ where fText = T.pack f
+
+       filterException :: E.SomeException -> IO a
+       filterException e = E.throwIO $ PandocFilterError fText $ tshow e
diff --git a/src/Text/Pandoc/Format.hs b/src/Text/Pandoc/Format.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Format.hs
@@ -0,0 +1,251 @@
+{-# LANGUAGE FlexibleContexts  #-}
+{-# LANGUAGE OverloadedStrings #-}
+{- |
+   Module      : Text.Pandoc.Format
+   Copyright   : © 2022-2024 Albert Krewinkel
+   License     : GPL-2.0-or-later
+   Maintainer  : Albert Krewinkel <albert+pandoc@tarleb.com>
+
+Handling of format specifiers for input and output.
+-}
+module Text.Pandoc.Format
+  ( FlavoredFormat (..)
+  , ExtensionsConfig (..)
+  , ExtensionsDiff (..)
+  , diffExtensions
+  , parseFlavoredFormat
+  , applyExtensionsDiff
+  , getExtensionsConfig
+  , formatFromFilePaths
+  ) where
+
+import Control.Monad.Except (throwError)
+import Data.Char (toLower)
+import Data.Foldable (asum)
+import qualified Data.List as L
+import System.FilePath (splitExtension, takeExtension)
+import Text.Pandoc.Class (PandocMonad)
+import Text.Pandoc.Error (PandocError (..))
+import Text.Pandoc.Extensions
+  ( Extension (Ext_literate_haskell)
+  , Extensions
+  , disableExtensions
+  , enableExtension
+  , extensionsFromList
+  , extensionsToList
+  , getAllExtensions
+  , getDefaultExtensions
+  , showExtension
+  , readExtension
+  )
+import Network.URI (URI (..), parseURI)
+import Text.Pandoc.Parsing
+import qualified Data.Text as T
+
+-- | Format specifier with the format's name and the lists of extensions
+-- to be enabled or disabled.
+data FlavoredFormat = FlavoredFormat
+  { formatName     :: T.Text
+  , formatExtsDiff :: ExtensionsDiff
+  } deriving (Show)
+
+-- | Changes to a set of extensions, i.e., list of extensions to be
+-- enabled or disabled.
+data ExtensionsDiff = ExtensionsDiff
+  { extsToEnable  :: Extensions
+  , extsToDisable :: Extensions
+  } deriving (Show)
+
+instance Semigroup ExtensionsDiff where
+  ExtensionsDiff enA disA <> ExtensionsDiff enB disB =
+    ExtensionsDiff
+    ((enA `disableExtensions` disB) <> enB)
+    ((disA `disableExtensions` enB) <> disB)
+
+instance Monoid ExtensionsDiff where
+  mempty = ExtensionsDiff mempty mempty
+  mappend = (<>)
+
+-- | Calculate the change set to get from one set of extensions to
+-- another.
+diffExtensions :: Extensions -> Extensions -> ExtensionsDiff
+diffExtensions def actual = ExtensionsDiff
+  { extsToEnable = actual `disableExtensions` def
+  , extsToDisable = def `disableExtensions` actual
+  }
+
+-- | Describes the properties of a format.
+data ExtensionsConfig = ExtensionsConfig
+  { extsDefault   :: Extensions -- ^ Extensions enabled by default
+  , extsSupported :: Extensions -- ^ Extensions that can be enabled or disabled.
+  } deriving (Show)
+
+-- | Returns the extensions configuration of a format.
+getExtensionsConfig :: T.Text -> ExtensionsConfig
+getExtensionsConfig fmt = ExtensionsConfig
+  { extsDefault = getDefaultExtensions fmt
+  , extsSupported = getAllExtensions fmt
+  }
+
+instance Semigroup ExtensionsConfig where
+  ExtensionsConfig x1 y1 <> ExtensionsConfig x2 y2 =
+    ExtensionsConfig (x1 <> x2) (y1 <> y2)
+
+instance Monoid ExtensionsConfig where
+  mappend = (<>)
+  mempty = ExtensionsConfig mempty mempty
+
+-- | Apply the extension changes in the format spec to the extensions
+-- given in the format's extensions configuration. Throws an error in
+-- case of an unknown or unsupported extension.
+applyExtensionsDiff :: PandocMonad m
+                    => ExtensionsConfig
+                    -> FlavoredFormat
+                    -> m Extensions
+applyExtensionsDiff extConf (FlavoredFormat fname extsDiff) = do
+  let extsInDiff  = extsToEnable extsDiff <> extsToDisable extsDiff
+  let unsupported = extsInDiff `disableExtensions` (extsSupported extConf)
+  case extensionsToList unsupported of
+    ext:_ -> throwError $ PandocUnsupportedExtensionError
+             (showExtension ext) fname
+    []    -> pure ((extsDefault extConf `disableExtensions`
+                    extsToDisable extsDiff) <> extsToEnable extsDiff)
+
+-- | Parse a format-specifying string into a markup format and the
+-- change set to the format's extensions. Throws an error if the spec
+-- cannot be parsed or contains an unknown extension.
+parseFlavoredFormat :: PandocMonad m
+                    => T.Text
+                    -> m FlavoredFormat
+parseFlavoredFormat spec =
+  -- Paths like `latex-foo-bar.lua` or `latex-smart-citations.lua`
+  -- should be parsed as the format name. The `-` (or `+`) in the
+  -- filename would confuse the extensions parser, so, if `spec` looks
+  -- like a filename, the file's basename is split off into the prefix.
+  -- Only the remaining part is parsed, and the prefix is appended back
+  -- to the format after parsing.
+  case parse (fixSourcePos *> formatSpec) "" spec' of
+    Right (fname, extsDiff) -> pure (FlavoredFormat (prefix <> fname) extsDiff)
+    Left err -> throwError $ PandocFormatError spec (T.pack $ show err)
+  where
+    fixSourcePos = do
+      pos <- getPosition
+      setPosition (incSourceColumn pos (T.length prefix))
+    formatSpec = do
+      name <- parseFormatName
+      extsDiff <- pExtensionsDiff
+      return ( T.pack name, extsDiff )
+    parseFormatName = many1 $ noneOf "-+"
+    (prefix, spec') = case splitExtension (T.unpack spec) of
+                        (_, "") -> ("", T.toLower spec) -- no extension
+                        (p,s)   -> (T.pack p, T.pack s)
+
+pExtensionsDiff :: (UpdateSourcePos s Char, Stream s m Char)
+                => ParsecT s u m ExtensionsDiff
+pExtensionsDiff = L.foldl' (flip ($)) mempty <$> many extMod
+  where
+    extMod = do
+      polarity <- oneOf "-+"
+      name <- many $ noneOf "-+"
+      let ext = readExtension name
+      return $ \extsDiff ->
+        case polarity of
+          '+' -> extsDiff{extsToEnable  = enableExtension ext $
+                                          extsToEnable extsDiff}
+          _   -> extsDiff{extsToDisable = enableExtension ext $
+                                          extsToDisable extsDiff}
+
+-- | Determines default format based on file extensions; uses the format
+-- of the first extension that's associated with a format.
+--
+-- Examples:
+--
+-- > formatFromFilePaths ["text.unknown", "no-extension"]
+-- Nothing
+--
+-- > formatFromFilePaths ["my.md", "other.rst"]
+-- Just "markdown"
+formatFromFilePaths :: [FilePath] -> (Maybe FlavoredFormat)
+formatFromFilePaths = asum . map formatFromFilePath
+
+-- | Determines format based on file extension.
+formatFromFilePath :: FilePath -> Maybe FlavoredFormat
+formatFromFilePath x =
+  case takeExtension (map toLower fpath) of
+    ".Rmd"      -> defFlavor "markdown"
+    ".adoc"     -> defFlavor "asciidoc"
+    ".asciidoc" -> defFlavor "asciidoc"
+    ".bib"      -> defFlavor "biblatex"
+    ".context"  -> defFlavor "context"
+    ".csv"      -> defFlavor "csv"
+    ".ctx"      -> defFlavor "context"
+    ".db"       -> defFlavor "docbook"
+    ".dj"       -> defFlavor "djot"
+    ".djvu"     -> defFlavor "djvu" -- so we get an "unknown reader" error
+    ".doc"      -> defFlavor "doc"  -- so we get an "unknown reader" error
+    ".docx"     -> defFlavor "docx"
+    ".dokuwiki" -> defFlavor "dokuwiki"
+    ".epub"     -> defFlavor "epub"
+    ".fb2"      -> defFlavor "fb2"
+    ".htm"      -> defFlavor "html"
+    ".html"     -> defFlavor "html"
+    ".icml"     -> defFlavor "icml"
+    ".ipynb"    -> defFlavor "ipynb"
+    ".json"     -> defFlavor "json"
+    ".latex"    -> defFlavor "latex"
+    ".lhs"      -> defFlavor "markdown" `withExtension` Ext_literate_haskell
+    ".ltx"      -> defFlavor "latex"
+    ".markdown" -> defFlavor "markdown"
+    ".markua"   -> defFlavor "markua"
+    ".md"       -> defFlavor "markdown"
+    ".mdown"    -> defFlavor "markdown"
+    ".mdwn"     -> defFlavor "markdown"
+    ".mkd"      -> defFlavor "markdown"
+    ".mkdn"     -> defFlavor "markdown"
+    ".ms"       -> defFlavor "ms"
+    ".muse"     -> defFlavor "muse"
+    ".native"   -> defFlavor "native"
+    ".ods"      -> defFlavor "ods"  -- so we get an "unknown reader" error
+    ".odp"      -> defFlavor "odp"  -- so we get an "unknown reader" error
+    ".odf"      -> defFlavor "odf"  -- so we get an "unknown reader" error
+    ".odt"      -> defFlavor "odt"
+    ".opml"     -> defFlavor "opml"
+    ".org"      -> defFlavor "org"
+    ".pdf"      -> defFlavor "pdf"  -- so we get an "unknown reader" error
+    ".pl"       -> defFlavor "pod"
+    ".pm"       -> defFlavor "pod"
+    ".pod"      -> defFlavor "pod"
+    ".pptx"     -> defFlavor "pptx"
+    ".ris"      -> defFlavor "ris"
+    ".roff"     -> defFlavor "ms"
+    ".rst"      -> defFlavor "rst"
+    ".rtf"      -> defFlavor "rtf"
+    ".s5"       -> defFlavor "s5"
+    ".t2t"      -> defFlavor "t2t"
+    ".tei"      -> defFlavor "tei"
+    ".tex"      -> defFlavor "latex"
+    ".texi"     -> defFlavor "texinfo"
+    ".texinfo"  -> defFlavor "texinfo"
+    ".text"     -> defFlavor "markdown"
+    ".textile"  -> defFlavor "textile"
+    ".tsv"      -> defFlavor "tsv"
+    ".txt"      -> defFlavor "markdown"
+    ".typ"      -> defFlavor "typst"
+    ".wiki"     -> defFlavor "mediawiki"
+    ".xhtml"    -> defFlavor "html"
+    ".xls"      -> defFlavor "xls"   -- so we get an "unknown reader" error
+    ".xlsx"     -> defFlavor "xlsx"  -- so we get an "unknown reader" error
+    ".xml"      -> defFlavor "xml"
+    ".zip"      -> defFlavor "zip"  -- so we get an "unknown reader" error
+    ['.',y]     | y `elem` ['1'..'9'] -> defFlavor "man"
+    _           -> Nothing
+ where
+  defFlavor f = Just (FlavoredFormat f mempty)
+  withExtension Nothing _ = Nothing
+  withExtension (Just (FlavoredFormat f ed)) ext = Just $
+    FlavoredFormat f (ed <> ExtensionsDiff (extensionsFromList [ext]) mempty)
+  fpath = case parseURI x of
+            Nothing -> x
+            Just URI{ uriPath = "" } -> "index.html"
+            Just URI{ uriPath = "/" } -> "index.html"
+            Just URI{ uriPath = up } -> up
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,24 +1,7 @@
-{-
-Copyright (C) 2008-2017 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 OverloadedStrings #-}
 {- |
    Module      : Text.Pandoc.Highlighting
-   Copyright   : Copyright (C) 2008-2017 John MacFarlane
+   Copyright   : Copyright (C) 2008-2025 John MacFarlane
    License     : GNU GPL, version 2 or above
 
    Maintainer  : John MacFarlane <jgm@berkeley.edu>
@@ -32,33 +15,92 @@
                                 , languages
                                 , languagesByExtension
                                 , highlight
+                                -- * Formats
+                                -- ** LaTeX
                                 , formatLaTeXInline
                                 , formatLaTeXBlock
                                 , styleToLaTeX
+                                -- ** HTML
                                 , formatHtmlInline
                                 , formatHtmlBlock
+                                , formatHtml4Block
                                 , styleToCss
+                                -- ** ConTeXt
+                                , formatConTeXtInline
+                                , formatConTeXtBlock
+                                , styleToConTeXt
+                                , formatANSI
+                                -- ** Typst
+                                , formatTypstBlock
+                                , formatTypstInline
+                                , styleToTypst
+                                -- * Styles
+                                , defaultStyle
                                 , pygments
                                 , espresso
                                 , zenburn
                                 , tango
                                 , kate
                                 , monochrome
+                                , breezeDark
                                 , haddock
                                 , Style
+                                , lookupHighlightingStyle
                                 , fromListingsLanguage
                                 , toListingsLanguage
                                 ) where
-import Control.Monad
-import Data.Char (toLower)
+import Control.Monad ( msum )
 import qualified Data.Map as M
 import Data.Maybe (fromMaybe)
 import qualified Data.Text as T
 import Skylighting
-import Text.Pandoc.Definition
+    ( SyntaxMap,
+      breezeDark,
+      espresso,
+      haddock,
+      kate,
+      monochrome,
+      pygments,
+      tango,
+      zenburn,
+      formatHtml4Block,
+      formatHtmlBlock,
+      formatHtmlInline,
+      styleToCss,
+      formatConTeXtBlock,
+      formatConTeXtInline,
+      styleToConTeXt,
+      formatLaTeXBlock,
+      formatLaTeXInline,
+      styleToLaTeX,
+      formatTypstBlock,
+      formatTypstInline,
+      styleToTypst,
+      formatANSI,
+      Style,
+      FormatOptions(containerClasses, startNumber, lineAnchors,
+                    numberLines, lineIdPrefix, codeClasses),
+      SourceLine,
+      lookupSyntax,
+      syntaxesByExtension,
+      parseTheme,
+      tokenize,
+      defaultFormatOpts,
+      TokenizerConfig(traceOutput, TokenizerConfig, syntaxMap),
+      Syntax(sShortname, sName),
+      TokenType(NormalTok) )
+import Text.Pandoc.Definition ( Attr )
+import Text.Pandoc.Class (PandocMonad, readFileLazy)
+import Text.Pandoc.Error (PandocError(..))
+import Control.Monad.Except (throwError)
+import System.FilePath (takeExtension)
 import Text.Pandoc.Shared (safeRead)
 
-highlightingStyles :: [(String, Style)]
+-- | The default highlighting style used by pandoc (pygments).
+defaultStyle :: Style
+defaultStyle = pygments
+
+highlightingStyles :: [(T.Text, Style)]
 highlightingStyles =
   [("pygments", pygments),
    ("tango", tango),
@@ -69,18 +111,18 @@
    ("breezedark", breezeDark),
    ("haddock", haddock)]
 
-languages :: [String]
-languages = [T.unpack (T.toLower (sName s)) | s <- M.elems defaultSyntaxMap]
+languages :: SyntaxMap -> [T.Text]
+languages syntaxmap = [T.toLower (sName s) | s <- M.elems syntaxmap]
 
-languagesByExtension :: String -> [String]
-languagesByExtension ext =
-  [T.unpack (T.toLower (sName s)) | s <- syntaxesByExtension defaultSyntaxMap ext]
+languagesByExtension :: SyntaxMap -> T.Text -> [T.Text]
+languagesByExtension syntaxmap ext =
+  [T.toLower (sName s) | s <- syntaxesByExtension syntaxmap (T.unpack ext)]
 
 highlight :: SyntaxMap
           -> (FormatOptions -> [SourceLine] -> a) -- ^ Formatter
           -> Attr   -- ^ Attributes of the CodeBlock
-          -> String -- ^ Raw contents of the CodeBlock
-          -> Either String a
+          -> T.Text -- ^ Raw contents of the CodeBlock
+          -> Either T.Text a
 highlight syntaxmap formatter (ident, classes, keyvals) rawCode =
   let firstNum = fromMaybe 1 (safeRead (fromMaybe "1" $ lookup "startFrom" keyvals))
       fmtOpts = defaultFormatOpts{
@@ -89,38 +131,36 @@
                         ["line-anchors", "lineAnchors"]) classes,
                   numberLines = any (`elem`
                         ["number","numberLines", "number-lines"]) classes,
-                  lineIdPrefix = if null ident
+                  lineIdPrefix = if T.null ident
                                     then mempty
-                                    else T.pack (ident ++ "-") }
+                                    else ident <> "-" }
       tokenizeOpts = TokenizerConfig{ syntaxMap = syntaxmap
                                     , traceOutput = False }
-      classes' = map T.pack classes
-      rawCode' = T.pack rawCode
-  in  case msum (map (`lookupSyntax` syntaxmap) classes') of
+  in  case msum (map (`lookupSyntax` syntaxmap) classes) of
             Nothing
               | numberLines fmtOpts -> Right
                               $ formatter fmtOpts{ codeClasses = [],
-                                                   containerClasses = classes' }
+                                                   containerClasses = classes }
                               $ map (\ln -> [(NormalTok, ln)])
-                              $ T.lines rawCode'
+                              $ T.lines rawCode
               | otherwise  -> Left ""
-            Just syntax  ->
+            Just syntax  -> either (Left . T.pack) Right $
               formatter fmtOpts{ codeClasses =
                                    [T.toLower (sShortname syntax)],
-                                  containerClasses = classes' } <$>
-                tokenize tokenizeOpts syntax rawCode'
+                                  containerClasses = classes } <$>
+                tokenize tokenizeOpts syntax rawCode
 
 -- Functions for correlating latex listings package's language names
 -- with skylighting language names:
 
-langToListingsMap :: M.Map String String
+langToListingsMap :: M.Map T.Text T.Text
 langToListingsMap = M.fromList langsList
 
-listingsToLangMap :: M.Map String String
+listingsToLangMap :: M.Map T.Text T.Text
 listingsToLangMap = M.fromList $ map switch langsList
   where switch (a,b) = (b,a)
 
-langsList :: [(String, String)]
+langsList :: [(T.Text, T.Text)]
 langsList =
   [("abap","ABAP"),
   ("acm","ACM"),
@@ -136,6 +176,8 @@
   ("monobasic","Basic"),
   ("purebasic","Basic"),
   ("c","C"),
+  ("cs","C"),
+  ("objectivec","C"),
   ("cpp","C++"),
   ("c++","C++"),
   ("ocaml","Caml"),
@@ -147,13 +189,16 @@
   ("comsol","Comsol"),
   ("csh","csh"),
   ("delphi","Delphi"),
+  ("eiffel","Eiffel"),
   ("elan","Elan"),
+  ("elisp","elisp"),
   ("erlang","erlang"),
   ("euphoria","Euphoria"),
   ("fortran","Fortran"),
   ("gap","GAP"),
   ("gcl","GCL"),
   ("gnuplot","Gnuplot"),
+  ("go","Go"),
   ("hansl","hansl"),
   ("haskell","Haskell"),
   ("html","HTML"),
@@ -183,6 +228,7 @@
   ("oberon2","Oberon-2"),
   ("ocl","OCL"),
   ("octave","Octave"),
+  ("oorexx","OORexx"),
   ("oz","Oz"),
   ("pascal","Pascal"),
   ("perl","Perl"),
@@ -209,6 +255,7 @@
   ("simula","Simula"),
   ("sparql","SPARQL"),
   ("sql","SQL"),
+  ("swift","Swift"),
   ("tcl","tcl"),
   ("tex","TeX"),
   ("latex","TeX"),
@@ -220,9 +267,26 @@
   ("xslt","XSLT")]
 
 -- | Determine listings language name from skylighting language name.
-toListingsLanguage :: String -> Maybe String
-toListingsLanguage lang = M.lookup (map toLower lang) langToListingsMap
+toListingsLanguage :: T.Text -> Maybe T.Text
+toListingsLanguage lang = M.lookup (T.toLower lang) langToListingsMap
 
 -- | Determine skylighting language name from listings language name.
-fromListingsLanguage :: String -> Maybe String
+fromListingsLanguage :: T.Text -> Maybe T.Text
 fromListingsLanguage lang = M.lookup lang listingsToLangMap
+
+-- | Lookup style from a name. If the name is a standard style,
+-- load it; if it ends in ".theme", attempt to load a KDE theme
+-- from the file path specified.
+lookupHighlightingStyle :: PandocMonad m => String -> m Style
+lookupHighlightingStyle s
+  | takeExtension s == ".theme" = -- attempt to load KDE theme
+    do contents <- readFileLazy s
+       case parseTheme contents of
+            Left _    -> throwError $ PandocOptionError $ T.pack $
+                           "Could not read highlighting theme " ++ s
+            Right sty -> return sty
+  | otherwise =
+  case lookup (T.toLower $ T.pack s) highlightingStyles of
+       Just sty -> return sty
+       Nothing  -> throwError $ PandocOptionError $ T.pack $
+                      "Unknown highlight-style " ++ s
diff --git a/src/Text/Pandoc/Image.hs b/src/Text/Pandoc/Image.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Image.hs
@@ -0,0 +1,38 @@
+{-# LANGUAGE OverloadedStrings, ScopedTypeVariables, CPP #-}
+{- |
+Module      : Text.Pandoc.Image
+Copyright   : Copyright (C) 2020-2024 John MacFarlane
+License     : GNU GPL, version 2 or above
+
+Maintainer  : John MacFarlane <jgm@berkeley.edu>
+Stability   : alpha
+Portability : portable
+
+Functions for converting images.
+-}
+module Text.Pandoc.Image ( svgToPng ) where
+import Text.Pandoc.Process (pipeProcess)
+import qualified Data.ByteString.Lazy as L
+import System.Exit
+import Data.Text (Text)
+import Text.Pandoc.Shared (tshow)
+import qualified Control.Exception as E
+import Control.Monad.IO.Class (MonadIO(liftIO))
+
+-- | Convert svg image to png. rsvg-convert
+-- is used and must be available on the path.
+svgToPng :: MonadIO m
+         => Int           -- ^ DPI
+         -> L.ByteString  -- ^ Input image as bytestring
+         -> m (Either Text L.ByteString)
+svgToPng dpi bs = do
+  let dpi' = show dpi
+  liftIO $ E.catch
+       (do (exit, out) <- pipeProcess Nothing "rsvg-convert"
+                          ["-f","png","-a","--dpi-x",dpi',"--dpi-y",dpi']
+                          bs
+           return $ if exit == ExitSuccess
+              then Right out
+              else Left "conversion from SVG failed")
+       (\(e :: E.SomeException) -> return $ Left $
+           "check that rsvg-convert is in path.\n" <> tshow e)
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,26 +1,9 @@
-{-# LANGUAGE OverloadedStrings, ScopedTypeVariables, CPP #-}
+{-# LANGUAGE OverloadedStrings, ScopedTypeVariables #-}
+{-# LANGUAGE ViewPatterns      #-}
 {-# OPTIONS_GHC -fno-warn-type-defaults #-}
-{-
-  Copyright (C) 2011-2017 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-2017 John MacFarlane
+Copyright   : Copyright (C) 2011-2024 John MacFarlane
 License     : GNU GPL, version 2 or above
 
 Maintainer  : John MacFarlane <jgm@berkeley.edu>
@@ -30,6 +13,7 @@
 Functions for determining the size of a PNG, JPEG, or GIF image.
 -}
 module Text.Pandoc.ImageSize ( ImageType(..)
+                             , ImageSize(..)
                              , imageType
                              , imageSize
                              , sizeInPixels
@@ -49,29 +33,37 @@
                              , showInPixel
                              , showFl
                              ) where
-import Data.ByteString (ByteString, unpack)
+import Data.ByteString (ByteString)
 import qualified Data.ByteString.Char8 as B
 import qualified Data.ByteString.Lazy as BL
+import Data.Binary.Get
+import Data.Bits ((.&.), shiftR, shiftL)
+import Data.Word (bitReverse32, Word32)
+import Data.Maybe (isJust, fromJust)
 import Data.Char (isDigit)
 import Control.Monad
-import Data.Bits
-import Data.Binary
-import Data.Binary.Get
 import Text.Pandoc.Shared (safeRead)
 import Data.Default (Default)
 import Numeric (showFFloat)
 import Text.Pandoc.Definition
 import Text.Pandoc.Options
 import qualified Text.Pandoc.UTF8 as UTF8
-import qualified Text.XML.Light as Xml
-import qualified Data.Map as M
-import Control.Monad.Except
-import Data.Maybe (fromMaybe)
+import Text.Pandoc.XML.Light hiding (Attr)
+import qualified Data.Text as T
+import qualified Data.Text.Lazy as TL
+import qualified Data.Text.Encoding as TE
+import Control.Applicative
+import qualified Data.Attoparsec.ByteString as AW
+import qualified Data.Attoparsec.ByteString.Char8 as A
+import qualified Codec.Picture.Metadata as Metadata
+import Codec.Picture (decodeImageWithMetadata)
+import Codec.Compression.Zlib (decompress)
+-- import Debug.Trace
 
 -- quick and dirty functions to get image sizes
--- algorithms borrowed from wwwis.pl
 
-data ImageType = Png | Gif | Jpeg | Svg | Pdf | Eps deriving Show
+data ImageType = Png | Gif | Jpeg | Svg | Pdf | Eps | Emf | Tiff | Webp | Avif
+                 deriving Show
 data Direction = Width | Height
 instance Show Direction where
   show Width  = "width"
@@ -81,16 +73,21 @@
                | Centimeter Double
                | Millimeter Double
                | Inch Double
+               | Point Double
+               | Pica Double
                | Percent Double
                | Em Double
+               deriving Eq
 
 instance Show Dimension where
-  show (Pixel a)      = show   a ++ "px"
-  show (Centimeter a) = showFl a ++ "cm"
-  show (Millimeter a) = showFl a ++ "mm"
-  show (Inch a)       = showFl a ++ "in"
-  show (Percent a)    = show   a ++ "%"
-  show (Em a)         = showFl a ++ "em"
+  show (Pixel a)      = show a              ++ "px"
+  show (Centimeter a) = T.unpack (showFl a) ++ "cm"
+  show (Millimeter a) = T.unpack (showFl a) ++ "mm"
+  show (Inch a)       = T.unpack (showFl a) ++ "in"
+  show (Point a)      = T.unpack (showFl a) ++ "pt"
+  show (Pica a)       = T.unpack (showFl a) ++ "pc"
+  show (Percent a)    = show a              ++ "%"
+  show (Em a)         = T.unpack (showFl a) ++ "em"
 
 data ImageSize = ImageSize{
                      pxX   :: Integer
@@ -101,21 +98,31 @@
 instance Default ImageSize where
   def = ImageSize 300 200 72 72
 
-showFl :: (RealFloat a) => a -> String
-showFl a = removeExtra0s $ showFFloat (Just 5) a ""
+showFl :: (RealFloat a) => a -> T.Text
+showFl a = removeExtra0s $ T.pack $ showFFloat (Just 5) a ""
 
-removeExtra0s :: String -> String
-removeExtra0s s =
-  case dropWhile (=='0') $ reverse s of
-       '.':xs -> reverse xs
-       xs     -> reverse xs
+removeExtra0s :: T.Text -> T.Text
+removeExtra0s s = case T.dropWhileEnd (=='0') s of
+  (T.unsnoc -> Just (xs, '.')) -> xs
+  xs                           -> xs
 
+dropBOM :: ByteString -> ByteString
+dropBOM bs =
+ if "\xEF\xBB\xBF" `B.isPrefixOf` bs
+    then B.drop 3 bs
+    else bs
+
 imageType :: ByteString -> Maybe ImageType
 imageType img = case B.take 4 img of
                      "\x89\x50\x4e\x47" -> return Png
                      "\x47\x49\x46\x38" -> return Gif
-                     "\xff\xd8\xff\xe0" -> return Jpeg  -- JFIF
-                     "\xff\xd8\xff\xe1" -> return Jpeg  -- Exif
+                     "\x49\x49\x2a\x00" -> return Tiff
+                     "\x4D\x4D\x00\x2a" -> return Tiff
+                     "\xff\xd8\xff\xbd" -> return Jpeg  -- JPEG without application segment -- see p.32 in https://www.w3.org/Graphics/JPEG/itu-t81.pdf (and https://gist.github.com/leommoore/f9e57ba2aa4bf197ebc5?permalink_comment_id=3863054#gistcomment-3863054)
+                     _ | B.take 3 img == "\xff\xd8\xff"
+                          && (let byte4 = B.take 1 (B.drop 3 img)
+                              in byte4 >= "\xe0" && byte4 <= "\xef")  -- JPEG with application segment
+                                        -> return Jpeg
                      "%PDF"             -> return Pdf
                      "<svg"             -> return Svg
                      "<?xm"
@@ -124,26 +131,42 @@
                      "%!PS"
                        |  B.take 4 (B.drop 1 $ B.dropWhile (/=' ') img) == "EPSF"
                                         -> return Eps
-                     _                  -> mzero
+                     "\x01\x00\x00\x00"
+                       | B.take 4 (B.drop 40 img) == " EMF"
+                                        -> return Emf
+                     "\xEF\xBB\xBF<" -- BOM before svg
+                          -> imageType (B.drop 3 img)
+                     "RIFF"
+                       | B.take 4 (B.drop 8 img) == "WEBP"
+                                        -> return Webp
+                     _ | B.take 4 (B.drop 4 img) == "ftyp" -> return Avif
+                     _ -> mzero
 
 findSvgTag :: ByteString -> Bool
 findSvgTag img = "<svg" `B.isInfixOf` img || "<SVG" `B.isInfixOf` img
 
-imageSize :: WriterOptions -> ByteString -> Either String ImageSize
-imageSize opts img =
+imageSize :: WriterOptions -> ByteString -> Either T.Text ImageSize
+imageSize opts img = checkDpi <$>
   case imageType img of
-       Just Png  -> mbToEither "could not determine PNG size" $ pngSize img
-       Just Gif  -> mbToEither "could not determine GIF size" $ gifSize img
-       Just Jpeg -> jpegSize img
+       Just Png  -> getSize img
+       Just Gif  -> getSize img
+       Just Jpeg -> getSize img
+       Just Tiff -> getSize img
        Just Svg  -> mbToEither "could not determine SVG size" $ svgSize opts img
        Just Eps  -> mbToEither "could not determine EPS size" $ epsSize img
-       Just Pdf  -> Left "could not determine PDF size" -- TODO
+       Just Pdf  -> mbToEither "could not determine PDF size" $ pdfSize img
+       Just Emf  -> mbToEither "could not determine EMF size" $ emfSize img
+       Just Webp -> mbToEither "could not determine WebP size" $ webpSize opts img
+       Just Avif -> mbToEither "could not determine AVIF size" $ avifSize opts img
        Nothing   -> Left "could not determine image type"
   where mbToEither msg Nothing  = Left msg
         mbToEither _   (Just x) = Right x
+        -- see #6880, some defective JPEGs may encode dpi 0, so default to 72
+        -- if that value is 0
+        checkDpi size =
+          size{ dpiX = if dpiX size == 0 then 72 else dpiX size
+              , dpiY = if dpiY size == 0 then 72 else dpiY size }
 
-defaultSize :: (Integer, Integer)
-defaultSize = (72, 72)
 
 sizeInPixels :: ImageSize -> (Integer, Integer)
 sizeInPixels s = (pxX s, pxY s)
@@ -188,6 +211,8 @@
     (Centimeter a) -> a * 0.3937007874
     (Millimeter a) -> a * 0.03937007874
     (Inch a)       -> a
+    (Point a)      -> (a / 72)
+    (Pica a)       -> (a / 6)
     (Percent _)    -> 0
     (Em a)         -> a * (11/64)
 
@@ -195,33 +220,27 @@
 inPixel opts dim =
   case dim of
     (Pixel a)      -> a
-    (Centimeter a) -> floor $ dpi * a * 0.3937007874 :: Integer
-    (Millimeter a) -> floor $ dpi * a * 0.03937007874 :: Integer
-    (Inch a)       -> floor $ dpi * a :: Integer
-    (Percent _)    -> 0
-    (Em a)         -> floor $ dpi * a * (11/64) :: Integer
+    _              -> floor (dpi * inInch opts dim)
   where
     dpi = fromIntegral $ writerDpi opts
 
--- | Convert a Dimension to a String denoting its equivalent in inches, for example "2.00000".
+-- | Convert a Dimension to Text denoting its equivalent in inches, for example "2.00000".
 -- Note: Dimensions in percentages are converted to the empty string.
-showInInch :: WriterOptions -> Dimension -> String
+showInInch :: WriterOptions -> Dimension -> T.Text
 showInInch _ (Percent _) = ""
 showInInch opts dim = showFl $ inInch opts dim
 
--- | Convert a Dimension to a String denoting its equivalent in pixels, for example "600".
+-- | Convert a Dimension to Text denoting its equivalent in pixels, for example "600".
 -- Note: Dimensions in percentages are converted to the empty string.
-showInPixel :: WriterOptions -> Dimension -> String
+showInPixel :: WriterOptions -> Dimension -> T.Text
 showInPixel _ (Percent _) = ""
-showInPixel opts dim = show $ inPixel opts dim
+showInPixel opts dim = T.pack $ show $ inPixel opts dim
 
 -- | Maybe split a string into a leading number and trailing unit, e.g. "3cm" to Just (3.0, "cm")
-numUnit :: String -> Maybe (Double, String)
+numUnit :: T.Text -> Maybe (Double, T.Text)
 numUnit s =
-  let (nums, unit) = span (\c -> isDigit c || ('.'==c)) s
-  in  case safeRead nums of
-        Just n  -> Just (n, unit)
-        Nothing -> Nothing
+  let (nums, unit) = T.span (\c -> isDigit c || ('.'==c)) s
+  in (\n -> (n, unit)) <$> safeRead nums
 
 -- | Scale a dimension by a factor.
 scaleDimension :: Double -> Dimension -> Dimension
@@ -231,6 +250,8 @@
         Centimeter x -> Centimeter (factor * x)
         Millimeter x -> Millimeter (factor * x)
         Inch x       -> Inch (factor * x)
+        Point x      -> Point (factor * x)
+        Pica x       -> Pica (factor * x)
         Percent x    -> Percent (factor * x)
         Em x         -> Em (factor * x)
 
@@ -244,7 +265,7 @@
   where
     extractDim key = lookup key kvs >>= lengthToDim
 
-lengthToDim :: String -> Maybe Dimension
+lengthToDim :: T.Text -> Maybe Dimension
 lengthToDim s = numUnit s >>= uncurry toDim
   where
     toDim a "cm"   = Just $ Centimeter a
@@ -254,8 +275,8 @@
     toDim a "%"    = Just $ Percent a
     toDim a "px"   = Just $ Pixel (floor a::Integer)
     toDim a ""     = Just $ Pixel (floor a::Integer)
-    toDim a "pt"   = Just $ Inch (a / 72)
-    toDim a "pc"   = Just $ Inch (a / 6)
+    toDim a "pt"   = Just $ Point a
+    toDim a "pc"   = Just $ Pica a
     toDim a "em"   = Just $ Em a
     toDim _ _      = Nothing
 
@@ -267,8 +288,8 @@
        []    -> mzero
        (x:_) -> case B.words x of
                      [_, _, _, ux, uy] -> do
-                        ux' <- safeRead $ B.unpack ux
-                        uy' <- safeRead $ B.unpack uy
+                        ux' <- safeRead $ TE.decodeUtf8 ux
+                        uy' <- safeRead $ TE.decodeUtf8 uy
                         return ImageSize{
                             pxX  = ux'
                           , pxY  = uy'
@@ -276,57 +297,88 @@
                           , dpiY = 72 }
                      _ -> mzero
 
-pngSize :: ByteString -> Maybe ImageSize
-pngSize img = do
-  let (h, rest) = B.splitAt 8 img
-  guard $ h == "\x8a\x4d\x4e\x47\x0d\x0a\x1a\x0a" ||
-          h == "\x89\x50\x4e\x47\x0d\x0a\x1a\x0a"
-  let (i, rest') = B.splitAt 4 $ B.drop 4 rest
-  guard $ i == "MHDR" || i == "IHDR"
-  let (sizes, rest'') = B.splitAt 8 rest'
-  (x,y) <- case map fromIntegral $unpack sizes of
-                ([w1,w2,w3,w4,h1,h2,h3,h4] :: [Integer]) -> return
-                    (shift w1 24 + shift w2 16 + shift w3 8 + w4,
-                     shift h1 24 + shift h2 16 + shift h3 8 + h4)
-                _ -> Nothing -- "PNG parse error"
-  let (dpix, dpiy) = findpHYs rest''
-  return ImageSize { pxX  = x, pxY = y, dpiX = dpix, dpiY = dpiy }
+pdfSize :: ByteString -> Maybe ImageSize
+pdfSize img =
+  case A.parseOnly pPdfSize img of
+    Left _   -> Nothing
+    Right sz -> Just sz
 
-findpHYs :: ByteString -> (Integer, Integer)
-findpHYs x
-  | B.null x || "IDAT" `B.isPrefixOf` x = (72,72)
-  | "pHYs" `B.isPrefixOf` x =
-    let [x1,x2,x3,x4,y1,y2,y3,y4,u] =
-          map fromIntegral $ unpack $ B.take 9 $ B.drop 4 x
-        factor = if u == 1 -- dots per meter
-                    then \z -> z * 254 `div` 10000
-                    else const 72
-    in  ( factor $ shift x1 24 + shift x2 16 + shift x3 8 + x4,
-          factor $ shift y1 24 + shift y2 16 + shift y3 8 + y4 )
-  | otherwise = findpHYs $ B.drop 1 x  -- read another byte
+pPdfSize :: A.Parser ImageSize
+pPdfSize =
+  (A.takeWhile1 (/= '/') *> pPdfSize)
+  <|>
+  (do A.string "/MediaBox"
+      A.skipSpace
+      A.char8 '['
+      A.skipSpace
+      [x1,y1,x2,y2] <- A.count 4 $ do
+        A.skipSpace
+        raw <- A.many1 $ A.satisfy (\c -> isDigit c || c == '.')
+        case safeRead $ T.pack raw of
+          Just (r :: Double) -> return $ floor r
+          Nothing            -> mzero
+      A.skipSpace
+      A.char8 ']'
+      return $ ImageSize{
+              pxX  = x2 - x1
+            , pxY  = y2 - y1
+            , dpiX = 72
+            , dpiY = 72 }
+  )
+  <|> -- if we encounter a compressed object stream, uncompress it (#10902)
+  (do A.string "/Type"
+      A.skipSpace
+      A.string "/ObjStm"
+      _ <- A.manyTill pLine (A.string "stream" *> pEol)
+      stream <- BL.pack <$> A.manyTill
+                        (AW.satisfy (const True))
+                        (pEol *> A.string "endstream" *> pEol)
+      let contents = BL.toStrict (decompress stream)
+      case A.parseOnly pPdfSize contents of
+        Left _ -> pPdfSize
+        Right is -> pure is)
+  <|>
+  (A.char '/' *> pPdfSize)
+ where
+   iseol '\r' = True
+   iseol '\n' = True
+   iseol _ = False
+   pEol = A.satisfy iseol *> A.skipMany (A.satisfy iseol)
+   pLine = A.takeWhile (not . iseol) <* pEol
 
-gifSize :: ByteString -> Maybe ImageSize
-gifSize img = do
-  let (h, rest) = B.splitAt 6 img
-  guard $ h == "GIF87a" || h == "GIF89a"
-  case map fromIntegral $ unpack $ B.take 4 rest of
-       [w2,w1,h2,h1] -> return ImageSize {
-                          pxX  = shift w1 8 + w2,
-                          pxY  = shift h1 8 + h2,
-                          dpiX = 72,
-                          dpiY = 72
-                          }
-       _             -> Nothing -- "GIF parse error"
+getSize :: ByteString -> Either T.Text ImageSize
+getSize img =
+  case decodeImageWithMetadata img of
+    Left e -> Left (T.pack e)
+    Right (_, meta) -> do
+      pxx <- maybe (Left "Could not determine width") Right $
+                   Metadata.lookup Metadata.Width meta
+      pxy <- maybe (Left "Could not determine height") Right $
+                   Metadata.lookup Metadata.Height meta
+      dpix <- maybe (Right 72) Right $ Metadata.lookup Metadata.DpiX meta
+      dpiy <- maybe (Right 72) Right $ Metadata.lookup Metadata.DpiY meta
+      return $ ImageSize
+                { pxX = fromIntegral pxx
+                , pxY = fromIntegral pxy
+                , dpiX = fromIntegral dpix
+                , dpiY = fromIntegral dpiy }
 
 svgSize :: WriterOptions -> ByteString -> Maybe ImageSize
 svgSize opts img = do
-  doc <- Xml.parseXMLDoc $ UTF8.toString img
+  doc <- either (const mzero) return $ parseXMLElement
+                                     $ TL.fromStrict $ UTF8.toText $ dropBOM img
+  let viewboxSize = do
+        vb <- findAttrBy (== QName "viewBox" Nothing Nothing) doc
+        [_,_,w,h] <- mapM safeRead (T.words vb)
+        return (w,h)
   let dpi = fromIntegral $ writerDpi opts
   let dirToInt dir = do
-        dim <- Xml.findAttrBy (== Xml.QName dir Nothing Nothing) doc >>= lengthToDim
-        return $ inPixel opts dim
-  w <- dirToInt "width"
-  h <- dirToInt "height"
+        dim <- findAttrBy (== QName dir Nothing Nothing) doc >>= lengthToDim
+        case dim of
+           Percent _ -> mzero
+           _ -> pure $ inPixel opts dim
+  w <- dirToInt "width" <|> (fst <$> viewboxSize)
+  h <- dirToInt "height" <|> (snd <$> viewboxSize)
   return ImageSize {
     pxX  = w
   , pxY  = h
@@ -334,276 +386,270 @@
   , dpiY = dpi
   }
 
-jpegSize :: ByteString -> Either String ImageSize
-jpegSize img =
-  let (hdr, rest) = B.splitAt 4 img
-  in if B.length rest < 14
-        then Left "unable to determine JPEG size"
-        else case hdr of
-               "\xff\xd8\xff\xe0" -> jfifSize rest
-               "\xff\xd8\xff\xe1" -> exifSize rest
-               _                  -> Left "unable to determine JPEG size"
+emfSize :: ByteString -> Maybe ImageSize
+emfSize img =
+  let
+    parseheader = runGetOrFail $ do
+      skip 0x18             -- 0x00
+      frameL <- getWord32le -- 0x18  measured in 1/100 of a millimetre
+      frameT <- getWord32le -- 0x1C
+      frameR <- getWord32le -- 0x20
+      frameB <- getWord32le -- 0x24
+      skip 0x20             -- 0x28
+      deviceX <- getWord32le  -- 0x48 pixels of reference device
+      deviceY <- getWord32le  -- 0x4C
+      mmX <- getWord32le      -- 0x50 real mm of reference device (always 320*240?)
+      mmY <- getWord32le      -- 0x58
+      -- end of header
+      let
+        w = (deviceX * (frameR - frameL)) `quot` (mmX * 100)
+        h = (deviceY * (frameB - frameT)) `quot` (mmY * 100)
+        dpiW = (deviceX * 254) `quot` (mmX * 10)
+        dpiH = (deviceY * 254) `quot` (mmY * 10)
+      return $ ImageSize
+        { pxX = fromIntegral w
+        , pxY = fromIntegral h
+        , dpiX = fromIntegral dpiW
+        , dpiY = fromIntegral dpiH
+        }
+  in
+    case parseheader . BL.fromStrict $ img of
+      Left _ -> Nothing
+      Right (_, _, size) -> Just size
 
-jfifSize :: ByteString -> Either String ImageSize
-jfifSize rest =
-  let [dpiDensity,dpix1,dpix2,dpiy1,dpiy2] = map fromIntegral
-                                           $ unpack $ B.take 5 $B.drop 9 rest
-      factor = case dpiDensity of
-                    1 -> id
-                    2 -> \x -> x * 254 `div` 10
-                    _ -> const 72
-      dpix = factor (shift dpix1 8 + dpix2)
-      dpiy = factor (shift dpiy1 8 + dpiy2)
-  in case findJfifSize rest of
-       Left msg    -> Left msg
-       Right (w,h) ->Right ImageSize { pxX = w
-                                        , pxY = h
-                                        , dpiX = dpix
-                                        , dpiY = dpiy }
+-- See https://developers.google.com/speed/webp/docs/riff_container
+-- and RFC 6386
+pWebpSize :: AW.Parser ImageSize
+pWebpSize = do
+  AW.string "RIFF"
+  AW.take 4
+  AW.string "WEBP"
+  (w, h) <- lossy <|> lossless <|> extended
+  return $ def
+    { pxX = w
+    , pxY = h
+    }
+  where
+    bitsToMaybe = either (const Nothing) (\((_, _, s)) -> Just s)
+    decode d = bitsToMaybe . d . BL.fromStrict
+    lossySize = runGetOrFail $ do
+      word <- getWord16le
+      return $ word .&. 0x3FFF
+    lossy = do
+      AW.string "VP8 "
+      AW.take 4 -- length in bytes of VP8 Lossy stream size
+      keyFrame <-  AW.anyWord8
+      guard $ keyFrame .&. 1 == 0
+      AW.take 2 -- remaining bytes of frame header
+      AW.word8 0x9d  -- VP8 keyframe magic
+      AW.word8 0x01
+      AW.word8 0x2a
+      width16 <- AW.take 2
+      height16 <- AW.take 2
+      let w = toInteger <$> decode lossySize width16
+          h = toInteger <$> decode lossySize height16
+      guard $ isJust w && isJust h
+      return (fromJust w, fromJust h)
+    losslessSizes = runGetOrFail $ do
+      bitReverse32 <$> getWord32le
+    losslessSize word = 1 + (word .&. 0x3FFF)
+    lossless = do
+      AW.string "VP8L"
+      AW.take 4 -- length in bytes of VP8 Lossless chunk size
+      AW.word8 0x2f  -- webp lossless stream magic
+      sizes <- AW.take 4
+      let mbword = decode losslessSizes sizes
+      guard $ isJust mbword
+      let word = fromJust mbword
+      let w = toInteger $ losslessSize word
+          h = toInteger $ losslessSize (word `shiftR` 14)
+      return (w, h)
+    extendedSize = runGetOrFail $ do
+      low <- toInteger <$> getWord16le
+      high <- toInteger <$> getWord8
+      return $ 1 + (high `shiftL` 16) + (low)
+    extended = do
+      AW.string "VP8X"
+      AW.take 8  -- VP8X chunk length, flags and reserved area
+      width24 <- AW.take 3
+      height24 <- AW.take 3
+      let w = decode extendedSize width24
+          h = decode extendedSize height24
+      guard $ isJust w && isJust h
+      return (fromJust w, fromJust h)
 
-findJfifSize :: ByteString -> Either String (Integer,Integer)
-findJfifSize bs =
-  let bs' = B.dropWhile (=='\xff') $ B.dropWhile (/='\xff') bs
-  in case B.uncons bs' of
-       Just (c,bs'') | c >= '\xc0' && c <= '\xc3' ->
-         case map fromIntegral $ unpack $ B.take 4 $ B.drop 3 bs'' of
-              [h1,h2,w1,w2] -> Right (shift w1 8 + w2, shift h1 8 + h2)
-              _             -> Left "JFIF parse error"
-       Just (_,bs'') ->
-         case map fromIntegral $ unpack $ B.take 2 bs'' of
-              [c1,c2] ->
-                let len = shift c1 8 + c2
-                -- skip variables
-                in  findJfifSize $ B.drop len bs''
-              _       -> Left "JFIF parse error"
-       Nothing -> Left "Did not find JFIF length record"
+webpSize :: WriterOptions -> ByteString -> Maybe ImageSize
+webpSize opts img =
+  case AW.parseOnly pWebpSize img of
+    Left _   -> Nothing
+    Right sz -> Just sz { dpiX = fromIntegral $ writerDpi opts, dpiY = fromIntegral $ writerDpi opts}
 
-runGet' :: Get (Either String a) -> BL.ByteString -> Either String a
-runGet' p bl =
-#if MIN_VERSION_binary(0,7,0)
-  case runGetOrFail p bl of
-       Left (_,_,msg) -> Left msg
-       Right (_,_,x)  -> x
-#else
-  runGet p bl
-#endif
+avifSize :: WriterOptions -> ByteString -> Maybe ImageSize
+avifSize _opts img =
+  case runGetOrFail (verifyFtyp >> findAvifDimensions) (BL.fromStrict img) of
+    Left (_, _, _err) -> Nothing
+    Right (_, _, (width, height)) ->
+      Just $ ImageSize { pxX = fromIntegral width
+                       , pxY = fromIntegral height
+                       , dpiX = 72
+                       , dpiY = 72 }
 
+---- AVIF parsing:
 
-exifSize :: ByteString -> Either String ImageSize
-exifSize bs =runGet' header bl
-  where bl = BL.fromChunks [bs]
-        header = runExceptT $ exifHeader bl
--- NOTE:  It would be nicer to do
--- runGet ((Just <$> exifHeader) <|> return Nothing)
--- which would prevent pandoc from raising an error when an exif header can't
--- be parsed.  But we only get an Alternative instance for Get in binary 0.6,
--- and binary 0.5 ships with ghc 7.6.
+verifyFtyp :: Get ()
+verifyFtyp = do
+  ftypSize <- getWord32be
+  when (ftypSize < 16) $ fail "Invalid ftyp size"
 
-exifHeader :: BL.ByteString -> ExceptT String Get ImageSize
-exifHeader hdr = do
-  _app1DataSize <- lift getWord16be
-  exifHdr <- lift getWord32be
-  unless (exifHdr == 0x45786966) $ throwError "Did not find exif header"
-  zeros <- lift getWord16be
-  unless (zeros == 0) $ throwError "Expected zeros after exif header"
-  -- beginning of tiff header -- we read whole thing to use
-  -- in getting data from offsets:
-  let tiffHeader = BL.drop 8 hdr
-  byteAlign <- lift getWord16be
-  let bigEndian = byteAlign == 0x4d4d
-  let (getWord16, getWord32, getWord64) =
-        if bigEndian
-           then (getWord16be, getWord32be, getWord64be)
-           else (getWord16le, getWord32le, getWord64le)
-  let getRational = do
-        num <- getWord32
-        den <- getWord32
-        return $ fromIntegral num / fromIntegral den
-  tagmark <- lift getWord16
-  unless (tagmark == 0x002a) $ throwError "Failed alignment sanity check"
-  ifdOffset <- lift getWord32
-  lift $ skip (fromIntegral ifdOffset - 8) -- skip to IDF
-  numentries <- lift  getWord16
-  let ifdEntry :: ExceptT String Get (TagType, DataFormat)
-      ifdEntry = do
-       tag <- fromMaybe UnknownTagType . flip M.lookup tagTypeTable
-                <$> lift getWord16
-       dataFormat <- lift getWord16
-       numComponents <- lift getWord32
-       (fmt, bytesPerComponent) <-
-             case dataFormat of
-                  1  -> return (UnsignedByte <$> getWord8, 1)
-                  2  -> return (AsciiString <$>
-                                getLazyByteString
-                                (fromIntegral numComponents), 1)
-                  3  -> return (UnsignedShort <$> getWord16, 2)
-                  4  -> return (UnsignedLong <$> getWord32, 4)
-                  5  -> return (UnsignedRational <$> getRational, 8)
-                  6  -> return (SignedByte <$> getWord8, 1)
-                  7  -> return (Undefined <$> getLazyByteString
-                                (fromIntegral numComponents), 1)
-                  8  -> return (SignedShort <$> getWord16, 2)
-                  9  -> return (SignedLong <$> getWord32, 4)
-                  10 -> return (SignedRational <$> getRational, 8)
-                  11 -> return (SingleFloat <$> getWord32 {- TODO -}, 4)
-                  12 -> return (DoubleFloat <$> getWord64 {- TODO -}, 8)
-                  _  -> throwError $ "Unknown data format " ++ show dataFormat
-       let totalBytes = fromIntegral $ numComponents * bytesPerComponent
-       payload <- if totalBytes <= 4 -- data is right here
-                     then lift $ fmt <* skip (4 - totalBytes)
-                     else do  -- get data from offset
-                          offs <- lift getWord32
-                          let bytesAtOffset =
-                                 BL.take (fromIntegral totalBytes)
-                                 $ BL.drop (fromIntegral offs) tiffHeader
-                          case runGet' (Right <$> fmt) bytesAtOffset of
-                               Left msg -> throwError msg
-                               Right x  -> return x
-       return (tag, payload)
-  entries <- replicateM (fromIntegral numentries) ifdEntry
-  subentries <- case lookup ExifOffset entries of
-                      Just (UnsignedLong offset') -> do
-                        pos <- lift bytesRead
-                        lift $ skip (fromIntegral offset' - (fromIntegral pos - 8))
-                        numsubentries <- lift getWord16
-                        replicateM (fromIntegral numsubentries) ifdEntry
-                      _ -> return []
-  let allentries = entries ++ subentries
-  (wdth, hght) <- case (lookup ExifImageWidth allentries,
-                        lookup ExifImageHeight allentries) of
-                       (Just (UnsignedLong w), Just (UnsignedLong h)) ->
-                         return (fromIntegral w, fromIntegral h)
-                       _ -> return defaultSize
-                            -- we return a default width and height when
-                            -- the exif header doesn't contain these
-  let resfactor = case lookup ResolutionUnit allentries of
-                        Just (UnsignedShort 1) -> 100 / 254
-                        _ -> 1
-  let xres = maybe 72 (\(UnsignedRational x) -> floor $ x * resfactor)
-             $ lookup XResolution allentries
-  let yres = maybe 72 (\(UnsignedRational x) -> floor $ x * resfactor)
-             $ lookup YResolution allentries
-  return ImageSize{
-                    pxX  = wdth
-                  , pxY  = hght
-                  , dpiX = xres
-                  , dpiY = yres }
+  ftyp <- getByteString 4
+  unless (ftyp == "ftyp") $ fail "ftyp signature not found"
 
-data DataFormat = UnsignedByte Word8
-                | AsciiString BL.ByteString
-                | UnsignedShort Word16
-                | UnsignedLong Word32
-                | UnsignedRational Rational
-                | SignedByte Word8
-                | Undefined BL.ByteString
-                | SignedShort Word16
-                | SignedLong Word32
-                | SignedRational Rational
-                | SingleFloat Word32
-                | DoubleFloat Word64
-                deriving (Show)
+  brand <- getByteString 4
+  unless (brand == "avif" || brand == "avis") $ fail "Not an AVIF file"
 
-data TagType = ImageDescription
-             | Make
-             | Model
-             | Orientation
-             | XResolution
-             | YResolution
-             | ResolutionUnit
-             | Software
-             | DateTime
-             | WhitePoint
-             | PrimaryChromaticities
-             | YCbCrCoefficients
-             | YCbCrPositioning
-             | ReferenceBlackWhite
-             | Copyright
-             | ExifOffset
-             | ExposureTime
-             | FNumber
-             | ExposureProgram
-             | ISOSpeedRatings
-             | ExifVersion
-             | DateTimeOriginal
-             | DateTimeDigitized
-             | ComponentConfiguration
-             | CompressedBitsPerPixel
-             | ShutterSpeedValue
-             | ApertureValue
-             | BrightnessValue
-             | ExposureBiasValue
-             | MaxApertureValue
-             | SubjectDistance
-             | MeteringMode
-             | LightSource
-             | Flash
-             | FocalLength
-             | MakerNote
-             | UserComment
-             | FlashPixVersion
-             | ColorSpace
-             | ExifImageWidth
-             | ExifImageHeight
-             | RelatedSoundFile
-             | ExifInteroperabilityOffset
-             | FocalPlaneXResolution
-             | FocalPlaneYResolution
-             | FocalPlaneResolutionUnit
-             | SensingMethod
-             | FileSource
-             | SceneType
-             | UnknownTagType
-             deriving (Show, Eq, Ord)
+  -- Skip minor version and compatible brands
+  -- (we've read 12 bytes: size+type+brand)
+  let remaining_ftyp = fromIntegral ftypSize - 12
+  when (remaining_ftyp > 0) $ skip remaining_ftyp
 
-tagTypeTable :: M.Map Word16 TagType
-tagTypeTable = M.fromList
-  [ (0x010e, ImageDescription)
-  , (0x010f, Make)
-  , (0x0110, Model)
-  , (0x0112, Orientation)
-  , (0x011a, XResolution)
-  , (0x011b, YResolution)
-  , (0x0128, ResolutionUnit)
-  , (0x0131, Software)
-  , (0x0132, DateTime)
-  , (0x013e, WhitePoint)
-  , (0x013f, PrimaryChromaticities)
-  , (0x0211, YCbCrCoefficients)
-  , (0x0213, YCbCrPositioning)
-  , (0x0214, ReferenceBlackWhite)
-  , (0x8298, Copyright)
-  , (0x8769, ExifOffset)
-  , (0x829a, ExposureTime)
-  , (0x829d, FNumber)
-  , (0x8822, ExposureProgram)
-  , (0x8827, ISOSpeedRatings)
-  , (0x9000, ExifVersion)
-  , (0x9003, DateTimeOriginal)
-  , (0x9004, DateTimeDigitized)
-  , (0x9101, ComponentConfiguration)
-  , (0x9102, CompressedBitsPerPixel)
-  , (0x9201, ShutterSpeedValue)
-  , (0x9202, ApertureValue)
-  , (0x9203, BrightnessValue)
-  , (0x9204, ExposureBiasValue)
-  , (0x9205, MaxApertureValue)
-  , (0x9206, SubjectDistance)
-  , (0x9207, MeteringMode)
-  , (0x9208, LightSource)
-  , (0x9209, Flash)
-  , (0x920a, FocalLength)
-  , (0x927c, MakerNote)
-  , (0x9286, UserComment)
-  , (0xa000, FlashPixVersion)
-  , (0xa001, ColorSpace)
-  , (0xa002, ExifImageWidth)
-  , (0xa003, ExifImageHeight)
-  , (0xa004, RelatedSoundFile)
-  , (0xa005, ExifInteroperabilityOffset)
-  , (0xa20e, FocalPlaneXResolution)
-  , (0xa20f, FocalPlaneYResolution)
-  , (0xa210, FocalPlaneResolutionUnit)
-  , (0xa217, SensingMethod)
-  , (0xa300, FileSource)
-  , (0xa301, SceneType)
-  ]
+findAvifDimensions :: Get (Word32, Word32)
+findAvifDimensions = searchAvifBoxes []
+
+searchAvifBoxes :: [B.ByteString] -> Get (Word32, Word32)
+searchAvifBoxes path = do
+  isempty <- isEmpty
+  if isempty
+    then fail $ "No dimensions found. Searched: " ++ show (reverse path)
+    else do
+      boxSize <- getWord32be
+      boxType <- getByteString 4
+
+      let contentSize = fromIntegral boxSize - 8
+      let newPath = boxType : path
+
+      -- If it's a container box, search inside it
+      if isContainerBox boxType
+        then searchInsideBox contentSize newPath
+        else do
+          -- Try to parse dimensions from this box
+          result <- tryParseDimensions boxType contentSize
+          case result of
+            Just dims -> return dims
+            Nothing -> do
+              -- Skip this box and continue
+              when (contentSize > 0 && contentSize < 10000000) $
+                skip contentSize
+              searchAvifBoxes path
+
+tryParseDimensions :: B.ByteString -> Int -> Get (Maybe (Word32, Word32))
+tryParseDimensions boxType size = do
+  pos <- bytesRead
+  result <- case boxType of
+    "ispe" -> parseIspeBox
+    "tkhd" -> parseTkhdBox
+    "stsd" -> parseStsdBox
+    "av01" -> parseAv01Box
+    _ -> return Nothing
+
+  -- Reset position if we didn't find dimensions
+  case result of
+    Nothing -> do
+      newPos <- bytesRead
+      let consumed = fromIntegral (newPos - pos)
+      case size - consumed of
+        n | n > 0 -> skip n
+        _ -> return ()
+    Just _ -> return ()
+
+  return result
+
+parseIspeBox :: Get (Maybe (Word32, Word32))
+parseIspeBox = do
+  skip 4  -- version/flags
+  width <- getWord32be
+  height <- getWord32be
+  return $ Just (width, height)
+
+parseTkhdBox :: Get (Maybe (Word32, Word32))
+parseTkhdBox = do
+  version <- getWord8
+  skip 3  -- flags
+
+  -- Skip to width/height based on version
+  let skipBytes = if version == 1 then 76 else 64
+  skip skipBytes
+
+  width <- getWord32be
+  height <- getWord32be
+  -- Convert from 16.16 fixed point
+  return $ Just (width `shiftR` 16, height `shiftR` 16)
+
+parseStsdBox :: Get (Maybe (Word32, Word32))
+parseStsdBox = do
+  skip 8  -- version, flags, entry count
+  findAv01Entry
+
+findAv01Entry :: Get (Maybe (Word32, Word32))
+findAv01Entry = do
+  entrySize <- getWord32be
+  codec <- getByteString 4
+
+  if codec == "av01"
+    then do
+      skip 6  -- reserved
+      skip 2  -- data reference index
+      skip 16 -- pre-defined + reserved
+      width <- getWord16be
+      height <- getWord16be
+      return $ Just (fromIntegral width, fromIntegral height)
+    else do
+      let skipSize = fromIntegral entrySize - 8
+      when (skipSize > 0) $ skip skipSize
+      findAv01Entry
+
+parseAv01Box :: Get (Maybe (Word32, Word32))
+parseAv01Box = do
+  skip 6   -- reserved
+  skip 2   -- data reference index
+  skip 16  -- predefined/reserved
+  width <- getWord16be
+  height <- getWord16be
+  return $ Just (fromIntegral width, fromIntegral height)
+
+searchInsideBox :: Int -> [B.ByteString] -> Get (Word32, Word32)
+searchInsideBox size path = do
+  -- For meta boxes, skip version/flags
+  let isMeta = case path of
+                 "meta":_ -> True
+                 _ -> False
+  when isMeta $ skip 4
+
+  let searchSize = if isMeta then size - 4 else size
+  searchAvifBoxesInRange searchSize path
+
+searchAvifBoxesInRange :: Int -> [B.ByteString] -> Get (Word32, Word32)
+searchAvifBoxesInRange remaining' path
+  | remaining' < 8 = searchAvifBoxes path
+  | otherwise = do
+      boxSize <- getWord32be
+      boxType <- getByteString 4
+
+      let contentSize = fromIntegral boxSize - 8
+      let newPath = boxType : path
+
+      when (contentSize < 0 || fromIntegral boxSize > remaining') $ do
+        fail $ "Malformed box at path: " ++ show (reverse newPath)
+
+      if isContainerBox boxType
+        then searchInsideBox contentSize newPath
+        else do
+          result <- tryParseDimensions boxType contentSize
+          case result of
+            Just dims -> return dims
+            Nothing -> do
+              -- Don't skip here - tryParseDimensions already handled it
+              searchAvifBoxesInRange (remaining' - fromIntegral boxSize) path
+
+isContainerBox :: B.ByteString -> Bool
+isContainerBox boxType = boxType `elem`
+  ["moov", "trak", "mdia", "minf", "stbl", "meta", "dinf", "ipco", "iprp"]
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
@@ -1,26 +1,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-2017 John MacFarlane
+   Copyright   : Copyright (C) 2006-2024 John MacFarlane
    License     : GNU GPL, version 2 or above
 
    Maintainer  : John MacFarlane <jgm@berkeley.edu>
@@ -45,12 +28,13 @@
                                  keyOrder)
 import qualified Data.ByteString.Lazy as BL
 import Data.Data (Data, toConstr)
-import Data.List (isSuffixOf)
 import qualified Data.Text as Text
+import Data.Text (Text)
 import Data.Typeable (Typeable)
 import GHC.Generics (Generic)
 import Text.Pandoc.Definition
 import Text.Parsec.Pos
+import Text.Pandoc.Shared (tshow)
 
 -- | Verbosity level.
 data Verbosity = ERROR | WARNING | INFO
@@ -68,102 +52,128 @@
   parseJSON _      =  mzero
 
 data LogMessage =
-    SkippedContent String SourcePos
-  | CouldNotParseYamlMetadata String SourcePos
-  | DuplicateLinkReference String SourcePos
-  | DuplicateNoteReference String SourcePos
-  | NoteDefinedButNotUsed String SourcePos
-  | DuplicateIdentifier String SourcePos
-  | ReferenceNotFound String SourcePos
-  | CircularReference String SourcePos
-  | UndefinedToggle String SourcePos
-  | ParsingUnescaped String SourcePos
-  | CouldNotLoadIncludeFile String SourcePos
-  | MacroAlreadyDefined String SourcePos
+    SkippedContent Text SourcePos
+  | IgnoredElement Text
+  | DuplicateLinkReference Text SourcePos
+  | DuplicateNoteReference Text SourcePos
+  | NoteDefinedButNotUsed Text SourcePos
+  | DuplicateIdentifier Text SourcePos
+  | ReferenceNotFound Text SourcePos
+  | CircularReference Text SourcePos
+  | UndefinedToggle Text SourcePos
+  | ParsingUnescaped Text SourcePos
+  | CouldNotLoadIncludeFile Text SourcePos
+  | CouldNotParseIncludeFile Text SourcePos
+  | MacroAlreadyDefined Text SourcePos
   | InlineNotRendered Inline
   | BlockNotRendered Block
-  | DocxParserWarning String
-  | CouldNotFetchResource String String
-  | CouldNotDetermineImageSize String String
-  | CouldNotConvertImage String String
-  | CouldNotDetermineMimeType String
-  | CouldNotConvertTeXMath String String
-  | CouldNotParseCSS String
-  | Fetching String
-  | Extracting String
-  | NoTitleElement String
+  | DocxParserWarning Text
+  | PowerpointTemplateWarning Text
+  | IgnoredIOError Text
+  | CouldNotFetchResource Text Text
+  | CouldNotDetermineImageSize Text Text
+  | CouldNotConvertImage Text Text
+  | CouldNotDetermineMimeType Text
+  | CouldNotConvertTeXMath Text Text
+  | CouldNotParseCSS Text
+  | Fetching Text
+  | Extracting Text
+  | LoadedResource FilePath FilePath
+  | ScriptingInfo Text (Maybe SourcePos)
+  | ScriptingWarning Text (Maybe SourcePos)
+  | NoTitleElement Text
   | NoLangSpecified
-  | InvalidLang String
-  | CouldNotHighlight String
-  | MissingCharacter String
-  | Deprecated String String
-  | NoTranslation String
-  | CouldNotLoadTranslations String String
+  | InvalidLang Text
+  | CouldNotHighlight Text
+  | MissingCharacter Text
+  | Deprecated Text Text
+  | NoTranslation Text
+  | CouldNotLoadTranslations Text Text
+  | UnusualConversion Text
+  | UnexpectedXmlElement Text Text
+  | UnknownOrgExportOption Text
+  | CouldNotDeduceFormat [Text] Text
+  | RunningFilter FilePath
+  | FilterCompleted FilePath Integer
+  | CiteprocWarning Text
+  | ATXHeadingInLHS Int Text
+  | EnvironmentVariableUndefined Text
+  | DuplicateAttribute Text Text
+  | NotUTF8Encoded FilePath
+  | MakePDFInfo Text Text
+  | MakePDFWarning Text
+  | UnclosedDiv SourcePos SourcePos
+  | UnsupportedCodePage Int
+  | YamlWarning SourcePos Text
+  | UnsupportedPdfStandard Text
   deriving (Show, Eq, Data, Ord, Typeable, Generic)
 
 instance ToJSON LogMessage where
   toJSON x = object $
     "verbosity" .= toJSON (messageVerbosity x) :
     "type" .= toJSON (show $ toConstr x) :
+    "pretty" .= toJSON (showLogMessage x) :
     case x of
       SkippedContent s pos ->
-           ["contents" .= Text.pack s,
-            "source" .= Text.pack (sourceName pos),
+           ["contents" .= s,
+            "source" .= sourceName pos,
             "line" .= sourceLine pos,
             "column" .= sourceColumn pos]
-      CouldNotParseYamlMetadata s pos ->
-           ["message" .= Text.pack s,
-            "source" .= Text.pack (sourceName pos),
-            "line" .= toJSON (sourceLine pos),
-            "column" .= toJSON (sourceColumn pos)]
+      IgnoredElement s ->
+           ["contents" .= s]
       DuplicateLinkReference s pos ->
-           ["contents" .= Text.pack s,
-            "source" .= Text.pack (sourceName pos),
+           ["contents" .= s,
+            "source" .= sourceName pos,
             "line" .= toJSON (sourceLine pos),
             "column" .= toJSON (sourceColumn pos)]
       NoteDefinedButNotUsed s pos ->
-           ["key" .= Text.pack s,
-            "source" .= Text.pack (sourceName pos),
+           ["key" .= s,
+            "source" .= sourceName pos,
             "line" .= toJSON (sourceLine pos),
             "column" .= toJSON (sourceColumn pos)]
       DuplicateNoteReference s pos ->
-           ["contents" .= Text.pack s,
-            "source" .= Text.pack (sourceName pos),
+           ["contents" .= s,
+            "source" .= sourceName pos,
             "line" .= toJSON (sourceLine pos),
             "column" .= toJSON (sourceColumn pos)]
       DuplicateIdentifier s pos ->
-           ["contents" .= Text.pack s,
-            "source" .= Text.pack (sourceName pos),
+           ["contents" .= s,
+            "source" .= sourceName pos,
             "line" .= toJSON (sourceLine pos),
             "column" .= toJSON (sourceColumn pos)]
       ReferenceNotFound s pos ->
-           ["contents" .= Text.pack s,
-            "source" .= Text.pack (sourceName pos),
+           ["contents" .= s,
+            "source" .= sourceName pos,
             "line" .= toJSON (sourceLine pos),
             "column" .= toJSON (sourceColumn pos)]
       CircularReference s pos ->
-           ["contents" .= Text.pack s,
-            "source" .= Text.pack (sourceName pos),
+           ["contents" .= s,
+            "source" .= sourceName pos,
             "line" .= toJSON (sourceLine pos),
             "column" .= toJSON (sourceColumn pos)]
       UndefinedToggle s pos ->
-           ["contents" .= Text.pack s,
-            "source" .= Text.pack (sourceName pos),
+           ["contents" .= s,
+            "source" .= sourceName pos,
             "line" .= toJSON (sourceLine pos),
             "column" .= toJSON (sourceColumn pos)]
       ParsingUnescaped s pos ->
-           ["contents" .= Text.pack s,
-            "source" .= Text.pack (sourceName pos),
+           ["contents" .= s,
+            "source" .= sourceName pos,
             "line" .= toJSON (sourceLine pos),
             "column" .= toJSON (sourceColumn pos)]
       CouldNotLoadIncludeFile fp pos ->
-           ["path" .= Text.pack fp,
-            "source" .= Text.pack (sourceName pos),
+           ["path" .= fp,
+            "source" .= sourceName pos,
             "line" .= toJSON (sourceLine pos),
             "column" .= toJSON (sourceColumn pos)]
+      CouldNotParseIncludeFile fp pos ->
+           ["path" .= fp,
+            "source" .= sourceName pos,
+            "line" .= toJSON (sourceLine pos),
+            "column" .= toJSON (sourceColumn pos)]
       MacroAlreadyDefined name pos ->
-           ["name" .= Text.pack name,
-            "source" .= Text.pack (sourceName pos),
+           ["name" .= name,
+            "source" .= sourceName pos,
             "line" .= toJSON (sourceLine pos),
             "column" .= toJSON (sourceColumn pos)]
       InlineNotRendered il ->
@@ -171,52 +181,128 @@
       BlockNotRendered bl ->
            ["contents" .= toJSON bl]
       DocxParserWarning s ->
-           ["contents" .= Text.pack s]
+           ["contents" .= s]
+      PowerpointTemplateWarning s ->
+           ["contents" .= s]
+      IgnoredIOError s ->
+           ["contents" .= s]
       CouldNotFetchResource fp s ->
-           ["path" .= Text.pack fp,
-            "message" .= Text.pack s]
+           ["path" .= fp,
+            "message" .= s]
       CouldNotDetermineImageSize fp s ->
-           ["path" .= Text.pack fp,
-            "message" .= Text.pack s]
+           ["path" .= fp,
+            "message" .= s]
       CouldNotConvertImage fp s ->
-           ["path" .= Text.pack fp,
-            "message" .= Text.pack s]
+           ["path" .= fp,
+            "message" .= s]
       CouldNotDetermineMimeType fp ->
-           ["path" .= Text.pack fp]
+           ["path" .= fp]
       CouldNotConvertTeXMath s msg ->
-           ["contents" .= Text.pack s,
-            "message" .= Text.pack msg]
+           ["contents" .= s,
+            "message" .= msg]
       CouldNotParseCSS msg ->
-           ["message" .= Text.pack msg]
+           ["message" .= msg]
       Fetching fp ->
-           ["path" .= Text.pack fp]
+           ["path" .= fp]
       Extracting fp ->
-           ["path" .= Text.pack fp]
+           ["path" .= fp]
+      LoadedResource orig found ->
+           ["for"  .= orig
+           ,"from" .= found]
+      ScriptingInfo msg mbpos ->
+           ["message" .= msg] <>
+           case mbpos of
+             Nothing  -> []
+             Just pos -> ["source" .= sourceName pos
+                         ,"line" .= toJSON (sourceLine pos)
+                         ,"column" .= toJSON (sourceColumn pos)
+                         ]
+      ScriptingWarning msg mbpos ->
+           ["message" .= msg] <>
+           case mbpos of
+             Nothing  -> []
+             Just pos -> ["source" .= sourceName pos
+                         ,"line" .= toJSON (sourceLine pos)
+                         ,"column" .= toJSON (sourceColumn pos)
+                         ]
       NoTitleElement fallback ->
-           ["fallback" .= Text.pack fallback]
+           ["fallback" .= fallback]
       NoLangSpecified -> []
       InvalidLang s ->
-           ["lang" .= Text.pack s]
+           ["lang" .= s]
       CouldNotHighlight msg ->
-           ["message" .= Text.pack msg]
+           ["message" .= msg]
       MissingCharacter msg ->
-           ["message" .= Text.pack msg]
+           ["message" .= msg]
       Deprecated thing msg ->
-           ["thing" .= Text.pack thing,
-            "message" .= Text.pack msg]
+           ["thing" .= thing,
+            "message" .= msg]
       NoTranslation term ->
-           ["term" .= Text.pack term]
+           ["term" .= term]
       CouldNotLoadTranslations lang msg ->
-           ["lang" .= Text.pack lang,
-            "message" .= Text.pack msg]
-
+           ["lang" .= lang,
+            "message" .= msg]
+      UnusualConversion msg ->
+           ["message" .= msg]
+      UnexpectedXmlElement element parent ->
+           ["element" .= element,
+            "parent" .= parent]
+      UnknownOrgExportOption option ->
+           ["option" .= option]
+      CouldNotDeduceFormat exts format ->
+           ["extensions" .= exts
+           ,"format" .= format]
+      RunningFilter fp ->
+           ["path" .= Text.pack fp ]
+      FilterCompleted fp ms ->
+           ["path" .= Text.pack fp
+           ,"milliseconds" .= Text.pack (show ms) ]
+      CiteprocWarning msg ->
+           ["message" .= msg]
+      ATXHeadingInLHS lvl contents ->
+           ["level" .= lvl
+           ,"contents" .= contents]
+      EnvironmentVariableUndefined var ->
+           ["variable" .= var ]
+      DuplicateAttribute attr val ->
+           ["attribute" .= attr
+           ,"value" .= val]
+      NotUTF8Encoded src ->
+           ["source" .= src]
+      MakePDFInfo description contents ->
+           ["description" .= description
+           ,"contents" .= contents]
+      MakePDFWarning message ->
+           ["message" .= message]
+      UnclosedDiv openpos closepos ->
+           ["openpos" .= object
+             [ "source" .= sourceName openpos,
+               "line" .= toJSON (sourceLine openpos),
+               "column" .= toJSON (sourceColumn openpos)]
+           ,"closepos" .= object
+             [ "source" .= sourceName closepos,
+               "line" .= toJSON (sourceLine closepos),
+               "column" .= toJSON (sourceColumn closepos)]
+           ]
+      UnsupportedCodePage cpg ->
+           ["codepage" .= cpg]
+      YamlWarning pos msg ->
+           [ "source" .= sourceName pos
+           , "line" .= toJSON (sourceLine pos)
+           , "column" .= toJSON (sourceColumn pos)
+           , "message" .= msg
+           ]
+      UnsupportedPdfStandard s ->
+           ["contents" .= s]
 
-showPos :: SourcePos -> String
-showPos pos = sn ++ "line " ++
+showPos :: SourcePos -> Text
+showPos pos = Text.pack $ sn ++ "line " ++
      show (sourceLine pos) ++ " column " ++ show (sourceColumn pos)
-  where sn = if sourceName pos == "source" || sourceName pos == ""
-                then ""
-                else sourceName pos ++ " "
+  where
+    sn' = sourceName pos
+    sn = if sn' == "source" || sn' == "" || sn' == "-"
+            then ""
+            else sn' ++ " "
 
 encodeLogMessages :: [LogMessage] -> BL.ByteString
 encodeLogMessages ms =
@@ -224,119 +310,196 @@
       keyOrder [ "type", "verbosity", "contents", "message", "path",
                  "source", "line", "column" ] } ms
 
-showLogMessage :: LogMessage -> String
+showLogMessage :: LogMessage -> Text
 showLogMessage msg =
   case msg of
        SkippedContent s pos ->
-         "Skipped '" ++ s ++ "' at " ++ showPos pos
-       CouldNotParseYamlMetadata s pos ->
-         "Could not parse YAML metadata at " ++ showPos pos ++
-           if null s then "" else ": " ++ s
+         "Skipped '" <> s <> "' at " <> showPos pos
+       IgnoredElement s ->
+         "Ignored element " <> s
        DuplicateLinkReference s pos ->
-         "Duplicate link reference '" ++ s ++ "' at " ++ showPos pos
+         "Duplicate link reference '" <> s <> "' at " <> showPos pos
        DuplicateNoteReference s pos ->
-         "Duplicate note reference '" ++ s ++ "' at " ++ showPos pos
+         "Duplicate note reference '" <> s <> "' at " <> showPos pos
        NoteDefinedButNotUsed s pos ->
-         "Note with key '" ++ s ++ "' defined at " ++ showPos pos ++
+         "Note with key '" <> s <> "' defined at " <> showPos pos <>
            " but not used."
        DuplicateIdentifier s pos ->
-         "Duplicate identifier '" ++ s ++ "' at " ++ showPos pos
+         "Duplicate identifier '" <> s <> "' at " <> showPos pos
        ReferenceNotFound s pos ->
-         "Reference not found for '" ++ s ++ "' at " ++ showPos pos
+         "Reference not found for '" <> s <> "' at " <> showPos pos
        CircularReference s pos ->
-         "Circular reference '" ++ s ++ "' at " ++ showPos pos
+         "Circular reference '" <> s <> "' at " <> showPos pos
        UndefinedToggle s pos ->
-         "Undefined toggle '" ++ s ++ "' at " ++ showPos pos
+         "Undefined toggle '" <> s <> "' at " <> showPos pos
        ParsingUnescaped s pos ->
-         "Parsing unescaped '" ++ s ++ "' at " ++ showPos pos
+         "Parsing unescaped '" <> s <> "' at " <> showPos pos
        CouldNotLoadIncludeFile fp pos ->
-         "Could not load include file '" ++ fp ++ "' at " ++ showPos pos
+         "Could not load include file " <> fp <> " at " <> showPos pos
+       CouldNotParseIncludeFile fp pos ->
+         "Parsing include file " <> fp <> " failed at " <> showPos pos
        MacroAlreadyDefined name pos ->
-         "Macro '" ++ name ++ "' already defined, ignoring at " ++ showPos pos
+         "Macro '" <> name <> "' already defined, ignoring at " <> showPos pos
        InlineNotRendered il ->
-         "Not rendering " ++ show il
+         "Not rendering " <> Text.pack (show il)
        BlockNotRendered bl ->
-         "Not rendering " ++ show bl
+         "Not rendering " <> Text.pack (show bl)
        DocxParserWarning s ->
-         "Docx parser warning: " ++ s
+         "Docx parser warning: " <> s
+       PowerpointTemplateWarning s ->
+         "Powerpoint template warning: " <> s
+       IgnoredIOError s ->
+         "IO Error (ignored): " <> s
        CouldNotFetchResource fp s ->
-         "Could not fetch resource '" ++ fp ++ "'" ++
-           if null s then "" else ": " ++ s
+         "Could not fetch resource " <> fp <>
+           if Text.null s then "" else ": " <> s
        CouldNotDetermineImageSize fp s ->
-         "Could not determine image size for '" ++ fp ++ "'" ++
-           if null s then "" else ": " ++ s
+         "Could not determine image size for " <> fp <>
+           if Text.null s then "" else ": " <> s
        CouldNotConvertImage fp s ->
-         "Could not convert image '" ++ fp ++ "'" ++
-           if null s then "" else ": " ++ s
+         "Could not convert image " <> fp <>
+           if Text.null s then "" else ": " <> s
        CouldNotDetermineMimeType fp ->
-         "Could not determine mime type for '" ++ fp ++ "'"
+         "Could not determine mime type for " <> fp
        CouldNotConvertTeXMath s m ->
-         "Could not convert TeX math '" ++ s ++ "', rendering as TeX" ++
-           if null m then "" else ':' : '\n' : m
+         "Could not convert TeX math " <> s <> ", rendering as TeX" <>
+           if Text.null m then "" else ":\n" <> m
        CouldNotParseCSS m ->
-         "Could not parse CSS" ++ if null m then "" else ':' : '\n' : m
+         "Could not parse CSS" <> if Text.null m then "" else ":\n" <> m
        Fetching fp ->
-         "Fetching " ++ fp ++ "..."
+         "Fetching " <> fp <> "..."
        Extracting fp ->
-         "Extracting " ++ fp ++ "..."
+         "Extracting " <> fp <> "..."
+       LoadedResource orig found ->
+         "Loaded " <> Text.pack orig <> " from " <> Text.pack found
+       ScriptingInfo s mbpos ->
+         "Scripting info" <>
+         maybe "" (\pos -> " at " <> showPos pos) mbpos  <> ": " <> s
+       ScriptingWarning s mbpos ->
+         "Scripting warning" <>
+         maybe "" (\pos -> " at " <> showPos pos) mbpos  <> ": " <> s
        NoTitleElement fallback ->
-         "This document format requires a nonempty <title> element.\n" ++
-         "Please specify either 'title' or 'pagetitle' in the metadata.\n" ++
-         "Falling back to '" ++ fallback ++ "'"
+         "This document format requires a nonempty <title> element.\n" <>
+         "Defaulting to '" <> fallback <> "' as the title.\n" <>
+         "To specify a title, use --variable pagetitle=\"...\"."
        NoLangSpecified ->
-         "No value for 'lang' was specified in the metadata.\n" ++
+         "No value for 'lang' was specified in the metadata.\n" <>
          "It is recommended that lang be specified for this format."
        InvalidLang s ->
-         "Invalid 'lang' value '" ++ s ++ "'.\n" ++
+         "Invalid 'lang' value '" <> s <> "'.\n" <>
          "Use an IETF language tag like 'en-US'."
        CouldNotHighlight m ->
-         "Could not highlight code block:\n" ++ m
+         "Could not highlight code block:\n" <> m
        MissingCharacter m ->
-         "Missing character: " ++ m
+         "Missing character: " <> m
        Deprecated t m ->
-         "Deprecated: " ++ t ++
-         if null m
+         "Deprecated: " <> t <>
+         if Text.null m
             then ""
-            else ". " ++ m
+            else ". " <> m
        NoTranslation t ->
-         "The term " ++ t ++ " has no translation defined."
+         "The term " <> t <> " has no translation defined."
        CouldNotLoadTranslations lang m ->
-         "Could not load translations for " ++ lang ++
-           if null m then "" else '\n' : m
+         "Could not load translations for " <> lang <>
+           if Text.null m then "" else "\n" <> m
+       UnusualConversion m ->
+         "Unusual conversion: " <> m
+       UnexpectedXmlElement element parent ->
+         "Unexpected XML element " <> element <> " in " <> parent
+       UnknownOrgExportOption option ->
+         "Ignoring unknown Org export option: " <> option
+       CouldNotDeduceFormat exts format ->
+         "Could not deduce format from file extension " <>
+         Text.intercalate " or " exts <> "\n" <>
+         "Defaulting to " <> format
+       RunningFilter fp -> "Running filter " <> Text.pack fp
+       FilterCompleted fp ms -> "Completed filter " <> Text.pack fp <>
+          " in " <> Text.pack (show ms) <> " ms"
+       CiteprocWarning ms -> "Citeproc: " <> ms
+       ATXHeadingInLHS lvl contents ->
+         "Rendering heading '" <> contents <> "' as a paragraph.\n" <>
+         "ATX headings cannot be used in literate Haskell, because " <>
+         "'#' is not\nallowed in column 1." <>
+         if lvl < 3
+            then " Consider using --markdown-headings=setext."
+            else ""
+       EnvironmentVariableUndefined var ->
+         "Undefined environment variable " <> var <> " in defaults file."
+       DuplicateAttribute attr val ->
+         "Ignoring duplicate attribute " <> attr <> "=" <> tshow val <> "."
+       NotUTF8Encoded src ->
+         Text.pack src <>
+           " is not UTF-8 encoded: falling back to latin1."
+       MakePDFInfo description contents ->
+         "[makePDF] " <> description <>
+          if Text.null contents
+             then mempty
+             else "\n" <> contents
+       MakePDFWarning message -> "[makePDF] " <> message
+       UnclosedDiv openpos closepos -> "Div at " <> showPos openpos <>
+          " unclosed at " <> showPos closepos <> ", closing implicitly."
+       UnsupportedCodePage cpg -> "Unsupported code page " <> tshow cpg <>
+          ". Text will likely be garbled."
+       YamlWarning pos m -> "YAML warning (" <> showPos pos <> "): " <> m
+       UnsupportedPdfStandard s ->
+         "PDF standard '" <> s <> "' is not supported by LaTeX and will be ignored."
 
-messageVerbosity:: LogMessage -> Verbosity
+messageVerbosity :: LogMessage -> Verbosity
 messageVerbosity msg =
   case msg of
-       SkippedContent{}             -> INFO
-       CouldNotParseYamlMetadata{}  -> WARNING
-       DuplicateLinkReference{}     -> WARNING
-       DuplicateNoteReference{}     -> WARNING
-       NoteDefinedButNotUsed{}      -> WARNING
-       DuplicateIdentifier{}        -> WARNING
-       ReferenceNotFound{}          -> WARNING
-       CircularReference{}          -> WARNING
-       UndefinedToggle{}            -> WARNING
+       SkippedContent{}              -> INFO
+       IgnoredElement{}              -> INFO
+       DuplicateLinkReference{}      -> WARNING
+       DuplicateNoteReference{}      -> WARNING
+       NoteDefinedButNotUsed{}       -> WARNING
+       DuplicateIdentifier{}         -> WARNING
+       ReferenceNotFound{}           -> WARNING
+       CircularReference{}           -> WARNING
+       UndefinedToggle{}             -> WARNING
        CouldNotLoadIncludeFile f _
-        | ".sty" `isSuffixOf` f     -> INFO
-        | otherwise                 -> WARNING
-       MacroAlreadyDefined{}        -> WARNING
-       ParsingUnescaped{}           -> INFO
-       InlineNotRendered{}          -> INFO
-       BlockNotRendered{}           -> INFO
-       DocxParserWarning{}          -> INFO
-       CouldNotFetchResource{}      -> WARNING
-       CouldNotDetermineImageSize{} -> WARNING
-       CouldNotConvertImage{}       -> WARNING
-       CouldNotDetermineMimeType{}  -> WARNING
-       CouldNotConvertTeXMath{}     -> WARNING
-       CouldNotParseCSS{}           -> WARNING
-       Fetching{}                   -> INFO
-       Extracting{}                 -> INFO
-       NoTitleElement{}             -> WARNING
-       NoLangSpecified              -> INFO
-       InvalidLang{}                -> WARNING
-       CouldNotHighlight{}          -> WARNING
-       MissingCharacter{}           -> WARNING
-       Deprecated{}                 -> WARNING
-       NoTranslation{}              -> WARNING
-       CouldNotLoadTranslations{}   -> WARNING
+        | ".sty" `Text.isSuffixOf` f -> INFO
+        | otherwise                  -> WARNING
+       CouldNotParseIncludeFile{}    -> WARNING
+       MacroAlreadyDefined{}         -> WARNING
+       ParsingUnescaped{}            -> INFO
+       InlineNotRendered{}           -> INFO
+       BlockNotRendered{}            -> INFO
+       DocxParserWarning{}           -> WARNING
+       PowerpointTemplateWarning{}   -> WARNING
+       IgnoredIOError{}              -> WARNING
+       CouldNotFetchResource{}       -> WARNING
+       CouldNotDetermineImageSize{}  -> WARNING
+       CouldNotConvertImage{}        -> WARNING
+       CouldNotDetermineMimeType{}   -> WARNING
+       CouldNotConvertTeXMath{}      -> WARNING
+       CouldNotParseCSS{}            -> WARNING
+       Fetching{}                    -> INFO
+       Extracting{}                  -> INFO
+       LoadedResource{}              -> INFO
+       ScriptingInfo{}               -> INFO
+       ScriptingWarning{}            -> WARNING
+       NoTitleElement{}              -> INFO
+       NoLangSpecified               -> INFO
+       InvalidLang{}                 -> WARNING
+       CouldNotHighlight{}           -> WARNING
+       MissingCharacter{}            -> WARNING
+       Deprecated{}                  -> WARNING
+       NoTranslation{}               -> WARNING
+       CouldNotLoadTranslations{}    -> WARNING
+       UnusualConversion {}          -> WARNING
+       UnexpectedXmlElement {}       -> WARNING
+       UnknownOrgExportOption {}     -> WARNING
+       CouldNotDeduceFormat{}        -> WARNING
+       RunningFilter{}               -> INFO
+       FilterCompleted{}             -> INFO
+       CiteprocWarning{}             -> WARNING
+       ATXHeadingInLHS{}             -> WARNING
+       EnvironmentVariableUndefined{}-> WARNING
+       DuplicateAttribute{}          -> WARNING
+       NotUTF8Encoded{}              -> WARNING
+       MakePDFInfo{}                 -> INFO
+       MakePDFWarning{}              -> WARNING
+       UnclosedDiv{}                 -> WARNING
+       UnsupportedCodePage{}         -> WARNING
+       YamlWarning{}                 -> WARNING
+       UnsupportedPdfStandard{}      -> WARNING
diff --git a/src/Text/Pandoc/Lua.hs b/src/Text/Pandoc/Lua.hs
deleted file mode 100644
--- a/src/Text/Pandoc/Lua.hs
+++ /dev/null
@@ -1,87 +0,0 @@
-{-
-Copyright © 2017 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 Albert Krewinkel
-   License     : GNU GPL, version 2 or above
-
-   Maintainer  : Albert Krewinkel <tarleb+pandoc@moltkeplatz.de>
-   Stability   : alpha
-
-Running pandoc Lua filters.
--}
-module Text.Pandoc.Lua
-  ( LuaException (..)
-  , runLuaFilter
-  , runPandocLua
-  , pushPandocModule
-  ) where
-
-import Control.Monad (when, (>=>))
-import Foreign.Lua (FromLuaStack (peek), Lua, LuaException (..),
-                    Status (OK), ToLuaStack (push))
-import Text.Pandoc.Class (PandocIO)
-import Text.Pandoc.Definition (Pandoc)
-import Text.Pandoc.Lua.Filter (LuaFilter, walkMWithLuaFilter)
-import Text.Pandoc.Lua.Init (runPandocLua)
-import Text.Pandoc.Lua.Module.Pandoc (pushModule) -- TODO: remove
-import qualified Foreign.Lua as Lua
-
--- | Run the Lua filter in @filterPath@ for a transformation to target
--- format @format@. Pandoc uses Lua init files to setup the Lua
--- interpreter.
-runLuaFilter :: FilePath -> String
-             -> Pandoc -> PandocIO (Either LuaException Pandoc)
-runLuaFilter filterPath format doc =
-  runPandocLua (runLuaFilter' filterPath format doc)
-
-runLuaFilter' :: FilePath -> String
-              -> Pandoc -> Lua Pandoc
-runLuaFilter' filterPath format pd = do
-  -- store module in global "pandoc"
-  registerFormat
-  top <- Lua.gettop
-  stat <- Lua.dofile filterPath
-  if stat /= OK
-    then do
-      luaErrMsg <- peek (-1) <* Lua.pop 1
-      Lua.throwLuaError luaErrMsg
-    else do
-      newtop <- Lua.gettop
-      -- Use the implicitly defined global filter if nothing was returned
-      when (newtop - top < 1) pushGlobalFilter
-      luaFilters <- peek (-1)
-      runAll luaFilters pd
- where
-  registerFormat = do
-    push format
-    Lua.setglobal "FORMAT"
-
-pushGlobalFilter :: Lua ()
-pushGlobalFilter = do
-  Lua.newtable
-  Lua.getglobal' "pandoc.global_filter"
-  Lua.call 0 1
-  Lua.rawseti (-2) 1
-
-runAll :: [LuaFilter] -> Pandoc -> Lua Pandoc
-runAll = foldr ((>=>) . walkMWithLuaFilter) return
-
--- | DEPRECATED: Push the pandoc module to the Lua Stack.
-pushPandocModule :: Maybe FilePath -> Lua Lua.NumResults
-pushPandocModule = pushModule
diff --git a/src/Text/Pandoc/Lua/Filter.hs b/src/Text/Pandoc/Lua/Filter.hs
deleted file mode 100644
--- a/src/Text/Pandoc/Lua/Filter.hs
+++ /dev/null
@@ -1,168 +0,0 @@
-{-# LANGUAGE FlexibleContexts #-}
-
-module Text.Pandoc.Lua.Filter ( LuaFilterFunction
-                              , LuaFilter
-                              , tryFilter
-                              , runFilterFunction
-                              , walkMWithLuaFilter
-                              , walkInlines
-                              , walkBlocks
-                              , blockElementNames
-                              , inlineElementNames
-                              ) where
-import Control.Monad (mplus, unless, when, (>=>))
-import Text.Pandoc.Definition
-import Data.Foldable (foldrM)
-import Data.Map (Map)
-import qualified Data.Map as Map
-import qualified Foreign.Lua as Lua
-import Foreign.Lua (FromLuaStack (peek), Lua, StackIndex,
-                    Status (OK), ToLuaStack (push))
-import Text.Pandoc.Walk (walkM, Walkable)
-import Data.Data (Data, DataType, dataTypeConstrs, dataTypeName, dataTypeOf,
-                  showConstr, toConstr, tyconUQname)
-import Text.Pandoc.Lua.StackInstances()
-
-type FunctionMap = Map String LuaFilterFunction
-
-newtype LuaFilterFunction = LuaFilterFunction { functionIndex :: Int }
-
-instance ToLuaStack LuaFilterFunction where
-  push = pushFilterFunction
-
-instance FromLuaStack LuaFilterFunction where
-  peek = registerFilterFunction
-
-newtype LuaFilter = LuaFilter FunctionMap
-
-instance FromLuaStack LuaFilter where
-  peek idx =
-    let constrs = metaFilterName : pandocFilterNames
-                  ++ blockElementNames
-                  ++ inlineElementNames
-        fn c acc = do
-          Lua.getfield idx c
-          filterFn <- Lua.tryLua (peek (-1))
-          Lua.pop 1
-          return $ case filterFn of
-            Left _  -> acc
-            Right f -> (c, f) : acc
-    in LuaFilter . Map.fromList <$> foldrM fn [] constrs
-
--- | Push the filter function to the top of the stack.
-pushFilterFunction :: LuaFilterFunction -> Lua ()
-pushFilterFunction lf =
-  -- The function is stored in a lua registry table, retrieve it from there.
-  Lua.rawgeti Lua.registryindex (functionIndex lf)
-
-registerFilterFunction :: StackIndex -> Lua LuaFilterFunction
-registerFilterFunction idx = do
-  isFn <- Lua.isfunction idx
-  unless isFn . Lua.throwLuaError $ "Not a function at index " ++ show idx
-  Lua.pushvalue idx
-  refIdx <- Lua.ref Lua.registryindex
-  return $ LuaFilterFunction refIdx
-
-elementOrList :: FromLuaStack a => a -> Lua [a]
-elementOrList x = do
-  let topOfStack = Lua.StackIndex (-1)
-  elementUnchanged <- Lua.isnil topOfStack
-  if elementUnchanged
-    then [x] <$ Lua.pop 1
-    else do
-       mbres <- Lua.peekEither topOfStack
-       case mbres of
-         Right res -> [res] <$ Lua.pop 1
-         Left _    -> Lua.toList topOfStack <* Lua.pop 1
-
--- | Try running a filter for the given element
-tryFilter :: (Data a, FromLuaStack a, ToLuaStack a)
-          => LuaFilter -> a -> Lua [a]
-tryFilter (LuaFilter fnMap) x =
-  let filterFnName = showConstr (toConstr x)
-      catchAllName = tyconUQname $ dataTypeName (dataTypeOf x)
-  in
-  case Map.lookup filterFnName fnMap `mplus` Map.lookup catchAllName fnMap of
-    Just fn -> runFilterFunction fn x *> elementOrList x
-    Nothing -> return [x]
-
--- | Push a value to the stack via a lua filter function. The filter function is
--- called with given element as argument and is expected to return an element.
--- Alternatively, the function can return nothing or nil, in which case the
--- element is left unchanged.
-runFilterFunction :: ToLuaStack a => LuaFilterFunction -> a -> Lua ()
-runFilterFunction lf x = do
-  pushFilterFunction lf
-  push x
-  z <- Lua.pcall 1 1 Nothing
-  when (z /= OK) $ do
-    let addPrefix = ("Error while running filter function: " ++)
-    Lua.throwTopMessageAsError' addPrefix
-
-walkMWithLuaFilter :: LuaFilter -> Pandoc -> Lua Pandoc
-walkMWithLuaFilter f =
-  walkInlines f >=> walkBlocks f >=> walkMeta f >=> walkPandoc f
-
-mconcatMapM :: (Monad m, Functor m) => (a -> m [a]) -> [a] -> m [a]
-mconcatMapM f = fmap mconcat . mapM f
-
-hasOneOf :: LuaFilter -> [String] -> Bool
-hasOneOf (LuaFilter fnMap) = any (\k -> Map.member k fnMap)
-
-walkInlines :: Walkable [Inline] a => LuaFilter -> a -> Lua a
-walkInlines f =
-  if f `hasOneOf` inlineElementNames
-     then walkM (mconcatMapM (tryFilter f :: Inline -> Lua [Inline]))
-     else return
-
-walkBlocks :: Walkable [Block] a => LuaFilter -> a -> Lua a
-walkBlocks f =
-  if f `hasOneOf` blockElementNames
-     then walkM (mconcatMapM (tryFilter f :: Block -> Lua [Block]))
-     else return
-
-walkMeta :: LuaFilter -> Pandoc -> Lua Pandoc
-walkMeta (LuaFilter fnMap) =
-  case Map.lookup "Meta" fnMap of
-    Just fn -> walkM (\(Pandoc meta blocks) -> do
-                         meta' <- runFilterFunction fn meta *> singleElement meta
-                         return $ Pandoc meta' blocks)
-    Nothing -> return
-
-walkPandoc :: LuaFilter -> Pandoc -> Lua Pandoc
-walkPandoc (LuaFilter fnMap) =
-  case foldl mplus Nothing (map (`Map.lookup` fnMap) pandocFilterNames) of
-    Just fn -> \x -> runFilterFunction fn x *> singleElement x
-    Nothing -> return
-
-constructorsFor :: DataType -> [String]
-constructorsFor x = map show (dataTypeConstrs x)
-
-inlineElementNames :: [String]
-inlineElementNames = "Inline" : constructorsFor (dataTypeOf (Str []))
-
-blockElementNames :: [String]
-blockElementNames = "Block" : constructorsFor (dataTypeOf (Para []))
-
-metaFilterName :: String
-metaFilterName = "Meta"
-
-pandocFilterNames :: [String]
-pandocFilterNames = ["Pandoc", "Doc"]
-
-singleElement :: FromLuaStack a => a -> Lua a
-singleElement x = do
-  elementUnchanged <- Lua.isnil (-1)
-  if elementUnchanged
-    then x <$ Lua.pop 1
-    else do
-    mbres <- Lua.peekEither (-1)
-    case mbres of
-      Right res -> res <$ Lua.pop 1
-      Left err  -> do
-        Lua.pop 1
-        Lua.throwLuaError $
-          "Error while trying to get a filter's return " ++
-          "value from lua stack.\n" ++ err
-
-
diff --git a/src/Text/Pandoc/Lua/Init.hs b/src/Text/Pandoc/Lua/Init.hs
deleted file mode 100644
--- a/src/Text/Pandoc/Lua/Init.hs
+++ /dev/null
@@ -1,79 +0,0 @@
-{-
-Copyright © 2017 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 Albert Krewinkel
-   License     : GNU GPL, version 2 or above
-
-   Maintainer  : Albert Krewinkel <tarleb+pandoc@moltkeplatz.de>
-   Stability   : alpha
-
-Functions to initialize the Lua interpreter.
--}
-module Text.Pandoc.Lua.Init
-  ( LuaException (..)
-  , LuaPackageParams (..)
-  , runPandocLua
-  , initLuaState
-  , luaPackageParams
-  ) where
-
-import Control.Monad.Trans (MonadIO (..))
-import Data.IORef (newIORef, readIORef)
-import Foreign.Lua (Lua, LuaException (..))
-import GHC.IO.Encoding (getForeignEncoding, setForeignEncoding, utf8)
-import Text.Pandoc.Class (PandocIO, getCommonState, getUserDataDir, getMediaBag,
-                          setMediaBag)
-import Text.Pandoc.Lua.Packages (LuaPackageParams (..),
-                                 installPandocPackageSearcher)
-import Text.Pandoc.Lua.Util (loadScriptFromDataDir)
-
-import qualified Foreign.Lua as Lua
-import qualified Foreign.Lua.Module.Text as Lua
-
--- | Run the lua interpreter, using pandoc's default way of environment
--- initalization.
-runPandocLua :: Lua a -> PandocIO (Either LuaException a)
-runPandocLua luaOp = do
-  luaPkgParams <- luaPackageParams
-  enc <- liftIO $ getForeignEncoding <* setForeignEncoding utf8
-  res <- liftIO $ Lua.runLuaEither (initLuaState luaPkgParams *> luaOp)
-  liftIO $ setForeignEncoding enc
-  newMediaBag <- liftIO (readIORef (luaPkgMediaBag luaPkgParams))
-  setMediaBag newMediaBag
-  return res
-
--- | 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
-    }
-
--- Initialize the lua state with all required values
-initLuaState :: LuaPackageParams -> Lua ()
-initLuaState luaPkgParams = do
-  Lua.openlibs
-  Lua.preloadTextModule "text"
-  installPandocPackageSearcher luaPkgParams
-  loadScriptFromDataDir (luaPkgDataDir luaPkgParams) "init.lua"
diff --git a/src/Text/Pandoc/Lua/Module/MediaBag.hs b/src/Text/Pandoc/Lua/Module/MediaBag.hs
deleted file mode 100644
--- a/src/Text/Pandoc/Lua/Module/MediaBag.hs
+++ /dev/null
@@ -1,108 +0,0 @@
-{-
-Copyright © 2017 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 Albert Krewinkel
-   License     : GNU GPL, version 2 or above
-
-   Maintainer  : Albert Krewinkel <tarleb+pandoc@moltkeplatz.de>
-   Stability   : alpha
-
-The lua module @pandoc.mediabag@.
--}
-module Text.Pandoc.Lua.Module.MediaBag
-  ( pushModule
-  ) where
-
-import Control.Monad (zipWithM_)
-import Data.IORef (IORef, modifyIORef', readIORef)
-import Data.Maybe (fromMaybe)
-import Foreign.Lua (Lua, NumResults, liftIO)
-import Text.Pandoc.Class (CommonState (..), fetchItem, putCommonState,
-                          runIOorExplode, setMediaBag)
-import Text.Pandoc.Lua.StackInstances ()
-import Text.Pandoc.Lua.Util (OrNil (toMaybe), addFunction)
-import Text.Pandoc.MIME (MimeType)
-
-import qualified Data.ByteString.Lazy as BL
-import qualified Foreign.Lua as Lua
-import qualified Text.Pandoc.MediaBag as MB
-
---
--- MediaBag submodule
---
-pushModule :: CommonState -> IORef MB.MediaBag -> Lua NumResults
-pushModule commonState mediaBagRef = do
-  Lua.newtable
-  addFunction "insert" (insertMediaFn mediaBagRef)
-  addFunction "lookup" (lookupMediaFn mediaBagRef)
-  addFunction "list" (mediaDirectoryFn mediaBagRef)
-  addFunction "fetch" (fetch commonState mediaBagRef)
-  return 1
-
-insertMediaFn :: IORef MB.MediaBag
-              -> FilePath
-              -> OrNil MimeType
-              -> BL.ByteString
-              -> Lua NumResults
-insertMediaFn mbRef fp nilOrMime contents = do
-  liftIO . modifyIORef' mbRef $
-    MB.insertMedia fp (toMaybe nilOrMime) contents
-  return 0
-
-lookupMediaFn :: IORef MB.MediaBag
-              -> FilePath
-              -> Lua NumResults
-lookupMediaFn mbRef fp = do
-  res <- MB.lookupMedia fp <$> liftIO (readIORef mbRef)
-  case res of
-    Nothing -> Lua.pushnil *> return 1
-    Just (mimeType, contents) -> do
-      Lua.push mimeType
-      Lua.push contents
-      return 2
-
-mediaDirectoryFn :: IORef MB.MediaBag
-                 -> Lua NumResults
-mediaDirectoryFn mbRef = do
-  dirContents <- MB.mediaDirectory <$> liftIO (readIORef mbRef)
-  Lua.newtable
-  zipWithM_ addEntry [1..] dirContents
-  return 1
- where
-  addEntry :: Int -> (FilePath, MimeType, Int) -> Lua ()
-  addEntry idx (fp, mimeType, contentLength) = do
-    Lua.newtable
-    Lua.push "path" *> Lua.push fp *> Lua.rawset (-3)
-    Lua.push "type" *> Lua.push mimeType *> Lua.rawset (-3)
-    Lua.push "length" *> Lua.push contentLength *> Lua.rawset (-3)
-    Lua.rawseti (-2) idx
-
-fetch :: CommonState
-      -> IORef MB.MediaBag
-      -> String
-      -> Lua NumResults
-fetch commonState mbRef src = do
-  mediaBag <- liftIO $ readIORef mbRef
-  (bs, mimeType) <- liftIO . runIOorExplode $ do
-    putCommonState commonState
-    setMediaBag mediaBag
-    fetchItem src
-  Lua.push $ fromMaybe "" mimeType
-  Lua.push bs
-  return 2 -- returns 2 values: contents, mimetype
diff --git a/src/Text/Pandoc/Lua/Module/Pandoc.hs b/src/Text/Pandoc/Lua/Module/Pandoc.hs
deleted file mode 100644
--- a/src/Text/Pandoc/Lua/Module/Pandoc.hs
+++ /dev/null
@@ -1,135 +0,0 @@
-{-
-Copyright © 2017 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 #-}
-{- |
-   Module      : Text.Pandoc.Lua.Module.Pandoc
-   Copyright   : Copyright © 2017 Albert Krewinkel
-   License     : GNU GPL, version 2 or above
-
-   Maintainer  : Albert Krewinkel <tarleb+pandoc@moltkeplatz.de>
-   Stability   : alpha
-
-Pandoc module for lua.
--}
-module Text.Pandoc.Lua.Module.Pandoc
-  ( pushModule
-  ) where
-
-import Control.Monad (when)
-import Data.Default (Default (..))
-import Data.Maybe (fromMaybe)
-import Data.Text (pack)
-import Foreign.Lua (ToLuaStack, FromLuaStack, Lua, NumResults, liftIO)
-import System.Exit (ExitCode (..))
-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.Util (OrNil (toMaybe), addFunction, addValue,
-                             loadScriptFromDataDir, raiseError)
-import Text.Pandoc.Walk (Walkable)
-import Text.Pandoc.Options (ReaderOptions (readerExtensions))
-import Text.Pandoc.Process (pipeProcess)
-import Text.Pandoc.Readers (Reader (..), getReader)
-
-import qualified Data.ByteString.Lazy as BL
-import qualified Data.ByteString.Lazy.Char8 as BSL
-import qualified Foreign.Lua as Lua
-
--- | Push the "pandoc" on the lua stack. Requires the `list` module to be
--- loaded.
-pushModule :: Maybe FilePath -> Lua NumResults
-pushModule datadir = do
-  loadScriptFromDataDir datadir "pandoc.lua"
-  addFunction "read" readDoc
-  addFunction "pipe" pipeFn
-  addFunction "walk_block" walkBlock
-  addFunction "walk_inline" walkInline
-  return 1
-
-walkElement :: (ToLuaStack a, Walkable [Inline] a, Walkable [Block] a)
-            => a -> LuaFilter -> Lua a
-walkElement x f = walkInlines f x >>= walkBlocks f
-
-walkInline :: Inline -> LuaFilter -> Lua Inline
-walkInline = walkElement
-
-walkBlock :: Block -> LuaFilter -> Lua Block
-walkBlock = walkElement
-
-readDoc :: String -> OrNil String -> Lua NumResults
-readDoc content formatSpecOrNil = do
-  let formatSpec = fromMaybe "markdown" (toMaybe formatSpecOrNil)
-  case getReader formatSpec of
-    Left  s      -> raiseError s -- Unknown reader
-    Right (reader, es) ->
-      case reader of
-        TextReader r -> do
-          res <- liftIO $ runIO $ r def{ readerExtensions = es } (pack content)
-          case res of
-            Right pd -> (1 :: NumResults) <$ Lua.push pd -- success, push Pandoc
-            Left s   -> raiseError (show s)              -- error while reading
-        _  -> raiseError "Only string formats are supported at the moment."
-
--- | Pipes input through a command.
-pipeFn :: String
-       -> [String]
-       -> BL.ByteString
-       -> Lua NumResults
-pipeFn command args input = do
-  (ec, output) <- liftIO $ pipeProcess Nothing command args input
-  case ec of
-    ExitSuccess -> 1 <$ Lua.push output
-    ExitFailure n -> raiseError (PipeError command n output)
-
-data PipeError = PipeError
-  { pipeErrorCommand :: String
-  , pipeErrorCode :: Int
-  , pipeErrorOutput :: BL.ByteString
-  }
-
-instance FromLuaStack PipeError where
-  peek idx =
-    PipeError
-    <$> (Lua.getfield idx "command"    *> Lua.peek (-1) <* Lua.pop 1)
-    <*> (Lua.getfield idx "error_code" *> Lua.peek (-1) <* Lua.pop 1)
-    <*> (Lua.getfield idx "output"     *> Lua.peek (-1) <* Lua.pop 1)
-
-instance ToLuaStack PipeError where
-  push pipeErr = do
-    Lua.newtable
-    addValue "command" (pipeErrorCommand pipeErr)
-    addValue "error_code" (pipeErrorCode pipeErr)
-    addValue "output" (pipeErrorOutput pipeErr)
-    pushPipeErrorMetaTable
-    Lua.setmetatable (-2)
-      where
-        pushPipeErrorMetaTable :: Lua ()
-        pushPipeErrorMetaTable = do
-          v <- Lua.newmetatable "pandoc pipe error"
-          when v $ addFunction "__tostring" pipeErrorMessage
-
-        pipeErrorMessage :: PipeError -> Lua BL.ByteString
-        pipeErrorMessage (PipeError cmd errorCode output) = return $ mconcat
-          [ BSL.pack "Error running "
-          , BSL.pack cmd
-          , BSL.pack " (error code "
-          , BSL.pack $ show errorCode
-          , BSL.pack "): "
-          , if output == mempty then BSL.pack "<no output>" else output
-          ]
diff --git a/src/Text/Pandoc/Lua/Module/Utils.hs b/src/Text/Pandoc/Lua/Module/Utils.hs
deleted file mode 100644
--- a/src/Text/Pandoc/Lua/Module/Utils.hs
+++ /dev/null
@@ -1,100 +0,0 @@
-{-
-Copyright © 2017 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 Albert Krewinkel
-   License     : GNU GPL, version 2 or above
-
-   Maintainer  : Albert Krewinkel <tarleb+pandoc@moltkeplatz.de>
-   Stability   : alpha
-
-Utility module for lua, exposing internal helper functions.
--}
-module Text.Pandoc.Lua.Module.Utils
-  ( pushModule
-  ) where
-
-import Control.Applicative ((<|>))
-import Foreign.Lua (FromLuaStack, Lua, LuaInteger, NumResults)
-import Text.Pandoc.Definition (Pandoc, Meta, Block, Inline)
-import Text.Pandoc.Lua.StackInstances ()
-import Text.Pandoc.Lua.Util (OrNil (OrNil), addFunction)
-
-import qualified Data.Digest.Pure.SHA as SHA
-import qualified Data.ByteString.Lazy as BSL
-import qualified Foreign.Lua as Lua
-import qualified Text.Pandoc.Shared as Shared
-
--- | Push the "pandoc.utils" module to the lua stack.
-pushModule :: Lua NumResults
-pushModule = do
-  Lua.newtable
-  addFunction "hierarchicalize" hierarchicalize
-  addFunction "normalize_date" normalizeDate
-  addFunction "sha1" sha1
-  addFunction "stringify" stringify
-  addFunction "to_roman_numeral" toRomanNumeral
-  return 1
-
--- | Convert list of Pandoc blocks into (hierarchical) list of Elements.
-hierarchicalize :: [Block] -> Lua [Shared.Element]
-hierarchicalize = return . Shared.hierarchicalize
-
--- | Parse a date and convert (if possible) to "YYYY-MM-DD" format. We
--- limit years to the range 1601-9999 (ISO 8601 accepts greater than
--- or equal to 1583, but MS Word only accepts dates starting 1601).
--- Returns nil instead of a string if the conversion failed.
-normalizeDate :: String -> Lua (OrNil String)
-normalizeDate = return . OrNil . Shared.normalizeDate
-
--- | Calculate the hash of the given contents.
-sha1 :: BSL.ByteString
-     -> Lua String
-sha1 = return . SHA.showDigest . SHA.sha1
-
--- | Convert pandoc structure to a string with formatting removed.
--- Footnotes are skipped (since we don't want their contents in link
--- labels).
-stringify :: AstElement -> Lua String
-stringify el = return $ case el of
-  PandocElement pd -> Shared.stringify pd
-  InlineElement i  -> Shared.stringify i
-  BlockElement b   -> Shared.stringify b
-  MetaElement m    -> Shared.stringify m
-
-data AstElement
-  = PandocElement Pandoc
-  | MetaElement Meta
-  | BlockElement Block
-  | InlineElement Inline
-  deriving (Show)
-
-instance FromLuaStack AstElement where
-  peek idx  = do
-    res <- Lua.tryLua $  (PandocElement <$> Lua.peek idx)
-                     <|> (InlineElement <$> Lua.peek idx)
-                     <|> (BlockElement <$> Lua.peek idx)
-                     <|> (MetaElement <$> Lua.peek idx)
-    case res of
-      Right x -> return x
-      Left _ -> Lua.throwLuaError
-        "Expected an AST element, but could not parse value as such."
-
--- | Convert a number < 4000 to uppercase roman numeral.
-toRomanNumeral :: LuaInteger -> Lua String
-toRomanNumeral = return . Shared.toRomanNumeral . fromIntegral
diff --git a/src/Text/Pandoc/Lua/Packages.hs b/src/Text/Pandoc/Lua/Packages.hs
deleted file mode 100644
--- a/src/Text/Pandoc/Lua/Packages.hs
+++ /dev/null
@@ -1,115 +0,0 @@
-{-
-Copyright © 2017 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 ScopedTypeVariables #-}
-{-# LANGUAGE FlexibleContexts #-}
-{- |
-   Module      : Text.Pandoc.Lua.Packages
-   Copyright   : Copyright © 2017 Albert Krewinkel
-   License     : GNU GPL, version 2 or above
-
-   Maintainer  : Albert Krewinkel <tarleb+pandoc@moltkeplatz.de>
-   Stability   : alpha
-
-Pandoc module for lua.
--}
-module Text.Pandoc.Lua.Packages
-  ( LuaPackageParams (..)
-  , installPandocPackageSearcher
-  ) where
-
-import Control.Monad (forM_)
-import Data.ByteString.Char8 (unpack)
-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.Lua.Util (dostring')
-
-import qualified Foreign.Lua as Lua
-import Text.Pandoc.Lua.Module.Pandoc as Pandoc
-import Text.Pandoc.Lua.Module.MediaBag as MediaBag
-import Text.Pandoc.Lua.Module.Utils as Utils
-
--- | Parameters used to create lua packages/modules.
-data LuaPackageParams = LuaPackageParams
-  { luaPkgCommonState :: CommonState
-  , luaPkgDataDir :: Maybe FilePath
-  , luaPkgMediaBag :: IORef MediaBag
-  }
-
--- | Insert pandoc's package loader as the first loader, making it the default.
-installPandocPackageSearcher :: LuaPackageParams -> Lua ()
-installPandocPackageSearcher luaPkgParams = do
-  luaVersion <- Lua.getglobal "_VERSION" *> Lua.peek (-1)
-  if luaVersion == "Lua 5.1"
-    then Lua.getglobal' "package.loaders"
-    else Lua.getglobal' "package.searchers"
-  shiftArray
-  Lua.pushHaskellFunction (pandocPackageSearcher luaPkgParams)
-  Lua.wrapHaskellFunction
-  Lua.rawseti (-2) 1
-  Lua.pop 1           -- remove 'package.searchers' from stack
- where
-  shiftArray = forM_ [4, 3, 2, 1] $ \i -> do
-    Lua.rawgeti (-1) i
-    Lua.rawseti (-2) (i + 1)
-
--- | Load a pandoc module.
-pandocPackageSearcher :: LuaPackageParams -> String -> Lua NumResults
-pandocPackageSearcher luaPkgParams pkgName =
-  case pkgName of
-    "pandoc"          -> let datadir = luaPkgDataDir luaPkgParams
-                         in pushWrappedHsFun (Pandoc.pushModule datadir)
-    "pandoc.mediabag" -> let st    = luaPkgCommonState luaPkgParams
-                             mbRef = luaPkgMediaBag luaPkgParams
-                         in pushWrappedHsFun (MediaBag.pushModule st mbRef)
-    "pandoc.utils"    -> pushWrappedHsFun Utils.pushModule
-    _ -> searchPureLuaLoader
- where
-  pushWrappedHsFun f = do
-    Lua.pushHaskellFunction f
-    Lua.wrapHaskellFunction
-    return 1
-  searchPureLuaLoader = do
-    let filename = pkgName ++ ".lua"
-    modScript <- liftIO (dataDirScript (luaPkgDataDir luaPkgParams) filename)
-    case modScript of
-      Just script -> pushWrappedHsFun (loadStringAsPackage pkgName script)
-      Nothing -> do
-        Lua.push ("no file '" ++ filename ++ "' in pandoc's datadir")
-        return 1
-
-loadStringAsPackage :: String -> String -> Lua NumResults
-loadStringAsPackage pkgName script = do
-  status <- dostring' script
-  if status == Lua.OK
-    then return (1 :: NumResults)
-    else do
-      msg <- Lua.peek (-1) <* Lua.pop 1
-      Lua.push ("Error while loading ``" ++ pkgName ++ "`.\n" ++ msg)
-      Lua.lerror
-      return (2 :: NumResults)
-
--- | Get the string representation of the pandoc module
-dataDirScript :: Maybe FilePath -> FilePath -> IO (Maybe String)
-dataDirScript datadir moduleFile = do
-  res <- runIO $ setUserDataDir datadir >> readDataFile moduleFile
-  return $ case res of
-    Left _ -> Nothing
-    Right s -> Just (unpack s)
-
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,334 +0,0 @@
-{-
-Copyright © 2012-2017 John MacFarlane <jgm@berkeley.edu>
-            2017 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        #-}
-{-# OPTIONS_GHC -fno-warn-orphans #-}
-{- |
-   Module      : Text.Pandoc.Lua.StackInstances
-   Copyright   : © 2012-2017 John MacFarlane
-                 © 2017 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 Control.Applicative ((<|>))
-import Control.Monad (when)
-import Foreign.Lua (FromLuaStack (peek), Lua, LuaInteger, LuaNumber, StackIndex,
-                    ToLuaStack (push), Type (..), throwLuaError, tryLua)
-import Text.Pandoc.Definition
-import Text.Pandoc.Lua.Util (adjustIndexBy, getTable, pushViaConstructor)
-import Text.Pandoc.Shared (Element (Blk, Sec), safeRead)
-
-import qualified Foreign.Lua as Lua
-import qualified Text.Pandoc.Lua.Util as LuaUtil
-
-instance ToLuaStack Pandoc where
-  push (Pandoc meta blocks) =
-    pushViaConstructor "Pandoc" blocks meta
-
-instance FromLuaStack Pandoc where
-  peek idx = do
-    blocks <- getTable idx "blocks"
-    meta   <- getTable idx "meta"
-    return $ Pandoc meta blocks
-
-instance ToLuaStack Meta where
-  push (Meta mmap) =
-    pushViaConstructor "Meta" mmap
-instance FromLuaStack Meta where
-  peek idx = Meta <$> peek idx
-
-instance ToLuaStack MetaValue where
-  push = pushMetaValue
-instance FromLuaStack MetaValue where
-  peek = peekMetaValue
-
-instance ToLuaStack Block where
-  push = pushBlock
-
-instance FromLuaStack Block where
-  peek = peekBlock
-
--- Inline
-instance ToLuaStack Inline where
-  push = pushInline
-
-instance FromLuaStack Inline where
-  peek = peekInline
-
--- Citation
-instance ToLuaStack Citation where
-  push (Citation cid prefix suffix mode noteNum hash) =
-    pushViaConstructor "Citation" cid mode prefix suffix noteNum hash
-
-instance FromLuaStack Citation where
-  peek idx = do
-    id' <- getTable idx "citationId"
-    prefix <- getTable idx "citationPrefix"
-    suffix <- getTable idx "citationSuffix"
-    mode <- getTable idx "citationMode"
-    num <- getTable idx "citationNoteNum"
-    hash <- getTable idx "citationHash"
-    return $ Citation id' prefix suffix mode num hash
-
-instance ToLuaStack Alignment where
-  push = push . show
-instance FromLuaStack Alignment where
-  peek idx = safeRead' =<< peek idx
-
-instance ToLuaStack CitationMode where
-  push = push . show
-instance FromLuaStack CitationMode where
-  peek idx = safeRead' =<< peek idx
-
-instance ToLuaStack Format where
-  push (Format f) = push f
-instance FromLuaStack Format where
-  peek idx = Format <$> peek idx
-
-instance ToLuaStack ListNumberDelim where
-  push = push . show
-instance FromLuaStack ListNumberDelim where
-  peek idx = safeRead' =<< peek idx
-
-instance ToLuaStack ListNumberStyle where
-  push = push . show
-instance FromLuaStack ListNumberStyle where
-  peek idx = safeRead' =<< peek idx
-
-instance ToLuaStack MathType where
-  push = push . show
-instance FromLuaStack MathType where
-  peek idx = safeRead' =<< peek idx
-
-instance ToLuaStack QuoteType where
-  push = push . show
-instance FromLuaStack QuoteType where
-  peek idx = safeRead' =<< peek idx
-
-instance ToLuaStack Double where
-  push = push . (realToFrac :: Double -> LuaNumber)
-instance FromLuaStack Double where
-  peek = fmap (realToFrac :: LuaNumber -> Double) . peek
-
-instance ToLuaStack Int where
-  push = push . (fromIntegral :: Int -> LuaInteger)
-instance FromLuaStack Int where
-  peek = fmap (fromIntegral :: LuaInteger-> Int) . peek
-
-safeRead' :: Read a => String -> Lua a
-safeRead' s = case safeRead s of
-  Nothing -> throwLuaError ("Could not read: " ++ s)
-  Just x  -> return x
-
--- | Push an meta value element to the top of the lua stack.
-pushMetaValue :: MetaValue -> Lua ()
-pushMetaValue = \case
-  MetaBlocks blcks  -> pushViaConstructor "MetaBlocks" blcks
-  MetaBool bool     -> push bool
-  MetaInlines inlns -> pushViaConstructor "MetaInlines" inlns
-  MetaList metalist -> pushViaConstructor "MetaList" metalist
-  MetaMap metamap   -> pushViaConstructor "MetaMap" metamap
-  MetaString str    -> push str
-
--- | Interpret the value at the given stack index as meta value.
-peekMetaValue :: StackIndex -> Lua MetaValue
-peekMetaValue idx = do
-  -- Get the contents of an AST element.
-  let elementContent :: FromLuaStack a => Lua a
-      elementContent = peek idx
-  luatype <- Lua.ltype idx
-  case luatype of
-    TypeBoolean -> MetaBool <$> peek idx
-    TypeString  -> MetaString <$> peek idx
-    TypeTable   -> do
-      tag <- tryLua $ 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             -> throwLuaError ("Unknown meta tag: " ++ t)
-        Left _ -> do
-          -- no meta value tag given, try to guess.
-          len <- Lua.rawlen idx
-          if len <= 0
-            then MetaMap <$> peek idx
-            else  (MetaInlines <$> peek idx)
-                  <|> (MetaBlocks <$> peek idx)
-                  <|> (MetaList <$> peek idx)
-    _        -> throwLuaError "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 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 = do
-  tag <- 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"    -> uncurry OrderedList <$> 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
-      _ -> throwLuaError ("Unknown block type: " ++ tag)
- where
-   -- Get the contents of an AST element.
-   elementContent :: FromLuaStack a => Lua a
-   elementContent = getTable 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 = do
-  tag <- 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
-    _ -> throwLuaError ("Unknown inline type: " ++ tag)
- where
-   -- Get the contents of an AST element.
-   elementContent :: FromLuaStack a => Lua a
-   elementContent = getTable idx "c"
-
-getTag :: StackIndex -> Lua String
-getTag idx = do
-  top <- Lua.gettop
-  hasMT <- Lua.getmetatable idx
-  push "tag"
-  if hasMT then Lua.rawget (-2) else Lua.rawget (idx `adjustIndexBy` 1)
-  r <- tryLua (peek (-1))
-  Lua.settop top
-  case r of
-    Left (Lua.LuaException err) -> throwLuaError err
-    Right res                   -> return res
-
-withAttr :: (Attr -> a -> b) -> (LuaAttr, a) -> b
-withAttr f (attributes, x) = f (fromLuaAttr attributes) x
-
--- | Wrapper for Attr
-newtype LuaAttr = LuaAttr { fromLuaAttr :: Attr }
-
-instance ToLuaStack LuaAttr where
-  push (LuaAttr (id', classes, kv)) =
-    pushViaConstructor "Attr" id' classes kv
-
-instance FromLuaStack LuaAttr where
-  peek idx = LuaAttr <$> peek idx
-
---
--- Hierarchical elements
---
-instance ToLuaStack Element where
-  push (Blk blk) = push blk
-  push (Sec lvl num attr label contents) = do
-    Lua.newtable
-    LuaUtil.addValue "level" lvl
-    LuaUtil.addValue "numbering" num
-    LuaUtil.addValue "attr" (LuaAttr attr)
-    LuaUtil.addValue "label" label
-    LuaUtil.addValue "contents" contents
-    pushSecMetaTable
-    Lua.setmetatable (-2)
-      where
-        pushSecMetaTable :: Lua ()
-        pushSecMetaTable = do
-          inexistant <- Lua.newmetatable "PandocElementSec"
-          when inexistant $ do
-            LuaUtil.addValue "t" "Sec"
-            Lua.push "__index"
-            Lua.pushvalue (-2)
-            Lua.rawset (-3)
diff --git a/src/Text/Pandoc/Lua/Util.hs b/src/Text/Pandoc/Lua/Util.hs
deleted file mode 100644
--- a/src/Text/Pandoc/Lua/Util.hs
+++ /dev/null
@@ -1,179 +0,0 @@
-{-
-Copyright © 2012-2017 John MacFarlane <jgm@berkeley.edu>
-            2017 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 #-}
-{- |
-   Module      : Text.Pandoc.Lua.Util
-   Copyright   : © 2012–2017 John MacFarlane,
-                 © 2017 Albert Krewinkel
-   License     : GNU GPL, version 2 or above
-
-   Maintainer  : Albert Krewinkel <tarleb+pandoc@moltkeplatz.de>
-   Stability   : alpha
-
-Lua utility functions.
--}
-module Text.Pandoc.Lua.Util
-  ( adjustIndexBy
-  , getTable
-  , addValue
-  , addFunction
-  , getRawInt
-  , setRawInt
-  , addRawInt
-  , raiseError
-  , OrNil (..)
-  , PushViaCall
-  , pushViaCall
-  , pushViaConstructor
-  , loadScriptFromDataDir
-  , dostring'
-  ) where
-
-import Control.Monad (when)
-import Data.ByteString.Char8 (unpack)
-import Foreign.Lua (FromLuaStack (..), NumResults, Lua, NumArgs, StackIndex,
-                    ToLuaStack (..), ToHaskellFunction, getglobal')
-import Foreign.Lua.Api (Status, call, pop, rawget, rawgeti, rawset, rawseti)
-import Text.Pandoc.Class (readDataFile, runIOorExplode, setUserDataDir)
-
-import qualified Foreign.Lua as Lua
-
--- | Adjust the stack index, assuming that @n@ new elements have been pushed on
--- the stack.
-adjustIndexBy :: StackIndex -> StackIndex -> StackIndex
-adjustIndexBy idx n =
-  if idx < 0
-  then idx - n
-  else idx
-
--- | Get value behind key from table at given index.
-getTable :: (ToLuaStack a, FromLuaStack b) => StackIndex -> a -> Lua b
-getTable idx key = do
-  push key
-  rawget (idx `adjustIndexBy` 1)
-  popValue
-
--- | Add a key-value pair to the table at the top of the stack.
-addValue :: (ToLuaStack a, ToLuaStack b) => a -> b -> Lua ()
-addValue key value = do
-  push key
-  push value
-  rawset (-3)
-
--- | Add a function to the table at the top of the stack, using the given name.
-addFunction :: ToHaskellFunction a => String -> a -> Lua ()
-addFunction name fn = do
-  Lua.push name
-  Lua.pushHaskellFunction fn
-  Lua.wrapHaskellFunction
-  Lua.rawset (-3)
-
--- | Get value behind key from table at given index.
-getRawInt :: FromLuaStack a => StackIndex -> Int -> Lua a
-getRawInt idx key = do
-  rawgeti idx key
-  popValue
-
--- | Set numeric key/value in table at the given index
-setRawInt :: ToLuaStack a => StackIndex -> Int -> a -> Lua ()
-setRawInt idx key value = do
-  push value
-  rawseti (idx `adjustIndexBy` 1) key
-
--- | Set numeric key/value in table at the top of the stack.
-addRawInt :: ToLuaStack a => Int -> a -> Lua ()
-addRawInt = setRawInt (-1)
-
-raiseError :: ToLuaStack a => a -> Lua NumResults
-raiseError e = do
-  Lua.push e
-  fromIntegral <$> Lua.lerror
-
--- | Get, then pop the value at the top of the stack.
-popValue :: FromLuaStack a => Lua a
-popValue = do
-  resOrError <- Lua.peekEither (-1)
-  pop 1
-  case resOrError of
-    Left err -> Lua.throwLuaError err
-    Right x -> return x
-
--- | Newtype wrapper intended to be used for optional Lua values. Nesting this
--- type is strongly discouraged and will likely lead to a wrong result.
-newtype OrNil a = OrNil { toMaybe :: Maybe a }
-
-instance FromLuaStack a => FromLuaStack (OrNil a) where
-  peek idx = do
-    noValue <- Lua.isnoneornil idx
-    if noValue
-      then return (OrNil Nothing)
-      else OrNil . Just <$> Lua.peek idx
-
-instance ToLuaStack a => ToLuaStack (OrNil a) where
-  push (OrNil Nothing)  = Lua.pushnil
-  push (OrNil (Just x)) = Lua.push x
-
--- | Helper class for pushing a single value to the stack via a lua function.
--- See @pushViaCall@.
-class PushViaCall a where
-  pushViaCall' :: String -> Lua () -> NumArgs -> a
-
-instance PushViaCall (Lua ()) where
-  pushViaCall' fn pushArgs num = do
-    getglobal' fn
-    pushArgs
-    call num 1
-
-instance (ToLuaStack a, PushViaCall b) => PushViaCall (a -> b) where
-  pushViaCall' fn pushArgs num x =
-    pushViaCall' fn (pushArgs *> push x) (num + 1)
-
--- | Push an value to the stack via a lua function. The lua function is called
--- with all arguments that are passed to this function and is expected to return
--- a single value.
-pushViaCall :: PushViaCall a => String -> a
-pushViaCall fn = pushViaCall' fn (return ()) 0
-
--- | Call a pandoc element constructor within lua, passing all given arguments.
-pushViaConstructor :: PushViaCall a => String -> a
-pushViaConstructor pandocFn = pushViaCall ("pandoc." ++ pandocFn)
-
--- | Load a file from pandoc's data directory.
-loadScriptFromDataDir :: Maybe FilePath -> FilePath -> Lua ()
-loadScriptFromDataDir datadir scriptFile = do
-  script <- fmap unpack . Lua.liftIO . runIOorExplode $
-            setUserDataDir datadir >> readDataFile scriptFile
-  status <- dostring' script
-  when (status /= Lua.OK) .
-    Lua.throwTopMessageAsError' $ \msg ->
-      "Couldn't load '" ++ scriptFile ++ "'.\n" ++ msg
-
--- | Load a string and immediately perform a full garbage collection. This is
--- important to keep the program from hanging: If the program contained a call
--- to @require@, the a new loader function was created which then become
--- garbage. If that function is collected at an inopportune times, i.e. when the
--- Lua API is called via a function that doesn't allow calling back into Haskell
--- (getraw, setraw, …). The function's finalizer, and the full program, hangs
--- when that happens.
-dostring' :: String -> Lua Status
-dostring' script = do
-  loadRes <- Lua.loadstring script
-  if loadRes == Lua.OK
-    then Lua.pcall 0 1 Nothing <* Lua.gc Lua.GCCOLLECT 0
-    else return loadRes
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,41 +1,32 @@
-{-
-Copyright (C) 2011-2017 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 OverloadedStrings #-}
 {- |
    Module      : Text.Pandoc.MIME
-   Copyright   : Copyright (C) 2011-2017 John MacFarlane
+   Copyright   : Copyright (C) 2011-2024 John MacFarlane
    License     : GNU GPL, version 2 or above
 
    Maintainer  : John MacFarlane <jgm@berkeley.edu>
    Stability   : alpha
    Portability : portable
 
-Mime type lookup for ODT writer.
+Mime type lookup.
 -}
-module Text.Pandoc.MIME ( MimeType, getMimeType, getMimeTypeDef,
-                          extensionFromMimeType )where
-import Data.Char (toLower)
+module Text.Pandoc.MIME (
+  MimeType,
+  getMimeType,
+  getMimeTypeDef,
+  getCharset,
+  extensionFromMimeType,
+  mediaCategory ) where
 import Data.List (isPrefixOf, isSuffixOf)
 import qualified Data.Map as M
-import Data.Maybe (fromMaybe)
+import qualified Data.Text as T
+import qualified Data.Text.Encoding as T
+import Data.Maybe (fromMaybe, listToMaybe)
+import Data.Tuple (swap)
+import qualified Network.Mime
 import System.FilePath
 
-type MimeType = String
+type MimeType = T.Text
 
 -- | Determine mime type appropriate for file path.
 getMimeType :: FilePath -> Maybe MimeType
@@ -46,55 +37,67 @@
   | "Formula-" `isPrefixOf` fp && "/" `isSuffixOf` fp =
         Just "application/vnd.oasis.opendocument.formula"
   -- generic
-  | otherwise = M.lookup (map toLower $ drop 1 $ takeExtension fp) mimeTypes
+  | otherwise = M.lookup (T.toLower $ T.drop 1 $ T.pack $ takeExtension fp) mimeTypes
 
 -- | Determime mime type appropriate for file path, defaulting to
 -- “application/octet-stream” if nothing else fits.
 getMimeTypeDef :: FilePath -> MimeType
 getMimeTypeDef = fromMaybe "application/octet-stream" . getMimeType
 
-extensionFromMimeType :: MimeType -> Maybe String
+extensionFromMimeType :: MimeType -> Maybe T.Text
 extensionFromMimeType mimetype =
-  M.lookup (takeWhile (/=';') mimetype) reverseMimeTypes
   -- note:  we just look up the basic mime type, dropping the content-encoding etc.
+  case T.takeWhile (/=';') mimetype of
+    -- handle a few special cases, where there are multiple options:
+    "text/plain" -> Just "txt"
+    "video/quicktime" -> Just "mov"
+    "video/mpeg" -> Just "mpeg"
+    "video/dv" -> Just "dv"
+    "image/vnd.djvu" -> Just "djvu"
+    "image/tiff" -> Just "tiff"
+    "image/jpeg" -> Just "jpg"
+    "application/xml" -> Just "xml"
+    "application/ogg" -> Just "ogg"
+    "image/svg+xml" -> Just "svg" -- avoid svgz
+    mt -> M.lookup mt reverseMimeTypes
 
-reverseMimeTypes :: M.Map MimeType String
-reverseMimeTypes = M.fromList $ map (\(k,v) -> (v,k)) mimeTypesList
+-- | Determine general media category for file path, e.g.
+--
+-- prop> mediaCategory "foo.jpg" = Just "image"
+mediaCategory :: FilePath -> Maybe T.Text
+mediaCategory fp = getMimeType fp >>= listToMaybe . T.splitOn "/"
 
-mimeTypes :: M.Map String MimeType
+reverseMimeTypes :: M.Map MimeType T.Text
+reverseMimeTypes = M.fromList $ map swap mimeTypesList
+
+mimeTypes :: M.Map T.Text MimeType
 mimeTypes = M.fromList mimeTypesList
 
-mimeTypesList :: [(String, MimeType)]
-mimeTypesList = -- List borrowed from happstack-server.
-           [("gz","application/x-gzip")
-           ,("cabal","application/x-cabal")
-           ,("%","application/x-trash")
+-- | Get the charset from a mime type, if one is present.
+getCharset :: MimeType -> Maybe T.Text
+getCharset mt =
+  let (_,y) = T.breakOn "charset=" mt
+   in if T.null y
+         then Nothing
+         else Just $ T.toUpper $ T.takeWhile (/= ';') $ T.drop 8 y
+
+-- | Collection of common mime types.
+-- Except for first entry, list borrowed from
+-- <https://github.com/Happstack/happstack-server/blob/master/src/Happstack/Server/FileServe/BuildingBlocks.hs happstack-server>
+mimeTypesList :: [(T.Text, MimeType)]
+mimeTypesList = M.toList (M.map T.decodeUtf8 Network.Mime.defaultMimeMap) ++
+           [("%","application/x-trash")
            ,("323","text/h323")
-           ,("3gp","video/3gpp")
-           ,("7z","application/x-7z-compressed")
-           ,("abw","application/x-abiword")
-           ,("ai","application/postscript")
-           ,("aif","audio/x-aiff")
-           ,("aifc","audio/x-aiff")
-           ,("aiff","audio/x-aiff")
            ,("alc","chemical/x-alchemy")
+           ,("apng","image/apng")
            ,("art","image/x-jg")
-           ,("asc","text/plain")
-           ,("asf","video/x-ms-asf")
            ,("asn","chemical/x-ncbi-asn1")
            ,("aso","chemical/x-ncbi-asn1-binary")
-           ,("asx","video/x-ms-asf")
-           ,("atom","application/atom")
-           ,("atomcat","application/atomcat+xml")
            ,("atomsrv","application/atomserv+xml")
-           ,("au","audio/basic")
-           ,("avi","video/x-msvideo")
+           ,("avif", "image/avif")
            ,("b","chemical/x-molconn-Z")
            ,("bak","application/x-trash")
            ,("bat","application/x-msdos-program")
-           ,("bcpio","application/x-bcpio")
-           ,("bib","text/x-bibtex")
-           ,("bin","application/octet-stream")
            ,("bmp","image/x-ms-bmp")
            ,("boo","text/x-boo")
            ,("book","application/x-maker")
@@ -102,89 +105,55 @@
            ,("c","text/x-csrc")
            ,("c++","text/x-c++src")
            ,("c3d","chemical/x-chem3d")
-           ,("cab","application/x-cab")
+           ,("cabal","application/x-cabal")
            ,("cac","chemical/x-cache")
            ,("cache","chemical/x-cache")
-           ,("cap","application/cap")
            ,("cascii","chemical/x-cactvs-binary")
-           ,("cat","application/vnd.ms-pki.seccat")
            ,("cbin","chemical/x-cactvs-binary")
-           ,("cbr","application/x-cbr")
            ,("cbz","application/x-cbz")
            ,("cc","text/x-c++src")
            ,("cdf","application/x-cdf")
            ,("cdr","image/x-coreldraw")
            ,("cdt","image/x-coreldrawtemplate")
-           ,("cdx","chemical/x-cdx")
-           ,("cdy","application/vnd.cinderella")
            ,("cef","chemical/x-cxf")
            ,("cer","chemical/x-cerius")
            ,("chm","chemical/x-chemdraw")
            ,("chrt","application/x-kchart")
-           ,("cif","chemical/x-cif")
-           ,("class","application/java-vm")
-           ,("cls","text/x-tex")
-           ,("cmdf","chemical/x-cmdf")
-           ,("cml","chemical/x-cml")
-           ,("cod","application/vnd.rim.cod")
            ,("com","application/x-msdos-program")
            ,("cpa","chemical/x-compass")
-           ,("cpio","application/x-cpio")
            ,("cpp","text/x-c++src")
-           ,("cpt","application/mac-compactpro")
+           ,("cpt","image/x-corelphotopaint")
            ,("crl","application/x-pkcs7-crl")
-           ,("crt","application/x-x509-ca-cert")
            ,("csf","chemical/x-cache-csf")
-           ,("csh","application/x-csh")
            ,("csm","chemical/x-csml")
-           ,("csml","chemical/x-csml")
-           ,("css","text/css")
-           ,("csv","text/csv")
            ,("ctab","chemical/x-cactvs-binary")
            ,("ctx","chemical/x-ctx")
-           ,("cu","application/cu-seeme")
            ,("cub","chemical/x-gaussian-cube")
            ,("cxf","chemical/x-cxf")
            ,("cxx","text/x-c++src")
            ,("d","text/x-dsrc")
            ,("dat","chemical/x-mopac-input")
-           ,("dcr","application/x-director")
-           ,("deb","application/x-debian-package")
            ,("dif","video/dv")
            ,("diff","text/x-diff")
-           ,("dir","application/x-director")
-           ,("djv","image/vnd.djvu")
-           ,("djvu","image/vnd.djvu")
            ,("dl","video/dl")
            ,("dll","application/x-msdos-program")
-           ,("dmg","application/x-apple-diskimage")
            ,("dms","application/x-dms")
-           ,("doc","application/msword")
-           ,("dot","application/msword")
-           ,("dv","video/dv")
-           ,("dvi","application/x-dvi")
            ,("dx","chemical/x-jcamp-dx")
-           ,("dxr","application/x-director")
            ,("emb","chemical/x-embl-dl-nucleotide")
            ,("embl","chemical/x-embl-dl-nucleotide")
            ,("emf","image/x-emf")
-           ,("emz","application/x-msmetafile")
-           ,("eml","message/rfc822")
            ,("ent","chemical/x-ncbi-asn1-ascii")
-           ,("eot","application/vnd.ms-fontobject")
-           ,("eps","application/postscript")
-           ,("etx","text/x-setext")
-           ,("exe","application/x-msdos-program")
-           ,("ez","application/andrew-inset")
+
+           -- The type used in mime-types is `application/postscript`,
+           -- but code in Text.Pandoc.PDF relies on the type being
+           -- `application/eps`. Do not remove without updating that
+           -- module.
+           ,("eps","application/eps")
+
            ,("fb","application/x-maker")
            ,("fbdoc","application/x-maker")
            ,("fch","chemical/x-gaussian-checkpoint")
            ,("fchk","chemical/x-gaussian-checkpoint")
-           ,("fig","application/x-xfig")
-           ,("flac","application/x-flac")
-           ,("fli","video/fli")
-           ,("fm","application/x-maker")
-           ,("frame","application/x-maker")
            ,("frm","application/x-maker")
            ,("fs","text/plain")
            ,("gal","chemical/x-gaussian-log")
@@ -195,162 +164,67 @@
            ,("gcf","application/x-graphing-calculator")
            ,("gcg","chemical/x-gcg8-sequence")
            ,("gen","chemical/x-genbank")
-           ,("gf","application/x-tex-gf")
-           ,("gif","image/gif")
            ,("gjc","chemical/x-gaussian-input")
            ,("gjf","chemical/x-gaussian-input")
            ,("gl","video/gl")
-           ,("gnumeric","application/x-gnumeric")
+           ,("glsl","text/plain")
            ,("gpt","chemical/x-mopac-graph")
-           ,("gsf","application/x-font")
            ,("gsm","audio/x-gsm")
-           ,("gtar","application/x-gtar")
            ,("h","text/x-chdr")
            ,("h++","text/x-c++hdr")
-           ,("hdf","application/x-hdf")
            ,("hh","text/x-c++hdr")
            ,("hin","chemical/x-hin")
            ,("hpp","text/x-c++hdr")
-           ,("hqx","application/mac-binhex40")
            ,("hs","text/x-haskell")
            ,("hta","application/hta")
-           ,("htc","text/x-component")
-           ,("htm","text/html")
-           ,("html","text/html")
            ,("hxx","text/x-c++hdr")
            ,("ica","application/x-ica")
-           ,("ice","x-conference/x-cooltalk")
-           ,("ico","image/x-icon")
-           ,("ics","text/calendar")
            ,("icz","text/calendar")
-           ,("ief","image/ief")
-           ,("iges","model/iges")
-           ,("igs","model/iges")
            ,("iii","application/x-iphone")
            ,("inp","chemical/x-gamess-input")
            ,("ins","application/x-internet-signup")
-           ,("iso","application/x-iso9660-image")
            ,("isp","application/x-internet-signup")
            ,("ist","chemical/x-isostar")
            ,("istr","chemical/x-isostar")
-           ,("jad","text/vnd.sun.j2me.app-descriptor")
-           ,("jar","application/java-archive")
-           ,("java","text/x-java")
            ,("jdx","chemical/x-jcamp-dx")
-           ,("jmz","application/x-jmol")
-           ,("jng","image/x-jng")
-           ,("jnlp","application/x-java-jnlp-file")
-           ,("jpe","image/jpeg")
-           ,("jpeg","image/jpeg")
            ,("jfif","image/jpeg")
-           ,("jpg","image/jpeg")
-           ,("js","application/javascript")
-           ,("kar","audio/midi")
+           ,("jxl","image/jxl")
+           ,("jmz","application/x-jmol")
            ,("key","application/pgp-keys")
            ,("kil","application/x-killustrator")
            ,("kin","chemical/x-kinemage")
-           ,("kml","application/vnd.google-earth.kml+xml")
-           ,("kmz","application/vnd.google-earth.kmz")
-           ,("kpr","application/x-kpresenter")
-           ,("kpt","application/x-kpresenter")
-           ,("ksp","application/x-kspread")
-           ,("kwd","application/x-kword")
-           ,("kwt","application/x-kword")
-           ,("latex","application/x-latex")
-           ,("lha","application/x-lha")
            ,("lhs","text/x-literate-haskell")
            ,("lsf","video/x-la-asf")
            ,("lsx","video/x-la-asf")
-           ,("ltx","text/x-tex")
            ,("lyx","application/x-lyx")
            ,("lzh","application/x-lzh")
            ,("lzx","application/x-lzx")
-           ,("m3u","audio/mpegurl")
-           ,("m4a","audio/mpeg")
-           ,("m4v","video/x-m4v")
-           ,("maker","application/x-maker")
            ,("man","application/x-troff-man")
            ,("mcif","chemical/x-mmcif")
            ,("mcm","chemical/x-macmolecule")
            ,("mdb","application/msaccess")
            ,("me","application/x-troff-me")
-           ,("mesh","model/mesh")
-           ,("mid","audio/midi")
-           ,("midi","audio/midi")
-           ,("mif","application/x-mif")
            ,("mm","application/x-freemind")
            ,("mmd","chemical/x-macromodel-input")
-           ,("mmf","application/vnd.smaf")
-           ,("mml","text/mathml")
            ,("mmod","chemical/x-macromodel-input")
-           ,("mng","video/x-mng")
            ,("moc","text/x-moc")
            ,("mol","chemical/x-mdl-molfile")
            ,("mol2","chemical/x-mol2")
            ,("moo","chemical/x-mopac-out")
            ,("mop","chemical/x-mopac-input")
            ,("mopcrt","chemical/x-mopac-input")
-           ,("mov","video/quicktime")
-           ,("movie","video/x-sgi-movie")
-           ,("mp2","audio/mpeg")
-           ,("mp3","audio/mpeg")
-           ,("mp4","video/mp4")
            ,("mpc","chemical/x-mopac-input")
-           ,("mpe","video/mpeg")
-           ,("mpeg","video/mpeg")
            ,("mpega","audio/mpeg")
-           ,("mpg","video/mpeg")
-           ,("mpga","audio/mpeg")
            ,("ms","application/x-troff-ms")
-           ,("msh","model/mesh")
            ,("msi","application/x-msi")
            ,("mvb","chemical/x-mopac-vib")
-           ,("mxu","video/vnd.mpegurl")
-           ,("nb","application/mathematica")
-           ,("nc","application/x-netcdf")
            ,("nwc","application/x-nwc")
            ,("o","application/x-object")
-           ,("oda","application/oda")
-           ,("odb","application/vnd.oasis.opendocument.database")
-           ,("odc","application/vnd.oasis.opendocument.chart")
-           ,("odf","application/vnd.oasis.opendocument.formula")
-           ,("odg","application/vnd.oasis.opendocument.graphics")
-           ,("odi","application/vnd.oasis.opendocument.image")
-           ,("odm","application/vnd.oasis.opendocument.text-master")
-           ,("odp","application/vnd.oasis.opendocument.presentation")
-           ,("ods","application/vnd.oasis.opendocument.spreadsheet")
-           ,("odt","application/vnd.oasis.opendocument.text")
-           ,("oga","audio/ogg")
-           ,("ogg","application/ogg")
-           ,("ogv","video/ogg")
-           ,("ogx","application/ogg")
            ,("old","application/x-trash")
-           ,("opus","audio/ogg")
-           ,("otg","application/vnd.oasis.opendocument.graphics-template")
-           ,("oth","application/vnd.oasis.opendocument.text-web")
-           ,("otp","application/vnd.oasis.opendocument.presentation-template")
-           ,("ots","application/vnd.oasis.opendocument.spreadsheet-template")
-           ,("otf","application/vnd.ms-opentype")
-           ,("ott","application/vnd.oasis.opendocument.text-template")
            ,("oza","application/x-oz-application")
-           ,("p","text/x-pascal")
-           ,("p7r","application/x-pkcs7-certreqresp")
-           ,("pac","application/x-ns-proxy-autoconfig")
-           ,("pas","text/x-pascal")
            ,("pat","image/x-coreldrawpattern")
            ,("patch","text/x-diff")
-           ,("pbm","image/x-portable-bitmap")
-           ,("pcap","application/cap")
-           ,("pcf","application/x-font")
-           ,("pcf.Z","application/x-font")
-           ,("pcx","image/pcx")
            ,("pdb","chemical/x-pdb")
-           ,("pdf","application/pdf")
-           ,("pfa","application/x-font")
-           ,("pfb","application/x-font")
-           ,("pgm","image/x-portable-graymap")
-           ,("pgn","application/x-chess-pgn")
-           ,("pgp","application/pgp-signature")
            ,("php","application/x-httpd-php")
            ,("php3","application/x-httpd-php3")
            ,("php3p","application/x-httpd-php3-preprocessed")
@@ -359,170 +233,46 @@
            ,("pht","application/x-httpd-php")
            ,("phtml","application/x-httpd-php")
            ,("pk","application/x-tex-pk")
-           ,("pl","text/x-perl")
            ,("pls","audio/x-scpls")
-           ,("pm","text/x-perl")
-           ,("png","image/png")
-           ,("pnm","image/x-portable-anymap")
            ,("pot","text/plain")
-           ,("ppm","image/x-portable-pixmap")
-           ,("pps","application/vnd.ms-powerpoint")
-           ,("ppt","application/vnd.ms-powerpoint")
-           ,("prf","application/pics-rules")
            ,("prt","chemical/x-ncbi-asn1-ascii")
-           ,("ps","application/postscript")
-           ,("psd","image/x-photoshop")
            ,("py","text/x-python")
            ,("pyc","application/x-python-code")
            ,("pyo","application/x-python-code")
-           ,("qt","video/quicktime")
            ,("qtl","application/x-quicktimeplayer")
-           ,("ra","audio/x-pn-realaudio")
-           ,("ram","audio/x-pn-realaudio")
-           ,("rar","application/rar")
-           ,("ras","image/x-cmu-raster")
            ,("rd","chemical/x-mdl-rdfile")
-           ,("rdf","application/rdf+xml")
-           ,("rgb","image/x-rgb")
            ,("rhtml","application/x-httpd-eruby")
            ,("rm","audio/x-pn-realaudio")
-           ,("roff","application/x-troff")
            ,("ros","chemical/x-rosdal")
-           ,("rpm","application/x-redhat-package-manager")
-           ,("rss","application/rss+xml")
-           ,("rtf","application/rtf")
-           ,("rtx","text/richtext")
            ,("rxn","chemical/x-mdl-rxnfile")
            ,("sct","text/scriptlet")
            ,("sd","chemical/x-mdl-sdfile")
            ,("sd2","audio/x-sd2")
-           ,("sda","application/vnd.stardivision.draw")
-           ,("sdc","application/vnd.stardivision.calc")
-           ,("sdd","application/vnd.stardivision.impress")
            ,("sdf","application/vnd.stardivision.math")
            ,("sds","application/vnd.stardivision.chart")
-           ,("sdw","application/vnd.stardivision.writer")
-           ,("ser","application/java-serialized-object")
            ,("sgf","application/x-go-sgf")
-           ,("sgl","application/vnd.stardivision.writer-global")
-           ,("sh","application/x-sh")
-           ,("shar","application/x-shar")
-           ,("shtml","text/html")
            ,("sid","audio/prs.sid")
            ,("sik","application/x-trash")
-           ,("silo","model/mesh")
-           ,("sis","application/vnd.symbian.install")
-           ,("sisx","x-epoc/x-sisx-app")
-           ,("sit","application/x-stuffit")
-           ,("sitx","application/x-stuffit")
-           ,("skd","application/x-koan")
-           ,("skm","application/x-koan")
-           ,("skp","application/x-koan")
-           ,("skt","application/x-koan")
-           ,("smi","application/smil")
-           ,("smil","application/smil")
-           ,("snd","audio/basic")
            ,("spc","chemical/x-galactic-spc")
-           ,("spl","application/futuresplash")
-           ,("spx","audio/ogg")
-           ,("src","application/x-wais-source")
-           ,("stc","application/vnd.sun.xml.calc.template")
-           ,("std","application/vnd.sun.xml.draw.template")
-           ,("sti","application/vnd.sun.xml.impress.template")
-           ,("stl","application/vnd.ms-pki.stl")
-           ,("stw","application/vnd.sun.xml.writer.template")
-           ,("sty","text/x-tex")
-           ,("sv4cpio","application/x-sv4cpio")
-           ,("sv4crc","application/x-sv4crc")
-           ,("svg","image/svg+xml")
-           -- removed for now, since it causes problems with
-           -- extensionFromMimeType: see #2183.
-           -- ,("svgz","image/svg+xml")
            ,("sw","chemical/x-swissprot")
-           ,("swf","application/x-shockwave-flash")
            ,("swfl","application/x-shockwave-flash")
-           ,("sxc","application/vnd.sun.xml.calc")
-           ,("sxd","application/vnd.sun.xml.draw")
-           ,("sxg","application/vnd.sun.xml.writer.global")
-           ,("sxi","application/vnd.sun.xml.impress")
-           ,("sxm","application/vnd.sun.xml.math")
-           ,("sxw","application/vnd.sun.xml.writer")
-           ,("t","application/x-troff")
-           ,("tar","application/x-tar")
            ,("taz","application/x-gtar")
-           ,("tcl","application/x-tcl")
-           ,("tex","text/x-tex")
-           ,("texi","application/x-texinfo")
-           ,("texinfo","application/x-texinfo")
-           ,("text","text/plain")
            ,("tgf","chemical/x-mdl-tgf")
-           ,("tgz","application/x-gtar")
-           ,("tif","image/tiff")
-           ,("tiff","image/tiff")
-           ,("tk","text/x-tcl")
            ,("tm","text/texmacs")
-           ,("torrent","application/x-bittorrent")
-           ,("tr","application/x-troff")
            ,("ts","text/texmacs")
            ,("tsp","application/dsptype")
-           ,("tsv","text/tab-separated-values")
-           ,("ttf","application/x-font-truetype")
-           ,("txt","text/plain")
-           ,("udeb","application/x-debian-package")
-           ,("uls","text/iuls")
-           ,("ustar","application/x-ustar")
            ,("val","chemical/x-ncbi-asn1-binary")
-           ,("vcd","application/x-cdlink")
-           ,("vcf","text/x-vcard")
-           ,("vcs","text/x-vcalendar")
            ,("vmd","chemical/x-vmd")
            ,("vms","chemical/x-vamas-iso14976")
            ,("vrm","x-world/x-vrml")
-           ,("vrml","model/vrml")
            ,("vs","text/plain")
-           ,("vsd","application/vnd.visio")
-           ,("vtt","text/vtt")
-           ,("wad","application/x-doom")
-           ,("wav","audio/x-wav")
-           ,("wax","audio/x-ms-wax")
-           ,("wbmp","image/vnd.wap.wbmp")
-           ,("wbxml","application/vnd.wap.wbxml")
-           ,("webm","video/webm")
            ,("wk","application/x-123")
-           ,("wm","video/x-ms-wm")
-           ,("wma","audio/x-ms-wma")
-           ,("wmd","application/x-ms-wmd")
            ,("wmf","image/x-wmf")
-           ,("wml","text/vnd.wap.wml")
-           ,("wmlc","application/vnd.wap.wmlc")
-           ,("wmls","text/vnd.wap.wmlscript")
-           ,("wmlsc","application/vnd.wap.wmlscriptc")
-           ,("wmv","video/x-ms-wmv")
-           ,("wmx","video/x-ms-wmx")
            ,("wmz","application/x-ms-wmz")
-           ,("woff","application/font-woff")
-           ,("woff2","font/woff2")
            ,("wp5","application/wordperfect5.1")
-           ,("wpd","application/wordperfect")
-           ,("wrl","model/vrml")
            ,("wsc","text/scriptlet")
-           ,("wvx","video/x-ms-wvx")
            ,("wz","application/x-wingz")
-           ,("xbm","image/x-xbitmap")
-           ,("xcf","application/x-xcf")
-           ,("xht","application/xhtml+xml")
-           ,("xhtml","application/xhtml+xml")
            ,("xlb","application/vnd.ms-excel")
-           ,("xls","application/vnd.ms-excel")
-           ,("xlt","application/vnd.ms-excel")
-           ,("xml","application/xml")
-           ,("xpi","application/x-xpinstall")
-           ,("xpm","image/x-xpixmap")
-           ,("xsl","application/xml")
            ,("xtel","chemical/x-xtel")
-           ,("xul","application/vnd.mozilla.xul+xml")
-           ,("xwd","image/x-xwindowdump")
-           ,("xyz","chemical/x-xyz")
-           ,("zip","application/zip")
            ,("zmt","chemical/x-mopac-input")
            ]
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
@@ -1,26 +1,10 @@
+{-# LANGUAGE CPP                        #-}
+{-# LANGUAGE OverloadedStrings          #-}
 {-# LANGUAGE DeriveDataTypeable         #-}
 {-# LANGUAGE GeneralizedNewtypeDeriving #-}
-{-
-Copyright (C) 2014-2015, 2017 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 John MacFarlane
+   Copyright   : Copyright (C) 2014-2015, 2017-2024 John MacFarlane
    License     : GNU GPL, version 2 or above
 
    Maintainer  : John MacFarlane <jgm@berkeley.edu>
@@ -31,30 +15,63 @@
 interface for interacting with it.
 -}
 module Text.Pandoc.MediaBag (
+                     MediaItem(..),
                      MediaBag,
+                     deleteMedia,
                      lookupMedia,
                      insertMedia,
                      mediaDirectory,
+                     mediaItems
                      ) where
+import Crypto.Hash (hashWith, SHA1(SHA1))
 import qualified Data.ByteString.Lazy as BL
 import Data.Data (Data)
 import qualified Data.Map as M
-import Data.Maybe (fromMaybe)
+import Data.Maybe (fromMaybe, isNothing)
 import Data.Typeable (Typeable)
 import System.FilePath
 import qualified System.FilePath.Posix as Posix
-import Text.Pandoc.MIME (MimeType, getMimeTypeDef)
+import qualified System.FilePath.Windows as Windows
+import Text.Pandoc.MIME (MimeType, getMimeTypeDef, extensionFromMimeType)
+import Data.Text (Text)
+import qualified Data.Text as T
+import Network.URI (URI (..), isURI, parseURI, unEscapeString)
+import Data.List (isInfixOf)
 
+data MediaItem =
+  MediaItem
+  { mediaMimeType :: MimeType
+  , mediaPath :: FilePath
+  , mediaContents :: BL.ByteString
+  } deriving (Eq, Ord, Show, Data, Typeable)
+
 -- | A container for a collection of binary resources, with names and
 -- mime types.  Note that a 'MediaBag' is a Monoid, so 'mempty'
 -- can be used for an empty 'MediaBag', and '<>' can be used to append
 -- two 'MediaBag's.
-newtype MediaBag = MediaBag (M.Map [String] (MimeType, BL.ByteString))
-        deriving (Monoid, Data, Typeable)
+newtype MediaBag = MediaBag (M.Map Text MediaItem)
+        deriving (Semigroup, Monoid, Data, Typeable)
 
 instance Show MediaBag where
   show bag = "MediaBag " ++ show (mediaDirectory bag)
 
+-- | We represent paths with /, in normalized form.  Percent-encoding
+-- is not resolved.
+canonicalize :: FilePath -> Text
+-- avoid an expensive call to isURI for data URIs:
+canonicalize fp@('d':'a':'t':'a':':':_) = T.pack fp
+canonicalize fp
+  | isURI fp = T.pack fp
+  | otherwise = T.replace "\\" "/" . T.pack . normalise $ fp
+
+-- | Delete a media item from a 'MediaBag', or do nothing if no item corresponds
+-- to the given path.
+deleteMedia :: FilePath       -- ^ relative path and canonical name of resource
+            -> MediaBag
+            -> MediaBag
+deleteMedia fp (MediaBag mediamap) =
+  MediaBag $ M.delete (canonicalize fp) mediamap
+
 -- | Insert a media item into a 'MediaBag', replacing any existing
 -- value with the same name.
 insertMedia :: FilePath       -- ^ relative path and canonical name of resource
@@ -62,22 +79,54 @@
             -> BL.ByteString  -- ^ contents of resource
             -> MediaBag
             -> MediaBag
-insertMedia fp mbMime contents (MediaBag mediamap) =
-  MediaBag (M.insert (splitDirectories fp) (mime, contents) mediamap)
-  where mime = fromMaybe fallback mbMime
-        fallback = case takeExtension fp of
-                        ".gz" -> getMimeTypeDef $ dropExtension fp
-                        _     -> getMimeTypeDef fp
+insertMedia fp mbMime contents (MediaBag mediamap)
+ | 'd':'a':'t':'a':':':_ <- fp
+ , Just mt' <- mbMime
+   = MediaBag (M.insert fp'
+               MediaItem{ mediaPath = hashpath
+                        , mediaContents = contents
+                        , mediaMimeType = mt' } mediamap)
+ | otherwise = MediaBag (M.insert fp' mediaItem mediamap)
+ where
+  mediaItem = MediaItem{ mediaPath = newpath
+                       , mediaContents = contents
+                       , mediaMimeType = mt }
+  fp' = canonicalize fp
+  fp'' = unEscapeString $ T.unpack fp'
+  uri = parseURI fp
+  hashpath = show (hashWith SHA1 (BL.toStrict contents)) <> ext
+  newpath = if Posix.isRelative fp''
+                 && Windows.isRelative fp''
+                 && isNothing uri
+                 && not (".." `isInfixOf` fp'')
+                 && '%' `notElem` fp''
+               then fp''
+               else hashpath
+  fallback = case takeExtension fp'' of
+                  ".gz" -> getMimeTypeDef $ dropExtension fp''
+                  _     -> getMimeTypeDef fp''
+  mt = fromMaybe fallback mbMime
+  path = maybe fp'' (unEscapeString . uriPath) uri
+  ext = case extensionFromMimeType mt of
+             Just e -> '.':T.unpack e
+             Nothing -> case takeExtension path of
+                             '.':e | '%' `notElem` e -> '.':e
+                             _ -> ""
 
 -- | Lookup a media item in a 'MediaBag', returning mime type and contents.
 lookupMedia :: FilePath
             -> MediaBag
-            -> Maybe (MimeType, BL.ByteString)
-lookupMedia fp (MediaBag mediamap) = M.lookup (splitDirectories fp) mediamap
+            -> Maybe MediaItem
+lookupMedia fp (MediaBag mediamap) = M.lookup (canonicalize fp) mediamap
 
 -- | Get a list of the file paths stored in a 'MediaBag', with
 -- their corresponding mime types and the lengths in bytes of the contents.
-mediaDirectory :: MediaBag -> [(String, MimeType, Int)]
-mediaDirectory (MediaBag mediamap) =
-  M.foldrWithKey (\fp (mime,contents) ->
-      ((Posix.joinPath fp, mime, fromIntegral $ BL.length contents):)) [] mediamap
+mediaDirectory :: MediaBag -> [(FilePath, MimeType, Int)]
+mediaDirectory mediabag =
+  map (\(fp, mt, bs) -> (fp, mt, fromIntegral (BL.length bs)))
+    (mediaItems mediabag)
+
+mediaItems :: MediaBag -> [(FilePath, MimeType, BL.ByteString)]
+mediaItems (MediaBag mediamap) =
+  map (\item -> (mediaPath item, mediaMimeType item, mediaContents item))
+      (M.elems mediamap)
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
@@ -1,27 +1,13 @@
+{-# LANGUAGE CPP                #-}
 {-# LANGUAGE DeriveDataTypeable #-}
 {-# LANGUAGE DeriveGeneric      #-}
+{-# LANGUAGE LambdaCase         #-}
+{-# LANGUAGE OverloadedStrings  #-}
+{-# LANGUAGE PatternSynonyms    #-}
 {-# LANGUAGE TemplateHaskell    #-}
-{-
-Copyright (C) 2012-2017 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-2017 John MacFarlane
+   Copyright   : Copyright (C) 2012-2024 John MacFarlane
    License     : GNU GPL, version 2 or above
 
    Maintainer  : John MacFarlane <jgm@berkeley.edu>
@@ -36,6 +22,10 @@
                            , HTMLMathMethod (..)
                            , CiteMethod (..)
                            , ObfuscationMethod (..)
+                           , HighlightMethod (..)
+                           , pattern NoHighlightingString
+                           , pattern DefaultHighlightingString
+                           , pattern IdiomaticHighlightingString
                            , HTMLSlideVariant (..)
                            , EPUBVersion (..)
                            , WrapOption (..)
@@ -43,19 +33,31 @@
                            , WriterOptions (..)
                            , TrackChanges (..)
                            , ReferenceLocation (..)
+                           , CaptionPosition (..)
                            , def
                            , isEnabled
+                           , defaultMathJaxURL
+                           , defaultWebTeXURL
+                           , defaultKaTeXURL
                            ) where
-import Data.Aeson (defaultOptions)
-import Data.Aeson.TH (deriveJSON)
+import Control.Applicative ((<|>))
+import Data.Maybe (fromMaybe)
 import Data.Data (Data)
 import Data.Default
+import Data.Char (toLower)
+import Data.Text (Text)
 import qualified Data.Set as Set
+import qualified Data.Text as T
 import Data.Typeable (Typeable)
 import GHC.Generics (Generic)
 import Skylighting (SyntaxMap, defaultSyntaxMap)
+import Text.DocTemplates (Context(..), Template)
 import Text.Pandoc.Extensions
-import Text.Pandoc.Highlighting (Style, pygments)
+import Text.Pandoc.Chunks (PathTemplate)
+import Text.Pandoc.Highlighting (Style)
+import Text.Pandoc.UTF8 (toStringLazy)
+import Data.Aeson.TH (deriveJSON)
+import Data.Aeson
 
 class HasSyntaxExtensions a where
   getExtensions :: a -> Extensions
@@ -65,12 +67,14 @@
        , readerStandalone            :: Bool -- ^ Standalone document with header
        , readerColumns               :: Int  -- ^ Number of columns in terminal
        , readerTabStop               :: Int  -- ^ Tab stop
-       , readerIndentedCodeClasses   :: [String] -- ^ Default classes for
+       , readerIndentedCodeClasses   :: [Text] -- ^ Default classes for
                                        -- indented code blocks
-       , readerAbbreviations         :: Set.Set String -- ^ Strings to treat as abbreviations
-       , readerDefaultImageExtension :: String -- ^ Default extension for images
+       , readerAbbreviations         :: Set.Set Text -- ^ Strings to treat as abbreviations
+       , readerDefaultImageExtension :: Text -- ^ Default extension for images
        , readerTrackChanges          :: TrackChanges -- ^ Track changes setting for docx
        , readerStripComments         :: Bool -- ^ Strip HTML comments instead of parsing as raw HTML
+                                             -- (only implemented in commonmark)
+       , readerTypstInputs           :: [(Text, Text)] -- ^ parameters specified using --typst-input
 } deriving (Show, Read, Data, Typeable, Generic)
 
 instance HasSyntaxExtensions ReaderOptions where
@@ -87,9 +91,10 @@
                , readerDefaultImageExtension = ""
                , readerTrackChanges          = AcceptChanges
                , readerStripComments         = False
+               , readerTypstInputs           = []
                }
 
-defaultAbbrevs :: Set.Set String
+defaultAbbrevs :: Set.Set Text
 defaultAbbrevs = Set.fromList
                  [ "Mr.", "Mrs.", "Ms.", "Capt.", "Dr.", "Prof.",
                    "Gen.", "Gov.", "e.g.", "i.e.", "Sgt.", "St.",
@@ -104,26 +109,128 @@
 data EPUBVersion = EPUB2 | EPUB3 deriving (Eq, Show, Read, Data, Typeable, Generic)
 
 data HTMLMathMethod = PlainMath
-                    | LaTeXMathML (Maybe String)  -- url of LaTeXMathML.js
-                    | JsMath (Maybe String)       -- url of jsMath load script
+                    | WebTeX Text               -- url of TeX->image script.
                     | GladTeX
-                    | WebTeX String               -- url of TeX->image script.
                     | MathML
-                    | MathJax String              -- url of MathJax.js
-                    | KaTeX String                -- url of KaTeX files
+                    | MathJax Text              -- url of MathJax.js
+                    | KaTeX Text                -- url of KaTeX files
                     deriving (Show, Read, Eq, Data, Typeable, Generic)
 
+instance FromJSON HTMLMathMethod where
+   parseJSON node =
+     (withObject "HTMLMathMethod" $ \m -> do
+        method <- m .: "method"
+        mburl <- m .:? "url"
+        case method :: Text of
+          "plain" -> return PlainMath
+          "webtex" -> return $ WebTeX $
+                         fromMaybe defaultWebTeXURL mburl
+          "gladtex" -> return GladTeX
+          "mathml" -> return MathML
+          "mathjax" -> return $ MathJax $
+                         fromMaybe defaultMathJaxURL mburl
+          "katex" -> return $ KaTeX $
+                         fromMaybe defaultKaTeXURL mburl
+          _ -> fail $ "Unknown HTML math method " ++ show method) node
+       <|> (case node of
+               String "plain" -> return PlainMath
+               String "webtex" -> return $ WebTeX defaultWebTeXURL
+               String "gladtex" -> return GladTeX
+               String "mathml" -> return MathML
+               String "mathjax" -> return $ MathJax defaultMathJaxURL
+               String "katex" -> return $ KaTeX defaultKaTeXURL
+               _ -> fail $ "Unknown HTML math method " <>
+                             toStringLazy (encode node))
+
+instance ToJSON HTMLMathMethod where
+  toJSON PlainMath = String "plain"
+  toJSON (WebTeX "") = String "webtex"
+  toJSON (WebTeX url) = object ["method" .= String "webtex",
+                                "url" .= String url]
+  toJSON GladTeX = String "gladtex"
+  toJSON MathML = String "mathml"
+  toJSON (MathJax "") = String "mathjax"
+  toJSON (MathJax url) = object ["method" .= String "mathjax",
+                                 "url" .= String url]
+  toJSON (KaTeX "") = String "katex"
+  toJSON (KaTeX url) = object ["method" .= String "katex",
+                               "url" .= String url]
+
 data CiteMethod = Citeproc                        -- use citeproc to render them
                   | Natbib                        -- output natbib cite commands
                   | Biblatex                      -- output biblatex cite commands
                 deriving (Show, Read, Eq, Data, Typeable, Generic)
 
+instance FromJSON CiteMethod where
+  parseJSON v =
+    case v of
+      String "citeproc" -> return Citeproc
+      String "natbib"   -> return Natbib
+      String "biblatex" -> return Biblatex
+      _                 -> fail $ "Unknown citation method: " <>
+                                    toStringLazy (encode v)
+
+instance ToJSON CiteMethod where
+  toJSON Citeproc = String "citeproc"
+  toJSON Natbib = String "natbib"
+  toJSON Biblatex = String "biblatex"
+
 -- | Methods for obfuscating email addresses in HTML.
 data ObfuscationMethod = NoObfuscation
                        | ReferenceObfuscation
                        | JavascriptObfuscation
                        deriving (Show, Read, Eq, Data, Typeable, Generic)
 
+instance FromJSON ObfuscationMethod where
+  parseJSON v =
+    case v of
+      String "none"       -> return NoObfuscation
+      String "references" -> return ReferenceObfuscation
+      String "javascript" -> return JavascriptObfuscation
+      _ -> fail $ "Unknown obfuscation method " ++ toStringLazy (encode v)
+
+instance ToJSON ObfuscationMethod where
+   toJSON NoObfuscation = String "none"
+   toJSON ReferenceObfuscation = String "references"
+   toJSON JavascriptObfuscation = String "javascript"
+
+-- | Method to provide code highlighting.
+data HighlightMethod =
+    Skylighting Style
+  | IdiomaticHighlighting
+  | DefaultHighlighting
+  | NoHighlighting
+  deriving (Show, Read, Eq, Data, Typeable, Generic)
+
+-- | String representation of the idiomatic highlighting option.
+pattern IdiomaticHighlightingString :: Text
+pattern IdiomaticHighlightingString = "idiomatic"
+
+-- | String representation of the default highlighting option.
+pattern DefaultHighlightingString :: Text
+pattern DefaultHighlightingString = "default"
+
+-- | String representation of the no highlighting option
+pattern NoHighlightingString :: Text
+pattern NoHighlightingString = "none"
+
+instance ToJSON HighlightMethod where
+  toJSON NoHighlighting        = String NoHighlightingString
+  toJSON IdiomaticHighlighting = String IdiomaticHighlightingString
+  toJSON DefaultHighlighting   = String DefaultHighlightingString
+  toJSON (Skylighting style)   = toJSON style
+
+instance FromJSON HighlightMethod where
+  parseJSON = \case
+    String NoHighlightingString        -> pure NoHighlighting
+    String IdiomaticHighlightingString -> pure IdiomaticHighlighting
+    String DefaultHighlightingString   -> pure DefaultHighlighting
+    String x           -> fail $ "Unknown highlighting method " <> T.unpack x
+    Bool True          -> pure DefaultHighlighting
+    Bool False         -> pure NoHighlighting
+    Null               -> pure NoHighlighting
+    v                  -> Skylighting <$> parseJSON v
+
 -- | Varieties of HTML slide shows.
 data HTMLSlideVariant = S5Slides
                       | SlidySlides
@@ -139,12 +246,45 @@
                   | AllChanges
                   deriving (Show, Read, Eq, Data, Typeable, Generic)
 
+-- update in doc/filters.md if this changes:
+instance FromJSON TrackChanges where
+  parseJSON v =
+    case v of
+      String "accept"     -> return AcceptChanges
+      String "reject"     -> return RejectChanges
+      String "all"        -> return AllChanges
+      String "accept-changes" -> return AcceptChanges
+      String "reject-changes" -> return RejectChanges
+      String "all-changes"    -> return AllChanges
+      _  -> fail $ "Unknown track changes method " <> toStringLazy (encode v)
+
+instance ToJSON TrackChanges where
+  toJSON AcceptChanges = String "accept-changes"
+  toJSON RejectChanges = String "reject-changes"
+  toJSON AllChanges = String "all-changes"
+
 -- | Options for wrapping text in the output.
 data WrapOption = WrapAuto        -- ^ Automatically wrap to width
                 | WrapNone        -- ^ No non-semantic newlines
                 | WrapPreserve    -- ^ Preserve wrapping of input source
                 deriving (Show, Read, Eq, Data, Typeable, Generic)
 
+instance FromJSON WrapOption where
+  parseJSON v =
+    case v of
+      String "auto"      -> return WrapAuto
+      String "wrap-auto" -> return WrapAuto
+      String "none"      -> return WrapNone
+      String "wrap-none" -> return WrapNone
+      String "preserve"  -> return WrapPreserve
+      String "wrap-preserve" -> return WrapPreserve
+      _ -> fail $ "Unknown wrap method " <> toStringLazy (encode v)
+
+instance ToJSON WrapOption where
+  toJSON WrapAuto = "wrap-auto"
+  toJSON WrapNone = "wrap-none"
+  toJSON WrapPreserve = "wrap-preserve"
+
 -- | Options defining the type of top-level headers.
 data TopLevelDivision = TopLevelPart      -- ^ Top-level headers become parts
                       | TopLevelChapter   -- ^ Top-level headers become chapters
@@ -153,18 +293,71 @@
                                           --   heuristics
                       deriving (Show, Read, Eq, Data, Typeable, Generic)
 
+instance FromJSON TopLevelDivision where
+  parseJSON v =
+      case v of
+        String "part"              -> return TopLevelPart
+        String "top-level-part"    -> return TopLevelPart
+        String "chapter"           -> return TopLevelChapter
+        String "top-level-chapter" -> return TopLevelChapter
+        String "section"           -> return TopLevelSection
+        String "top-level-section" -> return TopLevelSection
+        String "default"           -> return TopLevelDefault
+        String "top-level-default" -> return TopLevelDefault
+        _ -> fail $ "Unknown top level division " <> toStringLazy (encode v)
+
+instance ToJSON TopLevelDivision where
+  toJSON TopLevelPart = "top-level-part"
+  toJSON TopLevelChapter = "top-level-chapter"
+  toJSON TopLevelSection = "top-level-section"
+  toJSON TopLevelDefault = "top-level-default"
+
 -- | Locations for footnotes and references in markdown output
 data ReferenceLocation = EndOfBlock    -- ^ End of block
                        | EndOfSection  -- ^ prior to next section header (or end of document)
                        | EndOfDocument -- ^ at end of document
                        deriving (Show, Read, Eq, Data, Typeable, Generic)
 
+instance FromJSON ReferenceLocation where
+  parseJSON v =
+    case v of
+      String "block"           -> return EndOfBlock
+      String "end-of-block"    -> return EndOfBlock
+      String "section"         -> return EndOfSection
+      String "end-of-section"  -> return EndOfSection
+      String "document"        -> return EndOfDocument
+      String "end-of-document" -> return EndOfDocument
+      _ -> fail $ "Unknown reference location " <> toStringLazy (encode v)
+
+instance ToJSON ReferenceLocation where
+   toJSON EndOfBlock = "end-of-block"
+   toJSON EndOfSection = "end-of-section"
+   toJSON EndOfDocument = "end-of-document"
+
+-- | Positions for figure and table captions
+data CaptionPosition = CaptionAbove -- ^ above figure or table
+                     | CaptionBelow -- ^ below figure or table
+                     deriving (Show, Read, Eq, Data, Typeable, Generic)
+
+instance FromJSON CaptionPosition where
+  parseJSON v =
+    case v of
+      String "above" -> return CaptionAbove
+      String "below" -> return CaptionBelow
+      _ -> fail $ "Unknown caption position " <> toStringLazy (encode v)
+
+instance ToJSON CaptionPosition where
+   toJSON CaptionAbove = "above"
+   toJSON CaptionBelow = "below"
+
 -- | Options for writers
 data WriterOptions = WriterOptions
-  { writerTemplate          :: Maybe String -- ^ Template to use
-  , writerVariables         :: [(String, String)] -- ^ Variables to set in template
+  { writerTemplate          :: Maybe (Template Text) -- ^ Template to use
+  , writerVariables         :: Context Text -- ^ Variables to set in template
   , writerTabStop           :: Int    -- ^ Tabstop for conversion btw spaces and tabs
   , writerTableOfContents   :: Bool   -- ^ Include table of contents
+  , writerListOfFigures     :: Bool   -- ^ Include list of figures
+  , writerListOfTables      :: Bool   -- ^ Include list of tables
   , writerIncremental       :: Bool   -- ^ True if lists should be incremental
   , writerHTMLMathMethod    :: HTMLMathMethod  -- ^ How to print math in HTML
   , writerNumberSections    :: Bool   -- ^ Number sections in LaTeX
@@ -172,35 +365,42 @@
   , 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
-  , writerIdentifierPrefix  :: String -- ^ Prefix for section & note ids in HTML
+  , writerIdentifierPrefix  :: Text -- ^ Prefix for section & note ids in HTML
                                      -- and for footnote marks in markdown
   , writerCiteMethod        :: CiteMethod -- ^ How to print cites
   , writerHtmlQTags         :: Bool       -- ^ Use @<q>@ tags for quotes in HTML
   , writerSlideLevel        :: Maybe Int  -- ^ Force header level of slides
   , writerTopLevelDivision  :: TopLevelDivision -- ^ Type of top-level divisions
-  , writerListings          :: Bool       -- ^ Use listings package for code
-  , writerHighlightStyle    :: Maybe Style  -- ^ Style to use for highlighting
-                                           -- (Nothing = no highlighting)
+  , writerHighlightMethod   :: HighlightMethod  -- ^ Style to use for highlighting
   , writerSetextHeaders     :: Bool       -- ^ Use setext headers for levels 1-2 in markdown
-  , writerEpubSubdirectory  :: String       -- ^ Subdir for epub in OCF
-  , writerEpubMetadata      :: Maybe String -- ^ Metadata to include in EPUB
+  , writerListTables        :: Bool       -- ^ Use list tables for RST tables
+  , writerEpubSubdirectory  :: Text       -- ^ Subdir for epub in OCF
+  , writerEpubMetadata      :: Maybe Text -- ^ Metadata to include in EPUB
   , writerEpubFonts         :: [FilePath] -- ^ Paths to fonts to embed
-  , writerEpubChapterLevel  :: Int            -- ^ Header level for chapters (separate files)
+  , writerEpubTitlePage     :: Bool           -- ^ Include title page in epub
+  , writerSplitLevel        :: Int        -- ^ Header level at which to split EPUB or chunked HTML into separate files
+  , writerChunkTemplate     :: PathTemplate  -- ^ Template for filenames in chunked HTML
   , writerTOCDepth          :: Int            -- ^ Number of levels to include in TOC
   , writerReferenceDoc      :: Maybe FilePath -- ^ Path to reference document if specified
   , writerReferenceLocation :: ReferenceLocation    -- ^ Location of footnotes and references for writing markdown
+  , writerFigureCaptionPosition :: CaptionPosition -- ^ Position of figure caption
+  , writerTableCaptionPosition :: CaptionPosition -- ^ Position of table caption
   , writerSyntaxMap         :: SyntaxMap
+  , writerPreferAscii       :: Bool           -- ^ Prefer ASCII representations of characters when possible
+  , writerLinkImages        :: Bool           -- ^ Use links rather than embedding ODT images
   } deriving (Show, Data, Typeable, Generic)
 
 instance Default WriterOptions where
   def = WriterOptions { writerTemplate         = Nothing
-                      , writerVariables        = []
+                      , writerVariables        = mempty
                       , writerTabStop          = 4
                       , writerTableOfContents  = False
+                      , writerListOfFigures    = False
+                      , writerListOfTables     = False
                       , writerIncremental      = False
                       , writerHTMLMathMethod   = PlainMath
                       , writerNumberSections   = False
@@ -217,17 +417,23 @@
                       , writerHtmlQTags        = False
                       , writerSlideLevel       = Nothing
                       , writerTopLevelDivision = TopLevelDefault
-                      , writerListings         = False
-                      , writerHighlightStyle   = Just pygments
-                      , writerSetextHeaders    = True
+                      , writerHighlightMethod  = DefaultHighlighting
+                      , writerSetextHeaders    = False
+                      , writerListTables       = False
                       , writerEpubSubdirectory = "EPUB"
                       , writerEpubMetadata     = Nothing
                       , writerEpubFonts        = []
-                      , writerEpubChapterLevel = 1
+                      , writerEpubTitlePage    = True
+                      , writerSplitLevel       = 1
+                      , writerChunkTemplate    = "%s-%i.html"
                       , writerTOCDepth         = 3
                       , writerReferenceDoc     = Nothing
                       , writerReferenceLocation = EndOfDocument
+                      , writerFigureCaptionPosition = CaptionBelow
+                      , writerTableCaptionPosition  = CaptionAbove
                       , writerSyntaxMap        = defaultSyntaxMap
+                      , writerPreferAscii      = False
+                      , writerLinkImages       = False
                       }
 
 instance HasSyntaxExtensions WriterOptions where
@@ -237,12 +443,19 @@
 isEnabled :: HasSyntaxExtensions a => Extension -> a -> Bool
 isEnabled ext opts = ext `extensionEnabled` getExtensions opts
 
-$(deriveJSON defaultOptions ''ReaderOptions)
-$(deriveJSON defaultOptions ''HTMLMathMethod)
-$(deriveJSON defaultOptions ''CiteMethod)
-$(deriveJSON defaultOptions ''ObfuscationMethod)
-$(deriveJSON defaultOptions ''HTMLSlideVariant)
-$(deriveJSON defaultOptions ''TrackChanges)
-$(deriveJSON defaultOptions ''WrapOption)
-$(deriveJSON defaultOptions ''TopLevelDivision)
-$(deriveJSON defaultOptions ''ReferenceLocation)
+defaultMathJaxURL :: Text
+defaultMathJaxURL = "https://cdn.jsdelivr.net/npm/mathjax@4/tex-chtml.js"
+
+defaultWebTeXURL :: Text
+defaultWebTeXURL = "https://latex.codecogs.com/png.latex?"
+
+defaultKaTeXURL :: Text
+defaultKaTeXURL = "https://cdn.jsdelivr.net/npm/katex@latest/dist/"
+
+-- Update documentation in doc/filters.md if this is changed.
+$(deriveJSON defaultOptions{ fieldLabelModifier =
+                               camelTo2 '-' . drop 6 }
+                            ''ReaderOptions)
+
+$(deriveJSON defaultOptions{ constructorTagModifier = map toLower }
+  ''HTMLSlideVariant)
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
@@ -1,27 +1,11 @@
 {-# LANGUAGE CPP                 #-}
+{-# LANGUAGE LambdaCase          #-}
 {-# LANGUAGE OverloadedStrings   #-}
 {-# LANGUAGE ScopedTypeVariables #-}
-{-
-Copyright (C) 2012-2017 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 FlexibleContexts    #-}
 {- |
    Module      : Text.Pandoc.PDF
-   Copyright   : Copyright (C) 2012-2017 John MacFarlane
+   Copyright   : Copyright (C) 2012-2024 John MacFarlane
    License     : GNU GPL, version 2 or above
 
    Maintainer  : John MacFarlane <jgm@berkeley.edu>
@@ -34,176 +18,286 @@
 
 import qualified Codec.Picture as JP
 import qualified Control.Exception as E
-import Control.Monad (unless, when)
 import Control.Monad.Trans (MonadIO (..))
+import Control.Monad (foldM_)
+import Crypto.Hash (hashWith, SHA1(SHA1))
 import qualified Data.ByteString as BS
 import Data.ByteString.Lazy (ByteString)
 import qualified Data.ByteString.Lazy as BL
 import qualified Data.ByteString.Lazy.Char8 as BC
 import Data.Maybe (fromMaybe)
-import Data.Monoid ((<>))
 import Data.Text (Text)
 import qualified Data.Text as T
-import qualified Data.Text.IO as TextIO
+import qualified Data.Text.Lazy as TL
+import Data.Text.Lazy.Encoding (decodeUtf8')
+import Text.Printf (printf)
+import Data.Char (ord, isAscii, isSpace)
 import System.Directory
 import System.Environment
 import System.Exit (ExitCode (..))
 import System.FilePath
-import System.IO (stdout)
-import System.IO.Temp (withTempDirectory, withTempFile)
-#if MIN_VERSION_base(4,8,3)
-import System.IO.Error (IOError, isDoesNotExistError)
-#else
-import System.IO.Error (isDoesNotExistError)
-#endif
+import System.IO (hClose)
+import System.IO.Temp (withSystemTempDirectory, withTempDirectory,
+                       withTempFile)
+import qualified System.IO.Error as IE
+import Text.DocLayout (literal, render, hsep)
 import Text.Pandoc.Definition
 import Text.Pandoc.Error (PandocError (PandocPDFProgramNotFoundError))
+import Text.Pandoc.SelfContained (makeSelfContained)
 import Text.Pandoc.MIME (getMimeType)
 import Text.Pandoc.Options (HTMLMathMethod (..), WriterOptions (..))
+import Text.Pandoc.Extensions (disableExtension, Extension(Ext_smart))
 import Text.Pandoc.Process (pipeProcess)
-import Text.Pandoc.Shared (inDirectory, stringify, withTempDir)
+import System.Process (readProcessWithExitCode)
+import Text.Pandoc.Shared (inDirectory, stringify, tshow)
 import qualified Text.Pandoc.UTF8 as UTF8
 import Text.Pandoc.Walk (walkM)
-import Text.Pandoc.Writers.Shared (getField, metaToJSON)
+import Text.Pandoc.Writers.Shared (getField, metaToContext)
+import Control.Monad.Catch (MonadMask)
 #ifdef _WINDOWS
 import Data.List (intercalate)
 #endif
-import Text.Pandoc.Class (PandocIO, extractMedia, fillMediaBag, getCommonState,
-                          getVerbosity, putCommonState, report, runIO,
-                          runIOorExplode, setVerbosity)
+import Data.List (isPrefixOf, find)
+import Text.Pandoc.MediaBag (mediaItems)
+import Text.Pandoc.Class (fillMediaBag, getMediaBag, getVerbosity, setVerbosity,
+                          readFileStrict, fileExists,
+                          report, extractMedia, PandocMonad, runIOorExplode)
 import Text.Pandoc.Logging
+import Text.DocTemplates ( FromContext(lookupContext) )
 
 #ifdef _WINDOWS
 changePathSeparators :: FilePath -> FilePath
-changePathSeparators = intercalate "/" . splitDirectories
+changePathSeparators =
+  -- We filter out backslashes because an initial `C:\` gets
+  -- retained by `splitDirectories`, see #6173:
+  intercalate "/" . map (filter (/='\\')) . splitDirectories
 #endif
 
-makePDF :: String              -- ^ pdf creator (pdflatex, lualatex, xelatex,
-                               -- wkhtmltopdf, weasyprint, prince, context, pdfroff)
+makePDF :: (PandocMonad m, MonadIO m, MonadMask m)
+        => String              -- ^ pdf creator (pdflatex, lualatex, xelatex,
+                               -- wkhtmltopdf, weasyprint, prince, context,
+                               -- pdfroff, pagedjs,
+                               -- or path to executable)
         -> [String]            -- ^ arguments to pass to pdf creator
-        -> (WriterOptions -> Pandoc -> PandocIO Text)  -- ^ writer
+        -> (WriterOptions -> Pandoc -> m Text)  -- ^ writer
         -> WriterOptions       -- ^ options
         -> Pandoc              -- ^ document
-        -> PandocIO (Either ByteString ByteString)
-makePDF "wkhtmltopdf" pdfargs writer opts doc@(Pandoc meta _) = do
+        -> m (Either ByteString ByteString)
+makePDF program pdfargs writer opts doc = withTempDir (program == "typst") "media" $ \mediaDir -> do
+#ifdef _WINDOWS
+  -- note:  we want / even on Windows, for TexLive
+  let tmpdir = changePathSeparators mediaDir
+#else
+  let tmpdir = mediaDir
+#endif
+  let isTeXFormat "context" = True
+      isTeXFormat "tectonic" = True
+      isTeXFormat "latexmk" = True
+      isTeXFormat "lualatex" = True
+      isTeXFormat "lualatex-dev" = True
+      isTeXFormat "pdflatex" = True
+      isTeXFormat "pdflatex-dev" = True
+      isTeXFormat "xelatex" = True
+      isTeXFormat _ = False
+  let opts' = if isTeXFormat program
+                 then -- disable quote ligatures to avoid bad ligatures like ?`
+                      opts{ writerExtensions = disableExtension Ext_smart
+                                (writerExtensions opts) }
+                 else opts
+  source <- fillMediaBag doc
+              >>= extractMedia tmpdir
+              >>= (if isTeXFormat program
+                      then walkM (convertImages opts' tmpdir)
+                      else return)
+              >>= writer opts'
+
+  verbosity <- getVerbosity
+  let compileHTML mkOutArgs = do
+        -- check to see if there is anything in mediabag, and if so,
+        -- make the HTML self contained
+        mediabag <- getMediaBag
+        source' <- case mediaItems mediabag of
+                      [] -> pure source
+                      _ -> makeSelfContained source
+        liftIO $
+          toPdfViaTempFile verbosity program pdfargs mkOutArgs ".html" source'
+  case takeBaseName program of
+    "wkhtmltopdf" -> makeWithWkhtmltopdf program pdfargs writer opts' doc
+    "pagedjs-cli" -> compileHTML (\f -> ["-o", f])
+    "prince"      -> compileHTML (\f -> ["-o", f])
+    "weasyprint"  -> compileHTML (:[])
+    "typst" -> liftIO $
+        toPdfViaTempFile verbosity program ("compile":pdfargs) (:[]) ".typ" source
+    "pdfroff" -> do
+      let paperargs =
+            case lookupContext "papersize" (writerVariables opts') of
+              Just s
+                | T.takeEnd 1 s == "l" -> ["-P-p" <>
+                                           T.unpack (T.dropEnd 1 s), "-P-l"]
+                | otherwise -> ["-P-p" <> T.unpack s]
+              Nothing -> []
+      let args   = ["-ms", "-mpdfmark", "-mspdf",
+                    "-e", "-t", "-k", "-KUTF-8", "-i"] ++
+                   ["-U" | ".PDFPIC" `T.isInfixOf` source] ++
+                    paperargs ++ pdfargs
+      generic2pdf program args source
+    "groff" -> do
+      let paperargs =
+            case lookupContext "papersize" (writerVariables opts') of
+              Just s
+                | T.takeEnd 1 s == "l" -> ["-P-p" <>
+                                           T.unpack (T.dropEnd 1 s), "-P-l"]
+                | otherwise -> ["-P-p" <> T.unpack s]
+              Nothing -> []
+      let args   = ["-ms", "-Tpdf",
+                    "-e", "-t", "-k", "-KUTF-8"] ++
+                   ["-U" | ".PDFPIC" `T.isInfixOf` source] ++
+                    paperargs ++ pdfargs
+      generic2pdf program args source
+    "context"      -> context2pdf program pdfargs tmpdir source
+    "tectonic"     -> tectonic2pdf program pdfargs tmpdir source
+    "latexmk"      -> tex2pdf program pdfargs tmpdir source
+    "lualatex"     -> tex2pdf program pdfargs tmpdir source
+    "lualatex-dev" -> tex2pdf program pdfargs tmpdir source
+    "pdflatex"     -> tex2pdf program pdfargs tmpdir source
+    "pdflatex-dev" -> tex2pdf program pdfargs tmpdir source
+    "xelatex"      -> tex2pdf 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)
+withTempDir :: (PandocMonad m, MonadMask m, MonadIO m)
+            => Bool -> FilePath -> (FilePath -> m a) -> m a
+withTempDir useWorkingDirectory templ action = do
+  tmp <- liftIO getTemporaryDirectory
+  uname <- liftIO $ E.catch
+    (do (ec, sout, _) <- readProcessWithExitCode "uname" ["-o"] ""
+        if ec == ExitSuccess
+           then return $ Just $ filter (not . isSpace) sout
+           else return Nothing)
+    (\(_  :: E.SomeException) -> return Nothing)
+  if useWorkingDirectory || '~' `elem` tmp || uname == Just "Cygwin" -- see #5451
+     then withTempDirectory "." templ action
+     else withSystemTempDirectory templ action
+
+makeWithWkhtmltopdf :: (PandocMonad m, MonadIO m)
+                    => String              -- ^ wkhtmltopdf or path
+                    -> [String]            -- ^ arguments
+                    -> (WriterOptions -> Pandoc -> m Text)  -- ^ writer
+                    -> WriterOptions       -- ^ options
+                    -> Pandoc              -- ^ document
+                    -> m (Either ByteString ByteString)
+makeWithWkhtmltopdf program pdfargs writer opts doc@(Pandoc meta _) = do
   let mathArgs = case writerHTMLMathMethod opts of
                  -- with MathJax, wait til all math is rendered:
                       MathJax _ -> ["--run-script", "MathJax.Hub.Register.StartupHook('End Typeset', function() { window.status = 'mathjax_loaded' });",
                                     "--window-status", "mathjax_loaded"]
                       _ -> []
-  meta' <- metaToJSON opts (return . stringify) (return . stringify) meta
-  let toArgs (f, mbd) = maybe [] (\d -> ['-':'-':f, d]) mbd
-  let args   = pdfargs ++ mathArgs ++ concatMap toArgs
+  meta' <- metaToContext opts
+             (return . literal . stringify)
+             (return . literal . stringify)
+             meta
+  let toArgs (f, mbd) = maybe [] (\d -> ["--" <> f, T.unpack d]) mbd
+  let args   = mathArgs ++ concatMap toArgs
                  [("page-size", getField "papersize" meta')
                  ,("title", getField "title" meta')
-                 ,("margin-bottom", fromMaybe (Just "1.2in")
+                 ,("margin-bottom", Just $ fromMaybe "1.2in"
                             (getField "margin-bottom" meta'))
-                 ,("margin-top", fromMaybe (Just "1.25in")
+                 ,("margin-top", Just $ fromMaybe "1.25in"
                             (getField "margin-top" meta'))
-                 ,("margin-right", fromMaybe (Just "1.25in")
+                 ,("margin-right", Just $ fromMaybe "1.25in"
                             (getField "margin-right" meta'))
-                 ,("margin-left", fromMaybe (Just "1.25in")
+                 ,("margin-left", Just $ fromMaybe "1.25in"
                             (getField "margin-left" meta'))
-                 ]
-  source <- writer opts doc
-  verbosity <- getVerbosity
-  liftIO $ html2pdf verbosity "wkhtmltopdf" args source
-makePDF "weasyprint" pdfargs writer opts doc = do
-  source <- writer opts doc
-  verbosity <- getVerbosity
-  liftIO $ html2pdf verbosity "weasyprint" pdfargs source
-makePDF "prince" pdfargs writer opts doc = do
+                 ,("footer-html", getField "footer-html" meta')
+                 ,("header-html", getField "header-html" meta')
+                 ] ++ ("--enable-local-file-access" : pdfargs)
+                 -- see #6474
   source <- writer opts doc
   verbosity <- getVerbosity
-  liftIO $ html2pdf verbosity "prince" pdfargs source
-makePDF "pdfroff" pdfargs writer opts doc = do
-  source <- writer opts doc
-  let args   = ["-ms", "-mpdfmark", "-e", "-t", "-k", "-KUTF-8", "-i",
-                "--no-toc-relocation"] ++ pdfargs
-  verbosity <- getVerbosity
-  liftIO $ ms2pdf verbosity args source
-makePDF program pdfargs writer opts doc = do
-  let withTemp = if takeBaseName program == "context"
-                    then withTempDirectory "."
-                    else withTempDir
-  commonState <- getCommonState
-  verbosity <- getVerbosity
-  liftIO $ withTemp "tex2pdf." $ \tmpdir -> do
-    source <- runIOorExplode $ do
-                putCommonState commonState
-                doc' <- handleImages tmpdir doc
-                writer opts doc'
-    case takeBaseName program of
-       "context" -> context2pdf verbosity tmpdir source
-       prog | prog `elem` ["pdflatex", "lualatex", "xelatex"]
-           -> tex2pdf' verbosity pdfargs tmpdir program source
-       _ -> return $ Left $ UTF8.fromStringLazy $ "Unknown program " ++ program
-
-handleImages :: FilePath      -- ^ temp dir to store images
-             -> Pandoc        -- ^ document
-             -> PandocIO Pandoc
-handleImages tmpdir doc =
-  fillMediaBag doc >>=
-    extractMedia tmpdir >>=
-    walkM (convertImages tmpdir)
+  liftIO $ toPdfViaTempFile verbosity program args (:[]) ".html" source
 
-convertImages :: FilePath -> Inline -> PandocIO Inline
-convertImages tmpdir (Image attr ils (src, tit)) = do
-  img <- liftIO $ convertImage tmpdir src
+-- convert SVG to PDF, and pixel formats to PNG or JPEG, for TeX formats
+convertImages :: (PandocMonad m, MonadIO m)
+              => WriterOptions -> FilePath -> Inline -> m Inline
+convertImages opts tmpdir (Image attr ils (src, tit)) = do
+  img <- liftIO $ convertImage opts tmpdir $ T.unpack src
   newPath <-
     case img of
       Left e -> do
         report $ CouldNotConvertImage src e
         return src
-      Right fp -> return fp
+      Right fp -> return $ T.pack fp
   return (Image attr ils (newPath, tit))
-convertImages _ x = return x
+convertImages _ _ x = return x
 
 -- Convert formats which do not work well in pdf to png
-convertImage :: FilePath -> FilePath -> IO (Either String FilePath)
-convertImage tmpdir fname =
+convertImage :: WriterOptions -> FilePath -> FilePath
+             -> IO (Either Text FilePath)
+convertImage opts tmpdir fname = do
+  let dpi = show $ writerDpi opts
   case mime of
     Just "image/png" -> doNothing
     Just "image/jpeg" -> doNothing
     Just "application/pdf" -> doNothing
+    -- Note: eps is converted by pdflatex using epstopdf.pl
+    Just "application/eps" -> doNothing
     Just "image/svg+xml" -> E.catch (do
       (exit, _) <- pipeProcess Nothing "rsvg-convert"
-                     ["-f","pdf","-a","-o",pdfOut,fname] BL.empty
+                     ["-f","pdf","-a","--dpi-x",dpi,"--dpi-y",dpi,
+                      "-o",pdfOut,svgIn] BL.empty
       if exit == ExitSuccess
          then return $ Right pdfOut
          else return $ Left "conversion from SVG failed")
       (\(e :: E.SomeException) -> return $ Left $
-          "check that rsvg2pdf is in path.\n" ++
-          show e)
-    _ -> JP.readImage fname >>= \res ->
-          case res of
-               Left e    -> return $ Left e
+          "check that rsvg-convert is in path.\n" <>
+          tshow e)
+    _ -> JP.readImage fname >>= \case
+               Left e    -> return $ Left $ T.pack e
                Right img ->
                  E.catch (Right pngOut <$ JP.savePngImage pngOut img) $
-                     \(e :: E.SomeException) -> return (Left (show e))
+                     \(e :: E.SomeException) -> return (Left (tshow e))
   where
-    pngOut = replaceDirectory (replaceExtension fname ".png") tmpdir
-    pdfOut = replaceDirectory (replaceExtension fname ".pdf") tmpdir
+    sha = show (hashWith SHA1 (UTF8.fromString fname))
+    pngOut = normalise $ tmpdir </> sha <.> "png"
+    pdfOut = normalise $ tmpdir </> sha <.> "pdf"
+    svgIn = normalise fname
     mime = getMimeType fname
     doNothing = return (Right fname)
 
-tex2pdf' :: Verbosity                       -- ^ Verbosity level
-         -> [String]                        -- ^ Arguments to the latex-engine
-         -> FilePath                        -- ^ temp directory for output
-         -> String                          -- ^ tex program
-         -> Text                            -- ^ tex source
-         -> IO (Either ByteString ByteString)
-tex2pdf' verbosity args tmpDir program source = do
-  let numruns = 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)
+tectonic2pdf :: (PandocMonad m, MonadIO m)
+             => String                          -- ^ tex program
+             -> [String]                        -- ^ Arguments to the latex-engine
+             -> FilePath                        -- ^ temp directory for output
+             -> Text                            -- ^ tex source
+             -> m (Either ByteString ByteString)
+tectonic2pdf program args tmpDir source = do
+  (exit, log', mbPdf) <- runTectonic program args tmpDir source
   case (exit, mbPdf) of
+       (ExitFailure _, _)      -> return $ Left $ extractMsg log'
+       (ExitSuccess, Nothing)  -> return $ Left ""
+       (ExitSuccess, Just pdf) -> do
+          missingCharacterWarnings log'
+          return $ Right pdf
+
+tex2pdf :: (PandocMonad m, MonadIO m)
+        => String                          -- ^ tex program
+        -> [String]                        -- ^ Arguments to the latex-engine
+        -> FilePath                        -- ^ temp directory for output
+        -> Text                            -- ^ tex source
+        -> m (Either ByteString ByteString)
+tex2pdf program args tmpDir source = do
+  let isOutdirArg x = "-outdir=" `isPrefixOf` x ||
+                      "-output-directory=" `isPrefixOf` x
+  let outDir =
+        case find isOutdirArg args of
+          Just x  -> drop 1 $ dropWhile (/='=') x
+          Nothing -> tmpDir
+  let file = tmpDir ++ "/input.tex"  -- note: tmpDir has / path separators
+  liftIO $ BS.writeFile file $ UTF8.fromText source
+  (exit, log', mbPdf) <- runTeXProgram program args tmpDir outDir
+  case (exit, mbPdf) of
        (ExitFailure _, _)      -> do
           let logmsg = extractMsg log'
           let extramsg =
@@ -215,22 +309,38 @@
           return $ Left $ logmsg <> extramsg
        (ExitSuccess, Nothing)  -> return $ Left ""
        (ExitSuccess, Just pdf) -> do
-          missingCharacterWarnings verbosity log'
+          latexWarnings log'
+          missingCharacterWarnings log'
           return $ Right pdf
 
-missingCharacterWarnings :: Verbosity -> ByteString -> IO ()
-missingCharacterWarnings verbosity log' = do
+missingCharacterWarnings :: PandocMonad m => ByteString -> m ()
+missingCharacterWarnings log' = do
   let ls = BC.lines log'
-  let isMissingCharacterWarning = BC.isPrefixOf "Missing character: "
-  let warnings = [ UTF8.toStringLazy (BC.drop 19 l)
+  let isMissingCharacterWarning = BC.isPrefixOf "Missing character:"
+  let toCodePoint c
+        | isAscii c   = T.singleton c
+        | otherwise   = T.pack $ c : " (U+" ++ printf "%04X" (ord c) ++ ")"
+  let addCodePoint = T.concatMap toCodePoint
+  let warnings = [ addCodePoint (utf8ToText (BC.drop 19 l))
                  | l <- ls
                  , isMissingCharacterWarning l
                  ]
-  runIO $ do
-    setVerbosity verbosity
-    mapM_ (report . MissingCharacter) warnings
-  return ()
+  mapM_ (report . MissingCharacter) warnings
 
+latexWarnings :: PandocMonad m => ByteString -> m ()
+latexWarnings log' = foldM_ go Nothing (BC.lines log')
+ where
+   go Nothing ln
+     | BC.isPrefixOf "LaTeX Warning:" ln =
+       pure $ Just ln
+     | otherwise = pure Nothing
+   go (Just msg) ln
+     | ln == "" = do -- emit report and reset accumulator
+         report $ MakePDFWarning $ render (Just 60) $
+            hsep $ map literal $ T.words $ utf8ToText msg
+         pure Nothing
+     | otherwise = pure $ Just (msg <> ln)
+
 -- parsing output
 
 extractMsg :: ByteString -> ByteString
@@ -252,189 +362,319 @@
 
 -- running tex programs
 
--- Run a TeX program on an input bytestring and return (exit code,
--- 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
-    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
+runTectonic :: (PandocMonad m, MonadIO m)
+            => String -> [String] -> FilePath
+              -> Text -> m (ExitCode, ByteString, Maybe ByteString)
+runTectonic program args' tmpDir' source = do
+    let getOutDir acc (a:b:xs) = if a `elem` ["-o", "--outdir"]
+                                    then (reverse acc ++ xs, Just b)
+                                    else getOutDir (b:a:acc) xs
+        getOutDir acc xs = (reverse acc ++ xs, Nothing)
+        (args, outDir) = getOutDir [] args'
+        tmpDir = fromMaybe tmpDir' outDir
+    liftIO $ createDirectoryIfMissing True tmpDir
+    -- run tectonic on stdin so it reads \include commands from $PWD instead of a temp directory
+    let sourceBL = BL.fromStrict $ UTF8.fromText source
+    let programArgs = ["--outdir", tmpDir] ++ args ++ ["-"]
+    env <- liftIO getEnvironment
+    showVerboseInfo (Just tmpDir) program programArgs env (utf8ToText sourceBL)
+    (exit, out) <- liftIO $ E.catch
+      (pipeProcess (Just env) program programArgs sourceBL)
+      (handlePDFProgramNotFound program)
+    report $ MakePDFInfo "tectonic output" (utf8ToText out)
+    let pdfFile = tmpDir ++ "/texput.pdf"
+    (_, pdf) <- getResultingPDF Nothing pdfFile
+    return (exit, out, pdf)
+
+-- read a pdf that has been written to a temporary directory, and optionally read
+-- logs
+getResultingPDF :: (PandocMonad m, MonadIO m)
+                => Maybe String -> String
+                -> m (Maybe ByteString, Maybe ByteString)
+getResultingPDF logFile pdfFile = do
+    pdfExists <- fileExists 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`
+                   (readFileStrict 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:
+    log' <- case logFile of
+              Just logFile' -> do
+                logExists <- fileExists logFile'
+                if logExists
+                  then Just . BL.fromStrict <$> readFileStrict logFile'
+                  else return Nothing
+              Nothing -> return Nothing
+    return (log', pdf)
+
+-- Run a TeX program once in a temp directory (on input.tex) and return (exit code,
+-- contents of stdout, contents of produced PDF if any).
+runTeXProgram :: (PandocMonad m, MonadIO m)
+              => String -> [String] -> FilePath -> FilePath
+              -> m (ExitCode, ByteString, Maybe ByteString)
+runTeXProgram program args tmpDir outDir = do
+    let isLatexMk = takeBaseName program == "latexmk"
+        programArgs | isLatexMk =
+                      ["-interaction=batchmode", "-halt-on-error", "-pdf",
+                       "-quiet", "-outdir=" ++ outDir] ++ args ++ [file]
+                    | otherwise =
+                      ["-halt-on-error", "-interaction", "nonstopmode",
+                       "-output-directory", outDir] ++ 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
-      putStrLn $ "[makePDF] Run #" ++ show runNumber
-      BL.hPutStr stdout out
-      putStr "\n"
-    if runNumber <= numRuns
-       then runTeXProgram verbosity program args (runNumber + 1) numRuns tmpDir source
+                ("TEXMFOUTPUT", outDir) :
+                  [(k,v) | (k,v) <- env'
+                         , k /= "TEXINPUTS" && k /= "TEXMFOUTPUT"]
+    liftIO (UTF8.readFile file) >>=
+      showVerboseInfo (Just tmpDir) program programArgs env''
+    go env'' programArgs (1 :: Int)
+ where
+   file = tmpDir ++ "/input.tex"
+   outfile = outDir ++ "/input.pdf"
+   go env'' programArgs runNumber = do
+     let maxruns = 4 -- stop if warnings present after 4 runs
+     report $ MakePDFInfo ("LaTeX run number " <> tshow runNumber) mempty
+     (exit, out) <- liftIO $ E.catch
+       (pipeProcess (Just env'') program programArgs BL.empty)
+       (handlePDFProgramNotFound program)
+     report $ MakePDFInfo "LaTeX output" (utf8ToText out)
+     -- parse log to see if we need to rerun LaTeX
+     let logFile = replaceExtension outfile ".log"
+     logExists <- fileExists logFile
+     logContents <- if logExists
+                       then BL.fromStrict <$> readFileStrict logFile
+                       else return mempty
+     let rerunWarnings = checkForRerun logContents
+     tocFileExists <- fileExists (replaceExtension outfile ".toc")
+       -- if we have a TOC we always need 3 runs, see #10308
+     let rerunWarnings' = rerunWarnings ++ ["TOC is present" | tocFileExists]
+     if not (null rerunWarnings') && runNumber < maxruns
+        then do
+          report $ MakePDFInfo "Rerun needed"
+                    (T.intercalate "\n" (map utf8ToText rerunWarnings'))
+          go env'' programArgs (runNumber + 1)
        else do
-         let pdfFile = replaceDirectory (replaceExtension file ".pdf") tmpDir
-         pdfExists <- 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
-                   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
-         log' <- if logExists
-                    then BL.readFile logFile
-                    else return out
-         return (exit, log', pdf)
+          (log', pdf) <- getResultingPDF (Just logFile) outfile
+          return (exit, fromMaybe out log', pdf)
 
-ms2pdf :: Verbosity
-       -> [String]
-       -> Text
-       -> IO (Either ByteString ByteString)
-ms2pdf verbosity args source = do
-  env' <- getEnvironment
-  when (verbosity >= INFO) $ do
-    putStrLn "[makePDF] Command line:"
-    putStrLn $ "pdfroff " ++ " " ++ unwords (map show args)
-    putStr "\n"
-    putStrLn "[makePDF] Environment:"
-    mapM_ print env'
-    putStr "\n"
-    putStrLn "[makePDF] Contents:\n"
-    putStr $ T.unpack source
-    putStr "\n"
-  (exit, out) <- E.catch
-    (pipeProcess (Just env') "pdfroff" args
+   checkForRerun log' = filter isRerunWarning $ BC.lines log'
+
+   isRerunWarning ln =
+     let ln' = BL.toStrict ln
+       in BS.isInfixOf "Warning:" ln' && BS.isInfixOf "Rerun" ln'
+
+generic2pdf :: (PandocMonad m, MonadIO m)
+            => String
+            -> [String]
+            -> Text
+            -> m (Either ByteString ByteString)
+generic2pdf program args source = do
+  env' <- liftIO getEnvironment
+  showVerboseInfo Nothing program args env' source
+  (exit, out) <- liftIO $ E.catch
+    (pipeProcess (Just env') program args
                      (BL.fromStrict $ UTF8.fromText source))
-    (\(e :: IOError) -> if isDoesNotExistError e
-                           then E.throwIO $
-                                  PandocPDFProgramNotFoundError "pdfroff"
-                           else E.throwIO e)
-  when (verbosity >= INFO) $ do
-    BL.hPutStr stdout out
-    putStr "\n"
+    (handlePDFProgramNotFound program)
   return $ case exit of
              ExitFailure _ -> Left out
              ExitSuccess   -> Right out
 
-html2pdf  :: Verbosity    -- ^ Verbosity level
-          -> String       -- ^ Program (wkhtmltopdf, weasyprint or prince)
+toPdfViaTempFile  ::
+             Verbosity    -- ^ Verbosity level
+          -> String       -- ^ Program (program name or path)
           -> [String]     -- ^ Args to program
-          -> Text         -- ^ HTML5 source
+          -> (String -> [String]) -- ^ Construct args for output file
+          -> String       -- ^ extension to use for input file (e.g. '.html')
+          -> Text         -- ^ Source
           -> IO (Either ByteString ByteString)
-html2pdf verbosity program args source = do
-  pdfFile <- withTempFile "." "html2pdf.pdf" $ \fp _ -> return fp
-  let pdfFileArgName = ["-o" | program == "prince"]
-  let programArgs = args ++ ["-"] ++ pdfFileArgName ++ [pdfFile]
-  env' <- getEnvironment
-  when (verbosity >= INFO) $ do
-    putStrLn "[makePDF] Command line:"
-    putStrLn $ program ++ " " ++ unwords (map show programArgs)
-    putStr "\n"
-    putStrLn "[makePDF] Environment:"
-    mapM_ print env'
-    putStr "\n"
-    putStrLn "[makePDF] Contents of intermediate HTML:"
-    TextIO.putStr source
-    putStr "\n"
-  (exit, out) <- E.catch
-    (pipeProcess (Just env') program programArgs $ BL.fromStrict $ UTF8.fromText source)
-    (\(e :: IOError) -> if isDoesNotExistError e
-                           then E.throwIO $
-                                  PandocPDFProgramNotFoundError program
-                           else E.throwIO e)
-  when (verbosity >= INFO) $ do
-    BL.hPutStr stdout out
-    putStr "\n"
-  pdfExists <- doesFileExist pdfFile
-  mbPdf <- if pdfExists
-            -- We read PDF as a strict bytestring to make sure that the
-            -- temp directory is removed on Windows.
-            -- See https://github.com/jgm/pandoc/issues/1192.
-            then do
-              res <- (Just . BL.fromChunks . (:[])) `fmap` BS.readFile pdfFile
-              removeFile pdfFile
-              return res
-            else return Nothing
-  return $ case (exit, mbPdf) of
-             (ExitFailure _, _)      -> Left out
-             (ExitSuccess, Nothing)  -> Left ""
-             (ExitSuccess, Just pdf) -> Right pdf
+toPdfViaTempFile verbosity program args mkOutArgs extension source =
+  withTempFile "." ("toPdfViaTempFile" <> extension) $ \file h1 ->
+    withTempFile "." "toPdfViaTempFile.pdf" $ \pdfFile h2 -> do
+      hClose h1
+      hClose h2
+      BS.writeFile file $ UTF8.fromText source
+      let programArgs = args ++ [file] ++ mkOutArgs pdfFile
+      env' <- getEnvironment
+      fileContents <- UTF8.readFile file
+      runIOorExplode $ do
+        setVerbosity verbosity
+        showVerboseInfo Nothing program programArgs env' fileContents
+      (exit, out) <- E.catch
+        (pipeProcess (Just env') program programArgs BL.empty)
+        (handlePDFProgramNotFound program)
+      runIOorExplode $ do
+        setVerbosity verbosity
+        report $ MakePDFInfo "pdf-engine output" (utf8ToText out)
+      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 . (:[]) <$> BS.readFile pdfFile
+                else return Nothing
+      return $ case (exit, mbPdf) of
+                 (ExitFailure _, _)      -> Left out
+                 (ExitSuccess, Nothing)  -> Left ""
+                 (ExitSuccess, Just pdf) -> Right pdf
 
-context2pdf :: Verbosity    -- ^ Verbosity level
+context2pdf :: (PandocMonad m, MonadIO m)
+            => String       -- ^ "context" or path to it
+            -> [String]     -- ^ extra arguments
             -> FilePath     -- ^ temp directory for output
             -> Text         -- ^ ConTeXt source
-            -> IO (Either ByteString ByteString)
-context2pdf verbosity tmpDir source = inDirectory tmpDir $ do
+            -> m (Either ByteString ByteString)
+context2pdf program pdfargs tmpDir source = 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 $ "context" ++ " " ++ 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') "context" 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
+  let programArgs = "--batchmode" : pdfargs ++ [file]
+  env' <- liftIO getEnvironment
+  verbosity <- getVerbosity
+  liftIO $ BS.writeFile (tmpDir </> file) $ UTF8.fromText source
+  liftIO (UTF8.readFile (tmpDir </> file)) >>=
+    showVerboseInfo (Just tmpDir) program programArgs env'
+  liftIO $ inDirectory tmpDir $ do
+    (exit, out) <- E.catch
+      (pipeProcess (Just env') program programArgs BL.empty)
+      (handlePDFProgramNotFound program)
+    runIOorExplode $ do
+      setVerbosity verbosity
+      report $ MakePDFInfo "ConTeXt run output" (utf8ToText out)
+    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 :: PandocMonad m
+                => Maybe FilePath
+                -> String
+                -> [String]
+                -> [(String, String)]
+                -> Text
+                -> m ()
+showVerboseInfo mbTmpDir program programArgs env source = do
+  case mbTmpDir of
+    Just tmpDir -> report $ MakePDFInfo "Temp dir:" (T.pack tmpDir)
+    Nothing -> return ()
+  report $ MakePDFInfo "Command line:"
+           (T.pack program <> " " <> T.pack (unwords (map show programArgs)))
+  -- we filter out irrelevant stuff to avoid leaking passwords and keys!
+  let isRelevant e = (e `elem` [ "PKFONTS"
+                               , "AFMFONTS"
+                               , "BIBINPUTS"
+                               , "BLTXMLINPUTS"
+                               , "BSTINPUTS"
+                               , "CLUAINPUTS"
+                               , "CMAPFONTS"
+                               , "CWEBINPUTS"
+                               , "DVIPSHEADERS"
+                               , "ENCFONTS"
+                               , "FONTCIDMAPS"
+                               , "FONTFEATURES"
+                               , "GFFONTS"
+                               , "GLYPHFONTS"
+                               , "HOME"
+                               , "INDEXSTYLE"
+                               , "KPATHSEA_DEBUG"
+                               , "KPATHSEA_WARNING"
+                               , "LANG"
+                               , "LIGFONTS"
+                               , "LUAINPUTS"
+                               , "LUA_CPATH"
+                               , "LUA_PATH"
+                               , "MFBASES"
+                               , "MFINPUTS"
+                               , "MFPOOL"
+                               , "MFTINPUTS"
+                               , "MISCFONTS"
+                               , "MISSFONT_LOG"
+                               , "MLBIBINPUTS"
+                               , "MLBSTINPUTS"
+                               , "MPINPUTS"
+                               , "MPMEMS"
+                               , "MPPOOL"
+                               , "MPSUPPORT"
+                               , "OCPINPUTS"
+                               , "OFMFONTS"
+                               , "OPENTYPEFONTS"
+                               , "OPLFONTS"
+                               , "OTPINPUTS"
+                               , "OVFFONTS"
+                               , "OVPFONTS"
+                               , "PATH"
+                               , "PDFTEXCONFIG"
+                               , "PROGRAMFONTS"
+                               , "PSHEADERS"
+                               , "PWD"
+                               , "RISINPUTS"
+                               , "SELFAUTODIR"
+                               , "SELFAUTOLOC"
+                               , "SELFAUTOPARENT"
+                               , "SFDFONTS"
+                               , "SHELL"
+                               , "SOURCE_DATE_EPOCH"
+                               , "T1FONTS"
+                               , "T1INPUTS"
+                               , "T42FONTS"
+                               , "TEXBIB"
+                               , "TEXCONFIG"
+                               , "TEXDOCS"
+                               , "TEXFONTMAPS"
+                               , "TEXFONTS"
+                               , "TEXFORMATS"
+                               , "TEXINDEXSTYLE"
+                               , "TEXINPUTS"
+                               , "TEXMFCNF"
+                               , "TEXMFDBS"
+                               , "TEXMFINI"
+                               , "TEXMFSCRIPTS"
+                               , "TEXMFVAR"
+                               , "TEXPICTS"
+                               , "TEXPKS"
+                               , "TEXPOOL"
+                               , "TEXPSHEADERS"
+                               , "TEXSOURCES"
+                               , "TEX_HUSH"
+                               , "TFMFONTS"
+                               , "TMPDIR"
+                               , "TRFONTS"
+                               , "TTFONTS"
+                               , "USERPROFILE"
+                               , "USE_TEXMFVAR"
+                               , "USE_VARTEXFONTS"
+                               , "VARTEXFONTS"
+                               , "VFFONTS"
+                               , "WEB2C"
+                               , "WEBINPUTS"
+                               ]) || "TEXMF" `isPrefixOf` e
+  report $ MakePDFInfo "Relevant environment variables:"
+             (T.intercalate "\n" $ map tshow $ filter (isRelevant . fst) env)
+  report $ MakePDFInfo "Source:" source
+
+handlePDFProgramNotFound :: String -> IE.IOError -> IO a
+handlePDFProgramNotFound program e
+  | IE.isDoesNotExistError e =
+      E.throwIO $ PandocPDFProgramNotFoundError $ T.pack program
+  | otherwise = E.throwIO e
+
+utf8ToText :: ByteString -> Text
+utf8ToText lbs =
+  case decodeUtf8' lbs of
+    Left _  -> T.pack $ BC.unpack lbs  -- if decoding fails, treat as latin1
+    Right t -> TL.toStrict t
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
@@ -1,1471 +1,355 @@
-{-# LANGUAGE ExplicitForAll             #-}
-{-# LANGUAGE FlexibleContexts           #-}
-{-# LANGUAGE FlexibleInstances          #-}
-{-# LANGUAGE GeneralizedNewtypeDeriving #-}
-{-# LANGUAGE IncoherentInstances        #-}
-{-# LANGUAGE MultiParamTypeClasses      #-}
-{-# LANGUAGE TypeSynonymInstances       #-}
-{-
-Copyright (C) 2006-2017 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-2017 John MacFarlane
-   License     : GNU GPL, version 2 or above
-
-   Maintainer  : John MacFarlane <jgm@berkeley.edu>
-   Stability   : alpha
-   Portability : portable
-
-A utility library with parsers used in pandoc readers.
--}
-module Text.Pandoc.Parsing ( takeWhileP,
-                             takeP,
-                             anyLine,
-                             anyLineNewline,
-                             indentWith,
-                             many1Till,
-                             notFollowedBy',
-                             oneOfStrings,
-                             oneOfStringsCI,
-                             spaceChar,
-                             nonspaceChar,
-                             skipSpaces,
-                             blankline,
-                             blanklines,
-                             gobbleSpaces,
-                             gobbleAtMostSpaces,
-                             enclosed,
-                             stringAnyCase,
-                             parseFromString,
-                             parseFromString',
-                             lineClump,
-                             charsInBalanced,
-                             romanNumeral,
-                             emailAddress,
-                             uri,
-                             mathInline,
-                             mathDisplay,
-                             withHorizDisplacement,
-                             withRaw,
-                             escaped,
-                             characterReference,
-                             anyOrderedListMarker,
-                             orderedListMarker,
-                             charRef,
-                             lineBlockLines,
-                             tableWith,
-                             widthsFromIndices,
-                             gridTableWith,
-                             gridTableWith',
-                             readWith,
-                             readWithM,
-                             testStringWith,
-                             guardEnabled,
-                             guardDisabled,
-                             updateLastStrPos,
-                             notAfterString,
-                             logMessage,
-                             reportLogMessages,
-                             ParserState (..),
-                             HasReaderOptions (..),
-                             HasHeaderMap (..),
-                             HasIdentifierList (..),
-                             HasMacros (..),
-                             HasLogMessages (..),
-                             HasLastStrPosition (..),
-                             HasIncludeFiles (..),
-                             defaultParserState,
-                             HeaderType (..),
-                             ParserContext (..),
-                             QuoteContext (..),
-                             HasQuoteContext (..),
-                             NoteTable,
-                             NoteTable',
-                             KeyTable,
-                             SubstTable,
-                             Key (..),
-                             toKey,
-                             registerHeader,
-                             smartPunctuation,
-                             singleQuoteStart,
-                             singleQuoteEnd,
-                             doubleQuoteStart,
-                             doubleQuoteEnd,
-                             ellipses,
-                             apostrophe,
-                             dash,
-                             nested,
-                             citeKey,
-                             Parser,
-                             ParserT,
-                             F,
-                             Future(..),
-                             runF,
-                             askF,
-                             asksF,
-                             returnF,
-                             trimInlinesF,
-                             token,
-                             (<+?>),
-                             extractIdClass,
-                             insertIncludedFile,
-                             insertIncludedFileF,
-                             -- * Re-exports from Text.Pandoc.Parsec
-                             Stream,
-                             runParser,
-                             runParserT,
-                             parse,
-                             tokenPrim,
-                             anyToken,
-                             getInput,
-                             setInput,
-                             unexpected,
-                             char,
-                             letter,
-                             digit,
-                             alphaNum,
-                             skipMany,
-                             skipMany1,
-                             spaces,
-                             space,
-                             anyChar,
-                             satisfy,
-                             newline,
-                             string,
-                             count,
-                             eof,
-                             noneOf,
-                             oneOf,
-                             lookAhead,
-                             notFollowedBy,
-                             many,
-                             many1,
-                             manyTill,
-                             (<|>),
-                             (<?>),
-                             choice,
-                             try,
-                             sepBy,
-                             sepBy1,
-                             sepEndBy,
-                             sepEndBy1,
-                             endBy,
-                             endBy1,
-                             option,
-                             optional,
-                             optionMaybe,
-                             getState,
-                             setState,
-                             updateState,
-                             SourcePos,
-                             getPosition,
-                             setPosition,
-                             sourceColumn,
-                             sourceLine,
-                             setSourceColumn,
-                             setSourceLine,
-                             newPos,
-                             Line,
-                             Column
-                             )
-where
-
-import Control.Monad.Identity
-import Control.Monad.Reader
-import Data.Char (chr, isAlphaNum, isAscii, isAsciiUpper, isHexDigit, isPunctuation, isSpace,
-                  ord, toLower, toUpper)
-import Data.Default
-import Data.List (intercalate, isSuffixOf, transpose)
-import qualified Data.Map as M
-import Data.Maybe (mapMaybe)
-import Data.Monoid ((<>))
-import qualified Data.Set as Set
-import Data.Text (Text)
-import Text.HTML.TagSoup.Entity (lookupEntity)
-import Text.Pandoc.Asciify (toAsciiChar)
-import Text.Pandoc.Builder (Blocks, HasMeta (..), Inlines, trimInlines)
-import qualified Text.Pandoc.Builder as B
-import Text.Pandoc.Class (PandocMonad, readFileFromDirs, report)
-import Text.Pandoc.Definition
-import Text.Pandoc.Logging
-import Text.Pandoc.Options
-import Text.Pandoc.Readers.LaTeX.Types (Macro)
-import Text.Pandoc.Shared
-import qualified Text.Pandoc.UTF8 as UTF8 (putStrLn)
-import Text.Pandoc.XML (fromEntities)
-import Text.Parsec hiding (token)
-import Text.Parsec.Pos (initialPos, newPos, updatePosString)
-
-import Control.Monad.Except
-import Text.Pandoc.Error
-
-type Parser t s = Parsec t s
-
-type ParserT = ParsecT
-
--- | Reader monad wrapping the parser state. This is used to possibly delay
--- evaluation until all relevant information has been parsed and made available
--- in the parser state.
-newtype Future s a = Future { runDelayed :: Reader s a }
-  deriving (Monad, Applicative, Functor)
-
-type F = Future ParserState
-
-runF :: Future s a -> s -> a
-runF = runReader . runDelayed
-
-askF :: Future s s
-askF = Future ask
-
-asksF :: (s -> a) -> Future s a
-asksF f = Future $ asks f
-
-returnF :: Monad m => a -> m (Future s a)
-returnF = return . return
-
-trimInlinesF :: Future s Inlines -> Future s Inlines
-trimInlinesF = liftM trimInlines
-
-instance Monoid a => Monoid (Future s a) where
-  mempty = return mempty
-  mappend = liftM2 mappend
-  mconcat = liftM mconcat . sequence
-
--- | Parse characters while a predicate is true.
-takeWhileP :: Monad m
-           => (Char -> Bool)
-           -> ParserT [Char] st m [Char]
-takeWhileP f = do
-  -- faster than 'many (satisfy f)'
-  inp <- getInput
-  pos <- getPosition
-  let (xs, rest) = span f inp
-  -- needed to persuade parsec that this won't match an empty string:
-  anyChar
-  setInput rest
-  setPosition $ updatePosString pos xs
-  return xs
-
--- Parse n characters of input (or the rest of the input if
--- there aren't n characters).
-takeP :: Monad m => Int -> ParserT [Char] st m [Char]
-takeP n = do
-  guard (n > 0)
-  -- faster than 'count n anyChar'
-  inp <- getInput
-  pos <- getPosition
-  let (xs, rest) = splitAt n inp
-  -- needed to persuade parsec that this won't match an empty string:
-  anyChar
-  setInput rest
-  setPosition $ updatePosString pos xs
-  return xs
-
--- | Parse any line of text
-anyLine :: Monad m => ParserT [Char] st m [Char]
-anyLine = do
-  -- This is much faster than:
-  -- manyTill anyChar newline
-  inp <- getInput
-  pos <- getPosition
-  case break (=='\n') inp of
-       (this, '\n':rest) -> do
-         -- needed to persuade parsec that this won't match an empty string:
-         anyChar
-         setInput rest
-         setPosition $ incSourceLine (setSourceColumn pos 1) 1
-         return this
-       _ -> mzero
-
--- | Parse any line, include the final newline in the output
-anyLineNewline :: Monad m => ParserT [Char] st m [Char]
-anyLineNewline = (++ "\n") <$> anyLine
-
--- | Parse indent by specified number of spaces (or equiv. tabs)
-indentWith :: Stream s m Char
-           => HasReaderOptions st
-           => Int -> ParserT s st m [Char]
-indentWith num = do
-  tabStop <- getOption readerTabStop
-  if (num < tabStop)
-     then count num (char ' ')
-     else choice [ try (count num (char ' '))
-                 , try (char '\t' >> indentWith (num - tabStop)) ]
-
--- | Like @manyTill@, but reads at least one item.
-many1Till :: (Show end, Stream s m t)
-          => ParserT s st m a
-          -> ParserT s st m end
-          -> ParserT s st m [a]
-many1Till p end = do
-         notFollowedBy' end
-         first <- p
-         rest <- manyTill p end
-         return (first:rest)
-
--- | A more general form of @notFollowedBy@.  This one allows any
--- type of parser to be specified, and succeeds only if that parser fails.
--- It does not consume any input.
-notFollowedBy' :: (Show b, Stream s m a) => ParserT s st m b -> ParserT s st m ()
-notFollowedBy' p  = try $ join $  do  a <- try p
-                                      return (unexpected (show a))
-                                  <|>
-                                  return (return ())
--- (This version due to Andrew Pimlott on the Haskell mailing list.)
-
-oneOfStrings' :: Stream s m Char => (Char -> Char -> Bool) -> [String] -> ParserT s st m String
-oneOfStrings' _ []   = fail "no strings"
-oneOfStrings' matches strs = try $ do
-  c <- anyChar
-  let strs' = [xs | (x:xs) <- strs, x `matches` c]
-  case strs' of
-       []  -> fail "not found"
-       _   -> (c:) <$> oneOfStrings' matches strs'
-               <|> if "" `elem` strs'
-                      then return [c]
-                      else fail "not found"
-
--- | Parses one of a list of strings.  If the list contains
--- two strings one of which is a prefix of the other, the longer
--- string will be matched if possible.
-oneOfStrings :: Stream s m Char => [String] -> ParserT s st m String
-oneOfStrings = oneOfStrings' (==)
-
--- | Parses one of a list of strings (tried in order), case insensitive.
-oneOfStringsCI :: Stream s m Char => [String] -> ParserT s st m String
-oneOfStringsCI = oneOfStrings' ciMatch
-  where ciMatch x y = toLower' x == toLower' y
-        -- this optimizes toLower by checking common ASCII case
-        -- first, before calling the expensive unicode-aware
-        -- function:
-        toLower' c | isAsciiUpper c = chr (ord c + 32)
-                   | isAscii c = c
-                   | otherwise = toLower c
-
--- | Parses a space or tab.
-spaceChar :: Stream s m Char => ParserT s st m Char
-spaceChar = satisfy $ \c -> c == ' ' || c == '\t'
-
--- | Parses a nonspace, nonnewline character.
-nonspaceChar :: Stream s m Char => ParserT s st m Char
-nonspaceChar = satisfy $ flip notElem ['\t', '\n', ' ', '\r']
-
--- | Skips zero or more spaces or tabs.
-skipSpaces :: Stream s m Char => ParserT s st m ()
-skipSpaces = skipMany spaceChar
-
--- | Skips zero or more spaces or tabs, then reads a newline.
-blankline :: Stream s m Char => ParserT s st m Char
-blankline = try $ skipSpaces >> newline
-
--- | Parses one or more blank lines and returns a string of newlines.
-blanklines :: Stream s m Char => ParserT s st m [Char]
-blanklines = many1 blankline
-
--- | Gobble n spaces; if tabs are encountered, expand them
--- and gobble some or all of their spaces, leaving the rest.
-gobbleSpaces :: (HasReaderOptions st, Monad m)
-             => Int -> ParserT [Char] st m ()
-gobbleSpaces 0 = return ()
-gobbleSpaces n
-  | n < 0     = error "gobbleSpaces called with negative number"
-  | otherwise = try $ do
-      char ' ' <|> eatOneSpaceOfTab
-      gobbleSpaces (n - 1)
-
-eatOneSpaceOfTab :: (HasReaderOptions st, Monad m) => ParserT [Char] st m Char
-eatOneSpaceOfTab = do
-  char '\t'
-  tabstop <- getOption readerTabStop
-  inp <- getInput
-  setInput $ replicate (tabstop - 1) ' ' ++ inp
-  return ' '
-
--- | Gobble up to n spaces; if tabs are encountered, expand them
--- and gobble some or all of their spaces, leaving the rest.
-gobbleAtMostSpaces :: (HasReaderOptions st, Monad m)
-                   => Int -> ParserT [Char] st m Int
-gobbleAtMostSpaces 0 = return 0
-gobbleAtMostSpaces n
-  | n < 0     = error "gobbleAtMostSpaces called with negative number"
-  | otherwise = option 0 $ do
-      char ' ' <|> eatOneSpaceOfTab
-      (+ 1) <$> gobbleAtMostSpaces (n - 1)
-
--- | Parses material enclosed between start and end parsers.
-enclosed :: (Show end, Stream s  m Char) => ParserT s st m t   -- ^ start parser
-         -> ParserT s st m end  -- ^ end parser
-         -> ParserT s st m a    -- ^ content parser (to be used repeatedly)
-         -> ParserT s st m [a]
-enclosed start end parser = try $
-  start >> notFollowedBy space >> many1Till parser end
-
--- | Parse string, case insensitive.
-stringAnyCase :: Stream s m Char => [Char] -> ParserT s st m String
-stringAnyCase [] = string ""
-stringAnyCase (x:xs) = do
-  firstChar <- char (toUpper x) <|> char (toLower x)
-  rest <- stringAnyCase xs
-  return (firstChar:rest)
-
--- | Parse contents of 'str' using 'parser' and return result.
-parseFromString :: Monad m
-                => ParserT [Char] st m a
-                -> String
-                -> ParserT [Char] st m a
-parseFromString parser str = do
-  oldPos <- getPosition
-  setPosition $ initialPos "chunk"
-  oldInput <- getInput
-  setInput str
-  result <- parser
-  spaces
-  eof
-  setInput oldInput
-  setPosition oldPos
-  return result
-
--- | Like 'parseFromString' but specialized for 'ParserState'.
--- This resets 'stateLastStrPos', which is almost always what we want.
-parseFromString' :: Monad m
-                 => ParserT String ParserState m a
-                 -> String
-                 -> ParserT String ParserState m a
-parseFromString' parser str = do
-  oldStrPos <- stateLastStrPos <$> getState
-  res <- parseFromString parser str
-  updateState $ \st -> st{ stateLastStrPos = oldStrPos }
-  return res
-
--- | Parse raw line block up to and including blank lines.
-lineClump :: Monad m => ParserT [Char] st m String
-lineClump = blanklines
-          <|> (unlines <$> many1 (notFollowedBy blankline >> anyLine))
-
--- | Parse a string of characters between an open character
--- and a close character, including text between balanced
--- pairs of open and close, which must be different. For example,
--- @charsInBalanced '(' ')' anyChar@ will parse "(hello (there))"
--- and return "hello (there)".
-charsInBalanced :: Stream s m Char => Char -> Char -> ParserT s st m Char
-                -> ParserT s st m String
-charsInBalanced open close parser = try $ do
-  char open
-  let isDelim c = c == open || c == close
-  raw <- many $  many1 (notFollowedBy (satisfy isDelim) >> parser)
-             <|> (do res <- charsInBalanced open close parser
-                     return $ [open] ++ res ++ [close])
-  char close
-  return $ concat raw
-
--- old charsInBalanced would be:
--- charsInBalanced open close (noneOf "\n" <|> char '\n' >> notFollowedBy blankline)
--- old charsInBalanced' would be:
--- charsInBalanced open close anyChar
-
--- Auxiliary functions for romanNumeral:
-
-lowercaseRomanDigits :: [Char]
-lowercaseRomanDigits = ['i','v','x','l','c','d','m']
-
-uppercaseRomanDigits :: [Char]
-uppercaseRomanDigits = map toUpper lowercaseRomanDigits
-
--- | Parses a roman numeral (uppercase or lowercase), returns number.
-romanNumeral :: Stream s m Char => Bool                  -- ^ Uppercase if true
-             -> ParserT s st m Int
-romanNumeral upperCase = do
-    let romanDigits = if upperCase
-                         then uppercaseRomanDigits
-                         else lowercaseRomanDigits
-    lookAhead $ oneOf romanDigits
-    let [one, five, ten, fifty, hundred, fivehundred, thousand] =
-          map char romanDigits
-    thousands <- ((1000 *) . length) <$> many thousand
-    ninehundreds <- option 0 $ try $ hundred >> thousand >> return 900
-    fivehundreds <- ((500 *) . length) <$> many fivehundred
-    fourhundreds <- option 0 $ try $ hundred >> fivehundred >> return 400
-    hundreds <- ((100 *) . length) <$> many hundred
-    nineties <- option 0 $ try $ ten >> hundred >> return 90
-    fifties <- ((50 *) . length) <$> many fifty
-    forties <- option 0 $ try $ ten >> fifty >> return 40
-    tens <- ((10 *) . length) <$> many ten
-    nines <- option 0 $ try $ one >> ten >> return 9
-    fives <- ((5 *) . length) <$> many five
-    fours <- option 0 $ try $ one >> five >> return 4
-    ones <- length <$> many one
-    let total = thousands + ninehundreds + fivehundreds + fourhundreds +
-                hundreds + nineties + fifties + forties + tens + nines +
-                fives + fours + ones
-    if total == 0
-       then fail "not a roman numeral"
-       else return total
-
--- Parsers for email addresses and URIs
-
--- | Parses an email address; returns original and corresponding
--- escaped mailto: URI.
-emailAddress :: Stream s m Char => ParserT s st m (String, String)
-emailAddress = try $ toResult <$> mailbox <*> (char '@' *> domain)
- where toResult mbox dom = let full = fromEntities $ mbox ++ '@':dom
-                           in  (full, escapeURI $ "mailto:" ++ full)
-       mailbox           = intercalate "." <$> (emailWord `sepby1` dot)
-       domain            = intercalate "." <$> (subdomain `sepby1` dot)
-       dot               = char '.'
-       subdomain         = many1 $ alphaNum <|> innerPunct
-       -- this excludes some valid email addresses, since an
-       -- email could contain e.g. '__', but gives better results
-       -- for our purposes, when combined with markdown parsing:
-       innerPunct        = try (satisfy (\c -> isEmailPunct c || c == '@')
-                                 <* notFollowedBy space
-                                 <* notFollowedBy (satisfy isPunctuation))
-       -- technically an email address could begin with a symbol,
-       -- but allowing this creates too many problems.
-       -- See e.g. https://github.com/jgm/pandoc/issues/2940
-       emailWord         = do x <- satisfy isAlphaNum
-                              xs <- many (satisfy isEmailChar)
-                              return (x:xs)
-       isEmailChar c     = isAlphaNum c || isEmailPunct c
-       isEmailPunct c    = c `elem` "!\"#$%&'*+-/=?^_{|}~;"
-       -- note: sepBy1 from parsec consumes input when sep
-       -- succeeds and p fails, so we use this variant here.
-       sepby1 p sep      = (:) <$> p <*> many (try $ sep >> p)
-
-
-uriScheme :: Stream s m Char => ParserT s st m String
-uriScheme = oneOfStringsCI (Set.toList schemes)
-
--- | Parses a URI. Returns pair of original and URI-escaped version.
-uri :: Monad m => ParserT [Char] st m (String, String)
-uri = try $ do
-  scheme <- uriScheme
-  char ':'
-  -- Avoid parsing e.g. "**Notes:**" as a raw URI:
-  notFollowedBy (oneOf "*_]")
-  -- We allow sentence punctuation except at the end, since
-  -- we don't want the trailing '.' in 'http://google.com.' We want to allow
-  -- http://en.wikipedia.org/wiki/State_of_emergency_(disambiguation)
-  -- as a URL, while NOT picking up the closing paren in
-  -- (http://wikipedia.org). So we include balanced parens in the URL.
-  let isWordChar c = isAlphaNum c || c `elem` "#$%*+/@\\_-&="
-  let wordChar = satisfy isWordChar
-  let percentEscaped = try $ char '%' >> skipMany1 (satisfy isHexDigit)
-  let entity = () <$ characterReference
-  let punct = skipMany1 (char ',')
-          <|> () <$ satisfy (\c -> not (isSpace c) && c /= '<' && c /= '>')
-  let uriChunk =  skipMany1 wordChar
-              <|> percentEscaped
-              <|> entity
-              <|> (try $ punct >>
-                    lookAhead (void (satisfy isWordChar) <|> percentEscaped))
-  str <- snd <$> withRaw (skipMany1 ( () <$
-                                         (enclosed (char '(') (char ')') uriChunk
-                                         <|> enclosed (char '{') (char '}') uriChunk
-                                         <|> enclosed (char '[') (char ']') uriChunk)
-                                         <|> uriChunk))
-  str' <- option str $ char '/' >> return (str ++ "/")
-  let uri' = scheme ++ ":" ++ fromEntities str'
-  return (uri', escapeURI uri')
-
-mathInlineWith :: Stream s m Char  => String -> String -> ParserT s st m String
-mathInlineWith op cl = try $ do
-  string op
-  when (op == "$") $ notFollowedBy space
-  words' <- many1Till (count 1 (noneOf " \t\n\\")
-                   <|> (char '\\' >>
-                           -- This next clause is needed because \text{..} can
-                           -- contain $, \(\), etc.
-                           (try (string "text" >>
-                                 (("\\text" ++) <$> inBalancedBraces 0 ""))
-                            <|>  (\c -> ['\\',c]) <$> anyChar))
-                   <|> do (blankline <* notFollowedBy' blankline) <|>
-                             (oneOf " \t" <* skipMany (oneOf " \t"))
-                          notFollowedBy (char '$')
-                          return " "
-                    ) (try $ string cl)
-  notFollowedBy digit  -- to prevent capture of $5
-  return $ trim $ concat words'
- where
-  inBalancedBraces :: Stream s m Char => Int -> String -> ParserT s st m String
-  inBalancedBraces 0 "" = do
-    c <- anyChar
-    if c == '{'
-       then inBalancedBraces 1 "{"
-       else mzero
-  inBalancedBraces 0 s = return $ reverse s
-  inBalancedBraces numOpen ('\\':xs) = do
-    c <- anyChar
-    inBalancedBraces numOpen (c:'\\':xs)
-  inBalancedBraces numOpen xs = do
-    c <- anyChar
-    case c of
-         '}' -> inBalancedBraces (numOpen - 1) (c:xs)
-         '{' -> inBalancedBraces (numOpen + 1) (c:xs)
-         _   -> inBalancedBraces numOpen (c:xs)
-
-mathDisplayWith :: Stream s m Char => String -> String -> ParserT s st m String
-mathDisplayWith op cl = try $ do
-  string op
-  many1Till (noneOf "\n" <|> (newline <* notFollowedBy' blankline)) (try $ string cl)
-
-mathDisplay :: (HasReaderOptions st, Stream s m Char)
-            => ParserT s st m String
-mathDisplay =
-      (guardEnabled Ext_tex_math_dollars >> mathDisplayWith "$$" "$$")
-  <|> (guardEnabled Ext_tex_math_single_backslash >>
-       mathDisplayWith "\\[" "\\]")
-  <|> (guardEnabled Ext_tex_math_double_backslash >>
-       mathDisplayWith "\\\\[" "\\\\]")
-
-mathInline :: (HasReaderOptions st , Stream s m Char)
-           => ParserT s st m String
-mathInline =
-      (guardEnabled Ext_tex_math_dollars >> mathInlineWith "$" "$")
-  <|> (guardEnabled Ext_tex_math_single_backslash >>
-       mathInlineWith "\\(" "\\)")
-  <|> (guardEnabled Ext_tex_math_double_backslash >>
-       mathInlineWith "\\\\(" "\\\\)")
-
--- | Applies a parser, returns tuple of its results and its horizontal
--- displacement (the difference between the source column at the end
--- and the source column at the beginning). Vertical displacement
--- (source row) is ignored.
-withHorizDisplacement :: Stream s m Char
-                      => ParserT s st m a  -- ^ Parser to apply
-                      -> ParserT s st m (a, Int) -- ^ (result, displacement)
-withHorizDisplacement parser = do
-  pos1 <- getPosition
-  result <- parser
-  pos2 <- getPosition
-  return (result, sourceColumn pos2 - sourceColumn pos1)
-
--- | Applies a parser and returns the raw string that was parsed,
--- along with the value produced by the parser.
-withRaw :: Monad m
-        => ParsecT [Char] st m a
-        -> ParsecT [Char] st m (a, [Char])
-withRaw parser = do
-  pos1 <- getPosition
-  inp <- getInput
-  result <- parser
-  pos2 <- getPosition
-  let (l1,c1) = (sourceLine pos1, sourceColumn pos1)
-  let (l2,c2) = (sourceLine pos2, sourceColumn pos2)
-  let inplines = take ((l2 - l1) + 1) $ lines inp
-  let raw = case inplines of
-                []  -> ""
-                [l] -> take (c2 - c1) l
-                ls  -> unlines (init ls) ++ take (c2 - 1) (last ls)
-  return (result, raw)
-
--- | Parses backslash, then applies character parser.
-escaped :: Stream s m Char
-        => ParserT s st m Char  -- ^ Parser for character to escape
-        -> ParserT s st m Char
-escaped parser = try $ char '\\' >> parser
-
--- | Parse character entity.
-characterReference :: Stream s m Char => ParserT s st m Char
-characterReference = try $ do
-  char '&'
-  ent <- many1Till nonspaceChar (char ';')
-  let ent' = case ent of
-                  '#':'X':xs -> '#':'x':xs  -- workaround tagsoup bug
-                  '#':_      -> ent
-                  _          -> ent ++ ";"
-  case lookupEntity ent' of
-       Just (c : _) -> return c
-       _            -> fail "entity not found"
-
--- | Parses an uppercase roman numeral and returns (UpperRoman, number).
-upperRoman :: Stream s m Char => ParserT s st m (ListNumberStyle, Int)
-upperRoman = do
-  num <- romanNumeral True
-  return (UpperRoman, num)
-
--- | Parses a lowercase roman numeral and returns (LowerRoman, number).
-lowerRoman :: Stream s m Char => ParserT s st m (ListNumberStyle, Int)
-lowerRoman = do
-  num <- romanNumeral False
-  return (LowerRoman, num)
-
--- | Parses a decimal numeral and returns (Decimal, number).
-decimal :: Stream s m Char => ParserT s st m (ListNumberStyle, Int)
-decimal = do
-  num <- many1 digit
-  return (Decimal, read num)
-
--- | Parses a '@' and optional label and
--- returns (DefaultStyle, [next example number]).  The next
--- example number is incremented in parser state, and the label
--- (if present) is added to the label table.
-exampleNum :: Stream s m Char
-           => ParserT s ParserState m (ListNumberStyle, Int)
-exampleNum = do
-  char '@'
-  lab <- many (alphaNum <|> satisfy (\c -> c == '_' || c == '-'))
-  st <- getState
-  let num = stateNextExample st
-  let newlabels = if null lab
-                     then stateExamples st
-                     else M.insert lab num $ stateExamples st
-  updateState $ \s -> s{ stateNextExample = num + 1
-                       , stateExamples    = newlabels }
-  return (Example, num)
-
--- | Parses a '#' returns (DefaultStyle, 1).
-defaultNum :: Stream s m Char => ParserT s st m (ListNumberStyle, Int)
-defaultNum = do
-  char '#'
-  return (DefaultStyle, 1)
-
--- | Parses a lowercase letter and returns (LowerAlpha, number).
-lowerAlpha :: Stream s m Char => ParserT s st m (ListNumberStyle, Int)
-lowerAlpha = do
-  ch <- oneOf ['a'..'z']
-  return (LowerAlpha, ord ch - ord 'a' + 1)
-
--- | Parses an uppercase letter and returns (UpperAlpha, number).
-upperAlpha :: Stream s m Char => ParserT s st m (ListNumberStyle, Int)
-upperAlpha = do
-  ch <- oneOf ['A'..'Z']
-  return (UpperAlpha, ord ch - ord 'A' + 1)
-
--- | Parses a roman numeral i or I
-romanOne :: Stream s m Char => ParserT s st m (ListNumberStyle, Int)
-romanOne = (char 'i' >> return (LowerRoman, 1)) <|>
-           (char 'I' >> return (UpperRoman, 1))
-
--- | Parses an ordered list marker and returns list attributes.
-anyOrderedListMarker :: Stream s m Char => ParserT s ParserState m ListAttributes
-anyOrderedListMarker = choice $
-  [delimParser numParser | delimParser <- [inPeriod, inOneParen, inTwoParens],
-                           numParser <- [decimal, exampleNum, defaultNum, romanOne,
-                           lowerAlpha, lowerRoman, upperAlpha, upperRoman]]
-
--- | Parses a list number (num) followed by a period, returns list attributes.
-inPeriod :: Stream s m Char
-         => ParserT s st m (ListNumberStyle, Int)
-         -> ParserT s st m ListAttributes
-inPeriod num = try $ do
-  (style, start) <- num
-  char '.'
-  let delim = if style == DefaultStyle
-                 then DefaultDelim
-                 else Period
-  return (start, style, delim)
-
--- | Parses a list number (num) followed by a paren, returns list attributes.
-inOneParen :: Stream s m Char
-           => ParserT s st m (ListNumberStyle, Int)
-           -> ParserT s st m ListAttributes
-inOneParen num = try $ do
-  (style, start) <- num
-  char ')'
-  return (start, style, OneParen)
-
--- | Parses a list number (num) enclosed in parens, returns list attributes.
-inTwoParens :: Stream s m Char
-            => ParserT s st m (ListNumberStyle, Int)
-            -> ParserT s st m ListAttributes
-inTwoParens num = try $ do
-  char '('
-  (style, start) <- num
-  char ')'
-  return (start, style, TwoParens)
-
--- | Parses an ordered list marker with a given style and delimiter,
--- returns number.
-orderedListMarker :: Stream s m Char
-                  => ListNumberStyle
-                  -> ListNumberDelim
-                  -> ParserT s ParserState m Int
-orderedListMarker style delim = do
-  let num = defaultNum <|>  -- # can continue any kind of list
-            case style of
-               DefaultStyle -> decimal
-               Example      -> exampleNum
-               Decimal      -> decimal
-               UpperRoman   -> upperRoman
-               LowerRoman   -> lowerRoman
-               UpperAlpha   -> upperAlpha
-               LowerAlpha   -> lowerAlpha
-  let context = case delim of
-               DefaultDelim -> inPeriod
-               Period       -> inPeriod
-               OneParen     -> inOneParen
-               TwoParens    -> inTwoParens
-  (start, _, _) <- context num
-  return start
-
--- | Parses a character reference and returns a Str element.
-charRef :: Stream s m Char => ParserT s st m Inline
-charRef = do
-  c <- characterReference
-  return $ Str [c]
-
-lineBlockLine :: Monad m => ParserT [Char] st m String
-lineBlockLine = try $ do
-  char '|'
-  char ' '
-  white <- many (spaceChar >> return '\160')
-  notFollowedBy newline
-  line <- anyLine
-  continuations <- many (try $ char ' ' >> anyLine)
-  return $ white ++ unwords (line : continuations)
-
-blankLineBlockLine :: Stream s m Char => ParserT s st m Char
-blankLineBlockLine = try (char '|' >> blankline)
-
--- | Parses an RST-style line block and returns a list of strings.
-lineBlockLines :: Monad m => ParserT [Char] st m [String]
-lineBlockLines = try $ do
-  lines' <- many1 (lineBlockLine <|> ((:[]) <$> blankLineBlockLine))
-  skipMany blankline
-  return lines'
-
--- | Parse a table using 'headerParser', 'rowParser',
--- 'lineParser', and 'footerParser'.
-tableWith :: (Stream s m Char, HasReaderOptions st,
-              Functor mf, Applicative mf, Monad mf)
-          => ParserT s st m (mf [Blocks], [Alignment], [Int])
-          -> ([Int] -> ParserT s st m (mf [Blocks]))
-          -> ParserT s st m sep
-          -> ParserT s st m end
-          -> ParserT s st m (mf Blocks)
-tableWith headerParser rowParser lineParser footerParser = try $ do
-  (aligns, widths, heads, rows) <- tableWith' headerParser rowParser
-                                                lineParser footerParser
-  return $ B.table mempty (zip aligns widths) <$> heads <*> rows
-
-type TableComponents mf = ([Alignment], [Double], mf [Blocks], mf [[Blocks]])
-
-tableWith' :: (Stream s m Char, HasReaderOptions st,
-               Functor mf, Applicative mf, Monad mf)
-           => ParserT s st m (mf [Blocks], [Alignment], [Int])
-           -> ([Int] -> ParserT s st m (mf [Blocks]))
-           -> ParserT s st m sep
-           -> ParserT s st m end
-           -> ParserT s st m (TableComponents mf)
-tableWith' headerParser rowParser lineParser footerParser = try $ do
-    (heads, aligns, indices) <- headerParser
-    lines' <- sequence <$> rowParser indices `sepEndBy1` lineParser
-    footerParser
-    numColumns <- getOption readerColumns
-    let widths = if null indices
-                    then replicate (length aligns) 0.0
-                    else widthsFromIndices numColumns indices
-    return (aligns, widths, heads, lines')
-
--- Calculate relative widths of table columns, based on indices
-widthsFromIndices :: Int      -- Number of columns on terminal
-                  -> [Int]    -- Indices
-                  -> [Double] -- Fractional relative sizes of columns
-widthsFromIndices _ [] = []
-widthsFromIndices numColumns' indices =
-  let numColumns = max numColumns' (if null indices then 0 else last indices)
-      lengths' = zipWith (-) indices (0:indices)
-      lengths  = reverse $
-                 case reverse lengths' of
-                      []       -> []
-                      [x]      -> [x]
-                      -- compensate for the fact that intercolumn
-                      -- spaces are counted in widths of all columns
-                      -- but the last...
-                      (x:y:zs) -> if x < y && y - x <= 2
-                                     then y:y:zs
-                                     else x:y:zs
-      totLength = sum lengths
-      quotient = if totLength > numColumns
-                   then fromIntegral totLength
-                   else fromIntegral numColumns
-      fracs = map (\l -> (fromIntegral l) / quotient) lengths in
-  tail fracs
-
----
-
--- Parse a grid table:  starts with row of '-' on top, then header
--- (which may be grid), then the rows,
--- which may be grid, separated by blank lines, and
--- ending with a footer (dashed line followed by blank line).
-gridTableWith :: (Monad m, HasReaderOptions st,
-                  Functor mf, Applicative mf, Monad mf)
-              => ParserT [Char] st m (mf Blocks)  -- ^ Block list parser
-              -> Bool                             -- ^ Headerless table
-              -> ParserT [Char] st m (mf Blocks)
-gridTableWith blocks headless =
-  tableWith (gridTableHeader headless blocks) (gridTableRow blocks)
-            (gridTableSep '-') gridTableFooter
-
-gridTableWith' :: (Monad m, HasReaderOptions st,
-                   Functor mf, Applicative mf, Monad mf)
-               => ParserT [Char] st m (mf Blocks)  -- ^ Block list parser
-               -> Bool                             -- ^ Headerless table
-               -> ParserT [Char] st m (TableComponents mf)
-gridTableWith' blocks headless =
-  tableWith' (gridTableHeader headless blocks) (gridTableRow blocks)
-             (gridTableSep '-') gridTableFooter
-
-gridTableSplitLine :: [Int] -> String -> [String]
-gridTableSplitLine indices line = map removeFinalBar $ tail $
-  splitStringByIndices (init indices) $ trimr line
-
-gridPart :: Stream s m Char => Char -> ParserT s st m ((Int, Int), Alignment)
-gridPart ch = do
-  leftColon <- option False (True <$ char ':')
-  dashes <- many1 (char ch)
-  rightColon <- option False (True <$ char ':')
-  char '+'
-  let lengthDashes = length dashes + (if leftColon then 1 else 0) +
-                       (if rightColon then 1 else 0)
-  let alignment = case (leftColon, rightColon) of
-                       (True, True)   -> AlignCenter
-                       (True, False)  -> AlignLeft
-                       (False, True)  -> AlignRight
-                       (False, False) -> AlignDefault
-  return ((lengthDashes, lengthDashes + 1), alignment)
-
-gridDashedLines :: Stream s m Char => Char -> ParserT s st m [((Int, Int), Alignment)]
-gridDashedLines ch = try $ char '+' >> many1 (gridPart ch) <* blankline
-
-removeFinalBar :: String -> String
-removeFinalBar =
-  reverse . dropWhile (`elem` " \t") . dropWhile (=='|') . reverse
-
--- | Separator between rows of grid table.
-gridTableSep :: Stream s m Char => Char -> ParserT s st m Char
-gridTableSep ch = try $ gridDashedLines ch >> return '\n'
-
--- | Parse header for a grid table.
-gridTableHeader :: (Monad m, Functor mf, Applicative mf, Monad mf)
-                => Bool -- ^ Headerless table
-                -> ParserT [Char] st m (mf Blocks)
-                -> ParserT [Char] st m (mf [Blocks], [Alignment], [Int])
-gridTableHeader headless blocks = try $ do
-  optional blanklines
-  dashes <- gridDashedLines '-'
-  rawContent  <- if headless
-                    then return $ repeat ""
-                    else many1
-                         (notFollowedBy (gridTableSep '=') >> char '|' >>
-                           many1Till anyChar newline)
-  underDashes <- if headless
-                    then return dashes
-                    else gridDashedLines '='
-  guard $ length dashes == length underDashes
-  let lines'   = map (snd . fst) underDashes
-  let indices  = scanl (+) 0 lines'
-  let aligns   = map snd underDashes
-  let rawHeads = if headless
-                    then replicate (length underDashes) ""
-                    else map (unlines . map trim) $ transpose
-                       $ map (gridTableSplitLine indices) rawContent
-  heads <- fmap sequence $ mapM (parseFromString blocks . trim) rawHeads
-  return (heads, aligns, indices)
-
-gridTableRawLine :: Stream s m Char => [Int] -> ParserT s st m [String]
-gridTableRawLine indices = do
-  char '|'
-  line <- many1Till anyChar newline
-  return (gridTableSplitLine indices line)
-
--- | Parse row of grid table.
-gridTableRow :: (Monad m, Functor mf, Applicative mf, Monad mf)
-             => ParserT [Char] st m (mf Blocks)
-             -> [Int]
-             -> ParserT [Char] st m (mf [Blocks])
-gridTableRow blocks indices = do
-  colLines <- many1 (gridTableRawLine indices)
-  let cols = map ((++ "\n") . unlines . removeOneLeadingSpace) $
-               transpose colLines
-      compactifyCell bs = case compactify [bs] of
-                            []  -> mempty
-                            x:_ -> x
-  cells <- sequence <$> mapM (parseFromString blocks) cols
-  return $ fmap (map compactifyCell) cells
-
-removeOneLeadingSpace :: [String] -> [String]
-removeOneLeadingSpace xs =
-  if all startsWithSpace xs
-     then map (drop 1) xs
-     else xs
-   where startsWithSpace ""    = True
-         startsWithSpace (y:_) = y == ' '
-
--- | Parse footer for a grid table.
-gridTableFooter :: Stream s m Char => ParserT s st m [Char]
-gridTableFooter = blanklines
-
----
-
--- | Removes the ParsecT layer from the monad transformer stack
-readWithM :: Monad m
-          => ParserT [Char] st m a    -- ^ parser
-          -> st                       -- ^ initial state
-          -> String                   -- ^ input
-          -> m (Either PandocError a)
-readWithM parser state input =
-    mapLeft (PandocParsecError input) `liftM` runParserT parser state "source" input
-
-
--- | Parse a string with a given parser and state
-readWith :: Parser [Char] st a
-         -> st
-         -> String
-         -> Either PandocError a
-readWith p t inp = runIdentity $ readWithM p t inp
-
--- | Parse a string with @parser@ (for testing).
-testStringWith :: Show a
-               => ParserT [Char] ParserState Identity a
-               -> [Char]
-               -> IO ()
-testStringWith parser str = UTF8.putStrLn $ show $
-                            readWith parser defaultParserState str
-
--- | Parsing options.
-data ParserState = ParserState
-    { stateOptions           :: ReaderOptions, -- ^ User options
-      stateParserContext     :: ParserContext, -- ^ Inside list?
-      stateQuoteContext      :: QuoteContext,  -- ^ Inside quoted environment?
-      stateAllowLinks        :: Bool,          -- ^ Allow parsing of links
-      stateMaxNestingLevel   :: Int,           -- ^ Max # of nested Strong/Emph
-      stateLastStrPos        :: Maybe SourcePos, -- ^ Position after last str parsed
-      stateKeys              :: KeyTable,      -- ^ List of reference keys
-      stateHeaderKeys        :: KeyTable,      -- ^ List of implicit header ref keys
-      stateSubstitutions     :: SubstTable,    -- ^ List of substitution references
-      stateNotes             :: NoteTable,     -- ^ List of notes (raw bodies)
-      stateNotes'            :: NoteTable',    -- ^ List of notes (parsed bodies)
-      stateNoteRefs          :: Set.Set String, -- ^ List of note references used
-      stateMeta              :: Meta,          -- ^ Document metadata
-      stateMeta'             :: F Meta,        -- ^ Document metadata
-      stateCitations         :: M.Map String String, -- ^ RST-style citations
-      stateHeaderTable       :: [HeaderType],  -- ^ Ordered list of header types used
-      stateHeaders           :: M.Map Inlines String, -- ^ List of headers and ids (used for implicit ref links)
-      stateIdentifiers       :: Set.Set String, -- ^ Header identifiers used
-      stateNextExample       :: Int,           -- ^ Number of next example
-      stateExamples          :: M.Map String Int, -- ^ Map from example labels to numbers
-      stateMacros            :: M.Map Text Macro, -- ^ Table of macros defined so far
-      stateRstDefaultRole    :: String,        -- ^ Current rST default interpreted text role
-      stateRstCustomRoles    :: M.Map String (String, Maybe String, Attr), -- ^ Current rST custom text roles
-      -- Triple represents: 1) Base role, 2) Optional format (only for :raw:
-      -- roles), 3) Additional classes (rest of Attr is unused)).
-      stateCaption           :: Maybe Inlines, -- ^ Caption in current environment
-      stateInHtmlBlock       :: Maybe String,  -- ^ Tag type of HTML block being parsed
-      stateFencedDivLevel    :: Int,           -- ^ Depth of fenced div
-      stateContainers        :: [String],      -- ^ parent include files
-      stateLogMessages       :: [LogMessage],  -- ^ log messages
-      stateMarkdownAttribute :: Bool         -- ^ True if in markdown=1 context
-    }
-
-instance Default ParserState where
-  def = defaultParserState
-
-instance HasMeta ParserState where
-  setMeta field val st =
-    st{ stateMeta = setMeta field val $ stateMeta st }
-  deleteMeta field st =
-    st{ stateMeta = deleteMeta field $ stateMeta st }
-
-class HasReaderOptions st where
-  extractReaderOptions :: st -> ReaderOptions
-  getOption            :: (Stream s m t) => (ReaderOptions -> b) -> ParserT s st m b
-  -- default
-  getOption  f         = (f . extractReaderOptions) <$> getState
-
-instance HasReaderOptions ParserState where
-  extractReaderOptions = stateOptions
-
-class HasQuoteContext st m where
-  getQuoteContext :: (Stream s m t) => ParsecT s st m QuoteContext
-  withQuoteContext :: QuoteContext -> ParsecT s st m a -> ParsecT s st m a
-
-instance Monad m => HasQuoteContext ParserState m where
-  getQuoteContext = stateQuoteContext <$> getState
-  withQuoteContext context parser = do
-    oldState <- getState
-    let oldQuoteContext = stateQuoteContext oldState
-    setState oldState { stateQuoteContext = context }
-    result <- parser
-    newState <- getState
-    setState newState { stateQuoteContext = oldQuoteContext }
-    return result
-
-class HasHeaderMap st where
-  extractHeaderMap  :: st -> M.Map Inlines String
-  updateHeaderMap   :: (M.Map Inlines String -> M.Map Inlines String) ->
-                       st -> st
-
-instance HasHeaderMap ParserState where
-  extractHeaderMap     = stateHeaders
-  updateHeaderMap f st = st{ stateHeaders = f $ stateHeaders st }
-
-class HasIdentifierList st where
-  extractIdentifierList  :: st -> Set.Set String
-  updateIdentifierList   :: (Set.Set String -> Set.Set String) -> st -> st
-
-instance HasIdentifierList ParserState where
-  extractIdentifierList     = stateIdentifiers
-  updateIdentifierList f st = st{ stateIdentifiers = f $ stateIdentifiers st }
-
-class HasMacros st where
-  extractMacros         :: st -> M.Map Text Macro
-  updateMacros          :: (M.Map Text Macro -> M.Map Text Macro) -> st -> st
-
-instance HasMacros ParserState where
-  extractMacros        = stateMacros
-  updateMacros f st    = st{ stateMacros = f $ stateMacros st }
-
-class HasLastStrPosition st where
-  setLastStrPos  :: SourcePos -> st -> st
-  getLastStrPos  :: st -> Maybe SourcePos
-
-instance HasLastStrPosition ParserState where
-  setLastStrPos pos st = st{ stateLastStrPos = Just pos }
-  getLastStrPos st     = stateLastStrPos st
-
-class HasLogMessages st where
-  addLogMessage :: LogMessage -> st -> st
-  getLogMessages :: st -> [LogMessage]
-
-instance HasLogMessages ParserState where
-  addLogMessage msg st = st{ stateLogMessages = msg : stateLogMessages st }
-  getLogMessages st = reverse $ stateLogMessages st
-
-class HasIncludeFiles st where
-  getIncludeFiles :: st -> [String]
-  addIncludeFile :: String -> st -> st
-  dropLatestIncludeFile :: st -> st
-
-instance HasIncludeFiles ParserState where
-  getIncludeFiles = stateContainers
-  addIncludeFile f s = s{ stateContainers = f : stateContainers s }
-  dropLatestIncludeFile s = s { stateContainers = drop 1 $ stateContainers s }
-
-defaultParserState :: ParserState
-defaultParserState =
-    ParserState { stateOptions         = def,
-                  stateParserContext   = NullState,
-                  stateQuoteContext    = NoQuote,
-                  stateAllowLinks      = True,
-                  stateMaxNestingLevel = 6,
-                  stateLastStrPos      = Nothing,
-                  stateKeys            = M.empty,
-                  stateHeaderKeys      = M.empty,
-                  stateSubstitutions   = M.empty,
-                  stateNotes           = [],
-                  stateNotes'          = M.empty,
-                  stateNoteRefs        = Set.empty,
-                  stateMeta            = nullMeta,
-                  stateMeta'           = return nullMeta,
-                  stateCitations       = M.empty,
-                  stateHeaderTable     = [],
-                  stateHeaders         = M.empty,
-                  stateIdentifiers     = Set.empty,
-                  stateNextExample     = 1,
-                  stateExamples        = M.empty,
-                  stateMacros          = M.empty,
-                  stateRstDefaultRole  = "title-reference",
-                  stateRstCustomRoles  = M.empty,
-                  stateCaption         = Nothing,
-                  stateInHtmlBlock     = Nothing,
-                  stateFencedDivLevel  = 0,
-                  stateContainers      = [],
-                  stateLogMessages     = [],
-                  stateMarkdownAttribute = False
-                  }
-
--- | Add a log message.
-logMessage :: (Stream s m a, HasLogMessages st)
-           => LogMessage -> ParserT s st m ()
-logMessage msg = updateState (addLogMessage msg)
-
--- | Report all the accumulated log messages, according to verbosity level.
-reportLogMessages :: (PandocMonad m, HasLogMessages st) => ParserT s st m ()
-reportLogMessages = do
-  msgs <- getLogMessages <$> getState
-  mapM_ report msgs
-
--- | Succeed only if the extension is enabled.
-guardEnabled :: (Stream s m a,  HasReaderOptions st) => Extension -> ParserT s st m ()
-guardEnabled ext = getOption readerExtensions >>= guard . extensionEnabled ext
-
--- | Succeed only if the extension is disabled.
-guardDisabled :: (Stream s m a, HasReaderOptions st) => Extension -> ParserT s st m ()
-guardDisabled ext = getOption readerExtensions >>= guard . not . extensionEnabled ext
-
--- | Update the position on which the last string ended.
-updateLastStrPos :: (Stream s m a, HasLastStrPosition st) => ParserT s st m ()
-updateLastStrPos = getPosition >>= updateState . setLastStrPos
-
--- | Whether we are right after the end of a string.
-notAfterString :: (Stream s m a, HasLastStrPosition st) => ParserT s st m Bool
-notAfterString = do
-  pos <- getPosition
-  st  <- getState
-  return $ getLastStrPos st /= Just pos
-
-data HeaderType
-    = SingleHeader Char  -- ^ Single line of characters underneath
-    | DoubleHeader Char  -- ^ Lines of characters above and below
-    deriving (Eq, Show)
-
-data ParserContext
-    = ListItemState   -- ^ Used when running parser on list item contents
-    | NullState       -- ^ Default state
-    deriving (Eq, Show)
-
-data QuoteContext
-    = InSingleQuote   -- ^ Used when parsing inside single quotes
-    | InDoubleQuote   -- ^ Used when parsing inside double quotes
-    | NoQuote         -- ^ Used when not parsing inside quotes
-    deriving (Eq, Show)
-
-type NoteTable = [(String, String)]
-
-type NoteTable' = M.Map String (SourcePos, F Blocks)
--- used in markdown reader
-
-newtype Key = Key String deriving (Show, Read, Eq, Ord)
-
-toKey :: String -> Key
-toKey = Key . map toLower . unwords . words . unbracket
-  where unbracket ('[':xs) | "]" `isSuffixOf` xs = take (length xs - 1) xs
-        unbracket xs       = xs
-
-type KeyTable = M.Map Key (Target, Attr)
-
-type SubstTable = M.Map Key Inlines
-
---  | Add header to the list of headers in state, together
---  with its associated identifier.  If the identifier is null
---  and the auto_identifers extension is set, generate a new
---  unique identifier, and update the list of identifiers
---  in state.  Issue a warning if an explicit identifier
---  is encountered that duplicates an earlier identifier
---  (explict or automatically generated).
-registerHeader :: (Stream s m a, HasReaderOptions st,
-                    HasHeaderMap st, HasLogMessages st, HasIdentifierList st)
-               => Attr -> Inlines -> ParserT s st m Attr
-registerHeader (ident,classes,kvs) header' = do
-  ids <- extractIdentifierList <$> getState
-  exts <- getOption readerExtensions
-  let insert' = M.insertWith (\_new old -> old)
-  if null ident && Ext_auto_identifiers `extensionEnabled` exts
-     then do
-       let id' = uniqueIdent (B.toList header') ids
-       let id'' = if Ext_ascii_identifiers `extensionEnabled` exts
-                     then mapMaybe toAsciiChar id'
-                     else id'
-       updateState $ updateIdentifierList $ Set.insert id'
-       updateState $ updateIdentifierList $ Set.insert id''
-       updateState $ updateHeaderMap $ insert' header' id'
-       return (id'',classes,kvs)
-     else do
-        unless (null ident) $ do
-          when (ident `Set.member` ids) $ do
-            pos <- getPosition
-            logMessage $ DuplicateIdentifier ident pos
-          updateState $ updateIdentifierList $ Set.insert ident
-          updateState $ updateHeaderMap $ insert' header' ident
-        return (ident,classes,kvs)
-
-smartPunctuation :: (HasReaderOptions st, HasLastStrPosition st, HasQuoteContext st m, Stream s m Char)
-                 => ParserT s st m Inlines
-                 -> ParserT s st m Inlines
-smartPunctuation inlineParser = do
-  guardEnabled Ext_smart
-  choice [ quoted inlineParser, apostrophe, dash, ellipses ]
-
-apostrophe :: Stream s m Char => ParserT s st m Inlines
-apostrophe = (char '\'' <|> char '\8217') >> return (B.str "\x2019")
-
-quoted :: (HasLastStrPosition st, HasQuoteContext st m, Stream s m Char)
-       => ParserT s st m Inlines
-       -> ParserT s st m Inlines
-quoted inlineParser = doubleQuoted inlineParser <|> singleQuoted inlineParser
-
-singleQuoted :: (HasLastStrPosition st, HasQuoteContext st m, Stream s m Char)
-             => ParserT s st m Inlines
-             -> ParserT s st m Inlines
-singleQuoted inlineParser = try $ do
-  singleQuoteStart
-  withQuoteContext InSingleQuote $ many1Till inlineParser singleQuoteEnd >>=
-    return . B.singleQuoted . mconcat
-
-doubleQuoted :: (HasQuoteContext st m, Stream s m Char)
-             => ParserT s st m Inlines
-             -> ParserT s st m Inlines
-doubleQuoted inlineParser = try $ do
-  doubleQuoteStart
-  withQuoteContext InDoubleQuote $ manyTill inlineParser doubleQuoteEnd >>=
-    return . B.doubleQuoted . mconcat
-
-failIfInQuoteContext :: (HasQuoteContext st m, Stream s m t)
-                     => QuoteContext
-                     -> ParserT s st m ()
-failIfInQuoteContext context = do
-  context' <- getQuoteContext
-  if context' == context
-     then fail "already inside quotes"
-     else return ()
-
-charOrRef :: Stream s m Char => String -> ParserT s st m Char
-charOrRef cs =
-  oneOf cs <|> try (do c <- characterReference
-                       guard (c `elem` cs)
-                       return c)
-
-singleQuoteStart :: (HasLastStrPosition st, HasQuoteContext st m, Stream s m Char)
-                 => ParserT s st m ()
-singleQuoteStart = do
-  failIfInQuoteContext InSingleQuote
-  -- single quote start can't be right after str
-  guard =<< notAfterString
-  () <$ charOrRef "'\8216\145"
-
-singleQuoteEnd :: Stream s m Char
-               => ParserT s st m ()
-singleQuoteEnd = try $ do
-  charOrRef "'\8217\146"
-  notFollowedBy alphaNum
-
-doubleQuoteStart :: (HasQuoteContext st m, Stream s m Char)
-                 => ParserT s st m ()
-doubleQuoteStart = do
-  failIfInQuoteContext InDoubleQuote
-  try $ do charOrRef "\"\8220\147"
-           notFollowedBy . satisfy $ flip elem [' ', '\t', '\n']
-
-doubleQuoteEnd :: Stream s m Char
-               => ParserT s st m ()
-doubleQuoteEnd = void (charOrRef "\"\8221\148")
-
-ellipses :: Stream s m Char
-         => ParserT s st m Inlines
-ellipses = try (string "..." >> return (B.str "\8230"))
-
-dash :: (HasReaderOptions st, Stream s m Char)
-     => ParserT s st m Inlines
-dash = try $ do
-  oldDashes <- extensionEnabled Ext_old_dashes <$> getOption readerExtensions
-  if oldDashes
-     then do
-       char '-'
-       (char '-' >> return (B.str "\8212"))
-         <|> (lookAhead digit >> return (B.str "\8211"))
-     else do
-       string "--"
-       (char '-' >> return (B.str "\8212"))
-         <|> return (B.str "\8211")
-
--- This is used to prevent exponential blowups for things like:
--- a**a*a**a*a**a*a**a*a**a*a**a*a**
-nested :: Stream s m a
-       => ParserT s ParserState m a
-       -> ParserT s ParserState m a
-nested p = do
-  nestlevel <- stateMaxNestingLevel <$>  getState
-  guard $ nestlevel > 0
-  updateState $ \st -> st{ stateMaxNestingLevel = stateMaxNestingLevel st - 1 }
-  res <- p
-  updateState $ \st -> st{ stateMaxNestingLevel = nestlevel }
-  return res
-
-citeKey :: (Stream s m Char, HasLastStrPosition st)
-        => ParserT s st m (Bool, String)
-citeKey = try $ do
-  guard =<< notAfterString
-  suppress_author <- option False (char '-' *> return True)
-  char '@'
-  firstChar <- alphaNum <|> char '_' <|> char '*' -- @* for wildcard in nocite
-  let regchar = satisfy (\c -> isAlphaNum c || c == '_')
-  let internal p = try $ p <* lookAhead regchar
-  rest <- many $ regchar <|> internal (oneOf ":.#$%&-+?<>~/") <|>
-                 try (oneOf ":/" <* lookAhead (char '/'))
-  let key = firstChar:rest
-  return (suppress_author, key)
-
-
-token :: (Stream s m t)
-      => (t -> String)
-      -> (t -> SourcePos)
-      -> (t -> Maybe a)
-      -> ParsecT s st m a
-token pp pos match = tokenPrim pp (\_ t _ -> pos t) match
-
-infixr 5 <+?>
-(<+?>) :: (Monoid a) => ParserT s st m a -> ParserT s st m a -> ParserT s st m a
-a <+?> b = a >>= flip fmap (try b <|> return mempty) . (<>)
-
-extractIdClass :: Attr -> Attr
-extractIdClass (ident, cls, kvs) = (ident', cls', kvs')
-  where
-    ident' = case lookup "id" kvs of
-               Just v  -> v
-               Nothing -> ident
-    cls'   = case lookup "class" kvs of
-               Just cl -> words cl
-               Nothing -> cls
-    kvs'  = filter (\(k,_) -> k /= "id" || k /= "class") kvs
-
-insertIncludedFile' :: (PandocMonad m, HasIncludeFiles st,
-                        Functor mf, Applicative mf, Monad mf)
-                    => ParserT [a] st m (mf Blocks)
-                    -> (String -> [a])
-                    -> [FilePath] -> FilePath
-                    -> ParserT [a] st m (mf Blocks)
-insertIncludedFile' blocks totoks dirs f = do
-  oldPos <- getPosition
-  oldInput <- getInput
-  containers <- getIncludeFiles <$> getState
-  when (f `elem` containers) $
-    throwError $ PandocParseError $ "Include file loop at " ++ show oldPos
-  updateState $ addIncludeFile f
-  mbcontents <- readFileFromDirs dirs f
-  contents <- case mbcontents of
-                   Just s -> return s
-                   Nothing -> do
-                     report $ CouldNotLoadIncludeFile f oldPos
-                     return ""
-  setPosition $ newPos f 1 1
-  setInput $ totoks contents
-  bs <- blocks
-  setInput oldInput
-  setPosition oldPos
-  updateState dropLatestIncludeFile
-  return bs
-
--- | Parse content of include file as blocks. Circular includes result in an
--- @PandocParseError@.
-insertIncludedFile :: (PandocMonad m, HasIncludeFiles st)
-                   => ParserT [a] st m Blocks
-                   -> (String -> [a])
-                   -> [FilePath] -> FilePath
-                   -> ParserT [a] st m Blocks
-insertIncludedFile blocks totoks dirs f =
-  runIdentity <$> insertIncludedFile' (Identity <$> blocks) totoks dirs f
-
--- | Parse content of include file as future blocks. Circular includes result in
--- an @PandocParseError@.
-insertIncludedFileF :: (PandocMonad m, HasIncludeFiles st)
-                    => ParserT String st m (Future st Blocks)
-                    -> [FilePath] -> FilePath
-                    -> ParserT String st m (Future st Blocks)
-insertIncludedFileF p = insertIncludedFile' p id
+{- |
+   Module      : Text.Pandoc.Parsing
+   Copyright   : Copyright (C) 2006-2024 John MacFarlane
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : John MacFarlane <jgm@berkeley.edu>
+   Stability   : alpha
+   Portability : portable
+
+A utility library with parsers used in pandoc readers.
+-}
+
+module Text.Pandoc.Parsing ( module Text.Pandoc.Sources,
+                             countChar,
+                             textStr,
+                             anyLine,
+                             anyLineNewline,
+                             indentWith,
+                             manyChar,
+                             many1Char,
+                             manyTillChar,
+                             many1TillChar,
+                             many1Till,
+                             manyUntil,
+                             manyUntilChar,
+                             sepBy1',
+                             notFollowedBy',
+                             oneOfStrings,
+                             oneOfStringsCI,
+                             spaceChar,
+                             nonspaceChar,
+                             skipSpaces,
+                             blankline,
+                             blanklines,
+                             gobbleSpaces,
+                             gobbleAtMostSpaces,
+                             enclosed,
+                             stringAnyCase,
+                             parseFromString,
+                             parseFromString',
+                             lineClump,
+                             charsInBalanced,
+                             romanNumeral,
+                             emailAddress,
+                             uri,
+                             mathInline,
+                             mathDisplay,
+                             withHorizDisplacement,
+                             withRaw,
+                             fromParsecError,
+                             escaped,
+                             characterReference,
+                             upperRoman,
+                             lowerRoman,
+                             decimal,
+                             lowerAlpha,
+                             upperAlpha,
+                             anyOrderedListMarker,
+                             orderedListMarker,
+                             charRef,
+                             lineBlockLines,
+                             tableWith,
+                             tableWith',
+                             tableWithSpans,
+                             tableWithSpans',
+                             widthsFromIndices,
+                             gridTableWith,
+                             gridTableWith',
+                             TableComponents (..),
+                             TableNormalization (..),
+                             toTableComponents,
+                             toTableComponents',
+                             toTableComponentsWithSpans,
+                             toTableComponentsWithSpans',
+                             singleRowSpans,
+                             singleColumnSpans,
+                             readWith,
+                             readWithM,
+                             testStringWith,
+                             guardEnabled,
+                             guardDisabled,
+                             updateLastStrPos,
+                             notAfterString,
+                             logMessage,
+                             reportLogMessages,
+                             ParserState (..),
+                             HasReaderOptions (..),
+                             HasIdentifierList (..),
+                             HasMacros (..),
+                             HasLogMessages (..),
+                             HasLastStrPosition (..),
+                             HasIncludeFiles (..),
+                             defaultParserState,
+                             HeaderType (..),
+                             ParserContext (..),
+                             QuoteContext (..),
+                             HasQuoteContext (..),
+                             NoteTable,
+                             NoteTable',
+                             KeyTable,
+                             SubstTable,
+                             Key (..),
+                             toKey,
+                             registerHeader,
+                             smartPunctuation,
+                             singleQuoteStart,
+                             singleQuoteEnd,
+                             doubleQuoteStart,
+                             doubleQuoteEnd,
+                             apostrophe,
+                             doubleCloseQuote,
+                             ellipses,
+                             dash,
+                             citeKey,
+                             Parsec,
+                             ParsecT,
+                             Future(..),
+                             runF,
+                             askF,
+                             asksF,
+                             returnF,
+                             trimInlinesF,
+                             token,
+                             (<+?>),
+                             extractIdClass,
+                             insertIncludedFile,
+                             -- * Re-exports from Text.Parsec
+                             Stream(..),
+                             runParser,
+                             runParserT,
+                             parse,
+                             tokenPrim,
+                             anyToken,
+                             getInput,
+                             setInput,
+                             unexpected,
+                             skipMany,
+                             skipMany1,
+                             count,
+                             eof,
+                             lookAhead,
+                             notFollowedBy,
+                             many,
+                             many1,
+                             manyTill,
+                             (<|>),
+                             (<?>),
+                             choice,
+                             try,
+                             sepBy,
+                             sepBy1,
+                             sepEndBy,
+                             sepEndBy1,
+                             endBy,
+                             endBy1,
+                             option,
+                             optional,
+                             optionMaybe,
+                             getState,
+                             setState,
+                             updateState,
+                             SourcePos,
+                             SourceName,
+                             updatePosString,
+                             getPosition,
+                             setPosition,
+                             sourceName,
+                             setSourceName,
+                             sourceColumn,
+                             sourceLine,
+                             setSourceColumn,
+                             setSourceLine,
+                             incSourceColumn,
+                             incSourceLine,
+                             newPos,
+                             initialPos,
+                             Line,
+                             Column,
+                             ParseError,
+                             errorMessages,
+                             messageString
+                             )
+where
+
+import Text.Pandoc.Sources
+import Text.Parsec
+    ( Parsec,
+      ParsecT,
+      SourcePos,
+      SourceName,
+      setSourceName,
+      Column,
+      Line,
+      incSourceLine,
+      incSourceColumn,
+      setSourceLine,
+      setSourceColumn,
+      sourceLine,
+      sourceColumn,
+      sourceName,
+      setSourceName,
+      setPosition,
+      getPosition,
+      updateState,
+      setState,
+      getState,
+      optionMaybe,
+      optional,
+      option,
+      endBy1,
+      endBy,
+      sepEndBy1,
+      sepEndBy,
+      sepBy1,
+      sepBy,
+      try,
+      choice,
+      (<?>),
+      (<|>),
+      manyTill,
+      many1,
+      many,
+      notFollowedBy,
+      lookAhead,
+      eof,
+      count,
+      skipMany1,
+      skipMany,
+      unexpected,
+      setInput,
+      getInput,
+      anyToken,
+      tokenPrim,
+      parse,
+      runParserT,
+      runParser,
+      ParseError,
+      Stream(..) )
+import Text.Parsec.Error (
+      errorMessages,
+      messageString )
+import Text.Parsec.Pos (initialPos, newPos, updatePosString)
+import Text.Pandoc.Parsing.Capabilities
+    ( guardDisabled,
+      guardEnabled,
+      logMessage,
+      notAfterString,
+      reportLogMessages,
+      updateLastStrPos,
+      HasIdentifierList(..),
+      HasIncludeFiles(..),
+      HasLastStrPosition(..),
+      HasLogMessages(..),
+      HasMacros(..),
+      HasQuoteContext(..),
+      HasReaderOptions(..),
+      QuoteContext(..) )
+import Text.Pandoc.Parsing.Citations ( citeKey )
+import Text.Pandoc.Parsing.General
+    ( readWithM,
+      (<+?>),
+      anyLine,
+      anyLineNewline,
+      blankline,
+      blanklines,
+      charRef,
+      characterReference,
+      charsInBalanced,
+      countChar,
+      emailAddress,
+      enclosed,
+      escaped,
+      extractIdClass,
+      gobbleAtMostSpaces,
+      gobbleSpaces,
+      indentWith,
+      insertIncludedFile,
+      lineBlockLines,
+      lineClump,
+      many1Char,
+      many1Till,
+      many1TillChar,
+      manyChar,
+      manyTillChar,
+      manyUntil,
+      manyUntilChar,
+      nonspaceChar,
+      notFollowedBy',
+      oneOfStrings,
+      oneOfStringsCI,
+      parseFromString,
+      parseFromString',
+      readWith,
+      registerHeader,
+      sepBy1',
+      skipSpaces,
+      spaceChar,
+      stringAnyCase,
+      testStringWith,
+      textStr,
+      token,
+      trimInlinesF,
+      uri,
+      withHorizDisplacement,
+      withRaw,
+      fromParsecError )
+import Text.Pandoc.Parsing.GridTable
+    ( gridTableWith,
+      gridTableWith',
+      tableWith,
+      tableWith',
+      tableWithSpans,
+      tableWithSpans',
+      toTableComponents,
+      toTableComponents',
+      toTableComponentsWithSpans,
+      toTableComponentsWithSpans',
+      singleRowSpans,
+      singleColumnSpans,
+      widthsFromIndices,
+      TableComponents(..),
+      TableNormalization(..) )
+import Text.Pandoc.Parsing.Lists
+    ( anyOrderedListMarker,
+      decimal,
+      lowerAlpha,
+      lowerRoman,
+      orderedListMarker,
+      romanNumeral,
+      upperAlpha,
+      upperRoman )
+import Text.Pandoc.Parsing.Math ( mathDisplay, mathInline )
+import Text.Pandoc.Parsing.Smart
+    ( apostrophe,
+      dash,
+      doubleCloseQuote,
+      doubleQuoteEnd,
+      doubleQuoteStart,
+      ellipses,
+      singleQuoteEnd,
+      singleQuoteStart,
+      smartPunctuation )
+import Text.Pandoc.Parsing.State
+    ( defaultParserState,
+      toKey,
+      HeaderType(..),
+      Key(..),
+      KeyTable,
+      NoteTable,
+      NoteTable',
+      ParserContext(..),
+      ParserState(..),
+      SubstTable )
+import Text.Pandoc.Parsing.Future
+    ( askF, asksF, returnF, runF, Future(..) )
diff --git a/src/Text/Pandoc/Parsing/Capabilities.hs b/src/Text/Pandoc/Parsing/Capabilities.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Parsing/Capabilities.hs
@@ -0,0 +1,137 @@
+{-# LANGUAGE MultiParamTypeClasses      #-}
+{- |
+   Module      : Text.Pandoc.Parsing
+   Copyright   : © 2006-2024 John MacFarlane
+   License     : GPL-2.0-or-later
+   Maintainer  : John MacFarlane <jgm@berkeley.edu>
+
+Parser state capabilities.
+-}
+module Text.Pandoc.Parsing.Capabilities
+  ( -- * Capabilities
+
+    -- ** Element identifiers
+    HasIdentifierList (..)
+
+    -- ** Include files
+  , HasIncludeFiles (..)
+
+    -- ** String/Word boundaries
+  , HasLastStrPosition (..)
+  , updateLastStrPos
+  , notAfterString
+
+    -- ** Logging
+  , HasLogMessages (..)
+  , logMessage
+  , reportLogMessages
+
+    -- ** Macros
+  , HasMacros (..)
+
+    -- ** Quote context
+  , QuoteContext (..)
+  , HasQuoteContext (..)
+  , failIfInQuoteContext
+
+    -- ** Reader options
+  , HasReaderOptions (..)
+  , guardEnabled
+  , guardDisabled
+  )
+where
+
+import Control.Monad (guard, when)
+import Data.Text (Text)
+import Text.Parsec (SourcePos, Stream, ParsecT,
+                     getPosition, getState, updateState)
+import Text.Pandoc.Class.PandocMonad (PandocMonad, report)
+import Text.Pandoc.Logging (LogMessage)
+import Text.Pandoc.Options
+  ( Extension
+  , ReaderOptions(readerExtensions)
+  , extensionEnabled
+  )
+import Text.Pandoc.TeX (Macro)
+
+import qualified Data.Map as M
+import qualified Data.Set as Set
+
+class HasReaderOptions st where
+  extractReaderOptions :: st -> ReaderOptions
+  getOption            :: (Stream s m t) => (ReaderOptions -> b) -> ParsecT s st m b
+  -- default
+  getOption  f         = f . extractReaderOptions <$> getState
+
+class HasQuoteContext st m where
+  getQuoteContext :: (Stream s m t) => ParsecT s st m QuoteContext
+  withQuoteContext :: QuoteContext -> ParsecT s st m a -> ParsecT s st m a
+
+failIfInQuoteContext :: (HasQuoteContext st m, Stream s m t)
+                     => QuoteContext
+                     -> ParsecT s st m ()
+failIfInQuoteContext context = do
+  context' <- getQuoteContext
+  when (context' == context) $ Prelude.fail "already inside quotes"
+
+class HasIdentifierList st where
+  extractIdentifierList  :: st -> Set.Set Text
+  updateIdentifierList   :: (Set.Set Text -> Set.Set Text) -> st -> st
+
+class HasMacros st where
+  extractMacros          :: st -> M.Map Text Macro
+  updateMacros           :: (M.Map Text Macro -> M.Map Text Macro) -> st -> st
+
+class HasLastStrPosition st where
+  setLastStrPos  :: Maybe SourcePos -> st -> st
+  getLastStrPos  :: st -> Maybe SourcePos
+
+class HasLogMessages st where
+  addLogMessage :: LogMessage -> st -> st
+  getLogMessages :: st -> [LogMessage]
+
+class HasIncludeFiles st where
+  getIncludeFiles :: st -> [Text]
+  addIncludeFile :: Text -> st -> st
+  dropLatestIncludeFile :: st -> st
+
+-- | Add a log message.
+logMessage :: (Stream s m a, HasLogMessages st)
+           => LogMessage -> ParsecT s st m ()
+logMessage msg = updateState (addLogMessage msg)
+
+-- | Report all the accumulated log messages, according to verbosity level.
+reportLogMessages :: (PandocMonad m, HasLogMessages st) => ParsecT s st m ()
+reportLogMessages = do
+  msgs <- getLogMessages <$> getState
+  mapM_ report msgs
+
+-- | Succeed only if the extension is enabled.
+guardEnabled :: (Stream s m a,  HasReaderOptions st)
+             => Extension -> ParsecT s st m ()
+guardEnabled ext =
+  getOption readerExtensions >>= guard . extensionEnabled ext
+
+-- | Succeed only if the extension is disabled.
+guardDisabled :: (Stream s m a, HasReaderOptions st)
+              => Extension -> ParsecT s st m ()
+guardDisabled ext =
+  getOption readerExtensions >>= guard . not . extensionEnabled ext
+
+-- | Update the position on which the last string ended.
+updateLastStrPos :: (Stream s m a, HasLastStrPosition st)
+                 => ParsecT s st m ()
+updateLastStrPos = getPosition >>= updateState . setLastStrPos . Just
+
+-- | Whether we are right after the end of a string.
+notAfterString :: (Stream s m a, HasLastStrPosition st) => ParsecT s st m Bool
+notAfterString = do
+  pos <- getPosition
+  st  <- getState
+  return $ getLastStrPos st /= Just pos
+
+data QuoteContext
+    = InSingleQuote   -- ^ Used when parsing inside single quotes
+    | InDoubleQuote   -- ^ Used when parsing inside double quotes
+    | NoQuote         -- ^ Used when not parsing inside quotes
+    deriving (Eq, Show)
diff --git a/src/Text/Pandoc/Parsing/Citations.hs b/src/Text/Pandoc/Parsing/Citations.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Parsing/Citations.hs
@@ -0,0 +1,57 @@
+{-# LANGUAGE FlexibleContexts           #-}
+{-# LANGUAGE OverloadedStrings          #-}
+{- |
+Module      : Text.Pandoc.Parsing.Citations
+Copyright   : © 2006-2024 John MacFarlane
+License     : GPL-2.0-or-later
+Maintainer  : John MacFarlane <jgm@berkeley.edu>
+
+Citation parsing.
+-}
+
+module Text.Pandoc.Parsing.Citations
+  ( citeKey
+  )
+where
+
+import Control.Monad (guard, MonadPlus(mzero))
+import Data.Char (isAlphaNum , isSpace)
+import Data.Text (Text)
+import Text.Pandoc.Sources
+import Text.Parsec
+  ( (<|>)
+  , Stream(..)
+  , ParsecT
+  , lookAhead
+  , many
+  , option
+  , try
+  )
+import Text.Pandoc.Parsing.Capabilities (HasLastStrPosition, notAfterString)
+import Text.Pandoc.Parsing.General
+
+import qualified Data.Text as T
+
+citeKey :: (Stream s m Char, UpdateSourcePos s Char, HasLastStrPosition st)
+        => Bool -- ^ If True, allow expanded @{..} syntax.
+        -> ParsecT s st m (Bool, Text)
+citeKey allowBraced = try $ do
+  guard =<< notAfterString
+  suppress_author <- option False (True <$ char '-')
+  char '@'
+  key <- simpleCiteIdentifier
+        <|> if allowBraced
+               then charsInBalanced '{' '}'
+                     (T.singleton <$> (satisfy (not . isSpace)))
+               else mzero
+  return (suppress_author, key)
+
+simpleCiteIdentifier :: (Stream s m Char, UpdateSourcePos s Char)
+                      => ParsecT s st m Text
+simpleCiteIdentifier = do
+  firstChar <- alphaNum <|> char '_' <|> char '*' -- @* for wildcard in nocite
+  let regchar = satisfy (\c -> isAlphaNum c || c == '_')
+  let internal p = try $ p <* lookAhead regchar
+  rest <- many $ regchar <|> internal (oneOf ":.#$%&-+?<>~/") <|>
+                 try (oneOf ":/" <* lookAhead (char '/'))
+  return $ T.pack $ firstChar:rest
diff --git a/src/Text/Pandoc/Parsing/Future.hs b/src/Text/Pandoc/Parsing/Future.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Parsing/Future.hs
@@ -0,0 +1,49 @@
+{-# LANGUAGE GeneralizedNewtypeDeriving #-}
+{- |
+   Module      : Text.Pandoc.Parsing.Future
+   Copyright   : Copyright (C) 2006-2024 John MacFarlane
+   License     : GPL-2.0-or-later
+   Maintainer  : John MacFarlane <jgm@berkeley.edu>
+
+Future type for parsing.
+-}
+
+module Text.Pandoc.Parsing.Future
+  ( Future (..)
+  , runF
+  , askF
+  , asksF
+  , returnF
+  )
+where
+
+import Prelude hiding (Applicative(..))
+import Control.Applicative (Applicative(..))
+import Control.Monad.Reader
+  ( asks, runReader, MonadReader(ask), Reader, ReaderT(ReaderT) )
+
+-- | Reader monad wrapping the parser state. This is used to possibly
+-- delay evaluation until all relevant information has been parsed and
+-- made available in the parser state.
+newtype Future s a = Future { runDelayed :: Reader s a }
+  deriving (Monad, Applicative, Functor)
+
+instance Semigroup a => Semigroup (Future s a) where
+  (<>) = liftA2 (<>)
+
+instance (Semigroup a, Monoid a) => Monoid (Future s a) where
+  mempty = return mempty
+  mappend = (<>)
+
+-- | Run a delayed action with the given state.
+runF :: Future s a -> s -> a
+runF = runReader . runDelayed
+
+askF :: Future s s
+askF = Future ask
+
+asksF :: (s -> a) -> Future s a
+asksF f = Future $ asks f
+
+returnF :: Monad m => a -> m (Future s a)
+returnF = return . return
diff --git a/src/Text/Pandoc/Parsing/General.hs b/src/Text/Pandoc/Parsing/General.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Parsing/General.hs
@@ -0,0 +1,763 @@
+{-# LANGUAGE BangPatterns               #-}
+{-# LANGUAGE FlexibleContexts           #-}
+{-# LANGUAGE OverloadedStrings          #-}
+{- |
+Module      : Text.Pandoc.Parsing.General
+Copyright   : © 2006-2024 John MacFarlane
+License     : GPL-2.0-or-later
+Maintainer  : John MacFarlane <jgm@berkeley.edu>
+
+Parser combinators for pandoc format readers.
+-}
+
+module Text.Pandoc.Parsing.General
+  ( (<+?>)
+  , anyLine
+  , anyLineNewline
+  , blankline
+  , blanklines
+  , charRef
+  , characterReference
+  , charsInBalanced
+  , countChar
+  , emailAddress
+  , enclosed
+  , escaped
+  , extractIdClass
+  , gobbleAtMostSpaces
+  , gobbleSpaces
+  , indentWith
+  , insertIncludedFile
+  , isSpaceChar          -- not re-exported from T.P.Parsing
+  , lineBlockLines
+  , lineClump
+  , many1Char
+  , many1Till
+  , many1TillChar
+  , manyChar
+  , manyTillChar
+  , manyUntil
+  , manyUntilChar
+  , nonspaceChar
+  , notFollowedBy'
+  , oneOfStrings
+  , oneOfStringsCI
+  , parseFromString
+  , parseFromString'
+  , readWith
+  , readWithM
+  , registerHeader
+  , sepBy1'
+  , skipSpaces
+  , spaceChar
+  , stringAnyCase
+  , testStringWith
+  , textStr
+  , token
+  , trimInlinesF
+  , uri
+  , withHorizDisplacement
+  , withRaw
+  , fromParsecError
+  )
+where
+
+import Control.Monad
+  ( join
+  , liftM
+  , unless
+  , void
+  , when
+  , MonadPlus(mzero)
+  )
+import Control.Monad.Except ( MonadError(throwError) )
+import Control.Monad.Identity ( Identity(..) )
+import Data.Char
+  ( chr
+  , isAlphaNum
+  , isAscii
+  , isAsciiUpper
+  , isSpace
+  , ord
+  , toLower
+  , toUpper
+  )
+import Data.Functor (($>))
+import Data.List (intercalate, sortOn)
+import Data.Ord (Down(..))
+import Data.Maybe (fromMaybe)
+import Data.Text (Text)
+import qualified Data.Text.Lazy.Builder as TB
+import qualified Data.Text.Lazy as TL
+import Text.Pandoc.Asciify (toAsciiText)
+import Text.Pandoc.Builder (Attr, Inline(Str), Inlines, trimInlines)
+import Text.Pandoc.Class.PandocMonad (PandocMonad, readFileFromDirs, report)
+import Text.Pandoc.Logging
+  ( LogMessage(CouldNotLoadIncludeFile, DuplicateIdentifier) )
+import Text.Pandoc.Options
+  ( extensionEnabled
+  , Extension(Ext_auto_identifiers, Ext_ascii_identifiers)
+  , ReaderOptions(readerTabStop, readerExtensions) )
+import Text.Pandoc.Shared (tshow, uniqueIdent)
+import Text.Pandoc.URI (schemes, escapeURI)
+import Text.Pandoc.Sources
+import Text.Pandoc.XML (fromEntities, lookupEntity)
+import Text.Parsec
+  ( (<|>)
+  , Parsec
+  , ParsecT
+  , SourcePos
+  , sourceLine
+  , sourceColumn
+  , sourceName
+  , ParseError
+  , errorPos
+  , Stream(..)
+  , between
+  , choice
+  , count
+  , getInput
+  , getPosition
+  , getState
+  , lookAhead
+  , many
+  , many1
+  , manyTill
+  , notFollowedBy
+  , option
+  , runParserT
+  , setInput
+  , setPosition
+  , skipMany
+  , sourceColumn
+  , sourceName
+  , tokenPrim
+  , try
+  , unexpected
+  , updateState
+  )
+import Text.Parsec.Pos (initialPos, newPos)
+import Text.Pandoc.Error
+  ( PandocError(PandocParseError) )
+import Text.Pandoc.Parsing.Capabilities
+import Text.Pandoc.Parsing.State
+import Text.Pandoc.Parsing.Future (Future (..))
+import qualified Data.Set as Set
+import qualified Data.Text as T
+import qualified Text.Pandoc.Builder as B
+import qualified Text.Pandoc.UTF8 as UTF8 (putStrLn)
+import qualified Data.Bifunctor as Bifunctor
+
+-- | Remove whitespace from start and end; just like @'trimInlines'@,
+-- but lifted into the 'Future' type.
+trimInlinesF :: Future s Inlines -> Future s Inlines
+trimInlinesF = liftM trimInlines
+
+-- | Like @count@, but packs its result
+countChar :: (Stream s m Char, UpdateSourcePos s Char, Monad m)
+          => Int
+          -> ParsecT s st m Char
+          -> ParsecT s st m Text
+countChar n = fmap T.pack . count n
+
+-- | Like @string@, but uses @Text@.
+textStr :: (Stream s m Char, UpdateSourcePos s Char)
+        => Text -> ParsecT s u m Text
+textStr t = string (T.unpack t) $> t
+
+
+-- | Parse any line of text, returning the contents without the
+-- final newline.
+anyLine :: Monad m => ParsecT Sources st m Text
+anyLine = do
+  -- This is much faster than:
+  -- manyTill anyChar newline
+  inp <- getInput
+  case inp of
+    Sources [] -> mzero
+    Sources ((fp,t):inps) ->
+      -- we assume that lines don't span different input files
+      case T.break (=='\n') t of
+           (this, rest)
+             | T.null rest
+             , not (null inps) ->
+                -- line may span different input files, so do it
+                 -- character by character
+                 T.pack <$> manyTill anyChar newline
+             | otherwise -> do --  either end of inputs or newline in rest
+                 setInput $ Sources ((fp, rest):inps)
+                 char '\n' -- needed so parsec knows we won't match empty string
+                           -- and so source pos is updated
+                 return this
+
+-- | Parse any line, include the final newline in the output
+anyLineNewline :: Monad m => ParsecT Sources st m Text
+anyLineNewline = (<> "\n") <$> anyLine
+
+-- | Parse indent by specified number of spaces (or equiv. tabs)
+indentWith :: (Stream s m Char, UpdateSourcePos s Char)
+           => HasReaderOptions st
+           => Int -> ParsecT s st m Text
+indentWith num = do
+  tabStop <- getOption readerTabStop
+  if num < tabStop
+     then countChar num (char ' ')
+     else choice [ try (countChar num (char ' '))
+                 , try (char '\t' >> indentWith (num - tabStop)) ]
+
+-- | Like @many@, but packs its result.
+manyChar :: Stream s m t
+         => ParsecT s st m Char
+         -> ParsecT s st m Text
+manyChar = fmap T.pack . many
+
+-- | Like @many1@, but packs its result.
+many1Char :: Stream s m t
+          => ParsecT s st m Char
+          -> ParsecT s st m Text
+many1Char = fmap T.pack . many1
+
+-- | Like @manyTill@, but packs its result.
+manyTillChar :: Stream s m t
+             => ParsecT s st m Char
+             -> ParsecT s st m a
+             -> ParsecT s st m Text
+manyTillChar p = fmap T.pack . manyTill p
+
+-- | Like @manyTill@, but reads at least one item.
+many1Till :: (Show end, Stream s m t)
+          => ParsecT s st m a
+          -> ParsecT s st m end
+          -> ParsecT s st m [a]
+many1Till p end = do
+         notFollowedBy' end
+         first <- p
+         rest <- manyTill p end
+         return (first:rest)
+
+-- | Like @many1Till@, but packs its result
+many1TillChar :: (Show end, Stream s m t)
+              => ParsecT s st m Char
+              -> ParsecT s st m end
+              -> ParsecT s st m Text
+many1TillChar p = fmap T.pack . many1Till p
+
+-- | Like @manyTill@, but also returns the result of end parser.
+manyUntil :: ParsecT s u m a
+          -> ParsecT s u m b
+          -> ParsecT s u m ([a], b)
+manyUntil p end = scan
+  where scan =
+          (do e <- end
+              return ([], e)
+          ) <|>
+          (do x <- p
+              (xs, e) <- scan
+              return (x:xs, e))
+
+-- | Like @manyUntil@, but also packs its result.
+manyUntilChar :: ParsecT s u m Char
+              -> ParsecT s u m b
+              -> ParsecT s u m (Text, b)
+manyUntilChar p = fmap go . manyUntil p
+  where
+    go (x, y) = (T.pack x, y)
+
+-- | Like @sepBy1@ from Parsec,
+-- but does not fail if it @sep@ succeeds and @p@ fails.
+sepBy1' :: ParsecT s u m a
+        -> ParsecT s u m sep
+        -> ParsecT s u m [a]
+sepBy1' p sep = (:) <$> p <*> many (try $ sep >> p)
+
+-- | A more general form of @notFollowedBy@.  This one allows any
+-- type of parser to be specified, and succeeds only if that parser fails.
+-- It does not consume any input.
+notFollowedBy' :: (Show b, Stream s m a) => ParsecT s st m b -> ParsecT s st m ()
+notFollowedBy' p  = try $ join $  do  a <- try p
+                                      return (unexpected (show a))
+                                  <|>
+                                  return (return ())
+-- (This version due to Andrew Pimlott on the Haskell mailing list.)
+
+oneOfStrings' :: (Stream s m Char, UpdateSourcePos s Char)
+               => (Char -> Char -> Bool) -> [Text] -> ParsecT s st m Text
+oneOfStrings' _ [] = Prelude.fail "no strings to match"
+oneOfStrings' matches strs =
+  TL.toStrict . TB.toLazyText <$> try (go mempty strs)
+ where
+   go acc strs' = do
+     c <- anyChar
+     let strs'' = [t | Just (d, t) <- map T.uncons strs', matches c d]
+     let !acc' = acc <> TB.singleton c
+     case strs'' of
+       []  -> Prelude.fail "not found"
+       _   -> if any T.null strs''
+                 then option acc' (try (go acc' strs''))
+                 else go acc' strs''
+
+-- | Parses one of a list of strings.  If the list contains
+-- two strings one of which is a prefix of the other, the longer
+-- string will be matched if possible.
+oneOfStrings :: (Stream s m Char, UpdateSourcePos s Char)
+             => [Text] -> ParsecT s st m Text
+oneOfStrings = oneOfStrings' (==)
+
+-- | Parses one of a list of strings (tried in order), case insensitive.
+
+-- TODO: This will not be accurate with general Unicode (neither
+-- Text.toLower nor Text.toCaseFold can be implemented with a map)
+oneOfStringsCI :: (Stream s m Char, UpdateSourcePos s Char)
+               => [Text] -> ParsecT s st m Text
+oneOfStringsCI = oneOfStrings' ciMatch
+  where ciMatch x y = toLower' x == toLower' y
+        -- this optimizes toLower by checking common ASCII case
+        -- first, before calling the expensive unicode-aware
+        -- function:
+        toLower' c | isAsciiUpper c = chr (ord c + 32)
+                   | isAscii c = c
+                   | otherwise = toLower c
+
+-- | Parses a space or tab.
+spaceChar :: (Stream s m Char, UpdateSourcePos s Char)
+          => ParsecT s st m Char
+spaceChar = satisfy $ \c -> c == ' ' || c == '\t'
+
+-- | Parses a nonspace, nonnewline character.
+nonspaceChar :: (Stream s m Char, UpdateSourcePos s Char)
+             => ParsecT s st m Char
+nonspaceChar = satisfy (not . isSpaceChar)
+
+isSpaceChar :: Char -> Bool
+isSpaceChar ' '  = True
+isSpaceChar '\t' = True
+isSpaceChar '\n' = True
+isSpaceChar '\r' = True
+isSpaceChar _    = False
+
+-- | Skips zero or more spaces or tabs.
+skipSpaces :: (Stream s m Char, UpdateSourcePos s Char)
+           => ParsecT s st m ()
+skipSpaces = skipMany spaceChar
+
+-- | Skips zero or more spaces or tabs, then reads a newline.
+blankline :: (Stream s m Char, UpdateSourcePos s Char)
+          => ParsecT s st m Char
+blankline = try $ skipSpaces >> newline
+
+-- | Parses one or more blank lines and returns a string of newlines.
+blanklines :: (Stream s m Char, UpdateSourcePos s Char)
+           => ParsecT s st m Text
+blanklines = T.pack <$> many1 blankline
+
+-- | Gobble n spaces; if tabs are encountered, expand them
+-- and gobble some or all of their spaces, leaving the rest.
+gobbleSpaces :: (HasReaderOptions st, Monad m)
+             => Int -> ParsecT Sources st m ()
+gobbleSpaces 0 = return ()
+gobbleSpaces n
+  | n < 0     = error "gobbleSpaces called with negative number"
+  | otherwise = try $ do
+      char ' ' <|> eatOneSpaceOfTab
+      gobbleSpaces (n - 1)
+
+eatOneSpaceOfTab :: (HasReaderOptions st, Monad m) => ParsecT Sources st m Char
+eatOneSpaceOfTab = do
+  lookAhead (char '\t')
+  pos <- getPosition
+  tabstop <- getOption readerTabStop
+  -- replace the tab on the input stream with spaces
+  let numSpaces = tabstop - ((sourceColumn pos - 1) `mod` tabstop)
+  inp <- getInput
+  setInput $
+    case inp of
+      Sources [] -> error "eatOneSpaceOfTab - empty Sources list"
+      Sources ((fp,t):rest) ->
+        -- drop the tab and add spaces
+        Sources ((fp, T.replicate numSpaces " " <> T.drop 1 t):rest)
+  char ' '
+
+-- | Gobble up to n spaces; if tabs are encountered, expand them
+-- and gobble some or all of their spaces, leaving the rest.
+gobbleAtMostSpaces :: (HasReaderOptions st, Monad m)
+                   => Int -> ParsecT Sources st m Int
+gobbleAtMostSpaces 0 = return 0
+gobbleAtMostSpaces n
+  | n < 0     = error "gobbleAtMostSpaces called with negative number"
+  | otherwise = option 0 $ do
+      char ' ' <|> eatOneSpaceOfTab
+      (+ 1) <$> gobbleAtMostSpaces (n - 1)
+
+-- | Parses material enclosed between start and end parsers.
+enclosed :: (Show end, Stream s m Char, UpdateSourcePos s Char)
+         => ParsecT s st m t   -- ^ start parser
+         -> ParsecT s st m end  -- ^ end parser
+         -> ParsecT s st m a    -- ^ content parser (to be used repeatedly)
+         -> ParsecT s st m [a]
+enclosed start end parser = try $
+  start >> notFollowedBy space >> many1Till parser end
+
+-- | Parse string, case insensitive.
+stringAnyCase :: (Stream s m Char, UpdateSourcePos s Char)
+              => Text -> ParsecT s st m Text
+stringAnyCase t = TL.toStrict . TB.toLazyText <$> go (T.unpack t)
+  where
+    go [] = string "" $> mempty
+    go (x:xs) = do
+      c <- char (toUpper x) <|> char (toLower x)
+      rest <- go xs
+      pure $ TB.singleton c <> rest
+
+-- TODO rewrite by just adding to Sources stream?
+-- | Parse contents of 'str' using 'parser' and return result.
+parseFromString :: Monad m
+                => ParsecT Sources st m r
+                -> Text
+                -> ParsecT Sources st m r
+parseFromString parser str = do
+  oldPos <- getPosition
+  oldInput <- getInput
+  setInput $ toSources str
+  setPosition $ initialPos $ sourceName oldPos <> "_chunk"
+  result <- parser
+  setInput oldInput
+  setPosition oldPos
+  return result
+
+-- | Like 'parseFromString' but specialized for 'ParserState'.
+-- This resets 'stateLastStrPos', which is almost always what we want.
+parseFromString' :: (Monad m, HasLastStrPosition u)
+                 => ParsecT Sources u m a
+                 -> Text
+                 -> ParsecT Sources u m a
+parseFromString' parser str = do
+  oldLastStrPos <- getLastStrPos <$> getState
+  updateState $ setLastStrPos Nothing
+  res <- parseFromString parser str
+  updateState $ setLastStrPos oldLastStrPos
+  return res
+
+-- | Parse raw line block up to and including blank lines.
+lineClump :: Monad m => ParsecT Sources st m Text
+lineClump = blanklines
+          <|> (T.unlines <$> many1 (notFollowedBy blankline >> anyLine))
+
+-- | Parse a string of characters between an open character
+-- and a close character, including text between balanced
+-- pairs of open and close, which must be different. For example,
+-- @charsInBalanced '(' ')' (Data.Text.singleton <$> anyChar)@ will parse
+-- "(hello (there))" and return "hello (there)".
+charsInBalanced :: (Stream s m Char, UpdateSourcePos s Char)
+                => Char -> Char -> ParsecT s st m Text -> ParsecT s st m Text
+charsInBalanced open close parser = try $ do
+  char open
+  let isDelim c = c == open || c == close
+  raw <- many $ mconcat <$> many1 (notFollowedBy (satisfy isDelim) >> parser)
+             <|> (do res <- charsInBalanced open close parser
+                     return $ T.singleton open <> res <> T.singleton close)
+  char close
+  return $ mconcat raw
+
+-- Parsers for email addresses and URIs
+
+-- | Parses an email address; returns original and corresponding
+-- escaped mailto: URI.
+emailAddress :: (Stream s m Char, UpdateSourcePos s Char) => ParsecT s st m (Text, Text)
+emailAddress = try $ toResult <$> mailbox <*> (char '@' *> domain)
+ where toResult mbox dom = let full = fromEntities $ T.pack $ mbox ++ '@':dom
+                           in  (full, escapeURI $ "mailto:" <> full)
+       mailbox           = intercalate "." <$> (emailWord `sepBy1'` dot)
+       domain            = intercalate "." <$> (subdomain `sepBy1'` dot)
+       dot               = char '.'
+       subdomain         = many1 $ alphaNum <|> innerPunct (=='-')
+       -- this excludes some valid email addresses, since an
+       -- email could contain e.g. '__', but gives better results
+       -- for our purposes, when combined with markdown parsing:
+       innerPunct f      = try (satisfy f
+                                 <* notFollowedBy (satisfy (not . isAlphaNum)))
+       -- technically an email address could begin with a symbol,
+       -- but allowing this creates too many problems.
+       -- See e.g. https://github.com/jgm/pandoc/issues/2940
+       emailWord         = do x <- satisfy isAlphaNum
+                              xs <- many (satisfy isEmailChar)
+                              return (x:xs)
+       isEmailChar c     = isAlphaNum c || isEmailPunct c
+       isEmailPunct c    = c `Set.member` emailPunctChars
+
+emailPunctChars :: Set.Set Char
+emailPunctChars = Set.fromList "!\"#$%&'*+-/=?^_{|}~;"
+
+uriScheme :: (Stream s m Char, UpdateSourcePos s Char) => ParsecT s st m Text
+uriScheme = oneOfStringsCI (Set.toList schemes)
+
+-- | Parses a URI. Returns pair of original and URI-escaped version.
+uri :: (Stream s m Char, UpdateSourcePos s Char) => ParsecT s st m (Text, Text)
+uri = try $ do
+  scheme <- uriScheme
+  char ':'
+  -- Avoid parsing e.g. "**Notes:**" as a raw URI:
+  notFollowedBy $ satisfy (\c -> c == '*' || c == '_' || c == ']')
+  -- We allow sentence punctuation except at the end, since
+  -- we don't want the trailing '.' in 'http://google.com.' We want to allow
+  -- http://en.wikipedia.org/wiki/State_of_emergency_(disambiguation)
+  -- as a URL, while NOT picking up the closing paren in
+  -- (http://wikipedia.org). So we include balanced parens in the URL.
+  str <- T.concat <$> many1 (uriChunkBetween '(' ')'
+                        <|> uriChunkBetween '{' '}'
+                        <|> uriChunkBetween '[' ']'
+                        <|> T.pack <$> uriChunk)
+  str' <- option str $ char '/' >> return (str <> "/")
+  let uri' = scheme <> ":" <> fromEntities str'
+  return (uri', escapeURI uri')
+  where
+    isWordChar '#' = True
+    isWordChar '$' = True
+    isWordChar '%' = True
+    isWordChar '+' = True
+    isWordChar '/' = True
+    isWordChar '@' = True
+    isWordChar '\\' = True
+    isWordChar '_' = True
+    isWordChar '-' = True
+    isWordChar '&' = True
+    isWordChar '=' = True
+    isWordChar c   = isAlphaNum c
+
+    wordChar = satisfy isWordChar
+    percentEscaped = try $ (:) <$> char '%' <*> many1 hexDigit
+    entity = try $ T.unpack <$> characterReference
+    punct = try $ many1 (char ',') <|> fmap pure (satisfy (\c -> not (isSpace c) && c /= '<' && c /= '>'))
+    uriChunk = many1 wordChar
+           <|> percentEscaped
+           <|> entity
+           <|> try (punct <* lookAhead (void wordChar <|> void percentEscaped))
+    uriChunkBetween l r = try $ do chunk <- between (char l) (char r) uriChunk
+                                   return $ T.singleton l <> T.pack chunk <> T.singleton r
+
+-- | Applies a parser, returns tuple of its results and its horizontal
+-- displacement (the difference between the source column at the end
+-- and the source column at the beginning). Vertical displacement
+-- (source row) is ignored.
+withHorizDisplacement :: (Stream s m Char, UpdateSourcePos s Char)
+                      => ParsecT s st m a  -- ^ Parsec to apply
+                      -> ParsecT s st m (a, Int) -- ^ (result, displacement)
+withHorizDisplacement parser = do
+  pos1 <- getPosition
+  result <- parser
+  pos2 <- getPosition
+  return (result, sourceColumn pos2 - sourceColumn pos1)
+
+-- | Applies a parser and returns the raw string that was parsed,
+-- along with the value produced by the parser.
+withRaw :: Monad m
+        => ParsecT Sources st m a
+        -> ParsecT Sources st m (a, Text)
+withRaw parser = do
+  inps1 <- getInput
+  result <- parser
+  inps2 <- getInput
+  -- 'raw' is the difference between inps1 and inps2
+  return (result, sourcesDifference inps1 inps2)
+
+sourcesDifference :: Sources -> Sources -> Text
+sourcesDifference (Sources is1) (Sources is2) = go is1 is2
+ where
+   go inps1 inps2 =
+    case (inps1, inps2) of
+      ([], _) -> mempty
+      (_, []) -> mconcat $ map snd inps1
+      ((p1,t1):rest1, (p2, t2):rest2)
+        | p1 == p2
+        , t1 == t2  -> go rest1 rest2
+        | p1 == p2
+        , t1 /= t2  -> fromMaybe mempty $ T.stripSuffix t2 t1
+        | otherwise -> t1 <> go rest1 inps2
+
+-- | Parses backslash, then applies character parser.
+escaped :: (Stream s m Char, UpdateSourcePos s Char)
+        => ParsecT s st m Char  -- ^ Parsec for character to escape
+        -> ParsecT s st m Char
+escaped parser = try $ char '\\' >> parser
+
+-- | Parse character entity.
+characterReference :: (Stream s m Char, UpdateSourcePos s Char) => ParsecT s st m Text
+characterReference = try $ do
+  char '&'
+  ent <- many1TillChar nonspaceChar (char ';')
+  case lookupEntity (ent <> ";") of
+       Just t       -> return t
+       _            -> Prelude.fail "entity not found"
+
+-- | Parses a character reference and returns a Str element.
+charRef :: (Stream s m Char, UpdateSourcePos s Char) => ParsecT s st m Inline
+charRef = Str <$> characterReference
+
+lineBlockLine :: Monad m => ParsecT Sources st m Text
+lineBlockLine = try $ do
+  char '|'
+  char ' '
+  white <- T.pack <$> many (spaceChar >> return '\160')
+  notFollowedBy newline
+  line <- anyLine
+  continuations <- many (try $ char ' ' >> anyLine)
+  return $ white <> T.unwords (line : continuations)
+
+blankLineBlockLine :: (Stream s m Char, UpdateSourcePos s Char) => ParsecT s st m Char
+blankLineBlockLine = try (char '|' >> blankline)
+
+-- | Parses an RST-style line block and returns a list of strings.
+lineBlockLines :: Monad m => ParsecT Sources st m [Text]
+lineBlockLines = try $ do
+  lines' <- many1 (lineBlockLine <|> (T.singleton <$> blankLineBlockLine))
+  skipMany blankline
+  return lines'
+
+
+-- | Removes the ParsecT layer from the monad transformer stack
+readWithM :: (Monad m, ToSources t)
+          => ParsecT Sources st m a  -- ^ parser
+          -> st                      -- ^ initial state
+          -> t                       -- ^ input
+          -> m (Either PandocError a)
+readWithM parser state input =
+    Bifunctor.first (fromParsecError sources)
+      <$> runParserT parser state (initialSourceName sources) sources
+ where
+   sources = toSources input
+
+
+-- | Parse a string with a given parser and state
+readWith :: ToSources t
+         => Parsec Sources st a
+         -> st
+         -> t
+         -> Either PandocError a
+readWith p t inp = runIdentity $ readWithM p t inp
+
+-- | Parse a string with @parser@ (for testing).
+testStringWith :: Show a
+               => ParsecT Sources ParserState Identity a
+               -> Text
+               -> IO ()
+testStringWith parser str = UTF8.putStrLn $ tshow $
+                            readWith parser defaultParserState (toSources str)
+
+-- | Add header to the list of headers in state, together
+--  with its associated identifier.  If the identifier is null
+--  and the auto_identifiers extension is set, generate a new
+--  unique identifier, and update the list of identifiers
+--  in state.  Issue a warning if an explicit identifier
+--  is encountered that duplicates an earlier identifier
+--  (explicit or automatically generated).
+registerHeader :: (Stream s m a, HasReaderOptions st,
+                   HasLogMessages st, HasIdentifierList st)
+               => Attr -> Inlines -> ParsecT s st m Attr
+registerHeader (ident,classes,kvs) header' = do
+  ids <- extractIdentifierList <$> getState
+  exts <- getOption readerExtensions
+  if T.null ident && Ext_auto_identifiers `extensionEnabled` exts
+     then do
+       let id' = uniqueIdent exts (B.toList header') ids
+       let id'' = if Ext_ascii_identifiers `extensionEnabled` exts
+                     then toAsciiText id'
+                     else id'
+       updateState $ updateIdentifierList $ Set.insert id'
+       updateState $ updateIdentifierList $ Set.insert id''
+       return (id'',classes,kvs)
+     else do
+        unless (T.null ident) $ do
+          when (ident `Set.member` ids) $ do
+            pos <- getPosition
+            logMessage $ DuplicateIdentifier ident pos
+          updateState $ updateIdentifierList $ Set.insert ident
+        return (ident,classes,kvs)
+
+token :: (Stream s m t)
+      => (t -> Text)
+      -> (t -> SourcePos)
+      -> (t -> Maybe a)
+      -> ParsecT s st m a
+token pp pos match = tokenPrim (T.unpack . pp) (\_ t _ -> pos t) match
+
+infixr 5 <+?>
+(<+?>) :: (Monoid a) => ParsecT s st m a -> ParsecT s st m a -> ParsecT s st m a
+a <+?> b = a >>= flip fmap (try b <|> return mempty) . mappend
+
+extractIdClass :: Attr -> Attr
+extractIdClass (ident, cls, kvs) = (ident', cls', kvs')
+  where
+    ident' = fromMaybe ident (lookup "id" kvs)
+    cls'   = maybe cls T.words $ lookup "class" kvs
+    kvs'   = filter (\(k,_) -> k /= "id" && k /= "class") kvs
+
+insertIncludedFile :: (PandocMonad m, HasIncludeFiles st)
+                   => ParsecT a st m b -- ^ parser to apply
+                   -> (Text -> a) -- ^ convert Text to stream type
+                   -> [FilePath]  -- ^ search path (directories)
+                   -> FilePath    -- ^ path of file to include
+                   -> Maybe Int   -- ^ start line (negative counts from end)
+                   -> Maybe Int   -- ^ end line (negative counts from end)
+                   -> ParsecT a st m b
+insertIncludedFile parser toStream dirs f mbstartline mbendline = do
+  oldPos <- getPosition
+  oldInput <- getInput
+  containers <- getIncludeFiles <$> getState
+  when (T.pack f `elem` containers) $
+    throwError $ PandocParseError $ T.pack $ "Include file loop at " ++ show oldPos
+  updateState $ addIncludeFile $ T.pack f
+  mbcontents <- readFileFromDirs dirs f
+  contents <- case mbcontents of
+                   Just s -> return $ exciseLines mbstartline mbendline s
+                   Nothing -> do
+                     report $ CouldNotLoadIncludeFile (T.pack f) oldPos
+                     return ""
+  setInput $ toStream contents
+  setPosition $ newPos f (fromMaybe 1 mbstartline) 1
+  result <- parser
+  setInput oldInput
+  setPosition oldPos
+  updateState dropLatestIncludeFile
+  return result
+
+exciseLines :: Maybe Int -> Maybe Int -> Text -> Text
+exciseLines Nothing Nothing t = t
+exciseLines mbstartline mbendline t =
+  T.unlines $ take (endline' - (startline' - 1))
+            $ drop (startline' - 1) contentLines
+ where
+  contentLines = T.lines t
+  numLines = length contentLines
+  startline' = case mbstartline of
+                 Nothing -> 1
+                 Just x | x >= 0 -> x
+                        | otherwise -> numLines + x -- negative from end
+  endline' = case mbendline of
+                 Nothing -> numLines
+                 Just x | x >= 0 -> x
+                        | otherwise -> numLines + x -- negative from end
+
+fromParsecError :: Sources -> ParseError -> PandocError
+fromParsecError (Sources inputs) err' = PandocParseError msg
+ where
+  msg = "Error at " <> tshow  err' <> errorContext
+  errPos = errorPos err'
+  errLine = sourceLine errPos
+  errColumn = sourceColumn errPos
+  errFile = sourceName errPos
+  errorContext =
+    case sortOn (Down . sourceLine . fst)
+            [ (pos,t)
+              | (pos,t) <- inputs
+              , sourceName pos == errFile
+              , sourceLine pos <= errLine
+            ] of
+      []  -> ""
+      ((pos,txt):_) ->
+        let ls = T.lines txt <> [""]
+            ln = (errLine - sourceLine pos) + 1
+         in case drop (ln - 1) ls of
+               (l:_) | ln >= 1 ->
+                 T.concat ["\n", l
+                          ,"\n", T.replicate (errColumn - 1) " "
+                          ,"^"]
+               _ -> ""
diff --git a/src/Text/Pandoc/Parsing/GridTable.hs b/src/Text/Pandoc/Parsing/GridTable.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Parsing/GridTable.hs
@@ -0,0 +1,308 @@
+{-# LANGUAGE FlexibleContexts           #-}
+{-# LANGUAGE LambdaCase                 #-}
+{-# LANGUAGE OverloadedStrings          #-}
+{- |
+   Module      : Text.Pandoc.Parsing.GridTable
+   Copyright   : Copyright (C) 2006-2024 John MacFarlane
+   License     : GPL-2.0-or-later
+   Maintainer  : John MacFarlane <jgm@berkeley.edu>
+
+Shared parsers for plaintext tables.
+-}
+module Text.Pandoc.Parsing.GridTable
+  ( gridTableWith
+  , gridTableWith'
+  , tableWith
+  , tableWith'
+  , tableWithSpans
+  , tableWithSpans'
+  , widthsFromIndices
+    -- * Components of a plain-text table
+  , TableComponents (..)
+  , TableNormalization (..)
+  , toTableComponents
+  , toTableComponents'
+  , toTableComponentsWithSpans
+  , toTableComponentsWithSpans'
+  , singleRowSpans
+  , singleColumnSpans
+  )
+where
+
+import Data.Array (elems)
+import Data.Text (Text)
+import Safe (lastDef)
+import Text.Pandoc.Options (ReaderOptions (readerColumns))
+import Text.Pandoc.Builder (Blocks)
+import Text.Pandoc.Definition
+import Text.Pandoc.Parsing.Capabilities
+import Text.Pandoc.Parsing.General
+import Text.Pandoc.Sources
+import Text.Parsec (Stream (..), ParsecT, optional, sepEndBy1, try)
+
+import Data.Maybe (mapMaybe)
+import qualified Data.Text as T
+import qualified Text.GridTable as GT
+import qualified Text.Pandoc.Builder as B
+
+-- | Collection of components making up a Table block.
+data TableComponents = TableComponents
+  { tableAttr     :: Attr
+  , tableCaption  :: Caption
+  , tableColSpecs :: [ColSpec]
+  , tableHead     :: TableHead
+  , tableBodies   :: [TableBody]
+  , tableFoot     :: TableFoot
+  }
+
+-- | Creates a table block from the collection of table parts.
+tableFromComponents :: TableComponents -> Blocks
+tableFromComponents (TableComponents attr capt colspecs th tb tf) =
+  B.tableWith attr capt colspecs th tb tf
+
+-- | Bundles basic table components into a single value.
+toTableComponents :: [Alignment] -> [Double] -> [[Blocks]] -> [[Blocks]]
+                  -> TableComponents
+toTableComponents = toTableComponents' NoNormalization
+
+-- | Bundles basic table components into a single value, performing
+-- normalizations as necessary.
+toTableComponents' :: TableNormalization
+                   -> [Alignment] -> [Double] -> [[Blocks]] -> [[Blocks]]
+                   -> TableComponents
+toTableComponents' normalization aligns widths heads rows =
+  toTableComponentsWithSpans' normalization aligns widths (singleSpansBlocks heads) (singleSpansBlocks rows)
+
+-- | Bundles basic table components with span information into a single value.
+toTableComponentsWithSpans :: [Alignment] -> [Double] -> [[(Blocks, RowSpan, ColSpan)]] -> [[(Blocks, RowSpan, ColSpan)]]
+                           -> TableComponents
+toTableComponentsWithSpans = toTableComponentsWithSpans' NoNormalization
+
+-- | Bundles basic table components with span information into a single value,
+-- performing normalizations as necessary.
+toTableComponentsWithSpans' :: TableNormalization
+                            -> [Alignment] -> [Double] -> [[(Blocks, RowSpan, ColSpan)]] -> [[(Blocks, RowSpan, ColSpan)]]
+                            -> TableComponents
+toTableComponentsWithSpans' normalization aligns widths heads rows =
+  let th = TableHead nullAttr (mapMaybe (toHeaderRow normalization) heads)
+      tb = TableBody nullAttr 0 [] (map toRow rows)
+      tf = TableFoot nullAttr []
+      colspecs = toColSpecs aligns widths
+  in TableComponents nullAttr B.emptyCaption colspecs th [tb] tf
+
+-- | Combine a list of column alignments and column widths into a list
+-- of column specifiers. Both input lists should have the same length.
+toColSpecs :: [Alignment]   -- ^ column alignments
+           -> [Double]      -- ^ column widths
+           -> [ColSpec]
+toColSpecs aligns widths = zip aligns (map fromWidth widths')
+  where
+    fromWidth n
+      | n > 0     = ColWidth n
+      | otherwise = ColWidthDefault
+
+    -- renormalize widths if greater than 100%:
+    totalWidth = sum widths
+    widths' = if totalWidth < 1
+              then widths
+              else map (/ totalWidth) widths
+
+-- | Whether the table header should be normalized, i.e., whether an header row
+-- with only empty cells should be omitted.
+data TableNormalization
+  = NoNormalization
+  | NormalizeHeader
+
+--
+-- Grid Tables
+--
+
+-- | Parse a grid table: starts with row of '-' on top, then header
+-- (which may be grid), then the rows, which may be grid, separated by
+-- blank lines, and ending with a footer (dashed line followed by blank
+-- line).
+gridTableWith :: (Monad m, Monad mf, HasLastStrPosition st, HasReaderOptions st)
+              => ParsecT Sources st m (mf Blocks)  -- ^ Block list parser
+              -> ParsecT Sources st m (mf Blocks)
+gridTableWith blocks = fmap tableFromComponents <$>
+  gridTableWith' NoNormalization blocks
+
+-- | Like @'gridTableWith'@, but returns 'TableComponents' instead of a
+-- Table.
+gridTableWith' :: (Monad m, Monad mf,
+                   HasReaderOptions st, HasLastStrPosition st)
+               => TableNormalization
+               -> ParsecT Sources st m (mf Blocks) -- ^ Block list parser
+               -> ParsecT Sources st m (mf TableComponents)
+gridTableWith' normalization blocks = do
+  tbl <- GT.gridTable <* optional blanklines
+  let blkTbl = GT.mapCells
+               (\lns -> parseFromString' blocks
+                        . flip T.snoc '\n'  -- ensure proper block parsing
+                        . T.unlines
+                        . removeOneLeadingSpace
+                        $ map T.stripEnd lns)
+               tbl
+  let rows = GT.rows blkTbl
+  let toPandocCell (GT.Cell c (GT.RowSpan rs) (GT.ColSpan cs)) =
+        fmap (B.cell AlignDefault (B.RowSpan rs) (B.ColSpan cs) . plainify) <$> c
+  rows' <- mapM (mapM toPandocCell) rows
+  columns <- getOption readerColumns
+  let colspecs = zipWith (\cs w -> (convAlign $ fst cs, B.ColWidth w))
+                         (elems $ GT.arrayTableColSpecs tbl)
+                         (fractionalColumnWidths tbl columns)
+  let caption = B.emptyCaption
+  return $ do
+    rows'' <- mapM sequence rows'
+    let headLen = maybe 0 GT.fromRowIndex $ GT.arrayTableHead tbl
+    let (hRows, bRows') =
+          splitAt headLen (map (B.Row B.nullAttr) rows'')
+    let (bRows, fRows) =
+          case GT.arrayTableFoot tbl of
+            Just fIdx -> splitAt (GT.fromRowIndex fIdx - headLen - 1) bRows'
+            Nothing   -> (bRows', [])
+    let thead = B.TableHead B.nullAttr $ case (hRows, normalization) of
+          -- normalize header if necessary: remove header if it contains
+          -- only a single row in which all cells are empty.
+          ([hrow], NormalizeHeader) ->
+            let Row _attr cells = hrow
+                simple = \case
+                  Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1) [] ->
+                    True
+                  _ ->
+                    False
+            in [B.Row nullAttr cells | not (null cells) &&
+                                       not (all simple cells)]
+          _ -> hRows
+    let tfoot = B.TableFoot B.nullAttr fRows
+    let tbody = B.TableBody B.nullAttr 0 [] bRows
+    return $ TableComponents nullAttr caption colspecs thead [tbody] tfoot
+
+removeOneLeadingSpace :: [Text] -> [Text]
+removeOneLeadingSpace xs =
+  if all startsWithSpace xs
+     then map (T.drop 1) xs
+     else xs
+   where startsWithSpace t = case T.uncons t of
+           Nothing     -> True
+           Just (c, _) -> c == ' '
+
+plainify :: B.Blocks -> B.Blocks
+plainify blks = case B.toList blks of
+  [Para x] -> B.fromList [Plain x]
+  _        -> blks
+
+convAlign :: GT.Alignment -> B.Alignment
+convAlign GT.AlignLeft    = B.AlignLeft
+convAlign GT.AlignRight   = B.AlignRight
+convAlign GT.AlignCenter  = B.AlignCenter
+convAlign GT.AlignDefault = B.AlignDefault
+
+fractionalColumnWidths :: GT.ArrayTable a -> Int -> [Double]
+fractionalColumnWidths gt charColumns =
+  let widths = map ((+1) . snd) -- include width of separator
+               (elems $ GT.arrayTableColSpecs gt)
+      norm = fromIntegral $ max (sum widths + length widths - 2) charColumns
+  in map (\w -> fromIntegral w / norm) widths
+
+---
+
+-- | Parse a table using 'headerParser', 'rowParser',
+-- 'lineParser', and 'footerParser'.
+tableWith :: (Stream s m Char, UpdateSourcePos s Char,
+              HasReaderOptions st, Monad mf)
+          => ParsecT s st m (mf [[Blocks]], [Alignment], [Int]) -- ^ header parser
+          -> ([Int] -> ParsecT s st m (mf [Blocks]))  -- ^ row parser
+          -> ParsecT s st m sep                       -- ^ line parser
+          -> ParsecT s st m end                       -- ^ footer parser
+          -> ParsecT s st m (mf Blocks)
+tableWith hp rp lp fp = fmap tableFromComponents <$>
+  tableWith' NoNormalization hp rp lp fp
+
+tableWith' :: (Stream s m Char, UpdateSourcePos s Char,
+               HasReaderOptions st, Monad mf)
+           => TableNormalization
+           -> ParsecT s st m (mf [[Blocks]], [Alignment], [Int]) -- ^ header parser
+           -> ([Int] -> ParsecT s st m (mf [Blocks]))  -- ^ row parser
+           -> ParsecT s st m sep                       -- ^ line parser
+           -> ParsecT s st m end                       -- ^ footer parser
+           -> ParsecT s st m (mf TableComponents)
+tableWith' n11n headerParser rowParser lineParser footerParser =
+  tableWithSpans' n11n headerParser' rowParser' lineParser footerParser
+    where
+      headerParser' = fmap (\(heads, aligns, indices) -> (fmap singleSpansBlocks heads, aligns, indices)) headerParser
+      rowParser' indices = fmap (\row -> zip3 row (repeat 1) (repeat 1)) <$> rowParser indices
+
+tableWithSpans :: (Stream s m Char, UpdateSourcePos s Char,
+              HasReaderOptions st, Monad mf)
+               => ParsecT s st m (mf [[(Blocks, RowSpan, ColSpan)]], [Alignment], [Int]) -- ^ header parser
+               -> ([Int] -> ParsecT s st m (mf [(Blocks, RowSpan, ColSpan)]))  -- ^ row parser
+               -> ParsecT s st m sep                       -- ^ line parser
+               -> ParsecT s st m end                       -- ^ footer parser
+               -> ParsecT s st m (mf Blocks)
+tableWithSpans hp rp lp fp = fmap tableFromComponents <$>
+  tableWithSpans' NoNormalization hp rp lp fp
+
+tableWithSpans' :: (Stream s m Char, UpdateSourcePos s Char,
+               HasReaderOptions st, Monad mf)
+                => TableNormalization
+                -> ParsecT s st m (mf [[(Blocks, RowSpan, ColSpan)]], [Alignment], [Int]) -- ^ header parser
+                -> ([Int] -> ParsecT s st m (mf [(Blocks, RowSpan, ColSpan)]))  -- ^ row parser
+                -> ParsecT s st m sep                       -- ^ line parser
+                -> ParsecT s st m end                       -- ^ footer parser
+                -> ParsecT s st m (mf TableComponents)
+tableWithSpans' n11n headerParser rowParser lineParser footerParser = try $ do
+  (heads, aligns, indices) <- headerParser
+  lines' <- sequence <$> rowParser indices `sepEndBy1` lineParser
+  footerParser
+  numColumns <- getOption readerColumns
+  let widths = if null indices
+               then replicate (length aligns) 0.0
+               else widthsFromIndices numColumns indices
+  return $ toTableComponentsWithSpans' n11n aligns widths <$> heads <*> lines'
+
+toRow :: [(Blocks, RowSpan, ColSpan)] -> Row
+toRow =  Row nullAttr . map (\(blocks, rowSpan, columnSpan) -> B.cell AlignDefault rowSpan columnSpan blocks)
+
+toHeaderRow :: TableNormalization -> [(Blocks, RowSpan, ColSpan)] -> Maybe Row
+toHeaderRow = \case
+  NoNormalization -> \l -> if not (null l) then Just (toRow l) else Nothing
+  NormalizeHeader -> \l -> if not (all nullHeaderRow l) then Just (toRow l) else Nothing
+  where
+    nullHeaderRow (l, _, _) = null l
+
+-- | Calculate relative widths of table columns, based on indices
+widthsFromIndices :: Int      -- Number of columns on terminal
+                  -> [Int]    -- Indices
+                  -> [Double] -- Fractional relative sizes of columns
+widthsFromIndices _ [] = []
+widthsFromIndices numColumns' indices =
+  let numColumns = max numColumns' (lastDef 0 indices)
+      lengths' = zipWith (-) indices (0:indices)
+      lengths  = reverse $
+                 case reverse lengths' of
+                      []       -> []
+                      [x]      -> [x]
+                      -- compensate for the fact that intercolumn
+                      -- spaces are counted in widths of all columns
+                      -- but the last...
+                      (x:y:zs) -> if x < y && y - x <= 2
+                                     then y:y:zs
+                                     else x:y:zs
+      totLength = sum lengths
+      quotient = if totLength > numColumns
+                   then fromIntegral totLength
+                   else fromIntegral numColumns
+      fracs = map (\l -> fromIntegral l / quotient) lengths in
+  drop 1 fracs
+
+-- | List of lists of `RowSpan` of 1.
+singleRowSpans :: [[RowSpan]]
+singleRowSpans = repeat $ repeat 1
+
+-- | List of lists of `ColsSpan` of 1.
+singleColumnSpans :: [[ColSpan]]
+singleColumnSpans = repeat $ repeat 1
+
+singleSpansBlocks :: [[Blocks]] -> [[(Blocks, RowSpan, ColSpan)]]
+singleSpansBlocks blocks = zipWith3 zip3 blocks singleRowSpans singleColumnSpans
diff --git a/src/Text/Pandoc/Parsing/Lists.hs b/src/Text/Pandoc/Parsing/Lists.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Parsing/Lists.hs
@@ -0,0 +1,217 @@
+{-# LANGUAGE FlexibleContexts           #-}
+{-# LANGUAGE OverloadedStrings          #-}
+{- |
+Module      : Text.Pandoc.Parsing.Lists
+Copyright   : © 2006-2024 John MacFarlane
+License     : GPL-2.0-or-later
+Maintainer  : John MacFarlane <jgm@berkeley.edu>
+
+Parsers for list markers.
+-}
+
+module Text.Pandoc.Parsing.Lists
+  ( anyOrderedListMarker
+  , decimal
+  , lowerAlpha
+  , lowerRoman
+  , orderedListMarker
+  , romanNumeral
+  , upperAlpha
+  , upperRoman
+  )
+where
+
+import Data.Char
+  ( isAsciiUpper
+  , isAsciiLower
+  , ord
+  , toLower
+  )
+import Data.Maybe (fromMaybe)
+import Text.Pandoc.Definition
+  ( ListNumberDelim(..)
+  , ListAttributes
+  , ListNumberStyle(..)
+  )
+import Text.Pandoc.Shared (safeRead)
+import Text.Pandoc.Sources
+import Text.Parsec
+  ( (<|>)
+  , ParsecT
+  , Stream(..)
+  , choice
+  , getState
+  , lookAhead
+  , many
+  , many1
+  , option
+  , try
+  , updateState
+  )
+import Text.Pandoc.Parsing.State
+
+import qualified Data.Map as M
+import qualified Data.Text as T
+
+-- | Parses a roman numeral (uppercase or lowercase), returns number.
+romanNumeral :: (Stream s m Char, UpdateSourcePos s Char)
+             => Bool                  -- ^ Uppercase if true
+             -> ParsecT s st m Int
+romanNumeral upperCase = do
+    let rchar uc = char $ if upperCase then uc else toLower uc
+    let one         = rchar 'I'
+    let five        = rchar 'V'
+    let ten         = rchar 'X'
+    let fifty       = rchar 'L'
+    let hundred     = rchar 'C'
+    let fivehundred = rchar 'D'
+    let thousand    = rchar 'M'
+    lookAhead $ choice [one, five, ten, fifty, hundred, fivehundred, thousand]
+    thousands <- (1000 *) . length <$> many thousand
+    ninehundreds <- option 0 $ try $ hundred >> thousand >> return 900
+    fivehundreds <- option 0 $ 500 <$ fivehundred
+    fourhundreds <- option 0 $ try $ hundred >> fivehundred >> return 400
+    hundreds <- (100 *) . length <$> many hundred
+    nineties <- option 0 $ try $ ten >> hundred >> return 90
+    fifties <- option 0 (50 <$ fifty)
+    forties <- option 0 $ try $ ten >> fifty >> return 40
+    tens <- (10 *) . length <$> many ten
+    nines <- option 0 $ try $ one >> ten >> return 9
+    fives <- option 0 (5 <$ five)
+    fours <- option 0 $ try $ one >> five >> return 4
+    ones <- length <$> many one
+    let total = thousands + ninehundreds + fivehundreds + fourhundreds +
+                hundreds + nineties + fifties + forties + tens + nines +
+                fives + fours + ones
+    if total == 0
+       then Prelude.fail "not a roman numeral"
+       else return total
+
+-- | Parses an uppercase roman numeral and returns (UpperRoman, number).
+upperRoman :: (Stream s m Char, UpdateSourcePos s Char) => ParsecT s st m (ListNumberStyle, Int)
+upperRoman = do
+  num <- romanNumeral True
+  return (UpperRoman, num)
+
+-- | Parses a lowercase roman numeral and returns (LowerRoman, number).
+lowerRoman :: (Stream s m Char, UpdateSourcePos s Char) => ParsecT s st m (ListNumberStyle, Int)
+lowerRoman = do
+  num <- romanNumeral False
+  return (LowerRoman, num)
+
+-- | Parses a decimal numeral and returns (Decimal, number).
+decimal :: (Stream s m Char, UpdateSourcePos s Char) => ParsecT s st m (ListNumberStyle, Int)
+decimal = do
+  num <- many1 digit
+  return (Decimal, fromMaybe 1 $ safeRead $ T.pack num)
+
+-- | Parses a '@' and optional label and
+-- returns (DefaultStyle, [next example number]).  The next
+-- example number is incremented in parser state, and the label
+-- (if present) is added to the label table.
+exampleNum :: (Stream s m Char, UpdateSourcePos s Char)
+           => ParsecT s ParserState m (ListNumberStyle, Int)
+exampleNum = do
+  char '@'
+  lab <- T.pack . concat <$>
+                    many (many1 alphaNum <|>
+                          try (do c <- char '_' <|> char '-'
+                                  cs <- many1 alphaNum
+                                  return (c:cs)))
+  st <- getState
+  case M.lookup lab (stateExamples st) of
+    Nothing -> do -- new label
+      let num = stateNextExample st
+      let newlabels = if T.null lab
+                         then stateExamples st
+                         else M.insert lab num $ stateExamples st
+      updateState $ \s -> s{ stateNextExample = num + 1
+                           , stateExamples    = newlabels }
+      return (Example, num)
+    Just num -> -- reuse existing label
+      return (Example, num)
+
+-- | Parses a '#' returns (DefaultStyle, 1).
+defaultNum :: (Stream s m Char, UpdateSourcePos s Char) => ParsecT s st m (ListNumberStyle, Int)
+defaultNum = do
+  char '#'
+  return (DefaultStyle, 1)
+
+-- | Parses a lowercase letter and returns (LowerAlpha, number).
+lowerAlpha :: (Stream s m Char, UpdateSourcePos s Char) => ParsecT s st m (ListNumberStyle, Int)
+lowerAlpha = do
+  ch <- satisfy isAsciiLower
+  return (LowerAlpha, ord ch - ord 'a' + 1)
+
+-- | Parses an uppercase letter and returns (UpperAlpha, number).
+upperAlpha :: (Stream s m Char, UpdateSourcePos s Char) => ParsecT s st m (ListNumberStyle, Int)
+upperAlpha = do
+  ch <- satisfy isAsciiUpper
+  return (UpperAlpha, ord ch - ord 'A' + 1)
+
+-- | Parses a roman numeral i or I
+romanOne :: (Stream s m Char, UpdateSourcePos s Char) => ParsecT s st m (ListNumberStyle, Int)
+romanOne = (char 'i' >> return (LowerRoman, 1)) <|>
+           (char 'I' >> return (UpperRoman, 1))
+
+-- | Parses an ordered list marker and returns list attributes.
+anyOrderedListMarker :: (Stream s m Char, UpdateSourcePos s Char) => ParsecT s ParserState m ListAttributes
+anyOrderedListMarker = choice
+  [delimParser numParser | delimParser <- [inPeriod, inOneParen, inTwoParens],
+                           numParser <- [decimal, exampleNum, defaultNum, romanOne,
+                           lowerAlpha, lowerRoman, upperAlpha, upperRoman]]
+
+-- | Parses a list number (num) followed by a period, returns list attributes.
+inPeriod :: (Stream s m Char, UpdateSourcePos s Char)
+         => ParsecT s st m (ListNumberStyle, Int)
+         -> ParsecT s st m ListAttributes
+inPeriod num = try $ do
+  (style, start) <- num
+  char '.'
+  let delim = if style == DefaultStyle
+                 then DefaultDelim
+                 else Period
+  return (start, style, delim)
+
+-- | Parses a list number (num) followed by a paren, returns list attributes.
+inOneParen :: (Stream s m Char, UpdateSourcePos s Char)
+           => ParsecT s st m (ListNumberStyle, Int)
+           -> ParsecT s st m ListAttributes
+inOneParen num = try $ do
+  (style, start) <- num
+  char ')'
+  return (start, style, OneParen)
+
+-- | Parses a list number (num) enclosed in parens, returns list attributes.
+inTwoParens :: (Stream s m Char, UpdateSourcePos s Char)
+            => ParsecT s st m (ListNumberStyle, Int)
+            -> ParsecT s st m ListAttributes
+inTwoParens num = try $ do
+  char '('
+  (style, start) <- num
+  char ')'
+  return (start, style, TwoParens)
+
+-- | Parses an ordered list marker with a given style and delimiter,
+-- returns number.
+orderedListMarker :: (Stream s m Char, UpdateSourcePos s Char)
+                  => ListNumberStyle
+                  -> ListNumberDelim
+                  -> ParsecT s ParserState m Int
+orderedListMarker style delim = do
+  let num = defaultNum <|>  -- # can continue any kind of list
+            case style of
+               DefaultStyle -> decimal
+               Example      -> exampleNum
+               Decimal      -> decimal
+               UpperRoman   -> upperRoman
+               LowerRoman   -> lowerRoman
+               UpperAlpha   -> upperAlpha
+               LowerAlpha   -> lowerAlpha
+  let context = case delim of
+               DefaultDelim -> inPeriod
+               Period       -> inPeriod
+               OneParen     -> inOneParen
+               TwoParens    -> inTwoParens
+  (start, _, _) <- context num
+  return start
diff --git a/src/Text/Pandoc/Parsing/Math.hs b/src/Text/Pandoc/Parsing/Math.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Parsing/Math.hs
@@ -0,0 +1,102 @@
+{-# LANGUAGE FlexibleContexts           #-}
+{-# LANGUAGE OverloadedStrings          #-}
+{- |
+Module      : Text.Pandoc.Parsing.Math
+Copyright   : © 2006-2024 John MacFarlane
+License     : GPL-2.0-or-later
+Maintainer  : John MacFarlane <jgm@berkeley.edu>
+
+Parsing of LaTeX math.
+-}
+
+module Text.Pandoc.Parsing.Math
+  ( mathDisplay
+  , mathInline
+  )
+where
+
+import Control.Monad (mzero, when)
+import Data.Text (Text)
+import Text.Parsec ((<|>), ParsecT, Stream(..), notFollowedBy, many1, try)
+import Text.Pandoc.Options
+  ( Extension(Ext_tex_math_dollars, Ext_tex_math_single_backslash,
+              Ext_tex_math_double_backslash) )
+import Text.Pandoc.Parsing.Capabilities (HasReaderOptions, guardEnabled)
+import Text.Pandoc.Parsing.General
+import Text.Pandoc.Shared (trimMath)
+import Text.Pandoc.Sources
+  (UpdateSourcePos, anyChar, char, digit, newline, satisfy, space, string)
+
+import qualified Data.Text as T
+import qualified Data.Text.Lazy as TL
+import qualified Data.Text.Lazy.Builder as TB
+
+mathInlineWith :: (Stream s m Char, UpdateSourcePos s Char)  => Text -> Text -> ParsecT s st m Text
+mathInlineWith op cl = try $ do
+  textStr op
+  when (op == "$") $ notFollowedBy space
+  words' <- many1Till (
+                       (T.singleton <$>
+                          satisfy (\c -> not (isSpaceChar c || c == '\\')))
+                   <|> (char '\\' >>
+                           -- This next clause is needed because \text{..} can
+                           -- contain $, \(\), etc.
+                           (try (string "text" >>
+                                 (("\\text" <>) <$> inBalancedBraces 0 ""))
+                            <|>  (\c -> T.pack ['\\',c]) <$> anyChar))
+                   <|> ("\n" <$ blankline <* notFollowedBy' blankline <* notFollowedBy (char '$'))
+                   <|> (T.pack <$> many1 spaceChar <* notFollowedBy (char '$'))
+                    ) (try $ textStr cl)
+  notFollowedBy digit  -- to prevent capture of $5
+  return $ trimMath $ T.concat words'
+ where
+  inBalancedBraces :: (Stream s m Char, UpdateSourcePos s Char)
+                   => Int -> Text -> ParsecT s st m Text
+  inBalancedBraces n t =
+    TL.toStrict . TB.toLazyText <$>
+      go n False (TB.fromText t) (not (T.null t))
+
+  -- go depth lastWasBackslash accumulator started
+  go :: (Stream s m Char, UpdateSourcePos s Char)
+     => Int -> Bool -> TB.Builder -> Bool -> ParsecT s st m TB.Builder
+  go 0 _ acc False = do
+    c <- anyChar
+    if c == '{'
+       then go 1 False (acc <> TB.singleton '{') True
+       else mzero
+  go 0 _ acc True = return acc
+  go depth True acc _ = do
+    c <- anyChar
+    go depth False (acc <> TB.singleton c) True
+  go depth False acc _ = do
+    c <- anyChar
+    let acc' = acc <> TB.singleton c
+    case c of
+         '\\' -> go depth True acc' True
+         '}'  -> go (depth - 1) False acc' True
+         '{'  -> go (depth + 1) False acc' True
+         _    -> go depth False acc' True
+
+mathDisplayWith :: (Stream s m Char, UpdateSourcePos s Char) => Text -> Text -> ParsecT s st m Text
+mathDisplayWith op cl = try $ fmap T.pack $ do
+  textStr op
+  many1Till (satisfy (/= '\n') <|> (newline <* notFollowedBy' blankline))
+            (try $ textStr cl)
+
+mathDisplay :: (HasReaderOptions st, Stream s m Char, UpdateSourcePos s Char)
+            => ParsecT s st m Text
+mathDisplay =
+      (guardEnabled Ext_tex_math_dollars >> mathDisplayWith "$$" "$$")
+  <|> (guardEnabled Ext_tex_math_single_backslash >>
+       mathDisplayWith "\\[" "\\]")
+  <|> (guardEnabled Ext_tex_math_double_backslash >>
+       mathDisplayWith "\\\\[" "\\\\]")
+
+mathInline :: (HasReaderOptions st, Stream s m Char, UpdateSourcePos s Char)
+           => ParsecT s st m Text
+mathInline =
+      (guardEnabled Ext_tex_math_dollars >> mathInlineWith "$" "$")
+  <|> (guardEnabled Ext_tex_math_single_backslash >>
+       mathInlineWith "\\(" "\\)")
+  <|> (guardEnabled Ext_tex_math_double_backslash >>
+       mathInlineWith "\\\\(" "\\\\)")
diff --git a/src/Text/Pandoc/Parsing/Smart.hs b/src/Text/Pandoc/Parsing/Smart.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Parsing/Smart.hs
@@ -0,0 +1,179 @@
+{-# LANGUAGE FlexibleContexts           #-}
+{-# LANGUAGE OverloadedStrings          #-}
+{- |
+Module      : Text.Pandoc.Parsing.Smart
+Copyright   : © 2006-2024 John MacFarlane
+License     : GPL-2.0-or-later
+Maintainer  : John MacFarlane <jgm@berkeley.edu>
+
+Smart parsing of quotes, dashes, and other character combinations.
+-}
+
+module Text.Pandoc.Parsing.Smart
+  ( apostrophe
+  , dash
+  , doubleCloseQuote
+  , doubleQuoteEnd
+  , doubleQuoteStart
+  , doubleQuoted
+  , ellipses
+  , singleQuoteEnd
+  , singleQuoteStart
+  , singleQuoted
+  , smartPunctuation
+  )
+where
+
+import Control.Monad (guard , void)
+import Text.Pandoc.Builder (Inlines)
+import Text.Pandoc.Options
+  ( extensionEnabled
+  , Extension(Ext_old_dashes, Ext_smart)
+  , ReaderOptions(readerExtensions) )
+import Text.Pandoc.Sources
+import Text.Pandoc.Parsing.Capabilities
+import Text.Pandoc.Parsing.General
+import Text.Parsec
+  ( (<|>)
+  , Stream(..)
+  , ParsecT
+  , choice
+  , lookAhead
+  , manyTill
+  , notFollowedBy
+  , try
+  )
+import qualified Text.Pandoc.Builder as B
+
+-- | Parses various ASCII punctuation, quotes, and apostrophe in a smart
+-- way, inferring their semantic meaning.
+--
+-- Fails unless the 'Ext_smart' extension has been enabled.
+smartPunctuation :: (HasReaderOptions st, HasLastStrPosition st,
+                     HasQuoteContext st m,
+                     Stream s m Char, UpdateSourcePos s Char)
+                 => ParsecT s st m Inlines
+                 -> ParsecT s st m Inlines
+smartPunctuation inlineParser = do
+  guardEnabled Ext_smart
+  choice [ quoted inlineParser, apostrophe, doubleCloseQuote, dash, ellipses ]
+
+-- | Parses inline text in single or double quotes, assumes English
+-- quoting conventions.
+quoted :: (HasLastStrPosition st, HasQuoteContext st m,
+           Stream s m Char, UpdateSourcePos s Char)
+       => ParsecT s st m Inlines
+       -> ParsecT s st m Inlines
+quoted inlineParser = doubleQuoted inlineParser <|> singleQuoted inlineParser
+
+-- | Parses inline text in single quotes, assumes English quoting
+-- conventions.
+singleQuoted :: (HasLastStrPosition st, HasQuoteContext st m,
+                 Stream s m Char, UpdateSourcePos s Char)
+             => ParsecT s st m Inlines
+             -> ParsecT s st m Inlines
+singleQuoted inlineParser = do
+  singleQuoteStart
+  (B.singleQuoted . mconcat <$>
+    try
+     (withQuoteContext InSingleQuote (many1Till inlineParser singleQuoteEnd)))
+   <|> pure "\8217"
+
+-- | Parses inline text in double quotes; assumes English quoting
+-- conventions.
+doubleQuoted :: (HasQuoteContext st m, HasLastStrPosition st,
+                 Stream s m Char, UpdateSourcePos s Char)
+             => ParsecT s st m Inlines
+             -> ParsecT s st m Inlines
+doubleQuoted inlineParser = do
+  doubleQuoteStart
+  (B.doubleQuoted . mconcat <$>
+    try
+     (withQuoteContext InDoubleQuote (manyTill inlineParser doubleQuoteEnd)))
+   <|> pure (B.str "\8220")
+
+-- | Succeeds if the parser is
+--
+-- * not within single quoted text;
+-- * not directly after a word; and
+-- * looking at an opening single quote char that's not followed by a
+--   space.
+--
+-- Gobbles the quote character on success.
+singleQuoteStart :: (HasLastStrPosition st, HasQuoteContext st m,
+                     Stream s m Char, UpdateSourcePos s Char)
+                 => ParsecT s st m ()
+singleQuoteStart = do
+  failIfInQuoteContext InSingleQuote
+  -- single quote start can't be right after str
+  guard =<< notAfterString
+  try $ do
+    char '\''
+    void $ lookAhead (satisfy (not . isSpaceChar))
+
+singleQuoteEnd :: (Stream s m Char, UpdateSourcePos s Char)
+               => ParsecT s st m ()
+singleQuoteEnd = try $ do
+  char '\''
+  notFollowedBy alphaNum
+
+-- | Succeeds if the parser is
+--
+-- * not within a double quoted text;
+--
+-- * not directly after a word; and
+--
+-- * looking at an opening double quote char that's not followed by a
+--   space.
+--
+-- Gobbles the quote character on success.
+doubleQuoteStart :: (HasLastStrPosition st,
+                     HasQuoteContext st m,
+                     Stream s m Char, UpdateSourcePos s Char)
+                 => ParsecT s st m ()
+doubleQuoteStart = do
+  failIfInQuoteContext InDoubleQuote
+  guard =<< notAfterString
+  try $ do char '"'
+           void $ lookAhead (satisfy (not . isSpaceChar))
+
+-- | Parses a closing quote character.
+doubleQuoteEnd :: (Stream s m Char, UpdateSourcePos s Char)
+               => ParsecT s st m ()
+doubleQuoteEnd = void (char '"')
+
+-- | Parses an ASCII apostrophe (@'@) or right single quotation mark and
+-- returns a RIGHT SINGLE QUOtatiON MARK character.
+apostrophe :: (Stream s m Char, UpdateSourcePos s Char)
+           => ParsecT s st m Inlines
+apostrophe = (char '\'' <|> char '\8217') >> return (B.str "\8217")
+
+-- | Parses an ASCII quotation mark character and returns a RIGHT DOUBLE
+-- QUOTATION MARK.
+doubleCloseQuote :: (Stream s m Char, UpdateSourcePos s Char)
+                 => ParsecT s st m Inlines
+doubleCloseQuote = B.str "\8221" <$ char '"'
+
+-- | Parses three dots as HORIZONTAL ELLIPSIS.
+ellipses :: (Stream s m Char, UpdateSourcePos s Char)
+         => ParsecT s st m Inlines
+ellipses = try (string "..." >> return (B.str "\8230"))
+
+-- | Parses two hyphens as EN DASH and three as EM DASH.
+--
+-- If the extension @'Ext_old_dashes'@ is enabled, then two hyphens are
+-- parsed as EM DASH, and one hyphen is parsed as EN DASH if it is
+-- followed by a digit.
+dash :: (HasReaderOptions st, Stream s m Char, UpdateSourcePos s Char)
+     => ParsecT s st m Inlines
+dash = try $ do
+  oldDashes <- extensionEnabled Ext_old_dashes <$> getOption readerExtensions
+  if oldDashes
+     then do
+       char '-'
+       (char '-' >> return (B.str "\8212"))
+         <|> (lookAhead digit >> return (B.str "\8211"))
+     else do
+       string "--"
+       (char '-' >> return (B.str "\8212"))
+         <|> return (B.str "\8211")
diff --git a/src/Text/Pandoc/Parsing/State.hs b/src/Text/Pandoc/Parsing/State.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Parsing/State.hs
@@ -0,0 +1,189 @@
+{-# LANGUAGE FlexibleInstances          #-}
+{-# LANGUAGE MultiParamTypeClasses      #-}
+{-# LANGUAGE OverloadedStrings          #-}
+{- |
+   Module      : Text.Pandoc.Parsing
+   Copyright   : Copyright (C) 2006-2024 John MacFarlane
+   License     : GPL-2.0-or-later
+   Maintainer  : John MacFarlane <jgm@berkeley.edu>
+
+A default parser state with commonly used properties.
+-}
+
+module Text.Pandoc.Parsing.State
+  ( ParserState (..)
+  , ParserContext (..)
+  , HeaderType (..)
+  , NoteTable
+  , NoteTable'
+  , Key (..)
+  , KeyTable
+  , SubstTable
+  , defaultParserState
+  , toKey
+  )
+where
+
+import Data.Default (Default (def))
+import Data.Text (Text)
+import Text.Parsec (SourcePos, getState, setState)
+import Text.Pandoc.Builder (Blocks, HasMeta (..), Inlines)
+import Text.Pandoc.Definition (Attr, Meta, Target, nullMeta)
+import Text.Pandoc.Logging (LogMessage)
+import Text.Pandoc.Options (ReaderOptions)
+import Text.Pandoc.Parsing.Capabilities
+import Text.Pandoc.Parsing.Future
+import Text.Pandoc.TeX (Macro)
+
+import qualified Data.Map as M
+import qualified Data.Set as Set
+import qualified Data.Text as T
+
+-- | Parsing options.
+data ParserState = ParserState
+  { stateOptions         :: ReaderOptions -- ^ User options
+  , stateParserContext   :: ParserContext -- ^ Inside list?
+  , stateQuoteContext    :: QuoteContext  -- ^ Inside quoted environment?
+  , stateAllowLinks      :: Bool          -- ^ Allow parsing of links
+  , stateAllowLineBreaks :: Bool          -- ^ Allow parsing of line breaks
+  , stateLastStrPos      :: Maybe SourcePos -- ^ Position after last str parsed
+  , stateKeys            :: KeyTable      -- ^ List of reference keys
+  , stateHeaderKeys      :: KeyTable      -- ^ List of implicit header ref keys
+  , stateSubstitutions   :: SubstTable    -- ^ List of substitution references
+  , stateNotes           :: NoteTable     -- ^ List of notes (raw bodies)
+  , stateNotes'          :: NoteTable'    -- ^ List of notes (parsed bodies)
+  , stateNoteRefs        :: Set.Set Text  -- ^ List of note references used
+  , stateInNote          :: Bool          -- ^ True if parsing note contents
+  , stateNoteNumber      :: Int           -- ^ Last note number for citations
+  , stateMeta            :: Meta          -- ^ Document metadata
+  , stateMeta'           :: Future ParserState Meta -- ^ Document metadata
+  , stateCitations       :: M.Map Text Text -- ^ RST-style citations
+  , stateHeaderTable     :: [HeaderType]  -- ^ Ordered list of header types used
+  , stateIdentifiers     :: Set.Set Text  -- ^ Header identifiers used
+  , stateNextExample     :: Int           -- ^ Number of next example
+  , stateExamples        :: M.Map Text Int -- ^ Map from example labels to numbers
+  , stateMacros          :: M.Map Text Macro -- ^ Table of macros defined so far
+  , stateRstDefaultRole  :: Text          -- ^ Current rST default
+                                           -- interpreted text role
+  , stateRstHighlight    :: Maybe Text    -- ^ Current rST literal block
+                                           -- language
+  , stateRstCustomRoles  :: M.Map Text (Text, Maybe Text, Attr)
+    -- ^ Current rST cust text roles;
+    -- Triple represents:) Base role 2) Optional format (only for :raw:
+    -- roles) 3) Addition classes (rest of Attr is unused)).
+  , stateCaption         :: Maybe Inlines -- ^ Caption in current environment
+  , stateInHtmlBlock     :: Maybe Text    -- ^ Tag type of HTML block being parsed
+  , stateFencedDivLevel  :: Int           -- ^ Depth of fenced div
+  , stateContainers      :: [Text]        -- ^ parent include files
+  , stateLogMessages     :: [LogMessage]  -- ^ log messages
+  , stateMarkdownAttribute :: Bool        -- ^ True if in markdown=1 context
+  }
+
+instance Default ParserState where
+  def = defaultParserState
+
+instance HasMeta ParserState where
+  setMeta field val st =
+    st{ stateMeta = setMeta field val $ stateMeta st }
+  deleteMeta field st =
+    st{ stateMeta = deleteMeta field $ stateMeta st }
+
+instance HasReaderOptions ParserState where
+  extractReaderOptions = stateOptions
+
+instance Monad m => HasQuoteContext ParserState m where
+  getQuoteContext = stateQuoteContext <$> getState
+  withQuoteContext context parser = do
+    oldState <- getState
+    let oldQuoteContext = stateQuoteContext oldState
+    setState oldState { stateQuoteContext = context }
+    result <- parser
+    newState <- getState
+    setState newState { stateQuoteContext = oldQuoteContext }
+    return result
+
+instance HasIdentifierList ParserState where
+  extractIdentifierList     = stateIdentifiers
+  updateIdentifierList f st = st{ stateIdentifiers = f $ stateIdentifiers st }
+
+instance HasMacros ParserState where
+  extractMacros        = stateMacros
+  updateMacros f st    = st{ stateMacros = f $ stateMacros st }
+
+instance HasLastStrPosition ParserState where
+  setLastStrPos pos st = st{ stateLastStrPos = pos }
+  getLastStrPos st     = stateLastStrPos st
+
+instance HasLogMessages ParserState where
+  addLogMessage msg st = st{ stateLogMessages = msg : stateLogMessages st }
+  getLogMessages st = reverse $ stateLogMessages st
+
+instance HasIncludeFiles ParserState where
+  getIncludeFiles = stateContainers
+  addIncludeFile f s = s{ stateContainers = f : stateContainers s }
+  dropLatestIncludeFile s = s { stateContainers = drop 1 $ stateContainers s }
+
+data ParserContext
+    = ListItemState   -- ^ Used when running parser on list item contents
+    | NullState       -- ^ Default state
+    deriving (Eq, Show)
+
+data HeaderType
+    = SingleHeader Char  -- ^ Single line of characters underneath
+    | DoubleHeader Char  -- ^ Lines of characters above and below
+    deriving (Eq, Show)
+
+defaultParserState :: ParserState
+defaultParserState = ParserState
+  { stateOptions         = def
+  , stateParserContext   = NullState
+  , stateQuoteContext    = NoQuote
+  , stateAllowLinks      = True
+  , stateAllowLineBreaks = True
+  , stateLastStrPos      = Nothing
+  , stateKeys            = M.empty
+  , stateHeaderKeys      = M.empty
+  , stateSubstitutions   = M.empty
+  , stateNotes           = []
+  , stateNotes'          = M.empty
+  , stateNoteRefs        = Set.empty
+  , stateInNote          = False
+  , stateNoteNumber      = 0
+  , stateMeta            = nullMeta
+  , stateMeta'           = return nullMeta
+  , stateCitations       = M.empty
+  , stateHeaderTable     = []
+  , stateIdentifiers     = Set.empty
+  , stateNextExample     = 1
+  , stateExamples        = M.empty
+  , stateMacros          = M.empty
+  , stateRstDefaultRole  = "title-reference"
+  , stateRstHighlight    = Nothing
+  , stateRstCustomRoles  = M.empty
+  , stateCaption         = Nothing
+  , stateInHtmlBlock     = Nothing
+  , stateFencedDivLevel  = 0
+  , stateContainers      = []
+  , stateLogMessages     = []
+  , stateMarkdownAttribute = False
+  }
+
+type NoteTable = [(Text, Text)]
+
+type NoteTable' = M.Map Text (SourcePos, Future ParserState Blocks)
+-- used in markdown reader
+
+newtype Key = Key Text deriving (Show, Read, Eq, Ord)
+
+toKey :: Text -> Key
+toKey = Key . T.toLower . T.unwords . T.words . unbracket
+  where unbracket t
+          | Just ('[', t') <- T.uncons t
+          , Just (t'', ']') <- T.unsnoc t'
+          = t''
+          | otherwise
+          = t
+
+type KeyTable = M.Map Key (Target, Attr)
+
+type SubstTable = M.Map Key Blocks
diff --git a/src/Text/Pandoc/Pretty.hs b/src/Text/Pandoc/Pretty.hs
deleted file mode 100644
--- a/src/Text/Pandoc/Pretty.hs
+++ /dev/null
@@ -1,555 +0,0 @@
-{-# LANGUAGE CPP                        #-}
-{-# LANGUAGE GeneralizedNewtypeDeriving #-}
-{-
-Copyright (C) 2010-2017 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-2017 John MacFarlane
-   License     : GNU GPL, version 2 or above
-
-   Maintainer  : John MacFarlane <jgm@berkeley.edu>
-   Stability   : alpha
-   Portability : portable
-
-A prettyprinting library for the production of text documents,
-including wrapped text, indentated blocks, and tables.
--}
-
-module Text.Pandoc.Pretty (
-       Doc
-     , render
-     , cr
-     , blankline
-     , blanklines
-     , space
-     , text
-     , char
-     , prefixed
-     , flush
-     , nest
-     , hang
-     , beforeNonBlank
-     , nowrap
-     , afterBreak
-     , offset
-     , minOffset
-     , height
-     , lblock
-     , cblock
-     , rblock
-     , (<>)
-     , (<+>)
-     , ($$)
-     , ($+$)
-     , isEmpty
-     , empty
-     , cat
-     , hcat
-     , hsep
-     , vcat
-     , vsep
-     , nestle
-     , chomp
-     , inside
-     , braces
-     , brackets
-     , parens
-     , quotes
-     , doubleQuotes
-     , charWidth
-     , realLength
-     )
-
-where
-import Control.Monad
-import Control.Monad.State.Strict
-import Data.Char (isSpace)
-import Data.Foldable (toList)
-import Data.List (intersperse)
-import Data.Monoid ((<>))
-import Data.Sequence (Seq, ViewL (..), fromList, mapWithIndex, singleton, viewl,
-                      (<|))
-import qualified Data.Sequence as Seq
-import Data.String
-
-data RenderState a = RenderState{
-         output     :: [a]        -- ^ In reverse order
-       , prefix     :: String
-       , usePrefix  :: Bool
-       , lineLength :: Maybe Int  -- ^ 'Nothing' means no wrapping
-       , column     :: Int
-       , newlines   :: Int        -- ^ Number of preceding newlines
-       }
-
-type DocState a = State (RenderState a) ()
-
-data D = Text Int String
-       | Block Int [String]
-       | Prefixed String Doc
-       | BeforeNonBlank Doc
-       | Flush Doc
-       | BreakingSpace
-       | AfterBreak String
-       | CarriageReturn
-       | NewLine
-       | BlankLines Int  -- number of blank lines
-       deriving (Show, Eq)
-
-newtype Doc = Doc { unDoc :: Seq D }
-              deriving (Monoid, Show, Eq)
-
-instance IsString Doc where
-  fromString = text
-
-isBlank :: D -> Bool
-isBlank BreakingSpace  = True
-isBlank CarriageReturn = True
-isBlank NewLine        = True
-isBlank (BlankLines _) = True
-isBlank (Text _ (c:_)) = isSpace c
-isBlank _              = False
-
--- | True if the document is empty.
-isEmpty :: Doc -> Bool
-isEmpty = Seq.null . unDoc
-
--- | The empty document.
-empty :: Doc
-empty = mempty
-
--- | Concatenate a list of 'Doc's.
-cat :: [Doc] -> Doc
-cat = mconcat
-
--- | Same as 'cat'.
-hcat :: [Doc] -> Doc
-hcat = mconcat
-
--- | Concatenate a list of 'Doc's, putting breakable spaces
--- between them.
-infixr 6 <+>
-(<+>) :: Doc -> Doc -> Doc
-(<+>) x y
-  | isEmpty x = y
-  | isEmpty y = x
-  | otherwise = x <> space <> y
-
--- | Same as 'cat', but putting breakable spaces between the
--- 'Doc's.
-hsep :: [Doc] -> Doc
-hsep = foldr (<+>) empty
-
-infixr 5 $$
--- | @a $$ b@ puts @a@ above @b@.
-($$) :: Doc -> Doc -> Doc
-($$) x y
-  | isEmpty x = y
-  | isEmpty y = x
-  | otherwise = x <> cr <> y
-
-infixr 5 $+$
--- | @a $+$ b@ puts @a@ above @b@, with a blank line between.
-($+$) :: Doc -> Doc -> Doc
-($+$) x y
-  | isEmpty x = y
-  | isEmpty y = x
-  | otherwise = x <> blankline <> y
-
--- | List version of '$$'.
-vcat :: [Doc] -> Doc
-vcat = foldr ($$) empty
-
--- | List version of '$+$'.
-vsep :: [Doc] -> Doc
-vsep = foldr ($+$) empty
-
--- | Removes leading blank lines from a 'Doc'.
-nestle :: Doc -> Doc
-nestle (Doc d) = Doc $ go d
-  where go x = case viewl x of
-               (BlankLines _ :< rest) -> go rest
-               (NewLine :< rest)      -> go rest
-               _                      -> x
-
--- | Chomps trailing blank space off of a 'Doc'.
-chomp :: Doc -> Doc
-chomp d = Doc (fromList dl')
-  where dl = toList (unDoc d)
-        dl' = reverse $ go $ reverse dl
-        go []                    = []
-        go (BreakingSpace : xs)  = go xs
-        go (CarriageReturn : xs) = go xs
-        go (NewLine : xs)        = go xs
-        go (BlankLines _ : xs)   = go xs
-        go (Prefixed s d' : xs)  = Prefixed s (chomp d') : xs
-        go xs                    = xs
-
-outp :: (IsString a) => Int -> String -> DocState a
-outp off s | off < 0 = do  -- offset < 0 means newline characters
-  st' <- get
-  let rawpref = prefix st'
-  when (column st' == 0 && usePrefix st' && not (null rawpref)) $ do
-    let pref = reverse $ dropWhile isSpace $ reverse rawpref
-    modify $ \st -> st{ output = fromString pref : output st
-                      , column = column st + realLength pref }
-  let numnewlines = length $ takeWhile (=='\n') $ reverse s
-  modify $ \st -> st { output = fromString s : output st
-                     , column = 0
-                     , newlines = newlines st + numnewlines }
-outp off s = do           -- offset >= 0 (0 might be combining char)
-  st' <- get
-  let pref = prefix st'
-  when (column st' == 0 && usePrefix st' && not (null pref)) $
-    modify $ \st -> st{ output = fromString pref : output st
-                    , column = column st + realLength pref }
-  modify $ \st -> st{ output = fromString s : output st
-                    , column = column st + off
-                    , newlines = 0 }
-
--- | Renders a 'Doc'.  @render (Just n)@ will use
--- a line length of @n@ to reflow text on breakable spaces.
--- @render Nothing@ will not reflow text.
-render :: (IsString a) => Maybe Int -> Doc -> a
-render linelen doc = fromString . mconcat . reverse . output $
-  execState (renderDoc doc) startingState
-   where startingState = RenderState{
-                            output = mempty
-                          , prefix = ""
-                          , usePrefix = True
-                          , lineLength = linelen
-                          , column = 0
-                          , newlines = 2 }
-
-renderDoc :: (IsString a, Monoid a)
-          => Doc -> DocState a
-renderDoc = renderList . toList . unDoc
-
-data IsBlock = IsBlock Int [String]
-
--- This would be nicer with a pattern synonym
--- pattern VBlock i s <- mkIsBlock -> Just (IsBlock ..)
-
-renderList :: (IsString a, Monoid a)
-           => [D] -> DocState a
-renderList [] = return ()
-renderList (Text off s : xs) = do
-  outp off s
-  renderList xs
-
-renderList (Prefixed pref d : xs) = do
-  st <- get
-  let oldPref = prefix st
-  put st{ prefix = prefix st ++ pref }
-  renderDoc d
-  modify $ \s -> s{ prefix = oldPref }
-  renderList xs
-
-renderList (Flush d : xs) = do
-  st <- get
-  let oldUsePrefix = usePrefix st
-  put st{ usePrefix = False }
-  renderDoc d
-  modify $ \s -> s{ usePrefix = oldUsePrefix }
-  renderList xs
-
-renderList (BeforeNonBlank d : xs) =
-  case xs of
-    (x:_) | isBlank x -> renderList xs
-          | otherwise -> renderDoc d >> renderList xs
-    []                -> renderList xs
-
-renderList [BlankLines _] = return ()
-
-renderList (BlankLines m : BlankLines n : xs) =
-  renderList (BlankLines (max m n) : xs)
-
-renderList (BlankLines num : xs) = do
-  st <- get
-  case output st of
-     _ | newlines st > num -> return ()
-       | otherwise -> replicateM_ (1 + num - newlines st) (outp (-1) "\n")
-  renderList xs
-
-renderList (CarriageReturn : BlankLines m : xs) =
-  renderList (BlankLines m : xs)
-
-renderList (CarriageReturn : xs) = do
-  st <- get
-  if newlines st > 0 || null xs
-     then renderList xs
-     else do
-       outp (-1) "\n"
-       renderList xs
-
-renderList (NewLine : xs) = do
-  outp (-1) "\n"
-  renderList xs
-
-renderList (BreakingSpace : CarriageReturn : xs) = renderList (CarriageReturn:xs)
-renderList (BreakingSpace : NewLine : xs) = renderList (NewLine:xs)
-renderList (BreakingSpace : BlankLines n : xs) = renderList (BlankLines n:xs)
-renderList (BreakingSpace : BreakingSpace : xs) = renderList (BreakingSpace:xs)
-renderList (BreakingSpace : xs) = do
-  let isText (Text _ _)     = True
-      isText (Block _ _)    = True
-      isText (AfterBreak _) = True
-      isText _              = False
-  let isBreakingSpace BreakingSpace = True
-      isBreakingSpace _             = False
-  let xs' = dropWhile isBreakingSpace xs
-  let next = takeWhile isText xs'
-  st <- get
-  let off = sum $ map offsetOf next
-  case lineLength st of
-        Just l | column st + 1 + off > l -> do
-          outp (-1) "\n"
-          renderList xs'
-        _  -> do
-          outp 1 " "
-          renderList xs'
-
-renderList (AfterBreak s : xs) = do
-  st <- get
-  when (newlines st > 0) $ outp (realLength s) s
-  renderList xs
-
-renderList (Block i1 s1 : Block i2 s2  : xs) =
-  renderList (mergeBlocks False (IsBlock i1 s1) (IsBlock i2 s2) : xs)
-
-renderList (Block i1 s1 : BreakingSpace : Block i2 s2 : xs) =
-  renderList (mergeBlocks True (IsBlock i1 s1) (IsBlock i2 s2) : xs)
-
-renderList (Block _width lns : xs) = do
-  st <- get
-  let oldPref = prefix st
-  case column st - realLength oldPref of
-        n | n > 0 -> modify $ \s -> s{ prefix = oldPref ++ replicate n ' ' }
-        _ -> return ()
-  renderList $ intersperse CarriageReturn (map (Text 0) lns)
-  modify $ \s -> s{ prefix = oldPref }
-  renderList xs
-
-mergeBlocks :: Bool -> IsBlock -> IsBlock -> D
-mergeBlocks addSpace (IsBlock w1 lns1) (IsBlock w2 lns2) =
-  Block (w1 + w2 + if addSpace then 1 else 0) $
-     zipWith (\l1 l2 -> pad w1 l1 ++ l2) lns1' (map sp lns2')
-    where (lns1', lns2') = case (length lns1, length lns2) of
-                                (x, y) | x > y -> (lns1,
-                                                   lns2 ++ replicate (x - y) "")
-                                       | x < y -> (lns1 ++ replicate (y - x) "",
-                                                   lns2)
-                                       | otherwise -> (lns1, lns2)
-          pad n s = s ++ replicate (n - realLength s) ' '
-          sp "" = ""
-          sp xs = if addSpace then ' ' : xs else xs
-
-offsetOf :: D -> Int
-offsetOf (Text o _)    = o
-offsetOf (Block w _)   = w
-offsetOf BreakingSpace = 1
-offsetOf _             = 0
-
--- | A literal string.
-text :: String -> Doc
-text = Doc . toChunks
-  where toChunks :: String -> Seq D
-        toChunks [] = mempty
-        toChunks s = case break (=='\n') s of
-                          ([], _:ys) -> NewLine <| toChunks ys
-                          (xs, _:ys) -> Text (realLength xs) xs <|
-                                            (NewLine <| toChunks ys)
-                          (xs, [])      -> singleton $ Text (realLength xs) xs
-
--- | A character.
-char :: Char -> Doc
-char c = text [c]
-
--- | A breaking (reflowable) space.
-space :: Doc
-space = Doc $ singleton BreakingSpace
-
--- | A carriage return.  Does nothing if we're at the beginning of
--- a line; otherwise inserts a newline.
-cr :: Doc
-cr = Doc $ singleton CarriageReturn
-
--- | Inserts a blank line unless one exists already.
--- (@blankline <> blankline@ has the same effect as @blankline@.
-blankline :: Doc
-blankline = Doc $ singleton (BlankLines 1)
-
--- | Inserts blank lines unless they exist already.
--- (@blanklines m <> blanklines n@ has the same effect as @blanklines (max m n)@.
-blanklines :: Int -> Doc
-blanklines n = Doc $ singleton (BlankLines n)
-
--- | Uses the specified string as a prefix for every line of
--- the inside document (except the first, if not at the beginning
--- of the line).
-prefixed :: String -> Doc -> Doc
-prefixed pref doc = Doc $ singleton $ Prefixed pref doc
-
--- | Makes a 'Doc' flush against the left margin.
-flush :: Doc -> Doc
-flush doc = Doc $ singleton $ Flush doc
-
--- | Indents a 'Doc' by the specified number of spaces.
-nest :: Int -> Doc -> Doc
-nest ind = prefixed (replicate ind ' ')
-
--- | A hanging indent. @hang ind start doc@ prints @start@,
--- then @doc@, leaving an indent of @ind@ spaces on every
--- line but the first.
-hang :: Int -> Doc -> Doc -> Doc
-hang ind start doc = start <> nest ind doc
-
--- | @beforeNonBlank d@ conditionally includes @d@ unless it is
--- followed by blank space.
-beforeNonBlank :: Doc -> Doc
-beforeNonBlank d = Doc $ singleton (BeforeNonBlank d)
-
--- | Makes a 'Doc' non-reflowable.
-nowrap :: Doc -> Doc
-nowrap doc = Doc $ mapWithIndex replaceSpace $ unDoc doc
-  where replaceSpace _ BreakingSpace = Text 1 " "
-        replaceSpace _ x             = x
-
--- | Content to print only if it comes at the beginning of a line,
--- to be used e.g. for escaping line-initial `.` in groff man.
-afterBreak :: String -> Doc
-afterBreak s = Doc $ singleton (AfterBreak s)
-
--- | Returns the width of a 'Doc'.
-offset :: Doc -> Int
-offset d = case map realLength . lines . render Nothing $ d of
-                [] -> 0
-                os -> maximum os
-
--- | Returns the minimal width of a 'Doc' when reflowed at breakable spaces.
-minOffset :: Doc -> Int
-minOffset d = maximum (0: map realLength (lines $ render (Just 0) d))
-
--- | @lblock n d@ is a block of width @n@ characters, with
--- text derived from @d@ and aligned to the left.
-lblock :: Int -> Doc -> Doc
-lblock = block id
-
--- | Like 'lblock' but aligned to the right.
-rblock :: Int -> Doc -> Doc
-rblock w = block (\s -> replicate (w - realLength s) ' ' ++ s) w
-
--- | Like 'lblock' but aligned centered.
-cblock :: Int -> Doc -> Doc
-cblock w = block (\s -> replicate ((w - realLength s) `div` 2) ' ' ++ s) w
-
--- | Returns the height of a block or other 'Doc'.
-height :: Doc -> Int
-height = length . lines . render Nothing
-
-block :: (String -> String) -> Int -> Doc -> Doc
-block filler width d
-  | width < 1 && not (isEmpty d) = block filler 1 d
-  | otherwise                    = Doc $ singleton $ Block width $ map filler
-                                 $ chop width $ render (Just width) d
-
-chop :: Int -> String -> [String]
-chop _ [] = []
-chop n cs = case break (=='\n') cs of
-                  (xs, ys)     -> if len <= n
-                                     then case ys of
-                                             []     -> [xs]
-                                             ['\n'] -> [xs]
-                                             (_:zs) -> xs : chop n zs
-                                     else take n xs : chop n (drop n xs ++ ys)
-                                   where len = realLength xs
-
--- | Encloses a 'Doc' inside a start and end 'Doc'.
-inside :: Doc -> Doc -> Doc -> Doc
-inside start end contents =
-  start <> contents <> end
-
--- | Puts a 'Doc' in curly braces.
-braces :: Doc -> Doc
-braces = inside (char '{') (char '}')
-
--- | Puts a 'Doc' in square brackets.
-brackets :: Doc -> Doc
-brackets = inside (char '[') (char ']')
-
--- | Puts a 'Doc' in parentheses.
-parens :: Doc -> Doc
-parens = inside (char '(') (char ')')
-
--- | Wraps a 'Doc' in single quotes.
-quotes :: Doc -> Doc
-quotes = inside (char '\'') (char '\'')
-
--- | Wraps a 'Doc' in double quotes.
-doubleQuotes :: Doc -> Doc
-doubleQuotes = inside (char '"') (char '"')
-
--- | Returns width of a character in a monospace font:  0 for a combining
--- character, 1 for a regular character, 2 for an East Asian wide character.
-charWidth :: Char -> Int
-charWidth c =
-  case c of
-      _ | c <  '\x0300'                    -> 1
-        | c >= '\x0300' && c <= '\x036F'   -> 0  -- combining
-        | c >= '\x0370' && c <= '\x10FC'   -> 1
-        | c >= '\x1100' && c <= '\x115F'   -> 2
-        | c >= '\x1160' && c <= '\x11A2'   -> 1
-        | c >= '\x11A3' && c <= '\x11A7'   -> 2
-        | c >= '\x11A8' && c <= '\x11F9'   -> 1
-        | c >= '\x11FA' && c <= '\x11FF'   -> 2
-        | c >= '\x1200' && c <= '\x2328'   -> 1
-        | c >= '\x2329' && c <= '\x232A'   -> 2
-        | c >= '\x232B' && c <= '\x2E31'   -> 1
-        | c >= '\x2E80' && c <= '\x303E'   -> 2
-        | c == '\x303F'                    -> 1
-        | c >= '\x3041' && c <= '\x3247'   -> 2
-        | c >= '\x3248' && c <= '\x324F'   -> 1 -- ambiguous
-        | c >= '\x3250' && c <= '\x4DBF'   -> 2
-        | c >= '\x4DC0' && c <= '\x4DFF'   -> 1
-        | c >= '\x4E00' && c <= '\xA4C6'   -> 2
-        | c >= '\xA4D0' && c <= '\xA95F'   -> 1
-        | c >= '\xA960' && c <= '\xA97C'   -> 2
-        | c >= '\xA980' && c <= '\xABF9'   -> 1
-        | c >= '\xAC00' && c <= '\xD7FB'   -> 2
-        | c >= '\xD800' && c <= '\xDFFF'   -> 1
-        | c >= '\xE000' && c <= '\xF8FF'   -> 1 -- ambiguous
-        | c >= '\xF900' && c <= '\xFAFF'   -> 2
-        | c >= '\xFB00' && c <= '\xFDFD'   -> 1
-        | c >= '\xFE00' && c <= '\xFE0F'   -> 1 -- ambiguous
-        | c >= '\xFE10' && c <= '\xFE19'   -> 2
-        | c >= '\xFE20' && c <= '\xFE26'   -> 1
-        | c >= '\xFE30' && c <= '\xFE6B'   -> 2
-        | c >= '\xFE70' && c <= '\xFEFF'   -> 1
-        | c >= '\xFF01' && c <= '\xFF60'   -> 2
-        | c >= '\xFF61' && c <= '\x16A38'  -> 1
-        | c >= '\x1B000' && c <= '\x1B001' -> 2
-        | c >= '\x1D000' && c <= '\x1F1FF' -> 1
-        | c >= '\x1F200' && c <= '\x1F251' -> 2
-        | c >= '\x1F300' && c <= '\x1F773' -> 1
-        | c >= '\x20000' && c <= '\x3FFFD' -> 2
-        | otherwise                        -> 1
-
--- | Get real length of string, taking into account combining and double-wide
--- characters.
-realLength :: String -> Int
-realLength = sum . map charWidth
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,24 +1,6 @@
-{-
-Copyright (C) 2013-2017 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-2017 John MacFarlane
+   Copyright   : Copyright (C) 2013-2024 John MacFarlane
    License     : GNU GPL, version 2 or above
 
    Maintainer  : John MacFarlane <jgm@berkeley.edu>
@@ -29,12 +11,17 @@
 -}
 module Text.Pandoc.Process (pipeProcess)
 where
-import Control.Concurrent (forkIO, newEmptyMVar, putMVar, takeMVar)
-import Control.Exception
+import Control.Concurrent (MVar, forkIO, killThread, newEmptyMVar, putMVar,
+                           takeMVar)
+import Control.Exception (SomeException (..))
+import qualified Control.Exception as E
 import Control.Monad (unless)
+import Control.DeepSeq (rnf)
 import qualified Data.ByteString.Lazy as BL
+import Foreign.C (Errno (Errno), ePIPE)
+import GHC.IO.Exception (IOErrorType(..), IOException(..))
 import System.Exit (ExitCode (..))
-import System.IO (hClose, hFlush)
+import System.IO (hClose)
 import System.Process
 
 {- |
@@ -50,49 +37,76 @@
 @readProcessWithExitCode@, the forked process will be terminated and
 @readProcessWithExitCode@ will wait (block) until the process has been
 terminated.
--}
 
+This function was adapted from @readProcessWithExitCode@ of module
+System.Process, package process-1.6.3.0. The original code is BSD
+licensed and © University of Glasgow 2004-2008.
+-}
 pipeProcess
     :: Maybe [(String, String)] -- ^ environment variables
     -> FilePath                 -- ^ Filename of the executable (see 'proc' for details)
     -> [String]                 -- ^ any arguments
     -> BL.ByteString            -- ^ standard input
     -> IO (ExitCode,BL.ByteString) -- ^ exitcode, stdout
-pipeProcess mbenv cmd args input =
-    mask $ \restore -> do
-      (Just inh, Just outh, Nothing, pid) <- createProcess (proc cmd args)
-                                                   { env     = mbenv,
-                                                     std_in  = CreatePipe,
-                                                     std_out = CreatePipe,
-                                                     std_err = Inherit }
-      flip onException
-        (do hClose inh; hClose outh;
-            terminateProcess pid; waitForProcess pid) $ restore $ do
-        -- fork off a thread to start consuming stdout
+pipeProcess mbenv cmd args input = do
+    let cp_opts = (proc cmd args)
+                  { env     = mbenv
+                  , std_in  = CreatePipe
+                  , std_out = CreatePipe
+                  , std_err = Inherit
+                  }
+    withCreateProcess cp_opts $
+      \mbInh mbOuth _ pid -> do
+        let (inh, outh) =
+             case (mbInh, mbOuth) of
+                  (Just i, Just o) -> (i, o)
+                  (Nothing, _)     -> error "withCreateProcess no inh"
+                  (_, Nothing)     -> error "withCreateProcess no outh"
+
         out <- BL.hGetContents outh
-        waitOut <- forkWait $ evaluate $ BL.length out
 
-        -- now write and flush any input
-        let writeInput = do
-              unless (BL.null input) $ do
-                BL.hPutStr inh input
-                hFlush inh
-              hClose inh
+        -- fork off threads to start consuming stdout & stderr
+        withForkWait (E.evaluate $ rnf out) $ \waitOut -> do
 
-        writeInput
+          -- now write any input
+          unless (BL.null input) $
+            ignoreSigPipe $ BL.hPutStr inh input
+          -- hClose performs implicit hFlush, and thus may trigger a SIGPIPE
+          ignoreSigPipe $ hClose inh
 
-        -- wait on the output
-        waitOut
+          -- wait on the output
+          waitOut
 
-        hClose outh
+          hClose outh
 
         -- wait on the process
         ex <- waitForProcess pid
 
         return (ex, out)
 
-forkWait :: IO a -> IO (IO a)
-forkWait a = do
-  res <- newEmptyMVar
-  _ <- mask $ \restore -> forkIO $ try (restore a) >>= putMVar res
-  return (takeMVar res >>= either (\ex -> throwIO (ex :: SomeException)) return)
+-- | Fork a thread while doing something else, but kill it if there's an
+-- exception.
+--
+-- This is important in the cases above because we want to kill the thread
+-- that is holding the Handle lock, because when we clean up the process we
+-- try to close that handle, which could otherwise deadlock.
+--
+-- This function was copied verbatim from module System.Process of package
+-- process-1.6.3.0.
+withForkWait :: IO () -> (IO () ->  IO a) -> IO a
+withForkWait async body = do
+  waitVar <- newEmptyMVar :: IO (MVar (Either SomeException ()))
+  E.mask $ \restore -> do
+    tid <- forkIO $ E.try (restore async) >>= putMVar waitVar
+    let wait = takeMVar waitVar >>= either E.throwIO return
+    restore (body wait) `E.onException` killThread tid
+
+-- This function was copied verbatim from module System.Process of package
+-- process-1.6.3.0.
+ignoreSigPipe :: IO () -> IO ()
+ignoreSigPipe = E.handle $ \e ->
+  case e of
+    IOError { ioe_type  = ResourceVanished
+            , ioe_errno = Just ioe }
+      | Errno ioe == ePIPE -> return ()
+    _ -> E.throwIO e
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,27 +1,11 @@
-{-# LANGUAGE FlexibleInstances   #-}
-{-# LANGUAGE GADTs               #-}
+{-# LANGUAGE OverloadedStrings   #-}
+{-# LANGUAGE MonoLocalBinds      #-}
+{-# LANGUAGE RankNTypes          #-}
 {-# LANGUAGE ScopedTypeVariables #-}
-{-
-Copyright (C) 2006-2017 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 TupleSections       #-}
 {- |
    Module      : Text.Pandoc.Readers
-   Copyright   : Copyright (C) 2006-2017 John MacFarlane
+   Copyright   : Copyright (C) 2006-2024 John MacFarlane
    License     : GNU GPL, version 2 or above
 
    Maintainer  : John MacFarlane <jgm@berkeley.edu>
@@ -41,11 +25,15 @@
     -- * Readers: converting /to/ Pandoc format
     Reader (..)
   , readers
+  , readAsciiDoc
   , readDocx
-  , readOdt
+  , readPptx
+  , readXlsx
+  , readODT
   , readMarkdown
   , readCommonMark
   , readCreole
+  , readDokuWiki
   , readMediaWiki
   , readVimwiki
   , readRST
@@ -53,6 +41,7 @@
   , readLaTeX
   , readHtml
   , readJATS
+  , readJira
   , readTextile
   , readDocBook
   , readOPML
@@ -64,6 +53,22 @@
   , readTxt2Tags
   , readEPUB
   , readMuse
+  , readMan
+  , readMdoc
+  , readFB2
+  , readIpynb
+  , readCSV
+  , readTSV
+  , readCslJson
+  , readBibTeX
+  , readBibLaTeX
+  , readEndNoteXML
+  , readRIS
+  , readRTF
+  , readTypst
+  , readDjot
+  , readPod
+  , readXML
   -- * Miscellaneous
   , getReader
   , getDefaultExtensions
@@ -72,89 +77,134 @@
 import Control.Monad.Except (throwError)
 import Data.Aeson
 import qualified Data.ByteString.Lazy as BL
-import Data.List (intercalate)
 import Data.Text (Text)
+import qualified Data.Text as T
 import Text.Pandoc.Class
 import Text.Pandoc.Definition
 import Text.Pandoc.Error
 import Text.Pandoc.Extensions
+import qualified Text.Pandoc.Format as Format
 import Text.Pandoc.Options
+import Text.Pandoc.Readers.AsciiDoc
 import Text.Pandoc.Readers.CommonMark
+import Text.Pandoc.Readers.Markdown
 import Text.Pandoc.Readers.Creole
 import Text.Pandoc.Readers.DocBook
 import Text.Pandoc.Readers.Docx
+import Text.Pandoc.Readers.Pptx
+import Text.Pandoc.Readers.Xlsx
+import Text.Pandoc.Readers.DokuWiki
 import Text.Pandoc.Readers.EPUB
+import Text.Pandoc.Readers.FB2
+import Text.Pandoc.Readers.Ipynb
 import Text.Pandoc.Readers.Haddock
 import Text.Pandoc.Readers.HTML (readHtml)
 import Text.Pandoc.Readers.JATS (readJATS)
+import Text.Pandoc.Readers.Jira (readJira)
 import Text.Pandoc.Readers.LaTeX
-import Text.Pandoc.Readers.Markdown
 import Text.Pandoc.Readers.MediaWiki
 import Text.Pandoc.Readers.Muse
 import Text.Pandoc.Readers.Native
-import Text.Pandoc.Readers.Odt
+import Text.Pandoc.Readers.ODT
 import Text.Pandoc.Readers.OPML
 import Text.Pandoc.Readers.Org
+import Text.Pandoc.Readers.Pod
 import Text.Pandoc.Readers.RST
 import Text.Pandoc.Readers.Textile
 import Text.Pandoc.Readers.TikiWiki
 import Text.Pandoc.Readers.TWiki
 import Text.Pandoc.Readers.Txt2Tags
 import Text.Pandoc.Readers.Vimwiki
-import Text.Pandoc.Shared (mapLeft)
+import Text.Pandoc.Readers.Man
+import Text.Pandoc.Readers.Mdoc
+import Text.Pandoc.Readers.CSV
+import Text.Pandoc.Readers.CslJson
+import Text.Pandoc.Readers.BibTeX
+import Text.Pandoc.Readers.EndNote
+import Text.Pandoc.Readers.RIS
+import Text.Pandoc.Readers.RTF
+import Text.Pandoc.Readers.Typst
+import Text.Pandoc.Readers.Djot
+import Text.Pandoc.Readers.XML
 import qualified Text.Pandoc.UTF8 as UTF8
-import Text.Parsec.Error
+import Text.Pandoc.Sources (ToSources(..), sourcesToText)
 
-data Reader m = TextReader (ReaderOptions -> Text -> m Pandoc)
+data Reader m = TextReader (forall a . ToSources a =>
+                                ReaderOptions -> a -> m Pandoc)
               | ByteStringReader (ReaderOptions -> BL.ByteString -> m Pandoc)
 
 -- | Association list of formats and readers.
-readers :: PandocMonad m => [(String, Reader m)]
-readers = [ ("native"       , TextReader readNative)
-           ,("json"         , TextReader $ \o s ->
-                                               case readJSON o s of
-                                                 Right doc -> return doc
-                                                 Left _ -> throwError $ PandocParseError "JSON parse error")
-           ,("markdown"     , TextReader readMarkdown)
-           ,("markdown_strict" , TextReader readMarkdown)
-           ,("markdown_phpextra" , TextReader readMarkdown)
-           ,("markdown_github" , TextReader readMarkdown)
-           ,("markdown_mmd",  TextReader readMarkdown)
-           ,("commonmark"   , TextReader readCommonMark)
-           ,("creole"       , TextReader readCreole)
-           ,("gfm"          , TextReader readCommonMark)
-           ,("rst"          , TextReader readRST)
-           ,("mediawiki"    , TextReader readMediaWiki)
-           ,("vimwiki"      , TextReader readVimwiki)
-           ,("docbook"      , TextReader readDocBook)
-           ,("opml"         , TextReader readOPML)
-           ,("org"          , TextReader readOrg)
-           ,("textile"      , TextReader readTextile) -- TODO : textile+lhs
-           ,("html"         , TextReader readHtml)
-           ,("jats"         , TextReader readJATS)
-           ,("latex"        , TextReader readLaTeX)
-           ,("haddock"      , TextReader readHaddock)
-           ,("twiki"        , TextReader readTWiki)
-           ,("tikiwiki"     , TextReader readTikiWiki)
-           ,("docx"         , ByteStringReader readDocx)
-           ,("odt"          , ByteStringReader readOdt)
-           ,("t2t"          , TextReader readTxt2Tags)
-           ,("epub"         , ByteStringReader readEPUB)
-           ,("muse"         , TextReader readMuse)
-           ]
+readers :: PandocMonad m => [(Text, Reader m)]
+readers = [("native"       , TextReader readNative)
+          ,("json"         , TextReader readJSON)
+          ,("markdown"     , TextReader readMarkdown)
+          ,("markdown_strict" , TextReader readMarkdown)
+          ,("markdown_phpextra" , TextReader readMarkdown)
+          ,("markdown_github" , TextReader readMarkdown)
+          ,("markdown_mmd",  TextReader readMarkdown)
+          ,("commonmark"   , TextReader readCommonMark)
+          ,("commonmark_x" , TextReader readCommonMark)
+          ,("asciidoc"     , TextReader readAsciiDoc)
+          ,("creole"       , TextReader readCreole)
+          ,("dokuwiki"     , TextReader readDokuWiki)
+          ,("gfm"          , TextReader readCommonMark)
+          ,("rst"          , TextReader readRST)
+          ,("mediawiki"    , TextReader readMediaWiki)
+          ,("vimwiki"      , TextReader readVimwiki)
+          ,("docbook"      , TextReader readDocBook)
+          ,("opml"         , TextReader readOPML)
+          ,("org"          , TextReader readOrg)
+          ,("textile"      , TextReader readTextile) -- TODO : textile+lhs
+          ,("html"         , TextReader readHtml)
+          ,("bits"         , TextReader readJATS)
+          ,("jats"         , TextReader readJATS)
+          ,("jira"         , TextReader readJira)
+          ,("latex"        , TextReader readLaTeX)
+          ,("haddock"      , TextReader readHaddock)
+          ,("twiki"        , TextReader readTWiki)
+          ,("tikiwiki"     , TextReader readTikiWiki)
+          ,("docx"         , ByteStringReader readDocx)
+          ,("pptx"         , ByteStringReader readPptx)
+          ,("xlsx"         , ByteStringReader readXlsx)
+          ,("odt"          , ByteStringReader readODT)
+          ,("t2t"          , TextReader readTxt2Tags)
+          ,("epub"         , ByteStringReader readEPUB)
+          ,("muse"         , TextReader readMuse)
+          ,("man"          , TextReader readMan)
+          ,("fb2"          , TextReader readFB2)
+          ,("ipynb"        , TextReader readIpynb)
+          ,("csv"          , TextReader readCSV)
+          ,("tsv"          , TextReader readTSV)
+          ,("csljson"      , TextReader readCslJson)
+          ,("bibtex"       , TextReader readBibTeX)
+          ,("biblatex"     , TextReader readBibLaTeX)
+          ,("endnotexml"   , TextReader readEndNoteXML)
+          ,("ris"          , TextReader readRIS)
+          ,("rtf"          , TextReader readRTF)
+          ,("typst"        , TextReader readTypst)
+          ,("djot"         , TextReader readDjot)
+          ,("mdoc"         , TextReader readMdoc)
+          ,("pod"          , TextReader readPod)
+          ,("xml"          , TextReader readXML)
+          ]
 
--- | Retrieve reader, extensions based on formatSpec (format+extensions).
-getReader :: PandocMonad m => String -> Either String (Reader m, Extensions)
-getReader s =
-  case parseFormatSpec s of
-       Left e  -> Left $ intercalate "\n" [m | Message m <- errorMessages e]
-       Right (readerName, setExts) ->
-           case lookup readerName readers of
-                   Nothing  -> Left $ "Unknown reader: " ++ readerName
-                   Just  r  -> Right (r, setExts $
-                                        getDefaultExtensions readerName)
+-- | Retrieve reader, extensions based on format spec (format+extensions).
+getReader :: PandocMonad m => Format.FlavoredFormat -> m (Reader m, Extensions)
+getReader flvrd = do
+  let readerName = Format.formatName flvrd
+  case lookup readerName readers of
+    Nothing  -> throwError $ PandocUnknownReaderError readerName
+    Just  r  -> (r,) <$>
+      Format.applyExtensionsDiff (Format.getExtensionsConfig readerName) flvrd
 
 -- | Read pandoc document from JSON format.
-readJSON :: ReaderOptions -> Text -> Either PandocError Pandoc
-readJSON _ =
-  mapLeft PandocParseError . eitherDecode' . BL.fromStrict . UTF8.fromText
+readJSON :: (PandocMonad m, ToSources a)
+         => ReaderOptions
+         -> a
+         -> m Pandoc
+readJSON _ s =
+  case eitherDecode' . BL.fromStrict . UTF8.fromText
+                     . sourcesToText . toSources $ s of
+       Right doc -> return doc
+       Left e    -> throwError $ PandocParseError ("JSON parse error: "
+                                                   <> T.pack e)
diff --git a/src/Text/Pandoc/Readers/AsciiDoc.hs b/src/Text/Pandoc/Readers/AsciiDoc.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Readers/AsciiDoc.hs
@@ -0,0 +1,416 @@
+{-# LANGUAGE MultiParamTypeClasses #-}
+{-# LANGUAGE OverloadedStrings #-}
+{-# LANGUAGE ScopedTypeVariables #-}
+{-# LANGUAGE FlexibleInstances #-}
+{-# LANGUAGE FlexibleContexts #-}
+
+{- |
+   Module      : Text.Pandoc.Readers.AsciiDoc
+   Copyright   : Copyright (C) 2024 John MacFarlane
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : John MacFarlane <jgm@berkeley.edu>
+   Stability   : alpha
+   Portability : portable
+
+Reads and evaluates a AsciiDoc document as a Pandoc AST.
+-}
+module Text.Pandoc.Readers.AsciiDoc
+  ( readAsciiDoc
+  )
+where
+
+import Text.Pandoc.Class
+import Text.Pandoc.Options
+import Text.Pandoc.Definition
+import Text.Pandoc.Walk
+import Text.Pandoc.Shared (addPandocAttributes, blocksToInlines, safeRead,
+                           tshow)
+import qualified Text.Pandoc.UTF8 as UTF8
+import qualified AsciiDoc as A
+import Text.Pandoc.Error
+import qualified Text.Pandoc.Builder as B
+import Text.Pandoc.Readers.HTML (readHtml)
+import Control.Monad.Except (throwError)
+import Control.Monad
+import Text.Pandoc.Parsing (newPos, sourceName)
+import Text.Pandoc.Logging
+import Text.Pandoc.Sources
+import Control.Monad.State
+import qualified Data.List as L
+import Data.Char (chr, ord)
+import qualified Data.Text as T
+import qualified Data.Map as M
+import Data.Maybe (fromMaybe)
+
+-- import Debug.Trace
+
+-- | Read AsciiDoc from an input string and return a Pandoc document.
+readAsciiDoc :: (PandocMonad m, ToSources a) => ReaderOptions -> a -> m Pandoc
+readAsciiDoc _opts inp = do
+  let Sources sources = toSources inp
+  (mconcat <$> mapM
+   (\(sourcepos, t) ->
+     A.parseDocument getIncludeFile raiseError (sourceName sourcepos) t)
+    sources)
+   >>= resolveFootnotes
+   >>= resolveStem
+   >>= resolveIcons
+   >>= toPandoc
+ where
+  getIncludeFile fp = UTF8.toText <$> readFileStrict fp
+  raiseError fp pos msg = throwError $ PandocParseError $ T.pack
+                            $ msg <> " at " <> show fp <>
+                              " char " <> show pos
+
+toPandoc :: PandocMonad m => A.Document -> m Pandoc
+toPandoc doc =
+  Pandoc <$> doMeta (A.docMeta doc)
+         <*> (B.toList <$> doBlocks (A.docBlocks doc))
+
+resolveFootnotes :: Monad m => A.Document -> m A.Document
+resolveFootnotes doc = do
+  evalStateT (A.mapInlines go doc) (mempty :: M.Map T.Text [A.Inline])
+ where
+   go (A.Inline attr (A.Footnote (Just (A.FootnoteId fnid)) ils)) = do
+     fnmap <- get
+     case M.lookup fnid fnmap of
+       Just ils' ->
+         pure $ A.Inline attr (A.Footnote (Just (A.FootnoteId fnid)) ils')
+       Nothing -> do
+         put $ M.insert fnid ils fnmap
+         pure $ A.Inline attr (A.Footnote (Just (A.FootnoteId fnid)) ils)
+   go x = pure x
+
+resolveStem :: Monad m => A.Document -> m A.Document
+resolveStem doc = do
+  let defaultType = case M.lookup "stem" (A.docAttributes (A.docMeta doc)) of
+                      Just "asciimath" -> A.AsciiMath
+                      _ -> A.LaTeXMath
+  let doInlineStem (A.Inline attr (A.Math Nothing t)) =
+        pure $ A.Inline attr (A.Math (Just defaultType) t)
+      doInlineStem x = pure x
+  let doBlockStem (A.Block attr mbtit (A.MathBlock Nothing t)) =
+        pure $ A.Block attr mbtit (A.MathBlock (Just defaultType) t)
+      doBlockStem x = A.mapInlines doInlineStem x
+  A.mapBlocks doBlockStem doc
+
+-- resolve icons as either characters in an icon font or images
+resolveIcons :: Monad m => A.Document -> m A.Document
+resolveIcons doc = A.mapInlines fromIcon doc
+ where
+   docattrs = A.docAttributes (A.docMeta doc)
+   iconFont = case M.lookup "icons" docattrs of
+                Just "font" -> True
+                _ -> False
+   iconsdir = fromMaybe "./images/icons" $ M.lookup "iconsdir" docattrs
+   icontype = fromMaybe "png" $ M.lookup "icontype" docattrs
+   addClasses cls (A.Attr ps kvs) =
+     A.Attr ps $
+      case M.lookup "role" kvs of
+       Just r -> M.insert "role" (T.unwords (r : cls)) kvs
+       Nothing -> M.insert "role" (T.unwords cls) kvs
+   fromIcon (A.Inline attr (A.Icon name)) =
+     if iconFont
+        then pure $
+              A.Inline (addClasses ["fa", "fa-" <> name] attr) (A.Span [])
+        else pure $ -- default is to use an image
+              A.Inline (addClasses ["icon"] attr)
+                 (A.InlineImage
+                   (A.Target
+                      (iconsdir <> "/" <> name <> "." <> icontype))
+                      Nothing Nothing Nothing)
+   fromIcon x = pure x
+
+addAttribution :: Maybe A.Attribution -> B.Blocks -> B.Blocks
+addAttribution Nothing bs = bs
+addAttribution (Just (A.Attribution t)) bs = B.fromList $
+  case B.toList bs of
+    [B.Div attr bls] -> [B.Div attr (bls ++ [attrBlock])]
+    [B.BlockQuote bls] -> [B.BlockQuote (bls ++ [attrBlock])]
+    xs -> xs ++ [attrBlock]
+ where
+   attrBlock = Para (B.toList $ B.text $ "\x2014 " <> t)
+
+doMeta :: PandocMonad m => A.Meta -> m B.Meta
+doMeta meta = do
+  tit' <- doInlines (A.docTitle meta)
+  pure $
+    (if tit' == mempty
+        then id
+        else B.setMeta "title" tit') .
+    (case A.docAuthors meta of
+       [] -> id
+       as -> B.setMeta "author" (map fromAuthor as)) .
+    (case A.docRevision meta of
+       Nothing -> id
+       Just (A.Revision vers mbdate mbremark) ->
+         B.setMeta "version" vers .
+         maybe id (B.setMeta "date") mbdate .
+         maybe id (B.setMeta "remark") mbremark) .
+    flip (L.foldl' (\m (k,v) ->
+                    -- leave out flags that are set just for processing
+                    if k == "sectids" || k == "stem"
+                       then m
+                       else if T.null v
+                               then B.setMeta k True m
+                               else B.setMeta k v m))
+      (M.toList (A.docAttributes meta))
+    $ mempty
+
+fromAuthor :: A.Author -> B.Inlines
+fromAuthor au = B.text (A.authorName au) <>
+  maybe mempty (\email ->
+    " (" <> B.link ("mailto:" <> email) "" (B.str email) <> ")")
+    (A.authorEmail au)
+
+doBlocks :: PandocMonad m => [A.Block] -> m B.Blocks
+doBlocks = fmap mconcat . mapM doBlock
+
+addBlockAttr :: A.Attr -> B.Blocks -> B.Blocks
+addBlockAttr (A.Attr _ kvs') bs =
+  case B.toList bs of
+    x@(B.OrderedList{}) : xs -> -- "start" is handled in list attribs
+      addPandocAttributes (M.toList $ M.delete "start" kvs)
+             (B.singleton x) <> B.fromList xs
+    x:xs -> addPandocAttributes (M.toList kvs) (B.singleton x)
+                <> B.fromList xs
+    [] -> mempty
+ where
+  kvs = M.mapKeys (\k -> if k == "role" then "class" else k) kvs'
+
+addBlockTitle :: B.Inlines -> B.Blocks -> B.Blocks
+addBlockTitle tit' bs =
+  let tit = B.toList tit'
+  in case B.toList bs of
+    [B.Table attr _ colspecs thead tbody tfoot] ->
+      B.singleton $ B.Table attr (B.Caption Nothing [B.Plain tit])
+                     colspecs thead tbody tfoot
+    [B.Figure attr _ bs'] ->
+      B.singleton $ B.Figure attr (B.Caption Nothing [B.Plain tit]) bs'
+    [B.Div attr (B.Div ("",["title"],[]) [Para _] : bs')] ->
+      -- replace existing title, which might be e.g. "Note"
+      B.singleton $ B.Div attr (B.Div ("",["title"],[]) [B.Para tit] : bs')
+    [B.Div attr bs'] -> -- put title Div inside
+      B.singleton $ B.Div attr (B.Div ("",["title"],[]) [B.Para tit] : bs')
+    _ -> B.divWith B.nullAttr (B.divWith ("",["title"],[]) (B.para tit') <> bs)
+
+doBlock :: PandocMonad m => A.Block -> m B.Blocks
+doBlock (A.Block attr@(A.Attr ps kvs) mbtitle bt) = do
+  mbtitle' <- case mbtitle of
+                Nothing -> pure Nothing
+                Just (A.BlockTitle ils) -> Just <$> doInlines ils
+  addBlockAttr attr . maybe id addBlockTitle mbtitle' <$>
+   case bt of
+    A.Section (A.Level lev) ils bs -> do
+      ils' <- doInlines ils
+      bs' <- doBlocks bs
+      pure $ (B.header lev ils') <> bs'
+    A.DiscreteHeading (A.Level lev) ils ->
+      B.header lev <$> doInlines ils
+    A.Paragraph ils -> B.para <$> doInlines ils
+    A.LiteralBlock t -> pure $ B.codeBlock t
+    A.Listing mblang lns -> do
+      let fromCallout (A.Callout i)
+            | i <= 20 = T.pack [' ', chr (0x2460 + i - 1)]
+            | otherwise = "<" <> tshow i <> ">"
+      let fromSourceLine (A.SourceLine t callouts) =
+            t <> mconcat (map fromCallout callouts)
+      let code = T.intercalate "\n" $ map fromSourceLine lns
+      let classes = case mblang of
+                      Nothing -> []
+                      Just (A.Language l) -> [l]
+      pure $ B.codeBlockWith ("", classes, []) code
+    A.IncludeListing _ _ Nothing -> pure mempty
+    A.IncludeListing mblang _fp (Just lns) ->
+      doBlock (A.Block mempty mbtitle (A.Listing mblang lns))
+    A.ExampleBlock bs -> B.divWith ("",["example"],[]) <$> doBlocks bs
+    A.Sidebar bs -> B.divWith ("",["sidebar"],[]) <$> doBlocks bs
+    A.OpenBlock bs -> B.divWith ("",[],[]) <$> doBlocks bs
+    A.QuoteBlock mbattrib bs ->
+      addAttribution mbattrib . B.blockQuote <$> doBlocks bs
+    A.Verse mbattrib bs ->
+      addAttribution mbattrib . B.blockQuote <$> doBlocks bs
+    -- TODO when texmath's asciimath parser works, convert:
+    A.MathBlock (Just A.AsciiMath) t -> pure $ B.para $ B.displayMath t
+    A.MathBlock (Just A.LaTeXMath) t -> pure $ B.para $ B.displayMath t
+    A.MathBlock Nothing _ ->
+      throwError $ PandocParseError "Encountered math type Nothing"
+    A.List (A.BulletList _) items ->
+      B.bulletList <$> mapM doItem items
+    A.List A.CheckList items ->
+      B.bulletList <$> mapM doItem items
+    A.List (A.OrderedList _ mbstart) items -> do
+      let start = fromMaybe (1 :: Int)
+                    (mbstart `mplus` (M.lookup "start" kvs >>= safeRead))
+      let getStyle xs = case xs of
+                  "arabic":_ -> Decimal
+                  "decimal":_ -> Decimal
+                  "loweralpha":_ -> LowerAlpha
+                  "upperalpha":_ -> UpperAlpha
+                  "lowerroman":_ -> LowerRoman
+                  "upperroman":_ -> UpperRoman
+                  _:rest -> getStyle rest
+                  [] -> DefaultStyle
+      let sty = getStyle ps
+      let delim = DefaultDelim
+      B.orderedListWith (start, sty, delim) <$> mapM doItem items
+    A.List A.CalloutList items ->
+      B.divWith ("",["callout-list"],[]) . B.orderedList <$> mapM doItem items
+    A.DefinitionList items
+      | "ordered" `elem` ps ->
+          B.orderedList <$>
+             mapM (fmap (B.definitionList . (:[])) . doDefListItem) items
+      | otherwise -> B.definitionList <$> mapM doDefListItem items
+    A.Table specs mbHeader rows mbFooter -> do
+      let toAlign A.AlignLeft = B.AlignLeft
+          toAlign A.AlignCenter = B.AlignCenter
+          toAlign A.AlignRight = B.AlignRight
+      let fromCell (A.TableCell bs mbHorizAlign _mbVertAlign colspan rowspan) =
+            B.Cell B.nullAttr (maybe B.AlignDefault toAlign mbHorizAlign)
+                        (B.RowSpan rowspan) (B.ColSpan colspan) . B.toList
+                   <$> doBlocks bs
+      let fromRow (A.TableRow cs) = B.Row B.nullAttr <$> mapM fromCell cs
+      tbody <- B.TableBody B.nullAttr (B.RowHeadColumns 0) [] <$> mapM fromRow rows
+      thead <- B.TableHead B.nullAttr <$> maybe (pure []) (mapM fromRow) mbHeader
+      tfoot <- B.TableFoot B.nullAttr <$> maybe (pure []) (mapM fromRow) mbFooter
+      let totalWidth = sum $ map (fromMaybe 1 . A.colWidth) specs
+      let toColSpec spec = (maybe B.AlignDefault toAlign (A.colHorizAlign spec),
+                             maybe B.ColWidthDefault
+                               (B.ColWidth . (\x ->
+                                   fromIntegral x / fromIntegral totalWidth))
+                               (A.colWidth spec))
+      let colspecs = map toColSpec specs
+      pure $ B.table (B.Caption Nothing mempty) -- added by addBlockTitle
+                colspecs thead [tbody] tfoot
+    A.BlockImage target mbalt mbw mbh -> do
+      img' <- doInline (A.Inline mempty (A.InlineImage target mbalt mbw mbh))
+      -- TODO have a global function that adds the title to caption here:
+      pure $ B.figure (Caption Nothing mempty) -- added by addBlockTitle
+                      (B.plain img')
+    -- TODO alt text?
+    A.BlockAudio (A.Target t) ->
+      pure $ B.plain $ B.image t "" (B.str t)
+    -- TODO alt text?
+    A.BlockVideo (A.Target t) ->
+      pure $ B.plain $ B.image t "" (B.str t)
+    A.TOC -> pure $ B.divWith ("toc",[],[]) mempty
+    A.Admonition admonitionType bs -> do
+      let admon = T.pack $ show admonitionType
+      bs' <- doBlocks bs
+      pure $ B.divWith ("",[T.toLower admon],[])
+           $ B.divWith ("",["title"],[]) (B.para (B.str admon)) <> bs'
+    A.PageBreak ->
+      pure $ B.divWith ("", ["page-break"], [("wrapper", "1")]) B.horizontalRule
+    A.ThematicBreak -> pure $ B.horizontalRule
+    A.Include fp (Just bs) ->
+      B.divWith ("",["included"],[("path",T.pack fp)]) <$> doBlocks bs
+    A.Include fp Nothing -> do
+      report $ CouldNotLoadIncludeFile (T.pack fp) (newPos "" 0 0)
+      pure mempty
+    A.PassthroughBlock t ->
+         case runPure (readHtml def{
+                               readerExtensions = extensionsFromList [Ext_raw_html]
+                               } t) of
+        Left _ -> pure $ B.rawBlock "html" t
+        Right (Pandoc _ bs) -> pure $ B.fromList bs
+
+doItem :: PandocMonad m => A.ListItem -> m B.Blocks
+doItem (A.ListItem Nothing bs) = doBlocks bs
+doItem (A.ListItem (Just checkstate) bs) = do
+  bs' <- doBlocks bs
+  let check = case checkstate of
+                A.Checked -> Str "\9746"
+                A.Unchecked -> Str "\9744"
+  pure $ B.fromList
+       $ case B.toList bs' of
+           (B.Para ils : rest) -> B.Para (check : B.Space : ils) : rest
+           (B.Plain ils : rest) -> B.Plain (check : B.Space : ils) : rest
+           rest -> B.Para [check] : rest
+
+doDefListItem :: PandocMonad m
+              => ([A.Inline], [A.Block]) -> m (B.Inlines , [B.Blocks])
+doDefListItem (lab, bs) = do
+  lab' <- doInlines lab
+  bs' <- doBlocks bs
+  pure (lab', [bs'])
+
+doInlines :: PandocMonad m => [A.Inline] -> m B.Inlines
+doInlines = fmap mconcat . mapM doInline
+
+doInline :: PandocMonad m => A.Inline -> m B.Inlines
+doInline (A.Inline (A.Attr _ps kvs') it) = do
+  let kvs = M.mapKeys (\k -> if k == "role" then "class" else k) kvs'
+  addPandocAttributes (M.toList kvs) <$>
+   case it of
+    A.Str t -> pure $ B.text t
+    A.HardBreak -> pure B.linebreak
+    A.Bold ils -> B.strong <$> doInlines ils
+    A.Italic ils -> B.emph <$> doInlines ils
+    A.Monospace ils -> walk monospaceStr <$> doInlines ils
+    A.Superscript ils -> B.superscript <$> doInlines ils
+    A.Subscript ils -> B.subscript <$> doInlines ils
+    A.Highlight ils -> B.spanWith ("",["mark"],[]) <$> doInlines ils
+    A.Strikethrough ils -> B.strikeout <$> doInlines ils
+    A.DoubleQuoted ils -> B.doubleQuoted <$> doInlines ils
+    A.SingleQuoted ils -> B.singleQuoted <$> doInlines ils
+    -- TODO when texmath's asciimath parser works, convert:
+    A.Math (Just A.AsciiMath) t -> pure $ B.math t
+    A.Math (Just A.LaTeXMath) t -> pure $ B.math t
+    A.Math Nothing _ ->
+      throwError $ PandocParseError "Encountered math type Nothing"
+    A.Icon t -> pure $ B.spanWith ("",["icon"],[("name",t)])
+                         (B.str ("[" <> t <> "]"))
+    A.Button t -> pure $ B.spanWith ("",["button"],[])
+                         (B.strong $ B.str ("[" <> t <> "]"))
+    A.Kbd ts -> pure $ mconcat $ L.intersperse (B.str "+") $
+         map (B.spanWith ("",["kbd"],[]) . B.strong . B.str) ts
+    A.Menu ts -> pure $ B.spanWith ("",["menu"],[]) $
+        B.strong $ B.text $ T.intercalate " › " ts
+    -- TODO do we need linktype?
+    A.Link _linkType (A.Target t) ils -> B.link t "" <$> doInlines ils
+    A.InlineImage (A.Target url) mbalt mbwidth mbheight -> do
+      let alt = case mbalt of
+                  Just (A.AltText t) -> B.text t
+                  Nothing -> mempty
+          width = case mbwidth of
+                  Just (A.Width n) -> [("width", T.pack $ show n <> "px")]
+                  Nothing -> []
+          height = case mbheight of
+                  Just (A.Height n) -> [("height", T.pack $ show n <> "px")]
+                  Nothing -> []
+      pure $ B.imageWith ("",[], width ++ height) url "" alt
+    A.Footnote _ ils -> B.note . B.para <$> doInlines ils
+    A.InlineAnchor t _ -> pure $ B.spanWith (t, [], []) mempty
+    A.BibliographyAnchor t _ -> pure $ B.spanWith (t, [], []) mempty
+    A.CrossReference t Nothing ->
+      pure $ B.linkWith ("",["cross-reference"],[]) ("#" <> t) "" (B.str t)
+    A.CrossReference t (Just ils) -> do
+      B.linkWith ("",["cross-reference"],[]) ("#" <> t) "" <$> doInlines ils
+    A.AttributeReference (A.AttributeName t) -> -- if this is here, it's unresolved
+      pure $ B.str ("{" <> t <> "}")
+    A.Span ils -> B.spanWith B.nullAttr <$> doInlines ils
+    A.IndexEntry (A.TermInText t) ->
+      pure $ B.spanWith ("",["index"],[("term",t)]) (B.text t)
+    A.IndexEntry (A.TermConcealed ts) ->
+      pure $ B.spanWith ("",["index"],[("term",T.intercalate "," ts)]) mempty
+    A.Counter name ctype val ->
+      pure $ B.spanWith ("",["counter"],[("name",name)]) $ B.str $
+        case ctype of
+          A.DecimalCounter -> tshow val
+          A.UpperAlphaCounter -> T.singleton $ chr (ord 'A' + val - 1)
+          A.LowerAlphaCounter -> T.singleton $ chr (ord 'a' + val - 1)
+    -- Passthrough is hard to get right, because pandoc's RawInline needs
+    -- a format specifier. Often in asciidoc passthrough is used as a form
+    -- of escaping, so the best approach seems to be treating it as HTML
+    -- and parsing it:
+    A.Passthrough t -> do
+      case runPure (readHtml def{
+                               readerExtensions = extensionsFromList [Ext_raw_html]
+                               } t) of
+        Left _ -> pure $ B.rawInline "html" t
+        Right (Pandoc _ bs) -> pure $ B.fromList . blocksToInlines $ bs
+
+monospaceStr :: Inline -> Inline
+monospaceStr (Str t) = Code B.nullAttr t
+monospaceStr x = x
diff --git a/src/Text/Pandoc/Readers/BibTeX.hs b/src/Text/Pandoc/Readers/BibTeX.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Readers/BibTeX.hs
@@ -0,0 +1,78 @@
+{-# LANGUAGE OverloadedStrings #-}
+{- |
+   Module      : Text.Pandoc.Readers.BibTeX
+   Copyright   : Copyright (C) 2020-2024 John MacFarlane
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : John MacFarlane <jgm@berkeley.edu>
+   Stability   : alpha
+   Portability : portable
+
+Parses BibTeX or BibLaTeX bibliographies into a Pandoc document
+with empty body and `references` and `nocite` fields
+in the metadata.  A wildcard `nocite` is used so that
+if the document is rendered in another format, the
+entire bibliography will be printed.
+-}
+module Text.Pandoc.Readers.BibTeX
+  ( readBibTeX
+  , readBibLaTeX
+  )
+where
+
+import Text.Pandoc.Options
+import Text.Pandoc.Definition
+import Text.Pandoc.Builder (setMeta, cite, str)
+import Text.Pandoc.Parsing (fromParsecError)
+import Citeproc (Lang(..), parseLang)
+import Citeproc.Locale (getLocale)
+import Text.Pandoc.Error (PandocError(..))
+import Text.Pandoc.Class (PandocMonad, lookupEnv)
+import Text.Pandoc.Citeproc.BibTeX as BibTeX
+import Text.Pandoc.Citeproc.MetaValue (referenceToMetaValue)
+import Text.Pandoc.Sources (ToSources(..))
+import Control.Monad.Except (throwError)
+
+-- | Read BibTeX from an input string and return a Pandoc document.
+-- The document will have only metadata, with an empty body.
+-- The metadata will contain a `references` field with the
+-- bibliography entries, and a `nocite` field with the wildcard `[@*]`.
+readBibTeX :: (PandocMonad m, ToSources a)
+           => ReaderOptions -> a -> m Pandoc
+readBibTeX = readBibTeX' BibTeX.Bibtex
+
+-- | Read BibLaTeX from an input string and return a Pandoc document.
+-- The document will have only metadata, with an empty body.
+-- The metadata will contain a `references` field with the
+-- bibliography entries, and a `nocite` field with the wildcard `[@*]`.
+readBibLaTeX :: (PandocMonad m, ToSources a)
+             => ReaderOptions -> a -> m Pandoc
+readBibLaTeX = readBibTeX' BibTeX.Biblatex
+
+readBibTeX' :: (PandocMonad m, ToSources a)
+            => Variant -> ReaderOptions -> a -> m Pandoc
+readBibTeX' variant _opts t = do
+  mblangEnv <- lookupEnv "LANG"
+  let defaultLang = Lang "en" Nothing (Just "US") [] [] []
+  let lang = case mblangEnv of
+              Nothing  -> defaultLang
+              Just l   -> either (const defaultLang) id $ parseLang l
+  locale <- case getLocale lang of
+               Left e  ->
+                 case getLocale (Lang "en" Nothing (Just "US") [] [] []) of
+                   Right l -> return l
+                   Left _  -> throwError $ PandocCiteprocError e
+               Right l -> return l
+  case BibTeX.readBibtexString variant locale (const True) t of
+    Left e -> throwError $ fromParsecError (toSources t) e
+    Right refs -> return $ setMeta "references"
+                              (map referenceToMetaValue refs)
+                         . setMeta "nocite"
+                            (cite [Citation {citationId = "*"
+                                            , citationPrefix = []
+                                            , citationSuffix = []
+                                            , citationMode = NormalCitation
+                                            , citationNoteNum = 0
+                                            , citationHash = 0}]
+                                            (str "[@*]"))
+                        $ Pandoc nullMeta []
diff --git a/src/Text/Pandoc/Readers/CSV.hs b/src/Text/Pandoc/Readers/CSV.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Readers/CSV.hs
@@ -0,0 +1,73 @@
+{-# LANGUAGE FlexibleContexts    #-}
+
+{-# LANGUAGE ScopedTypeVariables #-}
+{- |
+   Module      : Text.Pandoc.Readers.CSV
+   Copyright   : Copyright (C) 2006-2024 John MacFarlane
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : John MacFarlane <jgm@berkeley.edu>
+   Stability   : alpha
+   Portability : portable
+
+Conversion from CSV or TSV to a 'Pandoc' table.
+-}
+module Text.Pandoc.Readers.CSV (
+  readCSV,
+  readTSV
+) where
+import qualified Data.Text as T
+import Text.Pandoc.CSV (parseCSV, defaultCSVOptions, CSVOptions(..))
+import Text.Pandoc.Definition
+import qualified Text.Pandoc.Builder as B
+import Text.Pandoc.Class (PandocMonad)
+import Text.Pandoc.Sources (ToSources(..), sourcesToText)
+import Text.Pandoc.Options (ReaderOptions)
+import Control.Monad.Except (throwError)
+import Data.Text (Text)
+import Data.List (intersperse)
+import Text.Pandoc.Parsing (fromParsecError)
+
+readCSV :: (PandocMonad m, ToSources a)
+        => ReaderOptions -- ^ Reader options
+        -> a
+        -> m Pandoc
+readCSV _opts s = do
+  readCSVWith defaultCSVOptions $ sourcesToText $ toSources s
+
+readTSV :: (PandocMonad m, ToSources a)
+        => ReaderOptions -- ^ Reader options
+        -> a
+        -> m Pandoc
+readTSV _opts s = do
+  readCSVWith tsvOpts $ sourcesToText $ toSources s
+ where
+  tsvOpts = CSVOptions{
+    csvDelim = '\t',
+    csvQuote = Nothing,
+    csvKeepSpace = False,
+    csvEscape = Nothing }
+
+readCSVWith :: PandocMonad m
+            => CSVOptions
+            -> Text
+            -> m Pandoc
+readCSVWith csvopts txt = do
+  case parseCSV csvopts txt of
+    Right (r:rs) -> return $ B.doc $ B.table capt
+                                             (zip aligns widths)
+                                             (TableHead nullAttr hdrs)
+                                             [TableBody nullAttr 0 [] rows]
+                                             (TableFoot nullAttr [])
+       where capt = B.emptyCaption
+             numcols = length r
+             toplain = B.simpleCell . B.plain . mconcat .
+                       intersperse B.linebreak . map B.text . T.lines
+             toRow = Row nullAttr . map toplain
+             toHeaderRow l = [toRow l | not (null l)]
+             hdrs = toHeaderRow r
+             rows = map toRow rs
+             aligns = replicate numcols AlignDefault
+             widths = replicate numcols ColWidthDefault
+    Right []     -> return $ B.doc mempty
+    Left e       -> throwError $ fromParsecError (toSources [("",txt)]) e
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,24 +1,9 @@
-{-
-Copyright (C) 2015-2017 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 OverloadedStrings #-}
+{-# LANGUAGE FlexibleContexts #-}
+{-# LANGUAGE ScopedTypeVariables #-}
 {- |
    Module      : Text.Pandoc.Readers.CommonMark
-   Copyright   : Copyright (C) 2015-2017 John MacFarlane
+   Copyright   : Copyright (C) 2015-2024 John MacFarlane
    License     : GNU GPL, version 2 or above
 
    Maintainer  : John MacFarlane <jgm@berkeley.edu>
@@ -32,204 +17,180 @@
 module Text.Pandoc.Readers.CommonMark (readCommonMark)
 where
 
-import CMarkGFM
-import Control.Monad.State
-import Data.Char (isAlphaNum, isLetter, isSpace, toLower)
-import Data.List (groupBy)
-import qualified Data.Map as Map
-import Data.Text (Text, unpack)
-import Text.Pandoc.Class (PandocMonad)
+import Commonmark
+import Commonmark.Extensions
+import Commonmark.Pandoc
+import Data.Text (Text)
+import Text.Pandoc.Class.PandocMonad (PandocMonad)
 import Text.Pandoc.Definition
-import Text.Pandoc.Emoji (emojis)
+import Text.Pandoc.Builder as B
 import Text.Pandoc.Options
-import Text.Pandoc.Shared (stringify)
-import Text.Pandoc.Walk (walkM)
+import Text.Pandoc.Readers.Metadata (yamlMetaBlock)
+import Control.Monad (MonadPlus(mzero))
+import Control.Monad.Except (  MonadError(throwError) )
+import Data.Functor.Identity (runIdentity)
+import Data.Typeable
+import Text.Pandoc.Parsing (runParserT, getInput, getPosition,
+                            runF, defaultParserState, option, many1, anyChar,
+                            Sources(..), ToSources(..), ParsecT, Future,
+                            incSourceLine, fromParsecError)
+import Text.Pandoc.Walk (walk)
+import qualified Data.Text as T
+import qualified Data.Attoparsec.Text as A
+import Control.Applicative ((<|>))
 
 -- | Parse a CommonMark formatted string into a 'Pandoc' structure.
-readCommonMark :: PandocMonad m => ReaderOptions -> Text -> m Pandoc
-readCommonMark opts s = return $
-  (if isEnabled Ext_gfm_auto_identifiers opts
-      then addHeaderIdentifiers
-      else id) $
-  nodeToPandoc opts $ commonmarkToNode opts' exts s
-  where opts' = [ optSmart | isEnabled Ext_smart opts ]
-        exts = [ extStrikethrough | isEnabled Ext_strikeout opts ] ++
-               [ extTable | isEnabled Ext_pipe_tables opts ] ++
-               [ extAutolink | isEnabled Ext_autolink_bare_uris opts ]
+readCommonMark :: (PandocMonad m, ToSources a)
+               => ReaderOptions -> a -> m Pandoc
+readCommonMark opts s
+  | isEnabled Ext_yaml_metadata_block opts = do
+    let sources = toSources s
+    let firstSourceName = case unSources sources of
+                               ((pos,_):_) -> sourceName pos
+                               _ -> ""
+    let toks = concatMap sourceToToks (unSources sources)
+    res <- runParserT (do meta <- yamlMetaBlock (metaValueParser opts)
+                          pos <- getPosition
+                          rest <- getInput
+                          let rest' = case rest of
+                                -- update position of first source (#7863):
+                                Sources ((_,t):xs) -> Sources ((pos,t):xs)
+                                _ -> rest
+                          return (meta, rest'))
+                      defaultParserState firstSourceName sources
+    case res of
+      Left _ -> readCommonMarkBody opts sources toks
+      Right (meta, rest) -> do
+        -- strip off metadata section and parse body
+        let body = concatMap sourceToToks (unSources rest)
+        Pandoc _ bs <- readCommonMarkBody opts sources body
+        return $ Pandoc (runF meta defaultParserState) bs
+  | otherwise = do
+    let sources = toSources s
+    let toks = concatMap sourceToToks (unSources sources)
+    readCommonMarkBody opts sources toks
 
-convertEmojis :: String -> String
-convertEmojis (':':xs) =
-   case break (==':') xs of
-        (ys,':':zs) ->
-           case Map.lookup ys emojis of
-                Just s  -> s ++ convertEmojis zs
-                Nothing -> ':' : ys ++ convertEmojis (':':zs)
-        _ -> ':':xs
-convertEmojis (x:xs) = x : convertEmojis xs
-convertEmojis [] = []
+makeFigures :: Block -> Block
+makeFigures (Para [Image (ident,classes,kvs) alt (src,tit)])
+  | not (null alt) =
+  Figure (ident,[],[])
+    (Caption Nothing [Plain alt])
+    [Plain [Image ("",classes,kvs) alt (src,tit)]]
+makeFigures b = b
 
-addHeaderIdentifiers :: Pandoc -> Pandoc
-addHeaderIdentifiers doc = evalState (walkM addHeaderId doc) mempty
+sourceToToks :: (SourcePos, Text) -> [Tok]
+sourceToToks (pos, s) = map adjust $ tokenize (sourceName pos) s
+ where
+   adjust = case sourceLine pos of
+              1 -> id
+              n -> \tok -> tok{ tokPos =
+                                  incSourceLine (tokPos tok) (n - 1) }
 
-addHeaderId :: Block -> State (Map.Map String Int) Block
-addHeaderId (Header lev (_,classes,kvs) ils) = do
-  idmap <- get
-  let ident = toIdent ils
-  ident' <- case Map.lookup ident idmap of
-                 Nothing -> do
-                   put (Map.insert ident 1 idmap)
-                   return ident
-                 Just i -> do
-                   put (Map.adjust (+ 1) ident idmap)
-                   return (ident ++ "-" ++ show i)
-  return $ Header lev (ident',classes,kvs) ils
-addHeaderId x = return x
 
-toIdent :: [Inline] -> String
-toIdent =   map (\c -> if isSpace c then '-' else c)
-          . filter (\c -> isLetter c || isAlphaNum c || isSpace c ||
-                           c == '_' || c == '-')
-          . map toLower . stringify
+metaValueParser :: Monad m
+                => ReaderOptions -> ParsecT Sources st m (Future st MetaValue)
+metaValueParser opts = do
+  inp <- option "" $ T.pack <$> many1 anyChar
+  let toks = concatMap sourceToToks (unSources (toSources inp))
+  case runIdentity (parseCommonmarkWith (specFor opts) toks) of
+     Left _ -> mzero
+     Right (Cm bls :: Cm () Blocks) -> return $ return $ B.toMetaValue bls
 
-nodeToPandoc :: ReaderOptions -> Node -> Pandoc
-nodeToPandoc opts (Node _ DOCUMENT nodes) =
-  Pandoc nullMeta $ foldr (addBlock opts) [] nodes
-nodeToPandoc opts n =  -- shouldn't happen
-  Pandoc nullMeta $ foldr (addBlock opts) [] [n]
+readCommonMarkBody :: PandocMonad m => ReaderOptions -> Sources -> [Tok] -> m Pandoc
+readCommonMarkBody opts s toks =
+  (if isEnabled Ext_implicit_figures opts
+      then walk makeFigures
+      else id) .
+  (if isEnabled Ext_tex_math_gfm opts
+      then walk handleGfmMath
+      else id) .
+  (if readerStripComments opts
+      then walk stripBlockComments . walk stripInlineComments
+      else id) <$>
+  if isEnabled Ext_sourcepos opts
+     then case runIdentity (parseCommonmarkWith (specFor opts) toks) of
+            Left err -> throwError $ fromParsecError s err
+            Right (Cm bls :: Cm SourceRange Blocks) -> return $ B.doc bls
+     else case runIdentity (parseCommonmarkWith (specFor opts) toks) of
+            Left err -> throwError $ fromParsecError s err
+            Right (Cm bls :: Cm () Blocks) -> return $ B.doc bls
 
-addBlocks :: ReaderOptions -> [Node] -> [Block]
-addBlocks opts = foldr (addBlock opts) []
+handleGfmMath :: Block -> Block
+handleGfmMath (CodeBlock ("",["math"],[]) raw) = Para [Math DisplayMath raw]
+handleGfmMath x = walk handleGfmMathInline x
 
-addBlock :: ReaderOptions -> Node -> [Block] -> [Block]
-addBlock opts (Node _ PARAGRAPH nodes) =
-  (Para (addInlines opts nodes) :)
-addBlock _ (Node _ THEMATIC_BREAK _) =
-  (HorizontalRule :)
-addBlock opts (Node _ BLOCK_QUOTE nodes) =
-  (BlockQuote (addBlocks opts nodes) :)
-addBlock opts (Node _ (HTML_BLOCK t) _)
-  | isEnabled Ext_raw_html opts = (RawBlock (Format "html") (unpack t) :)
-  | otherwise                 = id
--- Note:  the cmark parser will never generate CUSTOM_BLOCK,
--- so we don't need to handle it:
-addBlock _ (Node _ (CUSTOM_BLOCK _onEnter _onExit) _nodes) =
-  id
-addBlock _ (Node _ (CODE_BLOCK info t) _) =
-  (CodeBlock ("", take 1 (words (unpack info)), []) (unpack t) :)
-addBlock opts (Node _ (HEADING lev) nodes) =
-  (Header lev ("",[],[]) (addInlines opts nodes) :)
-addBlock opts (Node _ (LIST listAttrs) nodes) =
-  (constructor (map (setTightness . addBlocks opts . children) nodes) :)
-  where constructor = case listType listAttrs of
-                       BULLET_LIST  -> BulletList
-                       ORDERED_LIST -> OrderedList
-                                         (start, DefaultStyle, delim)
-        start = listStart listAttrs
-        setTightness = if listTight listAttrs
-                           then map paraToPlain
-                           else id
-        paraToPlain (Para xs) = Plain xs
-        paraToPlain x         = x
-        delim = case listDelim listAttrs of
-                     PERIOD_DELIM -> Period
-                     PAREN_DELIM  -> OneParen
-addBlock opts (Node _ (TABLE alignments) nodes) =
-  (Table [] aligns widths headers rows :)
-  where aligns = map fromTableCellAlignment alignments
-        fromTableCellAlignment NoAlignment   = AlignDefault
-        fromTableCellAlignment LeftAligned   = AlignLeft
-        fromTableCellAlignment RightAligned  = AlignRight
-        fromTableCellAlignment CenterAligned = AlignCenter
-        widths = replicate numcols 0.0
-        numcols = if null rows'
-                     then 0
-                     else maximum $ map length rows'
-        rows' = map toRow $ filter isRow nodes
-        (headers, rows) = case rows' of
-                               (h:rs) -> (h, rs)
-                               []     -> ([], [])
-        isRow (Node _ TABLE_ROW _) = True
-        isRow _                    = False
-        isCell (Node _ TABLE_CELL _) = True
-        isCell _                     = False
-        toRow (Node _ TABLE_ROW ns) = map toCell $ filter isCell ns
-        toRow (Node _ t _) = error $ "toRow encountered non-row " ++ show t
-        toCell (Node _ TABLE_CELL []) = []
-        toCell (Node _ TABLE_CELL (n:ns))
-          | isBlockNode n = addBlocks opts (n:ns)
-          | otherwise     = [Plain (addInlines opts (n:ns))]
-        toCell (Node _ t _) = error $ "toCell encountered non-cell " ++ show t
-addBlock _ (Node _ TABLE_ROW _) = id -- handled in TABLE
-addBlock _ (Node _ TABLE_CELL _) = id -- handled in TABLE
-addBlock _ _ = id
+handleGfmMathInline :: Inline -> Inline
+handleGfmMathInline (Math InlineMath math'') =
+  let math' = T.replace "\\\\{" "\\{" . T.replace "\\\\}" "\\}" $ math''
+              -- see #10631
+      (ticks, rest) = T.span (== '`') math'
+  in  if T.null ticks
+         then Math InlineMath math'
+         else case T.stripSuffix ticks rest of
+                Just middle | not (T.null middle) && (T.last middle /= '`')
+                             -> Math InlineMath middle
+                _ -> Math InlineMath math'
+handleGfmMathInline x = x
 
-isBlockNode :: Node -> Bool
-isBlockNode (Node _ nodetype _) =
-  case nodetype of
-       DOCUMENT          -> True
-       THEMATIC_BREAK    -> True
-       PARAGRAPH         -> True
-       BLOCK_QUOTE       -> True
-       HTML_BLOCK _      -> True
-       CUSTOM_BLOCK _ _  -> True
-       CODE_BLOCK _ _    -> True
-       HEADING _         -> True
-       LIST _            -> True
-       ITEM              -> True
-       TEXT _            -> False
-       SOFTBREAK         -> False
-       LINEBREAK         -> False
-       HTML_INLINE _     -> False
-       CUSTOM_INLINE _ _ -> False
-       CODE _            -> False
-       EMPH              -> False
-       STRONG            -> False
-       LINK _ _          -> False
-       IMAGE _ _         -> False
-       STRIKETHROUGH     -> False
-       TABLE _           -> False
-       TABLE_ROW         -> False
-       TABLE_CELL        -> False
+stripBlockComments :: Block -> Block
+stripBlockComments (RawBlock (B.Format "html") s) =
+  RawBlock (B.Format "html") (removeComments s)
+stripBlockComments x = x
 
-children :: Node -> [Node]
-children (Node _ _ ns) = ns
+stripInlineComments :: Inline -> Inline
+stripInlineComments (RawInline (B.Format "html") s) =
+  RawInline (B.Format "html") (removeComments s)
+stripInlineComments x = x
 
-addInlines :: ReaderOptions -> [Node] -> [Inline]
-addInlines opts = foldr (addInline opts) []
+removeComments :: Text -> Text
+removeComments s =
+  either (const s) id $ A.parseOnly pRemoveComments s
+ where
+  pRemoveComments = mconcat <$> A.many'
+    ("" <$ (A.string "<!--" *> A.scan (0 :: Int) scanChar <* A.char '>') <|>
+     (A.takeWhile1 (/= '<')) <|>
+     (A.string "<"))
+  scanChar st c =
+    case c of
+      '-' -> Just (st + 1)
+      '>' | st >= 2 -> Nothing
+      _ -> Just 0
 
-addInline :: ReaderOptions -> Node -> [Inline] -> [Inline]
-addInline opts (Node _ (TEXT t) _) = (map toinl clumps ++)
-  where raw = unpack t
-        clumps = groupBy samekind raw
-        samekind ' ' ' ' = True
-        samekind ' ' _   = False
-        samekind _   ' ' = False
-        samekind _  _    = True
-        toinl (' ':_) = Space
-        toinl xs      = Str $ if isEnabled Ext_emoji opts
-                                 then convertEmojis xs
-                                 else xs
-addInline _ (Node _ LINEBREAK _) = (LineBreak :)
-addInline opts (Node _ SOFTBREAK _)
-  | isEnabled Ext_hard_line_breaks opts = (LineBreak :)
-  | otherwise                           = (SoftBreak :)
-addInline opts (Node _ (HTML_INLINE t) _)
-  | isEnabled Ext_raw_html opts = (RawInline (Format "html") (unpack t) :)
-  | otherwise                 = id
--- Note:  the cmark parser will never generate CUSTOM_BLOCK,
--- so we don't need to handle it:
-addInline _ (Node _ (CUSTOM_INLINE _onEnter _onExit) _nodes) =
-  id
-addInline _ (Node _ (CODE t) _) =
-  (Code ("",[],[]) (unpack t) :)
-addInline opts (Node _ EMPH nodes) =
-  (Emph (addInlines opts nodes) :)
-addInline opts (Node _ STRONG nodes) =
-  (Strong (addInlines opts nodes) :)
-addInline opts (Node _ STRIKETHROUGH nodes) =
-  (Strikeout (addInlines opts nodes) :)
-addInline opts (Node _ (LINK url title) nodes) =
-  (Link nullAttr (addInlines opts nodes) (unpack url, unpack title) :)
-addInline opts (Node _ (IMAGE url title) nodes) =
-  (Image nullAttr (addInlines opts nodes) (unpack url, unpack title) :)
-addInline _ _ = id
+specFor :: (Monad m, Typeable m, Typeable a,
+            Rangeable (Cm a Inlines), Rangeable (Cm a Blocks))
+        => ReaderOptions -> SyntaxSpec m (Cm a Inlines) (Cm a Blocks)
+specFor opts = foldr ($) defaultSyntaxSpec exts
+ where
+  exts = [ (hardLineBreaksSpec <>) | isEnabled Ext_hard_line_breaks opts ] ++
+         [ (smartPunctuationSpec <>) | isEnabled Ext_smart opts ] ++
+         [ (strikethroughSpec <>) | isEnabled Ext_strikeout opts ] ++
+         [ (superscriptSpec <>) | isEnabled Ext_superscript opts ] ++
+         [ (subscriptSpec <>) | isEnabled Ext_subscript opts ] ++
+         [ (mathSpec <>) | isEnabled Ext_tex_math_dollars opts ] ++
+         [ (fancyListSpec <>) | isEnabled Ext_fancy_lists opts ] ++
+         [ (fencedDivSpec <>) | isEnabled Ext_fenced_divs opts ] ++
+         [ (bracketedSpanSpec <>) | isEnabled Ext_bracketed_spans opts ] ++
+         [ (rawAttributeSpec <>) | isEnabled Ext_raw_attribute opts ] ++
+         [ (attributesSpec <>) | isEnabled Ext_attributes opts ] ++
+         [ (alertSpec <>) | isEnabled Ext_alerts opts ] ++
+         [ (<> pipeTableSpec) | isEnabled Ext_pipe_tables opts ] ++
+            -- see #6739
+         [ (autolinkSpec <>) | isEnabled Ext_autolink_bare_uris opts ] ++
+         [ (emojiSpec <>) | isEnabled Ext_emoji opts ] ++
+         [ (autoIdentifiersSpec <>)
+           | isEnabled Ext_gfm_auto_identifiers opts
+           , not (isEnabled Ext_ascii_identifiers opts) ] ++
+         [ (autoIdentifiersAsciiSpec <>)
+           | isEnabled Ext_gfm_auto_identifiers opts
+           , isEnabled Ext_ascii_identifiers opts ] ++
+         [ (implicitHeadingReferencesSpec <>)
+           | isEnabled Ext_implicit_header_references opts ] ++
+         [ (footnoteSpec <>) | isEnabled Ext_footnotes opts ] ++
+         [ (definitionListSpec <>) | isEnabled Ext_definition_lists opts ] ++
+         [ (taskListSpec <>) | isEnabled Ext_task_lists opts ] ++
+         [ (wikilinksSpec TitleAfterPipe <>)
+           | isEnabled Ext_wikilinks_title_after_pipe opts ] ++
+         [ (wikilinksSpec TitleBeforePipe <>)
+           | isEnabled Ext_wikilinks_title_before_pipe opts ] ++
+         [ (rebaseRelativePathsSpec <>)
+           | isEnabled Ext_rebase_relative_paths opts ]
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,26 +1,4 @@
-{-
-  Copyright (C) 2017 Sascha Wilde <wilde@sha-bang.de>
-
-  partly based on all the other readers, especialy 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
--}
-
+{-# LANGUAGE OverloadedStrings #-}
 {- |
    Module      : Text.Pandoc.Readers.Creole
    Copyright   : Copyright (C) 2017 Sascha Wilde
@@ -35,39 +13,37 @@
 module Text.Pandoc.Readers.Creole ( readCreole
                                   ) where
 
-import Control.Monad.Except (guard, liftM2, throwError)
+import Control.Monad
+import Control.Monad.Except (throwError)
 import qualified Data.Foldable as F
 import Data.Maybe (fromMaybe)
-import Data.Monoid
 import Data.Text (Text)
 import qualified Data.Text as T
 import qualified Text.Pandoc.Builder as B
-import Text.Pandoc.Class (PandocMonad (..))
+import Text.Pandoc.Class.PandocMonad (PandocMonad (..))
 import Text.Pandoc.Definition
 import Text.Pandoc.Options
 import Text.Pandoc.Parsing hiding (enclosed)
-import Text.Pandoc.Shared (crFilter)
 
-
 -- | Read creole from an input string and return a Pandoc document.
-readCreole :: PandocMonad m
+readCreole :: (PandocMonad m, ToSources a)
           => ReaderOptions
-          -> Text
+          -> a
           -> m Pandoc
 readCreole opts s = do
-  res <- readWithM parseCreole def{ stateOptions = opts }
-             (T.unpack (crFilter s) ++ "\n\n")
+  let sources = ensureFinalNewlines 2 (toSources s)
+  res <- readWithM parseCreole def{ stateOptions = opts } sources
   case res of
        Left e  -> throwError e
        Right d -> return d
 
-type CRLParser = ParserT [Char] ParserState
+type CRLParser = ParsecT Sources ParserState
 
 --
 -- Utility functions
 --
 
-(<+>) :: (Monad m, Monoid a) => m a -> m a -> m a
+(<+>) :: (Monad m, Semigroup a) => m a -> m a -> m a
 (<+>) = liftM2 (<>)
 
 -- we have to redefine `enclosed' from Text.Pandoc.Parsing, because it
@@ -93,7 +69,6 @@
   eof
   return $ B.doc bs
 
-
 --
 -- block parsers
 --
@@ -115,9 +90,9 @@
                                              >> manyTill content nowikiEnd)
   where
     content = brackets <|> line
-    brackets = try $ option "" ((:[]) <$> newline)
-               <+> (char ' ' >> (many (char ' ') <+> string "}}}") <* eol)
-    line = option "" ((:[]) <$> newline) <+> manyTill anyChar eol
+    brackets = try $ option "" (T.singleton <$> newline)
+               <+> (char ' ' >> (manyChar (char ' ') <+> textStr "}}}") <* eol)
+    line = option "" (T.singleton <$> newline) <+> manyTillChar anyChar eol
     eol = lookAhead $ try $ nowikiEnd <|> newline
     nowikiStart = optional newline >> string "{{{" >> skipMany spaceChar >> newline
     nowikiEnd = try $ linebreak >> string "}}}" >> skipMany spaceChar >> newline
@@ -129,7 +104,7 @@
     fmap length (many1 (char '='))
   guard $ level <= 6
   skipSpaces
-  content <- B.str <$> manyTill (noneOf "\n") headerEnd
+  content <- B.str <$> manyTillChar (noneOf "\n") headerEnd
   return $ B.header level content
   where
     headerEnd = try $ skipSpaces >> many (char '=') >> skipSpaces >> newline
@@ -174,7 +149,7 @@
                  <$> (string "|=" >> many1Till inline cellEnd)
     row = try $ skipSpaces >> many1Till cell rowEnd
     cell = B.plain . B.trimInlines . mconcat
-           <$> (char '|' >> many1Till inline cellEnd)
+           <$> (char '|' >> manyTill inline cellEnd)
     rowEnd = try $ optional (char '|') >> skipSpaces >> newline
     cellEnd = lookAhead $ try $ char '|' <|> rowEnd
 
@@ -227,7 +202,7 @@
 
 escapedChar :: PandocMonad m => CRLParser m B.Inlines
 escapedChar =
-  fmap (B.str . (:[])) (try $ char '~' >> noneOf "\t\n ")
+  fmap (B.str . T.singleton) (try $ char '~' >> noneOf "\t\n ")
 
 escapedLink :: PandocMonad m => CRLParser m B.Inlines
 escapedLink = try $ do
@@ -240,8 +215,8 @@
   (orig, src) <- wikiImg
   return $ B.image src "" (B.str orig)
   where
-    linkSrc = many $ noneOf "|}\n\r\t"
-    linkDsc = char '|' >> many (noneOf "}\n\r\t")
+    linkSrc = manyChar $ noneOf "|}\n\r\t"
+    linkDsc = char '|' >> manyChar (noneOf "}\n\r\t")
     wikiImg = try $ do
       string "{{"
       src <- linkSrc
@@ -254,11 +229,11 @@
   (orig, src) <- uriLink <|> wikiLink
   return $ B.link src "" orig
   where
-    linkSrc = many $ noneOf "|]\n\r\t"
-    linkDsc :: PandocMonad m => String -> CRLParser m B.Inlines
+    linkSrc = manyChar $ noneOf "|]\n\r\t"
+    linkDsc :: PandocMonad m => Text -> CRLParser m B.Inlines
     linkDsc otxt = B.str
                    <$> try (option otxt
-                         (char '|' >> many (noneOf "]\n\r\t")))
+                         (char '|' >> manyChar (noneOf "]\n\r\t")))
     linkImg = try $ char '|' >> image
     wikiLink = try $ do
       string "[["
@@ -271,13 +246,13 @@
       return (B.str orig, src)
 
 inlineNowiki :: PandocMonad m => CRLParser m B.Inlines
-inlineNowiki = B.code <$> (start >> manyTill (noneOf "\n\r") end)
+inlineNowiki = B.code <$> (start >> manyTillChar (noneOf "\n\r") end)
   where
     start = try $ string "{{{"
     end = try $ string "}}}" >> lookAhead (noneOf "}")
 
 placeholder :: PandocMonad m => CRLParser m B.Inlines
--- The semantics of the placeholder is basicallly implementation
+-- The semantics of the placeholder is basically implementation
 -- dependent, so there is no way to DTRT for all cases.
 -- So for now we just drop them.
 placeholder = B.text <$> try (string "<<<" >> manyTill anyChar (string ">>>")
@@ -294,11 +269,11 @@
         innerNewline = return B.space
 
 symbol :: PandocMonad m => CRLParser m B.Inlines
-symbol = fmap (B.str . (:[])) (oneOf specialChars)
+symbol = fmap (B.str . T.singleton) (oneOf specialChars)
 
 str :: PandocMonad m => CRLParser m B.Inlines
 str = let strChar = noneOf ("\t\n " ++ specialChars) in
-        fmap B.str (many1 strChar)
+        fmap B.str (many1Char strChar)
 
 bold :: PandocMonad m => CRLParser m B.Inlines
 bold = B.strong . mconcat <$>
diff --git a/src/Text/Pandoc/Readers/CslJson.hs b/src/Text/Pandoc/Readers/CslJson.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Readers/CslJson.hs
@@ -0,0 +1,54 @@
+{-# LANGUAGE OverloadedStrings #-}
+{- |
+   Module      : Text.Pandoc.Readers.CslJson
+   Copyright   : Copyright (C) 2020-2024 John MacFarlane
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : John MacFarlane <jgm@berkeley.edu>
+   Stability   : alpha
+   Portability : portable
+
+Parses CSL JSON bibliographies into a Pandoc document
+with empty body and `references` and `nocite` fields
+in the metadata.  A wildcard `nocite` is used so that
+if the document is rendered in another format, the
+entire bibliography will be printed.
+
+<https://citeproc-js.readthedocs.io/en/latest/csl-json/markup.html>.
+-}
+module Text.Pandoc.Readers.CslJson
+  ( readCslJson )
+where
+
+import Text.Pandoc.Options
+import Text.Pandoc.Definition
+import Text.Pandoc.Builder (setMeta, cite, str)
+import qualified Text.Pandoc.UTF8 as UTF8
+import qualified Data.Text as T
+import Text.Pandoc.Error (PandocError(..))
+import Text.Pandoc.Class (PandocMonad)
+import Text.Pandoc.Citeproc.CslJson (cslJsonToReferences)
+import Text.Pandoc.Citeproc.MetaValue (referenceToMetaValue)
+import Control.Monad.Except (throwError)
+import Text.Pandoc.Sources (ToSources(..), sourcesToText)
+
+-- | Read CSL JSON from an input string and return a Pandoc document.
+-- The document will have only metadata, with an empty body.
+-- The metadata will contain a `references` field with the
+-- bibliography entries, and a `nocite` field with the wildcard `[@*]`.
+readCslJson :: (PandocMonad m, ToSources a)
+            => ReaderOptions -> a -> m Pandoc
+readCslJson _opts x =
+  case cslJsonToReferences (UTF8.fromText $ sourcesToText $ toSources x) of
+    Left e -> throwError $ PandocParseError $ T.pack e
+    Right refs -> return $ setMeta "references"
+                              (map referenceToMetaValue refs)
+                         . setMeta "nocite"
+                            (cite [Citation {citationId = "*"
+                                            , citationPrefix = []
+                                            , citationSuffix = []
+                                            , citationMode = NormalCitation
+                                            , citationNoteNum = 0
+                                            , citationHash = 0}]
+                                            (str "[@*]"))
+                         $ Pandoc nullMeta []
diff --git a/src/Text/Pandoc/Readers/Djot.hs b/src/Text/Pandoc/Readers/Djot.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Readers/Djot.hs
@@ -0,0 +1,273 @@
+{-# LANGUAGE RankNTypes #-}
+{-# LANGUAGE FlexibleInstances #-}
+{-# LANGUAGE UndecidableInstances #-}
+{-# LANGUAGE OverloadedStrings #-}
+{-# LANGUAGE ScopedTypeVariables #-}
+
+{- |
+   Module      : Text.Pandoc.Readers.Djot
+   Copyright   : Copyright (C) 2024 John MacFarlane
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : John MacFarlane <jgm@berkeley.edu>
+   Stability   : alpha
+   Portability : portable
+
+Reads and evaluates a Djot document as a Pandoc AST.
+-}
+module Text.Pandoc.Readers.Djot
+  ( readDjot
+  )
+where
+
+import Text.Pandoc.Class
+import Text.Pandoc.Sources
+import Text.Parsec.Pos (newPos)
+import Text.Pandoc.Options
+import Text.Pandoc.Definition
+import Text.Pandoc.Shared (addPandocAttributes, tshow)
+import qualified Text.Pandoc.UTF8 as UTF8
+import Djot (ParseOptions(..), SourcePosOption(..), parseDoc, Pos(..))
+import qualified Djot.AST as D
+import Text.Pandoc.Error (PandocError(..))
+import Control.Monad.Except (throwError)
+import qualified Data.Text as T
+import Text.Pandoc.Builder
+import Text.Pandoc.Logging
+import Text.Pandoc.Emoji (emojiToInline)
+import Control.Monad.Reader
+import qualified Data.Foldable as F
+import Data.ByteString (ByteString)
+-- import Debug.Trace
+
+-- | Read Djot from an input string and return a Pandoc document.
+readDjot :: (PandocMonad m, ToSources a) => ReaderOptions -> a -> m Pandoc
+readDjot opts inp = do
+  let sources = toSources inp
+  case parseDoc ParseOptions{ sourcePositions =
+                              if isEnabled Ext_sourcepos opts
+                                 then AllSourcePos
+                                 else NoSourcePos }
+          (UTF8.fromText $ sourcesToText sources) of
+    Left e -> throwError $ PandocParseError $ T.pack $ show e
+    Right d ->
+      runReaderT (doc <$> convertBlocks (D.docBlocks d))
+        Env{ references = D.docReferences d <> D.docAutoReferences d
+           , footnotes = D.docFootnotes d
+           }
+
+data Env =
+  Env{ references :: D.ReferenceMap
+     , footnotes :: D.NoteMap
+     }
+  deriving (Show, Ord, Eq)
+
+convertBlocks :: PandocMonad m => D.Blocks -> ReaderT Env m Blocks
+convertBlocks =  fmap mconcat . mapM convertBlock . F.toList . D.unMany
+
+convertBlock :: PandocMonad m => D.Node D.Block -> ReaderT Env m Blocks
+convertBlock (D.Node pos attr bl) =  addAttrToBlock pos attr <$>
+  case bl of
+    D.Para ils -> para <$> convertInlines ils
+    D.Section bls -> divWith ("",["section"],[]) <$> convertBlocks bls
+    D.Heading lev ils -> header lev <$> convertInlines ils
+    D.BlockQuote bls -> blockQuote <$> convertBlocks bls
+    D.CodeBlock lang bs -> pure $
+      codeBlockWith ("", [UTF8.toText lang], []) $ UTF8.toText bs
+    D.Div bls -> divWith nullAttr <$> convertBlocks bls
+    D.OrderedList olattr listSpacing items ->
+      orderedListWith olattr' .
+        (case listSpacing of
+           D.Tight -> map toTight
+           D.Loose -> id) <$> mapM convertBlocks items
+     where
+       olattr' = ( D.orderedListStart olattr
+                 , case D.orderedListStyle olattr of
+                     D.Decimal -> Decimal
+                     D.LetterUpper -> UpperAlpha
+                     D.LetterLower -> LowerAlpha
+                     D.RomanUpper -> UpperRoman
+                     D.RomanLower -> LowerRoman
+                 , case D.orderedListDelim olattr of
+                     D.RightPeriod -> Period
+                     D.RightParen -> OneParen
+                     D.LeftRightParen -> TwoParens
+                 )
+    D.BulletList listSpacing items ->
+        bulletList .
+        (case listSpacing of
+           D.Tight -> map toTight
+           D.Loose -> id) <$> mapM convertBlocks items
+    D.TaskList listSpacing items ->
+        bulletList .
+        (case listSpacing of
+           D.Tight -> map toTight
+           D.Loose -> id) <$> mapM toTaskListItem items
+    D.DefinitionList listSpacing items ->
+      definitionList .
+        (case listSpacing of
+           D.Tight -> map (\(t,d) -> (t, map toTight d))
+           D.Loose -> id) <$> mapM toDlItem items
+     where
+       toDlItem (ils,bls) = (,) <$> convertInlines ils
+                                <*> ((:[]) <$> convertBlocks bls)
+    D.ThematicBreak -> pure horizontalRule
+    D.Table mbCaption rows -> do
+      capt <- case mbCaption of
+                Just (D.Caption bls') ->
+                  Caption Nothing . toList <$> convertBlocks bls'
+                Nothing -> pure $ Caption Nothing mempty
+      let toAlign D.AlignLeft = AlignLeft
+          toAlign D.AlignRight = AlignRight
+          toAlign D.AlignCenter = AlignCenter
+          toAlign D.AlignDefault = AlignDefault
+      let toColSpec (D.Cell _ align _) = (toAlign align, ColWidthDefault)
+      let colspecs = case rows of
+                      [] -> []
+                      (cells:_) -> map toColSpec cells
+      let (headrow, rest) =
+            case rows of
+              (r@(D.Cell D.HeadCell _ _ : _) : rs) -> (r, rs)
+              _ -> ([],rows)
+      let getBody bods row =
+            case row of
+              (D.Cell D.HeadCell _ _ : _) ->
+                   case bods of
+                     [] -> [([row],[])]
+                     ([],_):_ -> (([row],[]):bods)
+                     (hs,bs):rs -> (hs,row:bs):rs
+              _ -> case bods of
+                     (hs,bs):rs -> (hs,row:bs):rs
+                     [] -> [([],[row])]
+      let reverseSnd (as,bs) = (as,reverse bs)
+      let bodies = reverse $ map reverseSnd $ F.foldl' getBody [] rest
+      let toCell (D.Cell _ al ils) =
+            Cell nullAttr (toAlign al) (RowSpan 1) (ColSpan 1)
+                   . (\is -> [Para $ toList is]) <$> convertInlines ils
+      let toRow = fmap (Row nullAttr) . mapM toCell
+      thead <- TableHead mempty <$> mapM toRow [headrow]
+      let toTableBody (hs, rs) =
+            TableBody mempty (RowHeadColumns 0) <$>
+              mapM toRow hs <*> mapM toRow rs
+      tbodies <- mapM toTableBody bodies
+      let tfoot = TableFoot mempty []
+      pure $ singleton $ Table mempty capt colspecs thead tbodies tfoot
+    D.RawBlock (D.Format fmt) bs -> pure $
+      rawBlock (UTF8.toText fmt) (UTF8.toText bs)
+
+addAttrToBlock :: Pos -> D.Attr -> Blocks -> Blocks
+addAttrToBlock pos (D.Attr as) =
+  addPandocAttributes $
+    case pos of
+        NoPos -> textkvs
+        Pos sl sc el ec ->
+          ("data-pos", tshow sl <> ":" <> tshow sc <>
+                 "-" <> tshow el <> ":" <> tshow ec) : textkvs
+     where
+       textkvs = (map (\(k,v) -> (UTF8.toText k, UTF8.toText v))
+                    (filter (not . internalAttribute) as))
+
+addAttrToInline :: Pos -> D.Attr -> Inlines -> Inlines
+addAttrToInline pos (D.Attr as) =
+  addPandocAttributes $
+    case pos of
+        NoPos -> textkvs
+        Pos sl sc el ec ->
+          ("data-pos", tshow sl <> ":" <> tshow sc <>
+                 "-" <> tshow el <> ":" <> tshow ec) : textkvs
+     where
+       textkvs = (map (\(k,v) -> (UTF8.toText k, UTF8.toText v))
+                    (filter (not . internalAttribute) as))
+
+convertInlines :: PandocMonad m => D.Inlines -> ReaderT Env m Inlines
+convertInlines = fmap mconcat . mapM convertInline . F.toList . D.unMany
+
+convertInline :: PandocMonad m => D.Node D.Inline -> ReaderT Env m Inlines
+convertInline (D.Node pos attr il) = addAttrToInline pos attr <$>
+  case il of
+    D.Str bs -> pure $ text (UTF8.toText bs)
+    D.Emph ils -> emph <$> convertInlines ils
+    D.Strong ils -> strong <$> convertInlines ils
+    D.Highlight ils -> spanWith ("",["mark"],[]) <$> convertInlines ils
+    D.Insert ils -> spanWith ("",["inserted"],[]) <$> convertInlines ils
+    D.Delete ils -> spanWith ("",["deleted"],[]) <$> convertInlines ils
+    D.Subscript ils -> subscript <$> convertInlines ils
+    D.Superscript ils -> superscript <$> convertInlines ils
+    D.Span ils -> spanWith nullAttr <$> convertInlines ils
+    D.Quoted D.DoubleQuotes ils -> doubleQuoted <$> convertInlines ils
+    D.Quoted D.SingleQuotes ils -> singleQuoted <$> convertInlines ils
+    D.Verbatim bs -> pure $ code (UTF8.toText bs)
+    D.Symbol bs -> pure $
+      let s = UTF8.toText bs
+       in maybe (spanWith ("",["symbol"],[]) (str s)) singleton $ emojiToInline s
+    D.Math sty bs -> pure $
+      (case sty of
+        D.DisplayMath -> displayMath
+        D.InlineMath -> math) (UTF8.toText bs)
+    D.Link ils target ->
+      case target of
+        D.Direct url -> link (UTF8.toText url) "" <$> convertInlines ils
+        D.Reference label -> do
+          refs <- asks references
+          case D.lookupReference label refs of
+            Just (url, lattr) ->
+              addAttrToInline pos lattr .
+                link (UTF8.toText url) "" <$> convertInlines ils
+            Nothing -> do
+              report $ ReferenceNotFound (UTF8.toText label) (newPos "" 0 0)
+              link "" "" <$> convertInlines ils
+    D.Image ils target ->
+      case target of
+        D.Direct url -> image (UTF8.toText url) "" <$> convertInlines ils
+        D.Reference label -> do
+          refs <- asks references
+          case D.lookupReference label refs of
+            Just (url, lattr) ->
+              addAttrToInline pos lattr .
+                image (UTF8.toText url) "" <$> convertInlines ils
+            Nothing -> do
+              report $ ReferenceNotFound (UTF8.toText label) (newPos "" 0 0)
+              image "" "" <$> convertInlines ils
+    D.FootnoteReference bs -> do
+      notes <- asks footnotes
+      case D.lookupNote bs notes of
+        Just bls -> note <$> convertBlocks bls
+        Nothing -> do
+          -- TODO consider new warning for this?
+          report $ IgnoredElement ("Undefined footnote reference " <> tshow bs)
+          pure mempty
+    D.UrlLink bs -> do
+      let url = UTF8.toText bs
+      pure $ linkWith ("",["uri"],[]) url "" (str url)
+    D.EmailLink bs -> do
+      let email = UTF8.toText bs
+      pure $ linkWith ("",["email"],[]) ("mailto:" <> email) "" (str email)
+    D.RawInline (D.Format fbs) bs -> pure $
+      rawInline (UTF8.toText fbs) (UTF8.toText bs)
+    D.NonBreakingSpace -> pure $ str "\160"
+    D.SoftBreak -> pure softbreak
+    D.HardBreak -> pure linebreak
+
+internalAttribute :: (ByteString, ByteString) -> Bool
+internalAttribute ("_implicit",_) = True
+internalAttribute ("_autogen",_) = True
+internalAttribute _ = False
+
+toTight :: Blocks -> Blocks
+toTight (Many bls) = Many $ paraToPlain <$> bls
+ where
+   paraToPlain (Para ils) = Plain ils
+   paraToPlain x = x
+
+toTaskListItem :: PandocMonad m
+               => (D.TaskStatus, D.Blocks) -> ReaderT Env m Blocks
+toTaskListItem (status, bls) = do
+  bls' <- convertBlocks bls
+  case toList bls' of
+    (Para ils : rest) -> pure $
+      fromList $ Para (Str taskmarker : Space : ils) : rest
+    _ -> pure $ para (str taskmarker) <> bls'
+ where
+   taskmarker
+     | status == D.Complete = "[X]"
+     | otherwise = "[ ]"
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,1062 +1,1502 @@
-{-# LANGUAGE ExplicitForAll #-}
-module Text.Pandoc.Readers.DocBook ( readDocBook ) where
-import Control.Monad.State.Strict
-import Data.Char (isSpace, toUpper)
-import Data.Default
-import Data.Either (rights)
-import Data.Foldable (asum)
-import Data.Generics
-import Data.List (intersperse)
-import Data.Maybe (fromMaybe)
-import Data.Text (Text)
-import qualified Data.Text as T
-import Text.HTML.TagSoup.Entity (lookupEntity)
-import Text.Pandoc.Builder
-import Text.Pandoc.Class (PandocMonad)
-import Text.Pandoc.Options
-import Text.Pandoc.Shared (crFilter, safeRead)
-import Text.TeXMath (readMathML, writeTeX)
-import Text.XML.Light
-
-{-
-
-List of all DocBook tags, with [x] indicating implemented,
-[o] meaning intentionally left unimplemented (pass through):
-
-[o] abbrev - An abbreviation, especially one followed by a period
-[x] abstract - A summary
-[o] accel - A graphical user interface (GUI) keyboard shortcut
-[x] ackno - Acknowledgements in an Article
-[o] acronym - An often pronounceable word made from the initial
-[o] action - A response to a user event
-[o] address - A real-world address, generally a postal address
-[ ] affiliation - The institutional affiliation of an individual
-[ ] alt - Text representation for a graphical element
-[o] anchor - A spot in the document
-[x] answer - An answer to a question posed in a QandASet
-[x] appendix - An appendix in a Book or Article
-[x] appendixinfo - Meta-information for an Appendix
-[o] application - The name of a software program
-[x] area - A region defined for a Callout in a graphic or code example
-[x] areaset - A set of related areas in a graphic or code example
-[x] areaspec - A collection of regions in a graphic or code example
-[ ] arg - An argument in a CmdSynopsis
-[x] article - An article
-[x] articleinfo - Meta-information for an Article
-[ ] artpagenums - The page numbers of an article as published
-[x] attribution - The source of a block quote or epigraph
-[ ] audiodata - Pointer to external audio data
-[ ] audioobject - A wrapper for audio data and its associated meta-information
-[x] author - The name of an individual author
-[ ] authorblurb - A short description or note about an author
-[x] authorgroup - Wrapper for author information when a document has
-    multiple authors or collaborators
-[x] authorinitials - The initials or other short identifier for an author
-[o] beginpage - The location of a page break in a print version of the document
-[ ] bibliocoverage - The spatial or temporal coverage of a document
-[x] bibliodiv - A section of a Bibliography
-[x] biblioentry - An entry in a Bibliography
-[x] bibliography - A bibliography
-[ ] bibliographyinfo - Meta-information for a Bibliography
-[ ] biblioid - An identifier for a document
-[o] bibliolist - A wrapper for a set of bibliography entries
-[ ] bibliomisc - Untyped bibliographic information
-[x] bibliomixed - An entry in a Bibliography
-[ ] bibliomset - A cooked container for related bibliographic information
-[ ] biblioref - A cross reference to a bibliographic entry
-[ ] bibliorelation - The relationship of a document to another
-[ ] biblioset - A raw container for related bibliographic information
-[ ] bibliosource - The source of a document
-[ ] blockinfo - Meta-information for a block element
-[x] blockquote - A quotation set off from the main text
-[x] book - A book
-[x] bookinfo - Meta-information for a Book
-[x] bridgehead - A free-floating heading
-[x] callout - A “called out” description of a marked Area
-[x] calloutlist - A list of Callouts
-[x] caption - A caption
-[x] caution - A note of caution
-[x] chapter - A chapter, as of a book
-[x] chapterinfo - Meta-information for a Chapter
-[ ] citation - An inline bibliographic reference to another published work
-[ ] citebiblioid - A citation of a bibliographic identifier
-[ ] citerefentry - A citation to a reference page
-[ ] citetitle - The title of a cited work
-[ ] city - The name of a city in an address
-[x] classname - The name of a class, in the object-oriented programming sense
-[ ] classsynopsis - The syntax summary for a class definition
-[ ] classsynopsisinfo - Information supplementing the contents of
-    a ClassSynopsis
-[ ] cmdsynopsis - A syntax summary for a software command
-[ ] co - The location of a callout embedded in text
-[x] code - An inline code fragment
-[x] col - Specifications for a column in an HTML table
-[x] colgroup - A group of columns in an HTML table
-[ ] collab - Identifies a collaborator
-[ ] collabname - The name of a collaborator
-[ ] colophon - Text at the back of a book describing facts about its production
-[x] colspec - Specifications for a column in a table
-[x] command - The name of an executable program or other software command
-[x] computeroutput - Data, generally text, displayed or presented by a computer
-[ ] confdates - The dates of a conference for which a document was written
-[ ] confgroup - A wrapper for document meta-information about a conference
-[ ] confnum - An identifier, frequently numerical, associated with a conference for which a document was written
-[ ] confsponsor - The sponsor of a conference for which a document was written
-[ ] conftitle - The title of a conference for which a document was written
-[x] constant - A programming or system constant
-[ ] constraint - A constraint in an EBNF production
-[ ] constraintdef - The definition of a constraint in an EBNF production
-[ ] constructorsynopsis - A syntax summary for a constructor
-[ ] contractnum - The contract number of a document
-[ ] contractsponsor - The sponsor of a contract
-[ ] contrib - A summary of the contributions made to a document by a
-    credited source
-[ ] copyright - Copyright information about a document
-[ ] coref - A cross reference to a co
-[ ] corpauthor - A corporate author, as opposed to an individual
-[ ] corpcredit - A corporation or organization credited in a document
-[ ] corpname - The name of a corporation
-[ ] country - The name of a country
-[ ] database - The name of a database, or part of a database
-[x] date - The date of publication or revision of a document
-[ ] dedication - A wrapper for the dedication section of a book
-[ ] destructorsynopsis - A syntax summary for a destructor
-[ ] edition - The name or number of an edition of a document
-[ ] editor - The name of the editor of a document
-[x] email - An email address
-[x] emphasis - Emphasized text
-[x] entry - A cell in a table
-[ ] entrytbl - A subtable appearing in place of an Entry in a table
-[ ] envar - A software environment variable
-[x] epigraph - A short inscription at the beginning of a document or component
-    note:  also handle embedded attribution tag
-[x] equation - A displayed mathematical equation
-[ ] errorcode - An error code
-[ ] errorname - An error name
-[ ] errortext - An error message.
-[ ] errortype - The classification of an error message
-[ ] example - A formal example, with a title
-[ ] exceptionname - The name of an exception
-[ ] fax - A fax number
-[ ] fieldsynopsis - The name of a field in a class definition
-[x] figure - A formal figure, generally an illustration, with a title
-[x] filename - The name of a file
-[ ] firstname - The first name of a person
-[ ] firstterm - The first occurrence of a term
-[x] footnote - A footnote
-[ ] footnoteref - A cross reference to a footnote (a footnote mark)
-[x] foreignphrase - A word or phrase in a language other than the primary
-    language of the document
-[x] formalpara - A paragraph with a title
-[ ] funcdef - A function (subroutine) name and its return type
-[ ] funcparams - Parameters for a function referenced through a function
-    pointer in a synopsis
-[ ] funcprototype - The prototype of a function
-[ ] funcsynopsis - The syntax summary for a function definition
-[ ] funcsynopsisinfo - Information supplementing the FuncDefs of a FuncSynopsis
-[x] function - The name of a function or subroutine, as in a
-    programming language
-[x] glossary - A glossary
-[x] glossaryinfo - Meta-information for a Glossary
-[x] glossdef - A definition in a GlossEntry
-[x] glossdiv - A division in a Glossary
-[x] glossentry - An entry in a Glossary or GlossList
-[x] glosslist - A wrapper for a set of GlossEntrys
-[x] glosssee - A cross-reference from one GlossEntry to another
-[x] glossseealso - A cross-reference from one GlossEntry to another
-[x] glossterm - A glossary term
-[ ] graphic - A displayed graphical object (not an inline)
-    Note: in DocBook v5 `graphic` is discarded
-[ ] graphicco - A graphic that contains callout areas
-    Note: in DocBook v5 `graphicco` is discarded
-[ ] group - A group of elements in a CmdSynopsis
-[ ] guibutton - The text on a button in a GUI
-[ ] guiicon - Graphic and/or text appearing as a icon in a GUI
-[ ] guilabel - The text of a label in a GUI
-[x] guimenu - The name of a menu in a GUI
-[x] guimenuitem - The name of a terminal menu item in a GUI
-[x] guisubmenu - The name of a submenu in a GUI
-[ ] hardware - A physical part of a computer system
-[ ] highlights - A summary of the main points of the discussed component
-[ ] holder - The name of the individual or organization that holds a copyright
-[o] honorific - The title of a person
-[ ] html:form - An HTML form
-[x] imagedata - Pointer to external image data (only `fileref` attribute
-    implemented but not `entityref` which would require parsing of the DTD)
-[x] imageobject - A wrapper for image data and its associated meta-information
-[ ] imageobjectco - A wrapper for an image object with callouts
-[x] important - An admonition set off from the text
-[x] index - An index
-[x] indexdiv - A division in an index
-[x] indexentry - An entry in an index
-[x] indexinfo - Meta-information for an Index
-[x] indexterm - A wrapper for terms to be indexed
-[x] info - A wrapper for information about a component or other block. (DocBook v5)
-[x] informalequation - A displayed mathematical equation without a title
-[x] informalexample - A displayed example without a title
-[ ] informalfigure - A untitled figure
-[ ] informaltable - A table without a title
-[ ] initializer - The initializer for a FieldSynopsis
-[x] inlineequation - A mathematical equation or expression occurring inline
-[ ] inlinegraphic - An object containing or pointing to graphical data
-    that will be rendered inline
-[x] inlinemediaobject - An inline media object (video, audio, image, and so on)
-[ ] interface - An element of a GUI
-[ ] interfacename - The name of an interface
-[ ] invpartnumber - An inventory part number
-[ ] isbn - The International Standard Book Number of a document
-[ ] issn - The International Standard Serial Number of a periodical
-[ ] issuenum - The number of an issue of a journal
-[x] itemizedlist - A list in which each entry is marked with a bullet or
-    other dingbat
-[ ] itermset - A set of index terms in the meta-information of a document
-[ ] jobtitle - The title of an individual in an organization
-[x] keycap - The text printed on a key on a keyboard
-[ ] keycode - The internal, frequently numeric, identifier for a key
-    on a keyboard
-[x] keycombo - A combination of input actions
-[ ] keysym - The symbolic name of a key on a keyboard
-[ ] keyword - One of a set of keywords describing the content of a document
-[ ] keywordset - A set of keywords describing the content of a document
-[ ] label - A label on a Question or Answer
-[ ] legalnotice - A statement of legal obligations or requirements
-[ ] lhs - The left-hand side of an EBNF production
-[ ] lineage - The portion of a person's name indicating a relationship to
-    ancestors
-[ ] lineannotation - A comment on a line in a verbatim listing
-[x] link - A hypertext link
-[x] listitem - A wrapper for the elements of a list item
-[x] literal - Inline text that is some literal value
-[x] literallayout - A block of text in which line breaks and white space are
-    to be reproduced faithfully
-[ ] lot - A list of the titles of formal objects (as tables or figures) in
-    a document
-[ ] lotentry - An entry in a list of titles
-[ ] manvolnum - A reference volume number
-[x] markup - A string of formatting markup in text that is to be
-    represented literally
-[ ] mathphrase - A mathematical phrase, an expression that can be represented
-    with ordinary text and a small amount of markup
-[ ] medialabel - A name that identifies the physical medium on which some
-    information resides
-[x] mediaobject - A displayed media object (video, audio, image, etc.)
-[ ] mediaobjectco - A media object that contains callouts
-[x] member - An element of a simple list
-[x] menuchoice - A selection or series of selections from a menu
-[ ] methodname - The name of a method
-[ ] methodparam - Parameters to a method
-[ ] methodsynopsis - A syntax summary for a method
-[x] mml:math - A MathML equation
-[ ] modespec - Application-specific information necessary for the
-    completion of an OLink
-[ ] modifier - Modifiers in a synopsis
-[ ] mousebutton - The conventional name of a mouse button
-[ ] msg - A message in a message set
-[ ] msgaud - The audience to which a message in a message set is relevant
-[ ] msgentry - A wrapper for an entry in a message set
-[ ] msgexplan - Explanatory material relating to a message in a message set
-[ ] msginfo - Information about a message in a message set
-[ ] msglevel - The level of importance or severity of a message in a message set
-[ ] msgmain - The primary component of a message in a message set
-[ ] msgorig - The origin of a message in a message set
-[ ] msgrel - A related component of a message in a message set
-[ ] msgset - A detailed set of messages, usually error messages
-[ ] msgsub - A subcomponent of a message in a message set
-[ ] msgtext - The actual text of a message component in a message set
-[ ] nonterminal - A non-terminal in an EBNF production
-[x] note - A message set off from the text
-[ ] objectinfo - Meta-information for an object
-[ ] olink - A link that addresses its target indirectly, through an entity
-[ ] ooclass - A class in an object-oriented programming language
-[ ] ooexception - An exception in an object-oriented programming language
-[ ] oointerface - An interface in an object-oriented programming language
-[x] option - An option for a software command
-[x] optional - Optional information
-[x] orderedlist - A list in which each entry is marked with a sequentially
-    incremented label
-[ ] orgdiv - A division of an organization
-[ ] orgname - The name of an organization other than a corporation
-[ ] otheraddr - Uncategorized information in address
-[ ] othercredit - A person or entity, other than an author or editor,
-    credited in a document
-[ ] othername - A component of a persons name that is not a first name,
-    surname, or lineage
-[ ] package - A package
-[ ] pagenums - The numbers of the pages in a book, for use in a bibliographic
-    entry
-[x] para - A paragraph
-[ ] paramdef - Information about a function parameter in a programming language
-[x] parameter - A value or a symbolic reference to a value
-[ ] part - A division in a book
-[ ] partinfo - Meta-information for a Part
-[ ] partintro - An introduction to the contents of a part
-[ ] personblurb - A short description or note about a person
-[ ] personname - The personal name of an individual
-[ ] phone - A telephone number
-[ ] phrase - A span of text
-[ ] pob - A post office box in an address
-[ ] postcode - A postal code in an address
-[x] preface - Introductory matter preceding the first chapter of a book
-[ ] prefaceinfo - Meta-information for a Preface
-[ ] primary - The primary word or phrase under which an index term should be
-    sorted
-[ ] primaryie - A primary term in an index entry, not in the text
-[ ] printhistory - The printing history of a document
-[ ] procedure - A list of operations to be performed in a well-defined sequence
-[ ] production - A production in a set of EBNF productions
-[ ] productionrecap - A cross-reference to an EBNF production
-[ ] productionset - A set of EBNF productions
-[ ] productname - The formal name of a product
-[ ] productnumber - A number assigned to a product
-[x] programlisting - A literal listing of all or part of a program
-[ ] programlistingco - A program listing with associated areas used in callouts
-[x] prompt - A character or string indicating the start of an input field in
-    a computer display
-[ ] property - A unit of data associated with some part of a computer system
-[ ] pubdate - The date of publication of a document
-[ ] publisher - The publisher of a document
-[ ] publishername - The name of the publisher of a document
-[ ] pubsnumber - A number assigned to a publication other than an ISBN or ISSN
-    or inventory part number
-[x] qandadiv - A titled division in a QandASet
-[o] qandaentry - A question/answer set within a QandASet
-[o] qandaset - A question-and-answer set
-[x] question - A question in a QandASet
-[x] quote - An inline quotation
-[ ] refclass - The scope or other indication of applicability of a
-    reference entry
-[ ] refdescriptor - A description of the topic of a reference page
-[ ] refentry - A reference page (originally a UNIX man-style reference page)
-[ ] refentryinfo - Meta-information for a Refentry
-[ ] refentrytitle - The title of a reference page
-[ ] reference - A collection of reference entries
-[ ] referenceinfo - Meta-information for a Reference
-[ ] refmeta - Meta-information for a reference entry
-[ ] refmiscinfo - Meta-information for a reference entry other than the title
-    and volume number
-[ ] refname - The name of (one of) the subject(s) of a reference page
-[ ] refnamediv - The name, purpose, and classification of a reference page
-[ ] refpurpose - A short (one sentence) synopsis of the topic of a reference
-    page
-[x] refsect1 - A major subsection of a reference entry
-[x] refsect1info - Meta-information for a RefSect1
-[x] refsect2 - A subsection of a RefSect1
-[x] refsect2info - Meta-information for a RefSect2
-[x] refsect3 - A subsection of a RefSect2
-[x] refsect3info - Meta-information for a RefSect3
-[x] refsection - A recursive section in a refentry
-[x] refsectioninfo - Meta-information for a refsection
-[ ] refsynopsisdiv - A syntactic synopsis of the subject of the reference page
-[ ] refsynopsisdivinfo - Meta-information for a RefSynopsisDiv
-[x] releaseinfo - Information about a particular release of a document
-[ ] remark - A remark (or comment) intended for presentation in a draft
-    manuscript
-[ ] replaceable - Content that may or must be replaced by the user
-[ ] returnvalue - The value returned by a function
-[ ] revdescription - A extended description of a revision to a document
-[ ] revhistory - A history of the revisions to a document
-[ ] revision - An entry describing a single revision in the history of the
-    revisions to a document
-[ ] revnumber - A document revision number
-[ ] revremark - A description of a revision to a document
-[ ] rhs - The right-hand side of an EBNF production
-[x] row - A row in a table
-[ ] sbr - An explicit line break in a command synopsis
-[x] screen - Text that a user sees or might see on a computer screen
-[o] screenco - A screen with associated areas used in callouts
-[o] screeninfo - Information about how a screen shot was produced
-[ ] screenshot - A representation of what the user sees or might see on a
-    computer screen
-[ ] secondary - A secondary word or phrase in an index term
-[ ] secondaryie - A secondary term in an index entry, rather than in the text
-[x] sect1 - A top-level section of document
-[x] sect1info - Meta-information for a Sect1
-[x] sect2 - A subsection within a Sect1
-[x] sect2info - Meta-information for a Sect2
-[x] sect3 - A subsection within a Sect2
-[x] sect3info - Meta-information for a Sect3
-[x] sect4 - A subsection within a Sect3
-[x] sect4info - Meta-information for a Sect4
-[x] sect5 - A subsection within a Sect4
-[x] sect5info - Meta-information for a Sect5
-[x] section - A recursive section
-[x] sectioninfo - Meta-information for a recursive section
-[x] see - Part of an index term directing the reader instead to another entry
-    in the index
-[x] seealso - Part of an index term directing the reader also to another entry
-    in the index
-[ ] seealsoie - A See also entry in an index, rather than in the text
-[ ] seeie - A See entry in an index, rather than in the text
-[x] seg - An element of a list item in a segmented list
-[x] seglistitem - A list item in a segmented list
-[x] segmentedlist - A segmented list, a list of sets of elements
-[x] segtitle - The title of an element of a list item in a segmented list
-[ ] seriesvolnums - Numbers of the volumes in a series of books
-[ ] set - A collection of books
-[ ] setindex - An index to a set of books
-[ ] setindexinfo - Meta-information for a SetIndex
-[ ] setinfo - Meta-information for a Set
-[ ] sgmltag - A component of SGML markup
-[ ] shortaffil - A brief description of an affiliation
-[ ] shortcut - A key combination for an action that is also accessible through
-    a menu
-[ ] sidebar - A portion of a document that is isolated from the main
-    narrative flow
-[ ] sidebarinfo - Meta-information for a Sidebar
-[x] simpara - A paragraph that contains only text and inline markup, no block
-    elements
-[x] simplelist - An undecorated list of single words or short phrases
-[ ] simplemsgentry - A wrapper for a simpler entry in a message set
-[ ] simplesect - A section of a document with no subdivisions
-[ ] spanspec - Formatting information for a spanned column in a table
-[ ] state - A state or province in an address
-[ ] step - A unit of action in a procedure
-[ ] stepalternatives - Alternative steps in a procedure
-[ ] street - A street address in an address
-[ ] structfield - A field in a structure (in the programming language sense)
-[ ] structname - The name of a structure (in the programming language sense)
-[ ] subject - One of a group of terms describing the subject matter of a
-    document
-[ ] subjectset - A set of terms describing the subject matter of a document
-[ ] subjectterm - A term in a group of terms describing the subject matter of
-    a document
-[x] subscript - A subscript (as in H2O, the molecular formula for water)
-[ ] substeps - A wrapper for steps that occur within steps in a procedure
-[x] subtitle - The subtitle of a document
-[x] superscript - A superscript (as in x2, the mathematical notation for x
-    multiplied by itself)
-[ ] surname - A family name; in western cultures the last name
-[ ] svg:svg - An SVG graphic
-[x] symbol - A name that is replaced by a value before processing
-[ ] synopfragment - A portion of a CmdSynopsis broken out from the main body
-    of the synopsis
-[ ] synopfragmentref - A reference to a fragment of a command synopsis
-[ ] synopsis - A general-purpose element for representing the syntax of
-    commands or functions
-[ ] systemitem - A system-related item or term
-[ ] table - A formal table in a document
-[ ] task - A task to be completed
-[ ] taskprerequisites - The prerequisites for a task
-[ ] taskrelated - Information related to a task
-[ ] tasksummary - A summary of a task
-[x] tbody - A wrapper for the rows of a table or informal table
-[x] td - A table entry in an HTML table
-[x] term - The word or phrase being defined or described in a variable list
-[ ] termdef - An inline term definition
-[ ] tertiary - A tertiary word or phrase in an index term
-[ ] tertiaryie - A tertiary term in an index entry, rather than in the text
-[ ] textdata - Pointer to external text data
-[ ] textobject - A wrapper for a text description of an object and its
-    associated meta-information
-[ ] tfoot - A table footer consisting of one or more rows
-[x] tgroup - A wrapper for the main content of a table, or part of a table
-[x] th - A table header entry in an HTML table
-[x] thead - A table header consisting of one or more rows
-[x] tip - A suggestion to the user, set off from the text
-[x] title - The text of the title of a section of a document or of a formal
-    block-level element
-[x] titleabbrev - The abbreviation of a Title
-[x] toc - A table of contents
-[x] tocback - An entry in a table of contents for a back matter component
-[x] tocchap - An entry in a table of contents for a component in the body of
-    a document
-[x] tocentry - A component title in a table of contents
-[x] tocfront - An entry in a table of contents for a front matter component
-[x] toclevel1 - A top-level entry within a table of contents entry for a
-    chapter-like component
-[x] toclevel2 - A second-level entry within a table of contents entry for a
-    chapter-like component
-[x] toclevel3 - A third-level entry within a table of contents entry for a
-    chapter-like component
-[x] toclevel4 - A fourth-level entry within a table of contents entry for a
-    chapter-like component
-[x] toclevel5 - A fifth-level entry within a table of contents entry for a
-    chapter-like component
-[x] tocpart - An entry in a table of contents for a part of a book
-[ ] token - A unit of information
-[x] tr - A row in an HTML table
-[ ] trademark - A trademark
-[x] type - The classification of a value
-[x] ulink - A link that addresses its target by means of a URL
-    (Uniform Resource Locator)
-[x] uri - A Uniform Resource Identifier
-[x] userinput - Data entered by the user
-[x] varargs - An empty element in a function synopsis indicating a variable
-    number of arguments
-[x] variablelist - A list in which each entry is composed of a set of one or
-    more terms and an associated description
-[x] varlistentry - A wrapper for a set of terms and the associated description
-    in a variable list
-[x] varname - The name of a variable
-[ ] videodata - Pointer to external video data
-[ ] videoobject - A wrapper for video data and its associated meta-information
-[ ] void - An empty element in a function synopsis indicating that the
-    function in question takes no arguments
-[ ] volumenum - The volume number of a document in a set (as of books in a set
-    or articles in a journal)
-[x] warning - An admonition set off from the text
-[x] wordasword - A word meant specifically as a word and not representing
-    anything else
-[x] xref - A cross reference to another part of the document
-[ ] year - The year of publication of a document
-[x] ?asciidoc-br? - line break from asciidoc docbook output
--}
-
-type DB m = StateT DBState m
-
-data DBState = DBState{ dbSectionLevel :: Int
-                      , dbQuoteType    :: QuoteType
-                      , dbMeta         :: Meta
-                      , dbAcceptsMeta  :: Bool
-                      , dbBook         :: Bool
-                      , dbFigureTitle  :: Inlines
-                      , dbContent      :: [Content]
-                      } deriving Show
-
-instance Default DBState where
-  def = DBState{ dbSectionLevel = 0
-               , dbQuoteType = DoubleQuote
-               , dbMeta = mempty
-               , dbAcceptsMeta = False
-               , dbBook = False
-               , dbFigureTitle = mempty
-               , dbContent = [] }
-
-
-readDocBook :: PandocMonad m => ReaderOptions -> Text -> m Pandoc
-readDocBook _ inp = do
-  let tree = normalizeTree . parseXML . handleInstructions
-               $ T.unpack $ crFilter inp
-  (bs, st') <- flip runStateT (def{ dbContent = tree }) $ mapM parseBlock tree
-  return $ Pandoc (dbMeta st') (toList . mconcat $ bs)
-
--- We treat <?asciidoc-br?> specially (issue #1236), converting it
--- to <br/>, since xml-light doesn't parse the instruction correctly.
--- Other xml instructions are simply removed from the input stream.
-handleInstructions :: String -> String
-handleInstructions ('<':'?':'a':'s':'c':'i':'i':'d':'o':'c':'-':'b':'r':'?':'>':xs) = '<':'b':'r':'/':'>': handleInstructions xs
-handleInstructions xs = case break (=='<') xs of
-                             (ys, [])     -> ys
-                             ([], '<':zs) -> '<' : handleInstructions zs
-                             (ys, zs)     -> ys ++ handleInstructions zs
-
-getFigure :: PandocMonad m => Element -> DB m Blocks
-getFigure e = do
-  tit <- case filterChild (named "title") e of
-              Just t  -> getInlines t
-              Nothing -> return mempty
-  modify $ \st -> st{ dbFigureTitle = tit }
-  res <- getBlocks e
-  modify $ \st -> st{ dbFigureTitle = mempty }
-  return res
-
--- normalize input, consolidating adjacent Text and CRef elements
-normalizeTree :: [Content] -> [Content]
-normalizeTree = everywhere (mkT go)
-  where go :: [Content] -> [Content]
-        go (Text (CData CDataRaw _ _):xs) = xs
-        go (Text (CData CDataText s1 z):Text (CData CDataText s2 _):xs) =
-           Text (CData CDataText (s1 ++ s2) z):xs
-        go (Text (CData CDataText s1 z):CRef r:xs) =
-           Text (CData CDataText (s1 ++ convertEntity r) z):xs
-        go (CRef r:Text (CData CDataText s1 z):xs) =
-             Text (CData CDataText (convertEntity r ++ s1) z):xs
-        go (CRef r1:CRef r2:xs) =
-             Text (CData CDataText (convertEntity r1 ++ convertEntity r2) Nothing):xs
-        go xs = xs
-
-convertEntity :: String -> String
-convertEntity e = Data.Maybe.fromMaybe (map toUpper e) (lookupEntity e)
-
--- convenience function to get an attribute value, defaulting to ""
-attrValue :: String -> Element -> String
-attrValue attr elt =
-  fromMaybe "" (lookupAttrBy (\x -> qName x == attr) (elAttribs elt))
-
--- convenience function
-named :: String -> Element -> Bool
-named s e = qName (elName e) == s
-
---
-
-acceptingMetadata :: PandocMonad m => DB m a -> DB m a
-acceptingMetadata p = do
-  modify (\s -> s { dbAcceptsMeta = True } )
-  res <- p
-  modify (\s -> s { dbAcceptsMeta = False })
-  return res
-
-checkInMeta :: (PandocMonad m, Monoid a) => DB m () -> DB m a
-checkInMeta p = do
-  accepts <- dbAcceptsMeta <$> get
-  when accepts p
-  return mempty
-
-addMeta :: PandocMonad m => ToMetaValue a => String -> a -> DB m ()
-addMeta field val = modify (setMeta field val)
-
-instance HasMeta DBState where
-  setMeta field v s =  s {dbMeta = setMeta field v (dbMeta s)}
-  deleteMeta field s = s {dbMeta = deleteMeta field (dbMeta s)}
-
-isBlockElement :: Content -> Bool
-isBlockElement (Elem e) = qName (elName e) `elem` blocktags
-  where blocktags = ["toc","index","para","formalpara","simpara",
-           "ackno","epigraph","blockquote","bibliography","bibliodiv",
-           "biblioentry","glossee","glosseealso","glossary",
-           "glossdiv","glosslist","chapter","appendix","preface",
-           "bridgehead","sect1","sect2","sect3","sect4","sect5","section",
-           "refsect1","refsect2","refsect3","refsection",
-           "important","caution","note","tip","warning","qandadiv",
-           "question","answer","abstract","itemizedlist","orderedlist",
-           "variablelist","article","book","table","informaltable",
-           "informalexample", "linegroup",
-           "screen","programlisting","example","calloutlist"]
-isBlockElement _ = False
-
--- Trim leading and trailing newline characters
-trimNl :: String -> String
-trimNl = reverse . go . reverse . go
-  where go ('\n':xs) = xs
-        go xs        = xs
-
--- meld text into beginning of first paragraph of Blocks.
--- assumes Blocks start with a Para; if not, does nothing.
-addToStart :: Inlines -> Blocks -> Blocks
-addToStart toadd bs =
-  case toList bs of
-    (Para xs : rest) -> para (toadd <> fromList xs) <> fromList rest
-    _                -> bs
-
--- function that is used by both mediaobject (in parseBlock)
--- and inlinemediaobject (in parseInline)
--- A DocBook mediaobject is a wrapper around a set of alternative presentations
-getMediaobject :: PandocMonad m => Element -> DB m Inlines
-getMediaobject e = do
-  (imageUrl, attr) <-
-    case filterChild (named "imageobject") e of
-      Nothing  -> return (mempty, nullAttr)
-      Just z   -> case filterChild (named "imagedata") z of
-                    Nothing -> return (mempty, nullAttr)
-                    Just i  -> let atVal a = attrValue a i
-                                   w = case atVal "width" of
-                                         "" -> []
-                                         d  -> [("width", d)]
-                                   h = case atVal "depth" of
-                                         "" -> []
-                                         d  -> [("height", d)]
-                                   atr = (atVal "id", words $ atVal "role", w ++ h)
-                               in  return (atVal "fileref", atr)
-  let getCaption el = case filterChild (\x -> named "caption" x
-                                            || named "textobject" x
-                                            || named "alt" x) el of
-                        Nothing -> return mempty
-                        Just z  -> mconcat <$>
-                                         mapM parseInline (elContent z)
-  figTitle <- gets dbFigureTitle
-  let (caption, title) = if isNull figTitle
-                            then (getCaption e, "")
-                            else (return figTitle, "fig:")
-  fmap (imageWith attr imageUrl title) caption
-
-getBlocks :: PandocMonad m => Element -> DB m Blocks
-getBlocks e =  mconcat <$>
-                 mapM parseBlock (elContent e)
-
-
-parseBlock :: PandocMonad m => Content -> DB m Blocks
-parseBlock (Text (CData CDataRaw _ _)) = return mempty -- DOCTYPE
-parseBlock (Text (CData _ s _)) = if all isSpace s
-                                     then return mempty
-                                     else return $ plain $ trimInlines $ text s
-parseBlock (CRef x) = return $ plain $ str $ map toUpper x
-parseBlock (Elem e) =
-  case qName (elName e) of
-        "toc"   -> return mempty -- skip TOC, since in pandoc it's autogenerated
-        "index" -> return mempty -- skip index, since page numbers meaningless
-        "para"  -> parseMixed para (elContent e)
-        "formalpara" -> do
-           tit <- case filterChild (named "title") e of
-                        Just t  -> (para . strong . (<> str ".")) <$>
-                                     getInlines t
-                        Nothing -> return mempty
-           (tit <>) <$> parseMixed para (elContent e)
-        "simpara"  -> parseMixed para (elContent e)
-        "ackno"  -> parseMixed para (elContent e)
-        "epigraph" -> parseBlockquote
-        "blockquote" -> parseBlockquote
-        "attribution" -> return mempty
-        "titleabbrev" -> return mempty
-        "authorinitials" -> return mempty
-        "title" ->  checkInMeta getTitle
-        "author" -> checkInMeta getAuthor
-        "authorgroup" -> checkInMeta getAuthorGroup
-        "releaseinfo" -> checkInMeta (getInlines e >>= addMeta "release")
-        "date" -> checkInMeta getDate
-        "bibliography" -> sect 0
-        "bibliodiv" -> sect 1
-        "biblioentry" -> parseMixed para (elContent e)
-        "bibliomixed" -> parseMixed para (elContent e)
-        "glosssee" -> para . (\ils -> text "See " <> ils <> str ".")
-                         <$> getInlines e
-        "glossseealso" -> para . (\ils -> text "See also " <> ils <> str ".")
-                         <$> getInlines e
-        "glossary" -> sect 0
-        "glossdiv" -> definitionList <$>
-                  mapM parseGlossEntry (filterChildren (named "glossentry") e)
-        "glosslist" -> definitionList <$>
-                  mapM parseGlossEntry (filterChildren (named "glossentry") e)
-        "chapter" -> sect 0
-        "appendix" -> sect 0
-        "preface" -> sect 0
-        "bridgehead" -> para . strong <$> getInlines e
-        "sect1" -> sect 1
-        "sect2" -> sect 2
-        "sect3" -> sect 3
-        "sect4" -> sect 4
-        "sect5" -> sect 5
-        "section" -> gets dbSectionLevel >>= sect . (+1)
-        "refsect1" -> sect 1
-        "refsect2" -> sect 2
-        "refsect3" -> sect 3
-        "refsection" -> gets dbSectionLevel >>= sect . (+1)
-        "important" -> blockQuote . (para (strong $ str "Important") <>)
-                        <$> getBlocks e
-        "caution" -> blockQuote . (para (strong $ str "Caution") <>)
-                        <$> getBlocks e
-        "note" -> blockQuote . (para (strong $ str "Note") <>)
-                        <$> getBlocks e
-        "tip" -> blockQuote . (para (strong $ str "Tip") <>)
-                        <$> getBlocks e
-        "warning" -> blockQuote . (para (strong $ str "Warning") <>)
-                        <$> getBlocks e
-        "area" -> return mempty
-        "areaset" -> return mempty
-        "areaspec" -> return mempty
-        "qandadiv" -> gets dbSectionLevel >>= sect . (+1)
-        "question" -> addToStart (strong (str "Q:") <> str " ") <$> getBlocks e
-        "answer" -> addToStart (strong (str "A:") <> str " ") <$> getBlocks e
-        "abstract" -> blockQuote <$> getBlocks e
-        "calloutlist" -> bulletList <$> callouts
-        "itemizedlist" -> bulletList <$> listitems
-        "orderedlist" -> do
-          let listStyle = case attrValue "numeration" e of
-                               "arabic"     -> Decimal
-                               "loweralpha" -> LowerAlpha
-                               "upperalpha" -> UpperAlpha
-                               "lowerroman" -> LowerRoman
-                               "upperroman" -> UpperRoman
-                               _            -> Decimal
-          let start = fromMaybe 1 $
-                      (attrValue "override" <$> filterElement (named "listitem") e)
-                       >>= safeRead
-          orderedListWith (start,listStyle,DefaultDelim)
-            <$> listitems
-        "variablelist" -> definitionList <$> deflistitems
-        "figure" -> getFigure e
-        "mediaobject" -> para <$> getMediaobject e
-        "caption" -> return mempty
-        "info" -> metaBlock
-        "articleinfo" -> metaBlock
-        "sectioninfo" -> return mempty  -- keywords & other metadata
-        "refsectioninfo" -> return mempty  -- keywords & other metadata
-        "refsect1info" -> return mempty  -- keywords & other metadata
-        "refsect2info" -> return mempty  -- keywords & other metadata
-        "refsect3info" -> return mempty  -- keywords & other metadata
-        "sect1info" -> return mempty  -- keywords & other metadata
-        "sect2info" -> return mempty  -- keywords & other metadata
-        "sect3info" -> return mempty  -- keywords & other metadata
-        "sect4info" -> return mempty  -- keywords & other metadata
-        "sect5info" -> return mempty  -- keywords & other metadata
-        "chapterinfo" -> return mempty  -- keywords & other metadata
-        "glossaryinfo" -> return mempty  -- keywords & other metadata
-        "appendixinfo" -> return mempty  -- keywords & other metadata
-        "bookinfo" -> metaBlock
-        "article" -> modify (\st -> st{ dbBook = False }) >>
-                           getBlocks e
-        "book" -> modify (\st -> st{ dbBook = True }) >>  getBlocks e
-        "table" -> parseTable
-        "informaltable" -> parseTable
-        "informalexample" -> divWith ("", ["informalexample"], []) <$>
-                             getBlocks e
-        "linegroup" -> lineBlock <$> lineItems
-        "literallayout" -> codeBlockWithLang
-        "screen" -> codeBlockWithLang
-        "programlisting" -> codeBlockWithLang
-        "?xml"  -> return mempty
-        _       -> getBlocks e
-   where parseMixed container conts = do
-           let (ils,rest) = break isBlockElement conts
-           ils' <- (trimInlines . mconcat) <$> mapM parseInline ils
-           let p = if ils' == mempty then mempty else container ils'
-           case rest of
-                 []     -> return p
-                 (r:rs) -> do
-                    b <- parseBlock r
-                    x <- parseMixed container rs
-                    return $ p <> b <> x
-         codeBlockWithLang = do
-           let classes' = case attrValue "language" e of
-                                "" -> []
-                                x  -> [x]
-           return $ codeBlockWith (attrValue "id" e, classes', [])
-                  $ trimNl $ strContentRecursive e
-         parseBlockquote = do
-            attrib <- case filterChild (named "attribution") e of
-                             Nothing  -> return mempty
-                             Just z   -> (para . (str "— " <>) . mconcat)
-                                         <$>
-                                              mapM parseInline (elContent z)
-            contents <- getBlocks e
-            return $ blockQuote (contents <> attrib)
-         listitems = mapM getBlocks $ filterChildren (named "listitem") e
-         callouts = mapM getBlocks $ filterChildren (named "callout") e
-         deflistitems = mapM parseVarListEntry $ filterChildren
-                     (named "varlistentry") e
-         parseVarListEntry e' = do
-                     let terms = filterChildren (named "term") e'
-                     let items = filterChildren (named "listitem") e'
-                     terms' <- mapM getInlines terms
-                     items' <- mapM getBlocks items
-                     return (mconcat $ intersperse (str "; ") terms', items')
-         parseGlossEntry e' = do
-                     let terms = filterChildren (named "glossterm") e'
-                     let items = filterChildren (named "glossdef") e'
-                     terms' <- mapM getInlines terms
-                     items' <- mapM getBlocks items
-                     return (mconcat $ intersperse (str "; ") terms', items')
-         getTitle =  do
-                     tit <- getInlines e
-                     subtit <-  case filterChild (named "subtitle") e of
-                                  Just s  -> (text ": " <>) <$>
-                                              getInlines s
-                                  Nothing -> return mempty
-                     addMeta "title" (tit <> subtit)
-
-         getAuthor = (:[]) <$> getInlines e >>= addMeta "author"
-         getAuthorGroup = do
-          let terms = filterChildren (named "author") e
-          mapM getInlines terms >>= addMeta "author"
-         getDate = getInlines e >>= addMeta "date"
-         parseTable = do
-                      let isCaption x = named "title" x || named "caption" x
-                      caption <- case filterChild isCaption e of
-                                       Just t  -> getInlines t
-                                       Nothing -> return mempty
-                      let e' = fromMaybe e $ filterChild (named "tgroup") e
-                      let isColspec x = named "colspec" x || named "col" x
-                      let colspecs = case filterChild (named "colgroup") e' of
-                                           Just c -> filterChildren isColspec c
-                                           _      -> filterChildren isColspec e'
-                      let isRow x = named "row" x || named "tr" x
-                      headrows <- case filterChild (named "thead") e' of
-                                       Just h  -> case filterChild isRow h of
-                                                       Just x  -> parseRow x
-                                                       Nothing -> return []
-                                       Nothing -> return []
-                      bodyrows <- case filterChild (named "tbody") e' of
-                                       Just b  -> mapM parseRow
-                                                  $ filterChildren isRow b
-                                       Nothing -> mapM parseRow
-                                                  $ filterChildren isRow e'
-                      let toAlignment c = case findAttr (unqual "align") c of
-                                                Just "left"   -> AlignLeft
-                                                Just "right"  -> AlignRight
-                                                Just "center" -> AlignCenter
-                                                _             -> AlignDefault
-                      let toWidth c = case findAttr (unqual "colwidth") c of
-                                                Just w -> fromMaybe 0
-                                                   $ safeRead $ '0': filter (\x ->
-                                                     (x >= '0' && x <= '9')
-                                                      || x == '.') w
-                                                Nothing -> 0 :: Double
-                      let numrows = case bodyrows of
-                                         [] -> 0
-                                         xs -> maximum $ map length xs
-                      let aligns = case colspecs of
-                                     [] -> replicate numrows AlignDefault
-                                     cs -> map toAlignment cs
-                      let widths = case colspecs of
-                                     []  -> replicate numrows 0
-                                     cs  -> let ws = map toWidth cs
-                                                tot = sum ws
-                                            in  if all (> 0) ws
-                                                   then map (/ tot) ws
-                                                   else replicate numrows 0
-                      let headrows' = if null headrows
-                                         then replicate numrows mempty
-                                         else headrows
-                      return $ table caption (zip aligns widths)
-                                 headrows' bodyrows
-         isEntry x  = named "entry" x || named "td" x || named "th" x
-         parseRow = mapM (parseMixed plain . elContent) . filterChildren isEntry
-         sect n = do isbook <- gets dbBook
-                     let n' = if isbook || n == 0 then n + 1 else n
-                     headerText <- case filterChild (named "title") e `mplus`
-                                        (filterChild (named "info") e >>=
-                                            filterChild (named "title")) of
-                                      Just t  -> getInlines t
-                                      Nothing -> return mempty
-                     modify $ \st -> st{ dbSectionLevel = n }
-                     b <- getBlocks e
-                     let ident = attrValue "id" e
-                     modify $ \st -> st{ dbSectionLevel = n - 1 }
-                     return $ headerWith (ident,[],[]) n' headerText <> b
-         lineItems = mapM getInlines $ filterChildren (named "line") e
-         metaBlock = acceptingMetadata (getBlocks e) >> return mempty
-
-getInlines :: PandocMonad m => Element -> DB m Inlines
-getInlines e' = (trimInlines . mconcat) <$>
-                 mapM parseInline (elContent e')
-
-strContentRecursive :: Element -> String
-strContentRecursive = strContent .
-  (\e' -> e'{ elContent = map elementToStr $ elContent e' })
-
-elementToStr :: Content -> Content
-elementToStr (Elem e') = Text $ CData CDataText (strContentRecursive e') Nothing
-elementToStr x = x
-
-parseInline :: PandocMonad m => Content -> DB m Inlines
-parseInline (Text (CData _ s _)) = return $ text s
-parseInline (CRef ref) =
-  return $ maybe (text $ map toUpper ref) text $ lookupEntity ref
-parseInline (Elem e) =
-  case qName (elName e) of
-        "equation" -> equation displayMath
-        "informalequation" -> equation displayMath
-        "inlineequation" -> equation math
-        "subscript" -> subscript <$> innerInlines
-        "superscript" -> superscript <$> innerInlines
-        "inlinemediaobject" -> getMediaobject e
-        "quote" -> do
-            qt <- gets dbQuoteType
-            let qt' = if qt == SingleQuote then DoubleQuote else SingleQuote
-            modify $ \st -> st{ dbQuoteType = qt' }
-            contents <- innerInlines
-            modify $ \st -> st{ dbQuoteType = qt }
-            return $ if qt == SingleQuote
-                        then singleQuoted contents
-                        else doubleQuoted contents
-        "simplelist" -> simpleList
-        "segmentedlist" -> segmentedList
-        "classname" -> codeWithLang
-        "code" -> codeWithLang
-        "filename" -> codeWithLang
-        "literal" -> codeWithLang
-        "computeroutput" -> codeWithLang
-        "prompt" -> codeWithLang
-        "parameter" -> codeWithLang
-        "option" -> codeWithLang
-        "optional" -> do x <- getInlines e
-                         return $ str "[" <> x <> str "]"
-        "markup" -> codeWithLang
-        "wordasword" -> emph <$> innerInlines
-        "command" -> codeWithLang
-        "varname" -> codeWithLang
-        "function" -> codeWithLang
-        "type"    -> codeWithLang
-        "symbol"  -> codeWithLang
-        "constant" -> codeWithLang
-        "userinput" -> codeWithLang
-        "varargs" -> return $ code "(...)"
-        "keycap" -> return (str $ strContent e)
-        "keycombo" -> keycombo <$>
-                         mapM parseInline (elContent e)
-        "menuchoice" -> menuchoice <$>
-                         mapM parseInline (
-                                        filter isGuiMenu $ elContent e)
-        "xref" -> do
-            content <- dbContent <$> get
-            let linkend = attrValue "linkend" e
-            let title = case attrValue "endterm" e of
-                            ""      -> maybe "???" xrefTitleByElem
-                                         (findElementById linkend content)
-                            endterm -> maybe "???" strContent
-                                         (findElementById endterm content)
-            return $ link ('#' : linkend) "" (text title)
-        "email" -> return $ link ("mailto:" ++ strContent e) ""
-                          $ str $ strContent e
-        "uri" -> return $ link (strContent e) "" $ str $ strContent e
-        "ulink" -> link (attrValue "url" e) "" <$> innerInlines
-        "link" -> do
-             ils <- innerInlines
-             let href = case findAttr (QName "href" (Just "http://www.w3.org/1999/xlink") Nothing) e of
-                               Just h -> h
-                               _      -> '#' : attrValue "linkend" e
-             let ils' = if ils == mempty then str href else ils
-             let attr = (attrValue "id" e, words $ attrValue "role" e, [])
-             return $ linkWith attr href "" ils'
-        "foreignphrase" -> emph <$> innerInlines
-        "emphasis" -> case attrValue "role" e of
-                             "bold"          -> strong <$> innerInlines
-                             "strong"        -> strong <$> innerInlines
-                             "strikethrough" -> strikeout <$> innerInlines
-                             _               -> emph <$> innerInlines
-        "footnote" -> (note . mconcat) <$>
-                         mapM parseBlock (elContent e)
-        "title" -> return mempty
-        "affiliation" -> return mempty
-        -- Note: this isn't a real docbook tag; it's what we convert
-        -- <?asciidor-br?> to in handleInstructions, above.  A kludge to
-        -- work around xml-light's inability to parse an instruction.
-        "br" -> return linebreak
-        _          -> innerInlines
-   where innerInlines = (trimInlines . mconcat) <$>
-                          mapM parseInline (elContent e)
-         equation constructor = return $ mconcat $
-           map (constructor . writeTeX)
-           $ rights
-           $ map (readMathML . showElement . everywhere (mkT removePrefix))
-           $ filterChildren (\x -> qName (elName x) == "math" &&
-                                   qPrefix (elName x) == Just "mml") e
-         removePrefix elname = elname { qPrefix = Nothing }
-         codeWithLang = do
-           let classes' = case attrValue "language" e of
-                               "" -> []
-                               l  -> [l]
-           return $ codeWith (attrValue "id" e,classes',[]) $ strContentRecursive e
-         simpleList = (mconcat . intersperse (str "," <> space)) <$> mapM getInlines
-                         (filterChildren (named "member") e)
-         segmentedList = do
-           tit <- maybe (return mempty) getInlines $ filterChild (named "title") e
-           segtits <- mapM getInlines $ filterChildren (named "segtitle") e
-           segitems <- mapM (mapM getInlines . filterChildren (named "seg"))
-                          $ filterChildren (named "seglistitem") e
-           let toSeg = mconcat . zipWith (\x y -> strong (x <> str ":") <> space <>
-                                  y <> linebreak) segtits
-           let segs = mconcat $ map toSeg segitems
-           let tit' = if tit == mempty
-                         then mempty
-                         else strong tit <> linebreak
-           return $ linebreak <> tit' <> segs
-         keycombo = spanWith ("",["keycombo"],[]) .
-                    mconcat . intersperse (str "+")
-         menuchoice = spanWith ("",["menuchoice"],[]) .
-                    mconcat . intersperse (text " > ")
-         isGuiMenu (Elem x) = named "guimenu" x || named "guisubmenu" x ||
-                              named "guimenuitem" x
-         isGuiMenu _        = False
-
-         findElementById idString content
-            = asum [filterElement (\x -> attrValue "id" x == idString) el | Elem el <- content]
-
-         -- Use the 'xreflabel' attribute for getting the title of a xref link;
-         -- if there's no such attribute, employ some heuristics based on what
-         -- docbook-xsl does.
-         xrefTitleByElem el
-             | not (null xrefLabel) = xrefLabel
-             | otherwise            = case qName (elName el) of
-                  "chapter"      -> descendantContent "title" el
-                  "sect1"        -> descendantContent "title" el
-                  "sect2"        -> descendantContent "title" el
-                  "sect3"        -> descendantContent "title" el
-                  "sect4"        -> descendantContent "title" el
-                  "sect5"        -> descendantContent "title" el
-                  "cmdsynopsis"  -> descendantContent "command" el
-                  "funcsynopsis" -> descendantContent "function" el
-                  _              -> qName (elName el) ++ "_title"
-          where
-            xrefLabel = attrValue "xreflabel" el
-            descendantContent name = maybe "???" strContent
-                                   . filterElementName (\n -> qName n == name)
+{-# LANGUAGE OverloadedStrings #-}
+{-# LANGUAGE LambdaCase #-}
+{-# LANGUAGE FlexibleContexts #-}
+{-# LANGUAGE TemplateHaskell #-}
+{- |
+   Module      : Text.Pandoc.Readers.DocBook
+   Copyright   : Copyright (C) 2006-2024 John MacFarlane
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : John MacFarlane <jgm@berkeley.edu>
+   Stability   : alpha
+   Portability : portable
+
+Conversion of DocBook XML to 'Pandoc' document.
+-}
+module Text.Pandoc.Readers.DocBook ( readDocBook ) where
+import Control.Monad (MonadPlus(mplus))
+import Control.Applicative ()
+import Control.Monad.State.Strict
+    ( MonadTrans(lift),
+      StateT(runStateT),
+      MonadState(get),
+      gets,
+      modify )
+import Data.ByteString (ByteString)
+import Data.FileEmbed
+import Data.Char (isSpace, isLetter, chr)
+import Data.Default
+import Data.List.Split (splitWhen)
+import Data.Either (rights)
+import Data.Foldable (asum)
+import Data.Generics
+import Data.List (intersperse,elemIndex)
+import qualified Data.Set as Set
+import Data.List.NonEmpty (nonEmpty)
+import Data.Maybe (catMaybes,fromMaybe,mapMaybe,maybeToList)
+import Data.Text (Text)
+import Data.Text.Read as TR
+import Data.Text.Encoding (decodeUtf8)
+import qualified Data.Text as T
+import qualified Data.Text.Lazy as TL
+import Control.Monad.Except (throwError)
+import Text.Pandoc.XML (lookupEntity)
+import Text.Pandoc.Error (PandocError(..))
+import Text.Pandoc.Builder
+import Text.Pandoc.Class.PandocMonad (PandocMonad, report)
+import Text.Pandoc.Options
+import Text.Pandoc.Logging (LogMessage(..))
+import Text.Pandoc.Shared (safeRead, addPandocAttributes)
+import Text.Pandoc.Sources (ToSources(..), sourcesToText)
+import Text.Pandoc.Transforms (headerShift)
+import Text.TeXMath (readMathML, writeTeX)
+import qualified Data.Map as M
+import Text.Pandoc.XML.Light
+import Text.Pandoc.Walk (query)
+import Text.Read (readMaybe)
+
+{-
+
+List of all DocBook tags, with [x] indicating implemented,
+[o] meaning intentionally left unimplemented (pass through):
+
+[o] abbrev - An abbreviation, especially one followed by a period
+[x] abstract - A summary
+[o] accel - A graphical user interface (GUI) keyboard shortcut
+[x] ackno - Acknowledgements in an Article
+[o] acronym - An often pronounceable word made from the initial
+[o] action - A response to a user event
+[o] address - A real-world address, generally a postal address
+[ ] affiliation - The institutional affiliation of an individual
+[ ] alt - Text representation for a graphical element
+[x] anchor - A spot in the document
+[x] answer - An answer to a question posed in a QandASet
+[x] appendix - An appendix in a Book or Article
+[x] appendixinfo - Meta-information for an Appendix
+[o] application - The name of a software program
+[x] area - A region defined for a Callout in a graphic or code example
+[x] areaset - A set of related areas in a graphic or code example
+[x] areaspec - A collection of regions in a graphic or code example
+[ ] arg - An argument in a CmdSynopsis
+[x] article - An article
+[x] articleinfo - Meta-information for an Article
+[ ] artpagenums - The page numbers of an article as published
+[x] attribution - The source of a block quote or epigraph
+[ ] audiodata - Pointer to external audio data
+[ ] audioobject - A wrapper for audio data and its associated meta-information
+[x] author - The name of an individual author
+[ ] authorblurb - A short description or note about an author
+[x] authorgroup - Wrapper for author information when a document has
+    multiple authors or collaborators
+[x] authorinitials - The initials or other short identifier for an author
+[o] beginpage - The location of a page break in a print version of the document
+[ ] bibliocoverage - The spatial or temporal coverage of a document
+[x] bibliodiv - A section of a Bibliography
+[x] biblioentry - An entry in a Bibliography
+[x] bibliography - A bibliography
+[ ] bibliographyinfo - Meta-information for a Bibliography
+[ ] biblioid - An identifier for a document
+[o] bibliolist - A wrapper for a set of bibliography entries
+[x] bibliomisc - Untyped bibliographic information
+[x] bibliomixed - An entry in a Bibliography
+[ ] bibliomset - A cooked container for related bibliographic information
+[ ] biblioref - A cross reference to a bibliographic entry
+[ ] bibliorelation - The relationship of a document to another
+[ ] biblioset - A raw container for related bibliographic information
+[ ] bibliosource - The source of a document
+[ ] blockinfo - Meta-information for a block element
+[x] blockquote - A quotation set off from the main text
+[x] book - A book
+[x] bookinfo - Meta-information for a Book
+[x] bridgehead - A free-floating heading
+[x] callout - A “called out” description of a marked Area
+[x] calloutlist - A list of Callouts
+[x] caption - A caption
+[x] caution - A note of caution
+[x] chapter - A chapter, as of a book
+[x] chapterinfo - Meta-information for a Chapter
+[ ] citation - An inline bibliographic reference to another published work
+[ ] citebiblioid - A citation of a bibliographic identifier
+[x] citerefentry - A citation to a reference page
+[ ] citetitle - The title of a cited work
+[ ] city - The name of a city in an address
+[x] classname - The name of a class, in the object-oriented programming sense
+[ ] classsynopsis - The syntax summary for a class definition
+[ ] classsynopsisinfo - Information supplementing the contents of
+    a ClassSynopsis
+[ ] cmdsynopsis - A syntax summary for a software command
+[ ] co - The location of a callout embedded in text
+[x] code - An inline code fragment
+[x] col - Specifications for a column in an HTML table
+[x] colgroup - A group of columns in an HTML table
+[ ] collab - Identifies a collaborator
+[ ] collabname - The name of a collaborator
+[ ] colophon - Text at the back of a book describing facts about its production
+[x] colspec - Specifications for a column in a table
+[x] command - The name of an executable program or other software command
+[x] computeroutput - Data, generally text, displayed or presented by a computer
+[ ] confdates - The dates of a conference for which a document was written
+[ ] confgroup - A wrapper for document meta-information about a conference
+[ ] confnum - An identifier, frequently numerical, associated with a conference for which a document was written
+[ ] confsponsor - The sponsor of a conference for which a document was written
+[ ] conftitle - The title of a conference for which a document was written
+[x] constant - A programming or system constant
+[ ] constraint - A constraint in an EBNF production
+[ ] constraintdef - The definition of a constraint in an EBNF production
+[ ] constructorsynopsis - A syntax summary for a constructor
+[ ] contractnum - The contract number of a document
+[ ] contractsponsor - The sponsor of a contract
+[ ] contrib - A summary of the contributions made to a document by a
+    credited source
+[ ] copyright - Copyright information about a document
+[ ] coref - A cross reference to a co
+[ ] corpauthor - A corporate author, as opposed to an individual
+[ ] corpcredit - A corporation or organization credited in a document
+[ ] corpname - The name of a corporation
+[ ] country - The name of a country
+[x] danger - An admonition set off from the text indicating hazardous situation
+[ ] database - The name of a database, or part of a database
+[x] date - The date of publication or revision of a document
+[ ] dedication - A wrapper for the dedication section of a book
+[ ] destructorsynopsis - A syntax summary for a destructor
+[ ] edition - The name or number of an edition of a document
+[ ] editor - The name of the editor of a document
+[x] email - An email address
+[x] emphasis - Emphasized text
+[x] entry - A cell in a table
+[ ] entrytbl - A subtable appearing in place of an Entry in a table
+[x] envar - A software environment variable
+[x] epigraph - A short inscription at the beginning of a document or component
+    note:  also handle embedded attribution tag
+[x] equation - A displayed mathematical equation
+[ ] errorcode - An error code
+[ ] errorname - An error name
+[ ] errortext - An error message.
+[ ] errortype - The classification of an error message
+[x] example - A formal example, with a title
+[ ] exceptionname - The name of an exception
+[ ] fax - A fax number
+[ ] fieldsynopsis - The name of a field in a class definition
+[x] figure - A formal figure, generally an illustration, with a title
+[x] filename - The name of a file
+[ ] firstname - The first name of a person
+[ ] firstterm - The first occurrence of a term
+[x] footnote - A footnote
+[ ] footnoteref - A cross reference to a footnote (a footnote mark)
+[x] foreignphrase - A word or phrase in a language other than the primary
+    language of the document
+[x] formalpara - A paragraph with a title
+[ ] funcdef - A function (subroutine) name and its return type
+[ ] funcparams - Parameters for a function referenced through a function
+    pointer in a synopsis
+[ ] funcprototype - The prototype of a function
+[ ] funcsynopsis - The syntax summary for a function definition
+[ ] funcsynopsisinfo - Information supplementing the FuncDefs of a FuncSynopsis
+[x] function - The name of a function or subroutine, as in a
+    programming language
+[x] glossary - A glossary
+[x] glossaryinfo - Meta-information for a Glossary
+[x] glossdef - A definition in a GlossEntry
+[x] glossdiv - A division in a Glossary
+[x] glossentry - An entry in a Glossary or GlossList
+[x] glosslist - A wrapper for a set of GlossEntrys
+[x] glosssee - A cross-reference from one GlossEntry to another
+[x] glossseealso - A cross-reference from one GlossEntry to another
+[x] glossterm - A glossary term
+[ ] graphic - A displayed graphical object (not an inline)
+    Note: in DocBook v5 `graphic` is discarded
+[ ] graphicco - A graphic that contains callout areas
+    Note: in DocBook v5 `graphicco` is discarded
+[ ] group - A group of elements in a CmdSynopsis
+[ ] guibutton - The text on a button in a GUI
+[ ] guiicon - Graphic and/or text appearing as a icon in a GUI
+[ ] guilabel - The text of a label in a GUI
+[x] guimenu - The name of a menu in a GUI
+[x] guimenuitem - The name of a terminal menu item in a GUI
+[x] guisubmenu - The name of a submenu in a GUI
+[ ] hardware - A physical part of a computer system
+[ ] highlights - A summary of the main points of the discussed component
+[ ] holder - The name of the individual or organization that holds a copyright
+[o] honorific - The title of a person
+[ ] html:form - An HTML form
+[x] imagedata - Pointer to external image data (only `fileref` attribute
+    implemented but not `entityref` which would require parsing of the DTD)
+[x] imageobject - A wrapper for image data and its associated meta-information
+[ ] imageobjectco - A wrapper for an image object with callouts
+[x] important - An admonition set off from the text
+[x] index - An index
+[x] indexdiv - A division in an index
+[x] indexentry - An entry in an index
+[x] indexinfo - Meta-information for an Index
+[x] indexterm - A wrapper for terms to be indexed
+[x] info - A wrapper for information about a component or other block. (DocBook v5)
+[x] informalequation - A displayed mathematical equation without a title
+[x] informalexample - A displayed example without a title
+[x] informalfigure - An untitled figure
+[ ] informaltable - A table without a title
+[ ] initializer - The initializer for a FieldSynopsis
+[x] inlineequation - A mathematical equation or expression occurring inline
+[ ] inlinegraphic - An object containing or pointing to graphical data
+    that will be rendered inline
+[x] inlinemediaobject - An inline media object (video, audio, image, and so on)
+[ ] interface - An element of a GUI
+[ ] interfacename - The name of an interface
+[ ] invpartnumber - An inventory part number
+[ ] isbn - The International Standard Book Number of a document
+[ ] issn - The International Standard Serial Number of a periodical
+[ ] issuenum - The number of an issue of a journal
+[x] itemizedlist - A list in which each entry is marked with a bullet or
+    other dingbat
+[ ] itermset - A set of index terms in the meta-information of a document
+[ ] jobtitle - The title of an individual in an organization
+[x] keycap - The text printed on a key on a keyboard
+[ ] keycode - The internal, frequently numeric, identifier for a key
+    on a keyboard
+[x] keycombo - A combination of input actions
+[ ] keysym - The symbolic name of a key on a keyboard
+[ ] keyword - One of a set of keywords describing the content of a document
+[ ] keywordset - A set of keywords describing the content of a document
+[ ] label - A label on a Question or Answer
+[ ] legalnotice - A statement of legal obligations or requirements
+[ ] lhs - The left-hand side of an EBNF production
+[ ] lineage - The portion of a person's name indicating a relationship to
+    ancestors
+[ ] lineannotation - A comment on a line in a verbatim listing
+[x] link - A hypertext link
+[x] listitem - A wrapper for the elements of a list item
+[x] literal - Inline text that is some literal value
+[x] literallayout - A block of text in which line breaks and white space are
+    to be reproduced faithfully
+[ ] lot - A list of the titles of formal objects (as tables or figures) in
+    a document
+[ ] lotentry - An entry in a list of titles
+[ ] manvolnum - A reference volume number
+[x] markup - A string of formatting markup in text that is to be
+    represented literally
+[x] mathphrase - A mathematical phrase, an expression that can be represented
+    with ordinary text and a small amount of markup
+[ ] medialabel - A name that identifies the physical medium on which some
+    information resides
+[x] mediaobject - A displayed media object (video, audio, image, etc.)
+[ ] mediaobjectco - A media object that contains callouts
+[x] member - An element of a simple list
+[x] menuchoice - A selection or series of selections from a menu
+[ ] methodname - The name of a method
+[ ] methodparam - Parameters to a method
+[ ] methodsynopsis - A syntax summary for a method
+[x] mml:math - A MathML equation
+[ ] modespec - Application-specific information necessary for the
+    completion of an OLink
+[ ] modifier - Modifiers in a synopsis
+[ ] mousebutton - The conventional name of a mouse button
+[ ] msg - A message in a message set
+[ ] msgaud - The audience to which a message in a message set is relevant
+[ ] msgentry - A wrapper for an entry in a message set
+[ ] msgexplan - Explanatory material relating to a message in a message set
+[ ] msginfo - Information about a message in a message set
+[ ] msglevel - The level of importance or severity of a message in a message set
+[ ] msgmain - The primary component of a message in a message set
+[ ] msgorig - The origin of a message in a message set
+[ ] msgrel - A related component of a message in a message set
+[ ] msgset - A detailed set of messages, usually error messages
+[ ] msgsub - A subcomponent of a message in a message set
+[ ] msgtext - The actual text of a message component in a message set
+[ ] nonterminal - A non-terminal in an EBNF production
+[x] note - A message set off from the text
+[ ] objectinfo - Meta-information for an object
+[ ] olink - A link that addresses its target indirectly, through an entity
+[ ] ooclass - A class in an object-oriented programming language
+[ ] ooexception - An exception in an object-oriented programming language
+[ ] oointerface - An interface in an object-oriented programming language
+[x] option - An option for a software command
+[x] optional - Optional information
+[x] orderedlist - A list in which each entry is marked with a sequentially
+    incremented label
+[ ] orgdiv - A division of an organization
+[ ] orgname - The name of an organization other than a corporation
+[ ] otheraddr - Uncategorized information in address
+[ ] othercredit - A person or entity, other than an author or editor,
+    credited in a document
+[ ] othername - A component of a persons name that is not a first name,
+    surname, or lineage
+[ ] package - A package
+[ ] pagenums - The numbers of the pages in a book, for use in a bibliographic
+    entry
+[x] para - A paragraph
+[ ] paramdef - Information about a function parameter in a programming language
+[x] parameter - A value or a symbolic reference to a value
+[x] part - A division in a book
+[ ] partinfo - Meta-information for a Part
+[ ] partintro - An introduction to the contents of a part
+[ ] personblurb - A short description or note about a person
+[ ] personname - The personal name of an individual
+[ ] phone - A telephone number
+[x] phrase - A span of text
+[ ] pob - A post office box in an address
+[ ] postcode - A postal code in an address
+[x] preface - Introductory matter preceding the first chapter of a book
+[ ] prefaceinfo - Meta-information for a Preface
+[x] primary - The primary word or phrase under which an index term should be
+    sorted
+[ ] primaryie - A primary term in an index entry, not in the text
+[ ] printhistory - The printing history of a document
+[x] procedure - A list of operations to be performed in a well-defined sequence
+[ ] production - A production in a set of EBNF productions
+[ ] productionrecap - A cross-reference to an EBNF production
+[ ] productionset - A set of EBNF productions
+[ ] productname - The formal name of a product
+[ ] productnumber - A number assigned to a product
+[x] programlisting - A literal listing of all or part of a program
+[ ] programlistingco - A program listing with associated areas used in callouts
+[x] prompt - A character or string indicating the start of an input field in
+    a computer display
+[ ] property - A unit of data associated with some part of a computer system
+[ ] pubdate - The date of publication of a document
+[ ] publisher - The publisher of a document
+[ ] publishername - The name of the publisher of a document
+[ ] pubsnumber - A number assigned to a publication other than an ISBN or ISSN
+    or inventory part number
+[x] qandadiv - A titled division in a QandASet
+[o] qandaentry - A question/answer set within a QandASet
+[o] qandaset - A question-and-answer set
+[x] question - A question in a QandASet
+[x] quote - An inline quotation
+[ ] refclass - The scope or other indication of applicability of a
+    reference entry
+[ ] refdescriptor - A description of the topic of a reference page
+[ ] refentry - A reference page (originally a UNIX man-style reference page)
+[ ] refentryinfo - Meta-information for a Refentry
+[ ] refentrytitle - The title of a reference page
+[ ] reference - A collection of reference entries
+[ ] referenceinfo - Meta-information for a Reference
+[ ] refmeta - Meta-information for a reference entry
+[ ] refmiscinfo - Meta-information for a reference entry other than the title
+    and volume number
+[ ] refname - The name of (one of) the subject(s) of a reference page
+[ ] refnamediv - The name, purpose, and classification of a reference page
+[ ] refpurpose - A short (one sentence) synopsis of the topic of a reference
+    page
+[x] refsect1 - A major subsection of a reference entry
+[x] refsect1info - Meta-information for a RefSect1
+[x] refsect2 - A subsection of a RefSect1
+[x] refsect2info - Meta-information for a RefSect2
+[x] refsect3 - A subsection of a RefSect2
+[x] refsect3info - Meta-information for a RefSect3
+[x] refsection - A recursive section in a refentry
+[x] refsectioninfo - Meta-information for a refsection
+[ ] refsynopsisdiv - A syntactic synopsis of the subject of the reference page
+[ ] refsynopsisdivinfo - Meta-information for a RefSynopsisDiv
+[ ] releaseinfo - Information about a particular release of a document
+[ ] remark - A remark (or comment) intended for presentation in a draft
+    manuscript
+[x] replaceable - Content that may or must be replaced by the user
+[ ] returnvalue - The value returned by a function
+[ ] revdescription - A extended description of a revision to a document
+[ ] revhistory - A history of the revisions to a document
+[ ] revision - An entry describing a single revision in the history of the
+    revisions to a document
+[ ] revnumber - A document revision number
+[ ] revremark - A description of a revision to a document
+[ ] rhs - The right-hand side of an EBNF production
+[x] row - A row in a table
+[ ] sbr - An explicit line break in a command synopsis
+[x] screen - Text that a user sees or might see on a computer screen
+[o] screenco - A screen with associated areas used in callouts
+[o] screeninfo - Information about how a screen shot was produced
+[ ] screenshot - A representation of what the user sees or might see on a
+    computer screen
+[x] secondary - A secondary word or phrase in an index term
+[ ] secondaryie - A secondary term in an index entry, rather than in the text
+[x] sect1 - A top-level section of document
+[x] sect1info - Meta-information for a Sect1
+[x] sect2 - A subsection within a Sect1
+[x] sect2info - Meta-information for a Sect2
+[x] sect3 - A subsection within a Sect2
+[x] sect3info - Meta-information for a Sect3
+[x] sect4 - A subsection within a Sect3
+[x] sect4info - Meta-information for a Sect4
+[x] sect5 - A subsection within a Sect4
+[x] sect5info - Meta-information for a Sect5
+[x] section - A recursive section
+[x] sectioninfo - Meta-information for a recursive section
+[x] see - Part of an index term directing the reader instead to another entry
+    in the index
+[x] seealso - Part of an index term directing the reader also to another entry
+    in the index
+[ ] seealsoie - A See also entry in an index, rather than in the text
+[ ] seeie - A See entry in an index, rather than in the text
+[x] seg - An element of a list item in a segmented list
+[x] seglistitem - A list item in a segmented list
+[x] segmentedlist - A segmented list, a list of sets of elements
+[x] segtitle - The title of an element of a list item in a segmented list
+[ ] seriesvolnums - Numbers of the volumes in a series of books
+[ ] set - A collection of books
+[ ] setindex - An index to a set of books
+[ ] setindexinfo - Meta-information for a SetIndex
+[ ] setinfo - Meta-information for a Set
+[ ] sgmltag - A component of SGML markup
+[ ] shortaffil - A brief description of an affiliation
+[ ] shortcut - A key combination for an action that is also accessible through
+    a menu
+[x] sidebar - A portion of a document that is isolated from the main
+    narrative flow
+[ ] sidebarinfo - Meta-information for a Sidebar
+[x] simpara - A paragraph that contains only text and inline markup, no block
+    elements
+[x] simplelist - An undecorated list of single words or short phrases
+[ ] simplemsgentry - A wrapper for a simpler entry in a message set
+[x] simplesect - A section of a document with no subdivisions
+[ ] spanspec - Formatting information for a spanned column in a table
+[ ] state - A state or province in an address
+[x] step - A unit of action in a procedure
+[ ] stepalternatives - Alternative steps in a procedure
+[ ] street - A street address in an address
+[ ] structfield - A field in a structure (in the programming language sense)
+[ ] structname - The name of a structure (in the programming language sense)
+[ ] subject - One of a group of terms describing the subject matter of a
+    document
+[ ] subjectset - A set of terms describing the subject matter of a document
+[ ] subjectterm - A term in a group of terms describing the subject matter of
+    a document
+[x] subscript - A subscript (as in H2O, the molecular formula for water)
+[x] substeps - A wrapper for steps that occur within steps in a procedure
+[x] subtitle - The subtitle of a document
+[x] superscript - A superscript (as in x2, the mathematical notation for x
+    multiplied by itself)
+[ ] surname - A family name; in western cultures the last name
+[ ] svg:svg - An SVG graphic
+[x] symbol - A name that is replaced by a value before processing
+[ ] synopfragment - A portion of a CmdSynopsis broken out from the main body
+    of the synopsis
+[ ] synopfragmentref - A reference to a fragment of a command synopsis
+[ ] synopsis - A general-purpose element for representing the syntax of
+    commands or functions
+[x] systemitem - A system-related item or term
+[ ] table - A formal table in a document
+[ ] task - A task to be completed
+[ ] taskprerequisites - The prerequisites for a task
+[ ] taskrelated - Information related to a task
+[ ] tasksummary - A summary of a task
+[x] tbody - A wrapper for the rows of a table or informal table
+[x] td - A table entry in an HTML table
+[x] term - The word or phrase being defined or described in a variable list
+[ ] termdef - An inline term definition
+[x] tertiary - A tertiary word or phrase in an index term
+[ ] tertiaryie - A tertiary term in an index entry, rather than in the text
+[ ] textdata - Pointer to external text data
+[ ] textobject - A wrapper for a text description of an object and its
+    associated meta-information
+[ ] tfoot - A table footer consisting of one or more rows
+[x] tgroup - A wrapper for the main content of a table, or part of a table
+[x] th - A table header entry in an HTML table
+[x] thead - A table header consisting of one or more rows
+[x] tip - A suggestion to the user, set off from the text
+[x] title - The text of the title of a section of a document or of a formal
+    block-level element
+[x] titleabbrev - The abbreviation of a Title
+[x] toc - A table of contents
+[x] tocback - An entry in a table of contents for a back matter component
+[x] tocchap - An entry in a table of contents for a component in the body of
+    a document
+[x] tocentry - A component title in a table of contents
+[x] tocfront - An entry in a table of contents for a front matter component
+[x] toclevel1 - A top-level entry within a table of contents entry for a
+    chapter-like component
+[x] toclevel2 - A second-level entry within a table of contents entry for a
+    chapter-like component
+[x] toclevel3 - A third-level entry within a table of contents entry for a
+    chapter-like component
+[x] toclevel4 - A fourth-level entry within a table of contents entry for a
+    chapter-like component
+[x] toclevel5 - A fifth-level entry within a table of contents entry for a
+    chapter-like component
+[x] tocpart - An entry in a table of contents for a part of a book
+[ ] token - A unit of information
+[x] tr - A row in an HTML table
+[ ] trademark - A trademark
+[x] type - The classification of a value
+[x] ulink - A link that addresses its target by means of a URL
+    (Uniform Resource Locator)
+[x] uri - A Uniform Resource Identifier
+[x] userinput - Data entered by the user
+[x] varargs - An empty element in a function synopsis indicating a variable
+    number of arguments
+[x] variablelist - A list in which each entry is composed of a set of one or
+    more terms and an associated description
+[x] varlistentry - A wrapper for a set of terms and the associated description
+    in a variable list
+[x] varname - The name of a variable
+[ ] videodata - Pointer to external video data
+[ ] videoobject - A wrapper for video data and its associated meta-information
+[ ] void - An empty element in a function synopsis indicating that the
+    function in question takes no arguments
+[ ] volumenum - The volume number of a document in a set (as of books in a set
+    or articles in a journal)
+[x] warning - An admonition set off from the text
+[x] wordasword - A word meant specifically as a word and not representing
+    anything else
+[x] xref - A cross reference to another part of the document
+[ ] year - The year of publication of a document
+[x] ?asciidoc-br? - line break from asciidoc docbook output
+-}
+
+type DB m = StateT DBState m
+
+data DBState = DBState{ dbSectionLevel  :: Int
+                      , dbQuoteType     :: QuoteType
+                      , dbMeta          :: Meta
+                      , dbBook          :: Bool
+                      , dbContent       :: [Content]
+                      , dbLiteralLayout :: Bool
+                      , dbElementStack  :: [Text]
+                      } deriving Show
+
+instance Default DBState where
+  def = DBState{ dbSectionLevel = 0
+               , dbQuoteType = DoubleQuote
+               , dbMeta = mempty
+               , dbBook = False
+               , dbContent = []
+               , dbLiteralLayout = False
+               , dbElementStack = []
+               }
+
+
+readDocBook :: (PandocMonad m, ToSources a)
+            => ReaderOptions
+            -> a
+            -> m Pandoc
+readDocBook _ inp = do
+  let sources = toSources inp
+  tree <- either (throwError . PandocXMLError "") return $
+            parseXMLContentsWithEntities
+            docbookEntityMap
+              (TL.fromStrict . handleInstructions . sourcesToText $ sources)
+  (bs, st') <- flip runStateT (def{ dbContent = tree }) $ mapM parseBlock tree
+  let headerLevel (Header n _ _) = [n]
+      headerLevel _              = []
+  let bottomLevel = maybe 1 minimum $ nonEmpty $ query headerLevel bs
+  return $
+    -- handle the case where you have <part> or <chapter>
+    (if bottomLevel < 1
+        then headerShift (1 - bottomLevel)
+        else id) $ Pandoc (dbMeta st') $ toList $ mconcat bs
+
+-- We treat certain processing instructions by converting them to tags
+-- beginning "pi-".
+handleInstructions :: Text -> Text
+handleInstructions t =
+  let (x,y) = T.breakOn "<?" t
+   in if T.null y
+         then x
+         else
+           let (w,z) = T.breakOn "?>" y
+            in (if T.takeWhile (\c -> isLetter c || c == '-')
+                    (T.drop 2 w) `elem` ["asciidoc-br", "dbfo"]
+                   then x <> "<pi-" <> T.drop 2 w <> "/>"
+                   else x <> w <> T.take 2 z) <>
+               handleInstructions (T.drop 2 z)
+
+getFigure :: PandocMonad m => Element -> DB m Blocks
+getFigure e = do
+  tit <- case filterChild (named "title") e of
+              Just t  -> getInlines t
+              Nothing -> return mempty
+  contents <- getBlocks e
+  let contents' =
+        case toList contents of
+          [Para [img@Image{}]] -> plain (fromList [img])
+          _ -> contents
+  return $ figureWith
+             (attrValue "id" e, [], [])
+             (simpleCaption $ plain tit)
+             contents'
+
+-- convenience function to get an attribute value, defaulting to ""
+attrValue :: Text -> Element -> Text
+attrValue attr elt =
+  fromMaybe "" (lookupAttrBy (\x -> qName x == attr) (elAttribs elt))
+
+-- convenience function
+named :: Text -> Element -> Bool
+named s e = qName (elName e) == s
+
+--
+
+addMetadataFromElement :: PandocMonad m => Element -> DB m Blocks
+addMetadataFromElement e = do
+  -- Add metadata if at root or appropriate parent element
+  elementStack <- gets dbElementStack
+  if take 1 elementStack `elem` [[], ["book"], ["article"]]
+    then mempty <$ mapM_ handleMetadataElement
+                  (filterChildren ((isMetadataField . qName . elName)) e)
+    else return mempty
+ where
+  handleMetadataElement elt =
+    case qName (elName elt) of
+      "title" -> addContentsToMetadata "title" elt
+      "subtitle" -> addContentsToMetadata "subtitle" elt
+      "abstract" -> addContentsToMetadata "abstract" elt
+      "date" -> addContentsToMetadata "date" elt
+      "release" -> addContentsToMetadata "release" elt
+      "releaseinfo" -> addContentsToMetadata "releaseinfo" elt
+      "address" -> addContentsToMetadata "address" elt
+      "copyright" -> addContentsToMetadata "copyright" elt
+      "author" -> fromAuthor elt >>= addMeta "author"
+      "authorgroup" ->
+        mapM fromAuthor (filterChildren (named "author") elt) >>= addMeta "author"
+      _ -> report . IgnoredElement . qName . elName $ elt
+
+  fromAuthor elt =
+    mconcat . intersperse space . filter (not . null)
+      <$> mapM getInlines (elChildren elt)
+
+  addContentsToMetadata fieldname elt =
+    if any ((`Set.member` blockTags) . qName . elName) (elChildren elt)
+       then getBlocks elt >>= addMeta fieldname
+       else getInlines elt >>= addMeta fieldname
+
+  isMetadataField "abstract" = True
+  isMetadataField "address" = True
+  isMetadataField "annotation" = True
+  isMetadataField "artpagenums" = True
+  isMetadataField "author" = True
+  isMetadataField "authorgroup" = True
+  isMetadataField "authorinitials" = True
+  isMetadataField "bibliocoverage" = True
+  isMetadataField "biblioid" = True
+  isMetadataField "bibliomisc" = True
+  isMetadataField "bibliomset" = True
+  isMetadataField "bibliorelation" = True
+  isMetadataField "biblioset" = True
+  isMetadataField "bibliosource" = True
+  isMetadataField "collab" = True
+  isMetadataField "confgroup" = True
+  isMetadataField "contractnum" = True
+  isMetadataField "contractsponsor" = True
+  isMetadataField "copyright" = True
+  isMetadataField "cover" = True
+  isMetadataField "date" = True
+  isMetadataField "edition" = True
+  isMetadataField "editor" = True
+  isMetadataField "extendedlink" = True
+  isMetadataField "issuenum" = True
+  isMetadataField "itermset" = True
+  isMetadataField "keywordset" = True
+  isMetadataField "legalnotice" = True
+  isMetadataField "mediaobject" = True
+  isMetadataField "org" = True
+  isMetadataField "orgname" = True
+  isMetadataField "othercredit" = True
+  isMetadataField "pagenums" = True
+  isMetadataField "printhistory" = True
+  isMetadataField "productname" = True
+  isMetadataField "productnumber" = True
+  isMetadataField "pubdate" = True
+  isMetadataField "publisher" = True
+  isMetadataField "publishername" = True
+  isMetadataField "releaseinfo" = True
+  isMetadataField "revhistory" = True
+  isMetadataField "seriesvolnums" = True
+  isMetadataField "subjectset" = True
+  isMetadataField "subtitle" = True
+  isMetadataField "title" = True
+  isMetadataField "titleabbrev" = True
+  isMetadataField "volumenum" = True
+  isMetadataField _ = False
+
+
+addMeta :: PandocMonad m => ToMetaValue a => Text -> a -> DB m ()
+addMeta field val = modify (setMeta field val)
+
+instance HasMeta DBState where
+  setMeta field v s =  s {dbMeta = setMeta field v (dbMeta s)}
+  deleteMeta field s = s {dbMeta = deleteMeta field (dbMeta s)}
+
+isBlockElement :: Content -> Bool
+isBlockElement (Elem e) = qName (elName e) `Set.member` blockTags
+isBlockElement _ = False
+
+blockTags :: Set.Set Text
+blockTags = Set.fromList $
+  [ "abstract"
+  , "ackno"
+  , "answer"
+  , "appendix"
+  , "appendixinfo"
+  , "area"
+  , "areaset"
+  , "areaspec"
+  , "article"
+  , "articleinfo"
+  , "attribution"
+  , "authorinitials"
+  , "biblioentry"
+  , "bibliomisc"
+  , "bibliomixed"
+  , "blockquote"
+  , "book"
+  , "bookinfo"
+  , "bridgehead"
+  , "calloutlist"
+  , "caption"
+  , "chapter"
+  , "chapterinfo"
+  , "epigraph"
+  , "example"
+  , "figure"
+  , "formalpara"
+  , "glossary"
+  , "glossaryinfo"
+  , "glossdiv"
+  , "glossee"
+  , "glosseealso"
+  , "glosslist"
+  , "glosssee"
+  , "glossseealso"
+  , "index"
+  , "info"
+  , "informalexample"
+  , "informalfigure"
+  , "informaltable"
+  , "itemizedlist"
+  , "linegroup"
+  , "literallayout"
+  , "mediaobject"
+  , "orderedlist"
+  , "para"
+  , "part"
+  , "partinfo"
+  , "preface"
+  , "procedure"
+  , "programlisting"
+  , "question"
+  , "refsect1info"
+  , "refsect2info"
+  , "refsect3info"
+  , "refsectioninfo"
+  , "screen"
+  , "sect1info"
+  , "sect2info"
+  , "sect3info"
+  , "sect4info"
+  , "sect5info"
+  , "sectioninfo"
+  , "simpara"
+  , "substeps"
+  , "subtitle"
+  , "table"
+  , "title"
+  , "titleabbrev"
+  , "toc"
+  , "variablelist"
+  ] ++ sectionTags ++ admonitionTags
+
+sectionTags :: [Text]
+sectionTags = ["bibliography", "bibliodiv"
+              , "sect1", "sect2", "sect3", "sect4", "sect5", "section", "simplesect"
+              , "refsect1", "refsect2", "refsect3", "refsection", "qandadiv"
+              ]
+
+admonitionTags :: [Text]
+admonitionTags = ["caution","danger","important","note","tip","warning"]
+
+titledBlockElements :: [Text]
+titledBlockElements = ["example", "formalpara", "sidebar"]
+
+-- Trim leading and trailing newline characters
+trimNl :: Text -> Text
+trimNl = T.dropAround (== '\n')
+
+-- meld text into beginning of first paragraph of Blocks.
+-- assumes Blocks start with a Para; if not, does nothing.
+addToStart :: Inlines -> Blocks -> Blocks
+addToStart toadd bs =
+  case toList bs of
+    (Para xs : rest) -> para (toadd <> fromList xs) <> fromList rest
+    _                -> bs
+
+-- function that is used by both mediaobject (in parseBlock)
+-- and inlinemediaobject (in parseInline)
+-- A DocBook mediaobject is a wrapper around a set of alternative presentations
+getMediaobject :: PandocMonad m => Element -> DB m Inlines
+getMediaobject e = do
+  let (imageUrl, tit, attr) =
+        case filterElements (named "imageobject") e of
+          []  -> (mempty, mempty, nullAttr)
+          (z:_) ->
+            let tit' = maybe "" strContent $
+                         filterChild (named "objectinfo") z >>=
+                         filterChild (named "title")
+                (imageUrl', attr') =
+                  case filterChild (named "imagedata") z of
+                        Nothing -> (mempty, nullAttr)
+                        Just i  -> let atVal a = attrValue a i
+                                       w = case atVal "width" of
+                                             "" -> []
+                                             d  -> [("width", d)]
+                                       h = case atVal "depth" of
+                                             "" -> []
+                                             d  -> [("height", d)]
+                                       id' = atVal "id"
+                                       cs = T.words $ atVal "role"
+                                       atr = (id', cs, w ++ h)
+                                   in  (atVal "fileref", atr)
+            in  (imageUrl', tit', attr')
+  let capt = case filterChild (\x -> named "caption" x
+                                            || named "textobject" x
+                                            || named "alt" x) e of
+                        Nothing -> return mempty
+                        Just z  -> trimInlines . mconcat <$>
+                                         mapM parseInline (elContent z)
+  fmap (imageWith attr imageUrl tit) capt
+
+getBlocks :: PandocMonad m => Element -> DB m Blocks
+getBlocks e = do
+  modify (\st -> st{ dbElementStack = qName (elName e) : dbElementStack st })
+  blocks <- mconcat <$> mapM parseBlock (elContent e)
+  modify (\st -> st{ dbElementStack = drop 1 $ dbElementStack st })
+  return blocks
+
+getRoleAttr :: Element -> [(Text, Text)] -- extract role attribute and add it to the attribute list
+getRoleAttr e = case attrValue "role" e of
+                  "" -> []
+                  r  -> [("role", r)]
+
+parseBlock :: PandocMonad m => Content -> DB m Blocks
+parseBlock (Text (CData CDataRaw _ _)) = return mempty -- DOCTYPE
+parseBlock (Text (CData _ s _)) = if T.all isSpace s
+                                     then return mempty
+                                     else return $ plain $ trimInlines $ text s
+parseBlock (CRef x) = return $ plain $ str $ T.toUpper x
+parseBlock (Elem e) = do
+  parsedBlock <- case qName (elName e) of
+        "toc"   -> skip -- skip TOC, since in pandoc it's autogenerated
+        "index" -> skip -- skip index, since page numbers meaningless
+        "para"  -> parseMixed para (elContent e)
+        "simpara"  -> parseMixed para (elContent e)
+        "ackno"  -> parseMixed para (elContent e)
+        "epigraph" -> parseBlockquote
+        "blockquote" -> withOptionalTitle parseBlockquote
+        "attribution" -> skip
+        "titleabbrev" -> skip
+        "authorinitials" -> skip
+        "bibliography" -> sect 0
+        "bibliodiv" ->
+          case filterChild (named "title") e of
+            Just _  -> sect 1
+            Nothing -> return mempty
+        "biblioentry" -> parseMixed para (elContent e)
+        "bibliomisc" -> parseMixed para (elContent e)
+        "bibliomixed" -> parseMixed para (elContent e)
+        "equation"         -> para <$> equation e displayMath
+        "informalequation" -> divWith (attrValue "id" e,["informalequation"],[]) .
+                              para <$> equation e displayMath
+        "glosssee" -> para . (\ils -> text "See " <> ils <> str ".")
+                         <$> getInlines e
+        "glossseealso" -> para . (\ils -> text "See also " <> ils <> str ".")
+                         <$> getInlines e
+        "glossary" -> sect 0
+        "glossdiv" -> definitionList <$>
+                  mapM parseGlossEntry (filterChildren (named "glossentry") e)
+        "glosslist" -> definitionList <$>
+                  mapM parseGlossEntry (filterChildren (named "glossentry") e)
+        "chapter" -> modify (\st -> st{ dbBook = True}) >> sect 0
+        "part" -> modify (\st -> st{ dbBook = True}) >> sect (-1)
+        "appendix" -> sect 0
+        "preface" -> sect 0
+        "bridgehead" -> para . strong <$> getInlines e
+        "sect1" -> sect 1
+        "sect2" -> sect 2
+        "sect3" -> sect 3
+        "sect4" -> sect 4
+        "sect5" -> sect 5
+        "section" -> gets dbSectionLevel >>= sect . (+1)
+        "simplesect" ->
+          gets dbSectionLevel >>=
+          sectWith(attrValue "id" e) ["unnumbered"] [] . (+1)
+        "refsect1" -> sect 1
+        "refsect2" -> sect 2
+        "refsect3" -> sect 3
+        "refsection" -> gets dbSectionLevel >>= sect . (+1)
+        l | l `elem` titledBlockElements -> parseAdmonition False l
+        l | l `elem` admonitionTags -> parseAdmonition True l
+        "area" -> skip
+        "areaset" -> skip
+        "areaspec" -> skip
+        "qandadiv" -> gets dbSectionLevel >>= sect . (+1)
+        "question" -> addToStart (strong (str "Q:") <> str " ") <$> getBlocks e
+        "answer" -> addToStart (strong (str "A:") <> str " ") <$> getBlocks e
+        "abstract" -> blockQuote <$> getBlocks e
+        "calloutlist" -> withOptionalTitle $ bulletList <$> callouts
+        "itemizedlist" -> withOptionalTitle $
+                            bulletList . handleCompact <$> listitems
+        "orderedlist" -> withOptionalTitle $ do
+          let listStyle = case attrValue "numeration" e of
+                               "arabic"     -> Decimal
+                               "loweralpha" -> LowerAlpha
+                               "upperalpha" -> UpperAlpha
+                               "lowerroman" -> LowerRoman
+                               "upperroman" -> UpperRoman
+                               _            -> Decimal
+          let start = fromMaybe 1 $ safeRead $ attrValue "startingnumber" e
+          orderedListWith (start,listStyle,DefaultDelim) . handleCompact
+            <$> listitems
+        "variablelist" -> definitionList <$> deflistitems
+        "procedure" -> orderedList <$> steps
+        "substeps" -> orderedList <$> steps
+        "figure" -> getFigure e
+        "informalfigure" -> getFigure e
+        "mediaobject" -> para <$> getMediaobject e
+        "caption" -> skip
+        "info" -> addMetadataFromElement e
+        "articleinfo" -> addMetadataFromElement e
+        "sectioninfo" -> skip -- keywords & other metadata
+        "refsectioninfo" -> skip -- keywords & other metadata
+        "refsect1info" -> skip -- keywords & other metadata
+        "refsect2info" -> skip -- keywords & other metadata
+        "refsect3info" -> skip -- keywords & other metadata
+        "sect1info" -> skip  -- keywords & other metadata
+        "sect2info" -> skip  -- keywords & other metadata
+        "sect3info" -> skip  -- keywords & other metadata
+        "sect4info" -> skip  -- keywords & other metadata
+        "sect5info" -> skip  -- keywords & other metadata
+        "chapterinfo" -> skip -- keywords & other metadata
+        "partinfo" -> skip -- keywords & other metadata
+        "glossaryinfo" -> skip  -- keywords & other metadata
+        "appendixinfo" -> skip  -- keywords & other metadata
+        "bookinfo" -> addMetadataFromElement e
+        "article" -> modify (\st -> st{ dbBook = False }) >>
+                           addMetadataFromElement e >> getBlocks e
+        "book" -> modify (\st -> st{ dbBook = True }) >>
+                    addMetadataFromElement e >> getBlocks e
+        "table" -> parseTable
+        "informaltable" -> parseTable
+        "informalexample" -> divWith ("", ["informalexample"], []) <$>
+                             getBlocks e
+        "linegroup" -> lineBlock <$> lineItems
+        "literallayout" -> literalLayout
+        "screen" -> codeBlockWithLang
+        "programlisting" -> codeBlockWithLang
+        "?xml"  -> return mempty
+        "title" -> return mempty     -- handled in parent element
+        "subtitle" -> return mempty  -- handled in parent element
+        _ -> skip >> getBlocks e
+  if qName (elName e) `elem` sectionTags
+     then return parsedBlock
+     else return $ addPandocAttributes (getRoleAttr e) parsedBlock
+   where skip = do
+           let qn = qName $ elName e
+           let name = if "pi-" `T.isPrefixOf` qn
+                         then "<?" <> qn <> "?>"
+                         else qn
+           lift $ report $ IgnoredElement name
+           return mempty
+
+
+         compactSpacing = case attrValue "spacing" e of
+                            "compact" -> True
+                            _         -> False
+
+         handleCompact = if compactSpacing
+                            then map (fmap paraToPlain)
+                            else id
+
+         literalLayout
+           | "monospaced" `elem` (T.words (attrValue "class" e))
+               = codeBlockWithLang
+           | otherwise = do
+               oldLiteralLayout <- gets dbLiteralLayout
+               modify $ \st -> st{ dbLiteralLayout = True }
+               content <- mconcat <$> mapM parseInline (elContent e)
+               let ls = map fromList . splitWhen (== LineBreak) . toList $ content
+               modify $ \st -> st{ dbLiteralLayout = oldLiteralLayout }
+               return $ lineBlock ls
+
+         codeBlockWithLang = do
+           let classes' = case attrValue "language" e of
+                                "" -> []
+                                x  -> [x]
+                ++ ["numberLines" | attrValue "linenumbering" e == "numbered"]
+           return $ codeBlockWith (attrValue "id" e, classes', [])
+                  $ trimNl $ strContentRecursive e
+         parseBlockquote = do
+            attrib <- case filterChild (named "attribution") e of
+                             Nothing  -> return mempty
+                             Just z   -> para . (str "— " <>) . mconcat
+                                         <$>
+                                              mapM parseInline (elContent z)
+            contents <- getBlocks e
+            return $ blockQuote (contents <> attrib)
+         listitems = mapM getBlocks $ filterChildren (named "listitem") e
+         callouts = mapM getBlocks $ filterChildren (named "callout") e
+         deflistitems = mapM parseVarListEntry $ filterChildren
+                     (named "varlistentry") e
+         steps = mapM getBlocks $ filterChildren (named "step") e
+         parseVarListEntry e' = do
+                     let terms = filterChildren (named "term") e'
+                     let items = filterChildren (named "listitem") e'
+                     terms' <- mapM getInlines terms
+                     items' <- mapM getBlocks items
+                     return (mconcat $ intersperse (str "; ") terms', items')
+         parseGlossEntry e' = do
+                     let terms = filterChildren (named "glossterm") e'
+                     let items = filterChildren (named "glossdef") e'
+                     terms' <- mapM getInlines terms
+                     items' <- mapM getBlocks items
+                     return (mconcat $ intersperse (str "; ") terms', items')
+         parseTable = do
+                      let elId = attrValue "id" e
+                      let attrs = case attrValue "tabstyle" e of
+                                    "" -> []
+                                    x  -> [("custom-style", x)]
+                      let classes = T.words $ attrValue "class" e
+                      let isCaption x = named "title" x || named "caption" x
+                      capt <- case filterChild isCaption e of
+                                    Just t  -> getInlines t
+                                    Nothing -> return mempty
+                      let e' = fromMaybe e $ filterChild (named "tgroup") e
+                      let isColspec x = named "colspec" x || named "col" x
+                      let colspecs = case filterChild (named "colgroup") e' of
+                                           Just c -> filterChildren isColspec c
+                                           _      -> filterChildren isColspec e'
+                      let colnames = case colspecs of
+                                       [] -> []
+                                       cs -> mapMaybe (findAttr (unqual "colname" )) cs
+                      let isRow x = named "row" x || named "tr" x
+                      headrows <- case filterChild (named "thead") e' of
+                                       Just h  -> mapM (parseRow colnames)
+                                                  $ filterChildren isRow h
+                                       Nothing -> return []
+                      bodyrows <- case filterChild (named "tbody") e' of
+                                       Just b  -> mapM (parseRow colnames)
+                                                  $ filterChildren isRow b
+                                       Nothing -> mapM (parseRow colnames)
+                                                  $ filterChildren isRow e'
+                      let toWidth c = do
+                            w <- findAttr (unqual "colwidth") c
+                            n <- safeRead $ "0" <> T.filter (\x ->
+                                                     (x >= '0' && x <= '9')
+                                                      || x == '.') w
+                            if n > 0 then Just n else Nothing
+                      let numrows = maybe 0 maximum $ nonEmpty
+                                                    $ map length (bodyrows ++ headrows)
+                      let aligns = case colspecs of
+                                     [] -> replicate numrows AlignDefault
+                                     cs -> map toAlignment cs
+                      let parseWidth s = safeRead (T.filter (\x -> (x >= '0' && x <= '9')
+                                                                   || x == '.') s)
+                      let textWidth = case filterChild (named "pi-dbfo") e of
+                                        Just d  -> case attrValue "table-width" d of
+                                                     "" -> 1.0
+                                                     w  -> fromMaybe 100.0 (parseWidth w) / 100.0
+                                        Nothing -> 1.0
+                      let widths = case colspecs of
+                                     [] -> replicate numrows ColWidthDefault
+                                     cs -> let ws = map toWidth cs
+                                           in case sequence ws of
+                                                Just ws' -> let colTot = sum ws'
+                                                                scale
+                                                                  | textWidth == 1.0 = (/ colTot)
+                                                                  | otherwise = (* (textWidth / colTot) )
+                                                            in  ColWidth . scale <$> ws'
+                                                Nothing  -> replicate numrows ColWidthDefault
+                      let toRow = Row nullAttr
+                      return $ tableWith (elId,classes,attrs)
+                                     (simpleCaption $ plain capt)
+                                     (zip aligns widths)
+                                     (TableHead nullAttr $ map toRow headrows)
+                                     [TableBody nullAttr 0 [] $ map toRow bodyrows]
+                                     (TableFoot nullAttr [])
+         sect n = sectWith(attrValue "id" e) [] [] n
+         sectWith elId classes attrs n = do
+           isbook <- gets dbBook
+           let n' = if isbook || n == 0 then n + 1 else n
+           headerText <- case filterChild (named "title") e `mplus`
+                              (filterChild (named "info") e >>=
+                                  filterChild (named "title")) of
+                            Just t  -> getInlines t
+                            Nothing -> return mempty
+           modify $ \st -> st{ dbSectionLevel = n }
+           b <- getBlocks e
+           modify $ \st -> st{ dbSectionLevel = n - 1 }
+           let hdr = addPandocAttributes (getRoleAttr e)
+                        $ headerWith (elId, classes, maybeToList titleabbrevElAsAttr ++ attrs)
+                                      n' headerText
+           return $ hdr <> b
+         titleabbrevElAsAttr =
+           case filterChild (named "titleabbrev") e `mplus`
+                (filterChild (named "info") e >>=
+                 filterChild (named "titleabbrev")) of
+             Just t  -> Just ("titleabbrev", strContentRecursive t)
+             Nothing -> Nothing
+         lineItems = mapM getInlines $ filterChildren (named "line") e
+
+         -- <title> elements can be directly nested inside an admonition block, use
+         -- it if it's there. It is unclear whether we should include the label in
+         -- the title: docbook references are ambiguous on that, and some implementations of admonitions
+         -- (e.g. asciidoctor) just use an icon in all cases. To be conservative, we don't
+         -- include the label and leave it to styling.
+         --
+         getTitle = case filterChild (named "title") e of
+                        Just t  -> Just <$> getInlines t
+                        Nothing -> return Nothing
+         withOptionalTitle p = do
+           mbt <- getTitle
+           b <- p
+           case mbt of
+             Nothing -> return b
+             Just t -> return $ divWith (attrValue "id" e, [], getRoleAttr e)
+                         (divWith ("", ["title"], []) (plain t) <> b)
+
+         -- Admonitions are parsed into a div. Following other Docbook tools that output HTML,
+         -- we parse the optional title as a div with the @title@ class, and give the
+         -- block itself a class corresponding to the admonition name.
+         parseAdmonition alwaysIncludeTitle label = do
+           mbt <- getTitle
+           -- this will ignore the title element if it is present:
+           b <- getBlocks e
+           let t = maybe mempty (divWith ("", ["title"], []) . plain)
+                        (case mbt of
+                           Nothing | alwaysIncludeTitle -> Just mempty
+                           _ -> mbt)
+           -- we also attach the label as a class, so it can be styled properly
+           return $ divWith (attrValue "id" e,[label],[]) (t <> b)
+
+toAlignment :: Element -> Alignment
+toAlignment c = case findAttr (unqual "align") c of
+                  Just "left"   -> AlignLeft
+                  Just "right"  -> AlignRight
+                  Just "center" -> AlignCenter
+                  _             -> AlignDefault
+
+
+parseMixed :: PandocMonad m => (Inlines -> Blocks) -> [Content] -> DB m Blocks
+parseMixed container conts = do
+  let (ils,rest) = break isBlockElement conts
+  ils' <- trimInlines . mconcat <$> mapM parseInline ils
+  let p = if ils' == mempty then mempty else container ils'
+  case rest of
+    [] -> return p
+    (r:rs) -> do
+      b <- parseBlock r
+      x <- parseMixed container rs
+      return $ p <> b <> x
+
+parseRow :: PandocMonad m => [Text] -> Element -> DB m [Cell]
+parseRow cn = do
+  let isEntry x = named "entry" x || named "td" x || named "th" x
+  mapM (parseEntry cn) . filterChildren isEntry
+
+parseEntry :: PandocMonad m => [Text] -> Element -> DB m Cell
+parseEntry cn el = do
+  let colDistance sa ea = do
+        let iStrt = elemIndex sa cn
+        let iEnd = elemIndex ea cn
+        case (iStrt, iEnd) of
+          (Just start, Just end) -> ColSpan $ end - start + 1
+          _ -> 1
+  let toColSpan en = do
+        let mStrt = findAttr (unqual "namest") en
+        let mEnd = findAttr (unqual "nameend") en
+        case (mStrt, mEnd) of
+          (Just start, Just end) -> colDistance start end
+          _ -> 1
+  let rowDistance mr = do
+        case readMaybe $ T.unpack mr :: Maybe Int of
+          Just moreRow -> RowSpan $ moreRow + 1
+          _ -> 1
+  let toRowSpan en = do
+        case findAttr (unqual "morerows") en of
+          Just moreRow -> rowDistance moreRow
+          _ -> 1
+  let colSpan = toColSpan el
+  let rowSpan = toRowSpan el
+  let align = toAlignment el
+  (fmap (cell align rowSpan colSpan) . parseMixed plain . elContent) el
+
+getInlines :: PandocMonad m => Element -> DB m Inlines
+getInlines e' = trimInlines . mconcat <$>
+                 mapM parseInline (elContent e')
+
+strContentRecursive :: Element -> Text
+strContentRecursive = strContent .
+  (\e' -> e'{ elContent = map elementToStr $ elContent e' })
+
+elementToStr :: Content -> Content
+elementToStr (Elem e') = Text $ CData CDataText (strContentRecursive e') Nothing
+elementToStr x = x
+
+childElTextAsAttr :: Text -> Element -> Maybe (Text, Text)
+childElTextAsAttr n e = case findChild q e of
+        Nothing -> Nothing
+        Just childEl -> Just (n, strContentRecursive childEl)
+        where q = QName n (Just "http://docbook.org/ns/docbook") Nothing
+
+attrValueAsOptionalAttr :: Text -> Element -> Maybe (Text, Text)
+attrValueAsOptionalAttr n e = case attrValue n e of
+        "" -> Nothing
+        _ -> Just (n, attrValue n e)
+
+parseInline :: PandocMonad m => Content -> DB m Inlines
+parseInline (Text (CData _ s _)) = do
+  literalLayout <- gets dbLiteralLayout
+  if literalLayout
+     then do
+       let ls = T.splitOn "\n" s
+       let toLiteralLine = str . T.map (\c -> if c == ' ' then '\xa0' else c)
+       return $ mconcat $ intersperse linebreak $ map toLiteralLine ls
+     else return $ text s
+parseInline (CRef ref) =
+  return $ text $ fromMaybe (T.toUpper ref) $ lookupEntity ref
+parseInline (Elem e) = do
+  parsedInline <- case qName (elName e) of
+        "anchor" -> do
+           return $ spanWith (attrValue "id" e, [], []) mempty
+        "phrase" -> do
+          let ident = attrValue "id" e
+          let classes = T.words $ attrValue "role" e
+          if ident /= "" || classes /= []
+            then innerInlines (spanWith (ident,classes,[]))
+            else innerInlines id
+        "indexterm" -> do
+          let ident = attrValue "id" e
+          let classes = T.words $ attrValue "role" e
+          let attrs =
+                -- In DocBook, <primary>, <secondary>, <tertiary>, <see>, and <seealso>
+                -- have mixed content models. However, because we're representing these
+                -- elements in Pandoc's AST as attributes of a phrase, we flatten all
+                -- the descendant content of these elements.
+                [ childElTextAsAttr "primary" e
+                , childElTextAsAttr "secondary" e
+                , childElTextAsAttr "tertiary" e
+                , childElTextAsAttr "see" e
+                , childElTextAsAttr "seealso" e
+                , attrValueAsOptionalAttr "significance" e
+                , attrValueAsOptionalAttr "startref" e
+                , attrValueAsOptionalAttr "scope" e
+                , attrValueAsOptionalAttr "class" e
+                -- We don't do anything with the "pagenum" attribute, because these only
+                -- occur within literal <index> sections, which is not supported by Pandoc,
+                -- because Pandoc has no concept of pages.
+                ]
+          return $ spanWith (ident, ("indexterm" : classes), (catMaybes attrs)) mempty
+        "equation" -> equation e displayMath
+        "informalequation" -> equation e displayMath
+        "inlineequation" -> equation e math
+        "subscript" -> innerInlines subscript
+        "superscript" -> innerInlines superscript
+        "inlinemediaobject" -> getMediaobject e
+        "quote" -> do
+            qt <- gets dbQuoteType
+            let qt' = if qt == SingleQuote then DoubleQuote else SingleQuote
+            modify $ \st -> st{ dbQuoteType = qt' }
+            contents <- innerInlines id
+            modify $ \st -> st{ dbQuoteType = qt }
+            return $ if qt == SingleQuote
+                        then singleQuoted contents
+                        else doubleQuoted contents
+        "simplelist" -> simpleList
+        "segmentedlist" -> segmentedList
+        "classname" -> codeWithLang
+        "code" -> codeWithLang
+        "citerefentry" -> do
+             let title = maybe mempty strContent $ filterChild (named "refentrytitle") e
+             let manvolnum = maybe mempty (\el -> "(" <> strContent el <> ")") $ filterChild (named "manvolnum") e
+             return $ codeWith ("",["citerefentry"],[]) (title <> manvolnum)
+        "filename" -> codeWithLang
+        "envar" -> codeWithLang
+        "literal" -> codeWithLang
+        "computeroutput" -> codeWithLang
+        "prompt" -> codeWithLang
+        "parameter" -> codeWithLang
+        "option" -> codeWithLang
+        "optional" -> do x <- getInlines e
+                         return $ str "[" <> x <> str "]"
+        "replaceable" -> do x <- getInlines e
+                            return $ str "<" <> x <> str ">"
+        "markup" -> codeWithLang
+        "wordasword" -> innerInlines emph
+        "command" -> codeWithLang
+        "varname" -> codeWithLang
+        "function" -> codeWithLang
+        "type"    -> codeWithLang
+        "symbol"  -> codeWithLang
+        "constant" -> codeWithLang
+        "userinput" -> codeWithLang
+        "systemitem" -> codeWithLang
+        "varargs" -> return $ code "(...)"
+        "keycap" -> return (str $ strContent e)
+        "keycombo" -> keycombo <$>
+                         mapM parseInline (elContent e)
+        "menuchoice" -> menuchoice <$>
+                         mapM parseInline (
+                                        filter isGuiMenu $ elContent e)
+        "xref" -> do
+            content <- dbContent <$> get
+            let linkend = attrValue "linkend" e
+            let title = case attrValue "endterm" e of
+                            ""      -> maybe "???" xrefTitleByElem
+                                         (findElementById linkend content)
+                            endterm -> maybe "???" strContent
+                                         (findElementById endterm content)
+            return $ link ("#" <> linkend) "" (text title)
+        "email" -> return $ link ("mailto:" <> strContent e) ""
+                          $ str $ strContent e
+        "uri" -> return $ link (strContent e) "" $ str $ strContent e
+        "ulink" -> innerInlines (link (attrValue "url" e) "")
+        "link" -> do
+             ils <- innerInlines id
+             let href = case findAttrBy
+                               (\case
+                                 QName "href" _ _ -> True
+                                 _ -> False) e of
+                               Just h -> h
+                               _      -> "#" <> attrValue "linkend" e
+             let ils' = if ils == mempty then str href else ils
+             let attr = (attrValue "id" e, T.words $ attrValue "role" e, [])
+             return $ linkWith attr href "" ils'
+        "foreignphrase" -> innerInlines emph
+        "emphasis" -> case attrValue "role" e of
+                             "bf"            -> innerInlines strong
+                             "bold"          -> innerInlines strong
+                             "strong"        -> innerInlines strong
+                             "strikethrough" -> innerInlines strikeout
+                             "underline"     -> innerInlines underline
+                             _               -> innerInlines emph
+        "footnote" -> note . mconcat <$>
+                         mapM parseBlock (elContent e)
+        "title" -> return mempty
+        "affiliation" -> skip
+        -- Note: this isn't a real docbook tag; it's what we convert
+        -- <?asciidor-br?> to in handleInstructions, above.
+        "pi-asciidoc-br" -> return linebreak
+        _          -> skip >> innerInlines id
+  return $ case qName (elName e) of
+    "emphasis" -> parsedInline
+    _ -> addPandocAttributes (getRoleAttr e) parsedInline
+   where skip = do
+           let qn = qName $ elName e
+           let name = if "pi-" `T.isPrefixOf` qn
+                         then "<?" <> qn <> "?>"
+                         else qn
+           lift $ report $ IgnoredElement name
+           return mempty
+
+         innerInlines f = f . mconcat <$> mapM parseInline (elContent e)
+         codeWithLang = do
+           let classes' = case attrValue "language" e of
+                               "" -> []
+                               l  -> [l]
+           return $ codeWith (attrValue "id" e,classes',[]) $
+             T.unwords $ T.words $ strContentRecursive e
+             -- collapse internal spaces/newlines, see #7821
+         simpleList = mconcat . intersperse (str "," <> space) <$> mapM getInlines
+                         (filterChildren (named "member") e)
+         segmentedList = do
+           tit <- maybe (return mempty) getInlines $ filterChild (named "title") e
+           segtits <- mapM getInlines $ filterChildren (named "segtitle") e
+           segitems <- mapM (mapM getInlines . filterChildren (named "seg"))
+                          $ filterChildren (named "seglistitem") e
+           let toSeg = mconcat . zipWith (\x y -> strong (x <> str ":") <> space <>
+                                  y <> linebreak) segtits
+           let segs = mconcat $ map toSeg segitems
+           let tit' = if tit == mempty
+                         then mempty
+                         else strong tit <> linebreak
+           return $ linebreak <> tit' <> segs
+         keycombo = spanWith ("",["keycombo"],[]) .
+                    mconcat . intersperse (str "+")
+         menuchoice = spanWith ("",["menuchoice"],[]) .
+                    mconcat . intersperse (text " > ")
+         isGuiMenu (Elem x) = named "guimenu" x || named "guisubmenu" x ||
+                              named "guimenuitem" x
+         isGuiMenu _        = False
+
+         findElementById idString content
+            = asum [filterElement (\x -> attrValue "id" x == idString) el | Elem el <- content]
+
+         -- Use the 'xreflabel' attribute for getting the title of a xref link;
+         -- if there's no such attribute, employ some heuristics based on what
+         -- docbook-xsl does.
+         xrefTitleByElem el
+             | not (T.null xrefLabel) = xrefLabel
+             | otherwise              = case qName (elName el) of
+                  "book"         -> descendantContent "title" el
+                  "part"         -> descendantContent "title" el
+                  "chapter"      -> descendantContent "title" el
+                  "section"      -> descendantContent "title" el
+                  "sect1"        -> descendantContent "title" el
+                  "sect2"        -> descendantContent "title" el
+                  "sect3"        -> descendantContent "title" el
+                  "sect4"        -> descendantContent "title" el
+                  "sect5"        -> descendantContent "title" el
+                  "cmdsynopsis"  -> descendantContent "command" el
+                  "funcsynopsis" -> descendantContent "function" el
+                  "figure"       -> descendantContent "title" el
+                  "table"        -> descendantContent "title" el
+                  _              -> qName (elName el) <> "_title"
+          where
+            xrefLabel = attrValue "xreflabel" el
+            descendantContent name = maybe "???" strContent
+                                   . filterElementName (\n -> qName n == name)
+
+-- | Extract a math equation from an element
+--
+-- asciidoc can generate Latex math in CDATA sections.
+--
+-- Note that if some MathML can't be parsed it is silently ignored!
+equation
+  :: Monad m
+  => Element
+  -- ^ The element from which to extract a mathematical equation
+  -> (Text -> Inlines)
+  -- ^ A constructor for some Inlines, taking the TeX code as input
+  -> m Inlines
+equation e constructor =
+  return $ mconcat $ map constructor $ mathMLEquations <> latexEquations
+  where
+    mathMLEquations :: [Text]
+    mathMLEquations = map writeTeX $ rights $ readMath
+      (\x -> qName (elName x) == "math" &&
+             qURI (elName x) == Just "http://www.w3.org/1998/Math/MathML")
+      (readMathML . showElement)
+
+    latexEquations :: [Text]
+    latexEquations = readMath (\x -> qName (elName x) == "mathphrase")
+                              (T.concat . fmap showVerbatimCData . elContent)
+
+    readMath :: (Element -> Bool) -> (Element -> b) -> [b]
+    readMath childPredicate fromElement =
+      map (fromElement . everywhere (mkT removePrefix))
+      $ filterChildren childPredicate e
+
+-- | Get the actual text stored in a CData block. 'showContent'
+-- returns the text still surrounded by the [[CDATA]] tags.
+showVerbatimCData :: Content -> Text
+showVerbatimCData (Text (CData _ d _)) = d
+showVerbatimCData c = showContent c
+
+
+-- | Set the prefix of a name to 'Nothing'
+removePrefix :: QName -> QName
+removePrefix elname = elname { qPrefix = Nothing }
+
+paraToPlain :: Block -> Block
+paraToPlain (Para ils) = Plain ils
+paraToPlain x = x
+
+docbookEntityMap :: M.Map Text Text
+docbookEntityMap = M.fromList
+  (map lineToPair (T.lines (decodeUtf8 docbookEntities)))
+ where
+   lineToPair l =
+     case T.words l of
+       (x:ys) -> (x, T.pack (mapMaybe readHex ys))
+       [] -> ("","")
+   readHex t = case TR.hexadecimal t of
+                 Left _ -> Nothing
+                 Right (n,_) -> Just (chr n)
+
+docbookEntities :: ByteString
+docbookEntities = $(embedFile "data/docbook-entities.txt")
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
@@ -1,28 +1,12 @@
 {-# LANGUAGE CPP               #-}
 {-# LANGUAGE OverloadedStrings #-}
 {-# LANGUAGE PatternGuards     #-}
-
-{-
-Copyright (C) 2014-2017 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
--}
-
+{-# LANGUAGE FlexibleContexts  #-}
+{-# LANGUAGE LambdaCase        #-}
+{-# LANGUAGE ViewPatterns      #-}
 {- |
    Module      : Text.Pandoc.Readers.Docx
-   Copyright   : Copyright (C) 2014-2017 Jesse Rosenthal
+   Copyright   : Copyright (C) 2014-2020 Jesse Rosenthal
    License     : GNU GPL, version 2 or above
 
    Maintainer  : Jesse Rosenthal <jrosenthal@jhu.edu>
@@ -40,7 +24,7 @@
 
   - [X] Para
   - [X] CodeBlock (styled with `SourceCode`)
-  - [X] BlockQuote (styled with `Quote`, `BlockQuote`, or, optionally,
+  - [X] BlockQuote (styled with `Quote`, `BlockQuote`, `Intense Quote` or, optionally,
         indented)
   - [X] OrderedList
   - [X] BulletList
@@ -76,83 +60,115 @@
        ) where
 
 import Codec.Archive.Zip
+import Control.Monad ( liftM, unless )
 import Control.Monad.Reader
+    ( asks,
+      MonadReader(local),
+      MonadTrans(lift),
+      ReaderT(runReaderT) )
 import Control.Monad.State.Strict
+    ( StateT,
+      gets,
+      modify,
+      evalStateT )
+import Data.Bifunctor (bimap, first)
 import qualified Data.ByteString.Lazy as B
 import Data.Default (Default)
 import Data.List (delete, intersect)
+import qualified Data.List as L
+import Data.Char (isSpace)
 import qualified Data.Map as M
+import qualified Data.Text as T
+import Data.Maybe (isJust, fromMaybe, mapMaybe)
 import Data.Sequence (ViewL (..), viewl)
 import qualified Data.Sequence as Seq
 import qualified Data.Set as Set
-import Text.Pandoc.Builder
--- import Text.Pandoc.Definition
+import Citeproc (ItemId(..), Val(TextVal,FancyVal), Reference(..), CitationItem(..))
+import qualified Citeproc
+import Text.Pandoc.Builder as Pandoc
 import Text.Pandoc.MediaBag (MediaBag)
 import Text.Pandoc.Options
 import Text.Pandoc.Readers.Docx.Combine
 import Text.Pandoc.Readers.Docx.Lists
-import Text.Pandoc.Readers.Docx.Parse
+import Text.Pandoc.Readers.Docx.Parse as Docx
 import Text.Pandoc.Shared
 import Text.Pandoc.Walk
 import Text.TeXMath (writeTeX)
-#if !(MIN_VERSION_base(4,8,0))
-import Data.Traversable (traverse)
-#endif
-import Control.Monad.Except (throwError)
-import Text.Pandoc.Class (PandocMonad)
-import qualified Text.Pandoc.Class as P
+import Control.Monad.Except (throwError, catchError)
+import Text.Pandoc.Class.PandocMonad (PandocMonad)
+import qualified Text.Pandoc.Class.PandocMonad as P
 import Text.Pandoc.Error
 import Text.Pandoc.Logging
+import Data.List.NonEmpty (nonEmpty)
+import Data.Aeson (eitherDecode)
+import qualified Data.Text.Lazy as TL
+import Text.Pandoc.UTF8 (fromTextLazy)
+import Text.Pandoc.Citeproc.MetaValue (referenceToMetaValue)
+import Text.Pandoc.Readers.EndNote (readEndNoteXMLCitation)
 
 readDocx :: PandocMonad m
          => ReaderOptions
          -> B.ByteString
          -> m Pandoc
-readDocx opts bytes
-  | Right archive <- toArchiveOrFail bytes
-  , Right (docx, parserWarnings) <- archiveToDocxWithWarnings archive = do
-      mapM_ (P.report . DocxParserWarning) parserWarnings
-      (meta, blks) <- docxToOutput opts docx
-      return $ Pandoc meta blks
-readDocx _ _ =
-  throwError $ PandocSomeError "couldn't parse docx file"
+readDocx opts bytes =
+  case toArchiveOrFail bytes of
+    Right archive ->
+      case archiveToDocxWithWarnings archive of
+        Right (docx, parserWarnings) -> do
+          mapM_ (P.report . DocxParserWarning) parserWarnings
+          (meta, blks) <- docxToOutput opts docx
+          return $ Pandoc meta blks
+        Left docxerr -> throwError $ PandocSomeError $
+                         "couldn't parse docx file: " <> T.pack (show docxerr)
+    Left err -> throwError $ PandocSomeError $
+                  "couldn't unpack docx container: " <> T.pack err
 
-data DState = DState { docxAnchorMap :: M.Map String String
+data DState = DState { docxAnchorMap :: M.Map T.Text T.Text
+                     , docxAnchorSet :: Set.Set T.Text
+                     , docxImmedPrevAnchor :: Maybe T.Text
                      , docxMediaBag  :: MediaBag
+                     , docxNumberedHeadings :: Bool
                      , docxDropCap   :: Inlines
-                     , docxWarnings  :: [String]
                      -- keep track of (numId, lvl) values for
                      -- restarting
-                     , docxListState :: M.Map (String, String) Integer
+                     , docxListState :: M.Map (T.Text, T.Text) Integer
+                     , docxPrevPara  :: Inlines
+                     , docxReferences :: M.Map ItemId (Reference Inlines)
                      }
 
 instance Default DState where
   def = DState { docxAnchorMap = M.empty
+               , docxAnchorSet = mempty
+               , docxImmedPrevAnchor = Nothing
                , docxMediaBag  = mempty
+               , docxNumberedHeadings = False
                , docxDropCap   = mempty
-               , docxWarnings  = []
                , docxListState = M.empty
+               , docxPrevPara  = mempty
+               , docxReferences = mempty
                }
 
 data DEnv = DEnv { docxOptions       :: ReaderOptions
-                 , docxInHeaderBlock :: Bool }
+                 , docxInHeaderBlock :: Bool
+                 , docxInBidi        :: Bool
+                 }
 
 instance Default DEnv where
-  def = DEnv def False
+  def = DEnv def False False
 
 type DocxContext m = ReaderT DEnv (StateT DState m)
 
 evalDocxContext :: PandocMonad m => DocxContext m a -> DEnv -> DState -> m a
-evalDocxContext ctx env st = flip evalStateT st $flip runReaderT env ctx
+evalDocxContext ctx env st = flip evalStateT st $ runReaderT ctx env
 
 -- This is empty, but we put it in for future-proofing.
-spansToKeep :: [String]
+spansToKeep :: [CharStyleName]
 spansToKeep = []
 
-divsToKeep :: [String]
-divsToKeep = ["list-item", "Definition", "DefinitionTerm"]
+divsToKeep :: [ParaStyleName]
+divsToKeep = ["Definition", "Definition Term"]
 
-metaStyles :: M.Map String String
+metaStyles :: M.Map ParaStyleName T.Text
 metaStyles = M.fromList [ ("Title", "title")
                         , ("Subtitle", "subtitle")
                         , ("Author", "author")
@@ -164,7 +180,7 @@
 
 isMetaPar :: BodyPart -> Bool
 isMetaPar (Paragraph pPr _) =
-  not $ null $ intersect (pStyle pPr) (M.keys metaStyles)
+  not $ null $ intersect (getStyleNames $ pStyle pPr) (M.keys metaStyles)
 isMetaPar _ = False
 
 isEmptyPar :: BodyPart -> Bool
@@ -177,15 +193,17 @@
     isEmptyElem _           = True
 isEmptyPar _ = False
 
-bodyPartsToMeta' :: PandocMonad m => [BodyPart] -> DocxContext m (M.Map String MetaValue)
+bodyPartsToMeta' :: PandocMonad m => [BodyPart] -> DocxContext m (M.Map T.Text MetaValue)
 bodyPartsToMeta' [] = return M.empty
 bodyPartsToMeta' (bp : bps)
   | (Paragraph pPr parParts) <- bp
-  , (c : _)<- intersect (pStyle pPr) (M.keys metaStyles)
+  , (c : _)<- getStyleNames (pStyle pPr) `intersect` M.keys metaStyles
   , (Just metaField) <- M.lookup c metaStyles = do
     inlines <- smushInlines <$> mapM parPartToInlines parParts
     remaining <- bodyPartsToMeta' bps
     let
+      -- for titles, we just take the first one and ignore the rest, #10359:
+      f _ x | metaField == "title" || metaField == "subtitle" = x
       f (MetaInlines ils) (MetaInlines ils') = MetaBlocks [Para ils, Para ils']
       f (MetaInlines ils) (MetaBlocks blks) = MetaBlocks (Para ils : blks)
       f m (MetaList mv) = MetaList (m : mv)
@@ -203,20 +221,33 @@
   return $ Meta mp'
 
 fixAuthors :: MetaValue -> MetaValue
-fixAuthors (MetaBlocks blks) =
-  MetaList $ map g $ filter f blks
-    where f (Para _) = True
-          f _        = False
-          g (Para ils) = MetaInlines ils
-          g _          = MetaInlines []
+fixAuthors (MetaBlocks blks) = MetaList [MetaInlines ils | Para ils <- blks]
 fixAuthors mv = mv
 
-codeStyles :: [String]
-codeStyles = ["VerbatimChar"]
+isInheritedFromStyles :: (Eq (StyleName s), HasStyleName s, HasParentStyle s) => [StyleName s] -> s -> Bool
+isInheritedFromStyles names sty
+  | getStyleName sty `elem` names = True
+  | Just psty <- getParentStyle sty = isInheritedFromStyles names psty
+  | otherwise = False
 
-codeDivs :: [String]
-codeDivs = ["SourceCode"]
+hasStylesInheritedFrom :: [ParaStyleName] -> ParagraphStyle -> Bool
+hasStylesInheritedFrom ns s = any (isInheritedFromStyles ns) $ pStyle s
 
+removeStyleNamed :: ParaStyleName -> ParagraphStyle -> ParagraphStyle
+removeStyleNamed sn ps = ps{pStyle = filter (\psd -> getStyleName psd /= sn) $ pStyle ps}
+
+isCodeCharStyle :: CharStyle -> Bool
+isCodeCharStyle = isInheritedFromStyles ["Verbatim Char"]
+
+isCodeDiv :: ParagraphStyle -> Bool
+isCodeDiv = hasStylesInheritedFrom ["Source Code", "SourceCode", "source_code"]
+
+isBlockQuote :: ParStyle -> Bool
+isBlockQuote =
+  isInheritedFromStyles [
+    "Quote", "Block Text", "Block Quote", "Block Quotation", "Intense Quote"
+    ]
+
 runElemToInlines :: RunElem -> Inlines
 runElemToInlines (TextRun s)   = text s
 runElemToInlines LnBrk         = linebreak
@@ -224,160 +255,176 @@
 runElemToInlines SoftHyphen    = text "\xad"
 runElemToInlines NoBreakHyphen = text "\x2011"
 
-runElemToString :: RunElem -> String
-runElemToString (TextRun s)   = s
-runElemToString LnBrk         = ['\n']
-runElemToString Tab           = ['\t']
-runElemToString SoftHyphen    = ['\xad']
-runElemToString NoBreakHyphen = ['\x2011']
+runElemToText :: RunElem -> T.Text
+runElemToText (TextRun s)   = s
+runElemToText LnBrk         = T.singleton '\n'
+runElemToText Tab           = T.singleton '\t'
+runElemToText SoftHyphen    = T.singleton '\xad'
+runElemToText NoBreakHyphen = T.singleton '\x2011'
 
-runToString :: Run -> String
-runToString (Run _ runElems) = concatMap runElemToString runElems
-runToString _                = ""
+runToText :: Run -> T.Text
+runToText (Run _ runElems) = T.concat $ map runElemToText runElems
+runToText _                = ""
 
-parPartToString :: ParPart -> String
-parPartToString (PlainRun run)             = runToString run
-parPartToString (InternalHyperLink _ runs) = concatMap runToString runs
-parPartToString (ExternalHyperLink _ runs) = concatMap runToString runs
-parPartToString _                          = ""
+parPartToText :: ParPart -> T.Text
+parPartToText (PlainRun run)             = runToText run
+parPartToText (InternalHyperLink _ children) = T.concat $ map parPartToText children
+parPartToText (ExternalHyperLink _ children) = T.concat $ map parPartToText children
+parPartToText _                          = ""
 
-blacklistedCharStyles :: [String]
+blacklistedCharStyles :: [CharStyleName]
 blacklistedCharStyles = ["Hyperlink"]
 
-resolveDependentRunStyle :: RunStyle -> RunStyle
+resolveDependentRunStyle :: PandocMonad m => RunStyle -> DocxContext m RunStyle
 resolveDependentRunStyle rPr
-  | Just (s, _)  <- rStyle rPr, s `elem` blacklistedCharStyles =
-    rPr
-  | Just (_, cs) <- rStyle rPr =
-      let rPr' = resolveDependentRunStyle cs
-      in
-       RunStyle { isBold = case isBold rPr of
-                     Just bool -> Just bool
-                     Nothing   -> isBold rPr'
-                , isItalic = case isItalic rPr of
-                     Just bool -> Just bool
-                     Nothing   -> isItalic rPr'
-                , isSmallCaps = case isSmallCaps rPr of
-                     Just bool -> Just bool
-                     Nothing   -> isSmallCaps rPr'
-                , isStrike = case isStrike rPr of
-                     Just bool -> Just bool
-                     Nothing   -> isStrike rPr'
-                , rVertAlign = case rVertAlign rPr of
-                     Just valign -> Just valign
-                     Nothing     -> rVertAlign rPr'
-                , rUnderline = case rUnderline rPr of
-                     Just ulstyle -> Just ulstyle
-                     Nothing      -> rUnderline rPr'
-                , rStyle = rStyle rPr }
-  | otherwise = rPr
+  | Just s  <- rParentStyle rPr
+  , getStyleName s `notElem` blacklistedCharStyles = do
+      opts <- asks docxOptions
+      if isEnabled Ext_styles opts
+        then return rPr
+        else leftBiasedMergeRunStyle rPr <$> resolveDependentRunStyle (cStyleData s)
+  | otherwise = return rPr
 
-runStyleToTransform :: RunStyle -> (Inlines -> Inlines)
-runStyleToTransform rPr
-  | Just (s, _) <- rStyle rPr
-  , s `elem` spansToKeep =
-    let rPr' = rPr{rStyle = Nothing}
-    in
-     spanWith ("", [s], []) . runStyleToTransform rPr'
-  | Just True <- isItalic rPr =
-      emph . runStyleToTransform rPr {isItalic = Nothing}
-  | Just True <- isBold rPr =
-      strong . runStyleToTransform rPr {isBold = Nothing}
-  | Just True <- isSmallCaps rPr =
-      smallcaps . runStyleToTransform rPr {isSmallCaps = Nothing}
-  | Just True <- isStrike rPr =
-      strikeout . runStyleToTransform rPr {isStrike = Nothing}
-  | Just SupScrpt <- rVertAlign rPr =
-      superscript . runStyleToTransform rPr {rVertAlign = Nothing}
-  | Just SubScrpt <- rVertAlign rPr =
-      subscript . runStyleToTransform rPr {rVertAlign = Nothing}
-  | Just "single" <- rUnderline rPr =
-      underlineSpan . runStyleToTransform rPr {rUnderline = Nothing}
-  | otherwise = id
+runStyleToTransform :: PandocMonad m => RunStyle -> DocxContext m (Inlines -> Inlines)
+runStyleToTransform rPr' = do
+  opts <- asks docxOptions
+  inBidi <- asks docxInBidi
+  let styles = isEnabled Ext_styles opts
+      ctl = (Just True == isRTL rPr') || (Just True == isForceCTL rPr')
+      italic rPr | ctl = isItalicCTL rPr
+                 | otherwise = isItalic rPr
+      bold rPr | ctl = isBoldCTL rPr
+               | otherwise = isBold rPr
+      go rPr
+        | Just sn <- getStyleName <$> rParentStyle rPr
+        , sn `elem` spansToKeep =
+            spanWith ("", [normalizeToClassName sn], [])
+            . go rPr{rParentStyle = Nothing}
+        | styles, Just s <- rParentStyle rPr =
+             spanWith (extraAttr s) . go rPr{rParentStyle = Nothing}
+        | Just True <- italic rPr =
+            emph . go rPr{isItalic = Nothing, isItalicCTL = Nothing}
+        | Just True <- bold rPr =
+            strong . go rPr{isBold = Nothing, isBoldCTL = Nothing}
+        | Just v <- rHighlight rPr
+        , v /= "none" =
+            spanWith ("",["mark"],[]) . go rPr{rHighlight = Nothing}
+        | Just True <- isSmallCaps rPr =
+            smallcaps . go rPr{isSmallCaps = Nothing}
+        | Just True <- isStrike rPr =
+            strikeout . go rPr{isStrike = Nothing}
+        | Just True <- isRTL rPr =
+            spanWith ("",[],[("dir","rtl")]) . go rPr{isRTL = Nothing}
+        | inBidi, Just False <- isRTL rPr =
+            spanWith ("",[],[("dir","ltr")]) . go rPr{isRTL = Nothing}
+        | Just SupScrpt <- rVertAlign rPr =
+            superscript . go rPr{rVertAlign = Nothing}
+        | Just SubScrpt <- rVertAlign rPr =
+            subscript . go rPr{rVertAlign = Nothing}
+        | Just "single" <- rUnderline rPr =
+            Pandoc.underline . go rPr{rUnderline = Nothing}
+        | otherwise = id
+  return $ go rPr'
 
+
 runToInlines :: PandocMonad m => Run -> DocxContext m Inlines
 runToInlines (Run rs runElems)
-  | Just (s, _) <- rStyle rs
-  , s `elem` codeStyles =
-    let rPr = resolveDependentRunStyle rs
-        codeString = code $ concatMap runElemToString runElems
-    in
-     return $ case rVertAlign rPr of
-     Just SupScrpt -> superscript codeString
-     Just SubScrpt -> subscript codeString
-     _             -> codeString
+  | maybe False isCodeCharStyle $ rParentStyle rs = do
+      rPr <- resolveDependentRunStyle rs
+      let codeString = code $ T.concat $ map runElemToText runElems
+      return $ case rVertAlign rPr of
+        Just SupScrpt -> superscript codeString
+        Just SubScrpt -> subscript codeString
+        _             -> codeString
   | otherwise = do
-    let ils = smushInlines (map runElemToInlines runElems)
-    return $ (runStyleToTransform $ resolveDependentRunStyle rs) ils
-runToInlines (Footnote bps) = do
-  blksList <- smushBlocks <$> mapM bodyPartToBlocks bps
-  return $ note blksList
-runToInlines (Endnote bps) = do
-  blksList <- smushBlocks <$> mapM bodyPartToBlocks bps
-  return $ note blksList
+      rPr <- resolveDependentRunStyle rs
+      let ils = smushInlines (map runElemToInlines runElems)
+      transform <- runStyleToTransform rPr
+      return $ transform ils
+runToInlines (Footnote bps) = note . smushBlocks <$> mapM bodyPartToBlocks bps
+runToInlines (Endnote bps) = note . smushBlocks <$> mapM bodyPartToBlocks bps
 runToInlines (InlineDrawing fp title alt bs ext) = do
   (lift . lift) $ P.insertMedia fp Nothing bs
-  return $ imageWith (extentToAttr ext) fp title $ text alt
+  return $ imageWith (extentToAttr ext) (T.pack fp) title $ text alt
 runToInlines InlineChart = return $ spanWith ("", ["chart"], []) $ text "[CHART]"
+runToInlines InlineDiagram = return $ spanWith ("", ["diagram"], []) $ text "[DIAGRAM]"
 
 extentToAttr :: Extent -> Attr
 extentToAttr (Just (w, h)) =
   ("", [], [("width", showDim w), ("height", showDim h)] )
   where
-    showDim d = show (d / 914400) ++ "in"
+    showDim d = tshow (d / 914400) <> "in"
 extentToAttr _ = nullAttr
 
-blocksToInlinesWarn :: PandocMonad m => String -> Blocks -> DocxContext m Inlines
+blocksToInlinesWarn :: PandocMonad m => T.Text -> Blocks -> DocxContext m Inlines
 blocksToInlinesWarn cmtId blks = do
-  let blkList = toList blks
-      notParaOrPlain :: Block -> Bool
-      notParaOrPlain (Para _)  = False
-      notParaOrPlain (Plain _) = False
-      notParaOrPlain _         = True
-  unless (null $ filter notParaOrPlain blkList) $
+  let paraOrPlain :: Block -> Bool
+      paraOrPlain (Para _)       = True
+      paraOrPlain (Plain _)      = True
+      paraOrPlain (Div _ nested) = all paraOrPlain nested
+      paraOrPlain _              = False
+  unless (all paraOrPlain blks) $
     lift $ P.report $ DocxParserWarning $
-      "Docx comment " ++ cmtId ++ " will not retain formatting"
-  return $ blocksToInlines' blkList
+      "Docx comment " <> cmtId <> " will not retain formatting"
+  return $ blocksToInlines' (toList blks)
 
+-- The majority of work in this function is done in the primed
+-- subfunction `partPartToInlines'`. We make this wrapper so that we
+-- don't have to modify `docxImmedPrevAnchor` state after every function.
 parPartToInlines :: PandocMonad m => ParPart -> DocxContext m Inlines
-parPartToInlines (PlainRun r) = runToInlines r
-parPartToInlines (Insertion _ author date runs) = do
+parPartToInlines parPart =
+  case parPart of
+    (BookMark _ anchor) | anchor `notElem` dummyAnchors -> do
+      inHdrBool <- asks docxInHeaderBlock
+      ils <- parPartToInlines' parPart
+      immedPrevAnchor <- gets docxImmedPrevAnchor
+      unless (isJust immedPrevAnchor || inHdrBool)
+        (modify $ \s -> s{ docxImmedPrevAnchor = Just anchor})
+      return ils
+    _ -> do
+      ils <- parPartToInlines' parPart
+      modify $ \s -> s{ docxImmedPrevAnchor = Nothing}
+      return ils
+
+parPartToInlines' :: PandocMonad m => ParPart -> DocxContext m Inlines
+parPartToInlines' (PlainRun r) = runToInlines r
+parPartToInlines' (ChangedRuns (TrackedChange Insertion (ChangeInfo _ author date)) pparts) = do
   opts <- asks docxOptions
   case readerTrackChanges opts of
-    AcceptChanges -> smushInlines <$> mapM runToInlines runs
+    AcceptChanges -> smushInlines <$> mapM parPartToInlines pparts
     RejectChanges -> return mempty
     AllChanges    -> do
-      ils <- smushInlines <$> mapM runToInlines runs
-      let attr = ("", ["insertion"], [("author", author), ("date", date)])
+      ils <- smushInlines <$> mapM parPartToInlines pparts
+      let attr = ("", ["insertion"], addAuthorAndDate author date)
       return $ spanWith attr ils
-parPartToInlines (Deletion _ author date runs) = do
+parPartToInlines' (ChangedRuns (TrackedChange Deletion (ChangeInfo _ author date)) pparts) = do
   opts <- asks docxOptions
   case readerTrackChanges opts of
     AcceptChanges -> return mempty
-    RejectChanges -> smushInlines <$> mapM runToInlines runs
+    RejectChanges -> smushInlines <$> mapM parPartToInlines pparts
     AllChanges    -> do
-      ils <- smushInlines <$> mapM runToInlines runs
-      let attr = ("", ["deletion"], [("author", author), ("date", date)])
+      ils <- smushInlines <$> mapM parPartToInlines pparts
+      let attr = ("", ["deletion"], addAuthorAndDate author date)
       return $ spanWith attr ils
-parPartToInlines (CommentStart cmtId author date bodyParts) = do
+parPartToInlines' (CommentStart cmtId author date bodyParts) = do
   opts <- asks docxOptions
   case readerTrackChanges opts of
     AllChanges -> do
       blks <- smushBlocks <$> mapM bodyPartToBlocks bodyParts
       ils <- blocksToInlinesWarn cmtId blks
-      let attr = ("", ["comment-start"], [("id", cmtId), ("author", author), ("date", date)])
+      let attr = ("", ["comment-start"], ("id", cmtId) : addAuthorAndDate author date)
       return $ spanWith attr ils
     _ -> return mempty
-parPartToInlines (CommentEnd cmtId) = do
+parPartToInlines' (CommentEnd cmtId) = do
   opts <- asks docxOptions
   case readerTrackChanges opts of
     AllChanges -> do
       let attr = ("", ["comment-end"], [("id", cmtId)])
       return $ spanWith attr mempty
     _ -> return mempty
-parPartToInlines (BookMark _ anchor) | anchor `elem` dummyAnchors =
+parPartToInlines' (BookMark _ anchor) | anchor `elem` dummyAnchors =
   return mempty
-parPartToInlines (BookMark _ anchor) =
+parPartToInlines' (BookMark _ anchor) =
   -- We record these, so we can make sure not to overwrite
   -- user-defined anchor links with header auto ids.
   do
@@ -393,36 +440,139 @@
     -- of rewriting user-defined anchor links. However, since these
     -- are not defined in pandoc, it seems like a necessary evil to
     -- avoid an extra pass.
-    let newAnchor =
-          if not inHdrBool && anchor `elem` M.elems anchorMap
-          then uniqueIdent [Str anchor] (Set.fromList $ M.elems anchorMap)
-          else anchor
-    unless inHdrBool
-      (modify $ \s -> s { docxAnchorMap = M.insert anchor newAnchor anchorMap})
-    return $ spanWith (newAnchor, ["anchor"], []) mempty
-parPartToInlines (Drawing fp title alt bs ext) = do
+    immedPrevAnchor <- gets docxImmedPrevAnchor
+    case immedPrevAnchor of
+      Just prevAnchor | not inHdrBool -> do
+        (modify $ \s -> s { docxAnchorMap = M.insert anchor prevAnchor anchorMap})
+        return mempty
+      _ -> do
+        exts <- asks (readerExtensions . docxOptions)
+        let newAnchor =
+              if not inHdrBool && anchor `elem` M.elems anchorMap
+              then uniqueIdent exts [Str anchor]
+                     (Set.fromList $ M.elems anchorMap)
+              else anchor
+        unless inHdrBool
+          (modify $ \s -> s { docxAnchorMap = M.insert anchor newAnchor anchorMap})
+        return $ spanWith (newAnchor, ["anchor"], []) mempty
+parPartToInlines' (Drawing fp title alt bs ext) = do
   (lift . lift) $ P.insertMedia fp Nothing bs
-  return $ imageWith (extentToAttr ext) fp title $ text alt
-parPartToInlines Chart =
+  return $ imageWith (extentToAttr ext) (T.pack fp) title $ text alt
+parPartToInlines' Chart =
   return $ spanWith ("", ["chart"], []) $ text "[CHART]"
-parPartToInlines (InternalHyperLink anchor runs) = do
-  ils <- smushInlines <$> mapM runToInlines runs
-  return $ link ('#' : anchor) "" ils
-parPartToInlines (ExternalHyperLink target runs) = do
-  ils <- smushInlines <$> mapM runToInlines runs
+parPartToInlines' Diagram =
+  return $ spanWith ("", ["diagram"], []) $ text "[DIAGRAM]"
+parPartToInlines' (InternalHyperLink anchor children) = do
+  ils <- smushInlines <$> mapM parPartToInlines' children
+  return $ link ("#" <> anchor) "" ils
+parPartToInlines' (ExternalHyperLink target children) = do
+  ils <- smushInlines <$> mapM parPartToInlines' children
   return $ link target "" ils
-parPartToInlines (PlainOMath exps) =
+parPartToInlines' (PlainOMath exps) =
   return $ math $ writeTeX exps
-parPartToInlines (SmartTag runs) = do
-  smushInlines <$> mapM runToInlines runs
+parPartToInlines' (OMathPara exps) =
+  return $ displayMath $ writeTeX exps
+parPartToInlines' (Field info children) =
+  case info of
+    HyperlinkField url -> parPartToInlines' $ ExternalHyperLink url children
+    IndexrefField ie ->
+      pure $ spanWith ("",["indexref"],
+                           (("entry", entryTitle ie) :
+                             maybe [] (\x -> [("crossref",x)]) (entrySee ie)
+                          ++ maybe [] (\x -> [("yomi",x)]) (entryYomi ie)
+                          ++ [("bold","") | entryBold ie]
+                          ++ [("italic","") | entryItalic ie])) mempty
+    PagerefField fieldAnchor True -> parPartToInlines' $ InternalHyperLink fieldAnchor children
+    CrossrefField fieldAnchor True -> parPartToInlines' $ InternalHyperLink fieldAnchor children
+    EndNoteCite t -> do
+      formattedCite <- smushInlines <$> mapM parPartToInlines' children
+      opts <- asks docxOptions
+      if isEnabled Ext_citations opts
+         then catchError
+              (do citation <- readEndNoteXMLCitation t
+                  cs <- handleCitation citation
+                  return $ cite cs formattedCite)
+              (\case
+                  PandocXMLError _ msg -> do
+                    P.report $ DocxParserWarning
+                             ("Cannot parse EndNote citation: " <> msg)
+                    return formattedCite
+                  e -> throwError e)
+         else return formattedCite
+    CslCitation t -> do
+      formattedCite <- smushInlines <$> mapM parPartToInlines' children
+      opts <- asks docxOptions
+      if isEnabled Ext_citations opts
+         then do
+           let bs = fromTextLazy $ TL.fromStrict t
+           case eitherDecode bs of
+             Left _err -> return formattedCite
+             Right citation -> do
+               cs <- handleCitation citation
+               return $ cite cs formattedCite
+         else return formattedCite
+    CslBibliography -> do
+      opts <- asks docxOptions
+      if isEnabled Ext_citations opts
+         then return mempty -- omit Zotero-generated bibliography
+         else smushInlines <$> mapM parPartToInlines' children
+    EndNoteRefList -> do
+      opts <- asks docxOptions
+      if isEnabled Ext_citations opts
+         then return mempty -- omit EndNote-generated bibliography
+         else smushInlines <$> mapM parPartToInlines' children
+    _ -> smushInlines <$> mapM parPartToInlines' children
 
+-- Helper function to convert CitationItemType to CitationMode
+convertCitationMode :: Citeproc.CitationItemType -> CitationMode
+convertCitationMode itemType = case itemType of
+                                 Citeproc.NormalCite -> NormalCitation
+                                 Citeproc.SuppressAuthor -> SuppressAuthor
+                                 Citeproc.AuthorOnly -> AuthorInText
+
+-- Turn a 'Citeproc.Citation' into a list of 'Text.Pandoc.Definition.Citation',
+-- and store the embedded bibliographic data in state.
+handleCitation :: PandocMonad m
+               => Citeproc.Citation T.Text
+               -> DocxContext m [Citation]
+handleCitation citation = do
+  let getItemId item =
+        case citationItemData item >>= M.lookup "citation-key" . referenceVariables of
+          Just (TextVal k) -> ItemId k
+          Just (FancyVal k) -> ItemId k
+          _ -> citationItemId item
+  let toPandocCitation item =
+        Citation{ citationId = unItemId (getItemId item)
+                , citationPrefix = maybe [] (toList . text) $
+                                     Citeproc.citationItemPrefix item
+                , citationSuffix = (toList . text) $
+                    maybe mempty (\x -> ", " <>
+                       maybe "" (<>" ") (Citeproc.citationItemLabel item)
+                         <> x <> " ")
+                     (Citeproc.citationItemLocator item)
+                    <> fromMaybe mempty (Citeproc.citationItemSuffix item)
+                , citationMode = convertCitationMode (Citeproc.citationItemType item)
+                , citationNoteNum = 0
+                , citationHash = 0 }
+  let items = Citeproc.citationItems citation
+  let cs = map toPandocCitation items
+  let refs = mapMaybe (\item -> fmap (\itemData -> text <$>
+                                        -- see #10366, sometimes itemData has a different
+                                        -- id and we need to use the same one:
+                                        itemData{ referenceId = getItemId item })
+                                  (Citeproc.citationItemData item)) items
+  modify $ \st ->
+    st{ docxReferences = foldr
+          (\ref -> M.insert (referenceId ref) ref)
+          (docxReferences st)
+          refs }
+  return cs
+
 isAnchorSpan :: Inline -> Bool
-isAnchorSpan (Span (_, classes, kvs) _) =
-  classes == ["anchor"] &&
-  null kvs
+isAnchorSpan (Span (_, ["anchor"], []) _) = True
 isAnchorSpan _ = False
 
-dummyAnchors :: [String]
+dummyAnchors :: [T.Text]
 dummyAnchors = ["_GoBack"]
 
 makeHeaderAnchor :: PandocMonad m => Blocks -> DocxContext m Blocks
@@ -435,8 +585,9 @@
   | (c:_) <- filter isAnchorSpan ils
   , (Span (anchIdent, ["anchor"], _) cIls) <- c = do
     hdrIDMap <- gets docxAnchorMap
-    let newIdent = if null ident
-                   then uniqueIdent ils (Set.fromList $ M.elems hdrIDMap)
+    exts <- asks (readerExtensions . docxOptions)
+    let newIdent = if T.null ident
+                   then uniqueIdent exts ils (Set.fromList $ M.elems hdrIDMap)
                    else ident
         newIls = concatMap f ils where f il | il == c   = cIls
                                             | otherwise = [il]
@@ -447,8 +598,9 @@
 makeHeaderAnchor' (Header n (ident, classes, kvs) ils) =
   do
     hdrIDMap <- gets docxAnchorMap
-    let newIdent = if null ident
-                   then uniqueIdent ils (Set.fromList $ M.elems hdrIDMap)
+    exts <- asks (readerExtensions . docxOptions)
+    let newIdent = if T.null ident
+                   then uniqueIdent exts ils (Set.fromList $ M.elems hdrIDMap)
                    else ident
     modify $ \s -> s {docxAnchorMap = M.insert newIdent newIdent hdrIDMap}
     return $ Header n (newIdent, classes, kvs) ils
@@ -462,162 +614,294 @@
       singleton $ Plain ils
 singleParaToPlain blks = blks
 
-cellToBlocks :: PandocMonad m => Cell -> DocxContext m Blocks
-cellToBlocks (Cell bps) = do
+cellToCell :: PandocMonad m => RowSpan -> Docx.Cell -> DocxContext m Pandoc.Cell
+cellToCell rowSpan (Docx.Cell align gridSpan _ bps) = do
   blks <- smushBlocks <$> mapM bodyPartToBlocks bps
-  return $ fromList $ blocksToDefinitions $ blocksToBullets $ toList blks
+  let blks' = singleParaToPlain $ fromList $ blocksToDefinitions $ blocksToBullets $ toList blks
+  return (cell (convertAlign align)
+          rowSpan (ColSpan (fromIntegral gridSpan)) blks')
 
-rowToBlocksList :: PandocMonad m => Row -> DocxContext m [Blocks]
-rowToBlocksList (Row cells) = do
-  blksList <- mapM cellToBlocks cells
-  return $ map singleParaToPlain blksList
+rowsToRows :: PandocMonad m => [Docx.Row] -> DocxContext m [Pandoc.Row]
+rowsToRows rows = do
+  let rowspans = (fmap . fmap) (first RowSpan) (Docx.rowsToRowspans rows)
+  cells <- traverse (traverse (uncurry cellToCell)) rowspans
+  return (fmap (Pandoc.Row nullAttr) cells)
 
+splitHeaderRows :: Bool -> [Docx.Row] -> ([Docx.Row], [Docx.Row])
+splitHeaderRows hasFirstRowFormatting rs = bimap reverse reverse $ fst
+  $ if hasFirstRowFormatting
+    then L.foldl' f ((take 1 rs, []), True) (drop 1 rs)
+    else L.foldl' f (([], []), False) rs
+  where
+    f ((headerRows, bodyRows), previousRowWasHeader) r@(Docx.Row h cs)
+      | h == HasTblHeader || (previousRowWasHeader && any isContinuationCell cs)
+        = ((r : headerRows, bodyRows), True)
+      | otherwise
+        = ((headerRows, r : bodyRows), False)
+
+    isContinuationCell (Docx.Cell _ _ vm _) = vm == Docx.Continue
+
+
 -- like trimInlines, but also take out linebreaks
 trimSps :: Inlines -> Inlines
-trimSps (Many ils) = Many $ Seq.dropWhileL isSp $Seq.dropWhileR isSp ils
+trimSps (Many ils) = Many $ Seq.dropWhileL isSp $ Seq.dropWhileR isSp ils
   where isSp Space     = True
         isSp SoftBreak = True
         isSp LineBreak = True
         isSp _         = False
 
-parStyleToTransform :: ParagraphStyle -> (Blocks -> Blocks)
-parStyleToTransform pPr
-  | (c:cs) <- pStyle pPr
-  , c `elem` divsToKeep =
-    let pPr' = pPr { pStyle = cs }
-    in
-     divWith ("", [c], []) . parStyleToTransform pPr'
-  | (c:cs) <- pStyle pPr,
-    c `elem` listParagraphDivs =
-      let pPr' = pPr { pStyle = cs, indentation = Nothing}
-      in
-       divWith ("", [c], []) . parStyleToTransform pPr'
-  | (_:cs) <- pStyle pPr
-  , Just True <- pBlockQuote pPr =
-    let pPr' = pPr { pStyle = cs }
-    in
-     blockQuote . parStyleToTransform pPr'
-  | (_:cs) <- pStyle pPr =
-      let pPr' = pPr { pStyle = cs}
-      in
-       parStyleToTransform pPr'
-  | null (pStyle pPr)
-  , Just left <- indentation pPr >>= leftParIndent
-  , Just hang <- indentation pPr >>= hangingParIndent =
-    let pPr' = pPr { indentation = Nothing }
-    in
-     case (left - hang) > 0 of
-       True  -> blockQuote . (parStyleToTransform pPr')
-       False -> parStyleToTransform pPr'
-  | null (pStyle pPr),
-    Just left <- indentation pPr >>= leftParIndent =
-      let pPr' = pPr { indentation = Nothing }
-      in
-       case left > 0 of
-         True  -> blockQuote . (parStyleToTransform pPr')
-         False -> parStyleToTransform pPr'
-parStyleToTransform _ = id
+extraAttr :: (Eq (StyleName a), HasStyleName a) => a -> Attr
+extraAttr s = ("", [], [("custom-style", fromStyleName $ getStyleName s)])
 
+paragraphStyleToTransform :: PandocMonad m => ParagraphStyle -> DocxContext m (Blocks -> Blocks)
+paragraphStyleToTransform pPr =
+  let transform = if relativeIndent pPr > 0 && not (numbered pPr) &&
+                        not (any ((`elem` listParagraphStyles) . getStyleName) (pStyle pPr))
+                  then blockQuote
+                  else id
+  in do
+    extStylesEnabled <- asks (isEnabled Ext_styles . docxOptions)
+    return $ foldr (\parStyle transform' ->
+        (parStyleToTransform extStylesEnabled parStyle) . transform'
+      ) transform (pStyle pPr)
+
+parStyleToTransform :: Bool -> ParStyle -> Blocks -> Blocks
+parStyleToTransform extStylesEnabled parStyle@(getStyleName -> styleName)
+  | (styleName `elem` divsToKeep) || (styleName `elem` listParagraphStyles) =
+      divWith ("", [normalizeToClassName styleName], [])
+  | otherwise =
+      (if extStylesEnabled then divWith (extraAttr parStyle) else id)
+      . (if isBlockQuote parStyle then blockQuote else id)
+
+-- The relative indent is the indentation minus the indentation of the parent style.
+-- This tells us whether this paragraph in particular was indented more and thus
+-- should be considered a block quote.
+relativeIndent :: ParagraphStyle -> Integer
+relativeIndent pPr =
+  let pStyleLeft = fromMaybe 0 $ pStyleIndentation pPr >>= leftParIndent
+      pStyleHang = fromMaybe 0 $ pStyleIndentation pPr >>= hangingParIndent
+      left = fromMaybe pStyleLeft $ indentation pPr >>= leftParIndent
+      hang = fromMaybe pStyleHang $ indentation pPr >>= hangingParIndent
+  in (left - hang) - (pStyleLeft - pStyleHang)
+
+normalizeToClassName :: (FromStyleName a) => a -> T.Text
+normalizeToClassName = T.map go . fromStyleName
+  where go c | isSpace c = '-'
+             | otherwise = c
+
 bodyPartToBlocks :: PandocMonad m => BodyPart -> DocxContext m Blocks
-bodyPartToBlocks (Paragraph pPr parparts)
-  | not $ null $ codeDivs `intersect` (pStyle pPr) =
-    return
-    $ parStyleToTransform pPr
-    $ codeBlock
-    $ concatMap parPartToString parparts
-  | Just (style, n) <- pHeading pPr = do
-    ils <-local (\s-> s{docxInHeaderBlock=True})
+bodyPartToBlocks (Heading n style pPr numId lvl mblvlInfo parparts) = do
+    ils <- local (\s-> s{docxInHeaderBlock=True})
            (smushInlines <$> mapM parPartToInlines parparts)
-    makeHeaderAnchor $
-      headerWith ("", delete style (pStyle pPr), []) n ils
+    let classes = map normalizeToClassName . delete style
+                $ getStyleNames (pStyle pPr)
+    hasNumbering <- gets docxNumberedHeadings
+    let addNum = if hasNumbering && not (numbered pPr)
+                 then (++ ["unnumbered"])
+                 else id
+    if T.null numId
+       then pure ()
+       else do
+         -- We check whether this current numId has previously been used,
+         -- since Docx expects us to pick up where we left off.
+         listState <- gets docxListState
+         let start = case M.lookup (numId, lvl) listState of
+                       Nothing -> case mblvlInfo of
+                         Nothing -> 1
+                         Just (Level _ _ _ z) -> fromMaybe 1 z
+                       Just z -> z + 1
+         modify $ \st -> st{ docxListState =
+             -- expire all the continuation data for lists of level > this one:
+             -- a new level 1 list item resets continuation for level 2+
+             -- see #10258
+             let notExpired (_, lvl') _ = lvl' <= lvl
+             in M.insert (numId, lvl) start
+                  (M.filterWithKey notExpired listState) }
+    makeHeaderAnchor $ headerWith ("", addNum classes, []) n ils
+bodyPartToBlocks (Paragraph pPr parparts)
+  | Just True <- pBidi pPr = do
+      let pPr' = pPr { pBidi = Nothing }
+      local (\s -> s{ docxInBidi = True })
+        (bodyPartToBlocks (Paragraph pPr' parparts))
+  | isCodeDiv pPr = do
+      transform <- paragraphStyleToTransform pPr
+      return $
+        transform $
+        codeBlock $
+        T.concat $
+        map parPartToText parparts
   | otherwise = do
-    ils <- (trimSps . smushInlines) <$> mapM parPartToInlines parparts
+    ils <- trimSps . smushInlines <$> mapM parPartToInlines parparts
+    prevParaIls <- gets docxPrevPara
     dropIls <- gets docxDropCap
     let ils' = dropIls <> ils
-    if dropCap pPr
+    let (paraOrPlain, pPr')
+          | hasStylesInheritedFrom ["Compact"] pPr = (plain, removeStyleNamed "Compact" pPr)
+          | otherwise = (para, pPr)
+    if dropCap pPr'
       then do modify $ \s -> s { docxDropCap = ils' }
               return mempty
       else do modify $ \s -> s { docxDropCap = mempty }
+              let ils'' = (if null prevParaIls then mempty
+                          else prevParaIls <> space) <> ils'
+                  handleInsertion = do
+                    modify $ \s -> s {docxPrevPara = mempty}
+                    transform <- paragraphStyleToTransform pPr'
+                    return $ transform $ paraOrPlain ils''
               opts <- asks docxOptions
-              if isNull ils' && not (isEnabled Ext_empty_paragraphs opts)
-                 then return mempty
-                 else return $ parStyleToTransform pPr $ para ils'
+              case (pChange pPr', readerTrackChanges opts) of
+                  _ | null ils'', not (isEnabled Ext_empty_paragraphs opts) ->
+                    return mempty
+                  (Just (TrackedChange Insertion _), AcceptChanges) ->
+                      handleInsertion
+                  (Just (TrackedChange Insertion _), RejectChanges) -> do
+                      modify $ \s -> s {docxPrevPara = ils''}
+                      return mempty
+                  (Just (TrackedChange Insertion (ChangeInfo _ cAuthor cDate))
+                   , AllChanges) -> do
+                      let attr = ("", ["paragraph-insertion"], addAuthorAndDate cAuthor cDate)
+                          insertMark = spanWith attr mempty
+                      transform <- paragraphStyleToTransform pPr'
+                      return $ transform $
+                        paraOrPlain $ ils'' <> insertMark
+                  (Just (TrackedChange Deletion _), AcceptChanges) -> do
+                      modify $ \s -> s {docxPrevPara = ils''}
+                      return mempty
+                  (Just (TrackedChange Deletion _), RejectChanges) ->
+                      handleInsertion
+                  (Just (TrackedChange Deletion (ChangeInfo _ cAuthor cDate))
+                   , AllChanges) -> do
+                      let attr = ("", ["paragraph-deletion"], addAuthorAndDate cAuthor cDate)
+                          insertMark = spanWith attr mempty
+                      transform <- paragraphStyleToTransform pPr'
+                      return $ transform $
+                        paraOrPlain $ ils'' <> insertMark
+                  _ -> handleInsertion
 bodyPartToBlocks (ListItem pPr numId lvl (Just levelInfo) parparts) = do
   -- We check whether this current numId has previously been used,
   -- since Docx expects us to pick up where we left off.
   listState <- gets docxListState
   let startFromState = M.lookup (numId, lvl) listState
-      (_, fmt,txt, startFromLevelInfo) = levelInfo
+      Level _ fmt txt startFromLevelInfo = levelInfo
       start = case startFromState of
         Just n -> n + 1
-        Nothing -> case startFromLevelInfo of
-          Just n' -> n'
-          Nothing -> 1
+        Nothing -> fromMaybe 1 startFromLevelInfo
       kvs = [ ("level", lvl)
             , ("num-id", numId)
             , ("format", fmt)
             , ("text", txt)
-            , ("start", show start)
+            , ("start", tshow start)
             ]
-  modify $ \st -> st{ docxListState = M.insert (numId, lvl) start listState}
+  modify $ \st -> st{ docxListState =
+    -- expire all the continuation data for lists of level > this one:
+    -- a new level 1 list item resets continuation for level 2+
+    let notExpired (_, lvl') _ = lvl' <= lvl
+    in M.insert (numId, lvl) start (M.filterWithKey notExpired listState) }
   blks <- bodyPartToBlocks (Paragraph pPr parparts)
-  return $ divWith ("", ["list-item"], kvs) blks 
+  return $ divWith ("", ["list-item"], kvs) blks
 bodyPartToBlocks (ListItem pPr _ _ _ parparts) =
-  let pPr' = pPr {pStyle = "ListParagraph": pStyle pPr}
+  let pPr' = pPr {pStyle = constructBogusParStyleData "list-paragraph": pStyle pPr}
   in
     bodyPartToBlocks $ Paragraph pPr' parparts
-bodyPartToBlocks (Tbl _ _ _ []) =
-  return $ para mempty
-bodyPartToBlocks (Tbl cap _ look (r:rs)) = do
-  let caption = text cap
-      (hdr, rows) = case firstRowFormatting look of
-        True | null rs -> (Nothing, [r])
-             | otherwise -> (Just r, rs)
-        False -> (Nothing, r:rs)
-
-  cells <- mapM rowToBlocksList rows
-
-  let width = case cells of
-        r':_ -> length r'
-        -- shouldn't happen
-        []   -> 0
+bodyPartToBlocks (Captioned parstyle parparts bpart) = do
+  bs <- bodyPartToBlocks bpart
+  captContents <- bodyPartToBlocks (Paragraph parstyle parparts)
+  let capt = Caption Nothing (toList captContents)
+  let toCaptioned attr' bls = case bls of
+        [Table attr _cap colspecs thead tbodies tfoot]
+          -> singleton $ Table (attr <> attr') capt colspecs thead tbodies tfoot
+        [Figure attr _cap blks]
+          -> singleton $ Figure (attr <> attr') capt blks
+        [Para im@[Image{}]]
+          -> singleton $ Figure attr' capt [Plain im]
+        [Div attr bls']
+          -> toCaptioned (attr <> attr') bls'
+        [BlockQuote bls']
+          -> toCaptioned attr' bls'
+        _ -> captContents
+  pure $ toCaptioned nullAttr (toList bs)
+bodyPartToBlocks (Tbl _ _ _ _ []) =
+  return mempty
+bodyPartToBlocks (Tbl mbsty cap grid look parts) = do
+  let fullCaption = if T.null cap then mempty else plain (text cap)
+  let shortCaption = if T.null cap then Nothing else Just (toList (text cap))
+      cap' = caption shortCaption fullCaption
+      (hdr, rows) = splitHeaderRows (firstRowFormatting look) parts
 
-  hdrCells <- case hdr of
-    Just r' -> rowToBlocksList r'
-    Nothing -> return $ replicate width mempty
+  let width = maybe 0 maximum $ nonEmpty $ map rowLength parts
+      rowLength :: Docx.Row -> Int
+      rowLength (Docx.Row _ c) = sum (fmap (\(Docx.Cell _ gridSpan _ _) -> fromIntegral gridSpan) c)
 
-      -- The two following variables (horizontal column alignment and
-      -- relative column widths) go to the default at the
-      -- moment. Width information is in the TblGrid field of the Tbl,
-      -- so should be possible. Alignment might be more difficult,
-      -- since there doesn't seem to be a column entity in docx.
-  let alignments = replicate width AlignDefault
-      widths = replicate width 0 :: [Double]
+  headerCells <- rowsToRows hdr
+  bodyCells <- rowsToRows rows
 
-  return $ table caption (zip alignments widths) hdrCells cells
-bodyPartToBlocks (OMathPara e) =
-  return $ para $ displayMath (writeTeX e)
+      -- Horizontal column alignment is taken from the first row's cells.
+  let getAlignment (Docx.Cell al colspan _ _) = replicate (fromIntegral colspan)
+                   $ convertAlign al
+      alignments = case rows of
+                     [] -> replicate width Pandoc.AlignDefault
+                     Docx.Row _ cs : _ -> concatMap getAlignment cs
+      widths = map (\n -> if n == 0
+                             then ColWidthDefault
+                             else ColWidth n) grid
 
+  extStylesEnabled <- asks (isEnabled Ext_styles . docxOptions)
+  let attr = case mbsty of
+                Just sty | extStylesEnabled -> ("", [], [("custom-style", sty)])
+                _ -> nullAttr
+  return $ tableWith attr cap'
+                 (zip alignments widths)
+                 (TableHead nullAttr headerCells)
+                 [TableBody nullAttr 0 [] bodyCells]
+                 (TableFoot nullAttr [])
+bodyPartToBlocks HRule = pure Pandoc.horizontalRule
 
 -- replace targets with generated anchors.
 rewriteLink' :: PandocMonad m => Inline -> DocxContext m Inline
-rewriteLink' l@(Link attr ils ('#':target, title)) = do
+rewriteLink' l@(Link attr ils (T.uncons -> Just ('#',target), title)) = do
   anchorMap <- gets docxAnchorMap
-  return $ case M.lookup target anchorMap of
-    Just newTarget -> Link attr ils ('#':newTarget, title)
-    Nothing        -> l
+  case M.lookup target anchorMap of
+    Just newTarget -> do
+      modify $ \s -> s{docxAnchorSet = Set.insert newTarget (docxAnchorSet s)}
+      return $ Link attr ils ("#" <> newTarget, title)
+    Nothing        -> do
+      modify $ \s -> s{docxAnchorSet = Set.insert target (docxAnchorSet s)}
+      return l
 rewriteLink' il = return il
 
 rewriteLinks :: PandocMonad m => [Block] -> DocxContext m [Block]
 rewriteLinks = mapM (walkM rewriteLink')
 
+removeOrphanAnchors'' :: PandocMonad m => Inline -> DocxContext m [Inline]
+removeOrphanAnchors'' s@(Span (ident, classes, _) ils)
+  | "anchor" `elem` classes = do
+      anchorSet <- gets docxAnchorSet
+      return $ if ident `Set.member` anchorSet
+               then [s]
+               else ils
+removeOrphanAnchors'' il = return [il]
+
+removeOrphanAnchors' :: PandocMonad m => [Inline] -> DocxContext m [Inline]
+removeOrphanAnchors' ils = liftM concat $ mapM removeOrphanAnchors'' ils
+
+removeOrphanAnchors :: PandocMonad m => [Block] -> DocxContext m [Block]
+removeOrphanAnchors = mapM (walkM removeOrphanAnchors')
+
 bodyToOutput :: PandocMonad m => Body -> DocxContext m (Meta, [Block])
 bodyToOutput (Body bps) = do
   let (metabps, blkbps) = sepBodyParts bps
   meta <- bodyPartsToMeta metabps
+  let isNumberedPara (Paragraph pPr _) = numbered pPr
+      isNumberedPara _                 = False
+  modify (\s -> s { docxNumberedHeadings = any isNumberedPara blkbps })
   blks <- smushBlocks <$> mapM bodyPartToBlocks blkbps
   blks' <- rewriteLinks $ blocksToDefinitions $ blocksToBullets $ toList blks
-  return (meta, blks')
+  blks'' <- removeOrphanAnchors blks'
+  refs <- gets (map referenceToMetaValue . M.elems . docxReferences)
+  let meta' = if null refs
+                 then meta
+                 else setMeta "references" refs meta
+  return (meta', blks'')
 
 docxToOutput :: PandocMonad m
              => ReaderOptions
@@ -626,3 +910,14 @@
 docxToOutput opts (Docx (Document _ body)) =
   let dEnv   = def { docxOptions  = opts} in
    evalDocxContext (bodyToOutput body) dEnv def
+
+addAuthorAndDate :: T.Text -> Maybe T.Text -> [(T.Text, T.Text)]
+addAuthorAndDate author mdate =
+  ("author", author) : maybe [] (\date -> [("date", date)]) mdate
+
+convertAlign :: Docx.Align -> Pandoc.Alignment
+convertAlign al = case al of
+                       Docx.AlignDefault -> Pandoc.AlignDefault
+                       Docx.AlignLeft -> Pandoc.AlignLeft
+                       Docx.AlignCenter -> Pandoc.AlignCenter
+                       Docx.AlignRight -> Pandoc.AlignRight
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
@@ -1,95 +1,128 @@
-{-# LANGUAGE FlexibleInstances    #-}
-{-# LANGUAGE PatternGuards        #-}
-{-# LANGUAGE TypeSynonymInstances #-}
+{-# LANGUAGE OverloadedStrings    #-}
+{- |
+   Module      : Text.Pandoc.Readers.Docx.Combine
+   Copyright   : © 2014-2020 Jesse Rosenthal <jrosenthal@jhu.edu>,
+                   2014-2024 John MacFarlane <jgm@berkeley.edu>,
+                   2020 Nikolay Yakimov <root@livid.pp.ru>
+   License     : GNU GPL, version 2 or above
 
-module Text.Pandoc.Readers.Docx.Combine ( smushInlines
+   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 ( combineBlocks
+                                        , smushInlines
                                         , smushBlocks
                                         )
        where
 
-import Data.List
-import Data.Sequence (ViewL (..), ViewR (..), viewl, viewr, (><), (|>))
-import qualified Data.Sequence as Seq (null)
-import Text.Pandoc.Builder
+import qualified Data.List as L
+import Data.Bifunctor
+import Data.Sequence ( ViewL (..), ViewR (..), viewl, viewr, spanr, spanl
+                     , (><), (|>) )
+import Text.Pandoc.Builder as B
 
 data Modifier a = Modifier (a -> a)
                 | AttrModifier (Attr -> a -> a) Attr
-                | NullModifier
 
 spaceOutInlinesL :: Inlines -> (Inlines, Inlines)
 spaceOutInlinesL ms = (l, stackInlines fs (m' <> r))
-  where (l, m, r) = spaceOutInlines ms
-        (fs, m')  = unstackInlines m
+  where (l, (fs, m'), r) = spaceOutInlines ms
 
 spaceOutInlinesR :: Inlines -> (Inlines, Inlines)
 spaceOutInlinesR ms = (stackInlines fs (l <> m'), r)
-  where (l, m, r) = spaceOutInlines ms
-        (fs, m')  = unstackInlines m
+  where (l, (fs, m'), r) = spaceOutInlines ms
 
-spaceOutInlines :: Inlines -> (Inlines, Inlines, Inlines)
+spaceOutInlines :: Inlines -> (Inlines, ([Modifier Inlines], Inlines), Inlines)
 spaceOutInlines ils =
   let (fs, ils') = unstackInlines ils
-      contents = unMany ils'
-      left  = case viewl contents of
-        (Space :< _) -> space
-        _            -> mempty
-      right = case viewr contents of
-        (_ :> Space) -> space
-        _            -> mempty in
-  (left, stackInlines fs $ trimInlines . Many $ contents, right)
+      (left, (right, contents')) = second (spanr isSpace) $ spanl isSpace $ unMany ils'
+      -- NOTE: spanr counterintuitively returns suffix as the FIRST tuple element
+  in (Many left, (fs, Many contents'), Many right)
 
+isSpace :: Inline -> Bool
+isSpace Space = True
+isSpace SoftBreak = True
+isSpace _ = False
+
 stackInlines :: [Modifier Inlines] -> Inlines -> Inlines
 stackInlines [] ms = ms
-stackInlines (NullModifier : fs) ms = stackInlines fs ms
 stackInlines (Modifier f : fs) ms =
-  if isEmpty ms
+  if null ms
   then stackInlines fs ms
   else f $ stackInlines fs ms
 stackInlines (AttrModifier f attr : fs) ms = f attr $ stackInlines fs ms
 
 unstackInlines :: Inlines -> ([Modifier Inlines], Inlines)
-unstackInlines ms = case ilModifier ms of
-  NullModifier -> ([], ms)
-  _            -> (f : fs, ms') where
-    f = ilModifier ms
-    (fs, ms') = unstackInlines $ ilInnards ms
-
-ilModifier :: Inlines -> Modifier Inlines
-ilModifier ils = case viewl (unMany ils) of
-  (x :< xs) | Seq.null xs -> case x of
-    (Emph _)          -> Modifier emph
-    (Strong _)        -> Modifier strong
-    (SmallCaps _)     -> Modifier smallcaps
-    (Strikeout _)     -> Modifier strikeout
-    (Superscript _)   -> Modifier superscript
-    (Subscript _)     -> Modifier subscript
-    (Link attr _ tgt) -> Modifier $ linkWith attr (fst tgt) (snd tgt)
-    (Span attr _)     -> AttrModifier spanWith attr
-    _                 -> NullModifier
-  _ -> NullModifier
+unstackInlines ms = case ilModifierAndInnards ms of
+  Nothing         -> ([], ms)
+  Just (f, inner) -> first (f :) $ unstackInlines inner
 
-ilInnards :: Inlines -> Inlines
-ilInnards ils = case viewl (unMany ils) of
-  (x :< xs) | Seq.null xs -> case x of
-    (Emph lst)        -> fromList lst
-    (Strong lst)      -> fromList lst
-    (SmallCaps lst)   -> fromList lst
-    (Strikeout lst)   -> fromList lst
-    (Superscript lst) -> fromList lst
-    (Subscript lst)   -> fromList lst
-    (Link _ lst _)    -> fromList lst
-    (Span _ lst)      -> fromList lst
-    _                 -> ils
-  _          -> ils
+ilModifierAndInnards :: Inlines -> Maybe (Modifier Inlines, Inlines)
+ilModifierAndInnards ils = case viewl $ unMany ils of
+  x :< xs | null xs -> second fromList <$> case x of
+    Emph lst          -> Just (Modifier emph, lst)
+    Strong lst        -> Just (Modifier strong, lst)
+    SmallCaps lst     -> Just (Modifier smallcaps, lst)
+    Strikeout lst     -> Just (Modifier strikeout, lst)
+    Underline lst     -> Just (Modifier underline, lst)
+    Superscript lst   -> Just (Modifier superscript, lst)
+    Subscript lst     -> Just (Modifier subscript, lst)
+    Link attr lst tgt -> Just (Modifier $ uncurry (linkWith attr) tgt, lst)
+    Span attr lst     -> Just (AttrModifier spanWith attr, lst)
+    _                 -> Nothing
+  _ -> Nothing
 
 inlinesL :: Inlines -> (Inlines, Inlines)
 inlinesL ils = case viewl $ unMany ils of
-  (s :< sq) -> (singleton s, Many sq)
+  (s :< sq) -> (B.singleton s, Many sq)
   _         -> (mempty, ils)
 
 inlinesR :: Inlines -> (Inlines, Inlines)
 inlinesR ils = case viewr $ unMany ils of
-  (sq :> s) -> (Many sq, singleton s)
+  (sq :> s) -> (Many sq, B.singleton s)
   _         -> (ils, mempty)
 
 combineInlines :: Inlines -> Inlines -> Inlines
@@ -103,19 +136,19 @@
 combineSingletonInlines x y =
   let (xfs, xs) = unstackInlines x
       (yfs, ys) = unstackInlines y
-      shared = xfs `intersect` yfs
-      x_remaining = xfs \\ shared
-      y_remaining = yfs \\ shared
+      shared = xfs `L.intersect` yfs
+      x_remaining = xfs L.\\ shared
+      y_remaining = yfs L.\\ shared
       x_rem_attr = filter isAttrModifier x_remaining
       y_rem_attr = filter isAttrModifier y_remaining
   in
    case null shared of
-     True | isEmpty xs && isEmpty ys ->
-            stackInlines (x_rem_attr ++ y_rem_attr) mempty
-          | isEmpty xs ->
+     True | null xs && null ys ->
+            stackInlines (x_rem_attr <> y_rem_attr) mempty
+          | null xs ->
             let (sp, y') = spaceOutInlinesL y in
             stackInlines x_rem_attr mempty <> sp <> y'
-          | isEmpty ys ->
+          | null ys ->
             let (x', sp) = spaceOutInlinesR x in
             x' <> sp <> stackInlines y_rem_attr mempty
           | otherwise ->
@@ -133,23 +166,24 @@
   | bs' :> BlockQuote bs'' <- viewr (unMany bs)
   , BlockQuote cs'' :< cs' <- viewl (unMany cs) =
       Many $ (bs' |> BlockQuote (bs'' <> cs'')) >< cs'
+  | bs' :> CodeBlock attr codeStr <- viewr (unMany bs)
+  , CodeBlock attr' codeStr' :< cs' <- viewl (unMany cs)
+  , attr == attr' =
+      Many $ (bs' |> CodeBlock attr (codeStr <> "\n" <> codeStr')) >< cs'
 combineBlocks bs cs = bs <> cs
 
 instance (Monoid a, Eq a) => Eq (Modifier a) where
   (Modifier f) == (Modifier g) = f mempty == g mempty
   (AttrModifier f attr) == (AttrModifier g attr') = f attr mempty == g attr' mempty
-  NullModifier == NullModifier = True
   _ == _ = False
 
-isEmpty :: (Monoid a, Eq a) => a -> Bool
-isEmpty x = x == mempty
-
 isAttrModifier :: Modifier a -> Bool
 isAttrModifier (AttrModifier _ _) = True
 isAttrModifier _                  = False
 
 smushInlines :: [Inlines] -> Inlines
-smushInlines xs = foldl combineInlines mempty xs
+smushInlines xs = combineInlines xs' mempty
+  where xs' = L.foldl' combineInlines mempty xs
 
 smushBlocks :: [Blocks] -> Blocks
-smushBlocks xs = foldl combineBlocks mempty xs
+smushBlocks xs = L.foldl' combineBlocks mempty xs
diff --git a/src/Text/Pandoc/Readers/Docx/Fields.hs b/src/Text/Pandoc/Readers/Docx/Fields.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Readers/Docx/Fields.hs
@@ -0,0 +1,167 @@
+{-# LANGUAGE OverloadedStrings #-}
+{- |
+   Module      : Text.Pandoc.Readers.Docx.Fields
+   Copyright   : Copyright (C) 2014-2020 Jesse Rosenthal
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : Jesse Rosenthal <jrosenthal@jhu.edu>
+   Stability   : alpha
+   Portability : portable
+
+For parsing Field definitions in instText tags, as described in
+ECMA-376-1:2016, §17.16.5 -}
+
+module Text.Pandoc.Readers.Docx.Fields ( FieldInfo(..)
+                                       , IndexEntry(..)
+                                       , parseFieldInfo
+                                       ) where
+
+import Data.Functor (($>), void)
+import qualified Data.Text as T
+import Text.Pandoc.Parsing
+import Data.Maybe (isJust)
+
+type URL = T.Text
+type Anchor = T.Text
+
+data IndexEntry = IndexEntry
+  { entryTitle :: T.Text
+  , entrySee :: Maybe T.Text
+  , entryYomi :: Maybe T.Text
+  , entryBold :: Bool
+  , entryItalic :: Bool }
+  deriving (Show)
+
+data FieldInfo = HyperlinkField URL
+                -- The boolean indicates whether the field is a hyperlink.
+               | PagerefField Anchor Bool
+               | CrossrefField Anchor Bool
+               | IndexrefField IndexEntry
+               | CslCitation T.Text
+               | CslBibliography
+               | EndNoteCite T.Text
+               | EndNoteRefList
+               | UnknownField
+               deriving (Show)
+
+type Parser = Parsec T.Text ()
+
+parseFieldInfo :: T.Text -> Either ParseError FieldInfo
+parseFieldInfo = parse fieldInfo ""
+
+fieldInfo :: Parser FieldInfo
+fieldInfo = do
+  spaces
+  hyperlink
+    <|>
+    pageref
+    <|>
+    indexref
+    <|>
+    crossref
+    <|>
+    addIn
+    <|>
+    return UnknownField
+
+addIn :: Parser FieldInfo
+addIn = do
+  string "ADDIN"
+  spaces
+  try cslCitation <|> cslBibliography <|> endnoteCite <|> endnoteRefList
+
+cslCitation :: Parser FieldInfo
+cslCitation = do
+  optional (string "ZOTERO_ITEM" *> spaces)
+  string "CSL_CITATION"
+  spaces
+  CslCitation <$> getInput
+
+cslBibliography :: Parser FieldInfo
+cslBibliography = do
+  string "ZOTERO_BIBL" <|> string "Mendeley Bibliography CSL_BIBLIOGRAPHY"
+  return CslBibliography
+
+endnoteCite :: Parser FieldInfo
+endnoteCite = try $ do
+  string "EN.CITE"
+  spaces
+  EndNoteCite <$> getInput
+
+endnoteRefList :: Parser FieldInfo
+endnoteRefList = try $ do
+  string "EN.REFLIST"
+  return EndNoteRefList
+
+
+escapedQuote :: Parser T.Text
+escapedQuote = string "\\\"" $> "\\\""
+
+inQuotes :: Parser T.Text
+inQuotes =
+  try escapedQuote <|> (T.singleton <$> anyChar)
+
+quotedString :: Parser T.Text
+quotedString = do
+  char '"'
+  T.concat <$> manyTill inQuotes (try (char '"'))
+
+unquotedString :: Parser T.Text
+unquotedString = T.pack <$> manyTill anyChar (try $ void (lookAhead space) <|> eof)
+
+fieldArgument :: Parser T.Text
+fieldArgument = do
+  notFollowedBy (char '\\') -- switch
+  quotedString <|> unquotedString
+
+hyperlink :: Parser FieldInfo
+hyperlink = do
+  string "HYPERLINK"
+  spaces
+  farg <- option "" $ notFollowedBy (char '\\') *> fieldArgument
+  switches <- many fieldSwitch
+  let url = case [s | ('l',s) <- switches] of
+              [s] -> farg <> "#" <> s
+              _   -> farg
+  return $ HyperlinkField url
+
+-- See §17.16.5.45
+fieldSwitch :: Parser (Char, T.Text)
+fieldSwitch = try $ do
+  spaces
+  char '\\'
+  c <- anyChar
+  spaces
+  farg <- option mempty fieldArgument
+  return (c, farg)
+
+pageref :: Parser FieldInfo
+pageref = do
+  string "PAGEREF"
+  spaces
+  farg <- fieldArgument
+  switches <- many fieldSwitch
+  let isLink = any ((== 'h') . fst) switches
+  return $ PagerefField farg isLink
+
+crossref :: Parser FieldInfo
+crossref = do
+  string "REF"
+  spaces
+  farg <- fieldArgument
+  switches <- many fieldSwitch
+  let isLink = any ((== 'h') . fst) switches
+  return $ CrossrefField farg isLink
+
+-- second element of tuple is optional "see".
+indexref :: Parser FieldInfo
+indexref = do
+  string "XE"
+  spaces
+  farg <- fieldArgument
+  switches <- spaces *> many fieldSwitch
+  return $ IndexrefField $ IndexEntry{ entryTitle = farg
+                                     , entrySee = lookup 't' switches
+                                     , entryYomi = lookup 'y' switches
+                                     , entryBold = isJust (lookup 'b' switches)
+                                     , entryItalic = isJust (lookup 'i' switches) }
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,24 +1,8 @@
-{-
-Copyright (C) 2014-2017 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
--}
-
+{-# LANGUAGE LambdaCase #-}
+{-# LANGUAGE OverloadedStrings #-}
 {- |
    Module      : Text.Pandoc.Readers.Docx.Lists
-   Copyright   : Copyright (C) 2014-2017 Jesse Rosenthal
+   Copyright   : Copyright (C) 2014-2020 Jesse Rosenthal
    License     : GNU GPL, version 2 or above
 
    Maintainer  : Jesse Rosenthal <jrosenthal@jhu.edu>
@@ -31,49 +15,54 @@
 module Text.Pandoc.Readers.Docx.Lists ( blocksToBullets
                                       , blocksToDefinitions
                                       , listParagraphDivs
+                                      , listParagraphStyles
                                       ) where
 
 import Data.List
+import Data.Char (isDigit)
 import Data.Maybe
-import Text.Pandoc.Generic (bottomUp)
+import Data.String (fromString)
+import qualified Data.Text as T
+import Text.Pandoc.Walk (walk)
 import Text.Pandoc.JSON
-import Text.Pandoc.Shared (trim)
+import Text.Pandoc.Readers.Docx.Parse (ParaStyleName)
+import Text.Pandoc.Shared (trim, safeRead)
 
 isListItem :: Block -> Bool
 isListItem (Div (_, classes, _) _) | "list-item" `elem` classes = True
 isListItem _                       = False
 
 getLevel :: Block -> Maybe Integer
-getLevel (Div (_, _, kvs) _) =  fmap read $ lookup "level" kvs
+getLevel (Div (_, _, kvs) _) =  lookup "level" kvs >>= safeRead
 getLevel _                   = Nothing
 
 getLevelN :: Block -> Integer
 getLevelN b = fromMaybe (-1) (getLevel b)
 
 getNumId :: Block -> Maybe Integer
-getNumId (Div (_, _, kvs) _) =  fmap read $ lookup "num-id" kvs
+getNumId (Div (_, _, kvs) _) =  lookup "num-id" kvs >>= safeRead
 getNumId _                   = Nothing
 
 getNumIdN :: Block -> Integer
 getNumIdN b = fromMaybe (-1) (getNumId b)
 
-getText :: Block -> Maybe String
+getText :: Block -> Maybe T.Text
 getText (Div (_, _, kvs) _) = lookup "text" kvs
 getText _                   = Nothing
 
 data ListType = Itemized | Enumerated ListAttributes
 
-listStyleMap :: [(String, ListNumberStyle)]
+listStyleMap :: [(T.Text, ListNumberStyle)]
 listStyleMap = [("upperLetter", UpperAlpha),
                 ("lowerLetter", LowerAlpha),
                 ("upperRoman", UpperRoman),
                 ("lowerRoman", LowerRoman),
                 ("decimal", Decimal)]
 
-listDelimMap :: [(String, ListNumberDelim)]
-listDelimMap = [("%1)", OneParen),
-                ("(%1)", TwoParens),
-                ("%1.", Period)]
+listDelimMap :: [(T.Text, ListNumberDelim)]
+listDelimMap = [("%)", OneParen),
+                ("(%)", TwoParens),
+                ("%.", Period)]
 
 getListType :: Block -> Maybe ListType
 getListType b@(Div (_, _, kvs) _) | isListItem b =
@@ -85,18 +74,21 @@
    case frmt of
      Just "bullet" -> Just Itemized
      Just f        ->
-       case txt of
+       case T.filter (not . isDigit) <$> txt of
          Just t -> Just $ Enumerated (
-                  read (fromMaybe "1" start) :: Int,
+                  fromMaybe 1 (start >>= safeRead) :: Int,
                   fromMaybe DefaultStyle (lookup f listStyleMap),
                   fromMaybe DefaultDelim (lookup t listDelimMap))
          Nothing -> Nothing
      _ -> Nothing
 getListType _ = Nothing
 
-listParagraphDivs :: [String]
-listParagraphDivs = ["ListParagraph"]
+listParagraphDivs :: [T.Text]
+listParagraphDivs = ["list-paragraph"]
 
+listParagraphStyles :: [ParaStyleName]
+listParagraphStyles = map (fromString . T.unpack) listParagraphDivs
+
 -- This is a first stab at going through and attaching meaning to list
 -- paragraphs, without an item marker, following a list item. We
 -- assume that these are paragraphs in the same item.
@@ -132,25 +124,48 @@
 
 flatToBullets' :: Integer -> [Block] -> [Block]
 flatToBullets' _ [] = []
-flatToBullets' num xs@(b : elems)
-  | getLevelN b == num = b : flatToBullets' num elems
-  | otherwise =
-    let bNumId = getNumIdN b
-        bLevel = getLevelN b
-        (children, remaining) =
-          span
-          (\b' ->
-            (getLevelN b') > bLevel ||
-             ((getLevelN b') == bLevel && (getNumIdN b') == bNumId))
-          xs
-    in
-     case getListType b of
-       Just (Enumerated attr) ->
-         OrderedList attr (separateBlocks $ flatToBullets' bLevel children) :
-         flatToBullets' num remaining
-       _ ->
-         BulletList (separateBlocks $ flatToBullets' bLevel children) :
-         flatToBullets' num remaining
+flatToBullets' num xs@(b : elems) =
+  if getLevelN b == num
+     then (case bCheckmark of
+             Just checked -> addCheckmark checked b
+             Nothing -> b) : flatToBullets' num elems
+     else case getListType b of
+            Just (Enumerated attr) ->
+              OrderedList attr (separateBlocks $ flatToBullets' bLevel children) :
+              flatToBullets' num remaining
+            _ ->
+              BulletList (separateBlocks $ flatToBullets' bLevel children) :
+              flatToBullets' num remaining
+ where
+  bNumId = getNumIdN b
+  bLevel = getLevelN b
+  isCheckmark (Just "\9744") = Just False
+  isCheckmark (Just "\9746") = Just True
+  isCheckmark _ = Nothing
+  bCheckmark =
+    case getListType b of
+      Just Itemized -> isCheckmark (getText b)
+      _ -> Nothing
+  addCheckmark checked (Div attrs [Para ils]) =
+    Div attrs [Para (Str (if checked then "\9746" else "\9744") : Space : ils)]
+  addCheckmark checked (Div attrs [Plain ils]) =
+    Div attrs [Plain (Str (if checked then "\9746" else "\9744") : Space : ils)]
+  addCheckmark _ x = x
+  (children, remaining) =
+    span
+    (\b' ->
+      getLevelN b' > bLevel ||
+       (getLevelN b' == bLevel &&
+          (getNumIdN b' == bNumId ||
+            (case bCheckmark of
+               Just _ ->
+                 case getText b' of
+                   Just "" -> True
+                   Just " " -> True
+                   Just x -> isJust (isCheckmark (Just x))
+                   Nothing -> False
+               Nothing -> False))))
+    xs
 
 flatToBullets :: [Block] -> [Block]
 flatToBullets elems = flatToBullets' (-1) elems
@@ -163,7 +178,7 @@
 blocksToBullets :: [Block] -> [Block]
 blocksToBullets blks =
   map singleItemHeaderToHeader $
-  bottomUp removeListDivs $flatToBullets (handleListParagraphs blks)
+  walk removeListDivs $ flatToBullets (handleListParagraphs blks)
 
 plainParaInlines :: Block -> [Inline]
 plainParaInlines (Plain ils) = ils
@@ -176,22 +191,21 @@
   reverse $ DefinitionList (reverse defAcc) : acc
 blocksToDefinitions' defAcc acc
   (Div (_, classes1, _) blks1 : Div (ident2, classes2, kvs2) blks2 : blks)
-  | "DefinitionTerm" `elem` classes1 && "Definition"  `elem` classes2 =
+  | "Definition-Term" `elem` classes1 && "Definition"  `elem` classes2 =
     let remainingAttr2 = (ident2, delete "Definition" classes2, kvs2)
         pair = if remainingAttr2 == ("", [], []) then (concatMap plainParaInlines blks1, [blks2]) else (concatMap plainParaInlines blks1, [[Div remainingAttr2 blks2]])
     in
      blocksToDefinitions' (pair : defAcc) acc blks
-blocksToDefinitions' defAcc acc
+blocksToDefinitions' ((defTerm, defItems):defs) acc
   (Div (ident2, classes2, kvs2) blks2 : blks)
-  | (not . null) defAcc && "Definition"  `elem` classes2 =
+  | "Definition"  `elem` classes2 =
     let remainingAttr2 = (ident2, delete "Definition" classes2, kvs2)
-        defItems2 = case remainingAttr2 == ("", [], []) of
-          True  -> blks2
-          False -> [Div remainingAttr2 blks2]
-        ((defTerm, defItems):defs) = defAcc
-        defAcc' = case null defItems of
-          True -> (defTerm, [defItems2]) : defs
-          False -> (defTerm, init defItems ++ [last defItems ++ defItems2]) : defs
+        defItems2 = if remainingAttr2 == ("", [], [])
+          then blks2
+          else [Div remainingAttr2 blks2]
+        defAcc' = if null defItems
+          then (defTerm, [defItems2]) : defs
+          else (defTerm, init defItems ++ [last defItems ++ defItems2]) : defs
     in
      blocksToDefinitions' defAcc' acc blks
 blocksToDefinitions' [] acc (b:blks) =
@@ -214,8 +228,6 @@
 
 removeListDivs :: [Block] -> [Block]
 removeListDivs = concatMap removeListDivs'
-
-
 
 blocksToDefinitions :: [Block] -> [Block]
 blocksToDefinitions = blocksToDefinitions' [] []
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
@@ -1,1069 +1,1502 @@
-{-# LANGUAGE FlexibleInstances #-}
-{-# LANGUAGE PatternGuards     #-}
-{-# LANGUAGE ViewPatterns      #-}
-
-{-
-Copyright (C) 2014-2017 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-2017 Jesse Rosenthal
- License : GNU GPL, version 2 or above
-
- Maintainer : Jesse Rosenthal <jrosenthal@jhu.edu>
- Stability : alpha
- Portability : portable
-
-Conversion of docx archive into Docx haskell type
--}
-
-module Text.Pandoc.Readers.Docx.Parse ( Docx(..)
-                                      , Document(..)
-                                      , Body(..)
-                                      , BodyPart(..)
-                                      , TblLook(..)
-                                      , Extent
-                                      , ParPart(..)
-                                      , Run(..)
-                                      , RunElem(..)
-                                      , Notes
-                                      , Numbering
-                                      , Relationship
-                                      , Media
-                                      , RunStyle(..)
-                                      , VertAlign(..)
-                                      , ParIndentation(..)
-                                      , ParagraphStyle(..)
-                                      , Row(..)
-                                      , Cell(..)
-                                      , archiveToDocx
-                                      , archiveToDocxWithWarnings
-                                      ) where
-import Codec.Archive.Zip
-import Control.Applicative ((<|>))
-import Control.Monad.Except
-import Control.Monad.Reader
-import Control.Monad.State.Strict
-import Data.Bits ((.|.))
-import qualified Data.ByteString.Lazy as B
-import Data.Char (chr, ord, readLitChar)
-import Data.List
-import qualified Data.Map as M
-import Data.Maybe
-import System.FilePath
-import Text.Pandoc.Readers.Docx.Util
-import Text.Pandoc.Shared (filteredFilesFromArchive, safeRead)
-import qualified Text.Pandoc.UTF8 as UTF8
-import Text.TeXMath (Exp)
-import Text.TeXMath.Readers.OMML (readOMML)
-import Text.TeXMath.Unicode.Fonts (Font (..), getUnicode, stringToFont)
-import Text.XML.Light
-import qualified Text.XML.Light.Cursor as XMLC
-
-data ReaderEnv = ReaderEnv { envNotes         :: Notes
-                           , envComments      :: Comments
-                           , envNumbering     :: Numbering
-                           , envRelationships :: [Relationship]
-                           , envMedia         :: Media
-                           , envFont          :: Maybe Font
-                           , envCharStyles    :: CharStyleMap
-                           , envParStyles     :: ParStyleMap
-                           , envLocation      :: DocumentLocation
-                           }
-               deriving Show
-
-data ReaderState = ReaderState { stateWarnings :: [String] }
-                 deriving Show
-
-data DocxError = DocxError | WrongElem
-               deriving Show
-
-type D = ExceptT DocxError (ReaderT ReaderEnv (State ReaderState))
-
-runD :: D a -> ReaderEnv -> ReaderState -> (Either DocxError a, ReaderState)
-runD dx re rs = runState (runReaderT (runExceptT dx) re) rs
-
-maybeToD :: Maybe a -> D a
-maybeToD (Just a) = return a
-maybeToD Nothing  = throwError DocxError
-
-eitherToD :: Either a b -> D b
-eitherToD (Right b) = return b
-eitherToD (Left _)  = throwError DocxError
-
-concatMapM        :: (Monad m) => (a -> m [b]) -> [a] -> m [b]
-concatMapM f xs   =  liftM concat (mapM f xs)
-
-
--- This is similar to `mapMaybe`: it maps a function returning the D
--- monad over a list, and only keeps the non-erroring return values.
-mapD :: (a -> D b) -> [a] -> D [b]
-mapD f xs =
-  let handler x = (f x >>= (\y-> return [y])) `catchError` (\_ -> return [])
-  in
-   concatMapM handler xs
-
-unwrapSDT :: NameSpaces -> Content -> Content
-unwrapSDT ns (Elem element)
-  | isElem ns "w" "sdt" element
-  , Just sdtContent <- findChildByName ns "w" "sdtContent" element
-  , child : _    <- elChildren sdtContent
-  = Elem child
-unwrapSDT _ content = content
-
-walkDocument' :: NameSpaces -> XMLC.Cursor -> XMLC.Cursor
-walkDocument' ns cur =
-  let modifiedCur = XMLC.modifyContent (unwrapSDT ns) cur
-  in
-    case XMLC.nextDF modifiedCur of
-      Just cur' -> walkDocument' ns cur'
-      Nothing   -> XMLC.root modifiedCur
-
-walkDocument :: NameSpaces -> Element -> Maybe Element
-walkDocument ns element =
-  let cur = XMLC.fromContent (Elem element)
-      cur' = walkDocument' ns cur
-  in
-    case XMLC.toTree cur' of
-      Elem element' -> Just element'
-      _             -> Nothing
-
-
-data Docx = Docx Document
-          deriving Show
-
-data Document = Document NameSpaces Body
-          deriving Show
-
-data Body = Body [BodyPart]
-          deriving Show
-
-type Media = [(FilePath, B.ByteString)]
-
-type CharStyle = (String, RunStyle)
-
-type ParStyle = (String, ParStyleData)
-
-type CharStyleMap = M.Map String RunStyle
-
-type ParStyleMap = M.Map String ParStyleData
-
-data Numbering = Numbering NameSpaces [Numb] [AbstractNumb]
-                 deriving Show
-
-data Numb = Numb String String           -- right now, only a key to an abstract num
-            deriving Show
-
-data AbstractNumb = AbstractNumb String [Level]
-                    deriving Show
-
--- (ilvl, format, string, start)
-type Level = (String, String, String, Maybe Integer)
-
-data DocumentLocation = InDocument | InFootnote | InEndnote
-                      deriving (Eq,Show)
-
-data Relationship = Relationship DocumentLocation RelId Target
-                  deriving Show
-
-data Notes = Notes NameSpaces
-             (Maybe (M.Map String Element))
-             (Maybe (M.Map String Element))
-           deriving Show
-
-data Comments = Comments NameSpaces (M.Map String Element)
-              deriving Show
-
-data ParIndentation = ParIndentation { leftParIndent    :: Maybe Integer
-                                     , rightParIndent   :: Maybe Integer
-                                     , hangingParIndent :: Maybe Integer}
-                      deriving Show
-
-data ParagraphStyle = ParagraphStyle { pStyle      :: [String]
-                                     , indentation :: Maybe ParIndentation
-                                     , dropCap     :: Bool
-                                     , pHeading    :: Maybe (String, Int)
-                                     , pNumInfo    :: Maybe (String, String)
-                                     , pBlockQuote :: Maybe Bool
-                                     }
-                      deriving Show
-
-defaultParagraphStyle :: ParagraphStyle
-defaultParagraphStyle = ParagraphStyle { pStyle = []
-                                       , indentation = Nothing
-                                       , dropCap     = False
-                                       , pHeading    = Nothing
-                                       , pNumInfo    = Nothing
-                                       , pBlockQuote = Nothing
-                                       }
-
-
-data BodyPart = Paragraph ParagraphStyle [ParPart]
-              | ListItem ParagraphStyle String String (Maybe Level) [ParPart]
-              | Tbl String TblGrid TblLook [Row]
-              | OMathPara [Exp]
-              deriving Show
-
-type TblGrid = [Integer]
-
-data TblLook = TblLook {firstRowFormatting::Bool}
-              deriving Show
-
-defaultTblLook :: TblLook
-defaultTblLook = TblLook{firstRowFormatting = False}
-
-data Row = Row [Cell]
-           deriving Show
-
-data Cell = Cell [BodyPart]
-            deriving Show
-
--- (width, height) in EMUs
-type Extent = Maybe (Double, Double)
-
-data ParPart = PlainRun Run
-             | Insertion ChangeId Author ChangeDate [Run]
-             | Deletion ChangeId Author ChangeDate [Run]
-             | CommentStart CommentId Author CommentDate [BodyPart]
-             | CommentEnd CommentId
-             | BookMark BookMarkId Anchor
-             | InternalHyperLink Anchor [Run]
-             | ExternalHyperLink URL [Run]
-             | Drawing FilePath String String B.ByteString Extent -- title, alt
-             | Chart                                              -- placeholder for now
-             | PlainOMath [Exp]
-             | SmartTag [Run]
-             deriving Show
-
-data Run = Run RunStyle [RunElem]
-         | Footnote [BodyPart]
-         | Endnote [BodyPart]
-         | InlineDrawing FilePath String String B.ByteString Extent -- title, alt
-         | InlineChart          -- placeholder
-           deriving Show
-
-data RunElem = TextRun String | LnBrk | Tab | SoftHyphen | NoBreakHyphen
-             deriving Show
-
-data VertAlign = BaseLn | SupScrpt | SubScrpt
-               deriving Show
-
-data RunStyle = RunStyle { isBold      :: Maybe Bool
-                         , isItalic    :: Maybe Bool
-                         , isSmallCaps :: Maybe Bool
-                         , isStrike    :: Maybe Bool
-                         , rVertAlign  :: Maybe VertAlign
-                         , rUnderline  :: Maybe String
-                         , rStyle      :: Maybe CharStyle}
-                deriving Show
-
-data ParStyleData = ParStyleData { headingLev   :: Maybe (String, Int)
-                                 , isBlockQuote :: Maybe Bool
-                                 , numInfo      :: Maybe (String, String)
-                                 , psStyle      :: Maybe ParStyle}
-                    deriving Show
-
-defaultRunStyle :: RunStyle
-defaultRunStyle = RunStyle { isBold = Nothing
-                           , isItalic = Nothing
-                           , isSmallCaps = Nothing
-                           , isStrike = Nothing
-                           , rVertAlign = Nothing
-                           , rUnderline = Nothing
-                           , rStyle = Nothing}
-
-type Target = String
-type Anchor = String
-type URL = String
-type BookMarkId = String
-type RelId = String
-type ChangeId = String
-type CommentId = String
-type Author = String
-type ChangeDate = String
-type CommentDate = String
-
-archiveToDocx :: Archive -> Either DocxError Docx
-archiveToDocx archive = fst <$> archiveToDocxWithWarnings archive
-
-archiveToDocxWithWarnings :: Archive -> Either DocxError (Docx, [String])
-archiveToDocxWithWarnings archive = do
-  let notes     = archiveToNotes archive
-      comments  = archiveToComments archive
-      numbering = archiveToNumbering archive
-      rels      = archiveToRelationships archive
-      media     = filteredFilesFromArchive archive filePathIsMedia
-      (styles, parstyles) = archiveToStyles archive
-      rEnv =
-        ReaderEnv notes comments numbering rels media Nothing styles parstyles InDocument
-      rState = ReaderState { stateWarnings = [] }
-      (eitherDoc, st) = runD (archiveToDocument archive) rEnv rState
-  case eitherDoc of
-    Right doc -> Right (Docx doc, stateWarnings st)
-    Left e    -> Left e
-
-
-
-archiveToDocument :: Archive -> D Document
-archiveToDocument zf = do
-  entry <- maybeToD $ findEntryByPath "word/document.xml" zf
-  docElem <- maybeToD $ (parseXMLDoc . UTF8.toStringLazy . fromEntry) entry
-  let namespaces = elemToNameSpaces docElem
-  bodyElem <- maybeToD $ findChildByName namespaces "w" "body" docElem
-  let bodyElem' = case walkDocument namespaces bodyElem of
-        Just e -> e
-        Nothing -> bodyElem
-  body <- elemToBody namespaces bodyElem'
-  return $ Document namespaces body
-
-elemToBody :: NameSpaces -> Element -> D Body
-elemToBody ns element | isElem ns "w" "body" element =
-  fmap Body (mapD (elemToBodyPart ns) (elChildren element))
-elemToBody _ _ = throwError WrongElem
-
-archiveToStyles :: Archive -> (CharStyleMap, ParStyleMap)
-archiveToStyles zf =
-  let stylesElem = findEntryByPath "word/styles.xml" zf >>=
-                   (parseXMLDoc . UTF8.toStringLazy . fromEntry)
-  in
-   case stylesElem of
-     Nothing -> (M.empty, M.empty)
-     Just styElem ->
-       let namespaces = elemToNameSpaces styElem
-       in
-        ( M.fromList $ buildBasedOnList namespaces styElem
-            (Nothing :: Maybe CharStyle),
-          M.fromList $ buildBasedOnList namespaces styElem
-            (Nothing :: Maybe ParStyle) )
-
-isBasedOnStyle :: (ElemToStyle a) => NameSpaces -> Element -> Maybe a -> Bool
-isBasedOnStyle ns element parentStyle
-  | isElem ns "w" "style" element
-  , Just styleType <- findAttrByName ns "w" "type" element
-  , styleType == cStyleType parentStyle
-  , Just basedOnVal <- findChildByName ns "w" "basedOn" element >>=
-                       findAttrByName ns "w" "val"
-  , Just ps <- parentStyle = basedOnVal == getStyleId ps
-  | isElem ns "w" "style" element
-  , Just styleType <- findAttrByName ns "w" "type" element
-  , styleType == cStyleType parentStyle
-  , Nothing <- findChildByName ns "w" "basedOn" element
-  , Nothing <- parentStyle = True
-  | otherwise = False
-
-class ElemToStyle a where
-  cStyleType  :: Maybe a -> String
-  elemToStyle :: NameSpaces -> Element -> Maybe a -> Maybe a
-  getStyleId     :: a -> String
-
-instance ElemToStyle CharStyle where
-  cStyleType _ = "character"
-  elemToStyle ns element parentStyle
-    | isElem ns "w" "style" element
-    , Just "character" <- findAttrByName ns "w" "type" element
-    , Just styleId <- findAttrByName ns "w" "styleId" element =
-      Just (styleId, elemToRunStyle ns element parentStyle)
-    | otherwise = Nothing
-  getStyleId s = fst s
-
-instance ElemToStyle ParStyle where
-  cStyleType _ = "paragraph"
-  elemToStyle ns element parentStyle
-    | isElem ns "w" "style" element
-    , Just "paragraph" <- findAttrByName ns "w" "type" element
-    , Just styleId <- findAttrByName ns "w" "styleId" element =
-      Just (styleId, elemToParStyleData ns element parentStyle)
-    | otherwise = Nothing
-  getStyleId s = fst s
-
-getStyleChildren :: (ElemToStyle a) => NameSpaces -> Element -> Maybe a -> [a]
-getStyleChildren ns element parentStyle
-  | isElem ns "w" "styles" element =
-    mapMaybe (\e -> elemToStyle ns e parentStyle) $
-    filterChildren (\e' -> isBasedOnStyle ns e' parentStyle) element
-  | otherwise = []
-
-buildBasedOnList :: (ElemToStyle a) => NameSpaces -> Element -> Maybe a -> [a]
-buildBasedOnList ns element rootStyle =
-  case getStyleChildren ns element rootStyle of
-    [] -> []
-    stys -> stys ++
-            concatMap (buildBasedOnList ns element . Just) stys
-
-archiveToNotes :: Archive -> Notes
-archiveToNotes zf =
-  let fnElem = findEntryByPath "word/footnotes.xml" zf
-               >>= (parseXMLDoc . UTF8.toStringLazy . fromEntry)
-      enElem = findEntryByPath "word/endnotes.xml" zf
-               >>= (parseXMLDoc . UTF8.toStringLazy . fromEntry)
-      fn_namespaces = case fnElem of
-        Just e  -> elemToNameSpaces e
-        Nothing -> []
-      en_namespaces = case enElem of
-        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"
-  in
-   Notes ns fn en
-
-archiveToComments :: Archive -> Comments
-archiveToComments zf =
-  let cmtsElem = findEntryByPath "word/comments.xml" zf
-               >>= (parseXMLDoc . UTF8.toStringLazy . fromEntry)
-      cmts_namespaces = case cmtsElem of
-        Just e  -> elemToNameSpaces e
-        Nothing -> []
-      cmts = elemToComments cmts_namespaces <$> cmtsElem
-  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
-
-relElemToRelationship :: DocumentLocation -> Element -> Maybe Relationship
-relElemToRelationship relType element | qName (elName element) == "Relationship" =
-  do
-    relId <- findAttr (QName "Id" Nothing Nothing) element
-    target <- findAttr (QName "Target" Nothing Nothing) element
-    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 =
-  mapMaybe (relElemToRelationship relType) $ elChildren relElems
-filePathToRelationships _ _ = []
-
-archiveToRelationships :: Archive -> [Relationship]
-archiveToRelationships archive =
-  concatMap (filePathToRelationships archive) $ filesInArchive archive
-
-filePathIsMedia :: FilePath -> Bool
-filePathIsMedia fp =
-  let (dir, _) = splitFileName fp
-  in
-   (dir == "word/media/")
-
-lookupLevel :: String -> String -> Numbering -> Maybe Level
-lookupLevel numId ilvl (Numbering _ numbs absNumbs) = do
-  absNumId <- lookup numId $ map (\(Numb nid absnumid) -> (nid, absnumid)) numbs
-  lvls <- lookup absNumId $ map (\(AbstractNumb aid ls) -> (aid, ls)) absNumbs
-  lookup ilvl $ map (\l@(i, _, _, _) -> (i, l)) lvls
-
-
-numElemToNum :: NameSpaces -> Element -> Maybe Numb
-numElemToNum ns element
-  | isElem ns "w" "num" element = do
-      numId <- findAttrByName ns "w" "numId" element
-      absNumId <- findChildByName ns "w" "abstractNumId" element
-                  >>= findAttrByName ns "w" "val"
-      return $ Numb numId absNumId
-numElemToNum _ _ = Nothing
-
-absNumElemToAbsNum :: NameSpaces -> Element -> Maybe AbstractNumb
-absNumElemToAbsNum ns element
-  | isElem ns "w" "abstractNum" element = do
-      absNumId <- findAttrByName ns "w" "abstractNumId" element
-      let levelElems = findChildrenByName ns "w" "lvl" element
-          levels = mapMaybe (levelElemToLevel ns) levelElems
-      return $ AbstractNumb absNumId levels
-absNumElemToAbsNum _ _ = Nothing
-
-levelElemToLevel :: NameSpaces -> Element -> Maybe Level
-levelElemToLevel ns element
-  | isElem ns "w" "lvl" element = do
-      ilvl <- findAttrByName ns "w" "ilvl" element
-      fmt <- findChildByName ns "w" "numFmt" element
-             >>= findAttrByName ns "w" "val"
-      txt <- findChildByName ns "w" "lvlText" element
-             >>= findAttrByName ns "w" "val"
-      let start = findChildByName ns "w" "start" element
-                  >>= findAttrByName ns "w" "val"
-                  >>= (\s -> listToMaybe (map fst (reads s :: [(Integer, String)])))
-      return (ilvl, fmt, txt, start)
-levelElemToLevel _ _ = Nothing
-
-archiveToNumbering' :: Archive -> Maybe Numbering
-archiveToNumbering' zf =
-  case findEntryByPath "word/numbering.xml" zf of
-    Nothing -> Just $ Numbering [] [] []
-    Just entry -> do
-      numberingElem <- (parseXMLDoc . UTF8.toStringLazy . fromEntry) entry
-      let namespaces = elemToNameSpaces numberingElem
-          numElems = findChildrenByName namespaces "w" "num" numberingElem
-          absNumElems = findChildrenByName namespaces "w" "abstractNum" numberingElem
-          nums = mapMaybe (numElemToNum namespaces) numElems
-          absNums = mapMaybe (absNumElemToAbsNum namespaces) absNumElems
-      return $ Numbering namespaces nums absNums
-
-archiveToNumbering :: Archive -> Numbering
-archiveToNumbering archive =
-  fromMaybe (Numbering [] [] []) (archiveToNumbering' archive)
-
-elemToNotes :: NameSpaces -> String -> Element -> Maybe (M.Map String Element)
-elemToNotes ns notetype element
-  | isElem ns "w" (notetype ++ "s") element =
-      let pairs = mapMaybe
-                  (\e -> findAttrByName ns "w" "id" e >>=
-                         (\a -> Just (a, e)))
-                  (findChildrenByName ns "w" notetype element)
-      in
-       Just $
-       M.fromList pairs
-elemToNotes _ _ _ = Nothing
-
-elemToComments :: NameSpaces -> Element -> M.Map String Element
-elemToComments ns element
-  | isElem ns "w" "comments" element =
-      let pairs = mapMaybe
-                  (\e -> findAttrByName ns "w" "id" e >>=
-                         (\a -> Just (a, e)))
-                  (findChildrenByName ns "w" "comment" element)
-      in
-       M.fromList pairs
-elemToComments _ _ = M.empty
-
-
----------------------------------------------
----------------------------------------------
-
-elemToTblGrid :: NameSpaces -> Element -> D TblGrid
-elemToTblGrid ns element | isElem ns "w" "tblGrid" element =
-  let cols = findChildrenByName ns "w" "gridCol" element
-  in
-   mapD (\e -> maybeToD (findAttrByName ns "w" "val" e >>= stringToInteger))
-   cols
-elemToTblGrid _ _ = throwError WrongElem
-
-elemToTblLook :: NameSpaces -> Element -> D TblLook
-elemToTblLook ns element | isElem ns "w" "tblLook" element =
-  let firstRow = findAttrByName ns "w" "firstRow" element
-      val = findAttrByName ns "w" "val" element
-      firstRowFmt =
-        case firstRow of
-          Just "1" -> True
-          Just  _  -> False
-          Nothing -> case val of
-            Just bitMask -> testBitMask bitMask 0x020
-            Nothing      -> False
-  in
-   return $ TblLook{firstRowFormatting = firstRowFmt}
-elemToTblLook _ _ = throwError WrongElem
-
-elemToRow :: NameSpaces -> Element -> D Row
-elemToRow ns element | isElem ns "w" "tr" element =
-  do
-    let cellElems = findChildrenByName ns "w" "tc" element
-    cells <- mapD (elemToCell ns) cellElems
-    return $ Row cells
-elemToRow _ _ = throwError WrongElem
-
-elemToCell :: NameSpaces -> Element -> D Cell
-elemToCell ns element | isElem ns "w" "tc" element =
-  do
-    cellContents <- mapD (elemToBodyPart ns) (elChildren element)
-    return $ Cell cellContents
-elemToCell _ _ = throwError WrongElem
-
-elemToParIndentation :: NameSpaces -> Element -> Maybe ParIndentation
-elemToParIndentation ns element | isElem ns "w" "ind" element =
-  Just $ ParIndentation {
-    leftParIndent =
-       findAttrByName ns "w" "left" element >>=
-       stringToInteger
-    , rightParIndent =
-      findAttrByName ns "w" "right" element >>=
-      stringToInteger
-    , hangingParIndent =
-      findAttrByName ns "w" "hanging" element >>=
-      stringToInteger}
-elemToParIndentation _ _ = Nothing
-
-testBitMask :: String -> Int -> Bool
-testBitMask bitMaskS n =
-  case (reads ("0x" ++ bitMaskS) :: [(Int, String)]) of
-    []            -> False
-    ((n', _) : _) -> (n' .|. n) /= 0
-
-stringToInteger :: String -> Maybe Integer
-stringToInteger s = listToMaybe $ map fst (reads s :: [(Integer, String)])
-
-elemToBodyPart :: NameSpaces -> Element -> D BodyPart
-elemToBodyPart ns element
-  | isElem ns "w" "p" element
-  , (c:_) <- findChildrenByName ns "m" "oMathPara" element =
-      do
-        expsLst <- eitherToD $ readOMML $ showElement c
-        return $ OMathPara expsLst
-elemToBodyPart ns element
-  | isElem ns "w" "p" element
-  , Just (numId, lvl) <- getNumInfo ns element = do
-    sty <- asks envParStyles
-    let parstyle = elemToParagraphStyle ns element sty
-    parparts <- mapD (elemToParPart ns) (elChildren element)
-    num <- asks envNumbering
-    let levelInfo = lookupLevel numId lvl num
-    return $ ListItem parstyle numId lvl levelInfo parparts
-elemToBodyPart ns element
-  | isElem ns "w" "p" element = do
-      sty <- asks envParStyles
-      let parstyle = elemToParagraphStyle ns element sty
-      parparts <- mapD (elemToParPart ns) (elChildren element)
-      -- Word uses list enumeration for numbered headings, so we only
-      -- want to infer a list from the styles if it is NOT a heading.
-      case pHeading parstyle of
-        Nothing | Just (numId, lvl) <- pNumInfo parstyle -> do
-                    num <- asks envNumbering
-                    let levelInfo = lookupLevel numId lvl num
-                    return $ ListItem parstyle numId lvl levelInfo parparts
-        _ -> return $ Paragraph parstyle parparts
-elemToBodyPart ns element
-  | isElem ns "w" "tbl" element = do
-    let caption' = findChildByName ns "w" "tblPr" element
-                   >>= findChildByName ns "w" "tblCaption"
-                   >>= findAttrByName ns "w" "val"
-        caption = (fromMaybe "" caption')
-        grid' = case findChildByName ns "w" "tblGrid" element of
-          Just g  -> elemToTblGrid ns g
-          Nothing -> return []
-        tblLook' = case findChildByName ns "w" "tblPr" element >>=
-                          findChildByName ns "w" "tblLook"
-                     of
-                       Just l  -> elemToTblLook ns l
-                       Nothing -> return defaultTblLook
-
-    grid <- grid'
-    tblLook <- tblLook'
-    rows <- mapD (elemToRow ns) (elChildren element)
-    return $ Tbl caption grid tblLook rows
-elemToBodyPart _ _ = throwError WrongElem
-
-lookupRelationship :: DocumentLocation -> RelId -> [Relationship] -> Maybe Target
-lookupRelationship docLocation relid rels =
-  lookup (docLocation, relid) pairs
-  where
-    pairs = map (\(Relationship loc relid' target) -> ((loc, relid'), target)) rels
-
-expandDrawingId :: String -> D (FilePath, B.ByteString)
-expandDrawingId s = do
-  location <- asks envLocation
-  target <- asks (lookupRelationship location s . envRelationships)
-  case target of
-    Just filepath -> do
-      bytes <- asks (lookup ("word/" ++ filepath) . envMedia)
-      case bytes of
-        Just bs -> return (filepath, bs)
-        Nothing -> throwError DocxError
-    Nothing -> throwError DocxError
-
-getTitleAndAlt :: NameSpaces -> Element -> (String, String)
-getTitleAndAlt ns element =
-  let mbDocPr = findChildByName ns "wp" "inline" element >>=
-                findChildByName ns "wp" "docPr"
-      title = fromMaybe "" (mbDocPr >>= findAttrByName ns "" "title")
-      alt = fromMaybe "" (mbDocPr >>= findAttrByName ns "" "descr")
-  in (title, alt)
-
-elemToParPart :: NameSpaces -> Element -> D ParPart
-elemToParPart ns element
-  | isElem ns "w" "r" element
-  , Just drawingElem <- findChildByName ns "w" "drawing" element
-  , pic_ns <- "http://schemas.openxmlformats.org/drawingml/2006/picture"
-  , Just picElem <- findElement (QName "pic" (Just pic_ns) (Just "pic")) drawingElem
-  = let (title, alt) = getTitleAndAlt ns drawingElem
-        a_ns = "http://schemas.openxmlformats.org/drawingml/2006/main"
-        drawing = findElement (QName "blip" (Just a_ns) (Just "a")) picElem
-                  >>= findAttrByName ns "r" "embed"
-    in
-     case drawing of
-       Just s -> expandDrawingId s >>= (\(fp, bs) -> return $ Drawing fp title alt bs $ elemToExtent drawingElem)
-       Nothing -> throwError WrongElem
--- The below is an attempt to deal with images in deprecated vml format.
-elemToParPart ns element
-  | isElem ns "w" "r" element
-  , Just _ <- findChildByName ns "w" "pict" element =
-    let drawing = findElement (elemName ns "v" "imagedata") element
-                  >>= findAttrByName ns "r" "id"
-    in
-     case drawing of
-       -- Todo: check out title and attr for deprecated format.
-       Just s -> expandDrawingId s >>= (\(fp, bs) -> return $ Drawing fp "" "" bs Nothing)
-       Nothing -> throwError WrongElem
--- Chart
-elemToParPart ns element
-  | isElem ns "w" "r" element
-  , Just drawingElem <- findChildByName ns "w" "drawing" element
-  , c_ns <- "http://schemas.openxmlformats.org/drawingml/2006/chart"
-  , Just _ <- findElement (QName "chart" (Just c_ns) (Just "c")) drawingElem
-  = return Chart
-elemToParPart ns element
-  | isElem ns "w" "r" element =
-    elemToRun ns element >>= (\r -> return $ PlainRun r)
-elemToParPart ns element
-  | isElem ns "w" "ins" element || isElem ns "w" "moveTo" element
-  , Just cId <- findAttrByName ns "w" "id" element
-  , Just cAuthor <- findAttrByName ns "w" "author" element
-  , Just cDate <- findAttrByName ns "w" "date" element = do
-    runs <- mapD (elemToRun ns) (elChildren element)
-    return $ Insertion cId cAuthor cDate runs
-elemToParPart ns element
-  | isElem ns "w" "del" element || isElem ns "w" "moveFrom" element
-  , Just cId <- findAttrByName ns "w" "id" element
-  , Just cAuthor <- findAttrByName ns "w" "author" element
-  , Just cDate <- findAttrByName ns "w" "date" element = do
-    runs <- mapD (elemToRun ns) (elChildren element)
-    return $ Deletion cId cAuthor cDate runs
-elemToParPart ns element
-  | isElem ns "w" "smartTag" element = do
-    runs <- mapD (elemToRun ns) (elChildren element)
-    return $ SmartTag runs
-elemToParPart ns element
-  | isElem ns "w" "bookmarkStart" element
-  , Just bmId <- findAttrByName ns "w" "id" element
-  , Just bmName <- findAttrByName ns "w" "name" element =
-    return $ BookMark bmId bmName
-elemToParPart ns element
-  | isElem ns "w" "hyperlink" element
-  , Just relId <- findAttrByName ns "r" "id" element = do
-    location <- asks envLocation
-    runs <- mapD (elemToRun ns) (elChildren element)
-    rels <- asks envRelationships
-    case lookupRelationship location relId rels of
-      Just target ->
-         case findAttrByName ns "w" "anchor" element of
-             Just anchor -> return $ ExternalHyperLink (target ++ '#':anchor) runs
-             Nothing -> return $ ExternalHyperLink target runs
-      Nothing     -> return $ ExternalHyperLink "" runs
-elemToParPart ns element
-  | isElem ns "w" "hyperlink" element
-  , Just anchor <- findAttrByName ns "w" "anchor" element = do
-    runs <- mapD (elemToRun ns) (elChildren element)
-    return $ InternalHyperLink anchor runs
-elemToParPart ns element
-  | isElem ns "w" "commentRangeStart" element
-  , Just cmtId <- findAttrByName ns "w" "id" element = do
-      (Comments _ commentMap) <- asks envComments
-      case M.lookup cmtId commentMap of
-        Just cmtElem -> elemToCommentStart ns cmtElem
-        Nothing      -> throwError WrongElem
-elemToParPart ns element
-  | isElem ns "w" "commentRangeEnd" element
-  , Just cmtId <- findAttrByName ns "w" "id" element =
-    return $ CommentEnd cmtId
-elemToParPart ns element
-  | isElem ns "m" "oMath" element =
-    fmap PlainOMath (eitherToD $ readOMML $ showElement element)
-elemToParPart _ _ = throwError WrongElem
-
-elemToCommentStart :: NameSpaces -> Element -> D ParPart
-elemToCommentStart ns element
-  | isElem ns "w" "comment" element
-  , Just cmtId <- findAttrByName ns "w" "id" element
-  , Just cmtAuthor <- findAttrByName ns "w" "author" element
-  , Just cmtDate <- findAttrByName ns "w" "date" element = do
-      bps <- mapD (elemToBodyPart ns) (elChildren element)
-      return $ CommentStart cmtId cmtAuthor cmtDate bps
-elemToCommentStart _ _ = throwError WrongElem
-
-lookupFootnote :: String -> Notes -> Maybe Element
-lookupFootnote s (Notes _ fns _) = fns >>= M.lookup s
-
-lookupEndnote :: String -> Notes -> Maybe Element
-lookupEndnote s (Notes _ _ ens) = ens >>= M.lookup s
-
-elemToExtent :: Element -> Extent
-elemToExtent drawingElem =
-  case (getDim "cx", getDim "cy") of
-    (Just w, Just h) -> Just (w, h)
-    _                -> Nothing
-    where
-      wp_ns  = "http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing"
-      getDim at = findElement (QName "extent" (Just wp_ns) (Just "wp")) drawingElem
-                    >>= findAttr (QName at Nothing Nothing) >>= safeRead
-
-
-childElemToRun :: NameSpaces -> Element -> D Run
-childElemToRun ns element
-  | isElem ns "w" "drawing" element
-  , pic_ns <- "http://schemas.openxmlformats.org/drawingml/2006/picture"
-  , Just picElem <- findElement (QName "pic" (Just pic_ns) (Just "pic")) element
-  = let (title, alt) = getTitleAndAlt ns element
-        a_ns = "http://schemas.openxmlformats.org/drawingml/2006/main"
-        drawing = findElement (QName "blip" (Just a_ns) (Just "a")) picElem
-                  >>= findAttr (QName "embed" (lookup "r" ns) (Just "r"))
-    in
-     case drawing of
-       Just s -> expandDrawingId s >>=
-                 (\(fp, bs) -> return $ InlineDrawing fp title alt bs $ elemToExtent element)
-       Nothing -> throwError WrongElem
-childElemToRun ns element
-  | isElem ns "w" "drawing" element
-  , c_ns <- "http://schemas.openxmlformats.org/drawingml/2006/chart"
-  , Just _ <- findElement (QName "chart" (Just c_ns) (Just "c")) element
-  = return InlineChart
-childElemToRun ns element
-  | isElem ns "w" "footnoteReference" element
-  , Just fnId <- findAttrByName ns "w" "id" element = do
-    notes <- asks envNotes
-    case lookupFootnote fnId notes of
-      Just e -> do bps <- local (\r -> r {envLocation=InFootnote}) $ mapD (elemToBodyPart ns) (elChildren e)
-                   return $ Footnote bps
-      Nothing  -> return $ Footnote []
-childElemToRun ns element
-  | isElem ns "w" "endnoteReference" element
-  , Just enId <- findAttrByName ns "w" "id" element = do
-    notes <- asks envNotes
-    case lookupEndnote enId notes of
-      Just e -> do bps <- local (\r -> r {envLocation=InEndnote}) $ mapD (elemToBodyPart ns) (elChildren e)
-                   return $ Endnote bps
-      Nothing  -> return $ Endnote []
-childElemToRun _ _ = throwError WrongElem
-
-elemToRun :: NameSpaces -> Element -> D Run
-elemToRun ns element
-  | isElem ns "w" "r" element
-  , Just altCont <- findChildByName ns "mc" "AlternateContent" element =
-    do let choices = findChildrenByName ns "mc" "Choice" altCont
-           choiceChildren = map head $ filter (not . null) $ map elChildren choices
-       outputs <- mapD (childElemToRun ns) choiceChildren
-       case outputs of
-         r : _ -> return r
-         []    -> throwError WrongElem
-elemToRun ns element
-  | isElem ns "w" "r" element
-  , Just drawingElem <- findChildByName ns "w" "drawing" element =
-    childElemToRun ns drawingElem
-elemToRun ns element
-  | isElem ns "w" "r" element
-  , Just ref <- findChildByName ns "w" "footnoteReference" element =
-    childElemToRun ns ref
-elemToRun ns element
-  | isElem ns "w" "r" element
-  , Just ref <- findChildByName ns "w" "endnoteReference" element =
-    childElemToRun ns ref
-elemToRun ns element
-  | isElem ns "w" "r" element = do
-    runElems <- elemToRunElems ns element
-    runStyle <- elemToRunStyleD ns element
-    return $ Run runStyle runElems
-elemToRun _ _ = throwError WrongElem
-
-getParentStyleValue :: (ParStyleData -> Maybe a) -> ParStyleData -> Maybe a
-getParentStyleValue field style
-  | Just value <- field style = Just value
-  | Just parentStyle <- psStyle style
-                      = getParentStyleValue field (snd parentStyle)
-getParentStyleValue _ _ = Nothing
-
-getParStyleField :: (ParStyleData -> Maybe a) -> ParStyleMap -> [String] ->
-                                                                        Maybe a
-getParStyleField field stylemap styles
-  | x     <- mapMaybe (\x -> M.lookup x stylemap) styles
-  , (y:_) <- mapMaybe (getParentStyleValue field) x
-           = Just y
-getParStyleField _ _ _ = Nothing
-
-elemToParagraphStyle :: NameSpaces -> Element -> ParStyleMap -> ParagraphStyle
-elemToParagraphStyle ns element sty
-  | Just pPr <- findChildByName ns "w" "pPr" element =
-    let style =
-          mapMaybe
-          (findAttrByName ns "w" "val")
-          (findChildrenByName ns "w" "pStyle" pPr)
-    in ParagraphStyle
-      {pStyle = style
-      , indentation =
-          findChildByName ns "w" "ind" pPr >>=
-          elemToParIndentation ns
-      , dropCap =
-          case
-            findChildByName ns "w" "framePr" pPr >>=
-            findAttrByName ns "w" "dropCap"
-          of
-            Just "none" -> False
-            Just _      -> True
-            Nothing     -> False
-      , pHeading = getParStyleField headingLev sty style
-      , pNumInfo = getParStyleField numInfo sty style
-      , pBlockQuote = getParStyleField isBlockQuote sty style
-      }
-elemToParagraphStyle _ _ _ =  defaultParagraphStyle
-
-checkOnOff :: NameSpaces -> Element -> QName -> Maybe Bool
-checkOnOff ns rPr tag
-  | Just t <-  findChild tag rPr
-  , Just val <- findAttrByName ns "w" "val" t =
-    Just $ case val of
-      "true"  -> True
-      "false" -> False
-      "on"    -> True
-      "off"   -> False
-      "1"     -> True
-      "0"     -> False
-      _       -> False
-  | Just _ <- findChild tag rPr = Just True
-checkOnOff _ _ _ = Nothing
-
-elemToRunStyleD :: NameSpaces -> Element -> D RunStyle
-elemToRunStyleD ns element
-  | Just rPr <- findChildByName ns "w" "rPr" element = do
-    charStyles <- asks envCharStyles
-    let parentSty = case
-          findChildByName ns "w" "rStyle" rPr >>=
-          findAttrByName ns "w" "val"
-          of
-            Just styName | Just style <- M.lookup styName charStyles ->
-              Just (styName, style)
-            _            -> Nothing
-    return $ elemToRunStyle ns element parentSty
-elemToRunStyleD _ _ = return defaultRunStyle
-
-elemToRunStyle :: NameSpaces -> Element -> Maybe CharStyle -> RunStyle
-elemToRunStyle ns element parentStyle
-  | Just rPr <- findChildByName ns "w" "rPr" element =
-    RunStyle
-      {
-        isBold = checkOnOff ns rPr (elemName ns "w" "b")
-      , isItalic = checkOnOff ns rPr (elemName ns "w" "i")
-      , isSmallCaps = checkOnOff ns rPr (elemName ns "w" "smallCaps")
-      , isStrike = checkOnOff ns rPr (elemName ns "w" "strike")
-      , rVertAlign =
-           findChildByName ns "w" "vertAlign" rPr >>=
-           findAttrByName ns "w" "val" >>=
-           \v -> Just $ case v of
-             "superscript" -> SupScrpt
-             "subscript"   -> SubScrpt
-             _             -> BaseLn
-      , rUnderline =
-          findChildByName ns "w" "u" rPr >>=
-          findAttrByName ns "w" "val"
-      , rStyle = parentStyle
-        }
-elemToRunStyle _ _ _ = defaultRunStyle
-
-getHeaderLevel :: NameSpaces -> Element -> Maybe (String,Int)
-getHeaderLevel ns element
-  | Just styleId <- findAttrByName ns "w" "styleId" element
-  , Just index   <- stripPrefix "Heading" styleId
-  , Just n       <- stringToInteger index
-  , n > 0 = Just (styleId, fromInteger n)
-  | Just styleId <- findAttrByName ns "w" "styleId" element
-  , Just index   <- findChildByName ns "w" "name" element >>=
-                    findAttrByName ns "w" "val" >>=
-                    stripPrefix "heading "
-  , Just n <- stringToInteger index
-  , n > 0 = Just (styleId, fromInteger n)
-getHeaderLevel _ _ = Nothing
-
-blockQuoteStyleIds :: [String]
-blockQuoteStyleIds = ["Quote", "BlockQuote", "BlockQuotation"]
-
-blockQuoteStyleNames :: [String]
-blockQuoteStyleNames = ["Quote", "Block Text"]
-
-getBlockQuote :: NameSpaces -> Element -> Maybe Bool
-getBlockQuote ns element
-  | Just styleId <- findAttrByName ns "w" "styleId" element
-  , styleId `elem` blockQuoteStyleIds = Just True
-  | Just styleName <- findChildByName ns "w" "name" element >>=
-                      findAttrByName ns "w" "val"
-  , styleName `elem` blockQuoteStyleNames = Just True
-getBlockQuote _ _ = Nothing
-
-getNumInfo :: NameSpaces -> Element -> Maybe (String, String)
-getNumInfo ns element = do
-  let numPr = findChildByName ns "w" "pPr" element >>=
-              findChildByName ns "w" "numPr"
-      lvl = fromMaybe "0" (numPr >>=
-                           findChildByName ns "w" "ilvl" >>=
-                           findAttrByName ns "w" "val")
-  numId <- numPr >>=
-           findChildByName ns "w" "numId" >>=
-           findAttrByName ns "w" "val"
-  return (numId, lvl)
-
-
-elemToParStyleData :: NameSpaces -> Element -> Maybe ParStyle -> ParStyleData
-elemToParStyleData ns element parentStyle =
-    ParStyleData
-      {
-        headingLev = getHeaderLevel ns element
-      , isBlockQuote = getBlockQuote ns element
-      , numInfo = getNumInfo ns element
-      , psStyle = parentStyle
-        }
-
-elemToRunElem :: NameSpaces -> Element -> D RunElem
-elemToRunElem ns element
-  | isElem ns "w" "t" element
-    || isElem ns "w" "delText" element
-    || isElem ns "m" "t" element = do
-    let str = strContent element
-    font <- asks envFont
-    case font of
-      Nothing -> return $ TextRun str
-      Just f  -> return . TextRun $
-                  map (\x -> fromMaybe x . getUnicode f . lowerFromPrivate $ x) str
-  | isElem ns "w" "br" element = return LnBrk
-  | isElem ns "w" "tab" element = return Tab
-  | isElem ns "w" "softHyphen" element = return SoftHyphen
-  | isElem ns "w" "noBreakHyphen" element = return NoBreakHyphen
-  | isElem ns "w" "sym" element = return (getSymChar ns element)
-  | otherwise = throwError WrongElem
-  where
-    lowerFromPrivate (ord -> c)
-      | c >= ord '\xF000' = chr $ c - ord '\xF000'
-      | otherwise = chr c
-
--- The char attribute is a hex string
-getSymChar :: NameSpaces -> Element -> RunElem
-getSymChar ns element
-  | Just s <- lowerFromPrivate <$> getCodepoint
-  , Just font <- getFont =
-  let [(char, _)] = readLitChar ("\\x" ++ s) in
-    TextRun . maybe "" (:[]) $ getUnicode font char
-  where
-    getCodepoint = findAttrByName ns "w" "char" element
-    getFont = stringToFont =<< findAttrByName ns "w" "font" element
-    lowerFromPrivate ('F':xs) = '0':xs
-    lowerFromPrivate xs       = xs
-getSymChar _ _ = TextRun ""
-
-elemToRunElems :: NameSpaces -> Element -> D [RunElem]
-elemToRunElems ns element
-  |  isElem ns "w" "r" element
-     || isElem ns "m" "r" element = do
-       let qualName = elemName ns "w"
-       let font = do
-                    fontElem <- findElement (qualName "rFonts") element
-                    stringToFont =<<
-                      foldr (<|>) Nothing (
-                        map (flip findAttr fontElem . qualName) ["ascii", "hAnsi"])
-       local (setFont font) (mapD (elemToRunElem ns) (elChildren element))
-elemToRunElems _ _ = throwError WrongElem
-
-setFont :: Maybe Font -> ReaderEnv -> ReaderEnv
-setFont f s = s{envFont = f}
+{-# LANGUAGE TupleSections     #-}
+{-# LANGUAGE LambdaCase        #-}
+{-# LANGUAGE OverloadedStrings #-}
+{- |
+ Module : Text.Pandoc.Readers.Docx.Parse
+ Copyright : Copyright (C) 2014-2020 Jesse Rosenthal
+                           2019 Nikolay Yakimov <root@livid.pp.ru>
+ License : GNU GPL, version 2 or above
+
+ Maintainer : Jesse Rosenthal <jrosenthal@jhu.edu>
+ Stability : alpha
+ Portability : portable
+
+Conversion of docx archive into Docx haskell type
+-}
+
+module Text.Pandoc.Readers.Docx.Parse ( Docx(..)
+                                      , Document(..)
+                                      , Body(..)
+                                      , BodyPart(..)
+                                      , TblLook(..)
+                                      , Extent
+                                      , ParPart(..)
+                                      , Run(..)
+                                      , RunElem(..)
+                                      , Notes
+                                      , Numbering
+                                      , Relationship
+                                      , Media
+                                      , RunStyle(..)
+                                      , VertAlign(..)
+                                      , ParIndentation(..)
+                                      , Justification(..)
+                                      , ParagraphStyle(..)
+                                      , ParStyle
+                                      , CharStyle(cStyleData)
+                                      , Row(..)
+                                      , TblHeader(..)
+                                      , Align(..)
+                                      , Cell(..)
+                                      , VMerge(..)
+                                      , TrackedChange(..)
+                                      , ChangeType(..)
+                                      , ChangeInfo(..)
+                                      , FieldInfo(..)
+                                      , IndexEntry(..)
+                                      , Level(..)
+                                      , ParaStyleName
+                                      , CharStyleName
+                                      , FromStyleName(..)
+                                      , HasStyleName(..)
+                                      , HasParentStyle(..)
+                                      , archiveToDocx
+                                      , archiveToDocxWithWarnings
+                                      , getStyleNames
+                                      , pHeading
+                                      , pStyleIndentation
+                                      , constructBogusParStyleData
+                                      , leftBiasedMergeRunStyle
+                                      , rowsToRowspans
+                                      , extractTarget
+                                      ) where
+import Text.Pandoc.Readers.Docx.Parse.Styles
+import Codec.Archive.Zip
+import Control.Applicative ((<|>))
+import Control.Monad
+import Control.Monad.Except
+import Control.Monad.Reader
+import Control.Monad.State.Strict
+import Data.Bits ((.&.))
+import qualified Data.ByteString.Lazy as B
+import Data.Char (chr, ord, readLitChar)
+import Data.List
+import qualified Data.Map as M
+import qualified Data.Text as T
+import Data.Text (Text)
+import Data.Maybe
+import System.FilePath
+import Text.Pandoc.Readers.Docx.Util
+import Text.Pandoc.Readers.Docx.Fields
+import Text.Pandoc.Shared (filteredFilesFromArchive, safeRead)
+import qualified Text.Pandoc.UTF8 as UTF8
+import Text.TeXMath (Exp)
+import Text.TeXMath.Readers.OMML (readOMML)
+import Text.Pandoc.Readers.Docx.Symbols (symbolMap, Font(..), textToFont)
+import Text.Pandoc.XML.Light
+    ( filterChild,
+      findElement,
+      strContent,
+      showElement,
+      findAttr,
+      filterChild,
+      filterChildrenName,
+      filterElementName,
+      filterElementsName,
+      lookupAttrBy,
+      parseXMLElement,
+      elChildren,
+      QName(QName, qName),
+      Content(Elem),
+      Element(..))
+
+data ReaderEnv = ReaderEnv { envNotes         :: Notes
+                           , envComments      :: Comments
+                           , envNumbering     :: Numbering
+                           , envRelationships :: [Relationship]
+                           , envMedia         :: Media
+                           , envFont          :: Maybe Font
+                           , envCharStyles    :: CharStyleMap
+                           , envParStyles     :: ParStyleMap
+                           , envLocation      :: DocumentLocation
+                           , envDocXmlPath    :: FilePath
+                           , envTextWidth     :: Int
+                           }
+               deriving Show
+
+data ReaderState = ReaderState { stateWarnings :: [T.Text]
+                               , stateFldCharState :: [FldCharState]
+                               }
+                 deriving Show
+
+data FldCharState = FldCharOpen
+                  | FldCharFieldInfo T.Text
+                  | FldCharContent FieldInfo [ParPart]
+                  deriving (Show)
+
+data DocxError = DocxError
+               | WrongElem
+               deriving Show
+
+type D = ExceptT DocxError (ReaderT ReaderEnv (State ReaderState))
+
+runD :: D a -> ReaderEnv -> ReaderState -> (Either DocxError a, ReaderState)
+runD dx re rs = runState (runReaderT (runExceptT dx) re) rs
+
+maybeToD :: Maybe a -> D a
+maybeToD (Just a) = return a
+maybeToD Nothing  = throwError DocxError
+
+eitherToD :: Either a b -> D b
+eitherToD (Right b) = return b
+eitherToD (Left _)  = throwError DocxError
+
+concatMapM        :: (Monad m) => (a -> m [b]) -> [a] -> m [b]
+concatMapM f xs   =  liftM concat (mapM f xs)
+
+-- This is similar to `mapMaybe`: it maps a function returning the D
+-- monad over a list, and only keeps the non-erroring return values.
+mapD :: (a -> D b) -> [a] -> D [b]
+mapD f xs =
+  let handler x = (f x >>= (\y-> return [y])) `catchError` (\_ -> return [])
+  in
+   concatMapM handler xs
+
+unwrapElement :: NameSpaces -> Element -> [Element]
+unwrapElement ns element
+  | isElem ns "w" "sdt" element
+  , Just sdtContent <- findChildByName ns "w" "sdtContent" element
+  = concatMap (unwrapElement ns) (elChildren sdtContent)
+  | isElem ns "w" "smartTag" element
+  = concatMap (unwrapElement ns) (elChildren element)
+  | isElem ns "w" "p" element
+  , _:_ <- findChildrenByName ns "w" "r" element >>= findTextboxes
+  = let result = splitP (elContent element) [] -- handle #9214, #11053
+    in [element{ elName = QName "textbox-image" Nothing Nothing
+              , elContent = map Elem result }]
+  | isElem ns "w" "r" element
+  , Just fallback <- findChildByName ns "mc" "AlternateContent" element >>=
+                     findChildByName ns "mc" "Fallback"
+  = [element{ elContent = concatMap (unwrapContent ns) (elContent fallback) }]
+  | otherwise
+  = [element{ elContent = concatMap (unwrapContent ns) (elContent element) }]
+  where
+    -- Split a w:p's children around textbox-bearing runs, preserving order.
+    -- Non-textbox content is grouped into a copy of the original w:p;
+    -- textbox content is unwrapped into sibling elements in place.
+    splitP [] acc = [wrapP acc | hasContent acc]
+    splitP (c:cs) acc
+      | Elem el <- c
+      , isElem ns "w" "r" el
+      , tbs@(_:_) <- findTextboxes el
+      = [wrapP acc | hasContent acc]
+        ++ concatMap (unwrapElement ns) (concatMap elChildren tbs)
+        ++ splitP cs []
+      | otherwise
+      = splitP cs (acc ++ [c])
+    wrapP cs = element{ elContent = concatMap (unwrapContent ns) cs }
+    hasContent = any (\case Elem el -> isElem ns "w" "r" el
+                                                  && any (isContentElem . elName)
+                                                         (elChildren el)
+                            _ -> False)
+    isContentElem n = qName n `elem`
+      ["t", "drawing", "pict", "br", "tab", "sym", "fldChar", "instrText"]
+    -- Search textbox content in the run's effective children.
+    -- If AlternateContent is present, use only the fallback branch,
+    -- matching the w:r unwrapping logic and avoiding duplicate textbox
+    -- extraction when both direct and fallback encodings are present.
+    findRunFallback run =
+      findChildByName ns "mc" "AlternateContent" run >>=
+      findChildByName ns "mc" "Fallback"
+    findTextboxes run =
+      findTextboxContent =<<
+      case findRunFallback run of
+        Just fallback -> findChildrenByName ns "w" "pict" fallback
+        Nothing -> findChildrenByName ns "w" "pict" run
+    findTextboxContent pict =
+      (findChildrenByName ns "v" "shape" pict <>
+       findChildrenByName ns "v" "rect" pict) >>=
+      findChildrenByName ns "v" "textbox" >>=
+      findChildrenByName ns "w" "txbxContent"
+
+unwrapContent :: NameSpaces -> Content -> [Content]
+unwrapContent ns (Elem element) = map Elem $ unwrapElement ns element
+unwrapContent _ content = [content]
+
+walkDocument :: NameSpaces -> Element -> Element
+walkDocument ns element =
+  element{ elContent = concatMap (unwrapContent ns) (elContent element) }
+
+newtype Docx = Docx Document
+          deriving Show
+
+data Document = Document NameSpaces Body
+          deriving Show
+
+newtype Body = Body [BodyPart]
+          deriving Show
+
+type Media = [(FilePath, B.ByteString)]
+
+type CharStyleMap = M.Map CharStyleId CharStyle
+
+type ParStyleMap = M.Map ParaStyleId ParStyle
+
+data Numbering = Numbering NameSpaces [Numb] [AbstractNumb]
+                 deriving Show
+
+data Numb = Numb T.Text T.Text [LevelOverride]
+            deriving Show
+
+--                                 ilvl    startOverride   lvl
+data LevelOverride = LevelOverride T.Text (Maybe Integer) (Maybe Level)
+  deriving Show
+
+data AbstractNumb = AbstractNumb T.Text [Level]
+                    deriving Show
+
+--                 ilvl   format string  start
+data Level = Level T.Text T.Text T.Text (Maybe Integer)
+  deriving Show
+
+data DocumentLocation = InDocument | InFootnote | InEndnote
+                      deriving (Eq,Show)
+
+data Relationship = Relationship DocumentLocation RelId Target
+                  deriving Show
+
+data Notes = Notes NameSpaces
+             (Maybe (M.Map T.Text Element))
+             (Maybe (M.Map T.Text Element))
+           deriving Show
+
+data Comments = Comments NameSpaces (M.Map T.Text Element)
+              deriving Show
+
+data ChangeType = Insertion | Deletion
+                deriving Show
+
+data ChangeInfo = ChangeInfo ChangeId Author (Maybe ChangeDate)
+                deriving Show
+
+data TrackedChange = TrackedChange ChangeType ChangeInfo
+                   deriving Show
+
+data Justification = JustifyBoth | JustifyLeft | JustifyRight | JustifyCenter
+  deriving (Show, Eq)
+
+data ParagraphStyle = ParagraphStyle { pStyle        :: [ParStyle]
+                                     , indentation   :: Maybe ParIndentation
+                                     , justification :: Maybe Justification
+                                     , numbered      :: Bool
+                                     , dropCap       :: Bool
+                                     , pChange       :: Maybe TrackedChange
+                                     , pBidi         :: Maybe Bool
+                                     , pKeepNext     :: Bool
+                                     }
+                      deriving Show
+
+defaultParagraphStyle :: ParagraphStyle
+defaultParagraphStyle = ParagraphStyle { pStyle = []
+                                       , indentation = Nothing
+                                       , justification = Nothing
+                                       , numbered = False
+                                       , dropCap = False
+                                       , pChange = Nothing
+                                       , pBidi = Just False
+                                       , pKeepNext = False
+                                       }
+
+
+data BodyPart = Paragraph ParagraphStyle [ParPart]
+              | Heading Int ParaStyleName ParagraphStyle T.Text T.Text (Maybe Level)
+                 [ParPart]
+              | ListItem ParagraphStyle T.Text T.Text (Maybe Level) [ParPart]
+              | Tbl (Maybe T.Text) T.Text TblGrid TblLook [Row]
+              | Captioned ParagraphStyle [ParPart] BodyPart
+              | HRule
+              deriving Show
+
+type TblGrid = [Double]
+
+newtype TblLook = TblLook {firstRowFormatting::Bool}
+              deriving Show
+
+defaultTblLook :: TblLook
+defaultTblLook = TblLook{firstRowFormatting = False}
+
+data Row = Row TblHeader [Cell] deriving Show
+
+data TblHeader = HasTblHeader | NoTblHeader deriving (Show, Eq)
+
+data Align = AlignDefault | AlignLeft | AlignRight | AlignCenter
+  deriving (Show, Eq)
+
+data Cell = Cell Align GridSpan VMerge [BodyPart]
+            deriving Show
+
+emptyCell :: Cell
+emptyCell = Cell AlignDefault 1 Restart []
+
+type GridSpan = Integer
+
+data VMerge = Continue
+            -- ^ This cell should be merged with the one above it
+            | Restart
+            -- ^ This cell should not be merged with the one above it
+            deriving (Show, Eq)
+
+rowsToRowspans :: [Row] -> [[(Int, Cell)]]
+rowsToRowspans rows = let
+  removeMergedCells = fmap (filter (\(_, Cell _ _ vmerge _) -> vmerge == Restart))
+  in removeMergedCells (foldr f [] rows)
+  where
+    f :: Row -> [[(Int, Cell)]] -> [[(Int, Cell)]]
+    f (Row _ cells) acc = let
+      spans = g cells Nothing (listToMaybe acc)
+      in spans : acc
+
+    g :: [Cell] -- the current row
+      -> Maybe Integer -- Number of columns left below
+      -> Maybe [(Int, Cell)] -- (rowspan so far, cell) for the row below this one
+      -> [(Int, Cell)] -- (rowspan so far, cell) for this row
+    g cells _ Nothing = map (1,) cells
+    g cells columnsLeftBelow (Just rowBelow) =
+        case cells of
+          [] -> []
+          thisCell@(Cell _ thisGridSpan _ _) : restOfRow -> case rowBelow of
+            [] -> map (1,) cells
+            (spanSoFarBelow, Cell _ gridSpanBelow vmerge _) : _ ->
+              let spanSoFar = case vmerge of
+                    Restart -> 1
+                    Continue -> 1 + spanSoFarBelow
+                  columnsToDrop = thisGridSpan + (gridSpanBelow - fromMaybe gridSpanBelow columnsLeftBelow)
+                  (newColumnsLeftBelow, restOfRowBelow) = dropColumns columnsToDrop rowBelow
+              in (spanSoFar, thisCell) : g restOfRow (Just newColumnsLeftBelow) (Just restOfRowBelow)
+
+    dropColumns :: Integer -> [(a, Cell)] -> (Integer, [(a, Cell)])
+    dropColumns n [] = (n, [])
+    dropColumns n cells@((_, Cell _ gridSpan _ _) : otherCells) =
+      if n < gridSpan
+      then (gridSpan - n, cells)
+      else dropColumns (n - gridSpan) otherCells
+
+leftBiasedMergeRunStyle :: RunStyle -> RunStyle -> RunStyle
+leftBiasedMergeRunStyle a b = RunStyle
+    { isBold = isBold a <|> isBold b
+    , isBoldCTL = isBoldCTL a <|> isBoldCTL b
+    , isItalic = isItalic a <|> isItalic b
+    , isItalicCTL = isItalicCTL a <|> isItalicCTL b
+    , isSmallCaps = isSmallCaps a <|> isSmallCaps b
+    , isStrike = isStrike a <|> isStrike b
+    , isRTL = isRTL a <|> isRTL b
+    , isForceCTL = isForceCTL a <|> isForceCTL b
+    , rHighlight = rHighlight a <|> rHighlight b
+    , rVertAlign = rVertAlign a <|> rVertAlign b
+    , rUnderline = rUnderline a <|> rUnderline b
+    , rParentStyle = rParentStyle a
+    }
+
+-- (width, height) in EMUs
+type Extent = Maybe (Double, Double)
+
+data ParPart = PlainRun Run
+             | ChangedRuns TrackedChange [ParPart]
+             | CommentStart CommentId Author (Maybe CommentDate) [BodyPart]
+             | CommentEnd CommentId
+             | BookMark BookMarkId Anchor
+             | InternalHyperLink Anchor [ParPart]
+             | ExternalHyperLink URL [ParPart]
+             | Drawing FilePath T.Text T.Text B.ByteString Extent -- title, alt
+             | Chart                                              -- placeholder for now
+             | Diagram                                            -- placeholder for now
+             | PlainOMath [Exp]
+             | OMathPara [Exp]
+             | Field FieldInfo [ParPart]
+             deriving Show
+
+data Run = Run RunStyle [RunElem]
+         | Footnote [BodyPart]
+         | Endnote [BodyPart]
+         | InlineDrawing FilePath T.Text T.Text B.ByteString Extent -- title, alt
+         | InlineChart          -- placeholder
+         | InlineDiagram        -- placeholder
+           deriving Show
+
+data RunElem = TextRun T.Text | LnBrk | Tab | SoftHyphen | NoBreakHyphen
+             deriving Show
+
+type Target = T.Text
+type Anchor = T.Text
+type URL = T.Text
+type BookMarkId = T.Text
+type RelId = T.Text
+type ChangeId = T.Text
+type CommentId = T.Text
+type Author = T.Text
+type ChangeDate = T.Text
+type CommentDate = T.Text
+
+archiveToDocx :: Archive -> Either DocxError Docx
+archiveToDocx archive = fst <$> archiveToDocxWithWarnings archive
+
+archiveToDocxWithWarnings :: Archive -> Either DocxError (Docx, [T.Text])
+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 docXmlPath
+      media     = filteredFilesFromArchive archive filePathIsMedia
+      (styles, parstyles) = archiveToStyles archive
+      textWidth = archiveToTextWidth archive
+      rEnv = ReaderEnv { envNotes = notes
+                       , envComments = comments
+                       , envNumbering = numbering
+                       , envRelationships = rels
+                       , envMedia = media
+                       , envFont = Nothing
+                       , envCharStyles = styles
+                       , envParStyles = parstyles
+                       , envLocation = InDocument
+                       , envDocXmlPath = docXmlPath
+                       , envTextWidth = fromMaybe 9360 textWidth
+                       }
+      rState = ReaderState { stateWarnings = []
+                           , stateFldCharState = []
+                           }
+      (eitherDoc, st) = runD (archiveToDocument archive) rEnv rState
+  case eitherDoc of
+    Right doc -> Right (Docx doc, stateWarnings st)
+    Left e    -> Left e
+
+parseXMLFromEntry :: Entry -> Maybe Element
+parseXMLFromEntry entry =
+  case parseXMLElement (UTF8.toTextLazy (fromEntry entry)) of
+    Left _   -> Nothing
+    Right el -> Just el
+
+getDocumentXmlPath :: Archive -> Maybe FilePath
+getDocumentXmlPath zf = do
+  entry <- findEntryByPath "_rels/.rels" zf
+  relsElem <- parseXMLFromEntry entry
+  let rels = filterChildrenName (\n -> qName n == "Relationship") relsElem
+  rel <- find (\e ->
+                 case findAttr (QName "Type" Nothing Nothing) e of
+                   Just u -> isNamespace "officeDocument" "relationships/officeDocument" u
+                   Nothing -> False)
+         rels
+  fp <- findAttr (QName "Target" Nothing Nothing) rel
+  -- sometimes there will be a leading slash, which windows seems to
+  -- have trouble with.
+  return $ case T.unpack fp of
+    '/' : fp' -> fp'
+    fp'       -> fp'
+
+archiveToDocument :: Archive -> D Document
+archiveToDocument zf = do
+  docPath <- asks envDocXmlPath
+  entry <- maybeToD $ findEntryByPath docPath zf
+  docElem <- maybeToD $ parseXMLFromEntry entry
+  let namespaces = elemToNameSpaces docElem
+  bodyElem <- maybeToD $ findChildByName namespaces "w" "body" docElem
+  let bodyElem' = walkDocument namespaces bodyElem
+  body <- elemToBody namespaces bodyElem'
+  return $ Document namespaces body
+
+elemToBody :: NameSpaces -> Element -> D Body
+elemToBody ns element
+  | isElem ns "w" "body" element =
+      Body . addCaptioned <$> concatMapM (elemToBodyParts ns) (elChildren element)
+  | otherwise = throwError WrongElem
+  where
+    elemToBodyParts ns' el
+      | qName (elName el) == "textbox-image"
+      = addSplitGroupCaptioned . splitMixedParagraphs
+          <$> mapD (elemToBodyPart ns') (elChildren el)
+      | otherwise
+      = ((:[]) <$> elemToBodyPart ns' el) `catchError` (\_ -> return [])
+
+archiveToStyles :: Archive -> (CharStyleMap, ParStyleMap)
+archiveToStyles = archiveToStyles' getStyleId getStyleId
+
+class HasParentStyle a where
+  getParentStyle :: a -> Maybe a
+
+instance HasParentStyle CharStyle where
+  getParentStyle = rParentStyle . cStyleData
+
+instance HasParentStyle ParStyle where
+  getParentStyle = psParentStyle
+
+getStyleNames :: (Functor t, HasStyleName a) => t a -> t (StyleName a)
+getStyleNames = fmap getStyleName
+
+constructBogusParStyleData :: ParaStyleName -> ParStyle
+constructBogusParStyleData stName = ParStyle
+  { headingLev = Nothing
+  , indent = Nothing
+  , numInfo = Nothing
+  , psParentStyle = Nothing
+  , pStyleName = stName
+  , pStyleId = ParaStyleId . T.filter (/=' ') . fromStyleName $ stName
+  }
+
+archiveToNotes :: Archive -> Notes
+archiveToNotes zf =
+  let fnElem = findEntryByPath "word/footnotes.xml" zf
+               >>= parseXMLFromEntry
+      enElem = findEntryByPath "word/endnotes.xml" zf
+               >>= parseXMLFromEntry
+      fn_namespaces = maybe mempty elemToNameSpaces fnElem
+      en_namespaces = maybe mempty elemToNameSpaces enElem
+      ns = M.union fn_namespaces en_namespaces
+      fn = fnElem >>= elemToNotes ns "footnote" . walkDocument ns
+      en = enElem >>= elemToNotes ns "endnote" . walkDocument ns
+  in
+   Notes ns fn en
+
+archiveToComments :: Archive -> Comments
+archiveToComments zf =
+  let cmtsElem = findEntryByPath "word/comments.xml" zf
+               >>= parseXMLFromEntry
+      cmts_namespaces = maybe mempty elemToNameSpaces cmtsElem
+      cmts = elemToComments cmts_namespaces . walkDocument cmts_namespaces <$>
+               cmtsElem
+  in
+    case cmts of
+      Just c  -> Comments cmts_namespaces c
+      Nothing -> Comments cmts_namespaces M.empty
+
+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" =
+  do
+    relId <- findAttr (QName "Id" Nothing Nothing) element
+    target <- findAttr (QName "Target" Nothing Nothing) element
+    -- target may be relative (media/image1.jpeg) or absolute (/word/media/image1.jpg)
+    return $ Relationship relType relId target
+relElemToRelationship _ _ = Nothing
+
+extractTarget :: Element -> Maybe Target
+extractTarget element = do (Relationship _ _ target) <- relElemToRelationship InDocument element
+                           return target
+
+filePathToRelationships :: Archive -> FilePath -> FilePath ->  [Relationship]
+filePathToRelationships ar docXmlPath fp
+  | Just relType <- filePathToRelType fp docXmlPath
+  , Just entry <- findEntryByPath fp ar
+  , Just relElems <- parseXMLFromEntry entry =
+  mapMaybe (relElemToRelationship relType) $ elChildren relElems
+filePathToRelationships _ _ _ = []
+
+archiveToRelationships :: Archive -> FilePath -> [Relationship]
+archiveToRelationships archive docXmlPath =
+  concatMap (filePathToRelationships archive docXmlPath) $ filesInArchive archive
+
+filePathIsMedia :: FilePath -> Bool
+filePathIsMedia fp =
+  "media" `elem` splitDirectories (takeDirectory fp)
+
+lookupLevel :: T.Text -> T.Text -> Numbering -> Maybe Level
+lookupLevel numId ilvl (Numbering _ numbs absNumbs) = do
+  (absNumId, ovrrides) <- lookup numId $
+                          map (\(Numb nid absnumid ovrRides) -> (nid, (absnumid, ovrRides))) numbs
+  lvls <- lookup absNumId $
+    map (\(AbstractNumb aid ls) -> (aid, ls)) absNumbs
+  -- this can be a maybe, so we do a let
+  let lvlOverride = lookup ilvl $
+                    map (\lo@(LevelOverride ilvl' _ _) -> (ilvl', lo)) ovrrides
+  case lvlOverride of
+    Just (LevelOverride _ _ (Just lvl')) -> Just lvl'
+    Just (LevelOverride _ (Just strt) _) ->
+      lookup ilvl $ map (\(Level i fmt s _) -> (i, Level i fmt s (Just strt))) lvls
+    _ ->
+      lookup ilvl $ map (\l@(Level i _ _ _) -> (i, l)) lvls
+
+loElemToLevelOverride :: NameSpaces -> Element -> Maybe LevelOverride
+loElemToLevelOverride ns element
+  | isElem ns "w" "lvlOverride" element = do
+      ilvl <- findAttrByName ns "w" "ilvl" element
+      let startOverride = findChildByName ns "w" "startOverride" element
+                          >>= findAttrByName ns "w" "val"
+                          >>= stringToInteger
+          lvl = findChildByName ns "w" "lvl" element
+                >>= levelElemToLevel ns
+      return $ LevelOverride ilvl startOverride lvl
+loElemToLevelOverride _ _ = Nothing
+
+numElemToNum :: NameSpaces -> Element -> Maybe Numb
+numElemToNum ns element
+  | isElem ns "w" "num" element = do
+      numId <- findAttrByName ns "w" "numId" element
+      absNumId <- findChildByName ns "w" "abstractNumId" element
+                  >>= findAttrByName ns "w" "val"
+      let lvlOverrides = mapMaybe
+                         (loElemToLevelOverride ns)
+                         (findChildrenByName ns "w" "lvlOverride" element)
+      return $ Numb numId absNumId lvlOverrides
+numElemToNum _ _ = Nothing
+
+absNumElemToAbsNum :: NameSpaces -> Element -> Maybe AbstractNumb
+absNumElemToAbsNum ns element
+  | isElem ns "w" "abstractNum" element = do
+      absNumId <- findAttrByName ns "w" "abstractNumId" element
+      let levelElems = findChildrenByName ns "w" "lvl" element
+          levels = mapMaybe (levelElemToLevel ns) levelElems
+      return $ AbstractNumb absNumId levels
+absNumElemToAbsNum _ _ = Nothing
+
+levelElemToLevel :: NameSpaces -> Element -> Maybe Level
+levelElemToLevel ns element
+  | isElem ns "w" "lvl" element = do
+      ilvl <- findAttrByName ns "w" "ilvl" element
+      fmt <- findChildByName ns "w" "numFmt" element
+             >>= findAttrByName ns "w" "val"
+      txt <- findChildByName ns "w" "lvlText" element
+             >>= findAttrByName ns "w" "val"
+      let start = findChildByName ns "w" "start" element
+                  >>= findAttrByName ns "w" "val"
+                  >>= stringToInteger
+      return (Level ilvl fmt txt start)
+levelElemToLevel _ _ = Nothing
+
+archiveToNumbering' :: Archive -> Maybe Numbering
+archiveToNumbering' zf =
+  case findEntryByPath "word/numbering.xml" zf of
+    Nothing -> Just $ Numbering mempty [] []
+    Just entry -> do
+      numberingElem <- parseXMLFromEntry entry
+      let namespaces = elemToNameSpaces numberingElem
+          numElems = findChildrenByName namespaces "w" "num" numberingElem
+          absNumElems = findChildrenByName namespaces "w" "abstractNum" numberingElem
+          nums = mapMaybe (numElemToNum namespaces) numElems
+          absNums = mapMaybe (absNumElemToAbsNum namespaces) absNumElems
+      return $ Numbering namespaces nums absNums
+
+archiveToNumbering :: Archive -> Numbering
+archiveToNumbering archive =
+  fromMaybe (Numbering mempty [] []) (archiveToNumbering' archive)
+
+archiveToTextWidth :: Archive -> Maybe Int
+archiveToTextWidth zf = do
+  entry <- findEntryByPath "word/document.xml" zf
+  docElem <- parseXMLFromEntry entry
+  let ns = elemToNameSpaces docElem
+  sectElem <- findChildByName ns "w" "body" docElem >>= findChildByName ns "w" "sectPr"
+  pgWidth <- findChildByName ns "w" "pgSz" sectElem
+               >>= findAttrByName ns "w" "w" >>= safeRead
+  pgMar <- findChildByName ns "w" "pgMar" sectElem
+  leftMargin <- findAttrByName ns "w" "left" pgMar >>= safeRead
+  rightMargin <- findAttrByName ns "w" "right" pgMar >>= safeRead
+  gutter <- findAttrByName ns "w" "gutter" pgMar >>= safeRead
+  return $ pgWidth - (leftMargin + rightMargin + gutter)
+
+elemToNotes :: NameSpaces -> Text -> Element -> Maybe (M.Map T.Text Element)
+elemToNotes ns notetype element
+  | isElem ns "w" (notetype <> "s") element =
+      let pairs = mapMaybe
+                  (\e -> findAttrByName ns "w" "id" e >>=
+                         (\a -> Just (a, e)))
+                  (findChildrenByName ns "w" notetype element)
+      in
+       Just $
+       M.fromList pairs
+elemToNotes _ _ _ = Nothing
+
+elemToComments :: NameSpaces -> Element -> M.Map T.Text Element
+elemToComments ns element
+  | isElem ns "w" "comments" element =
+      let pairs = mapMaybe
+                  (\e -> findAttrByName ns "w" "id" e >>=
+                         (\a -> Just (a, e)))
+                  (findChildrenByName ns "w" "comment" element)
+      in
+       M.fromList pairs
+elemToComments _ _ = M.empty
+
+
+---------------------------------------------
+---------------------------------------------
+
+elemToTblGrid :: NameSpaces -> Element -> D TblGrid
+elemToTblGrid ns element | isElem ns "w" "tblGrid" element = do
+  let cols = findChildrenByName ns "w" "gridCol" element
+  textWidth <- asks envTextWidth
+  -- space between cols is 10 twips, so we subtract this:
+  let totalWidth = textWidth - (10 * (length cols - 1))
+  let toFraction :: Int -> Double
+      toFraction x = fromIntegral x / fromIntegral totalWidth
+  let normalizeFractions xs =
+        case sum xs of
+          tot | tot > 1.0 -> map (/ tot) xs
+          _ -> xs
+  normalizeFractions <$>
+    mapD (\e -> maybeToD (findAttrByName ns "w" "w" e >>=
+                          fmap toFraction . safeRead)) cols
+elemToTblGrid _ _ = throwError WrongElem
+
+elemToTblLook :: NameSpaces -> Element -> D TblLook
+elemToTblLook ns element | isElem ns "w" "tblLook" element =
+  let firstRow = findAttrByName ns "w" "firstRow" element
+      val = findAttrByName ns "w" "val" element
+      firstRowFmt =
+        case firstRow of
+          Just "1" -> True
+          Just  _  -> False
+          Nothing -> case val of
+            Just bitMask -> testBitMask bitMask 0x020
+            Nothing      -> False
+  in
+   return TblLook{firstRowFormatting = firstRowFmt}
+elemToTblLook _ _ = throwError WrongElem
+
+elemToRow :: NameSpaces -> Element -> D Row
+elemToRow ns element | isElem ns "w" "tr" element =
+  do
+    let properties = findChildByName ns "w" "trPr" element
+    let gridBefore = properties
+                     >>= findChildByName ns "w" "gridBefore"
+                     >>= findAttrByName ns "w" "val"
+                     >>= stringToInteger
+    let cellElems = findChildrenByName ns "w" "tc" element
+    let beforeCells = genericReplicate (fromMaybe 0 gridBefore) emptyCell
+    cells <- mapD (elemToCell ns) cellElems
+    let hasTblHeader =
+          case (properties >>= findChildByName ns "w" "tblHeader") of
+            Nothing -> NoTblHeader
+            Just he -> case findAttrByName ns "w" "val" he of
+              Just "0" -> NoTblHeader
+              _ -> HasTblHeader
+    return $ Row hasTblHeader (beforeCells ++ cells)
+elemToRow _ _ = throwError WrongElem
+
+elemToCell :: NameSpaces -> Element -> D Cell
+elemToCell ns element | isElem ns "w" "tc" element =
+  do
+    let properties = findChildByName ns "w" "tcPr" element
+    let gridSpan = properties
+                     >>= findChildByName ns "w" "gridSpan"
+                     >>= findAttrByName ns "w" "val"
+                     >>= stringToInteger
+    let vMerge = case properties >>= findChildByName ns "w" "vMerge" of
+                   Nothing -> Restart
+                   Just e ->
+                     fromMaybe Continue $ do
+                       s <- findAttrByName ns "w" "val" e
+                       case s of
+                         "continue" -> Just Continue
+                         "restart" -> Just Restart
+                         _ -> Nothing
+    cellContents <- mapD (elemToBodyPart ns) (elChildren element)
+    let align = case cellContents of -- take alignment from first paragraph
+                  Paragraph pstyle _ : _ ->
+                    case justification pstyle of
+                      Just JustifyBoth -> AlignLeft
+                      Just JustifyLeft -> AlignLeft
+                      Just JustifyRight -> AlignRight
+                      Just JustifyCenter -> AlignCenter
+                      Nothing -> AlignDefault
+                  _ -> AlignDefault
+    return $ Cell align (fromMaybe 1 gridSpan) vMerge cellContents
+elemToCell _ _ = throwError WrongElem
+
+testBitMask :: Text -> Int -> Bool
+testBitMask bitMaskS n =
+  case (reads ("0x" ++ T.unpack bitMaskS) :: [(Int, String)]) of
+    []            -> False
+    ((n', _) : _) -> (n' .&. n) /= 0
+
+pHeading :: ParagraphStyle -> Maybe (ParaStyleName, Int)
+pHeading = getParStyleField headingLev . pStyle
+
+pNumInfo :: ParagraphStyle -> Maybe (T.Text, T.Text)
+pNumInfo = getParStyleField numInfo . pStyle
+
+mkListItem :: ParagraphStyle -> Text -> Text -> [ParPart] -> D BodyPart
+mkListItem parstyle numId lvl parparts = do
+  lvlInfo <- lookupLevel numId lvl <$> asks envNumbering
+  return $ ListItem parstyle numId lvl lvlInfo parparts
+
+pStyleIndentation :: ParagraphStyle -> Maybe ParIndentation
+pStyleIndentation style = (getParStyleField indent . pStyle) style
+
+addCaptioned :: [BodyPart] -> [BodyPart]
+addCaptioned [] = []
+addCaptioned (Paragraph parstyle parparts : x : xs)
+  | hasCaptionStyle parstyle
+  , isCaptionable x
+    = Captioned parstyle parparts x : addCaptioned xs
+addCaptioned (x : Paragraph parstyle parparts : xs)
+  | hasCaptionStyle parstyle
+  , not (pKeepNext parstyle)
+  , isCaptionable x
+    = Captioned parstyle parparts x : addCaptioned xs
+addCaptioned (x:xs) = x : addCaptioned xs
+
+-- Split paragraphs that contain both a Drawing and text into two body parts,
+-- so that the captioning logic can combine them.
+splitMixedParagraphs :: [BodyPart] -> [BodyPart]
+splitMixedParagraphs [] = []
+splitMixedParagraphs (Paragraph ps parts : rest)
+  | (drawings@(_:_), texts@(_:_)) <- partition isDrawingPart parts
+  = Paragraph ps drawings : Paragraph ps texts : splitMixedParagraphs rest
+  where isDrawingPart Drawing{} = True
+        isDrawingPart _         = False
+splitMixedParagraphs (x:xs) = x : splitMixedParagraphs xs
+
+-- For textbox-image groups: combine image + any adjacent text into Captioned
+addSplitGroupCaptioned :: [BodyPart] -> [BodyPart]
+addSplitGroupCaptioned [] = []
+addSplitGroupCaptioned (Paragraph parstyle parparts : x : xs)
+  | isCaptionable x
+  = Captioned parstyle parparts x : addSplitGroupCaptioned xs
+addSplitGroupCaptioned (x : Paragraph parstyle parparts : xs)
+  | isCaptionable x
+  = Captioned parstyle parparts x : addSplitGroupCaptioned xs
+addSplitGroupCaptioned (x:xs) = x : addSplitGroupCaptioned xs
+
+isCaptionable :: BodyPart -> Bool
+isCaptionable (Paragraph _ [Drawing{}]) = True
+isCaptionable (Tbl{}) = True
+isCaptionable _ = False
+
+elemToBodyPart :: NameSpaces -> Element -> D BodyPart
+elemToBodyPart ns element
+  | isElem ns "m" "oMathPara" element = do
+      expsLst <- eitherToD $ readOMML $ showElement element
+      parstyle <- elemToParagraphStyle ns element
+                  <$> asks envParStyles
+                  <*> asks envNumbering
+      return $ Paragraph parstyle [OMathPara expsLst]
+elemToBodyPart ns element
+  | isElem ns "w" "p" element
+  , Just (numId, lvl) <- getNumInfo ns element = do
+    lvlInfo <- lookupLevel numId lvl <$> asks envNumbering
+    parstyle <- elemToParagraphStyle ns element
+                <$> asks envParStyles
+                <*> asks envNumbering
+    parparts <- mconcat <$> mapD (elemToParPart ns) (elChildren element)
+    case pHeading parstyle of
+      Nothing -> mkListItem parstyle numId lvl parparts
+      Just (parstylename, lev)
+        -> return $ Heading lev parstylename parstyle numId lvl lvlInfo parparts
+elemToBodyPart ns element
+  | isElem ns "w" "p" element
+  , [Elem ppr] <- elContent element
+  , isElem ns "w" "pPr" ppr
+  , [Elem pbdr] <- elContent ppr
+  , isElem ns "w" "pBdr" pbdr
+    = return HRule
+      -- for this style of horizontal rule, see
+      -- https://support.microsoft.com/en-us/office/insert-a-horizontal-line-9bf172f6-5908-4791-9bb9-2c952197b1a9
+elemToBodyPart ns element -- pandoc-style horizontal rule
+  | isElem ns "w" "p" element
+  , [Elem r] <- elContent element
+  , isElem ns "w" "r" r
+  , [Elem pict] <- elContent r
+  , isElem ns "w" "pict" pict
+  , [Elem rect] <- elContent pict
+  , isElem ns "v" "rect" rect
+    = return HRule
+elemToBodyPart ns element
+  | isElem ns "w" "p" element = do
+      parstyle <- elemToParagraphStyle ns element
+                  <$> asks envParStyles
+                  <*> asks envNumbering
+
+      let children =
+            (if hasCaptionStyle parstyle
+                then stripCaptionLabel
+                else id) (elChildren element)
+
+      parparts' <- mconcat <$> mapD (elemToParPart ns) children
+      fldCharState <- gets stateFldCharState
+      modify $ \st -> st {stateFldCharState = emptyFldCharContents fldCharState}
+      -- Word uses list enumeration for numbered headings, so we only
+      -- want to infer a list from the styles if it is NOT a heading.
+      let parparts = parparts' ++ openFldCharsToParParts fldCharState
+      case pHeading parstyle of
+        Nothing | Just (numId, lvl) <- pNumInfo parstyle -> do
+                    mkListItem parstyle numId lvl parparts
+        Just (parstylename, lev) -> do
+          let (numId, lvl) = fromMaybe ("","") $ pNumInfo parstyle
+          lvlInfo <- lookupLevel numId lvl <$> asks envNumbering
+          return $ Heading lev parstylename parstyle numId lvl lvlInfo parparts
+        Nothing -> return $ Paragraph parstyle parparts
+elemToBodyPart ns element
+  | isElem ns "w" "tbl" element = do
+    let tblProperties = findChildByName ns "w" "tblPr" element
+        caption = fromMaybe "" $ tblProperties
+                   >>= findChildByName ns "w" "tblCaption"
+                   >>= findAttrByName ns "w" "val"
+        description = fromMaybe "" $ tblProperties
+                       >>= findChildByName ns "w" "tblDescription"
+                       >>= findAttrByName ns "w" "val"
+        mbstyle = tblProperties
+                       >>= findChildByName ns "w" "tblStyle"
+                       >>= findAttrByName ns "w" "val"
+        grid' = case findChildByName ns "w" "tblGrid" element of
+          Just g  -> elemToTblGrid ns g
+          Nothing -> return []
+        tblLook' = case findChildByName ns "w" "tblPr" element >>=
+                          findChildByName ns "w" "tblLook"
+                     of
+                       Just l  -> elemToTblLook ns l
+                       Nothing -> return defaultTblLook
+
+    grid'' <- grid'
+    tblLook <- tblLook'
+    rows <- mapD (elemToRow ns) (elChildren element)
+    let grid = if null grid''
+                  then let numcols = case rowsToRowspans rows of
+                                       (cs@(_:_):_) -> sum (map fst cs)
+                                       _ -> 0
+                       in replicate numcols 0.0
+                  else grid''
+    return $ Tbl mbstyle (caption <> description) grid tblLook rows
+elemToBodyPart _ _ = throwError WrongElem
+
+lookupRelationship :: DocumentLocation -> RelId -> [Relationship] -> Maybe Target
+lookupRelationship docLocation relid rels =
+  lookup (docLocation, relid) pairs
+  where
+    pairs = map (\(Relationship loc relid' target) -> ((loc, relid'), target)) rels
+
+openFldCharsToParParts :: [FldCharState] -> [ParPart]
+openFldCharsToParParts [] = []
+openFldCharsToParParts (FldCharContent info children : ancestors) = case openFldCharsToParParts ancestors of
+  Field parentInfo siblings : _ -> [Field parentInfo $ siblings ++ [Field info $ reverse children]]
+  _ -> [Field info $ reverse children]
+openFldCharsToParParts (_ : ancestors) = openFldCharsToParParts ancestors
+
+emptyFldCharContents :: [FldCharState] -> [FldCharState]
+emptyFldCharContents = map
+  (\x -> case x of
+    FldCharContent info _ -> FldCharContent info []
+    _ -> x)
+
+expandDrawingId :: T.Text -> D (FilePath, B.ByteString)
+expandDrawingId s = do
+  location <- asks envLocation
+  target <- asks (fmap T.unpack . lookupRelationship location s . envRelationships)
+  case target of
+    Just filepath -> do
+      media <- asks envMedia
+      -- the mediaName is the name we store it under in the mediabag.
+      -- This is derived from the path, which might be absolute, e.g. /media/foo.jpg,
+      -- or relative, media/foo.jpg (interpreted as /word/media/foo.jpg).
+      -- The mediaName will strip off any leading `/` or `word/`.
+      -- We assume here that the media will not be stored *both* in
+      -- /media and in /word/media, which would lead to a name conflict
+      -- given the scheme here for generating a mediaName.
+      let (filepath', mediaName) =
+            case filepath of
+               ('/':rest)  -- absolute path e.g. /media/foo.jpg
+                  -> (rest, case stripPrefix "word/" rest of
+                              Just rest' -> rest'
+                              Nothing -> rest)
+               _  -- rel path to word, e.g. media/foo.jpg
+                 -> ("word/" ++ filepath, filepath)
+      case lookup filepath' media of
+        Just bs -> return (mediaName, bs)
+        Nothing -> throwError DocxError
+    Nothing -> throwError DocxError
+
+getTitleAndAlt :: NameSpaces -> Element -> (T.Text, T.Text)
+getTitleAndAlt ns element =
+  let mbDocPr = (findChildByName ns "wp" "inline" element <|>   -- Word
+                 findChildByName ns "wp" "anchor" element) >>=  -- LibreOffice
+                findChildByName ns "wp" "docPr"
+      title = fromMaybe "" (mbDocPr >>= findAttrByName ns "" "title")
+      alt = fromMaybe "" (mbDocPr >>= findAttrByName ns "" "descr")
+  in (title, alt)
+
+elemToParPart :: NameSpaces -> Element -> D [ParPart]
+{-
+The next one is a bit complicated. fldChar fields work by first
+having a <w:fldChar fldCharType="begin"> in a run, then a run with
+<w:instrText>, then a <w:fldChar fldCharType="separate"> run, then the
+content runs, and finally a <w:fldChar fldCharType="end"> run. For
+example (omissions and my comments in brackets):
+
+      <w:r>
+        [...]
+        <w:fldChar w:fldCharType="begin"/>
+      </w:r>
+      <w:r>
+        [...]
+        <w:instrText xml:space="preserve"> HYPERLINK [hyperlink url] </w:instrText>
+      </w:r>
+      <w:r>
+        [...]
+        <w:fldChar w:fldCharType="separate"/>
+      </w:r>
+      <w:r w:rsidRPr=[...]>
+        [...]
+        <w:t>Foundations of Analysis, 2nd Edition</w:t>
+      </w:r>
+      <w:r>
+        [...]
+        <w:fldChar w:fldCharType="end"/>
+      </w:r>
+
+Note that there may be mulitple w:instrText elements in a row.
+For example, you might first have ` XE "`, then `Kay, Alan`, then `"`.
+The texts in all of them should be concatenated before it is processed!
+
+So we do this in a number of steps. If we encounter the fldchar begin
+tag, we start open a fldchar state variable (see state above). We add
+the instrtext to it as FieldInfo. Then we close that and start adding
+the children when we get to separate. Then when we get to end, we produce
+the Field type with appropriate FieldInfo and ParParts.
+
+Since there can be nested fields, the fldchar state needs to be a stack,
+so we can have multiple fldchars open at the same time. When a fldchar is
+closed, we either add the resulting field to its parent or we return it if
+there is no parent.
+-}
+elemToParPart ns element
+  | isElem ns "w" "r" element
+  , Just fldChar <- findChildByName ns "w" "fldChar" element
+  , Just fldCharType <- findAttrByName ns "w" "fldCharType" fldChar = do
+      fldCharState <- gets stateFldCharState
+      case fldCharState of
+        _ | fldCharType == "begin" -> do
+          modify $ \st -> st {stateFldCharState = FldCharOpen : fldCharState}
+          return []
+        FldCharFieldInfo t : ancestors | fldCharType == "separate" -> do
+          info <- eitherToD $ parseFieldInfo t
+          modify $ \st -> st {stateFldCharState = FldCharContent info [] : ancestors}
+          return []
+        -- Some fields have no content, e.g. index XE:
+        FldCharFieldInfo t : ancestors | fldCharType == "end" -> do
+          modify $ \st -> st {stateFldCharState = ancestors}
+          info <- eitherToD $ parseFieldInfo t
+          return [Field info []]
+        [FldCharContent info children] | fldCharType == "end" -> do
+          modify $ \st -> st {stateFldCharState = []}
+          return [Field info $ reverse children]
+        FldCharContent info children : FldCharContent parentInfo siblings : ancestors | fldCharType == "end" ->
+          let parent = FldCharContent parentInfo $ (Field info (reverse children)) : siblings in do
+            modify $ \st -> st {stateFldCharState = parent : ancestors}
+            return []
+        _ -> throwError WrongElem
+elemToParPart ns element
+  | isElem ns "w" "r" element
+  , Just instrText <- findChildByName ns "w" "instrText" element = do
+      fldCharState <- gets stateFldCharState
+      case fldCharState of
+        FldCharOpen : ancestors -> do
+          modify $ \st -> st {stateFldCharState =
+                               FldCharFieldInfo (strContent instrText) : ancestors}
+          return []
+        FldCharFieldInfo t : ancestors -> do
+          modify $ \st -> st {stateFldCharState =
+                               FldCharFieldInfo (t <> strContent instrText) :
+                                ancestors}
+          return []
+        _ -> return []
+{-
+There is an open fldchar, so we calculate the element and add it to the
+children. For this we need to first change the fldchar state to an empty
+stack to avoid descendants of children simply being added to the state instead
+of to their direct parent element. This would happen in the case of a
+w:hyperlink element for example.
+-}
+elemToParPart ns element = do
+  fldCharState <- gets stateFldCharState
+  case fldCharState of
+    FldCharContent info children : ancestors -> do
+      modify $ \st -> st {stateFldCharState = []}
+      parParts <- elemToParPart' ns element `catchError` \_ -> return []
+      modify $ \st -> st{stateFldCharState = FldCharContent info (parParts ++ children) : ancestors}
+      return []
+    _ -> elemToParPart' ns element
+
+elemToParPart' :: NameSpaces -> Element -> D [ParPart]
+elemToParPart' ns element
+  | isElem ns "w" "r" element
+  , Just drawingElem <- findChildByName ns "w" "drawing" element
+  , picElems <- filterElementsName
+                 (matchQName "drawingml" "picture" (Just "pic") "pic") drawingElem
+  = let (title, alt) = getTitleAndAlt ns drawingElem
+        drawings = map (\el ->
+                        ((findBlip el >>= findAttrByName ns "r" "embed"), el))
+                       picElems
+    in mapM (\case
+                (Just s, el) -> do
+                  (fp, bs) <- expandDrawingId s
+                  let extent = elemToExtent el <|> elemToExtent element
+                  return $ Drawing fp title alt bs extent
+                (Nothing, _) -> throwError WrongElem)
+            drawings
+-- The two cases below are an attempt to deal with images in deprecated vml format.
+-- Todo: check out title and attr for deprecated format.
+elemToParPart' ns element
+  | isElem ns "w" "r" element
+  , Just _ <- findChildByName ns "w" "pict" element =
+    let drawing = findElement (elemName ns "v" "imagedata") element
+                  >>= findAttrByName ns "r" "id"
+    in
+     case drawing of
+       Just s -> expandDrawingId s >>= (\(fp, bs) -> return [Drawing fp "" "" bs Nothing])
+       Nothing -> throwError WrongElem
+elemToParPart' ns element
+  | isElem ns "w" "r" element
+  , Just objectElem <- findChildByName ns "w" "object" element
+  , Just shapeElem <- findChildByName ns "v" "shape" objectElem
+  , Just imagedataElem <- findChildByName ns "v" "imagedata" shapeElem
+  , Just drawingId <- findAttrByName ns "r" "id" imagedataElem
+  = expandDrawingId drawingId >>= (\(fp, bs) -> return [Drawing fp "" "" bs Nothing])
+-- Diagram
+elemToParPart' ns element
+  | isElem ns "w" "r" element
+  , Just drawingElem <- findChildByName ns "w" "drawing" element
+  , Just _ <- filterElementName
+                 (matchQName "drawingml" "diagram" (Just "dgm") "relIds") drawingElem
+  = return [Diagram]
+-- Chart
+elemToParPart' ns element
+  | isElem ns "w" "r" element
+  , Just drawingElem <- findChildByName ns "w" "drawing" element
+  , Just _ <- filterElementName
+                (matchQName "drawingml" "chart" (Just "c") "chart") drawingElem
+  = return [Chart]
+elemToParPart' ns element
+  | isElem ns "w" "r" element = do
+    runs <- elemToRun ns element
+    return $ map PlainRun runs
+elemToParPart' ns element
+  | Just change <- getTrackedChange ns element = do
+      runs <- mconcat <$> mapD (elemToParPart' ns) (elChildren element)
+      return [ChangedRuns change runs]
+elemToParPart' ns element
+  | isElem ns "w" "bookmarkStart" element
+  , Just bmId <- findAttrByName ns "w" "id" element
+  , Just bmName <- findAttrByName ns "w" "name" element =
+    return [BookMark bmId bmName]
+elemToParPart' ns element
+  | isElem ns "w" "hyperlink" element
+  , Just relId <- findAttrByName ns "r" "id" element = do
+    location <- asks envLocation
+    children <- mconcat <$> mapD (elemToParPart ns) (elChildren element)
+    rels <- asks envRelationships
+    case lookupRelationship location relId rels of
+      Just target ->
+         case findAttrByName ns "w" "anchor" element of
+             Just anchor -> return
+               [ExternalHyperLink (target <> "#" <> anchor) children]
+             Nothing -> return [ExternalHyperLink target children]
+      Nothing     -> return [ExternalHyperLink "" children]
+elemToParPart' ns element
+  | isElem ns "w" "hyperlink" element
+  , Just anchor <- findAttrByName ns "w" "anchor" element = do
+    children <- mconcat <$> mapD (elemToParPart ns) (elChildren element)
+    return [InternalHyperLink anchor children]
+elemToParPart' ns element
+  | isElem ns "w" "commentRangeStart" element
+  , Just cmtId <- findAttrByName ns "w" "id" element = do
+      (Comments _ commentMap) <- asks envComments
+      case M.lookup cmtId commentMap of
+        Just cmtElem -> elemToCommentStart ns cmtElem
+        Nothing      -> throwError WrongElem
+elemToParPart' ns element
+  | isElem ns "w" "commentRangeEnd" element
+  , Just cmtId <- findAttrByName ns "w" "id" element =
+    return [CommentEnd cmtId]
+elemToParPart' ns element
+  | isElem ns "m" "oMath" element =
+    fmap (return . PlainOMath) (eitherToD $ readOMML $ showElement element)
+elemToParPart' ns element
+  | isElem ns "m" "oMathPara" element =
+    fmap (return . OMathPara) (eitherToD $ readOMML $ showElement element)
+elemToParPart' _ _ = throwError WrongElem
+
+elemToCommentStart :: NameSpaces -> Element -> D [ParPart]
+elemToCommentStart ns element
+  | isElem ns "w" "comment" element
+  , Just cmtId <- findAttrByName ns "w" "id" element
+  , Just cmtAuthor <- findAttrByName ns "w" "author" element
+  , cmtDate <- findAttrByName ns "w" "date" element = do
+      bps <- mapD (elemToBodyPart ns) (elChildren element)
+      return [CommentStart cmtId cmtAuthor cmtDate bps]
+elemToCommentStart _ _ = throwError WrongElem
+
+lookupFootnote :: T.Text -> Notes -> Maybe Element
+lookupFootnote s (Notes _ fns _) = fns >>= M.lookup s
+
+lookupEndnote :: T.Text -> Notes -> Maybe Element
+lookupEndnote s (Notes _ _ ens) = ens >>= M.lookup s
+
+elemToExtent :: Element -> Extent
+elemToExtent el =
+  case (getDim "cx", getDim "cy") of
+    (Just w, Just h) -> Just (w, h)
+    _                -> Nothing
+ where
+  getDim at = filterElementName (\n -> qName n == "extent") el
+              >>= findAttr (QName at Nothing Nothing) >>= safeRead
+
+
+childElemToRun :: NameSpaces -> Element -> D [Run]
+childElemToRun ns element
+  | isElem ns "w" "drawing" element
+  , picElems <- filterElementsName
+                 (matchQName "drawingml" "picture" (Just "pic") "pic") element
+  = let (title, alt) = getTitleAndAlt ns element
+        drawings = map (\el ->
+                         ((findBlip el >>= findAttrByName ns "r" "embed"), el))
+                   picElems
+    in mapM (\case
+                (Just s, el) -> do
+                  (fp, bs) <- expandDrawingId s
+                  let extent = elemToExtent el <|> elemToExtent element
+                  return $ InlineDrawing fp title alt bs extent
+                (Nothing, _) -> throwError WrongElem)
+       drawings
+childElemToRun ns element
+  | isElem ns "w" "drawing" element
+  , Just _ <- filterElementName
+                 (matchQName "drawingml" "chart" (Just "c") "chart") element
+  = return [InlineChart]
+childElemToRun ns element
+  | isElem ns "w" "drawing" element
+  , Just _ <- filterElementName
+                 (matchQName "drawingml" "diagram" (Just "dgm") "relIds") element
+  = return [InlineDiagram]
+childElemToRun ns element
+  | isElem ns "w" "footnoteReference" element
+  , Just fnId <- findAttrByName ns "w" "id" element = do
+    notes <- asks envNotes
+    case lookupFootnote fnId notes of
+      Just e -> do bps <- local (\r -> r {envLocation=InFootnote}) $ mapD (elemToBodyPart ns) (elChildren e)
+                   return [Footnote bps]
+      Nothing  -> return [Footnote []]
+childElemToRun ns element
+  | isElem ns "w" "endnoteReference" element
+  , Just enId <- findAttrByName ns "w" "id" element = do
+    notes <- asks envNotes
+    case lookupEndnote enId notes of
+      Just e -> do bps <- local (\r -> r {envLocation=InEndnote}) $ mapD (elemToBodyPart ns) (elChildren e)
+                   return [Endnote bps]
+      Nothing  -> return [Endnote []]
+childElemToRun _ _ = throwError WrongElem
+
+elemToRun :: NameSpaces -> Element -> D [Run]
+elemToRun ns element
+  | isElem ns "w" "r" element
+  , Just drawingElem <- findChildByName ns "w" "drawing" element =
+    childElemToRun ns drawingElem
+elemToRun ns element
+  | isElem ns "w" "r" element
+  , Just ref <- findChildByName ns "w" "footnoteReference" element =
+    childElemToRun ns ref
+elemToRun ns element
+  | isElem ns "w" "r" element
+  , Just ref <- findChildByName ns "w" "endnoteReference" element =
+    childElemToRun ns ref
+elemToRun ns element
+  | isElem ns "w" "r" element = do
+    runElems <- elemToRunElems ns element
+    runStyle <- elemToRunStyleD ns element
+    return [Run runStyle runElems]
+elemToRun _ _ = throwError WrongElem
+
+getParentStyleValue :: (ParStyle -> Maybe a) -> ParStyle -> Maybe a
+getParentStyleValue field style
+  | Just value <- field style = Just value
+  | Just parentStyle <- psParentStyle style
+                      = getParentStyleValue field parentStyle
+getParentStyleValue _ _ = Nothing
+
+getParStyleField :: (ParStyle -> Maybe a) -> [ParStyle] -> Maybe a
+getParStyleField field styles
+  | (y:_) <- mapMaybe (getParentStyleValue field) styles
+           = Just y
+getParStyleField _ _ = Nothing
+
+getTrackedChange :: NameSpaces -> Element -> Maybe TrackedChange
+getTrackedChange ns element
+  | isElem ns "w" "ins" element || isElem ns "w" "moveTo" element
+  , Just cId <- findAttrByName ns "w" "id" element
+  , Just cAuthor <- findAttrByName ns "w" "author" element
+  , mcDate <- findAttrByName ns "w" "date" element =
+      Just $ TrackedChange Insertion (ChangeInfo cId cAuthor mcDate)
+getTrackedChange ns element
+  | isElem ns "w" "del" element || isElem ns "w" "moveFrom" element
+  , Just cId <- findAttrByName ns "w" "id" element
+  , Just cAuthor <- findAttrByName ns "w" "author" element
+  , mcDate <- findAttrByName ns "w" "date" element =
+      Just $ TrackedChange Deletion (ChangeInfo cId cAuthor mcDate)
+getTrackedChange _ _ = Nothing
+
+elemToParagraphStyle :: NameSpaces -> Element
+                     -> ParStyleMap
+                     -> Numbering
+                     -> ParagraphStyle
+elemToParagraphStyle ns element sty numbering
+  | Just pPr <- findChildByName ns "w" "pPr" element =
+    let style =
+          mapMaybe
+          (fmap ParaStyleId . findAttrByName ns "w" "val")
+          (findChildrenByName ns "w" "pStyle" pPr)
+        pStyle' = mapMaybe (`M.lookup` sty) style
+    in ParagraphStyle
+      {pStyle = pStyle'
+      , numbered = case getNumInfo ns element of
+          Just (numId, lvl) -> isJust $ lookupLevel numId lvl numbering
+          Nothing -> isJust $ getParStyleField numInfo pStyle'
+      , justification =
+          case findChildByName ns "w" "jc" pPr >>= findAttrByName ns "w" "val" of
+            Nothing -> Nothing
+            Just "both" -> Just JustifyBoth
+            Just "center" -> Just JustifyCenter
+            Just "left" -> Just JustifyLeft
+            Just "right" -> Just JustifyRight
+            _ -> Nothing
+      , indentation =
+          getIndentation ns element
+      , dropCap =
+          case
+            findChildByName ns "w" "framePr" pPr >>=
+            findAttrByName ns "w" "dropCap"
+          of
+            Just "none" -> False
+            Just _      -> True
+            Nothing     -> False
+      , pChange     = findChildByName ns "w" "rPr" pPr >>=
+                      filterChild (\e -> isElem ns "w" "ins" e ||
+                                         isElem ns "w" "moveTo" e ||
+                                         isElem ns "w" "del" e ||
+                                         isElem ns "w" "moveFrom" e
+                                  ) >>=
+                      getTrackedChange ns
+      , pBidi = checkOnOff ns pPr (elemName ns "w" "bidi")
+      , pKeepNext = isJust $ findChildByName ns "w" "keepNext" pPr
+      }
+  | otherwise = defaultParagraphStyle
+
+elemToRunStyleD :: NameSpaces -> Element -> D RunStyle
+elemToRunStyleD ns element
+  | Just rPr <- findChildByName ns "w" "rPr" element = do
+    charStyles <- asks envCharStyles
+    let parentSty =
+          findChildByName ns "w" "rStyle" rPr >>=
+          findAttrByName ns "w" "val" >>=
+          flip M.lookup charStyles . CharStyleId
+    return $ elemToRunStyle ns element parentSty
+elemToRunStyleD _ _ = return defaultRunStyle
+
+elemToRunElem :: NameSpaces -> Element -> D RunElem
+elemToRunElem ns element
+  | isElem ns "w" "t" element
+    || isElem ns "w" "delText" element
+    || isElem ns "m" "t" element = do
+    let str = strContent element
+    font <- asks envFont
+    case font of
+      Nothing -> return $ TextRun str
+      Just f  -> return . TextRun $
+                   T.map (\c -> fromMaybe c (getFontChar f c)) str
+  | isElem ns "w" "br" element = return LnBrk
+  | isElem ns "w" "tab" element = return Tab
+  | isElem ns "w" "softHyphen" element = return SoftHyphen
+  | isElem ns "w" "noBreakHyphen" element = return NoBreakHyphen
+  | isElem ns "w" "sym" element = return (getSymChar ns element)
+  | otherwise = throwError WrongElem
+
+-- The char attribute is a hex string
+getSymChar :: NameSpaces -> Element -> RunElem
+getSymChar ns element
+  | Just s <- getCodepoint
+  , Just font <- getFont =
+    case readLitChar ("\\x" ++ T.unpack s) of
+         [(ch, _)] ->
+              TextRun $ T.singleton $ fromMaybe ch $ getFontChar font ch
+         _ -> TextRun ""
+  where
+    getCodepoint = findAttrByName ns "w" "char" element
+    getFont = findAttrByName ns "w" "font" element >>= textToFont
+getSymChar _ _ = TextRun ""
+
+getFontChar :: Font -> Char -> Maybe Char
+getFontChar font ch = chr <$> M.lookup (font, point) symbolMap
+ where
+   point  -- sometimes F000 is added to put char in private range:
+      | ch >= '\xF000' = ord ch - 0xF000
+      | otherwise = ord ch
+
+elemToRunElems :: NameSpaces -> Element -> D [RunElem]
+elemToRunElems ns element
+  |  isElem ns "w" "r" element
+     || isElem ns "m" "r" element = do
+       let qualName = elemName ns "w"
+       let font = do
+                    fontElem <- findElement (qualName "rFonts") element
+                    foldr ((<|>) . (flip findAttr fontElem . qualName))
+                         Nothing ["ascii", "hAnsi"]
+                      >>= textToFont
+       local (setFont font) (mapD (elemToRunElem ns) (elChildren element))
+elemToRunElems _ _ = throwError WrongElem
+
+setFont :: Maybe Font -> ReaderEnv -> ReaderEnv
+setFont f s = s{envFont = f}
+
+findBlip :: Element -> Maybe Element
+findBlip el = do
+  blip <- filterElementName (matchQName "drawingml" "main" (Just "a") "blip") el
+  -- return svg if present:
+  filterElementName (\(QName tag _ _) -> tag == "svgBlip") el `mplus` pure blip
+
+-- | Checks if any style in the style hierarchy is a caption style.
+hasCaptionStyle :: ParagraphStyle -> Bool
+hasCaptionStyle =
+  any (isCaptionStyleName . pStyleName) . concatMap nestedStyles . pStyle
+ where -- note that these are case insensitive:
+   isCaptionStyleName "caption" = True
+   isCaptionStyleName "table caption" = True
+   isCaptionStyleName "image caption" = True
+   isCaptionStyleName _ = False
+
+   -- Gets all the style names in the style hierarchy
+   nestedStyles :: ParStyle -> [ParStyle]
+   nestedStyles ps = ps : maybe [] nestedStyles (psParentStyle ps)
+
+stripCaptionLabel :: [Element] -> [Element]
+stripCaptionLabel els =
+  if any isNumberElt els
+     then dropWhile (not . isNumberElt) els
+     else els
+  where
+    isNumberElt el@(Element name attribs _ _) =
+       (qName name == "fldSimple" &&
+             case lookupAttrBy ((== "instr") . qName) attribs of
+               Nothing -> False
+               Just instr -> "Table" `elem` T.words instr ||
+                             "Figure" `elem` T.words instr) ||
+       (qName name == "instrText" &&
+          let ws = T.words (strContent el)
+          in  ("Table" `elem` ws || "Figure" `elem` ws))
+
+isNamespace :: Text -> Text -> Text -> Bool
+isNamespace primary secondary url =
+  -- first try transitional:
+  case T.stripPrefix "http://schemas.openxmlformats.org/" url of
+    Just path -> path == primary <> "/2006/" <> secondary
+    Nothing -> -- then try strict:
+      case T.stripPrefix "http://purl.oclc.org/ooxml/" url of
+        Just path -> path == primary <> "/" <> snakeToCamel secondary
+        Nothing -> False
+ where
+   snakeToCamel "custom-properties" = "customProperties"
+   snakeToCamel "extended-properties" = "extendedProperties"
+   snakeToCamel x = x
+
+matchQName :: Text -> Text -> Maybe Text -> Text -> QName -> Bool
+matchQName primary secondary mbprefix name (QName name' mbns' mbprefix') =
+  name == name' &&
+  (isNothing mbprefix || mbprefix' == mbprefix) &&
+  maybe True (isNamespace primary secondary) mbns'
diff --git a/src/Text/Pandoc/Readers/Docx/Parse/Styles.hs b/src/Text/Pandoc/Readers/Docx/Parse/Styles.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Readers/Docx/Parse/Styles.hs
@@ -0,0 +1,352 @@
+{-# LANGUAGE FlexibleInstances #-}
+{-# LANGUAGE FlexibleContexts  #-}
+{-# LANGUAGE TypeFamilies      #-}
+{-# LANGUAGE GeneralizedNewtypeDeriving #-}
+{-# LANGUAGE OverloadedStrings #-}
+{- |
+ Module : Text.Pandoc.Readers.Docx.Parse.Styles
+ Copyright : Copyright (C) 2014-2020 Jesse Rosenthal
+                           2019 Nikolay Yakimov <root@livid.pp.ru>
+ License : GNU GPL, version 2 or above
+
+ Maintainer : Jesse Rosenthal <jrosenthal@jhu.edu>
+ Stability : alpha
+ Portability : portable
+
+Type machinery and code for extraction and manipulation of docx styles
+-}
+
+module Text.Pandoc.Readers.Docx.Parse.Styles (
+    CharStyleId(..)
+  , CharStyle
+  , ParaStyleId(..)
+  , ParStyle(..)
+  , ParIndentation(..)
+  , RunStyle(..)
+  , HasStyleName
+  , StyleName
+  , ParaStyleName
+  , CharStyleName
+  , FromStyleName
+  , VertAlign(..)
+  , StyleId
+  , HasStyleId
+  , archiveToStyles'
+  , getStyleId
+  , getStyleName
+  , cStyleData
+  , fromStyleName
+  , fromStyleId
+  , stringToInteger
+  , getIndentation
+  , getNumInfo
+  , elemToRunStyle
+  , defaultRunStyle
+  , checkOnOff
+  ) where
+import Codec.Archive.Zip
+import Control.Applicative ((<|>))
+import Data.Function (on)
+import Data.String (IsString(..))
+import qualified Data.Map as M
+import qualified Data.Text as T
+import qualified Data.Text.Read
+import Data.Text (Text)
+import Data.Maybe
+import Data.Coerce
+import Text.Pandoc.Readers.Docx.Util
+import qualified Text.Pandoc.UTF8 as UTF8
+import Text.Pandoc.XML.Light
+
+newtype CharStyleId   = CharStyleId T.Text
+  deriving (Show, Eq, Ord, IsString, FromStyleId)
+newtype ParaStyleId   = ParaStyleId T.Text
+  deriving (Show, Eq, Ord, IsString, FromStyleId)
+
+newtype CharStyleName = CharStyleName CIString
+  deriving (Show, Eq, Ord, IsString, FromStyleName)
+newtype ParaStyleName = ParaStyleName CIString
+  deriving (Show, Eq, Ord, IsString, FromStyleName)
+
+-- Case-insensitive comparisons
+newtype CIString = CIString T.Text deriving (Show, IsString, FromStyleName)
+
+class FromStyleName a where
+  fromStyleName :: a -> T.Text
+
+instance FromStyleName String where
+  fromStyleName = T.pack
+
+instance FromStyleName T.Text where
+  fromStyleName = id
+
+class FromStyleId a where
+  fromStyleId :: a -> T.Text
+
+instance FromStyleId String where
+  fromStyleId = T.pack
+
+instance FromStyleId T.Text where
+  fromStyleId = id
+
+instance Eq CIString where
+   (==) = (==) `on` T.toCaseFold . coerce
+
+instance Ord CIString where
+  compare = compare `on` T.toCaseFold . coerce
+
+data VertAlign = BaseLn | SupScrpt | SubScrpt
+               deriving Show
+
+data CharStyle = CharStyle { cStyleId   :: CharStyleId
+                           , cStyleName :: CharStyleName
+                           , cStyleData :: RunStyle
+                           } deriving (Show)
+
+data RunStyle = RunStyle { isBold       :: Maybe Bool
+                         , isBoldCTL    :: Maybe Bool
+                         , isItalic     :: Maybe Bool
+                         , isItalicCTL  :: Maybe Bool
+                         , isSmallCaps  :: Maybe Bool
+                         , isStrike     :: Maybe Bool
+                         , isRTL        :: Maybe Bool
+                         , isForceCTL   :: Maybe Bool
+                         , rHighlight   :: Maybe Text
+                         , rVertAlign   :: Maybe VertAlign
+                         , rUnderline   :: Maybe Text
+                         , rParentStyle :: Maybe CharStyle
+                         }
+                deriving Show
+
+data ParIndentation = ParIndentation { leftParIndent    :: Maybe Integer
+                                     , rightParIndent   :: Maybe Integer
+                                     , hangingParIndent :: Maybe Integer}
+                      deriving Show
+
+data ParStyle = ParStyle { headingLev    :: Maybe (ParaStyleName, Int)
+                         , indent        :: Maybe ParIndentation
+                         , numInfo       :: Maybe (T.Text, T.Text)
+                         , psParentStyle :: Maybe ParStyle
+                         , pStyleName    :: ParaStyleName
+                         , pStyleId      :: ParaStyleId
+                         }
+                    deriving Show
+
+defaultRunStyle :: RunStyle
+defaultRunStyle = RunStyle { isBold = Nothing
+                           , isBoldCTL = Nothing
+                           , isItalic = Nothing
+                           , isItalicCTL = Nothing
+                           , isSmallCaps = Nothing
+                           , isStrike = Nothing
+                           , isRTL = Nothing
+                           , isForceCTL = Nothing
+                           , rHighlight = Nothing
+                           , rVertAlign = Nothing
+                           , rUnderline = Nothing
+                           , rParentStyle = Nothing
+                           }
+
+archiveToStyles'
+  :: (Ord k1, Ord k2, ElemToStyle a1, ElemToStyle a2)
+  => (a1 -> k1) -> (a2 -> k2) -> Archive -> (M.Map k1 a1, M.Map k2 a2)
+archiveToStyles' conv1 conv2 zf =
+  case findEntryByPath "word/styles.xml" zf of
+    Nothing -> (M.empty, M.empty)
+    Just entry ->
+      case parseXMLElement . UTF8.toTextLazy . fromEntry $ entry of
+        Left _ -> (M.empty, M.empty)
+        Right styElem ->
+          let namespaces = elemToNameSpaces styElem
+          in
+           ( M.fromList $ map (\r -> (conv1 r, r)) $
+               buildBasedOnList namespaces styElem Nothing,
+             M.fromList $ map (\p -> (conv2 p, p)) $
+               buildBasedOnList namespaces styElem Nothing)
+
+isBasedOnStyle :: (ElemToStyle a, FromStyleId (StyleId a)) => NameSpaces -> Element -> Maybe a -> Bool
+isBasedOnStyle ns element parentStyle
+  | isElem ns "w" "style" element
+  , Just styleType <- findAttrByName ns "w" "type" element
+  , styleType == cStyleType parentStyle
+  , Just basedOnVal <- findChildByName ns "w" "basedOn" element >>=
+                       findAttrByName ns "w" "val"
+  , Just ps <- parentStyle = basedOnVal == fromStyleId (getStyleId ps)
+  | isElem ns "w" "style" element
+  , Just styleType <- findAttrByName ns "w" "type" element
+  , styleType == cStyleType parentStyle
+  , Nothing <- findChildByName ns "w" "basedOn" element
+  , Nothing <- parentStyle = True
+  | otherwise = False
+
+class HasStyleId a => ElemToStyle a where
+  cStyleType  :: Maybe a -> Text
+  elemToStyle :: NameSpaces -> Element -> Maybe a -> Maybe a
+
+class FromStyleId (StyleId a) => HasStyleId a where
+  type StyleId a
+  getStyleId :: a -> StyleId a
+
+class FromStyleName (StyleName a) => HasStyleName a where
+  type StyleName a
+  getStyleName :: a -> StyleName a
+
+instance ElemToStyle CharStyle where
+  cStyleType _ = "character"
+  elemToStyle ns element parentStyle
+    | isElem ns "w" "style" element
+    , Just "character" <- findAttrByName ns "w" "type" element =
+      elemToCharStyle ns element parentStyle
+    | otherwise = Nothing
+
+instance HasStyleId CharStyle where
+  type StyleId CharStyle = CharStyleId
+  getStyleId = cStyleId
+
+instance HasStyleName CharStyle where
+  type StyleName CharStyle = CharStyleName
+  getStyleName = cStyleName
+
+instance ElemToStyle ParStyle where
+  cStyleType _ = "paragraph"
+  elemToStyle ns element parentStyle
+    | isElem ns "w" "style" element
+    , Just "paragraph" <- findAttrByName ns "w" "type" element
+    = elemToParStyleData ns element parentStyle
+    | otherwise = Nothing
+
+instance HasStyleId ParStyle where
+  type StyleId ParStyle = ParaStyleId
+  getStyleId = pStyleId
+
+instance HasStyleName ParStyle where
+  type StyleName ParStyle = ParaStyleName
+  getStyleName = pStyleName
+
+getStyleChildren :: (ElemToStyle a) => NameSpaces -> Element -> Maybe a -> [a]
+getStyleChildren ns element parentStyle
+  | isElem ns "w" "styles" element =
+    mapMaybe (\e -> elemToStyle ns e parentStyle) $
+    filterChildren (\e' -> isBasedOnStyle ns e' parentStyle) element
+  | otherwise = []
+
+buildBasedOnList :: (ElemToStyle a) => NameSpaces -> Element -> Maybe a -> [a]
+buildBasedOnList ns element rootStyle =
+  case getStyleChildren ns element rootStyle of
+    [] -> []
+    stys -> stys ++
+            concatMap (buildBasedOnList ns element . Just) stys
+
+stringToInteger :: Text -> Maybe Integer
+stringToInteger s = case Data.Text.Read.decimal s of
+                      Right (x,t) | T.null t -> Just x
+                      _                      -> Nothing
+
+checkOnOff :: NameSpaces -> Element -> QName -> Maybe Bool
+checkOnOff ns rPr tag
+  | Just t <-  findChild tag rPr
+  , Just val <- findAttrByName ns "w" "val" t =
+    Just $ case val of
+      "true"  -> True
+      "false" -> False
+      "on"    -> True
+      "off"   -> False
+      "1"     -> True
+      "0"     -> False
+      _       -> False
+  | Just _ <- findChild tag rPr = Just True
+checkOnOff _ _ _ = Nothing
+
+elemToCharStyle :: NameSpaces
+                -> Element -> Maybe CharStyle -> Maybe CharStyle
+elemToCharStyle ns element parentStyle
+  = CharStyle <$> (CharStyleId <$> findAttrByName ns "w" "styleId" element)
+              <*> getElementStyleName ns element
+              <*> Just (elemToRunStyle ns element parentStyle)
+
+elemToRunStyle :: NameSpaces -> Element -> Maybe CharStyle -> RunStyle
+elemToRunStyle ns element parentStyle
+  | Just rPr <- findChildByName ns "w" "rPr" element =
+    RunStyle
+      {
+        isBold = checkOnOff ns rPr (elemName ns "w" "b")
+      , isBoldCTL = checkOnOff ns rPr (elemName ns "w" "bCs")
+      , isItalic = checkOnOff ns rPr (elemName ns "w" "i")
+      , isItalicCTL = checkOnOff ns rPr (elemName ns "w" "iCs")
+      , isSmallCaps = checkOnOff ns rPr (elemName ns "w" "smallCaps")
+      , isStrike = checkOnOff ns rPr (elemName ns "w" "strike")
+      , isRTL = checkOnOff ns rPr (elemName ns "w" "rtl")
+      , isForceCTL = checkOnOff ns rPr (elemName ns "w" "cs")
+      , rHighlight =
+          findChildByName ns "w" "highlight" rPr >>=
+            findAttrByName ns "w" "val"
+      , rVertAlign =
+           findChildByName ns "w" "vertAlign" rPr >>=
+           findAttrByName ns "w" "val" >>=
+           \v -> Just $ case v of
+             "superscript" -> SupScrpt
+             "subscript"   -> SubScrpt
+             _             -> BaseLn
+      , rUnderline =
+          findChildByName ns "w" "u" rPr >>=
+          findAttrByName ns "w" "val"
+      , rParentStyle = parentStyle
+      }
+elemToRunStyle _ _ _ = defaultRunStyle
+
+getHeaderLevel :: NameSpaces -> Element -> Maybe (ParaStyleName, Int)
+getHeaderLevel ns element
+  | Just styleName <- getElementStyleName ns element
+  , Just n <- stringToInteger =<<
+              (T.stripPrefix "heading " . T.toLower $
+                fromStyleName styleName)
+  , n > 0 = Just (styleName, fromInteger n)
+getHeaderLevel _ _ = Nothing
+
+getIndentation :: NameSpaces -> Element -> Maybe ParIndentation
+getIndentation ns el = do
+  indElement <- findChildByName ns "w" "pPr" el >>=
+                findChildByName ns "w" "ind"
+  return $ ParIndentation
+    {
+      leftParIndent = findAttrByName ns "w" "left" indElement <|>
+                      findAttrByName ns "w" "start" indElement >>=
+                      stringToInteger
+    , rightParIndent = findAttrByName ns "w" "right" indElement <|>
+                       findAttrByName ns "w" "end" indElement >>=
+                       stringToInteger
+    , hangingParIndent = findAttrByName ns "w" "hanging" indElement >>=
+                         stringToInteger
+    }
+
+getElementStyleName :: Coercible T.Text a => NameSpaces -> Element -> Maybe a
+getElementStyleName ns el = coerce <$>
+  ((findChildByName ns "w" "name" el >>= findAttrByName ns "w" "val")
+  <|> findAttrByName ns "w" "styleId" el)
+
+getNumInfo :: NameSpaces -> Element -> Maybe (T.Text, T.Text)
+getNumInfo ns element = do
+  let numPr = findChildByName ns "w" "pPr" element >>=
+              findChildByName ns "w" "numPr"
+      lvl = fromMaybe "0" (numPr >>=
+                           findChildByName ns "w" "ilvl" >>=
+                           findAttrByName ns "w" "val")
+  numId <- numPr >>=
+           findChildByName ns "w" "numId" >>=
+           findAttrByName ns "w" "val"
+  return (numId, lvl)
+
+elemToParStyleData :: NameSpaces -> Element -> Maybe ParStyle -> Maybe ParStyle
+elemToParStyleData ns element parentStyle
+  | Just styleId <- findAttrByName ns "w" "styleId" element
+  , Just styleName <- getElementStyleName ns element
+  = Just $ ParStyle
+      {
+        headingLev = getHeaderLevel ns element
+      , indent = getIndentation ns element
+      , numInfo = getNumInfo ns element
+      , psParentStyle = parentStyle
+      , pStyleName = styleName
+      , pStyleId = ParaStyleId styleId
+      }
+elemToParStyleData _ _ _ = Nothing
diff --git a/src/Text/Pandoc/Readers/Docx/StyleMap.hs b/src/Text/Pandoc/Readers/Docx/StyleMap.hs
deleted file mode 100644
--- a/src/Text/Pandoc/Readers/Docx/StyleMap.hs
+++ /dev/null
@@ -1,108 +0,0 @@
-module Text.Pandoc.Readers.Docx.StyleMap (  StyleMaps(..)
-                                          , alterMap
-                                          , getMap
-                                          , defaultStyleMaps
-                                          , getStyleMaps
-                                          , getStyleId
-                                          , hasStyleName
-                                          ) where
-
-import Control.Monad.State.Strict
-import Data.Char (toLower)
-import qualified Data.Map as M
-import Text.Pandoc.Readers.Docx.Util
-import Text.XML.Light
-
-newtype ParaStyleMap = ParaStyleMap ( M.Map String String )
-newtype CharStyleMap = CharStyleMap ( M.Map String String )
-
-class StyleMap a where
-  alterMap :: (M.Map String String -> M.Map String String) -> a -> a
-  getMap :: a -> M.Map String String
-
-instance StyleMap ParaStyleMap where
-  alterMap f (ParaStyleMap m) = ParaStyleMap $ f m
-  getMap (ParaStyleMap m) = m
-
-instance StyleMap CharStyleMap where
-  alterMap f (CharStyleMap m) = CharStyleMap $ f m
-  getMap (CharStyleMap m) = m
-
-insert :: (StyleMap a) => Maybe String -> Maybe String -> a -> a
-insert (Just k) (Just v) m = alterMap (M.insert k v) m
-insert _ _ m               = m
-
-getStyleId :: (StyleMap a) => String -> a -> String
-getStyleId s = M.findWithDefault (filter (/=' ') s) (map toLower s) . getMap
-
-hasStyleName :: (StyleMap a) => String -> a -> Bool
-hasStyleName styleName = M.member (map toLower styleName) . getMap
-
-data StyleMaps = StyleMaps { sNameSpaces   :: NameSpaces
-                           , sParaStyleMap :: ParaStyleMap
-                           , sCharStyleMap :: CharStyleMap
-                           }
-
-data StyleType = ParaStyle | CharStyle
-
-defaultStyleMaps :: StyleMaps
-defaultStyleMaps = StyleMaps { sNameSpaces = []
-                             , sParaStyleMap = ParaStyleMap M.empty
-                             , sCharStyleMap = CharStyleMap M.empty
-                             }
-
-type StateM a = State StyleMaps a
-
-getStyleMaps :: Element -> StyleMaps
-getStyleMaps docElem = execState genStyleMap state'
-    where
-    state' = defaultStyleMaps {sNameSpaces = elemToNameSpaces docElem}
-    genStyleItem e = do
-      styleType <- getStyleType e
-      styleId <- getAttrStyleId e
-      nameValLowercase <- fmap (map toLower) `fmap` getNameVal e
-      case styleType of
-        Just ParaStyle -> modParaStyleMap $ insert nameValLowercase styleId
-        Just CharStyle -> modCharStyleMap $ insert nameValLowercase styleId
-        _              -> return ()
-    genStyleMap = do
-      style <- elemName' "style"
-      let styles = findChildren style docElem
-      forM_ styles genStyleItem
-
-modParaStyleMap :: (ParaStyleMap -> ParaStyleMap) -> StateM ()
-modParaStyleMap f = modify $ \s ->
-  s {sParaStyleMap = f $ sParaStyleMap s}
-
-modCharStyleMap :: (CharStyleMap -> CharStyleMap) -> StateM ()
-modCharStyleMap f = modify $ \s ->
-  s {sCharStyleMap = f $ sCharStyleMap s}
-
-getStyleType :: Element -> StateM (Maybe StyleType)
-getStyleType e = do
-  styleTypeStr <- getAttrType e
-  case styleTypeStr of
-    Just "paragraph" -> return $ Just ParaStyle
-    Just "character" -> return $ Just CharStyle
-    _                -> return   Nothing
-
-getAttrType :: Element -> StateM (Maybe String)
-getAttrType el = do
-  name <- elemName' "type"
-  return $ findAttr name el
-
-getAttrStyleId :: Element -> StateM (Maybe String)
-getAttrStyleId el = do
-  name <- elemName' "styleId"
-  return $ findAttr name el
-
-getNameVal :: Element -> StateM (Maybe String)
-getNameVal el = do
-  name <- elemName' "name"
-  val <- elemName' "val"
-  return $ findChild name el >>= findAttr val
-
-elemName' :: String -> StateM QName
-elemName' name = do
-  namespaces <- gets sNameSpaces
-  return $ elemName namespaces "w" name
diff --git a/src/Text/Pandoc/Readers/Docx/Symbols.hs b/src/Text/Pandoc/Readers/Docx/Symbols.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Readers/Docx/Symbols.hs
@@ -0,0 +1,1085 @@
+{-# LANGUAGE OverloadedStrings #-}
+{- |
+   Module      : Text.Pandoc.Readers.Docx.Symbols
+   Copyright   : © 2023 John MacFarlane <jgm@berkeley.edu>
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : John MacFarlane <jgm@berkeley.edu>
+   Stability   : alpha
+   Portability : portable
+
+Symbol tables for MS symbol fonts. This is needed for w:sym.
+-}
+module Text.Pandoc.Readers.Docx.Symbols ( Font(..),
+                                          textToFont,
+                                          symbolMap ) where
+
+import Data.Text (Text)
+import qualified Data.Map as M
+
+data Font = Symbol | Wingdings | Wingdings2 | Wingdings3 | Webdings
+  deriving (Show, Ord, Eq)
+
+textToFont :: Text -> Maybe Font
+textToFont "Symbol" = Just Symbol
+textToFont "Wingdings" = Just Wingdings
+textToFont "Wingdings 2" = Just Wingdings2
+textToFont "Wingdings 3" = Just Wingdings3
+textToFont "Webdings" = Just Webdings
+textToFont _ = Nothing
+
+-- \ Maps font and internal character number to Unicode code point.
+symbolMap :: M.Map (Font, Int) Int
+symbolMap = M.fromList
+  [((Wingdings, 0x21), 0x1F589)
+  ,((Wingdings, 0x22), 0x2702)
+  ,((Wingdings, 0x23), 0x2701)
+  ,((Wingdings, 0x24), 0x1F453)
+  ,((Wingdings, 0x25), 0x1F56D)
+  ,((Wingdings, 0x26), 0x1F56E)
+  ,((Wingdings, 0x27), 0x1F56F)
+  ,((Wingdings, 0x28), 0x1F57F)
+  ,((Wingdings, 0x29), 0x2706)
+  ,((Wingdings, 0x2A), 0x1F582)
+  ,((Wingdings, 0x2B), 0x1F583)
+  ,((Wingdings, 0x2C), 0x1F4EA)
+  ,((Wingdings, 0x2D), 0x1F4EB)
+  ,((Wingdings, 0x2E), 0x1F4EC)
+  ,((Wingdings, 0x2F), 0x1F4ED)
+  ,((Wingdings, 0x30), 0x1F4C1)
+  ,((Wingdings, 0x31), 0x1F4C2)
+  ,((Wingdings, 0x32), 0x1F4C4)
+  ,((Wingdings, 0x33), 0x1F5CF)
+  ,((Wingdings, 0x34), 0x1F5D0)
+  ,((Wingdings, 0x35), 0x1F5C4)
+  ,((Wingdings, 0x36), 0x231B)
+  ,((Wingdings, 0x37), 0x1F5AE)
+  ,((Wingdings, 0x38), 0x1F5B0)
+  ,((Wingdings, 0x39), 0x1F5B2)
+  ,((Wingdings, 0x3A), 0x1F5B3)
+  ,((Wingdings, 0x3B), 0x1F5B4)
+  ,((Wingdings, 0x3C), 0x1F5AB)
+  ,((Wingdings, 0x3D), 0x1F5AC)
+  ,((Wingdings, 0x3E), 0x2707)
+  ,((Wingdings, 0x3F), 0x270D)
+  ,((Wingdings, 0x40), 0x1F58E)
+  ,((Wingdings, 0x41), 0x270C)
+  ,((Wingdings, 0x42), 0x1F44C)
+  ,((Wingdings, 0x43), 0x1F44D)
+  ,((Wingdings, 0x44), 0x1F44E)
+  ,((Wingdings, 0x45), 0x261C)
+  ,((Wingdings, 0x46), 0x261E)
+  ,((Wingdings, 0x47), 0x261D)
+  ,((Wingdings, 0x48), 0x261F)
+  ,((Wingdings, 0x49), 0x1F590)
+  ,((Wingdings, 0x4A), 0x263A)
+  ,((Wingdings, 0x4B), 0x1F610)
+  ,((Wingdings, 0x4C), 0x2639)
+  ,((Wingdings, 0x4D), 0x1F4A3)
+  ,((Wingdings, 0x4E), 0x2620)
+  ,((Wingdings, 0x4F), 0x1F3F3)
+  ,((Wingdings, 0x50), 0x1F3F1)
+  ,((Wingdings, 0x51), 0x2708)
+  ,((Wingdings, 0x52), 0x263C)
+  ,((Wingdings, 0x53), 0x1F4A7)
+  ,((Wingdings, 0x54), 0x2744)
+  ,((Wingdings, 0x55), 0x1F546)
+  ,((Wingdings, 0x56), 0x271E)
+  ,((Wingdings, 0x57), 0x1F548)
+  ,((Wingdings, 0x58), 0x2720)
+  ,((Wingdings, 0x59), 0x2721)
+  ,((Wingdings, 0x5A), 0x262A)
+  ,((Wingdings, 0x5B), 0x262F)
+  ,((Wingdings, 0x5C), 0x0950)
+  ,((Wingdings, 0x5D), 0x2638)
+  ,((Wingdings, 0x5E), 0x2648)
+  ,((Wingdings, 0x5F), 0x2649)
+  ,((Wingdings, 0x60), 0x264A)
+  ,((Wingdings, 0x61), 0x264B)
+  ,((Wingdings, 0x62), 0x264C)
+  ,((Wingdings, 0x63), 0x264D)
+  ,((Wingdings, 0x64), 0x264E)
+  ,((Wingdings, 0x65), 0x264F)
+  ,((Wingdings, 0x66), 0x2650)
+  ,((Wingdings, 0x67), 0x2651)
+  ,((Wingdings, 0x68), 0x2652)
+  ,((Wingdings, 0x69), 0x2653)
+  ,((Wingdings, 0x6A), 0x1F670)
+  ,((Wingdings, 0x6B), 0x1F675)
+  ,((Wingdings, 0x6C), 0x25CF)
+  ,((Wingdings, 0x6D), 0x1F53E)
+  ,((Wingdings, 0x6E), 0x25A0)
+  ,((Wingdings, 0x6F), 0x25A1)
+  ,((Wingdings, 0x70), 0x1F790)
+  ,((Wingdings, 0x71), 0x2751)
+  ,((Wingdings, 0x72), 0x2752)
+  ,((Wingdings, 0x73), 0x2B27)
+  ,((Wingdings, 0x74), 0x29EB)
+  ,((Wingdings, 0x75), 0x25C6)
+  ,((Wingdings, 0x76), 0x2756)
+  ,((Wingdings, 0x77), 0x2B25)
+  ,((Wingdings, 0x78), 0x2327)
+  ,((Wingdings, 0x79), 0x2BB9)
+  ,((Wingdings, 0x7A), 0x2318)
+  ,((Wingdings, 0x7B), 0x1F3F5)
+  ,((Wingdings, 0x7C), 0x1F3F6)
+  ,((Wingdings, 0x7D), 0x1F676)
+  ,((Wingdings, 0x7E), 0x1F677)
+  ,((Wingdings, 0x80), 0x24EA)
+  ,((Wingdings, 0x81), 0x2460)
+  ,((Wingdings, 0x82), 0x2461)
+  ,((Wingdings, 0x83), 0x2462)
+  ,((Wingdings, 0x84), 0x2463)
+  ,((Wingdings, 0x85), 0x2464)
+  ,((Wingdings, 0x86), 0x2465)
+  ,((Wingdings, 0x87), 0x2466)
+  ,((Wingdings, 0x88), 0x2467)
+  ,((Wingdings, 0x89), 0x2468)
+  ,((Wingdings, 0x8A), 0x2469)
+  ,((Wingdings, 0x8B), 0x24FF)
+  ,((Wingdings, 0x8C), 0x2776)
+  ,((Wingdings, 0x8D), 0x2777)
+  ,((Wingdings, 0x8E), 0x2778)
+  ,((Wingdings, 0x8F), 0x2779)
+  ,((Wingdings, 0x90), 0x277A)
+  ,((Wingdings, 0x91), 0x277B)
+  ,((Wingdings, 0x92), 0x277C)
+  ,((Wingdings, 0x93), 0x277D)
+  ,((Wingdings, 0x94), 0x277E)
+  ,((Wingdings, 0x95), 0x277F)
+  ,((Wingdings, 0x96), 0x1F662)
+  ,((Wingdings, 0x97), 0x1F660)
+  ,((Wingdings, 0x98), 0x1F661)
+  ,((Wingdings, 0x99), 0x1F663)
+  ,((Wingdings, 0x9A), 0x1F65E)
+  ,((Wingdings, 0x9B), 0x1F65C)
+  ,((Wingdings, 0x9C), 0x1F65D)
+  ,((Wingdings, 0x9D), 0x1F65F)
+  ,((Wingdings, 0x9E), 0x00B7)
+  ,((Wingdings, 0x9F), 0x2022)
+  ,((Wingdings, 0xA1), 0x26AA)
+  ,((Wingdings, 0xA2), 0x1F786)
+  ,((Wingdings, 0xA3), 0x1F788)
+  ,((Wingdings, 0xA4), 0x25C9)
+  ,((Wingdings, 0xA5), 0x25CE)
+  ,((Wingdings, 0xA6), 0x1F53F)
+  ,((Wingdings, 0xA7), 0x25AA)
+  ,((Wingdings, 0xA8), 0x25FB)
+  ,((Wingdings, 0xA9), 0x1F7C2)
+  ,((Wingdings, 0xAA), 0x2726)
+  ,((Wingdings, 0xAB), 0x2605)
+  ,((Wingdings, 0xAC), 0x2736)
+  ,((Wingdings, 0xAD), 0x2734)
+  ,((Wingdings, 0xAE), 0x2739)
+  ,((Wingdings, 0xAF), 0x2735)
+  ,((Wingdings, 0xB0), 0x2BD0)
+  ,((Wingdings, 0xB1), 0x2316)
+  ,((Wingdings, 0xB2), 0x27E1)
+  ,((Wingdings, 0xB3), 0x2311)
+  ,((Wingdings, 0xB4), 0x2BD1)
+  ,((Wingdings, 0xB5), 0x272A)
+  ,((Wingdings, 0xB6), 0x2730)
+  ,((Wingdings, 0xB7), 0x1F550)
+  ,((Wingdings, 0xB8), 0x1F551)
+  ,((Wingdings, 0xB9), 0x1F552)
+  ,((Wingdings, 0xBA), 0x1F553)
+  ,((Wingdings, 0xBB), 0x1F554)
+  ,((Wingdings, 0xBC), 0x1F555)
+  ,((Wingdings, 0xBD), 0x1F556)
+  ,((Wingdings, 0xBE), 0x1F557)
+  ,((Wingdings, 0xBF), 0x1F558)
+  ,((Wingdings, 0xC0), 0x1F559)
+  ,((Wingdings, 0xC1), 0x1F55A)
+  ,((Wingdings, 0xC2), 0x1F55B)
+  ,((Wingdings, 0xC3), 0x2BB0)
+  ,((Wingdings, 0xC4), 0x2BB1)
+  ,((Wingdings, 0xC5), 0x2BB2)
+  ,((Wingdings, 0xC6), 0x2BB3)
+  ,((Wingdings, 0xC7), 0x2BB4)
+  ,((Wingdings, 0xC8), 0x2BB5)
+  ,((Wingdings, 0xC9), 0x2BB6)
+  ,((Wingdings, 0xCA), 0x2BB7)
+  ,((Wingdings, 0xCB), 0x1F66A)
+  ,((Wingdings, 0xCC), 0x1F66B)
+  ,((Wingdings, 0xCD), 0x1F655)
+  ,((Wingdings, 0xCE), 0x1F654)
+  ,((Wingdings, 0xCF), 0x1F657)
+  ,((Wingdings, 0xD0), 0x1F656)
+  ,((Wingdings, 0xD1), 0x1F650)
+  ,((Wingdings, 0xD2), 0x1F651)
+  ,((Wingdings, 0xD3), 0x1F652)
+  ,((Wingdings, 0xD4), 0x1F653)
+  ,((Wingdings, 0xD5), 0x232B)
+  ,((Wingdings, 0xD6), 0x2326)
+  ,((Wingdings, 0xD7), 0x2B98)
+  ,((Wingdings, 0xD8), 0x2B9A)
+  ,((Wingdings, 0xD9), 0x2B99)
+  ,((Wingdings, 0xDA), 0x2B9B)
+  ,((Wingdings, 0xDB), 0x2B88)
+  ,((Wingdings, 0xDC), 0x2B8A)
+  ,((Wingdings, 0xDD), 0x2B89)
+  ,((Wingdings, 0xDE), 0x2B8B)
+  ,((Wingdings, 0xDF), 0x1F868)
+  ,((Wingdings, 0xE0), 0x1F86A)
+  ,((Wingdings, 0xE1), 0x1F869)
+  ,((Wingdings, 0xE2), 0x1F86B)
+  ,((Wingdings, 0xE3), 0x1F86C)
+  ,((Wingdings, 0xE4), 0x1F86D)
+  ,((Wingdings, 0xE5), 0x1F86F)
+  ,((Wingdings, 0xE6), 0x1F86E)
+  ,((Wingdings, 0xE7), 0x1F878)
+  ,((Wingdings, 0xE8), 0x1F87A)
+  ,((Wingdings, 0xE9), 0x1F879)
+  ,((Wingdings, 0xEA), 0x1F87B)
+  ,((Wingdings, 0xEB), 0x1F87C)
+  ,((Wingdings, 0xEC), 0x1F87D)
+  ,((Wingdings, 0xED), 0x1F87F)
+  ,((Wingdings, 0xEE), 0x1F87E)
+  ,((Wingdings, 0xEF), 0x21E6)
+  ,((Wingdings, 0xF0), 0x21E8)
+  ,((Wingdings, 0xF1), 0x21E7)
+  ,((Wingdings, 0xF2), 0x21E9)
+  ,((Wingdings, 0xF3), 0x2B04)
+  ,((Wingdings, 0xF4), 0x21F3)
+  ,((Wingdings, 0xF5), 0x2B00)
+  ,((Wingdings, 0xF6), 0x2B01)
+  ,((Wingdings, 0xF7), 0x2B03)
+  ,((Wingdings, 0xF8), 0x2B02)
+  ,((Wingdings, 0xF9), 0x1F8AC)
+  ,((Wingdings, 0xFA), 0x1F8AD)
+  ,((Wingdings, 0xFB), 0x1F5F6)
+  ,((Wingdings, 0xFC), 0x2714)
+  ,((Wingdings, 0xFD), 0x1F5F7)
+  ,((Wingdings, 0xFE), 0x1F5F9)
+  ,((Wingdings2, 0x21), 0x1F58A)
+  ,((Wingdings2, 0x22), 0x1F58B)
+  ,((Wingdings2, 0x23), 0x1F58C)
+  ,((Wingdings2, 0x24), 0x1F58D)
+  ,((Wingdings2, 0x25), 0x2704)
+  ,((Wingdings2, 0x26), 0x2700)
+  ,((Wingdings2, 0x27), 0x1F57E)
+  ,((Wingdings2, 0x28), 0x1F57D)
+  ,((Wingdings2, 0x29), 0x1F5C5)
+  ,((Wingdings2, 0x2A), 0x1F5C6)
+  ,((Wingdings2, 0x2B), 0x1F5C7)
+  ,((Wingdings2, 0x2C), 0x1F5C8)
+  ,((Wingdings2, 0x2D), 0x1F5C9)
+  ,((Wingdings2, 0x2E), 0x1F5CA)
+  ,((Wingdings2, 0x2F), 0x1F5CB)
+  ,((Wingdings2, 0x30), 0x1F5CC)
+  ,((Wingdings2, 0x31), 0x1F5CD)
+  ,((Wingdings2, 0x32), 0x1F4CB)
+  ,((Wingdings2, 0x33), 0x1F5D1)
+  ,((Wingdings2, 0x34), 0x1F5D4)
+  ,((Wingdings2, 0x35), 0x1F5B5)
+  ,((Wingdings2, 0x36), 0x1F5B6)
+  ,((Wingdings2, 0x37), 0x1F5B7)
+  ,((Wingdings2, 0x38), 0x1F5B8)
+  ,((Wingdings2, 0x39), 0x1F5AD)
+  ,((Wingdings2, 0x3A), 0x1F5AF)
+  ,((Wingdings2, 0x3B), 0x1F5B1)
+  ,((Wingdings2, 0x3C), 0x1F592)
+  ,((Wingdings2, 0x3D), 0x1F593)
+  ,((Wingdings2, 0x3E), 0x1F598)
+  ,((Wingdings2, 0x3F), 0x1F599)
+  ,((Wingdings2, 0x40), 0x1F59A)
+  ,((Wingdings2, 0x41), 0x1F59B)
+  ,((Wingdings2, 0x42), 0x1F448)
+  ,((Wingdings2, 0x43), 0x1F449)
+  ,((Wingdings2, 0x44), 0x1F59C)
+  ,((Wingdings2, 0x45), 0x1F59D)
+  ,((Wingdings2, 0x46), 0x1F59E)
+  ,((Wingdings2, 0x47), 0x1F59F)
+  ,((Wingdings2, 0x48), 0x1F5A0)
+  ,((Wingdings2, 0x49), 0x1F5A1)
+  ,((Wingdings2, 0x4A), 0x1F446)
+  ,((Wingdings2, 0x4B), 0x1F447)
+  ,((Wingdings2, 0x4C), 0x1F5A2)
+  ,((Wingdings2, 0x4D), 0x1F5A3)
+  ,((Wingdings2, 0x4E), 0x1F591)
+  ,((Wingdings2, 0x4F), 0x1F5F4)
+  ,((Wingdings2, 0x50), 0x2713)
+  ,((Wingdings2, 0x51), 0x1F5F5)
+  ,((Wingdings2, 0x52), 0x2611)
+  ,((Wingdings2, 0x53), 0x2612)
+  ,((Wingdings2, 0x54), 0x2612)
+  ,((Wingdings2, 0x55), 0x2BBE)
+  ,((Wingdings2, 0x56), 0x2BBF)
+  ,((Wingdings2, 0x57), 0x29B8)
+  ,((Wingdings2, 0x58), 0x29B8)
+  ,((Wingdings2, 0x59), 0x1F671)
+  ,((Wingdings2, 0x5A), 0x1F674)
+  ,((Wingdings2, 0x5B), 0x1F672)
+  ,((Wingdings2, 0x5C), 0x1F673)
+  ,((Wingdings2, 0x5D), 0x203D)
+  ,((Wingdings2, 0x5E), 0x1F679)
+  ,((Wingdings2, 0x5F), 0x1F67A)
+  ,((Wingdings2, 0x60), 0x1F67B)
+  ,((Wingdings2, 0x61), 0x1F666)
+  ,((Wingdings2, 0x62), 0x1F664)
+  ,((Wingdings2, 0x63), 0x1F665)
+  ,((Wingdings2, 0x64), 0x1F667)
+  ,((Wingdings2, 0x65), 0x1F65A)
+  ,((Wingdings2, 0x66), 0x1F658)
+  ,((Wingdings2, 0x67), 0x1F659)
+  ,((Wingdings2, 0x68), 0x1F65B)
+  ,((Wingdings2, 0x69), 0x24EA)
+  ,((Wingdings2, 0x6A), 0x2460)
+  ,((Wingdings2, 0x6B), 0x2461)
+  ,((Wingdings2, 0x6C), 0x2462)
+  ,((Wingdings2, 0x6D), 0x2463)
+  ,((Wingdings2, 0x6E), 0x2464)
+  ,((Wingdings2, 0x6F), 0x2465)
+  ,((Wingdings2, 0x70), 0x2466)
+  ,((Wingdings2, 0x71), 0x2467)
+  ,((Wingdings2, 0x72), 0x2468)
+  ,((Wingdings2, 0x73), 0x2469)
+  ,((Wingdings2, 0x74), 0x24FF)
+  ,((Wingdings2, 0x75), 0x2776)
+  ,((Wingdings2, 0x76), 0x2777)
+  ,((Wingdings2, 0x77), 0x2778)
+  ,((Wingdings2, 0x78), 0x2779)
+  ,((Wingdings2, 0x79), 0x277A)
+  ,((Wingdings2, 0x7A), 0x277B)
+  ,((Wingdings2, 0x7B), 0x277C)
+  ,((Wingdings2, 0x7C), 0x277D)
+  ,((Wingdings2, 0x7D), 0x277E)
+  ,((Wingdings2, 0x7E), 0x277F)
+  ,((Wingdings2, 0x80), 0x2609)
+  ,((Wingdings2, 0x81), 0x1F315)
+  ,((Wingdings2, 0x82), 0x263D)
+  ,((Wingdings2, 0x83), 0x263E)
+  ,((Wingdings2, 0x84), 0x2E3F)
+  ,((Wingdings2, 0x85), 0x271D)
+  ,((Wingdings2, 0x86), 0x1F547)
+  ,((Wingdings2, 0x87), 0x1F55C)
+  ,((Wingdings2, 0x88), 0x1F55D)
+  ,((Wingdings2, 0x89), 0x1F55E)
+  ,((Wingdings2, 0x8A), 0x1F55F)
+  ,((Wingdings2, 0x8B), 0x1F560)
+  ,((Wingdings2, 0x8C), 0x1F561)
+  ,((Wingdings2, 0x8D), 0x1F562)
+  ,((Wingdings2, 0x8E), 0x1F563)
+  ,((Wingdings2, 0x8F), 0x1F564)
+  ,((Wingdings2, 0x90), 0x1F565)
+  ,((Wingdings2, 0x91), 0x1F566)
+  ,((Wingdings2, 0x92), 0x1F567)
+  ,((Wingdings2, 0x93), 0x1F668)
+  ,((Wingdings2, 0x94), 0x1F669)
+  ,((Wingdings2, 0x95), 0x2022)
+  ,((Wingdings2, 0x96), 0x25CF)
+  ,((Wingdings2, 0x97), 0x26AB)
+  ,((Wingdings2, 0x98), 0x2B24)
+  ,((Wingdings2, 0x99), 0x1F785)
+  ,((Wingdings2, 0x9A), 0x1F786)
+  ,((Wingdings2, 0x9B), 0x1F787)
+  ,((Wingdings2, 0x9C), 0x1F788)
+  ,((Wingdings2, 0x9D), 0x1F78A)
+  ,((Wingdings2, 0x9E), 0x29BF)
+  ,((Wingdings2, 0x9F), 0x25FE)
+  ,((Wingdings2, 0xA1), 0x25FC)
+  ,((Wingdings2, 0xA2), 0x2B1B)
+  ,((Wingdings2, 0xA3), 0x2B1C)
+  ,((Wingdings2, 0xA4), 0x1F791)
+  ,((Wingdings2, 0xA5), 0x1F792)
+  ,((Wingdings2, 0xA6), 0x1F793)
+  ,((Wingdings2, 0xA7), 0x1F794)
+  ,((Wingdings2, 0xA8), 0x25A3)
+  ,((Wingdings2, 0xA9), 0x1F795)
+  ,((Wingdings2, 0xAA), 0x1F796)
+  ,((Wingdings2, 0xAB), 0x1F797)
+  ,((Wingdings2, 0xAC), 0x2B29)
+  ,((Wingdings2, 0xAD), 0x2B25)
+  ,((Wingdings2, 0xAE), 0x25C6)
+  ,((Wingdings2, 0xAF), 0x25C7)
+  ,((Wingdings2, 0xB0), 0x1F79A)
+  ,((Wingdings2, 0xB1), 0x25C8)
+  ,((Wingdings2, 0xB2), 0x1F79B)
+  ,((Wingdings2, 0xB3), 0x1F79C)
+  ,((Wingdings2, 0xB4), 0x1F79D)
+  ,((Wingdings2, 0xB5), 0x2B2A)
+  ,((Wingdings2, 0xB6), 0x2B27)
+  ,((Wingdings2, 0xB7), 0x29EB)
+  ,((Wingdings2, 0xB8), 0x25CA)
+  ,((Wingdings2, 0xB9), 0x1F7A0)
+  ,((Wingdings2, 0xBA), 0x25D6)
+  ,((Wingdings2, 0xBB), 0x25D7)
+  ,((Wingdings2, 0xBC), 0x2BCA)
+  ,((Wingdings2, 0xBD), 0x2BCB)
+  ,((Wingdings2, 0xBE), 0x25FC)
+  ,((Wingdings2, 0xBF), 0x2B25)
+  ,((Wingdings2, 0xC0), 0x2B1F)
+  ,((Wingdings2, 0xC1), 0x2BC2)
+  ,((Wingdings2, 0xC2), 0x2B23)
+  ,((Wingdings2, 0xC3), 0x2B22)
+  ,((Wingdings2, 0xC4), 0x2BC3)
+  ,((Wingdings2, 0xC5), 0x2BC4)
+  ,((Wingdings2, 0xC6), 0x1F7A1)
+  ,((Wingdings2, 0xC7), 0x1F7A2)
+  ,((Wingdings2, 0xC8), 0x1F7A3)
+  ,((Wingdings2, 0xC9), 0x1F7A4)
+  ,((Wingdings2, 0xCA), 0x1F7A5)
+  ,((Wingdings2, 0xCB), 0x1F7A6)
+  ,((Wingdings2, 0xCC), 0x1F7A7)
+  ,((Wingdings2, 0xCD), 0x1F7A8)
+  ,((Wingdings2, 0xCE), 0x1F7A9)
+  ,((Wingdings2, 0xCF), 0x1F7AA)
+  ,((Wingdings2, 0xD0), 0x1F7AB)
+  ,((Wingdings2, 0xD1), 0x1F7AC)
+  ,((Wingdings2, 0xD2), 0x1F7AD)
+  ,((Wingdings2, 0xD3), 0x1F7AE)
+  ,((Wingdings2, 0xD4), 0x1F7AF)
+  ,((Wingdings2, 0xD5), 0x1F7B0)
+  ,((Wingdings2, 0xD6), 0x1F7B1)
+  ,((Wingdings2, 0xD7), 0x1F7B2)
+  ,((Wingdings2, 0xD8), 0x1F7B3)
+  ,((Wingdings2, 0xD9), 0x1F7B4)
+  ,((Wingdings2, 0xDA), 0x1F7B5)
+  ,((Wingdings2, 0xDB), 0x1F7B6)
+  ,((Wingdings2, 0xDC), 0x1F7B7)
+  ,((Wingdings2, 0xDD), 0x1F7B8)
+  ,((Wingdings2, 0xDE), 0x1F7B9)
+  ,((Wingdings2, 0xDF), 0x1F7BA)
+  ,((Wingdings2, 0xE0), 0x1F7BB)
+  ,((Wingdings2, 0xE1), 0x1F7BC)
+  ,((Wingdings2, 0xE2), 0x1F7BD)
+  ,((Wingdings2, 0xE3), 0x1F7BE)
+  ,((Wingdings2, 0xE4), 0x1F7BF)
+  ,((Wingdings2, 0xE5), 0x1F7C0)
+  ,((Wingdings2, 0xE6), 0x1F7C2)
+  ,((Wingdings2, 0xE7), 0x1F7C4)
+  ,((Wingdings2, 0xE8), 0x2726)
+  ,((Wingdings2, 0xE9), 0x1F7C9)
+  ,((Wingdings2, 0xEA), 0x2605)
+  ,((Wingdings2, 0xEB), 0x2736)
+  ,((Wingdings2, 0xEC), 0x1F7CB)
+  ,((Wingdings2, 0xED), 0x2737)
+  ,((Wingdings2, 0xEE), 0x1F7CF)
+  ,((Wingdings2, 0xEF), 0x1F7D2)
+  ,((Wingdings2, 0xF0), 0x2739)
+  ,((Wingdings2, 0xF1), 0x1F7C3)
+  ,((Wingdings2, 0xF2), 0x1F7C7)
+  ,((Wingdings2, 0xF3), 0x272F)
+  ,((Wingdings2, 0xF4), 0x1F7CD)
+  ,((Wingdings2, 0xF5), 0x1F7D4)
+  ,((Wingdings2, 0xF6), 0x2BCC)
+  ,((Wingdings2, 0xF7), 0x2BCD)
+  ,((Wingdings2, 0xF8), 0x203B)
+  ,((Wingdings2, 0xF9), 0x2042)
+  ,((Wingdings3, 0x21), 0x2B60)
+  ,((Wingdings3, 0x22), 0x2B62)
+  ,((Wingdings3, 0x23), 0x2B61)
+  ,((Wingdings3, 0x24), 0x2B63)
+  ,((Wingdings3, 0x25), 0x2B66)
+  ,((Wingdings3, 0x26), 0x2B67)
+  ,((Wingdings3, 0x27), 0x2B69)
+  ,((Wingdings3, 0x28), 0x2B68)
+  ,((Wingdings3, 0x29), 0x2B70)
+  ,((Wingdings3, 0x2A), 0x2B72)
+  ,((Wingdings3, 0x2B), 0x2B71)
+  ,((Wingdings3, 0x2C), 0x2B73)
+  ,((Wingdings3, 0x2D), 0x2B76)
+  ,((Wingdings3, 0x2E), 0x2B78)
+  ,((Wingdings3, 0x2F), 0x2B7B)
+  ,((Wingdings3, 0x30), 0x2B7D)
+  ,((Wingdings3, 0x31), 0x2B64)
+  ,((Wingdings3, 0x32), 0x2B65)
+  ,((Wingdings3, 0x33), 0x2B6A)
+  ,((Wingdings3, 0x34), 0x2B6C)
+  ,((Wingdings3, 0x35), 0x2B6B)
+  ,((Wingdings3, 0x36), 0x2B6D)
+  ,((Wingdings3, 0x37), 0x2B4D)
+  ,((Wingdings3, 0x38), 0x2BA0)
+  ,((Wingdings3, 0x39), 0x2BA1)
+  ,((Wingdings3, 0x3A), 0x2BA2)
+  ,((Wingdings3, 0x3B), 0x2BA3)
+  ,((Wingdings3, 0x3C), 0x2BA4)
+  ,((Wingdings3, 0x3D), 0x2BA5)
+  ,((Wingdings3, 0x3E), 0x2BA6)
+  ,((Wingdings3, 0x3F), 0x2BA7)
+  ,((Wingdings3, 0x40), 0x2B90)
+  ,((Wingdings3, 0x41), 0x2B91)
+  ,((Wingdings3, 0x42), 0x2B92)
+  ,((Wingdings3, 0x43), 0x2B93)
+  ,((Wingdings3, 0x44), 0x2B80)
+  ,((Wingdings3, 0x45), 0x2B83)
+  ,((Wingdings3, 0x46), 0x2B7E)
+  ,((Wingdings3, 0x47), 0x2B7F)
+  ,((Wingdings3, 0x48), 0x2B84)
+  ,((Wingdings3, 0x49), 0x2B86)
+  ,((Wingdings3, 0x4A), 0x2B85)
+  ,((Wingdings3, 0x4B), 0x2B87)
+  ,((Wingdings3, 0x4C), 0x2B8F)
+  ,((Wingdings3, 0x4D), 0x2B8D)
+  ,((Wingdings3, 0x4E), 0x2B8E)
+  ,((Wingdings3, 0x4F), 0x2B8C)
+  ,((Wingdings3, 0x50), 0x2B6E)
+  ,((Wingdings3, 0x51), 0x2B6F)
+  ,((Wingdings3, 0x52), 0x238B)
+  ,((Wingdings3, 0x53), 0x2324)
+  ,((Wingdings3, 0x54), 0x2303)
+  ,((Wingdings3, 0x55), 0x2325)
+  ,((Wingdings3, 0x56), 0x23B5)
+  ,((Wingdings3, 0x57), 0x237D)
+  ,((Wingdings3, 0x58), 0x21EA)
+  ,((Wingdings3, 0x59), 0x2BB8)
+  ,((Wingdings3, 0x5A), 0x1F8A0)
+  ,((Wingdings3, 0x5B), 0x1F8A1)
+  ,((Wingdings3, 0x5C), 0x1F8A2)
+  ,((Wingdings3, 0x5D), 0x1F8A3)
+  ,((Wingdings3, 0x5E), 0x1F8A4)
+  ,((Wingdings3, 0x5F), 0x1F8A5)
+  ,((Wingdings3, 0x60), 0x1F8A6)
+  ,((Wingdings3, 0x61), 0x1F8A7)
+  ,((Wingdings3, 0x62), 0x1F8A8)
+  ,((Wingdings3, 0x63), 0x1F8A9)
+  ,((Wingdings3, 0x64), 0x1F8AA)
+  ,((Wingdings3, 0x65), 0x1F8AB)
+  ,((Wingdings3, 0x66), 0x2190)
+  ,((Wingdings3, 0x67), 0x2192)
+  ,((Wingdings3, 0x68), 0x2191)
+  ,((Wingdings3, 0x69), 0x2193)
+  ,((Wingdings3, 0x6A), 0x2196)
+  ,((Wingdings3, 0x6B), 0x2197)
+  ,((Wingdings3, 0x6C), 0x2199)
+  ,((Wingdings3, 0x6D), 0x2198)
+  ,((Wingdings3, 0x6E), 0x1F858)
+  ,((Wingdings3, 0x6F), 0x1F859)
+  ,((Wingdings3, 0x70), 0x25B2)
+  ,((Wingdings3, 0x71), 0x25BC)
+  ,((Wingdings3, 0x72), 0x25B3)
+  ,((Wingdings3, 0x73), 0x25BD)
+  ,((Wingdings3, 0x74), 0x25C4)
+  ,((Wingdings3, 0x75), 0x25BA)
+  ,((Wingdings3, 0x76), 0x25C1)
+  ,((Wingdings3, 0x77), 0x25B7)
+  ,((Wingdings3, 0x78), 0x25E3)
+  ,((Wingdings3, 0x79), 0x25E2)
+  ,((Wingdings3, 0x7A), 0x25E4)
+  ,((Wingdings3, 0x7B), 0x25E5)
+  ,((Wingdings3, 0x7C), 0x1F780)
+  ,((Wingdings3, 0x7D), 0x1F782)
+  ,((Wingdings3, 0x7E), 0x1F781)
+  ,((Wingdings3, 0x80), 0x1F783)
+  ,((Wingdings3, 0x81), 0x25B2)
+  ,((Wingdings3, 0x82), 0x25BC)
+  ,((Wingdings3, 0x83), 0x25C0)
+  ,((Wingdings3, 0x84), 0x25B6)
+  ,((Wingdings3, 0x85), 0x2B9C)
+  ,((Wingdings3, 0x86), 0x2B9E)
+  ,((Wingdings3, 0x87), 0x2B9D)
+  ,((Wingdings3, 0x88), 0x2B9F)
+  ,((Wingdings3, 0x89), 0x1F810)
+  ,((Wingdings3, 0x8A), 0x1F812)
+  ,((Wingdings3, 0x8B), 0x1F811)
+  ,((Wingdings3, 0x8C), 0x1F813)
+  ,((Wingdings3, 0x8D), 0x1F814)
+  ,((Wingdings3, 0x8E), 0x1F816)
+  ,((Wingdings3, 0x8F), 0x1F815)
+  ,((Wingdings3, 0x90), 0x1F817)
+  ,((Wingdings3, 0x91), 0x1F818)
+  ,((Wingdings3, 0x92), 0x1F81A)
+  ,((Wingdings3, 0x93), 0x1F819)
+  ,((Wingdings3, 0x94), 0x1F81B)
+  ,((Wingdings3, 0x95), 0x1F81C)
+  ,((Wingdings3, 0x96), 0x1F81E)
+  ,((Wingdings3, 0x97), 0x1F81D)
+  ,((Wingdings3, 0x98), 0x1F81F)
+  ,((Wingdings3, 0x99), 0x1F800)
+  ,((Wingdings3, 0x9A), 0x1F802)
+  ,((Wingdings3, 0x9B), 0x1F801)
+  ,((Wingdings3, 0x9C), 0x1F803)
+  ,((Wingdings3, 0x9D), 0x1F804)
+  ,((Wingdings3, 0x9E), 0x1F806)
+  ,((Wingdings3, 0x9F), 0x1F805)
+  ,((Wingdings3, 0xA1), 0x1F808)
+  ,((Wingdings3, 0xA2), 0x1F80A)
+  ,((Wingdings3, 0xA3), 0x1F809)
+  ,((Wingdings3, 0xA4), 0x1F80B)
+  ,((Wingdings3, 0xA5), 0x1F820)
+  ,((Wingdings3, 0xA6), 0x1F822)
+  ,((Wingdings3, 0xA7), 0x1F824)
+  ,((Wingdings3, 0xA8), 0x1F826)
+  ,((Wingdings3, 0xA9), 0x1F828)
+  ,((Wingdings3, 0xAA), 0x1F82A)
+  ,((Wingdings3, 0xAB), 0x1F82C)
+  ,((Wingdings3, 0xAC), 0x1F89C)
+  ,((Wingdings3, 0xAD), 0x1F89D)
+  ,((Wingdings3, 0xAE), 0x1F89E)
+  ,((Wingdings3, 0xAF), 0x1F89F)
+  ,((Wingdings3, 0xB0), 0x1F82E)
+  ,((Wingdings3, 0xB1), 0x1F830)
+  ,((Wingdings3, 0xB2), 0x1F832)
+  ,((Wingdings3, 0xB3), 0x1F834)
+  ,((Wingdings3, 0xB4), 0x1F836)
+  ,((Wingdings3, 0xB5), 0x1F838)
+  ,((Wingdings3, 0xB6), 0x1F83A)
+  ,((Wingdings3, 0xB7), 0x1F839)
+  ,((Wingdings3, 0xB8), 0x1F83B)
+  ,((Wingdings3, 0xB9), 0x1F898)
+  ,((Wingdings3, 0xBA), 0x1F89A)
+  ,((Wingdings3, 0xBB), 0x1F899)
+  ,((Wingdings3, 0xBC), 0x1F89B)
+  ,((Wingdings3, 0xBD), 0x1F83C)
+  ,((Wingdings3, 0xBE), 0x1F83E)
+  ,((Wingdings3, 0xBF), 0x1F83D)
+  ,((Wingdings3, 0xC0), 0x1F83F)
+  ,((Wingdings3, 0xC1), 0x1F840)
+  ,((Wingdings3, 0xC2), 0x1F842)
+  ,((Wingdings3, 0xC3), 0x1F841)
+  ,((Wingdings3, 0xC4), 0x1F843)
+  ,((Wingdings3, 0xC5), 0x1F844)
+  ,((Wingdings3, 0xC6), 0x1F846)
+  ,((Wingdings3, 0xC7), 0x1F845)
+  ,((Wingdings3, 0xC8), 0x1F847)
+  ,((Wingdings3, 0xC9), 0x2BA8)
+  ,((Wingdings3, 0xCA), 0x2BA9)
+  ,((Wingdings3, 0xCB), 0x2BAA)
+  ,((Wingdings3, 0xCC), 0x2BAB)
+  ,((Wingdings3, 0xCD), 0x2BAC)
+  ,((Wingdings3, 0xCE), 0x2BAD)
+  ,((Wingdings3, 0xCF), 0x2BAE)
+  ,((Wingdings3, 0xD0), 0x2BAF)
+  ,((Wingdings3, 0xD1), 0x1F860)
+  ,((Wingdings3, 0xD2), 0x1F862)
+  ,((Wingdings3, 0xD3), 0x1F861)
+  ,((Wingdings3, 0xD4), 0x1F863)
+  ,((Wingdings3, 0xD5), 0x1F864)
+  ,((Wingdings3, 0xD6), 0x1F865)
+  ,((Wingdings3, 0xD7), 0x1F867)
+  ,((Wingdings3, 0xD8), 0x1F866)
+  ,((Wingdings3, 0xD9), 0x1F870)
+  ,((Wingdings3, 0xDA), 0x1F872)
+  ,((Wingdings3, 0xDB), 0x1F871)
+  ,((Wingdings3, 0xDC), 0x1F873)
+  ,((Wingdings3, 0xDD), 0x1F874)
+  ,((Wingdings3, 0xDE), 0x1F875)
+  ,((Wingdings3, 0xDF), 0x1F877)
+  ,((Wingdings3, 0xE0), 0x1F876)
+  ,((Wingdings3, 0xE1), 0x1F880)
+  ,((Wingdings3, 0xE2), 0x1F882)
+  ,((Wingdings3, 0xE3), 0x1F881)
+  ,((Wingdings3, 0xE4), 0x1F883)
+  ,((Wingdings3, 0xE5), 0x1F884)
+  ,((Wingdings3, 0xE6), 0x1F885)
+  ,((Wingdings3, 0xE7), 0x1F887)
+  ,((Wingdings3, 0xE8), 0x1F886)
+  ,((Wingdings3, 0xE9), 0x1F890)
+  ,((Wingdings3, 0xEA), 0x1F892)
+  ,((Wingdings3, 0xEB), 0x1F891)
+  ,((Wingdings3, 0xEC), 0x1F893)
+  ,((Wingdings3, 0xED), 0x1F894)
+  ,((Wingdings3, 0xEE), 0x1F896)
+  ,((Wingdings3, 0xEF), 0x1F895)
+  ,((Wingdings3, 0xF0), 0x1F897)
+  ,((Webdings, 0x21), 0x1F577)
+  ,((Webdings, 0x22), 0x1F578)
+  ,((Webdings, 0x23), 0x1F572)
+  ,((Webdings, 0x24), 0x1F576)
+  ,((Webdings, 0x25), 0x1F3C6)
+  ,((Webdings, 0x26), 0x1F396)
+  ,((Webdings, 0x27), 0x1F587)
+  ,((Webdings, 0x28), 0x1F5E8)
+  ,((Webdings, 0x29), 0x1F5E9)
+  ,((Webdings, 0x2A), 0x1F5F0)
+  ,((Webdings, 0x2B), 0x1F5F1)
+  ,((Webdings, 0x2C), 0x1F336)
+  ,((Webdings, 0x2D), 0x1F397)
+  ,((Webdings, 0x2E), 0x1F67E)
+  ,((Webdings, 0x2F), 0x1F67C)
+  ,((Webdings, 0x30), 0x1F5D5)
+  ,((Webdings, 0x31), 0x1F5D6)
+  ,((Webdings, 0x32), 0x1F5D7)
+  ,((Webdings, 0x33), 0x23F4)
+  ,((Webdings, 0x34), 0x23F5)
+  ,((Webdings, 0x35), 0x23F6)
+  ,((Webdings, 0x36), 0x23F7)
+  ,((Webdings, 0x37), 0x23EA)
+  ,((Webdings, 0x38), 0x23E9)
+  ,((Webdings, 0x39), 0x23EE)
+  ,((Webdings, 0x3A), 0x23ED)
+  ,((Webdings, 0x3B), 0x23F8)
+  ,((Webdings, 0x3C), 0x23F9)
+  ,((Webdings, 0x3D), 0x23FA)
+  ,((Webdings, 0x3E), 0x1F5DA)
+  ,((Webdings, 0x3F), 0x1F5F3)
+  ,((Webdings, 0x40), 0x1F6E0)
+  ,((Webdings, 0x41), 0x1F3D7)
+  ,((Webdings, 0x42), 0x1F3D8)
+  ,((Webdings, 0x43), 0x1F3D9)
+  ,((Webdings, 0x44), 0x1F3DA)
+  ,((Webdings, 0x45), 0x1F3DC)
+  ,((Webdings, 0x46), 0x1F3ED)
+  ,((Webdings, 0x47), 0x1F3DB)
+  ,((Webdings, 0x48), 0x1F3E0)
+  ,((Webdings, 0x49), 0x1F3D6)
+  ,((Webdings, 0x4A), 0x1F3DD)
+  ,((Webdings, 0x4B), 0x1F6E3)
+  ,((Webdings, 0x4C), 0x1F50D)
+  ,((Webdings, 0x4D), 0x1F3D4)
+  ,((Webdings, 0x4E), 0x1F441)
+  ,((Webdings, 0x4F), 0x1F442)
+  ,((Webdings, 0x50), 0x1F3DE)
+  ,((Webdings, 0x51), 0x1F3D5)
+  ,((Webdings, 0x52), 0x1F6E4)
+  ,((Webdings, 0x53), 0x1F3DF)
+  ,((Webdings, 0x54), 0x1F6F3)
+  ,((Webdings, 0x55), 0x1F56C)
+  ,((Webdings, 0x56), 0x1F56B)
+  ,((Webdings, 0x57), 0x1F568)
+  ,((Webdings, 0x58), 0x1F508)
+  ,((Webdings, 0x59), 0x1F394)
+  ,((Webdings, 0x5A), 0x1F395)
+  ,((Webdings, 0x5B), 0x1F5EC)
+  ,((Webdings, 0x5C), 0x1F67D)
+  ,((Webdings, 0x5D), 0x1F5ED)
+  ,((Webdings, 0x5E), 0x1F5EA)
+  ,((Webdings, 0x5F), 0x1F5EB)
+  ,((Webdings, 0x60), 0x2B94)
+  ,((Webdings, 0x61), 0x2714)
+  ,((Webdings, 0x62), 0x1F6B2)
+  ,((Webdings, 0x63), 0x25A1)
+  ,((Webdings, 0x64), 0x1F6E1)
+  ,((Webdings, 0x65), 0x1F4E6)
+  ,((Webdings, 0x66), 0x1F6F1)
+  ,((Webdings, 0x67), 0x25A0)
+  ,((Webdings, 0x68), 0x1F691)
+  ,((Webdings, 0x69), 0x1F6C8)
+  ,((Webdings, 0x6A), 0x1F6E9)
+  ,((Webdings, 0x6B), 0x1F6F0)
+  ,((Webdings, 0x6C), 0x1F7C8)
+  ,((Webdings, 0x6D), 0x1F574)
+  ,((Webdings, 0x6E), 0x26AB)
+  ,((Webdings, 0x6F), 0x1F6E5)
+  ,((Webdings, 0x70), 0x1F694)
+  ,((Webdings, 0x71), 0x1F5D8)
+  ,((Webdings, 0x72), 0x1F5D9)
+  ,((Webdings, 0x73), 0x2753)
+  ,((Webdings, 0x74), 0x1F6F2)
+  ,((Webdings, 0x75), 0x1F687)
+  ,((Webdings, 0x76), 0x1F68D)
+  ,((Webdings, 0x77), 0x26F3)
+  ,((Webdings, 0x78), 0x1F6C7)
+  ,((Webdings, 0x79), 0x2296)
+  ,((Webdings, 0x7A), 0x1F6AD)
+  ,((Webdings, 0x7B), 0x1F5EE)
+  ,((Webdings, 0x7C), 0x007C)
+  ,((Webdings, 0x7D), 0x1F5EF)
+  ,((Webdings, 0x7E), 0x1F5F2)
+  ,((Webdings, 0x80), 0x1F6B9)
+  ,((Webdings, 0x81), 0x1F6BA)
+  ,((Webdings, 0x82), 0x1F6C9)
+  ,((Webdings, 0x83), 0x1F6CA)
+  ,((Webdings, 0x84), 0x1F6BC)
+  ,((Webdings, 0x85), 0x1F47D)
+  ,((Webdings, 0x86), 0x1F3CB)
+  ,((Webdings, 0x87), 0x26F7)
+  ,((Webdings, 0x88), 0x1F3C2)
+  ,((Webdings, 0x89), 0x1F3CC)
+  ,((Webdings, 0x8A), 0x1F3CA)
+  ,((Webdings, 0x8B), 0x1F3C4)
+  ,((Webdings, 0x8C), 0x1F3CD)
+  ,((Webdings, 0x8D), 0x1F3CE)
+  ,((Webdings, 0x8E), 0x1F698)
+  ,((Webdings, 0x8F), 0x1F5E0)
+  ,((Webdings, 0x90), 0x1F6E2)
+  ,((Webdings, 0x91), 0x1F4B0)
+  ,((Webdings, 0x92), 0x1F3F7)
+  ,((Webdings, 0x93), 0x1F4B3)
+  ,((Webdings, 0x94), 0x1F46A)
+  ,((Webdings, 0x95), 0x1F5E1)
+  ,((Webdings, 0x96), 0x1F5E2)
+  ,((Webdings, 0x97), 0x1F5E3)
+  ,((Webdings, 0x98), 0x272F)
+  ,((Webdings, 0x99), 0x1F584)
+  ,((Webdings, 0x9A), 0x1F585)
+  ,((Webdings, 0x9B), 0x1F583)
+  ,((Webdings, 0x9C), 0x1F586)
+  ,((Webdings, 0x9D), 0x1F5B9)
+  ,((Webdings, 0x9E), 0x1F5BA)
+  ,((Webdings, 0x9F), 0x1F5BB)
+  ,((Webdings, 0xA1), 0x1F570)
+  ,((Webdings, 0xA2), 0x1F5BD)
+  ,((Webdings, 0xA3), 0x1F5BE)
+  ,((Webdings, 0xA4), 0x1F4CB)
+  ,((Webdings, 0xA5), 0x1F5D2)
+  ,((Webdings, 0xA6), 0x1F5D3)
+  ,((Webdings, 0xA7), 0x1F4D6)
+  ,((Webdings, 0xA8), 0x1F4DA)
+  ,((Webdings, 0xA9), 0x1F5DE)
+  ,((Webdings, 0xAA), 0x1F5DF)
+  ,((Webdings, 0xAB), 0x1F5C3)
+  ,((Webdings, 0xAC), 0x1F5C2)
+  ,((Webdings, 0xAD), 0x1F5BC)
+  ,((Webdings, 0xAE), 0x1F3AD)
+  ,((Webdings, 0xAF), 0x1F39C)
+  ,((Webdings, 0xB0), 0x1F398)
+  ,((Webdings, 0xB1), 0x1F399)
+  ,((Webdings, 0xB2), 0x1F3A7)
+  ,((Webdings, 0xB3), 0x1F4BF)
+  ,((Webdings, 0xB4), 0x1F39E)
+  ,((Webdings, 0xB5), 0x1F4F7)
+  ,((Webdings, 0xB6), 0x1F39F)
+  ,((Webdings, 0xB7), 0x1F3AC)
+  ,((Webdings, 0xB8), 0x1F4FD)
+  ,((Webdings, 0xB9), 0x1F4F9)
+  ,((Webdings, 0xBA), 0x1F4FE)
+  ,((Webdings, 0xBB), 0x1F4FB)
+  ,((Webdings, 0xBC), 0x1F39A)
+  ,((Webdings, 0xBD), 0x1F39B)
+  ,((Webdings, 0xBE), 0x1F4FA)
+  ,((Webdings, 0xBF), 0x1F4BB)
+  ,((Webdings, 0xC0), 0x1F5A5)
+  ,((Webdings, 0xC1), 0x1F5A6)
+  ,((Webdings, 0xC2), 0x1F5A7)
+  ,((Webdings, 0xC3), 0x1F579)
+  ,((Webdings, 0xC4), 0x1F3AE)
+  ,((Webdings, 0xC5), 0x1F57B)
+  ,((Webdings, 0xC6), 0x1F57C)
+  ,((Webdings, 0xC7), 0x1F4DF)
+  ,((Webdings, 0xC8), 0x1F581)
+  ,((Webdings, 0xC9), 0x1F580)
+  ,((Webdings, 0xCA), 0x1F5A8)
+  ,((Webdings, 0xCB), 0x1F5A9)
+  ,((Webdings, 0xCC), 0x1F5BF)
+  ,((Webdings, 0xCD), 0x1F5AA)
+  ,((Webdings, 0xCE), 0x1F5DC)
+  ,((Webdings, 0xCF), 0x1F512)
+  ,((Webdings, 0xD0), 0x1F513)
+  ,((Webdings, 0xD1), 0x1F5DD)
+  ,((Webdings, 0xD2), 0x1F4E5)
+  ,((Webdings, 0xD3), 0x1F4E4)
+  ,((Webdings, 0xD4), 0x1F573)
+  ,((Webdings, 0xD5), 0x1F323)
+  ,((Webdings, 0xD6), 0x1F324)
+  ,((Webdings, 0xD7), 0x1F325)
+  ,((Webdings, 0xD8), 0x1F326)
+  ,((Webdings, 0xD9), 0x2601)
+  ,((Webdings, 0xDA), 0x1F327)
+  ,((Webdings, 0xDB), 0x1F328)
+  ,((Webdings, 0xDC), 0x1F329)
+  ,((Webdings, 0xDD), 0x1F32A)
+  ,((Webdings, 0xDE), 0x1F32C)
+  ,((Webdings, 0xDF), 0x1F32B)
+  ,((Webdings, 0xE0), 0x1F31C)
+  ,((Webdings, 0xE1), 0x1F321)
+  ,((Webdings, 0xE2), 0x1F6CB)
+  ,((Webdings, 0xE3), 0x1F6CF)
+  ,((Webdings, 0xE4), 0x1F37D)
+  ,((Webdings, 0xE5), 0x1F378)
+  ,((Webdings, 0xE6), 0x1F6CE)
+  ,((Webdings, 0xE7), 0x1F6CD)
+  ,((Webdings, 0xE8), 0x24C5)
+  ,((Webdings, 0xE9), 0x267F)
+  ,((Webdings, 0xEA), 0x1F6C6)
+  ,((Webdings, 0xEB), 0x1F588)
+  ,((Webdings, 0xEC), 0x1F393)
+  ,((Webdings, 0xED), 0x1F5E4)
+  ,((Webdings, 0xEE), 0x1F5E5)
+  ,((Webdings, 0xEF), 0x1F5E6)
+  ,((Webdings, 0xF0), 0x1F5E7)
+  ,((Webdings, 0xF1), 0x1F6EA)
+  ,((Webdings, 0xF2), 0x1F43F)
+  ,((Webdings, 0xF3), 0x1F426)
+  ,((Webdings, 0xF4), 0x1F41F)
+  ,((Webdings, 0xF5), 0x1F415)
+  ,((Webdings, 0xF6), 0x1F408)
+  ,((Webdings, 0xF7), 0x1F66C)
+  ,((Webdings, 0xF8), 0x1F66E)
+  ,((Webdings, 0xF9), 0x1F66D)
+  ,((Webdings, 0xFA), 0x1F66F)
+  ,((Webdings, 0xFB), 0x1F5FA)
+  ,((Webdings, 0xFC), 0x1F30D)
+  ,((Webdings, 0xFD), 0x1F30F)
+  ,((Webdings, 0xFE), 0x1F30E)
+  ,((Webdings, 0xFF), 0x1F54A)
+  ,((Symbol,0x20), 0xA0)
+  ,((Symbol,0x21), 0x21)
+  ,((Symbol,0x22), 0x2200)
+  ,((Symbol,0x23), 0x23)
+  ,((Symbol,0x24), 0x2203)
+  ,((Symbol,0x25), 0x25)
+  ,((Symbol,0x26), 0x26)
+  ,((Symbol,0x27), 0x220B)
+  ,((Symbol,0x28), 0x28)
+  ,((Symbol,0x29), 0x29)
+  ,((Symbol,0x2A), 0x2217)
+  ,((Symbol,0x2B), 0x2B)
+  ,((Symbol,0x2C), 0x2C)
+  ,((Symbol,0x2D), 0x2212)
+  ,((Symbol,0x2E), 0x2E)
+  ,((Symbol,0x2F), 0x2F)
+  ,((Symbol,0x30), 0x30)
+  ,((Symbol,0x31), 0x31)
+  ,((Symbol,0x32), 0x32)
+  ,((Symbol,0x33), 0x33)
+  ,((Symbol,0x34), 0x34)
+  ,((Symbol,0x35), 0x35)
+  ,((Symbol,0x36), 0x36)
+  ,((Symbol,0x37), 0x37)
+  ,((Symbol,0x38), 0x38)
+  ,((Symbol,0x39), 0x39)
+  ,((Symbol,0x3A), 0x3A)
+  ,((Symbol,0x3B), 0x3B)
+  ,((Symbol,0x3C), 0x3C)
+  ,((Symbol,0x3D), 0x3D)
+  ,((Symbol,0x3E), 0x3E)
+  ,((Symbol,0x3F), 0x3F)
+  ,((Symbol,0x40), 0x2245)
+  ,((Symbol,0x41), 0x391)
+  ,((Symbol,0x42), 0x392)
+  ,((Symbol,0x43), 0x3A7)
+  ,((Symbol,0x44), 0x2206)
+  ,((Symbol,0x45), 0x395)
+  ,((Symbol,0x46), 0x3A6)
+  ,((Symbol,0x47), 0x393)
+  ,((Symbol,0x48), 0x397)
+  ,((Symbol,0x49), 0x399)
+  ,((Symbol,0x4A), 0x3D1)
+  ,((Symbol,0x4B), 0x39A)
+  ,((Symbol,0x4C), 0x39B)
+  ,((Symbol,0x4D), 0x39C)
+  ,((Symbol,0x4E), 0x39D)
+  ,((Symbol,0x4F), 0x39F)
+  ,((Symbol,0x50), 0x3A0)
+  ,((Symbol,0x51), 0x398)
+  ,((Symbol,0x52), 0x3A1)
+  ,((Symbol,0x53), 0x3A3)
+  ,((Symbol,0x54), 0x3A4)
+  ,((Symbol,0x55), 0x3A5)
+  ,((Symbol,0x56), 0x3C2)
+  ,((Symbol,0x57), 0x2126)
+  ,((Symbol,0x58), 0x39E)
+  ,((Symbol,0x59), 0x3A8)
+  ,((Symbol,0x5A), 0x396)
+  ,((Symbol,0x5B), 0x5B)
+  ,((Symbol,0x5C), 0x2234)
+  ,((Symbol,0x5D), 0x5D)
+  ,((Symbol,0x5E), 0x22A5)
+  ,((Symbol,0x5F), 0x5F)
+  ,((Symbol,0x60), 0xF8E5)
+  ,((Symbol,0x61), 0x3B1)
+  ,((Symbol,0x62), 0x3B2)
+  ,((Symbol,0x63), 0x3C7)
+  ,((Symbol,0x64), 0x3B4)
+  ,((Symbol,0x65), 0x3B5)
+  ,((Symbol,0x66), 0x3C6)
+  ,((Symbol,0x67), 0x3B3)
+  ,((Symbol,0x68), 0x3B7)
+  ,((Symbol,0x69), 0x3B9)
+  ,((Symbol,0x6A), 0x3D5)
+  ,((Symbol,0x6B), 0x3BA)
+  ,((Symbol,0x6C), 0x3BB)
+  ,((Symbol,0x6D), 0x3BC)
+  ,((Symbol,0x6E), 0x3BD)
+  ,((Symbol,0x6F), 0x3BF)
+  ,((Symbol,0x70), 0x3C0)
+  ,((Symbol,0x71), 0x3B8)
+  ,((Symbol,0x72), 0x3C1)
+  ,((Symbol,0x73), 0x3C3)
+  ,((Symbol,0x74), 0x3C4)
+  ,((Symbol,0x75), 0x3C5)
+  ,((Symbol,0x76), 0x3D6)
+  ,((Symbol,0x77), 0x3C9)
+  ,((Symbol,0x78), 0x3BE)
+  ,((Symbol,0x79), 0x3C8)
+  ,((Symbol,0x7A), 0x3B6)
+  ,((Symbol,0x7B), 0x7B)
+  ,((Symbol,0x7C), 0x7C)
+  ,((Symbol,0x7D), 0x7D)
+  ,((Symbol,0x7E), 0x223C)
+  ,((Symbol,0xA0), 0x20AC)
+  ,((Symbol,0xA1), 0x3D2)
+  ,((Symbol,0xA2), 0x2032)
+  ,((Symbol,0xA3), 0x2264)
+  ,((Symbol,0xA4), 0x2215)
+  ,((Symbol,0xA5), 0x221E)
+  ,((Symbol,0xA6), 0x192)
+  ,((Symbol,0xA7), 0x2663)
+  ,((Symbol,0xA8), 0x2666)
+  ,((Symbol,0xA9), 0x2665)
+  ,((Symbol,0xAA), 0x2660)
+  ,((Symbol,0xAB), 0x2194)
+  ,((Symbol,0xAC), 0x2190)
+  ,((Symbol,0xAD), 0x2191)
+  ,((Symbol,0xAE), 0x2192)
+  ,((Symbol,0xAF), 0x2193)
+  ,((Symbol,0xB0), 0xB0)
+  ,((Symbol,0xB1), 0xB1)
+  ,((Symbol,0xB2), 0x2033)
+  ,((Symbol,0xB3), 0x2265)
+  ,((Symbol,0xB4), 0xD7)
+  ,((Symbol,0xB5), 0x221D)
+  ,((Symbol,0xB6), 0x2202)
+  ,((Symbol,0xB7), 0x2022)
+  ,((Symbol,0xB8), 0xF7)
+  ,((Symbol,0xB9), 0x2260)
+  ,((Symbol,0xBA), 0x2261)
+  ,((Symbol,0xBB), 0x2248)
+  ,((Symbol,0xBC), 0x2026)
+  ,((Symbol,0xBD), 0xF8E6)
+  ,((Symbol,0xBE), 0xF8E7)
+  ,((Symbol,0xBF), 0x21B5)
+  ,((Symbol,0xC0), 0x2135)
+  ,((Symbol,0xC1), 0x2111)
+  ,((Symbol,0xC2), 0x211C)
+  ,((Symbol,0xC3), 0x2118)
+  ,((Symbol,0xC4), 0x2297)
+  ,((Symbol,0xC5), 0x2295)
+  ,((Symbol,0xC6), 0x2205)
+  ,((Symbol,0xC7), 0x2229)
+  ,((Symbol,0xC8), 0x222A)
+  ,((Symbol,0xC9), 0x2283)
+  ,((Symbol,0xCA), 0x2287)
+  ,((Symbol,0xCB), 0x2284)
+  ,((Symbol,0xCC), 0x2282)
+  ,((Symbol,0xCD), 0x2286)
+  ,((Symbol,0xCE), 0x2208)
+  ,((Symbol,0xCF), 0x2209)
+  ,((Symbol,0xD0), 0x2220)
+  ,((Symbol,0xD1), 0x2207)
+  ,((Symbol,0xD2), 0xF6DA)
+  ,((Symbol,0xD3), 0xF6D9)
+  ,((Symbol,0xD4), 0xF6DB)
+  ,((Symbol,0xD5), 0x220F)
+  ,((Symbol,0xD6), 0x221A)
+  ,((Symbol,0xD7), 0x22C5)
+  ,((Symbol,0xD8), 0xAC)
+  ,((Symbol,0xD9), 0x2227)
+  ,((Symbol,0xDA), 0x2228)
+  ,((Symbol,0xDB), 0x21D4)
+  ,((Symbol,0xDC), 0x21D0)
+  ,((Symbol,0xDD), 0x21D1)
+  ,((Symbol,0xDE), 0x21D2)
+  ,((Symbol,0xDF), 0x21D3)
+  ,((Symbol,0xE0), 0x25CA)
+  ,((Symbol,0xE1), 0x2329)
+  ,((Symbol,0xE2), 0xF8E8)
+  ,((Symbol,0xE3), 0xF8E9)
+  ,((Symbol,0xE4), 0xF8EA)
+  ,((Symbol,0xE5), 0x2211)
+  ,((Symbol,0xE6), 0xF8EB)
+  ,((Symbol,0xE7), 0xF8EC)
+  ,((Symbol,0xE8), 0xF8ED)
+  ,((Symbol,0xE9), 0xF8EE)
+  ,((Symbol,0xEA), 0xF8EF)
+  ,((Symbol,0xEB), 0xF8F0)
+  ,((Symbol,0xEC), 0xF8F1)
+  ,((Symbol,0xED), 0xF8F2)
+  ,((Symbol,0xEE), 0xF8F3)
+  ,((Symbol,0xEF), 0xF8F4)
+  ,((Symbol,0xF1), 0x232A)
+  ,((Symbol,0xF2), 0x222B)
+  ,((Symbol,0xF3), 0x2320)
+  ,((Symbol,0xF4), 0xF8F5)
+  ,((Symbol,0xF5), 0x2321)
+  ,((Symbol,0xF6), 0xF8F6)
+  ,((Symbol,0xF7), 0xF8F7)
+  ,((Symbol,0xF8), 0xF8F8)
+  ,((Symbol,0xF9), 0xF8F9)
+  ,((Symbol,0xFA), 0xF8FA)
+  ,((Symbol,0xFB), 0xF8FB)
+  ,((Symbol,0xFC), 0xF8FC)
+  ,((Symbol,0xFD), 0xF8FD)
+  ,((Symbol,0xFE), 0xF8FE)
+  ]
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,3 +1,17 @@
+{-# LANGUAGE OverloadedStrings #-}
+{- |
+   Module      : Text.Pandoc.Readers.Docx.Util
+   Copyright   : © 2014-2020 Jesse Rosenthal <jrosenthal@jhu.edu>,
+                   2014-2024 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
@@ -5,42 +19,27 @@
                                       , elemToNameSpaces
                                       , findChildByName
                                       , findChildrenByName
+                                      , findElementByName
                                       , findAttrByName
+                                      , extractChildren
                                       ) where
 
-import Data.Maybe (mapMaybe)
-import Text.XML.Light
+import Data.List (partition)
+import Text.Pandoc.XML.Light
+import Text.Pandoc.Readers.OOXML.Shared
+  (NameSpaces, elemName, isElem, elemToNameSpaces,
+   findChildByName, findChildrenByName, findElementByName, findAttrByName)
 
-type NameSpaces = [(String, String)]
 
-elemToNameSpaces :: Element -> NameSpaces
-elemToNameSpaces = mapMaybe attrToNSPair . elAttribs
-
-attrToNSPair :: Attr -> Maybe (String, String)
-attrToNSPair (Attr (QName s _ (Just "xmlns")) val) = Just (s, val)
-attrToNSPair _                                     = Nothing
-
-elemName :: NameSpaces -> String -> String -> QName
-elemName ns prefix name =
-  QName name (lookup prefix ns) (if null prefix then Nothing else Just prefix)
-
-isElem :: NameSpaces -> String -> String -> Element -> Bool
-isElem ns prefix name element =
-  let ns' = ns ++ elemToNameSpaces element
-  in qName (elName element) == name &&
-     qURI (elName element) == lookup prefix ns'
-
-findChildByName :: NameSpaces -> String -> String -> Element -> Maybe Element
-findChildByName ns pref name el =
-  let ns' = ns ++ elemToNameSpaces el
-  in  findChild (elemName ns' pref name) el
-
-findChildrenByName :: NameSpaces -> String -> String -> Element -> [Element]
-findChildrenByName ns pref name el =
-  let ns' = ns ++ elemToNameSpaces el
-  in  findChildren (elemName ns' pref name) el
+-- | Removes child elements that satisfy a given condition.
+-- Returns the modified element and the list of removed children.
+extractChildren :: Element -> (Element -> Bool) -> Maybe (Element, [Element])
+extractChildren el condition
+  | null removedChildren = Nothing  -- No children removed, return Nothing
+  | otherwise = Just (modifiedElement, removedChildren)  -- Children removed, return Just
+  where
+    -- Separate the children based on the condition
+    (removedChildren, keptChildren) = partition condition (onlyElems $ elContent el)
 
-findAttrByName :: NameSpaces -> String -> String -> Element -> Maybe String
-findAttrByName ns pref name el =
-  let ns' = ns ++ elemToNameSpaces el
-  in  findAttr (elemName ns' pref name) el
+    -- Reconstruct the element with the kept children
+    modifiedElement = el { elContent = map Elem keptChildren }
diff --git a/src/Text/Pandoc/Readers/DokuWiki.hs b/src/Text/Pandoc/Readers/DokuWiki.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Readers/DokuWiki.hs
@@ -0,0 +1,571 @@
+{-# LANGUAGE FlexibleContexts  #-}
+{-# LANGUAGE OverloadedStrings #-}
+{-# LANGUAGE TupleSections     #-}
+{-# LANGUAGE ViewPatterns      #-}
+{- |
+   Module      : Text.Pandoc.Readers.DokuWiki
+   Copyright   : Copyright (C) 2018-2020 Alexander Krotov
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : Alexander Krotov <ilabdsf@gmail.com>
+   Stability   : alpha
+   Portability : portable
+
+Conversion of DokuWiki text to 'Pandoc' document.
+-}
+module Text.Pandoc.Readers.DokuWiki (readDokuWiki) where
+
+import Control.Monad
+import Control.Monad.Except (throwError)
+import Data.Char (isAlphaNum, isDigit)
+import qualified Data.Foldable as F
+import Data.Maybe (fromMaybe, catMaybes)
+import Data.Bifunctor (second)
+import Data.Text (Text)
+import qualified Data.Text as T
+import qualified Text.Pandoc.Builder as B
+import Text.Pandoc.Class.PandocMonad (PandocMonad (..))
+import Text.Pandoc.Definition
+import Text.Pandoc.Options
+import Text.Pandoc.Parsing hiding (enclosed)
+import Text.Pandoc.Shared (trim, stringify, tshow)
+import Data.List (isPrefixOf, isSuffixOf, groupBy)
+import qualified Safe
+
+-- | Read DokuWiki from an input string and return a Pandoc document.
+readDokuWiki :: (PandocMonad m, ToSources a)
+             => ReaderOptions
+             -> a
+             -> m Pandoc
+readDokuWiki opts s = do
+  let sources = toSources s
+  res <- runParserT parseDokuWiki def {stateOptions = opts }
+           (initialSourceName sources) sources
+  case res of
+       Left e  -> throwError $ fromParsecError sources e
+       Right d -> return d
+
+type DWParser = ParsecT Sources ParserState
+
+-- * Utility functions
+
+-- | Parse end-of-line, which can be either a newline or end-of-file.
+eol :: (Stream s m Char, UpdateSourcePos s Char) => ParsecT s st m ()
+eol = void newline <|> eof
+
+guardColumnOne :: PandocMonad m => DWParser m ()
+guardColumnOne = getPosition >>= \pos -> guard (sourceColumn pos == 1)
+
+-- | Parse DokuWiki document.
+parseDokuWiki :: PandocMonad m => DWParser m Pandoc
+parseDokuWiki =
+  B.doc . mconcat <$> many block <* spaces <* eof
+
+-- | Parse <code> and <file> attributes
+codeLanguage :: PandocMonad m => DWParser m (Text, [Text], [(Text, Text)])
+codeLanguage = try $ do
+  rawLang <- option "-" (spaceChar *> manyTillChar anyChar (lookAhead (spaceChar <|> char '>')))
+  let attr = case rawLang of
+               "-" -> []
+               l -> [l]
+  return ("", attr, [])
+
+-- | Generic parser for <code> and <file> tags
+codeTag :: PandocMonad m
+        => ((Text, [Text], [(Text, Text)]) -> Text -> a)
+        -> Text
+        -> DWParser m a
+codeTag f tag = try $ f
+  <$  char '<'
+  <*  textStr tag
+  <*> codeLanguage
+  <*  manyTill anyChar (char '>')
+  <*  optional (manyTill spaceChar eol)
+  <*> manyTillChar anyChar (try $ string "</" <* textStr tag <* char '>')
+
+-- * Inline parsers
+
+-- | Parse any inline element but softbreak.
+inline' :: PandocMonad m => DWParser m B.Inlines
+inline' = whitespace
+      <|> inline''
+
+-- | Parse any inline element but whitespace.
+inline'' :: PandocMonad m => DWParser m B.Inlines
+inline'' = br
+      <|> bold
+      <|> italic
+      <|> underlined
+      <|> nowiki
+      <|> percent
+      <|> link
+      <|> image
+      <|> monospaced
+      <|> subscript
+      <|> superscript
+      <|> deleted
+      <|> footnote
+      <|> inlineRaw
+      <|> math
+      <|> autoLink
+      <|> autoEmail
+      <|> notoc
+      <|> nocache
+      <|> smartPunctuation inline
+      <|> str
+      <|> symbol
+      <?> "inline"
+
+-- | Parse any inline element but soft breaks and do not consolidate spaces.
+inlineUnconsolidatedWhitespace :: PandocMonad m => DWParser m B.Inlines
+inlineUnconsolidatedWhitespace = (B.space <$ spaceChar) <|> inline'
+
+-- | Parse any inline element, including soft break.
+inline :: PandocMonad m => DWParser m B.Inlines
+inline = endline <|> inline'
+
+endline :: PandocMonad m => DWParser m B.Inlines
+endline = try $ B.softbreak <$ skipMany spaceChar <* linebreak
+
+whitespace :: PandocMonad m => DWParser m B.Inlines
+whitespace = try $ B.space <$ skipMany1 spaceChar
+
+br :: PandocMonad m => DWParser m B.Inlines
+br = try $ B.linebreak <$ string "\\\\" <* space
+
+linebreak :: PandocMonad m => DWParser m B.Inlines
+linebreak = newline >> notFollowedBy newline >> (lastNewline <|> innerNewline)
+  where lastNewline  = mempty <$ eof
+        innerNewline = pure B.space
+
+between :: (Monoid c, PandocMonad m, Show b)
+        => DWParser m a -> DWParser m b -> (DWParser m b -> DWParser m c)
+        -> DWParser m c
+between start end p =
+  mconcat <$> try (start >> notFollowedBy whitespace >> many1Till (p end) end)
+
+enclosed :: (Monoid b, PandocMonad m, Show a)
+         => DWParser m a -> (DWParser m a -> DWParser m b) -> DWParser m b
+enclosed sep p = between sep (try sep) p
+
+nestedInlines :: (Show a, PandocMonad m)
+              => DWParser m a -> DWParser m B.Inlines
+nestedInlines end = innerSpace <|> nestedInline
+  where
+    innerSpace   = try $ whitespace <* notFollowedBy end
+    nestedInline = notFollowedBy whitespace >> inline
+
+bold :: PandocMonad m => DWParser m B.Inlines
+bold = try $ B.strong <$> enclosed (string "**") nestedInlines
+
+italic :: PandocMonad m => DWParser m B.Inlines
+italic = try $ B.emph <$> enclosed (string "//") nestedInlines
+
+underlined :: PandocMonad m => DWParser m B.Inlines
+underlined = try $ B.underline <$> enclosed (string "__") nestedInlines
+
+nowiki :: PandocMonad m => DWParser m B.Inlines
+nowiki = try $ B.text <$ string "<nowiki>" <*> manyTillChar anyChar (try $ string "</nowiki>")
+
+percent :: PandocMonad m => DWParser m B.Inlines
+percent = try $ B.text <$> enclosed (string "%%") nestedText
+
+nestedText :: (Show a, PandocMonad m)
+             => DWParser m a -> DWParser m Text
+nestedText end = innerSpace <|> countChar 1 nonspaceChar
+  where
+    innerSpace = try $ many1Char spaceChar <* notFollowedBy end
+
+monospaced :: PandocMonad m => DWParser m B.Inlines
+monospaced = try $ B.code . (T.concat . map stringify . B.toList) <$> enclosed (string "''") nestedInlines
+
+subscript :: PandocMonad m => DWParser m B.Inlines
+subscript = try $ B.subscript <$> between (string "<sub>") (try $ string "</sub>") nestedInlines
+
+superscript :: PandocMonad m => DWParser m B.Inlines
+superscript = try $ B.superscript <$> between (string "<sup>") (try $ string "</sup>") nestedInlines
+
+deleted :: PandocMonad m => DWParser m B.Inlines
+deleted = try $ B.strikeout <$> between (string "<del>") (try $ string "</del>") nestedInlines
+
+-- | Parse a footnote.
+footnote :: PandocMonad m => DWParser m B.Inlines
+footnote = try $ B.note . B.para <$> between (string "((") (try $ string "))") nestedInlines
+
+inlineRaw :: PandocMonad m => DWParser m B.Inlines
+inlineRaw = try $ do
+  char '<'
+  fmt <- oneOfStrings ["html", "php", "latex"]
+  -- LaTeX via https://www.dokuwiki.org/plugin:latex
+  char '>'
+  contents <- manyTillChar anyChar
+                (try $ string "</" *> string (T.unpack fmt) *> char '>')
+  return $
+    case T.toLower fmt of
+         "php" -> B.rawInline "html" $ "<?php " <> contents <> " ?>"
+         f -> B.rawInline f contents
+
+-- see https://www.dokuwiki.org/plugin:latex
+math :: PandocMonad m => DWParser m B.Inlines
+math = (B.displayMath <$> mathDisplay) <|> (B.math <$> mathInline)
+
+makeLink :: (Text, Text) -> B.Inlines
+makeLink (text, url) = B.link url "" $ B.str text
+
+autoEmail :: PandocMonad m => DWParser m B.Inlines
+autoEmail = try $ do
+  state <- getState
+  guard $ stateAllowLinks state
+  makeLink <$ char '<' <*> emailAddress <* char '>'
+
+autoLink :: PandocMonad m => DWParser m B.Inlines
+autoLink = try $ do
+  state <- getState
+  guard $ stateAllowLinks state
+  (text, url) <- uri
+  guard $ not $ T.isInfixOf "%%//%%" text  -- see #9153
+  guard $ checkLink (T.last url)
+  return $ makeLink (text, url)
+  where
+    checkLink c
+      | c == '/' = True
+      | otherwise = isAlphaNum c
+
+notoc :: PandocMonad m => DWParser m B.Inlines
+notoc = try $ mempty <$ string "~~NOTOC~~"
+
+nocache :: PandocMonad m => DWParser m B.Inlines
+nocache = try $ mempty <$ string "~~NOCACHE~~"
+
+str :: PandocMonad m => DWParser m B.Inlines
+str = B.str <$> (many1Char alphaNum <|> characterReference)
+
+symbol :: PandocMonad m => DWParser m B.Inlines
+symbol = B.str <$> (notFollowedBy' blockCode *> countChar 1 nonspaceChar)
+
+link :: PandocMonad m => DWParser m B.Inlines
+link = try $ do
+  st <- getState
+  guard $ stateAllowLinks st
+  setState $ st{ stateAllowLinks = False }
+  l <- linkText
+  setState $ st{ stateAllowLinks = True }
+  return l
+
+isExternalLink :: Text -> Bool
+isExternalLink s = "://" `T.isPrefixOf` sSuff
+  where
+    sSuff = T.dropWhile (\c -> isAlphaNum c || (c `elem` ['-', '.', '+'])) s
+
+isAbsolutePath :: Text -> Bool
+isAbsolutePath (T.uncons -> Just ('.', _)) = False
+isAbsolutePath s = T.any (== ':') s
+
+normalizeDots :: Text -> Text
+normalizeDots path
+  | not (T.null pref) = case T.uncons suff of
+      Just (':', _) -> path
+      _             -> pref <> ":" <> suff
+  | otherwise = path
+  where
+    (pref, suff) = T.span (== '.') path
+
+normalizeInternalPath :: Text -> Text
+normalizeInternalPath path =
+  if isAbsolutePath path
+    then ensureAbsolute normalizedPath
+    else normalizedPath
+  where
+    normalizedPath = T.intercalate "/" $ dropWhile (== ".") $ T.splitOn ":" $ normalizeDots path
+    ensureAbsolute s@(T.uncons -> Just ('/', _)) = s
+    ensureAbsolute s = "/" <> s
+
+normalizePath :: Text -> Text
+normalizePath path =
+  if isExternalLink path
+    then path
+    else normalizeInternalPath path
+
+urlToText :: Text -> Text
+urlToText url =
+  if isExternalLink url
+    then url
+    else T.takeWhileEnd (/= ':') url
+
+-- Parse link or image
+parseLink :: PandocMonad m
+          => (Text -> Maybe B.Inlines -> B.Inlines)
+          -> Text
+          -> Text
+          -> DWParser m B.Inlines
+parseLink f l r = f
+  <$  textStr l
+  <*> many1TillChar anyChar (lookAhead (void (char '|') <|> try (void $ textStr r)))
+  <*> ( (char '|' *> optionMaybe (B.trimInlines . B.text . T.pack <$>
+                       many1Till anyChar (lookAhead (try (textStr r)))))
+       <|> pure Nothing
+      )
+  <* textStr r
+
+-- | Split Interwiki link into left and right part
+-- | Return Nothing if it is not Interwiki link
+splitInterwiki :: Text -> Maybe (Text, Text)
+splitInterwiki path =
+  case T.span (\c -> isAlphaNum c || c == '.') path of
+    (l, T.uncons -> Just ('>', r)) -> Just (l, r)
+    _ -> Nothing
+
+interwikiToUrl :: Text -> Text -> Text
+interwikiToUrl "callto" page = "callto://" <> page
+interwikiToUrl "doku" page = "https://www.dokuwiki.org/" <> page
+interwikiToUrl "phpfn" page = "https://secure.php.net/" <> page
+interwikiToUrl "tel" page = "tel:" <> page
+interwikiToUrl "wp" page = "https://en.wikipedia.org/wiki/" <> page
+interwikiToUrl "wpde" page = "https://de.wikipedia.org/wiki/" <> page
+interwikiToUrl "wpes" page = "https://es.wikipedia.org/wiki/" <> page
+interwikiToUrl "wpfr" page = "https://fr.wikipedia.org/wiki/" <> page
+interwikiToUrl "wpjp" page = "https://jp.wikipedia.org/wiki/" <> page
+interwikiToUrl "wppl" page = "https://pl.wikipedia.org/wiki/" <> page
+interwikiToUrl unknown page = unknown <> ">" <> page
+
+linkText :: PandocMonad m => DWParser m B.Inlines
+linkText = parseLink fromRaw "[[" "]]"
+  where
+    fromRaw path description =
+      B.link normalizedPath "" (fromMaybe (B.str defaultDescription) description)
+      where
+        path' = trim path
+        interwiki = splitInterwiki path'
+        normalizedPath =
+          case interwiki of
+            Nothing -> normalizePath path'
+            Just (l, r) -> interwikiToUrl l r
+        defaultDescription =
+          case interwiki of
+            Nothing -> urlToText path'
+            Just (_, r) -> r
+
+-- Matches strings like "100x100" (width x height) and "50" (width)
+isWidthHeightParameter :: Text -> Bool
+isWidthHeightParameter s =
+  case T.uncons s of
+    Just (x, xs) ->
+      isDigit x && case T.uncons $ T.dropWhile isDigit xs of
+                     Just ('x', ys) | not (T.null ys) -> T.all isDigit ys
+                     Nothing -> True
+                     _ -> False
+    _ -> False
+
+parseWidthHeight :: Text -> (Maybe Text, Maybe Text)
+parseWidthHeight s = (width, height)
+  where
+    width = Just $ T.takeWhile isDigit s
+    height =
+      case T.uncons $ T.dropWhile isDigit s of
+        Just ('x', xs) -> Just xs
+        _ -> Nothing
+
+image :: PandocMonad m => DWParser m B.Inlines
+image = try $ parseLink fromRaw "{{" "}}"
+  where
+    fromRaw path description =
+      if linkOnly
+        then B.link normalizedPath "" (fromMaybe defaultDescription description)
+        else B.imageWith ("", classes, attributes) normalizedPath "" (fromMaybe defaultDescription description)
+      where
+        (path', parameters) = T.span (/= '?') $ trim path
+        normalizedPath = normalizePath path'
+        leftPadding = " " `T.isPrefixOf` path
+        rightPadding = " " `T.isSuffixOf` path
+        classes =
+          case (leftPadding, rightPadding) of
+            (False, False) -> []
+            (False, True) -> ["align-left"]
+            (True, False) -> ["align-right"]
+            (True, True) -> ["align-center"]
+        parameterList = T.splitOn "&" $ T.drop 1 parameters
+        linkOnly = "linkonly" `elem` parameterList
+        (width, height) = maybe (Nothing, Nothing) parseWidthHeight (F.find isWidthHeightParameter parameterList)
+        attributes = catMaybes [
+                fmap ("width",) width,
+                fmap ("height",) height,
+                fmap ("query",) (if T.null parameters then Nothing else Just parameters)
+            ]
+        defaultDescription = B.str $ urlToText path'
+
+-- * Block parsers
+
+block :: PandocMonad m => DWParser m B.Blocks
+block = do
+  res <- mempty <$ skipMany1 blankline
+         <|> blockElements
+         <|> para
+  skipMany blankline
+  trace (T.take 60 $ tshow $ B.toList res)
+  return res
+
+blockElements :: PandocMonad m => DWParser m B.Blocks
+blockElements = horizontalLine
+            <|> header
+            <|> list "  "
+            <|> indentedCode
+            <|> quote
+            <|> blockCode
+            <|> blockRaw
+            <|> table
+
+horizontalLine :: PandocMonad m => DWParser m B.Blocks
+horizontalLine = try $ B.horizontalRule <$ string "---" <* many1 (char '-') <* eol
+
+header :: PandocMonad m => DWParser m B.Blocks
+header = try $ do
+  guardColumnOne
+  eqs <- many1 (char '=')
+  let lev = length eqs
+  guard $ lev < 7
+  contents <- B.trimInlines . mconcat <$> manyTill inline (try $ char '=' *> many1 (char '='))
+  attr <- registerHeader nullAttr contents
+  return $ B.headerWith attr (7 - lev) contents
+
+list :: PandocMonad m => Text -> DWParser m B.Blocks
+list prefix = bulletList prefix <|> orderedList prefix
+
+bulletList :: PandocMonad m => Text -> DWParser m B.Blocks
+bulletList prefix = try $ B.bulletList <$> parseList prefix '*'
+
+orderedList :: PandocMonad m => Text -> DWParser m B.Blocks
+orderedList prefix = try $ B.orderedList <$> parseList prefix '-'
+
+parseList :: PandocMonad m
+          => Text
+          -> Char
+          -> DWParser m [B.Blocks]
+parseList prefix marker =
+  many1 ((<>) <$> item <*> fmap mconcat (many continuation))
+  where
+    continuation = try $ list ("  " <> prefix)
+    item = try $ textStr prefix *>
+                   optional (char ' ') *>  -- see #8863
+                   char marker *> char ' ' *>
+                   (mconcat <$> many1 itemContents <* eol)
+    itemContents = (B.plain . mconcat <$> many1 inline') <|>
+                   blockCode
+
+indentedCode :: PandocMonad m => DWParser m B.Blocks
+indentedCode = try $ B.codeBlock . T.unlines <$> many1 indentedLine
+ where
+   indentedLine = try $ string "  " *> manyTillChar anyChar eol
+
+-- Note that block quotes in dokuwiki parse as lists of hard-break
+-- separated lines; see #6461.
+quote :: PandocMonad m => DWParser m B.Blocks
+quote = go <$> many1 blockQuoteLine
+ where
+   blockQuoteLine = try $ do
+     lev <- length <$> many1 (char '>')
+     skipMany spaceChar
+     contents <- (blockCode <* skipMany spaceChar <* optional eol) <|>
+       (B.plain . B.trimInlines . mconcat <$> many1Till inline' eol)
+     pure (lev, contents)
+   go [] = mempty
+   go xs = mconcat $ map go' (groupBy (\(x,_) (y,_) -> (x == 0 && y == 0) ||
+                                                        (x > 0 && y > 0)) xs)
+   go' [] = mempty
+   go' xs@((0,_):_) =
+        let (lns, bls) = F.foldl' consolidatePlains (mempty,mempty) (map snd xs)
+         in bls <> if lns == mempty
+                      then mempty
+                      else B.plain lns
+   go' xs = B.blockQuote (go $ map (\(x,y) -> (x - 1, y)) xs)
+   consolidatePlains (lns, bls) b =
+     case B.toList b of
+       [Plain ils] -> ((if lns == mempty
+                           then B.fromList ils
+                           else lns <> B.linebreak <> B.fromList ils), bls)
+       _ -> (mempty, bls <>
+                     (if lns == lns
+                         then mempty
+                         else B.plain lns)
+                      <> b)
+
+blockRaw :: PandocMonad m => DWParser m B.Blocks
+blockRaw = try $ do
+  char '<'
+  fmt <- oneOfStrings ["HTML", "PHP", "LATEX"]
+  -- LaTeX via https://www.dokuwiki.org/plugin:latex
+  char '>'
+  optional (manyTill spaceChar eol)
+  contents <- manyTillChar anyChar
+               (try $ string "</" *> string (T.unpack fmt) *> char '>')
+  return $
+    case T.toLower fmt of
+         "php" -> B.rawBlock "html" $ "<?php " <> contents <> " ?>"
+         f -> B.rawBlock f contents
+
+table :: PandocMonad m => DWParser m B.Blocks
+table = do
+  firstSeparator <- lookAhead tableCellSeparator
+  rows <- tableRows
+  let firstRow = fromMaybe [] . Safe.headMay $ rows
+  let (headerRow, body) = if firstSeparator == '^'
+                            then (firstRow, drop 1 rows)
+                            else ([], rows)
+  -- Since Pandoc only has column level alignment, we have to make an arbitrary
+  -- choice of how to reconcile potentially different alignments in the row.
+  -- Here we end up assuming that the alignment of the header / first row is
+  -- what the user wants to apply to the whole thing.
+  let attrs =  map (\(a, _) -> (a, ColWidthDefault)) firstRow
+  let toRow = Row nullAttr . map B.simpleCell
+      toHeaderRow l = [toRow l | not (null l)]
+  pure $ B.table B.emptyCaption
+                 attrs
+                 (TableHead nullAttr $ toHeaderRow (map snd headerRow))
+                 [TableBody nullAttr 0 [] $ map (toRow . (map snd)) body]
+                 (TableFoot nullAttr [])
+
+
+tableRows :: PandocMonad m => DWParser m [[(Alignment, B.Blocks)]]
+tableRows = many1 tableRow
+
+tableRow :: PandocMonad m => DWParser m [(Alignment, B.Blocks)]
+tableRow = many1Till tableCell tableRowEnd
+
+tableRowEnd :: PandocMonad m => DWParser m Char
+tableRowEnd = try $ tableCellSeparator <* manyTill spaceChar eol
+
+tableCellSeparator :: PandocMonad m => DWParser m Char
+tableCellSeparator = char '|' <|> char '^'
+
+tableCell :: PandocMonad m => DWParser m (Alignment, B.Blocks)
+tableCell = try $ (second (B.plain . B.trimInlines . mconcat)) <$> cellContent
+  where
+    cellContent = do
+      -- https://www.dokuwiki.org/wiki:syntax#tables
+      -- DokuWiki represents the alignment of cells with two spaces padding.
+      tableCellSeparator
+      cellInline <- manyTill inlineUnconsolidatedWhitespace (lookAhead tableCellSeparator)
+      let left  = [B.space, B.space] `isPrefixOf` cellInline
+      let right = [B.space, B.space] `isSuffixOf` cellInline
+      let alignment = case (left, right) of
+                           (True, True)   -> AlignCenter
+                           (True, False)  -> AlignRight
+                           (False, True)  -> AlignLeft
+                           (False, False) -> AlignDefault
+      return (alignment, cellInline)
+
+
+blockCode :: PandocMonad m => DWParser m B.Blocks
+blockCode = codeTag B.codeBlockWith "code" <|>
+            codeTag B.codeBlockWith "file"
+
+para :: PandocMonad m => DWParser m B.Blocks
+para = result . mconcat <$> many1Till inline endOfParaElement
+ where
+   endOfParaElement = lookAhead $ endOfInput <|> endOfPara <|> newBlockElement
+   endOfInput       = try $ skipMany blankline >> skipSpaces >> eof
+   endOfPara        = try $ blankline >> skipMany1 blankline
+   newBlockElement  = try (blankline >> void blockElements)
+                       <|> lookAhead (void blockCode)
+   result content   = if F.all (==Space) content
+                      then mempty
+                      else B.para $ B.trimInlines content
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,63 +1,75 @@
-{-# LANGUAGE FlexibleContexts #-}
+{-# LANGUAGE TupleSections     #-}
+{-# LANGUAGE ViewPatterns      #-}
+{-# LANGUAGE OverloadedStrings #-}
+{- |
+   Module      : Text.Pandoc.Readers.EPUB
+   Copyright   : Copyright (C) 2014-2020 Matthew Pickering
+   License     : GNU GPL, version 2 or above
 
-{-# LANGUAGE TupleSections    #-}
-{-# LANGUAGE ViewPatterns     #-}
+   Maintainer  : John MacFarlane <jgm@berkeley.edu>
+   Stability   : alpha
+   Portability : portable
 
+Conversion of EPUB to 'Pandoc' document.
+-}
+
 module Text.Pandoc.Readers.EPUB
   (readEPUB)
   where
 
-import Codec.Archive.Zip (Archive (..), Entry, findEntryByPath, fromEntry,
+import Codec.Archive.Zip (Archive (..), Entry(..), findEntryByPath, fromEntry,
                           toArchiveOrFail)
 import Control.DeepSeq (NFData, deepseq)
-import Control.Monad (guard, liftM)
+import Control.Monad (guard, liftM, liftM2, mplus)
 import Control.Monad.Except (throwError)
 import qualified Data.ByteString.Lazy as BL (ByteString)
-import Data.List (isInfixOf, isPrefixOf)
+import qualified Data.Text as T
+import Data.Text (Text)
 import qualified Data.Map as M (Map, elems, fromList, lookup)
-import Data.Maybe (fromMaybe, mapMaybe)
-import Data.Monoid ((<>))
+import Data.Maybe (mapMaybe)
 import qualified Data.Text.Lazy as TL
 import qualified Data.Text.Lazy.Encoding as TL
-import Network.URI (unEscapeString)
+import Network.URI (unEscapeString, parseRelativeReference, URI(..))
 import System.FilePath (dropFileName, dropFileName, normalise, splitFileName,
                         takeFileName, (</>))
 import qualified Text.Pandoc.Builder as B
-import Text.Pandoc.Class (PandocMonad, insertMedia)
+import Text.Pandoc.Class.PandocMonad (PandocMonad, insertMedia)
 import Text.Pandoc.Definition hiding (Attr)
 import Text.Pandoc.Error
 import Text.Pandoc.Extensions (Extension (Ext_raw_html), enableExtension)
 import Text.Pandoc.MIME (MimeType)
 import Text.Pandoc.Options (ReaderOptions (..))
 import Text.Pandoc.Readers.HTML (readHtml)
-import Text.Pandoc.Shared (addMetaField, collapseFilePath, escapeURI)
-import qualified Text.Pandoc.UTF8 as UTF8 (toStringLazy)
+import Text.Pandoc.Shared (addMetaField, collapseFilePath, tshow)
+import Text.Pandoc.URI (escapeURI)
+import qualified Text.Pandoc.UTF8 as UTF8 (toTextLazy)
 import Text.Pandoc.Walk (query, walk)
-import Text.XML.Light
+import Text.Pandoc.XML.Light
 
-type Items = M.Map String (FilePath, MimeType)
+type Items = M.Map Text (FilePath, MimeType)
 
 readEPUB :: PandocMonad m => ReaderOptions -> BL.ByteString -> m Pandoc
 readEPUB opts bytes = case toArchiveOrFail bytes of
   Right archive -> archiveToEPUB opts archive
-  Left  _       -> throwError $ PandocParseError "Couldn't extract ePub file"
+  Left  e       -> throwError $ PandocParseError $
+                     "Couldn't extract ePub file: " <> T.pack e
 
 -- runEPUB :: Except PandocError a -> Either PandocError a
 -- runEPUB = runExcept
 
--- Note that internal reference are aggresively normalised so that all ids
+-- Note that internal reference are aggressively normalised so that all ids
 -- are of the form "filename#id"
 --
 archiveToEPUB :: (PandocMonad m) => ReaderOptions -> Archive -> m Pandoc
 archiveToEPUB os archive = do
   -- root is path to folder with manifest file in
   (root, content) <- getManifest archive
-  meta  <- parseMeta content
-  (cover, items) <- parseManifest content
+  (coverId, meta) <- parseMeta content
+  (cover, items)  <- parseManifest content coverId
   -- No need to collapse here as the image path is from the manifest file
-  let coverDoc = fromMaybe mempty (imageToPandoc <$> cover)
+  let coverDoc = maybe mempty imageToPandoc cover
   spine <- parseSpine items content
-  let escapedSpine = map (escapeURI . takeFileName . fst) spine
+  let escapedSpine = map (escapeURI . T.pack . takeFileName . fst) spine
   Pandoc _ bs <-
       foldM' (\a b -> ((a <>) . walk (prependHash escapedSpine))
         `liftM` parseSpineElem root b) mempty spine
@@ -69,7 +81,7 @@
     parseSpineElem :: PandocMonad m => FilePath -> (FilePath, MimeType) -> m Pandoc
     parseSpineElem (normalise -> r) (normalise -> path, mime) = do
       doc <- mimeToReader mime r path
-      let docSpan = B.doc $ B.para $ B.spanWith (takeFileName path, [], []) mempty
+      let docSpan = B.doc $ B.para $ B.spanWith (T.pack $ takeFileName path, [], []) mempty
       return $ docSpan <> doc
     mimeToReader :: PandocMonad m => MimeType -> FilePath -> FilePath -> m Pandoc
     mimeToReader "application/xhtml+xml" (unEscapeString -> root)
@@ -93,44 +105,49 @@
     mapM_ (uncurry3 insertMedia) (mapMaybe getEntry links)
   where
     getEntry link =
-        let abslink = normalise (root </> link) in
+        let abslink = normalise (unEscapeString (root </> link)) in
         (link , lookup link mimes, ) . fromEntry
           <$> findEntryByPath abslink arc
 
 iq :: Inline -> [FilePath]
-iq (Image _ _ (url, _)) = [url]
+iq (Image _ _ (url, _)) = [T.unpack url]
 iq _                    = []
 
 -- Remove relative paths
 renameImages :: FilePath -> Inline -> Inline
 renameImages root img@(Image attr a (url, b))
-  | "data:" `isPrefixOf` url = img
-  | otherwise                = Image attr a (collapseFilePath (root </> url), b)
+  | "data:" `T.isPrefixOf` url = img
+  | otherwise                  = Image attr a ( T.pack $ collapseFilePath (root </> T.unpack url)
+                                              , b)
 renameImages _ x = x
 
 imageToPandoc :: FilePath -> Pandoc
-imageToPandoc s = B.doc . B.para $ B.image s "" mempty
+imageToPandoc s = B.doc . B.para $ B.image (T.pack s) "" mempty
 
 imageMimes :: [MimeType]
 imageMimes = ["image/gif", "image/jpeg", "image/png"]
 
+type CoverId = Text
+
 type CoverImage = FilePath
 
-parseManifest :: (PandocMonad m) => Element -> m (Maybe CoverImage, Items)
-parseManifest content = do
+parseManifest :: (PandocMonad m)
+              => Element -> Maybe CoverId -> m (Maybe CoverImage, Items)
+parseManifest content coverId = do
   manifest <- findElementE (dfName "manifest") content
   let items = findChildren (dfName "item") manifest
   r <- mapM parseItem items
   let cover = findAttr (emptyName "href") =<< filterChild findCover manifest
-  return (cover, M.fromList r)
+  return (T.unpack <$> (cover `mplus` coverId), M.fromList r)
   where
-    findCover e = maybe False (isInfixOf "cover-image")
+    findCover e = maybe False (T.isInfixOf "cover-image")
                   (findAttr (emptyName "properties") e)
+               || Just True == liftM2 (==) coverId (findAttr (emptyName "id") e)
     parseItem e = do
       uid <- findAttrE (emptyName "id") e
       href <- findAttrE (emptyName "href") e
       mime <- findAttrE (emptyName "media-type") e
-      return (uid, (href, mime))
+      return (uid, (T.unpack href, mime))
 
 parseSpine :: PandocMonad m => Items -> Element -> m [(FilePath, MimeType)]
 parseSpine is e = do
@@ -143,63 +160,74 @@
       guard linear
       findAttr (emptyName "idref") ref
 
-parseMeta :: PandocMonad m => Element -> m Meta
+parseMeta :: PandocMonad m => Element -> m (Maybe CoverId, Meta)
 parseMeta content = do
   meta <- findElementE (dfName "metadata") content
   let dcspace (QName _ (Just "http://purl.org/dc/elements/1.1/") (Just "dc")) = True
       dcspace _ = False
   let dcs = filterChildrenName dcspace meta
   let r = foldr parseMetaItem nullMeta dcs
-  return r
+  let coverId = findAttr (emptyName "content") =<< filterChild findCover meta
+  return (coverId, r)
+  where
+    findCover e = findAttr (emptyName "name") e == Just "cover"
 
 -- http://www.idpf.org/epub/30/spec/epub30-publications.html#sec-metadata-elem
 parseMetaItem :: Element -> Meta -> Meta
 parseMetaItem e@(stripNamespace . elName -> field) meta =
   addMetaField (renameMeta field) (B.str $ strContent e) meta
 
-renameMeta :: String -> String
+renameMeta :: Text -> Text
 renameMeta "creator" = "author"
 renameMeta s         = s
 
 getManifest :: PandocMonad m => Archive -> m (String, Element)
 getManifest archive = do
   metaEntry <- findEntryByPathE ("META-INF" </> "container.xml") archive
-  docElem <- (parseXMLDocE . UTF8.toStringLazy . fromEntry) metaEntry
+  docElem <- parseXMLDocE metaEntry
   let namespaces = mapMaybe attrToNSPair (elAttribs docElem)
   ns <- mkE "xmlns not in namespaces" (lookup "xmlns" namespaces)
   as <- fmap (map attrToPair . elAttribs)
     (findElementE (QName "rootfile" (Just ns) Nothing) docElem)
-  manifestFile <- mkE "Root not found" (lookup "full-path" as)
+  manifestFile <- T.unpack <$> mkE "Root not found" (lookup "full-path" as)
   let rootdir = dropFileName manifestFile
   --mime <- lookup "media-type" as
   manifest <- findEntryByPathE manifestFile archive
-  fmap ((,) rootdir) (parseXMLDocE . UTF8.toStringLazy . fromEntry $ manifest)
+  (rootdir,) <$> parseXMLDocE manifest
 
 -- Fixup
 
 fixInternalReferences :: FilePath -> Pandoc -> Pandoc
 fixInternalReferences pathToFile =
    walk (renameImages root)
-  .  walk (fixBlockIRs filename)
+  . walk (fixBlockIRs filename)
   . walk (fixInlineIRs filename)
   where
-    (root, escapeURI -> filename) = splitFileName pathToFile
+    (root, T.unpack . escapeURI . T.pack -> filename) =
+      splitFileName pathToFile
 
 fixInlineIRs :: String -> Inline -> Inline
 fixInlineIRs s (Span as v) =
   Span (fixAttrs s as) v
 fixInlineIRs s (Code as code) =
   Code (fixAttrs s as) code
-fixInlineIRs s (Link as is ('#':url, tit)) =
-  Link (fixAttrs s as) is (addHash s url, tit)
-fixInlineIRs s (Link as is t) =
-  Link (fixAttrs s as) is t
+fixInlineIRs s (Link as is (url, tit)) =
+  case parseRelativeReference (T.unpack url) of
+    Just URI{ uriScheme = ""
+            , uriAuthority = Nothing
+            , uriPath = upath
+            , uriQuery = ""
+            , uriFragment = '#':ufrag } ->
+         Link (fixAttrs s as) is (addHash (if null upath
+                                              then s
+                                              else upath) (T.pack ufrag), tit)
+    _ -> Link (fixAttrs s as) is (url, tit)
 fixInlineIRs _ v = v
 
-prependHash :: [String] -> Inline -> Inline
+prependHash :: [Text] -> Inline -> Inline
 prependHash ps l@(Link attr is (url, tit))
-  | or [s `isPrefixOf` url | s <- ps] =
-    Link attr is ('#':url, tit)
+  | or [s `T.isPrefixOf` url | s <- ps] =
+    Link attr is ("#" <> url, tit)
   | otherwise = l
 prependHash _ i = i
 
@@ -213,17 +241,18 @@
 fixBlockIRs _ b = b
 
 fixAttrs :: FilePath -> B.Attr -> B.Attr
-fixAttrs s (ident, cs, kvs) = (addHash s ident, filter (not . null) cs, removeEPUBAttrs kvs)
+fixAttrs s (ident, cs, kvs) =
+  (addHash s ident, filter (not . T.null) cs, removeEPUBAttrs kvs)
 
-addHash :: String -> String -> String
+addHash :: FilePath -> Text -> Text
 addHash _ ""    = ""
-addHash s ident = takeFileName s ++ "#" ++ ident
+addHash s ident = T.pack (takeFileName s) <> "_" <> ident
 
-removeEPUBAttrs :: [(String, String)] -> [(String, String)]
+removeEPUBAttrs :: [(Text, Text)] -> [(Text, Text)]
 removeEPUBAttrs kvs = filter (not . isEPUBAttr) kvs
 
-isEPUBAttr :: (String, String) -> Bool
-isEPUBAttr (k, _) = "epub:" `isPrefixOf` k
+isEPUBAttr :: (Text, a) -> Bool
+isEPUBAttr (k, _) = "epub:" `T.isPrefixOf` k
 
 -- Library
 
@@ -239,39 +268,44 @@
 
 -- Utility
 
-stripNamespace :: QName -> String
+stripNamespace :: QName -> Text
 stripNamespace (QName v _ _) = v
 
-attrToNSPair :: Attr -> Maybe (String, String)
+attrToNSPair :: Attr -> Maybe (Text, Text)
 attrToNSPair (Attr (QName "xmlns" _ _) val) = Just ("xmlns", val)
 attrToNSPair _                              = Nothing
 
-attrToPair :: Attr -> (String, String)
+attrToPair :: Attr -> (Text, Text)
 attrToPair (Attr (QName name _ _) val) = (name, val)
 
-defaultNameSpace :: Maybe String
+defaultNameSpace :: Maybe Text
 defaultNameSpace = Just "http://www.idpf.org/2007/opf"
 
-dfName :: String -> QName
+dfName :: Text -> QName
 dfName s = QName s defaultNameSpace Nothing
 
-emptyName :: String -> QName
+emptyName :: Text -> QName
 emptyName s = QName s Nothing Nothing
 
 -- Convert Maybe interface to Either
 
-findAttrE :: PandocMonad m => QName -> Element -> m String
+findAttrE :: PandocMonad m => QName -> Element -> m Text
 findAttrE q e = mkE "findAttr" $ findAttr q e
 
 findEntryByPathE :: PandocMonad m => FilePath -> Archive -> m Entry
-findEntryByPathE (normalise -> path) a =
-  mkE ("No entry on path: " ++ path) $ findEntryByPath path a
+findEntryByPathE (normalise . unEscapeString -> path) a =
+  mkE ("No entry on path: " <> T.pack path) $ findEntryByPath path a
 
-parseXMLDocE :: PandocMonad m => String -> m Element
-parseXMLDocE doc = mkE "Unable to parse XML doc" $ parseXMLDoc doc
+parseXMLDocE :: PandocMonad m => Entry -> m Element
+parseXMLDocE entry =
+  either (throwError . PandocXMLError fp) return $ parseXMLElement doc
+ where
+  doc = UTF8.toTextLazy . fromEntry $ entry
+  fp  = T.pack $ eRelativePath entry
 
 findElementE :: PandocMonad m => QName -> Element -> m Element
-findElementE e x = mkE ("Unable to find element: " ++ show e) $ findElement e x
+findElementE e x =
+  mkE ("Unable to find element: " <> tshow e) $ findElement e x
 
-mkE :: PandocMonad m => String -> Maybe a -> m a
+mkE :: PandocMonad m => Text -> Maybe a -> m a
 mkE s = maybe (throwError . PandocParseError $ s) return
diff --git a/src/Text/Pandoc/Readers/EndNote.hs b/src/Text/Pandoc/Readers/EndNote.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Readers/EndNote.hs
@@ -0,0 +1,251 @@
+{-# LANGUAGE TupleSections #-}
+{-# LANGUAGE OverloadedStrings #-}
+{- |
+   Module      : Text.Pandoc.Readers.EndNote
+   Copyright   : Copyright (C) 2022-2024 John MacFarlane
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : John MacFarlane <jgm@berkeley.edu>
+   Stability   : alpha
+   Portability : portable
+
+Parses EndNote XML bibliographies into a Pandoc document
+with empty body and `references` and `nocite` fields
+in the metadata.  A wildcard `nocite` is used so that
+if the document is rendered in another format, the
+entire bibliography will be printed.
+-}
+module Text.Pandoc.Readers.EndNote
+  ( readEndNoteXML
+  , readEndNoteXMLCitation
+  )
+where
+
+import Text.Pandoc.Options
+import Text.Pandoc.Definition
+import Citeproc (Reference(..), ItemId(..), Val(..), Date(..), DateParts(..))
+import qualified Citeproc
+import Text.Pandoc.Builder as B
+import Text.Pandoc.Error (PandocError(..))
+import Text.Pandoc.Class (PandocMonad)
+import Text.Pandoc.Citeproc.MetaValue (referenceToMetaValue)
+import Text.Pandoc.Sources (Sources(..), ToSources(..), sourcesToText)
+import Text.Pandoc.Citeproc.Name (toName, NameOpts(..))
+import Control.Applicative ((<|>))
+import Control.Monad.Except (throwError)
+import Control.Monad (mzero, unless)
+import Text.Pandoc.XML.Light
+    ( filterElementName,
+      strContent,
+      QName(qName),
+      Element(..),
+      Content(..),
+      CData(..),
+      filterElementsName,
+      filterChildName,
+      filterChildrenName,
+      findAttrBy,
+      parseXMLElement )
+import qualified Data.Text.Lazy as TL
+import qualified Data.Text as T
+import Data.Text (Text)
+import qualified Data.Map as M
+import Safe (readMay)
+
+-- | Read EndNote XML from an input string and return a Pandoc document.
+-- The document will have only metadata, with an empty body.
+-- The metadata will contain a `references` field with the
+-- bibliography entries, and a `nocite` field with the wildcard `[@*]`.
+readEndNoteXML :: (PandocMonad m, ToSources a)
+               => ReaderOptions -> a -> m Pandoc
+readEndNoteXML _opts inp = do
+  let sources = toSources inp
+  refs <- readEndNoteXMLReferences sources >>= mapM (traverse (return . text))
+  return $
+    setMeta "nocite" (cite [Citation {citationId = "*"
+                                     , citationPrefix = []
+                                     , citationSuffix = []
+                                     , citationMode = NormalCitation
+                                     , citationNoteNum = 0
+                                     , citationHash = 0}] (str "[@*]")) $
+    setMeta "references" (map referenceToMetaValue refs) $
+    B.doc mempty
+
+readEndNoteXMLCitation :: PandocMonad m
+                    => Text -> m (Citeproc.Citation Text)
+readEndNoteXMLCitation xml = do
+  tree <- either (throwError . PandocXMLError "EndNote references") return $
+              parseXMLElement (TL.fromStrict xml)
+  unless (qName (elName tree) == "EndNote") $
+    throwError $ PandocXMLError "EndNote references" "Expected EndNote element"
+  let items = map toCitationItem $ filterElementsName (name "Cite") tree
+  return $ Citeproc.Citation{
+                     Citeproc.citationId = Nothing
+                   , Citeproc.citationResetPosition = False
+                   , Citeproc.citationPrefix = Nothing
+                   , Citeproc.citationSuffix = Nothing
+                   , Citeproc.citationNoteNumber = Nothing
+                   , Citeproc.citationItems = items
+                   }
+
+readEndNoteXMLReferences :: PandocMonad m
+                         => Sources -> m [Reference Text]
+readEndNoteXMLReferences sources = do
+  tree <- either (throwError . PandocXMLError "EndNote references") return $
+              parseXMLElement (TL.fromStrict . sourcesToText $ sources)
+  let records = filterElementsName (name "record") tree
+  return $ map recordToReference records
+
+
+toCitationItem :: Element -> Citeproc.CitationItem Text
+toCitationItem el =
+    Citeproc.CitationItem{ Citeproc.citationItemId =
+                              maybe mempty referenceId mbref
+                         , Citeproc.citationItemLabel = Nothing
+                         , Citeproc.citationItemLocator = mbpages
+                         , Citeproc.citationItemType = Citeproc.NormalCite
+                         , Citeproc.citationItemPrefix = mbprefix
+                         , Citeproc.citationItemSuffix = mbsuffix
+                         , Citeproc.citationItemData = mbref
+                         }
+ where
+  mbref = recordToReference <$> filterChildName (name "record") el
+  mbprefix = getText <$> filterChildName (name "Prefix") el
+  mbsuffix = getText <$> filterChildName (name "Suffix") el
+  mbpages  = getText <$> filterChildName (name "Pages") el
+
+name :: Text -> (QName -> Bool)
+name t = (== t) . qName
+
+getText :: Element -> Text
+getText el = getText' (Elem el)
+ where
+  getText' (Elem el') = mconcat $ map getText' $ elContent el'
+  getText' (Text cd) = cdData cd
+  getText' (CRef _) = mempty
+
+recordToReference :: Element -> Reference Text
+recordToReference e =
+  Reference{ referenceId = ItemId refid,
+             referenceType = reftype,
+             referenceDisambiguation = Nothing,
+             referenceVariables = refvars }
+
+ where
+   -- get strContent, recursing inside style elements:
+   refid = maybe mempty (T.strip . strContent)
+           (filterElementName (name "key") e
+            <|> filterElementName (name "rec-number") e)
+   reftype = maybe "document" toCslReferenceType
+              (filterElementName (name "ref-type") e >>=
+                findAttrBy (name "name"))
+   authors =
+     filterChildrenName (name "contributors") e >>=
+     filterChildrenName (name "authors") >>=
+     filterChildrenName (name "author") >>=
+          toName NameOpts{ nameOptsPrefixIsNonDroppingParticle = False
+                         , nameOptsUseJuniorComma = False }
+             . B.toList .  B.text . T.strip . getText
+   titles = do
+     x <- filterChildrenName (name "titles") e
+     (key, name') <- [("title", "title"),
+                      ("container-title", "secondary-title")]
+     (key,) . FancyVal . T.strip . getText <$>
+                    filterChildrenName (name name') x
+   pages = ("pages",) . FancyVal . T.strip . getText <$>
+                filterChildrenName (name "pages") e
+   volume = ("volume",) . FancyVal . T.strip . getText <$>
+                filterChildrenName (name "volume") e
+   number = ("number",) . FancyVal . T.strip . getText <$>
+                filterChildrenName (name "number") e
+   isbn = ("isbn",) . FancyVal . T.strip . getText <$>
+                filterChildrenName (name "isbn") e
+   publisher = ("publisher",) . FancyVal . T.strip . getText <$>
+                filterChildrenName (name "publisher") e
+   originalPublisher =
+     ("original-publisher",) . FancyVal . T.strip . getText <$>
+                filterChildrenName (name "orig-pub") e
+   publisherPlace =
+     ("publisher-place",) . FancyVal . T.strip . getText <$>
+                filterChildrenName (name "pub-location") e
+   abstract = ("abstract",) . FancyVal . T.strip . getText <$>
+                filterChildrenName (name "abstract") e
+   dates = ("issued",) . toDate <$> filterChildrenName (name "dates") e
+   toDate e' = DateVal $
+    Date { dateParts = toDateParts e'
+         , dateCirca = False
+         , dateSeason = Nothing
+         , dateLiteral = Nothing }
+   toDateParts e' = do
+    x <- filterChildrenName (name "year") e'
+    case readMay . T.unpack . T.strip . getText $ x of
+      Nothing -> mzero
+      Just y  -> return $ DateParts [y]
+
+   refvars = M.fromList $
+     [ ("author", NamesVal authors) | not (null authors) ] ++
+     titles ++
+     pages ++
+     volume ++
+     number ++
+     isbn ++
+     dates ++
+     publisher ++
+     originalPublisher ++
+     publisherPlace ++
+     abstract
+
+toCslReferenceType :: Text -> Text
+toCslReferenceType t =
+  case t of
+    "Aggregated Database" -> "dataset"
+    "Ancient Text" -> "classic"
+    "Artwork" -> "graphic"
+    "Audiovisual Material" -> "graphic"
+    "Bill" -> "legislation"
+    "Blog" -> "post-weblog"
+    "Book" -> "book"
+    "Book Section" -> "chapter"
+    "Case" -> "legal_case"
+    "Catalog" -> "document"
+    "Chart or Table" -> "graphic"
+    "Classical Work" -> "classic"
+    "Computer program" -> "software"
+    "Conference Paper" -> "article"
+    "Conference Proceedings" -> "periodical"
+    "Dataset" -> "dataset"
+    "Dictionary" -> "book"
+    "Edited Book" -> "book"
+    "Electronic Article" -> "article"
+    "Electronic Book" -> "book"
+    "Electronic Book Section" -> "chapter"
+    "Encyclopedia" -> "book"
+    "Equation" -> "document"
+    "Figure" -> "graphic"
+    "Film or Broadcast" -> "motion_picture"
+    "Government Document" -> "document"
+    "Grant" -> "document"
+    "Hearing" -> "hearing"
+    "Interview" -> "interview"
+    "Journal Article" -> "article-journal"
+    "Legal Rule or Regulation" -> "regulation"
+    "Magazine Article" -> "article-magazine"
+    "Manuscript" -> "manuscript"
+    "Map" -> "map"
+    "Music" -> "musical_score"
+    "Newspaper Article" -> "article-newspaper"
+    "Online Database" -> "dataset"
+    "Online Multimedia" -> "webpage"
+    "Pamphlet" -> "pamphlet"
+    "Patent" -> "patent"
+    "Personal Communication" -> "personal_communication"
+    "Podcast" -> "document"
+    "Press Release" -> "report"
+    "Report" -> "report"
+    "Serial" -> "periodical"
+    "Standard" -> "standard"
+    "Statute" -> "legislation"
+    "Thesis" -> "thesis"
+    "Unpublished Work" -> "unpublished"
+    "Web Page" -> "webpage"
+    _ -> "document"
diff --git a/src/Text/Pandoc/Readers/FB2.hs b/src/Text/Pandoc/Readers/FB2.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Readers/FB2.hs
@@ -0,0 +1,462 @@
+{-# LANGUAGE FlexibleContexts #-}
+{-# LANGUAGE TupleSections #-}
+{-# LANGUAGE OverloadedStrings #-}
+{- |
+   Module      : Text.Pandoc.Readers.FB2
+   Copyright   : Copyright (C) 2018-2020 Alexander Krotov
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : Alexander Krotov <ilabdsf@gmail.com>
+   Stability   : alpha
+   Portability : portable
+
+Conversion of FB2 to 'Pandoc' document.
+-}
+
+{-
+
+TODO:
+ - Tables
+ - Named styles
+ - Parse ID attribute for all elements that have it
+
+-}
+
+module Text.Pandoc.Readers.FB2 ( readFB2 ) where
+import Control.Monad.Except (throwError)
+import Control.Monad.State.Strict
+import Data.ByteString.Base64.Lazy
+import Data.Functor
+import Data.List (intersperse)
+import qualified Data.Map as M
+import Data.Text (Text)
+import qualified Data.Text as T
+import qualified Data.Text.Lazy as TL
+import Data.Default
+import Data.Maybe
+import Text.Pandoc.XML (lookupEntity)
+import Text.Pandoc.Builder
+import Text.Pandoc.Class.PandocMonad (PandocMonad, insertMedia, report)
+import Text.Pandoc.Error
+import Text.Pandoc.Logging
+import Text.Pandoc.Options
+import Text.Pandoc.XML.Light
+import qualified Text.Pandoc.UTF8 as UTF8
+import Text.Pandoc.Sources (ToSources(..), sourcesToText)
+
+type FB2 m = StateT FB2State m
+
+data FB2State = FB2State{ fb2SectionLevel :: Int
+                        , fb2Meta :: Meta
+                        , fb2Authors :: [Text]
+                        , fb2Notes :: M.Map Text Blocks
+                        } deriving Show
+
+instance Default FB2State where
+  def = FB2State{ fb2SectionLevel = 1
+                , fb2Meta = mempty
+                , fb2Authors = []
+                , fb2Notes = M.empty
+                }
+
+instance HasMeta FB2State where
+  setMeta field v s = s {fb2Meta = setMeta field v (fb2Meta s)}
+  deleteMeta field s = s {fb2Meta = deleteMeta field (fb2Meta s)}
+
+readFB2 :: (PandocMonad m, ToSources a)
+        => ReaderOptions
+        -> a
+        -> m Pandoc
+readFB2 _ inp =
+  case parseXMLElement $ TL.fromStrict $ sourcesToText $ toSources inp of
+    Left msg -> throwError $ PandocXMLError "" msg
+    Right el ->  do
+      (bs, st) <- runStateT (parseRootElement el) def
+      let authors = if null $ fb2Authors st
+                    then id
+                    else setMeta "author" (map text $ reverse $ fb2Authors st)
+      pure $ Pandoc (authors $ fb2Meta st) $ toList bs
+
+-- * Utility functions
+
+trim :: Text -> Text
+trim = T.strip
+
+removeHash :: Text -> Text
+removeHash t = case T.uncons t of
+  Just ('#', xs) -> xs
+  _              -> t
+
+convertEntity :: Text -> Text
+convertEntity e = fromMaybe (T.toUpper e) $ lookupEntity e
+
+parseInline :: PandocMonad m => Content -> FB2 m Inlines
+parseInline (Elem e) =
+  case qName $ elName e of
+    "strong" -> strong <$> parseStyleType e
+    "emphasis" -> emph <$> parseStyleType e
+    "style" -> parseNamedStyle e
+    "a" -> parseLinkType e
+    "strikethrough" -> strikeout <$> parseStyleType e
+    "sub" -> subscript <$> parseStyleType e
+    "sup" -> superscript <$> parseStyleType e
+    "code" -> pure $ code $ strContent e
+    "image" -> parseInlineImageElement e
+    name -> do
+      report $ IgnoredElement name
+      pure mempty
+parseInline (Text x) = pure $ text $ cdData x
+parseInline (CRef r) = pure $ str $ convertEntity r
+
+parseSubtitle :: PandocMonad m => Element -> FB2 m Blocks
+parseSubtitle e = headerWith ("", ["unnumbered"], []) <$> gets fb2SectionLevel <*> parsePType e
+
+-- * Root element parser
+
+parseRootElement :: PandocMonad m => Element -> FB2 m Blocks
+parseRootElement e =
+  case qName $ elName e of
+    "FictionBook" -> do
+      -- Parse notes before parsing the rest of the content.
+      case filterChild isNotesBody e of
+        Nothing -> pure ()
+        Just notesBody -> parseNotesBody notesBody
+      -- Parse metadata and content
+      mconcat <$> mapM parseFictionBookChild (elChildren e)
+    name -> report (UnexpectedXmlElement name "root") $> mempty
+
+-- | Parse notes
+parseNotesBody :: PandocMonad m => Element -> FB2 m ()
+parseNotesBody e = mempty <$ mapM parseNotesBodyChild (elChildren e)
+
+-- | Parse a child of @\<body name="notes">@ element.
+parseNotesBodyChild :: PandocMonad m => Element -> FB2 m ()
+parseNotesBodyChild e =
+  case qName $ elName e of
+    "section" -> parseNote e
+    _ -> pure ()
+
+isNotesBody :: Element -> Bool
+isNotesBody e =
+  qName (elName e) == "body" &&
+  findAttr (unqual "name") e == Just "notes"
+
+parseNote :: PandocMonad m => Element -> FB2 m ()
+parseNote e =
+  case findAttr (unqual "id") e of
+    Nothing -> pure ()
+    Just sectionId -> do
+      content <- mconcat <$> mapM parseSectionChild (dropTitle $ elChildren e)
+      oldNotes <- gets fb2Notes
+      modify $ \s -> s { fb2Notes = M.insert ("#" <> sectionId) content oldNotes }
+      pure ()
+  where
+    isTitle x = qName (elName x) == "title"
+    dropTitle (x:xs) = if isTitle x
+                         then xs -- Drop note section <title> if present
+                         else x:xs
+    dropTitle [] = []
+
+-- | Parse a child of @\<FictionBook>@ element.
+parseFictionBookChild :: PandocMonad m => Element -> FB2 m Blocks
+parseFictionBookChild e =
+  case qName $ elName e of
+    "stylesheet" -> pure mempty -- stylesheet is ignored
+    "description" -> mempty <$ mapM_ parseDescriptionChild (elChildren e)
+    "body" -> if isNotesBody e
+                then pure mempty
+                else mconcat <$> mapM parseBodyChild (elChildren e)
+    "binary" -> mempty <$ parseBinaryElement e
+    name -> report (UnexpectedXmlElement name "FictionBook") $> mempty
+
+-- | Parse a child of @\<description>@ element.
+parseDescriptionChild :: PandocMonad m => Element -> FB2 m ()
+parseDescriptionChild e =
+  case qName $ elName e of
+    "title-info" -> mapM_ parseTitleInfoChild (elChildren e)
+    "src-title-info" -> pure () -- ignore
+    "document-info" -> pure ()
+    "publish-info" -> pure ()
+    "custom-info" -> pure ()
+    "output" -> pure ()
+    name -> do
+      report $ IgnoredElement $ name <> " in description"
+      pure mempty
+
+-- | Parse a child of @\<body>@ element.
+parseBodyChild :: PandocMonad m => Element -> FB2 m Blocks
+parseBodyChild e =
+  case qName $ elName e of
+    "image" -> parseImageElement e
+    "title" -> header <$> gets fb2SectionLevel <*> parseTitleType (elContent e)
+    "epigraph" -> parseEpigraph e
+    "section" -> parseSection e
+    name -> report (UnexpectedXmlElement name "body") $> mempty
+
+-- | Parse a @\<binary>@ element.
+parseBinaryElement :: PandocMonad m => Element -> FB2 m ()
+parseBinaryElement e =
+  case (findAttr (unqual "id") e, findAttr (unqual "content-type") e) of
+    (Nothing, _) -> report $ IgnoredElement "binary without id attribute"
+    (Just _, Nothing) ->
+      report $ IgnoredElement "binary without content-type attribute"
+    (Just filename, contentType) ->
+      insertMedia (T.unpack filename) contentType
+                    (decodeLenient
+                      (UTF8.fromTextLazy . TL.fromStrict . strContent $ e))
+
+-- * Type parsers
+
+-- | Parse @authorType@
+parseAuthor :: PandocMonad m => Element -> FB2 m Text
+parseAuthor e = T.unwords . catMaybes <$> mapM parseAuthorChild (elChildren e)
+
+parseAuthorChild :: PandocMonad m => Element -> FB2 m (Maybe Text)
+parseAuthorChild e =
+  case qName $ elName e of
+    "first-name" -> pure $ Just $ strContent e
+    "middle-name" -> pure $ Just $ strContent e
+    "last-name" -> pure $ Just $ strContent e
+    "nickname" -> pure $ Just $ strContent e
+    "home-page" -> pure $ Just $ strContent e
+    "email" -> pure $ Just $ strContent e
+    name -> do
+      report $ IgnoredElement $ name <> " in author"
+      pure Nothing
+
+-- | Parse @titleType@
+parseTitle :: PandocMonad m => Element -> FB2 m Blocks
+parseTitle e = header <$> gets fb2SectionLevel <*> parseTitleType (elContent e)
+
+parseTitleType :: PandocMonad m => [Content] -> FB2 m Inlines
+parseTitleType c = mconcat . intersperse linebreak . catMaybes <$> mapM parseTitleContent c
+
+parseTitleContent :: PandocMonad m => Content -> FB2 m (Maybe Inlines)
+parseTitleContent (Elem e) =
+  case qName $ elName e of
+    "p" -> Just <$> parsePType e
+    "empty-line" -> pure $ Just mempty
+    _ -> pure mempty
+parseTitleContent _ = pure Nothing
+
+-- | Parse @imageType@
+parseImageElement :: PandocMonad m => Element -> FB2 m Blocks
+parseImageElement e =
+  case href of
+    Just src -> pure $ para $ imageWith (imgId, [], []) (removeHash src) title alt
+    Nothing -> do
+      report $ IgnoredElement " image without href"
+      pure mempty
+  where alt = maybe mempty str $ findAttr (unqual "alt") e
+        title = fromMaybe "" $ findAttr (unqual "title") e
+        imgId = fromMaybe "" $ findAttr (unqual "id") e
+        href = findAttr (QName "href" (Just "http://www.w3.org/1999/xlink") Nothing) e
+
+-- | Parse @pType@
+parsePType :: PandocMonad m => Element -> FB2 m Inlines
+parsePType = parseStyleType -- TODO add support for optional "id" and "style" attributes
+
+-- | Parse @citeType@
+parseCite :: PandocMonad m => Element -> FB2 m Blocks
+parseCite e = blockQuote . mconcat <$> mapM parseCiteChild (elChildren e)
+
+-- | Parse @citeType@ child
+parseCiteChild :: PandocMonad m => Element -> FB2 m Blocks
+parseCiteChild e =
+  case qName $ elName e of
+    "p" -> para <$> parsePType e
+    "poem" -> parsePoem e
+    "empty-line" -> pure horizontalRule
+    "subtitle" -> parseSubtitle e
+    "table" -> parseTable e
+    "text-author" -> para <$> parsePType e
+    name -> report (UnexpectedXmlElement name "cite") $> mempty
+
+-- | Parse @poemType@
+parsePoem :: PandocMonad m => Element -> FB2 m Blocks
+parsePoem e = mconcat <$> mapM parsePoemChild (elChildren e)
+
+parsePoemChild :: PandocMonad m => Element -> FB2 m Blocks
+parsePoemChild e =
+  case qName $ elName e of
+    "title" -> parseTitle e
+    "subtitle" -> parseSubtitle e
+    "epigraph" -> parseEpigraph e
+    "stanza" -> parseStanza e
+    "text-author" -> para <$> parsePType e
+    "date" -> pure $ para $ text $ strContent e
+    name -> report (UnexpectedXmlElement name "poem") $> mempty
+
+parseStanza :: PandocMonad m => Element -> FB2 m Blocks
+parseStanza e = fromList . joinLineBlocks . toList . mconcat <$> mapM parseStanzaChild (elChildren e)
+
+joinLineBlocks :: [Block] -> [Block]
+joinLineBlocks (LineBlock xs:LineBlock ys:zs) = joinLineBlocks (LineBlock (xs ++ ys) : zs)
+joinLineBlocks (x:xs) = x:joinLineBlocks xs
+joinLineBlocks [] = []
+
+parseStanzaChild :: PandocMonad m => Element -> FB2 m Blocks
+parseStanzaChild e =
+  case qName $ elName e of
+    "title" -> parseTitle e
+    "subtitle" -> parseSubtitle e
+    "v" -> lineBlock . (:[]) <$> parsePType e
+    name -> report (UnexpectedXmlElement name "stanza") $> mempty
+
+-- | Parse @epigraphType@
+parseEpigraph :: PandocMonad m => Element -> FB2 m Blocks
+parseEpigraph e =
+  divWith (divId, ["epigraph"], []) . mconcat <$> mapM parseEpigraphChild (elChildren e)
+  where divId = fromMaybe "" $ findAttr (unqual "id") e
+
+parseEpigraphChild :: PandocMonad m => Element -> FB2 m Blocks
+parseEpigraphChild e =
+  case qName $ elName e of
+    "p" -> para <$> parsePType e
+    "poem" -> parsePoem e
+    "cite" -> parseCite e
+    "empty-line" -> pure horizontalRule
+    "text-author" -> para <$> parsePType e
+    name -> report (UnexpectedXmlElement name "epigraph") $> mempty
+
+-- | Parse @annotationType@
+parseAnnotation :: PandocMonad m => Element -> FB2 m Blocks
+parseAnnotation e = mconcat <$> mapM parseAnnotationChild (elChildren e)
+
+parseAnnotationChild :: PandocMonad m => Element -> FB2 m Blocks
+parseAnnotationChild e =
+  case qName $ elName e of
+    "p" -> para <$> parsePType e
+    "poem" -> parsePoem e
+    "cite" -> parseCite e
+    "subtitle" -> parseSubtitle e
+    "table" -> parseTable e
+    "empty-line" -> pure horizontalRule
+    name -> report (UnexpectedXmlElement name "annotation") $> mempty
+
+-- | Parse @sectionType@
+parseSection :: PandocMonad m => Element -> FB2 m Blocks
+parseSection e = do
+  n <- gets fb2SectionLevel
+  modify $ \st -> st{ fb2SectionLevel = n + 1 }
+  let sectionId = fromMaybe "" $ findAttr (unqual "id") e
+  bs <- divWith (sectionId, ["section"], []) . mconcat <$> mapM parseSectionChild (elChildren e)
+  modify $ \st -> st{ fb2SectionLevel = n }
+  pure bs
+
+parseSectionChild :: PandocMonad m => Element -> FB2 m Blocks
+parseSectionChild e =
+  case qName $ elName e of
+    "title" -> parseBodyChild e
+    "epigraph" -> parseEpigraph e
+    "image" -> parseImageElement e
+    "annotation" -> parseAnnotation e
+    "poem" -> parsePoem e
+    "cite" -> parseCite e
+    "empty-line" -> pure horizontalRule
+    "table" -> parseTable e
+    "subtitle" -> parseSubtitle e
+    "p" -> para <$> parsePType e
+    "section" -> parseSection e
+    name -> report (UnexpectedXmlElement name "section") $> mempty
+
+-- | parse @styleType@
+parseStyleType :: PandocMonad m => Element -> FB2 m Inlines
+parseStyleType e = mconcat <$> mapM parseInline (elContent e)
+
+-- | Parse @namedStyleType@
+parseNamedStyle :: PandocMonad m => Element -> FB2 m Inlines
+parseNamedStyle e = do
+  content <- mconcat <$> mapM parseNamedStyleChild (elContent e)
+  let lang = maybeToList $ ("lang",) <$> findAttr (QName "lang" Nothing (Just "xml")) e
+  case findAttr (unqual "name") e of
+    Just name -> pure $ spanWith ("", [name], lang) content
+    Nothing -> do
+      report $ IgnoredElement "link without required name"
+      pure mempty
+
+parseNamedStyleChild :: PandocMonad m => Content -> FB2 m Inlines
+parseNamedStyleChild (Elem e) =
+  case qName (elName e) of
+    "strong" -> strong <$> parseStyleType e
+    "emphasis" -> emph <$> parseStyleType e
+    "style" -> parseNamedStyle e
+    "a" -> parseLinkType e
+    "strikethrough" -> strikeout <$> parseStyleType e
+    "sub" -> subscript <$> parseStyleType e
+    "sup" -> superscript <$> parseStyleType e
+    "code" -> pure $ code $ strContent e
+    "image" -> parseInlineImageElement e
+    name -> do
+      report $ IgnoredElement $ name <> " in style"
+      pure mempty
+parseNamedStyleChild x = parseInline x
+
+-- | Parse @linkType@
+parseLinkType :: PandocMonad m => Element -> FB2 m Inlines
+parseLinkType e = do
+  content <- mconcat <$> mapM parseStyleLinkType (elContent e)
+  notes <- gets fb2Notes
+  case findAttr (QName "href" (Just "http://www.w3.org/1999/xlink") Nothing) e of
+    Just href -> case findAttr (QName "type" Nothing Nothing) e of
+                   Just "note" -> case M.lookup href notes of
+                                    Nothing -> pure $ link href "" content
+                                    Just contents -> pure $ note contents
+                   _ -> pure $ link href "" content
+    Nothing -> do
+      report $ IgnoredElement "link without required href"
+      pure mempty
+
+-- | Parse @styleLinkType@
+parseStyleLinkType :: PandocMonad m => Content -> FB2 m Inlines
+parseStyleLinkType x@(Elem e) =
+  case qName (elName e) of
+    "a" -> do
+      report $ IgnoredElement "nested link"
+      pure mempty
+    _ -> parseInline x
+parseStyleLinkType x = parseInline x
+
+-- | Parse @tableType@
+parseTable :: PandocMonad m => Element -> FB2 m Blocks
+parseTable _ = pure mempty -- TODO: tables are not supported yet
+
+-- | Parse @title-infoType@
+parseTitleInfoChild :: PandocMonad m => Element -> FB2 m ()
+parseTitleInfoChild e =
+  case qName (elName e) of
+    "genre" -> pure ()
+    "author" -> parseAuthor e >>= \author -> modify (\st -> st {fb2Authors = author:fb2Authors st})
+    "book-title" -> modify (setMeta "title" (text $ strContent e))
+    "annotation" -> parseAnnotation e >>= modify . setMeta "abstract"
+    "keywords" -> modify (setMeta "keywords" (map (MetaString . trim) $ T.splitOn ","
+                                                                      $ strContent e))
+    "date" -> modify (setMeta "date" (text $ strContent e))
+    "coverpage" -> parseCoverPage e
+    "lang" -> pure ()
+    "src-lang" -> pure ()
+    "translator" -> pure ()
+    "sequence" -> pure ()
+    name -> report $ IgnoredElement $ name <> " in title-info"
+
+parseCoverPage :: PandocMonad m => Element -> FB2 m ()
+parseCoverPage e =
+  case findChild (QName "image" (Just "http://www.gribuser.ru/xml/fictionbook/2.0") Nothing) e of
+    Just img -> case href of
+                  Just src -> modify (setMeta "cover-image" (MetaString $ removeHash src))
+                  Nothing -> pure ()
+                where href = findAttr (QName "href" (Just "http://www.w3.org/1999/xlink") Nothing) img
+    Nothing -> pure ()
+
+-- | Parse @inlineImageType@ element
+parseInlineImageElement :: PandocMonad m
+                        => Element
+                        -> FB2 m Inlines
+parseInlineImageElement e =
+  case href of
+    Just src -> pure $ imageWith ("", [], []) (removeHash src) "" alt
+    Nothing -> do
+      report $ IgnoredElement "inline image without href"
+      pure mempty
+  where alt = maybe mempty str $ findAttr (unqual "alt") e
+        href = findAttr (QName "href" (Just "http://www.w3.org/1999/xlink") Nothing) e
diff --git a/src/Text/Pandoc/Readers/HTML.hs b/src/Text/Pandoc/Readers/HTML.hs
--- a/src/Text/Pandoc/Readers/HTML.hs
+++ b/src/Text/Pandoc/Readers/HTML.hs
@@ -1,1313 +1,1242 @@
-{-# LANGUAGE FlexibleContexts      #-}
-{-# LANGUAGE FlexibleInstances     #-}
-{-# LANGUAGE MultiParamTypeClasses #-}
-{-# LANGUAGE OverloadedStrings     #-}
-{-# LANGUAGE ViewPatterns          #-}
-{-
-Copyright (C) 2006-2017 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-2017 John MacFarlane
-   License     : GNU GPL, version 2 or above
-
-   Maintainer  : John MacFarlane <jgm@berkeley.edu>
-   Stability   : alpha
-   Portability : portable
-
-Conversion of HTML to 'Pandoc' document.
--}
-module Text.Pandoc.Readers.HTML ( readHtml
-                                , htmlTag
-                                , htmlInBalanced
-                                , isInlineTag
-                                , isBlockTag
-                                , NamedTag(..)
-                                , isTextTag
-                                , isCommentTag
-                                ) where
-
-import Control.Applicative ((<|>))
-import Control.Arrow ((***))
-import Control.Monad (guard, mplus, msum, mzero, unless, void)
-import Control.Monad.Except (throwError)
-import Control.Monad.Reader (ReaderT, ask, asks, lift, local, runReaderT)
-import Data.Char (isAlphaNum, isDigit, isLetter)
-import Data.Default (Default (..), def)
-import Data.Foldable (for_)
-import Data.List (intercalate, isPrefixOf)
-import Data.List.Split (wordsBy, splitWhen)
-import qualified Data.Map as M
-import Data.Maybe (fromMaybe, isJust, isNothing)
-import Data.Monoid (First (..), (<>))
-import qualified Data.Set as Set
-import Data.Text (Text)
-import qualified Data.Text as T
-import Network.URI (URI, nonStrictRelativeTo, parseURIReference)
-import Text.HTML.TagSoup
-import Text.HTML.TagSoup.Match
-import Text.Pandoc.Builder (Blocks, HasMeta (..), Inlines, trimInlines)
-import qualified Text.Pandoc.Builder as B
-import Text.Pandoc.Class (PandocMonad (..))
-import Text.Pandoc.CSS (foldOrElse, pickStyleAttrProps)
-import Text.Pandoc.Definition
-import Text.Pandoc.Error
-import Text.Pandoc.Logging
-import Text.Pandoc.Options (
-    Extension (Ext_epub_html_exts, Ext_empty_paragraphs, Ext_native_divs,
-               Ext_native_spans, Ext_raw_html, Ext_line_blocks),
-    ReaderOptions (readerExtensions, readerStripComments),
-    extensionEnabled)
-import Text.Pandoc.Parsing hiding ((<|>))
-import Text.Pandoc.Shared (addMetaField, blocksToInlines', crFilter, escapeURI,
-                           extractSpaces, safeRead, underlineSpan)
-import Text.Pandoc.Walk
-import Text.Parsec.Error
-import Text.TeXMath (readMathML, writeTeX)
-
--- | Convert HTML-formatted string to 'Pandoc' document.
-readHtml :: PandocMonad m
-         => ReaderOptions -- ^ Reader options
-         -> Text        -- ^ String to parse (assumes @'\n'@ line endings)
-         -> m Pandoc
-readHtml opts inp = do
-  let tags = stripPrefixes . canonicalizeTags $
-             parseTagsOptions parseOptions{ optTagPosition = True }
-             (crFilter inp)
-      parseDoc = do
-        blocks <- fixPlains False . mconcat <$> manyTill block eof
-        meta <- stateMeta . parserState <$> getState
-        bs' <- replaceNotes (B.toList blocks)
-        reportLogMessages
-        return $ Pandoc meta bs'
-      getError (errorMessages -> ms) = case ms of
-                                         []    -> ""
-                                         (m:_) -> messageString m
-  result <- flip runReaderT def $
-       runParserT parseDoc
-       (HTMLState def{ stateOptions = opts } [] Nothing Set.empty M.empty [])
-       "source" tags
-  case result of
-    Right doc -> return doc
-    Left  err -> throwError $ PandocParseError $ getError err
-
-replaceNotes :: PandocMonad m => [Block] -> TagParser m [Block]
-replaceNotes = walkM replaceNotes'
-
-replaceNotes' :: PandocMonad m => Inline -> TagParser m Inline
-replaceNotes' (RawInline (Format "noteref") ref) = maybe (Str "") (Note . B.toList) . lookup ref <$> getNotes
-  where
-    getNotes = noteTable <$> getState
-replaceNotes' x = return x
-
-data HTMLState =
-  HTMLState
-  {  parserState :: ParserState,
-     noteTable   :: [(String, Blocks)],
-     baseHref    :: Maybe URI,
-     identifiers :: Set.Set String,
-     headerMap   :: M.Map Inlines String,
-     logMessages :: [LogMessage]
-  }
-
-data HTMLLocal = HTMLLocal { quoteContext :: QuoteContext
-                           , inChapter    :: Bool -- ^ Set if in chapter section
-                           , inPlain      :: Bool -- ^ Set if in pPlain
-                           }
-
-setInChapter :: PandocMonad m => HTMLParser m s a -> HTMLParser m s a
-setInChapter = local (\s -> s {inChapter = True})
-
-setInPlain :: PandocMonad m => HTMLParser m s a -> HTMLParser m s a
-setInPlain = local (\s -> s {inPlain = True})
-
-type HTMLParser m s = ParserT s HTMLState (ReaderT HTMLLocal m)
-
-type TagParser m = HTMLParser m [Tag Text]
-
-pHtml :: PandocMonad m => TagParser m Blocks
-pHtml = try $ do
-  (TagOpen "html" attr) <- lookAhead pAnyTag
-  for_ (lookup "lang" attr) $
-    updateState . B.setMeta "lang" . B.text . T.unpack
-  pInTags "html" block
-
-pBody :: PandocMonad m => TagParser m Blocks
-pBody = pInTags "body" block
-
-pHead :: PandocMonad m => TagParser m Blocks
-pHead = pInTags "head" $ pTitle <|> pMetaTag <|> pBaseTag <|> (mempty <$ pAnyTag)
-  where pTitle = pInTags "title" inline >>= setTitle . trimInlines
-        setTitle t = mempty <$ updateState (B.setMeta "title" t)
-        pMetaTag = do
-          mt <- pSatisfy (matchTagOpen "meta" [])
-          let name = T.unpack $ fromAttrib "name" mt
-          if null name
-             then return mempty
-             else do
-               let content = T.unpack $ fromAttrib "content" mt
-               updateState $ \s ->
-                 let ps = parserState s in
-                 s{ parserState = ps{
-                      stateMeta = addMetaField name (B.text content)
-                                   (stateMeta ps) } }
-               return mempty
-        pBaseTag = do
-          bt <- pSatisfy (matchTagOpen "base" [])
-          updateState $ \st -> st{ baseHref =
-               parseURIReference $ T.unpack $ fromAttrib "href" bt }
-          return mempty
-
-block :: PandocMonad m => TagParser m Blocks
-block = do
-  res <- choice
-            [ eSection
-            , eSwitch B.para block
-            , mempty <$ eFootnote
-            , mempty <$ eTOC
-            , mempty <$ eTitlePage
-            , pPara
-            , pHeader
-            , pBlockQuote
-            , pCodeBlock
-            , pList
-            , pHrule
-            , pTable
-            , pHtml
-            , pHead
-            , pBody
-            , pLineBlock
-            , pDiv
-            , pPlain
-            , pFigure
-            , pRawHtmlBlock
-            ]
-  trace (take 60 $ show $ B.toList res)
-  return res
-
-namespaces :: PandocMonad m => [(String, TagParser m Inlines)]
-namespaces = [(mathMLNamespace, pMath True)]
-
-mathMLNamespace :: String
-mathMLNamespace = "http://www.w3.org/1998/Math/MathML"
-
-eSwitch :: (PandocMonad m, Monoid a)
-        => (Inlines -> a)
-        -> TagParser m a
-        -> TagParser m a
-eSwitch constructor parser = try $ do
-  guardEnabled Ext_epub_html_exts
-  pSatisfy (matchTagOpen "switch" [])
-  cases <- getFirst . mconcat <$>
-            manyTill (First <$> (eCase <* skipMany pBlank) )
-              (lookAhead $ try $ pSatisfy (matchTagOpen "default" []))
-  skipMany pBlank
-  fallback <- pInTags "default" (skipMany pBlank *> parser <* skipMany pBlank)
-  skipMany pBlank
-  pSatisfy (matchTagClose "switch")
-  return $ maybe fallback constructor cases
-
-eCase :: PandocMonad m => TagParser m (Maybe Inlines)
-eCase = do
-  skipMany pBlank
-  TagOpen _ attr' <- lookAhead $ pSatisfy (matchTagOpen "case" [])
-  let attr = toStringAttr attr'
-  case flip lookup namespaces =<< lookup "required-namespace" attr of
-    Just p -> Just <$> pInTags "case" (skipMany pBlank *> p <* skipMany pBlank)
-    Nothing -> Nothing <$ manyTill pAnyTag (pSatisfy (matchTagClose "case"))
-
-eFootnote :: PandocMonad m => TagParser m ()
-eFootnote = try $ do
-  let notes = ["footnote", "rearnote"]
-  guardEnabled Ext_epub_html_exts
-  (TagOpen tag attr') <- lookAhead pAnyTag
-  let attr = toStringAttr attr'
-  guard $ maybe False (`elem` notes) (lookup "type" attr)
-  let ident = fromMaybe "" (lookup "id" attr)
-  content <- pInTags tag block
-  addNote ident content
-
-addNote :: PandocMonad m => String -> Blocks -> TagParser m ()
-addNote uid cont = updateState (\s -> s {noteTable = (uid, cont) : noteTable s})
-
-eNoteref :: PandocMonad m => TagParser m Inlines
-eNoteref = try $ do
-  guardEnabled Ext_epub_html_exts
-  TagOpen tag attr' <- lookAhead pAnyTag
-  let attr = toStringAttr attr'
-  guard $ lookup "type" attr == Just "noteref"
-  let ident = maybe "" (dropWhile (== '#')) (lookup "href" attr)
-  guard (not (null ident))
-  pInTags tag block
-  return $ B.rawInline "noteref" ident
-
--- Strip TOC if there is one, better to generate again
-eTOC :: PandocMonad m => TagParser m ()
-eTOC = try $ do
-  guardEnabled Ext_epub_html_exts
-  (TagOpen tag attr) <- lookAhead pAnyTag
-  guard $ lookup "type" attr == Just "toc"
-  void (pInTags tag block)
-
-pList :: PandocMonad m => TagParser m Blocks
-pList = pBulletList <|> pOrderedList <|> pDefinitionList
-
-pBulletList :: PandocMonad m => TagParser m Blocks
-pBulletList = try $ do
-  pSatisfy (matchTagOpen "ul" [])
-  let nonItem = pSatisfy (\t ->
-                  not (tagOpen (`elem` ["li","ol","ul","dl"]) (const True) t) &&
-                  not (matchTagClose "ul" t))
-  -- note: if they have an <ol> or <ul> not in scope of a <li>,
-  -- treat it as a list item, though it's not valid xhtml...
-  skipMany nonItem
-  items <- manyTill (pListItem nonItem) (pCloses "ul")
-  return $ B.bulletList $ map (fixPlains True) items
-
-pListItem :: PandocMonad m => TagParser m a -> TagParser m Blocks
-pListItem nonItem = do
-  TagOpen _ attr' <- lookAhead $ pSatisfy (matchTagOpen "li" [])
-  let attr = toStringAttr attr'
-  let addId ident bs = case B.toList bs of
-                           (Plain ils:xs) -> B.fromList (Plain
-                                [Span (ident, [], []) ils] : xs)
-                           _ -> B.divWith (ident, [], []) bs
-  maybe id addId (lookup "id" attr) <$>
-    pInTags "li" block <* skipMany nonItem
-
-parseListStyleType :: String -> ListNumberStyle
-parseListStyleType "lower-roman" = LowerRoman
-parseListStyleType "upper-roman" = UpperRoman
-parseListStyleType "lower-alpha" = LowerAlpha
-parseListStyleType "upper-alpha" = UpperAlpha
-parseListStyleType "decimal"     = Decimal
-parseListStyleType _             = DefaultStyle
-
-parseTypeAttr :: String -> ListNumberStyle
-parseTypeAttr "i" = LowerRoman
-parseTypeAttr "I" = UpperRoman
-parseTypeAttr "a" = LowerAlpha
-parseTypeAttr "A" = UpperAlpha
-parseTypeAttr "1" = Decimal
-parseTypeAttr _   = DefaultStyle
-
-pOrderedList :: PandocMonad m => TagParser m Blocks
-pOrderedList = try $ do
-  TagOpen _ attribs' <- pSatisfy (matchTagOpen "ol" [])
-  let attribs = toStringAttr attribs'
-  let (start, style) = (sta', sty')
-                       where sta = fromMaybe "1" $
-                                   lookup "start" attribs
-                             sta' = if all isDigit sta
-                                       then read sta
-                                       else 1
-
-                             pickListStyle = pickStyleAttrProps ["list-style-type", "list-style"]
-
-                             typeAttr  = fromMaybe "" $ lookup "type"  attribs
-                             classAttr = fromMaybe "" $ lookup "class" attribs
-                             styleAttr = fromMaybe "" $ lookup "style" attribs
-                             listStyle = fromMaybe "" $ pickListStyle styleAttr
-
-                             sty' = foldOrElse DefaultStyle
-                                      [ parseTypeAttr      typeAttr
-                                      , parseListStyleType classAttr
-                                      , parseListStyleType listStyle
-                                      ]
-  let nonItem = pSatisfy (\t ->
-                  not (tagOpen (`elem` ["li","ol","ul","dl"]) (const True) t) &&
-                  not (matchTagClose "ol" t))
-  -- note: if they have an <ol> or <ul> not in scope of a <li>,
-  -- treat it as a list item, though it's not valid xhtml...
-  skipMany nonItem
-  items <- manyTill (pListItem nonItem) (pCloses "ol")
-  return $ B.orderedListWith (start, style, DefaultDelim) $ map (fixPlains True) items
-
-pDefinitionList :: PandocMonad m => TagParser m Blocks
-pDefinitionList = try $ do
-  pSatisfy (matchTagOpen "dl" [])
-  items <- manyTill pDefListItem (pCloses "dl")
-  return $ B.definitionList items
-
-pDefListItem :: PandocMonad m => TagParser m (Inlines, [Blocks])
-pDefListItem = try $ do
-  let nonItem = pSatisfy (\t -> not (matchTagOpen "dt" [] t) &&
-                  not (matchTagOpen "dd" [] t) && not (matchTagClose "dl" t))
-  terms <- many1 (try $ skipMany nonItem >> pInTags "dt" inline)
-  defs  <- many1 (try $ skipMany nonItem >> pInTags "dd" block)
-  skipMany nonItem
-  let term = foldl1 (\x y ->  x <> B.linebreak <> y) terms
-  return (term, map (fixPlains True) defs)
-
-fixPlains :: Bool -> Blocks -> Blocks
-fixPlains inList bs = if any isParaish bs'
-                         then B.fromList $ map plainToPara bs'
-                         else bs
-  where isParaish Para{}           = True
-        isParaish CodeBlock{}      = True
-        isParaish Header{}         = True
-        isParaish BlockQuote{}     = True
-        isParaish BulletList{}     = not inList
-        isParaish OrderedList{}    = not inList
-        isParaish DefinitionList{} = not inList
-        isParaish _                = False
-        plainToPara (Plain xs) = Para xs
-        plainToPara x          = x
-        bs' = B.toList bs
-
-pRawTag :: PandocMonad m => TagParser m Text
-pRawTag = do
-  tag <- pAnyTag
-  let ignorable x = x `elem` ["html","head","body","!DOCTYPE","?xml"]
-  if tagOpen ignorable (const True) tag || tagClose ignorable tag
-     then return mempty
-     else return $ renderTags' [tag]
-
-pLineBlock :: PandocMonad m => TagParser m Blocks
-pLineBlock = try $ do
-  guardEnabled Ext_line_blocks
-  _ <- pSatisfy $ tagOpen (=="div") (== [("class","line-block")])
-  ils <- trimInlines . mconcat <$> manyTill inline (pSatisfy (tagClose (=="div")))
-  let lns = map B.fromList $
-            splitWhen (== LineBreak) $ filter (/= SoftBreak) $
-            B.toList ils
-  return $ B.lineBlock lns
-
-pDiv :: PandocMonad m => TagParser m Blocks
-pDiv = try $ do
-  guardEnabled Ext_native_divs
-  let isDivLike "div"     = True
-      isDivLike "section" = True
-      isDivLike "main"    = True
-      isDivLike _         = False
-  TagOpen tag attr' <- lookAhead $ pSatisfy $ tagOpen isDivLike (const True)
-  let attr = toStringAttr attr'
-  contents <- pInTags tag block
-  let (ident, classes, kvs) = mkAttr attr
-  let classes' = if tag == "section"
-                    then "section":classes
-                    else classes
-      kvs' = if tag == "main" && isNothing (lookup "role" kvs)
-               then ("role", "main"):kvs
-               else kvs
-  return $ B.divWith (ident, classes', kvs') contents
-
-pRawHtmlBlock :: PandocMonad m => TagParser m Blocks
-pRawHtmlBlock = do
-  raw <- T.unpack <$> (pHtmlBlock "script" <|> pHtmlBlock "style" <|> pRawTag)
-  exts <- getOption readerExtensions
-  if extensionEnabled Ext_raw_html exts && not (null raw)
-     then return $ B.rawBlock "html" raw
-     else ignore raw
-
-ignore :: (Monoid a, PandocMonad m) => String -> TagParser m a
-ignore raw = do
-  pos <- getPosition
-  -- raw can be null for tags like <!DOCTYPE>; see paRawTag
-  -- in this case we don't want a warning:
-  unless (null raw) $
-    logMessage $ SkippedContent raw pos
-  return mempty
-
-pHtmlBlock :: PandocMonad m => Text -> TagParser m Text
-pHtmlBlock t = try $ do
-  open <- pSatisfy (matchTagOpen t [])
-  contents <- manyTill pAnyTag (pSatisfy (matchTagClose t))
-  return $ renderTags' $ [open] <> contents <> [TagClose t]
-
--- Sets chapter context
-eSection :: PandocMonad m => TagParser m Blocks
-eSection = try $ do
-  let matchChapter as = maybe False (T.isInfixOf "chapter") (lookup "type" as)
-  let sectTag = tagOpen (`elem` sectioningContent) matchChapter
-  TagOpen tag _ <- lookAhead $ pSatisfy sectTag
-  setInChapter (pInTags tag block)
-
-headerLevel :: PandocMonad m => Text -> TagParser m Int
-headerLevel tagtype =
-  case safeRead (T.unpack (T.drop 1 tagtype)) of
-        Just level ->
---          try (do
---            guardEnabled Ext_epub_html_exts
---            asks inChapter >>= guard
---            return (level - 1))
---            <|>
-              return level
-        Nothing -> fail "Could not retrieve header level"
-
-eTitlePage :: PandocMonad m => TagParser m ()
-eTitlePage = try $ do
-  let isTitlePage as = maybe False (T.isInfixOf "titlepage") (lookup "type" as)
-  let groupTag = tagOpen (\x -> x `elem` groupingContent || x == "section")
-                          isTitlePage
-  TagOpen tag _ <- lookAhead $ pSatisfy groupTag
-  () <$ pInTags tag block
-
-pHeader :: PandocMonad m => TagParser m Blocks
-pHeader = try $ do
-  TagOpen tagtype attr' <- pSatisfy $
-                           tagOpen (`elem` ["h1","h2","h3","h4","h5","h6"])
-                           (const True)
-  let attr = toStringAttr attr'
-  let bodyTitle = TagOpen tagtype attr' ~== TagOpen ("h1" :: Text)
-                                               [("class","title")]
-  level <- headerLevel tagtype
-  contents <- trimInlines . mconcat <$> manyTill inline (pCloses tagtype <|> eof)
-  let ident = fromMaybe "" $ lookup "id" attr
-  let classes = maybe [] words $ lookup "class" attr
-  let keyvals = [(k,v) | (k,v) <- attr, k /= "class", k /= "id"]
-  attr'' <- registerHeader (ident, classes, keyvals) contents
-  return $ if bodyTitle
-              then mempty  -- skip a representation of the title in the body
-              else B.headerWith attr'' level contents
-
-pHrule :: PandocMonad m => TagParser m Blocks
-pHrule = do
-  pSelfClosing (=="hr") (const True)
-  return B.horizontalRule
-
-pTable :: PandocMonad m => TagParser m Blocks
-pTable = try $ do
-  TagOpen _ _ <- pSatisfy (matchTagOpen "table" [])
-  skipMany pBlank
-  caption <- option mempty $ pInTags "caption" inline <* skipMany pBlank
-  widths' <- (mconcat <$> many1 pColgroup) <|> many pCol
-  let pTh = option [] $ pInTags "tr" (pCell "th")
-      pTr = try $ skipMany pBlank >>
-                  pInTags "tr" (pCell "td" <|> pCell "th")
-      pTBody = pOptInTag "tbody" $ many1 pTr
-  head'' <- pOptInTag "thead" pTh
-  head'  <- map snd <$>
-             pOptInTag "tbody"
-               (if null head'' then pTh else return head'')
-  rowsLs <- many pTBody
-  rows'  <- pOptInTag "tfoot" $ many pTr
-  TagClose _ <- pSatisfy (matchTagClose "table")
-  let rows'' = concat rowsLs <> rows'
-  let rows''' = map (map snd) rows''
-  -- let rows''' = map (map snd) rows''
-  -- fail on empty table
-  guard $ not $ null head' && null rows'''
-  let isSinglePlain x = case B.toList x of
-                             []        -> True
-                             [Plain _] -> True
-                             _         -> False
-  let isSimple = all isSinglePlain $ concat (head':rows''')
-  let cols = length $ if null head' then head rows''' else head'
-  -- add empty cells to short rows
-  let addEmpties r = case cols - length r of
-                           n | n > 0 -> r <> replicate n mempty
-                             | otherwise -> r
-  let rows = map addEmpties rows'''
-  let aligns = case rows'' of
-                    (cs:_) -> map fst cs
-                    _      -> replicate cols AlignDefault
-  let widths = if null widths'
-                  then if isSimple
-                       then replicate cols 0
-                       else replicate cols (1.0 / fromIntegral cols)
-                  else widths'
-  return $ B.table caption (zip aligns widths) head' rows
-
-pCol :: PandocMonad m => TagParser m Double
-pCol = try $ do
-  TagOpen _ attribs' <- pSatisfy (matchTagOpen "col" [])
-  let attribs = toStringAttr attribs'
-  skipMany pBlank
-  optional $ pSatisfy (matchTagClose "col")
-  skipMany pBlank
-  return $ case lookup "width" attribs of
-           Nothing -> case lookup "style" attribs of
-               Just ('w':'i':'d':'t':'h':':':xs) | '%' `elem` xs ->
-                 fromMaybe 0.0 $ safeRead ('0':'.':filter
-                   (`notElem` (" \t\r\n%'\";" :: [Char])) xs)
-               _ -> 0.0
-           Just x | not (null x) && last x == '%' ->
-             fromMaybe 0.0 $ safeRead ('0':'.':init x)
-           _ -> 0.0
-
-pColgroup :: PandocMonad m => TagParser m [Double]
-pColgroup = try $ do
-  pSatisfy (matchTagOpen "colgroup" [])
-  skipMany pBlank
-  manyTill pCol (pCloses "colgroup" <|> eof) <* skipMany pBlank
-
-noColOrRowSpans :: Tag Text -> Bool
-noColOrRowSpans t = isNullOrOne "colspan" && isNullOrOne "rowspan"
-  where isNullOrOne x = case fromAttrib x t of
-                              ""  -> True
-                              "1" -> True
-                              _   -> False
-
-pCell :: PandocMonad m => Text -> TagParser m [(Alignment, Blocks)]
-pCell celltype = try $ do
-  skipMany pBlank
-  tag <- lookAhead $
-           pSatisfy (\t -> t ~== TagOpen celltype [] && noColOrRowSpans t)
-  let extractAlign' []                 = ""
-      extractAlign' ("text-align":x:_) = x
-      extractAlign' (_:xs)             = extractAlign' xs
-  let extractAlign = extractAlign' . wordsBy (`elem` [' ','\t',';',':'])
-  let align = case maybeFromAttrib "align" tag `mplus`
-                   (extractAlign <$> maybeFromAttrib "style" tag) of
-                   Just "left"   -> AlignLeft
-                   Just "right"  -> AlignRight
-                   Just "center" -> AlignCenter
-                   _             -> AlignDefault
-  res <- pInTags' celltype noColOrRowSpans block
-  skipMany pBlank
-  return [(align, res)]
-
-pBlockQuote :: PandocMonad m => TagParser m Blocks
-pBlockQuote = do
-  contents <- pInTags "blockquote" block
-  return $ B.blockQuote $ fixPlains False contents
-
-pPlain :: PandocMonad m => TagParser m Blocks
-pPlain = do
-  contents <- setInPlain $ trimInlines . mconcat <$> many1 inline
-  if B.isNull contents
-     then return mempty
-     else return $ B.plain contents
-
-pPara :: PandocMonad m => TagParser m Blocks
-pPara = do
-  contents <- trimInlines <$> pInTags "p" inline
-  (do guardDisabled Ext_empty_paragraphs
-      guard (B.isNull contents)
-      return mempty)
-    <|> return (B.para contents)
-
-pFigure :: PandocMonad m => TagParser m Blocks
-pFigure = try $ do
-  TagOpen _ _ <- pSatisfy (matchTagOpen "figure" [])
-  skipMany pBlank
-  let pImg  = (\x -> (Just x, Nothing)) <$>
-               (pOptInTag "p" pImage <* skipMany pBlank)
-      pCapt = (\x -> (Nothing, Just x)) <$> do
-                bs <- pInTags "figcaption" block
-                return $ blocksToInlines' $ B.toList bs
-      pSkip = (Nothing, Nothing) <$ pSatisfy (not . matchTagClose "figure")
-  res <- many (pImg <|> pCapt <|> pSkip)
-  let mbimg = msum $ map fst res
-  let mbcap = msum $ map snd res
-  TagClose _ <- pSatisfy (matchTagClose "figure")
-  let caption = fromMaybe mempty mbcap
-  case B.toList <$> mbimg of
-       Just [Image attr _ (url, tit)] ->
-         return $ B.para $ B.imageWith attr url ("fig:" ++ tit) caption
-       _ -> mzero
-
-pCodeBlock :: PandocMonad m => TagParser m Blocks
-pCodeBlock = try $ do
-  TagOpen _ attr' <- pSatisfy (matchTagOpen "pre" [])
-  let attr = toStringAttr attr'
-  contents <- manyTill pAnyTag (pCloses "pre" <|> eof)
-  let rawText = concatMap tagToString contents
-  -- drop leading newline if any
-  let result' = case rawText of
-                     '\n':xs -> xs
-                     _       -> rawText
-  -- drop trailing newline if any
-  let result = case reverse result' of
-                    '\n':_ -> init result'
-                    _      -> result'
-  return $ B.codeBlockWith (mkAttr attr) result
-
-tagToString :: Tag Text -> String
-tagToString (TagText s)      = T.unpack s
-tagToString (TagOpen "br" _) = "\n"
-tagToString _                = ""
-
-inline :: PandocMonad m => TagParser m Inlines
-inline = choice
-           [ eNoteref
-           , eSwitch id inline
-           , pTagText
-           , pQ
-           , pEmph
-           , pStrong
-           , pSuperscript
-           , pSubscript
-           , pStrikeout
-           , pUnderline
-           , pLineBreak
-           , pLink
-           , pImage
-           , pCode
-           , pSpan
-           , pMath False
-           , pRawHtmlInline
-           ]
-
-pLocation :: PandocMonad m => TagParser m ()
-pLocation = do
-  (TagPosition r c) <- pSat isTagPosition
-  setPosition $ newPos "input" r c
-
-pSat :: PandocMonad m => (Tag Text -> Bool) -> TagParser m (Tag Text)
-pSat f = do
-  pos <- getPosition
-  token show (const pos) (\x -> if f x then Just x else Nothing)
-
-pSatisfy :: PandocMonad m => (Tag Text -> Bool) -> TagParser m (Tag Text)
-pSatisfy f = try $ optional pLocation >> pSat f
-
-pAnyTag :: PandocMonad m => TagParser m (Tag Text)
-pAnyTag = pSatisfy (const True)
-
-pSelfClosing :: PandocMonad m
-             => (Text -> Bool) -> ([Attribute Text] -> Bool)
-             -> TagParser m (Tag Text)
-pSelfClosing f g = do
-  open <- pSatisfy (tagOpen f g)
-  optional $ pSatisfy (tagClose f)
-  return open
-
-pQ :: PandocMonad m => TagParser m Inlines
-pQ = do
-  context <- asks quoteContext
-  let quoteType = case context of
-                       InDoubleQuote -> SingleQuote
-                       _             -> DoubleQuote
-  let innerQuoteContext = if quoteType == SingleQuote
-                             then InSingleQuote
-                             else InDoubleQuote
-  let constructor = case quoteType of
-                            SingleQuote -> B.singleQuoted
-                            DoubleQuote -> B.doubleQuoted
-  withQuoteContext innerQuoteContext $
-    pInlinesInTags "q" constructor
-
-pEmph :: PandocMonad m => TagParser m Inlines
-pEmph = pInlinesInTags "em" B.emph <|> pInlinesInTags "i" B.emph
-
-pStrong :: PandocMonad m => TagParser m Inlines
-pStrong = pInlinesInTags "strong" B.strong <|> pInlinesInTags "b" B.strong
-
-pSuperscript :: PandocMonad m => TagParser m Inlines
-pSuperscript = pInlinesInTags "sup" B.superscript
-
-pSubscript :: PandocMonad m => TagParser m Inlines
-pSubscript = pInlinesInTags "sub" B.subscript
-
-pStrikeout :: PandocMonad m => TagParser m Inlines
-pStrikeout =
-  pInlinesInTags "s" B.strikeout <|>
-    pInlinesInTags "strike" B.strikeout <|>
-    pInlinesInTags "del" B.strikeout <|>
-    try (do pSatisfy (matchTagOpen "span" [("class","strikeout")])
-            contents <- mconcat <$> manyTill inline (pCloses "span")
-            return $ B.strikeout contents)
-
-pUnderline :: PandocMonad m => TagParser m Inlines
-pUnderline = pInlinesInTags "u" underlineSpan <|> pInlinesInTags "ins" underlineSpan
-
-pLineBreak :: PandocMonad m => TagParser m Inlines
-pLineBreak = do
-  pSelfClosing (=="br") (const True)
-  return B.linebreak
-
--- Unlike fromAttrib from tagsoup, this distinguishes
--- between a missing attribute and an attribute with empty content.
-maybeFromAttrib :: String -> Tag Text -> Maybe String
-maybeFromAttrib name (TagOpen _ attrs) =
-  T.unpack <$> lookup (T.pack name) attrs
-maybeFromAttrib _ _ = Nothing
-
-pLink :: PandocMonad m => TagParser m Inlines
-pLink = try $ do
-  tag <- pSatisfy $ tagOpenLit "a" (const True)
-  let title = T.unpack $ fromAttrib "title" tag
-  -- take id from id attribute if present, otherwise name
-  let uid = fromMaybe (T.unpack $ fromAttrib "name" tag) $
-               maybeFromAttrib "id" tag
-  let cls = words $ T.unpack $ fromAttrib "class" tag
-  lab <- trimInlines . mconcat <$> manyTill inline (pCloses "a")
-  -- check for href; if href, then a link, otherwise a span
-  case maybeFromAttrib "href" tag of
-       Nothing   ->
-         return $ B.spanWith (uid, cls, []) lab
-       Just url' -> do
-         mbBaseHref <- baseHref <$> getState
-         let url = case (parseURIReference url', mbBaseHref) of
-                        (Just rel, Just bs) ->
-                          show (rel `nonStrictRelativeTo` bs)
-                        _                   -> url'
-         return $ B.linkWith (uid, cls, []) (escapeURI url) title lab
-
-pImage :: PandocMonad m => TagParser m Inlines
-pImage = do
-  tag <- pSelfClosing (=="img") (isJust . lookup "src")
-  mbBaseHref <- baseHref <$> getState
-  let url' = T.unpack $ fromAttrib "src" tag
-  let url = case (parseURIReference url', mbBaseHref) of
-                 (Just rel, Just bs) -> show (rel `nonStrictRelativeTo` bs)
-                 _                   -> url'
-  let title = T.unpack $ fromAttrib "title" tag
-  let alt = T.unpack $ fromAttrib "alt" tag
-  let uid = T.unpack $ fromAttrib "id" tag
-  let cls = words $ T.unpack $ fromAttrib "class" tag
-  let getAtt k = case fromAttrib k tag of
-                   "" -> []
-                   v  -> [(T.unpack k, T.unpack v)]
-  let kvs = concatMap getAtt ["width", "height", "sizes", "srcset"]
-  return $ B.imageWith (uid, cls, kvs) (escapeURI url) title (B.text alt)
-
-pCode :: PandocMonad m => TagParser m Inlines
-pCode = try $ do
-  (TagOpen open attr') <- pSatisfy $ tagOpen (`elem` ["code","tt"]) (const True)
-  let attr = toStringAttr attr'
-  result <- manyTill pAnyTag (pCloses open)
-  return $ B.codeWith (mkAttr attr) $ intercalate " " $ lines $ T.unpack $
-           innerText result
-
-pSpan :: PandocMonad m => TagParser m Inlines
-pSpan = try $ do
-  guardEnabled Ext_native_spans
-  TagOpen _ attr' <- lookAhead $ pSatisfy $ tagOpen (=="span") (const True)
-  let attr = toStringAttr attr'
-  contents <- pInTags "span" inline
-  let isSmallCaps = fontVariant == "small-caps" || "smallcaps" `elem` classes
-                    where styleAttr   = fromMaybe "" $ lookup "style" attr
-                          fontVariant = fromMaybe "" $ pickStyleAttrProps ["font-variant"] styleAttr
-                          classes     = fromMaybe [] $
-                                          words <$> lookup "class" attr
-  let tag = if isSmallCaps then B.smallcaps else B.spanWith (mkAttr attr)
-  return $ tag contents
-
-pRawHtmlInline :: PandocMonad m => TagParser m Inlines
-pRawHtmlInline = do
-  inplain <- asks inPlain
-  result <- pSatisfy (tagComment (const True))
-            <|> if inplain
-                   then pSatisfy (not . isBlockTag)
-                   else pSatisfy isInlineTag
-  exts <- getOption readerExtensions
-  let raw = T.unpack $ renderTags' [result]
-  if extensionEnabled Ext_raw_html exts
-     then return $ B.rawInline "html" raw
-     else ignore raw
-
-mathMLToTeXMath :: String -> Either String String
-mathMLToTeXMath s = writeTeX <$> readMathML s
-
-toStringAttr :: [(Text, Text)] -> [(String, String)]
-toStringAttr = map go
-  where go (x,y) = (T.unpack x, T.unpack y)
-
-pMath :: PandocMonad m => Bool -> TagParser m Inlines
-pMath inCase = try $ do
-  open@(TagOpen _ attr') <- pSatisfy $ tagOpen (=="math") (const True)
-  -- we'll assume math tags are MathML unless specially marked
-  -- otherwise...
-  let attr = toStringAttr attr'
-  unless inCase $
-    guard (maybe True (== mathMLNamespace) (lookup "xmlns" attr))
-  contents <- manyTill pAnyTag (pSatisfy (matchTagClose "math"))
-  case mathMLToTeXMath (T.unpack $ renderTags $
-          [open] <> contents <> [TagClose "math"]) of
-       Left _   -> return $ B.spanWith ("",["math"],attr) $ B.text $
-                             T.unpack $ innerText contents
-       Right [] -> return mempty
-       Right x  -> return $ case lookup "display" attr of
-                                 Just "block" -> B.displayMath x
-                                 _            -> B.math x
-
-pInlinesInTags :: PandocMonad m => Text -> (Inlines -> Inlines)
-               -> TagParser m Inlines
-pInlinesInTags tagtype f = extractSpaces f <$> pInTags tagtype inline
-
-pInTags :: (PandocMonad m, Monoid a) => Text -> TagParser m a -> TagParser m a
-pInTags tagtype parser = pInTags' tagtype (const True) parser
-
-pInTags' :: (PandocMonad m, Monoid a)
-         => Text
-         -> (Tag Text -> Bool)
-         -> TagParser m a
-         -> TagParser m a
-pInTags' tagtype tagtest parser = try $ do
-  pSatisfy (\t -> t ~== TagOpen tagtype [] && tagtest t)
-  mconcat <$> manyTill parser (pCloses tagtype <|> eof)
-
--- parses p, preceeded by an optional opening tag
--- and followed by an optional closing tags
-pOptInTag :: PandocMonad m => Text -> TagParser m a -> TagParser m a
-pOptInTag tagtype p = try $ do
-  skipMany pBlank
-  optional $ pSatisfy (matchTagOpen tagtype [])
-  skipMany pBlank
-  x <- p
-  skipMany pBlank
-  optional $ pSatisfy (matchTagClose tagtype)
-  skipMany pBlank
-  return x
-
-pCloses :: PandocMonad m => Text -> TagParser m ()
-pCloses tagtype = try $ do
-  t <- lookAhead $ pSatisfy $ \tag -> isTagClose tag || isTagOpen tag
-  case t of
-       (TagClose t') | t' == tagtype -> void pAnyTag
-       (TagOpen t' _) | t' `closes` tagtype -> return ()
-       (TagClose "ul") | tagtype == "li" -> return ()
-       (TagClose "ol") | tagtype == "li" -> return ()
-       (TagClose "dl") | tagtype == "dd" -> return ()
-       (TagClose "table") | tagtype == "td" -> return ()
-       (TagClose "table") | tagtype == "tr" -> return ()
-       (TagClose "td") | tagtype `Set.member` blockHtmlTags -> return ()
-       (TagClose "th") | tagtype `Set.member` blockHtmlTags -> return ()
-       (TagClose t') | tagtype == "p" && t' `Set.member` blockHtmlTags
-                                            -> return () -- see #3794
-       _ -> mzero
-
-pTagText :: PandocMonad m => TagParser m Inlines
-pTagText = try $ do
-  (TagText str) <- pSatisfy isTagText
-  st <- getState
-  qu <- ask
-  parsed <- lift $ lift $
-            flip runReaderT qu $ runParserT (many pTagContents) st "text" str
-  case parsed of
-       Left _        -> throwError $ PandocParseError $ "Could not parse `" <> T.unpack str <> "'"
-       Right result  -> return $ mconcat result
-
-pBlank :: PandocMonad m => TagParser m ()
-pBlank = try $ do
-  (TagText str) <- pSatisfy isTagText
-  guard $ T.all isSpace str
-
-type InlinesParser m = HTMLParser m Text
-
-pTagContents :: PandocMonad m => InlinesParser m Inlines
-pTagContents =
-      B.displayMath <$> mathDisplay
-  <|> B.math        <$> mathInline
-  <|> pStr
-  <|> pSpace
-  <|> smartPunctuation pTagContents
-  <|> pSymbol
-  <|> pBad
-
-pStr :: PandocMonad m => InlinesParser m Inlines
-pStr = do
-  result <- many1 $ satisfy $ \c ->
-                     not (isSpace c) && not (isSpecial c) && not (isBad c)
-  updateLastStrPos
-  return $ B.str result
-
-isSpecial :: Char -> Bool
-isSpecial '"'     = True
-isSpecial '\''    = True
-isSpecial '.'     = True
-isSpecial '-'     = True
-isSpecial '$'     = True
-isSpecial '\8216' = True
-isSpecial '\8217' = True
-isSpecial '\8220' = True
-isSpecial '\8221' = True
-isSpecial _       = False
-
-pSymbol :: PandocMonad m => InlinesParser m Inlines
-pSymbol = satisfy isSpecial >>= return . B.str . (:[])
-
-isBad :: Char -> Bool
-isBad c = c >= '\128' && c <= '\159' -- not allowed in HTML
-
-pBad :: PandocMonad m => InlinesParser m Inlines
-pBad = do
-  c <- satisfy isBad
-  let c' = case c of
-                '\128' -> '\8364'
-                '\130' -> '\8218'
-                '\131' -> '\402'
-                '\132' -> '\8222'
-                '\133' -> '\8230'
-                '\134' -> '\8224'
-                '\135' -> '\8225'
-                '\136' -> '\710'
-                '\137' -> '\8240'
-                '\138' -> '\352'
-                '\139' -> '\8249'
-                '\140' -> '\338'
-                '\142' -> '\381'
-                '\145' -> '\8216'
-                '\146' -> '\8217'
-                '\147' -> '\8220'
-                '\148' -> '\8221'
-                '\149' -> '\8226'
-                '\150' -> '\8211'
-                '\151' -> '\8212'
-                '\152' -> '\732'
-                '\153' -> '\8482'
-                '\154' -> '\353'
-                '\155' -> '\8250'
-                '\156' -> '\339'
-                '\158' -> '\382'
-                '\159' -> '\376'
-                _      -> '?'
-  return $ B.str [c']
-
-pSpace :: PandocMonad m => InlinesParser m Inlines
-pSpace = many1 (satisfy isSpace) >>= \xs ->
-            if '\n' `elem` xs
-               then return B.softbreak
-               else return B.space
-
---
--- Constants
---
-
-eitherBlockOrInline :: Set.Set Text
-eitherBlockOrInline = Set.fromList
-  ["audio", "applet", "button", "iframe", "embed",
-   "del", "ins", "progress", "map", "area", "noscript", "script",
-   "object", "svg", "video", "source"]
-
-blockHtmlTags :: Set.Set Text
-blockHtmlTags = Set.fromList
-   ["?xml", "!DOCTYPE", "address", "article", "aside",
-    "blockquote", "body", "canvas",
-    "caption", "center", "col", "colgroup", "dd", "details",
-    "dir", "div", "dl", "dt", "fieldset", "figcaption", "figure",
-    "footer", "form", "h1", "h2", "h3", "h4",
-    "h5", "h6", "head", "header", "hgroup", "hr", "html",
-    "isindex", "main", "menu", "meta", "noframes", "ol", "output", "p", "pre",
-    "section", "table", "tbody", "textarea",
-    "thead", "tfoot", "ul", "dd",
-    "dt", "frameset", "li", "tbody", "td", "tfoot",
-    "th", "thead", "tr", "script", "style"]
-
--- We want to allow raw docbook in markdown documents, so we
--- include docbook block tags here too.
-blockDocBookTags :: Set.Set Text
-blockDocBookTags = Set.fromList
-   ["calloutlist", "bibliolist", "glosslist", "itemizedlist",
-    "orderedlist", "segmentedlist", "simplelist",
-    "variablelist", "caution", "important", "note", "tip",
-    "warning", "address", "literallayout", "programlisting",
-    "programlistingco", "screen", "screenco", "screenshot",
-    "synopsis", "example", "informalexample", "figure",
-    "informalfigure", "table", "informaltable", "para",
-    "simpara", "formalpara", "equation", "informalequation",
-    "figure", "screenshot", "mediaobject", "qandaset",
-    "procedure", "task", "cmdsynopsis", "funcsynopsis",
-    "classsynopsis", "blockquote", "epigraph", "msgset",
-    "sidebar", "title"]
-
-epubTags :: Set.Set Text
-epubTags = Set.fromList ["case", "switch", "default"]
-
-blockTags :: Set.Set Text
-blockTags = Set.unions [blockHtmlTags, blockDocBookTags, epubTags]
-
-class NamedTag a where
-  getTagName :: a -> Maybe Text
-
-instance NamedTag (Tag Text) where
-  getTagName (TagOpen t _) = Just t
-  getTagName (TagClose t)  = Just t
-  getTagName _             = Nothing
-
-instance NamedTag (Tag String) where
-  getTagName (TagOpen t _) = Just (T.pack t)
-  getTagName (TagClose t)  = Just (T.pack t)
-  getTagName _             = Nothing
-
-isInlineTag :: NamedTag (Tag a) => Tag a -> Bool
-isInlineTag t = isInlineTagName || isCommentTag t
-                 where isInlineTagName = case getTagName t of
-                                              Just x -> x
-                                                  `Set.notMember` blockTags
-                                              Nothing -> False
-
-isBlockTag :: NamedTag (Tag a) => Tag a -> Bool
-isBlockTag t = isBlockTagName || isTagComment t
-                 where isBlockTagName =
-                         case getTagName t of
-                              Just x
-                                | "?" `T.isPrefixOf` x -> True
-                                | "!" `T.isPrefixOf` x -> True
-                                | otherwise -> x `Set.member` blockTags
-                                    || x `Set.member` eitherBlockOrInline
-                              Nothing -> False
-
-isTextTag :: Tag a -> Bool
-isTextTag = tagText (const True)
-
-isCommentTag :: Tag a -> Bool
-isCommentTag = tagComment (const True)
-
--- taken from HXT and extended
--- See http://www.w3.org/TR/html5/syntax.html sec 8.1.2.4 optional tags
-closes :: Text -> Text -> Bool
-_ `closes` "body" = False
-_ `closes` "html" = False
-"body" `closes` "head" = True
-"a" `closes` "a" = True
-"li" `closes` "li" = True
-"th" `closes` t | t `elem` ["th","td"] = True
-"td" `closes` t | t `elem` ["th","td"] = True
-"tr" `closes` t | t `elem` ["th","td","tr"] = True
-"dd" `closes` t | t `elem` ["dt", "dd"] = True
-"dt" `closes` t | t `elem` ["dt","dd"] = True
-"rt" `closes` t | t `elem` ["rb", "rt", "rtc"] = True
-"optgroup" `closes` "optgroup" = True
-"optgroup" `closes` "option" = True
-"option" `closes` "option" = True
--- https://html.spec.whatwg.org/multipage/syntax.html#optional-tags
-x `closes` "p" | x `elem` ["address", "article", "aside", "blockquote",
-   "dir", "div", "dl", "fieldset", "footer", "form", "h1", "h2", "h3", "h4",
-   "h5", "h6", "header", "hr", "main", "menu", "nav", "ol", "p", "pre", "section",
-   "table", "ul"] = True
-_ `closes` "meta" = True
-"form" `closes` "form" = True
-"label" `closes` "label" = True
-"map" `closes` "map" = True
-"object" `closes` "object" = True
-_ `closes` t | t `elem` ["option","style","script","textarea","title"] = True
-t `closes` "select" | t /= "option" = True
-"thead" `closes` t | t `elem` ["colgroup"] = True
-"tfoot" `closes` t | t `elem` ["thead","colgroup"] = True
-"tbody" `closes` t | t `elem` ["tbody","tfoot","thead","colgroup"] = True
-t `closes` t2 |
-   t `elem` ["h1","h2","h3","h4","h5","h6","dl","ol","ul","table","div","main","p"] &&
-   t2 `elem` ["h1","h2","h3","h4","h5","h6","p" ] = True -- not "div" or "main"
-t1 `closes` t2 |
-   t1 `Set.member` blockTags &&
-   t2 `Set.notMember` blockTags &&
-   t2 `Set.notMember` eitherBlockOrInline = True
-_ `closes` _ = False
-
---- parsers for use in markdown, textile readers
-
--- | Matches a stretch of HTML in balanced tags.
-htmlInBalanced :: (HasReaderOptions st, Monad m)
-               => (Tag String -> Bool)
-               -> ParserT String st m String
-htmlInBalanced f = try $ do
-  lookAhead (char '<')
-  inp <- getInput
-  let ts = canonicalizeTags $
-        parseTagsOptions parseOptions{ optTagWarning = True,
-                                       optTagPosition = True } inp
-  case ts of
-    (TagPosition sr sc : t@(TagOpen tn _) : rest) -> do
-       guard $ f t
-       guard $ not $ hasTagWarning (t : take 1 rest)
-       case htmlInBalanced' tn (t:rest) of
-            []  -> mzero
-            xs  -> case reverse xs of
-                        (TagClose _ : TagPosition er ec : _) -> do
-                          let ls = er - sr
-                          let cs = ec - sc
-                          lscontents <- unlines <$> count ls anyLine
-                          cscontents <- count cs anyChar
-                          closetag <- do
-                            x <- many (satisfy (/='>'))
-                            char '>'
-                            return (x <> ">")
-                          return (lscontents <> cscontents <> closetag)
-                        _ -> mzero
-    _ -> mzero
-
-htmlInBalanced' :: String
-                -> [Tag String]
-                -> [Tag String]
-htmlInBalanced' tagname ts = fromMaybe [] $ go 0 ts
-  where go :: Int -> [Tag String] -> Maybe [Tag String]
-        go n (t@(TagOpen tn' _):rest) | tn' == tagname =
-              (t :) <$> go (n + 1) rest
-        go 1 (t@(TagClose tn'):_) | tn' == tagname =
-              return [t]
-        go n (t@(TagClose tn'):rest)  | tn' == tagname =
-              (t :) <$> go (n - 1) rest
-        go n (t:ts') = (t :) <$> go n ts'
-        go _ [] = mzero
-
-hasTagWarning :: [Tag a] -> Bool
-hasTagWarning (TagWarning _:_) = True
-hasTagWarning _                = False
-
--- | Matches a tag meeting a certain condition.
-htmlTag :: (HasReaderOptions st, Monad m)
-        => (Tag String -> Bool)
-        -> ParserT [Char] st m (Tag String, String)
-htmlTag f = try $ do
-  lookAhead (char '<')
-  startpos <- getPosition
-  inp <- getInput
-  let ts = canonicalizeTags $ parseTagsOptions
-                               parseOptions{ optTagWarning = False
-                                           , optTagPosition = True }
-                               (inp ++ " ") -- add space to ensure that
-                               -- we get a TagPosition after the tag
-  (next, ln, col) <- case ts of
-                      (TagPosition{} : next : TagPosition ln col : _)
-                        | f next -> return (next, ln, col)
-                      _ -> mzero
-
-  -- <www.boe.es/buscar/act.php?id=BOE-A-1996-8930#a66>
-  -- should NOT be parsed as an HTML tag, see #2277,
-  -- so we exclude . even though it's a valid character
-  -- in XML element names
-  let isNameChar c = isAlphaNum c || c == ':' || c == '-' || c == '_'
-  let isName s = case s of
-                      []      -> False
-                      ('?':_) -> True -- processing instruction
-                      (c:cs)  -> isLetter c && all isNameChar cs
-
-  let endpos = if ln == 1
-                  then setSourceColumn startpos
-                         (sourceColumn startpos + (col - 1))
-                  else setSourceColumn (setSourceLine startpos
-                                        (sourceLine startpos + (ln - 1)))
-                         col
-  let endAngle = try $
-        do char '>'
-           pos <- getPosition
-           guard $ pos >= endpos
-
-  let handleTag tagname = do
-       -- basic sanity check, since the parser is very forgiving
-       -- and finds tags in stuff like x<y)
-       guard $ isName tagname
-       guard $ not $ null tagname
-       -- <https://example.org> should NOT be a tag either.
-       -- tagsoup will parse it as TagOpen "https:" [("example.org","")]
-       guard $ last tagname /= ':'
-       char '<'
-       rendered <- manyTill anyChar endAngle
-       return (next, "<" ++ rendered ++ ">")
-  case next of
-       TagComment s
-         | "<!--" `isPrefixOf` inp -> do
-          string "<!--"
-          count (length s) anyChar
-          string "-->"
-          stripComments <- getOption readerStripComments
-          if stripComments
-             then return (next, "")
-             else return (next, "<!--" <> s <> "-->")
-         | otherwise -> fail "bogus comment mode, HTML5 parse error"
-       TagOpen tagname attr -> do
-         guard $ all (isName . fst) attr
-         handleTag tagname
-       TagClose tagname ->
-         handleTag tagname
-       _ -> mzero
-
-mkAttr :: [(String, String)] -> Attr
-mkAttr attr = (attribsId, attribsClasses, attribsKV)
-  where attribsId = fromMaybe "" $ lookup "id" attr
-        attribsClasses = words (fromMaybe "" $ lookup "class" attr) <> epubTypes
-        attribsKV = filter (\(k,_) -> k /= "class" && k /= "id") attr
-        epubTypes = words $ fromMaybe "" $ lookup "epub:type" attr
-
--- Strip namespace prefixes
-stripPrefixes :: [Tag Text] -> [Tag Text]
-stripPrefixes = map stripPrefix
-
-stripPrefix :: Tag Text -> Tag Text
-stripPrefix (TagOpen s as) =
-    TagOpen (stripPrefix' s) (map (stripPrefix' *** id) as)
-stripPrefix (TagClose s) = TagClose (stripPrefix' s)
-stripPrefix x = x
-
-stripPrefix' :: Text -> Text
-stripPrefix' s =
-  if T.null t then s else T.drop 1 t
-  where (_, t) = T.span (/= ':') s
-
-isSpace :: Char -> Bool
-isSpace ' '  = True
-isSpace '\t' = True
-isSpace '\n' = True
-isSpace '\r' = True
-isSpace _    = False
-
--- Instances
-
-instance HasIdentifierList HTMLState where
-  extractIdentifierList = identifiers
-  updateIdentifierList f s = s{ identifiers = f (identifiers s) }
-
-instance HasHeaderMap HTMLState where
-  extractHeaderMap = headerMap
-  updateHeaderMap  f s = s{ headerMap = f (headerMap s) }
-
-instance HasLogMessages HTMLState where
-  addLogMessage m s = s{ logMessages = m : logMessages s }
-  getLogMessages = reverse . logMessages
-
--- This signature should be more general
--- MonadReader HTMLLocal m => HasQuoteContext st m
-instance PandocMonad m => HasQuoteContext HTMLState (ReaderT HTMLLocal m) where
-  getQuoteContext = asks quoteContext
-  withQuoteContext q = local (\s -> s{quoteContext = q})
-
-instance HasReaderOptions HTMLState where
-    extractReaderOptions = extractReaderOptions . parserState
-
-instance HasMeta HTMLState where
-  setMeta s b st = st {parserState = setMeta s b $ parserState st}
-  deleteMeta s st = st {parserState = deleteMeta s $ parserState st}
-
-instance Default HTMLLocal where
-  def = HTMLLocal NoQuote False False
-
-instance HasLastStrPosition HTMLState where
-  setLastStrPos s st = st {parserState = setLastStrPos s (parserState st)}
-  getLastStrPos = getLastStrPos . parserState
-
--- For now we need a special verison here; the one in Shared has String type
-renderTags' :: [Tag Text] -> Text
-renderTags' = renderTagsOptions
-               renderOptions{ optMinimize = matchTags ["hr", "br", "img",
-                                                       "meta", "link"]
-                            , optRawTag   = matchTags ["script", "style"] }
-              where matchTags tags = flip elem tags . T.toLower
-
-
--- EPUB Specific
---
---
-sectioningContent :: [Text]
-sectioningContent = ["article", "aside", "nav", "section"]
-
-
-groupingContent :: [Text]
-groupingContent = ["p", "hr", "pre", "blockquote", "ol"
-                  , "ul", "li", "dl", "dt", "dt", "dd"
-                  , "figure", "figcaption", "div", "main"]
-
-matchTagClose :: Text -> (Tag Text -> Bool)
-matchTagClose t = (~== TagClose t)
-
-matchTagOpen :: Text -> [(Text, Text)] -> (Tag Text -> Bool)
-matchTagOpen t as = (~== TagOpen t as)
-
-{-
-
-types :: [(String, ([String], Int))]
-types =  -- Document divisions
-   map (\s -> (s, (["section", "body"], 0)))
-    ["volume", "part", "chapter", "division"]
-  <> -- Document section and components
-  [
-    ("abstract",  ([], 0))]
--}
+{-# LANGUAGE FlexibleContexts     #-}
+{-# LANGUAGE FlexibleInstances     #-}
+{-# LANGUAGE LambdaCase            #-}
+{-# LANGUAGE OverloadedStrings     #-}
+{-# LANGUAGE ViewPatterns          #-}
+{- |
+   Module      : Text.Pandoc.Readers.HTML
+   Copyright   : Copyright (C) 2006-2024 John MacFarlane
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : John MacFarlane <jgm@berkeley.edu>
+   Stability   : alpha
+   Portability : portable
+
+Conversion of HTML to 'Pandoc' document.
+-}
+module Text.Pandoc.Readers.HTML ( readHtml
+                                , htmlTag
+                                , htmlInBalanced
+                                , isInlineTag
+                                , isBlockTag
+                                , isTextTag
+                                , isCommentTag
+                                , toAttr
+                                ) where
+
+import Control.Applicative ((<|>))
+import Control.Monad (guard, mzero, unless, void)
+import Control.Monad.Except (throwError, catchError)
+import Control.Monad.Reader (ask, asks, lift, local, runReaderT)
+import Data.ByteString.Base64 (encode)
+import Data.Char (isAlphaNum, isLetter)
+import Data.Default (Default (..), def)
+import Data.Foldable (for_)
+import Data.List.Split (splitWhen)
+import qualified Data.List as L
+import qualified Data.Map as M
+import Data.Either (partitionEithers)
+import Data.Monoid (First (..))
+import qualified Data.Set as Set
+import Data.Text (Text)
+import qualified Data.Text as T
+import Network.URI (nonStrictRelativeTo, parseURIReference)
+import Text.HTML.TagSoup
+import Text.HTML.TagSoup.Match
+import Text.Pandoc.Builder (Blocks, Inlines, trimInlines)
+import qualified Text.Pandoc.Builder as B
+import Text.Pandoc.Class.PandocMonad (PandocMonad (..))
+import Text.Pandoc.CSS (pickStyleAttrProps)
+import qualified Text.Pandoc.UTF8 as UTF8
+import Text.Pandoc.Definition
+import Text.Pandoc.Readers.HTML.Parsing
+import Text.Pandoc.Readers.HTML.Table (pTable)
+import Text.Pandoc.Readers.HTML.TagCategories
+import Text.Pandoc.Readers.HTML.Types
+import Text.Pandoc.Readers.LaTeX (rawLaTeXInline)
+import Text.Pandoc.Error
+import Text.Pandoc.Logging
+import Text.Pandoc.Options (
+    Extension (Ext_epub_html_exts, Ext_empty_paragraphs, Ext_native_divs,
+               Ext_native_spans, Ext_raw_html, Ext_line_blocks, Ext_raw_tex),
+    ReaderOptions (readerExtensions, readerStripComments),
+    extensionEnabled)
+import Text.Pandoc.Parsing hiding ((<|>))
+import Text.Pandoc.Shared (
+    addMetaField, extractSpaces, htmlSpanLikeElements, renderTags',
+    safeRead, tshow, formatCode)
+import Text.Pandoc.URI (escapeURI)
+import Text.Pandoc.Walk
+import Text.TeXMath (readMathML, writeTeX)
+import qualified Data.Sequence as Seq
+import Data.Maybe (fromMaybe, isJust)
+
+-- | Convert HTML-formatted string to 'Pandoc' document.
+readHtml :: (PandocMonad m, ToSources a)
+         => ReaderOptions -- ^ Reader options
+         -> a             -- ^ Input to parse
+         -> m Pandoc
+readHtml opts inp = do
+  let tags = stripPrefixes $ canonicalizeTags $
+             parseTagsOptions parseOptions{ optTagPosition = True }
+             (sourcesToText $ toSources inp)
+      parseDoc = do
+        blocks <- fixPlains False . mconcat <$> manyTill block eof
+        meta <- stateMeta . parserState <$> getState
+        bs' <- replaceNotes (B.toList blocks)
+        reportLogMessages
+        return $ Pandoc meta $ extractMain bs'
+      getError (errorMessages -> ms) = case ms of
+                                         []    -> ""
+                                         (m:_) -> messageString m
+  result <- flip runReaderT def $
+       runParserT parseDoc
+       (HTMLState def{ stateOptions = opts }
+         [] Nothing Set.empty [] M.empty opts False)
+       "source" tags
+  case result of
+    Right doc -> return doc
+    Left  err -> throwError $ PandocParseError $ T.pack $ getError err
+
+-- Extract contents of main element if exactly one is present; otherwise
+-- return all blocks.
+extractMain :: [Block] -> [Block]
+extractMain bs =
+  case query getMain bs of
+    [] -> bs
+    [Div ("",[],_) bs'] -> bs'
+    bs' -> bs'
+ where
+   getMain :: Block -> [Block]
+   getMain b@(Div (_,_,kvs) _)
+     | Just "main" <- lookup "role" kvs = [b]
+   getMain _ = []
+
+-- Strip namespace prefixes on tags (not attributes)
+stripPrefixes :: [Tag Text] -> [Tag Text]
+stripPrefixes = map stripPrefix
+
+stripPrefix :: Tag Text -> Tag Text
+stripPrefix (TagOpen s as) = TagOpen (T.takeWhileEnd (/=':') s) as
+stripPrefix (TagClose s)   = TagClose (T.takeWhileEnd (/=':') s)
+stripPrefix x = x
+
+replaceNotes :: PandocMonad m => [Block] -> TagParser m [Block]
+replaceNotes bs = do
+  notes <- noteTable <$> getState
+  walkM (replaceNotes' notes) bs
+
+replaceNotes' :: PandocMonad m
+              => [(Text, Blocks)] -> Inline -> TagParser m Inline
+replaceNotes' noteTbl (RawInline (Format "noteref") ref) =
+  maybe warnNotFound (pure . Note . B.toList) $ lookup ref noteTbl
+ where
+  warnNotFound = do
+    pos <- getPosition
+    logMessage $ ReferenceNotFound ref pos
+    pure (Note [])
+replaceNotes' _ x = pure x
+
+setInChapter :: PandocMonad m => HTMLParser m s a -> HTMLParser m s a
+setInChapter = local (\s -> s {inChapter = True})
+
+setInPlain :: PandocMonad m => HTMLParser m s a -> HTMLParser m s a
+setInPlain = local (\s -> s {inPlain = True})
+
+-- Some items should be handled differently when in a list item tag, e.g. checkbox
+setInListItem :: PandocMonad m => HTMLParser m s a -> HTMLParser m s a
+setInListItem = local (\s -> s {inListItem = True})
+
+pHtml :: PandocMonad m => TagParser m Blocks
+pHtml = do
+  (TagOpen "html" attr) <- lookAhead pAny
+  for_ (lookup "lang" attr <|> lookup "xml:lang" attr) $
+    updateState . B.setMeta "lang" . B.text
+  pInTags "html" block
+
+pBody :: PandocMonad m => TagParser m Blocks
+pBody = do
+  (TagOpen "body" attr) <- lookAhead pAny
+  for_ (lookup "lang" attr <|> lookup "xml:lang" attr) $
+    updateState . B.setMeta "lang" . B.text
+  pInTags "body" block
+
+pHead :: PandocMonad m => TagParser m Blocks
+pHead = pInTags "head" $ pTitle <|> pMetaTag <|> pBaseTag <|> (mempty <$ pAny)
+  where pTitle = pInTags "title" inline >>= setTitle . trimInlines
+        setTitle t = mempty <$ updateState (B.setMeta "title" t)
+        pMetaTag = do
+          mt <- pSatisfy (matchTagOpen "meta" [])
+          let name = fromAttrib "name" mt
+          if T.null name
+             then return mempty
+             else do
+               let content = fromAttrib "content" mt
+               updateState $ \s ->
+                 let ps = parserState s in
+                 s{ parserState = ps{
+                      stateMeta = addMetaField name (B.text content)
+                                   (stateMeta ps) } }
+               return mempty
+        pBaseTag = do
+          bt <- pSatisfy (matchTagOpen "base" [])
+          updateState $ \st -> st{ baseHref =
+               parseURIReference $ T.unpack $ fromAttrib "href" bt }
+          return mempty
+
+block :: PandocMonad m => TagParser m Blocks
+block = ((do
+  tag <- lookAhead (pSatisfy isBlockTag)
+  exts <- getOption readerExtensions
+  case tag of
+    TagOpen name attr ->
+      let type' = fromMaybe "" $
+                     lookup "type" attr <|> lookup "epub:type" attr
+          role = fromMaybe "" $ lookup "role" attr
+          epubExts = extensionEnabled Ext_epub_html_exts exts
+      in
+      case name of
+        _ | name `elem` sectioningContent
+          , epubExts
+          , "chapter" `T.isInfixOf` type'
+          -> eSection
+        _ | epubExts
+          , type' `elem` ["footnotes", "rearnotes"]
+          -> eFootnotes
+        _ | epubExts
+          , type' `elem` ["footnote", "rearnote"]
+          -> mempty <$ eFootnote
+        _ | epubExts
+          , type' == "toc"
+          -> mempty <$ eTOC
+        _ | "titlepage" `T.isInfixOf` type'
+          , name `elem` ("section" : groupingContent)
+          -> mempty <$ eTitlePage
+        _ | role == "doc-endnotes"
+          -> eFootnotes
+        "p" -> pPara
+        "h1" -> pHeader
+        "h2" -> pHeader
+        "h3" -> pHeader
+        "h4" -> pHeader
+        "h5" -> pHeader
+        "h6" -> pHeader
+        "blockquote" -> pBlockQuote
+        "pre" -> pCodeBlock
+        "ul" -> pBulletList
+        "ol" -> pOrderedList
+        "dl" -> pDefinitionList
+        "table" -> pTable block
+        "hr" -> pHrule
+        "html" -> pHtml
+        "head" -> pHead
+        "body" -> pBody
+        "div"
+          | extensionEnabled Ext_line_blocks exts
+          , Just "line-block" <- lookup "class" attr
+          -> pLineBlock
+          | otherwise
+          -> pDiv
+        "aside" -> pDiv
+        "section" -> pDiv
+        "header" -> pDiv
+        "main" -> pDiv
+        "figure" -> pFigure
+        "iframe" -> pIframe
+        "style" -> pRawHtmlBlock
+        "textarea" -> pRawHtmlBlock
+        "switch"
+          | epubExts
+          -> eSwitch B.para block
+        _ -> mzero
+    _ -> mzero) <|> pPlain <|> pRawHtmlBlock) >>= \res ->
+        res <$ trace (T.take 60 $ tshow $ B.toList res)
+
+namespaces :: PandocMonad m => [(Text, TagParser m Inlines)]
+namespaces = [(mathMLNamespace, pMath True)]
+
+mathMLNamespace :: Text
+mathMLNamespace = "http://www.w3.org/1998/Math/MathML"
+
+eSwitch :: (PandocMonad m, Monoid a)
+        => (Inlines -> a)
+        -> TagParser m a
+        -> TagParser m a
+eSwitch constructor parser = try $ do
+  guardEnabled Ext_epub_html_exts
+  pSatisfy (matchTagOpen "switch" [])
+  cases <- getFirst . mconcat <$>
+            manyTill (First <$> (eCase <* skipMany pBlank) )
+              (lookAhead $ try $ pSatisfy (matchTagOpen "default" []))
+  skipMany pBlank
+  fallback <- pInTags "default" (skipMany pBlank *> parser <* skipMany pBlank)
+  skipMany pBlank
+  pSatisfy (matchTagClose "switch")
+  return $ maybe fallback constructor cases
+
+eCase :: PandocMonad m => TagParser m (Maybe Inlines)
+eCase = do
+  skipMany pBlank
+  TagOpen _ attr' <- lookAhead $ pSatisfy (matchTagOpen "case" [])
+  let attr = toStringAttr attr'
+  case flip lookup namespaces =<< lookup "required-namespace" attr of
+    Just p -> Just <$> pInTags "case" (skipMany pBlank *> p <* skipMany pBlank)
+    Nothing -> Nothing <$ manyTill pAny (pSatisfy (matchTagClose "case"))
+
+eFootnote :: PandocMonad m => TagParser m ()
+eFootnote = do
+  inNotes <- inFootnotes <$> getState
+  TagOpen tag attr' <- lookAhead $ pSatisfy
+    (\case
+       TagOpen _ attr'
+         -> case lookup "type" attr' <|> lookup "epub:type" attr' of
+              Just "footnote" -> True
+              Just "rearnote" -> True
+              _ -> inNotes
+       _ -> False)
+  let attr = toStringAttr attr'
+  let ident = fromMaybe "" (lookup "id" attr)
+  content <- pInTags tag block
+  updateState $ \s ->
+    s {noteTable = (ident, content) : noteTable s}
+
+eFootnotes :: PandocMonad m => TagParser m Blocks
+eFootnotes = try $ do
+  let notes = ["footnotes", "rearnotes"]
+  (TagOpen tag attr') <- lookAhead pAny
+  let attr = toStringAttr attr'
+  guard (lookup "role" attr == Just "doc-endnotes") <|>
+    (guardEnabled Ext_epub_html_exts >>
+     guard (maybe False (`elem` notes)
+             (lookup "type" attr <|> lookup "epub:type" attr)))
+  updateState $ \s -> s{ inFootnotes = True }
+  result <- pInTags tag block
+  updateState $ \s -> s{ inFootnotes = False }
+  if null result
+     -- if it just contains notes, we don't need the container:
+     then return result
+     -- but there might be content other than notes, in which case
+     -- we want a div:
+     else return $ B.divWith (toAttr attr') result
+
+eNoteref :: PandocMonad m => TagParser m Inlines
+eNoteref = try $ do
+  TagOpen tag attr <-
+    pSatisfy (\case
+                 TagOpen _ as
+                    -> (lookup "type" as <|> lookup "epub:type" as)
+                        == Just "noteref" ||
+                        lookup "role" as == Just "doc-noteref"
+                 _  -> False)
+  ident <- case lookup "href" attr >>= T.uncons of
+             Just ('#', rest) -> return rest
+             _ -> mzero
+  _ <- manyTill pAny (pSatisfy (\case
+                                   TagClose t -> t == tag
+                                   _          -> False))
+  return $ B.rawInline "noteref" ident
+
+-- Strip TOC if there is one, better to generate again
+eTOC :: PandocMonad m => TagParser m ()
+eTOC = try $ do
+  guardEnabled Ext_epub_html_exts
+  (TagOpen tag attr) <- lookAhead pAny
+  guard $ (lookup "type" attr <|> lookup "epub:type" attr) == Just "toc"
+  void (pInTags tag block)
+
+pBulletList :: PandocMonad m => TagParser m Blocks
+pBulletList = try $ do
+  pSatisfy (matchTagOpen "ul" [])
+  -- note: if they have an <ol> or <ul> not in scope of a <li>,
+  -- treat it as a list item, though it's not valid xhtml...
+  skipMany pBlank
+  orphans <- many (do notFollowedBy (pSatisfy (matchTagOpen "li" []))
+                      notFollowedBy (pSatisfy isTagClose)
+                      block) -- e.g. <ul>, see #9187
+  items <- manyTill pListItem (pCloses "ul")
+  let items' = case orphans of
+                 [] -> items
+                 xs -> mconcat xs : items
+  return $ B.bulletList $ map (fixPlains True) items'
+
+pListItem :: PandocMonad m => TagParser m Blocks
+pListItem = setInListItem $ do
+  TagOpen _ attr' <- lookAhead $ pSatisfy (matchTagOpen "li" [])
+  let attr = toStringAttr attr'
+  let addId ident bs = case B.toList bs of
+                           (Plain ils:xs) -> B.fromList (Plain
+                                [Span (ident, [], []) ils] : xs)
+                           _ -> B.divWith (ident, [], []) bs
+  item <- pInTags "li" block
+  skipMany pBlank
+  orphans <- many (do notFollowedBy (pSatisfy (matchTagOpen "li" []))
+                      notFollowedBy (pSatisfy isTagClose)
+                      block) -- e.g. <ul>, see #9187
+  skipMany pBlank
+  return $ maybe id addId (lookup "id" attr) $ item <> mconcat orphans
+
+pCheckbox :: PandocMonad m => TagParser m Inlines
+pCheckbox = do
+  TagOpen _ attr' <- pSatisfy $ matchTagOpen "input" [("type","checkbox")]
+  TagClose _ <- pSatisfy (matchTagClose "input")
+  let attr = toStringAttr attr'
+  let isChecked = isJust $ lookup "checked" attr
+  let escapeSequence = B.str $ if isChecked then "\9746" else "\9744"
+  return $ escapeSequence <> B.space
+
+
+parseListStyleType :: Text -> ListNumberStyle
+parseListStyleType "lower-roman" = LowerRoman
+parseListStyleType "upper-roman" = UpperRoman
+parseListStyleType "lower-alpha" = LowerAlpha
+parseListStyleType "upper-alpha" = UpperAlpha
+parseListStyleType "decimal"     = Decimal
+parseListStyleType _             = DefaultStyle
+
+parseTypeAttr :: Text -> ListNumberStyle
+parseTypeAttr "i" = LowerRoman
+parseTypeAttr "I" = UpperRoman
+parseTypeAttr "a" = LowerAlpha
+parseTypeAttr "A" = UpperAlpha
+parseTypeAttr "1" = Decimal
+parseTypeAttr _   = DefaultStyle
+
+pOrderedList :: PandocMonad m => TagParser m Blocks
+pOrderedList = try $ do
+  TagOpen _ attribs' <- pSatisfy (matchTagOpen "ol" [])
+  isNoteList <- inFootnotes <$> getState
+  let attribs = toStringAttr attribs'
+  let start = fromMaybe 1 $ lookup "start" attribs >>= safeRead
+  let style = fromMaybe DefaultStyle
+         $  (parseTypeAttr      <$> lookup "type" attribs)
+        <|> (parseListStyleType <$> lookup "class" attribs)
+        <|> (parseListStyleType <$> (lookup "style" attribs >>= pickListStyle))
+        where
+          pickListStyle = pickStyleAttrProps ["list-style-type", "list-style"]
+
+  -- note: if they have an <ol> or <ul> not in scope of a <li>,
+  -- treat it as a list item, though it's not valid xhtml...
+  skipMany pBlank
+  orphans <- many (do notFollowedBy (pSatisfy (matchTagOpen "li" []))
+                      notFollowedBy (pSatisfy isTagClose)
+                      block) -- e.g. <ul>, see #9187
+  if isNoteList
+     then do
+       _ <- manyTill (eFootnote <|> pBlank) (pCloses "ol")
+       return mempty
+     else do
+       items <- manyTill pListItem (pCloses "ol")
+       let items' = case orphans of
+                      [] -> items
+                      xs -> mconcat xs : items
+       return $ B.orderedListWith (start, style, DefaultDelim) $
+                map (fixPlains True) items'
+
+pDefinitionList :: PandocMonad m => TagParser m Blocks
+pDefinitionList = try $ do
+  pSatisfy (matchTagOpen "dl" [])
+  items <- manyTill pDefListItem (pCloses "dl")
+  return $ B.definitionList items
+
+pDefListItem :: PandocMonad m => TagParser m (Inlines, [Blocks])
+pDefListItem = try $ do
+  let nonItem = pSatisfy (\t -> not (matchTagOpen "dt" [] t) &&
+                  not (matchTagOpen "dd" [] t) && not (matchTagClose "dl" t))
+  terms <- many1 (try $ skipMany nonItem >> pInTags "dt" inline)
+  defs  <- many1 (try $ skipMany nonItem >> pInTags "dd" block)
+  skipMany nonItem
+  let term = L.foldl' (\x y -> if null x
+                                  then trimInlines y
+                                  else x <> B.linebreak <> trimInlines y)
+                    mempty terms
+  return (term, map (fixPlains True) defs)
+
+fixPlains :: Bool -> Blocks -> Blocks
+fixPlains inList bs = if any isParaish bs'
+                         then B.fromList $ map plainToPara bs'
+                         else bs
+  where isParaish Para{}           = True
+        isParaish CodeBlock{}      = True
+        isParaish Header{}         = True
+        isParaish BlockQuote{}     = True
+        isParaish BulletList{}     = not inList
+        isParaish OrderedList{}    = not inList
+        isParaish DefinitionList{} = not inList
+        isParaish _                = False
+        plainToPara (Plain xs) = Para xs
+        plainToPara x          = x
+        bs' = B.toList bs
+
+pRawTag :: PandocMonad m => TagParser m Text
+pRawTag = do
+  tag <- pAny
+  let ignorable x = x `elem` ["html","head","body","!DOCTYPE","?xml"]
+  if tagOpen ignorable (const True) tag || tagClose ignorable tag
+     then return mempty
+     else return $ renderTags' [tag]
+
+pLineBlock :: PandocMonad m => TagParser m Blocks
+pLineBlock = try $ do
+  guardEnabled Ext_line_blocks
+  _ <- pSatisfy $ tagOpen (=="div") (== [("class","line-block")])
+  ils <- trimInlines . mconcat <$> manyTill inline (pSatisfy (tagClose (=="div")))
+  let lns = map B.fromList $
+            splitWhen (== LineBreak) $ filter (/= SoftBreak) $
+            B.toList ils
+  return $ B.lineBlock lns
+
+isDivLike :: Text -> Bool
+isDivLike "div"     = True
+isDivLike "section" = True
+isDivLike "header"  = True
+isDivLike "main"    = True
+isDivLike "aside"   = True
+isDivLike _         = False
+
+pDiv :: PandocMonad m => TagParser m Blocks
+pDiv = try $ do
+  guardEnabled Ext_native_divs
+  TagOpen tag attr' <- lookAhead $ pSatisfy $ tagOpen isDivLike (const True)
+  let (ident, classes, kvs) = toAttr attr'
+  contents <- pInTags tag block
+  let contents' = case B.unMany contents of
+                    Header lev (hident,hclasses,hkvs) ils Seq.:<| rest
+                        | hident == ident ->
+                          B.Many $ Header lev ("",hclasses,hkvs) ils Seq.<| rest
+                    _ -> contents
+  let (classes', kvs') =
+        case tag of
+          "section" -> ("section":classes, kvs)
+          "aside" -> ("aside":classes, kvs)
+          "header" -> ("header":classes, kvs)
+          "main" | Nothing <- lookup "role" kvs -> (classes, ("role", "main"):kvs)
+          _ -> (classes, kvs)
+  return $ B.divWith (ident, classes', kvs') contents'
+
+pIframe :: PandocMonad m => TagParser m Blocks
+pIframe = try $ do
+  guardDisabled Ext_raw_html
+  tag <- pSatisfy (tagOpen (=="iframe") (isJust . lookup "src"))
+  skipMany pBlank
+  pCloses "iframe" <|> eof
+  url <- canonicalizeUrl $ fromAttrib "src" tag
+  if T.null url
+     then ignore $ renderTags' [tag, TagClose "iframe"]
+     else catchError
+       (do (bs, mbMime) <- openURL url
+           case mbMime of
+             Just mt
+               | "text/html" `T.isPrefixOf` mt -> do
+                    let inp = UTF8.toText bs
+                    opts <- readerOpts <$> getState
+                    Pandoc _ contents <- readHtml opts inp
+                    return $ B.divWith ("",["iframe"],[]) $ B.fromList contents
+               | "image/" `T.isPrefixOf` mt -> do
+                    return $ B.divWith ("",["iframe"],[]) $
+                      B.plain $ B.image url "" mempty
+             _ -> return $ B.divWith ("",["iframe"],[("src", url)]) mempty)
+       (\e -> do
+         logMessage $ CouldNotFetchResource url (renderError e)
+         ignore $ renderTags' [tag, TagClose "iframe"])
+
+pRawHtmlBlock :: PandocMonad m => TagParser m Blocks
+pRawHtmlBlock = do
+  raw <- pHtmlBlock "script" <|> pHtmlBlock "style" <|> pHtmlBlock "textarea"
+          <|> pRawTag
+  exts <- getOption readerExtensions
+  if extensionEnabled Ext_raw_html exts && not (T.null raw)
+     then return $ B.rawBlock "html" raw
+     else ignore raw
+
+ignore :: (Monoid a, PandocMonad m) => Text -> TagParser m a
+ignore raw = do
+  pos <- getPosition
+  -- raw can be null for tags like <!DOCTYPE>; see paRawTag
+  -- in this case we don't want a warning:
+  unless (T.null raw) $
+    logMessage $ SkippedContent raw pos
+  return mempty
+
+pHtmlBlock :: PandocMonad m => Text -> TagParser m Text
+pHtmlBlock t = try $ do
+  open <- pSatisfy (matchTagOpen t [])
+  contents <- manyTill pAny (pSatisfy (matchTagClose t))
+  return $ renderTags' $ [open] <> contents <> [TagClose t]
+
+-- Sets chapter context
+eSection :: PandocMonad m => TagParser m Blocks
+eSection = try $ do
+  let matchChapter as = maybe False (T.isInfixOf "chapter")
+                        (lookup "type" as <|> lookup "epub:type" as)
+  let sectTag = tagOpen (`elem` sectioningContent) matchChapter
+  TagOpen tag _ <- lookAhead $ pSatisfy sectTag
+  setInChapter (pInTags tag block)
+
+headerLevel :: Text -> TagParser m Int
+headerLevel tagtype =
+  case safeRead (T.drop 1 tagtype) of
+        Just level ->
+--          try (do
+--            guardEnabled Ext_epub_html_exts
+--            asks inChapter >>= guard
+--            return (level - 1))
+--            <|>
+              return level
+        Nothing -> Prelude.fail "Could not retrieve header level"
+
+eTitlePage :: PandocMonad m => TagParser m ()
+eTitlePage = try $ do
+  let isTitlePage as = maybe False (T.isInfixOf "titlepage")
+       (lookup "type" as <|> lookup "epub:type" as)
+  let groupTag = tagOpen (\x -> x `elem` groupingContent || x == "section")
+                          isTitlePage
+  TagOpen tag _ <- lookAhead $ pSatisfy groupTag
+  () <$ pInTags tag block
+
+pHeader :: PandocMonad m => TagParser m Blocks
+pHeader = try $ do
+  TagOpen tagtype attr' <- pSatisfy $
+                           tagOpen (`elem` ["h1","h2","h3","h4","h5","h6"])
+                           (const True)
+  let attr = toStringAttr attr'
+  level <- headerLevel tagtype
+  contents <- trimInlines . mconcat <$> manyTill inline (pCloses tagtype <|> eof)
+  let ident = fromMaybe "" $ lookup "id" attr
+  let classes = maybe [] T.words $ lookup "class" attr
+  let keyvals = [(k,v) | (k,v) <- attr, k /= "class", k /= "id"]
+  attr'' <- registerHeader (ident, classes, keyvals) contents
+  return $ B.headerWith attr'' level contents
+
+pHrule :: PandocMonad m => TagParser m Blocks
+pHrule = do
+  pSelfClosing (=="hr") (const True)
+  inNotes <- inFootnotes <$> getState
+  return $ if inNotes
+              then mempty
+              else B.horizontalRule
+
+pBlockQuote :: PandocMonad m => TagParser m Blocks
+pBlockQuote = do
+  contents <- pInTags "blockquote" block
+  return $ B.blockQuote $ fixPlains False contents
+
+pPlain :: PandocMonad m => TagParser m Blocks
+pPlain = do
+  contents <- setInPlain $ trimInlines . mconcat <$> many1 inline
+  if null contents
+     then return mempty
+     else return $ B.plain contents
+
+pPara :: PandocMonad m => TagParser m Blocks
+pPara = do
+  contents <- trimInlines <$> pInTags "p" inline
+  (do guardDisabled Ext_empty_paragraphs
+      guard (null contents)
+      return mempty)
+    <|> return (B.para contents)
+
+pFigure :: PandocMonad m => TagParser m Blocks
+pFigure = do
+  TagOpen tag attrList <- pSatisfy $ matchTagOpen "figure" []
+  let parser = Left <$> pInTags "figcaption" block <|>
+             (Right <$> block)
+  (captions, rest) <- partitionEithers <$> manyTill parser (pCloses tag <|> eof)
+  -- Concatenate all captions together
+  return $ B.figureWith (toAttr attrList)
+                        (B.simpleCaption (mconcat captions))
+                        (mconcat rest)
+
+pCodeBlock :: PandocMonad m => TagParser m Blocks
+pCodeBlock = try $ do
+  TagOpen _ attr' <- pSatisfy (matchTagOpen "pre" [])
+  -- if the `pre` has no attributes, try if it is followed by a `code`
+  -- element and use those attributes if possible.
+  attr <- case attr' of
+    _:_ -> pure (toAttr attr')
+    []  -> option nullAttr $ do
+      TagOpen _ codeAttr <- pSatisfy (matchTagOpen "code" [])
+      pure $ toAttr
+        [ (k, v') | (k, v) <- codeAttr
+                    -- strip language from class
+                  , let v' = if k == "class"
+                             then fromMaybe v (T.stripPrefix "language-" v)
+                             else v ]
+  contents <- manyTill pAny (pCloses "pre" <|> eof)
+  let rawText = T.concat $ map tagToText contents
+  -- drop trailing newline if any
+  let result = case T.unsnoc rawText of
+                    Just (result'', '\n') -> result''
+                    _                     -> rawText
+  return $ B.codeBlockWith attr result
+
+tagToText :: Tag Text -> Text
+tagToText (TagText s)      = s
+tagToText (TagOpen "br" _) = "\n"
+tagToText _                = ""
+
+inline :: PandocMonad m => TagParser m Inlines
+inline = pTagText <|> do
+  tag <- lookAhead (pSatisfy isInlineTag)
+  exts <- getOption readerExtensions
+  case tag of
+    TagOpen name attr ->
+      case name of
+        "a" | extensionEnabled Ext_epub_html_exts exts
+          , Just "noteref" <- lookup "type" attr <|> lookup "epub:type" attr
+          , Just ('#',_) <- lookup "href" attr >>= T.uncons
+            -> eNoteref
+          | Just "doc-noteref" <- lookup "role" attr
+          , Just ('#',_) <- lookup "href" attr >>= T.uncons
+            -> eNoteref
+            | otherwise -> pLink
+        "switch" -> eSwitch id inline
+        "q" -> pQ
+        "em" -> pEmph
+        "i"  -> pEmph
+        "strong" -> pStrong
+        "b" -> pStrong
+        "sup" -> pSuperscript
+        "sub" -> pSubscript
+        "small" -> pSmall
+        "s" -> pStrikeout
+        "strike" -> pStrikeout
+        "del" -> pStrikeout
+        "u" -> pUnderline
+        "ins" -> pUnderline
+        "br" -> pLineBreak
+        "img" -> pImage
+        "svg" -> pSvg
+        "bdo" -> pBdo
+        "tt" -> pCode
+        "code" -> pCode
+        "samp" -> pCodeWithClass "samp" "sample"
+        "var" -> pCodeWithClass "var" "variable"
+        "span" -> pSpan
+        "math" -> pMath False
+        "input"
+          | lookup "type" attr == Just "checkbox"
+          -> asks inListItem >>= guard >> pCheckbox
+        "style" -> B.rawInline "html" <$> pHtmlBlock "style"
+        "script"
+          | Just x <- lookup "type" attr
+          , "math/tex" `T.isPrefixOf` x -> pScriptMath
+        _ | name `elem` htmlSpanLikeElements -> pSpanLike
+        _ -> pRawHtmlInline
+    TagText _ -> pTagText
+    _ -> pRawHtmlInline
+
+pSelfClosing :: PandocMonad m
+             => (Text -> Bool) -> ([Attribute Text] -> Bool)
+             -> TagParser m (Tag Text)
+pSelfClosing f g = do
+  open <- pSatisfy (tagOpen f g)
+  optional $ pSatisfy (tagClose f)
+  return open
+
+pQ :: PandocMonad m => TagParser m Inlines
+pQ = do
+  TagOpen _ attrs <- pSatisfy $ tagOpenLit "q" (const True)
+  case lookup "cite" attrs of
+    Just url -> do
+      let uid = fromMaybe mempty $
+                   lookup "name" attrs <|> lookup "id" attrs
+      let cls = maybe [] T.words $ lookup "class" attrs
+      url' <- canonicalizeUrl url
+      makeQuote $ B.spanWith (uid, cls, [("cite", escapeURI url')])
+    Nothing -> makeQuote id
+ where
+  makeQuote wrapper = do
+    ctx <- asks quoteContext
+    let (constructor, innerContext) = case ctx of
+                  InDoubleQuote -> (B.singleQuoted, InSingleQuote)
+                  _             -> (B.doubleQuoted, InDoubleQuote)
+    content <- withQuoteContext innerContext
+                  (mconcat <$> manyTill inline (pCloses "q"))
+    return $ extractSpaces (constructor . wrapper) content
+
+pEmph :: PandocMonad m => TagParser m Inlines
+pEmph = pInlinesInTags "em" B.emph <|> pInlinesInTags "i" B.emph
+
+pStrong :: PandocMonad m => TagParser m Inlines
+pStrong = pInlinesInTags "strong" B.strong <|> pInlinesInTags "b" B.strong
+
+pSuperscript :: PandocMonad m => TagParser m Inlines
+pSuperscript = pInlinesInTags "sup" B.superscript
+
+pSubscript :: PandocMonad m => TagParser m Inlines
+pSubscript = pInlinesInTags "sub" B.subscript
+
+pSpanLike :: PandocMonad m => TagParser m Inlines
+pSpanLike =
+  Set.foldr
+    (\tagName acc -> acc <|> parseTag tagName)
+    mzero
+    htmlSpanLikeElements
+  where
+    parseTag tagName = do
+      TagOpen _ attrs <- pSatisfy $ tagOpenLit tagName (const True)
+      let (ids, cs, kvs) = toAttr attrs
+      content <- mconcat <$> manyTill inline (pCloses tagName <|> eof)
+      return $ B.spanWith (ids, tagName : cs, kvs) content
+
+pSmall :: PandocMonad m => TagParser m Inlines
+pSmall = pInlinesInTags "small" (B.spanWith ("",["small"],[]))
+
+pStrikeout :: PandocMonad m => TagParser m Inlines
+pStrikeout =
+  pInlinesInTags "s" B.strikeout <|>
+    pInlinesInTags "strike" B.strikeout <|>
+    pInlinesInTags "del" B.strikeout <|>
+    try (do pSatisfy (matchTagOpen "span" [("class","strikeout")])
+            contents <- mconcat <$> manyTill inline (pCloses "span")
+            return $ B.strikeout contents)
+
+pUnderline :: PandocMonad m => TagParser m Inlines
+pUnderline = pInlinesInTags "u" B.underline <|> pInlinesInTags "ins" B.underline
+
+pLineBreak :: PandocMonad m => TagParser m Inlines
+pLineBreak = do
+  pSelfClosing (=="br") (const True)
+  return B.linebreak
+
+pLink :: PandocMonad m => TagParser m Inlines
+pLink = try $ do
+  tag@(TagOpen _ attr') <- pSatisfy $ tagOpenLit "a" (const True)
+  let title = fromAttrib "title" tag
+  let attr = toAttr $ filter (\(k,_) -> k /= "title" && k /= "href") attr'
+  lab <- mconcat <$> manyTill inline (pCloses "a")
+  st <- getState
+  if inFootnotes st && maybeFromAttrib "role" tag == Just "doc-backlink"
+     then return mempty
+     else do
+       -- check for href; if href, then a link, otherwise a span
+       case maybeFromAttrib "href" tag of
+            Nothing   ->
+              return $ extractSpaces (B.spanWith attr) lab
+            Just url' -> do
+              url <- canonicalizeUrl url'
+              return $ extractSpaces
+                        (B.linkWith attr (escapeURI url) title) lab
+
+pImage :: PandocMonad m => TagParser m Inlines
+pImage = do
+  tag@(TagOpen _ attr') <- pSelfClosing (=="img") (isJust . lookup "src")
+  url <- canonicalizeUrl $ fromAttrib "src" tag
+  let title = fromAttrib "title" tag
+  let alt = fromAttrib "alt" tag
+  let attr = toAttr $ filter (\(k,_) -> k /= "alt" && k /= "title" && k /= "src") attr'
+  return $ B.imageWith attr (escapeURI url) title (B.text alt)
+
+pSvg :: PandocMonad m => TagParser m Inlines
+pSvg = do
+  guardDisabled Ext_raw_html
+  -- if raw_html enabled, parse svg tag as raw
+  opent@(TagOpen _ attr') <- pSatisfy (matchTagOpen "svg" [])
+  let (ident,cls,_) = toAttr attr'
+  contents <- many (notFollowedBy (pCloses "svg") >> pAny)
+  closet <- TagClose "svg" <$ (pCloses "svg" <|> eof)
+  let rawText = T.strip $ renderTags' (opent : contents ++ [closet])
+  let svgData = "data:image/svg+xml;base64," <>
+                   UTF8.toText (encode $ UTF8.fromText rawText)
+  let kvs = [("width", "1em") | "fa-w-14" `elem` cls ||
+                                "fa-w-16" `elem` cls ||
+                                "fa-fw" `elem` cls] -- #10134
+  return $ B.imageWith (ident,cls,kvs) svgData mempty mempty
+
+pCodeWithClass :: PandocMonad m => Text -> Text -> TagParser m Inlines
+pCodeWithClass name class' = try $ do
+  TagOpen open attr' <- pSatisfy $ tagOpen (== name) (const True)
+  let (ids,cs,kvs) = toAttr attr'
+      cs'          = class' : cs
+  code open (ids,cs',kvs)
+
+pCode :: PandocMonad m => TagParser m Inlines
+pCode = try $ do
+  (TagOpen open attr') <- pSatisfy $ tagOpen (`elem` ["code","tt"]) (const True)
+  let attr = toAttr attr'
+  code open attr
+
+code :: PandocMonad m => Text -> Attr -> TagParser m Inlines
+code open attr = do
+  result <- mconcat <$> manyTill inline (pCloses open)
+  return $ formatCode attr result
+
+-- https://developer.mozilla.org/en-US/docs/Web/HTML/Element/bdo
+-- Bidirectional Text Override
+pBdo :: PandocMonad m => TagParser m Inlines
+pBdo = try $ do
+  TagOpen _ attr' <- lookAhead $ pSatisfy $ tagOpen (=="bdo") (const True)
+  let attr = toStringAttr attr'
+  contents <- pInTags "bdo" inline
+  return $ case lookup "dir" attr of
+    -- Only bdo with a direction matters
+    Just dir -> B.spanWith ("", [], [("dir",T.toLower dir)]) contents
+    Nothing  -> contents
+
+pSpan :: PandocMonad m => TagParser m Inlines
+pSpan = do
+  (TagOpen _ attr') <- lookAhead (pSatisfy $ tagOpen (=="span") (const True))
+  exts <- getOption readerExtensions
+  let attr = toAttr attr'
+  case attr of
+     (_,cls,_) -- skip MathJaX-generated HTML; see #10673
+       | "mjx-chtml" `elem` cls -> mempty <$ pInTags "span" inline
+       | "MathJax_CHTML" `elem` cls -> mempty <$ pInTags "span" inline
+       | "MathJax_Preview" `elem` cls -> mempty <$ pInTags "span" inline
+       | "MJX_Assistive_MathML" `elem` cls -> pInTags "span" inline
+     (_,["katex-html"],_) -> mempty <$ pInTags "span" inline
+       -- skip HTML generated by KaTeX, since we get
+       -- the math by parsing mathml (#9971)
+     _ | extensionEnabled Ext_native_spans exts -> do
+           contents <- pInTags "span" inline
+           let classes = maybe [] T.words $ lookup "class" attr'
+           let styleAttr   = fromMaybe "" $ lookup "style" attr'
+           let fontVariant = fromMaybe "" $
+                              pickStyleAttrProps ["font-variant"] styleAttr
+           let isSmallCaps = fontVariant == "small-caps" ||
+                               "smallcaps" `elem` classes
+           let tag = if isSmallCaps then B.smallcaps else B.spanWith attr
+           return $ tag contents
+       | extensionEnabled Ext_raw_html exts -> do
+            tag <- pSatisfy $ tagOpen (=="span") (const True)
+            return $ B.rawInline "html" $ renderTags' [tag]
+       | otherwise  -> pInTags "span" inline -- just contents
+
+pRawHtmlInline :: PandocMonad m => TagParser m Inlines
+pRawHtmlInline = do
+  inplain <- asks inPlain
+  result <- pSatisfy (tagComment (const True))
+            <|> if inplain
+                   then pSatisfy (not . isBlockTag)
+                   else pSatisfy isInlineTag
+  exts <- getOption readerExtensions
+  let raw = renderTags' [result]
+  if extensionEnabled Ext_raw_html exts
+     then return $ B.rawInline "html" raw
+     else ignore raw
+
+mathMLToTeXMath :: Text -> Either Text Text
+mathMLToTeXMath s = writeTeX <$> readMathML s
+
+pScriptMath :: PandocMonad m => TagParser m Inlines
+pScriptMath = try $ do
+  TagOpen _ attr' <- pSatisfy $ tagOpen (=="script") (const True)
+  isdisplay <- case lookup "type" attr' of
+                    Just x | "math/tex" `T.isPrefixOf` x
+                      -> return $ "display" `T.isSuffixOf` x
+                    _ -> mzero
+  contents <- innerText <$> manyTill pAny (pSatisfy (matchTagClose "script"))
+  return $ (if isdisplay then B.displayMath else B.math) contents
+
+pMath :: PandocMonad m => Bool -> TagParser m Inlines
+pMath inCase = try $ do
+  open@(TagOpen _ attr') <- pSatisfy $ tagOpen (=="math") (const True)
+  -- we'll assume math tags are MathML unless specially marked
+  -- otherwise...
+  let attr = toStringAttr attr'
+  unless inCase $
+    guard (maybe True (== mathMLNamespace) (lookup "xmlns" attr))
+  let constructor = case lookup "display" attr of
+                       Just "block" -> B.displayMath
+                       _ -> B.math
+  contents <- manyTill pAny (pSatisfy (matchTagClose "math"))
+  -- KaTeX and others include original TeX in annotation tag;
+  -- just use this if present rather than parsing MathML:
+  case extractTeXAnnotation contents of
+    Just x -> return $ constructor x
+    Nothing ->
+      case mathMLToTeXMath (renderTags $
+              [open] <> contents <> [TagClose "math"]) of
+           Left _   -> return $ B.spanWith ("",["math"],attr) $ B.text $
+                                 innerText contents
+           Right "" -> return mempty
+           Right x  -> return $ constructor x
+
+extractTeXAnnotation :: [Tag Text] -> Maybe Text
+extractTeXAnnotation [] = Nothing
+extractTeXAnnotation (TagOpen "annotation" [("encoding","application/x-tex")]
+                       : ts) =
+  Just $ innerText $ takeWhile (~/= TagClose ("annotation" :: Text)) ts
+extractTeXAnnotation (_:ts) = extractTeXAnnotation ts
+
+
+pInlinesInTags :: PandocMonad m => Text -> (Inlines -> Inlines)
+               -> TagParser m Inlines
+pInlinesInTags tagtype f = extractSpaces f <$> pInTags tagtype inline
+
+pTagText :: PandocMonad m => TagParser m Inlines
+pTagText = try $ do
+  pos <- getPosition
+  (TagText str) <- pSatisfy isTagText
+  st <- getState
+  qu <- ask
+  parsed <- lift $ lift $
+            flip runReaderT qu $ runParserT (many pTagContents) st "text"
+               (Sources [(pos, str)])
+  case parsed of
+       Left _        -> throwError $ PandocParseError $
+                        "Could not parse `" <> str <> "'"
+       Right result  -> return $ mconcat result
+
+type InlinesParser m = HTMLParser m Sources
+
+pTagContents :: PandocMonad m => InlinesParser m Inlines
+pTagContents =
+      B.displayMath <$> mathDisplay
+  <|> B.math        <$> mathInline
+  <|> pStr
+  <|> pSpace
+  <|> smartPunctuation pTagContents
+  <|> pRawTeX
+  <|> pSymbol
+  <|> pBad
+
+pRawTeX :: PandocMonad m => InlinesParser m Inlines
+pRawTeX = do
+  lookAhead $ try $ do
+    char '\\'
+    choice $ map (try . string) ["begin", "eqref", "ref"]
+  guardEnabled Ext_raw_tex
+  inp <- getInput
+  st <- getState
+  res <- lift $ runParserT (withRaw rawLaTeXInline) st "chunk" inp
+  case res of
+       Left _                -> mzero
+       Right (contents, raw) -> do
+         _ <- count (T.length raw) anyChar
+         return $ B.rawInline "tex" contents
+
+pStr :: PandocMonad m => InlinesParser m Inlines
+pStr = do
+  result <- many1 $ satisfy $ \c ->
+                     not (isSpace c) && not (isSpecial c) && not (isBad c)
+  updateLastStrPos
+  return $ B.str $ T.pack result
+
+isSpecial :: Char -> Bool
+isSpecial '"'     = True
+isSpecial '\''    = True
+isSpecial '.'     = True
+isSpecial '-'     = True
+isSpecial '$'     = True
+isSpecial '\\'    = True
+isSpecial '\8216' = True
+isSpecial '\8217' = True
+isSpecial '\8220' = True
+isSpecial '\8221' = True
+isSpecial _       = False
+
+pSymbol :: PandocMonad m => InlinesParser m Inlines
+pSymbol = B.str . T.singleton <$> satisfy isSpecial
+
+isBad :: Char -> Bool
+isBad c = c >= '\128' && c <= '\159' -- not allowed in HTML
+
+pBad :: PandocMonad m => InlinesParser m Inlines
+pBad = do
+  c <- satisfy isBad
+  let c' = case c of
+                '\128' -> '\8364'
+                '\130' -> '\8218'
+                '\131' -> '\402'
+                '\132' -> '\8222'
+                '\133' -> '\8230'
+                '\134' -> '\8224'
+                '\135' -> '\8225'
+                '\136' -> '\710'
+                '\137' -> '\8240'
+                '\138' -> '\352'
+                '\139' -> '\8249'
+                '\140' -> '\338'
+                '\142' -> '\381'
+                '\145' -> '\8216'
+                '\146' -> '\8217'
+                '\147' -> '\8220'
+                '\148' -> '\8221'
+                '\149' -> '\8226'
+                '\150' -> '\8211'
+                '\151' -> '\8212'
+                '\152' -> '\732'
+                '\153' -> '\8482'
+                '\154' -> '\353'
+                '\155' -> '\8250'
+                '\156' -> '\339'
+                '\158' -> '\382'
+                '\159' -> '\376'
+                _      -> '?'
+  return $ B.str $ T.singleton c'
+
+pSpace :: PandocMonad m => InlinesParser m Inlines
+pSpace = many1 (satisfy isSpace) >>= \xs ->
+            if '\n' `elem` xs
+               then return B.softbreak
+               else return B.space
+
+getTagName :: Tag Text -> Maybe Text
+getTagName (TagOpen t _) = Just t
+getTagName (TagClose t)  = Just t
+getTagName _             = Nothing
+
+isInlineTag :: Tag Text -> Bool
+isInlineTag t = isCommentTag t || case t of
+  TagOpen "script" _ -> "math/tex" `T.isPrefixOf` fromAttrib "type" t
+  TagClose "script"  -> True
+  TagOpen "style" _  -> True -- see #10643, invalid but it happens
+  TagClose "style"   -> True
+  TagOpen name _     -> isInlineTagName name
+  TagClose name      -> isInlineTagName name
+  _                  -> False
+ where isInlineTagName x =
+         x `Set.notMember` blockTags ||
+         T.take 1 x == "?" -- processing instr.
+
+isBlockTag :: Tag Text -> Bool
+isBlockTag t = isBlockTagName || isTagComment t
+                 where isBlockTagName =
+                         case getTagName t of
+                              Just x
+                                | "?" `T.isPrefixOf` x -> True
+                                | "!" `T.isPrefixOf` x -> True
+                                | otherwise -> x `Set.member` blockTags
+                                    || x `Set.member` eitherBlockOrInline
+                              Nothing -> False
+
+isTextTag :: Tag Text -> Bool
+isTextTag = tagText (const True)
+
+isCommentTag :: Tag Text -> Bool
+isCommentTag = tagComment (const True)
+
+--- parsers for use in markdown, textile readers
+
+-- | Matches a stretch of HTML in balanced tags.
+htmlInBalanced :: Monad m
+               => (Tag Text -> Bool)
+               -> ParsecT Sources st m Text
+htmlInBalanced f = try $ do
+  lookAhead (char '<')
+  sources <- getInput
+  let ts = canonicalizeTags
+        $ parseTagsOptions parseOptions{ optTagWarning = True,
+                                         optTagPosition = True }
+        $ sourcesToText sources
+  case ts of
+    (TagPosition sr sc : t@(TagOpen tn _) : rest) -> do
+       guard $ f t
+       guard $ not $ hasTagWarning (t : take 1 rest)
+       case htmlInBalanced' tn (t:rest) of
+            []  -> mzero
+            xs  -> case reverse xs of
+                        (TagClose _ : TagPosition er ec : _) -> do
+                          let ls = er - sr
+                          let cs = ec - sc
+                          lscontents <- T.unlines <$> count ls anyLine
+                          cscontents <- count cs anyChar
+                          closetag <- do
+                            x <- many (satisfy (/='>'))
+                            char '>'
+                            return (x <> ">")
+                          return $ lscontents <> T.pack cscontents <> T.pack closetag
+                        _ -> mzero
+    _ -> mzero
+
+htmlInBalanced' :: Text
+                -> [Tag Text]
+                -> [Tag Text]
+htmlInBalanced' tagname ts = fromMaybe [] $ go 0 ts
+  where go :: Int -> [Tag Text] -> Maybe [Tag Text]
+        go n (t@(TagOpen tn' _):rest) | tn' == tagname =
+              (t :) <$> go (n + 1) rest
+        go 1 (t@(TagClose tn'):_) | tn' == tagname =
+              return [t]
+        go n (t@(TagClose tn'):rest)  | tn' == tagname =
+              (t :) <$> go (n - 1) rest
+        go n (t:ts') = (t :) <$> go n ts'
+        go _ [] = mzero
+
+hasTagWarning :: [Tag Text] -> Bool
+hasTagWarning (TagWarning _:_) = True
+hasTagWarning _                = False
+
+-- | Matches a tag meeting a certain condition.
+htmlTag :: (HasReaderOptions st, Monad m)
+        => (Tag Text -> Bool)
+        -> ParsecT Sources st m (Tag Text, Text)
+htmlTag f = try $ do
+  lookAhead (char '<')
+  startpos <- getPosition
+  sources <- getInput
+  let inp = sourcesToText sources
+  let ts = canonicalizeTags $ parseTagsOptions
+                               parseOptions{ optTagWarning = False
+                                           , optTagPosition = True }
+                               (inp <> " ")
+                               -- add space to ensure that
+                               -- we get a TagPosition after the tag
+  (next, ln, col) <- case ts of
+                      (TagPosition{} : next : TagPosition ln col : _)
+                        | f next -> return (next, ln, col)
+                      _ -> mzero
+
+  -- <www.boe.es/buscar/act.php?id=BOE-A-1996-8930#a66>
+  -- should NOT be parsed as an HTML tag, see #2277,
+  -- so we exclude . even though it's a valid character
+  -- in XML element names
+  let isNameChar c = isAlphaNum c || c == ':' || c == '-' || c == '_'
+  let isName s = case T.uncons s of
+                   Nothing      -> False
+                   Just (c, cs) -> isLetter c && T.all isNameChar cs
+  let isPI s = case T.uncons s of
+                 Just ('?', _) -> True -- processing instruction
+                 _             -> False
+  let endpos = if ln == 1
+                  then setSourceColumn startpos
+                         (sourceColumn startpos + (col - 1))
+                  else setSourceColumn (setSourceLine startpos
+                                        (sourceLine startpos + (ln - 1)))
+                         col
+  let endAngle = try $
+        do char '>'
+           pos <- getPosition
+           guard $ pos >= endpos
+
+  let handleTag tagname = do
+       -- basic sanity check, since the parser is very forgiving
+       -- and finds tags in stuff like x<y)
+       guard $ isName tagname || isPI tagname
+       guard $ not $ T.null tagname
+       -- <https://example.org> should NOT be a tag either.
+       -- tagsoup will parse it as TagOpen "https:" [("example.org","")]
+       guard $ T.last tagname /= ':'
+       char '<'
+       rendered <- manyTill anyChar endAngle
+       return (next, T.pack $ "<" ++ rendered ++ ">")
+  case next of
+       TagComment s
+         | "<!--" `T.isPrefixOf` inp -> do
+          string "<!--"
+          count (T.length s) anyChar
+          string "-->"
+          stripComments <- getOption readerStripComments
+          if stripComments
+             then return (next, "")
+             else return (next, "<!--" <> s <> "-->")
+         | otherwise -> Prelude.fail "bogus comment mode, HTML5 parse error"
+       TagOpen tagname attr -> do
+         guard $ isPI tagname || all (isName . fst) attr
+         handleTag tagname
+       TagClose tagname ->
+         handleTag tagname
+       _ -> mzero
+
+-- Utilities
+
+-- | Adjusts a url according to the document's base URL.
+canonicalizeUrl :: PandocMonad m => Text -> TagParser m Text
+canonicalizeUrl url
+  | "data:" `T.isPrefixOf` url = return url
+  | otherwise = do
+     mbBaseHref <- baseHref <$> getState
+     return $ case (parseURIReference (T.unpack url), mbBaseHref) of
+                   (Just rel, Just bs) -> tshow (rel `nonStrictRelativeTo` bs)
+                   _                   -> url
diff --git a/src/Text/Pandoc/Readers/HTML/Parsing.hs b/src/Text/Pandoc/Readers/HTML/Parsing.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Readers/HTML/Parsing.hs
@@ -0,0 +1,232 @@
+{-# LANGUAGE LambdaCase            #-}
+{-# LANGUAGE OverloadedStrings     #-}
+{- |
+   Module      : Text.Pandoc.Readers.HTML.Parsing
+   Copyright   : Copyright (C) 2006-2024 John MacFarlane
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : John MacFarlane <jgm@berkeley.edu>
+   Stability   : alpha
+   Portability : portable
+
+Parsing functions and utilities.
+-}
+module Text.Pandoc.Readers.HTML.Parsing
+  ( TagOmission (..)
+  , pInTags
+  , pInTags'
+  , pInTag
+  , pInTagWithAttribs
+  , pAny
+  , pCloses
+  , pSatisfy
+  , pBlank
+  , matchTagClose
+  , matchTagOpen
+  , isSpace
+  , maybeFromAttrib
+  , toAttr
+  , toStringAttr
+  )
+where
+
+import Control.Monad (void, mzero, mplus)
+import Data.Maybe (fromMaybe)
+import Data.Text (Text)
+import Text.HTML.TagSoup
+  ( Attribute, Tag (..), isTagPosition, isTagOpen, isTagClose, (~==) )
+import Text.Pandoc.Class.PandocMonad (PandocMonad (..))
+import Text.Pandoc.Definition (Attr)
+import Text.Pandoc.Parsing
+  ( (<|>), eof, getPosition, lookAhead, manyTill, newPos, option, optional
+  , skipMany, setPosition, token, try)
+import Text.Pandoc.Readers.HTML.TagCategories
+import Text.Pandoc.Readers.HTML.Types
+import Text.Pandoc.Shared (tshow)
+import Text.Pandoc.XML (html5Attributes, html4Attributes, rdfaAttributes)
+import qualified Data.Set as Set
+import qualified Data.Text as T
+
+-- | Whether no tag, the closing tag, or both tags can be omitted.
+data TagOmission
+  = TagsRequired       -- ^ Opening and closing tags are both required
+  | ClosingTagOptional -- ^ The closing tag can be omitted
+  | TagsOmittable      -- ^ Both tags, opening and closing, can be omitted.
+  deriving (Eq)
+
+pInTags :: (PandocMonad m, Monoid a) => Text -> TagParser m a -> TagParser m a
+pInTags tagtype parser = pInTags' tagtype (const True) parser
+
+pInTags' :: (PandocMonad m, Monoid a)
+         => Text
+         -> (Tag Text -> Bool)
+         -> TagParser m a
+         -> TagParser m a
+pInTags' tagtype tagtest parser = try $ do
+  pSatisfy $ \t -> matchTagOpen tagtype [] t && tagtest t
+  mconcat <$> manyTill parser (pCloses tagtype <|> eof)
+
+pInTag :: PandocMonad m
+       => TagOmission    -- ^ Whether some tags can be omitted
+       -> Text           -- ^ @tagtype@ Tag name
+       -> TagParser m a  -- ^ @p@ Content parser
+       -> TagParser m a
+pInTag tagOmission tagtype = fmap snd . pInTagWithAttribs tagOmission tagtype
+
+-- | Returns the contents of a tag together with its attributes; parses
+-- @p@, preceded by an opening tag (optional if TagsOmittable) and
+-- followed by a closing tag (optional unless TagsRequired).
+pInTagWithAttribs :: PandocMonad m
+                  => TagOmission    -- ^ Whether some tags can be omitted
+                  -> Text           -- ^ @tagtype@ Tag name
+                  -> TagParser m a  -- ^ @p@ Content parser
+                  -> TagParser m ([Attribute Text], a)
+pInTagWithAttribs tagOmission tagtype p = try $ do
+  let openingOptional = tagOmission == TagsOmittable
+  let closingOptional = tagOmission /= TagsRequired
+  skipMany pBlank
+  attribs <- (if openingOptional then option [] else id)
+             (getAttribs <$> pSatisfy (matchTagOpen tagtype []))
+  skipMany pBlank
+  x <- p
+  skipMany pBlank
+  (if closingOptional then optional else void) $
+    pSatisfy (matchTagClose tagtype)
+  skipMany pBlank
+  return (attribs, x)
+  where
+    getAttribs = \case
+      TagOpen _ attribs -> attribs
+      _                 -> []
+
+pCloses :: PandocMonad m => Text -> TagParser m ()
+pCloses tagtype = try $ do
+  t <- lookAhead $ pSatisfy $ \tag -> isTagClose tag || isTagOpen tag
+  case t of
+       (TagClose t') | t' == tagtype -> void pAny
+       (TagClose "th") | tagtype == "td" -> void pAny -- see #9090
+       (TagClose "td") | tagtype == "th" -> void pAny
+       (TagOpen t' _) | t' `closes` tagtype -> return ()
+       (TagClose "ul") | tagtype == "li" -> return ()
+       (TagClose "ol") | tagtype == "li" -> return ()
+       (TagClose "dl") | tagtype == "dd" -> return ()
+       (TagClose "table") | tagtype == "td" -> return ()
+       (TagClose "table") | tagtype == "th" -> return ()
+       (TagClose "table") | tagtype == "tr" -> return ()
+       (TagClose "td") | tagtype `Set.member` blockHtmlTags -> return ()
+       (TagClose "th") | tagtype `Set.member` blockHtmlTags -> return ()
+       (TagClose t') | tagtype == "p" && t' `Set.member` blockHtmlTags
+                                            -> return () -- see #3794
+       _ -> mzero
+
+pBlank :: PandocMonad m => TagParser m ()
+pBlank = void $ pSatisfy isBlank
+ where
+  isBlank (TagText t) = T.all isSpace t
+  isBlank (TagComment _) = True
+  isBlank _ = False
+
+pLocation :: PandocMonad m => TagParser m ()
+pLocation = do
+  (TagPosition r c) <- pSat isTagPosition
+  setPosition $ newPos "input" r c
+
+pSat :: PandocMonad m => (Tag Text -> Bool) -> TagParser m (Tag Text)
+pSat f = do
+  pos <- getPosition
+  token tshow (const pos) (\x -> if f x then Just x else Nothing)
+
+pSatisfy :: PandocMonad m => (Tag Text -> Bool) -> TagParser m (Tag Text)
+pSatisfy f = try $ optional pLocation >> pSat f
+
+matchTagClose :: Text -> (Tag Text -> Bool)
+matchTagClose t = (~== TagClose t)
+
+matchTagOpen :: Text -> [(Text, Text)] -> (Tag Text -> Bool)
+matchTagOpen t as = (~== TagOpen t as)
+
+pAny :: PandocMonad m => TagParser m (Tag Text)
+pAny = pSatisfy (const True)
+
+isSpace :: Char -> Bool
+isSpace ' '  = True
+isSpace '\t' = True
+isSpace '\n' = True
+isSpace '\r' = True
+isSpace _    = False
+
+-- taken from HXT and extended
+-- See http://www.w3.org/TR/html5/syntax.html sec 8.1.2.4 optional tags
+closes :: Text -> Text -> Bool
+_ `closes` "body" = False
+_ `closes` "html" = False
+"body" `closes` "head" = True
+"a" `closes` "a" = True
+"li" `closes` "li" = True
+"th" `closes` t | t `elem` ["th","td"] = True
+"td" `closes` t | t `elem` ["th","td"] = True
+"tr" `closes` t | t `elem` ["th","td","tr","colgroup"] = True
+"dd" `closes` t | t `elem` ["dt", "dd"] = True
+"dt" `closes` t | t `elem` ["dt","dd"] = True
+"rt" `closes` t | t `elem` ["rb", "rt", "rtc"] = True
+"col" `closes` "col" = True
+"colgroup" `closes` "col" = True
+"optgroup" `closes` "optgroup" = True
+"optgroup" `closes` "option" = True
+"option" `closes` "option" = True
+-- https://html.spec.whatwg.org/multipage/syntax.html#optional-tags
+x `closes` "p" | x `elem` ["address", "article", "aside", "blockquote",
+   "dir", "div", "dl", "fieldset", "footer", "form", "h1", "h2", "h3", "h4",
+   "h5", "h6", "header", "hr", "main", "menu", "nav", "ol", "p", "pre", "section",
+   "table", "ul"] = True
+_ `closes` "meta" = True
+"form" `closes` "form" = True
+"label" `closes` "label" = True
+"map" `closes` "map" = True
+"object" `closes` "object" = True
+_ `closes` t | t `elem` ["option","style","script","textarea","title"] = True
+t `closes` "select" | t /= "option" = True
+"thead" `closes` "colgroup" = True
+"tfoot" `closes` t | t `elem` ["thead","colgroup"] = True
+"tbody" `closes` t | t `elem` ["tbody","tfoot","thead","colgroup"] = True
+t `closes` t2 |
+   t `elem` ["h1","h2","h3","h4","h5","h6","dl","ol","ul","table","div","main","p"] &&
+   t2 `elem` ["h1","h2","h3","h4","h5","h6","p" ] = True -- not "div" or "main"
+t1 `closes` t2 |
+   t1 `Set.member` blockTags &&
+   t2 `Set.notMember` blockTags &&
+   t2 `Set.notMember` eitherBlockOrInline = True
+_ `closes` _ = False
+
+toStringAttr :: [(Text, Text)] -> [(Text, Text)]
+toStringAttr = foldr go []
+  where
+   go :: (Text, Text) -> [(Text, Text)] -> [(Text, Text)]
+   -- treat xml:lang as lang
+   go ("xml:lang",y) ats = go ("lang",y) ats
+   -- prevent duplicate attributes
+   go (x,y) ats
+     | any (\(x',_) -> x == x') ats = ats
+     | otherwise      =
+        case T.stripPrefix "data-" x of
+          Just x' | x' `Set.notMember` (html5Attributes <>
+                                        html4Attributes <> rdfaAttributes)
+            -> go (x',y) ats
+          _ -> (x,y):ats
+
+-- Unlike fromAttrib from tagsoup, this distinguishes
+-- between a missing attribute and an attribute with empty content.
+maybeFromAttrib :: Text -> Tag Text -> Maybe Text
+maybeFromAttrib name (TagOpen _ attrs) = lookup name attrs
+maybeFromAttrib _ _ = Nothing
+
+mkAttr :: [(Text, Text)] -> Attr
+mkAttr attr = (attribsId, attribsClasses, attribsKV)
+  where attribsId = fromMaybe "" $ lookup "id" attr `mplus` lookup "name" attr
+        attribsClasses = T.words (fromMaybe "" $ lookup "class" attr) <> epubTypes
+        attribsKV = filter (\(k,_) -> k /= "class" && k /= "id" && k /= "name")
+                           attr
+        epubTypes = T.words $ fromMaybe "" $ lookup "epub:type" attr
+
+toAttr :: [(Text, Text)] -> Attr
+toAttr = mkAttr . toStringAttr
diff --git a/src/Text/Pandoc/Readers/HTML/Table.hs b/src/Text/Pandoc/Readers/HTML/Table.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Readers/HTML/Table.hs
@@ -0,0 +1,307 @@
+{-# LANGUAGE LambdaCase        #-}
+{-# LANGUAGE OverloadedStrings #-}
+{-# LANGUAGE ViewPatterns      #-}
+{- |
+   Module      : Text.Pandoc.Readers.HTML.Table
+   Copyright   : © 2006-2024 John MacFarlane,
+                   2020-2024 Albert Krewinkel
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : Albert Krewinkel <albert+pandoc@tarleb.com>
+   Stability   : alpha
+   Portability : portable
+
+HTML table parser.
+-}
+module Text.Pandoc.Readers.HTML.Table (pTable) where
+
+import qualified Data.Vector as V
+import Control.Applicative ((<|>))
+import Data.Maybe (fromMaybe, isJust)
+import Data.Either (lefts, rights)
+import Data.List.NonEmpty (nonEmpty)
+import qualified Data.List as L
+import Data.Text (Text)
+import Text.HTML.TagSoup
+import Text.Pandoc.Builder (Blocks)
+import Text.Pandoc.CSS (cssAttributes)
+import Text.Pandoc.Definition
+import Text.Pandoc.Class.PandocMonad (PandocMonad (..))
+import Text.Pandoc.Parsing
+  ( eof, lookAhead, many, many1, manyTill, option, optional
+  , optionMaybe, skipMany, try )
+import Text.Pandoc.Readers.HTML.Parsing
+import Text.Pandoc.Readers.HTML.Types (TagParser)
+import Text.Pandoc.Shared (onlySimpleTableCells, safeRead)
+import qualified Data.Text as T
+import qualified Text.Pandoc.Builder as B
+import Control.Monad (guard)
+
+-- | Parses a @<col>@ element, returning the column's width.
+-- An Either value is used:  Left i means a "relative length" with
+-- integral value i (see https://www.w3.org/TR/html4/types.html#h-6.6);
+-- Right w means a regular width.  Defaults to @'Right ColWidthDefault'@
+-- if the width is not set or cannot be determined.
+pCol :: PandocMonad m => TagParser m (Either Int ColWidth)
+pCol = try $ do
+  TagOpen _ attribs' <- pSatisfy (matchTagOpen "col" [])
+  let attribs = toStringAttr attribs'
+  skipMany pBlank
+  optional $ pSatisfy (matchTagClose "col")
+  skipMany pBlank
+  return $ case lookup "width" attribs of
+                Nothing -> case lookup "style" attribs of
+                  Just (T.stripPrefix "width:" -> Just xs) | T.any (== '%') xs ->
+                    maybe (Right ColWidthDefault) (Right . ColWidth . (/ 100.0))
+                      $ safeRead (T.filter
+                                   (`notElem` (" \t\r\n%'\";" :: [Char])) xs)
+                  _ -> Right ColWidthDefault
+                Just (T.unsnoc -> Just (xs, '*')) ->
+                  maybe (Left 1) Left $ safeRead xs
+                Just (T.unsnoc -> Just (xs, '%')) ->
+                  maybe (Right ColWidthDefault)
+                        (Right . ColWidth . (/ 100.0)) $ safeRead xs
+                _ -> Right ColWidthDefault
+
+pColgroup :: PandocMonad m => TagParser m [Either Int ColWidth]
+pColgroup = try $ do
+  pSatisfy (matchTagOpen "colgroup" [])
+  skipMany pBlank
+  manyTill pCol (pCloses "colgroup" <|> eof) <* skipMany pBlank
+
+resolveRelativeLengths :: [Either Int ColWidth] -> [ColWidth]
+resolveRelativeLengths ws =
+  let remaining = 1 - sum (map getColWidth $ rights ws)
+      relatives = sum $ lefts ws
+      relUnit = remaining / fromIntegral relatives
+      toColWidth (Right x) = x
+      toColWidth (Left i) = ColWidth (fromIntegral i * relUnit)
+  in  map toColWidth ws
+
+getColWidth :: ColWidth -> Double
+getColWidth ColWidthDefault = 0
+getColWidth (ColWidth w) = w
+
+data CellType
+  = HeaderCell
+  | BodyCell
+  deriving Eq
+
+pCell :: PandocMonad m
+      => TagParser m Blocks
+      -> CellType
+      -> TagParser m (CellType, Cell)
+pCell block celltype = try $ do
+  let celltype' = case celltype of
+        HeaderCell -> "th"
+        BodyCell   -> "td"
+  skipMany pBlank
+  TagOpen _ attribs <- lookAhead $ pSatisfy (matchTagOpen celltype' [])
+  let cssAttribs = maybe [] cssAttributes $ lookup "style" attribs
+  let align = case lookup "align" attribs <|>
+                   lookup "text-align" cssAttribs of
+                Just "left"   -> AlignLeft
+                Just "right"  -> AlignRight
+                Just "center" -> AlignCenter
+                _             -> AlignDefault
+  let rowspan = RowSpan . fromMaybe 1 $
+                safeRead =<< lookup "rowspan" attribs
+  let colspan = ColSpan . fromMaybe 1 $
+                safeRead =<< lookup "colspan" attribs
+  res <- pInTags celltype' block
+  skipMany pBlank
+  let handledAttribs = ["align", "colspan", "rowspan", "text-align"]
+      attribs' = foldr go [] attribs
+      go kv@(k, _) acc = case k of
+        "style" -> case filter ((/= "text-align") . fst) cssAttribs of
+                     [] -> acc
+                     cs -> ("style", toStyleString cs) : acc
+        -- drop attrib if it's already handled
+        _ | k `elem` handledAttribs -> acc
+        _ -> kv : acc
+  return (celltype, B.cellWith (toAttr attribs') align rowspan colspan res)
+
+-- | Create a style attribute string from a list of CSS attributes
+toStyleString :: [(Text, Text)] -> Text
+toStyleString = T.intercalate "; " . map (\(k, v) -> k <> ": " <> v)
+
+-- | Parses a normal table row; returns the row and the number
+-- of cells at the beginning that are header cells.
+pRow :: PandocMonad m
+     => TagParser m Blocks
+     -> TagParser m (Int, B.Row)
+pRow block = try $ do
+  skipMany pBlank
+  TagOpen _ attribs <- pSatisfy (matchTagOpen "tr" []) <* skipMany pBlank
+  cells <- many (pCell block BodyCell <|> pCell block HeaderCell)
+  TagClose _ <- pSatisfy (matchTagClose "tr")
+  let numheadcells = length $ takeWhile (\(ct,_) -> ct == HeaderCell) cells
+  return (numheadcells, Row (toAttr attribs) $ map snd cells)
+
+-- | Parses a header row, i.e., a row which containing nothing but
+-- @<th>@ elements.
+pHeaderRow :: PandocMonad m
+           => TagParser m Blocks
+           -> TagParser m B.Row
+pHeaderRow block = try $ do
+  skipMany pBlank
+  let pThs = many (snd <$> pCell block HeaderCell)
+  let mkRow (attribs, cells) = Row (toAttr attribs) cells
+  mkRow <$> pInTagWithAttribs TagsRequired "tr" pThs
+
+-- | Parses a table head. If there is no @thead@ element, this looks for
+-- a row of @<th>@-only elements as the first line of the table.
+pTableHead :: PandocMonad m
+           => TagParser m Blocks
+           -> TagParser m TableHead
+pTableHead block = try $ do
+  skipMany pBlank
+  let pRows = many (pRow block)
+  let pThead = pInTagWithAttribs ClosingTagOptional "thead" pRows
+  optionMaybe pThead >>= \case
+    Just (attribs, rows) ->
+      return $ TableHead (toAttr attribs) $ map snd rows
+    Nothing -> mkTableHead <$> optionMaybe (pHeaderRow block)
+               where
+                 mkTableHead = TableHead nullAttr . \case
+                   -- Use row as header only if it's non-empty
+                   Just row@(Row _ (_:_)) -> [row]
+                   _                      -> []
+
+-- | Parses a table foot
+pTableFoot :: PandocMonad m
+           => TagParser m Blocks
+           -> TagParser m TableFoot
+pTableFoot block = try $ do
+  skipMany pBlank
+  TagOpen _ attribs <- pSatisfy (matchTagOpen "tfoot" []) <* skipMany pBlank
+  rows <- many $ snd <$> (pRow block <* skipMany pBlank)
+  optional $ pSatisfy (matchTagClose "tfoot")
+  return $ TableFoot (toAttr attribs) rows
+
+-- | Parses a table body
+pTableBody :: PandocMonad m
+           => TagParser m Blocks
+           -> TagParser m TableBody
+pTableBody block = try $ do
+  skipMany pBlank
+  mbattribs <- option Nothing $ Just . getAttribs <$>
+                 pSatisfy (matchTagOpen "tbody" []) <* skipMany pBlank
+  bodyheads <- many (pHeaderRow block)
+  rows <- many (pRow block <* skipMany pBlank)
+  optional $ pSatisfy (matchTagClose "tbody")
+  guard $ isJust mbattribs || not (null bodyheads && null rows)
+  let attribs = fromMaybe [] mbattribs
+  -- we only set row head columns if all rows agree;
+  -- if some rows have headings but others not, we use 0; see #8984, #8634:
+  let numrows = length rows
+  let adjustRowHeadColsForCell currentrow headcolsv
+                    (Cell _ _ (RowSpan rowspan) (ColSpan colspan) _) =
+        V.imap (\i x -> if i >= currentrow &&
+                           i < currentrow + rowspan
+                           then x + colspan
+                           else x) headcolsv
+  let adjustRowHeadCols
+        headcolsv
+        (currentrow, (numheads, Row _ cells)) =
+          L.foldl' (adjustRowHeadColsForCell currentrow) headcolsv
+            (take numheads cells)
+  let headcols = L.foldl' adjustRowHeadCols
+                         (V.replicate numrows (0 :: Int))
+                         (zip [(0 :: Int)..] rows)
+  let rowHeadCols = case V.uncons headcols of
+                       Just (x, v) | all (== x) v -> RowHeadColumns x
+                       _ -> RowHeadColumns 0
+  return $ TableBody (toAttr attribs) rowHeadCols bodyheads (map snd rows)
+  where
+    getAttribs (TagOpen _ attribs) = attribs
+    getAttribs _ = []
+
+-- | Parses a simple HTML table
+pTable :: PandocMonad m
+       => TagParser m Blocks -- ^ Caption and cell contents parser
+       -> TagParser m Blocks
+pTable block = try $ do
+  TagOpen _ attribs <- pSatisfy (matchTagOpen "table" [])  <* skipMany pBlank
+  caption <- option mempty $ pInTags "caption" block       <* skipMany pBlank
+  widths <- resolveRelativeLengths <$>
+              ((mconcat <$> many1 pColgroup) <|> many pCol) <* skipMany pBlank
+  thead   <- pTableHead block               <* skipMany pBlank
+  topfoot <- optionMaybe (pTableFoot block) <* skipMany pBlank
+  tbodies <- many (pTableBody block)        <* skipMany pBlank
+  botfoot <- optionMaybe (pTableFoot block) <* skipMany pBlank
+  TagClose _ <- pSatisfy (matchTagClose "table")
+  let tfoot = fromMaybe (TableFoot nullAttr []) $ topfoot <|> botfoot
+  case normalize widths thead tbodies tfoot of
+    Left err -> fail err
+    Right (colspecs, thead', tbodies', tfoot') -> return $
+      B.tableWith (toAttr attribs)
+                  (B.simpleCaption caption)
+                  colspecs
+                  thead'
+                  tbodies'
+                  tfoot'
+data TableType
+  = SimpleTable
+  | NormalTable
+
+tableType :: [[Cell]] -> TableType
+tableType cells =
+  if onlySimpleTableCells $ map (map cellContents) cells
+  then SimpleTable
+  else NormalTable
+  where
+    cellContents :: Cell -> [Block]
+    cellContents (Cell _ _ _ _ bs) = bs
+
+normalize :: [ColWidth] -> TableHead -> [TableBody] -> TableFoot
+          -> Either String ([ColSpec], TableHead, [TableBody], TableFoot)
+normalize widths head' bodies foot = do
+  let rows = headRows head' <> concatMap bodyRows bodies <> footRows foot
+  let cellWidth (Cell _ _ _ (ColSpan cs) _) = cs
+  let rowLength = foldr (\cell acc -> cellWidth cell + acc) 0 . rowCells
+  let ncols = maybe 0 maximum $ nonEmpty $ map rowLength rows
+  let tblType = tableType (map rowCells rows)
+  -- fail on empty table
+  if null rows
+    then Left "empty table"
+    else Right
+         ( zip (calculateAlignments ncols bodies)
+               (normalizeColWidths ncols tblType widths)
+         , head'
+         , bodies
+         , foot
+         )
+
+normalizeColWidths :: Int -> TableType -> [ColWidth] -> [ColWidth]
+normalizeColWidths ncols tblType = \case
+  [] -> case tblType of
+          SimpleTable -> replicate ncols ColWidthDefault
+          NormalTable -> replicate ncols (ColWidth $ 1 / fromIntegral ncols)
+  widths -> widths
+
+calculateAlignments :: Int -> [TableBody] -> [Alignment]
+calculateAlignments cols tbodies =
+  case cells of
+    cs:_ -> take cols $ concatMap cellAligns cs ++ repeat AlignDefault
+    _    -> replicate cols AlignDefault
+  where
+    cells :: [[Cell]]
+    cells = concatMap bodyRowCells tbodies
+    cellAligns :: Cell -> [Alignment]
+    cellAligns (Cell _ align _ (ColSpan cs) _) = replicate cs align
+
+bodyRowCells :: TableBody -> [[Cell]]
+bodyRowCells = map rowCells . bodyRows
+
+headRows :: TableHead -> [B.Row]
+headRows (TableHead _ rows) = rows
+
+bodyRows :: TableBody -> [B.Row]
+bodyRows (TableBody _ _ headerRows bodyRows') = headerRows <> bodyRows'
+
+footRows :: TableFoot -> [B.Row]
+footRows (TableFoot _ rows) = rows
+
+rowCells :: B.Row -> [Cell]
+rowCells (Row _ cells) = cells
diff --git a/src/Text/Pandoc/Readers/HTML/TagCategories.hs b/src/Text/Pandoc/Readers/HTML/TagCategories.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Readers/HTML/TagCategories.hs
@@ -0,0 +1,78 @@
+{-# LANGUAGE OverloadedStrings     #-}
+{- |
+   Module      : Text.Pandoc.Readers.HTML.TagCategories
+   Copyright   : Copyright (C) 2006-2024 John MacFarlane
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : John MacFarlane <jgm@berkeley.edu>
+   Stability   : alpha
+   Portability : portable
+
+Categories of tags.
+-}
+module Text.Pandoc.Readers.HTML.TagCategories
+  ( blockHtmlTags
+  , blockDocBookTags
+  , eitherBlockOrInline
+  , epubTags
+  , blockTags
+  , sectioningContent
+  , groupingContent
+  )
+where
+
+import Data.Set (Set, fromList, unions)
+import Data.Text (Text)
+
+eitherBlockOrInline :: Set Text
+eitherBlockOrInline = fromList
+  ["audio", "applet", "button", "iframe", "embed",
+   "del", "ins", "progress", "map", "area", "noscript", "script",
+   "object", "svg", "video", "source", "track"]
+
+blockHtmlTags :: Set Text
+blockHtmlTags = fromList
+   ["?xml", "!DOCTYPE", "address", "article", "aside",
+    "blockquote", "body", "canvas",
+    "caption", "center", "col", "colgroup", "dd", "details",
+    "dir", "div", "dl", "dt", "fieldset", "figcaption", "figure",
+    "footer", "form", "h1", "h2", "h3", "h4",
+    "h5", "h6", "head", "header", "hgroup", "hr", "html",
+    "isindex", "main", "menu", "meta", "noframes", "nav",
+    "ol", "output", "p", "pre",
+    "section", "summary", "table", "tbody", "textarea",
+    "thead", "tfoot", "ul", "dd",
+    "dt", "frameset", "li", "tbody", "td", "tfoot",
+    "th", "thead", "tr", "script", "style"]
+
+-- We want to allow raw docbook in markdown documents, so we
+-- include docbook block tags here too.
+blockDocBookTags :: Set Text
+blockDocBookTags = fromList
+   ["calloutlist", "bibliolist", "glosslist", "itemizedlist",
+    "orderedlist", "segmentedlist", "simplelist",
+    "variablelist", "caution", "important", "note", "tip",
+    "warning", "address", "literallayout", "programlisting",
+    "programlistingco", "screen", "screenco", "screenshot",
+    "synopsis", "example", "informalexample", "figure",
+    "informalfigure", "table", "informaltable", "para",
+    "simpara", "formalpara", "equation", "informalequation",
+    "figure", "screenshot", "mediaobject", "qandaset",
+    "procedure", "task", "cmdsynopsis", "funcsynopsis",
+    "classsynopsis", "blockquote", "epigraph", "msgset",
+    "sidebar", "title"]
+
+epubTags :: Set Text
+epubTags = fromList ["case", "switch", "default"]
+
+blockTags :: Set Text
+blockTags = unions [blockHtmlTags, blockDocBookTags, epubTags]
+
+sectioningContent :: [Text]
+sectioningContent = ["article", "aside", "nav", "section"]
+
+
+groupingContent :: [Text]
+groupingContent = ["p", "hr", "pre", "blockquote", "ol"
+                  , "ul", "li", "dl", "dt", "dt", "dd"
+                  , "figure", "figcaption", "div", "main"]
diff --git a/src/Text/Pandoc/Readers/HTML/Types.hs b/src/Text/Pandoc/Readers/HTML/Types.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Readers/HTML/Types.hs
@@ -0,0 +1,99 @@
+{-# LANGUAGE FlexibleInstances     #-}
+{-# LANGUAGE MultiParamTypeClasses #-}
+{- |
+   Module      : Text.Pandoc.Readers.HTML.Types
+   Copyright   : Copyright (C) 2006-2024 John MacFarlane
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : John MacFarlane <jgm@berkeley.edu>
+   Stability   : alpha
+   Portability : portable
+
+Types for pandoc's HTML reader.
+-}
+module Text.Pandoc.Readers.HTML.Types
+  ( TagParser
+  , HTMLParser
+  , HTMLState (..)
+  , HTMLLocal (..)
+  )
+where
+
+import Control.Monad.Reader (ReaderT, asks, local)
+import Data.Default (Default (def))
+import Data.Map (Map)
+import Data.Set (Set)
+import Data.Text (Text)
+import Network.URI (URI)
+import Text.HTML.TagSoup
+import Text.Pandoc.Builder (Blocks, HasMeta (..))
+import Text.Pandoc.Class.PandocMonad (PandocMonad (..))
+import Text.Pandoc.Logging (LogMessage)
+import Text.Pandoc.Options (ReaderOptions)
+import Text.Pandoc.Parsing
+  ( HasIdentifierList (..), HasLastStrPosition (..), HasLogMessages (..)
+  , HasMacros (..), HasQuoteContext (..), HasReaderOptions (..)
+  , ParsecT, ParserState, QuoteContext (NoQuote)
+  )
+import Text.Pandoc.TeX (Macro)
+
+-- | HTML parser type
+type HTMLParser m s = ParsecT s HTMLState (ReaderT HTMLLocal m)
+
+-- | HTML parser, expecting @Tag Text@ as tokens.
+type TagParser m = HTMLParser m [Tag Text]
+
+-- | Global HTML parser state
+data HTMLState = HTMLState
+  { parserState :: ParserState
+  , noteTable   :: [(Text, Blocks)]
+  , baseHref    :: Maybe URI
+  , identifiers :: Set Text
+  , logMessages :: [LogMessage]
+  , macros      :: Map Text Macro
+  , readerOpts  :: ReaderOptions
+  , inFootnotes :: Bool
+  }
+
+-- | Local HTML parser state
+data HTMLLocal = HTMLLocal
+  { quoteContext :: QuoteContext
+  , inChapter    :: Bool -- ^ Set if in chapter section
+  , inPlain      :: Bool -- ^ Set if in pPlain
+  , inListItem   :: Bool -- ^ Set if in <li> tag
+  }
+
+
+-- Instances
+
+instance HasMacros HTMLState where
+  extractMacros        = macros
+  updateMacros f st    = st{ macros = f $ macros st }
+
+instance HasIdentifierList HTMLState where
+  extractIdentifierList = identifiers
+  updateIdentifierList f s = s{ identifiers = f (identifiers s) }
+
+instance HasLogMessages HTMLState where
+  addLogMessage m s = s{ logMessages = m : logMessages s }
+  getLogMessages = reverse . logMessages
+
+-- This signature should be more general
+-- MonadReader HTMLLocal m => HasQuoteContext st m
+instance PandocMonad m => HasQuoteContext HTMLState (ReaderT HTMLLocal m) where
+  getQuoteContext = asks quoteContext
+  withQuoteContext q = local (\s -> s{quoteContext = q})
+
+instance HasReaderOptions HTMLState where
+    extractReaderOptions = extractReaderOptions . parserState
+
+instance HasMeta HTMLState where
+  setMeta s b st = st {parserState = setMeta s b $ parserState st}
+  deleteMeta s st = st {parserState = deleteMeta s $ parserState st}
+
+instance Default HTMLLocal where
+  def = HTMLLocal NoQuote False False False
+
+instance HasLastStrPosition HTMLState where
+  setLastStrPos s st = st {parserState = setLastStrPos s (parserState st)}
+  getLastStrPos = getLastStrPos . parserState
diff --git a/src/Text/Pandoc/Readers/Haddock.hs b/src/Text/Pandoc/Readers/Haddock.hs
--- a/src/Text/Pandoc/Readers/Haddock.hs
+++ b/src/Text/Pandoc/Readers/Haddock.hs
@@ -1,4 +1,5 @@
-{-# LANGUAGE CPP #-}
+{-# LANGUAGE CPP               #-}
+{-# LANGUAGE OverloadedStrings #-}
 {- |
    Module      : Text.Pandoc.Readers.Haddock
    Copyright   : Copyright (C) 2013 David Lazar
@@ -15,27 +16,30 @@
     ) where
 
 import Control.Monad.Except (throwError)
-import Data.List (intersperse, stripPrefix)
+import Data.List (intersperse)
+import Data.List.NonEmpty (nonEmpty)
 import Data.Maybe (fromMaybe)
-import Data.Monoid ((<>))
-import Data.Text (Text, unpack)
+import Data.Text (unpack)
+import qualified Data.Text as T
 import Documentation.Haddock.Parser
-import Documentation.Haddock.Types
+import Documentation.Haddock.Types as H
 import Text.Pandoc.Builder (Blocks, Inlines)
 import qualified Text.Pandoc.Builder as B
-import Text.Pandoc.Class (PandocMonad)
+import Text.Pandoc.Class.PandocMonad (PandocMonad)
 import Text.Pandoc.Definition
 import Text.Pandoc.Error
 import Text.Pandoc.Options
-import Text.Pandoc.Shared (crFilter, splitBy, trim)
+import Text.Pandoc.Sources (ToSources(..), sourcesToText)
+import Text.Pandoc.Shared (splitTextBy, trim)
 
 
 -- | Parse Haddock markup and return a 'Pandoc' document.
-readHaddock :: PandocMonad m
+readHaddock :: (PandocMonad m, ToSources a)
             => ReaderOptions
-            -> Text
+            -> a
             -> m Pandoc
-readHaddock opts s = case readHaddockEither opts (unpack (crFilter s)) of
+readHaddock opts s = case readHaddockEither opts
+                           (unpack . sourcesToText . toSources $ s) of
   Right result -> return result
   Left e       -> throwError e
 
@@ -43,18 +47,14 @@
                   -> String        -- ^ String to parse
                   -> Either PandocError Pandoc
 readHaddockEither _opts =
-#if MIN_VERSION_haddock_library(1,2,0)
-  Right . B.doc . docHToBlocks . _doc . parseParas
-#else
-  Right .  B.doc . docHToBlocks . parseParas
-#endif
+  Right . B.doc . docHToBlocks . _doc . parseParas Nothing
 
 docHToBlocks :: DocH String Identifier -> Blocks
 docHToBlocks d' =
   case d' of
     DocEmpty -> mempty
     DocAppend (DocParagraph (DocHeader h)) (DocParagraph (DocAName ident)) ->
-         B.headerWith (ident,[],[]) (headerLevel h)
+         B.headerWith (T.pack ident,[],[]) (headerLevel h)
             (docHToInlines False $ headerTitle h)
     DocAppend d1 d2 -> mappend (docHToBlocks d1) (docHToBlocks d2)
     DocString _ -> inlineFallback
@@ -67,25 +67,50 @@
     DocEmphasis _ -> inlineFallback
     DocMonospaced _ -> inlineFallback
     DocBold _ -> inlineFallback
-#if MIN_VERSION_haddock_library(1,4,0)
     DocMathInline _ -> inlineFallback
     DocMathDisplay _ -> inlineFallback
-#endif
     DocHeader h -> B.header (headerLevel h)
                            (docHToInlines False $ headerTitle h)
     DocUnorderedList items -> B.bulletList (map docHToBlocks items)
+#if MIN_VERSION_haddock_library(1,11,0)
+    DocOrderedList items ->
+      B.orderedListWith attr (map (docHToBlocks . snd) items)
+     where
+      attr = (start, DefaultStyle, DefaultDelim)
+      start = case items of
+                [] -> 1
+                ((n,_):_) -> n
+#else
     DocOrderedList items -> B.orderedList (map docHToBlocks items)
+#endif
     DocDefList items -> B.definitionList (map (\(d,t) ->
                                (docHToInlines False d,
                                 [consolidatePlains $ docHToBlocks t])) items)
-    DocCodeBlock (DocString s) -> B.codeBlockWith ("",[],[]) s
+    DocCodeBlock (DocString s) -> B.codeBlockWith ("",[],[]) $ T.pack s
     DocCodeBlock d -> B.para $ docHToInlines True d
     DocHyperlink _ -> inlineFallback
     DocPic _ -> inlineFallback
     DocAName _ -> inlineFallback
-    DocProperty s -> B.codeBlockWith ("",["property","haskell"],[]) (trim s)
+    DocProperty s -> B.codeBlockWith ("",["property","haskell"],[]) (trim $ T.pack s)
     DocExamples es -> mconcat $ map (\e ->
        makeExample ">>>" (exampleExpression e) (exampleResult e)) es
+    DocTable H.Table{ tableHeaderRows = headerRows
+                    , tableBodyRows = bodyRows
+                    }
+      -> let toCells = map (docHToBlocks . tableCellContents) . tableRowCells
+             toRow = Row nullAttr . map B.simpleCell
+             toHeaderRow l = [toRow l | not (null l)]
+             (header, body) =
+               case headerRows of
+                  [] -> ([], map toCells bodyRows)
+                  (x:xs) -> (toCells x, map toCells (xs ++ bodyRows))
+             colspecs = replicate (maybe 0 maximum (nonEmpty (map length body)))
+                             (AlignDefault, ColWidthDefault)
+         in  B.table B.emptyCaption
+                     colspecs
+                     (TableHead nullAttr $ toHeaderRow header)
+                     [TableBody nullAttr 0 [] $ map toRow body]
+                     (TableFoot nullAttr [])
 
   where inlineFallback = B.plain $ docHToInlines False d'
         consolidatePlains = B.fromList . consolidatePlains' . B.toList
@@ -107,55 +132,59 @@
                                (docHToInlines isCode d2)
     DocString s
       | isCode -> mconcat $ intersperse B.linebreak
-                              $ map B.code $ splitBy (=='\n') s
-      | otherwise  -> B.text s
+                              $ map B.code $ splitTextBy (=='\n') $ T.pack s
+      | otherwise  -> B.text $ T.pack s
     DocParagraph _ -> mempty
-    DocIdentifier (_,s,_) -> B.codeWith ("",["haskell","identifier"],[]) s
-    DocIdentifierUnchecked s -> B.codeWith ("",["haskell","identifier"],[]) s
-    DocModule s -> B.codeWith ("",["haskell","module"],[]) s
+    DocIdentifier ident ->
+        case toRegular (DocIdentifier ident) of
+          DocIdentifier s -> B.codeWith ("",["haskell","identifier"],[]) $ T.pack s
+          _               -> mempty
+    DocIdentifierUnchecked s -> B.codeWith ("",["haskell","identifier"],[]) $ T.pack s
+    DocModule s -> B.codeWith ("",["haskell","module"],[]) $
+                   T.pack (modLinkName s)
     DocWarning _ -> mempty -- TODO
     DocEmphasis d -> B.emph (docHToInlines isCode d)
-    DocMonospaced (DocString s) -> B.code s
+    DocMonospaced (DocString s) -> B.code $ T.pack s
     DocMonospaced d -> docHToInlines True d
     DocBold d -> B.strong (docHToInlines isCode d)
-#if MIN_VERSION_haddock_library(1,4,0)
-    DocMathInline s -> B.math s
-    DocMathDisplay s -> B.displayMath s
-#endif
+    DocMathInline s -> B.math $ T.pack s
+    DocMathDisplay s -> B.displayMath $ T.pack s
     DocHeader _ -> mempty
     DocUnorderedList _ -> mempty
     DocOrderedList _ -> mempty
     DocDefList _ -> mempty
     DocCodeBlock _ -> mempty
-    DocHyperlink h -> B.link (hyperlinkUrl h) (hyperlinkUrl h)
-             (maybe (B.text $ hyperlinkUrl h) B.text $ hyperlinkLabel h)
-    DocPic p -> B.image (pictureUri p) (fromMaybe (pictureUri p) $ pictureTitle p)
-                        (maybe mempty B.text $ pictureTitle p)
-    DocAName s -> B.spanWith (s,["anchor"],[]) mempty
+    DocHyperlink h -> B.link (T.pack $ hyperlinkUrl h) (T.pack $ hyperlinkUrl h)
+             (maybe (B.text $ T.pack $ hyperlinkUrl h) (docHToInlines isCode)
+               (hyperlinkLabel h))
+    DocPic p -> B.image (T.pack $ pictureUri p) (T.pack $ fromMaybe (pictureUri p) $ pictureTitle p)
+                        (maybe mempty (B.text . T.pack) $ pictureTitle p)
+    DocAName s -> B.spanWith (T.pack s,["anchor"],[]) mempty
     DocProperty _ -> mempty
     DocExamples _ -> mempty
+    DocTable _ -> mempty
 
 -- | Create an 'Example', stripping superfluous characters as appropriate
-makeExample :: String -> String -> [String] -> Blocks
+makeExample :: T.Text -> String -> [String] -> Blocks
 makeExample prompt expression result =
     B.para $ B.codeWith ("",["prompt"],[]) prompt
         <> B.space
-        <> B.codeWith ([], ["haskell","expr"], []) (trim expression)
+        <> B.codeWith ("", ["haskell","expr"], []) (trim $ T.pack expression)
         <> B.linebreak
         <> mconcat (intersperse B.linebreak $ map coder result')
   where
     -- 1. drop trailing whitespace from the prompt, remember the prefix
-    prefix = takeWhile (`elem` " \t") prompt
+    prefix = T.takeWhile (`elem` (" \t" :: String)) prompt
 
     -- 2. drop, if possible, the exact same sequence of whitespace
     -- characters from each result line
     --
     -- 3. interpret lines that only contain the string "<BLANKLINE>" as an
     -- empty line
-    result' = map (substituteBlankLine . tryStripPrefix prefix) result
+    result' = map (substituteBlankLine . tryStripPrefix prefix . T.pack) result
       where
-        tryStripPrefix xs ys = fromMaybe ys $ stripPrefix xs ys
+        tryStripPrefix xs ys = fromMaybe ys $ T.stripPrefix xs ys
 
         substituteBlankLine "<BLANKLINE>" = ""
         substituteBlankLine line          = line
-    coder = B.codeWith ([], ["result"], [])
+    coder = B.codeWith ("", ["result"], [])
diff --git a/src/Text/Pandoc/Readers/Ipynb.hs b/src/Text/Pandoc/Readers/Ipynb.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Readers/Ipynb.hs
@@ -0,0 +1,245 @@
+{-# LANGUAGE LambdaCase #-}
+{-# LANGUAGE OverloadedStrings #-}
+{-# LANGUAGE FlexibleContexts  #-}
+{-# LANGUAGE ScopedTypeVariables #-}
+{- |
+   Module      : Text.Pandoc.Readers.Ipynb
+   Copyright   : Copyright (C) 2019-2024 John MacFarlane
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : John MacFarlane <jgm@berkeley.edu>
+   Stability   : alpha
+   Portability : portable
+
+Ipynb (Jupyter notebook JSON format) reader for pandoc.
+-}
+module Text.Pandoc.Readers.Ipynb ( readIpynb )
+where
+import Crypto.Hash (hashWith, SHA1(SHA1))
+import Data.Char (isDigit)
+import Data.Maybe (fromMaybe)
+import Text.Pandoc.Options
+import Control.Applicative ((<|>))
+import qualified Data.Scientific as Scientific
+import qualified Text.Pandoc.Builder as B
+import Text.Pandoc.Logging
+import Text.Pandoc.Definition
+import Data.Ipynb as Ipynb
+import Text.Pandoc.Class.PandocMonad
+import Text.Pandoc.MIME (extensionFromMimeType)
+import Text.Pandoc.Shared (tshow)
+import Text.Pandoc.UTF8
+import Text.Pandoc.Walk (walk)
+import Text.Pandoc.Error
+import Data.Text (Text)
+import qualified Data.Map as M
+import qualified Data.Text as T
+import qualified Data.Text.Encoding as TE
+import qualified Data.ByteString.Lazy as BL
+import Data.Aeson as Aeson
+import Control.Monad.Except (throwError)
+import Text.Pandoc.Readers.Markdown (readMarkdown)
+import qualified Text.Pandoc.UTF8 as UTF8
+import Text.Pandoc.Sources (ToSources(..), sourcesToText)
+
+readIpynb :: (PandocMonad m, ToSources a)
+          => ReaderOptions -> a -> m Pandoc
+readIpynb opts x = do
+  let src = BL.fromStrict . TE.encodeUtf8 . sourcesToText $ toSources x
+  case eitherDecode src of
+    Right (notebook4 :: Notebook NbV4) -> notebookToPandoc opts notebook4
+    Left _ ->
+      case eitherDecode src of
+        Right (notebook3 :: Notebook NbV3) -> notebookToPandoc opts notebook3
+        Left err -> throwError $ PandocIpynbDecodingError $ T.pack err
+
+notebookToPandoc :: PandocMonad m
+                 => ReaderOptions -> Notebook a -> m Pandoc
+notebookToPandoc opts notebook = do
+  let cells = notebookCells notebook
+  let (fmt,fmtminor) = notebookFormat notebook
+  let m = M.insert "nbformat" (MetaString $ tshow fmt) $
+          M.insert "nbformat_minor" (MetaString $ tshow fmtminor) $
+          jsonMetaToMeta (notebookMetadata notebook)
+  let lang = case M.lookup "kernelspec" m of
+                   Just (MetaMap ks) ->
+                      case M.lookup "language" ks of
+                         Just (MetaString l) -> l
+                         _ -> "python"
+                   _ -> "python"
+  bs <- mconcat <$> mapM (cellToBlocks opts lang) cells
+  let Pandoc _ blocks = B.doc bs
+  return $ Pandoc (Meta $ M.insert "jupyter" (MetaMap m) mempty) blocks
+
+cellToBlocks :: PandocMonad m
+             => ReaderOptions -> Text -> Ipynb.Cell a -> m B.Blocks
+cellToBlocks opts lang c = do
+  let Source ts = cellSource c
+  let source = mconcat ts
+  let kvs = jsonMetaToPairs (cellMetadata c)
+  let attachments = case cellAttachments c of
+                      Nothing -> mempty
+                      Just (MimeAttachments m) -> M.toList m
+  let ident = fromMaybe mempty $ cellId c
+  mapM_ (addAttachment (cellId c)) attachments
+  case cellType c of
+    Ipynb.Markdown -> do
+      bs <- if isEnabled Ext_raw_markdown opts
+               then return [RawBlock (Format "markdown") source]
+               else do
+                 Pandoc _ bs <- walk (fixImage (cellId c)) <$> readMarkdown opts source
+                 return bs
+      return $ B.divWith (ident,["cell","markdown"],kvs)
+             $ B.fromList bs
+    Ipynb.Heading lev -> do
+      Pandoc _ bs <- readMarkdown opts
+        (T.replicate lev "#" <> " " <> source)
+      return $ B.divWith (ident,["cell","markdown"],kvs)
+             $ B.fromList bs
+    Ipynb.Raw -> do
+      -- we use ipynb to indicate no format given (a wildcard in nbformat)
+      let format = fromMaybe "ipynb" $ lookup "raw_mimetype" kvs <|> lookup "format" kvs
+      let format' =
+            case format of
+              "text/html"             -> "html"
+              "slides"                -> "html"
+              "text/latex"            -> "latex"
+              "application/pdf"       -> "latex"
+              "pdf"                   -> "latex"
+              "text/markdown"         -> "markdown"
+              "text/x-rst"            -> "rst"
+              "text/restructuredtext" -> "rst"
+              "text/asciidoc"         -> "asciidoc"
+              _                       -> format
+      return $ B.divWith (ident,["cell","raw"],kvs)
+             $ B.rawBlock format' source
+    Ipynb.Code{ codeOutputs = outputs, codeExecutionCount = ec } -> do
+      outputBlocks <- mconcat <$> mapM outputToBlock outputs
+      let kvs' = maybe kvs (\x -> ("execution_count", tshow x):kvs) ec
+      return $ B.divWith (ident,["cell","code"],kvs') $
+        B.codeBlockWith ("",[lang],[]) source
+        <> outputBlocks
+
+-- Remove attachment: prefix from images...
+fixImage :: Maybe Text -> Inline -> Inline
+fixImage mbident (Image attr lab (src,tit))
+  | "attachment:" `T.isPrefixOf` src =
+     let src' = T.drop 11 src
+         qualifiedSrc = maybe src' (<> ("-" <> src')) mbident
+      in Image attr lab (qualifiedSrc, tit)
+fixImage _ x = x
+
+addAttachment :: PandocMonad m => Maybe Text -> (Text, MimeBundle) -> m ()
+addAttachment mbident (fname, mimeBundle) = do
+  let fp = T.unpack $ maybe fname (<> ("-" <> fname)) mbident
+  case M.toList (unMimeBundle mimeBundle) of
+    (mimeType, BinaryData bs):_ ->
+      insertMedia fp (Just mimeType) (BL.fromStrict bs)
+    (mimeType, TextualData t):_ ->
+      insertMedia fp (Just mimeType)
+          (BL.fromStrict $ TE.encodeUtf8 t)
+    (mimeType, JsonData v):_ ->
+      insertMedia fp (Just mimeType) (encode v)
+    [] -> report $ CouldNotFetchResource fname "no attachment"
+
+outputToBlock :: PandocMonad m => Output a -> m B.Blocks
+outputToBlock Stream{ streamName = sName,
+                      streamText = Source text } =
+  return $ B.divWith ("",["output","stream",sName],[])
+         $ B.codeBlock $ T.concat text
+outputToBlock DisplayData{ displayData = data',
+                            displayMetadata = metadata' } =
+  B.divWith ("",["output", "display_data"],[]) <$>
+    handleData metadata' data'
+outputToBlock ExecuteResult{ executeCount = ec,
+                              executeData = data',
+                              executeMetadata = metadata' } =
+  B.divWith ("",["output", "execute_result"],[("execution_count",tshow ec)])
+    <$> handleData metadata' data'
+outputToBlock Err{ errName = ename,
+                   errValue = evalue,
+                   errTraceback = traceback } =
+  return $ B.divWith ("",["output","error"],
+                         [("ename",ename),
+                          ("evalue",evalue)])
+         $ B.codeBlock $ T.unlines traceback
+
+-- We want to display the richest output possible given
+-- the output format.
+handleData :: PandocMonad m
+           => JSONMeta -> MimeBundle -> m B.Blocks
+handleData (JSONMeta metadata) (MimeBundle mb) =
+  mconcat <$> mapM dataBlock (M.toList mb)
+
+  where
+
+    dataBlock :: PandocMonad m => (MimeType, MimeData) -> m B.Blocks
+    dataBlock (mt, d)
+     | "image/" `T.isPrefixOf` mt || mt == "application/pdf"
+      = do
+      -- normally metadata maps from mime types to key-value map;
+      -- but not always...
+      let meta = case M.lookup mt metadata of
+                   Just v@Object{} ->
+                     case fromJSON v of
+                       Success m' -> m'
+                       Error _   -> mempty
+                   _ -> mempty
+      let metaPairs = jsonMetaToPairs meta
+      let bs = case d of
+                 BinaryData bs' -> bs'
+                 TextualData t  -> UTF8.fromText t
+                 JsonData v     -> BL.toStrict $ encode v
+      -- SHA1 hash for filename
+      let fname = T.pack (show (hashWith SHA1 bs)) <>
+            case extensionFromMimeType mt of
+              Nothing  -> ""
+              Just ext -> "." <> ext
+      insertMedia (T.unpack fname) (Just mt) (BL.fromStrict bs)
+      return $ B.para $ B.imageWith ("",[],metaPairs) fname "" mempty
+
+    dataBlock ("text/html", TextualData t)
+      = return $ B.rawBlock "html" t
+
+    dataBlock ("text/latex", TextualData t)
+      = return $ B.rawBlock "latex" t
+
+    dataBlock ("text/markdown", TextualData t)
+      = return $ B.rawBlock "markdown" t
+
+    dataBlock ("text/plain", TextualData t) =
+      return $ B.codeBlock t
+
+    dataBlock (_, JsonData v) =
+      return $ B.codeBlockWith ("",["json"],[]) $ T.pack $ toStringLazy $ encode v
+
+    dataBlock _ = return mempty
+
+jsonMetaToMeta :: JSONMeta -> M.Map Text MetaValue
+jsonMetaToMeta (JSONMeta m) = M.map valueToMetaValue m
+  where
+    valueToMetaValue :: Value -> MetaValue
+    valueToMetaValue x@Object{} =
+      case fromJSON x of
+        Error s -> MetaString $ T.pack s
+        Success jm' -> MetaMap $ jsonMetaToMeta jm'
+    valueToMetaValue x@Array{} =
+      case fromJSON x of
+        Error s -> MetaString $ T.pack s
+        Success xs -> MetaList $ map valueToMetaValue xs
+    valueToMetaValue (Bool b) = MetaBool b
+    valueToMetaValue (String t) = MetaString t
+    valueToMetaValue (Number n)
+      | Scientific.isInteger n = MetaString (tshow (floor n :: Integer))
+      | otherwise              = MetaString (tshow n)
+    valueToMetaValue Aeson.Null = MetaString ""
+
+jsonMetaToPairs :: JSONMeta -> [(Text, Text)]
+jsonMetaToPairs (JSONMeta m) = M.toList . M.map
+  (\case
+      String t
+        | not (T.all isDigit t)
+        , t /= "true"
+        , t /= "false"
+                 -> t
+      x          -> T.pack $ UTF8.toStringLazy $ Aeson.encode x) $ m
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,23 +1,45 @@
-{-# LANGUAGE ExplicitForAll, TupleSections #-}
+{-# LANGUAGE ScopedTypeVariables #-}
+{-# LANGUAGE TupleSections #-}
+{-# LANGUAGE OverloadedStrings #-}
+{- |
+   Module      : Text.Pandoc.Readers.JATS
+   Copyright   : Copyright (C) 2017-2020 Hamish Mackenzie
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : John MacFarlane <jgm@berkeley.edu>
+   Stability   : alpha
+   Portability : portable
+
+Conversion of JATS XML to 'Pandoc' document.
+-}
+
 module Text.Pandoc.Readers.JATS ( readJATS ) where
-import Control.Monad.State.Strict
-import Data.Char (isDigit, isSpace, toUpper)
+import Control.Monad.State.Strict ( StateT(runStateT), gets, modify )
+import Control.Monad (forM_,  when, unless)
+import Control.Monad.Except (throwError)
+import Text.Pandoc.Error (PandocError(..))
+import Data.Char (isDigit, isSpace)
 import Data.Default
 import Data.Generics
-import Data.List (intersperse)
+import qualified Data.List as L
 import qualified Data.Map as Map
-import Data.Maybe (maybeToList, fromMaybe)
+import Data.Maybe (maybeToList, fromMaybe, catMaybes)
 import Data.Text (Text)
 import qualified Data.Text as T
-import Text.HTML.TagSoup.Entity (lookupEntity)
+import qualified Data.Text.Lazy as TL
+import Text.Pandoc.XML (lookupEntity)
 import Text.Pandoc.Builder
-import Text.Pandoc.Class (PandocMonad)
+import Text.Pandoc.Class.PandocMonad (PandocMonad)
 import Text.Pandoc.Options
-import Text.Pandoc.Shared (underlineSpan, crFilter, safeRead)
+import Text.Pandoc.Shared (safeRead)
+import Text.Pandoc.Walk (walk)
+import Text.Pandoc.XML.Light
 import Text.TeXMath (readMathML, writeTeX)
-import Text.XML.Light
 import qualified Data.Set as S (fromList, member)
 import Data.Set ((\\))
+import Text.Pandoc.Sources (ToSources(..), sourcesToText)
+import Safe (headMay)
+import Text.Printf (printf)
 
 type JATS m = StateT JATSState m
 
@@ -25,8 +47,9 @@
                           , jatsQuoteType    :: QuoteType
                           , jatsMeta         :: Meta
                           , jatsBook         :: Bool
-                          , jatsFigureTitle  :: Inlines
+                          , jatsFootnotes    :: Map.Map Text Blocks
                           , jatsContent      :: [Content]
+                          , jatsInFigure     :: Bool
                           } deriving Show
 
 instance Default JATSState where
@@ -34,51 +57,48 @@
                  , jatsQuoteType = DoubleQuote
                  , jatsMeta = mempty
                  , jatsBook = False
-                 , jatsFigureTitle = mempty
-                 , jatsContent = [] }
+                 , jatsFootnotes = mempty
+                 , jatsContent = []
+                 , jatsInFigure = False }
 
 
-readJATS :: PandocMonad m => ReaderOptions -> Text -> m Pandoc
+readJATS :: (PandocMonad m, ToSources a)
+         => ReaderOptions
+         -> a
+         -> m Pandoc
 readJATS _ inp = do
-  let tree = normalizeTree . parseXML
-               $ T.unpack $ crFilter inp
+  let sources = toSources inp
+  tree <- either (throwError . PandocXMLError "") return $
+            parseXMLContents (TL.fromStrict . sourcesToText $ sources)
   (bs, st') <- flip runStateT (def{ jatsContent = tree }) $ mapM parseBlock tree
-  return $ Pandoc (jatsMeta st') (toList . mconcat $ bs)
-
--- normalize input, consolidating adjacent Text and CRef elements
-normalizeTree :: [Content] -> [Content]
-normalizeTree = everywhere (mkT go)
-  where go :: [Content] -> [Content]
-        go (Text (CData CDataRaw _ _):xs) = xs
-        go (Text (CData CDataText s1 z):Text (CData CDataText s2 _):xs) =
-           Text (CData CDataText (s1 ++ s2) z):xs
-        go (Text (CData CDataText s1 z):CRef r:xs) =
-           Text (CData CDataText (s1 ++ convertEntity r) z):xs
-        go (CRef r:Text (CData CDataText s1 z):xs) =
-             Text (CData CDataText (convertEntity r ++ s1) z):xs
-        go (CRef r1:CRef r2:xs) =
-             Text (CData CDataText (convertEntity r1 ++ convertEntity r2) Nothing):xs
-        go xs = xs
-
-convertEntity :: String -> String
-convertEntity e = Data.Maybe.fromMaybe (map toUpper e) (lookupEntity e)
+  let footnotes = jatsFootnotes st'
+  let blockList = toList $ mconcat bs
+  let linkToFootnotes :: Inline -> Inline
+      linkToFootnotes link'@(Link _attr _txt (href, _title)) =
+        case T.uncons href of
+          Just ('#', rid) -> case Map.lookup rid footnotes of
+                               Just footnote -> Note (toList footnote)
+                               Nothing       -> link'
+          _               -> link'
+      linkToFootnotes inline = inline
+  return $ Pandoc (jatsMeta st') (walk linkToFootnotes blockList)
 
 -- convenience function to get an attribute value, defaulting to ""
-attrValue :: String -> Element -> String
+attrValue :: Text -> Element -> Text
 attrValue attr =
   fromMaybe "" . maybeAttrValue attr
 
-maybeAttrValue :: String -> Element -> Maybe String
+maybeAttrValue :: Text -> Element -> Maybe Text
 maybeAttrValue attr elt =
   lookupAttrBy (\x -> qName x == attr) (elAttribs elt)
 
 -- convenience function
-named :: String -> Element -> Bool
+named :: Text -> Element -> Bool
 named s e = qName (elName e) == s
 
 --
 
-addMeta :: PandocMonad m => ToMetaValue a => String -> a -> JATS m ()
+addMeta :: PandocMonad m => ToMetaValue a => Text -> a -> JATS m ()
 addMeta field val = modify (setMeta field val)
 
 instance HasMeta JATSState where
@@ -86,56 +106,48 @@
   deleteMeta field s = s {jatsMeta = deleteMeta field (jatsMeta s)}
 
 isBlockElement :: Content -> Bool
-isBlockElement (Elem e) = qName (elName e) `S.member` blocktags
-  where blocktags = S.fromList (paragraphLevel ++ lists ++ mathML ++ other) \\ S.fromList inlinetags
-        paragraphLevel = ["address", "array", "boxed-text", "chem-struct-wrap",
-            "code", "fig", "fig-group", "graphic", "media", "preformat",
+isBlockElement (Elem e) = case qName (elName e) of
+            "disp-formula" -> if onlyOneChild e
+                                  then if hasFormulaChild e
+                                          then False
+                                          else case filterChild (named "alternatives") e of
+                                            Just a -> if hasFormulaChild a then False else True
+                                            Nothing -> True
+                                  else True
+            "alternatives" -> if hasFormulaChild e then False else True
+            _ -> qName (elName e) `S.member` blocktags
+
+  where blocktags = S.fromList (paragraphLevel ++ lists ++ formulae ++ other) \\ S.fromList canBeInline
+        paragraphLevel = ["address", "answer", "answer-set", "array", "boxed-text", "chem-struct-wrap",
+            "code", "explanation", "fig", "fig-group", "graphic", "media", "preformat", "question", "question-wrap", "question-wrap-group",
             "supplementary-material", "table-wrap", "table-wrap-group",
             "alternatives", "disp-formula", "disp-formula-group"]
         lists = ["def-list", "list"]
-        mathML = ["tex-math", "mml:math"]
+        formulae = ["tex-math", "mml:math"]
         other = ["p", "related-article", "related-object", "ack", "disp-quote",
             "speech", "statement", "verse-group", "x"]
-        inlinetags = ["email", "ext-link", "uri", "inline-supplementary-material",
-            "related-article", "related-object", "hr", "bold", "fixed-case",
-            "italic", "monospace", "overline", "overline-start", "overline-end",
-            "roman", "sans-serif", "sc", "strike", "underline", "underline-start",
-            "underline-end", "ruby", "alternatives", "inline-graphic", "private-char",
-            "chem-struct", "inline-formula", "tex-math", "mml:math", "abbrev",
-            "milestone-end", "milestone-start", "named-content", "styled-content",
-            "fn", "target", "xref", "sub", "sup", "x", "address", "array",
-            "boxed-text", "chem-struct-wrap", "code", "fig", "fig-group", "graphic",
-            "media", "preformat", "supplementary-material", "table-wrap",
-            "table-wrap-group", "disp-formula", "disp-formula-group",
-            "citation-alternatives", "element-citation", "mixed-citation",
-            "nlm-citation", "award-id", "funding-source", "open-access",
-            "def-list", "list", "ack", "disp-quote", "speech", "statement",
-            "verse-group"]
+        canBeInline = ["tex-math", "mml:math", "related-object", "x"]
+        onlyOneChild x = length (allChildren x) == 1
+        allChildren x = filterChildren (const True) x
+
 isBlockElement _ = False
 
 -- Trim leading and trailing newline characters
-trimNl :: String -> String
-trimNl = reverse . go . reverse . go
-  where go ('\n':xs) = xs
-        go xs        = xs
+trimNl :: Text -> Text
+trimNl = T.dropAround (== '\n')
 
 -- function that is used by both graphic (in parseBlock)
 -- and inline-graphic (in parseInline)
 getGraphic :: PandocMonad m => Element -> JATS m Inlines
 getGraphic e = do
   let atVal a = attrValue a e
-      attr = (atVal "id", words $ atVal "role", [])
+  let altText = case filterElement (named "alt-text") e of
+         Just alt -> textContent alt
+         Nothing -> mempty
+      (ident, title, altText') = (atVal "id", atVal "title", text altText)
+      attr = (ident, T.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 altText'
 
 getBlocks :: PandocMonad m => Element -> JATS m Blocks
 getBlocks e =  mconcat <$>
@@ -144,42 +156,94 @@
 
 parseBlock :: PandocMonad m => Content -> JATS m Blocks
 parseBlock (Text (CData CDataRaw _ _)) = return mempty -- DOCTYPE
-parseBlock (Text (CData _ s _)) = if all isSpace s
+parseBlock (Text (CData _ s _)) = if T.all isSpace s
                                      then return mempty
                                      else return $ plain $ trimInlines $ text s
-parseBlock (CRef x) = return $ plain $ str $ map toUpper x
-parseBlock (Elem e) =
+parseBlock (CRef x) = return $ plain $ str $ T.toUpper x
+parseBlock (Elem e) = do
+  sectionLevel <- gets jatsSectionLevel
+  let parseBlockWithHeader = wrapWithHeader (sectionLevel+1) (getBlocks e)
+
   case qName (elName e) of
+        "book" -> parseBook
+        "book-part-wrapper" -> parseBook
         "p" -> parseMixed para (elContent e)
         "code" -> codeBlockWithLang
         "preformat" -> codeBlockWithLang
-        "disp-quote" -> parseBlockquote
-        "list" -> case attrValue "list-type" e of
-                    "bullet" -> bulletList <$> listitems
-                    listType -> do
-                      let start = fromMaybe 1 $
-                                  (strContent <$> (filterElement (named "list-item") e
-                                               >>= filterElement (named "lable")))
-                                   >>= safeRead
-                      orderedListWith (start, parseListStyleType listType, DefaultDelim)
-                        <$> listitems
-        "def-list" -> definitionList <$> deflistitems
-        "sec" -> gets jatsSectionLevel >>= sect . (+1)
+        "disp-quote" -> wrapWithHeader (sectionLevel+1) parseBlockquote
+        "list" ->  wrapWithHeader (sectionLevel+1) parseList
+        "def-list" -> wrapWithHeader (sectionLevel+1) (definitionList <$> deflistitems)
+        "sec" -> parseBlockWithHeader
+        "abstract" -> parseBlockWithHeader
+        "ack" -> parseBlockWithHeader
+        "answer" -> parseBlockWithHeader
+        "answer-set" -> parseBlockWithHeader
+        "app" -> parseBlockWithHeader
+        "app-group" -> parseBlockWithHeader
+        "author-comment" -> parseBlockWithHeader
+        "author-notes" -> parseBlockWithHeader
+        "back" -> parseBlockWithHeader
+        "bio" -> parseBlockWithHeader
+        "explanation" -> parseBlockWithHeader
+        "glossary" -> parseBlockWithHeader
+        "kwd-group" -> parseBlockWithHeader
+        "list-item" -> parseBlockWithHeader
+        "notes" -> parseBlockWithHeader
+        "option" -> parseBlockWithHeader
+        "question" -> parseBlockWithHeader
+        "question-preamble" -> parseBlockWithHeader
+        "question-wrap-group" -> parseBlockWithHeader
+        "statement" -> parseBlockWithHeader
+        "supplement" -> parseBlockWithHeader
+        "table-wrap-foot" -> parseBlockWithHeader
+        "trans-abstract" -> parseBlockWithHeader
+        "verse-group" -> parseBlockWithHeader
         "graphic" -> para <$> getGraphic e
         "journal-meta" -> parseMetadata e
         "article-meta" -> parseMetadata e
         "custom-meta" -> parseMetadata e
+        "processing-meta" -> return mempty
+        "book-meta" -> parseMetadata e
         "title" -> return mempty -- processed by header
+        "label" -> 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
-        "caption" -> divWith (attrValue "id" e, ["caption"], []) <$> sect 6
+        "fig" -> parseFigure
+        "fig-group" -> divWith (attrValue "id" e, ["fig-group"], [])
+                          <$> getBlocks e
+        "table-wrap" -> divWith (attrValue "id" e, ["table-wrap"], [])
+                          <$> getBlocks e
+        "caption" -> do
+          inFigure <- gets jatsInFigure
+          if inFigure -- handled by parseFigure
+             then return mempty
+             else divWith (attrValue "id" e, ["caption"], []) <$> wrapWithHeader 6 (getBlocks e)
+        "fn-group" -> parseFootnoteGroup
         "ref-list" -> parseRefList e
+        "alternatives" -> if hasFormulaChild e
+                            then blockFormula displayMath e
+                            else getBlocks e
+        "disp-formula" -> if hasFormulaChild e
+                            then blockFormula displayMath e
+                            else divWith (attrValue "id" e, ["disp-formula"], [])
+                                    <$> getBlocks e
+        "index" -> parseBlockWithHeader
+        "index-div" -> parseBlockWithHeader
+        "index-group" -> parseBlockWithHeader
+        "index-title-group" -> return mempty -- handled by index and index-div
+        "toc" -> parseBlockWithHeader
+        "toc-div" -> parseBlockWithHeader
+        "toc-entry" -> parseBlockWithHeader
+        "toc-group" -> parseBlockWithHeader
+        "toc-title-group" -> return mempty -- handled by toc
+        "legend" -> parseBlockWithHeader
+        "dedication" -> parseBlockWithHeader
+        "foreword" -> parseBlockWithHeader
+        "preface" -> parseBlockWithHeader
         "?xml"  -> return mempty
         _       -> getBlocks e
    where parseMixed container conts = do
            let (ils,rest) = break isBlockElement conts
-           ils' <- (trimInlines . mconcat) <$> mapM parseInline ils
+           ils' <- trimInlines . mconcat <$> mapM parseInline ils
            let p = if ils' == mempty then mempty else container ils'
            case rest of
                  []     -> return p
@@ -194,13 +258,25 @@
            return $ codeBlockWith (attrValue "id" e, classes', [])
                   $ trimNl $ strContentRecursive e
          parseBlockquote = do
-            attrib <- case filterChild (named "attribution") e of
+            attrib <- case filterChild (named "attrib") e of
                              Nothing  -> return mempty
-                             Just z   -> (para . (str "— " <>) . mconcat)
+                             Just z   -> para . (str "— " <>) . mconcat
                                          <$>
                                               mapM parseInline (elContent z)
             contents <- getBlocks e
             return $ blockQuote (contents <> attrib)
+         parseList = do
+            case attrValue "list-type" e of
+              "bullet" -> bulletList <$> listitems
+              listType -> do
+                let start =
+                      fromMaybe 1 $
+                        ( filterElement (named "list-item") e
+                            >>= filterElement (named "label")
+                        )
+                          >>= safeRead . textContent
+                orderedListWith (start, parseListStyleType listType, DefaultDelim)
+                  <$> listitems
          parseListStyleType "roman-lower" = LowerRoman
          parseListStyleType "roman-upper" = UpperRoman
          parseListStyleType "alpha-lower" = LowerAlpha
@@ -214,85 +290,147 @@
                      let items = filterChildren (named "def") e'
                      terms' <- mapM getInlines terms
                      items' <- mapM getBlocks items
-                     return (mconcat $ intersperse (str "; ") terms', items')
+                     return (mconcat $ L.intersperse (str "; ") terms', items')
+         parseFigure = do
+           modify $ \st -> st{ jatsInFigure = True }
+           capt <- case filterChild (named "caption") e of
+                     Just t  -> mconcat . L.intersperse linebreak <$>
+                                mapM getInlines (filterChildren (const True) t)
+                     Nothing -> return mempty
+           contents <- getBlocks e
+           modify $ \st -> st{ jatsInFigure = False }
+           return $ figureWith
+             (attrValue "id" e, [], [])
+             (simpleCaption $ plain capt)
+             contents
+         parseFootnoteGroup = do
+           forM_ (filterChildren (named "fn") e) $ \fn -> do
+             let id' = attrValue "id" fn
+             contents <- getBlocks fn
+             modify $ \st ->
+               st { jatsFootnotes = Map.insert id' contents (jatsFootnotes st) }
+           return mempty
+
          parseTable = do
                       let isCaption x = named "title" x || named "caption" x
-                      caption <- case filterChild isCaption e of
-                                       Just t  -> getInlines t
-                                       Nothing -> return mempty
+                      capt <- case filterChild isCaption e of
+                                    Just t  -> getInlines t
+                                    Nothing -> return mempty
                       let e' = fromMaybe e $ filterChild (named "tgroup") e
                       let isColspec x = named "colspec" x || named "col" x
                       let colspecs = case filterChild (named "colgroup") e' of
                                            Just c -> filterChildren isColspec c
                                            _      -> filterChildren isColspec e'
                       let isRow x = named "row" x || named "tr" x
-                      headrows <- case filterChild (named "thead") e' of
-                                       Just h  -> case filterChild isRow h of
-                                                       Just x  -> parseRow x
-                                                       Nothing -> return []
-                                       Nothing -> return []
-                      bodyrows <- case filterChild (named "tbody") e' of
-                                       Just b  -> mapM parseRow
-                                                  $ filterChildren isRow b
-                                       Nothing -> mapM parseRow
-                                                  $ filterChildren isRow e'
+
+                      let parseRows elementWithRows =
+                            map parseElement $ filterChildren isRow elementWithRows
+
+                      -- list of list of body cell elements
+                      let multipleBodyRowElements =
+                            map parseRows $ filterChildren (named "tbody") e'
+
+                      -- list of list header cell elements
+                      let headRowElements = maybe [] parseRows (filterChild (named "thead") e')
+
+                      -- list of foot cell elements
+                      let footRowElements = maybe [] parseRows (filterChild (named "tfoot") e')
+
                       let toAlignment c = case findAttr (unqual "align") c of
                                                 Just "left"   -> AlignLeft
                                                 Just "right"  -> AlignRight
                                                 Just "center" -> AlignCenter
                                                 _             -> AlignDefault
-                      let toWidth c = case findAttr (unqual "colwidth") c of
-                                                Just w -> fromMaybe 0
-                                                   $ safeRead $ '0': filter (\x ->
-                                                     isDigit x || x == '.') w
-                                                Nothing -> 0 :: Double
-                      let numrows = case bodyrows of
-                                         [] -> 0
-                                         xs -> maximum $ map length xs
+                      let toColSpan element = fromMaybe 1 $
+                            findAttr (unqual "colspan") element >>= safeRead
+                      let toRowSpan element =  fromMaybe 1 $
+                            findAttr (unqual "rowspan") element >>= safeRead
+                      let toWidth c = do
+                            w <- findAttr (unqual "colwidth") c
+                            n <- safeRead $ "0" <> T.filter (\x -> isDigit x || x == '.') w
+                            if n > 0 then Just n else Nothing
+                      let firstBody = fromMaybe [] (headMay multipleBodyRowElements)
+                      let numrows = L.foldl' max 0 $ map length firstBody
                       let aligns = case colspecs of
                                      [] -> replicate numrows AlignDefault
                                      cs -> map toAlignment cs
                       let widths = case colspecs of
-                                     []  -> replicate numrows 0
-                                     cs  -> let ws = map toWidth cs
-                                                tot = sum ws
-                                            in  if all (> 0) ws
-                                                   then map (/ tot) ws
-                                                   else replicate numrows 0
-                      let headrows' = if null headrows
-                                         then replicate numrows mempty
-                                         else headrows
-                      return $ table caption (zip aligns widths)
-                                 headrows' bodyrows
+                                     [] -> replicate numrows ColWidthDefault
+                                     cs -> let ws = map toWidth cs
+                                           in case sequence ws of
+                                                Just ws' -> let tot = sum ws'
+                                                            in  ColWidth . (/ tot) <$> ws'
+                                                Nothing  -> replicate numrows ColWidthDefault
+                      let parseCell = parseMixed plain . elContent
+                      let elementToCell element = cell
+                            (toAlignment element)
+                            (RowSpan $ toRowSpan element)
+                            (ColSpan $ toColSpan element)
+                            <$> (parseCell element)
+                      let rowElementsToCells elements = mapM elementToCell elements
+                      let toRow = fmap (Row nullAttr) . rowElementsToCells
+                          toRows elements = mapM toRow elements
+
+                      headerRows <- toRows headRowElements
+                      footerRows <- toRows footRowElements
+                      bodyRows <- mapM toRows multipleBodyRowElements
+
+                      return $ table (simpleCaption $ plain capt)
+                                     (zip aligns widths)
+                                     (TableHead nullAttr headerRows)
+                                     (map (TableBody nullAttr 0 []) bodyRows)
+                                     (TableFoot nullAttr footerRows)
          isEntry x  = named "entry" x || named "td" x || named "th" x
-         parseRow = mapM (parseMixed plain . elContent) . filterChildren isEntry
-         sect n = do isbook <- gets jatsBook
-                     let n' = if isbook || n == 0 then n + 1 else n
-                     headerText <- case filterChild (named "title") e `mplus`
-                                        (filterChild (named "info") e >>=
-                                            filterChild (named "title")) of
-                                      Just t  -> getInlines t
-                                      Nothing -> return mempty
-                     oldN <- gets jatsSectionLevel
-                     modify $ \st -> st{ jatsSectionLevel = n }
-                     b <- getBlocks e
-                     let ident = attrValue "id" e
-                     modify $ \st -> st{ jatsSectionLevel = oldN }
-                     return $ headerWith (ident,[],[]) n' headerText <> b
+         parseElement = filterChildren isEntry
+         wrapWithHeader n mBlocks = do
+                      isBook <- gets jatsBook
+                      let n' = case (filterChild (named "title") e >>= maybeAttrValue "display-as") of
+                                  Just t -> read $ T.unpack t
+                                  Nothing -> if isBook || n == 0 then n + 1 else n
+                      headerText <- case filterChild (named "title") e of
+                                       Just t  -> case maybeAttrValue "suppress" t of
+                                                     Just s -> if s == "no"
+                                                                 then getInlines t
+                                                                 else return mempty
+                                                     Nothing -> getInlines t
+                                       Nothing -> do
+                                           let name = qName (elName e)
+                                           if (name == "dedication" || name == "foreword" || name == "preface")
+                                             then return $ str $ T.toTitle name
+                                             else case filterChild (named "index-title-group") e >>= filterChild (named "title") of
+                                                     Just i -> getInlines i
+                                                     Nothing -> case filterChild (named "toc-title-group") e >>= filterChild (named "title") of
+                                                                   Just t -> getInlines t
+                                                                   Nothing -> return mempty
+                      oldN <- gets jatsSectionLevel
+                      modify $ \st -> st{ jatsSectionLevel = n }
+                      blocks <- mBlocks
+                      let ident = attrValue "id" e
+                      modify $ \st -> st{ jatsSectionLevel = oldN }
+                      return $ (if headerText == mempty
+                                  then mempty
+                                  else headerWith (ident,[],[]) n' headerText) <> blocks
+         parseBook = do
+           modify $ \st -> st{ jatsBook = True }
+           getBlocks e
 
 getInlines :: PandocMonad m => Element -> JATS m Inlines
-getInlines e' = (trimInlines . mconcat) <$>
+getInlines e' = trimInlines . mconcat <$>
                  mapM parseInline (elContent e')
 
 parseMetadata :: PandocMonad m => Element -> JATS m Blocks
 parseMetadata e = do
-  getTitle e
-  getAuthors e
+  isBook <- gets jatsBook
+  if isBook then getBookTitle e else getArticleTitle e
+  if isBook then getBookAuthors e else getArticleAuthors e
   getAffiliations e
+  getAbstract e
+  getPubDate e
+  getPermissions e
   return mempty
 
-getTitle :: PandocMonad m => Element -> JATS m ()
-getTitle e = do
+getArticleTitle :: PandocMonad m => Element -> JATS m ()
+getArticleTitle e = do
   tit <-  case filterElement (named "article-title") e of
                Just s  -> getInlines s
                Nothing -> return mempty
@@ -303,8 +441,21 @@
   when (tit /= mempty) $ addMeta "title" tit
   when (subtit /= mempty) $ addMeta "subtitle" subtit
 
-getAuthors :: PandocMonad m => Element -> JATS m ()
-getAuthors e = do
+
+getBookTitle :: PandocMonad m => Element -> JATS m ()
+getBookTitle e = do
+  tit <-  case (filterElement (named "book-title-group") e >>= filterElement (named "book-title")) of
+               Just s  -> getInlines s
+               Nothing -> return mempty
+  subtit <-  case (filterElement (named "book-title-group") e >>= filterElement (named "subtitle")) of
+               Just s  -> (text ": " <>) <$>
+                           getInlines s
+               Nothing -> return mempty
+  when (tit /= mempty) $ addMeta "title" tit
+  when (subtit /= mempty) $ addMeta "subtitle" subtit
+
+getArticleAuthors :: PandocMonad m => Element -> JATS m ()
+getArticleAuthors e = do
   authors <- mapM getContrib $ filterElements
               (\x -> named "contrib" x &&
                      attrValue "contrib-type" x == "author") e
@@ -315,11 +466,97 @@
                    (a:as, ns) -> reverse as ++ [a <> mconcat ns]
   unless (null authors) $ addMeta "author" authors'
 
+getBookAuthors :: PandocMonad m => Element -> JATS m ()
+getBookAuthors e = do
+  authors <- mapM getContrib $ filterElements (\x -> named "contrib-group" x) e
+              >>= filterElements (\x -> named "contrib" x &&
+                     attrValue "contrib-type" x == "author")
+  authorNotes <- mapM getInlines $ filterElements (named "author-notes") e
+  let authors' = case (reverse authors, authorNotes) of
+                   ([], _)    -> []
+                   (_, [])    -> authors
+                   (a:as, ns) -> reverse as ++ [a <> mconcat ns]
+  unless (null authors) $ addMeta "author" authors'
+
 getAffiliations :: PandocMonad m => Element -> JATS m ()
 getAffiliations x = do
   affs <- mapM getInlines $ filterChildren (named "aff") x
   unless (null affs) $ addMeta "institute" affs
 
+getAbstract :: PandocMonad m => Element -> JATS m ()
+getAbstract e =
+  case filterElement (named "abstract") e of
+    Just s -> do
+      blks <- getBlocks s
+      addMeta "abstract" blks
+    Nothing -> pure ()
+
+getPubDate :: PandocMonad m => Element -> JATS m ()
+getPubDate e =
+  case filterElement (named "pub-date") e of
+    Just d -> getDate d >>= addMeta "date" . text
+    Nothing -> pure ()
+
+-- extract a structured date and create an ISO-8901 string date from it
+getDate :: PandocMonad m => Element -> JATS m Text
+getDate e =
+  case maybeAttrValue "iso-8601-date" e of
+    Just isod -> pure isod
+    Nothing -> do
+      let extractDate :: Element -> Maybe Int
+          extractDate = safeRead . strContent
+      let yr = filterElement (named "year") e >>= extractDate
+      let mon = filterElement (named "month") e >>= extractDate
+      let day = filterElement (named "day") e >>= extractDate
+      let stringDate = strContent <$> filterElement (named "string-date") e
+      pure $
+        case (yr, mon, day) of
+          (Just y, Just m, Just d) -> T.pack $ printf "%04d-%02d-%02d" y m d
+          (Just y, Just m, Nothing) -> T.pack $ printf "%04d-%02d" y m
+          (Just y, Nothing, Nothing) -> T.pack $ printf "%04d" y
+          _ -> fromMaybe mempty stringDate
+
+getPermissions :: PandocMonad m => Element -> JATS m ()
+getPermissions e = do
+  copyright <- getCopyright e
+  license <-  case filterElement (named "license") e of
+               Just s  -> getLicense s
+               Nothing -> return mempty
+  when (copyright /= mempty) $ addMeta "copyright" copyright
+  when (license /= mempty) $ addMeta "license" license
+
+getCopyright :: PandocMonad m => Element -> JATS m (Map.Map Text MetaValue)
+getCopyright e = do
+  let holder = metaElement e "copyright-holder" "holder"
+  let statement = metaElement e "copyright-statement" "statement"
+  let year = metaElement e "copyright-year" "year"
+  return $ Map.fromList (catMaybes $ [holder, statement, year])
+
+getLicense :: PandocMonad m => Element -> JATS m (Map.Map Text MetaValue)
+getLicense e = do
+  let licenseType = metaAttribute e "license-type" "type"
+  let licenseLink = metaElementAliRef e "link"
+  let licenseText = metaElement e "license-p" "text"
+  return $ Map.fromList (catMaybes $ [licenseType, licenseLink, licenseText])
+
+metaElement :: Element -> Text -> Text -> Maybe (Text, MetaValue)
+metaElement e child key =
+  case filterElement (named child) e of
+    Just content -> Just (key, toMetaValue $ strContent content)
+    Nothing -> Nothing
+
+metaElementAliRef :: Element -> Text -> Maybe (Text, MetaValue)
+metaElementAliRef e key =
+  case filterElement isAliLicenseRef e of
+    Just content -> Just (key, toMetaValue $ strContent content)
+    Nothing -> Nothing
+
+metaAttribute :: Element -> Text -> Text -> Maybe (Text, MetaValue)
+metaAttribute e attr key =
+  case maybeAttrValue attr e of
+    Just content -> Just (key, toMetaValue content)
+    Nothing -> Nothing
+
 getContrib :: PandocMonad m => Element -> JATS m Inlines
 getContrib x = do
   given <- maybe (return mempty) getInlines
@@ -335,72 +572,87 @@
 parseRefList :: PandocMonad m => Element -> JATS m Blocks
 parseRefList e = do
   refs <- mapM parseRef $ filterChildren (named "ref") e
+  let mbtitle = filterChild (named "title") e
+  title <- case mbtitle of
+    Nothing -> pure mempty
+    Just te -> header 1 <$> parseInline (Elem te)
   addMeta "references" refs
-  return mempty
+  return $ title <> divWith ("refs",[],[]) mempty
 
 parseRef :: PandocMonad m
-         => Element -> JATS m (Map.Map String MetaValue)
+         => Element -> JATS m (Map.Map Text MetaValue)
 parseRef e = do
-  let refId = text $ attrValue "id" e
-  let getInlineText n = maybe (return mempty) getInlines . filterChild (named n)
-  case filterChild (named "element-citation") e of
-       Just c  -> do
-         let refType = text $
-               case attrValue "publication-type" c of
-                  "journal" -> "article-journal"
-                  x -> x
-         (refTitle, refContainerTitle) <- do
-           t <- getInlineText "article-title" c
-           ct <- getInlineText "source" c
-           if t == mempty
-              then return (ct, mempty)
-              else return (t, ct)
-         refLabel <- getInlineText "label" c
-         refYear <- getInlineText "year" c
-         refVolume <- getInlineText "volume" c
-         refFirstPage <- getInlineText "fpage" c
-         refLastPage <- getInlineText "lpage" c
-         refPublisher <- getInlineText "publisher-name" c
-         refPublisherPlace <- getInlineText "publisher-loc" c
-         let refPages = refFirstPage <> (if refLastPage == mempty
-                                            then mempty
-                                            else text "\x2013" <> refLastPage)
-         let personGroups' = filterChildren (named "person-group") c
-         let getName nm = do
-               given <- maybe (return mempty) getInlines
-                         $ filterChild (named "given-names") nm
-               family <- maybe (return mempty) getInlines
-                         $ filterChild (named "surname") nm
-               return $ toMetaValue $ Map.fromList [
-                   ("given", given)
-                 , ("family", family)
-                 ]
-         personGroups <- mapM (\pg ->
-                                do names <- mapM getName
-                                            (filterChildren (named "name") pg)
-                                   return (attrValue "person-group-type" pg,
-                                           toMetaValue names))
-                         personGroups'
-         return $ Map.fromList $
-           [ ("id", toMetaValue refId)
-           , ("type", toMetaValue refType)
-           , ("title", toMetaValue refTitle)
-           , ("container-title", toMetaValue refContainerTitle)
-           , ("publisher", toMetaValue refPublisher)
-           , ("publisher-place", toMetaValue refPublisherPlace)
-           , ("title", toMetaValue refTitle)
-           , ("issued", toMetaValue
-                        $ Map.fromList [
-                            ("year", refYear)
-                          ])
-           , ("volume", toMetaValue refVolume)
-           , ("page", toMetaValue refPages)
-           , ("citation-label", toMetaValue refLabel)
-           ] ++ personGroups
-       Nothing -> return $ Map.insert "id" (toMetaValue refId) mempty
-       -- TODO handle mixed-citation
+  let combineWithDash x y = x <> text "-" <> y
+  let getName nm = do
+        given <- maybe (return mempty) getInlines
+                  $ filterChild (named "given-names") nm
+        family <- maybe (return mempty) getInlines
+                  $ filterChild (named "surname") nm
+        return $ toMetaValue $ Map.fromList [
+            ("given" :: Text, given)
+          , ("family", family)
+          ]
+  let refElement :: PandocMonad m
+                 => Element -> Element -> JATS m (Maybe (Text, MetaValue))
+      refElement c el =
+        case qName (elName el) of
+          "article-title" -> Just . ("title",) . toMetaValue <$> getInlines el
+          "source" ->
+            case filterChild (named "article-title") c of
+              Just _ -> Just . ("container-title",) . toMetaValue <$> getInlines el
+              Nothing -> Just . ("title",) . toMetaValue <$> getInlines el
+          "label" -> Just . ("citation-label",) . toMetaValue <$> getInlines el
+          "year" -> case filterChild (named "month") c of
+                      Just m -> Just . ("issued",) . toMetaValue <$>
+                                 (combineWithDash
+                                    <$> getInlines el <*> getInlines m)
+                      Nothing -> Just . ("issued",) . toMetaValue <$> getInlines el
+          "volume" -> Just . ("volume",) . toMetaValue <$> getInlines el
+          "issue" -> Just . ("issue",) . toMetaValue <$> getInlines el
+          "isbn" -> Just . ("ISBN",) . toMetaValue <$> getInlines el
+          "issn" -> Just . ("ISSN",) . toMetaValue <$> getInlines el
+          "uri" -> Just . ("url",) . toMetaValue <$> getInlines el
+          "fpage" ->
+            case filterChild (named "lpage") c of
+              Just lp -> Just . ("page",) . toMetaValue <$>
+                          (combineWithDash <$> getInlines el <*> getInlines lp)
+              Nothing -> Just . ("page-first",) . toMetaValue <$> getInlines el
+          "publisher-name" -> Just . ("publisher",) . toMetaValue <$> getInlines el
+          "publisher-loc" -> Just . ("publisher-place",) . toMetaValue
+                                <$> getInlines el
+          "edition" -> pure $ Just ("edition",
+                               toMetaValue . T.filter isDigit $ strContent el)
+          "person-group" -> do names <- mapM getName
+                                            (filterChildren (named "name") el)
+                               pure $ Just (attrValue "person-group-type" el,
+                                            toMetaValue names)
+          "pub-id" -> case attrValue "pub-id-type" el of
+                         "doi"  -> pure $ Just ("DOI",  toMetaValue $ strContent el)
+                         "pmid" -> pure $ Just ("PMID", toMetaValue $ strContent el)
+                         _      -> pure Nothing
+          "object-id" -> case attrValue "pub-id-type" el of
+                         "doi"  -> pure $ Just ("DOI",  toMetaValue $ strContent el)
+                         "pmid" -> pure $ Just ("PMID", toMetaValue $ strContent el)
+                         _      -> pure Nothing
 
-strContentRecursive :: Element -> String
+
+          _ -> pure Nothing
+  refVariables <-
+    case filterChild (named "element-citation") e of
+      Just c -> (("type", toMetaValue $ case attrValue "publication-type" c of
+                            "journal" -> "article-journal"
+                            x -> x) :) .
+                  catMaybes <$> mapM (refElement c) (elChildren c)
+      Nothing -> pure []   -- TODO handle mixed-citation
+  -- allows round-tripping, since JATS writer puts ref- in front of citation ids:
+  let stripPref t = fromMaybe t $ T.stripPrefix "ref-" t
+  return $ Map.fromList (("id", toMetaValue $ stripPref $ attrValue "id" e)
+                        : refVariables)
+
+textContent :: Element -> Text
+textContent = strContent
+
+strContentRecursive :: Element -> Text
 strContentRecursive = strContent .
   (\e' -> e'{ elContent = map elementToStr $ elContent e' })
 
@@ -410,18 +662,18 @@
 
 parseInline :: PandocMonad m => Content -> JATS m Inlines
 parseInline (Text (CData _ s _)) = return $ text s
-parseInline (CRef ref) =
-  return $ maybe (text $ map toUpper ref) text $ lookupEntity ref
+parseInline (CRef ref) = return $ maybe (text $ T.toUpper ref) text
+                                $ lookupEntity ref
 parseInline (Elem e) =
   case qName (elName e) of
-        "italic" -> emph <$> innerInlines
-        "bold" -> strong <$> innerInlines
-        "strike" -> strikeout <$> innerInlines
-        "sub" -> subscript <$> innerInlines
-        "sup" -> superscript <$> innerInlines
-        "underline" -> underlineSpan <$> innerInlines
+        "italic" -> innerInlines emph
+        "bold" -> innerInlines strong
+        "strike" -> innerInlines strikeout
+        "sub" -> innerInlines subscript
+        "sup" -> innerInlines superscript
+        "underline" -> innerInlines underline
         "break" -> return linebreak
-        "sc" -> smallcaps <$> innerInlines
+        "sc" -> innerInlines smallcaps
 
         "code" -> codeWithLang
         "monospace" -> codeWithLang
@@ -431,67 +683,102 @@
             qt <- gets jatsQuoteType
             let qt' = if qt == SingleQuote then DoubleQuote else SingleQuote
             modify $ \st -> st{ jatsQuoteType = qt' }
-            contents <- innerInlines
+            contents <- innerInlines id
             modify $ \st -> st{ jatsQuoteType = qt }
             return $ if qt == SingleQuote
                         then singleQuoted contents
                         else doubleQuoted contents
 
         "xref" -> do
-            ils <- innerInlines
+            ils <- innerInlines id
             let rid = attrValue "rid" e
+            let rids = T.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
-                        else linkWith attr ('#' : rid) "" ils
+                        then cite
+                             (map (\id' ->
+                               let id'' = fromMaybe id' $
+                                           T.stripPrefix "ref-" id'
+                                 in Citation { citationId = id''
+                                             , citationPrefix = []
+                                             , citationSuffix = []
+                                             , citationMode = NormalCitation
+                                             , citationNoteNum = 0
+                                             , citationHash = 0}) rids)
+                             ils
+                        else linkWith attr ("#" <> rid) "" ils
         "ext-link" -> do
-             ils <- innerInlines
+             ils <- innerInlines id
              let title = fromMaybe "" $ findAttr (QName "title" (Just "http://www.w3.org/1999/xlink") Nothing) e
              let href = case findAttr (QName "href" (Just "http://www.w3.org/1999/xlink") Nothing) e of
                                Just h -> h
-                               _      -> '#' : attrValue "rid" e
+                               _      -> "#" <> attrValue "rid" e
              let ils' = if ils == mempty then str href else ils
              let attr = (attrValue "id" e, [], [])
              return $ linkWith attr href title ils'
 
-        "disp-formula" -> formula displayMath
-        "inline-formula" -> formula math
-        "math" | qPrefix (elName e) == Just "mml" -> return . math $ mathML e
-        "tex-math" -> return . math $ strContent e
+        "alternatives" -> if hasFormulaChild e
+                            then inlineFormula math e
+                            else innerInlines id
+        "disp-formula" -> inlineFormula displayMath e
+        "inline-formula" -> inlineFormula math e
+        "math" | qURI (elName e) == Just "http://www.w3.org/1998/Math/MathML"
+                   -> return . math $ mathML e
+        "tex-math" -> return . math $ textContent e
 
-        "email" -> return $ link ("mailto:" ++ strContent e) ""
-                          $ str $ strContent e
-        "uri" -> return $ link (strContent e) "" $ str $ strContent e
-        "fn" -> (note . mconcat) <$>
+        "email" -> return $ link ("mailto:" <> textContent e) ""
+                          $ str $ textContent e
+        "uri" -> return $ link (textContent e) "" $ str $ textContent e
+        "fn" -> note . mconcat <$>
                          mapM parseBlock (elContent e)
-        _          -> innerInlines
-   where innerInlines = (trimInlines . mconcat) <$>
-                          mapM parseInline (elContent e)
-         mathML x =
-            case readMathML . showElement $ everywhere (mkT removePrefix) x of
-                Left _ -> mempty
-                Right m -> writeTeX m
-         formula constructor = do
+        _          -> innerInlines id
+   where innerInlines f = f . mconcat <$> mapM parseInline (elContent e)
+         codeWithLang = do
+           let classes' = case attrValue "language" e of
+                               "" -> []
+                               l  -> [l]
+           return $ codeWith (attrValue "id" e,classes',[]) $ strContentRecursive e
+
+inlineFormula ::  PandocMonad m => (Text->Inlines) -> Element -> JATS m Inlines
+inlineFormula constructor e = do
             let whereToLook = fromMaybe e $ filterElement (named "alternatives") e
-                texMaths = map strContent $
+                texMaths = map textContent $
                             filterChildren (named  "tex-math") whereToLook
                 mathMLs = map mathML $
                             filterChildren isMathML whereToLook
             return . mconcat . take 1 . map constructor $ texMaths ++ mathMLs
 
-         isMathML x = qName   (elName x) == "math" &&
-                      qPrefix (elName x) == Just "mml"
-         removePrefix elname = elname { qPrefix = Nothing }
-         codeWithLang = do
-           let classes' = case attrValue "language" e of
-                               "" -> []
-                               l  -> [l]
-           return $ codeWith (attrValue "id" e,classes',[]) $ strContentRecursive e
+blockFormula ::  PandocMonad m => (Text->Inlines) -> Element -> JATS m Blocks
+blockFormula constructor e = do
+            let whereToLook = fromMaybe e $ filterElement (named "alternatives") e
+                texMaths = map textContent $
+                            filterChildren (named  "tex-math") whereToLook
+                mathMLs = map mathML $
+                            filterChildren isMathML whereToLook
+            case texMaths ++ mathMLs of
+              [] -> return mempty
+              (m:_) -> return $ para (constructor m)
 
+mathML :: Element -> Text
+mathML x =
+          case readMathML . showElement $ everywhere (mkT removePrefix) x of
+                Left _ -> mempty
+                Right m -> writeTeX m
+          where removePrefix elname = elname { qPrefix = Nothing }
+
+isMathML :: Element -> Bool
+isMathML x = qName (elName x) == "math" &&
+                      qURI  (elName x) ==
+                                      Just "http://www.w3.org/1998/Math/MathML"
+
+formulaChildren :: Element -> [Element]
+formulaChildren x = filterChildren isMathML x ++ filterChildren (named "tex-math") x
+
+hasFormulaChild :: Element -> Bool
+hasFormulaChild x = length (formulaChildren x) > 0
+
+isAliLicenseRef :: Element -> Bool
+isAliLicenseRef x = qName (elName x) == "license_ref" &&
+                      qURI  (elName x) ==
+                                      Just "http://www.niso.org/schemas/ali/1.0/"
diff --git a/src/Text/Pandoc/Readers/Jira.hs b/src/Text/Pandoc/Readers/Jira.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Readers/Jira.hs
@@ -0,0 +1,213 @@
+{-# LANGUAGE LambdaCase #-}
+{-# LANGUAGE OverloadedStrings #-}
+{- |
+   Module      : Text.Pandoc.Readers.Jira
+   Copyright   : © 2019-2024 Albert Krewinkel
+   License     : GPL-2.0-or-later
+
+   Maintainer  : Albert Krewinkel <albert+pandoc@tarleb.com>
+
+Conversion of jira wiki formatted plain text to 'Pandoc' document.
+-}
+module Text.Pandoc.Readers.Jira ( readJira ) where
+
+import Control.Monad.Except (throwError)
+import Data.List (partition)
+import Data.Text (Text, append, pack, singleton)
+import Text.Pandoc.XML (lookupEntity)
+import Text.Jira.Parser (parse)
+import Text.Pandoc.Class.PandocMonad (PandocMonad (..))
+import Text.Pandoc.Builder hiding (cell)
+import Text.Pandoc.Error (PandocError (PandocParseError))
+import Text.Pandoc.Options (ReaderOptions)
+import Text.Pandoc.Shared (stringify)
+import Text.Pandoc.Sources (ToSources(..), sourcesToText)
+import qualified Text.Jira.Markup as Jira
+
+-- | Read Jira wiki markup.
+readJira :: (PandocMonad m, ToSources a)
+         => ReaderOptions
+         -> a
+         -> m Pandoc
+readJira _opts inp = do
+  let sources = toSources inp
+  case parse (sourcesToText sources) of
+    Right d -> return $ jiraToPandoc d
+    Left e  -> throwError . PandocParseError $
+               "Jira parse error" `append` pack (show e)
+
+jiraToPandoc :: Jira.Doc -> Pandoc
+jiraToPandoc (Jira.Doc blks) = doc $ foldMap jiraToPandocBlocks blks
+
+--
+-- Blocks
+--
+
+-- | Converts a Jira block to a Pandoc block.
+jiraToPandocBlocks :: Jira.Block -> Blocks
+jiraToPandocBlocks = \case
+  Jira.BlockQuote blcks -> blockQuote $ foldMap jiraToPandocBlocks blcks
+  Jira.Code lang ps txt -> toPandocCodeBlocks (Just lang) ps txt
+  Jira.Color c blcks    -> divWith (mempty, mempty, [("color", colorName c)]) $
+                           foldMap jiraToPandocBlocks blcks
+  Jira.Header lvl inlns -> header lvl $ foldMap jiraToPandocInlines inlns
+  Jira.HorizontalRule   -> horizontalRule
+  Jira.List style items -> toPandocList style items
+  Jira.NoFormat ps txt  -> toPandocCodeBlocks Nothing ps txt
+  Jira.Panel ps blcks   -> toPandocDiv ps blcks
+  Jira.Para inlns       -> para $ foldMap jiraToPandocInlines inlns
+  Jira.Table rows       -> toPandocTable rows
+
+-- | Create a pandoc list – either to a @'BulletList'@ or an @'OrderedList'@.
+toPandocList :: Jira.ListStyle -> [[Jira.Block]] -> Blocks
+toPandocList style items =
+  let items' = map (foldMap jiraToPandocBlocks) items
+  in if style == Jira.Enumeration
+     then orderedList items'
+     else bulletList items'
+
+-- | Create a pandoc @'CodeBlock'@
+toPandocCodeBlocks :: Maybe Jira.Language -> [Jira.Parameter] -> Text -> Blocks
+toPandocCodeBlocks langMay params txt =
+  let classes = case langMay of
+                  Just (Jira.Language lang) -> [lang]
+                  Nothing                   -> []
+  in codeBlockWith ("", classes, map paramToPair params) txt
+
+-- | Create a pandoc @'Div'@ from a panel.
+toPandocDiv :: [Jira.Parameter] -> [Jira.Block] -> Blocks
+toPandocDiv params =
+  let (titles, params') = partition ((== "title") . Jira.parameterKey) params
+      addTitle = case titles of
+        [] ->
+          id
+        (title:_) -> \blks ->
+          (divWith ("", ["panelheader"], []) . plain . strong $
+           text (Jira.parameterValue title)) <> blks
+  in divWith ("", ["panel"], map paramToPair params')
+     . addTitle
+     . foldMap jiraToPandocBlocks
+
+paramToPair :: Jira.Parameter -> (Text, Text)
+paramToPair (Jira.Parameter key value) = (key, value)
+
+-- | Give textual representation of a color.
+colorName :: Jira.ColorName -> Text
+colorName (Jira.ColorName name) = name
+
+-- | Create a pandoc @'Table'@.
+-- This relies on 'simpleTable' to sanitize the table.
+toPandocTable :: [Jira.Row] -> Blocks
+toPandocTable rows =
+  let (headerRow, bodyRows) = splitIntoHeaderAndBody rows
+  in simpleTable
+       (rowToBlocksList headerRow)
+       (map rowToBlocksList bodyRows)
+
+rowToBlocksList :: Jira.Row -> [Blocks]
+rowToBlocksList (Jira.Row cells) =
+  map cellContent cells
+  where
+    cellContent cell = let content = case cell of
+                             Jira.HeaderCell x -> x
+                             Jira.BodyCell x   -> x
+                       in foldMap jiraToPandocBlocks content
+
+splitIntoHeaderAndBody :: [Jira.Row] -> (Jira.Row, [Jira.Row])
+splitIntoHeaderAndBody [] = (Jira.Row [], [])
+splitIntoHeaderAndBody rows@(first@(Jira.Row cells) : rest) =
+  let isHeaderCell Jira.HeaderCell{} = True
+      isHeaderCell Jira.BodyCell{}   = False
+  in if all isHeaderCell cells
+     then (first, rest)
+     else (Jira.Row [], rows)
+
+--
+-- Inlines
+--
+
+-- | Converts a Jira inline to a Pandoc block.
+jiraToPandocInlines :: Jira.Inline -> Inlines
+jiraToPandocInlines = \case
+  Jira.Anchor t          -> spanWith (t, [], []) mempty
+  Jira.AutoLink url      -> link (Jira.fromURL url) "" (str (Jira.fromURL url))
+  Jira.Citation ils      -> str "—" <> space <> emph (fromInlines ils)
+  Jira.ColorInline c ils -> spanWith ("", [], [("color", colorName c)]) $
+                                     fromInlines ils
+  Jira.Emoji icon        -> str . iconUnicode $ icon
+  Jira.Entity entity     -> str . fromEntity $ entity
+  Jira.Image params url  -> let (title, attr) = imgParams params
+                            in imageWith attr (Jira.fromURL url) title mempty
+  Jira.Link lt alias url -> jiraLinkToPandoc lt alias url
+  Jira.Linebreak         -> linebreak
+  Jira.Monospaced inlns  -> code . stringify . toList . fromInlines $ inlns
+  Jira.Space             -> space
+  Jira.SpecialChar c     -> str (Data.Text.singleton c)
+  Jira.Str t             -> str t
+  Jira.Styled style inlns -> fromStyle style $ fromInlines inlns
+  where
+    fromInlines  = foldMap jiraToPandocInlines
+    fromEntity e = case lookupEntity (e <> ";") of
+                     Nothing -> "&" `append` e `append` ";"
+                     Just t ->t
+
+    fromStyle = \case
+      Jira.Emphasis    -> emph
+      Jira.Insert      -> underline
+      Jira.Strikeout   -> strikeout
+      Jira.Strong      -> strong
+      Jira.Subscript   -> subscript
+      Jira.Superscript -> superscript
+
+    imgParams :: [Jira.Parameter] -> (Text, Attr)
+    imgParams = foldr addImgParam ("", ("", [], []))
+
+    addImgParam :: Jira.Parameter -> (Text, Attr) -> (Text, Attr)
+    addImgParam p (title, attr@(ident, classes, kvs)) =
+      case Jira.parameterKey p of
+        "title"     -> (Jira.parameterValue p, attr)
+        "thumbnail" -> (title, (ident, "thumbnail":classes, kvs))
+        _           -> let kv = (Jira.parameterKey p, Jira.parameterValue p)
+                       in (title, (ident, classes, kv:kvs))
+
+-- | Convert a Jira link to pandoc inlines.
+jiraLinkToPandoc :: Jira.LinkType -> [Jira.Inline] -> Jira.URL -> Inlines
+jiraLinkToPandoc linkType alias url =
+  let url' = (if linkType == Jira.User then ("~" <>) else id) $ Jira.fromURL url
+      alias' = case alias of
+                 [] -> str url'
+                 _  -> foldMap jiraToPandocInlines alias
+  in case linkType of
+    Jira.External   -> link url' "" alias'
+    Jira.Email      -> link ("mailto:" <> url') "" alias'
+    Jira.Attachment -> linkWith ("", ["attachment"], []) url' "" alias'
+    Jira.User       -> linkWith ("", ["user-account"], []) url' "" alias'
+    Jira.SmartCard  -> linkWith ("", ["smart-card"], []) url' "" alias'
+    Jira.SmartLink  -> linkWith ("", ["smart-link"], []) url' "" alias'
+
+-- | Get unicode representation of a Jira icon.
+iconUnicode :: Jira.Icon -> Text
+iconUnicode = \case
+  Jira.IconSlightlySmiling -> "🙂"
+  Jira.IconFrowning        -> "🙁"
+  Jira.IconTongue          -> "😛"
+  Jira.IconSmiling         -> "😃"
+  Jira.IconWinking         -> "😉"
+  Jira.IconThumbsUp        -> "👍"
+  Jira.IconThumbsDown      -> "👎"
+  Jira.IconInfo            -> "ℹ"
+  Jira.IconCheckmark       -> "✔"
+  Jira.IconX               -> "❌"
+  Jira.IconAttention       -> "❗"
+  Jira.IconPlus            -> "➕"
+  Jira.IconMinus           -> "➖"
+  Jira.IconQuestionmark    -> "❓"
+  Jira.IconOn              -> "💡"
+  Jira.IconOff             -> "🌙"
+  Jira.IconStar            -> "⭐"
+  Jira.IconStarRed         -> "⭐"
+  Jira.IconStarGreen       -> "⭐"
+  Jira.IconStarBlue        -> "⭐"
+  Jira.IconStarYellow      -> "⭐"
+  Jira.IconFlag            -> "⚑"
+  Jira.IconFlagOff         -> "⚐"
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
@@ -1,2687 +1,1423 @@
-{-# LANGUAGE FlexibleInstances     #-}
-{-# LANGUAGE MultiParamTypeClasses #-}
-{-# LANGUAGE OverloadedStrings     #-}
-{-# LANGUAGE PatternGuards         #-}
-{-# LANGUAGE ScopedTypeVariables   #-}
-{-
-Copyright (C) 2006-2017 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-2017 John MacFarlane
-   License     : GNU GPL, version 2 or above
-
-   Maintainer  : John MacFarlane <jgm@berkeley.edu>
-   Stability   : alpha
-   Portability : portable
-
-Conversion of LaTeX to 'Pandoc' document.
-
--}
-module Text.Pandoc.Readers.LaTeX ( readLaTeX,
-                                   applyMacros,
-                                   rawLaTeXInline,
-                                   rawLaTeXBlock,
-                                   inlineCommand,
-                                   tokenize,
-                                   untokenize
-                                 ) where
-
-import Control.Applicative (many, optional, (<|>))
-import Control.Monad
-import Control.Monad.Except (throwError)
-import Control.Monad.Trans (lift)
-import Data.Char (chr, isAlphaNum, isDigit, isLetter, ord, toLower)
-import Data.Default
-import Data.List (intercalate, isPrefixOf)
-import qualified Data.Map as M
-import Data.Maybe (fromMaybe, maybeToList)
-import qualified Data.Set as Set
-import Data.Text (Text)
-import qualified Data.Text as T
-import Safe (minimumDef)
-import System.FilePath (addExtension, replaceExtension, takeExtension)
-import Text.Pandoc.BCP47 (Lang (..), renderLang)
-import Text.Pandoc.Builder
-import Text.Pandoc.Class (PandocMonad, PandocPure, getResourcePath, lookupEnv,
-                          readFileFromDirs, report, setResourcePath,
-                          setTranslations, translateTerm)
-import Text.Pandoc.Error (PandocError (PandocMacroLoop, PandocParseError, PandocParsecError))
-import Text.Pandoc.Highlighting (fromListingsLanguage, languagesByExtension)
-import Text.Pandoc.ImageSize (numUnit, showFl)
-import Text.Pandoc.Logging
-import Text.Pandoc.Options
-import Text.Pandoc.Parsing hiding (blankline, many, mathDisplay, mathInline,
-                            optional, space, spaces, withRaw, (<|>))
-import Text.Pandoc.Readers.LaTeX.Types (ExpansionPoint (..), Macro (..),
-                                        Tok (..), TokType (..))
-import Text.Pandoc.Shared
-import qualified Text.Pandoc.Translations as Translations
-import Text.Pandoc.Walk
-import Text.Parsec.Pos
-
--- for debugging:
--- import Text.Pandoc.Extensions (getDefaultExtensions)
--- import Text.Pandoc.Class (runIOorExplode, PandocIO)
--- import Debug.Trace (traceShowId)
-
--- | Parse LaTeX from string and return 'Pandoc' document.
-readLaTeX :: PandocMonad m
-          => ReaderOptions -- ^ Reader options
-          -> Text        -- ^ String to parse (assumes @'\n'@ line endings)
-          -> m Pandoc
-readLaTeX opts ltx = do
-  parsed <- runParserT parseLaTeX def{ sOptions = opts } "source"
-               (tokenize "source" (crFilter ltx))
-  case parsed of
-    Right result -> return result
-    Left e       -> throwError $ PandocParsecError (T.unpack ltx) e
-
-parseLaTeX :: PandocMonad m => LP m Pandoc
-parseLaTeX = do
-  bs <- blocks
-  eof
-  st <- getState
-  let meta = sMeta st
-  let doc' = doc bs
-  let headerLevel (Header n _ _) = [n]
-      headerLevel _              = []
-  let bottomLevel = minimumDef 1 $ query headerLevel doc'
-  let adjustHeaders m (Header n attr ils) = Header (n+m) attr ils
-      adjustHeaders _ x                   = x
-  let (Pandoc _ bs') =
-       -- handle the case where you have \part or \chapter
-       (if bottomLevel < 1
-           then walk (adjustHeaders (1 - bottomLevel))
-           else id) $
-       walk (resolveRefs (sLabels st)) doc'
-  return $ Pandoc meta bs'
-
-resolveRefs :: M.Map String [Inline] -> Inline -> Inline
-resolveRefs labels x@(Link (ident,classes,kvs) _ _) =
-  case (lookup "reference-type" kvs,
-        lookup "reference" kvs) of
-        (Just "ref", Just lab) ->
-          case M.lookup lab labels of
-               Just txt -> Link (ident,classes,kvs) txt ('#':lab, "")
-               Nothing  -> x
-        _ -> x
-resolveRefs _ x = x
-
-
--- testParser :: LP PandocIO a -> Text -> IO a
--- testParser p t = do
---   res <- runIOorExplode (runParserT p defaultLaTeXState{
---             sOptions = def{ readerExtensions =
---               enableExtension Ext_raw_tex $
---                 getDefaultExtensions "latex" }} "source" (tokenize "source" t))
---   case res of
---        Left e  -> error (show e)
---        Right r -> return r
-
-newtype HeaderNum = HeaderNum [Int]
-  deriving (Show)
-
-renderHeaderNum :: HeaderNum -> String
-renderHeaderNum (HeaderNum xs) =
-  intercalate "." (map show xs)
-
-incrementHeaderNum :: Int -> HeaderNum -> HeaderNum
-incrementHeaderNum level (HeaderNum ns) = HeaderNum $
-  case reverse (take level (ns ++ repeat 0)) of
-       (x:xs) -> reverse (x+1 : xs)
-       []     -> []  -- shouldn't happen
-
-data LaTeXState = LaTeXState{ sOptions       :: ReaderOptions
-                            , sMeta          :: Meta
-                            , sQuoteContext  :: QuoteContext
-                            , sMacros        :: M.Map Text Macro
-                            , sContainers    :: [String]
-                            , sHeaders       :: M.Map Inlines String
-                            , sLogMessages   :: [LogMessage]
-                            , sIdentifiers   :: Set.Set String
-                            , sVerbatimMode  :: Bool
-                            , sCaption       :: Maybe Inlines
-                            , sInListItem    :: Bool
-                            , sInTableCell   :: Bool
-                            , sLastHeaderNum :: HeaderNum
-                            , sLabels        :: M.Map String [Inline]
-                            , sToggles       :: M.Map String Bool
-                            }
-     deriving Show
-
-defaultLaTeXState :: LaTeXState
-defaultLaTeXState = LaTeXState{ sOptions       = def
-                              , sMeta          = nullMeta
-                              , sQuoteContext  = NoQuote
-                              , sMacros        = M.empty
-                              , sContainers    = []
-                              , sHeaders       = M.empty
-                              , sLogMessages   = []
-                              , sIdentifiers   = Set.empty
-                              , sVerbatimMode  = False
-                              , sCaption       = Nothing
-                              , sInListItem    = False
-                              , sInTableCell   = False
-                              , sLastHeaderNum = HeaderNum []
-                              , sLabels        = M.empty
-                              , sToggles       = M.empty
-                              }
-
-instance PandocMonad m => HasQuoteContext LaTeXState m where
-  getQuoteContext = sQuoteContext <$> getState
-  withQuoteContext context parser = do
-    oldState <- getState
-    let oldQuoteContext = sQuoteContext oldState
-    setState oldState { sQuoteContext = context }
-    result <- parser
-    newState <- getState
-    setState newState { sQuoteContext = oldQuoteContext }
-    return result
-
-instance HasLogMessages LaTeXState where
-  addLogMessage msg st = st{ sLogMessages = msg : sLogMessages st }
-  getLogMessages st = reverse $ sLogMessages st
-
-instance HasIdentifierList LaTeXState where
-  extractIdentifierList     = sIdentifiers
-  updateIdentifierList f st = st{ sIdentifiers = f $ sIdentifiers st }
-
-instance HasIncludeFiles LaTeXState where
-  getIncludeFiles = sContainers
-  addIncludeFile f s = s{ sContainers = f : sContainers s }
-  dropLatestIncludeFile s = s { sContainers = drop 1 $ sContainers s }
-
-instance HasHeaderMap LaTeXState where
-  extractHeaderMap     = sHeaders
-  updateHeaderMap f st = st{ sHeaders = f $ sHeaders st }
-
-instance HasMacros LaTeXState where
-  extractMacros  st  = sMacros st
-  updateMacros f st  = st{ sMacros = f (sMacros st) }
-
-instance HasReaderOptions LaTeXState where
-  extractReaderOptions = sOptions
-
-instance HasMeta LaTeXState where
-  setMeta field val st =
-    st{ sMeta = setMeta field val $ sMeta st }
-  deleteMeta field st =
-    st{ sMeta = deleteMeta field $ sMeta st }
-
-instance Default LaTeXState where
-  def = defaultLaTeXState
-
-type LP m = ParserT [Tok] LaTeXState m
-
-withVerbatimMode :: PandocMonad m => LP m a -> LP m a
-withVerbatimMode parser = do
-  updateState $ \st -> st{ sVerbatimMode = True }
-  result <- parser
-  updateState $ \st -> st{ sVerbatimMode = False }
-  return result
-
-rawLaTeXParser :: (PandocMonad m, HasMacros s, HasReaderOptions s)
-               => LP m a -> ParserT String s m (a, String)
-rawLaTeXParser parser = do
-  inp <- getInput
-  let toks = tokenize "source" $ T.pack inp
-  pstate <- getState
-  let lstate = def{ sOptions = extractReaderOptions pstate
-                  , sMacros = extractMacros pstate }
-  let rawparser = (,) <$> withRaw parser <*> getState
-  res <- lift $ runParserT rawparser lstate "chunk" toks
-  case res of
-       Left _    -> mzero
-       Right ((val, raw), st) -> do
-         updateState (updateMacros (sMacros st <>))
-         rawstring <- takeP (T.length (untokenize raw))
-         return (val, rawstring)
-
-applyMacros :: (PandocMonad m, HasMacros s, HasReaderOptions s)
-            => String -> ParserT String s m String
-applyMacros s = (guardDisabled Ext_latex_macros >> return s) <|>
-   do let retokenize = doMacros 0 *>
-             (toksToString <$> many (satisfyTok (const True)))
-      pstate <- getState
-      let lstate = def{ sOptions = extractReaderOptions pstate
-                      , sMacros  = extractMacros pstate }
-      res <- runParserT retokenize lstate "math" (tokenize "math" (T.pack s))
-      case res of
-           Left e   -> fail (show e)
-           Right s' -> return s'
-
-rawLaTeXBlock :: (PandocMonad m, HasMacros s, HasReaderOptions s)
-              => ParserT String s m String
-rawLaTeXBlock = do
-  lookAhead (try (char '\\' >> letter))
-  -- we don't want to apply newly defined latex macros to their own
-  -- definitions:
-  (do (_, raw) <- rawLaTeXParser macroDef
-      (guardDisabled Ext_latex_macros >> return raw) <|> return "")
-  <|> (do (_, raw) <- rawLaTeXParser (environment <|> blockCommand)
-          applyMacros raw)
-
-rawLaTeXInline :: (PandocMonad m, HasMacros s, HasReaderOptions s)
-               => ParserT String s m String
-rawLaTeXInline = do
-  lookAhead (try (char '\\' >> letter) <|> char '$')
-  rawLaTeXParser (inlineEnvironment <|> inlineCommand') >>= applyMacros . snd
-
-inlineCommand :: PandocMonad m => ParserT String ParserState m Inlines
-inlineCommand = do
-  lookAhead (try (char '\\' >> letter) <|> char '$')
-  fst <$> rawLaTeXParser (inlineEnvironment <|> inlineCommand')
-
-tokenize :: SourceName -> Text -> [Tok]
-tokenize sourcename = totoks (initialPos sourcename)
-
-totoks :: SourcePos -> Text -> [Tok]
-totoks pos t =
-  case T.uncons t of
-       Nothing        -> []
-       Just (c, rest)
-         | c == '\n' ->
-           Tok pos Newline "\n"
-           : totoks (setSourceColumn (incSourceLine pos 1) 1) rest
-         | isSpaceOrTab c ->
-           let (sps, rest') = T.span isSpaceOrTab t
-           in  Tok pos Spaces sps
-               : totoks (incSourceColumn pos (T.length sps))
-                 rest'
-         | isAlphaNum c ->
-           let (ws, rest') = T.span isAlphaNum t
-           in  Tok pos Word ws
-               : totoks (incSourceColumn pos (T.length ws)) rest'
-         | c == '%' ->
-           let (cs, rest') = T.break (== '\n') rest
-           in  Tok pos Comment ("%" <> cs)
-               : totoks (incSourceColumn pos (1 + T.length cs)) rest'
-         | c == '\\' ->
-           case T.uncons rest of
-                Nothing -> [Tok pos (CtrlSeq " ") "\\"]
-                Just (d, rest')
-                  | isLetterOrAt d ->
-                      -- \makeatletter is common in macro defs;
-                      -- ideally we should make tokenization sensitive
-                      -- to \makeatletter and \makeatother, but this is
-                      -- probably best for now
-                      let (ws, rest'') = T.span isLetterOrAt rest
-                          (ss, rest''') = T.span isSpaceOrTab rest''
-                      in  Tok pos (CtrlSeq ws) ("\\" <> ws <> ss)
-                          : totoks (incSourceColumn pos
-                               (1 + T.length ws + T.length ss)) rest'''
-                  | isSpaceOrTab d || d == '\n' ->
-                      let (w1, r1) = T.span isSpaceOrTab rest
-                          (w2, (w3, r3)) = case T.uncons r1 of
-                                          Just ('\n', r2)
-                                                  -> (T.pack "\n",
-                                                        T.span isSpaceOrTab r2)
-                                          _ -> (mempty, (mempty, r1))
-                      in  case T.uncons r3 of
-                               Just ('\n', _) ->
-                                 Tok pos (CtrlSeq " ") ("\\" <> w1)
-                                 : totoks (incSourceColumn pos 1) r1
-                               _ ->
-                                 Tok pos (CtrlSeq " ") ("\\" <> w1 <> w2 <> w3)
-                                 : totoks (incSourceColumn pos 1) r3
-                  | otherwise  ->
-                      Tok pos (CtrlSeq (T.singleton d)) (T.pack [c,d])
-                      : totoks (incSourceColumn pos 2) rest'
-         | c == '#' ->
-           let (t1, t2) = T.span (\d -> d >= '0' && d <= '9') rest
-           in  case safeRead (T.unpack t1) of
-                    Just i ->
-                       Tok pos (Arg i) ("#" <> t1)
-                       : totoks (incSourceColumn pos (1 + T.length t1)) t2
-                    Nothing ->
-                       Tok pos Symbol ("#")
-                       : totoks (incSourceColumn pos 1) t2
-         | c == '^' ->
-           case T.uncons rest of
-                Just ('^', rest') ->
-                  case T.uncons rest' of
-                       Just (d, rest'')
-                         | isLowerHex d ->
-                           case T.uncons rest'' of
-                                Just (e, rest''') | isLowerHex e ->
-                                  Tok pos Esc2 (T.pack ['^','^',d,e])
-                                  : totoks (incSourceColumn pos 4) rest'''
-                                _ ->
-                                  Tok pos Esc1 (T.pack ['^','^',d])
-                                  : totoks (incSourceColumn pos 3) rest''
-                         | d < '\128' ->
-                                  Tok pos Esc1 (T.pack ['^','^',d])
-                                  : totoks (incSourceColumn pos 3) rest''
-                       _ -> Tok pos Symbol ("^") :
-                            Tok (incSourceColumn pos 1) Symbol ("^") :
-                            totoks (incSourceColumn pos 2) rest'
-                _ -> Tok pos Symbol ("^")
-                     : totoks (incSourceColumn pos 1) rest
-         | otherwise ->
-           Tok pos Symbol (T.singleton c) : totoks (incSourceColumn pos 1) rest
-
-isSpaceOrTab :: Char -> Bool
-isSpaceOrTab ' '  = True
-isSpaceOrTab '\t' = True
-isSpaceOrTab _    = False
-
-isLetterOrAt :: Char -> Bool
-isLetterOrAt '@' = True
-isLetterOrAt c   = isLetter c
-
-isLowerHex :: Char -> Bool
-isLowerHex x = x >= '0' && x <= '9' || x >= 'a' && x <= 'f'
-
-untokenize :: [Tok] -> Text
-untokenize = mconcat . map untoken
-
-untoken :: Tok -> Text
-untoken (Tok _ _ t) = t
-
-satisfyTok :: PandocMonad m => (Tok -> Bool) -> LP m Tok
-satisfyTok f =
-  try $ do
-    res <- tokenPrim (T.unpack . untoken) updatePos matcher
-    doMacros 0 -- apply macros on remaining input stream
-    return res
-  where matcher t | f t       = Just t
-                  | otherwise = Nothing
-        updatePos :: SourcePos -> Tok -> [Tok] -> SourcePos
-        updatePos _spos _ (Tok pos _ _ : _) = pos
-        updatePos spos _ []                 = spos
-
-doMacros :: PandocMonad m => Int -> LP m ()
-doMacros n = do
-  verbatimMode <- sVerbatimMode <$> getState
-  unless verbatimMode $ do
-    inp <- getInput
-    case inp of
-         Tok spos (CtrlSeq "begin") _ : Tok _ Symbol "{" :
-          Tok _ Word name : Tok _ Symbol "}" : ts
-            -> handleMacros spos name ts
-         Tok spos (CtrlSeq "end") _ : Tok _ Symbol "{" :
-          Tok _ Word name : Tok _ Symbol "}" : ts
-            -> handleMacros spos ("end" <> name) ts
-         Tok _ (CtrlSeq "expandafter") _ : t : ts
-            -> do setInput ts
-                  doMacros n
-                  getInput >>= setInput . combineTok t
-         Tok spos (CtrlSeq name) _ : ts
-            -> handleMacros spos name ts
-         _ -> return ()
-  where combineTok (Tok spos (CtrlSeq name) x) (Tok _ Word w : ts)
-          | T.all isLetterOrAt w =
-            Tok spos (CtrlSeq (name <> w)) (x1 <> w <> x2) : ts
-              where (x1, x2) = T.break isSpaceOrTab x
-        combineTok t ts = t:ts
-        handleMacros spos name ts = do
-                macros <- sMacros <$> getState
-                case M.lookup name macros of
-                     Nothing -> return ()
-                     Just (Macro expansionPoint numargs optarg newtoks) -> do
-                       setInput ts
-                       let getarg = try $ spaces >> bracedOrToken
-                       args <- case optarg of
-                                    Nothing -> count numargs getarg
-                                    Just o  ->
-                                       (:) <$> option o bracketedToks
-                                           <*> count (numargs - 1) getarg
-                       let addTok (Tok _ (Arg i) _) acc | i > 0
-                                                        , i <= numargs =
-                                 foldr addTok acc (args !! (i - 1))
-                           -- add space if needed after control sequence
-                           -- see #4007
-                           addTok (Tok _ (CtrlSeq x) txt)
-                                  acc@(Tok _ Word _ : _)
-                             | not (T.null txt) &&
-                               (isLetter (T.last txt)) =
-                               Tok spos (CtrlSeq x) (txt <> " ") : acc
-                           addTok t acc = setpos spos t : acc
-                       ts' <- getInput
-                       setInput $ foldr addTok ts' newtoks
-                       case expansionPoint of
-                            ExpandWhenUsed ->
-                              if n > 20  -- detect macro expansion loops
-                                 then throwError $ PandocMacroLoop (T.unpack name)
-                                 else doMacros (n + 1)
-                            ExpandWhenDefined -> return ()
-
-
-setpos :: SourcePos -> Tok -> Tok
-setpos spos (Tok _ tt txt) = Tok spos tt txt
-
-anyControlSeq :: PandocMonad m => LP m Tok
-anyControlSeq = satisfyTok isCtrlSeq
-  where isCtrlSeq (Tok _ (CtrlSeq _) _) = True
-        isCtrlSeq _                     = False
-
-anySymbol :: PandocMonad m => LP m Tok
-anySymbol = satisfyTok isSym
-  where isSym (Tok _ Symbol _) = True
-        isSym _                = False
-
-spaces :: PandocMonad m => LP m ()
-spaces = skipMany (satisfyTok (tokTypeIn [Comment, Spaces, Newline]))
-
-spaces1 :: PandocMonad m => LP m ()
-spaces1 = skipMany1 (satisfyTok (tokTypeIn [Comment, Spaces, Newline]))
-
-tokTypeIn :: [TokType] -> Tok -> Bool
-tokTypeIn toktypes (Tok _ tt _) = tt `elem` toktypes
-
-controlSeq :: PandocMonad m => Text -> LP m Tok
-controlSeq name = satisfyTok isNamed
-  where isNamed (Tok _ (CtrlSeq n) _) = n == name
-        isNamed _                     = False
-
-symbol :: PandocMonad m => Char -> LP m Tok
-symbol c = satisfyTok isc
-  where isc (Tok _ Symbol d) = case T.uncons d of
-                                    Just (c',_) -> c == c'
-                                    _           -> False
-        isc _ = False
-
-symbolIn :: PandocMonad m => [Char] -> LP m Tok
-symbolIn cs = satisfyTok isInCs
-  where isInCs (Tok _ Symbol d) = case T.uncons d of
-                                       Just (c,_) -> c `elem` cs
-                                       _          -> False
-        isInCs _ = False
-
-sp :: PandocMonad m => LP m ()
-sp = whitespace <|> endline
-
-whitespace :: PandocMonad m => LP m ()
-whitespace = () <$ satisfyTok isSpaceTok
-  where isSpaceTok (Tok _ Spaces _) = True
-        isSpaceTok _                = False
-
-newlineTok :: PandocMonad m => LP m ()
-newlineTok = () <$ satisfyTok isNewlineTok
-
-isNewlineTok :: Tok -> Bool
-isNewlineTok (Tok _ Newline _) = True
-isNewlineTok _                 = False
-
-comment :: PandocMonad m => LP m ()
-comment = () <$ satisfyTok isCommentTok
-  where isCommentTok (Tok _ Comment _) = True
-        isCommentTok _                 = False
-
-anyTok :: PandocMonad m => LP m Tok
-anyTok = satisfyTok (const True)
-
-endline :: PandocMonad m => LP m ()
-endline = try $ do
-  newlineTok
-  lookAhead anyTok
-  notFollowedBy blankline
-
-blankline :: PandocMonad m => LP m ()
-blankline = try $ skipMany whitespace *> newlineTok
-
-primEscape :: PandocMonad m => LP m Char
-primEscape = do
-  Tok _ toktype t <- satisfyTok (tokTypeIn [Esc1, Esc2])
-  case toktype of
-       Esc1 -> case T.uncons (T.drop 2 t) of
-                    Just (c, _)
-                      | c >= '\64' && c <= '\127' -> return (chr (ord c - 64))
-                      | otherwise                 -> return (chr (ord c + 64))
-                    Nothing -> fail "Empty content of Esc1"
-       Esc2 -> case safeRead ('0':'x':T.unpack (T.drop 2 t)) of
-                    Just x  -> return (chr x)
-                    Nothing -> fail $ "Could not read: " ++ T.unpack t
-       _    -> fail "Expected an Esc1 or Esc2 token" -- should not happen
-
-bgroup :: PandocMonad m => LP m Tok
-bgroup = try $ do
-  skipMany sp
-  symbol '{' <|> controlSeq "bgroup" <|> controlSeq "begingroup"
-
-egroup :: PandocMonad m => LP m Tok
-egroup = symbol '}' <|> controlSeq "egroup" <|> controlSeq "endgroup"
-
-grouped :: (PandocMonad m,  Monoid a) => LP m a -> LP m a
-grouped parser = try $ do
-  bgroup
-  -- first we check for an inner 'grouped', because
-  -- {{a,b}} should be parsed the same as {a,b}
-  try (grouped parser <* egroup) <|> (mconcat <$> manyTill parser egroup)
-
-braced :: PandocMonad m => LP m [Tok]
-braced = bgroup *> braced' 1
-  where braced' (n :: Int) =
-          handleEgroup n <|> handleBgroup n <|> handleOther n
-        handleEgroup n = do
-          t <- egroup
-          if n == 1
-             then return []
-             else (t:) <$> braced' (n - 1)
-        handleBgroup n = do
-          t <- bgroup
-          (t:) <$> braced' (n + 1)
-        handleOther n = do
-          t <- anyTok
-          (t:) <$> braced' n
-
-bracketed :: PandocMonad m => Monoid a => LP m a -> LP m a
-bracketed parser = try $ do
-  symbol '['
-  mconcat <$> manyTill parser (symbol ']')
-
-dimenarg :: PandocMonad m => LP m Text
-dimenarg = try $ do
-  ch  <- option False $ True <$ symbol '='
-  Tok _ _ s <- satisfyTok isWordTok
-  guard $ T.take 2 (T.reverse s) `elem`
-           ["pt","pc","in","bp","cm","mm","dd","cc","sp"]
-  let num = T.take (T.length s - 2) s
-  guard $ T.length num > 0
-  guard $ T.all isDigit num
-  return $ T.pack ['=' | ch] <> s
-
--- inline elements:
-
-word :: PandocMonad m => LP m Inlines
-word = (str . T.unpack . untoken) <$> satisfyTok isWordTok
-
-regularSymbol :: PandocMonad m => LP m Inlines
-regularSymbol = (str . T.unpack . untoken) <$> satisfyTok isRegularSymbol
-  where isRegularSymbol (Tok _ Symbol t) = not $ T.any isSpecial t
-        isRegularSymbol _                = False
-        isSpecial c = c `Set.member` specialChars
-
-specialChars :: Set.Set Char
-specialChars = Set.fromList "#$%&~_^\\{}"
-
-isWordTok :: Tok -> Bool
-isWordTok (Tok _ Word _) = True
-isWordTok _              = False
-
-inlineGroup :: PandocMonad m => LP m Inlines
-inlineGroup = do
-  ils <- grouped inline
-  if isNull ils
-     then return mempty
-     else return $ spanWith nullAttr ils
-          -- we need the span so we can detitlecase bibtex entries;
-          -- we need to know when something is {C}apitalized
-
-doLHSverb :: PandocMonad m => LP m Inlines
-doLHSverb =
-  (codeWith ("",["haskell"],[]) . T.unpack . untokenize)
-    <$> manyTill (satisfyTok (not . isNewlineTok)) (symbol '|')
-
-mkImage :: PandocMonad m => [(String, String)] -> String -> LP m Inlines
-mkImage options src = do
-   let replaceTextwidth (k,v) =
-         case numUnit v of
-              Just (num, "\\textwidth") -> (k, showFl (num * 100) ++ "%")
-              _                         -> (k, v)
-   let kvs = map replaceTextwidth
-             $ filter (\(k,_) -> k `elem` ["width", "height"]) options
-   let attr = ("",[], kvs)
-   let alt = str "image"
-   case takeExtension src of
-        "" -> do
-              defaultExt <- getOption readerDefaultImageExtension
-              return $ imageWith attr (addExtension src defaultExt) "" alt
-        _  -> return $ imageWith attr src "" alt
-
-doxspace :: PandocMonad m => LP m Inlines
-doxspace =
-  (space <$ lookAhead (satisfyTok startsWithLetter)) <|> return mempty
-  where startsWithLetter (Tok _ Word t) =
-          case T.uncons t of
-               Just (c, _) | isLetter c -> True
-               _           -> False
-        startsWithLetter _ = False
-
-
--- converts e.g. \SI{1}[\$]{} to "$ 1" or \SI{1}{\euro} to "1 €"
-dosiunitx :: PandocMonad m => LP m Inlines
-dosiunitx = do
-  skipopts
-  value <- tok
-  valueprefix <- option "" $ bracketed tok
-  unit <- tok
-  let emptyOr160 "" = ""
-      emptyOr160 _  = "\160"
-  return . mconcat $ [valueprefix,
-                      emptyOr160 valueprefix,
-                      value,
-                      emptyOr160 unit,
-                      unit]
-
-lit :: String -> LP m Inlines
-lit = pure . str
-
-removeDoubleQuotes :: Text -> Text
-removeDoubleQuotes t =
-  Data.Maybe.fromMaybe t $ T.stripPrefix "\"" t >>= T.stripSuffix "\""
-
-doubleQuote :: PandocMonad m => LP m Inlines
-doubleQuote =
-       quoted' doubleQuoted (try $ count 2 $ symbol '`')
-                     (void $ try $ count 2 $ symbol '\'')
-   <|> quoted' doubleQuoted ((:[]) <$> symbol '“') (void $ symbol '”')
-   -- the following is used by babel for localized quotes:
-   <|> quoted' doubleQuoted (try $ sequence [symbol '"', symbol '`'])
-                            (void $ try $ sequence [symbol '"', symbol '\''])
-
-singleQuote :: PandocMonad m => LP m Inlines
-singleQuote =
-       quoted' singleQuoted ((:[]) <$> symbol '`')
-                     (try $ symbol '\'' >>
-                           notFollowedBy (satisfyTok startsWithLetter))
-   <|> quoted' singleQuoted ((:[]) <$> symbol '‘')
-                            (try $ symbol '’' >>
-                                  notFollowedBy (satisfyTok startsWithLetter))
-  where startsWithLetter (Tok _ Word t) =
-          case T.uncons t of
-               Just (c, _) | isLetter c -> True
-               _           -> False
-        startsWithLetter _ = False
-
-quoted' :: PandocMonad m
-        => (Inlines -> Inlines)
-        -> LP m [Tok]
-        -> LP m ()
-        -> LP m Inlines
-quoted' f starter ender = do
-  startchs <- (T.unpack . untokenize) <$> starter
-  smart <- extensionEnabled Ext_smart <$> getOption readerExtensions
-  if smart
-     then do
-       ils <- many (notFollowedBy ender >> inline)
-       (ender >> return (f (mconcat ils))) <|>
-            (<> mconcat ils) <$>
-                    lit (case startchs of
-                              "``" -> "“"
-                              "`"  -> "‘"
-                              cs   -> cs)
-     else lit startchs
-
-enquote :: PandocMonad m => LP m Inlines
-enquote = do
-  skipopts
-  quoteContext <- sQuoteContext <$> getState
-  if quoteContext == InDoubleQuote
-     then singleQuoted <$> withQuoteContext InSingleQuote tok
-     else doubleQuoted <$> withQuoteContext InDoubleQuote tok
-
-doAcronym :: PandocMonad m => String -> LP m Inlines
-doAcronym form = do
-  acro <- braced
-  return . mconcat $ [spanWith ("",[],[("acronym-label", toksToString acro),
-    ("acronym-form", "singular+" ++ form)])
-    $ str $ toksToString acro]
-
-doAcronymPlural :: PandocMonad m => String -> LP m Inlines
-doAcronymPlural form = do
-  acro <- braced
-  plural <- lit "s"
-  return . mconcat $ [spanWith ("",[],[("acronym-label", toksToString acro),
-    ("acronym-form", "plural+" ++ form)]) $
-   mconcat [str $ toksToString acro, plural]]
-
-doverb :: PandocMonad m => LP m Inlines
-doverb = do
-  Tok _ Symbol t <- anySymbol
-  marker <- case T.uncons t of
-              Just (c, ts) | T.null ts -> return c
-              _            -> mzero
-  withVerbatimMode $
-    (code . T.unpack . untokenize) <$>
-      manyTill (verbTok marker) (symbol marker)
-
-verbTok :: PandocMonad m => Char -> LP m Tok
-verbTok stopchar = do
-  t@(Tok pos toktype txt) <- satisfyTok (not . isNewlineTok)
-  case T.findIndex (== stopchar) txt of
-       Nothing -> return t
-       Just i  -> do
-         let (t1, t2) = T.splitAt i txt
-         inp <- getInput
-         setInput $ Tok (incSourceColumn pos i) Symbol (T.singleton stopchar)
-                  : totoks (incSourceColumn pos (i + 1)) (T.drop 1 t2) ++ inp
-         return $ Tok pos toktype t1
-
-dolstinline :: PandocMonad m => LP m Inlines
-dolstinline = do
-  options <- option [] keyvals
-  let classes = maybeToList $ lookup "language" options >>= fromListingsLanguage
-  Tok _ Symbol t <- anySymbol
-  marker <- case T.uncons t of
-              Just (c, ts) | T.null ts -> return c
-              _            -> mzero
-  let stopchar = if marker == '{' then '}' else marker
-  withVerbatimMode $
-    (codeWith ("",classes,[]) . T.unpack . untokenize) <$>
-      manyTill (verbTok stopchar) (symbol stopchar)
-
-keyval :: PandocMonad m => LP m (String, String)
-keyval = try $ do
-  Tok _ Word key <- satisfyTok isWordTok
-  let isSpecSym (Tok _ Symbol t) = t /= "]" && t /= ","
-      isSpecSym _                = False
-  optional sp
-  val <- option [] $ do
-           symbol '='
-           optional sp
-           braced <|> many1 (satisfyTok isWordTok <|> satisfyTok isSpecSym
-                               <|> anyControlSeq)
-  optional sp
-  optional (symbol ',')
-  optional sp
-  return (T.unpack key, T.unpack . untokenize $ val)
-
-keyvals :: PandocMonad m => LP m [(String, String)]
-keyvals = try $ symbol '[' >> manyTill keyval (symbol ']')
-
-accent :: PandocMonad m => Char -> (Char -> String) -> LP m Inlines
-accent c f = try $ do
-  ils <- tok
-  case toList ils of
-       (Str (x:xs) : ys) -> return $ fromList (Str (f x ++ xs) : ys)
-       [Space]           -> return $ str [c]
-       []                -> return $ str [c]
-       _                 -> return ils
-
-grave :: Char -> String
-grave 'A' = "À"
-grave 'E' = "È"
-grave 'I' = "Ì"
-grave 'O' = "Ò"
-grave 'U' = "Ù"
-grave 'a' = "à"
-grave 'e' = "è"
-grave 'i' = "ì"
-grave 'o' = "ò"
-grave 'u' = "ù"
-grave c   = [c]
-
-acute :: Char -> String
-acute 'A' = "Á"
-acute 'E' = "É"
-acute 'I' = "Í"
-acute 'O' = "Ó"
-acute 'U' = "Ú"
-acute 'Y' = "Ý"
-acute 'a' = "á"
-acute 'e' = "é"
-acute 'i' = "í"
-acute 'o' = "ó"
-acute 'u' = "ú"
-acute 'y' = "ý"
-acute 'C' = "Ć"
-acute 'c' = "ć"
-acute 'L' = "Ĺ"
-acute 'l' = "ĺ"
-acute 'N' = "Ń"
-acute 'n' = "ń"
-acute 'R' = "Ŕ"
-acute 'r' = "ŕ"
-acute 'S' = "Ś"
-acute 's' = "ś"
-acute 'Z' = "Ź"
-acute 'z' = "ź"
-acute c   = [c]
-
-circ :: Char -> String
-circ 'A' = "Â"
-circ 'E' = "Ê"
-circ 'I' = "Î"
-circ 'O' = "Ô"
-circ 'U' = "Û"
-circ 'a' = "â"
-circ 'e' = "ê"
-circ 'i' = "î"
-circ 'o' = "ô"
-circ 'u' = "û"
-circ 'C' = "Ĉ"
-circ 'c' = "ĉ"
-circ 'G' = "Ĝ"
-circ 'g' = "ĝ"
-circ 'H' = "Ĥ"
-circ 'h' = "ĥ"
-circ 'J' = "Ĵ"
-circ 'j' = "ĵ"
-circ 'S' = "Ŝ"
-circ 's' = "ŝ"
-circ 'W' = "Ŵ"
-circ 'w' = "ŵ"
-circ 'Y' = "Ŷ"
-circ 'y' = "ŷ"
-circ c   = [c]
-
-tilde :: Char -> String
-tilde 'A' = "Ã"
-tilde 'a' = "ã"
-tilde 'O' = "Õ"
-tilde 'o' = "õ"
-tilde 'I' = "Ĩ"
-tilde 'i' = "ĩ"
-tilde 'U' = "Ũ"
-tilde 'u' = "ũ"
-tilde 'N' = "Ñ"
-tilde 'n' = "ñ"
-tilde c   = [c]
-
-umlaut :: Char -> String
-umlaut 'A' = "Ä"
-umlaut 'E' = "Ë"
-umlaut 'I' = "Ï"
-umlaut 'O' = "Ö"
-umlaut 'U' = "Ü"
-umlaut 'a' = "ä"
-umlaut 'e' = "ë"
-umlaut 'i' = "ï"
-umlaut 'o' = "ö"
-umlaut 'u' = "ü"
-umlaut c   = [c]
-
-hungarumlaut :: Char -> String
-hungarumlaut 'A' = "A̋"
-hungarumlaut 'E' = "E̋"
-hungarumlaut 'I' = "I̋"
-hungarumlaut 'O' = "Ő"
-hungarumlaut 'U' = "Ű"
-hungarumlaut 'Y' = "ӳ"
-hungarumlaut 'a' = "a̋"
-hungarumlaut 'e' = "e̋"
-hungarumlaut 'i' = "i̋"
-hungarumlaut 'o' = "ő"
-hungarumlaut 'u' = "ű"
-hungarumlaut 'y' = "ӳ"
-hungarumlaut c   = [c]
-
-dot :: Char -> String
-dot 'C' = "Ċ"
-dot 'c' = "ċ"
-dot 'E' = "Ė"
-dot 'e' = "ė"
-dot 'G' = "Ġ"
-dot 'g' = "ġ"
-dot 'I' = "İ"
-dot 'Z' = "Ż"
-dot 'z' = "ż"
-dot c   = [c]
-
-macron :: Char -> String
-macron 'A' = "Ā"
-macron 'E' = "Ē"
-macron 'I' = "Ī"
-macron 'O' = "Ō"
-macron 'U' = "Ū"
-macron 'a' = "ā"
-macron 'e' = "ē"
-macron 'i' = "ī"
-macron 'o' = "ō"
-macron 'u' = "ū"
-macron c   = [c]
-
-cedilla :: Char -> String
-cedilla 'c' = "ç"
-cedilla 'C' = "Ç"
-cedilla 's' = "ş"
-cedilla 'S' = "Ş"
-cedilla 't' = "ţ"
-cedilla 'T' = "Ţ"
-cedilla 'e' = "ȩ"
-cedilla 'E' = "Ȩ"
-cedilla 'h' = "ḩ"
-cedilla 'H' = "Ḩ"
-cedilla 'o' = "o̧"
-cedilla 'O' = "O̧"
-cedilla c   = [c]
-
-hacek :: Char -> String
-hacek 'A' = "Ǎ"
-hacek 'a' = "ǎ"
-hacek 'C' = "Č"
-hacek 'c' = "č"
-hacek 'D' = "Ď"
-hacek 'd' = "ď"
-hacek 'E' = "Ě"
-hacek 'e' = "ě"
-hacek 'G' = "Ǧ"
-hacek 'g' = "ǧ"
-hacek 'H' = "Ȟ"
-hacek 'h' = "ȟ"
-hacek 'I' = "Ǐ"
-hacek 'i' = "ǐ"
-hacek 'j' = "ǰ"
-hacek 'K' = "Ǩ"
-hacek 'k' = "ǩ"
-hacek 'L' = "Ľ"
-hacek 'l' = "ľ"
-hacek 'N' = "Ň"
-hacek 'n' = "ň"
-hacek 'O' = "Ǒ"
-hacek 'o' = "ǒ"
-hacek 'R' = "Ř"
-hacek 'r' = "ř"
-hacek 'S' = "Š"
-hacek 's' = "š"
-hacek 'T' = "Ť"
-hacek 't' = "ť"
-hacek 'U' = "Ǔ"
-hacek 'u' = "ǔ"
-hacek 'Z' = "Ž"
-hacek 'z' = "ž"
-hacek c   = [c]
-
-ogonek :: Char -> String
-ogonek 'a' = "ą"
-ogonek 'e' = "ę"
-ogonek 'o' = "ǫ"
-ogonek 'i' = "į"
-ogonek 'u' = "ų"
-ogonek 'A' = "Ą"
-ogonek 'E' = "Ę"
-ogonek 'I' = "Į"
-ogonek 'O' = "Ǫ"
-ogonek 'U' = "Ų"
-ogonek c   = [c]
-
-breve :: Char -> String
-breve 'A' = "Ă"
-breve 'a' = "ă"
-breve 'E' = "Ĕ"
-breve 'e' = "ĕ"
-breve 'G' = "Ğ"
-breve 'g' = "ğ"
-breve 'I' = "Ĭ"
-breve 'i' = "ĭ"
-breve 'O' = "Ŏ"
-breve 'o' = "ŏ"
-breve 'U' = "Ŭ"
-breve 'u' = "ŭ"
-breve c   = [c]
-
-toksToString :: [Tok] -> String
-toksToString = T.unpack . untokenize
-
-mathDisplay :: String -> Inlines
-mathDisplay = displayMath . trim
-
-mathInline :: String -> Inlines
-mathInline = math . trim
-
-dollarsMath :: PandocMonad m => LP m Inlines
-dollarsMath = do
-  symbol '$'
-  display <- option False (True <$ symbol '$')
-  contents <- trim . toksToString <$>
-               many (notFollowedBy (symbol '$') >> anyTok)
-  if display
-     then
-       mathDisplay contents <$ try (symbol '$' >> symbol '$')
-   <|> (guard (null contents) >> return (mathInline ""))
-     else mathInline contents <$ symbol '$'
-
--- citations
-
-addPrefix :: [Inline] -> [Citation] -> [Citation]
-addPrefix p (k:ks) = k {citationPrefix = p ++ citationPrefix k} : ks
-addPrefix _ _      = []
-
-addSuffix :: [Inline] -> [Citation] -> [Citation]
-addSuffix s ks@(_:_) =
-  let k = last ks
-  in  init ks ++ [k {citationSuffix = citationSuffix k ++ s}]
-addSuffix _ _ = []
-
-simpleCiteArgs :: PandocMonad m => LP m [Citation]
-simpleCiteArgs = try $ do
-  first  <- optionMaybe $ toList <$> opt
-  second <- optionMaybe $ toList <$> opt
-  keys <- try $ bgroup *> manyTill citationLabel egroup
-  let (pre, suf) = case (first  , second ) of
-        (Just s , Nothing) -> (mempty, s )
-        (Just s , Just t ) -> (s , t )
-        _                  -> (mempty, mempty)
-      conv k = Citation { citationId      = k
-                        , citationPrefix  = []
-                        , citationSuffix  = []
-                        , citationMode    = NormalCitation
-                        , citationHash    = 0
-                        , citationNoteNum = 0
-                        }
-  return $ addPrefix pre $ addSuffix suf $ map conv keys
-
-citationLabel :: PandocMonad m => LP m String
-citationLabel  = do
-  optional sp
-  toksToString <$>
-    (many1 (satisfyTok isWordTok <|> symbolIn bibtexKeyChar)
-          <* optional sp
-          <* optional (symbol ',')
-          <* optional sp)
-  where bibtexKeyChar = ".:;?!`'()/*@_+=-[]" :: [Char]
-
-cites :: PandocMonad m => CitationMode -> Bool -> LP m [Citation]
-cites mode multi = try $ do
-  cits <- if multi
-             then many1 simpleCiteArgs
-             else count 1 simpleCiteArgs
-  let cs = concat cits
-  return $ case mode of
-        AuthorInText -> case cs of
-                             (c:rest) -> c {citationMode = mode} : rest
-                             []       -> []
-        _            -> map (\a -> a {citationMode = mode}) cs
-
-citation :: PandocMonad m => String -> CitationMode -> Bool -> LP m Inlines
-citation name mode multi = do
-  (c,raw) <- withRaw $ cites mode multi
-  return $ cite c (rawInline "latex" $ "\\" ++ name ++ toksToString raw)
-
-handleCitationPart :: Inlines -> [Citation]
-handleCitationPart ils =
-  let isCite Cite{} = True
-      isCite _      = False
-      (pref, rest) = break isCite (toList ils)
-  in case rest of
-          (Cite cs _:suff) -> addPrefix pref $ addSuffix suff cs
-          _                -> []
-
-complexNatbibCitation :: PandocMonad m => CitationMode -> LP m Inlines
-complexNatbibCitation mode = try $ do
-  (cs, raw) <-
-    withRaw $ concat <$> do
-      bgroup
-      items <- mconcat <$>
-                many1 (notFollowedBy (symbol ';') >> inline)
-                  `sepBy1` (symbol ';')
-      egroup
-      return $ map handleCitationPart items
-  case cs of
-       []       -> mzero
-       (c:cits) -> return $ cite (c{ citationMode = mode }:cits)
-                      (rawInline "latex" $ "\\citetext" ++ toksToString raw)
-
-inNote :: Inlines -> Inlines
-inNote ils =
-  note $ para $ ils <> str "."
-
-inlineCommand' :: PandocMonad m => LP m Inlines
-inlineCommand' = try $ do
-  Tok _ (CtrlSeq name) cmd <- anyControlSeq
-  guard $ name /= "begin" && name /= "end"
-  star <- option "" ("*" <$ symbol '*' <* optional sp)
-  let name' = name <> star
-  let names = ordNub [name', name] -- check non-starred as fallback
-  let raw = do
-       guard $ isInlineCommand name || not (isBlockCommand name)
-       rawcommand <- getRawCommand name (cmd <> star)
-       (guardEnabled Ext_raw_tex >> return (rawInline "latex" rawcommand))
-         <|> ignore rawcommand
-  lookupListDefault raw names inlineCommands
-
-tok :: PandocMonad m => LP m Inlines
-tok = try $ spaces >> grouped inline <|> inlineCommand' <|> singleChar'
-  where singleChar' = do
-          Tok _ _ t <- singleChar
-          return (str (T.unpack t))
-
-singleChar :: PandocMonad m => LP m Tok
-singleChar = try $ do
-  Tok pos toktype t <- satisfyTok (tokTypeIn [Word, Symbol])
-  guard $ not $ toktype == Symbol &&
-                T.any (`Set.member` specialChars) t
-  if T.length t > 1
-     then do
-       let (t1, t2) = (T.take 1 t, T.drop 1 t)
-       inp <- getInput
-       setInput $ Tok (incSourceColumn pos 1) toktype t2 : inp
-       return $ Tok pos toktype t1
-     else return $ Tok pos toktype t
-
-opt :: PandocMonad m => LP m Inlines
-opt = bracketed inline
-
-rawopt :: PandocMonad m => LP m Text
-rawopt = do
-  inner <- untokenize <$> bracketedToks
-  optional sp
-  return $ "[" <> inner <> "]"
-
-skipopts :: PandocMonad m => LP m ()
-skipopts = skipMany rawopt
-
--- opts in angle brackets are used in beamer
-rawangle :: PandocMonad m => LP m ()
-rawangle = try $ do
-  symbol '<'
-  () <$ manyTill anyTok (symbol '>')
-
-skipangles :: PandocMonad m => LP m ()
-skipangles = skipMany rawangle
-
-ignore :: (Monoid a, PandocMonad m) => String -> ParserT s u m a
-ignore raw = do
-  pos <- getPosition
-  report $ SkippedContent raw pos
-  return mempty
-
-withRaw :: PandocMonad m => LP m a -> LP m (a, [Tok])
-withRaw parser = do
-  inp <- getInput
-  result <- parser
-  nxt <- option (Tok (initialPos "source") Word "") (lookAhead anyTok)
-  let raw = takeWhile (/= nxt) inp
-  return (result, raw)
-
-inBrackets :: Inlines -> Inlines
-inBrackets x = str "[" <> x <> str "]"
-
-unescapeURL :: String -> String
-unescapeURL ('\\':x:xs) | isEscapable x = x:unescapeURL xs
-  where isEscapable c = c `elem` ("#$%&~_^\\{}" :: String)
-unescapeURL (x:xs) = x:unescapeURL xs
-unescapeURL [] = ""
-
-mathEnvWith :: PandocMonad m
-            => (Inlines -> a) -> Maybe Text -> Text -> LP m a
-mathEnvWith f innerEnv name = f . mathDisplay . inner <$> mathEnv name
-   where inner x = case innerEnv of
-                        Nothing -> x
-                        Just y  -> "\\begin{" ++ T.unpack y ++ "}\n" ++ x ++
-                                   "\\end{" ++ T.unpack y ++ "}"
-
-mathEnv :: PandocMonad m => Text -> LP m String
-mathEnv name = do
-  skipopts
-  optional blankline
-  res <- manyTill anyTok (end_ name)
-  return $ stripTrailingNewlines $ T.unpack $ untokenize res
-
-inlineEnvironment :: PandocMonad m => LP m Inlines
-inlineEnvironment = try $ do
-  controlSeq "begin"
-  name <- untokenize <$> braced
-  M.findWithDefault mzero name inlineEnvironments
-
-inlineEnvironments :: PandocMonad m => M.Map Text (LP m Inlines)
-inlineEnvironments = M.fromList [
-    ("displaymath", mathEnvWith id Nothing "displaymath")
-  , ("math", math <$> mathEnv "math")
-  , ("equation", mathEnvWith id Nothing "equation")
-  , ("equation*", mathEnvWith id Nothing "equation*")
-  , ("gather", mathEnvWith id (Just "gathered") "gather")
-  , ("gather*", mathEnvWith id (Just "gathered") "gather*")
-  , ("multline", mathEnvWith id (Just "gathered") "multline")
-  , ("multline*", mathEnvWith id (Just "gathered") "multline*")
-  , ("eqnarray", mathEnvWith id (Just "aligned") "eqnarray")
-  , ("eqnarray*", mathEnvWith id (Just "aligned") "eqnarray*")
-  , ("align", mathEnvWith id (Just "aligned") "align")
-  , ("align*", mathEnvWith id (Just "aligned") "align*")
-  , ("alignat", mathEnvWith id (Just "aligned") "alignat")
-  , ("alignat*", mathEnvWith id (Just "aligned") "alignat*")
-  ]
-
-inlineCommands :: PandocMonad m => M.Map Text (LP m Inlines)
-inlineCommands = M.union inlineLanguageCommands $ M.fromList $
-  [ ("emph", extractSpaces emph <$> tok)
-  , ("textit", extractSpaces emph <$> tok)
-  , ("textsl", extractSpaces emph <$> tok)
-  , ("textsc", extractSpaces smallcaps <$> tok)
-  , ("textsf", extractSpaces (spanWith ("",["sans-serif"],[])) <$> tok)
-  , ("textmd", extractSpaces (spanWith ("",["medium"],[])) <$> tok)
-  , ("textrm", extractSpaces (spanWith ("",["roman"],[])) <$> tok)
-  , ("textup", extractSpaces (spanWith ("",["upright"],[])) <$> tok)
-  , ("texttt", ttfamily)
-  , ("sout", extractSpaces strikeout <$> tok)
-  , ("alert", skipangles >> spanWith ("",["alert"],[]) <$> tok) -- beamer
-  , ("lq", return (str "‘"))
-  , ("rq", return (str "’"))
-  , ("textquoteleft", return (str "‘"))
-  , ("textquoteright", return (str "’"))
-  , ("textquotedblleft", return (str "“"))
-  , ("textquotedblright", return (str "”"))
-  , ("textsuperscript", extractSpaces superscript <$> tok)
-  , ("textsubscript", extractSpaces subscript <$> tok)
-  , ("textbackslash", lit "\\")
-  , ("backslash", lit "\\")
-  , ("slash", lit "/")
-  , ("textbf", extractSpaces strong <$> tok)
-  , ("textnormal", extractSpaces (spanWith ("",["nodecor"],[])) <$> tok)
-  , ("ldots", lit "…")
-  , ("vdots", lit "\8942")
-  , ("dots", lit "…")
-  , ("mdots", lit "…")
-  , ("sim", lit "~")
-  , ("sep", lit ",")
-  , ("label", rawInlineOr "label" dolabel)
-  , ("ref", rawInlineOr "ref" $ doref "ref")
-  , ("cref", rawInlineOr "cref" $ doref "ref")       -- from cleveref.sty
-  , ("vref", rawInlineOr "vref" $ doref "ref+page")  -- from varioref.sty
-  , ("eqref", rawInlineOr "eqref" $ doref "eqref")   -- from amsmath.sty
-  , ("lettrine", optional opt >> extractSpaces (spanWith ("",["lettrine"],[])) <$> tok)
-  , ("(", mathInline . toksToString <$> manyTill anyTok (controlSeq ")"))
-  , ("[", mathDisplay . toksToString <$> manyTill anyTok (controlSeq "]"))
-  , ("ensuremath", mathInline . toksToString <$> braced)
-  , ("texorpdfstring", (\_ x -> x) <$> tok <*> tok)
-  , ("P", lit "¶")
-  , ("S", lit "§")
-  , ("$", lit "$")
-  , ("%", lit "%")
-  , ("&", lit "&")
-  , ("#", lit "#")
-  , ("_", lit "_")
-  , ("{", lit "{")
-  , ("}", lit "}")
-  -- old TeX commands
-  , ("em", extractSpaces emph <$> inlines)
-  , ("it", extractSpaces emph <$> inlines)
-  , ("sl", extractSpaces emph <$> inlines)
-  , ("bf", extractSpaces strong <$> inlines)
-  , ("rm", inlines)
-  , ("itshape", extractSpaces emph <$> inlines)
-  , ("slshape", extractSpaces emph <$> inlines)
-  , ("scshape", extractSpaces smallcaps <$> inlines)
-  , ("bfseries", extractSpaces strong <$> inlines)
-  , ("/", pure mempty) -- italic correction
-  , ("aa", lit "å")
-  , ("AA", lit "Å")
-  , ("ss", lit "ß")
-  , ("o", lit "ø")
-  , ("O", lit "Ø")
-  , ("L", lit "Ł")
-  , ("l", lit "ł")
-  , ("ae", lit "æ")
-  , ("AE", lit "Æ")
-  , ("oe", lit "œ")
-  , ("OE", lit "Œ")
-  , ("pounds", lit "£")
-  , ("euro", lit "€")
-  , ("copyright", lit "©")
-  , ("textasciicircum", lit "^")
-  , ("textasciitilde", lit "~")
-  , ("H", accent '\779' hungarumlaut)
-  , ("`", accent '`' grave)
-  , ("'", accent '\'' acute)
-  , ("^", accent '^' circ)
-  , ("~", accent '~' tilde)
-  , ("\"", accent '\776' umlaut)
-  , (".", accent '\775' dot)
-  , ("=", accent '\772' macron)
-  , ("c", accent '\807' cedilla)
-  , ("v", accent 'ˇ' hacek)
-  , ("u", accent '\774' breve)
-  , ("k", accent '\808' ogonek)
-  , ("textogonekcentered", accent '\808' ogonek)
-  , ("i", lit "i")
-  , ("\\", linebreak <$ (do inTableCell <- sInTableCell <$> getState
-                            guard $ not inTableCell
-                            optional opt
-                            spaces))
-  , (",", lit "\8198")
-  , ("@", pure mempty)
-  , (" ", lit "\160")
-  , ("ps", pure $ str "PS." <> space)
-  , ("TeX", lit "TeX")
-  , ("LaTeX", lit "LaTeX")
-  , ("bar", lit "|")
-  , ("textless", lit "<")
-  , ("textgreater", lit ">")
-  , ("thanks", skipopts >> note <$> grouped block)
-  , ("footnote", skipopts >> note <$> grouped block)
-  , ("verb", doverb)
-  , ("lstinline", dolstinline)
-  , ("Verb", doverb)
-  , ("url", ((unescapeURL . T.unpack . untokenize) <$> braced) >>= \url ->
-                  pure (link url "" (str url)))
-  , ("href", (unescapeURL . toksToString <$>
-                 braced <* optional sp) >>= \url ->
-                   tok >>= \lab -> pure (link url "" lab))
-  , ("includegraphics", do options <- option [] keyvals
-                           src <- unescapeURL . T.unpack .
-                                    removeDoubleQuotes . untokenize <$> braced
-                           mkImage options src)
-  , ("enquote", enquote)
-  , ("figurename", doTerm Translations.Figure)
-  , ("prefacename", doTerm Translations.Preface)
-  , ("refname", doTerm Translations.References)
-  , ("bibname", doTerm Translations.Bibliography)
-  , ("chaptername", doTerm Translations.Chapter)
-  , ("partname", doTerm Translations.Part)
-  , ("contentsname", doTerm Translations.Contents)
-  , ("listfigurename", doTerm Translations.ListOfFigures)
-  , ("listtablename", doTerm Translations.ListOfTables)
-  , ("indexname", doTerm Translations.Index)
-  , ("abstractname", doTerm Translations.Abstract)
-  , ("tablename", doTerm Translations.Table)
-  , ("enclname", doTerm Translations.Encl)
-  , ("ccname", doTerm Translations.Cc)
-  , ("headtoname", doTerm Translations.To)
-  , ("pagename", doTerm Translations.Page)
-  , ("seename", doTerm Translations.See)
-  , ("seealsoname", doTerm Translations.SeeAlso)
-  , ("proofname", doTerm Translations.Proof)
-  , ("glossaryname", doTerm Translations.Glossary)
-  , ("lstlistingname", doTerm Translations.Listing)
-  , ("cite", citation "cite" NormalCitation False)
-  , ("Cite", citation "Cite" NormalCitation False)
-  , ("citep", citation "citep" NormalCitation False)
-  , ("citep*", citation "citep*" NormalCitation False)
-  , ("citeal", citation "citeal" NormalCitation False)
-  , ("citealp", citation "citealp" NormalCitation False)
-  , ("citealp*", citation "citealp*" NormalCitation False)
-  , ("autocite", citation "autocite" NormalCitation False)
-  , ("smartcite", citation "smartcite" NormalCitation False)
-  , ("footcite", inNote <$> citation "footcite" NormalCitation False)
-  , ("parencite", citation "parencite" NormalCitation False)
-  , ("supercite", citation "supercite" NormalCitation False)
-  , ("footcitetext", inNote <$> citation "footcitetext" NormalCitation False)
-  , ("citeyearpar", citation "citeyearpar" SuppressAuthor False)
-  , ("citeyear", citation "citeyear" SuppressAuthor False)
-  , ("autocite*", citation "autocite*" SuppressAuthor False)
-  , ("cite*", citation "cite*" SuppressAuthor False)
-  , ("parencite*", citation "parencite*" SuppressAuthor False)
-  , ("textcite", citation "textcite" AuthorInText False)
-  , ("citet", citation "citet" AuthorInText False)
-  , ("citet*", citation "citet*" AuthorInText False)
-  , ("citealt", citation "citealt" AuthorInText False)
-  , ("citealt*", citation "citealt*" AuthorInText False)
-  , ("textcites", citation "textcites" AuthorInText True)
-  , ("cites", citation "cites" NormalCitation True)
-  , ("autocites", citation "autocites" NormalCitation True)
-  , ("footcites", inNote <$> citation "footcites" NormalCitation True)
-  , ("parencites", citation "parencites" NormalCitation True)
-  , ("supercites", citation "supercites" NormalCitation True)
-  , ("footcitetexts", inNote <$> citation "footcitetexts" NormalCitation True)
-  , ("Autocite", citation "Autocite" NormalCitation False)
-  , ("Smartcite", citation "Smartcite" NormalCitation False)
-  , ("Footcite", citation "Footcite" NormalCitation False)
-  , ("Parencite", citation "Parencite" NormalCitation False)
-  , ("Supercite", citation "Supercite" NormalCitation False)
-  , ("Footcitetext", inNote <$> citation "Footcitetext" NormalCitation False)
-  , ("Citeyearpar", citation "Citeyearpar" SuppressAuthor False)
-  , ("Citeyear", citation "Citeyear" SuppressAuthor False)
-  , ("Autocite*", citation "Autocite*" SuppressAuthor False)
-  , ("Cite*", citation "Cite*" SuppressAuthor False)
-  , ("Parencite*", citation "Parencite*" SuppressAuthor False)
-  , ("Textcite", citation "Textcite" AuthorInText False)
-  , ("Textcites", citation "Textcites" AuthorInText True)
-  , ("Cites", citation "Cites" NormalCitation True)
-  , ("Autocites", citation "Autocites" NormalCitation True)
-  , ("Footcites", citation "Footcites" NormalCitation True)
-  , ("Parencites", citation "Parencites" NormalCitation True)
-  , ("Supercites", citation "Supercites" NormalCitation True)
-  , ("Footcitetexts", inNote <$> citation "Footcitetexts" NormalCitation True)
-  , ("citetext", complexNatbibCitation NormalCitation)
-  , ("citeauthor", (try (tok *> optional sp *> controlSeq "citetext") *>
-                        complexNatbibCitation AuthorInText)
-                   <|> citation "citeauthor" AuthorInText False)
-  , ("nocite", mempty <$ (citation "nocite" NormalCitation False >>=
-                          addMeta "nocite"))
-  , ("hyperlink", hyperlink)
-  , ("hypertarget", hypertargetInline)
-  -- glossaries package
-  , ("gls", doAcronym "short")
-  , ("Gls", doAcronym "short")
-  , ("glsdesc", doAcronym "long")
-  , ("Glsdesc", doAcronym "long")
-  , ("GLSdesc", doAcronym "long")
-  , ("acrlong", doAcronym "long")
-  , ("Acrlong", doAcronym "long")
-  , ("acrfull", doAcronym "full")
-  , ("Acrfull", doAcronym "full")
-  , ("acrshort", doAcronym "abbrv")
-  , ("Acrshort", doAcronym "abbrv")
-  , ("glspl", doAcronymPlural "short")
-  , ("Glspl", doAcronymPlural "short")
-  , ("glsdescplural", doAcronymPlural "long")
-  , ("Glsdescplural", doAcronymPlural "long")
-  , ("GLSdescplural", doAcronymPlural "long")
-  -- acronyms package
-  , ("ac", doAcronym "short")
-  , ("acf", doAcronym "full")
-  , ("acs", doAcronym "abbrv")
-  , ("acp", doAcronymPlural "short")
-  , ("acfp", doAcronymPlural "full")
-  , ("acsp", doAcronymPlural "abbrv")
-  -- siuntix
-  , ("SI", dosiunitx)
-  -- hyphenat
-  , ("bshyp", lit "\\\173")
-  , ("fshyp", lit "/\173")
-  , ("dothyp", lit ".\173")
-  , ("colonhyp", lit ":\173")
-  , ("hyp", lit "-")
-  , ("nohyphens", tok)
-  , ("textnhtt", ttfamily)
-  , ("nhttfamily", ttfamily)
-  -- LaTeX colors
-  , ("textcolor", coloredInline "color")
-  , ("colorbox", coloredInline "background-color")
-  -- fontawesome
-  , ("faCheck", lit "\10003")
-  , ("faClose", lit "\10007")
-  -- xspace
-  , ("xspace", doxspace)
-  -- etoolbox
-  , ("ifstrequal", ifstrequal)
-  , ("newtoggle", braced >>= newToggle)
-  , ("toggletrue", braced >>= setToggle True)
-  , ("togglefalse", braced >>= setToggle False)
-  , ("iftoggle", try $ ifToggle >> inline)
-  -- biblatex misc
-  , ("RN", romanNumeralUpper)
-  , ("Rn", romanNumeralLower)
-  -- babel
-  , ("foreignlanguage", foreignlanguage)
-  ]
-
-foreignlanguage :: PandocMonad m => LP m Inlines
-foreignlanguage = do
-  babelLang <- T.unpack . untokenize <$> braced
-  case babelLangToBCP47 babelLang of
-       Just lang -> spanWith ("", [], [("lang", renderLang $ lang)]) <$> tok
-       _ -> tok
-
-inlineLanguageCommands :: PandocMonad m => M.Map Text (LP m Inlines)
-inlineLanguageCommands = M.fromList $ mk <$> M.toList polyglossiaLangToBCP47
-  where
-    mk (polyglossia, bcp47Func) =
-      ("text" <> T.pack polyglossia, inlineLanguage bcp47Func)
-
-inlineLanguage :: PandocMonad m => (String -> Lang) -> LP m Inlines
-inlineLanguage bcp47Func = do
-  o <- option "" $ (T.unpack . T.filter (\c -> c /= '[' && c /= ']'))
-                <$> rawopt
-  let lang = renderLang $ bcp47Func o
-  extractSpaces (spanWith ("", [], [("lang", lang)])) <$> tok
-
-hyperlink :: PandocMonad m => LP m Inlines
-hyperlink = try $ do
-  src <- toksToString <$> braced
-  lab <- tok
-  return $ link ('#':src) "" lab
-
-hypertargetBlock :: PandocMonad m => LP m Blocks
-hypertargetBlock = try $ do
-  ref <- toksToString <$> braced
-  bs <- grouped block
-  case toList bs of
-       [Header 1 (ident,_,_) _] | ident == ref -> return bs
-       _                        -> return $ divWith (ref, [], []) bs
-
-hypertargetInline :: PandocMonad m => LP m Inlines
-hypertargetInline = try $ do
-  ref <- toksToString <$> braced
-  ils <- grouped inline
-  return $ spanWith (ref, [], []) ils
-
-romanNumeralUpper :: (PandocMonad m) => LP m Inlines
-romanNumeralUpper =
-  str . toRomanNumeral <$> romanNumeralArg
-
-romanNumeralLower :: (PandocMonad m) => LP m Inlines
-romanNumeralLower =
-  str . map toLower . toRomanNumeral <$> romanNumeralArg
-
-romanNumeralArg :: (PandocMonad m) => LP m Int
-romanNumeralArg = spaces *> (parser <|> inBraces)
-  where
-    inBraces = do
-      symbol '{'
-      spaces
-      res <- parser
-      spaces
-      symbol '}'
-      return res
-    parser = do
-      Tok _ Word s <- satisfyTok isWordTok
-      let (digits, rest) = T.span isDigit s
-      unless (T.null rest) $
-        fail "Non-digits in argument to \\Rn or \\RN"
-      safeRead $ T.unpack digits
-
-newToggle :: (Monoid a, PandocMonad m) => [Tok] -> LP m a
-newToggle name = do
-  updateState $ \st ->
-    st{ sToggles = M.insert (toksToString name) False (sToggles st) }
-  return mempty
-
-setToggle :: (Monoid a, PandocMonad m) => Bool -> [Tok] -> LP m a
-setToggle on name = do
-  updateState $ \st ->
-    st{ sToggles = M.adjust (const on) (toksToString name) (sToggles st) }
-  return mempty
-
-ifToggle :: PandocMonad m => LP m ()
-ifToggle = do
-  name <- braced
-  spaces
-  yes <- braced
-  spaces
-  no <- braced
-  toggles <- sToggles <$> getState
-  inp <- getInput
-  let name' = toksToString name
-  case M.lookup name' toggles of
-                Just True  -> setInput (yes ++ inp)
-                Just False -> setInput (no  ++ inp)
-                Nothing    -> do
-                  pos <- getPosition
-                  report $ UndefinedToggle name' pos
-  return ()
-
-doTerm :: PandocMonad m => Translations.Term -> LP m Inlines
-doTerm term = str <$> translateTerm term
-
-ifstrequal :: (PandocMonad m, Monoid a) => LP m a
-ifstrequal = do
-  str1 <- tok
-  str2 <- tok
-  ifequal <- braced
-  ifnotequal <- braced
-  if str1 == str2
-     then getInput >>= setInput . (ifequal ++)
-     else getInput >>= setInput . (ifnotequal ++)
-  return mempty
-
-coloredInline :: PandocMonad m => String -> LP m Inlines
-coloredInline stylename = do
-  skipopts
-  color <- braced
-  spanWith ("",[],[("style",stylename ++ ": " ++ toksToString color)]) <$> tok
-
-ttfamily :: PandocMonad m => LP m Inlines
-ttfamily = (code . stringify . toList) <$> tok
-
-rawInlineOr :: PandocMonad m => Text -> LP m Inlines -> LP m Inlines
-rawInlineOr name' fallback = do
-  parseRaw <- extensionEnabled Ext_raw_tex <$> getOption readerExtensions
-  if parseRaw
-     then rawInline "latex" <$> getRawCommand name' ("\\" <> name')
-     else fallback
-
-getRawCommand :: PandocMonad m => Text -> Text -> LP m String
-getRawCommand name txt = do
-  (_, rawargs) <- withRaw $
-      case name of
-           "write" -> do
-             void $ satisfyTok isWordTok -- digits
-             void braced
-           "titleformat" -> do
-             void braced
-             skipopts
-             void $ count 4 braced
-           "def" ->
-             void $ manyTill anyTok braced
-           _ -> do
-             skipangles
-             skipopts
-             option "" (try (optional sp *> dimenarg))
-             void $ many braced
-  return $ T.unpack (txt <> untokenize rawargs)
-
-isBlockCommand :: Text -> Bool
-isBlockCommand s =
-  s `M.member` (blockCommands :: M.Map Text (LP PandocPure Blocks))
-  || s `Set.member` treatAsBlock
-
-treatAsBlock :: Set.Set Text
-treatAsBlock = Set.fromList
-   [ "let", "def", "DeclareRobustCommand"
-   , "newcommand", "renewcommand"
-   , "newenvironment", "renewenvironment"
-   , "providecommand", "provideenvironment"
-     -- newcommand, etc. should be parsed by macroDef, but we need this
-     -- here so these aren't parsed as inline commands to ignore
-   , "special", "pdfannot", "pdfstringdef"
-   , "bibliographystyle"
-   , "maketitle", "makeindex", "makeglossary"
-   , "addcontentsline", "addtocontents", "addtocounter"
-      -- \ignore{} is used conventionally in literate haskell for definitions
-      -- that are to be processed by the compiler but not printed.
-   , "ignore"
-   , "hyperdef"
-   , "markboth", "markright", "markleft"
-   , "hspace", "vspace"
-   , "newpage"
-   , "clearpage"
-   , "pagebreak"
-   , "titleformat"
-   ]
-
-isInlineCommand :: Text -> Bool
-isInlineCommand s =
-  s `M.member` (inlineCommands :: M.Map Text (LP PandocPure Inlines))
-  || s `Set.member` treatAsInline
-
-treatAsInline :: Set.Set Text
-treatAsInline = Set.fromList
-  [ "index"
-  , "hspace"
-  , "vspace"
-  , "noindent"
-  , "newpage"
-  , "clearpage"
-  , "pagebreak"
-  ]
-
-dolabel :: PandocMonad m => LP m Inlines
-dolabel = do
-  v <- braced
-  let refstr = toksToString v
-  return $ spanWith (refstr,[],[("label", refstr)])
-    $ inBrackets $ str $ toksToString v
-
-doref :: PandocMonad m => String -> LP m Inlines
-doref cls = do
-  v <- braced
-  let refstr = toksToString v
-  return $ linkWith ("",[],[ ("reference-type", cls)
-                           , ("reference", refstr)])
-                    ('#':refstr)
-                    ""
-                    (inBrackets $ str refstr)
-
-lookupListDefault :: (Show k, Ord k) => v -> [k] -> M.Map k v -> v
-lookupListDefault d = (fromMaybe d .) . lookupList
-  where lookupList l m = msum $ map (`M.lookup` m) l
-
-inline :: PandocMonad m => LP m Inlines
-inline = (mempty <$ comment)
-     <|> (space  <$ whitespace)
-     <|> (softbreak <$ endline)
-     <|> word
-     <|> inlineCommand'
-     <|> inlineEnvironment
-     <|> inlineGroup
-     <|> (symbol '-' *>
-           option (str "-") (symbol '-' *>
-             option (str "–") (str "—" <$ symbol '-')))
-     <|> doubleQuote
-     <|> singleQuote
-     <|> (str "”" <$ try (symbol '\'' >> symbol '\''))
-     <|> (str "”" <$ symbol '”')
-     <|> (str "’" <$ symbol '\'')
-     <|> (str "’" <$ symbol '’')
-     <|> (str "\160" <$ symbol '~')
-     <|> dollarsMath
-     <|> (guardEnabled Ext_literate_haskell *> symbol '|' *> doLHSverb)
-     <|> (str . (:[]) <$> primEscape)
-     <|> regularSymbol
-     <|> (do res <- symbolIn "#^'`\"[]&"
-             pos <- getPosition
-             let s = T.unpack (untoken res)
-             report $ ParsingUnescaped s pos
-             return $ str s)
-
-inlines :: PandocMonad m => LP m Inlines
-inlines = mconcat <$> many inline
-
--- block elements:
-
-begin_ :: PandocMonad m => Text -> LP m ()
-begin_ t = try (do
-  controlSeq "begin"
-  spaces
-  txt <- untokenize <$> braced
-  guard (t == txt)) <?> ("\\begin{" ++ T.unpack t ++ "}")
-
-end_ :: PandocMonad m => Text -> LP m ()
-end_ t = try (do
-  controlSeq "end"
-  spaces
-  txt <- untokenize <$> braced
-  guard $ t == txt) <?> ("\\end{" ++ T.unpack t ++ "}")
-
-preamble :: PandocMonad m => LP m Blocks
-preamble = mempty <$ many preambleBlock
-  where preambleBlock =  spaces1
-                     <|> void include
-                     <|> void macroDef
-                     <|> void blockCommand
-                     <|> void braced
-                     <|> (notFollowedBy (begin_ "document") >> void anyTok)
-
-paragraph :: PandocMonad m => LP m Blocks
-paragraph = do
-  x <- trimInlines . mconcat <$> many1 inline
-  if x == mempty
-     then return mempty
-     else return $ para x
-
-include :: PandocMonad m => LP m Blocks
-include = do
-  (Tok _ (CtrlSeq name) _) <-
-                    controlSeq "include" <|> controlSeq "input" <|>
-                    controlSeq "subfile" <|> controlSeq "usepackage"
-  skipMany opt
-  fs <- (map (T.unpack . removeDoubleQuotes . T.strip) . T.splitOn "," .
-         untokenize) <$> braced
-  let fs' = if name == "usepackage"
-               then map (maybeAddExtension ".sty") fs
-               else map (maybeAddExtension ".tex") fs
-  dirs <- (splitBy (==':') . fromMaybe ".") <$> lookupEnv "TEXINPUTS"
-  mapM_ (insertIncluded dirs) fs'
-  return mempty
-
-insertIncluded :: PandocMonad m
-               => [FilePath]
-               -> FilePath
-               -> LP m ()
-insertIncluded dirs f = do
-  pos <- getPosition
-  containers <- getIncludeFiles <$> getState
-  when (f `elem` containers) $
-    throwError $ PandocParseError $ "Include file loop at " ++ show pos
-  updateState $ addIncludeFile f
-  mbcontents <- readFileFromDirs dirs f
-  contents <- case mbcontents of
-                   Just s -> return s
-                   Nothing -> do
-                     report $ CouldNotLoadIncludeFile f pos
-                     return ""
-  getInput >>= setInput . (tokenize f (T.pack contents) ++)
-  updateState dropLatestIncludeFile
-
-maybeAddExtension :: String -> FilePath -> FilePath
-maybeAddExtension ext fp =
-  if null (takeExtension fp)
-     then addExtension fp ext
-     else fp
-
-addMeta :: PandocMonad m => ToMetaValue a => String -> a -> LP m ()
-addMeta field val = updateState $ \st ->
-   st{ sMeta = addMetaField field val $ sMeta st }
-
-authors :: PandocMonad m => LP m ()
-authors = try $ do
-  bgroup
-  let oneAuthor = mconcat <$>
-       many1 (notFollowedBy' (controlSeq "and") >>
-               (inline <|> mempty <$ blockCommand))
-               -- skip e.g. \vspace{10pt}
-  auths <- sepBy oneAuthor (controlSeq "and")
-  egroup
-  addMeta "author" (map trimInlines auths)
-
-macroDef :: PandocMonad m => LP m Blocks
-macroDef =
-  mempty <$ ((commandDef <|> environmentDef) <* doMacros 0)
-  where commandDef = do
-          (name, macro') <- newcommand <|> letmacro <|> defmacro
-          guardDisabled Ext_latex_macros <|>
-           updateState (\s -> s{ sMacros = M.insert name macro' (sMacros s) })
-        environmentDef = do
-          (name, macro1, macro2) <- newenvironment
-          guardDisabled Ext_latex_macros <|>
-            do updateState $ \s -> s{ sMacros =
-                M.insert name macro1 (sMacros s) }
-               updateState $ \s -> s{ sMacros =
-                M.insert ("end" <> name) macro2 (sMacros s) }
-        -- @\newenvironment{envname}[n-args][default]{begin}{end}@
-        -- is equivalent to
-        -- @\newcommand{\envname}[n-args][default]{begin}@
-        -- @\newcommand{\endenvname}@
-
-letmacro :: PandocMonad m => LP m (Text, Macro)
-letmacro = do
-  controlSeq "let"
-  Tok _ (CtrlSeq name) _ <- anyControlSeq
-  optional $ symbol '='
-  spaces
-  contents <- bracedOrToken
-  return (name, Macro ExpandWhenDefined 0 Nothing contents)
-
-defmacro :: PandocMonad m => LP m (Text, Macro)
-defmacro = try $ do
-  controlSeq "def"
-  Tok _ (CtrlSeq name) _ <- anyControlSeq
-  numargs <- option 0 $ argSeq 1
-  -- we use withVerbatimMode, because macros are to be expanded
-  -- at point of use, not point of definition
-  contents <- withVerbatimMode bracedOrToken
-  return (name, Macro ExpandWhenUsed numargs Nothing contents)
-
--- Note: we don't yet support fancy things like #1.#2
-argSeq :: PandocMonad m => Int -> LP m Int
-argSeq n = do
-  Tok _ (Arg i) _ <- satisfyTok isArgTok
-  guard $ i == n
-  argSeq (n+1) <|> return n
-
-isArgTok :: Tok -> Bool
-isArgTok (Tok _ (Arg _) _) = True
-isArgTok _                 = False
-
-bracedOrToken :: PandocMonad m => LP m [Tok]
-bracedOrToken = braced <|> ((:[]) <$> (anyControlSeq <|> singleChar))
-
-newcommand :: PandocMonad m => LP m (Text, Macro)
-newcommand = do
-  pos <- getPosition
-  Tok _ (CtrlSeq mtype) _ <- controlSeq "newcommand" <|>
-                             controlSeq "renewcommand" <|>
-                             controlSeq "providecommand" <|>
-                             controlSeq "DeclareRobustCommand"
-  optional $ symbol '*'
-  Tok _ (CtrlSeq name) txt <- withVerbatimMode $ anyControlSeq <|>
-    (symbol '{' *> spaces *> anyControlSeq <* spaces <* symbol '}')
-  spaces
-  numargs <- option 0 $ try bracketedNum
-  spaces
-  optarg <- option Nothing $ Just <$> try bracketedToks
-  spaces
-  contents <- withVerbatimMode bracedOrToken
-  when (mtype == "newcommand") $ do
-    macros <- sMacros <$> getState
-    case M.lookup name macros of
-         Just _  -> report $ MacroAlreadyDefined (T.unpack txt) pos
-         Nothing -> return ()
-  return (name, Macro ExpandWhenUsed numargs optarg contents)
-
-newenvironment :: PandocMonad m => LP m (Text, Macro, Macro)
-newenvironment = do
-  pos <- getPosition
-  Tok _ (CtrlSeq mtype) _ <- controlSeq "newenvironment" <|>
-                             controlSeq "renewenvironment" <|>
-                             controlSeq "provideenvironment"
-  optional $ symbol '*'
-  spaces
-  name <- untokenize <$> braced
-  spaces
-  numargs <- option 0 $ try bracketedNum
-  spaces
-  optarg <- option Nothing $ Just <$> try bracketedToks
-  spaces
-  startcontents <- withVerbatimMode bracedOrToken
-  spaces
-  endcontents <- withVerbatimMode bracedOrToken
-  when (mtype == "newenvironment") $ do
-    macros <- sMacros <$> getState
-    case M.lookup name macros of
-         Just _  -> report $ MacroAlreadyDefined (T.unpack name) pos
-         Nothing -> return ()
-  return (name, Macro ExpandWhenUsed numargs optarg startcontents,
-             Macro ExpandWhenUsed 0 Nothing endcontents)
-
-bracketedToks :: PandocMonad m => LP m [Tok]
-bracketedToks = do
-  symbol '['
-  mconcat <$> manyTill (braced <|> (:[]) <$> anyTok) (symbol ']')
-
-bracketedNum :: PandocMonad m => LP m Int
-bracketedNum = do
-  ds <- untokenize <$> bracketedToks
-  case safeRead (T.unpack ds) of
-       Just i -> return i
-       _      -> return 0
-
-setCaption :: PandocMonad m => LP m Blocks
-setCaption = do
-  ils <- tok
-  mblabel <- option Nothing $
-               try $ spaces >> controlSeq "label" >> (Just <$> tok)
-  let ils' = case mblabel of
-                  Just lab -> ils <> spanWith
-                                ("",[],[("label", stringify lab)]) mempty
-                  Nothing  -> ils
-  updateState $ \st -> st{ sCaption = Just ils' }
-  return mempty
-
-looseItem :: PandocMonad m => LP m Blocks
-looseItem = do
-  inListItem <- sInListItem <$> getState
-  guard $ not inListItem
-  skipopts
-  return mempty
-
-resetCaption :: PandocMonad m => LP m ()
-resetCaption = updateState $ \st -> st{ sCaption = Nothing }
-
-section :: PandocMonad m => Bool -> Attr -> Int -> LP m Blocks
-section starred (ident, classes, kvs) lvl = do
-  skipopts
-  contents <- grouped inline
-  lab <- option ident $
-          try (spaces >> controlSeq "label"
-               >> spaces >> toksToString <$> braced)
-  let classes' = if starred then "unnumbered" : classes else classes
-  unless starred $ do
-    hn <- sLastHeaderNum <$> getState
-    let num = incrementHeaderNum lvl hn
-    updateState $ \st -> st{ sLastHeaderNum = num }
-    updateState $ \st -> st{ sLabels = M.insert lab
-                            [Str (renderHeaderNum num)]
-                            (sLabels st) }
-  attr' <- registerHeader (lab, classes', kvs) contents
-  return $ headerWith attr' lvl contents
-
-blockCommand :: PandocMonad m => LP m Blocks
-blockCommand = try $ do
-  Tok _ (CtrlSeq name) txt <- anyControlSeq
-  guard $ name /= "begin" && name /= "end"
-  star <- option "" ("*" <$ symbol '*' <* optional sp)
-  let name' = name <> star
-  let names = ordNub [name', name]
-  let rawDefiniteBlock = do
-        guard $ isBlockCommand name
-        rawBlock "latex" <$> getRawCommand name (txt <> star)
-  -- heuristic:  if it could be either block or inline, we
-  -- treat it if block if we have a sequence of block
-  -- commands followed by a newline.  But we stop if we
-  -- hit a \startXXX, since this might start a raw ConTeXt
-  -- environment (this is important because this parser is
-  -- used by the Markdown reader).
-  let startCommand = try $ do
-        Tok _ (CtrlSeq n) _ <- anyControlSeq
-        guard $ "start" `T.isPrefixOf` n
-  let rawMaybeBlock = try $ do
-        guard $ not $ isInlineCommand name
-        curr <- rawBlock "latex" <$> getRawCommand name (txt <> star)
-        rest <- many $ notFollowedBy startCommand *> blockCommand
-        lookAhead $ blankline <|> startCommand
-        return $ curr <> mconcat rest
-  let raw = rawDefiniteBlock <|> rawMaybeBlock
-  lookupListDefault raw names blockCommands
-
-closing :: PandocMonad m => LP m Blocks
-closing = do
-  contents <- tok
-  st <- getState
-  let extractInlines (MetaBlocks [Plain ys]) = ys
-      extractInlines (MetaBlocks [Para ys ]) = ys
-      extractInlines _                       = []
-  let sigs = case lookupMeta "author" (sMeta st) of
-                  Just (MetaList xs) ->
-                    para $ trimInlines $ fromList $
-                      intercalate [LineBreak] $ map extractInlines xs
-                  _ -> mempty
-  return $ para (trimInlines contents) <> sigs
-
-blockCommands :: PandocMonad m => M.Map Text (LP m Blocks)
-blockCommands = M.fromList $
-   [ ("par", mempty <$ skipopts)
-   , ("parbox",  skipopts >> braced >> grouped blocks)
-   , ("title", mempty <$ (skipopts *>
-                             (grouped inline >>= addMeta "title")
-                         <|> (grouped block >>= addMeta "title")))
-   , ("subtitle", mempty <$ (skipopts *> tok >>= addMeta "subtitle"))
-   , ("author", mempty <$ (skipopts *> authors))
-   -- -- in letter class, temp. store address & sig as title, author
-   , ("address", mempty <$ (skipopts *> tok >>= addMeta "address"))
-   , ("signature", mempty <$ (skipopts *> authors))
-   , ("date", mempty <$ (skipopts *> tok >>= addMeta "date"))
-   -- Koma-script metadata commands
-   , ("dedication", mempty <$ (skipopts *> tok >>= addMeta "dedication"))
-   -- sectioning
-   , ("part", section False nullAttr (-1))
-   , ("part*", section True nullAttr (-1))
-   , ("chapter", section False nullAttr 0)
-   , ("chapter*", section True ("",["unnumbered"],[]) 0)
-   , ("section", section False nullAttr 1)
-   , ("section*", section True ("",["unnumbered"],[]) 1)
-   , ("subsection", section False nullAttr 2)
-   , ("subsection*", section True ("",["unnumbered"],[]) 2)
-   , ("subsubsection", section False nullAttr 3)
-   , ("subsubsection*", section True ("",["unnumbered"],[]) 3)
-   , ("paragraph", section False nullAttr 4)
-   , ("paragraph*", section True ("",["unnumbered"],[]) 4)
-   , ("subparagraph", section False nullAttr 5)
-   , ("subparagraph*", section True ("",["unnumbered"],[]) 5)
-   -- beamer slides
-   , ("frametitle", section False nullAttr 3)
-   , ("framesubtitle", section False nullAttr 4)
-   -- letters
-   , ("opening", (para . trimInlines) <$> (skipopts *> tok))
-   , ("closing", skipopts *> closing)
-   -- memoir
-   , ("plainbreak", braced >> pure horizontalRule)
-   , ("plainbreak*", braced >> pure horizontalRule)
-   , ("fancybreak", braced >> pure horizontalRule)
-   , ("fancybreak*", braced >> pure horizontalRule)
-   , ("plainfancybreak", braced >> braced >> braced >> pure horizontalRule)
-   , ("plainfancybreak*", braced >> braced >> braced >> pure horizontalRule)
-   , ("pfbreak", pure horizontalRule)
-   , ("pfbreak*", pure horizontalRule)
-   --
-   , ("hrule", pure horizontalRule)
-   , ("strut", pure mempty)
-   , ("rule", skipopts *> tok *> tok *> pure horizontalRule)
-   , ("item", looseItem)
-   , ("documentclass", skipopts *> braced *> preamble)
-   , ("centerline", (para . trimInlines) <$> (skipopts *> tok))
-   , ("caption", skipopts *> setCaption)
-   , ("bibliography", mempty <$ (skipopts *> braced >>=
-         addMeta "bibliography" . splitBibs . toksToString))
-   , ("addbibresource", mempty <$ (skipopts *> braced >>=
-         addMeta "bibliography" . splitBibs . toksToString))
-   -- includes
-   , ("lstinputlisting", inputListing)
-   , ("graphicspath", graphicsPath)
-   -- polyglossia
-   , ("setdefaultlanguage", setDefaultLanguage)
-   , ("setmainlanguage", setDefaultLanguage)
-   -- hyperlink
-   , ("hypertarget", hypertargetBlock)
-   -- LaTeX colors
-   , ("textcolor", coloredBlock "color")
-   , ("colorbox", coloredBlock "background-color")
-   ]
-
-
-environments :: PandocMonad m => M.Map Text (LP m Blocks)
-environments = M.fromList
-   [ ("document", env "document" blocks)
-   , ("abstract", mempty <$ (env "abstract" blocks >>= addMeta "abstract"))
-   , ("letter", env "letter" letterContents)
-   , ("minipage", env "minipage" $
-          skipopts *> spaces *> optional braced *> spaces *> blocks)
-   , ("figure", env "figure" $ skipopts *> figure)
-   , ("subfigure", env "subfigure" $ skipopts *> tok *> figure)
-   , ("center", env "center" blocks)
-   , ("longtable",  env "longtable" $
-          resetCaption *> simpTable "longtable" False >>= addTableCaption)
-   , ("table",  env "table" $
-          resetCaption *> skipopts *> blocks >>= addTableCaption)
-   , ("tabular*", env "tabular" $ simpTable "tabular*" True)
-   , ("tabularx", env "tabularx" $ simpTable "tabularx" True)
-   , ("tabular", env "tabular"  $ simpTable "tabular" False)
-   , ("quote", blockQuote <$> env "quote" blocks)
-   , ("quotation", blockQuote <$> env "quotation" blocks)
-   , ("verse", blockQuote <$> env "verse" blocks)
-   , ("itemize", bulletList <$> listenv "itemize" (many item))
-   , ("description", definitionList <$> listenv "description" (many descItem))
-   , ("enumerate", orderedList')
-   , ("alltt", alltt <$> env "alltt" blocks)
-   , ("code", guardEnabled Ext_literate_haskell *>
-       (codeBlockWith ("",["sourceCode","literate","haskell"],[]) <$>
-         verbEnv "code"))
-   , ("comment", mempty <$ verbEnv "comment")
-   , ("verbatim", codeBlock <$> verbEnv "verbatim")
-   , ("Verbatim", fancyverbEnv "Verbatim")
-   , ("BVerbatim", fancyverbEnv "BVerbatim")
-   , ("lstlisting", do attr <- parseListingsOptions <$> option [] keyvals
-                       codeBlockWith attr <$> verbEnv "lstlisting")
-   , ("minted", minted)
-   , ("obeylines", obeylines)
-   , ("displaymath", mathEnvWith para Nothing "displaymath")
-   , ("equation", mathEnvWith para Nothing "equation")
-   , ("equation*", mathEnvWith para Nothing "equation*")
-   , ("gather", mathEnvWith para (Just "gathered") "gather")
-   , ("gather*", mathEnvWith para (Just "gathered") "gather*")
-   , ("multline", mathEnvWith para (Just "gathered") "multline")
-   , ("multline*", mathEnvWith para (Just "gathered") "multline*")
-   , ("eqnarray", mathEnvWith para (Just "aligned") "eqnarray")
-   , ("eqnarray*", mathEnvWith para (Just "aligned") "eqnarray*")
-   , ("align", mathEnvWith para (Just "aligned") "align")
-   , ("align*", mathEnvWith para (Just "aligned") "align*")
-   , ("alignat", mathEnvWith para (Just "aligned") "alignat")
-   , ("alignat*", mathEnvWith para (Just "aligned") "alignat*")
-   , ("tikzpicture", rawVerbEnv "tikzpicture")
-   -- etoolbox
-   , ("ifstrequal", ifstrequal)
-   , ("newtoggle", braced >>= newToggle)
-   , ("toggletrue", braced >>= setToggle True)
-   , ("togglefalse", braced >>= setToggle False)
-   , ("iftoggle", try $ ifToggle >> block)
-   ]
-
-environment :: PandocMonad m => LP m Blocks
-environment = do
-  controlSeq "begin"
-  name <- untokenize <$> braced
-  M.findWithDefault mzero name environments
-    <|> rawEnv name
-
-env :: PandocMonad m => Text -> LP m a -> LP m a
-env name p = p <* end_ name
-
-rawEnv :: PandocMonad m => Text -> LP m Blocks
-rawEnv name = do
-  exts <- getOption readerExtensions
-  let parseRaw = extensionEnabled Ext_raw_tex exts
-  rawOptions <- mconcat <$> many rawopt
-  let beginCommand = "\\begin{" <> name <> "}" <> rawOptions
-  pos1 <- getPosition
-  (bs, raw) <- withRaw $ env name blocks
-  if parseRaw
-     then return $ rawBlock "latex"
-                 $ T.unpack $ beginCommand <> untokenize raw
-     else do
-       report $ SkippedContent (T.unpack beginCommand) pos1
-       pos2 <- getPosition
-       report $ SkippedContent ("\\end{" ++ T.unpack name ++ "}") pos2
-       return bs
-
-rawVerbEnv :: PandocMonad m => Text -> LP m Blocks
-rawVerbEnv name = do
-  pos <- getPosition
-  (_, raw) <- withRaw $ verbEnv name
-  let raw' = "\\begin{tikzpicture}" ++ toksToString raw
-  exts <- getOption readerExtensions
-  let parseRaw = extensionEnabled Ext_raw_tex exts
-  if parseRaw
-     then return $ rawBlock "latex" raw'
-     else do
-       report $ SkippedContent raw' pos
-       return mempty
-
-verbEnv :: PandocMonad m => Text -> LP m String
-verbEnv name = withVerbatimMode $ do
-  skipopts
-  optional blankline
-  res <- manyTill anyTok (end_ name)
-  return $ stripTrailingNewlines $ toksToString res
-
-fancyverbEnv :: PandocMonad m => Text -> LP m Blocks
-fancyverbEnv name = do
-  options <- option [] keyvals
-  let kvs = [ (if k == "firstnumber"
-                  then "startFrom"
-                  else k, v) | (k,v) <- options ]
-  let classes = [ "numberLines" |
-                  lookup "numbers" options == Just "left" ]
-  let attr = ("",classes,kvs)
-  codeBlockWith attr <$> verbEnv name
-
-obeylines :: PandocMonad m => LP m Blocks
-obeylines =
-  para . fromList . removeLeadingTrailingBreaks .
-   walk softBreakToHard . toList <$> env "obeylines" inlines
-  where softBreakToHard SoftBreak = LineBreak
-        softBreakToHard x         = x
-        removeLeadingTrailingBreaks = reverse . dropWhile isLineBreak .
-                                      reverse . dropWhile isLineBreak
-        isLineBreak LineBreak = True
-        isLineBreak _         = False
-
-minted :: PandocMonad m => LP m Blocks
-minted = do
-  options <- option [] keyvals
-  lang <- toksToString <$> braced
-  let kvs = [ (if k == "firstnumber"
-                  then "startFrom"
-                  else k, v) | (k,v) <- options ]
-  let classes = [ lang | not (null lang) ] ++
-                [ "numberLines" |
-                  lookup "linenos" options == Just "true" ]
-  let attr = ("",classes,kvs)
-  codeBlockWith attr <$> verbEnv "minted"
-
-letterContents :: PandocMonad m => LP m Blocks
-letterContents = do
-  bs <- blocks
-  st <- getState
-  -- add signature (author) and address (title)
-  let addr = case lookupMeta "address" (sMeta st) of
-                  Just (MetaBlocks [Plain xs]) ->
-                     para $ trimInlines $ fromList xs
-                  _ -> mempty
-  return $ addr <> bs -- sig added by \closing
-
-figure :: PandocMonad m => LP m Blocks
-figure = try $ do
-  resetCaption
-  blocks >>= addImageCaption
-
-addImageCaption :: PandocMonad m => Blocks -> LP m Blocks
-addImageCaption = walkM go
-  where go (Image attr alt (src,tit))
-            | not ("fig:" `isPrefixOf` tit) = do
-          mbcapt <- sCaption <$> getState
-          return $ case mbcapt of
-               Just ils -> Image attr (toList ils) (src, "fig:" ++ tit)
-               Nothing  -> Image attr alt (src,tit)
-        go x = return x
-
-coloredBlock :: PandocMonad m => String -> LP m Blocks
-coloredBlock stylename = try $ do
-  skipopts
-  color <- braced
-  notFollowedBy (grouped inline)
-  let constructor = divWith ("",[],[("style",stylename ++ ": " ++ toksToString color)])
-  constructor <$> grouped block
-
-graphicsPath :: PandocMonad m => LP m Blocks
-graphicsPath = do
-  ps <- map toksToString <$> (bgroup *> manyTill braced egroup)
-  getResourcePath >>= setResourcePath . (++ ps)
-  return mempty
-
-splitBibs :: String -> [Inlines]
-splitBibs = map (str . flip replaceExtension "bib" . trim) . splitBy (==',')
-
-alltt :: Blocks -> Blocks
-alltt = walk strToCode
-  where strToCode (Str s)   = Code nullAttr s
-        strToCode Space     = RawInline (Format "latex") "\\ "
-        strToCode SoftBreak = LineBreak
-        strToCode x         = x
-
-parseListingsOptions :: [(String, String)] -> Attr
-parseListingsOptions options =
-  let kvs = [ (if k == "firstnumber"
-                  then "startFrom"
-                  else k, v) | (k,v) <- options ]
-      classes = [ "numberLines" |
-                  lookup "numbers" options == Just "left" ]
-             ++ maybeToList (lookup "language" options
-                     >>= fromListingsLanguage)
-  in  (fromMaybe "" (lookup "label" options), classes, kvs)
-
-inputListing :: PandocMonad m => LP m Blocks
-inputListing = do
-  pos <- getPosition
-  options <- option [] keyvals
-  f <- filter (/='"') . toksToString <$> braced
-  dirs <- (splitBy (==':') . fromMaybe ".") <$> lookupEnv "TEXINPUTS"
-  mbCode <- readFileFromDirs dirs f
-  codeLines <- case mbCode of
-                      Just s -> return $ lines s
-                      Nothing -> do
-                        report $ CouldNotLoadIncludeFile f pos
-                        return []
-  let (ident,classes,kvs) = parseListingsOptions options
-  let language = case lookup "language" options >>= fromListingsLanguage of
-                      Just l -> [l]
-                      Nothing -> take 1 $ languagesByExtension (takeExtension f)
-  let firstline = fromMaybe 1 $ lookup "firstline" options >>= safeRead
-  let lastline = fromMaybe (length codeLines) $
-                       lookup "lastline" options >>= safeRead
-  let codeContents = intercalate "\n" $ take (1 + lastline - firstline) $
-                       drop (firstline - 1) codeLines
-  return $ codeBlockWith (ident,ordNub (classes ++ language),kvs) codeContents
-
--- lists
-
-item :: PandocMonad m => LP m Blocks
-item = void blocks *> controlSeq "item" *> skipopts *> blocks
-
-descItem :: PandocMonad m => LP m (Inlines, [Blocks])
-descItem = do
-  blocks -- skip blocks before item
-  controlSeq "item"
-  optional sp
-  ils <- opt
-  bs <- blocks
-  return (ils, [bs])
-
-listenv :: PandocMonad m => Text -> LP m a -> LP m a
-listenv name p = try $ do
-  oldInListItem <- sInListItem `fmap` getState
-  updateState $ \st -> st{ sInListItem = True }
-  res <- env name p
-  updateState $ \st -> st{ sInListItem = oldInListItem }
-  return res
-
-orderedList' :: PandocMonad m => LP m Blocks
-orderedList' = try $ do
-  spaces
-  let markerSpec = do
-        symbol '['
-        ts <- toksToString <$> manyTill anyTok (symbol ']')
-        case runParser anyOrderedListMarker def "option" ts of
-             Right r -> return r
-             Left _  -> do
-               pos <- getPosition
-               report $ SkippedContent ("[" ++ ts ++ "]") pos
-               return (1, DefaultStyle, DefaultDelim)
-  (_, style, delim) <- option (1, DefaultStyle, DefaultDelim) markerSpec
-  spaces
-  optional $ try $ controlSeq "setlength"
-                   *> grouped (count 1 $ controlSeq "itemindent")
-                   *> braced
-  spaces
-  start <- option 1 $ try $ do pos <- getPosition
-                               controlSeq "setcounter"
-                               ctr <- toksToString <$> braced
-                               guard $ "enum" `isPrefixOf` ctr
-                               guard $ all (`elem` ['i','v']) (drop 4 ctr)
-                               optional sp
-                               num <- toksToString <$> braced
-                               case safeRead num of
-                                    Just i -> return (i + 1 :: Int)
-                                    Nothing -> do
-                                      report $ SkippedContent
-                                        ("\\setcounter{" ++ ctr ++
-                                         "}{" ++ num ++ "}") pos
-                                      return 1
-  bs <- listenv "enumerate" (many item)
-  return $ orderedListWith (start, style, delim) bs
-
--- tables
-
-hline :: PandocMonad m => LP m ()
-hline = try $ do
-  spaces
-  controlSeq "hline" <|>
-    -- booktabs rules:
-    controlSeq "toprule" <|>
-    controlSeq "bottomrule" <|>
-    controlSeq "midrule" <|>
-    controlSeq "endhead" <|>
-    controlSeq "endfirsthead"
-  spaces
-  optional opt
-  return ()
-
-lbreak :: PandocMonad m => LP m Tok
-lbreak = (controlSeq "\\" <|> controlSeq "tabularnewline") <* spaces
-
-amp :: PandocMonad m => LP m Tok
-amp = symbol '&'
-
--- Split a Word into individual Symbols (for parseAligns)
-splitWordTok :: PandocMonad m => LP m ()
-splitWordTok = do
-  inp <- getInput
-  case inp of
-       (Tok spos Word t : rest) ->
-         setInput $ map (Tok spos Symbol . T.singleton) (T.unpack t) ++ rest
-       _ -> return ()
-
-parseAligns :: PandocMonad m => LP m [(Alignment, Double, ([Tok], [Tok]))]
-parseAligns = try $ do
-  let maybeBar = skipMany $
-        sp <|> () <$ symbol '|' <|> () <$ (symbol '@' >> braced)
-  let cAlign = AlignCenter <$ symbol 'c'
-  let lAlign = AlignLeft <$ symbol 'l'
-  let rAlign = AlignRight <$ symbol 'r'
-  let parAlign = AlignLeft <$ symbol 'p'
-  -- aligns from tabularx
-  let xAlign = AlignLeft <$ symbol 'X'
-  let mAlign = AlignLeft <$ symbol 'm'
-  let bAlign = AlignLeft <$ symbol 'b'
-  let alignChar = splitWordTok *> (  cAlign <|> lAlign <|> rAlign <|> parAlign
-                                 <|> xAlign <|> mAlign <|> bAlign )
-  let alignPrefix = symbol '>' >> braced
-  let alignSuffix = symbol '<' >> braced
-  let colWidth = try $ do
-        symbol '{'
-        ds <- trim . toksToString <$> manyTill anyTok (controlSeq "linewidth")
-        spaces
-        symbol '}'
-        case safeRead ds of
-              Just w  -> return w
-              Nothing -> return 0.0
-  let alignSpec = do
-        pref <- option [] alignPrefix
-        spaces
-        al <- alignChar
-        width <- colWidth <|> option 0.0 (do s <- toksToString <$> braced
-                                             pos <- getPosition
-                                             report $ SkippedContent s pos
-                                             return 0.0)
-        spaces
-        suff <- option [] alignSuffix
-        return (al, width, (pref, suff))
-  let starAlign = do -- '*{2}{r}' == 'rr', we just expand like a macro
-        symbol '*'
-        spaces
-        ds <- trim . toksToString <$> braced
-        spaces
-        spec <- braced
-        case safeRead ds of
-             Just n  -> do
-               getInput >>= setInput . (mconcat (replicate n spec) ++)
-             Nothing -> fail $ "Could not parse " ++ ds ++ " as number"
-  bgroup
-  spaces
-  maybeBar
-  aligns' <- many $ try $ spaces >> optional starAlign >>
-                            (alignSpec <* maybeBar)
-  spaces
-  egroup
-  spaces
-  return aligns'
-
-parseTableRow :: PandocMonad m
-              => Text   -- ^ table environment name
-              -> [([Tok], [Tok])] -- ^ pref/suffixes
-              -> LP m [Blocks]
-parseTableRow envname prefsufs = do
-  notFollowedBy (spaces *> end_ envname)
-  let cols = length prefsufs
-  -- add prefixes and suffixes in token stream:
-  let celltoks (pref, suff) = do
-        prefpos <- getPosition
-        contents <- many (notFollowedBy
-                         (() <$ amp <|> () <$ lbreak <|> end_ envname)
-                         >> anyTok)
-        suffpos <- getPosition
-        option [] (count 1 amp)
-        return $ map (setpos prefpos) pref ++ contents ++ map (setpos suffpos) suff
-  rawcells <- mapM celltoks prefsufs
-  oldInput <- getInput
-  cells <- mapM (\ts -> setInput ts >> parseTableCell) rawcells
-  setInput oldInput
-  spaces
-  let numcells = length cells
-  guard $ numcells <= cols && numcells >= 1
-  guard $ cells /= [mempty]
-  -- note:  a & b in a three-column table leaves an empty 3rd cell:
-  return $ cells ++ replicate (cols - numcells) mempty
-
-parseTableCell :: PandocMonad m => LP m Blocks
-parseTableCell = do
-  let plainify bs = case toList bs of
-                         [Para ils] -> plain (fromList ils)
-                         _          -> bs
-  updateState $ \st -> st{ sInTableCell = True }
-  cells <- plainify <$> blocks
-  updateState $ \st -> st{ sInTableCell = False }
-  return cells
-
-simpTable :: PandocMonad m => Text -> Bool -> LP m Blocks
-simpTable envname hasWidthParameter = try $ do
-  when hasWidthParameter $ () <$ (spaces >> tok)
-  skipopts
-  colspecs <- parseAligns
-  let (aligns, widths, prefsufs) = unzip3 colspecs
-  let cols = length colspecs
-  optional $ controlSeq "caption" *> skipopts *> setCaption
-  optional lbreak
-  spaces
-  skipMany hline
-  spaces
-  header' <- option [] $ try (parseTableRow envname prefsufs <*
-                                   lbreak <* many1 hline)
-  spaces
-  rows <- sepEndBy (parseTableRow envname prefsufs)
-                    (lbreak <* optional (skipMany hline))
-  spaces
-  optional $ controlSeq "caption" *> skipopts *> setCaption
-  optional lbreak
-  spaces
-  let header'' = if null header'
-                    then replicate cols mempty
-                    else header'
-  lookAhead $ controlSeq "end" -- make sure we're at end
-  return $ table mempty (zip aligns widths) header'' rows
-
-addTableCaption :: PandocMonad m => Blocks -> LP m Blocks
-addTableCaption = walkM go
-  where go (Table c als ws hs rs) = do
-          mbcapt <- sCaption <$> getState
-          return $ case mbcapt of
-               Just ils -> Table (toList ils) als ws hs rs
-               Nothing  -> Table c als ws hs rs
-        go x = return x
-
-
-block :: PandocMonad m => LP m Blocks
-block = (mempty <$ spaces1)
-    <|> environment
-    <|> include
-    <|> macroDef
-    <|> blockCommand
-    <|> paragraph
-    <|> grouped block
-
-blocks :: PandocMonad m => LP m Blocks
-blocks = mconcat <$> many block
-
-setDefaultLanguage :: PandocMonad m => LP m Blocks
-setDefaultLanguage = do
-  o <- option "" $ (T.unpack . T.filter (\c -> c /= '[' && c /= ']'))
-                <$> rawopt
-  polylang <- toksToString <$> braced
-  case M.lookup polylang polyglossiaLangToBCP47 of
-       Nothing -> return mempty -- TODO mzero? warning?
-       Just langFunc -> do
-         let l = langFunc o
-         setTranslations l
-         updateState $ setMeta "lang" $ str (renderLang l)
-         return mempty
-
-polyglossiaLangToBCP47 :: M.Map String (String -> Lang)
-polyglossiaLangToBCP47 = M.fromList
-  [ ("arabic", \o -> case filter (/=' ') o of
-       "locale=algeria"    -> Lang "ar" "" "DZ" []
-       "locale=mashriq"    -> Lang "ar" "" "SY" []
-       "locale=libya"      -> Lang "ar" "" "LY" []
-       "locale=morocco"    -> Lang "ar" "" "MA" []
-       "locale=mauritania" -> Lang "ar" "" "MR" []
-       "locale=tunisia"    -> Lang "ar" "" "TN" []
-       _                   -> Lang "ar" "" "" [])
-  , ("german", \o -> case filter (/=' ') o of
-       "spelling=old" -> Lang "de" "" "DE" ["1901"]
-       "variant=austrian,spelling=old"
-                       -> Lang "de" "" "AT" ["1901"]
-       "variant=austrian" -> Lang "de" "" "AT" []
-       "variant=swiss,spelling=old"
-                       -> Lang "de" "" "CH" ["1901"]
-       "variant=swiss" -> Lang "de" "" "CH" []
-       _ -> Lang "de" "" "" [])
-  , ("lsorbian", \_ -> Lang "dsb" "" "" [])
-  , ("greek", \o -> case filter (/=' ') o of
-       "variant=poly"    -> Lang "el" "" "polyton" []
-       "variant=ancient" -> Lang "grc" "" "" []
-       _                 -> Lang "el" "" "" [])
-  , ("english", \o -> case filter (/=' ') o of
-       "variant=australian" -> Lang "en" "" "AU" []
-       "variant=canadian"   -> Lang "en" "" "CA" []
-       "variant=british"    -> Lang "en" "" "GB" []
-       "variant=newzealand" -> Lang "en" "" "NZ" []
-       "variant=american"   -> Lang "en" "" "US" []
-       _                    -> Lang "en" "" "" [])
-  , ("usorbian", \_ -> Lang "hsb" "" "" [])
-  , ("latin", \o -> case filter (/=' ') o of
-       "variant=classic" -> Lang "la" "" "" ["x-classic"]
-       _                 -> Lang "la" "" "" [])
-  , ("slovenian", \_ -> Lang "sl" "" "" [])
-  , ("serbianc", \_ -> Lang "sr" "cyrl" "" [])
-  , ("pinyin", \_ -> Lang "zh" "Latn" "" ["pinyin"])
-  , ("afrikaans", \_ -> Lang "af" "" "" [])
-  , ("amharic", \_ -> Lang "am" "" "" [])
-  , ("assamese", \_ -> Lang "as" "" "" [])
-  , ("asturian", \_ -> Lang "ast" "" "" [])
-  , ("bulgarian", \_ -> Lang "bg" "" "" [])
-  , ("bengali", \_ -> Lang "bn" "" "" [])
-  , ("tibetan", \_ -> Lang "bo" "" "" [])
-  , ("breton", \_ -> Lang "br" "" "" [])
-  , ("catalan", \_ -> Lang "ca" "" "" [])
-  , ("welsh", \_ -> Lang "cy" "" "" [])
-  , ("czech", \_ -> Lang "cs" "" "" [])
-  , ("coptic", \_ -> Lang "cop" "" "" [])
-  , ("danish", \_ -> Lang "da" "" "" [])
-  , ("divehi", \_ -> Lang "dv" "" "" [])
-  , ("esperanto", \_ -> Lang "eo" "" "" [])
-  , ("spanish", \_ -> Lang "es" "" "" [])
-  , ("estonian", \_ -> Lang "et" "" "" [])
-  , ("basque", \_ -> Lang "eu" "" "" [])
-  , ("farsi", \_ -> Lang "fa" "" "" [])
-  , ("finnish", \_ -> Lang "fi" "" "" [])
-  , ("french", \_ -> Lang "fr" "" "" [])
-  , ("friulan", \_ -> Lang "fur" "" "" [])
-  , ("irish", \_ -> Lang "ga" "" "" [])
-  , ("scottish", \_ -> Lang "gd" "" "" [])
-  , ("ethiopic", \_ -> Lang "gez" "" "" [])
-  , ("galician", \_ -> Lang "gl" "" "" [])
-  , ("hebrew", \_ -> Lang "he" "" "" [])
-  , ("hindi", \_ -> Lang "hi" "" "" [])
-  , ("croatian", \_ -> Lang "hr" "" "" [])
-  , ("magyar", \_ -> Lang "hu" "" "" [])
-  , ("armenian", \_ -> Lang "hy" "" "" [])
-  , ("interlingua", \_ -> Lang "ia" "" "" [])
-  , ("indonesian", \_ -> Lang "id" "" "" [])
-  , ("icelandic", \_ -> Lang "is" "" "" [])
-  , ("italian", \_ -> Lang "it" "" "" [])
-  , ("japanese", \_ -> Lang "jp" "" "" [])
-  , ("khmer", \_ -> Lang "km" "" "" [])
-  , ("kurmanji", \_ -> Lang "kmr" "" "" [])
-  , ("kannada", \_ -> Lang "kn" "" "" [])
-  , ("korean", \_ -> Lang "ko" "" "" [])
-  , ("lao", \_ -> Lang "lo" "" "" [])
-  , ("lithuanian", \_ -> Lang "lt" "" "" [])
-  , ("latvian", \_ -> Lang "lv" "" "" [])
-  , ("malayalam", \_ -> Lang "ml" "" "" [])
-  , ("mongolian", \_ -> Lang "mn" "" "" [])
-  , ("marathi", \_ -> Lang "mr" "" "" [])
-  , ("dutch", \_ -> Lang "nl" "" "" [])
-  , ("nynorsk", \_ -> Lang "nn" "" "" [])
-  , ("norsk", \_ -> Lang "no" "" "" [])
-  , ("nko", \_ -> Lang "nqo" "" "" [])
-  , ("occitan", \_ -> Lang "oc" "" "" [])
-  , ("panjabi", \_ -> Lang "pa" "" "" [])
-  , ("polish", \_ -> Lang "pl" "" "" [])
-  , ("piedmontese", \_ -> Lang "pms" "" "" [])
-  , ("portuguese", \_ -> Lang "pt" "" "" [])
-  , ("romansh", \_ -> Lang "rm" "" "" [])
-  , ("romanian", \_ -> Lang "ro" "" "" [])
-  , ("russian", \_ -> Lang "ru" "" "" [])
-  , ("sanskrit", \_ -> Lang "sa" "" "" [])
-  , ("samin", \_ -> Lang "se" "" "" [])
-  , ("slovak", \_ -> Lang "sk" "" "" [])
-  , ("albanian", \_ -> Lang "sq" "" "" [])
-  , ("serbian", \_ -> Lang "sr" "" "" [])
-  , ("swedish", \_ -> Lang "sv" "" "" [])
-  , ("syriac", \_ -> Lang "syr" "" "" [])
-  , ("tamil", \_ -> Lang "ta" "" "" [])
-  , ("telugu", \_ -> Lang "te" "" "" [])
-  , ("thai", \_ -> Lang "th" "" "" [])
-  , ("turkmen", \_ -> Lang "tk" "" "" [])
-  , ("turkish", \_ -> Lang "tr" "" "" [])
-  , ("ukrainian", \_ -> Lang "uk" "" "" [])
-  , ("urdu", \_ -> Lang "ur" "" "" [])
-  , ("vietnamese", \_ -> Lang "vi" "" "" [])
-  ]
-
-babelLangToBCP47 :: String -> Maybe Lang
-babelLangToBCP47 s =
-  case s of
-       "austrian" -> Just $ Lang "de" "" "AT" ["1901"]
-       "naustrian" -> Just $ Lang "de" "" "AT" []
-       "swissgerman" -> Just $ Lang "de" "" "CH" ["1901"]
-       "nswissgerman" -> Just $ Lang "de" "" "CH" []
-       "german" -> Just $ Lang "de" "" "DE" ["1901"]
-       "ngerman" -> Just $ Lang "de" "" "DE" []
-       "lowersorbian" -> Just $ Lang "dsb" "" "" []
-       "uppersorbian" -> Just $ Lang "hsb" "" "" []
-       "polutonikogreek" -> Just $ Lang "el" "" "" ["polyton"]
-       "slovene" -> Just $ Lang "sl" "" "" []
-       "australian" -> Just $ Lang "en" "" "AU" []
-       "canadian" -> Just $ Lang "en" "" "CA" []
-       "british" -> Just $ Lang "en" "" "GB" []
-       "newzealand" -> Just $ Lang "en" "" "NZ" []
-       "american" -> Just $ Lang "en" "" "US" []
-       "classiclatin" -> Just $ Lang "la" "" "" ["x-classic"]
-       _ -> fmap ($ "") $ M.lookup s polyglossiaLangToBCP47
+{-# LANGUAGE OverloadedStrings     #-}
+{-# LANGUAGE PatternGuards         #-}
+{-# LANGUAGE ScopedTypeVariables   #-}
+{-# LANGUAGE ViewPatterns          #-}
+{- |
+   Module      : Text.Pandoc.Readers.LaTeX
+   Copyright   : Copyright (C) 2006-2024 John MacFarlane
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : John MacFarlane <jgm@berkeley.edu>
+   Stability   : alpha
+   Portability : portable
+
+Conversion of LaTeX to 'Pandoc' document.
+
+-}
+module Text.Pandoc.Readers.LaTeX ( readLaTeX,
+                                   applyMacros,
+                                   rawLaTeXInline,
+                                   rawLaTeXBlock,
+                                   inlineCommand
+                                 ) where
+
+import Control.Applicative (many, optional, (<|>))
+import Control.Monad
+import Control.Monad.Except (throwError)
+import Data.Containers.ListUtils (nubOrd)
+import Data.Char (isDigit, isLetter, isAlphaNum, toUpper, chr)
+import Data.Default
+import Data.List (intercalate)
+import qualified Data.Map as M
+import Data.Maybe (fromMaybe, maybeToList)
+import qualified Data.Set as Set
+import Data.Text (Text)
+import qualified Data.Text as T
+import Data.Either (partitionEithers)
+import Skylighting (defaultSyntaxMap)
+import System.FilePath (addExtension, replaceExtension, takeExtension)
+import Text.Collate.Lang (renderLang)
+import Text.Pandoc.Builder as B
+import Text.Pandoc.Class (PandocPure, PandocMonad (..), getResourcePath,
+                          readFileFromDirs, report,
+                          setResourcePath, getZonedTime)
+import Data.Time (ZonedTime(..), LocalTime(..), showGregorian)
+import Text.Pandoc.Error (PandocError (PandocParseError))
+import Text.Pandoc.Highlighting (languagesByExtension)
+import Text.Pandoc.ImageSize (numUnit, showFl)
+import Text.Pandoc.Logging
+import Text.Pandoc.Options
+import Text.Pandoc.Parsing hiding (blankline, many, mathDisplay, mathInline,
+                            optional, space, spaces, withRaw, (<|>))
+import Text.Pandoc.TeX (Tok (..), TokType (..))
+import Text.Pandoc.Readers.LaTeX.Parsing
+import Text.Pandoc.Readers.LaTeX.Citation (citationCommands, cites)
+import Text.Pandoc.Readers.LaTeX.Math (withMathMode, dollarsMath,
+                                       inlineEnvironments, inlineEnvironment,
+                                       mathDisplay, mathInline,
+                                       newtheorem, theoremstyle, proof,
+                                       theoremEnvironment)
+import Text.Pandoc.Readers.LaTeX.Table (tableEnvironments)
+import Text.Pandoc.Readers.LaTeX.Macro (macroDef)
+import Text.Pandoc.Readers.LaTeX.Lang (inlineLanguageCommands,
+                                       enquoteCommands,
+                                       babelLangToBCP47,
+                                       setDefaultLanguage)
+import Text.Pandoc.Readers.LaTeX.SIunitx (siunitxCommands)
+import Text.Pandoc.Readers.LaTeX.Inline (acronymCommands, refCommands,
+                                         nameCommands, charCommands,
+                                         accentCommands,
+                                         miscCommands,
+                                         biblatexInlineCommands,
+                                         verbCommands, rawInlineOr,
+                                         listingsLanguage)
+import Text.Pandoc.Shared
+import Text.Pandoc.Walk
+import Data.List.NonEmpty (nonEmpty)
+
+-- for debugging:
+-- import Text.Pandoc.Extensions (getDefaultExtensions)
+-- import Text.Pandoc.Class.PandocIO (runIOorExplode, PandocIO)
+-- import Debug.Trace (traceShowId)
+
+-- | Parse LaTeX from string and return 'Pandoc' document.
+readLaTeX :: (PandocMonad m, ToSources a)
+          => ReaderOptions -- ^ Reader options
+          -> a             -- ^ Input to parse
+          -> m Pandoc
+readLaTeX opts ltx = do
+  let sources = toSources ltx
+  parsed <- runParserT parseLaTeX def{ sOptions = opts } "source"
+               (TokStream False (tokenizeSources sources))
+  case parsed of
+    Right result -> return result
+    Left e       -> throwError $ fromParsecError sources e
+
+parseLaTeX :: PandocMonad m => LP m Pandoc
+parseLaTeX = do
+  bs <- blocks
+  eof
+  st <- getState
+  let meta = sMeta st
+  let doc' = doc bs
+  let headerLevel (Header n _ _) = [n]
+      headerLevel _              = []
+  let bottomLevel = maybe 1 minimum $ nonEmpty $ query headerLevel doc'
+  let adjustHeaders m (Header n attr ils) = Header (n+m) attr ils
+      adjustHeaders _ x                   = x
+  let (Pandoc _ bs') =
+       -- handle the case where you have \part or \chapter
+       (if bottomLevel < 1
+           then walk (adjustHeaders (1 - bottomLevel))
+           else id) $
+       walk (resolveFootnoteMarks (sFootnoteTexts st)) $
+       walk (resolveRefs (sLabels st)) doc'
+  return $ Pandoc meta bs'
+
+resolveRefs :: M.Map Text [Inline] -> Inline -> Inline
+resolveRefs labels x@(Link (ident,classes,kvs) _ _) =
+  case (T.takeWhile (/='+') <$> lookup "reference-type" kvs,
+        lookup "reference" kvs) of
+        (Just "ref", Just lab) -> -- TODO special treatment of ref+label
+          case M.lookup lab labels of
+               Just txt -> Link (ident,classes,kvs) txt ("#" <> lab, "")
+               Nothing  -> x
+        _ -> x
+resolveRefs _ x = x
+
+-- | Resolve footnote marks (\footnotemark) to actual notes using
+-- the footnote texts collected from \footnotetext commands.
+resolveFootnoteMarks :: M.Map Int Blocks -> Inline -> Inline
+resolveFootnoteMarks fnTexts (Span (_, classes, kvs) _)
+  | "footnote-mark" `elem` classes
+  , Just numText <- lookup "note-num" kvs
+  , [(n, "")] <- reads (T.unpack numText)
+  = case M.lookup n fnTexts of
+      Just contents -> Note (toList contents)
+      Nothing       -> Str ""  -- No matching footnotetext found
+resolveFootnoteMarks _ x = x
+
+
+-- testParser :: LP PandocIO a -> Text -> IO a
+-- testParser p t = do
+--   res <- runIOorExplode (runParserT p defaultLaTeXState{
+--             sOptions = def{ readerExtensions =
+--               enableExtension Ext_raw_tex $
+--                 getDefaultExtensions "latex" }} "source"
+--                   (tokenize (initialPos "source") t))
+--   case res of
+--        Left e  -> error (show e)
+--        Right r -> return r
+
+
+rawLaTeXBlock :: (PandocMonad m, HasMacros s, HasReaderOptions s)
+              => ParsecT Sources s m Text
+rawLaTeXBlock = do
+  lookAhead (try (char '\\' >> letter))
+  toks <- getInputTokens
+  snd <$> (
+          rawLaTeXParser toks
+             (makeAtLetterSection <|>
+              macroDef (const mempty) <|>
+              do choice (map controlSeq
+                   ["include", "input", "subfile", "usepackage"])
+                 skipMany opt
+                 braced
+                 return mempty) blocks
+      <|> rawLaTeXParser toks
+           (void (environment <|> blockCommand))
+           (mconcat <$> many (block <|> beginOrEndCommand)))
+
+makeAtLetterSection :: PandocMonad m => LP m ()
+makeAtLetterSection = try $ do
+  controlSeq "makeatletter"
+  void $ manyTill
+    (   whitespace
+    <|> newlineTok
+    <|> macroDef (const ())
+    <|> void environment
+    <|> void blockCommand
+    ) (controlSeq "makeatother")
+
+-- See #4667 for motivation; sometimes people write macros
+-- that just evaluate to a begin or end command, which blockCommand
+-- won't accept.
+beginOrEndCommand :: PandocMonad m => LP m Blocks
+beginOrEndCommand = try $ do
+  Tok _ (CtrlSeq name) txt <- anyControlSeq
+  guard $ name == "begin" || name == "end"
+  (envname, rawargs) <- withRaw braced
+  if M.member (untokenize envname)
+      (inlineEnvironments :: M.Map Text (LP PandocPure Inlines))
+     then mzero
+     else return $ rawBlock "latex"
+                    (txt <> untokenize rawargs)
+
+rawLaTeXInline :: (PandocMonad m, HasMacros s, HasReaderOptions s)
+               => ParsecT Sources s m Text
+rawLaTeXInline = do
+  lookAhead (try (char '\\' >> letter))
+  toks <- getInputTokens
+  raw <- snd <$>
+          (   rawLaTeXParser toks
+              (mempty <$ (controlSeq "input" >> skipMany rawopt >> braced))
+              inlines
+          <|> rawLaTeXParser toks (void inline) inlines
+          )
+  finalbraces <- mconcat <$> many (try (string "{}")) -- see #5439
+  return $ raw <> T.pack finalbraces
+
+inlineCommand :: PandocMonad m => ParsecT Sources ParserState m Inlines
+inlineCommand = do
+  lookAhead (try (char '\\' >> letter))
+  toks <- getInputTokens
+  fst <$> rawLaTeXParser toks (void (inlineEnvironment <|> inlineCommand'))
+          inlines
+
+-- inline elements:
+
+inlineGroup :: PandocMonad m => LP m Inlines
+inlineGroup = do
+  ils <- grouped inline
+  if null ils
+     then return mempty
+     else return $ spanWith nullAttr ils
+          -- we need the span so we can detitlecase bibtex entries;
+          -- we need to know when something is {C}apitalized
+
+doLHSverb :: PandocMonad m => LP m Inlines
+doLHSverb =
+  codeWith ("",["haskell"],[]) . untokenize
+    <$> manyTill (satisfyTok (not . isNewlineTok)) (symbol '|')
+
+mkImage :: PandocMonad m => [(Text, Text)] -> Text -> LP m Inlines
+mkImage options (T.unpack -> src) = do
+   let replaceRelative (k,v) =
+         case numUnit v of
+              Just (num, "\\textwidth") -> (k, showFl (num * 100) <> "%")
+              Just (num, "\\linewidth") -> (k, showFl (num * 100) <> "%")
+              Just (num, "\\textheight") -> (k, showFl (num * 100) <> "%")
+              _                         -> (k, v)
+   let kvs = map replaceRelative
+             $ filter (\(k,_) -> k `elem` ["width", "height"]) options
+   let attr = ("",[], kvs)
+   let alt = maybe (str "image") str $ lookup "alt" options
+   defaultExt <- getOption readerDefaultImageExtension
+   let exts' = [".pdf", ".png", ".jpg", ".mps", ".jpeg", ".jbig2", ".jb2"]
+   let exts  = exts' ++ map (map toUpper) exts'
+   let findFile s [] = return s
+       findFile s (e:es) = do
+         let s' = addExtension s e
+         exists <- fileExists s'
+         if exists
+            then return s'
+            else findFile s es
+   src' <- case takeExtension src of
+               "" | not (T.null defaultExt) -> return $ addExtension src $ T.unpack defaultExt
+                  | otherwise -> findFile src exts
+               _  -> return src
+   return $ imageWith attr (T.pack src') "" alt
+
+removeDoubleQuotes :: Text -> Text
+removeDoubleQuotes t =
+  Data.Maybe.fromMaybe t $ T.stripPrefix "\"" t >>= T.stripSuffix "\""
+
+doubleQuote :: PandocMonad m => LP m Inlines
+doubleQuote =
+       quoted' doubleQuoted (try $ count 2 $ symbol '`')
+                     (void $ try $ count 2 $ symbol '\'')
+   <|> quoted' doubleQuoted ((:[]) <$> symbol '“') (void $ symbol '”')
+   -- the following is used by babel for localized quotes:
+   <|> quoted' doubleQuoted (try $ sequence [symbol '"', symbol '`'])
+                            (void $ try $ sequence [symbol '"', symbol '\''])
+
+singleQuote :: PandocMonad m => LP m Inlines
+singleQuote =
+       quoted' singleQuoted ((:[]) <$> symbol '`')
+                     (try $ symbol '\'' >>
+                           notFollowedBy (satisfyTok startsWithLetter))
+   <|> quoted' singleQuoted ((:[]) <$> symbol '‘')
+                            (try $ symbol '’' >>
+                                  notFollowedBy (satisfyTok startsWithLetter))
+  where startsWithLetter (Tok _ Word t) =
+          case T.uncons t of
+               Just (c, _) | isLetter c -> True
+               _           -> False
+        startsWithLetter _ = False
+
+quoted' :: PandocMonad m
+        => (Inlines -> Inlines)
+        -> LP m [Tok]
+        -> LP m ()
+        -> LP m Inlines
+quoted' f starter ender = do
+  startchs <- untokenize <$> starter
+  smart <- extensionEnabled Ext_smart <$> getOption readerExtensions
+  if smart
+     then do
+       ils <- many (notFollowedBy ender >> inline)
+       (ender >> return (f (mconcat ils))) <|>
+            (<> mconcat ils) <$>
+                    lit (case startchs of
+                              "``" -> "“"
+                              "`"  -> "‘"
+                              cs   -> cs)
+     else lit startchs
+
+lit :: Text -> LP m Inlines
+lit = pure . str
+
+blockquote :: PandocMonad m => Bool -> Maybe Text -> LP m Blocks
+blockquote cvariant mblang = do
+  citepar <- if cvariant
+                then (\xs -> para (cite xs mempty))
+                       <$> cites inline NormalCitation False
+                else option mempty $ para <$> bracketed inline
+  let lang = mblang >>= babelLangToBCP47
+  let langdiv = case lang of
+                      Nothing -> id
+                      Just l  -> divWith ("",[],[("lang", renderLang l)])
+  _closingPunct <- option mempty $ bracketed inline -- currently ignored
+  bs <- grouped block
+  optional $ symbolIn (".:;?!" :: [Char])  -- currently ignored
+  return $ blockQuote . langdiv $ (bs <> citepar)
+
+inlineCommand' :: PandocMonad m => LP m Inlines
+inlineCommand' = try $ do
+  Tok _ (CtrlSeq name) cmd <- anyControlSeq
+  guard $ name /= "begin" && name /= "end" && name /= "and"
+  star <- if T.all isAlphaNum name
+             then option "" ("*" <$ symbol '*' <* sp)
+             else pure ""
+  overlay <- option "" overlaySpecification
+  let name' = name <> star <> overlay
+  let names = nubOrd [name', name] -- check non-starred as fallback
+  let raw = do
+       guard $ isInlineCommand name || not (isBlockCommand name)
+       rawcommand <- getRawCommand name (cmd <> star)
+       (guardEnabled Ext_raw_tex >> return (rawInline "latex" rawcommand))
+         <|> ignore rawcommand
+  lookupListDefault raw names inlineCommands
+
+tok :: PandocMonad m => LP m Inlines
+tok = tokWith inline
+
+unescapeURL :: Text -> Text
+unescapeURL = T.concat . go . T.splitOn "\\"
+  where
+    isEscapable c = T.any (== c) "#$%&~_^\\{}"
+    go (x:xs) = x : map unescapeInterior xs
+    go []     = []
+    unescapeInterior t
+      | Just (c, _) <- T.uncons t
+      , isEscapable c = t
+      | otherwise = "\\" <> t
+
+inlineCommands :: PandocMonad m => M.Map Text (LP m Inlines)
+inlineCommands = M.unions
+  [ accentCommands tok
+  , miscCommands
+  , citationCommands inline
+  , siunitxCommands tok
+  , acronymCommands
+  , refCommands
+  , nameCommands
+  , verbCommands
+  , charCommands
+  , enquoteCommands tok
+  , inlineLanguageCommands tok
+  , biblatexInlineCommands tok
+  , rest ]
+ where
+  disableLigatures p = do
+    oldLigatures <- sLigatures <$> getState
+    updateState (\s -> s{ sLigatures = False })
+    res <- p
+    updateState (\s -> s{ sLigatures = oldLigatures })
+    pure res
+  rest = M.fromList
+    [ ("emph", extractSpaces emph <$> tok)
+    , ("textit", extractSpaces emph <$> tok)
+    , ("textsl", extractSpaces emph <$> tok)
+    , ("textsc", extractSpaces smallcaps <$> tok)
+    , ("textsf", extractSpaces (spanWith ("",["sans-serif"],[])) <$> tok)
+    , ("textmd", extractSpaces (spanWith ("",["medium"],[])) <$> tok)
+    , ("textrm", extractSpaces (spanWith ("",["roman"],[])) <$> tok)
+    , ("textup", extractSpaces (spanWith ("",["upright"],[])) <$> tok)
+    , ("texttt", formatCode nullAttr <$> disableLigatures tok)
+    , ("alert", skipopts >> spanWith ("",["alert"],[]) <$> tok) -- beamer
+    , ("textsuperscript", extractSpaces superscript <$> tok)
+    , ("textsubscript", extractSpaces subscript <$> tok)
+    , ("textbf", extractSpaces strong <$> tok)
+    , ("textnormal", extractSpaces (spanWith ("",["nodecor"],[])) <$> tok)
+    , ("underline", underline <$> tok)
+    , ("mbox", rawInlineOr "mbox" $ processHBox <$> tok)
+    , ("hbox", rawInlineOr "hbox" $ processHBox <$> tok)
+    , ("vbox", rawInlineOr "vbox" tok)
+    , ("lettrine", rawInlineOr "lettrine" lettrine)
+    , ("(", withMathMode
+        (mathInline . untokenize <$> manyTill anyTok (controlSeq ")")))
+    , ("[", withMathMode
+        (mathDisplay . untokenize <$> manyTill anyTok (controlSeq "]")))
+    , ("ensuremath", withMathMode (mathInline . untokenize <$> braced))
+    , ("texorpdfstring", const <$> tok <*> tok)
+    -- old TeX commands
+    , ("em", extractSpaces emph <$> inlines)
+    , ("it", extractSpaces emph <$> inlines)
+    , ("sl", extractSpaces emph <$> inlines)
+    , ("bf", extractSpaces strong <$> inlines)
+    , ("tt", formatCode nullAttr <$> inlines)
+    , ("rm", inlines)
+    , ("itshape", extractSpaces emph <$> inlines)
+    , ("slshape", extractSpaces emph <$> inlines)
+    , ("scshape", extractSpaces smallcaps <$> inlines)
+    , ("bfseries", extractSpaces strong <$> inlines)
+    , ("MakeUppercase", makeUppercase <$> tok)
+    , ("MakeTextUppercase", makeUppercase <$> tok) -- textcase
+    , ("uppercase", makeUppercase <$> tok)
+    , ("MakeLowercase", makeLowercase <$> tok)
+    , ("MakeTextLowercase", makeLowercase <$> tok)
+    , ("lowercase", makeLowercase <$> tok)
+    , ("thanks", skipopts >> note <$> grouped block)
+    , ("footnote", skipopts >> footnote)
+    , ("footnotemark", footnotemark)
+    , ("footnotetext", footnotetext)
+    , ("newline", pure B.linebreak)
+    , ("passthrough", fixPassthroughEscapes <$> tok)
+    -- \passthrough macro used by latex writer
+                           -- for listings
+    , ("includegraphics", do options <- option [] keyvals
+                             src <- bracedFilename
+                             mkImage options . unescapeURL $ src)
+    -- svg
+    , ("includesvg",      do options <- option [] keyvals
+                             src <- bracedFilename
+                             mkImage options . unescapeURL $ src)
+    -- hyperref
+    , ("url", (\url -> linkWith ("",["uri"],[]) url "" (str url))
+                        . unescapeURL . untokenize <$> bracedUrl)
+    , ("nolinkurl", code . unescapeURL . untokenize <$> bracedUrl)
+    , ("href", do url <- bracedUrl
+                  sp
+                  link (unescapeURL $ untokenize url) "" <$> tok)
+    , ("hyperlink", hyperlink)
+    , ("hyperref", hyperref)
+    , ("hypertarget", hypertargetInline)
+    -- hyphenat
+    , ("nohyphens", tok)
+    , ("textnhtt", formatCode nullAttr <$> tok)
+    , ("nhttfamily", formatCode nullAttr <$> tok)
+    -- LaTeX colors
+    , ("textcolor", coloredInline "color")
+    , ("colorbox", coloredInline "background-color")
+    -- etoolbox
+    , ("newtoggle", braced >>= newToggle)
+    , ("toggletrue", braced >>= setToggle True)
+    , ("togglefalse", braced >>= setToggle False)
+    , ("iftoggle", try $ ifToggle >> inline)
+    -- include
+    , ("input", rawInlineOr "input" $ include "input")
+    -- soul package
+    , ("st", extractSpaces strikeout <$> tok)
+    , ("ul", underline <$> tok)
+    , ("hl", extractSpaces (spanWith ("",["mark"],[])) <$> tok)
+    -- ulem package
+    , ("sout", extractSpaces strikeout <$> tok)
+    , ("uline", underline <$> tok)
+    -- plain tex stuff that should just be passed through as raw tex
+    , ("ifdim", ifdim)
+    -- generally only used in \date
+    , ("today", today)
+    -- this is used internally by pandoc but the definition is too complicated
+    -- for pandoc to handle (see #11140):
+    , ("pandocbounded", tok)
+    ]
+
+bracedFilename :: PandocMonad m => LP m Text
+bracedFilename =
+  removeDoubleQuotes . T.strip . untokenize . filter (not . isComment) <$> braced
+
+isComment :: Tok -> Bool
+isComment (Tok _ Comment _) = True
+isComment _ = False
+
+today :: PandocMonad m => LP m Inlines
+today =
+  text . T.pack . showGregorian . localDay . zonedTimeToLocalTime
+    <$> getZonedTime
+
+footnote :: PandocMonad m => LP m Inlines
+footnote = do
+  updateState $ \st -> st{ sLastNoteNum = sLastNoteNum st + 1 }
+  contents <- grouped block >>= walkM resolveNoteLabel
+  return $ note contents
+
+-- | Parse \footnotemark[n]. If n is not given, increment the counter.
+-- Returns a span marker that will be resolved to a Note later.
+footnotemark :: PandocMonad m => LP m Inlines
+footnotemark = do
+  mbNum <- optionalFootnoteNum
+  noteNum <- case mbNum of
+    Just n  -> return n
+    Nothing -> do
+      updateState $ \st -> st{ sLastNoteNum = sLastNoteNum st + 1 }
+      sLastNoteNum <$> getState
+  return $ B.spanWith ("", ["footnote-mark"], [("note-num", tshow noteNum)]) mempty
+
+-- | Parse \footnotetext[n]{text}. If n is not given, use current counter.
+-- Stores the text in state to be resolved later.
+footnotetext :: PandocMonad m => LP m Inlines
+footnotetext = do
+  mbNum <- optionalFootnoteNum
+  noteNum <- case mbNum of
+    Just n  -> return n
+    Nothing -> sLastNoteNum <$> getState
+  contents <- grouped block >>= walkM resolveNoteLabel
+  updateState $ \st -> st{
+    sFootnoteTexts = M.insert noteNum contents (sFootnoteTexts st) }
+  return mempty
+
+-- | Parse optional footnote number argument [n]
+optionalFootnoteNum :: PandocMonad m => LP m (Maybe Int)
+optionalFootnoteNum = option Nothing $ do
+  t <- bracketedToks
+  case reads (T.unpack $ untokenize t) of
+    [(n, "")] -> return $ Just n
+    _         -> return Nothing
+
+resolveNoteLabel :: PandocMonad m => Inline -> LP m Inline
+resolveNoteLabel (Span (_,cls,kvs) _)
+  | Just lab <- lookup "label" kvs = do
+      updateState $ \st -> st{
+        sLabels = M.insert lab (toList . text . tshow $ sLastNoteNum st)
+                      $ sLabels st }
+      return $ Span (lab,cls,kvs) []
+resolveNoteLabel il = return il
+
+
+lettrine :: PandocMonad m => LP m Inlines
+lettrine = do
+  optional rawopt
+  x <- tok
+  y <- tok
+  return $ extractSpaces (spanWith ("",["lettrine"],[])) x <> smallcaps y
+
+ifdim :: PandocMonad m => LP m Inlines
+ifdim = do
+  contents <- manyTill anyTok (controlSeq "fi")
+  return $ rawInline "latex" $ "\\ifdim" <> untokenize contents <> "\\fi"
+
+makeUppercase :: Inlines -> Inlines
+makeUppercase = fromList . walk (alterStr T.toUpper) . toList
+
+makeLowercase :: Inlines -> Inlines
+makeLowercase = fromList . walk (alterStr T.toLower) . toList
+
+alterStr :: (Text -> Text) -> Inline -> Inline
+alterStr f (Str xs) = Str (f xs)
+alterStr _ x = x
+
+fixPassthroughEscapes :: Inlines -> Inlines
+fixPassthroughEscapes = walk go
+ where
+  go (Code attr txt) = Code attr (T.pack $ unescapePassthrough $ T.unpack txt)
+  go x = x
+  unescapePassthrough [] = []
+  unescapePassthrough ('\\':c:cs)
+    | c `elem` ['%','{','}','\\'] = c : unescapePassthrough cs
+  unescapePassthrough (c:cs) = c : unescapePassthrough cs
+
+hyperlink :: PandocMonad m => LP m Inlines
+hyperlink = try $ do
+  src <- untokenize <$> braced
+  lab <- tok
+  return $ link ("#" <> src) "" lab
+
+hyperref :: PandocMonad m => LP m Inlines
+hyperref = try $ do
+  url <- (("#" <>) . untokenize <$> try (sp *> bracketedToks <* sp))
+       <|> untokenize <$> (bracedUrl <* bracedUrl <* bracedUrl)
+  link url "" <$> tok
+
+hypertargetBlock :: PandocMonad m => LP m Blocks
+hypertargetBlock = try $ do
+  ref <- untokenize <$> braced
+  bs <- grouped block
+  case toList bs of
+       [Header 1 (ident,_,_) _] | ident == ref -> return bs
+       _                        -> return $ divWith (ref, [], []) bs
+
+hypertargetInline :: PandocMonad m => LP m Inlines
+hypertargetInline = try $ do
+  ref <- untokenize <$> braced
+  ils <- grouped inline
+  return $ spanWith (ref, [], []) ils
+
+newToggle :: (Monoid a, PandocMonad m) => [Tok] -> LP m a
+newToggle name = do
+  updateState $ \st ->
+    st{ sToggles = M.insert (untokenize name) False (sToggles st) }
+  return mempty
+
+setToggle :: (Monoid a, PandocMonad m) => Bool -> [Tok] -> LP m a
+setToggle on name = do
+  updateState $ \st ->
+    st{ sToggles = M.adjust (const on) (untokenize name) (sToggles st) }
+  return mempty
+
+ifToggle :: PandocMonad m => LP m ()
+ifToggle = do
+  name <- braced
+  spaces
+  yes <- withVerbatimMode braced
+  spaces
+  no <- withVerbatimMode braced
+  toggles <- sToggles <$> getState
+  TokStream _ inp <- getInput
+  let name' = untokenize name
+  case M.lookup name' toggles of
+                Just True  -> setInput $ TokStream False (yes ++ inp)
+                Just False -> setInput $ TokStream False (no  ++ inp)
+                Nothing    -> do
+                  pos <- getPosition
+                  report $ UndefinedToggle name' pos
+  return ()
+
+coloredInline :: PandocMonad m => Text -> LP m Inlines
+coloredInline stylename = do
+  skipopts
+  color <- braced
+  spanWith ("",[],[("style",stylename <> ": " <> untokenize color)]) <$> tok
+
+processHBox :: Inlines -> Inlines
+processHBox = walk convert
+  where
+    convert Space     = Str $ T.singleton $ chr 160 -- non-breakable space
+    convert SoftBreak = Str $ T.singleton $ chr 160 -- non-breakable space
+    convert LineBreak = Str ""
+    convert x         = x
+
+isBlockCommand :: Text -> Bool
+isBlockCommand s =
+  s `M.member` (blockCommands :: M.Map Text (LP PandocPure Blocks))
+  || s `Set.member` treatAsBlock
+
+treatAsBlock :: Set.Set Text
+treatAsBlock = Set.fromList
+   [ "special", "pdfannot", "pdfstringdef"
+   , "bibliographystyle"
+   , "maketitle", "makeindex", "makeglossary"
+   , "addcontentsline", "addtocontents", "addtocounter"
+      -- \ignore{} is used conventionally in literate haskell for definitions
+      -- that are to be processed by the compiler but not printed.
+   , "ignore"
+   , "hyperdef"
+   , "markboth", "markright", "markleft"
+   , "hspace", "vspace"
+   , "newpage"
+   , "clearpage"
+   , "pagebreak"
+   , "titleformat"
+   , "listoffigures"
+   , "listoftables"
+   , "write"
+   ]
+
+isInlineCommand :: Text -> Bool
+isInlineCommand s =
+  s `M.member` (inlineCommands :: M.Map Text (LP PandocPure Inlines))
+  || s `Set.member` treatAsInline
+
+treatAsInline :: Set.Set Text
+treatAsInline = Set.fromList
+  [ "index"
+  , "hspace"
+  , "vspace"
+  , "noindent"
+  , "newpage"
+  , "clearpage"
+  , "pagebreak"
+  ]
+
+lookupListDefault :: (Ord k) => v -> [k] -> M.Map k v -> v
+lookupListDefault d = (fromMaybe d .) . lookupList
+  where lookupList l m = msum $ map (`M.lookup` m) l
+
+inline :: PandocMonad m => LP m Inlines
+inline = do
+  Tok pos toktype t <- peekTok
+  let eatOneToken = satisfyTok (const True)
+  let symbolAsString = str t <$ eatOneToken
+  let unescapedSymbolAsString =
+        do eatOneToken
+           report $ ParsingUnescaped t pos
+           return $ str t
+  ligatures <- sLigatures <$> getState
+  case toktype of
+    Comment     -> mempty <$ eatOneToken
+    Spaces      -> space <$ eatOneToken
+    Newline     -> softbreak <$ endline
+    Word        -> str t <$ eatOneToken
+    Symbol      ->
+      case t of
+        "-" | ligatures
+                -> eatOneToken *>
+                    option (str "-") (symbol '-' *>
+                      option (str "–") (str "—" <$ symbol '-'))
+        "'"     -> eatOneToken *>
+                    option (str "’") (str  "”" <$ (guard ligatures *> symbol '\''))
+        "~"     -> str "\160" <$ eatOneToken
+        "`" | ligatures
+                -> doubleQuote <|> singleQuote <|> (str "‘" <$ symbol '`')
+            | otherwise
+                -> str "‘" <$ symbol '`'
+        "\"" | ligatures
+                -> doubleQuote <|> singleQuote <|> symbolAsString
+        "“"     -> doubleQuote <|> symbolAsString
+        "‘"     -> singleQuote <|> symbolAsString
+        "$"     -> dollarsMath <|> unescapedSymbolAsString
+        "|"     -> (guardEnabled Ext_literate_haskell *>
+                    eatOneToken *> doLHSverb) <|> symbolAsString
+        "{"     -> inlineGroup
+        "#"     -> unescapedSymbolAsString
+        "&"     -> unescapedSymbolAsString
+        "_"     -> unescapedSymbolAsString
+        "^"     -> unescapedSymbolAsString
+        "\\"    -> mzero
+        "}"     -> mzero
+        _       -> symbolAsString
+    CtrlSeq _   -> macroDef (rawInline "latex")
+                  <|> inlineGroup
+                  <|> inlineCommand'
+                  <|> inlineEnvironment
+    Esc1        -> str . T.singleton <$> primEscape
+    Esc2        -> str . T.singleton <$> primEscape
+    _           -> mzero
+
+inlines :: PandocMonad m => LP m Inlines
+inlines = mconcat <$> many inline
+
+opt :: PandocMonad m => LP m Inlines
+opt = do
+  toks <- try (sp *> bracketedToks <* sp)
+  -- now parse the toks as inlines
+  st <- getState
+  parsed <- runParserT (mconcat <$> many inline) st "bracketed option"
+              (TokStream False toks)
+  case parsed of
+    Right result -> return result
+    Left e       -> throwError $ fromParsecError (toSources toks) e
+
+-- block elements:
+
+preamble :: PandocMonad m => LP m Blocks
+preamble = mconcat <$> many preambleBlock
+  where preambleBlock =  (mempty <$ spaces1)
+                     <|> macroDef (rawBlock "latex")
+                     <|> filecontents
+                     <|> (mempty <$ blockCommand)
+                     <|> (mempty <$ braced)
+                     <|> (do notFollowedBy (begin_ "document")
+                             anyTok
+                             return mempty)
+
+rule :: PandocMonad m => LP m Blocks
+rule = do
+  skipopts
+  width <- T.takeWhile (\c -> isDigit c || c == '.') . stringify <$> tok
+  _thickness <- tok
+  -- 0-width rules are used to fix spacing issues:
+  case safeRead width of
+    Just (0 :: Double) -> return mempty
+    _ -> return horizontalRule
+
+paragraph :: PandocMonad m => LP m Blocks
+paragraph = do
+  x <- trimInlines . mconcat <$> many1 inline
+  if x == mempty
+     then return mempty
+     else return $ para x
+
+rawBlockOr :: PandocMonad m => Text -> LP m Blocks -> LP m Blocks
+rawBlockOr name fallback = do
+  -- if raw_tex allowed, don't process
+  parseRaw <- extensionEnabled Ext_raw_tex <$> getOption readerExtensions
+  if parseRaw
+     then rawBlock "latex" <$> getRawCommand name ("\\" <> name)
+     else fallback
+
+doSubfile :: PandocMonad m => LP m Blocks
+doSubfile = do
+  skipMany opt
+  f <- T.unpack <$> bracedFilename
+  oldToks <- getInput
+  setInput $ TokStream False []
+  insertIncluded (ensureExtension (/= "") ".tex" f)
+  bs <- blocks
+  eof
+  setInput oldToks
+  return bs
+
+include :: (PandocMonad m, Monoid a) => Text -> LP m a
+include name = do
+  let isAllowed =
+        case name of
+          "include" -> (== ".tex")
+          "input" -> (/= "")
+          _ -> const False
+  skipMany opt
+  fs <- map (T.unpack . removeDoubleQuotes . T.strip) . T.splitOn "," .
+         untokenize . filter (not . isComment) <$> braced
+  mapM_ (insertIncluded . ensureExtension isAllowed ".tex") fs
+  return mempty
+
+usepackage :: (PandocMonad m, Monoid a) => LP m a
+usepackage = do
+  skipMany opt
+  fs <- map (T.unpack . removeDoubleQuotes . T.strip) . T.splitOn "," .
+           untokenize . filter (not . isComment) <$> braced
+  let parsePackage f = do
+        TokStream _ ts <- getIncludedToks (ensureExtension (== ".sty") ".sty" f)
+        parseFromToks (do _ <- blocks
+                          eof <|>
+                            do pos <- getPosition
+                               report $ CouldNotParseIncludeFile (T.pack f) pos)
+                      ts
+  mapM_ parsePackage fs
+  return mempty
+
+readFileFromTexinputs :: PandocMonad m => FilePath -> LP m (Maybe Text)
+readFileFromTexinputs fp = do
+  fileContentsMap <- sFileContents <$> getState
+  case M.lookup (T.pack fp) fileContentsMap of
+    Just t -> return (Just t)
+    Nothing -> do
+      dirs <- map (\t -> if T.null t
+                            then "."
+                            else T.unpack t)
+               . T.split (==':') . fromMaybe ""
+              <$> lookupEnv "TEXINPUTS"
+      readFileFromDirs dirs fp
+
+ensureExtension :: (FilePath -> Bool) -> FilePath -> FilePath -> FilePath
+ensureExtension isAllowed defaultExt fp =
+  let ext = takeExtension fp
+   in if isAllowed ext
+         then fp
+         else addExtension fp defaultExt
+
+getIncludedToks :: PandocMonad m
+                => FilePath
+                -> LP m TokStream
+getIncludedToks f = do
+  pos <- getPosition
+  containers <- getIncludeFiles <$> getState
+  when (T.pack f `elem` containers) $
+    throwError $ PandocParseError $ T.pack $ "Include file loop at " ++ show pos
+  updateState $ addIncludeFile $ T.pack f
+  mbcontents <- readFileFromTexinputs f
+  contents <- case mbcontents of
+                   Just s -> return s
+                   Nothing -> do
+                     report $ CouldNotLoadIncludeFile (T.pack f) pos
+                     return ""
+  updateState dropLatestIncludeFile
+  return $ TokStream False $ tokenize (initialPos f) contents
+
+insertIncluded :: PandocMonad m
+               => FilePath
+               -> LP m ()
+insertIncluded f = do
+  contents <- getIncludedToks f
+  ts <- getInput
+  setInput $ contents <> ts
+
+authors :: PandocMonad m => LP m ()
+authors = try $ do
+  bgroup
+  let oneAuthor = blocksToInlines' . B.toList . mconcat <$> many1 block
+  auths <- sepBy oneAuthor (controlSeq "and")
+  egroup
+  addMeta "author" (map trimInlines auths)
+
+looseItem :: PandocMonad m => LP m Blocks
+looseItem = do
+  inListItem <- sInListItem <$> getState
+  guard $ not inListItem
+  skipopts
+  return mempty
+
+epigraph :: PandocMonad m => LP m Blocks
+epigraph = do
+  p1 <- grouped block
+  p2 <- grouped block
+  return $ divWith ("", ["epigraph"], []) (p1 <> p2)
+
+section :: PandocMonad m => Attr -> Int -> LP m Blocks
+section (ident, classes, kvs) lvl = do
+  skipopts
+  contents <- grouped inline
+  lab <- option ident $
+          try (spaces >> controlSeq "label"
+               >> spaces >> untokenize <$> braced)
+  when (lvl == 0) $
+    updateState $ \st -> st{ sHasChapters = True }
+  unless ("unnumbered" `elem` classes) $ do
+    hn <- sLastHeaderNum <$> getState
+    hasChapters <- sHasChapters <$> getState
+    let lvl' = lvl + if hasChapters then 1 else 0
+    let num = incrementDottedNum lvl' hn
+    updateState $ \st -> st{ sLastHeaderNum = num
+                           , sLabels = M.insert lab
+                              [Str (renderDottedNum num)]
+                              (sLabels st) }
+  attr' <- registerHeader (lab, classes, kvs) contents
+  return $ headerWith attr' lvl contents
+
+blockCommand :: PandocMonad m => LP m Blocks
+blockCommand = try $ do
+  Tok _ (CtrlSeq name) txt <- anyControlSeq
+  guard $ name /= "begin" && name /= "end" && name /= "and"
+  star <- option "" ("*" <$ symbol '*' <* sp)
+  let name' = name <> star
+  let names = nubOrd [name', name]
+  let rawDefiniteBlock = do
+        guard $ isBlockCommand name
+        rawcontents <- getRawCommand name (txt <> star)
+        (guardEnabled Ext_raw_tex >> return (rawBlock "latex" rawcontents))
+          <|> ignore rawcontents
+  -- heuristic:  if it could be either block or inline, we
+  -- treat it if block if we have a sequence of block
+  -- commands followed by a newline.  But we stop if we
+  -- hit a \startXXX, since this might start a raw ConTeXt
+  -- environment (this is important because this parser is
+  -- used by the Markdown reader).
+  let startCommand = try $ do
+        Tok _ (CtrlSeq n) _ <- anyControlSeq
+        guard $ "start" `T.isPrefixOf` n
+  let rawMaybeBlock = try $ do
+        guard $ not $ isInlineCommand name
+        rawcontents <- getRawCommand name (txt <> star)
+        curr <- (guardEnabled Ext_raw_tex >>
+                    return (rawBlock "latex" rawcontents))
+                   <|> ignore rawcontents
+        rest <- many $ notFollowedBy startCommand *> blockCommand
+        lookAhead $ blankline <|> startCommand
+        return $ curr <> mconcat rest
+  let raw = rawDefiniteBlock <|> rawMaybeBlock
+  lookupListDefault raw names blockCommands
+
+closing :: PandocMonad m => LP m Blocks
+closing = do
+  contents <- tok
+  st <- getState
+  let extractInlines (MetaBlocks [Plain ys]) = ys
+      extractInlines (MetaBlocks [Para ys ]) = ys
+      extractInlines _                       = []
+  let sigs = case lookupMeta "author" (sMeta st) of
+                  Just (MetaList xs) ->
+                    para $ trimInlines $ fromList $
+                      intercalate [LineBreak] $ map extractInlines xs
+                  _ -> mempty
+  return $ para (trimInlines contents) <> sigs
+
+parbox :: PandocMonad m => LP m Blocks
+parbox = try $ do
+  skipopts
+  braced -- size
+  oldInTableCell <- sInTableCell <$> getState
+  -- see #5711
+  updateState $ \st -> st{ sInTableCell = False }
+  res <- grouped block
+  updateState $ \st -> st{ sInTableCell = oldInTableCell }
+  return res
+
+blockCommands :: PandocMonad m => M.Map Text (LP m Blocks)
+blockCommands = M.fromList
+   [ ("par", mempty <$ skipopts)
+   , ("parbox",  parbox)
+   , ("title", mempty <$ (skipopts *>
+                             (grouped inline >>= addMeta "title")
+                         <|> (grouped block >>= addMeta "title")))
+   , ("subtitle", mempty <$ (skipopts *> tok >>= addMeta "subtitle"))
+   , ("author", mempty <$ (skipopts *> authors))
+   -- -- in letter class, temp. store address & sig as title, author
+   , ("address", mempty <$ (skipopts *> tok >>= addMeta "address"))
+   , ("signature", mempty <$ (skipopts *> authors))
+   , ("date", mempty <$ (skipopts *> tok >>= addMeta "date"))
+   , ("newtheorem", newtheorem)
+   , ("theoremstyle", theoremstyle)
+   -- KOMA-Script metadata commands
+   , ("extratitle", mempty <$ (skipopts *> tok >>= addMeta "extratitle"))
+   , ("frontispiece", mempty <$ (skipopts *> tok >>= addMeta "frontispiece"))
+   , ("titlehead", mempty <$ (skipopts *> tok >>= addMeta "titlehead"))
+   , ("subject", mempty <$ (skipopts *> tok >>= addMeta "subject"))
+   , ("publishers", mempty <$ (skipopts *> tok >>= addMeta "publishers"))
+   , ("uppertitleback", mempty <$ (skipopts *> tok >>= addMeta "uppertitleback"))
+   , ("lowertitleback", mempty <$ (skipopts *> tok >>= addMeta "lowertitleback"))
+   , ("dedication", mempty <$ (skipopts *> tok >>= addMeta "dedication"))
+   -- sectioning
+   , ("part", section nullAttr (-1))
+   , ("part*", section ("",["unnumbered"],[]) (-1))
+   , ("chapter", section nullAttr 0)
+   , ("chapter*", section ("",["unnumbered"],[]) 0)
+   , ("section", section nullAttr 1)
+   , ("section*", section ("",["unnumbered"],[]) 1)
+   , ("subsection", section nullAttr 2)
+   , ("subsection*", section ("",["unnumbered"],[]) 2)
+   , ("subsubsection", section nullAttr 3)
+   , ("subsubsection*", section ("",["unnumbered"],[]) 3)
+   , ("paragraph", section nullAttr 4)
+   , ("paragraph*", section ("",["unnumbered"],[]) 4)
+   , ("subparagraph", section nullAttr 5)
+   , ("subparagraph*", section ("",["unnumbered"],[]) 5)
+   , ("minisec", section ("",["unnumbered","unlisted"],[]) 6) -- from KOMA
+   -- beamer slides
+   , ("frametitle", section nullAttr 3)
+   , ("framesubtitle", section nullAttr 4)
+   -- letters
+   , ("opening", para . trimInlines <$> (skipopts *> tok))
+   , ("closing", skipopts *> closing)
+   -- memoir
+   , ("plainbreak", braced >> pure horizontalRule)
+   , ("plainbreak*", braced >> pure horizontalRule)
+   , ("fancybreak", braced >> pure horizontalRule)
+   , ("fancybreak*", braced >> pure horizontalRule)
+   , ("plainfancybreak", braced >> braced >> braced >> pure horizontalRule)
+   , ("plainfancybreak*", braced >> braced >> braced >> pure horizontalRule)
+   , ("pfbreak", pure horizontalRule)
+   , ("pfbreak*", pure horizontalRule)
+   --
+   , ("hrule", pure horizontalRule)
+   , ("strut", pure mempty)
+   , ("rule", rule)
+   , ("item", looseItem)
+   , ("documentclass", skipopts *> braced *> preamble)
+   , ("centerline", para . trimInlines <$> (skipopts *> tok))
+   , ("caption", mempty <$ setCaption inline)
+   , ("bibliography", mempty <$ (skipopts *> braced >>=
+         addMeta "bibliography" . splitBibs . untokenize))
+   , ("addbibresource", mempty <$ (skipopts *> braced >>=
+         addMeta "bibliography" . splitBibs . untokenize))
+   , ("endinput", mempty <$ skipSameFileToks)
+   -- includes
+   , ("lstinputlisting", inputListing)
+   , ("inputminted", inputMinted)
+   , ("graphicspath", graphicsPath)
+   -- polyglossia
+   , ("setdefaultlanguage", setDefaultLanguage)
+   , ("setmainlanguage", setDefaultLanguage)
+   -- hyperlink
+   , ("hypertarget", hypertargetBlock)
+   -- LaTeX colors
+   , ("textcolor", coloredBlock "color")
+   , ("colorbox", coloredBlock "background-color")
+   -- csquotes
+   , ("blockquote", blockquote False Nothing)
+   , ("blockcquote", blockquote True Nothing)
+   , ("foreignblockquote", braced >>= blockquote False . Just . untokenize)
+   , ("foreignblockcquote", braced >>= blockquote True . Just . untokenize)
+   , ("hyphenblockquote", braced >>= blockquote False . Just . untokenize)
+   , ("hyphenblockcquote", braced >>= blockquote True . Just . untokenize)
+   -- include
+   , ("include", rawBlockOr "include" $ include "include")
+   , ("input", rawBlockOr "input" $ include "input")
+   , ("subfile", rawBlockOr "subfile" doSubfile)
+   , ("usepackage", rawBlockOr "usepackage" usepackage)
+   -- preamble
+   , ("PackageError", mempty <$ (braced >> braced >> braced))
+   -- epigraph package
+   , ("epigraph", epigraph)
+   -- alignment
+   , ("raggedright", pure mempty)
+   -- etoolbox
+   , ("newtoggle", braced >>= newToggle)
+   , ("toggletrue", braced >>= setToggle True)
+   , ("togglefalse", braced >>= setToggle False)
+   , ("iftoggle", try $ ifToggle >> block)
+   ]
+
+skipSameFileToks :: PandocMonad m => LP m ()
+skipSameFileToks = do
+    pos <- getPosition
+    skipMany $ infile (sourceName pos)
+
+environments :: PandocMonad m => M.Map Text (LP m Blocks)
+environments = M.union (tableEnvironments block inline) $
+   M.fromList
+   [ ("document", env "document" blocks <* skipMany anyTok)
+   , ("abstract", mempty <$ (env "abstract" blocks >>= addMeta "abstract"))
+   , ("sloppypar", env "sloppypar" blocks)
+   , ("letter", env "letter" letterContents)
+   , ("minipage", divWith ("",["minipage"],[]) <$>
+       env "minipage" (skipopts *> spaces *> optional braced *> spaces *> blocks))
+   , ("figure", env "figure" figure')
+   , ("figure*", env "figure*" figure')
+   , ("subfigure", env "subfigure" $ skipopts *> tok *> figure')
+   , ("center", divWith ("", ["center"], []) <$> env "center" blocks)
+   , ("quote", blockQuote <$> env "quote" blocks)
+   , ("quotation", blockQuote <$> env "quotation" blocks)
+   , ("verse", blockQuote <$> env "verse" blocks)
+   , ("itemize", bulletList <$> listenv "itemize" (many item))
+   , ("description", definitionList <$> listenv "description" (many descItem))
+   , ("enumerate", orderedList')
+   , ("alltt", alltt <$> env "alltt" blocks)
+   , ("code", guardEnabled Ext_literate_haskell *>
+       (codeBlockWith ("",["haskell","literate"],[]) <$> verbEnv "code"))
+   , ("comment", mempty <$ verbEnv "comment")
+   , ("verbatim", codeBlock <$> verbEnv "verbatim")
+   , ("Verbatim", fancyverbEnv "Verbatim")
+   , ("BVerbatim", fancyverbEnv "BVerbatim")
+   , ("lstlisting", do attr <- parseListingsOptions <$> option [] keyvals
+                       codeBlockWith attr <$> verbEnv "lstlisting")
+   , ("minted", minted)
+   , ("obeylines", obeylines)
+   , ("tikzpicture", rawVerbEnv "tikzpicture")
+   , ("tikzcd", rawVerbEnv "tikzcd")
+   , ("lilypond", rawVerbEnv "lilypond")
+   , ("ly", rawVerbEnv "ly")
+   -- amsthm
+   , ("proof", proof blocks opt)
+   -- other
+   , ("CSLReferences", braced >> braced >> env "CSLReferences" blocks)
+   , ("otherlanguage", env "otherlanguage" otherlanguageEnv)
+   ]
+
+otherlanguageEnv :: PandocMonad m => LP m Blocks
+otherlanguageEnv = do
+  skipopts
+  babelLang <- untokenize <$> braced
+  case babelLangToBCP47 babelLang of
+    Just lang -> divWith ("", [], [("lang", renderLang lang)]) <$> blocks
+    Nothing -> blocks
+
+langEnvironment :: PandocMonad m => Text -> LP m Blocks
+langEnvironment name =
+  case babelLangToBCP47 name of
+    Just lang ->
+      env name (divWith ("", [], [("lang", renderLang lang)]) <$> blocks)
+    Nothing -> mzero -- fall through to raw environment
+
+filecontents :: PandocMonad m => LP m Blocks
+filecontents = try $ do
+  controlSeq "begin"
+  name <- untokenize <$> braced
+  guard $ name == "filecontents" || name == "filecontents*"
+  skipopts
+  fp <- untokenize <$> braced
+  txt <- verbEnv name
+  updateState $ \st ->
+    st{ sFileContents = M.insert fp txt (sFileContents st) }
+  return mempty
+
+environment :: PandocMonad m => LP m Blocks
+environment = try $ do
+  controlSeq "begin"
+  name <- untokenize <$> braced
+  M.findWithDefault mzero name environments <|>
+    langEnvironment name <|>
+    theoremEnvironment blocks inlines opt name <|>
+    if M.member name (inlineEnvironments
+                       :: M.Map Text (LP PandocPure Inlines))
+       then mzero
+       else try (rawEnv name) <|> rawVerbEnv name
+
+rawEnv :: PandocMonad m => Text -> LP m Blocks
+rawEnv name = do
+  exts <- getOption readerExtensions
+  let parseRaw = extensionEnabled Ext_raw_tex exts
+  rawOptions <- mconcat <$> many rawopt
+  let beginCommand = "\\begin{" <> name <> "}" <> rawOptions
+  pos1 <- getPosition
+  if parseRaw
+     then do
+       (_, raw) <- withRaw $ env name blocks
+       return $ rawBlock "latex"
+                 $ beginCommand <> untokenize raw
+     else do
+       bs <- env name blocks
+       report $ SkippedContent beginCommand pos1
+       pos2 <- getPosition
+       report $ SkippedContent ("\\end{" <> name <> "}") pos2
+       return $ divWith ("",[name],[]) bs
+
+rawVerbEnv :: PandocMonad m => Text -> LP m Blocks
+rawVerbEnv name = do
+  pos <- getPosition
+  (_, raw) <- withRaw $ verbEnv name
+  let raw' = "\\begin{" <> name <> "}" <> untokenize raw
+  exts <- getOption readerExtensions
+  let parseRaw = extensionEnabled Ext_raw_tex exts
+  if parseRaw
+     then return $ rawBlock "latex" raw'
+     else do
+       report $ SkippedContent raw' pos
+       return mempty
+
+fancyverbEnv :: PandocMonad m => Text -> LP m Blocks
+fancyverbEnv name = do
+  options <- option [] keyvals
+  let kvs = [ (if k == "firstnumber"
+                  then "startFrom"
+                  else k, v) | (k,v) <- options ]
+  let classes = [ "numberLines" |
+                  lookup "numbers" options == Just "left" ]
+  let attr = ("",classes,kvs)
+  codeBlockWith attr <$> verbEnv name
+
+obeylines :: PandocMonad m => LP m Blocks
+obeylines =
+  para . fromList . removeLeadingTrailingBreaks .
+   walk softBreakToHard . toList <$> env "obeylines" inlines
+  where softBreakToHard SoftBreak = LineBreak
+        softBreakToHard x         = x
+        removeLeadingTrailingBreaks = reverse . dropWhile isLineBreak .
+                                      reverse . dropWhile isLineBreak
+        isLineBreak LineBreak = True
+        isLineBreak _         = False
+
+minted :: PandocMonad m => LP m Blocks
+minted = do
+  attr <- mintedAttr
+  codeBlockWith attr <$> verbEnv "minted"
+
+mintedAttr :: PandocMonad m => LP m Attr
+mintedAttr = do
+  options <- option [] keyvals
+  lang <- untokenize <$> braced
+  let kvs = [ (if k == "firstnumber"
+                  then "startFrom"
+                  else k, v) | (k,v) <- options ]
+  let classes = [ lang | not (T.null lang) ] ++
+                [ "numberLines" |
+                  lookup "linenos" options == Just "true" ]
+  return ("",classes,kvs)
+
+inputMinted :: PandocMonad m => LP m Blocks
+inputMinted = do
+  pos <- getPosition
+  attr <- mintedAttr
+  f <- T.filter (/='"') . untokenize <$> braced
+  mbCode <- readFileFromTexinputs (T.unpack f)
+  rawcode <- case mbCode of
+                  Just s -> return s
+                  Nothing -> do
+                    report $ CouldNotLoadIncludeFile f pos
+                    return ""
+  return $ B.codeBlockWith attr rawcode
+
+letterContents :: PandocMonad m => LP m Blocks
+letterContents = do
+  bs <- blocks
+  st <- getState
+  -- add signature (author) and address (title)
+  let addr = case lookupMeta "address" (sMeta st) of
+                  Just (MetaBlocks [Plain xs]) ->
+                     para $ trimInlines $ fromList xs
+                  _ -> mempty
+  return $ addr <> bs -- sig added by \closing
+
+figure' :: PandocMonad m => LP m Blocks
+figure' = try $ do
+  sp
+  poshint <- option "" $ untokenize <$> bracketedToks
+  sp
+  resetCaption
+  innerContent <- many $ try (Left <$> label) <|> (Right <$> block)
+  let content = walk go $ mconcat $ snd $ partitionEithers innerContent
+  st <- getState
+  let caption' = fromMaybe B.emptyCaption $ sCaption st
+  let mblabel  = sLastLabel st
+  let kvs = [("latex-placement", poshint) | not (T.null poshint)]
+  let ident = fromMaybe "" mblabel
+  let attr  = (ident, [], kvs)
+  case mblabel of
+    Nothing   -> pure ()
+    Just lab  -> do
+      num <- getNextNumber sLastFigureNum
+      setState
+        st { sLastFigureNum = num
+           , sLabels = M.insert lab [Str (renderDottedNum num)] (sLabels st)
+           }
+  return $ B.figureWith attr caption' content
+
+  where
+  -- Remove the `Image` caption b.c. it's on the `Figure`
+  go (Para [Image attr [Str "image"] target]) = Plain [Image attr [] target]
+  go x = x
+
+coloredBlock :: PandocMonad m => Text -> LP m Blocks
+coloredBlock stylename = try $ do
+  skipopts
+  color <- braced
+  notFollowedBy (grouped inline)
+  let constructor = divWith ("",[],[("style",stylename <> ": " <> untokenize color)])
+  constructor <$> grouped block
+
+graphicsPath :: PandocMonad m => LP m Blocks
+graphicsPath = do
+  ps <- map (T.unpack . untokenize) <$>
+          (bgroup *> spaces *> manyTill (braced <* spaces) egroup)
+  getResourcePath >>= setResourcePath . (<> ps)
+  return mempty
+
+splitBibs :: Text -> [Inlines]
+splitBibs = map (str . T.pack . flip replaceExtension "bib" . T.unpack . trim) . splitTextBy (==',')
+
+alltt :: Blocks -> Blocks
+alltt = walk strToCode
+  where strToCode (Str s)   = Code nullAttr s
+        strToCode Space     = RawInline (Format "latex") "\\ "
+        strToCode SoftBreak = LineBreak
+        strToCode x         = x
+
+parseListingsOptions :: [(Text, Text)] -> Attr
+parseListingsOptions options =
+  let kvs = [ (if k == "firstnumber"
+                  then "startFrom"
+                  else k, v) | (k,v) <- options ]
+      classes = [ "numberLines" |
+                  lookup "numbers" options == Just "left" ]
+             ++ maybeToList (listingsLanguage options)
+  in  (fromMaybe "" (lookup "label" options), classes, kvs)
+
+inputListing :: PandocMonad m => LP m Blocks
+inputListing = do
+  pos <- getPosition
+  options <- option [] keyvals
+  f <- T.filter (/='"') . untokenize <$> braced
+  mbCode <- readFileFromTexinputs (T.unpack f)
+  codeLines <- case mbCode of
+                      Just s -> return $ T.lines s
+                      Nothing -> do
+                        report $ CouldNotLoadIncludeFile f pos
+                        return []
+  let (ident,classes,kvs) = parseListingsOptions options
+  let classes' =
+        (case listingsLanguage options of
+           Nothing -> (take 1 (languagesByExtension defaultSyntaxMap
+                                (T.pack $ takeExtension $ T.unpack f)) <>)
+           Just _  -> id) classes
+  let firstline = fromMaybe 1 $ lookup "firstline" options >>= safeRead
+  let lastline = fromMaybe (length codeLines) $
+                       lookup "lastline" options >>= safeRead
+  let codeContents = T.intercalate "\n" $ take (1 + lastline - firstline) $
+                       drop (firstline - 1) codeLines
+  return $ codeBlockWith (ident,classes',kvs) codeContents
+
+-- lists
+
+item :: PandocMonad m => LP m Blocks
+item = void blocks *> controlSeq "item" *> skipopts *> blocks
+
+descItem :: PandocMonad m => LP m (Inlines, [Blocks])
+descItem = do
+  optional spaces1
+  controlSeq "item"
+  sp
+  ils <- opt
+  bs <- blocks
+  return (ils, [bs])
+
+listenv :: PandocMonad m => Text -> LP m a -> LP m a
+listenv name p = try $ do
+  oldInListItem <- sInListItem `fmap` getState
+  updateState $ \st -> st{ sInListItem = True }
+  res <- env name p
+  updateState $ \st -> st{ sInListItem = oldInListItem }
+  return res
+
+orderedList' :: PandocMonad m => LP m Blocks
+orderedList' = try $ do
+  spaces
+  let markerSpec = do
+        symbol '['
+        ts <- untokenize <$> manyTill anyTok (symbol ']')
+        case runParser anyOrderedListMarker def "option" ts of
+             Right r -> return r
+             Left _  -> do
+               pos <- getPosition
+               report $ SkippedContent ("[" <> ts <> "]") pos
+               return (1, DefaultStyle, DefaultDelim)
+  (_, style, delim) <- option (1, DefaultStyle, DefaultDelim) markerSpec
+  spaces
+  optional $ try $ controlSeq "setlength"
+                   *> grouped (count 1 $ controlSeq "itemindent")
+                   *> braced
+  spaces
+  start <- option 1 $ try $ do pos <- getPosition
+                               controlSeq "setcounter"
+                               ctr <- untokenize <$> braced
+                               guard $ "enum" `T.isPrefixOf` ctr
+                               guard $ T.all (`elem` ['i','v']) (T.drop 4 ctr)
+                               sp
+                               num <- untokenize <$> braced
+                               case safeRead num of
+                                    Just i -> return (i + 1 :: Int)
+                                    Nothing -> do
+                                      report $ SkippedContent
+                                        ("\\setcounter{" <> ctr <>
+                                         "}{" <> num <> "}") pos
+                                      return 1
+  bs <- listenv "enumerate" (many item)
+  return $ orderedListWith (start, style, delim) bs
+
+block :: PandocMonad m => LP m Blocks
+block = do
+  Tok _ toktype _ <- peekTok
+  res <- (case toktype of
+            Newline           -> mempty <$ spaces1
+            Spaces            -> mempty <$ spaces1
+            Comment           -> mempty <$ spaces1
+            Word              -> paragraph
+            CtrlSeq "begin"   -> environment
+            CtrlSeq _         -> macroDef (rawBlock "latex")
+                               <|> blockCommand
+            _                 -> mzero)
+          <|> paragraph
+          <|> grouped block
+  trace (T.take 60 $ tshow $ B.toList res)
+  return res
+
+blocks :: PandocMonad m => LP m Blocks
+blocks = mconcat <$> many block
diff --git a/src/Text/Pandoc/Readers/LaTeX/Citation.hs b/src/Text/Pandoc/Readers/LaTeX/Citation.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Readers/LaTeX/Citation.hs
@@ -0,0 +1,209 @@
+{-# LANGUAGE ScopedTypeVariables #-}
+{-# LANGUAGE OverloadedStrings #-}
+module Text.Pandoc.Readers.LaTeX.Citation
+  ( citationCommands
+  , cites
+  )
+where
+
+import Text.Pandoc.Class
+import Text.Pandoc.Readers.LaTeX.Parsing
+import Text.Pandoc.Builder as B
+import qualified Data.Map as M
+import Data.Text (Text)
+import Control.Applicative ((<|>), optional, many)
+import Control.Monad (mzero)
+import Control.Monad.Trans (lift)
+import Control.Monad.Except (throwError)
+import Text.Pandoc.Parsing hiding (blankline, many, mathDisplay, mathInline,
+                            optional, space, spaces, withRaw, (<|>))
+
+citationCommands :: PandocMonad m => LP m Inlines -> M.Map Text (LP m Inlines)
+citationCommands inline =
+  let citation = citationWith inline
+      tok = spaces *> grouped inline
+   in M.fromList
+  [ ("cite", citation "cite" NormalCitation False)
+  , ("Cite", citation "Cite" NormalCitation False)
+  , ("citep", citation "citep" NormalCitation False)
+  , ("citep*", citation "citep*" NormalCitation False)
+  , ("citeal", citation "citeal" NormalCitation False)
+  , ("citealp", citation "citealp" NormalCitation False)
+  , ("citealp*", citation "citealp*" NormalCitation False)
+  , ("autocite", citation "autocite" NormalCitation False)
+  , ("smartcite", citation "smartcite" NormalCitation False)
+  , ("footcite", inNote <$> citation "footcite" NormalCitation False)
+  , ("parencite", citation "parencite" NormalCitation False)
+  , ("supercite", citation "supercite" NormalCitation False)
+  , ("footcitetext", inNote <$> citation "footcitetext" NormalCitation False)
+  , ("citeyearpar", citation "citeyearpar" SuppressAuthor False)
+  , ("citeyear", citation "citeyear" SuppressAuthor False)
+  , ("autocite*", citation "autocite*" SuppressAuthor False)
+  , ("cite*", citation "cite*" SuppressAuthor False)
+  , ("parencite*", citation "parencite*" SuppressAuthor False)
+  , ("textcite", citation "textcite" AuthorInText False)
+  , ("citet", citation "citet" AuthorInText False)
+  , ("citet*", citation "citet*" AuthorInText False)
+  , ("citealt", citation "citealt" AuthorInText False)
+  , ("citealt*", citation "citealt*" AuthorInText False)
+  , ("textcites", citation "textcites" AuthorInText True)
+  , ("cites", citation "cites" NormalCitation True)
+  , ("autocites", citation "autocites" NormalCitation True)
+  , ("footcites", inNote <$> citation "footcites" NormalCitation True)
+  , ("parencites", citation "parencites" NormalCitation True)
+  , ("supercites", citation "supercites" NormalCitation True)
+  , ("footcitetexts", inNote <$> citation "footcitetexts" NormalCitation True)
+  , ("Autocite", citation "Autocite" NormalCitation False)
+  , ("Smartcite", citation "Smartcite" NormalCitation False)
+  , ("Footcite", inNote <$> citation "Footcite" NormalCitation False)
+  , ("Parencite", citation "Parencite" NormalCitation False)
+  , ("Supercite", citation "Supercite" NormalCitation False)
+  , ("Footcitetext", inNote <$> citation "Footcitetext" NormalCitation False)
+  , ("Citeyearpar", citation "Citeyearpar" SuppressAuthor False)
+  , ("Citeyear", citation "Citeyear" SuppressAuthor False)
+  , ("Autocite*", citation "Autocite*" SuppressAuthor False)
+  , ("Cite*", citation "Cite*" SuppressAuthor False)
+  , ("Parencite*", citation "Parencite*" SuppressAuthor False)
+  , ("Textcite", citation "Textcite" AuthorInText False)
+  , ("Textcites", citation "Textcites" AuthorInText True)
+  , ("Cites", citation "Cites" NormalCitation True)
+  , ("Autocites", citation "Autocites" NormalCitation True)
+  , ("Footcites", inNote <$> citation "Footcites" NormalCitation True)
+  , ("Parencites", citation "Parencites" NormalCitation True)
+  , ("Supercites", citation "Supercites" NormalCitation True)
+  , ("Footcitetexts", inNote <$> citation "Footcitetexts" NormalCitation True)
+  , ("citetext", complexNatbibCitation inline NormalCitation)
+  , ("citeauthor", (try (tok *> sp *> controlSeq "citetext") *>
+                        complexNatbibCitation inline AuthorInText)
+                   <|> citation "citeauthor" AuthorInText False)
+  , ("nocite", mempty <$ (citation "nocite" NormalCitation False >>=
+                          addMeta "nocite"))
+  ]
+
+-- citations
+
+addPrefix :: [Inline] -> [Citation] -> [Citation]
+addPrefix p (k:ks) = k {citationPrefix = p ++ citationPrefix k} : ks
+addPrefix _ _      = []
+
+addSuffix :: [Inline] -> [Citation] -> [Citation]
+addSuffix s ks@(_:_) =
+  let k = last ks
+  in  init ks ++ [k {citationSuffix = citationSuffix k ++ s}]
+addSuffix _ _ = []
+
+simpleCiteArgs :: forall m . PandocMonad m => LP m Inlines -> LP m [Citation]
+simpleCiteArgs inline = try $ do
+  first  <- optionMaybe $ toList <$> opt
+  second <- optionMaybe $ toList <$> opt
+  keys <- try $ bgroup *> manyTill citationLabel egroup
+  let (pre, suf) = case (first  , second ) of
+        (Just s , Nothing) -> (mempty, s )
+        (Just s , Just t ) -> (s , t )
+        _                  -> (mempty, mempty)
+      conv k = Citation { citationId      = k
+                        , citationPrefix  = []
+                        , citationSuffix  = []
+                        , citationMode    = NormalCitation
+                        , citationHash    = 0
+                        , citationNoteNum = 0
+                        }
+  return $ addPrefix pre $ addSuffix suf $ map conv keys
+ where
+  opt :: PandocMonad m => LP m Inlines
+  opt = do
+    toks <- try (sp *> bracketedToks <* sp)
+    -- now parse the toks as inlines
+    st <- getState
+    parsed <- lift $
+      runParserT (mconcat <$> many inline) st "bracketed option"
+       (TokStream False toks)
+    case parsed of
+      Right result -> return result
+      Left e       -> throwError $ fromParsecError (toSources toks) e
+
+
+
+citationLabel :: PandocMonad m => LP m Text
+citationLabel  = do
+  sp
+  untokenize <$>
+    (many1 (satisfyTok isWordTok <|> symbolIn bibtexKeyChar)
+          <* sp
+          <* optional (symbol ',')
+          <* sp)
+  where bibtexKeyChar = ".:;?!`'()/*@_+=-&[]" :: [Char]
+
+cites :: PandocMonad m
+      => LP m Inlines -> CitationMode -> Bool -> LP m [Citation]
+cites inline mode multi = try $ do
+  let paropt = parenWrapped inline
+  cits <- if multi
+             then do
+               multiprenote <- optionMaybe $ toList <$> paropt
+               multipostnote <- optionMaybe $ toList <$> paropt
+               let (pre, suf) = case (multiprenote, multipostnote) of
+                     (Just s , Nothing) -> (mempty, s)
+                     (Nothing , Just t) -> (mempty, t)
+                     (Just s , Just t ) -> (s, t)
+                     _                  -> (mempty, mempty)
+               tempCits <- many1 $ simpleCiteArgs inline
+               case tempCits of
+                 (k:ks) -> case ks of
+                             (_:_) -> return $ (addMprenote pre k : init ks) ++
+                                                 [addMpostnote suf (last ks)]
+                             _ -> return [addMprenote pre (addMpostnote suf k)]
+                 _ -> return [[]]
+             else count 1 $ simpleCiteArgs inline
+  let cs = concat cits
+  return $ case mode of
+        AuthorInText -> case cs of
+                             (c:rest) -> c {citationMode = mode} : rest
+                             []       -> []
+        _            -> map (\a -> a {citationMode = mode}) cs
+  where mprenote (k:ks) = (k:ks) ++ [Space]
+        mprenote _ = mempty
+        mpostnote (k:ks) = [Str ",", Space] ++ (k:ks)
+        mpostnote _ = mempty
+        addMprenote mpn (k:ks) =
+          let mpnfinal = case citationPrefix k of
+                           (_:_) -> mprenote mpn
+                           _ -> mpn
+          in addPrefix mpnfinal (k:ks)
+        addMprenote _ _ = []
+        addMpostnote = addSuffix . mpostnote
+
+citationWith :: PandocMonad m
+             => LP m Inlines -> Text -> CitationMode -> Bool -> LP m Inlines
+citationWith inline name mode multi = do
+  (c,raw) <- withRaw $ cites inline mode multi
+  return $ cite c (rawInline "latex" $ "\\" <> name <> untokenize raw)
+
+handleCitationPart :: Inlines -> [Citation]
+handleCitationPart ils =
+  let isCite Cite{} = True
+      isCite _      = False
+      (pref, rest) = break isCite (toList ils)
+  in case rest of
+          (Cite cs _:suff) -> addPrefix pref $ addSuffix suff cs
+          _                -> []
+
+complexNatbibCitation :: PandocMonad m
+                      => LP m Inlines -> CitationMode -> LP m Inlines
+complexNatbibCitation inline mode = try $ do
+  (cs, raw) <-
+    withRaw $ concat <$> do
+      bgroup
+      items <- mconcat <$>
+                many1 (notFollowedBy (symbol ';') >> inline)
+                  `sepBy1` symbol ';'
+      egroup
+      return $ map handleCitationPart items
+  case cs of
+       []       -> mzero
+       (c:cits) -> return $ cite (c{ citationMode = mode }:cits)
+                      (rawInline "latex" $ "\\citetext" <> untokenize raw)
+
+inNote :: Inlines -> Inlines
+inNote ils =
+  note $ para $ ils <> str "."
diff --git a/src/Text/Pandoc/Readers/LaTeX/Inline.hs b/src/Text/Pandoc/Readers/LaTeX/Inline.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Readers/LaTeX/Inline.hs
@@ -0,0 +1,452 @@
+{-# LANGUAGE OverloadedStrings     #-}
+{-# LANGUAGE ViewPatterns          #-}
+{- |
+   Module      : Text.Pandoc.Readers.LaTeX.Inline
+   Copyright   : Copyright (C) 2006-2024 John MacFarlane
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : John MacFarlane <jgm@berkeley.edu>
+   Stability   : alpha
+   Portability : portable
+-}
+module Text.Pandoc.Readers.LaTeX.Inline
+  ( acronymCommands
+  , verbCommands
+  , charCommands
+  , accentCommands
+  , miscCommands
+  , nameCommands
+  , biblatexInlineCommands
+  , refCommands
+  , rawInlineOr
+  , listingsLanguage
+  )
+where
+
+import qualified Data.Map as M
+import Data.Text (Text)
+import qualified Data.Text as T
+import Text.Pandoc.Builder
+import Text.Pandoc.Shared (toRomanNumeral, safeRead)
+import Text.Pandoc.TeX (Tok (..), TokType (..))
+import Control.Applicative (optional, (<|>))
+import Control.Monad (guard, mzero, mplus, unless)
+import Text.Pandoc.Class.PandocMonad (PandocMonad (..))
+import Text.Pandoc.Translations (translateTerm)
+import Text.Pandoc.Readers.LaTeX.Parsing
+import Text.Pandoc.Extensions (extensionEnabled, Extension(..))
+import Text.Pandoc.Parsing (getOption, updateState, getState, notFollowedBy,
+                            manyTill, getInput, setInput, incSourceColumn,
+                            option, many1)
+import Data.Char (isDigit)
+import Text.Pandoc.Highlighting (fromListingsLanguage,)
+import Data.Maybe (maybeToList, fromMaybe)
+import Text.Pandoc.Options (ReaderOptions(..))
+import qualified Data.Text.Normalize as Normalize
+import qualified Text.Pandoc.Translations as Translations
+
+rawInlineOr :: PandocMonad m => Text -> LP m Inlines -> LP m Inlines
+rawInlineOr name' fallback = do
+  parseRaw <- extensionEnabled Ext_raw_tex <$> getOption readerExtensions
+  if parseRaw
+     then rawInline "latex" <$> getRawCommand name' ("\\" <> name')
+     else fallback
+
+dolabel :: PandocMonad m => LP m Inlines
+dolabel = do
+  v <- braced
+  let refstr = untokenize v
+  updateState $ \st ->
+    st{ sLastLabel = Just refstr }
+  return $ spanWith (refstr,[],[("label", refstr)]) mempty
+
+doref :: PandocMonad m => Text -> LP m Inlines
+doref cls = do
+  v <- braced
+  let refstr = untokenize v
+  return $ linkWith ("",[],[ ("reference-type", cls)
+                           , ("reference", refstr)])
+                    ("#" <> refstr)
+                    ""
+                    (inBrackets $ str refstr)
+
+inBrackets :: Inlines -> Inlines
+inBrackets x = str "[" <> x <> str "]"
+
+doTerm :: PandocMonad m => Translations.Term -> LP m Inlines
+doTerm term = str <$> translateTerm term
+
+lit :: Text -> LP m Inlines
+lit = pure . str
+
+doverb :: PandocMonad m => LP m Inlines
+doverb = do
+  Tok _ Symbol t <- anySymbol
+  marker <- case T.uncons t of
+              Just (c, ts) | T.null ts -> return c
+              _            -> mzero
+  withVerbatimMode $
+    code . untokenize <$>
+      manyTill (notFollowedBy newlineTok >> verbTok marker) (symbol marker)
+
+verbTok :: PandocMonad m => Char -> LP m Tok
+verbTok stopchar = do
+  t@(Tok pos toktype txt) <- anyTok
+  case T.findIndex (== stopchar) txt of
+       Nothing -> return t
+       Just i  -> do
+         let (t1, t2) = T.splitAt i txt
+         TokStream macrosExpanded inp <- getInput
+         setInput $ TokStream macrosExpanded
+                  $ Tok (incSourceColumn pos i) Symbol (T.singleton stopchar)
+                  : tokenize (incSourceColumn pos (i + 1)) (T.drop 1 t2) ++ inp
+         return $ Tok pos toktype t1
+
+listingsLanguage :: [(Text, Text)] -> Maybe Text
+listingsLanguage opts =
+  case lookup "language" opts of
+    Nothing  -> Nothing
+    Just l   -> fromListingsLanguage l `mplus` Just l
+
+dolstinline :: PandocMonad m => LP m Inlines
+dolstinline = do
+  options <- option [] keyvals
+  let classes = maybeToList $ listingsLanguage options
+  doinlinecode classes
+
+domintinline :: PandocMonad m => LP m Inlines
+domintinline = do
+  skipopts
+  cls <- untokenize <$> braced
+  doinlinecode [cls]
+
+doinlinecode :: PandocMonad m => [Text] -> LP m Inlines
+doinlinecode classes = do
+  Tok _ Symbol t <- anySymbol
+  marker <- case T.uncons t of
+              Just (c, ts) | T.null ts -> return c
+              _            -> mzero
+  let stopchar = if marker == '{' then '}' else marker
+  withVerbatimMode $
+    codeWith ("",classes,[]) . T.map nlToSpace . untokenize <$>
+      manyTill (verbTok stopchar) (symbol stopchar)
+
+nlToSpace :: Char -> Char
+nlToSpace '\n' = ' '
+nlToSpace x    = x
+
+romanNumeralUpper :: (PandocMonad m) => LP m Inlines
+romanNumeralUpper =
+  str . toRomanNumeral <$> romanNumeralArg
+
+romanNumeralLower :: (PandocMonad m) => LP m Inlines
+romanNumeralLower =
+  str . T.toLower . toRomanNumeral <$> romanNumeralArg
+
+romanNumeralArg :: (PandocMonad m) => LP m Int
+romanNumeralArg = spaces *> (parser <|> inBraces)
+  where
+    inBraces = do
+      symbol '{'
+      spaces
+      res <- parser
+      spaces
+      symbol '}'
+      return res
+    parser = do
+      s <- untokenize <$> many1 (satisfyTok isWordTok)
+      let (digits, rest) = T.span isDigit s
+      unless (T.null rest) $
+        Prelude.fail "Non-digits in argument to \\Rn or \\RN"
+      safeRead digits
+
+accentWith :: PandocMonad m
+           => LP m Inlines -> Char -> Maybe Char -> LP m Inlines
+accentWith tok combiningAccent fallBack = do
+  ils <- option mempty tok
+  case toList ils of
+       (Str (T.uncons -> Just (x, xs)) : ys) -> return $ fromList $
+         -- try to normalize to the combined character:
+         Str (Normalize.normalize Normalize.NFC
+               (T.pack [x, combiningAccent]) <> xs) : ys
+       [Space] -> return $ str $ T.singleton
+                         $ fromMaybe combiningAccent fallBack
+       []      -> return $ str $ T.singleton
+                         $ fromMaybe combiningAccent fallBack
+       _       -> return ils
+
+
+verbCommands :: PandocMonad m => M.Map Text (LP m Inlines)
+verbCommands = M.fromList
+  [ ("verb", doverb)
+  , ("lstinline", dolstinline)
+  , ("mintinline", domintinline)
+  , ("Verb", doverb)
+  ]
+
+miscCommands :: PandocMonad m => M.Map Text (LP m Inlines)
+miscCommands =
+  M.fromList
+  [ ("pounds", lit "£")
+  , ("euro", lit "€")
+  , ("copyright", lit "©")
+  , ("textasciicircum", lit "^")
+  , ("textasciitilde", lit "~")
+  , ("textbaht", lit "฿")
+  , ("textblank", lit "␢")
+  , ("textbigcircle", lit "○")
+  , ("textbrokenbar", lit "¦")
+  , ("textbullet", lit "•")
+  , ("textcentoldstyle", lit "¢")
+  , ("textcopyright", lit "©")
+  , ("textdagger", lit "†")
+  , ("textdegree", lit "°")
+  , ("textdollar", lit "$")
+  , ("textdong", lit "₫")
+  , ("textlira", lit "₤")
+  , ("textmu", lit "μ")
+  , ("textmusicalnote", lit "♪")
+  , ("textonehalf", lit "½")
+  , ("textonequarter", lit "¼")
+  , ("textparagraph", lit "¶")
+  , ("textpertenthousand", lit "‱")
+  , ("textpeso", lit "₱")
+  , ("textquotesingle", lit "'")
+  , ("textregistered", lit "®")
+  , ("textsection", lit "§")
+  , ("textsterling", lit "£")
+  , ("textthreequarters", lit "¾")
+  , ("textthreesuperior", lit "³")
+  , ("texttwosuperior", lit "²")
+  , ("textyen", lit "¥")
+  ]
+
+accentCommands :: PandocMonad m => LP m Inlines -> M.Map Text (LP m Inlines)
+accentCommands tok =
+  let accent = accentWith tok
+  in  M.fromList
+  [ ("aa", lit "å")
+  , ("AA", lit "Å")
+  , ("ss", lit "ß")
+  , ("o", lit "ø")
+  , ("O", lit "Ø")
+  , ("L", lit "Ł")
+  , ("l", lit "ł")
+  , ("ae", lit "æ")
+  , ("AE", lit "Æ")
+  , ("oe", lit "œ")
+  , ("OE", lit "Œ")
+  , ("H", accent '\779' Nothing) -- hungarumlaut
+  , ("`", accent '\768' (Just '`')) -- grave
+  , ("'", accent '\769' (Just '\'')) -- acute
+  , ("^", accent '\770' (Just '^')) -- circ
+  , ("~", accent '\771' (Just '~')) -- tilde
+  , ("\"", accent '\776' Nothing) -- umlaut
+  , (".", accent '\775' Nothing) -- dot
+  , ("=", accent '\772' Nothing) -- macron
+  , ("|", accent '\781' Nothing) -- vertical line above
+  , ("b", accent '\817' Nothing) -- macron below
+  , ("c", accent '\807' Nothing) -- cedilla
+  , ("G", accent '\783' Nothing) -- doublegrave
+  , ("h", accent '\777' Nothing) -- hookabove
+  , ("d", accent '\803' Nothing) -- dotbelow
+  , ("f", accent '\785' Nothing)  -- inverted breve
+  , ("r", accent '\778' Nothing)  -- ringabove
+  , ("t", accent '\865' Nothing)  -- double inverted breve
+  , ("U", accent '\782' Nothing)  -- double vertical line above
+  , ("v", accent '\780' Nothing) -- hacek
+  , ("u", accent '\774' Nothing) -- breve
+  , ("k", accent '\808' Nothing) -- ogonek
+  , ("textogonekcentered", accent '\808' Nothing) -- ogonek
+  , ("i", lit "ı")  -- dotless i
+  , ("j", lit "ȷ")  -- dotless j
+  , ("newtie", accent '\785' Nothing) -- inverted breve
+  , ("textcircled", accent '\8413' Nothing) -- combining circle
+  ]
+
+charCommands :: PandocMonad m => M.Map Text (LP m Inlines)
+charCommands = M.fromList
+  [ ("ldots", lit "…")
+  , ("vdots", lit "\8942")
+  , ("dots", lit "…")
+  , ("mdots", lit "…")
+  , ("sim", lit "~")
+  , ("sep", lit ",")
+  , ("P", lit "¶")
+  , ("S", lit "§")
+  , ("$", lit "$")
+  , ("%", lit "%")
+  , ("&", lit "&")
+  , ("#", lit "#")
+  , ("_", lit "_")
+  , ("{", lit "{")
+  , ("}", lit "}")
+  , ("-", lit "\x00ad") -- soft hyphen
+  , ("qed", lit "\a0\x25FB")
+  , ("lq", return (str "‘"))
+  , ("rq", return (str "’"))
+  , ("textquoteleft", return (str "‘"))
+  , ("textquoteright", return (str "’"))
+  , ("textquotedblleft", return (str "“"))
+  , ("textquotedblright", return (str "”"))
+  , ("/", pure mempty) -- italic correction
+  , ("\\", linebreak <$ (do inTableCell <- sInTableCell <$> getState
+                            guard $ not inTableCell
+                            optional rawopt
+                            spaces))
+  , (",", lit "\8198")
+  , ("@", pure mempty)
+  , (" ", lit "\160")
+  , ("ps", pure $ str "PS." <> space)
+  , ("TeX", lit "TeX")
+  , ("LaTeX", lit "LaTeX")
+  , ("bar", lit "|")
+  , ("textless", lit "<")
+  , ("textgreater", lit ">")
+  , ("textbackslash", lit "\\")
+  , ("backslash", lit "\\")
+  , ("slash", lit "/")
+  -- fontawesome
+  , ("faCheck", lit "\10003")
+  , ("faClose", lit "\10007")
+  -- hyphenat
+  , ("bshyp", lit "\\\173")
+  , ("fshyp", lit "/\173")
+  , ("dothyp", lit ".\173")
+  , ("colonhyp", lit ":\173")
+  , ("hyp", lit "-")
+  -- ngerman (babel)
+  , ("glq", lit "‚")
+  , ("grq", lit "‘")
+  , ("glqq", lit "„")
+  , ("grqq", lit "“")
+  , ("flq", lit "‹")
+  , ("frq", lit "›")
+  , ("flqq", lit "«")
+  , ("frqq", lit "»")
+  , ("dq", lit "\"")
+  -- fontspec
+  , ("guillemetleft", lit "«")
+  , ("guillemotleft", lit "«")
+  , ("guillemetright", lit "»")
+  , ("guillemotright", lit "»")
+  , ("guilsinglleft", lit "‹")
+  , ("guilsinglright", lit "›")
+  , ("quotedblbase", lit "„")
+  , ("quotesinglbase", lit ",")
+  , ("textquotedbl", lit "\"")
+  ]
+
+biblatexInlineCommands :: PandocMonad m
+                       => LP m Inlines -> M.Map Text (LP m Inlines)
+biblatexInlineCommands tok = M.fromList
+  -- biblatex misc
+  [ ("RN", romanNumeralUpper)
+  , ("Rn", romanNumeralLower)
+  , ("mkbibquote", spanWith nullAttr . doubleQuoted <$> tok)
+  , ("mkbibemph", spanWith nullAttr . emph <$> tok)
+  , ("mkbibitalic", spanWith nullAttr . emph <$> tok)
+  , ("mkbibbold", spanWith nullAttr . strong <$> tok)
+  , ("mkbibparens",
+       spanWith nullAttr . (\x -> str "(" <> x <> str ")") <$> tok)
+  , ("mkbibbrackets",
+       spanWith nullAttr . (\x -> str "[" <> x <> str "]") <$> tok)
+  , ("autocap", spanWith nullAttr <$> tok)
+  , ("textnormal", spanWith ("",["nodecor"],[]) <$> tok)
+  , ("bibstring",
+       (\x -> spanWith ("",[],[("bibstring",x)]) (str x)) . untokenize
+         <$> braced)
+  , ("adddot", pure (str "."))
+  , ("adddotspace", pure (spanWith nullAttr (str "." <> space)))
+  , ("addabbrvspace", pure space)
+  , ("hyphen", pure (str "-"))
+  ]
+
+nameCommands :: PandocMonad m => M.Map Text (LP m Inlines)
+nameCommands = M.fromList
+  [ ("figurename", doTerm Translations.Figure)
+  , ("prefacename", doTerm Translations.Preface)
+  , ("refname", doTerm Translations.References)
+  , ("bibname", doTerm Translations.Bibliography)
+  , ("chaptername", doTerm Translations.Chapter)
+  , ("partname", doTerm Translations.Part)
+  , ("contentsname", doTerm Translations.Contents)
+  , ("listfigurename", doTerm Translations.ListOfFigures)
+  , ("listtablename", doTerm Translations.ListOfTables)
+  , ("indexname", doTerm Translations.Index)
+  , ("abstractname", doTerm Translations.Abstract)
+  , ("tablename", doTerm Translations.Table)
+  , ("enclname", doTerm Translations.Encl)
+  , ("ccname", doTerm Translations.Cc)
+  , ("headtoname", doTerm Translations.To)
+  , ("pagename", doTerm Translations.Page)
+  , ("seename", doTerm Translations.See)
+  , ("seealsoname", doTerm Translations.SeeAlso)
+  , ("proofname", doTerm Translations.Proof)
+  , ("glossaryname", doTerm Translations.Glossary)
+  , ("lstlistingname", doTerm Translations.Listing)
+  ]
+
+refCommands :: PandocMonad m => M.Map Text (LP m Inlines)
+refCommands = M.fromList
+  [ ("label", rawInlineOr "label" dolabel)
+  , ("ref", rawInlineOr "ref" $ doref "ref")
+  , ("cref", rawInlineOr "cref" $ doref "ref+label")       -- from cleveref.sty
+  , ("Cref", rawInlineOr "Cref" $ doref "ref+Label")       -- from cleveref.sty
+  , ("vref", rawInlineOr "vref" $ doref "ref")  -- from varioref.sty
+  , ("eqref", rawInlineOr "eqref" $ doref "eqref")   -- from amsmath.sty
+  , ("autoref", rawInlineOr "autoref" $ doref "ref+label") -- from hyperref.sty
+  ]
+
+acronymCommands :: PandocMonad m => M.Map Text (LP m Inlines)
+acronymCommands = M.fromList
+  -- glossaries package
+  [ ("gls", doAcronym "short")
+  , ("Gls", doAcronym "short")
+  , ("glsdesc", doAcronym "long")
+  , ("Glsdesc", doAcronym "long")
+  , ("GLSdesc", doAcronym "long")
+  , ("acrlong", doAcronym "long")
+  , ("Acrlong", doAcronym "long")
+  , ("acrfull", doAcronym "full")
+  , ("Acrfull", doAcronym "full")
+  , ("acrshort", doAcronym "abbrv")
+  , ("Acrshort", doAcronym "abbrv")
+  , ("glspl", doAcronymPlural "short")
+  , ("Glspl", doAcronymPlural "short")
+  , ("glsdescplural", doAcronymPlural "long")
+  , ("Glsdescplural", doAcronymPlural "long")
+  , ("GLSdescplural", doAcronymPlural "long")
+  -- acronyms package
+  , ("ac", doAcronym "short")
+  , ("acf", doAcronym "full")
+  , ("acs", doAcronym "abbrv")
+  , ("acl", doAcronym "long")
+  , ("acp", doAcronymPlural "short")
+  , ("acfp", doAcronymPlural "full")
+  , ("acsp", doAcronymPlural "abbrv")
+  , ("aclp", doAcronymPlural "long")
+  , ("Ac", doAcronym "short")
+  , ("Acf", doAcronym "full")
+  , ("Acs", doAcronym "abbrv")
+  , ("Acl", doAcronym "long")
+  , ("Acp", doAcronymPlural "short")
+  , ("Acfp", doAcronymPlural "full")
+  , ("Acsp", doAcronymPlural "abbrv")
+  , ("Aclp", doAcronymPlural "long")
+  ]
+
+doAcronym :: PandocMonad m => Text -> LP m Inlines
+doAcronym form = do
+  acro <- braced
+  return . mconcat $ [spanWith ("",[],[("acronym-label", untokenize acro),
+    ("acronym-form", "singular+" <> form)])
+    $ str $ untokenize acro]
+
+doAcronymPlural :: PandocMonad m => Text -> LP m Inlines
+doAcronymPlural form = do
+  acro <- braced
+  let plural = str "s"
+  return . mconcat $ [spanWith ("",[],[("acronym-label", untokenize acro),
+    ("acronym-form", "plural+" <> form)]) $
+   mconcat [str $ untokenize acro, plural]]
diff --git a/src/Text/Pandoc/Readers/LaTeX/Lang.hs b/src/Text/Pandoc/Readers/LaTeX/Lang.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Readers/LaTeX/Lang.hs
@@ -0,0 +1,238 @@
+{-# LANGUAGE OverloadedStrings #-}
+{- |
+   Module      : Text.Pandoc.Readers.LaTeX.Lang
+   Copyright   : Copyright (C) 2018-2024 John MacFarlane
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : John MacFarlane <jgm@berkeley.edu>
+   Stability   : alpha
+   Portability : portable
+
+Functions for parsing polyglossia and babel language specifiers to
+BCP47 'Lang'.
+-}
+module Text.Pandoc.Readers.LaTeX.Lang
+  ( setDefaultLanguage
+  , polyglossiaLangToBCP47
+  , babelLangToBCP47
+  , enquoteCommands
+  , inlineLanguageCommands
+  )
+where
+import qualified Data.Map as M
+import Data.Text (Text)
+import qualified Data.Text as T
+import Text.Pandoc.Shared (extractSpaces)
+import Text.Collate.Lang (Lang(..), renderLang)
+import Text.Pandoc.Class (PandocMonad(..))
+import Text.Pandoc.Translations (setTranslations)
+import Text.Pandoc.Readers.LaTeX.Parsing
+import Text.Pandoc.Parsing (updateState, option, getState, QuoteContext(..),
+                            withQuoteContext)
+import Text.Pandoc.Builder (Blocks, Inlines, setMeta, str, spanWith,
+                            singleQuoted, doubleQuoted)
+
+enquote :: PandocMonad m
+        => LP m Inlines
+        -> Bool -> Maybe Text -> LP m Inlines
+enquote tok starred mblang = do
+  skipopts
+  let lang = mblang >>= babelLangToBCP47
+  let langspan = case lang of
+                      Nothing -> id
+                      Just l  -> spanWith ("",[],[("lang", renderLang l)])
+  quoteContext <- sQuoteContext <$> getState
+  if starred || quoteContext == InDoubleQuote
+     then singleQuoted . langspan <$> withQuoteContext InSingleQuote tok
+     else doubleQuoted . langspan <$> withQuoteContext InDoubleQuote tok
+
+enquoteCommands :: PandocMonad m
+                => LP m Inlines -> M.Map Text (LP m Inlines)
+enquoteCommands tok = M.fromList
+  [ ("enquote*", enquote tok True Nothing)
+  , ("enquote", enquote tok False Nothing)
+  -- foreignquote is supposed to use native quote marks
+  , ("foreignquote*", braced >>= enquote tok True . Just . untokenize)
+  , ("foreignquote", braced >>= enquote tok False . Just . untokenize)
+  -- hypehnquote uses regular quotes
+  , ("hyphenquote*", braced >>= enquote tok True . Just . untokenize)
+  , ("hyphenquote", braced >>= enquote tok False . Just . untokenize)
+  ]
+
+foreignlanguage :: PandocMonad m => LP m Inlines -> LP m Inlines
+foreignlanguage tok = do
+  babelLang <- untokenize <$> braced
+  case babelLangToBCP47 babelLang of
+       Just lang -> spanWith ("", [], [("lang",  renderLang lang)]) <$> tok
+       _ -> tok
+
+inlineLanguageCommands :: PandocMonad m
+                       => LP m Inlines -> M.Map Text (LP m Inlines)
+inlineLanguageCommands tok =
+  M.fromList $
+    ("foreignlanguage", foreignlanguage tok) :
+    (mk <$> M.toList polyglossiaLangToBCP47)
+  where
+    mk (polyglossia, bcp47Func) =
+      ("text" <> polyglossia, inlineLanguage tok bcp47Func)
+
+inlineLanguage :: PandocMonad m
+               => LP m Inlines -> (Text -> Lang) -> LP m Inlines
+inlineLanguage tok bcp47Func = do
+  o <- option "" $ T.filter (\c -> c /= '[' && c /= ']')
+                <$> rawopt
+  let lang = renderLang $ bcp47Func o
+  extractSpaces (spanWith ("", [], [("lang", lang)])) <$> tok
+
+setDefaultLanguage :: PandocMonad m => LP m Blocks
+setDefaultLanguage = do
+  o <- option "" $ T.filter (\c -> c /= '[' && c /= ']')
+                <$> rawopt
+  polylang <- untokenize <$> braced
+  case M.lookup polylang polyglossiaLangToBCP47 of
+       Nothing -> return mempty -- TODO mzero? warning?
+       Just langFunc -> do
+         let l = langFunc o
+         setTranslations l
+         updateState $ setMeta "lang" $ str (renderLang l)
+         return mempty
+
+polyglossiaLangToBCP47 :: M.Map T.Text (T.Text -> Lang)
+polyglossiaLangToBCP47 = M.fromList
+  [ ("arabic", \o -> case T.filter (/=' ') o of
+       "locale=algeria"    -> Lang "ar" Nothing (Just "DZ") [] [] []
+       "locale=mashriq"    -> Lang "ar" Nothing (Just "SY") [] [] []
+       "locale=libya"      -> Lang "ar" Nothing (Just "LY") [] [] []
+       "locale=morocco"    -> Lang "ar" Nothing (Just "MA") [] [] []
+       "locale=mauritania" -> Lang "ar" Nothing (Just "MR") [] [] []
+       "locale=tunisia"    -> Lang "ar" Nothing (Just "TN") [] [] []
+       _                   -> Lang "ar" Nothing Nothing     [] [] [])
+  , ("german", \o -> case T.filter (/=' ') o of
+       "spelling=old" -> Lang "de" Nothing (Just "DE") ["1901"] [] []
+       "variant=austrian,spelling=old"
+                       -> Lang "de" Nothing (Just "AT") ["1901"] [] []
+       "variant=austrian" -> Lang "de" Nothing (Just "AT") [] [] []
+       "variant=swiss,spelling=old"
+                       -> Lang "de" Nothing (Just "CH") ["1901"] [] []
+       "variant=swiss" -> Lang "de" Nothing (Just "CH") [] [] []
+       _ -> Lang "de" Nothing Nothing [] [] [])
+  , ("lsorbian", \_ -> Lang "dsb" Nothing Nothing [] [] [])
+  , ("greek", \o -> case T.filter (/=' ') o of
+       "variant=poly"    -> Lang "el" Nothing (Just "polyton") [] [] []
+       "variant=ancient" -> Lang "grc" Nothing Nothing [] [] []
+       _                 -> Lang "el" Nothing Nothing [] [] [])
+  , ("english", \o -> case T.filter (/=' ') o of
+       "variant=australian" -> Lang "en" Nothing (Just "AU") [] [] []
+       "variant=canadian"   -> Lang "en" Nothing (Just "CA") [] [] []
+       "variant=british"    -> Lang "en" Nothing (Just "GB") [] [] []
+       "variant=newzealand" -> Lang "en" Nothing (Just "NZ") [] [] []
+       "variant=american"   -> Lang "en" Nothing (Just "US") [] [] []
+       _                    -> Lang "en" Nothing Nothing     [] [] [])
+  , ("usorbian", \_ -> Lang "hsb" Nothing Nothing [] [] [])
+  , ("latin", \o -> case T.filter (/=' ') o of
+       "variant=classic" -> Lang "la" Nothing Nothing ["x-classic"] [] []
+       _                 -> Lang "la" Nothing Nothing [] [] [])
+  , ("slovenian", \_ -> Lang "sl" Nothing Nothing [] [] [])
+  , ("serbianc", \_ -> Lang "sr" (Just "Cyrl") Nothing [] [] [])
+  , ("pinyin", \_ -> Lang "zh" (Just "Latn") Nothing ["pinyin"] [] [])
+  , ("afrikaans", \_ -> simpleLang "af")
+  , ("amharic", \_ -> simpleLang "am")
+  , ("assamese", \_ -> simpleLang "as")
+  , ("asturian", \_ -> simpleLang "ast")
+  , ("bulgarian", \_ -> simpleLang "bg")
+  , ("bengali", \_ -> simpleLang "bn")
+  , ("tibetan", \_ -> simpleLang "bo")
+  , ("breton", \_ -> simpleLang "br")
+  , ("catalan", \_ -> simpleLang "ca")
+  , ("welsh", \_ -> simpleLang "cy")
+  , ("czech", \_ -> simpleLang "cs")
+  , ("coptic", \_ -> simpleLang "cop")
+  , ("danish", \_ -> simpleLang "da")
+  , ("divehi", \_ -> simpleLang "dv")
+  , ("esperanto", \_ -> simpleLang "eo")
+  , ("spanish", \_ -> simpleLang "es")
+  , ("estonian", \_ -> simpleLang "et")
+  , ("basque", \_ -> simpleLang "eu")
+  , ("farsi", \_ -> simpleLang "fa")
+  , ("finnish", \_ -> simpleLang "fi")
+  , ("french", \_ -> simpleLang "fr")
+  , ("friulan", \_ -> simpleLang "fur")
+  , ("irish", \_ -> simpleLang "ga")
+  , ("scottish", \_ -> simpleLang "gd")
+  , ("ethiopic", \_ -> simpleLang "gez")
+  , ("galician", \_ -> simpleLang "gl")
+  , ("hebrew", \_ -> simpleLang "he")
+  , ("hindi", \_ -> simpleLang "hi")
+  , ("croatian", \_ -> simpleLang "hr")
+  , ("magyar", \_ -> simpleLang "hu")
+  , ("armenian", \_ -> simpleLang "hy")
+  , ("gujarati", \_ -> simpleLang "gu")
+  , ("interlingua", \_ -> simpleLang "ia")
+  , ("indonesian", \_ -> simpleLang "id")
+  , ("icelandic", \_ -> simpleLang "is")
+  , ("italian", \_ -> simpleLang "it")
+  , ("japanese", \_ -> simpleLang "ja")
+  , ("khmer", \_ -> simpleLang "km")
+  , ("kurmanji", \_ -> simpleLang "kmr")
+  , ("kannada", \_ -> simpleLang "kn")
+  , ("korean", \_ -> simpleLang "ko")
+  , ("lao", \_ -> simpleLang "lo")
+  , ("lithuanian", \_ -> simpleLang "lt")
+  , ("latvian", \_ -> simpleLang "lv")
+  , ("malayalam", \_ -> simpleLang "ml")
+  , ("mongolian", \_ -> simpleLang "mn")
+  , ("marathi", \_ -> simpleLang "mr")
+  , ("dutch", \_ -> simpleLang "nl")
+  , ("nynorsk", \_ -> simpleLang "nn")
+  , ("norsk", \_ -> simpleLang "no")
+  , ("nko", \_ -> simpleLang "nqo")
+  , ("occitan", \_ -> simpleLang "oc")
+  , ("oriya", \_ -> simpleLang "or")
+  , ("punjabi", \_ -> simpleLang "pa")
+  , ("polish", \_ -> simpleLang "pl")
+  , ("piedmontese", \_ -> simpleLang "pms")
+  , ("portuguese", \_ -> simpleLang "pt")
+  , ("romansh", \_ -> simpleLang "rm")
+  , ("romanian", \_ -> simpleLang "ro")
+  , ("russian", \_ -> simpleLang "ru")
+  , ("sanskrit", \_ -> simpleLang "sa")
+  , ("samin", \_ -> simpleLang "se")
+  , ("slovak", \_ -> simpleLang "sk")
+  , ("albanian", \_ -> simpleLang "sq")
+  , ("serbian", \_ -> simpleLang "sr")
+  , ("swedish", \_ -> simpleLang "sv")
+  , ("syriac", \_ -> simpleLang "syr")
+  , ("tamil", \_ -> simpleLang "ta")
+  , ("telugu", \_ -> simpleLang "te")
+  , ("thai", \_ -> simpleLang "th")
+  , ("turkmen", \_ -> simpleLang "tk")
+  , ("turkish", \_ -> simpleLang "tr")
+  , ("ukrainian", \_ -> simpleLang "uk")
+  , ("urdu", \_ -> simpleLang "ur")
+  , ("vietnamese", \_ -> simpleLang "vi")
+  ]
+
+simpleLang :: Text -> Lang
+simpleLang l = Lang l Nothing Nothing [] [] []
+
+babelLangToBCP47 :: T.Text -> Maybe Lang
+babelLangToBCP47 s =
+  case s of
+       "austrian" -> Just $ Lang "de" Nothing (Just "AT") ["1901"] [] []
+       "naustrian" -> Just $ Lang "de" Nothing (Just "AT") [] [] []
+       "swissgerman" -> Just $ Lang "de" Nothing (Just "CH") ["1901"] [] []
+       "nswissgerman" -> Just $ Lang "de" Nothing (Just "CH") [] [] []
+       "german" -> Just $ Lang "de" Nothing (Just "DE") ["1901"] [] []
+       "ngerman" -> Just $ Lang "de" Nothing (Just "DE") [] [] []
+       "lowersorbian" -> Just $ Lang "dsb" Nothing Nothing [] [] []
+       "uppersorbian" -> Just $ Lang "hsb" Nothing Nothing [] [] []
+       "polytonicgreek" -> Just $ Lang "el" Nothing Nothing ["polyton"] [] []
+       "polutonikogreek" -> Just $ Lang "el" Nothing Nothing ["polyton"] [] []
+       "slovene" -> Just $ simpleLang "sl"
+       "australian" -> Just $ Lang "en" Nothing (Just "AU") [] [] []
+       "canadian" -> Just $ Lang "en" Nothing (Just "CA") [] [] []
+       "british" -> Just $ Lang "en" Nothing (Just "GB") [] [] []
+       "newzealand" -> Just $ Lang "en" Nothing (Just "NZ") [] [] []
+       "american" -> Just $ Lang "en" Nothing (Just "US") [] [] []
+       "classiclatin" -> Just $ Lang "la" Nothing Nothing ["x-classic"] [] []
+       _ -> ($ "") <$> M.lookup s polyglossiaLangToBCP47
diff --git a/src/Text/Pandoc/Readers/LaTeX/Macro.hs b/src/Text/Pandoc/Readers/LaTeX/Macro.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Readers/LaTeX/Macro.hs
@@ -0,0 +1,235 @@
+{-# LANGUAGE OverloadedStrings #-}
+module Text.Pandoc.Readers.LaTeX.Macro
+  ( macroDef
+  )
+where
+import Text.Pandoc.Extensions (Extension(..))
+import Text.Pandoc.Logging (LogMessage(MacroAlreadyDefined))
+import Text.Pandoc.Readers.LaTeX.Parsing
+import Text.Pandoc.TeX
+import Text.Pandoc.Class
+import Text.Pandoc.Shared (safeRead)
+import Text.Pandoc.Parsing hiding (blankline, mathDisplay, mathInline,
+                            optional, space, spaces, withRaw, (<|>))
+import Control.Applicative ((<|>), optional)
+import qualified Data.Map as M
+import Data.Text (Text)
+import qualified Data.Text as T
+import qualified Data.List.NonEmpty as NonEmpty
+import Data.List.NonEmpty (NonEmpty(..))
+
+macroDef :: (PandocMonad m, Monoid a) => (Text -> a) -> LP m a
+macroDef constructor = do
+    (_, s) <- withRaw (commandDef <|> environmentDef)
+    (constructor (untokenize s) <$
+      guardDisabled Ext_latex_macros)
+     <|> return mempty
+  where commandDef = do
+          nameMacroPairs <- newcommand <|>
+            checkGlobal (letmacro <|> edefmacro <|> defmacro <|> newif)
+          guardDisabled Ext_latex_macros <|>
+            mapM_ insertMacro nameMacroPairs
+        environmentDef = do
+          mbenv <- newenvironment
+          case mbenv of
+            Nothing -> return ()
+            Just (name, macro1, macro2) ->
+              guardDisabled Ext_latex_macros <|>
+                do insertMacro (name, macro1)
+                   insertMacro ("end" <> name, macro2)
+        -- @\newenvironment{envname}[n-args][default]{begin}{end}@
+        -- is equivalent to
+        -- @\newcommand{\envname}[n-args][default]{begin}@
+        -- @\newcommand{\endenvname}@
+
+insertMacro :: PandocMonad m => (Text, Macro) -> LP m ()
+insertMacro (name, macro'@(Macro GlobalScope _ _ _ _)) =
+  updateState $ \s ->
+     s{ sMacros = NonEmpty.map (M.insert name macro') (sMacros s) }
+insertMacro (name, macro'@(Macro GroupScope _ _ _ _)) =
+  updateState $ \s ->
+     s{ sMacros = M.insert name macro' (NonEmpty.head (sMacros s)) :|
+                      NonEmpty.tail (sMacros s) }
+
+lookupMacro :: PandocMonad m => Text -> LP m Macro
+lookupMacro name = do
+   macros :| _ <- sMacros <$> getState
+   case M.lookup name macros of
+     Just m -> return m
+     Nothing -> fail "Macro not found"
+
+letmacro :: PandocMonad m => LP m [(Text, Macro)]
+letmacro = do
+  controlSeq "let"
+  withVerbatimMode $ do
+    Tok _ (CtrlSeq name) _ <- anyControlSeq
+    optional $ symbol '='
+    spaces
+    -- we first parse in verbatim mode, and then expand macros,
+    -- because we don't want \let\foo\bar to turn into
+    -- \let\foo hello if we have previously \def\bar{hello}
+    target <- anyControlSeq <|> singleChar
+    case target of
+      (Tok _ (CtrlSeq name') _) ->
+         (do m <- lookupMacro name'
+             pure [(name, m)])
+         <|> pure [(name,
+                    Macro GroupScope ExpandWhenDefined [] Nothing [target])]
+      _ -> pure [(name, Macro GroupScope ExpandWhenDefined [] Nothing [target])]
+
+checkGlobal :: PandocMonad m => LP m [(Text, Macro)] -> LP m [(Text, Macro)]
+checkGlobal p =
+  (controlSeq "global" *>
+      (map (\(n, Macro _ expand arg optarg contents) ->
+                (n, Macro GlobalScope expand arg optarg contents)) <$> p))
+   <|> p
+
+edefmacro :: PandocMonad m => LP m [(Text, Macro)]
+edefmacro = do
+  scope <- (GroupScope <$ controlSeq "edef")
+       <|> (GlobalScope <$ controlSeq "xdef")
+  (name, contents) <- withVerbatimMode $ do
+    Tok _ (CtrlSeq name) _ <- anyControlSeq
+    -- we first parse in verbatim mode, and then expand macros,
+    -- because we don't want \let\foo\bar to turn into
+    -- \let\foo hello if we have previously \def\bar{hello}
+    contents <- bracedOrToken
+    return (name, contents)
+  -- expand macros
+  contents' <- parseFromToks (many anyTok) contents
+  return [(name, Macro scope ExpandWhenDefined [] Nothing contents')]
+
+defmacro :: PandocMonad m => LP m [(Text, Macro)]
+defmacro = do
+  -- we use withVerbatimMode, because macros are to be expanded
+  -- at point of use, not point of definition
+  scope <- (GroupScope <$ controlSeq "def")
+       <|> (GlobalScope <$ controlSeq "gdef")
+  withVerbatimMode $ do
+    Tok _ (CtrlSeq name) _ <- anyControlSeq
+    argspecs <- many (argspecArg <|> argspecPattern)
+    contents <- bracedOrToken
+    return [(name, Macro scope ExpandWhenUsed argspecs Nothing contents)]
+
+-- \newif\iffoo' defines:
+-- \iffoo to be \iffalse
+-- \footrue to be a command that defines \iffoo to be \iftrue
+-- \foofalse to be a command that defines \iffoo to be \iffalse
+newif :: PandocMonad m => LP m [(Text, Macro)]
+newif = do
+  controlSeq "newif"
+  withVerbatimMode $ do
+    Tok pos (CtrlSeq name) _ <- anyControlSeq
+    -- \def\iffoo\iffalse
+    -- \def\footrue{\def\iffoo\iftrue}
+    -- \def\foofalse{\def\iffoo\iffalse}
+    let base = T.drop 2 name
+    return [ (name, Macro GroupScope ExpandWhenUsed [] Nothing
+                    [Tok pos (CtrlSeq "iffalse") "\\iffalse"])
+           , (base <> "true",
+                   Macro GroupScope ExpandWhenUsed [] Nothing
+                   [ Tok pos (CtrlSeq "def") "\\def"
+                   , Tok pos (CtrlSeq name) ("\\" <> name)
+                   , Tok pos Symbol "{"
+                   , Tok pos (CtrlSeq "iftrue") "\\iftrue"
+                   , Tok pos Symbol "}"
+                   ])
+           , (base <> "false",
+                   Macro GroupScope ExpandWhenUsed [] Nothing
+                   [ Tok pos (CtrlSeq "def") "\\def"
+                   , Tok pos (CtrlSeq name) ("\\" <> name)
+                   , Tok pos Symbol "{"
+                   , Tok pos (CtrlSeq "iffalse") "\\iffalse"
+                   , Tok pos Symbol "}"
+                   ])
+           ]
+
+argspecArg :: PandocMonad m => LP m ArgSpec
+argspecArg = do
+  Tok _ (Arg i) _ <- satisfyTok isArgTok
+  return $ ArgNum i
+
+argspecPattern :: PandocMonad m => LP m ArgSpec
+argspecPattern =
+  Pattern <$> many1 (satisfyTok (\(Tok _ toktype' txt) ->
+                              (toktype' == Symbol || toktype' == Word) &&
+                              (txt /= "{" && txt /= "\\" && txt /= "}")))
+
+newcommand :: PandocMonad m => LP m [(Text, Macro)]
+newcommand = do
+  Tok pos (CtrlSeq mtype) _ <- controlSeq "newcommand" <|>
+                             controlSeq "renewcommand" <|>
+                             controlSeq "providecommand" <|>
+                             controlSeq "DeclareMathOperator" <|>
+                             controlSeq "DeclareRobustCommand"
+  withVerbatimMode $ do
+    Tok _ (CtrlSeq name) txt <- do
+      optional (symbol '*')
+      anyControlSeq <|>
+        (symbol '{' *> spaces *> anyControlSeq <* spaces <* symbol '}')
+    spaces
+    numargs <- option 0 $ try bracketedNum
+    let argspecs = map ArgNum [1..numargs]
+    spaces
+    optarg <- option Nothing $ Just <$> try bracketedToks
+    spaces
+    contents' <- bracedOrToken
+    let contents =
+         case mtype of
+              "DeclareMathOperator" ->
+                 Tok pos (CtrlSeq "mathop") "\\mathop"
+                 : Tok pos Symbol "{"
+                 : Tok pos (CtrlSeq "mathrm") "\\mathrm"
+                 : Tok pos Symbol "{"
+                 : (contents' ++
+                   [ Tok pos Symbol "}", Tok pos Symbol "}" ])
+              _                     -> contents'
+    let macro = Macro GroupScope ExpandWhenUsed argspecs optarg contents
+    (do lookupMacro name
+        case mtype of
+          "providecommand" -> return []
+          "renewcommand" -> return [(name, macro)]
+          _ -> [] <$ report (MacroAlreadyDefined txt pos))
+      <|> pure [(name, macro)]
+
+newenvironment :: PandocMonad m => LP m (Maybe (Text, Macro, Macro))
+newenvironment = do
+  pos <- getPosition
+  Tok _ (CtrlSeq mtype) _ <- controlSeq "newenvironment" <|>
+                             controlSeq "renewenvironment" <|>
+                             controlSeq "provideenvironment"
+  withVerbatimMode $ do
+    optional $ symbol '*'
+    spaces
+    name <- untokenize <$> braced
+    spaces
+    numargs <- option 0 $ try bracketedNum
+    spaces
+    optarg <- option Nothing $ Just <$> try bracketedToks
+    let argspecs = map (\i -> ArgNum i) [1..numargs]
+    startcontents <- spaces >> bracedOrToken
+    endcontents <- spaces >> bracedOrToken
+    -- we need the environment to be in a group so macros defined
+    -- inside behave correctly:
+    let bg = Tok pos (CtrlSeq "bgroup") "\\bgroup "
+    let eg = Tok pos (CtrlSeq "egroup") "\\egroup "
+    let result = (name,
+                    Macro GroupScope ExpandWhenUsed argspecs optarg
+                      (bg:startcontents),
+                    Macro GroupScope ExpandWhenUsed [] Nothing
+                      (endcontents ++ [eg]))
+    (do lookupMacro name
+        case mtype of
+          "provideenvironment" -> return Nothing
+          "renewenvironment" -> return (Just result)
+          _ -> do
+             report $ MacroAlreadyDefined name pos
+             return Nothing)
+      <|> return (Just result)
+
+bracketedNum :: PandocMonad m => LP m Int
+bracketedNum = do
+  ds <- untokenize <$> bracketedToks
+  case safeRead ds of
+       Just i -> return i
+       _      -> return 0
diff --git a/src/Text/Pandoc/Readers/LaTeX/Math.hs b/src/Text/Pandoc/Readers/LaTeX/Math.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Readers/LaTeX/Math.hs
@@ -0,0 +1,253 @@
+{-# LANGUAGE OverloadedStrings #-}
+module Text.Pandoc.Readers.LaTeX.Math
+  ( withMathMode
+  , dollarsMath
+  , inlineEnvironments
+  , inlineEnvironmentNames
+  , inlineEnvironment
+  , mathInline
+  , mathDisplay
+  , theoremstyle
+  , theoremEnvironment
+  , newtheorem
+  , proof
+  )
+where
+import Data.Maybe (fromMaybe, mapMaybe, listToMaybe)
+import qualified Data.List as L
+import Text.Pandoc.Walk (walk)
+import Text.Pandoc.Builder as B
+import qualified Data.Sequence as Seq
+import Text.Pandoc.Readers.LaTeX.Parsing
+import Text.Pandoc.TeX
+import Text.Pandoc.Class
+import Text.Pandoc.Shared (trimMath, trimr)
+import Text.Pandoc.Parsing hiding (blankline, mathDisplay, mathInline,
+                            optional, space, spaces, withRaw, (<|>))
+import Control.Applicative ((<|>), optional)
+import Control.Monad (guard, mzero)
+import qualified Data.Map as M
+import Data.Text (Text)
+
+withMathMode :: PandocMonad m => LP m a -> LP m a
+withMathMode p = do
+  oldMathMode <- sMathMode <$> getState
+  updateState $ \s -> s{ sMathMode = True }
+  result <- p
+  updateState $ \s -> s{ sMathMode = oldMathMode }
+  return result
+
+dollarsMath :: PandocMonad m => LP m Inlines
+dollarsMath = do
+  symbol '$'
+  display <- option False (True <$ symbol '$')
+  (do contents <- try $ untokenize <$> withMathMode (pDollarsMath 0)
+      if display
+         then mathDisplay contents <$ symbol '$'
+         else return $ mathInline contents)
+   <|> (guard display >> return (mathInline ""))
+
+-- Int is number of embedded groupings
+pDollarsMath :: PandocMonad m => Int -> LP m [Tok]
+pDollarsMath n = do
+  tk@(Tok _ toktype t) <- anyTok
+  case toktype of
+       Symbol | t == "$"
+              , n == 0 -> return []
+              | t == "\\" -> do
+                  tk' <- anyTok
+                  (tk :) . (tk' :) <$> pDollarsMath n
+              | t == "{" -> (tk :) <$> pDollarsMath (n+1)
+              | t == "}" ->
+                if n > 0
+                then (tk :) <$> pDollarsMath (n-1)
+                else mzero
+       _ -> (tk :) <$> pDollarsMath n
+
+mathDisplay :: Text -> Inlines
+mathDisplay = displayMath . trimMath
+
+mathInline :: Text -> Inlines
+mathInline = math . trimMath
+
+mathEnvWith :: PandocMonad m
+            => (Inlines -> a) -> Maybe Text -> Text -> LP m a
+mathEnvWith f innerEnv name = f . mathDisplay . inner <$> mathEnv name
+   where inner x = case innerEnv of
+                        Nothing -> x
+                        Just y  -> "\\begin{" <> y <> "}\n" <> x <>
+                                   "\n\\end{" <> y <> "}"
+
+mathEnv :: PandocMonad m => Text -> LP m Text
+mathEnv name = withMathMode $ do
+  optional blankline
+  res <- manyTill anyTok (end_ name)
+  return $ trimr $ untokenize res
+
+inlineEnvironment :: PandocMonad m => LP m Inlines
+inlineEnvironment = try $ do
+  controlSeq "begin"
+  name <- untokenize <$> braced
+  M.findWithDefault mzero name inlineEnvironments
+
+inlineEnvironmentNames :: [Text]
+inlineEnvironmentNames =
+  M.keys (inlineEnvironments :: M.Map Text (LP PandocPure Inlines))
+
+inlineEnvironments :: PandocMonad m => M.Map Text (LP m Inlines)
+inlineEnvironments = M.fromList [
+    ("displaymath", mathEnvWith id Nothing "displaymath")
+  , ("math", math <$> mathEnv "math")
+  , ("equation", mathEnvWith id (Just "equation") "equation")
+  , ("equation*", mathEnvWith id (Just "equation*") "equation*")
+  , ("gather", mathEnvWith id (Just "gather") "gather")
+  , ("gather*", mathEnvWith id (Just "gather*") "gather*")
+  , ("multline", mathEnvWith id (Just "multline") "multline")
+  , ("multline*", mathEnvWith id (Just "multline*") "multline*")
+  , ("eqnarray", mathEnvWith id (Just "eqnarray") "eqnarray")
+  , ("eqnarray*", mathEnvWith id (Just "eqnarray*") "eqnarray*")
+  , ("align", mathEnvWith id (Just "align") "align")
+  , ("align*", mathEnvWith id (Just "align*") "align*")
+  , ("alignat", mathEnvWith id (Just "alignat") "alignat")
+  , ("alignat*", mathEnvWith id (Just "alignat*") "alignat*")
+  , ("flalign", mathEnvWith id (Just "flalign") "flalign")
+  , ("flalign*", mathEnvWith id (Just "flalign*") "flalign*")
+  -- the following are not yet handled by texmath, so we use substitutes:
+  , ("dmath", mathEnvWith id Nothing "dmath")
+  , ("dmath*", mathEnvWith id Nothing "dmath*")
+  , ("dgroup", mathEnvWith id (Just "aligned") "dgroup")
+  , ("dgroup*", mathEnvWith id (Just "aligned") "dgroup*")
+  , ("darray", mathEnvWith id (Just "aligned") "darray")
+  , ("darray*", mathEnvWith id (Just "aligned") "darray*")
+  , ("subequations", mathEnvWith id Nothing "subequations")
+  ]
+
+theoremstyle :: PandocMonad m => LP m Blocks
+theoremstyle = do
+  stylename <- untokenize <$> braced
+  let mbstyle = case stylename of
+                  "plain"      -> Just PlainStyle
+                  "definition" -> Just DefinitionStyle
+                  "remark"     -> Just RemarkStyle
+                  _            -> Nothing
+  case mbstyle of
+    Nothing  -> return ()
+    Just sty -> updateState $ \s -> s{ sLastTheoremStyle = sty }
+  return mempty
+
+newtheorem :: PandocMonad m => LP m Blocks
+newtheorem = do
+  number <- option True (False <$ symbol '*' <* sp)
+  name <- untokenize <$> braced
+  sp
+  series <- option Nothing $ Just . untokenize <$> bracketedToks
+  sp
+  showName <- braced <|> ((:[]) <$> anyTok)
+  sp
+  syncTo <- option Nothing $ Just . untokenize <$> bracketedToks
+  sty <- sLastTheoremStyle <$> getState
+  let spec = TheoremSpec { theoremName = showName
+                         , theoremStyle = sty
+                         , theoremSeries = series
+                         , theoremSyncTo = syncTo
+                         , theoremNumber = number
+                         , theoremLastNum = DottedNum [0] }
+  tmap <- sTheoremMap <$> getState
+  updateState $ \s -> s{ sTheoremMap =
+                            M.insert name spec tmap }
+  return mempty
+
+extractLabelFromBlock :: Block -> Maybe Text
+extractLabelFromBlock (Para inlines) = extractLabel Nothing inlines
+  where
+    extractLabel = L.foldl' go
+    go :: Maybe Text -> Inline -> Maybe Text
+    go (Just t) _ = Just t
+    go Nothing (Span (_, _, attrs) _) = lookup "label" attrs
+    go Nothing _ = Nothing
+extractLabelFromBlock _ = Nothing
+
+theoremEnvironment :: PandocMonad m
+                   => LP m Blocks
+                   -> LP m Inlines
+                   -> LP m Inlines
+                   -> Text
+                   -> LP m Blocks
+theoremEnvironment blocks inlines opt name = do
+  resetCaption
+  tmap <- sTheoremMap <$> getState
+  case M.lookup name tmap of
+    Nothing -> mzero
+    Just tspec -> do
+       optTitle <- option mempty $ (\x -> space <> "(" <> x <> ")") <$> opt
+       bs <- env name blocks
+       let mblabel = listToMaybe $ mapMaybe extractLabelFromBlock (toList bs)
+
+       number <-
+         if theoremNumber tspec
+            then do
+               let name' = fromMaybe name $ theoremSeries tspec
+               num <- getNextNumber
+                   (maybe (DottedNum [0]) theoremLastNum .
+                    M.lookup name' . sTheoremMap)
+               updateState $ \s ->
+                 s{ sTheoremMap =
+                       M.adjust
+                       (\spec -> spec{ theoremLastNum = num })
+                       name'
+                       (sTheoremMap s)
+                  }
+
+               case mblabel of
+                 Just ident ->
+                   updateState $ \s ->
+                     s{ sLabels = M.insert ident
+                         (B.toList $ str (renderDottedNum num)) (sLabels s) }
+                 Nothing -> return ()
+               return $ space <> B.text (renderDottedNum num)
+            else return mempty
+       let titleEmph = case theoremStyle tspec of
+                         PlainStyle      -> B.strong
+                         DefinitionStyle -> B.strong
+                         RemarkStyle     -> B.emph
+       tname <- parseFromToks inlines (theoremName tspec)
+       let title = titleEmph (tname <> number)
+                      <> optTitle <> "." <> space
+       return $ divWith (fromMaybe "" mblabel, [name], [])
+              $ addTitle title
+              $ maybe id removeLabel mblabel
+              $ case theoremStyle tspec of
+                  PlainStyle -> walk italicize bs
+                  _          -> bs
+
+
+proof :: PandocMonad m => LP m Blocks -> LP m Inlines -> LP m Blocks
+proof blocks opt = do
+  title <- option (B.text "Proof") opt
+  bs <- env "proof" blocks
+  return $
+    B.divWith ("", ["proof"], []) $
+      addQed $ addTitle (B.emph (title <> ".")) bs
+
+addTitle :: Inlines -> Blocks -> Blocks
+addTitle ils bs =
+  case B.toList bs of
+    (Para xs : rest)
+      -> B.fromList (Para (B.toList ils ++ (Space : xs)) : rest)
+    _ -> B.para ils <> bs
+
+addQed :: Blocks -> Blocks
+addQed bs =
+  case Seq.viewr (B.unMany bs) of
+    s Seq.:> Para ils
+      -> B.Many (s Seq.|> Para (ils ++ B.toList qedSign))
+    _ -> bs <> B.para qedSign
+ where
+  qedSign = B.str "\xa0\x25FB"
+
+italicize :: Block -> Block
+italicize x@(Para [Image{}])  = x -- see #6925
+italicize x@(Plain [Image{}]) = x -- ditto
+italicize (Para ils) = Para [Emph ils]
+italicize (Plain ils) = Plain [Emph ils]
+italicize x = x
diff --git a/src/Text/Pandoc/Readers/LaTeX/Parsing.hs b/src/Text/Pandoc/Readers/LaTeX/Parsing.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Readers/LaTeX/Parsing.hs
@@ -0,0 +1,1182 @@
+{-# LANGUAGE FlexibleInstances     #-}
+{-# LANGUAGE FlexibleContexts      #-}
+{-# LANGUAGE LambdaCase            #-}
+{-# LANGUAGE BangPatterns          #-}
+{-# LANGUAGE MultiParamTypeClasses #-}
+{-# LANGUAGE OverloadedStrings     #-}
+{-# LANGUAGE ScopedTypeVariables   #-}
+{- |
+   Module      : Text.Pandoc.Readers.LaTeX.Parsing
+   Copyright   : Copyright (C) 2006-2024 John MacFarlane
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : John MacFarlane <jgm@berkeley.edu>
+   Stability   : alpha
+   Portability : portable
+
+General parsing types and functions for LaTeX.
+-}
+module Text.Pandoc.Readers.LaTeX.Parsing
+  ( DottedNum(..)
+  , renderDottedNum
+  , incrementDottedNum
+  , TheoremSpec(..)
+  , TheoremStyle(..)
+  , LaTeXState(..)
+  , defaultLaTeXState
+  , LP
+  , TokStream(..)
+  , withVerbatimMode
+  , rawLaTeXParser
+  , applyMacros
+  , tokenize
+  , tokenizeSources
+  , getInputTokens
+  , untokenize
+  , untoken
+  , satisfyTok
+  , peekTok
+  , parseFromToks
+  , disablingWithRaw
+  , doMacros
+  , doMacros'
+  , setpos
+  , anyControlSeq
+  , anySymbol
+  , isNewlineTok
+  , isWordTok
+  , isArgTok
+  , infile
+  , spaces
+  , spaces1
+  , tokTypeIn
+  , controlSeq
+  , symbol
+  , symbolIn
+  , sp
+  , whitespace
+  , newlineTok
+  , comment
+  , anyTok
+  , singleChar
+  , tokWith
+  , specialChars
+  , endline
+  , blankline
+  , primEscape
+  , bgroup
+  , egroup
+  , grouped
+  , braced
+  , braced'
+  , bracedUrl
+  , bracedOrToken
+  , bracketed
+  , bracketedToks
+  , parenWrapped
+  , dimenarg
+  , ignore
+  , withRaw
+  , keyvals
+  , verbEnv
+  , begin_
+  , end_
+  , getRawCommand
+  , skipopts
+  , rawopt
+  , overlaySpecification
+  , getNextNumber
+  , label
+  , setCaption
+  , resetCaption
+  , env
+  , addMeta
+  , removeLabel
+  ) where
+
+import Control.Applicative (many, (<|>))
+import Control.Monad
+import Control.Monad.Except (throwError)
+import Control.Monad.Trans (lift)
+import Data.Char (chr, isAlphaNum, isDigit, isLetter, ord)
+import Data.Default
+import Data.List (intercalate)
+import qualified Data.IntMap as IntMap
+import qualified Data.Map as M
+import qualified Data.Set as Set
+import Data.Text (Text)
+import Data.Maybe (fromMaybe)
+import Data.List.NonEmpty (NonEmpty(..))
+import qualified Data.List.NonEmpty as NonEmpty
+import qualified Data.Text as T
+import Text.Pandoc.Builder
+import Text.Pandoc.Class.PandocMonad (PandocMonad, report)
+import Text.Pandoc.Error
+         (PandocError (PandocMacroLoop,PandocShouldNeverHappenError))
+import Text.Pandoc.Logging
+import Text.Pandoc.Options
+import Text.Pandoc.Parsing hiding (blankline, many, mathDisplay, mathInline,
+                            space, spaces, withRaw, (<|>))
+import Text.Pandoc.TeX (ExpansionPoint (..), Macro (..),
+                                        ArgSpec (..), Tok (..), TokType (..))
+import Text.Pandoc.Shared
+import Text.Pandoc.Walk
+
+newtype DottedNum = DottedNum [Int]
+  deriving (Show, Eq)
+
+renderDottedNum :: DottedNum -> T.Text
+renderDottedNum (DottedNum xs) = T.pack $
+  intercalate "." (map show xs)
+
+incrementDottedNum :: Int -> DottedNum -> DottedNum
+incrementDottedNum level (DottedNum ns) = DottedNum $
+  case reverse (take level (ns ++ repeat 0)) of
+       (x:xs) -> reverse (x+1 : xs)
+       []     -> []  -- shouldn't happen
+
+data TheoremStyle =
+  PlainStyle | DefinitionStyle | RemarkStyle
+  deriving (Show, Eq)
+
+data TheoremSpec =
+  TheoremSpec
+    { theoremName    :: [Tok]
+    , theoremStyle   :: TheoremStyle
+    , theoremSeries  :: Maybe Text
+    , theoremSyncTo  :: Maybe Text
+    , theoremNumber  :: Bool
+    , theoremLastNum :: DottedNum }
+    deriving (Show, Eq)
+
+data LaTeXState = LaTeXState{ sOptions       :: ReaderOptions
+                            , sMeta          :: Meta
+                            , sQuoteContext  :: QuoteContext
+                            , sMacros        :: NonEmpty (M.Map Text Macro)
+                            , sContainers    :: [Text]
+                            , sLogMessages   :: [LogMessage]
+                            , sIdentifiers   :: Set.Set Text
+                            , sVerbatimMode  :: Bool
+                            , sMathMode      :: Bool
+                            , sCaption       :: Maybe Caption
+                            , sInListItem    :: Bool
+                            , sInTableCell   :: Bool
+                            , sLastHeaderNum :: DottedNum
+                            , sLastFigureNum :: DottedNum
+                            , sLastTableNum  :: DottedNum
+                            , sLastNoteNum   :: Int
+                            , sFootnoteTexts :: M.Map Int Blocks
+                            , sTheoremMap    :: M.Map Text TheoremSpec
+                            , sLastTheoremStyle :: TheoremStyle
+                            , sLastLabel     :: Maybe Text
+                            , sLabels        :: M.Map Text [Inline]
+                            , sHasChapters   :: Bool
+                            , sToggles       :: M.Map Text Bool
+                            , sFileContents  :: M.Map Text Text
+                            , sEnableWithRaw :: Bool
+                            , sRawTokens     :: IntMap.IntMap [Tok]
+                            , sLigatures     :: Bool
+                            }
+     deriving Show
+
+defaultLaTeXState :: LaTeXState
+defaultLaTeXState = LaTeXState{ sOptions       = def
+                              , sMeta          = nullMeta
+                              , sQuoteContext  = NoQuote
+                              , sMacros        = M.empty :| []
+                              , sContainers    = []
+                              , sLogMessages   = []
+                              , sIdentifiers   = Set.empty
+                              , sVerbatimMode  = False
+                              , sMathMode      = False
+                              , sCaption       = Nothing
+                              , sInListItem    = False
+                              , sInTableCell   = False
+                              , sLastHeaderNum = DottedNum []
+                              , sLastFigureNum = DottedNum []
+                              , sLastTableNum  = DottedNum []
+                              , sLastNoteNum   = 0
+                              , sFootnoteTexts = M.empty
+                              , sTheoremMap    = M.empty
+                              , sLastTheoremStyle = PlainStyle
+                              , sLastLabel     = Nothing
+                              , sLabels        = M.empty
+                              , sHasChapters   = False
+                              , sToggles       = M.empty
+                              , sFileContents  = M.empty
+                              , sEnableWithRaw = True
+                              , sRawTokens     = IntMap.empty
+                              , sLigatures     = True
+                              }
+
+instance PandocMonad m => HasQuoteContext LaTeXState m where
+  getQuoteContext = sQuoteContext <$> getState
+  withQuoteContext context parser = do
+    oldState <- getState
+    let oldQuoteContext = sQuoteContext oldState
+    setState oldState { sQuoteContext = context }
+    result <- parser
+    newState <- getState
+    setState newState { sQuoteContext = oldQuoteContext }
+    return result
+
+instance HasLogMessages LaTeXState where
+  addLogMessage msg st = st{ sLogMessages = msg : sLogMessages st }
+  getLogMessages st = reverse $ sLogMessages st
+
+instance HasIdentifierList LaTeXState where
+  extractIdentifierList     = sIdentifiers
+  updateIdentifierList f st = st{ sIdentifiers = f $ sIdentifiers st }
+
+instance HasIncludeFiles LaTeXState where
+  getIncludeFiles = sContainers
+  addIncludeFile f s = s{ sContainers = f : sContainers s }
+  dropLatestIncludeFile s = s { sContainers = drop 1 $ sContainers s }
+
+instance HasMacros LaTeXState where
+  extractMacros  st  = NonEmpty.head $ sMacros st
+  updateMacros f st  = st{ sMacros = f (NonEmpty.head (sMacros st))
+                                     :| NonEmpty.tail (sMacros st) }
+
+instance HasReaderOptions LaTeXState where
+  extractReaderOptions = sOptions
+
+instance HasMeta LaTeXState where
+  setMeta field val st =
+    st{ sMeta = setMeta field val $ sMeta st }
+  deleteMeta field st =
+    st{ sMeta = deleteMeta field $ sMeta st }
+
+instance Default LaTeXState where
+  def = defaultLaTeXState
+
+-- The Boolean is True if macros have already been expanded,
+-- False if they need expanding.
+data TokStream = TokStream !Bool [Tok]
+  deriving (Show)
+
+instance Semigroup TokStream where
+  (TokStream exp1 ts1) <> (TokStream exp2 ts2) =
+    TokStream (if null ts1 then exp2 else exp1) (ts1 <> ts2)
+
+instance Monoid TokStream where
+  mempty = TokStream False mempty
+  mappend = (<>)
+
+instance Monad m => Stream TokStream m Tok where
+  uncons (TokStream _ []) = return Nothing
+  uncons (TokStream _ (t:ts)) = return $ Just (t, TokStream False ts)
+
+type LP m = ParsecT TokStream LaTeXState m
+
+withVerbatimMode :: PandocMonad m => LP m a -> LP m a
+withVerbatimMode parser = do
+  alreadyVerbatimMode <- sVerbatimMode <$> getState
+  if alreadyVerbatimMode
+     then parser
+     else do
+       updateState $ \st -> st{ sVerbatimMode = True }
+       result <- parser
+       updateState $ \st -> st{ sVerbatimMode = False }
+       return result
+
+rawLaTeXParser :: (PandocMonad m, HasMacros s, HasReaderOptions s, Show a)
+               => [Tok] -> LP m () -> LP m a
+               -> ParsecT Sources s m (a, Text)
+rawLaTeXParser toks parser valParser = do
+  pstate <- getState
+  let lstate = def{ sOptions = extractReaderOptions pstate }
+  let lstate' = lstate { sMacros = extractMacros pstate :| [] }
+  let setStartPos = case toks of
+                      Tok pos _ _ : _ -> setPosition pos
+                      _ -> return ()
+  let preparser = setStartPos >> parser
+  let rawparser = (,) <$> withRaw valParser <*> getState
+  res' <- lift $ runParserT (withRaw (preparser >> getPosition))
+                            lstate "chunk" $ TokStream False toks
+  case res' of
+       Left _    -> mzero
+       Right (endpos, toks') -> do
+         res <- lift $ runParserT rawparser lstate' "chunk"
+                     $ TokStream False toks'
+         case res of
+              Left _    -> mzero
+              Right ((val, raw), st) -> do
+                updateState (updateMacros ((NonEmpty.head (sMacros st)) <>))
+                let rawChar = do
+                      pos <- getPosition
+                      if pos >= endpos
+                         then mzero
+                         else anyChar
+                result <- (guardEnabled Ext_latex_macros
+                             >> (untokenize raw <$ skipMany rawChar))
+                          <|> T.pack <$> many rawChar
+                -- ensure we end with space if input did, see #4442
+                let result' =
+                      case reverse toks' of
+                        (Tok _ (CtrlSeq _) t : _)
+                         | " " `T.isSuffixOf` t
+                         , not (" " `T.isSuffixOf` result)
+                          -> result <> " "
+                        _ -> result
+                return (val, result')
+
+applyMacros :: (PandocMonad m, HasMacros s, HasReaderOptions s)
+            => Text -> ParsecT Sources s m Text
+applyMacros s = (guardDisabled Ext_latex_macros >> return s) <|>
+   do let retokenize = untokenize <$> many anyTok
+      pstate <- getState
+      let lstate = def{ sOptions = extractReaderOptions pstate
+                      , sMacros  = extractMacros pstate :| [] }
+      res <- runParserT retokenize lstate "math" $
+                 TokStream False (tokenize (initialPos "math") s)
+      case res of
+           Left e   -> Prelude.fail (show e)
+           Right s' -> return s'
+
+{-
+When tokenize or untokenize change, test with this
+QuickCheck property:
+
+> tokUntokRoundtrip :: String -> Bool
+> tokUntokRoundtrip s =
+>   let t = T.pack s in untokenize (tokenize "random" t) == t
+-}
+
+tokenizeSources :: Sources -> [Tok]
+tokenizeSources = concatMap tokenizeSource . unSources
+ where
+   tokenizeSource (pos, t) = tokenize pos t
+
+-- Return tokens from input sources. Ensure that starting position is
+-- correct.
+getInputTokens :: PandocMonad m => ParsecT Sources s m [Tok]
+getInputTokens = do
+  pos <- getPosition
+  ss <- getInput
+  return $
+    case ss of
+      Sources [] -> []
+      Sources ((_,t):rest) -> tokenizeSources $ Sources ((pos,t):rest)
+
+tokenize :: SourcePos -> Text -> [Tok]
+tokenize = totoks False
+ where
+  totoks atIsLetter pos t =
+    case T.uncons t of
+       Nothing        -> []
+       Just (c, rest)
+         | c == '\n' ->
+           Tok pos Newline "\n"
+           : totoks atIsLetter (setSourceColumn (incSourceLine pos 1) 1) rest
+         | isSpaceOrTab c ->
+           let (sps, rest') = T.span isSpaceOrTab t
+           in  Tok pos Spaces sps
+               : totoks atIsLetter (incSourceColumn pos (T.length sps))
+                 rest'
+         | isAlphaNum c ->
+           let (ws, rest') = T.span isAlphaNum t
+           in  Tok pos Word ws
+               : totoks atIsLetter (incSourceColumn pos (T.length ws)) rest'
+         | c == '%' ->
+           let (cs, rest') = T.break (== '\n') rest
+           in  Tok pos Comment ("%" <> cs)
+               : totoks atIsLetter (incSourceColumn pos (1 + T.length cs)) rest'
+         | c == '\\' ->
+           case T.uncons rest of
+                Nothing -> [Tok pos (CtrlSeq " ") "\\"]
+                Just (d, rest')
+                  | isLetter' atIsLetter d ->
+                      let (ws, rest'') = T.span (isLetter' atIsLetter) rest
+                          (ss, rest''') = T.span isSpaceOrTab rest''
+                          atIsLetter' = case ws of
+                                          "makeatletter" -> True
+                                          "makeatother" -> False
+                                          _ -> atIsLetter
+                      in  Tok pos (CtrlSeq ws) ("\\" <> ws <> ss)
+                          : totoks atIsLetter' (incSourceColumn pos
+                               (1 + T.length ws + T.length ss)) rest'''
+                  | isSpaceOrTab d || d == '\n' ->
+                      let (w1, r1) = T.span isSpaceOrTab rest
+                          (w2, (w3, r3)) = case T.uncons r1 of
+                                          Just ('\n', r2)
+                                                  -> (T.pack "\n",
+                                                        T.span isSpaceOrTab r2)
+                                          _ -> (mempty, (mempty, r1))
+                          ws = "\\" <> w1 <> w2 <> w3
+                      in  case T.uncons r3 of
+                               Just ('\n', _) ->
+                                 Tok pos (CtrlSeq " ") ("\\" <> w1)
+                                 : totoks atIsLetter
+                                    (incSourceColumn pos (T.length ws)) r1
+                               _ ->
+                                 Tok pos (CtrlSeq " ") ws
+                                 : totoks atIsLetter
+                                    (incSourceColumn pos (T.length ws)) r3
+                  | otherwise  ->
+                      Tok pos (CtrlSeq (T.singleton d)) (T.pack [c,d])
+                      : totoks atIsLetter (incSourceColumn pos 2) rest'
+         | c == '#' ->
+           case T.uncons rest of
+             Just ('#', t3) ->
+               let (t1, t2) = T.span (\d -> d >= '0' && d <= '9') t3
+               in  case safeRead t1 of
+                        Just i ->
+                           Tok pos (DeferredArg i) ("##" <> t1)
+                           : totoks atIsLetter
+                              (incSourceColumn pos (2 + T.length t1)) t2
+                        Nothing -> Tok pos Symbol "#"
+                                  : Tok (incSourceColumn pos 1) Symbol "#"
+                                  : totoks atIsLetter (incSourceColumn pos 1) t3
+             _ ->
+               let (t1, t2) = T.span (\d -> d >= '0' && d <= '9') rest
+               in  case safeRead t1 of
+                        Just i ->
+                           Tok pos (Arg i) ("#" <> t1)
+                           : totoks atIsLetter
+                               (incSourceColumn pos (1 + T.length t1)) t2
+                        Nothing -> Tok pos Symbol "#"
+                                  : totoks atIsLetter (incSourceColumn pos 1) rest
+         | c == '^' ->
+           case T.uncons rest of
+                Just ('^', rest') ->
+                  case T.uncons rest' of
+                       Just (d, rest'')
+                         | isLowerHex d ->
+                           case T.uncons rest'' of
+                                Just (e, rest''') | isLowerHex e ->
+                                  Tok pos Esc2 (T.pack ['^','^',d,e])
+                                  : totoks atIsLetter
+                                     (incSourceColumn pos 4) rest'''
+                                _ ->
+                                  Tok pos Esc1 (T.pack ['^','^',d])
+                                  : totoks atIsLetter
+                                      (incSourceColumn pos 3) rest''
+                         | d < '\128' ->
+                                  Tok pos Esc1 (T.pack ['^','^',d])
+                                  : totoks atIsLetter
+                                     (incSourceColumn pos 3) rest''
+                       _ -> Tok pos Symbol "^" :
+                            Tok (incSourceColumn pos 1) Symbol "^" :
+                            totoks atIsLetter (incSourceColumn pos 2) rest'
+                _ -> Tok pos Symbol "^"
+                     : totoks atIsLetter (incSourceColumn pos 1) rest
+         | otherwise ->
+           Tok pos Symbol (T.singleton c) :
+             totoks atIsLetter (incSourceColumn pos 1) rest
+
+isSpaceOrTab :: Char -> Bool
+isSpaceOrTab ' '  = True
+isSpaceOrTab '\t' = True
+isSpaceOrTab _    = False
+
+-- First parameter is True if @ is letter
+isLetter' :: Bool -> Char -> Bool
+isLetter' True '@' = True
+isLetter' _ c = isLetter c
+
+isLetterOrAt :: Char -> Bool
+isLetterOrAt '@' = True
+isLetterOrAt c   = isLetter c
+
+isLowerHex :: Char -> Bool
+isLowerHex x = x >= '0' && x <= '9' || x >= 'a' && x <= 'f'
+
+untokenize :: [Tok] -> Text
+untokenize = foldr untokenAccum mempty
+
+untokenAccum :: Tok -> Text -> Text
+untokenAccum (Tok _ (CtrlSeq _) t) accum =
+  -- insert space to prevent breaking a control sequence; see #5836
+  case (T.unsnoc t, T.uncons accum) of
+    (Just (_,c), Just (d,_))
+      | isLetter c
+      , isLetter d
+      -> t <> " " <> accum
+    _ -> t <> accum
+untokenAccum (Tok _ _ t) accum = t <> accum
+
+untoken :: Tok -> Text
+untoken t = untokenAccum t mempty
+
+parseFromToks :: PandocMonad m => LP m a -> [Tok] -> LP m a
+parseFromToks parser toks = do
+  oldInput <- getInput
+  setInput $ TokStream False toks
+  oldpos <- getPosition
+  case toks of
+     Tok pos _ _ : _ -> setPosition pos
+     _ -> return ()
+  -- we ignore existing raw tokens maps (see #9517)
+  oldRawTokens <- sRawTokens <$> getState
+  updateState $ \st -> st{ sRawTokens = mempty }
+  result <- parser
+  updateState $ \st -> st{ sRawTokens = oldRawTokens }
+  setInput oldInput
+  setPosition oldpos
+  return result
+
+disablingWithRaw :: PandocMonad m => LP m a -> LP m a
+disablingWithRaw parser = do
+  oldEnableWithRaw <- sEnableWithRaw <$> getState
+  updateState $ \st -> st{ sEnableWithRaw = False }
+  result <- parser
+  updateState $ \st -> st{ sEnableWithRaw = oldEnableWithRaw }
+  return result
+
+satisfyTok :: PandocMonad m => (Tok -> Bool) -> LP m Tok
+satisfyTok f = do
+    doMacros -- apply macros on remaining input stream
+    res <- tokenPrim (T.unpack . untoken) updatePos matcher
+    updateState $ \st ->
+      if sEnableWithRaw st
+         then
+           let !newraws = IntMap.map (res:) $! sRawTokens st
+            in  st{ sRawTokens = newraws }
+         else st
+    return $! res
+  where matcher t | f t       = Just t
+                  | otherwise = Nothing
+        updatePos :: SourcePos -> Tok -> TokStream -> SourcePos
+        updatePos _spos _ (TokStream _ (Tok pos _ _ : _)) = pos
+        updatePos spos (Tok _ _ t) _ = incSourceColumn spos (T.length t)
+
+peekTok :: PandocMonad m => LP m Tok
+peekTok = do
+  doMacros
+  lookAhead (satisfyTok (const True))
+
+doMacros :: PandocMonad m => LP m ()
+doMacros = do
+  TokStream macrosExpanded toks <- getInput
+  unless macrosExpanded $ do
+    st <- getState
+    unless (sVerbatimMode st) $
+      doMacros' 1 toks >>= setInput . TokStream True
+
+doMacros' :: PandocMonad m => Int -> [Tok] -> LP m [Tok]
+doMacros' n inp =
+  case inp of
+     Tok spos (CtrlSeq "begin") _ : Tok _ Symbol "{" :
+      Tok _ Word name : Tok _ Symbol "}" : ts
+        -> handleMacros n spos name ts <|> return inp
+     Tok spos (CtrlSeq "end") _ : Tok _ Symbol "{" :
+      Tok _ Word name : Tok _ Symbol "}" : ts
+        -> handleMacros n spos ("end" <> name) ts <|> return inp
+     Tok _ (CtrlSeq "expandafter") _ : t : ts
+        -> combineTok t <$> doMacros' n ts
+     Tok spos (CtrlSeq name) _ : ts
+        -> handleMacros n spos name ts <|> return inp
+     _ -> return inp
+
+  where
+    combineTok (Tok spos (CtrlSeq name) x) (Tok _ Word w : ts)
+      | T.all isLetterOrAt w =
+        Tok spos (CtrlSeq (name <> w)) (x1 <> w <> x2) : ts
+          where (x1, x2) = T.break isSpaceOrTab x
+    combineTok t ts = t:ts
+
+    matchTok (Tok _ toktype txt) =
+      satisfyTok (\(Tok _ toktype' txt') ->
+                    toktype == toktype' &&
+                    txt == txt')
+
+    matchPattern toks = try $ mapM_ matchTok toks
+
+    getargs argmap [] = return argmap
+    getargs argmap (Pattern toks : rest) = try $ do
+       matchPattern toks
+       getargs argmap rest
+    getargs argmap (ArgNum i : Pattern toks : rest) =
+      try $ do
+        x <- mconcat <$> manyTill (braced <|> ((:[]) <$> anyTok))
+                  (matchPattern toks)
+        getargs (M.insert i x argmap) rest
+    getargs argmap (ArgNum i : rest) = do
+      x <- try $ spaces >> bracedOrToken
+      getargs (M.insert i x argmap) rest
+
+    addTok False _args spos (Tok _ (DeferredArg i) txt) acc =
+      Tok spos (Arg i) txt : acc
+    addTok False args spos (Tok _ (Arg i) _) acc =
+       case M.lookup i args of
+            Nothing -> mzero
+            Just xs -> foldr (addTok True args spos) acc xs
+    -- see #4007
+    addTok _ _ spos (Tok _ (CtrlSeq x) txt)
+           acc@(Tok _ Word _ : _)
+      | not (T.null txt)
+      , isLetter (T.last txt) =
+        Tok spos (CtrlSeq x) (txt <> " ") : acc
+    addTok _ _ spos t acc = setpos spos t : acc
+
+    handleMacros n' spos name ts = do
+      when (n' > 20)  -- detect macro expansion loops
+        $ throwError $ PandocMacroLoop name
+      (macros :| _ ) <- sMacros <$> getState
+      case M.lookup name macros of
+           Nothing -> trySpecialMacro name ts
+           Just (Macro _scope expansionPoint argspecs optarg newtoks) -> do
+             let getargs' = do
+                   args <-
+                     (case expansionPoint of
+                        ExpandWhenUsed    -> withVerbatimMode
+                        ExpandWhenDefined -> id)
+                     $ case optarg of
+                             Nothing -> getargs M.empty argspecs
+                             Just o  -> do
+                                x <- option o bracketedToks
+                                getargs (M.singleton 1 x) $ drop 1 argspecs
+                   TokStream _ rest <- getInput
+                   return (args, rest)
+             lstate <- getState
+             res <- lift $ runParserT getargs' lstate "args" $ TokStream False ts
+             case res of
+               Left _ -> Prelude.fail $ "Could not parse arguments for " ++
+                                T.unpack name
+               Right (args, rest) -> do
+                 -- first boolean param is true if we're tokenizing
+                 -- an argument (in which case we don't want to
+                 -- expand #1 etc.)
+                 let result = foldr (addTok False args spos) rest newtoks
+                 case expansionPoint of
+                   ExpandWhenUsed    -> doMacros' (n' + 1) result
+                   ExpandWhenDefined -> return result
+
+-- | Certain macros do low-level tex manipulations that can't
+-- be represented in our Macro type, so we handle them here.
+trySpecialMacro :: PandocMonad m => Text -> [Tok] -> LP m [Tok]
+trySpecialMacro "xspace" ts = do
+  ts' <- doMacros' 1 ts
+  case ts' of
+    Tok pos Word t : _
+      | startsWithAlphaNum t -> return $ Tok pos Spaces " " : ts'
+    _ -> return ts'
+trySpecialMacro "iftrue" ts = handleIf (ifParser True) ts
+trySpecialMacro "iffalse" ts = handleIf (ifParser False) ts
+trySpecialMacro "ifmmode" ts = do
+  mathMode <- sMathMode <$> getState
+  handleIf (ifParser mathMode) ts
+trySpecialMacro "ifstrequal" ts = do
+  handleIf ifStrequalParser ts
+trySpecialMacro _ _ = mzero
+
+ifStrequalParser :: PandocMonad m => LP m [Tok]
+ifStrequalParser = do
+  str1 <- braced <|> count 1 anyTok
+  str2 <- braced <|> count 1 anyTok
+  ifequal <- withVerbatimMode (braced <|> count 1 anyTok)
+  ifnotequal <- withVerbatimMode (braced <|> count 1 anyTok)
+  TokStream _ ts <- getInput
+  return $
+    if untokenize str1 == untokenize str2
+       then ifequal ++ ts
+       else ifnotequal ++ ts
+
+handleIf :: PandocMonad m => LP m [Tok] -> [Tok] -> LP m [Tok]
+handleIf parser ts = do
+  res' <- lift $ runParserT parser defaultLaTeXState "tokens"
+               $ TokStream False ts
+  case res' of
+    Left _ -> Prelude.fail "Could not parse conditional"
+    Right ts' -> return ts'
+
+ifParser :: PandocMonad m => Bool -> LP m [Tok]
+ifParser b = do
+  ifToks <- many (notFollowedBy (controlSeq "else" <|> controlSeq "fi")
+                    *> anyTok)
+  elseToks <- (controlSeq "else" >> manyTill anyTok (controlSeq "fi"))
+                 <|> ([] <$ controlSeq "fi")
+  TokStream _ rest <- getInput
+  return $ (if b then ifToks else elseToks) ++ rest
+
+startsWithAlphaNum :: Text -> Bool
+startsWithAlphaNum t =
+  case T.uncons t of
+       Just (c, _) | isAlphaNum c -> True
+       _           -> False
+
+setpos :: SourcePos -> Tok -> Tok
+setpos spos (Tok _ tt txt) = Tok spos tt txt
+
+anyControlSeq :: PandocMonad m => LP m Tok
+anyControlSeq = satisfyTok isCtrlSeq
+
+isCtrlSeq :: Tok -> Bool
+isCtrlSeq (Tok _ (CtrlSeq _) _) = True
+isCtrlSeq _                     = False
+
+anySymbol :: PandocMonad m => LP m Tok
+anySymbol = satisfyTok isSymbolTok
+
+isSymbolTok :: Tok -> Bool
+isSymbolTok (Tok _ Symbol _) = True
+isSymbolTok _                = False
+
+isWordTok :: Tok -> Bool
+isWordTok (Tok _ Word _) = True
+isWordTok _              = False
+
+isArgTok :: Tok -> Bool
+isArgTok (Tok _ (Arg _) _) = True
+isArgTok _                 = False
+
+infile :: PandocMonad m => SourceName -> LP m Tok
+infile reference = satisfyTok (\(Tok source _ _) -> (sourceName source) == reference)
+
+spaces :: PandocMonad m => LP m ()
+spaces = skipMany (satisfyTok (tokTypeIn [Comment, Spaces, Newline]))
+
+spaces1 :: PandocMonad m => LP m ()
+spaces1 = skipMany1 (satisfyTok (tokTypeIn [Comment, Spaces, Newline]))
+
+tokTypeIn :: [TokType] -> Tok -> Bool
+tokTypeIn toktypes (Tok _ tt _) = tt `elem` toktypes
+
+controlSeq :: PandocMonad m => Text -> LP m Tok
+controlSeq name = satisfyTok isNamed
+  where isNamed (Tok _ (CtrlSeq n) _) = n == name
+        isNamed _                     = False
+
+symbol :: PandocMonad m => Char -> LP m Tok
+symbol c = satisfyTok isc
+  where isc (Tok _ Symbol d) = case T.uncons d of
+                                    Just (c',_) -> c == c'
+                                    _           -> False
+        isc _ = False
+
+symbolIn :: PandocMonad m => [Char] -> LP m Tok
+symbolIn cs = satisfyTok isInCs
+  where isInCs (Tok _ Symbol d) = case T.uncons d of
+                                       Just (c,_) -> c `elem` cs
+                                       _          -> False
+        isInCs _ = False
+
+sp :: PandocMonad m => LP m ()
+sp = do
+  optional $ skipMany (whitespace <|> comment)
+  optional $ endline  *> skipMany (whitespace <|> comment)
+
+whitespace :: PandocMonad m => LP m ()
+whitespace = () <$ satisfyTok isSpaceTok
+
+isSpaceTok :: Tok -> Bool
+isSpaceTok (Tok _ Spaces _) = True
+isSpaceTok _                = False
+
+newlineTok :: PandocMonad m => LP m ()
+newlineTok = () <$ satisfyTok isNewlineTok
+
+isNewlineTok :: Tok -> Bool
+isNewlineTok (Tok _ Newline _) = True
+isNewlineTok _                 = False
+
+comment :: PandocMonad m => LP m ()
+comment = () <$ satisfyTok isCommentTok
+
+isCommentTok :: Tok -> Bool
+isCommentTok (Tok _ Comment _) = True
+isCommentTok _                 = False
+
+anyTok :: PandocMonad m => LP m Tok
+anyTok = satisfyTok (const True)
+
+singleCharTok :: PandocMonad m => LP m Tok
+singleCharTok =
+  satisfyTok $ \case
+     Tok _ Word  t   -> T.length t == 1
+     Tok _ Symbol t  -> not (T.any (`Set.member` specialChars) t)
+     _               -> False
+
+singleChar :: PandocMonad m => LP m Tok
+singleChar = singleCharTok <|> singleCharFromWord
+ where
+  singleCharFromWord = do
+    Tok pos toktype t <- disablingWithRaw $ satisfyTok isWordTok
+    let (t1, t2) = (T.take 1 t, T.drop 1 t)
+    TokStream macrosExpanded inp <- getInput
+    setInput $ TokStream macrosExpanded
+             $ Tok pos toktype t1 : Tok (incSourceColumn pos 1) toktype t2 : inp
+    anyTok
+
+specialChars :: Set.Set Char
+specialChars = Set.fromList "#$%&~_^\\{}"
+
+endline :: PandocMonad m => LP m ()
+endline = try $ do
+  newlineTok
+  lookAhead anyTok
+  notFollowedBy blankline
+
+blankline :: PandocMonad m => LP m ()
+blankline = try $ skipMany whitespace *> newlineTok
+
+primEscape :: PandocMonad m => LP m Char
+primEscape = do
+  Tok _ toktype t <- satisfyTok (tokTypeIn [Esc1, Esc2])
+  case toktype of
+       Esc1 -> case T.uncons (T.drop 2 t) of
+                    Just (c, _)
+                      | c >= '\64' && c <= '\127' -> return (chr (ord c - 64))
+                      | otherwise                 -> return (chr (ord c + 64))
+                    Nothing -> Prelude.fail "Empty content of Esc1"
+       Esc2 -> case safeRead ("0x" <> T.drop 2 t) of
+                    Just x  -> return (chr x)
+                    Nothing -> Prelude.fail $ "Could not read: " ++ T.unpack t
+       _    -> Prelude.fail "Expected an Esc1 or Esc2 token" -- should not happen
+
+bgroup :: PandocMonad m => LP m Tok
+bgroup = try $ do
+  optional sp
+  t <- symbol '{' <|> controlSeq "bgroup" <|> controlSeq "begingroup"
+  -- Add a copy of the macro table to the top of the macro stack,
+  -- private for this group. We inherit all the macros defined in
+  -- the parent group.
+  updateState $ \s -> s{ sMacros = NonEmpty.cons (NonEmpty.head (sMacros s))
+                                                 (sMacros s) }
+  return t
+
+
+egroup :: PandocMonad m => LP m Tok
+egroup = do
+  t <- symbol '}' <|> controlSeq "egroup" <|> controlSeq "endgroup"
+  -- remove the group's macro table from the stack
+  updateState $ \s -> s{ sMacros = fromMaybe (sMacros s) $
+      NonEmpty.nonEmpty (NonEmpty.tail (sMacros s)) }
+  return t
+
+grouped :: (PandocMonad m,  Monoid a) => LP m a -> LP m a
+grouped parser = try $ do
+  bgroup
+  -- first we check for an inner 'grouped', because
+  -- {{a,b}} should be parsed the same as {a,b}
+  try (grouped parser <* egroup) <|> (mconcat <$> manyTill parser egroup)
+
+braced' :: PandocMonad m => LP m Tok -> LP m [Tok]
+braced' getTok = symbol '{' *> go (1 :: Int)
+ where
+  go n = do
+    t <- getTok
+    case t of
+      Tok _ Symbol "}"
+        | n > 1     -> (t:) <$> go (n - 1)
+        | otherwise -> return []
+      Tok _ Symbol "{" -> (t:) <$> go (n + 1)
+      _ -> (t:) <$> go n
+
+braced :: PandocMonad m => LP m [Tok]
+braced = braced' anyTok
+
+-- URLs require special handling, because they can contain %
+-- characters.  So we retonenize comments as we go...
+bracedUrl :: PandocMonad m => LP m [Tok]
+bracedUrl = braced' (retokenizeComment >> anyTok)
+
+-- For handling URLs, which allow literal % characters...
+retokenizeComment :: PandocMonad m => LP m ()
+retokenizeComment = (do
+  Tok pos Comment txt <- satisfyTok isCommentTok
+  let updPos (Tok pos' toktype' txt') =
+        Tok (incSourceColumn (incSourceLine pos' (sourceLine pos - 1))
+             (sourceColumn pos)) toktype' txt'
+  let newtoks = map updPos $ tokenize pos $ T.tail txt
+  TokStream macrosExpanded ts <- getInput
+  setInput $ TokStream macrosExpanded ((Tok pos Symbol "%" : newtoks) ++ ts))
+    <|> return ()
+
+bracedOrToken :: PandocMonad m => LP m [Tok]
+bracedOrToken = braced <|> ((:[]) <$> (anyControlSeq <|> singleChar))
+
+bracketed :: PandocMonad m => Monoid a => LP m a -> LP m a
+bracketed parser = try $ do
+  symbol '['
+  mconcat <$> manyTill parser (symbol ']')
+
+bracketedToks :: PandocMonad m => LP m [Tok]
+bracketedToks = do
+  symbol '['
+  concat <$> manyTill ((snd <$> withRaw (try braced)) <|> count 1 anyTok)
+                      (symbol ']')
+
+parenWrapped :: PandocMonad m => Monoid a => LP m a -> LP m a
+parenWrapped parser = try $ do
+  symbol '('
+  mconcat <$> manyTill parser (symbol ')')
+
+dimenarg :: PandocMonad m => LP m Text
+dimenarg = try $ do
+  optional sp
+  ch  <- option False $ True <$ symbol '='
+  minus <- option "" $ "-" <$ symbol '-'
+  s1 <- option ""
+        (do Tok _ _ s1 <- satisfyTok isWordTok
+            guard (case T.uncons s1 of
+                     Just (c,_) -> isDigit c
+                     Nothing -> False)
+            pure s1)
+  s2 <- option "" $ try $ do
+          symbol '.'
+          Tok _ _ t <-  satisfyTok isWordTok
+          return ("." <> t)
+  let s = s1 <> s2
+  let (num, rest) = T.span (\c -> isDigit c || c == '.') s
+  guard $ T.length num > 0
+  guard $ rest `elem`
+    ["", "pt","pc","in","bp","cm","mm","dd","cc","sp","ex","em",
+     "mu", -- "mu" in math mode only
+     "px" -- "px" with pdftex and luatex only
+    ]
+  return $ T.pack ['=' | ch] <> minus <> s
+
+ignore :: (Monoid a, PandocMonad m) => Text -> ParsecT s u m a
+ignore raw = do
+  pos <- getPosition
+  report $ SkippedContent raw pos
+  return mempty
+
+withRaw :: PandocMonad m => LP m a -> LP m (a, [Tok])
+withRaw parser = do
+  rawTokensMap <- sRawTokens <$> getState
+  let key = case IntMap.lookupMax rawTokensMap of
+               Nothing     -> 0
+               Just (n,_)  -> n + 1
+  -- insert empty list at key
+  updateState $ \st -> st{ sRawTokens =
+                             IntMap.insert key [] $ sRawTokens st }
+  result <- parser
+  mbRevToks <- IntMap.lookup key . sRawTokens <$> getState
+  raw <- case mbRevToks of
+           Just revtoks -> do
+             updateState $ \st -> st{ sRawTokens =
+                                        IntMap.delete key $ sRawTokens st}
+             return $ reverse revtoks
+           Nothing      ->
+             throwError $ PandocShouldNeverHappenError $
+                "sRawTokens has nothing at key " <> T.pack (show key)
+  return (result, raw)
+
+keyval :: PandocMonad m => LP m (Text, Text)
+keyval = try $ do
+  sp
+  key <- untokenize <$> many1 (notFollowedBy (symbol '=') >>
+                         (symbol '-' <|> symbol '_' <|> satisfyTok isWordTok))
+  sp
+  val <- option mempty $ do
+           symbol '='
+           sp
+           (untokenize <$> braced) <|>
+             (mconcat <$> many1 (
+                 (untokenize . snd <$> withRaw braced)
+                 <|>
+                 (untokenize <$> many1
+                      (satisfyTok
+                         (\case
+                                Tok _ Symbol "]" -> False
+                                Tok _ Symbol "," -> False
+                                Tok _ Symbol "{" -> False
+                                Tok _ Symbol "}" -> False
+                                _                -> True)))))
+  sp
+  optional (symbol ',')
+  sp
+  return (key, T.strip val)
+
+keyvals :: PandocMonad m => LP m [(Text, Text)]
+keyvals = try $ symbol '[' >> manyTill keyval (symbol ']') <* sp
+
+verbEnv :: PandocMonad m => Text -> LP m Text
+verbEnv name = withVerbatimMode $ do
+  optional blankline
+  res <- manyTill anyTok (end_ name)
+  return $ stripTrailingNewline
+         $ untokenize res
+
+-- Strip single final newline and any spaces following it.
+-- Input is unchanged if it doesn't end with newline +
+-- optional spaces.
+stripTrailingNewline :: Text -> Text
+stripTrailingNewline t =
+  let (b, e) = T.breakOnEnd "\n" t
+  in  if T.all (== ' ') e
+         then T.dropEnd 1 b
+         else t
+
+begin_ :: PandocMonad m => Text -> LP m ()
+begin_ t = try (do
+  controlSeq "begin"
+  spaces
+  txt <- untokenize <$> braced
+  guard (t == txt)) <?> ("\\begin{" ++ T.unpack t ++ "}")
+
+end_ :: PandocMonad m => Text -> LP m ()
+end_ t = try (do
+  controlSeq "end"
+  spaces
+  txt <- untokenize <$> braced
+  guard $ t == txt) <?> ("\\end{" ++ T.unpack t ++ "}")
+
+getRawCommand :: PandocMonad m => Text -> Text -> LP m Text
+getRawCommand name txt = do
+  (_, rawargs) <- withRaw $
+      case name of
+           "write" -> do
+             void $ many $ satisfyTok isDigitTok -- digits
+             void braced
+           "titleformat" -> do
+             void braced
+             skipopts
+             void $ count 4 braced
+           "def" ->
+             void $ manyTill anyTok braced
+           "vadjust" ->
+             void (manyTill anyTok braced) <|>
+                void (satisfyTok isPreTok) -- see #7531
+           _ | isFontSizeCommand name -> return ()
+             | name `elem` ["hfil", "hfill", "vfil", "vfill",
+                            "hfilneg", "vfilneg"] -> return ()
+             | name `elem` ["hskip", "vskip", "mskip"] -> do
+                 dimenarg
+                 skipMany $ try $ do
+                   sp
+                   satisfyTok $
+                     \case
+                       Tok _ Word "plus" -> True
+                       Tok _ Word "minus" -> True
+                       _ -> False
+                   dimenarg
+             | otherwise -> do
+               skipopts
+               option "" (try dimenarg)
+               void $ many braced
+  return $ txt <> untokenize rawargs
+
+isPreTok :: Tok -> Bool
+isPreTok (Tok _ Word "pre") = True
+isPreTok _ = False
+
+isDigitTok :: Tok -> Bool
+isDigitTok (Tok _ Word t) = T.all isDigit t
+isDigitTok _              = False
+
+skipopts :: PandocMonad m => LP m ()
+skipopts = skipMany (void overlaySpecification <|> void rawopt)
+
+-- opts in angle brackets are used in beamer
+overlaySpecification :: PandocMonad m => LP m Text
+overlaySpecification = try $ do
+  symbol '<'
+  t <- untokenize <$> manyTill overlayTok (symbol '>')
+  -- see issue #3368
+  guard $ not (T.all isLetter t) ||
+          t `elem` ["beamer","presentation", "trans",
+                    "handout","article", "second"]
+  return $ "<" <> t <> ">"
+
+overlayTok :: PandocMonad m => LP m Tok
+overlayTok =
+  satisfyTok (\case
+                    Tok _ Word _       -> True
+                    Tok _ Spaces _     -> True
+                    Tok _ Symbol c     -> c `elem` ["-","+","@","|",":",","]
+                    _                  -> False)
+
+rawopt :: PandocMonad m => LP m Text
+rawopt = try $ do
+  sp
+  inner <- untokenize <$> bracketedToks
+  sp
+  return $ "[" <> inner <> "]"
+
+isFontSizeCommand :: Text -> Bool
+isFontSizeCommand "tiny" = True
+isFontSizeCommand "scriptsize" = True
+isFontSizeCommand "footnotesize" = True
+isFontSizeCommand "small" = True
+isFontSizeCommand "normalsize" = True
+isFontSizeCommand "large" = True
+isFontSizeCommand "Large" = True
+isFontSizeCommand "LARGE" = True
+isFontSizeCommand "huge" = True
+isFontSizeCommand "Huge" = True
+isFontSizeCommand _ = False
+
+getNextNumber :: Monad m
+              => (LaTeXState -> DottedNum) -> LP m DottedNum
+getNextNumber getCurrentNum = do
+  st <- getState
+  let chapnum =
+        case sLastHeaderNum st of
+             DottedNum (n:_) | sHasChapters st -> Just n
+             _                                 -> Nothing
+  return . DottedNum $
+    case getCurrentNum st of
+       DottedNum [m,n]  ->
+         case chapnum of
+              Just m' | m' == m   -> [m, n+1]
+                      | otherwise -> [m', 1]
+              Nothing             -> [1]
+                                      -- shouldn't happen
+       DottedNum [n]   ->
+         case chapnum of
+              Just m  -> [m, 1]
+              Nothing -> [n + 1]
+       _               ->
+         case chapnum of
+               Just n  -> [n, 1]
+               Nothing -> [1]
+
+label :: PandocMonad m => LP m ()
+label = do
+  controlSeq "label"
+  t <- braced
+  updateState $ \st -> st{ sLastLabel = Just $ untokenize t }
+
+setCaption :: PandocMonad m => LP m Inlines -> LP m ()
+setCaption inline = try $ do
+  mbshort <- Just . toList <$> bracketed inline <|> pure Nothing
+  ils <- tokWith inline
+  optional $ try $ spaces *> label
+  updateState $ \st -> st{ sCaption = Just $
+                              Caption mbshort [Plain $ toList ils] }
+
+resetCaption :: PandocMonad m => LP m ()
+resetCaption = updateState $ \st -> st{ sCaption   = Nothing
+                                      , sLastLabel = Nothing }
+
+env :: PandocMonad m => Text -> LP m a -> LP m a
+env name p = do
+  -- environments are groups as far as macros are concerned,
+  -- so we need a local copy of the macro table (see above, bgroup, egroup):
+  updateState $ \s -> s{ sMacros = NonEmpty.cons (NonEmpty.head (sMacros s))
+                                                 (sMacros s) }
+  result <- p
+  updateState $ \s -> s{ sMacros = fromMaybe (sMacros s) $
+      NonEmpty.nonEmpty (NonEmpty.tail (sMacros s)) }
+  end_ name
+  return result
+
+tokWith :: PandocMonad m => LP m Inlines -> LP m Inlines
+tokWith inlineParser = try $ spaces >>
+                                 grouped inlineParser
+                            <|> (lookAhead anyControlSeq >> inlineParser)
+                            <|> singleChar'
+  where singleChar' = do
+          Tok _ _ t <- singleChar
+          return $ str t
+
+addMeta :: PandocMonad m => ToMetaValue a => Text -> a -> LP m ()
+addMeta field val = updateState $ \st ->
+   st{ sMeta = addMetaField field val $ sMeta st }
+
+-- remove label spans to avoid duplicated identifier
+removeLabel :: Walkable [Inline] a => Text -> a -> a
+removeLabel lbl = walk go
+ where
+  go (Span (_,_,kvs) _ : rest)
+    | Just lbl' <- lookup "label" kvs
+    , lbl' == lbl = go (dropWhile isSpaceOrSoftBreak rest)
+  go (x:xs) = x : go xs
+  go [] = []
+  isSpaceOrSoftBreak Space = True
+  isSpaceOrSoftBreak SoftBreak = True
+  isSpaceOrSoftBreak _ = False
diff --git a/src/Text/Pandoc/Readers/LaTeX/SIunitx.hs b/src/Text/Pandoc/Readers/LaTeX/SIunitx.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Readers/LaTeX/SIunitx.hs
@@ -0,0 +1,471 @@
+{-# LANGUAGE ScopedTypeVariables #-}
+{-# LANGUAGE OverloadedStrings #-}
+module Text.Pandoc.Readers.LaTeX.SIunitx
+  ( siunitxCommands )
+where
+import Text.Pandoc.Builder
+    ( space,
+      subscript,
+      superscript,
+      emph,
+      str,
+      fromList,
+      text,
+      Many(Many, unMany),
+      Inline(Superscript, Str),
+      Inlines )
+import Text.Pandoc.Readers.LaTeX.Parsing
+    ( anyControlSeq,
+      braced,
+      bracketed,
+      controlSeq,
+      grouped,
+      isWordTok,
+      keyvals,
+      satisfyTok,
+      skipopts,
+      spaces1,
+      symbol,
+      untokenize,
+      LP )
+import Text.Pandoc.TeX
+    ( Tok(Tok), TokType(Word, CtrlSeq) )
+import Text.Pandoc.Class.PandocMonad ( PandocMonad )
+import Text.Pandoc.Parsing
+    ( many1,
+      eof,
+      string,
+      satisfy,
+      skipMany,
+      option,
+      many,
+      char,
+      try,
+      skipMany1,
+      runParser,
+      Parsec )
+import Control.Applicative ((<|>))
+import Control.Monad (void)
+import qualified Data.Map as M
+import Data.Char (isDigit)
+import Data.Text (Text)
+import qualified Data.Text as T
+import Data.List (intersperse)
+import qualified Data.Sequence as Seq
+import Text.Pandoc.Walk (walk)
+
+siunitxCommands :: PandocMonad m
+                 => LP m Inlines -> M.Map Text (LP m Inlines)
+siunitxCommands tok = M.fromList
+  [ ("si", dosi tok)
+  , ("unit", dosi tok) -- v3 version of si
+  , ("SI", doSI tok)
+  , ("qty", doSI tok) -- v3 version of SI
+  , ("SIrange", doSIrange True tok)
+  , ("qtyrange", doSIrange True tok) -- v3 version of SIrange
+  , ("SIlist", doSIlist tok)
+  , ("qtylist", doSIlist tok) -- v3 version of SIlist
+  , ("numrange", doSIrange False tok)
+  , ("numlist", doSInumlist)
+  , ("num", doSInum)
+  , ("ang", doSIang)
+  ]
+
+dosi :: PandocMonad m => LP m Inlines -> LP m Inlines
+dosi tok = do
+  options <- option [] keyvals
+  grouped (siUnit options tok) <|> siUnit options tok
+
+-- converts e.g. \SI{1}[\$]{} to "$ 1" or \SI{1}{\euro} to "1 €"
+doSI :: PandocMonad m => LP m Inlines -> LP m Inlines
+doSI tok = do
+  skipopts
+  value <- doSInum
+  valueprefix <- option "" $ bracketed tok
+  unit <- dosi tok
+  return . mconcat $ [valueprefix,
+                      emptyOr160 valueprefix,
+                      value,
+                      emptyOr160 unit,
+                      unit]
+
+doSInum :: PandocMonad m => LP m Inlines
+doSInum = skipopts *> (tonum . untokenize <$> braced)
+
+tonum :: Text -> Inlines
+tonum value =
+  case runParser parseNum () "" value of
+    Left _    -> text value
+    Right num -> num
+
+doSInumlist :: PandocMonad m => LP m Inlines
+doSInumlist = do
+  skipopts
+  xs <- map tonum . T.splitOn ";" . untokenize <$> braced
+  case xs of
+    []  -> return mempty
+    [x] -> return x
+    _   -> return $
+             mconcat (intersperse (str "," <> space) (init xs)) <>
+             text ", & " <> last xs
+
+doSIlist :: PandocMonad m => LP m Inlines -> LP m Inlines
+doSIlist tok = do
+  options <- option [] keyvals
+  nums <- map tonum . T.splitOn ";" . untokenize <$> braced
+  unit <- grouped (siUnit options tok) <|> siUnit options tok
+  let xs = map (<> (str "\xa0" <> unit)) nums
+  case xs of
+    []  -> return mempty
+    [x] -> return x
+    _   -> return $
+             mconcat (intersperse (str "," <> space) (init xs)) <>
+             text ", & " <> last xs
+
+parseNum :: Parsec Text () Inlines
+parseNum = (mconcat <$> many parseNumPart) <* eof
+
+minus :: Text
+minus = "\x2212"
+
+hyphenToMinus :: Inline -> Inline
+hyphenToMinus (Str t) = Str (T.replace "-" minus t)
+hyphenToMinus x = x
+
+parseNumPart :: Parsec Text () Inlines
+parseNumPart =
+  parseDecimalNum <|>
+  parseComma <|>
+  parsePlusMinus <|>
+  parsePM <|>
+  parseI <|>
+  parseExp <|>
+  parseX <|>
+  parseSpace
+ where
+  parseDecimalNum, parsePlusMinus, parsePM,
+    parseComma, parseI, parseX,
+    parseExp, parseSpace :: Parsec Text () Inlines
+  parseDecimalNum = try $ do
+    pref <- option mempty $ (mempty <$ char '+') <|> (minus <$ char '-')
+    basenum' <- many1 (satisfy (\c -> isDigit c || c == '.'))
+    let basenum = pref <> T.pack
+                    (case basenum' of
+                      '.':_ -> '0':basenum'
+                      _ -> basenum')
+    uncertainty <- option mempty $ T.pack <$> parseParens
+    if T.null uncertainty
+       then return $ str basenum
+       else return $ str $ basenum <> "\xa0\xb1\xa0" <>
+             let (_,ys) = T.break (=='.') basenum
+              in case (T.length ys - 1, T.length uncertainty) of
+                   (0,_) -> uncertainty
+                   (x,y)
+                     | x > y  -> "0." <> T.replicate (x - y) "0" <>
+                                      T.dropWhileEnd (=='0') uncertainty
+                     | otherwise -> T.take (y - x) uncertainty <>
+                                      case T.dropWhileEnd (=='0')
+                                             (T.drop (y - x) uncertainty) of
+                                             t | T.null t -> mempty
+                                               | otherwise -> "." <> t
+  parseComma = str "." <$ char ','
+  parsePlusMinus = str "\xa0\xb1\xa0" <$ try (string "+-")
+  parsePM = str "\xa0\xb1\xa0" <$ try (string "\\pm")
+  parseParens =
+    char '(' *> many1 (satisfy (\c -> isDigit c || c == '.')) <* char ')'
+  parseI = str "i" <$ char 'i'
+  parseX = str "\xa0\xd7\xa0" <$ char 'x'
+  parseExp = (\n -> str ("\xa0\xd7\xa0" <> "10") <> superscript n)
+               <$> (char 'e' *> parseDecimalNum)
+  parseSpace = mempty <$ skipMany1 (char ' ')
+
+doSIang :: PandocMonad m => LP m Inlines
+doSIang = do
+  skipopts
+  ps <- T.splitOn ";" . untokenize <$> braced
+  let dropPlus t = case T.uncons t of
+                     Just ('+',t') -> t'
+                     _ -> t
+  case ps ++ repeat "" of
+    (d:m:s:_) -> return $
+      (if T.null d then mempty else str (dropPlus d) <> str "\xb0") <>
+      (if T.null m then mempty else str (dropPlus m) <> str "\x2032") <>
+      (if T.null s then mempty else str (dropPlus s) <> str "\x2033")
+    _ -> return mempty
+
+-- converts e.g. \SIrange{100}{200}{\ms} to "100 ms--200 ms"
+doSIrange :: PandocMonad m => Bool -> LP m Inlines -> LP m Inlines
+doSIrange includeUnits tok = do
+  skipopts
+  startvalue <- doSInum
+  startvalueprefix <- option "" $ bracketed tok
+  stopvalue <- doSInum
+  stopvalueprefix <- option "" $ bracketed tok
+  unit <- if includeUnits
+             then dosi tok
+             else return mempty
+  return . mconcat $ [startvalueprefix,
+                      emptyOr160 startvalueprefix,
+                      startvalue,
+                      emptyOr160 unit,
+                      unit,
+                      "\8211", -- An en-dash
+                      stopvalueprefix,
+                      emptyOr160 stopvalueprefix,
+                      stopvalue,
+                      emptyOr160 unit,
+                      unit]
+
+emptyOr160 :: Inlines -> Inlines
+emptyOr160 x = if x == mempty then x else str "\160"
+
+siUnit :: forall m. PandocMonad m => [(Text,Text)] -> LP m Inlines -> LP m Inlines
+siUnit options tok = mconcat . intersperse (str "\xa0") <$> many1 siUnitPart
+ where
+  siUnitPart :: LP m Inlines
+  siUnitPart = try $ do
+    skipMany (void (symbol '.') <|> void (symbol '~') <|> spaces1)
+    x <- ((siPrefix <*> siBase)
+            <|> (do u <- siBase <|> tok
+                    option u $ siSuffix <*> pure u))
+    option x (siInfix x)
+  siInfix :: Inlines -> LP m Inlines
+  siInfix u1 = try $
+       (do _ <- controlSeq "per"
+           u2 <- siUnitPart
+           let useSlash = lookup "per-mode" options == Just "symbol"
+           if useSlash
+              then return (u1 <> str "/" <> u2)
+              else return (u1 <> str "\xa0" <> negateExponent u2))
+   <|> (do _ <- symbol '/'
+           u2 <- siUnitPart
+           return (u1 <> str "/" <> u2))
+  siPrefix :: LP m (Inlines -> Inlines)
+  siPrefix =
+       (do _ <- controlSeq "square"
+           skipopts
+           return (<> superscript "2"))
+   <|> (do _ <- controlSeq "cubic"
+           skipopts
+           return (<> superscript "3"))
+   <|> (do _ <- controlSeq "raisetothe"
+           skipopts
+           n <- walk hyphenToMinus <$> tok
+           return (<> superscript n))
+  siSuffix :: LP m (Inlines -> Inlines)
+  siSuffix =
+       (do _ <- controlSeq "squared"
+           skipopts
+           return (<> superscript "2"))
+   <|> (do _ <- controlSeq "cubed"
+           skipopts
+           return (<> superscript "3"))
+   <|> (do _ <- controlSeq "tothe"
+           skipopts
+           n <- walk hyphenToMinus <$> tok
+           return (<> superscript n))
+   <|> (symbol '^' *> (do n <- walk hyphenToMinus <$> tok
+                          return (<> superscript n)))
+   <|> (symbol '_' *> (do n <- walk hyphenToMinus <$> tok
+                          return (<> subscript n)))
+  negateExponent :: Inlines -> Inlines
+  negateExponent ils =
+    case Seq.viewr (unMany ils) of
+      xs Seq.:> Superscript ss -> (Many xs) <>
+                                     superscript (str minus <> fromList ss)
+      _ -> ils <> superscript (str (minus <> "1"))
+  siBase :: LP m Inlines
+  siBase =
+    ((try
+       (do Tok _ (CtrlSeq name) _ <- anyControlSeq
+           case M.lookup name siUnitModifierMap of
+              Just il -> (il <>) <$> siBase
+              Nothing ->
+                case M.lookup name siUnitMap of
+                   Just il -> pure il
+                   Nothing -> fail "not a unit command"))
+    <|> (do Tok _ Word t <- satisfyTok isWordTok
+            return $ str t)
+     )
+
+siUnitModifierMap :: M.Map Text Inlines
+siUnitModifierMap = M.fromList
+  [ ("atto", str "a")
+  , ("centi", str "c")
+  , ("deca", str "d")
+  , ("deci", str "d")
+  , ("deka", str "d")
+  , ("exa", str "E")
+  , ("femto", str "f")
+  , ("giga", str "G")
+  , ("hecto", str "h")
+  , ("kilo", str "k")
+  , ("mega", str "M")
+  , ("micro", str "μ")
+  , ("milli", str "m")
+  , ("nano", str "n")
+  , ("peta", str "P")
+  , ("pico", str "p")
+  , ("tera", str "T")
+  , ("yocto", str "y")
+  , ("yotta", str "Y")
+  , ("zepto", str "z")
+  , ("zetta", str "Z")
+  ]
+
+siUnitMap :: M.Map Text Inlines
+siUnitMap = M.fromList
+  [ ("fg", str "fg")
+  , ("pg", str "pg")
+  , ("ng", str "ng")
+  , ("ug", str "μg")
+  , ("mg", str "mg")
+  , ("g", str "g")
+  , ("kg", str "kg")
+  , ("amu", str "u")
+  , ("pm", str "pm")
+  , ("nm", str "nm")
+  , ("um", str "μm")
+  , ("mm", str "mm")
+  , ("cm", str "cm")
+  , ("dm", str "dm")
+  , ("m", str "m")
+  , ("km", str "km")
+  , ("as", str "as")
+  , ("fs", str "fs")
+  , ("ps", str "ps")
+  , ("ns", str "ns")
+  , ("us", str "μs")
+  , ("ms", str "ms")
+  , ("s", str "s")
+  , ("fmol", str "fmol")
+  , ("pmol", str "pmol")
+  , ("nmol", str "nmol")
+  , ("umol", str "μmol")
+  , ("mmol", str "mmol")
+  , ("mol", str "mol")
+  , ("kmol", str "kmol")
+  , ("pA", str "pA")
+  , ("nA", str "nA")
+  , ("uA", str "μA")
+  , ("mA", str "mA")
+  , ("A", str "A")
+  , ("kA", str "kA")
+  , ("ul", str "μl")
+  , ("ml", str "ml")
+  , ("l", str "l")
+  , ("hl", str "hl")
+  , ("uL", str "μL")
+  , ("mL", str "mL")
+  , ("L", str "L")
+  , ("hL", str "hL")
+  , ("mHz", str "mHz")
+  , ("Hz", str "Hz")
+  , ("kHz", str "kHz")
+  , ("MHz", str "MHz")
+  , ("GHz", str "GHz")
+  , ("THz", str "THz")
+  , ("mN", str "mN")
+  , ("N", str "N")
+  , ("kN", str "kN")
+  , ("MN", str "MN")
+  , ("Pa", str "Pa")
+  , ("kPa", str "kPa")
+  , ("MPa", str "MPa")
+  , ("GPa", str "GPa")
+  , ("mohm", str "mΩ")
+  , ("kohm", str "kΩ")
+  , ("Mohm", str "MΩ")
+  , ("pV", str "pV")
+  , ("nV", str "nV")
+  , ("uV", str "μV")
+  , ("mV", str "mV")
+  , ("V", str "V")
+  , ("kV", str "kV")
+  , ("W", str "W")
+  , ("uW", str "μW")
+  , ("mW", str "mW")
+  , ("kW", str "kW")
+  , ("MW", str "MW")
+  , ("GW", str "GW")
+  , ("J", str "J")
+  , ("uJ", str "μJ")
+  , ("mJ", str "mJ")
+  , ("kJ", str "kJ")
+  , ("eV", str "eV")
+  , ("meV", str "meV")
+  , ("keV", str "keV")
+  , ("MeV", str "MeV")
+  , ("GeV", str "GeV")
+  , ("TeV", str "TeV")
+  , ("kWh", str "kWh")
+  , ("F", str "F")
+  , ("fF", str "fF")
+  , ("pF", str "pF")
+  , ("K", str "K")
+  , ("dB", str "dB")
+  , ("ampere", str "A")
+  , ("angstrom", str "Å")
+  , ("arcmin", str "′")
+  , ("arcminute", str "′")
+  , ("arcsecond", str "″")
+  , ("astronomicalunit", str "au")
+  , ("atomicmassunit", str "u")
+  , ("bar", str "bar")
+  , ("barn", str "b")
+  , ("becquerel", str "Bq")
+  , ("bel", str "B")
+  , ("bohr", emph (str "a") <> subscript (str "0"))
+  , ("candela", str "cd")
+  , ("celsius", str "°C")
+  , ("clight", emph (str "c") <> subscript (str "0"))
+  , ("coulomb", str "C")
+  , ("dalton", str "Da")
+  , ("day", str "d")
+  , ("decibel", str "db")
+  , ("degreeCelsius",str "°C")
+  , ("degree", str "°")
+  , ("electronmass", emph (str "m") <> subscript (str "e"))
+  , ("electronvolt", str "eV")
+  , ("elementarycharge", emph (str "e"))
+  , ("farad", str "F")
+  , ("gram", str "g")
+  , ("gray", str "Gy")
+  , ("hartree", emph (str "E") <> subscript (str "h"))
+  , ("hectare", str "ha")
+  , ("henry", str "H")
+  , ("hertz", str "Hz")
+  , ("hour", str "h")
+  , ("joule", str "J")
+  , ("katal", str "kat")
+  , ("kelvin", str "K")
+  , ("kilogram", str "kg")
+  , ("knot", str "kn")
+  , ("liter", str "L")
+  , ("litre", str "l")
+  , ("lumen", str "lm")
+  , ("lux", str "lx")
+  , ("meter", str "m")
+  , ("metre", str "m")
+  , ("minute", str "min")
+  , ("mmHg", str "mmHg")
+  , ("mole", str "mol")
+  , ("nauticalmile", str "M")
+  , ("neper", str "Np")
+  , ("newton", str "N")
+  , ("ohm", str "Ω")
+  , ("Pa", str "Pa")
+  , ("pascal", str "Pa")
+  , ("percent", str "%")
+  , ("planckbar", emph (str "\x210f"))
+  , ("radian", str "rad")
+  , ("second", str "s")
+  , ("siemens", str "S")
+  , ("sievert", str "Sv")
+  , ("steradian", str "sr")
+  , ("tesla", str "T")
+  , ("tonne", str "t")
+  , ("volt", str "V")
+  , ("watt", str "W")
+  , ("weber", str "Wb")
+  ]
diff --git a/src/Text/Pandoc/Readers/LaTeX/Table.hs b/src/Text/Pandoc/Readers/LaTeX/Table.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Readers/LaTeX/Table.hs
@@ -0,0 +1,384 @@
+{-# LANGUAGE BangPatterns #-}
+{-# LANGUAGE OverloadedStrings #-}
+module Text.Pandoc.Readers.LaTeX.Table
+  ( tableEnvironments )
+where
+
+import Data.Functor (($>))
+import Text.Pandoc.Class
+import Text.Pandoc.Readers.LaTeX.Parsing
+import Text.Pandoc.TeX
+import Text.Pandoc.Builder as B
+import qualified Data.Map as M
+import Data.Text (Text)
+import Data.Maybe (fromMaybe)
+import qualified Data.Text as T
+import Control.Applicative ((<|>), optional, many)
+import Control.Monad (when, void)
+import Text.Pandoc.Shared (safeRead, trim)
+import Text.Pandoc.Logging (LogMessage(SkippedContent))
+import Text.Pandoc.Walk (walkM)
+import Text.Pandoc.Parsing hiding (blankline, many, mathDisplay, mathInline,
+                            optional, space, spaces, withRaw, (<|>))
+
+tableEnvironments :: PandocMonad m
+                  => LP m Blocks
+                  -> LP m Inlines
+                  -> M.Map Text (LP m Blocks)
+tableEnvironments block inline =
+  M.fromList
+  [ ("longtable",  env "longtable" $
+          resetCaption *>
+            simpTable block inline "longtable" False >>= addTableCaption)
+  , ("table",  env "table" $
+          skipopts *> resetCaption *> blocks >>= addTableCaption)
+  , ("tabular*", env "tabular*" $ simpTable block inline "tabular*" True)
+  , ("tabularx", env "tabularx" $ simpTable block inline "tabularx" True)
+  , ("tabular", env "tabular"  $ simpTable block inline "tabular" False)
+  , ("supertabular", env "supertabular" $ simpTable block inline "supertabular" False)
+  , ("supertabular*", env "supertabular*" $ simpTable block inline "supertabular*" False)
+  ]
+ where
+   blocks = mconcat <$> many block
+
+hline :: PandocMonad m => LP m ()
+hline = try $ do
+  spaces
+  hasParenArg <-
+      (False <$ controlSeq "hline") <|>
+      (False <$ controlSeq "cline") <|>
+      (True <$ controlSeq "cmidrule") <|>
+      -- booktabs rules:
+      (True <$ controlSeq "toprule") <|>
+      (True <$ controlSeq "bottomrule") <|>
+      (True <$ controlSeq "midrule") <|>
+      (True <$ controlSeq "endhead") <|>
+      (True <$ controlSeq "endfirsthead")
+  optional rawopt
+  when hasParenArg $ void $ optional (parenWrapped (() <$ singleChar))
+
+lbreak :: PandocMonad m => LP m Tok
+lbreak = (controlSeq "\\" <|> controlSeq "tabularnewline")
+         <* optional (void rawopt) <* spaces
+
+amp :: PandocMonad m => LP m Tok
+amp = symbol '&'
+
+-- Split a Word into individual Symbols (for parseAligns)
+splitWordTok :: PandocMonad m => LP m ()
+splitWordTok = do
+  TokStream macrosExpanded inp <- getInput
+  case inp of
+       (Tok spos Word t : rest) ->
+         setInput $ TokStream macrosExpanded
+                  $ map (Tok spos Symbol . T.singleton) (T.unpack t) <> rest
+       _ -> return ()
+
+parseAligns :: PandocMonad m => LP m [(Alignment, ColWidth, ([Tok], [Tok]))]
+parseAligns = try $ do
+  let maybeBar = skipMany
+        (try $ sp *> (() <$ symbol '|' <|> () <$ (symbol '@' >> braced)))
+  let cAlign = AlignCenter <$ symbol 'c'
+  let lAlign = AlignLeft <$ symbol 'l'
+  let rAlign = AlignRight <$ symbol 'r'
+  let parAlign = AlignLeft <$ symbol 'p'
+  -- aligns from tabularx
+  let xAlign = AlignLeft <$ symbol 'X'
+  let mAlign = AlignLeft <$ symbol 'm'
+  let bAlign = AlignLeft <$ symbol 'b'
+  let alignChar = splitWordTok *> (  cAlign <|> lAlign <|> rAlign <|> parAlign
+                                 <|> xAlign <|> mAlign <|> bAlign )
+  let alignPrefix = symbol '>' >> braced
+  let alignSuffix = symbol '<' >> braced
+  let colWidth = try $ do
+        ts <- braced
+        let isLinewidth (Tok _ (CtrlSeq "linewidth") _) = True
+            isLinewidth _ = False
+        case break isLinewidth ts of
+          (ds, _:_) -> return $ safeRead $ trim $ untokenize ds
+          _ -> return Nothing
+  let alignSpec = do
+        pref <- option [] alignPrefix
+        spaces
+        al <- alignChar
+        width <- colWidth <|> option Nothing (do s <- untokenize <$> braced
+                                                 pos <- getPosition
+                                                 report $ SkippedContent s pos
+                                                 return Nothing)
+        spaces
+        suff <- option [] alignSuffix
+        return (al, width, (pref, suff))
+  let starAlign = do -- '*{2}{r}' == 'rr', we just expand like a macro
+        symbol '*'
+        spaces
+        ds <- trim . untokenize <$> bracedOrToken
+        spaces
+        spec <- bracedOrToken
+        case safeRead ds of
+             Just n  -> do
+               TokStream _ ts <- getInput
+               setInput $ TokStream False (mconcat (replicate n spec) ++ ts)
+             Nothing -> Prelude.fail $ "Could not parse " <> T.unpack ds <> " as number"
+  bgroup
+  spaces
+  maybeBar
+  aligns' <- many $ try $ spaces >> optional starAlign >>
+                            (alignSpec <* maybeBar)
+  spaces
+  egroup
+  spaces
+  return $ map toSpec aligns'
+  where
+    toColWidth (Just w) | w > 0 = ColWidth w
+    toColWidth _                = ColWidthDefault
+    toSpec (x, y, z) = (x, toColWidth y, z)
+
+-- N.B. this parser returns a Row that may have erroneous empty cells
+-- in it. See the note above fixTableHead for details.
+parseTableRow :: PandocMonad m
+              => LP m Blocks -- ^ block parser
+              -> LP m Inlines -- ^ inline parser
+              -> Text   -- ^ table environment name
+              -> [([Tok], [Tok])] -- ^ pref/suffixes
+              -> LP m Row
+parseTableRow block inline envname prefsufs = do
+  notFollowedBy (spaces *> end_ envname)
+  -- contexts that can contain & that is not colsep:
+  let canContainAmp (Tok _ (CtrlSeq "begin") _) = True
+      canContainAmp (Tok _ (CtrlSeq "verb") _)  = True
+      canContainAmp (Tok _ (CtrlSeq "Verb") _)  = True
+      canContainAmp _       = False
+  -- add prefixes and suffixes in token stream:
+  let celltoks (pref, suff) = do
+        prefpos <- getPosition
+        contents <- mconcat <$>
+            many ( snd <$> withRaw
+                     ((lookAhead (controlSeq "parbox") >>
+                       void block) -- #5711
+                      <|>
+                      (lookAhead (satisfyTok canContainAmp) >> void inline)
+                      <|>
+                      (lookAhead (controlSeq "begin") >>
+                       void block) -- #4746
+                      <|>
+                      (lookAhead (symbol '$') >> void inline))
+                  <|>
+                   (do notFollowedBy
+                         (() <$ amp <|> () <$ lbreak <|> end_ envname)
+                       count 1 anyTok) )
+
+        suffpos <- getPosition
+        option [] (count 1 amp)
+        return $ map (setpos prefpos) pref ++ contents ++ map (setpos suffpos) suff
+  rawcells <- mapM celltoks prefsufs
+  cells <- mapM (parseFromToks (parseTableCell block)) rawcells
+  spaces
+  return $ Row nullAttr cells
+
+parseTableCell :: PandocMonad m => LP m Blocks -> LP m Cell
+parseTableCell block = do
+  spaces
+  updateState $ \st -> st{ sInTableCell = True }
+  cell' <-   multicolumnCell block
+         <|> multirowCell block
+         <|> parseSimpleCell
+         <|> parseEmptyCell
+  updateState $ \st -> st{ sInTableCell = False }
+  spaces
+  return cell'
+  where
+    -- The parsing of empty cells is important in LaTeX, especially when dealing
+    -- with multirow/multicolumn. See #6603.
+    parseEmptyCell = spaces $> emptyCell
+    parseSimpleCell = simpleCell <$> (plainify . mconcat <$> many block)
+
+
+cellAlignment :: PandocMonad m => LP m Alignment
+cellAlignment = skipMany (symbol '|') *> alignment <* skipMany (symbol '|')
+  where
+    alignment = do
+      c <- untoken <$> singleChar <* optional braced -- ignore args
+      return $ case c of
+        "l" -> AlignLeft
+        "r" -> AlignRight
+        "c" -> AlignCenter
+        "*" -> AlignDefault
+        _   -> AlignDefault
+
+plainify :: Blocks -> Blocks
+plainify bs = case toList bs of
+                [Para ils] -> plain (fromList ils)
+                _          -> bs
+
+multirowCell :: PandocMonad m => LP m Blocks -> LP m Cell
+multirowCell block = controlSeq "multirow" >> do
+  -- Full prototype for \multirow macro is:
+  --     \multirow[vpos]{nrows}[bigstruts]{width}[vmove]{text}
+  -- However, everything except `nrows` and `text` make
+  -- sense in the context of the Pandoc AST
+  _ <- optional $ symbol '[' *> cellAlignment <* symbol ']'   -- vertical position
+  nrows <- fmap (fromMaybe 1 . safeRead . untokenize) braced
+  _ <- optional $ symbol '[' *> manyTill anyTok (symbol ']')  -- bigstrut-related
+  _ <- symbol '{' *> manyTill anyTok (symbol '}')             -- Cell width
+  _ <- optional $ symbol '[' *> manyTill anyTok (symbol ']')  -- Length used for fine-tuning
+  content <- symbol '{' *> (plainify . mconcat <$> many block) <* symbol '}'
+  return $ cell AlignDefault (RowSpan nrows) (ColSpan 1) content
+
+multicolumnCell :: PandocMonad m => LP m Blocks -> LP m Cell
+multicolumnCell block = controlSeq "multicolumn" >> do
+  span' <- fmap (fromMaybe 1 . safeRead . untokenize) braced
+  alignment <- symbol '{' *> cellAlignment <* symbol '}'
+
+  let singleCell = do
+        content <- plainify . mconcat <$> many block
+        return $ cell alignment (RowSpan 1) (ColSpan span') content
+
+  -- Two possible contents: either a \multirow cell, or content.
+  -- E.g. \multicol{1}{c}{\multirow{2}{1em}{content}}
+  -- Note that a \multirow cell can be nested in a \multicolumn,
+  -- but not the other way around. See #6603
+  let nestedCell = do
+        (Cell _ _ (RowSpan rs) _ bs) <- multirowCell block
+        return $ cell
+                  alignment
+                  (RowSpan rs)
+                  (ColSpan span')
+                  (fromList bs)
+
+  symbol '{' *> (nestedCell <|> singleCell) <* symbol '}'
+
+-- LaTeX tables are stored with empty cells underneath multirow cells
+-- denoting the grid spaces taken up by them. More specifically, if a
+-- cell spans m rows, then it will overwrite all the cells in the
+-- columns it spans for (m-1) rows underneath it, requiring padding
+-- cells in these places. These padding cells need to be removed for
+-- proper table reading. See #6603.
+--
+-- These fixTable functions do not otherwise fix up malformed
+-- input tables: that is left to the table builder.
+fixTableHead :: TableHead -> TableHead
+fixTableHead (TableHead attr rows) = TableHead attr rows'
+  where
+    rows' = fixTableRows rows
+
+fixTableBody :: TableBody -> TableBody
+fixTableBody (TableBody attr rhc th tb)
+  = TableBody attr rhc th' tb'
+  where
+    th' = fixTableRows th
+    tb' = fixTableRows tb
+
+fixTableRows :: [Row] -> [Row]
+fixTableRows = fixTableRows' $ repeat Nothing
+  where
+    fixTableRows' oldHang (Row attr cells : rs)
+      = let (newHang, cells') = fixTableRow oldHang cells
+            rs'               = fixTableRows' newHang rs
+        in Row attr cells' : rs'
+    fixTableRows' _ [] = []
+
+-- The overhang is represented as Just (relative cell dimensions) or
+-- Nothing for an empty grid space.
+fixTableRow :: [Maybe (ColSpan, RowSpan)] -> [Cell] -> ([Maybe (ColSpan, RowSpan)], [Cell])
+fixTableRow oldHang cells
+  -- If there's overhang, drop cells until their total width meets the
+  -- width of the occupied grid spaces (or we run out)
+  | (n, prefHang, restHang) <- splitHang oldHang
+  , n > 0
+  = let cells' = dropToWidth getCellW n cells
+        (restHang', cells'') = fixTableRow restHang cells'
+    in (prefHang restHang', cells'')
+  -- Otherwise record the overhang of a pending cell and fix the rest
+  -- of the row
+  | c@(Cell _ _ h w _):cells' <- cells
+  = let h' = max 1 h
+        w' = max 1 w
+        oldHang' = dropToWidth getHangW w' oldHang
+        (newHang, cells'') = fixTableRow oldHang' cells'
+    in (toHang w' h' <> newHang, c : cells'')
+  | otherwise
+  = (oldHang, [])
+  where
+    getCellW (Cell _ _ _ w _) = w
+    getHangW = maybe 1 fst
+    getCS (ColSpan n) = n
+
+    toHang c r
+      | r > 1     = [Just (c, r)]
+      | otherwise = replicate (getCS c) Nothing
+
+    -- Take the prefix of the overhang list representing filled grid
+    -- spaces. Also return the remainder and the length of this prefix.
+    splitHang = splitHang' 0 id
+
+    splitHang' !n l (Just (c, r):xs)
+      = splitHang' (n + c) (l . (toHang c (r-1) ++)) xs
+    splitHang' n l xs = (n, l, xs)
+
+    -- Drop list items until the total width of the dropped items
+    -- exceeds the passed width.
+    dropToWidth _     n l | n < 1 = l
+    dropToWidth wproj n (c:cs)    = dropToWidth wproj (n - wproj c) cs
+    dropToWidth _     _ []        = []
+
+simpTable :: PandocMonad m
+          => LP m Blocks
+          -> LP m Inlines
+          -> Text
+          -> Bool
+          -> LP m Blocks
+simpTable block inline envname hasWidthParameter = try $ do
+  when hasWidthParameter $ () <$ tokWith inline
+  skipopts
+  colspecs <- parseAligns
+  let (aligns, widths, prefsufs) = unzip3 colspecs
+  optional $ controlSeq "caption" *> setCaption inline
+  spaces
+  optional label
+  spaces
+  optional lbreak
+  spaces
+  skipMany hline
+  spaces
+  header' <- option [] . try . fmap (:[]) $
+             parseTableRow block inline envname prefsufs <*
+               lbreak <* many1 hline
+  spaces
+  rows <- sepEndBy (parseTableRow block inline envname prefsufs)
+                    (lbreak <* optional (skipMany hline))
+  spaces
+  optional $ controlSeq "caption" *> setCaption inline
+  spaces
+  optional label
+  spaces
+  optional lbreak
+  spaces
+  lookAhead $ controlSeq "end" -- make sure we're at end
+  let th  = fixTableHead $ TableHead nullAttr header'
+  let tbs = [fixTableBody $ TableBody nullAttr 0 [] rows]
+  let tf  = TableFoot nullAttr []
+  return $ table emptyCaption (zip aligns widths) th tbs tf
+
+addTableCaption :: PandocMonad m => Blocks -> LP m Blocks
+addTableCaption = walkM go
+  where go (Table attr c spec th tb tf) = do
+          st <- getState
+          let capt = fromMaybe c $ sCaption st
+          let mblabel = sLastLabel st
+          case mblabel of
+            Nothing -> return ()
+            Just lab -> do
+                     num <- getNextNumber sLastTableNum
+                     setState
+                       st{ sLastTableNum = num
+                         , sLabels = M.insert lab
+                                    [Str (renderDottedNum num)]
+                                    (sLabels st) }
+          -- add num to caption?
+          let attr' = case (attr, mblabel) of
+                        ((_,classes,kvs), Just ident) ->
+                           (ident,classes,kvs)
+                        _ -> attr
+          return $ maybe id removeLabel mblabel
+                 $ Table attr' capt spec th tb tf
+        go x = return x
diff --git a/src/Text/Pandoc/Readers/LaTeX/Types.hs b/src/Text/Pandoc/Readers/LaTeX/Types.hs
deleted file mode 100644
--- a/src/Text/Pandoc/Readers/LaTeX/Types.hs
+++ /dev/null
@@ -1,51 +0,0 @@
-{-
-Copyright (C) 2017 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 John MacFarlane
-   License     : GNU GPL, version 2 or above
-
-   Maintainer  : John MacFarlane <jgm@berkeley.edu>
-   Stability   : alpha
-   Portability : portable
-
-Types for LaTeX tokens and macros.
--}
-module Text.Pandoc.Readers.LaTeX.Types ( Tok(..)
-                                       , TokType(..)
-                                       , Macro(..)
-                                       , ExpansionPoint(..)
-                                       , SourcePos
-                                       )
-where
-import Data.Text (Text)
-import Text.Parsec.Pos (SourcePos)
-
-data TokType = CtrlSeq Text | Spaces | Newline | Symbol | Word | Comment |
-               Esc1    | Esc2   | Arg Int
-     deriving (Eq, Ord, Show)
-
-data Tok = Tok SourcePos TokType Text
-     deriving (Eq, Ord, Show)
-
-data ExpansionPoint = ExpandWhenDefined | ExpandWhenUsed
-     deriving (Eq, Ord, Show)
-
-data Macro = Macro ExpansionPoint Int (Maybe [Tok]) [Tok]
-     deriving Show
diff --git a/src/Text/Pandoc/Readers/Man.hs b/src/Text/Pandoc/Readers/Man.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Readers/Man.hs
@@ -0,0 +1,561 @@
+{-# LANGUAGE FlexibleContexts  #-}
+{-# LANGUAGE ViewPatterns      #-}
+{-# LANGUAGE OverloadedStrings #-}
+{- |
+   Module      : Text.Pandoc.Readers.Man
+   Copyright   : Copyright (C) 2018-2020 Yan Pashkovsky and John MacFarlane
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : Yan Pashkovsky <yanp.bugz@gmail.com>
+   Stability   : WIP
+   Portability : portable
+
+Conversion of man to 'Pandoc' document.
+-}
+module Text.Pandoc.Readers.Man (readMan) where
+
+import Data.Char (toLower)
+import Data.Default (Default)
+import Control.Monad (mzero, guard, void)
+import Control.Monad.Trans (lift)
+import Control.Monad.Except (throwError)
+import Data.Maybe (catMaybes, isJust)
+import Data.List (intersperse)
+import qualified Data.Text as T
+import Text.Pandoc.Builder as B
+import Text.Pandoc.Class.PandocMonad (PandocMonad(..), report)
+import Text.Pandoc.Logging (LogMessage(..))
+import Text.Pandoc.Options
+import Text.Pandoc.Parsing.Capabilities
+import Text.Pandoc.Parsing
+import Text.Pandoc.Walk (query)
+import Text.Pandoc.Readers.Roff  -- TODO explicit imports
+import qualified Text.Pandoc.Parsing as P
+import qualified Data.Foldable as Foldable
+import qualified Data.Set as Set
+import Text.Pandoc.Shared (extractSpaces)
+
+data ManState = ManState { readerOptions   :: ReaderOptions
+                         , manLogMessages  :: []LogMessage
+                         , manIdentifiers  :: Set.Set T.Text
+                         , metadata        :: Meta
+                         , tableCellsPlain :: Bool
+                         } deriving Show
+
+instance Default ManState where
+  def = ManState { readerOptions   = def
+                 , manLogMessages  = []
+                 , manIdentifiers  = Set.empty
+                 , metadata        = nullMeta
+                 , tableCellsPlain = True }
+
+instance HasReaderOptions ManState where
+  extractReaderOptions = readerOptions
+
+instance HasLogMessages ManState where
+  addLogMessage msg st = st{ manLogMessages = msg : manLogMessages st }
+  getLogMessages st = reverse $ manLogMessages st
+
+instance HasIdentifierList ManState where
+  extractIdentifierList = manIdentifiers
+  updateIdentifierList f st = st{ manIdentifiers = f $ manIdentifiers st }
+
+type ManParser m = P.ParsecT [RoffToken] ManState m
+
+
+-- | Read man (troff) from an input string and return a Pandoc document.
+readMan :: (PandocMonad m, ToSources a)
+        => ReaderOptions
+        -> a
+        -> m Pandoc
+readMan opts s = do
+  let Sources inps = toSources s
+  tokenz <- mconcat <$> mapM (uncurry lexRoff) inps
+  let state = def {readerOptions = opts} :: ManState
+  eitherdoc <- readWithMTokens parseMan state
+     (Foldable.toList . unRoffTokens $ tokenz)
+  either (throwError . fromParsecError (Sources inps)) return eitherdoc
+
+
+readWithMTokens :: PandocMonad m
+        => ParsecT [RoffToken] ManState m a  -- ^ parser
+        -> ManState                         -- ^ initial state
+        -> [RoffToken]                       -- ^ input
+        -> m (Either ParseError a)
+readWithMTokens parser state input =
+  runParserT parser state "source" input
+
+
+parseMan :: PandocMonad m => ManParser m Pandoc
+parseMan = do
+  bs <- many parseBlock <* eof
+  meta <- metadata <$> getState
+  let (Pandoc _ blocks) = doc $ mconcat bs
+  reportLogMessages
+  return $ Pandoc meta blocks
+
+parseBlock :: PandocMonad m => ManParser m Blocks
+parseBlock = choice [ parseList
+                    , parseDefinitionList
+                    , parseHeader
+                    , parseTable
+                    , parseTitle
+                    , parseCodeBlock
+                    , parseBlockQuote
+                    , parseNewParagraph
+                    , parsePara
+                    , skipUnknownMacro
+                    ]
+
+parseTable :: PandocMonad m => ManParser m Blocks
+parseTable = do
+  updateState $ \st -> st { tableCellsPlain = True }
+  let isTbl Tbl{} = True
+      isTbl _     = False
+  Tbl _opts rows pos <- msatisfy isTbl
+  case rows of
+    ((as,_):_) -> try (do
+      let as' = map (columnTypeToAlignment . columnType) as
+      guard $ all isJust as'
+      let alignments = catMaybes as'
+      let (headerRow', bodyRows') =
+            case rows of
+              (h:x:bs)
+               | isHrule x -> (h, bs)
+              _ -> (([],[]), rows)
+      headerRow <- mapM parseTableCell $ snd headerRow'
+      bodyRows <- mapM (mapM parseTableCell . snd) bodyRows'
+      isPlainTable <- tableCellsPlain <$> getState
+      let widths = if isPlainTable
+                      then repeat ColWidthDefault
+                      else repeat $ ColWidth (1.0 / fromIntegral (length alignments))
+      return $ B.table B.emptyCaption (zip alignments widths)
+                  (TableHead nullAttr $ toHeaderRow headerRow)
+                  [TableBody nullAttr 0 [] $ map toRow bodyRows]
+                  (TableFoot nullAttr [])) <|> fallback pos
+    [] -> fallback pos
+
+ where
+
+  parseTableCell ts = do
+    st <- getState
+    let ts' = Foldable.toList $ unRoffTokens ts
+    let plaintcell = try $ do
+          skipMany memptyLine
+          plain . trimInlines <$> (parseInlines <* eof)
+    let blockstcell = try $ do
+          skipMany memptyLine
+          mconcat <$> many parseBlock <* eof
+    res <- if null ts'
+              then return $ Right mempty
+              else lift $ readWithMTokens plaintcell st ts'
+    case res of
+      Left _  -> do
+        res' <- lift $ readWithMTokens blockstcell st ts'
+        case res' of
+          Left _  -> Prelude.fail "Could not parse table cell"
+          Right x -> do
+            updateState $ \s -> s{ tableCellsPlain = False }
+            return x
+      Right x -> return x
+
+  isHrule :: TableRow -> Bool
+  isHrule ([cellfmt], _) = columnType cellfmt `elem` ['_','-','=']
+  isHrule (_, [RoffTokens ss]) =
+    case Foldable.toList ss of
+      [TextLine [RoffStr (T.unpack -> [c])]] -> c `elem` ['_','-','=']
+      _                     -> False
+  isHrule _ = False
+
+  fallback pos = do
+    report $ SkippedContent "TABLE" pos
+    return $ B.para (B.text "TABLE")
+
+  columnTypeToAlignment :: Char -> Maybe Alignment
+  columnTypeToAlignment c =
+    case toLower c of
+      'a' -> Just AlignLeft
+      'c' -> Just AlignCenter
+      'l' -> Just AlignLeft
+      'n' -> Just AlignRight
+      'r' -> Just AlignRight
+      _   -> Nothing
+
+  toRow = Row nullAttr . map simpleCell
+  toHeaderRow l = [toRow l | not (null l)]
+
+parseNewParagraph :: PandocMonad m => ManParser m Blocks
+parseNewParagraph = do
+  mmacro "P" <|> mmacro "PP" <|> mmacro "LP" <|> memptyLine
+  return mempty
+
+--
+-- Parser: [RoffToken] -> Pandoc
+--
+
+msatisfy :: Monad m
+         => (RoffToken -> Bool) -> P.ParsecT [RoffToken] st m RoffToken
+msatisfy predic = P.tokenPrim show nextPos testTok
+  where
+    testTok t     = if predic t then Just t else Nothing
+    nextPos _pos _x (ControlLine _ _ pos':_) = pos'
+    nextPos pos _x _xs  = P.updatePosString
+                             (P.setSourceColumn
+                               (P.setSourceLine pos $
+                                 P.sourceLine pos + 1) 1) ""
+
+mtoken :: PandocMonad m => ManParser m RoffToken
+mtoken = msatisfy (const True)
+
+mline :: PandocMonad m => ManParser m RoffToken
+mline = msatisfy isTextLine where
+  isTextLine (TextLine _) = True
+  isTextLine _ = False
+
+memptyLine :: PandocMonad m => ManParser m RoffToken
+memptyLine = msatisfy isEmptyLine where
+  isEmptyLine EmptyLine = True
+  isEmptyLine _ = False
+
+mmacro :: PandocMonad m => T.Text -> ManParser m RoffToken
+mmacro mk = mmacroMatching (== mk)
+
+mmacroMatching :: PandocMonad m => (T.Text -> Bool) -> ManParser m RoffToken
+mmacroMatching f = msatisfy isControlLine where
+  isControlLine (ControlLine mk _ _) = f mk
+  isControlLine _ = False
+
+mmacroAny :: PandocMonad m => ManParser m RoffToken
+mmacroAny = msatisfy isControlLine where
+  isControlLine ControlLine{} = True
+  isControlLine _ = False
+
+--
+-- RoffToken -> Block functions
+--
+
+parseTitle :: PandocMonad m => ManParser m Blocks
+parseTitle = do
+  (ControlLine _ args _) <- mmacro "TH"
+  let adjustMeta =
+       case args of
+         (x:y:z:a:b:_) -> setMeta "title" (linePartsToInlines x) .
+                          setMeta "section" (linePartsToInlines y) .
+                          setMeta "date" (linePartsToInlines z) .
+                          setMeta "footer" (linePartsToInlines a) .
+                          setMeta "header" (linePartsToInlines b)
+         [x,y,z,a] -> setMeta "title" (linePartsToInlines x) .
+                      setMeta "section" (linePartsToInlines y) .
+                      setMeta "date" (linePartsToInlines z) .
+                      setMeta "footer" (linePartsToInlines a)
+         [x,y,z]   -> setMeta "title" (linePartsToInlines x) .
+                      setMeta "section" (linePartsToInlines y) .
+                      setMeta "date" (linePartsToInlines z)
+         [x,y]     -> setMeta "title" (linePartsToInlines x) .
+                      setMeta "section" (linePartsToInlines y)
+         [x]       -> setMeta "title" (linePartsToInlines x)
+         []        -> id
+  updateState $ \st -> st{ metadata = adjustMeta $ metadata st }
+  return mempty
+
+linePartsToInlines :: [LinePart] -> Inlines
+linePartsToInlines = go False
+
+  where
+  go :: Bool -> [LinePart] -> Inlines
+  go _ [] = mempty
+  go mono (MacroArg _:xs) = go mono xs -- shouldn't happen
+  go mono (RoffStr s : RoffStr t : xs) = go mono (RoffStr (s <> t):xs)
+  go mono (RoffStr s : xs)
+    | mono      = code s <> go mono xs
+    | otherwise = text s <> go mono xs
+  go mono (Font fs: xs)
+    | litals > 0 && litals >= lbolds && litals >= lmonos
+       = extractSpaces emph (go mono (Font fs{ fontItalic = False } :
+                   map (adjustFontSpec (\s -> s{ fontItalic = False }))
+                   itals)) <>
+            go mono italsrest
+    | lbolds > 0 && lbolds >= lmonos
+       = extractSpaces strong (go mono (Font fs{ fontBold = False } :
+              map (adjustFontSpec (\s -> s{ fontBold = False }))
+              bolds)) <>
+            go mono boldsrest
+    | lmonos > 0
+       = go True (Font fs{ fontMonospace = False } :
+          map (adjustFontSpec (\s -> s { fontMonospace = False }))
+          monos) <> go mono monosrest
+    | otherwise = go mono xs
+    where
+      adjustFontSpec f (Font fspec) = Font (f fspec)
+      adjustFontSpec _ x            = x
+      withFont f (Font fspec) = f fspec
+      withFont _ _            = False
+      litals = length itals
+      lbolds = length bolds
+      lmonos = length monos
+      (itals, italsrest) =
+        if fontItalic fs
+           then break (withFont (not . fontItalic)) xs
+           else ([], xs)
+      (bolds, boldsrest) =
+        if fontBold fs
+           then break (withFont (not . fontBold)) xs
+           else ([], xs)
+      (monos, monosrest) =
+        if fontMonospace fs
+           then break (withFont (not . fontMonospace)) xs
+           else ([], xs)
+
+parsePara :: PandocMonad m => ManParser m Blocks
+parsePara = para . trimInlines <$> parseInlines
+
+parseInlines :: PandocMonad m => ManParser m Inlines
+parseInlines = mconcat . intersperse B.space <$> many1 parseInline
+
+parseInline :: PandocMonad m => ManParser m Inlines
+parseInline = try $ do
+  tok <- mtoken
+  case tok of
+    TextLine lparts -> return $ linePartsToInlines lparts
+    ControlLine mname args pos -> handleInlineMacro mname args pos
+    _ -> mzero
+
+handleInlineMacro :: PandocMonad m
+                  => T.Text -> [Arg] -> SourcePos -> ManParser m Inlines
+handleInlineMacro mname args _pos =
+  case mname of
+    "UR" -> parseLink args
+    "MT" -> parseEmailLink args
+    "B"  -> parseBold args
+    "I"  -> parseItalic args
+    "br" -> return linebreak
+    "BI" -> parseAlternatingFonts [strong, emph] args
+    "IB" -> parseAlternatingFonts [emph, strong] args
+    "IR" -> parseAlternatingFonts [emph, id] args
+    "RI" -> parseAlternatingFonts [id, emph] args
+    "BR" -> parseAlternatingFonts [strong, id] args
+    "RB" -> parseAlternatingFonts [id, strong] args
+    "SY" -> return $ extractSpaces strong $ mconcat $ intersperse B.space
+                   $ map linePartsToInlines args
+    "YS" -> return mempty
+    "OP" -> case args of
+              (x:ys) -> return $ B.space <> str "[" <> B.space <>
+                         mconcat (extractSpaces strong (linePartsToInlines x) :
+                           map ((B.space <>) . linePartsToInlines) ys)
+                         <> B.space <> str "]"
+              []     -> return mempty
+    _ -> mzero
+
+parseBold :: PandocMonad m => [Arg] -> ManParser m Inlines
+parseBold [] = do
+  TextLine lparts <- mline
+  return $ extractSpaces strong $ linePartsToInlines lparts
+parseBold args = return $
+  extractSpaces strong $
+  mconcat $ intersperse B.space $ map linePartsToInlines args
+
+parseItalic :: PandocMonad m => [Arg] -> ManParser m Inlines
+parseItalic [] = do
+  TextLine lparts <- mline
+  return $ extractSpaces emph $ linePartsToInlines lparts
+parseItalic args = return $
+  extractSpaces emph $
+  mconcat $ intersperse B.space $ map linePartsToInlines args
+
+parseAlternatingFonts :: [Inlines -> Inlines]
+                      -> [Arg]
+                      -> ManParser m Inlines
+parseAlternatingFonts constructors args = return $ mconcat $
+  zipWith (\f arg -> f (linePartsToInlines arg)) (cycle constructors) args
+
+lineInl :: PandocMonad m => ManParser m Inlines
+lineInl = do
+  (TextLine fragments) <- mline
+  return $ linePartsToInlines fragments
+
+bareIP :: PandocMonad m => ManParser m RoffToken
+bareIP = msatisfy isBareIP where
+  isBareIP (ControlLine "IP" [] _) = True
+  isBareIP _                  = False
+
+endmacro :: PandocMonad m => T.Text -> ManParser m ()
+endmacro name = void (mmacro name)
+             <|> lookAhead (void newBlockMacro)
+             <|> lookAhead eof
+  where
+    newBlockMacro = msatisfy isNewBlockMacro
+    isNewBlockMacro (ControlLine "SH" _ _) = True
+    isNewBlockMacro (ControlLine "SS" _ _) = True
+    isNewBlockMacro _ = False
+
+parseCodeBlock :: PandocMonad m => ManParser m Blocks
+parseCodeBlock = try $ do
+  optional bareIP
+  optional (mmacro "in") -- some people indent their code
+  toks <- (mmacro "nf" *> manyTill codeline (endmacro "fi"))
+      <|> (mmacro "EX" *> manyTill codeline (endmacro "EE"))
+  optional (mmacro "in")
+  return $ codeBlock (T.intercalate "\n" $ catMaybes toks)
+
+  where
+
+  codeline = do
+    tok <- mtoken
+    case tok of
+      ControlLine "PP" _ _ -> return $ Just "" -- .PP sometimes used for blank line
+      ControlLine mname args pos ->
+        (Just . query getText <$> handleInlineMacro mname args pos) <|>
+          do report $ SkippedContent ("." <> mname) pos
+             return Nothing
+      Tbl _ _ pos     -> do
+        report $ SkippedContent "TABLE" pos
+        return $ Just "TABLE"
+      EmptyLine -> return $ Just ""
+      TextLine ss
+        | not (null ss)
+        , all isFontToken ss -> return Nothing
+        | otherwise -> return $ Just $ linePartsToText ss
+
+  isFontToken Font{}     = True
+  isFontToken _            = False
+
+  getText :: Inline -> T.Text
+  getText (Str s)    = s
+  getText Space      = " "
+  getText (Code _ s) = s
+  getText SoftBreak  = "\n"
+  getText LineBreak  = "\n"
+  getText _          = ""
+
+parseHeader :: PandocMonad m => ManParser m Blocks
+parseHeader = do
+  ControlLine name args _ <- mmacro "SH" <|> mmacro "SS"
+  contents <- if null args
+                 then option mempty lineInl
+                 else return $ mconcat $ intersperse B.space
+                             $ map linePartsToInlines args
+  let lvl = if name == "SH" then 1 else 2
+  attr <- registerHeader nullAttr contents
+
+  return $ B.headerWith attr lvl contents
+
+parseBlockQuote :: PandocMonad m => ManParser m Blocks
+parseBlockQuote = blockQuote <$>
+   (  (mmacro "RS" *> (mconcat <$> manyTill parseBlock (endmacro "RE")))
+  <|> parseIndentedParagraphs
+   )
+ where
+  parseIndentedParagraphs = try $ do
+    bareIP
+    first <- parsePara <|> parseCodeBlock
+    rest <- many $ try (memptyLine *> (parsePara <|> parseCodeBlock))
+    pure (first <> mconcat rest)
+
+data ListType = Ordered ListAttributes
+              | Bullet
+              | Definition T.Text
+
+listTypeMatches :: Maybe ListType -> ListType -> Bool
+listTypeMatches Nothing _            = True
+listTypeMatches (Just Bullet) Bullet = True
+listTypeMatches (Just (Ordered (_,x,y))) (Ordered (_,x',y'))
+                                     = x == x' && y == y'
+listTypeMatches (Just (Definition _)) (Definition _) = True
+listTypeMatches (Just _) _           = False
+
+listItem :: PandocMonad m => Maybe ListType -> ManParser m (ListType, Blocks)
+listItem mbListType = try $ do
+  (ControlLine _ args _) <- mmacro "IP"
+  case args of
+    (arg1 : _)  -> do
+      let cs = linePartsToText arg1
+      let cs' = if not (T.any (== '.') cs || T.any (== ')') cs) then cs <> "." else cs
+      let lt = case P.runParser anyOrderedListMarker defaultParserState
+                     "list marker" cs' of
+                  Right (start, listtype, listdelim)
+                    | cs == cs' -> Ordered (start, listtype, listdelim)
+                    | otherwise -> Ordered (start, listtype, DefaultDelim)
+                  Left _
+                    | cs == "\183" || cs == "-" || cs == "*" || cs == "+"
+                                   -> Bullet
+                    | otherwise    -> Definition cs
+      guard $ listTypeMatches mbListType lt
+      skipMany memptyLine
+      inls <- option mempty parseInlines
+      skipMany memptyLine
+      continuations <- mconcat <$> many continuation
+      return (lt, para inls <> continuations)
+    []          -> mzero
+
+parseList :: PandocMonad m => ManParser m Blocks
+parseList = try $ do
+  x@(lt, _) <- listItem Nothing
+  xs <- many (listItem (Just lt))
+  let toDefItem (Definition t, bs) = (B.text t, [bs])
+      toDefItem _ = mempty
+  return $ case lt of
+             Bullet        -> bulletList $ map snd (x:xs)
+             Ordered lattr -> orderedListWith lattr $ map snd (x:xs)
+             Definition _  -> definitionList $ map toDefItem (x:xs)
+
+continuation :: PandocMonad m => ManParser m Blocks
+continuation =
+      (mmacro "RS" *> (mconcat <$> manyTill parseBlock (endmacro "RE")))
+  <|> (bareIP *> parsePara)
+  <|> (notFollowedBy (mmacroMatching
+                      (`elem` ["TP","IP","LP","P","PP","HP",
+                               "RE","RS","SH","SS","SV","YS","TH",
+                               "TQ","YS","AT","DT","OP","PD","UC"]))
+                                *> parseBlock)
+
+definitionListItem :: PandocMonad m
+                   => ManParser m (Inlines, [Blocks])
+definitionListItem = try $ do
+  mmacro "TP"  -- args specify indent level, can ignore
+  skipMany memptyLine
+  term <- parseInline
+  skipMany memptyLine
+  moreterms <- many $ try $ do
+                 mmacro "TQ"
+                 parseInline
+  skipMany memptyLine
+  firstBlock <- parseBlock
+  otherBlocks <- mconcat <$> many continuation
+  return ( mconcat (intersperse B.linebreak (term:moreterms))
+         , [firstBlock <> otherBlocks])
+
+parseDefinitionList :: PandocMonad m => ManParser m Blocks
+parseDefinitionList = definitionList <$> many1 definitionListItem
+
+parseLink :: PandocMonad m => [Arg] -> ManParser m Inlines
+parseLink args = do
+  contents <- mconcat <$> many lineInl
+  ControlLine _ endargs _ <- mmacro "UE"
+  let url = case args of
+              [] -> ""
+              (x:_) -> linePartsToText x
+  return $ link url "" contents <>
+    case endargs of
+      []    -> mempty
+      (x:_) -> linePartsToInlines x
+
+parseEmailLink :: PandocMonad m => [Arg] -> ManParser m Inlines
+parseEmailLink args = do
+  contents <- mconcat <$> many lineInl
+  ControlLine _ endargs _ <- mmacro "ME"
+  let url = case args of
+              [] -> ""
+              (x:_) -> "mailto:" <> linePartsToText x
+  return $ link url "" contents <>
+    case endargs of
+      []    -> mempty
+      (x:_) -> linePartsToInlines x
+
+skipUnknownMacro :: PandocMonad m => ManParser m Blocks
+skipUnknownMacro = do
+  tok <- mmacroAny
+  case tok of
+    ControlLine mkind _ pos -> do
+      report $ SkippedContent ("." <> mkind) pos
+      return mempty
+    _                 -> Prelude.fail "the impossible happened"
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
@@ -1,2146 +1,2375 @@
-{-# LANGUAGE RelaxedPolyRec      #-}
-{-# LANGUAGE ScopedTypeVariables #-}
-
-{-
-Copyright (C) 2006-2017 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-2017 John MacFarlane
-   License     : GNU GPL, version 2 or above
-
-   Maintainer  : John MacFarlane <jgm@berkeley.edu>
-   Stability   : alpha
-   Portability : portable
-
-Conversion of markdown-formatted plain text to 'Pandoc' document.
--}
-module Text.Pandoc.Readers.Markdown ( readMarkdown ) where
-
-import Control.Monad
-import Control.Monad.Except (throwError)
-import Data.Char (isAlphaNum, isPunctuation, isSpace, toLower)
-import qualified Data.HashMap.Strict as H
-import Data.List (findIndex, intercalate, sortBy, transpose)
-import qualified Data.Map as M
-import Data.Maybe
-import Data.Monoid ((<>))
-import Data.Ord (comparing)
-import Data.Scientific (base10Exponent, coefficient)
-import qualified Data.Set as Set
-import Data.Text (Text)
-import qualified Data.Text as T
-import qualified Data.Vector as V
-import Data.Yaml (ParseException (..), YamlException (..), YamlMark (..))
-import qualified Data.Yaml as Yaml
-import System.FilePath (addExtension, takeExtension)
-import Text.HTML.TagSoup
-import Text.Pandoc.Builder (Blocks, Inlines)
-import qualified Text.Pandoc.Builder as B
-import Text.Pandoc.Class (PandocMonad (..), report)
-import Text.Pandoc.Definition
-import Text.Pandoc.Emoji (emojis)
-import Text.Pandoc.Error
-import Text.Pandoc.Logging
-import Text.Pandoc.Options
-import Text.Pandoc.Parsing hiding (tableWith)
-import Text.Pandoc.Readers.HTML (htmlInBalanced, htmlTag, isBlockTag,
-                                 isCommentTag, isInlineTag, isTextTag)
-import Text.Pandoc.Readers.LaTeX (applyMacros, rawLaTeXBlock, rawLaTeXInline)
-import Text.Pandoc.Shared
-import qualified Text.Pandoc.UTF8 as UTF8
-import Text.Pandoc.XML (fromEntities)
-
-type MarkdownParser m = ParserT [Char] ParserState m
-
--- | Read markdown from an input string and return a Pandoc document.
-readMarkdown :: PandocMonad m
-             => ReaderOptions -- ^ Reader options
-             -> Text      -- ^ String to parse (assuming @'\n'@ line endings)
-             -> m Pandoc
-readMarkdown opts s = do
-  parsed <- readWithM parseMarkdown def{ stateOptions = opts }
-               (T.unpack (crFilter s) ++ "\n\n")
-  case parsed of
-    Right result -> return result
-    Left e       -> throwError e
-
---
--- Constants and data structure definitions
---
-
-isBulletListMarker :: Char -> Bool
-isBulletListMarker '*' = True
-isBulletListMarker '+' = True
-isBulletListMarker '-' = True
-isBulletListMarker _   = False
-
-isHruleChar :: Char -> Bool
-isHruleChar '*' = True
-isHruleChar '-' = True
-isHruleChar '_' = True
-isHruleChar _   = False
-
-setextHChars :: String
-setextHChars = "=-"
-
-isBlank :: Char -> Bool
-isBlank ' '  = True
-isBlank '\t' = True
-isBlank '\n' = True
-isBlank _    = False
-
---
--- auxiliary functions
---
-
--- | Succeeds when we're in list context.
-inList :: PandocMonad m => MarkdownParser m ()
-inList = do
-  ctx <- stateParserContext <$> getState
-  guard (ctx == ListItemState)
-
-spnl :: PandocMonad m => ParserT [Char] st m ()
-spnl = try $ do
-  skipSpaces
-  optional newline
-  skipSpaces
-  notFollowedBy (char '\n')
-
-indentSpaces :: PandocMonad m => MarkdownParser m String
-indentSpaces = try $ do
-  tabStop <- getOption readerTabStop
-  count tabStop (char ' ') <|>
-    string "\t" <?> "indentation"
-
-nonindentSpaces :: PandocMonad m => MarkdownParser m String
-nonindentSpaces = do
-  n <- skipNonindentSpaces
-  return $ replicate n ' '
-
--- returns number of spaces parsed
-skipNonindentSpaces :: PandocMonad m => MarkdownParser m Int
-skipNonindentSpaces = do
-  tabStop <- getOption readerTabStop
-  gobbleAtMostSpaces (tabStop - 1) <* notFollowedBy spaceChar
-
-litChar :: PandocMonad m => MarkdownParser m Char
-litChar = escapedChar'
-       <|> characterReference
-       <|> noneOf "\n"
-       <|> try (newline >> notFollowedBy blankline >> return ' ')
-
--- | Parse a sequence of inline elements between square brackets,
--- including inlines between balanced pairs of square brackets.
-inlinesInBalancedBrackets :: PandocMonad m => MarkdownParser m (F Inlines)
-inlinesInBalancedBrackets = do
-  char '['
-  pos <- getPosition
-  (_, raw) <- withRaw $ charsInBalancedBrackets 1
-  guard $ not $ null raw
-  parseFromString' (setPosition pos >>
-                   trimInlinesF <$> inlines) (init raw)
-
-charsInBalancedBrackets :: PandocMonad m => Int -> MarkdownParser m ()
-charsInBalancedBrackets 0 = return ()
-charsInBalancedBrackets openBrackets =
-      (char '[' >> charsInBalancedBrackets (openBrackets + 1))
-  <|> (char ']' >> charsInBalancedBrackets (openBrackets - 1))
-  <|> ((  (() <$ code)
-     <|> (() <$ escapedChar')
-     <|> (newline >> notFollowedBy blankline)
-     <|> skipMany1 (noneOf "[]`\n\\")
-     <|> (() <$ count 1 (oneOf "`\\"))
-      ) >> charsInBalancedBrackets openBrackets)
-
---
--- document structure
---
-
-rawTitleBlockLine :: PandocMonad m => MarkdownParser m String
-rawTitleBlockLine = do
-  char '%'
-  skipSpaces
-  first <- anyLine
-  rest <- many $ try $ do spaceChar
-                          notFollowedBy blankline
-                          skipSpaces
-                          anyLine
-  return $ trim $ unlines (first:rest)
-
-titleLine :: PandocMonad m => MarkdownParser m (F Inlines)
-titleLine = try $ do
-  raw <- rawTitleBlockLine
-  res <- parseFromString' inlines raw
-  return $ trimInlinesF res
-
-authorsLine :: PandocMonad m => MarkdownParser m (F [Inlines])
-authorsLine = try $ do
-  raw <- rawTitleBlockLine
-  let sep = (char ';' <* spaces) <|> newline
-  let pAuthors = sepEndBy
-            (trimInlinesF . mconcat <$> many
-                 (try $ notFollowedBy sep >> inline))
-            sep
-  sequence <$> parseFromString' pAuthors raw
-
-dateLine :: PandocMonad m => MarkdownParser m (F Inlines)
-dateLine = try $ do
-  raw <- rawTitleBlockLine
-  res <- parseFromString' inlines raw
-  return $ trimInlinesF res
-
-titleBlock :: PandocMonad m => MarkdownParser m ()
-titleBlock = pandocTitleBlock <|> mmdTitleBlock
-
-pandocTitleBlock :: PandocMonad m => MarkdownParser m ()
-pandocTitleBlock = try $ do
-  guardEnabled Ext_pandoc_title_block
-  lookAhead (char '%')
-  title <- option mempty titleLine
-  author <- option (return []) authorsLine
-  date <- option mempty dateLine
-  optional blanklines
-  let meta' = do title' <- title
-                 author' <- author
-                 date' <- date
-                 return $
-                     (if B.isNull title' then id else B.setMeta "title" title')
-                   . (if null author' then id else B.setMeta "author" author')
-                   . (if B.isNull date' then id else B.setMeta "date" date')
-                   $ nullMeta
-  updateState $ \st -> st{ stateMeta' = stateMeta' st <> meta' }
-
-
-yamlMetaBlock :: PandocMonad m => MarkdownParser m (F Blocks)
-yamlMetaBlock = try $ do
-  guardEnabled Ext_yaml_metadata_block
-  pos <- getPosition
-  string "---"
-  blankline
-  notFollowedBy blankline  -- if --- is followed by a blank it's an HRULE
-  rawYamlLines <- manyTill anyLine stopLine
-  -- by including --- and ..., we allow yaml blocks with just comments:
-  let rawYaml = unlines ("---" : (rawYamlLines ++ ["..."]))
-  optional blanklines
-  case Yaml.decodeEither' $ UTF8.fromString rawYaml of
-       Right (Yaml.Object hashmap) -> do
-         let alist = H.toList hashmap
-         mapM_ (\(k, v) ->
-             if ignorable k
-                then return ()
-                else do
-                  v' <- yamlToMeta v
-                  let k' = T.unpack k
-                  updateState $ \st -> st{ stateMeta' =
-                     (do m <- stateMeta' st
-                         -- if there's already a value, leave it unchanged
-                         case lookupMeta k' m of
-                              Just _ -> return m
-                              Nothing -> do
-                                v'' <- v'
-                                return $ B.setMeta (T.unpack k) v'' m)}
-           ) alist
-       Right Yaml.Null -> return ()
-       Right _ -> do
-                   logMessage $
-                      CouldNotParseYamlMetadata "not an object"
-                      pos
-                   return ()
-       Left err' -> do
-                case err' of
-                   InvalidYaml (Just YamlParseException{
-                               yamlProblem = problem
-                             , yamlContext = _ctxt
-                             , yamlProblemMark = Yaml.YamlMark {
-                                   yamlLine = yline
-                                 , yamlColumn = ycol
-                             }}) ->
-                        logMessage $ CouldNotParseYamlMetadata
-                           problem (setSourceLine
-                           (setSourceColumn pos
-                              (sourceColumn pos + ycol))
-                           (sourceLine pos + 1 + yline))
-                   _ -> logMessage $ CouldNotParseYamlMetadata
-                           (show err') pos
-                return ()
-  return mempty
-
--- ignore fields ending with _
-ignorable :: Text -> Bool
-ignorable t = (T.pack "_") `T.isSuffixOf` t
-
-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)
-        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.
-
-yamlToMeta :: PandocMonad m
-           => Yaml.Value -> MarkdownParser m (F MetaValue)
-yamlToMeta (Yaml.String t) = toMetaValue t
-yamlToMeta (Yaml.Number n)
-  -- avoid decimal points for numbers that don't need them:
-  | base10Exponent n >= 0     = return $ return $ MetaString $ show
-                                $ coefficient n * (10 ^ base10Exponent n)
-  | otherwise                 = return $ return $ MetaString $ show n
-yamlToMeta (Yaml.Bool b) = return $ return $ MetaBool b
-yamlToMeta (Yaml.Array xs) = do
-  xs' <- mapM yamlToMeta (V.toList xs)
-  return $ do
-    xs'' <- sequence xs'
-    return $ B.toMetaValue xs''
-yamlToMeta (Yaml.Object o) = do
-  let alist = H.toList o
-  foldM (\m (k,v) ->
-           if ignorable k
-              then return m
-              else do
-                v' <- yamlToMeta v
-                return $ do
-                   MetaMap m' <- m
-                   v'' <- v'
-                   return (MetaMap $ M.insert (T.unpack k) v'' m'))
-        (return $ MetaMap M.empty)
-        alist
-yamlToMeta _ = return $ return $ MetaString ""
-
-stopLine :: PandocMonad m => MarkdownParser m ()
-stopLine = try $ (string "---" <|> string "...") >> blankline >> return ()
-
-mmdTitleBlock :: PandocMonad m => MarkdownParser m ()
-mmdTitleBlock = try $ do
-  guardEnabled Ext_mmd_title_block
-  firstPair <- kvPair False
-  restPairs <- many (kvPair True)
-  let kvPairs = firstPair : restPairs
-  blanklines
-  updateState $ \st -> st{ stateMeta' = stateMeta' st <>
-                             return (Meta $ M.fromList kvPairs) }
-
-kvPair :: PandocMonad m => Bool -> MarkdownParser m (String, MetaValue)
-kvPair allowEmpty = try $ do
-  key <- many1Till (alphaNum <|> oneOf "_- ") (char ':')
-  val <- trim <$> manyTill anyChar
-          (try $ newline >> lookAhead (blankline <|> nonspaceChar))
-  guard $ allowEmpty || not (null val)
-  let key' = concat $ words $ map toLower key
-  let val' = MetaBlocks $ B.toList $ B.plain $B.text val
-  return (key',val')
-
-parseMarkdown :: PandocMonad m => MarkdownParser m Pandoc
-parseMarkdown = do
-  optional titleBlock
-  blocks <- parseBlocks
-  st <- getState
-  -- check for notes with no corresponding note references
-  let notesUsed = stateNoteRefs st
-  let notesDefined = M.keys (stateNotes' st)
-  mapM_ (\n -> unless (n `Set.member` notesUsed) $
-                case M.lookup n (stateNotes' st) of
-                   Just (pos, _) -> report (NoteDefinedButNotUsed n pos)
-                   Nothing -> throwError $
-                     PandocShouldNeverHappenError "note not found")
-         notesDefined
-  let doc = runF (do Pandoc _ bs <- B.doc <$> blocks
-                     meta <- stateMeta' st
-                     return $ Pandoc meta bs) st
-  reportLogMessages
-  return doc
-
-referenceKey :: PandocMonad m => MarkdownParser m (F Blocks)
-referenceKey = try $ do
-  pos <- getPosition
-  skipNonindentSpaces
-  (_,raw) <- reference
-  char ':'
-  skipSpaces >> optional newline >> skipSpaces >> notFollowedBy (char '[')
-  let sourceURL = fmap unwords $ many $ try $ do
-                    skipMany spaceChar
-                    notFollowedBy' referenceTitle
-                    notFollowedBy' $ guardEnabled Ext_link_attributes >> attributes
-                    notFollowedBy' (() <$ reference)
-                    many1 $ notFollowedBy space >> litChar
-  let betweenAngles = try $ char '<' >> manyTill litChar (char '>')
-  src <- try betweenAngles <|> sourceURL
-  tit <- option "" referenceTitle
-  attr   <- option nullAttr $ try $
-              do guardEnabled Ext_link_attributes
-                 skipSpaces >> optional newline >> skipSpaces
-                 attributes
-  addKvs <- option [] $ guardEnabled Ext_mmd_link_attributes
-                          >> many (try $ spnl >> keyValAttr)
-  blanklines
-  let attr'  = extractIdClass $ foldl (\x f -> f x) attr addKvs
-      target = (escapeURI $ trimr src, tit)
-  st <- getState
-  let oldkeys = stateKeys st
-  let key = toKey raw
-  case M.lookup key oldkeys of
-    Just (t,a) | not (t == target && a == attr') ->
-      -- We don't warn on two duplicate keys if the targets are also
-      -- the same. This can happen naturally with --reference-location=block
-      -- or section. See #3701.
-      logMessage $ DuplicateLinkReference raw pos
-    _ -> return ()
-  updateState $ \s -> s { stateKeys = M.insert key (target, attr') oldkeys }
-  return $ return mempty
-
-referenceTitle :: PandocMonad m => MarkdownParser m String
-referenceTitle = try $ do
-  skipSpaces >> optional newline >> skipSpaces
-  quotedTitle '"' <|> quotedTitle '\'' <|> charsInBalanced '(' ')' litChar
-
--- A link title in quotes
-quotedTitle :: PandocMonad m => Char -> MarkdownParser m String
-quotedTitle c = try $ do
-  char c
-  notFollowedBy spaces
-  let pEnder = try $ char c >> notFollowedBy (satisfy isAlphaNum)
-  let regChunk = many1 (noneOf ['\\','\n','&',c]) <|> count 1 litChar
-  let nestedChunk = (\x -> [c] ++ x ++ [c]) <$> quotedTitle c
-  unwords . words . concat <$> manyTill (nestedChunk <|> regChunk) pEnder
-
--- | PHP Markdown Extra style abbreviation key.  Currently
--- we just skip them, since Pandoc doesn't have an element for
--- an abbreviation.
-abbrevKey :: PandocMonad m => MarkdownParser m (F Blocks)
-abbrevKey = do
-  guardEnabled Ext_abbreviations
-  try $ do
-    char '*'
-    reference
-    char ':'
-    skipMany (satisfy (/= '\n'))
-    blanklines
-    return $ return mempty
-
-noteMarker :: PandocMonad m => MarkdownParser m String
-noteMarker = string "[^" >> many1Till (satisfy $ not . isBlank) (char ']')
-
-rawLine :: PandocMonad m => MarkdownParser m String
-rawLine = try $ do
-  notFollowedBy blankline
-  notFollowedBy' $ try $ skipNonindentSpaces >> noteMarker
-  optional indentSpaces
-  anyLine
-
-rawLines :: PandocMonad m => MarkdownParser m String
-rawLines = do
-  first <- anyLine
-  rest <- many rawLine
-  return $ unlines (first:rest)
-
-noteBlock :: PandocMonad m => MarkdownParser m (F Blocks)
-noteBlock = try $ do
-  pos <- getPosition
-  skipNonindentSpaces
-  ref <- noteMarker
-  char ':'
-  optional blankline
-  optional indentSpaces
-  first <- rawLines
-  rest <- many $ try $ blanklines >> indentSpaces >> rawLines
-  let raw = unlines (first:rest) ++ "\n"
-  optional blanklines
-  parsed <- parseFromString' parseBlocks raw
-  oldnotes <- stateNotes' <$> getState
-  case M.lookup ref oldnotes of
-    Just _  -> logMessage $ DuplicateNoteReference ref pos
-    Nothing -> return ()
-  updateState $ \s -> s { stateNotes' = M.insert ref (pos, parsed) oldnotes }
-  return mempty
-
---
--- parsing blocks
---
-
-parseBlocks :: PandocMonad m => MarkdownParser m (F Blocks)
-parseBlocks = mconcat <$> manyTill block eof
-
-block :: PandocMonad m => MarkdownParser m (F Blocks)
-block = do
-  res <- choice [ mempty <$ blanklines
-               , codeBlockFenced
-               , yamlMetaBlock
-               -- note: bulletList needs to be before header because of
-               -- the possibility of empty list items: -
-               , bulletList
-               , header
-               , lhsCodeBlock
-               , divHtml
-               , divFenced
-               , htmlBlock
-               , table
-               , codeBlockIndented
-               , rawTeXBlock
-               , lineBlock
-               , blockQuote
-               , hrule
-               , orderedList
-               , definitionList
-               , noteBlock
-               , referenceKey
-               , abbrevKey
-               , para
-               , plain
-               ] <?> "block"
-  trace (take 60 $ show $ B.toList $ runF res defaultParserState)
-  return res
-
---
--- header blocks
---
-
-header :: PandocMonad m => MarkdownParser m (F Blocks)
-header = setextHeader <|> atxHeader <?> "header"
-
-atxChar :: PandocMonad m => MarkdownParser m Char
-atxChar = do
-  exts <- getOption readerExtensions
-  return $ if extensionEnabled Ext_literate_haskell exts
-              then '='
-              else '#'
-
-atxHeader :: PandocMonad m => MarkdownParser m (F Blocks)
-atxHeader = try $ do
-  level <- fmap length (atxChar >>= many1 . char)
-  notFollowedBy $ guardEnabled Ext_fancy_lists >>
-                  (char '.' <|> char ')') -- this would be a list
-  guardDisabled Ext_space_in_atx_header <|> notFollowedBy nonspaceChar
-  skipSpaces
-  (text, raw) <- withRaw $
-          trimInlinesF . mconcat <$> many (notFollowedBy atxClosing >> inline)
-  attr <- atxClosing
-  attr' <- registerHeader attr (runF text defaultParserState)
-  guardDisabled Ext_implicit_header_references
-    <|> registerImplicitHeader raw attr'
-  return $ B.headerWith attr' level <$> text
-
-atxClosing :: PandocMonad m => MarkdownParser m Attr
-atxClosing = try $ do
-  attr' <- option nullAttr
-             (guardEnabled Ext_mmd_header_identifiers >> mmdHeaderIdentifier)
-  skipMany . char =<< atxChar
-  skipSpaces
-  attr <- option attr'
-             (guardEnabled Ext_header_attributes >> attributes)
-  blanklines
-  return attr
-
-setextHeaderEnd :: PandocMonad m => MarkdownParser m Attr
-setextHeaderEnd = try $ do
-  attr <- option nullAttr
-          $ (guardEnabled Ext_mmd_header_identifiers >> mmdHeaderIdentifier)
-           <|> (guardEnabled Ext_header_attributes >> attributes)
-  blanklines
-  return attr
-
-mmdHeaderIdentifier :: PandocMonad m => MarkdownParser m Attr
-mmdHeaderIdentifier = do
-  (_, raw) <- reference
-  let raw' = trim $ stripFirstAndLast raw
-  let ident = concat $ words $ map toLower raw'
-  let attr = (ident, [], [])
-  guardDisabled Ext_implicit_header_references
-    <|> registerImplicitHeader raw' attr
-  skipSpaces
-  return attr
-
-setextHeader :: PandocMonad m => MarkdownParser m (F Blocks)
-setextHeader = try $ do
-  -- This lookahead prevents us from wasting time parsing Inlines
-  -- unless necessary -- it gives a significant performance boost.
-  lookAhead $ anyLine >> many1 (oneOf setextHChars) >> blankline
-  skipSpaces
-  (text, raw) <- withRaw $
-       trimInlinesF . mconcat <$> many1 (notFollowedBy setextHeaderEnd >> inline)
-  attr <- setextHeaderEnd
-  underlineChar <- oneOf setextHChars
-  many (char underlineChar)
-  blanklines
-  let level = fromMaybe 0 (findIndex (== underlineChar) setextHChars) + 1
-  attr' <- registerHeader attr (runF text defaultParserState)
-  guardDisabled Ext_implicit_header_references
-    <|> registerImplicitHeader raw attr'
-  return $ B.headerWith attr' level <$> text
-
-registerImplicitHeader :: PandocMonad m => String -> Attr -> MarkdownParser m ()
-registerImplicitHeader raw attr@(ident, _, _) = do
-  let key = toKey $ "[" ++ raw ++ "]"
-  updateState (\s -> s { stateHeaderKeys =
-                         M.insert key (('#':ident,""), attr) (stateHeaderKeys s) })
-
---
--- hrule block
---
-
-hrule :: PandocMonad m => ParserT [Char] st m (F Blocks)
-hrule = try $ do
-  skipSpaces
-  start <- satisfy isHruleChar
-  count 2 (skipSpaces >> char start)
-  skipMany (spaceChar <|> char start)
-  newline
-  optional blanklines
-  return $ return B.horizontalRule
-
---
--- code blocks
---
-
-indentedLine :: PandocMonad m => MarkdownParser m String
-indentedLine = indentSpaces >> anyLineNewline
-
-blockDelimiter :: PandocMonad m
-               => (Char -> Bool)
-               -> Maybe Int
-               -> ParserT [Char] ParserState m Int
-blockDelimiter f len = try $ do
-  skipNonindentSpaces
-  c <- lookAhead (satisfy f)
-  case len of
-      Just l  -> count l (char c) >> many (char c) >> return l
-      Nothing -> fmap ((+ 3) . length) (count 3 (char c) >> many (char c))
-
-attributes :: PandocMonad m => MarkdownParser m Attr
-attributes = try $ do
-  char '{'
-  spnl
-  attrs <- many (attribute <* spnl)
-  char '}'
-  return $ foldl (\x f -> f x) nullAttr attrs
-
-attribute :: PandocMonad m => MarkdownParser m (Attr -> Attr)
-attribute = identifierAttr <|> classAttr <|> keyValAttr <|> specialAttr
-
-identifier :: PandocMonad m => MarkdownParser m String
-identifier = do
-  first <- letter
-  rest <- many $ alphaNum <|> oneOf "-_:."
-  return (first:rest)
-
-identifierAttr :: PandocMonad m => MarkdownParser m (Attr -> Attr)
-identifierAttr = try $ do
-  char '#'
-  result <- identifier
-  return $ \(_,cs,kvs) -> (result,cs,kvs)
-
-classAttr :: PandocMonad m => MarkdownParser m (Attr -> Attr)
-classAttr = try $ do
-  char '.'
-  result <- identifier
-  return $ \(id',cs,kvs) -> (id',cs ++ [result],kvs)
-
-keyValAttr :: PandocMonad m => MarkdownParser m (Attr -> Attr)
-keyValAttr = try $ do
-  key <- identifier
-  char '='
-  val <- enclosed (char '"') (char '"') litChar
-     <|> enclosed (char '\'') (char '\'') litChar
-     <|> many (escapedChar' <|> noneOf " \t\n\r}")
-  return $ \(id',cs,kvs) ->
-    case key of
-         "id"    -> (val,cs,kvs)
-         "class" -> (id',cs ++ words val,kvs)
-         _       -> (id',cs,kvs ++ [(key,val)])
-
-specialAttr :: PandocMonad m => MarkdownParser m (Attr -> Attr)
-specialAttr = do
-  char '-'
-  return $ \(id',cs,kvs) -> (id',cs ++ ["unnumbered"],kvs)
-
-rawAttribute :: PandocMonad m => MarkdownParser m String
-rawAttribute = do
-  char '{'
-  skipMany spaceChar
-  char '='
-  format <- many1 $ satisfy (\c -> isAlphaNum c || c `elem` "-_")
-  skipMany spaceChar
-  char '}'
-  return format
-
-codeBlockFenced :: PandocMonad m => MarkdownParser m (F Blocks)
-codeBlockFenced = try $ do
-  indentchars <- nonindentSpaces
-  let indentLevel = length indentchars
-  c <- try (guardEnabled Ext_fenced_code_blocks >> lookAhead (char '~'))
-     <|> (guardEnabled Ext_backtick_code_blocks >> lookAhead (char '`'))
-  size <- blockDelimiter (== c) Nothing
-  skipMany spaceChar
-  rawattr <-
-     (Left <$> try (guardEnabled Ext_raw_attribute >> rawAttribute))
-    <|>
-     (Right <$> option ("",[],[])
-         (try (guardEnabled Ext_fenced_code_attributes >> attributes)
-          <|> ((\x -> ("",[toLanguageId x],[])) <$> many1 nonspaceChar)))
-  blankline
-  contents <- intercalate "\n" <$>
-                 manyTill (gobbleAtMostSpaces indentLevel >> anyLine)
-                          (blockDelimiter (== c) (Just size))
-  blanklines
-  return $ return $
-    case rawattr of
-          Left syn   -> B.rawBlock syn contents
-          Right attr -> B.codeBlockWith attr contents
-
--- correctly handle github language identifiers
-toLanguageId :: String -> String
-toLanguageId = map toLower . go
-  where go "c++"         = "cpp"
-        go "objective-c" = "objectivec"
-        go x             = x
-
-codeBlockIndented :: PandocMonad m => MarkdownParser m (F Blocks)
-codeBlockIndented = do
-  contents <- many1 (indentedLine <|>
-                     try (do b <- blanklines
-                             l <- indentedLine
-                             return $ b ++ l))
-  optional blanklines
-  classes <- getOption readerIndentedCodeClasses
-  return $ return $ B.codeBlockWith ("", classes, []) $
-           stripTrailingNewlines $ concat contents
-
-lhsCodeBlock :: PandocMonad m => MarkdownParser m (F Blocks)
-lhsCodeBlock = do
-  guardEnabled Ext_literate_haskell
-  (return . B.codeBlockWith ("",["sourceCode","literate","haskell"],[]) <$>
-          (lhsCodeBlockBird <|> lhsCodeBlockLaTeX))
-    <|> (return . B.codeBlockWith ("",["sourceCode","haskell"],[]) <$>
-          lhsCodeBlockInverseBird)
-
-lhsCodeBlockLaTeX :: PandocMonad m => MarkdownParser m String
-lhsCodeBlockLaTeX = try $ do
-  string "\\begin{code}"
-  manyTill spaceChar newline
-  contents <- many1Till anyChar (try $ string "\\end{code}")
-  blanklines
-  return $ stripTrailingNewlines contents
-
-lhsCodeBlockBird :: PandocMonad m => MarkdownParser m String
-lhsCodeBlockBird = lhsCodeBlockBirdWith '>'
-
-lhsCodeBlockInverseBird :: PandocMonad m => MarkdownParser m String
-lhsCodeBlockInverseBird = lhsCodeBlockBirdWith '<'
-
-lhsCodeBlockBirdWith :: PandocMonad m => Char -> MarkdownParser m String
-lhsCodeBlockBirdWith c = try $ do
-  pos <- getPosition
-  when (sourceColumn pos /= 1) $ fail "Not in first column"
-  lns <- many1 $ birdTrackLine c
-  -- if (as is normal) there is always a space after >, drop it
-  let lns' = if all (\ln -> null ln || take 1 ln == " ") lns
-                then map (drop 1) lns
-                else lns
-  blanklines
-  return $ intercalate "\n" lns'
-
-birdTrackLine :: PandocMonad m => Char -> ParserT [Char] st m String
-birdTrackLine c = try $ do
-  char c
-  -- allow html tags on left margin:
-  when (c == '<') $ notFollowedBy letter
-  anyLine
-
---
--- block quotes
---
-
-emailBlockQuoteStart :: PandocMonad m => MarkdownParser m Char
-emailBlockQuoteStart = try $ skipNonindentSpaces >> char '>' <* optional (char ' ')
-
-emailBlockQuote :: PandocMonad m => MarkdownParser m [String]
-emailBlockQuote = try $ do
-  emailBlockQuoteStart
-  let emailLine = many $ nonEndline <|> try
-                         (endline >> notFollowedBy emailBlockQuoteStart >>
-                         return '\n')
-  let emailSep = try (newline >> emailBlockQuoteStart)
-  first <- emailLine
-  rest <- many $ try $ emailSep >> emailLine
-  let raw = first:rest
-  newline <|> (eof >> return '\n')
-  optional blanklines
-  return raw
-
-blockQuote :: PandocMonad m => MarkdownParser m (F Blocks)
-blockQuote = do
-  raw <- emailBlockQuote
-  -- parse the extracted block, which may contain various block elements:
-  contents <- parseFromString' parseBlocks $ intercalate "\n" raw ++ "\n\n"
-  return $ B.blockQuote <$> contents
-
---
--- list blocks
---
-
-bulletListStart :: PandocMonad m => MarkdownParser m ()
-bulletListStart = try $ do
-  optional newline -- if preceded by a Plain block in a list context
-  skipNonindentSpaces
-  notFollowedBy' (() <$ hrule)     -- because hrules start out just like lists
-  satisfy isBulletListMarker
-  gobbleSpaces 1 <|> () <$ lookAhead newline
-  try (gobbleAtMostSpaces 3 >> notFollowedBy spaceChar) <|> return ()
-
-orderedListStart :: PandocMonad m
-                 => Maybe (ListNumberStyle, ListNumberDelim)
-                 -> MarkdownParser m (Int, ListNumberStyle, ListNumberDelim)
-orderedListStart mbstydelim = try $ do
-  optional newline -- if preceded by a Plain block in a list context
-  skipNonindentSpaces
-  notFollowedBy $ string "p." >> spaceChar >> digit  -- page number
-  (do guardDisabled Ext_fancy_lists
-      start <- many1 digit >>= safeRead
-      char '.'
-      gobbleSpaces 1 <|> () <$ lookAhead newline
-      optional $ try (gobbleAtMostSpaces 3 >> notFollowedBy spaceChar)
-      return (start, DefaultStyle, DefaultDelim))
-   <|>
-   (do (num, style, delim) <- maybe
-          anyOrderedListMarker
-          (\(sty,delim) -> (\start -> (start,sty,delim)) <$>
-               orderedListMarker sty delim)
-          mbstydelim
-       gobbleSpaces 1 <|> () <$ lookAhead newline
-       -- if it could be an abbreviated first name,
-       -- insist on more than one space
-       when (delim == Period && (style == UpperAlpha ||
-            (style == UpperRoman &&
-             num `elem` [1, 5, 10, 50, 100, 500, 1000]))) $
-              () <$ lookAhead (newline <|> spaceChar)
-       optional $ try (gobbleAtMostSpaces 3 >> notFollowedBy spaceChar)
-       return (num, style, delim))
-
-listStart :: PandocMonad m => MarkdownParser m ()
-listStart = bulletListStart <|> (Control.Monad.void (orderedListStart Nothing))
-
-listLine :: PandocMonad m => Int -> MarkdownParser m String
-listLine continuationIndent = try $ do
-  notFollowedBy' (do gobbleSpaces continuationIndent
-                     skipMany spaceChar
-                     listStart)
-  notFollowedByHtmlCloser
-  notFollowedByDivCloser
-  optional (() <$ gobbleSpaces continuationIndent)
-  listLineCommon
-
-listLineCommon :: PandocMonad m => MarkdownParser m String
-listLineCommon = concat <$> manyTill
-              (  many1 (satisfy $ \c -> c /= '\n' && c /= '<')
-             <|> fmap snd (htmlTag isCommentTag)
-             <|> count 1 anyChar
-              ) newline
-
--- parse raw text for one list item, excluding start marker and continuations
-rawListItem :: PandocMonad m
-            => Bool -- four space rule
-            -> MarkdownParser m a
-            -> MarkdownParser m (String, Int)
-rawListItem fourSpaceRule start = try $ do
-  pos1 <- getPosition
-  start
-  pos2 <- getPosition
-  let continuationIndent = if fourSpaceRule
-                              then 4
-                              else (sourceColumn pos2 - sourceColumn pos1)
-  first <- listLineCommon
-  rest <- many (do notFollowedBy listStart
-                   notFollowedBy (() <$ codeBlockFenced)
-                   notFollowedBy blankline
-                   listLine continuationIndent)
-  blanks <- many blankline
-  let result = unlines (first:rest) ++ blanks
-  return (result, continuationIndent)
-
--- continuation of a list item - indented and separated by blankline
--- or (in compact lists) endline.
--- note: nested lists are parsed as continuations
-listContinuation :: PandocMonad m => Int -> MarkdownParser m String
-listContinuation continuationIndent = try $ do
-  x <- try $ do
-         notFollowedBy blankline
-         notFollowedByHtmlCloser
-         notFollowedByDivCloser
-         gobbleSpaces continuationIndent
-         anyLineNewline
-  xs <- many $ try $ do
-         notFollowedBy blankline
-         notFollowedByHtmlCloser
-         notFollowedByDivCloser
-         gobbleSpaces continuationIndent <|> notFollowedBy' listStart
-         anyLineNewline
-  blanks <- many blankline
-  return $ concat (x:xs) ++ blanks
-
-notFollowedByDivCloser :: PandocMonad m => MarkdownParser m ()
-notFollowedByDivCloser = do
-  guardDisabled Ext_fenced_divs <|>
-    do divLevel <- stateFencedDivLevel <$> getState
-       guard (divLevel < 1) <|> notFollowedBy divFenceEnd
-
-notFollowedByHtmlCloser :: PandocMonad m => MarkdownParser m ()
-notFollowedByHtmlCloser = do
-  inHtmlBlock <- stateInHtmlBlock <$> getState
-  case inHtmlBlock of
-        Just t  -> notFollowedBy' $ htmlTag (~== TagClose t)
-        Nothing -> return ()
-
-listItem :: PandocMonad m
-         => Bool -- four-space rule
-         -> MarkdownParser m a
-         -> MarkdownParser m (F Blocks)
-listItem fourSpaceRule start = try $ do
-  (first, continuationIndent) <- rawListItem fourSpaceRule start
-  continuations <- many (listContinuation continuationIndent)
-  -- parsing with ListItemState forces markers at beginning of lines to
-  -- count as list item markers, even if not separated by blank space.
-  -- see definition of "endline"
-  state <- getState
-  let oldContext = stateParserContext state
-  setState $ state {stateParserContext = ListItemState}
-  -- parse the extracted block, which may contain various block elements:
-  let raw = concat (first:continuations)
-  contents <- parseFromString' parseBlocks raw
-  updateState (\st -> st {stateParserContext = oldContext})
-  return contents
-
-orderedList :: PandocMonad m => MarkdownParser m (F Blocks)
-orderedList = try $ do
-  (start, style, delim) <- lookAhead (orderedListStart Nothing)
-  unless (style `elem` [DefaultStyle, Decimal, Example] &&
-          delim `elem` [DefaultDelim, Period]) $
-    guardEnabled Ext_fancy_lists
-  when (style == Example) $ guardEnabled Ext_example_lists
-  fourSpaceRule <- (True <$ guardEnabled Ext_four_space_rule)
-               <|> return (style == Example)
-  items <- fmap sequence $ many1 $ listItem fourSpaceRule
-                 (orderedListStart (Just (style, delim)))
-  start' <- (start <$ guardEnabled Ext_startnum) <|> return 1
-  return $ B.orderedListWith (start', style, delim) <$> fmap compactify items
-
-bulletList :: PandocMonad m => MarkdownParser m (F Blocks)
-bulletList = do
-  fourSpaceRule <- (True <$ guardEnabled Ext_four_space_rule)
-               <|> return False
-  items <- fmap sequence $ many1 $ listItem fourSpaceRule bulletListStart
-  return $ B.bulletList <$> fmap compactify items
-
--- definition lists
-
-defListMarker :: PandocMonad m => MarkdownParser m ()
-defListMarker = do
-  sps <- nonindentSpaces
-  char ':' <|> char '~'
-  tabStop <- getOption readerTabStop
-  let remaining = tabStop - (length sps + 1)
-  if remaining > 0
-     then try (count remaining (char ' ')) <|> string "\t" <|> many1 spaceChar
-     else mzero
-  return ()
-
-definitionListItem :: PandocMonad m => Bool -> MarkdownParser m (F (Inlines, [Blocks]))
-definitionListItem compact = try $ do
-  rawLine' <- anyLine
-  raw <- many1 $ defRawBlock compact
-  term <- parseFromString' (trimInlinesF <$> inlines) rawLine'
-  contents <- mapM (parseFromString' parseBlocks . (++"\n")) raw
-  optional blanklines
-  return $ liftM2 (,) term (sequence contents)
-
-defRawBlock :: PandocMonad m => Bool -> MarkdownParser m String
-defRawBlock compact = try $ do
-  hasBlank <- option False $ blankline >> return True
-  defListMarker
-  firstline <- anyLineNewline
-  let dline = try
-               ( do notFollowedBy blankline
-                    notFollowedByHtmlCloser
-                    notFollowedByDivCloser
-                    if compact -- laziness not compatible with compact
-                       then () <$ indentSpaces
-                       else (() <$ indentSpaces)
-                             <|> notFollowedBy defListMarker
-                    anyLine )
-  rawlines <- many dline
-  cont <- fmap concat $ many $ try $ do
-            trailing <- option "" blanklines
-            ln <- indentSpaces >> notFollowedBy blankline >> anyLine
-            lns <- many dline
-            return $ trailing ++ unlines (ln:lns)
-  return $ trimr (firstline ++ unlines rawlines ++ cont) ++
-            if hasBlank || not (null cont) then "\n\n" else ""
-
-definitionList :: PandocMonad m => MarkdownParser m (F Blocks)
-definitionList = try $ do
-  lookAhead (anyLine >>
-             optional (blankline >> notFollowedBy (Control.Monad.void table)) >>
-             -- don't capture table caption as def list!
-             defListMarker)
-  compactDefinitionList <|> normalDefinitionList
-
-compactDefinitionList :: PandocMonad m => MarkdownParser m (F Blocks)
-compactDefinitionList = do
-  guardEnabled Ext_compact_definition_lists
-  items <- fmap sequence $ many1 $ definitionListItem True
-  return $ B.definitionList <$> fmap compactifyDL items
-
-normalDefinitionList :: PandocMonad m => MarkdownParser m (F Blocks)
-normalDefinitionList = do
-  guardEnabled Ext_definition_lists
-  items <- fmap sequence $ many1 $ definitionListItem False
-  return $ B.definitionList <$> items
-
---
--- paragraph block
---
-
-para :: PandocMonad m => MarkdownParser m (F Blocks)
-para = try $ do
-  exts <- getOption readerExtensions
-  result <- trimInlinesF <$> inlines1
-  option (B.plain <$> result)
-    $ try $ do
-            newline
-            (blanklines >> return mempty)
-              <|> (guardDisabled Ext_blank_before_blockquote >> () <$ lookAhead blockQuote)
-              <|> (guardEnabled Ext_backtick_code_blocks >> () <$ lookAhead codeBlockFenced)
-              <|> (guardDisabled Ext_blank_before_header >> () <$ lookAhead header)
-              <|> (guardEnabled Ext_lists_without_preceding_blankline >>
-                       -- Avoid creating a paragraph in a nested list.
-                       notFollowedBy' inList >>
-                       () <$ lookAhead listStart)
-              <|> do guardEnabled Ext_native_divs
-                     inHtmlBlock <- stateInHtmlBlock <$> getState
-                     case inHtmlBlock of
-                          Just "div" -> () <$
-                                       lookAhead (htmlTag (~== TagClose "div"))
-                          _          -> mzero
-              <|> do guardEnabled Ext_fenced_divs
-                     divLevel <- stateFencedDivLevel <$> getState
-                     if divLevel > 0
-                        then lookAhead divFenceEnd
-                        else mzero
-            return $ do
-              result' <- result
-              case B.toList result' of
-                   [Image attr alt (src,tit)]
-                     | not (null alt) &&
-                       Ext_implicit_figures `extensionEnabled` exts ->
-                        -- the fig: at beginning of title indicates a figure
-                        return $ B.para $ B.singleton
-                               $ Image attr alt (src,'f':'i':'g':':':tit)
-                   _ -> return $ B.para result'
-
-plain :: PandocMonad m => MarkdownParser m (F Blocks)
-plain = fmap B.plain . trimInlinesF <$> inlines1
-
---
--- raw html
---
-
-htmlElement :: PandocMonad m => MarkdownParser m String
-htmlElement = rawVerbatimBlock
-          <|> strictHtmlBlock
-          <|> fmap snd (htmlTag isBlockTag)
-
-htmlBlock :: PandocMonad m => MarkdownParser m (F Blocks)
-htmlBlock = do
-  guardEnabled Ext_raw_html
-  try (do
-      (TagOpen t attrs) <- lookAhead $ fst <$> htmlTag isBlockTag
-      (guard (t `elem` ["pre","style","script"]) >>
-          (return . B.rawBlock "html") <$> rawVerbatimBlock)
-        <|> (do guardEnabled Ext_markdown_attribute
-                oldMarkdownAttribute <- stateMarkdownAttribute <$> getState
-                markdownAttribute <-
-                   case lookup "markdown" attrs of
-                        Just "0" -> False <$ updateState (\st -> st{
-                                       stateMarkdownAttribute = False })
-                        Just _   -> True <$ updateState (\st -> st{
-                                       stateMarkdownAttribute = True })
-                        Nothing  -> return oldMarkdownAttribute
-                res <- if markdownAttribute
-                          then rawHtmlBlocks
-                          else htmlBlock'
-                updateState $ \st -> st{ stateMarkdownAttribute =
-                                         oldMarkdownAttribute }
-                return res)
-        <|> (guardEnabled Ext_markdown_in_html_blocks >> rawHtmlBlocks))
-    <|> htmlBlock'
-
-htmlBlock' :: PandocMonad m => MarkdownParser m (F Blocks)
-htmlBlock' = try $ do
-    first <- htmlElement
-    skipMany spaceChar
-    optional blanklines
-    return $ if null first
-                then mempty
-                else return $ B.rawBlock "html" first
-
-strictHtmlBlock :: PandocMonad m => MarkdownParser m String
-strictHtmlBlock = htmlInBalanced (not . isInlineTag)
-
-rawVerbatimBlock :: PandocMonad m => MarkdownParser m String
-rawVerbatimBlock = htmlInBalanced isVerbTag
-  where isVerbTag (TagOpen "pre" _)    = True
-        isVerbTag (TagOpen "style" _)  = True
-        isVerbTag (TagOpen "script" _) = True
-        isVerbTag _                    = False
-
-rawTeXBlock :: PandocMonad m => MarkdownParser m (F Blocks)
-rawTeXBlock = do
-  guardEnabled Ext_raw_tex
-  result <- (B.rawBlock "context" . trim . concat <$>
-                many1 ((++) <$> (rawConTeXtEnvironment <|> conTeXtCommand)
-                            <*> (blanklines <|> many spaceChar)))
-          <|> (B.rawBlock "latex" . trim . concat <$>
-                many1 ((++) <$> rawLaTeXBlock
-                            <*> (blanklines <|> many spaceChar)))
-  return $ case B.toList result of
-                [RawBlock _ cs]
-                  | all (`elem` [' ','\t','\n']) cs -> return mempty
-                -- don't create a raw block for suppressed macro defs
-                _ -> return result
-
-conTeXtCommand :: PandocMonad m => MarkdownParser m String
-conTeXtCommand = oneOfStrings ["\\placeformula"]
-
-rawHtmlBlocks :: PandocMonad m => MarkdownParser m (F Blocks)
-rawHtmlBlocks = do
-  (TagOpen tagtype _, raw) <- htmlTag isBlockTag
-  -- we don't want '<td>    text' to be a code block:
-  skipMany spaceChar
-  indentlevel <- (blankline >> length <$> many (char ' ')) <|> return 0
-  -- try to find closing tag
-  -- we set stateInHtmlBlock so that closing tags that can be either block or
-  -- inline will not be parsed as inline tags
-  oldInHtmlBlock <- stateInHtmlBlock <$> getState
-  updateState $ \st -> st{ stateInHtmlBlock = Just tagtype }
-  let closer = htmlTag (\x -> x ~== TagClose tagtype)
-  let block' = do notFollowedBy' closer
-                  gobbleAtMostSpaces indentlevel
-                  block
-  contents <- mconcat <$> many block'
-  result <-
-    (closer >>= \(_, rawcloser) -> return (
-                return (B.rawBlock "html" $ stripMarkdownAttribute raw) <>
-                contents <>
-                return (B.rawBlock "html" rawcloser)))
-      <|> return (return (B.rawBlock "html" raw) <> contents)
-  updateState $ \st -> st{ stateInHtmlBlock = oldInHtmlBlock }
-  return result
-
--- remove markdown="1" attribute
-stripMarkdownAttribute :: String -> String
-stripMarkdownAttribute s = renderTags' $ map filterAttrib $ parseTags s
-  where filterAttrib (TagOpen t as) = TagOpen t
-                                        [(k,v) | (k,v) <- as, k /= "markdown"]
-        filterAttrib              x = x
-
---
--- line block
---
-
-lineBlock :: PandocMonad m => MarkdownParser m (F Blocks)
-lineBlock = try $ do
-  guardEnabled Ext_line_blocks
-  lines' <- lineBlockLines >>=
-            mapM (parseFromString' (trimInlinesF <$> inlines))
-  return $ B.lineBlock <$> sequence lines'
-
---
--- Tables
---
-
--- Parse a dashed line with optional trailing spaces; return its length
--- and the length including trailing space.
-dashedLine :: PandocMonad m
-           => Char
-           -> ParserT [Char] st m (Int, Int)
-dashedLine ch = do
-  dashes <- many1 (char ch)
-  sp     <- many spaceChar
-  let lengthDashes = length dashes
-      lengthSp     = length sp
-  return (lengthDashes, lengthDashes + lengthSp)
-
--- Parse a table header with dashed lines of '-' preceded by
--- one (or zero) line of text.
-simpleTableHeader :: PandocMonad m
-                  => Bool  -- ^ Headerless table
-                  -> MarkdownParser m (F [Blocks], [Alignment], [Int])
-simpleTableHeader headless = try $ do
-  rawContent  <- if headless
-                    then return ""
-                    else anyLine
-  initSp      <- nonindentSpaces
-  dashes      <- many1 (dashedLine '-')
-  newline
-  let (lengths, lines') = unzip dashes
-  let indices  = scanl (+) (length initSp) lines'
-  -- If no header, calculate alignment on basis of first row of text
-  rawHeads <- fmap (tail . splitStringByIndices (init indices)) $
-              if headless
-                 then lookAhead anyLine
-                 else return rawContent
-  let aligns   = zipWith alignType (map ((: [])) rawHeads) lengths
-  let rawHeads' = if headless
-                     then replicate (length dashes) ""
-                     else rawHeads
-  heads <- fmap sequence
-           $
-            mapM ((parseFromString' (mconcat <$> many plain)).trim) rawHeads'
-  return (heads, aligns, indices)
-
--- Returns an alignment type for a table, based on a list of strings
--- (the rows of the column header) and a number (the length of the
--- dashed line under the rows.
-alignType :: [String]
-          -> Int
-          -> Alignment
-alignType [] _ = AlignDefault
-alignType strLst len =
-  let nonempties = filter (not . null) $ map trimr strLst
-      (leftSpace, rightSpace) =
-           case sortBy (comparing length) nonempties of
-                 (x:_) -> (head x `elem` " \t", length x < len)
-                 []    -> (False, False)
-  in  case (leftSpace, rightSpace) of
-        (True,  False) -> AlignRight
-        (False, True)  -> AlignLeft
-        (True,  True)  -> AlignCenter
-        (False, False) -> AlignDefault
-
--- Parse a table footer - dashed lines followed by blank line.
-tableFooter :: PandocMonad m => MarkdownParser m String
-tableFooter = try $ skipNonindentSpaces >> many1 (dashedLine '-') >> blanklines
-
--- Parse a table separator - dashed line.
-tableSep :: PandocMonad m => MarkdownParser m Char
-tableSep = try $ skipNonindentSpaces >> many1 (dashedLine '-') >> char '\n'
-
--- Parse a raw line and split it into chunks by indices.
-rawTableLine :: PandocMonad m
-             => [Int]
-             -> MarkdownParser m [String]
-rawTableLine indices = do
-  notFollowedBy' (blanklines <|> tableFooter)
-  line <- many1Till anyChar newline
-  return $ map trim $ tail $
-           splitStringByIndices (init indices) line
-
--- Parse a table line and return a list of lists of blocks (columns).
-tableLine :: PandocMonad m
-          => [Int]
-          -> MarkdownParser m (F [Blocks])
-tableLine indices = rawTableLine indices >>=
-  fmap sequence . mapM (parseFromString' (mconcat <$> many plain))
-
--- Parse a multiline table row and return a list of blocks (columns).
-multilineRow :: PandocMonad m
-             => [Int]
-             -> MarkdownParser m (F [Blocks])
-multilineRow indices = do
-  colLines <- many1 (rawTableLine indices)
-  let cols = map unlines $ transpose colLines
-  fmap sequence $ mapM (parseFromString' (mconcat <$> many plain)) cols
-
--- Parses a table caption:  inlines beginning with 'Table:'
--- and followed by blank lines.
-tableCaption :: PandocMonad m => MarkdownParser m (F Inlines)
-tableCaption = try $ do
-  guardEnabled Ext_table_captions
-  skipNonindentSpaces
-  (string ":" <* notFollowedBy (satisfy isPunctuation)) <|> string "Table:"
-  trimInlinesF <$> inlines1 <* blanklines
-
--- Parse a simple table with '---' header and one line per row.
-simpleTable :: PandocMonad m
-            => Bool  -- ^ Headerless table
-            -> MarkdownParser m ([Alignment], [Double], F [Blocks], F [[Blocks]])
-simpleTable headless = do
-  (aligns, _widths, heads', lines') <-
-       tableWith (simpleTableHeader headless) tableLine
-              (return ())
-              (if headless then tableFooter else tableFooter <|> blanklines)
-  -- Simple tables get 0s for relative column widths (i.e., use default)
-  return (aligns, replicate (length aligns) 0, heads', lines')
-
--- Parse a multiline table:  starts with row of '-' on top, then header
--- (which may be multiline), then the rows,
--- which may be multiline, separated by blank lines, and
--- ending with a footer (dashed line followed by blank line).
-multilineTable :: PandocMonad m
-               => Bool -- ^ Headerless table
-               -> MarkdownParser m ([Alignment], [Double], F [Blocks], F [[Blocks]])
-multilineTable headless =
-  tableWith (multilineTableHeader headless) multilineRow blanklines tableFooter
-
-multilineTableHeader :: PandocMonad m
-                     => Bool -- ^ Headerless table
-                     -> MarkdownParser m (F [Blocks], [Alignment], [Int])
-multilineTableHeader headless = try $ do
-  unless headless $
-     tableSep >> notFollowedBy blankline
-  rawContent  <- if headless
-                    then return $ repeat ""
-                    else many1 $ notFollowedBy tableSep >> anyLine
-  initSp      <- nonindentSpaces
-  dashes      <- many1 (dashedLine '-')
-  newline
-  let (lengths, lines') = unzip dashes
-  let indices  = scanl (+) (length initSp) lines'
-  rawHeadsList <- if headless
-                     then fmap (map (:[]) . tail .
-                              splitStringByIndices (init indices)) $ lookAhead anyLine
-                     else return $ transpose $ map
-                           (tail . splitStringByIndices (init indices))
-                           rawContent
-  let aligns   = zipWith alignType rawHeadsList lengths
-  let rawHeads = if headless
-                    then replicate (length dashes) ""
-                    else map (unlines . map trim) rawHeadsList
-  heads <- fmap sequence $
-            mapM ((parseFromString' (mconcat <$> many plain)).trim) rawHeads
-  return (heads, aligns, indices)
-
--- Parse a grid table:  starts with row of '-' on top, then header
--- (which may be grid), then the rows,
--- which may be grid, separated by blank lines, and
--- ending with a footer (dashed line followed by blank line).
-gridTable :: PandocMonad m => Bool -- ^ Headerless table
-          -> MarkdownParser m ([Alignment], [Double], F [Blocks], F [[Blocks]])
-gridTable headless = gridTableWith' parseBlocks headless
-
-pipeBreak :: PandocMonad m => MarkdownParser m ([Alignment], [Int])
-pipeBreak = try $ do
-  nonindentSpaces
-  openPipe <- (True <$ char '|') <|> return False
-  first <- pipeTableHeaderPart
-  rest <- many $ sepPipe *> pipeTableHeaderPart
-  -- surrounding pipes needed for a one-column table:
-  guard $ not (null rest && not openPipe)
-  optional (char '|')
-  blankline
-  return $ unzip (first:rest)
-
-pipeTable :: PandocMonad m => MarkdownParser m ([Alignment], [Double], F [Blocks], F [[Blocks]])
-pipeTable = try $ do
-  nonindentSpaces
-  lookAhead nonspaceChar
-  (heads,(aligns, seplengths)) <- (,) <$> pipeTableRow <*> pipeBreak
-  let heads' = take (length aligns) <$> heads
-  lines' <- many pipeTableRow
-  let lines'' = map (take (length aligns) <$>) lines'
-  let maxlength = maximum $
-       map (\x -> length . stringify $ runF x def) (heads' : lines'')
-  numColumns <- getOption readerColumns
-  let widths = if maxlength > numColumns
-                  then map (\len ->
-                         fromIntegral len / fromIntegral (sum seplengths))
-                         seplengths
-                  else replicate (length aligns) 0.0
-  return (aligns, widths, heads', sequence lines'')
-
-sepPipe :: PandocMonad m => MarkdownParser m ()
-sepPipe = try $ do
-  char '|' <|> char '+'
-  notFollowedBy blankline
-
--- parse a row, also returning probable alignments for org-table cells
-pipeTableRow :: PandocMonad m => MarkdownParser m (F [Blocks])
-pipeTableRow = try $ do
-  scanForPipe
-  skipMany spaceChar
-  openPipe <- (True <$ char '|') <|> return False
-  -- split into cells
-  let chunk = void (code <|> math <|> rawHtmlInline <|> escapedChar <|> rawLaTeXInline')
-       <|> void (noneOf "|\n\r")
-  let cellContents = ((trim . snd) <$> withRaw (many chunk)) >>=
-        parseFromString' pipeTableCell
-  cells <- cellContents `sepEndBy1` char '|'
-  -- surrounding pipes needed for a one-column table:
-  guard $ not (length cells == 1 && not openPipe)
-  blankline
-  return $ sequence cells
-
-pipeTableCell :: PandocMonad m => MarkdownParser m (F Blocks)
-pipeTableCell =
-  (do result <- inlines1
-      return $ B.plain <$> result)
-    <|> return mempty
-
-pipeTableHeaderPart :: PandocMonad m => ParserT [Char] st m (Alignment, Int)
-pipeTableHeaderPart = try $ do
-  skipMany spaceChar
-  left <- optionMaybe (char ':')
-  pipe <- many1 (char '-')
-  right <- optionMaybe (char ':')
-  skipMany spaceChar
-  let len = length pipe + maybe 0 (const 1) left + maybe 0 (const 1) right
-  return
-    ((case (left,right) of
-       (Nothing,Nothing) -> AlignDefault
-       (Just _,Nothing)  -> AlignLeft
-       (Nothing,Just _)  -> AlignRight
-       (Just _,Just _)   -> AlignCenter), len)
-
--- Succeed only if current line contains a pipe.
-scanForPipe :: PandocMonad m => ParserT [Char] st m ()
-scanForPipe = do
-  inp <- getInput
-  case break (\c -> c == '\n' || c == '|') inp of
-       (_,'|':_) -> return ()
-       _         -> mzero
-
--- | Parse a table using 'headerParser', 'rowParser',
--- 'lineParser', and 'footerParser'.  Variant of the version in
--- Text.Pandoc.Parsing.
-tableWith :: PandocMonad m
-          => MarkdownParser m (F [Blocks], [Alignment], [Int])
-          -> ([Int] -> MarkdownParser m (F [Blocks]))
-          -> MarkdownParser m sep
-          -> MarkdownParser m end
-          -> MarkdownParser m ([Alignment], [Double], F [Blocks], F [[Blocks]])
-tableWith headerParser rowParser lineParser footerParser = try $ do
-    (heads, aligns, indices) <- headerParser
-    lines' <- fmap sequence $ rowParser indices `sepEndBy1` lineParser
-    footerParser
-    numColumns <- getOption readerColumns
-    let widths = if null indices
-                    then replicate (length aligns) 0.0
-                    else widthsFromIndices numColumns indices
-    return (aligns, widths, heads, lines')
-
-table :: PandocMonad m => MarkdownParser m (F Blocks)
-table = try $ do
-  frontCaption <- option Nothing (Just <$> tableCaption)
-  (aligns, widths, heads, lns) <-
-         try (guardEnabled Ext_pipe_tables >> scanForPipe >> pipeTable) <|>
-         try (guardEnabled Ext_multiline_tables >>
-                multilineTable False) <|>
-         try (guardEnabled Ext_simple_tables >>
-                (simpleTable True <|> simpleTable False)) <|>
-         try (guardEnabled Ext_multiline_tables >>
-                multilineTable True) <|>
-         try (guardEnabled Ext_grid_tables >>
-                (gridTable False <|> gridTable True)) <?> "table"
-  optional blanklines
-  caption <- case frontCaption of
-                  Nothing -> option (return mempty) tableCaption
-                  Just c  -> return c
-  -- renormalize widths if greater than 100%:
-  let totalWidth = sum widths
-  let widths' = if totalWidth < 1
-                   then widths
-                   else map (/ totalWidth) widths
-  return $ do
-    caption' <- caption
-    heads' <- heads
-    lns' <- lns
-    return $ B.table caption' (zip aligns widths') heads' lns'
-
---
--- inline
---
-
-inlines :: PandocMonad m => MarkdownParser m (F Inlines)
-inlines = mconcat <$> many inline
-
-inlines1 :: PandocMonad m => MarkdownParser m (F Inlines)
-inlines1 = mconcat <$> many1 inline
-
-inline :: PandocMonad m => MarkdownParser m (F Inlines)
-inline = choice [ whitespace
-                , bareURL
-                , str
-                , endline
-                , code
-                , strongOrEmph
-                , note
-                , cite
-                , bracketedSpan
-                , link
-                , image
-                , math
-                , strikeout
-                , subscript
-                , superscript
-                , inlineNote  -- after superscript because of ^[link](/foo)^
-                , autoLink
-                , spanHtml
-                , rawHtmlInline
-                , escapedNewline
-                , escapedChar
-                , rawLaTeXInline'
-                , exampleRef
-                , smart
-                , return . B.singleton <$> charRef
-                , emoji
-                , symbol
-                , ltSign
-                ] <?> "inline"
-
-escapedChar' :: PandocMonad m => MarkdownParser m Char
-escapedChar' = try $ do
-  char '\\'
-  (guardEnabled Ext_all_symbols_escapable >> satisfy (not . isAlphaNum))
-     <|> (guardEnabled Ext_angle_brackets_escapable >>
-            oneOf "\\`*_{}[]()>#+-.!~\"<>")
-     <|> oneOf "\\`*_{}[]()>#+-.!~\""
-
-escapedNewline :: PandocMonad m => MarkdownParser m (F Inlines)
-escapedNewline = try $ do
-  guardEnabled Ext_escaped_line_breaks
-  char '\\'
-  lookAhead (char '\n') -- don't consume the newline (see #3730)
-  return $ return B.linebreak
-
-escapedChar :: PandocMonad m => MarkdownParser m (F Inlines)
-escapedChar = do
-  result <- escapedChar'
-  case result of
-       ' ' -> return $ return $ B.str "\160" -- "\ " is a nonbreaking space
-       _   -> return $ return $ B.str [result]
-
-ltSign :: PandocMonad m => MarkdownParser m (F Inlines)
-ltSign = do
-  guardDisabled Ext_raw_html
-    <|> (notFollowedByHtmlCloser >> notFollowedBy' (htmlTag isBlockTag))
-  char '<'
-  return $ return $ B.str "<"
-
-exampleRef :: PandocMonad m => MarkdownParser m (F Inlines)
-exampleRef = try $ do
-  guardEnabled Ext_example_lists
-  char '@'
-  lab <- many1 (alphaNum <|> oneOf "-_")
-  return $ do
-    st <- askF
-    return $ case M.lookup lab (stateExamples st) of
-                  Just n  -> B.str (show n)
-                  Nothing -> B.str ('@':lab)
-
-symbol :: PandocMonad m => MarkdownParser m (F Inlines)
-symbol = do
-  result <- noneOf "<\\\n\t "
-         <|> try (do lookAhead $ char '\\'
-                     notFollowedBy' (() <$ rawTeXBlock)
-                     char '\\')
-  return $ return $ B.str [result]
-
--- parses inline code, between n `s and n `s
-code :: PandocMonad m => MarkdownParser m (F Inlines)
-code = try $ do
-  starts <- many1 (char '`')
-  skipSpaces
-  result <- (trim . concat) <$>
-            many1Till (many1 (noneOf "`\n") <|> many1 (char '`') <|>
-                       (char '\n' >> notFollowedBy' blankline >> return " "))
-                      (try (skipSpaces >> count (length starts) (char '`') >>
-                      notFollowedBy (char '`')))
-  rawattr <-
-     (Left <$> try (guardEnabled Ext_raw_attribute >> rawAttribute))
-    <|>
-     (Right <$> option ("",[],[])
-         (try (guardEnabled Ext_inline_code_attributes >> attributes)))
-  return $ return $
-    case rawattr of
-         Left syn   -> B.rawInline syn result
-         Right attr -> B.codeWith attr result
-
-math :: PandocMonad m => MarkdownParser m (F Inlines)
-math =  (return . B.displayMath <$> (mathDisplay >>= applyMacros))
-     <|> (return . B.math <$> (mathInline >>= applyMacros)) <+?>
-               (guardEnabled Ext_smart *> (return <$> apostrophe)
-                <* notFollowedBy (space <|> satisfy isPunctuation))
-
--- Parses material enclosed in *s, **s, _s, or __s.
--- Designed to avoid backtracking.
-enclosure :: PandocMonad m
-          => Char
-          -> MarkdownParser m (F Inlines)
-enclosure c = do
-  -- we can't start an enclosure with _ if after a string and
-  -- the intraword_underscores extension is enabled:
-  guardDisabled Ext_intraword_underscores
-    <|> guard (c == '*')
-    <|> (guard =<< notAfterString)
-  cs <- many1 (char c)
-  (return (B.str cs) <>) <$> whitespace
-    <|>
-        case length cs of
-             3 -> three c
-             2 -> two   c mempty
-             1 -> one   c mempty
-             _ -> return (return $ B.str cs)
-
-ender :: PandocMonad m => Char -> Int -> MarkdownParser m ()
-ender c n = try $ do
-  count n (char c)
-  guard (c == '*')
-    <|> guardDisabled Ext_intraword_underscores
-    <|> notFollowedBy alphaNum
-
--- Parse inlines til you hit one c or a sequence of two cs.
--- If one c, emit emph and then parse two.
--- If two cs, emit strong and then parse one.
--- Otherwise, emit ccc then the results.
-three :: PandocMonad m => Char -> MarkdownParser m (F Inlines)
-three c = do
-  contents <- mconcat <$> many (notFollowedBy (ender c 1) >> inline)
-  (ender c 3 >> updateLastStrPos >> return ((B.strong . B.emph) <$> contents))
-    <|> (ender c 2 >> updateLastStrPos >> one c (B.strong <$> contents))
-    <|> (ender c 1 >> updateLastStrPos >> two c (B.emph <$> contents))
-    <|> return (return (B.str [c,c,c]) <> contents)
-
--- Parse inlines til you hit two c's, and emit strong.
--- If you never do hit two cs, emit ** plus inlines parsed.
-two :: PandocMonad m => Char -> F Inlines -> MarkdownParser m (F Inlines)
-two c prefix' = do
-  contents <- mconcat <$> many (try $ notFollowedBy (ender c 2) >> inline)
-  (ender c 2 >> updateLastStrPos >>
-                return (B.strong <$> (prefix' <> contents)))
-    <|> return (return (B.str [c,c]) <> (prefix' <> contents))
-
--- Parse inlines til you hit a c, and emit emph.
--- If you never hit a c, emit * plus inlines parsed.
-one :: PandocMonad m => Char -> F Inlines -> MarkdownParser m (F Inlines)
-one c prefix' = do
-  contents <- mconcat <$> many (  (notFollowedBy (ender c 1) >> inline)
-                           <|> try (string [c,c] >>
-                                    notFollowedBy (ender c 1) >>
-                                    two c mempty) )
-  (ender c 1 >> updateLastStrPos >> return (B.emph <$> (prefix' <> contents)))
-    <|> return (return (B.str [c]) <> (prefix' <> contents))
-
-strongOrEmph :: PandocMonad m => MarkdownParser m (F Inlines)
-strongOrEmph =  enclosure '*' <|> enclosure '_'
-
--- | Parses a list of inlines between start and end delimiters.
-inlinesBetween :: PandocMonad m
-               => (Show b)
-               => MarkdownParser m a
-               -> MarkdownParser m b
-               -> MarkdownParser m (F Inlines)
-inlinesBetween start end =
-  (trimInlinesF . mconcat) <$> try (start >> many1Till inner end)
-    where inner      = innerSpace <|> (notFollowedBy' (() <$ whitespace) >> inline)
-          innerSpace = try $ whitespace <* notFollowedBy' end
-
-strikeout :: PandocMonad m => MarkdownParser m (F Inlines)
-strikeout = fmap B.strikeout <$>
- (guardEnabled Ext_strikeout >> inlinesBetween strikeStart strikeEnd)
-    where strikeStart = string "~~" >> lookAhead nonspaceChar
-                        >> notFollowedBy (char '~')
-          strikeEnd   = try $ string "~~"
-
-superscript :: PandocMonad m => MarkdownParser m (F Inlines)
-superscript = fmap B.superscript <$> try (do
-  guardEnabled Ext_superscript
-  char '^'
-  mconcat <$> many1Till (notFollowedBy spaceChar >> inline) (char '^'))
-
-subscript :: PandocMonad m => MarkdownParser m (F Inlines)
-subscript = fmap B.subscript <$> try (do
-  guardEnabled Ext_subscript
-  char '~'
-  mconcat <$> many1Till (notFollowedBy spaceChar >> inline) (char '~'))
-
-whitespace :: PandocMonad m => MarkdownParser m (F Inlines)
-whitespace = spaceChar >> return <$> (lb <|> regsp) <?> "whitespace"
-  where lb = spaceChar >> skipMany spaceChar >> option B.space (endline >> return B.linebreak)
-        regsp = skipMany spaceChar >> return B.space
-
-nonEndline :: PandocMonad m => ParserT [Char] st m Char
-nonEndline = satisfy (/='\n')
-
-str :: PandocMonad m => MarkdownParser m (F Inlines)
-str = do
-  result <- many1 (alphaNum <|> try (char '.' <* notFollowedBy (char '.')))
-  updateLastStrPos
-  (do guardEnabled Ext_smart
-      abbrevs <- getOption readerAbbreviations
-      if not (null result) && last result == '.' && result `Set.member` abbrevs
-         then try (do ils <- whitespace <|> endline
-                      lookAhead alphaNum
-                      return $ do
-                        ils' <- ils
-                        if ils' == B.space
-                           then return (B.str result <> B.str "\160")
-                           else -- linebreak or softbreak
-                                return (ils' <> B.str result <> B.str "\160"))
-                <|> return (return (B.str result))
-         else return (return (B.str result)))
-     <|> return (return (B.str result))
-
--- an endline character that can be treated as a space, not a structural break
-endline :: PandocMonad m => MarkdownParser m (F Inlines)
-endline = try $ do
-  newline
-  notFollowedBy blankline
-  -- parse potential list-starts differently if in a list:
-  notFollowedBy (inList >> listStart)
-  guardDisabled Ext_lists_without_preceding_blankline <|> notFollowedBy listStart
-  guardEnabled Ext_blank_before_blockquote <|> notFollowedBy emailBlockQuoteStart
-  guardEnabled Ext_blank_before_header <|> (notFollowedBy . char =<< atxChar) -- atx header
-  guardDisabled Ext_backtick_code_blocks <|>
-     notFollowedBy (() <$ (lookAhead (char '`') >> codeBlockFenced))
-  notFollowedByHtmlCloser
-  notFollowedByDivCloser
-  (eof >> return mempty)
-    <|> (guardEnabled Ext_hard_line_breaks >> return (return B.linebreak))
-    <|> (guardEnabled Ext_ignore_line_breaks >> return mempty)
-    <|> (skipMany spaceChar >> return (return B.softbreak))
-
---
--- links
---
-
--- a reference label for a link
-reference :: PandocMonad m => MarkdownParser m (F Inlines, String)
-reference = do
-  guardDisabled Ext_footnotes <|> notFollowedBy' (string "[^")
-  guardDisabled Ext_citations <|> notFollowedBy' (string "[@")
-  withRaw $ trimInlinesF <$> inlinesInBalancedBrackets
-
-parenthesizedChars :: PandocMonad m => MarkdownParser m [Char]
-parenthesizedChars = do
-  result <- charsInBalanced '(' ')' litChar
-  return $ '(' : result ++ ")"
-
--- source for a link, with optional title
-source :: PandocMonad m => MarkdownParser m (String, String)
-source = do
-  char '('
-  skipSpaces
-  let urlChunk =
-            try parenthesizedChars
-        <|> (notFollowedBy (oneOf " )") >> count 1 litChar)
-        <|> try (many1 spaceChar <* notFollowedBy (oneOf "\"')"))
-  let sourceURL = (unwords . words . concat) <$> many urlChunk
-  let betweenAngles = try $
-         char '<' >> manyTill litChar (char '>')
-  src <- try betweenAngles <|> sourceURL
-  tit <- option "" $ try $ spnl >> linkTitle
-  skipSpaces
-  char ')'
-  return (escapeURI $ trimr src, tit)
-
-linkTitle :: PandocMonad m => MarkdownParser m String
-linkTitle = quotedTitle '"' <|> quotedTitle '\''
-
-link :: PandocMonad m => MarkdownParser m (F Inlines)
-link = try $ do
-  st <- getState
-  guard $ stateAllowLinks st
-  setState $ st{ stateAllowLinks = False }
-  (lab,raw) <- reference
-  setState $ st{ stateAllowLinks = True }
-  regLink B.linkWith lab <|> referenceLink B.linkWith (lab,raw)
-
-bracketedSpan :: PandocMonad m => MarkdownParser m (F Inlines)
-bracketedSpan = try $ do
-  guardEnabled Ext_bracketed_spans
-  (lab,_) <- reference
-  attr <- attributes
-  return $ if isSmallCaps attr
-              then B.smallcaps <$> lab
-              else B.spanWith attr <$> lab
-
--- | We treat a span as SmallCaps if class is "smallcaps" (and
--- no other attributes are set or if style is "font-variant:small-caps"
--- (and no other attributes are set).
-isSmallCaps :: Attr -> Bool
-isSmallCaps ("",["smallcaps"],[]) = True
-isSmallCaps ("",[],kvs) =
-  case lookup "style" kvs of
-       Just s -> map toLower (filter (`notElem` " \t;") s) ==
-                    "font-variant:small-caps"
-       Nothing -> False
-isSmallCaps _ = False
-
-regLink :: PandocMonad m
-        => (Attr -> String -> String -> Inlines -> Inlines)
-        -> F Inlines
-        -> MarkdownParser m (F Inlines)
-regLink constructor lab = try $ do
-  (src, tit) <- source
-  attr <- option nullAttr $
-          guardEnabled Ext_link_attributes >> attributes
-  return $ constructor attr src tit <$> lab
-
--- a link like [this][ref] or [this][] or [this]
-referenceLink :: PandocMonad m
-              => (Attr -> String -> String -> Inlines -> Inlines)
-              -> (F Inlines, String)
-              -> MarkdownParser m (F Inlines)
-referenceLink constructor (lab, raw) = do
-  sp <- (True <$ lookAhead (char ' ')) <|> return False
-  (_,raw') <- option (mempty, "") $
-      lookAhead (try (do guardEnabled Ext_citations
-                         guardDisabled Ext_spaced_reference_links <|> spnl
-                         normalCite
-                         return (mempty, "")))
-      <|>
-      try ((guardDisabled Ext_spaced_reference_links <|> spnl) >> reference)
-  when (raw' == "") $ guardEnabled Ext_shortcut_reference_links
-  let labIsRef = raw' == "" || raw' == "[]"
-  let key = toKey $ if labIsRef then raw else raw'
-  parsedRaw <- parseFromString' inlines raw'
-  fallback  <- parseFromString' inlines $ dropBrackets raw
-  implicitHeaderRefs <- option False $
-                         True <$ guardEnabled Ext_implicit_header_references
-  let makeFallback = do
-       parsedRaw' <- parsedRaw
-       fallback' <- fallback
-       return $ B.str "[" <> fallback' <> B.str "]" <>
-                (if sp && not (null raw) then B.space else mempty) <>
-                parsedRaw'
-  return $ do
-    keys <- asksF stateKeys
-    case M.lookup key keys of
-       Nothing        ->
-         if implicitHeaderRefs
-            then do
-              headerKeys <- asksF stateHeaderKeys
-              case M.lookup key headerKeys of
-                   Just ((src, tit), _) -> constructor nullAttr src tit <$> lab
-                   Nothing              -> makeFallback
-            else makeFallback
-       Just ((src,tit), attr) -> constructor attr src tit <$> lab
-
-dropBrackets :: String -> String
-dropBrackets = reverse . dropRB . reverse . dropLB
-  where dropRB (']':xs) = xs
-        dropRB xs       = xs
-        dropLB ('[':xs) = xs
-        dropLB xs       = xs
-
-bareURL :: PandocMonad m => MarkdownParser m (F Inlines)
-bareURL = try $ do
-  guardEnabled Ext_autolink_bare_uris
-  getState >>= guard . stateAllowLinks
-  (orig, src) <- uri <|> emailAddress
-  notFollowedBy $ try $ spaces >> htmlTag (~== TagClose "a")
-  return $ return $ B.link src "" (B.str orig)
-
-autoLink :: PandocMonad m => MarkdownParser m (F Inlines)
-autoLink = try $ do
-  getState >>= guard . stateAllowLinks
-  char '<'
-  (orig, src) <- uri <|> emailAddress
-  -- in rare cases, something may remain after the uri parser
-  -- is finished, because the uri parser tries to avoid parsing
-  -- final punctuation.  for example:  in `<http://hi---there>`,
-  -- the URI parser will stop before the dashes.
-  extra <- fromEntities <$> manyTill nonspaceChar (char '>')
-  attr  <- option nullAttr $ try $
-            guardEnabled Ext_link_attributes >> attributes
-  return $ return $ B.linkWith attr (src ++ escapeURI extra) "" (B.str $ orig ++ extra)
-
-image :: PandocMonad m => MarkdownParser m (F Inlines)
-image = try $ do
-  char '!'
-  (lab,raw) <- reference
-  defaultExt <- getOption readerDefaultImageExtension
-  let constructor attr' src = case takeExtension src of
-                          "" -> B.imageWith attr' (addExtension src defaultExt)
-                          _  -> B.imageWith attr' src
-  regLink constructor lab <|> referenceLink constructor (lab,raw)
-
-note :: PandocMonad m => MarkdownParser m (F Inlines)
-note = try $ do
-  guardEnabled Ext_footnotes
-  ref <- noteMarker
-  updateState $ \st -> st{ stateNoteRefs = Set.insert ref (stateNoteRefs st) }
-  return $ do
-    notes <- asksF stateNotes'
-    case M.lookup ref notes of
-        Nothing       -> return $ B.str $ "[^" ++ ref ++ "]"
-        Just (_pos, contents) -> do
-          st <- askF
-          -- process the note in a context that doesn't resolve
-          -- notes, to avoid infinite looping with notes inside
-          -- notes:
-          let contents' = runF contents st{ stateNotes' = M.empty }
-          return $ B.note contents'
-
-inlineNote :: PandocMonad m => MarkdownParser m (F Inlines)
-inlineNote = try $ do
-  guardEnabled Ext_inline_notes
-  char '^'
-  contents <- inlinesInBalancedBrackets
-  return $ B.note . B.para <$> contents
-
-rawLaTeXInline' :: PandocMonad m => MarkdownParser m (F Inlines)
-rawLaTeXInline' = try $ do
-  guardEnabled Ext_raw_tex
-  lookAhead (char '\\')
-  notFollowedBy' rawConTeXtEnvironment
-  s <- rawLaTeXInline
-  return $ return $ B.rawInline "tex" s -- "tex" because it might be context
-
-rawConTeXtEnvironment :: PandocMonad m => ParserT [Char] st m String
-rawConTeXtEnvironment = try $ do
-  string "\\start"
-  completion <- inBrackets (letter <|> digit <|> spaceChar)
-               <|> many1 letter
-  contents <- manyTill (rawConTeXtEnvironment <|> count 1 anyChar)
-                       (try $ string "\\stop" >> string completion)
-  return $ "\\start" ++ completion ++ concat contents ++ "\\stop" ++ completion
-
-inBrackets :: PandocMonad m => (ParserT [Char] st m Char) -> ParserT [Char] st m String
-inBrackets parser = do
-  char '['
-  contents <- many parser
-  char ']'
-  return $ "[" ++ contents ++ "]"
-
-spanHtml :: PandocMonad m => MarkdownParser m (F Inlines)
-spanHtml = try $ do
-  guardEnabled Ext_native_spans
-  (TagOpen _ attrs, _) <- htmlTag (~== TagOpen "span" [])
-  contents <- mconcat <$> manyTill inline (htmlTag (~== TagClose "span"))
-  let ident = fromMaybe "" $ lookup "id" attrs
-  let classes = maybe [] words $ lookup "class" attrs
-  let keyvals = [(k,v) | (k,v) <- attrs, k /= "id" && k /= "class"]
-  return $ if isSmallCaps (ident, classes, keyvals)
-              then B.smallcaps <$> contents
-              else B.spanWith (ident, classes, keyvals) <$> contents
-
-divHtml :: PandocMonad m => MarkdownParser m (F Blocks)
-divHtml = try $ do
-  guardEnabled Ext_native_divs
-  (TagOpen _ attrs, rawtag) <- htmlTag (~== TagOpen "div" [])
-  -- we set stateInHtmlBlock so that closing tags that can be either block or
-  -- inline will not be parsed as inline tags
-  oldInHtmlBlock <- stateInHtmlBlock <$> getState
-  updateState $ \st -> st{ stateInHtmlBlock = Just "div" }
-  bls <- option "" (blankline >> option "" blanklines)
-  contents <- mconcat <$>
-              many (notFollowedBy' (htmlTag (~== TagClose "div")) >> block)
-  closed <- option False (True <$ htmlTag (~== TagClose "div"))
-  if closed
-     then do
-       updateState $ \st -> st{ stateInHtmlBlock = oldInHtmlBlock }
-       let ident = fromMaybe "" $ lookup "id" attrs
-       let classes = maybe [] words $ lookup "class" attrs
-       let keyvals = [(k,v) | (k,v) <- attrs, k /= "id" && k /= "class"]
-       return $ B.divWith (ident, classes, keyvals) <$> contents
-     else -- avoid backtracing
-       return $ return (B.rawBlock "html" (rawtag <> bls)) <> contents
-
-divFenced :: PandocMonad m => MarkdownParser m (F Blocks)
-divFenced = try $ do
-  guardEnabled Ext_fenced_divs
-  nonindentSpaces
-  string ":::"
-  skipMany (char ':')
-  skipMany spaceChar
-  attribs <- attributes <|> ((\x -> ("",[x],[])) <$> many1 nonspaceChar)
-  skipMany spaceChar
-  skipMany (char ':')
-  blankline
-  updateState $ \st -> st{ stateFencedDivLevel = stateFencedDivLevel st + 1 }
-  bs <- mconcat <$> manyTill block divFenceEnd
-  updateState $ \st -> st{ stateFencedDivLevel = stateFencedDivLevel st - 1 }
-  return $ B.divWith attribs <$> bs
-
-divFenceEnd :: PandocMonad m => MarkdownParser m ()
-divFenceEnd = try $ do
-  nonindentSpaces
-  string ":::"
-  skipMany (char ':')
-  blanklines
-  return ()
-
-rawHtmlInline :: PandocMonad m => MarkdownParser m (F Inlines)
-rawHtmlInline = do
-  guardEnabled Ext_raw_html
-  inHtmlBlock <- stateInHtmlBlock <$> getState
-  let isCloseBlockTag t = case inHtmlBlock of
-                               Just t' -> t ~== TagClose t'
-                               Nothing -> False
-  mdInHtml <- option False $
-                (    guardEnabled Ext_markdown_in_html_blocks
-                 <|> guardEnabled Ext_markdown_attribute
-                ) >> return True
-  (_,result) <- htmlTag $ if mdInHtml
-                             then (\x -> isInlineTag x &&
-                                         not (isCloseBlockTag x))
-                             else not . isTextTag
-  return $ return $ B.rawInline "html" result
-
--- Emoji
-
-emojiChars :: [Char]
-emojiChars = ['a'..'z'] ++ ['0'..'9'] ++ ['_','+','-']
-
-emoji :: PandocMonad m => MarkdownParser m (F Inlines)
-emoji = try $ do
-  guardEnabled Ext_emoji
-  char ':'
-  emojikey <- many1 (oneOf emojiChars)
-  char ':'
-  case M.lookup emojikey emojis of
-       Just s  -> return (return (B.str s))
-       Nothing -> mzero
-
--- Citations
-
-cite :: PandocMonad m => MarkdownParser m (F Inlines)
-cite = do
-  guardEnabled Ext_citations
-  textualCite
-            <|> do (cs, raw) <- withRaw normalCite
-                   return $ flip B.cite (B.text raw) <$> cs
-
-textualCite :: PandocMonad m => MarkdownParser m (F Inlines)
-textualCite = try $ do
-  (suppressAuthor, key) <- citeKey
-  let first = Citation{ citationId      = key
-                      , citationPrefix  = []
-                      , citationSuffix  = []
-                      , citationMode    = if suppressAuthor
-                                             then SuppressAuthor
-                                             else AuthorInText
-                      , citationNoteNum = 0
-                      , citationHash    = 0
-                      }
-  mbrest <- option Nothing $ try $ spnl >> Just <$> withRaw normalCite
-  case mbrest of
-       Just (rest, raw) ->
-         return $ (flip B.cite (B.text $ '@':key ++ " " ++ raw) . (first:))
-               <$> rest
-       Nothing   ->
-         (do
-          (cs, raw) <- withRaw $ bareloc first
-          let (spaces',raw') = span isSpace raw
-              spc | null spaces' = mempty
-                  | otherwise    = B.space
-          lab <- parseFromString' inlines $ dropBrackets raw'
-          fallback <- referenceLink B.linkWith (lab,raw')
-          return $ do
-            fallback' <- fallback
-            cs' <- cs
-            return $
-              case B.toList fallback' of
-                Link{}:_ -> B.cite [first] (B.str $ '@':key) <> spc <> fallback'
-                _        -> B.cite cs' (B.text $ '@':key ++ " " ++ raw))
-         <|> return (do st <- askF
-                        return $ case M.lookup key (stateExamples st) of
-                                 Just n -> B.str (show n)
-                                 _      -> B.cite [first] $ B.str $ '@':key)
-
-bareloc :: PandocMonad m => Citation -> MarkdownParser m (F [Citation])
-bareloc c = try $ do
-  spnl
-  char '['
-  notFollowedBy $ char '^'
-  suff <- suffix
-  rest <- option (return []) $ try $ char ';' >> citeList
-  spnl
-  char ']'
-  notFollowedBy $ oneOf "[("
-  return $ do
-    suff' <- suff
-    rest' <- rest
-    return $ c{ citationSuffix = B.toList suff' } : rest'
-
-normalCite :: PandocMonad m => MarkdownParser m (F [Citation])
-normalCite = try $ do
-  char '['
-  spnl
-  citations <- citeList
-  spnl
-  char ']'
-  return citations
-
-suffix :: PandocMonad m => MarkdownParser m (F Inlines)
-suffix = try $ do
-  hasSpace <- option False (notFollowedBy nonspaceChar >> return True)
-  spnl
-  rest <- trimInlinesF . mconcat <$> many (notFollowedBy (oneOf ";]") >> inline)
-  return $ if hasSpace
-              then (B.space <>) <$> rest
-              else rest
-
-prefix :: PandocMonad m => MarkdownParser m (F Inlines)
-prefix = trimInlinesF . mconcat <$>
-  manyTill inline (char ']' <|> fmap (const ']') (lookAhead citeKey))
-
-citeList :: PandocMonad m => MarkdownParser m (F [Citation])
-citeList = fmap sequence $ sepBy1 citation (try $ char ';' >> spnl)
-
-citation :: PandocMonad m => MarkdownParser m (F Citation)
-citation = try $ do
-  pref <- prefix
-  (suppress_author, key) <- citeKey
-  suff <- suffix
-  return $ do
-    x <- pref
-    y <- suff
-    return Citation{ citationId      = key
-                   , citationPrefix  = B.toList x
-                   , citationSuffix  = B.toList y
-                   , citationMode    = if suppress_author
-                                          then SuppressAuthor
-                                          else NormalCitation
-                   , citationNoteNum = 0
-                   , citationHash    = 0
-                   }
-
-smart :: PandocMonad m => MarkdownParser m (F Inlines)
-smart = do
-  guardEnabled Ext_smart
-  doubleQuoted <|> singleQuoted <|>
-    choice (map (return <$>) [apostrophe, dash, ellipses])
-
-singleQuoted :: PandocMonad m => MarkdownParser m (F Inlines)
-singleQuoted = try $ do
-  singleQuoteStart
-  withQuoteContext InSingleQuote $
-    fmap B.singleQuoted . trimInlinesF . mconcat <$>
-      many1Till inline singleQuoteEnd
-
--- doubleQuoted will handle regular double-quoted sections, as well
--- as dialogues with an open double-quote without a close double-quote
--- in the same paragraph.
-doubleQuoted :: PandocMonad m => MarkdownParser m (F Inlines)
-doubleQuoted = try $ do
-  doubleQuoteStart
-  contents <- mconcat <$> many (try $ notFollowedBy doubleQuoteEnd >> inline)
-  (withQuoteContext InDoubleQuote $ doubleQuoteEnd >> return
-       (fmap B.doubleQuoted . trimInlinesF $ contents))
-   <|> (return $ return (B.str "\8220") <> contents)
+{-# LANGUAGE ScopedTypeVariables #-}
+{-# LANGUAGE BangPatterns        #-}
+{-# LANGUAGE FlexibleContexts    #-}
+{-# LANGUAGE TupleSections       #-}
+{-# LANGUAGE OverloadedStrings   #-}
+{-# LANGUAGE ViewPatterns        #-}
+{- |
+   Module      : Text.Pandoc.Readers.Markdown
+   Copyright   : Copyright (C) 2006-2024 John MacFarlane
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : John MacFarlane <jgm@berkeley.edu>
+   Stability   : alpha
+   Portability : portable
+
+Conversion of markdown-formatted plain text to 'Pandoc' document.
+-}
+module Text.Pandoc.Readers.Markdown (
+  readMarkdown,
+  yamlToMeta,
+  yamlToRefs ) where
+
+import Control.Monad
+import Control.Monad.Except (throwError)
+import qualified Data.Bifunctor as Bifunctor
+import Data.Char (isAlphaNum, isPunctuation, isSpace)
+import Data.List (transpose, elemIndex, sortOn)
+import qualified Data.List as L
+import qualified Data.Map as M
+import Data.Maybe
+import qualified Data.Set as Set
+import qualified Data.Attoparsec.Text as A
+import Data.Text (Text)
+import qualified Data.Text as T
+import qualified Data.ByteString as BS
+import System.FilePath (addExtension, takeExtension, takeDirectory)
+import qualified System.FilePath.Windows as Windows
+import qualified System.FilePath.Posix as Posix
+import Text.DocLayout (realLength)
+import Text.HTML.TagSoup hiding (Row)
+import Text.Pandoc.Builder (Blocks, Inlines)
+import qualified Text.Pandoc.Builder as B
+import Text.Pandoc.Class.PandocMonad (PandocMonad (..), report)
+import Text.Pandoc.Definition as Pandoc
+import Text.Pandoc.Emoji (emojiToInline)
+import Safe.Foldable (maximumBounded)
+import Text.Pandoc.Logging
+import Text.Pandoc.Options
+import Text.Pandoc.Walk (walk)
+import Text.Pandoc.Parsing hiding (tableCaption)
+import Text.Pandoc.Readers.HTML (htmlInBalanced, htmlTag, isBlockTag,
+                                 isInlineTag, isTextTag)
+import Text.Pandoc.Readers.LaTeX (applyMacros, rawLaTeXBlock, rawLaTeXInline)
+import Text.Pandoc.Shared
+import Text.Pandoc.URI (escapeURI, isURI, pBase64DataURI)
+import Text.Pandoc.XML (fromEntities)
+import Text.Pandoc.Readers.Metadata (yamlBsToMeta, yamlBsToRefs, yamlMetaBlock)
+-- import Debug.Trace (traceShowId)
+
+type MarkdownParser m = ParsecT Sources ParserState m
+
+type F = Future ParserState
+
+-- | Read markdown from an input string and return a Pandoc document.
+readMarkdown :: (PandocMonad m, ToSources a)
+             => ReaderOptions -- ^ Reader options
+             -> a             -- ^ Input
+             -> m Pandoc
+readMarkdown opts s = do
+  parsed <- readWithM parseMarkdown def{ stateOptions = opts }
+                (ensureFinalNewlines 3 (toSources s))
+  case parsed of
+    Right result -> return result
+    Left e       -> throwError e
+
+-- | Read a YAML string and convert it to pandoc metadata.
+-- String scalars in the YAML are parsed as Markdown.
+yamlToMeta :: PandocMonad m
+           => ReaderOptions
+           -> Maybe FilePath
+           -> BS.ByteString
+           -> m Meta
+yamlToMeta opts mbfp bstr = do
+  let parser = do
+        oldPos <- getPosition
+        setPosition $ initialPos (fromMaybe "" mbfp)
+        meta <- yamlBsToMeta (fmap B.toMetaValue <$> parseBlocks) bstr
+        checkNotes
+        setPosition oldPos
+        st <- getState
+        let result = runF meta st
+        reportLogMessages
+        return result
+  parsed <- readWithM parser def{ stateOptions = opts } ("" :: Text)
+  case parsed of
+    Right result -> return result
+    Left e       -> throwError e
+
+-- | Read a YAML string and extract references from the
+-- 'references' field, filter using an id predicate and
+-- parsing fields as Markdown.
+yamlToRefs :: PandocMonad m
+           => (Text -> Bool)
+           -> ReaderOptions
+           -> Maybe FilePath
+           -> BS.ByteString
+           -> m [MetaValue]
+yamlToRefs idpred opts mbfp bstr = do
+  let parser = do
+        case mbfp of
+          Nothing -> return ()
+          Just fp -> setPosition $ initialPos fp
+        refs <- yamlBsToRefs (fmap B.toMetaValue <$> parseBlocks) idpred bstr
+        checkNotes
+        st <- getState
+        let result = runF refs st
+        reportLogMessages
+        return result
+  parsed <- readWithM parser def{ stateOptions = opts } ("" :: Text)
+  case parsed of
+    Right result -> return result
+    Left e       -> throwError e
+
+
+
+
+--
+-- Constants and data structure definitions
+--
+
+isBulletListMarker :: Char -> Bool
+isBulletListMarker '*' = True
+isBulletListMarker '+' = True
+isBulletListMarker '-' = True
+isBulletListMarker _   = False
+
+isHruleChar :: Char -> Bool
+isHruleChar '*' = True
+isHruleChar '-' = True
+isHruleChar '_' = True
+isHruleChar _   = False
+
+setextHChars :: [Char]
+setextHChars = "=-"
+
+--
+-- auxiliary functions
+--
+
+-- | Succeeds when we're in list context.
+inList :: PandocMonad m => MarkdownParser m ()
+inList = do
+  ctx <- stateParserContext <$> getState
+  guard (ctx == ListItemState)
+
+spnl :: PandocMonad m => ParsecT Sources st m ()
+spnl = try $ do
+  skipSpaces
+  optional newline
+  skipSpaces
+  notFollowedBy (char '\n')
+
+spnl' :: PandocMonad m => ParsecT Sources st m Text
+spnl' = try $ do
+  xs <- many spaceChar
+  ys <- option "" $ try $ (:) <$> newline
+                              <*> (many spaceChar <* notFollowedBy (char '\n'))
+  return $ T.pack $ xs ++ ys
+
+indentSpaces :: PandocMonad m => MarkdownParser m Text
+indentSpaces = try $ do
+  tabStop <- getOption readerTabStop
+  countChar tabStop (char ' ') <|>
+    textStr "\t" <?> "indentation"
+
+nonindentSpaces :: PandocMonad m => MarkdownParser m Text
+nonindentSpaces = do
+  n <- skipNonindentSpaces
+  return $ T.replicate n " "
+
+-- returns number of spaces parsed
+skipNonindentSpaces :: PandocMonad m => MarkdownParser m Int
+skipNonindentSpaces = do
+  tabStop <- getOption readerTabStop
+  gobbleAtMostSpaces (tabStop - 1) <* notFollowedBy spaceChar
+
+litChar :: PandocMonad m => MarkdownParser m Text
+litChar = T.singleton <$> escapedChar'
+       <|> characterReference
+       <|> T.singleton <$> noneOf "\n"
+       <|> try (newline >> notFollowedBy blankline >> return " ")
+
+litBetween :: PandocMonad m => Char -> Char -> MarkdownParser m Text
+litBetween op cl = try $ do
+  char op
+  mconcat <$> (manyTill litChar (char cl))
+
+litCharNoSpace :: PandocMonad m => MarkdownParser m Text
+litCharNoSpace = T.singleton <$> escapedChar''
+       <|> characterReference
+       <|> (snd <$> withRaw attributes)
+       <|> T.singleton <$> noneOf "\n \r\t"
+ where
+   escapedChar'' = do
+     c <- escapedChar'
+     pure $ case c of
+       ' ' -> '\160'
+       _ -> c
+
+litBetweenNoSpace :: PandocMonad m => Char -> Char -> MarkdownParser m Text
+litBetweenNoSpace op cl = try $ do
+  char op
+  mconcat <$> (manyTill litCharNoSpace (char cl))
+
+-- | Parse a sequence of elements between square brackets,
+-- including between balanced pairs of square brackets.
+-- Skip brackets in standard inline escapes, code, raw HTML or LaTeX.
+inBalancedBrackets :: PandocMonad m
+                   => MarkdownParser m (F a)
+                   -> MarkdownParser m (F a)
+inBalancedBrackets innerParser =
+  try $ char '[' >> withRaw (go 1) >>=
+          parseFromString innerParser . stripBracket . snd
+  where stripBracket t = case T.unsnoc t of
+          Just (t', ']') -> t'
+          _              -> t
+        go :: PandocMonad m => Int -> MarkdownParser m ()
+        go 0 = return ()
+        go openBrackets =
+          (() <$ (escapedChar <|>
+                code <|>
+                math <|>
+                endline <|>
+                rawHtmlInline <|>
+                rawLaTeXInline') >> go openBrackets)
+          <|>
+          (do char ']'
+              Control.Monad.when (openBrackets > 1) $ go (openBrackets - 1))
+          <|>
+          (char '[' >> go (openBrackets + 1))
+          <|>
+          (satisfy (/= '\n') >> go openBrackets)
+
+--
+-- document structure
+--
+
+rawTitleBlockLine :: PandocMonad m => MarkdownParser m Text
+rawTitleBlockLine = do
+  char '%'
+  skipSpaces
+  first <- anyLine
+  rest <- many $ try $ do spaceChar
+                          notFollowedBy blankline
+                          skipSpaces
+                          anyLine
+  return $ trim $ T.unlines (first:rest)
+
+titleLine :: PandocMonad m => MarkdownParser m (F Inlines)
+titleLine = try $ do
+  raw <- rawTitleBlockLine
+  res <- parseFromString' inlines raw
+  return $ trimInlinesF res
+
+authorsLine :: PandocMonad m => MarkdownParser m (F [Inlines])
+authorsLine = try $ do
+  raw <- rawTitleBlockLine
+  let sep = (char ';' <* spaces) <|> newline
+  let pAuthors = sepEndBy
+            (trimInlinesF . mconcat <$> many
+                 (try $ notFollowedBy sep >> inline))
+            sep
+  sequence <$> parseFromString' pAuthors raw
+
+dateLine :: PandocMonad m => MarkdownParser m (F Inlines)
+dateLine = try $ do
+  raw <- rawTitleBlockLine
+  res <- parseFromString' inlines raw
+  return $ trimInlinesF res
+
+titleBlock :: PandocMonad m => MarkdownParser m ()
+titleBlock = pandocTitleBlock <|> mmdTitleBlock
+
+pandocTitleBlock :: PandocMonad m => MarkdownParser m ()
+pandocTitleBlock = do
+  guardEnabled Ext_pandoc_title_block
+  lookAhead (char '%')
+  try $ do
+    title <- option mempty titleLine
+    author <- option (return []) authorsLine
+    date <- option mempty dateLine
+    optional blanklines
+    let meta' = do title' <- title
+                   author' <- author
+                   date' <- date
+                   return $
+                       (if null title'
+                           then id
+                           else B.setMeta "title" title')
+                     . (if null author'
+                           then id
+                           else B.setMeta "author" author')
+                     . (if null date'
+                           then id
+                           else B.setMeta "date" date')
+                     $ nullMeta
+    updateState $ \st -> st{ stateMeta' = stateMeta' st <> meta' }
+
+yamlMetaBlock' :: PandocMonad m => MarkdownParser m (F Blocks)
+yamlMetaBlock' = do
+  guardEnabled Ext_yaml_metadata_block
+  newMetaF <- yamlMetaBlock (fmap B.toMetaValue <$> parseBlocks)
+  -- Since `<>` is left-biased, existing values are not touched:
+  updateState $ \st -> st{ stateMeta' = stateMeta' st <> newMetaF }
+  return mempty
+
+mmdTitleBlock :: PandocMonad m => MarkdownParser m ()
+mmdTitleBlock = do
+  guardEnabled Ext_mmd_title_block
+  try $ do
+    firstPair <- kvPair False
+    restPairs <- many (kvPair True)
+    let kvPairs = firstPair : restPairs
+    blanklines
+    updateState $ \st -> st{ stateMeta' = stateMeta' st <>
+                               return (Meta $ M.fromList kvPairs) }
+
+kvPair :: PandocMonad m => Bool -> MarkdownParser m (Text, MetaValue)
+kvPair allowEmpty = try $ do
+  key <- many1TillChar (alphaNum <|> oneOf "_- ") (char ':')
+  val <- trim <$> manyTillChar anyChar
+          (try $ newline >> lookAhead (blankline <|> nonspaceChar))
+  guard $ allowEmpty || not (T.null val)
+  let key' = T.concat $ T.words $ T.toLower key
+  let val' = MetaInlines $ B.toList $ B.text val
+  return (key',val')
+
+parseMarkdown :: PandocMonad m => MarkdownParser m Pandoc
+parseMarkdown = do
+  optional titleBlock
+  blocks <- parseBlocks
+  st <- getState
+  checkNotes
+  let doc = runF (do Pandoc _ bs <- B.doc <$> blocks
+                     meta <- stateMeta' st
+                     return $ Pandoc meta bs) st
+  reportLogMessages
+  return doc
+
+-- check for notes with no corresponding note references
+checkNotes :: PandocMonad m => MarkdownParser m ()
+checkNotes = do
+  st <- getState
+  let notesUsed = stateNoteRefs st
+  forM_ (M.toList (stateNotes' st)) $ \(n, (pos, _)) ->
+    unless (n `Set.member` notesUsed) $
+      report (NoteDefinedButNotUsed n pos)
+
+
+referenceKey :: PandocMonad m => MarkdownParser m (F Blocks)
+referenceKey = try $ do
+  pos <- getPosition
+  skipNonindentSpaces
+  notFollowedBy (void cite)
+  (_,raw) <- reference
+  char ':'
+  skipSpaces >> optional newline >> skipSpaces >> notFollowedBy (char '[')
+  let sourceURL = fmap T.unwords $ many $ try $ do
+                    skipMany spaceChar
+                    notFollowedBy' referenceTitle
+                    notFollowedBy' $ guardEnabled Ext_link_attributes >>
+                                     attributes
+                    notFollowedBy' $ guardEnabled Ext_mmd_link_attributes >>
+                                     try (spnl <* keyValAttr)
+                    notFollowedBy' (() <$ reference)
+                    mconcat <$> many1 (notFollowedBy space *> litChar)
+  rebase <- option False (True <$ guardEnabled Ext_rebase_relative_paths)
+  src <- (if rebase then rebasePath pos else id) <$>
+             (try (litBetween '<' '>') <|> sourceURL)
+  tit <- option "" referenceTitle
+  attr   <- option nullAttr $ try $
+              do guardEnabled Ext_link_attributes
+                 skipSpaces >> optional newline >> skipSpaces
+                 attributes
+  addKvs <- option [] $ guardEnabled Ext_mmd_link_attributes
+                          >> many (try $ spnl >> keyValAttr)
+  blanklines
+  let attr'  = extractIdClass $ L.foldl' (\x f -> f x) attr addKvs
+      target = (escapeURI $ trimr src, tit)
+  st <- getState
+  let oldkeys = stateKeys st
+  let key = toKey raw
+  case M.lookup key oldkeys of
+    Just (t,a) | not (t == target && a == attr') ->
+      -- We don't warn on two duplicate keys if the targets are also
+      -- the same. This can happen naturally with --reference-location=block
+      -- or section. See #3701.
+      logMessage $ DuplicateLinkReference raw pos
+    _ -> return ()
+  updateState $ \s -> s { stateKeys = M.insert key (target, attr') oldkeys }
+  return $ return mempty
+
+referenceTitle :: PandocMonad m => MarkdownParser m Text
+referenceTitle = try $ do
+  skipSpaces >> optional newline >> skipSpaces
+  quotedTitle '"' <|> quotedTitle '\'' <|> charsInBalanced '(' ')' litChar
+
+-- A link title in quotes
+quotedTitle :: PandocMonad m => Char -> MarkdownParser m Text
+quotedTitle c = try $ do
+  char c
+  notFollowedBy spaces
+  let pEnder = try $ char c >> notFollowedBy (satisfy isAlphaNum)
+  let regChunk = many1Char (noneOf ['\\','\n','&',c]) <|> litChar
+  let nestedChunk = (\x -> (c `T.cons` x) `T.snoc` c) <$> quotedTitle c
+  T.unwords . T.words . T.concat <$> manyTill (nestedChunk <|> regChunk) pEnder
+
+-- | PHP Markdown Extra style abbreviation key.  Currently
+-- we just skip them, since Pandoc doesn't have an element for
+-- an abbreviation.
+abbrevKey :: PandocMonad m => MarkdownParser m (F Blocks)
+abbrevKey = do
+  guardEnabled Ext_abbreviations
+  try $ do
+    char '*'
+    reference
+    char ':'
+    skipMany (satisfy (/= '\n'))
+    blanklines
+    return $ return mempty
+
+noteMarker :: PandocMonad m => MarkdownParser m Text
+noteMarker = string "[^" >>
+  many1TillChar (satisfy (`notElem` ['\r','\n','\t',' ','^','[',']']))
+                (char ']')
+
+rawLine :: PandocMonad m => MarkdownParser m Text
+rawLine = try $ do
+  notFollowedBy blankline
+  notFollowedByDivCloser
+  notFollowedBy' $ try $ skipNonindentSpaces >> noteMarker
+  optional indentSpaces
+  anyLine
+
+rawLines :: PandocMonad m => MarkdownParser m Text
+rawLines = do
+  first <- anyLine
+  rest <- many rawLine
+  return $ T.unlines (first:rest)
+
+noteBlock :: PandocMonad m => MarkdownParser m (F Blocks)
+noteBlock = do
+  guardEnabled Ext_footnotes
+  try $ do
+     pos <- getPosition
+     skipNonindentSpaces
+     ref <- noteMarker
+     char ':'
+     optional blankline
+     optional indentSpaces
+     updateState $ \st -> st{ stateInNote = True }
+     first <- rawLines
+     rest <- many $ try $ blanklines >> indentSpaces >> rawLines
+     let raw = T.unlines (first:rest) <> "\n"
+     optional blanklines
+     parsed <- parseFromString' parseBlocks raw
+     oldnotes <- stateNotes' <$> getState
+     case M.lookup ref oldnotes of
+       Just _  -> logMessage $ DuplicateNoteReference ref pos
+       Nothing -> return ()
+     updateState $ \s -> s { stateNotes' =
+       M.insert ref (pos, parsed) oldnotes,
+                             stateInNote = False }
+     return mempty
+
+--
+-- parsing blocks
+--
+
+parseBlocks :: PandocMonad m => MarkdownParser m (F Blocks)
+parseBlocks = mconcat <$> manyTill block eof
+
+block :: PandocMonad m => MarkdownParser m (F Blocks)
+block = do
+  res <- choice [ mempty <$ blanklines
+               , codeBlockFenced
+               , yamlMetaBlock'
+               -- note: bulletList needs to be before header because of
+               -- the possibility of empty list items: -
+               , bulletList
+               , divHtml
+               , divFenced
+               , header
+               , lhsCodeBlock
+               , htmlBlock
+               , table
+               , codeBlockIndented
+               , rawTeXBlock
+               , lineBlock
+               , blockQuote
+               , hrule
+               , orderedList
+               , definitionList
+               , noteBlock
+               , referenceKey
+               , abbrevKey
+               , para
+               , plain
+               ] <?> "block"
+  trace (T.take 60 $ tshow $ B.toList $ runF res defaultParserState)
+  return res
+
+--
+-- header blocks
+--
+
+header :: PandocMonad m => MarkdownParser m (F Blocks)
+header = setextHeader <|> atxHeader <?> "header"
+
+atxChar :: PandocMonad m => MarkdownParser m Char
+atxChar = do
+  exts <- getOption readerExtensions
+  return $ if extensionEnabled Ext_literate_haskell exts
+              then '='
+              else '#'
+
+atxHeader :: PandocMonad m => MarkdownParser m (F Blocks)
+atxHeader = try $ do
+  level <- fmap length (atxChar >>= many1 . char)
+  notFollowedBy $ guardEnabled Ext_fancy_lists >>
+                  (char '.' <|> char ')') -- this would be a list
+  guardDisabled Ext_space_in_atx_header <|> notFollowedBy nonspaceChar
+  skipSpaces
+  (text, raw) <- withRaw $ do
+    oldAllowLineBreaks <- stateAllowLineBreaks <$> getState
+    updateState $ \st -> st{ stateAllowLineBreaks = False }
+    res <- trimInlinesF . mconcat <$>
+               many (notFollowedBy atxClosing >> inline)
+    updateState $ \st -> st{ stateAllowLineBreaks = oldAllowLineBreaks }
+    return res
+  attr <- atxClosing
+  attr' <- registerHeader attr (runF text defaultParserState)
+  guardDisabled Ext_implicit_header_references
+    <|> registerImplicitHeader raw attr'
+  return $ B.headerWith attr' level <$> text
+
+atxClosing :: PandocMonad m => MarkdownParser m Attr
+atxClosing = try $ do
+  attr' <- option nullAttr
+             (guardEnabled Ext_mmd_header_identifiers >> mmdHeaderIdentifier)
+  skipMany . char =<< atxChar
+  skipSpaces
+  attr <- option attr'
+             (guardEnabled Ext_header_attributes >> attributes)
+  blanklines
+  return attr
+
+setextHeaderEnd :: PandocMonad m => MarkdownParser m Attr
+setextHeaderEnd = try $ do
+  attr <- option nullAttr
+          $ (guardEnabled Ext_mmd_header_identifiers >> mmdHeaderIdentifier)
+           <|> (guardEnabled Ext_header_attributes >> attributes)
+  blanklines
+  return attr
+
+mmdHeaderIdentifier :: PandocMonad m => MarkdownParser m Attr
+mmdHeaderIdentifier = do
+  (_, raw) <- reference
+  let raw' = trim $ stripFirstAndLast raw
+  let ident = T.concat $ T.words $ T.toLower raw'
+  let attr = (ident, [], [])
+  guardDisabled Ext_implicit_header_references
+    <|> registerImplicitHeader raw' attr
+  skipSpaces
+  return attr
+
+setextHeader :: PandocMonad m => MarkdownParser m (F Blocks)
+setextHeader = try $ do
+  -- This lookahead prevents us from wasting time parsing Inlines
+  -- unless necessary -- it gives a significant performance boost.
+  lookAhead $ anyLine >> many1 (oneOf setextHChars) >> blankline
+  skipSpaces
+  (text, raw) <- withRaw $ do
+    oldAllowLineBreaks <- stateAllowLineBreaks <$> getState
+    updateState $ \st -> st{ stateAllowLineBreaks = False }
+    res <- trimInlinesF . mconcat <$>
+               many (notFollowedBy setextHeaderEnd >> inline)
+    updateState $ \st -> st{ stateAllowLineBreaks = oldAllowLineBreaks }
+    return res
+  attr <- setextHeaderEnd
+  underlineChar <- oneOf setextHChars
+  many (char underlineChar)
+  blanklines
+  let level = fromMaybe 0 (elemIndex underlineChar setextHChars) + 1
+  attr' <- registerHeader attr (runF text defaultParserState)
+  guardDisabled Ext_implicit_header_references
+    <|> registerImplicitHeader raw attr'
+  return $ B.headerWith attr' level <$> text
+
+registerImplicitHeader :: PandocMonad m => Text -> Attr -> MarkdownParser m ()
+registerImplicitHeader raw attr@(ident, _, _)
+  | T.null raw = return ()
+  | otherwise = do
+      let key = toKey $ "[" <> raw <> "]"
+      updateState $ \s ->  -- don't override existing headers
+        s { stateHeaderKeys = M.insertWith (\_new old -> old)
+                                     key (("#" <> ident,""), attr)
+                                     (stateHeaderKeys s) }
+
+--
+-- hrule block
+--
+
+hrule :: PandocMonad m => ParsecT Sources st m (F Blocks)
+hrule = try $ do
+  skipSpaces
+  start <- satisfy isHruleChar
+  count 2 (skipSpaces >> char start)
+  skipMany (spaceChar <|> char start)
+  newline
+  optional blanklines
+  return $ return B.horizontalRule
+
+--
+-- code blocks
+--
+
+indentedLine :: PandocMonad m => MarkdownParser m Text
+indentedLine = indentSpaces >> anyLineNewline
+
+blockDelimiter :: PandocMonad m
+               => (Char -> Bool)
+               -> Maybe Int
+               -> ParsecT Sources ParserState m Int
+blockDelimiter f len = try $ do
+  skipNonindentSpaces
+  c <- lookAhead (satisfy f)
+  case len of
+      Just l  -> count l (char c) >> many (char c) >> return l
+      Nothing -> fmap ((+ 3) . length) (count 3 (char c) >> many (char c))
+
+attributes :: PandocMonad m => MarkdownParser m Attr
+attributes = try $ do
+  char '{'
+  spnl
+  attrs <- many (attribute <* spnl)
+  char '}'
+  return $ L.foldl' (\x f -> f x) nullAttr attrs
+
+attribute :: PandocMonad m => MarkdownParser m (Attr -> Attr)
+attribute = identifierAttr <|> classAttr <|> keyValAttr <|> specialAttr
+
+identifier :: PandocMonad m => MarkdownParser m Text
+identifier = do
+  first <- letter
+  rest <- many $ alphaNum <|> oneOf "-_:."
+  return $ T.pack (first:rest)
+
+identifierAttr :: PandocMonad m => MarkdownParser m (Attr -> Attr)
+identifierAttr = try $ do
+  char '#'
+  result <- T.pack <$> many1 (alphaNum <|> oneOf "-_:.") -- see #7920
+  return $ \(_,cs,kvs) -> (result,cs,kvs)
+
+classAttr :: PandocMonad m => MarkdownParser m (Attr -> Attr)
+classAttr = try $ do
+  char '.'
+  result <- identifier
+  return $ \(id',cs,kvs) -> (id',cs ++ [result],kvs)
+
+keyValAttr :: PandocMonad m => MarkdownParser m (Attr -> Attr)
+keyValAttr = try $ do
+  key <- identifier
+  char '='
+  val <- mconcat <$> enclosed (char '"') (char '"') litChar
+     <|> mconcat <$> enclosed (char '\'') (char '\'') litChar
+     <|> ("" <$ try (string "\"\""))
+     <|> ("" <$ try (string "''"))
+     <|> manyChar (escapedChar' <|> noneOf " \t\n\r}")
+  return $ \(id',cs,kvs) ->
+    case key of
+         "id"    -> (val,cs,kvs)
+         "class" -> (id',cs ++ T.words val,kvs)
+         _       -> (id',cs,kvs ++ [(key,val)])
+
+specialAttr :: PandocMonad m => MarkdownParser m (Attr -> Attr)
+specialAttr = do
+  char '-'
+  return $ \(id',cs,kvs) -> (id',cs ++ ["unnumbered"],kvs)
+
+rawAttribute :: PandocMonad m => MarkdownParser m Text
+rawAttribute = do
+  char '{'
+  skipMany spaceChar
+  char '='
+  format <- many1Char $ satisfy (\c -> isAlphaNum c || c `elem` ['-', '_'])
+  skipMany spaceChar
+  char '}'
+  return format
+
+codeBlockFenced :: PandocMonad m => MarkdownParser m (F Blocks)
+codeBlockFenced = try $ do
+  indentchars <- nonindentSpaces
+  let indentLevel = T.length indentchars
+  c <- (guardEnabled Ext_fenced_code_blocks >> lookAhead (char '~'))
+     <|> (guardEnabled Ext_backtick_code_blocks >> lookAhead (char '`'))
+  size <- blockDelimiter (== c) Nothing
+  skipMany spaceChar
+  rawattr <-
+     (Left <$> (guardEnabled Ext_raw_attribute >> try rawAttribute))
+    <|>
+     (Right <$> do
+         let pLangId = many1Char . satisfy $ \x ->
+               x `notElem` ['`', '{', '}'] && not (isSpace x)
+         mbLanguageId <- optionMaybe (toLanguageId <$> pLangId)
+         skipMany spaceChar
+         mbAttr <- optionMaybe
+                   (guardEnabled Ext_fenced_code_attributes *> try attributes)
+         return $ case mbAttr of
+           Nothing -> ("", maybeToList mbLanguageId, [])
+           Just (elementId, classes, attrs) ->
+             (elementId, (maybe id (:) mbLanguageId) classes, attrs))
+  blankline
+  contents <- T.intercalate "\n" <$>
+                 manyTill (gobbleAtMostSpaces indentLevel >> anyLine)
+                          (try $ do
+                            blockDelimiter (== c) (Just size)
+                            blanklines)
+  return $ return $
+    case rawattr of
+          Left syn   -> B.rawBlock syn contents
+          Right attr -> B.codeBlockWith attr contents
+
+-- correctly handle github language identifiers
+toLanguageId :: Text -> Text
+toLanguageId = T.toLower . go
+  where go "c++"         = "cpp"
+        go "objective-c" = "objectivec"
+        go x             = x
+
+codeBlockIndented :: PandocMonad m => MarkdownParser m (F Blocks)
+codeBlockIndented = do
+  contents <- many1 (indentedLine <|>
+                     try (do b <- blanklines
+                             l <- indentedLine
+                             return $ b <> l))
+  optional blanklines
+  classes <- getOption readerIndentedCodeClasses
+  return $ return $ B.codeBlockWith ("", classes, []) $
+           stripTrailingNewlines $ T.concat contents
+
+lhsCodeBlock :: PandocMonad m => MarkdownParser m (F Blocks)
+lhsCodeBlock = do
+  guardEnabled Ext_literate_haskell
+  (return . B.codeBlockWith ("",["haskell","literate"],[]) <$>
+          (lhsCodeBlockBird <|> lhsCodeBlockLaTeX))
+    <|> (return . B.codeBlockWith ("",["haskell"],[]) <$>
+          lhsCodeBlockInverseBird)
+
+lhsCodeBlockLaTeX :: PandocMonad m => MarkdownParser m Text
+lhsCodeBlockLaTeX = try $ do
+  string "\\begin{code}"
+  manyTill spaceChar newline
+  contents <- many1TillChar anyChar (try $ string "\\end{code}")
+  blanklines
+  return $ stripTrailingNewlines contents
+
+lhsCodeBlockBird :: PandocMonad m => MarkdownParser m Text
+lhsCodeBlockBird = lhsCodeBlockBirdWith '>'
+
+lhsCodeBlockInverseBird :: PandocMonad m => MarkdownParser m Text
+lhsCodeBlockInverseBird = lhsCodeBlockBirdWith '<'
+
+lhsCodeBlockBirdWith :: PandocMonad m => Char -> MarkdownParser m Text
+lhsCodeBlockBirdWith c = try $ do
+  pos <- getPosition
+  when (sourceColumn pos /= 1) $ Prelude.fail "Not in first column"
+  lns <- many1 $ birdTrackLine c
+  -- if (as is normal) there is always a space after >, drop it
+  let lns' = if all (\ln -> T.null ln || T.head ln == ' ') lns
+                then map (T.drop 1) lns
+                else lns
+  blanklines
+  return $ T.intercalate "\n" lns'
+
+birdTrackLine :: PandocMonad m => Char -> ParsecT Sources st m Text
+birdTrackLine c = try $ do
+  char c
+  -- allow html tags on left margin:
+  when (c == '<') $ notFollowedBy letter
+  anyLine
+
+--
+-- block quotes
+--
+
+emailBlockQuoteStart :: PandocMonad m => MarkdownParser m Char
+emailBlockQuoteStart = try $ skipNonindentSpaces >> char '>' <* optional (char ' ')
+
+emailBlockQuote :: PandocMonad m => MarkdownParser m [Text]
+emailBlockQuote = try $ do
+  emailBlockQuoteStart
+  let emailLine = manyChar $ nonEndline <|> try
+                              (endline >> notFollowedBy emailBlockQuoteStart >>
+                               return '\n')
+  let emailSep = try (newline >> emailBlockQuoteStart)
+  first <- emailLine
+  rest <- many $ try $ emailSep >> emailLine
+  let raw = first:rest
+  newline <|> (eof >> return '\n')
+  optional blanklines
+  return raw
+
+blockQuote :: PandocMonad m => MarkdownParser m (F Blocks)
+blockQuote = do
+  raw <- emailBlockQuote
+  (mbAlert, raw') <-
+    (do guardEnabled Ext_alerts
+        case raw of
+          (t:ts) | "[!" `T.isPrefixOf` t ->
+              case T.strip t of
+                "[!TIP]" -> pure (Just "tip", ts)
+                "[!WARNING]" -> pure (Just "warning", ts)
+                "[!IMPORTANT]" -> pure (Just "important", ts)
+                "[!CAUTION]" -> pure (Just "caution", ts)
+                "[!NOTE]" -> pure (Just "note", ts)
+                _ -> pure (Nothing, raw)
+          _ -> pure (Nothing, raw))
+      <|> pure (Nothing, raw)
+  -- parse the extracted block, which may contain various block elements:
+  contents <- parseFromString' parseBlocks $ T.intercalate "\n" raw' <> "\n\n"
+  return $
+    case mbAlert of
+      Nothing -> B.blockQuote <$> contents
+      Just alert ->
+        (B.divWith ("", [alert], [])
+          . (B.divWith ("", ["title"], []) (B.para (B.str (T.toTitle alert))) <>))
+           <$> contents
+
+--
+-- list blocks
+--
+
+bulletListStart :: PandocMonad m => MarkdownParser m ()
+bulletListStart = try $ do
+  optional newline -- if preceded by a Plain block in a list context
+  skipNonindentSpaces
+  notFollowedBy' (() <$ hrule)     -- because hrules start out just like lists
+  satisfy isBulletListMarker
+  gobbleSpaces 1 <|> () <$ lookAhead newline
+  try (gobbleAtMostSpaces 3 >> notFollowedBy spaceChar) <|> return ()
+
+orderedListStart :: PandocMonad m
+                 => Maybe (ListNumberStyle, ListNumberDelim)
+                 -> MarkdownParser m (Int, ListNumberStyle, ListNumberDelim)
+orderedListStart mbstydelim = try $ do
+  optional newline -- if preceded by a Plain block in a list context
+  skipNonindentSpaces
+  notFollowedBy $ string "p." >> spaceChar >> digit  -- page number
+  (do guardDisabled Ext_fancy_lists
+      start <- many1Char digit >>= safeRead
+      char '.'
+      gobbleSpaces 1 <|> () <$ lookAhead newline
+      optional $ try (gobbleAtMostSpaces 3 >> notFollowedBy spaceChar)
+      return (start, DefaultStyle, DefaultDelim))
+   <|>
+   (do (num, style, delim) <- maybe
+          anyOrderedListMarker
+          (\(sty,delim) -> (\start -> (start,sty,delim)) <$>
+               orderedListMarker sty delim)
+          mbstydelim
+       gobbleSpaces 1 <|> () <$ lookAhead newline
+       -- if it could be an abbreviated first name,
+       -- insist on more than one space
+       when (delim == Period && (style == UpperAlpha ||
+            (style == UpperRoman &&
+             num `elem` [1, 5, 10, 50, 100, 500, 1000]))) $
+              () <$ lookAhead (newline <|> spaceChar)
+       optional $ try (gobbleAtMostSpaces 3 >> notFollowedBy spaceChar)
+       return (num, style, delim))
+
+listStart :: PandocMonad m => MarkdownParser m ()
+listStart = bulletListStart
+        <|> Control.Monad.void (orderedListStart Nothing)
+        <|> defListStart
+
+listLine :: PandocMonad m => Int -> MarkdownParser m Text
+listLine continuationIndent = try $ do
+  notFollowedBy' (do gobbleSpaces continuationIndent
+                     skipMany spaceChar
+                     listStart)
+  notFollowedByHtmlCloser
+  notFollowedByDivCloser
+  optional (() <$ gobbleSpaces continuationIndent)
+  anyLine
+
+-- parse raw text for one list item, excluding start marker and continuations
+rawListItem :: PandocMonad m
+            => Bool -- four space rule
+            -> MarkdownParser m a
+            -> MarkdownParser m (Text, Int)
+rawListItem fourSpaceRule start = try $ do
+  pos1 <- getPosition
+  start
+  pos2 <- getPosition
+  let continuationIndent = if fourSpaceRule
+                              then 4
+                              else sourceColumn pos2 - sourceColumn pos1
+  first <- anyLine
+  rest <- many (do notFollowedBy listStart
+                   notFollowedBy (() <$ codeBlockFenced)
+                   notFollowedBy blankline
+                   listLine continuationIndent)
+  blanks <- manyChar blankline
+  let result = T.unlines (first:rest) <> blanks
+  return (result, continuationIndent)
+
+-- continuation of a list item - indented and separated by blankline
+-- or (in compact lists) endline.
+-- note: nested lists are parsed as continuations
+listContinuation :: PandocMonad m => Int -> MarkdownParser m Text
+listContinuation continuationIndent = try $ do
+  x <- try $ do
+         notFollowedBy blankline
+         notFollowedByHtmlCloser
+         notFollowedByDivCloser
+         gobbleSpaces continuationIndent
+         anyLineNewline
+  xs <- many $ try $ do
+         notFollowedBy blankline
+         notFollowedByHtmlCloser
+         notFollowedByDivCloser
+         gobbleSpaces continuationIndent <|> notFollowedBy' listStart
+         anyLineNewline
+  blanks <- manyChar blankline
+  return $ T.concat (x:xs) <> blanks
+
+-- Variant of blanklines that doesn't require blank lines
+-- before a fence or eof.
+blanklines' :: PandocMonad m => MarkdownParser m Text
+blanklines' = blanklines <|> try checkDivCloser
+  where checkDivCloser = do
+          guardEnabled Ext_fenced_divs
+          divLevel <- stateFencedDivLevel <$> getState
+          guard (divLevel >= 1)
+          lookAhead divFenceEnd
+          return ""
+
+notFollowedByDivCloser :: PandocMonad m => MarkdownParser m ()
+notFollowedByDivCloser =
+  guardDisabled Ext_fenced_divs <|>
+  do divLevel <- stateFencedDivLevel <$> getState
+     guard (divLevel < 1) <|> notFollowedBy divFenceEnd
+
+notFollowedByHtmlCloser :: PandocMonad m => MarkdownParser m ()
+notFollowedByHtmlCloser = do
+  inHtmlBlock <- stateInHtmlBlock <$> getState
+  case inHtmlBlock of
+        Just t  -> notFollowedBy' $ htmlTag (~== TagClose t)
+        Nothing -> return ()
+
+listItem :: PandocMonad m
+         => Bool -- four-space rule
+         -> MarkdownParser m a
+         -> MarkdownParser m (F Blocks)
+listItem fourSpaceRule start = try $ do
+  -- parsing with ListItemState forces markers at beginning of lines to
+  -- count as list item markers, even if not separated by blank space.
+  -- see definition of "endline"
+  state <- getState
+  let oldContext = stateParserContext state
+  setState $ state {stateParserContext = ListItemState}
+  (first, continuationIndent) <- rawListItem fourSpaceRule start
+  continuations <- many (listContinuation continuationIndent)
+  -- parse the extracted block, which may contain various block elements:
+  let raw = T.concat (first:continuations)
+  contents <- parseFromString' parseBlocks raw
+  updateState (\st -> st {stateParserContext = oldContext})
+  exts <- getOption readerExtensions
+  return $ B.fromList . taskListItemFromAscii exts . B.toList <$> contents
+
+orderedList :: PandocMonad m => MarkdownParser m (F Blocks)
+orderedList = try $ do
+  (start, style, delim) <- lookAhead (orderedListStart Nothing)
+  unless (style `elem` [DefaultStyle, Decimal, Example] &&
+          delim `elem` [DefaultDelim, Period]) $
+    guardEnabled Ext_fancy_lists
+  when (style == Example) $ guardEnabled Ext_example_lists
+  fourSpaceRule <- (True <$ guardEnabled Ext_four_space_rule)
+               <|> return (style == Example)
+  items <- fmap sequence $ many1 $ listItem fourSpaceRule
+                 (orderedListStart (Just (style, delim)))
+  start' <- if style == Example
+               then return start
+               else (start <$ guardEnabled Ext_startnum) <|> return 1
+  return $ B.orderedListWith (start', style, delim) <$> fmap compactify items
+
+bulletList :: PandocMonad m => MarkdownParser m (F Blocks)
+bulletList = do
+  fourSpaceRule <- (True <$ guardEnabled Ext_four_space_rule)
+               <|> return False
+  items <- fmap sequence $ many1 $ listItem fourSpaceRule bulletListStart
+  return $ B.bulletList <$> fmap compactify items
+
+-- definition lists
+
+defListStart :: PandocMonad m => MarkdownParser m ()
+defListStart = do
+  nonindentSpaces
+  char ':' <|> char '~'
+  gobbleSpaces 1 <|> () <$ lookAhead newline
+  try (gobbleAtMostSpaces 3 >> notFollowedBy spaceChar) <|> return ()
+
+definitionListItem :: PandocMonad m => MarkdownParser m (F (Inlines, [Blocks]))
+definitionListItem = try $ do
+  rawLine' <- anyLine
+  term <- parseFromString' (trimInlinesF <$> inlines) rawLine'
+  isTight <- (False <$ blanklines) <|> pure True
+  fourSpaceRule <- (True <$ guardEnabled Ext_four_space_rule) <|> pure False
+  contents <- many1 $ listItem fourSpaceRule defListStart
+  optional blanklines
+  return $ liftM2 (,)
+              term
+              ((if isTight
+                   then fmap (fmap (fmap paraToPlain))
+                   else id) (sequence contents))
+
+paraToPlain :: Block -> Block
+paraToPlain (Para ils) = Plain ils
+paraToPlain x = x
+
+definitionList :: PandocMonad m => MarkdownParser m (F Blocks)
+definitionList = try $ do
+  guardEnabled Ext_definition_lists
+  lookAhead (anyLine >>
+             optional (blankline >> notFollowedBy (Control.Monad.void table)) >>
+             -- don't capture table caption as def list!
+             defListStart)
+  items <- fmap sequence $ many1 definitionListItem
+  return $ B.definitionList <$> items
+
+--
+-- paragraph block
+--
+
+para :: PandocMonad m => MarkdownParser m (F Blocks)
+para = try $ do
+  exts <- getOption readerExtensions
+
+  result <- trimInlinesF <$> inlines1
+  let figureOr constr inlns =
+        case B.toList inlns of
+          [Image attr figCaption (src, tit)]
+            | extensionEnabled Ext_implicit_figures exts
+            , not (null figCaption) -> do
+                implicitFigure attr (B.fromList figCaption) src tit
+
+          _ -> constr inlns
+
+  option (figureOr B.plain <$> result)
+    $ try $ do
+            newline
+            (mempty <$ blanklines)
+              <|> (guardDisabled Ext_blank_before_blockquote
+                   <* lookAhead blockQuote)
+              <|> (guardEnabled Ext_backtick_code_blocks
+                   <* lookAhead codeBlockFenced)
+              <|> (guardDisabled Ext_blank_before_header
+                   <* lookAhead header)
+              <|> (guardEnabled Ext_lists_without_preceding_blankline
+                    -- Avoid creating a paragraph in a nested list.
+                    <* notFollowedBy' (inList <* listStart))
+              <|> do guardEnabled Ext_native_divs
+                     inHtmlBlock <- stateInHtmlBlock <$> getState
+                     case inHtmlBlock of
+                       Just "div" -> () <$
+                         lookAhead (htmlTag (~== TagClose ("div" :: Text)))
+                       _          -> mzero
+              <|> do guardEnabled Ext_fenced_divs
+                     divLevel <- stateFencedDivLevel <$> getState
+                     if divLevel > 0
+                        then lookAhead divFenceEnd
+                        else mzero
+            return $ figureOr B.para <$> result
+
+plain :: PandocMonad m => MarkdownParser m (F Blocks)
+plain = fmap B.plain . trimInlinesF <$> inlines1
+
+implicitFigure :: Attr -> Inlines -> Text -> Text -> Blocks
+implicitFigure (ident, classes, attribs) capt url title =
+  let alt = case "alt" `lookup` attribs of
+              Just alt'       -> B.text alt'
+              _               -> capt
+      attribs' = filter ((/= "latex-placement") . fst)
+                    (filter ((/= "alt") . fst) attribs)
+      figattribs = case lookup "latex-placement" attribs of
+        Just p -> [("latex-placement", p)]
+        _      -> mempty
+      figattr = (ident, mempty, figattribs)
+      caption = B.simpleCaption $ B.plain capt
+      figbody = B.plain $ B.imageWith ("", classes, attribs') url title alt
+  in B.figureWith figattr caption figbody
+
+--
+-- raw html
+--
+
+htmlElement :: PandocMonad m => MarkdownParser m Text
+htmlElement = rawVerbatimBlock
+          <|> strictHtmlBlock
+          <|> fmap snd (htmlTag isBlockTag)
+
+htmlBlock :: PandocMonad m => MarkdownParser m (F Blocks)
+htmlBlock = do
+  guardEnabled Ext_raw_html
+  try (do
+      (TagOpen _ attrs) <- lookAhead $ fst <$> htmlTag isBlockTag
+      return . B.rawBlock "html" <$> rawVerbatimBlock
+        <|> (do guardEnabled Ext_markdown_attribute
+                oldMarkdownAttribute <- stateMarkdownAttribute <$> getState
+                markdownAttribute <-
+                   case lookup "markdown" attrs of
+                        Just "0" -> False <$ updateState (\st -> st{
+                                       stateMarkdownAttribute = False })
+                        Just _   -> True <$ updateState (\st -> st{
+                                       stateMarkdownAttribute = True })
+                        Nothing  -> return oldMarkdownAttribute
+                res <- if markdownAttribute
+                          then rawHtmlBlocks
+                          else htmlBlock'
+                updateState $ \st -> st{ stateMarkdownAttribute =
+                                         oldMarkdownAttribute }
+                return res)
+        <|> (guardEnabled Ext_markdown_in_html_blocks >> rawHtmlBlocks))
+    <|> htmlBlock'
+
+htmlBlock' :: PandocMonad m => MarkdownParser m (F Blocks)
+htmlBlock' = try $ do
+    first <- htmlElement
+    skipMany spaceChar
+    optional blanklines
+    return $ if T.null first
+                then mempty
+                else return $ B.rawBlock "html" first
+
+strictHtmlBlock :: PandocMonad m => MarkdownParser m Text
+strictHtmlBlock = htmlInBalanced (not . isInlineTag)
+
+rawVerbatimBlock :: PandocMonad m => MarkdownParser m Text
+rawVerbatimBlock = htmlInBalanced isVerbTag
+  where isVerbTag (TagOpen "pre" _)      = True
+        isVerbTag (TagOpen "style" _)    = True
+        isVerbTag (TagOpen "script" _)   = True
+        isVerbTag (TagOpen "textarea" _) = True
+        isVerbTag _                      = False
+
+rawTeXBlock :: PandocMonad m => MarkdownParser m (F Blocks)
+rawTeXBlock = do
+  guardEnabled Ext_raw_tex
+  result <- (B.rawBlock "tex" . trim . T.concat <$>
+                many1 ((<>) <$> rawConTeXtEnvironment <*> spnl'))
+          <|> (B.rawBlock "tex" . trim . T.concat <$>
+                many1 ((<>) <$> rawLaTeXBlock <*> spnl'))
+  return $ case B.toList result of
+                [RawBlock _ cs]
+                  | T.all (\c -> c == ' ' || c == '\t' || c == '\n') cs -> return mempty
+                -- don't create a raw block for suppressed macro defs
+                _ -> return result
+
+rawHtmlBlocks :: PandocMonad m => MarkdownParser m (F Blocks)
+rawHtmlBlocks = do
+  (TagOpen tagtype _, raw) <- htmlTag isBlockTag
+  let selfClosing = "/>" `T.isSuffixOf` raw
+  -- we don't want '<td>    text' to be a code block:
+  skipMany spaceChar
+  tabStop <- getOption readerTabStop
+  indentlevel <- option 0 $
+                 do blankline
+                    sum <$> many ( (1 <$ char ' ')
+                                   <|>
+                                   (tabStop <$ char '\t') )
+  -- try to find closing tag
+  -- we set stateInHtmlBlock so that closing tags that can be either block or
+  -- inline will not be parsed as inline tags
+  oldInHtmlBlock <- stateInHtmlBlock <$> getState
+  updateState $ \st -> st{ stateInHtmlBlock = Just tagtype }
+  let closer = htmlTag (~== TagClose tagtype)
+  let block' = try $ do
+                 gobbleAtMostSpaces indentlevel
+                 notFollowedBy' closer
+                 block
+  contents <- if selfClosing
+                 then return mempty
+                 else mconcat <$> many block'
+  result <-
+    try
+    (do gobbleAtMostSpaces indentlevel
+        (_, rawcloser) <- closer
+        return (return (B.rawBlock "html" $ stripMarkdownAttribute raw) <>
+                contents <>
+                return (B.rawBlock "html" rawcloser)))
+      <|> if T.all isSpace raw
+             then return mempty
+             else return (return (B.rawBlock "html" raw) <> contents)
+  updateState $ \st -> st{ stateInHtmlBlock = oldInHtmlBlock }
+  return result
+
+-- remove markdown="1" attribute
+stripMarkdownAttribute :: Text -> Text
+stripMarkdownAttribute s = renderTags' $ map filterAttrib $ parseTags s
+  where filterAttrib (TagOpen t as) = TagOpen t
+                                        [(k,v) | (k,v) <- as, k /= "markdown"]
+        filterAttrib              x = x
+
+--
+-- line block
+--
+
+lineBlock :: PandocMonad m => MarkdownParser m (F Blocks)
+lineBlock = do
+  guardEnabled Ext_line_blocks
+  try $ do
+    lines' <- lineBlockLines >>=
+              mapM (parseFromString' (trimInlinesF <$> inlines))
+    return $ B.lineBlock <$> sequence lines'
+
+--
+-- Tables
+--
+
+-- Parse a dashed line with optional trailing spaces; return its length
+-- and the length including trailing space.
+dashedLine :: PandocMonad m
+           => Char
+           -> ParsecT Sources st m (Int, Int)
+dashedLine ch = do
+  dashes <- many1 (char ch)
+  sp     <- many spaceChar
+  let lengthDashes = length dashes
+      lengthSp     = length sp
+  return (lengthDashes, lengthDashes + lengthSp)
+
+-- Parse a table header with dashed lines of '-' preceded by
+-- one (or zero) line of text.
+simpleTableHeader :: PandocMonad m
+                  => Bool  -- ^ Headerless table
+                  -> MarkdownParser m (F [[Blocks]], [Alignment], [Int])
+simpleTableHeader headless = try $ do
+  rawContent  <- if headless
+                    then return ""
+                    else anyLine
+  initSp      <- nonindentSpaces
+  dashes      <- many1 (dashedLine '-')
+  newline
+  let (lengths, lines') = unzip dashes
+  let indices  = scanl (+) (T.length initSp) lines'
+  -- If no header, calculate alignment on basis of first row of text
+  rawHeads <- fmap (drop 1 . splitTextByIndices (init indices)) $
+              if headless
+                 then lookAhead anyLine
+                 else return rawContent
+  let aligns   = zipWith alignType (map (: []) rawHeads) lengths
+  let rawHeads' = if headless
+                     then []
+                     else rawHeads
+  heads <- fmap sequence
+           $
+            mapM (parseFromString' (mconcat <$> many plain).trim) rawHeads'
+  return (fmap (:[]) heads, aligns, indices)
+
+-- Returns an alignment type for a table, based on a list of strings
+-- (the rows of the column header) and a number (the length of the
+-- dashed line under the rows.
+alignType :: [Text]
+          -> Int
+          -> Alignment
+alignType [] _ = AlignDefault
+alignType strLst len =
+  let nonempties = filter (not . T.null) $ map trimr strLst
+      (leftSpace, rightSpace) =
+           case sortOn T.length nonempties of
+                 (x:_) -> (T.head x `elem` [' ', '\t'], realLength x < len)
+                 []    -> (False, False)
+  in  case (leftSpace, rightSpace) of
+        (True,  False) -> AlignRight
+        (False, True)  -> AlignLeft
+        (True,  True)  -> AlignCenter
+        (False, False) -> AlignDefault
+
+-- Parse a table footer - dashed lines followed by blank line.
+tableFooter :: PandocMonad m => MarkdownParser m Text
+tableFooter = try $ skipNonindentSpaces >> many1 (dashedLine '-') >> blanklines'
+
+-- Parse a table separator - dashed line.
+tableSep :: PandocMonad m => MarkdownParser m Char
+tableSep = try $ skipNonindentSpaces >> many1 (dashedLine '-') >> char '\n'
+
+-- Parse a raw line and split it into chunks by indices.
+rawTableLine :: PandocMonad m
+             => [Int]
+             -> MarkdownParser m [Text]
+rawTableLine indices = do
+  notFollowedBy' (blanklines' <|> tableFooter)
+  line <- anyLine
+  return $ map trim $ drop 1 $ splitTextByIndices (init indices) line
+
+-- Parse a table line and return a list of lists of blocks (columns).
+tableLine :: PandocMonad m
+          => [Int]
+          -> MarkdownParser m (F [Blocks])
+tableLine indices = rawTableLine indices >>=
+  fmap sequence . mapM (parseFromString' (mconcat <$> many plain))
+
+-- Parse a multiline table row and return a list of blocks (columns).
+multilineRow :: PandocMonad m
+             => [Int]
+             -> MarkdownParser m (F [Blocks])
+multilineRow indices = do
+  colLines <- many1 (rawTableLine indices)
+  let cols = map T.unlines $ transpose colLines
+  fmap sequence $ mapM (parseFromString' (mconcat <$> many plain)) cols
+
+-- Parses a table caption:  inlines beginning with 'Table:'
+-- and followed by blank lines.
+tableCaption :: PandocMonad m => MarkdownParser m (F Inlines, Attr)
+tableCaption = do
+  guardEnabled Ext_table_captions
+  try $ do
+    skipNonindentSpaces
+    (string ":" <* notFollowedBy (satisfy isPunctuation)) <|>
+      (oneOf ['T','t'] >> string "able:")
+    let attributes' = guardEnabled Ext_table_attributes *> attributes
+    ils <- trimInlinesF . mconcat <$>
+               many (notFollowedBy (attributes' *> blanklines) *> inline)
+    attr <- option nullAttr attributes'
+    blanklines
+    pure (ils, attr)
+
+-- Parse a simple table with '---' header and one line per row.
+simpleTable :: PandocMonad m
+            => Bool  -- ^ Headerless table
+            -> MarkdownParser m (F TableComponents)
+simpleTable headless = do
+  tableComponents <-
+       tableWith' NormalizeHeader
+              (simpleTableHeader headless) tableLine
+              (return ())
+              (if headless then tableFooter else tableFooter <|> blanklines')
+  -- All columns in simple tables have default widths.
+  let useDefaultColumnWidths tc =
+        let cs' = map (Bifunctor.second (const ColWidthDefault)) $
+                   tableColSpecs tc
+        in tc {tableColSpecs = cs'}
+  return $ useDefaultColumnWidths <$> tableComponents
+
+-- Parse a multiline table:  starts with row of '-' on top, then header
+-- (which may be multiline), then the rows,
+-- which may be multiline, separated by blank lines, and
+-- ending with a footer (dashed line followed by blank line).
+multilineTable :: PandocMonad m
+               => Bool -- ^ Headerless table
+               -> MarkdownParser m (F TableComponents)
+multilineTable headless =
+  tableWith' NormalizeHeader (multilineTableHeader headless)
+             multilineRow blanklines tableFooter
+
+multilineTableHeader :: PandocMonad m
+                     => Bool -- ^ Headerless table
+                     -> MarkdownParser m (F [[Blocks]], [Alignment], [Int])
+multilineTableHeader headless = try $ do
+  unless headless $
+     tableSep >> notFollowedBy blankline
+  rawContent  <- if headless
+                    then return $ repeat ""
+                    else many1 $ notFollowedBy tableSep >> anyLine
+  initSp      <- nonindentSpaces
+  dashes      <- many1 (dashedLine '-')
+  newline
+  let (lengths, lines') = unzip dashes
+  let indices  = scanl (+) (T.length initSp) lines'
+  -- compensate for the fact that intercolumn spaces are
+  -- not included in the last index:
+  let indices' = case reverse indices of
+                      []     -> []
+                      (x:xs) -> reverse (x+1:xs)
+  rawHeadsList <- if headless
+                     then map (:[]) . drop 1 . splitTextByIndices (init indices')
+                          <$> lookAhead anyLine
+                     else return $ transpose $ map
+                           (drop 1 . splitTextByIndices (init indices'))
+                           rawContent
+  let aligns   = zipWith alignType rawHeadsList lengths
+  let rawHeads = if headless
+                    then []
+                    else map (T.unlines . map trim) rawHeadsList
+  heads <- fmap sequence $
+            mapM (parseFromString' (mconcat <$> many plain).trim) rawHeads
+  return (fmap (:[]) heads, aligns, indices')
+
+-- Parse a grid table:  starts with row of '-' on top, then header
+-- (which may be grid), then the rows,
+-- which may be grid, separated by blank lines, and
+-- ending with a footer (dashed line followed by blank line).
+gridTable :: PandocMonad m
+          => MarkdownParser m (F TableComponents)
+gridTable = try $ do
+  -- Like other block-level constructs, a grid table may be indented by
+  -- up to three spaces.  The underlying grid-table parser expects the
+  -- table to begin at the left margin, so strip a uniform indentation
+  -- from every line before handing it off.
+  indent <- T.length <$> lookAhead nonindentSpaces
+  if indent == 0
+     then gridTableWith' NormalizeHeader parseBlocks
+     else do
+       let gridLine = try $ count indent (char ' ')
+                              *> lookAhead (oneOf "+|")
+                              *> anyLineNewline
+       rawTable <- T.concat <$> many1 gridLine
+       parseFromString' (gridTableWith' NormalizeHeader parseBlocks) rawTable
+
+pipeBreak :: PandocMonad m => MarkdownParser m ([Alignment], [Int])
+pipeBreak = try $ do
+  nonindentSpaces
+  openPipe <- (True <$ char '|') <|> return False
+  first <- pipeTableHeaderPart
+  rest <- many $ sepPipe *> pipeTableHeaderPart
+  closePipe <- (True <$ char '|') <|> return False
+  -- at least one pipe needed for a one-column table:
+  guard $ not (null rest && not (openPipe || closePipe))
+  blankline
+  return $ unzip (first:rest)
+
+pipeTable :: PandocMonad m => MarkdownParser m (F TableComponents)
+pipeTable = try $ do
+  nonindentSpaces
+  lookAhead nonspaceChar
+  (heads,(aligns, seplengths)) <- (,) <$> pipeTableRow <*> pipeBreak
+  let cellContents = parseFromString' pipeTableCell . trim
+  let numcols = length aligns
+  let heads' = take numcols heads
+  lines' <- many pipeTableRow
+  let lines'' = map (take numcols) lines'
+  let lineWidths = map (sum . map realLength) (heads' : lines'')
+  columns <- getOption readerColumns
+  -- add numcols + 1 for the pipes themselves
+  let widths = if maximumBounded (sum seplengths : lineWidths) + (numcols + 1)
+                  > columns
+                  then map (\len ->
+                         fromIntegral len / fromIntegral (sum seplengths))
+                         seplengths
+                  else replicate (length aligns) 0.0
+  (headCells :: F [Blocks]) <- sequence <$> mapM cellContents heads'
+  (rows :: F [[Blocks]]) <- sequence <$>
+                            mapM (fmap sequence . mapM cellContents) lines''
+  return $
+    toTableComponents' NormalizeHeader aligns widths <$> fmap (:[]) headCells <*> rows
+
+sepPipe :: PandocMonad m => MarkdownParser m ()
+sepPipe = try $ do
+  char '|' <|> char '+'
+  notFollowedBy blankline
+
+-- parse a row, returning raw cell contents
+pipeTableRow :: PandocMonad m => MarkdownParser m [Text]
+pipeTableRow = try $ do
+  scanForPipe
+  skipMany spaceChar
+  openPipe <- (True <$ char '|') <|> return False
+  -- split into cells
+  let chunk = void (code <|> math <|> rawHtmlInline <|>
+                    escapedChar <|> rawLaTeXInline')
+       <|> void (noneOf "|\n\r")
+  cells <- (snd <$> withRaw (many chunk)) `sepBy1` char '|'
+  closePipe <- (True <$ char '|') <|> return False
+  -- at least one pipe needed for a one-column table:
+  guard $ not (length cells == 1 && not (openPipe || closePipe))
+  blankline
+  return cells
+
+pipeTableCell :: PandocMonad m => MarkdownParser m (F Blocks)
+pipeTableCell =
+  (do result <- inlines1
+      return $ B.plain <$> result)
+    <|> return mempty
+
+pipeTableHeaderPart :: PandocMonad m => ParsecT Sources st m (Alignment, Int)
+pipeTableHeaderPart = try $ do
+  skipMany spaceChar
+  left <- optionMaybe (char ':')
+  pipe <- many1 (char '-')
+  right <- optionMaybe (char ':')
+  skipMany spaceChar
+  let len = length pipe + maybe 0 (const 1) left + maybe 0 (const 1) right
+  return
+    (case (left,right) of
+      (Nothing,Nothing) -> AlignDefault
+      (Just _,Nothing)  -> AlignLeft
+      (Nothing,Just _)  -> AlignRight
+      (Just _,Just _)   -> AlignCenter, len)
+
+-- Succeed only if current line contains a pipe.
+scanForPipe :: PandocMonad m => ParsecT Sources st m ()
+scanForPipe = do
+  Sources inps <- getInput
+  let ln = case inps of
+             [] -> ""
+             ((_,t):(_,t'):_) | T.null t -> t'
+             ((_,t):_) -> t
+  case T.break (\c -> c == '\n' || c == '|') ln of
+       (_, T.uncons -> Just ('|', _)) -> return ()
+       _                              -> mzero
+
+table :: PandocMonad m => MarkdownParser m (F Blocks)
+table = try $ do
+  (frontCaption, frontAttr) <- option (Nothing, nullAttr)
+                               (Bifunctor.first Just <$> tableCaption)
+  tableComponents <-
+         (guardEnabled Ext_pipe_tables >> try (scanForPipe >> pipeTable)) <|>
+         (guardEnabled Ext_multiline_tables >> try (multilineTable False)) <|>
+         (guardEnabled Ext_simple_tables >>
+                try (simpleTable True <|> simpleTable False)) <|>
+         (guardEnabled Ext_multiline_tables >>
+                try (multilineTable True)) <|>
+         (guardEnabled Ext_grid_tables >>
+                try gridTable) <?> "table"
+  optional blanklines
+  (caption, attr) <- case frontCaption of
+                        Nothing -> option (return mempty, nullAttr) tableCaption
+                        Just c  -> return (c, frontAttr)
+  return $ do
+    caption' <- caption
+    (TableComponents _attr _capt colspecs th tb tf) <- tableComponents
+    return $ B.tableWith attr
+                (B.simpleCaption $ B.plain caption') colspecs th tb tf
+
+--
+-- inline
+--
+
+inlines :: PandocMonad m => MarkdownParser m (F Inlines)
+inlines = mconcat <$> many inline
+
+inlines1 :: PandocMonad m => MarkdownParser m (F Inlines)
+inlines1 = mconcat <$> many1 inline
+
+inline :: PandocMonad m => MarkdownParser m (F Inlines)
+inline = do
+  c <- lookAhead anyChar
+  ((case c of
+     ' '     -> whitespace
+     '\t'    -> whitespace
+     '\n'    -> endline
+     '`'     -> code
+     '_'     -> strongOrEmph
+     '*'     -> strongOrEmph
+     '^'     -> inlineNote <|> superscript
+     '['     -> note <|> cite <|> bracketedSpan <|> wikilink B.linkWith <|> link
+     '!'     -> image
+     '$'     -> math
+     '~'     -> strikeout <|> subscript
+     '='     -> mark
+     '<'     -> autoLink <|> spanHtml <|> rawHtmlInline <|> ltSign
+     '\\'    -> math <|> escapedNewline <|> escapedChar <|> rawLaTeXInline'
+     '@'     -> cite <|> exampleRef
+     '"'     -> smart
+     '\''    -> smart
+     '\8216' -> smart
+     '\145'  -> smart
+     '\8220' -> smart
+     '\147'  -> smart
+     '-'     -> cite <|> smart
+     '.'     -> smart
+     '&'     -> return . B.singleton <$> charRef
+     ':'     -> emoji
+     _       -> mzero)
+   <|> bareURL
+   <|> str
+   <|> symbol) <?> "inline"
+
+escapedChar' :: PandocMonad m => MarkdownParser m Char
+escapedChar' = try $ do
+  char '\\'
+  (guardEnabled Ext_all_symbols_escapable >>
+     satisfy (\c -> c /= '\n' && c /= '\r' && not (isAlphaNum c)))
+     <|> (guardEnabled Ext_angle_brackets_escapable >>
+            oneOf "\\`*_{}[]()>#+-.!~\"<>")
+     <|> oneOf "\\`*_{}[]()>#+-.!"
+
+escapedNewline :: PandocMonad m => MarkdownParser m (F Inlines)
+escapedNewline = do
+  guardEnabled Ext_escaped_line_breaks
+  try $ do
+    char '\\'
+    lookAhead (char '\n') -- don't consume the newline (see #3730)
+    return $ return B.linebreak
+
+escapedChar :: PandocMonad m => MarkdownParser m (F Inlines)
+escapedChar = do
+  result <- escapedChar'
+  case result of
+       ' ' -> return $ return $ B.str "\160" -- "\ " is a nonbreaking space
+       _   -> return $ return $ B.str $ T.singleton result
+
+ltSign :: PandocMonad m => MarkdownParser m (F Inlines)
+ltSign = do
+  guardDisabled Ext_raw_html
+    <|> (notFollowedByHtmlCloser >> notFollowedBy' (htmlTag isBlockTag))
+  char '<'
+  return $ return $ B.str "<"
+
+-- Note that if the citations extension is enabled, example refs will be
+-- parsed as citations, and handled by a clause in the parser for citations,
+-- since we won't know whether we have an example ref until the
+-- whole document has been parsed.  But we need this parser
+-- here in case citations is disabled.
+exampleRef :: PandocMonad m => MarkdownParser m (F Inlines)
+exampleRef = do
+  guardEnabled Ext_example_lists
+  try $ do
+    char '@'
+    lab <- T.pack . concat <$>
+                      many (many1 alphaNum <|>
+                            try (do c <- char '_' <|> char '-'
+                                    cs <- many1 alphaNum
+                                    return (c:cs)))
+    return $ do
+      st <- askF
+      return $ case M.lookup lab (stateExamples st) of
+                    Just n  -> B.str $ tshow n
+                    Nothing -> B.str $ "@" <> lab
+
+symbol :: PandocMonad m => MarkdownParser m (F Inlines)
+symbol = do
+  result <- noneOf "<\\\n\t "
+         <|> try (do lookAhead $ char '\\'
+                     notFollowedBy' (() <$ rawTeXBlock)
+                     char '\\')
+  return $ return $ B.str $! T.singleton result
+
+-- parses inline code, between n `s and n `s
+code :: PandocMonad m => MarkdownParser m (F Inlines)
+code = try $ do
+  starts <- many1 (char '`')
+  skipSpaces
+  result <- trim . T.concat
+        <$> manyTill
+              (   many1Char (noneOf "`\n")
+              <|> many1Char (char '`')
+              <|> (char '\n'
+                    >> notFollowedBy (inList >> listStart)
+                    >> notFollowedBy' blankline
+                    >> return " "))
+              (try $ skipSpaces
+                  >> count (length starts) (char '`')
+                  >> notFollowedBy (char '`'))
+  rawattr <-
+     (Left <$> (guardEnabled Ext_raw_attribute >> try rawAttribute))
+    <|>
+     (Right <$> option ("",[],[])
+         (guardEnabled Ext_inline_code_attributes >> try attributes))
+  return $ return $
+    case rawattr of
+         Left syn   -> B.rawInline syn $! result
+         Right attr -> B.codeWith attr $! result
+
+math :: PandocMonad m => MarkdownParser m (F Inlines)
+math =  (return . B.displayMath <$> (mathDisplay >>= applyMacros))
+     <|> (return . B.math <$> (mathInline >>= applyMacros)) <+?>
+               (guardEnabled Ext_smart *> (return <$> apostrophe)
+                <* notFollowedBy (space <|> satisfy isPunctuation))
+
+-- Parses material enclosed in *s, **s, _s, or __s.
+-- Designed to avoid backtracking.
+enclosure :: PandocMonad m
+          => Char
+          -> MarkdownParser m (F Inlines)
+enclosure c = do
+  -- we can't start an enclosure with _ if after a string and
+  -- the intraword_underscores extension is enabled:
+  guardDisabled Ext_intraword_underscores
+    <|> guard (c == '*')
+    <|> (guard =<< notAfterString)
+  cs <- many1Char (char c)
+  (return (B.str cs) <>) <$> whitespace
+    <|>
+        case T.length cs of
+             3 -> three c
+             2 -> two   c mempty
+             1 -> one   c mempty
+             _ -> return (return $ B.str cs)
+
+ender :: PandocMonad m => Char -> Int -> MarkdownParser m ()
+ender c n = try $ do
+  count n (char c)
+  guard (c == '*')
+    <|> guardDisabled Ext_intraword_underscores
+    <|> notFollowedBy alphaNum
+
+-- Parse inlines til you hit one c or a sequence of two cs.
+-- If one c, emit emph and then parse two.
+-- If two cs, emit strong and then parse one.
+-- Otherwise, emit ccc then the results.
+three :: PandocMonad m => Char -> MarkdownParser m (F Inlines)
+three c = do
+  contents <- mconcat <$> many (notFollowedBy (ender c 1) >> inline)
+  (ender c 3 >> updateLastStrPos >> return (B.strong . B.emph <$> contents))
+    <|> (ender c 2 >> updateLastStrPos >> one c (B.strong <$> contents))
+    <|> (ender c 1 >> updateLastStrPos >> two c (B.emph <$> contents))
+    <|> return (return (B.str $ T.pack [c,c,c]) <> contents)
+
+-- Parse inlines til you hit two c's, and emit strong.
+-- If you never do hit two cs, emit ** plus inlines parsed.
+two :: PandocMonad m => Char -> F Inlines -> MarkdownParser m (F Inlines)
+two c prefix' = do
+  contents <- mconcat <$> many (try $ notFollowedBy (ender c 2) >> inline)
+  (ender c 2 >> updateLastStrPos >>
+                return (B.strong <$> (prefix' <> contents)))
+    <|> return (return (B.str $ T.pack [c,c]) <> (prefix' <> contents))
+
+-- Parse inlines til you hit a c, and emit emph.
+-- If you never hit a c, emit * plus inlines parsed.
+one :: PandocMonad m => Char -> F Inlines -> MarkdownParser m (F Inlines)
+one c prefix' = do
+  contents <- mconcat <$> many (  (notFollowedBy (ender c 1) >> inline)
+                           <|> try (string [c,c] >>
+                                    notFollowedBy (ender c 1) >>
+                                    two c mempty) )
+  (ender c 1 >> updateLastStrPos >> return (B.emph <$> (prefix' <> contents)))
+    <|> return (return (B.str $ T.singleton c) <> (prefix' <> contents))
+
+strongOrEmph :: PandocMonad m => MarkdownParser m (F Inlines)
+strongOrEmph =  enclosure '*' <|> enclosure '_'
+
+-- | Parses a list of inlines between start and end delimiters.
+inlinesBetween :: PandocMonad m
+               => (Show b)
+               => MarkdownParser m a
+               -> MarkdownParser m b
+               -> MarkdownParser m (F Inlines)
+inlinesBetween start end =
+  trimInlinesF . mconcat <$> try (start >> many1Till inner end)
+    where inner      = innerSpace <|>
+                       (notFollowedBy' (() <$ whitespace) >> inline)
+          innerSpace = try $ whitespace <* notFollowedBy' end
+
+strikeout :: PandocMonad m => MarkdownParser m (F Inlines)
+strikeout = fmap B.strikeout <$>
+ (guardEnabled Ext_strikeout >> inlinesBetween strikeStart strikeEnd)
+    where strikeStart = string "~~" >> lookAhead nonspaceChar
+                        >> notFollowedBy (char '~')
+          strikeEnd   = try $ string "~~"
+
+mark :: PandocMonad m => MarkdownParser m (F Inlines)
+mark = fmap (B.spanWith ("",["mark"],[])) <$>
+ (guardEnabled Ext_mark >> inlinesBetween markStart markEnd)
+    where markStart = string "==" >> lookAhead nonspaceChar
+                        >> notFollowedBy (char '=')
+          markEnd   = try $ string "=="
+
+superscript :: PandocMonad m => MarkdownParser m (F Inlines)
+superscript = do
+  fmap B.superscript <$> (regularSuperscript <|> mmdShortSuperscript)
+      where
+        regularSuperscript = do
+          guardEnabled Ext_superscript
+          litBetweenNoSpace '^' '^' >>= parseFromString inlines
+        mmdShortSuperscript = try $ do
+          guardEnabled Ext_short_subsuperscripts
+          char '^'
+          result <- T.pack <$> many1 alphaNum
+          return $ return $ B.str result
+
+subscript :: PandocMonad m => MarkdownParser m (F Inlines)
+subscript = do
+  fmap B.subscript <$> (regularSubscript <|> mmdShortSubscript)
+      where
+        regularSubscript = do
+          guardEnabled Ext_subscript
+          litBetweenNoSpace '~' '~' >>= parseFromString inlines
+        mmdShortSubscript = try $ do
+          guardEnabled Ext_short_subsuperscripts
+          char '~'
+          result <- T.pack <$> many1 alphaNum
+          return $ return $ B.str result
+
+whitespace :: PandocMonad m => MarkdownParser m (F Inlines)
+whitespace = spaceChar >> return <$> (lb <|> regsp) <?> "whitespace"
+  where lb = spaceChar >> skipMany spaceChar
+                       >> option B.space (endline >> return B.linebreak)
+        regsp = skipMany spaceChar >> return B.space
+
+nonEndline :: PandocMonad m => ParsecT Sources st m Char
+nonEndline = satisfy (/='\n')
+
+str :: PandocMonad m => MarkdownParser m (F Inlines)
+str = do
+  !result <- mconcat <$> many1
+             ( T.pack <$> (many1 alphaNum)
+              <|> "." <$ try (char '.' <* notFollowedBy (char '.')) )
+  updateLastStrPos
+  (do guardEnabled Ext_smart
+      abbrevs <- getOption readerAbbreviations
+      if result `Set.member` abbrevs
+         then try (do ils <- whitespace
+                      notFollowedBy (() <$ cite <|> () <$ note)
+                      -- ?? lookAhead alphaNum
+                      -- replace space after with nonbreaking space
+                      -- if softbreak, move before abbrev if possible (#4635)
+                      return $ do
+                        ils' <- ils
+                        case B.toList ils' of
+                             [Space] ->
+                                 return $! (B.str result <> B.str "\160")
+                             _ -> return $! (B.str result <> ils'))
+                <|> return (return $! B.str result)
+         else return (return $! B.str result))
+     <|> return (return $! B.str result)
+
+-- an endline character that can be treated as a space, not a structural break
+endline :: PandocMonad m => MarkdownParser m (F Inlines)
+endline = try $ do
+  newline
+  notFollowedBy blankline
+  getState >>= guard . stateAllowLineBreaks
+  -- parse potential list-starts differently if in a list:
+  notFollowedBy (inList >> listStart)
+  guardDisabled Ext_lists_without_preceding_blankline <|> notFollowedBy listStart
+  guardEnabled Ext_blank_before_blockquote <|> notFollowedBy emailBlockQuoteStart
+  guardEnabled Ext_blank_before_header <|> (notFollowedBy . char =<< atxChar) -- atx header
+  guardDisabled Ext_backtick_code_blocks <|>
+     notFollowedBy (() <$ (lookAhead (char '`') >> codeBlockFenced))
+  notFollowedByHtmlCloser
+  notFollowedByDivCloser
+  (eof >> return mempty)
+    <|> (guardEnabled Ext_hard_line_breaks >> return (return B.linebreak))
+    <|> (guardEnabled Ext_ignore_line_breaks >> return mempty)
+    <|> (skipMany spaceChar >> return (return B.softbreak))
+
+--
+-- links
+--
+
+-- a reference label for a link
+reference :: PandocMonad m => MarkdownParser m (F Inlines, Text)
+reference = do
+  guardDisabled Ext_footnotes <|> notFollowedBy' noteMarker
+  withRaw $ trimInlinesF <$> inBalancedBrackets inlines
+
+-- source for a link, with optional title
+source :: PandocMonad m => MarkdownParser m (Text, Text)
+source = do
+  char '('
+  skipSpaces
+  let parenthesizedChars = do
+        result <- charsInBalanced '(' ')' litChar
+        return $ "(" <> result <> ")"
+  let linkTitle' = try $ spnl >> linkTitle
+  let urlChunk = do
+        try parenthesizedChars
+          <|> (notFollowedBy (oneOf "\n\r )") >> litChar)
+          <|> (lookAhead (oneOf "\n\r") >> notFollowedBy linkTitle' >> litChar)
+          <|> try (many1Char spaceChar <* notFollowedBy (oneOf "\"')"))
+  let sourceURL = T.unwords . T.words . T.concat <$> many urlChunk
+  src <- try (litBetween '<' '>') <|> try base64DataURI <|> sourceURL
+  tit <- option "" linkTitle'
+  skipSpaces
+  char ')'
+  return (escapeURI $ trimr src, tit)
+
+base64DataURI :: PandocMonad m => ParsecT Sources s m Text
+base64DataURI = do
+  Sources ((pos, txt):rest) <- getInput
+  let r = A.parse (fst <$> A.match pBase64DataURI) txt
+  case r of
+    A.Done remaining consumed -> do
+      let pos' = incSourceColumn pos (T.length consumed)
+      setInput $ Sources ((pos', remaining):rest)
+      return consumed
+    _ -> mzero
+
+linkTitle :: PandocMonad m => MarkdownParser m Text
+linkTitle = quotedTitle '"' <|> quotedTitle '\''
+
+wikilink :: PandocMonad m
+  => (Attr -> Text -> Text -> Inlines -> Inlines)
+  -> MarkdownParser m (F Inlines)
+wikilink constructor = do
+  let attr = (mempty, ["wikilink"], mempty)
+  titleAfter <-
+    (True <$ guardEnabled Ext_wikilinks_title_after_pipe) <|>
+    (False <$ guardEnabled Ext_wikilinks_title_before_pipe)
+  try $ do
+    string "[[" *> notFollowedBy' (char '[')
+    raw <- many1TillChar anyChar (try $ string "]]")
+    let (title, url) = case T.break (== '|') raw of
+          (before, "") -> (before, before)
+          (before, after)
+            | titleAfter -> (T.drop 1 after, before)
+            | otherwise -> (before, T.drop 1 after)
+    guard $ T.all (\c -> c /= '\n' && c /= '\r' && c /= '\f' && c /= '\t') url
+    return . pure . constructor attr url "" $
+       B.text $ fromEntities title
+
+link :: PandocMonad m => MarkdownParser m (F Inlines)
+link = try $ do
+  st <- getState
+  guard $ stateAllowLinks st
+  setState $ st{ stateAllowLinks = False }
+  (lab,raw) <- reference
+  setState $ st{ stateAllowLinks = True }
+  regLink B.linkWith lab <|> referenceLink B.linkWith (lab,raw)
+
+bracketedSpan :: PandocMonad m => MarkdownParser m (F Inlines)
+bracketedSpan = do
+  guardEnabled Ext_bracketed_spans
+  try $ do
+    (lab,_) <- reference
+    attr <- attributes
+    return $ wrapSpan attr <$> lab
+
+-- | Given an @Attr@ value, this returns a function to wrap the contents
+-- of a span. Handles special classes (@smallcaps@, @ul@, @underline@)
+-- and uses the respective constructors to handle them.
+wrapSpan :: Attr -> Inlines -> Inlines
+wrapSpan (ident, classes, kvs) =
+  let (initConst, kvs') = case lookup "style" kvs of
+        Just s | isSmallCapsFontVariant s ->
+                   let kvsNoStyle =  [(k, v) | (k, v) <- kvs, k /= "style"]
+                   in (Just B.smallcaps, kvsNoStyle)
+        _ -> (Nothing, kvs)
+      (mConstr, remainingClasses) = foldr go (initConst, []) classes
+      wrapInConstr c = maybe c (c .)
+      go cls (accConstr, other) =
+        case cls of
+          "smallcaps" -> (Just $ wrapInConstr B.smallcaps accConstr, other)
+          "ul"        -> (Just $ wrapInConstr B.underline accConstr, other)
+          "underline" -> (Just $ wrapInConstr B.underline accConstr, other)
+          _           -> (accConstr, cls:other)
+  in case (ident, remainingClasses, kvs') of
+       ("", [], []) -> fromMaybe (B.spanWith nullAttr) mConstr
+       attr         -> wrapInConstr (B.spanWith attr) mConstr
+
+isSmallCapsFontVariant :: Text -> Bool
+isSmallCapsFontVariant s =
+  T.toLower (T.filter (\c -> c /= ' ' && c /= '\t' && c /= ';') s) ==
+  "font-variant:small-caps"
+
+regLink :: PandocMonad m
+        => (Attr -> Text -> Text -> Inlines -> Inlines)
+        -> F Inlines
+        -> MarkdownParser m (F Inlines)
+regLink constructor lab = try $ do
+  (!src, !tit) <- source
+  rebase <- option False (True <$ guardEnabled Ext_rebase_relative_paths)
+  pos <- getPosition
+  let !src' = if rebase then rebasePath pos src else src
+  !attr <- option nullAttr $ guardEnabled Ext_link_attributes >> attributes
+  return $ constructor attr src' tit <$> lab
+
+-- a link like [this][ref] or [this][] or [this]
+referenceLink :: PandocMonad m
+              => (Attr -> Text -> Text -> Inlines -> Inlines)
+              -> (F Inlines, Text)
+              -> MarkdownParser m (F Inlines)
+referenceLink constructor (lab, raw) = do
+  sp <- (True <$ lookAhead (char ' ')) <|> return False
+  (_,!raw') <- option (mempty, "") $
+      lookAhead (try (do guardEnabled Ext_citations
+                         guardDisabled Ext_spaced_reference_links <|> spnl
+                         normalCite
+                         return (mempty, "")))
+      <|>
+      try ((guardDisabled Ext_spaced_reference_links <|> spnl) >> reference)
+  when (raw' == "") $ guardEnabled Ext_shortcut_reference_links
+  !attr <- option nullAttr $ guardEnabled Ext_link_attributes >> attributes
+  let !labIsRef = raw' == "" || raw' == "[]"
+  let (exclam, rawsuffix) =
+        case T.uncons raw of
+          Just ('!', rest) -> (True, rest)
+          _ -> (False, raw)
+  let !key = toKey $ if labIsRef then rawsuffix else raw'
+  parsedRaw <- parseFromString' inlines raw'
+  fallback  <- parseFromString' inlines $ if exclam
+                                             then rawsuffix
+                                             else dropBrackets rawsuffix
+  implicitHeaderRefs <- option False $
+                         True <$ guardEnabled Ext_implicit_header_references
+  let makeFallback = do
+       parsedRaw' <- parsedRaw
+       fallback' <- fallback
+       return $ (if exclam
+                    then "!" <> fallback'
+                    else B.str "[" <> fallback' <> B.str "]") <>
+                (if sp && not (T.null raw) then B.space else mempty) <>
+                parsedRaw'
+  return $ do
+    keys <- asksF stateKeys
+    case M.lookup key keys of
+       Nothing        ->
+         if implicitHeaderRefs
+            then do
+              headerKeys <- asksF stateHeaderKeys
+              case M.lookup key headerKeys of
+                   Just ((src, tit), _) -> constructor attr src tit <$> lab
+                   Nothing              -> makeFallback
+            else makeFallback
+       Just ((src,tit), defattr) ->
+           constructor (combineAttr attr defattr) src tit <$> lab
+
+dropBrackets :: Text -> Text
+dropBrackets = dropRB . dropLB
+  where dropRB (T.unsnoc -> Just (xs,']')) = xs
+        dropRB xs                          = xs
+        dropLB (T.uncons -> Just ('[',xs)) = xs
+        dropLB xs                          = xs
+
+bareURL :: PandocMonad m => MarkdownParser m (F Inlines)
+bareURL = do
+  guardEnabled Ext_autolink_bare_uris
+  getState >>= guard . stateAllowLinks
+  try $ do
+    (cls, (orig, src)) <- (("uri",) <$> uri) <|> (("email",) <$> emailAddress)
+    notFollowedBy $ try $ spaces >> htmlTag (~== TagClose ("a" :: Text))
+    return $ return $ B.linkWith ("",[cls],[]) src "" (B.str orig)
+
+autoLink :: PandocMonad m => MarkdownParser m (F Inlines)
+autoLink = try $ do
+  getState >>= guard . stateAllowLinks
+  char '<'
+  (cls, (orig, src)) <- (("uri",) <$> uri) <|> (("email",) <$> emailAddress)
+  -- in rare cases, something may remain after the uri parser
+  -- is finished, because the uri parser tries to avoid parsing
+  -- final punctuation.  for example:  in `<http://hi---there>`,
+  -- the URI parser will stop before the dashes.
+  extra <- fromEntities <$> manyTillChar nonspaceChar (char '>')
+  attr  <- option ("", [cls], []) $ try $
+            guardEnabled Ext_link_attributes >> attributes
+  return $ return $ B.linkWith attr (src <> escapeURI extra) ""
+                     (B.str $ orig <> extra)
+
+-- | Rebase a relative path, by adding the (relative) directory
+-- of the containing source position.  Absolute links and URLs
+-- are untouched.
+rebasePath :: SourcePos -> Text -> Text
+rebasePath pos path = do
+  let fp = sourceName pos
+      isFragment = T.take 1 path == "#"
+      path' = T.unpack path
+      isAbsolutePath = Posix.isAbsolute path' || Windows.isAbsolute path'
+   in if T.null path || isFragment || isAbsolutePath || isURI path
+         then path
+         else
+           case takeDirectory fp of
+             ""  -> path
+             "." -> path
+             d   -> T.pack d <> "/" <> path
+
+image :: PandocMonad m => MarkdownParser m (F Inlines)
+image = try $ do
+  char '!'
+  wikilink B.imageWith <|>
+    do (lab,raw) <- reference
+       defaultExt <- getOption readerDefaultImageExtension
+       let constructor attr' src
+             | "data:" `T.isPrefixOf` src = B.imageWith attr' src  -- see #9118
+             | otherwise =
+                case takeExtension (T.unpack src) of
+                   "" -> B.imageWith attr' (T.pack $ addExtension (T.unpack src)
+                                                   $ T.unpack defaultExt)
+                   _  -> B.imageWith attr' src
+       regLink constructor lab <|> referenceLink constructor (lab, "!" <> raw)
+
+note :: PandocMonad m => MarkdownParser m (F Inlines)
+note = try $ do
+  guardEnabled Ext_footnotes
+  ref <- noteMarker
+  updateState $ \st -> st{ stateNoteRefs = Set.insert ref (stateNoteRefs st)
+                         , stateNoteNumber = stateNoteNumber st + 1 }
+  noteNum <- stateNoteNumber <$> getState
+  return $ do
+    notes <- asksF stateNotes'
+    case M.lookup ref notes of
+        Nothing       -> return $ B.str $ "[^" <> ref <> "]"
+        Just (_pos, contents) -> do
+          st <- askF
+          -- process the note in a context that doesn't resolve
+          -- notes, to avoid infinite looping with notes inside
+          -- notes:
+          let contents' = runF contents st{ stateNotes' = M.empty }
+          let addCitationNoteNum c@Citation{} =
+                c{ citationNoteNum = noteNum }
+          let adjustCite (Cite cs ils) =
+                Cite (map addCitationNoteNum cs) ils
+              adjustCite x = x
+          return $ B.note $ walk adjustCite contents'
+
+inlineNote :: PandocMonad m => MarkdownParser m (F Inlines)
+inlineNote = do
+  guardEnabled Ext_inline_notes
+  try $ do
+    char '^'
+    updateState $ \st -> st{ stateInNote = True
+                           , stateNoteNumber = stateNoteNumber st + 1 }
+    contents <- withQuoteContext NoQuote $ inBalancedBrackets inlines
+    notFollowedBy (char '(' <|> char '[' <|> ('{' <$ attributes))
+      -- ^[link](foo)^ is superscript
+    updateState $ \st -> st{ stateInNote = False }
+    return $ B.note . B.para <$> contents
+
+rawLaTeXInline' :: PandocMonad m => MarkdownParser m (F Inlines)
+rawLaTeXInline' = do
+  guardEnabled Ext_raw_tex
+  notFollowedBy' rawConTeXtEnvironment
+  !s <- rawLaTeXInline
+  return $ return $ B.rawInline "tex" s -- "tex" because it might be context
+
+rawConTeXtEnvironment :: PandocMonad m => ParsecT Sources st m Text
+rawConTeXtEnvironment = try $ do
+  string "\\start"
+  completion <- inBrackets (letter <|> digit <|> spaceChar)
+               <|> many1Char letter
+  !contents <- manyTill (rawConTeXtEnvironment <|> countChar 1 anyChar)
+                       (try $ string "\\stop" >> textStr completion)
+  return $! "\\start" <> completion <> T.concat contents <> "\\stop" <> completion
+
+inBrackets :: PandocMonad m => ParsecT Sources st m Char -> ParsecT Sources st m Text
+inBrackets parser = do
+  char '['
+  contents <- manyChar parser
+  char ']'
+  return $! "[" <> contents <> "]"
+
+spanHtml :: PandocMonad m => MarkdownParser m (F Inlines)
+spanHtml = do
+  guardEnabled Ext_native_spans
+  try $ do
+    (TagOpen _ attrs, _) <- htmlTag (~== TagOpen ("span" :: Text) [])
+    contents <- mconcat <$> manyTill inline (htmlTag (~== TagClose ("span" :: Text)))
+    let ident = fromMaybe "" $ lookup "id" attrs
+    let classes = maybe [] T.words $ lookup "class" attrs
+    let keyvals = [(k,v) | (k,v) <- attrs, k /= "id" && k /= "class"]
+    return $ wrapSpan (ident, classes, keyvals) <$> contents
+
+divHtml :: PandocMonad m => MarkdownParser m (F Blocks)
+divHtml = do
+  guardEnabled Ext_native_divs
+  try $ do
+    openpos <- getPosition
+    (TagOpen _ attrs, _) <- htmlTag (~== TagOpen ("div" :: Text) [])
+    -- we set stateInHtmlBlock so that closing tags that can be either block
+    -- or inline will not be parsed as inline tags
+    oldInHtmlBlock <- stateInHtmlBlock <$> getState
+    updateState $ \st -> st{ stateInHtmlBlock = Just "div" }
+    optional blanklines
+    contents <- mconcat <$>
+                many (notFollowedBy' (htmlTag (~== TagClose ("div" :: Text)))
+                      >> block)
+    void (htmlTag (~== TagClose ("div" :: Text))) <|>
+       (getPosition >>= report . UnclosedDiv openpos)
+    let ident = fromMaybe "" $ lookup "id" attrs
+    let classes = maybe [] T.words $ lookup "class" attrs
+    let keyvals = [(k,v) | (k,v) <- attrs, k /= "id" && k /= "class"]
+    updateState $ \st -> st{ stateInHtmlBlock = oldInHtmlBlock }
+    return $ B.divWith (ident, classes, keyvals) <$> contents
+
+divFenced :: PandocMonad m => MarkdownParser m (F Blocks)
+divFenced = do
+  guardEnabled Ext_fenced_divs
+  try $ do
+    openpos <- getPosition
+    string ":::"
+    skipMany (char ':')
+    skipMany spaceChar
+    attribs <- attributes <|> ((\x -> ("",[x],[])) <$> many1Char nonspaceChar)
+    skipMany spaceChar
+    skipMany (char ':')
+    blankline
+    updateState $ \st ->
+      st{ stateFencedDivLevel = stateFencedDivLevel st + 1 }
+    bs <- mconcat <$> many (notFollowedBy divFenceEnd >> block)
+    divFenceEnd <|> (getPosition >>= report . UnclosedDiv openpos)
+    updateState $ \st ->
+      st{ stateFencedDivLevel = stateFencedDivLevel st - 1 }
+    return $ B.divWith attribs <$> bs
+
+divFenceEnd :: PandocMonad m => MarkdownParser m ()
+divFenceEnd = try $ do
+  string ":::"
+  skipMany (char ':')
+  blanklines
+  return ()
+
+rawHtmlInline :: PandocMonad m => MarkdownParser m (F Inlines)
+rawHtmlInline = do
+  guardEnabled Ext_raw_html
+  inHtmlBlock <- stateInHtmlBlock <$> getState
+  let isCloseBlockTag t = case inHtmlBlock of
+                               Just t' -> t ~== TagClose t'
+                               Nothing -> False
+  mdInHtml <- option False $
+                (    guardEnabled Ext_markdown_in_html_blocks
+                 <|> guardEnabled Ext_markdown_attribute
+                ) >> return True
+  (_,result) <- htmlTag $ if mdInHtml
+                             then (\x -> isInlineTag x &&
+                                         not (isCloseBlockTag x))
+                             else not . isTextTag
+  return $ if T.all isSpace result
+              then return mempty
+              else return $ B.rawInline "html" result
+
+-- Emoji
+
+emoji :: PandocMonad m => MarkdownParser m (F Inlines)
+emoji = do
+  guardEnabled Ext_emoji
+  try $ do
+    char ':'
+    emojikey <- many1Char (alphaNum <|> oneOf "_+-")
+    char ':'
+    case emojiToInline emojikey of
+      Just i -> return (return $ B.singleton i)
+      Nothing -> mzero
+
+-- Citations
+
+cite :: PandocMonad m => MarkdownParser m (F Inlines)
+cite = do
+  guardEnabled Ext_citations
+  -- We only use stateNoteNumber for assigning citationNoteNum,
+  -- so we just assume that all citations produce notes.
+  -- citationNoteNum doesn't affect non-note styles.
+  inNote <- stateInNote <$> getState
+  unless inNote $
+    updateState $ \st -> st{ stateNoteNumber = stateNoteNumber st + 1 }
+  textualCite
+            <|> do (cs, raw) <- withRaw normalCite
+                   return $ flip B.cite (B.text raw) <$> cs
+
+textualCite :: PandocMonad m => MarkdownParser m (F Inlines)
+textualCite = try $ do
+  (suppressAuthor, key) <- citeKey True
+  -- If this is a reference to an earlier example list item,
+  -- then don't parse it as a citation.  If the example list
+  -- item comes later, we'll parse it here and figure out in
+  -- the runF stage if it's a citation.  But it helps with
+  -- issue #6836 to filter out known example list references
+  -- at this stage, so that we don't increment stateNoteNumber.
+  getState >>= guard . isNothing . M.lookup key . stateExamples
+  noteNum <- stateNoteNumber <$> getState
+  let first = Citation{ citationId      = key
+                      , citationPrefix  = []
+                      , citationSuffix  = []
+                      , citationMode    = if suppressAuthor
+                                             then SuppressAuthor
+                                             else AuthorInText
+                      , citationNoteNum = noteNum
+                      , citationHash    = 0
+                      }
+  (do -- parse [braced] material after author-in-text cite
+      (cs, raw) <- withRaw $
+                        (fmap (first:) <$> try (spnl *> normalCite))
+                    <|> bareloc first
+      let (spaces',raw') = T.span isSpace raw
+          spc | T.null spaces' = mempty
+              | otherwise      = B.space
+      lab <- parseFromString' inlines $ dropBrackets raw'
+      fallback <- referenceLink B.linkWith (lab,raw')
+      -- undo any incrementing of stateNoteNumber from last step:
+      updateState $ \st -> st{ stateNoteNumber = noteNum }
+      return $ do
+        fallback' <- fallback
+        cs' <- cs
+        return $
+          case B.toList fallback' of
+            Link{}:_ -> B.cite [first] (B.str $ "@" <> key) <> spc <> fallback'
+            _        -> B.cite cs' (B.text $ "@" <> key <> " " <> raw))
+    <|> -- no braced material
+        return (do st <- askF
+                   return $ case M.lookup key (stateExamples st) of
+                            Just n -> B.str $ tshow n
+                            _      -> B.cite [first] $ B.str $ "@" <> key)
+
+bareloc :: PandocMonad m => Citation -> MarkdownParser m (F [Citation])
+bareloc c = try $ do
+  spnl
+  char '['
+  notFollowedBy $ char '^'
+  suff <- suffix
+  rest <- option (return []) $ try $ char ';' >> spnl >> citeList
+  spnl
+  char ']'
+  notFollowedBy $ oneOf "[({"
+  return $ do
+    suff' <- suff
+    rest' <- rest
+    return $ c{ citationSuffix = B.toList suff' } : rest'
+
+normalCite :: PandocMonad m => MarkdownParser m (F [Citation])
+normalCite = try $ do
+  char '['
+  spnl
+  citations <- citeList
+  spnl
+  char ']'
+  -- not a link or a bracketed span
+  notFollowedBy (try (void source) <|>
+                  (guardEnabled Ext_bracketed_spans *> void attributes) <|>
+                  void reference)
+  return citations
+
+suffix :: PandocMonad m => MarkdownParser m (F Inlines)
+suffix = try $ do
+  hasSpace <- option False (notFollowedBy nonspaceChar >> return True)
+  spnl
+  ils <- many (notFollowedBy (oneOf ";]") >> inline)
+  let rest = trimInlinesF (mconcat ils)
+  return $ if hasSpace && not (null ils)
+              then (B.space <>) <$> rest
+              else rest
+
+prefix :: PandocMonad m => MarkdownParser m (F Inlines)
+prefix = trimInlinesF . mconcat <$>
+  manyTill (notFollowedBy (char ';') >> inline) (char ']'
+   <|> lookAhead
+         (try $ do optional (try (char ';' >> spnl))
+                   citeKey True
+                   return ']'))
+
+citeList :: PandocMonad m => MarkdownParser m (F [Citation])
+citeList = fmap sequence $ sepBy1 citation (try $ char ';' >> spnl)
+
+citation :: PandocMonad m => MarkdownParser m (F Citation)
+citation = try $ do
+  pref <- prefix
+  (suppress_author, key) <- citeKey True
+  suff <- suffix
+  noteNum <- stateNoteNumber <$> getState
+  return $ do
+    x <- pref
+    y <- suff
+    return Citation{ citationId      = key
+                   , citationPrefix  = B.toList x
+                   , citationSuffix  = B.toList y
+                   , citationMode    = if suppress_author
+                                          then SuppressAuthor
+                                          else NormalCitation
+                   , citationNoteNum = noteNum
+                   , citationHash    = 0
+                   }
+
+smart :: PandocMonad m => MarkdownParser m (F Inlines)
+smart = do
+  guardEnabled Ext_smart
+  doubleQuoted <|> singleQuoted <|> (return <$> doubleCloseQuote) <|>
+    (return <$> apostrophe) <|> (return <$> dash) <|> (return <$> ellipses)
+
+singleQuoted :: PandocMonad m => MarkdownParser m (F Inlines)
+singleQuoted = do
+  singleQuoteStart
+  (try (withQuoteContext InSingleQuote $
+    fmap B.singleQuoted . trimInlinesF . mconcat <$>
+      many1Till inline singleQuoteEnd))
+    <|> (return (return (B.str "\8217")))
+
+-- doubleQuoted will handle regular double-quoted sections, as well
+-- as dialogues with an open double-quote without a close double-quote
+-- in the same paragraph.
+doubleQuoted :: PandocMonad m => MarkdownParser m (F Inlines)
+doubleQuoted = do
+  doubleQuoteStart
+  (try (withQuoteContext InDoubleQuote $
+    fmap B.doubleQuoted . trimInlinesF . mconcat <$>
+      many1Till inline doubleQuoteEnd))
+    <|> (return (return (B.str "\8220")))
diff --git a/src/Text/Pandoc/Readers/Mdoc.hs b/src/Text/Pandoc/Readers/Mdoc.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Readers/Mdoc.hs
@@ -0,0 +1,1469 @@
+{-# LANGUAGE CPP  #-}
+{-# LANGUAGE FlexibleContexts  #-}
+{-# LANGUAGE OverloadedStrings #-}
+{-# LANGUAGE LambdaCase #-}
+{-# LANGUAGE ViewPatterns #-}
+{- |
+   Module      : Text.Pandoc.Readers.Mdoc
+   Copyright   : © 2024 Evan Silberman
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : Evan Silberman <evan@jklol.net>
+   Stability   : WIP
+   Portability : portable
+
+Conversion of mdoc to 'Pandoc' document.
+-}
+module Text.Pandoc.Readers.Mdoc (readMdoc) where
+
+import Data.Char (isAsciiLower, toUpper)
+import Data.Default (Default)
+import Data.Either (fromRight)
+import Data.Functor (($>))
+import Data.Maybe (catMaybes)
+import Control.Monad (mplus, guard, void, when, unless)
+import Control.Monad.Except (throwError)
+#if MIN_VERSION_base(4,19,0)
+import Data.List (intersperse, unsnoc)
+#else
+import Data.List (intersperse)
+#endif
+import qualified Data.Map.Strict as M
+import qualified Data.Text as T
+import Text.Pandoc.Definition (Pandoc(Pandoc), Meta)
+import Text.Pandoc.Builder (Blocks, Inlines)
+import qualified Text.Pandoc.Builder as B
+import Text.Pandoc.Class.PandocMonad (PandocMonad(..))
+import Text.Pandoc.Options
+import Text.Pandoc.Parsing hiding (uncons)
+import Text.Pandoc.Logging
+import Text.Pandoc.Readers.Mdoc.Lex
+import Text.Pandoc.Readers.Mdoc.Standards
+import Text.Parsec (modifyState)
+import qualified Text.Pandoc.Parsing as P
+import qualified Data.Foldable as Foldable
+import Text.Pandoc.Shared (stringify)
+
+#if !MIN_VERSION_base(4,19,0)
+unsnoc :: [a] -> Maybe ([a], a)
+unsnoc = foldr (\x -> Just . maybe ([], x) (\(~(a, b)) -> (x : a, b))) Nothing
+#endif
+
+  {- As a general principle, if mandoc -T lint issues a WARNING admonition
+     or worse about a construct, I consider it fair game for this reader to
+     do something different than what mandoc does with it, including bailing
+     out instead of recovering. -}
+
+data MdocSection
+  = ShName
+  | ShSynopsis
+  | ShAuthors
+  | ShSeeAlso
+  | ShOther
+  deriving (Show, Eq)
+
+-- Declaration order is important: this is the order fields of a reference
+-- are printed by mandoc
+data ReferenceField =
+  Author
+  | ArticleTitle
+  | BookTitle
+  | Publisher
+  | Journal
+  | TechReportTitle
+  | IssueNumber
+  | VolumeNumber
+  | Url
+  | Pages
+  | Institution
+  | PubLocation
+  | PubDate
+  | Optional
+  deriving (Show, Eq, Ord, Enum)
+
+-- mandoc allows specifying multiple of _any_ reference field, and just
+-- prints them all out in document order, even though authors are the only
+-- field where this is the documented behavior. There's no lint warning
+-- about this either. I'd prefer to do last-one-wins for the non-author
+-- fields, which would presumably make it easier to transform the
+-- bibliographic data into something else, but for now all I'm doing is
+-- printing the references out the same way mandoc does.
+type MdocReference = M.Map ReferenceField [T.Text]
+
+data MdocState = MdocState
+    { readerOptions :: ReaderOptions
+    , metadata :: Meta
+    , tableCellsPlain :: Bool
+    , spacingMode :: Bool
+    , authorNameSplit :: Bool
+    , inLineEnclosure :: Bool
+    , progName :: Maybe T.Text
+    , currentSection :: MdocSection
+    , currentReference :: MdocReference
+    , logMessages :: [LogMessage]
+    }
+    deriving (Show)
+
+instance Default MdocState where
+    def =
+        MdocState
+            { readerOptions = def
+            , metadata = B.nullMeta
+            , tableCellsPlain = True
+            , spacingMode = True
+            , authorNameSplit = False
+            , inLineEnclosure = False
+            , currentSection = ShOther
+            , currentReference = M.empty
+            , progName = Nothing
+            , logMessages = []
+            }
+
+instance HasLogMessages MdocState where
+  addLogMessage msg st = st{ logMessages = msg : logMessages st }
+  getLogMessages st = reverse $ logMessages st
+
+type MdocParser m = P.ParsecT [MdocToken] MdocState m
+
+
+-- | Read mdoc from an input string and return a Pandoc document.
+readMdoc :: (PandocMonad m, ToSources a)
+        => ReaderOptions
+        -> a
+        -> m Pandoc
+readMdoc opts s = do
+  let Sources inps = toSources s
+  tokenz <- mconcat <$> mapM (uncurry lexMdoc) inps
+  let state = def {readerOptions = opts} :: MdocState
+  eitherdoc <- readWithMTokens parseMdoc state
+     (Foldable.toList . unMdocTokens $ tokenz)
+  either (throwError . fromParsecError (Sources inps)) return eitherdoc
+
+
+readWithMTokens :: PandocMonad m
+        => ParsecT [MdocToken] MdocState m a  -- ^ parser
+        -> MdocState                         -- ^ initial state
+        -> [MdocToken]                       -- ^ input
+        -> m (Either ParseError a)
+readWithMTokens parser state input =
+  runParserT parser state "source" input
+
+
+parseMdoc :: PandocMonad m => MdocParser m Pandoc
+parseMdoc = do
+  optional parsePrologue
+  bs <- many parseBlock <* eof
+  meta <- metadata <$> getState
+  let (Pandoc _ blocks) = B.doc $ mconcat bs
+  reportLogMessages
+  return $ Pandoc meta blocks
+
+msatisfy :: Monad m
+         => (MdocToken -> Bool) -> P.ParsecT [MdocToken] st m MdocToken
+msatisfy predic = P.tokenPrim show nextPos testTok
+  where
+    testTok t     = if predic t then Just t else Nothing
+    nextPos _ _ (Macro _ pos':_) = pos'
+    nextPos _ _ (Lit _ pos':_) = pos'
+    nextPos _ _ (Str _ pos':_) = pos'
+    nextPos _ _ (Delim _ _ pos':_) = pos'
+    nextPos _ _ (Blank pos':_) = pos'
+    nextPos a _ (Eol{}:x:xs) = nextPos a x xs
+    nextPos pos _ [Eol] = pos
+    nextPos pos _ [] = pos
+
+macro :: PandocMonad m => T.Text -> MdocParser m MdocToken
+macro name = msatisfy t where
+  t (Macro n _) = n == name
+  t _ = False
+
+anyMacro :: PandocMonad m => MdocParser m MdocToken
+anyMacro = msatisfy t where
+  t (Macro _ _) = True
+  t _ = False
+
+emptyMacro :: PandocMonad m => T.Text -> MdocParser m MdocToken
+emptyMacro n = macro n <* eol
+
+delim :: PandocMonad m => DelimSide -> MdocParser m MdocToken
+delim side = msatisfy t where
+  t (Delim s _ _) = side == s
+  t _ = False
+
+str :: PandocMonad m => MdocParser m MdocToken
+str = msatisfy t where
+  t Str{} = True
+  t _ = False
+
+lit :: PandocMonad m => MdocParser m MdocToken
+lit = msatisfy t where
+  t Lit{} = True
+  t _ = False
+
+arg :: PandocMonad m => MdocParser m MdocToken
+arg = msatisfy t where
+  t Lit{} = True
+  t Macro{} = True
+  t _ = False
+
+literal :: PandocMonad m => T.Text -> MdocParser m MdocToken
+literal n = msatisfy t where
+  t (Lit n' _) = n == n'
+  t _ = False
+
+blank :: PandocMonad m => MdocParser m MdocToken
+blank = msatisfy t where
+  t Blank{} = True
+  t _ = False
+
+eol :: PandocMonad m => MdocParser m ()
+eol = void $ msatisfy t where
+  t Eol{} = True
+  t _ = False
+
+newControlContext :: MdocToken -> Bool
+newControlContext Eol{} = True
+newControlContext Macro{} = True
+newControlContext Str{} = True
+newControlContext Blank{} = True
+newControlContext Lit{} = False
+newControlContext Delim{} = False
+
+
+inlineContextEnd :: PandocMonad m => MdocParser m ()
+inlineContextEnd = eof <|> (void . lookAhead $ msatisfy newControlContext)
+
+sectionEnd :: PandocMonad m => MdocParser m ()
+sectionEnd = eof <|> (void . lookAhead $ macro "Sh")
+
+argsToInlines :: PandocMonad m => MdocParser m Inlines
+argsToInlines = do
+  ls <- manyTill arg eol
+  let strs = map (B.str . toString) ls
+  spacify strs
+
+parsePrologue :: PandocMonad m => MdocParser m ()
+parsePrologue = do
+  macro "Dd"
+  date <- argsToInlines
+  macro "Dt"
+  (Lit title _) <- lit
+  (Lit section _) <- lit
+  arch <- optionMaybe (toString <$> lit)
+  eol
+  emptyMacro "Os"
+  let adjust = B.setMeta "title" (B.str title)
+             . B.setMeta "date" date
+             . B.setMeta "section" (B.str section)
+             . maybe id (B.setMeta "architecture" . B.str) arch
+  modifyState $ \s -> s{metadata = adjust $ metadata s}
+
+shToSectionMode :: T.Text -> MdocSection
+shToSectionMode "NAME" = ShName
+shToSectionMode "SYNOPSIS" = ShSynopsis
+shToSectionMode "AUTHORS" = ShAuthors
+shToSectionMode "SEE ALSO" = ShSeeAlso
+shToSectionMode _ = ShOther
+
+parseHeader :: PandocMonad m => MdocParser m Blocks
+parseHeader = do
+  (Macro m _) <- lookAhead $ macro "Sh" <|> macro "Ss"
+  txt <- lineEnclosure m id
+  let lvl = if m == "Sh" then 1 else 2
+  when (lvl == 1) $ modifyState $ \s -> s{currentSection = (shToSectionMode . stringify) txt}
+  return $ B.header lvl txt
+
+parseNameSection :: PandocMonad m => MdocParser m Blocks
+parseNameSection = do
+  sec <- currentSection <$> getState
+  guard $ sec == ShName
+  nms <- mconcat . intersperse B.space <$> many nameNm
+  macro "Nd"
+  desc <- argsToInlines
+  return $ B.para $ nms <> B.space <> "—" <> B.space <> desc
+ where
+   nameNm = do
+     macro "Nm"
+     nms <- many1 aNm
+     eol
+     return $ mconcat $ intersperse B.space nms
+   comma = msatisfy $ \case
+     (Delim _ "," _) -> True
+     _ -> False
+   aNm = do
+     nm <- toString <$> lit
+     c <- option mempty (toString <$> comma)
+     modifyState $ \s -> s{progName = mplus (progName s) (Just nm)}
+     return $ B.code nm <> B.str c
+
+parseSynopsisSection :: PandocMonad m => MdocParser m Blocks
+parseSynopsisSection = do
+  sec <- currentSection <$> getState
+  guard $ sec == ShSynopsis
+  parseSynopsis sectionEnd
+
+parseMiniSynopsis :: PandocMonad m => MdocParser m Blocks
+parseMiniSynopsis = do
+  macro "nr"
+  literal "nS"
+  literal "1"
+  eol
+  parseSynopsis (sectionEnd <|> end)
+  where
+    end = do
+      macro "nr"
+      literal "nS"
+      literal "0"
+      eol
+      return ()
+
+parseSynopsis :: PandocMonad m => MdocParser m () -> MdocParser m Blocks
+parseSynopsis end = do
+  bs <- manyTill synopsisBlock end
+  return $ mconcat bs
+  where
+    synopsisGroup p = B.lineBlock <$> many1 p <* optional (emptyMacro "Pp")
+    synopsisBlock = synopsisGroup parseInvocation
+                <|> synopsisGroup (parseCd <* optional eol)
+                <|> synopsisGroup (parseIn <* optional eol)
+                <|> synopsisGroup (parseFd <* optional eol)
+                <|> synopsisGroup (parseVt <* optional eol)
+                <|> try parseSignature
+                <|> parseWeirdSignature
+                <|> parseRegularBlock
+    parseInvocation = do
+      nm <- parseNm
+      optional eol
+      rest <- many synopsisInline
+      spacify (nm:rest)
+    parseSignature = do
+      ft <- parseFt <* optional eol
+      sig <- (parseFn <|> parseFo) <* optional eol
+      return $ B.lineBlock [ft, sig <> ";"]
+    -- e.g. OpenBSD MB_CUR_MAX(3), mild abuse of notation for Ft
+    parseWeirdSignature = do
+      ft <- parseFt <* optional eol
+      rest <- many synopsisInline
+      line <- spacify (ft:rest)
+      return $ B.lineBlock [line]
+    synopsisInline = parseSmToggle <|> parseStrs <|> (controlLine >>= spacify) <?> "synopsis inlines"
+    safeEol = do
+      amNested <- inLineEnclosure <$> getState
+      unless amNested $ optional eol
+    controlLine = many1 ((choice otherInlineMacros <|> litsAndDelimsToInlines) <* safeEol)
+
+parseSeeAlsoSection :: PandocMonad m => MdocParser m Blocks
+parseSeeAlsoSection = do
+  sec <- currentSection <$> getState
+  guard $ sec == ShSeeAlso
+  blocks <- many1Till parseSeeAlsoBlock sectionEnd
+  return $ mconcat blocks
+  where
+    parseSeeAlsoBlock = parseRegularBlock <|> (B.para <$> parseRs)
+
+-- roff(7) says "In text lines, whitespace is preserved within a line." I
+-- considered following this rule but it really cuts against the grain of what
+-- Pandoc writers want to work with, for no clear benefit. This isn't wholly
+-- inconsistent with mandoc, because it makes no effort to render multiple
+-- consecutive spaces from the source document in HTML. Hence I call B.text
+-- instead of B.str
+parseStr :: PandocMonad m => MdocParser m Inlines
+parseStr = do
+  (Str txt _) <- str
+  return $ B.text txt
+
+-- It's unclear whether consecutive text lines ought to be affected by the
+-- spacing mode. mdoc(7) claims that:
+--
+-- > By default, spacing is on. When switched off, no white space is
+-- > inserted between macro arguments and between the output generated from
+-- > adjacent macros, but text lines still get normal spacing between words
+-- > **and sentences.**
+--
+-- (emphasis added)
+-- This implied to me that while spacing is off, consecutive text lines
+-- would have spacing between them as normal. In fact, in mandoc's
+-- implementation, they do not:
+--
+--     text
+--     .Sm off
+--     text.
+--     text
+--     .Sm on
+--     text
+--
+-- renders as
+--
+--     text text.text text
+--
+-- (The "." is in there since the allusion in the documentation to
+-- sentences made me wonder if that made a difference; it doesn't.)
+--
+-- I've chosen to adopt my interpretation of the documented behavior, rather
+-- than mandoc's implementation. Multiple consecutive strs within a block get
+-- spaces between them and then packed up together, and text lines are not
+-- affected by the spacing mode.
+--
+-- Reported at https://inbox.vuxu.org/mandoc-discuss/369KFE6SHMXSE.3PS4387AYEFB5@silby.fyi/T/
+parseStrs :: PandocMonad m => MdocParser m Inlines
+parseStrs = do
+  txt <- many1 parseStr
+  return $ mconcat $ intersperse B.space txt
+
+parseDelim :: PandocMonad m => DelimSide -> MdocParser m Inlines
+parseDelim pos = do
+  (Delim _ txt _) <- delim pos
+  return $ B.str txt
+
+litsToText :: PandocMonad m => MdocParser m [T.Text]
+litsToText = do
+  ls <- many1 lit
+  return $ map toString ls
+
+litsToInlines :: PandocMonad m => MdocParser m Inlines
+litsToInlines = do
+  ls <- many1 lit
+  let strs = map (B.str . toString) ls
+  spacify strs
+
+litsAndDelimsToInlines :: PandocMonad m => MdocParser m Inlines
+litsAndDelimsToInlines = do
+  (o, ls, c) <- delimitedArgs $ many lit
+  guard $ not (null o && null ls && null c)
+  strs <- spacify $ map (B.str . toString) ls
+  return $ o <> strs <> c
+
+openingDelimiters :: PandocMonad m => MdocParser m Inlines
+openingDelimiters = do
+    openDelim <- mconcat <$> many (parseDelim Open)
+    omids <- pipes
+    addSpace <- spacingMode <$> getState
+    let omid | null omids = mempty
+             | addSpace = omids <> B.space
+             | otherwise = omids
+    return $ openDelim <> omid
+
+pipes :: PandocMonad m => MdocParser m Inlines
+pipes = many (parseDelim Middle) >>= spacify
+
+closingDelimiters :: PandocMonad m => MdocParser m Inlines
+closingDelimiters = do
+    cmids <- pipes
+    addSpace <- spacingMode <$> getState
+    let cmid | null cmids = mempty
+             | addSpace = B.space <> cmids
+             | otherwise = cmids
+    closeDelim <- mconcat <$> many (parseDelim Close)
+    return $ cmid <> closeDelim
+
+delimitedArgs :: PandocMonad m => MdocParser m x -> MdocParser m (Inlines, x, Inlines)
+delimitedArgs p = do
+    openDelim <- openingDelimiters
+    inlines <- p
+    closeDelim <- closingDelimiters
+    return (openDelim, inlines, closeDelim)
+
+simpleInline :: PandocMonad m => T.Text -> (Inlines -> Inlines) -> MdocParser m Inlines
+simpleInline nm xform = do
+  macro nm
+  segs <- manyTill segment inlineContextEnd
+  spacify segs
+ where
+   segment = do
+      (openDelim, inlines, closeDelim) <- delimitedArgs $ option mempty litsToInlines
+      return $ openDelim <> xform inlines <> closeDelim
+
+codeLikeInline' :: PandocMonad m => T.Text -> T.Text -> MdocParser m Inlines
+codeLikeInline' nm cl = simpleInline nm (eliminateEmpty (B.codeWith (cls cl) . stringify))
+
+codeLikeInline :: PandocMonad m => T.Text -> MdocParser m Inlines
+codeLikeInline nm = codeLikeInline' nm nm
+
+spanLikeInline :: PandocMonad m => T.Text -> MdocParser m Inlines
+spanLikeInline nm = simpleInline nm (eliminateEmpty (B.spanWith (cls nm)))
+
+-- One-line enclosures need a little bit of state so that we don't parse
+-- the closing delimiters that follow nested one-line or multiline
+-- enclosures; the closing delimiters are meant to go after the close of
+-- the outermost enclosure. Hence we respect and set inLineEnclosure.
+lineEnclosure :: PandocMonad m => T.Text -> (Inlines -> Inlines) -> MdocParser m Inlines
+lineEnclosure nm xform = do
+  macro nm
+  amNested <- inLineEnclosure <$> getState
+  modifyState $ \s -> s{inLineEnclosure = True}
+  first <- openingDelimiters
+  further <-
+    (manyTill
+      (parseInlineMacro
+        <|> (try (litsAndDelimsToInlines <* notFollowedBy eol))
+        <|> litsToInlines
+        <|> openingDelimiters)
+      lineEnclosureContextEnd)
+  further' <- spacify further
+  finally <- if amNested then mempty else closingDelimiters <* optional eol
+  modifyState $ \s -> s{inLineEnclosure = amNested}
+  return $ first <> xform further' <> finally
+  where
+    lineEnclosureContextEnd =
+      try $
+        void (lookAhead (macro "Ta"))
+        <|> lookAhead (many (macro "Ns" <|> delim Close) *> eol)
+
+
+-- The Ns, Ap, and Sm macros affect the automatic insertion of spaces between
+-- macro arguments that occurs by default. We parse these macros to RawInlines
+-- that we then eliminate in foldNoSpaces. If any of these macros end up
+-- in the final AST returned by readMdoc, it's a bug.
+
+noSpace :: Inlines
+noSpace = B.rawInline "mdoc" "Ns"
+
+apMacro :: Inlines
+apMacro = B.rawInline "mdoc" "Ap"
+
+smOff :: Inlines
+smOff = B.rawInline "mdoc" "Sm off"
+
+smOn :: Inlines
+smOn = B.rawInline "mdoc" "Sm on"
+
+-- Accumulator for eliminating of Ns, Ap, and Sm macros from a list of 'Inlines'
+data SpacifyState = SpacifyState
+  { accum :: [Inlines],  -- already-folded 'Inlines'
+    prev :: Inlines,  -- content we might be appending further content to
+    ns :: Bool,  -- True when we've read an Ns and are waiting to concatenate content to prev
+    sm :: Bool  -- True when spacing mode is on
+  }
+
+instance Default SpacifyState where
+  def = SpacifyState [] mempty False True
+
+-- Given a list of 'Inlines'es, concatenate consecutive elements that shouldn't
+-- have a 'Space' inserted between them based on changes to the spacing mode,
+-- Ap macros, and Ns macros.
+foldNoSpaces :: [Inlines] -> [Inlines]
+foldNoSpaces xs = (finalize . foldl go def) xs
+  where
+    go :: SpacifyState -> Inlines -> SpacifyState
+    go s x
+      | ns s && x == noSpace = s
+      |         x == apMacro = s{prev = prev s <> "'", ns = True}
+      |         x == noSpace = s{ns = True}
+      |         x == smOn    = s{sm = True}
+      | sm s && x == smOff   = s{accum = accum s <> [prev s], prev = mempty, sm = False}
+      | ns s                 = s{prev = prev s <> x, ns = False}
+      | not (sm s)           = s{prev = prev s <> x}
+      | null (prev s)        = s{prev = x}
+      | otherwise            = s{accum = accum s <> [prev s], prev = x}
+    finalize s
+      | null (prev s) = accum s
+      | otherwise     = accum s <> [prev s]
+
+-- Add any necessary spaces between individual 'Inlines' in a list.
+-- Respects the spacing mode status. This should more or less
+-- always get applied to any list of 'Inlines' before doing anything
+-- else with it.
+spacify :: PandocMonad m => [Inlines] -> MdocParser m Inlines
+spacify x = do
+  mode <- spacingMode <$> getState
+  return (go mode x)
+  where
+    go True = mconcat . intersperse B.space . foldNoSpaces
+    go False = mconcat . foldNoSpaces
+
+-- Compatibility note: mandoc permits, and doesn't warn on, "vertical" macros
+-- (Pp, Bl/El, Bd/Ed) inside of "horizontal" block partial-explicit quotations
+-- like Do/Dc. However there are no OpenBSD manual pages that employ such markup
+-- and it doesn't look right when rendered. We don't attempt to consume anything
+-- but pandoc inlines inside of these multiline enclosures.
+multilineEnclosure :: PandocMonad m => T.Text -> T.Text -> (Inlines -> Inlines) -> MdocParser m Inlines
+multilineEnclosure op cl xform = do
+  macro op
+  amNested <- inLineEnclosure <$> getState
+  -- we're now "protected" from any outer enclosure or .It
+  modifyState $ \s -> s{inLineEnclosure = False}
+  openDelim <- mconcat <$> many (parseDelim Open)
+  optional eol
+  contents <- parseInlines
+  (macro cl <?> show cl)
+  closeDelim <-
+    if amNested
+       then mempty
+       else mconcat <$> many (parseDelim Close) <* optional eol
+  modifyState $ \s -> s{inLineEnclosure = amNested}
+  return $ openDelim <> xform contents <> closeDelim
+
+parseEo :: PandocMonad m => MdocParser m Inlines
+parseEo = do
+  macro "Eo"
+  odel <- del
+  optional eol
+  inner <- parseInlines
+  macro "Ec"
+  cdel <- del
+  optional eol
+  return $ odel <> inner <> cdel
+  where
+    del = B.str . toString <$> (arg <|> delim Open <|> delim Middle <|> delim Close)
+
+eliminateEmpty :: (Inlines -> Inlines) -> Inlines -> Inlines
+eliminateEmpty x y = if null y then mempty else x y
+
+cls :: T.Text -> B.Attr
+cls x = (mempty, [x], mempty)
+
+-- mandoc -T html formats Sy with a <b> tag, since it's not really
+-- semantically <strong>, but Strong is our best option in Pandoc
+parseSy :: PandocMonad m => MdocParser m Inlines
+parseSy = simpleInline "Sy" (eliminateEmpty B.strong)
+
+parseEm :: PandocMonad m => MdocParser m Inlines
+parseEm = simpleInline "Em" (eliminateEmpty B.emph)
+
+parseNo :: PandocMonad m => MdocParser m Inlines
+parseNo = simpleInline "No" (eliminateEmpty id)
+
+-- Deprecated, mandoc doesn't style this at all
+parseTn :: PandocMonad m => MdocParser m Inlines
+parseTn = simpleInline "Tn" (eliminateEmpty id)
+
+parseLi :: PandocMonad m => MdocParser m Inlines
+parseLi = codeLikeInline "Li"
+
+parseEv :: PandocMonad m => MdocParser m Inlines
+parseEv = codeLikeInline "Ev"
+
+parseDv :: PandocMonad m => MdocParser m Inlines
+parseDv = codeLikeInline "Dv"
+
+parseAd :: PandocMonad m => MdocParser m Inlines
+parseAd = spanLikeInline "Ad"
+
+parseVa :: PandocMonad m => MdocParser m Inlines
+parseVa = codeLikeInline' "Va" "variable"
+
+parseVt :: PandocMonad m => MdocParser m Inlines
+parseVt = codeLikeInline' "Vt" "variable"
+
+parseAn :: PandocMonad m => MdocParser m Inlines
+parseAn = try anSplit <|> anRegular
+  where
+    anSplit = do
+      macro "An"
+      mode <- literal "-split" $> True <|> literal "-nosplit" $> False
+      modifyState $ \s -> s{authorNameSplit = mode}
+      return mempty
+    anRegular = do
+      an <- spanLikeInline "An"
+      spl <- authorNameSplit <$> getState
+      return $ (if spl then B.linebreak else mempty) <> an
+
+parseMs :: PandocMonad m => MdocParser m Inlines
+parseMs = spanLikeInline "Ms"
+
+-- TODO implement internal reference links
+parseSx :: PandocMonad m => MdocParser m Inlines
+parseSx = spanLikeInline "Sx"
+
+-- I'm not sure why mandoc inserts a ~ when Mt is missing an argument,
+-- but it does, and it doesn't issue a warning, so that quirk is
+-- retained.
+parseMt :: PandocMonad m => MdocParser m Inlines
+parseMt = simpleInline "Mt" mailto
+  where mailto x | null x = B.link ("mailto:~") "" "~"
+                 | otherwise = B.link ("mailto:" <> stringify x) "" x
+
+parsePa :: PandocMonad m => MdocParser m Inlines
+parsePa = simpleInline "Pa" p
+  where p x | null x = B.spanWith (cls "Pa") "~"
+            | otherwise = B.spanWith (cls "Pa") x
+
+-- There's a number of unique-looking cases for Fl parsing so I am just
+-- handling them very explicitly instead of trying to generalize anything
+-- enough to handle it. Could conceivably be better.
+parseFl :: PandocMonad m => MdocParser m Inlines
+parseFl = do
+  macro "Fl"
+  start <- option mempty (emptyWithDelim <|> flfl <|> emptyWithMacro <|> emptyEmpty)
+  segs <- manyTill segment inlineContextEnd
+  spacify ([start] <> segs)
+ where
+   emptyWithDelim = do
+     lookAhead $ many1 (delim Middle <|> delim Close)
+     ds <- closingDelimiters
+     return $ fl "-" <> ds
+   flfl = do
+     lookAhead (macro "Fl")
+     x:xs <- B.toList <$> parseFl
+     let xx = B.codeWith (cls "Fl") $ "-" <> stringify x
+     return $ xx <> B.fromList xs
+   emptyWithMacro = do
+     lookAhead anyMacro
+     rest <- parseInline
+     return $ fl "-" <> rest
+   emptyEmpty = lookAhead eol $> fl "-"
+   segment = do
+      (openDelim, inlines, closeDelim) <- delimitedArgs $ option mempty litsToText
+      inner <- (spacify . (map fl) . flags) inlines
+      return $ openDelim <> inner <> closeDelim
+   fl = B.codeWith (cls "Fl")
+   flags [] = ["-"]
+   flags xs = map ("-" <>) xs
+
+parseAr :: PandocMonad m => MdocParser m Inlines
+parseAr = simpleInline "Ar" ar
+  where ar x | null x = B.codeWith (cls "variable") "file ..."
+             | otherwise = B.codeWith (cls "variable") $ stringify x
+
+
+parseCm :: PandocMonad m => MdocParser m Inlines
+parseCm = codeLikeInline "Cm"
+
+parseIc :: PandocMonad m => MdocParser m Inlines
+parseIc = codeLikeInline "Ic"
+
+parseEr :: PandocMonad m => MdocParser m Inlines
+parseEr = codeLikeInline "Er"
+
+parseCd :: PandocMonad m => MdocParser m Inlines
+parseCd = codeLikeInline "Cd"
+
+parseQl :: PandocMonad m => MdocParser m Inlines
+parseQl = lineEnclosure "Ql" $ B.codeWith (cls "Ql") . stringify
+
+parseDq :: PandocMonad m => MdocParser m Inlines
+parseDq = lineEnclosure "Dq" B.doubleQuoted
+
+parseDo :: PandocMonad m => MdocParser m Inlines
+parseDo = multilineEnclosure "Do" "Dc" B.doubleQuoted
+
+parseSq :: PandocMonad m => MdocParser m Inlines
+parseSq = lineEnclosure "Sq" B.singleQuoted
+
+parseSo :: PandocMonad m => MdocParser m Inlines
+parseSo = multilineEnclosure "So" "Sc" B.singleQuoted
+
+parseQq :: PandocMonad m => MdocParser m Inlines
+parseQq = lineEnclosure "Qq" $ \x -> "\"" <> x <> "\""
+
+parseQo :: PandocMonad m => MdocParser m Inlines
+parseQo = multilineEnclosure "Qo" "Qc" $ \x -> "\"" <> x <> "\""
+
+parsePq :: PandocMonad m => MdocParser m Inlines
+parsePq = lineEnclosure "Pq" $ \x -> "(" <> x <> ")"
+
+parsePo :: PandocMonad m => MdocParser m Inlines
+parsePo = multilineEnclosure "Po" "Pc" $ \x -> "(" <> x <> ")"
+
+parseBq :: PandocMonad m => MdocParser m Inlines
+parseBq = lineEnclosure "Bq" $ \x -> "[" <> x <> "]"
+
+parseBo :: PandocMonad m => MdocParser m Inlines
+parseBo = multilineEnclosure "Bo" "Bc" $ \x -> "[" <> x <> "]"
+
+-- For our purposes this probably behaves identically to Bq
+-- in most circumstances but I might need to do something
+-- special with it in SYNOPSIS
+parseOp :: PandocMonad m => MdocParser m Inlines
+parseOp = lineEnclosure "Op" $ \x -> "[" <> x <> "]"
+
+parseOo :: PandocMonad m => MdocParser m Inlines
+parseOo =  multilineEnclosure "Oo" "Oc" $ \x -> "[" <> x <> "]"
+
+parseBrq :: PandocMonad m => MdocParser m Inlines
+parseBrq = lineEnclosure "Brq" $ \x -> "{" <> x <> "}"
+
+parseBro :: PandocMonad m => MdocParser m Inlines
+parseBro = multilineEnclosure "Bro" "Brc" $ \x -> "{" <> x <> "}"
+
+parseAq :: PandocMonad m => MdocParser m Inlines
+parseAq = lineEnclosure "Aq" $ \x -> "⟨" <> x <> "⟩"
+
+parseAo :: PandocMonad m => MdocParser m Inlines
+parseAo = multilineEnclosure "Ao" "Ac" $ \x -> "⟨" <> x <> "⟩"
+
+parseDl :: PandocMonad m => MdocParser m Blocks
+parseDl = do
+  inner <- lineEnclosure "Dl" id
+  return $ B.codeBlock (stringify inner)
+
+parseD1 :: PandocMonad m => MdocParser m Blocks
+parseD1 = do
+  inner <- lineEnclosure "D1" id
+  return $ B.divWith (cls "display") $ B.plain inner
+
+parseNm :: PandocMonad m => MdocParser m Inlines
+parseNm = do
+  macro "Nm"
+  mnm <- (progName <$> getState)
+  (op, rg, cl) <- delimitedArgs $ option mempty litsToInlines
+  return $ case (mnm, rg) of
+    (Just nm, x) | null x ->
+      op <> ok nm <> cl
+    (_, x) ->
+      op <> (ok . stringify) x <> cl
+  where
+    ok = B.codeWith (cls "Nm")
+
+
+parseXr :: PandocMonad m => MdocParser m Inlines
+parseXr = do
+  macro "Xr"
+  (open, (name, section), close) <- delimitedArgs f
+  let ref = name <> "(" <> section <> ")"
+  return $ open <> B.spanWith (cls "Xr") (B.str ref) <> close
+    where
+      f = do
+        n <- lit <?> "Xr manual name"
+        s <- lit <?> "Xr manual section"
+        return (toString n, toString s)
+
+parseIn :: PandocMonad m => MdocParser m Inlines
+parseIn = do
+  macro "In"
+  openClose <- closingDelimiters
+  openOpen <- openingDelimiters
+  header <- toString <$> lit
+  close <- closingDelimiters
+  return $ open openClose openOpen <> B.codeWith (cls "In") ("<" <> header <> ">") <> close
+  where
+    open a b
+      | null a = b
+      | null b = a
+      | otherwise = a <> B.space <> b
+
+parseFd :: PandocMonad m => MdocParser m Inlines
+parseFd = codeLikeInline "Fd"
+
+parseFt :: PandocMonad m => MdocParser m Inlines
+parseFt = codeLikeInline' "Ft" "variable"
+
+-- The output here is comparable to mandoc's HTML output, which doesn't tag
+-- the commas/parentheses. Is this questionable from a pandoc POV?
+formatFunction :: T.Text -> [Inlines] -> Inlines
+formatFunction nm args = B.codeWith (cls "Fn") nm <> "(" <> args' <> ")"
+  where
+    args' = mconcat $ intersperse (", ") args
+
+parseFn :: PandocMonad m => MdocParser m Inlines
+parseFn = do
+  macro "Fn"
+  (op, (nm, args), cl) <- delimitedArgs f
+  return $ op <> formatFunction nm (fmap (B.codeWith (cls "variable")) args) <> cl
+  where
+    f = do
+      nm <- toString <$> lit
+      args <- option [] litsToText
+      return (nm, args)
+
+parseFa :: PandocMonad m => MdocParser m Inlines
+parseFa = codeLikeInline' "Fa" "variable"
+
+parseFo :: PandocMonad m => MdocParser m Inlines
+parseFo = do
+  macro "Fo"
+  nm <- toString <$> lit
+  eol
+  args <- many (parseFa <* eol)
+  macro "Fc"
+  return $ formatFunction nm args
+
+parseLk :: PandocMonad m => MdocParser m Inlines
+parseLk = do
+  macro "Lk"
+  openClose <- closingDelimiters
+  openOpen <- openingDelimiters
+  url <- toString <$> lit
+  inner <- many segment >>= spacify
+  close <- closingDelimiters
+  let label | null inner = B.str url
+            | otherwise = inner
+  return $ open openClose openOpen <> B.link url "" label <> close
+  where
+    open a b
+      | null a = b
+      | null b = a
+      | otherwise = a <> B.space <> b
+    end = msatisfy newControlContext
+    segment = do
+      a <- openingDelimiters
+      m <- option mempty litsToInlines
+      z <-
+        try (closingDelimiters <* notFollowedBy end)
+          <|> option mempty pipes
+      guard $ not $ all null [a, m, z]
+      return $ a <> m <> z
+
+-- This is a raw roff request but it appears sometimes in mdoc
+-- manuals and is easy enough to handle
+parsebr :: PandocMonad m => MdocParser m Inlines
+parsebr = emptyMacro "br" >> return B.linebreak
+
+parseNs :: PandocMonad m => MdocParser m Inlines
+parseNs = macro "Ns" >> return noSpace
+
+-- Per mdoc(7), Pf prefix macro [argument ...] is equivalent to
+-- No \&prefix Ns macro [argument ...] and because of the way
+-- spacify works, the easiest thing to do is just push an Ns onto
+-- the input
+parsePf :: PandocMonad m => MdocParser m Inlines
+parsePf = do
+  macro "Pf"
+  t <- toString <$> anyToken
+  rest <- getInput
+  pos <- getPosition
+  setInput $ (Macro "Ns" pos):rest
+  return $ B.str t
+
+parseAp :: PandocMonad m => MdocParser m Inlines
+parseAp = macro "Ap" >> return apMacro
+
+parseEx :: PandocMonad m => MdocParser m Inlines
+parseEx = do
+  macro "Ex"
+  literal "-std"
+  args <- fmap toString <$> many lit
+  pn <- progName <$> getState
+  eol
+  return $ "The"
+          <> B.space
+          <> utils pn args
+          <> B.space
+          <> "0 on success, and >0 if an error occurs."
+  where
+    nm = B.codeWith (cls "Nm")
+    sing = "utility exits"
+    plur = "utilities exit"
+    utils (Just x) [] = nm x <> B.space <> sing
+    utils _ [x] = nm x <> B.space <> sing
+    utils _ [x,y] = nm x <> B.space <> "and" <> B.space <> nm y <> B.space <> plur
+    utils pn xs =
+      case (pn, unsnoc xs) of
+        (Nothing, Nothing) -> sing
+        (_, Just (hd, end)) -> mconcat ((intersperse (", ") . fmap nm) hd) <> ", and " <> nm end <> B.space <> plur
+        (Just p, Nothing) -> nm p <> B.space <> sing
+
+
+parseRv :: (PandocMonad m) => MdocParser m Inlines
+parseRv = do
+  macro "Rv"
+  literal "-std"
+  args <- fmap toString <$> many lit
+  pn <- progName <$> getState
+  eol
+  return $ go pn args
+  where
+    nm a = B.codeWith (cls "Fn") a <> "()"
+    nothing = "Upon successful completion, the value 0 is returned;"
+    sing = "function returns"
+    plur = "functions return"
+    success = "the value 0 if successful;"
+    errno =
+      "otherwise the value -1 is returned and the global variable"
+        <> B.codeWith (cls "variable") "errno"
+        <> "is set to indicate the error."
+    message conj =
+      "The"
+        <> B.space
+        <> conj
+        <> B.space
+        <> success
+        <> B.space
+        <> errno
+    go (Just x) [] = message (nm x <> B.space <> sing)
+    go _ [x] = message (nm x <> B.space <> sing)
+    go _ [x, y] = message (nm x <> B.space <> "and" <> B.space <> nm y <> B.space <> plur)
+    go pn xs =
+      case (pn, unsnoc xs) of
+        (Nothing, Nothing) -> nothing <> B.space <> errno
+        (_, Just (hd, end)) -> message (mconcat ((intersperse (", ") . fmap nm) hd) <> ", and " <> nm end <> B.space <> plur)
+        (Just p, Nothing) -> message (nm p <> B.space <> sing)
+
+parseSt :: PandocMonad m => MdocParser m Inlines
+parseSt = do
+  macro "St"
+  (Lit std pos) <- lit
+  case standard std of
+    Nothing -> do
+      logMessage $ SkippedContent ("unrecognized argument to St: " <> std) pos
+      return mempty
+    Just t -> return $ B.text t
+
+-- TODO incorporate well-known library description and linker options
+-- from mandoc lib.in expected in FreeBSD LIBRARY section, at minimum.
+parseLb :: PandocMonad m => MdocParser m Inlines
+parseLb = do
+  macro "Lb"
+  library <- toString <$> lit
+  return $ "library" <> B.space <> B.doubleQuoted (B.str library)
+
+unixVersion :: PandocMonad m => T.Text -> T.Text -> MdocParser m Inlines
+unixVersion m s = do
+  macro m
+  (o, v, c) <- delimitedArgs (option mempty (toString <$> lit))
+  return $ o <> B.str s <> f v <> c
+  where
+    f v | T.null v = mempty
+        | otherwise = B.space <> B.str v
+
+parseAt :: PandocMonad m => MdocParser m Inlines
+parseAt = do
+  macro "At"
+  (o, v, c) <-  delimitedArgs (optionMaybe (toString <$> lit))
+  let v' = maybe "AT&T UNIX" attVer v
+  return $ o <> B.text v' <> c
+  where
+    isVersion x = x `elem` ["1", "2", "3", "4", "5", "6", "7"]
+    isRelease x = x `elem` ["1", "2", "3", "4"]
+    attVer (T.stripPrefix "v" -> Just ver)
+      | isVersion ver = "Version " <> ver <> " AT&T UNIX"
+    attVer "32v" = "Version 7 AT&T UNIX/32V"
+    attVer "III" = "AT&T System III UNIX"
+    attVer (T.stripPrefix "V." -> Just release)
+      | isRelease release = "AT&T System V Release " <> release <> " UNIX"
+    attVer "V" = "AT&T System V UNIX"
+    attVer x = "AT&T UNIX " <> x
+
+parseBsx :: PandocMonad m => MdocParser m Inlines
+parseBsx = unixVersion "Bsx" "BSD/OS"
+
+parseBx :: PandocMonad m => MdocParser m Inlines
+parseBx = do
+  macro "Bx"
+  (o, v, c) <- delimitedArgs zeroToTwoLits
+  return $ o <> bsd v <> c
+  where
+    zeroToTwoLits = do
+      toks <- try (count 2 lit) <|> count 1 lit <|> count 0 lit
+      return $ toString <$> toks
+    bsd [] = B.str "BSD"
+    bsd [x] = B.str $ x <> "BSD"
+    bsd (x:y:_) = B.str (x <> "BSD" <> "-" <> T.toTitle y)
+
+parseDx :: PandocMonad m => MdocParser m Inlines
+parseDx = unixVersion "Dx" "DragonFly"
+
+parseFx :: PandocMonad m => MdocParser m Inlines
+parseFx = unixVersion "Fx" "FreeBSD"
+
+-- This dance to capitalize a letter at the end of a NetBSD
+-- version matches what mandoc does to the argument of .Nx.
+-- See mandoc mdoc_validate.c r1.350
+-- Curiously, there's little easy-to-find evidence of what
+-- these lettered releases actually are, other than
+-- references in man page history sections to 0.9A etc.
+parseNx :: PandocMonad m => MdocParser m Inlines
+parseNx = do
+  macro "Nx"
+  (o, v, c) <-  delimitedArgs (option mempty (toString <$> lit))
+  return $ o <> "NetBSD" <> f v <> c
+  where
+    f v | T.null v = mempty
+        | otherwise = B.space <> B.str (fromRight v $ readWith earlyNetBSDVersion () v)
+    earlyNetBSDVersion = do
+      major <- oneOf "01"
+      dot <- char '.'
+      minor <- digit
+      ltr <- satisfy isAsciiLower
+      return $ T.pack [major, dot, minor, toUpper ltr]
+
+parseOx :: PandocMonad m => MdocParser m Inlines
+parseOx = unixVersion "Ox" "OpenBSD"
+
+parseUx :: PandocMonad m => MdocParser m Inlines
+parseUx = macro "Ux" >> return (B.str "UNIX")
+
+parseInlineMacro :: PandocMonad m => MdocParser m Inlines
+parseInlineMacro = choice (synopsisTopicMacros <> otherInlineMacros) <?> "inline macro"
+
+-- These macros always start a new line in SYNOPSIS
+synopsisTopicMacros :: PandocMonad m => [MdocParser m Inlines]
+synopsisTopicMacros =
+    [parseNm, parseCd, parseFd, parseFn, parseFo, parseIn, parseVt, parseFt]
+
+otherInlineMacros :: PandocMonad m => [MdocParser m Inlines]
+otherInlineMacros =
+    [ parseSy,
+      parseEm,
+      parseLk,
+      parseLi,
+      parseEv,
+      parseDv,
+      parseMt,
+      parsePa,
+      parseFl,
+      parseCm,
+      parseIc,
+      parseEr,
+      parseAd,
+      parseVa,
+      parseAn,
+      parseMs,
+      parseSx,
+      parseAr,
+      parseFa,
+      parseNo,
+      parseTn,
+      parseXr,
+      parseQl,
+      parseOp,
+      parseSq,
+      parseDq,
+      parseQq,
+      parsePq,
+      parseBq,
+      parseBrq,
+      parseAq,
+      parseEo,
+      parseSo,
+      parseDo,
+      parseQo,
+      parsePo,
+      parseBo,
+      parseBro,
+      parseAo,
+      parseOo,
+      parseBf,
+      parseRsInline,
+      parseEx,
+      parseRv,
+      parseSt,
+      parseLb,
+      parseAt,
+      parseBsx,
+      parseBx,
+      parseDx,
+      parseFx,
+      parseNx,
+      parseOx,
+      parseUx,
+      parsebr,
+      parseAp,
+      parsePf,
+      parseNs,
+      skipUnsupportedInlines
+    ]
+
+parseInline :: PandocMonad m => MdocParser m Inlines
+parseInline = parseStrs <|> (controlLine >>= spacify) <?> "text lines or inline macros"
+  where
+    safeEol = do
+      amNested <- inLineEnclosure <$> getState
+      unless amNested $ optional eol
+    controlLine = many1 ((parseInlineMacro <|> litsAndDelimsToInlines) <* safeEol)
+
+parseInlines :: PandocMonad m => MdocParser m Inlines
+parseInlines = many1 (parseSmToggle <|> parseInline) >>= spacify
+
+-- Lp is a deprecated synonym for Pp
+parsePara :: PandocMonad m => MdocParser m Blocks
+parsePara = B.para . B.trimInlines <$> parseInlines <*
+    optional (emptyMacro "Pp" <|> emptyMacro "Lp")
+
+-- Indented display blocks are visually similar to block quotes
+-- but rarely carry those semantics. I'm just putting things in
+-- divs. Centered is discouraged and rarely seen.
+parseDisplay :: PandocMonad m => MdocParser m Blocks
+parseDisplay = do
+  literal "-filled" <|> literal "-ragged" <|> literal "-centered"
+  many $ (literal "-offset" *> lit) <|> (literal "-compact")
+  eol
+  B.divWith (cls "display") . mconcat <$> many parseRegularBlock
+
+-- This is something of a best-effort interpretation of the -unfilled
+-- display block type. The main difference with mandoc is probably
+-- that newlines inside of multiline enclosures won't be preserved.
+parseUnfilled :: PandocMonad m => MdocParser m Blocks
+parseUnfilled = do
+  literal "-unfilled"
+  many $ (literal "-offset" *> lit) <|> (literal "-compact")
+  eol
+  lns <- many $ Just <$> parseStrPreserveSpace
+            <|> Nothing <$ parseSmToggle
+            <|> Just <$> parseInline
+            <|> Just "" <$ emptyMacro "Pp"
+  return $ B.lineBlock (catMaybes lns)
+  where
+    parseStrPreserveSpace = (B.str . toString) <$> str <|> (blank *> mempty)
+
+parseCodeBlock :: PandocMonad m => MdocParser m Blocks
+parseCodeBlock = do
+  literal "-literal"
+  many $ (literal "-offset" *> lit) <|> (literal "-compact")
+  eol
+  lns <- many $ Just . toString <$> (str <|> blank)
+            <|> Nothing <$ parseSmToggle
+            <|> Just . stringify <$> parseInline
+            <|> Just "" <$ emptyMacro "Pp"
+  return $ B.codeBlock (T.unlines (catMaybes lns))
+
+parseBd :: PandocMonad m => MdocParser m Blocks
+parseBd = do
+  macro "Bd"
+  blk <- parseCodeBlock <|> parseDisplay <|> parseUnfilled
+  emptyMacro "Ed"
+  return blk
+
+-- This is a bit of a best effort version. Hypothetically multiple blocks
+-- could occur inside a Bf and this should be a stateful thing but I don't
+-- know if that's observed in the wild.
+parseBf :: PandocMonad m => MdocParser m Inlines
+parseBf = do
+  macro "Bf"
+  xform <-   B.strong <$ (literal "Sy" <|> literal "-symbolic")
+         <|> B.emph   <$ (literal "Em" <|> literal "-emphasis")
+         <|> code     <$ (literal "Li" <|> literal "-literal")
+  eol
+  ins <- parseInlines
+  emptyMacro "Ef"
+  return $ xform ins
+  where
+    code = B.code . stringify
+
+skipListArgument :: (PandocMonad m) => MdocParser m ()
+skipListArgument =
+  void $ choice
+    [ literal "-width" *> lit,
+      literal "-offset" *> lit,
+      literal "-compact"
+    ]
+
+parseItemList :: PandocMonad m => MdocParser m Blocks
+parseItemList = do
+  f <- (choice (map literal ["-bullet", "-dash", "-hyphen", "-item"]) $> B.bulletList)
+       <|> literal "-enum" $> B.orderedList
+  many skipListArgument
+  eol
+  items <- many bulletItem
+  return $ f items
+  where
+    bulletItem = do
+      emptyMacro "It"
+      mconcat <$> many parseRegularBlock
+
+-- Despite some ambiguous documentation to the contrary the Xo/Xc macros
+-- only seem genuinely useful in an .It head, and it's not clear what if
+-- anything it means to use them somewhere else in a contemporary mdoc manual.
+-- See https://inbox.vuxu.org/mandoc-discuss/2UKLZW0DL8BSM.2IIO9W4HSUSRR@silby.fyi/T/
+-- for more blathering.
+parseDefinitionList :: PandocMonad m => MdocParser m Blocks
+parseDefinitionList = do
+  headParser <- (choice . map literal) ["-hang", "-inset", "-ohang", "-tag"] $> parsedHead <|> literal "-diag" $> diagHead
+  many skipListArgument
+  eol
+  items <- many (parseSmToggle *> mempty <|> dlItem headParser)
+  return $ B.definitionList items
+  where
+    parsedHead = try xoListHead <|> eolListHead
+    eolListHead = do
+      modifyState $ \s -> s{inLineEnclosure = True}
+      inner <- parseInlines
+      eol
+      modifyState $ \s -> s{inLineEnclosure = False}
+      return inner
+    diagHead = argsToInlines
+    dlItem hed = do
+      -- Some manuals have an evidently useless .Pp before .It
+      -- e.g. OpenBSD ld(1), just deal with it.
+      many ((void . emptyMacro) "Pp" <|> skipUnsupportedMacro "Tg")
+      macro "It"
+      dt <- hed
+      dd <- mconcat <$> many parseRegularBlock
+      return (dt, [dd])
+    xoListHead = do
+      before <- option mempty parseInline
+      macro "Xo"
+      optional eol
+      after <- many1Till parseInlines (emptyMacro "Xc")
+      spacify (before:after)
+
+-- TODO support implicit rows:
+--   If the first line of the body of a -column list is not an It macro line,
+--   It contexts spanning one input line each are implied until an It macro
+--   line is encountered
+-- and support literal tabs
+parseColumnList :: PandocMonad m => MdocParser m Blocks
+parseColumnList = do
+  literal "-column"
+  many skipListArgument
+  many $ arg <|> delim Open <|> delim Middle <|> delim Close
+  eol
+  rows <- many listRow
+  return $ B.simpleTable [] rows
+  where
+    listRow = do
+      optional (emptyMacro "Pp")
+      macro "It"
+      fmap B.plain <$> sepBy (parseInlines <|> pure mempty) (macro "Ta" <* optional eol)
+
+parseBl :: PandocMonad m => MdocParser m Blocks
+parseBl = do
+  macro "Bl"
+  blk <- parseItemList <|> parseDefinitionList <|> parseColumnList
+  emptyMacro "El"
+  return blk
+
+referenceField :: PandocMonad m => T.Text -> ReferenceField -> MdocParser m ()
+referenceField m field = do
+  macro m
+  reference <- currentReference <$> getState
+  contents <- stringify <$> litsAndDelimsToInlines
+  eol
+  modifyState $ \s -> s{currentReference = M.insertWith (++) field [contents] reference}
+  return ()
+
+parsePercentA :: PandocMonad m => MdocParser m ()
+parsePercentA = referenceField "%A" Author
+
+parsePercentB :: PandocMonad m => MdocParser m ()
+parsePercentB = referenceField "%B" BookTitle
+
+parsePercentC :: PandocMonad m => MdocParser m ()
+parsePercentC = referenceField "%C" PubLocation
+
+parsePercentD :: PandocMonad m => MdocParser m ()
+parsePercentD = referenceField "%D" PubDate
+
+parsePercentI :: PandocMonad m => MdocParser m ()
+parsePercentI = referenceField "%I" Publisher
+
+parsePercentJ :: PandocMonad m => MdocParser m ()
+parsePercentJ = referenceField "%J" Journal
+
+parsePercentN :: PandocMonad m => MdocParser m ()
+parsePercentN = referenceField "%N" IssueNumber
+
+parsePercentO :: PandocMonad m => MdocParser m ()
+parsePercentO = referenceField "%O" Optional
+
+parsePercentP :: PandocMonad m => MdocParser m ()
+parsePercentP = referenceField "%P" Pages
+
+parsePercentQ :: PandocMonad m => MdocParser m ()
+parsePercentQ = referenceField "%Q" Institution
+
+parsePercentR :: PandocMonad m => MdocParser m ()
+parsePercentR = referenceField "%R" TechReportTitle
+
+parsePercentT :: PandocMonad m => MdocParser m ()
+parsePercentT = referenceField "%T" ArticleTitle
+
+parsePercentU :: PandocMonad m => MdocParser m ()
+parsePercentU = referenceField "%U" Url
+
+parsePercentV :: PandocMonad m => MdocParser m ()
+parsePercentV = referenceField "%V" VolumeNumber
+
+parseReferenceField :: PandocMonad m => MdocParser m ()
+parseReferenceField =
+  choice [
+      parsePercentA,
+      parsePercentB,
+      parsePercentC,
+      parsePercentD,
+      parsePercentI,
+      parsePercentJ,
+      parsePercentN,
+      parsePercentO,
+      parsePercentP,
+      parsePercentQ,
+      parsePercentR,
+      parsePercentT,
+      parsePercentU,
+      parsePercentV
+    ]
+
+parseRsInline :: PandocMonad m => MdocParser m Inlines
+parseRsInline = do
+  sec <- currentSection <$> getState
+  guard $ sec /= ShSeeAlso
+  parseRs
+
+parseRs :: PandocMonad m => MdocParser m Inlines
+parseRs = do
+  emptyMacro "Rs"
+  modifyState $ \s -> s{currentReference = M.empty}
+  many1 parseReferenceField
+  emptyMacro "Re"
+  ref <- currentReference <$> getState
+  -- TODO formatting fields correctly
+  return $ B.text $ (M.foldl f mempty ref) <> "."
+  where join v = T.concat (intersperse ", " v)
+        f a v | T.null a = join v
+              | otherwise = a <> ", " <> join v
+
+-- mandoc's roff(7) says "Blank text lines, which may include whitespace,
+-- are only permitted within literal contexts." mandoc -T lint warns about
+-- blank lines and inserts a roff `sp` request, which is handled
+-- differently depending on the output format. My read is that mandoc
+-- considers the handling of a blank line in non-literal context in mdoc(7)
+-- to be undefined. The Mdoc reader thus ignores blank input lines outside
+-- of -literal and -unfilled displays.
+skipBlanks :: PandocMonad m => MdocParser m Blocks
+skipBlanks = many1 blank *> mempty
+
+-- By default, mdoc is in "spacing mode", where horizontal space is added
+-- between macro contents. The Sm macro turns it off and on. When we encounter
+-- the Sm macro, we both modify the parser state and we emit a sentinel value
+-- that spacify/foldNoSpaces uses to handle cases where spacing mode gets
+-- turned off and on within a stretch of inlines.
+parseSmToggle :: PandocMonad m => MdocParser m Inlines
+parseSmToggle = do
+  macro "Sm"
+  cur <- spacingMode <$> getState
+  mode <- optionMaybe (literal "on" $> True <|> literal "off" $> False)
+  eol
+  let newMode = update mode cur
+  modifyState $ \s -> s{spacingMode = newMode}
+  return $ if newMode then smOn else smOff
+  where
+    update = \case
+      Nothing -> not
+      Just x -> const x
+
+skipUnsupportedMacro :: PandocMonad m => T.Text -> MdocParser m ()
+skipUnsupportedMacro nm = do
+  (Macro _ pos) <- macro nm
+  manyTill anyToken eol
+  logMessage $ SkippedContent ("unsupported macro: " <> nm) pos
+
+
+skipUnsupportedInlines :: PandocMonad m => MdocParser m Inlines
+skipUnsupportedInlines = choice
+      [ skipUnsupportedMacro "Tg",
+        skipUnsupportedMacro "Bk",
+        skipUnsupportedMacro "Ek"
+      ] *> mempty
+
+skipUnknownMacro :: PandocMonad m => MdocParser m Blocks
+skipUnknownMacro = do
+  pos <- getPosition
+  m <- anyMacro
+  manyTill anyToken eol
+  logMessage $ SkippedContent ("unsupported macro: " <> toString m) pos
+  return mempty
+
+
+parseRegularBlock :: PandocMonad m => MdocParser m Blocks
+parseRegularBlock =
+  choice
+    [ parseDl
+    , parseD1
+    , parsePara
+    , emptyMacro "Pp" *> mempty
+    , parseBd
+    , parseBl
+    , skipBlanks
+    ]
+
+parseBlock :: (PandocMonad m) => MdocParser m Blocks
+parseBlock =
+  choice
+    [ parseHeader
+    , parseNameSection
+    , parseSynopsisSection
+    , parseSeeAlsoSection
+    , parseMiniSynopsis
+    , parseRegularBlock
+    , skipUnknownMacro
+    ]
diff --git a/src/Text/Pandoc/Readers/Mdoc/Lex.hs b/src/Text/Pandoc/Readers/Mdoc/Lex.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Readers/Mdoc/Lex.hs
@@ -0,0 +1,225 @@
+{-# LANGUAGE FlexibleContexts #-}
+{-# LANGUAGE FlexibleInstances #-}
+{-# LANGUAGE MultiParamTypeClasses #-}
+{-# LANGUAGE GeneralizedNewtypeDeriving #-}
+{-# LANGUAGE OverloadedStrings #-}
+{-# LANGUAGE TypeFamilies #-}
+{- |
+   Module      : Text.Pandoc.Readers.Mdoc.Lex
+   Copyright   : Copyright (C) 2024 Evan Silberman
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : Evan Silberman <evan@jklol.net>
+   Stability   : WIP
+   Portability : portable
+
+Tokenizer for mdoc
+-}
+module Text.Pandoc.Readers.Mdoc.Lex
+  ( MdocToken(..)
+  , MdocTokens(..)
+  , DelimSide(..)
+  , lexMdoc
+  , toString
+  )
+where
+
+import Control.Monad (void, guard, when)
+import Control.Monad.Except (throwError)
+import Text.Pandoc.Class.PandocMonad (PandocMonad(..))
+import Data.Char (isAlphaNum)
+import Data.Maybe (isJust)
+import qualified Data.Text as T
+import Text.Pandoc.Options
+import Text.Pandoc.Parsing
+import Text.Pandoc.Readers.Roff.Escape
+import Text.Pandoc.Readers.Mdoc.Macros
+import qualified Data.Sequence as Seq
+
+-- As a higher level language with a wealth of semantic macros, mdoc
+-- discourages authors from falling back to low-level roff features like font
+-- selection, custom macros, defined strings, etc. Pandoc's mdoc reader is
+-- accordingly implemented as a high-level interpreter of mdoc's semantic macros
+-- and almost no raw roff requests are supported.
+--
+-- tbl(7) and eqn(7) macros are rare but not completely unseen in mdoc manuals.
+-- they are not yet implemented. most use of tbl macros in mdoc could probably
+-- be replaced with .Bl -column
+
+data DelimSide = Open | Middle | Close deriving (Show, Eq)
+
+-- | Tokens for Mdoc documents
+data MdocToken = Str T.Text SourcePos -- ^ The contents of a text line
+               | Macro T.Text SourcePos  -- ^ A macro to be processed
+               | Lit T.Text SourcePos  -- ^ Literal text on a control line
+               | Blank SourcePos  -- ^ A blank line
+               | Delim DelimSide T.Text SourcePos  -- ^ A delimiter character
+               | Eol  -- ^ The end of a control line
+               deriving Show
+
+toString :: MdocToken -> T.Text
+toString (Str x _) = x
+toString (Macro x _) = x
+toString (Lit x _) = x
+toString (Delim _ x _) = x
+toString Blank{} = mempty
+toString Eol = mempty
+
+newtype MdocTokens = MdocTokens { unMdocTokens :: Seq.Seq MdocToken }
+        deriving (Show, Semigroup, Monoid)
+
+singleTok :: MdocToken -> MdocTokens
+singleTok t = MdocTokens (Seq.singleton t)
+
+type Lexer m = ParsecT Sources () m
+
+instance RoffLikeLexer MdocTokens where
+  -- This is a bit confusing. We're lexing to MdocTokens, but for escaping
+  -- purposes we just want Texts.
+  type Token MdocTokens = T.Text
+  -- We don't need a state
+  type State MdocTokens = ()
+  -- We don't support predefined string expansion
+  expandString = return ()
+  escString = return mempty
+  -- what token type the unescaped text gets wrapped in is decided by other
+  -- parts of the lexer.
+  emit = id
+  -- All escapes are resolved in the lexer and we never need to emit anything,
+  -- vs. the roff lexer which has to push the backlashes to the output while
+  -- in copy mode.
+  backslash = (mempty <* char '\\') <|> (mempty <* string "\\E")
+  -- We don't support macro definition and we don't output anything for \A
+  checkDefined = const mempty
+  -- We don't support copy mode and \E is treated as backslash
+  escE = return mempty
+  -- We don't support low-level font selection
+  escFont = escIgnore 'f' [escapeArg, countChar 1 (satisfy (/='\n'))]
+
+eofline :: (Stream s m Char, UpdateSourcePos s Char) => ParsecT s u m MdocToken
+eofline = do
+  void newline <|> eof
+  return Eol
+
+lexComment :: PandocMonad m => Lexer m MdocTokens
+lexComment = do
+  try $ string ".\\\""
+  skipMany $ noneOf "\n"
+  eofline
+  return mempty
+
+argText :: PandocMonad m => Lexer m T.Text
+argText = do
+  beg <- escape <|> regularText
+  end <- mconcat <$> many (escape <|> regularText <|> quoteChar)
+  return $ beg <> end
+
+spaceTabChar :: PandocMonad m => Lexer m T.Text
+spaceTabChar = T.singleton <$> spaceChar
+
+quotedArg :: PandocMonad m => Lexer m T.Text
+quotedArg = do
+  quoteChar
+  t <- mconcat <$> many (try innerQuote <|> escape <|> regularText <|> spaceTabChar)
+  quoteChar
+  notFollowedBy quoteChar
+  return t
+  where
+    innerQuote = do
+      string "\"\""
+      return "\""
+
+anyText :: PandocMonad m => Lexer m T.Text
+anyText = escape <|> regularText <|> quoteChar <|> spaceTabChar
+
+regularText :: PandocMonad m => Lexer m T.Text
+regularText = many1Char $ noneOf "\n\r\t \\\""
+
+quoteChar :: PandocMonad m => Lexer m T.Text
+quoteChar = T.singleton <$> char '"'
+
+mdocToken :: PandocMonad m => Lexer m MdocTokens
+mdocToken = lexComment <|> lexControlLine <|> lexTextLine
+
+lexMacroName :: PandocMonad m => Lexer m T.Text
+lexMacroName = many1Char (satisfy isMacroChar)
+  where
+    isMacroChar '%' = True
+    isMacroChar x = isAlphaNum x
+
+lexMacro :: PandocMonad m => Lexer m MdocToken
+lexMacro = do
+  pos <- getPosition
+  name <- lexMacroName
+  eof <|> void (lookAhead (spaceChar <|> newline))
+  skipSpaces
+  return $ Macro name pos
+
+lexCallableMacro :: PandocMonad m => Lexer m MdocToken
+lexCallableMacro = do
+  pos <- getPosition
+  q <- optionMaybe quoteChar
+  name <- lexMacroName
+  when (isJust q) (void quoteChar)
+  eof <|> void (lookAhead (spaceChar <|> newline))
+  skipSpaces
+  guard $ isCallableMacro name
+  return $ Macro name pos
+
+lexDelim :: (PandocMonad m) => Lexer m MdocToken
+lexDelim = do
+  pos <- getPosition
+  q <- optionMaybe quoteChar
+  t <-
+    Delim Open <$> oneOfStrings ["(", "["]
+      <|> Delim Close <$> oneOfStrings [".", ",", ":", ";", ")", "]", "?", "!"]
+      <|> Delim Middle <$> textStr "|"
+  when (isJust q) (void quoteChar)
+  eof <|> void (lookAhead (spaceChar <|> newline))
+  skipSpaces
+  return $ t pos
+
+lexLit :: PandocMonad m => Lexer m MdocToken
+lexLit = do
+  pos <- getPosition
+  t <- argText <|> quotedArg
+  skipSpaces
+  return $ Lit t pos
+
+lexTextLine :: PandocMonad m => Lexer m MdocTokens
+lexTextLine = do
+  pos <- getPosition
+  guard $ sourceColumn pos == 1
+  t <- mconcat <$> many anyText
+  eofline
+  if T.null $ T.strip t
+     then return $ singleTok $ Blank pos
+     else return $ singleTok $ Str t pos
+
+lexControlLine :: PandocMonad m => Lexer m MdocTokens
+lexControlLine = do
+  pos <- getPosition
+  guard $ sourceColumn pos == 1
+  char '.'
+  eofline *> mempty <|> do
+    m@(Macro name _) <- lexMacro
+    -- .Ns macros at the start of a line are ignored. We'd have to look behind
+    -- to keep track of the "start of the line" in the parser, so we'll drop
+    -- those macros in lexing.
+    let start | name == "Ns" = []
+              | otherwise = [m]
+    let parsed = isParsedMacro name
+    (wds, e) <- manyUntil (l parsed) eofline
+    return $ MdocTokens $ Seq.fromList $ start <> wds <> [e]
+      where
+        l True = try lexDelim <|> try lexCallableMacro <|> lexLit
+        l False = try lexDelim <|> lexLit
+
+-- | Tokenize a string as a sequence of mdoc tokens.
+lexMdoc :: PandocMonad m => SourcePos -> T.Text -> m MdocTokens
+lexMdoc pos txt = do
+  eithertokens <- readWithM (do setPosition pos
+                                mconcat <$> manyTill mdocToken eof) def txt
+  case eithertokens of
+    Left e       -> throwError e
+    Right tokenz -> return tokenz
diff --git a/src/Text/Pandoc/Readers/Mdoc/Macros.hs b/src/Text/Pandoc/Readers/Mdoc/Macros.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Readers/Mdoc/Macros.hs
@@ -0,0 +1,183 @@
+{-# LANGUAGE OverloadedStrings #-}
+{- |
+   Module      : Text.Pandoc.Readers.Mdoc.Macros
+   Copyright   : © 2024 Evan Silberman
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : Evan Silberman <evan@jklol.net>
+   Stability   : WIP
+   Portability : portable
+
+-}
+module Text.Pandoc.Readers.Mdoc.Macros (isParsedMacro, isCallableMacro) where
+
+import Data.Set (member, fromList, Set)
+import Data.Text
+
+isParsedMacro :: Text -> Bool
+isParsedMacro a = member a parsedMacros
+
+isCallableMacro :: Text -> Bool
+isCallableMacro a = member a callableMacros
+
+parsedMacros :: Set Text
+parsedMacros = fromList [
+  "Ac",
+  "Ad",
+  "An",
+  "Ao",
+  "Ap",
+  "Aq",
+  "Ar",
+  "At",
+  "Bc",
+  "Bo",
+  "Bq",
+  "Brc",
+  "Bro",
+  "Brq",
+  "Bsx",
+  "Bx",
+  "Cd",
+  "Cm",
+  "D1",
+  "Dc",
+  "Dl",
+  "Do",
+  "Dq",
+  "Dv",
+  "Dx",
+  "Ec",
+  "Em",
+  "En",
+  "Eo",
+  "Er",
+  "Es",
+  "Ev",
+  "Fa",
+  "Fc",
+  "Fl",
+  "Fn",
+  "Fr",
+  "Ft",
+  "Fx",
+  "Ic",
+  "In",
+  "It",
+  "Li",
+  "Lk",
+  "Ms",
+  "Mt",
+  "Nm",
+  "No",
+  "Ns",
+  "Nx",
+  "Oc",
+  "Oo",
+  "Op",
+  "Ot",
+  "Ox",
+  "Pa",
+  "Pc",
+  "Pf",
+  "Po",
+  "Pq",
+  "Qc",
+  "Ql",
+  "Qo",
+  "Qq",
+  "Sc",
+  "Sh",
+  "So",
+  "Sq",
+  "Ss",
+  "St",
+  "Sx",
+  "Sy",
+  "Ta",
+  "Tn",
+  "Ux",
+  "Va",
+  "Vt",
+  "Xc",
+  "Xo",
+  "Xr"]
+
+callableMacros :: Set Text
+callableMacros = fromList [
+  "Ac",
+  "Ad",
+  "An",
+  "Ao",
+  "Ap",
+  "Aq",
+  "Ar",
+  "At",
+  "Bc",
+  "Bo",
+  "Bq",
+  "Brc",
+  "Bro",
+  "Brq",
+  "Bsx",
+  "Bx",
+  "Cd",
+  "Cm",
+  "Dc",
+  "Do",
+  "Dq",
+  "Dv",
+  "Dx",
+  "Ec",
+  "Em",
+  "En",
+  "Eo",
+  "Er",
+  "Es",
+  "Ev",
+  "Fa",
+  "Fc",
+  "Fl",
+  "Fn",
+  "Fo",
+  "Fr",
+  "Ft",
+  "Fx",
+  "Ic",
+  "In",
+  "Li",
+  "Lk",
+  "Ms",
+  "Mt",
+  "Nm",
+  "No",
+  "Ns",
+  "Nx",
+  "Oc",
+  "Oo",
+  "Op",
+  "Ot",
+  "Ox",
+  "Pa",
+  "Pc",
+  "Pf",
+  "Po",
+  "Pq",
+  "Qc",
+  "Ql",
+  "Qo",
+  "Qq",
+  "Sc",
+  "So",
+  "Sq",
+  "St",
+  "Sx",
+  "Sy",
+  "Ta",
+  "Tn",
+  "Ux",
+  "Va",
+  "Vt",
+  "Xc",
+  "Xo",
+  "Xr"]
diff --git a/src/Text/Pandoc/Readers/Mdoc/Standards.hs b/src/Text/Pandoc/Readers/Mdoc/Standards.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Readers/Mdoc/Standards.hs
@@ -0,0 +1,70 @@
+{-# LANGUAGE OverloadedStrings #-}
+{- |
+   Module      : Text.Pandoc.Readers.Mdoc.Standards
+   Copyright   : © 2024 Evan Silberman
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : Evan Silberman <evan@jklol.net>
+   Stability   : WIP
+   Portability : portable
+
+-}
+module Text.Pandoc.Readers.Mdoc.Standards (standard) where
+
+import Data.Map (fromList, Map)
+import qualified Data.Map as M
+import Data.Text
+
+standard :: Text -> Maybe Text
+standard = flip M.lookup standards
+
+standards :: Map Text Text
+standards = fromList [
+  ("-p1003.1-88",    "IEEE Std 1003.1-1988 (“POSIX.1”)"),
+  ("-p1003.1-90",    "IEEE Std 1003.1-1990 (“POSIX.1”)"),
+  ("-p1003.1-96",    "ISO/IEC 9945-1:1996 (“POSIX.1”)"),
+  ("-p1003.1-2001",  "IEEE Std 1003.1-2001 (“POSIX.1”)"),
+  ("-p1003.1-2004",  "IEEE Std 1003.1-2004 (“POSIX.1”)"),
+  ("-p1003.1-2008",  "IEEE Std 1003.1-2008 (“POSIX.1”)"),
+  ("-p1003.1-2024",  "IEEE Std 1003.1-2024 (“POSIX.1”)"),
+  ("-p1003.1",       "IEEE Std 1003.1 (“POSIX.1”)"),
+  ("-p1003.1b",      "IEEE Std 1003.1b (“POSIX.1b”)"),
+  ("-p1003.1b-93",   "IEEE Std 1003.1b-1993 (“POSIX.1b”)"),
+  ("-p1003.1c-95",   "IEEE Std 1003.1c-1995 (“POSIX.1c”)"),
+  ("-p1003.1g-2000", "IEEE Std 1003.1g-2000 (“POSIX.1g”)"),
+  ("-p1003.1i-95",   "IEEE Std 1003.1i-1995 (“POSIX.1i”)"),
+  ("-p1003.2",       "IEEE Std 1003.2 (“POSIX.2”)"),
+  ("-p1003.2-92",    "IEEE Std 1003.2-1992 (“POSIX.2”)"),
+  ("-p1003.2a-92",   "IEEE Std 1003.2a-1992 (“POSIX.2”)"),
+  ("-isoC",          "ISO/IEC 9899:1990 (“ISO C90”)"),
+  ("-isoC-90",       "ISO/IEC 9899:1990 (“ISO C90”)"),
+  ("-isoC-amd1",     "ISO/IEC 9899/AMD1:1995 (“ISO C90, Amendment 1”)"),
+  ("-isoC-tcor1",    "ISO/IEC 9899/TCOR1:1994 (“ISO C90, Technical Corrigendum 1”)"),
+  ("-isoC-tcor2",    "ISO/IEC 9899/TCOR2:1995 (“ISO C90, Technical Corrigendum 2”)"),
+  ("-isoC-99",       "ISO/IEC 9899:1999 (“ISO C99”)"),
+  ("-isoC-2011",     "ISO/IEC 9899:2011 (“ISO C11”)"),
+  ("-isoC-2023",     "ISO/IEC 9899:2024 (“ISO C23”)"),
+  ("-iso9945-1-90",  "ISO/IEC 9945-1:1990 (“POSIX.1”)"),
+  ("-iso9945-1-96",  "ISO/IEC 9945-1:1996 (“POSIX.1”)"),
+  ("-iso9945-2-93",  "ISO/IEC 9945-2:1993 (“POSIX.2”)"),
+  ("-ansiC",         "ANSI X3.159-1989 (“ANSI C89”)"),
+  ("-ansiC-89",      "ANSI X3.159-1989 (“ANSI C89”)"),
+  ("-ieee754",       "IEEE Std 754-1985"),
+  ("-iso8802-3",     "ISO 8802-3: 1989"),
+  ("-iso8601",       "ISO 8601"),
+  ("-ieee1275-94",   "IEEE Std 1275-1994 (“Open Firmware”)"),
+  ("-xpg3",          "X/Open Portability Guide Issue 3 (“XPG3”)"),
+  ("-xpg4",          "X/Open Portability Guide Issue 4 (“XPG4”)"),
+  ("-xpg4.2",        "X/Open Portability Guide Issue 4, Version 2 (“XPG4.2”)"),
+  ("-xbd5",          "X/Open Base Definitions Issue 5 (“XBD5”)"),
+  ("-xcu5",          "X/Open Commands and Utilities Issue 5 (“XCU5”)"),
+  ("-xsh5",          "X/Open System Interfaces and Headers Issue 5 (“XSH5”)"),
+  ("-xns5",          "X/Open Networking Services Issue 5 (“XNS5”)"),
+  ("-xns5.2",        "X/Open Networking Services Issue 5.2 (“XNS5.2”)"),
+  ("-xcurses4.2",    "X/Open Curses Issue 4, Version 2 (“XCURSES4.2”)"),
+  ("-susv1",         "Version 1 of the Single UNIX Specification (“SUSv1”)"),
+  ("-susv2",         "Version 2 of the Single UNIX Specification (“SUSv2”)"),
+  ("-susv3",         "Version 3 of the Single UNIX Specification (“SUSv3”)"),
+  ("-susv4",         "Version 4 of the Single UNIX Specification (“SUSv4”)"),
+  ("-svid4",         "System V Interface Definition, Fourth Edition (“SVID4”)")
+  ]
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,28 +1,7 @@
-{-# LANGUAGE FlexibleInstances    #-}
-{-# LANGUAGE RelaxedPolyRec       #-}
-{-# LANGUAGE TypeSynonymInstances #-}
--- RelaxedPolyRec needed for inlinesBetween on GHC < 7
-{-
-  Copyright (C) 2012-2017 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 OverloadedStrings #-}
 {- |
    Module      : Text.Pandoc.Readers.MediaWiki
-   Copyright   : Copyright (C) 2012-2017 John MacFarlane
+   Copyright   : Copyright (C) 2012-2024 John MacFarlane
    License     : GNU GPL, version 2 or above
 
    Maintainer  : John MacFarlane <jgm@berkeley.edu>
@@ -34,51 +13,52 @@
 {-
 TODO:
 _ correctly handle tables within tables
-_ parse templates?
+_ parse templates(?) and built-in magic words
 -}
 module Text.Pandoc.Readers.MediaWiki ( readMediaWiki ) where
 
 import Control.Monad
 import Control.Monad.Except (throwError)
-import Data.Char (isDigit, isSpace)
+import Data.Char (isDigit, isLetter, isSpace)
 import qualified Data.Foldable as F
-import Data.List (intercalate, intersperse, isPrefixOf)
-import qualified Data.Map as M
+import Data.List (intersperse)
 import Data.Maybe (fromMaybe, maybeToList)
-import Data.Monoid ((<>))
 import Data.Sequence (ViewL (..), viewl, (<|))
 import qualified Data.Set as Set
-import Data.Text (Text, unpack)
+import Data.Text (Text)
+import qualified Data.Text as T
 import Text.HTML.TagSoup
-import Text.Pandoc.Builder (Blocks, Inlines, trimInlines)
 import qualified Text.Pandoc.Builder as B
-import Text.Pandoc.Class (PandocMonad (..))
+import Text.Pandoc.Builder (Blocks, Inlines, trimInlines)
+import Text.Pandoc.Char (isCJK)
+import Text.Pandoc.Class.PandocMonad (PandocMonad (..))
 import Text.Pandoc.Definition
 import Text.Pandoc.Logging
 import Text.Pandoc.Options
-import Text.Pandoc.Parsing hiding (nested)
-import Text.Pandoc.Readers.HTML (htmlTag, isBlockTag, isCommentTag)
-import Text.Pandoc.Shared (crFilter, safeRead, stringify, stripTrailingNewlines,
-                           trim)
-import Text.Pandoc.Walk (walk)
+import Text.Pandoc.Parsing hiding (tableCaption)
+import Text.Pandoc.Readers.HTML (htmlTag, isCommentTag, toAttr)
+import Text.Pandoc.Shared (formatCode, safeRead, splitTextBy, stringify,
+                           stripTrailingNewlines, trim, tshow)
 import Text.Pandoc.XML (fromEntities)
 
 -- | Read mediawiki from an input string and return a Pandoc document.
-readMediaWiki :: PandocMonad m
-              => ReaderOptions -- ^ Reader options
-              -> Text          -- ^ String to parse (assuming @'\n'@ line endings)
+readMediaWiki :: (PandocMonad m, ToSources a)
+              => ReaderOptions
+              -> a
               -> m Pandoc
 readMediaWiki opts s = do
+  let sources = toSources s
   parsed <- readWithM parseMediaWiki MWState{ mwOptions = opts
                                             , mwMaxNestingLevel = 4
                                             , mwNextLinkNumber  = 1
                                             , mwCategoryLinks = []
-                                            , mwHeaderMap = M.empty
                                             , mwIdentifierList = Set.empty
                                             , mwLogMessages = []
                                             , mwInTT = False
+                                            , mwAllowNewlines = True
+                                            , mwMeta = nullMeta
                                             }
-            (unpack (crFilter s) ++ "\n")
+            sources
   case parsed of
     Right result -> return result
     Left e       -> throwError e
@@ -87,21 +67,18 @@
                        , mwMaxNestingLevel :: Int
                        , mwNextLinkNumber  :: Int
                        , mwCategoryLinks   :: [Inlines]
-                       , mwHeaderMap       :: M.Map Inlines String
-                       , mwIdentifierList  :: Set.Set String
+                       , mwIdentifierList  :: Set.Set Text
                        , mwLogMessages     :: [LogMessage]
                        , mwInTT            :: Bool
+                       , mwAllowNewlines   :: Bool
+                       , mwMeta            :: Meta
                        }
 
-type MWParser m = ParserT [Char] MWState m
+type MWParser m = ParsecT Sources MWState m
 
 instance HasReaderOptions MWState where
   extractReaderOptions = mwOptions
 
-instance HasHeaderMap MWState where
-  extractHeaderMap     = mwHeaderMap
-  updateHeaderMap f st = st{ mwHeaderMap = f $ mwHeaderMap st }
-
 instance HasIdentifierList MWState where
   extractIdentifierList     = mwIdentifierList
   updateIdentifierList f st = st{ mwIdentifierList = f $ mwIdentifierList st }
@@ -114,75 +91,131 @@
 -- auxiliary functions
 --
 
--- This is used to prevent exponential blowups for things like:
--- ''a'''a''a'''a''a'''a''a'''a
-nested :: PandocMonad m => MWParser m a -> MWParser m a
-nested p = do
-  nestlevel <- mwMaxNestingLevel `fmap` getState
-  guard $ nestlevel > 0
-  updateState $ \st -> st{ mwMaxNestingLevel = mwMaxNestingLevel st - 1 }
-  res <- p
-  updateState $ \st -> st{ mwMaxNestingLevel = nestlevel }
-  return res
-
 specialChars :: [Char]
-specialChars = "'[]<=&*{}|\":\\"
+specialChars = "'[]<=&*{}|\":\\_"
 
 spaceChars :: [Char]
 spaceChars = " \n\t"
 
-sym :: PandocMonad m => String -> MWParser m ()
-sym s = () <$ try (string s)
+sym :: PandocMonad m => Text -> MWParser m ()
+sym s = () <$ try (string $ T.unpack s)
 
-newBlockTags :: [String]
+newBlockTags :: [Text]
 newBlockTags = ["haskell","syntaxhighlight","source","gallery","references"]
 
-isBlockTag' :: Tag String -> Bool
-isBlockTag' tag@(TagOpen t _) = (isBlockTag tag || t `elem` newBlockTags) &&
-  t `notElem` eitherBlockOrInline
-isBlockTag' tag@(TagClose t) = (isBlockTag tag || t `elem` newBlockTags) &&
-  t `notElem` eitherBlockOrInline
-isBlockTag' tag = isBlockTag tag
+isBlockTag' :: Tag Text -> Bool
+isBlockTag' (TagOpen t _) = isBlockTagName t
+isBlockTag' (TagClose t) = isBlockTagName t
+isBlockTag' _ = False
 
-isInlineTag' :: Tag String -> Bool
+isBlockTagName :: Text -> Bool
+isBlockTagName t =
+  t `elem` [ "blockquote"
+           , "caption"
+           , "col"
+           , "colgroup"
+           , "dd"
+           , "div"
+           , "dl"
+           , "dt"
+           , "h1"
+           , "h2"
+           , "h3"
+           , "h4"
+           , "h5"
+           , "h6"
+           , "hr"
+           , "li"
+           , "meta"
+           , "ol"
+           , "p"
+           , "pre"
+           , "rp"
+           , "table"
+           , "td"
+           , "th"
+           , "time"
+           , "tr"
+           , "ul"
+           , "center"
+           ] || t `elem` newBlockTags
+
+isInlineTag' :: Tag Text -> Bool
 isInlineTag' (TagComment _) = True
-isInlineTag' t              = not (isBlockTag' t)
+isInlineTag' (TagOpen t _) = isInlineTagName t
+isInlineTag' (TagClose t) = isInlineTagName t
+isInlineTag' _ = False
 
-eitherBlockOrInline :: [String]
-eitherBlockOrInline = ["applet", "button", "del", "iframe", "ins",
-                               "map", "area", "object"]
+isInlineTagName :: Text -> Bool
+isInlineTagName t =
+  t `elem` [ "abbr"
+           , "b"
+           , "bdi"
+           , "bdo"
+           , "big"
+           , "br"
+           , "cite"
+           , "code"
+           , "data"
+           , "del"
+           , "dfn"
+           , "em"
+           , "i"
+           , "ins"
+           , "kbd"
+           , "link"
+           , "mark"
+           , "q"
+           , "rt"
+           , "ruby"
+           , "s"
+           , "samp"
+           , "small"
+           , "span"
+           , "strong"
+           , "sub"
+           , "sup"
+           , "u"
+           , "var"
+           , "wbr"
+           , "font"
+           , "rb"
+           , "rtc"
+           , "strike"
+           , "tt"
+           ]
 
 htmlComment :: PandocMonad m => MWParser m ()
 htmlComment = () <$ htmlTag isCommentTag
 
-inlinesInTags :: PandocMonad m => String -> MWParser m Inlines
+inlinesInTags :: PandocMonad m => Text -> MWParser m Inlines
 inlinesInTags tag = try $ do
   (_,raw) <- htmlTag (~== TagOpen tag [])
-  if '/' `elem` raw   -- self-closing tag
+  if T.any (== '/') raw   -- self-closing tag
      then return mempty
      else trimInlines . mconcat <$>
             manyTill inline (htmlTag (~== TagClose tag))
 
-blocksInTags :: PandocMonad m => String -> MWParser m Blocks
+blocksInTags :: PandocMonad m => Text -> MWParser m Blocks
 blocksInTags tag = try $ do
   (_,raw) <- htmlTag (~== TagOpen tag [])
   let closer = if tag == "li"
-                  then htmlTag (~== TagClose "li")
+                  then htmlTag (~== TagClose ("li" :: Text))
                      <|> lookAhead (
-                              htmlTag (~== TagOpen "li" [])
-                          <|> htmlTag (~== TagClose "ol")
-                          <|> htmlTag (~== TagClose "ul"))
+                              htmlTag (~== TagOpen ("li" :: Text) [])
+                          <|> htmlTag (~== TagClose ("ol" :: Text))
+                          <|> htmlTag (~== TagClose ("ul" :: Text)))
                   else htmlTag (~== TagClose tag)
-  if '/' `elem` raw   -- self-closing tag
+  if T.any (== '/') raw   -- self-closing tag
      then return mempty
      else mconcat <$> manyTill block closer
 
-charsInTags :: PandocMonad m => String -> MWParser m [Char]
-charsInTags tag = try $ do
+textInTags :: PandocMonad m => Text -> MWParser m Text
+textInTags tag = try $ do
   (_,raw) <- htmlTag (~== TagOpen tag [])
-  if '/' `elem` raw   -- self-closing tag
+  if T.any (== '/') raw   -- self-closing tag
      then return ""
-     else manyTill anyChar (htmlTag (~== TagClose tag))
+     else T.pack <$> manyTill anyChar (htmlTag (~== TagClose tag))
 
 --
 -- main parser
@@ -194,11 +227,12 @@
   spaces
   eof
   categoryLinks <- reverse . mwCategoryLinks <$> getState
+  meta <- mwMeta <$> getState
   let categories = if null categoryLinks
                       then mempty
                       else B.para $ mconcat $ intersperse B.space categoryLinks
   reportLogMessages
-  return $ B.doc $ bs <> categories
+  return $ Pandoc meta (B.toList bs <> B.toList categories)
 
 --
 -- block parsers
@@ -218,7 +252,7 @@
      <|> blockTag
      <|> (B.rawBlock "mediawiki" <$> template)
      <|> para
-  trace (take 60 $ show $ B.toList res)
+  trace (T.take 60 $ tshow $ B.toList res)
   return res
 
 para :: PandocMonad m => MWParser m Blocks
@@ -226,48 +260,71 @@
   contents <- trimInlines . mconcat <$> many1 inline
   if F.all (==Space) contents
      then return mempty
-     else return $ B.para contents
+     else case B.toList contents of
+         -- For the MediaWiki format all images are considered figures
+         [Image attr figureCaption (src, title)] ->
+             return $ B.simpleFigureWith
+                 attr (B.fromList figureCaption) src title
+         _ -> return $ B.para contents
 
 table :: PandocMonad m => MWParser m Blocks
 table = do
   tableStart
-  styles <- option [] parseAttrs
+  styles <- option [] $
+               parseAttrs <* skipMany spaceChar <* optional (char '|')
   skipMany spaceChar
+  optional $ template >> skipMany spaceChar
   optional blanklines
   let tableWidth = case lookup "width" styles of
                          Just w  -> fromMaybe 1.0 $ parseWidth w
                          Nothing -> 1.0
   caption <- option mempty tableCaption
+  optional newline
   optional rowsep
   hasheader <- option False $ True <$ lookAhead (skipSpaces *> char '!')
-  (cellspecs',hdr) <- unzip <$> tableRow
-  let widths = map ((tableWidth *) . snd) cellspecs'
+  (cellwidths,hdr) <- unzip <$> tableRow
+  let widths = map (tableWidth *) (concat cellwidths)
   let restwidth = tableWidth - sum widths
   let zerocols = length $ filter (==0.0) widths
   let defaultwidth = if zerocols == 0 || zerocols == length widths
-                        then 0.0
-                        else restwidth / fromIntegral zerocols
-  let widths' = map (\w -> if w == 0 then defaultwidth else w) widths
-  let cellspecs = zip (map fst cellspecs') widths'
+                        then ColWidthDefault
+                        else ColWidth $ restwidth / fromIntegral zerocols
+  let widths' = map (\w -> if w > 0 then ColWidth w else defaultwidth) widths
+  let cellspecs = zip (calculateAlignments hdr) widths'
   rows' <- many $ try $ rowsep *> (map snd <$> tableRow)
   optional blanklines
   tableEnd
-  let cols = length hdr
   let (headers,rows) = if hasheader
                           then (hdr, rows')
-                          else (replicate cols mempty, hdr:rows')
-  return $ B.table caption cellspecs headers rows
+                          else ([], hdr:rows')
+  let toRow = Row nullAttr
+      toHeaderRow l = [toRow l | not (null l)]
+  return $ B.table (B.simpleCaption $ B.plain caption)
+                   cellspecs
+                   (TableHead nullAttr $ toHeaderRow headers)
+                   [TableBody nullAttr 0 [] $ map toRow rows]
+                   (TableFoot nullAttr [])
 
-parseAttrs :: PandocMonad m => MWParser m [(String,String)]
+calculateAlignments :: [Cell] -> [Alignment]
+calculateAlignments = concatMap cellAligns
+  where
+    cellAligns :: Cell -> [Alignment]
+    cellAligns (Cell _ align _ (ColSpan colspan) _) = replicate colspan align
+
+parseAttrs :: PandocMonad m => MWParser m [(Text,Text)]
 parseAttrs = many1 parseAttr
 
-parseAttr :: PandocMonad m => MWParser m (String, String)
+parseAttr :: PandocMonad m => MWParser m (Text, Text)
 parseAttr = try $ do
   skipMany spaceChar
-  k <- many1 letter
+  kFirst <- letter
+  kRest <- many (alphaNum <|> oneOf "_-:.")
+  let k = T.pack (kFirst : kRest)
+  skipMany spaceChar
   char '='
-  v <- (char '"' >> many1Till (satisfy (/='\n')) (char '"'))
-       <|> many1 (satisfy $ \c -> not (isSpace c) && c /= '|')
+  skipMany spaceChar
+  v <- (char '"' >> manyTillChar (satisfy (/='\n')) (char '"'))
+       <|> many1Char (satisfy $ \c -> not (isSpace c) && c /= '|')
   return (k,v)
 
 tableStart :: PandocMonad m => MWParser m ()
@@ -278,89 +335,109 @@
 
 rowsep :: PandocMonad m => MWParser m ()
 rowsep = try $ guardColumnOne *> skipSpaces *> sym "|-" <*
-               many (char '-') <* optional parseAttr <* blanklines
+               many (char '-') <* optional parseAttrs
+                               <* skipSpaces
+                               <* skipMany htmlComment
+                               <* blanklines
 
-cellsep :: PandocMonad m => MWParser m ()
+cellsep :: PandocMonad m => MWParser m [(Text,Text)]
 cellsep = try $ do
-  skipSpaces
-  (char '|' *> notFollowedBy (oneOf "-}+") *> optional (char '|'))
-    <|> (char '!' *> optional (char '!'))
+  col <- sourceColumn <$> getPosition
+  skipMany spaceChar
+  c <- oneOf "|!"
+  when (col > 1) $ void $ char c
+  notFollowedBy (oneOf "-}")
+  attribs <- option [] (parseAttrs <* skipMany spaceChar <* char '|')
+  skipMany spaceChar
+  pure attribs
 
 tableCaption :: PandocMonad m => MWParser m Inlines
 tableCaption = try $ do
+  optional rowsep
   guardColumnOne
   skipSpaces
   sym "|+"
-  optional (try $ parseAttr *> skipSpaces *> char '|' *> skipSpaces)
-  (trimInlines . mconcat) <$> many (notFollowedBy (cellsep <|> rowsep) *> inline)
+  optional (try $ parseAttrs *> skipSpaces *> char '|' *> blanklines)
+  trimInlines . mconcat <$>
+    many (notFollowedBy (void cellsep <|> rowsep) *> inline)
 
-tableRow :: PandocMonad m => MWParser m [((Alignment, Double), Blocks)]
+tableRow :: PandocMonad m => MWParser m [([Double], Cell)]
 tableRow = try $ skipMany htmlComment *> many tableCell
 
-tableCell :: PandocMonad m => MWParser m ((Alignment, Double), Blocks)
+-- multiple widths because cell might have colspan
+tableCell :: PandocMonad m => MWParser m ([Double], Cell)
 tableCell = try $ do
-  cellsep
-  skipMany spaceChar
-  attrs <- option [] $ try $ parseAttrs <* skipSpaces <* char '|' <*
-                                 notFollowedBy (char '|')
-  skipMany spaceChar
+  attribs <- cellsep
   pos' <- getPosition
-  ls <- concat <$> many (notFollowedBy (cellsep <|> rowsep <|> tableEnd) *>
-                     ((snd <$> withRaw table) <|> count 1 anyChar))
+  ls <- T.concat <$> many (notFollowedBy (void cellsep <|> rowsep <|> tableEnd) *>
+                            ((snd <$> withRaw table) <|> countChar 1 anyChar))
   bs <- parseFromString (do setPosition pos'
                             mconcat <$> many block) ls
-  let align = case lookup "align" attrs of
+  let align = case lookup "align" attribs of
                     Just "left"   -> AlignLeft
                     Just "right"  -> AlignRight
                     Just "center" -> AlignCenter
                     _             -> AlignDefault
-  let width = case lookup "width" attrs of
-                    Just xs -> fromMaybe 0.0 $ parseWidth xs
-                    Nothing -> 0.0
-  return ((align, width), bs)
+  let rowspan = RowSpan . fromMaybe 1 $
+                safeRead =<< lookup "rowspan" attribs
+  let colspan = ColSpan . fromMaybe 1 $
+                safeRead =<< lookup "colspan" attribs
+  let ColSpan rawcolspan = colspan
+  let handledAttribs = ["align", "colspan", "rowspan"]
+      attribs' = [ (k, v) | (k, v) <- attribs
+                          , k `notElem` handledAttribs
+                 ]
+  let widths = case lookup "width" attribs of
+                    Just xs -> maybe (replicate rawcolspan 0.0)
+                                 (\w -> replicate rawcolspan
+                                    (w / fromIntegral rawcolspan))
+                                 (parseWidth xs)
+                    Nothing -> replicate rawcolspan 0.0
+  return (widths, B.cellWith (toAttr attribs') align rowspan colspan bs)
 
-parseWidth :: String -> Maybe Double
+parseWidth :: Text -> Maybe Double
 parseWidth s =
-  case reverse s of
-       ('%':ds) | all isDigit ds -> safeRead ('0':'.':reverse ds)
-       _        -> Nothing
+  case T.unsnoc s of
+    Just (ds, '%') | T.all isDigit ds -> safeRead $ "0." <> ds
+    _ -> Nothing
 
-template :: PandocMonad m => MWParser m String
+template :: PandocMonad m => MWParser m Text
 template = try $ do
   string "{{"
   notFollowedBy (char '{')
   lookAhead $ letter <|> digit <|> char ':'
-  let chunk = template <|> variable <|> many1 (noneOf "{}") <|> count 1 anyChar
+  let chunk = template <|> variable <|> many1Char (noneOf "{}") <|> countChar 1 anyChar
   contents <- manyTill chunk (try $ string "}}")
-  return $ "{{" ++ concat contents ++ "}}"
+  return $ "{{" <> T.concat contents <> "}}"
 
 blockTag :: PandocMonad m => MWParser m Blocks
 blockTag = do
   (tag, _) <- lookAhead $ htmlTag isBlockTag'
   case tag of
       TagOpen "blockquote" _ -> B.blockQuote <$> blocksInTags "blockquote"
-      TagOpen "pre" _ -> B.codeBlock . trimCode <$> charsInTags "pre"
+      TagOpen "pre" _ -> B.codeBlock . trimCode <$> textInTags "pre"
       TagOpen "syntaxhighlight" attrs -> syntaxhighlight "syntaxhighlight" attrs
       TagOpen "source" attrs -> syntaxhighlight "source" attrs
       TagOpen "haskell" _ -> B.codeBlockWith ("",["haskell"],[]) . trimCode <$>
-                                charsInTags "haskell"
+                                textInTags "haskell"
       TagOpen "gallery" _ -> blocksInTags "gallery"
       TagOpen "p" _ -> mempty <$ htmlTag (~== tag)
       TagClose "p"  -> mempty <$ htmlTag (~== tag)
       _ -> B.rawBlock "html" . snd <$> htmlTag (~== tag)
 
-trimCode :: String -> String
-trimCode ('\n':xs) = stripTrailingNewlines xs
-trimCode xs        = stripTrailingNewlines xs
+trimCode :: Text -> Text
+trimCode t = case T.uncons t of
+  Just ('\n', xs) -> stripTrailingNewlines xs
+  _               -> stripTrailingNewlines t
 
-syntaxhighlight :: PandocMonad m => String -> [Attribute String] -> MWParser m Blocks
+syntaxhighlight :: PandocMonad m => Text -> [Attribute Text] -> MWParser m Blocks
 syntaxhighlight tag attrs = try $ do
   let mblang = lookup "lang" attrs
   let mbstart = lookup "start" attrs
   let mbline = lookup "line" attrs
   let classes = maybeToList mblang ++ maybe [] (const ["numberLines"]) mbline
   let kvs = maybe [] (\x -> [("startFrom",x)]) mbstart
-  contents <- charsInTags tag
+  contents <- textInTags tag
   return $ B.codeBlockWith ("",classes,kvs) $ trimCode contents
 
 hrule :: PandocMonad m => MWParser m Blocks
@@ -374,56 +451,56 @@
   guardColumnOne
   char ' '
   let endline' = B.linebreak <$ try (newline <* char ' ')
-  let whitespace' = B.str <$> many1 ('\160' <$ spaceChar)
+  let whitespace' = B.str <$> many1Char ('\160' <$ spaceChar)
   let spToNbsp ' ' = '\160'
       spToNbsp x   = x
   let nowiki' = mconcat . intersperse B.linebreak . map B.str .
-                lines . fromEntities . map spToNbsp <$> try
-                  (htmlTag (~== TagOpen "nowiki" []) *>
-                   manyTill anyChar (htmlTag (~== TagClose "nowiki")))
+                T.lines . fromEntities . T.map spToNbsp <$> try
+                  (htmlTag (~== TagOpen ("nowiki" :: Text) []) *>
+                   manyTillChar anyChar (htmlTag (~== TagClose ("nowiki" :: Text))))
   let inline' = whitespace' <|> endline' <|> nowiki'
                   <|> try (notFollowedBy newline *> inline)
   contents <- mconcat <$> many1 inline'
-  let spacesStr (Str xs) = all isSpace xs
+  let spacesStr (Str xs) = T.all isSpace xs
       spacesStr _        = False
   if F.all spacesStr contents
      then return mempty
      else return $ B.para $ encode contents
 
 encode :: Inlines -> Inlines
-encode = B.fromList . normalizeCode . B.toList . walk strToCode
-  where strToCode (Str s) = Code ("",[],[]) s
-        strToCode Space   = Code ("",[],[]) " "
-        strToCode  x      = x
-        normalizeCode []  = []
-        normalizeCode (Code a1 x : Code a2 y : zs) | a1 == a2 =
-          normalizeCode $ Code a1 (x ++ y) : zs
-        normalizeCode (x:xs) = x : normalizeCode xs
+encode = formatCode nullAttr
 
 header :: PandocMonad m => MWParser m Blocks
 header = try $ do
   guardColumnOne
-  eqs <- many1 (char '=')
-  let lev = length eqs
+  lev <- length <$> many1 (char '=')
   guard $ lev <= 6
   contents <- trimInlines . mconcat <$> manyTill inline (count lev $ char '=')
-  attr <- registerHeader nullAttr contents
+  opts <- mwOptions <$> getState
+  attr <- (if isEnabled Ext_gfm_auto_identifiers opts
+              then id
+              else modifyIdentifier) <$> registerHeader nullAttr contents
   return $ B.headerWith attr lev contents
 
+-- See #4731:
+modifyIdentifier :: Attr -> Attr
+modifyIdentifier (ident,cl,kv) = (ident',cl,kv)
+  where ident' = T.map (\c -> if c == '-' then '_' else c) ident
+
 bulletList :: PandocMonad m => MWParser m Blocks
 bulletList = B.bulletList <$>
    (   many1 (listItem '*')
-   <|> (htmlTag (~== TagOpen "ul" []) *> spaces *> many (listItem '*' <|> li) <*
-        optional (htmlTag (~== TagClose "ul"))) )
+   <|> (htmlTag (~== TagOpen ("ul" :: Text) []) *> spaces *> many (listItem '*' <|> li) <*
+        optional (htmlTag (~== TagClose ("ul" :: Text)))) )
 
 orderedList :: PandocMonad m => MWParser m Blocks
 orderedList =
        (B.orderedList <$> many1 (listItem '#'))
    <|> try
-       (do (tag,_) <- htmlTag (~== TagOpen "ol" [])
+       (do (tag,_) <- htmlTag (~== TagOpen ("ol" :: Text) [])
            spaces
            items <- many (listItem '#' <|> li)
-           optional (htmlTag (~== TagClose "ol"))
+           optional (htmlTag (~== TagClose ("ol" :: Text)))
            let start = fromMaybe 1 $ safeRead $ fromAttrib "start" tag
            return $ B.orderedListWith (start, DefaultStyle, DefaultDelim) items)
 
@@ -434,7 +511,7 @@
 defListItem = try $ do
   terms <- mconcat . intersperse B.linebreak <$> many defListTerm
   -- we allow dd with no dt, or dt with no dd
-  defs  <- if B.isNull terms
+  defs  <- if null terms
               then notFollowedBy
                     (try $ skipMany1 (char ':') >> string "<math>") *>
                        many1 (listItem ':')
@@ -446,9 +523,8 @@
   guardColumnOne
   char ';'
   skipMany spaceChar
-  pos' <- getPosition
-  anyLine >>= parseFromString (do setPosition pos'
-                                  trimInlines . mconcat <$> many inline)
+  trimInlines . mconcat <$> many (notFollowedBy (oneOf ":\r\n") *> inline) <*
+    optional newline
 
 listStart :: PandocMonad m => Char -> MWParser m ()
 listStart c = char c *> notFollowedBy listStartChar
@@ -460,25 +536,25 @@
 anyListStart = guardColumnOne >> oneOf "*#:;"
 
 li :: PandocMonad m => MWParser m Blocks
-li = lookAhead (htmlTag (~== TagOpen "li" [])) *>
+li = lookAhead (htmlTag (~== TagOpen ("li" :: Text) [])) *>
      (firstParaToPlain <$> blocksInTags "li") <* spaces
 
 listItem :: PandocMonad m => Char -> MWParser m Blocks
 listItem c = try $ do
-  guardColumnOne
+  guardColumnOne <|> guard (c == ':') -- def can start on same line as term
   extras <- many (try $ char c <* lookAhead listStartChar)
   if null extras
      then listItem' c
      else do
        skipMany spaceChar
        pos' <- getPosition
-       first <- concat <$> manyTill listChunk newline
+       first <- T.concat <$> manyTill listChunk newline
        rest <- many
                 (try $ string extras *> lookAhead listStartChar *>
-                       (concat <$> manyTill listChunk newline))
+                       (T.concat <$> manyTill listChunk newline))
        contents <- parseFromString (do setPosition pos'
                                        many1 $ listItem' c)
-                          (unlines (first : rest))
+                          (T.unlines (first : rest))
        case c of
            '*' -> return $ B.bulletList contents
            '#' -> return $ B.orderedList contents
@@ -492,20 +568,21 @@
 -- }}
 -- * next list item
 -- which seems to be valid mediawiki.
-listChunk :: PandocMonad m => MWParser m String
-listChunk = template <|> count 1 anyChar
+-- Also multiline math: see #9293.
+listChunk :: PandocMonad m => MWParser m Text
+listChunk = template <|> (snd <$> withRaw math) <|> countChar 1 anyChar
 
 listItem' :: PandocMonad m => Char -> MWParser m Blocks
 listItem' c = try $ do
   listStart c
   skipMany spaceChar
   pos' <- getPosition
-  first <- concat <$> manyTill listChunk newline
+  first <- T.concat <$> manyTill listChunk newline
   rest <- many (try $ char c *> lookAhead listStartChar *>
-                   (concat <$> manyTill listChunk newline))
+                   (T.concat <$> manyTill listChunk newline))
   parseFromString (do setPosition pos'
                       firstParaToPlain . mconcat <$> many1 block)
-      $ unlines $ first : rest
+      $ T.unlines $ first : rest
 
 firstParaToPlain :: Blocks -> Blocks
 firstParaToPlain contents =
@@ -524,6 +601,7 @@
       <|> doubleQuotes
       <|> strong
       <|> emph
+      <|> behaviorSwitch
       <|> image
       <|> internalLink
       <|> externalLink
@@ -536,41 +614,55 @@
       <|> special
 
 str :: PandocMonad m => MWParser m Inlines
-str = B.str <$> many1 (noneOf $ specialChars ++ spaceChars)
+str = B.str <$> many1Char (noneOf $ specialChars ++ spaceChars)
 
 math :: PandocMonad m => MWParser m Inlines
-math = (B.displayMath . trim <$> try (many1 (char ':') >> charsInTags "math"))
-   <|> (B.math . trim <$> charsInTags "math")
-   <|> (B.displayMath . trim <$> try (dmStart *> manyTill anyChar dmEnd))
-   <|> (B.math . trim <$> try (mStart *> manyTill (satisfy (/='\n')) mEnd))
+math = (B.displayMath . trim <$> try (many1 (char ':') >> textInTags "math"))
+   <|> (B.math . trim <$> textInTags "math")
+   <|> (B.displayMath . trim <$> try (dmStart *> manyTillChar anyChar dmEnd))
+   <|> (B.math . trim <$> try (mStart *> manyTillChar (satisfy (/='\n')) mEnd))
  where dmStart = string "\\["
        dmEnd   = try (string "\\]")
        mStart  = string "\\("
        mEnd    = try (string "\\)")
 
-variable :: PandocMonad m => MWParser m String
+variable :: PandocMonad m => MWParser m Text
 variable = try $ do
   string "{{{"
-  contents <- manyTill anyChar (try $ string "}}}")
-  return $ "{{{" ++ contents ++ "}}}"
+  contents <- manyTillChar anyChar (try $ string "}}}")
+  return $ "{{{" <> contents <> "}}}"
 
+singleParaToPlain :: Blocks -> Blocks
+singleParaToPlain bs =
+  case B.toList bs of
+    [Para ils] -> B.fromList [Plain ils]
+    _ -> bs
+
 inlineTag :: PandocMonad m => MWParser m Inlines
 inlineTag = do
-  (tag, _) <- lookAhead $ htmlTag isInlineTag'
+  (tag, _) <- lookAhead $ htmlTag (\tag -> case tag of
+                                      TagOpen "hask" _ -> True
+                                      TagOpen "ref" _ -> True
+                                      TagOpen "nowiki" _ -> True
+                                      _ -> isInlineTag' tag)
   case tag of
-       TagOpen "ref" _ -> B.note . B.plain <$> inlinesInTags "ref"
+       TagOpen "ref" _ -> B.note . singleParaToPlain <$> blocksInTags "ref"
        TagOpen "nowiki" _ -> try $ do
           (_,raw) <- htmlTag (~== tag)
-          if '/' `elem` raw
+          if T.any (== '/') raw
              then return mempty
              else B.text . fromEntities <$>
-                       manyTill anyChar (htmlTag (~== TagClose "nowiki"))
-       TagOpen "br" _ -> B.linebreak <$ (htmlTag (~== TagOpen "br" []) -- will get /> too
+                       manyTillChar anyChar (htmlTag (~== TagClose ("nowiki" :: Text)))
+       TagOpen "br" _ -> B.linebreak <$ (htmlTag (~== TagOpen ("br" :: Text) []) -- will get /> too
                             *> optional blankline)
        TagOpen "strike" _ -> B.strikeout <$> inlinesInTags "strike"
        TagOpen "del" _ -> B.strikeout <$> inlinesInTags "del"
        TagOpen "sub" _ -> B.subscript <$> inlinesInTags "sub"
        TagOpen "sup" _ -> B.superscript <$> inlinesInTags "sup"
+       TagOpen "var" _ -> B.codeWith ("",["variable"],[]) <$> textInTags "var"
+       TagOpen "samp" _ -> B.codeWith ("",["sample"],[]) <$> textInTags "samp"
+       TagOpen "kbd" _ -> B.spanWith ("",["kbd"],[]) <$> inlinesInTags "kbd"
+       TagOpen "mark" _ -> B.spanWith ("",["mark"],[]) <$> inlinesInTags "mark"
        TagOpen "code" _ -> encode <$> inlinesInTags "code"
        TagOpen "tt" _ -> do
          inTT <- mwInTT <$> getState
@@ -578,12 +670,19 @@
          result <- encode <$> inlinesInTags "tt"
          updateState $ \st -> st{ mwInTT = inTT }
          return result
-       TagOpen "hask" _ -> B.codeWith ("",["haskell"],[]) <$> charsInTags "hask"
+       TagOpen "hask" _ -> B.codeWith ("",["haskell"],[]) <$> textInTags "hask"
        _ -> B.rawInline "html" . snd <$> htmlTag (~== tag)
 
 special :: PandocMonad m => MWParser m Inlines
-special = B.str <$> count 1 (notFollowedBy' (htmlTag isBlockTag') *>
-                             oneOf specialChars)
+special = B.str . T.singleton <$>
+  (notFollowedBy' (htmlTag (\t -> isInlineTag' t ||
+                                  isBlockTag' t ||
+                                  case t of
+                                    TagClose "ref" -> True
+                                    TagClose "hask" -> True
+                                    TagClose "nowiki" -> True
+                                    _ -> False)
+                                  ) *> oneOf specialChars)
 
 inlineHtml :: PandocMonad m => MWParser m Inlines
 inlineHtml = B.rawInline "html" . snd <$> htmlTag isInlineTag'
@@ -593,26 +692,28 @@
          <|> B.softbreak <$ endline
 
 endline :: PandocMonad m => MWParser m ()
-endline = () <$ try (newline <*
-                     notFollowedBy spaceChar <*
-                     notFollowedBy newline <*
-                     notFollowedBy' hrule <*
-                     notFollowedBy tableStart <*
-                     notFollowedBy' header <*
-                     notFollowedBy anyListStart)
+endline = do
+ getState >>= guard . mwAllowNewlines
+ () <$ try (newline <* notFollowedBy spaceChar <*
+                       notFollowedBy newline <*
+                       notFollowedBy' hrule <*
+                       notFollowedBy tableStart <*
+                       notFollowedBy' header <*
+                       notFollowedBy anyListStart)
 
-imageIdentifiers :: PandocMonad m => [MWParser m ()]
-imageIdentifiers = [sym (identifier ++ ":") | identifier <- identifiers]
-    where identifiers = ["File", "Image", "Archivo", "Datei", "Fichier",
-                         "Bild"]
+imageIdentifier :: PandocMonad m => MWParser m ()
+imageIdentifier = try $ do
+  ident <- T.pack <$> many1Till letter (char ':')
+  guard $ T.toLower ident `elem`
+            ["file", "image", "archivo", "datei", "fichier", "bild"]
 
 image :: PandocMonad m => MWParser m Inlines
 image = try $ do
   sym "[["
-  choice imageIdentifiers
-  fname <- addUnderscores <$> many1 (noneOf "|]")
+  imageIdentifier
+  fname <- addUnderscores <$> many1Char (noneOf "|]")
   _ <- many imageOption
-  dims <- try (char '|' *> sepBy (many digit) (char 'x') <* string "px")
+  dims <- try (char '|' *> sepBy (manyChar digit) (char 'x') <* string "px")
           <|> return []
   _ <- many imageOption
   let kvs = case dims of
@@ -622,9 +723,9 @@
   let attr = ("", [], kvs)
   caption <-   (B.str fname <$ sym "]]")
            <|> try (char '|' *> (mconcat <$> manyTill inline (sym "]]")))
-  return $ B.imageWith attr fname ("fig:" ++ stringify caption) caption
+  return $ B.imageWith attr fname (stringify caption) caption
 
-imageOption :: PandocMonad m => MWParser m String
+imageOption :: PandocMonad m => MWParser m Text
 imageOption = try $ char '|' *> opt
   where
     opt = try (oneOfStrings [ "border", "thumbnail", "frameless"
@@ -632,30 +733,28 @@
                             , "center", "none", "baseline", "sub"
                             , "super", "top", "text-top", "middle"
                             , "bottom", "text-bottom" ])
-      <|> try (string "frame")
+      <|> try (textStr "frame")
       <|> try (oneOfStrings ["link=","alt=","page=","class="] <* many (noneOf "|]"))
 
-collapseUnderscores :: String -> String
-collapseUnderscores []           = []
-collapseUnderscores ('_':'_':xs) = collapseUnderscores ('_':xs)
-collapseUnderscores (x:xs)       = x : collapseUnderscores xs
-
-addUnderscores :: String -> String
-addUnderscores = collapseUnderscores . intercalate "_" . words
+addUnderscores :: Text -> Text
+addUnderscores = T.intercalate "_" . splitTextBy sep . T.strip
+  where
+    sep c = isSpace c || c == '_'
 
 internalLink :: PandocMonad m => MWParser m Inlines
 internalLink = try $ do
   sym "[["
-  pagename <- unwords . words <$> many (noneOf "|]")
+  pagename <- T.unwords . T.words <$> manyChar (noneOf "|]")
   label <- option (B.text pagename) $ char '|' *>
              (  (mconcat <$> many1 (notFollowedBy (char ']') *> inline))
              -- the "pipe trick"
              -- [[Help:Contents|] -> "Contents"
-             <|> return (B.text $ drop 1 $ dropWhile (/=':') pagename) )
+             <|> return (B.text $ T.drop 1 $ T.dropWhile (/=':') pagename) )
   sym "]]"
-  linktrail <- B.text <$> many letter
-  let link = B.link (addUnderscores pagename) "wikilink" (label <> linktrail)
-  if "Category:" `isPrefixOf` pagename
+  -- see #8525:
+  linktrail <- B.text <$> manyChar (satisfy (\c -> isLetter c && not (isCJK c)))
+  let link = B.linkWith (mempty, ["wikilink"], mempty) (addUnderscores pagename) (stringify label) (label <> linktrail)
+  if "Category:" `T.isPrefixOf` pagename
      then do
        updateState $ \st -> st{ mwCategoryLinks = link : mwCategoryLinks st }
        return mempty
@@ -670,7 +769,7 @@
        <|> do char ']'
               num <- mwNextLinkNumber <$> getState
               updateState $ \st -> st{ mwNextLinkNumber = num + 1 }
-              return $ B.str $ show num
+              return $ B.str $ tshow num
   return $ B.link src "" lab
 
 url :: PandocMonad m => MWParser m Inlines
@@ -681,25 +780,57 @@
 -- | Parses a list of inlines between start and end delimiters.
 inlinesBetween :: (PandocMonad m, Show b) => MWParser m a -> MWParser m b -> MWParser m Inlines
 inlinesBetween start end =
-  (trimInlines . mconcat) <$> try (start >> many1Till inner end)
-    where inner      = innerSpace <|> (notFollowedBy' (() <$ whitespace) >> inline)
-          innerSpace = try $ whitespace <* notFollowedBy' end
+  trimInlines . mconcat <$> try (start >> many1Till inline end)
 
 emph :: PandocMonad m => MWParser m Inlines
-emph = B.emph <$> nested (inlinesBetween start end)
-    where start = sym "''" >> lookAhead nonspaceChar
+emph = B.emph <$> inlinesBetween start end
+    where start = sym "''"
           end   = try $ notFollowedBy' (() <$ strong) >> sym "''"
 
 strong :: PandocMonad m => MWParser m Inlines
-strong = B.strong <$> nested (inlinesBetween start end)
-    where start = sym "'''" >> lookAhead nonspaceChar
-          end   = try $ sym "'''"
+strong = B.strong <$> inlinesBetween start end
+    where start = sym "'''"
+          end   = sym "'''"
 
 doubleQuotes :: PandocMonad m => MWParser m Inlines
 doubleQuotes = do
   guardEnabled Ext_smart
   inTT <- mwInTT <$> getState
   guard (not inTT)
-  B.doubleQuoted <$> nested (inlinesBetween openDoubleQuote closeDoubleQuote)
+  B.doubleQuoted <$> inlinesBetween openDoubleQuote closeDoubleQuote
     where openDoubleQuote = sym "\"" >> lookAhead nonspaceChar
           closeDoubleQuote = try $ sym "\""
+
+behaviorSwitch :: PandocMonad m => MWParser m Inlines
+behaviorSwitch = try $ do
+  let reservedMagicWords = [ "NOTOC"
+              , "FORCETOC"
+              , "TOC"
+              , "NOEDITSECTION"
+              , "NEWSECTIONLINK"
+              , "NONEWSECTIONLINK"
+              , "NOGALLERY"
+              , "HIDDENCAT"
+              , "EXPECTUNUSEDCATEGORY"
+              , "NOCONTENTCONVERT"
+              , "NOCC"
+              , "NOTITLECONVERT"
+              , "NOTC"
+              , "INDEX"
+              , "NOINDEX"
+              , "STATICREDIRECT"
+              , "EXPECTUNUSEDTEMPLATE"
+              -- From popular extensions
+              , "NOGLOBAL"
+              , "DISAMBIG"
+              , "ARCHIVEDTALK"
+              , "NOTALK"
+              ]
+  string "__"
+  name <- many1 alphaNum
+  string "__"
+  case name `elem` reservedMagicWords of
+    True -> do
+      updateState $ \st -> st{ mwMeta = B.setMeta (T.toLower $ T.pack name) True (mwMeta st) }
+      return mempty
+    False -> return $ B.str $ "__" <> T.pack name <> "__"
diff --git a/src/Text/Pandoc/Readers/Metadata.hs b/src/Text/Pandoc/Readers/Metadata.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Readers/Metadata.hs
@@ -0,0 +1,190 @@
+{-# LANGUAGE OverloadedStrings   #-}
+{-# LANGUAGE ScopedTypeVariables #-}
+{- |
+   Module      : Text.Pandoc.Readers.Metadata
+   Copyright   : Copyright (C) 2006-2024 John MacFarlane
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : John MacFarlane <jgm@berkeley.edu>
+   Stability   : alpha
+   Portability : portable
+
+Parse YAML/JSON metadata to 'Pandoc' 'Meta'.
+-}
+module Text.Pandoc.Readers.Metadata (
+  yamlBsToMeta,
+  yamlBsToRefs,
+  yamlMetaBlock,
+  yamlMap ) where
+
+
+import Control.Monad.Except (throwError)
+import qualified Data.ByteString as B
+import qualified Data.Map as M
+import qualified Data.Vector as V
+import Data.Text (Text)
+import qualified Data.Text as T
+import qualified Data.Yaml as Yaml
+import qualified Data.Yaml.Internal as Yaml
+import qualified Text.Libyaml as Y
+import Data.Aeson (Value(..), Object, Result(..), fromJSON, (.:?), withObject,
+                   FromJSON)
+import Data.Aeson.Types (formatRelativePath, parse)
+import Text.Pandoc.Shared (tshow, blocksToInlines)
+import Text.Pandoc.Class (PandocMonad (..), report)
+import Text.Pandoc.Definition
+import Text.Pandoc.Error
+import Text.Pandoc.Logging (LogMessage(YamlWarning))
+import Text.Pandoc.Parsing hiding (tableWith, parse)
+import qualified Text.Pandoc.UTF8 as UTF8
+import System.IO.Unsafe (unsafePerformIO)
+
+yamlBsToMeta :: (PandocMonad m, HasLastStrPosition st)
+             => ParsecT Sources st m (Future st MetaValue)
+             -> B.ByteString
+             -> ParsecT Sources st m (Future st Meta)
+yamlBsToMeta pMetaValue bstr = do
+  pos <- getPosition
+  case decodeAllWithWarnings bstr of
+       Right (warnings, xs) -> do
+         mapM_ (\(Yaml.DuplicateKey jpath) ->
+                          report (YamlWarning pos $ "Duplicate key: " <>
+                                  T.pack (formatRelativePath jpath)))
+           warnings
+         case xs of
+           (Object o : _) -> fmap Meta <$> yamlMap pMetaValue o
+           [Null] -> return . return $ mempty
+           [] -> return . return $ mempty
+           _  -> Prelude.fail "expected YAML object"
+       Left err' -> do
+         let msg = T.pack $ "Error parsing YAML metadata at " <>
+                             show pos <> ":\n" <>
+                             Yaml.prettyPrintParseException err'
+         throwError $ PandocParseError $
+           if "did not find expected key" `T.isInfixOf` msg
+              then msg <>
+                   "\nConsider enclosing the entire field in 'single quotes'"
+              else msg
+
+decodeAllWithWarnings :: FromJSON a
+                      => B.ByteString
+                      -> (Either Yaml.ParseException ([Yaml.Warning], [a]))
+decodeAllWithWarnings = either Left (\(ws,res)
+                       -> case res of
+                            Left s  -> Left (Yaml.AesonException s)
+                            Right v -> Right (ws, v))
+                   . unsafePerformIO
+                   . Yaml.decodeAllHelper
+                   . Y.decode
+
+-- Returns filtered list of references.
+yamlBsToRefs :: (PandocMonad m, HasLastStrPosition st)
+             => ParsecT Sources st m (Future st MetaValue)
+             -> (Text -> Bool) -- ^ Filter for id
+             -> B.ByteString
+             -> ParsecT Sources st m (Future st [MetaValue])
+yamlBsToRefs pMetaValue idpred bstr =
+  case Yaml.decodeAllEither' bstr of
+       Right (Object m : _) -> do
+         case parse (withObject "metadata" (.:? "references")) (Object m) of
+           Success (Just refs) -> sequence <$>
+                 mapM (yamlToMetaValue pMetaValue) (filter hasSelectedId refs)
+           _ -> return $ return []
+       Right (Array v : _) -> do
+         let refs = filter hasSelectedId $ V.toList v
+         sequence <$> mapM (yamlToMetaValue pMetaValue) (filter hasSelectedId refs)
+       Right _ -> return . return $ []
+       Left err' -> throwError $ PandocParseError
+                               $ T.pack $ Yaml.prettyPrintParseException err'
+ where
+   isSelected (String t) = idpred t
+   isSelected _ = False
+   hasSelectedId (Object o) =
+     case parse (withObject "ref" (.:? "id")) (Object o) of
+       Success (Just id') -> isSelected id'
+       _ -> False
+   hasSelectedId _ = False
+
+normalizeMetaValue :: (PandocMonad m, HasLastStrPosition st)
+                   => ParsecT Sources st m (Future st MetaValue)
+                   -> Text
+                   -> ParsecT Sources st m (Future st MetaValue)
+normalizeMetaValue pMetaValue x =
+   -- Note: a standard quoted or unquoted YAML value will
+   -- not end in a newline, but a "block" set off with
+   -- `|` or `>` will.
+   if "\n" `T.isSuffixOf` (T.dropWhileEnd isSpaceChar x) -- see #6823
+      then parseFromString' pMetaValue (x <> "\n\n")
+      else try (parseFromString' asInlines x') -- see #8358
+           <|> -- see #8465
+           parseFromString' asInlines (x' <> "\n\n")
+  where x' = T.dropWhile isSpaceOrNlChar x
+        asInlines = fmap b2i <$> pMetaValue
+        b2i (MetaBlocks bs) = MetaInlines (blocksToInlines bs)
+        b2i y = y
+        isSpaceChar ' '  = True
+        isSpaceChar '\t' = True
+        isSpaceChar _    = False
+        isSpaceOrNlChar '\r' = True
+        isSpaceOrNlChar '\n' = True
+        isSpaceOrNlChar c = isSpaceChar c
+
+yamlToMetaValue :: (PandocMonad m, HasLastStrPosition st)
+                => ParsecT Sources st m (Future st MetaValue)
+                -> Value
+                -> ParsecT Sources st m (Future st MetaValue)
+yamlToMetaValue pMetaValue v =
+  case v of
+       String t -> normalizeMetaValue pMetaValue t
+       Bool b -> return $ return $ MetaBool b
+       Number d -> normalizeMetaValue pMetaValue $
+         case fromJSON v of
+           Success (x :: Int) -> tshow x
+           _ -> tshow d
+       Null -> return $ return $ MetaString ""
+       Array{} -> do
+         case fromJSON v of
+           Error err' -> throwError $ PandocParseError $ T.pack err'
+           Success xs -> fmap MetaList . sequence <$>
+                          mapM (yamlToMetaValue pMetaValue) xs
+       Object o -> fmap MetaMap <$> yamlMap pMetaValue o
+
+yamlMap :: (PandocMonad m, HasLastStrPosition st)
+        => ParsecT Sources st m (Future st MetaValue)
+        -> Object
+        -> ParsecT Sources st m (Future st (M.Map Text MetaValue))
+yamlMap pMetaValue o = do
+    case fromJSON (Object o) of
+      Error err' -> throwError $ PandocParseError $ T.pack err'
+      Success (m' :: M.Map Text Value) -> do
+        let kvs = filter (not . ignorable . fst) $ M.toList m'
+        fmap M.fromList . sequence <$> mapM toMeta kvs
+  where
+    ignorable t = "_" `T.isSuffixOf` t
+    toMeta (k, v) = do
+      fv <- yamlToMetaValue pMetaValue v
+      return $ do
+        v' <- fv
+        return (k, v')
+
+-- | Parse a YAML metadata block using the supplied 'MetaValue' parser.
+yamlMetaBlock :: (HasLastStrPosition st, PandocMonad m)
+              => ParsecT Sources st m (Future st MetaValue)
+              -> ParsecT Sources st m (Future st Meta)
+yamlMetaBlock parser = try $ do
+  pos <- getPosition
+  string "---"
+  blankline
+  notFollowedBy blankline  -- if --- is followed by a blank it's an HRULE
+  rawYamlLines <- manyTill anyLine stopLine
+  -- by including --- and ..., we allow yaml blocks with just comments:
+  let rawYaml = T.unlines ("---" : (rawYamlLines ++ ["..."]))
+  optional blanklines
+  oldPos <- getPosition
+  setPosition pos
+  res <- yamlBsToMeta parser $ UTF8.fromText rawYaml
+  setPosition oldPos
+  pure res
+
+stopLine :: Monad m => ParsecT Sources st m ()
+stopLine = try $ (string "---" <|> string "...") >> blankline >> return ()
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,796 +1,991 @@
-{-# LANGUAGE FlexibleContexts      #-}
-{-
-  Copyright (C) 2017 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 Alexander Krotov
-   License     : GNU GPL, version 2 or above
-
-   Maintainer  : Alexander Krotov <ilabdsf@gmail.com>
-   Stability   : alpha
-   Portability : portable
-
-Conversion of Muse text to 'Pandoc' document.
--}
-{-
-TODO:
-- Page breaks (five "*")
-- Org tables
-- table.el tables
-- Images with attributes (floating and width)
-- Citations and <biblio>
-- <play> environment
--}
-module Text.Pandoc.Readers.Muse (readMuse) where
-
-import Control.Monad
-import Control.Monad.Except (throwError)
-import Data.Char (isLetter)
-import Data.List (stripPrefix)
-import qualified Data.Map as M
-import Data.Maybe (fromMaybe)
-import Data.Text (Text, unpack)
-import System.FilePath (takeExtension)
-import Text.HTML.TagSoup
-import Text.Pandoc.Builder (Blocks, Inlines)
-import qualified Text.Pandoc.Builder as B
-import Text.Pandoc.Class (PandocMonad (..))
-import Text.Pandoc.Definition
-import Text.Pandoc.Logging
-import Text.Pandoc.Options
-import Text.Pandoc.Parsing
-import Text.Pandoc.Readers.HTML (htmlTag)
-import Text.Pandoc.Shared (crFilter, underlineSpan)
-
--- | Read Muse from an input string and return a Pandoc document.
-readMuse :: PandocMonad m
-         => ReaderOptions
-         -> Text
-         -> m Pandoc
-readMuse opts s = do
-  res <- readWithM parseMuse def{ stateOptions = opts } (unpack (crFilter s))
-  case res of
-       Left e  -> throwError e
-       Right d -> return d
-
-type MuseParser = ParserT String ParserState
-
---
--- main parser
---
-
-parseMuse :: PandocMonad m => MuseParser m Pandoc
-parseMuse = do
-  many directive
-  blocks <- parseBlocks
-  st <- getState
-  let doc = runF (do Pandoc _ bs <- B.doc <$> blocks
-                     meta <- stateMeta' st
-                     return $ Pandoc meta bs) st
-  reportLogMessages
-  return doc
-
-parseBlocks :: PandocMonad m => MuseParser m (F Blocks)
-parseBlocks = do
-  res <- mconcat <$> many block
-  spaces
-  eof
-  return res
-
---
--- utility functions
---
-
-eol :: Stream s m Char => ParserT s st m ()
-eol = void newline <|> eof
-
-htmlElement :: PandocMonad m => String -> MuseParser m (Attr, String)
-htmlElement tag = try $ do
-  (TagOpen _ attr, _) <- htmlTag (~== TagOpen tag [])
-  content <- manyTill anyChar endtag
-  return (htmlAttrToPandoc attr, content)
-  where
-    endtag = void $ htmlTag (~== TagClose tag)
-
-htmlAttrToPandoc :: [Attribute String] -> Attr
-htmlAttrToPandoc attrs = (ident, classes, keyvals)
-  where
-    ident   = fromMaybe "" $ lookup "id" attrs
-    classes = maybe [] words $ lookup "class" attrs
-    keyvals = [(k,v) | (k,v) <- attrs, k /= "id" && k /= "class"]
-
-parseHtmlContentWithAttrs :: PandocMonad m
-                          => String -> MuseParser m a -> MuseParser m (Attr, [a])
-parseHtmlContentWithAttrs tag parser = do
-  (attr, content) <- htmlElement tag
-  parsedContent <- parseContent (content ++ "\n")
-  return (attr, parsedContent)
-  where
-    parseContent = parseFromString $ manyTill parser endOfContent
-    endOfContent = try $ skipMany blankline >> skipSpaces >> eof
-
-parseHtmlContent :: PandocMonad m => String -> MuseParser m a -> MuseParser m [a]
-parseHtmlContent tag p = fmap snd (parseHtmlContentWithAttrs tag p)
-
-commonPrefix :: String -> String -> String
-commonPrefix _ [] = []
-commonPrefix [] _ = []
-commonPrefix (x:xs) (y:ys)
-  | x == y    = x : commonPrefix xs ys
-  | otherwise = []
-
-atStart :: PandocMonad m => MuseParser m a -> MuseParser m a
-atStart p = do
-  pos <- getPosition
-  st <- getState
-  guard $ stateLastStrPos st /= Just pos
-  p
-
---
--- directive parsers
---
-
--- While not documented, Emacs Muse allows "-" in directive name
-parseDirectiveKey :: PandocMonad m => MuseParser m String
-parseDirectiveKey = do
-  char '#'
-  many (letter <|> char '-')
-
-parseEmacsDirective :: PandocMonad m => MuseParser m (String, F Inlines)
-parseEmacsDirective = do
-  key <- parseDirectiveKey
-  space
-  spaces
-  raw <- manyTill anyChar eol
-  value <- parseFromString (trimInlinesF . mconcat <$> many inline) raw
-  return (key, value)
-
-parseAmuseDirective :: PandocMonad m => MuseParser m (String, F Inlines)
-parseAmuseDirective = do
-  key <- parseDirectiveKey
-  space
-  spaces
-  first <- manyTill anyChar eol
-  rest <- manyTill anyLine endOfDirective
-  many blankline
-  value <- parseFromString (trimInlinesF . mconcat <$> many inline) $ unlines (first : rest)
-  return (key, value)
-  where
-    endOfDirective = lookAhead $ endOfInput <|> try (void blankline) <|> try (void parseDirectiveKey)
-    endOfInput     = try $ skipMany blankline >> skipSpaces >> eof
-
-directive :: PandocMonad m => MuseParser m ()
-directive = do
-  ext <- getOption readerExtensions
-  (key, value) <- if extensionEnabled Ext_amuse ext then parseAmuseDirective else parseEmacsDirective
-  updateState $ \st -> st { stateMeta' = B.setMeta key <$> value <*> stateMeta' st }
-
---
--- block parsers
---
-
-block :: PandocMonad m => MuseParser m (F Blocks)
-block = do
-  res <- mempty <$ skipMany1 blankline
-         <|> blockElements
-         <|> para
-  skipMany blankline
-  trace (take 60 $ show $ B.toList $ runF res defaultParserState)
-  return res
-
-blockElements :: PandocMonad m => MuseParser m (F Blocks)
-blockElements = choice [ comment
-                       , separator
-                       , header
-                       , example
-                       , exampleTag
-                       , literal
-                       , centerTag
-                       , rightTag
-                       , quoteTag
-                       , divTag
-                       , verseTag
-                       , lineBlock
-                       , bulletList
-                       , orderedList
-                       , definitionList
-                       , table
-                       , commentTag
-                       , amuseNoteBlock
-                       , emacsNoteBlock
-                       ]
-
-comment :: PandocMonad m => MuseParser m (F Blocks)
-comment = try $ do
-  char ';'
-  optionMaybe (spaceChar >> (many $ noneOf "\n"))
-  eol
-  return mempty
-
-separator :: PandocMonad m => MuseParser m (F Blocks)
-separator = try $ do
-  string "----"
-  many $ char '-'
-  many spaceChar
-  eol
-  return $ return B.horizontalRule
-
-header :: PandocMonad m => MuseParser m (F Blocks)
-header = try $ do
-  st <- stateParserContext <$> getState
-  q <- stateQuoteContext <$> getState
-  getPosition >>= \pos -> guard (st == NullState && q == NoQuote && sourceColumn pos == 1)
-  level <- fmap length $ many1 $ char '*'
-  guard $ level <= 5
-  spaceChar
-  content <- trimInlinesF . mconcat <$> manyTill inline eol
-  anchorId <- option "" parseAnchor
-  attr <- registerHeader (anchorId, [], []) (runF content defaultParserState)
-  return $ B.headerWith attr level <$> content
-
-example :: PandocMonad m => MuseParser m (F Blocks)
-example = try $ do
-  string "{{{"
-  optionMaybe blankline
-  contents <- manyTill anyChar $ try (optionMaybe blankline >> string "}}}")
-  return $ return $ B.codeBlock contents
-
--- Trim up to one newline from the beginning and the end,
--- in case opening and/or closing tags are on separate lines.
-chop :: String -> String
-chop = lchop . rchop
-  where lchop s = case s of
-                    '\n':ss -> ss
-                    _       -> s
-        rchop = reverse . lchop . reverse
-
-exampleTag :: PandocMonad m => MuseParser m (F Blocks)
-exampleTag = do
-  (attr, contents) <- htmlElement "example"
-  return $ return $ B.codeBlockWith attr $ chop contents
-
-literal :: PandocMonad m => MuseParser m (F Blocks)
-literal = do
-  guardDisabled Ext_amuse -- Text::Amuse does not support <literal>
-  (return . rawBlock) <$> htmlElement "literal"
-  where
-    -- FIXME: Emacs Muse inserts <literal> without style into all output formats, but we assume HTML
-    format (_, _, kvs)        = fromMaybe "html" $ lookup "style" kvs
-    rawBlock (attrs, content) = B.rawBlock (format attrs) $ chop content
-
-blockTag :: PandocMonad m
-          => (Blocks -> Blocks)
-          -> String
-          -> MuseParser m (F Blocks)
-blockTag f s = do
-  res <- parseHtmlContent s block
-  return $ f <$> mconcat res
-
--- <center> tag is ignored
-centerTag :: PandocMonad m => MuseParser m (F Blocks)
-centerTag = blockTag id "center"
-
--- <right> tag is ignored
-rightTag :: PandocMonad m => MuseParser m (F Blocks)
-rightTag = blockTag id "right"
-
-quoteTag :: PandocMonad m => MuseParser m (F Blocks)
-quoteTag = withQuoteContext InDoubleQuote $ blockTag B.blockQuote "quote"
-
--- <div> tag is supported by Emacs Muse, but not Amusewiki 2.025
-divTag :: PandocMonad m => MuseParser m (F Blocks)
-divTag = do
-  (attrs, content) <- parseHtmlContentWithAttrs "div" block
-  return $ B.divWith attrs <$> mconcat content
-
-verseLine :: PandocMonad m => MuseParser m String
-verseLine = do
-  line <- anyLine <|> many1Till anyChar eof
-  let (white, rest) = span (== ' ') line
-  return $ replicate (length white) '\160' ++ rest
-
-verseLines :: PandocMonad m => MuseParser m (F Blocks)
-verseLines = do
-  optionMaybe blankline -- Skip blankline after opening tag on separate line
-  lns <- many verseLine
-  lns' <- mapM (parseFromString' (trimInlinesF . mconcat <$> many inline)) lns
-  return $ B.lineBlock <$> sequence lns'
-
-verseTag :: PandocMonad m => MuseParser m (F Blocks)
-verseTag = do
-  (_, content) <- htmlElement "verse"
-  parseFromString verseLines content
-
-commentTag :: PandocMonad m => MuseParser m (F Blocks)
-commentTag = parseHtmlContent "comment" anyChar >> return mempty
-
--- Indented paragraph is either center, right or quote
-para :: PandocMonad m => MuseParser m (F Blocks)
-para = do
- indent <- length <$> many spaceChar
- st <- stateParserContext <$> getState
- let f = if st /= ListItemState && indent >= 2 && indent < 6 then B.blockQuote else id
- fmap (f . B.para) . trimInlinesF . mconcat <$> many1Till inline endOfParaElement
- where
-   endOfParaElement = lookAhead $ endOfInput <|> endOfPara <|> newBlockElement
-   endOfInput       = try $ skipMany blankline >> skipSpaces >> eof
-   endOfPara        = try $ blankline >> skipMany1 blankline
-   newBlockElement  = try $ blankline >> void blockElements
-
-noteMarker :: PandocMonad m => MuseParser m String
-noteMarker = try $ do
-  char '['
-  first <- oneOf "123456789"
-  rest <- manyTill digit (char ']')
-  return $ first:rest
-
--- Amusewiki version of note
--- Parsing is similar to list item, except that note marker is used instead of list marker
-amuseNoteBlock :: PandocMonad m => MuseParser m (F Blocks)
-amuseNoteBlock = try $ do
-  guardEnabled Ext_amuse
-  pos <- getPosition
-  ref <- noteMarker <* spaceChar
-  content <- listItemContents $ 3 + length ref
-  oldnotes <- stateNotes' <$> getState
-  case M.lookup ref oldnotes of
-    Just _  -> logMessage $ DuplicateNoteReference ref pos
-    Nothing -> return ()
-  updateState $ \s -> s{ stateNotes' = M.insert ref (pos, content) oldnotes }
-  return mempty
-
--- Emacs version of note
--- Notes are allowed only at the end of text, no indentation is required.
-emacsNoteBlock :: PandocMonad m => MuseParser m (F Blocks)
-emacsNoteBlock = try $ do
-  guardDisabled Ext_amuse
-  pos <- getPosition
-  ref <- noteMarker <* skipSpaces
-  content <- mconcat <$> blocksTillNote
-  oldnotes <- stateNotes' <$> getState
-  case M.lookup ref oldnotes of
-    Just _  -> logMessage $ DuplicateNoteReference ref pos
-    Nothing -> return ()
-  updateState $ \s -> s{ stateNotes' = M.insert ref (pos, content) oldnotes }
-  return mempty
-  where
-    blocksTillNote =
-      many1Till block (eof <|> () <$ lookAhead noteMarker)
-
---
--- Verse markup
---
-
-lineVerseLine :: PandocMonad m => MuseParser m String
-lineVerseLine = try $ do
-  char '>'
-  white <- many1 (char ' ' >> pure '\160')
-  rest <- anyLine
-  return $ tail white ++ rest
-
-blanklineVerseLine :: PandocMonad m => MuseParser m Char
-blanklineVerseLine = try $ char '>' >> blankline
-
-lineBlock :: PandocMonad m => MuseParser m (F Blocks)
-lineBlock = try $ do
-  lns <- many1 (pure <$> blanklineVerseLine <|> lineVerseLine)
-  lns' <- mapM (parseFromString' (trimInlinesF . mconcat <$> many inline)) lns
-  return $ B.lineBlock <$> sequence lns'
-
---
--- lists
---
-
-listLine :: PandocMonad m => Int -> MuseParser m String
-listLine markerLength = try $ do
-  indentWith markerLength
-  manyTill anyChar eol
-
-withListContext :: PandocMonad m => MuseParser m a -> MuseParser m a
-withListContext p = do
-  state <- getState
-  let oldContext = stateParserContext state
-  setState $ state { stateParserContext = ListItemState }
-  parsed <- p
-  updateState (\st -> st {stateParserContext = oldContext})
-  return parsed
-
-listContinuation :: PandocMonad m => Int -> MuseParser m [String]
-listContinuation markerLength = try $ do
-  result <- many1 $ listLine markerLength
-  blank <- option id ((++ [""]) <$ blankline)
-  return $ blank result
-
-listStart :: PandocMonad m => MuseParser m Int -> MuseParser m Int
-listStart marker = try $ do
-  preWhitespace <- length <$> many spaceChar
-  st <- stateParserContext <$> getState
-  getPosition >>= \pos -> guard (st == ListItemState || sourceColumn pos /= 1)
-  markerLength <- marker
-  void spaceChar <|> eol
-  return $ preWhitespace + markerLength + 1
-
-dropSpacePrefix :: [String] -> [String]
-dropSpacePrefix lns =
-  map (drop maxIndent) lns
-  where flns = filter (not . all (== ' ')) lns
-        maxIndent = if null flns then 0 else length $ takeWhile (== ' ') $ foldl1 commonPrefix flns
-
-listItemContents :: PandocMonad m => Int -> MuseParser m (F Blocks)
-listItemContents markerLength = do
-  firstLine <- manyTill anyChar eol
-  restLines <- many $ listLine markerLength
-  blank <- option id ((++ [""]) <$ blankline)
-  let first = firstLine : blank restLines
-  rest <- many $ listContinuation markerLength
-  let allLines = concat (first : rest)
-  parseFromString (withListContext parseBlocks) $ unlines (dropSpacePrefix allLines)
-
-listItem :: PandocMonad m => MuseParser m Int -> MuseParser m (F Blocks)
-listItem start = try $ do
-  markerLength <- start
-  listItemContents markerLength
-
-bulletListItems :: PandocMonad m => MuseParser m (F [Blocks])
-bulletListItems = sequence <$> many1 (listItem bulletListStart)
-
-bulletListStart :: PandocMonad m => MuseParser m Int
-bulletListStart = listStart (char '-' >> return 1)
-
-bulletList :: PandocMonad m => MuseParser m (F Blocks)
-bulletList = do
-  listItems <- bulletListItems
-  return $ B.bulletList <$> listItems
-
-orderedListStart :: PandocMonad m
-                 => ListNumberStyle
-                 -> ListNumberDelim
-                 -> MuseParser m Int
-orderedListStart style delim = listStart (snd <$> withHorizDisplacement (orderedListMarker style delim))
-
-orderedList :: PandocMonad m => MuseParser m (F Blocks)
-orderedList = try $ do
-  p@(_, style, delim) <- lookAhead (many spaceChar *> anyOrderedListMarker <* (eol <|> void spaceChar))
-  guard $ style `elem` [Decimal, LowerAlpha, UpperAlpha, LowerRoman, UpperRoman]
-  guard $ delim == Period
-  items <- sequence <$> many1 (listItem $ orderedListStart style delim)
-  return $ B.orderedListWith p <$> items
-
-definitionListItem :: PandocMonad m => MuseParser m (F (Inlines, [Blocks]))
-definitionListItem = try $ do
-  rawTerm <- termParser
-  term <- parseFromString (trimInlinesF . mconcat <$> many inline) rawTerm
-  many1 spaceChar
-  string "::"
-  firstLine <- manyTill anyChar eol
-  restLines <- manyTill anyLine endOfListItemElement
-  let lns = dropWhile (== ' ') firstLine : dropSpacePrefix restLines
-  lineContent <- parseFromString (withListContext parseBlocks) $ unlines lns
-  pure $ do lineContent' <- lineContent
-            term' <- term
-            pure (term', [lineContent'])
-  where
-    termParser = (guardDisabled Ext_amuse <|> void spaceChar) >> -- Initial space is required by Amusewiki, but not Emacs Muse
-                 many spaceChar >>
-                 many1Till (noneOf "\n") (lookAhead (void (try (spaceChar >> string "::"))))
-    endOfInput = lookAhead $ try $ skipMany blankline >> skipSpaces >> eof
-    twoBlankLines = try $ blankline >> skipMany1 blankline
-    newDefinitionListItem = try $ void termParser
-    endOfListItemElement = lookAhead $ endOfInput <|> newDefinitionListItem <|> twoBlankLines
-
-definitionListItems :: PandocMonad m => MuseParser m (F [(Inlines, [Blocks])])
-definitionListItems = sequence <$> many1 definitionListItem
-
-definitionList :: PandocMonad m => MuseParser m (F Blocks)
-definitionList = do
-  listItems <- definitionListItems
-  return $ B.definitionList <$> listItems
-
---
--- tables
---
-
-data MuseTable = MuseTable
-  { museTableCaption :: Inlines
-  , museTableHeaders :: [[Blocks]]
-  , museTableRows    :: [[Blocks]]
-  , museTableFooters :: [[Blocks]]
-  }
-
-data MuseTableElement = MuseHeaderRow (F [Blocks])
-                      | MuseBodyRow   (F [Blocks])
-                      | MuseFooterRow (F [Blocks])
-                      | MuseCaption (F Inlines)
-
-museToPandocTable :: MuseTable -> Blocks
-museToPandocTable (MuseTable caption headers body footers) =
-  B.table caption attrs headRow rows
-  where ncol = maximum (0 : map length (headers ++ body ++ footers))
-        attrs = replicate ncol (AlignDefault, 0.0)
-        headRow = if null headers then [] else head headers
-        rows = (if null headers then [] else tail headers) ++ body ++ footers
-
-museAppendElement :: MuseTable
-                  -> MuseTableElement
-                  -> F MuseTable
-museAppendElement tbl element =
-  case element of
-    MuseHeaderRow row -> do
-      row' <- row
-      return tbl{ museTableHeaders = museTableHeaders tbl ++ [row'] }
-    MuseBodyRow row -> do
-      row' <- row
-      return tbl{ museTableRows = museTableRows tbl ++ [row'] }
-    MuseFooterRow row-> do
-      row' <- row
-      return tbl{ museTableFooters = museTableFooters tbl ++ [row'] }
-    MuseCaption inlines -> do
-      inlines' <- inlines
-      return tbl{ museTableCaption = inlines' }
-
-tableCell :: PandocMonad m => MuseParser m (F Blocks)
-tableCell = try $ fmap B.plain . trimInlinesF . mconcat <$> manyTill inline (lookAhead cellEnd)
-  where cellEnd = try $ void (many1 spaceChar >> char '|') <|> eol
-
-tableElements :: PandocMonad m => MuseParser m [MuseTableElement]
-tableElements = tableParseElement `sepEndBy1` eol
-
-elementsToTable :: [MuseTableElement] -> F MuseTable
-elementsToTable = foldM museAppendElement emptyTable
-  where emptyTable = MuseTable mempty mempty mempty mempty
-
-table :: PandocMonad m => MuseParser m (F Blocks)
-table = try $ do
-  rows <- tableElements
-  let tbl = elementsToTable rows
-  let pandocTbl = museToPandocTable <$> tbl :: F Blocks
-  return pandocTbl
-
-tableParseElement :: PandocMonad m => MuseParser m MuseTableElement
-tableParseElement = tableParseHeader
-                <|> tableParseBody
-                <|> tableParseFooter
-                <|> tableParseCaption
-
-tableParseRow :: PandocMonad m => Int -> MuseParser m (F [Blocks])
-tableParseRow n = try $ do
-  fields <- tableCell `sepBy2` fieldSep
-  return $ sequence fields
-    where p `sepBy2` sep = (:) <$> p <*> many1 (sep >> p)
-          fieldSep = many1 spaceChar >> count n (char '|') >> (void (many1 spaceChar) <|> void (lookAhead newline))
-
-tableParseHeader :: PandocMonad m => MuseParser m MuseTableElement
-tableParseHeader = MuseHeaderRow <$> tableParseRow 2
-
-tableParseBody :: PandocMonad m => MuseParser m MuseTableElement
-tableParseBody = MuseBodyRow <$> tableParseRow 1
-
-tableParseFooter :: PandocMonad m => MuseParser m MuseTableElement
-tableParseFooter = MuseFooterRow <$> tableParseRow 3
-
-tableParseCaption :: PandocMonad m => MuseParser m MuseTableElement
-tableParseCaption = try $ do
-  many spaceChar
-  string "|+"
-  contents <- trimInlinesF . mconcat <$> many1Till inline (lookAhead $ string "+|")
-  string "+|"
-  return $ MuseCaption contents
-
---
--- inline parsers
---
-
-inlineList :: PandocMonad m => [MuseParser m (F Inlines)]
-inlineList = [ endline
-             , br
-             , anchor
-             , footnote
-             , strong
-             , strongTag
-             , emph
-             , emphTag
-             , underlined
-             , superscriptTag
-             , subscriptTag
-             , strikeoutTag
-             , verbatimTag
-             , nbsp
-             , link
-             , code
-             , codeTag
-             , inlineLiteralTag
-             , whitespace
-             , str
-             , symbol
-             ]
-
-inline :: PandocMonad m => MuseParser m (F Inlines)
-inline = choice inlineList <?> "inline"
-
-endline :: PandocMonad m => MuseParser m (F Inlines)
-endline = try $ do
-  newline
-  notFollowedBy blankline
-  returnF B.softbreak
-
-parseAnchor :: PandocMonad m => MuseParser m String
-parseAnchor = try $ do
-  getPosition >>= \pos -> guard (sourceColumn pos == 1)
-  char '#'
-  first <- letter
-  rest <- many (letter <|> digit)
-  skipMany spaceChar <|> void newline
-  return $ first:rest
-
-anchor :: PandocMonad m => MuseParser m (F Inlines)
-anchor = try $ do
-  anchorId <- parseAnchor
-  return $ return $ B.spanWith (anchorId, [], []) mempty
-
-footnote :: PandocMonad m => MuseParser m (F Inlines)
-footnote = try $ do
-  ref <- noteMarker
-  return $ do
-    notes <- asksF stateNotes'
-    case M.lookup ref notes of
-      Nothing -> return $ B.str $ "[" ++ ref ++ "]"
-      Just (_pos, contents) -> do
-        st <- askF
-        let contents' = runF contents st { stateNotes' = M.empty }
-        return $ B.note contents'
-
-whitespace :: PandocMonad m => MuseParser m (F Inlines)
-whitespace = fmap return (lb <|> regsp)
-  where lb = try $ skipMany spaceChar >> linebreak >> return B.space
-        regsp = try $ skipMany1 spaceChar >> return B.space
-
-br :: PandocMonad m => MuseParser m (F Inlines)
-br = try $ do
-  string "<br>"
-  return $ return B.linebreak
-
-linebreak :: PandocMonad m => MuseParser m (F Inlines)
-linebreak = newline >> notFollowedBy newline >> (lastNewline <|> innerNewline)
-  where lastNewline  = do
-                         eof
-                         return $ return mempty
-        innerNewline = return $ return B.space
-
-emphasisBetween :: (PandocMonad m, Show a) => MuseParser m a -> MuseParser m (F Inlines)
-emphasisBetween c = try $ enclosedInlines c c
-
-enclosedInlines :: (PandocMonad m, Show a, Show b)
-                => MuseParser m a
-                -> MuseParser m b
-                -> MuseParser m (F Inlines)
-enclosedInlines start end = try $
-  trimInlinesF . mconcat <$> (enclosed (atStart start) end inline <* notFollowedBy (satisfy isLetter))
-
-inlineTag :: PandocMonad m
-          => (Inlines -> Inlines)
-          -> String
-          -> MuseParser m (F Inlines)
-inlineTag f s = try $ do
-  res <- parseHtmlContent s inline
-  return $ f <$> mconcat res
-
-strongTag :: PandocMonad m => MuseParser m (F Inlines)
-strongTag = inlineTag B.strong "strong"
-
-strong :: PandocMonad m => MuseParser m (F Inlines)
-strong = fmap B.strong <$> emphasisBetween (string "**")
-
-emph :: PandocMonad m => MuseParser m (F Inlines)
-emph = fmap B.emph <$> emphasisBetween (char '*')
-
-underlined :: PandocMonad m => MuseParser m (F Inlines)
-underlined = do
-  guardDisabled Ext_amuse -- Supported only by Emacs Muse
-  fmap underlineSpan <$> emphasisBetween (char '_')
-
-emphTag :: PandocMonad m => MuseParser m (F Inlines)
-emphTag = inlineTag B.emph "em"
-
-superscriptTag :: PandocMonad m => MuseParser m (F Inlines)
-superscriptTag = inlineTag B.superscript "sup"
-
-subscriptTag :: PandocMonad m => MuseParser m (F Inlines)
-subscriptTag = inlineTag B.subscript "sub"
-
-strikeoutTag :: PandocMonad m => MuseParser m (F Inlines)
-strikeoutTag = inlineTag B.strikeout "del"
-
-verbatimTag :: PandocMonad m => MuseParser m (F Inlines)
-verbatimTag = do
-  content <- parseHtmlContent "verbatim" anyChar
-  return $ return $ B.text content
-
-nbsp :: PandocMonad m => MuseParser m (F Inlines)
-nbsp = do
-  guardDisabled Ext_amuse -- Supported only by Emacs Muse
-  string "~~"
-  return $ return $ B.str "\160"
-
-code :: PandocMonad m => MuseParser m (F Inlines)
-code = try $ do
-  pos <- getPosition
-  sp <- if sourceColumn pos == 1
-          then pure mempty
-          else skipMany1 spaceChar >> pure B.space
-  char '='
-  contents <- many1Till (noneOf "\n\r" <|> (newline <* notFollowedBy newline)) $ char '='
-  guard $ not $ null contents
-  guard $ head contents `notElem` " \t\n"
-  guard $ last contents `notElem` " \t\n"
-  notFollowedBy $ satisfy isLetter
-  return $ return (sp B.<> B.code contents)
-
-codeTag :: PandocMonad m => MuseParser m (F Inlines)
-codeTag = do
-  (attrs, content) <- parseHtmlContentWithAttrs "code" anyChar
-  return $ return $ B.codeWith attrs content
-
-inlineLiteralTag :: PandocMonad m => MuseParser m (F Inlines)
-inlineLiteralTag = do
-  guardDisabled Ext_amuse -- Text::Amuse does not support <literal>
-  (attrs, content) <- parseHtmlContentWithAttrs "literal" anyChar
-  return $ return $ rawInline (attrs, content)
-  where
-    -- FIXME: Emacs Muse inserts <literal> without style into all output formats, but we assume HTML
-    format (_, _, kvs)        = fromMaybe "html" $ lookup "style" kvs
-    rawInline (attrs, content) = B.rawInline (format attrs) content
-
-str :: PandocMonad m => MuseParser m (F Inlines)
-str = do
-  result <- many1 alphaNum
-  updateLastStrPos
-  return $ return $ B.str result
-
-symbol :: PandocMonad m => MuseParser m (F Inlines)
-symbol = return . B.str <$> count 1 nonspaceChar
-
-link :: PandocMonad m => MuseParser m (F Inlines)
-link = try $ do
-  st <- getState
-  guard $ stateAllowLinks st
-  setState $ st{ stateAllowLinks = False }
-  (url, title, content) <- linkText
-  setState $ st{ stateAllowLinks = True }
-  return $ case stripPrefix "URL:" url of
-             Nothing -> if isImageUrl url
-                          then B.image url title <$> fromMaybe (return mempty) content
-                          else B.link url title <$> fromMaybe (return $ B.str url) content
-             Just url' -> B.link url' title <$> fromMaybe (return $ B.str url') content
-    where -- Taken from muse-image-regexp defined in Emacs Muse file lisp/muse-regexps.el
-          imageExtensions = [".eps", ".gif", ".jpg", ".jpeg", ".pbm", ".png", ".tiff", ".xbm", ".xpm"]
-          isImageUrl = (`elem` imageExtensions) . takeExtension
-
-linkContent :: PandocMonad m => MuseParser m (F Inlines)
-linkContent = do
-  char '['
-  res <- many1Till anyChar $ char ']'
-  parseFromString (mconcat <$> many1 inline) res
-
-linkText :: PandocMonad m => MuseParser m (String, String, Maybe (F Inlines))
-linkText = do
-  string "[["
-  url <- many1Till anyChar $ char ']'
-  content <- optionMaybe linkContent
-  char ']'
-  return (url, "", content)
+{-# LANGUAGE FlexibleContexts  #-}
+{-# LANGUAGE TupleSections     #-}
+{-# LANGUAGE OverloadedStrings #-}
+{- |
+   Module      : Text.Pandoc.Readers.Muse
+   Copyright   : Copyright (C) 2017-2020 Alexander Krotov
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : Alexander Krotov <ilabdsf@gmail.com>
+   Stability   : alpha
+   Portability : portable
+
+Conversion of Muse text to 'Pandoc' document.
+-}
+{-
+TODO:
+- <cite> tag
+-}
+module Text.Pandoc.Readers.Muse (readMuse) where
+
+import Control.Monad
+import Control.Monad.Reader
+import Control.Monad.Except (throwError)
+import Data.Bifunctor
+import Data.Default
+import Data.List (transpose)
+import qualified Data.Map as M
+import qualified Data.Set as Set
+import Data.Maybe (fromMaybe, isNothing, maybeToList)
+import Data.Text (Text)
+import qualified Data.Text as T
+import Text.Pandoc.Builder (Blocks, Inlines, underline)
+import qualified Text.Pandoc.Builder as B
+import Text.Pandoc.Class.PandocMonad (PandocMonad (..))
+import Text.Pandoc.Definition
+import Text.Pandoc.Logging
+import Text.Pandoc.Options
+import Text.Pandoc.Parsing
+import Text.Pandoc.Shared (trimr, tshow)
+
+-- | Read Muse from an input string and return a Pandoc document.
+readMuse :: (PandocMonad m, ToSources a)
+         => ReaderOptions
+         -> a
+         -> m Pandoc
+readMuse opts s = do
+  let sources = toSources s
+  res <- flip runReaderT def $ runParserT parseMuse def{ museOptions = opts }
+              (initialSourceName sources) sources
+  case res of
+       Left e  -> throwError $ fromParsecError sources e
+       Right d -> return d
+
+type F = Future MuseState
+
+data MuseState = MuseState { museMeta :: F Meta -- ^ Document metadata
+                           , museOptions :: ReaderOptions
+                           , museIdentifierList :: Set.Set Text
+                           , museLastSpacePos :: Maybe SourcePos -- ^ Position after last space or newline parsed
+                           , museLastStrPos :: Maybe SourcePos -- ^ Position after last str parsed
+                           , museLogMessages :: [LogMessage]
+                           , museNotes :: M.Map Text (SourcePos, F Blocks)
+                           }
+
+instance Default MuseState where
+  def = MuseState { museMeta = return nullMeta
+                  , museOptions = def
+                  , museIdentifierList = Set.empty
+                  , museLastStrPos = Nothing
+                  , museLastSpacePos = Nothing
+                  , museLogMessages = []
+                  , museNotes = M.empty
+                  }
+
+data MuseEnv =
+  MuseEnv { museInLink :: Bool -- ^ True when parsing a link description to avoid nested links
+          , museInPara :: Bool -- ^ True when parsing paragraph is not allowed
+          }
+
+instance Default MuseEnv where
+  def = MuseEnv { museInLink = False
+                , museInPara = False
+                }
+
+type MuseParser m = ParsecT Sources MuseState (ReaderT MuseEnv m)
+
+instance HasReaderOptions MuseState where
+  extractReaderOptions = museOptions
+
+instance HasIdentifierList MuseState where
+  extractIdentifierList     = museIdentifierList
+  updateIdentifierList f st = st{ museIdentifierList = f $ museIdentifierList st }
+
+instance HasLastStrPosition MuseState where
+  setLastStrPos pos st = st{ museLastStrPos = pos }
+  getLastStrPos st     = museLastStrPos st
+
+instance HasLogMessages MuseState where
+  addLogMessage m s = s{ museLogMessages = m : museLogMessages s }
+  getLogMessages = reverse . museLogMessages
+
+updateLastSpacePos :: Monad m => MuseParser m ()
+updateLastSpacePos = getPosition >>= \pos ->
+  updateState $ \s -> s { museLastSpacePos = Just pos }
+
+-- | Parse Muse document
+parseMuse :: PandocMonad m => MuseParser m Pandoc
+parseMuse = do
+  many directive
+  blocks <- (:) <$> parseBlocks <*> many parseSection
+  eof
+  st <- getState
+  runF (Pandoc <$> museMeta st <*> fmap B.toList (mconcat blocks)) st <$ reportLogMessages
+
+-- * Utility functions
+
+-- | Trim up to one newline from the beginning of the string.
+lchop :: Text -> Text
+lchop s = case T.uncons s of
+  Just ('\n', xs) -> xs
+  _               -> s
+
+-- | Trim up to one newline from the end of the string.
+rchop :: Text -> Text
+rchop s = case T.unsnoc s of
+  Just (xs, '\n') -> xs
+  _               -> s
+
+unindent :: Text -> Text
+unindent = rchop . T.intercalate "\n" . dropSpacePrefix . T.splitOn "\n" . lchop
+
+dropSpacePrefix :: [Text] -> [Text]
+dropSpacePrefix lns = T.drop maxIndent <$> lns
+  where isSpaceChar c = c == ' ' || c == '\t'
+        maxIndent = length $ takeWhile (isSpaceChar . T.head) $ takeWhile same $ T.transpose lns
+        same t = case T.uncons t of
+          Just (c, cs) -> T.all (== c) cs
+          Nothing      -> True
+
+atStart :: PandocMonad m => MuseParser m ()
+atStart = do
+  pos <- getPosition
+  st <- getState
+  guard $ museLastStrPos st /= Just pos
+
+noSpaceBefore :: PandocMonad m => MuseParser m ()
+noSpaceBefore = do
+  pos <- getPosition
+  st <- getState
+  guard $ museLastSpacePos st /= Just pos
+
+firstColumn :: PandocMonad m => MuseParser m ()
+firstColumn = getPosition >>= \pos -> guard (sourceColumn pos == 1)
+
+-- * Parsers
+
+-- | Parse end-of-line, which can be either a newline or end-of-file.
+eol :: (Stream s m Char, UpdateSourcePos s Char) => ParsecT s st m ()
+eol = void newline <|> eof
+
+getIndent :: PandocMonad m
+          => MuseParser m Int
+getIndent = subtract 1 . sourceColumn <$ many spaceChar <*> getPosition
+
+-- ** HTML parsers
+
+openTag :: PandocMonad m => Text -> MuseParser m [(Text, Text)]
+openTag tag = try $
+  char '<' *> textStr tag *> manyTill attr (char '>')
+  where
+    attr = try $ (,)
+      <$  many1 spaceChar
+      <*> many1Char (noneOf "=\n")
+      <*  string "=\""
+      <*> manyTillChar (noneOf "\"") (char '"')
+
+closeTag :: PandocMonad m => Text -> MuseParser m ()
+closeTag tag = try $ string "</" *> textStr tag *> void (char '>')
+
+-- | Convert HTML attributes to Pandoc 'Attr'
+htmlAttrToPandoc :: [(Text, Text)] -> Attr
+htmlAttrToPandoc attrs = (ident, classes, keyvals)
+  where
+    ident   = fromMaybe "" $ lookup "id" attrs
+    classes = maybe [] T.words $ lookup "class" attrs
+    keyvals = [(k,v) | (k,v) <- attrs, k /= "id", k /= "class"]
+
+parseHtmlContent :: PandocMonad m
+                 => Text -- ^ Tag name
+                 -> MuseParser m (Attr, F Blocks)
+parseHtmlContent tag = try $ getIndent >>= \indent -> (,)
+  <$> fmap htmlAttrToPandoc (openTag tag)
+  <*  manyTill spaceChar eol
+  <*> allowPara (parseBlocksTill (try $ indentWith indent *> closeTag tag))
+  <*  manyTill spaceChar eol -- closing tag must be followed by optional whitespace and newline
+
+-- ** Directive parsers
+
+-- While not documented, Emacs Muse allows "-" in directive name
+parseDirectiveKey :: PandocMonad m => MuseParser m Text
+parseDirectiveKey = char '#' *> manyChar (letter <|> char '-')
+
+parseEmacsDirective :: PandocMonad m => MuseParser m (Text, F Inlines)
+parseEmacsDirective = (,)
+  <$> parseDirectiveKey
+  <*  spaceChar
+  <*> (trimInlinesF . mconcat <$> manyTill inline' eol)
+
+parseAmuseDirective :: PandocMonad m => MuseParser m (Text, F Inlines)
+parseAmuseDirective = (,)
+  <$> parseDirectiveKey
+  <*  many1 spaceChar
+  <*> (trimInlinesF . mconcat <$> many1Till inline endOfDirective)
+  <*  many blankline
+  where
+    endOfDirective = lookAhead $ eof <|> try (newline *> (void blankline <|> void parseDirectiveKey))
+
+directive :: PandocMonad m => MuseParser m ()
+directive = do
+  ext <- getOption readerExtensions
+  (key, value) <- if extensionEnabled Ext_amuse ext then parseAmuseDirective else parseEmacsDirective
+  updateState $ \st -> st { museMeta = B.setMeta (translateKey key) <$> value <*> museMeta st }
+  where translateKey "cover" = "cover-image"
+        translateKey x = x
+
+-- ** Block parsers
+
+allowPara :: MonadReader MuseEnv m => m a -> m a
+allowPara p = local (\s -> s { museInPara = False }) p
+
+-- | Parse section contents until EOF or next header
+parseBlocks :: PandocMonad m
+            => MuseParser m (F Blocks)
+parseBlocks =
+  try (parseEnd <|>
+       nextSection <|>
+       listStart <|>
+       blockStart <|>
+       paraStart)
+  where
+    nextSection = mempty <$ lookAhead headingStart
+    parseEnd = mempty <$ eof
+    blockStart = (B.<>) <$> (blockElements <|> emacsNoteBlock)
+                        <*> allowPara parseBlocks
+    listStart =
+      uncurry (B.<>) <$> allowPara (anyListUntil parseBlocks <|> amuseNoteBlockUntil parseBlocks)
+    paraStart = do
+      indent <- length <$> many spaceChar
+      uncurry (B.<>) . first (p indent) <$> paraUntil parseBlocks
+      where p indent = if indent >= 2 && indent < 6 then fmap B.blockQuote else id
+
+-- | Parse section that starts with a header
+parseSection :: PandocMonad m
+             => MuseParser m (F Blocks)
+parseSection =
+  ((B.<>) <$> emacsHeading <*> parseBlocks) <|>
+  (uncurry (B.<>) <$> amuseHeadingUntil parseBlocks)
+
+parseBlocksTill :: PandocMonad m
+                => MuseParser m a
+                -> MuseParser m (F Blocks)
+parseBlocksTill end = continuation
+  where
+    parseEnd = mempty <$ end
+    blockStart = (B.<>) <$> blockElements <*> allowPara continuation
+    listStart = uncurry (B.<>) <$> allowPara (anyListUntil (parseEnd <|> continuation))
+    paraStart = uncurry (B.<>) <$> paraUntil (parseEnd <|> continuation)
+    continuation = try $ parseEnd <|> listStart <|> blockStart <|> paraStart
+
+listItemContentsUntil :: PandocMonad m
+                      => Int
+                      -> MuseParser m a
+                      -> MuseParser m a
+                      -> MuseParser m (F Blocks, a)
+listItemContentsUntil col pre end = p
+  where
+    p = try listStart <|> try blockStart <|> try paraStart
+    parsePre = (mempty,) <$> pre
+    parseEnd = (mempty,) <$> end
+    paraStart = do
+      (f, (r, e)) <- paraUntil (parsePre <|> continuation <|> parseEnd)
+      return (f B.<> r, e)
+    blockStart = first <$> ((B.<>) <$> blockElements)
+                       <*> allowPara (parsePre <|> continuation <|> parseEnd)
+    listStart = do
+      (f, (r, e)) <- allowPara $ anyListUntil (parsePre <|> continuation <|> parseEnd)
+      return (f B.<> r, e)
+    continuation = try $ do blank <- optionMaybe blankline
+                            skipMany blankline
+                            indentWith col
+                            local (\s -> s { museInPara = museInPara s && isNothing blank }) p
+
+parseBlock :: PandocMonad m => MuseParser m (F Blocks)
+parseBlock = do
+  res <- blockElements <|> para
+  trace (T.take 60 $ tshow $ B.toList $ runF res def)
+  return res
+  where para = fst <$> paraUntil (try (eof <|> void (lookAhead blockElements)))
+
+blockElements :: PandocMonad m => MuseParser m (F Blocks)
+blockElements = (mempty <$ blankline)
+            <|> comment
+            <|> separator
+            <|> pagebreak
+            <|> example
+            <|> exampleTag
+            <|> literalTag
+            <|> centerTag
+            <|> rightTag
+            <|> quoteTag
+            <|> divTag
+            <|> biblioTag
+            <|> playTag
+            <|> verseTag
+            <|> lineBlock
+            <|> museGridTable
+            <|> table
+            <|> commentTag
+
+-- | Parse a line comment, starting with @;@ in the first column.
+comment :: PandocMonad m => MuseParser m (F Blocks)
+comment = try $ mempty
+  <$ firstColumn
+  <* char ';'
+  <* optional (spaceChar *> many (noneOf "\n"))
+  <* eol
+
+-- | Parse a horizontal rule, consisting of 4 or more @\'-\'@ characters.
+separator :: PandocMonad m => MuseParser m (F Blocks)
+separator = try $ pure B.horizontalRule
+  <$ string "----"
+  <* many (char '-')
+  <* many spaceChar
+  <* eol
+
+-- | Parse a page break
+pagebreak :: PandocMonad m => MuseParser m (F Blocks)
+pagebreak = try $ pure (B.divWith ("", [], [("style", "page-break-before: always;")]) mempty)
+  <$ count 6 spaceChar
+  <* many spaceChar
+  <* string "* * * * *"
+  <* manyTill spaceChar eol
+
+headingStart :: PandocMonad m => MuseParser m (Text, Int)
+headingStart = try $ (,)
+  <$> option "" (try (parseAnchor <* manyTill spaceChar eol))
+  <*  firstColumn
+  <*> fmap length (many1 $ char '*')
+  <*  spaceChar
+
+-- | Parse a single-line heading.
+emacsHeading :: PandocMonad m => MuseParser m (F Blocks)
+emacsHeading = try $ do
+  guardDisabled Ext_amuse
+  (anchorId, level) <- headingStart
+  content <- trimInlinesF . mconcat <$> manyTill inline eol
+  attr <- registerHeader (anchorId, [], []) (runF content def)
+  return $ B.headerWith attr level <$> content
+
+-- | Parse a multi-line heading.
+-- It is a Text::Amuse extension, Emacs Muse does not allow heading to span multiple lines.
+amuseHeadingUntil :: PandocMonad m
+                  => MuseParser m a -- ^ Terminator parser
+                  -> MuseParser m (F Blocks, a)
+amuseHeadingUntil end = try $ do
+  guardEnabled Ext_amuse
+  (anchorId, level) <- headingStart
+  (content, e) <- paraContentsUntil end
+  attr <- registerHeader (anchorId, [], []) (runF content def)
+  return (B.headerWith attr level <$> content, e)
+
+-- | Parse an example between @{{{@ and @}}}@.
+-- It is an Amusewiki extension influenced by Creole wiki, as described in @Text::Amuse@ documentation.
+example :: PandocMonad m => MuseParser m (F Blocks)
+example = try $ pure . B.codeBlock
+  <$  string "{{{"
+  <*  many spaceChar
+  <*> (unindent <$> manyTillChar anyChar (string "}}}"))
+
+-- | Parse an @\<example>@ tag.
+exampleTag :: PandocMonad m => MuseParser m (F Blocks)
+exampleTag = try $ fmap pure $ B.codeBlockWith
+  <$  many spaceChar
+  <*> (htmlAttrToPandoc <$> openTag "example")
+  <*> (unindent <$> manyTillChar anyChar (closeTag "example"))
+  <*  manyTill spaceChar eol
+
+-- | Parse a @\<literal>@ tag as a raw block.
+-- For 'RawInline' @\<literal>@ parser, see 'inlineLiteralTag'.
+literalTag :: PandocMonad m => MuseParser m (F Blocks)
+literalTag = try $ fmap pure $ B.rawBlock
+  <$  many spaceChar
+  <*> (fromMaybe "html" . lookup "style" <$> openTag "literal") -- FIXME: Emacs Muse inserts <literal> without style into all output formats, but we assume HTML
+  <*  manyTill spaceChar eol
+  <*> (unindent <$> manyTillChar anyChar (closeTag "literal"))
+  <*  manyTill spaceChar eol
+
+-- | Parse @\<center>@ tag.
+-- Currently it is ignored as Pandoc cannot represent centered blocks.
+centerTag :: PandocMonad m => MuseParser m (F Blocks)
+centerTag = snd <$> parseHtmlContent "center"
+
+-- | Parse @\<right>@ tag.
+-- Currently it is ignored as Pandoc cannot represent centered blocks.
+rightTag :: PandocMonad m => MuseParser m (F Blocks)
+rightTag = snd <$> parseHtmlContent "right"
+
+-- | Parse @\<quote>@ tag.
+quoteTag :: PandocMonad m => MuseParser m (F Blocks)
+quoteTag = fmap B.blockQuote . snd <$> parseHtmlContent "quote"
+
+-- | Parse @\<div>@ tag.
+-- @\<div>@ tag is supported by Emacs Muse, but not Amusewiki 2.025.
+divTag :: PandocMonad m => MuseParser m (F Blocks)
+divTag = do
+  (attrs, content) <- parseHtmlContent "div"
+  return $ B.divWith attrs <$> content
+
+-- | Parse @\<biblio>@ tag, the result is the same as @\<div class="biblio">@.
+-- @\<biblio>@ tag is supported only in Text::Amuse mode.
+biblioTag :: PandocMonad m => MuseParser m (F Blocks)
+biblioTag = fmap (B.divWith ("", ["biblio"], [])) . snd
+  <$  guardEnabled Ext_amuse
+  <*> parseHtmlContent "biblio"
+
+-- | Parse @\<play>@ tag, the result is the same as @\<div class="play">@.
+-- @\<play>@ tag is supported only in Text::Amuse mode.
+playTag :: PandocMonad m => MuseParser m (F Blocks)
+playTag = do
+  guardEnabled Ext_amuse
+  fmap (B.divWith ("", ["play"], [])) . snd <$> parseHtmlContent "play"
+
+verseLine :: PandocMonad m => MuseParser m (F Inlines)
+verseLine = (<>)
+  <$> fmap pure (option mempty (B.str <$> many1Char ('\160' <$ char ' ')))
+  <*> fmap (trimInlinesF . mconcat) (manyTill inline' eol)
+
+-- | Parse @\<verse>@ tag.
+verseTag :: PandocMonad m => MuseParser m (F Blocks)
+verseTag = try $ getIndent >>= \indent -> fmap B.lineBlock . sequence
+  <$  openTag "verse"
+  <*  manyTill spaceChar eol
+  <*> manyTill (indentWith indent *> verseLine) (try $ indentWith indent *> closeTag "verse")
+  <*  manyTill spaceChar eol
+
+-- | Parse @\<comment>@ tag.
+commentTag :: PandocMonad m => MuseParser m (F Blocks)
+commentTag = try $ mempty
+  <$ many spaceChar
+  <* openTag "comment"
+  <* manyTill anyChar (closeTag "comment")
+  <* manyTill spaceChar eol
+
+-- | Parse paragraph contents.
+paraContentsUntil :: PandocMonad m
+                  => MuseParser m a -- ^ Terminator parser
+                  -> MuseParser m (F Inlines, a)
+paraContentsUntil end = first (trimInlinesF . mconcat)
+  <$> manyUntil inline (try (manyTill spaceChar eol *> local (\s -> s { museInPara = True}) end))
+
+-- | Parse a paragraph.
+paraUntil :: PandocMonad m
+          => MuseParser m a -- ^ Terminator parser
+          -> MuseParser m (F Blocks, a)
+paraUntil end = do
+  inPara <- asks museInPara
+  guard $ not inPara
+  first (fmap B.para) <$> paraContentsUntil end
+
+noteMarker' :: PandocMonad m
+            => Char
+            -> Char
+            -> MuseParser m Text
+noteMarker' l r = try $ (\x y -> T.pack $ l:x:y ++ [r])
+  <$ char l
+  <*> oneOf "123456789"
+  <*> manyTill digit (char r)
+
+noteMarker :: PandocMonad m => MuseParser m Text
+noteMarker = noteMarker' '[' ']' <|> noteMarker' '{' '}'
+
+addNote :: PandocMonad m
+        => Text
+        -> SourcePos
+        -> F Blocks
+        -> MuseParser m ()
+addNote ref pos content = do
+  oldnotes <- museNotes <$> getState
+  when (M.member ref oldnotes)
+    (logMessage $ DuplicateNoteReference ref pos)
+  updateState $ \s -> s{ museNotes = M.insert ref (pos, content) oldnotes }
+
+-- Amusewiki version of note
+-- Parsing is similar to list item, except that note marker is used instead of list marker
+amuseNoteBlockUntil :: PandocMonad m
+                    => MuseParser m a
+                    -> MuseParser m (F Blocks, a)
+amuseNoteBlockUntil end = try $ do
+  guardEnabled Ext_amuse
+  ref <- noteMarker
+  pos <- getPosition
+  void spaceChar <|> lookAhead eol
+  (content, e) <- allowPara $ listItemContentsUntil (sourceColumn pos) (Prelude.fail "x") end
+  addNote ref pos content
+  return (mempty, e)
+
+-- Emacs version of note
+-- Notes are allowed only at the end of text, no indentation is required.
+emacsNoteBlock :: PandocMonad m => MuseParser m (F Blocks)
+emacsNoteBlock = try $ do
+  guardDisabled Ext_amuse
+  ref <- noteMarker
+  pos <- getPosition
+  content <- fmap mconcat blocksTillNote
+  addNote ref pos content
+  return mempty
+  where
+    blocksTillNote =
+      many1Till parseBlock (eof <|> () <$ lookAhead noteMarker)
+
+--
+-- Verse markup
+--
+
+-- | Parse a line block indicated by @\'>\'@ characters.
+lineBlock :: PandocMonad m => MuseParser m (F Blocks)
+lineBlock = try $ getIndent >>= \indent -> fmap B.lineBlock . sequence
+  <$> (blankVerseLine <|> nonblankVerseLine) `sepBy1'` try (indentWith indent)
+  where
+    blankVerseLine = try $ mempty <$ char '>' <* blankline
+    nonblankVerseLine = try (string "> ") *> verseLine
+
+-- *** List parsers
+
+bulletListItemsUntil :: PandocMonad m
+                     => Int -- ^ Indentation
+                     -> MuseParser m a -- ^ Terminator parser
+                     -> MuseParser m ([F Blocks], a)
+bulletListItemsUntil indent end = try $ do
+  char '-'
+  void spaceChar <|> lookAhead eol
+  (x, (xs, e)) <- allowPara $ listItemContentsUntil (indent + 2) (try (optional blankline *> indentWith indent *> bulletListItemsUntil indent end)) (([],) <$> end)
+  return (x:xs, e)
+
+-- | Parse a bullet list.
+bulletListUntil :: PandocMonad m
+                => MuseParser m a
+                -> MuseParser m (F Blocks, a)
+bulletListUntil end = try $ do
+  indent <- getIndent
+  guard $ indent /= 0
+  first (fmap B.bulletList . sequence) <$> bulletListItemsUntil indent end
+
+museOrderedListMarker :: PandocMonad m
+                      => ListNumberStyle
+                      -> MuseParser m Int
+museOrderedListMarker style =
+  snd <$> p <* char '.'
+  where p = case style of
+              Decimal    -> decimal
+              UpperRoman -> upperRoman
+              LowerRoman -> lowerRoman
+              UpperAlpha -> upperAlpha
+              LowerAlpha -> lowerAlpha
+              _          -> Prelude.fail "Unhandled case"
+
+orderedListItemsUntil :: PandocMonad m
+                      => Int
+                      -> ListNumberStyle
+                      -> MuseParser m a
+                      -> MuseParser m ([F Blocks], a)
+orderedListItemsUntil indent style end =
+  continuation
+  where
+    continuation = try $ do
+      pos <- getPosition
+      void spaceChar <|> lookAhead eol
+      (x, (xs, e)) <- allowPara $ listItemContentsUntil (sourceColumn pos) (try (optional blankline *> indentWith indent *> museOrderedListMarker style *> continuation)) (([],) <$> end)
+      return (x:xs, e)
+
+-- | Parse an ordered list.
+orderedListUntil :: PandocMonad m
+                 => MuseParser m a
+                 -> MuseParser m (F Blocks, a)
+orderedListUntil end = try $ do
+  indent <- getIndent
+  guard $ indent /= 0
+  (style, start) <- decimal <|> lowerRoman <|> upperRoman <|> lowerAlpha <|> upperAlpha
+  char '.'
+  first (fmap (B.orderedListWith (start, style, Period)) . sequence)
+    <$> orderedListItemsUntil indent style end
+
+descriptionsUntil :: PandocMonad m
+                  => Int
+                  -> MuseParser m a
+                  -> MuseParser m ([F Blocks], a)
+descriptionsUntil indent end = do
+  void spaceChar <|> lookAhead eol
+  (x, (xs, e)) <- allowPara $ listItemContentsUntil indent (try (optional blankline *> indentWith indent *> manyTill spaceChar (string "::") *> descriptionsUntil indent end)) (([],) <$> end)
+  return (x:xs, e)
+
+definitionListItemsUntil :: PandocMonad m
+                         => Int
+                         -> MuseParser m a
+                         -> MuseParser m ([F (Inlines, [Blocks])], a)
+definitionListItemsUntil indent end =
+  continuation
+  where
+    continuation = try $ do
+      pos <- getPosition
+      term <- trimInlinesF . mconcat <$> manyTill inline' (try $ string "::")
+      (x, (xs, e)) <- descriptionsUntil (sourceColumn pos) (try (optional blankline *> indentWith indent *> continuation) <|> (([],) <$> end))
+      let xx = (,) <$> term <*> sequence x
+      return (xx:xs, e)
+
+-- | Parse a definition list.
+definitionListUntil :: PandocMonad m
+                    => MuseParser m a -- ^ Terminator parser
+                    -> MuseParser m (F Blocks, a)
+definitionListUntil end = try $ do
+  indent <- getIndent
+  guardDisabled Ext_amuse <|> guard (indent /= 0) -- Initial space is required by Amusewiki, but not Emacs Muse
+  first (fmap B.definitionList . sequence) <$> definitionListItemsUntil indent end
+
+anyListUntil :: PandocMonad m
+             => MuseParser m a -- ^ Terminator parser
+             -> MuseParser m (F Blocks, a)
+anyListUntil end =
+  bulletListUntil end <|> orderedListUntil end <|> definitionListUntil end
+
+-- *** Table parsers
+
+-- | Internal Muse table representation.
+data MuseTable = MuseTable
+  { museTableCaption :: Inlines
+  , museTableHeaders :: [[Blocks]]
+  , museTableRows    :: [[Blocks]]
+  , museTableFooters :: [[Blocks]]
+  }
+
+data MuseTableElement = MuseHeaderRow [Blocks]
+                      | MuseBodyRow [Blocks]
+                      | MuseFooterRow [Blocks]
+                      | MuseCaption Inlines
+
+museToPandocTable :: MuseTable -> Blocks
+museToPandocTable (MuseTable caption headers body footers) =
+  B.table (B.simpleCaption $ B.plain caption)
+          attrs
+          (TableHead nullAttr $ toHeaderRow headRow)
+          [TableBody nullAttr 0 [] $ map toRow $ rows ++ body ++ footers]
+          (TableFoot nullAttr [])
+  where attrs = (AlignDefault, ColWidthDefault) <$ transpose (headers ++ body ++ footers)
+        (headRow, rows) =
+          case headers of
+            (r:rs) -> (r, rs)
+            []     -> ([], [])
+        toRow = Row nullAttr . map B.simpleCell
+        toHeaderRow l = [toRow l | not (null l)]
+
+museAppendElement :: MuseTableElement
+                  -> MuseTable
+                  -> MuseTable
+museAppendElement element tbl =
+  case element of
+    MuseHeaderRow row -> tbl{ museTableHeaders = row : museTableHeaders tbl }
+    MuseBodyRow row -> tbl{ museTableRows = row : museTableRows tbl }
+    MuseFooterRow row -> tbl{ museTableFooters = row : museTableFooters tbl }
+    MuseCaption inlines -> tbl{ museTableCaption = inlines }
+
+tableElements :: PandocMonad m => MuseParser m (F [MuseTableElement])
+tableElements = sequence <$> many1 tableParseElement
+
+elementsToTable :: [MuseTableElement] -> MuseTable
+elementsToTable = foldr museAppendElement emptyTable
+  where emptyTable = MuseTable mempty mempty mempty mempty
+
+museGridPart :: PandocMonad m => MuseParser m Int
+museGridPart = try $ length <$> many1 (char '-') <* char '+'
+
+museGridTableHeader :: PandocMonad m => MuseParser m [Int]
+museGridTableHeader = try $ char '+' *> many1 museGridPart <* manyTill spaceChar eol
+
+museGridTableRow :: PandocMonad m
+                 => Int
+                 -> [Int]
+                 -> MuseParser m (F [Blocks])
+museGridTableRow indent indices = try $ do
+  lns <- many1 $ try (indentWith indent *> museGridTableRawLine indices)
+  let cols = map (T.unlines . map trimr) $ transpose lns
+  indentWith indent *> museGridTableHeader
+  sequence <$> mapM (parseFromString' parseBlocks) cols
+
+museGridTableRawLine :: PandocMonad m
+                     => [Int]
+                     -> MuseParser m [Text]
+museGridTableRawLine indices =
+  char '|' *> forM indices (\n -> countChar n anyChar <* char '|') <* manyTill spaceChar eol
+
+museGridTable :: PandocMonad m => MuseParser m (F Blocks)
+museGridTable = try $ do
+  indent <- getIndent
+  indices <- museGridTableHeader
+  fmap rowsToTable . sequence <$> many1 (museGridTableRow indent indices)
+  where rowsToTable rows = B.table B.emptyCaption
+                                   attrs
+                                   (TableHead nullAttr [])
+                                   [TableBody nullAttr 0 [] $ map toRow rows]
+                                   (TableFoot nullAttr [])
+                           where attrs = (AlignDefault, ColWidthDefault) <$ transpose rows
+                                 toRow = Row nullAttr . map B.simpleCell
+
+-- | Parse a table.
+table :: PandocMonad m => MuseParser m (F Blocks)
+table = try $ fmap (museToPandocTable . elementsToTable) <$> tableElements
+
+tableParseElement :: PandocMonad m => MuseParser m (F MuseTableElement)
+tableParseElement = tableParseHeader
+                <|> tableParseBody
+                <|> tableParseFooter
+                <|> tableParseCaption
+
+tableParseRow :: PandocMonad m
+              => Int -- ^ Number of separator characters
+              -> MuseParser m (F [Blocks])
+tableParseRow n = try $ sequence <$> tableCells
+  where tableCells = (:) <$> tableCell sep <*> (tableCells <|> fmap pure (tableCell eol))
+        tableCell p = try $ fmap B.plain . trimInlinesF . mconcat <$> manyTill inline' p
+        sep = try $ many1 spaceChar *> count n (char '|') *> lookAhead (void (many1 spaceChar) <|> void eol)
+
+-- | Parse a table header row.
+tableParseHeader :: PandocMonad m => MuseParser m (F MuseTableElement)
+tableParseHeader = fmap MuseHeaderRow <$> tableParseRow 2
+
+-- | Parse a table body row.
+tableParseBody :: PandocMonad m => MuseParser m (F MuseTableElement)
+tableParseBody = fmap MuseBodyRow <$> tableParseRow 1
+
+-- | Parse a table footer row.
+tableParseFooter :: PandocMonad m => MuseParser m (F MuseTableElement)
+tableParseFooter = fmap MuseFooterRow <$> tableParseRow 3
+
+-- | Parse table caption.
+tableParseCaption :: PandocMonad m => MuseParser m (F MuseTableElement)
+tableParseCaption = try $ fmap MuseCaption . trimInlinesF . mconcat
+  <$  many spaceChar
+  <*  string "|+"
+  <*> many1Till inline (try $ string "+|" *> eol)
+
+-- ** Inline parsers
+
+inline' :: PandocMonad m => MuseParser m (F Inlines)
+inline' = whitespace
+      <|> br
+      <|> anchor
+      <|> footnote
+      <|> strongEmph
+      <|> strong
+      <|> strongTag
+      <|> emph
+      <|> emphTag
+      <|> underlined
+      <|> superscriptTag
+      <|> subscriptTag
+      <|> strikeoutTag
+      <|> verbatimTag
+      <|> classTag
+      <|> inlineRtl
+      <|> inlineLtr
+      <|> nbsp
+      <|> linkOrImage
+      <|> code
+      <|> codeTag
+      <|> mathTag
+      <|> inlineLiteralTag
+      <|> str
+      <|> asterisks
+      <|> symbol
+      <?> "inline"
+
+inline :: PandocMonad m => MuseParser m (F Inlines)
+inline = endline <|> inline'
+
+-- | Parse a soft break.
+endline :: PandocMonad m => MuseParser m (F Inlines)
+endline = try $ pure B.softbreak <$ newline <* notFollowedBy blankline <* updateLastSpacePos
+
+parseAnchor :: PandocMonad m => MuseParser m Text
+parseAnchor = try $ T.cons
+  <$  firstColumn
+  <*  char '#'
+  <*> letter
+  <*> manyChar (letter <|> digit <|> char '-')
+
+anchor :: PandocMonad m => MuseParser m (F Inlines)
+anchor = try $ do
+  anchorId <- parseAnchor
+  skipMany spaceChar <|> void newline
+  return $ return $ B.spanWith (anchorId, [], []) mempty
+
+-- | Parse a footnote reference.
+footnote :: PandocMonad m => MuseParser m (F Inlines)
+footnote = try $ do
+  inLink <- asks museInLink
+  guard $ not inLink
+  ref <- noteMarker
+  return $ do
+    notes <- asksF museNotes
+    case M.lookup ref notes of
+      Nothing -> return $ B.str ref
+      Just (_pos, contents) -> do
+        st <- askF
+        let contents' = runF contents st { museNotes = M.delete ref (museNotes st) }
+        return $ B.note contents'
+
+whitespace :: PandocMonad m => MuseParser m (F Inlines)
+whitespace = try $ pure B.space <$ skipMany1 spaceChar <* updateLastSpacePos
+
+-- | Parse @\<br>@ tag.
+br :: PandocMonad m => MuseParser m (F Inlines)
+br = try $ pure B.linebreak <$ string "<br>"
+
+emphasisBetween :: (PandocMonad m, Show a)
+                => MuseParser m a
+                -> MuseParser m (F Inlines)
+emphasisBetween p = try $ trimInlinesF . mconcat
+  <$  atStart
+  <*  p
+  <*  notFollowedBy space
+  <*> many1Till inline (try $ noSpaceBefore *> p <* notFollowedBy alphaNum)
+
+-- | Parse an inline tag, such as @\<em>@ and @\<strong>@.
+inlineTag :: PandocMonad m
+          => Text -- ^ Tag name
+          -> MuseParser m (F Inlines)
+inlineTag tag = try $ mconcat
+  <$  openTag tag
+  <*> manyTill inline (closeTag tag)
+
+-- | Parse strong emphasis inline markup, indicated by @***@.
+strongEmph :: PandocMonad m => MuseParser m (F Inlines)
+strongEmph = fmap (B.strong . B.emph) <$> emphasisBetween (string "***" <* notFollowedBy (char '*'))
+
+-- | Parse strong inline markup, indicated by @**@.
+strong :: PandocMonad m => MuseParser m (F Inlines)
+strong = fmap B.strong <$> emphasisBetween (string "**" <* notFollowedBy (char '*'))
+
+-- | Parse emphasis inline markup, indicated by @*@.
+emph :: PandocMonad m => MuseParser m (F Inlines)
+emph = fmap B.emph <$> emphasisBetween (char '*' <* notFollowedBy (char '*'))
+
+-- | Parse underline inline markup, indicated by @_@.
+-- Supported only in Emacs Muse mode, not Text::Amuse.
+underlined :: PandocMonad m => MuseParser m (F Inlines)
+underlined = fmap underline
+  <$  guardDisabled Ext_amuse -- Supported only by Emacs Muse
+  <*> emphasisBetween (char '_')
+
+-- | Parse @\<strong>@ tag.
+strongTag :: PandocMonad m => MuseParser m (F Inlines)
+strongTag = fmap B.strong <$> inlineTag "strong"
+
+-- | Parse @\<em>@ tag.
+emphTag :: PandocMonad m => MuseParser m (F Inlines)
+emphTag = fmap B.emph <$> inlineTag "em"
+
+-- | Parse @\<sup>@ tag.
+superscriptTag :: PandocMonad m => MuseParser m (F Inlines)
+superscriptTag = fmap B.superscript <$> inlineTag "sup"
+
+-- | Parse @\<sub>@ tag.
+subscriptTag :: PandocMonad m => MuseParser m (F Inlines)
+subscriptTag = fmap B.subscript <$> inlineTag "sub"
+
+-- | Parse @\<del>@ tag.
+strikeoutTag :: PandocMonad m => MuseParser m (F Inlines)
+strikeoutTag = fmap B.strikeout <$> inlineTag "del"
+
+-- | Parse @\<verbatim>@ tag.
+verbatimTag :: PandocMonad m => MuseParser m (F Inlines)
+verbatimTag = return . B.text
+  <$  openTag "verbatim"
+  <*> manyTillChar anyChar (closeTag "verbatim")
+
+-- | Parse @\<class>@ tag.
+classTag :: PandocMonad m => MuseParser m (F Inlines)
+classTag = do
+  classes <- maybe [] T.words . lookup "name" <$> openTag "class"
+  fmap (B.spanWith ("", classes, [])) . mconcat <$> manyTill inline (closeTag "class")
+
+-- | Parse @\<\<\<RTL>>>@ text.
+inlineRtl :: PandocMonad m => MuseParser m (F Inlines)
+inlineRtl = try $
+  fmap (B.spanWith ("", [], [("dir", "rtl")])) . mconcat <$ string "<<<" <*> manyTill inline (string ">>>")
+
+-- | Parse @\<\<\<LTR>>>@ text.
+inlineLtr :: PandocMonad m => MuseParser m (F Inlines)
+inlineLtr = try $
+  fmap (B.spanWith ("", [], [("dir", "ltr")])) . mconcat <$ string ">>>" <*> manyTill inline (string "<<<")
+
+-- | Parse "~~" as nonbreaking space.
+nbsp :: PandocMonad m => MuseParser m (F Inlines)
+nbsp = try $ pure (B.str "\160") <$ string "~~"
+
+-- | Parse code markup, indicated by @\'=\'@ characters.
+code :: PandocMonad m => MuseParser m (F Inlines)
+code = try $ fmap pure $ B.code . uncurry (<>)
+  <$  atStart
+  <*  char '='
+  <*  notFollowedBy (spaceChar <|> newline)
+  <*> manyUntilChar (noneOf "\n\r" <|> (newline <* notFollowedBy newline)) (try $ fmap T.singleton $ noneOf " \t\n\r=" <* char '=')
+  <*  notFollowedBy alphaNum
+
+-- | Parse @\<code>@ tag.
+codeTag :: PandocMonad m => MuseParser m (F Inlines)
+codeTag = fmap pure $ B.codeWith
+  <$> (htmlAttrToPandoc <$> openTag "code")
+  <*> manyTillChar anyChar (closeTag "code")
+
+-- | Parse @\<math>@ tag.
+-- @\<math>@ tag is an Emacs Muse extension enabled by @(require 'muse-latex2png)@
+mathTag :: PandocMonad m => MuseParser m (F Inlines)
+mathTag = return . B.math
+  <$  openTag "math"
+  <*> manyTillChar anyChar (closeTag "math")
+
+-- | Parse inline @\<literal>@ tag as a raw inline.
+inlineLiteralTag :: PandocMonad m => MuseParser m (F Inlines)
+inlineLiteralTag = try $ fmap pure $ B.rawInline
+  <$> (fromMaybe "html" . lookup "style" <$> openTag "literal") -- FIXME: Emacs Muse inserts <literal> without style into all output formats, but we assume HTML
+  <*> manyTillChar anyChar (closeTag "literal")
+
+str :: PandocMonad m => MuseParser m (F Inlines)
+str = return . B.str <$> many1Char alphaNum <* updateLastStrPos
+
+-- | Consume asterisks that were not used as emphasis opening.
+-- This prevents series of asterisks from being split into
+-- literal asterisk and emphasis opening.
+asterisks :: PandocMonad m => MuseParser m (F Inlines)
+asterisks = pure . B.str <$> many1Char (char '*')
+
+symbol :: PandocMonad m => MuseParser m (F Inlines)
+symbol = pure . B.str . T.singleton <$> nonspaceChar
+
+-- | Parse a link or image.
+linkOrImage :: PandocMonad m => MuseParser m (F Inlines)
+linkOrImage = try $ link "URL:" <|> image <|> link ""
+
+linkContent :: PandocMonad m => MuseParser m (F Inlines)
+linkContent = trimInlinesF . mconcat
+  <$  char '['
+  <*> manyTill inline (char ']')
+
+-- | Parse a link starting with (possibly null) prefix
+link :: PandocMonad m => Text -> MuseParser m (F Inlines)
+link prefix = try $ do
+  inLink <- asks museInLink
+  guard $ not inLink
+  textStr $ "[[" <> prefix
+  url <- manyTillChar anyChar $ char ']'
+  content <- option (pure $ B.str url) (local (\s -> s { museInLink = True }) linkContent)
+  char ']'
+  return $ B.link url "" <$> content
+
+image :: PandocMonad m => MuseParser m (F Inlines)
+image = try $ do
+  string "[["
+  (url, (ext, width, align)) <- manyUntilChar (noneOf "]") (imageExtensionAndOptions <* char ']')
+  content <- option mempty linkContent
+  char ']'
+  let widthAttr = case align of
+                    Just 'f' -> [("width", fromMaybe "100" width <> "%"), ("height", "75%")]
+                    _ -> maybeToList (("width",) . (<> "%") <$> width)
+  let alignClass = case align of
+                     Just 'r' -> ["align-right"]
+                     Just 'l' -> ["align-left"]
+                     Just 'f' -> []
+                     _        -> []
+  return $ B.imageWith ("", alignClass, widthAttr) (url <> ext) mempty <$> content
+  where -- Taken from muse-image-regexp defined in Emacs Muse file lisp/muse-regexps.el
+        imageExtensions = [".eps", ".gif", ".jpg", ".jpeg", ".pbm", ".png", ".tiff", ".xbm", ".xpm"]
+        imageExtension = choice (try . textStr <$> imageExtensions)
+        imageExtensionAndOptions = do
+          ext <- imageExtension
+          (width, align) <- option (Nothing, Nothing) imageAttrs
+          return (ext, width, align)
+        imageAttrs = (,)
+          <$  many1 spaceChar
+          <*> optionMaybe (many1Char digit)
+          <*  many spaceChar
+          <*> optionMaybe (oneOf "rlf")
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,24 +1,7 @@
-{-
-Copyright (C) 2011-2017 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 OverloadedStrings #-}
 {- |
    Module      : Text.Pandoc.Readers.Native
-   Copyright   : Copyright (C) 2011-2017 John MacFarlane
+   Copyright   : Copyright (C) 2011-2024 John MacFarlane
    License     : GNU GPL, version 2 or above
 
    Maintainer  : John MacFarlane <jgm@berkeley.edu>
@@ -35,9 +18,10 @@
 import Text.Pandoc.Shared (safeRead)
 
 import Control.Monad.Except (throwError)
-import Data.Text (Text, unpack)
-import Text.Pandoc.Class
+import Data.Text (Text)
+import Text.Pandoc.Class.PandocMonad (PandocMonad)
 import Text.Pandoc.Error
+import Text.Pandoc.Sources (ToSources(..), sourcesToText)
 
 -- | Read native formatted text and return a Pandoc document.
 -- The input may be a full pandoc document, a block list, a block,
@@ -49,23 +33,24 @@
 --
 -- > Pandoc nullMeta [Plain [Str "hi"]]
 --
-readNative :: PandocMonad m
+readNative :: (PandocMonad m, ToSources a)
            => ReaderOptions
-           -> Text       -- ^ String to parse (assuming @'\n'@ line endings)
+           -> a
            -> m Pandoc
 readNative _ s =
-  case maybe (Pandoc nullMeta <$> readBlocks s) Right (safeRead (unpack s)) of
-    Right doc -> return doc
-    Left _    -> throwError $ PandocParseError "couldn't read native"
+  let t = sourcesToText . toSources $ s
+  in  case maybe (Pandoc nullMeta <$> readBlocks t) Right (safeRead t) of
+        Right doc -> return doc
+        Left _    -> throwError $ PandocParseError "couldn't read native"
 
 readBlocks :: Text -> Either PandocError [Block]
-readBlocks s = maybe ((:[]) <$> readBlock s) Right (safeRead (unpack s))
+readBlocks s = maybe ((:[]) <$> readBlock s) Right (safeRead s)
 
 readBlock :: Text -> Either PandocError Block
-readBlock s = maybe (Plain <$> readInlines s) Right (safeRead (unpack s))
+readBlock s = maybe (Plain <$> readInlines s) Right (safeRead s)
 
 readInlines :: Text -> Either PandocError [Inline]
-readInlines s = maybe ((:[]) <$> readInline s) Right (safeRead (unpack s))
+readInlines s = maybe ((:[]) <$> readInline s) Right (safeRead s)
 
 readInline :: Text -> Either PandocError Inline
-readInline s = maybe (Left . PandocParseError $ "Could not read: " ++ unpack s) Right (safeRead (unpack s))
+readInline s = maybe (Left . PandocParseError $ "Could not read: " <> s) Right (safeRead s)
diff --git a/src/Text/Pandoc/Readers/ODT.hs b/src/Text/Pandoc/Readers/ODT.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Readers/ODT.hs
@@ -0,0 +1,114 @@
+{-# LANGUAGE OverloadedStrings #-}
+{- |
+   Module      : Text.Pandoc.Reader.ODT
+   Copyright   : Copyright (C) 2015 Martin Linnemann
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : Martin Linnemann <theCodingMarlin@googlemail.com>
+   Stability   : alpha
+   Portability : portable
+
+Entry point to the odt reader.
+-}
+
+module Text.Pandoc.Readers.ODT ( readODT ) where
+
+import Codec.Archive.Zip
+import Text.Pandoc.XML.Light
+import Text.Pandoc.Walk
+
+import Data.Char (isDigit)
+import qualified Data.ByteString.Lazy as B
+
+import System.FilePath
+
+import Control.Monad.Except (throwError)
+
+import qualified Data.Text as T
+
+import Text.Pandoc.Class.PandocMonad (PandocMonad)
+import qualified Text.Pandoc.Class.PandocMonad as P
+import Text.Pandoc.Definition
+import Text.Pandoc.Error
+import Text.Pandoc.MediaBag
+import Text.Pandoc.Options
+import qualified Text.Pandoc.UTF8 as UTF8
+
+import Text.Pandoc.Readers.ODT.ContentReader
+import Text.Pandoc.Readers.ODT.StyleReader
+
+import Text.Pandoc.Readers.ODT.Generic.Fallible
+import Text.Pandoc.Readers.ODT.Generic.XMLConverter
+import Text.Pandoc.Shared (filteredFilesFromArchive)
+
+readODT :: PandocMonad m
+        => ReaderOptions
+        -> B.ByteString
+        -> m Pandoc
+readODT opts bytes = case readODT' opts bytes of
+  Right (doc, mb) -> do
+    P.setMediaBag mb
+    return $ walk makeFigure doc
+  Left e -> throwError e
+
+-- the ODT parser uses old-style figures: an image with title beginning
+-- "fig:" in a paragraph by itself.  Convert these to new Figure elements.
+makeFigure :: Block -> Block
+makeFigure (Para [ Image (ident, classes, kvs) capt (src, tit) ])
+  | "fig:" `T.isPrefixOf` tit
+  = Figure (ident, [], []) (Caption Nothing [Plain capt'])
+      [Plain [Image ("", classes, kvs) capt (src, "")]]
+   where
+     capt' = case capt of -- strip "Figure 1:" for consistency
+                 (Str _ : Space : Str t : Space : xs)
+                    | T.all (\c -> isDigit c || c == ':') t
+                    , ":" `T.isSuffixOf` t -> xs
+                 xs -> xs
+makeFigure x = x
+
+--
+readODT' :: ReaderOptions
+         -> B.ByteString
+         -> Either PandocError (Pandoc, MediaBag)
+readODT' _ bytes = bytesToODT bytes-- of
+--                    Right (pandoc, mediaBag) -> Right (pandoc , mediaBag)
+--                    Left  err                -> Left err
+
+--
+bytesToODT :: B.ByteString -> Either PandocError (Pandoc, MediaBag)
+bytesToODT bytes = case toArchiveOrFail bytes of
+  Right archive -> archiveToODT archive
+  Left err      -> Left $ PandocParseError
+                        $ "Could not unzip ODT: " <> T.pack err
+
+--
+archiveToODT :: Archive -> Either PandocError (Pandoc, MediaBag)
+archiveToODT archive = do
+  let onFailure msg Nothing = Left $ PandocParseError msg
+      onFailure _   (Just x) = Right x
+  contentEntry <- onFailure "Could not find content.xml"
+                   (findEntryByPath "content.xml" archive)
+  stylesEntry <- onFailure "Could not find styles.xml"
+                   (findEntryByPath "styles.xml" archive)
+  contentElem <- entryToXmlElem contentEntry
+  stylesElem <- entryToXmlElem stylesEntry
+  styles <- either
+               (\_ -> Left $ PandocParseError "Could not read styles")
+               Right
+               (chooseMax (readStylesAt stylesElem ) (readStylesAt contentElem))
+  let filePathIsODTMedia :: FilePath -> Bool
+      filePathIsODTMedia fp =
+        let (dir, name) = splitFileName fp
+        in  (dir == "Pictures/") || (dir /= "./" && name == "content.xml")
+  let media = filteredFilesFromArchive archive filePathIsODTMedia
+  let startState = readerState styles media
+  either (\_ -> Left $ PandocParseError "Could not convert opendocument") Right
+    (runConverter' read_body startState contentElem)
+
+
+--
+entryToXmlElem :: Entry -> Either PandocError Element
+entryToXmlElem entry =
+  case parseXMLElement . UTF8.toTextLazy . fromEntry $ entry of
+    Right x  -> Right x
+    Left msg -> Left $ PandocXMLError (T.pack $ eRelativePath entry) msg
diff --git a/src/Text/Pandoc/Readers/ODT/Arrows/State.hs b/src/Text/Pandoc/Readers/ODT/Arrows/State.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Readers/ODT/Arrows/State.hs
@@ -0,0 +1,153 @@
+{-# LANGUAGE FlexibleInstances #-}
+{-# LANGUAGE TupleSections     #-}
+{- |
+   Module      : Text.Pandoc.Readers.ODT.Arrows.State
+   Copyright   : Copyright (C) 2015 Martin Linnemann
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : Martin Linnemann <theCodingMarlin@googlemail.com>
+   Stability   : alpha
+   Portability : portable
+
+An arrow that transports a state. It is in essence a more powerful version of
+the standard state monad. As it is such a simple extension, there are
+other version out there that do exactly the same.
+The implementation is duplicated, though, to add some useful features.
+Most of these might be implemented without access to innards, but it's much
+faster and easier to implement this way.
+-}
+
+module Text.Pandoc.Readers.ODT.Arrows.State
+  ( ArrowState(..)
+  , withState
+  , modifyState
+  , ignoringState
+  , fromState
+  , extractFromState
+  , tryModifyState
+  , withSubStateF
+  , withSubStateF'
+  , foldS
+  , iterateS
+  , iterateSL
+  , iterateS'
+  ) where
+
+import qualified Data.List as L
+import Control.Arrow
+import qualified Control.Category as Cat
+import Control.Monad
+import Text.Pandoc.Readers.ODT.Arrows.Utils
+import Text.Pandoc.Readers.ODT.Generic.Fallible
+
+
+newtype ArrowState state a b = ArrowState
+  { runArrowState :: (state, a) -> (state, b) }
+
+-- | Constructor
+withState           :: (state -> a -> (state, b)) -> ArrowState state a b
+withState            = ArrowState . uncurry
+
+-- | Constructor
+modifyState         :: (state      ->  state    ) -> ArrowState state a a
+modifyState          = ArrowState . first
+
+-- | Constructor
+ignoringState       :: (         a ->         b ) -> ArrowState state a b
+ignoringState        = ArrowState . second
+
+-- | Constructor
+fromState           :: (state      -> (state, b)) -> ArrowState state a b
+fromState            = ArrowState . (.fst)
+
+-- | Constructor
+extractFromState    :: (state      ->         b ) -> ArrowState state x b
+extractFromState   f = ArrowState $ \(state,_) -> (state, f state)
+
+-- | Constructor
+tryModifyState      :: (state ->  Either f state)
+                    -> ArrowState state a (Either f a)
+tryModifyState     f = ArrowState $ \(state,a)
+                                  -> (state,).Left ||| (,Right a) $ f state
+
+instance Cat.Category (ArrowState s) where
+  id                = ArrowState id
+  arrow2 . arrow1   = ArrowState $ runArrowState arrow2 . runArrowState arrow1
+
+instance Arrow (ArrowState state) where
+  arr               = ignoringState
+  first  a          = ArrowState $ \(s,(aF,aS))
+                                    -> second (,aS) $ runArrowState a (s,aF)
+  second a          = ArrowState $ \(s,(aF,aS))
+                                    -> second (aF,) $ runArrowState a (s,aS)
+
+instance ArrowChoice (ArrowState state) where
+  left   a          = ArrowState $ \(s,e) -> case e of
+                                 Left  l -> second Left  $ runArrowState a (s,l)
+                                 Right r -> (s, Right r)
+  right  a          = ArrowState $ \(s,e) -> case e of
+                                 Left  l -> (s, Left l)
+                                 Right r -> second Right $ runArrowState a (s,r)
+
+instance ArrowApply (ArrowState state) where
+   app             = ArrowState $ \(s, (f,b)) -> runArrowState f (s,b)
+
+-- | Switches the type of the state temporarily.
+-- Drops the intermediate result state, behaving like a fallible
+-- identity arrow, save for side effects in the state.
+withSubStateF  :: ArrowState s  x (Either f s')
+               -> ArrowState s' s (Either f s )
+               -> ArrowState s  x (Either f x )
+withSubStateF  unlift a = keepingTheValue (withSubStateF' unlift a)
+                          >>^ spreadChoice
+                          >>^ fmap fst
+
+-- | Switches the type of the state temporarily.
+-- Returns the resulting sub-state.
+withSubStateF' :: ArrowState s  x (Either f s')
+               -> ArrowState s' s (Either f s )
+               -> ArrowState s  x (Either f s')
+withSubStateF' unlift a = ArrowState go
+  where go p@(s,_) = tryRunning unlift
+                                ( tryRunning a (second Right) )
+                                p
+          where tryRunning a' b v = case runArrowState a' v of
+                                      (_ , Left  f) -> (s, Left f)
+                                      (x , Right y) -> b (y,x)
+
+-- | Fold a state arrow through something 'Foldable'. Collect the results
+-- in a 'Monoid'.
+-- Intermediate form of a fold between one with "only" a 'Monoid'
+-- and one with any function.
+foldS :: (Foldable f, Monoid m) => ArrowState s x m -> ArrowState s (f x) m
+foldS a = ArrowState $ \(s,f) -> foldr a' (s,mempty) f
+  where a' x (s',m) = second (mappend m)  $ runArrowState a (s',x)
+
+-- | Fold a state arrow through something 'Foldable'. Collect the results in a
+-- 'MonadPlus'.
+iterateS :: (Foldable f, MonadPlus m)
+         => ArrowState s    x     y
+         -> ArrowState s (f x) (m y)
+iterateS a = ArrowState $ \(s,f) -> foldr a' (s,mzero) f
+  where a' x (s',m) = second (mplus m.return) $ runArrowState a (s',x)
+
+-- | Fold a state arrow through something 'Foldable'. Collect the results in a
+-- 'MonadPlus'.
+iterateSL :: (Foldable f, MonadPlus m)
+          => ArrowState s    x     y
+          -> ArrowState s (f x) (m y)
+iterateSL a = ArrowState $ \(s,f) -> L.foldl' a' (s,mzero) f
+  where a' (s',m) x = second (mplus m.return) $ runArrowState a (s',x)
+
+
+-- | Fold a fallible state arrow through something 'Foldable'.
+-- Collect the results in a 'MonadPlus'.
+-- If the iteration fails, the state will be reset to the initial one.
+iterateS' :: (Foldable f, MonadPlus m)
+          => ArrowState s    x  (Either e    y )
+          -> ArrowState s (f x) (Either e (m y))
+iterateS' a = ArrowState $ \(s,f) -> foldr (a' s) (s,Right mzero) f
+  where a' s x (s',Right m) = case runArrowState a (s',x) of
+                                (s'',Right m') -> (s'',Right $ mplus m $ return m')
+                                (_  ,Left  e ) -> (s  ,Left  e )
+        a' _ _   e          = e
diff --git a/src/Text/Pandoc/Readers/ODT/Arrows/Utils.hs b/src/Text/Pandoc/Readers/ODT/Arrows/Utils.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Readers/ODT/Arrows/Utils.hs
@@ -0,0 +1,241 @@
+{- |
+   Module      : Text.Pandoc.Readers.ODT.Arrows.Utils
+   Copyright   : Copyright (C) 2015 Martin Linnemann
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : Martin Linnemann <theCodingMarlin@googlemail.com>
+   Stability   : alpha
+   Portability : portable
+
+Utility functions for Arrows (Kleisli monads).
+
+Some general notes on notation:
+
+* "^" is meant to stand for a pure function that is lifted into an arrow
+based on its usage for that purpose in "Control.Arrow".
+* "?" is meant to stand for the usage of a 'FallibleArrow' or a pure function
+with an equivalent return value.
+* "_" stands for the dropping of a value.
+-}
+
+-- We export everything
+module Text.Pandoc.Readers.ODT.Arrows.Utils
+  ( and2
+  , and3
+  , and4
+  , and5
+  , and6
+  , liftA2
+  , liftA3
+  , liftA4
+  , liftA5
+  , liftA6
+  , liftA
+  , duplicate
+  , (>>%)
+  , keepingTheValue
+  , (^|||)
+  , (|||^)
+  , (^|||^)
+  , (^&&&)
+  , (&&&^)
+  , choiceToMaybe
+  , maybeToChoice
+  , returnV
+  , FallibleArrow
+  , liftAsSuccess
+  , (>>?)
+  , (>>?^)
+  , (>>?^?)
+  , (^>>?)
+  , (>>?!)
+  , (>>?%)
+  , (>>?%?)
+  , ifFailedDo
+  ) where
+
+import Prelude hiding (Applicative(..))
+import Control.Arrow
+import Control.Monad (join)
+
+import Text.Pandoc.Readers.ODT.Generic.Fallible
+import Text.Pandoc.Readers.ODT.Generic.Utils
+
+and2 :: (Arrow a) => a b c -> a b c' -> a b (c,c')
+and2 = (&&&)
+
+and3 :: (Arrow a)
+     => a b c0->a b c1->a b c2
+     -> a b (c0,c1,c2               )
+and4 :: (Arrow a)
+     => a b c0->a b c1->a b c2->a b c3
+     -> a b (c0,c1,c2,c3            )
+and5 :: (Arrow a)
+     => a b c0->a b c1->a b c2->a b c3->a b c4
+     -> a b (c0,c1,c2,c3,c4         )
+and6 :: (Arrow a)
+     => a b c0->a b c1->a b c2->a b c3->a b c4->a b c5
+     -> a b (c0,c1,c2,c3,c4,c5      )
+
+and3 a b c           = and2 a b &&& c
+                       >>^ \((z,y          ) , x) -> (z,y,x          )
+and4 a b c d         = and3 a b c &&& d
+                       >>^ \((z,y,x        ) , w) -> (z,y,x,w        )
+and5 a b c d e       = and4 a b c d &&& e
+                       >>^ \((z,y,x,w      ) , v) -> (z,y,x,w,v      )
+and6 a b c d e f     = and5 a b c d e &&& f
+                       >>^ \((z,y,x,w,v    ) , u) -> (z,y,x,w,v,u    )
+
+liftA2 :: (Arrow a) => (x -> y -> z) -> a b x -> a b y -> a b z
+liftA2 f a b = a &&& b >>^ uncurry f
+
+liftA3 :: (Arrow a) => (z->y->x                -> r)
+                    -> a b z->a b y->a b x
+                    -> a b r
+liftA4 :: (Arrow a) => (z->y->x->w             -> r)
+                    -> a b z->a b y->a b x->a b w
+                    -> a b r
+liftA5 :: (Arrow a) => (z->y->x->w->v          -> r)
+                    -> a b z->a b y->a b x->a b w->a b v
+                    -> a b r
+liftA6 :: (Arrow a) => (z->y->x->w->v->u       -> r)
+                    -> a b z->a b y->a b x->a b w->a b v->a b u
+                    -> a b r
+
+liftA3 fun a b c           = and3 a b c           >>^ uncurry3 fun
+liftA4 fun a b c d         = and4 a b c d         >>^ uncurry4 fun
+liftA5 fun a b c d e       = and5 a b c d e       >>^ uncurry5 fun
+liftA6 fun a b c d e f     = and6 a b c d e f     >>^ uncurry6 fun
+
+liftA :: (Arrow a) => (y -> z) -> a b y -> a b z
+liftA  fun a = a >>^ fun
+
+
+-- | Duplicate a value to subsequently feed it into different arrows.
+-- Can almost always be replaced with '(&&&)', 'keepingTheValue',
+-- or even '(|||)'.
+-- Equivalent to
+-- > returnA &&& returnA
+duplicate :: (Arrow a) => a b (b,b)
+duplicate = arr $ join (,)
+
+-- | Applies a function to the uncurried result-pair of an arrow-application.
+-- (The %-symbol was chosen to evoke an association with pairs.)
+(>>%) :: (Arrow a) => a x (b,c) -> (b -> c -> d) -> a x d
+a >>% f = a >>^ uncurry f
+
+infixr 2 >>%
+
+
+-- | Duplicate a value and apply an arrow to the second instance.
+-- Equivalent to
+-- > \a -> duplicate >>> second a
+-- or
+-- > \a -> returnA &&& a
+keepingTheValue :: (Arrow a) => a b c -> a b (b,c)
+keepingTheValue a = returnA &&& a
+
+( ^|||  ) :: (ArrowChoice a) => (b -> d) ->  a c d   -> a (Either b c) d
+(  |||^ ) :: (ArrowChoice a) =>  a b d   -> (c -> d) -> a (Either b c) d
+( ^|||^ ) :: (ArrowChoice a) => (b -> d) -> (c -> d) -> a (Either b c) d
+
+l ^|||  r  = arr l |||     r
+l  |||^ r  =     l ||| arr r
+l ^|||^ r  = arr l ||| arr r
+
+infixr 2 ^||| ,  |||^, ^|||^
+
+( ^&&&  ) :: (Arrow a) => (b -> c) ->  a b c'   -> a b (c,c')
+(  &&&^ ) :: (Arrow a) =>  a b c   -> (b -> c') -> a b (c,c')
+
+l ^&&&  r = arr l &&&     r
+l  &&&^ r =     l &&& arr r
+
+infixr 3 ^&&&, &&&^
+
+
+-- | Converts @Right a@ into @Just a@ and @Left _@ into @Nothing@.
+choiceToMaybe :: (ArrowChoice a) => a (Either l r) (Maybe r)
+choiceToMaybe = arr eitherToMaybe
+
+-- | Converts @Nothing@ into @Left ()@ and @Just a@ into @Right a@.
+maybeToChoice :: (ArrowChoice a) => a (Maybe b) (Fallible b)
+maybeToChoice = arr maybeToEither
+
+-- | Lifts a constant value into an arrow
+returnV :: (Arrow a) => c -> a x c
+returnV = arr.const
+
+-- | Defines Left as failure, Right as success
+type FallibleArrow a input failure success = a input (Either failure success)
+
+--
+liftAsSuccess     :: (ArrowChoice a)
+                  => a x success
+                  -> FallibleArrow a x failure success
+liftAsSuccess a   = a >>^ Right
+
+-- | Execute the second arrow if the first succeeds
+(>>?) :: (ArrowChoice a)
+            => FallibleArrow a x       failure success
+            -> FallibleArrow a success failure success'
+            -> FallibleArrow a x       failure success'
+a >>? b = a >>> Left ^||| b
+
+-- | Execute the lifted second arrow if the first succeeds
+(>>?^) :: (ArrowChoice a)
+            => FallibleArrow a x       failure success
+            -> (success                     -> success')
+            -> FallibleArrow a x       failure success'
+a >>?^ f = a >>^ Left ^|||^ Right . f
+
+-- | Execute the lifted second arrow if the first succeeds
+(>>?^?) :: (ArrowChoice a)
+            => FallibleArrow a x       failure success
+            -> (success      -> Either failure success')
+            -> FallibleArrow a x       failure success'
+a >>?^? b = a >>> Left ^|||^ b
+
+-- | Execute the second arrow if the lifted first arrow succeeds
+(^>>?) :: (ArrowChoice a)
+            => (x            -> Either failure success)
+            -> FallibleArrow a success failure success'
+            -> FallibleArrow a x       failure success'
+a ^>>? b = a ^>> Left ^||| b
+
+-- | Execute the second, non-fallible arrow if the first arrow succeeds
+(>>?!) :: (ArrowChoice a)
+            => FallibleArrow a x       failure success
+            ->               a success         success'
+            -> FallibleArrow a x       failure success'
+a >>?! f = a >>> right f
+
+---
+(>>?%) :: (ArrowChoice a)
+          => FallibleArrow a x f (b,b')
+          -> (b -> b' -> c)
+          -> FallibleArrow a x f c
+a >>?% f = a >>?^ uncurry f
+
+
+---
+(>>?%?) :: (ArrowChoice a)
+           => FallibleArrow a x f (b,b')
+           -> (b -> b' -> Either f c)
+           -> FallibleArrow a x f c
+a >>?%? f = a >>?^? uncurry f
+
+infixr 1  >>?,  >>?^,  >>?^?
+infixr 1 ^>>?, >>?!
+infixr 1 >>?%, >>?%?
+
+-- | An arrow version of a short-circuit (<|>)
+ifFailedDo :: (ArrowChoice a)
+           => FallibleArrow a x f y
+           -> FallibleArrow a x f y
+           -> FallibleArrow a x f y
+ifFailedDo a b = keepingTheValue a >>> repackage ^>> (b |||^ Right)
+  where repackage (x , Left  _) = Left  x
+        repackage (_ , Right y) = Right y
+
+infixr 1 `ifFailedDo`
diff --git a/src/Text/Pandoc/Readers/ODT/Base.hs b/src/Text/Pandoc/Readers/ODT/Base.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Readers/ODT/Base.hs
@@ -0,0 +1,26 @@
+{- |
+   Module      : Text.Pandoc.Readers.ODT.Base
+   Copyright   : Copyright (C) 2015 Martin Linnemann
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : Martin Linnemann <theCodingMarlin@googlemail.com>
+   Stability   : alpha
+   Portability : portable
+
+Core types of the odt reader.
+-}
+
+module Text.Pandoc.Readers.ODT.Base
+  ( ODTConverterState
+  , XMLReader
+  , XMLReaderSafe
+  ) where
+
+import Text.Pandoc.Readers.ODT.Generic.XMLConverter
+import Text.Pandoc.Readers.ODT.Namespaces
+
+type ODTConverterState s = XMLConverterState Namespace s
+
+type XMLReader     s a b = FallibleXMLConverter Namespace s a b
+
+type XMLReaderSafe s a b =         XMLConverter Namespace s a b
diff --git a/src/Text/Pandoc/Readers/ODT/ContentReader.hs b/src/Text/Pandoc/Readers/ODT/ContentReader.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Readers/ODT/ContentReader.hs
@@ -0,0 +1,1054 @@
+{-# LANGUAGE Arrows            #-}
+{-# LANGUAGE CPP               #-}
+{-# LANGUAGE DeriveFoldable    #-}
+{-# LANGUAGE GeneralizedNewtypeDeriving #-}
+{-# LANGUAGE PatternGuards     #-}
+{-# LANGUAGE RecordWildCards   #-}
+{-# LANGUAGE TupleSections     #-}
+{-# LANGUAGE ViewPatterns      #-}
+{-# LANGUAGE OverloadedStrings #-}
+{- |
+   Module      : Text.Pandoc.Readers.ODT.ContentReader
+   Copyright   : Copyright (C) 2015 Martin Linnemann
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : Martin Linnemann <theCodingMarlin@googlemail.com>
+   Stability   : alpha
+   Portability : portable
+
+The core of the odt reader that converts odt features into Pandoc types.
+-}
+
+module Text.Pandoc.Readers.ODT.ContentReader
+( readerState
+, read_body
+) where
+
+import Prelude hiding (Applicative(..))
+import Control.Applicative hiding (liftA, liftA2, liftA3)
+import Control.Arrow
+import Control.Monad ((<=<))
+
+import qualified Data.ByteString.Lazy as B
+import Data.Foldable (fold)
+import Data.List (find)
+import qualified Data.Map as M
+import qualified Data.Text as T
+import Data.Maybe
+import Data.Monoid (Alt (..))
+
+import Text.TeXMath (readMathML, writeTeX)
+import qualified Text.Pandoc.XML.Light as XML
+
+import Text.Pandoc.Builder hiding (underline)
+import Text.Pandoc.MediaBag (MediaBag, insertMedia)
+import Text.Pandoc.Shared
+import Text.Pandoc.Extensions (extensionsFromList, Extension(..))
+import qualified Text.Pandoc.UTF8 as UTF8
+
+import Text.Pandoc.Readers.Docx.Combine (combineBlocks)
+
+import Text.Pandoc.Readers.ODT.Base
+import Text.Pandoc.Readers.ODT.Namespaces
+import Text.Pandoc.Readers.ODT.StyleReader
+
+import Text.Pandoc.Readers.ODT.Arrows.State (foldS)
+import Text.Pandoc.Readers.ODT.Arrows.Utils
+import Text.Pandoc.Readers.ODT.Generic.Fallible
+import Text.Pandoc.Readers.ODT.Generic.Utils
+import Text.Pandoc.Readers.ODT.Generic.XMLConverter
+
+import Network.URI (parseRelativeReference, URI(uriPath))
+import qualified Data.Set as Set
+
+--------------------------------------------------------------------------------
+-- State
+--------------------------------------------------------------------------------
+
+type Anchor = T.Text
+type Media = [(FilePath, B.ByteString)]
+
+data ReaderState
+   = ReaderState { -- | A collection of styles read somewhere else.
+                   -- It is only queried here, not modified.
+                   styleSet         :: Styles
+                   -- | A stack of the styles of parent elements.
+                   -- Used to look up inherited style properties.
+                 , styleTrace       :: [Style]
+                   -- | Keeps track of the current depth in nested lists
+                 , currentListLevel :: ListLevel
+                   -- | Keeps track of the previous list start counters,
+                   -- so whenever a new list continues numbering,
+                   -- we know what number to start from.
+                   -- If  list does not continue numbering, the counter
+                   -- is being reset.
+                 , listContinuationStartCounters :: M.Map ListLevel Int
+                   -- | Lists may provide their own style, but they don't have
+                   -- to. If they do not, the style of a parent list may be used
+                   -- or even a default list style from the paragraph style.
+                   -- This value keeps track of the closest list style there
+                   -- currently is.
+                 , currentListStyle :: Maybe ListStyle
+                   -- | A map from internal anchor names to "pretty" ones.
+                   -- The mapping is a purely cosmetic one.
+                 , bookmarkAnchors  :: M.Map Anchor Anchor
+                   -- | A map of files / binary data from the archive
+                 , envMedia         :: Media
+                   -- | Hold binary resources used in the document
+                 , odtMediaBag      :: MediaBag
+                 }
+  deriving ( Show )
+
+readerState :: Styles -> Media -> ReaderState
+readerState styles media = ReaderState styles [] 0 M.empty Nothing M.empty media mempty
+
+--
+pushStyle'  :: Style -> ReaderState -> ReaderState
+pushStyle' style state = state { styleTrace = style : styleTrace state }
+
+--
+popStyle'   :: ReaderState -> ReaderState
+popStyle' state = case styleTrace state of
+                   _:trace -> state  { styleTrace = trace  }
+                   _       -> state
+--
+modifyListLevel :: (ListLevel -> ListLevel) -> (ReaderState -> ReaderState)
+modifyListLevel f state = state { currentListLevel = f (currentListLevel state) }
+
+--
+modifyListContinuationStartCounter :: ListLevel -> Int -> (ReaderState -> ReaderState)
+modifyListContinuationStartCounter listLevel count state =
+    state { listContinuationStartCounters = M.insert listLevel count (listContinuationStartCounters state) }
+
+--
+shiftListLevel :: ListLevel -> (ReaderState -> ReaderState)
+shiftListLevel diff = modifyListLevel (+ diff)
+
+--
+swapCurrentListStyle :: Maybe ListStyle -> ReaderState
+                     -> (ReaderState, Maybe ListStyle)
+swapCurrentListStyle mListStyle state = ( state { currentListStyle = mListStyle }
+                                        ,  currentListStyle state
+                                        )
+
+--
+lookupPrettyAnchor :: Anchor -> ReaderState -> Maybe Anchor
+lookupPrettyAnchor anchor ReaderState{..} = M.lookup anchor bookmarkAnchors
+
+--
+putPrettyAnchor :: Anchor -> Anchor -> ReaderState -> ReaderState
+putPrettyAnchor ugly pretty state@ReaderState{..}
+  = state { bookmarkAnchors = M.insert ugly pretty bookmarkAnchors }
+
+--
+usedAnchors :: ReaderState -> [Anchor]
+usedAnchors ReaderState{..} = M.elems bookmarkAnchors
+
+getMediaBag :: ReaderState -> MediaBag
+getMediaBag ReaderState{..} = odtMediaBag
+
+getMediaEnv :: ReaderState -> Media
+getMediaEnv ReaderState{..} = envMedia
+
+insertMedia' :: (FilePath, B.ByteString) -> ReaderState ->  ReaderState
+insertMedia' (fp, bs) state@ReaderState{..}
+  = state { odtMediaBag = insertMedia fp Nothing bs odtMediaBag }
+
+--------------------------------------------------------------------------------
+-- Reader type and associated tools
+--------------------------------------------------------------------------------
+
+type ODTReader      a b = XMLReader     ReaderState a b
+
+type ODTReaderSafe  a b = XMLReaderSafe ReaderState a b
+
+-- | Extract something from the styles
+fromStyles :: (a -> Styles -> b) -> ODTReaderSafe a b
+fromStyles f =     keepingTheValue
+                     (getExtraState >>^ styleSet)
+               >>% f
+
+--
+getStyleByName :: ODTReader StyleName Style
+getStyleByName = fromStyles lookupStyle >>^ maybeToChoice
+
+--
+findStyleFamily :: ODTReader Style StyleFamily
+findStyleFamily = fromStyles getStyleFamily >>^ maybeToChoice
+
+--
+lookupListStyle :: ODTReader StyleName ListStyle
+lookupListStyle = fromStyles lookupListStyleByName >>^ maybeToChoice
+
+--
+switchCurrentListStyle :: ODTReaderSafe (Maybe ListStyle) (Maybe ListStyle)
+switchCurrentListStyle =     keepingTheValue getExtraState
+                         >>% swapCurrentListStyle
+                         >>> first setExtraState
+                         >>^ snd
+
+--
+pushStyle :: ODTReaderSafe Style Style
+pushStyle =     keepingTheValue (
+                  (     keepingTheValue getExtraState
+                    >>% pushStyle'
+                  )
+                  >>> setExtraState
+                )
+            >>^ fst
+
+--
+popStyle :: ODTReaderSafe x x
+popStyle =     keepingTheValue (
+                     getExtraState
+                 >>> arr popStyle'
+                 >>> setExtraState
+               )
+           >>^ fst
+
+--
+getCurrentListLevel :: ODTReaderSafe a ListLevel
+getCurrentListLevel = getExtraState >>^ currentListLevel
+
+--
+getListContinuationStartCounters :: ODTReaderSafe a (M.Map ListLevel Int)
+getListContinuationStartCounters = getExtraState >>^ listContinuationStartCounters
+
+
+--
+getPreviousListStartCounter :: ODTReaderSafe ListLevel Int
+getPreviousListStartCounter = proc listLevel -> do
+    counts <- getListContinuationStartCounters -< ()
+    returnA -< M.findWithDefault 0 listLevel counts
+
+--
+updateMediaWithResource :: ODTReaderSafe (FilePath, B.ByteString) (FilePath, B.ByteString)
+updateMediaWithResource = keepingTheValue (
+                 (keepingTheValue getExtraState
+                  >>% insertMedia'
+                  )
+                 >>> setExtraState
+               )
+           >>^ fst
+
+lookupResource :: ODTReaderSafe FilePath (FilePath, B.ByteString)
+lookupResource = proc target -> do
+    state <- getExtraState -< ()
+    case lookup target (getMediaEnv state) of
+      Just bs -> returnV (target, bs) -<< ()
+      Nothing -> returnV ("", B.empty) -< ()
+
+type AnchorPrefix = T.Text
+
+-- | An adaptation of 'uniqueIdent' from "Text.Pandoc.Shared" that generates a
+-- unique identifier but without assuming that the id should be for a header.
+-- Second argument is a list of already used identifiers.
+uniqueIdentFrom :: AnchorPrefix -> [Anchor] -> Anchor
+uniqueIdentFrom baseIdent usedIdents =
+  let  numIdent n = baseIdent <> "-" <> T.pack (show n)
+  in  if baseIdent `elem` usedIdents
+        then maybe baseIdent numIdent
+             $ find (\x -> numIdent x `notElem` usedIdents) ([1..60000] :: [Int])
+               -- if we have more than 60,000, allow repeats
+        else baseIdent
+
+-- | First argument: basis for a new "pretty" anchor if none exists yet
+-- Second argument: a key ("ugly" anchor)
+-- Returns: saved "pretty" anchor or created new one
+getPrettyAnchor :: ODTReaderSafe (AnchorPrefix, Anchor) Anchor
+getPrettyAnchor = proc (baseIdent, uglyAnchor) -> do
+  state <- getExtraState -< ()
+  case lookupPrettyAnchor uglyAnchor state of
+    Just prettyAnchor -> returnA -< prettyAnchor
+    Nothing           -> do
+      let newPretty = uniqueIdentFrom baseIdent (usedAnchors state)
+      modifyExtraState (putPrettyAnchor uglyAnchor newPretty) -<< newPretty
+
+-- | Input: basis for a new header anchor
+-- Output: saved new anchor
+getHeaderAnchor :: ODTReaderSafe Inlines Anchor
+getHeaderAnchor = proc title -> do
+  state <- getExtraState -< ()
+  let exts = extensionsFromList [Ext_auto_identifiers]
+  let anchor = uniqueIdent exts (toList title)
+                (Set.fromList $ usedAnchors state)
+  modifyExtraState (putPrettyAnchor anchor anchor) -<< anchor
+
+
+--------------------------------------------------------------------------------
+-- Working with styles
+--------------------------------------------------------------------------------
+
+--
+readStyleByName :: ODTReader a (StyleName, Style)
+readStyleByName =
+  findAttr NsText "style-name" >>? keepingTheValue getStyleByName >>^ liftE
+  where
+    liftE :: (StyleName, Fallible Style) -> Fallible (StyleName, Style)
+    liftE (name, Right v) = Right (name, v)
+    liftE (_, Left v)     = Left v
+
+--
+isStyleToTrace :: ODTReader Style Bool
+isStyleToTrace = findStyleFamily >>?^ (==FaText)
+
+--
+withNewStyle :: ODTReaderSafe x Inlines -> ODTReaderSafe x Inlines
+withNewStyle a = proc x -> do
+  fStyle <- readStyleByName -< ()
+  case fStyle of
+    Right (styleName, _) | isCodeStyle styleName -> do
+      inlines <- a -< x
+      arr inlineCode -<< inlines
+    Right (_, style) -> do
+      mFamily    <- arr styleFamily -< style
+      fTextProps <- arr ( maybeToChoice
+                        . textProperties
+                        . styleProperties
+                        )           -< style
+      case fTextProps of
+        Right textProps -> do
+          state        <- getExtraState             -< ()
+          let triple = (state, textProps, mFamily)
+          modifier     <- arr modifierFromStyleDiff -< triple
+          fShouldTrace <- isStyleToTrace            -< style
+          case fShouldTrace of
+            Right shouldTrace ->
+              if shouldTrace
+                then do
+                  pushStyle      -< style
+                  inlines   <- a -< x
+                  popStyle       -< ()
+                  arr modifier   -<< inlines
+                else
+    -- In case anything goes wrong
+                      a -< x
+            Left _ -> a -< x
+        Left _     -> a -< x
+    Left _         -> a -< x
+  where
+    isCodeStyle :: StyleName -> Bool
+    isCodeStyle "Source_Text" = True
+    isCodeStyle "Source_20_Text" = True
+    isCodeStyle _             = False
+
+    inlineCode :: Inlines -> Inlines
+    inlineCode = code . T.concat . map stringify . toList
+
+type PropertyTriple = (ReaderState, TextProperties, Maybe StyleFamily)
+type InlineModifier = Inlines -> Inlines
+
+-- | Given data about the local style changes, calculates how to modify
+-- an instance of 'Inlines'
+modifierFromStyleDiff :: PropertyTriple -> InlineModifier
+modifierFromStyleDiff propertyTriple  =
+  composition $
+  getVPosModifier propertyTriple
+  : map (first ($ propertyTriple) >>> ifThen_else ignore)
+        [ (hasEmphChanged           , emph      )
+        , (hasChanged isStrong      , strong    )
+        , (hasChanged strikethrough , strikeout )
+        ]
+  where
+    ifThen_else else' (if',then') = if if' then then' else else'
+
+    ignore = id :: InlineModifier
+
+    getVPosModifier :: PropertyTriple -> InlineModifier
+    getVPosModifier triple@(_,textProps,_) =
+        let getVPos = Just . verticalPosition
+        in  case lookupPreviousValueM getVPos triple of
+              Nothing      -> ignore
+              Just oldVPos -> getVPosModifier' (oldVPos, verticalPosition textProps)
+
+    getVPosModifier' (oldVPos , newVPos   ) | oldVPos == newVPos = ignore
+    getVPosModifier' ( _      , VPosSub   ) = subscript
+    getVPosModifier' ( _      , VPosSuper ) = superscript
+    getVPosModifier' ( _      ,  _        ) = ignore
+
+    hasEmphChanged :: PropertyTriple -> Bool
+    hasEmphChanged = swing any [ hasChanged  isEmphasised
+                               , hasChangedM pitch
+                               , hasChanged  underline
+                               ]
+
+    hasChanged property triple@(_, property -> newProperty, _) =
+        (/= Just newProperty) (lookupPreviousValue property triple)
+
+    hasChangedM property triple@(_, textProps,_) =
+      fromMaybe False $ (/=) <$> property textProps <*> lookupPreviousValueM property triple
+
+    lookupPreviousValue f = lookupPreviousStyleValue (fmap f . textProperties)
+
+    lookupPreviousValueM f = lookupPreviousStyleValue (f <=< textProperties)
+
+    lookupPreviousStyleValue f (ReaderState{..},_,mFamily)
+      =     findBy f (extendedStylePropertyChain styleTrace styleSet)
+        <|> (f . lookupDefaultStyle' styleSet =<< mFamily)
+
+
+type ParaModifier = Blocks -> Blocks
+
+_MINIMUM_INDENTATION_FOR_BLOCKQUOTES_IN_MM_      :: Int
+_MINIMUM_INDENTATION_FOR_BLOCKQUOTES_IN_PERCENT_ :: Int
+_MINIMUM_INDENTATION_FOR_BLOCKQUOTES_IN_MM_      = 5
+_MINIMUM_INDENTATION_FOR_BLOCKQUOTES_IN_PERCENT_ = 5
+
+-- | Returns either 'id' or 'blockQuote' depending if any of the StyleProperties
+-- are indented at quote level.
+getParaModifier :: ListLevel -> [StyleProperties] -> ParaModifier
+getParaModifier listLevel props
+  | listLevel > 0 = id -- see #9505, list paragraphs need indentation
+  | any isBlockQuote props = blockQuote
+  | otherwise = id
+  where
+  isBlockQuote SProps {..} | Just paraProps <- paraProperties
+                                    , isQuoteWidth (margin_left paraProps)
+                                    = True
+                                    | otherwise
+                                    = False
+  isQuoteWidth mMargin
+    | LengthValueMM margin <- mMargin
+    ,           margin > _MINIMUM_INDENTATION_FOR_BLOCKQUOTES_IN_MM_
+     = True
+    | PercentValue  margin <- mMargin
+    ,           margin > _MINIMUM_INDENTATION_FOR_BLOCKQUOTES_IN_PERCENT_
+     = True
+    | otherwise
+     = False
+
+--
+constructPara :: ODTReaderSafe a Blocks -> ODTReaderSafe a Blocks
+constructPara reader = proc blocks -> do
+  fStyle <- readStyleByName -< blocks
+  case fStyle of
+    Left   _    -> reader -< blocks
+    Right (styleName, _) | isTableCaptionStyle styleName -> do
+      blocks' <- reader   -< blocks
+      arr tableCaptionP  -< blocks'
+    Right (_, style) -> do
+      props <- fromStyles extendedStylePropertyChain -< [style]
+      listLevel <- getCurrentListLevel -< ()
+      let modifier = getParaModifier listLevel props
+      blocks' <- reader   -<  blocks
+      arr modifier        -<< blocks'
+  where
+    isTableCaptionStyle :: StyleName -> Bool
+    isTableCaptionStyle "Table" = True
+    isTableCaptionStyle _       = False
+    tableCaptionP b = divWith ("", ["caption"], []) b
+
+type ListConstructor = [Blocks] -> Blocks
+
+getListConstructor :: ListLevelStyle -> Int -> ListConstructor
+getListConstructor ListLevelStyle{..} startNum =
+  case listLevelType of
+    LltBullet   -> bulletList
+    LltImage    -> bulletList
+    LltNumbered -> let listNumberStyle = toListNumberStyle listItemFormat
+                       listNumberDelim = toListNumberDelim listItemPrefix
+                                                           listItemSuffix
+                   in  orderedListWith (startNum, listNumberStyle, listNumberDelim)
+  where
+    toListNumberStyle  LinfNone      = DefaultStyle
+    toListNumberStyle  LinfNumber    = Decimal
+    toListNumberStyle  LinfRomanLC   = LowerRoman
+    toListNumberStyle  LinfRomanUC   = UpperRoman
+    toListNumberStyle  LinfAlphaLC   = LowerAlpha
+    toListNumberStyle  LinfAlphaUC   = UpperAlpha
+    toListNumberStyle (LinfString _) = Example
+
+    toListNumberDelim  Nothing   (Just ".") = Period
+    toListNumberDelim (Just "" ) (Just ".") = Period
+    toListNumberDelim  Nothing   (Just ")") = OneParen
+    toListNumberDelim (Just "" ) (Just ")") = OneParen
+    toListNumberDelim (Just "(") (Just ")") = TwoParens
+    toListNumberDelim     _          _      = DefaultDelim
+
+-- | Determines which style to use for a list, which level to use of that
+-- style, and which type of list to create as a result of this information.
+-- Then prepares the state for eventual child lists and constructs the list from
+-- the results.
+-- Two main cases are handled: The list may provide its own style or it may
+-- rely on a parent list's style. I the former case the current style in the
+-- state must be switched before and after the call to the child converter
+-- while in the latter the child converter can be called directly.
+-- If anything goes wrong, a default ordered-list-constructor is used.
+constructList :: ODTReaderSafe x [Blocks] -> ODTReaderSafe x Blocks
+constructList reader = proc x -> do
+  modifyExtraState (shiftListLevel 1)                                  -< ()
+  listLevel                    <- getCurrentListLevel                  -< ()
+  listContinuationStartCounter <- getPreviousListStartCounter          -< listLevel
+  fStyleName                   <- findAttr NsText "style-name"         -< ()
+  fContNumbering               <- findAttr NsText "continue-numbering" -< ()
+  listItemCount                <- reader >>^ length                    -< x
+
+  let continueNumbering = case fContNumbering of
+                            Right "true" -> True
+                            _            -> False
+
+  let startNumForListLevelStyle = listStartingNumber continueNumbering listContinuationStartCounter
+  let defaultOrderedListConstructor = constructOrderedList (startNumForListLevelStyle Nothing) listLevel listItemCount
+
+  case fStyleName of
+    Right styleName -> do
+      fListStyle <- lookupListStyle -< styleName
+      case fListStyle of
+        Right listStyle -> do
+          fListLevelStyle <- arr (uncurry getListLevelStyle) -< (listLevel, listStyle)
+          case fListLevelStyle of
+            Just listLevelStyle -> do
+              let startNum = startNumForListLevelStyle $ Just listLevelStyle
+              oldListStyle <- switchCurrentListStyle                    -<  Just listStyle
+              blocks       <- constructListWith listLevelStyle startNum listLevel listItemCount -<< x
+              switchCurrentListStyle                                    -<  oldListStyle
+              returnA                                                   -<  blocks
+            Nothing             -> defaultOrderedListConstructor -<< x
+        Left _                  -> defaultOrderedListConstructor -<< x
+    Left _ -> do
+      state      <- getExtraState        -< ()
+      mListStyle <- arr currentListStyle -< state
+      case mListStyle of
+        Just listStyle -> do
+          fListLevelStyle <- arr (uncurry getListLevelStyle) -< (listLevel, listStyle)
+          case fListLevelStyle of
+            Just listLevelStyle -> do
+              let startNum = startNumForListLevelStyle $ Just listLevelStyle
+              constructListWith listLevelStyle startNum listLevel listItemCount -<< x
+            Nothing             -> defaultOrderedListConstructor -<< x
+        Nothing                 -> defaultOrderedListConstructor -<< x
+  where
+    listStartingNumber continueNumbering listContinuationStartCounter mListLevelStyle
+      | continueNumbering                = listContinuationStartCounter
+      | isJust mListLevelStyle           = listItemStart (fromJust mListLevelStyle)
+      | otherwise                        = 1
+    constructOrderedList startNum listLevel listItemCount =
+          reader
+      >>> modifyExtraState (shiftListLevel (-1))
+      >>> modifyExtraState (modifyListContinuationStartCounter listLevel (startNum + listItemCount))
+      >>^ orderedListWith (startNum, DefaultStyle, DefaultDelim)
+    constructListWith listLevelStyle startNum listLevel listItemCount =
+          reader
+      >>> getListConstructor listLevelStyle startNum
+      ^>> modifyExtraState (shiftListLevel (-1))
+      >>> modifyExtraState (modifyListContinuationStartCounter listLevel (startNum + listItemCount))
+
+--------------------------------------------------------------------------------
+-- Readers
+--------------------------------------------------------------------------------
+
+type ElementMatcher result = (Namespace, ElementName, ODTReader result result)
+
+type InlineMatcher = ElementMatcher Inlines
+
+type BlockMatcher  = ElementMatcher Blocks
+
+newtype FirstMatch a = FirstMatch (Alt Maybe a)
+  deriving (Foldable, Monoid, Semigroup)
+
+firstMatch :: a -> FirstMatch a
+firstMatch = FirstMatch . Alt . Just
+
+newtype CombiningBlocks = CombiningBlocks { unCombiningBlocks :: Blocks }
+
+instance Semigroup CombiningBlocks where
+  CombiningBlocks l <> CombiningBlocks r = CombiningBlocks (combineBlocks l r)
+
+instance Monoid CombiningBlocks where
+  mempty = CombiningBlocks mempty
+
+--
+matchingElement :: (Monoid e)
+                => Namespace -> ElementName
+                -> ODTReaderSafe  e e
+                -> ElementMatcher e
+matchingElement ns name reader = (ns, name, asResultAccumulator reader)
+  where
+   asResultAccumulator :: (ArrowChoice a, Monoid m) => a m m -> a m (Fallible m)
+   asResultAccumulator a = liftAsSuccess $ keepingTheValue a >>% mappend
+
+--
+matchChildContent'   :: (Monoid result)
+                     => [ElementMatcher result]
+                     ->  ODTReaderSafe a result
+matchChildContent' ls = returnV mempty >>> matchContent' ls
+
+--
+matchSmushedChildBlocks' :: [ElementMatcher CombiningBlocks] ->  ODTReaderSafe a Blocks
+matchSmushedChildBlocks' ls = liftA unCombiningBlocks
+                              $ returnV mempty
+                                >>> matchContent' ls
+
+--
+matchChildContent    :: (Monoid result)
+                     => [ElementMatcher result]
+                     ->  ODTReaderSafe  (result, XML.Content) result
+                     ->  ODTReaderSafe a result
+matchChildContent ls fallback = returnV mempty >>> matchContent ls fallback
+
+--------------------------------------------
+-- Matchers
+--------------------------------------------
+
+----------------------
+-- Basics
+----------------------
+
+--
+-- | Open Document allows several consecutive spaces if they are marked up
+read_plain_text :: ODTReaderSafe (Inlines, XML.Content) Inlines
+read_plain_text =  fst ^&&& read_plain_text' >>% recover
+  where
+    -- fallible version
+    read_plain_text' :: ODTReader (Inlines, XML.Content) Inlines
+    read_plain_text' =      (     second ( arr extractText )
+                              >>^ spreadChoice >>?! second text
+                            )
+                       >>?% mappend
+    --
+    extractText     :: XML.Content -> Fallible T.Text
+    extractText (XML.Text cData) = succeedWith (XML.cdData cData)
+    extractText         _        = failEmpty
+
+read_text_seq :: InlineMatcher
+read_text_seq  = matchingElement NsText "sequence"
+                 $ matchChildContent [] read_plain_text
+
+
+-- specifically. I honor that, although the current implementation of 'mappend'
+-- for 'Inlines' in "Text.Pandoc.Builder" will collapse them again.
+-- The rational is to be prepared for future modifications.
+read_spaces      :: InlineMatcher
+read_spaces       = matchingElement NsText "s" (
+                          readAttrWithDefault NsText "c" 1 -- how many spaces?
+                      >>^ fromList.(`replicate` Space)
+                    )
+--
+read_line_break  :: InlineMatcher
+read_line_break   = matchingElement NsText "line-break"
+                    $ returnV linebreak
+--
+read_tab         :: InlineMatcher
+read_tab          = matchingElement NsText "tab"
+                    $ returnV space
+--
+read_span        :: InlineMatcher
+read_span         = matchingElement NsText "span"
+                    $ withNewStyle
+                    $ matchChildContent [ read_span
+                                        , read_spaces
+                                        , read_line_break
+                                        , read_tab
+                                        , read_link
+                                        , read_frame
+                                        , read_note
+                                        , read_citation
+                                        , read_bookmark
+                                        , read_bookmark_start
+                                        , read_reference_start
+                                        , read_bookmark_ref
+                                        , read_reference_ref
+                                        ] read_plain_text
+
+--
+read_paragraph   :: ElementMatcher CombiningBlocks
+read_paragraph    = matchingElement NsText "p" $
+                      liftA CombiningBlocks $ proc blocks -> do
+                        fStyle <- readStyleByName -< blocks
+                        case fStyle of
+                          Right style | isPreformattedStyle style -> do
+                            liftA (codeBlock . stringify) $ matchParagraphContent -< blocks
+                          _ ->
+                            constructPara $ liftA para $ withNewStyle matchParagraphContent -< blocks
+                        where
+                          isPreformattedStyle :: (StyleName, Style) -> Bool
+                          isPreformattedStyle ("Preformatted_20_Text", _) = True
+                          isPreformattedStyle (_, Style { styleParentName = Just "Preformatted_20_Text" }) = True
+                          isPreformattedStyle _ = False
+
+
+matchParagraphContent :: ODTReaderSafe a Inlines
+matchParagraphContent = matchChildContent [ read_span
+                                          , read_spaces
+                                          , read_line_break
+                                          , read_tab
+                                          , read_link
+                                          , read_note
+                                          , read_citation
+                                          , read_bookmark
+                                          , read_bookmark_start
+                                          , read_reference_start
+                                          , read_bookmark_ref
+                                          , read_reference_ref
+                                          , read_frame
+                                          , read_text_seq
+                                          ] read_plain_text
+
+
+----------------------
+-- Headers
+----------------------
+
+--
+read_header      :: ElementMatcher CombiningBlocks
+read_header       = matchingElement NsText "h"
+                    $  proc blocks -> do
+  level    <- ( readAttrWithDefault NsText "outline-level" 1
+              ) -< blocks
+  children <- ( matchChildContent [ read_span
+                                  , read_spaces
+                                  , read_line_break
+                                  , read_tab
+                                  , read_link
+                                  , read_note
+                                  , read_citation
+                                  , read_bookmark
+                                  , read_bookmark_start
+                                  , read_reference_start
+                                  , read_bookmark_ref
+                                  , read_reference_ref
+                                  , read_frame
+                                  ] read_plain_text
+              ) -< blocks
+  anchor   <- getHeaderAnchor -< children
+  let idAttr = (anchor, [], []) -- no classes, no key-value pairs
+  arr (CombiningBlocks . uncurry3 headerWith) -< (idAttr, level, children)
+
+----------------------
+-- Lists
+----------------------
+
+--
+read_list        :: ElementMatcher CombiningBlocks
+read_list         = matchingElement NsText "list"
+                    $ liftA CombiningBlocks
+                    $ constructList
+                    $ matchChildContent' [ read_list_item
+                                         , read_list_header
+                                         ]
+--
+read_list_item   :: ElementMatcher [Blocks]
+read_list_item    = read_list_element "list-item"
+
+read_list_header :: ElementMatcher [Blocks]
+read_list_header  = read_list_element "list-header"
+
+read_list_element               :: ElementName -> ElementMatcher [Blocks]
+read_list_element listElement   = matchingElement NsText listElement
+                                  $ liftA (compactify.(:[]))
+                                    ( matchSmushedChildBlocks' [ read_paragraph
+                                                               , read_header
+                                                               , read_list
+                                                               , read_section
+                                                               ]
+                                    )
+
+----------------------
+-- Sections
+----------------------
+
+read_section :: ElementMatcher CombiningBlocks
+read_section = matchingElement NsText "section"
+                 $ liftA (CombiningBlocks . divWith nullAttr)
+                 $ matchSmushedChildBlocks' [ read_paragraph
+                                            , read_header
+                                            , read_list
+                                            , read_table
+                                            , read_section
+                                            ]
+
+
+----------------------
+-- Links
+----------------------
+
+read_link        :: InlineMatcher
+read_link         = matchingElement NsText "a"
+                    $ liftA3 link
+                      ( findAttrTextWithDefault NsXLink  "href"  ""
+                        >>> arr fixRelativeLink                              )
+                      ( findAttrTextWithDefault NsOffice "title" ""          )
+                      ( matchChildContent [ read_span
+                                          , read_note
+                                          , read_citation
+                                          , read_bookmark
+                                          , read_bookmark_start
+                                          , read_reference_start
+                                          , read_bookmark_ref
+                                          , read_reference_ref
+                                          ] read_plain_text                  )
+
+fixRelativeLink :: T.Text -> T.Text
+fixRelativeLink uri =
+    case parseRelativeReference (T.unpack uri) of
+      Nothing -> uri
+      Just u  ->
+        case uriPath u of
+          '.':'.':'/':xs -> tshow $ u{ uriPath = xs }
+          _ -> uri
+
+-------------------------
+-- Footnotes
+-------------------------
+
+read_note        :: InlineMatcher
+read_note         = matchingElement NsText "note"
+                    $ liftA note
+                    $ matchChildContent' [ read_note_body ]
+
+read_note_body   :: BlockMatcher
+read_note_body    = matchingElement NsText "note-body"
+                    $ matchSmushedChildBlocks' [ read_paragraph ]
+
+-------------------------
+-- Citations
+-------------------------
+
+read_citation    :: InlineMatcher
+read_citation     = matchingElement NsText "bibliography-mark"
+                    $ liftA2 cite
+                      ( liftA2 makeCitation
+                        ( findAttrTextWithDefault NsText "identifier" "" )
+                        ( readAttrWithDefault NsText "number" 0          )
+                      )
+                      ( matchChildContent [] read_plain_text             )
+  where
+   makeCitation :: T.Text -> Int -> [Citation]
+   makeCitation citeId num = [Citation citeId [] [] NormalCitation num 0]
+
+
+----------------------
+-- Tables
+----------------------
+
+--
+read_table        :: ElementMatcher CombiningBlocks
+read_table         = matchingElement NsTable "table"
+                     $ liftA (CombiningBlocks . table')
+                     $ (matchChildContent' [read_table_header]) &&&
+                       (matchChildContent' [read_table_row])
+
+-- | A table without a caption.
+table' :: ([[Cell]], [[Cell]]) -> Blocks
+table' (headers, rows) =
+  table emptyCaption (replicate numcols defaults) th [tb] tf
+  where
+    defaults = (AlignDefault, ColWidthDefault)
+    numcols = maximum $ map length $ headers ++ rows
+    toRow = Row nullAttr
+    th = TableHead nullAttr $ map toRow headers
+    tb = TableBody nullAttr 0 [] $ map toRow rows
+    tf = TableFoot nullAttr []
+
+--
+read_table_header :: ElementMatcher [[Cell]]
+read_table_header = matchingElement NsTable "table-header-rows"
+                      $ matchChildContent' [ read_table_row
+                                           ]
+
+--
+read_table_row    :: ElementMatcher [[Cell]]
+read_table_row     = matchingElement NsTable "table-row"
+                     $ liftA (:[])
+                     $ matchChildContent'  [ read_table_cell
+                                           ]
+
+--
+read_table_cell   :: ElementMatcher [Cell]
+read_table_cell    = matchingElement NsTable "table-cell"
+                     $ liftA3 cell'
+                       (readAttrWithDefault NsTable "number-rows-spanned" 1 >>^ RowSpan)
+                       (readAttrWithDefault NsTable "number-columns-spanned" 1 >>^ ColSpan)
+                     $ matchSmushedChildBlocks' [ read_paragraph
+                                                , read_list
+                                                ]
+  where
+    cell' rowSpan colSpan blocks = map (cell AlignDefault rowSpan colSpan) $ compactify [blocks]
+
+----------------------
+-- Frames
+----------------------
+
+--
+read_frame :: InlineMatcher
+read_frame = matchingElement NsDraw "frame"
+             $ filterChildrenName' NsDraw (`elem` ["image", "object", "text-box"])
+           >>> foldS read_frame_child
+           >>> arr fold
+
+read_frame_child :: ODTReaderSafe XML.Element (FirstMatch Inlines)
+read_frame_child =
+  proc child -> case elName child of
+    "image"    -> read_frame_img      -< child
+    "object"   -> read_frame_mathml   -< child
+    "text-box" -> read_frame_text_box -< child
+    _          -> returnV mempty      -< ()
+
+read_frame_img :: ODTReaderSafe XML.Element (FirstMatch Inlines)
+read_frame_img =
+  proc img -> do
+    src <- executeIn (findAttr' NsXLink "href") -< img
+    case fold src of
+      ""   -> returnV mempty -< ()
+      src' -> do
+        let exts = extensionsFromList [Ext_auto_identifiers]
+            src'' = fixRelativeLink src'
+        resource   <- lookupResource                          -< T.unpack src''
+        _          <- updateMediaWithResource                 -< resource
+        w          <- findAttrText' NsSVG "width"             -< ()
+        h          <- findAttrText' NsSVG "height"            -< ()
+        titleNodes <- matchChildContent' [ read_frame_title ] -< ()
+        alt        <- matchChildContent [] read_plain_text    -< ()
+        arr (firstMatch . uncurry4 imageWith)                 -<
+          (image_attributes w h, src'', inlineListToIdentifier exts (toList titleNodes), alt)
+
+read_frame_title :: InlineMatcher
+read_frame_title = matchingElement NsSVG "title" (matchChildContent [] read_plain_text)
+
+image_attributes :: Maybe T.Text -> Maybe T.Text -> Attr
+image_attributes x y =
+  ( "", [], dim "width" x ++ dim "height" y)
+  where
+    dim _ (Just "")   = []
+    dim name (Just v) = [(name, v)]
+    dim _ Nothing     = []
+
+read_frame_mathml :: ODTReaderSafe XML.Element (FirstMatch Inlines)
+read_frame_mathml =
+  proc obj -> do
+    src <- executeIn (findAttr' NsXLink "href") -< obj
+    case fold src of
+      ""   -> returnV mempty -< ()
+      src' -> do
+        let path = T.unpack $
+                    fromMaybe src' (T.stripPrefix "./" src') <> "/content.xml"
+        (_, mathml) <- lookupResource -< path
+        case readMathML (UTF8.toText $ B.toStrict mathml) of
+          Left _     -> returnV mempty -< ()
+          Right exps -> arr (firstMatch . displayMath . writeTeX) -< exps
+
+read_frame_text_box :: ODTReaderSafe XML.Element (FirstMatch Inlines)
+read_frame_text_box = proc box -> do
+    paragraphs <- executeIn (matchSmushedChildBlocks' [ read_paragraph ]) -< box
+    arr read_img_with_caption -< toList paragraphs
+
+read_img_with_caption :: [Block] -> FirstMatch Inlines
+read_img_with_caption (Para [Image attr alt (src,title)] : _) =
+  firstMatch $ singleton (Image attr alt (src, "fig:" <> title))   -- no text, default caption
+read_img_with_caption (Para (Image attr _ (src,title) : txt) : _) =
+  firstMatch $ singleton (Image attr txt (src, "fig:" <> title) )  -- override caption with the text that follows
+read_img_with_caption  ( Para (_ : xs) : ys) =
+  read_img_with_caption (Para xs : ys)
+read_img_with_caption _ =
+  mempty
+
+----------------------
+-- Internal links
+----------------------
+
+_ANCHOR_PREFIX_ :: T.Text
+_ANCHOR_PREFIX_ = "anchor"
+
+--
+readAnchorAttr :: ODTReader a Anchor
+readAnchorAttr = findAttrText NsText "name"
+
+-- | Beware: may fail
+findAnchorName :: ODTReader AnchorPrefix Anchor
+findAnchorName = (      keepingTheValue readAnchorAttr
+                   >>^  spreadChoice
+                 ) >>?! getPrettyAnchor
+
+
+--
+maybeAddAnchorFrom :: ODTReader Inlines AnchorPrefix
+                   -> ODTReaderSafe Inlines Inlines
+maybeAddAnchorFrom anchorReader =
+  keepingTheValue (anchorReader >>? findAnchorName >>?^ toAnchorElem)
+  >>>
+  proc (inlines, fAnchorElem) -> do
+  case fAnchorElem of
+    Right anchorElem -> returnA -< anchorElem
+    Left _           -> returnA -< inlines
+  where
+    toAnchorElem :: Anchor -> Inlines
+    toAnchorElem anchorID = spanWith (anchorID, [], []) mempty
+                            -- no classes, no key-value pairs
+
+--
+read_bookmark     :: InlineMatcher
+read_bookmark      = matchingElement NsText "bookmark"
+                     $ maybeAddAnchorFrom (liftAsSuccess $ returnV _ANCHOR_PREFIX_)
+
+--
+read_bookmark_start :: InlineMatcher
+read_bookmark_start = matchingElement NsText "bookmark-start"
+                     $ maybeAddAnchorFrom (liftAsSuccess $ returnV _ANCHOR_PREFIX_)
+
+--
+read_reference_start :: InlineMatcher
+read_reference_start = matchingElement NsText "reference-mark-start"
+                     $ maybeAddAnchorFrom readAnchorAttr
+
+-- | Beware: may fail
+findAnchorRef :: ODTReader a Anchor
+findAnchorRef = (      findAttrText NsText "ref-name"
+                  >>?^ (_ANCHOR_PREFIX_,)
+                ) >>?! getPrettyAnchor
+
+
+--
+maybeInAnchorRef :: ODTReaderSafe Inlines Inlines
+maybeInAnchorRef = proc inlines -> do
+  fRef <- findAnchorRef -< ()
+  case fRef of
+    Right anchor ->
+      arr (toAnchorRef anchor) -<< inlines
+    Left _ -> returnA -< inlines
+  where
+    toAnchorRef :: Anchor -> Inlines -> Inlines
+    toAnchorRef anchor = link ("#" <> anchor) "" -- no title
+
+--
+read_bookmark_ref :: InlineMatcher
+read_bookmark_ref = matchingElement NsText "bookmark-ref"
+                    $    maybeInAnchorRef
+                     <<< matchChildContent [] read_plain_text
+
+--
+read_reference_ref :: InlineMatcher
+read_reference_ref = matchingElement NsText "reference-ref"
+                    $    maybeInAnchorRef
+                     <<< matchChildContent [] read_plain_text
+
+
+----------------------
+-- Entry point
+----------------------
+
+read_text :: ODTReaderSafe a Pandoc
+read_text = matchSmushedChildBlocks' [ read_header
+                                     , read_paragraph
+                                     , read_list
+                                     , read_section
+                                     , read_table
+                                     ]
+            >>^ doc
+
+post_process :: Pandoc -> Pandoc
+post_process (Pandoc m blocks) =
+  Pandoc m (post_process' blocks)
+
+post_process' :: [Block] -> [Block]
+post_process' (Table attr _ specs th tb tf : Div ("", ["caption"], _) blks : xs)
+  = Table attr (Caption Nothing blks) specs th tb tf : post_process' xs
+post_process' bs = bs
+
+read_body :: ODTReader a (Pandoc, MediaBag)
+read_body = executeInSub NsOffice "body"
+          $ executeInSub NsOffice "text"
+          $ liftAsSuccess
+          $ proc inlines -> do
+             txt   <- read_text     -< inlines
+             state <- getExtraState -< ()
+             returnA                -< (post_process txt, getMediaBag state)
diff --git a/src/Text/Pandoc/Readers/ODT/Generic/Fallible.hs b/src/Text/Pandoc/Readers/ODT/Generic/Fallible.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Readers/ODT/Generic/Fallible.hs
@@ -0,0 +1,113 @@
+{- |
+   Module      : Text.Pandoc.Readers.ODT.Generic.Fallible
+   Copyright   : Copyright (C) 2015 Martin Linnemann
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : Martin Linnemann <theCodingMarlin@googlemail.com>
+   Stability   : alpha
+   Portability : portable
+
+Data types and utilities representing failure. Most of it is based on the
+"Either" type in its usual configuration (left represents failure).
+
+In most cases, the failure type is implied or required to be a "Monoid".
+
+The choice of "Either" instead of a custom type makes it easier to write
+compatible instances of "ArrowChoice".
+-}
+
+-- We export everything
+module Text.Pandoc.Readers.ODT.Generic.Fallible
+  ( Failure
+  , Fallible
+  , maybeToEither
+  , eitherToMaybe
+  , recover
+  , failWith
+  , failEmpty
+  , succeedWith
+  , collapseEither
+  , chooseMax
+  , chooseMaxWith
+  , ChoiceVector(..)
+  , SuccessList(..)
+  ) where
+
+-- | Default for now. Will probably become a class at some point.
+type Failure = ()
+
+type Fallible a = Either Failure a
+
+
+--
+maybeToEither :: Maybe a -> Fallible a
+maybeToEither (Just a) = Right a
+maybeToEither Nothing  = Left  ()
+
+--
+eitherToMaybe :: Either _l a -> Maybe a
+eitherToMaybe (Left  _) = Nothing
+eitherToMaybe (Right a) = Just a
+
+-- | > recover a === either (const a) id
+recover :: a -> Either _f a -> a
+recover a (Left  _) = a
+recover _ (Right a) = a
+
+-- | I would love to use 'fail'. Alas, 'Monad.fail'...
+failWith :: failure -> Either failure _x
+failWith f = Left f
+
+--
+failEmpty :: (Monoid failure) => Either failure _x
+failEmpty = failWith mempty
+
+--
+succeedWith :: a -> Either _x a
+succeedWith = Right
+
+--
+collapseEither :: Either failure (Either failure x)
+               -> Either failure x
+collapseEither (Left f         ) = Left f
+collapseEither (Right (Left  f)) = Left f
+collapseEither (Right (Right x)) = Right x
+
+-- | If either of the values represents a  non-error, the result is a
+-- (possibly combined) non-error. If both values represent an error, an error
+-- is returned.
+chooseMax :: (Monoid a, Monoid b) => Either a b -> Either a b -> Either a b
+chooseMax = chooseMaxWith mappend
+
+-- | If either of the values represents a non-error, the result is a
+-- (possibly combined) non-error. If both values represent an error, an error
+-- is returned.
+chooseMaxWith :: (Monoid a) => (b -> b -> b)
+                            -> Either a b
+                            -> Either a b
+                            -> Either a b
+chooseMaxWith (><) (Right a) (Right b) = Right $ a >< b
+chooseMaxWith  _   (Left  a) (Left  b) = Left  $ a `mappend` b
+chooseMaxWith  _   (Right a)     _     = Right a
+chooseMaxWith  _       _     (Right b) = Right b
+
+
+-- | Class of containers that can escalate contained 'Either's.
+-- The word "Vector" is meant in the sense of a disease transmitter.
+class ChoiceVector v where
+  spreadChoice :: v (Either f a) -> Either f (v a)
+
+instance ChoiceVector ((,) a) where
+  spreadChoice (_, Left  f) = Left  f
+  spreadChoice (x, Right y) = Right (x,y)
+  -- Wasn't there a newtype somewhere with the elements flipped?
+
+-- | Wrapper for a list. While the normal list instance of 'ChoiceVector'
+-- fails whenever it can, this type will never fail.
+newtype SuccessList a = SuccessList { collectNonFailing :: [a] }
+  deriving ( Eq, Ord, Show )
+
+instance ChoiceVector SuccessList  where
+  spreadChoice = Right . SuccessList . foldr unTagRight [] . collectNonFailing
+    where unTagRight (Right x) = (x:)
+          unTagRight _         = id
diff --git a/src/Text/Pandoc/Readers/ODT/Generic/Namespaces.hs b/src/Text/Pandoc/Readers/ODT/Generic/Namespaces.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Readers/ODT/Generic/Namespaces.hs
@@ -0,0 +1,49 @@
+{- |
+   Module      : Text.Pandoc.Readers.ODT.Generic.Namespaces
+   Copyright   : Copyright (C) 2015 Martin Linnemann
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : Martin Linnemann <theCodingMarlin@googlemail.com>
+   Stability   : alpha
+   Portability : portable
+
+A class containing a set of namespace identifiers. Used to convert between
+typesafe Haskell namespace identifiers and unsafe "real world" namespaces.
+-}
+
+module Text.Pandoc.Readers.ODT.Generic.Namespaces
+  ( NameSpaceIRI
+  , NameSpaceIRIs
+  , NameSpaceID(..)
+  ) where
+
+import qualified Data.Map as M
+import Data.Text (Text)
+
+--
+type NameSpaceIRI          = Text
+
+--
+type NameSpaceIRIs     nsID = M.Map nsID NameSpaceIRI
+
+--
+class (Eq nsID, Ord nsID) => NameSpaceID nsID where
+
+  -- | Given a IRI, possibly update the map and return the id of the namespace.
+  -- May fail if the namespace is unknown and the application does not
+  -- allow unknown namespaces.
+  getNamespaceID   :: NameSpaceIRI
+                      -> NameSpaceIRIs nsID
+                      -> Maybe (NameSpaceIRIs nsID, nsID)
+  -- | Given a namespace id, lookup its IRI. May be overridden for performance.
+  getIRI           :: nsID
+                      -> NameSpaceIRIs nsID
+                      -> Maybe NameSpaceIRI
+  -- | The root element of an XML document has a namespace, too, and the
+  -- "XML.Light-parser" is eager to remove the corresponding namespace
+  -- attribute.
+  -- As a result, at least this root namespace must be provided.
+  getInitialIRImap :: NameSpaceIRIs nsID
+
+  getIRI           = M.lookup
+  getInitialIRImap = M.empty
diff --git a/src/Text/Pandoc/Readers/ODT/Generic/SetMap.hs b/src/Text/Pandoc/Readers/ODT/Generic/SetMap.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Readers/ODT/Generic/SetMap.hs
@@ -0,0 +1,36 @@
+{- |
+   Module      : Text.Pandoc.Readers.ODT.Generic.SetMap
+   Copyright   : Copyright (C) 2015 Martin Linnemann
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : Martin Linnemann <theCodingMarlin@googlemail.com>
+   Stability   : alpha
+   Portability : portable
+
+A map of values to sets of values.
+-}
+
+module Text.Pandoc.Readers.ODT.Generic.SetMap
+  ( SetMap
+  , empty
+  , fromList
+  , insert
+  , union3
+  ) where
+
+import qualified Data.Map as M
+import qualified Data.Set as S
+
+type SetMap k v = M.Map k (S.Set v)
+
+empty :: SetMap k v
+empty = M.empty
+
+fromList :: (Ord k, Ord v) => [(k,v)] -> SetMap k v
+fromList = foldr (uncurry insert) empty
+
+insert :: (Ord k, Ord v) => k -> v -> SetMap k v -> SetMap k v
+insert key value setMap = M.insertWith S.union key (S.singleton value) setMap
+
+union3 :: (Ord k) => SetMap k v -> SetMap k v -> SetMap k v -> SetMap k v
+union3 sm1 sm2 sm3 = sm1 `M.union` sm2 `M.union` sm3
diff --git a/src/Text/Pandoc/Readers/ODT/Generic/Utils.hs b/src/Text/Pandoc/Readers/ODT/Generic/Utils.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Readers/ODT/Generic/Utils.hs
@@ -0,0 +1,116 @@
+{-# LANGUAGE ViewPatterns  #-}
+{- |
+   Module      : Text.Pandoc.Reader.ODT.Generic.Utils
+   Copyright   : Copyright (C) 2015 Martin Linnemann
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : Martin Linnemann <theCodingMarlin@googlemail.com>
+   Stability   : alpha
+   Portability : portable
+
+General utility functions for the odt reader.
+-}
+
+module Text.Pandoc.Readers.ODT.Generic.Utils
+( uncurry3
+, uncurry4
+, uncurry5
+, uncurry6
+, swap
+, reverseComposition
+, tryToRead
+, Lookupable(..)
+, readLookupable
+, readPercent
+, findBy
+, swing
+, composition
+) where
+
+import Control.Category (Category, (<<<), (>>>))
+import qualified Control.Category as Cat (id)
+import Data.Char (isSpace)
+import qualified Data.Foldable as F (Foldable, foldr)
+import Data.Maybe
+import Data.Text (Text)
+import qualified Data.Text as T
+
+-- | Equivalent to
+-- > foldr (.) id
+-- where '(.)' are 'id' are the ones from "Control.Category"
+-- and 'foldr' is the one from "Data.Foldable".
+-- The noun-form was chosen to be consistent with 'sum', 'product' etc
+-- based on the discussion at
+-- <https://groups.google.com/forum/#!topic/haskell-cafe/VkOZM1zaHOI>
+-- (that I was not part of)
+composition        :: (Category cat, F.Foldable f) => f (cat a a) -> cat a a
+composition        = F.foldr (<<<) Cat.id
+
+-- | Equivalent to
+-- > foldr (flip (.)) id
+-- where '(.)' are 'id' are the ones from "Control.Category"
+-- and 'foldr' is the one from "Data.Foldable".
+-- A reversed version of 'composition'.
+reverseComposition :: (Category cat, F.Foldable f) => f (cat a a) -> cat a a
+reverseComposition = F.foldr (>>>) Cat.id
+
+-- | This function often makes it possible to switch values with the functions
+-- that are applied to them.
+--
+-- Examples:
+-- > swing map :: [a -> b] -> a -> [b]
+-- > swing any :: [a -> Bool] -> a -> Bool
+-- > swing foldr :: b -> a -> [a -> b -> b] -> b
+-- > swing scanr :: c -> a -> [a -> c -> c] -> c
+-- > swing zipWith :: [a -> b -> c] -> a -> [b] -> [c]
+-- > swing find :: [a -> Bool] -> a -> Maybe (a -> Bool)
+--
+-- Stolen from <https://wiki.haskell.org/Pointfree>
+swing :: (((a -> b) -> b) -> c -> d) -> c -> a -> d
+swing = flip.(.flip id)
+-- swing f c a = f ($ a) c
+
+
+-- | Alternative to 'read'/'reads'. The former of these throws errors
+-- (nobody wants that) while the latter returns "to much" for simple purposes.
+-- This function instead applies 'reads' and returns the first match (if any)
+-- in a 'Maybe'.
+tryToRead :: (Read r) => Text -> Maybe r
+tryToRead = (reads . T.unpack) >>> listToMaybe >>> fmap fst
+
+-- | A version of 'reads' that requires a '%' sign after the number
+readPercent :: ReadS Int
+readPercent s = [ (i,s') | (i   , r ) <- reads s
+                         , ("%" , s') <- lex   r
+              ]
+
+-- | Data that can be looked up.
+-- This is mostly a utility to read data with kind *.
+class Lookupable a where
+  lookupTable :: [(Text, a)]
+
+-- | Very similar to a simple 'lookup' in the 'lookupTable', but with a lexer.
+readLookupable :: (Lookupable a) => Text -> Maybe a
+readLookupable s =
+  lookup (T.takeWhile (not . isSpace) $ T.dropWhile isSpace s) lookupTable
+
+uncurry3 :: (a->b->c                -> z) -> (a,b,c          ) -> z
+uncurry4 :: (a->b->c->d             -> z) -> (a,b,c,d        ) -> z
+uncurry5 :: (a->b->c->d->e          -> z) -> (a,b,c,d,e      ) -> z
+uncurry6 :: (a->b->c->d->e->f       -> z) -> (a,b,c,d,e,f    ) -> z
+
+uncurry3 fun (a,b,c          ) = fun a b c
+uncurry4 fun (a,b,c,d        ) = fun a b c d
+uncurry5 fun (a,b,c,d,e      ) = fun a b c d e
+uncurry6 fun (a,b,c,d,e,f    ) = fun a b c d e f
+
+swap :: (a,b) -> (b,a)
+swap (a,b) = (b,a)
+
+-- | A version of "Data.List.find" that uses a converter to a Maybe instance.
+-- The returned value is the first which the converter returns in a 'Just'
+-- wrapper.
+findBy :: (a -> Maybe b) -> [a] -> Maybe b
+findBy _               []   = Nothing
+findBy f ((f -> Just x):_ ) = Just x
+findBy f (            _:xs) = findBy f xs
diff --git a/src/Text/Pandoc/Readers/ODT/Generic/XMLConverter.hs b/src/Text/Pandoc/Readers/ODT/Generic/XMLConverter.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Readers/ODT/Generic/XMLConverter.hs
@@ -0,0 +1,781 @@
+{-# LANGUAGE OverloadedStrings #-}
+{-# LANGUAGE TupleSections   #-}
+{-# LANGUAGE GADTs           #-}
+{-# LANGUAGE LambdaCase      #-}
+{-# LANGUAGE PatternGuards   #-}
+{- |
+   Module      : Text.Pandoc.Readers.ODT.Generic.XMLConverter
+   Copyright   : Copyright (C) 2015 Martin Linnemann
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : Martin Linnemann <theCodingMarlin@googlemail.com>
+   Stability   : alpha
+   Portability : portable
+
+A generalized XML parser based on stateful arrows.
+It might be sufficient to define this reader as a comonad, but there is
+not a lot of use in trying.
+-}
+
+module Text.Pandoc.Readers.ODT.Generic.XMLConverter
+( ElementName
+, XMLConverterState
+, XMLConverter
+, FallibleXMLConverter
+, runConverter'
+, getExtraState
+, setExtraState
+, modifyExtraState
+, producingExtraState
+, findChild'
+, filterChildrenName'
+, isSet'
+, isSetWithDefault
+, elName
+, searchAttr
+, lookupAttr
+, lookupAttr'
+, lookupDefaultingAttr
+, findAttr'
+, findAttrText'
+, findAttr
+, findAttrText
+, findAttrTextWithDefault
+, readAttr
+, readAttr'
+, readAttrWithDefault
+, getAttr
+, executeIn
+, executeInSub
+, withEveryL
+, tryAll
+, matchContent'
+, matchContent
+) where
+
+import           Prelude hiding (Applicative(..))
+import           Control.Applicative  hiding ( liftA, liftA2 )
+import           Control.Monad               ( MonadPlus )
+import           Control.Arrow
+
+import           Data.Bool ( bool )
+import           Data.Either ( rights )
+import qualified Data.Map             as M
+import           Data.Text (Text)
+import           Data.Default
+import           Data.Maybe
+import qualified Data.List as L
+import qualified Data.List.NonEmpty as NonEmpty
+import           Data.List.NonEmpty (NonEmpty(..))
+
+import qualified Text.Pandoc.XML.Light as XML
+
+import           Text.Pandoc.Readers.ODT.Arrows.State
+import           Text.Pandoc.Readers.ODT.Arrows.Utils
+import           Text.Pandoc.Readers.ODT.Generic.Namespaces
+import           Text.Pandoc.Readers.ODT.Generic.Utils
+import           Text.Pandoc.Readers.ODT.Generic.Fallible
+
+--------------------------------------------------------------------------------
+--  Basis types for readability
+--------------------------------------------------------------------------------
+
+--
+type ElementName           = Text
+type AttributeName         = Text
+type AttributeValue        = Text
+type TextAttributeValue    = Text
+
+--
+type NameSpacePrefix       = Text
+
+--
+type NameSpacePrefixes nsID = M.Map nsID NameSpacePrefix
+
+--------------------------------------------------------------------------------
+-- Main converter state
+--------------------------------------------------------------------------------
+
+-- GADT so some of the NameSpaceID restrictions can be deduced
+data XMLConverterState nsID extraState where
+  XMLConverterState :: NameSpaceID nsID
+    => { -- | A stack of parent elements. The top element is the current one.
+         -- Arguably, a real Zipper would be better. But that is an
+         -- optimization that can be made at a later time, e.g. when
+         -- replacing Text.XML.Light.
+         parentElements    :: NonEmpty XML.Element
+         -- | A map from internal namespace IDs to the namespace prefixes
+         -- used in XML elements
+       , namespacePrefixes :: NameSpacePrefixes nsID
+         -- | A map from internal namespace IDs to namespace IRIs
+         -- (Only necessary for matching namespace IDs and prefixes)
+       , namespaceIRIs     :: NameSpaceIRIs nsID
+         -- | A place to put "something else". This feature is used heavily
+         -- to keep the main code cleaner. More specifically, the main reader
+         -- is divided into different stages. Each stage lifts something up
+         -- here, which the next stage can then use. This could of course be
+         -- generalized to a state-tree or used for the namespace IRIs. The
+         -- border between states and values is an imaginary one, after all.
+         -- But the separation as it is seems to be enough for now.
+       , moreState         :: extraState
+       }
+    -> XMLConverterState nsID extraState
+
+--
+createStartState :: (NameSpaceID nsID)
+                    => XML.Element
+                    -> extraState
+                    -> XMLConverterState nsID extraState
+createStartState element extraState =
+  XMLConverterState
+       { parentElements    = element :| []
+       , namespacePrefixes = M.empty
+       , namespaceIRIs     = getInitialIRImap
+       , moreState         = extraState
+       }
+
+-- | Functor over extra state
+instance Functor (XMLConverterState nsID) where
+  fmap f ( XMLConverterState parents prefixes iRIs    extraState  )
+       =   XMLConverterState parents prefixes iRIs (f extraState)
+
+--
+replaceExtraState   :: extraState
+                    -> XMLConverterState nsID _x
+                    -> XMLConverterState nsID extraState
+replaceExtraState x s
+                     = fmap (const x) s
+
+--
+currentElement      :: XMLConverterState nsID extraState
+                    -> XML.Element
+currentElement state = NonEmpty.head (parentElements state)
+
+-- | Replace the current position by another, modifying the extra state
+-- in the process
+swapStack'          :: XMLConverterState nsID extraState
+                    -> NonEmpty XML.Element
+                    -> ( XMLConverterState nsID extraState
+                       , NonEmpty XML.Element )
+swapStack' state stack
+                     = ( state { parentElements = stack }
+                       , parentElements state
+                       )
+
+--
+pushElement         :: XML.Element
+                    -> XMLConverterState nsID extraState
+                    -> XMLConverterState nsID extraState
+pushElement e state  = state { parentElements =
+                                 NonEmpty.cons e (parentElements state) }
+
+-- | Pop the top element from the call stack, unless it is the last one.
+popElement          :: XMLConverterState nsID extraState
+                    -> Maybe (XMLConverterState nsID extraState)
+popElement state
+  | _ :| (e:es) <- parentElements state
+                = Just $ state { parentElements = e :| es }
+  | otherwise   = Nothing
+
+--------------------------------------------------------------------------------
+-- Main type
+--------------------------------------------------------------------------------
+
+-- It might be a good idea to pack the converters in a GADT
+-- Downside: data instead of type
+-- Upside: 'Failure' could be made a parameter as well.
+
+--
+type XMLConverter nsID extraState input output
+      = ArrowState (XMLConverterState nsID extraState ) input output
+
+type FallibleXMLConverter nsID extraState input output
+     = XMLConverter nsID extraState input (Fallible output)
+
+--
+runConverter     :: XMLConverter nsID extraState input output
+                 -> XMLConverterState nsID extraState
+                 -> input
+                 -> output
+runConverter converter state input = snd $ runArrowState converter (state,input)
+
+runConverter' :: (NameSpaceID nsID)
+              => FallibleXMLConverter nsID extraState () success
+              -> extraState
+              -> XML.Element
+              -> Fallible success
+runConverter' converter extraState element = runConverter (readNSattributes >>? converter) (createStartState element extraState) ()
+
+--
+getCurrentElement :: XMLConverter nsID extraState x XML.Element
+getCurrentElement  = extractFromState currentElement
+
+--
+getExtraState     :: XMLConverter nsID extraState x extraState
+getExtraState      = extractFromState moreState
+
+--
+setExtraState     :: XMLConverter nsID extraState extraState extraState
+setExtraState      = withState $ \state extra
+                                  -> (replaceExtraState extra state , extra)
+
+
+-- | Lifts a function to the extra state.
+modifyExtraState  :: (extraState -> extraState)
+                  -> XMLConverter nsID extraState x x
+modifyExtraState   = modifyState.fmap
+
+
+-- | First sets the extra state to the new value. Then modifies the original
+-- extra state with a converter that uses the new state. Finally, the
+-- intermediate state is dropped and the extra state is lifted into the
+-- state as it was at the beginning of the function.
+-- As a result, exactly the extra state and nothing else is changed.
+-- The resulting converter even behaves like an identity converter on the
+-- value level.
+--
+-- (The -ing form is meant to be mnemonic in a sequence of arrows as in
+--  convertingExtraState () converter >>> doOtherStuff)
+--
+convertingExtraState :: extraState'
+                     -> FallibleXMLConverter nsID extraState' extraState extraState
+                     -> FallibleXMLConverter nsID extraState x x
+convertingExtraState v a = withSubStateF setVAsExtraState modifyWithA
+  where
+    setVAsExtraState     = liftAsSuccess $ extractFromState id >>^ replaceExtraState v
+    modifyWithA          = keepingTheValue (moreState ^>> a)
+                           >>^ spreadChoice >>?% flip replaceExtraState
+
+-- | First sets the extra state to the new value. Then produces a new
+-- extra state with a converter that uses the new state. Finally, the
+-- intermediate state is dropped and the extra state is lifted into the
+-- state as it was at the beginning of the function.
+-- As a result, exactly the extra state and nothing else is changed.
+-- The resulting converter even behaves like an identity converter on the
+-- value level.
+--
+-- Equivalent to
+--
+-- > \v x a -> convertingExtraState v (returnV x >>> a)
+--
+-- (The -ing form is meant to be mnemonic in a sequence of arrows as in
+--  producingExtraState () () producer >>> doOtherStuff)
+--
+producingExtraState  :: extraState'
+                     -> a
+                     -> FallibleXMLConverter nsID extraState' a extraState
+                     -> FallibleXMLConverter nsID extraState x x
+producingExtraState v x a = convertingExtraState v (returnV x >>> a)
+
+
+--------------------------------------------------------------------------------
+-- Work in namespaces
+--------------------------------------------------------------------------------
+
+-- | Arrow version of 'getIRI'
+lookupNSiri             :: (NameSpaceID nsID)
+                        => nsID
+                        -> XMLConverter nsID extraState x (Maybe NameSpaceIRI)
+lookupNSiri nsID        = extractFromState
+                          $ \state -> getIRI nsID $ namespaceIRIs state
+
+--
+lookupNSprefix           :: (NameSpaceID nsID)
+                         => nsID
+                         -> XMLConverter nsID extraState x (Maybe NameSpacePrefix)
+lookupNSprefix nsID      = extractFromState
+                           $ \state -> M.lookup nsID $ namespacePrefixes state
+
+-- | Extracts namespace attributes from the current element and tries to
+-- update the current mapping accordingly
+readNSattributes         :: (NameSpaceID nsID)
+                         => FallibleXMLConverter nsID extraState x ()
+readNSattributes         = fromState $ \state -> maybe (state, failEmpty     )
+                                                       (     , succeedWith ())
+                                                       (extractNSAttrs state )
+  where
+    extractNSAttrs       :: (NameSpaceID nsID)
+                         => XMLConverterState nsID extraState
+                         -> Maybe (XMLConverterState nsID extraState)
+    extractNSAttrs startState
+                         = L.foldl' (\state d -> state >>= addNS d)
+                                 (Just startState)
+                                 nsAttribs
+      where nsAttribs    = mapMaybe readNSattr (XML.elAttribs element)
+            element      = currentElement startState
+            readNSattr (XML.Attr (XML.QName name _ (Just "xmlns")) iri)
+                         = Just (name, iri)
+            readNSattr _ = Nothing
+    addNS  (prefix, iri) state = fmap updateState
+                                 $ getNamespaceID iri
+                                 $ namespaceIRIs state
+      where updateState (iris,nsID)
+                         = state { namespaceIRIs     = iris
+                                 , namespacePrefixes = M.insert nsID prefix
+                                                       $ namespacePrefixes state
+                                 }
+
+--------------------------------------------------------------------------------
+-- Common namespace accessors
+--------------------------------------------------------------------------------
+
+-- | Given a namespace id and an element name, creates a 'XML.QName' for
+-- internal use
+qualifyName              :: (NameSpaceID nsID)
+                         => nsID -> ElementName
+                         -> XMLConverter nsID extraState x XML.QName
+qualifyName nsID name    =         lookupNSiri nsID
+                               &&& lookupNSprefix nsID
+                           >>% XML.QName name
+
+-- | Checks if a given element matches both a specified namespace id
+-- and a predicate
+elemNameMatches          :: (NameSpaceID nsID)
+                         => nsID -> (ElementName -> Bool)
+                         -> XMLConverter nsID extraState XML.Element Bool
+elemNameMatches nsID f    = keepingTheValue (lookupNSiri nsID) >>% hasMatchingName
+  where hasMatchingName e iri = let name = XML.elName e
+                                in     f (XML.qName name)
+                                    && XML.qURI name == iri
+
+-- | Checks if a given element matches both a specified namespace id
+-- and a specified element name
+elemNameIs               :: (NameSpaceID nsID)
+                         => nsID -> ElementName
+                         -> XMLConverter nsID extraState XML.Element Bool
+elemNameIs nsID name     = elemNameMatches nsID (== name)
+
+--------------------------------------------------------------------------------
+-- General content
+--------------------------------------------------------------------------------
+
+elName :: XML.Element -> ElementName
+elName = XML.qName . XML.elName
+
+--
+elContent               :: XMLConverter nsID extraState x [XML.Content]
+elContent               =     getCurrentElement
+                           >>^ XML.elContent
+
+--------------------------------------------------------------------------------
+-- Children
+--------------------------------------------------------------------------------
+
+--
+--
+findChildren             :: (NameSpaceID nsID)
+                         => nsID -> ElementName
+                         -> XMLConverter nsID extraState x [XML.Element]
+findChildren nsID name   =         qualifyName nsID name
+                               &&& getCurrentElement
+                           >>% XML.findChildren
+
+--
+findChild'              :: (NameSpaceID nsID)
+                        => nsID
+                        -> ElementName
+                        -> XMLConverter nsID extraState x (Maybe XML.Element)
+findChild' nsID name    =         qualifyName nsID name
+                              &&& getCurrentElement
+                          >>% XML.findChild
+
+--
+findChild              :: (NameSpaceID nsID)
+                       => nsID -> ElementName
+                       -> FallibleXMLConverter nsID extraState x XML.Element
+findChild nsID name    =     findChild' nsID name
+                         >>> maybeToChoice
+
+filterChildrenName'        :: (NameSpaceID nsID)
+                           => nsID
+                           -> (ElementName -> Bool)
+                           -> XMLConverter nsID extraState x [XML.Element]
+filterChildrenName' nsID f =     getCurrentElement
+                             >>> arr XML.elChildren
+                             >>> iterateS (keepingTheValue (elemNameMatches nsID f))
+                             >>> arr (map fst . filter snd)
+
+--------------------------------------------------------------------------------
+-- Attributes
+--------------------------------------------------------------------------------
+
+--
+isSet'                   :: (NameSpaceID nsID)
+                         => nsID -> AttributeName
+                         -> XMLConverter nsID extraState x (Maybe Bool)
+isSet' nsID attrName     =     findAttr' nsID attrName
+                           >>^ (>>= stringToBool')
+
+isSetWithDefault         :: (NameSpaceID nsID)
+                         => nsID -> AttributeName
+                         -> Bool
+                         -> XMLConverter nsID extraState x Bool
+isSetWithDefault nsID attrName def'
+                         =     isSet' nsID attrName
+                           >>^ fromMaybe def'
+
+-- | Lookup value in a dictionary, fail if no attribute found or value
+-- not in dictionary
+searchAttrIn             :: (NameSpaceID nsID)
+                         => nsID -> AttributeName
+                         -> [(AttributeValue,a)]
+                         -> FallibleXMLConverter nsID extraState x a
+searchAttrIn nsID attrName dict
+                         =       findAttr nsID attrName
+                           >>?^? maybeToChoice.(`lookup` dict )
+
+-- | Lookup value in a dictionary. If attribute or value not found,
+-- return default value
+searchAttr               :: (NameSpaceID nsID)
+                         => nsID -> AttributeName
+                         -> a
+                         -> [(AttributeValue,a)]
+                         -> XMLConverter nsID extraState x a
+searchAttr nsID attrName defV dict
+                         =     searchAttrIn nsID attrName dict
+                           >>> const defV ^|||^ id
+
+-- | Read a 'Lookupable' attribute. Fail if no match.
+lookupAttr               :: (NameSpaceID nsID, Lookupable a)
+                         => nsID -> AttributeName
+                         -> FallibleXMLConverter nsID extraState x a
+lookupAttr nsID attrName =     lookupAttr' nsID attrName
+                           >>^ maybeToChoice
+
+
+-- | Read a 'Lookupable' attribute. Return the result as a 'Maybe'.
+lookupAttr'              :: (NameSpaceID nsID, Lookupable a)
+                         => nsID -> AttributeName
+                         -> XMLConverter nsID extraState x (Maybe a)
+lookupAttr' nsID attrName
+                         =     findAttr' nsID attrName
+                           >>^ (>>= readLookupable)
+
+-- | Read a 'Lookupable' attribute with explicit default
+lookupAttrWithDefault    :: (NameSpaceID nsID, Lookupable a)
+                         => nsID -> AttributeName
+                         -> a
+                         -> XMLConverter nsID extraState x a
+lookupAttrWithDefault nsID attrName deflt
+                         =     lookupAttr' nsID attrName
+                           >>^ fromMaybe deflt
+
+-- | Read a 'Lookupable' attribute with implicit default
+lookupDefaultingAttr     :: (NameSpaceID nsID, Lookupable a, Default a)
+                         => nsID -> AttributeName
+                         -> XMLConverter nsID extraState x a
+lookupDefaultingAttr nsID attrName
+                         = lookupAttrWithDefault nsID attrName def
+
+-- | Return value as a (Maybe Text)
+findAttr'               :: (NameSpaceID nsID)
+                        => nsID -> AttributeName
+                        -> XMLConverter nsID extraState x (Maybe AttributeValue)
+findAttr' nsID attrName =         qualifyName nsID attrName
+                              &&& getCurrentElement
+                          >>% XML.findAttr
+
+-- | Return value as a (Maybe Text)
+findAttrText'           :: (NameSpaceID nsID)
+                        => nsID -> AttributeName
+                        -> XMLConverter nsID extraState x (Maybe TextAttributeValue)
+findAttrText' nsID attrName
+                        =         qualifyName nsID attrName
+                              &&& getCurrentElement
+                          >>% XML.findAttr
+
+-- | Return value as string or fail
+findAttr               :: (NameSpaceID nsID)
+                       => nsID -> AttributeName
+                       -> FallibleXMLConverter nsID extraState x AttributeValue
+findAttr nsID attrName =     findAttr' nsID attrName
+                         >>> maybeToChoice
+
+-- | Return value as text or fail
+findAttrText           :: (NameSpaceID nsID)
+                       => nsID -> AttributeName
+                       -> FallibleXMLConverter nsID extraState x TextAttributeValue
+findAttrText nsID attrName
+                       = findAttr' nsID attrName
+                         >>> maybeToChoice
+
+-- | Return value as string or return provided default value
+findAttrTextWithDefault :: (NameSpaceID nsID)
+                        => nsID -> AttributeName
+                        -> TextAttributeValue
+                        -> XMLConverter nsID extraState x TextAttributeValue
+findAttrTextWithDefault nsID attrName deflt
+                       = findAttr' nsID attrName
+                         >>^ fromMaybe deflt
+
+-- | Read and return value or fail
+readAttr               :: (NameSpaceID nsID, Read attrValue)
+                       => nsID -> AttributeName
+                       -> FallibleXMLConverter nsID extraState x attrValue
+readAttr nsID attrName =     readAttr' nsID attrName
+                         >>> maybeToChoice
+
+-- | Read and return value or return Nothing
+readAttr'              :: (NameSpaceID nsID, Read attrValue)
+                       => nsID -> AttributeName
+                       -> XMLConverter nsID extraState x (Maybe attrValue)
+readAttr' nsID attrName =     findAttr' nsID attrName
+                          >>^ (>>= tryToRead)
+
+-- | Read and return value or return provided default value
+readAttrWithDefault    :: (NameSpaceID nsID, Read attrValue)
+                       => nsID -> AttributeName
+                       -> attrValue
+                       -> XMLConverter nsID extraState x attrValue
+readAttrWithDefault nsID attrName deflt
+                       =     findAttr' nsID attrName
+                         >>^ (>>= tryToRead)
+                         >>^ fromMaybe deflt
+
+-- | Read and return value or return default value from 'Default' instance
+getAttr                :: (NameSpaceID nsID, Read attrValue, Default attrValue)
+                       => nsID -> AttributeName
+                       -> XMLConverter nsID extraState x attrValue
+getAttr nsID attrName  = readAttrWithDefault nsID attrName def
+
+--------------------------------------------------------------------------------
+-- Movements
+--------------------------------------------------------------------------------
+
+--
+jumpThere              :: XMLConverter nsID extraState XML.Element XML.Element
+jumpThere              = withState (\state element
+                                     -> ( pushElement element state , element )
+                                   )
+
+--
+swapStack             :: XMLConverter nsID extraState (NonEmpty XML.Element)
+                                                      (NonEmpty XML.Element)
+swapStack             = withState swapStack'
+
+--
+jumpBack               :: FallibleXMLConverter nsID extraState _x _x
+jumpBack               = tryModifyState (popElement >>> maybeToChoice)
+
+-- | Support function for "procedural" converters: jump to an element, execute
+-- a converter, jump back.
+-- This version is safer than 'executeThere', because it does not rely on the
+-- internal stack. As a result, the converter can not move around in arbitrary
+-- ways. The downside is of course that some of the environment is not
+-- accessible to the converter.
+switchingTheStack      :: XMLConverter nsID moreState a b
+                       -> XMLConverter nsID moreState (a, XML.Element) b
+switchingTheStack a    =     second ( (:| []) ^>> swapStack )
+                         >>> first  a
+                         >>> second swapStack
+                         >>^ fst
+
+-- | Support function for "procedural" converters: jumps to an element, executes
+-- a converter, jumps back.
+-- Make sure that the converter is well-behaved; that is it should
+-- return to the exact position it started from in /every possible path/ of
+-- execution, even if it "fails". If it does not, you may encounter
+-- strange bugs. If you are not sure about the behaviour or want to use
+-- shortcuts, you can often use 'switchingTheStack' instead.
+executeThere           :: FallibleXMLConverter nsID moreState a b
+                       -> FallibleXMLConverter nsID moreState (a, XML.Element) b
+executeThere a         =      second jumpThere
+                          >>> fst
+                          ^>> a
+                          >>> jumpBack -- >>? jumpBack  would not ensure the jump.
+                          >>^ collapseEither
+
+
+-- | Do something in a specific element, then come back
+executeIn   :: XMLConverter nsID extraState XML.Element s
+            -> XMLConverter nsID extraState XML.Element s
+executeIn a = duplicate >>> switchingTheStack a
+
+-- | Do something in a sub-element, then come back
+executeInSub              :: (NameSpaceID nsID)
+                          => nsID -> ElementName
+                          -> FallibleXMLConverter nsID extraState f s
+                          -> FallibleXMLConverter nsID extraState f s
+executeInSub nsID name a  =     keepingTheValue
+                                  (findChild nsID name)
+                            >>> ignoringState liftFailure
+                            >>? switchingTheStack a
+  where liftFailure (_, Left  f) = Left  f
+        liftFailure (x, Right e) = Right (x, e)
+
+--------------------------------------------------------------------------------
+-- Iterating over children
+--------------------------------------------------------------------------------
+
+-- Helper converter to prepare different types of iterations.
+-- It lifts the children (of a certain type) of the current element
+-- into the value level and pairs each one with the current input value.
+prepareIteration       :: (NameSpaceID nsID)
+                       => nsID -> ElementName
+                       -> XMLConverter nsID extraState b [(b, XML.Element)]
+prepareIteration nsID name =     keepingTheValue
+                                   (findChildren nsID name)
+                             >>% distributeValue
+
+--
+withEveryL             :: (NameSpaceID nsID)
+                       => nsID -> ElementName
+                       -> FallibleXMLConverter nsID extraState a  b
+                       -> FallibleXMLConverter nsID extraState a [b]
+withEveryL = withEvery
+
+-- | Applies a converter to every child element of a specific type.
+-- Collects results in a 'MonadPlus'.
+-- Fails completely if any conversion fails.
+withEvery              :: (NameSpaceID nsID, MonadPlus m)
+                       => nsID -> ElementName
+                       -> FallibleXMLConverter nsID extraState a    b
+                       -> FallibleXMLConverter nsID extraState a (m b)
+withEvery nsID name a      =     prepareIteration nsID name
+                             >>> iterateS' (switchingTheStack a)
+
+-- | Applies a converter to every child element of a specific type.
+-- Collects all successful results in a list.
+tryAll                 :: (NameSpaceID nsID)
+                       => nsID -> ElementName
+                       -> FallibleXMLConverter nsID extraState b  a
+                       ->         XMLConverter nsID extraState b [a]
+tryAll nsID name a         =     prepareIteration nsID name
+                             >>> iterateS (switchingTheStack a)
+                             >>^ rights
+
+--------------------------------------------------------------------------------
+-- Matching children
+--------------------------------------------------------------------------------
+
+type IdXMLConverter nsID moreState x
+   = XMLConverter   nsID moreState x x
+
+type MaybeCConverter nsID moreState x
+   = Maybe (IdXMLConverter nsID moreState (x, XML.Content))
+
+-- Chainable converter that helps deciding which converter to actually use.
+type ContentMatchConverter nsID extraState x
+   = IdXMLConverter  nsID
+                     extraState
+                     (MaybeCConverter nsID extraState x, XML.Content)
+
+-- Helper function: The @c@ is actually a converter that is to be selected by
+-- matching XML content to the first two parameters.
+-- The fold used to match elements however is very simple, so to use it,
+-- this function wraps the converter in another converter that unifies
+-- the accumulator. Think of a lot of converters with the resulting type
+-- chained together. The accumulator not only transports the element
+-- unchanged to the next matcher, it also does the actual selecting by
+-- combining the intermediate results with '(<|>)'.
+makeMatcherC           :: (NameSpaceID nsID)
+                       => nsID -> ElementName
+                       -> FallibleXMLConverter  nsID extraState a a
+                       -> ContentMatchConverter nsID extraState a
+makeMatcherC nsID name c = (    second (    contentToElem
+                                         >>> returnV Nothing
+                                         ||| (    elemNameIs nsID name
+                                              >>^ bool Nothing (Just cWithJump)
+                                             )
+                                        )
+                             >>% (<|>)
+                           ) &&&^ snd
+  where cWithJump =      ( fst
+                           ^&&& (      second contentToElem
+                                  >>>  spreadChoice
+                                  ^>>? executeThere c
+                                )
+                            >>% recover)
+                    &&&^ snd
+        contentToElem :: FallibleXMLConverter nsID extraState XML.Content XML.Element
+        contentToElem = arr $ \case
+                                     XML.Elem e' -> succeedWith e'
+                                     _           -> failEmpty
+
+-- Creates and chains a bunch of matchers
+prepareMatchersC      :: (NameSpaceID nsID)
+                       => [(nsID, ElementName, FallibleXMLConverter nsID extraState x x)]
+                       -> ContentMatchConverter nsID extraState x
+--prepareMatchersC      = foldSs . (map $ uncurry3  makeMatcherC)
+prepareMatchersC      = reverseComposition . map (uncurry3  makeMatcherC)
+
+-- | Takes a list of element-data - converter groups and
+-- * Finds all content of the current element
+-- * Matches each group to each piece of content in order
+--   (at most one group per piece of content)
+-- * Filters non-matched content
+-- * Chains all found converters in content-order
+-- * Applies the chain to the input element
+matchContent'           :: (NameSpaceID nsID)
+                       => [(nsID, ElementName, FallibleXMLConverter nsID extraState a a)]
+                       -> XMLConverter nsID extraState a a
+matchContent' lookups   = matchContent lookups (arr fst)
+
+-- | Takes a list of element-data - converter groups and
+-- * Finds all content of the current element
+-- * Matches each group to each piece of content in order
+--   (at most one group per piece of content)
+-- * Adds a default converter for all non-matched content
+-- * Chains all found converters in content-order
+-- * Applies the chain to the input element
+matchContent          :: (NameSpaceID nsID)
+                       => [(nsID, ElementName, FallibleXMLConverter nsID extraState a a)]
+                       -> XMLConverter nsID extraState (a,XML.Content) a
+                       -> XMLConverter nsID extraState a a
+matchContent lookups fallback
+                        = let matcher = prepareMatchersC lookups
+                          in  keepingTheValue (
+                                   elContent
+                               >>> map (Nothing,)
+                               ^>> iterateSL matcher
+                               >>^ map swallowOrFallback
+                              -- >>> foldSs
+                               >>> reverseComposition
+                             )
+                         >>> swap
+                         ^>> app
+  where
+        -- let the converter swallow the content and drop the content
+        -- in the return value
+        swallowOrFallback (Just converter,content) = (,content) ^>> converter >>^ fst
+        swallowOrFallback (Nothing       ,content) = (,content) ^>> fallback
+
+--------------------------------------------------------------------------------
+-- Internals
+--------------------------------------------------------------------------------
+
+stringToBool' :: Text -> Maybe Bool
+stringToBool' val | val `elem` trueValues  = Just True
+                  | val `elem` falseValues = Just False
+                  | otherwise              = Nothing
+  where trueValues  = ["true" ,"on" ,"1"]
+        falseValues = ["false","off","0"]
+
+
+distributeValue ::  a -> [b] -> [(a,b)]
+distributeValue = map.(,)
+
+--------------------------------------------------------------------------------
+
+{-
+NOTES
+It might be a good idea to refactor the namespace stuff.
+E.g.: if a namespace constructor took a string as a parameter, things like
+> a ?>/< (NsText,"body")
+would be nicer.
+Together with a rename and some trickery, something like
+> |< NsText "body" >< NsText "p" ?> a </> </>|
+might even be possible.
+
+Some day, XML.Light should be replaced by something better.
+While doing that, it might be useful to replace String as the type of element
+names with something else, too. (Of course with OverloadedStrings).
+While doing that, maybe the types can be created in a way that something like
+> NsText:"body"
+could be used. Overloading (:) does not sounds like the best idea, but if the
+element name type was a list, this might be possible.
+Of course that would be a bit hackish, so the "right" way would probably be
+something like
+> InNS NsText "body"
+but isn't that a bit boring? ;)
+-}
diff --git a/src/Text/Pandoc/Readers/ODT/Namespaces.hs b/src/Text/Pandoc/Readers/ODT/Namespaces.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Readers/ODT/Namespaces.hs
@@ -0,0 +1,93 @@
+{-# LANGUAGE OverloadedStrings #-}
+{- |
+   Module      : Text.Pandoc.Reader.ODT.Namespaces
+   Copyright   : Copyright (C) 2015 Martin Linnemann
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : Martin Linnemann <theCodingMarlin@googlemail.com>
+   Stability   : alpha
+   Portability : portable
+
+Namespaces used in odt files.
+-}
+
+module Text.Pandoc.Readers.ODT.Namespaces ( Namespace (..)
+                                          ) where
+
+import qualified Data.Map as M (empty, insert)
+import Data.Maybe (fromMaybe, listToMaybe)
+import Data.Text (Text)
+import qualified Data.Text as T
+import Text.Pandoc.Readers.ODT.Generic.Namespaces
+
+
+instance NameSpaceID Namespace where
+
+  getInitialIRImap     = nsIDmap
+
+  getNamespaceID ""  m = Just(m, NsXML)
+  getNamespaceID iri m = asPair $ fromMaybe (NsOther iri) (findID iri)
+    where asPair nsID = Just (M.insert nsID iri m, nsID)
+
+
+findID :: NameSpaceIRI -> Maybe Namespace
+findID iri = listToMaybe [nsID | (iri',nsID) <- nsIDs, iri' `T.isPrefixOf` iri]
+
+nsIDmap :: NameSpaceIRIs Namespace
+nsIDmap = foldr (uncurry $ flip M.insert) M.empty nsIDs
+
+data Namespace = -- Open Document core
+                 NsOffice | NsStyle  | NsText   | NsTable  | NsForm
+               | NsDraw   | Ns3D     | NsAnim   | NsChart  | NsConfig
+               | NsDB     | NsMeta   | NsNumber | NsScript | NsManifest
+               | NsPresentation
+                 -- Metadata
+               | NsODF
+                 -- Compatible elements
+               | NsXSL_FO  | NsSVG    | NsSmil
+                 -- External standards
+               | NsMathML | NsXForms | NsXLink  | NsXHtml  | NsGRDDL
+               | NsDublinCore
+                 -- Metadata manifest
+               | NsPKG
+                 -- Others
+               | NsOpenFormula
+                 -- Core XML (basically only for the 'id'-attribute)
+               | NsXML
+                 -- Fallback
+               | NsOther Text
+  deriving ( Eq, Ord, Show )
+
+-- | Not the actual iri's, but large prefixes of them - this way there are
+-- less versioning problems and the like.
+nsIDs :: [(Text, Namespace)]
+nsIDs = [
+  ("urn:oasis:names:tc:opendocument:xmlns:animation"        , NsAnim         ),
+  ("urn:oasis:names:tc:opendocument:xmlns:chart"            , NsChart        ),
+  ("urn:oasis:names:tc:opendocument:xmlns:config"           , NsConfig       ),
+  ("urn:oasis:names:tc:opendocument:xmlns:database"         , NsDB           ),
+  ("urn:oasis:names:tc:opendocument:xmlns:dr3d"             , Ns3D           ),
+  ("urn:oasis:names:tc:opendocument:xmlns:drawing"          , NsDraw         ),
+  ("urn:oasis:names:tc:opendocument:xmlns:form"             , NsForm         ),
+  ("urn:oasis:names:tc:opendocument:xmlns:manifest"         , NsManifest     ),
+  ("urn:oasis:names:tc:opendocument:xmlns:meta"             , NsMeta         ),
+  ("urn:oasis:names:tc:opendocument:xmlns:datastyle"        , NsNumber       ),
+  ("urn:oasis:names:tc:opendocument:xmlns:of"               , NsOpenFormula  ),
+  ("urn:oasis:names:tc:opendocument:xmlns:office:1.0"       , NsOffice       ),
+  ("urn:oasis:names:tc:opendocument:xmlns:presentation"     , NsPresentation ),
+  ("urn:oasis:names:tc:opendocument:xmlns:script"           , NsScript       ),
+  ("urn:oasis:names:tc:opendocument:xmlns:style"            , NsStyle        ),
+  ("urn:oasis:names:tc:opendocument:xmlns:table"            , NsTable        ),
+  ("urn:oasis:names:tc:opendocument:xmlns:text"             , NsText         ),
+  ("urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible", NsXSL_FO       ),
+  ("urn:oasis:names:tc:opendocument:xmlns:smil-compatible"  , NsSmil         ),
+  ("urn:oasis:names:tc:opendocument:xmlns:svg-compatible"   , NsSVG          ),
+  ("http://docs.oasis-open.org/ns/office/1.2/meta/odf"      , NsODF          ),
+  ("http://docs.oasis-open.org/ns/office/1.2/meta/pkg"      , NsPKG          ),
+  ("http://purl.org/dc/elements"                            , NsDublinCore   ),
+  ("http://www.w3.org/2003/g/data-view"                     , NsGRDDL        ),
+  ("http://www.w3.org/1998/Math/MathML"                     , NsMathML       ),
+  ("http://www.w3.org/1999/xhtml"                           , NsXHtml        ),
+  ("http://www.w3.org/2002/xforms"                          , NsXForms       ),
+  ("http://www.w3.org/1999/xlink"                           , NsXLink        )
+  ]
diff --git a/src/Text/Pandoc/Readers/ODT/StyleReader.hs b/src/Text/Pandoc/Readers/ODT/StyleReader.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Readers/ODT/StyleReader.hs
@@ -0,0 +1,640 @@
+{-# LANGUAGE CPP             #-}
+{-# LANGUAGE Arrows          #-}
+{-# LANGUAGE RecordWildCards #-}
+{-# LANGUAGE TupleSections   #-}
+{-# LANGUAGE OverloadedStrings #-}
+{- |
+   Module      : Text.Pandoc.Readers.ODT.StyleReader
+   Copyright   : Copyright (C) 2015 Martin Linnemann
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : Martin Linnemann <theCodingMarlin@googlemail.com>
+   Stability   : alpha
+   Portability : portable
+
+Reader for the style information in an odt document.
+-}
+
+module Text.Pandoc.Readers.ODT.StyleReader
+( Style                (..)
+, StyleName
+, StyleFamily          (..)
+, Styles               (..)
+, StyleProperties      (..)
+, TextProperties       (..)
+, ParaProperties       (..)
+, VerticalTextPosition (..)
+, ListItemNumberFormat (..)
+, ListLevel
+, ListStyle            (..)
+, ListLevelStyle       (..)
+, ListLevelType        (..)
+, LengthOrPercent      (..)
+, lookupStyle
+, getListLevelStyle
+, getStyleFamily
+, lookupDefaultStyle'
+, lookupListStyleByName
+, extendedStylePropertyChain
+, readStylesAt
+) where
+
+import Prelude hiding (Applicative(..))
+import Control.Applicative hiding (liftA, liftA2, liftA3)
+import Control.Arrow
+
+import Data.Default
+import qualified Data.Foldable as F
+import qualified Data.List as L
+import qualified Data.Map as M
+import Data.Maybe
+import Data.Text (Text)
+import qualified Data.Text as T
+import qualified Data.Set as S
+
+import qualified Text.Pandoc.XML.Light as XML
+
+import Text.Pandoc.Shared (safeRead, tshow)
+
+import Text.Pandoc.Readers.ODT.Arrows.Utils
+
+import Text.Pandoc.Readers.ODT.Generic.Fallible
+import qualified Text.Pandoc.Readers.ODT.Generic.SetMap as SM
+import Text.Pandoc.Readers.ODT.Generic.Utils
+import Text.Pandoc.Readers.ODT.Generic.XMLConverter
+
+import Text.Pandoc.Readers.ODT.Base
+import Text.Pandoc.Readers.ODT.Namespaces
+
+readStylesAt :: XML.Element -> Fallible Styles
+readStylesAt e = runConverter' readAllStyles mempty e
+
+--------------------------------------------------------------------------------
+-- Reader for font declarations and font pitches
+--------------------------------------------------------------------------------
+
+-- Pandoc has no support for different font pitches. Yet knowing them can be
+-- very helpful in cases where Pandoc has more semantics than OpenDocument.
+-- In these cases, the pitch can help deciding as what to define a block of
+-- text. So let's start with a type for font pitches:
+
+data FontPitch    = PitchVariable | PitchFixed
+  deriving ( Eq, Show )
+
+instance Lookupable FontPitch where
+  lookupTable = [ ("variable" , PitchVariable)
+                , ("fixed"    , PitchFixed   )
+                ]
+
+instance Default FontPitch where
+  def = PitchVariable
+
+-- The font pitch can be specified in a style directly. Normally, however,
+-- it is defined in the font. That is also the specs' recommendation.
+--
+-- Thus, we want
+
+type FontFaceName = Text
+
+type FontPitches = M.Map FontFaceName FontPitch
+
+-- To get there, the fonts have to be read and the pitches extracted.
+-- But the resulting map are only needed at one later place, so it should not be
+-- transported on the value level, especially as we already use a state arrow.
+-- So instead, the resulting map is lifted into the state of the reader.
+-- (An alternative might be ImplicitParams, but again, we already have a state.)
+--
+-- So the main style readers will have the types
+type StyleReader     a b  = XMLReader     FontPitches a b
+-- and
+type StyleReaderSafe a b  = XMLReaderSafe FontPitches a b
+-- respectively.
+--
+-- But before we can work with these, we need to define the reader that reads
+-- the fonts:
+
+-- | A reader for font pitches
+fontPitchReader :: XMLReader s a FontPitches
+fontPitchReader = executeInSub NsOffice "font-face-decls" (
+                          withEveryL NsStyle "font-face" (liftAsSuccess (
+                              findAttr' NsStyle "name"
+                              &&&
+                              lookupDefaultingAttr NsStyle "font-pitch"
+                            ))
+                    >>?^ ( M.fromList . L.foldl' accumLegalPitches [] )
+                  ) `ifFailedDo` returnV (Right M.empty)
+  where accumLegalPitches ls (Nothing,_) = ls
+        accumLegalPitches ls (Just n,p)  = (n,p):ls
+
+
+-- | A wrapper around the font pitch reader that lifts the result into the
+-- state.
+readFontPitches :: StyleReader a a
+readFontPitches = producingExtraState () () fontPitchReader
+
+
+-- | Looking up a pitch in the state of the arrow.
+--
+-- The function does the following:
+-- * Look for the font pitch in an attribute.
+-- * If that fails, look for the font name, look up the font in the state
+--   and use the pitch from there.
+-- * Return the result in a Maybe
+--
+findPitch :: XMLReaderSafe FontPitches a (Maybe FontPitch)
+findPitch =     ( lookupAttr NsStyle "font-pitch"
+                  `ifFailedDo`     findAttr NsStyle "font-name"
+                               >>? (     keepingTheValue getExtraState
+                                     >>% M.lookup
+                                     >>^ maybeToChoice
+                                   )
+                )
+            >>> choiceToMaybe
+
+--------------------------------------------------------------------------------
+-- Definitions of main data
+--------------------------------------------------------------------------------
+
+type StyleName        = Text
+
+-- | There are two types of styles: named styles with a style family and an
+-- optional style parent, and default styles for each style family,
+-- defining default style properties
+data Styles           = Styles
+                          { stylesByName     :: M.Map StyleName   Style
+                          , listStylesByName :: M.Map StyleName   ListStyle
+                          , defaultStyleMap  :: M.Map StyleFamily StyleProperties
+                          }
+  deriving ( Show )
+
+-- Styles from a monoid under union
+instance Semigroup Styles where
+  (Styles sBn1 dSm1 lsBn1) <> (Styles sBn2 dSm2 lsBn2)
+          = Styles (M.union sBn1  sBn2)
+                   (M.union dSm1  dSm2)
+                   (M.union lsBn1 lsBn2)
+instance Monoid Styles where
+  mempty  = Styles M.empty M.empty M.empty
+  mappend = (<>)
+
+-- Not all families from the specifications are implemented, only those we need.
+-- But there are none that are not mentioned here.
+data StyleFamily      = FaText    | FaParagraph
+--                    | FaTable   | FaTableCell | FaTableColumn | FaTableRow
+--                    | FaGraphic | FaDrawing   | FaChart
+--                    | FaPresentation
+--                    | FaRuby
+  deriving ( Eq, Ord, Show )
+
+instance Lookupable StyleFamily where
+  lookupTable = [ ( "text"         , FaText         )
+                , ( "paragraph"    , FaParagraph    )
+--              , ( "table"        , FaTable        )
+--              , ( "table-cell"   , FaTableCell    )
+--              , ( "table-column" , FaTableColumn  )
+--              , ( "table-row"    , FaTableRow     )
+--              , ( "graphic"      , FaGraphic      )
+--              , ( "drawing-page" , FaDrawing      )
+--              , ( "chart"        , FaChart        )
+--              , ( "presentation" , FaPresentation )
+--              , ( "ruby"         , FaRuby         )
+                ]
+
+-- | A named style
+data Style            = Style  { styleFamily     :: Maybe StyleFamily
+                               , styleParentName :: Maybe StyleName
+                               , listStyle       :: Maybe StyleName
+                               , styleProperties :: StyleProperties
+                               }
+  deriving ( Eq, Show )
+
+data StyleProperties  = SProps { textProperties :: Maybe TextProperties
+                               , paraProperties :: Maybe ParaProperties
+--                             , tableColProperties  :: Maybe TColProperties
+--                             , tableRowProperties  :: Maybe TRowProperties
+--                             , tableCellProperties :: Maybe TCellProperties
+--                             , tableProperties     :: Maybe TableProperties
+--                             , graphicProperties   :: Maybe GraphProperties
+                               }
+  deriving ( Eq, Show )
+
+instance  Default StyleProperties where
+  def =                SProps { textProperties       = Just def
+                               , paraProperties      = Just def
+                               }
+
+data TextProperties   = PropT  { isEmphasised     :: Bool
+                               , isStrong         :: Bool
+                               , pitch            :: Maybe FontPitch
+                               , verticalPosition :: VerticalTextPosition
+                               , underline        :: Maybe UnderlineMode
+                               , strikethrough    :: Maybe UnderlineMode
+                               }
+  deriving ( Eq, Show )
+
+instance Default TextProperties where
+  def =                 PropT  { isEmphasised     = False
+                               , isStrong         = False
+                               , pitch            = Just def
+                               , verticalPosition = def
+                               , underline        = Nothing
+                               , strikethrough    = Nothing
+                               }
+
+data ParaProperties   = PropP { paraNumbering :: ParaNumbering
+                              , indentation   :: LengthOrPercent
+                              , margin_left   :: LengthOrPercent
+                              }
+  deriving ( Eq, Show )
+
+instance Default ParaProperties where
+  def =                 PropP { paraNumbering = NumberingNone
+                              , indentation   = def
+                              , margin_left   = def
+                              }
+
+----
+-- All the little data types that make up the properties
+----
+
+data VerticalTextPosition = VPosNormal | VPosSuper | VPosSub
+  deriving ( Eq, Show )
+
+instance Default VerticalTextPosition where
+  def = VPosNormal
+
+instance Read VerticalTextPosition where
+  readsPrec _ s =    [ (VPosSub        , s') | ("sub"   , s') <- lexS          ]
+                  ++ [ (VPosSuper      , s') | ("super" , s') <- lexS          ]
+                  ++ [ (signumToVPos n , s') | (  n     , s') <- readPercent s ]
+    where
+      lexS = lex s
+      signumToVPos n | n < 0     = VPosSub
+                     | n > 0     = VPosSuper
+                     | otherwise = VPosNormal
+
+data UnderlineMode = UnderlineModeNormal | UnderlineModeSkipWhitespace
+  deriving ( Eq, Show )
+
+instance Lookupable UnderlineMode where
+  lookupTable = [ ( "continuous"       , UnderlineModeNormal         )
+                , ( "skip-white-space" , UnderlineModeSkipWhitespace )
+                ]
+
+
+data ParaNumbering = NumberingNone | NumberingKeep | NumberingRestart Int
+  deriving ( Eq, Show )
+
+data LengthOrPercent = LengthValueMM Int | PercentValue Int
+  deriving ( Eq, Show )
+
+instance Default LengthOrPercent where
+  def = LengthValueMM 0
+
+instance Read LengthOrPercent where
+  readsPrec _ s =
+      [ (PercentValue  percent  , s' ) | (percent , s' ) <- readPercent s]
+   ++ [ (LengthValueMM lengthMM , s'') | (length' , s' ) <- reads s
+                                       , (unit    , s'') <- reads s'
+                                       , let lengthMM = estimateInMillimeter
+                                                                   length' unit
+                                       ]
+
+data XslUnit = XslUnitMM | XslUnitCM
+             | XslUnitInch
+             | XslUnitPoints | XslUnitPica
+             | XslUnitPixel
+             | XslUnitEM
+
+instance Show XslUnit where
+  show XslUnitMM     = "mm"
+  show XslUnitCM     = "cm"
+  show XslUnitInch   = "in"
+  show XslUnitPoints = "pt"
+  show XslUnitPica   = "pc"
+  show XslUnitPixel  = "px"
+  show XslUnitEM     = "em"
+
+instance Read XslUnit where
+  readsPrec _ "mm" = [(XslUnitMM     , "")]
+  readsPrec _ "cm" = [(XslUnitCM     , "")]
+  readsPrec _ "in" = [(XslUnitInch   , "")]
+  readsPrec _ "pt" = [(XslUnitPoints , "")]
+  readsPrec _ "pc" = [(XslUnitPica   , "")]
+  readsPrec _ "px" = [(XslUnitPixel  , "")]
+  readsPrec _ "em" = [(XslUnitEM     , "")]
+  readsPrec _  _   = []
+
+-- | Rough conversion of measures into millimetres.
+-- Pixels and em's are actually implementation dependent/relative measures,
+-- so I could not really easily calculate anything exact here even if I wanted.
+-- But I do not care about exactness right now, as I only use measures
+-- to determine if a paragraph is "indented" or not.
+estimateInMillimeter :: Double -> XslUnit -> Int
+estimateInMillimeter n XslUnitMM     = round n
+estimateInMillimeter n XslUnitCM     = round $ n * 10
+estimateInMillimeter n XslUnitInch   = round $ n * 25.4
+estimateInMillimeter n XslUnitPoints = round $ n * (1/72) * 25.4
+estimateInMillimeter n XslUnitPica   = round $ n * 12 * (1/72) * 25.4
+estimateInMillimeter n XslUnitPixel  = round $ n * (1/72) * 25.4
+estimateInMillimeter n XslUnitEM     = round $ n * 16 * (1/72) * 25.4
+
+
+----
+-- List styles
+----
+
+type ListLevel = Int
+
+newtype ListStyle = ListStyle { levelStyles :: M.Map ListLevel ListLevelStyle
+                              }
+  deriving ( Eq, Show )
+
+--
+getListLevelStyle :: ListLevel -> ListStyle -> Maybe ListLevelStyle
+getListLevelStyle level ListStyle{..} =
+  let (lower , exactHit , _) = M.splitLookup level levelStyles
+  in  exactHit <|> fmap fst (M.maxView lower)
+  -- findBy (`M.lookup` levelStyles) [level, (level-1) .. 1]
+  -- \^ simpler, but in general less efficient
+
+data ListLevelStyle = ListLevelStyle { listLevelType  :: ListLevelType
+                                     , listItemPrefix :: Maybe Text
+                                     , listItemSuffix :: Maybe Text
+                                     , listItemFormat :: ListItemNumberFormat
+                                     , listItemStart  :: Int
+                                     }
+  deriving ( Eq, Ord )
+
+instance Show ListLevelStyle where
+  show ListLevelStyle{..} =    "<LLS|"
+                            ++ show listLevelType
+                            ++ "|"
+                            ++ maybeToString (T.unpack <$> listItemPrefix)
+                            ++ show listItemFormat
+                            ++ maybeToString (T.unpack <$> listItemSuffix)
+                            ++ ">"
+    where maybeToString = fromMaybe ""
+
+data ListLevelType = LltBullet | LltImage | LltNumbered
+  deriving ( Eq, Ord, Show )
+
+data ListItemNumberFormat = LinfNone
+                          | LinfNumber
+                          | LinfRomanLC | LinfRomanUC
+                          | LinfAlphaLC | LinfAlphaUC
+                          | LinfString String
+  deriving ( Eq, Ord )
+
+instance Show ListItemNumberFormat where
+  show  LinfNone      = ""
+  show  LinfNumber    = "1"
+  show  LinfRomanLC   = "i"
+  show  LinfRomanUC   = "I"
+  show  LinfAlphaLC   = "a"
+  show  LinfAlphaUC   = "A"
+  show (LinfString s) =  s
+
+instance Default ListItemNumberFormat where
+  def = LinfNone
+
+instance Read ListItemNumberFormat where
+  readsPrec _ ""  = [(LinfNone     , "")]
+  readsPrec _ "1" = [(LinfNumber   , "")]
+  readsPrec _ "i" = [(LinfRomanLC  , "")]
+  readsPrec _ "I" = [(LinfRomanUC  , "")]
+  readsPrec _ "a" = [(LinfAlphaLC  , "")]
+  readsPrec _ "A" = [(LinfAlphaUC  , "")]
+  readsPrec _  s  = [(LinfString s , "")]
+
+--------------------------------------------------------------------------------
+-- Readers
+--
+-- ...it seems like a whole lot of this should be automatically derivable
+--    or at least moveable into a class. Most of this is data concealed in
+--    code.
+--------------------------------------------------------------------------------
+
+--
+readAllStyles :: StyleReader a Styles
+readAllStyles = (      readFontPitches
+                  >>?! (     readAutomaticStyles
+                         &&& readStyles ))
+                  >>?%? chooseMax
+ -- all top elements are always on the same hierarchy level
+
+--
+readStyles :: StyleReader a Styles
+readStyles = executeInSub NsOffice "styles" $ liftAsSuccess
+  $ liftA3 Styles
+    ( tryAll NsStyle "style"         readStyle        >>^ M.fromList )
+    ( tryAll NsText  "list-style"    readListStyle    >>^ M.fromList )
+    ( tryAll NsStyle "default-style" readDefaultStyle >>^ M.fromList )
+
+--
+readAutomaticStyles :: StyleReader a Styles
+readAutomaticStyles = executeInSub NsOffice "automatic-styles" $ liftAsSuccess
+  $ liftA3 Styles
+    ( tryAll NsStyle "style"         readStyle        >>^ M.fromList )
+    ( tryAll NsText  "list-style"    readListStyle    >>^ M.fromList )
+    ( returnV M.empty                                                )
+
+--
+readDefaultStyle :: StyleReader a (StyleFamily, StyleProperties)
+readDefaultStyle =      lookupAttr NsStyle "family"
+                   >>?! keepingTheValue readStyleProperties
+
+--
+readStyle :: StyleReader a (StyleName,Style)
+readStyle =      findAttr NsStyle "name"
+            >>?! keepingTheValue
+                   ( liftA4 Style
+                       ( lookupAttr' NsStyle "family"            )
+                       ( findAttr'   NsStyle "parent-style-name" )
+                       ( findAttr'   NsStyle "list-style-name"   )
+                       readStyleProperties
+                   )
+
+--
+readStyleProperties :: StyleReaderSafe a StyleProperties
+readStyleProperties = liftA2 SProps
+                       ( readTextProperties >>> choiceToMaybe )
+                       ( readParaProperties >>> choiceToMaybe )
+
+--
+readTextProperties :: StyleReader a TextProperties
+readTextProperties =
+  executeInSub NsStyle "text-properties" $ liftAsSuccess
+    ( liftA6 PropT
+       ( searchAttr   NsXSL_FO "font-style"  False isFontEmphasised )
+       ( searchAttr   NsXSL_FO "font-weight" False isFontBold       )
+       findPitch
+       ( getAttr      NsStyle  "text-position"                      )
+       readUnderlineMode
+       readStrikeThroughMode
+     )
+  where isFontEmphasised = [("normal",False),("italic",True),("oblique",True)]
+        isFontBold = ("normal",False):("bold",True)
+                    :map ((,True) . tshow) ([100,200..900]::[Int])
+
+readUnderlineMode     :: StyleReaderSafe a (Maybe UnderlineMode)
+readUnderlineMode     = readLineMode "text-underline-mode"
+                                     "text-underline-style"
+
+readStrikeThroughMode :: StyleReaderSafe a (Maybe UnderlineMode)
+readStrikeThroughMode = readLineMode "text-line-through-mode"
+                                     "text-line-through-style"
+
+readLineMode :: Text -> Text -> StyleReaderSafe a (Maybe UnderlineMode)
+readLineMode modeAttr styleAttr = proc x -> do
+  isUL <- searchAttr  NsStyle styleAttr False isLinePresent -< x
+  mode <- lookupAttr' NsStyle  modeAttr                     -< x
+  if isUL
+    then case mode of
+           Just m  -> returnA -< Just m
+           Nothing -> returnA -< Just UnderlineModeNormal
+    else              returnA -< Nothing
+  where
+    isLinePresent = ("none",False) : map (,True)
+                    [ "dash"      , "dot-dash" , "dot-dot-dash" , "dotted"
+                    , "long-dash" , "solid"    , "wave"
+                    ]
+
+--
+readParaProperties :: StyleReader a ParaProperties
+readParaProperties =
+   executeInSub NsStyle "paragraph-properties" $ liftAsSuccess
+     ( liftA3 PropP
+       ( liftA2 readNumbering
+         ( isSet'           NsText   "number-lines"           )
+         ( readAttr'        NsText   "line-number"            )
+       )
+       ( liftA2 readIndentation
+         ( isSetWithDefault NsStyle  "auto-text-indent" False )
+         ( getAttr          NsXSL_FO "text-indent"            )
+       )
+       (   getAttr          NsXSL_FO "margin-left"            )
+     )
+  where readNumbering (Just True) (Just n) = NumberingRestart n
+        readNumbering (Just True)  _       = NumberingKeep
+        readNumbering      _       _       = NumberingNone
+
+        readIndentation False indent = indent
+        readIndentation True  _      = def
+
+----
+-- List styles
+----
+
+--
+readListStyle :: StyleReader a (StyleName, ListStyle)
+readListStyle =
+       findAttr NsStyle "name"
+  >>?! keepingTheValue
+       ( liftA ListStyle
+         $ liftA3 SM.union3
+             ( readListLevelStyles NsText "list-level-style-number" LltNumbered )
+             ( readListLevelStyles NsText "list-level-style-bullet" LltBullet   )
+             ( readListLevelStyles NsText "list-level-style-image"  LltImage    ) >>^ M.mapMaybe chooseMostSpecificListLevelStyle
+       )
+--
+readListLevelStyles :: Namespace -> ElementName
+                    -> ListLevelType
+                    -> StyleReaderSafe a (SM.SetMap Int ListLevelStyle)
+readListLevelStyles namespace elementName levelType =
+  tryAll namespace elementName (readListLevelStyle levelType)
+    >>^ SM.fromList
+
+--
+readListLevelStyle :: ListLevelType -> StyleReader a (Int, ListLevelStyle)
+readListLevelStyle levelType =      readAttr NsText "level"
+                               >>?! keepingTheValue
+                                    ( liftA5 toListLevelStyle
+                                      ( returnV       levelType             )
+                                      ( findAttr'     NsStyle "num-prefix"  )
+                                      ( findAttr'     NsStyle "num-suffix"  )
+                                      ( getAttr       NsStyle "num-format"  )
+                                      ( findAttrText' NsText  "start-value" )
+                                    )
+  where
+  toListLevelStyle _ p s LinfNone b         = ListLevelStyle LltBullet p s LinfNone (startValue b)
+  toListLevelStyle _ p s f@(LinfString _) b = ListLevelStyle LltBullet p s f (startValue b)
+  toListLevelStyle t p s f b                = ListLevelStyle t      p s f (startValue b)
+  startValue mbx = fromMaybe 1 (mbx >>= safeRead)
+
+--
+chooseMostSpecificListLevelStyle :: S.Set ListLevelStyle -> Maybe ListLevelStyle
+chooseMostSpecificListLevelStyle ls = F.foldr select Nothing ls
+  where
+   select l Nothing = Just l
+   select ( ListLevelStyle t1 p1 s1 f1 b1 )
+          ( Just ( ListLevelStyle t2 p2 s2 f2 _ ))
+        =   Just $ ListLevelStyle (select' t1 t2) (p1 <|> p2) (s1 <|> s2)
+                                  (selectLinf f1 f2) b1
+   select' LltNumbered _           = LltNumbered
+   select' _           LltNumbered = LltNumbered
+   select' _           _           = LltBullet
+   selectLinf LinfNone       f2             = f2
+   selectLinf f1             LinfNone       = f1
+   selectLinf (LinfString _) f2             = f2
+   selectLinf f1             (LinfString _) = f1
+   selectLinf f1             _              = f1
+
+
+--------------------------------------------------------------------------------
+-- Tools to access style data
+--------------------------------------------------------------------------------
+
+--
+lookupStyle           :: StyleName   -> Styles -> Maybe Style
+lookupStyle name Styles{..} = M.lookup name stylesByName
+
+--
+lookupDefaultStyle'   :: Styles -> StyleFamily -> StyleProperties
+lookupDefaultStyle' Styles{..} family = fromMaybe def
+                                        (M.lookup family defaultStyleMap)
+
+--
+lookupListStyleByName :: StyleName   -> Styles -> Maybe ListStyle
+lookupListStyleByName name Styles{..} = M.lookup name listStylesByName
+
+
+-- | Returns a chain of parent of the current style. The direct parent will
+-- be the first element of the list, followed by its parent and so on.
+-- The current style is not in the list.
+parents               :: Style       -> Styles ->      [Style]
+parents style styles = L.unfoldr findNextParent style -- Ha!
+  where findNextParent Style{..}
+          = fmap duplicate $ (`lookupStyle` styles) =<< styleParentName
+
+-- | Looks up the style family of the current style. Normally, every style
+-- should have one. But if not, all parents are searched.
+getStyleFamily        :: Style       -> Styles -> Maybe StyleFamily
+getStyleFamily style@Style{..} styles
+  =     styleFamily
+    <|> F.asum (map (`getStyleFamily` styles) $ parents style styles)
+
+-- | Each 'Style' has certain 'StyleProperties'. But sometimes not all property
+-- values are specified. Instead, a value might be inherited from a
+-- parent style. This function makes this chain of inheritance
+-- concrete and easily accessible by encapsulating the necessary lookups.
+-- The resulting list contains the direct properties of the style as the first
+-- element, the ones of the direct parent element as the next one, and so on.
+--
+-- Note: There should also be default properties for each style family. These
+--       are @not@ contained in this list because properties inherited from
+--       parent elements take precedence over default styles.
+--
+-- This function is primarily meant to be used through convenience wrappers.
+--
+stylePropertyChain    :: Style       -> Styles -> [StyleProperties]
+stylePropertyChain style styles
+  = map styleProperties (style : parents style styles)
+
+--
+extendedStylePropertyChain :: [Style] -> Styles -> [StyleProperties]
+extendedStylePropertyChain [] _ = []
+extendedStylePropertyChain [style]       styles =    stylePropertyChain style styles
+                                                  ++ maybeToList (fmap (lookupDefaultStyle' styles) (getStyleFamily style styles))
+extendedStylePropertyChain (style:trace) styles =    stylePropertyChain style styles
+                                                  ++ extendedStylePropertyChain trace styles
diff --git a/src/Text/Pandoc/Readers/OOXML/Shared.hs b/src/Text/Pandoc/Readers/OOXML/Shared.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Readers/OOXML/Shared.hs
@@ -0,0 +1,95 @@
+{-# LANGUAGE OverloadedStrings #-}
+{- |
+   Module      : Text.Pandoc.Readers.OOXML.Shared
+   Copyright   : © 2025 Anton Antic
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : Anton Antic <anton@everworker.ai>
+   Stability   : alpha
+   Portability : portable
+
+Shared utilities for Office Open XML (OOXML) readers (DOCX, PPTX).
+Provides common functions for ZIP archive handling, XML parsing,
+namespace management, and DrawingML parsing.
+-}
+module Text.Pandoc.Readers.OOXML.Shared
+  ( -- * Constants
+    emusPerInch
+  , emuToInches
+  , inchesToEmu
+    -- * Types
+  , NameSpaces
+  , elemName
+  , elemToNameSpaces
+  , isElem
+  , findChildByName
+  , findChildrenByName
+  , findElementByName
+  , findAttrByName
+  ) where
+
+import qualified Data.Map as M
+import qualified Data.Text as T
+import Data.Text (Text)
+import Text.Pandoc.XML.Light
+
+-- | Type alias for namespace mappings
+type NameSpaces = M.Map Text Text
+
+-- | English Metric Units per inch
+-- 1 inch = 914400 EMUs (used in OOXML for dimensions)
+emusPerInch :: Integer
+emusPerInch = 914400
+
+-- | Convert EMUs to inches
+emuToInches :: Integer -> Double
+emuToInches n = fromIntegral n / fromIntegral emusPerInch
+
+-- | Convert inches to EMUs
+inchesToEmu :: Double -> Integer
+inchesToEmu n = round (n * fromIntegral emusPerInch)
+
+-- | Extract namespace declarations from element attributes
+elemToNameSpaces :: Element -> NameSpaces
+elemToNameSpaces = foldr (\(Attr qn val) ->
+                            case qn of
+                              QName s _ (Just "xmlns") -> M.insert s val
+                              _ -> id) mempty . elAttribs
+
+-- | Create a qualified name from namespace map, prefix, and local name
+elemName :: NameSpaces -> Text -> Text -> QName
+elemName ns prefix name =
+  QName name
+        (M.lookup prefix ns)
+        (if T.null prefix then Nothing else Just prefix)
+
+-- | Check if element matches namespace prefix and local name
+isElem :: NameSpaces -> Text -> Text -> Element -> Bool
+isElem ns prefix name element =
+  let ns' = ns <> elemToNameSpaces element
+  in  qName (elName element) == name &&
+      qURI (elName element) == M.lookup prefix ns'
+
+-- | Find first child element matching namespace and name
+findChildByName :: NameSpaces -> Text -> Text -> Element -> Maybe Element
+findChildByName ns pref name el =
+  let ns' = ns <> elemToNameSpaces el
+  in  findChild (elemName ns' pref name) el
+
+-- | Find all children matching namespace and name
+findChildrenByName :: NameSpaces -> Text -> Text -> Element -> [Element]
+findChildrenByName ns pref name el =
+  let ns' = ns <> elemToNameSpaces el
+  in  findChildren (elemName ns' pref name) el
+
+-- | Find element anywhere in descendants matching namespace and name
+findElementByName :: NameSpaces -> Text -> Text -> Element -> Maybe Element
+findElementByName ns pref name el =
+  let ns' = ns <> elemToNameSpaces el
+  in  findElement (elemName ns' pref name) el
+
+-- | Find attribute value by namespace prefix and name
+findAttrByName :: NameSpaces -> Text -> Text -> Element -> Maybe Text
+findAttrByName ns pref name el =
+  let ns' = ns <> elemToNameSpaces el
+  in  findAttr (elemName ns' pref name) el
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,19 +1,33 @@
-{-# LANGUAGE FlexibleContexts #-}
+{-# LANGUAGE OverloadedStrings #-}
+{- |
+   Module      : Text.Pandoc.Readers.OPML
+   Copyright   : Copyright (C) 2013-2024 John MacFarlane
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : John MacFarlane <jgm@berkeley.edu>
+   Stability   : alpha
+   Portability : portable
+
+Conversion of OPML to 'Pandoc' document.
+-}
+
 module Text.Pandoc.Readers.OPML ( readOPML ) where
 import Control.Monad.State.Strict
-import Data.Char (toUpper)
 import Data.Default
-import Data.Generics
 import Data.Maybe (fromMaybe)
-import Data.Text (Text, pack, unpack)
-import Text.HTML.TagSoup.Entity (lookupEntity)
+import Data.Text (Text)
+import qualified Data.Text as T
+import qualified Data.Text.Lazy as TL
 import Text.Pandoc.Builder
-import Text.Pandoc.Class (PandocMonad)
+import Text.Pandoc.Class.PandocMonad (PandocMonad)
 import Text.Pandoc.Options
+import Text.Pandoc.Error (PandocError(..))
 import Text.Pandoc.Readers.HTML (readHtml)
 import Text.Pandoc.Readers.Markdown (readMarkdown)
-import Text.Pandoc.Shared (crFilter, blocksToInlines')
-import Text.XML.Light
+import Text.Pandoc.Shared (blocksToInlines')
+import Text.Pandoc.Sources (ToSources(..), sourcesToText)
+import Text.Pandoc.XML.Light
+import Control.Monad.Except (throwError)
 
 type OPML m = StateT OPMLState m
 
@@ -33,53 +47,41 @@
                  , opmlOptions = def
                  }
 
-readOPML :: PandocMonad m => ReaderOptions -> Text -> m Pandoc
+readOPML :: (PandocMonad m, ToSources a)
+         => ReaderOptions
+         -> a
+         -> m Pandoc
 readOPML opts inp  = do
-  (bs, st') <- runStateT
-                 (mapM parseBlock $ normalizeTree $
-                    parseXML (unpack (crFilter inp))) def{ opmlOptions = opts }
+  let sources = toSources inp
+  (bs, st') <-
+    runStateT (case parseXMLContents (TL.fromStrict . sourcesToText $ sources) of
+                     Left msg -> throwError $ PandocXMLError "" msg
+                     Right ns -> mapM parseBlock ns)
+                 def{ opmlOptions = opts }
   return $
     setTitle (opmlDocTitle st') $
     setAuthors (opmlDocAuthors st') $
     setDate (opmlDocDate st') $
     doc $ mconcat bs
 
--- normalize input, consolidating adjacent Text and CRef elements
-normalizeTree :: [Content] -> [Content]
-normalizeTree = everywhere (mkT go)
-  where go :: [Content] -> [Content]
-        go (Text (CData CDataRaw _ _):xs) = xs
-        go (Text (CData CDataText s1 z):Text (CData CDataText s2 _):xs) =
-           Text (CData CDataText (s1 ++ s2) z):xs
-        go (Text (CData CDataText s1 z):CRef r:xs) =
-           Text (CData CDataText (s1 ++ convertEntity r) z):xs
-        go (CRef r:Text (CData CDataText s1 z):xs) =
-             Text (CData CDataText (convertEntity r ++ s1) z):xs
-        go (CRef r1:CRef r2:xs) =
-             Text (CData CDataText (convertEntity r1 ++ convertEntity r2) Nothing):xs
-        go xs = xs
-
-convertEntity :: String -> String
-convertEntity e = Data.Maybe.fromMaybe (map toUpper e) (lookupEntity e)
-
 -- convenience function to get an attribute value, defaulting to ""
-attrValue :: String -> Element -> String
+attrValue :: Text -> Element -> Text
 attrValue attr elt =
   fromMaybe "" (lookupAttrBy (\x -> qName x == attr) (elAttribs elt))
 
 -- exceptT :: PandocMonad m => Either PandocError a -> OPML m a
 -- exceptT = either throwError return
 
-asHtml :: PandocMonad m => String -> OPML m Inlines
+asHtml :: PandocMonad m => Text -> OPML m Inlines
 asHtml s = do
   opts <- gets opmlOptions
-  Pandoc _ bs <- readHtml def{ readerExtensions = readerExtensions opts } (pack s)
+  Pandoc _ bs <- readHtml def{ readerExtensions = readerExtensions opts } s
   return $ blocksToInlines' bs
 
-asMarkdown :: PandocMonad m => String -> OPML m Blocks
+asMarkdown :: PandocMonad m => Text -> OPML m Blocks
 asMarkdown s = do
   opts <- gets opmlOptions
-  Pandoc _ bs <- readMarkdown def{ readerExtensions = readerExtensions opts }  (pack s)
+  Pandoc _ bs <- readMarkdown def{ readerExtensions = readerExtensions opts } s
   return $ fromList bs
 
 getBlocks :: PandocMonad m => Element -> OPML m Blocks
@@ -102,7 +104,7 @@
                      modify $ \st -> st{ opmlSectionLevel = n }
                      bs <- getBlocks e
                      modify $ \st -> st{ opmlSectionLevel = n - 1 }
-                     let headerText' = case map toUpper (attrValue "type" e) of
+                     let headerText' = case T.toUpper (attrValue "type" e) of
                                              "LINK"  -> link
                                                (attrValue "url" e) "" headerText
                                              _ -> headerText
diff --git a/src/Text/Pandoc/Readers/Odt.hs b/src/Text/Pandoc/Readers/Odt.hs
deleted file mode 100644
--- a/src/Text/Pandoc/Readers/Odt.hs
+++ /dev/null
@@ -1,113 +0,0 @@
-{-# 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
-   License     : GNU GPL, version 2 or above
-
-   Maintainer  : Martin Linnemann <theCodingMarlin@googlemail.com>
-   Stability   : alpha
-   Portability : portable
-
-Entry point to the odt reader.
--}
-
-module Text.Pandoc.Readers.Odt ( readOdt ) where
-
-import Codec.Archive.Zip
-import qualified Text.XML.Light as XML
-
-import qualified Data.ByteString.Lazy as B
-
-import System.FilePath
-
-import Control.Monad.Except (throwError)
-
-import Text.Pandoc.Class (PandocMonad)
-import qualified Text.Pandoc.Class as P
-import Text.Pandoc.Definition
-import Text.Pandoc.Error
-import Text.Pandoc.MediaBag
-import Text.Pandoc.Options
-import qualified Text.Pandoc.UTF8 as UTF8
-
-import Text.Pandoc.Readers.Odt.ContentReader
-import Text.Pandoc.Readers.Odt.StyleReader
-
-import Text.Pandoc.Readers.Odt.Generic.Fallible
-import Text.Pandoc.Readers.Odt.Generic.XMLConverter
-import Text.Pandoc.Shared (filteredFilesFromArchive)
-
-readOdt :: PandocMonad m
-        => ReaderOptions
-        -> B.ByteString
-        -> m Pandoc
-readOdt opts bytes = case readOdt' opts bytes of
-  Right (doc, mb) -> do
-    P.setMediaBag mb
-    return doc
-  Left e -> throwError e
-
---
-readOdt' :: ReaderOptions
-         -> B.ByteString
-         -> Either PandocError (Pandoc, MediaBag)
-readOdt' _ bytes = bytesToOdt bytes-- of
---                    Right (pandoc, mediaBag) -> Right (pandoc , mediaBag)
---                    Left  err                -> Left err
-
---
-bytesToOdt :: B.ByteString -> Either PandocError (Pandoc, MediaBag)
-bytesToOdt bytes = case toArchiveOrFail bytes of
-  Right archive -> archiveToOdt archive
-  Left _        -> Left $ PandocParseError "Couldn't parse odt file."
-
---
-archiveToOdt :: Archive -> Either PandocError (Pandoc, MediaBag)
-archiveToOdt archive
-  | Just contentEntry      <- findEntryByPath "content.xml" archive
-  , Just stylesEntry       <- findEntryByPath "styles.xml"  archive
-  , Just contentElem       <- entryToXmlElem contentEntry
-  , Just stylesElem        <- entryToXmlElem stylesEntry
-  , Right styles           <- chooseMax (readStylesAt stylesElem )
-                                        (readStylesAt contentElem)
-  , media                  <- filteredFilesFromArchive archive filePathIsOdtMedia
-  , startState             <- readerState styles media
-  , Right pandocWithMedia  <- runConverter' read_body
-                                            startState
-                                            contentElem
-
-  = Right pandocWithMedia
-
-  | otherwise
-    -- Not very detailed, but I don't think more information would be helpful
-  = Left $ PandocParseError "Couldn't parse odt file."
-    where
-      filePathIsOdtMedia :: FilePath -> Bool
-      filePathIsOdtMedia fp =
-        let (dir, _) = splitFileName fp
-        in
-         (dir == "Pictures/")
-
-
---
-entryToXmlElem :: Entry -> Maybe XML.Element
-entryToXmlElem = XML.parseXMLDoc . UTF8.toStringLazy . fromEntry
diff --git a/src/Text/Pandoc/Readers/Odt/Arrows/State.hs b/src/Text/Pandoc/Readers/Odt/Arrows/State.hs
deleted file mode 100644
--- a/src/Text/Pandoc/Readers/Odt/Arrows/State.hs
+++ /dev/null
@@ -1,163 +0,0 @@
-
-{-# 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
-   License     : GNU GPL, version 2 or above
-
-   Maintainer  : Martin Linnemann <theCodingMarlin@googlemail.com>
-   Stability   : alpha
-   Portability : portable
-
-An arrow that transports a state. It is in essence a more powerful version of
-the standard state monad. As it is such a simple extension, there are
-other version out there that do exactly the same.
-The implementation is duplicated, though, to add some useful features.
-Most of these might be implemented without access to innards, but it's much
-faster and easier to implement this way.
--}
-
-module Text.Pandoc.Readers.Odt.Arrows.State where
-
-import Prelude hiding (foldl, foldr)
-
-import Control.Arrow
-import qualified Control.Category as Cat
-import Control.Monad
-
-import Data.Foldable
-import Data.Monoid
-
-import Text.Pandoc.Readers.Odt.Arrows.Utils
-import Text.Pandoc.Readers.Odt.Generic.Fallible
-
-
-newtype ArrowState state a b = ArrowState
-  { runArrowState :: (state, a) -> (state, b) }
-
--- | Constructor
-withState           :: (state -> a -> (state, b)) -> ArrowState state a b
-withState            = ArrowState . uncurry
-
--- | Constructor
-modifyState         :: (state      ->  state    ) -> ArrowState state a a
-modifyState          = ArrowState . first
-
--- | Constructor
-ignoringState       :: (         a ->         b ) -> ArrowState state a b
-ignoringState        = ArrowState . second
-
--- | Constructor
-fromState           :: (state      -> (state, b)) -> ArrowState state a b
-fromState            = ArrowState . (.fst)
-
--- | Constructor
-extractFromState    :: (state      ->         b ) -> ArrowState state x b
-extractFromState   f = ArrowState $ \(state,_) -> (state, f state)
-
--- | Constructor
-tryModifyState      :: (state ->  Either f state)
-                    -> ArrowState state a (Either f a)
-tryModifyState     f = ArrowState $ \(state,a)
-                                  -> (state,).Left ||| (,Right a) $ f state
-
-instance Cat.Category (ArrowState s) where
-  id                = ArrowState id
-  arrow2 . arrow1   = ArrowState $ runArrowState arrow2 . runArrowState arrow1
-
-instance Arrow (ArrowState state) where
-  arr               = ignoringState
-  first  a          = ArrowState $ \(s,(aF,aS))
-                                    -> second (,aS) $ runArrowState a (s,aF)
-  second a          = ArrowState $ \(s,(aF,aS))
-                                    -> second (aF,) $ runArrowState a (s,aS)
-
-instance ArrowChoice (ArrowState state) where
-  left   a          = ArrowState $ \(s,e) -> case e of
-                                 Left  l -> second Left  $ runArrowState a (s,l)
-                                 Right r -> (s, Right r)
-  right  a          = ArrowState $ \(s,e) -> case e of
-                                 Left  l -> (s, Left l)
-                                 Right r -> second Right $ runArrowState a (s,r)
-
-instance ArrowApply (ArrowState state) where
-   app             = ArrowState $ \(s, (f,b)) -> runArrowState f (s,b)
-
--- | Switches the type of the state temporarily.
--- Drops the intermediate result state, behaving like a fallible
--- identity arrow, save for side effects in the state.
-withSubStateF  :: ArrowState s  x (Either f s')
-               -> ArrowState s' s (Either f s )
-               -> ArrowState s  x (Either f x )
-withSubStateF  unlift a = keepingTheValue (withSubStateF' unlift a)
-                          >>^ spreadChoice
-                          >>^ fmap fst
-
--- | Switches the type of the state temporarily.
--- Returns the resulting sub-state.
-withSubStateF' :: ArrowState s  x (Either f s')
-               -> ArrowState s' s (Either f s )
-               -> ArrowState s  x (Either f s')
-withSubStateF' unlift a = ArrowState go
-  where go p@(s,_) = tryRunning unlift
-                                ( tryRunning a (second Right) )
-                                p
-          where tryRunning a' b v = case runArrowState a' v of
-                                      (_ , Left  f) -> (s, Left f)
-                                      (x , Right y) -> b (y,x)
-
--- | Fold a state arrow through something 'Foldable'. Collect the results
--- in a 'Monoid'.
--- Intermediate form of a fold between one with "only" a 'Monoid'
--- and one with any function.
-foldS :: (Foldable f, Monoid m) => ArrowState s x m -> ArrowState s (f x) m
-foldS a = ArrowState $ \(s,f) -> foldr a' (s,mempty) f
-  where a' x (s',m) = second (m <>)  $ runArrowState a (s',x)
-
--- | Fold a state arrow through something 'Foldable'. Collect the results in a
--- 'MonadPlus'.
-iterateS :: (Foldable f, MonadPlus m)
-         => ArrowState s    x     y
-         -> ArrowState s (f x) (m y)
-iterateS a = ArrowState $ \(s,f) -> foldr a' (s,mzero) f
-  where a' x (s',m) = second (mplus m.return) $ runArrowState a (s',x)
-
--- | Fold a state arrow through something 'Foldable'. Collect the results in a
--- 'MonadPlus'.
-iterateSL :: (Foldable f, MonadPlus m)
-          => ArrowState s    x     y
-          -> ArrowState s (f x) (m y)
-iterateSL a = ArrowState $ \(s,f) -> foldl a' (s,mzero) f
-  where a' (s',m) x = second (mplus m.return) $ runArrowState a (s',x)
-
-
--- | Fold a fallible state arrow through something 'Foldable'.
--- Collect the results in a 'MonadPlus'.
--- If the iteration fails, the state will be reset to the initial one.
-iterateS' :: (Foldable f, MonadPlus m)
-          => ArrowState s    x  (Either e    y )
-          -> ArrowState s (f x) (Either e (m y))
-iterateS' a = ArrowState $ \(s,f) -> foldr (a' s) (s,Right mzero) f
-  where a' s x (s',Right m) = case runArrowState a (s',x) of
-                                (s'',Right m') -> (s'',Right $ mplus m $ return m')
-                                (_  ,Left  e ) -> (s  ,Left  e )
-        a' _ _   e          = e
diff --git a/src/Text/Pandoc/Readers/Odt/Arrows/Utils.hs b/src/Text/Pandoc/Readers/Odt/Arrows/Utils.hs
deleted file mode 100644
--- a/src/Text/Pandoc/Readers/Odt/Arrows/Utils.hs
+++ /dev/null
@@ -1,231 +0,0 @@
-{-
-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
-   License     : GNU GPL, version 2 or above
-
-   Maintainer  : Martin Linnemann <theCodingMarlin@googlemail.com>
-   Stability   : alpha
-   Portability : portable
-
-Utility functions for Arrows (Kleisli monads).
-
-Some general notes on notation:
-
-* "^" is meant to stand for a pure function that is lifted into an arrow
-based on its usage for that purpose in "Control.Arrow".
-* "?" is meant to stand for the usage of a 'FallibleArrow' or a pure function
-with an equivalent return value.
-* "_" stands for the dropping of a value.
--}
-
--- We export everything
-module Text.Pandoc.Readers.Odt.Arrows.Utils where
-
-import Control.Arrow
-import Control.Monad (join)
-
-import Text.Pandoc.Readers.Odt.Generic.Fallible
-import Text.Pandoc.Readers.Odt.Generic.Utils
-
-and2 :: (Arrow a) => a b c -> a b c' -> a b (c,c')
-and2 = (&&&)
-
-and3 :: (Arrow a)
-     => a b c0->a b c1->a b c2
-     -> a b (c0,c1,c2               )
-and4 :: (Arrow a)
-     => a b c0->a b c1->a b c2->a b c3
-     -> a b (c0,c1,c2,c3            )
-and5 :: (Arrow a)
-     => a b c0->a b c1->a b c2->a b c3->a b c4
-     -> a b (c0,c1,c2,c3,c4         )
-and6 :: (Arrow a)
-     => a b c0->a b c1->a b c2->a b c3->a b c4->a b c5
-     -> a b (c0,c1,c2,c3,c4,c5      )
-
-and3 a b c           = (and2 a b          ) &&& c
-                       >>^ \((z,y          ) , x) -> (z,y,x          )
-and4 a b c d         = (and3 a b c        ) &&& d
-                       >>^ \((z,y,x        ) , w) -> (z,y,x,w        )
-and5 a b c d e       = (and4 a b c d      ) &&& e
-                       >>^ \((z,y,x,w      ) , v) -> (z,y,x,w,v      )
-and6 a b c d e f     = (and5 a b c d e    ) &&& f
-                       >>^ \((z,y,x,w,v    ) , u) -> (z,y,x,w,v,u    )
-
-liftA2 :: (Arrow a) => (x -> y -> z) -> a b x -> a b y -> a b z
-liftA2 f a b = a &&& b >>^ uncurry f
-
-liftA3 :: (Arrow a) => (z->y->x                -> r)
-                    -> a b z->a b y->a b x
-                    -> a b r
-liftA4 :: (Arrow a) => (z->y->x->w             -> r)
-                    -> a b z->a b y->a b x->a b w
-                    -> a b r
-liftA5 :: (Arrow a) => (z->y->x->w->v          -> r)
-                    -> a b z->a b y->a b x->a b w->a b v
-                    -> a b r
-liftA6 :: (Arrow a) => (z->y->x->w->v->u       -> r)
-                    -> a b z->a b y->a b x->a b w->a b v->a b u
-                    -> a b r
-
-liftA3 fun a b c           = and3 a b c           >>^ uncurry3 fun
-liftA4 fun a b c d         = and4 a b c d         >>^ uncurry4 fun
-liftA5 fun a b c d e       = and5 a b c d e       >>^ uncurry5 fun
-liftA6 fun a b c d e f     = and6 a b c d e f     >>^ uncurry6 fun
-
-liftA :: (Arrow a) => (y -> z) -> a b y -> a b z
-liftA  fun a = a >>^ fun
-
-
--- | Duplicate a value to subsequently feed it into different arrows.
--- Can almost always be replaced with '(&&&)', 'keepingTheValue',
--- or even '(|||)'.
--- Aequivalent to
--- > returnA &&& returnA
-duplicate :: (Arrow a) => a b (b,b)
-duplicate = arr $ join (,)
-
--- | Applies a function to the uncurried result-pair of an arrow-application.
--- (The %-symbol was chosen to evoke an association with pairs.)
-(>>%) :: (Arrow a) => a x (b,c) -> (b -> c -> d) -> a x d
-a >>% f = a >>^ uncurry f
-
-infixr 2 >>%
-
-
--- | Duplicate a value and apply an arrow to the second instance.
--- Aequivalent to
--- > \a -> duplicate >>> second a
--- or
--- > \a -> returnA &&& a
-keepingTheValue :: (Arrow a) => a b c -> a b (b,c)
-keepingTheValue a = returnA &&& a
-
-( ^|||  ) :: (ArrowChoice a) => (b -> d) ->  a c d   -> a (Either b c) d
-(  |||^ ) :: (ArrowChoice a) =>  a b d   -> (c -> d) -> a (Either b c) d
-( ^|||^ ) :: (ArrowChoice a) => (b -> d) -> (c -> d) -> a (Either b c) d
-
-l ^|||  r  = arr l |||     r
-l  |||^ r  =     l ||| arr r
-l ^|||^ r  = arr l ||| arr r
-
-infixr 2 ^||| ,  |||^, ^|||^
-
-( ^&&&  ) :: (Arrow a) => (b -> c) ->  a b c'   -> a b (c,c')
-(  &&&^ ) :: (Arrow a) =>  a b c   -> (b -> c') -> a b (c,c')
-
-l ^&&&  r = arr l &&&     r
-l  &&&^ r =     l &&& arr r
-
-infixr 3 ^&&&, &&&^
-
-
--- | Converts @Right a@ into @Just a@ and @Left _@ into @Nothing@.
-choiceToMaybe :: (ArrowChoice a) => a (Either l r) (Maybe r)
-choiceToMaybe = arr eitherToMaybe
-
--- | Converts @Nothing@ into @Left ()@ and @Just a@ into @Right a@.
-maybeToChoice :: (ArrowChoice a) => a (Maybe b) (Fallible b)
-maybeToChoice = arr maybeToEither
-
--- | Lifts a constant value into an arrow
-returnV :: (Arrow a) => c -> a x c
-returnV = arr.const
-
--- | Defines Left as failure, Right as success
-type FallibleArrow a input failure success = a input (Either failure success)
-
---
-liftAsSuccess     :: (ArrowChoice a)
-                  => a x success
-                  -> FallibleArrow a x failure success
-liftAsSuccess a   = a >>^ Right
-
--- | Execute the second arrow if the first succeeds
-(>>?) :: (ArrowChoice a)
-            => FallibleArrow a x       failure success
-            -> FallibleArrow a success failure success'
-            -> FallibleArrow a x       failure success'
-a >>? b = a >>> Left ^||| b
-
--- | Execute the lifted second arrow if the first succeeds
-(>>?^) :: (ArrowChoice a)
-            => FallibleArrow a x       failure success
-            -> (success                     -> success')
-            -> FallibleArrow a x       failure success'
-a >>?^ f = a >>^ Left ^|||^ Right . f
-
--- | Execute the lifted second arrow if the first succeeds
-(>>?^?) :: (ArrowChoice a)
-            => FallibleArrow a x       failure success
-            -> (success      -> Either failure success')
-            -> FallibleArrow a x       failure success'
-a >>?^? b = a >>> Left ^|||^ b
-
--- | Execute the second arrow if the lifted first arrow succeeds
-(^>>?) :: (ArrowChoice a)
-            => (x            -> Either failure success)
-            -> FallibleArrow a success failure success'
-            -> FallibleArrow a x       failure success'
-a ^>>? b = a ^>> Left ^||| b
-
--- | Execute the second, non-fallible arrow if the first arrow succeeds
-(>>?!) :: (ArrowChoice a)
-            => FallibleArrow a x       failure success
-            ->               a success         success'
-            -> FallibleArrow a x       failure success'
-a >>?! f = a >>> right f
-
----
-(>>?%) :: (ArrowChoice a)
-          => FallibleArrow a x f (b,b')
-          -> (b -> b' -> c)
-          -> FallibleArrow a x f c
-a >>?% f = a >>?^ (uncurry f)
-
----
-(^>>?%) :: (ArrowChoice a)
-          => (x -> Either f (b,b'))
-          -> (b -> b' -> c)
-          -> FallibleArrow a x f c
-a ^>>?% f = arr a >>?^ (uncurry f)
-
----
-(>>?%?) :: (ArrowChoice a)
-           => FallibleArrow a x f (b,b')
-           -> (b -> b' -> (Either f c))
-           -> FallibleArrow a x f c
-a >>?%? f = a >>?^? (uncurry f)
-
-infixr 1  >>?,  >>?^,  >>?^?
-infixr 1 ^>>?, >>?!
-infixr 1 >>?%, ^>>?%, >>?%?
-
--- | An arrow version of a short-circuit (<|>)
-ifFailedDo :: (ArrowChoice a)
-           => FallibleArrow a x f y
-           -> FallibleArrow a x f y
-           -> FallibleArrow a x f y
-ifFailedDo a b = keepingTheValue a >>> repackage ^>> (b |||^ Right)
-  where repackage (x , Left  _) = Left  x
-        repackage (_ , Right y) = Right y
-
-infixr 1 `ifFailedDo`
diff --git a/src/Text/Pandoc/Readers/Odt/Base.hs b/src/Text/Pandoc/Readers/Odt/Base.hs
deleted file mode 100644
--- a/src/Text/Pandoc/Readers/Odt/Base.hs
+++ /dev/null
@@ -1,42 +0,0 @@
-
-
-{-
-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
-   License     : GNU GPL, version 2 or above
-
-   Maintainer  : Martin Linnemann <theCodingMarlin@googlemail.com>
-   Stability   : alpha
-   Portability : portable
-
-Core types of the odt reader.
--}
-
-module Text.Pandoc.Readers.Odt.Base where
-
-import Text.Pandoc.Readers.Odt.Generic.XMLConverter
-import Text.Pandoc.Readers.Odt.Namespaces
-
-type OdtConverterState s = XMLConverterState Namespace s
-
-type XMLReader     s a b = FallibleXMLConverter Namespace s a b
-
-type XMLReaderSafe s a b =         XMLConverter Namespace s a b
diff --git a/src/Text/Pandoc/Readers/Odt/ContentReader.hs b/src/Text/Pandoc/Readers/Odt/ContentReader.hs
deleted file mode 100644
--- a/src/Text/Pandoc/Readers/Odt/ContentReader.hs
+++ /dev/null
@@ -1,923 +0,0 @@
-{-# LANGUAGE Arrows          #-}
-{-# LANGUAGE PatternGuards   #-}
-{-# 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
-   License     : GNU GPL, version 2 or above
-
-   Maintainer  : Martin Linnemann <theCodingMarlin@googlemail.com>
-   Stability   : alpha
-   Portability : portable
-
-The core of the odt reader that converts odt features into Pandoc types.
--}
-
-module Text.Pandoc.Readers.Odt.ContentReader
-( readerState
-, read_body
-) where
-
-import Control.Applicative hiding (liftA, liftA2, liftA3)
-import Control.Arrow
-
-import qualified Data.ByteString.Lazy as B
-import Data.List (find, intercalate)
-import qualified Data.Map as M
-import Data.Maybe
-
-import qualified Text.XML.Light as XML
-
-import Text.Pandoc.Builder
-import Text.Pandoc.MediaBag (MediaBag, insertMedia)
-import Text.Pandoc.Shared
-
-import Text.Pandoc.Readers.Odt.Base
-import Text.Pandoc.Readers.Odt.Namespaces
-import Text.Pandoc.Readers.Odt.StyleReader
-
-import Text.Pandoc.Readers.Odt.Arrows.Utils
-import Text.Pandoc.Readers.Odt.Generic.Fallible
-import Text.Pandoc.Readers.Odt.Generic.Utils
-import Text.Pandoc.Readers.Odt.Generic.XMLConverter
-
-import qualified Data.Set as Set
-
---------------------------------------------------------------------------------
--- State
---------------------------------------------------------------------------------
-
-type Anchor = String
-type Media = [(FilePath, B.ByteString)]
-
-data ReaderState
-   = ReaderState { -- | A collection of styles read somewhere else.
-                   -- It is only queried here, not modified.
-                   styleSet         :: Styles
-                   -- | A stack of the styles of parent elements.
-                   -- Used to look up inherited style properties.
-                 , styleTrace       :: [Style]
-                   -- | Keeps track of the current depth in nested lists
-                 , currentListLevel :: ListLevel
-                   -- | Lists may provide their own style, but they don't have
-                   -- to. If they do not, the style of a parent list may be used
-                   -- or even a default list style from the paragraph style.
-                   -- This value keeps track of the closest list style there
-                   -- currently is.
-                 , currentListStyle :: Maybe ListStyle
-                   -- | A map from internal anchor names to "pretty" ones.
-                   -- The mapping is a purely cosmetic one.
-                 , bookmarkAnchors  :: M.Map Anchor Anchor
-                   -- | A map of files / binary data from the archive
-                 , envMedia         :: Media
-                   -- | Hold binary resources used in the document
-                 , odtMediaBag      :: MediaBag
-                 }
-  deriving ( Show )
-
-readerState :: Styles -> Media -> ReaderState
-readerState styles media = ReaderState styles [] 0 Nothing M.empty media mempty
-
---
-pushStyle'  :: Style -> ReaderState -> ReaderState
-pushStyle' style state = state { styleTrace = style : styleTrace state }
-
---
-popStyle'   :: ReaderState -> ReaderState
-popStyle' state = case styleTrace state of
-                   _:trace -> state  { styleTrace = trace  }
-                   _       -> state
-
---
-modifyListLevel :: (ListLevel -> ListLevel) -> (ReaderState -> ReaderState)
-modifyListLevel f state = state { currentListLevel = f (currentListLevel state) }
-
---
-shiftListLevel :: ListLevel -> (ReaderState -> ReaderState)
-shiftListLevel diff = modifyListLevel (+ diff)
-
---
-swapCurrentListStyle :: Maybe ListStyle -> ReaderState
-                     -> (ReaderState, Maybe ListStyle)
-swapCurrentListStyle mListStyle state = ( state { currentListStyle = mListStyle }
-                                        ,  currentListStyle state
-                                        )
-
---
-lookupPrettyAnchor :: Anchor -> ReaderState -> Maybe Anchor
-lookupPrettyAnchor anchor ReaderState{..} = M.lookup anchor bookmarkAnchors
-
---
-putPrettyAnchor :: Anchor -> Anchor -> ReaderState -> ReaderState
-putPrettyAnchor ugly pretty state@ReaderState{..}
-  = state { bookmarkAnchors = M.insert ugly pretty bookmarkAnchors }
-
---
-usedAnchors :: ReaderState -> [Anchor]
-usedAnchors ReaderState{..} = M.elems bookmarkAnchors
-
-getMediaBag :: ReaderState -> MediaBag
-getMediaBag ReaderState{..} = odtMediaBag
-
-getMediaEnv :: ReaderState -> Media
-getMediaEnv ReaderState{..} = envMedia
-
-insertMedia' :: (FilePath, B.ByteString) -> ReaderState ->  ReaderState
-insertMedia' (fp, bs) state@ReaderState{..}
-  = state { odtMediaBag = insertMedia fp Nothing bs odtMediaBag }
-
---------------------------------------------------------------------------------
--- Reader type and associated tools
---------------------------------------------------------------------------------
-
-type OdtReader      a b = XMLReader     ReaderState a b
-
-type OdtReaderSafe  a b = XMLReaderSafe ReaderState a b
-
--- | Extract something from the styles
-fromStyles :: (a -> Styles -> b) -> OdtReaderSafe a b
-fromStyles f =     keepingTheValue
-                     (getExtraState >>^ styleSet)
-               >>% f
-
---
-getStyleByName :: OdtReader StyleName Style
-getStyleByName = fromStyles lookupStyle >>^ maybeToChoice
-
---
-findStyleFamily :: OdtReader Style StyleFamily
-findStyleFamily = fromStyles getStyleFamily >>^ maybeToChoice
-
---
-lookupListStyle :: OdtReader StyleName ListStyle
-lookupListStyle = fromStyles lookupListStyleByName >>^ maybeToChoice
-
---
-switchCurrentListStyle :: OdtReaderSafe (Maybe ListStyle) (Maybe ListStyle)
-switchCurrentListStyle =     keepingTheValue getExtraState
-                         >>% swapCurrentListStyle
-                         >>> first setExtraState
-                         >>^ snd
-
---
-pushStyle :: OdtReaderSafe Style Style
-pushStyle =     keepingTheValue (
-                  (     keepingTheValue getExtraState
-                    >>% pushStyle'
-                  )
-                  >>> setExtraState
-                )
-            >>^ fst
-
---
-popStyle :: OdtReaderSafe x x
-popStyle =     keepingTheValue (
-                     getExtraState
-                 >>> arr popStyle'
-                 >>> setExtraState
-               )
-           >>^ fst
-
---
-getCurrentListLevel :: OdtReaderSafe _x ListLevel
-getCurrentListLevel = getExtraState >>^ currentListLevel
-
---
-updateMediaWithResource :: OdtReaderSafe (FilePath, B.ByteString) (FilePath, B.ByteString)
-updateMediaWithResource = keepingTheValue (
-                 (keepingTheValue getExtraState
-                  >>% insertMedia'
-                  )
-                 >>> setExtraState
-               )
-           >>^ fst
-
-lookupResource :: OdtReaderSafe String (FilePath, B.ByteString)
-lookupResource = proc target -> do
-    state <- getExtraState -< ()
-    case lookup target (getMediaEnv state) of
-      Just bs -> returnV (target, bs) -<< ()
-      Nothing -> returnV ("", B.empty) -< ()
-
-type AnchorPrefix = String
-
--- | An adaptation of 'uniqueIdent' from "Text.Pandoc.Shared" that generates a
--- unique identifier but without assuming that the id should be for a header.
--- Second argument is a list of already used identifiers.
-uniqueIdentFrom :: AnchorPrefix -> [Anchor] -> Anchor
-uniqueIdentFrom baseIdent usedIdents =
-  let  numIdent n = baseIdent ++ "-" ++ show n
-  in  if baseIdent `elem` usedIdents
-        then case find (\x -> numIdent x `notElem` usedIdents) ([1..60000] :: [Int]) of
-                  Just x  -> numIdent x
-                  Nothing -> baseIdent   -- if we have more than 60,000, allow repeats
-        else baseIdent
-
--- | First argument: basis for a new "pretty" anchor if none exists yet
--- Second argument: a key ("ugly" anchor)
--- Returns: saved "pretty" anchor or created new one
-getPrettyAnchor :: OdtReaderSafe (AnchorPrefix, Anchor) Anchor
-getPrettyAnchor = proc (baseIdent, uglyAnchor) -> do
-  state <- getExtraState -< ()
-  case lookupPrettyAnchor uglyAnchor state of
-    Just prettyAnchor -> returnA -< prettyAnchor
-    Nothing           -> do
-      let newPretty = uniqueIdentFrom baseIdent (usedAnchors state)
-      modifyExtraState (putPrettyAnchor uglyAnchor newPretty) -<< newPretty
-
--- | Input: basis for a new header anchor
--- Output: saved new anchor
-getHeaderAnchor :: OdtReaderSafe Inlines Anchor
-getHeaderAnchor = proc title -> do
-  state <- getExtraState -< ()
-  let anchor = uniqueIdent (toList title) (Set.fromList $ usedAnchors state)
-  modifyExtraState (putPrettyAnchor anchor anchor) -<< anchor
-
-
---------------------------------------------------------------------------------
--- Working with styles
---------------------------------------------------------------------------------
-
---
-readStyleByName :: OdtReader _x (StyleName, Style)
-readStyleByName =
-  findAttr NsText "style-name" >>? keepingTheValue getStyleByName >>^ liftE
-  where
-    liftE :: (StyleName, Fallible Style) -> Fallible (StyleName, Style)
-    liftE (name, Right v) = Right (name, v)
-    liftE (_, Left v)     = Left v
-
---
-isStyleToTrace :: OdtReader Style Bool
-isStyleToTrace = findStyleFamily >>?^ (==FaText)
-
---
-withNewStyle :: OdtReaderSafe x Inlines -> OdtReaderSafe x Inlines
-withNewStyle a = proc x -> do
-  fStyle <- readStyleByName -< ()
-  case fStyle of
-    Right (styleName, _) | isCodeStyle styleName -> do
-      inlines <- a -< x
-      arr inlineCode -<< inlines
-    Right (_, style) -> do
-      mFamily    <- arr styleFamily -< style
-      fTextProps <- arr ( maybeToChoice
-                        . textProperties
-                        . styleProperties
-                        )           -< style
-      case fTextProps of
-        Right textProps -> do
-          state        <- getExtraState             -< ()
-          let triple = (state, textProps, mFamily)
-          modifier     <- arr modifierFromStyleDiff -< triple
-          fShouldTrace <- isStyleToTrace            -< style
-          case fShouldTrace of
-            Right shouldTrace ->
-              if shouldTrace
-                then do
-                  pushStyle      -< style
-                  inlines   <- a -< x
-                  popStyle       -< ()
-                  arr modifier   -<< inlines
-                else
-    -- In case anything goes wrong
-                      a -< x
-            Left _ -> a -< x
-        Left _     -> a -< x
-    Left _         -> a -< x
-  where
-    isCodeStyle :: StyleName -> Bool
-    isCodeStyle "Source_Text" = True
-    isCodeStyle _             = False
-
-    inlineCode :: Inlines -> Inlines
-    inlineCode = code . intercalate "" . map stringify . toList
-
-type PropertyTriple = (ReaderState, TextProperties, Maybe StyleFamily)
-type InlineModifier = Inlines -> Inlines
-
--- | Given data about the local style changes, calculates how to modify
--- an instance of 'Inlines'
-modifierFromStyleDiff :: PropertyTriple -> InlineModifier
-modifierFromStyleDiff propertyTriple  =
-  composition $
-  (getVPosModifier propertyTriple)
-  : map (first ($ propertyTriple) >>> ifThen_else ignore)
-        [ (hasEmphChanged           , emph      )
-        , (hasChanged isStrong      , strong    )
-        , (hasChanged strikethrough , strikeout )
-        ]
-  where
-    ifThen_else else' (if',then') = if if' then then' else else'
-
-    ignore = id :: InlineModifier
-
-    getVPosModifier :: PropertyTriple -> InlineModifier
-    getVPosModifier triple@(_,textProps,_) =
-        let getVPos = Just . verticalPosition
-        in  case lookupPreviousValueM getVPos triple of
-              Nothing      -> ignore
-              Just oldVPos -> getVPosModifier' (oldVPos, verticalPosition textProps)
-
-    getVPosModifier' (oldVPos , newVPos   ) | oldVPos == newVPos = ignore
-    getVPosModifier' ( _      , VPosSub   ) = subscript
-    getVPosModifier' ( _      , VPosSuper ) = superscript
-    getVPosModifier' ( _      ,  _        ) = ignore
-
-    hasEmphChanged :: PropertyTriple -> Bool
-    hasEmphChanged = swing any [ hasChanged  isEmphasised
-                               , hasChangedM pitch
-                               , hasChanged  underline
-                               ]
-
-    hasChanged property triple@(_, property -> newProperty, _) =
-        maybe True (/=newProperty) (lookupPreviousValue property triple)
-
-    hasChangedM property triple@(_, textProps,_) =
-      fromMaybe False $ (/=) <$> property textProps <*> lookupPreviousValueM property triple
-
-    lookupPreviousValue f = lookupPreviousStyleValue (fmap f . textProperties)
-
-    lookupPreviousValueM f = lookupPreviousStyleValue ((f =<<).textProperties)
-
-    lookupPreviousStyleValue f (ReaderState{..},_,mFamily)
-      =     ( findBy f $ extendedStylePropertyChain styleTrace styleSet )
-        <|> ( f =<< fmap (lookupDefaultStyle' styleSet) mFamily         )
-
-
-type ParaModifier = Blocks -> Blocks
-
-_MINIMUM_INDENTATION_FOR_BLOCKQUOTES_IN_MM_      :: Int
-_MINIMUM_INDENTATION_FOR_BLOCKQUOTES_IN_PERCENT_ :: Int
-_MINIMUM_INDENTATION_FOR_BLOCKQUOTES_IN_MM_      = 5
-_MINIMUM_INDENTATION_FOR_BLOCKQUOTES_IN_PERCENT_ = 5
-
--- | Returns either 'id' or 'blockQuote' depending on the current indentation
-getParaModifier :: Style -> ParaModifier
-getParaModifier Style{..} | Just props <- paraProperties styleProperties
-                          , isBlockQuote (indentation props)
-                                         (margin_left props)
-                          = blockQuote
-                          | otherwise
-                          = id
-  where
-  isBlockQuote mIndent mMargin
-    | LengthValueMM indent <- mIndent
-    ,  indent          > _MINIMUM_INDENTATION_FOR_BLOCKQUOTES_IN_MM_
-     = True
-    | LengthValueMM margin <- mMargin
-    ,           margin > _MINIMUM_INDENTATION_FOR_BLOCKQUOTES_IN_MM_
-     = True
-    | LengthValueMM indent <- mIndent
-    , LengthValueMM margin <- mMargin
-     = indent + margin > _MINIMUM_INDENTATION_FOR_BLOCKQUOTES_IN_MM_
-
-    | PercentValue  indent <- mIndent
-    ,  indent          > _MINIMUM_INDENTATION_FOR_BLOCKQUOTES_IN_PERCENT_
-     = True
-    | PercentValue  margin <- mMargin
-    ,           margin > _MINIMUM_INDENTATION_FOR_BLOCKQUOTES_IN_PERCENT_
-     = True
-    | PercentValue  indent <- mIndent
-    , PercentValue  margin <- mMargin
-     = indent + margin > _MINIMUM_INDENTATION_FOR_BLOCKQUOTES_IN_PERCENT_
-
-    | otherwise
-     = False
-
---
-constructPara :: OdtReaderSafe Blocks Blocks -> OdtReaderSafe Blocks Blocks
-constructPara reader = proc blocks -> do
-  fStyle <- readStyleByName -< blocks
-  case fStyle of
-    Left   _    -> reader -< blocks
-    Right (styleName, _) | isTableCaptionStyle styleName -> do
-      blocks' <- reader   -< blocks
-      arr tableCaptionP  -< blocks'
-    Right (_, style) -> do
-      let modifier = getParaModifier style
-      blocks' <- reader   -<  blocks
-      arr modifier        -<< blocks'
-  where
-    isTableCaptionStyle :: StyleName -> Bool
-    isTableCaptionStyle "Table" = True
-    isTableCaptionStyle _       = False
-    tableCaptionP b = divWith ("", ["caption"], []) b
-
-type ListConstructor = [Blocks] -> Blocks
-
-getListConstructor :: ListLevelStyle -> ListConstructor
-getListConstructor ListLevelStyle{..} =
-  case listLevelType of
-    LltBullet   -> bulletList
-    LltImage    -> bulletList
-    LltNumbered -> let listNumberStyle = toListNumberStyle listItemFormat
-                       listNumberDelim = toListNumberDelim listItemPrefix
-                                                           listItemSuffix
-                   in  orderedListWith (listItemStart, listNumberStyle, listNumberDelim)
-  where
-    toListNumberStyle  LinfNone      = DefaultStyle
-    toListNumberStyle  LinfNumber    = Decimal
-    toListNumberStyle  LinfRomanLC   = LowerRoman
-    toListNumberStyle  LinfRomanUC   = UpperRoman
-    toListNumberStyle  LinfAlphaLC   = LowerAlpha
-    toListNumberStyle  LinfAlphaUC   = UpperAlpha
-    toListNumberStyle (LinfString _) = Example
-
-    toListNumberDelim  Nothing   (Just ".") = Period
-    toListNumberDelim (Just "" ) (Just ".") = Period
-    toListNumberDelim  Nothing   (Just ")") = OneParen
-    toListNumberDelim (Just "" ) (Just ")") = OneParen
-    toListNumberDelim (Just "(") (Just ")") = TwoParens
-    toListNumberDelim     _          _      = DefaultDelim
-
-
--- | Determines which style to use for a list, which level to use of that
--- style, and which type of list to create as a result of this information.
--- Then prepares the state for eventual child lists and constructs the list from
--- the results.
--- Two main cases are handled: The list may provide its own style or it may
--- rely on a parent list's style. I the former case the current style in the
--- state must be switched before and after the call to the child converter
--- while in the latter the child converter can be called directly.
--- If anything goes wrong, a default ordered-list-constructor is used.
-constructList :: OdtReaderSafe x [Blocks] -> OdtReaderSafe x Blocks
-constructList reader = proc x -> do
-  modifyExtraState (shiftListLevel 1)        -< ()
-  listLevel  <- getCurrentListLevel          -< ()
-  fStyleName <- findAttr NsText "style-name" -< ()
-  case fStyleName of
-    Right styleName -> do
-      fListStyle <- lookupListStyle -< styleName
-      case fListStyle of
-        Right listStyle -> do
-          fLLS <- arr (uncurry getListLevelStyle) -< (listLevel,listStyle)
-          case fLLS of
-            Just listLevelStyle -> do
-              oldListStyle <- switchCurrentListStyle           -<  Just listStyle
-              blocks       <- constructListWith listLevelStyle -<< x
-              switchCurrentListStyle                           -<  oldListStyle
-              returnA                                          -<  blocks
-            Nothing             -> constructOrderedList        -< x
-        Left _                  -> constructOrderedList        -< x
-    Left _ -> do
-      state      <- getExtraState        -< ()
-      mListStyle <- arr currentListStyle -< state
-      case mListStyle of
-        Just listStyle -> do
-          fLLS <- arr (uncurry getListLevelStyle) -< (listLevel,listStyle)
-          case fLLS of
-            Just listLevelStyle -> constructListWith listLevelStyle -<< x
-            Nothing             -> constructOrderedList             -<  x
-        Nothing                 -> constructOrderedList             -<  x
-  where
-    constructOrderedList =
-          reader
-      >>> modifyExtraState (shiftListLevel (-1))
-      >>^ orderedList
-    constructListWith listLevelStyle =
-          reader
-      >>> getListConstructor listLevelStyle
-      ^>> modifyExtraState (shiftListLevel (-1))
-
---------------------------------------------------------------------------------
--- Readers
---------------------------------------------------------------------------------
-
-type ElementMatcher result = (Namespace, ElementName, OdtReader result result)
-
-type InlineMatcher = ElementMatcher Inlines
-
-type BlockMatcher  = ElementMatcher Blocks
-
-
---
-matchingElement :: (Monoid e)
-                => Namespace -> ElementName
-                -> OdtReaderSafe  e e
-                -> ElementMatcher e
-matchingElement ns name reader = (ns, name, asResultAccumulator reader)
-  where
-   asResultAccumulator :: (ArrowChoice a, Monoid m) => a m m -> a m (Fallible m)
-   asResultAccumulator a = liftAsSuccess $ keepingTheValue a >>% (<>)
-
---
-matchChildContent'   :: (Monoid result)
-                     => [ElementMatcher result]
-                     ->  OdtReaderSafe _x result
-matchChildContent' ls = returnV mempty >>> matchContent' ls
-
---
-matchChildContent    :: (Monoid result)
-                     => [ElementMatcher result]
-                     ->  OdtReaderSafe  (result, XML.Content) result
-                     ->  OdtReaderSafe _x result
-matchChildContent ls fallback = returnV mempty >>> matchContent ls fallback
-
-
---------------------------------------------
--- Matchers
---------------------------------------------
-
-----------------------
--- Basics
-----------------------
-
---
--- | Open Document allows several consecutive spaces if they are marked up
-read_plain_text :: OdtReaderSafe (Inlines, XML.Content) Inlines
-read_plain_text =  fst ^&&& read_plain_text' >>% recover
-  where
-    -- fallible version
-    read_plain_text' :: OdtReader (Inlines, XML.Content) Inlines
-    read_plain_text' =      (     second ( arr extractText )
-                              >>^ spreadChoice >>?! second text
-                            )
-                       >>?% (<>)
-    --
-    extractText     :: XML.Content -> Fallible String
-    extractText (XML.Text cData) = succeedWith (XML.cdData cData)
-    extractText         _        = failEmpty
-
-read_text_seq :: InlineMatcher
-read_text_seq  = matchingElement NsText "sequence"
-                 $ matchChildContent [] read_plain_text
-
-
--- specifically. I honor that, although the current implementation of '(<>)'
--- for 'Inlines' in "Text.Pandoc.Builder" will collapse them again.
--- The rational is to be prepared for future modifications.
-read_spaces      :: InlineMatcher
-read_spaces       = matchingElement NsText "s" (
-                          readAttrWithDefault NsText "c" 1 -- how many spaces?
-                      >>^ fromList.(`replicate` Space)
-                    )
---
-read_line_break  :: InlineMatcher
-read_line_break   = matchingElement NsText "line-break"
-                    $ returnV linebreak
-
---
-read_span        :: InlineMatcher
-read_span         = matchingElement NsText "span"
-                    $ withNewStyle
-                    $ matchChildContent [ read_span
-                                        , read_spaces
-                                        , read_line_break
-                                        , read_link
-                                        , read_note
-                                        , read_citation
-                                        , read_bookmark
-                                        , read_bookmark_start
-                                        , read_reference_start
-                                        , read_bookmark_ref
-                                        , read_reference_ref
-                                        ] read_plain_text
-
---
-read_paragraph   :: BlockMatcher
-read_paragraph    = matchingElement NsText "p"
-                    $ constructPara
-                    $ liftA para
-                    $ withNewStyle
-                    $ matchChildContent [ read_span
-                                        , read_spaces
-                                        , read_line_break
-                                        , read_link
-                                        , read_note
-                                        , read_citation
-                                        , read_bookmark
-                                        , read_bookmark_start
-                                        , read_reference_start
-                                        , read_bookmark_ref
-                                        , read_reference_ref
-                                        , read_maybe_nested_img_frame
-                                        , read_text_seq
-                                        ] read_plain_text
-
-
-----------------------
--- Headers
-----------------------
-
---
-read_header      :: BlockMatcher
-read_header       = matchingElement NsText "h"
-                    $  proc blocks -> do
-  level    <- ( readAttrWithDefault NsText "outline-level" 1
-              ) -< blocks
-  children <- ( matchChildContent [ read_span
-                                  , read_spaces
-                                  , read_line_break
-                                  , read_link
-                                  , read_note
-                                  , read_citation
-                                  , read_bookmark
-                                  , read_bookmark_start
-                                  , read_reference_start
-                                  , read_bookmark_ref
-                                  , read_reference_ref
-                                  , read_maybe_nested_img_frame
-                                  ] read_plain_text
-              ) -< blocks
-  anchor   <- getHeaderAnchor -< children
-  let idAttr = (anchor, [], []) -- no classes, no key-value pairs
-  arr (uncurry3 headerWith) -< (idAttr, level, children)
-
-----------------------
--- Lists
-----------------------
-
---
-read_list        :: BlockMatcher
-read_list         = matchingElement NsText "list"
---                  $ withIncreasedListLevel
-                    $ constructList
---                  $ liftA bulletList
-                    $ matchChildContent' [ read_list_item
-                                         ]
---
-read_list_item   :: ElementMatcher [Blocks]
-read_list_item    = matchingElement NsText "list-item"
-                    $ liftA (compactify.(:[]))
-                      ( matchChildContent' [ read_paragraph
-                                           , read_header
-                                           , read_list
-                                           ]
-                      )
-
-
-----------------------
--- Links
-----------------------
-
-read_link        :: InlineMatcher
-read_link         = matchingElement NsText "a"
-                    $ liftA3 link
-                      ( findAttrWithDefault NsXLink  "href"  ""              )
-                      ( findAttrWithDefault NsOffice "title" ""              )
-                      ( matchChildContent [ read_span
-                                          , read_note
-                                          , read_citation
-                                          , read_bookmark
-                                          , read_bookmark_start
-                                          , read_reference_start
-                                          , read_bookmark_ref
-                                          , read_reference_ref
-                                          ] read_plain_text                  )
-
-
--------------------------
--- Footnotes
--------------------------
-
-read_note        :: InlineMatcher
-read_note         = matchingElement NsText "note"
-                    $ liftA note
-                    $ matchChildContent' [ read_note_body ]
-
-read_note_body   :: BlockMatcher
-read_note_body    = matchingElement NsText "note-body"
-                    $ matchChildContent' [ read_paragraph ]
-
--------------------------
--- Citations
--------------------------
-
-read_citation    :: InlineMatcher
-read_citation     = matchingElement NsText "bibliography-mark"
-                    $ liftA2 cite
-                      ( liftA2 makeCitation
-                        ( findAttrWithDefault NsText "identifier" ""     )
-                        ( readAttrWithDefault NsText "number" 0          )
-                      )
-                      ( matchChildContent [] read_plain_text             )
-  where
-   makeCitation :: String -> Int -> [Citation]
-   makeCitation citeId num = [Citation citeId [] [] NormalCitation num 0]
-
-
-----------------------
--- Tables
-----------------------
-
---
-read_table        :: BlockMatcher
-read_table         = matchingElement NsTable "table"
-                     $ liftA simpleTable'
-                     $ matchChildContent'  [ read_table_row
-                                           ]
-
--- | A simple table without a caption or headers
--- | Infers the number of headers from rows
-simpleTable' :: [[Blocks]] -> Blocks
-simpleTable' []         = simpleTable [] []
-simpleTable' (x : rest) = simpleTable (fmap (const defaults) x) (x : rest)
-  where defaults = fromList []
-
---
-read_table_row    :: ElementMatcher [[Blocks]]
-read_table_row     = matchingElement NsTable "table-row"
-                     $ liftA (:[])
-                     $ matchChildContent'  [ read_table_cell
-                                           ]
-
---
-read_table_cell   :: ElementMatcher [Blocks]
-read_table_cell    = matchingElement NsTable "table-cell"
-                     $ liftA (compactify.(:[]))
-                     $ matchChildContent' [ read_paragraph
-                                          ]
-
-----------------------
--- Images
-----------------------
-
---
-read_maybe_nested_img_frame  :: InlineMatcher
-read_maybe_nested_img_frame   = matchingElement NsDraw "frame"
-                                $ proc blocks -> do
-                                   img <- (findChild' NsDraw "image") -< ()
-                                   case img of
-                                     Just _  ->  read_frame                                 -< blocks
-                                     Nothing ->  matchChildContent' [ read_frame_text_box ] -< blocks
-
-read_frame :: OdtReaderSafe Inlines Inlines
-read_frame =
-  proc blocks -> do
-   w          <- ( findAttr' NsSVG "width" )                 -< ()
-   h          <- ( findAttr' NsSVG "height" )                -< ()
-   titleNodes <- ( matchChildContent' [ read_frame_title ] ) -< blocks
-   src        <-  matchChildContent' [ read_image_src ]      -< blocks
-   resource   <- lookupResource                              -< src
-   _          <- updateMediaWithResource                     -< resource
-   alt        <- (matchChildContent [] read_plain_text)      -< blocks
-   arr (uncurry4 imageWith ) -<
-                (image_attributes w h, src, inlineListToIdentifier (toList titleNodes), alt)
-
-image_attributes :: Maybe String -> Maybe String -> Attr
-image_attributes x y =
-  ( "", [], (dim "width" x) ++ (dim "height" y))
-  where
-    dim _ (Just "")   = []
-    dim name (Just v) = [(name, v)]
-    dim _ Nothing     = []
-
-read_image_src :: (Namespace, ElementName, OdtReader Anchor Anchor)
-read_image_src = matchingElement NsDraw "image"
-                 $ proc _ -> do
-                    imgSrc <- findAttr NsXLink "href" -< ()
-                    case imgSrc of
-                      Right src -> returnV src -<< ()
-                      Left _    -> returnV ""  -< ()
-
-read_frame_title :: InlineMatcher
-read_frame_title = matchingElement NsSVG "title"
-                   $ (matchChildContent [] read_plain_text)
-
-read_frame_text_box :: InlineMatcher
-read_frame_text_box = matchingElement NsDraw "text-box"
-                      $ proc blocks -> do
-                         paragraphs <- (matchChildContent' [ read_paragraph ]) -< blocks
-                         arr read_img_with_caption                             -< toList paragraphs
-
-read_img_with_caption :: [Block] -> Inlines
-read_img_with_caption ((Para [Image attr alt (src,title)]) : _) =
-  singleton (Image attr alt (src, 'f':'i':'g':':':title))   -- no text, default caption
-read_img_with_caption (Para (Image attr _ (src,title) : txt) : _) =
-  singleton (Image attr txt (src, 'f':'i':'g':':':title) )  -- override caption with the text that follows
-read_img_with_caption  ( (Para (_ : xs)) : ys) =
-  read_img_with_caption ((Para xs) : ys)
-read_img_with_caption _ =
-  mempty
-
-----------------------
--- Internal links
-----------------------
-
-_ANCHOR_PREFIX_ :: String
-_ANCHOR_PREFIX_ = "anchor"
-
---
-readAnchorAttr :: OdtReader _x Anchor
-readAnchorAttr = findAttr NsText "name"
-
--- | Beware: may fail
-findAnchorName :: OdtReader AnchorPrefix Anchor
-findAnchorName = (      keepingTheValue readAnchorAttr
-                   >>^  spreadChoice
-                 ) >>?! getPrettyAnchor
-
-
---
-maybeAddAnchorFrom :: OdtReader Inlines AnchorPrefix
-                   -> OdtReaderSafe Inlines Inlines
-maybeAddAnchorFrom anchorReader =
-  keepingTheValue (anchorReader >>? findAnchorName >>?^ toAnchorElem)
-  >>>
-  proc (inlines, fAnchorElem) -> do
-  case fAnchorElem of
-    Right anchorElem -> returnA -< anchorElem
-    Left _           -> returnA -< inlines
-  where
-    toAnchorElem :: Anchor -> Inlines
-    toAnchorElem anchorID = spanWith (anchorID, [], []) mempty
-                            -- no classes, no key-value pairs
-
---
-read_bookmark     :: InlineMatcher
-read_bookmark      = matchingElement NsText "bookmark"
-                     $ maybeAddAnchorFrom (liftAsSuccess $ returnV _ANCHOR_PREFIX_)
-
---
-read_bookmark_start :: InlineMatcher
-read_bookmark_start = matchingElement NsText "bookmark-start"
-                     $ maybeAddAnchorFrom (liftAsSuccess $ returnV _ANCHOR_PREFIX_)
-
---
-read_reference_start :: InlineMatcher
-read_reference_start = matchingElement NsText "reference-mark-start"
-                     $ maybeAddAnchorFrom readAnchorAttr
-
--- | Beware: may fail
-findAnchorRef :: OdtReader _x Anchor
-findAnchorRef = (      findAttr NsText "ref-name"
-                  >>?^ (_ANCHOR_PREFIX_,)
-                ) >>?! getPrettyAnchor
-
-
---
-maybeInAnchorRef :: OdtReaderSafe Inlines Inlines
-maybeInAnchorRef = proc inlines -> do
-  fRef <- findAnchorRef -< ()
-  case fRef of
-    Right anchor ->
-      arr (toAnchorRef anchor) -<< inlines
-    Left _ -> returnA -< inlines
-  where
-    toAnchorRef :: Anchor -> Inlines -> Inlines
-    toAnchorRef anchor = link ('#':anchor) "" -- no title
-
---
-read_bookmark_ref :: InlineMatcher
-read_bookmark_ref = matchingElement NsText "bookmark-ref"
-                    $    maybeInAnchorRef
-                     <<< matchChildContent [] read_plain_text
-
---
-read_reference_ref :: InlineMatcher
-read_reference_ref = matchingElement NsText "reference-ref"
-                    $    maybeInAnchorRef
-                     <<< matchChildContent [] read_plain_text
-
-
-----------------------
--- Entry point
-----------------------
-
-read_text :: OdtReaderSafe _x Pandoc
-read_text = matchChildContent' [ read_header
-                               , read_paragraph
-                               , read_list
-                               , read_table
-                               ]
-            >>^ doc
-
-post_process :: Pandoc -> Pandoc
-post_process (Pandoc m blocks) =
-  Pandoc m (post_process' blocks)
-
-post_process' :: [Block] -> [Block]
-post_process' ((Table _ a w h r) : (Div ("", ["caption"], _) [Para inlines] ) : xs) =
-  (Table inlines a w h r) : ( post_process' xs )
-post_process' bs = bs
-
-read_body :: OdtReader _x (Pandoc, MediaBag)
-read_body = executeIn NsOffice "body"
-          $ executeIn NsOffice "text"
-          $ liftAsSuccess
-          $ proc inlines -> do
-             txt   <- read_text     -< inlines
-             state <- getExtraState -< ()
-             returnA                -< (post_process txt, getMediaBag state)
diff --git a/src/Text/Pandoc/Readers/Odt/Generic/Fallible.hs b/src/Text/Pandoc/Readers/Odt/Generic/Fallible.hs
deleted file mode 100644
--- a/src/Text/Pandoc/Readers/Odt/Generic/Fallible.hs
+++ /dev/null
@@ -1,126 +0,0 @@
-
-
-{-
-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
-   License     : GNU GPL, version 2 or above
-
-   Maintainer  : Martin Linnemann <theCodingMarlin@googlemail.com>
-   Stability   : alpha
-   Portability : portable
-
-Data types and utilities representing failure. Most of it is based on the
-"Either" type in its usual configuration (left represents failure).
-
-In most cases, the failure type is implied or required to be a "Monoid".
-
-The choice of "Either" instead of a custom type makes it easier to write
-compatible instances of "ArrowChoice".
--}
-
--- We export everything
-module Text.Pandoc.Readers.Odt.Generic.Fallible where
-
-import Data.Monoid ((<>))
-
--- | Default for now. Will probably become a class at some point.
-type Failure = ()
-
-type Fallible a = Either Failure a
-
-
---
-maybeToEither :: Maybe a -> Fallible a
-maybeToEither (Just a) = Right a
-maybeToEither Nothing  = Left  ()
-
---
-eitherToMaybe :: Either _l a -> Maybe a
-eitherToMaybe (Left  _) = Nothing
-eitherToMaybe (Right a) = Just a
-
--- | > fromLeft f === either f id
-fromLeft :: (a -> b) -> Either a b -> b
-fromLeft f (Left  a) = f a
-fromLeft _ (Right b) = b
-
--- | > recover a === fromLeft (const a) === either (const a) id
-recover :: a -> Either _f a -> a
-recover a (Left  _) = a
-recover _ (Right a) = a
-
--- | I would love to use 'fail'. Alas, 'Monad.fail'...
-failWith :: failure -> Either failure _x
-failWith f = Left f
-
---
-failEmpty :: (Monoid failure) => Either failure _x
-failEmpty = failWith mempty
-
---
-succeedWith :: a -> Either _x a
-succeedWith = Right
-
---
-collapseEither :: Either failure (Either failure x)
-               -> Either failure x
-collapseEither (Left f         ) = Left f
-collapseEither (Right (Left  f)) = Left f
-collapseEither (Right (Right x)) = Right x
-
--- | If either of the values represents a  non-error, the result is a
--- (possibly combined) non-error. If both values represent an error, an error
--- is returned.
-chooseMax :: (Monoid a, Monoid b) => Either a b -> Either a b -> Either a b
-chooseMax = chooseMaxWith (<>)
-
--- | If either of the values represents a non-error, the result is a
--- (possibly combined) non-error. If both values represent an error, an error
--- is returned.
-chooseMaxWith :: (Monoid a) => (b -> b -> b)
-                            -> Either a b
-                            -> Either a b
-                            -> Either a b
-chooseMaxWith (><) (Right a) (Right b) = Right $ a >< b
-chooseMaxWith  _   (Left  a) (Left  b) = Left  $ a <> b
-chooseMaxWith  _   (Right a)     _     = Right a
-chooseMaxWith  _       _     (Right b) = Right b
-
-
--- | Class of containers that can escalate contained 'Either's.
--- The word "Vector" is meant in the sense of a disease transmitter.
-class ChoiceVector v where
-  spreadChoice :: v (Either f a) -> Either f (v a)
-
-instance ChoiceVector ((,) a) where
-  spreadChoice (_, Left  f) = Left  f
-  spreadChoice (x, Right y) = Right (x,y)
-  -- Wasn't there a newtype somewhere with the elements flipped?
-
--- | Wrapper for a list. While the normal list instance of 'ChoiceVector'
--- fails whenever it can, this type will never fail.
-newtype SuccessList a = SuccessList { collectNonFailing :: [a] }
-  deriving ( Eq, Ord, Show )
-
-instance ChoiceVector SuccessList  where
-  spreadChoice = Right . SuccessList . foldr unTagRight [] . collectNonFailing
-    where unTagRight (Right x) = (x:)
-          unTagRight _         = id
diff --git a/src/Text/Pandoc/Readers/Odt/Generic/Namespaces.hs b/src/Text/Pandoc/Readers/Odt/Generic/Namespaces.hs
deleted file mode 100644
--- a/src/Text/Pandoc/Readers/Odt/Generic/Namespaces.hs
+++ /dev/null
@@ -1,62 +0,0 @@
-{-
-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
-   License     : GNU GPL, version 2 or above
-
-   Maintainer  : Martin Linnemann <theCodingMarlin@googlemail.com>
-   Stability   : alpha
-   Portability : portable
-
-A class containing a set of namespace identifiers. Used to convert between
-typesafe Haskell namespace identifiers and unsafe "real world" namespaces.
--}
-
-module Text.Pandoc.Readers.Odt.Generic.Namespaces where
-
-import qualified Data.Map as M
-
---
-type NameSpaceIRI          = String
-
---
-type NameSpaceIRIs     nsID = M.Map nsID NameSpaceIRI
-
---
-class (Eq nsID, Ord nsID) => NameSpaceID nsID where
-
-  -- | Given a IRI, possibly update the map and return the id of the namespace.
-  -- May fail if the namespace is unknown and the application does not
-  -- allow unknown namespaces.
-  getNamespaceID   :: NameSpaceIRI
-                      -> NameSpaceIRIs nsID
-                      -> Maybe (NameSpaceIRIs nsID, nsID)
-  -- | Given a namespace id, lookup its IRI. May be overriden for performance.
-  getIRI           :: nsID
-                      -> NameSpaceIRIs nsID
-                      -> Maybe NameSpaceIRI
-  -- | The root element of an XML document has a namespace, too, and the
-  -- "XML.Light-parser" is eager to remove the corresponding namespace
-  -- attribute.
-  -- As a result, at least this root namespace must be provided.
-  getInitialIRImap :: NameSpaceIRIs nsID
-
-  getIRI           = M.lookup
-  getInitialIRImap = M.empty
diff --git a/src/Text/Pandoc/Readers/Odt/Generic/SetMap.hs b/src/Text/Pandoc/Readers/Odt/Generic/SetMap.hs
deleted file mode 100644
--- a/src/Text/Pandoc/Readers/Odt/Generic/SetMap.hs
+++ /dev/null
@@ -1,48 +0,0 @@
-{-
-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
-   License     : GNU GPL, version 2 or above
-
-   Maintainer  : Martin Linnemann <theCodingMarlin@googlemail.com>
-   Stability   : alpha
-   Portability : portable
-
-A map of values to sets of values.
--}
-
-module Text.Pandoc.Readers.Odt.Generic.SetMap where
-
-import qualified Data.Map as M
-import qualified Data.Set as S
-
-type SetMap k v = M.Map k (S.Set v)
-
-empty :: SetMap k v
-empty = M.empty
-
-fromList :: (Ord k, Ord v) => [(k,v)] -> SetMap k v
-fromList = foldr (uncurry insert) empty
-
-insert :: (Ord k, Ord v) => k -> v -> SetMap k v -> SetMap k v
-insert key value setMap = M.insertWith S.union key (S.singleton value) setMap
-
-union3 :: (Ord k) => SetMap k v -> SetMap k v -> SetMap k v -> SetMap k v
-union3 sm1 sm2 sm3 = sm1 `M.union` sm2 `M.union` sm3
diff --git a/src/Text/Pandoc/Readers/Odt/Generic/Utils.hs b/src/Text/Pandoc/Readers/Odt/Generic/Utils.hs
deleted file mode 100644
--- a/src/Text/Pandoc/Readers/Odt/Generic/Utils.hs
+++ /dev/null
@@ -1,164 +0,0 @@
-
-
-{-# 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
-   License     : GNU GPL, version 2 or above
-
-   Maintainer  : Martin Linnemann <theCodingMarlin@googlemail.com>
-   Stability   : alpha
-   Portability : portable
-
-General utility functions for the odt reader.
--}
-
-module Text.Pandoc.Readers.Odt.Generic.Utils
-( uncurry3
-, uncurry4
-, uncurry5
-, uncurry6
-, swap
-, reverseComposition
-, bool
-, tryToRead
-, Lookupable(..)
-, readLookupables
-, readLookupable
-, readPercent
-, findBy
-, swing
-, composition
-) where
-
-import Control.Category (Category, (<<<), (>>>))
-import qualified Control.Category as Cat (id)
-import Control.Monad (msum)
-
-import qualified Data.Foldable as F (Foldable, foldr)
-import Data.Maybe
-
-
--- | Aequivalent to
--- > foldr (.) id
--- where '(.)' are 'id' are the ones from "Control.Category"
--- and 'foldr' is the one from "Data.Foldable".
--- The noun-form was chosen to be consistend with 'sum', 'product' etc
--- based on the discussion at
--- <https://groups.google.com/forum/#!topic/haskell-cafe/VkOZM1zaHOI>
--- (that I was not part of)
-composition        :: (Category cat, F.Foldable f) => f (cat a a) -> cat a a
-composition        = F.foldr (<<<) Cat.id
-
--- | Aequivalent to
--- > foldr (flip (.)) id
--- where '(.)' are 'id' are the ones from "Control.Category"
--- and 'foldr' is the one from "Data.Foldable".
--- A reversed version of 'composition'.
-reverseComposition :: (Category cat, F.Foldable f) => f (cat a a) -> cat a a
-reverseComposition = F.foldr (>>>) Cat.id
-
--- | 'Either' has 'either', 'Maybe' has 'maybe'. 'Bool' should have 'bool'.
--- Note that the first value is selected if the boolean value is 'False'.
--- That makes 'bool' consistent with the other two. Also, 'bool' now takes its
--- arguments in the exact opposite order compared to the normal if construct.
-bool :: a -> a -> Bool -> a
-bool x _ False = x
-bool _ x True  = x
-
--- | This function often makes it possible to switch values with the functions
--- that are applied to them.
---
--- Examples:
--- > swing map :: [a -> b] -> a -> [b]
--- > swing any :: [a -> Bool] -> a -> Bool
--- > swing foldr :: b -> a -> [a -> b -> b] -> b
--- > swing scanr :: c -> a -> [a -> c -> c] -> c
--- > swing zipWith :: [a -> b -> c] -> a -> [b] -> [c]
--- > swing find :: [a -> Bool] -> a -> Maybe (a -> Bool)
---
--- Stolen from <https://wiki.haskell.org/Pointfree>
-swing :: (((a -> b) -> b) -> c -> d) -> c -> a -> d
-swing = flip.(.flip id)
--- swing f c a = f ($ a) c
-
-
--- | Alternative to 'read'/'reads'. The former of these throws errors
--- (nobody wants that) while the latter returns "to much" for simple purposes.
--- This function instead applies 'reads' and returns the first match (if any)
--- in a 'Maybe'.
-tryToRead :: (Read r) => String -> Maybe r
-tryToRead = reads >>> listToMaybe >>> fmap fst
-
--- | A version of 'reads' that requires a '%' sign after the number
-readPercent :: ReadS Int
-readPercent s = [ (i,s') | (i   , r ) <- reads s
-                         , ("%" , s') <- lex   r
-              ]
-
--- | Data that can be looked up.
--- This is mostly a utility to read data with kind *.
-class Lookupable a where
-  lookupTable :: [(String, a)]
-
--- | The idea is to use this function as if there was a declaration like
---
--- > instance (Lookupable a) => (Read a) where
--- >   readsPrec _ = readLookupables
--- .
--- But including this code in this form would need UndecideableInstances.
--- That is a bad idea. Luckily 'readLookupable' (without the s at the end)
--- can be used directly in almost any case.
-readLookupables :: (Lookupable a) => String -> [(a,String)]
-readLookupables s = [ (a,rest) | (word,rest) <- lex s,
-                                 let result = lookup word lookupTable,
-                                 isJust result,
-                                 let Just a = result
-                    ]
-
--- | Very similar to a simple 'lookup' in the 'lookupTable', but with a lexer.
-readLookupable :: (Lookupable a) => String -> Maybe a
-readLookupable s = msum
-                 $ map ((`lookup` lookupTable).fst)
-                 $ lex s
-
-uncurry3 :: (a->b->c                -> z) -> (a,b,c          ) -> z
-uncurry4 :: (a->b->c->d             -> z) -> (a,b,c,d        ) -> z
-uncurry5 :: (a->b->c->d->e          -> z) -> (a,b,c,d,e      ) -> z
-uncurry6 :: (a->b->c->d->e->f       -> z) -> (a,b,c,d,e,f    ) -> z
-
-uncurry3 fun (a,b,c          ) = fun a b c
-uncurry4 fun (a,b,c,d        ) = fun a b c d
-uncurry5 fun (a,b,c,d,e      ) = fun a b c d e
-uncurry6 fun (a,b,c,d,e,f    ) = fun a b c d e f
-
-swap :: (a,b) -> (b,a)
-swap (a,b) = (b,a)
-
--- | A version of "Data.List.find" that uses a converter to a Maybe instance.
--- The returned value is the first which the converter returns in a 'Just'
--- wrapper.
-findBy :: (a -> Maybe b) -> [a] -> Maybe b
-findBy _               []   = Nothing
-findBy f ((f -> Just x):_ ) = Just x
-findBy f (            _:xs) = findBy f xs
diff --git a/src/Text/Pandoc/Readers/Odt/Generic/XMLConverter.hs b/src/Text/Pandoc/Readers/Odt/Generic/XMLConverter.hs
deleted file mode 100644
--- a/src/Text/Pandoc/Readers/Odt/Generic/XMLConverter.hs
+++ /dev/null
@@ -1,744 +0,0 @@
-{-# LANGUAGE Arrows          #-}
-{-# LANGUAGE TupleSections   #-}
-{-# 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
-   License     : GNU GPL, version 2 or above
-
-   Maintainer  : Martin Linnemann <theCodingMarlin@googlemail.com>
-   Stability   : alpha
-   Portability : portable
-
-A generalized XML parser based on stateful arrows.
-It might be sufficient to define this reader as a comonad, but there is
-not a lot of use in trying.
--}
-
-module Text.Pandoc.Readers.Odt.Generic.XMLConverter
-( ElementName
-, XMLConverterState
-, XMLConverter
-, FallibleXMLConverter
-, runConverter'
-, getExtraState
-, setExtraState
-, modifyExtraState
-, producingExtraState
-, findChild'
-, isSet'
-, isSetWithDefault
-, searchAttr
-, lookupAttr
-, lookupAttr'
-, lookupDefaultingAttr
-, findAttr'
-, findAttr
-, findAttrWithDefault
-, readAttr
-, readAttr'
-, readAttrWithDefault
-, getAttr
-, executeIn
-, withEveryL
-, tryAll
-, matchContent'
-, matchContent
-) where
-
-import           Control.Applicative  hiding ( liftA, liftA2 )
-import           Control.Monad               ( MonadPlus )
-import           Control.Arrow
-
-import           Data.Either ( rights )
-import qualified Data.Map             as M
-import           Data.Default
-import           Data.Maybe
-
-import qualified Text.XML.Light       as XML
-
-import           Text.Pandoc.Readers.Odt.Arrows.State
-import           Text.Pandoc.Readers.Odt.Arrows.Utils
-
-import           Text.Pandoc.Readers.Odt.Generic.Namespaces
-import           Text.Pandoc.Readers.Odt.Generic.Utils
-import           Text.Pandoc.Readers.Odt.Generic.Fallible
-
---------------------------------------------------------------------------------
---  Basis types for readability
---------------------------------------------------------------------------------
-
---
-type ElementName           = String
-type AttributeName         = String
-type AttributeValue        = String
-
---
-type NameSpacePrefix       = String
-
---
-type NameSpacePrefixes nsID = M.Map nsID NameSpacePrefix
-
---------------------------------------------------------------------------------
--- Main converter state
---------------------------------------------------------------------------------
-
--- GADT so some of the NameSpaceID restrictions can be deduced
-data XMLConverterState nsID extraState where
-  XMLConverterState :: NameSpaceID nsID
-    => { -- | A stack of parent elements. The top element is the current one.
-         -- Arguably, a real Zipper would be better. But that is an
-         -- optimization that can be made at a later time, e.g. when
-         -- replacing Text.XML.Light.
-         parentElements    :: [XML.Element]
-         -- | A map from internal namespace IDs to the namespace prefixes
-         -- used in XML elements
-       , namespacePrefixes :: NameSpacePrefixes nsID
-         -- | A map from internal namespace IDs to namespace IRIs
-         -- (Only necessary for matching namespace IDs and prefixes)
-       , namespaceIRIs     :: NameSpaceIRIs nsID
-         -- | A place to put "something else". This feature is used heavily
-         -- to keep the main code cleaner. More specifically, the main reader
-         -- is divided into different stages. Each stage lifts something up
-         -- here, which the next stage can then use. This could of course be
-         -- generalized to a state-tree or used for the namespace IRIs. The
-         -- border between states and values is an imaginary one, after all.
-         -- But the separation as it is seems to be enough for now.
-       , moreState         :: extraState
-       }
-    -> XMLConverterState nsID extraState
-
---
-createStartState :: (NameSpaceID nsID)
-                    => XML.Element
-                    -> extraState
-                    -> XMLConverterState nsID extraState
-createStartState element extraState =
-  XMLConverterState
-       { parentElements    = [element]
-       , namespacePrefixes = M.empty
-       , namespaceIRIs     = getInitialIRImap
-       , moreState         = extraState
-       }
-
--- | Functor over extra state
-instance Functor (XMLConverterState nsID) where
-  fmap f ( XMLConverterState parents prefixes iRIs    extraState  )
-       =   XMLConverterState parents prefixes iRIs (f extraState)
-
---
-replaceExtraState   :: extraState
-                    -> XMLConverterState nsID _x
-                    -> XMLConverterState nsID extraState
-replaceExtraState x s
-                     = fmap (const x) s
-
---
-currentElement      :: XMLConverterState nsID extraState
-                    -> XML.Element
-currentElement state = head (parentElements state)
-
--- | Replace the current position by another, modifying the extra state
--- in the process
-swapStack'          :: XMLConverterState nsID extraState
-                    -> [XML.Element]
-                    -> ( XMLConverterState nsID extraState , [XML.Element] )
-swapStack' state stack
-                     = ( state { parentElements = stack }
-                       , parentElements state
-                       )
-
---
-pushElement         :: XML.Element
-                    -> XMLConverterState nsID extraState
-                    -> XMLConverterState nsID extraState
-pushElement e state  = state { parentElements = e:(parentElements state) }
-
--- | Pop the top element from the call stack, unless it is the last one.
-popElement          :: XMLConverterState nsID extraState
-                    -> Maybe (XMLConverterState nsID extraState)
-popElement state
-  | _:es@(_:_) <- parentElements state = Just $ state { parentElements = es }
-  | otherwise                          = Nothing
-
---------------------------------------------------------------------------------
--- Main type
---------------------------------------------------------------------------------
-
--- It might be a good idea to pack the converters in a GADT
--- Downside: data instead of type
--- Upside: 'Failure' could be made a parameter as well.
-
---
-type XMLConverter nsID extraState input output
-      = ArrowState (XMLConverterState nsID extraState ) input output
-
-type FallibleXMLConverter nsID extraState input output
-     = XMLConverter nsID extraState input (Fallible output)
-
---
-runConverter     :: XMLConverter nsID extraState input output
-                 -> XMLConverterState nsID extraState
-                 -> input
-                 -> output
-runConverter converter state input = snd $ runArrowState converter (state,input)
-
-runConverter' :: (NameSpaceID nsID)
-              => FallibleXMLConverter nsID extraState () success
-              -> extraState
-              -> XML.Element
-              -> Fallible success
-runConverter' converter extraState element = runConverter (readNSattributes >>? converter) (createStartState element extraState) ()
-
---
-getCurrentElement :: XMLConverter nsID extraState x XML.Element
-getCurrentElement  = extractFromState currentElement
-
---
-getExtraState     :: XMLConverter nsID extraState x extraState
-getExtraState      = extractFromState moreState
-
---
-setExtraState     :: XMLConverter nsID extraState extraState extraState
-setExtraState      = withState $ \state extra
-                                  -> (replaceExtraState extra state , extra)
-
-
--- | Lifts a function to the extra state.
-modifyExtraState  :: (extraState -> extraState)
-                  -> XMLConverter nsID extraState x x
-modifyExtraState   = modifyState.fmap
-
-
--- | First sets the extra state to the new value. Then modifies the original
--- extra state with a converter that uses the new state. Finally, the
--- intermediate state is dropped and the extra state is lifted into the
--- state as it was at the beginning of the function.
--- As a result, exactly the extra state and nothing else is changed.
--- The resulting converter even behaves like an identity converter on the
--- value level.
---
--- (The -ing form is meant to be mnemonic in a sequence of arrows as in
---  convertingExtraState () converter >>> doOtherStuff)
---
-convertingExtraState :: extraState'
-                     -> FallibleXMLConverter nsID extraState' extraState extraState
-                     -> FallibleXMLConverter nsID extraState x x
-convertingExtraState v a = withSubStateF setVAsExtraState modifyWithA
-  where
-    setVAsExtraState     = liftAsSuccess $ extractFromState id >>^ replaceExtraState v
-    modifyWithA          = keepingTheValue (moreState ^>> a)
-                           >>^ spreadChoice >>?% flip replaceExtraState
-
--- | First sets the extra state to the new value. Then produces a new
--- extra state with a converter that uses the new state. Finally, the
--- intermediate state is dropped and the extra state is lifted into the
--- state as it was at the beginning of the function.
--- As a result, exactly the extra state and nothing else is changed.
--- The resulting converter even behaves like an identity converter on the
--- value level.
---
--- Aequivalent to
---
--- > \v x a -> convertingExtraState v (returnV x >>> a)
---
--- (The -ing form is meant to be mnemonic in a sequence of arrows as in
---  producingExtraState () () producer >>> doOtherStuff)
---
-producingExtraState  :: extraState'
-                     -> a
-                     -> FallibleXMLConverter nsID extraState' a extraState
-                     -> FallibleXMLConverter nsID extraState x x
-producingExtraState v x a = convertingExtraState v (returnV x >>> a)
-
-
---------------------------------------------------------------------------------
--- Work in namespaces
---------------------------------------------------------------------------------
-
--- | Arrow version of 'getIRI'
-lookupNSiri             :: (NameSpaceID nsID)
-                        => nsID
-                        -> XMLConverter nsID extraState x (Maybe NameSpaceIRI)
-lookupNSiri nsID        = extractFromState
-                          $ \state -> getIRI nsID $ namespaceIRIs state
-
---
-lookupNSprefix           :: (NameSpaceID nsID)
-                         => nsID
-                         -> XMLConverter nsID extraState x (Maybe NameSpacePrefix)
-lookupNSprefix nsID      = extractFromState
-                           $ \state -> M.lookup nsID $ namespacePrefixes state
-
--- | Extracts namespace attributes from the current element and tries to
--- update the current mapping accordingly
-readNSattributes         :: (NameSpaceID nsID)
-                         => FallibleXMLConverter nsID extraState x ()
-readNSattributes         = fromState $ \state -> maybe (state, failEmpty     )
-                                                       (     , succeedWith ())
-                                                       (extractNSAttrs state )
-  where
-    extractNSAttrs       :: (NameSpaceID nsID)
-                         => XMLConverterState nsID extraState
-                         -> Maybe (XMLConverterState nsID extraState)
-    extractNSAttrs startState
-                         = foldl (\state d -> state >>= addNS d)
-                                 (Just startState)
-                                 nsAttribs
-      where nsAttribs    = mapMaybe readNSattr (XML.elAttribs element)
-            element      = currentElement startState
-            readNSattr (XML.Attr (XML.QName name _ (Just "xmlns")) iri)
-                         = Just (name, iri)
-            readNSattr _ = Nothing
-    addNS  (prefix, iri) state = fmap updateState
-                                 $ getNamespaceID iri
-                                 $ namespaceIRIs state
-      where updateState (iris,nsID)
-                         = state { namespaceIRIs     = iris
-                                 , namespacePrefixes = M.insert nsID prefix
-                                                       $ namespacePrefixes state
-                                 }
-
---------------------------------------------------------------------------------
--- Common namespace accessors
---------------------------------------------------------------------------------
-
--- | Given a namespace id and an element name, creates a 'XML.QName' for
--- internal use
-elemName                 :: (NameSpaceID nsID)
-                         => nsID -> ElementName
-                         -> XMLConverter nsID extraState x XML.QName
-elemName nsID name       =         lookupNSiri nsID
-                               &&& lookupNSprefix nsID
-                           >>% XML.QName name
-
--- | Checks if a given element matches both a specified namespace id
--- and a specified element name
-elemNameIs               :: (NameSpaceID nsID)
-                         => nsID -> ElementName
-                         -> XMLConverter nsID extraState XML.Element Bool
-elemNameIs nsID name     = keepingTheValue (lookupNSiri nsID) >>% hasThatName
-  where hasThatName e iri = let elName = XML.elName e
-                            in     XML.qName elName == name
-                                && XML.qURI  elName == iri
-
---------------------------------------------------------------------------------
--- General content
---------------------------------------------------------------------------------
-
---
-elContent               :: XMLConverter nsID extraState x [XML.Content]
-elContent               =     getCurrentElement
-                           >>^ XML.elContent
-
---------------------------------------------------------------------------------
--- Chilren
---------------------------------------------------------------------------------
-
---
---
-findChildren             :: (NameSpaceID nsID)
-                         => nsID -> ElementName
-                         -> XMLConverter nsID extraState x [XML.Element]
-findChildren nsID name   =         elemName nsID name
-                               &&& getCurrentElement
-                           >>% XML.findChildren
-
---
-findChild'              :: (NameSpaceID nsID)
-                        => nsID
-                        -> ElementName
-                        -> XMLConverter nsID extraState x (Maybe XML.Element)
-findChild' nsID name    =         elemName nsID name
-                              &&& getCurrentElement
-                          >>% XML.findChild
-
---
-findChild              :: (NameSpaceID nsID)
-                       => nsID -> ElementName
-                       -> FallibleXMLConverter nsID extraState x XML.Element
-findChild nsID name    =     findChild' nsID name
-                         >>> maybeToChoice
-
-
---------------------------------------------------------------------------------
--- Attributes
---------------------------------------------------------------------------------
-
---
-isSet'                   :: (NameSpaceID nsID)
-                         => nsID -> AttributeName
-                         -> XMLConverter nsID extraState x (Maybe Bool)
-isSet' nsID attrName     =     findAttr' nsID attrName
-                           >>^ (>>= stringToBool')
-
-isSetWithDefault         :: (NameSpaceID nsID)
-                         => nsID -> AttributeName
-                         -> Bool
-                         -> XMLConverter nsID extraState x Bool
-isSetWithDefault nsID attrName def'
-                         =     isSet' nsID attrName
-                           >>^ fromMaybe def'
-
--- | Lookup value in a dictionary, fail if no attribute found or value
--- not in dictionary
-searchAttrIn             :: (NameSpaceID nsID)
-                         => nsID -> AttributeName
-                         -> [(AttributeValue,a)]
-                         -> FallibleXMLConverter nsID extraState x a
-searchAttrIn nsID attrName dict
-                         =       findAttr nsID attrName
-                           >>?^? maybeToChoice.(`lookup` dict )
-
--- | Lookup value in a dictionary. If attribute or value not found,
--- return default value
-searchAttr               :: (NameSpaceID nsID)
-                         => nsID -> AttributeName
-                         -> a
-                         -> [(AttributeValue,a)]
-                         -> XMLConverter nsID extraState x a
-searchAttr nsID attrName defV dict
-                         =     searchAttrIn nsID attrName dict
-                           >>> const defV ^|||^ id
-
--- | Read a 'Lookupable' attribute. Fail if no match.
-lookupAttr               :: (NameSpaceID nsID, Lookupable a)
-                         => nsID -> AttributeName
-                         -> FallibleXMLConverter nsID extraState x a
-lookupAttr nsID attrName =     lookupAttr' nsID attrName
-                           >>^ maybeToChoice
-
-
--- | Read a 'Lookupable' attribute. Return the result as a 'Maybe'.
-lookupAttr'              :: (NameSpaceID nsID, Lookupable a)
-                         => nsID -> AttributeName
-                         -> XMLConverter nsID extraState x (Maybe a)
-lookupAttr' nsID attrName
-                         =     findAttr' nsID attrName
-                           >>^ (>>= readLookupable)
-
--- | Read a 'Lookupable' attribute with explicit default
-lookupAttrWithDefault    :: (NameSpaceID nsID, Lookupable a)
-                         => nsID -> AttributeName
-                         -> a
-                         -> XMLConverter nsID extraState x a
-lookupAttrWithDefault nsID attrName deflt
-                         =     lookupAttr' nsID attrName
-                           >>^ fromMaybe deflt
-
--- | Read a 'Lookupable' attribute with implicit default
-lookupDefaultingAttr     :: (NameSpaceID nsID, Lookupable a, Default a)
-                         => nsID -> AttributeName
-                         -> XMLConverter nsID extraState x a
-lookupDefaultingAttr nsID attrName
-                         = lookupAttrWithDefault nsID attrName def
-
--- | Return value as a (Maybe String)
-findAttr'               :: (NameSpaceID nsID)
-                        => nsID -> AttributeName
-                        -> XMLConverter nsID extraState x (Maybe AttributeValue)
-findAttr' nsID attrName =         elemName nsID attrName
-                              &&& getCurrentElement
-                          >>% XML.findAttr
-
--- | Return value as string or fail
-findAttr               :: (NameSpaceID nsID)
-                       => nsID -> AttributeName
-                       -> FallibleXMLConverter nsID extraState x AttributeValue
-findAttr nsID attrName =     findAttr' nsID attrName
-                         >>> maybeToChoice
-
--- | Return value as string or return provided default value
-findAttrWithDefault    :: (NameSpaceID nsID)
-                       => nsID -> AttributeName
-                       -> AttributeValue
-                       -> XMLConverter nsID extraState x AttributeValue
-findAttrWithDefault nsID attrName deflt
-                       = findAttr' nsID attrName
-                         >>^ fromMaybe deflt
-
--- | Read and return value or fail
-readAttr               :: (NameSpaceID nsID, Read attrValue)
-                       => nsID -> AttributeName
-                       -> FallibleXMLConverter nsID extraState x attrValue
-readAttr nsID attrName =     readAttr' nsID attrName
-                         >>> maybeToChoice
-
--- | Read and return value or return Nothing
-readAttr'              :: (NameSpaceID nsID, Read attrValue)
-                       => nsID -> AttributeName
-                       -> XMLConverter nsID extraState x (Maybe attrValue)
-readAttr' nsID attrName =     findAttr' nsID attrName
-                          >>^ (>>= tryToRead)
-
--- | Read and return value or return provided default value
-readAttrWithDefault    :: (NameSpaceID nsID, Read attrValue)
-                       => nsID -> AttributeName
-                       -> attrValue
-                       -> XMLConverter nsID extraState x attrValue
-readAttrWithDefault nsID attrName deflt
-                       =     findAttr' nsID attrName
-                         >>^ (>>= tryToRead)
-                         >>^ fromMaybe deflt
-
--- | Read and return value or return default value from 'Default' instance
-getAttr                :: (NameSpaceID nsID, Read attrValue, Default attrValue)
-                       => nsID -> AttributeName
-                       -> XMLConverter nsID extraState x attrValue
-getAttr nsID attrName  = readAttrWithDefault nsID attrName def
-
---------------------------------------------------------------------------------
--- Movements
---------------------------------------------------------------------------------
-
---
-jumpThere              :: XMLConverter nsID extraState XML.Element XML.Element
-jumpThere              = withState (\state element
-                                     -> ( pushElement element state , element )
-                                   )
-
---
-swapStack             :: XMLConverter nsID extraState [XML.Element] [XML.Element]
-swapStack             = withState swapStack'
-
---
-jumpBack               :: FallibleXMLConverter nsID extraState _x _x
-jumpBack               = tryModifyState (popElement >>> maybeToChoice)
-
--- | Support function for "procedural" converters: jump to an element, execute
--- a converter, jump back.
--- This version is safer than 'executeThere', because it does not rely on the
--- internal stack. As a result, the converter can not move around in arbitrary
--- ways. The downside is of course that some of the environment is not
--- accessible to the converter.
-switchingTheStack      :: XMLConverter nsID moreState a b
-                       -> XMLConverter nsID moreState (a, XML.Element) b
-switchingTheStack a    =     second ( (:[]) ^>> swapStack )
-                         >>> first  a
-                         >>> second swapStack
-                         >>^ fst
-
--- | Support function for "procedural" converters: jumps to an element, executes
--- a converter, jumps back.
--- Make sure that the converter is well-behaved; that is it should
--- return to the exact position it started from in /every possible path/ of
--- execution, even if it "fails". If it does not, you may encounter
--- strange bugs. If you are not sure about the behaviour or want to use
--- shortcuts, you can often use 'switchingTheStack' instead.
-executeThere           :: FallibleXMLConverter nsID moreState a b
-                       -> FallibleXMLConverter nsID moreState (a, XML.Element) b
-executeThere a         =      second jumpThere
-                          >>> fst
-                          ^>> a
-                          >>> jumpBack -- >>? jumpBack  would not ensure the jump.
-                          >>^ collapseEither
-
--- | Do something in a sub-element, tnen come back
-executeIn              :: (NameSpaceID nsID)
-                       => nsID -> ElementName
-                       -> FallibleXMLConverter nsID extraState f s
-                       -> FallibleXMLConverter nsID extraState f s
-executeIn nsID name a  =     keepingTheValue
-                               (findChild nsID name)
-                         >>> ignoringState liftFailure
-                         >>? switchingTheStack a
-  where liftFailure (_, (Left  f)) = Left  f
-        liftFailure (x, (Right e)) = Right (x, e)
-
---------------------------------------------------------------------------------
--- Iterating over children
---------------------------------------------------------------------------------
-
--- Helper converter to prepare different types of iterations.
--- It lifts the children (of a certain type) of the current element
--- into the value level and pairs each one with the current input value.
-prepareIteration       :: (NameSpaceID nsID)
-                       => nsID -> ElementName
-                       -> XMLConverter nsID extraState b [(b, XML.Element)]
-prepareIteration nsID name =     keepingTheValue
-                                   (findChildren nsID name)
-                             >>% distributeValue
-
---
-withEveryL             :: (NameSpaceID nsID)
-                       => nsID -> ElementName
-                       -> FallibleXMLConverter nsID extraState a  b
-                       -> FallibleXMLConverter nsID extraState a [b]
-withEveryL = withEvery
-
--- | Applies a converter to every child element of a specific type.
--- Collects results in a 'MonadPlus'.
--- Fails completely if any conversion fails.
-withEvery              :: (NameSpaceID nsID, MonadPlus m)
-                       => nsID -> ElementName
-                       -> FallibleXMLConverter nsID extraState a    b
-                       -> FallibleXMLConverter nsID extraState a (m b)
-withEvery nsID name a      =     prepareIteration nsID name
-                             >>> iterateS' (switchingTheStack a)
-
--- | Applies a converter to every child element of a specific type.
--- Collects all successful results in a list.
-tryAll                 :: (NameSpaceID nsID)
-                       => nsID -> ElementName
-                       -> FallibleXMLConverter nsID extraState b  a
-                       ->         XMLConverter nsID extraState b [a]
-tryAll nsID name a         =     prepareIteration nsID name
-                             >>> iterateS (switchingTheStack a)
-                             >>^ rights
-
---------------------------------------------------------------------------------
--- Matching children
---------------------------------------------------------------------------------
-
-type IdXMLConverter nsID moreState x
-   = XMLConverter   nsID moreState x x
-
-type MaybeCConverter nsID moreState x
-   = Maybe (IdXMLConverter nsID moreState (x, XML.Content))
-
--- Chainable converter that helps deciding which converter to actually use.
-type ContentMatchConverter nsID extraState x
-   = IdXMLConverter  nsID
-                     extraState
-                     (MaybeCConverter nsID extraState x, XML.Content)
-
--- Helper function: The @c@ is actually a converter that is to be selected by
--- matching XML content to the first two parameters.
--- The fold used to match elements however is very simple, so to use it,
--- this function wraps the converter in another converter that unifies
--- the accumulator. Think of a lot of converters with the resulting type
--- chained together. The accumulator not only transports the element
--- unchanged to the next matcher, it also does the actual selecting by
--- combining the intermediate results with '(<|>)'.
-makeMatcherC           :: (NameSpaceID nsID)
-                       => nsID -> ElementName
-                       -> FallibleXMLConverter  nsID extraState a a
-                       -> ContentMatchConverter nsID extraState a
-makeMatcherC nsID name c = (    second (    contentToElem
-                                         >>> returnV Nothing
-                                         ||| (    elemNameIs nsID name
-                                              >>^ bool Nothing (Just cWithJump)
-                                             )
-                                        )
-                             >>% (<|>)
-                           ) &&&^ snd
-  where cWithJump =      ( fst
-                           ^&&& (      second contentToElem
-                                  >>>  spreadChoice
-                                  ^>>? executeThere c
-                                )
-                            >>% recover)
-                    &&&^ snd
-        contentToElem :: FallibleXMLConverter nsID extraState XML.Content XML.Element
-        contentToElem = arr $ \e -> case e of
-                                     XML.Elem e' -> succeedWith e'
-                                     _           -> failEmpty
-
--- Creates and chains a bunch of matchers
-prepareMatchersC      :: (NameSpaceID nsID)
-                       => [(nsID, ElementName, FallibleXMLConverter nsID extraState x x)]
-                       -> ContentMatchConverter nsID extraState x
---prepareMatchersC      = foldSs . (map $ uncurry3  makeMatcherC)
-prepareMatchersC      = reverseComposition . (map $ uncurry3  makeMatcherC)
-
--- | Takes a list of element-data - converter groups and
--- * Finds all content of the current element
--- * Matches each group to each piece of content in order
---   (at most one group per piece of content)
--- * Filters non-matched content
--- * Chains all found converters in content-order
--- * Applies the chain to the input element
-matchContent'           :: (NameSpaceID nsID)
-                       => [(nsID, ElementName, FallibleXMLConverter nsID extraState a a)]
-                       -> XMLConverter nsID extraState a a
-matchContent' lookups   = matchContent lookups (arr fst)
-
--- | Takes a list of element-data - converter groups and
--- * Finds all content of the current element
--- * Matches each group to each piece of content in order
---   (at most one group per piece of content)
--- * Adds a default converter for all non-matched content
--- * Chains all found converters in content-order
--- * Applies the chain to the input element
-matchContent          :: (NameSpaceID nsID)
-                       => [(nsID, ElementName, FallibleXMLConverter nsID extraState a a)]
-                       -> XMLConverter nsID extraState (a,XML.Content) a
-                       -> XMLConverter nsID extraState a a
-matchContent lookups fallback
-                        = let matcher = prepareMatchersC lookups
-                          in  keepingTheValue (
-                                   elContent
-                               >>> map (Nothing,)
-                               ^>> iterateSL matcher
-                               >>^ map swallowOrFallback
-                              -- >>> foldSs
-                               >>> reverseComposition
-                             )
-                         >>> swap
-                         ^>> app
-  where
-        -- let the converter swallow the content and drop the content
-        -- in the return value
-        swallowOrFallback (Just converter,content) = (,content) ^>> converter >>^ fst
-        swallowOrFallback (Nothing       ,content) = (,content) ^>> fallback
-
---------------------------------------------------------------------------------
--- Internals
---------------------------------------------------------------------------------
-
-stringToBool' :: String -> Maybe Bool
-stringToBool' val | val `elem` trueValues  = Just True
-                  | val `elem` falseValues = Just False
-                  | otherwise              = Nothing
-  where trueValues  = ["true" ,"on" ,"1"]
-        falseValues = ["false","off","0"]
-
-
-distributeValue ::  a -> [b] -> [(a,b)]
-distributeValue = map.(,)
-
---------------------------------------------------------------------------------
-
-{-
-NOTES
-It might be a good idea to refactor the namespace stuff.
-E.g.: if a namespace constructor took a string as a parameter, things like
-> a ?>/< (NsText,"body")
-would be nicer.
-Together with a rename and some trickery, something like
-> |< NsText "body" >< NsText "p" ?> a </> </>|
-might even be possible.
-
-Some day, XML.Light should be replaced by something better.
-While doing that, it might be useful to replace String as the type of element
-names with something else, too. (Of course with OverloadedStrings).
-While doing that, maybe the types can be created in a way that something like
-> NsText:"body"
-could be used. Overloading (:) does not sounds like the best idea, but if the
-element name type was a list, this might be possible.
-Of course that would be a bit hackish, so the "right" way would probably be
-something like
-> InNS NsText "body"
-but isn't that a bit boring? ;)
--}
diff --git a/src/Text/Pandoc/Readers/Odt/Namespaces.hs b/src/Text/Pandoc/Readers/Odt/Namespaces.hs
deleted file mode 100644
--- a/src/Text/Pandoc/Readers/Odt/Namespaces.hs
+++ /dev/null
@@ -1,110 +0,0 @@
-{-
-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
-   License     : GNU GPL, version 2 or above
-
-   Maintainer  : Martin Linnemann <theCodingMarlin@googlemail.com>
-   Stability   : alpha
-   Portability : portable
-
-Namespaces used in odt files.
--}
-
-module Text.Pandoc.Readers.Odt.Namespaces ( Namespace (..)
-                                          ) where
-
-import Data.List (isPrefixOf)
-import qualified Data.Map as M (empty, insert)
-import Data.Maybe (fromMaybe, listToMaybe)
-
-import Text.Pandoc.Readers.Odt.Generic.Namespaces
-
-
-instance NameSpaceID Namespace where
-
-  getInitialIRImap     = nsIDmap
-
-  getNamespaceID ""  m = Just(m, NsXML)
-  getNamespaceID iri m = asPair $ fromMaybe (NsOther iri) (findID iri)
-    where asPair nsID = Just (M.insert nsID iri m, nsID)
-
-
-findID :: NameSpaceIRI -> Maybe Namespace
-findID iri = listToMaybe [nsID | (iri',~nsID) <- nsIDs, iri' `isPrefixOf` iri]
-
-nsIDmap :: NameSpaceIRIs Namespace
-nsIDmap = foldr (uncurry $ flip M.insert) M.empty nsIDs
-
-data Namespace = -- Open Document core
-                 NsOffice | NsStyle  | NsText   | NsTable  | NsForm
-               | NsDraw   | Ns3D     | NsAnim   | NsChart  | NsConfig
-               | NsDB     | NsMeta   | NsNumber | NsScript | NsManifest
-               | NsPresentation
-                 -- Metadata
-               | NsODF
-                 -- Compatible elements
-               | NsXSL_FO  | NsSVG    | NsSmil
-                 -- External standards
-               | NsMathML | NsXForms | NsXLink  | NsXHtml  | NsGRDDL
-               | NsDublinCore
-                 -- Metadata manifest
-               | NsPKG
-                 -- Others
-               | NsOpenFormula
-                 -- Core XML (basically only for the 'id'-attribute)
-               | NsXML
-                 -- Fallback
-               | NsOther String
-  deriving ( Eq, Ord, Show )
-
--- | Not the actual iri's, but large prefixes of them - this way there are
--- less versioning problems and the like.
-nsIDs :: [(String,Namespace)]
-nsIDs = [
-  ("urn:oasis:names:tc:opendocument:xmlns:animation"        , NsAnim         ),
-  ("urn:oasis:names:tc:opendocument:xmlns:chart"            , NsChart        ),
-  ("urn:oasis:names:tc:opendocument:xmlns:config"           , NsConfig       ),
-  ("urn:oasis:names:tc:opendocument:xmlns:database"         , NsDB           ),
-  ("urn:oasis:names:tc:opendocument:xmlns:dr3d"             , Ns3D           ),
-  ("urn:oasis:names:tc:opendocument:xmlns:drawing"          , NsDraw         ),
-  ("urn:oasis:names:tc:opendocument:xmlns:form"             , NsForm         ),
-  ("urn:oasis:names:tc:opendocument:xmlns:manifest"         , NsManifest     ),
-  ("urn:oasis:names:tc:opendocument:xmlns:meta"             , NsMeta         ),
-  ("urn:oasis:names:tc:opendocument:xmlns:datastyle"        , NsNumber       ),
-  ("urn:oasis:names:tc:opendocument:xmlns:of"               , NsOpenFormula  ),
-  ("urn:oasis:names:tc:opendocument:xmlns:office:1.0"       , NsOffice       ),
-  ("urn:oasis:names:tc:opendocument:xmlns:presentation"     , NsPresentation ),
-  ("urn:oasis:names:tc:opendocument:xmlns:script"           , NsScript       ),
-  ("urn:oasis:names:tc:opendocument:xmlns:style"            , NsStyle        ),
-  ("urn:oasis:names:tc:opendocument:xmlns:table"            , NsTable        ),
-  ("urn:oasis:names:tc:opendocument:xmlns:text"             , NsText         ),
-  ("urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible", NsXSL_FO       ),
-  ("urn:oasis:names:tc:opendocument:xmlns:smil-compatible"  , NsSmil         ),
-  ("urn:oasis:names:tc:opendocument:xmlns:svg-compatible"   , NsSVG          ),
-  ("http://docs.oasis-open.org/ns/office/1.2/meta/odf"      , NsODF          ),
-  ("http://docs.oasis-open.org/ns/office/1.2/meta/pkg"      , NsPKG          ),
-  ("http://purl.org/dc/elements"                            , NsDublinCore   ),
-  ("http://www.w3.org/2003/g/data-view"                     , NsGRDDL        ),
-  ("http://www.w3.org/1998/Math/MathML"                     , NsMathML       ),
-  ("http://www.w3.org/1999/xhtml"                           , NsXHtml        ),
-  ("http://www.w3.org/2002/xforms"                          , NsXForms       ),
-  ("http://www.w3.org/1999/xlink"                           , NsXLink        )
-  ]
diff --git a/src/Text/Pandoc/Readers/Odt/StyleReader.hs b/src/Text/Pandoc/Readers/Odt/StyleReader.hs
deleted file mode 100644
--- a/src/Text/Pandoc/Readers/Odt/StyleReader.hs
+++ /dev/null
@@ -1,660 +0,0 @@
-{-# 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
-   License     : GNU GPL, version 2 or above
-
-   Maintainer  : Martin Linnemann <theCodingMarlin@googlemail.com>
-   Stability   : alpha
-   Portability : portable
-
-Reader for the style information in an odt document.
--}
-
-module Text.Pandoc.Readers.Odt.StyleReader
-( Style                (..)
-, StyleName
-, StyleFamily          (..)
-, Styles               (..)
-, StyleProperties      (..)
-, TextProperties       (..)
-, ParaProperties       (..)
-, VerticalTextPosition (..)
-, ListItemNumberFormat (..)
-, ListLevel
-, ListStyle            (..)
-, ListLevelStyle       (..)
-, ListLevelType        (..)
-, LengthOrPercent      (..)
-, lookupStyle
-, getListLevelStyle
-, getStyleFamily
-, lookupDefaultStyle'
-, lookupListStyleByName
-, extendedStylePropertyChain
-, readStylesAt
-) where
-
-import Control.Applicative hiding (liftA, liftA2, liftA3)
-import Control.Arrow
-
-import Data.Char (isDigit)
-import Data.Default
-import qualified Data.Foldable as F
-import Data.List (unfoldr)
-import qualified Data.Map as M
-import Data.Maybe
-import qualified Data.Set as S
-
-import qualified Text.XML.Light as XML
-
-import Text.Pandoc.Readers.Odt.Arrows.Utils
-
-import Text.Pandoc.Readers.Odt.Generic.Fallible
-import qualified Text.Pandoc.Readers.Odt.Generic.SetMap as SM
-import Text.Pandoc.Readers.Odt.Generic.Utils
-import Text.Pandoc.Readers.Odt.Generic.XMLConverter
-
-import Text.Pandoc.Readers.Odt.Base
-import Text.Pandoc.Readers.Odt.Namespaces
-
-
-readStylesAt :: XML.Element -> Fallible Styles
-readStylesAt e = runConverter' readAllStyles mempty e
-
---------------------------------------------------------------------------------
--- Reader for font declarations and font pitches
---------------------------------------------------------------------------------
-
--- Pandoc has no support for different font pitches. Yet knowing them can be
--- very helpful in cases where Pandoc has more semantics than OpenDocument.
--- In these cases, the pitch can help deciding as what to define a block of
--- text. So let's start with a type for font pitches:
-
-data FontPitch    = PitchVariable | PitchFixed
-  deriving ( Eq, Show )
-
-instance Lookupable FontPitch where
-  lookupTable = [ ("variable" , PitchVariable)
-                , ("fixed"    , PitchFixed   )
-                ]
-
-instance Default FontPitch where
-  def = PitchVariable
-
--- The font pitch can be specified in a style directly. Normally, however,
--- it is defined in the font. That is also the specs' recommendation.
---
--- Thus, we want
-
-type FontFaceName = String
-
-type FontPitches = M.Map FontFaceName FontPitch
-
--- To get there, the fonts have to be read and the pitches extracted.
--- But the resulting map are only needed at one later place, so it should not be
--- transported on the value level, especially as we already use a state arrow.
--- So instead, the resulting map is lifted into the state of the reader.
--- (An alternative might be ImplicitParams, but again, we already have a state.)
---
--- So the main style readers will have the types
-type StyleReader     a b  = XMLReader     FontPitches a b
--- and
-type StyleReaderSafe a b  = XMLReaderSafe FontPitches a b
--- respectively.
---
--- But before we can work with these, we need to define the reader that reads
--- the fonts:
-
--- | A reader for font pitches
-fontPitchReader :: XMLReader _s _x FontPitches
-fontPitchReader = executeIn NsOffice "font-face-decls" (
-                         (  withEveryL NsStyle "font-face" $ liftAsSuccess (
-                              findAttr' NsStyle "name"
-                              &&&
-                              lookupDefaultingAttr NsStyle "font-pitch"
-                            )
-                         )
-                    >>?^ ( M.fromList . (foldl accumLegalPitches []) )
-                  )
-  where accumLegalPitches ls (Nothing,_) = ls
-        accumLegalPitches ls (Just n,p)  = (n,p):ls
-
-
--- | A wrapper around the font pitch reader that lifts the result into the
--- state.
-readFontPitches :: StyleReader x x
-readFontPitches = producingExtraState () () fontPitchReader
-
-
--- | Looking up a pitch in the state of the arrow.
---
--- The function does the following:
--- * Look for the font pitch in an attribute.
--- * If that fails, look for the font name, look up the font in the state
---   and use the pitch from there.
--- * Return the result in a Maybe
---
-findPitch :: XMLReaderSafe FontPitches _x (Maybe FontPitch)
-findPitch =     ( lookupAttr NsStyle "font-pitch"
-                  `ifFailedDo`     findAttr NsStyle "font-name"
-                               >>? (     keepingTheValue getExtraState
-                                     >>% M.lookup
-                                     >>^ maybeToChoice
-                                   )
-                )
-            >>> choiceToMaybe
-
---------------------------------------------------------------------------------
--- Definitions of main data
---------------------------------------------------------------------------------
-
-type StyleName        = String
-
--- | There are two types of styles: named styles with a style family and an
--- optional style parent, and default styles for each style family,
--- defining default style properties
-data Styles           = Styles
-                          { stylesByName     :: M.Map StyleName   Style
-                          , listStylesByName :: M.Map StyleName   ListStyle
-                          , defaultStyleMap  :: M.Map StyleFamily StyleProperties
-                          }
-  deriving ( Show )
-
--- Styles from a monoid under union
-instance Monoid Styles where
-  mempty  = Styles M.empty M.empty M.empty
-  mappend  (Styles sBn1 dSm1 lsBn1)
-           (Styles sBn2 dSm2 lsBn2)
-          = Styles (M.union sBn1  sBn2)
-                   (M.union dSm1  dSm2)
-                   (M.union lsBn1 lsBn2)
-
--- Not all families from the specifications are implemented, only those we need.
--- But there are none that are not mentioned here.
-data StyleFamily      = FaText    | FaParagraph
---                    | FaTable   | FaTableCell | FaTableColumn | FaTableRow
---                    | FaGraphic | FaDrawing   | FaChart
---                    | FaPresentation
---                    | FaRuby
-  deriving ( Eq, Ord, Show )
-
-instance Lookupable StyleFamily where
-  lookupTable = [ ( "text"         , FaText         )
-                , ( "paragraph"    , FaParagraph    )
---              , ( "table"        , FaTable        )
---              , ( "table-cell"   , FaTableCell    )
---              , ( "table-column" , FaTableColumn  )
---              , ( "table-row"    , FaTableRow     )
---              , ( "graphic"      , FaGraphic      )
---              , ( "drawing-page" , FaDrawing      )
---              , ( "chart"        , FaChart        )
---              , ( "presentation" , FaPresentation )
---              , ( "ruby"         , FaRuby         )
-                ]
-
--- | A named style
-data Style            = Style  { styleFamily     :: Maybe StyleFamily
-                               , styleParentName :: Maybe StyleName
-                               , listStyle       :: Maybe StyleName
-                               , styleProperties :: StyleProperties
-                               }
-  deriving ( Eq, Show )
-
-data StyleProperties  = SProps { textProperties :: Maybe TextProperties
-                               , paraProperties :: Maybe ParaProperties
---                             , tableColProperties  :: Maybe TColProperties
---                             , tableRowProperties  :: Maybe TRowProperties
---                             , tableCellProperties :: Maybe TCellProperties
---                             , tableProperties     :: Maybe TableProperties
---                             , graphicProperties   :: Maybe GraphProperties
-                               }
-  deriving ( Eq, Show )
-
-instance  Default StyleProperties where
-  def =                SProps { textProperties       = Just def
-                               , paraProperties      = Just def
-                               }
-
-data TextProperties   = PropT  { isEmphasised     :: Bool
-                               , isStrong         :: Bool
-                               , pitch            :: Maybe FontPitch
-                               , verticalPosition :: VerticalTextPosition
-                               , underline        :: Maybe UnderlineMode
-                               , strikethrough    :: Maybe UnderlineMode
-                               }
-  deriving ( Eq, Show )
-
-instance Default TextProperties where
-  def =                 PropT  { isEmphasised     = False
-                               , isStrong         = False
-                               , pitch            = Just def
-                               , verticalPosition = def
-                               , underline        = Nothing
-                               , strikethrough    = Nothing
-                               }
-
-data ParaProperties   = PropP { paraNumbering :: ParaNumbering
-                              , indentation   :: LengthOrPercent
-                              , margin_left   :: LengthOrPercent
-                              }
-  deriving ( Eq, Show )
-
-instance Default ParaProperties where
-  def =                 PropP { paraNumbering = NumberingNone
-                              , indentation   = def
-                              , margin_left   = def
-                              }
-
-----
--- All the little data types that make up the properties
-----
-
-data VerticalTextPosition = VPosNormal | VPosSuper | VPosSub
-  deriving ( Eq, Show )
-
-instance Default VerticalTextPosition where
-  def = VPosNormal
-
-instance Read VerticalTextPosition where
-  readsPrec _ s =    [ (VPosSub        , s') | ("sub"   , s') <- lexS          ]
-                  ++ [ (VPosSuper      , s') | ("super" , s') <- lexS          ]
-                  ++ [ (signumToVPos n , s') | (  n     , s') <- readPercent s ]
-    where
-      lexS = lex s
-      signumToVPos n | n < 0     = VPosSub
-                     | n > 0     = VPosSuper
-                     | otherwise = VPosNormal
-
-data UnderlineMode = UnderlineModeNormal | UnderlineModeSkipWhitespace
-  deriving ( Eq, Show )
-
-instance Lookupable UnderlineMode where
-  lookupTable = [ ( "continuous"       , UnderlineModeNormal         )
-                , ( "skip-white-space" , UnderlineModeSkipWhitespace )
-                ]
-
-
-data ParaNumbering = NumberingNone | NumberingKeep | NumberingRestart Int
-  deriving ( Eq, Show )
-
-data LengthOrPercent = LengthValueMM Int | PercentValue Int
-  deriving ( Eq, Show )
-
-instance Default LengthOrPercent where
-  def = LengthValueMM 0
-
-instance Read LengthOrPercent where
-  readsPrec _ s =
-      [ (PercentValue  percent  , s' ) | (percent , s' ) <- readPercent s]
-   ++ [ (LengthValueMM lengthMM , s'') | (length' , s' ) <- reads s
-                                       , (unit    , s'') <- reads s'
-                                       , let lengthMM = estimateInMillimeter
-                                                                   length' unit
-                                       ]
-
-data XslUnit = XslUnitMM | XslUnitCM
-             | XslUnitInch
-             | XslUnitPoints | XslUnitPica
-             | XslUnitPixel
-             | XslUnitEM
-
-instance Show XslUnit where
-  show XslUnitMM     = "mm"
-  show XslUnitCM     = "cm"
-  show XslUnitInch   = "in"
-  show XslUnitPoints = "pt"
-  show XslUnitPica   = "pc"
-  show XslUnitPixel  = "px"
-  show XslUnitEM     = "em"
-
-instance Read XslUnit where
-  readsPrec _ "mm" = [(XslUnitMM     , "")]
-  readsPrec _ "cm" = [(XslUnitCM     , "")]
-  readsPrec _ "in" = [(XslUnitInch   , "")]
-  readsPrec _ "pt" = [(XslUnitPoints , "")]
-  readsPrec _ "pc" = [(XslUnitPica   , "")]
-  readsPrec _ "px" = [(XslUnitPixel  , "")]
-  readsPrec _ "em" = [(XslUnitEM     , "")]
-  readsPrec _  _   = []
-
--- | Rough conversion of measures into millimetres.
--- Pixels and em's are actually implementation dependant/relative measures,
--- so I could not really easily calculate anything exact here even if I wanted.
--- But I do not care about exactness right now, as I only use measures
--- to determine if a paragraph is "indented" or not.
-estimateInMillimeter :: Int -> XslUnit -> Int
-estimateInMillimeter n XslUnitMM     = n
-estimateInMillimeter n XslUnitCM     = n * 10
-estimateInMillimeter n XslUnitInch   = n * 25    -- \*             25.4
-estimateInMillimeter n XslUnitPoints = n `div` 3 -- \*      1/72 * 25.4
-estimateInMillimeter n XslUnitPica   = n * 4     -- \* 12 * 1/72 * 25.4
-estimateInMillimeter n XslUnitPixel  = n `div`3  -- \*      1/72 * 25.4
-estimateInMillimeter n XslUnitEM     = n * 7     -- \* 16 * 1/72 * 25.4
-
-
-----
--- List styles
-----
-
-type ListLevel = Int
-
-newtype ListStyle = ListStyle { levelStyles :: M.Map ListLevel ListLevelStyle
-                              }
-  deriving ( Eq, Show )
-
---
-getListLevelStyle :: ListLevel -> ListStyle -> Maybe ListLevelStyle
-getListLevelStyle level ListStyle{..} =
-  let (lower , exactHit , _) = M.splitLookup level levelStyles
-  in  exactHit <|> fmap fst (M.maxView lower)
-  -- findBy (`M.lookup` levelStyles) [level, (level-1) .. 1]
-  -- \^ simpler, but in general less efficient
-
-data ListLevelStyle = ListLevelStyle { listLevelType  :: ListLevelType
-                                     , listItemPrefix :: Maybe String
-                                     , listItemSuffix :: Maybe String
-                                     , listItemFormat :: ListItemNumberFormat
-                                     , listItemStart  :: Int
-                                     }
-  deriving ( Eq, Ord )
-
-instance Show ListLevelStyle where
-  show ListLevelStyle{..} =    "<LLS|"
-                            ++ (show listLevelType)
-                            ++ "|"
-                            ++ (maybeToString listItemPrefix)
-                            ++ (show listItemFormat)
-                            ++ (maybeToString listItemSuffix)
-                            ++ ">"
-    where maybeToString = fromMaybe ""
-
-data ListLevelType = LltBullet | LltImage | LltNumbered
-  deriving ( Eq, Ord, Show )
-
-data ListItemNumberFormat = LinfNone
-                          | LinfNumber
-                          | LinfRomanLC | LinfRomanUC
-                          | LinfAlphaLC | LinfAlphaUC
-                          | LinfString String
-  deriving ( Eq, Ord )
-
-instance Show ListItemNumberFormat where
-  show  LinfNone      = ""
-  show  LinfNumber    = "1"
-  show  LinfRomanLC   = "i"
-  show  LinfRomanUC   = "I"
-  show  LinfAlphaLC   = "a"
-  show  LinfAlphaUC   = "A"
-  show (LinfString s) =  s
-
-instance Default ListItemNumberFormat where
-  def = LinfNone
-
-instance Read ListItemNumberFormat where
-  readsPrec _ ""  = [(LinfNone     , "")]
-  readsPrec _ "1" = [(LinfNumber   , "")]
-  readsPrec _ "i" = [(LinfRomanLC  , "")]
-  readsPrec _ "I" = [(LinfRomanUC  , "")]
-  readsPrec _ "a" = [(LinfAlphaLC  , "")]
-  readsPrec _ "A" = [(LinfAlphaUC  , "")]
-  readsPrec _  s  = [(LinfString s , "")]
-
---------------------------------------------------------------------------------
--- Readers
---
--- ...it seems like a whole lot of this should be automatically derivable
---    or at least moveable into a class. Most of this is data concealed in
---    code.
---------------------------------------------------------------------------------
-
---
-readAllStyles :: StyleReader _x Styles
-readAllStyles = (      readFontPitches
-                  >>?! (     readAutomaticStyles
-                         &&& readStyles ))
-                  >>?%? chooseMax
- -- all top elements are always on the same hierarchy level
-
---
-readStyles :: StyleReader _x Styles
-readStyles = executeIn NsOffice "styles" $ liftAsSuccess
-  $ liftA3 Styles
-    ( tryAll NsStyle "style"         readStyle        >>^ M.fromList )
-    ( tryAll NsText  "list-style"    readListStyle    >>^ M.fromList )
-    ( tryAll NsStyle "default-style" readDefaultStyle >>^ M.fromList )
-
---
-readAutomaticStyles :: StyleReader _x Styles
-readAutomaticStyles = executeIn NsOffice "automatic-styles" $ liftAsSuccess
-  $ liftA3 Styles
-    ( tryAll NsStyle "style"         readStyle        >>^ M.fromList )
-    ( tryAll NsText  "list-style"    readListStyle    >>^ M.fromList )
-    ( returnV M.empty                                                )
-
---
-readDefaultStyle :: StyleReader _x (StyleFamily, StyleProperties)
-readDefaultStyle =      lookupAttr NsStyle "family"
-                   >>?! keepingTheValue readStyleProperties
-
---
-readStyle :: StyleReader _x (StyleName,Style)
-readStyle =      findAttr NsStyle "name"
-            >>?! keepingTheValue
-                   ( liftA4 Style
-                       ( lookupAttr' NsStyle "family"            )
-                       ( findAttr'   NsStyle "parent-style-name" )
-                       ( findAttr'   NsStyle "list-style-name"   )
-                       readStyleProperties
-                   )
-
---
-readStyleProperties :: StyleReaderSafe _x StyleProperties
-readStyleProperties = liftA2 SProps
-                       ( readTextProperties >>> choiceToMaybe )
-                       ( readParaProperties >>> choiceToMaybe )
-
---
-readTextProperties :: StyleReader _x TextProperties
-readTextProperties =
-  executeIn NsStyle "text-properties" $ liftAsSuccess
-    ( liftA6 PropT
-       ( searchAttr   NsXSL_FO "font-style"  False isFontEmphasised )
-       ( searchAttr   NsXSL_FO "font-weight" False isFontBold       )
-       ( findPitch                                                  )
-       ( getAttr      NsStyle  "text-position"                      )
-       ( readUnderlineMode                                          )
-       ( readStrikeThroughMode                                      )
-     )
-  where isFontEmphasised = [("normal",False),("italic",True),("oblique",True)]
-        isFontBold = ("normal",False):("bold",True)
-                    :(map ((,True).show) ([100,200..900]::[Int]))
-
-readUnderlineMode     :: StyleReaderSafe _x (Maybe UnderlineMode)
-readUnderlineMode     = readLineMode "text-underline-mode"
-                                     "text-underline-style"
-
-readStrikeThroughMode :: StyleReaderSafe _x (Maybe UnderlineMode)
-readStrikeThroughMode = readLineMode "text-line-through-mode"
-                                     "text-line-through-style"
-
-readLineMode :: String -> String -> StyleReaderSafe _x (Maybe UnderlineMode)
-readLineMode modeAttr styleAttr = proc x -> do
-  isUL <- searchAttr  NsStyle styleAttr False isLinePresent -< x
-  mode <- lookupAttr' NsStyle  modeAttr                     -< x
-  if isUL
-    then case mode of
-           Just m  -> returnA -< Just m
-           Nothing -> returnA -< Just UnderlineModeNormal
-    else              returnA -< Nothing
-  where
-    isLinePresent = [("none",False)] ++ map (,True)
-                    [ "dash"      , "dot-dash" , "dot-dot-dash" , "dotted"
-                    , "long-dash" , "solid"    , "wave"
-                    ]
-
---
-readParaProperties :: StyleReader _x ParaProperties
-readParaProperties =
-   executeIn NsStyle "paragraph-properties" $ liftAsSuccess
-     ( liftA3 PropP
-       ( liftA2 readNumbering
-         ( isSet'           NsText   "number-lines"           )
-         ( readAttr'        NsText   "line-number"            )
-       )
-       ( liftA2 readIndentation
-         ( isSetWithDefault NsStyle  "auto-text-indent" False )
-         ( getAttr          NsXSL_FO "text-indent"            )
-       )
-       (   getAttr          NsXSL_FO "margin-left"            )
-     )
-  where readNumbering (Just True) (Just n) = NumberingRestart n
-        readNumbering (Just True)  _       = NumberingKeep
-        readNumbering      _       _       = NumberingNone
-
-        readIndentation False indent = indent
-        readIndentation True  _      = def
-
-----
--- List styles
-----
-
---
-readListStyle :: StyleReader _x (StyleName, ListStyle)
-readListStyle =
-       findAttr NsStyle "name"
-  >>?! keepingTheValue
-       ( liftA ListStyle
-         $ ( liftA3 SM.union3
-             ( readListLevelStyles NsText "list-level-style-number" LltNumbered )
-             ( readListLevelStyles NsText "list-level-style-bullet" LltBullet   )
-             ( readListLevelStyles NsText "list-level-style-image"  LltImage    )
-           ) >>^ M.mapMaybe chooseMostSpecificListLevelStyle
-       )
---
-readListLevelStyles :: Namespace -> ElementName
-                    -> ListLevelType
-                    -> StyleReaderSafe _x (SM.SetMap Int ListLevelStyle)
-readListLevelStyles namespace elementName levelType =
-  (     tryAll namespace elementName (readListLevelStyle levelType)
-    >>^ SM.fromList
-  )
-
---
-readListLevelStyle :: ListLevelType -> StyleReader _x (Int, ListLevelStyle)
-readListLevelStyle levelType =      readAttr NsText "level"
-                               >>?! keepingTheValue
-                                    ( liftA5 toListLevelStyle
-                                      ( returnV  levelType              )
-                                      ( findAttr' NsStyle "num-prefix"  )
-                                      ( findAttr' NsStyle "num-suffix"  )
-                                      ( getAttr   NsStyle "num-format"  )
-                                      ( findAttr' NsText  "start-value" )
-                                    )
-  where
-  toListLevelStyle _ p s LinfNone b         = ListLevelStyle LltBullet p s LinfNone (startValue b)
-  toListLevelStyle _ p s f@(LinfString _) b = ListLevelStyle LltBullet p s f (startValue b)
-  toListLevelStyle t p s f b                = ListLevelStyle t      p s f (startValue b)
-  startValue (Just "") = 1
-  startValue (Just v)  = if all isDigit v
-                           then read v
-                           else 1
-  startValue Nothing   = 1
-
---
-chooseMostSpecificListLevelStyle :: S.Set ListLevelStyle -> Maybe ListLevelStyle
-chooseMostSpecificListLevelStyle ls | ls == mempty = Nothing
-                                    | otherwise    = Just ( F.foldr1 select ls )
-  where
-   select ( ListLevelStyle       t1            p1          s1          f1          b1 )
-          ( ListLevelStyle       t2            p2          s2          f2          _ )
-        =   ListLevelStyle (select' t1 t2) (p1 <|> p2) (s1 <|> s2) (selectLinf f1 f2) b1
-   select' LltNumbered _           = LltNumbered
-   select' _           LltNumbered = LltNumbered
-   select' _           _           = LltBullet
-   selectLinf LinfNone       f2             = f2
-   selectLinf f1             LinfNone       = f1
-   selectLinf (LinfString _) f2             = f2
-   selectLinf f1             (LinfString _) = f1
-   selectLinf f1             _              = f1
-
-
---------------------------------------------------------------------------------
--- Tools to access style data
---------------------------------------------------------------------------------
-
---
-lookupStyle           :: StyleName   -> Styles -> Maybe Style
-lookupStyle name Styles{..} = M.lookup name stylesByName
-
---
-lookupDefaultStyle'   :: Styles -> StyleFamily -> StyleProperties
-lookupDefaultStyle' Styles{..} family = fromMaybe def
-                                        (M.lookup family defaultStyleMap)
-
---
-lookupListStyleByName :: StyleName   -> Styles -> Maybe ListStyle
-lookupListStyleByName name Styles{..} = M.lookup name listStylesByName
-
-
--- | Returns a chain of parent of the current style. The direct parent will
--- be the first element of the list, followed by its parent and so on.
--- The current style is not in the list.
-parents               :: Style       -> Styles ->      [Style]
-parents style styles = unfoldr findNextParent style -- Ha!
-  where findNextParent Style{..}
-          = fmap duplicate $ (`lookupStyle` styles) =<< styleParentName
-
--- | Looks up the style family of the current style. Normally, every style
--- should have one. But if not, all parents are searched.
-getStyleFamily        :: Style       -> Styles -> Maybe StyleFamily
-getStyleFamily style@Style{..} styles
-  =     styleFamily
-    <|> (F.asum $ map (`getStyleFamily` styles) $ parents style styles)
-
--- | Each 'Style' has certain 'StyleProperties'. But sometimes not all property
--- values are specified. Instead, a value might be inherited from a
--- parent style. This function makes this chain of inheritance
--- concrete and easily accessible by encapsulating the necessary lookups.
--- The resulting list contains the direct properties of the style as the first
--- element, the ones of the direct parent element as the next one, and so on.
---
--- Note: There should also be default properties for each style family. These
---       are @not@ contained in this list because properties inherited from
---       parent elements take precedence over default styles.
---
--- This function is primarily meant to be used through convenience wrappers.
---
-stylePropertyChain    :: Style       -> Styles -> [StyleProperties]
-stylePropertyChain style styles
-  = map styleProperties (style : parents style styles)
-
---
-extendedStylePropertyChain :: [Style] -> Styles -> [StyleProperties]
-extendedStylePropertyChain [] _ = []
-extendedStylePropertyChain [style]       styles =    (stylePropertyChain style styles)
-                                                  ++ (maybeToList (fmap (lookupDefaultStyle' styles) (getStyleFamily style styles)))
-extendedStylePropertyChain (style:trace) styles =    (stylePropertyChain style styles)
-                                                  ++ (extendedStylePropertyChain trace styles)
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,27 +1,9 @@
-{-
-Copyright (C) 2014-2017 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-2017 Albert Krewinkel
+   Copyright   : Copyright (C) 2014-2024 Albert Krewinkel
    License     : GNU GPL, version 2 or above
 
-   Maintainer  : Albert Krewinkel <tarleb+pandoc@moltkeplatz.de>
+   Maintainer  : Albert Krewinkel <albert+pandoc@tarleb.com>
 
 Conversion of org-mode formatted plain text to 'Pandoc' document.
 -}
@@ -31,31 +13,26 @@
 import Text.Pandoc.Readers.Org.ParserState (optionsToParserState)
 import Text.Pandoc.Readers.Org.Parsing (OrgParser, readWithM)
 
-import Text.Pandoc.Class (PandocMonad)
+import Text.Pandoc.Class.PandocMonad (PandocMonad)
 import Text.Pandoc.Definition
-import Text.Pandoc.Error
 import Text.Pandoc.Options
 import Text.Pandoc.Parsing (reportLogMessages)
-import Text.Pandoc.Shared (crFilter)
-
+import Text.Pandoc.Sources (ToSources(..), ensureFinalNewlines)
 import Control.Monad.Except (throwError)
 import Control.Monad.Reader (runReaderT)
 
-import Data.Text (Text)
-import qualified Data.Text as T
-
 -- | Parse org-mode string and return a Pandoc document.
-readOrg :: PandocMonad m
+readOrg :: (PandocMonad m, ToSources a)
         => ReaderOptions -- ^ Reader options
-        -> Text          -- ^ String to parse (assuming @'\n'@ line endings)
+        -> a
         -> m Pandoc
 readOrg opts s = do
   parsed <- flip runReaderT def $
             readWithM parseOrg (optionsToParserState opts)
-            (T.unpack (crFilter s) ++ "\n\n")
+            (ensureFinalNewlines 2 (toSources s))
   case parsed of
     Right result -> return result
-    Left  _      -> throwError $ PandocParseError "problem parsing org"
+    Left  e      -> throwError e
 
 --
 -- Parser
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,27 +1,10 @@
-{-
-Copyright (C) 2014-2017 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 OverloadedStrings #-}
 {- |
    Module      : Text.Pandoc.Readers.Org.BlockStarts
-   Copyright   : Copyright (C) 2014-2017 Albert Krewinkel
+   Copyright   : Copyright (C) 2014-2024 Albert Krewinkel
    License     : GNU GPL, version 2 or above
 
-   Maintainer  : Albert Krewinkel <tarleb+pandoc@moltkeplatz.de>
+   Maintainer  : Albert Krewinkel <albert+pandoc@tarleb.com>
 
 Parsers for Org-mode inline elements.
 -}
@@ -40,8 +23,15 @@
   , endOfBlock
   ) where
 
-import Control.Monad (void)
+import Control.Monad (void, guard)
+import Data.Text (Text)
 import Text.Pandoc.Readers.Org.Parsing
+import Text.Pandoc.Definition as Pandoc
+import Text.Pandoc.Shared (safeRead)
+import Text.Pandoc.Parsing (lowerAlpha, upperAlpha)
+import Text.Pandoc.Extensions
+import Text.Pandoc.Readers.LaTeX.Math (inlineEnvironmentNames)
+import Data.Functor (($>))
 
 -- | Horizontal Line (five -- dashes or more)
 hline :: Monad m => OrgParser m ()
@@ -65,60 +55,85 @@
 gridTableStart = try $ skipSpaces <* char '+' <* char '-'
 
 
-latexEnvStart :: Monad m => OrgParser m String
-latexEnvStart = try $
-  skipSpaces *> string "\\begin{"
-             *> latexEnvName
-             <* string "}"
-             <* blankline
+latexEnvStart :: Monad m => OrgParser m Text
+latexEnvStart = try $ do
+  skipSpaces
+  string "\\begin{"
+  name <- latexEnvName
+  char '}'
+  guard $ name `notElem` inlineEnvironmentNames
+  pure name
  where
-   latexEnvName :: Monad m => OrgParser m String
-   latexEnvName = try $ mappend <$> many1 alphaNum <*> option "" (string "*")
+   latexEnvName :: Monad m => OrgParser m Text
+   latexEnvName = try $ mappend <$> many1Char alphaNum <*> option "" (textStr "*")
 
+listCounterCookie :: Monad m => OrgParser m Int
+listCounterCookie = try $
+  string "[@"
+  *> parseNum
+  <* char ']'
+  <* (skipSpaces <|> lookAhead eol)
+  where parseNum = (safeRead =<< many1Char digit)
+                   <|> snd <$> (lowerAlpha <|> upperAlpha)
+
 bulletListStart :: Monad m => OrgParser m Int
 bulletListStart = try $ do
   ind <- length <$> many spaceChar
    -- Unindented lists cannot use '*' bullets.
   oneOf (if ind == 0 then "+-" else "*+-")
   skipSpaces1 <|> lookAhead eol
-  return (ind + 1)
-
-genericListStart :: Monad m
-                 => OrgParser m String
-                 -> OrgParser m Int
-genericListStart listMarker = try $ do
-  ind <- length <$> many spaceChar
-  void listMarker
-  skipSpaces1 <|> lookAhead eol
+  optionMaybe listCounterCookie
   return (ind + 1)
 
 eol :: Monad m => OrgParser m ()
 eol = void (char '\n')
 
-orderedListStart :: Monad m => OrgParser m Int
-orderedListStart = genericListStart orderedListMarker
+orderedListStart :: Monad m => OrgParser m (Int, ListAttributes)
+orderedListStart = try $ do
+  ind <- length <$> many spaceChar
+  fancy <- option False $ True <$ guardEnabled Ext_fancy_lists
   -- Ordered list markers allowed in org-mode
-  where orderedListMarker = mappend <$> many1 digit <*> (pure <$> oneOf ".)")
+  let styles = (many1Char digit $> (if fancy
+                                       then Decimal
+                                       else DefaultStyle))
+               : if fancy
+                    then [ fst <$> lowerAlpha
+                         , fst <$> upperAlpha ]
+                    else []
+  let delims = [ char '.' $> (if fancy
+                                 then Period
+                                 else DefaultDelim)
+               , char ')' $> (if fancy
+                                 then OneParen
+                                 else DefaultDelim)
+               ]
+  style <- choice styles
+  delim <- choice delims
+  skipSpaces1 <|> lookAhead eol
+  start <- option 1 listCounterCookie
+  return (ind + 1, (start, style, delim))
 
-drawerStart :: Monad m => OrgParser m String
+drawerStart :: Monad m => OrgParser m Text
 drawerStart = try $ skipSpaces *> drawerName <* skipSpaces <* newline
- where drawerName = char ':' *> manyTill nonspaceChar (char ':')
+ where drawerName = char ':' *> manyTillChar nonspaceChar (char ':')
 
 metaLineStart :: Monad m => OrgParser m ()
 metaLineStart = try $ skipSpaces <* string "#+"
 
 commentLineStart :: Monad m => OrgParser m ()
-commentLineStart = try $ skipSpaces <* string "# "
+commentLineStart = try $
+  -- the first char after '#' must be a plain space character or a newline
+  skipSpaces <* string "#" <* lookAhead (oneOf " \n")
 
 exampleLineStart :: Monad m => OrgParser m ()
-exampleLineStart = () <$ try (skipSpaces *> string ": ")
+exampleLineStart = () <$ try (skipSpaces *> char ':' *> (void (char ' ') <|> lookAhead eol))
 
-noteMarker :: Monad m => OrgParser m String
+noteMarker :: Monad m => OrgParser m Text
 noteMarker = try $ do
   char '['
-  choice [ many1Till digit (char ']')
-         , (++) <$> string "fn:"
-                <*> many1Till (noneOf "\n\r\t ") (char ']')
+  choice [ many1TillChar digit (char ']')
+         , (<>) <$> textStr "fn:"
+                <*> many1TillChar (noneOf "\n\r\t ") (char ']')
          ]
 
 -- | Succeeds if the parser is at the end of a block.
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,28 +1,14 @@
-{-
-Copyright (C) 2014-2017 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  #-}
+{-# LANGUAGE ScopedTypeVariables #-}
+{-# LANGUAGE FlexibleContexts  #-}
+{-# LANGUAGE LambdaCase        #-}
+{-# LANGUAGE OverloadedStrings #-}
+{-# LANGUAGE RecordWildCards   #-}
 {- |
    Module      : Text.Pandoc.Readers.Org.Blocks
-   Copyright   : Copyright (C) 2014-2017 Albert Krewinkel
+   Copyright   : Copyright (C) 2014-2024 Albert Krewinkel
    License     : GNU GPL, version 2 or above
 
-   Maintainer  : Albert Krewinkel <tarleb+pandoc@moltkeplatz.de>
+   Maintainer  : Albert Krewinkel <albert+pandoc@tarleb.com>
 
 Parsers for Org-mode block elements.
 -}
@@ -32,29 +18,36 @@
   ) where
 
 import Text.Pandoc.Readers.Org.BlockStarts
-import Text.Pandoc.Readers.Org.DocumentTree (documentTree, headlineToBlocks)
+import Text.Pandoc.Readers.Org.DocumentTree (documentTree,
+                                             unprunedHeadlineToBlocks)
 import Text.Pandoc.Readers.Org.Inlines
 import Text.Pandoc.Readers.Org.Meta (metaExport, metaKey, metaLine)
 import Text.Pandoc.Readers.Org.ParserState
 import Text.Pandoc.Readers.Org.Parsing
-import Text.Pandoc.Readers.Org.Shared (cleanLinkString, isImageFilename,
-                                       originalLang, translateLang)
-
-import Text.Pandoc.Builder (Blocks, Inlines)
-import Text.Pandoc.Class (PandocMonad)
+import Text.Pandoc.Readers.Org.Shared (cleanLinkText, isImageFilename,
+                                       originalLang, translateLang, exportsCode)
+import Text.Pandoc.Readers.LaTeX.Math (inlineEnvironmentNames)
+import Text.Pandoc.Builder (Blocks, Inlines, Many(..))
+import Text.Pandoc.Class.PandocMonad (PandocMonad)
 import Text.Pandoc.Definition
 import Text.Pandoc.Options
 import Text.Pandoc.Shared (compactify, compactifyDL, safeRead)
 
 import Control.Monad (foldM, guard, mzero, void)
-import Data.Char (isSpace, toLower, toUpper)
+import Data.Bifunctor (bimap)
+import Data.Char (isSpace)
 import Data.Default (Default)
-import Data.List (foldl', isPrefixOf)
+import Data.Functor (($>))
+import qualified Data.List as L
 import Data.Maybe (fromMaybe, isJust, isNothing)
-import Data.Monoid ((<>))
-
+import Data.Text (Text)
+import Data.List.NonEmpty (nonEmpty)
+import System.FilePath
+import qualified Data.Foldable as F
+import qualified Data.Text as T
 import qualified Text.Pandoc.Builder as B
 import qualified Text.Pandoc.Walk as Walk
+import Text.Pandoc.Sources (ToSources(..))
 
 --
 -- parsing blocks
@@ -63,11 +56,10 @@
 -- | Get a list of blocks.
 blockList :: PandocMonad m => OrgParser m [Block]
 blockList = do
-  headlines      <- documentTree blocks inline
+  fHeadlineTree  <- documentTree blocks inline
   st             <- getState
-  headlineBlocks <- headlineToBlocks $ runF headlines st
-  -- ignore first headline, it's the document's title
-  return . drop 1 . B.toList $ headlineBlocks
+  let headlineTree = runF fHeadlineTree st
+  unprunedHeadlineToBlocks headlineTree st
 
 -- | Get the meta information saved in the state.
 meta :: Monad m => OrgParser m Meta
@@ -81,6 +73,7 @@
 block :: PandocMonad m => OrgParser m (F Blocks)
 block = choice [ mempty <$ blanklines
                , table
+               , dynamicBlock
                , orgBlock
                , figure
                , example
@@ -91,6 +84,7 @@
                , list
                , latexFragment
                , noteBlock
+               , rawOrgLine
                , paraOrPlain
                ] <?> "block"
 
@@ -106,10 +100,9 @@
 
 -- | Attributes that may be added to figures (like a name or caption).
 data BlockAttributes = BlockAttributes
-  { blockAttrName      :: Maybe String
-  , blockAttrLabel     :: Maybe String
+  { blockAttrName      :: Maybe Text
   , blockAttrCaption   :: Maybe (F Inlines)
-  , blockAttrKeyValues :: [(String, String)]
+  , blockAttrKeyValues :: [(Text, Text)]
   }
 
 -- | Convert BlockAttributes into pandoc Attr
@@ -117,146 +110,174 @@
 attrFromBlockAttributes BlockAttributes{..} =
   let
     ident   = fromMaybe mempty $ lookup "id" blockAttrKeyValues
-    classes = case lookup "class" blockAttrKeyValues of
-                Nothing     -> []
-                Just clsStr -> words clsStr
+    classes = maybe [] T.words $ lookup "class" blockAttrKeyValues
     kv      = filter ((`notElem` ["id", "class"]) . fst) blockAttrKeyValues
   in (ident, classes, kv)
 
-stringyMetaAttribute :: Monad m => OrgParser m (String, String)
+stringyMetaAttribute :: Monad m => OrgParser m (Text, Text)
 stringyMetaAttribute = try $ do
-  metaLineStart
-  attrName <- map toUpper <$> many1Till nonspaceChar (char ':')
+  metaLineStart *> notFollowedBy (stringAnyCase "begin" *> oneOf ":_")
+  attrName <- T.toLower <$> many1TillChar nonspaceChar (char ':')
   skipSpaces
   attrValue <- anyLine <|> ("" <$ newline)
   return (attrName, attrValue)
 
+-- | Parse a set of block attributes. Block attributes are given through
+-- lines like @#+caption: block caption@ or @#+attr_html: :width 20@.
+-- Parsing will fail if any line contains an attribute different from
+-- those attributes known to work on blocks.
 blockAttributes :: PandocMonad m => OrgParser m BlockAttributes
 blockAttributes = try $ do
   kv <- many stringyMetaAttribute
-  guard $ all (attrCheck . fst) kv
-  let caption = foldl' (appendValues "CAPTION") Nothing kv
-  let kvAttrs = foldl' (appendValues "ATTR_HTML") Nothing kv
-  let name    = lookup "NAME" kv
-  let label   = lookup "LABEL" kv
-  caption' <- case caption of
-                   Nothing -> return Nothing
-                   Just s  -> Just <$> parseFromString inlines (s ++ "\n")
-  kvAttrs' <- parseFromString keyValues . (++ "\n") $ fromMaybe mempty kvAttrs
+  guard $ all (isBlockAttr . fst) kv
+  let caption = L.foldl' (appendValues "caption") Nothing kv
+  let kvAttrs = L.foldl' (appendValues "attr_html") Nothing kv
+  let name    = snd <$> L.find ((`elem` ["name", "label"]) . fst) (reverse kv)
+  caption' <- traverse (parseFromString inlines . (<> "\n")) caption
+  kvAttrs' <- parseFromString keyValues . (<> "\n") $ fromMaybe mempty kvAttrs
   return BlockAttributes
            { blockAttrName = name
-           , blockAttrLabel = label
            , blockAttrCaption = caption'
            , blockAttrKeyValues = kvAttrs'
            }
  where
-   attrCheck :: String -> Bool
-   attrCheck x = x `elem` ["NAME", "LABEL", "CAPTION", "ATTR_HTML", "RESULTS"]
+   isBlockAttr :: Text -> Bool
+   isBlockAttr = flip elem
+                 [ "name", "label", "caption"
+                 , "attr_html", "attr_latex"
+                 , "results"
+                 ]
 
-   appendValues :: String -> Maybe String -> (String, String) -> Maybe String
+   appendValues :: Text -> Maybe Text -> (Text, Text) -> Maybe Text
    appendValues attrName accValue (key, value) =
      if key /= attrName
      then accValue
      else case accValue of
-            Just acc -> Just $ acc ++ ' ':value
+            Just acc -> Just $ acc <> " " <> value
             Nothing  -> Just value
 
 -- | Parse key-value pairs for HTML attributes
-keyValues :: Monad m => OrgParser m [(String, String)]
+keyValues :: Monad m => OrgParser m [(Text, Text)]
 keyValues = try $
   manyTill ((,) <$> key <*> value) newline
  where
-   key :: Monad m => OrgParser m String
-   key = try $ skipSpaces *> char ':' *> many1 nonspaceChar
+   key :: Monad m => OrgParser m Text
+   key = try $ skipSpaces *> char ':' *> many1Char nonspaceChar
 
-   value :: Monad m => OrgParser m String
-   value = skipSpaces *> manyTill anyChar endOfValue
+   value :: Monad m => OrgParser m Text
+   value = skipSpaces *> manyTillChar anyChar endOfValue
 
    endOfValue :: Monad m => OrgParser m ()
-   endOfValue =
-     lookAhead $ (() <$ try (many1 spaceChar <* key))
-              <|> () <$ newline
+   endOfValue = lookAhead (void $ try (many1 spaceChar <* key))
+            <|> try (skipSpaces <* lookAhead newline)
 
 
 --
--- Org Blocks (#+BEGIN_... / #+END_...)
+-- Org Blocks (#+begin_... / #+end_...)
 --
 
--- | Read an org-mode block delimited by #+BEGIN_TYPE and #+END_TYPE.
+-- | Read an org-mode block delimited by #+begin_type and #+end_type.
 orgBlock :: PandocMonad m => OrgParser m (F Blocks)
 orgBlock = try $ do
   blockAttrs <- blockAttributes
   blkType <- blockHeaderStart
   ($ blkType) $
-    case map toLower blkType of
-      "export"  -> exportBlock
-      "comment" -> rawBlockLines (const mempty)
-      "html"    -> rawBlockLines (return . B.rawBlock (lowercase blkType))
-      "latex"   -> rawBlockLines (return . B.rawBlock (lowercase blkType))
-      "ascii"   -> rawBlockLines (return . B.rawBlock (lowercase blkType))
-      "example" -> rawBlockLines (return . exampleCode)
-      "quote"   -> parseBlockLines (fmap B.blockQuote)
-      "verse"   -> verseBlock
-      "src"     -> codeBlock blockAttrs
-      _         -> parseBlockLines $
-                   let (ident, classes, kv) = attrFromBlockAttributes blockAttrs
-                   in fmap $ B.divWith (ident, classes ++ [blkType], kv)
+    case T.toLower blkType of
+      "export"    -> exportBlock
+      "comment"   -> rawBlockLines (const mempty)
+      "html"      -> rawBlockLines (return . B.rawBlock (T.toLower blkType))
+      "latex"     -> rawBlockLines (return . B.rawBlock (T.toLower blkType))
+      "ascii"     -> rawBlockLines (return . B.rawBlock (T.toLower blkType))
+      "example"   -> exampleBlock blockAttrs
+      "quote"     -> \x -> ignHeaders *> parseBlockLines (fmap B.blockQuote) x
+      "verse"     -> verseBlock
+      "src"       -> codeBlock blockAttrs
+      "note"      -> admonitionBlock "note" blockAttrs
+      "warning"   -> admonitionBlock "warning" blockAttrs
+      "tip"       -> admonitionBlock "tip" blockAttrs
+      "caution"   -> admonitionBlock "caution" blockAttrs
+      "important" -> admonitionBlock "important" blockAttrs
+      _           ->
+        -- case-sensitive checks
+        case blkType of
+          "abstract" -> metadataBlock
+          _ -> \bt -> do
+            params <- blockParameters
+            let (ident, classes, kv) = attrFromBlockAttributes blockAttrs
+                toDiv = (B.divWith (ident, classes ++ [blkType], kv <> params))
+            parseBlockLines (fmap toDiv) bt
  where
-   blockHeaderStart :: Monad m => OrgParser m String
-   blockHeaderStart = try $ skipSpaces *> stringAnyCase "#+begin_" *> orgArgWord
+   blockHeaderStart :: Monad m => OrgParser m Text
+   blockHeaderStart = try $ do
+     skipSpaces
+     metaLineStart
+     stringAnyCase "begin_"
+     many1Char (satisfy (not . isSpace))
 
-   lowercase :: String -> String
-   lowercase = map toLower
+admonitionBlock :: PandocMonad m
+                => Text -> BlockAttributes -> Text -> OrgParser m (F Blocks)
+admonitionBlock blockType blockAttrs rawtext = do
+  bls <- ignHeaders *> parseBlockLines id rawtext
+  let id' = fromMaybe mempty $ blockAttrName blockAttrs
+  pure $ fmap
+    (B.divWith (id', [blockType], []) .
+     (B.divWith ("", ["title"], []) (B.para (B.str (T.toTitle blockType))) <>))
+    bls
 
-rawBlockLines :: Monad m => (String   -> F Blocks) -> String -> OrgParser m (F Blocks)
+exampleBlock :: PandocMonad m => BlockAttributes -> Text -> OrgParser m (F Blocks)
+exampleBlock blockAttrs _label = do
+  skipSpaces
+  (classes, kv) <- switchesAsAttributes
+  newline
+  content <- rawBlockContent "example"
+  let id' = fromMaybe mempty $ blockAttrName blockAttrs
+  let codeBlck = B.codeBlockWith (id', classes, kv) content
+  return . return $ codeBlck
+
+rawBlockLines :: Monad m => (Text   -> F Blocks) -> Text -> OrgParser m (F Blocks)
 rawBlockLines f blockType = ignHeaders *> (f <$> rawBlockContent blockType)
 
-parseBlockLines :: PandocMonad m => (F Blocks -> F Blocks) -> String -> OrgParser m (F Blocks)
-parseBlockLines f blockType = ignHeaders *> (f <$> parsedBlockContent)
+parseBlockLines :: PandocMonad m => (F Blocks -> F Blocks) -> Text -> OrgParser m (F Blocks)
+parseBlockLines f blockType = (f <$> parsedBlockContent)
  where
    parsedBlockContent :: PandocMonad m => OrgParser m (F Blocks)
    parsedBlockContent = try $ do
      raw <- rawBlockContent blockType
-     parseFromString blocks (raw ++ "\n")
+     parseFromString blocks (raw <> "\n")
 
 -- | Read the raw string content of a block
-rawBlockContent :: Monad m => String -> OrgParser m String
-rawBlockContent blockType = try $ do
-  blkLines <- manyTill rawLine blockEnder
-  tabLen <- getOption readerTabStop
-  return
-    . unlines
-    . stripIndent
-    . map (tabsToSpaces tabLen . commaEscaped)
-    $ blkLines
- where
-   rawLine :: Monad m => OrgParser m String
-   rawLine = try $ ("" <$ blankline) <|> anyLine
-
-   blockEnder :: Monad m => OrgParser m ()
-   blockEnder = try $ skipSpaces <* stringAnyCase ("#+end_" <> blockType)
-
-   stripIndent :: [String] -> [String]
-   stripIndent strs = map (drop (shortestIndent strs)) strs
+rawBlockContent :: Monad m => Text -> OrgParser m Text
+rawBlockContent blockType = rawBlockContent' $
+   stringAnyCase ("#+end_" <> blockType)
 
-   shortestIndent :: [String] -> Int
-   shortestIndent = foldr (min . length . takeWhile isSpace) maxBound
-                    . filter (not . null)
+-- | Read the raw string content of a block
+rawBlockContent' :: Monad m => OrgParser m Text -> OrgParser m Text
+rawBlockContent' blockEnder = try $ do
+  blkLines <- manyTill rawLine (try $ skipSpaces <* blockEnder)
+  tabStop <- getOption readerTabStop
+  trimP <- orgStateTrimLeadBlkIndent <$> getState
+  -- split lines into indentation/contents tuples
+  let splitLines = map (T.span (\c -> c == ' ' || c == '\t')) blkLines
+  let countSpaces = T.foldr (\case {'\t' -> (tabStop +); _ -> (1 +)}) 0
+  let shortestIndent = foldr (min . countSpaces . fst) maxBound
+                     . filter (not . T.null . snd) -- ignore empty lines
+                     $ splitLines
+  let tabsToSpaces = T.replace "\t" (T.replicate tabStop " ")
+  let reIndent = if trimP
+                 then (T.drop shortestIndent . tabsToSpaces)
+                 else id
 
-   tabsToSpaces :: Int -> String -> String
-   tabsToSpaces _      []         = []
-   tabsToSpaces tabLen cs'@(c:cs) =
-       case c of
-         ' '  -> ' ':tabsToSpaces tabLen cs
-         '\t' -> replicate tabLen ' ' ++ tabsToSpaces tabLen cs
-         _    -> cs'
+  T.unlines (map (uncurry T.append . bimap reIndent commaEscaped) splitLines)
+   <$ updateState (\s -> s { orgStateTrimLeadBlkIndent = True })
+ where
+   rawLine :: Monad m => OrgParser m Text
+   rawLine = try $ ("" <$ blankline) <|> anyLine
 
-   commaEscaped :: String -> String
-   commaEscaped (',':cs@('*':_))     = cs
-   commaEscaped (',':cs@('#':'+':_)) = cs
-   commaEscaped (' ':cs)             = ' ':commaEscaped cs
-   commaEscaped ('\t':cs)            = '\t':commaEscaped cs
-   commaEscaped cs                   = cs
+   commaEscaped suff = case T.uncons suff of
+     Just (',', cs)
+       | "*"  <- T.take 1 cs -> cs
+       | "#+" <- T.take 2 cs -> cs
+     _                       -> suff
 
 -- | Read but ignore all remaining block headers.
 ignHeaders :: Monad m => OrgParser m ()
@@ -264,59 +285,69 @@
 
 -- | Read a block containing code intended for export in specific backends
 -- only.
-exportBlock :: Monad m => String -> OrgParser m (F Blocks)
+exportBlock :: Monad m => Text -> OrgParser m (F Blocks)
 exportBlock blockType = try $ do
   exportType <- skipSpaces *> orgArgWord <* ignHeaders
   contents   <- rawBlockContent blockType
-  returnF (B.rawBlock (map toLower exportType) contents)
+  returnF (B.rawBlock (T.toLower exportType) contents)
 
-verseBlock :: PandocMonad m => String -> OrgParser m (F Blocks)
+verseBlock :: PandocMonad m => Text -> OrgParser m (F Blocks)
 verseBlock blockType = try $ do
   ignHeaders
   content <- rawBlockContent blockType
   fmap B.lineBlock . sequence
-    <$> mapM parseVerseLine (lines content)
+    <$> mapM parseVerseLine (T.lines content)
  where
    -- replace initial spaces with nonbreaking spaces to preserve
    -- indentation, parse the rest as normal inline
-   parseVerseLine :: PandocMonad m => String -> OrgParser m (F Inlines)
+   parseVerseLine :: PandocMonad m => Text -> OrgParser m (F Inlines)
    parseVerseLine cs = do
-     let (initialSpaces, indentedLine) = span isSpace cs
-     let nbspIndent = if null initialSpaces
+     let (initialSpaces, indentedLine) = T.span isSpace cs
+     let nbspIndent = if T.null initialSpaces
                       then mempty
-                      else B.str $ map (const '\160') initialSpaces
-     line <- parseFromString inlines (indentedLine ++ "\n")
+                      else B.str $ T.map (const '\160') initialSpaces
+     line <- parseFromString inlines (indentedLine <> "\n")
      return (trimInlinesF $ pure nbspIndent <> line)
 
+-- | Parses an environment of the given name and adds the result to the document
+-- metadata under a key of the same name.
+metadataBlock :: PandocMonad m => Text -> OrgParser m (F Blocks)
+metadataBlock blockType = try $ do
+  ignHeaders
+  content <- parseBlockLines id blockType
+  meta'   <- orgStateMeta <$> getState
+  updateState $ \st ->
+    st { orgStateMeta = B.setMeta blockType <$> content <*> meta' }
+  return mempty
+
 -- | Read a code block and the associated results block if present.  Which of
--- boths blocks is included in the output is determined using the "exports"
+-- the blocks is included in the output is determined using the "exports"
 -- argument in the block header.
-codeBlock :: PandocMonad m => BlockAttributes -> String -> OrgParser m (F Blocks)
+codeBlock :: PandocMonad m => BlockAttributes -> Text -> OrgParser m (F Blocks)
 codeBlock blockAttrs blockType = do
   skipSpaces
-  (classes, kv)     <- codeHeaderArgs <|> (mempty <$ ignHeaders)
-  content           <- rawBlockContent blockType
-  resultsContent    <- option mempty babelResultsBlock
-  let id'            = fromMaybe mempty $ blockAttrName blockAttrs
-  let codeBlck       = B.codeBlockWith ( id', classes, kv ) content
-  let labelledBlck   = maybe (pure codeBlck)
-                             (labelDiv codeBlck)
-                             (blockAttrCaption blockAttrs)
+  (classes, kv)  <- codeHeaderArgs <|> (mempty <$ ignHeaders)
+  content        <- rawBlockContent blockType
+  resultsContent <- option mempty babelResultsBlock
+  let identifier = fromMaybe mempty $ blockAttrName blockAttrs
+  let classes'   = case classes of
+                     c:cs | Just c' <- T.stripPrefix "jupyter-" c ->
+                            c' : "code" : cs
+                     _ -> classes
+  let codeBlk    = B.codeBlockWith (identifier, classes', kv) content
+  let wrap       = maybe pure addCaption (blockAttrCaption blockAttrs)
   return $
-    (if exportsCode kv    then labelledBlck   else mempty) <>
+    (if exportsCode kv    then wrap codeBlk   else mempty) <>
     (if exportsResults kv then resultsContent else mempty)
  where
-   labelDiv :: Blocks -> F Inlines -> F Blocks
-   labelDiv blk value =
-     B.divWith nullAttr <$> (mappend <$> labelledBlock value <*> pure blk)
-
-   labelledBlock :: F Inlines -> F Blocks
-   labelledBlock = fmap (B.plain . B.spanWith ("", ["label"], []))
+   addCaption :: F Inlines -> Blocks -> F Blocks
+   addCaption caption blk = B.divWith ("", ["captioned-content"], [])
+                         <$> (mkCaptionBlock caption <> pure blk)
 
-   exportsCode :: [(String, String)] -> Bool
-   exportsCode = maybe True (`elem` ["code", "both"]) . lookup "exports"
+   mkCaptionBlock :: F Inlines -> F Blocks
+   mkCaptionBlock = fmap (B.divWith ("", ["caption"], []) . B.plain)
 
-   exportsResults :: [(String, String)] -> Bool
+   exportsResults :: [(Text, Text)] -> Bool
    exportsResults = maybe False (`elem` ["results", "both"]) . lookup "exports"
 
 -- | Parse the result of an evaluated babel code block.
@@ -331,7 +362,7 @@
   resultsMarker = try . void $ stringAnyCase "#+RESULTS:" *> blankline
 
 -- | Parse code block arguments
-codeHeaderArgs :: Monad m => OrgParser m ([String], [(String, String)])
+codeHeaderArgs :: Monad m => OrgParser m ([Text], [(Text, Text)])
 codeHeaderArgs = try $ do
   language   <- skipSpaces *> orgArgWord
   (switchClasses, switchKv) <- switchesAsAttributes
@@ -340,14 +371,14 @@
          , originalLang language <> switchKv <> parameters
          )
 
-switchesAsAttributes :: Monad m => OrgParser m ([String], [(String, String)])
+switchesAsAttributes :: Monad m => OrgParser m ([Text], [(Text, Text)])
 switchesAsAttributes = try $ do
   switches <- skipSpaces *> try (switch `sepBy` many1 spaceChar)
   return $ foldr addToAttr ([], []) switches
  where
-  addToAttr :: (Char, Maybe String, SwitchPolarity)
-            -> ([String], [(String, String)])
-            -> ([String], [(String, String)])
+  addToAttr :: (Char, Maybe Text, SwitchPolarity)
+            -> ([Text], [(Text, Text)])
+            -> ([Text], [(Text, Text)])
   addToAttr ('n', lineNum, pol) (cls, kv) =
     let kv' = case lineNum of
                 Just num -> ("startFrom", num):kv
@@ -367,18 +398,25 @@
 switchPolarity = (SwitchMinus <$ char '-') <|> (SwitchPlus <$ char '+')
 
 -- | Parses a source block switch option.
-switch :: Monad m => OrgParser m (Char, Maybe String, SwitchPolarity)
-switch = try $ lineNumberSwitch <|> labelSwitch <|> simpleSwitch
+switch :: Monad m => OrgParser m (Char, Maybe Text, SwitchPolarity)
+switch = try $ lineNumberSwitch <|> labelSwitch
+               <|> whitespaceSwitch <|> simpleSwitch
  where
    simpleSwitch = (\pol c -> (c, Nothing, pol)) <$> switchPolarity <*> letter
    labelSwitch = genericSwitch 'l' $
-     char '"' *> many1Till nonspaceChar (char '"')
+     char '"' *> many1TillChar nonspaceChar (char '"')
 
+whitespaceSwitch :: Monad m => OrgParser m (Char, Maybe Text, SwitchPolarity)
+whitespaceSwitch = do
+  string "-i"
+  updateState $ \s -> s { orgStateTrimLeadBlkIndent = False }
+  return ('i', Nothing, SwitchMinus)
+
 -- | Generic source block switch-option parser.
 genericSwitch :: Monad m
               => Char
-              -> OrgParser m String
-              -> OrgParser m (Char, Maybe String, SwitchPolarity)
+              -> OrgParser m Text
+              -> OrgParser m (Char, Maybe Text, SwitchPolarity)
 genericSwitch c p = try $ do
   polarity <- switchPolarity <* char c <* skipSpaces
   arg <- optionMaybe p
@@ -386,20 +424,21 @@
 
 -- | Reads a line number switch option. The line number switch can be used with
 -- example and source blocks.
-lineNumberSwitch :: Monad m => OrgParser m (Char, Maybe String, SwitchPolarity)
-lineNumberSwitch = genericSwitch 'n' (many digit)
+lineNumberSwitch :: Monad m => OrgParser m (Char, Maybe Text, SwitchPolarity)
+lineNumberSwitch = genericSwitch 'n' (manyChar digit)
 
-blockOption :: Monad m => OrgParser m (String, String)
+blockOption :: Monad m => OrgParser m (Text, Text)
 blockOption = try $ do
   argKey <- orgArgKey
   paramValue <- option "yes" orgParamValue
   return (argKey, paramValue)
 
-orgParamValue :: Monad m => OrgParser m String
+orgParamValue :: Monad m => OrgParser m Text
 orgParamValue = try $
   skipSpaces
     *> notFollowedBy orgArgKey
-    *> noneOf "\n\r" `many1Till` endOfValue
+    *> ((char '"' *> manyChar (noneOf "\n\r\"") <* char '"') <|>
+        noneOf "\n\r" `many1TillChar` endOfValue)
     <* skipSpaces
  where
   endOfValue = lookAhead $  try (skipSpaces <* oneOf "\n\r")
@@ -407,6 +446,34 @@
 
 
 --
+-- Dynamic block (#+begin: ...  #+end:)
+--
+
+-- | Parses a Dynamic Block, i.e., a block delimited by #+BEGIN: and
+-- #+END:.
+dynamicBlock :: PandocMonad m => OrgParser m (F Blocks)
+dynamicBlock = try $ do
+  metaLineStart *> stringAnyCase "begin:" *> spaces
+  blockname <- optionMaybe orgArgWord
+  blockArgs <- blockParameters
+  contents <- do
+    raw <- rawBlockContent' $ metaLineStart *> stringAnyCase "end:"
+    parseFromString blocks (raw <> "\n")
+  let attr = ("", maybe [] (:[]) blockname, blockArgs)
+  return $ B.divWith attr <$> contents
+
+-- | Parse block arguments; in order, this tries to parse a Lisp-style
+-- argument list, a set of key-value pairs using /equals/, and as a
+-- fallback the whole line as a single /parameters/ argument.
+blockParameters :: PandocMonad m => OrgParser m [(Text, Text)]
+blockParameters = choice
+  [ try $ manyTill ((,) <$> orgArgKey <*> orgParamValue) newline
+  , try $ manyTill ((,) <$> (spaces *> orgArgWord <* char '=') <*> orgArgWord)
+                   newline
+  , (\x -> [ ("parameters", x) | not (T.null x)]) <$> (skipSpaces *> anyLine)
+  ]
+
+--
 -- Drawers
 --
 
@@ -415,7 +482,7 @@
 -- export setting.
 genericDrawer :: PandocMonad m => OrgParser m (F Blocks)
 genericDrawer = try $ do
-  name    <- map toUpper <$> drawerStart
+  name    <- T.toUpper <$> drawerStart
   content <- manyTill drawerLine (try drawerEnd)
   state   <- getState
   -- Include drawer if it is explicitly included in or not explicitly excluded
@@ -427,16 +494,16 @@
     Right names | name `notElem` names -> return mempty
     _           -> drawerDiv name <$> parseLines content
  where
-  parseLines :: PandocMonad m => [String] -> OrgParser m (F Blocks)
-  parseLines = parseFromString blocks . (++ "\n") . unlines
+  parseLines :: PandocMonad m => [Text] -> OrgParser m (F Blocks)
+  parseLines = parseFromString blocks . (<> "\n") . T.unlines
 
-  drawerDiv :: String -> F Blocks -> F Blocks
+  drawerDiv :: Text -> F Blocks -> F Blocks
   drawerDiv drawerName = fmap $ B.divWith (mempty, [drawerName, "drawer"], mempty)
 
-drawerLine :: Monad m => OrgParser m String
+drawerLine :: Monad m => OrgParser m Text
 drawerLine = anyLine
 
-drawerEnd :: Monad m => OrgParser m String
+drawerEnd :: Monad m => OrgParser m Text
 drawerEnd = try $
   skipSpaces *> stringAnyCase ":END:" <* skipSpaces <* newline
 
@@ -451,33 +518,28 @@
 figure = try $ do
   figAttrs <- blockAttributes
   src <- skipSpaces *> selfTarget <* skipSpaces <* endOfParagraph
-  case cleanLinkString src of
+  case cleanLinkText src of
     Nothing     -> mzero
     Just imgSrc -> do
       guard (isImageFilename imgSrc)
       let isFigure = isJust $ blockAttrCaption figAttrs
       return $ imageBlock isFigure figAttrs imgSrc
  where
-   selfTarget :: PandocMonad m => OrgParser m String
+   selfTarget :: PandocMonad m => OrgParser m Text
    selfTarget = try $ char '[' *> linkTarget <* char ']'
 
-   imageBlock :: Bool -> BlockAttributes -> String -> F Blocks
+   imageBlock :: Bool -> BlockAttributes -> Text -> F Blocks
    imageBlock isFigure figAttrs imgSrc =
      let
        figName    = fromMaybe mempty $ blockAttrName figAttrs
-       figLabel   = fromMaybe mempty $ blockAttrLabel figAttrs
        figCaption = fromMaybe mempty $ blockAttrCaption figAttrs
        figKeyVals = blockAttrKeyValues figAttrs
-       attr       = (figLabel, mempty, figKeyVals)
-       figTitle   = (if isFigure then withFigPrefix else id) figName
-     in
-       B.para . B.imageWith attr imgSrc figTitle <$> figCaption
-
-   withFigPrefix :: String -> String
-   withFigPrefix cs =
-     if "fig:" `isPrefixOf` cs
-     then cs
-     else "fig:" ++ cs
+       attr       = (figName, mempty, figKeyVals)
+     in if isFigure
+           then (\c -> B.figureWith attr (B.simpleCaption (B.plain c))
+                       (B.plain $ B.image imgSrc "" mempty))
+                <$> figCaption
+           else B.para . B.imageWith attr imgSrc figName <$> figCaption
 
 -- | Succeeds if looking at the end of the current paragraph
 endOfParagraph :: Monad m => OrgParser m ()
@@ -490,13 +552,13 @@
 
 -- | Example code marked up by a leading colon.
 example :: Monad m => OrgParser m (F Blocks)
-example = try $ returnF . exampleCode =<< unlines <$> many1 exampleLine
+example = try $ returnF . exampleCode . T.unlines =<< many1 exampleLine
  where
-   exampleLine :: Monad m => OrgParser m String
+   exampleLine :: Monad m => OrgParser m Text
    exampleLine = try $ exampleLineStart *> anyLine
 
-exampleCode :: String -> Blocks
-exampleCode = B.codeBlockWith ("", ["example"], [])
+exampleCode :: Text -> Blocks
+exampleCode = B.codeBlockWith ("", [], [])
 
 
 --
@@ -504,43 +566,57 @@
 --
 
 specialLine :: PandocMonad m => OrgParser m (F Blocks)
-specialLine = fmap return . try $ rawExportLine <|> metaLine <|> commentLine
+specialLine = fmap return . try $
+  rawExportLine <|> printbibliographyLine <|> metaLine <|> commentLine
 
+printbibliographyLine :: PandocMonad m => OrgParser m Blocks
+printbibliographyLine = do
+  try $ skipSpaces <* string "#+print_bibliography:" <* anyLine
+  return $ B.divWith ("refs",[],[]) mempty
+
 -- | Include the content of a file.
 include :: PandocMonad m => OrgParser m (F Blocks)
 include = try $ do
   metaLineStart <* stringAnyCase "include:" <* skipSpaces
   filename <- includeTarget
-  includeArgs <- many (try $ skipSpaces *> many1 alphaNum)
+  includeArgs <- many (try $ skipSpaces *> many1Char alphaNum)
   params <- keyValues
   blocksParser <- case includeArgs of
       ("example" : _) -> return $ pure . B.codeBlock <$> parseRaw
       ["export"] -> return . returnF $ B.fromList []
-      ("export" : format : []) -> return $ pure . B.rawBlock format <$> parseRaw
+      ["export", format] -> return $ pure . B.rawBlock format <$> parseRaw
       ("src" : rest) -> do
         let attr = case rest of
                      [lang] -> (mempty, [lang], mempty)
                      _ -> nullAttr
         return $ pure . B.codeBlockWith attr <$> parseRaw
       _ -> return $ return . B.fromList . blockFilter params <$> blockList
-  insertIncludedFileF blocksParser ["."] filename
+  currentDir <- takeDirectory . sourceName <$> getPosition
+  let (startLine, endLine) =
+        case lookup "lines" params of
+          Nothing -> (Nothing, Nothing)
+          Just bounds -> let boundStr = T.drop 1 (T.dropEnd 1 bounds)
+                             begStr = T.takeWhile (/= '-') boundStr
+                             endStr = T.takeWhileEnd (/= '-') boundStr
+                         in (safeRead begStr, pred <$> safeRead endStr)
+  insertIncludedFile blocksParser toSources
+                     [currentDir] filename startLine endLine
  where
   includeTarget :: PandocMonad m => OrgParser m FilePath
   includeTarget = do
     char '"'
     manyTill (noneOf "\n\r\t") (char '"')
 
-  parseRaw :: PandocMonad m => OrgParser m String
-  parseRaw = many anyChar
+  parseRaw :: PandocMonad m => OrgParser m Text
+  parseRaw = manyChar anyChar
 
-  blockFilter :: [(String, String)] -> [Block] -> [Block]
+  blockFilter :: [(Text, Text)] -> [Block] -> [Block]
   blockFilter params blks =
     let minlvl = lookup "minlevel" params
     in case (minlvl >>= safeRead :: Maybe Int) of
          Nothing -> blks
          Just lvl -> let levels = Walk.query headerLevel blks
-                         -- CAVE: partial function in else
-                         curMin = if null levels then 0 else minimum levels
+                         curMin = maybe 0 minimum $ nonEmpty levels
                      in Walk.walk (shiftHeader (curMin - lvl)) blks
 
   headerLevel :: Block -> [Int]
@@ -549,12 +625,14 @@
 
   shiftHeader :: Int -> Block -> Block
   shiftHeader shift blk =
-    if shift <= 0
-    then blk
-    else case blk of
-      (Header lvl attr content) -> Header (lvl - shift) attr content
+    case blk of
+      (Header lvl attr content)
+       | lvl - shift > 0  -> Header (lvl - shift) attr content
+       | otherwise        -> Para content
       _ -> blk
 
+-- | Parses a meta line which defines a raw block. Currently recognized:
+-- @#+LATEX:@, @#+HTML:@, @#+TEXINFO:@, and @#+BEAMER@.
 rawExportLine :: PandocMonad m => OrgParser m Blocks
 rawExportLine = try $ do
   metaLineStart
@@ -563,8 +641,16 @@
     then B.rawBlock key <$> anyLine
     else mzero
 
+-- | Parses any meta line, i.e., a line starting with @#+@, into a raw
+-- org block. This should be the last resort when trying to parse
+-- keywords. Leading spaces are discarded.
+rawOrgLine :: PandocMonad m => OrgParser m (F Blocks)
+rawOrgLine = do
+  line <- metaLineStart *> anyLine
+  returnF $ B.rawBlock "org" $ "#+" <> line
+
 commentLine :: Monad m => OrgParser m Blocks
-commentLine = commentLineStart *> anyLine *> pure mempty
+commentLine = commentLineStart *> anyLine $> mempty
 
 
 --
@@ -593,47 +679,68 @@
   }
 
 table :: PandocMonad m => OrgParser m (F Blocks)
-table = gridTableWith blocks True <|> orgTable
-
--- | A normal org table
-orgTable :: PandocMonad m => OrgParser m (F Blocks)
-orgTable = try $ do
+table = try $ do
   -- don't allow a table on the first line of a list item; org requires that
   -- tables start at first non-space character on the line
   let isFirstInListItem st = orgStateParserContext st == ListItemState &&
                              isNothing (orgStateLastPreCharPos st)
-  guard =<< not . isFirstInListItem <$> getState
+  guard . not . isFirstInListItem =<< getState
   blockAttrs <- blockAttributes
+  let identMb = blockAttrName blockAttrs
+  tbl <- gridTableWith blocks <|> orgTable
+  withTables <- getExportSetting exportWithTables
+  return $ if withTables
+              then do
+                xs <- unMany <$> tbl
+                case F.toList xs of
+                  [Table _ _ cs th tb tf] -> do
+                    capt <- case blockAttrCaption blockAttrs of
+                              Nothing -> pure $ Caption Nothing []
+                              Just ils -> do
+                                ils' <- ils
+                                pure $ B.simpleCaption . B.plain $ ils'
+                    let attr = (fromMaybe mempty identMb, [],
+                                 blockAttrKeyValues blockAttrs)
+                    pure $ B.tableWith attr capt cs th tb tf
+                  _ -> tbl   -- should not happen
+              else mempty
+
+-- | A normal org table
+orgTable :: PandocMonad m => OrgParser m (F Blocks)
+orgTable = do
   lookAhead tableStart
-  do
-    rows <- tableRows
-    let caption = fromMaybe (return mempty) $ blockAttrCaption blockAttrs
-    return $ (<$> caption) . orgToPandocTable . normalizeTable =<< rowsToTable rows
+  rows <- tableRows
+  let orgTbl = normalizeTable <$> rowsToTable rows
+  return $ orgToPandocTable <$> orgTbl
 
-orgToPandocTable :: OrgTable
-                 -> Inlines
-                 -> Blocks
-orgToPandocTable (OrgTable colProps heads lns) caption =
-  let totalWidth = if any isJust (map columnRelWidth colProps)
+orgToPandocTable :: OrgTable -> Blocks
+orgToPandocTable (OrgTable colProps heads lns) =
+  let totalWidth = if any (isJust . columnRelWidth) colProps
                    then Just . sum $ map (fromMaybe 1 . columnRelWidth) colProps
                    else Nothing
-  in B.table caption (map (convertColProp totalWidth) colProps) heads lns
+  in B.tableWith nullAttr (Caption Nothing mempty)
+                 (map (convertColProp totalWidth) colProps)
+                 (TableHead nullAttr $ toHeaderRow heads)
+                 [TableBody nullAttr 0 [] $ map toRow lns]
+                 (TableFoot nullAttr [])
  where
-   convertColProp :: Maybe Int -> ColumnProperty -> (Alignment, Double)
+   toRow = Row nullAttr . map B.simpleCell
+   toHeaderRow l = [toRow l | not (null l)]
+   convertColProp :: Maybe Int -> ColumnProperty -> (Alignment, ColWidth)
    convertColProp totalWidth colProp =
      let
        align' = fromMaybe AlignDefault $ columnAlignment colProp
-       width' = fromMaybe 0 $ (\w t -> (fromIntegral w / fromIntegral t))
-                              <$> columnRelWidth colProp
-                              <*> totalWidth
-     in (align', width')
+       width' = (\w t -> fromIntegral w / fromIntegral t)
+                <$> columnRelWidth colProp
+                <*> totalWidth
+     in (align', maybe ColWidthDefault ColWidth width')
 
 tableRows :: PandocMonad m => OrgParser m [OrgTableRow]
 tableRows = try $ many (tableAlignRow <|> tableHline <|> tableContentRow)
 
 tableContentRow :: PandocMonad m => OrgParser m OrgTableRow
 tableContentRow = try $
-  OrgContentRow . sequence <$> (tableStart *> many1Till tableContentCell newline)
+  OrgContentRow . sequence <$> (tableStart *> manyTill tableContentCell newline)
 
 tableContentCell :: PandocMonad m => OrgParser m (F Blocks)
 tableContentCell = try $
@@ -648,22 +755,22 @@
   return $ OrgAlignRow colProps
 
 columnPropertyCell :: Monad m => OrgParser m ColumnProperty
-columnPropertyCell = emptyCell <|> propCell <?> "alignment info"
+columnPropertyCell = emptyOrgCell <|> propCell <?> "alignment info"
  where
-   emptyCell = ColumnProperty Nothing Nothing <$ try (skipSpaces *> endOfCell)
+   emptyOrgCell = ColumnProperty Nothing Nothing <$ try (skipSpaces *> endOfCell)
    propCell = try $ ColumnProperty
                  <$> (skipSpaces
                       *> char '<'
                       *> optionMaybe tableAlignFromChar)
-                 <*> (optionMaybe (many1 digit >>= safeRead)
+                 <*> (optionMaybe (many1Char digit >>= safeRead)
                       <* char '>'
-                      <* emptyCell)
+                      <* emptyOrgCell)
 
 tableAlignFromChar :: Monad m => OrgParser m Alignment
 tableAlignFromChar = try $
-  choice [ char 'l' *> return AlignLeft
-         , char 'c' *> return AlignCenter
-         , char 'r' *> return AlignRight
+  choice [ char 'l' $> AlignLeft
+         , char 'c' $> AlignCenter
+         , char 'r' $> AlignRight
          ]
 
 tableHline :: Monad m => OrgParser m OrgTableRow
@@ -723,26 +830,29 @@
 --
 -- LaTeX fragments
 --
-latexFragment :: Monad m => OrgParser m (F Blocks)
+latexFragment :: PandocMonad m => OrgParser m (F Blocks)
 latexFragment = try $ do
   envName <- latexEnvStart
-  content <- mconcat <$> manyTill anyLineNewline (latexEnd envName)
-  returnF $ B.rawBlock "latex" (content `inLatexEnv` envName)
+  guard $ envName `notElem` inlineEnvironmentNames
+  texOpt  <- getExportSetting exportWithLatex
+  let envStart = "\\begin{" <> envName <> "}"
+  let envEnd = "\\end{" <> envName <> "}"
+  envContent <- do
+    content <- manyTillChar anyChar (latexEnd envName)
+    return $ envStart <> content <> envEnd
+  returnF $ case texOpt of
+    TeXExport -> B.rawBlock "latex" (envContent <> "\n")
+    TeXIgnore   -> mempty
+    TeXVerbatim -> B.para . B.text $ envContent
  where
-   c `inLatexEnv` e = mconcat [ "\\begin{", e, "}\n"
-                              , c
-                              , "\\end{", e, "}\n"
-                              ]
-
-latexEnd :: Monad m => String -> OrgParser m ()
-latexEnd envName = try $
-  () <$ skipSpaces
-     <* string ("\\end{" ++ envName ++ "}")
-     <* blankline
+  latexEnd :: Monad m => Text -> OrgParser m ()
+  latexEnd envName = try . void
+     $ textStr ("\\end{" <> envName <> "}")
+    <* blankline
 
 
 --
--- Footnote defintions
+-- Footnote definitions
 --
 noteBlock :: PandocMonad m => OrgParser m (F Blocks)
 noteBlock = try $ do
@@ -762,13 +872,13 @@
   -- Make sure we are not looking at a headline
   notFollowedBy' headerStart
   ils <- inlines
-  nl <- option False (newline *> return True)
+  nl <- option False (newline $> True)
   -- Read block as paragraph, except if we are in a list context and the block
   -- is directly followed by a list item, in which case the block is read as
   -- plain text.
   try (guard nl
-       *> notFollowedBy (inList *> (orderedListStart <|> bulletListStart))
-       *> return (B.para <$> ils))
+       *> notFollowedBy (inList *> (void orderedListStart <|> void bulletListStart))
+       $> (B.para <$> ils))
     <|>  return (B.plain <$> ils)
 
 
@@ -791,7 +901,7 @@
   fmap (B.bulletList . compactify) . sequence
     <$> many1 (listItem (bulletListStart `indented` indent))
 
-indented :: Monad m => OrgParser m Int -> Int -> OrgParser m Int
+indented :: OrgParser m Int -> Int -> OrgParser m Int
 indented indentedMarker minIndent = try $ do
   n <- indentedMarker
   guard (minIndent <= n)
@@ -799,44 +909,94 @@
 
 orderedList :: PandocMonad m => OrgParser m (F Blocks)
 orderedList = try $ do
-  indent <- lookAhead orderedListStart
-  fmap (B.orderedList . compactify) . sequence
-    <$> many1 (listItem (orderedListStart `indented` indent))
+  (indent, attr) <- lookAhead orderedListStart
+  fmap (B.orderedListWith attr . compactify) . sequence
+    <$> many1 (listItem ((fst <$> orderedListStart) `indented` indent))
 
 definitionListItem :: PandocMonad m
                    => OrgParser m Int
                    -> OrgParser m (F (Inlines, [Blocks]))
 definitionListItem parseIndentedMarker = try $ do
   markerLength <- parseIndentedMarker
-  term <- manyTill (noneOf "\n\r") (try definitionMarker)
+  term <- manyTillChar (noneOf "\n\r") (try definitionMarker)
   line1 <- anyLineNewline
   blank <- option "" ("\n" <$ blankline)
-  cont <- concat <$> many (listContinuation markerLength)
+  cont <- T.concat <$> many (listContinuation markerLength)
   term' <- parseFromString inlines term
-  contents' <- parseFromString blocks $ line1 ++ blank ++ cont
+  contents' <- parseFromString blocks $ line1 <> blank <> cont
   return $ (,) <$> term' <*> fmap (:[]) contents'
  where
    definitionMarker =
      spaceChar *> string "::" <* (spaceChar <|> lookAhead newline)
 
+-- | Checkbox for tasks.
+data Checkbox
+  = UncheckedBox
+  | CheckedBox
+  | SemicheckedBox
+
+-- | Parses a checkbox in a plain list.
+checkbox :: PandocMonad m
+         => OrgParser m Checkbox
+checkbox = do
+  guardEnabled Ext_task_lists
+  try (char '[' *> status <* char ']') <?> "checkbox"
+  where
+    status = choice
+      [ UncheckedBox   <$ char ' '
+      , CheckedBox     <$ char 'X'
+      , SemicheckedBox <$ char '-'
+      ]
+
+checkboxToInlines :: Checkbox -> Inline
+checkboxToInlines = B.Str . \case
+  UncheckedBox   -> "☐"
+  SemicheckedBox -> "☐"
+  CheckedBox     -> "☒"
+
 -- | parse raw text for one list item
 listItem :: PandocMonad m
          => OrgParser m Int
          -> OrgParser m (F Blocks)
 listItem parseIndentedMarker = try . withContext ListItemState $ do
   markerLength <- try parseIndentedMarker
+  box <- optionMaybe checkbox
   firstLine <- anyLineNewline
   blank <- option "" ("\n" <$ blankline)
-  rest <- concat <$> many (listContinuation markerLength)
-  parseFromString blocks $ firstLine ++ blank ++ rest
+  rest <- T.concat <$> many (listContinuation markerLength)
+  contents <- parseFromString (do initial <- paraOrPlain <|> pure mempty
+                                  subsequent <- blocks
+                                  return $ initial <> subsequent)
+                (firstLine <> blank <> rest)
+  return (maybe id (prependInlines . checkboxToInlines) box <$> contents)
 
+-- | Prepend inlines to blocks, adding them to the first paragraph or
+-- creating a new Plain element if necessary.
+prependInlines :: Inline -> Blocks -> Blocks
+prependInlines inlns = B.fromList . prepend . B.toList
+  where
+    prepend (Plain is : bs) = Plain (inlns : Space : is) : bs
+    prepend (Para  is : bs) = Para  (inlns : Space : is) : bs
+    prepend bs              = Plain [inlns, Space] : bs
+
 -- continuation of a list item - indented and separated by blankline or endline.
 -- Note: nested lists are parsed as continuations.
-listContinuation :: Monad m => Int
-                 -> OrgParser m String
+listContinuation :: PandocMonad m => Int -> OrgParser m Text
 listContinuation markerLength = try $ do
   notFollowedBy' blankline
-  mappend <$> (concat <$> many1 listLine)
-          <*> many blankline
+  mappend <$> (T.concat <$> many1 (listContinuation' markerLength))
+          <*> manyChar blankline
  where
-   listLine = try $ indentWith markerLength *> anyLineNewline
+   listContinuation' indentation =
+      blockLines indentation <|> listLine indentation
+   listLine indentation = try $ indentWith indentation *> anyLineNewline
+  -- The block attributes and start must be appropriately indented,
+  -- but the contents, and end do not.
+   blockLines indentation =
+      try $ lookAhead (indentWith indentation
+                       >> blockAttributes
+                       >>= (\blockAttrs ->
+                              case attrFromBlockAttributes blockAttrs of
+                                ("", [], []) -> countChar 1 anyChar
+                                _ -> indentWith indentation))
+            >> (snd <$> withRaw orgBlock)
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,50 +1,34 @@
-{-
-Copyright (C) 2014-2017 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  #-}
-{-# LANGUAGE ViewPatterns     #-}
+{-# LANGUAGE FlexibleContexts  #-}
+{-# LANGUAGE OverloadedStrings #-}
+{-# LANGUAGE TupleSections     #-}
 {- |
    Module      : Text.Pandoc.Readers.Org.DocumentTree
-   Copyright   : Copyright (C) 2014-2017 Albert Krewinkel
+   Copyright   : Copyright (C) 2014-2024 Albert Krewinkel
    License     : GNU GPL, version 2 or above
 
-   Maintainer  : Albert Krewinkel <tarleb+pandoc@moltkeplatz.de>
+   Maintainer  : Albert Krewinkel <albert+pandoc@tarleb.com>
 
 Parsers for org-mode headlines and document subtrees
 -}
 module Text.Pandoc.Readers.Org.DocumentTree
   ( documentTree
-  , headlineToBlocks
+  , unprunedHeadlineToBlocks
   ) where
 
-import Control.Arrow ((***))
-import Control.Monad (guard, void)
-import Data.Char (toLower, toUpper)
+import Control.Arrow ((***), first)
+import Control.Monad (guard, mplus)
 import Data.List (intersperse)
-import Data.Monoid ((<>))
+import Data.Maybe (mapMaybe)
+import Data.Text (Text)
 import Text.Pandoc.Builder (Blocks, Inlines)
-import Text.Pandoc.Class (PandocMonad)
+import Text.Pandoc.Class.PandocMonad (PandocMonad)
 import Text.Pandoc.Definition
 import Text.Pandoc.Readers.Org.BlockStarts
 import Text.Pandoc.Readers.Org.ParserState
 import Text.Pandoc.Readers.Org.Parsing
 
-import qualified Data.Map as Map
+import qualified Data.Set as Set
+import qualified Data.Text as T
 import qualified Text.Pandoc.Builder as B
 
 --
@@ -57,9 +41,11 @@
              -> OrgParser m (F Inlines)
              -> OrgParser m (F Headline)
 documentTree blocks inline = do
+  many commentLine
+  properties <- option mempty propertiesDrawer
   initialBlocks <- blocks
   headlines <- sequence <$> manyTill (headline blocks inline 1) eof
-  title <- fmap (getTitle . unMeta) . orgStateMeta <$> getState
+  title <- fmap docTitle . orgStateMeta <$> getState
   return $ do
     headlines' <- headlines
     initialBlocks' <- initialBlocks
@@ -69,43 +55,38 @@
       , headlineTodoMarker = Nothing
       , headlineText = B.fromList title'
       , headlineTags = mempty
-      , headlineProperties = mempty
+      , headlinePlanning = emptyPlanning
+      , headlineProperties = properties
       , headlineContents = initialBlocks'
       , headlineChildren = headlines'
       }
- where
-  getTitle :: Map.Map String MetaValue -> [Inline]
-  getTitle metamap =
-    case Map.lookup "title" metamap of
-      Just (MetaInlines inlns) -> inlns
-      _                        -> []
-
-newtype Tag = Tag { fromTag :: String }
-  deriving (Show, Eq)
+  where
+    commentLine :: Monad m => OrgParser m ()
+    commentLine = commentLineStart <* anyLine
 
 -- | Create a tag containing the given string.
-toTag :: String -> Tag
+toTag :: Text -> Tag
 toTag = Tag
 
 -- | The key (also called name or type) of a property.
-newtype PropertyKey = PropertyKey { fromKey :: String }
+newtype PropertyKey = PropertyKey { fromKey :: Text }
   deriving (Show, Eq, Ord)
 
 -- | Create a property key containing the given string.  Org mode keys are
 -- case insensitive and are hence converted to lower case.
-toPropertyKey :: String -> PropertyKey
-toPropertyKey = PropertyKey . map toLower
+toPropertyKey :: Text -> PropertyKey
+toPropertyKey = PropertyKey . T.toLower
 
 -- | The value assigned to a property.
-newtype PropertyValue = PropertyValue { fromValue :: String }
+newtype PropertyValue = PropertyValue { fromValue :: Text }
 
 -- | Create a property value containing the given string.
-toPropertyValue :: String -> PropertyValue
+toPropertyValue :: Text -> PropertyValue
 toPropertyValue = PropertyValue
 
 -- | Check whether the property value is non-nil (i.e. truish).
 isNonNil :: PropertyValue -> Bool
-isNonNil p = map toLower (fromValue p) `notElem` ["()", "{}", "nil"]
+isNonNil p = T.toLower (fromValue p) `notElem` ["()", "{}", "nil"]
 
 -- | Key/value pairs from a PROPERTIES drawer
 type Properties = [(PropertyKey, PropertyValue)]
@@ -116,6 +97,7 @@
   , headlineTodoMarker :: Maybe TodoMarker
   , headlineText       :: Inlines
   , headlineTags       :: [Tag]
+  , headlinePlanning   :: PlanningInfo -- ^ subtree planning information
   , headlineProperties :: Properties
   , headlineContents   :: Blocks
   , headlineChildren   :: [Headline]
@@ -132,14 +114,13 @@
   level <- headerStart
   guard (lvl <= level)
   todoKw <- optionMaybe todoKeyword
-  title <- trimInlinesF . mconcat <$> manyTill inline endOfTitle
-  tags  <- option [] headerTags
-  newline
+  (title, tags) <- manyThen inline endOfTitle
+  planning   <- option emptyPlanning planningInfo
   properties <- option mempty propertiesDrawer
   contents   <- blocks
   children   <- many (headline blocks inline (level + 1))
   return $ do
-    title'    <- title
+    title'    <- trimInlinesF (mconcat title)
     contents' <- contents
     children' <- sequence children
     return Headline
@@ -147,33 +128,107 @@
       , headlineTodoMarker = todoKw
       , headlineText = title'
       , headlineTags = tags
+      , headlinePlanning = planning
       , headlineProperties = properties
       , headlineContents = contents'
       , headlineChildren = children'
       }
  where
-   endOfTitle :: Monad m => OrgParser m ()
-   endOfTitle = void . lookAhead $ optional headerTags *> newline
+   endOfTitle :: Monad m => OrgParser m [Tag]
+   endOfTitle = try $ do
+     skipSpaces
+     tags <- option [] (headerTags <* skipSpaces)
+     newline
+     return tags
 
    headerTags :: Monad m => OrgParser m [Tag]
-   headerTags = try $
-     let tag = many1 (alphaNum <|> oneOf "@%#_") <* char ':'
-     in map toTag <$> (skipSpaces *> char ':' *> many1 tag <* skipSpaces)
+   headerTags = try $ do
+     char ':'
+     endBy1 (toTag <$> orgTagWord) (char ':')
 
+   manyThen :: Monad m
+            => OrgParser m a
+            -> OrgParser m b
+            -> OrgParser m ([a], b)
+   manyThen p end = (([],) <$> try end) <|> do
+     x <- p
+     first (x:) <$> manyThen p end
+
+   -- titleFollowedByTags :: Monad m => OrgParser m (Inlines, [Tag])
+   -- titleFollowedByTags = do
+
+
+unprunedHeadlineToBlocks :: Monad m => Headline -> OrgParserState -> OrgParser m [Block]
+unprunedHeadlineToBlocks hdln st =
+  let usingSelectedTags = docContainsSelectTags hdln st
+      rootNode = if not usingSelectedTags
+                   then hdln
+                   else includeRootAndSelected hdln st
+      rootNode' = removeExplicitlyExcludedNodes rootNode st
+  in if not usingSelectedTags ||
+        any (`Set.member` orgStateSelectTags st) (headlineTags rootNode')
+        then do headlineBlocks <- headlineToBlocks rootNode'
+                -- add metadata from root node :PROPERTIES:
+                updateState $ \s ->
+                  s{ orgStateMeta = foldr
+                    (\(PropertyKey k, PropertyValue v) m ->
+                        B.setMeta k v <$> m)
+                    (orgStateMeta s)
+                    (headlineProperties rootNode') }
+                -- ignore first headline, it's the document's title
+                return $ drop 1 $ B.toList headlineBlocks
+        else do headlineBlocks <- mconcat <$> mapM headlineToBlocks
+                                                   (headlineChildren rootNode')
+                return . B.toList $ headlineBlocks
+
 -- | Convert an Org mode headline (i.e. a document tree) into pandoc's Blocks
 headlineToBlocks :: Monad m => Headline -> OrgParser m Blocks
-headlineToBlocks hdln@Headline {..} = do
-  maxHeadlineLevels <- getExportSetting exportHeadlineLevels
+headlineToBlocks hdln = do
+  maxLevel <- getExportSetting exportHeadlineLevels
+  let tags = headlineTags hdln
+  let text = headlineText hdln
+  let level = headlineLevel hdln
   case () of
-    _ | any isNoExportTag headlineTags     -> return mempty
-    _ | any isArchiveTag  headlineTags     -> archivedHeadlineToBlocks hdln
-    _ | isCommentTitle headlineText        -> return mempty
-    _ | headlineLevel >= maxHeadlineLevels -> headlineToHeaderWithList hdln
-    _ | otherwise                          -> headlineToHeaderWithContents hdln
+    _ | any isArchiveTag  tags -> archivedHeadlineToBlocks hdln
+    _ | isCommentTitle text    -> return mempty
+    _ | maxLevel <= level      -> headlineToHeaderWithList hdln
+    _ | otherwise              -> headlineToHeaderWithContents hdln
 
-isNoExportTag :: Tag -> Bool
-isNoExportTag = (== toTag "noexport")
+removeExplicitlyExcludedNodes :: Headline -> OrgParserState -> Headline
+removeExplicitlyExcludedNodes hdln st =
+  hdln { headlineChildren =
+           [removeExplicitlyExcludedNodes childHdln st |
+              childHdln <- headlineChildren hdln,
+              not $ headlineContainsExcludeTags childHdln st] }
 
+includeRootAndSelected :: Headline -> OrgParserState -> Headline
+includeRootAndSelected hdln st =
+  hdln { headlineChildren = mapMaybe (`includeAncestorsAndSelected` st)
+                                     (headlineChildren hdln)}
+
+docContainsSelectTags :: Headline -> OrgParserState -> Bool
+docContainsSelectTags hdln st =
+  headlineContainsSelectTags hdln st ||
+  any (`docContainsSelectTags` st) (headlineChildren hdln)
+
+includeAncestorsAndSelected :: Headline -> OrgParserState -> Maybe Headline
+includeAncestorsAndSelected hdln st =
+  if headlineContainsSelectTags hdln st
+    then Just hdln
+    else let children = mapMaybe (`includeAncestorsAndSelected` st)
+                                 (headlineChildren hdln)
+         in case children of
+              [] -> Nothing
+              _ -> Just $ hdln { headlineChildren = children }
+
+headlineContainsSelectTags :: Headline -> OrgParserState -> Bool
+headlineContainsSelectTags hdln st =
+  any (`Set.member` orgStateSelectTags st) (headlineTags hdln)
+
+headlineContainsExcludeTags :: Headline -> OrgParserState -> Bool
+headlineContainsExcludeTags hdln st =
+  any (`Set.member` orgStateExcludeTags st) (headlineTags hdln)
+
 isArchiveTag :: Tag -> Bool
 isArchiveTag = (== toTag "ARCHIVE")
 
@@ -181,8 +236,9 @@
 -- FIXME: This accesses builder internals not intended for use in situations
 -- like these.  Replace once keyword parsing is supported.
 isCommentTitle :: Inlines -> Bool
-isCommentTitle (B.toList -> (Str "COMMENT":_)) = True
-isCommentTitle _                               = False
+isCommentTitle inlns = case B.toList inlns of
+  (Str "COMMENT":_) -> True
+  _ -> False
 
 archivedHeadlineToBlocks :: Monad m => Headline -> OrgParser m Blocks
 archivedHeadlineToBlocks hdln = do
@@ -193,17 +249,23 @@
     ArchivedTreesHeadlineOnly -> headlineToHeader hdln
 
 headlineToHeaderWithList :: Monad m => Headline -> OrgParser m Blocks
-headlineToHeaderWithList hdln@Headline {..} = do
+headlineToHeaderWithList hdln = do
   maxHeadlineLevels <- getExportSetting exportHeadlineLevels
   header        <- headlineToHeader hdln
-  listElements  <- mapM headlineToBlocks headlineChildren
+  listElements  <- mapM headlineToBlocks (headlineChildren hdln)
+  planningBlock <- planningToBlock (headlinePlanning hdln)
   let listBlock  = if null listElements
                    then mempty
                    else B.orderedList listElements
-  let headerText = if maxHeadlineLevels == headlineLevel
+  let headerText = if maxHeadlineLevels == headlineLevel hdln
                    then header
                    else flattenHeader header
-  return $ headerText <> headlineContents <> listBlock
+  return . mconcat $
+    [ headerText
+    , planningBlock
+    , headlineContents hdln
+    , listBlock
+    ]
  where
    flattenHeader :: Blocks -> Blocks
    flattenHeader blks =
@@ -212,57 +274,62 @@
        _                    -> mempty
 
 headlineToHeaderWithContents :: Monad m => Headline -> OrgParser m Blocks
-headlineToHeaderWithContents hdln@Headline {..} = do
+headlineToHeaderWithContents hdln = do
   header         <- headlineToHeader hdln
-  childrenBlocks <- mconcat <$> mapM headlineToBlocks headlineChildren
-  return $ header <> headlineContents <> childrenBlocks
+  planningBlock <- planningToBlock (headlinePlanning hdln)
+  childrenBlocks <- mconcat <$> mapM headlineToBlocks (headlineChildren hdln)
+  return $ header <> planningBlock <> headlineContents hdln <> childrenBlocks
 
 headlineToHeader :: Monad m => Headline -> OrgParser m Blocks
-headlineToHeader Headline {..} = do
+headlineToHeader hdln = do
   exportTodoKeyword <- getExportSetting exportWithTodoKeywords
   exportTags        <- getExportSetting exportWithTags
   let todoText    = if exportTodoKeyword
-                    then case headlineTodoMarker of
+                    then case headlineTodoMarker hdln of
                       Just kw -> todoKeywordToInlines kw <> B.space
                       Nothing -> mempty
                     else mempty
-  let text        = todoText <> headlineText <>
+  let text        = todoText <> headlineText hdln <>
                     if exportTags
-                    then tagsToInlines headlineTags
+                    then tagsToInlines (headlineTags hdln)
                     else mempty
-  let propAttr    = propertiesToAttr headlineProperties
-  attr           <- registerHeader propAttr headlineText
-  return $ B.headerWith attr headlineLevel text
+  let propAttr    = propertiesToAttr (headlineProperties hdln)
+  attr           <- registerHeader propAttr (headlineText hdln)
+  return $ B.headerWith attr (headlineLevel hdln) text
 
 todoKeyword :: Monad m => OrgParser m TodoMarker
 todoKeyword = try $ do
   taskStates <- activeTodoMarkers <$> getState
-  let kwParser tdm = try (tdm <$ string (todoMarkerName tdm) <* spaceChar)
+  let kwParser tdm = try (tdm <$ textStr (todoMarkerName tdm)
+                              <* spaceChar
+                              <* updateLastPreCharPos)
   choice (map kwParser taskStates)
 
 todoKeywordToInlines :: TodoMarker -> Inlines
 todoKeywordToInlines tdm =
   let todoText  = todoMarkerName tdm
-      todoState = map toLower . show $ todoMarkerState tdm
+      todoState = T.toLower . T.pack . show $ todoMarkerState tdm
       classes = [todoState, todoText]
   in B.spanWith (mempty, classes, mempty) (B.str todoText)
 
 propertiesToAttr :: Properties -> Attr
 propertiesToAttr properties =
   let
-    toStringPair = fromKey *** fromValue
+    toTextPair = fromKey *** fromValue
     customIdKey = toPropertyKey "custom_id"
+    idKey = toPropertyKey "id"
     classKey    = toPropertyKey "class"
     unnumberedKey = toPropertyKey "unnumbered"
-    specialProperties = [customIdKey, classKey, unnumberedKey]
-    id'  = maybe mempty fromValue . lookup customIdKey $ properties
+    specialProperties = [customIdKey, idKey, classKey, unnumberedKey]
+    id'  = maybe mempty fromValue $
+              (lookup customIdKey properties `mplus` lookup idKey properties)
     cls  = maybe mempty fromValue . lookup classKey    $ properties
-    kvs' = map toStringPair . filter ((`notElem` specialProperties) . fst)
+    kvs' = map toTextPair . filter ((`notElem` specialProperties) . fst)
            $ properties
     isUnnumbered =
       maybe False isNonNil . lookup unnumberedKey $ properties
   in
-    (id', words cls ++ ["unnumbered" | isUnnumbered], kvs')
+    (id', T.words cls ++ ["unnumbered" | isUnnumbered], kvs')
 
 tagsToInlines :: [Tag] -> Inlines
 tagsToInlines [] = mempty
@@ -276,16 +343,67 @@
 tagSpan :: Tag -> Inlines -> Inlines
 tagSpan t = B.spanWith ("", ["tag"], [("tag-name", fromTag t)])
 
+-- | Render planning info as a block iff the respective export setting is
+-- enabled.
+planningToBlock :: Monad m => PlanningInfo -> OrgParser m Blocks
+planningToBlock planning = do
+  includePlanning <- getExportSetting exportWithPlanning
+  return $
+    if includePlanning
+    then B.plain . mconcat . intersperse B.space . filter (/= mempty) $
+         [ datumInlines planningClosed "CLOSED"
+         , datumInlines planningDeadline "DEADLINE"
+         , datumInlines planningScheduled "SCHEDULED"
+         ]
+    else mempty
+ where
+  datumInlines field name =
+    case field planning of
+      Nothing -> mempty
+      Just time ->   B.strong (B.str name <> B.str ":")
+                  <> B.space
+                  <> B.emph (B.str time)
 
+-- | An Org timestamp, including repetition marks. TODO: improve
+type Timestamp = Text
 
+timestamp :: Monad m => OrgParser m Timestamp
+timestamp = try $ do
+  openChar <- oneOf "<["
+  let isActive = openChar == '<'
+  let closeChar = if isActive then '>' else ']'
+  content <- many1TillChar anyChar (char closeChar)
+  return $ T.cons openChar $ content `T.snoc` closeChar
 
+-- | Planning information for a subtree/headline.
+data PlanningInfo = PlanningInfo
+  { planningClosed :: Maybe Timestamp
+  , planningDeadline :: Maybe Timestamp
+  , planningScheduled :: Maybe Timestamp
+  }
 
+emptyPlanning :: PlanningInfo
+emptyPlanning = PlanningInfo Nothing Nothing Nothing
+
+-- | Read a single planning-related and timestamped line.
+planningInfo :: Monad m => OrgParser m PlanningInfo
+planningInfo = try $ do
+  updaters <- many1 planningDatum <* skipSpaces <* newline
+  return $ foldr ($) emptyPlanning updaters
+ where
+  planningDatum = skipSpaces *> choice
+    [ updateWith (\s p -> p { planningScheduled = Just s}) "SCHEDULED"
+    , updateWith (\d p -> p { planningDeadline = Just d}) "DEADLINE"
+    , updateWith (\c p -> p { planningClosed = Just c}) "CLOSED"
+    ]
+  updateWith fn cs = fn <$> (string cs *> char ':' *> skipSpaces *> timestamp)
+
 -- | Read a :PROPERTIES: drawer and return the key/value pairs contained
 -- within.
 propertiesDrawer :: Monad m => OrgParser m Properties
 propertiesDrawer = try $ do
   drawerType <- drawerStart
-  guard $ map toUpper drawerType == "PROPERTIES"
+  guard $ T.toUpper drawerType == "PROPERTIES"
   manyTill property (try endOfDrawer)
  where
    property :: Monad m => OrgParser m (PropertyKey, PropertyValue)
@@ -293,12 +411,13 @@
 
    key :: Monad m => OrgParser m PropertyKey
    key = fmap toPropertyKey . try $
-         skipSpaces *> char ':' *> many1Till nonspaceChar (char ':')
+         skipSpaces *> char ':' *>
+         many1TillChar nonspaceChar (try $ char ':' *> spaceChar)
 
    value :: Monad m => OrgParser m PropertyValue
    value = fmap toPropertyValue . try $
-           skipSpaces *> manyTill anyChar (try $ skipSpaces *> newline)
+           skipSpaces *> manyTillChar anyChar (try $ skipSpaces *> newline)
 
-   endOfDrawer :: Monad m => OrgParser m String
+   endOfDrawer :: Monad m => OrgParser m Text
    endOfDrawer = try $
      skipSpaces *> stringAnyCase ":END:" <* skipSpaces <* newline
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,27 +1,10 @@
-{-
-Copyright (C) 2014-2017 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 OverloadedStrings #-}
 {- |
    Module      : Text.Pandoc.Readers.Org.ExportSettings
-   Copyright   : © 2016–2017 Albert Krewinkel
+   Copyright   : © 2016-2024 Albert Krewinkel
    License     : GNU GPL, version 2 or above
 
-   Maintainer  : Albert Krewinkel <tarleb+pandoc@moltkeplatz.de>
+   Maintainer  : Albert Krewinkel <albert+pandoc@tarleb.com>
 
 Parsers for Org-mode export options.
 -}
@@ -29,22 +12,25 @@
   ( exportSettings
   ) where
 
+import Text.Pandoc.Class.PandocMonad (PandocMonad, report)
+import Text.Pandoc.Logging (LogMessage (UnknownOrgExportOption))
 import Text.Pandoc.Readers.Org.ParserState
 import Text.Pandoc.Readers.Org.Parsing
 
 import Control.Monad (mzero, void)
 import Data.Char (toLower)
 import Data.Maybe (listToMaybe)
+import Data.Text (Text, unpack)
 
 -- | Read and handle space separated org-mode export settings.
-exportSettings :: Monad m => OrgParser m ()
-exportSettings = void $ sepBy spaces exportSetting
+exportSettings :: PandocMonad m => OrgParser m ()
+exportSettings = void $ sepBy skipSpaces exportSetting
 
 -- | Setter function for export settings.
 type ExportSettingSetter a = a -> ExportSettings -> ExportSettings
 
 -- | Read and process a single org-mode export option.
-exportSetting :: Monad m => OrgParser m ()
+exportSetting :: PandocMonad m => OrgParser m ()
 exportSetting = choice
   [ booleanSetting "^" (\val es -> es { exportSubSuperscripts = val })
   , booleanSetting "'" (\val es -> es { exportSmartQuotes = val })
@@ -61,33 +47,36 @@
   , booleanSetting "creator" (\val es -> es { exportWithCreator = val })
   , complementableListSetting "d" (\val es -> es { exportDrawers = val })
   , ignoredSetting "date"
-  , ignoredSetting "e"
+  , booleanSetting "e" (\val es -> es { exportWithEntities = val })
   , booleanSetting "email" (\val es -> es { exportWithEmail = val })
-  , ignoredSetting "f"
+  , booleanSetting "f" (\val es -> es { exportWithFootnotes = val })
   , integerSetting "H" (\val es -> es { exportHeadlineLevels = val })
   , ignoredSetting "inline"
   , ignoredSetting "num"
-  , ignoredSetting "p"
+  , booleanSetting "p" (\val es -> es { exportWithPlanning = val })
   , ignoredSetting "pri"
   , ignoredSetting "prop"
   , ignoredSetting "stat"
   , booleanSetting "tags" (\val es -> es { exportWithTags = val })
   , ignoredSetting "tasks"
-  , ignoredSetting "tex"
+  , texSetting     "tex" (\val es -> es { exportWithLatex = val })
   , ignoredSetting "timestamp"
   , ignoredSetting "title"
   , ignoredSetting "toc"
   , booleanSetting "todo" (\val es -> es { exportWithTodoKeywords = val })
-  , ignoredSetting "|"
+  , booleanSetting "|" (\val es -> es { exportWithTables = val })
+  , ignoreAndWarn
   ] <?> "export setting"
 
+-- | Generic handler for export settings. Takes a parser which converts
+-- the plain option text into a data structure.
 genericExportSetting :: Monad m
                      => OrgParser m a
-                     -> String
+                     -> Text
                      -> ExportSettingSetter a
                      -> OrgParser m ()
 genericExportSetting optionParser settingIdentifier setter = try $ do
-  _     <- string settingIdentifier *> char ':'
+  _     <- textStr settingIdentifier *> char ':'
   value <- optionParser
   updateState $ modifyExportSettings value
  where
@@ -95,11 +84,11 @@
      st { orgStateExportSettings = setter val . orgStateExportSettings $ st }
 
 -- | A boolean option, either nil (False) or non-nil (True).
-booleanSetting :: Monad m => String ->  ExportSettingSetter Bool -> OrgParser m ()
+booleanSetting :: Monad m => Text ->  ExportSettingSetter Bool -> OrgParser m ()
 booleanSetting = genericExportSetting elispBoolean
 
 -- | An integer-valued option.
-integerSetting :: Monad m => String -> ExportSettingSetter Int -> OrgParser m ()
+integerSetting :: Monad m => Text -> ExportSettingSetter Int -> OrgParser m ()
 integerSetting = genericExportSetting parseInt
  where
    parseInt = try $
@@ -108,16 +97,14 @@
 -- | Either the string "headline" or an elisp boolean and treated as an
 -- @ArchivedTreesOption@.
 archivedTreeSetting :: Monad m
-                    => String
+                    => Text
                     -> ExportSettingSetter ArchivedTreesOption
                     -> OrgParser m ()
 archivedTreeSetting =
   genericExportSetting $ archivedTreesHeadlineSetting <|> archivedTreesBoolean
  where
-   archivedTreesHeadlineSetting = try $ do
-     _ <- string "headline"
-     lookAhead (newline <|> spaceChar)
-     return ArchivedTreesHeadlineOnly
+   archivedTreesHeadlineSetting =
+     ArchivedTreesHeadlineOnly <$ optionString "headline"
 
    archivedTreesBoolean = try $ do
      exportBool <- elispBoolean
@@ -128,38 +115,61 @@
 
 -- | A list or a complement list (i.e. a list starting with `not`).
 complementableListSetting :: Monad m
-                          => String
-                          -> ExportSettingSetter (Either [String] [String])
+                          => Text
+                          -> ExportSettingSetter (Either [Text] [Text])
                           -> OrgParser m ()
 complementableListSetting = genericExportSetting $ choice
-  [ Left  <$> complementStringList
+  [ Left  <$> complementTextList
   , Right <$> stringList
   , (\b -> if b then Left [] else Right []) <$> elispBoolean
   ]
  where
    -- Read a plain list of strings.
-   stringList :: Monad m => OrgParser m [String]
+   stringList :: Monad m => OrgParser m [Text]
    stringList = try $
      char '('
-       *> sepBy elispString spaces
+       *> sepBy elispText spaces
        <* char ')'
 
    -- Read an emacs lisp list specifying a complement set.
-   complementStringList :: Monad m => OrgParser m [String]
-   complementStringList = try $
+   complementTextList :: Monad m => OrgParser m [Text]
+   complementTextList = try $
      string "(not "
-       *> sepBy elispString spaces
+       *> sepBy elispText spaces
        <* char ')'
 
-   elispString :: Monad m => OrgParser m String
-   elispString = try $
+   elispText :: Monad m => OrgParser m Text
+   elispText = try $
      char '"'
-       *> manyTill alphaNum (char '"')
+       *> manyTillChar alphaNum (char '"')
 
+-- | Parses either @t@, @nil@, or @verbatim@ into a 'TeXExport' value.
+texSetting :: Monad m
+           => Text
+           -> ExportSettingSetter TeXExport
+           -> OrgParser m ()
+texSetting = genericExportSetting $ texVerbatim <|> texBoolean
+ where
+   texVerbatim = TeXVerbatim <$ optionString "verbatim"
+
+   texBoolean = try $ do
+     exportBool <- elispBoolean
+     return $
+       if exportBool
+       then TeXExport
+       else TeXIgnore
+
 -- | Read but ignore the export setting.
-ignoredSetting :: Monad m => String -> OrgParser m ()
-ignoredSetting s = try (() <$ string s <* char ':' <* many1 nonspaceChar)
+ignoredSetting :: Monad m => Text -> OrgParser m ()
+ignoredSetting s = try (() <$ textStr s <* char ':' <* many1 nonspaceChar)
 
+-- | Read any setting string, but ignore it and emit a warning.
+ignoreAndWarn :: PandocMonad m => OrgParser m ()
+ignoreAndWarn = try $ do
+  opt <- many1Char nonspaceChar
+  report (UnknownOrgExportOption opt)
+  return ()
+
 -- | Read an elisp boolean.  Only NIL is treated as false, non-NIL values are
 -- interpreted as true.
 elispBoolean :: Monad m => OrgParser m Bool
@@ -170,3 +180,11 @@
              "{}"  -> False
              "()"  -> False
              _     -> True
+
+-- | Try to parse a literal string as the option value. Returns the
+-- string on success.
+optionString :: Monad m => Text -> OrgParser m Text
+optionString s = try $ do
+  _ <- string (unpack s)
+  lookAhead (newline <|> spaceChar)
+  return s
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,28 +1,11 @@
+{-# LANGUAGE LambdaCase #-}
 {-# LANGUAGE OverloadedStrings #-}
-{-
-Copyright (C) 2014-2017 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-2017 Albert Krewinkel
-   License     : GNU GPL, version 2 or above
+   Copyright   : Copyright (C) 2014-2025 Albert Krewinkel
+   License     : GPL-2.0-or-later
 
-   Maintainer  : Albert Krewinkel <tarleb+pandoc@moltkeplatz.de>
+   Maintainer  : Albert Krewinkel <albert+pandoc@tarleb.com>
 
 Parsers for Org-mode inline elements.
 -}
@@ -36,36 +19,29 @@
 import Text.Pandoc.Readers.Org.BlockStarts (endOfBlock, noteMarker)
 import Text.Pandoc.Readers.Org.ParserState
 import Text.Pandoc.Readers.Org.Parsing
-import Text.Pandoc.Readers.Org.Shared (cleanLinkString, isImageFilename,
-                                       originalLang, translateLang)
+import Text.Pandoc.Readers.Org.Shared (cleanLinkText, isImageFilename,
+                                       originalLang, translateLang, exportsCode)
 
 import Text.Pandoc.Builder (Inlines)
 import qualified Text.Pandoc.Builder as B
-import Text.Pandoc.Class (PandocMonad)
+import Text.Pandoc.Class.PandocMonad (PandocMonad)
 import Text.Pandoc.Definition
 import Text.Pandoc.Options
 import Text.Pandoc.Readers.LaTeX (inlineCommand, rawLaTeXInline)
-import Text.Pandoc.Shared (underlineSpan)
 import Text.TeXMath (DisplayType (..), readTeX, writePandoc)
+import Text.Pandoc.Sources (ToSources(..))
 import qualified Text.TeXMath.Readers.MathML.EntityMap as MathMLEntityMap
-
-import Control.Monad (guard, mplus, mzero, unless, void, when)
+import Safe (lastMay)
+import Control.Monad (guard, mplus, mzero, unless, when, void)
 import Control.Monad.Trans (lift)
 import Data.Char (isAlphaNum, isSpace)
-import Data.List (intersperse)
 import qualified Data.Map as M
-import Data.Maybe (fromMaybe)
-import Data.Monoid ((<>))
-import Data.Traversable (sequence)
-import Prelude hiding (sequence)
+import Data.Text (Text)
+import qualified Data.Text as T
 
 --
 -- Functions acting on the parser state
 --
-recordAnchorId :: PandocMonad m => String -> OrgParser m ()
-recordAnchorId i = updateState $ \s ->
-  s{ orgStateAnchorIds = i : orgStateAnchorIds s }
-
 pushToInlineCharStack :: PandocMonad m => Char -> OrgParser m ()
 pushToInlineCharStack c = updateState $ \s ->
   s{ orgStateEmphasisCharStack = c:orgStateEmphasisCharStack s }
@@ -112,17 +88,18 @@
          , inlineCodeBlock
          , str
          , endline
+         , subscript   -- takes precedence over underlined text
+         , superscript
          , emphasizedText
          , code
          , math
          , displayMath
          , verbatim
-         , subscript
-         , superscript
          , inlineLaTeX
          , exportSnippet
          , macro
-         , smart
+         , smartQuotes
+         , specialStrings
          , symbol
          ] <* (guard =<< newlinesCountWithinLimits)
   <?> "inline"
@@ -146,8 +123,12 @@
 linebreak = try $ pure B.linebreak <$ string "\\\\" <* skipSpaces <* newline
 
 str :: PandocMonad m => OrgParser m (F Inlines)
-str = return . B.str <$> many1 (noneOf $ specialChars ++ "\n\r ")
+str = return . B.str <$>
+      ( many1Char (noneOf $ specialChars ++ "\n\r ") >>= updatePositions' )
       <* updateLastStrPos
+  where
+    updatePositions' str' = str' <$
+      maybe mzero (updatePositions . snd) (T.unsnoc str')
 
 -- | An endline character that can be treated as a space, not a structural
 -- break.  This should reflect the values of the Emacs variable
@@ -167,31 +148,179 @@
 -- Citations
 --
 
--- The state of citations is a bit confusing due to the lack of an official
--- syntax and multiple syntaxes coexisting.  The pandocOrgCite syntax was the
--- first to be implemented here and is almost identical to Markdown's citation
--- syntax.  The org-ref package is in wide use to handle citations, but the
--- syntax is a bit limiting and not quite as simple to write.  The
--- semi-offical Org-mode citation syntax is based on John MacFarlane's Pandoc
--- sytax and Org-oriented enhancements contributed by Richard Lawrence and
--- others.  It's dubbed Berkeley syntax due the place of activity of its main
--- contributors.  All this should be consolidated once an official Org-mode
--- citation syntax has emerged.
+-- We first try to parse official org-cite citations, then fall
+-- back to org-ref citations (which are still in wide use).
 
+-- | A citation in org-cite style
+orgCite :: PandocMonad m => OrgParser m (F [Citation])
+orgCite = try $ do
+  string "[cite"
+  (sty, _variants) <- citeStyle
+  char ':'
+  spnl
+  globalPref <- option mempty (try (citePrefix <* char ';'))
+  items <- citeItems
+  globalSuff <- option mempty (try (char ';' *> citeSuffix))
+  spnl
+  char ']'
+  return $ adjustCiteStyle sty .
+           addPrefixToFirstItem globalPref .
+           addSuffixToLastItem globalSuff $ items
+
+adjustCiteStyle :: CiteStyle -> (F [Citation]) -> (F [Citation])
+adjustCiteStyle sty cs = do
+  cs' <- cs
+  case cs' of
+    [] -> return []
+    (d:ds)  -- TODO needs refinement
+      -> case sty of
+         TextStyle -> return $ d{ citationMode = AuthorInText
+                                , citationSuffix = dropWhile (== Space)
+                                    (citationSuffix d)} : ds
+         NoAuthorStyle -> return $ d{ citationMode = SuppressAuthor } : ds
+         _ -> return (d:ds)
+
+addPrefixToFirstItem :: (F Inlines) -> (F [Citation]) -> (F [Citation])
+addPrefixToFirstItem aff cs = do
+  cs' <- cs
+  aff' <- aff
+  case cs' of
+    [] -> return []
+    (d:ds) -> return (d{ citationPrefix =
+                          B.toList aff' <> citationPrefix d }:ds)
+
+addSuffixToLastItem :: (F Inlines) -> (F [Citation]) -> (F [Citation])
+addSuffixToLastItem aff cs = do
+  cs' <- cs
+  aff' <- aff
+  case lastMay cs' of
+    Nothing -> return cs'
+    Just d  ->
+      return (init cs' ++ [d{ citationSuffix =
+                                citationSuffix d <> B.toList aff' }])
+
+citeItems :: PandocMonad m => OrgParser m (F [Citation])
+citeItems = sequence <$> sepBy1' citeItem (char ';' <* void (many spaceChar))
+
+citeItem :: PandocMonad m => OrgParser m (F Citation)
+citeItem = try $ do
+  pref <- citePrefix
+  itemKey <- orgCiteKey
+  suff <- citeSuffix
+  return $ do
+    pre' <- pref
+    suf' <- suff
+    return Citation
+      { citationId      = itemKey
+      , citationPrefix  = B.toList pre'
+      , citationSuffix  = B.toList suf'
+      , citationMode    = NormalCitation
+      , citationNoteNum = 0
+      , citationHash    = 0
+      }
+
+orgCiteKey :: PandocMonad m => OrgParser m Text
+orgCiteKey = do
+  char '@'
+  T.pack <$> many1 (satisfy orgCiteKeyChar)
+
+orgCiteKeyChar :: Char -> Bool
+orgCiteKeyChar c =
+  isAlphaNum c || c `elem` ['.',':','?','!','`','\'','/','*','@','+','|',
+                            '(',')','{','}','<','>','&','_','^','$','#',
+                            '%','~','-']
+
+rawAffix :: PandocMonad m => Bool -> OrgParser m Text
+rawAffix isPrefix = snd <$> withRaw
+  (many
+   (affixChar
+     <|>
+     try (void (char '[' >> rawAffix isPrefix >> char ']'))))
+ where
+   affixChar = void $ satisfy $ \c ->
+     not (c == '^' || c == ';' || c == '[' || c == ']') &&
+     (not isPrefix || c /= '@')
+
+citePrefix :: PandocMonad m => OrgParser m (F Inlines)
+citePrefix =
+  rawAffix True >>= parseFromString (trimInlinesF . mconcat <$> many inline)
+
+citeSuffix :: PandocMonad m => OrgParser m (F Inlines)
+citeSuffix =
+  rawAffix False >>= parseFromString (mconcat <$> many inline)
+
+citeStyle :: PandocMonad m => OrgParser m (CiteStyle, [CiteVariant])
+citeStyle = do
+  sty <- option NilStyle $ try $ char '/' *> orgCiteStyle
+  variants <- option [] $ try $ char '/' *> orgCiteVariants
+  return (sty, variants)
+
+orgCiteStyle :: PandocMonad m => OrgParser m CiteStyle
+orgCiteStyle = try $ do
+  s <- many1 letter
+  case s of
+    "author" -> pure AuthorStyle
+    "a" -> pure AuthorStyle
+    "noauthor" -> pure NoAuthorStyle
+    "na" -> pure NoAuthorStyle
+    "nocite" -> pure NociteStyle
+    "n" -> pure NociteStyle
+    "text" -> pure TextStyle
+    "t" -> pure TextStyle
+    "note" -> pure NoteStyle
+    "ft" -> pure NoteStyle
+    "numeric" -> pure NumericStyle
+    "nb" -> pure NumericStyle
+    "nil" -> pure NilStyle
+    _ -> fail $ "Unknown org cite style " <> show s
+
+orgCiteVariants :: PandocMonad m => OrgParser m [CiteVariant]
+orgCiteVariants =
+  (sepBy1' fullnameVariant (char '-')) <|> (many1 onecharVariant)
+ where
+  fullnameVariant = choice $ map try
+     [ Bare <$ string "bare"
+     , Caps <$ string "caps"
+     , Full <$ string "full"
+     ]
+  onecharVariant = choice
+     [ Bare <$ char 'b'
+     , Caps <$ char 'c'
+     , Full <$ char 'f'
+     ]
+
+data CiteStyle =
+    AuthorStyle
+  | NoAuthorStyle
+  | LocatorsStyle
+  | NociteStyle
+  | TextStyle
+  | NoteStyle
+  | NumericStyle
+  | NilStyle
+  deriving Show
+
+data CiteVariant =
+    Caps
+  | Bare
+  | Full
+  deriving Show
+
+
+spnl :: PandocMonad m => OrgParser m ()
+spnl =
+  skipSpaces *> optional (newline *> notFollowedBy blankline *> skipSpaces)
+
 cite :: PandocMonad m => OrgParser m (F Inlines)
-cite = try $ berkeleyCite <|> do
+cite = do
   guardEnabled Ext_citations
-  (cs, raw) <- withRaw $ choice
-               [ pandocOrgCite
+  (cs, raw) <- withRaw $ try $ choice
+               [ orgCite
                , orgRefCite
-               , berkeleyTextualCite
                ]
   return $ flip B.cite (B.text raw) <$> cs
 
--- | A citation in Pandoc Org-mode style (@[prefix \@citekey suffix]@).
-pandocOrgCite :: PandocMonad m => OrgParser m (F [Citation])
-pandocOrgCite = try $
-  char '[' *> skipSpaces *> citeList <* skipSpaces <* char ']'
+-- org-ref
 
 orgRefCite :: PandocMonad m => OrgParser m (F [Citation])
 orgRefCite = try $ choice
@@ -206,7 +335,7 @@
   moreCitations <- many (try $ char ',' *> orgRefCiteList mode)
   return . sequence $ firstCitation : moreCitations
  where
-  -- | A list of org-ref style citation keys, parsed as citation of the given
+  -- A list of org-ref style citation keys, parsed as citation of the given
   -- citation mode.
   orgRefCiteList :: PandocMonad m => CitationMode -> OrgParser m (F Citation)
   orgRefCiteList citeMode = try $ do
@@ -220,100 +349,6 @@
      , citationHash    = 0
      }
 
--- | Read an Berkeley-style Org-mode citation.  Berkeley citation style was
--- develop and adjusted to Org-mode style by John MacFarlane and Richard
--- Lawrence, respectively, both philosophers at UC Berkeley.
-berkeleyCite :: PandocMonad m => OrgParser m (F Inlines)
-berkeleyCite = try $ do
-  bcl <- berkeleyCitationList
-  return $ do
-    parens <- berkeleyCiteParens <$> bcl
-    prefix <- berkeleyCiteCommonPrefix <$> bcl
-    suffix <- berkeleyCiteCommonSuffix <$> bcl
-    citationList <- berkeleyCiteCitations <$> bcl
-    return $
-      if parens
-      then toCite
-           . maybe id (alterFirst . prependPrefix) prefix
-           . maybe id (alterLast . appendSuffix) suffix
-           $ citationList
-      else maybe mempty (<> " ") prefix
-             <> toListOfCites (map toInTextMode citationList)
-             <> maybe mempty (", " <>) suffix
- where
-   toCite :: [Citation] -> Inlines
-   toCite cs = B.cite cs mempty
-
-   toListOfCites :: [Citation] -> Inlines
-   toListOfCites = mconcat . intersperse ", " . map (\c -> B.cite [c] mempty)
-
-   toInTextMode :: Citation -> Citation
-   toInTextMode c = c { citationMode = AuthorInText }
-
-   alterFirst, alterLast :: (a -> a) -> [a] -> [a]
-   alterFirst _ []     = []
-   alterFirst f (c:cs) = f c : cs
-   alterLast  f = reverse . alterFirst f . reverse
-
-   prependPrefix, appendSuffix :: Inlines -> Citation -> Citation
-   prependPrefix pre c = c { citationPrefix = B.toList pre <> citationPrefix c }
-   appendSuffix  suf c = c { citationSuffix = citationSuffix c <> B.toList suf }
-
-data BerkeleyCitationList = BerkeleyCitationList
-  { berkeleyCiteParens       :: Bool
-  , berkeleyCiteCommonPrefix :: Maybe Inlines
-  , berkeleyCiteCommonSuffix :: Maybe Inlines
-  , berkeleyCiteCitations    :: [Citation]
-  }
-berkeleyCitationList :: PandocMonad m => OrgParser m (F BerkeleyCitationList)
-berkeleyCitationList = try $ do
-  char '['
-  parens <- choice [ False <$ berkeleyBareTag, True <$ berkeleyParensTag ]
-  char ':'
-  skipSpaces
-  commonPrefix <- optionMaybe (try $ citationListPart <* char ';')
-  citations    <- citeList
-  commonSuffix <- optionMaybe (try citationListPart)
-  char ']'
-  return (BerkeleyCitationList parens
-    <$> sequence commonPrefix
-    <*> sequence commonSuffix
-    <*> citations)
- where
-   citationListPart :: PandocMonad m => OrgParser m (F Inlines)
-   citationListPart = fmap (trimInlinesF . mconcat) . try . many1 $ do
-     notFollowedBy' citeKey
-     notFollowedBy (oneOf ";]")
-     inline
-
-berkeleyBareTag :: PandocMonad m => OrgParser m ()
-berkeleyBareTag = try $ void berkeleyBareTag'
-
-berkeleyParensTag :: PandocMonad m => OrgParser m ()
-berkeleyParensTag = try . void $ enclosedByPair '(' ')' berkeleyBareTag'
-
-berkeleyBareTag' :: PandocMonad m => OrgParser m ()
-berkeleyBareTag' = try $ void (string "cite")
-
-berkeleyTextualCite :: PandocMonad m => OrgParser m (F [Citation])
-berkeleyTextualCite = try $ do
-  (suppressAuthor, key) <- citeKey
-  returnF . return $ Citation
-    { citationId      = key
-    , citationPrefix  = mempty
-    , citationSuffix  = mempty
-    , citationMode    = if suppressAuthor then SuppressAuthor else AuthorInText
-    , citationNoteNum = 0
-    , citationHash    = 0
-    }
-
--- The following is what a Berkeley-style bracketed textual citation parser
--- would look like.  However, as these citations are a subset of Pandoc's Org
--- citation style, this isn't used.
--- berkeleyBracketedTextualCite :: PandocMonad m => OrgParser m (F [Citation])
--- berkeleyBracketedTextualCite = try . (fmap head) $
---   enclosedByPair '[' ']' berkeleyTextualCite
-
 -- | Read a link-like org-ref style citation.  The citation includes pre and
 -- post text.  However, multiple citations are not possible due to limitations
 -- in the syntax.
@@ -340,16 +375,17 @@
 
 -- | Read a citation key.  The characters allowed in citation keys are taken
 -- from the `org-ref-cite-re` variable in `org-ref.el`.
-orgRefCiteKey :: PandocMonad m => OrgParser m String
+orgRefCiteKey :: PandocMonad m => OrgParser m Text
 orgRefCiteKey =
-  let citeKeySpecialChars = "-_:\\./," :: String
+  let citeKeySpecialChars = "-_:\\./" :: String
       isCiteKeySpecialChar c = c `elem` citeKeySpecialChars
       isCiteKeyChar c = isAlphaNum c || isCiteKeySpecialChar c
       endOfCitation = try $ do
         many $ satisfy isCiteKeySpecialChar
         satisfy $ not . isCiteKeyChar
-  in try $ satisfy isCiteKeyChar `many1Till` lookAhead endOfCitation
-
+  in try $ do
+        optional (char '&') -- this is used in org-ref v3
+        satisfy isCiteKeyChar `many1TillChar` lookAhead endOfCitation
 
 -- | Supported citation types.  Only a small subset of org-ref types is
 -- supported for now.  TODO: rewrite this, use LaTeX reader as template.
@@ -364,50 +400,20 @@
     , ("citeyear", SuppressAuthor)
     ]
 
-citeList :: PandocMonad m => OrgParser m (F [Citation])
-citeList = sequence <$> sepEndBy1 citation (try $ char ';' *> skipSpaces)
-
-citation :: PandocMonad m => OrgParser m (F Citation)
-citation = try $ do
-  pref <- prefix
-  (suppress_author, key) <- citeKey
-  suff <- suffix
-  return $ do
-    x <- pref
-    y <- suff
-    return Citation
-      { citationId      = key
-      , citationPrefix  = B.toList x
-      , citationSuffix  = B.toList y
-      , citationMode    = if suppress_author
-                          then SuppressAuthor
-                          else NormalCitation
-      , citationNoteNum = 0
-      , citationHash    = 0
-      }
- where
-   prefix = trimInlinesF . mconcat <$>
-            manyTill inline (char ']' <|> (']' <$ lookAhead citeKey))
-   suffix = try $ do
-     hasSpace <- option False (notFollowedBy nonspaceChar >> return True)
-     skipSpaces
-     rest <- trimInlinesF . mconcat <$>
-             many (notFollowedBy (oneOf ";]") *> inline)
-     return $ if hasSpace
-              then (B.space <>) <$> rest
-              else rest
-
 footnote :: PandocMonad m => OrgParser m (F Inlines)
-footnote = try $ inlineNote <|> referencedNote
+footnote = try $ do
+  note <- inlineNote <|> referencedNote
+  withNote <- getExportSetting exportWithFootnotes
+  return $ if withNote then note else mempty
 
 inlineNote :: PandocMonad m => OrgParser m (F Inlines)
 inlineNote = try $ do
   string "[fn:"
-  ref <- many alphaNum
+  ref <- manyChar alphaNum
   char ':'
   note <- fmap B.para . trimInlinesF . mconcat <$> many1Till inline (char ']')
-  unless (null ref) $
-       addToNotesTable ("fn:" ++ ref, note)
+  unless (T.null ref) $
+       addToNotesTable ("fn:" <> ref, note)
   return $ B.note <$> note
 
 referencedNote :: PandocMonad m => OrgParser m (F Inlines)
@@ -416,7 +422,7 @@
   return $ do
     notes <- asksF orgStateNotes'
     case lookup ref notes of
-      Nothing   -> return . B.str $ "[" ++ ref ++ "]"
+      Nothing   -> return . B.str $ "[" <> ref <> "]"
       Just contents  -> do
         st <- askF
         let contents' = runF contents st{ orgStateNotes' = [] }
@@ -433,21 +439,28 @@
 explicitOrImageLink = try $ do
   char '['
   srcF   <- applyCustomLinkFormat =<< possiblyEmptyLinkTarget
-  title  <- enclosedRaw (char '[') (char ']')
-  title' <- parseFromString (mconcat <$> many inline) title
+  descr  <- enclosedRaw (char '[') (char ']')
+  titleF <- parseFromString (mconcat <$> many inline) descr
   char ']'
   return $ do
     src <- srcF
-    case cleanLinkString title of
+    title <- titleF
+    case cleanLinkText descr of
       Just imgSrc | isImageFilename imgSrc ->
-        pure . B.link src "" $ B.image imgSrc mempty mempty
+        return . B.link src "" $ B.image imgSrc mempty mempty
       _ ->
-        linkToInlinesF src =<< title'
+        linkToInlinesF src title
 
 selflinkOrImage :: PandocMonad m => OrgParser m (F Inlines)
 selflinkOrImage = try $ do
-  src <- char '[' *> linkTarget <* char ']'
-  return $ linkToInlinesF src (B.str src)
+  target <- char '[' *> linkTarget <* char ']'
+  case cleanLinkText target of
+    Nothing        -> case T.uncons target of
+                        Just ('#', _) -> returnF $ B.link target "" (B.str target)
+                        _             -> return $ internalLink target (B.str target)
+    Just nonDocTgt -> if isImageFilename nonDocTgt
+                      then returnF $ B.image nonDocTgt "" ""
+                      else returnF $ B.link nonDocTgt "" (B.str target)
 
 plainLink :: PandocMonad m => OrgParser m (F Inlines)
 plainLink = try $ do
@@ -461,61 +474,52 @@
   char '>'
   return link
 
-linkTarget :: PandocMonad m => OrgParser m String
-linkTarget = enclosedByPair '[' ']' (noneOf "\n\r[]")
+linkTarget :: PandocMonad m => OrgParser m Text
+linkTarget = T.pack <$> enclosedByPair1 '[' ']' (noneOf "\n\r[]")
 
-possiblyEmptyLinkTarget :: PandocMonad m => OrgParser m String
+possiblyEmptyLinkTarget :: PandocMonad m => OrgParser m Text
 possiblyEmptyLinkTarget = try linkTarget <|> ("" <$ string "[]")
 
-applyCustomLinkFormat :: String -> OrgParser m (F String)
+applyCustomLinkFormat :: Text -> OrgParser m (F Text)
 applyCustomLinkFormat link = do
-  let (linkType, rest) = break (== ':') link
+  let (linkType, rest) = T.break (== ':') link
   return $ do
     formatter <- M.lookup linkType <$> asksF orgStateLinkFormatters
-    return $ maybe link ($ drop 1 rest) formatter
+    return $ maybe link ($ T.drop 1 rest) formatter
 
 -- | Take a link and return a function which produces new inlines when given
 -- description inlines.
-linkToInlinesF :: String -> Inlines -> F Inlines
+linkToInlinesF :: Text -> Inlines -> F Inlines
 linkToInlinesF linkStr =
-  case linkStr of
-    ""      -> pure . B.link mempty ""       -- wiki link (empty by convention)
-    ('#':_) -> pure . B.link linkStr ""      -- document-local fraction
-    _       -> case cleanLinkString linkStr of
-                 (Just cleanedLink) -> if isImageFilename cleanedLink
-                                       then const . pure $ B.image cleanedLink "" ""
-                                       else pure . B.link cleanedLink ""
-                 Nothing -> internalLink linkStr  -- other internal link
+  case T.uncons linkStr of
+    Nothing       -> pure . B.link mempty ""       -- wiki link (empty by convention)
+    Just ('#', _) -> pure . B.link linkStr ""      -- document-local fraction
+    _             -> case cleanLinkText linkStr of
+      Just extTgt -> return . B.link extTgt ""
+      Nothing     -> internalLink linkStr  -- other internal link
 
-internalLink :: String -> Inlines -> F Inlines
+internalLink :: Text -> Inlines -> F Inlines
 internalLink link title = do
-  anchorB <- (link `elem`) <$> asksF orgStateAnchorIds
-  if anchorB
-    then return $ B.link ('#':link) "" title
-    else return $ B.emph title
+  ids <- asksF orgStateAnchorIds
+  if link `elem` ids
+    then return $ B.link ("#" <> link) "" title
+    else let attr' = ("", ["spurious-link"] , [("target", link)])
+         in return $ B.spanWith attr' (B.emph title)
 
 -- | Parse an anchor like @<<anchor-id>>@ and return an empty span with
 -- @anchor-id@ set as id.  Legal anchors in org-mode are defined through
 -- @org-target-regexp@, which is fairly liberal.  Since no link is created if
 -- @anchor-id@ contains spaces, we are more restrictive in what is accepted as
 -- an anchor.
-
 anchor :: PandocMonad m => OrgParser m (F Inlines)
-anchor =  try $ do
-  anchorId <- parseAnchor
-  recordAnchorId anchorId
+anchor =  do
+  anchorId <- orgAnchor
   returnF $ B.spanWith (solidify anchorId, [], []) mempty
- where
-       parseAnchor = string "<<"
-                     *> many1 (noneOf "\t\n\r<>\"' ")
-                     <* string ">>"
-                     <* skipSpaces
 
--- | Replace every char but [a-zA-Z0-9_.-:] with a hypen '-'.  This mirrors
+-- | Replace every char but [a-zA-Z0-9_.-:] with a hyphen '-'.  This mirrors
 -- the org function @org-export-solidify-link-text@.
-
-solidify :: String -> String
-solidify = map replaceSpecialChar
+solidify :: Text -> Text
+solidify = T.map replaceSpecialChar
  where replaceSpecialChar c
            | isAlphaNum c    = c
            | c `elem` ("_.-:" :: String) = c
@@ -525,24 +529,25 @@
 inlineCodeBlock :: PandocMonad m => OrgParser m (F Inlines)
 inlineCodeBlock = try $ do
   string "src_"
-  lang <- many1 orgArgWordChar
+  lang <- many1Char orgArgWordChar
   opts <- option [] $ enclosedByPair '[' ']' inlineBlockOption
-  inlineCode <- enclosedByPair '{' '}' (noneOf "\n\r")
+  inlineCode <- T.pack <$> enclosedByPair1 '{' '}' (noneOf "\n\r")
   let attrClasses = [translateLang lang]
   let attrKeyVal  = originalLang lang <> opts
-  returnF $ B.codeWith ("", attrClasses, attrKeyVal) inlineCode
+  let codeInlineBlck = B.codeWith ("", attrClasses, attrKeyVal) inlineCode
+  returnF $ if exportsCode opts then codeInlineBlck else mempty
  where
-   inlineBlockOption :: PandocMonad m => OrgParser m (String, String)
+   inlineBlockOption :: PandocMonad m => OrgParser m (Text, Text)
    inlineBlockOption = try $ do
      argKey <- orgArgKey
      paramValue <- option "yes" orgInlineParamValue
      return (argKey, paramValue)
 
-   orgInlineParamValue :: PandocMonad m => OrgParser m String
+   orgInlineParamValue :: PandocMonad m => OrgParser m Text
    orgInlineParamValue = try $
      skipSpaces
        *> notFollowedBy (char ':')
-       *> many1 (noneOf "\t\n\r ]")
+       *> many1Char (noneOf "\t\n\r ]")
        <* skipSpaces
 
 
@@ -562,8 +567,15 @@
                -> Char          -- ^ closing char
                -> OrgParser m a   -- ^ parser
                -> OrgParser m [a]
-enclosedByPair s e p = char s *> many1Till p (char e)
+enclosedByPair s e p = char s *> manyTill p (char e)
 
+enclosedByPair1 :: PandocMonad m
+               => Char          -- ^ opening char
+               -> Char          -- ^ closing char
+               -> OrgParser m a   -- ^ parser
+               -> OrgParser m [a]
+enclosedByPair1 s e p = char s *> many1Till p (char e)
+
 emph      :: PandocMonad m => OrgParser m (F Inlines)
 emph      = fmap B.emph         <$> emphasisBetween '/'
 
@@ -574,23 +586,37 @@
 strikeout = fmap B.strikeout    <$> emphasisBetween '+'
 
 underline :: PandocMonad m => OrgParser m (F Inlines)
-underline = fmap underlineSpan  <$> emphasisBetween '_'
+underline = fmap B.underline    <$> emphasisBetween '_'
 
 verbatim  :: PandocMonad m => OrgParser m (F Inlines)
-verbatim  = return . B.code     <$> verbatimBetween '='
+verbatim  = return . B.codeWith ("", ["verbatim"], []) <$> verbatimBetween '='
 
 code      :: PandocMonad m => OrgParser m (F Inlines)
 code      = return . B.code     <$> verbatimBetween '~'
 
+-- | Returns 'True' if the parser position right after a string, and 'False'
+-- otherwise.
+isAfterString :: PandocMonad m => OrgParser m Bool
+isAfterString = do
+  pos <- getPosition
+  st  <- getState
+  pure $ getLastStrPos st == Just pos
+
+-- | Parses subscript markup. Subscripts must be preceded by a string.
 subscript   :: PandocMonad m => OrgParser m (F Inlines)
-subscript   = fmap B.subscript   <$> try (char '_' *> subOrSuperExpr)
+subscript   = do
+  guard =<< isAfterString
+  fmap B.subscript   <$> try (char '_' *> subOrSuperExpr)
 
+-- | Parses superscript markup. Superscript must be preceded by a string.
 superscript :: PandocMonad m => OrgParser m (F Inlines)
-superscript = fmap B.superscript <$> try (char '^' *> subOrSuperExpr)
+superscript = do
+  guard =<< isAfterString
+  fmap B.superscript <$> try (char '^' *> subOrSuperExpr)
 
 math      :: PandocMonad m => OrgParser m (F Inlines)
 math      = return . B.math      <$> choice [ math1CharBetween '$'
-                                            , mathStringBetween '$'
+                                            , mathTextBetween '$'
                                             , rawMathBetween "\\(" "\\)"
                                             ]
 
@@ -603,12 +629,14 @@
                 => Char
                 -> OrgParser m Char
 updatePositions c = do
+  st <- getState
+  let emphasisPreChars = orgStateEmphasisPreChars st
   when (c `elem` emphasisPreChars) updateLastPreCharPos
   when (c `elem` emphasisForbiddenBorderChars) updateLastForbiddenCharPos
   return c
 
 symbol :: PandocMonad m => OrgParser m (F Inlines)
-symbol = return . B.str . (: "") <$> (oneOf specialChars >>= updatePositions)
+symbol = return . B.str . T.singleton <$> (oneOf specialChars >>= updatePositions)
 
 emphasisBetween :: PandocMonad m
                 => Char
@@ -623,47 +651,46 @@
 
 verbatimBetween :: PandocMonad m
                 => Char
-                -> OrgParser m String
-verbatimBetween c = try $
-  emphasisStart c *>
-  many1TillNOrLessNewlines 1 verbatimChar (emphasisEnd c)
+                -> OrgParser m Text
+verbatimBetween c = newlinesToSpaces <$>
+  try (emphasisStart c *> many1TillNOrLessNewlines 1 verbatimChar (emphasisEnd c))
  where
    verbatimChar = noneOf "\n\r" >>= updatePositions
+   newlinesToSpaces = T.map (\d -> if d == '\n' then ' ' else d)
 
 -- | Parses a raw string delimited by @c@ using Org's math rules
-mathStringBetween :: PandocMonad m
+mathTextBetween :: PandocMonad m
                   => Char
-                  -> OrgParser m String
-mathStringBetween c = try $ do
+                  -> OrgParser m Text
+mathTextBetween c = try $ do
   mathStart c
   body <- many1TillNOrLessNewlines mathAllowedNewlines
                                    (noneOf (c:"\n\r"))
                                    (lookAhead $ mathEnd c)
   final <- mathEnd c
-  return $ body ++ [final]
+  return $ T.snoc body final
 
 -- | Parse a single character between @c@ using math rules
 math1CharBetween :: PandocMonad m
                  => Char
-                -> OrgParser m String
+                -> OrgParser m Text
 math1CharBetween c = try $ do
   char c
   res <- noneOf $ c:mathForbiddenBorderChars
   char c
   eof <|> () <$ lookAhead (oneOf mathPostChars)
-  return [res]
+  return $ T.singleton res
 
 rawMathBetween :: PandocMonad m
-               => String
-               -> String
-               -> OrgParser m String
-rawMathBetween s e = try $ string s *> manyTill anyChar (try $ string e)
+               => Text
+               -> Text
+               -> OrgParser m Text
+rawMathBetween s e = try $ textStr s *> manyTillChar anyChar (try $ textStr e)
 
 -- | Parses the start (opening character) of emphasis
 emphasisStart :: PandocMonad m => Char -> OrgParser m Char
 emphasisStart c = try $ do
   guard =<< afterEmphasisPreChar
-  guard =<< notAfterString
   char c
   lookAhead (noneOf emphasisForbiddenBorderChars)
   pushToInlineCharStack c
@@ -681,8 +708,10 @@
   updateLastStrPos
   popInlineCharStack
   return c
- where acceptablePostChars =
-           surroundingEmphasisChar >>= \x -> oneOf (x ++ emphasisPostChars)
+ where
+  acceptablePostChars = do
+    emphasisPostChars <- orgStateEmphasisPostChars <$> getState
+    surroundingEmphasisChar >>= \x -> oneOf (x ++ emphasisPostChars)
 
 mathStart :: PandocMonad m => Char -> OrgParser m Char
 mathStart c = try $
@@ -704,10 +733,10 @@
 
 enclosedRaw :: (PandocMonad m, Show b) => OrgParser m a
             -> OrgParser m b
-            -> OrgParser m String
+            -> OrgParser m Text
 enclosedRaw start end = try $
   start *> (onSingleLine <|> spanningTwoLines)
- where onSingleLine = try $ many1Till (noneOf "\n\r") end
+ where onSingleLine = try $ many1TillChar (noneOf "\n\r") end
        spanningTwoLines = try $
          anyLine >>= \f -> mappend (f <> " ") <$> onSingleLine
 
@@ -716,7 +745,7 @@
 many1TillNOrLessNewlines :: PandocMonad m => Int
                          -> OrgParser m Char
                          -> OrgParser m a
-                         -> OrgParser m String
+                         -> OrgParser m Text
 many1TillNOrLessNewlines n p end = try $
   nMoreLines (Just n) mempty >>= oneOrMore
  where
@@ -728,23 +757,15 @@
    rest  m cs = (\x -> (minus1 <$> m, cs ++ x ++ "\n")) <$> try (manyTill p newline)
    finalLine = try $ manyTill p end
    minus1 k = k - 1
-   oneOrMore cs = guard (not $ null cs) *> return cs
+   oneOrMore cs = T.pack cs <$ guard (not $ null cs)
 
 -- Org allows customization of the way it reads emphasis.  We use the defaults
 -- here (see, e.g., the Emacs Lisp variable `org-emphasis-regexp-components`
 -- for details).
 
--- | Chars allowed to occur before emphasis (spaces and newlines are ok, too)
-emphasisPreChars :: [Char]
-emphasisPreChars = "-\t ('\"{"
-
--- | Chars allowed at after emphasis
-emphasisPostChars :: [Char]
-emphasisPostChars = "-\t\n .,:!?;'\")}["
-
 -- | Chars not allowed at the (inner) border of emphasis
 emphasisForbiddenBorderChars :: [Char]
-emphasisForbiddenBorderChars = "\t\n\r "
+emphasisForbiddenBorderChars = "\t\n\r \x200B"
 
 -- | The maximum number of newlines within
 emphasisAllowedNewlines :: Int
@@ -769,7 +790,7 @@
 afterEmphasisPreChar = do
   pos <- getPosition
   lastPrePos <- orgStateLastPreCharPos <$> getState
-  return . fromMaybe True $ (== pos) <$> lastPrePos
+  return $ maybe True (== pos) lastPrePos
 
 -- | Whether the parser is right after a forbidden border char
 notAfterForbiddenBorderChar :: PandocMonad m => OrgParser m Bool
@@ -781,73 +802,88 @@
 -- | Read a sub- or superscript expression
 subOrSuperExpr :: PandocMonad m => OrgParser m (F Inlines)
 subOrSuperExpr = try $
-  choice [ charsInBalanced '{' '}' (noneOf "\n\r")
-         , enclosing ('(', ')') <$> charsInBalanced '(' ')' (noneOf "\n\r")
-         , simpleSubOrSuperString
-         ] >>= parseFromString (mconcat <$> many inline)
- where enclosing (left, right) s = left : s ++ [right]
+  simpleSubOrSuperText <|>
+  (choice [ charsInBalanced '{' '}' (T.singleton <$> noneOf "\n\r")
+          , enclosing ('(', ')') <$> charsInBalanced '(' ')' (T.singleton <$> noneOf "\n\r")
+          ] >>= parseFromString (mconcat <$> many inline))
+ where enclosing (left, right) s = T.cons left $ T.snoc s right
 
-simpleSubOrSuperString :: PandocMonad m => OrgParser m String
-simpleSubOrSuperString = try $ do
+simpleSubOrSuperText :: PandocMonad m => OrgParser m (F Inlines)
+simpleSubOrSuperText = try $ do
   state <- getState
   guard . exportSubSuperscripts . orgStateExportSettings $ state
-  choice [ string "*"
-         , mappend <$> option [] ((:[]) <$> oneOf "+-")
-                   <*> many1 alphaNum
-         ]
+  return . B.str <$>
+    choice [ textStr "*"
+           , mappend <$> option "" (T.singleton <$> oneOf "+-")
+                     <*> many1Char alphaNum
+           ]
 
 inlineLaTeX :: PandocMonad m => OrgParser m (F Inlines)
 inlineLaTeX = try $ do
   cmd <- inlineLaTeXCommand
-  ils <- (lift . lift) $ parseAsInlineLaTeX cmd
+  texOpt <- getExportSetting exportWithLatex
+  allowEntities <- getExportSetting exportWithEntities
+  ils <- parseAsInlineLaTeX cmd texOpt
   maybe mzero returnF $
-     parseAsMath cmd `mplus` parseAsMathMLSym cmd `mplus` ils
+    if "\\begin{" `T.isPrefixOf` cmd
+       then ils
+       else parseAsMathMLSym allowEntities cmd `mplus`
+            parseAsMath cmd texOpt `mplus`
+            ils
  where
-   parseAsMath :: String -> Maybe Inlines
-   parseAsMath cs = B.fromList <$> texMathToPandoc cs
-
-   parseAsInlineLaTeX :: PandocMonad m => String -> m (Maybe Inlines)
-   parseAsInlineLaTeX cs = maybeRight <$> runParserT inlineCommand state "" cs
+   parseAsInlineLaTeX :: PandocMonad m
+                      => Text -> TeXExport -> OrgParser m (Maybe Inlines)
+   parseAsInlineLaTeX cs = \case
+     TeXExport -> maybeRight <$> runParserT
+                  (B.rawInline "latex" . snd <$> withRaw inlineCommand)
+                  state "" (toSources cs)
+     TeXIgnore -> return (Just mempty)
+     TeXVerbatim -> return (Just $ B.text cs)
 
-   parseAsMathMLSym :: String -> Maybe Inlines
-   parseAsMathMLSym cs = B.str <$> MathMLEntityMap.getUnicode (clean cs)
-    -- drop initial backslash and any trailing "{}"
-    where clean = dropWhileEnd (`elem` ("{}" :: String)) . drop 1
+   parseAsMathMLSym :: Bool -> Text -> Maybe Inlines
+   parseAsMathMLSym allowEntities cs = do
+     -- drop initial backslash and any trailing "{}"
+     let clean = T.dropWhileEnd (`elem` ("{}" :: String)) . T.drop 1
+     -- If entities are disabled, then return the string as text, but
+     -- only if this *is* a MathML entity.
+     case B.str <$> MathMLEntityMap.getUnicode (clean cs) of
+       Just _ | not allowEntities -> Just $ B.str cs
+       x -> x
 
    state :: ParserState
    state = def{ stateOptions = def{ readerExtensions =
                     enableExtension Ext_raw_tex (readerExtensions def) } }
 
-   texMathToPandoc :: String -> Maybe [Inline]
-   texMathToPandoc cs = maybeRight (readTeX cs) >>= writePandoc DisplayInline
+   parseAsMath :: Text -> TeXExport -> Maybe Inlines
+   parseAsMath cs = \case
+     TeXExport -> maybeRight (readTeX cs) >>=
+                  fmap B.fromList . writePandoc DisplayInline
+     TeXIgnore -> Just mempty
+     TeXVerbatim -> Just $ B.str cs
 
 maybeRight :: Either a b -> Maybe b
 maybeRight = either (const Nothing) Just
 
-inlineLaTeXCommand :: PandocMonad m => OrgParser m String
+inlineLaTeXCommand :: PandocMonad m => OrgParser m Text
 inlineLaTeXCommand = try $ do
   rest <- getInput
   st <- getState
   parsed <- (lift . lift) $ runParserT rawLaTeXInline st "source" rest
   case parsed of
     Right cs -> do
-      -- drop any trailing whitespace, those are not be part of the command as
+      -- drop any trailing whitespace, those are not part of the command as
       -- far as org mode is concerned.
-      let cmdNoSpc = dropWhileEnd isSpace cs
-      let len = length cmdNoSpc
+      let cmdNoSpc = T.dropWhileEnd isSpace cs
+      let len = T.length cmdNoSpc
       count len anyChar
       return cmdNoSpc
     _ -> mzero
 
--- Taken from Data.OldList.
-dropWhileEnd :: (a -> Bool) -> [a] -> [a]
-dropWhileEnd p = foldr (\x xs -> if p x && null xs then [] else x : xs) []
-
 exportSnippet :: PandocMonad m => OrgParser m (F Inlines)
 exportSnippet = try $ do
   string "@@"
-  format <- many1Till (alphaNum <|> char '-') (char ':')
-  snippet <- manyTill anyChar (try $ string "@@")
+  format <- many1TillChar (alphaNum <|> char '-') (char ':')
+  snippet <- manyTillChar anyChar (try $ string "@@")
   returnF $ B.rawInline format snippet
 
 macro :: PandocMonad m => OrgParser m (F Inlines)
@@ -855,7 +891,7 @@
   recursionDepth <- orgStateMacroDepth <$> getState
   guard $ recursionDepth < 15
   string "{{{"
-  name <- many alphaNum
+  name <- manyChar alphaNum
   args <- ([] <$ string "}}}")
           <|> char '(' *> argument `sepBy` char ',' <* eoa
   expander <- lookupMacro name <$> getState
@@ -867,32 +903,31 @@
       updateState $ \s -> s { orgStateMacroDepth = recursionDepth }
       return res
  where
-  argument = many $ notFollowedBy eoa *> noneOf ","
+  argument = manyChar $ notFollowedBy eoa *> (escapedComma <|> noneOf ",")
+  escapedComma = try $ char '\\' *> oneOf ",\\"
   eoa = string ")}}}"
 
-smart :: PandocMonad m => OrgParser m (F Inlines)
-smart = choice [doubleQuoted, singleQuoted, orgApostrophe, orgDash, orgEllipses]
+smartQuotes :: PandocMonad m => OrgParser m (F Inlines)
+smartQuotes = do
+  guard =<< getExportSetting exportSmartQuotes
+  choice [doubleQuoted, singleQuoted, orgApostrophe]
   where
-    orgDash = do
-      guardOrSmartEnabled =<< getExportSetting exportSpecialStrings
-      pure <$> dash <* updatePositions '-'
-    orgEllipses = do
-      guardOrSmartEnabled =<< getExportSetting exportSpecialStrings
-      pure <$> ellipses <* updatePositions '.'
     orgApostrophe = do
-      guardEnabled Ext_smart
       (char '\'' <|> char '\8217') <* updateLastPreCharPos
                                    <* updateLastForbiddenCharPos
       returnF (B.str "\x2019")
 
-guardOrSmartEnabled :: PandocMonad m => Bool -> OrgParser m ()
-guardOrSmartEnabled b = do
-  smartExtension <- extensionEnabled Ext_smart <$> getOption readerExtensions
-  guard (b || smartExtension)
+specialStrings :: PandocMonad m => OrgParser m (F Inlines)
+specialStrings = do
+  guard =<< getExportSetting exportSpecialStrings
+  choice [orgDash, orgEllipses, shyHyphen]
+  where
+    shyHyphen   = pure <$> (B.str "\173" <$ string "\\-") <* updatePositions '-'
+    orgDash     = pure <$> dash <* updatePositions '-'
+    orgEllipses = pure <$> ellipses <* updatePositions '.'
 
 singleQuoted :: PandocMonad m => OrgParser m (F Inlines)
 singleQuoted = try $ do
-  guardOrSmartEnabled =<< getExportSetting exportSmartQuotes
   singleQuoteStart
   updatePositions '\''
   withQuoteContext InSingleQuote $
@@ -904,7 +939,6 @@
 -- in the same paragraph.
 doubleQuoted :: PandocMonad m => OrgParser m (F Inlines)
 doubleQuoted = try $ do
-  guardOrSmartEnabled =<< getExportSetting exportSmartQuotes
   doubleQuoteStart
   updatePositions '"'
   contents <- mconcat <$> many (try $ notFollowedBy doubleQuoteEnd >> inline)
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,29 +1,12 @@
-{-# LANGUAGE FlexibleContexts #-}
-{-# LANGUAGE TupleSections    #-}
-{-
-Copyright (C) 2014-2017 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 LambdaCase        #-}
+{-# LANGUAGE OverloadedStrings #-}
 {- |
    Module      : Text.Pandoc.Readers.Org.Meta
-   Copyright   : Copyright (C) 2014-2017 Albert Krewinkel
+   Copyright   : Copyright (C) 2014-2024 Albert Krewinkel
    License     : GNU GPL, version 2 or above
 
-   Maintainer  : Albert Krewinkel <tarleb+pandoc@moltkeplatz.de>
+   Maintainer  : Albert Krewinkel <albert+pandoc@tarleb.com>
 
 Parsers for Org-mode meta declarations.
 -}
@@ -41,14 +24,19 @@
 
 import Text.Pandoc.Builder (Blocks, Inlines)
 import qualified Text.Pandoc.Builder as B
-import Text.Pandoc.Class (PandocMonad)
+import Text.Pandoc.Class.PandocMonad (PandocMonad)
 import Text.Pandoc.Definition
+import Text.Pandoc.Shared (blocksToInlines, safeRead)
+import Text.Pandoc.URI (urlEncode)
 
-import Control.Monad (mzero, void, when)
-import Data.Char (toLower)
-import Data.List (intersperse)
-import qualified Data.Map as M
-import Network.HTTP (urlEncode)
+import Control.Monad (mzero, void)
+import Data.List (intercalate, intersperse)
+import Data.Map (Map)
+import Data.Maybe (fromMaybe)
+import Data.Text (Text)
+import qualified Data.Map as Map
+import qualified Data.Set as Set
+import qualified Data.Text as T
 
 -- | Returns the current meta, respecting export options.
 metaExport :: Monad m => OrgParser m (F Meta)
@@ -60,145 +48,202 @@
          . (if exportWithEmail   settings then id else removeMeta "email")
         <$> orgStateMeta st
 
-removeMeta :: String -> Meta -> Meta
+removeMeta :: Text -> Meta -> Meta
 removeMeta key meta' =
   let metaMap = unMeta meta'
-  in Meta $ M.delete key metaMap
+  in Meta $ Map.delete key metaMap
 
 -- | Parse and handle a single line containing meta information
 -- The order, in which blocks are tried, makes sure that we're not looking at
 -- the beginning of a block, so we don't need to check for it
 metaLine :: PandocMonad m => OrgParser m Blocks
-metaLine = mempty <$ metaLineStart <* (optionLine <|> declarationLine)
-
-declarationLine :: PandocMonad m => OrgParser m ()
-declarationLine = try $ do
-  key   <- map toLower <$> metaKey
-  (key', value) <- metaValue key
-  let addMetaValue st =
-        st { orgStateMeta = B.setMeta key' <$> value <*> orgStateMeta st }
-  when (key' /= "results") $ updateState addMetaValue
+metaLine = try $ mempty <$ metaLineStart <* keywordLine
 
-metaKey :: Monad m => OrgParser m String
-metaKey = map toLower <$> many1 (noneOf ": \n\r")
-                      <*  char ':'
-                      <*  skipSpaces
+keywordLine :: PandocMonad m => OrgParser m ()
+keywordLine = try $ do
+  key   <- T.toLower <$> metaKey
+  case Map.lookup key keywordHandlers of
+    Nothing -> fail $ "Unknown keyword: " ++ T.unpack key
+    Just hd -> hd
 
-metaValue :: PandocMonad m => String -> OrgParser m (String, F MetaValue)
-metaValue key =
-  let inclKey = "header-includes"
-  in case key of
-    "author"          -> (key,) <$> metaInlinesCommaSeparated
-    "keywords"        -> (key,) <$> metaInlinesCommaSeparated
-    "title"           -> (key,) <$> metaInlines
-    "subtitle"        -> (key,) <$> metaInlines
-    "date"            -> (key,) <$> metaInlines
-    "nocite"          -> (key,) <$> accumulatingList key metaInlines
-    "header-includes" -> (key,) <$> accumulatingList key metaInlines
-    "latex_header"    -> (inclKey,) <$>
-                         accumulatingList inclKey (metaExportSnippet "latex")
-    "latex_class"     -> ("documentclass",) <$> metaString
-    -- Org-mode expects class options to contain the surrounding brackets,
-    -- pandoc does not.
-    "latex_class_options" -> ("classoption",) <$>
-                             metaModifiedString (filter (`notElem` "[]"))
-    "html_head"       -> (inclKey,) <$>
-                         accumulatingList inclKey (metaExportSnippet "html")
-    _                 -> (key,) <$> metaString
+metaKey :: Monad m => OrgParser m Text
+metaKey = T.toLower <$> many1Char (noneOf ": \n\r")
+                    <*  char ':'
+                    <*  skipSpaces
 
-metaInlines :: PandocMonad m => OrgParser m (F MetaValue)
-metaInlines = fmap (MetaInlines . B.toList) <$> inlinesTillNewline
+infix 0 ~~>
+(~~>) :: a -> b -> (a, b)
+a ~~> b = (a, b)
 
-metaInlinesCommaSeparated :: PandocMonad m => OrgParser m (F MetaValue)
-metaInlinesCommaSeparated = do
-  itemStrs <- many1 (noneOf ",\n") `sepBy1` char ','
-  newline
-  items <- mapM (parseFromString inlinesTillNewline . (++ "\n")) itemStrs
-  let toMetaInlines = MetaInlines . B.toList
-  return $ MetaList . map toMetaInlines <$> sequence items
+keywordHandlers :: PandocMonad m => Map Text (OrgParser m ())
+keywordHandlers = Map.fromList
+  [ "author" ~~> lineOfInlines `parseThen` collectLines "author"
+  , "bibliography" ~~> fmap pure anyLine `parseThen` collectAsList "bibliography"
+  , "creator" ~~> fmap pure anyLine `parseThen` B.setMeta "creator"
+  , "date" ~~> lineOfInlines `parseThen` B.setMeta "date"
+  , "description" ~~> lineOfInlines `parseThen` collectLines "description"
+  , "email" ~~> fmap pure anyLine `parseThen` B.setMeta "email"
+  , "exclude_tags" ~~> tagList >>= updateState . setExcludedTags
+  , "header-includes" ~~>
+    lineOfInlines `parseThen` collectLines "header-includes"
+  -- HTML-specifix export settings
+  , "html_head" ~~>
+    metaExportSnippet "html" `parseThen` collectAsList "header-includes"
+  , "html_head_extra" ~~>
+    metaExportSnippet "html" `parseThen` collectAsList "header-includes"
+  , "institute" ~~> lineOfInlines `parseThen` collectLines "institute"
+  -- topic keywords
+  , "keywords" ~~> lineOfInlines `parseThen` collectLines "keywords"
+  -- document language
+  , "language" ~~> fmap pure anyLine `parseThen` B.setMeta "lang"
+  -- LaTeX-specific export settings
+  , "latex_class" ~~> fmap pure anyLine `parseThen` B.setMeta "documentclass"
+  , "latex_class_options" ~~>
+      (pure . T.filter (`notElem` ("[]" :: String)) <$> anyLine)
+      `parseThen` B.setMeta "classoption"
+  , "latex_header" ~~>
+      metaExportSnippet "latex" `parseThen` collectAsList "header-includes"
+  , "latex_header_extra" ~~>
+      metaExportSnippet "latex" `parseThen` collectAsList "header-includes"
+  -- link and macro
+  , "link" ~~> addLinkFormatter
+  , "macro" ~~> macroDefinition >>= updateState . registerMacro
+  -- pandoc-specific way to include references in the bibliography
+  , "nocite" ~~> lineOfInlines `parseThen` collectLines "nocite"
+  -- compact way to set export settings
+  , "options"  ~~> exportSettings
+  -- pandoc-specific way to configure emphasis recognition
+  , "pandoc-emphasis-post" ~~> emphChars >>= updateState . setEmphasisPostChar
+  , "pandoc-emphasis-pre" ~~> emphChars >>= updateState . setEmphasisPreChar
+  -- result markers (ignored)
+  , "result" ~~> void anyLine
+  , "select_tags" ~~> tagList >>= updateState . setSelectedTags
+  , "seq_todo" ~~> todoSequence >>= updateState . registerTodoSequence
+  , "subtitle" ~~> lineOfInlines `parseThen` collectLines "subtitle"
+  , "title" ~~> lineOfInlines `parseThen` collectLines "title"
+  , "todo" ~~> todoSequence >>= updateState . registerTodoSequence
+  , "typ_todo" ~~> todoSequence >>= updateState . registerTodoSequence
+  ]
 
-metaString :: Monad m => OrgParser m (F MetaValue)
-metaString = metaModifiedString id
+parseThen :: PandocMonad m
+          => OrgParser m (F a)
+          -> (a -> Meta -> Meta)
+          -> OrgParser m ()
+parseThen p modMeta = do
+  value <- p
+  meta  <- orgStateMeta <$> getState
+  updateState (\st -> st { orgStateMeta = modMeta <$> value <*> meta })
 
-metaModifiedString :: Monad m => (String -> String) -> OrgParser m (F MetaValue)
-metaModifiedString f = return . MetaString . f <$> anyLine
+collectLines :: Text -> Inlines -> Meta -> Meta
+collectLines key value meta =
+  let value' = appendValue meta (B.toList value)
+  in B.setMeta key value' meta
+ where
+  appendValue :: Meta -> [Inline] -> MetaValue
+  appendValue m v = MetaInlines $ curInlines m <> v
 
--- | Read an format specific meta definition
-metaExportSnippet :: Monad m => String -> OrgParser m (F MetaValue)
-metaExportSnippet format =
-  return . MetaInlines . B.toList . B.rawInline format <$> anyLine
+  curInlines m = case collectInlines <$> lookupMeta key m of
+    Nothing -> []
+    Just [] -> []
+    Just xs -> xs <> [B.SoftBreak]
 
--- | Accumulate the result of the @parser@ in a list under @key@.
-accumulatingList :: Monad m => String
-                 -> OrgParser m (F MetaValue)
-                 -> OrgParser m (F MetaValue)
-accumulatingList key p = do
-  value <- p
-  meta' <- orgStateMeta <$> getState
-  return $ (\m v -> MetaList (curList m ++ [v])) <$> meta' <*> value
- where curList m = case lookupMeta key m of
-                     Just (MetaList ms) -> ms
-                     Just x             -> [x]
-                     _                  -> []
+  collectInlines :: MetaValue -> [Inline]
+  collectInlines = \case
+    MetaInlines inlns -> inlns
+    MetaList ml       -> intercalate [B.SoftBreak] $ map collectInlines ml
+    MetaString s      -> [B.Str s]
+    MetaBlocks blks   -> blocksToInlines blks
+    MetaMap _map      -> []
+    MetaBool _bool    -> []
 
---
--- export options
---
-optionLine :: Monad m => OrgParser m ()
-optionLine = try $ do
-  key <- metaKey
-  case key of
-    "link"     -> parseLinkFormat >>= uncurry addLinkFormat
-    "options"  -> exportSettings
-    "todo"     -> todoSequence >>= updateState . registerTodoSequence
-    "seq_todo" -> todoSequence >>= updateState . registerTodoSequence
-    "typ_todo" -> todoSequence >>= updateState . registerTodoSequence
-    "macro"    -> macroDefinition >>= updateState . registerMacro
-    _          -> mzero
+-- | Accumulate the result as a MetaList under the given key.
+collectAsList :: B.ToMetaValue a => Text -> a -> Meta -> Meta
+collectAsList key value meta =
+  let value' = metaListAppend meta (B.toMetaValue value)
+  in B.setMeta key value' meta
+ where
+  metaListAppend m v = MetaList (curList m ++ [v])
+  curList m = case lookupMeta key m of
+                Just (MetaList ms) -> ms
+                Just x             -> [x]
+                _                  -> []
 
-addLinkFormat :: Monad m => String
-              -> (String -> String)
-              -> OrgParser m ()
-addLinkFormat key formatter = updateState $ \s ->
-  let fs = orgStateLinkFormatters s
-  in s{ orgStateLinkFormatters = M.insert key formatter fs }
+-- | Read an format specific meta definition
+metaExportSnippet :: Monad m => Text -> OrgParser m (F Inlines)
+metaExportSnippet format = pure . B.rawInline format <$> anyLine
 
-parseLinkFormat :: Monad m => OrgParser m (String, String -> String)
-parseLinkFormat = try $ do
-  linkType <- (:) <$> letter <*> many (alphaNum <|> oneOf "-_") <* skipSpaces
-  linkSubst <- parseFormat
-  return (linkType, linkSubst)
+-- | Parse a link type definition (like @wp https://en.wikipedia.org/wiki/@).
+addLinkFormatter :: Monad m => OrgParser m ()
+addLinkFormatter = try $ do
+  linkType <- T.cons <$> letter <*> manyChar (alphaNum <|> oneOf "-_") <* skipSpaces
+  formatter <- parseFormat
+  updateState $ \s ->
+    let fs = orgStateLinkFormatters s
+    in s{ orgStateLinkFormatters = Map.insert linkType formatter fs }
 
 -- | An ad-hoc, single-argument-only implementation of a printf-style format
 -- parser.
-parseFormat :: Monad m => OrgParser m (String -> String)
+parseFormat :: Monad m => OrgParser m (Text -> Text)
 parseFormat = try $ replacePlain <|> replaceUrl <|> justAppend
  where
-   -- inefficient, but who cares
-   replacePlain = try $ (\x -> concat . flip intersperse x)
+   -- inefficient
+   replacePlain = try $ (\x -> T.concat . flip intersperse x)
                      <$> sequence [tillSpecifier 's', rest]
-   replaceUrl   = try $ (\x -> concat . flip intersperse x . urlEncode)
+   replaceUrl   = try $ (\x -> T.concat . flip intersperse x . urlEncode)
                      <$> sequence [tillSpecifier 'h', rest]
-   justAppend   = try $ (++) <$> rest
+   justAppend   = try $ (<>) <$> rest
 
-   rest            = manyTill anyChar         (eof <|> () <$ oneOf "\n\r")
-   tillSpecifier c = manyTill (noneOf "\n\r") (try $ string ('%':c:""))
+   rest            = manyTillChar anyChar         (eof <|> () <$ oneOf "\n\r")
+   tillSpecifier c = manyTillChar (noneOf "\n\r") (try $ string ('%':c:""))
 
-inlinesTillNewline :: PandocMonad m => OrgParser m (F Inlines)
-inlinesTillNewline = do
+tagList :: Monad m => OrgParser m [Tag]
+tagList = do
+  skipSpaces
+  map Tag <$> many (orgTagWord <* skipSpaces) <* newline
+
+setExcludedTags :: [Tag] -> OrgParserState -> OrgParserState
+setExcludedTags tags st =
+  let finalSet = if orgStateExcludeTagsChanged st
+                   then foldr Set.insert (orgStateExcludeTags st) tags
+                   else Set.fromList tags
+  in st { orgStateExcludeTags = finalSet, orgStateExcludeTagsChanged = True }
+
+setSelectedTags :: [Tag] -> OrgParserState -> OrgParserState
+setSelectedTags tags st =
+  let finalSet = if orgStateSelectTagsChanged st
+                   then foldr Set.insert (orgStateSelectTags st) tags
+                   else Set.fromList tags
+  in st { orgStateSelectTags = finalSet, orgStateSelectTagsChanged = True }
+
+setEmphasisPreChar :: Maybe [Char] -> OrgParserState -> OrgParserState
+setEmphasisPreChar csMb st =
+  let preChars = fromMaybe (orgStateEmphasisPreChars defaultOrgParserState) csMb
+  in st { orgStateEmphasisPreChars = preChars }
+
+setEmphasisPostChar :: Maybe [Char] -> OrgParserState -> OrgParserState
+setEmphasisPostChar csMb st =
+  let postChars = fromMaybe (orgStateEmphasisPostChars defaultOrgParserState) csMb
+  in st { orgStateEmphasisPostChars = postChars }
+
+-- | Parses emphasis border character like @".,?!"@
+emphChars :: Monad m => OrgParser m (Maybe [Char])
+emphChars = do
+  skipSpaces
+  safeRead <$> anyLine
+
+lineOfInlines :: PandocMonad m => OrgParser m (F Inlines)
+lineOfInlines = do
   updateLastPreCharPos
   trimInlinesF . mconcat <$> manyTill inline newline
 
---
--- ToDo Sequences and Keywords
---
+-- | Parses ToDo sequences / keywords like @TODO DOING | DONE@.
 todoSequence :: Monad m => OrgParser m TodoSequence
 todoSequence = try $ do
   todoKws <- todoKeywords
-  doneKws <- optionMaybe $ todoDoneSep *> todoKeywords
+  doneKws <- optionMaybe $ todoDoneSep *> doneKeywords
   newline
-  -- There must be at least one DONE keyword. The last TODO keyword is taken if
-  -- necessary.
+  -- There must be at least one DONE keyword. The last TODO keyword is
+  -- taken if necessary.
   case doneKws of
     Just done  -> return $ keywordsToSequence todoKws done
     Nothing    -> case reverse todoKws of
@@ -206,41 +251,51 @@
                     (x:xs) -> return $ keywordsToSequence (reverse xs) [x]
 
  where
-   todoKeywords :: Monad m => OrgParser m [String]
+   todoKeyword :: Monad m => OrgParser m Text
+   todoKeyword = do
+     keyword <- many1Char nonspaceChar
+     let cleanKeyword = T.takeWhile (/= '(') keyword
+     skipSpaces
+     return cleanKeyword
+
+   todoKeywords :: Monad m => OrgParser m [Text]
    todoKeywords = try $
-     let keyword = many1 nonspaceChar <* skipSpaces
-         endOfKeywords = todoDoneSep <|> void newline
-     in manyTill keyword (lookAhead endOfKeywords)
+     let endOfKeywords = todoDoneSep <|> void newline
+     in manyTill todoKeyword (lookAhead endOfKeywords)
 
+   doneKeywords :: Monad m => OrgParser m [Text]
+   doneKeywords = try $
+     manyTill (todoKeyword <* optional todoDoneSep) (lookAhead newline)
+
    todoDoneSep :: Monad m => OrgParser m ()
    todoDoneSep = void . try $ skipSpaces *> char '|' <* skipSpaces1
 
-   keywordsToSequence :: [String] -> [String] -> TodoSequence
+   keywordsToSequence :: [Text] -> [Text] -> TodoSequence
    keywordsToSequence todo done =
      let todoMarkers = map (TodoMarker Todo) todo
          doneMarkers = map (TodoMarker Done) done
      in todoMarkers ++ doneMarkers
 
-macroDefinition :: Monad m => OrgParser m (String, [String] -> String)
+macroDefinition :: Monad m => OrgParser m (Text, [Text] -> Text)
 macroDefinition = try $ do
-  macroName <- many1 nonspaceChar <* skipSpaces
+  macroName <- many1Char nonspaceChar <* skipSpaces
   firstPart <- expansionPart
   (elemOrder, parts) <- unzip <$> many ((,) <$> placeholder <*> expansionPart)
   let expander = mconcat . alternate (firstPart:parts) . reorder elemOrder
   return (macroName, expander)
  where
   placeholder :: Monad m => OrgParser m Int
-  placeholder = try . fmap read $ char '$' *> many1 digit
+  placeholder = try . fmap (fromMaybe 1 . safeRead) $ char '$' *> many1Char digit
 
-  expansionPart :: Monad m => OrgParser m String
-  expansionPart = try $ many (notFollowedBy placeholder *> noneOf "\n\r")
+  expansionPart :: Monad m => OrgParser m Text
+  expansionPart = try $ manyChar (notFollowedBy placeholder *> noneOf "\n\r")
 
   alternate :: [a] -> [a] -> [a]
   alternate []     ys     = ys
   alternate xs     []     = xs
   alternate (x:xs) (y:ys) = x : y : alternate xs ys
 
-  reorder :: [Int] -> [String] -> [String]
+  reorder :: [Int] -> [Text] -> [Text]
   reorder perm xs =
     let element n = take 1 $ drop (n - 1) xs
     in concatMap element perm
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,36 +1,21 @@
 {-# LANGUAGE FlexibleInstances     #-}
 {-# LANGUAGE MultiParamTypeClasses #-}
-{-
-Copyright (C) 2014-2017 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 OverloadedStrings     #-}
 {- |
    Module      : Text.Pandoc.Readers.Org.ParserState
-   Copyright   : Copyright (C) 2014-2017 Albert Krewinkel
+   Copyright   : Copyright (C) 2014-2025 Albert Krewinkel
    License     : GNU GPL, version 2 or above
 
-   Maintainer  : Albert Krewinkel <tarleb+pandoc@moltkeplatz.de>
+   Maintainer  : Albert Krewinkel <albert+pandoc@tarleb.com>
 
 Define the Org-mode parser state.
 -}
 module Text.Pandoc.Readers.Org.ParserState
   ( OrgParserState (..)
+  , defaultOrgParserState
   , OrgParserLocal (..)
   , OrgNoteRecord
+  , Tag(..)
   , HasReaderOptions (..)
   , HasQuoteContext (..)
   , HasMacros (..)
@@ -50,6 +35,7 @@
   , returnF
   , ExportSettings (..)
   , ArchivedTreesOption (..)
+  , TeXExport (..)
   , optionsToParserState
   ) where
 
@@ -60,31 +46,34 @@
 import qualified Data.Set as Set
 import Data.Text (Text)
 
-import Text.Pandoc.Builder (Blocks, Inlines)
+import Text.Pandoc.Builder (Blocks)
 import Text.Pandoc.Definition (Meta (..), nullMeta)
 import Text.Pandoc.Logging
-import Text.Pandoc.Options (ReaderOptions (..))
-import Text.Pandoc.Parsing (Future, HasHeaderMap (..), HasIdentifierList (..),
+import Text.Pandoc.Options (ReaderOptions (..), Extension(..), isEnabled)
+import Text.Pandoc.Parsing (Future, HasIdentifierList (..),
                             HasIncludeFiles (..), HasLastStrPosition (..),
                             HasLogMessages (..), HasMacros (..),
                             HasQuoteContext (..), HasReaderOptions (..),
                             ParserContext (..), QuoteContext (..), SourcePos,
                             askF, asksF, returnF, runF, trimInlinesF)
-import Text.Pandoc.Readers.LaTeX.Types (Macro)
+import Text.Pandoc.TeX (Macro)
 
 -- | This is used to delay evaluation until all relevant information has been
 -- parsed and made available in the parser state.
 type F = Future OrgParserState
 
 -- | An inline note / footnote containing the note key and its (inline) value.
-type OrgNoteRecord = (String, F Blocks)
+type OrgNoteRecord = (Text, F Blocks)
 -- | Table of footnotes
 type OrgNoteTable = [OrgNoteRecord]
 -- | Map of functions for link transformations.  The map key is refers to the
 -- link-type, the corresponding function transforms the given link string.
-type OrgLinkFormatters = M.Map String (String -> String)
+type OrgLinkFormatters = M.Map Text (Text -> Text)
 -- | Macro expander function
-type MacroExpander = [String] -> String
+type MacroExpander = [Text] -> Text
+-- | Tag
+newtype Tag = Tag { fromTag :: Text }
+  deriving (Show, Eq, Ord)
 
 -- | The states in which a todo item can be
 data TodoState = Todo | Done
@@ -93,7 +82,7 @@
 -- | A ToDo keyword like @TODO@ or @DONE@.
 data TodoMarker = TodoMarker
   { todoMarkerState :: TodoState
-  , todoMarkerName  :: String
+  , todoMarkerName  :: Text
   }
   deriving (Show, Eq)
 
@@ -102,29 +91,40 @@
 
 -- | Org-mode parser state
 data OrgParserState = OrgParserState
-  { orgStateAnchorIds            :: [String]
+  { orgStateAnchorIds            :: [Text]
   , orgStateEmphasisCharStack    :: [Char]
+  , orgStateEmphasisPreChars     :: [Char] -- ^ Chars allowed to occur before
+                                           -- emphasis; spaces and newlines are
+                                           -- always ok in addition to what is
+                                           -- specified here.
+  , orgStateEmphasisPostChars    :: [Char] -- ^ Chars allowed at after emphasis
   , orgStateEmphasisNewlines     :: Maybe Int
+  , orgStateExcludeTags          :: Set.Set Tag
+  , orgStateExcludeTagsChanged   :: Bool
   , orgStateExportSettings       :: ExportSettings
-  , orgStateHeaderMap            :: M.Map Inlines String
-  , orgStateIdentifiers          :: Set.Set String
-  , orgStateIncludeFiles         :: [String]
+  , orgStateIdentifiers          :: Set.Set Text
+  , orgStateIncludeFiles         :: [Text]
   , orgStateLastForbiddenCharPos :: Maybe SourcePos
   , orgStateLastPreCharPos       :: Maybe SourcePos
   , orgStateLastStrPos           :: Maybe SourcePos
   , orgStateLinkFormatters       :: OrgLinkFormatters
-  , orgStateMacros               :: M.Map String MacroExpander
+  , orgStateMacros               :: M.Map Text MacroExpander
   , orgStateMacroDepth           :: Int
   , orgStateMeta                 :: F Meta
   , orgStateNotes'               :: OrgNoteTable
   , orgStateOptions              :: ReaderOptions
   , orgStateParserContext        :: ParserContext
+  , orgStateSelectTags           :: Set.Set Tag
+  , orgStateSelectTagsChanged    :: Bool
   , orgStateTodoSequences        :: [TodoSequence]
+  , orgStateTrimLeadBlkIndent    :: Bool
   , orgLogMessages               :: [LogMessage]
   , orgMacros                    :: M.Map Text Macro
   }
 
-data OrgParserLocal = OrgParserLocal { orgLocalQuoteContext :: QuoteContext }
+newtype OrgParserLocal = OrgParserLocal
+  { orgLocalQuoteContext :: QuoteContext
+  }
 
 instance Default OrgParserLocal where
   def = OrgParserLocal NoQuote
@@ -134,7 +134,7 @@
 
 instance HasLastStrPosition OrgParserState where
   getLastStrPos = orgStateLastStrPos
-  setLastStrPos pos st = st{ orgStateLastStrPos = Just pos }
+  setLastStrPos pos st = st{ orgStateLastStrPos = pos }
 
 instance Monad m => HasQuoteContext st (ReaderT OrgParserLocal m) where
   getQuoteContext = asks orgLocalQuoteContext
@@ -144,10 +144,6 @@
   extractIdentifierList = orgStateIdentifiers
   updateIdentifierList f s = s{ orgStateIdentifiers = f (orgStateIdentifiers s) }
 
-instance HasHeaderMap OrgParserState where
-  extractHeaderMap = orgStateHeaderMap
-  updateHeaderMap  f s = s{ orgStateHeaderMap = f (orgStateHeaderMap s) }
-
 instance HasLogMessages OrgParserState where
   addLogMessage msg st = st{ orgLogMessages = msg : orgLogMessages st }
   getLogMessages st = reverse $ orgLogMessages st
@@ -168,10 +164,13 @@
 defaultOrgParserState :: OrgParserState
 defaultOrgParserState = OrgParserState
   { orgStateAnchorIds = []
+  , orgStateEmphasisPreChars = "-\t ('\"{\x200B"
+  , orgStateEmphasisPostChars  = "-\t\n .,:!?;'\")}[\x200B"
   , orgStateEmphasisCharStack = []
   , orgStateEmphasisNewlines = Nothing
   , orgStateExportSettings = def
-  , orgStateHeaderMap = M.empty
+  , orgStateExcludeTags = Set.singleton $ Tag "noexport"
+  , orgStateExcludeTagsChanged = False
   , orgStateIdentifiers = Set.empty
   , orgStateIncludeFiles = []
   , orgStateLastForbiddenCharPos = Nothing
@@ -184,6 +183,9 @@
   , orgStateNotes' = []
   , orgStateOptions = def
   , orgStateParserContext = NullState
+  , orgStateSelectTags = Set.singleton $ Tag "export"
+  , orgStateSelectTagsChanged = False
+  , orgStateTrimLeadBlkIndent = True
   , orgStateTodoSequences = []
   , orgLogMessages = []
   , orgMacros = M.empty
@@ -191,7 +193,15 @@
 
 optionsToParserState :: ReaderOptions -> OrgParserState
 optionsToParserState opts =
-  def { orgStateOptions = opts }
+  let exportSettings = defaultExportSettings
+        { exportSmartQuotes = isEnabled Ext_smart opts ||
+                              isEnabled Ext_smart_quotes opts
+        , exportSpecialStrings = isEnabled Ext_smart opts ||
+                                 isEnabled Ext_special_strings opts
+        }
+  in def { orgStateOptions = opts
+         , orgStateExportSettings = exportSettings
+         }
 
 registerTodoSequence :: TodoSequence -> OrgParserState -> OrgParserState
 registerTodoSequence todoSeq st =
@@ -210,10 +220,10 @@
 activeTodoMarkers :: OrgParserState -> TodoSequence
 activeTodoMarkers = concat . activeTodoSequences
 
-lookupMacro :: String -> OrgParserState -> Maybe MacroExpander
+lookupMacro :: Text -> OrgParserState -> Maybe MacroExpander
 lookupMacro macroName = M.lookup macroName . orgStateMacros
 
-registerMacro :: (String, MacroExpander) -> OrgParserState -> OrgParserState
+registerMacro :: (Text, MacroExpander) -> OrgParserState -> OrgParserState
 registerMacro (name, expander) st =
   let curMacros = orgStateMacros st
   in st{ orgStateMacros = M.insert name expander curMacros }
@@ -230,11 +240,18 @@
   | ArchivedTreesNoExport     -- ^ Exclude archived trees from exporting
   | ArchivedTreesHeadlineOnly -- ^ Export only the headline, discard the contents
 
+-- | Options for the handling of LaTeX environments and fragments.
+-- Represents allowed values of Emacs variable @org-export-with-latex@.
+data TeXExport
+  = TeXExport                 -- ^ Include raw TeX in the output
+  | TeXIgnore                 -- ^ Ignore raw TeX
+  | TeXVerbatim               -- ^ Keep everything in verbatim
+
 -- | Export settings <http://orgmode.org/manual/Export-settings.html>
 -- These settings can be changed via OPTIONS statements.
 data ExportSettings = ExportSettings
   { exportArchivedTrees    :: ArchivedTreesOption -- ^ How to treat archived trees
-  , exportDrawers          :: Either [String] [String]
+  , exportDrawers          :: Either [Text] [Text]
   -- ^ Specify drawer names which should be exported.  @Left@ names are
   -- explicitly excluded from the resulting output while @Right@ means that
   -- only the listed drawer names should be included.
@@ -248,7 +265,12 @@
   , exportWithAuthor       :: Bool -- ^ Include author in final meta-data
   , exportWithCreator      :: Bool -- ^ Include creator in final meta-data
   , exportWithEmail        :: Bool -- ^ Include email in final meta-data
+  , exportWithEntities     :: Bool -- ^ Include MathML-like entities
+  , exportWithFootnotes    :: Bool -- ^ Include footnotes
+  , exportWithLatex        :: TeXExport -- ^ Handling of raw TeX commands
+  , exportWithPlanning     :: Bool -- ^ Keep planning info after headlines
   , exportWithTags         :: Bool -- ^ Keep tags as part of headlines
+  , exportWithTables       :: Bool -- ^ Include tables
   , exportWithTodoKeywords :: Bool -- ^ Keep TODO keywords in headers
   }
 
@@ -268,6 +290,11 @@
   , exportWithAuthor = True
   , exportWithCreator = True
   , exportWithEmail = True
+  , exportWithEntities = True
+  , exportWithFootnotes = True
+  , exportWithLatex = TeXExport
+  , exportWithPlanning = False
   , exportWithTags = True
+  , exportWithTables = True
   , exportWithTodoKeywords = True
   }
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,27 +1,9 @@
-{-
-Copyright (C) 2014-2017 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-2017 Albert Krewinkel
+   Copyright   : Copyright (C) 2014-2025 Albert Krewinkel
    License     : GNU GPL, version 2 or above
 
-   Maintainer  : Albert Krewinkel <tarleb+pandoc@moltkeplatz.de>
+   Maintainer  : Albert Krewinkel <albert+pandoc@tarleb.com>
 
 Org-mode parsing utilities.
 
@@ -45,10 +27,20 @@
   , orgArgKey
   , orgArgWord
   , orgArgWordChar
+  , orgTagWord
+  , orgTagWordChar
+  , orgAnchor
   -- * Re-exports from Text.Pandoc.Parser
   , ParserContext (..)
+  , textStr
+  , countChar
+  , manyChar
+  , many1Char
+  , manyTillChar
   , many1Till
+  , many1TillChar
   , notFollowedBy'
+  , sepBy1'
   , spaceChar
   , nonspaceChar
   , skipSpaces
@@ -62,6 +54,7 @@
   , guardEnabled
   , updateLastStrPos
   , notAfterString
+  , getLastStrPos
   , ParserState (..)
   , registerHeader
   , QuoteContext (..)
@@ -73,8 +66,7 @@
   , ellipses
   , citeKey
   , gridTableWith
-  , insertIncludedFileF
-  -- * Re-exports from Text.Pandoc.Parsec
+  , insertIncludedFile
   , runParser
   , runParserT
   , getInput
@@ -103,46 +95,48 @@
   , sepBy
   , sepBy1
   , sepEndBy1
+  , endBy1
   , option
   , optional
   , optionMaybe
   , getState
   , updateState
   , SourcePos
+  , sourceName
   , getPosition
   ) where
 
+import Data.Text (Text)
 import Text.Pandoc.Readers.Org.ParserState
 
-import Text.Pandoc.Parsing hiding (F, anyLine, blanklines, newline,
-                            parseFromString)
+import Text.Pandoc.Parsing hiding (anyLine, blanklines, newline,
+                                   parseFromString)
 import qualified Text.Pandoc.Parsing as P
 
 import Control.Monad (guard)
 import Control.Monad.Reader (ReaderT)
 
 -- | The parser used to read org files.
-type OrgParser m = ParserT [Char] OrgParserState (ReaderT OrgParserLocal m)
+type OrgParser m = ParsecT Sources OrgParserState (ReaderT OrgParserLocal m)
 
 --
 -- Adaptions and specializations of parsing utilities
 --
 
 -- | Parse any line of text
-anyLine :: Monad m => OrgParser m String
+anyLine :: Monad m => OrgParser m Text
 anyLine =
   P.anyLine
     <* updateLastPreCharPos
     <* updateLastForbiddenCharPos
 
--- The version Text.Pandoc.Parsing cannot be used, as we need additional parts
--- of the state saved and restored.
-parseFromString :: Monad m => OrgParser m a -> String -> OrgParser m a
+-- | Like @'Text.Pandoc.Parsing'@, but resets the position of the last character
+-- allowed before emphasised text.
+parseFromString :: Monad m => OrgParser m a -> Text -> OrgParser m a
 parseFromString parser str' = do
-  oldLastPreCharPos <- orgStateLastPreCharPos <$> getState
   updateState $ \s -> s{ orgStateLastPreCharPos = Nothing }
   result <- P.parseFromString parser str'
-  updateState $ \s -> s{ orgStateLastPreCharPos = oldLastPreCharPos }
+  updateState $ \s -> s { orgStateLastPreCharPos = Nothing }
   return result
 
 -- | Skip one or more tab or space characters.
@@ -157,7 +151,7 @@
        <* updateLastForbiddenCharPos
 
 -- | Like @Text.Parsec.Char.blanklines@, but causes additional state changes.
-blanklines :: Monad m => OrgParser m [Char]
+blanklines :: Monad m => OrgParser m Text
 blanklines =
   P.blanklines
        <* updateLastPreCharPos
@@ -172,7 +166,7 @@
 -- | Parse in different context
 withContext :: Monad m
             => ParserContext -- ^ New parser context
-            -> OrgParser m a   -- ^ Parser to run in that context
+            -> OrgParser m a   -- ^ Parsec to run in that context
             -> OrgParser m a
 withContext context parser = do
   oldContext <- orgStateParserContext <$> getState
@@ -182,7 +176,7 @@
   return result
 
 --
--- Parser state functions
+-- Parsec state functions
 --
 
 -- | Get an export setting.
@@ -207,15 +201,34 @@
 --
 
 -- | Read the key of a plist style key-value list.
-orgArgKey :: Monad m => OrgParser m String
+orgArgKey :: Monad m => OrgParser m Text
 orgArgKey = try $
   skipSpaces *> char ':'
-             *> many1 orgArgWordChar
+             *> many1Char orgArgWordChar
 
 -- | Read the value of a plist style key-value list.
-orgArgWord :: Monad m => OrgParser m String
-orgArgWord = many1 orgArgWordChar
+orgArgWord :: Monad m => OrgParser m Text
+orgArgWord = many1Char orgArgWordChar
 
 -- | Chars treated as part of a word in plists.
 orgArgWordChar :: Monad m => OrgParser m Char
 orgArgWordChar = alphaNum <|> oneOf "-_"
+
+orgTagWord :: Monad m => OrgParser m Text
+orgTagWord = many1Char orgTagWordChar
+
+orgTagWordChar :: Monad m => OrgParser m Char
+orgTagWordChar = alphaNum <|> oneOf "@%#_"
+
+orgAnchor :: Monad m => OrgParser m Text
+orgAnchor = try $ do
+  string "<<"
+  anchorId <- many1Char (noneOf "\t\n\r<>\"' ")
+  string ">>"
+  skipSpaces
+  recordAnchorId anchorId
+  return anchorId
+
+recordAnchorId :: Monad m => Text -> OrgParser m ()
+recordAnchorId i = updateState $ \s ->
+  s{ orgStateAnchorIds = i : orgStateAnchorIds s }
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,87 +1,79 @@
 {-# LANGUAGE OverloadedStrings #-}
-{-
-Copyright (C) 2014-2017 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-2017 Albert Krewinkel
+   Copyright   : Copyright (C) 2014-2024 Albert Krewinkel
    License     : GNU GPL, version 2 or above
 
-   Maintainer  : Albert Krewinkel <tarleb+pandoc@moltkeplatz.de>
+   Maintainer  : Albert Krewinkel <albert+pandoc@tarleb.com>
 
 Utility functions used in other Pandoc Org modules.
 -}
 module Text.Pandoc.Readers.Org.Shared
-  ( cleanLinkString
+  ( cleanLinkText
   , isImageFilename
   , originalLang
   , translateLang
+  , exportsCode
   ) where
 
+import Control.Applicative ((<|>))
 import Data.Char (isAlphaNum)
-import Data.List (isPrefixOf, isSuffixOf)
-
+import Data.Text (Text)
+import qualified Data.Text as T
+import System.FilePath (isValid, takeExtension)
+import qualified System.FilePath.Posix as Posix
+import qualified System.FilePath.Windows as Windows
 
 -- | Check whether the given string looks like the path to of URL of an image.
-isImageFilename :: String -> Bool
-isImageFilename filename =
-  any (\x -> ('.':x)  `isSuffixOf` filename) imageExtensions &&
-  (any (\x -> (x ++ "://") `isPrefixOf` filename) protocols ||
-   ':' `notElem` filename)
+isImageFilename :: Text -> Bool
+isImageFilename fp = hasImageExtension && (isValid (T.unpack fp) || isKnownProtocolUri)
  where
-   imageExtensions = [ "jpeg" , "jpg" , "png" , "gif" , "svg" ]
+   hasImageExtension = takeExtension (T.unpack $ T.toLower fp)
+                       `elem` imageExtensions
+   isKnownProtocolUri = any (\x -> (x <> "://") `T.isPrefixOf` fp) protocols
+
+   imageExtensions = [ ".jpeg", ".jpg", ".png", ".gif", ".svg", ".webp", ".jxl", ".avif" ]
    protocols = [ "file", "http", "https" ]
 
 -- | Cleanup and canonicalize a string describing a link.  Return @Nothing@ if
 -- the string does not appear to be a link.
-cleanLinkString :: String -> Maybe String
-cleanLinkString s =
-  case s of
-    '/':_                  -> Just $ "file://" ++ s  -- absolute path
-    '.':'/':_              -> Just s                 -- relative path
-    '.':'.':'/':_          -> Just s                 -- relative path
-    -- Relative path or URL (file schema)
-    'f':'i':'l':'e':':':s' -> Just $ if "//" `isPrefixOf` s' then s else s'
-    _                      | isUrl s            -> Just s                 -- URL
-    _                      -> Nothing
- where
-   isUrl :: String -> Bool
-   isUrl cs =
-     let (scheme, path) = break (== ':') cs
-     in all (\c -> isAlphaNum c || c `elem` (".-"::String)) scheme
-          && not (null path)
+cleanLinkText :: Text -> Maybe Text
+cleanLinkText s
+  | Just f <- toFileSchema s           = Just f                -- absolute path
+  | Just _ <- T.stripPrefix "./" s     = Just s                -- relative path
+  | Just _ <- T.stripPrefix "../" s    = Just s                -- relative path
+  -- Relative path or URL (file schema)
+  | Just s' <- T.stripPrefix "file:" s = if "//" `T.isPrefixOf` s'
+                                         then Just s
+                                         else  toFileSchema s' <|> Just s'
+  | isUrl s                            = Just s
+  | otherwise                          = Nothing
+  where
+    toFileSchema :: Text -> Maybe Text
+    toFileSchema t
+      | Windows.isAbsolute (T.unpack t) = Just ("file:///" <> t)
+      | Posix.isAbsolute (T.unpack t)   = Just ("file://" <> t)
+      | otherwise                       = Nothing
+    isUrl :: Text -> Bool
+    isUrl cs =
+      let (scheme, path) = T.break (== ':') cs
+      in T.all (\c -> isAlphaNum c || T.any (== c) ".-") scheme
+         && not (T.null path)
 
 -- | Creates an key-value pair marking the original language name specified for
 -- a piece of source code.
 
 -- | Creates an key-value attributes marking the original language name
 -- specified for a piece of source code.
-originalLang :: String -> [(String, String)]
+originalLang :: Text -> [(Text, Text)]
 originalLang lang =
   let transLang = translateLang lang
-  in if transLang == lang
-     then []
-     else [("org-language", lang)]
+  in [("org-language", lang) | transLang /= lang]
 
 -- | Translate from Org-mode's programming language identifiers to those used
 -- by Pandoc.  This is useful to allow for proper syntax highlighting in
 -- Pandoc output.
-translateLang :: String -> String
+translateLang :: Text -> Text
 translateLang cs =
   case cs of
     "C"          -> "c"
@@ -93,3 +85,6 @@
     "sh"         -> "bash"
     "sqlite"     -> "sql"
     _            -> cs
+
+exportsCode :: [(Text, Text)] -> Bool
+exportsCode = maybe True (`elem` ["code", "both"]) . lookup "exports"
diff --git a/src/Text/Pandoc/Readers/Pod.hs b/src/Text/Pandoc/Readers/Pod.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Readers/Pod.hs
@@ -0,0 +1,446 @@
+{-# LANGUAGE OverloadedStrings #-}
+{-# LANGUAGE ViewPatterns #-}
+{-# LANGUAGE TypeApplications #-}
+{- |
+   Module      : Text.Pandoc.Readers.Pod
+   Copyright   : © 2024 Evan Silberman
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : Evan Silberman <evan@jklol.net>
+   Stability   : WIP
+   Portability : portable
+
+Conversion of Pod to 'Pandoc' documents
+-}
+module Text.Pandoc.Readers.Pod (readPod) where
+
+import Control.Monad (void)
+import Control.Monad.Except (throwError)
+import Data.Char (isAsciiUpper, digitToInt)
+import Data.Default (Default)
+import Text.Pandoc.Logging
+import Text.Pandoc.Options
+import Text.Pandoc.Parsing
+import Text.Pandoc.Parsing.General (isSpaceChar)
+import Text.Pandoc.XML (lookupEntity)
+import Text.Pandoc.Class.PandocMonad (PandocMonad(..))
+import Text.Pandoc.Definition (Pandoc)
+import Text.Pandoc.Error
+import Text.Pandoc.Builder (Blocks, Inlines)
+import qualified Text.Pandoc.Builder as B
+import qualified Data.Text as T
+import qualified Data.Text.Read as TR
+import Text.Pandoc.Shared (stringify, textToIdentifier, tshow)
+import Data.Set (Set)
+import Data.Functor (($>))
+import Data.Maybe (listToMaybe, fromMaybe)
+import Numeric (readOct)
+
+data PodState = PodState
+  { logMessages :: [LogMessage]
+  , headerIds :: Set T.Text
+  , options :: ReaderOptions
+} deriving (Show)
+
+instance HasLogMessages PodState where
+  addLogMessage msg st = st{ logMessages = msg : logMessages st }
+  getLogMessages st = reverse $ logMessages st
+
+instance HasIdentifierList PodState where
+  extractIdentifierList = headerIds
+  updateIdentifierList f st = st{headerIds = f (headerIds st)}
+
+instance HasReaderOptions PodState where
+  extractReaderOptions = options
+
+instance Default PodState where
+  def = PodState
+    { logMessages = []
+    , headerIds = mempty
+    , options = def
+    }
+
+data PodLinkDestination = LinkUrl Inlines T.Text
+                        | LinkMan Inlines (Maybe Inlines)
+                        | LinkInternal Inlines
+                        deriving (Show)
+
+defaultLinkName :: PodLinkDestination -> Inlines
+defaultLinkName (LinkUrl inl _) = inl
+defaultLinkName (LinkMan nm (Just sec)) = B.doubleQuoted sec <> " in " <> nm
+defaultLinkName (LinkMan nm Nothing) = nm
+defaultLinkName (LinkInternal sec) = B.doubleQuoted sec
+
+type PodParser m = ParsecT Sources PodState m
+
+readPod :: (PandocMonad m, ToSources a)
+        => ReaderOptions
+        -> a
+        -> m Pandoc
+readPod _ s = do
+  let sources = toSources s
+  p <- readWithM parsePod def sources
+  case p of
+    Right result -> return result
+    Left e       -> throwError e
+
+parsePod :: PandocMonad m => PodParser m Pandoc
+parsePod = do
+  -- We don't actually start processing Pod until we encounter a Pod command.
+  -- If we never encounter a Pod command, the document is still valid Pod, it
+  -- just contains no content.
+  notPod
+  bs <- manyTill block eof
+  reportLogMessages
+  return $ B.doc $ mconcat bs
+
+block :: PandocMonad m => PodParser m Blocks
+block = verbatim  <|> paragraph <|> command <?> "Pod paragraph"
+
+command :: PandocMonad m => PodParser m Blocks
+command = do
+    try (char '=' >> notFollowedBy (string "item" <|> string "back" <|> string "end"))
+    header <|> pod <|> cut <|> over <|> for <|> begin <|> encoding <?> "Pod command"
+
+cmd :: PandocMonad m => T.Text -> PodParser m ()
+cmd nm = do
+  textStr nm
+  notFollowedBy nonspaceChar
+  void $ many spaceChar
+
+encoding :: PandocMonad m => PodParser m Blocks
+encoding = do
+  cmd "encoding"
+  anyLine
+  optional blanklines
+  logMessage $ IgnoredElement "=encoding; Pandoc requires UTF-8 input"
+  return mempty
+
+header :: PandocMonad m => PodParser m Blocks
+header = do
+  string "head"
+  dig <- oneOf "123456"
+  void blankline <|> skipMany1 spaceChar
+  ins <- inlines
+  attrs <- registerHeader B.nullAttr ins
+  optional blanklines
+  return $ B.headerWith attrs (digitToInt dig) ins
+
+pod :: PandocMonad m => PodParser m Blocks
+pod = do
+  cmd "pod"
+  optional (try inlines)
+  optional blanklines
+  return mempty
+
+cut :: PandocMonad m => PodParser m Blocks
+cut = cmd "cut" *> notPod
+
+notPod :: PandocMonad m => PodParser m Blocks
+notPod = do
+  manyTill anyLine (eof <|> void (try (lookAhead (char '=' *> letter))))
+  return mempty
+
+over :: PandocMonad m => PodParser m Blocks
+over = do
+  cmd "over"
+  anyLine
+  blanklines
+  optional $ try (char '=' *> cut)
+  bs <- list <|> blockquote
+  string "=back" <* blanklines
+  return bs
+
+list :: PandocMonad m => PodParser m Blocks
+list = try bulletList <|> try orderedList <|> definitionList
+
+bulletList :: PandocMonad m => PodParser m Blocks
+bulletList = B.bulletList <$> many1 (item (many spaceChar *> optional (char '*')))
+
+orderedList :: PandocMonad m => PodParser m Blocks
+orderedList = do
+  start <- item1
+  more <- many orderedItem
+  return $ B.orderedList (start : more)
+  where
+    item1 = item $ spaces *> char '1' *> optional (char '.')
+    orderedItem = item $ spaces *> many digit *> optional (char '.')
+
+item :: PandocMonad m => PodParser m () -> PodParser m Blocks
+item p = do
+  try (cmd "=item")
+  p
+  blanklines
+  mconcat <$> many block <?> "runaway item"
+
+definitionList :: PandocMonad m => PodParser m Blocks
+definitionList = B.definitionList <$> many1 dlItem
+  where
+    dlItem = do
+      try (cmd "=item")
+      spaces
+      term <- inlines
+      blanklines
+      -- perlpodspec sez the /section part of a link can refer to either
+      -- a header or a dl item, hence treating it as a "header" here
+      attrs <- registerHeader B.nullAttr term
+      defn <- mconcat <$> many block <?> "runaway dlitem"
+      return (B.spanWith attrs term, [defn])
+
+blockquote :: PandocMonad m => PodParser m Blocks
+blockquote = B.blockQuote . mconcat <$> many block <?> "runaway blockquote"
+
+paragraph :: PandocMonad m => PodParser m Blocks
+paragraph = do
+  try (notFollowedBy (char '=' *> letter))
+  inl <- inlines
+  optional blanklines
+  return $ B.para $ B.trimInlines inl
+
+inlines :: PandocMonad m => PodParser m Inlines
+inlines = mconcat <$> many1 (format <|> whitespace <|> str)
+
+-- perlpodspec sez:
+--   If a Pod processor sees any formatting code other than the ones listed,
+--   that processor must by default treat this as an error.
+format :: PandocMonad m => PodParser m Inlines
+format = try $ do
+  ctrl <- satisfy isAsciiUpper
+  p <- getPosition
+  lookAhead (char '<')
+  case ctrl of
+    'B' -> B.strong <$> argument
+    'C' -> B.code . stringify <$> argument
+    'F' -> B.spanWith (mempty, ["filename"], mempty) <$> argument
+    'I' -> B.emph <$> argument
+    'S' -> argument  -- TODO map nbsps
+    'X' -> argument $> mempty
+    'Z' -> argument $> mempty
+
+    'E' -> do
+      a <- stringify <$> argument
+      case entity a of
+             -- per spec:
+             --   Pod parsers, when faced with some unknown "E<identifier>" code,
+             --   shouldn't simply replace it with nullstring (by default, at
+             --   least), but may pass it through as a string consisting of the
+             --   literal characters E, less-than, identifier, greater-than.
+             Nothing -> do
+               logMessage $ SkippedContent ("unknown entity " <> a) p
+               return $ B.str $ "E<" <> a <> ">"
+             Just e -> return $ B.str e
+
+    'L' -> link
+
+    x -> throwError $ PandocParseError $ T.snoc "unknown Pod formatting code " x
+  where
+    argument = try expandedArg <|> compactArg <?> "argument"
+    innerStr =  B.str <$> many1Char (podCharLess ">")
+    compactArg = do
+      char '<'
+      mconcat <$> manyTill (format <|> whitespace <|> innerStr) (char '>')
+    expandedArg = do
+      openLen <- length <$> many1 (char '<')
+      let close = T.pack $ replicate openLen '>'
+      skipMany1 spaceChar <|> void blankline
+      arg <- mconcat <$> many (format <|> try (whitespace <* notFollowedBy (textStr close)) <|> str)
+      many1 spaceChar
+      textStr close
+      return arg
+    -- Some legacy entity names are required to be parsed by Pod formatters
+    oct = listToMaybe . readOct @Integer
+    entity "apos" = Just "'"
+    entity "sol" = Just "/"
+    entity "verbar" = Just "|"
+    entity "lchevron" = Just "«"
+    entity "rchevron" = Just "»"
+    entity (T.stripPrefix "0x" -> Just suf) = lookupEntity $ "#x" <> suf
+    entity (T.stripPrefix "0" -> Just suf)
+        | Just (n, "") <- oct (T.unpack suf) = lookupEntity $ "#" <> tshow n
+    entity (TR.decimal @Integer -> Right (x, "")) = lookupEntity $ "#" <> tshow x
+    -- named entities in Commonmark.Entity de facto have to be looked up with
+    -- the semicolon at the end. perlpodspec says arguments to E<> must be
+    -- alphanumeric, so an argument that already has a trailing semicolon
+    -- is bogus anyway, so just paste the semicolon on unconditionally.
+    entity x = lookupEntity (x <> ";")
+
+-- god knows there must be a higher order way of writing this thing, where we
+-- have multiple different possible parser states within the link argument
+-- varying depending on whether the link is expanded or not, but at least I
+-- understand what I've done. This would be less wacky with a lexing step.
+link :: PandocMonad m => PodParser m Inlines
+link = do
+  identifier <- textToIdentifier <$> getOption readerExtensions
+  (name, dest) <- try expandedLinkArg <|> compactLinkArg
+  return $ mkLink identifier name dest
+  where
+    compactLinkArg = do
+      char '<'
+      name <- linkName whitespace ">"
+      dest <- linkDest whitespace (char '>') ">"
+      char '>'
+      return (mconcat <$> name, dest)
+    expandedLinkArg = do
+      openLen <- length <$> many1 (char '<')
+      let closeStr = textStr (T.pack $ replicate openLen '>')
+      let close = skipMany1 spaceChar *> closeStr
+      let sp = try $ many1 spaceChar *> notFollowedBy closeStr $> B.space
+      many1 spaceChar
+      name <- linkName sp ""
+      dest <- linkDest sp close ""
+      close
+      return (mconcat <$> name, dest)
+    mkLink identifier name dest =
+      let name' = fromMaybe (defaultLinkName dest) name in
+          case dest of
+            LinkUrl _ href -> B.link href "" name'
+            LinkMan nm Nothing ->  B.linkWith (mempty, mempty, [("manual", stringify nm)]) "" "" name'
+            LinkMan nm (Just sc) -> B.linkWith (mempty, mempty, [("manual", stringify nm), ("section", stringify sc)]) "" "" name'
+            LinkInternal sc -> B.link ("#" <> identifier (stringify sc)) "" name'
+
+    linkName sp ex = optionMaybe $ try $ many
+        (try format
+         <|> sp
+         <|> B.str <$> many1Char (podCharLess ('|':ex))) <* char '|'
+    linkDest sp close ex = try (url ex) <|> internal sp close ex <|> man sp close ex
+    -- perlpodspec sez:
+    --    Note that you can distinguish URL-links from anything else by the
+    --    fact that they match m/\A\w+:[^:\s]\S*\z/.
+    -- This is obviously not an RFC-compliant matcher for a URI scheme, but
+    -- this is what the specification and the canonical implementation (Pod::Simple)
+    -- do for deciding that a link target "looks like" a URL, as opposed to a
+    -- manual page reference, so what we are doing here is roughly equivalent
+    -- even though it is nonsense
+    url ex = do
+      scheme <- many1Char (letter <|> digit <|> char '_')
+      colon <- T.singleton <$> char ':' <* notFollowedBy (char ':')
+      rst <- many (format <|> B.str <$> many1Char (podCharLess ex))
+      return $ LinkUrl
+                 (B.str scheme <> B.str colon <> mconcat rst)
+                 (scheme <> colon <> stringify rst)
+    quotedSection sp close ex = do
+      let mystr = B.str <$> many1Char (podCharLess ('\"':ex) <|> try (char '"' <* notFollowedBy close))
+      char '"'
+      ins <- mconcat <$> many1 (format <|> sp <|> mystr)
+      char '"'
+      return ins
+    section sp close ex = try (quotedSection sp close ex) <|> mconcat <$> many1 (format <|> sp <|> B.str <$> many1Char (podCharLess ex))
+    internal sp close ex = do
+      char '/'
+      LinkInternal <$> section sp close ex
+    notSlash sp ex = format <|> sp <|> B.str <$> many1Char (podCharLess ('/':ex))
+    man sp close ex = do
+      page <- mconcat <$> many (notSlash sp ex)
+      sec <- optionMaybe $ char '/' *> section sp close ex
+      return $ LinkMan page sec
+
+whitespace :: PandocMonad m => PodParser m Inlines
+whitespace = try $ do
+  many1 spaceChar *> optional newline <|> many spaceChar *> void newline
+  notFollowedBy blankline
+  return B.space
+
+podCharLess :: PandocMonad m => String -> PodParser m Char
+podCharLess exclude = try (satisfy isAsciiUpper <* notFollowedBy (char '<'))
+                <|> satisfy (\c -> not (isSpaceChar c || isAsciiUpper c || elem c exclude))
+
+podChar :: PandocMonad m => PodParser m Char
+podChar = try (satisfy isAsciiUpper <* notFollowedBy (char '<'))
+                <|> satisfy (\c -> not (isSpaceChar c || isAsciiUpper c))
+
+str :: PandocMonad m => PodParser m Inlines
+str = B.str <$> many1Char podChar
+
+nonEmptyLine :: PandocMonad m => PodParser m T.Text
+nonEmptyLine = try $ do
+  pre <- manyChar spaceChar
+  something <- T.singleton <$> nonspaceChar
+  post <- anyLineNewline
+  return $ pre <> something <> post
+
+verbatim :: PandocMonad m => PodParser m Blocks
+verbatim = do
+  start <- startVerbatimLine
+  lns <- many (nonEmptyLine <|>
+                     try (do b <- blanklines
+                             l <- startVerbatimLine
+                             return $ b <> l))
+  optional blanklines
+  return $ B.codeBlock $ mconcat $ start:lns
+  where
+    startVerbatimLine = many1Char spaceChar <> nonEmptyLine
+
+-- =begin/=end/=for and data paragraphs
+-- The =begin/=end (and single-paragraph =for variant) markers in Pod are
+-- designed as an extension point for specific formatters
+--
+-- this doesn't strictly match the intent of "=begin :ident" pod blocks, which
+-- are still meant to be processed specially by the formatter, and only land in
+-- the output upon request, i.e. pod2html will process "=begin :html" blocks as
+-- Pod and include them in the regular output. Since the regions contain Pod
+-- markup it seems to me that the best thing to do is parse the markup and put
+-- a classname on it, allowing users to respond as desired with filters.
+-- Pandoc doesn't have a built-in concept of parsed Divs that are only rendered
+-- to certain formats, just raw blocks.
+--
+-- perlpodspec allows nesting of =begin/=end regions but we currently don't
+-- because it would be annoying and we have something somewhat useful we
+-- can do with these blocks which is treat them as RawBlocks, which matches
+-- the intent reasonably well, and that gets weirder if we parse a nested
+-- structure. It seems unlikely this would be encountered in the wild.
+
+regionIdentifier :: PandocMonad m => PodParser m T.Text
+regionIdentifier = many1Char (alphaNum <|> oneOf "-_")
+
+for :: PandocMonad m => PodParser m Blocks
+for = do
+  string "for"
+  many1 spaceChar
+  forDiv <|> forData
+
+forDiv :: PandocMonad m => PodParser m Blocks
+forDiv = do
+  char ':'
+  cls <- regionIdentifier
+  many1 spaceChar
+  B.divWith (mempty, [cls], mempty) <$> paragraph
+
+forData :: PandocMonad m => PodParser m Blocks
+forData = do
+  fmt <- regionIdentifier
+  ln1 <- anyLineNewline
+  lns <- many nonEmptyLine
+  optional blanklines
+  return $ B.rawBlock fmt (T.concat (ln1 : lns))
+
+begin :: PandocMonad m => PodParser m Blocks
+begin = do
+  cmd "begin"
+  beginDiv <|> beginData
+
+beginDiv :: PandocMonad m => PodParser m Blocks
+beginDiv = do
+  char ':'
+  cls <- regionIdentifier
+  anyLine  -- "parameters" may appear in this position
+  blanklines
+  bs <- mconcat <$> many block
+  textStr ("=end :" <> cls) <* blanklines
+  return $ B.divWith (mempty, [cls], mempty) bs
+
+beginData :: PandocMonad m => PodParser m Blocks
+beginData = do
+  fmt <- regionIdentifier
+  anyLine
+  blanklines
+  lns <- mconcat <$> many (try rawCut <|> rawLine)
+  textStr ("=end " <> fmt) <* blanklines
+  return $ B.rawBlock fmt lns
+  where
+    rawCut = do
+      char '=' *> cut
+      pod <?> "=pod to close =cut within =begin/=end"
+      return mempty
+    rawLine = do
+      try (notFollowedBy (char '=' *> letter))
+      anyLineNewline
diff --git a/src/Text/Pandoc/Readers/Pptx.hs b/src/Text/Pandoc/Readers/Pptx.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Readers/Pptx.hs
@@ -0,0 +1,43 @@
+{-# LANGUAGE OverloadedStrings #-}
+{- |
+   Module      : Text.Pandoc.Readers.Pptx
+   Copyright   : © 2025 Anton Antic
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : Anton Antic <anton@everworker.ai>
+   Stability   : alpha
+   Portability : portable
+
+Conversion of PPTX (PowerPoint) documents to 'Pandoc' document.
+-}
+module Text.Pandoc.Readers.Pptx (readPptx) where
+
+import qualified Data.ByteString.Lazy as B
+import qualified Data.Text as T
+import Codec.Archive.Zip (toArchiveOrFail)
+import Control.Monad.Except (throwError)
+import Text.Pandoc.Class.PandocMonad (PandocMonad)
+import Text.Pandoc.Definition (Pandoc(..))
+import Text.Pandoc.Error (PandocError(..))
+import Text.Pandoc.Options (ReaderOptions)
+import Text.Pandoc.Readers.Pptx.Parse (archiveToPptx)
+import Text.Pandoc.Readers.Pptx.Slides (pptxToOutput)
+
+-- | Read PPTX file into Pandoc AST
+readPptx :: PandocMonad m => ReaderOptions -> B.ByteString -> m Pandoc
+readPptx opts bytes =
+  case toArchiveOrFail bytes of
+    Right archive ->
+      case archiveToPptx archive of
+        Right pptx -> do
+          -- Convert Pptx intermediate to Pandoc AST
+          (meta, blocks) <- pptxToOutput opts pptx
+          return $ Pandoc meta blocks
+
+        Left err ->
+          throwError $ PandocParseError $
+            "Failed to parse PPTX: " <> err
+
+    Left err ->
+      throwError $ PandocParseError $
+        "Failed to unpack PPTX archive: " <> T.pack err
diff --git a/src/Text/Pandoc/Readers/Pptx/Parse.hs b/src/Text/Pandoc/Readers/Pptx/Parse.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Readers/Pptx/Parse.hs
@@ -0,0 +1,216 @@
+{-# LANGUAGE OverloadedStrings #-}
+{- |
+   Module      : Text.Pandoc.Readers.Pptx.Parse
+   Copyright   : © 2025 Anton Antic
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : Anton Antic <anton@everworker.ai>
+   Stability   : alpha
+   Portability : portable
+
+Parsing of PPTX archive to intermediate representation.
+-}
+module Text.Pandoc.Readers.Pptx.Parse
+  ( Pptx(..)
+  , PresentationDoc(..)
+  , PptxSlide(..)
+  , SlideId(..)
+  , archiveToPptx
+  ) where
+
+import Codec.Archive.Zip (Archive, Entry, findEntryByPath, fromEntry)
+import qualified Data.ByteString.Lazy as B
+import Data.List (find)
+import Data.Maybe (mapMaybe)
+import qualified Data.Text as T
+import qualified Data.Text.Lazy.Encoding as TL
+import Data.Text (Text)
+import System.FilePath (splitFileName)
+import Text.Pandoc.Readers.OOXML.Shared
+import Text.Pandoc.XML.Light
+import Text.Read (readMaybe)
+
+-- | Slide identifier
+newtype SlideId = SlideId Int deriving (Show, Eq, Ord)
+
+-- | Complete PPTX document (intermediate representation)
+data Pptx = Pptx
+  { pptxPresentation :: PresentationDoc
+  , pptxSlides       :: [PptxSlide]
+  , pptxArchive      :: Archive
+  } deriving (Show)
+
+-- | Individual slide data
+data PptxSlide = PptxSlide
+  { slideId      :: SlideId
+  , slidePath    :: FilePath
+  , slideElement :: Element     -- The parsed p:sld element
+  , slideRels    :: [(Text, Text)]  -- Slide relationships
+  } deriving (Show)
+
+-- | Presentation-level information from presentation.xml
+data PresentationDoc = PresentationDoc
+  { presNameSpaces   :: NameSpaces
+  , presSlideSize    :: (Integer, Integer)  -- (width, height) in pixels
+  , presSlideIds     :: [(SlideId, Text)]   -- (slideId, relationshipId)
+  } deriving (Show)
+
+-- | Parse PPTX archive to intermediate representation
+archiveToPptx :: Archive -> Either Text Pptx
+archiveToPptx archive = do
+  -- Find and parse presentation.xml
+  presPath <- getPresentationXmlPath archive
+  presElem <- loadXMLFromArchive archive presPath
+  presDoc <- elemToPresentation presElem
+
+  -- Load presentation relationships to resolve slide paths
+  presRelsPath <- getPresentationRelsPath archive presPath
+  presRels <- loadRelationships archive presRelsPath
+
+  -- Parse each slide
+  slides <- mapM (parseSlide archive presRels) (presSlideIds presDoc)
+
+  return $ Pptx presDoc slides archive
+
+-- | Find presentation.xml via root relationships
+getPresentationXmlPath :: Archive -> Either Text FilePath
+getPresentationXmlPath archive = do
+  -- Load _rels/.rels
+  relsEntry <- maybeToEither "Missing _rels/.rels" $
+               findEntryByPath "_rels/.rels" archive
+
+  relsElem <- parseXMLFromEntry relsEntry
+
+  -- The Relationships element has a default namespace, but Relationship children don't use prefix
+  -- We need to look at all children regardless of namespace
+  let relElems = onlyElems $ elContent relsElem
+
+  -- Look for relationship containing "officeDocument" in Type attribute
+  case find isOfficeDocRel relElems of
+    Nothing -> Left $ "No presentation.xml relationship found. Found " <>
+                     T.pack (show (length relElems)) <> " relationships."
+    Just rel -> do
+      target <- maybeToEither "Missing Target attribute" $
+                findAttr (unqual "Target") rel
+      return $ T.unpack target  -- Convert Text to FilePath
+
+  where
+    isOfficeDocRel el =
+      case findAttr (unqual "Type") el of
+        -- Must end with "/officeDocument" to avoid matching "/extended-properties"
+        Just relType -> "/officeDocument" `T.isSuffixOf` relType
+        Nothing -> False
+
+-- | Load and parse XML from archive entry
+loadXMLFromArchive :: Archive -> FilePath -> Either Text Element
+loadXMLFromArchive archive path = do
+  entry <- maybeToEither ("Entry not found: " <> T.pack path) $
+           findEntryByPath path archive
+
+  let xmlBytes = fromEntry entry
+  parseXMLFromBS xmlBytes
+
+-- | Parse XML from ByteString
+parseXMLFromBS :: B.ByteString -> Either Text Element
+parseXMLFromBS = parseXMLElement . TL.decodeUtf8
+
+-- | Parse XML from Entry
+parseXMLFromEntry :: Entry -> Either Text Element
+parseXMLFromEntry = parseXMLFromBS . fromEntry
+
+-- | Parse presentation.xml element to PresentationDoc
+elemToPresentation :: Element -> Either Text PresentationDoc
+elemToPresentation presElem = do
+  let ns = elemToNameSpaces presElem
+
+  -- Extract slide size (with defaults)
+  let sizeElem = findChildByName ns "p" "sldSz" presElem
+      (widthEMU, heightEMU) = case sizeElem of
+        Just el ->
+          let cx = readAttrInt "cx" el
+              cy = readAttrInt "cy" el
+           in (cx, cy)
+        Nothing -> (9144000, 6858000)  -- Default 10" x 7.5"
+
+  -- Convert EMUs to pixels (approximate for metadata)
+  let width = widthEMU `div` emusPerInch
+      height = heightEMU `div` emusPerInch
+
+  -- Extract slide ID list (optional - some presentations may have no slides)
+  let sldIdLstElem = findChildByName ns "p" "sldIdLst" presElem
+
+  slideRefs <- case sldIdLstElem of
+    Nothing -> return []  -- No slides is valid for templates/masters-only presentations
+    Just el -> do
+      let sldIdElems = findChildren (elemName ns "p" "sldId") el
+      mapM (extractSlideRef ns) (zip [1..] sldIdElems)
+
+  return $ PresentationDoc
+    { presNameSpaces = ns
+    , presSlideSize = (width, height)
+    , presSlideIds = slideRefs
+    }
+
+-- | Extract slide ID and relationship ID from p:sldId element
+extractSlideRef :: NameSpaces -> (Int, Element) -> Either Text (SlideId, Text)
+extractSlideRef ns (idx, sldIdElem) = do
+  relId <- maybeToEither ("Missing r:id in slide " <> T.pack (show idx)) $
+           findAttrByName ns "r" "id" sldIdElem
+
+  return (SlideId idx, relId)
+
+-- | Safe read attribute as Integer (with default of 0)
+readAttrInt :: Text -> Element -> Integer
+readAttrInt attrName el =
+  case findAttr (unqual attrName) el of
+    Just str -> case readMaybe (T.unpack str) of
+      Just n -> n
+      Nothing -> 0
+    Nothing -> 0
+
+-- | Get presentation relationships path
+getPresentationRelsPath :: Archive -> FilePath -> Either Text FilePath
+getPresentationRelsPath _archive presPath =
+  -- ppt/presentation.xml → ppt/_rels/presentation.xml.rels
+  let (dir, file) = splitFileName presPath
+      relsPath = dir ++ "/_rels/" ++ file ++ ".rels"
+   in Right relsPath
+
+-- | Load relationships from .rels file
+loadRelationships :: Archive -> FilePath -> Either Text [(Text, Text)]
+loadRelationships archive relsPath =
+  case findEntryByPath relsPath archive of
+    Nothing -> Right []  -- No relationships is OK
+    Just entry -> do
+      relsElem <- parseXMLFromEntry entry
+      let relElems = onlyElems $ elContent relsElem
+      return $ mapMaybe extractRelationship relElems
+  where
+    extractRelationship el = do
+      relId <- findAttr (unqual "Id") el
+      target <- findAttr (unqual "Target") el
+      return (relId, target)
+
+-- | Parse a single slide
+parseSlide :: Archive -> [(Text, Text)] -> (SlideId, Text) -> Either Text PptxSlide
+parseSlide archive rels (sid, relId) = do
+  -- Resolve relationship to get slide path
+  target <- maybeToEither ("Relationship not found: " <> relId) $
+            lookup relId rels
+
+  -- Resolve relative path: ppt/slides/slide1.xml
+  let slidePath' = "ppt/" <> T.unpack target
+
+  -- Load and parse slide XML
+  slideElem <- loadXMLFromArchive archive slidePath'
+
+  -- Load slide-specific relationships
+  slideRelsPath <- getPresentationRelsPath archive slidePath'
+  slideRels' <- loadRelationships archive slideRelsPath
+
+  return $ PptxSlide sid slidePath' slideElem slideRels'
+
+-- | Helper: Maybe a -> Either Text a
+maybeToEither :: Text -> Maybe a -> Either Text a
+maybeToEither err Nothing = Left err
+maybeToEither _ (Just x) = Right x
diff --git a/src/Text/Pandoc/Readers/Pptx/Shapes.hs b/src/Text/Pandoc/Readers/Pptx/Shapes.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Readers/Pptx/Shapes.hs
@@ -0,0 +1,330 @@
+{-# LANGUAGE OverloadedStrings #-}
+{-# OPTIONS_GHC -Wno-partial-fields #-}
+{- |
+   Module      : Text.Pandoc.Readers.Pptx.Shapes
+   Copyright   : © 2025 Anton Antic
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : Anton Antic <anton@everworker.ai>
+   Stability   : alpha
+   Portability : portable
+
+Parsing of PPTX shapes (text boxes, images, tables, diagrams).
+-}
+module Text.Pandoc.Readers.Pptx.Shapes
+  ( PptxShape(..)
+  , PptxParagraph(..)
+  , BulletType(..)
+  , parseShapes
+  , parseShape
+  , shapeToBlocks
+  , isTitlePlaceholder
+  , extractDrawingMLText
+  ) where
+
+import Codec.Archive.Zip (Archive, findEntryByPath, fromEntry)
+import qualified Data.ByteString.Lazy as B
+import Data.List (find, groupBy)
+import Data.Maybe (mapMaybe)
+import qualified Data.Text as T
+import Data.Text (Text)
+import Text.Read (readMaybe)
+import Text.Pandoc.Class.PandocMonad (PandocMonad)
+import qualified Text.Pandoc.Class.PandocMonad as P
+import Text.Pandoc.Definition
+import Text.Pandoc.Readers.OOXML.Shared
+import Text.Pandoc.Readers.Pptx.SmartArt
+import Text.Pandoc.XML.Light
+
+-- | Paragraph with bullet/numbering information
+data PptxParagraph = PptxParagraph
+  { paraLevel   :: Int            -- Bullet level (0, 1, 2...)
+  , paraBullet  :: BulletType
+  , paraText    :: Text
+  } deriving (Show)
+
+-- | Bullet type
+data BulletType
+  = NoBullet
+  | Bullet                        -- Has bullet (character detected or implicit)
+  | WingdingsBullet              -- Detected via Wingdings symbol
+  deriving (Show, Eq)
+
+-- | Shape types in PPTX slides
+data PptxShape
+  = PptxTextBox [PptxParagraph]         -- Parsed paragraphs with bullet info
+  | PptxPicture
+      { picRelId  :: Text               -- Relationship ID (lazy loading)
+      , picTitle  :: Text
+      , picAlt    :: Text
+      }
+  | PptxTable [[Text]]                  -- Simple text cells for now
+  | PptxDiagramRef
+      { dgmDataRelId   :: Text          -- Relationship to data.xml
+      , dgmLayoutRelId :: Text          -- Relationship to layout.xml
+      }
+  | PptxGraphic Text                    -- Placeholder for other graphics
+  deriving (Show)
+
+-- | Parse all shapes from shape tree
+parseShapes :: NameSpaces -> Element -> [PptxShape]
+parseShapes ns spTreeElem =
+  let shapeElems = onlyElems $ elContent spTreeElem
+      -- Merge parent namespaces with element namespaces
+      ns' = ns <> elemToNameSpaces spTreeElem
+   in mapMaybe (parseShape ns') shapeElems
+
+-- | Parse individual shape element
+parseShape :: NameSpaces -> Element -> Maybe PptxShape
+parseShape ns el
+  -- Text box: <p:sp> with <p:txBody>
+  | isElem ns "p" "sp" el =
+      case findChildByName ns "p" "txBody" el of
+        Just txBody ->
+          let paras = parseParagraphs ns txBody
+           in if null paras
+              then Nothing
+              else Just $ PptxTextBox paras
+        Nothing -> Nothing
+
+  -- Picture: <p:pic>
+  | isElem ns "p" "pic" el = do
+      nvPicPr <- findChildByName ns "p" "nvPicPr" el
+      cNvPr <- findChildByName ns "p" "cNvPr" nvPicPr
+
+      let title = maybe "" id $ findAttr (unqual "name") cNvPr
+          alt = maybe "" id $ findAttr (unqual "descr") cNvPr
+
+      -- Get blip relationship ID
+      blipFill <- findChildByName ns "p" "blipFill" el
+      blip <- findChildByName ns "a" "blip" blipFill
+      relId <- findAttrByName ns "r" "embed" blip
+
+      return $ PptxPicture relId title alt
+
+  -- GraphicFrame: table or diagram
+  | isElem ns "p" "graphicFrame" el =
+      case findChildByName ns "a" "graphic" el >>=
+           findChildByName ns "a" "graphicData" of
+        Nothing -> Nothing
+        Just graphicData ->
+          case findAttr (unqual "uri") graphicData of
+            Nothing -> Just $ PptxGraphic "no-uri"
+            Just uri ->
+              if "table" `T.isInfixOf` uri
+                then
+                  -- Table
+                  case findChildByName ns "a" "tbl" graphicData of
+                    Just tbl ->
+                      let rows = parseTableRows ns tbl
+                       in Just $ PptxTable rows
+                    Nothing -> Nothing
+                else if "diagram" `T.isInfixOf` uri
+                  then
+                    -- SmartArt diagram - dgm namespace is declared inline on relIds element
+                    let dgmRelIds = find (\e -> qName (elName e) == "relIds") (elChildren graphicData)
+                     in case dgmRelIds of
+                          Nothing -> Just $ PptxGraphic "diagram-no-relIds"
+                          Just relIdsElem ->
+                            -- Get r:dm and r:lo attributes (r namespace is in parent)
+                            let ns' = ns <> elemToNameSpaces relIdsElem
+                             in case (findAttrByName ns' "r" "dm" relIdsElem,
+                                      findAttrByName ns' "r" "lo" relIdsElem) of
+                                  (Just dataRelId, Just layoutRelId) ->
+                                    Just $ PptxDiagramRef dataRelId layoutRelId
+                                  _ -> Just $ PptxGraphic "diagram-missing-rels"
+                  else
+                    -- Other graphic (chart, etc.)
+                    Just $ PptxGraphic ("other: " <> uri)
+
+  -- Skip other shapes for now
+  | otherwise = Nothing
+
+-- | Parse table rows (simple text extraction)
+parseTableRows :: NameSpaces -> Element -> [[Text]]
+parseTableRows ns tblElem =
+  let trElems = findChildrenByName ns "a" "tr" tblElem
+   in map (parseTableRow ns) trElems
+
+parseTableRow :: NameSpaces -> Element -> [Text]
+parseTableRow ns trElem =
+  let tcElems = findChildrenByName ns "a" "tc" trElem
+   in map extractCellText tcElems
+  where
+    extractCellText tcElem =
+      -- Get text from txBody/a:p/a:r/a:t
+      case findChildByName ns "a" "txBody" tcElem of
+        Just txBody -> extractDrawingMLText txBody
+        Nothing -> ""
+
+-- | Convert shape to Pandoc blocks
+shapeToBlocks :: PandocMonad m => Archive -> [(Text, Text)] -> PptxShape -> m [Block]
+shapeToBlocks _archive _rels (PptxTextBox paras) =
+  return $ paragraphsToBlocks paras
+shapeToBlocks archive rels (PptxPicture relId title alt) = do
+  -- Resolve relationship to get media path
+  case lookup relId rels of
+    Nothing -> return []  -- Image not found
+    Just target -> do
+      let mediaPath = resolveMediaPath target
+
+      -- Load image bytes and add to MediaBag
+      case loadMediaFromArchive archive mediaPath of
+        Nothing -> return []
+        Just mediaBytes -> do
+          P.insertMedia (T.unpack mediaPath) Nothing mediaBytes
+
+          let altText = if T.null alt then [] else [Str alt]
+          return [Para [Image nullAttr altText (mediaPath, title)]]
+
+shapeToBlocks _archive _rels (PptxTable rows) =
+  -- Simple table representation for now
+  case rows of
+    [] -> return []
+    (headerRow:bodyRows) -> do
+      let makeCell text = Cell nullAttr AlignDefault (RowSpan 1) (ColSpan 1) [Plain [Str text]]
+          headerCells = map makeCell headerRow
+          bodyCells = map (map makeCell) bodyRows
+          caption = Caption Nothing []
+          colSpec = replicate (length headerRow) (AlignDefault, ColWidthDefault)
+          headerRow' = Row nullAttr headerCells
+          bodyRows' = map (Row nullAttr) bodyCells
+          thead = TableHead nullAttr [headerRow']
+          tbody = [TableBody nullAttr 0 [] bodyRows']
+          tfoot = TableFoot nullAttr []
+      return [Table nullAttr caption colSpec thead tbody tfoot]
+
+shapeToBlocks archive rels (PptxDiagramRef dataRelId layoutRelId) = do
+  -- Parse SmartArt diagram
+  case parseDiagram archive rels dataRelId layoutRelId of
+    Left err -> do
+      -- Failed to parse diagram, return placeholder
+      return [Para [Str $ "[Diagram parse error: " <> err <> "]"]]
+    Right diagram ->
+      return $ diagramToBlocks diagram
+shapeToBlocks _archive _rels (PptxGraphic text) =
+  -- Placeholder for other graphics (charts, etc.)
+  return [Para [Str $ "[Graphic: " <> text <> "]"]]
+
+-- | Resolve media path (handle relative paths)
+resolveMediaPath :: Text -> Text
+resolveMediaPath target =
+  if "../media/" `T.isPrefixOf` target
+    then "ppt/media/" <> T.drop 9 target  -- "../media/" = 9 chars
+    else if "media/" `T.isPrefixOf` target
+      then "ppt/" <> target
+      else target
+
+-- | Load media file from archive
+loadMediaFromArchive :: Archive -> Text -> Maybe B.ByteString
+loadMediaFromArchive archive path =
+  case findEntryByPath (T.unpack path) archive of
+    Just entry -> Just $ fromEntry entry
+    Nothing -> Nothing
+
+-- | Parse paragraphs from text box
+parseParagraphs :: NameSpaces -> Element -> [PptxParagraph]
+parseParagraphs ns txBody =
+  let pElems = findChildrenByName ns "a" "p" txBody
+   in map (parseParagraph ns) pElems
+
+-- | Parse individual paragraph
+parseParagraph :: NameSpaces -> Element -> PptxParagraph
+parseParagraph ns pElem =
+  let level = parseBulletLevel ns pElem
+      bullet = detectBulletType ns pElem
+      text = extractParagraphText ns pElem
+   in PptxParagraph level bullet text
+
+-- | Parse bullet level from paragraph properties
+parseBulletLevel :: NameSpaces -> Element -> Int
+parseBulletLevel ns pElem =
+  case findChildByName ns "a" "pPr" pElem >>=
+       findAttr (unqual "lvl") >>=
+       (\s -> readMaybe (T.unpack s) :: Maybe Int) of
+    Just lvl -> lvl
+    Nothing -> 0  -- Default to level 0
+
+-- | Detect bullet type
+detectBulletType :: NameSpaces -> Element -> BulletType
+detectBulletType ns pElem =
+  -- Check for explicit <a:pPr><a:buChar>
+  case findChildByName ns "a" "pPr" pElem >>=
+       findChildByName ns "a" "buChar" of
+    Just _buCharElem -> Bullet
+    Nothing ->
+      -- Check for Wingdings symbol (common in PowerPoint)
+      if hasWingdingsSymbol ns pElem
+        then WingdingsBullet
+        else NoBullet
+
+-- | Check if paragraph starts with Wingdings symbol
+hasWingdingsSymbol :: NameSpaces -> Element -> Bool
+hasWingdingsSymbol ns pElem =
+  let runs = findChildrenByName ns "a" "r" pElem
+      checkRun r = case findChildByName ns "a" "rPr" r >>=
+                        findChildByName ns "a" "sym" of
+                     Just symElem ->
+                       case findAttr (unqual "typeface") symElem of
+                         Just typeface -> "Wingdings" `T.isInfixOf` typeface
+                         Nothing -> False
+                     Nothing -> False
+   in any checkRun runs
+
+-- | Extract text from paragraph
+extractParagraphText :: NameSpaces -> Element -> Text
+extractParagraphText _ns pElem =
+  -- Find all <a:t> elements and concatenate
+  let textElems = filterElementsName (\qn -> qName qn == "t") pElem
+      texts = map strContent textElems
+   in T.unwords $ filter (not . T.null) texts
+
+-- | Extract text from DrawingML element (finds all <a:t> descendants)
+extractDrawingMLText :: Element -> Text
+extractDrawingMLText el =
+  let textElems = filterElementsName (\qn -> qName qn == "t") el
+      texts = map strContent textElems
+   in T.unwords $ filter (not . T.null) texts
+
+-- | Convert paragraphs to blocks, grouping bullets into lists
+paragraphsToBlocks :: [PptxParagraph] -> [Block]
+paragraphsToBlocks paras =
+  -- If we have multiple paragraphs with bullets, group them
+  let hasBullets = any (\p -> paraBullet p /= NoBullet) paras
+   in if hasBullets
+      then groupBulletParagraphs paras
+      else map (\p -> Para [Str $ paraText p]) paras
+
+-- | Group bullet paragraphs into lists
+groupBulletParagraphs :: [PptxParagraph] -> [Block]
+groupBulletParagraphs paras =
+  let grouped = groupBy sameBulletLevel paras
+   in concatMap groupToBlock grouped
+  where
+    sameBulletLevel p1 p2 =
+      (paraBullet p1 /= NoBullet) &&
+      (paraBullet p2 /= NoBullet) &&
+      (paraLevel p1 == paraLevel p2)
+
+    groupToBlock :: [PptxParagraph] -> [Block]
+    groupToBlock [] = []
+    groupToBlock ps@(p:_)
+      | paraBullet p /= NoBullet =
+          -- Bullet list
+          let items = map (\para -> [Plain [Str $ paraText para]]) ps
+           in [BulletList items]
+      | otherwise =
+          -- Plain paragraph
+          map (\para -> Para [Str $ paraText para]) ps
+
+-- | Check if shape is title placeholder (also used in Slides module)
+isTitlePlaceholder :: NameSpaces -> Element -> Bool
+isTitlePlaceholder ns el =
+  case findChildByName ns "p" "nvSpPr" el >>=
+       findChildByName ns "p" "nvPr" >>=
+       findChildByName ns "p" "ph" of
+    Just phElem ->
+      case findAttr (unqual "type") phElem of
+        Just phType -> phType == "title" || phType == "ctrTitle"
+        Nothing -> False
+    Nothing -> False
diff --git a/src/Text/Pandoc/Readers/Pptx/Slides.hs b/src/Text/Pandoc/Readers/Pptx/Slides.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Readers/Pptx/Slides.hs
@@ -0,0 +1,83 @@
+{-# LANGUAGE OverloadedStrings #-}
+{- |
+   Module      : Text.Pandoc.Readers.Pptx.Slides
+   Copyright   : © 2025 Anton Antic
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : Anton Antic <anton@everworker.ai>
+   Stability   : alpha
+   Portability : portable
+
+Conversion of PPTX slides to Pandoc AST blocks.
+-}
+module Text.Pandoc.Readers.Pptx.Slides
+  ( pptxToOutput
+  ) where
+
+import Codec.Archive.Zip (Archive)
+import Data.List (find)
+import Data.Maybe (mapMaybe)
+import qualified Data.Text as T
+import Data.Text (Text)
+import Text.Pandoc.Class.PandocMonad (PandocMonad)
+import Text.Pandoc.Definition
+import Text.Pandoc.Options (ReaderOptions)
+import Text.Pandoc.Readers.OOXML.Shared
+import Text.Pandoc.Readers.Pptx.Parse
+import Text.Pandoc.Readers.Pptx.Shapes
+import Text.Pandoc.XML.Light
+
+-- | Convert Pptx intermediate representation to Pandoc AST
+pptxToOutput :: PandocMonad m => ReaderOptions -> Pptx -> m (Meta, [Block])
+pptxToOutput _opts pptx = do
+  let slides = pptxSlides pptx
+      archive = pptxArchive pptx
+
+  -- Convert each slide to blocks
+  slideBlocks <- concat <$> mapM (slideToBlocks archive) slides
+
+  return (mempty, slideBlocks)
+
+-- | Convert slide to blocks
+slideToBlocks :: PandocMonad m => Archive -> PptxSlide -> m [Block]
+slideToBlocks archive slide = do
+  let SlideId n = slideId slide
+      slideElem = slideElement slide
+      rels = slideRels slide
+      ns = elemToNameSpaces slideElem
+
+      -- Extract title from title placeholder
+      title = extractSlideTitle ns slideElem
+
+      -- Create header
+      slideIdent = "slide-" <> T.pack (show n)
+      headerText = if T.null title
+                   then "Slide " <> T.pack (show n)
+                   else title
+      header = Header 2 (slideIdent, [], []) [Str headerText]
+
+  -- Parse shapes and convert to blocks
+  case findChildByName ns "p" "cSld" slideElem >>=
+       findChildByName ns "p" "spTree" of
+    Nothing -> return [header]
+    Just spTree -> do
+      -- Filter out title placeholder shapes before parsing
+      let allShapeElems = onlyElems $ elContent spTree
+          nonTitleShapeElems = filter (not . isTitlePlaceholder ns) allShapeElems
+          shapes = mapMaybe (parseShape ns) nonTitleShapeElems
+      shapeBlocks <- concat <$> mapM (shapeToBlocks archive rels) shapes
+      return $ header : shapeBlocks
+
+-- | Extract title from title placeholder
+extractSlideTitle :: NameSpaces -> Element -> Text
+extractSlideTitle ns slideElem =
+  case findChildByName ns "p" "cSld" slideElem >>=
+       findChildByName ns "p" "spTree" of
+    Nothing -> ""
+    Just spTree ->
+      -- Find shape with ph type="title"
+      let shapes = onlyElems $ elContent spTree
+          titleShape = find (isTitlePlaceholder ns) shapes
+       in maybe "" extractDrawingMLText titleShape
+
+-- isTitlePlaceholder is imported from Shapes module
diff --git a/src/Text/Pandoc/Readers/Pptx/SmartArt.hs b/src/Text/Pandoc/Readers/Pptx/SmartArt.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Readers/Pptx/SmartArt.hs
@@ -0,0 +1,220 @@
+{-# LANGUAGE OverloadedStrings #-}
+{- |
+   Module      : Text.Pandoc.Readers.Pptx.SmartArt
+   Copyright   : © 2025 Anton Antic
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : Anton Antic <anton@everworker.ai>
+   Stability   : alpha
+   Portability : portable
+
+SmartArt diagram parsing and text extraction for PPTX.
+-}
+module Text.Pandoc.Readers.Pptx.SmartArt
+  ( PptxDiagram(..)
+  , parseDiagram
+  , diagramToBlocks
+  ) where
+
+import Codec.Archive.Zip (Archive, findEntryByPath, fromEntry)
+import qualified Data.Map.Strict as M
+import Data.Maybe (mapMaybe)
+import qualified Data.Text as T
+import qualified Data.Text.Lazy.Encoding as TL
+import Data.Text (Text)
+import Text.Pandoc.Definition
+import Text.Pandoc.Readers.OOXML.Shared
+import Text.Pandoc.XML.Light
+
+-- | SmartArt diagram data
+data PptxDiagram = PptxDiagram
+  { diagramType :: Text               -- Layout type (chevron, cycle, etc.)
+  , diagramNodes :: [(Text, [Text])]  -- (nodeText, childTexts)
+  } deriving (Show)
+
+-- | Parse SmartArt diagram from relationship IDs
+parseDiagram :: Archive
+             -> [(Text, Text)]  -- Slide relationships
+             -> Text            -- data relationship ID
+             -> Text            -- layout relationship ID
+             -> Either Text PptxDiagram
+parseDiagram archive rels dataRelId layoutRelId = do
+  -- Resolve relationships to file paths
+  dataTarget <- maybeToEither ("Relationship not found: " <> dataRelId) $
+                lookup dataRelId rels
+  layoutTarget <- maybeToEither ("Relationship not found: " <> layoutRelId) $
+                  lookup layoutRelId rels
+
+  -- Resolve relative paths (diagrams are in ../diagrams/ from slides/)
+  let dataPath = resolveDiagramPath dataTarget
+      layoutPath = resolveDiagramPath layoutTarget
+
+  -- Load XML files
+  dataElem <- loadXMLFromArchive archive dataPath
+  layoutElem <- loadXMLFromArchive archive layoutPath
+
+  -- Extract layout type
+  layoutType <- extractLayoutType layoutElem
+
+  -- Extract text nodes with hierarchy
+  nodes <- extractDiagramNodes dataElem
+
+  return $ PptxDiagram layoutType nodes
+
+-- | Resolve diagram path (handle ../diagrams/ relative paths)
+resolveDiagramPath :: Text -> FilePath
+resolveDiagramPath target =
+  if "../diagrams/" `T.isPrefixOf` target
+    then "ppt/diagrams/" ++ T.unpack (T.drop 12 target)  -- "../diagrams/" = 12 chars
+    else T.unpack target
+
+-- | Load XML from archive
+loadXMLFromArchive :: Archive -> FilePath -> Either Text Element
+loadXMLFromArchive archive path =
+  case findEntryByPath path archive of
+    Nothing -> Left $ "File not found in archive: " <> T.pack path
+    Just entry ->
+      let xmlBytes = fromEntry entry
+          lazyText = TL.decodeUtf8 xmlBytes
+       in parseXMLElement lazyText
+
+-- | Extract layout type from layout XML
+extractLayoutType :: Element -> Either Text Text
+extractLayoutType layoutElem = do
+  -- Look for uniqueId attribute: "urn:.../layout/chevron2"
+  case findAttr (unqual "uniqueId") layoutElem of
+    Just uid ->
+      -- Extract last part after last /
+      let layoutName = T.takeWhileEnd (/= '/') uid
+       in Right layoutName
+    Nothing ->
+      -- Fallback: look for title
+      case findChildByName ns "dgm" "title" layoutElem >>=
+           findAttr (unqual "val") of
+        Just title -> Right title
+        Nothing -> Right "unknown"
+  where
+    ns = elemToNameSpaces layoutElem
+
+-- | Extract text nodes from diagram data
+extractDiagramNodes :: Element -> Either Text [(Text, [Text])]
+extractDiagramNodes dataElem = do
+  let ns = elemToNameSpaces dataElem
+
+  -- Find point list
+  ptLst <- maybeToEither "Missing dgm:ptLst" $
+           findChildByName ns "dgm" "ptLst" dataElem
+
+  let ptElems = findChildrenByName ns "dgm" "pt" ptLst
+
+  -- Build node map: modelId → text
+  let nodeMap = M.fromList $ mapMaybe (extractNodeText ns) ptElems
+
+  -- Parse connections
+  let cxnLst = findChildByName ns "dgm" "cxnLst" dataElem
+      connections = maybe [] (parseConnections ns) cxnLst
+
+  -- Build parent-child map
+  let parentMap = buildParentMap connections
+
+  -- Find parent nodes (nodes that have children)
+  let parentIds = M.keys parentMap
+
+  -- Build hierarchy - only show nodes that are parents
+  -- (children are shown under their parents)
+  let hierarchy = map (buildNodeWithChildren nodeMap parentMap) parentIds
+      -- Filter out nodes with empty text (presentation nodes)
+      validHierarchy = filter (\(nodeText, _) -> not $ T.null nodeText) hierarchy
+
+  return validHierarchy
+
+-- | Extract text from a point element (returns Nothing if no text)
+extractNodeText :: NameSpaces -> Element -> Maybe (Text, Text)
+extractNodeText ns ptElem = do
+  modelId <- findAttr (unqual "modelId") ptElem
+
+  -- Extract text from dgm:t element (which contains a:p/a:r/a:t)
+  let text = case findChildByName ns "dgm" "t" ptElem of
+        Just tElem ->
+          -- Recursively get ALL text content from all descendants
+          getAllText tElem
+        Nothing -> ""
+
+  -- Only return nodes with actual text
+  if T.null (T.strip text)
+    then Nothing
+    else return (modelId, text)
+
+-- | Connection between nodes
+data Connection = Connection
+  { connType :: Text
+  , connSrc  :: Text
+  , connDest :: Text
+  } deriving (Show)
+
+-- | Parse connections
+parseConnections :: NameSpaces -> Element -> [Connection]
+parseConnections ns cxnLst =
+  let cxnElems = findChildrenByName ns "dgm" "cxn" cxnLst
+   in mapMaybe (parseConnection ns) cxnElems
+
+parseConnection :: NameSpaces -> Element -> Maybe Connection
+parseConnection _ns cxnElem = do
+  let cxnType = maybe "" id $ findAttr (unqual "type") cxnElem  -- Empty if no type
+  srcId <- findAttr (unqual "srcId") cxnElem
+  destId <- findAttr (unqual "destId") cxnElem
+  return $ Connection cxnType srcId destId
+
+-- | Build parent-child map from connections
+-- Use connections WITHOUT a type attribute (these are the data hierarchy)
+buildParentMap :: [Connection] -> M.Map Text [Text]
+buildParentMap connections =
+  let dataConnections = filter (\c -> T.null (connType c)) connections
+   in foldr addConn M.empty dataConnections
+  where
+    addConn conn m = M.insertWith (++) (connSrc conn) [connDest conn] m
+
+-- | Build node with its children
+buildNodeWithChildren :: M.Map Text Text -> M.Map Text [Text] -> Text -> (Text, [Text])
+buildNodeWithChildren nodeMap parentMap nodeId =
+  let nodeText = M.findWithDefault "" nodeId nodeMap
+      childIds = M.findWithDefault [] nodeId parentMap
+      -- Only include children that have text
+      childTexts = filter (not . T.null) $
+                   map (\cid -> M.findWithDefault "" cid nodeMap) childIds
+   in (nodeText, childTexts)
+
+-- | Convert diagram to Pandoc blocks
+diagramToBlocks :: PptxDiagram -> [Block]
+diagramToBlocks diagram =
+  let nodes = diagramNodes diagram
+      layoutType = diagramType diagram
+
+      -- Build content blocks
+      contentBlocks = concatMap nodeToBlocks nodes
+
+   in [Div ("", ["smartart", layoutType], [("layout", layoutType)])
+           contentBlocks]
+
+-- | Convert node to blocks
+nodeToBlocks :: (Text, [Text]) -> [Block]
+nodeToBlocks (nodeText, childTexts) =
+  if null childTexts
+    then [Para [Strong [Str nodeText]]]
+    else [ Para [Strong [Str nodeText]]
+         , BulletList [[Plain [Str child]] | child <- childTexts]
+         ]
+
+-- | Recursively extract all text from an element and its descendants
+getAllText :: Element -> Text
+getAllText el =
+  let textFromContent (Text cdata) = cdData cdata
+      textFromContent (Elem e) = getAllText e
+      textFromContent _ = ""
+      texts = map textFromContent (elContent el)
+   in T.unwords $ filter (not . T.null) texts
+
+-- Helper functions
+maybeToEither :: Text -> Maybe a -> Either Text a
+maybeToEither err Nothing = Left err
+maybeToEither _ (Just x) = Right x
diff --git a/src/Text/Pandoc/Readers/RIS.hs b/src/Text/Pandoc/Readers/RIS.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Readers/RIS.hs
@@ -0,0 +1,256 @@
+{-# LANGUAGE OverloadedStrings #-}
+{- |
+   Module      : Text.Pandoc.Readers.RIS
+   Copyright   : Copyright (C) 2022-2024 John MacFarlane
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : John MacFarlane <jgm@berkeley.edu>
+   Stability   : alpha
+   Portability : portable
+
+Parses RIS bibliographies into a Pandoc document
+with empty body and `references` and `nocite` fields
+in the metadata.  A wildcard `nocite` is used so that
+if the document is rendered in another format, the
+entire bibliography will be printed.
+-}
+module Text.Pandoc.Readers.RIS
+  ( readRIS
+  )
+where
+
+import Text.Pandoc.Options
+import Text.Pandoc.Definition
+import Text.Pandoc.Parsing
+import Data.Char (isAsciiUpper, isDigit, isSpace, ord, chr)
+import qualified Data.List as L
+import Citeproc (Reference(..), ItemId(..), Val(..), Date(..), DateParts(..),
+                 toVariable)
+import Text.Pandoc.Builder as B
+import Text.Pandoc.Class (PandocMonad)
+import Text.Pandoc.Citeproc.MetaValue (referenceToMetaValue)
+import Text.Pandoc.Citeproc.Name (toName, NameOpts(..))
+import Control.Monad.Except (throwError)
+import qualified Data.Text as T
+import Data.Text (Text)
+import Data.Maybe (fromMaybe)
+import qualified Data.Map as M
+import Safe (readMay)
+
+-- | Read RIS from an input string and return a Pandoc document.
+-- The document will have only metadata, with an empty body.
+-- The metadata will contain a `references` field with the
+-- bibliography entries, and a `nocite` field with the wildcard `[@*]`.
+readRIS :: (PandocMonad m, ToSources a)
+        => ReaderOptions -> a -> m Pandoc
+readRIS _opts inp = do
+  parsed <- readWithM risReferences () inp
+  case parsed of
+    Right refs -> do
+      refs' <- mapM (traverse (return . text)) refs
+      return $
+        setMeta "nocite" (cite [Citation {citationId = "*"
+                                         , citationPrefix = []
+                                         , citationSuffix = []
+                                         , citationMode = NormalCitation
+                                         , citationNoteNum = 0
+                                         , citationHash = 0}] (str "[@*]")) $
+        setMeta "references" (map referenceToMetaValue refs') $
+        B.doc mempty
+    Left e       -> throwError e
+
+type RISParser m = ParsecT Sources () m
+
+risLine :: PandocMonad m => RISParser m (Text, Text)
+risLine = do
+  key <- T.pack <$> count 2 (satisfy (\c -> isAsciiUpper c || isDigit c))
+  _ <- many1 spaceChar
+  char '-'
+  val <- (many1 spaceChar *> anyLine) <|> mempty <$ newline
+  return (key, T.strip val)
+
+risSeparator :: PandocMonad m => RISParser m ()
+risSeparator = do
+  try $ string "ER"
+  _ <- many1 spaceChar
+  char '-'
+  _ <- anyLine
+  optional blanklines
+
+risRecord :: PandocMonad m => RISParser m [(Text, Text)]
+risRecord = manyTill risLine risSeparator
+
+risRecordToReference :: [(Text, Text)] -> Reference Text
+risRecordToReference keys = addId $ foldr go defref keys
+ where
+   go (key, val) =
+     case key of
+       "TY" -> \ref -> ref{ referenceType =
+          fromMaybe "misc" (M.lookup val risTypes) }
+       "ID" -> \ref -> ref{ referenceId = ItemId val }
+       "VL" -> addVar "volume" val
+       "KW" -> \ref ->
+         ref{ referenceVariables =
+               M.alter (\x -> case x of
+                           Nothing -> Just $ TextVal val
+                           Just (TextVal kws)
+                                   -> Just (TextVal (kws <> ", " <> val))
+                           _ -> x)
+               "keyword"
+               (referenceVariables ref) }
+       "PB" -> addVar "publisher" val
+       "PP" -> addVar "publisher-place" val
+       "DO" -> addVar "DOI" val
+       "SP" -> \ref ->
+         case M.lookup "page" (referenceVariables ref) of
+           Nothing -> addVar "page" val ref
+           Just (FancyVal eg) -> addVar "page" (val <> eg) ref
+           _ -> ref
+       "EP" -> \ref ->
+         case M.lookup "page" (referenceVariables ref) of
+           Nothing -> addVar "page" ("-" <> val) ref
+           Just (FancyVal eg) -> addVar "page" (val <> "-" <> eg) ref
+           _ -> ref
+       "AU" -> addName "author" val
+       "A1" -> addName "author" val
+       "ED" -> addName "editor" val
+       "A2" -> addName "editor" val
+       "TI" -> addVar "title" val
+       "T1" -> addVar "title" val
+       "CT" -> addVar "title" val
+       "BT" -> \ref ->
+         if referenceType ref == "book"
+            then addVar "title" val ref
+            else addVar "container-title" val ref
+       "JO" -> addVar "container-title" val
+       "JF" -> addVar "container-title" val
+       "T2" -> addVar "container-title" val
+       "ET" -> addVar "edition" val
+       "NV" -> addVar "number-of-volumes" val
+       "AB" -> addVar "abstract" val
+       "PY" -> addYear "issued" val
+       "Y1" -> addYear "issued" val
+       "IS" -> addVar "issue" val
+       "SN" -> addVar "ISSN" val
+       "LA" -> addVar "language" val
+       "UR" -> addVar "url" val
+       "LK" -> addVar "url" val
+       _ -> id -- TODO
+   addVar k v r = r{ referenceVariables =
+                       M.insert (toVariable k) (FancyVal v)
+                       (referenceVariables r) }
+   addName k v r =
+     let new = toName NameOpts{ nameOptsPrefixIsNonDroppingParticle = False
+                              , nameOptsUseJuniorComma = False }
+                . B.toList .  B.text $ v
+         f Nothing   = Just (NamesVal new)
+         f (Just (NamesVal ns)) = Just (NamesVal (new ++ ns))
+         f (Just x) = Just x
+      in r{ referenceVariables =
+              M.alter f k (referenceVariables r) }
+   addYear k v r =
+     let d = DateVal $
+              case readMay (T.unpack v) of
+                Nothing ->
+                  Date { dateParts = []
+                       , dateCirca = False
+                       , dateSeason = Nothing
+                       , dateLiteral = Just v }
+                Just y ->
+                  Date { dateParts = [DateParts [y]]
+                       , dateCirca = False
+                       , dateSeason = Nothing
+                       , dateLiteral = Nothing }
+      in r{ referenceVariables = M.insert k d (referenceVariables r) }
+
+   defref = Reference{
+       referenceId = mempty
+     , referenceType = mempty
+     , referenceDisambiguation = Nothing
+     , referenceVariables = mempty }
+   addId rec =
+     if referenceId rec == mempty
+        then rec{ referenceId = ItemId (authors <> pubdate) }
+        else rec
+   authors = T.intercalate "_" $
+               [T.takeWhile (\c -> c /= ',' && not (isSpace c)) n
+                 | (k, n) <- keys, k == "AU" || k == "A1"]
+   pubdate = mconcat ["_" <> d | (k, d) <- keys, k == "PY" || k == "Y1"]
+
+risReferences :: PandocMonad m => RISParser m [Reference Text]
+risReferences = do
+  recs <- many risRecord
+  spaces
+  eof
+  return $ fixDuplicateIds $ map risRecordToReference recs
+
+fixDuplicateIds :: [Reference Text] -> [Reference Text]
+fixDuplicateIds = reverse . snd . L.foldl' go (mempty, [])
+ where
+   go (ids_seen, refs) ref =
+     case M.lookup (referenceId ref) ids_seen of
+       Nothing -> (M.insert (referenceId ref) (ord 'a') ids_seen, ref:refs)
+       Just n  -> (M.insert (referenceId ref) (n+1) ids_seen,
+                     ref{ referenceId =
+                          ItemId . (<> T.singleton (chr n)) . unItemId $
+                           referenceId ref }
+                    : refs)
+
+risTypes :: M.Map Text Text
+risTypes = M.fromList
+    [ ("ABST", "article")
+    , ("ADVS", "motion-picture")
+    , ("AGGR", "dataset")
+    , ("ANCIENT", "book")
+    , ("ART", "graphic")
+    , ("BILL", "bill")
+    , ("BLOG", "post-weblog")
+    , ("BOOK", "book")
+    , ("CASE", "legal_case")
+    , ("CHAP", "chapter")
+    , ("CHART", "graphic")
+    , ("CLSWK", "book")
+    , ("COMP", "program")
+    , ("CONF", "paper-conference")
+    , ("CPAPER", "paper-conference")
+    , ("CTLG", "catalog")
+    , ("DATA", "dataset")
+    , ("DBASE", "dataset")
+    , ("DICT", "book")
+    , ("EBOOK", "book")
+    , ("ECHAP", "chapter")
+    , ("EDBOOK", "book")
+    , ("EJOUR", "article")
+    , ("WEB", "webpage")
+    , ("ENCYC", "entry-encyclopedia")
+    , ("EQUA", "figure")
+    , ("FIGURE", "figure")
+    , ("GEN", "entry")
+    , ("GOVDOC", "report")
+    , ("GRANT", "report")
+    , ("HEAR", "report")
+    , ("ICOMM", "personal_communication")
+    , ("INPR", "article-journal")
+    , ("JFULL", "article-journal")
+    , ("JOUR", "article-journal")
+    , ("LEGAL", "legal_case")
+    , ("MANSCPT", "manuscript")
+    , ("MAP", "map")
+    , ("MGZN", "article-magazine")
+    , ("MPCT", "motion-picture")
+    , ("MULTI", "webpage")
+    , ("MUSIC", "musical_score")
+    , ("NEWS", "article-newspaper")
+    , ("PAMP", "pamphlet")
+    , ("PAT", "patent")
+    , ("PCOMM", "personal_communication")
+    , ("RPRT", "report")
+    , ("SER", "article")
+    , ("SLIDE", "graphic")
+    , ("SOUND", "musical_score")
+    , ("STAND", "report")
+    , ("STAT", "legislation")
+    , ("THES", "thesis")
+    , ("UNBILL", "bill")
+    , ("UNPB", "unpublished")
+    , ("VIDEO", "graphic") ]
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
@@ -1,1591 +1,1876 @@
 {-# LANGUAGE FlexibleContexts    #-}
 {-# LANGUAGE OverloadedStrings   #-}
 {-# LANGUAGE ScopedTypeVariables #-}
-{-
-Copyright (C) 2006-2017 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-2017 John MacFarlane
-   License     : GNU GPL, version 2 or above
-
-   Maintainer  : John MacFarlane <jgm@berkeley.edu>
-   Stability   : alpha
-   Portability : portable
-
-Conversion from reStructuredText to 'Pandoc' document.
--}
-module Text.Pandoc.Readers.RST ( readRST ) where
-import Control.Arrow (second)
-import Control.Monad (forM_, guard, liftM, mplus, mzero, when)
-import Control.Monad.Except (throwError)
-import Control.Monad.Identity (Identity (..))
-import Data.Char (isHexDigit, isSpace, toLower, toUpper)
-import Data.List (deleteFirstsBy, elemIndex, intercalate, isInfixOf, isSuffixOf,
-                  nub, sort, transpose, union)
-import qualified Data.Map as M
-import Data.Maybe (fromMaybe, isJust)
-import Data.Monoid ((<>))
-import Data.Sequence (ViewR (..), viewr)
-import Data.Text (Text)
-import qualified Data.Text as T
-import Text.Pandoc.Builder (Blocks, Inlines, fromList, setMeta, trimInlines)
-import qualified Text.Pandoc.Builder as B
-import Text.Pandoc.Class (PandocMonad, fetchItem, readFileFromDirs)
-import Text.Pandoc.CSV (CSVOptions (..), defaultCSVOptions, parseCSV)
-import Text.Pandoc.Definition
-import Text.Pandoc.Error
-import Text.Pandoc.ImageSize (lengthToDim, scaleDimension)
-import Text.Pandoc.Logging
-import Text.Pandoc.Options
-import Text.Pandoc.Parsing
-import Text.Pandoc.Shared
-import qualified Text.Pandoc.UTF8 as UTF8
-import Text.Printf (printf)
-
--- TODO:
--- [ ] .. parsed-literal
-
--- | Parse reStructuredText string and return Pandoc document.
-readRST :: PandocMonad m
-        => ReaderOptions -- ^ Reader options
-        -> Text          -- ^ String to parse (assuming @'\n'@ line endings)
-        -> m Pandoc
-readRST opts s = do
-  parsed <- readWithM parseRST def{ stateOptions = opts }
-               (T.unpack (crFilter s) ++ "\n\n")
-  case parsed of
-    Right result -> return result
-    Left e       -> throwError e
-
-type RSTParser m = ParserT [Char] ParserState m
-
---
--- Constants and data structure definitions
----
-
-bulletListMarkers :: [Char]
-bulletListMarkers = "*+-"
-
-underlineChars :: [Char]
-underlineChars = "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~"
-
--- treat these as potentially non-text when parsing inline:
-specialChars :: [Char]
-specialChars = "\\`|*_<>$:/[]{}()-.\"'\8216\8217\8220\8221"
-
---
--- parsing documents
---
-
-isHeader :: Int -> Block -> Bool
-isHeader n (Header x _ _) = x == n
-isHeader _ _              = False
-
--- | Promote all headers in a list of blocks.  (Part of
--- title transformation for RST.)
-promoteHeaders :: Int -> [Block] -> [Block]
-promoteHeaders num (Header level attr text:rest) =
-    Header (level - num) attr text:promoteHeaders num rest
-promoteHeaders num (other:rest) = other:promoteHeaders num rest
-promoteHeaders _   [] = []
-
--- | If list of blocks starts with a header (or a header and subheader)
--- of level that are not found elsewhere, return it as a title and
--- promote all the other headers.  Also process a definition list right
--- after the title block as metadata.
-titleTransform :: ([Block], Meta)  -- ^ list of blocks, metadata
-               -> ([Block], Meta)  -- ^ modified list of blocks, metadata
-titleTransform (bs, meta) =
-  let (bs', meta') =
-       case bs of
-          (Header 1 _ head1:Header 2 _ head2:rest)
-           | not (any (isHeader 1) rest || any (isHeader 2) rest) -> -- tit/sub
-            (promoteHeaders 2 rest, setMeta "title" (fromList head1) $
-              setMeta "subtitle" (fromList head2) meta)
-          (Header 1 _ head1:rest)
-           | not (any (isHeader 1) rest) -> -- title only
-            (promoteHeaders 1 rest,
-                setMeta "title" (fromList head1) meta)
-          _ -> (bs, meta)
-  in   case bs' of
-          (DefinitionList ds : rest) ->
-            (rest, metaFromDefList ds meta')
-          _ -> (bs', meta')
-
-metaFromDefList :: [([Inline], [[Block]])] -> Meta -> Meta
-metaFromDefList ds meta = adjustAuthors $ foldr f meta ds
- where f (k,v) = setMeta (map toLower $ stringify k) (mconcat $ map fromList v)
-       adjustAuthors (Meta metamap) = Meta $ M.adjust splitAuthors "author"
-                                           $ M.adjust toPlain "date"
-                                           $ M.adjust toPlain "title"
-                                           $ M.mapKeys (\k ->
-                                                 if k == "authors"
-                                                    then "author"
-                                                    else k) metamap
-       toPlain (MetaBlocks [Para xs]) = MetaInlines xs
-       toPlain x                      = x
-       splitAuthors (MetaBlocks [Para xs])
-                                      = MetaList $ map MetaInlines
-                                                 $ splitAuthors' xs
-       splitAuthors x                 = x
-       splitAuthors'                  = map normalizeSpaces .
-                                         splitOnSemi . concatMap factorSemi
-       normalizeSpaces                = reverse . dropWhile isSp . reverse .
-                                         dropWhile isSp
-       isSp Space     = True
-       isSp SoftBreak = True
-       isSp LineBreak = True
-       isSp _         = False
-       splitOnSemi                    = splitBy (==Str ";")
-       factorSemi (Str [])            = []
-       factorSemi (Str s)             = case break (==';') s of
-                                             (xs,[]) -> [Str xs]
-                                             (xs,';':ys) -> Str xs : Str ";" :
-                                                factorSemi (Str ys)
-                                             (xs,ys) -> Str xs :
-                                                factorSemi (Str ys)
-       factorSemi x                   = [x]
-
-parseRST :: PandocMonad m => RSTParser m Pandoc
-parseRST = do
-  optional blanklines -- skip blank lines at beginning of file
-  startPos <- getPosition
-  -- go through once just to get list of reference keys and notes
-  -- docMinusKeys is the raw document with blanks where the keys were...
-  docMinusKeys <- concat <$>
-                  manyTill (referenceKey <|> anchorDef <|>
-                            noteBlock <|> citationBlock <|>
-                            headerBlock <|> lineClump) eof
-  setInput docMinusKeys
-  setPosition startPos
-  st' <- getState
-  let reversedNotes = stateNotes st'
-  updateState $ \s -> s { stateNotes = reverse reversedNotes
-                        , stateHeaders = mempty
-                        , stateIdentifiers = mempty }
-  -- now parse it for real...
-  blocks <- B.toList <$> parseBlocks
-  citations <- (sort . M.toList . stateCitations) <$> getState
-  citationItems <- mapM parseCitation citations
-  let refBlock = if null citationItems
-                    then []
-                    else [Div ("citations",[],[]) $
-                            B.toList $ B.definitionList citationItems]
-  standalone <- getOption readerStandalone
-  state <- getState
-  let meta = stateMeta state
-  let (blocks', meta') = if standalone
-                            then titleTransform (blocks, meta)
-                            else (blocks, meta)
-  reportLogMessages
-  return $ Pandoc meta' (blocks' ++ refBlock)
-
-parseCitation :: PandocMonad m
-              => (String, String) -> RSTParser m (Inlines, [Blocks])
-parseCitation (ref, raw) = do
-  contents <- parseFromString' parseBlocks raw
-  return (B.spanWith (ref, ["citation-label"], []) (B.str ref),
-           [contents])
-
-
---
--- parsing blocks
---
-
-parseBlocks :: PandocMonad m => RSTParser m Blocks
-parseBlocks = mconcat <$> manyTill block eof
-
-block :: PandocMonad m => RSTParser m Blocks
-block = choice [ codeBlock
-               , blockQuote
-               , fieldList
-               , directive
-               , anchor
-               , comment
-               , header
-               , hrule
-               , lineBlock     -- must go before definitionList
-               , table
-               , list
-               , lhsCodeBlock
-               , para
-               , mempty <$ blanklines
-               ] <?> "block"
-
---
--- field list
---
-
-rawFieldListItem :: Monad m => Int -> RSTParser m (String, String)
-rawFieldListItem minIndent = try $ do
-  indent <- length <$> many (char ' ')
-  guard $ indent >= minIndent
-  char ':'
-  name <- many1Till (noneOf "\n") (char ':')
-  (() <$ lookAhead newline) <|> skipMany1 spaceChar
-  first <- anyLine
-  rest <- option "" $ try $ do lookAhead (count indent (char ' ') >> spaceChar)
-                               indentedBlock
-  let raw = (if null first then "" else (first ++ "\n")) ++ rest ++ "\n"
-  return (name, raw)
-
-fieldListItem :: PandocMonad m => Int -> RSTParser m (Inlines, [Blocks])
-fieldListItem minIndent = try $ do
-  (name, raw) <- rawFieldListItem minIndent
-  term <- parseInlineFromString name
-  contents <- parseFromString' parseBlocks raw
-  optional blanklines
-  return (term, [contents])
-
-fieldList :: PandocMonad m => RSTParser m Blocks
-fieldList = try $ do
-  indent <- length <$> lookAhead (many spaceChar)
-  items <- many1 $ fieldListItem indent
-  case items of
-     []     -> return mempty
-     items' -> return $ B.definitionList items'
-
---
--- line block
---
-
-lineBlock :: PandocMonad m => RSTParser m Blocks
-lineBlock = try $ do
-  lines' <- lineBlockLines
-  lines'' <- mapM parseInlineFromString lines'
-  return $ B.lineBlock lines''
-
-lineBlockDirective :: PandocMonad m => String -> RSTParser m Blocks
-lineBlockDirective body = do
-  lines' <- mapM parseInlineFromString $ lines $ stripTrailingNewlines body
-  return $ B.lineBlock lines'
-
---
--- paragraph block
---
-
--- note: paragraph can end in a :: starting a code block
-para :: PandocMonad m => RSTParser m Blocks
-para = try $ do
-  result <- trimInlines . mconcat <$> many1 inline
-  option (B.plain result) $ try $ do
-    newline
-    blanklines
-    case viewr (B.unMany result) of
-         ys :> Str xs | "::" `isSuffixOf` xs -> do
-              raw <- option mempty codeBlockBody
-              return $ B.para (B.Many ys <> B.str (take (length xs - 1) xs))
-                         <> raw
-         _ -> return (B.para result)
-
-plain :: PandocMonad m => RSTParser m Blocks
-plain = B.plain . trimInlines . mconcat <$> many1 inline
-
---
--- header blocks
---
-
-header :: PandocMonad m => RSTParser m Blocks
-header = doubleHeader <|> singleHeader <?> "header"
-
--- a header with lines on top and bottom
-doubleHeader :: PandocMonad m => RSTParser m Blocks
-doubleHeader = do
-  (txt, c) <- doubleHeader'
-  -- check to see if we've had this kind of header before.
-  -- if so, get appropriate level.  if not, add to list.
-  state <- getState
-  let headerTable = stateHeaderTable state
-  let (headerTable',level) = case elemIndex (DoubleHeader c) headerTable of
-        Just ind -> (headerTable, ind + 1)
-        Nothing  -> (headerTable ++ [DoubleHeader c], length headerTable + 1)
-  setState (state { stateHeaderTable = headerTable' })
-  attr <- registerHeader nullAttr txt
-  return $ B.headerWith attr level txt
-
-doubleHeader' :: PandocMonad m => RSTParser m (Inlines, Char)
-doubleHeader' = try $ do
-  c <- oneOf underlineChars
-  rest <- many (char c)  -- the top line
-  let lenTop = length (c:rest)
-  skipSpaces
-  newline
-  txt <- trimInlines . mconcat <$> many1 (notFollowedBy blankline >> inline)
-  pos <- getPosition
-  let len = sourceColumn pos - 1
-  when (len > lenTop) $ fail "title longer than border"
-  blankline              -- spaces and newline
-  count lenTop (char c)  -- the bottom line
-  blanklines
-  return (txt, c)
-
--- a header with line on the bottom only
-singleHeader :: PandocMonad m => RSTParser m Blocks
-singleHeader = do
-  (txt, c) <- singleHeader'
-  state <- getState
-  let headerTable = stateHeaderTable state
-  let (headerTable',level) = case elemIndex (SingleHeader c) headerTable of
-        Just ind -> (headerTable, ind + 1)
-        Nothing  -> (headerTable ++ [SingleHeader c], length headerTable + 1)
-  setState (state { stateHeaderTable = headerTable' })
-  attr <- registerHeader nullAttr txt
-  return $ B.headerWith attr level txt
-
-singleHeader' :: PandocMonad m => RSTParser m (Inlines, Char)
-singleHeader' = try $ do
-  notFollowedBy' whitespace
-  lookAhead $ anyLine >> oneOf underlineChars
-  txt <- trimInlines . mconcat <$> many1 (do {notFollowedBy newline; inline})
-  pos <- getPosition
-  let len = sourceColumn pos - 1
-  blankline
-  c <- oneOf underlineChars
-  count (len - 1) (char c)
-  many (char c)
-  blanklines
-  return (txt, c)
-
---
--- hrule block
---
-
-hrule :: Monad m => ParserT [Char] st m Blocks
-hrule = try $ do
-  chr <- oneOf underlineChars
-  count 3 (char chr)
-  skipMany (char chr)
-  blankline
-  blanklines
-  return B.horizontalRule
-
---
--- code blocks
---
-
--- read a line indented by a given string
-indentedLine :: Monad m => String -> ParserT [Char] st m [Char]
-indentedLine indents = try $ do
-  string indents
-  anyLine
-
--- one or more indented lines, possibly separated by blank lines.
--- any amount of indentation will work.
-indentedBlock :: Monad m => ParserT [Char] st m [Char]
-indentedBlock = try $ do
-  indents <- lookAhead $ many1 spaceChar
-  lns <- many1 $ try $ do b <- option "" blanklines
-                          l <- indentedLine indents
-                          return (b ++ l)
-  optional blanklines
-  return $ unlines lns
-
-quotedBlock :: Monad m => ParserT [Char] st m [Char]
-quotedBlock = try $ do
-    quote <- lookAhead $ oneOf "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~"
-    lns <- many1 $ lookAhead (char quote) >> anyLine
-    optional blanklines
-    return $ unlines lns
-
-codeBlockStart :: Monad m => ParserT [Char] st m Char
-codeBlockStart = string "::" >> blankline >> blankline
-
-codeBlock :: Monad m => ParserT [Char] st m Blocks
-codeBlock = try $ codeBlockStart >> codeBlockBody
-
-codeBlockBody :: Monad m => ParserT [Char] st m Blocks
-codeBlockBody = try $ B.codeBlock . stripTrailingNewlines <$>
-                (indentedBlock <|> quotedBlock)
-
-lhsCodeBlock :: Monad m => RSTParser m Blocks
-lhsCodeBlock = try $ do
-  getPosition >>= guard . (==1) . sourceColumn
-  guardEnabled Ext_literate_haskell
-  optional codeBlockStart
-  lns <- latexCodeBlock <|> birdCodeBlock
-  blanklines
-  return $ B.codeBlockWith ("", ["sourceCode", "literate", "haskell"], [])
-         $ intercalate "\n" lns
-
-latexCodeBlock :: Monad m => ParserT [Char] st m [[Char]]
-latexCodeBlock = try $ do
-  try (latexBlockLine "\\begin{code}")
-  many1Till anyLine (try $ latexBlockLine "\\end{code}")
- where
-  latexBlockLine s = skipMany spaceChar >> string s >> blankline
-
-birdCodeBlock :: Monad m => ParserT [Char] st m [[Char]]
-birdCodeBlock = filterSpace <$> many1 birdTrackLine
-  where filterSpace lns =
-            -- if (as is normal) there is always a space after >, drop it
-            if all (\ln -> null ln || take 1 ln == " ") lns
-               then map (drop 1) lns
-               else lns
-
-birdTrackLine :: Monad m => ParserT [Char] st m [Char]
-birdTrackLine = char '>' >> anyLine
-
---
--- block quotes
---
-
-blockQuote :: PandocMonad m => RSTParser m Blocks
-blockQuote = do
-  raw <- indentedBlock
-  -- parse the extracted block, which may contain various block elements:
-  contents <- parseFromString' parseBlocks $ raw ++ "\n\n"
-  return $ B.blockQuote contents
-
-{-
-Unsupported options for include:
-tab-width
-encoding
--}
-
-includeDirective :: PandocMonad m
-                 => String -> [(String, String)] -> String
-                 -> RSTParser m Blocks
-includeDirective top fields body = do
-  let f = trim top
-  guard $ not (null f)
-  guard $ null (trim body)
-  -- options
-  let (startLine :: Maybe Int) = lookup "start-line" fields >>= safeRead
-  let (endLine :: Maybe Int) = lookup "end-line" fields >>= safeRead
-  oldPos <- getPosition
-  oldInput <- getInput
-  containers <- stateContainers <$> getState
-  when (f `elem` containers) $
-    throwError $ PandocParseError $ "Include file loop at " ++ show oldPos
-  updateState $ \s -> s{ stateContainers = f : stateContainers s }
-  mbContents <- readFileFromDirs ["."] f
-  contentLines <- case mbContents of
-                       Just s -> return $ lines s
-                       Nothing -> do
-                         logMessage $ CouldNotLoadIncludeFile f oldPos
-                         return []
-  let numLines = length contentLines
-  let startLine' = case startLine of
-                        Nothing            -> 1
-                        Just x | x >= 0    -> x
-                               | otherwise -> numLines + x -- negative from end
-  let endLine' = case endLine of
-                        Nothing            -> numLines + 1
-                        Just x | x >= 0    -> x
-                               | otherwise -> numLines + x -- negative from end
-  let contentLines' =   drop (startLine' - 1)
-                      $ take (endLine' - 1) contentLines
-  let contentLines'' = (case trim <$> lookup "end-before" fields of
-                             Just patt -> takeWhile (not . (patt `isInfixOf`))
-                             Nothing   -> id) .
-                       (case trim <$> lookup "start-after" fields of
-                             Just patt -> drop 1 .
-                                            dropWhile (not . (patt `isInfixOf`))
-                             Nothing   -> id) $ contentLines'
-  let contents' = unlines contentLines'' ++ "\n"
-  case lookup "code" fields of
-       Just lang -> do
-         let numberLines = lookup "number-lines" fields
-         let classes = trimr lang : ["numberLines" | isJust numberLines] ++
-                          maybe [] words (lookup "class" fields)
-         let kvs = maybe [] (\n -> [("startFrom", trimr n)]) numberLines
-         let ident = maybe "" trimr $ lookup "name" fields
-         let attribs = (ident, classes, kvs)
-         return $ B.codeBlockWith attribs contents'
-       Nothing   -> case lookup "literal" fields of
-                         Just _  -> return $ B.rawBlock "rst" contents'
-                         Nothing -> do
-                           setPosition $ newPos f 1 1
-                           setInput contents'
-                           bs <- optional blanklines >>
-                                  (mconcat <$> many block)
-                           setInput oldInput
-                           setPosition oldPos
-                           updateState $ \s -> s{ stateContainers =
-                                         tail $ stateContainers s }
-                           return bs
-
-
---
--- list blocks
---
-
-list :: PandocMonad m => RSTParser m Blocks
-list = choice [ bulletList, orderedList, definitionList ] <?> "list"
-
-definitionListItem :: PandocMonad m => RSTParser m (Inlines, [Blocks])
-definitionListItem = try $ do
-  -- avoid capturing a directive or comment
-  notFollowedBy (try $ char '.' >> char '.')
-  term <- trimInlines . mconcat <$> many1Till inline endline
-  raw <- indentedBlock
-  -- parse the extracted block, which may contain various block elements:
-  contents <- parseFromString' parseBlocks $ raw ++ "\n"
-  return (term, [contents])
-
-definitionList :: PandocMonad m => RSTParser m Blocks
-definitionList = B.definitionList <$> many1 definitionListItem
-
--- parses bullet list start and returns its length (inc. following whitespace)
-bulletListStart :: Monad m => ParserT [Char] st m Int
-bulletListStart = try $ do
-  notFollowedBy' hrule  -- because hrules start out just like lists
-  marker <- oneOf bulletListMarkers
-  white <- many1 spaceChar <|> "" <$ lookAhead (char '\n')
-  return $ length (marker:white)
-
--- parses ordered list start and returns its length (inc following whitespace)
-orderedListStart :: Monad m => ListNumberStyle
-                 -> ListNumberDelim
-                 -> RSTParser m Int
-orderedListStart style delim = try $ do
-  (_, markerLen) <- withHorizDisplacement (orderedListMarker style delim)
-  white <- many1 spaceChar <|> "" <$ lookAhead (char '\n')
-  return $ markerLen + length white
-
--- parse a line of a list item
-listLine :: Monad m => Int -> RSTParser m [Char]
-listLine markerLength = try $ do
-  notFollowedBy blankline
-  indentWith markerLength
-  anyLineNewline
-
--- parse raw text for one list item, excluding start marker and continuations
-rawListItem :: Monad m => RSTParser m Int
-            -> RSTParser m (Int, [Char])
-rawListItem start = try $ do
-  markerLength <- start
-  firstLine <- anyLineNewline
-  restLines <- many (listLine markerLength)
-  return (markerLength, firstLine ++ concat restLines)
-
--- continuation of a list item - indented and separated by blankline or
--- (in compact lists) endline.
--- Note: nested lists are parsed as continuations.
-listContinuation :: Monad m => Int -> RSTParser m [Char]
-listContinuation markerLength = try $ do
-  blanks <- many1 blankline
-  result <- many1 (listLine markerLength)
-  return $ blanks ++ concat result
-
-listItem :: PandocMonad m
-         => RSTParser m Int
-         -> RSTParser m Blocks
-listItem start = try $ do
-  (markerLength, first) <- rawListItem start
-  rest <- many (listContinuation markerLength)
-  skipMany1 blankline <|> () <$ lookAhead start
-  -- parsing with ListItemState forces markers at beginning of lines to
-  -- count as list item markers, even if not separated by blank space.
-  -- see definition of "endline"
-  state <- getState
-  let oldContext = stateParserContext state
-  setState $ state {stateParserContext = ListItemState}
-  -- parse the extracted block, which may itself contain block elements
-  parsed <- parseFromString' parseBlocks $ concat (first:rest) ++ "\n"
-  updateState (\st -> st {stateParserContext = oldContext})
-  return $ case B.toList parsed of
-                [Para xs] ->
-                   B.singleton $ Plain xs
-                [Para xs, BulletList ys] ->
-                   B.fromList [Plain xs, BulletList ys]
-                [Para xs, OrderedList s ys] ->
-                   B.fromList [Plain xs, OrderedList s ys]
-                [Para xs, DefinitionList ys] ->
-                   B.fromList [Plain xs, DefinitionList ys]
-                _         -> parsed
-
-orderedList :: PandocMonad m => RSTParser m Blocks
-orderedList = try $ do
-  (start, style, delim) <- lookAhead (anyOrderedListMarker <* spaceChar)
-  items <- many1 (listItem (orderedListStart style delim))
-  let items' = compactify items
-  return $ B.orderedListWith (start, style, delim) items'
-
-bulletList :: PandocMonad m => RSTParser m Blocks
-bulletList = B.bulletList . compactify <$> many1 (listItem bulletListStart)
-
---
--- directive (e.g. comment, container, compound-paragraph)
---
-
-comment :: Monad m => RSTParser m Blocks
-comment = try $ do
-  string ".."
-  skipMany1 spaceChar <|> (() <$ lookAhead newline)
-  -- notFollowedBy' directiveLabel -- comment comes after directive so unnec.
-  manyTill anyChar blanklines
-  optional indentedBlock
-  return mempty
-
-directiveLabel :: Monad m => RSTParser m String
-directiveLabel = map toLower
-  <$> many1Till (letter <|> char '-') (try $ string "::")
-
-directive :: PandocMonad m => RSTParser m Blocks
-directive = try $ do
-  string ".."
-  directive'
-
-directive' :: PandocMonad m => RSTParser m Blocks
-directive' = do
-  skipMany1 spaceChar
-  label <- directiveLabel
-  skipMany spaceChar
-  top <- many $ satisfy (/='\n')
-             <|> try (char '\n' <*
-                      notFollowedBy' (rawFieldListItem 3) <*
-                      count 3 (char ' ') <*
-                      notFollowedBy blankline)
-  newline
-  fields <- many $ rawFieldListItem 3
-  body <- option "" $ try $ blanklines >> indentedBlock
-  optional blanklines
-  let body' = body ++ "\n\n"
-      name = trim $ fromMaybe "" (lookup "name" fields)
-      imgAttr cl = ("", classes, widthAttr ++ heightAttr)
-        where
-          classes = words $ maybe "" trim (lookup cl fields) ++
-                      maybe "" (\x -> "align-" ++ trim x)
-                        (lookup "align" fields)
-          scale = case trim <$> lookup "scale" fields of
-                       Just v  -> case reverse v of
-                                       '%':vv ->
-                                         case safeRead (reverse vv) of
-                                              Just (percent :: Double)
-                                                      -> percent / 100.0
-                                              Nothing -> 1.0
-                                       _ ->
-                                         case safeRead v of
-                                              Just (s :: Double) -> s
-                                              Nothing            -> 1.0
-                       Nothing -> 1.0
-          widthAttr = maybe [] (\x -> [("width",
-                                        show $ scaleDimension scale x)])
-                        $ lookup "width" fields >>=
-                          (lengthToDim . filter (not . isSpace))
-          heightAttr = maybe [] (\x -> [("height",
-                                         show $ scaleDimension scale x)])
-                        $ lookup "height" fields >>=
-                          (lengthToDim . filter (not . isSpace))
-  case label of
-        "include" -> includeDirective top fields body'
-        "table" -> tableDirective top fields body'
-        "list-table" -> listTableDirective top fields body'
-        "csv-table" -> csvTableDirective top fields body'
-        "line-block" -> lineBlockDirective body'
-        "raw" -> return $ B.rawBlock (trim top) (stripTrailingNewlines body)
-        "role" -> addNewRole top $ map (second trim) fields
-        "container" -> B.divWith (name, "container" : words top, []) <$>
-                            parseFromString' parseBlocks body'
-        "replace" -> B.para <$>  -- consumed by substKey
-                   parseInlineFromString (trim top)
-        "unicode" -> B.para <$>  -- consumed by substKey
-                   parseInlineFromString (trim $ unicodeTransform top)
-        "compound" -> parseFromString' parseBlocks body'
-        "pull-quote" -> B.blockQuote <$> parseFromString' parseBlocks body'
-        "epigraph" -> B.blockQuote <$> parseFromString' parseBlocks body'
-        "highlights" -> B.blockQuote <$> parseFromString' parseBlocks body'
-        "rubric" -> B.para . B.strong <$> parseInlineFromString top
-        _ | label `elem` ["attention","caution","danger","error","hint",
-                          "important","note","tip","warning","admonition"] ->
-           do bod <- parseFromString' parseBlocks $ top ++ "\n\n" ++ body'
-              let lab = case label of
-                             "admonition" -> mempty
-                             (l:ls) -> B.divWith ("",["admonition-title"],[])
-                                          (B.para (B.str (toUpper l : ls)))
-                             [] -> mempty
-              return $ B.divWith ("",[label],[]) (lab <> bod)
-        "sidebar" ->
-           do let subtit = maybe "" trim $ lookup "subtitle" fields
-              tit <- B.para . B.strong <$> parseInlineFromString
-                          (trim top ++ if null subtit
-                                          then ""
-                                          else (":  " ++ subtit))
-              bod <- parseFromString' parseBlocks body'
-              return $ B.divWith ("",["sidebar"],[]) $ tit <> bod
-        "topic" ->
-           do tit <- B.para . B.strong <$> parseInlineFromString top
-              bod <- parseFromString' parseBlocks body'
-              return $ B.divWith ("",["topic"],[]) $ tit <> bod
-        "default-role" -> mempty <$ updateState (\s ->
-                              s { stateRstDefaultRole =
-                                  case trim top of
-                                     ""   -> stateRstDefaultRole def
-                                     role -> role })
-        x | x == "code" || x == "code-block" ->
-          codeblock (words $ fromMaybe [] $ lookup "class" fields)
-                    (lookup "number-lines" fields) (trim top) body
-        "aafig" -> do
-          let attribs = ("", ["aafig"], map (second trimr) fields)
-          return $ B.codeBlockWith attribs $ stripTrailingNewlines body
-        "math" -> return $ B.para $ mconcat $ map B.displayMath
-                         $ toChunks $ top ++ "\n\n" ++ body
-        "figure" -> do
-           (caption, legend) <- parseFromString' extractCaption body'
-           let src = escapeURI $ trim top
-           return $ B.para (B.imageWith (imgAttr "figclass") src "fig:"
-                       caption) <> legend
-        "image" -> do
-           let src = escapeURI $ trim top
-           let alt = B.str $ maybe "image" trim $ lookup "alt" fields
-           let attr = imgAttr "class"
-           return $ B.para
-                  $ case lookup "target" fields of
-                          Just t  -> B.link (escapeURI $ trim t) ""
-                                     $ B.imageWith attr src "" alt
-                          Nothing -> B.imageWith attr src "" alt
-        "class" -> do
-            let attrs = ("", splitBy isSpace $ trim top,
-                              map (second trimr) fields)
-            --  directive content or the first immediately following element
-            children <- case body of
-                "" -> block
-                _  -> parseFromString' parseBlocks  body'
-            return $ B.divWith attrs children
-        other     -> do
-            pos <- getPosition
-            logMessage $ SkippedContent (".. " ++ other) pos
-            bod <- parseFromString' parseBlocks $ top ++ "\n\n" ++ body'
-            return $ B.divWith ("",[other],[]) bod
-
-tableDirective :: PandocMonad m
-               => String -> [(String, String)] -> String -> RSTParser m Blocks
-tableDirective top fields body = do
-  bs <- parseFromString' parseBlocks body
-  case B.toList bs of
-       [Table _ aligns' widths' header' rows'] -> do
-         title <- parseFromString' (trimInlines . mconcat <$> many inline) top
-         columns <- getOption readerColumns
-         let numOfCols = length header'
-         let normWidths ws =
-                map (/ max 1.0 (fromIntegral (columns - numOfCols))) ws
-         let widths = case trim <$> lookup "widths" fields of
-                           Just "auto" -> replicate numOfCols 0.0
-                           Just "grid" -> widths'
-                           Just specs -> normWidths
-                               $ map (fromMaybe (0 :: Double) . safeRead)
-                               $ splitBy (`elem` (" ," :: String)) specs
-                           Nothing -> widths'
-         -- align is not applicable since we can't represent whole table align
-         return $ B.singleton $ Table (B.toList title)
-                                  aligns' widths header' rows'
-       _ -> return mempty
-
-
--- TODO: :stub-columns:.
--- Only the first row becomes the header even if header-rows: > 1,
--- since Pandoc doesn't support a table with multiple header rows.
--- We don't need to parse :align: as it represents the whole table align.
-listTableDirective :: PandocMonad m
-                   => String -> [(String, String)] -> String
-                   -> RSTParser m Blocks
-listTableDirective top fields body = do
-  bs <- parseFromString' parseBlocks body
-  title <- parseFromString' (trimInlines . mconcat <$> many inline) top
-  let rows = takeRows $ B.toList bs
-      headerRowsNum = fromMaybe (0 :: Int) $
-         lookup "header-rows" fields >>= safeRead
-      (headerRow,bodyRows,numOfCols) = case rows of
-        x:xs -> if headerRowsNum > 0
-                   then (x, xs, length x)
-                   else ([], rows, length x)
-        _ -> ([],[],0)
-      widths = case trim <$> lookup "widths" fields of
-        Just "auto" -> replicate numOfCols 0
-        Just specs -> normWidths $ map (fromMaybe (0 :: Double) . safeRead) $
-                           splitBy (`elem` (" ," :: String)) specs
-        _ -> replicate numOfCols 0
-  return $ B.table title
-             (zip (replicate numOfCols AlignDefault) widths)
-             headerRow
-             bodyRows
-    where takeRows [BulletList rows] = map takeCells rows
-          takeRows _                 = []
-          takeCells [BulletList cells] = map B.fromList cells
-          takeCells _                  = []
-          normWidths ws = map (/ max 1 (sum ws)) ws
-
-csvTableDirective :: PandocMonad m
-                   => String -> [(String, String)] -> String
-                   -> RSTParser m Blocks
-csvTableDirective top fields rawcsv = do
-  let explicitHeader = trim <$> lookup "header" fields
-  let opts = defaultCSVOptions{
-                csvDelim = case trim <$> lookup "delim" fields of
-                                Just "tab"   -> '\t'
-                                Just "space" -> ' '
-                                Just [c]     -> c
-                                _            -> ','
-              , csvQuote = case trim <$> lookup "quote" fields of
-                                Just [c] -> c
-                                _        -> '"'
-              , csvEscape = case trim <$> lookup "escape" fields of
-                                Just [c] -> Just c
-                                _        -> Nothing
-              , csvKeepSpace = case trim <$> lookup "keepspace" fields of
-                                       Just "true" -> True
-                                       _           -> False
-              }
-  let headerRowsNum = fromMaybe (case explicitHeader of
-                                       Just _  -> 1 :: Int
-                                       Nothing -> 0 :: Int) $
-           lookup "header-rows" fields >>= safeRead
-  rawcsv' <- case trim <$>
-                    lookup "file" fields `mplus` lookup "url" fields of
-                  Just u  -> do
-                    (bs, _) <- fetchItem u
-                    return $ UTF8.toString bs
-                  Nothing -> return rawcsv
-  let res = parseCSV opts (T.pack $ case explicitHeader of
-                                         Just h  -> h ++ "\n" ++ rawcsv'
-                                         Nothing -> rawcsv')
-  case res of
-       Left e  ->
-         throwError $ PandocParsecError "csv table" e
-       Right rawrows -> do
-         let parseCell = parseFromString' (plain <|> return mempty) . T.unpack
-         let parseRow = mapM parseCell
-         rows <- mapM parseRow rawrows
-         let (headerRow,bodyRows,numOfCols) =
-              case rows of
-                   x:xs -> if headerRowsNum > 0
-                          then (x, xs, length x)
-                          else ([], rows, length x)
-                   _ -> ([],[],0)
-         title <- parseFromString' (trimInlines . mconcat <$> many inline) top
-         let normWidths ws = map (/ max 1 (sum ws)) ws
-         let widths =
-               case trim <$> lookup "widths" fields of
-                 Just "auto" -> replicate numOfCols 0
-                 Just specs -> normWidths
-                               $ map (fromMaybe (0 :: Double) . safeRead)
-                               $ splitBy (`elem` (" ," :: String)) specs
-                 _ -> replicate numOfCols 0
-         return $ B.table title
-                  (zip (replicate numOfCols AlignDefault) widths)
-                  headerRow
-                  bodyRows
-
--- TODO:
---  - Only supports :format: fields with a single format for :raw: roles,
---    change Text.Pandoc.Definition.Format to fix
-addNewRole :: PandocMonad m
-           => String -> [(String, String)] -> RSTParser m Blocks
-addNewRole roleString fields = do
-    pos <- getPosition
-    (role, parentRole) <- parseFromString' inheritedRole roleString
-    customRoles <- stateRstCustomRoles <$> getState
-    let getBaseRole (r, f, a) roles =
-            case M.lookup r roles of
-                 Just (r', f', a') -> getBaseRole (r', f', a') roles
-                 Nothing           -> (r, f, a)
-        (baseRole, baseFmt, baseAttr) =
-               getBaseRole (parentRole, Nothing, nullAttr) customRoles
-        fmt = if parentRole == "raw" then lookup "format" fields else baseFmt
-        annotate :: [String] -> [String]
-        annotate = maybe id (:) $
-            if baseRole == "code"
-               then lookup "language" fields
-               else Nothing
-        attr = let (ident, classes, keyValues) = baseAttr
-        -- nub in case role name & language class are the same
-               in (ident, nub . (role :) . annotate $ classes, keyValues)
-
-    -- warn about syntax we ignore
-    forM_ fields $ \(key, _) -> case key of
-                 "language" -> when (baseRole /= "code") $ logMessage $
-                     SkippedContent ":language: [because parent of role is not :code:]"
-                        pos
-                 "format" -> when (baseRole /= "raw") $ logMessage $
-                     SkippedContent ":format: [because parent of role is not :raw:]" pos
-                 _ -> logMessage $ SkippedContent (":" ++ key ++ ":") pos
-    when (parentRole == "raw" && countKeys "format" > 1) $
-        logMessage $ SkippedContent
-                  ":format: [after first in definition of role]"
-                  pos
-    when (parentRole == "code" && countKeys "language" > 1) $
-        logMessage $ SkippedContent
-          ":language: [after first in definition of role]" pos
-
-    updateState $ \s -> s {
-        stateRstCustomRoles =
-          M.insert role (baseRole, fmt, attr) customRoles
-    }
-
-    return mempty
-  where
-    countKeys k = length . filter (== k) . map fst $ fields
-    inheritedRole =
-        (,) <$> roleName <*> ((char '(' *> roleName <* char ')')
-                            <|> pure "span")
-
-
--- Can contain character codes as decimal numbers or
--- hexadecimal numbers, prefixed by 0x, x, \x, U+, u, or \u
--- or as XML-style hexadecimal character entities, e.g. &#x1a2b;
--- or text, which is used as-is.  Comments start with ..
-unicodeTransform :: String -> String
-unicodeTransform t =
-  case t of
-       ('.':'.':xs)  -> unicodeTransform $ dropWhile (/='\n') xs -- comment
-       ('0':'x':xs)  -> go "0x" xs
-       ('x':xs)      -> go "x" xs
-       ('\\':'x':xs) -> go "\\x" xs
-       ('U':'+':xs)  -> go "U+" xs
-       ('u':xs)      -> go "u" xs
-       ('\\':'u':xs) -> go "\\u" xs
-       ('&':'#':'x':xs) -> maybe ("&#x" ++ unicodeTransform xs)
-                           -- drop semicolon
-                           (\(c,s) -> c : unicodeTransform (drop 1 s))
-                           $ extractUnicodeChar xs
-       (x:xs)        -> x : unicodeTransform xs
-       []            -> []
-    where go pref zs = maybe (pref ++ unicodeTransform zs)
-                         (\(c,s) -> c : unicodeTransform s)
-                         $ extractUnicodeChar zs
-
-extractUnicodeChar :: String -> Maybe (Char, String)
-extractUnicodeChar s = maybe Nothing (\c -> Just (c,rest)) mbc
-  where (ds,rest) = span isHexDigit s
-        mbc = safeRead ('\'':'\\':'x':ds ++ "'")
-
-extractCaption :: PandocMonad m => RSTParser m (Inlines, Blocks)
-extractCaption = do
-  capt <- trimInlines . mconcat <$> many inline
-  legend <- optional blanklines >> (mconcat <$> many block)
-  return (capt,legend)
-
--- divide string by blanklines
-toChunks :: String -> [String]
-toChunks = dropWhile null
-           . map (trim . unlines)
-           . splitBy (all (`elem` (" \t" :: String))) . lines
-
-codeblock :: [String] -> Maybe String -> String -> String -> RSTParser m Blocks
-codeblock classes numberLines lang body =
-  return $ B.codeBlockWith attribs $ stripTrailingNewlines body
-    where attribs = ("", classes', kvs)
-          classes' = "sourceCode" : lang
-                    : maybe [] (const ["numberLines"]) numberLines
-                    ++ classes
-          kvs     = case numberLines of
-                          Just "" -> []
-                          Nothing -> []
-                          Just n  -> [("startFrom",trim n)]
-
----
---- note block
----
-
-noteBlock :: Monad m => RSTParser m [Char]
-noteBlock = try $ do
-  (ref, raw, replacement) <- noteBlock' noteMarker
-  updateState $ \s -> s { stateNotes = (ref, raw) : stateNotes s }
-  -- return blanks so line count isn't affected
-  return replacement
-
-citationBlock :: Monad m => RSTParser m [Char]
-citationBlock = try $ do
-  (ref, raw, replacement) <- noteBlock' citationMarker
-  updateState $ \s ->
-     s { stateCitations = M.insert ref raw (stateCitations s),
-         stateKeys = M.insert (toKey ref) (('#':ref,""), ("",["citation"],[]))
-                               (stateKeys s) }
-  -- return blanks so line count isn't affected
-  return replacement
-
-noteBlock' :: Monad m
-           => RSTParser m String -> RSTParser m (String, String, String)
-noteBlock' marker = try $ do
-  startPos <- getPosition
-  string ".."
-  spaceChar >> skipMany spaceChar
-  ref <- marker
-  first <- (spaceChar >> skipMany spaceChar >> anyLine)
-        <|> (newline >> return "")
-  blanks <- option "" blanklines
-  rest <- option "" indentedBlock
-  endPos <- getPosition
-  let raw = first ++ "\n" ++ blanks ++ rest ++ "\n"
-  let replacement =replicate (sourceLine endPos - sourceLine startPos) '\n'
-  return (ref, raw, replacement)
-
-citationMarker :: Monad m => RSTParser m [Char]
-citationMarker = do
-  char '['
-  res <- simpleReferenceName
-  char ']'
-  return res
-
-noteMarker :: Monad m => RSTParser m [Char]
-noteMarker = do
-  char '['
-  res <- many1 digit
-      <|>
-                  try (char '#' >> liftM ('#':) simpleReferenceName)
-      <|> count 1 (oneOf "#*")
-  char ']'
-  return res
-
---
--- reference key
---
-
-quotedReferenceName :: PandocMonad m => RSTParser m String
-quotedReferenceName = try $ do
-  char '`' >> notFollowedBy (char '`') -- `` means inline code!
-  manyTill anyChar (char '`')
-
--- Simple reference names are single words consisting of alphanumerics
--- plus isolated (no two adjacent) internal hyphens, underscores,
--- periods, colons and plus signs; no whitespace or other characters
--- are allowed.
-simpleReferenceName :: Monad m => ParserT [Char] st m String
-simpleReferenceName = do
-  x <- alphaNum
-  xs <- many $  alphaNum
-            <|> try (oneOf "-_:+." <* lookAhead alphaNum)
-  return (x:xs)
-
-referenceName :: PandocMonad m => RSTParser m String
-referenceName = quotedReferenceName <|> simpleReferenceName
-
-referenceKey :: PandocMonad m => RSTParser m [Char]
-referenceKey = do
-  startPos <- getPosition
-  choice [substKey, anonymousKey, regularKey]
-  optional blanklines
-  endPos <- getPosition
-  -- return enough blanks to replace key
-  return $ replicate (sourceLine endPos - sourceLine startPos) '\n'
-
-targetURI :: Monad m => ParserT [Char] st m [Char]
-targetURI = do
-  skipSpaces
-  optional newline
-  contents <- many1 (try (many spaceChar >> newline >>
-                          many1 spaceChar >> noneOf " \t\n") <|> noneOf "\n")
-  blanklines
-  return $ escapeURI $ trim contents
-
-substKey :: PandocMonad m => RSTParser m ()
-substKey = try $ do
-  string ".."
-  skipMany1 spaceChar
-  (alt,ref) <- withRaw $ trimInlines . mconcat
-                      <$> enclosed (char '|') (char '|') inline
-  res <- B.toList <$> directive'
-  il <- case res of
-             -- use alt unless :alt: attribute on image:
-             [Para [Image attr [Str "image"] (src,tit)]] ->
-                return $ B.imageWith attr src tit alt
-             [Para [Link _ [Image attr [Str "image"] (src,tit)] (src',tit')]] ->
-                return $ B.link src' tit' (B.imageWith attr src tit alt)
-             [Para ils] -> return $ B.fromList ils
-             _          -> mzero
-  let key = toKey $ stripFirstAndLast ref
-  updateState $ \s -> s{ stateSubstitutions =
-                          M.insert key il $ stateSubstitutions s }
-
-anonymousKey :: Monad m => RSTParser m ()
-anonymousKey = try $ do
-  oneOfStrings [".. __:", "__"]
-  src <- targetURI
-  pos <- getPosition
-  let key = toKey $ "_" ++ printf "%09d" (sourceLine pos)
-  updateState $ \s -> s { stateKeys = M.insert key ((src,""), nullAttr) $
-                          stateKeys s }
-
-referenceNames :: PandocMonad m => RSTParser m [String]
-referenceNames = do
-  let rn = try $ do
-             string ".. _"
-             ref <- quotedReferenceName
-                  <|> many (  noneOf ":\n"
-                          <|> try (char '\n' <*
-                                   string "   " <*
-                                   notFollowedBy blankline)
-                          <|> try (char ':' <* lookAhead alphaNum)
-                           )
-             char ':'
-             return ref
-  first <- rn
-  rest  <- many (try (blanklines *> rn))
-  return (first:rest)
-
-regularKey :: PandocMonad m => RSTParser m ()
-regularKey = try $ do
-  -- we allow several references to the same URL, e.g.
-  -- .. _hello:
-  -- .. _goodbye: url.com
-  refs <- referenceNames
-  src <- targetURI
-  guard $ not (null src)
-  let keys = map toKey refs
-  forM_ keys $ \key ->
-    updateState $ \s -> s { stateKeys = M.insert key ((src,""), nullAttr) $
-                            stateKeys s }
-
-anchorDef :: PandocMonad m => RSTParser m [Char]
-anchorDef = try $ do
-  (refs, raw) <- withRaw $ try (referenceNames <* blanklines)
-  forM_ refs $ \rawkey ->
-    updateState $ \s -> s { stateKeys =
-       M.insert (toKey rawkey) (('#':rawkey,""), nullAttr) $ stateKeys s }
-  -- keep this for 2nd round of parsing, where we'll add the divs (anchor)
-  return raw
-
-anchor :: PandocMonad m => RSTParser m Blocks
-anchor = try $ do
-  refs <- referenceNames
-  blanklines
-  b <- block
-  -- put identifier on next block:
-  let addDiv ref = B.divWith (ref, [], [])
-  return $ foldr addDiv b refs
-
-headerBlock :: PandocMonad m => RSTParser m [Char]
-headerBlock = do
-  ((txt, _), raw) <- withRaw (doubleHeader' <|> singleHeader')
-  (ident,_,_) <- registerHeader nullAttr txt
-  let key = toKey (stringify txt)
-  updateState $ \s -> s { stateKeys = M.insert key (('#':ident,""), nullAttr)
-                          $ stateKeys s }
-  return raw
-
-
---
--- tables
---
-
--- General tables TODO:
---  - figure out if leading spaces are acceptable and if so, add
---    support for them
---
--- Simple tables TODO:
---  - column spans
---  - multiline support
---  - ensure that rightmost column span does not need to reach end
---  - require at least 2 columns
---
--- Grid tables TODO:
---  - column spans
-
-dashedLine :: Monad m => Char -> ParserT [Char] st m (Int, Int)
-dashedLine ch = do
-  dashes <- many1 (char ch)
-  sp     <- many (char ' ')
-  return (length dashes, length $ dashes ++ sp)
-
-simpleDashedLines :: Monad m => Char -> ParserT [Char] st m [(Int,Int)]
-simpleDashedLines ch = try $ many1 (dashedLine ch)
-
--- Parse a table row separator
-simpleTableSep :: Monad m => Char -> RSTParser m Char
-simpleTableSep ch = try $ simpleDashedLines ch >> newline
-
--- Parse a table footer
-simpleTableFooter :: Monad m => RSTParser m [Char]
-simpleTableFooter = try $ simpleTableSep '=' >> blanklines
-
--- Parse a raw line and split it into chunks by indices.
-simpleTableRawLine :: Monad m => [Int] -> RSTParser m [String]
-simpleTableRawLine indices = simpleTableSplitLine indices <$> anyLine
-
-simpleTableRawLineWithEmptyCell :: Monad m => [Int] -> RSTParser m [String]
-simpleTableRawLineWithEmptyCell indices = try $ do
-  cs <- simpleTableRawLine indices
-  let isEmptyCell = all (\c -> c == ' ' || c == '\t')
-  guard $ any isEmptyCell cs
-  return cs
-
--- Parse a table row and return a list of blocks (columns).
-simpleTableRow :: PandocMonad m => [Int] -> RSTParser m [Blocks]
-simpleTableRow indices = do
-  notFollowedBy' simpleTableFooter
-  firstLine <- simpleTableRawLine indices
-  conLines  <- many $ simpleTableRawLineWithEmptyCell indices
-  let cols = map unlines . transpose $ firstLine : conLines ++
-                                 [replicate (length indices) ""
-                                   | not (null conLines)]
-  mapM (parseFromString' parseBlocks) cols
-
-simpleTableSplitLine :: [Int] -> String -> [String]
-simpleTableSplitLine indices line =
-  map trimr
-  $ tail $ splitByIndices (init indices) line
-
-simpleTableHeader :: PandocMonad m
-                  => Bool  -- ^ Headerless table
-                  -> RSTParser m ([Blocks], [Alignment], [Int])
-simpleTableHeader headless = try $ do
-  optional blanklines
-  rawContent  <- if headless
-                    then return ""
-                    else simpleTableSep '=' >> anyLine
-  dashes      <- simpleDashedLines '=' <|> simpleDashedLines '-'
-  newline
-  let lines'   = map snd dashes
-  let indices  = scanl (+) 0 lines'
-  let aligns   = replicate (length lines') AlignDefault
-  let rawHeads = if headless
-                    then replicate (length dashes) ""
-                    else simpleTableSplitLine indices rawContent
-  heads <- mapM ( (parseFromString' (mconcat <$> many plain)) . trim) rawHeads
-  return (heads, aligns, indices)
-
--- Parse a simple table.
-simpleTable :: PandocMonad m
-            => Bool  -- ^ Headerless table
-            -> RSTParser m Blocks
-simpleTable headless = do
-  let wrapIdFst (a, b, c) = (Identity a, b, c)
-      wrapId = fmap Identity
-  tbl <- runIdentity <$> tableWith
-           (wrapIdFst <$> simpleTableHeader headless)
-           (wrapId <$> simpleTableRow)
-           sep simpleTableFooter
-  -- Simple tables get 0s for relative column widths (i.e., use default)
-  case B.toList tbl of
-       [Table c a _w h l]  -> return $ B.singleton $
-                                 Table c a (replicate (length a) 0) h l
-       _ ->
-         throwError $ PandocShouldNeverHappenError
-            "tableWith returned something unexpected"
- where
-  sep = return () -- optional (simpleTableSep '-')
-
-gridTable :: PandocMonad m
-          => Bool -- ^ Headerless table
-          -> RSTParser m Blocks
-gridTable headerless = runIdentity <$>
-  gridTableWith (Identity <$> parseBlocks) headerless
-
-table :: PandocMonad m => RSTParser m Blocks
-table = gridTable False <|> simpleTable False <|>
-        gridTable True  <|> simpleTable True <?> "table"
-
---
--- inline
---
-
-inline :: PandocMonad m => RSTParser m Inlines
-inline = choice [ note          -- can start with whitespace, so try before ws
-                , whitespace
-                , link
-                , str
-                , endline
-                , strong
-                , emph
-                , code
-                , subst
-                , interpretedRole
-                , smart
-                , hyphens
-                , escapedChar
-                , symbol ] <?> "inline"
-
-parseInlineFromString :: PandocMonad m => String -> RSTParser m Inlines
-parseInlineFromString = parseFromString' (trimInlines . mconcat <$> many inline)
-
-hyphens :: Monad m => RSTParser m Inlines
-hyphens = do
-  result <- many1 (char '-')
-  optional endline
-  -- don't want to treat endline after hyphen or dash as a space
-  return $ B.str result
-
-escapedChar :: Monad m => ParserT [Char] st m Inlines
-escapedChar = do c <- escaped anyChar
-                 return $ if c == ' ' || c == '\n' || c == '\r'
-                             -- '\ ' is null in RST
-                             then mempty
-                             else B.str [c]
-
-symbol :: Monad m => RSTParser m Inlines
-symbol = do
-  result <- oneOf specialChars
-  return $ B.str [result]
-
--- parses inline code, between codeStart and codeEnd
-code :: Monad m => RSTParser m Inlines
-code = try $ do
-  string "``"
-  result <- manyTill anyChar (try (string "``"))
-  return $ B.code
-         $ trim $ unwords $ lines result
-
--- succeeds only if we're not right after a str (ie. in middle of word)
-atStart :: Monad m => RSTParser m a -> RSTParser m a
-atStart p = do
-  pos <- getPosition
-  st <- getState
-  -- single quote start can't be right after str
-  guard $ stateLastStrPos st /= Just pos
-  p
-
-emph :: PandocMonad m => RSTParser m Inlines
-emph = B.emph . trimInlines . mconcat <$>
-         enclosed (atStart $ char '*') (char '*') inline
-
-strong :: PandocMonad m => RSTParser m Inlines
-strong = B.strong . trimInlines . mconcat <$>
-          enclosed (atStart $ string "**") (try $ string "**") inline
-
--- Note, this doesn't precisely implement the complex rule in
--- http://docutils.sourceforge.net/docs/ref/rst/restructuredtext.html#inline-markup-recognition-rules
--- but it should be good enough for most purposes
---
--- TODO:
---  - Classes are silently discarded in addNewRole
---  - Lacks sensible implementation for title-reference (which is the default)
---  - Allows direct use of the :raw: role, rST only allows inherited use.
-interpretedRole :: PandocMonad m => RSTParser m Inlines
-interpretedRole = try $ do
-  (role, contents) <- roleBefore <|> roleAfter
-  renderRole contents Nothing role nullAttr
-
-renderRole :: PandocMonad m
-           => String -> Maybe String -> String -> Attr -> RSTParser m Inlines
-renderRole contents fmt role attr = case role of
-    "sup"  -> return $ B.superscript $ B.str contents
-    "superscript" -> return $ B.superscript $ B.str contents
-    "sub"  -> return $ B.subscript $ B.str contents
-    "subscript"  -> return $ B.subscript $ B.str contents
-    "emphasis" -> return $ B.emph $ B.str contents
-    "strong" -> return $ B.strong $ B.str contents
-    "rfc-reference" -> return $ rfcLink contents
-    "RFC" -> return $ rfcLink contents
-    "pep-reference" -> return $ pepLink contents
-    "PEP" -> return $ pepLink contents
-    "literal" -> return $ B.codeWith attr contents
-    "math" -> return $ B.math contents
-    "title-reference" -> titleRef contents
-    "title" -> titleRef contents
-    "t" -> titleRef contents
-    "code" -> return $ B.codeWith (addClass "sourceCode" attr) contents
-    "span" -> return $ B.spanWith attr $ B.str contents
-    "raw" -> return $ B.rawInline (fromMaybe "" fmt) contents
-    custom -> do
-        customRoles <- stateRstCustomRoles <$> getState
-        case M.lookup custom customRoles of
-            Just (newRole, newFmt, newAttr) ->
-                renderRole contents newFmt newRole newAttr
-            Nothing -> -- undefined role
-                return $ B.spanWith ("",[],[("role",role)]) (B.str contents)
- where
-   titleRef ref = return $ B.str ref -- FIXME: Not a sensible behaviour
-   rfcLink rfcNo = B.link rfcUrl ("RFC " ++ rfcNo) $ B.str ("RFC " ++ rfcNo)
-     where rfcUrl = "http://www.faqs.org/rfcs/rfc" ++ rfcNo ++ ".html"
-   pepLink pepNo = B.link pepUrl ("PEP " ++ pepNo) $ B.str ("PEP " ++ pepNo)
-     where padNo = replicate (4 - length pepNo) '0' ++ pepNo
-           pepUrl = "http://www.python.org/dev/peps/pep-" ++ padNo ++ "/"
-
-addClass :: String -> Attr -> Attr
-addClass c (ident, classes, keyValues) = (ident, union classes [c], keyValues)
-
-roleName :: PandocMonad m => RSTParser m String
-roleName = many1 (letter <|> char '-')
-
-roleMarker :: PandocMonad m => RSTParser m String
-roleMarker = char ':' *> roleName <* char ':'
-
-roleBefore :: PandocMonad m => RSTParser m (String,String)
-roleBefore = try $ do
-  role <- roleMarker
-  contents <- unmarkedInterpretedText
-  return (role,contents)
-
-roleAfter :: PandocMonad m => RSTParser m (String,String)
-roleAfter = try $ do
-  contents <- unmarkedInterpretedText
-  role <- roleMarker <|> (stateRstDefaultRole <$> getState)
-  return (role,contents)
-
-unmarkedInterpretedText :: PandocMonad m => RSTParser m [Char]
-unmarkedInterpretedText = enclosed (atStart $ char '`') (char '`') anyChar
-
-whitespace :: PandocMonad m => RSTParser m Inlines
-whitespace = B.space <$ skipMany1 spaceChar <?> "whitespace"
-
-str :: Monad m => RSTParser m Inlines
-str = do
-  let strChar = noneOf ("\t\n " ++ specialChars)
-  result <- many1 strChar
-  updateLastStrPos
-  return $ B.str result
-
--- an endline character that can be treated as a space, not a structural break
-endline :: Monad m => RSTParser m Inlines
-endline = try $ do
-  newline
-  notFollowedBy blankline
-  -- parse potential list-starts at beginning of line differently in a list:
-  st <- getState
-  when ((stateParserContext st) == ListItemState) $ notFollowedBy (anyOrderedListMarker >> spaceChar) >>
-          notFollowedBy' bulletListStart
-  return B.softbreak
-
---
--- links
---
-
-link :: PandocMonad m => RSTParser m Inlines
-link = choice [explicitLink, referenceLink, autoLink]  <?> "link"
-
-explicitLink :: PandocMonad m => RSTParser m Inlines
-explicitLink = try $ do
-  char '`'
-  notFollowedBy (char '`') -- `` marks start of inline code
-  label' <- trimInlines . mconcat <$>
-             manyTill (notFollowedBy (char '`') >> inline) (char '<')
-  src <- trim <$> manyTill (noneOf ">\n") (char '>')
-  skipSpaces
-  string "`_"
-  optional $ char '_' -- anonymous form
-  let label'' = if label' == mempty
-                   then B.str src
-                   else label'
-  -- `link <google_>` is a reference link to _google!
-  ((src',tit),attr) <- case reverse src of
-                          '_':xs -> lookupKey [] (toKey (reverse xs))
-                          _      -> return ((src, ""), nullAttr)
-  return $ B.linkWith attr (escapeURI src') tit label''
-
-citationName :: PandocMonad m => RSTParser m String
-citationName = do
-  raw <- citationMarker
-  return $ "[" ++ raw ++ "]"
-
-referenceLink :: PandocMonad m => RSTParser m Inlines
-referenceLink = try $ do
-  ref <- (referenceName <|> citationName) <* char '_'
-  let label' = B.text ref
-  let isAnonKey (Key ('_':_)) = True
-      isAnonKey _             = False
-  state <- getState
-  let keyTable = stateKeys state
-  key <- option (toKey ref) $
-                do char '_'
-                   let anonKeys = sort $ filter isAnonKey $ M.keys keyTable
-                   case anonKeys of
-                        []    -> mzero
-                        (k:_) -> return k
-  ((src,tit), attr) <- lookupKey [] key
-  -- if anonymous link, remove key so it won't be used again
-  when (isAnonKey key) $ updateState $ \s ->
-                          s{ stateKeys = M.delete key keyTable }
-  return $ B.linkWith attr src tit label'
-
--- We keep a list of oldkeys so we can detect lookup loops.
-lookupKey :: PandocMonad m
-          => [Key] -> Key -> RSTParser m ((String, String), Attr)
-lookupKey oldkeys key = do
-  pos <- getPosition
-  state <- getState
-  let keyTable = stateKeys state
-  case M.lookup key keyTable of
-       Nothing  -> do
-         let Key key' = key
-         logMessage $ ReferenceNotFound key' pos
-         return (("",""),nullAttr)
-       -- check for keys of the form link_, which need to be resolved:
-       Just ((u@(_:_),""),_) | last u == '_' -> do
-         let rawkey = init u
-         let newkey = toKey rawkey
-         if newkey `elem` oldkeys
-            then do
-              logMessage $ CircularReference rawkey pos
-              return (("",""),nullAttr)
-            else lookupKey (key:oldkeys) newkey
-       Just val -> return val
-
-autoURI :: Monad m => RSTParser m Inlines
-autoURI = do
-  (orig, src) <- uri
-  return $ B.link src "" $ B.str orig
-
-autoEmail :: Monad m => RSTParser m Inlines
-autoEmail = do
-  (orig, src) <- emailAddress
-  return $ B.link src "" $ B.str orig
-
-autoLink :: PandocMonad m => RSTParser m Inlines
-autoLink = autoURI <|> autoEmail
-
-subst :: PandocMonad m => RSTParser m Inlines
-subst = try $ do
-  (_,ref) <- withRaw $ enclosed (char '|') (char '|') inline
-  state <- getState
-  let substTable = stateSubstitutions state
-  let key = toKey $ stripFirstAndLast ref
-  case M.lookup key substTable of
-       Nothing     -> do
-         pos <- getPosition
-         logMessage $ ReferenceNotFound (show key) pos
-         return mempty
-       Just target -> return target
-
-note :: PandocMonad m => RSTParser m Inlines
-note = try $ do
-  optional whitespace
-  ref <- noteMarker
-  char '_'
-  state <- getState
-  let notes = stateNotes state
-  case lookup ref notes of
-    Nothing   -> do
-      pos <- getPosition
-      logMessage $ ReferenceNotFound ref pos
-      return mempty
-    Just raw  -> do
-      -- We temporarily empty the note list while parsing the note,
-      -- so that we don't get infinite loops with notes inside notes...
-      -- Note references inside other notes are allowed in reST, but
-      -- not yet in this implementation.
-      updateState $ \st -> st{ stateNotes = [] }
-      contents <- parseFromString' parseBlocks raw
-      let newnotes = if (ref == "*" || ref == "#") -- auto-numbered
-                        -- delete the note so the next auto-numbered note
-                        -- doesn't get the same contents:
-                        then deleteFirstsBy (==) notes [(ref,raw)]
-                        else notes
-      updateState $ \st -> st{ stateNotes = newnotes }
-      return $ B.note contents
-
-smart :: PandocMonad m => RSTParser m Inlines
-smart = do
-  guardEnabled Ext_smart
-  doubleQuoted <|> singleQuoted <|>
-    choice [apostrophe, dash, ellipses]
-
-singleQuoted :: PandocMonad m => RSTParser m Inlines
-singleQuoted = try $ do
-  singleQuoteStart
-  withQuoteContext InSingleQuote $
-    B.singleQuoted . trimInlines . mconcat <$>
-      many1Till inline singleQuoteEnd
-
-doubleQuoted :: PandocMonad m => RSTParser m Inlines
-doubleQuoted = try $ do
-  doubleQuoteStart
-  withQuoteContext InDoubleQuote $
-    B.doubleQuoted . trimInlines . mconcat <$>
-      many1Till inline doubleQuoteEnd
+{-# LANGUAGE ViewPatterns        #-}
+{- |
+   Module      : Text.Pandoc.Readers.RST
+   Copyright   : Copyright (C) 2006-2024 John MacFarlane
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : John MacFarlane <jgm@berkeley.edu>
+   Stability   : alpha
+   Portability : portable
+
+Conversion from reStructuredText to 'Pandoc' document.
+-}
+module Text.Pandoc.Readers.RST ( readRST ) where
+import Control.Arrow (second)
+import Control.Monad (forM_, guard, liftM, mplus, mzero, when, unless, void)
+import Control.Monad.Except (throwError)
+import Control.Monad.Identity (Identity (..))
+import Data.Char (isHexDigit, isSpace, toUpper, isAlphaNum, generalCategory,
+                  GeneralCategory(OpenPunctuation, InitialQuote, FinalQuote,
+                                  DashPunctuation, OtherSymbol))
+import Data.List (deleteFirstsBy, elemIndex, nub, partition, sort, transpose)
+import qualified Data.Map as M
+import Data.Maybe (fromMaybe, maybeToList, isJust, isNothing, catMaybes)
+import Data.Sequence (ViewR (..), viewr)
+import Data.Text (Text)
+import qualified Data.Text as T
+import Text.Printf (printf)
+import Text.Pandoc.Builder (Blocks, Inlines, fromList, setMeta, trimInlines)
+import qualified Text.Pandoc.Builder as B
+import Text.Pandoc.Class (PandocMonad, readFileFromDirs, fetchItem, getTimestamp)
+import Text.Pandoc.CSV (CSVOptions (..), defaultCSVOptions, parseCSV)
+import Text.Pandoc.Definition
+import Text.Pandoc.Error
+import Text.Pandoc.ImageSize (lengthToDim, scaleDimension)
+import Text.Pandoc.Logging
+import Text.Pandoc.Options
+import Text.Pandoc.Parsing
+import Text.Pandoc.Shared
+import Text.Pandoc.URI
+import Text.Pandoc.Walk (walkM)
+import qualified Text.Pandoc.UTF8 as UTF8
+import Data.Time.Format
+import System.FilePath (takeDirectory)
+
+-- TODO:
+-- [ ] .. parsed-literal
+
+-- | Parse reStructuredText string and return Pandoc document.
+readRST :: (PandocMonad m, ToSources a)
+        => ReaderOptions -- ^ Reader options
+        -> a
+        -> m Pandoc
+readRST opts s = do
+  parsed <- readWithM parseRST def{ stateOptions = opts }
+               (ensureFinalNewlines 2 (toSources s))
+  case parsed of
+    Right result -> return result
+    Left e       -> throwError e
+
+type RSTParser m = ParsecT Sources ParserState m
+
+--
+-- Constants and data structure definitions
+---
+
+bulletListMarkers :: [Char]
+bulletListMarkers = "*+-•‣⁃"
+
+underlineChars :: [Char]
+underlineChars = "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~"
+
+-- treat these as potentially non-text when parsing inline:
+specialChars :: [Char]
+specialChars = "\\`|*_<>$:/[]{}()-.\"'\8216\8217\8220\8221"
+
+--
+-- parsing documents
+--
+
+isHeader :: Int -> Block -> Bool
+isHeader n (Header x _ _) = x == n
+isHeader _ _              = False
+
+-- | Promote all headers in a list of blocks.  (Part of
+-- title transformation for RST.)
+promoteHeaders :: Int -> [Block] -> [Block]
+promoteHeaders num (Header level attr text:rest) =
+    Header (level - num) attr text:promoteHeaders num rest
+promoteHeaders num (other:rest) = other:promoteHeaders num rest
+promoteHeaders _   [] = []
+
+-- | If list of blocks starts with a header (or a header and subheader)
+-- of level that are not found elsewhere, return it as a title and
+-- promote all the other headers.  Also process a definition list right
+-- after the title block as metadata.
+titleTransform :: ([Block], Meta)  -- ^ list of blocks, metadata
+               -> ([Block], Meta)  -- ^ modified list of blocks, metadata
+titleTransform (bs, meta) =
+  let (bs', meta') =
+       case bs of
+          (Header 1 _ head1:Header 2 _ head2:rest)
+           | not (any (isHeader 1) rest || any (isHeader 2) rest) -> -- tit/sub
+            (promoteHeaders 2 rest, setMeta "title" (fromList head1) $
+              setMeta "subtitle" (fromList head2) meta)
+          (Header 1 _ head1:rest)
+           | not (any (isHeader 1) rest) -> -- title only
+            (promoteHeaders 1 rest,
+                setMeta "title" (fromList head1) meta)
+          _ -> (bs, meta)
+  in   case bs' of
+          (DefinitionList ds : rest) ->
+            (rest, metaFromDefList ds meta')
+          _ -> (bs', meta')
+
+metaFromDefList :: [([Inline], [[Block]])] -> Meta -> Meta
+metaFromDefList ds meta = adjustAuthors $ foldr f meta ds
+ where f (k,v) =
+         case v of
+           [[Plain ils]] ->  setMeta (T.toLower (stringify k)) $ MetaInlines ils
+           _ -> setMeta (T.toLower (stringify k)) $ mconcat $ map fromList v
+       adjustAuthors (Meta metamap) = Meta $ M.adjust splitAuthors "author"
+                                           $ M.mapKeys (\k ->
+                                                 if k == "authors"
+                                                    then "author"
+                                                    else k) metamap
+       splitAuthors (MetaInlines xs)  = MetaList $ map MetaInlines
+                                                 $ splitAuthors' xs
+       splitAuthors x                 = x
+       splitAuthors'                  = map normalizeSpaces .
+                                         splitOnSemi . concatMap factorSemi
+       normalizeSpaces                = reverse . dropWhile isSp . reverse .
+                                         dropWhile isSp
+       isSp Space     = True
+       isSp SoftBreak = True
+       isSp LineBreak = True
+       isSp _         = False
+       splitOnSemi                    = splitBy (==Str ";")
+       factorSemi (Str "")            = []
+       factorSemi (Str s)             = case T.break (==';') s of
+                                          (xs,"") -> [Str xs]
+                                          (xs,T.uncons -> Just (';',ys)) -> Str xs : Str ";" :
+                                            factorSemi (Str ys)
+                                          (xs,ys) -> Str xs :
+                                            factorSemi (Str ys)
+       factorSemi x                   = [x]
+
+parseRST :: PandocMonad m => RSTParser m Pandoc
+parseRST = do
+  standalone <- getOption readerStandalone
+  optional blanklines -- skip blank lines at beginning of file
+  blocks <- B.toList <$> parseBlocks
+  citations <- sort . M.toList . stateCitations <$> getState
+  citationItems <- mapM parseCitation citations
+  let refBlock = [Div ("citations",[],[]) $
+                 B.toList $ B.definitionList citationItems | not (null citationItems)]
+  state <- getState
+  let meta = stateMeta state
+  let (blocks', meta') = if standalone
+                            then titleTransform (blocks, meta)
+                            else (blocks, meta)
+  let reversedNotes = stateNotes state
+  updateState $ \s -> s { stateNotes = reverse reversedNotes }
+  doc <- walkM resolveReferences =<<
+         walkM resolveBlockSubstitutions
+         (Pandoc meta' (blocks' ++ refBlock))
+  reportLogMessages
+  return doc
+
+resolveBlockSubstitutions :: PandocMonad m => Block -> RSTParser m Block
+resolveBlockSubstitutions x@(Para [Link _attr _ (s,_)])
+  | Just ref <- T.stripPrefix "##SUBST##" s = do
+          substTable <- stateSubstitutions <$> getState
+          let key@(Key key') = toKey $ stripFirstAndLast ref
+          case M.lookup key substTable of
+               Nothing     -> do
+                 pos <- getPosition
+                 logMessage $ ReferenceNotFound (tshow key') pos
+                 return x
+               Just target -> case
+                 B.toList target of
+                   [bl] -> return bl
+                   bls -> return $ Div nullAttr bls
+resolveBlockSubstitutions x = return x
+
+resolveReferences :: PandocMonad m => Inline -> RSTParser m Inline
+resolveReferences x@(Link _ ils (s,_))
+  | Just ref <- T.stripPrefix "##REF##" s = do
+      let isAnonKey (Key (T.uncons -> Just ('_',_))) = True
+          isAnonKey _                                = False
+      state <- getState
+      let keyTable = stateKeys state
+      let anonKeys = sort $ filter isAnonKey $ M.keys keyTable
+      key <-  if ref == "_" -- anonymous key
+                then
+                  case anonKeys of
+                    []    -> mzero -- TODO log?
+                    (k:_) -> return k
+                else return $ toKey ref
+      ((src,tit), attr) <- lookupKey [] key
+      -- if anonymous link, remove key so it won't be used again
+      when (isAnonKey key) $ updateState $ \st ->
+                              st{ stateKeys = M.delete key keyTable }
+      return $ Link attr ils (src, tit)
+  | Just ref <- T.stripPrefix "##NOTE##" s = do
+      state <- getState
+      let notes = stateNotes state
+      case lookup ref notes of
+        Nothing   -> do
+          pos <- getPosition
+          logMessage $ ReferenceNotFound ref pos
+          return x
+        Just raw  -> do
+          -- We temporarily empty the note list while parsing the note,
+          -- so that we don't get infinite loops with notes inside notes...
+          -- Note references inside other notes are allowed in reST, but
+          -- not yet in this implementation.
+          updateState $ \st -> st{ stateNotes = [] }
+          contents <- parseFromString' parseBlocks raw
+          let newnotes = if ref == "*" || ref == "#" -- auto-numbered
+                            -- delete the note so the next auto-numbered note
+                            -- doesn't get the same contents:
+                            then deleteFirstsBy (==) notes [(ref,raw)]
+                            else notes
+          updateState $ \st -> st{ stateNotes = newnotes }
+          return $ Note (B.toList contents)
+  | Just ref <- T.stripPrefix "##SUBST##" s = do
+          substTable <- stateSubstitutions <$> getState
+          let key@(Key key') = toKey $ stripFirstAndLast ref
+          case M.lookup key substTable of
+               Nothing     -> do
+                 pos <- getPosition
+                 logMessage $ ReferenceNotFound (tshow key') pos
+                 return x
+               Just target -> case
+                 B.toList target of
+                   [Para [t]] -> return t
+                   [Para xs] -> return $ Span nullAttr xs
+                   bls -> return $ Span nullAttr $ blocksToInlines bls
+  | otherwise = return x
+resolveReferences x = return x
+
+parseCitation :: PandocMonad m
+              => (Text, Text) -> RSTParser m (Inlines, [Blocks])
+parseCitation (ref, raw) = do
+  contents <- parseFromString' parseBlocks raw
+  return (B.spanWith (ref, ["citation-label"], []) (B.str ref),
+           [contents])
+
+
+--
+-- parsing blocks
+--
+
+parseBlocks :: PandocMonad m => RSTParser m Blocks
+parseBlocks = mconcat <$> manyTill block eof
+
+block :: PandocMonad m => RSTParser m Blocks
+block = choice [ codeBlock
+               , blockQuote
+               , fieldList
+               , optionList
+               , referenceKey
+               , noteBlock
+               , citationBlock
+               , directive
+               , anchor
+               , comment
+               , header
+               , hrule
+               , lineBlock     -- must go before definitionList
+               , table
+               , list
+               , lhsCodeBlock
+               , para
+               , mempty <$ blanklines
+               ] <?> "block"
+
+--
+-- field list
+--
+
+rawFieldListItem :: Monad m => Int -> RSTParser m (Text, Text)
+rawFieldListItem minIndent = try $ do
+  indent <- length <$> many (char ' ')
+  guard $ indent >= minIndent
+  char ':'
+  name <- many1TillChar (noneOf "\n") (char ':')
+  (void (lookAhead newline)) <|> skipMany1 spaceChar
+  first <- anyLine
+  rest <- option "" $ try $ do lookAhead (count indent (char ' ') >> spaceChar)
+                               indentedBlock
+  let raw = (if T.null first then "" else first <> "\n") <> rest <>
+            (if T.null first && T.null rest then "" else "\n")
+  return (name, raw)
+
+fieldListItem :: PandocMonad m => Int -> RSTParser m (Inlines, [Blocks])
+fieldListItem minIndent = try $ do
+  (name, raw) <- rawFieldListItem minIndent
+  term <- parseInlineFromText name
+  contents <- parseFromString' parseBlocks raw
+  optional blanklines
+  let defn = case B.toList contents of
+                [Para ils] -> [B.plain $ B.fromList ils] -- see #7766
+                _ -> [contents]
+  return (term, defn)
+
+fieldList :: PandocMonad m => RSTParser m Blocks
+fieldList = try $ do
+  indent <- length <$> lookAhead (many spaceChar)
+  items <- many1 $ fieldListItem indent
+  case items of
+     []     -> return mempty
+     items' -> return $ B.definitionList items'
+
+optionList :: PandocMonad m => RSTParser m Blocks
+optionList = B.definitionList <$> many1 optionListItem
+
+optionListItem :: PandocMonad m => RSTParser m (Inlines, [Blocks])
+optionListItem = try $ do
+  opts <- snd <$> withRaw (do
+     let anyOpt = shortOpt <|> longOpt <|> dosOpt
+     anyOpt
+     many $ try (char ',' <* many spaceChar *> anyOpt))
+  -- at least two spaces
+  rawfirst <- try (char ' ' *> many1 (char ' ') *> anyLineNewline)
+                    <|> try (mempty <$ skipMany spaceChar <* newline)
+  bodyElements <- do
+    raw <- option "" indentedBlock
+    parseFromString' parseBlocks $ (rawfirst <> raw) <> "\n\n"
+  optional blanklines
+  pure (B.code opts, [bodyElements])
+
+shortOpt :: PandocMonad m => RSTParser m ()
+shortOpt = try $ do
+  char '-'
+  alphaNum
+  optional $ try (optional (char ' ') *> optArg)
+
+optArg :: PandocMonad m => RSTParser m ()
+optArg = do
+  c <- letter <|> char '<'
+  if c == '<'
+     then void $ manyTill (noneOf "<>") (char '>')
+     else skipMany (alphaNum <|> char '_' <|> char '-')
+
+longOpt :: PandocMonad m => RSTParser m ()
+longOpt = try $ do
+  char '-'
+  char '-'
+  alphaNum
+  skipMany1 (alphaNum <|> char '-' <|> char '_')
+  optional $ try (oneOf " =" *> optArg)
+
+dosOpt :: PandocMonad m => RSTParser m ()
+dosOpt = try $ do
+  char '/'
+  alphaNum <|> char '?'
+  optional $ try (char ' ' *> optArg)
+
+--
+-- line block
+--
+
+lineBlock :: PandocMonad m => RSTParser m Blocks
+lineBlock = try $ do
+  lines' <- lineBlockLines
+  lines'' <- mapM parseInlineFromText lines'
+  return $ B.lineBlock lines''
+
+lineBlockDirective :: PandocMonad m => Text -> RSTParser m Blocks
+lineBlockDirective body = do
+  lines' <- mapM parseInlineFromText $ T.lines $ stripTrailingNewlines body
+  return $ B.lineBlock lines'
+
+--
+-- paragraph block
+--
+
+-- note: paragraph can end in a :: starting a code block
+para :: PandocMonad m => RSTParser m Blocks
+para = try $ do
+  result <- trimInlines . mconcat <$> many1 inline
+  option (B.plain result) $ try $ do
+    newline
+    blanklines
+    case viewr (B.unMany result) of
+         ys :> Str xs | "::" `T.isSuffixOf` xs -> do
+              raw <- option mempty codeBlockBody
+              return $ B.para (B.Many ys <> B.str (T.take (T.length xs - 1) xs))
+                         <> raw
+         _ -> return (B.para result)
+
+plain :: PandocMonad m => RSTParser m Blocks
+plain = B.plain . trimInlines . mconcat <$> many1 inline
+
+--
+-- header blocks
+--
+
+header :: PandocMonad m => RSTParser m Blocks
+header = doubleHeader <|> singleHeader <?> "header"
+
+-- a header with lines on top and bottom
+doubleHeader :: PandocMonad m => RSTParser m Blocks
+doubleHeader = do
+  (txt, c) <- doubleHeader'
+  -- check to see if we've had this kind of header before.
+  -- if so, get appropriate level.  if not, add to list.
+  state <- getState
+  let headerTable = stateHeaderTable state
+  let (headerTable',level) = case elemIndex (DoubleHeader c) headerTable of
+        Just ind -> (headerTable, ind + 1)
+        Nothing  -> (headerTable ++ [DoubleHeader c], length headerTable + 1)
+  setState (state { stateHeaderTable = headerTable' })
+  attr@(ident,_,_) <- registerHeader nullAttr txt
+  let key = toKey (stringify txt)
+  updateState $ \s ->
+    s { stateKeys = M.insert key (("#" <> ident,""), nullAttr) $ stateKeys s }
+  return $ B.headerWith attr level txt
+
+doubleHeader' :: PandocMonad m => RSTParser m (Inlines, Char)
+doubleHeader' = try $ do
+  c <- oneOf underlineChars
+  rest <- many (char c)  -- the top line
+  let lenTop = length (c:rest)
+  skipSpaces
+  newline
+  txt <- trimInlines . mconcat <$> many1 (notFollowedBy blankline >> inline)
+  pos <- getPosition
+  let len = sourceColumn pos - 1
+  when (len > lenTop) $ Prelude.fail "title longer than border"
+  blankline              -- spaces and newline
+  count lenTop (char c)  -- the bottom line
+  blanklines
+  return (txt, c)
+
+-- a header with line on the bottom only
+singleHeader :: PandocMonad m => RSTParser m Blocks
+singleHeader = do
+  (txt, c) <- singleHeader'
+  state <- getState
+  let headerTable = stateHeaderTable state
+  let (headerTable',level) = case elemIndex (SingleHeader c) headerTable of
+        Just ind -> (headerTable, ind + 1)
+        Nothing  -> (headerTable ++ [SingleHeader c], length headerTable + 1)
+  setState (state { stateHeaderTable = headerTable' })
+  attr@(ident,_,_) <- registerHeader nullAttr txt
+  let key = toKey (stringify txt)
+  updateState $ \s ->
+    s { stateKeys = M.insert key (("#" <> ident,""), nullAttr) $ stateKeys s }
+  return $ B.headerWith attr level txt
+
+singleHeader' :: PandocMonad m => RSTParser m (Inlines, Char)
+singleHeader' = try $ do
+  notFollowedBy' whitespace
+  lookAhead $ anyLine >> oneOf underlineChars
+  txt <- trimInlines . mconcat <$> many1 (notFollowedBy blankline >> inline)
+  pos <- getPosition
+  let len = sourceColumn pos - 1
+  blankline
+  c <- oneOf underlineChars
+  count (len - 1) (char c)
+  many (char c)
+  blanklines
+  return (txt, c)
+
+--
+-- hrule block
+--
+
+hrule :: Monad m => ParsecT Sources st m Blocks
+hrule = try $ do
+  chr <- oneOf underlineChars
+  count 3 (char chr)
+  skipMany (char chr)
+  blankline
+  blanklines
+  return B.horizontalRule
+
+--
+-- code blocks
+--
+
+-- read a line indented by a given string
+indentedLine :: (HasReaderOptions st, Monad m)
+             => Int -> ParsecT Sources st m Text
+indentedLine indents = try $ do
+  lookAhead spaceChar
+  gobbleAtMostSpaces indents
+  anyLine
+
+-- one or more indented lines, possibly separated by blank lines.
+-- any amount of indentation will work.
+indentedBlock :: (HasReaderOptions st, Monad m)
+              => ParsecT Sources st m Text
+indentedBlock = try $ do
+  indents <- length <$> lookAhead (many1 spaceChar)
+  lns <- many1 $ try $ do b <- option "" blanklines
+                          l <- indentedLine indents
+                          return (b <> l)
+  optional blanklines
+  return $ T.unlines lns
+
+quotedBlock :: Monad m => ParsecT Sources st m Text
+quotedBlock = try $ do
+    quote <- lookAhead $ oneOf "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~"
+    lns <- many1 $ lookAhead (char quote) >> anyLine
+    optional blanklines
+    return $ T.unlines lns
+
+codeBlockStart :: Monad m => ParsecT Sources st m Char
+codeBlockStart = string "::" >> blankline >> blankline
+
+codeBlock :: Monad m => ParsecT Sources ParserState m Blocks
+codeBlock = try $ codeBlockStart >> codeBlockBody
+
+codeBlockBody :: Monad m => ParsecT Sources ParserState m Blocks
+codeBlockBody = do
+  lang <- stateRstHighlight <$> getState
+  try $ B.codeBlockWith ("", maybeToList lang, []) . stripTrailingNewlines <$>
+                (indentedBlock <|> quotedBlock)
+
+lhsCodeBlock :: Monad m => RSTParser m Blocks
+lhsCodeBlock = try $ do
+  getPosition >>= guard . (==1) . sourceColumn
+  guardEnabled Ext_literate_haskell
+  optional codeBlockStart
+  lns <- latexCodeBlock <|> birdCodeBlock
+  blanklines
+  return $ B.codeBlockWith ("", ["haskell","literate"], [])
+         $ T.intercalate "\n" lns
+
+latexCodeBlock :: Monad m => ParsecT Sources st m [Text]
+latexCodeBlock = try $ do
+  try (latexBlockLine "\\begin{code}")
+  many1Till anyLine (try $ latexBlockLine "\\end{code}")
+ where
+  latexBlockLine s = skipMany spaceChar >> string s >> blankline
+
+birdCodeBlock :: Monad m => ParsecT Sources st m [Text]
+birdCodeBlock = filterSpace <$> many1 birdTrackLine
+  where filterSpace lns =
+            -- if (as is normal) there is always a space after >, drop it
+            if all (\ln -> T.null ln || T.take 1 ln == " ") lns
+               then map (T.drop 1) lns
+               else lns
+
+birdTrackLine :: Monad m => ParsecT Sources st m Text
+birdTrackLine = char '>' >> anyLine
+
+--
+-- block quotes
+--
+
+blockQuote :: PandocMonad m => RSTParser m Blocks
+blockQuote = do
+  raw <- indentedBlock
+  -- parse the extracted block, which may contain various block elements:
+  contents <- parseFromString' parseBlocks $ raw <> "\n\n"
+  return $ B.blockQuote contents
+
+{-
+Unsupported options for include:
+tab-width
+encoding
+-}
+
+includeDirective :: PandocMonad m
+                 => Text
+                 -> [(Text, Text)]
+                 -> Text
+                 -> RSTParser m Blocks
+includeDirective top fields body = do
+  let f = T.unpack $ trim top
+  guard $ not $ null f
+  guard $ T.null (trim body)
+  let startLine = lookup "start-line" fields >>= safeRead
+  let endLine = lookup "end-line" fields >>= safeRead
+  let classes =  maybe [] T.words (lookup "class" fields)
+  let ident = maybe "" trimr $ lookup "name" fields
+  let parser =
+       case lookup "code" fields `mplus` lookup "literal" fields of
+         Just lang ->
+           (codeblock ident classes fields (trimr lang) False
+            . sourcesToText) <$> getInput
+         Nothing   -> parseBlocks
+  let isLiteral = isJust (lookup "code" fields `mplus` lookup "literal" fields)
+  let selectLines =
+        (case trim <$> lookup "end-before" fields of
+                         Just patt -> takeWhile (not . (patt `T.isInfixOf`))
+                         Nothing   -> id) .
+        (case trim <$> lookup "start-after" fields of
+                         Just patt -> drop 1 .
+                                        dropWhile (not . (patt `T.isInfixOf`))
+                         Nothing   -> id)
+
+  let toStream t =
+        Sources [(initialPos f,
+                   (T.unlines . selectLines . T.lines $ t) <>
+                    if isLiteral then mempty else "\n")]  -- see #7436
+  currentDir <- takeDirectory . sourceName <$> getPosition
+  insertIncludedFile parser toStream [currentDir] f startLine endLine
+
+--
+-- list blocks
+--
+
+list :: PandocMonad m => RSTParser m Blocks
+list = choice [ bulletList, orderedList, definitionList ] <?> "list"
+
+definitionListItem :: PandocMonad m => RSTParser m (Inlines, [Blocks])
+definitionListItem = try $ do
+  -- avoid capturing a directive or comment
+  notFollowedBy (try $ char '.' >> char '.')
+  term <- trimInlines . mconcat <$> many1Till inline endline
+  raw <- indentedBlock
+  -- parse the extracted block, which may contain various block elements:
+  contents <- parseFromString' parseBlocks $ raw <> "\n"
+  return (term, [contents])
+
+definitionList :: PandocMonad m => RSTParser m Blocks
+definitionList = B.definitionList <$> many1 definitionListItem
+
+-- parses bullet list start and returns its length (inc. following whitespace)
+bulletListStart :: Monad m => ParsecT Sources st m Int
+bulletListStart = try $ do
+  notFollowedBy' hrule  -- because hrules start out just like lists
+  marker <- oneOf bulletListMarkers
+  white <- many1 spaceChar <|> "" <$ lookAhead (char '\n')
+  return $ length (marker:white)
+
+-- parses ordered list start and returns its length (inc following whitespace)
+orderedListStart :: Monad m => ListNumberStyle
+                 -> ListNumberDelim
+                 -> RSTParser m Int
+orderedListStart style delim = try $ do
+  (_, markerLen) <- withHorizDisplacement (orderedListMarker style delim)
+  white <- many1 spaceChar <|> "" <$ lookAhead (char '\n')
+  return $ markerLen + length white
+
+-- parse a line of a list item
+listLine :: Monad m => Int -> RSTParser m Text
+listLine markerLength = try $ do
+  notFollowedBy blankline
+  indentWith markerLength
+  anyLineNewline
+
+-- parse raw text for one list item, excluding start marker and continuations
+rawListItem :: Monad m => RSTParser m Int
+            -> RSTParser m (Int, Text)
+rawListItem start = try $ do
+  markerLength <- start
+  firstLine <- anyLineNewline
+  restLines <- many (listLine markerLength)
+  return (markerLength, firstLine <> T.concat restLines)
+
+-- continuation of a list item - indented and separated by blankline or
+-- (in compact lists) endline.
+-- Note: nested lists are parsed as continuations.
+listContinuation :: Monad m => Int -> RSTParser m Text
+listContinuation markerLength = try $ do
+  blanks <- many1Char blankline
+  result <- many1 (listLine markerLength)
+  return $ blanks <> T.concat result
+
+listItem :: PandocMonad m
+         => RSTParser m Int
+         -> RSTParser m Blocks
+listItem start = try $ do
+  (markerLength, first) <- rawListItem start
+  rest <- many (listContinuation markerLength)
+  skipMany1 blankline <|> void (lookAhead start)
+  -- parsing with ListItemState forces markers at beginning of lines to
+  -- count as list item markers, even if not separated by blank space.
+  -- see definition of "endline"
+  state <- getState
+  let oldContext = stateParserContext state
+  setState $ state {stateParserContext = ListItemState}
+  -- parse the extracted block, which may itself contain block elements
+  parsed <- parseFromString' parseBlocks $ T.concat (first:rest) <> "\n"
+  updateState (\st -> st {stateParserContext = oldContext})
+  return $ case B.toList parsed of
+                [Para xs] ->
+                   B.singleton $ Plain xs
+                [Para xs, BulletList ys] ->
+                   B.fromList [Plain xs, BulletList ys]
+                [Para xs, OrderedList s ys] ->
+                   B.fromList [Plain xs, OrderedList s ys]
+                [Para xs, DefinitionList ys] ->
+                   B.fromList [Plain xs, DefinitionList ys]
+                _         -> parsed
+
+orderedList :: PandocMonad m => RSTParser m Blocks
+orderedList = try $ do
+  (start, style, delim) <- lookAhead (anyOrderedListMarker <* spaceChar)
+  items <- many1 (listItem (orderedListStart style delim))
+  let items' = compactify items
+  return $ B.orderedListWith (start, style, delim) items'
+
+bulletList :: PandocMonad m => RSTParser m Blocks
+bulletList = B.bulletList . compactify <$> many1 (listItem bulletListStart)
+
+--
+-- directive (e.g. comment, container, compound-paragraph)
+--
+
+comment :: Monad m => RSTParser m Blocks
+comment = try $ do
+  string ".."
+  skipMany1 spaceChar <|> void (lookAhead newline)
+  -- notFollowedBy' directiveLabel -- comment comes after directive so unnec.
+  _ <- anyLine
+  optional indentedBlock
+  optional blanklines
+  return mempty
+
+directiveLabel :: Monad m => RSTParser m Text
+directiveLabel = T.toLower
+  <$> many1TillChar (letter <|> char '-') (try $ string "::")
+
+directive :: PandocMonad m => RSTParser m Blocks
+directive = try $ do
+  string ".."
+  directive'
+
+directive' :: PandocMonad m => RSTParser m Blocks
+directive' = do
+  skipMany1 spaceChar
+  label <- directiveLabel
+  skipMany spaceChar
+  top <- manyChar $ satisfy (/='\n')
+             <|> try (char '\n' <*
+                      notFollowedBy' (rawFieldListItem 1) <*
+                      many1 (char ' ') <*
+                      notFollowedBy blankline)
+  newline
+  fields <- do
+    fieldIndent <- length <$> lookAhead (many (char ' '))
+    if fieldIndent == 0
+       then return []
+       else many $ rawFieldListItem fieldIndent
+  let mbfile = trim <$> lookup "file" fields
+  body <- case mbfile of
+            Just f | label == "raw" -> do
+               currentDir <- takeDirectory . sourceName <$> getPosition
+               fromMaybe mempty <$> readFileFromDirs [currentDir] (T.unpack f)
+            _ -> option "" $ try $ blanklines >> indentedBlock
+  optional blanklines
+  let body' = body <> "\n\n"
+      name = trim $ fromMaybe "" (lookup "name" fields)
+      classes = T.words $ maybe "" trim (lookup "class" fields)
+      keyvals = [(k, trim v) | (k, v) <- fields, k /= "name", k /= "class"]
+      imgAttr cl = (name, classes, alignClasses, widthAttr ++ heightAttr)
+        where
+          alignClasses = T.words $ maybe "" trim (lookup cl fields) <>
+                          maybe "" (\x -> "align-" <> trim x)
+                          (lookup "align" fields)
+          scale = case trim <$> lookup "scale" fields of
+                    Just v -> case T.unsnoc v of
+                      Just (vv, '%') -> case safeRead vv of
+                                          Just (percent :: Double)
+                                            -> percent / 100.0
+                                          Nothing -> 1.0
+                      _ -> case safeRead v of
+                             Just (s :: Double) -> s
+                             Nothing            -> 1.0
+                    Nothing -> 1.0
+          widthAttr = maybe [] (\x -> [("width",
+                                        tshow $ scaleDimension scale x)])
+                        $ lookup "width" fields >>=
+                          (lengthToDim . T.filter (not . isSpace))
+          heightAttr = maybe [] (\x -> [("height",
+                                         tshow $ scaleDimension scale x)])
+                        $ lookup "height" fields >>=
+                          (lengthToDim . T.filter (not . isSpace))
+  case label of
+        "include" -> includeDirective top fields body'
+        "table" -> tableDirective top fields body'
+        "list-table" -> listTableDirective top fields body'
+        "csv-table" -> csvTableDirective top fields body'
+        "line-block" -> lineBlockDirective body'
+        "raw" -> return $ B.rawBlock (trim top) (stripTrailingNewlines body)
+        "role" -> addNewRole top $ map (second trim) fields
+        "container" -> B.divWith
+                         (name, "container" : T.words top ++ classes, []) <$>
+                          parseFromString' parseBlocks body'
+        "replace" -> B.para <$>  -- consumed by substKey
+                   parseInlineFromText (trim top)
+        "date" -> B.para <$> do  -- consumed by substKey
+                     t <- getTimestamp
+                     let format = case T.unpack (T.strip top) of
+                                    [] -> "%Y-%m-%d"
+                                    x  -> x
+                     return $ B.text $
+                              T.pack $ formatTime defaultTimeLocale format t
+        "unicode" -> B.para <$>  -- consumed by substKey
+                   parseInlineFromText (trim $ unicodeTransform top)
+        "compound" -> parseFromString' parseBlocks body'
+        "pull-quote" -> B.blockQuote <$> parseFromString' parseBlocks body'
+        "epigraph" -> B.blockQuote <$> parseFromString' parseBlocks body'
+        "highlights" -> B.blockQuote <$> parseFromString' parseBlocks body'
+        "rubric" -> B.para . B.strong <$> parseInlineFromText top
+        _ | label `elem` ["attention","caution","danger","error","hint",
+                          "important","note","tip","warning","admonition"] ->
+           do bod <- parseFromString' parseBlocks $ top <> "\n\n" <> body'
+              let lab = case label of
+                          "admonition" -> mempty
+                          (T.uncons -> Just (l, ls))
+                            -> B.divWith ("",["title"],[])
+                                          (B.para (B.str $ T.cons (toUpper l)  ls))
+                          _ -> mempty
+              return $ B.divWith (name,label:classes,keyvals) (lab <> bod)
+        "sidebar" ->
+           do let subtit = maybe "" trim $ lookup "subtitle" fields
+              tit <- B.para . B.strong <$> parseInlineFromText
+                          (trim top <> if T.null subtit
+                                          then ""
+                                          else ":  " <> subtit)
+              bod <- parseFromString' parseBlocks body'
+              return $ B.divWith (name,"sidebar":classes,keyvals) $ tit <> bod
+        "topic" ->
+           do tit <- B.para . B.strong <$> parseInlineFromText top
+              bod <- parseFromString' parseBlocks body'
+              return $ B.divWith (name,"topic":classes,keyvals) $ tit <> bod
+        "default-role" -> mempty <$ updateState (\s ->
+                              s { stateRstDefaultRole =
+                                  case trim top of
+                                     ""   -> stateRstDefaultRole def
+                                     role -> role })
+        "highlight" -> mempty <$ updateState (\s ->
+                              s { stateRstHighlight =
+                                  case trim top of
+                                     ""   -> stateRstHighlight def
+                                     lang -> Just lang })
+        x | x == "code" || x == "code-block" || x == "sourcecode" ->
+          return $ codeblock name classes (map (second trimr) fields)
+             (trim top) True body
+        "aafig" -> do
+          let attribs = (name, ["aafig"], map (second trimr) fields)
+          return $ B.codeBlockWith attribs $ stripTrailingNewlines body
+        "math" -> return $ B.para
+                  $ (case mkAttr name classes fields of
+                       attr | attr == nullAttr -> id
+                            | otherwise        -> B.spanWith attr)
+                  $ mconcat $ map B.displayMath
+                  $ toChunks $ top <> "\n\n" <> body
+        "figure" -> do
+           (caption, legend) <- parseFromString' extractCaption body'
+           let src = escapeURI $ trim top
+           let (imgident, imgcls, aligncls, imgkvs) = imgAttr "class"
+           let (figclasskv, _) = partition ((== "figclass") . fst) keyvals
+           let figcls = concatMap (T.words . snd) figclasskv
+           let figattr = ("", figcls ++ aligncls, [])
+           let capt = B.caption Nothing (B.plain caption <> legend)
+           let alt = maybe caption (B.text . trim) (lookup "alt" fields)
+           return $ B.figureWith figattr capt $
+             B.plain (B.imageWith (imgident, imgcls, imgkvs) src "" alt)
+        "image" -> do
+           let src = escapeURI $ trim top
+           let alt = B.str $ maybe "image" trim $ lookup "alt" fields
+           let attr = (ident, cls ++ align, dims) where
+                 (ident, cls, align, dims) = imgAttr "class"
+           return $ B.para
+                  $ case lookup "target" fields of
+                          Just t  -> B.link (escapeURI $ trim t) ""
+                                     $ B.imageWith attr src "" alt
+                          Nothing -> B.imageWith attr src "" alt
+        "bibliography" -> pure $ B.divWith ("refs",[],[]) mempty
+        "class" -> do
+            let attrs = (name, T.words (trim top), map (second trimr) fields)
+            --  directive content or the first immediately following element
+            children <- case body of
+                "" -> block
+                _  -> parseFromString' parseBlocks  body'
+            return $
+              case B.toList children of
+                [Header lev attrs' ils]
+                  | T.null body -> -- # see #6699
+                     B.headerWith (attrs' <> attrs) lev (B.fromList ils)
+                _ -> B.divWith attrs children
+        other     -> do
+            pos <- getPosition
+            logMessage $ SkippedContent (".. " <> other) pos
+            bod <- parseFromString' parseBlocks $ top <> "\n\n" <> body'
+            return $ B.divWith (name, other:classes, keyvals) bod
+
+tableDirective :: PandocMonad m
+               => Text -> [(Text, Text)] -> Text -> RSTParser m Blocks
+tableDirective top fields body = do
+  bs <- parseFromString' parseBlocks body
+  case B.toList bs of
+       [Table attr _ tspecs' thead@(TableHead _ thrs) tbody tfoot] -> do
+         let (aligns', widths') = unzip tspecs'
+         title <- parseFromString' (trimInlines . mconcat <$> many inline) top
+         columns <- getOption readerColumns
+         let numOfCols = case thrs of
+               [] -> 0
+               (r:_) -> rowLength r
+         let normWidths ws =
+                strictPos . (/ max 1.0 (fromIntegral (columns - numOfCols))) <$> ws
+         let widths = case trim <$> lookup "widths" fields of
+                           Just "auto" -> replicate numOfCols ColWidthDefault
+                           Just "grid" -> widths'
+                           Just specs -> normWidths
+                               $ map (fromMaybe (0 :: Double) . safeRead)
+                               $ splitTextBy (`elem` (" ," :: String)) specs
+                           Nothing -> widths'
+         -- align is not applicable since we can't represent whole table align
+         let tspecs = zip aligns' widths
+         return $ B.singleton $ Table attr (B.caption Nothing (B.plain title))
+                                  tspecs thead tbody tfoot
+       _ -> do
+         pos <- getPosition
+         logMessage $ SkippedContent body pos
+         return mempty
+  where
+    -- only valid on the very first row of a table section
+    rowLength (Row _ rb) = sum $ cellLength <$> rb
+    cellLength (Cell _ _ _ (ColSpan w) _) = max 1 w
+    strictPos w
+      | w > 0     = ColWidth w
+      | otherwise = ColWidthDefault
+
+-- TODO: :stub-columns:.
+-- Only the first row becomes the header even if header-rows: > 1,
+-- since Pandoc doesn't support a table with multiple header rows.
+-- We don't need to parse :align: as it represents the whole table align.
+listTableDirective :: PandocMonad m
+                   => Text -> [(Text, Text)] -> Text
+                   -> RSTParser m Blocks
+listTableDirective top fields body = do
+  bs <- parseFromString' parseBlocks body
+  title <- parseFromString' (trimInlines . mconcat <$> many inline) top
+  let rows = takeRows $ B.toList bs
+      headerRowsNum = fromMaybe (0 :: Int) $
+         lookup "header-rows" fields >>= safeRead
+      (headerRow,bodyRows,numOfCols) = case rows of
+        x:xs -> if headerRowsNum > 0
+                   then (x, xs, length x)
+                   else ([], rows, length x)
+        _ -> ([],[],0)
+      widths = case trim <$> lookup "widths" fields of
+        Just "auto" -> replicate numOfCols ColWidthDefault
+        Just specs -> normWidths $ map (fromMaybe (0 :: Double) . safeRead) $
+                           splitTextBy (`elem` (" ," :: String)) specs
+        _ -> replicate numOfCols ColWidthDefault
+      toRow = Row nullAttr . map B.simpleCell
+      toHeaderRow l = [toRow l | not (null l)]
+  return $ B.table (B.simpleCaption $ B.plain title)
+             (zip (replicate numOfCols AlignDefault) widths)
+             (TableHead nullAttr $ toHeaderRow headerRow)
+             [TableBody nullAttr 0 [] $ map toRow bodyRows]
+             (TableFoot nullAttr [])
+    where takeRows [BulletList rows] = map takeCells rows
+          takeRows _                 = []
+          takeCells [BulletList cells] = map B.fromList cells
+          takeCells _                  = []
+          normWidths ws = strictPos . (/ max 1 (sum ws)) <$> ws
+          strictPos w
+            | w > 0     = ColWidth w
+            | otherwise = ColWidthDefault
+
+csvTableDirective :: PandocMonad m
+                   => Text -> [(Text, Text)] -> Text
+                   -> RSTParser m Blocks
+csvTableDirective top fields rawcsv = do
+  let explicitHeader = trim <$> lookup "header" fields
+  let opts = defaultCSVOptions{
+                csvDelim = case trim <$> lookup "delim" fields of
+                                Just "tab"   -> '\t'
+                                Just "space" -> ' '
+                                Just (T.unpack -> [c])
+                                             -> c
+                                _            -> ','
+              , csvQuote = case trim <$> lookup "quote" fields of
+                                Just (T.unpack -> [c])
+                                  -> Just c
+                                _ -> Just '"'
+              , csvEscape = case trim <$> lookup "escape" fields of
+                                Just (T.unpack -> [c])
+                                  -> Just c
+                                _ -> Nothing
+              , csvKeepSpace = case trim <$> lookup "keepspace" fields of
+                                       Just "true" -> True
+                                       _           -> False
+              }
+  let headerRowsNum = fromMaybe (case explicitHeader of
+                                       Just _  -> 1 :: Int
+                                       Nothing -> 0 :: Int) $
+           lookup "header-rows" fields >>= safeRead
+  rawcsv' <- case trim <$>
+                    lookup "file" fields `mplus` lookup "url" fields of
+                  Just u  -> do
+                    (bs, _) <- fetchItem u
+                    return $ UTF8.toText bs
+                  Nothing -> return rawcsv
+  let header' = case explicitHeader of
+                  Just h  -> parseCSV defaultCSVOptions h
+                  Nothing -> Right []
+  let res = parseCSV opts rawcsv'
+  case (<>) <$> header' <*> res of
+       Left e  ->
+         throwError $ fromParsecError (toSources rawcsv') e
+       Right rawrows -> do
+         let parseRow = mapM parseCell
+         rows <- mapM parseRow rawrows
+         let (headerRow,bodyRows,numOfCols) =
+              case rows of
+                   x:xs -> if headerRowsNum > 0
+                          then (x, xs, length x)
+                          else ([], rows, length x)
+                   _ -> ([],[],0)
+         title <- parseFromString' (trimInlines . mconcat <$> many inline) top
+         let strictPos w
+               | w > 0     = ColWidth w
+               | otherwise = ColWidthDefault
+         let normWidths ws = strictPos . (/ max 1 (sum ws)) <$> ws
+         let widths =
+               case trim <$> lookup "widths" fields of
+                 Just "auto" -> replicate numOfCols ColWidthDefault
+                 Just specs -> normWidths
+                               $ map (fromMaybe (0 :: Double) . safeRead)
+                               $ splitTextBy (`elem` (" ," :: String)) specs
+                 _ -> replicate numOfCols ColWidthDefault
+         let toRow = Row nullAttr . map B.simpleCell
+             toHeaderRow l = [toRow l | not (null l)]
+         return $ B.table (B.simpleCaption $ B.plain title)
+                          (zip (replicate numOfCols AlignDefault) widths)
+                          (TableHead nullAttr $ toHeaderRow headerRow)
+                          [TableBody nullAttr 0 [] $ map toRow bodyRows]
+                          (TableFoot nullAttr [])
+
+singleParaToPlain :: Blocks -> Blocks
+singleParaToPlain bs =
+  case B.toList bs of
+    [Para ils] -> B.fromList [Plain ils]
+    _          -> bs
+
+parseCell :: PandocMonad m => Text -> RSTParser m Blocks
+parseCell t = singleParaToPlain
+   <$> parseFromString' parseBlocks (trim t <> "\n\n")
+
+
+-- TODO:
+--  - Only supports :format: fields with a single format for :raw: roles,
+--    change Text.Pandoc.Definition.Format to fix
+addNewRole :: PandocMonad m
+           => Text -> [(Text, Text)] -> RSTParser m Blocks
+addNewRole roleText fields = do
+    pos <- getPosition
+    (role, parentRole) <- parseFromString' inheritedRole roleText
+    customRoles <- stateRstCustomRoles <$> getState
+    let getBaseRole (r, f, a) roles =
+            case M.lookup r roles of
+                 Just (r', f', a') -> getBaseRole (r', f', a') roles
+                 Nothing           -> (r, f, a)
+        (baseRole, baseFmt, baseAttr) =
+               getBaseRole (parentRole, Nothing, nullAttr) customRoles
+        fmt = if parentRole == "raw" then lookup "format" fields else baseFmt
+
+        updateClasses :: [Text] -> [Text]
+        updateClasses oldClasses = let
+
+          codeLanguageClass = if baseRole == "code"
+            then maybeToList (lookup "language" fields)
+            else []
+
+          -- if no ":class:" field is given, the default is the role name
+          classFieldClasses = maybe [role] T.words (lookup "class" fields)
+
+          -- nub in case role name & language class are the same
+          in nub (classFieldClasses ++ codeLanguageClass ++ oldClasses)
+
+        attr = let (ident, baseClasses, keyValues) = baseAttr
+               in (ident, updateClasses baseClasses, keyValues)
+
+    -- warn about syntax we ignore
+    forM_ fields $ \(key, _) -> case key of
+                 "language" -> when (baseRole /= "code") $ logMessage $
+                     SkippedContent ":language: [because parent of role is not :code:]"
+                        pos
+                 "format" -> when (baseRole /= "raw") $ logMessage $
+                     SkippedContent ":format: [because parent of role is not :raw:]" pos
+                 _ -> logMessage $ SkippedContent (":" <> key <> ":") pos
+    when (parentRole == "raw" && countKeys "format" > 1) $
+        logMessage $ SkippedContent
+                  ":format: [after first in definition of role]"
+                  pos
+    when (parentRole == "code" && countKeys "language" > 1) $
+        logMessage $ SkippedContent
+          ":language: [after first in definition of role]" pos
+
+    updateState $ \s -> s {
+        stateRstCustomRoles =
+          M.insert role (baseRole, fmt, attr) customRoles
+    }
+
+    return mempty
+  where
+    countKeys k = length . filter (== k) . map fst $ fields
+    inheritedRole =
+        (,) <$> roleName <*> ((char '(' *> roleName <* char ')')
+                            <|> pure "span")
+
+
+-- Can contain character codes as decimal numbers or
+-- hexadecimal numbers, prefixed by 0x, x, \x, U+, u, or \u
+-- or as XML-style hexadecimal character entities, e.g. &#x1a2b;
+-- or text, which is used as-is.  Comments start with ..
+unicodeTransform :: Text -> Text
+unicodeTransform t
+  | Just xs <- T.stripPrefix ".." t  = unicodeTransform $ T.dropWhile (/= '\n') xs -- comment
+  | Just xs <- T.stripPrefix "0x" t  = go "0x" xs
+  | Just xs <- T.stripPrefix "x" t   = go "x" xs
+  | Just xs <- T.stripPrefix "\\x" t = go "\\x" xs
+  | Just xs <- T.stripPrefix "U+" t  = go "U+" xs
+  | Just xs <- T.stripPrefix "u" t   = go "u" xs
+  | Just xs <- T.stripPrefix "\\u" t = go "\\u" xs
+  | Just xs <- T.stripPrefix "&#x" t = maybe ("&#x" <> unicodeTransform xs)
+                                       -- drop semicolon
+                                       (\(c,s) -> T.cons c $ unicodeTransform $ T.drop 1 s)
+                                       $ extractUnicodeChar xs
+  | Just (x, xs) <- T.uncons t       = T.cons x $ unicodeTransform xs
+  | otherwise                        = ""
+  where go pref zs = maybe (pref <> unicodeTransform zs)
+                     (\(c,s) -> T.cons c $ unicodeTransform s)
+                     $ extractUnicodeChar zs
+
+extractUnicodeChar :: Text -> Maybe (Char, Text)
+extractUnicodeChar s = fmap (\c -> (c,rest)) mbc
+  where (ds,rest) = T.span isHexDigit s
+        mbc = safeRead ("'\\x" <> ds <> "'")
+
+extractCaption :: PandocMonad m => RSTParser m (Inlines, Blocks)
+extractCaption = do
+  capt <- trimInlines . mconcat <$> many inline
+  legend <- optional blanklines >> (mconcat <$> many block)
+  return (capt,legend)
+
+-- divide string by blanklines, and surround with
+-- \begin{aligned}...\end{aligned} if needed.
+toChunks :: Text -> [Text]
+toChunks = dropWhile T.null
+           . map (addAligned . trim . T.unlines)
+           . splitBy (T.all (`elem` (" \t" :: String))) . T.lines
+  -- we put this in an aligned environment if it contains \\, see #4254
+  where addAligned s = if "\\\\" `T.isInfixOf` s
+                          then "\\begin{aligned}\n" <> s <> "\n\\end{aligned}"
+                          else s
+
+codeblock :: Text -> [Text] -> [(Text, Text)] -> Text -> Bool -> Text
+          -> Blocks
+codeblock ident classes fields lang rmTrailingNewlines body =
+  B.codeBlockWith attribs $ stripTrailingNewlines' body
+    where stripTrailingNewlines' = if rmTrailingNewlines
+                                     then stripTrailingNewlines
+                                     else id
+          attribs = (ident, classes', kvs)
+          classes' = lang
+                    : ["numberLines" | isJust (lookup "number-lines" fields)]
+                    ++ classes
+          kvs = [(k,v) | (k,v) <- fields, k /= "number-lines", k /= "class",
+                                          k /= "id", k /= "name"]
+                ++ case lookup "number-lines" fields of
+                     Just v | not (T.null v) -> [("startFrom", v)]
+                     _ -> []
+
+-- | Creates element attributes from a name, list of classes, and fields.
+-- Removes fields named @name@, @id@, or @class@.
+mkAttr :: Text -> [Text] -> [(Text, Text)] -> Attr
+mkAttr ident classes fields = (ident, classes, fields')
+  where fields' = [(k, v') | (k, v) <- fields
+                           , let v' = trimr v
+                           , k /= "name", k /= "id", k /= "class"]
+
+---
+--- note block
+---
+
+noteBlock :: Monad m => RSTParser m Blocks
+noteBlock = try $ do
+  (ref, raw) <- noteBlock' noteMarker
+  updateState $ \s -> s { stateNotes = (ref, raw) : stateNotes s }
+  return mempty
+
+citationBlock :: Monad m => RSTParser m Blocks
+citationBlock = try $ do
+  (ref, raw) <- noteBlock' citationMarker
+  updateState $ \s ->
+     s { stateCitations = M.insert ref raw (stateCitations s),
+         stateKeys = M.insert (toKey ref) (("#" <> ref,""), ("",["citation"],[]))
+                               (stateKeys s) }
+  return mempty
+
+noteBlock' :: Monad m
+           => RSTParser m Text -> RSTParser m (Text, Text)
+noteBlock' marker = try $ do
+  string ".."
+  spaceChar >> skipMany spaceChar
+  ref <- marker
+  first <- (spaceChar >> skipMany spaceChar >> anyLine)
+        <|> (newline >> return "")
+  blanks <- option "" blanklines
+  rest <- option "" indentedBlock
+  let raw = first <> "\n" <> blanks <> rest <> "\n"
+  return (ref, raw)
+
+citationMarker :: Monad m => RSTParser m Text
+citationMarker = do
+  char '['
+  res <- simpleReferenceName
+  char ']'
+  return res
+
+noteMarker :: Monad m => RSTParser m Text
+noteMarker = do
+  char '['
+  res <- many1Char digit
+      <|>
+                  try (char '#' >> liftM ("#" <>) simpleReferenceName)
+      <|> countChar 1 (oneOf "#*")
+  char ']'
+  return res
+
+--
+-- reference key
+--
+
+quotedReferenceName :: PandocMonad m => RSTParser m Text
+quotedReferenceName = try $ do
+  char '`' >> notFollowedBy (char '`') -- `` means inline code!
+  manyTillChar anyChar (char '`')
+
+-- Simple reference names are single words consisting of alphanumerics
+-- plus isolated (no two adjacent) internal hyphens, underscores,
+-- periods, colons and plus signs; no whitespace or other characters
+-- are allowed.
+simpleReferenceName :: Monad m => ParsecT Sources st m Text
+simpleReferenceName = do
+  x <- alphaNum
+  xs <- many $  alphaNum
+            <|> try (oneOf "-_:+." <* lookAhead alphaNum)
+  return $ T.pack (x:xs)
+
+referenceName :: PandocMonad m => RSTParser m Text
+referenceName = quotedReferenceName <|> simpleReferenceName
+
+referenceKey :: PandocMonad m => RSTParser m Blocks
+referenceKey = do
+  choice [substKey, anonymousKey, regularKey]
+  optional blanklines
+  return mempty
+
+targetURI :: Monad m => ParsecT Sources st m Text
+targetURI = do
+  skipSpaces
+  optional $ try $ newline >> notFollowedBy blankline
+  contents <- trim <$>
+     many1Char (satisfy (/='\n')
+     <|> try (newline >> many1 spaceChar >> noneOf " \t\n"))
+  blanklines
+  return $ stripBackticks contents
+  where
+    stripBackticks t
+      | Just xs <- T.stripSuffix "`_" t = T.dropWhile (=='`') xs <> "_"
+      | Just _  <- T.stripSuffix "_"  t = t
+      | otherwise                       = escapeURI t
+
+substKey :: PandocMonad m => RSTParser m ()
+substKey = try $ do
+  string ".."
+  skipMany1 spaceChar
+  (alt,ref) <- withRaw $ trimInlines . mconcat
+                      <$> enclosed (char '|') (char '|') inline
+  res <- B.toList <$> directive'
+  bls <- case res of
+             -- use alt unless :alt: attribute on image:
+             [Para [Image attr [Str "image"] (src,tit)]] ->
+                return $ B.para $ B.imageWith attr src tit alt
+             [Para [Link _ [Image attr [Str "image"] (src,tit)] (src',tit')]] ->
+                return $ B.para $ B.link src' tit' (B.imageWith attr src tit alt)
+             _          -> return $ B.fromList res
+  let key = toKey $ stripFirstAndLast ref
+  updateState $ \s -> s{ stateSubstitutions =
+                          M.insert key bls $ stateSubstitutions s }
+
+anonymousKey :: PandocMonad m => RSTParser m ()
+anonymousKey = try $ do
+  oneOfStrings [".. __:", "__"]
+  skipMany1 spaceChar
+  src <- targetURI
+  -- we need to ensure that the keys are ordered by occurrence in
+  -- the document.
+  numKeys <- M.size . stateKeys <$> getState
+  let key = toKey $ "_" <> T.pack (printf "%04d" numKeys)
+  updateState $ \s -> s { stateKeys = M.insert key ((src,""), nullAttr) $
+                          stateKeys s }
+
+referenceNames :: PandocMonad m => RSTParser m [Text]
+referenceNames = do
+  let rn = try $ do
+             string ".. _"
+             ref <- quotedReferenceName
+                  <|> manyChar (  noneOf "\\:\n"
+                              <|> try (char '\n' <*
+                                       string "   " <*
+                                       notFollowedBy blankline)
+                              <|> try (char '\\' *> char ':')
+                              <|> try (char ':' <* lookAhead alphaNum)
+                               )
+             char ':'
+             return ref
+  first <- rn
+  rest  <- many (try (blanklines *> rn))
+  return (first:rest)
+
+regularKey :: PandocMonad m => RSTParser m ()
+regularKey = try $ do
+  -- we allow several references to the same URL, e.g.
+  -- .. _hello:
+  -- .. _goodbye: url.com
+  refs <- referenceNames
+  src <- targetURI
+  guard $ not (T.null src)
+  let keys = map toKey refs
+  forM_ keys $ \key ->
+    updateState $ \s -> s { stateKeys = M.insert key ((src,""), nullAttr) $
+                            stateKeys s }
+
+anchor :: PandocMonad m => RSTParser m Blocks
+anchor = try $ do
+  refs <- referenceNames
+  blanklines
+  forM_ refs $ \rawkey ->
+    updateState $ \s -> s { stateKeys =
+       M.insert (toKey rawkey) (("#" <> rawkey,""), nullAttr)
+         (stateKeys s) }
+  b <- block
+  let addDiv ref = B.divWith (ref, [], [])
+  let emptySpanWithId id' = Span (id',[],[]) []
+  -- put identifier on next block:
+  case B.toList b of
+       [Header lev (_,classes,kvs) txt] ->
+         case reverse refs of
+              [] -> return b
+              (r:rs) -> return $ B.singleton $
+                           Header lev (r,classes,kvs)
+                             (txt ++ map emptySpanWithId rs)
+                -- we avoid generating divs for headers,
+                -- because it hides them from promoteHeader, see #4240
+       _ -> return $ foldr addDiv b refs
+
+--
+-- tables
+--
+
+-- General tables TODO:
+--  - figure out if leading spaces are acceptable and if so, add
+--    support for them
+--
+-- Simple tables TODO:
+--  - multiline support
+--  - ensure that rightmost column span does not need to reach end
+--  - require at least 2 columns
+
+dashedLine :: Monad m => Char -> ParsecT Sources st m (Int, Int)
+dashedLine ch = do
+  dashes <- many1 (char ch)
+  sp     <- many (char ' ')
+  return (length dashes, length sp)
+
+simpleDashedLines :: Monad m => Char -> ParsecT Sources st m [(Int,Int)]
+simpleDashedLines ch = try $ do
+  lines' <- many1 (dashedLine ch)
+  skipMany spaceChar
+  newline
+  return $ addSpaces lines'
+ where
+  addSpaces [] = []
+  addSpaces [(dashes, _)] = [(dashes, dashes)] -- Don't count trailing whitespaces
+  addSpaces ((dashes, sp) : moreLines) =
+    (dashes, dashes + sp) : addSpaces moreLines
+
+-- Parse a table row separator
+simpleTableSep :: Monad m => Char -> RSTParser m ()
+simpleTableSep ch = void (simpleDashedLines ch)
+
+-- Parse a table footer
+simpleTableFooter :: Monad m => RSTParser m ()
+simpleTableFooter = try $ simpleTableSep '=' >> void blanklines
+
+-- Parse a raw line and split it into chunks by indices.
+simpleTableRawLine :: Monad m => [Int] -> RSTParser m [(Text, ColSpan)]
+simpleTableRawLine indices = do
+  row <- rowWithOptionalColSpan
+
+  case simpleTableSplitLine indices row of
+    Just rowLine -> return rowLine
+    Nothing -> Prelude.fail "col spans don't match"
+
+simpleTableRawLineWithInitialEmptyCell :: Monad m => [Int] -> RSTParser m [(Text, ColSpan)]
+simpleTableRawLineWithInitialEmptyCell indices = try $ do
+  cs <- simpleTableRawLine indices
+  let isEmptyCell = T.all (\c -> c == ' ' || c == '\t')
+  case cs of
+    c:_ | isEmptyCell (fst c) -> return cs
+    _ -> mzero
+
+-- Parse a table row and return a list of blocks (columns).
+simpleTableRow :: PandocMonad m => [Int] -> RSTParser m [(Blocks, RowSpan, ColSpan)]
+simpleTableRow indices = do
+  notFollowedBy' (void blanklines <|> simpleTableFooter)
+  firstLine <- simpleTableRawLine indices
+  conLines  <- many $ simpleTableRawLineWithInitialEmptyCell indices
+  let cols = map T.unlines . transpose $ (map fst firstLine) : (map (map fst) conLines) ++
+                                  [replicate (length indices) ""
+                                    | not (null conLines)]
+  let rowParser = mapM parseCell cols
+  fmap (\blocks -> zip3 blocks (repeat 1) (map snd firstLine)) rowParser
+
+simpleTableSplitLine :: [Int] -> (Text, Maybe [Int]) -> Maybe [(Text, ColSpan)]
+simpleTableSplitLine indices (line, maybeColspanIndices) =
+  fmap (zip tableLines) columnSpans
+ where
+  splitTableLines lineIndices = map trimr $ drop 1 $ splitTextByIndices (init lineIndices) line
+  (tableLines, columnSpans) = case maybeColspanIndices of
+      Nothing -> (splitTableLines indices, Just $ repeat 1)
+      Just colSpanIndices -> (splitTableLines colSpanIndices, colSpans indices colSpanIndices)
+
+simpleTableHeader :: PandocMonad m
+                  => Bool  -- ^ Headerless table
+                  -> RSTParser m ([[(Blocks, RowSpan, ColSpan)]], [Alignment], [Int])
+simpleTableHeader headless = try $ do
+  optional blanklines
+  dashes <- simpleDashedLines '='
+
+  rawContent  <- if headless
+                    then return [("", Nothing)]
+                    else many1 $ notFollowedBy (simpleDashedLines '=') >> rowWithOptionalColSpan
+
+  unless headless $ simpleTableSep '='
+
+  let (lines', indices) = dashedLinesToLinesWithIndices dashes
+  let aligns   = replicate (length lines') AlignDefault
+  let rawHeads = if headless
+                    then []
+                    else map (simpleTableSplitLine indices) rawContent
+
+  when (any isNothing rawHeads) $ Prelude.fail "col spans don't match"
+
+  let justRawHeads  = catMaybes rawHeads
+  let rawHeads'     = map fst <$> justRawHeads
+  let columnSpans   = map snd <$> justRawHeads
+  heads <- mapM (mapM $ parseFromString' (mconcat <$> many plain) . trim) rawHeads'
+  let headsWithSpans = zipWith3 zip3 heads singleRowSpans columnSpans
+  return (headsWithSpans, aligns, indices)
+
+rowWithOptionalColSpan :: Monad m
+                       => RSTParser m (Text, Maybe [Int])
+rowWithOptionalColSpan = do
+  line <- anyLine
+  colSpanHyphens <- optionMaybe $ simpleDashedLines '-'
+
+  let colSpan = fmap colSpanFromHyphens colSpanHyphens
+  return (line, colSpan)
+ where
+  colSpanFromHyphens colSpanHyphens = snd $ dashedLinesToLinesWithIndices colSpanHyphens
+
+-- Parse a simple table.
+simpleTable :: PandocMonad m
+            => Bool  -- ^ Headerless table
+            -> RSTParser m Blocks
+simpleTable headless = do
+  let wrapIdFst (a, b, c) = (Identity a, b, c)
+      wrapId = fmap Identity
+  tbl <- runIdentity <$> tableWithSpans
+           (wrapIdFst <$> simpleTableHeader headless)
+           (wrapId <$> simpleTableRow)
+           sep simpleTableFooter
+  -- Simple tables get 0s for relative column widths (i.e., use default)
+  case B.toList tbl of
+       [Table attr cap spec th tb tf] -> return $ B.singleton $
+                                         Table attr cap (rewidth spec) th tb tf
+       _ ->
+         throwError $ PandocShouldNeverHappenError
+            "tableWith returned something unexpected"
+ where
+  sep = return () -- optional (simpleTableSep '-')
+  rewidth = fmap $ fmap $ const ColWidthDefault
+
+gridTable :: PandocMonad m
+          => RSTParser m Blocks
+gridTable = runIdentity <$>
+  gridTableWith (Identity <$> parseBlocks)
+
+table :: PandocMonad m => RSTParser m Blocks
+table = gridTable <|> simpleTable False <|> simpleTable True <?> "table"
+
+--
+-- inline
+--
+
+inline :: PandocMonad m => RSTParser m Inlines
+inline =
+  (note          -- can start with whitespace, so try before ws
+    <|> do notAfterString >>= guard
+           (link <|> inlineAnchor <|> strong <|> emph)
+    <|> code
+    <|> subst
+    <|> interpretedRole
+    <|> inlineContent) <?> "inline"
+
+-- strings, spaces and other characters that can appear either by
+-- themselves or within inline markup
+inlineContent :: PandocMonad m => RSTParser m Inlines
+inlineContent = choice [ whitespace
+                       , str
+                       , endline
+                       , smart
+                       , escapedChar
+                       , symbol ] <?> "inline content"
+
+parseInlineFromText :: PandocMonad m => Text -> RSTParser m Inlines
+parseInlineFromText = parseFromString' (trimInlines . mconcat <$> many inline)
+
+escapedChar :: Monad m => RSTParser m Inlines
+escapedChar = do c <- escaped anyChar
+                 if c == ' ' || c == '\n' || c == '\r'
+                    -- '\ ' is null in RST
+                    then return mempty
+                    else do
+                      unless (canPrecedeOpener c) updateLastStrPos
+                      return $ B.str $ T.singleton c
+
+canPrecedeOpener :: Char -> Bool
+canPrecedeOpener c =
+  generalCategory c `elem`
+   [OpenPunctuation, InitialQuote, FinalQuote, DashPunctuation, OtherSymbol]
+
+symbol :: Monad m => RSTParser m Inlines
+symbol = do
+  c <- oneOf specialChars
+  unless (canPrecedeOpener c) updateLastStrPos
+  return $ B.str $ T.singleton c
+
+-- parses inline code, between codeStart and codeEnd
+code :: Monad m => RSTParser m Inlines
+code = try $ do
+  string "``"
+  result <- manyTillChar anyChar (try (string "``"))
+  return $ B.code
+         $ trim $ T.unwords $ T.lines result
+
+-- succeeds only if we're not right after a str (ie. in middle of word)
+atStart :: Monad m => RSTParser m a -> RSTParser m a
+atStart p = do
+  pos <- getPosition
+  st <- getState
+  -- single quote start can't be right after str
+  guard $ stateLastStrPos st /= Just pos
+  p
+
+emph :: PandocMonad m => RSTParser m Inlines
+emph = B.emph . trimInlines . mconcat <$>
+         enclosed (atStart $ char '*') (char '*') inlineContent
+
+strong :: PandocMonad m => RSTParser m Inlines
+strong = B.strong . trimInlines . mconcat <$>
+          enclosed (atStart $ string "**") (try $ string "**") inlineContent
+
+-- Note, this doesn't precisely implement the complex rule in
+-- http://docutils.sourceforge.net/docs/ref/rst/restructuredtext.html#inline-markup-recognition-rules
+-- but it should be good enough for most purposes
+--
+-- TODO:
+--  - Classes are silently discarded in addNewRole
+--  - Allows direct use of the :raw: role, rST only allows inherited use.
+interpretedRole :: PandocMonad m => RSTParser m Inlines
+interpretedRole = try $ do
+  (role, contents) <- roleBefore <|> roleAfter
+  renderRole contents Nothing role nullAttr
+
+renderRole :: PandocMonad m
+           => Text -> Maybe Text -> Text -> Attr -> RSTParser m Inlines
+renderRole contents fmt role attr = case role of
+    "sup"  -> return $ B.superscript $ treatAsText contents
+    "superscript" -> return $ B.superscript $ treatAsText contents
+    "sub"  -> return $ B.subscript $ treatAsText contents
+    "subscript"  -> return $ B.subscript $ treatAsText contents
+    "mark"  -> return $ B.spanWith ("",["mark"],[]) $ treatAsText contents
+    "emphasis" -> return $ B.emph $ treatAsText contents
+    "strong" -> return $ B.strong $ treatAsText contents
+    "rfc-reference" -> return $ rfcLink contents
+    "RFC" -> return $ rfcLink contents
+    "pep-reference" -> return $ pepLink contents
+    "PEP" -> return $ pepLink contents
+    "literal" -> return $ B.codeWith attr contents
+    "math" -> return $ B.math contents
+    "title-reference" -> titleRef contents
+    "title" -> titleRef contents
+    "t" -> titleRef contents
+    "code" -> return $ B.codeWith attr contents
+    "span" -> return $ B.spanWith attr $ treatAsText contents
+    "raw" -> return $ B.rawInline (fromMaybe "" fmt) contents
+    custom
+     | Just citeType <- T.stripPrefix "cite" custom
+       -> cite citeType contents
+     | otherwise -> do
+        customRoles <- stateRstCustomRoles <$> getState
+        case M.lookup custom customRoles of
+            Just (newRole, newFmt, newAttr) ->
+                renderRole contents newFmt newRole newAttr
+            Nothing -> -- undefined role
+                return $ B.codeWith ("",["interpreted-text"],[("role",role)])
+                          contents
+ where
+   titleRef ref = return $ B.spanWith ("",["title-ref"],[]) $ treatAsText ref
+   rfcLink rfcNo = B.link rfcUrl ("RFC " <> rfcNo) $ B.str ("RFC " <> rfcNo)
+     where rfcUrl = "http://www.faqs.org/rfcs/rfc" <> rfcNo <> ".html"
+   pepLink pepNo = B.link pepUrl ("PEP " <> pepNo) $ B.str ("PEP " <> pepNo)
+     where padNo = T.replicate (4 - T.length pepNo) "0" <> pepNo
+           pepUrl = "http://www.python.org/dev/peps/pep-" <> padNo <> "/"
+   treatAsText = B.text . handleEscapes
+   handleEscapes = T.concat . removeSpace . T.splitOn "\\"
+     where headSpace t = fromMaybe t $ T.stripPrefix " " t
+           removeSpace (x:xs) = x : map headSpace xs
+           removeSpace []     = []
+
+cite :: PandocMonad m => Text -> Text -> RSTParser m Inlines
+cite citeType rawcite = do
+  let citations =
+        case map parseCite (T.splitOn "," rawcite) of
+                (c:cs)
+                  | citeType == ":t" || citeType == ":ct"
+                     -> c{ citationMode = AuthorInText } : cs
+                  | citeType == ":year" || citeType == ":yearpar"
+                     -> c{ citationMode = SuppressAuthor } : cs
+                cs -> cs
+  pure $ B.cite citations (B.str rawcite)
+
+parseCite :: Text -> Citation
+parseCite t =
+  let (_, pref, suff, ident) = T.foldl go (ParseStart, "", "", "") t
+  in  Citation{citationId = ident
+              ,citationPrefix = B.toList $ B.text pref
+              ,citationSuffix = B.toList $ B.text suff
+              ,citationMode = NormalCitation
+              ,citationNoteNum = 0
+              ,citationHash = 0}
+ where
+   go (ParseStart, p, s, i) '{' = (ParsePrefix, p, s, i)
+   go (ParseStart, p, s, i) c = (ParseId, p, s, T.snoc i c)
+   go (ParsePrefix, p, s, i) '}' = (ParseId, p, s, i)
+   go (ParsePrefix, p, s, i) c = (ParsePrefix, T.snoc p c, s, i)
+   go (ParseId, p, s, i) '{' = (ParseSuffix, p, s, i)
+   go (ParseId, p, s, i) c = (ParseId, p, s, T.snoc i c)
+   go (ParseSuffix, p, s, i) '}' = (ParseSuffix, p, s, i)
+   go (ParseSuffix, p, s, i) c = (ParseSuffix, p, T.snoc s c, i)
+
+data ParseCiteState = ParseStart | ParsePrefix | ParseSuffix | ParseId
+  deriving (Show)
+
+-- single words consisting of alphanumerics plus isolated (no two adjacent)
+-- internal hyphens, underscores, periods, colons and plus signs;
+-- no whitespace or other characters are allowed
+roleName :: PandocMonad m => RSTParser m Text
+roleName = many1Char (alphaNum <|> try (oneOf "-_.:+" <* lookAhead alphaNum))
+
+roleMarker :: PandocMonad m => RSTParser m Text
+roleMarker = char ':' *> roleName <* char ':'
+
+roleBefore :: PandocMonad m => RSTParser m (Text,Text)
+roleBefore = try $ do
+  role <- roleMarker
+  contents <- unmarkedInterpretedText
+  return (role,contents)
+
+roleAfter :: PandocMonad m => RSTParser m (Text,Text)
+roleAfter = try $ do
+  contents <- unmarkedInterpretedText
+  role <- roleMarker <|> (stateRstDefaultRole <$> getState)
+  return (role,contents)
+
+unmarkedInterpretedText :: PandocMonad m => RSTParser m Text
+unmarkedInterpretedText = try $ do
+  atStart (char '`')
+  contents <- mconcat <$> many1
+       (  many1 (noneOf "`\\\n")
+      <|> (char '\\' >> ((\c -> ['\\',c]) <$> noneOf "\n"))
+      <|> (string "\n" <* notFollowedBy blankline)
+      <|> try (string "`" <*
+                notFollowedBy (void roleMarker) <*
+                lookAhead (satisfy isAlphaNum))
+       )
+  char '`'
+  return $ T.pack contents
+
+whitespace :: PandocMonad m => RSTParser m Inlines
+whitespace = B.space <$ skipMany1 spaceChar <?> "whitespace"
+
+str :: Monad m => RSTParser m Inlines
+str = do
+  let strChar = noneOf ("\t\n " ++ specialChars)
+  result <- many1Char strChar
+  updateLastStrPos
+  return $ B.str result
+
+-- an endline character that can be treated as a space, not a structural break
+endline :: Monad m => RSTParser m Inlines
+endline = try $ do
+  newline
+  notFollowedBy blankline
+  -- parse potential list-starts at beginning of line differently in a list:
+  st <- getState
+  when (stateParserContext st == ListItemState) $ notFollowedBy (anyOrderedListMarker >> spaceChar) >>
+          notFollowedBy' bulletListStart
+  return B.softbreak
+
+--
+-- links
+--
+
+link :: PandocMonad m => RSTParser m Inlines
+link = choice [explicitLink, referenceLink, autoLink]  <?> "link"
+
+explicitLink :: PandocMonad m => RSTParser m Inlines
+explicitLink = try $ do
+  char '`'
+  notFollowedBy (char '`') -- `` marks start of inline code
+  label' <- trimInlines . mconcat <$>
+              manyTill (notFollowedBy (char '`') >> inlineContent) (char '<')
+  src <- trim . T.pack . filter (/= '\n') <$> -- see #10279
+           manyTill (noneOf ">\n" <|> (char '\n' <* notFollowedBy blankline))
+                    (char '>')
+  skipSpaces
+  string "`_"
+  optional $ char '_' -- anonymous form
+  let src' | isURI src = escapeURI src
+           | otherwise =
+              case T.unsnoc src of
+                 Just (xs, '_') -> "##REF##" <> xs
+                 _              -> src
+  let label'' = if label' == mempty
+                   then B.str src
+                   else label'
+  let key = toKey $ stringify label'
+  unless (key == Key mempty) $ do
+    updateState $ \s -> s{
+      stateKeys = M.insert key ((src',""), nullAttr) $ stateKeys s }
+  return $ B.linkWith nullAttr src' "" label''
+
+citationName :: PandocMonad m => RSTParser m Text
+citationName = do
+  raw <- citationMarker
+  return $ "[" <> raw <> "]"
+
+-- We store the reference link label as the link target,
+-- preceded by '##REF##'. This is replaced after the AST
+-- has been built by the resolved reference.
+referenceLink :: PandocMonad m => RSTParser m Inlines
+referenceLink = try $ do
+  ref <- (referenceName <|> citationName) <* char '_'
+  isAnonymous <- (True <$ char '_') <|> pure False
+  eof <|> notFollowedBy alphaNum
+  let ref' = if isAnonymous
+                then "_"
+                else ref
+  pure $ B.linkWith nullAttr ("##REF##" <> ref') "" (B.text ref)
+
+-- We keep a list of oldkeys so we can detect lookup loops.
+lookupKey :: PandocMonad m
+          => [Key] -> Key -> RSTParser m ((Text, Text), Attr)
+lookupKey oldkeys key = do
+  pos <- getPosition
+  state <- getState
+  let keyTable = stateKeys state
+  case M.lookup key keyTable of
+       Nothing  -> do
+         let Key key' = key
+         logMessage $ ReferenceNotFound key' pos
+         return (("",""),nullAttr)
+       -- check for keys of the form link_, which need to be resolved:
+       Just ((u, ""),_) | T.length u > 1, T.last u == '_', T.head u /= '#' -> do
+         let rawkey = T.init u
+         let newkey = toKey rawkey
+         if newkey `elem` oldkeys
+            then do
+              -- TODO the pos is not going to be accurate
+              -- because we're calling this after the AST is
+              -- constructed. Probably good to remove that
+              -- parameter form CircularReference at some point.
+              logMessage $ CircularReference rawkey pos
+              return (("",""),nullAttr)
+            else lookupKey (key:oldkeys) newkey
+       Just val -> return val
+
+autoURI :: Monad m => RSTParser m Inlines
+autoURI = do
+  (orig, src) <- uri
+  return $ B.link src "" $ B.str orig
+
+autoEmail :: Monad m => RSTParser m Inlines
+autoEmail = do
+  (orig, src) <- emailAddress
+  return $ B.link src "" $ B.str orig
+
+autoLink :: PandocMonad m => RSTParser m Inlines
+autoLink = autoURI <|> autoEmail
+
+subst :: PandocMonad m => RSTParser m Inlines
+subst = try $ do
+  (_,ref) <- withRaw $ enclosed (char '|') (char '|') inline
+  let substlink = B.linkWith nullAttr ("##SUBST##" <> ref) "" (B.text ref)
+  reflink <- option False (True <$ char '_')
+  if reflink
+     then do
+       let linkref = T.drop 1 $ T.dropEnd 1 ref
+       return $ B.linkWith nullAttr ("##REF##" <> linkref) "" substlink
+     else return substlink
+
+note :: PandocMonad m => RSTParser m Inlines
+note = try $ do
+  optional whitespace
+  ref <- noteMarker
+  char '_'
+  pure $ B.linkWith nullAttr ("##NOTE##" <> ref) "" (B.text ref)
+
+smart :: PandocMonad m => RSTParser m Inlines
+smart = smartPunctuation inline
+
+inlineAnchor :: PandocMonad m => RSTParser m Inlines
+inlineAnchor = try $ do
+  char '_'
+  name <- quotedReferenceName <|> simpleReferenceName
+  let ident = textToIdentifier mempty name
+  updateState $ \s ->
+    s{ stateKeys = M.insert (toKey name) (("#" <> ident, ""), nullAttr)
+                    (stateKeys s) }
+  pure $ B.spanWith (ident,[],[]) (B.text name)
+
+dashedLinesToLinesWithIndices :: [(Int, Int)] -> ([Int], [Int])
+dashedLinesToLinesWithIndices dashes =
+  let lines'  = map snd dashes
+      indices = scanl (+) 0 lines'
+  in  (lines', indices)
+
+-- | Determines column spans by appying indices of a table border with column span indices.
+--
+-- The indices need to align.
+colSpans :: [Int] -> [Int] -> Maybe [ColSpan]
+colSpans [] []  = Just []
+colSpans [] _   = Nothing
+colSpans _ []   = Nothing
+colSpans (index : indices) colSpanIndices@(colIndex : colSpanIndicesTail)
+    | index /= colIndex = colSpans indices colSpanIndices
+    | otherwise =
+        -- For a matching index start counting the column spans.
+        let (spanCount, remainingIndices, remainingColSpanindices) = colSpanCount indices colSpanIndicesTail 1
+        in  (:) spanCount <$> colSpans remainingIndices remainingColSpanindices
+
+-- | Counts column spans by consuming all non-matching indices until a matching one is encountered.
+--
+-- If the indices match, the end of a column span has been encountered and the
+-- column count can be returned. Otherwise, if the indices don't match, add to
+-- the span count until a matching index is found.
+colSpanCount :: [Int] -> [Int] -> ColSpan -> (ColSpan, [Int], [Int])
+colSpanCount [] colSpanIndices spanCount = (spanCount, [], colSpanIndices)
+colSpanCount _ [] spanCount = (spanCount, [], [])
+colSpanCount indices@(index : indicesTail) colSpanIndices@(colIndex : colSpanIndicesTail) spanCount
+    | index == colIndex = case colSpanIndicesTail of
+        [] -> (spanCount, indicesTail, colSpanIndicesTail)
+        _ -> (spanCount, indices, colSpanIndices)
+    | otherwise = colSpanCount indicesTail colSpanIndices $ spanCount + 1
diff --git a/src/Text/Pandoc/Readers/RTF.hs b/src/Text/Pandoc/Readers/RTF.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Readers/RTF.hs
@@ -0,0 +1,1436 @@
+{-# LANGUAGE FlexibleContexts  #-}
+{-# LANGUAGE BangPatterns      #-}
+{-# LANGUAGE OverloadedStrings #-}
+{- |
+   Module      : Text.Pandoc.Readers.RTF
+   Copyright   : Copyright (C) 2021-2024 John MacFarlane
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : John MacFarlane (<jgm@berkeley.edu>)
+   Stability   : alpha
+   Portability : portable
+
+Conversion of RTF documents 'Pandoc' document.
+We target version 1.5 of the RTF spec.
+-}
+module Text.Pandoc.Readers.RTF (readRTF) where
+
+import qualified Data.IntMap as IntMap
+import qualified Data.Sequence as Seq
+import Control.Monad
+import Control.Monad.Except (throwError)
+import Crypto.Hash (hashWith, SHA1(SHA1))
+import qualified Data.List as L
+import Data.Word (Word8, Word16)
+import Data.Default
+import Data.Text (Text)
+import qualified Data.Text as T
+import qualified Data.Text.Read as TR
+import Text.Pandoc.Builder (Blocks, Inlines)
+import qualified Text.Pandoc.Builder as B
+import Text.Pandoc.Class (PandocMonad (..), insertMedia, report)
+import Text.Pandoc.Definition
+import Text.Pandoc.Options
+import Text.Pandoc.Parsing
+import Text.Pandoc.Logging (LogMessage(UnsupportedCodePage))
+import Text.Pandoc.Shared (tshow)
+import Data.Char (isAlphaNum, chr, isAscii, isLetter, isSpace, ord)
+import qualified Data.ByteString.Lazy as BL
+import Data.Maybe (mapMaybe, fromMaybe)
+import Safe (lastMay, initSafe, headDef)
+-- import Debug.Trace
+
+-- TODO:
+-- [ ] more complex table features
+--
+
+-- | Read RTF from an input string and return a Pandoc document.
+readRTF  :: (PandocMonad m, ToSources a)
+         => ReaderOptions
+         -> a
+         -> m Pandoc
+readRTF opts s = do
+  let sources = toSources s
+  parsed <- readWithM parseRTF def{ sOptions = opts } sources
+  case parsed of
+       Left e  -> throwError e
+       Right d -> return d
+
+data CharSet = ANSI | Mac | Pc | Pca
+  deriving (Show, Eq)
+
+-- first index is the list (or override) id, second is the list level
+type ListTable = IntMap.IntMap ListLevelTable
+type ListLevelTable = IntMap.IntMap ListType
+
+data RTFState = RTFState  { sOptions     :: ReaderOptions
+                          , sCharSet     :: CharSet
+                          , sGroupStack  :: [Properties]
+                          , sListStack   :: [List]
+                          , sCurrentCell :: Blocks
+                          , sTableRows   :: [TableRow] -- reverse order
+                          , sTextContent :: [(Properties, Text)]
+                          , sMetadata    :: [(Text, Inlines)]
+                          , sFontTable   :: FontTable
+                          , sStylesheet  :: Stylesheet
+                          , sListTable   :: ListTable
+                          , sListOverrideTable :: ListTable
+                          , sEatChars    :: Int
+                          } deriving (Show)
+
+instance Default RTFState where
+ def = RTFState { sOptions = def
+                , sCharSet = ANSI
+                , sGroupStack = []
+                , sListStack = []
+                , sCurrentCell = mempty
+                , sTableRows = []
+                , sTextContent = []
+                , sMetadata = []
+                , sFontTable = mempty
+                , sStylesheet = mempty
+                , sListTable = mempty
+                , sListOverrideTable = mempty
+                , sEatChars = 0
+                }
+
+type FontTable = IntMap.IntMap FontFamily
+
+data FontFamily =
+  Roman | Swiss | Modern | Script | Decor | Tech | Bidi
+  deriving (Show, Eq)
+
+data StyleType = ParagraphStyle | SectionStyle | CharStyle | TableStyle
+  deriving (Show, Eq)
+
+data Style =
+  Style { styleNum :: Int
+        , styleType :: StyleType
+        , styleBasedOn :: Maybe Int
+        , styleName :: Text
+        , styleFormatting :: [Tok]
+        } deriving (Show, Eq)
+
+type Stylesheet = IntMap.IntMap Style
+
+data PictType =
+  Emfblip | Pngblip | Jpegblip
+  deriving (Show, Eq)
+
+data Pict =
+  Pict { picType :: Maybe PictType
+       , picWidth :: Maybe Int
+       , picHeight :: Maybe Int
+       , picWidthGoal :: Maybe Int
+       , picHeightGoal :: Maybe Int
+       , picBinary :: Bool
+       , picData :: Text
+       , picName :: Text
+       , picBytes :: BL.ByteString
+       } deriving (Show, Eq)
+
+instance Default Pict where
+ def = Pict { picType = Nothing
+            , picWidth = Nothing
+            , picHeight = Nothing
+            , picWidthGoal = Nothing
+            , picHeightGoal = Nothing
+            , picBinary = False
+            , picData = mempty
+            , picName = mempty
+            , picBytes = mempty }
+
+data Properties =
+  Properties
+  { gBold :: Bool
+  , gItalic :: Bool
+  , gCaps :: Bool
+  , gDeleted :: Bool
+  , gSub :: Bool
+  , gSuper :: Bool
+  , gSmallCaps :: Bool
+  , gUnderline :: Bool
+  , gHyperlink :: Maybe Text
+  , gAnchor :: Maybe Text
+  , gImage :: Maybe Pict
+  , gFontFamily :: Maybe FontFamily
+  , gHidden :: Bool
+  , gUC :: Int -- number of ansi chars to skip after unicode char
+  , gFootnote :: Maybe Blocks
+  , gOutlineLevel :: Maybe ListLevel
+  , gListOverride :: Maybe Override
+  , gListLevel :: Maybe Int
+  , gInTable :: Bool
+  } deriving (Show, Eq)
+
+instance Default Properties where
+   def = Properties { gBold = False
+                    , gItalic = False
+                    , gCaps = False
+                    , gDeleted = False
+                    , gSub = False
+                    , gSuper = False
+                    , gSmallCaps = False
+                    , gUnderline = False
+                    , gHyperlink = Nothing
+                    , gAnchor = Nothing
+                    , gImage = Nothing
+                    , gFontFamily = Nothing
+                    , gHidden = False
+                    , gUC = 1
+                    , gFootnote = Nothing
+                    , gOutlineLevel = Nothing
+                    , gListOverride = Nothing
+                    , gListLevel = Nothing
+                    , gInTable = False
+                    }
+
+type RTFParser m = ParsecT Sources RTFState m
+
+data ListType = Bullet | Ordered ListAttributes
+  deriving (Show, Eq)
+
+type Override = Int
+
+type ListLevel = Int
+
+data List =
+    List Override ListLevel ListType [Blocks]  -- items in reverse order
+    deriving (Show, Eq)
+
+newtype TableRow = TableRow [Blocks] -- cells in reverse order
+    deriving (Show, Eq)
+
+parseRTF :: PandocMonad m => RTFParser m Pandoc
+parseRTF = do
+  skipMany nl
+  bs <- many tok >>= foldM processTok mempty >>= emitBlocks
+  unclosed <- closeContainers
+  let doc = B.doc $ bs <> unclosed
+  kvs <- sMetadata <$> getState
+  pure $ foldr (uncurry B.setMeta) doc kvs
+
+data Tok = Tok !SourcePos !TokContents
+  deriving (Show, Eq)
+
+data TokContents =
+    ControlWord !Text !(Maybe Int)
+  | ControlSymbol !Char
+  | UnformattedText !Text
+  | BinData !BL.ByteString
+  | HexVals [Word8]
+  | Grouped [Tok]
+  deriving (Show, Eq)
+
+tok :: PandocMonad m => RTFParser m Tok
+tok = do
+  pos <- getPosition
+  Tok pos <$!> ((controlThing <|> unformattedText <|> grouped) <* skipMany nl)
+ where
+  controlThing = do
+    char '\\' *>
+      ( controlWord
+     <|> (HexVals <$> many1 hexVal)
+     <|> (ControlSymbol <$> anyChar) )
+  controlWord = do
+    name <- letterSequence
+    param <- parameter <* optional delimChar
+    case name of
+      "bin" -> do
+        let n = fromMaybe 0 param
+        spaces
+        -- NOTE: We assume here that if the document contains binary
+        -- data, it will not be valid UTF-8 and hence it will have been
+        -- read as latin1, so we can recover the data in the following
+        -- way.  This is probably not completely reliable, but I don't
+        -- know if we can do better without making this reader take
+        -- a ByteString input.
+        dat <- BL.pack . map (fromIntegral . ord) <$> count n anyChar
+        return $! BinData dat
+      _ -> return $! ControlWord name param
+  parameter = do
+    hyph <- option False $ True <$ char '-'
+    rest <- many digit
+    if null rest
+       then return Nothing
+       else do
+         let pstr = T.pack rest
+         case TR.decimal pstr of
+           Right (!i,_) ->
+                return $! Just $! if hyph
+                                     then (-1) * i
+                                     else i
+           _ -> return Nothing
+  hexVal = do
+    char '\''
+    x <- hexDigit
+    y <- hexDigit
+    return $ hexToWord (T.pack [x,y])
+  letterSequence = T.pack <$> many1 (satisfy (\c -> isAscii c && isLetter c))
+  unformattedText = do
+    ts <-  filter (\c -> c /= '\r' && c /= '\n') <$>
+           ( many1 (satisfy (\c -> not (isSpecial c) || c == '\r' || c == '\n')))
+    return $! UnformattedText $! T.pack ts
+  grouped = do
+    char '{'
+    skipMany nl
+    ts <- manyTill tok (char '}')
+    case ts of
+       Tok _ (ControlWord "rtf" (Just 1)) : _ -> do
+         setInput mempty -- discard remaining input: content after the \rtf1
+                         -- group can be non-RTF
+       _ -> return ()
+    return $! Grouped ts
+
+nl :: PandocMonad m => RTFParser m ()
+nl = void (char '\n' <|> char '\r')
+
+isSpecial :: Char -> Bool
+isSpecial '{' = True
+isSpecial '}' = True
+isSpecial '\\' = True
+isSpecial '\n' = True
+isSpecial _ = False
+
+delimChar :: PandocMonad m => RTFParser m Char
+delimChar = satisfy (\c -> not (isAlphaNum c || isSpecial c))
+
+modifyGroup :: PandocMonad m
+            => (Properties -> Properties)
+            -> RTFParser m ()
+modifyGroup f =
+  updateState $ \st ->
+    st{ sGroupStack =
+          case sGroupStack st of
+            [] -> []
+            (x:xs) -> f x : xs }
+
+-- | @\\plain@ resets character formatting to default values.  Unlike a
+-- full reset to 'def', it must leave paragraph-level properties (such as
+-- whether we are inside a table, the list level, or the outline level)
+-- intact, as well as contextual properties like the current hyperlink or
+-- anchor.  Resetting these caused tables to be parsed as deeply nested
+-- structures when cell paragraphs used @\\plain@ after @\\intbl@.
+resetCharProps :: Properties -> Properties
+resetCharProps g =
+  g{ gBold = False
+   , gItalic = False
+   , gCaps = False
+   , gDeleted = False
+   , gSub = False
+   , gSuper = False
+   , gSmallCaps = False
+   , gUnderline = False
+   , gFontFamily = Nothing
+   , gHidden = False
+   }
+
+addFormatting :: (Properties, Text) -> Inlines
+addFormatting (_, "\n") = B.linebreak
+addFormatting (props, _) | gHidden props = mempty
+addFormatting (props, _) | Just bs <- gFootnote props = B.note bs
+addFormatting (props, txt) =
+  (if gBold props then B.strong else id) .
+  (if gItalic props then B.emph else id) .
+  (if gDeleted props then B.strikeout else id) .
+  (if gSub props then B.subscript else id) .
+  (if gSuper props then B.superscript else id) .
+  (if gSmallCaps props then B.smallcaps else id) .
+  (if gUnderline props then B.underline else id) .
+  (case gHyperlink props of
+     Nothing -> id
+     Just linkdest -> B.link linkdest mempty) .
+  (case gAnchor props of
+     Nothing -> id
+     Just ident -> B.spanWith (ident,[],[])) .
+  (case gFontFamily props of
+     Just Modern -> B.code
+     _ -> case gImage props of
+            Just pict ->
+              let attr = ("",[],
+                         (case picWidthGoal pict of
+                           Nothing -> []
+                           Just w  -> [("width", tshow (fromIntegral w / 1440
+                                                         :: Double)
+                                          <> "in")]) ++
+                         (case picHeightGoal pict of
+                            Nothing -> []
+                            Just h -> [("height", tshow (fromIntegral h / 1440
+                                                         :: Double)
+                                          <> "in")]))
+              in  B.imageWith attr (picName pict) "" . B.text
+            Nothing -> B.text) .
+  (if gCaps props then T.toUpper else id)
+  $ txt
+
+addText :: PandocMonad m => Text -> RTFParser m ()
+addText t = do
+  gs <- sGroupStack <$> getState
+  let !props = case gs of
+                (x:_) -> x
+                _ -> def
+  updateState (\s -> s{ sTextContent = (props, t) : sTextContent s })
+
+inGroup :: PandocMonad m => RTFParser m a -> RTFParser m a
+inGroup p = do
+  updateState $ \st ->
+    st{ sGroupStack =
+        case sGroupStack st of
+          [] -> [def]
+          (x:xs) -> (x:x:xs) } -- inherit current group's properties
+  result <- p
+  updateState $ \st ->
+    st{ sGroupStack =
+        case sGroupStack st of
+          [] -> [] -- should not happen
+          (_:xs) -> xs }
+  return result
+
+getStyleFormatting :: PandocMonad m => Int -> RTFParser m [Tok]
+getStyleFormatting stynum = do
+  stylesheet <- sStylesheet <$> getState
+  case IntMap.lookup stynum stylesheet of
+    Nothing -> return []
+    Just sty ->
+      case styleBasedOn sty of
+        Just i -> (<> styleFormatting sty)  <$> getStyleFormatting i
+        Nothing -> return $ styleFormatting sty
+
+isMetadataField :: Text -> Bool
+isMetadataField "title" = True
+isMetadataField "subject" = True
+isMetadataField "author" = True
+isMetadataField "manager" = True
+isMetadataField "company" = True
+isMetadataField "operator" = True
+isMetadataField "category" = True
+isMetadataField "keywords" = True
+isMetadataField "comment" = True
+isMetadataField "doccomm" = True
+isMetadataField "hlinkbase" = True
+isMetadataField "generator" = True
+isMetadataField _ = False
+
+isHeaderFooter :: Text -> Bool
+isHeaderFooter "header" = True
+isHeaderFooter "headerl" = True
+isHeaderFooter "headerr" = True
+isHeaderFooter "headerf" = True
+isHeaderFooter "footer" = True
+isHeaderFooter "footerl" = True
+isHeaderFooter "footerr" = True
+isHeaderFooter "footerf" = True
+isHeaderFooter _ = False
+
+boolParam :: Maybe Int -> Bool
+boolParam (Just 0) = False
+boolParam _ = True
+
+isUnderline :: Text -> Bool
+isUnderline "ul" = True
+isUnderline "uld" = True
+isUnderline "uldash" = True
+isUnderline "uldashd" = True
+isUnderline "uldashdd" = True
+isUnderline "uldb" = True
+isUnderline "ulth" = True
+isUnderline "ulthd" = True
+isUnderline "ulthdash" = True
+isUnderline "ulw" = True
+isUnderline "ulwave" = True
+isUnderline _ = False
+
+processTok :: PandocMonad m => Blocks -> Tok -> RTFParser m Blocks
+processTok bs (Tok pos tok') = do
+  setPosition pos
+  case tok' of
+    HexVals{} -> return ()
+    UnformattedText{} -> return ()
+    _ -> updateState $ \s -> s{ sEatChars = 0 }
+  case tok' of
+    Grouped (Tok _ (ControlSymbol '*') : toks@(firsttok:_)) ->
+      case firsttok of
+        Tok _ (ControlWord "shppict" _) -> inGroup (foldM processTok bs toks)
+        Tok _ (ControlWord "shpinst" _) -> inGroup (foldM processTok bs toks)
+        _ -> bs <$ (do oldTextContent <- sTextContent <$> getState
+                       processTok mempty (Tok pos (Grouped toks))
+                       updateState $ \st -> st{ sTextContent = oldTextContent })
+    Grouped (Tok _ (ControlWord "shp" _) : toks) ->
+      inGroup (foldM processTok bs toks)
+    Grouped [ Tok _ (ControlWord "sp" _)
+            , Tok _ (Grouped [Tok _ (ControlWord "sn" _),
+                      Tok _ (UnformattedText sn)])
+            , Tok _ (Grouped (Tok _ (ControlWord "sv" _) : svtoks))
+            ] ->
+      case sn of
+        "pib" -> inGroup (foldM processTok bs svtoks)
+        _ -> pure bs
+    Grouped (Tok _ (ControlWord "fonttbl" _) : toks) -> inGroup $ do
+      updateState $ \s -> s{ sFontTable = processFontTable toks }
+      pure bs
+    Grouped (Tok _ (ControlWord "field" _) : toks) ->
+      inGroup $ handleField bs toks
+    Grouped (Tok _ (ControlWord "pict" _) : toks) ->
+      bs <$ inGroup (handlePict toks)
+    Grouped (Tok _ (ControlWord "stylesheet" _) : toks) ->
+      bs <$ inGroup (handleStylesheet toks)
+    Grouped (Tok _ (ControlWord "listtext" _) : _) -> do
+      -- eject any previous list items...sometimes TextEdit
+      -- doesn't put in a \par
+      emitBlocks bs
+    Grouped (Tok _ (ControlWord "pgdsc" _) : _) -> pure bs
+    Grouped (Tok _ (ControlWord "colortbl" _) : _) -> pure bs
+    Grouped (Tok _ (ControlWord "listtable" _) : toks) ->
+      bs <$ inGroup (handleListTable toks)
+    Grouped (Tok _ (ControlWord "listoverridetable" _) : toks) ->
+      bs <$ inGroup (handleListOverrideTable toks)
+    Grouped (Tok _ (ControlWord "wgrffmtfilter" _) : _) -> pure bs
+    Grouped (Tok _ (ControlWord "themedata" _) : _) -> pure bs
+    Grouped (Tok _ (ControlWord "colorschememapping" _) : _) -> pure bs
+    Grouped (Tok _ (ControlWord "datastore" _) : _) -> pure bs
+    Grouped (Tok _ (ControlWord "latentstyles" _) : _) -> pure bs
+    Grouped (Tok _ (ControlWord "pntxta" _) : _) -> pure bs -- TODO
+    Grouped (Tok _ (ControlWord "pntxtb" _) : _) -> pure bs -- TODO
+    Grouped (Tok _ (ControlWord "xmlnstbl" _) : _) -> pure bs
+    Grouped (Tok _ (ControlWord "filetbl" _) : _) -> pure bs
+    Grouped (Tok _ (ControlWord "expandedcolortbl" _) : _) -> pure bs
+    Grouped (Tok _ (ControlWord "listtables" _) : _) -> pure bs
+    Grouped (Tok _ (ControlWord "revtbl" _) : _) -> pure bs
+    Grouped (Tok _ (ControlWord "bkmkstart" _)
+             : Tok _ (UnformattedText t) : _) -> do
+      -- TODO ideally we'd put the span around bkmkstart/end, but this
+      -- is good for now:
+      modifyGroup (\g -> g{ gAnchor = Just $ T.strip t })
+      pure bs
+    Grouped (Tok _ (ControlWord "bkmkend" _) : _) -> do
+      modifyGroup (\g -> g{ gAnchor = Nothing })
+      pure bs
+    Grouped (Tok _ (ControlWord f _) : _) | isHeaderFooter f -> pure bs
+    Grouped (Tok _ (ControlWord "footnote" _) : toks) -> do
+      noteBs <- inGroup $ processDestinationToks toks
+      modifyGroup (\g -> g{ gFootnote = Just noteBs })
+      addText "*"
+      modifyGroup (\g -> g{ gFootnote = Nothing })
+      return bs
+    Grouped (Tok _ (ControlWord "info" _) : toks) ->
+      bs <$ inGroup (processDestinationToks toks)
+    Grouped (Tok _ (ControlWord f _) : toks) | isMetadataField f -> inGroup $ do
+      foldM_ processTok mempty toks
+      annotatedToks <- reverse . sTextContent <$> getState
+      updateState $ \s -> s{ sTextContent = [] }
+      let ils = B.trimInlines . mconcat $ map addFormatting annotatedToks
+      updateState $ \s -> s{ sMetadata = (f, ils) : sMetadata s }
+      pure bs
+    Grouped toks -> inGroup (foldM processTok bs toks)
+    UnformattedText t -> bs <$ do
+      -- return $! traceShowId $! (pos, t)
+      eatChars <- sEatChars <$> getState
+      case eatChars of
+        0 -> addText t
+        n | n < T.length t -> do
+             updateState $ \s -> s{ sEatChars = 0 }
+             addText (T.drop n t)
+          | otherwise -> do
+             updateState $ \s -> s{ sEatChars = n - T.length t }
+    HexVals ws -> bs <$ do
+      eatChars <- sEatChars <$> getState
+      let ws' = drop eatChars ws
+      updateState $ \s -> s{ sEatChars = if null ws'
+                                            then eatChars - length ws
+                                            else 0 }
+      charset <- sCharSet <$> getState
+      case charset of
+        ANSI -> addText $ T.pack $ map defaultAnsiWordToChar ws'
+        Mac  -> addText $ T.pack $ map macToChar ws'
+        Pc   -> addText $ T.pack $ map pcToChar ws'
+        Pca  -> addText $ T.pack $ map pcaToChar ws'
+    ControlWord "ansi" _ -> bs <$
+      updateState (\s -> s{ sCharSet = ANSI })
+    ControlWord "ansicpg" (Just cpg) | cpg /= 1252 -> bs <$
+      report (UnsupportedCodePage cpg)
+    ControlWord "mac" _ -> bs <$
+      updateState (\s -> s{ sCharSet = Mac })
+    ControlWord "pc" _ -> bs <$
+      updateState (\s -> s{ sCharSet = Pc })
+    ControlWord "pca" _ -> bs <$
+      updateState (\s -> s{ sCharSet = Pca })
+    ControlWord "outlinelevel" mbp -> bs <$
+      modifyGroup (\g -> g{ gOutlineLevel = mbp })
+    ControlWord "ls" mbp -> bs <$
+      modifyGroup (\g -> g{ gListOverride = mbp })
+    ControlWord "ilvl" mbp -> bs <$
+      modifyGroup (\g -> g{ gListLevel = mbp })
+    ControlSymbol '\\' -> bs <$ addText "\\"
+    ControlSymbol '{' -> bs <$ addText "{"
+    ControlSymbol '}' -> bs <$ addText "}"
+    ControlSymbol '~' -> bs <$ addText "\x00a0"
+    ControlSymbol '-' -> bs <$ addText "\x00ad"
+    ControlSymbol '_' -> bs <$ addText "\x2011"
+    ControlWord "trowd" _ -> bs <$ beginTableRow -- begin new row
+    ControlWord "row" _ -> bs <$ beginTableRow -- end current row
+    ControlWord "cell" _ -> bs <$ do
+      new <- emitBlocks mempty
+      curCell <- (<> new) . sCurrentCell <$> getState
+      updateState $ \s -> s{ sTableRows =
+                                case sTableRows s of
+                                  TableRow cs : rs ->
+                                    TableRow (curCell : cs) : rs
+                                  [] -> [TableRow [curCell]] -- shouldn't happen
+                           , sCurrentCell = mempty }
+    ControlWord "intbl" _ -> do
+      ls <- closeLists 0 -- see #11364
+      ((ls <>) <$> emitBlocks bs) <* modifyGroup (\g -> g{ gInTable = True })
+    ControlWord "plain" _ -> bs <$ modifyGroup resetCharProps
+    ControlWord "lquote" _ -> bs <$ addText "\x2018"
+    ControlWord "rquote" _ -> bs <$ addText "\x2019"
+    ControlWord "ldblquote" _ -> bs <$ addText "\x201C"
+    ControlWord "rdblquote" _ -> bs <$ addText "\x201D"
+    ControlWord "emdash" _ -> bs <$ addText "\x2014"
+    ControlWord "emspace" _ -> bs <$ addText "\x2003"
+    ControlWord "enspace" _ -> bs <$ addText "\x2002"
+    ControlWord "endash" _ -> bs <$ addText "\x2013"
+    ControlWord "bullet" _ -> bs <$ addText "\x2022"
+    ControlWord "tab" _ -> bs <$ addText "\t"
+    ControlWord "line" _ -> bs <$ addText "\n"
+    ControlSymbol '\n' -> bs <$ addText "\n"
+    ControlSymbol '\r' -> bs <$ addText "\n"
+    ControlWord "uc" (Just i) -> bs <$ modifyGroup (\g -> g{ gUC = i })
+    ControlWord "cs" (Just n) -> do
+      getStyleFormatting n >>= foldM processTok bs
+    ControlWord "s" (Just n) -> do
+      getStyleFormatting n >>= foldM processTok bs
+    ControlWord "ds" (Just n) -> do
+      getStyleFormatting n >>= foldM processTok bs
+    ControlWord "f" (Just i) -> bs <$ do
+      fontTable <- sFontTable <$> getState
+      modifyGroup (\g -> g{ gFontFamily = IntMap.lookup i fontTable })
+    ControlWord "u" (Just i) -> bs <$ do
+      st <- getState
+      let curgroup = case sGroupStack st of
+                       [] -> def
+                       (x:_) -> x
+      updateState $ \s -> s{ sEatChars = gUC curgroup }
+      -- "RTF control words generally accept signed 16-bit numbers as
+      -- arguments. For this reason, Unicode values greater than 32767
+      -- must be expressed as negative numbers."
+      let codepoint :: Word16
+          codepoint = fromIntegral i
+      addText (T.singleton (chr $ fromIntegral codepoint))
+    ControlWord "caps" mbp -> bs <$
+      modifyGroup (\g -> g{ gCaps = boolParam mbp })
+    ControlWord "deleted" mbp -> bs <$
+      modifyGroup (\g -> g{ gDeleted = boolParam mbp })
+    ControlWord "b" mbp -> bs <$
+      modifyGroup (\g -> g{ gBold = boolParam mbp })
+    ControlWord "i" mbp -> bs <$
+      modifyGroup (\g -> g{ gItalic = boolParam mbp })
+    ControlWord "sub" mbp -> bs <$
+      modifyGroup (\g -> g{ gSub = boolParam mbp })
+    ControlWord "super" mbp -> bs <$
+      modifyGroup (\g -> g{ gSuper = boolParam mbp })
+    ControlWord "nosupersub" mbp -> bs <$
+      modifyGroup (\g -> g{ gSuper = not $ boolParam mbp
+                          , gSub = not $ boolParam mbp })
+    ControlWord "up" mbp -> bs <$
+      modifyGroup (\g -> g{ gSuper = boolParam mbp })
+    ControlWord "strike" mbp -> bs <$
+      modifyGroup (\g -> g{ gDeleted = boolParam mbp })
+    ControlWord "strikedl" mbp -> bs <$
+      modifyGroup (\g -> g{ gDeleted = boolParam mbp })
+    ControlWord "striked" mbp -> bs <$
+      modifyGroup (\g -> g{ gDeleted = boolParam mbp })
+    ControlWord "scaps" mbp -> bs <$
+      modifyGroup (\g -> g{ gSmallCaps = boolParam mbp })
+    ControlWord "v" mbp -> bs <$
+      modifyGroup (\g -> g{ gHidden = boolParam mbp })
+    ControlWord x mbp | isUnderline x -> bs <$
+      modifyGroup (\g -> g{ gUnderline = boolParam mbp })
+    ControlWord "ulnone" _ -> bs <$
+      modifyGroup (\g -> g{ gUnderline = False })
+    ControlWord "pard" _ -> do
+      newbs <- emitBlocks bs
+      modifyGroup (const def)
+      getStyleFormatting 0 >>= foldM processTok newbs
+    ControlWord "par" _ -> emitBlocks bs
+    _ -> pure bs
+
+processDestinationToks :: PandocMonad m => [Tok] -> RTFParser m Blocks
+processDestinationToks toks = do
+  textContent <- sTextContent <$> getState
+  liststack <- sListStack <$> getState
+  updateState $ \s -> s{ sTextContent = mempty
+                       , sListStack = [] }
+  result <- inGroup $
+              foldM processTok mempty toks >>= emitBlocks
+  unclosed <- closeContainers
+  updateState $ \s -> s{ sTextContent = textContent
+                       , sListStack = liststack }
+  return $ result <> unclosed
+
+-- close lists >= level
+closeLists :: PandocMonad m => Int -> RTFParser m Blocks
+closeLists lvl = do
+  lists <- sListStack <$> getState
+  case lists of
+    (List _ lvl' lt items : rest) | lvl' >= lvl -> do
+      let newlist = (case lt of
+                      Bullet -> B.bulletList
+                      Ordered listAttr -> B.orderedListWith listAttr)
+                    (reverse items)
+      updateState $ \s -> s{ sListStack = rest }
+      case rest of
+        [] -> do
+          updateState $ \s -> s{ sListStack = rest }
+          pure newlist
+        (List lo lvl'' lt' [] : rest') -> do -- should not happen
+          updateState $ \s -> s{ sListStack =
+               List lo lvl'' lt' [newlist] : rest' }
+          closeLists lvl
+        (List lo lvl'' lt' (i:is) : rest') -> do
+          updateState $ \s -> s{ sListStack =
+               List lo lvl'' lt' (i <> newlist : is) : rest' }
+          closeLists lvl
+    _ -> pure mempty
+
+-- Begin a new table row.  Both @\\trowd@ (which sets row defaults) and
+-- @\\row@ (which ends a row) start a fresh row to be filled by subsequent
+-- @\\cell@s.  We only push a new empty row when the current one already has
+-- cells, so that documents repeating @\\trowd@ after @\\row@ (or omitting
+-- @\\trowd@ between rows) both produce the same flat structure.
+beginTableRow :: PandocMonad m => RTFParser m ()
+beginTableRow =
+  updateState $ \s ->
+    s{ sTableRows = case sTableRows s of
+                      TableRow [] : _ -> sTableRows s
+                      rs -> TableRow [] : rs
+     , sCurrentCell = mempty }
+
+closeTable :: PandocMonad m => RTFParser m Blocks
+closeTable = do
+  rawrows <- sTableRows <$> getState
+  if null rawrows
+     then return mempty
+     else do
+       let getCells (TableRow cs) = reverse cs
+       -- drop empty rows produced by row terminators
+       let rows = filter (not . null) . map getCells . reverse $ rawrows
+       updateState $ \s -> s{ sCurrentCell = mempty
+                            , sTableRows = [] }
+       if null rows
+          then return mempty
+          else return $ B.simpleTable [] rows
+
+closeContainers :: PandocMonad m => RTFParser m Blocks
+closeContainers = do
+  tbl <- closeTable
+  lists <- closeLists 0
+  return $ tbl <> lists
+
+trimFinalLineBreak :: Inlines -> Inlines
+trimFinalLineBreak ils =
+  case Seq.viewr (B.unMany ils) of
+    rest Seq.:> LineBreak -> B.Many rest
+    _ -> ils
+
+emitBlocks :: PandocMonad m => Blocks -> RTFParser m Blocks
+emitBlocks bs = do
+  annotatedToks <- reverse . sTextContent <$> getState
+  updateState $ \s -> s{ sTextContent = [] }
+  let justCode = def{ gFontFamily = Just Modern }
+  let prop = case annotatedToks of
+               [] -> def
+               ((p,_):_) -> p
+  tbl <- if gInTable prop || null annotatedToks
+            then pure mempty
+            else closeTable
+  new <-
+    case annotatedToks of
+      [] -> pure mempty
+      _ | Just lst <- gListOverride prop
+         -> do
+           let level = fromMaybe 0 $ gListLevel prop
+           listOverrideTable <- sListOverrideTable <$> getState
+           let listType = fromMaybe Bullet $
+                 IntMap.lookup lst listOverrideTable >>= IntMap.lookup level
+           lists <- sListStack <$> getState
+           -- get para contents of list item
+           let newbs = B.para . B.trimInlines . trimFinalLineBreak . mconcat $
+                        map addFormatting annotatedToks
+           case lists of
+             (List lo parentlevel _lt items : cs)
+               | lo == lst
+               , parentlevel == level
+               -- add another item to existing list
+               -> do updateState $ \s ->
+                        s{ sListStack =
+                             List lo level listType (newbs:items) : cs }
+                     pure mempty
+               | lo /= lst || level < parentlevel
+               -- close parent list and add new list
+               -> do new <- closeLists level  -- close open lists > level
+                     updateState $ \s ->
+                       s{ sListStack = List lst level listType [newbs] :
+                           sListStack s }
+                     pure new
+             _ -> do -- add new list (level > parentlevel)
+                  updateState $ \s ->
+                    s{ sListStack = List lst level listType [newbs] :
+                         sListStack s }
+                  pure mempty
+        | Just lvl <- gOutlineLevel prop
+         -> do
+            lists <- closeLists 0
+            pure $ lists <>
+                   B.header (lvl + 1)
+                   (B.trimInlines . mconcat $ map addFormatting
+                                            $ removeCommonFormatting
+                                              annotatedToks)
+        | all ((== justCode) . fst) annotatedToks
+         -> do
+            lists <- closeLists 0
+            pure $ lists <>
+                    B.codeBlock (mconcat $ map snd annotatedToks)
+        | all (T.all isSpace . snd) annotatedToks
+         -> closeLists 0
+        | otherwise -> do
+            lists <- closeLists 0
+            pure $ lists <>
+              B.para (B.trimInlines . trimFinalLineBreak . mconcat
+                $ map addFormatting annotatedToks)
+  if gInTable prop
+     then do
+       updateState $ \s -> s{ sCurrentCell = sCurrentCell s <> new }
+       pure bs
+     else do
+       pure $ bs <> tbl <> new
+
+-- Headers often have a style applied. We usually want to remove
+-- this, because headers will have their own styling in the target
+-- format.
+removeCommonFormatting :: [(Properties, Text)] -> [(Properties, Text)]
+removeCommonFormatting =
+  (\ts ->
+    if all (gBold . fst) ts
+       then map (\(p,t) -> (p{ gBold = False }, t)) ts
+       else ts) .
+  (\ts ->
+    if all (gItalic . fst) ts
+       then map (\(p,t) -> (p{ gItalic = False }, t)) ts
+       else ts)
+
+
+-- {\field{\*\fldinst{HYPERLINK "http://pandoc.org"}}{\fldrslt foo}}
+handleField :: PandocMonad m => Blocks -> [Tok] -> RTFParser m Blocks
+handleField bs ts = do
+  let isFieldMod (Tok _ (ControlWord w _)) =
+        w `elem` ["flddirty", "fldedit", "fldlock", "fldpriv"]
+      isFieldMod _ = False
+
+  let instructionTokens (Tok _ (Grouped toks)) = Just toks
+      instructionTokens unformattedTok@(Tok _ (UnformattedText _)) = Just [unformattedTok]
+      instructionTokens _ = Nothing
+  case dropWhile isFieldMod ts of
+    [Tok _ (Grouped
+       (Tok _ (ControlSymbol '*')
+       :Tok _ (ControlWord "fldinst" Nothing)
+       :instrtoks
+       :_)),
+     Tok _ (Grouped
+       (Tok _ (ControlWord "fldrslt" Nothing)
+       :resulttoks))] -> do
+         case instructionTokens instrtoks of
+           Nothing -> pure bs
+           Just instrtoks' ->
+             case getHyperlink instrtoks' of
+               Just linkdest -> do
+                 modifyGroup $ \g -> g{ gHyperlink = Just linkdest }
+                 result <- foldM processTok bs resulttoks
+                 modifyGroup $ \g -> g{ gHyperlink = Nothing }
+                 return result
+               Nothing -> foldM processTok bs resulttoks
+    _ -> pure bs
+
+getHyperlink :: [Tok] -> Maybe Text
+getHyperlink [] = Nothing
+getHyperlink (Tok _ (UnformattedText w) : rest)
+  | Just w' <- unquote <$> T.stripPrefix "HYPERLINK" (T.strip w)
+    = if T.null w'
+         then case rest of
+                (Tok _ (ControlSymbol '\\') : Tok _ (UnformattedText b) : _)
+                  | Just bkmrk <- unquote <$> T.stripPrefix "l " (T.strip b)
+                    -> Just $ "#" <> bkmrk
+                _ -> Just mempty
+         else Just w'
+getHyperlink (_:ts) = getHyperlink ts
+
+unquote :: Text -> Text
+unquote = T.dropWhile (=='"') . T.dropWhileEnd (=='"') . T.strip
+
+handleListTable :: PandocMonad m => [Tok] -> RTFParser m ()
+handleListTable toks = do
+  mapM_ handleList toks
+
+handleList :: PandocMonad m => Tok -> RTFParser m ()
+handleList (Tok _ (Grouped (Tok _ (ControlWord "list" _) : toks))) = do
+  let listid = headDef 0 [n | Tok _ (ControlWord "listid" (Just n)) <- toks]
+  let levels = [ts | Tok _ (Grouped (Tok _ (ControlWord "listlevel" _) : ts))
+                 <- toks]
+  tbl <- foldM handleListLevel mempty (zip [0..] levels)
+  updateState $ \s -> s{ sListTable = IntMap.insert listid tbl $ sListTable s }
+handleList _ = return ()
+
+handleListLevel :: PandocMonad m
+                => ListLevelTable
+                -> (Int, [Tok])
+                -> RTFParser m ListLevelTable
+handleListLevel levelTable (lvl, toks) = do
+  let start = headDef 1
+                [n | Tok _ (ControlWord "levelstartat" (Just n)) <- toks]
+  let mbNumberStyle =
+        case [n | Tok _ (ControlWord "levelnfc" (Just n)) <- toks] of
+          [] -> Nothing
+          (0:_) -> Just Decimal
+          (1:_) -> Just UpperRoman
+          (2:_) -> Just LowerRoman
+          (3:_) -> Just UpperAlpha
+          (4:_) -> Just LowerAlpha
+          (23:_) -> Nothing
+          (255:_) -> Nothing
+          _ -> Just DefaultStyle
+  let listType = case mbNumberStyle of
+                   Nothing -> Bullet
+                   Just numStyle -> Ordered (start,numStyle,Period)
+  return $ IntMap.insert lvl listType levelTable
+
+handleListOverrideTable :: PandocMonad m => [Tok] -> RTFParser m ()
+handleListOverrideTable toks = mapM_ handleListOverride toks
+
+handleListOverride :: PandocMonad m => Tok -> RTFParser m ()
+handleListOverride
+ (Tok _ (Grouped (Tok _ (ControlWord "listoverride" _) : toks))) = do
+  let listid = headDef 0 [n | Tok _ (ControlWord "listid" (Just n)) <- toks]
+  let lsn = headDef 0 [n | Tok _ (ControlWord "ls" (Just n)) <- toks]
+  -- TODO override stuff, esp. start num -- for now we just handle indirection
+  listTable <- sListTable <$> getState
+  case IntMap.lookup listid listTable of
+    Nothing -> return ()
+    Just tbl -> updateState $ \s ->
+                   s{ sListOverrideTable = IntMap.insert lsn tbl $
+                        sListOverrideTable s }
+handleListOverride _ = return ()
+
+handleStylesheet :: PandocMonad m => [Tok] -> RTFParser m ()
+handleStylesheet toks = do
+  let styles = mapMaybe parseStyle toks
+  updateState $ \s -> s{ sStylesheet = IntMap.fromList
+                                     $ zip (map styleNum styles) styles }
+
+parseStyle :: Tok -> Maybe Style
+parseStyle (Tok _ (Grouped toks)) = do
+  let (styType, styNum, rest) =
+        case toks of
+          Tok _ (ControlWord "s" (Just n)) : ts -> (ParagraphStyle, n, ts)
+          Tok _ (ControlWord "ds" (Just n)) : ts -> (SectionStyle, n, ts)
+          Tok _ (ControlWord "cs" (Just n)) : ts -> (CharStyle, n, ts)
+          Tok _ (ControlWord "ts" (Just n)) : ts -> (TableStyle, n, ts)
+          _ -> (ParagraphStyle, 0, toks)
+  let styName = case lastMay rest of
+                  Just (Tok _ (UnformattedText t)) -> T.dropWhileEnd (==';') t
+                  _ -> mempty
+  let isBasedOn (Tok _ (ControlWord "sbasedon" (Just _))) = True
+      isBasedOn _ = False
+  let styBasedOn = case L.find isBasedOn toks of
+                     Just (Tok _ (ControlWord "sbasedon" (Just i))) -> Just i
+                     _ -> Nothing
+  let isStyleControl (Tok _ (ControlWord x _)) =
+         x `elem` ["cs", "s", "ds", "additive", "sbasedon", "snext",
+                   "sautoupd", "shidden", "keycode", "alt", "shift",
+                   "ctrl", "fn"]
+      isStyleControl _ = False
+  let styFormatting = filter (not . isStyleControl) (initSafe rest)
+  return $ Style{ styleNum = styNum
+                , styleType = styType
+                , styleBasedOn = styBasedOn
+                , styleName = styName
+                , styleFormatting = styFormatting
+                }
+parseStyle _ = Nothing
+
+hexToWord  :: Text -> Word8
+hexToWord t = case TR.hexadecimal t of
+                Left _ -> 0
+                Right (x,_) -> x
+
+
+handlePict :: PandocMonad m => [Tok] -> RTFParser m ()
+handlePict toks = do
+  let pict = L.foldl' getPictData def toks
+  let altText = "image"
+  let bytes =
+        if picBinary pict
+           then picBytes pict
+           else BL.pack $ map hexToWord $ T.chunksOf 2 $ picData pict
+  let (mimetype, ext) =
+        case picType pict of
+          Just Emfblip -> (Just "image/x-emf", ".emf")
+          Just Pngblip -> (Just "image/png", ".png")
+          Just Jpegblip -> (Just "image/jpeg", ".jpg")
+          Nothing -> (Nothing, "")
+  case mimetype of
+    Just mt -> do
+      let pictname = show (hashWith SHA1 $ BL.toStrict bytes) <> ext
+      insertMedia pictname (Just mt) bytes
+      modifyGroup $ \g -> g{ gImage = Just pict{ picName = T.pack pictname,
+                                                 picBytes = bytes } }
+      addText altText
+      modifyGroup $ \g -> g{ gImage = Nothing }
+    _ -> return ()
+ where
+  getPictData :: Pict -> Tok -> Pict
+  getPictData pict (Tok _ tok') =
+    case tok' of
+      ControlWord "emfblip" _-> pict{ picType = Just Emfblip }
+      ControlWord "pngblip" _-> pict{ picType = Just Pngblip }
+      ControlWord "jpegblip" _-> pict{ picType = Just Jpegblip }
+      ControlWord "picw" (Just w) -> pict{ picWidth = Just w }
+      ControlWord "pich" (Just h) -> pict{ picHeight = Just h }
+      ControlWord "picwgoal" (Just w) -> pict{ picWidthGoal = Just w }
+      ControlWord "pichgoal" (Just h) -> pict{ picHeightGoal = Just h }
+      BinData d | not (BL.null d)
+                  -> pict{ picBinary = True, picBytes = picBytes pict <> d }
+      UnformattedText t -> pict{ picData = t }
+      _ -> pict
+
+
+processFontTable :: [Tok] -> FontTable
+processFontTable = snd . L.foldl' go (0, mempty)
+ where
+  go (fontnum, tbl) (Tok _ tok') =
+    case tok' of
+     (ControlWord "f" (Just i)) -> (i, tbl)
+     (ControlWord "fnil" _) -> (fontnum, tbl)
+     (ControlWord "froman" _) -> (fontnum, IntMap.insert fontnum Roman tbl)
+     (ControlWord "fswiss" _) -> (fontnum, IntMap.insert fontnum Swiss tbl)
+     (ControlWord "fmodern" _) -> (fontnum, IntMap.insert fontnum Modern tbl)
+     (ControlWord "fscript" _) -> (fontnum, IntMap.insert fontnum Script tbl)
+     (ControlWord "fdecor" _) -> (fontnum, IntMap.insert fontnum Decor tbl)
+     (ControlWord "ftech" _) -> (fontnum, IntMap.insert fontnum Tech tbl)
+     (ControlWord "fbidi" _) -> (fontnum, IntMap.insert fontnum Bidi tbl)
+     (Grouped ts) -> L.foldl' go (fontnum, tbl) ts
+     _ -> (fontnum, tbl)
+
+defaultAnsiWordToChar :: Word8 -> Char
+defaultAnsiWordToChar i =
+  case i of
+    128 -> '\8364'
+    130 -> '\8218'
+    131 -> '\402'
+    132 -> '\8222'
+    133 -> '\8230'
+    134 -> '\8224'
+    135 -> '\8225'
+    136 -> '\710'
+    137 -> '\8240'
+    138 -> '\352'
+    139 -> '\8249'
+    140 -> '\338'
+    142 -> '\381'
+    145 -> '\8216'
+    146 -> '\8217'
+    147 -> '\8220'
+    148 -> '\8221'
+    149 -> '\8226'
+    150 -> '\8211'
+    151 -> '\8212'
+    152 -> '\732'
+    153 -> '\8482'
+    154 -> '\353'
+    155 -> '\8250'
+    156 -> '\339'
+    158 -> '\382'
+    159 -> '\376'
+    173 -> '\xAD'
+    _ -> chr (fromIntegral i)
+
+macToChar :: Word8 -> Char
+macToChar i = chr $
+  case i of
+    0x80 -> 0xC4
+    0x81 -> 0xC5
+    0x82 -> 0xC7
+    0x83 -> 0xC9
+    0x84 -> 0xD1
+    0x85 -> 0xD6
+    0x86 -> 0xDC
+    0x87 -> 0xE1
+    0x88 -> 0xE0
+    0x89 -> 0xE2
+    0x8A -> 0xE4
+    0x8B -> 0xE3
+    0x8C -> 0xE5
+    0x8D -> 0xE7
+    0x8E -> 0xE9
+    0x8F -> 0xE8
+    0x90 -> 0xEA
+    0x91 -> 0xEB
+    0x92 -> 0xED
+    0x93 -> 0xEC
+    0x94 -> 0xEE
+    0x95 -> 0xEF
+    0x96 -> 0xF1
+    0x97 -> 0xF3
+    0x98 -> 0xF2
+    0x99 -> 0xF4
+    0x9A -> 0xF6
+    0x9B -> 0xF5
+    0x9C -> 0xFA
+    0x9D -> 0xF9
+    0x9E -> 0xFB
+    0x9F -> 0xFC
+    0xA0 -> 0xDD
+    0xA1 -> 0xB0
+    0xA2 -> 0xA2
+    0xA3 -> 0xA3
+    0xA4 -> 0xA7
+    0xA5 -> 0xD7
+    0xA6 -> 0xB6
+    0xA7 -> 0xDF
+    0xA8 -> 0xAE
+    0xA9 -> 0xA9
+    0xAA -> 0xB2
+    0xAB -> 0xB4
+    0xAC -> 0xA8
+    0xAD -> 0xB3
+    0xAE -> 0xC6
+    0xAF -> 0xD8
+    0xB0 -> 0xB9
+    0xB1 -> 0xB1
+    0xB2 -> 0xBC
+    0xB3 -> 0xBD
+    0xB4 -> 0xA5
+    0xB5 -> 0xB5
+    0xBA -> 0xBE
+    0xBB -> 0xAA
+    0xBC -> 0xBA
+    0xBE -> 0xE6
+    0xBF -> 0xF8
+    0xC0 -> 0xBF
+    0xC1 -> 0xA1
+    0xC2 -> 0xAC
+    0xC3 -> 0x0141
+    0xC4 -> 0x0192
+    0xC5 -> 0x02CB
+    0xC7 -> 0xAB
+    0xC8 -> 0xBB
+    0xC9 -> 0xA6
+    0xCA -> 0xA0
+    0xCB -> 0xC0
+    0xCC -> 0xC3
+    0xCD -> 0xD5
+    0xCE -> 0x0152
+    0xCF -> 0x0153
+    0xD0 -> 0xAD
+    0xD4 -> 0x0142
+    0xD6 -> 0xF7
+    0xD8 -> 0xFF
+    0xD9 -> 0x0178
+    0xDB -> 0xA4
+    0xDC -> 0xD0
+    0xDD -> 0xF0
+    0xDE -> 0xDE
+    0xDF -> 0xFE
+    0xE0 -> 0xFD
+    0xE1 -> 0xB7
+    0xE5 -> 0xC2
+    0xE6 -> 0xCA
+    0xE7 -> 0xC1
+    0xE8 -> 0xCB
+    0xE9 -> 0xC8
+    0xEA -> 0xCD
+    0xEB -> 0xCE
+    0xEC -> 0xCF
+    0xED -> 0xCC
+    0xEE -> 0xD3
+    0xEF -> 0xD4
+    0xF1 -> 0xD2
+    0xF2 -> 0xDA
+    0xF3 -> 0xDB
+    0xF4 -> 0xD9
+    0xF5 -> 0x0131
+    0xF6 -> 0x02C6
+    0xF7 -> 0x02DC
+    0xF8 -> 0xAF
+    0xF9 -> 0x02D8
+    0xFA -> 0x02D9
+    0xFB -> 0x02DA
+    0xFC -> 0xB8
+    0xFD -> 0x02DD
+    0xFE -> 0x02DB
+    0xFF -> 0x02C7
+    _ -> fromIntegral i
+
+pcToChar :: Word8 -> Char
+pcToChar i = chr $
+  case i of
+    0x80 -> 0xc7
+    0x81 -> 0xfc
+    0x82 -> 0xe9
+    0x83 -> 0xe2
+    0x84 -> 0xe4
+    0x85 -> 0xe0
+    0x86 -> 0xe5
+    0x87 -> 0xe7
+    0x88 -> 0xea
+    0x89 -> 0xeb
+    0x8a -> 0xe8
+    0x8b -> 0xef
+    0x8c -> 0xee
+    0x8d -> 0xec
+    0x8e -> 0xc4
+    0x8f -> 0xc5
+    0x90 -> 0xc9
+    0x91 -> 0xe6
+    0x92 -> 0xc6
+    0x93 -> 0xf4
+    0x94 -> 0xf6
+    0x95 -> 0xf2
+    0x96 -> 0xfb
+    0x97 -> 0xf9
+    0x98 -> 0xff
+    0x99 -> 0xd6
+    0x9a -> 0xdc
+    0x9b -> 0xa2
+    0x9c -> 0xa3
+    0x9d -> 0xa5
+    0x9e -> 0x20a7
+    0x9f -> 0x0192
+    0xa0 -> 0xe1
+    0xa1 -> 0xed
+    0xa2 -> 0xf3
+    0xa3 -> 0xfa
+    0xa4 -> 0xf1
+    0xa5 -> 0xd1
+    0xa6 -> 0xaa
+    0xa7 -> 0xba
+    0xa8 -> 0xbf
+    0xa9 -> 0x2310
+    0xaa -> 0xac
+    0xab -> 0xbd
+    0xac -> 0xbc
+    0xad -> 0xa1
+    0xae -> 0xab
+    0xaf -> 0xbb
+    0xb0 -> 0x2591
+    0xb1 -> 0x2592
+    0xb2 -> 0x2593
+    0xb3 -> 0x2502
+    0xb4 -> 0x2524
+    0xb5 -> 0x2561
+    0xb6 -> 0x2562
+    0xb7 -> 0x2556
+    0xb8 -> 0x2555
+    0xb9 -> 0x2563
+    0xba -> 0x2551
+    0xbb -> 0x2557
+    0xbc -> 0x255d
+    0xbd -> 0x255c
+    0xbe -> 0x255b
+    0xbf -> 0x2510
+    0xc0 -> 0x2514
+    0xc1 -> 0x2534
+    0xc2 -> 0x252c
+    0xc3 -> 0x251c
+    0xc4 -> 0x2500
+    0xc5 -> 0x253c
+    0xc6 -> 0x255e
+    0xc7 -> 0x255f
+    0xc8 -> 0x255a
+    0xc9 -> 0x2554
+    0xca -> 0x2569
+    0xcb -> 0x2566
+    0xcc -> 0x2560
+    0xcd -> 0x2550
+    0xce -> 0x256c
+    0xcf -> 0x2567
+    0xd0 -> 0x2568
+    0xd1 -> 0x2564
+    0xd2 -> 0x2565
+    0xd3 -> 0x2559
+    0xd4 -> 0x2558
+    0xd5 -> 0x2552
+    0xd6 -> 0x2553
+    0xd7 -> 0x256b
+    0xd8 -> 0x256a
+    0xd9 -> 0x2518
+    0xda -> 0x250c
+    0xdb -> 0x2588
+    0xdc -> 0x2584
+    0xdd -> 0x258c
+    0xde -> 0x2590
+    0xdf -> 0x2580
+    0xe0 -> 0x03b1
+    0xe1 -> 0xdf
+    0xe2 -> 0x0393
+    0xe3 -> 0x03c0
+    0xe4 -> 0x03a3
+    0xe5 -> 0x03c3
+    0xe6 -> 0xb5
+    0xe7 -> 0x03c4
+    0xe8 -> 0x03a6
+    0xe9 -> 0x0398
+    0xea -> 0x03a9
+    0xeb -> 0x03b4
+    0xec -> 0x221e
+    0xed -> 0x03c6
+    0xee -> 0x03b5
+    0xef -> 0x2229
+    0xf0 -> 0x2261
+    0xf1 -> 0xb1
+    0xf2 -> 0x2265
+    0xf3 -> 0x2264
+    0xf4 -> 0x2320
+    0xf5 -> 0x2321
+    0xf6 -> 0xf7
+    0xf7 -> 0x2248
+    0xf8 -> 0xb0
+    0xf9 -> 0x2219
+    0xfa -> 0xb7
+    0xfb -> 0x221a
+    0xfc -> 0x207f
+    0xfd -> 0xb2
+    0xfe -> 0x25a0
+    0xff -> 0xa0
+    _    -> fromIntegral i
+
+pcaToChar :: Word8 -> Char
+pcaToChar i = chr $
+  case i of
+    0x80 -> 0x00c7
+    0x81 -> 0x00fc
+    0x82 -> 0x00e9
+    0x83 -> 0x00e2
+    0x84 -> 0x00e4
+    0x85 -> 0x00e0
+    0x86 -> 0x00e5
+    0x87 -> 0x00e7
+    0x88 -> 0x00ea
+    0x89 -> 0x00eb
+    0x8a -> 0x00e8
+    0x8b -> 0x00ef
+    0x8c -> 0x00ee
+    0x8d -> 0x00ec
+    0x8e -> 0x00c4
+    0x8f -> 0x00c5
+    0x90 -> 0x00c9
+    0x91 -> 0x00e6
+    0x92 -> 0x00c6
+    0x93 -> 0x00f4
+    0x94 -> 0x00f6
+    0x95 -> 0x00f2
+    0x96 -> 0x00fb
+    0x97 -> 0x00f9
+    0x98 -> 0x00ff
+    0x99 -> 0x00d6
+    0x9a -> 0x00dc
+    0x9b -> 0x00f8
+    0x9c -> 0x00a3
+    0x9d -> 0x00d8
+    0x9e -> 0x00d7
+    0x9f -> 0x0192
+    0xa0 -> 0x00e1
+    0xa1 -> 0x00ed
+    0xa2 -> 0x00f3
+    0xa3 -> 0x00fa
+    0xa4 -> 0x00f1
+    0xa5 -> 0x00d1
+    0xa6 -> 0x00aa
+    0xa7 -> 0x00ba
+    0xa8 -> 0x00bf
+    0xa9 -> 0x00ae
+    0xaa -> 0x00ac
+    0xab -> 0x00bd
+    0xac -> 0x00bc
+    0xad -> 0x00a1
+    0xae -> 0x00ab
+    0xaf -> 0x00bb
+    0xb0 -> 0x2591
+    0xb1 -> 0x2592
+    0xb2 -> 0x2593
+    0xb3 -> 0x2502
+    0xb4 -> 0x2524
+    0xb5 -> 0x00c1
+    0xb6 -> 0x00c2
+    0xb7 -> 0x00c0
+    0xb8 -> 0x00a9
+    0xb9 -> 0x2563
+    0xba -> 0x2551
+    0xbb -> 0x2557
+    0xbc -> 0x255d
+    0xbd -> 0x00a2
+    0xbe -> 0x00a5
+    0xbf -> 0x2510
+    0xc0 -> 0x2514
+    0xc1 -> 0x2534
+    0xc2 -> 0x252c
+    0xc3 -> 0x251c
+    0xc4 -> 0x2500
+    0xc5 -> 0x253c
+    0xc6 -> 0x00e3
+    0xc7 -> 0x00c3
+    0xc8 -> 0x255a
+    0xc9 -> 0x2554
+    0xca -> 0x2569
+    0xcb -> 0x2566
+    0xcc -> 0x2560
+    0xcd -> 0x2550
+    0xce -> 0x256c
+    0xcf -> 0x00a4
+    0xd0 -> 0x00f0
+    0xd1 -> 0x00d0
+    0xd2 -> 0x00ca
+    0xd3 -> 0x00cb
+    0xd4 -> 0x00c8
+    0xd5 -> 0x0131
+    0xd6 -> 0x00cd
+    0xd7 -> 0x00ce
+    0xd8 -> 0x00cf
+    0xd9 -> 0x2518
+    0xda -> 0x250c
+    0xdb -> 0x2588
+    0xdc -> 0x2584
+    0xdd -> 0x00a6
+    0xde -> 0x00cc
+    0xdf -> 0x2580
+    0xe0 -> 0x00d3
+    0xe1 -> 0x00df
+    0xe2 -> 0x00d4
+    0xe3 -> 0x00d2
+    0xe4 -> 0x00f5
+    0xe5 -> 0x00d5
+    0xe6 -> 0x00b5
+    0xe7 -> 0x00fe
+    0xe8 -> 0x00de
+    0xe9 -> 0x00da
+    0xea -> 0x00db
+    0xeb -> 0x00d9
+    0xec -> 0x00fd
+    0xed -> 0x00dd
+    0xee -> 0x00af
+    0xef -> 0x00b4
+    0xf0 -> 0x00ad
+    0xf1 -> 0x00b1
+    0xf2 -> 0x2017
+    0xf3 -> 0x00be
+    0xf4 -> 0x00b6
+    0xf5 -> 0x00a7
+    0xf6 -> 0x00f7
+    0xf7 -> 0x00b8
+    0xf8 -> 0x00b0
+    0xf9 -> 0x00a8
+    0xfa -> 0x00b7
+    0xfb -> 0x00b9
+    0xfc -> 0x00b3
+    0xfd -> 0x00b2
+    0xfe -> 0x25a0
+    0xff -> 0x00a0
+    _    -> fromIntegral i
diff --git a/src/Text/Pandoc/Readers/Roff.hs b/src/Text/Pandoc/Readers/Roff.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Readers/Roff.hs
@@ -0,0 +1,565 @@
+{-# LANGUAGE FlexibleContexts #-}
+{-# LANGUAGE GeneralizedNewtypeDeriving #-}
+{-# LANGUAGE OverloadedStrings #-}
+{-# LANGUAGE ViewPatterns #-}
+{-# LANGUAGE TypeFamilies #-}
+{- |
+   Module      : Text.Pandoc.Readers.Roff
+   Copyright   : Copyright (C) 2018-2020 Yan Pashkovsky and John MacFarlane
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : Yan Pashkovsky <yanp.bugz@gmail.com>
+   Stability   : WIP
+   Portability : portable
+
+Tokenizer for roff formats (man, ms).
+-}
+module Text.Pandoc.Readers.Roff
+  ( FontSpec(..)
+  , defaultFontSpec
+  , LinePart(..)
+  , Arg
+  , TableOption
+  , CellFormat(..)
+  , TableRow
+  , RoffToken(..)
+  , RoffTokens(..)
+  , linePartsToText
+  , lexRoff
+  )
+where
+
+import Safe (lastDef)
+import Control.Monad (void, guard)
+import Control.Monad.Except (throwError)
+import Text.Pandoc.Class.PandocMonad
+       (getResourcePath, readFileFromDirs, PandocMonad(..), report)
+import Data.Char (isLower, toLower, toUpper, isAlphaNum)
+import Data.Default (Default)
+import qualified Data.Map as M
+import Data.List (intercalate)
+import qualified Data.Text as T
+import Text.Pandoc.Logging (LogMessage(..))
+import Text.Pandoc.Options
+import Text.Pandoc.Parsing
+import Text.Pandoc.Shared (safeRead)
+import Text.Pandoc.Readers.Roff.Escape
+import qualified Data.Sequence as Seq
+import qualified Data.Foldable as Foldable
+
+-- import Debug.Trace (traceShowId)
+
+--
+-- Data Types
+--
+data FontSpec = FontSpec{ fontBold      :: Bool
+                        , fontItalic    :: Bool
+                        , fontMonospace :: Bool
+                        } deriving (Show, Eq, Ord)
+
+defaultFontSpec :: FontSpec
+defaultFontSpec = FontSpec False False False
+
+data LinePart = RoffStr T.Text
+              | Font FontSpec
+              | MacroArg Int
+              deriving Show
+
+instance RoffLikeLexer RoffTokens where
+  -- The token stream is a list of 'LinePart's
+  type Token RoffTokens = [LinePart]
+  type State RoffTokens = RoffState
+  emit t = [RoffStr t]
+  expandString = try $ do
+    pos <- getPosition
+    char '\\'
+    char '*'
+    cs <- escapeArg <|> countChar 1 anyChar
+    s <- linePartsToText <$> resolveText cs pos
+    addToInput s
+  escString = try $ do
+    pos <- getPosition
+    (do cs <- escapeArg <|> countChar 1 anyChar
+        resolveText cs pos)
+      <|> mempty <$ char 'S'
+  backslash = do
+    char '\\'
+    mode <- roffMode <$> getState
+    case mode of
+      -- experimentally, it seems you don't always need to double
+      -- the backslash in macro defs.  It's essential with \\$1,
+      -- but not with \\f[I].  So we make the second one optional.
+      CopyMode   -> optional $ char '\\'
+      NormalMode -> return ()
+  checkDefined name = do
+    macros <- customMacros <$> getState
+    case M.lookup name macros of
+      Just _  -> return [RoffStr "1"]
+      Nothing -> return [RoffStr "0"]
+  -- \E is ignored in copy mode
+  escE = do
+      mode <- roffMode <$> getState
+      case mode of
+        CopyMode   -> return mempty
+        NormalMode -> return [RoffStr "\\"]
+  escFont = do
+    font <- escapeArg <|> countChar 1 alphaNum
+    font' <- if T.null font || font == "P"
+                then prevFont <$> getState
+                else return $ foldr processFontLetter defaultFontSpec $ T.unpack font
+    updateState $ \st -> st{ prevFont = currentFont st
+                           , currentFont = font' }
+    return [Font font']
+    where
+      processFontLetter c fs
+                | isLower c    = processFontLetter (toUpper c) fs
+      processFontLetter 'B' fs = fs{ fontBold = True }
+      processFontLetter 'I' fs = fs{ fontItalic = True }
+      processFontLetter 'C' fs = fs{ fontMonospace = True }
+      processFontLetter _   fs = fs -- do nothing
+
+type Arg = [LinePart]
+
+type TableOption = (T.Text, T.Text)
+
+data CellFormat =
+  CellFormat
+  { columnType     :: Char
+  , pipePrefix     :: Bool
+  , pipeSuffix     :: Bool
+  , columnSuffixes :: [T.Text]
+  } deriving (Show, Eq, Ord)
+
+type TableRow = ([CellFormat], [RoffTokens])
+
+data RoffToken = TextLine [LinePart]
+               | EmptyLine
+               | ControlLine T.Text [Arg] SourcePos
+               | Tbl [TableOption] [TableRow] SourcePos
+               deriving Show
+
+newtype RoffTokens = RoffTokens { unRoffTokens :: Seq.Seq RoffToken }
+        deriving (Show, Semigroup, Monoid)
+
+singleTok :: RoffToken -> RoffTokens
+singleTok t = RoffTokens (Seq.singleton t)
+
+data RoffMode = NormalMode
+              | CopyMode
+              deriving Show
+
+data RoffState = RoffState { customMacros     :: M.Map T.Text RoffTokens
+                           , prevFont         :: FontSpec
+                           , currentFont      :: FontSpec
+                           , tableTabChar     :: Char
+                           , roffMode         :: RoffMode
+                           , lastExpression   :: Maybe Bool
+                           , afterConditional :: Bool
+                           } deriving Show
+
+instance Default RoffState where
+  def = RoffState { customMacros = M.fromList
+                       $ map (\(n, s) ->
+                                (n, singleTok
+                                  (TextLine [RoffStr s])))
+                       [ ("Tm", "\x2122")
+                       , ("lq", "\x201C")
+                       , ("rq", "\x201D")
+                       , ("R",  "\x00AE") ]
+                  , prevFont = defaultFontSpec
+                  , currentFont = defaultFontSpec
+                  , tableTabChar = '\t'
+                  , roffMode = NormalMode
+                  , lastExpression = Nothing
+                  , afterConditional = False
+                  }
+
+type RoffLexer m = ParsecT Sources RoffState m
+
+--
+-- Lexer: T.Text -> RoffToken
+--
+
+eofline :: (Stream s m Char, UpdateSourcePos s Char) => ParsecT s u m ()
+eofline = void newline <|> eof <|> () <$ lookAhead (string "\\}")
+
+spacetab :: (Stream s m Char, UpdateSourcePos s Char) => ParsecT s u m Char
+spacetab = char ' ' <|> char '\t'
+
+-- separate function from lexMacro since real man files sometimes do not
+-- follow the rules
+lexComment :: PandocMonad m => RoffLexer m RoffTokens
+lexComment = do
+  try $ string ".\\\""
+  skipMany $ noneOf "\n"
+  eofline
+  return mempty
+
+lexMacro :: PandocMonad m => RoffLexer m RoffTokens
+lexMacro = do
+  pos <- getPosition
+  st <- getState
+  guard $ sourceColumn pos == 1 || afterConditional st
+  char '.' <|> char '\''
+  skipMany spacetab
+  macroName <- manyChar (satisfy isAlphaNum)
+  case macroName of
+    "nop" -> return mempty
+    "ie"  -> lexConditional "ie"
+    "if"  -> lexConditional "if"
+    "el"  -> lexConditional "el"
+    "while" -> lexConditional "while"
+               -- this doesn't get the semantics right but
+               -- avoids parse errors
+
+    _ -> do
+       args <- lexArgs
+       case macroName of
+         ""     -> return mempty
+         "TS"   -> lexTable pos
+         "de"   -> lexMacroDef args
+         "de1"  -> lexMacroDef args
+         "ds"   -> lexStringDef args
+         "ds1"  -> lexStringDef args
+         "sp"   -> return $ singleTok EmptyLine
+         "so"   -> lexIncludeFile args
+         _      -> resolveMacro macroName args pos
+
+lexTable :: PandocMonad m => SourcePos -> RoffLexer m RoffTokens
+lexTable pos = do
+  skipMany lexComment
+  spaces
+  opts <- try tableOptions <|> [] <$ optional (char ';')
+  case lookup "tab" opts of
+    Just (T.uncons -> Just (c, _)) -> updateState $ \st -> st{ tableTabChar = c }
+    _                              -> updateState $ \st -> st{ tableTabChar = '\t' }
+  spaces
+  skipMany lexComment
+  spaces
+  rows <- lexTableRows
+  morerows <- many $ try $ do
+    string ".T&"
+    skipMany spacetab
+    newline
+    lexTableRows
+  string ".TE"
+  skipMany spacetab
+  eofline
+  return $ singleTok $ Tbl opts (rows <> concat morerows) pos
+
+lexTableRows :: PandocMonad m => RoffLexer m [TableRow]
+lexTableRows = do
+  aligns <- tableFormatSpec
+  spaces
+  skipMany $ lexComment
+          <|> try (mempty <$ (string ".sp" >> skipMany spaceChar >> newline))
+  spaces
+  rows <- many (notFollowedBy (try (string ".TE") <|> try (string ".T&")) >>
+                  tableRow)
+  return $ zip aligns rows
+
+tableCell :: PandocMonad m => RoffLexer m RoffTokens
+tableCell = do
+  pos <- getPosition
+  (enclosedCell <|> simpleCell) >>= lexRoff pos . T.pack
+  where
+  enclosedCell = do
+    try (string "T{")
+    manyTill anyChar (try (string "T}"))
+  simpleCell = do
+    tabChar <- tableTabChar <$> getState
+    many $ (char '\\' >> anyChar)
+       <|> (notFollowedBy (char tabChar <|> newline) >> anyChar)
+
+tableRow :: PandocMonad m => RoffLexer m [RoffTokens]
+tableRow = do
+  tabChar <- tableTabChar <$> getState
+  c <- tableCell
+  cs <- many $ try (char tabChar >> tableCell)
+  skipMany spacetab
+  eofline
+  skipMany lexComment
+  return (c:cs)
+
+tableOptions :: PandocMonad m => RoffLexer m [TableOption]
+tableOptions = many1 tableOption <* spaces <* char ';'
+
+tableOption :: PandocMonad m => RoffLexer m TableOption
+tableOption = do
+  k <- many1Char letter
+  v <- option "" $ try $ do
+         skipMany spacetab
+         char '('
+         manyTillChar anyChar (char ')')
+  skipMany spacetab
+  optional (char ',' >> skipMany spacetab)
+  return (k,v)
+
+tableFormatSpec :: PandocMonad m => RoffLexer m [[CellFormat]]
+tableFormatSpec = do
+  first <- tableFormatSpecLine
+  rest <- many $ try $ (newline <|> char ',') *> tableFormatSpecLine
+  let speclines = first:rest
+  spaces
+  char '.'
+  return $ speclines <> repeat (lastDef [] speclines) -- last line is default
+
+tableFormatSpecLine :: PandocMonad m => RoffLexer m [CellFormat]
+tableFormatSpecLine =
+  many1 $ skipMany spacetab *> tableColFormat <* skipMany spacetab
+
+tableColFormat :: PandocMonad m => RoffLexer m CellFormat
+tableColFormat = do
+    pipePrefix' <- option False
+                   $ True <$ try (string "|" <* notFollowedBy spacetab)
+    c <- oneOf ['a','A','c','C','l','L','n','N','r','R','s','S','^','_','-',
+                '=','|']
+    suffixes <- many $ try (skipMany spacetab *> countChar 1 digit) <|>
+      (do x <- oneOf ['b','B','d','D','e','E','f','F','i','I','m','M',
+                  'p','P','t','T','u','U','v','V','w','W','x','X', 'z','Z']
+          num <- case toLower x of
+                   'w' -> many1 digit <|>
+                           (do char '('
+                               xs <- manyTill anyChar (char ')')
+                               return ("(" <> xs <> ")")) <|>
+                           return ""
+                   'f' -> count 1 alphaNum <* skipMany spacetab
+                   'm' -> count 1 alphaNum <* skipMany spacetab
+                   _   -> return ""
+          return $ T.pack $ x : num)
+    pipeSuffix' <- option False $ True <$ string "|"
+    return $ CellFormat
+             { columnType     = c
+             , pipePrefix     = pipePrefix'
+             , pipeSuffix     = pipeSuffix'
+             , columnSuffixes = suffixes }
+
+-- We don't fully handle the conditional.  But we do
+-- include everything under '.ie n', which occurs commonly
+-- in man pages.
+lexConditional :: PandocMonad m => T.Text -> RoffLexer m RoffTokens
+lexConditional mname = do
+  pos <- getPosition
+  skipMany spacetab
+  mbtest <- if mname == "el"
+               then fmap not . lastExpression <$> getState
+               else expression
+  skipMany spacetab
+  st <- getState -- save state, so we can reset it
+  ifPart <- do
+      optional $ try $ char '\\' >> newline
+      lexGroup
+       <|> do updateState $ \s -> s{ afterConditional = True }
+              t <- manToken
+              updateState $ \s -> s{ afterConditional = False }
+              return t
+  case mbtest of
+    Nothing    -> do
+      setState st  -- reset state, so we don't record macros in skipped section
+      report $ SkippedContent (T.cons '.' mname) pos
+      return mempty
+    Just True  -> return ifPart
+    Just False -> do
+      setState st
+      return mempty
+
+expression :: PandocMonad m => RoffLexer m (Maybe Bool)
+expression = do
+  raw <- charsInBalanced '(' ')' (T.singleton <$> (satisfy (/= '\n')))
+      <|> many1Char nonspaceChar
+  returnValue $
+    case raw of
+      "1"  -> Just True
+      "n"  -> Just True  -- nroff mode
+      "t"  -> Just False -- troff mode
+      _    -> Nothing
+  where
+    returnValue v = do
+      updateState $ \st -> st{ lastExpression = v }
+      return v
+
+lexGroup :: PandocMonad m => RoffLexer m RoffTokens
+lexGroup = do
+  groupstart
+  mconcat <$> manyTill manToken groupend
+  where
+    groupstart = try $ string "\\{" <* optional (try (string "\\\n"))
+    groupend   = try $ string "\\}"
+
+lexIncludeFile :: PandocMonad m => [Arg] -> RoffLexer m RoffTokens
+lexIncludeFile args = do
+  pos <- getPosition
+  case args of
+    (f:_) -> do
+      let fp = linePartsToText f
+      dirs <- getResourcePath
+      result <- readFileFromDirs dirs $ T.unpack fp
+      case result of
+        Nothing  -> report $ CouldNotLoadIncludeFile fp pos
+        Just s   -> addToInput s
+      return mempty
+    []    -> return mempty
+
+resolveMacro :: PandocMonad m
+             => T.Text -> [Arg] -> SourcePos -> RoffLexer m RoffTokens
+resolveMacro macroName args pos = do
+  macros <- customMacros <$> getState
+  case M.lookup macroName macros of
+    Nothing -> return $ singleTok $ ControlLine macroName args pos
+    Just ts -> do
+      let fillLP (MacroArg i)    zs =
+            case drop (i - 1) args of
+              []     -> zs
+              (ys:_) -> ys <> zs
+          fillLP z zs = z : zs
+      let fillMacroArg (TextLine lineparts) =
+            TextLine (foldr fillLP [] lineparts)
+          fillMacroArg x = x
+      return $ RoffTokens . fmap fillMacroArg . unRoffTokens $ ts
+
+lexStringDef :: PandocMonad m => [Arg] -> RoffLexer m RoffTokens
+lexStringDef args = do -- string definition
+   case args of
+     []     -> Prelude.fail "No argument to .ds"
+     (x:ys) -> do
+       let ts = singleTok $ TextLine (intercalate [RoffStr " " ] ys)
+       let stringName = linePartsToText x
+       updateState $ \st ->
+         st{ customMacros = M.insert stringName ts (customMacros st) }
+   return mempty
+
+lexMacroDef :: PandocMonad m => [Arg] -> RoffLexer m RoffTokens
+lexMacroDef args = do -- macro definition
+   updateState $ \st -> st{ roffMode = CopyMode }
+   (macroName, stopMacro) <-
+     case args of
+       (x : y : _) -> return (linePartsToText x, linePartsToText y)
+                      -- optional second arg
+       (x:_)       -> return (linePartsToText x, ".")
+       []          -> Prelude.fail "No argument to .de"
+   let stop = try $ do
+         char '.' <|> char '\''
+         skipMany spacetab
+         textStr stopMacro
+         _ <- lexArgs
+         return ()
+   ts <- mconcat <$> manyTill manToken stop
+   updateState $ \st ->
+     st{ customMacros = M.insert macroName ts (customMacros st)
+       , roffMode = NormalMode }
+   return mempty
+
+lexArgs :: PandocMonad m => RoffLexer m [Arg]
+lexArgs = do
+  args <- many $ try oneArg
+  skipMany spacetab
+  eofline
+  return args
+
+  where
+
+  oneArg :: PandocMonad m => RoffLexer m [LinePart]
+  oneArg = do
+    skipMany $ try $ string "\\\n"  -- continuation line
+    try quotedArg <|> plainArg
+    -- try, because there are some erroneous files, e.g. linux/bpf.2
+
+  plainArg :: PandocMonad m => RoffLexer m [LinePart]
+  plainArg = do
+    skipMany spacetab
+    mconcat <$> many1 (macroArg <|> escape <|> regularText <|> unescapedQuote)
+    where
+      unescapedQuote = char '"' >> return [RoffStr "\""]
+
+  quotedArg :: PandocMonad m => RoffLexer m [LinePart]
+  quotedArg = do
+    skipMany spacetab
+    char '"'
+    xs <- mconcat <$>
+           many (macroArg <|> escape <|> regularText
+                 <|> spaceTabChar <|> escapedQuote)
+    char '"'
+    return xs
+    where
+      escapedQuote = try $ do
+        char '"'
+        char '"'
+        return [RoffStr "\""]
+
+-- strings and macros share namespace
+resolveText :: PandocMonad m
+              => T.Text -> SourcePos -> RoffLexer m [LinePart]
+resolveText stringname pos = do
+  RoffTokens ts <- resolveMacro stringname [] pos
+  case Foldable.toList ts of
+    [TextLine xs] -> return xs
+    _          -> do
+      report $ SkippedContent ("unknown string " <> stringname) pos
+      return mempty
+
+lexLine :: PandocMonad m => RoffLexer m RoffTokens
+lexLine = do
+  mode <- roffMode <$> getState
+  case mode of
+    CopyMode   -> optional $ try $ string "\\&"
+    NormalMode -> return ()
+  lnparts <- mconcat <$> many1 linePart
+  eofline
+  go lnparts
+  where  -- return empty line if we only have empty strings;
+         -- this can happen if the line just contains \f[C], for example.
+    go [] = return mempty
+    go (RoffStr "" : xs) = go xs
+    go xs = return $ singleTok $ TextLine xs
+
+linePart :: PandocMonad m => RoffLexer m [LinePart]
+linePart = macroArg <|> escape <|>
+           regularText <|> quoteChar <|> spaceTabChar
+
+macroArg :: PandocMonad m => RoffLexer m [LinePart]
+macroArg = try $ do
+  pos <- getPosition
+  backslash
+  char '$'
+  x <- escapeArg <|> countChar 1 digit
+  case safeRead x of
+    Just i  -> return [MacroArg i]
+    Nothing -> do
+      report $ SkippedContent ("illegal macro argument " <> x) pos
+      return []
+
+regularText :: PandocMonad m => RoffLexer m [LinePart]
+regularText = do
+  s <- many1Char $ noneOf "\n\r\t \\\""
+  return [RoffStr s]
+
+quoteChar :: PandocMonad m => RoffLexer m [LinePart]
+quoteChar = do
+  char '"'
+  return [RoffStr "\""]
+
+spaceTabChar :: PandocMonad m => RoffLexer m [LinePart]
+spaceTabChar = do
+  c <- spacetab
+  return [RoffStr $ T.singleton c]
+
+lexEmptyLine :: PandocMonad m => RoffLexer m RoffTokens
+lexEmptyLine = newline >> return (singleTok EmptyLine)
+
+manToken :: PandocMonad m => RoffLexer m RoffTokens
+manToken = lexComment <|> lexMacro <|> lexLine <|> lexEmptyLine
+
+linePartsToText :: [LinePart] -> T.Text
+linePartsToText = mconcat . map go
+  where
+  go (RoffStr s) = s
+  go _ = mempty
+
+-- | Tokenize a string as a sequence of roff tokens.
+lexRoff :: PandocMonad m => SourcePos -> T.Text -> m RoffTokens
+lexRoff pos txt = do
+  eithertokens <- readWithM (do setPosition pos
+                                mconcat <$> many manToken) def txt
+  case eithertokens of
+    Left e       -> throwError e
+    Right tokenz -> return tokenz
diff --git a/src/Text/Pandoc/Readers/Roff/Escape.hs b/src/Text/Pandoc/Readers/Roff/Escape.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Readers/Roff/Escape.hs
@@ -0,0 +1,222 @@
+{-# LANGUAGE FlexibleContexts #-}
+{-# LANGUAGE OverloadedStrings #-}
+{-# LANGUAGE MultiParamTypeClasses #-}
+{-# LANGUAGE TypeFamilyDependencies #-}
+module Text.Pandoc.Readers.Roff.Escape
+  ( escape,
+    escapeArg,
+    escIgnore,
+    RoffLikeLexer(..),
+  )
+where
+import Text.Pandoc.Class.PandocMonad
+    ( PandocMonad(..), report, PandocMonad(..), report )
+import Control.Monad
+    ( mzero, mplus, mzero, mplus )
+import Data.Char (chr, isAscii, isAlphaNum)
+import qualified Data.Map as M
+import qualified Data.Text as T
+import Text.Pandoc.Logging (LogMessage(..))
+import Text.Pandoc.Parsing
+import Text.Pandoc.Shared (safeRead)
+import qualified Data.Text.Normalize as Normalize
+import Text.Pandoc.RoffChar (characterCodes, combiningAccents)
+
+-- | Functions and typeclass for escaping special characters in languages
+-- that inherit the Roff syntax.
+--
+-- For various reasons, the mdoc reader doesn't directly reuse the previously
+-- existing roff lexer. The main one is to make it possible to simultaneously
+-- process roff escapes and to tokenize mdoc macros correctly based on the
+-- control line contents. The extracted interface here allows the same `escape`
+-- function to work with lexers that target different token types and support
+-- different subsets of the original roff language.
+
+type Lexer m x = ParsecT Sources (State x) m
+
+-- | Lexers for Roff macro
+class (Monoid (Token x)) => RoffLikeLexer x where
+  -- | Type family for the lexer state
+  type State x = a | a -> x
+  -- | Type family for the token type being lexed
+  type Token x = a | a -> x
+  -- | Turn a `T.Text` into a token of the output
+  emit :: T.Text -> Token x
+  -- | Attempt to parse a roff predefined string sequence and push its expansion
+  -- onto the input stream.
+  expandString :: PandocMonad m => Lexer m x ()
+  -- | Parse the name of a defined string and return its expansion as a `Token`
+  escString :: PandocMonad m => Lexer m x (Token x)
+  -- | Parse the escape character
+  backslash :: PandocMonad m => Lexer m x ()
+  -- | If the given custom macro is defined in this document, emit a
+  -- tokenized "1", otherwise emit a tokenized "0", implementing the roff
+  -- escape @\A@.
+  checkDefined :: PandocMonad m => T.Text -> Lexer m x (Token x)
+  -- | Output an appropriate token for the @\E@ escape sequence. In roff, @\E@
+  -- is an "escape character intended to not be interpreted in copy mode".
+  -- If the lexer being defined doesn't implement copy mode, @\E@ can just be
+  -- lexed by 'backslash'
+  escE :: PandocMonad m => Lexer m x (Token x)
+  -- | Lex the low-level roff font selection escape @\f@.
+  escFont :: PandocMonad m => Lexer m x (Token x)
+
+
+characterCodeMap :: M.Map T.Text Char
+characterCodeMap =
+  M.fromList $ map (\(x,y) -> (y,x)) characterCodes
+
+combiningAccentsMap :: M.Map T.Text Char
+combiningAccentsMap =
+  M.fromList $ map (\(x,y) -> (y,x)) combiningAccents
+
+escape ::  (PandocMonad m, RoffLikeLexer x) => Lexer m x (Token x)
+escape = try $ do
+  backslash
+  escapeGlyph <|> escapeNormal
+
+escapeGlyph :: (PandocMonad m, RoffLikeLexer x) => Lexer m x (Token x)
+escapeGlyph = do
+  c <- lookAhead (oneOf ['[','('])
+  escapeArg >>= resolveGlyph c
+
+resolveGlyph :: (PandocMonad m, RoffLikeLexer x) => Char -> T.Text -> Lexer m x (Token x)
+resolveGlyph delimChar glyph = do
+  let cs = T.replace "_u" " u" glyph -- unicode glyphs separated by _
+  (case T.words cs of
+      []  -> mzero
+      [s] -> case M.lookup s characterCodeMap `mplus` readUnicodeChar s of
+               Nothing -> mzero
+               Just c  -> return $ emit $ T.singleton c
+      (s:ss) -> do
+        basechar <- case M.lookup s characterCodeMap `mplus`
+                         readUnicodeChar s of
+                      Nothing ->
+                        case T.unpack s of
+                          [ch] | isAscii ch && isAlphaNum ch ->
+                                 return ch
+                          _ -> mzero
+                      Just c  -> return c
+        let addAccents [] xs = return $ Normalize.normalize Normalize.NFC $
+                                        T.reverse xs
+            addAccents (a:as) xs =
+              case M.lookup a combiningAccentsMap `mplus` readUnicodeChar a of
+                Just x  -> addAccents as $ T.cons x xs
+                Nothing -> mzero
+        addAccents ss (T.singleton basechar) >>= \xs -> return $ emit xs)
+      <|> case delimChar of
+            '['  -> escUnknown ("\\[" <> glyph <> "]")
+            '('  -> escUnknown ("\\(" <> glyph)
+            '\'' -> escUnknown ("\\C'" <> glyph <> "'")
+            _    -> Prelude.fail "resolveGlyph: unknown glyph delimiter"
+
+readUnicodeChar :: T.Text -> Maybe Char
+readUnicodeChar t = case T.uncons t of
+  Just ('u', cs) | T.length cs > 3 -> chr <$> safeRead ("0x" <> cs)
+  _ -> Nothing
+
+escapeNormal :: (PandocMonad m, RoffLikeLexer x) => Lexer m x (Token x)
+escapeNormal = do
+  c <- noneOf "{}"
+  optional expandString
+  let groffSkip = [escapeArg, countChar 1 (satisfy (/='\n'))]
+  case c of
+    ' ' -> return $ emit " " -- mandoc_char(7) says this should be a nonbreaking space
+    '"' -> mempty <$ skipMany (satisfy (/='\n')) -- line comment
+    '#' -> mempty <$ manyTill anyChar newline
+    '%' -> return mempty  -- optional hyphenation
+    '&' -> return mempty  -- nonprintable zero-width
+    ')' -> return mempty  -- nonprintable zero-width
+    '*' -> escString
+    ',' -> return mempty  -- to fix spacing after roman
+    '-' -> return $ emit "-"
+    '.' -> return $ emit "."
+    '/' -> return mempty  -- to fix spacing before roman
+    '0' -> return $ emit "\x2007" -- digit-width space
+    ':' -> return mempty  -- zero-width break
+    'A' -> quoteArg >>= checkDefined
+    'B' -> escIgnore 'B' [quoteArg]
+    'C' -> quoteArg >>= resolveGlyph '\''
+    'D' -> escIgnore 'D' [quoteArg]
+    'E' -> escE
+    'F' -> escIgnore 'F' groffSkip
+    'H' -> escIgnore 'H' [quoteArg]
+    'L' -> escIgnore 'L' [quoteArg]
+    'M' -> escIgnore 'M' groffSkip
+    'N' -> escIgnore 'N' [quoteArg]
+    'O' -> escIgnore 'O' [countChar 1 (oneOf ['0','1'])]
+    'R' -> escIgnore 'R' [quoteArg]
+    'S' -> escIgnore 'S' [quoteArg]
+    'V' -> escIgnore 'V' groffSkip
+    'X' -> escIgnore 'X' [quoteArg]
+    'Y' -> escIgnore 'Y' groffSkip
+    'Z' -> escIgnore 'Z' [quoteArg]
+    '\'' -> return $ emit "'"
+    '\n' -> return mempty  -- line continuation
+    '^' -> return $ emit "\x200A" -- 1/12 em space
+    '_' -> return $ emit "_"
+    '`' -> return $ emit "`"
+    'a' -> return mempty  -- "non-interpreted leader character"
+    'b' -> escIgnore 'b' [quoteArg]
+    'c' -> return mempty  -- interrupt text processing
+    'd' -> escIgnore 'd' [] -- forward down 1/2em
+    'e' -> return $ emit "\\"
+    'f' -> escFont
+    'g' -> escIgnore 'g' groffSkip
+    'h' -> escIgnore 'h' [quoteArg]
+    'k' -> escIgnore 'k' groffSkip
+    'l' -> escIgnore 'l' [quoteArg]
+    'm' -> escIgnore 'm' groffSkip
+    'n' -> escIgnore 'm' groffSkip
+    'o' -> escIgnore 'o' [quoteArg]
+    'p' -> escIgnore 'p' []
+    'r' -> escIgnore 'r' []
+    's' -> escIgnore 's' [escapeArg, signedNumber]
+    't' -> return $ emit "\t"
+    'u' -> escIgnore 'u' []
+    'v' -> escIgnore 'v' [quoteArg]
+    'w' -> escIgnore 'w' [quoteArg]
+    'x' -> escIgnore 'x' [quoteArg]
+    'z' -> escIgnore 'z' [countChar 1 anyChar]
+    '|' -> return $ emit "\x2006" --1/6 em space
+    '~' -> return $ emit "\160" -- nonbreaking space
+    '\\' -> return $ emit "\\"
+    _   -> return $ emit $ T.singleton c
+    -- man 7 groff: "If  a  backslash  is followed by a character that
+    -- does not constitute a defined escape sequence, the backslash
+    -- is  silently  ignored  and  the character maps to itself."
+
+escIgnore :: (PandocMonad m, RoffLikeLexer x)
+          => Char
+          -> [Lexer m x T.Text]
+          -> Lexer m x (Token x)
+escIgnore c argparsers = do
+  pos <- getPosition
+  arg <- snd <$> withRaw (choice argparsers) <|> return ""
+  report $ SkippedContent ("\\" <> T.cons c arg) pos
+  return mempty
+
+escUnknown :: (PandocMonad m, RoffLikeLexer x) => T.Text -> Lexer m x (Token x)
+escUnknown s = do
+  pos <- getPosition
+  report $ SkippedContent s pos
+  return $ emit "\xFFFD"
+
+signedNumber :: (PandocMonad m, RoffLikeLexer x) => Lexer m x T.Text
+signedNumber = try $ do
+  sign <- option "" ("-" <$ char '-' <|> "" <$ char '+')
+  ds <- many1Char digit
+  return (sign <> ds)
+
+-- Parses: [..] or (..
+escapeArg :: (PandocMonad m, RoffLikeLexer x) => Lexer m x T.Text
+escapeArg = choice
+    [ char '[' *> optional expandString *>
+                  manyTillChar (noneOf ['\n',']']) (char ']')
+    , char '(' *> optional expandString *>
+                  countChar 2 (satisfy (/='\n'))
+    ]
+
+-- Parses: '..'
+quoteArg :: (PandocMonad m, RoffLikeLexer x) => Lexer m x T.Text
+quoteArg = char '\'' *> manyTillChar (noneOf ['\n','\'']) (char '\'')
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,5 @@
-{-# LANGUAGE FlexibleContexts     #-}
-{-# LANGUAGE FlexibleInstances    #-}
-{-# LANGUAGE RelaxedPolyRec       #-}
-{-# LANGUAGE TypeSynonymInstances #-}
--- 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
--}
-
+{-# LANGUAGE FlexibleContexts  #-}
+{-# LANGUAGE OverloadedStrings #-}
 {- |
    Module      : Text.Pandoc.Readers.TWiki
    Copyright   : Copyright (C) 2014 Alexander Sulfrian
@@ -37,94 +16,85 @@
 
 import Control.Monad
 import Control.Monad.Except (throwError)
-import Data.Char (isAlphaNum)
+import Data.Char (isAlphaNum, isDigit, isUpper, isLower, isLetter)
 import qualified Data.Foldable as F
 import Data.Maybe (fromMaybe)
 import Data.Text (Text)
 import qualified Data.Text as T
 import Text.HTML.TagSoup
 import qualified Text.Pandoc.Builder as B
-import Text.Pandoc.Class (PandocMonad (..))
+import Text.Pandoc.Class.PandocMonad (PandocMonad (..))
 import Text.Pandoc.Definition
 import Text.Pandoc.Options
-import Text.Pandoc.Parsing hiding (enclosed, nested)
+import Text.Pandoc.Parsing hiding (enclosed)
 import Text.Pandoc.Readers.HTML (htmlTag, isCommentTag)
-import Text.Pandoc.Shared (crFilter)
+import Text.Pandoc.Shared (tshow)
 import Text.Pandoc.XML (fromEntities)
 
 -- | Read twiki from an input string and return a Pandoc document.
-readTWiki :: PandocMonad m
+readTWiki :: (PandocMonad m, ToSources a)
           => ReaderOptions
-          -> Text
+          -> a
           -> m Pandoc
 readTWiki opts s = do
-  res <- readWithM parseTWiki def{ stateOptions = opts }
-             (T.unpack (crFilter s) ++ "\n\n")
+  let sources = ensureFinalNewlines 2 (toSources s)
+  res <- readWithM parseTWiki def{ stateOptions = opts } sources
   case res of
        Left e  -> throwError e
        Right d -> return d
 
-type TWParser = ParserT [Char] ParserState
+type TWParser = ParsecT Sources ParserState
 
 --
 -- utility functions
 --
 
-tryMsg :: String -> TWParser m a -> TWParser m a
-tryMsg msg p = try p <?> msg
-
-skip :: TWParser m a -> TWParser m ()
-skip parser = parser >> return ()
-
-nested :: PandocMonad m => TWParser m a -> TWParser m a
-nested p = do
-  nestlevel <- stateMaxNestingLevel <$>  getState
-  guard $ nestlevel > 0
-  updateState $ \st -> st{ stateMaxNestingLevel = stateMaxNestingLevel st - 1 }
-  res <- p
-  updateState $ \st -> st{ stateMaxNestingLevel = nestlevel }
-  return res
+tryMsg :: Text -> TWParser m a -> TWParser m a
+tryMsg msg p = try p <?> T.unpack msg
 
-htmlElement :: PandocMonad m => String -> TWParser m (Attr, String)
+htmlElement :: PandocMonad m => Text -> TWParser m (Attr, Text)
 htmlElement tag = tryMsg tag $ do
   (TagOpen _ attr, _) <- htmlTag (~== TagOpen tag [])
-  content <- manyTill anyChar (endtag <|> endofinput)
+  content <- T.pack <$> manyTill anyChar (endtag <|> endofinput)
   return (htmlAttrToPandoc attr, trim content)
   where
-    endtag     = skip $ htmlTag (~== TagClose tag)
+    endtag     = void $ htmlTag (~== TagClose tag)
     endofinput = lookAhead $ try $ skipMany blankline >> skipSpaces >> eof
-    trim       = dropWhile (=='\n') . reverse . dropWhile (=='\n') . reverse
+    trim       = T.dropAround (=='\n')
 
-htmlAttrToPandoc :: [Attribute String] -> Attr
+htmlAttrToPandoc :: [Attribute Text] -> Attr
 htmlAttrToPandoc attrs = (ident, classes, keyvals)
   where
     ident   = fromMaybe "" $ lookup "id" attrs
-    classes = maybe [] words $ lookup "class" attrs
+    classes = maybe [] T.words $ lookup "class" attrs
     keyvals = [(k,v) | (k,v) <- attrs, k /= "id" && k /= "class"]
 
 parseHtmlContentWithAttrs :: PandocMonad m
-                          => String -> TWParser m a -> TWParser m (Attr, [a])
+                          => Text -> TWParser m a -> TWParser m (Attr, [a])
 parseHtmlContentWithAttrs tag parser = do
   (attr, content) <- htmlElement tag
   parsedContent <- try $ parseContent content
   return (attr, parsedContent)
   where
-    parseContent = parseFromString' $ nested $ manyTill parser endOfContent
+    parseContent = parseFromString' $ manyTill parser endOfContent
     endOfContent = try $ skipMany blankline >> skipSpaces >> eof
 
-parseHtmlContent :: PandocMonad m => String -> TWParser m a -> TWParser m [a]
-parseHtmlContent tag p = parseHtmlContentWithAttrs tag p >>= return . snd
+parseCharHtmlContentWithAttrs :: PandocMonad m
+                          => Text -> TWParser m Char -> TWParser m (Attr, Text)
+parseCharHtmlContentWithAttrs tag = fmap go . parseHtmlContentWithAttrs tag
+  where
+    go (x, y) = (x, T.pack y)
 
+parseHtmlContent :: PandocMonad m => Text -> TWParser m a -> TWParser m [a]
+parseHtmlContent tag p = snd <$> parseHtmlContentWithAttrs tag p
+
 --
 -- main parser
 --
 
 parseTWiki :: PandocMonad m => TWParser m Pandoc
-parseTWiki = do
-  bs <- mconcat <$> many block
-  spaces
-  eof
-  return $ B.doc bs
+parseTWiki =
+  B.doc . mconcat <$> many block <* spaces <* eof
 
 
 --
@@ -137,7 +107,7 @@
          <|> blockElements
          <|> para
   skipMany blankline
-  trace (take 60 $ show $ B.toList res)
+  trace (T.take 60 $ tshow $ B.toList res)
   return res
 
 blockElements :: PandocMonad m => TWParser m B.Blocks
@@ -157,7 +127,7 @@
 header :: PandocMonad m => TWParser m B.Blocks
 header = tryMsg "header" $ do
   string "---"
-  level <- many1 (char '+') >>= return . length
+  level <- length <$> many1 (char '+')
   guard $ level <= 6
   classes <- option [] $ string "!!" >> return ["unnumbered"]
   skipSpaces
@@ -166,47 +136,46 @@
   return $ B.headerWith attr level content
 
 verbatim :: PandocMonad m => TWParser m B.Blocks
-verbatim = (htmlElement "verbatim" <|> htmlElement "pre")
-           >>= return . (uncurry B.codeBlockWith)
+verbatim = uncurry B.codeBlockWith <$> (htmlElement "verbatim" <|> htmlElement "pre")
 
 literal :: PandocMonad m => TWParser m B.Blocks
-literal = htmlElement "literal" >>= return . rawBlock
+literal = rawBlock <$> htmlElement "literal"
   where
     format (_, _, kvs)        = fromMaybe "html" $ lookup "format" kvs
     rawBlock (attrs, content) = B.rawBlock (format attrs) content
 
-list :: PandocMonad m => String -> TWParser m B.Blocks
+list :: PandocMonad m => Text -> TWParser m B.Blocks
 list prefix = choice [ bulletList prefix
                      , orderedList prefix
                      , definitionList prefix]
 
-definitionList :: PandocMonad m => String -> TWParser m B.Blocks
+definitionList :: PandocMonad m => Text -> TWParser m B.Blocks
 definitionList prefix = tryMsg "definitionList" $ do
-  indent <- lookAhead $ string prefix *> (many1 $ string "   ") <* string "$ "
-  elements <- many $ parseDefinitionListItem (prefix ++ concat indent)
+  indent <- lookAhead $ textStr prefix *> many1 (textStr "   ") <* textStr "$ "
+  elements <- many $ parseDefinitionListItem (prefix <> T.concat indent)
   return $ B.definitionList elements
   where
     parseDefinitionListItem :: PandocMonad m
-                            => String -> TWParser m (B.Inlines, [B.Blocks])
+                            => Text -> TWParser m (B.Inlines, [B.Blocks])
     parseDefinitionListItem indent = do
-      string (indent ++ "$ ") >> skipSpaces
+      textStr (indent <> "$ ") >> skipSpaces
       term <- many1Till inline $ string ": "
       line <- listItemLine indent $ string "$ "
-      return $ (mconcat term, [line])
+      return (mconcat term, [line])
 
-bulletList :: PandocMonad m => String -> TWParser m B.Blocks
+bulletList :: PandocMonad m => Text -> TWParser m B.Blocks
 bulletList prefix = tryMsg "bulletList" $
                     parseList prefix (char '*') (char ' ')
 
-orderedList :: PandocMonad m => String -> TWParser m B.Blocks
+orderedList :: PandocMonad m => Text -> TWParser m B.Blocks
 orderedList prefix = tryMsg "orderedList" $
                      parseList prefix (oneOf "1iIaA") (string ". ")
 
 parseList :: PandocMonad m
-          => String -> TWParser m Char -> TWParser m a -> TWParser m B.Blocks
+          => Text -> TWParser m Char -> TWParser m a -> TWParser m B.Blocks
 parseList prefix marker delim = do
-  (indent, style) <- lookAhead $ string prefix *> listStyle <* delim
-  blocks <- many $ parseListItem (prefix ++ indent) (char style <* delim)
+  (indent, style) <- lookAhead $ textStr prefix *> listStyle <* delim
+  blocks <- many $ parseListItem (prefix <> indent) (char style <* delim)
   return $ case style of
     '1' -> B.orderedListWith (1, DefaultStyle, DefaultDelim) blocks
     'i' -> B.orderedListWith (1, LowerRoman, DefaultDelim) blocks
@@ -216,59 +185,66 @@
     _   -> B.bulletList blocks
   where
     listStyle = do
-      indent <- many1 $ string "   "
+      indent <- many1 $ textStr "   "
       style <- marker
-      return (concat indent, style)
+      return (T.concat indent, style)
 
 parseListItem :: (PandocMonad m, Show a)
-              => String -> TWParser m a -> TWParser m B.Blocks
-parseListItem prefix marker = string prefix >> marker >> listItemLine prefix marker
+              => Text -> TWParser m a -> TWParser m B.Blocks
+parseListItem prefix marker = textStr prefix >> marker >> listItemLine prefix marker
 
 listItemLine :: (PandocMonad m, Show a)
-             => String -> TWParser m a -> TWParser m B.Blocks
-listItemLine prefix marker = lineContent >>= parseContent >>= return . mconcat
+             => Text -> TWParser m a -> TWParser m B.Blocks
+listItemLine prefix marker = mconcat <$> (lineContent >>= parseContent)
   where
     lineContent = do
       content <- anyLine
       continuation <- optionMaybe listContinuation
-      return $ filterSpaces content ++ "\n" ++ (maybe "" ("   " ++) continuation)
-    filterSpaces = reverse . dropWhile (== ' ') . reverse
-    listContinuation = notFollowedBy (string prefix >> marker) >>
+      return $ filterSpaces content <> "\n" <> maybe "" ("   " <>) continuation
+    filterSpaces = T.dropWhileEnd (== ' ')
+    listContinuation = notFollowedBy (textStr prefix >> marker) >>
                        string "   " >> lineContent
     parseContent = parseFromString' $ many1 $ nestedList <|> parseInline
-    parseInline = many1Till inline (lastNewline <|> newlineBeforeNestedList) >>=
-                  return . B.plain . mconcat
+    parseInline = B.plain . mconcat <$> many1Till inline (lastNewline <|> newlineBeforeNestedList)
     nestedList = list prefix
     lastNewline = try $ char '\n' <* eof
     newlineBeforeNestedList = try $ char '\n' <* lookAhead nestedList
 
 table :: PandocMonad m => TWParser m B.Blocks
 table = try $ do
-  tableHead <- optionMaybe $ many1Till tableParseHeader newline >>= return . unzip
+  thead <- optionMaybe (unzip <$> many1Till tableParseHeader newline)
   rows <- many1 tableParseRow
-  return $ buildTable mempty rows $ fromMaybe (align rows, columns rows) tableHead
+  return $ buildTable mempty rows $ fromMaybe (align rows, columns rows) thead
   where
     buildTable caption rows (aligns, heads)
-                    = B.table caption aligns heads rows
-    align rows      = replicate (columCount rows) (AlignDefault, 0)
-    columns rows    = replicate (columCount rows) mempty
-    columCount rows = length $ head rows
+                    = B.table (B.simpleCaption $ B.plain caption)
+                              aligns
+                              (TableHead nullAttr $ toHeaderRow heads)
+                              [TableBody nullAttr 0 [] $ map toRow rows]
+                              (TableFoot nullAttr [])
+    align rows      = replicate (columnCount rows)
+                         (AlignDefault, ColWidthDefault)
+    columns rows    = replicate (columnCount rows) mempty
+    columnCount (r:_) = length r
+    columnCount []  = 0
+    toRow           = Row nullAttr . map B.simpleCell
+    toHeaderRow l = [toRow l | not (null l)]
 
-tableParseHeader :: PandocMonad m => TWParser m ((Alignment, Double), B.Blocks)
+tableParseHeader :: PandocMonad m => TWParser m ((Alignment, ColWidth), B.Blocks)
 tableParseHeader = try $ do
   char '|'
-  leftSpaces <- many spaceChar >>= return . length
+  leftSpaces <- length <$> many spaceChar
   char '*'
   content <- tableColumnContent (char '*' >> skipSpaces >> char '|')
   char '*'
-  rightSpaces <- many spaceChar >>= return . length
+  rightSpaces <- length <$> many spaceChar
   optional tableEndOfRow
   return (tableAlign leftSpaces rightSpaces, content)
   where
     tableAlign left right
-      | left >= 2 && left == right = (AlignCenter, 0)
-      | left > right = (AlignRight, 0)
-      | otherwise = (AlignLeft, 0)
+      | left >= 2 && left == right = (AlignCenter, ColWidthDefault)
+      | left > right = (AlignRight, ColWidthDefault)
+      | otherwise = (AlignLeft, ColWidthDefault)
 
 tableParseRow :: PandocMonad m => TWParser m [B.Blocks]
 tableParseRow = many1Till tableParseColumn newline
@@ -282,13 +258,13 @@
 tableEndOfRow = lookAhead (try $ char '|' >> char '\n') >> char '|'
 
 tableColumnContent :: PandocMonad m => TWParser m a -> TWParser m B.Blocks
-tableColumnContent end = manyTill content (lookAhead $ try end) >>= return . B.plain . mconcat
+tableColumnContent end = B.plain . mconcat <$> manyTill content (lookAhead $ try end)
   where
     content = continuation <|> inline
     continuation = try $ char '\\' >> newline >> return mempty
 
 blockQuote :: PandocMonad m => TWParser m B.Blocks
-blockQuote = parseHtmlContent "blockquote" block >>= return . B.blockQuote . mconcat
+blockQuote = B.blockQuote . mconcat <$> parseHtmlContent "blockquote" block
 
 noautolink :: PandocMonad m => TWParser m B.Blocks
 noautolink = do
@@ -299,15 +275,15 @@
   setState $ st{ stateAllowLinks = True }
   return $ mconcat blocks
   where
-    parseContent      = parseFromString' $ many $ block
+    parseContent = parseFromString' $ many block
 
 para :: PandocMonad m => TWParser m B.Blocks
-para = many1Till inline endOfParaElement >>= return . result . mconcat
+para = result . mconcat <$> many1Till inline endOfParaElement
  where
    endOfParaElement = lookAhead $ endOfInput <|> endOfPara <|> newBlockElement
    endOfInput       = try $ skipMany blankline >> skipSpaces >> eof
    endOfPara        = try $ blankline >> skipMany1 blankline
-   newBlockElement  = try $ blankline >> skip blockElements
+   newBlockElement  = try $ blankline >> void blockElements
    result content   = if F.all (==Space) content
                       then mempty
                       else B.para $ B.trimInlines content
@@ -339,7 +315,7 @@
                 ] <?> "inline"
 
 whitespace :: PandocMonad m => TWParser m B.Inlines
-whitespace = (lb <|> regsp) >>= return
+whitespace = lb <|> regsp
   where lb = try $ skipMany spaceChar >> linebreak >> return B.space
         regsp = try $ skipMany1 spaceChar >> return B.space
 
@@ -361,13 +337,13 @@
          => TWParser m a -> (TWParser m a -> TWParser m b) -> TWParser m b
 enclosed sep p = between sep (try $ sep <* endMarker) p
   where
-    endMarker   = lookAhead $ skip endSpace <|> skip (oneOf ".,!?:)|") <|> eof
+    endMarker   = lookAhead $ void endSpace <|> void (oneOf ".,!?:)|") <|> eof
     endSpace    = (spaceChar <|> newline) >> return B.space
 
 macro :: PandocMonad m => TWParser m B.Inlines
 macro = macroWithParameters <|> withoutParameters
   where
-    withoutParameters = enclosed (char '%') (\_ -> macroName) >>= return . emptySpan
+    withoutParameters = emptySpan <$> enclosed (char '%') (const macroName)
     emptySpan name = buildSpan name [] mempty
 
 macroWithParameters :: PandocMonad m => TWParser m B.Inlines
@@ -378,84 +354,84 @@
   char '%'
   return $ buildSpan name kvs $ B.str content
 
-buildSpan :: String -> [(String, String)] -> B.Inlines -> B.Inlines
+buildSpan :: Text -> [(Text, Text)] -> B.Inlines -> B.Inlines
 buildSpan className kvs = B.spanWith attrs
   where
     attrs             = ("", ["twiki-macro", className] ++ additionalClasses, kvsWithoutClasses)
-    additionalClasses = maybe [] words $ lookup "class" kvs
+    additionalClasses = maybe [] T.words $ lookup "class" kvs
     kvsWithoutClasses = [(k,v) | (k,v) <- kvs, k /= "class"]
 
-macroName :: PandocMonad m => TWParser m String
+macroName :: PandocMonad m => TWParser m Text
 macroName = do
   first <- letter
   rest <- many $ alphaNum <|> char '_'
-  return (first:rest)
+  return $ T.pack $ first:rest
 
-attributes :: PandocMonad m => TWParser m (String, [(String, String)])
-attributes = char '{' *> spnl *> many (attribute <* spnl) <* char '}' >>=
-             return . foldr (either mkContent mkKvs) ([], [])
+attributes :: PandocMonad m => TWParser m (Text, [(Text, Text)])
+attributes = foldr (either mkContent mkKvs) ("", [])
+  <$> (char '{' *> spnl *> many (attribute <* spnl) <* char '}')
   where
     spnl                      = skipMany (spaceChar <|> newline)
-    mkContent c  ([], kvs)   = (c, kvs)
-    mkContent c  (rest, kvs) = (c ++ " " ++ rest, kvs)
-    mkKvs     kv (cont, rest) = (cont, (kv : rest))
+    mkContent c  ("", kvs)    = (c, kvs)
+    mkContent c  (rest, kvs)  = (c <> " " <> rest, kvs)
+    mkKvs     kv (cont, rest) = (cont, kv : rest)
 
-attribute :: PandocMonad m => TWParser m (Either String (String, String))
+attribute :: PandocMonad m => TWParser m (Either Text (Text, Text))
 attribute = withKey <|> withoutKey
   where
     withKey = try $ do
       key <- macroName
       char '='
-      parseValue False >>= return . (curry Right key)
-    withoutKey = try $ parseValue True >>= return . Left
-    parseValue allowSpaces = (withQuotes <|> withoutQuotes allowSpaces) >>= return . fromEntities
-    withQuotes             = between (char '"') (char '"') (\_ -> count 1 $ noneOf ['"'])
+      curry Right key <$> parseValue False
+    withoutKey = try $ Left <$> parseValue True
+    parseValue allowSpaces = fromEntities <$> (withQuotes <|> withoutQuotes allowSpaces)
+    withQuotes             = between (char '"') (char '"') (\_ -> countChar 1 $ noneOf ['"'])
     withoutQuotes allowSpaces
-      | allowSpaces == True = many1 $ noneOf "}"
-      | otherwise           = many1 $ noneOf " }"
+      | allowSpaces = many1Char $ noneOf "}"
+      | otherwise   = many1Char $ noneOf " }"
 
 nestedInlines :: (Show a, PandocMonad m)
               => TWParser m a -> TWParser m B.Inlines
 nestedInlines end = innerSpace <|> nestedInline
   where
-    innerSpace   = try $ whitespace <* (notFollowedBy end)
-    nestedInline = notFollowedBy whitespace >> nested inline
+    innerSpace   = try $ whitespace <* notFollowedBy end
+    nestedInline = notFollowedBy whitespace >> inline
 
 strong :: PandocMonad m => TWParser m B.Inlines
-strong = try $ enclosed (char '*') nestedInlines >>= return . B.strong
+strong = try $ B.strong <$> enclosed (char '*') nestedInlines
 
 strongHtml :: PandocMonad m => TWParser m B.Inlines
-strongHtml = (parseHtmlContent "strong" inline <|> parseHtmlContent "b" inline)
-             >>= return . B.strong . mconcat
+strongHtml = B.strong . mconcat <$> (parseHtmlContent "strong" inline <|> parseHtmlContent "b" inline)
 
 strongAndEmph :: PandocMonad m => TWParser m B.Inlines
-strongAndEmph = try $ enclosed (string "__") nestedInlines >>= return . B.emph . B.strong
+strongAndEmph = try $ B.emph . B.strong <$> enclosed (string "__") nestedInlines
 
 emph :: PandocMonad m => TWParser m B.Inlines
-emph = try $ enclosed (char '_') nestedInlines >>= return . B.emph
+emph = try $ B.emph <$> enclosed (char '_')
+                        (\p -> notFollowedBy (char '|') >> nestedInlines p)
+-- emphasis closers can't cross table cell boundaries, see #3921
 
 emphHtml :: PandocMonad m => TWParser m B.Inlines
-emphHtml = (parseHtmlContent "em" inline <|> parseHtmlContent "i" inline)
-           >>= return . B.emph . mconcat
+emphHtml = B.emph . mconcat <$> (parseHtmlContent "em" inline <|> parseHtmlContent "i" inline)
 
 nestedString :: (Show a, PandocMonad m)
-             => TWParser m a -> TWParser m String
-nestedString end = innerSpace <|> (count 1 nonspaceChar)
+             => TWParser m a -> TWParser m Text
+nestedString end = innerSpace <|> countChar 1 nonspaceChar
   where
-    innerSpace = try $ many1 spaceChar <* notFollowedBy end
+    innerSpace = try $ many1Char spaceChar <* notFollowedBy end
 
 boldCode :: PandocMonad m => TWParser m B.Inlines
-boldCode = try $ enclosed (string "==") nestedString >>= return . B.strong . B.code . fromEntities
+boldCode = try $ B.strong . B.code . fromEntities <$> enclosed (string "==") nestedString
 
 htmlComment :: PandocMonad m => TWParser m B.Inlines
 htmlComment = htmlTag isCommentTag >> return mempty
 
 code :: PandocMonad m => TWParser m B.Inlines
-code = try $ enclosed (char '=') nestedString >>= return . B.code . fromEntities
+code = try $ B.code . fromEntities <$> enclosed (char '=') nestedString
 
 codeHtml :: PandocMonad m => TWParser m B.Inlines
 codeHtml = do
-  (attrs, content) <- parseHtmlContentWithAttrs "code" anyChar
+  (attrs, content) <- parseCharHtmlContentWithAttrs "code" anyChar
   return $ B.codeWith attrs $ fromEntities content
 
 autoLink :: PandocMonad m => TWParser m B.Inlines
@@ -463,7 +439,7 @@
   state <- getState
   guard $ stateAllowLinks state
   (text, url) <- parseLink
-  guard $ checkLink (head $ reverse url)
+  guard $ checkLink (T.last url)
   return $ makeLink (text, url)
   where
     parseLink            = notFollowedBy nop >> (uri <|> emailAddress)
@@ -473,58 +449,49 @@
       | otherwise = isAlphaNum c
 
 str :: PandocMonad m => TWParser m B.Inlines
-str = (many1 alphaNum <|> count 1 characterReference) >>= return . B.str
+str = B.str <$> (many1Char alphaNum <|> characterReference)
 
 nop :: PandocMonad m => TWParser m B.Inlines
-nop = try $ (skip exclamation <|> skip nopTag) >> followContent
+nop = try $ (void exclamation <|> void nopTag) >> followContent
   where
     exclamation   = char '!'
     nopTag        = stringAnyCase "<nop>"
-    followContent = many1 nonspaceChar >>= return . B.str . fromEntities
+    followContent = B.str . fromEntities <$> many1Char nonspaceChar
 
 symbol :: PandocMonad m => TWParser m B.Inlines
-symbol = count 1 nonspaceChar >>= return . B.str
+symbol = B.str <$> countChar 1 nonspaceChar
 
 smart :: PandocMonad m => TWParser m B.Inlines
-smart = do
-  guardEnabled Ext_smart
-  doubleQuoted <|> singleQuoted <|>
-    choice [ apostrophe
-           , dash
-           , ellipses
-           ]
-
-singleQuoted :: PandocMonad m => TWParser m B.Inlines
-singleQuoted = try $ do
-  singleQuoteStart
-  withQuoteContext InSingleQuote $
-    many1Till inline singleQuoteEnd >>=
-    (return . B.singleQuoted . B.trimInlines . mconcat)
-
-doubleQuoted :: PandocMonad m => TWParser m B.Inlines
-doubleQuoted = try $ do
-  doubleQuoteStart
-  contents <- mconcat <$> many (try $ notFollowedBy doubleQuoteEnd >> inline)
-  (withQuoteContext InDoubleQuote $ doubleQuoteEnd >>
-   return (B.doubleQuoted $ B.trimInlines contents))
-   <|> (return $ (B.str "\8220") B.<> contents)
+smart = smartPunctuation inline
 
 link :: PandocMonad m => TWParser m B.Inlines
 link = try $ do
   st <- getState
   guard $ stateAllowLinks st
   setState $ st{ stateAllowLinks = False }
-  (url, title, content) <- linkText
+  (url, title, classes, content) <- linkText <|> simpleWikiLink
   setState $ st{ stateAllowLinks = True }
-  return $ B.link url title content
+  return $ B.linkWith ("",classes,[]) url title content
 
-linkText :: PandocMonad m => TWParser m (String, String, B.Inlines)
+linkText :: PandocMonad m => TWParser m (Text, Text, [Text], B.Inlines)
 linkText = do
   string "[["
-  url <- many1Till anyChar (char ']')
+  url <- T.pack <$> many1Till anyChar (char ']')
   content <- option (B.str url) (mconcat <$> linkContent)
   char ']'
-  return (url, "", content)
+  return (url, "", [], content)
   where
-    linkContent      = (char '[') >> many1Till anyChar (char ']') >>= parseLinkContent
+    linkContent      = char '[' >> many1Till anyChar (char ']') >>= parseLinkContent . T.pack
     parseLinkContent = parseFromString' $ many1 inline
+
+simpleWikiLink :: PandocMonad m => TWParser m (Text, Text, [Text], B.Inlines)
+simpleWikiLink = do
+  w <- wikiWord
+  return (w, "", ["wikilink"], B.str w)
+ where
+   wikiWord = do
+     cs <- many1 $ satisfy (\x -> isLetter x && isUpper x)
+     ds <- many1 $ satisfy (\x -> isDigit x || (isLetter x && isLower x))
+     es <- many1 $ satisfy (\x -> isLetter x && isUpper x)
+     fs <- many $ satisfy isAlphaNum
+     return $ T.pack $ cs ++ ds ++ es ++ fs
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,26 +1,9 @@
-{-
-Copyright (C) 2010-2012 Paul Rivier <paul*rivier#demotera*com> | tr '*#' '.@'
-              2010-2017 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
--}
-
+{-# LANGUAGE OverloadedStrings #-}
+{-# LANGUAGE ViewPatterns      #-}
 {- |
    Module      : Text.Pandoc.Readers.Textile
    Copyright   : Copyright (C) 2010-2012 Paul Rivier
-                               2010-2017 John MacFarlane
+                               2010-2024 John MacFarlane
    License     : GNU GPL, version 2 or above
 
    Maintainer  : Paul Rivier <paul*rivier#demotera*com>
@@ -28,7 +11,7 @@
    Portability : portable
 
 Conversion from Textile to 'Pandoc' document, based on the spec
-available at http://redcloth.org/textile.
+available at https://www.promptworks.com/textile/.
 
 Implemented and parsed:
  - Paragraphs
@@ -55,76 +38,107 @@
 import Control.Monad (guard, liftM)
 import Control.Monad.Except (throwError)
 import Data.Char (digitToInt, isUpper)
-import Data.List (intercalate, intersperse, transpose)
-import Data.Monoid ((<>))
+import Data.List (intersperse, transpose)
+import qualified Data.List as L
+import Data.List.NonEmpty (NonEmpty(..), nonEmpty)
+import qualified Data.Map as M
 import Data.Text (Text)
 import qualified Data.Text as T
 import Text.HTML.TagSoup (Tag (..), fromAttrib)
 import Text.HTML.TagSoup.Match
 import Text.Pandoc.Builder (Blocks, Inlines, trimInlines)
 import qualified Text.Pandoc.Builder as B
-import Text.Pandoc.Class (PandocMonad (..))
+import Text.Pandoc.Class.PandocMonad (PandocMonad (..))
 import Text.Pandoc.CSS
 import Text.Pandoc.Definition
+import Text.Pandoc.Logging
 import Text.Pandoc.Options
 import Text.Pandoc.Parsing
 import Text.Pandoc.Readers.HTML (htmlTag, isBlockTag, isInlineTag)
 import Text.Pandoc.Readers.LaTeX (rawLaTeXBlock, rawLaTeXInline)
-import Text.Pandoc.Shared (crFilter, trim, underlineSpan)
+import Text.Pandoc.Shared (trim, tshow)
+import Text.Read (readMaybe)
 
 -- | Parse a Textile text and return a Pandoc document.
-readTextile :: PandocMonad m
+readTextile :: (PandocMonad m, ToSources a)
             => ReaderOptions -- ^ Reader options
-            -> Text          -- ^ String to parse (assuming @'\n'@ line endings)
+            -> a
             -> m Pandoc
 readTextile opts s = do
-  parsed <- readWithM parseTextile def{ stateOptions = opts }
-                (T.unpack (crFilter s) ++ "\n\n")
+  let sources = ensureFinalNewlines 2 (toSources s)
+  parsed <- readWithM parseTextile def{ stateOptions = opts } sources
   case parsed of
      Right result -> return result
      Left e       -> throwError e
 
+type TextileParser = ParsecT Sources ParserState
 
 -- | Generate a Pandoc ADT from a textile document
-parseTextile :: PandocMonad m => ParserT [Char] ParserState m Pandoc
+parseTextile :: PandocMonad m => TextileParser m Pandoc
 parseTextile = do
   many blankline
   startPos <- getPosition
   -- go through once just to get list of reference keys and notes
   -- docMinusKeys is the raw document with blanks where the keys/notes were...
-  let firstPassParser = noteBlock <|> lineClump
-  manyTill firstPassParser eof >>= setInput . concat
+  let firstPassParser = do
+        pos <- getPosition
+        t <- noteBlock <|> referenceKey <|> lineClump
+        return (pos, t)
+  manyTill firstPassParser eof >>= setInput . Sources
   setPosition startPos
   st' <- getState
   let reversedNotes = stateNotes st'
   updateState $ \s -> s { stateNotes = reverse reversedNotes }
   -- now parse it for real...
-  blocks <- parseBlocks
-  return $ Pandoc nullMeta (B.toList blocks) -- FIXME
+  Pandoc nullMeta . B.toList <$> parseBlocks -- FIXME
 
-noteMarker :: PandocMonad m => ParserT [Char] ParserState m [Char]
-noteMarker = skipMany spaceChar >> string "fn" >> manyTill digit (char '.')
+noteMarker :: PandocMonad m => TextileParser m Text
+noteMarker = do
+  skipMany spaceChar
+  string "fn"
+  T.pack <$> manyTill digit (string "." <|> try (string "^."))
 
-noteBlock :: PandocMonad m => ParserT [Char] ParserState m [Char]
+noteBlock :: PandocMonad m => TextileParser m Text
 noteBlock = try $ do
   startPos <- getPosition
   ref <- noteMarker
   optional blankline
-  contents <- fmap unlines $ many1Till anyLine (blanklines <|> noteBlock)
+  contents <- T.unlines <$> many1Till anyLine (blanklines <|> noteBlock)
   endPos <- getPosition
-  let newnote = (ref, contents ++ "\n")
+  let newnote = (ref, contents <> "\n")
   st <- getState
   let oldnotes = stateNotes st
   updateState $ \s -> s { stateNotes = newnote : oldnotes }
   -- return blanks so line count isn't affected
-  return $ replicate (sourceLine endPos - sourceLine startPos) '\n'
+  return $ T.replicate (sourceLine endPos - sourceLine startPos) "\n"
 
+referenceKey :: PandocMonad m => TextileParser m Text
+referenceKey = try $ do
+  pos <- getPosition
+  char '['
+  refName <- T.pack <$> many1Till nonspaceChar (char ']')
+  refDestination <- T.pack <$> many1Till anyChar newline
+  st <- getState
+  let oldKeys = stateKeys st
+  let key = toKey refName
+  -- Textile doesn't support link titles on the reference
+  -- definition, so use the empty string
+  let target = (refDestination, "")
+  case M.lookup key oldKeys of
+    Just (t, _) | not (t == target) ->
+      -- similar to Markdown, only warn when the targets
+      -- for matching named references differ
+      logMessage $ DuplicateLinkReference refName pos
+    _ -> return ()
+  updateState $ \s -> s {stateKeys = M.insert key (target, nullAttr) oldKeys }
+  return "\n"
+
 -- | Parse document blocks
-parseBlocks :: PandocMonad m => ParserT [Char] ParserState m Blocks
+parseBlocks :: PandocMonad m => TextileParser m Blocks
 parseBlocks = mconcat <$> manyTill block eof
 
 -- | Block parsers list tried in definition order
-blockParsers :: PandocMonad m => [ParserT [Char] ParserState m Blocks]
+blockParsers :: PandocMonad m => [TextileParser m Blocks]
 blockParsers = [ codeBlock
                , header
                , blockQuote
@@ -134,65 +148,66 @@
                , rawHtmlBlock
                , rawLaTeXBlock'
                , table
-               , maybeExplicitBlock "p" para
+               , explicitBlock "p" (para <|> pure (B.para mempty))
+               , para
                , mempty <$ blanklines
                ]
 
 -- | Any block in the order of definition of blockParsers
-block :: PandocMonad m => ParserT [Char] ParserState m Blocks
+block :: PandocMonad m => TextileParser m Blocks
 block = do
   res <- choice blockParsers <?> "block"
-  trace (take 60 $ show $ B.toList res)
+  trace (T.take 60 $ tshow $ B.toList res)
   return res
 
-commentBlock :: PandocMonad m => ParserT [Char] ParserState m Blocks
+commentBlock :: PandocMonad m => TextileParser m Blocks
 commentBlock = try $ do
   string "###."
   manyTill anyLine blanklines
   return mempty
 
-codeBlock :: PandocMonad m => ParserT [Char] ParserState m Blocks
-codeBlock = codeBlockBc <|> codeBlockPre
+codeBlock :: PandocMonad m => TextileParser m Blocks
+codeBlock = codeBlockTextile <|> codeBlockHtml
 
-codeBlockBc :: PandocMonad m => ParserT [Char] ParserState m Blocks
-codeBlockBc = try $ do
-  string "bc."
+codeBlockTextile :: PandocMonad m => TextileParser m Blocks
+codeBlockTextile = try $ do
+  string "bc." <|> string "pre."
   extended <- option False (True <$ char '.')
   char ' '
-  let starts = ["p", "table", "bq", "bc", "h1", "h2", "h3",
+  let starts = ["p", "table", "bq", "bc", "pre", "h1", "h2", "h3",
                 "h4", "h5", "h6", "pre", "###", "notextile"]
-  let ender = choice $ map explicitBlockStart starts
+  let ender = () <$ choice (map explicitBlockStart starts)
   contents <- if extended
                  then do
                    f <- anyLine
                    rest <- many (notFollowedBy ender *> anyLine)
                    return (f:rest)
                  else manyTill anyLine blanklines
-  return $ B.codeBlock (trimTrailingNewlines (unlines contents))
+  return $ B.codeBlock (trimTrailingNewlines (T.unlines contents))
 
-trimTrailingNewlines :: String -> String
-trimTrailingNewlines = reverse . dropWhile (=='\n') . reverse
+trimTrailingNewlines :: Text -> Text
+trimTrailingNewlines = T.dropWhileEnd (=='\n')
 
 -- | Code Blocks in Textile are between <pre> and </pre>
-codeBlockPre :: PandocMonad m => ParserT [Char] ParserState m Blocks
-codeBlockPre = try $ do
+codeBlockHtml :: PandocMonad m => TextileParser m Blocks
+codeBlockHtml = try $ do
   (t@(TagOpen _ attrs),_) <- htmlTag (tagOpen (=="pre") (const True))
-  result' <- manyTill anyChar (htmlTag (tagClose (=="pre")))
+  result' <- T.pack <$> manyTill anyChar (htmlTag (tagClose (=="pre")))
   -- drop leading newline if any
-  let result'' = case result' of
-                      '\n':xs -> xs
-                      _       -> result'
+  let result'' = case T.uncons result' of
+                   Just ('\n', xs) -> xs
+                   _               -> result'
   -- drop trailing newline if any
-  let result''' = case reverse result'' of
-                       '\n':_ -> init result''
-                       _      -> result''
-  let classes = words $ fromAttrib "class" t
+  let result''' = case T.unsnoc result'' of
+                    Just (xs, '\n') -> xs
+                    _               -> result''
+  let classes = T.words $ fromAttrib "class" t
   let ident = fromAttrib "id" t
   let kvs = [(k,v) | (k,v) <- attrs, k /= "id" && k /= "class"]
   return $ B.codeBlockWith (ident,classes,kvs) result'''
 
 -- | Header of the form "hN. content" with N in 1..6
-header :: PandocMonad m => ParserT [Char] ParserState m Blocks
+header :: PandocMonad m => TextileParser m Blocks
 header = try $ do
   char 'h'
   level <- digitToInt <$> oneOf "123456"
@@ -204,14 +219,14 @@
   return $ B.headerWith attr' level name
 
 -- | Blockquote of the form "bq. content"
-blockQuote :: PandocMonad m => ParserT [Char] ParserState m Blocks
+blockQuote :: PandocMonad m => TextileParser m Blocks
 blockQuote = try $ do
   string "bq" >> attributes >> char '.' >> whitespace
   B.blockQuote <$> para
 
 -- Horizontal rule
 
-hrule :: PandocMonad m => ParserT [Char] st m Blocks
+hrule :: PandocMonad m => TextileParser m Blocks
 hrule = try $ do
   skipSpaces
   start <- oneOf "-*"
@@ -226,67 +241,101 @@
 -- | Can be a bullet list or an ordered list. This implementation is
 -- strict in the nesting, sublist must start at exactly "parent depth
 -- plus one"
-anyList :: PandocMonad m => ParserT [Char] ParserState m Blocks
+anyList :: PandocMonad m => TextileParser m Blocks
 anyList = try $ anyListAtDepth 1 <* blanklines
 
 -- | This allow one type of list to be nested into an other type,
 -- provided correct nesting
-anyListAtDepth :: PandocMonad m => Int -> ParserT [Char] ParserState m Blocks
+anyListAtDepth :: PandocMonad m => Int -> TextileParser m Blocks
 anyListAtDepth depth = choice [ bulletListAtDepth depth,
                                 orderedListAtDepth depth,
                                 definitionList ]
 
 -- | Bullet List of given depth, depth being the number of leading '*'
-bulletListAtDepth :: PandocMonad m => Int -> ParserT [Char] ParserState m Blocks
+bulletListAtDepth :: PandocMonad m => Int -> TextileParser m Blocks
 bulletListAtDepth depth = try $ B.bulletList  <$> many1 (bulletListItemAtDepth depth)
 
 -- | Bullet List Item of given depth, depth being the number of
 -- leading '*'
-bulletListItemAtDepth :: PandocMonad m => Int -> ParserT [Char] ParserState m Blocks
-bulletListItemAtDepth = genericListItemAtDepth '*'
+bulletListItemAtDepth :: PandocMonad m => Int -> TextileParser m Blocks
+bulletListItemAtDepth depth = try $ do
+  bulletListStartAtDepth depth
+  genericListItemContentsAtDepth depth
 
 -- | Ordered List of given depth, depth being the number of
 -- leading '#'
-orderedListAtDepth :: PandocMonad m => Int -> ParserT [Char] ParserState m Blocks
+-- The first Ordered List Item may have a start attribute
+orderedListAtDepth :: PandocMonad m => Int -> TextileParser m Blocks
 orderedListAtDepth depth = try $ do
-  items <- many1 (orderedListItemAtDepth depth)
-  return $ B.orderedList items
+  (startNum, firstItem) <- firstOrderedListItemAtDepth depth
+  moreItems <- many (orderedListItemAtDepth depth)
+  let listItems = firstItem : moreItems
+  return $ B.orderedListWith (startNum, DefaultStyle, DefaultDelim) listItems
 
+-- | The first Ordered List Item, which could have a start attribute
+firstOrderedListItemAtDepth :: PandocMonad m => Int
+                                             -> TextileParser m (Int, Blocks)
+firstOrderedListItemAtDepth depth = try $ do
+  startNum <- orderedListStartAtDepth depth
+  contents <- genericListItemContentsAtDepth depth
+  return (startNum, contents)
+
 -- | Ordered List Item of given depth, depth being the number of
 -- leading '#'
-orderedListItemAtDepth :: PandocMonad m => Int -> ParserT [Char] ParserState m Blocks
-orderedListItemAtDepth = genericListItemAtDepth '#'
+orderedListItemAtDepth :: PandocMonad m => Int -> TextileParser m Blocks
+orderedListItemAtDepth depth = try $ do
+  orderedListStartAtDepth depth
+  genericListItemContentsAtDepth depth
 
--- | Common implementation of list items
-genericListItemAtDepth :: PandocMonad m => Char -> Int -> ParserT [Char] ParserState m Blocks
-genericListItemAtDepth c depth = try $ do
-  count depth (char c) >> attributes >> whitespace
+-- | Lists always start with a number of leading characters '#' or '*'
+-- Ordered list start characters '#' can be followed by the start attribute
+-- number, but bullet list characters '*' can not
+orderedListStartAtDepth :: PandocMonad m => Int -> TextileParser m Int
+orderedListStartAtDepth depth = count depth (char '#') >>
+  try orderedListStartAttr <* (attributes >> whitespace)
+
+bulletListStartAtDepth :: PandocMonad m => Int -> TextileParser m ()
+bulletListStartAtDepth depth =  () <$ (count depth (char '*') >>
+                                       attributes >> whitespace)
+
+-- | The leading characters and start attributes differ between ordered and
+-- unordered lists, but their contents have the same structure and can
+-- share a Parser
+genericListItemContentsAtDepth :: PandocMonad m => Int
+                                                -> TextileParser m Blocks
+genericListItemContentsAtDepth depth = do
   contents <- mconcat <$> many ((B.plain . mconcat <$> many1 inline) <|>
-                                try (newline >> codeBlockPre))
+                                try (newline >> codeBlockHtml))
   newline
   sublist <- option mempty (anyListAtDepth (depth + 1))
   return $ contents <> sublist
 
+
 -- | A definition list is a set of consecutive definition items
-definitionList :: PandocMonad m => ParserT [Char] ParserState m Blocks
+definitionList :: PandocMonad m => TextileParser m Blocks
 definitionList = try $ B.definitionList <$> many1 definitionListItem
 
 -- | List start character.
-listStart :: PandocMonad m => ParserT [Char] ParserState m ()
+listStart :: PandocMonad m => TextileParser m ()
 listStart = genericListStart '*'
-        <|> () <$ genericListStart '#'
+        <|> () <$ orderedListStart
         <|> () <$ definitionListStart
 
-genericListStart :: PandocMonad m => Char -> ParserT [Char] st m ()
+genericListStart :: PandocMonad m => Char -> TextileParser m ()
 genericListStart c = () <$ try (many1 (char c) >> whitespace)
 
-basicDLStart :: PandocMonad m => ParserT [Char] ParserState m ()
+orderedListStart :: PandocMonad m => TextileParser m ()
+orderedListStart = () <$ try (many1 (char '#') >>
+                              try orderedListStartAttr >>
+                              whitespace)
+
+basicDLStart :: PandocMonad m => TextileParser m ()
 basicDLStart = do
   char '-'
   whitespace
   notFollowedBy newline
 
-definitionListStart :: PandocMonad m => ParserT [Char] ParserState m Inlines
+definitionListStart :: PandocMonad m => TextileParser m Inlines
 definitionListStart = try $ do
   basicDLStart
   trimInlines . mconcat <$>
@@ -299,26 +348,26 @@
 -- the term defined, then spaces and ":=". The definition follows, on
 -- the same single line, or spaned on multiple line, after a line
 -- break.
-definitionListItem :: PandocMonad m => ParserT [Char] ParserState m (Inlines, [Blocks])
+definitionListItem :: PandocMonad m => TextileParser m (Inlines, [Blocks])
 definitionListItem = try $ do
-  term <- (mconcat . intersperse B.linebreak) <$> many1 definitionListStart
+  term <- mconcat . intersperse B.linebreak <$> many1 definitionListStart
   def' <- string ":=" *> optional whitespace *> (multilineDef <|> inlineDef)
   return (term, def')
-  where inlineDef :: PandocMonad m => ParserT [Char] ParserState m [Blocks]
+  where inlineDef :: PandocMonad m => TextileParser m [Blocks]
         inlineDef = liftM (\d -> [B.plain d])
                     $ optional whitespace >> (trimInlines . mconcat <$> many inline) <* newline
-        multilineDef :: PandocMonad m => ParserT [Char] ParserState m [Blocks]
+        multilineDef :: PandocMonad m => TextileParser m [Blocks]
         multilineDef = try $ do
           optional whitespace >> newline
-          s <- many1Till anyChar (try (string "=:" >> newline))
-          -- this ++ "\n\n" does not look very good
-          ds <- parseFromString' parseBlocks (s ++ "\n\n")
+          s <- T.pack <$> many1Till anyChar (try (string "=:" >> newline))
+          -- this <> "\n\n" does not look very good
+          ds <- parseFromString' parseBlocks (s <> "\n\n")
           return [ds]
 
 -- raw content
 
 -- | A raw Html Block, optionally followed by blanklines
-rawHtmlBlock :: PandocMonad m => ParserT [Char] ParserState m Blocks
+rawHtmlBlock :: PandocMonad m => TextileParser m Blocks
 rawHtmlBlock = try $ do
   skipMany spaceChar
   (_,b) <- htmlTag isBlockTag
@@ -326,14 +375,14 @@
   return $ B.rawBlock "html" b
 
 -- | Raw block of LaTeX content
-rawLaTeXBlock' :: PandocMonad m => ParserT [Char] ParserState m Blocks
+rawLaTeXBlock' :: PandocMonad m => TextileParser m Blocks
 rawLaTeXBlock' = do
   guardEnabled Ext_raw_tex
   B.rawBlock "latex" <$> (rawLaTeXBlock <* spaces)
 
 
 -- | In textile, paragraphs are separated by blank lines.
-para :: PandocMonad m => ParserT [Char] ParserState m Blocks
+para :: PandocMonad m => TextileParser m Blocks
 para = B.para . trimInlines . mconcat <$> many1 inline
 
 -- Tables
@@ -344,7 +393,7 @@
 toAlignment '=' = AlignCenter
 toAlignment _   = AlignDefault
 
-cellAttributes :: PandocMonad m => ParserT [Char] ParserState m (Bool, Alignment)
+cellAttributes :: PandocMonad m => TextileParser m (Bool, Alignment)
 cellAttributes = try $ do
   isHeader <- option False (True <$ char '_')
   -- we just ignore colspan and rowspan markers:
@@ -357,18 +406,22 @@
   return (isHeader, alignment)
 
 -- | A table cell spans until a pipe |
-tableCell :: PandocMonad m => ParserT [Char] ParserState m ((Bool, Alignment), Blocks)
+tableCell :: PandocMonad m => TextileParser m ((Bool, Alignment), Blocks)
 tableCell = try $ do
   char '|'
-  (isHeader, alignment) <- option (False, AlignDefault) $ cellAttributes
+  (isHeader, alignment) <- option (False, AlignDefault) cellAttributes
   notFollowedBy blankline
-  raw <- trim <$>
+  raw <- trim . T.pack <$>
          many (noneOf "|\n" <|> try (char '\n' <* notFollowedBy blankline))
-  content <- mconcat <$> parseFromString' (many inline) raw
-  return ((isHeader, alignment), B.plain content)
+  content <- parseFromString' parseBlocks (raw <> "\n\n")
+  -- Convert lone Para to Plain for backward compatibility
+  let content' = case B.toList content of
+                   [Para ils] -> B.plain (B.fromList ils)
+                   _          -> content
+  return ((isHeader, alignment), content')
 
 -- | A table row is made of many table cells
-tableRow :: PandocMonad m => ParserT [Char] ParserState m [((Bool, Alignment), Blocks)]
+tableRow :: PandocMonad m => TextileParser m [((Bool, Alignment), Blocks)]
 tableRow = try $ do
   -- skip optional row attributes
   optional $ try $ do
@@ -378,7 +431,7 @@
   many1 tableCell <* char '|' <* blankline
 
 -- | A table with an optional header.
-table :: PandocMonad m => ParserT [Char] ParserState m Blocks
+table :: PandocMonad m => TextileParser m Blocks
 table = try $ do
   -- ignore table attributes
   caption <- option mempty $ try $ do
@@ -394,15 +447,19 @@
                              (toprow:rest) | any (fst . fst) toprow ->
                                 (toprow, rest)
                              _ -> (mempty, rawrows)
-  let nbOfCols = max (length headers) (length $ head rows)
-  let aligns = map minimum $ transpose $ map (map (snd . fst)) (headers:rows)
-  return $ B.table caption
-    (zip aligns (replicate nbOfCols 0.0))
-    (map snd headers)
-    (map (map snd) rows)
+  let nbOfCols = maximum $ fmap length (headers :| rows)
+  let aligns = map (maybe AlignDefault minimum . nonEmpty) $
+                transpose $ map (map (snd . fst)) (headers:rows)
+  let toRow = Row nullAttr . map B.simpleCell
+      toHeaderRow l = [toRow l | not (null l)]
+  return $ B.table (B.simpleCaption $ B.plain caption)
+    (zip aligns (replicate nbOfCols ColWidthDefault))
+    (TableHead nullAttr $ toHeaderRow $ map snd headers)
+    [TableBody nullAttr 0 [] $ map (toRow . map snd) rows]
+    (TableFoot nullAttr [])
 
 -- | Ignore markers for cols, thead, tfoot.
-ignorableRow :: PandocMonad m => ParserT [Char] ParserState m ()
+ignorableRow :: PandocMonad m => TextileParser m ()
 ignorableRow = try $ do
   char '|'
   oneOf ":^-~"
@@ -411,25 +468,27 @@
   _ <- anyLine
   return ()
 
-explicitBlockStart :: PandocMonad m => String -> ParserT [Char] ParserState m ()
+explicitBlockStart :: PandocMonad m => Text -> TextileParser m Attr
 explicitBlockStart name = try $ do
-  string name
-  attributes
+  string (T.unpack name)
+  attr <- attributes
   char '.'
   optional whitespace
   optional endline
+  return attr
 
 -- | Blocks like 'p' and 'table' do not need explicit block tag.
 -- However, they can be used to set HTML/CSS attributes when needed.
-maybeExplicitBlock :: PandocMonad m
-                   => String  -- ^ block tag name
-                   -> ParserT [Char] ParserState m Blocks -- ^ implicit block
-                   -> ParserT [Char] ParserState m Blocks
-maybeExplicitBlock name blk = try $ do
-  optional $ explicitBlockStart name
-  blk
-
-
+explicitBlock :: PandocMonad m
+              => Text  -- ^ block tag name
+              -> TextileParser m Blocks -- ^ implicit block
+              -> TextileParser m Blocks
+explicitBlock name blk = try $ do
+  attr <- explicitBlockStart name
+  contents <- blk
+  return $ if attr == nullAttr
+              then contents
+              else B.divWith attr contents
 
 ----------
 -- Inlines
@@ -437,16 +496,17 @@
 
 
 -- | Any inline element
-inline :: PandocMonad m => ParserT [Char] ParserState m Inlines
+inline :: PandocMonad m => TextileParser m Inlines
 inline = choice inlineParsers <?> "inline"
 
 -- | Inline parsers tried in order
-inlineParsers :: PandocMonad m => [ParserT [Char] ParserState m Inlines]
+inlineParsers :: PandocMonad m => [TextileParser m Inlines]
 inlineParsers = [ str
                 , whitespace
                 , endline
                 , code
                 , escapedInline
+                , spanGroup
                 , inlineMarkup
                 , groupedInlineMarkup
                 , rawHtmlInline
@@ -455,54 +515,66 @@
                 , link
                 , image
                 , mark
-                , (B.str . (:[])) <$> characterReference
+                , B.str <$> characterReference
                 , smartPunctuation inline
                 , symbol
                 ]
 
 -- | Inline markups
-inlineMarkup :: PandocMonad m => ParserT [Char] ParserState m Inlines
+inlineMarkup :: PandocMonad m => TextileParser m Inlines
 inlineMarkup = choice [ simpleInline (string "??") (B.cite [])
                       , simpleInline (string "**") B.strong
                       , simpleInline (string "__") B.emph
                       , simpleInline (char '*') B.strong
                       , simpleInline (char '_') B.emph
-                      , simpleInline (char '+') underlineSpan
+                      , simpleInline (char '+') B.underline
                       , simpleInline (char '-' <* notFollowedBy (char '-')) B.strikeout
                       , simpleInline (char '^') B.superscript
                       , simpleInline (char '~') B.subscript
-                      , simpleInline (char '%') id
                       ]
 
+-- "The <span> tag is created by percent % signs between whitespaces."
+-- e.g. My mother has %{color:green;}green% eyes.
+spanGroup :: PandocMonad m => TextileParser m Inlines
+spanGroup = try $ do
+  notAfterString >>= guard
+  char '%' *> notFollowedBy whitespace
+  attr <- option nullAttr attributes
+  contents <- mconcat <$> manyTill
+   (try (((B.space <>) <$> try (whitespace *> notFollowedBy newline *> inline))
+         <|> try (notFollowedBy newline *> inline)))
+   (try (char '%' <* lookAhead (newline <|> ' ' <$ whitespace)))
+  pure $ B.spanWith attr contents
+
 -- | Trademark, registered, copyright
-mark :: PandocMonad m => ParserT [Char] st m Inlines
+mark :: PandocMonad m => TextileParser m Inlines
 mark = try $ char '(' >> (try tm <|> try reg <|> copy)
 
-reg :: PandocMonad m => ParserT [Char] st m Inlines
+reg :: PandocMonad m => TextileParser m Inlines
 reg = do
   oneOf "Rr"
   char ')'
   return $ B.str "\174"
 
-tm :: PandocMonad m => ParserT [Char] st m Inlines
+tm :: PandocMonad m => TextileParser m Inlines
 tm = do
   oneOf "Tt"
   oneOf "Mm"
   char ')'
   return $ B.str "\8482"
 
-copy :: PandocMonad m => ParserT [Char] st m Inlines
+copy :: PandocMonad m => TextileParser m Inlines
 copy = do
   oneOf "Cc"
   char ')'
   return $ B.str "\169"
 
-note :: PandocMonad m => ParserT [Char] ParserState m Inlines
+note :: PandocMonad m => TextileParser m Inlines
 note = try $ do
-  ref <- (char '[' *> many1 digit <* char ']')
+  ref <- char '[' *> many1 digit <* char ']'
   notes <- stateNotes <$> getState
-  case lookup ref notes of
-    Nothing  -> fail "note not found"
+  case lookup (T.pack ref) notes of
+    Nothing  -> Prelude.fail "note not found"
     Just raw -> B.note <$> parseFromString' parseBlocks raw
 
 -- | Special chars
@@ -518,42 +590,42 @@
 stringBreakers = " \t\n\r.,\"'?!;:<>«»„“”‚‘’()[]"
 
 wordBoundaries :: [Char]
-wordBoundaries = markupChars ++ stringBreakers
+wordBoundaries = markupChars <> stringBreakers
 
 -- | Parse a hyphened sequence of words
-hyphenedWords :: PandocMonad m => ParserT [Char] ParserState m String
+hyphenedWords :: PandocMonad m => TextileParser m Text
 hyphenedWords = do
   x <- wordChunk
   xs <-  many (try $ char '-' >> wordChunk)
-  return $ intercalate "-" (x:xs)
+  return $ T.intercalate "-" (x:xs)
 
-wordChunk :: PandocMonad m => ParserT [Char] ParserState m String
+wordChunk :: PandocMonad m => TextileParser m Text
 wordChunk = try $ do
   hd <- noneOf wordBoundaries
-  tl <- many ( (noneOf wordBoundaries) <|>
+  tl <- many ( noneOf wordBoundaries <|>
                try (notFollowedBy' note *> oneOf markupChars
                      <* lookAhead (noneOf wordBoundaries) ) )
-  return $ hd:tl
+  return $ T.pack $ hd:tl
 
 -- | Any string
-str :: PandocMonad m => ParserT [Char] ParserState m Inlines
+str :: PandocMonad m => TextileParser m Inlines
 str = do
   baseStr <- hyphenedWords
-  -- RedCloth compliance : if parsed word is uppercase and immediatly
+  -- RedCloth compliance : if parsed word is uppercase and immediately
   -- followed by parens, parens content is unconditionally word acronym
   fullStr <- option baseStr $ try $ do
-    guard $ all isUpper baseStr
-    acro <- enclosed (char '(') (char ')') anyChar'
-    return $ concat [baseStr, " (", acro, ")"]
+    guard $ T.all isUpper baseStr
+    acro <- T.pack <$> enclosed (char '(') (char ')') anyChar'
+    return $ T.concat [baseStr, " (", acro, ")"]
   updateLastStrPos
   return $ B.str fullStr
 
 -- | Some number of space chars
-whitespace :: PandocMonad m => ParserT [Char] st m Inlines
+whitespace :: PandocMonad m => TextileParser m Inlines
 whitespace = many1 spaceChar >> return B.space <?> "whitespace"
 
 -- | In Textile, an isolated endline character is a line break
-endline :: PandocMonad m => ParserT [Char] ParserState m Inlines
+endline :: PandocMonad m => TextileParser m Inlines
 endline = try $ do
   newline
   notFollowedBy blankline
@@ -561,158 +633,184 @@
   notFollowedBy rawHtmlBlock
   return B.linebreak
 
-rawHtmlInline :: PandocMonad m => ParserT [Char] ParserState m Inlines
+rawHtmlInline :: PandocMonad m => TextileParser m Inlines
 rawHtmlInline = B.rawInline "html" . snd <$> htmlTag isInlineTag
 
 -- | Raw LaTeX Inline
-rawLaTeXInline' :: PandocMonad m => ParserT [Char] ParserState m Inlines
+rawLaTeXInline' :: PandocMonad m => TextileParser m Inlines
 rawLaTeXInline' = try $ do
   guardEnabled Ext_raw_tex
   B.rawInline "latex" <$> rawLaTeXInline
 
 -- | Textile standard link syntax is "label":target. But we
 -- can also have ["label":target].
-link :: PandocMonad m => ParserT [Char] ParserState m Inlines
+link :: PandocMonad m => TextileParser m Inlines
 link = try $ do
   bracketed <- (True <$ char '[') <|> return False
   char '"' *> notFollowedBy (oneOf " \t\n\r")
   attr <- attributes
   name <- trimInlines . mconcat <$>
           withQuoteContext InDoubleQuote (many1Till inline (char '"'))
-  char ':'
-  let stop = if bracketed
-                then char ']'
-                else lookAhead $ space <|> eof' <|>
-                       try (oneOf "!.,;:" *>
-                              (space <|> newline <|> eof'))
-  url <- many1Till nonspaceChar stop
+  url <- linkUrl bracketed
   let name' = if B.toList name == [Str "$"] then B.str url else name
   return $ if attr == nullAttr
               then B.link url "" name'
               else B.spanWith attr $ B.link url "" name'
 
+linkUrl :: PandocMonad m => Bool -> TextileParser m Text
+linkUrl bracketed = do
+  char ':'
+  let stop = if bracketed
+                then char ']'
+                else lookAhead $ space <|> eof' <|> oneOf "[]" <|>
+                       try (oneOf "!.,;:*" *>
+                              (space <|> newline <|> eof'))
+  rawLink <- T.pack <$> many1Till nonspaceChar stop
+  st <- getState
+  return $ case M.lookup (toKey rawLink) (stateKeys st) of
+    Nothing -> rawLink
+    Just ((src, _), _) -> src
+
 -- | image embedding
-image :: PandocMonad m => ParserT [Char] ParserState m Inlines
+image :: PandocMonad m => TextileParser m Inlines
 image = try $ do
   char '!' >> notFollowedBy space
   (ident, cls, kvs) <- attributes
   let attr = case lookup "style" kvs of
                Just stls -> (ident, cls, pickStylesToKVs ["width", "height"] stls)
                Nothing   -> (ident, cls, kvs)
-  src <- many1 (noneOf " \t\n\r!(")
-  alt <- option "" $ try $ char '(' *> manyTill anyChar (char ')')
+  src <- T.pack <$> many1 (noneOf " \t\n\r!(")
+  alt <- fmap T.pack $ option "" $ try $ char '(' *> manyTill anyChar (char ')')
   char '!'
-  return $ B.imageWith attr src alt (B.str alt)
+  let img = B.imageWith attr src alt (B.str alt)
+  try (do -- image link
+         url <- linkUrl False
+         return (B.link url "" img))
+   <|> return img
 
-escapedInline :: PandocMonad m => ParserT [Char] ParserState m Inlines
+escapedInline :: PandocMonad m => TextileParser m Inlines
 escapedInline = escapedEqs <|> escapedTag
 
-escapedEqs :: PandocMonad m => ParserT [Char] ParserState m Inlines
-escapedEqs = B.str <$>
+escapedEqs :: PandocMonad m => TextileParser m Inlines
+escapedEqs = B.str . T.pack <$>
   try (string "==" *> manyTill anyChar' (try $ string "=="))
 
 -- | literal text escaped btw <notextile> tags
-escapedTag :: PandocMonad m => ParserT [Char] ParserState m Inlines
-escapedTag = B.str <$>
-  (try $ string "<notextile>" *>
+escapedTag :: PandocMonad m => TextileParser m Inlines
+escapedTag = B.str . T.pack <$>
+  try (string "<notextile>" *>
          manyTill anyChar' (try $ string "</notextile>"))
 
 -- | Any special symbol defined in wordBoundaries
-symbol :: PandocMonad m => ParserT [Char] ParserState m Inlines
-symbol = B.str . singleton <$> (notFollowedBy newline *>
-                                notFollowedBy rawHtmlBlock *>
-                                oneOf wordBoundaries)
+symbol :: PandocMonad m => TextileParser m Inlines
+symbol = do
+  c <- notFollowedBy newline *>
+         notFollowedBy rawHtmlBlock *>
+         oneOf wordBoundaries
+  updateLastStrPos
+  pure $ B.str . T.singleton $ c
 
 -- | Inline code
-code :: PandocMonad m => ParserT [Char] ParserState m Inlines
+code :: PandocMonad m => TextileParser m Inlines
 code = code1 <|> code2
 
 -- any character except a newline before a blank line
-anyChar' :: PandocMonad m => ParserT [Char] ParserState m Char
+anyChar' :: PandocMonad m => TextileParser m Char
 anyChar' =
-  satisfy (/='\n') <|> (try $ char '\n' <* notFollowedBy blankline)
+  satisfy (/='\n') <|>
+  try (char '\n' <* notFollowedBy blankline)
 
-code1 :: PandocMonad m => ParserT [Char] ParserState m Inlines
-code1 = B.code <$> surrounded (char '@') anyChar'
+code1 :: PandocMonad m => TextileParser m Inlines
+code1 = B.code . T.pack <$> surrounded (char '@') anyChar'
 
-code2 :: PandocMonad m => ParserT [Char] ParserState m Inlines
+code2 :: PandocMonad m => TextileParser m Inlines
 code2 = do
   htmlTag (tagOpen (=="tt") null)
-  B.code <$> manyTill anyChar' (try $ htmlTag $ tagClose (=="tt"))
+  B.code . T.pack <$> manyTill anyChar' (try $ htmlTag $ tagClose (=="tt"))
 
+orderedListStartAttr :: PandocMonad m => TextileParser m Int
+orderedListStartAttr = do
+  digits <- many digit
+  case readMaybe digits :: Maybe Int of
+    Nothing -> return 1
+    Just n  -> return n
+
 -- | Html / CSS attributes
-attributes :: PandocMonad m => ParserT [Char] ParserState m Attr
-attributes = foldl (flip ($)) ("",[],[]) <$>
+attributes :: PandocMonad m => TextileParser m Attr
+attributes = L.foldl' (flip ($)) ("",[],[]) <$>
   try (do special <- option id specialAttribute
           attrs <- many attribute
           return (special : attrs))
 
-specialAttribute :: PandocMonad m => ParserT [Char] ParserState m (Attr -> Attr)
+specialAttribute :: PandocMonad m => TextileParser m (Attr -> Attr)
 specialAttribute = do
   alignStr <- ("center" <$ char '=') <|>
     ("justify" <$ try (string "<>")) <|>
     ("right" <$ char '>') <|>
     ("left" <$ char '<')
   notFollowedBy spaceChar
-  return $ addStyle ("text-align:" ++ alignStr)
+  return $ addStyle $ T.pack $ "text-align:" ++ alignStr
 
-attribute :: PandocMonad m => ParserT [Char] ParserState m (Attr -> Attr)
+attribute :: PandocMonad m => TextileParser m (Attr -> Attr)
 attribute = try $
   (classIdAttr <|> styleAttr <|> langAttr) <* notFollowedBy spaceChar
 
-classIdAttr :: PandocMonad m => ParserT [Char] ParserState m (Attr -> Attr)
+classIdAttr :: PandocMonad m => TextileParser m (Attr -> Attr)
 classIdAttr = try $ do -- (class class #id)
   char '('
-  ws <- words `fmap` manyTill anyChar' (char ')')
+  ws <- T.words `fmap` T.pack <$> manyTill anyChar' (char ')')
   case reverse ws of
-       []                      -> return $ \(_,_,keyvals) -> ("",[],keyvals)
-       (('#':ident'):classes') -> return $ \(_,_,keyvals) ->
-                                             (ident',classes',keyvals)
-       classes'                -> return $ \(_,_,keyvals) ->
-                                             ("",classes',keyvals)
+       []
+         -> return $ \(_,_,keyvals) -> ("",[],keyvals)
+       ((T.uncons -> Just ('#', ident')):classes')
+         -> return $ \(_,_,keyvals) -> (ident',classes',keyvals)
+       classes'
+         -> return $ \(_,_,keyvals) -> ("",classes',keyvals)
 
-styleAttr :: PandocMonad m => ParserT [Char] ParserState m (Attr -> Attr)
+styleAttr :: PandocMonad m => TextileParser m (Attr -> Attr)
 styleAttr = do
   style <- try $ enclosed (char '{') (char '}') anyChar'
-  return $ addStyle style
+  return $ addStyle $ T.pack style
 
-addStyle :: String -> Attr -> Attr
+addStyle :: Text -> Attr -> Attr
 addStyle style (id',classes,keyvals) =
   (id',classes,keyvals')
   where keyvals' = ("style", style') : [(k,v) | (k,v) <- keyvals, k /= "style"]
-        style' = style ++ ";" ++ concat [v | ("style",v) <- keyvals]
+        style' = style <> ";" <> T.concat [v | ("style",v) <- keyvals]
 
-langAttr :: PandocMonad m => ParserT [Char] ParserState m (Attr -> Attr)
+langAttr :: PandocMonad m => TextileParser m (Attr -> Attr)
 langAttr = do
   lang <- try $ enclosed (char '[') (char ']') alphaNum
-  return $ \(id',classes,keyvals) -> (id',classes,("lang",lang):keyvals)
+  return $ \(id',classes,keyvals) -> (id',classes,("lang",T.pack lang):keyvals)
 
 -- | Parses material surrounded by a parser.
 surrounded :: (PandocMonad m, Show t)
-           => ParserT [Char] st m t   -- ^ surrounding parser
-           -> ParserT [Char] st m a   -- ^ content parser (to be used repeatedly)
-           -> ParserT [Char] st m [a]
+           => ParsecT Sources st m t   -- ^ surrounding parser
+           -> ParsecT Sources st m a   -- ^ content parser (to be used repeatedly)
+           -> ParsecT Sources st m [a]
 surrounded border =
   enclosed (border *> notFollowedBy (oneOf " \t\n\r")) (try border)
 
 simpleInline :: PandocMonad m
-             => ParserT [Char] ParserState m t        -- ^ surrounding parser
+             => TextileParser m t        -- ^ surrounding parser
              -> (Inlines -> Inlines)                  -- ^ Inline constructor
-             -> ParserT [Char] ParserState m Inlines  -- ^ content parser (to be used repeatedly)
+             -> TextileParser m Inlines  -- ^ content parser (to be used repeatedly)
 simpleInline border construct = try $ do
-  notAfterString
+  notAfterString >>= guard
   border *> notFollowedBy (oneOf " \t\n\r")
   attr <- attributes
   body <- trimInlines . mconcat <$>
           withQuoteContext InSingleQuote
-            (manyTill (notFollowedBy newline >> inline)
+            (manyTill (((B.space <>) <$>
+                         try (whitespace *> notFollowedBy newline >> inline))
+                     <|> try (notFollowedBy newline >> inline))
              (try border <* notFollowedBy alphaNum))
   return $ construct $
         if attr == nullAttr
            then body
            else B.spanWith attr body
 
-groupedInlineMarkup :: PandocMonad m => ParserT [Char] ParserState m Inlines
+groupedInlineMarkup :: PandocMonad m => TextileParser m Inlines
 groupedInlineMarkup = try $ do
     char '['
     sp1 <- option mempty $ B.space <$ whitespace
@@ -721,9 +819,5 @@
     char ']'
     return $ sp1 <> result <> sp2
 
--- | Create a singleton list
-singleton :: a -> [a]
-singleton x = [x]
-
-eof' :: Monad m => ParserT [Char] s m Char
+eof' :: Monad m => ParsecT Sources s m Char
 eof' = '\n' <$ eof
diff --git a/src/Text/Pandoc/Readers/TikiWiki.hs b/src/Text/Pandoc/Readers/TikiWiki.hs
--- a/src/Text/Pandoc/Readers/TikiWiki.hs
+++ b/src/Text/Pandoc/Readers/TikiWiki.hs
@@ -1,13 +1,10 @@
-{-# LANGUAGE FlexibleContexts     #-}
-{-# LANGUAGE FlexibleInstances    #-}
-{-# LANGUAGE OverloadedStrings    #-}
-{-# LANGUAGE RelaxedPolyRec       #-}
-{-# LANGUAGE TypeSynonymInstances #-}
+{-# LANGUAGE FlexibleContexts  #-}
+{-# LANGUAGE OverloadedStrings #-}
 
 {- |
    Module      : Text.Pandoc.Readers.TikiWiki
    Copyright   : Copyright (C) 2017 Robin Lee Powell
-   License     : GPLv2
+   License     : GNU GPL, version 2 or above
 
    Maintainer  : Robin Lee Powell <robinleepowell@gmail.com>
    Stability   : alpha
@@ -22,52 +19,44 @@
 import Control.Monad
 import Control.Monad.Except (throwError)
 import qualified Data.Foldable as F
+import Data.List (dropWhileEnd)
 import Data.Maybe (fromMaybe)
 import Data.Text (Text)
 import qualified Data.Text as T
 import qualified Text.Pandoc.Builder as B
-import Text.Pandoc.Class (CommonState (..), PandocMonad (..))
+import Text.Pandoc.Class.PandocMonad (PandocMonad (..), getVerbosity)
 import Text.Pandoc.Definition
 import Text.Pandoc.Logging (Verbosity (..))
 import Text.Pandoc.Options
-import Text.Pandoc.Parsing hiding (enclosed, nested)
-import Text.Pandoc.Shared (crFilter)
+import Text.Pandoc.Parsing hiding (enclosed)
+import Text.Pandoc.Shared (safeRead)
 import Text.Pandoc.XML (fromEntities)
 import Text.Printf (printf)
 
 -- | Read TikiWiki from an input string and return a Pandoc document.
-readTikiWiki :: PandocMonad m
+readTikiWiki :: (PandocMonad m, ToSources a)
           => ReaderOptions
-          -> Text
+          -> a
           -> m Pandoc
 readTikiWiki opts s = do
-  res <- readWithM parseTikiWiki def{ stateOptions = opts }
-             (T.unpack (crFilter s) ++ "\n\n")
+  let sources = ensureFinalNewlines 2 (toSources s)
+  res <- readWithM parseTikiWiki def{ stateOptions = opts } sources
   case res of
        Left e  -> throwError e
        Right d -> return d
 
-type TikiWikiParser = ParserT [Char] ParserState
+type TikiWikiParser = ParsecT Sources ParserState
 
 --
 -- utility functions
 --
 
-tryMsg :: PandocMonad m => String -> TikiWikiParser m a -> TikiWikiParser m a
-tryMsg msg p = try p <?> msg
+tryMsg :: Text -> TikiWikiParser m a -> TikiWikiParser m a
+tryMsg msg p = try p <?> T.unpack msg
 
-skip :: PandocMonad m => TikiWikiParser m a -> TikiWikiParser m ()
+skip :: TikiWikiParser m a -> TikiWikiParser m ()
 skip parser = Control.Monad.void parser
 
-nested :: PandocMonad m => TikiWikiParser m a -> TikiWikiParser m a
-nested p = do
-  nestlevel <- stateMaxNestingLevel <$>  getState
-  guard $ nestlevel > 0
-  updateState $ \st -> st{ stateMaxNestingLevel = stateMaxNestingLevel st - 1 }
-  res <- p
-  updateState $ \st -> st{ stateMaxNestingLevel = nestlevel }
-  return res
-
 --
 -- main parser
 --
@@ -81,14 +70,14 @@
 
 block :: PandocMonad m => TikiWikiParser m B.Blocks
 block = do
-  verbosity <- getsCommonState stVerbosity
+  verbosity <- getVerbosity
   pos <- getPosition
   res <- mempty <$ skipMany1 blankline
          <|> blockElements
          <|> para
   skipMany blankline
   when (verbosity >= INFO) $
-    trace (printf "line %d: %s" (sourceLine pos) (take 60 $ show $ B.toList res))
+    trace (T.pack $ printf "line %d: %s" (sourceLine pos) (take 60 $ show $ B.toList res))
   return res
 
 blockElements :: PandocMonad m => TikiWikiParser m B.Blocks
@@ -126,13 +115,13 @@
   skipSpaces
   content <- B.trimInlines . mconcat <$> manyTill inline newline
   attr <- registerHeader nullAttr content
-  return $B.headerWith attr level content
+  return $ B.headerWith attr level content
 
 tableRow :: PandocMonad m => TikiWikiParser m [B.Blocks]
 tableRow = try $ do
 --  row <- sepBy1 (many1Till inline $ oneOf "\n|") (try $ string "|" <* notFollowedBy (oneOf "|\n"))
 --  return $ map (B.plain . mconcat) row
-  row <- sepBy1 (many1 (noneOf "\n|") >>= parseColumn) (try $ string "|" <* notFollowedBy (oneOf "|\n"))
+  row <- sepBy1 (many1 (noneOf "\n|") >>= parseColumn . T.pack) (try $ string "|" <* notFollowedBy (oneOf "|\n"))
   return $ map B.plain row
   where
     parseColumn x = do
@@ -164,11 +153,12 @@
   string "||"
   newline
   -- return $ B.simpleTable (headers rows) $ trace ("rows: " ++ (show rows)) rows
-  return $B.simpleTable (headers rows) rows
+  return $ B.simpleTable (headers rows) rows
   where
-    -- The headers are as many empty srings as the number of columns
-    -- in the first row
-    headers rows = map (B.plain . B.str) $replicate (length $ rows !! 0) ""
+    -- The headers are as many empty strings as the number of columns
+-- in the first row
+    headers [] = []
+    headers (r:_) = replicate (length r) ((B.plain . B.str) "")
 
 para :: PandocMonad m => TikiWikiParser m B.Blocks
 para =  fmap (result . mconcat) ( many1Till inline endOfParaElement)
@@ -236,10 +226,9 @@
 -- fixListNesting nestall | trace ("\n\nfixListNesting: " ++ (show nestall)) False = undefined
 -- fixListNesting nestall@(first:second:rest) =
 fixListNesting (first:second:rest) =
-  let secondBlock = head $ B.toList second in
-    case secondBlock of
-      BulletList _ -> fixListNesting $ (mappend (recurseOnList first) (recurseOnList second)) : rest
-      OrderedList _ _ -> fixListNesting $ (mappend (recurseOnList first) (recurseOnList second)) : rest
+    case B.toList second of
+      (BulletList _ : _) -> fixListNesting $ mappend (recurseOnList first) (recurseOnList second) : rest
+      (OrderedList _ _ : _) -> fixListNesting $ mappend (recurseOnList first) (recurseOnList second) : rest
       _ -> recurseOnList first : fixListNesting (second:rest)
 
 -- This function walks the Block structure for fixListNesting,
@@ -249,10 +238,9 @@
 -- recurseOnList item | trace ("rOL: " ++ (show $ length $ B.toList item) ++ ", " ++ (show $ B.toList item)) False = undefined
 recurseOnList items
   | length (B.toList items) == 1 =
-    let itemBlock = head $ B.toList items in
-      case itemBlock of
-        BulletList listItems -> B.bulletList $ fixListNesting $ map B.fromList listItems
-        OrderedList _ listItems -> B.orderedList $ fixListNesting $ map B.fromList listItems
+      case B.toList items of
+        (BulletList listItems : _) -> B.bulletList $ fixListNesting $ map B.fromList listItems
+        (OrderedList _ listItems : _) -> B.orderedList $ fixListNesting $ map B.fromList listItems
         _ -> items
 
   -- The otherwise works because we constructed the blocks, and we
@@ -285,7 +273,7 @@
 -- level and of the same type.
 splitListNesting :: ListNesting -> (ListNesting, B.Blocks) -> Bool
 splitListNesting ln1 (ln2, _)
-  | (lnnest ln1) < (lnnest ln2) =
+  | lnnest ln1 < lnnest ln2 =
   True
   | ln1 == ln2 =
   True
@@ -319,7 +307,7 @@
 bulletItem :: PandocMonad m => TikiWikiParser m (ListNesting, B.Blocks)
 bulletItem = try $ do
   prefix <- many1 $ char '*'
-  many1 $ char ' '
+  many $ char ' '
   content <- listItemLine (length prefix)
   return (LN Bullet (length prefix), B.plain content)
 
@@ -331,7 +319,7 @@
 numberedItem :: PandocMonad m => TikiWikiParser m (ListNesting, B.Blocks)
 numberedItem = try $ do
   prefix <- many1 $ char '#'
-  many1 $ char ' '
+  many $ char ' '
   content <- listItemLine (length prefix)
   return (LN Numbered (length prefix), B.plain content)
 
@@ -341,15 +329,15 @@
     lineContent = do
       content <- anyLine
       continuation <- optionMaybe listContinuation
-      return $ filterSpaces content ++ "\n" ++ maybe "" id continuation
-    filterSpaces = reverse . dropWhile (== ' ') . reverse
+      return $ filterSpaces content <> "\n" <> Data.Maybe.fromMaybe "" continuation
+    filterSpaces = T.dropWhileEnd (== ' ')
     listContinuation = string (replicate nest '+') >> lineContent
     parseContent x = do
       parsed <- parseFromString (many1 inline) x
-      return $ mconcat parsed
+      return $ mconcat $ dropWhileEnd (== B.space) parsed
 
 -- Turn the CODE macro attributes into Pandoc code block attributes.
-mungeAttrs :: [(String, String)] -> (String, [String], [(String, String)])
+mungeAttrs :: [(Text, Text)] -> (Text, [Text], [(Text, Text)])
 mungeAttrs rawAttrs = ("", classes, rawAttrs)
   where
     -- "colors" is TikiWiki CODE macro for "name of language to do
@@ -369,7 +357,7 @@
   string "{CODE("
   rawAttrs <- macroAttrs
   string ")}"
-  body <- manyTill anyChar (try (string "{CODE}"))
+  body <- T.pack <$> manyTill anyChar (try (string "{CODE}"))
   newline
   if not (null rawAttrs)
     then
@@ -410,7 +398,7 @@
                 ] <?> "inline"
 
 whitespace :: PandocMonad m => TikiWikiParser m B.Inlines
-whitespace = (lb <|> regsp)
+whitespace = lb <|> regsp
   where lb = try $ skipMany spaceChar >> linebreak >> return B.space
         regsp = try $ skipMany1 spaceChar >> return B.space
 
@@ -427,9 +415,9 @@
 htmlComment :: PandocMonad m => TikiWikiParser m B.Inlines
 htmlComment = try $ do
   string "~hc~"
-  inner <- many1 $ noneOf "~"
+  inner <- fmap T.pack $ many1 $ noneOf "~"
   string "~/hc~"
-  return $ B.str $ " NOT SUPPORTED: ~hc~ (html comment opener) BEGIN: " ++ inner ++ " ~/hc~ :END "
+  return $ B.str $ " NOT SUPPORTED: ~hc~ (html comment opener) BEGIN: " <> inner <> " ~/hc~ :END "
 
 linebreak :: PandocMonad m => TikiWikiParser m B.Inlines
 linebreak = newline >> notFollowedBy newline >> (lastNewline <|> innerNewline)
@@ -451,7 +439,7 @@
 nestedInlines end = innerSpace <|> nestedInline
   where
     innerSpace   = try $ whitespace <* notFollowedBy end
-    nestedInline = notFollowedBy whitespace >> nested inline
+    nestedInline = notFollowedBy whitespace >> inline
 
 -- {img attId="39" imalign="right" link="http://info.tikiwiki.org" alt="Panama Hat"}
 --
@@ -468,15 +456,15 @@
   let title = fromMaybe src $ lookup "desc" rawAttrs
   let alt = fromMaybe title $ lookup "alt" rawAttrs
   let classes = map fst $ filter (\(_,b) -> b == "" || b == "y") rawAttrs
-  if not (null src)
+  if not (T.null src)
     then
       return $ B.imageWith ("", classes, rawAttrs) src title (B.str alt)
     else
-      return $ B.str $ " NOT SUPPORTED: image without src attribute BEGIN: {img " ++ printAttrs rawAttrs ++ "} :END "
+      return $ B.str $ " NOT SUPPORTED: image without src attribute BEGIN: {img " <> printAttrs rawAttrs <> "} :END "
   where
-    printAttrs attrs = unwords $ map (\(a, b) -> a ++ "=\"" ++ b ++ "\"") attrs
+    printAttrs attrs = T.unwords $ map (\(a, b) -> a <> "=\"" <> b <> "\"") attrs
 
-imageAttr :: PandocMonad m => TikiWikiParser m (String, String)
+imageAttr :: PandocMonad m => TikiWikiParser m (Text, Text)
 imageAttr = try $ do
   key <- many1 (noneOf "=} \t\n")
   char '='
@@ -484,7 +472,7 @@
   value <- many1 (noneOf "}\"\n")
   optional $ char '"'
   optional $ char ','
-  return (key, value)
+  return (T.pack key, T.pack value)
 
 
 -- __strong__
@@ -499,54 +487,52 @@
 escapedChar :: PandocMonad m => TikiWikiParser m B.Inlines
 escapedChar = try $ do
   string "~"
-  inner <- many1 $ oneOf "0123456789"
+  mNumber <- safeRead . T.pack <$> many1 digit
   string "~"
-  return $B.str [(toEnum (read inner :: Int)) :: Char]
+  return $ B.str $
+    case mNumber of
+      Just number -> T.singleton $ toEnum (number :: Int)
+      Nothing     -> ""
 
 -- UNSUPPORTED, as there doesn't seem to be any facility in calibre
 -- for this
 centered :: PandocMonad m => TikiWikiParser m B.Inlines
 centered = try $ do
   string "::"
-  inner <- many1 $ noneOf ":\n"
+  inner <- fmap T.pack $ many1 $ noneOf ":\n"
   string "::"
-  return $ B.str $ " NOT SUPPORTED: :: (centered) BEGIN: ::" ++ inner ++ ":: :END "
+  return $ B.str $ " NOT SUPPORTED: :: (centered) BEGIN: ::" <> inner <> ":: :END "
 
 -- UNSUPPORTED, as there doesn't seem to be any facility in calibre
 -- for this
 colored :: PandocMonad m => TikiWikiParser m B.Inlines
 colored = try $ do
   string "~~"
-  inner <- many1 $ noneOf "~\n"
+  inner <- fmap T.pack $ many1 $ noneOf "~\n"
   string "~~"
-  return $ B.str $ " NOT SUPPORTED: ~~ (colored) BEGIN: ~~" ++ inner ++ "~~ :END "
+  return $ B.str $ " NOT SUPPORTED: ~~ (colored) BEGIN: ~~" <> inner <> "~~ :END "
 
--- UNSUPPORTED, as there doesn't seem to be any facility in calibre
--- for this
+-- ===underlined===
 underlined :: PandocMonad m => TikiWikiParser m B.Inlines
-underlined = try $ do
-  string "==="
-  inner <- many1 $ noneOf "=\n"
-  string "==="
-  return $ B.str $ " NOT SUPPORTED: ==== (underlined) BEGIN: ===" ++ inner ++ "=== :END "
+underlined = try $ B.underline <$> enclosed (string "===") nestedInlines
 
 -- UNSUPPORTED, as there doesn't seem to be any facility in calibre
 -- for this
 boxed :: PandocMonad m => TikiWikiParser m B.Inlines
 boxed = try $ do
   string "^"
-  inner <- many1 $ noneOf "^\n"
+  inner <- fmap T.pack $ many1 $ noneOf "^\n"
   string "^"
-  return $ B.str $ " NOT SUPPORTED: ^ (boxed) BEGIN: ^" ++ inner ++ "^ :END "
+  return $ B.str $ " NOT SUPPORTED: ^ (boxed) BEGIN: ^" <> inner <> "^ :END "
 
 -- --text--
 strikeout :: PandocMonad m => TikiWikiParser m B.Inlines
 strikeout = try $ fmap B.strikeout (enclosed (string "--") nestedInlines)
 
-nestedString :: (Show a, PandocMonad m) => TikiWikiParser m a -> TikiWikiParser m String
-nestedString end = innerSpace <|> count 1 nonspaceChar
+nestedString :: (Show a, PandocMonad m) => TikiWikiParser m a -> TikiWikiParser m Text
+nestedString end = innerSpace <|> countChar 1 nonspaceChar
   where
-    innerSpace = try $ many1 spaceChar <* notFollowedBy end
+    innerSpace = try $ T.pack <$> many1 spaceChar <* notFollowedBy end
 
 breakChars :: PandocMonad m => TikiWikiParser m B.Inlines
 breakChars = try $ string "%%%" >> return B.linebreak
@@ -560,7 +546,7 @@
   string "{SUP("
   manyTill anyChar (string ")}")
   body <- manyTill anyChar (string "{SUP}")
-  return $ B.superscript $ B.text body
+  return $ B.superscript $ B.text $ T.pack body
 
 -- subscript: baz{TAG(tag=>sub)}sub{TAG}qux / qux{SUB()}sub2{SUB}qux
 subTag :: PandocMonad m => TikiWikiParser m B.Inlines
@@ -571,22 +557,22 @@
   string "{SUB("
   manyTill anyChar (string ")}")
   body <- manyTill anyChar (string "{SUB}")
-  return $ B.subscript $ B.text body
+  return $ B.subscript $ B.text $ T.pack body
 
 -- -+text+-
 code :: PandocMonad m => TikiWikiParser m B.Inlines
 code = try $  fmap (B.code . fromEntities) ( between (string "-+") (string "+-") nestedString)
 
-macroAttr :: PandocMonad m => TikiWikiParser m (String, String)
+macroAttr :: PandocMonad m => TikiWikiParser m (Text, Text)
 macroAttr = try $ do
   key <- many1 (noneOf "=)")
   char '='
   optional $ char '"'
   value <- many1 (noneOf " )\"")
   optional $ char '"'
-  return (key, value)
+  return (T.pack key, T.pack value)
 
-macroAttrs :: PandocMonad m => TikiWikiParser m [(String, String)]
+macroAttrs :: PandocMonad m => TikiWikiParser m [(Text, Text)]
 macroAttrs = try $ sepEndBy macroAttr spaces
 
 -- ~np~ __not bold__ ~/np~
@@ -594,13 +580,13 @@
 noparse = try $ do
   string "~np~"
   body <- manyTill anyChar (string "~/np~")
-  return $ B.str body
+  return $ B.str $ T.pack body
 
 str :: PandocMonad m => TikiWikiParser m B.Inlines
-str = fmap B.str (many1 alphaNum <|> count 1 characterReference)
+str = fmap B.str (T.pack <$> many1 alphaNum <|> characterReference)
 
 symbol :: PandocMonad m => TikiWikiParser m B.Inlines
-symbol = fmap B.str (count 1 nonspaceChar)
+symbol = fmap B.str (countChar 1 nonspaceChar)
 
 -- [[not a link]
 notExternalLink :: PandocMonad m => TikiWikiParser m B.Inlines
@@ -608,14 +594,14 @@
   start <- string "[["
   body <- many (noneOf "\n[]")
   end <- string "]"
-  return $ B.text (start ++ body ++ end)
+  return $ B.text $ T.pack $ start ++ body ++ end
 
 -- [http://www.somesite.org url|Some Site title]
 -- ((internal link))
 --
 -- The ((...)) wiki links and [...] external links are handled
 -- exactly the same; this abstracts that out
-makeLink :: PandocMonad m => String -> String -> String -> TikiWikiParser m B.Inlines
+makeLink :: PandocMonad m => Text -> Text -> Text -> TikiWikiParser m B.Inlines
 makeLink start middle end = try $ do
   st <- getState
   guard $ stateAllowLinks st
@@ -623,15 +609,15 @@
   (url, title, anchor) <- wikiLinkText start middle end
   parsedTitle <- parseFromString (many1 inline) title
   setState $ st{ stateAllowLinks = True }
-  return $ B.link (url++anchor) "" $mconcat parsedTitle
+  return $ B.link (url <> anchor) "" $ mconcat parsedTitle
 
-wikiLinkText :: PandocMonad m => String -> String -> String -> TikiWikiParser m (String, String, String)
+wikiLinkText :: PandocMonad m => Text -> Text -> Text -> TikiWikiParser m (Text, Text, Text)
 wikiLinkText start middle end = do
-  string start
-  url <- many1 (noneOf $ middle ++ "\n")
+  string (T.unpack start)
+  url <- T.pack <$> many1 (noneOf $ T.unpack middle ++ "\n")
   seg1 <- option url linkContent
   seg2 <- option "" linkContent
-  string end
+  string (T.unpack end)
   if seg2 /= ""
     then
       return (url, seg2, seg1)
@@ -640,7 +626,7 @@
   where
     linkContent      = do
       char '|'
-      many (noneOf middle)
+      T.pack <$> many (noneOf $ T.unpack middle)
 
 externalLink :: PandocMonad m => TikiWikiParser m B.Inlines
 externalLink = makeLink "[" "]|" "]"
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,21 +1,5 @@
-{-
-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
--}
-
+{-# LANGUAGE OverloadedStrings #-}
+{-# LANGUAGE LambdaCase #-}
 {- |
    Module      : Text.Pandoc.Readers.Txt2Tags
    Copyright   : Copyright (C) 2014 Matthew Pickering
@@ -34,32 +18,31 @@
 import Control.Monad (guard, void, when)
 import Control.Monad.Except (catchError, throwError)
 import Control.Monad.Reader (Reader, asks, runReader)
-import Data.Char (toLower)
 import Data.Default
-import Data.List (intercalate, intersperse, transpose)
+import Data.List (intercalate, transpose)
+import Data.List.NonEmpty (nonEmpty)
 import Data.Maybe (fromMaybe)
-import Data.Monoid ((<>))
 import Data.Text (Text)
 import qualified Data.Text as T
 import Data.Time.Format (formatTime)
 import Text.Pandoc.Builder (Blocks, Inlines, trimInlines)
 import qualified Text.Pandoc.Builder as B
-import Text.Pandoc.Class (PandocMonad)
-import qualified Text.Pandoc.Class as P
-import Text.Pandoc.Compat.Time (defaultTimeLocale)
+import Text.Pandoc.Class.PandocMonad (PandocMonad)
+import qualified Text.Pandoc.Class.PandocMonad as P
+import Data.Time (defaultTimeLocale)
 import Text.Pandoc.Definition
 import Text.Pandoc.Options
 import Text.Pandoc.Parsing hiding (space, spaces, uri)
-import Text.Pandoc.Shared (compactify, compactifyDL, crFilter, escapeURI,
-                           underlineSpan)
+import Text.Pandoc.Shared (compactify, compactifyDL)
+import Text.Pandoc.URI (escapeURI)
 
-type T2T = ParserT String ParserState (Reader T2TMeta)
+type T2T = ParsecT Sources ParserState (Reader T2TMeta)
 
 -- | An object for the T2T macros meta information
 -- the contents of each field is simply substituted verbatim into the file
 data  T2TMeta = T2TMeta {
-                 date    :: String -- ^ Current date
-               , mtime   :: String -- ^ Last modification time of infile
+                 date    :: Text -- ^ Current date
+               , mtime   :: Text -- ^ Last modification time of infile
                , infile  :: FilePath -- ^ Input file
                , outfile :: FilePath -- ^ Output file
                } deriving Show
@@ -73,32 +56,35 @@
     inps <- P.getInputFiles
     outp <- fromMaybe "" <$> P.getOutputFile
     curDate <- formatTime defaultTimeLocale "%F" <$> P.getZonedTime
-    let getModTime = fmap (formatTime defaultTimeLocale "%T") .
-                       P.getModificationTime
-    curMtime <- case inps of
-                  [] -> formatTime defaultTimeLocale "%T" <$> P.getZonedTime
-                  _ -> catchError
-                        (maximum <$> mapM getModTime inps)
-                        (const (return ""))
-    return $ T2TMeta curDate curMtime (intercalate ", " inps) outp
+    curMtime <- catchError
+                 (mapM P.getModificationTime inps >>=
+                   (\case
+                       Nothing ->
+                         formatTime defaultTimeLocale "%T" <$> P.getZonedTime
+                       Just ts -> return $
+                         formatTime defaultTimeLocale "%T" $ maximum ts)
+                    . nonEmpty)
+                (const (return ""))
+    return $ T2TMeta (T.pack curDate) (T.pack curMtime)
+                     (intercalate ", " inps) outp
 
 -- | Read Txt2Tags from an input string returning a Pandoc document
-readTxt2Tags :: PandocMonad m
+readTxt2Tags :: (PandocMonad m, ToSources a)
              => ReaderOptions
-             -> Text
+             -> a
              -> m Pandoc
 readTxt2Tags opts s = do
+  let sources = ensureFinalNewlines 2 (toSources s)
   meta <- getT2TMeta
   let parsed = flip runReader meta $
-        readWithM parseT2T (def {stateOptions = opts}) $
-        T.unpack (crFilter s) ++ "\n\n"
+        readWithM parseT2T (def {stateOptions = opts}) sources
   case parsed of
     Right result -> return result
     Left e       -> throwError e
 
 -- | Read Txt2Tags (ignoring all macros) from an input string returning
 -- a Pandoc document
--- readTxt2TagsNoMacros :: PandocMonad m => ReaderOptions -> String -> m Pandoc
+-- readTxt2TagsNoMacros :: PandocMonad m => ReaderOptions -> Text -> m Pandoc
 -- readTxt2TagsNoMacros = readTxt2Tags
 
 parseT2T :: T2T Pandoc
@@ -123,7 +109,7 @@
 header :: T2T ()
 header = titleline >> authorline >> dateline
 
-headerline :: B.ToMetaValue a => String -> T2T a -> T2T ()
+headerline :: B.ToMetaValue a => Text -> T2T a -> T2T ()
 headerline field p = (() <$ try blankline)
                         <|> (p >>= updateState . B.setMeta field)
 
@@ -140,15 +126,15 @@
 dateline :: T2T ()
 dateline = headerline "date" (trimInlines . mconcat <$> manyTill inline newline)
 
-type Keyword = String
-type Value = String
+type Keyword = Text
+type Value = Text
 
 setting :: T2T (Keyword, Value)
 setting = do
   string "%!"
-  keyword <- ignoreSpacesCap (many1 alphaNum)
+  keyword <- ignoreSpacesCap (many1Char alphaNum)
   char ':'
-  value <- ignoreSpacesCap (manyTill anyChar newline)
+  value <- ignoreSpacesCap (manyTillChar anyChar newline)
   return (keyword, value)
 
 -- Blocks
@@ -180,10 +166,10 @@
   spaces
   level <- length <$> many1 (char c)
   guard (level <= 5) -- Max header level 5
-  heading <- manyTill (noneOf "\n\r") (count level (char c))
+  heading <- manyTillChar (noneOf "\n\r") (count level (char c))
   label <- optionMaybe (enclosed (char '[') (char ']') (alphaNum <|> oneOf "_-"))
   many spaceChar *> newline
-  let attr = maybe nullAttr (\x -> (x, [], [])) label
+  let attr = maybe nullAttr (\x -> (T.pack x, [], [])) label
   return $ B.headerWith attr level (trimInlines $ B.text heading)
 
 para :: T2T Blocks
@@ -197,7 +183,7 @@
 commentBlock :: T2T Blocks
 commentBlock = try (blockMarkupArea anyLine (const mempty) "%%%") <|> comment
 
--- Seperator and Strong line treated the same
+-- Separator and Strong line treated the same
 hrule :: T2T Blocks
 hrule = try $ do
   spaces
@@ -209,7 +195,7 @@
 quote = try $ do
   lookAhead tab
   rawQuote <-  many1 (tab *> optional spaces *> anyLine)
-  contents <- parseFromString' parseBlocks (intercalate "\n" rawQuote ++ "\n\n")
+  contents <- parseFromString' parseBlocks (T.intercalate "\n" rawQuote <> "\n\n")
   return $ B.blockQuote contents
 
 commentLine :: T2T Inlines
@@ -260,17 +246,17 @@
   markerLength <- try start
   firstLine <- anyLineNewline
   blank <- option "" ("\n" <$ blankline)
-  rest <- concat <$> many (listContinuation markerLength)
-  parseFromString' end $ firstLine ++ blank ++ rest
+  rest <- T.concat <$> many (listContinuation markerLength)
+  parseFromString' end $ firstLine <> blank <> rest
 
 -- continuation of a list item - indented and separated by blankline or endline.
 -- Note: nested lists are parsed as continuations.
 listContinuation :: Int
-                 -> T2T String
+                 -> T2T Text
 listContinuation markerLength = try $
   notFollowedBy' (blankline >> blankline)
-  *> (mappend <$> (concat <$> many1 listLine)
-              <*> many blankline)
+  *> (mappend <$> (T.concat <$> many1 listLine)
+              <*> manyChar blankline)
  where listLine = try $ indentWith markerLength *> anyLineNewline
 
 -- Table
@@ -281,23 +267,28 @@
   rows <- many1 (many commentLine *> tableRow)
   let columns = transpose rows
   let ncolumns = length columns
-  let aligns = map (foldr1 findAlign . map fst) columns
+  let aligns = map (fromMaybe AlignDefault . foldr findAlign Nothing) columns
   let rows' = map (map snd) rows
-  let size = maximum (map length rows')
+  let size = maybe 0 maximum $ nonEmpty $ map length rows'
   let rowsPadded = map (pad size) rows'
   let headerPadded = if null tableHeader then mempty else pad size tableHeader
-  return $ B.table mempty
-                    (zip aligns (replicate ncolumns 0.0))
-                      headerPadded rowsPadded
+  let toRow = Row nullAttr . map B.simpleCell
+      toHeaderRow l = [toRow l | not (null l)]
+  return $ B.table B.emptyCaption
+                    (zip aligns (replicate ncolumns ColWidthDefault))
+                      (TableHead nullAttr $ toHeaderRow headerPadded)
+                      [TableBody nullAttr 0 [] $ map toRow rowsPadded]
+                      (TableFoot nullAttr [])
 
 pad :: (Monoid a) => Int -> [a] -> [a]
 pad n xs = xs ++ replicate (n - length xs) mempty
 
 
-findAlign :: Alignment -> Alignment -> Alignment
-findAlign x y
-  | x == y = x
-  | otherwise = AlignDefault
+findAlign :: (Alignment, a) -> Maybe Alignment -> Maybe Alignment
+findAlign (x,_) (Just y)
+  | x == y = Just x
+  | otherwise = Just AlignDefault
+findAlign (x,_) Nothing = Just x
 
 headerRow :: T2T [(Alignment, Blocks)]
 headerRow = genericRow (string "||")
@@ -344,16 +335,16 @@
 
 -- Generic
 
-genericBlock :: Monoid a => T2T a -> (a -> Blocks) -> String -> T2T Blocks
+genericBlock :: Monoid a => T2T a -> (a -> Blocks) -> Text -> T2T Blocks
 genericBlock p f s = blockMarkupArea p f s <|> blockMarkupLine p f s
 
-blockMarkupArea :: Monoid a => T2T a -> (a -> Blocks) -> String -> T2T Blocks
+blockMarkupArea :: Monoid a => T2T a -> (a -> Blocks) -> Text -> T2T Blocks
 blockMarkupArea p f s = try (do
-  string s *> blankline
-  f . mconcat <$> manyTill p (eof <|> void (string s *> blankline)))
+  textStr s *> blankline
+  f . mconcat <$> manyTill p (eof <|> void (textStr s *> blankline)))
 
-blockMarkupLine :: T2T a -> (a -> Blocks) -> String -> T2T Blocks
-blockMarkupLine p f s = try (f <$> (string s *> space *> p))
+blockMarkupLine :: T2T a -> (a -> Blocks) -> Text -> T2T Blocks
+blockMarkupLine p f s = try (f <$> (textStr s *> space *> p))
 
 -- Can be in either block or inline position
 comment :: Monoid a => T2T a
@@ -393,7 +384,7 @@
 bold = inlineMarkup inline B.strong '*' B.str
 
 underline :: T2T Inlines
-underline = inlineMarkup inline underlineSpan '_' B.str
+underline = inlineMarkup inline B.underline '_' B.str
 
 strike :: T2T Inlines
 strike = inlineMarkup inline B.strikeout '-' B.str
@@ -402,17 +393,17 @@
 italic = inlineMarkup inline B.emph '/' B.str
 
 code :: T2T Inlines
-code = inlineMarkup ((:[]) <$> anyChar) B.code '`' id
+code = inlineMarkup (T.singleton <$> anyChar) B.code '`' id
 
 raw :: T2T Inlines
-raw = inlineMarkup ((:[]) <$> anyChar) B.text '"' id
+raw = inlineMarkup (T.singleton <$> anyChar) B.text '"' id
 
 tagged :: T2T Inlines
 tagged = do
   target <- getTarget
-  inlineMarkup ((:[]) <$> anyChar) (B.rawInline target) '\'' id
+  inlineMarkup (T.singleton <$> anyChar) (B.rawInline target) '\'' id
 
--- Parser for markup indicated by a double character.
+-- Parsec for markup indicated by a double character.
 -- Inline markup is greedy and glued
 -- Greedy meaning ***a*** = Bold [Str "*a*"]
 -- Glued meaning that markup must be tight to content
@@ -421,33 +412,33 @@
              => T2T a -- Content parser
              -> (a -> Inlines) -- Constructor
              -> Char -- Fence
-             -> (String -> a) -- Special Case to handle ******
+             -> (Text -> a) -- Special Case to handle ******
              -> T2T Inlines
 inlineMarkup p f c special = try $ do
-  start <- many1 (char c)
-  let l = length start
+  start <- many1Char (char c)
+  let l = T.length start
   guard (l >= 2)
   when (l == 2) (void $ notFollowedBy space)
   -- We must make sure that there is no space before the start of the
   -- closing tags
-  body <-  optionMaybe (try $ manyTill (noneOf "\n\r")
+  body <-  optionMaybe (try $ manyTillChar (noneOf "\n\r")
                 (try $ lookAhead (noneOf " " >> string [c,c] )))
   case body of
     Just middle -> do
       lastChar <- anyChar
-      end <- many1 (char c)
+      end <- many1Char (char c)
       let parser inp = parseFromString' (mconcat <$> many p) inp
-      let start' = case drop 2 start of
+      let start' = case T.drop 2 start of
                           "" -> mempty
                           xs -> special xs
-      body' <- parser (middle ++ [lastChar])
-      let end' = case drop 2 end of
+      body' <- parser (middle <> T.singleton lastChar)
+      let end' = case T.drop 2 end of
                           "" -> mempty
                           xs -> special xs
-      return $ f (start' <> body' <> end')
+      return $ f (start' `mappend` body' `mappend` end')
     Nothing -> do -- Either bad or case such as *****
       guard (l >= 5)
-      let body' = replicate (l - 4) c
+      let body' = T.replicate (l - 4) $ T.singleton c
       return $ f (special body')
 
 link :: T2T Inlines
@@ -458,12 +449,12 @@
 titleLink = try $ do
   char '['
   notFollowedBy space
-  tokens <- sepBy1 (many $ noneOf " ]") space
+  tokens <- sepBy1 (manyChar $ noneOf " ]") space
   guard (length tokens >= 2)
   char ']'
   let link' = last tokens
-  guard $ not $ null link'
-  let tit = concat (intersperse " " (init tokens))
+  guard $ not $ T.null link'
+  let tit = T.unwords (init tokens)
   return $ B.link link' "" (B.text tit)
 
 -- Link with image
@@ -472,7 +463,7 @@
   char '['
   body <- image
   many1 space
-  l <- manyTill (noneOf "\n\r ") (char ']')
+  l <- manyTillChar (noneOf "\n\r ") (char ']')
   return (B.link l "" body)
 
 macro :: T2T Inlines
@@ -480,18 +471,38 @@
   name <- string "%%" *> oneOfStringsCI (map fst commands)
   optional (try $ enclosed (char '(') (char ')') anyChar)
   lookAhead (spaceChar <|> oneOf specialChars <|> newline)
-  maybe (return mempty) (\f -> B.str <$> asks f) (lookup name commands)
+  maybe (return mempty) (\f -> asks (B.str . f)) (lookup name commands)
   where
     commands = [ ("date", date), ("mtime", mtime)
-               , ("infile", infile), ("outfile", outfile)]
+               , ("infile", T.pack . infile), ("outfile", T.pack . outfile)]
 
 -- raw URLs in text are automatically linked
 url :: T2T Inlines
 url = try $ do
-  (rawUrl, escapedUrl) <- try uri <|> emailAddress
+  (rawUrl, escapedUrl) <- try uri <|> emailAddress'
   return $ B.link rawUrl "" (B.str escapedUrl)
 
-uri :: T2T (String, String)
+emailAddress' :: T2T (Text, Text)
+emailAddress' = do
+  (base, mailURI) <- emailAddress
+  query <- option "" emailQuery
+  return (base <> query, mailURI <> query)
+
+emailQuery :: T2T Text
+emailQuery = do
+  char '?'
+  parts <- kv `sepBy1` (char '&')
+  return $ "?" <> T.intercalate "&" parts
+
+kv :: T2T Text
+kv = do
+  k <- T.pack <$> many1 alphaNum
+  char '='
+  let vchar = alphaNum <|> try (oneOf "%._/~:,=$@&+-;*" <* lookAhead alphaNum)
+  v <- T.pack <$> many1 vchar
+  return (k <> "=" <> v)
+
+uri :: T2T (Text, Text)
 uri = try $ do
   address <- t2tURI
   return (address, escapeURI address)
@@ -503,25 +514,25 @@
 --isT2TURI (parse t2tURI "" -> Right _) = True
 --isT2TURI _ = False
 
-t2tURI :: T2T String
+t2tURI :: T2T Text
 t2tURI = do
-  start <- try ((++) <$> proto <*> urlLogin) <|> guess
-  domain <- many1 chars
-  sep <- many (char '/')
-  form' <- option mempty ((:) <$> char '?' <*> many1 form)
-  anchor' <- option mempty ((:) <$> char '#' <*> many anchor)
-  return (start ++ domain ++ sep ++ form' ++ anchor')
+  start <- try ((<>) <$> proto <*> urlLogin) <|> guess
+  domain <- many1Char chars
+  sep <- manyChar (char '/')
+  form' <- option mempty (T.cons <$> char '?' <*> many1Char form)
+  anchor' <- option mempty (T.cons <$> char '#' <*> manyChar anchor)
+  return (start <> domain <> sep <> form' <> anchor')
   where
     protos = ["http", "https", "ftp", "telnet", "gopher", "wais"]
-    proto = (++) <$> oneOfStrings protos <*> string "://"
-    guess = (++) <$> (((++) <$> stringAnyCase "www" <*> option mempty ((:[]) <$> oneOf "23"))
-              <|> stringAnyCase "ftp") <*> ((:[]) <$> char '.')
+    proto = (<>) <$> oneOfStrings protos <*> textStr "://"
+    guess = (<>) <$> (((<>) <$> stringAnyCase "www" <*> option mempty (T.singleton <$> oneOf "23"))
+              <|> stringAnyCase "ftp") <*> (T.singleton <$> char '.')
     login = alphaNum <|> oneOf "_.-"
-    pass = many (noneOf " @")
+    pass = manyChar (noneOf " @")
     chars = alphaNum <|> oneOf "%._/~:,=$@&+-"
     anchor = alphaNum <|> oneOf "%._0"
     form = chars <|> oneOf ";*"
-    urlLogin = option mempty $ try ((\x y z -> x ++ y ++ [z]) <$> many1 login <*> option mempty ((:) <$> char ':' <*> pass) <*> char '@')
+    urlLogin = option mempty $ try ((\x y z -> x <> y <> T.singleton z) <$> many1Char login <*> option mempty (T.cons <$> char ':' <*> pass) <*> char '@')
 
 
 image :: T2T Inlines
@@ -529,13 +540,12 @@
   -- List taken from txt2tags source
   let extensions = [".jpg", ".jpeg", ".gif", ".png", ".eps", ".bmp"]
   char '['
-  path <- manyTill (noneOf "\n\t\r ") (try $ lookAhead (oneOfStrings extensions))
-  ext <- oneOfStrings extensions
+  (path, ext) <- manyUntilChar (noneOf "\n\t\r ") (oneOfStrings extensions)
   char ']'
-  return $ B.image (path ++ ext) "" mempty
+  return $ B.image (path <> ext) "" mempty
 
 -- Characters used in markup
-specialChars :: String
+specialChars :: [Char]
 specialChars = "%*-_/|:+;"
 
 tab :: T2T Char
@@ -544,8 +554,8 @@
 space :: T2T Char
 space = char ' '
 
-spaces :: T2T String
-spaces = many space
+spaces :: T2T Text
+spaces = manyChar space
 
 endline :: T2T Inlines
 endline = try $ do
@@ -562,24 +572,26 @@
   return B.softbreak
 
 str :: T2T Inlines
-str = try $ B.str <$> many1 (noneOf $ specialChars ++ "\n\r ")
+str = try $ B.str <$> many1Char (noneOf $ specialChars ++ "\n\r ")
 
 whitespace :: T2T Inlines
 whitespace = try $ B.space <$ spaceChar
 
 symbol :: T2T Inlines
-symbol = B.str . (:[]) <$> oneOf specialChars
+symbol = B.str . T.singleton <$> oneOf specialChars
 
 -- Utility
 
-getTarget :: T2T String
+getTarget :: T2T Text
 getTarget = do
   mv <- lookupMeta "target" . stateMeta <$> getState
-  let MetaString target = fromMaybe (MetaString "html") mv
-  return target
+  return $ case mv of
+              Just (MetaString target)        -> target
+              Just (MetaInlines [Str target]) -> target
+              _                               -> "html"
 
 atStart :: T2T ()
-atStart = (sourceColumn <$> getPosition) >>= guard . (== 1)
+atStart = getPosition >>= guard . (== 1) . sourceColumn
 
-ignoreSpacesCap :: T2T String -> T2T String
-ignoreSpacesCap p = map toLower <$> (spaces *> p <* spaces)
+ignoreSpacesCap :: T2T Text -> T2T Text
+ignoreSpacesCap p = T.toLower <$> (spaces *> p <* spaces)
diff --git a/src/Text/Pandoc/Readers/Typst.hs b/src/Text/Pandoc/Readers/Typst.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Readers/Typst.hs
@@ -0,0 +1,781 @@
+{-# LANGUAGE RankNTypes #-}
+{-# LANGUAGE BangPatterns #-}
+{-# LANGUAGE FlexibleInstances #-}
+{-# LANGUAGE UndecidableInstances #-}
+{-# LANGUAGE OverloadedStrings #-}
+{-# LANGUAGE LambdaCase #-}
+{-# LANGUAGE OverloadedLists #-}
+{-# LANGUAGE ScopedTypeVariables #-}
+
+{- |
+   Module      : Text.Pandoc.Readers.Typst
+   Copyright   : Copyright (C) 2023 John MacFarlane
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : John MacFarlane <jgm@berkeley.edu>
+   Stability   : alpha
+   Portability : portable
+
+Reads and evaluates a Typst document as a Pandoc AST.
+-}
+module Text.Pandoc.Readers.Typst
+  ( readTypst
+  )
+where
+
+import Text.Pandoc.Class
+import Text.Pandoc.Sources
+import Text.Pandoc.Options
+import Text.Pandoc.Definition
+import Typst ( parseTypst, evaluateTypst )
+import Text.Pandoc.Error (PandocError(..))
+import Text.Pandoc.Translations (Term(References), translateTerm)
+import Text.Pandoc.Shared (tshow, blocksToInlines)
+import Control.Monad.Except (throwError)
+import Control.Monad (MonadPlus (mplus), void, guard, foldM)
+import Control.Monad.Trans (lift)
+import qualified Data.Foldable as F
+import qualified Data.Map as M
+import Data.Maybe (catMaybes, fromMaybe, isJust)
+import Data.Sequence (Seq)
+import qualified Data.Sequence as Seq
+import qualified Data.Set as Set
+import Data.Text (Text)
+import qualified Data.Text as T
+import qualified Text.Pandoc.Builder as B
+import Text.Pandoc.Walk
+import Text.Parsec
+import Text.TeXMath (writeTeX)
+import Text.TeXMath.Shared (getSpaceChars)
+import Text.Pandoc.Readers.Typst.Math (pMathMany)
+import Text.Pandoc.Readers.Typst.Parsing (pTok, ignored, getField, P,
+                                          PState(..), defaultPState)
+import Typst.Methods (formatNumber, applyPureFunction)
+import Typst.Types
+import qualified Data.Vector as V
+import System.FilePath (takeDirectory)
+import qualified System.FilePath.Windows as Windows
+import qualified System.FilePath.Posix as Posix
+
+-- | Read Typst from an input string and return a Pandoc document.
+readTypst :: (PandocMonad m, ToSources a)
+           => ReaderOptions -> a -> m Pandoc
+readTypst opts inp = do
+  let sources = toSources inp
+  let inputName = case sources of
+        Sources ((pos, _):_) -> sourceName pos
+        _ -> ""
+  case parseTypst inputName (sourcesToText sources) of
+    Left e -> throwError $ PandocParseError $ T.pack $ show e
+    Right parsed -> do
+      let ops = Operations {
+                  loadBytes = readFileStrict,
+                  currentUTCTime = getCurrentTime,
+                  lookupEnvVar = fmap (fmap T.unpack) . lookupEnv . T.pack,
+                  checkExistence = fileExists }
+      res <- evaluateTypst ops (readerTypstInputs opts) inputName parsed
+      case res of
+        Left e -> throwError $ PandocParseError $ tshow e
+        Right content -> do
+          let content' = fixNesting content
+          let labs = findLabels [content']
+          runParserT pPandoc defaultPState{ sLabels = labs }
+            inputName [content'] >>=
+              either (throwError . PandocParseError . T.pack . show) pure
+
+pBlockElt :: PandocMonad m => P m B.Blocks
+pBlockElt = try $ do
+  res <- pTok (\t -> isBlock t || not (isInline t))
+  -- check for following label
+  mbident <- option Nothing $ Just <$> pLab
+  case res of
+    Elt name@(Identifier tname) pos fields -> do
+      case M.lookup name blockHandlers of
+        Nothing -> do
+          ignored ("unknown block element " <> tname <>
+                   " at " <> tshow pos)
+          pure mempty
+        Just handler -> handler pos mbident fields
+    _ -> pure mempty
+
+pInline :: PandocMonad m => P m B.Inlines
+pInline = try $ do
+  res <- pTok (\t -> isInline t || not (isBlock t))
+  case res of
+    Txt t -> pure $ B.text t
+    Lab name -> pure $ B.spanWith (name, [], []) mempty
+    Elt (Identifier tname) _ _
+      | "math." `T.isPrefixOf` tname
+      , tname /= "math.equation" ->
+          B.math . writeTeX <$> pMathMany (Seq.singleton res)
+    Elt name@(Identifier tname) pos fields -> do
+      labs <- sLabels <$> getState
+      labelTarget <- (do result <- getField "target" fields
+                         case result of
+                           VLabel t | t `elem` labs -> pure True
+                           _ -> pure False)
+                  <|> pure False
+      if tname == "ref" && not labelTarget
+         then do
+           -- @foo is a citation unless it links to a lab in the doc:
+           let targetToKey (Identifier "target") = Identifier "key"
+               targetToKey k = k
+           case M.lookup "cite" inlineHandlers of
+             Nothing -> do
+               ignored ("unknown inline element " <> tname <>
+                        " at " <> tshow pos)
+               pure mempty
+             Just handler -> handler pos Nothing (M.mapKeys targetToKey fields)
+         else do
+          case M.lookup name inlineHandlers of
+            Nothing -> do
+              ignored ("unknown inline element " <> tname <>
+                       " at " <> tshow pos)
+              pure mempty
+            Just handler -> handler pos Nothing fields
+
+-- Pull block elements out of inline elements, e.g.
+-- Elt "smallcaps" [ Elt "heading" [..] ] ->
+-- Elt "heading" [ Elt "smallcaps" [..]]. See #11017.
+fixNesting :: Content -> Content
+fixNesting el@(Elt name pos fields)
+  | Just (VContent elts) <- M.lookup "body" fields
+  = let elts' = fmap fixNesting elts
+        fields' = M.insert "body" (VContent elts') fields
+        in if isBlock el
+              then Elt name pos fields'
+              else case getField "body" fields' of
+                        Just ([el'@(Elt name' pos' fields'')] :: Seq Content)
+                          | isBlock el'
+                          , not (isInline el')
+                          , "body" `M.member` fields''
+                          -> Elt name' pos' $
+                               M.insert "body" (VContent
+                                                (Seq.singleton
+                                                  (Elt name pos fields'')))
+                                        fields'
+                        _ -> Elt name pos fields'
+fixNesting x = x
+
+pPandoc :: PandocMonad m => P m B.Pandoc
+pPandoc = do
+  Elt "document" _ fields <- pTok isDocument
+  bs <- getField "body" fields >>= pWithContents pBlocks
+  title <- (getField "title" fields >>= pWithContents pInlines) <|>
+              pure mempty
+  authors <- (getField "author" fields >>=
+                          mapM (pWithContents pInlines) . V.toList) <|>
+             ((:[]) <$> (getField "author" fields >>=
+                           (\x -> guard (not (null x)) *>
+                             pWithContents pInlines x))) <|>
+              pure []
+  date <- (getField "date" fields >>= pWithContents pInlines) <|>
+              pure mempty
+  keywords <- (getField "keywords" fields >>=
+                 mapM (pWithContents pInlines) . V.toList)
+                <|> pure []
+  meta <- sMeta <$> getState
+  let meta' =
+        (if title == mempty || isJust (lookupMeta "title" meta)
+            then id
+            else B.setMeta "title" title) .
+        (if null authors
+            then id
+            else B.setMeta "author" authors) .
+        (if null date
+            then id
+            else B.setMeta "date" date) .
+        (if null keywords
+            then id
+            else B.setMeta "keywords" keywords) $ meta
+  pure $ Pandoc meta' (B.toList bs)
+
+pBlocks :: PandocMonad m => P m B.Blocks
+pBlocks = mconcat <$> many pBlock
+
+pBlock :: PandocMonad m => P m B.Blocks
+pBlock = pPara <|> pBlockElt
+
+pSpace :: PandocMonad m => P m Content
+pSpace = pTok
+      ( \case
+          Txt t | T.all (== ' ') t -> True
+          _ -> False )
+
+pLab :: PandocMonad m => P m Text
+pLab = try $ do
+  optional pSpace
+  Lab t <- pTok
+       ( \case
+           Lab _ -> True
+           _ -> False
+       )
+  pure t
+
+isDocument :: Content -> Bool
+isDocument (Elt "document" _ _) = True
+isDocument _ = False
+
+isBlock :: Content -> Bool
+isBlock (Elt "raw" _ fields) = M.lookup "block" fields == Just (VBoolean True)
+isBlock (Elt name _ _) = name `Set.member` blockKeys
+isBlock Lab{} = True
+isBlock _ = False
+
+isInline :: Content -> Bool
+isInline (Elt "raw" _ fields) = M.lookup "block" fields /= Just (VBoolean True)
+isInline (Elt name _ _) = name `Set.member` inlineKeys
+isInline Lab{} = True
+isInline Txt{} = True
+
+blockKeys :: Set.Set Identifier
+blockKeys = Set.fromList $ M.keys
+  (blockHandlers :: M.Map Identifier
+     (Maybe SourcePos -> Maybe Text ->
+      M.Map Identifier Val -> P PandocPure B.Blocks))
+
+inlineKeys :: Set.Set Identifier
+inlineKeys = Set.fromList $ M.keys
+  (inlineHandlers :: M.Map Identifier
+     (Maybe SourcePos -> Maybe Text ->
+      M.Map Identifier Val -> P PandocPure B.Inlines))
+
+blockHandlers :: PandocMonad m =>
+                   M.Map Identifier
+                   (Maybe SourcePos -> Maybe Text ->
+                    M.Map Identifier Val -> P m B.Blocks)
+blockHandlers = M.fromList
+  [("text", \_ _ fields -> do
+      body <- getField "body" fields
+      -- sometimes text elements include para breaks
+      notFollowedBy $ void $ pWithContents pInlines body
+      pWithContents pBlocks body)
+  ,("title", \_ _ fields -> do
+      body <- getField "body" fields
+      case body of
+        VContent cs -> do
+          ils <- pWithContents pInlines cs <|> pure mempty
+          updateState $ \s -> s{ sMeta = B.setMeta "title" ils (sMeta s) }
+          pure mempty
+        _ -> pure mempty)
+  ,("box", \_ _ fields -> do
+      body <- getField "body" fields
+      B.divWith ("", ["box"], []) <$> pWithContents pBlocks body)
+  ,("heading", \_ mbident fields -> do
+      body <- getField "body" fields
+      lev <- getField "level" fields <|> pure 1
+      B.headerWith (fromMaybe "" mbident,[],[]) lev
+         <$> pWithContents pInlines body)
+  ,("quote", \_ _ fields -> do
+      getField "block" fields >>= guard
+      body <- getField "body" fields >>= pWithContents pBlocks
+      attribution' <- getField "attribution" fields
+      attribution <- if attribution' == mempty
+                        then pure mempty
+                        else (\x -> B.para ("\x2014\xa0" <> x)) <$>
+                              (pWithContents pInlines attribution')
+      pure $ B.blockQuote $ body <> attribution)
+  ,("list", \_ _ fields -> do
+      children <- V.toList <$> getField "children" fields
+      B.bulletList <$> mapM (pWithContents pBlocks) children)
+  ,("list.item", \_ _ fields -> getField "body" fields >>= pWithContents pBlocks)
+  ,("enum", \_ _ fields -> do
+      children <- V.toList <$> getField "children" fields
+      mbstart <- getField "start" fields
+      start <- case mbstart of
+        Nothing -> pure 1
+        Just x
+          | x >= 0 -> pure x
+          | otherwise -> fail "number must be positive"
+      (numbering :: Text) <- getField "numbering" fields `mplus` pure ""
+      let (sty, delim) =
+            case numbering of
+              "1." -> (B.Decimal, B.Period)
+              "1)" -> (B.Decimal, B.OneParen)
+              "(1)" -> (B.Decimal, B.TwoParens)
+              "a." -> (B.LowerAlpha, B.Period)
+              "a)" -> (B.LowerAlpha, B.OneParen)
+              "(a)" -> (B.LowerAlpha, B.TwoParens)
+              "A." -> (B.UpperAlpha, B.Period)
+              "A)" -> (B.UpperAlpha, B.OneParen)
+              "(A)" -> (B.UpperAlpha, B.TwoParens)
+              "i." -> (B.LowerRoman, B.Period)
+              "i)" -> (B.LowerRoman, B.OneParen)
+              "(i)" -> (B.LowerRoman, B.TwoParens)
+              "I." -> (B.UpperRoman, B.Period)
+              "I)" -> (B.UpperRoman, B.OneParen)
+              "(I)" -> (B.UpperRoman, B.TwoParens)
+              _ -> (B.DefaultStyle, B.DefaultDelim)
+      let listAttr = (start, sty, delim)
+      B.orderedListWith listAttr <$> mapM (pWithContents pBlocks) children)
+  ,("enum.item", \_ _ fields -> getField "body" fields >>= pWithContents pBlocks)
+  ,("terms", \_ _ fields -> do
+      children <- V.toList <$> getField "children" fields
+      B.definitionList
+        <$> mapM
+          ( \case
+              VTermItem t d -> do
+                t' <- pWithContents pInlines t
+                d' <- pWithContents pBlocks d
+                pure (t', [d'])
+              _ -> pure (mempty, [])
+          )
+          children)
+  ,("terms.item", \_ _ fields -> getField "body" fields >>= pWithContents pBlocks)
+  ,("raw", \_ mbident fields -> do
+      txt <- T.filter (/= '\r') <$> getField "text" fields
+      mblang <- getField "lang" fields
+      let attr = (fromMaybe "" mbident, maybe [] (\l -> [l]) mblang, [])
+      pure $ B.codeBlockWith attr txt)
+  ,("parbreak", \_ _ _ -> pure mempty)
+  ,("block", \_ mbident fields ->
+      maybe id (\ident -> B.divWith (ident, [], [])) mbident
+        <$> (getField "body" fields >>= pWithContents pBlocks))
+  ,("place", \_ _ fields -> do
+      ignored "parameters of place"
+      getField "body" fields >>= pWithContents pBlocks)
+  ,("columns", \_ _ fields -> do
+      (cnt :: Integer) <- getField "count" fields
+      B.divWith ("", ["columns-flow"], [("count", T.pack (show cnt))])
+        <$> (getField "body" fields >>= pWithContents pBlocks))
+  ,("rect", \_ _ fields ->
+      B.divWith ("", ["rect"], []) <$> (getField "body" fields >>= pWithContents pBlocks))
+  ,("circle", \_ _ fields ->
+      B.divWith ("", ["circle"], []) <$> (getField "body" fields >>= pWithContents pBlocks))
+  ,("ellipse", \_ _ fields ->
+      B.divWith ("", ["ellipse"], []) <$> (getField "body" fields >>= pWithContents pBlocks))
+  ,("polygon", \_ _ fields ->
+      B.divWith ("", ["polygon"], []) <$> (getField "body" fields >>= pWithContents pBlocks))
+  ,("square", \_ _ fields ->
+      B.divWith ("", ["square"], []) <$> (getField "body" fields >>= pWithContents pBlocks))
+  ,("align", \_ _ fields -> do
+      alignment <- getField "alignment" fields
+      B.divWith ("", [], [("align", repr alignment)])
+        <$> (getField "body" fields >>= pWithContents pBlocks))
+  ,("stack", \_ _ fields -> do
+      (dir :: Direction) <- getField "dir" fields `mplus` pure Ltr
+      rawchildren <- getField "children" fields
+      children <-
+        mapM
+          ( \case
+              val@(VFraction {}) ->
+                pure $ B.divWith ("", [], [("space", repr val)]) mempty
+              val -> fromVal val >>= pWithContents pBlocks
+          )
+          (V.toList rawchildren)
+      pure $
+        B.divWith ("", [], [("stack", repr (VDirection dir))]) $
+          mconcat $
+            map (B.divWith ("", [], [])) children)
+  ,("grid", \_ mbident fields -> parseTable mbident fields)
+  ,("table", \_ mbident fields -> parseTable mbident fields)
+  ,("figure", \_ mbident fields -> do
+      body <- getField "body" fields >>= pWithContents pBlocks
+      (mbCaption :: Maybe (Seq Content)) <- getField "caption" fields
+      (caption :: B.Blocks) <- maybe mempty (pWithContents pBlocks) mbCaption
+      pure $ case B.toList body of
+        [B.Table attr _ colspecs thead tbodies tfoot] ->
+          B.singleton
+            (B.Table attr (B.Caption Nothing (B.toList caption)) colspecs thead tbodies tfoot)
+        _ -> B.figureWith (fromMaybe "" mbident, [], [])
+                          (B.Caption Nothing (B.toList caption)) body)
+  ,("line", \_ _ fields ->
+      case ( M.lookup "start" fields
+              >> M.lookup "end" fields
+              >> M.lookup "angle" fields ) of
+        Nothing -> pure B.horizontalRule
+        _ -> pure mempty)
+  ,("numbering", \_ _ fields -> do
+      numStyle <- getField "numbering" fields
+      (nums :: V.Vector Integer) <- getField "numbers" fields
+      let toText v = fromMaybe "" $ fromVal v
+      let toNum n =
+            case numStyle of
+              VString t -> formatNumber t (fromIntegral n)
+              VFunction _ _ f ->
+                case applyPureFunction f [VInteger n] of
+                  Success x -> toText x
+                  Failure _ -> "?"
+              _ -> "?"
+      pure $ B.plain . B.text . mconcat . map toNum $ V.toList nums)
+  ,("footnote.entry", \_ _ fields ->
+      getField "body" fields >>= pWithContents pBlocks)
+  ,("pad", \_ _ fields ->  -- ignore paddingy
+      getField "body" fields >>= pWithContents pBlocks)
+  ,("pagebreak", \_ _ _ -> pure $ B.divWith ("", ["page-break"], [("wrapper", "1")]) B.horizontalRule)
+  ,("bibliography", \_ _ fields -> do
+      let getSources v = case v of
+                      VString t -> MetaString t
+                      VArray xs -> MetaList $ map getSources $ V.toList xs
+                      _ -> MetaBool True -- should not occur
+      let mbSources = getSources <$> M.lookup "sources" fields
+
+      let updateBibliography x = updateState $ \s ->
+             s{ sMeta = B.setMeta "bibliography" x (sMeta s) }
+      maybe (pure ()) updateBibliography mbSources
+
+      let title' = M.lookup "title" fields
+      mbTitle <- case title' of
+                   Just VNone -> pure Nothing
+                   Just (VContent cs) -> Just <$> pWithContents pInlines cs
+                   Just (VString t) -> pure $ Just $ B.text t
+                   _ -> Just . B.text <$> lift (translateTerm References)
+      let hdr = maybe mempty (B.header 1) mbTitle
+      pure $ hdr <> B.divWith ("refs", [], []) mempty)
+  ,("rotate", \_ _ fields -> do
+      body <- getField "body" fields >>= pWithContents pBlocks
+      let kvs = case M.lookup "angle" fields of
+                    Just (VAngle ang) -> [("angle", T.pack $ show ang)]
+                    _ -> []
+      pure $ B.divWith ("", ["rotate"], kvs) body)
+  ]
+
+inlineHandlers :: PandocMonad m =>
+    M.Map Identifier (Maybe SourcePos -> Maybe Text ->
+                      M.Map Identifier Val -> P m B.Inlines)
+inlineHandlers = M.fromList
+  [("ref", \_ _ fields -> do
+      VLabel target <- getField "target" fields
+      supplement' <- getField "supplement" fields
+      supplement <- case supplement' of
+                      VAuto -> -- TODO for now, until we can locate the element
+                        pure $ B.text ("[" <> target <> "]")
+                      VContent cs -> pWithContents pInlines cs
+                      VFunction _ _ _f -> -- TODO for now, until we can locate the element
+                           pure $ B.text ("[" <> target <> "]")
+                      _ -> pure mempty
+      pure $ B.linkWith ("", ["ref"], []) ("#" <> target) "" supplement)
+  ,("linebreak", \_ _ _ -> pure B.linebreak)
+  ,("text", \_ _ fields -> do
+      body <- getField "body" fields
+      (mbweight :: Maybe Text) <- getField "weight" fields
+      case mbweight of
+        Just "bold" -> B.strong <$> pWithContents pInlines body
+        _ -> pWithContents pInlines body)
+  ,("raw", \_ _ fields -> B.code . T.filter (/= '\r') <$> getField "text" fields)
+  ,("footnote", \_ _ fields ->
+      B.note <$> (getField "body" fields >>= pWithContents pBlocks))
+  ,("cite", \_ _ fields -> do
+      VLabel key <- getField "key" fields
+      (form :: Text) <- getField "form" fields <|> pure "normal"
+      let citation =
+            B.Citation
+              { B.citationId = key,
+                B.citationPrefix = mempty,
+                B.citationSuffix = mempty,
+                B.citationMode = case form of
+                                    "year" -> B.SuppressAuthor
+                                    _ -> B.NormalCitation,
+                B.citationNoteNum = 0,
+                B.citationHash = 0
+              }
+      pure $ B.cite [citation] (B.text $ "[" <> key <> "]"))
+  ,("lower", \_ _ fields -> do
+      body <- getField "text" fields
+      walk (modString T.toLower) <$> pWithContents pInlines body)
+  ,("upper", \_ _ fields -> do
+      body <- getField "text" fields
+      walk (modString T.toUpper) <$> pWithContents pInlines body)
+  ,("emph", \_ _ fields -> do
+      body <- getField "body" fields
+      B.emph <$> pWithContents pInlines body)
+  ,("strong", \_ _ fields -> do
+      body <- getField "body" fields
+      B.strong <$> pWithContents pInlines body)
+  ,("sub", \_ _ fields -> do
+      body <- getField "body" fields
+      B.subscript <$> pWithContents pInlines body)
+  ,("super", \_ _ fields -> do
+      body <- getField "body" fields
+      B.superscript <$> pWithContents pInlines body)
+  ,("strike", \_ _ fields -> do
+      body <- getField "body" fields
+      B.strikeout <$> pWithContents pInlines body)
+  ,("smallcaps", \_ _ fields -> do
+      body <- getField "body" fields
+      B.smallcaps <$> pWithContents pInlines body)
+  ,("underline", \_ _ fields -> do
+      body <- getField "body" fields
+      B.underline <$> pWithContents pInlines body)
+  ,("quote", \_ _ fields -> do
+      (getField "block" fields <|> pure False) >>= guard . not
+      body <- getInlineBody fields >>= pWithContents pInlines
+      pure $ B.doubleQuoted $ B.trimInlines body)
+  ,("link", \_ _ fields -> do
+      dest <- getField "dest" fields
+      src <- case dest of
+        VString t -> pure t
+        VLabel t -> pure $ "#" <> t
+        VDict _ -> do
+          ignored "link to location, linking to #"
+          pure "#"
+        _ -> fail "Expected string or label for dest"
+      body <- getField "body" fields
+      description <-
+        if null body
+          then
+            pure $
+              B.text $
+                if "mailto:" `T.isPrefixOf` src
+                  then T.drop 7 src
+                  else
+                    if "tel:" `T.isPrefixOf` src
+                      then T.drop 4 src
+                      else src
+          else pWithContents pInlines body <|>
+               pWithContents
+                (B.fromList . blocksToInlines . B.toList <$> pBlocks) body
+      pure $ B.link src "" description)
+  ,("image", \mbpos _ fields -> do
+      path <- getField "source" fields <|> getField "path" fields
+      alt <- (B.text <$> getField "alt" fields) `mplus` pure mempty
+      let basedir = maybe "." (takeDirectory . sourceName) mbpos
+      let isAbsolutePath p = Posix.isAbsolute p || Windows.isAbsolute p
+      let path' = T.pack $
+                  if isAbsolutePath path || basedir == "."
+                     then path
+                     else basedir Posix.</> path
+      (mbwidth :: Maybe Text) <-
+        fmap (renderLength False) <$> getField "width" fields
+      (mbheight :: Maybe Text) <-
+        fmap (renderLength False) <$> getField "height" fields
+      let attr =
+            ( "",
+              [],
+              maybe [] (\x -> [("width", x)]) mbwidth
+                ++ maybe [] (\x -> [("height", x)]) mbheight
+            )
+      pure $ B.imageWith attr path' "" alt)
+  ,("box", \_ _ fields -> do
+      body <- getField "body" fields
+      B.spanWith ("", ["box"], []) <$> pWithContents pInlines body)
+  ,("h", \_ _ fields -> do
+      amount <- getField "amount" fields `mplus` pure (LExact 1 LEm)
+      let em = case amount of
+            LExact x LEm -> toRational x
+            _ -> case amount <> LExact 0 LPt of -- force to Pt
+              LExact x LPt -> toRational x / 12
+              _ -> 1 / 3 -- guess!
+      pure $ B.text $ getSpaceChars em)
+  ,("place", \_ _ fields -> do
+      ignored "parameters of place"
+      getField "body" fields >>= pWithContents pInlines)
+  ,("align", \_ _ fields -> do
+      alignment <- getField "alignment" fields
+      B.spanWith ("", [], [("align", repr alignment)])
+        <$> (getField "body" fields >>= pWithContents pInlines))
+  ,("sys.version", \_ _ _ -> pure $ B.text "typst-hs")
+  ,("math.equation", \_ _ fields -> do
+      body <- getField "body" fields
+      display <- getField "block" fields
+      (if display then B.displayMath else B.math) . writeTeX <$> pMathMany body)
+  ,("pad", \_ _ fields ->  -- ignore paddingy
+      getField "body" fields >>= pWithContents pInlines)
+  ,("block", \_ mbident fields ->
+      maybe id (\ident -> B.spanWith (ident, [], [])) mbident
+        <$> (getField "body" fields >>= pWithContents pInlines))
+  ,("rotate", \_ _ fields -> do
+      body <- getField "body" fields >>= pWithContents pInlines
+      let kvs = case M.lookup "angle" fields of
+                    Just (VAngle ang) -> [("angle", T.pack $ show ang)]
+                    _ -> []
+      pure $ B.spanWith ("", ["rotate"], kvs) body)
+  ]
+
+getInlineBody :: PandocMonad m => M.Map Identifier Val -> P m (Seq Content)
+getInlineBody fields =
+  parbreaksToLinebreaks <$> getField "body" fields
+
+parbreaksToLinebreaks :: Seq Content -> Seq Content
+parbreaksToLinebreaks =
+  fmap go . Seq.dropWhileL isParbreak . Seq.dropWhileR isParbreak
+ where
+   go (Elt "parbreak" pos _) = Elt "linebreak" pos mempty
+   go x = x
+   isParbreak (Elt "parbreak" _ _) = True
+   isParbreak _ = False
+
+pPara :: PandocMonad m => P m B.Blocks
+pPara = do
+  ils <- B.trimInlines . collapseAdjacentCites . mconcat <$> many1 pInline
+  optional pParBreak
+  pure $ if ils == mempty
+         then mempty
+         else B.para ils
+
+pParBreak :: PandocMonad m => P m ()
+pParBreak =
+  void $
+    pTok
+      ( \case
+          Elt "parbreak" _ _ -> True
+          _ -> False
+      )
+
+pWithContents :: PandocMonad m => P m a -> Seq Content -> P m a
+pWithContents pa cs = try $ do
+  inp <- getInput
+  setInput $ F.toList cs
+  res <- pa
+  eof
+  setInput inp
+  pure res
+
+pInlines :: PandocMonad m => P m B.Inlines
+pInlines =
+  mappend <$> (collapseAdjacentCites . mconcat <$> many pInline)
+          <*> ((B.softbreak <$ pParBreak) <|> pure mempty)
+
+collapseAdjacentCites :: B.Inlines -> B.Inlines
+collapseAdjacentCites = B.fromList . foldr go [] . B.toList
+ where
+   go (Cite cs1 ils1) (Cite cs2 ils2 : xs) =
+     Cite (cs1 ++ cs2) (ils1 <> ils2) : xs
+   go (Cite cs1 ils1) (Space : Cite cs2 ils2 : xs) =
+     Cite (cs1 ++ cs2) (ils1 <> ils2) : xs
+   go x xs = x:xs
+
+modString :: (Text -> Text) -> B.Inline -> B.Inline
+modString f (B.Str t) = B.Str (f t)
+modString _ x = x
+
+findLabels :: Seq.Seq Content -> [Text]
+findLabels = foldr go []
+ where
+   go (Txt{}) = id
+   go (Lab t) = (t :)
+   go (Elt{ eltFields = fs }) = \ts -> foldr go' ts fs
+   go' (VContent cs) = (findLabels cs ++)
+   go' _ = id
+
+parseTable :: PandocMonad m
+           => Maybe Text -> M.Map Identifier Val -> P m B.Blocks
+parseTable mbident fields = do
+  children <- V.toList <$> getField "children" fields
+  (columns :: Val) <- getField "columns" fields
+  let toWidth (VFraction f) = Just (floor $ 1000 * f)
+      toWidth _ = Nothing
+  let normalizeWidths xs =
+        let givenwidths = catMaybes xs
+            (totgivenwidth :: Int) = sum givenwidths
+            avgwidth = totgivenwidth `div` length givenwidths
+            totwidth = avgwidth * length xs
+         in if null givenwidths
+              then replicate (length xs) B.ColWidthDefault
+              else
+                map
+                  ( \case
+                      Just x ->
+                        B.ColWidth (fromIntegral x / fromIntegral totwidth)
+                      Nothing ->
+                        B.ColWidth
+                        (fromIntegral avgwidth / fromIntegral totwidth)
+                  )
+                  xs
+  widths <- case columns of
+    VInteger x -> pure $ replicate (fromIntegral x) B.ColWidthDefault
+    VArray x -> pure $ normalizeWidths $ map toWidth (V.toList x)
+    VNone -> pure [B.ColWidthDefault]
+    _ -> fail $ "Could not determine number of columns: " <> show columns
+  let numcols = length widths
+  align <- getField "align" fields
+  let toAlign (VAlignment (Just horiz) _) =
+        case horiz of
+          HorizStart -> B.AlignLeft
+          HorizLeft -> B.AlignLeft
+          HorizEnd -> B.AlignRight
+          HorizRight -> B.AlignRight
+          HorizCenter -> B.AlignCenter
+      toAlign _ = B.AlignDefault
+  aligns <-
+    case align of
+      VAlignment {} -> pure $ replicate numcols (toAlign align)
+      VArray v -> pure $ map toAlign (V.toList v)
+      VFunction _ _ f -> do
+        mapM
+          ( \colnum -> case applyPureFunction
+              f
+              [VInteger colnum, VInteger 0] of
+              Success x -> pure $ toAlign x
+              Failure e -> fail e
+          )
+          [0 .. (fromIntegral numcols - 1)]
+      _ -> pure $ replicate numcols B.AlignDefault
+  let colspecs = zip (aligns ++ repeat B.AlignDefault) widths
+  let addCell' cell Nothing = addCell' cell (Just ([], []))
+      addCell' cell@(B.Cell _ _ (B.RowSpan rowspan) (B.ColSpan colspan) _)
+       (Just (freecols, revrows))  =
+        let freecols' =
+              case (rowspan + 1) - length freecols of
+                n | n < 0 -> freecols
+                  | otherwise -> freecols ++ replicate n numcols
+        in case freecols' of
+             [] -> -- should not happen
+                   error "empty freecols'"
+             x:xs
+               | colspan <= x -- there is room on current row
+                 -> let (as, bs) = splitAt rowspan (x:xs)
+                    in  Just
+                        (map (\z -> z - colspan) as ++ bs,
+                           case revrows of
+                             [] -> [[cell]]
+                             r:rs -> (cell:r):rs)
+               | otherwise ->
+                    let (as, bs) = splitAt rowspan xs
+                    in  Just (map (\z -> z - colspan) as ++ bs, [cell]:revrows)
+  let addCell tableSection cell (TableData tdata) =
+        TableData (M.alter (addCell' cell) tableSection tdata)
+  let toCell tableSection tableData contents = do
+        case contents of
+          [Elt (Identifier "grid.cell") _pos fs] -> do
+            bs <- B.toList <$> (getField "body" fs >>= pWithContents pBlocks)
+            rowspan <- getField "rowspan" fs <|> pure 1
+            colspan <- getField "colspan" fs <|> pure 1
+            align' <- (toAlign <$> getField "align" fs) <|> pure B.AlignDefault
+            pure $ addCell tableSection
+              (B.Cell B.nullAttr align' (B.RowSpan rowspan)
+                (B.ColSpan colspan) bs) tableData
+          [Elt (Identifier "table.cell") pos fs] ->
+            toCell tableSection tableData [Elt (Identifier "grid.cell") pos fs]
+          [Elt (Identifier "table.vline") _pos _fs] -> pure tableData
+          [Elt (Identifier "table.hline") _pos _fs] -> pure tableData
+          [Elt (Identifier "grid.vline") _pos _fs] -> pure tableData
+          [Elt (Identifier "grid.hline") _pos _fs] -> pure tableData
+          [Elt (Identifier "table.header") _pos fs] ->
+            getField "children" fs >>=
+              foldM (toCell THeader) tableData . V.toList
+          [Elt (Identifier "table.footer") _pos fs] ->
+            getField "children" fs >>=
+              foldM (toCell TFooter) tableData . V.toList
+          _ -> do
+            bs <- B.toList <$> pWithContents pBlocks contents
+            pure $ addCell tableSection
+              (B.Cell B.nullAttr B.AlignDefault (B.RowSpan 1) (B.ColSpan 1) bs)
+              tableData
+  tableData <- foldM (toCell TBody) (TableData mempty) children
+  let getRows tablePart = map (B.Row B.nullAttr . reverse)
+                          . maybe [] (reverse . snd)
+                          . M.lookup tablePart . unTableData
+  let headRows = getRows THeader tableData
+  let bodyRows = getRows TBody tableData
+  let footRows = getRows TFooter tableData
+  pure $
+    B.tableWith
+      (fromMaybe "" mbident, [], [])
+      (B.Caption mempty mempty)
+      colspecs
+      (B.TableHead B.nullAttr headRows)
+      [B.TableBody B.nullAttr 0 [] bodyRows]
+      (B.TableFoot B.nullAttr footRows)
+
+data TableSection = THeader | TBody | TFooter
+  deriving (Show, Ord, Eq)
+
+newtype TableData =
+  TableData { unTableData :: M.Map TableSection ([Int], [[Cell]]) }
+  deriving (Show)
+  -- for each table section, we have a pair
+  -- the first element indicates the number of column spaces left
+  -- in [currentLine, nextLine, lineAfter, etc.]
+  -- the second element is a list of rows, in reverse order,
+  -- each of which is a list of cells, in reverse order
diff --git a/src/Text/Pandoc/Readers/Typst/Math.hs b/src/Text/Pandoc/Readers/Typst/Math.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Readers/Typst/Math.hs
@@ -0,0 +1,421 @@
+{-# LANGUAGE OverloadedLists #-}
+{-# LANGUAGE OverloadedStrings #-}
+{-# LANGUAGE ScopedTypeVariables #-}
+
+module Text.Pandoc.Readers.Typst.Math
+  ( pMathMany
+  )
+where
+
+import Control.Monad (MonadPlus (mplus))
+import Data.Char (isAlphaNum, isDigit)
+import Data.List (intercalate)
+import qualified Data.Map as M
+import Data.Maybe (fromMaybe)
+import Data.Sequence (Seq)
+import qualified Data.Sequence as Seq
+import Data.Text (Text)
+import qualified Data.Text as T
+import qualified Data.Vector as V
+import Text.Pandoc.Parsing ( many )
+import Text.Pandoc.Class ( PandocMonad )
+import Text.TeXMath.Types
+  ( Alignment (..),
+    Exp (..),
+    FractionType (..),
+    TeXSymbolType (..),
+    TextType (..),
+  )
+import Text.TeXMath.Unicode.ToTeX (getSymbolType)
+import Text.Pandoc.Readers.Typst.Parsing
+    ( P, pTok, ignored, pWithContents, getField, chunks )
+import Typst.Types
+
+withGroup :: [Exp] -> Exp
+withGroup [x] = x
+withGroup xs = EGrouped xs
+
+data AttachmentStyle = Limits | LimitsDisplay | Scripts
+  deriving (Eq, Show)
+
+getAttachmentStyle :: PandocMonad m => M.Map Identifier Val -> P m (Maybe AttachmentStyle)
+getAttachmentStyle fields = do
+  (base :: Seq Content) <- getField "base" fields
+  case base of
+    [Elt "math.op" _ fs] -> do
+      limits <- getField "limits" fs
+      if limits == VBoolean True
+         then pure $ Just Limits
+         else pure Nothing
+    [Elt "math.limits" _ fs] -> do
+      inl <- getField "inline" fs
+      if inl == VBoolean False
+         then pure $ Just LimitsDisplay
+         else pure $ Just Limits
+    [Elt "math.scripts" _ _] -> pure $ Just Scripts
+    _ -> pure Nothing
+
+pMath :: PandocMonad m => P m Exp
+pMath = pTok (const True) >>= handleMath
+
+handleMath :: PandocMonad m => Content -> P m Exp
+handleMath tok =
+  case tok of
+    Lab t -> do
+      ignored ("label " <> t)
+      pure (EGrouped [])
+    Txt t
+      | T.any isDigit t -> pure $ ENumber t
+      | T.length t == 1 ->
+          case T.unpack t of
+            [c] | not (isAlphaNum c) -> pure $ ESymbol (getSymbolType c) t
+            _ -> pure $ EIdentifier t
+      | otherwise -> pure $ EText TextNormal t
+    Elt "math.dif" _ _ -> pure $ EIdentifier "d"
+    Elt "math.Dif" _ _ -> pure $ EIdentifier "D"
+    Elt "math.equation" _ fields -> getField "body" fields >>= pMathGrouped
+    Elt "text" _ fields -> do
+      body <- getField "body" fields
+      (mbweight :: Maybe Text) <- getField "weight" fields
+      case mbweight of
+        Just "bold" -> EStyled TextBold <$> pMathMany body
+        _ -> pMathGrouped body
+    Elt "math.op" _ fields -> EMathOperator <$> getField "text" fields
+    Elt "math.frac" _ fields -> do
+      num <- getField "num" fields >>= pMathGrouped
+      denom <- getField "denom" fields >>= pMathGrouped
+      pure $ EFraction NormalFrac num denom
+    Elt "math.accent" _ fields -> do
+      base <- getField "base" fields >>= pMathGrouped
+      acc <- getField "accent" fields >>= pMathGrouped
+      let acc' = case acc of
+            ESymbol _ "\8901" -> ESymbol Accent "\775" -- \dot
+            ESymbol _ "\168" -> ESymbol Accent "\776" -- \ddot
+            ESymbol _ "\8764" -> ESymbol Accent "\771" -- \tilde
+            ESymbol _ t -> ESymbol Accent t
+            _ -> acc
+      pure $ EOver False base acc'
+    Elt "math.attach" _ fields -> do
+      base <- getField "base" fields >>= pMathGrouped
+      t' <- getField "t" fields
+      b' <- getField "b" fields
+      tr' <- getField "tr" fields
+      tl' <- getField "tl" fields
+      br' <- getField "br" fields
+      bl' <- getField "bl" fields
+      attachmentStyle <- getAttachmentStyle fields
+      let limits = case attachmentStyle of
+                     Just Limits -> True
+                     Just LimitsDisplay -> True
+                     _ -> False
+      let convertible = attachmentStyle == Just LimitsDisplay
+      let (mbt, mbtr) =
+            case (t', tr') of
+              (Just top, Just topright) -> (Just top, Just topright)
+              (Just top, Nothing)
+                | limits -> (Just top, Nothing)
+                | otherwise -> (Nothing, Just top)
+              (Nothing, Just topright) -> (Nothing, Just topright)
+              (Nothing, Nothing) -> (Nothing, Nothing)
+      let (mbb, mbbr) =
+            case (b', br') of
+              (Just bot, Just botright) -> (Just bot, Just botright)
+              (Just bot, Nothing)
+                | limits -> (Just bot, Nothing)
+                | otherwise -> (Nothing, Just bot)
+              (Nothing, Just topright) -> (Nothing, Just topright)
+              (Nothing, Nothing) -> (Nothing, Nothing)
+      let dummy = EGrouped []
+      let addPrefix x =
+            case (tl', bl') of
+              (Nothing, Nothing) -> pure x
+              (Just top, Nothing) -> do
+                res <- ESuper dummy <$> pMathGrouped top
+                pure $ EGrouped [res, x]
+              (Nothing, Just bot) -> do
+                res <- ESub dummy <$> pMathGrouped bot
+                pure $ EGrouped [res, x]
+              (Just top, Just bot) -> do
+                res <- ESubsup dummy <$> pMathGrouped bot <*> pMathGrouped top
+                pure $ EGrouped [res, x]
+
+      base' <- case (mbtr, mbbr) of
+        (Nothing, Nothing) -> pure base
+        (Nothing, Just br) -> ESub base <$> pMathGrouped br
+        (Just tr, Nothing) -> ESuper base <$> pMathGrouped tr
+        (Just tr, Just br) -> ESubsup base <$> pMathGrouped br <*> pMathGrouped tr
+
+      suffix <- case (mbt, mbb) of
+        (Nothing, Nothing) -> pure base'
+        (Nothing, Just bot) -> EUnder convertible base' <$> pMathGrouped bot
+        (Just top, Nothing) -> EOver convertible base' <$> pMathGrouped top
+        (Just top, Just bot) -> EUnderover convertible base'
+                                  <$> pMathGrouped bot <*> pMathGrouped top
+
+      addPrefix suffix
+    Elt "math.serif" _ fields ->
+      EStyled TextNormal <$> (getField "body" fields >>= pMathMany)
+    Elt "math.sans" _ fields ->
+      EStyled TextSansSerif <$> (getField "body" fields >>= pMathMany)
+    Elt "math.frak" _ fields ->
+      EStyled TextFraktur <$> (getField "body" fields >>= pMathMany)
+    Elt "math.mono" _ fields ->
+      EStyled TextMonospace <$> (getField "body" fields >>= pMathMany)
+    Elt "math.cal" _ fields ->
+      EStyled TextScript <$> (getField "body" fields >>= pMathMany)
+    Elt "math.bb" _ fields ->
+      EStyled TextDoubleStruck <$> (getField "body" fields >>= pMathMany)
+    Elt "math.upright" _ fields ->
+      EStyled TextNormal <$> (getField "body" fields >>= pMathMany)
+    Elt "math.bold" _ fields ->
+      EStyled TextBold <$> (getField "body" fields >>= pMathMany)
+    Elt "math.italic" _ fields ->
+      EStyled TextItalic <$> (getField "body" fields >>= pMathMany)
+    Elt "math.underline" _ fields ->
+      EUnder False
+        <$> (getField "body" fields >>= pMathGrouped)
+        <*> pure (ESymbol TUnder "_")
+    Elt "math.overline" _ fields ->
+      EOver False
+        <$> (getField "body" fields >>= pMathGrouped)
+        <*> pure (ESymbol TOver "\175")
+    Elt "math.underbrace" _ fields -> do
+      mbAnn <- getField "annotation" fields
+      body <- getField "body" fields >>= pMathGrouped
+      let x = EUnder False body (ESymbol TUnder "\9183")
+      case mbAnn of
+        Nothing -> pure x
+        Just ann -> EUnder False x <$> pMathGrouped ann
+    Elt "math.overbrace" _ fields -> do
+      mbAnn <- getField "annotation" fields
+      body <- getField "body" fields >>= pMathGrouped
+      let x = EOver False body (ESymbol TOver "\9182")
+      case mbAnn of
+        Nothing -> pure x
+        Just ann -> EOver False x <$> pMathGrouped ann
+    Elt "math.underbracket" _ fields -> do
+      mbAnn <- getField "annotation" fields
+      body <- getField "body" fields >>= pMathGrouped
+      let x = EUnder False body (ESymbol TUnder "\9141")
+      case mbAnn of
+        Nothing -> pure x
+        Just ann -> EUnder False x <$> pMathGrouped ann
+    Elt "math.overbracket" _ fields -> do
+      mbAnn <- getField "annotation" fields
+      body <- getField "body" fields >>= pMathGrouped
+      let x = EOver False body (ESymbol TOver "\9140")
+      case mbAnn of
+        Nothing -> pure x
+        Just ann -> EOver False x <$> pMathGrouped ann
+    Elt "math.underparen" _ fields -> do
+      mbAnn <- getField "annotation" fields
+      body <- getField "body" fields >>= pMathGrouped
+      let x = EUnder False body (ESymbol TUnder "\9181")
+      case mbAnn of
+        Nothing -> pure x
+        Just ann -> EUnder False x <$> pMathGrouped ann
+    Elt "math.overparen" _ fields -> do
+      mbAnn <- getField "annotation" fields
+      body <- getField "body" fields >>= pMathGrouped
+      let x = EOver False body (ESymbol TOver "\9180")
+      case mbAnn of
+        Nothing -> pure x
+        Just ann -> EOver False x <$> pMathGrouped ann
+    Elt "math.scripts" _ fields -> getField "body" fields >>= pMathGrouped
+    Elt "math.limits" _ fields -> getField "body" fields >>= pMathGrouped
+    Elt "math.root" _ fields -> do
+      mbindex <- getField "index" fields
+      radicand <- getField "radicand" fields >>= pMathGrouped
+      case mbindex of
+        Nothing -> pure $ ESqrt radicand
+        Just index -> do
+          index' <- pMathGrouped index
+          pure $ ERoot index' radicand
+    Elt "math.sqrt" _ fields ->
+      ESqrt <$> (getField "radicand" fields >>= pMathGrouped)
+    Elt "math.abs" _ fields -> do
+      body <- getField "body" fields >>= pMathGrouped
+      pure $ EDelimited "|" "|" [Right body]
+    Elt "math.floor" _ fields -> do
+      body <- getField "body" fields >>= pMathGrouped
+      pure $ EDelimited "\8970" "\8971" [Right body]
+    Elt "math.ceil" _ fields -> do
+      body <- getField "body" fields >>= pMathGrouped
+      pure $ EDelimited "\8968" "\8969" [Right body]
+    Elt "math.norm" _ fields -> do
+      body <- getField "body" fields >>= pMathGrouped
+      pure $ EDelimited "\8214" "\8214" [Right body]
+    Elt "math.round" _ fields -> do
+      body <- getField "body" fields >>= pMathGrouped
+      pure $ EDelimited "\8970" "\8969" [Right body]
+    Elt "math.lr" _ fields -> do
+      bodyparts <- getField "body" fields >>= mapM pMathMany . V.toList
+      let rawbody = intercalate [ESymbol Pun ","] bodyparts
+      let (op, rest) =
+            case rawbody of
+              (ESymbol _ t : xs) -> (t, xs)
+              _ -> ("", rawbody)
+      let (body, cl) =
+            case reverse rest of
+              (ESymbol _ t : _) -> (map Right (init rest), t)
+              _ -> (map Right rest, "")
+      pure $ EDelimited op cl body
+    Elt "math.binom" _ fields -> do
+      up <- getField "upper" fields >>= pMathGrouped
+      low <- getField "lower" fields >>= pMathGrouped
+      pure $ EDelimited "(" ")" [Right (EFraction NoLineFrac up low)]
+    Elt "math.cases" _ fields -> do
+      (delim :: Maybe Text) <- getField "delim" fields
+      (children :: [Seq Content]) <-
+        map valToContent . V.toList <$> getField "children" fields
+      let isAlignPoint (Elt "math.alignpoint" _ _) = True
+          isAlignPoint _ = False
+      let formatRow vs = case Seq.breakl isAlignPoint vs of
+            (xs, ys) -> do
+              case Seq.viewl ys of
+                _ Seq.:< rest -> do
+                  xs' <- pMathMany xs
+                  ys' <- pMathMany rest
+                  pure [xs', ys']
+                _ -> (: []) <$> pMathMany vs
+      rows <- mapM formatRow children
+      pure $
+        EDelimited
+          (fromMaybe "{" delim)
+          ""
+          [Right (EArray [AlignLeft, AlignLeft] rows)]
+    Elt "math.vec" _ fields -> do
+      (op, cl) <- arrayDelims fields
+      rows <-
+        getField "children" fields
+          >>= mapM (fmap (: []) . pMathMany) . V.toList
+      pure $
+        EDelimited
+          op
+          cl
+          [Right (EArray [AlignCenter] rows)]
+    Elt "math.mat" _ fields -> do
+      (op, cl) <- arrayDelims fields
+      let formatCell x = do
+            let content = valToContent x
+            let align = case Seq.viewl content of
+                  Elt "math.alignpoint" _ _ Seq.:< _ -> AlignLeft
+                  _ -> case Seq.viewr content of
+                    _ Seq.:> Elt "math.alignpoint" _ _ -> AlignRight
+                    _ -> AlignCenter
+            exp' <- pMathMany content
+            pure (align, exp')
+      let formatRow (VArray vs) = mapM formatCell (V.toList vs)
+          formatRow _ = fail "mat expected array"
+      (rawrows :: V.Vector Val) <- getField "rows" fields
+      rows <- mapM formatRow (V.toList rawrows)
+      let aligns =
+            case rows of
+              [] -> []
+              (r : _) -> map fst r
+      pure $
+        EDelimited
+          op
+          cl
+          [Right (EArray aligns (map (map snd) rows))]
+    Elt "hide" _ fields -> do
+      EPhantom <$> (getField "body" fields >>= pMathGrouped)
+    Elt "h" _ fields -> do
+      amount <- getField "amount" fields
+      let em = case amount of
+            LExact x LEm -> toRational x
+            _ -> case amount <> LExact 0 LPt of -- force to Pt
+              LExact x LPt -> toRational x / 12
+              _ -> 1 / 3 -- guess!
+      pure $ ESpace em
+    Elt "grid" _ fields -> do
+      children <- getField "children" fields >>= mapM pMathMany . V.toList
+      (columns :: Val) <- getField "columns" fields
+      numcols <- case columns of
+        VInteger x -> pure $ fromIntegral x
+        VArray x -> pure $ V.length x
+        VNone -> pure 1
+        _ -> fail $ "Could not determine number of columns: " <> show columns
+      let rows = chunks numcols children
+      pure $ EArray (replicate numcols AlignLeft) rows
+    Elt "table" pos fields -> handleMath (Elt "grid" pos fields)
+    Elt "link" _ fields -> do
+      body <- getField "body" fields
+      ignored "hyperlink in math"
+      pMathGrouped body
+    Elt "math.display" _ fields -> do
+      content <- getField "content" fields
+      ignored "display"
+      pMathGrouped content
+    Elt "math.inline" _ fields -> do
+      content <- getField "content" fields
+      ignored "inline"
+      pMathGrouped content
+    Elt "math.script" _ fields -> do
+      content <- getField "content" fields
+      ignored "script"
+      pMathGrouped content
+    Elt "math.sscript" _ fields -> do
+      content <- getField "content" fields
+      ignored "sscript"
+      pMathGrouped content
+    Elt (Identifier name) _ fields -> do
+      body <- getField "body" fields `mplus` pure mempty
+      ignored name
+      pMathGrouped body
+
+arrayDelims :: PandocMonad m => M.Map Identifier Val -> P m (Text, Text)
+arrayDelims fields = do
+  (mbdelim :: Maybe Text) <- getField "delim" fields
+  pure $ case mbdelim of
+    Just "(" -> ("(", ")")
+    Just "[" -> ("[", "]")
+    Just "{" -> ("{", "}")
+    Just "|" -> ("|", "|")
+    Just "||" -> ("\8741", "\8741")
+    _ -> ("(", ")")
+
+pMathMany :: PandocMonad m => Seq Content -> P m [Exp]
+pMathMany cs = do
+  -- check for "alignpoint" and "linebreak" elements
+  -- and use an array structure for alignment
+  let lns = splitOnLinebreaks cs
+  case lns of
+    [] -> pure []
+    [ln] | not (any isAlignpoint ln) -> pWithContents (many pMath) ln
+    _ -> do
+      rows <- mapM (mapM (pWithContents (many pMath)) . splitOnAlignpoints) lns
+      let numcols = maximum $ map length rows
+      let cols = take numcols $ AlignRight : cycle [AlignLeft, AlignRight]
+      pure [EArray cols rows]
+
+pMathGrouped :: PandocMonad m => Seq Content -> P m Exp
+pMathGrouped = fmap withGroup . pMathMany
+
+splitOnLinebreaks :: Seq Content -> [Seq Content]
+splitOnLinebreaks xs =
+  if Seq.null bs
+    then
+      if null as
+        then []
+        else [as]
+    else as : splitOnLinebreaks (Seq.drop 1 bs)
+  where
+    (as, bs) = Seq.breakl isLinebreak xs
+    isLinebreak (Elt "linebreak" _ _) = True
+    isLinebreak _ = False
+
+splitOnAlignpoints :: Seq Content -> [Seq Content]
+splitOnAlignpoints xs =
+  if Seq.null bs
+    then
+      if null as
+        then []
+        else [as]
+    else as : splitOnAlignpoints (Seq.drop 1 bs)
+  where
+    (as, bs) = Seq.breakl isAlignpoint xs
+
+isAlignpoint :: Content -> Bool
+isAlignpoint (Elt "math.alignpoint" _ _) = True
+isAlignpoint _ = False
diff --git a/src/Text/Pandoc/Readers/Typst/Parsing.hs b/src/Text/Pandoc/Readers/Typst/Parsing.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Readers/Typst/Parsing.hs
@@ -0,0 +1,76 @@
+{-# LANGUAGE LambdaCase #-}
+{-# LANGUAGE OverloadedLists #-}
+{-# LANGUAGE OverloadedStrings #-}
+{-# LANGUAGE ScopedTypeVariables #-}
+
+module Text.Pandoc.Readers.Typst.Parsing
+  ( P,
+    PState(..),
+    defaultPState,
+    pTok,
+    pWithContents,
+    ignored,
+    getField,
+    chunks,
+  )
+where
+import Control.Monad (MonadPlus)
+import Control.Monad.Reader (lift)
+import qualified Data.Foldable as F
+import qualified Data.Map as M
+import Data.Maybe (fromMaybe)
+import Data.Sequence (Seq)
+import Data.Text (Text)
+import Text.Parsec
+    ( ParsecT, getInput, setInput, tokenPrim )
+import Typst.Types
+    ( Identifier, Content(Elt), FromVal(..), Val(VNone) )
+import Text.Pandoc.Class.PandocMonad ( PandocMonad, report )
+import Text.Pandoc.Logging (LogMessage(..))
+import Text.Pandoc.Definition
+
+data PState = PState
+        { sLabels :: [Text]
+        , sMeta :: Meta }
+        deriving (Show)
+
+defaultPState :: PState
+defaultPState =
+  PState
+  { sLabels = []
+  , sMeta = mempty }
+
+type P m a = ParsecT [Content] PState m a
+-- state tracks a list of labels in the document
+
+pTok :: PandocMonad m => (Content -> Bool) -> P m Content
+pTok f = tokenPrim show showPos match
+  where
+    showPos _oldpos (Elt _ (Just pos) _) _ = pos
+    showPos oldpos _ _ = oldpos
+    match x | f x = Just x
+    match _ = Nothing
+
+ignored :: PandocMonad m => Text -> P m ()
+ignored msg = lift $ report $ IgnoredElement msg
+
+pWithContents :: PandocMonad m => P m a -> Seq Content -> P m a
+pWithContents pa cs = do
+  inp <- getInput
+  setInput $ F.toList cs
+  res <- pa
+  setInput inp
+  pure res
+
+-- | Get field value from element, defaulting to VNone.
+getField ::
+  (MonadFail m, MonadPlus m, FromVal a) =>
+  Identifier ->
+  M.Map Identifier Val ->
+  m a
+getField name fields = fromVal $ fromMaybe VNone $ M.lookup name fields
+
+-- | Split a list into chunks of a given size. The last chunk may be smaller.
+chunks :: Int -> [a] -> [[a]]
+chunks _ [] = []
+chunks n xs = take n xs : chunks n (drop n xs)
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,24 +1,8 @@
-{-
-  Copyright (C) 2017 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
--}
-
+{-# LANGUAGE OverloadedStrings #-}
+{-# LANGUAGE CPP #-}
 {- |
    Module      : Text.Pandoc.Readers.Vimwiki
-   Copyright   : Copyright (C) 2017 Yuchen Pei
+   Copyright   : Copyright (C) 2017-2020 Yuchen Pei
    License     : GNU GPL, version 2 or above
 
    Maintainer  : Yuchen Pei <me@ypei.me>
@@ -66,46 +50,45 @@
 import Control.Monad (guard)
 import Control.Monad.Except (throwError)
 import Data.Default
-import Data.List (isInfixOf, isPrefixOf)
+import Data.List (isInfixOf)
 import Data.Maybe
-import Data.Monoid ((<>))
-import Data.Text (Text, unpack)
+import Data.Text (Text)
+import qualified Data.Text as T
+import Safe (lastMay)
 import Text.Pandoc.Builder (Blocks, Inlines, fromList, toList, trimInlines)
-import qualified Text.Pandoc.Builder as B (blockQuote, bulletList, code,
-                                           codeBlockWith, definitionList,
-                                           displayMath, divWith, emph,
-                                           headerWith, horizontalRule, image,
-                                           imageWith, link, math, orderedList,
-                                           para, plain, setMeta, simpleTable,
-                                           softbreak, space, spanWith, str,
-                                           strikeout, strong, subscript,
-                                           superscript)
-import Text.Pandoc.Class (PandocMonad (..))
+import qualified Text.Pandoc.Builder as B
+import Text.Pandoc.Class.PandocMonad (PandocMonad (..))
 import Text.Pandoc.Definition (Attr, Block (BulletList, OrderedList),
                                Inline (Space), ListNumberDelim (..),
-                               ListNumberStyle (..), Meta, Pandoc (..),
+                               ListNumberStyle (..), Pandoc (..),
                                nullMeta)
 import Text.Pandoc.Options (ReaderOptions)
-import Text.Pandoc.Parsing (F, ParserState, ParserT, blanklines, emailAddress,
+import Text.Pandoc.Parsing (ParserState, ParsecT, blanklines, emailAddress,
                             many1Till, orderedListMarker, readWithM,
-                            registerHeader, runF, spaceChar, stateMeta',
-                            stateOptions, uri)
-import Text.Pandoc.Shared (crFilter, splitBy, stringify, stripFirstAndLast)
-import Text.Parsec.Char (alphaNum, anyChar, char, newline, noneOf, oneOf, space,
-                         spaces, string)
-import Text.Parsec.Combinator (between, choice, count, eof, lookAhead, many1,
-                               manyTill, notFollowedBy, option, skipMany1)
-import Text.Parsec.Prim (getState, many, try, updateState, (<|>))
+                            registerHeader, spaceChar, stateMeta,
+                            stateOptions, uri, manyTillChar, manyChar, textStr,
+                            many1Char, countChar, many1TillChar,
+                            alphaNum, anyChar, char, newline, noneOf, oneOf,
+                            space, spaces, string, choice, eof, lookAhead,
+                            many1, many, manyTill, notFollowedBy,
+                            skipMany1, try, option,
+                            updateState, getState, (<|>))
+import Text.Pandoc.Sources (ToSources(..), Sources)
+import Text.Pandoc.Shared (splitTextBy, stringify, stripFirstAndLast, tshow)
+import Text.Pandoc.URI (isURI)
 
-readVimwiki :: PandocMonad m => ReaderOptions -> Text -> m Pandoc
+readVimwiki :: (PandocMonad m, ToSources a)
+            => ReaderOptions
+            -> a
+            -> m Pandoc
 readVimwiki opts s = do
-  res <- readWithM parseVimwiki def{ stateOptions = opts }
-            (unpack (crFilter s))
+  let sources = toSources s
+  res <- readWithM parseVimwiki def{ stateOptions = opts } sources
   case res of
        Left e       -> throwError e
        Right result -> return result
 
-type VwParser = ParserT [Char] ParserState
+type VwParser = ParsecT Sources ParserState
 
 
 -- constants
@@ -124,7 +107,7 @@
   spaces
   eof
   st <- getState
-  let meta = runF (stateMeta' st) st
+  let meta = stateMeta st
   return $ Pandoc meta (toList bs)
 
 -- block parser
@@ -144,7 +127,7 @@
                 , definitionList
                 , para
                 ]
-  trace (take 60 $ show $ toList res)
+  trace (T.take 60 $ tshow $ toList res)
   return res
 
 blockML :: PandocMonad m => VwParser m Blocks
@@ -160,7 +143,7 @@
   contents <- trimInlines . mconcat <$> manyTill inline (try $ spaceChar
     >> string eqs >> many spaceChar >> newline)
   attr <- registerHeader (makeId contents,
-    if sp == "" then [] else ["justcenter"], []) contents
+    ["justcenter" | not (null sp)], []) contents
   return $ B.headerWith attr lev contents
 
 para :: PandocMonad m => VwParser m Blocks
@@ -226,7 +209,7 @@
 
 definitionTerm2 :: PandocMonad m => VwParser m Inlines
 definitionTerm2 = try $ trimInlines . mconcat <$> manyTill inline'
-  (try $lookAhead (defMarkerM >> notFollowedBy hasDefMarkerM))
+  (try $ lookAhead (defMarkerM >> notFollowedBy hasDefMarkerM))
 
 defMarkerM :: PandocMonad m => VwParser m Char
 defMarkerM = string "::" >> spaceChar
@@ -234,51 +217,54 @@
 defMarkerE :: PandocMonad m => VwParser m Char
 defMarkerE = string "::" >> newline
 
-hasDefMarkerM :: PandocMonad m => VwParser m String
-hasDefMarkerM = manyTill (noneOf "\n") (try defMarkerM)
+hasDefMarkerM :: PandocMonad m => VwParser m Text
+hasDefMarkerM = manyTillChar (noneOf "\n") (try defMarkerM)
 
 preformatted :: PandocMonad m => VwParser m Blocks
 preformatted = try $ do
   many spaceChar >> string "{{{"
-  attrText <- many (noneOf "\n")
+  attrText <- manyChar (noneOf "\n")
   lookAhead newline
-  contents <- manyTill anyChar (try (char '\n' >> many spaceChar >> string "}}}"
+  contents <- manyTillChar anyChar (try (char '\n' >> many spaceChar >> string "}}}"
     >> many spaceChar >> newline))
-  if (contents /= "") && (head contents == '\n')
-     then return $ B.codeBlockWith (makeAttr attrText) (tail contents)
+  if (contents /= "") && (T.head contents == '\n')
+     then return $ B.codeBlockWith (makeAttr attrText) (T.tail contents)
      else return $ B.codeBlockWith (makeAttr attrText) contents
 
-makeAttr :: String -> Attr
+makeAttr :: Text -> Attr
 makeAttr s =
-  let xs = splitBy (`elem` " \t") s in
-    ("", [], mapMaybe nameValue xs)
+  let xs = splitTextBy (`elem` (" \t" :: String)) s in
+    ("", syntax xs, mapMaybe nameValue xs)
 
-nameValue :: String -> Maybe (String, String)
-nameValue s =
-  let t = splitBy (== '=') s in
-    if length t /= 2
-      then Nothing
-      else let (a, b) = (head t, last t) in
-             if (length b < 2) || ((head b, last b) /= ('"', '"'))
-               then Nothing
-               else Just (a, stripFirstAndLast b)
+syntax :: [Text] -> [Text]
+syntax (s:_) | not $ T.isInfixOf "=" s = [s]
+syntax _ = []
 
+nameValue :: Text -> Maybe (Text, Text)
+nameValue s =
+  case splitTextBy (== '=') s of
+    [a,b]
+      | T.length b >= 2
+      , "\"" `T.isPrefixOf` b
+      , "\"" `T.isSuffixOf` b
+      -> Just (a, stripFirstAndLast b)
+    _ -> Nothing
 
 displayMath :: PandocMonad m => VwParser m Blocks
 displayMath = try $ do
   many spaceChar >> string "{{$"
   mathTag <- option "" mathTagParser
   many space
-  contents <- manyTill anyChar (try (char '\n' >> many spaceChar >> string "}}$"
+  contents <- manyTillChar anyChar (try (char '\n' >> many spaceChar >> string "}}$"
     >> many spaceChar >> newline))
   let contentsWithTags
         | mathTag == "" = contents
-        | otherwise     = "\\begin{" ++ mathTag ++ "}\n" ++ contents
-                          ++ "\n\\end{" ++ mathTag ++ "}"
+        | otherwise     = "\\begin{" <> mathTag <> "}\n" <> contents
+                          <> "\n\\end{" <> mathTag <> "}"
   return $ B.para $ B.displayMath contentsWithTags
 
 
-mathTagLaTeX :: String -> String
+mathTagLaTeX :: Text -> Text
 mathTagLaTeX s = case s of
    "equation"  -> ""
    "equation*" -> ""
@@ -297,8 +283,8 @@
 
 mixedList :: PandocMonad m => VwParser m Blocks
 mixedList = try $ do
-  (bl, _) <- mixedList' (-1)
-  return $ head bl
+  ((bl:_), _) <- mixedList' (-1)
+  return bl
 
 mixedList' :: PandocMonad m => Int -> VwParser m ([Blocks], Int)
 mixedList' prevInd = do
@@ -351,8 +337,9 @@
 
 listTodoMarker :: PandocMonad m => VwParser m Inlines
 listTodoMarker = try $ do
-  x <- between (many spaceChar >> char '[') (char ']' >> spaceChar)
-    (oneOf " .oOX")
+  x <- (many spaceChar >> char '[')
+       *> oneOf " .oOX"
+       <* (char ']' >> spaceChar)
   return $ makeListMarkerSpan x
 
 makeListMarkerSpan :: Char -> Inlines
@@ -376,21 +363,19 @@
                             _ -> x:[y]
 combineList x xs = x:xs
 
-listStart :: PandocMonad m => VwParser m (Int, String)
+listStart :: PandocMonad m => VwParser m (Int, Text)
 listStart = try $ do
   s <- many spaceChar
   listType <- bulletListMarkers <|> orderedListMarkers
   spaceChar
   return (length s, listType)
 
-bulletListMarkers :: PandocMonad m => VwParser m String
+bulletListMarkers :: PandocMonad m => VwParser m Text
 bulletListMarkers = "ul" <$ (char '*' <|> char '-')
 
-orderedListMarkers :: PandocMonad m => VwParser m String
+orderedListMarkers :: PandocMonad m => VwParser m Text
 orderedListMarkers =
-  ("ol" <$choice (orderedListMarker Decimal Period:(($OneParen)
-    <$> orderedListMarker
-    <$> [Decimal, LowerRoman, UpperRoman, LowerAlpha, UpperAlpha])))
+  ("ol" <$ choice (orderedListMarker Decimal Period:(($ OneParen) . orderedListMarker <$> [Decimal, LowerRoman, UpperRoman, LowerAlpha, UpperAlpha])))
     <|> ("ol" <$ char '#')
 
 --many need trimInlines
@@ -414,8 +399,8 @@
 -- headerless table
 table2 :: PandocMonad m => VwParser m ([Blocks], [[Blocks]])
 table2 = try $ do
-  trs <- many1 tableRow
-  return (replicate (length $ head trs) mempty, trs)
+  trs@(firstrow:_) <- many1 tableRow
+  return (replicate (length firstrow) mempty, trs)
 
 tableHeaderSeparator :: PandocMonad m => VwParser m ()
 tableHeaderSeparator = try $ do
@@ -429,9 +414,7 @@
   s <- lookAhead $ manyTill anyChar (try (char '|' >> many spaceChar
     >> newline))
   guard $ not $ "||" `isInfixOf` ("|" ++ s ++ "|")
-  tr <- many tableCell
-  many spaceChar >> char '\n'
-  return tr
+  many tableCell <* many spaceChar <* char '\n'
 
 tableCell :: PandocMonad m => VwParser m Blocks
 tableCell = try $
@@ -441,23 +424,25 @@
 placeholder = try $
   choice (ph <$> ["title", "date"]) <|> noHtmlPh <|> templatePh
 
-ph :: PandocMonad m => String -> VwParser m ()
+ph :: PandocMonad m => Text -> VwParser m ()
 ph s = try $ do
-  many spaceChar >>string ('%':s) >> spaceChar
+  many spaceChar >> textStr (T.cons '%' s) >> spaceChar
   contents <- trimInlines . mconcat <$> manyTill inline (lookAhead newline)
     --use lookAhead because of placeholder in the whitespace parser
-  let meta' = return $ B.setMeta s contents nullMeta :: F Meta
-  updateState $ \st -> st { stateMeta' = stateMeta' st <> meta' }
+  let meta' = B.setMeta s contents nullMeta
+  -- this order ensures that later values will be ignored in favor
+  -- of earlier ones:
+  updateState $ \st -> st { stateMeta = meta' <> stateMeta st }
 
 noHtmlPh :: PandocMonad m => VwParser m ()
 noHtmlPh = try $
-  () <$ (many spaceChar >> string "%nohtml" >> many spaceChar
-    >> lookAhead newline)
+  () <$ many spaceChar <* string "%nohtml" <* many spaceChar
+    <* lookAhead newline
 
 templatePh :: PandocMonad m => VwParser m ()
 templatePh = try $
-  () <$ (many spaceChar >> string "%template" >>many (noneOf "\n")
-    >> lookAhead newline)
+  () <$ many spaceChar <* string "%template" <* many (noneOf "\n")
+    <* lookAhead newline
 
 -- inline parser
 
@@ -494,7 +479,7 @@
 inlineML = choice $ whitespace endlineML:inlineList
 
 str :: PandocMonad m => VwParser m Inlines
-str = B.str <$>many1 (noneOf $ spaceChars ++ specialChars)
+str = B.str <$> many1Char (noneOf $ spaceChars ++ specialChars)
 
 whitespace :: PandocMonad m => VwParser m () -> VwParser m Inlines
 whitespace endline = B.space <$ (skipMany1 spaceChar <|>
@@ -505,7 +490,7 @@
 whitespace' = B.space <$ skipMany1 spaceChar
 
 special :: PandocMonad m => VwParser m Inlines
-special = B.str <$> count 1 (oneOf specialChars)
+special = B.str <$> countChar 1 (oneOf specialChars)
 
 bareURL :: PandocMonad m => VwParser m Inlines
 bareURL = try $ do
@@ -514,26 +499,23 @@
 
 strong :: PandocMonad m => VwParser m Inlines
 strong = try $ do
-  s <- lookAhead $ between (char '*') (char '*') (many1 $ noneOf "*")
-  guard $ (head s `notElem` spaceChars)
-             && (last s `notElem` spaceChars)
   char '*'
-  contents <- mconcat <$>manyTill inline' (char '*'
-    >> notFollowedBy alphaNum)
-  return $ B.spanWith (makeId contents, [], []) mempty
-    <> B.strong contents
+  notFollowedBy (oneOf spaceChars)
+  contents <- mconcat <$> many1Till inline'
+                           (try (char '*' *> notFollowedBy alphaNum))
+  guard $ lastMay (toList contents) /= Just Space
+  return $ B.spanWith (makeId contents, [], []) mempty <> B.strong contents
 
-makeId :: Inlines -> String
-makeId i = concat (stringify <$> toList i)
+makeId :: Inlines -> Text
+makeId i = T.concat (stringify <$> toList i)
 
 emph :: PandocMonad m => VwParser m Inlines
 emph = try $ do
-  s <- lookAhead $ between (char '_') (char '_') (many1 $ noneOf "_")
-  guard $ (head s `notElem` spaceChars)
-          && (last s `notElem` spaceChars)
   char '_'
-  contents <- mconcat <$>manyTill inline' (char '_'
-    >> notFollowedBy alphaNum)
+  notFollowedBy (oneOf spaceChars)
+  contents <- mconcat <$> many1Till inline'
+                           (try (char '_' *> notFollowedBy alphaNum))
+  guard $ lastMay (toList contents) /= Just Space
   return $ B.emph contents
 
 strikeout :: PandocMonad m => VwParser m Inlines
@@ -545,7 +527,7 @@
 code :: PandocMonad m => VwParser m Inlines
 code = try $ do
   char '`'
-  contents <- many1Till (noneOf "\n") (char '`')
+  contents <- many1TillChar (noneOf "\n") (char '`')
   return $ B.code contents
 
 superscript :: PandocMonad m => VwParser m Inlines
@@ -560,16 +542,19 @@
 link :: PandocMonad m => VwParser m Inlines
 link = try $ do
   string "[["
-  contents <- lookAhead $ manyTill anyChar (string "]]")
-  case '|' `elem` contents of
-                  False -> do
+  contents <- lookAhead $ manyTillChar anyChar (string "]]")
+  if T.any (== '|') contents
+                  then do
+                    url <- manyTillChar anyChar $ char '|'
+                    lab <- mconcat <$> manyTill inline (string "]]")
+                    return $ B.linkWith (attr url) (procLink url) "" lab
+                  else do
                     manyTill anyChar (string "]]")
 -- not using try here because [[hell]o]] is not rendered as a link in vimwiki
-                    return $ B.link (procLink contents) "" (B.str contents)
-                  True  -> do
-                    url <- manyTill anyChar $ char '|'
-                    lab <- mconcat <$> manyTill inline (string "]]")
-                    return $ B.link (procLink url) "" lab
+                    return $ B.linkWith (attr contents) (procLink contents) "" (B.str contents)
+  where
+    attr t | isURI t = B.nullAttr
+           | otherwise = (mempty, ["wikilink"], mempty)
 
 image :: PandocMonad m => VwParser m Inlines
 image = try $ do
@@ -580,55 +565,54 @@
 images :: PandocMonad m => Int -> VwParser m Inlines
 images k
   | k == 0 = do
-           imgurl <- manyTill anyChar (try $ string "}}")
+           imgurl <- manyTillChar anyChar (try $ string "}}")
            return $ B.image (procImgurl imgurl) "" (B.str "")
   | k == 1 = do
-           imgurl <- manyTill anyChar (char '|')
+           imgurl <- manyTillChar anyChar (char '|')
            alt <- mconcat <$> manyTill inline (try $ string "}}")
            return $ B.image (procImgurl imgurl) "" alt
   | k == 2 = do
-           imgurl <- manyTill anyChar (char '|')
-           alt <- mconcat <$>manyTill inline (char '|')
-           attrText <- manyTill anyChar (try $ string "}}")
+           imgurl <- manyTillChar anyChar (char '|')
+           alt <- mconcat <$> manyTill inline (char '|')
+           attrText <- manyTillChar anyChar (try $ string "}}")
            return $ B.imageWith (makeAttr attrText) (procImgurl imgurl) "" alt
   | otherwise = do
-           imgurl <- manyTill anyChar (char '|')
-           alt <- mconcat <$>manyTill inline (char '|')
-           attrText <- manyTill anyChar (char '|')
+           imgurl <- manyTillChar anyChar (char '|')
+           alt <- mconcat <$> manyTill inline (char '|')
+           attrText <- manyTillChar anyChar (char '|')
            manyTill anyChar (try $ string "}}")
            return $ B.imageWith (makeAttr attrText) (procImgurl imgurl) "" alt
 
-procLink' :: String -> String
+procLink' :: Text -> Text
 procLink' s
-  | take 6 s == "local:" = "file" ++ drop 5 s
-  | take 6 s == "diary:" = "diary/" ++ drop 6 s ++ ".html"
-  | or ((`isPrefixOf` s) <$> [ "http:", "https:", "ftp:", "file:", "mailto:",
-                              "news:", "telnet:" ])
+  | T.take 6 s == "local:" = "file" <> T.drop 5 s
+  | T.take 6 s == "diary:" = "diary/" <> T.drop 6 s
+  | any (`T.isPrefixOf` s) [ "http:", "https:", "ftp:", "file:", "mailto:",
+                             "news:", "telnet:" ]
                              = s
   | s == ""                  = ""
-  | last s == '/'          = s
-  | otherwise                = s ++ ".html"
+  | T.last s == '/'          = s
+  | otherwise                = s
 
-procLink :: String -> String
-procLink s = procLink' x ++ y
-  where (x, y) = break (=='#') s
+procLink :: Text -> Text
+procLink s = procLink' x <> y
+  where (x, y) = T.break (=='#') s
 
-procImgurl :: String -> String
-procImgurl s = if take 6 s == "local:" then "file" ++ drop 5 s else s
+procImgurl :: Text -> Text
+procImgurl s = if T.take 6 s == "local:" then "file" <> T.drop 5 s else s
 
 inlineMath :: PandocMonad m => VwParser m Inlines
-inlineMath = try $ do
-  char '$'
-  contents <- many1Till (noneOf "\n") (char '$')
-  return $ B.math contents
+inlineMath = try $
+  B.math <$ char '$' <*> many1TillChar (noneOf "\n") (char '$')
 
 tag :: PandocMonad m => VwParser m Inlines
 tag = try $ do
   char ':'
-  s <- manyTill (noneOf spaceChars) (try (char ':' >> lookAhead space))
-  guard $ not $ "::" `isInfixOf` (":" ++ s ++ ":")
-  let ss = splitBy (==':') s
-  return $ mconcat $ makeTagSpan' (head ss):(makeTagSpan <$> tail ss)
+  s <- manyTillChar (noneOf spaceChars) (try (char ':' >> lookAhead space))
+  guard $ not $ "::" `T.isInfixOf` (":" <> s <> ":")
+  case splitTextBy (==':') s of
+    [] -> fail "tag doesn't contain :"
+    (x:xs) -> return $ mconcat $ makeTagSpan' x : (makeTagSpan <$> xs)
 
 todoMark :: PandocMonad m => VwParser m Inlines
 todoMark = try $ do
@@ -660,16 +644,16 @@
 hasDefMarker :: PandocMonad m => VwParser m ()
 hasDefMarker = () <$ manyTill (noneOf "\n") (string "::" >> oneOf spaceChars)
 
-makeTagSpan' :: String -> Inlines
-makeTagSpan' s = B.spanWith ('-' : s, [], []) (B.str "") <>
+makeTagSpan' :: Text -> Inlines
+makeTagSpan' s = B.spanWith (T.cons '-' s, [], []) (B.str "") <>
                   B.spanWith (s, ["tag"], []) (B.str s)
 
-makeTagSpan :: String -> Inlines
+makeTagSpan :: Text -> Inlines
 makeTagSpan s = B.space <> makeTagSpan' s
 
-mathTagParser :: PandocMonad m => VwParser m String
+mathTagParser :: PandocMonad m => VwParser m Text
 mathTagParser = do
-  s <- try $ lookAhead (char '%' >> manyTill (noneOf spaceChars)
+  s <- try $ lookAhead (char '%' >> manyTillChar (noneOf spaceChars)
     (try $ char '%' >> many (noneOf $ '%':spaceChars) >> space))
-  char '%' >> string s >> char '%'
+  char '%' >> textStr s >> char '%'
   return $ mathTagLaTeX s
diff --git a/src/Text/Pandoc/Readers/XML.hs b/src/Text/Pandoc/Readers/XML.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Readers/XML.hs
@@ -0,0 +1,543 @@
+{-# LANGUAGE OverloadedStrings #-}
+{-# LANGUAGE ScopedTypeVariables #-}
+
+-- |
+--   Module      : Text.Pandoc.Readers.XML
+--   Copyright   : Copyright (C) 2025- Massimiliano Farinella and John MacFarlane
+--   License     : GNU GPL, version 2 or above
+--
+--   Maintainer  : Massimiliano Farinella <massifrg@gmail.com>
+--   Stability   : WIP
+--   Portability : portable
+--
+-- Conversion of (Pandoc specific) xml to 'Pandoc' document.
+module Text.Pandoc.Readers.XML (readXML) where
+
+import Control.Monad (msum)
+import Control.Monad.Except (throwError)
+import Control.Monad.State.Strict (StateT (runStateT), modify)
+import Data.Char (isSpace)
+import Data.Default (Default (..))
+import qualified Data.List as L
+import qualified Data.Map as M
+import Data.Maybe (catMaybes, fromMaybe, mapMaybe)
+import qualified Data.Set as S (Set, fromList, member)
+import Data.Text (Text)
+import qualified Data.Text as T
+import Data.Text.Lazy (fromStrict)
+import Data.Version (Version, makeVersion)
+import Text.Pandoc.Builder
+import Text.Pandoc.Class.PandocMonad
+import Text.Pandoc.Error (PandocError (..))
+import Text.Pandoc.Options
+import Text.Pandoc.Parsing (ToSources, toSources)
+import Text.Pandoc.Sources (sourcesToText)
+import Text.Pandoc.Version (pandocVersion)
+import Text.Pandoc.XML (lookupEntity)
+import Text.Pandoc.XML.Light
+import Text.Pandoc.XMLFormat
+import Text.Read (readMaybe)
+
+-- TODO: use xmlPath state to give better context when an error occurs
+
+type XMLReader m = StateT XMLReaderState m
+
+data XMLReaderState = XMLReaderState
+  { xmlApiVersion :: Version,
+    xmlMeta :: Meta,
+    xmlContent :: [Content],
+    xmlPath :: [Text]
+  }
+  deriving (Show)
+
+instance Default XMLReaderState where
+  def =
+    XMLReaderState
+      { xmlApiVersion = pandocVersion,
+        xmlMeta = mempty,
+        xmlContent = [],
+        xmlPath = ["root"]
+      }
+
+readXML :: (PandocMonad m, ToSources a) => ReaderOptions -> a -> m Pandoc
+readXML _ inp = do
+  let sources = toSources inp
+  tree <-
+    either (throwError . PandocXMLError "") return $
+      parseXMLContents (fromStrict . sourcesToText $ sources)
+  (bs, st') <- flip runStateT (def {xmlContent = tree}) $ mapM parseBlock tree
+  let blockList = toList $ concatMany bs
+  return $ Pandoc (xmlMeta st') blockList
+
+concatMany :: [Many a] -> Many a
+concatMany = Many . mconcat . map unMany
+
+parseBlocks :: (PandocMonad m) => [Content] -> XMLReader m Blocks
+parseBlocks contents = concatMany <$> mapM parseBlock contents
+
+getBlocks :: (PandocMonad m) => Element -> XMLReader m Blocks
+getBlocks e = parseBlocks (elContent e)
+
+elementName :: Element -> Text
+elementName e = qName $ elName e
+
+attrValue :: Text -> Element -> Text
+attrValue attr =
+  fromMaybe "" . maybeAttrValue attr
+
+maybeAttrValue :: Text -> Element -> Maybe Text
+maybeAttrValue attr elt =
+  lookupAttrBy (\x -> qName x == attr) (elAttribs elt)
+
+parseBlock :: (PandocMonad m) => Content -> XMLReader m Blocks
+parseBlock (Text (CData CDataRaw _ _)) = return mempty -- DOCTYPE
+parseBlock (Text (CData _ s _)) =
+  if T.all isSpace s
+    then return mempty
+    else do
+      throwError $ PandocXMLError "" "non-space characters out of inline context"
+parseBlock (CRef x) = do
+  throwError $ PandocXMLError "" ("reference \"" <> x <> "\" out of inline context")
+parseBlock (Elem e) = do
+  let name = elementName e
+   in case (name) of
+        "Pandoc" -> parsePandoc
+        "?xml" -> return mempty
+        "blocks" -> getBlocks e
+        "meta" ->
+          let entry_els = childrenNamed tgNameMetaMapEntry e
+           in do
+                entries <- catMaybes <$> mapM parseMetaMapEntry entry_els
+                mapM_ (uncurry addMeta) entries
+                return mempty
+        "Para" -> para <$> getInlines (elContent e)
+        "Plain" -> do
+          ils <- getInlines (elContent e)
+          return $ singleton . Plain . toList $ ils
+        "Header" -> (headerWith attr level) <$> getInlines (elContent e)
+          where
+            level = textToInt (attrValue atNameLevel e) 1
+            attr = filterAttrAttributes [atNameLevel] $ attrFromElement e
+        "HorizontalRule" -> return horizontalRule
+        "BlockQuote" -> do
+          contents <- getBlocks e
+          return $ blockQuote contents
+        "Div" -> do
+          contents <- getBlocks e
+          return $ divWith (attrFromElement e) contents
+        "BulletList" -> do
+          items <- getListItems e
+          return $ bulletList items
+        "OrderedList" -> do
+          items <- getListItems e
+          return $ orderedListWith (getListAttributes e) items
+        "DefinitionList" -> do
+          let items_contents = getContentsOfElements (isElementNamed tgNameDefListItem) (elContent e)
+          items <- mapM parseDefinitionListItem items_contents
+          return $ definitionList items
+        "Figure" -> do
+          let attr = attrFromElement e
+              (maybe_caption_el, contents) = partitionFirstChildNamed "Caption" $ elContent e
+          figure_caption <- case (maybe_caption_el) of
+            Just (caption_el) -> parseCaption $ elContent caption_el
+            Nothing -> pure emptyCaption
+          blocks <- parseBlocks contents
+          return $ figureWith attr figure_caption blocks
+        "CodeBlock" -> do
+          let attr = attrFromElement e
+          return $ codeBlockWith attr $ strContentRecursive e
+        "RawBlock" -> do
+          let format = (attrValue atNameFormat e)
+          return $ rawBlock format $ strContentRecursive e
+        "LineBlock" -> do
+          lins <- mapM getInlines (contentsOfChildren tgNameLineItem (elContent e))
+          return $ lineBlock lins
+        "Table" -> do
+          -- TODO: check unexpected items
+          let attr = attrFromElement e
+              (maybe_caption_el, after_caption) = partitionFirstChildNamed "Caption" $ elContent e
+              children = elementsWithNames (S.fromList [tgNameColspecs, "TableHead", "TableBody", "TableFoot"]) after_caption
+              is_element tag el = tag == elementName el
+          colspecs <- getColspecs $ L.find (is_element tgNameColspecs) children
+          tbs <- getTableBodies $ filter (is_element "TableBody") children
+          th <- getTableHead $ L.find (is_element "TableHead") children
+          tf <- getTableFoot $ L.find (is_element "TableFoot") children
+          capt <- parseMaybeCaptionElement maybe_caption_el
+          case colspecs of
+            Nothing -> return mempty
+            Just cs -> return $ fromList [Table attr capt cs th tbs tf]
+        _ -> do
+          throwError $ PandocXMLError "" ("unexpected element \"" <> name <> "\" in blocks context")
+  where
+    parsePandoc = do
+      let version = maybeAttrValue atNameApiVersion e
+          apiversion = case (version) of
+            Just (v) -> makeVersion $ map (read . T.unpack) $ T.splitOn "," v
+            Nothing -> pandocVersion
+       in modify $ \st -> st {xmlApiVersion = apiversion}
+      getBlocks e
+
+getListItems :: (PandocMonad m) => Element -> XMLReader m [Blocks]
+getListItems e =
+  let items_els = childrenNamed tgNameListItem e
+   in do
+        mapM getBlocks items_els
+
+getContentsOfElements :: (Content -> Bool) -> [Content] -> [[Content]]
+getContentsOfElements filter_element contents = mapMaybe element_contents $ filter filter_element contents
+  where
+    element_contents :: Content -> Maybe [Content]
+    element_contents c = case (c) of
+      Elem e -> Just (elContent e)
+      _ -> Nothing
+
+strContentRecursive :: Element -> Text
+strContentRecursive =
+  strContent
+    . (\e' -> e' {elContent = map elementToStr $ elContent e'})
+
+elementToStr :: Content -> Content
+elementToStr (Elem e') = Text $ CData CDataText (strContentRecursive e') Nothing
+elementToStr x = x
+
+textToInt :: Text -> Int -> Int
+textToInt t deflt =
+  let safe_to_int :: Text -> Maybe Int
+      safe_to_int s = readMaybe $ T.unpack s
+   in case (safe_to_int t) of
+        Nothing -> deflt
+        Just (n) -> n
+
+parseInline :: (PandocMonad m) => Content -> XMLReader m Inlines
+parseInline (Text (CData _ s _)) =
+  return $ text s
+parseInline (CRef ref) =
+  return $
+    maybe (text $ T.toUpper ref) text $
+      lookupEntity ref
+parseInline (Elem e) =
+  let name = elementName e
+   in case (name) of
+        "Space" ->
+          let count = textToInt (attrValue atNameSpaceCount e) 1
+           in return $ fromList $ replicate count Space
+        "Str" -> return $ fromList [Str $ attrValue atNameStrContent e]
+        "Emph" -> innerInlines emph
+        "Strong" -> innerInlines strong
+        "Strikeout" -> innerInlines strikeout
+        "Subscript" -> innerInlines subscript
+        "Superscript" -> innerInlines superscript
+        "Underline" -> innerInlines underline
+        "SoftBreak" -> return softbreak
+        "LineBreak" -> return linebreak
+        "SmallCaps" -> innerInlines smallcaps
+        "Quoted" -> case (attrValue atNameQuoteType e) of
+          "SingleQuote" -> innerInlines singleQuoted
+          _ -> innerInlines doubleQuoted
+        "Math" -> case (attrValue atNameMathType e) of
+          "DisplayMath" -> pure $ displayMath $ strContentRecursive e
+          _ -> pure $ math $ strContentRecursive e
+        "Span" -> innerInlines $ spanWith (attrFromElement e)
+        "Code" -> do
+          let attr = attrFromElement e
+          return $ codeWith attr $ strContentRecursive e
+        "Link" -> innerInlines $ linkWith attr url title
+          where
+            url = attrValue atNameLinkUrl e
+            title = attrValue atNameTitle e
+            attr = filterAttrAttributes [atNameLinkUrl, atNameTitle] $ attrFromElement e
+        "Image" -> innerInlines $ imageWith attr url title
+          where
+            url = attrValue atNameImageUrl e
+            title = attrValue atNameTitle e
+            attr = filterAttrAttributes [atNameImageUrl, atNameTitle] $ attrFromElement e
+        "RawInline" -> do
+          let format = (attrValue atNameFormat e)
+          return $ rawInline format $ strContentRecursive e
+        "Note" -> do
+          contents <- getBlocks e
+          return $ note contents
+        "Cite" ->
+          let (maybe_citations_el, contents) = partitionFirstChildNamed tgNameCitations $ elContent e
+           in case (maybe_citations_el) of
+                Just citations_el -> do
+                  citations <- parseCitations $ elContent citations_el
+                  (innerInlines' contents) $ cite citations
+                Nothing -> getInlines contents
+        _ -> do
+          throwError $ PandocXMLError "" ("unexpected element \"" <> name <> "\" in inline context")
+  where
+    innerInlines' contents f =
+      f . concatMany
+        <$> mapM parseInline contents
+    innerInlines f = innerInlines' (elContent e) f
+
+getInlines :: (PandocMonad m) => [Content] -> XMLReader m Inlines
+getInlines contents = concatMany <$> mapM parseInline contents
+
+getListAttributes :: Element -> ListAttributes
+getListAttributes e = (start, style, delim)
+  where
+    start = textToInt (attrValue atNameStart e) 1
+    style = case (attrValue atNameNumberStyle e) of
+      "Example" -> Example
+      "Decimal" -> Decimal
+      "LowerRoman" -> LowerRoman
+      "UpperRoman" -> UpperRoman
+      "LowerAlpha" -> LowerAlpha
+      "UpperAlpha" -> UpperAlpha
+      _ -> DefaultStyle
+    delim = case (attrValue atNameNumberDelim e) of
+      "Period" -> Period
+      "OneParen" -> OneParen
+      "TwoParens" -> TwoParens
+      _ -> DefaultDelim
+
+contentsOfChildren :: Text -> [Content] -> [[Content]]
+contentsOfChildren tag contents = mapMaybe childrenElementWithTag contents
+  where
+    childrenElementWithTag :: Content -> Maybe [Content]
+    childrenElementWithTag c = case (c) of
+      (Elem e) -> if tag == elementName e then Just (elContent e) else Nothing
+      _ -> Nothing
+
+alignmentFromText :: Text -> Alignment
+alignmentFromText t = case t of
+  "AlignLeft" -> AlignLeft
+  "AlignRight" -> AlignRight
+  "AlignCenter" -> AlignCenter
+  _ -> AlignDefault
+
+getColWidth :: Text -> ColWidth
+getColWidth txt = case reads (T.unpack txt) of
+  [(value, "")] -> if value == 0.0 then ColWidthDefault else ColWidth value
+  _ -> ColWidthDefault
+
+getColspecs :: (PandocMonad m) => Maybe Element -> XMLReader m (Maybe [ColSpec])
+getColspecs Nothing = pure Nothing
+getColspecs (Just cs) = do
+  return $ Just $ map elementToColSpec (childrenNamed "ColSpec" cs)
+  where
+    elementToColSpec e = (alignmentFromText $ attrValue atNameAlignment e, getColWidth $ attrValue atNameColWidth e)
+
+getTableBody :: (PandocMonad m) => Element -> XMLReader m (Maybe TableBody)
+getTableBody body_el = do
+  let attr = filterAttrAttributes [atNameRowHeadColumns] $ attrFromElement body_el
+      bh = childrenNamed tgNameBodyHeader body_el
+      bb = childrenNamed tgNameBodyBody body_el
+      headcols = textToInt (attrValue atNameRowHeadColumns body_el) 0
+  hrows <- mconcat <$> mapM getRows bh
+  brows <- mconcat <$> mapM getRows bb
+  return $ Just $ TableBody attr (RowHeadColumns headcols) hrows brows
+
+getTableBodies :: (PandocMonad m) => [Element] -> XMLReader m [TableBody]
+getTableBodies body_elements = do
+  catMaybes <$> mapM getTableBody body_elements
+
+getTableHead :: (PandocMonad m) => Maybe Element -> XMLReader m TableHead
+getTableHead maybe_e = case maybe_e of
+  Just e -> do
+    let attr = attrFromElement e
+    rows <- getRows e
+    return $ TableHead attr rows
+  Nothing -> return $ TableHead nullAttr []
+
+getTableFoot :: (PandocMonad m) => Maybe Element -> XMLReader m TableFoot
+getTableFoot maybe_e = case maybe_e of
+  Just e -> do
+    let attr = attrFromElement e
+    rows <- getRows e
+    return $ TableFoot attr rows
+  Nothing -> return $ TableFoot nullAttr []
+
+getCell :: (PandocMonad m) => Element -> XMLReader m Cell
+getCell c = do
+  let alignment = alignmentFromText $ attrValue atNameAlignment c
+      rowspan = RowSpan $ textToInt (attrValue atNameRowspan c) 1
+      colspan = ColSpan $ textToInt (attrValue atNameColspan c) 1
+      attr = filterAttrAttributes [atNameAlignment, atNameRowspan, atNameColspan] $ attrFromElement c
+  blocks <- getBlocks c
+  return $ Cell attr alignment rowspan colspan (toList blocks)
+
+getRows :: (PandocMonad m) => Element -> XMLReader m [Row]
+getRows e = mapM getRow $ childrenNamed "Row" e
+  where
+    getRow r = do
+      cells <- mapM getCell (childrenNamed "Cell" r)
+      return $ Row (attrFromElement r) cells
+
+parseCitations :: (PandocMonad m) => [Content] -> XMLReader m [Citation]
+parseCitations contents = do
+  maybecitations <- mapM getCitation contents
+  return $ catMaybes maybecitations
+  where
+    getCitation :: (PandocMonad m) => Content -> XMLReader m (Maybe Citation)
+    getCitation content = case (content) of
+      (Elem e) ->
+        if qName (elName e) == "Citation"
+          then do
+            p <- inlinesOfChildrenNamed tgNameCitationPrefix e
+            s <- inlinesOfChildrenNamed tgNameCitationSuffix e
+            return $
+              Just
+                ( Citation
+                    { citationId = attrValue "id" e,
+                      citationPrefix = toList p,
+                      citationSuffix = toList s,
+                      citationMode = case (attrValue atNameCitationMode e) of
+                        "AuthorInText" -> AuthorInText
+                        "SuppressAuthor" -> SuppressAuthor
+                        _ -> NormalCitation,
+                      citationNoteNum = textToInt (attrValue atNameCitationNoteNum e) 0,
+                      citationHash = textToInt (attrValue atNameCitationHash e) 0
+                    }
+                )
+          else do
+            return Nothing
+      _ -> do
+        return Nothing
+      where
+        inlinesOfChildrenNamed tag e = getInlines $ concatMap (\e' -> elContent e') (childrenNamed tag e)
+
+parseMaybeCaptionElement :: (PandocMonad m) => Maybe Element -> XMLReader m Caption
+parseMaybeCaptionElement Nothing = pure emptyCaption
+parseMaybeCaptionElement (Just e) = parseCaption $ elContent e
+
+parseCaption :: (PandocMonad m) => [Content] -> XMLReader m Caption
+parseCaption contents =
+  let (maybe_shortcaption_el, caption_contents) = partitionFirstChildNamed tgNameShortCaption contents
+   in do
+        blocks <- parseBlocks caption_contents
+        case (maybe_shortcaption_el) of
+          Just shortcaption_el -> do
+            short_caption <- getInlines (elContent shortcaption_el)
+            return $ caption (Just $ toList short_caption) blocks
+          Nothing -> return $ caption Nothing blocks
+
+parseDefinitionListItem :: (PandocMonad m) => [Content] -> XMLReader m (Inlines, [Blocks])
+parseDefinitionListItem contents = do
+  let term_contents = getContentsOfElements (isElementNamed tgNameDefListTerm) contents
+      defs_elements = elementContents $ filter (isElementNamed tgNameDefListDef) contents
+  term_inlines <- getInlines (concat term_contents)
+  defs <- mapM getBlocks defs_elements
+  return (term_inlines, defs)
+
+elementContents :: [Content] -> [Element]
+elementContents contents = mapMaybe toElement contents
+  where
+    toElement :: Content -> Maybe Element
+    toElement (Elem e) = Just e
+    toElement _ = Nothing
+
+isElementNamed :: Text -> Content -> Bool
+isElementNamed t c = case (c) of
+  Elem e -> t == elementName e
+  _ -> False
+
+childrenNamed :: Text -> Element -> [Element]
+childrenNamed tag e = elementContents $ filter (isElementNamed tag) (elContent e)
+
+elementsWithNames :: S.Set Text -> [Content] -> [Element]
+elementsWithNames tags contents = mapMaybe isElementWithNameInSet contents
+  where
+    isElementWithNameInSet c = case (c) of
+      Elem el ->
+        if (elementName el) `S.member` tags
+          then Just el
+          else Nothing
+      _ -> Nothing
+
+partitionFirstChildNamed :: Text -> [Content] -> (Maybe Element, [Content])
+partitionFirstChildNamed tag contents = case (contents) of
+  (Text (CData _ s _) : rest) ->
+    if T.all isSpace s
+      then partitionFirstChildNamed tag rest
+      else (Nothing, contents)
+  (Elem e : rest) ->
+    if tag == elementName e
+      then (Just e, rest)
+      else (Nothing, contents)
+  _ -> (Nothing, contents)
+
+type PandocAttr = (Text, [Text], [(Text, Text)])
+
+filterAttributes :: S.Set Text -> [(Text, Text)] -> [(Text, Text)]
+filterAttributes to_be_removed a = filter keep_attr a
+  where
+    keep_attr (k, _) = not (k `S.member` to_be_removed)
+
+filterAttrAttributes :: [Text] -> PandocAttr -> PandocAttr
+filterAttrAttributes to_be_removed (idn, classes, a) = (idn, classes, filtered)
+  where
+    filtered = filterAttributes (S.fromList to_be_removed) a
+
+attrFromElement :: Element -> PandocAttr
+attrFromElement e = filterAttrAttributes ["id", "class"] (idn, classes, attributes)
+  where
+    idn = attrValue "id" e
+    classes = T.words $ attrValue "class" e
+    attributes = map (\a -> (qName $ attrKey a, attrVal a)) $ elAttribs e
+
+addMeta :: (PandocMonad m) => (ToMetaValue a) => Text -> a -> XMLReader m ()
+addMeta field val = modify (setMeta field val)
+
+instance HasMeta XMLReaderState where
+  setMeta field v s = s {xmlMeta = setMeta field v (xmlMeta s)}
+
+  deleteMeta field s = s {xmlMeta = deleteMeta field (xmlMeta s)}
+
+parseMetaMapEntry :: (PandocMonad m) => Element -> XMLReader m (Maybe (Text, MetaValue))
+parseMetaMapEntry e =
+  let key = attrValue atNameMetaMapEntryKey e
+   in case (key) of
+        "" -> pure Nothing
+        k -> do
+          maybe_value <- parseMetaMapEntryContents $ elContent e
+          case (maybe_value) of
+            Nothing -> return Nothing
+            Just v -> return $ Just (k, v)
+
+parseMetaMapEntryContents :: (PandocMonad m) => [Content] -> XMLReader m (Maybe MetaValue)
+parseMetaMapEntryContents cs = msum <$> mapM parseMeta cs
+
+getElementText :: Element -> T.Text
+getElementText el = T.concat [cdData c | Text c <- elContent el]
+
+parseMeta :: (PandocMonad m) => Content -> XMLReader m (Maybe MetaValue)
+parseMeta (Text (CData CDataRaw _ _)) = return Nothing
+parseMeta (Text (CData _ s _)) =
+  if T.all isSpace s
+    then return Nothing
+    else do
+      throwError $ PandocXMLError "" "non-space characters out of inline context in metadata"
+parseMeta (CRef x) =
+  throwError $ PandocXMLError "" ("reference \"" <> x <> "\" out of inline context")
+parseMeta (Elem e) = do
+  let name = elementName e
+   in case (name) of
+        "MetaBool" -> case (attrValue atNameMetaBoolValue e) of
+          "true" -> return $ Just $ MetaBool True
+          _ -> return $ Just $ MetaBool False
+        "MetaString" -> return $ Just $ MetaString (getElementText e)
+        "MetaInlines" -> do
+          inlines <- getInlines (elContent e)
+          return $ Just $ MetaInlines $ toList inlines
+        "MetaBlocks" -> do
+          blocks <- getBlocks e
+          return $ Just $ MetaBlocks $ toList blocks
+        "MetaList" -> do
+          maybe_items <- mapM parseMeta $ elContent e
+          let items = catMaybes maybe_items
+           in -- TODO: report empty MetaList?
+              return $ Just $ MetaList items
+        "MetaMap" ->
+          let entry_els = childrenNamed tgNameMetaMapEntry e
+           in do
+                entries <- catMaybes <$> mapM parseMetaMapEntry entry_els
+                if null entries
+                  then
+                    -- TODO: report empty MetaMap
+                    return Nothing
+                  else return $ Just $ MetaMap $ M.fromList entries
+        _ -> do
+          throwError $ PandocXMLError "" ("unexpected element \"" <> name <> "\" in metadata")
diff --git a/src/Text/Pandoc/Readers/Xlsx.hs b/src/Text/Pandoc/Readers/Xlsx.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Readers/Xlsx.hs
@@ -0,0 +1,40 @@
+{-# LANGUAGE OverloadedStrings #-}
+{- |
+   Module      : Text.Pandoc.Readers.Xlsx
+   Copyright   : © 2025 Anton Antic
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : Anton Antic <anton@everworker.ai>
+   Stability   : alpha
+   Portability : portable
+
+Conversion of XLSX (Excel spreadsheet) documents to 'Pandoc' document.
+-}
+module Text.Pandoc.Readers.Xlsx (readXlsx) where
+
+import qualified Data.ByteString.Lazy as B
+import qualified Data.Text as T
+import Codec.Archive.Zip (toArchiveOrFail)
+import Control.Monad.Except (throwError)
+import Text.Pandoc.Class.PandocMonad (PandocMonad)
+import Text.Pandoc.Definition (Pandoc(..))
+import Text.Pandoc.Error (PandocError(..))
+import Text.Pandoc.Options (ReaderOptions)
+import Text.Pandoc.Readers.Xlsx.Parse (archiveToXlsx)
+import Text.Pandoc.Readers.Xlsx.Sheets (xlsxToOutput)
+
+-- | Read XLSX file into Pandoc AST
+readXlsx :: PandocMonad m => ReaderOptions -> B.ByteString -> m Pandoc
+readXlsx opts bytes =
+  case toArchiveOrFail bytes of
+    Right archive ->
+      case archiveToXlsx archive of
+        Right xlsx -> do
+          let (meta, blocks) = xlsxToOutput opts xlsx
+          return $ Pandoc meta blocks
+        Left err ->
+          throwError $ PandocParseError $ "Failed to parse XLSX: " <> err
+
+    Left err ->
+      throwError $ PandocParseError $
+        "Failed to unpack XLSX archive: " <> T.pack err
diff --git a/src/Text/Pandoc/Readers/Xlsx/Cells.hs b/src/Text/Pandoc/Readers/Xlsx/Cells.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Readers/Xlsx/Cells.hs
@@ -0,0 +1,63 @@
+{-# LANGUAGE OverloadedStrings #-}
+{- |
+   Module      : Text.Pandoc.Readers.Xlsx.Cells
+   Copyright   : © 2025 Anton Antic
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : Anton Antic <anton@everworker.ai>
+   Stability   : alpha
+   Portability : portable
+
+Cell types and parsing for XLSX.
+-}
+module Text.Pandoc.Readers.Xlsx.Cells
+  ( CellRef(..)
+  , XlsxCell(..)
+  , CellValue(..)
+  , parseCellRef
+  ) where
+
+import qualified Data.Text as T
+import Data.Text (Text)
+import Data.Char (ord, isAlpha)
+import Text.Read (readMaybe)
+
+-- | Cell reference (A1 notation)
+data CellRef = CellRef
+  { cellRefCol :: Int    -- 1-based (A=1, B=2, ..., AA=27)
+  , cellRefRow :: Int    -- 1-based
+  } deriving (Show, Eq, Ord)
+
+-- | Cell value types
+data CellValue
+  = TextValue Text
+  | NumberValue Double
+  | EmptyValue
+  deriving (Show, Eq)
+
+-- | Parsed cell
+data XlsxCell = XlsxCell
+  { cellRef :: CellRef
+  , cellValue :: CellValue
+  , cellBold :: Bool
+  , cellItalic :: Bool
+  } deriving (Show)
+
+-- | Parse cell reference (A1 → CellRef)
+parseCellRef :: Text -> Either Text CellRef
+parseCellRef ref = do
+  let (colStr, rowStr) = T.span isAlpha ref
+
+  row <- case readMaybe (T.unpack rowStr) of
+    Just r | r > 0 -> Right r
+    _ -> Left $ "Invalid row: " <> rowStr
+
+  col <- parseColumn colStr
+
+  return $ CellRef col row
+
+-- | Parse column (A=1, Z=26, AA=27, etc.)
+parseColumn :: Text -> Either Text Int
+parseColumn colStr
+  | T.null colStr = Left "Empty column"
+  | otherwise = Right $ T.foldl' (\acc c -> acc * 26 + (ord c - ord 'A' + 1)) 0 colStr
diff --git a/src/Text/Pandoc/Readers/Xlsx/Parse.hs b/src/Text/Pandoc/Readers/Xlsx/Parse.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Readers/Xlsx/Parse.hs
@@ -0,0 +1,296 @@
+{-# LANGUAGE OverloadedStrings #-}
+{- |
+   Module      : Text.Pandoc.Readers.Xlsx.Parse
+   Copyright   : © 2025 Anton Antic
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : Anton Antic <anton@everworker.ai>
+   Stability   : alpha
+   Portability : portable
+
+Parsing of XLSX archive to intermediate representation.
+-}
+module Text.Pandoc.Readers.Xlsx.Parse
+  ( Xlsx(..)
+  , XlsxWorkbook(..)
+  , XlsxSheet(..)
+  , SheetId(..)
+  , SharedStrings
+  , Styles(..)
+  , FontInfo(..)
+  , archiveToXlsx
+  ) where
+
+import Codec.Archive.Zip (Archive, Entry, findEntryByPath, fromEntry)
+import Data.List (find)
+import qualified Data.Map.Strict as M
+import Data.Maybe (mapMaybe, fromMaybe)
+import qualified Data.Text as T
+import qualified Data.Text.Lazy.Encoding as TL
+import Data.Text (Text)
+import qualified Data.Vector as V
+import System.FilePath (splitFileName)
+import Text.Pandoc.Readers.OOXML.Shared
+import Text.Pandoc.Readers.Xlsx.Cells
+import Text.Pandoc.XML.Light
+import Text.Read (readMaybe)
+
+-- | Sheet identifier
+newtype SheetId = SheetId Int deriving (Show, Eq, Ord)
+
+-- | Shared strings table (Vector for O(1) lookup)
+type SharedStrings = V.Vector Text
+
+-- | Font information
+data FontInfo = FontInfo
+  { fontBold :: Bool
+  , fontItalic :: Bool
+  , fontUnderline :: Bool
+  } deriving (Show)
+
+-- | Style information
+data Styles = Styles
+  { styleFonts :: V.Vector FontInfo
+  } deriving (Show)
+
+-- | Complete XLSX document
+data Xlsx = Xlsx
+  { xlsxWorkbook :: XlsxWorkbook
+  , xlsxSheets :: [XlsxSheet]
+  , xlsxSharedStrings :: SharedStrings
+  , xlsxStyles :: Styles
+  } deriving (Show)
+
+-- | Workbook information
+data XlsxWorkbook = XlsxWorkbook
+  { workbookSheetNames :: [(SheetId, Text, Text)]  -- (id, name, relId)
+  } deriving (Show)
+
+-- | Individual worksheet
+data XlsxSheet = XlsxSheet
+  { sheetId :: SheetId
+  , sheetName :: Text
+  , sheetCells :: M.Map CellRef XlsxCell
+  } deriving (Show)
+
+-- | Parse XLSX archive
+archiveToXlsx :: Archive -> Either Text Xlsx
+archiveToXlsx archive = do
+  -- Find and parse workbook.xml
+  workbookPath <- getWorkbookXmlPath archive
+  workbookElem <- loadXMLFromArchive archive workbookPath
+  workbook <- parseWorkbook workbookElem
+    `addContext` ("Parsing workbook.xml from: " <> T.pack workbookPath)
+
+  -- Load workbook relationships
+  workbookRels <- loadRelationships archive (relsPathFor workbookPath)
+
+  -- Parse shared strings (look for sharedStrings relationship)
+  sharedStrings <- case findRelWithTarget workbookRels "sharedStrings" of
+    Just (_, target) -> do
+      let path = "xl/" ++ T.unpack target
+      el <- loadXMLFromArchive archive path
+      parseSharedStrings el
+    Nothing -> Right V.empty
+
+  -- Parse styles
+  styles <- case findRelWithTarget workbookRels "styles" of
+    Just (_, target) -> do
+      let path = "xl/" ++ T.unpack target
+      el <- loadXMLFromArchive archive path
+      parseStyles el
+    Nothing -> Right $ Styles V.empty
+
+  -- Parse worksheets
+  sheets <- mapM (\sheetInfo -> parseSheet archive workbookRels sharedStrings styles sheetInfo)
+                 (workbookSheetNames workbook)
+
+  return $ Xlsx workbook sheets sharedStrings styles
+
+-- | Find workbook.xml via root relationships
+getWorkbookXmlPath :: Archive -> Either Text FilePath
+getWorkbookXmlPath archive = do
+  relsEntry <- maybeToEither "Missing _rels/.rels" $
+               findEntryByPath "_rels/.rels" archive
+  relsElem <- parseXMLFromEntry relsEntry
+
+  let relElems = onlyElems $ elContent relsElem
+  case find isOfficeDocRel relElems of
+    Nothing -> Left "No workbook.xml relationship found"
+    Just rel -> do
+      target <- maybeToEither "Missing Target" $ findAttr (unqual "Target") rel
+      return $ T.unpack target
+  where
+    isOfficeDocRel el =
+      case (findAttr (unqual "Type") el, findAttr (unqual "Target") el) of
+        (Just relType, Just target) ->
+          "officeDocument" `T.isInfixOf` relType && "workbook" `T.isInfixOf` target
+        _ -> False
+
+-- | Parse workbook.xml
+parseWorkbook :: Element -> Either Text XlsxWorkbook
+parseWorkbook wbElem = do
+  let ns = elemToNameSpaces wbElem
+
+  -- Find sheets element (match by local name only)
+  sheets <- maybeToEither "Missing <sheets>" $
+            find (\e -> qName (elName e) == "sheets") (onlyElems $ elContent wbElem)
+
+  let sheetElems = filter (\e -> qName (elName e) == "sheet") (onlyElems $ elContent sheets)
+  sheetRefs <- mapM (parseSheetRef ns) (zip [1..] sheetElems)
+
+  return $ XlsxWorkbook sheetRefs
+
+parseSheetRef :: NameSpaces -> (Int, Element) -> Either Text (SheetId, Text, Text)
+parseSheetRef ns (idx, sheetElem) = do
+  let name = fromMaybe ("Sheet" <> T.pack (show idx)) $
+             findAttr (unqual "name") sheetElem
+  relId <- maybeToEither "Missing r:id" $
+           findAttrByName ns "r" "id" sheetElem
+  return (SheetId idx, name, relId)
+
+-- | Parse shared strings
+parseSharedStrings :: Element -> Either Text SharedStrings
+parseSharedStrings sstElem = do
+  let siElems = filter (\e -> qName (elName e) == "si") (onlyElems $ elContent sstElem)
+      strings = map extractString siElems
+  return $ V.fromList strings
+  where
+    extractString siElem =
+      case find (\e -> qName (elName e) == "t") (onlyElems $ elContent siElem) of
+        Just tElem -> strContent tElem
+        Nothing -> getAllText siElem
+
+-- | Parse styles (fonts only for MVP)
+parseStyles :: Element -> Either Text Styles
+parseStyles stylesElem = do
+  -- Parse fonts (match by local name)
+  let fontsElem = find (\e -> qName (elName e) == "fonts") (onlyElems $ elContent stylesElem)
+      fontElems = maybe [] (\fe -> filter (\e -> qName (elName e) == "font") (onlyElems $ elContent fe)) fontsElem
+      fonts = V.fromList $ map (parseFont mempty) fontElems
+
+  return $ Styles fonts
+
+parseFont :: NameSpaces -> Element -> FontInfo
+parseFont _ns fontElem =
+  FontInfo
+    { fontBold = any (\e -> qName (elName e) == "b") (onlyElems $ elContent fontElem)
+    , fontItalic = any (\e -> qName (elName e) == "i") (onlyElems $ elContent fontElem)
+    , fontUnderline = any (\e -> qName (elName e) == "u") (onlyElems $ elContent fontElem)
+    }
+
+-- | Parse individual worksheet
+parseSheet :: Archive -> [(Text, Text)] -> SharedStrings -> Styles -> (SheetId, Text, Text) -> Either Text XlsxSheet
+parseSheet archive rels sharedStrings styles (sid, name, relId) = do
+  target <- maybeToEither ("Sheet relationship not found: " <> relId) $
+            lookup relId rels
+
+  let sheetPath = "xl/" ++ T.unpack target
+  sheetElem <- loadXMLFromArchive archive sheetPath
+
+  cells <- parseSheetCells sheetElem sharedStrings styles
+
+  return $ XlsxSheet sid name cells
+
+-- | Parse sheet cells
+parseSheetCells :: Element -> SharedStrings -> Styles -> Either Text (M.Map CellRef XlsxCell)
+parseSheetCells sheetElem sharedStrings styles = do
+  -- Find sheetData by local name
+  case find (\e -> qName (elName e) == "sheetData") (onlyElems $ elContent sheetElem) of
+    Nothing -> return M.empty
+    Just sheetData -> do
+      let rowElems = filter (\e -> qName (elName e) == "row") (onlyElems $ elContent sheetData)
+          cellElems = concatMap (\r -> filter (\e -> qName (elName e) == "c") (onlyElems $ elContent r)) rowElems
+          cells = mapMaybe (parseCell sharedStrings styles) cellElems
+      return $ M.fromList [(cellRef c, c) | c <- cells]
+
+-- | Parse individual cell
+parseCell :: SharedStrings -> Styles -> Element -> Maybe XlsxCell
+parseCell sharedStrings styles cElem = do
+  -- Get cell reference
+  refText <- findAttr (unqual "r") cElem
+  cellRefParsed <- either (const Nothing) Just $ parseCellRef refText
+
+  -- Get cell type (default to number if missing)
+  let cellType = fromMaybe "" $ findAttr (unqual "t") cElem
+      styleIdx = findAttr (unqual "s") cElem >>= readMaybe . T.unpack
+
+  -- Get value (match by local name)
+  let vElem = find (\e -> qName (elName e) == "v") (onlyElems $ elContent cElem)
+      vText = maybe "" strContent vElem
+
+  -- Parse value based on type
+  let value = if cellType == "s"
+              then
+                -- Shared string
+                case readMaybe (T.unpack vText) of
+                  Just idx | idx >= 0 && idx < V.length sharedStrings ->
+                    TextValue (sharedStrings V.! idx)
+                  _ -> EmptyValue
+              else if T.null vText
+                then EmptyValue
+                else
+                  -- Number
+                  case readMaybe (T.unpack vText) of
+                    Just n -> NumberValue n
+                    Nothing -> TextValue vText
+
+  -- Get formatting from style
+  let (bold, italic) = case styleIdx of
+        Just idx | idx >= 0 && idx < V.length (styleFonts styles) ->
+          let font = styleFonts styles V.! idx
+           in (fontBold font, fontItalic font)
+        _ -> (False, False)
+
+  return $ XlsxCell cellRefParsed value bold italic
+
+-- Helper functions
+loadXMLFromArchive :: Archive -> FilePath -> Either Text Element
+loadXMLFromArchive archive path = do
+  entry <- maybeToEither ("Entry not found: " <> T.pack path) $
+           findEntryByPath path archive
+  parseXMLFromEntry entry
+
+parseXMLFromEntry :: Entry -> Either Text Element
+parseXMLFromEntry entry =
+  let lazyText = TL.decodeUtf8 $ fromEntry entry
+   in parseXMLElement lazyText
+
+loadRelationships :: Archive -> FilePath -> Either Text [(Text, Text)]
+loadRelationships archive relsPath =
+  case findEntryByPath relsPath archive of
+    Nothing -> Right []
+    Just entry -> do
+      relsElem <- parseXMLFromEntry entry
+      let relElems = onlyElems $ elContent relsElem
+      return $ mapMaybe extractRel relElems
+  where
+    extractRel el = do
+      relId <- findAttr (unqual "Id") el
+      target <- findAttr (unqual "Target") el
+      return (relId, target)
+
+relsPathFor :: FilePath -> FilePath
+relsPathFor path =
+  let (dir, file) = splitFileName path
+   in dir ++ "/_rels/" ++ file ++ ".rels"
+
+findRelWithTarget :: [(Text, Text)] -> Text -> Maybe (Text, Text)
+findRelWithTarget rels targetName =
+  find (\(_, target) -> targetName `T.isInfixOf` target) rels
+
+maybeToEither :: Text -> Maybe a -> Either Text a
+maybeToEither err Nothing = Left err
+maybeToEither _ (Just x) = Right x
+
+getAllText :: Element -> Text
+getAllText el =
+  let textFromContent (Text cdata) = cdData cdata
+      textFromContent (Elem e) = getAllText e
+      textFromContent _ = ""
+      texts = map textFromContent (elContent el)
+   in T.unwords $ filter (not . T.null) texts
+
+addContext :: Either Text a -> Text -> Either Text a
+addContext (Right x) _ = Right x
+addContext (Left err) ctx = Left (err <> " (context: " <> ctx <> ")")
diff --git a/src/Text/Pandoc/Readers/Xlsx/Sheets.hs b/src/Text/Pandoc/Readers/Xlsx/Sheets.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Readers/Xlsx/Sheets.hs
@@ -0,0 +1,112 @@
+{-# LANGUAGE OverloadedStrings #-}
+{- |
+   Module      : Text.Pandoc.Readers.Xlsx.Sheets
+   Copyright   : © 2025 Anton Antic
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : Anton Antic <anton@everworker.ai>
+   Stability   : alpha
+   Portability : portable
+
+Conversion of XLSX sheets to Pandoc AST.
+-}
+module Text.Pandoc.Readers.Xlsx.Sheets
+  ( xlsxToOutput
+  ) where
+
+import qualified Data.Map.Strict as M
+import qualified Data.Text as T
+import Data.List (sort, dropWhileEnd)
+import Data.Char (isSpace)
+import Text.Pandoc.Definition
+import Text.Pandoc.Options (ReaderOptions)
+import Text.Pandoc.Readers.Xlsx.Parse
+import Text.Pandoc.Readers.Xlsx.Cells
+import qualified Text.Pandoc.Builder as B
+
+-- | Convert XLSX to Pandoc output
+xlsxToOutput :: ReaderOptions -> Xlsx -> (Meta, [Block])
+xlsxToOutput _opts xlsx =
+  let sheets = xlsxSheets xlsx
+      sheetBlocks = concatMap sheetToBlocks sheets
+   in (mempty, sheetBlocks)
+
+-- | Convert sheet to blocks (header + table)
+sheetToBlocks :: XlsxSheet -> [Block]
+sheetToBlocks sheet =
+  let SheetId n = sheetId sheet
+      name = sheetName sheet
+      sheetIdent = "sheet-" <> T.pack (show n)
+      header = Header 2 (sheetIdent, [], []) (B.toList (B.text name))
+
+      -- Convert cells to table
+      tableBlock = case cellsToTable sheet of
+        Just tbl -> [tbl]
+        Nothing -> []  -- Empty sheet
+   in header : tableBlock
+
+-- | Convert cells to Pandoc Table
+cellsToTable :: XlsxSheet -> Maybe Block
+cellsToTable sheet
+  | M.null (sheetCells sheet) = Nothing
+  | otherwise =
+      let cells = sheetCells sheet
+          -- Get bounds
+          refs = sort $ M.keys cells
+          minCol = minimum $ map cellRefCol refs
+          maxCol = maximum $ map cellRefCol refs
+          minRow = minimum $ map cellRefRow refs
+          maxRow = maximum $ map cellRefRow refs
+
+          -- Build dense grid
+          grid = [ [ M.lookup (CellRef col row) cells
+                   | col <- [minCol..maxCol]
+                   ]
+                 | row <- [minRow..maxRow]
+                 ]
+
+          -- First row is header (simple heuristic)
+          (headerRow, bodyRows) = case grid of
+            (h:bs) -> (h, bs)
+            [] -> ([], [])
+
+          -- Filter out trailing empty rows (rows with only whitespace)
+          filteredBodyRows = dropWhileEnd isEmptyRow bodyRows
+
+          makeCell mcell = case mcell of
+            Just cell ->
+              let inlines = cellToInlines cell
+               in Cell nullAttr AlignDefault (RowSpan 1) (ColSpan 1) [Plain inlines]
+            Nothing ->
+              Cell nullAttr AlignDefault (RowSpan 1) (ColSpan 1) [Plain []]
+
+          numCols = length headerRow
+          colSpec = replicate numCols (AlignDefault, ColWidthDefault)
+          thead = TableHead nullAttr [Row nullAttr $ map makeCell headerRow]
+          tbody = [TableBody nullAttr 0 [] $ map (Row nullAttr . map makeCell) filteredBodyRows]
+          tfoot = TableFoot nullAttr []
+
+       in Just $ Table nullAttr (Caption Nothing []) colSpec thead tbody tfoot
+
+-- | Check if a row contains only whitespace or empty cells
+isEmptyRow :: [Maybe XlsxCell] -> Bool
+isEmptyRow = all isEmptyCell
+  where
+    isEmptyCell Nothing = True
+    isEmptyCell (Just cell) = case cellValue cell of
+      EmptyValue -> True
+      TextValue t -> T.all isSpace t
+      NumberValue _ -> False
+
+-- | Convert cell to Pandoc inlines
+cellToInlines :: XlsxCell -> [Inline]
+cellToInlines cell =
+  let base = case cellValue cell of
+        TextValue t -> B.toList $ B.text t
+        NumberValue n -> [Str $ T.pack $ show n]
+        EmptyValue -> []
+
+      applyBold inls = if cellBold cell then [Strong inls] else inls
+      applyItalic inls = if cellItalic cell then [Emph inls] else inls
+
+   in applyItalic $ applyBold base
diff --git a/src/Text/Pandoc/RoffChar.hs b/src/Text/Pandoc/RoffChar.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/RoffChar.hs
@@ -0,0 +1,423 @@
+{-# LANGUAGE OverloadedStrings #-}
+{- |
+   Module      : Text.Pandoc.RoffChar
+   Copyright   : Copyright (C) 2007-2024 John MacFarlane
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : John MacFarlane <jgm@berkeley.edu>
+   Stability   : alpha
+   Portability : portable
+
+Roff character escaping/unescaping.
+-}
+
+module Text.Pandoc.RoffChar (
+    standardEscapes
+  , characterCodes
+  , combiningAccents
+  ) where
+import qualified Data.Text as T
+
+-- | These are the escapes specifically mentioned in groff_man(7),
+-- plus @ and ellipsis. We use the \(aq form when possible (with
+-- two-letter escapes), because these are compatible with all forms
+-- of roff (#10716).
+standardEscapes :: [(Char, T.Text)]
+standardEscapes =
+  [ ('\160', "\\ ")
+  , ('\'', "\\(aq")
+  , ('‘', "\\(oq")
+  , ('’', "\\(cq")
+  , ('"', "\\(dq")
+  , ('“', "\\(lq")
+  , ('”', "\\(rq")
+  , ('—', "\\(em")
+  , ('–', "\\(en")
+  , ('`', "\\(ga")
+  , ('^', "\\(ha")
+  , ('~', "\\(ti")
+  , ('\\', "\\(rs")
+  , ('@', "\\(at") -- because we use @ as a table and math delimiter
+  , ('\x2026', "\\&...")  -- because u2026 doesn't render on tty
+  ]
+
+characterCodes :: [(Char, T.Text)]
+characterCodes =
+  [ ('Ð', "-D")
+  , ('ð', "Sd")
+  , ('Þ', "TP")
+  , ('þ', "Tp")
+  , ('ß', "ss")
+  , ('ﬀ', "ff")
+  , ('ﬁ', "fi")
+  , ('ﬂ', "fl")
+  , ('ﬃ', "Fi")
+  , ('ﬄ', "Fl")
+  , ('Ł', "/L")
+  , ('ł', "/l")
+  , ('Ø', "/O")
+  , ('ø', "/o")
+  , ('Æ', "AE")
+  , ('æ', "ae")
+  , ('Œ', "OE")
+  , ('œ', "oe")
+  , ('Ĳ', "IJ")
+  , ('ĳ', "ij")
+  , ('ı', ".i")
+  , ('ȷ', ".j")
+  , ('Á', "'A")
+  , ('Ć', "'C")
+  , ('É', "'E")
+  , ('Í', "'I")
+  , ('Ó', "'O")
+  , ('Ú', "'U")
+  , ('Ý', "'Y")
+  , ('á', "'a")
+  , ('ć', "'c")
+  , ('é', "'e")
+  , ('í', "'i")
+  , ('ó', "'o")
+  , ('ú', "'u")
+  , ('ý', "'y")
+  , ('Ä', ":A")
+  , ('Ë', ":E")
+  , ('Ï', ":I")
+  , ('Ö', ":O")
+  , ('Ü', ":U")
+  , ('Ÿ', ":Y")
+  , ('ä', ":a")
+  , ('ë', ":e")
+  , ('ï', ":i")
+  , ('ö', ":o")
+  , ('ü', ":u")
+  , ('ÿ', ":y")
+  , ('Â', "^A")
+  , ('Ê', "^E")
+  , ('Î', "^I")
+  , ('Ô', "^O")
+  , ('Û', "^U")
+  , ('â', "^a")
+  , ('ê', "^e")
+  , ('î', "^i")
+  , ('ô', "^o")
+  , ('û', "^u")
+  , ('À', "`A")
+  , ('È', "`E")
+  , ('Ì', "`I")
+  , ('Ò', "`O")
+  , ('Ù', "`U")
+  , ('à', "`a")
+  , ('è', "`e")
+  , ('ì', "`i")
+  , ('ò', "`o")
+  , ('ù', "`u")
+  , ('Ã', "~A")
+  , ('Ñ', "~N")
+  , ('Õ', "~O")
+  , ('ã', "~a")
+  , ('ñ', "~n")
+  , ('õ', "~o")
+  , ('Š', "vS")
+  , ('š', "vs")
+  , ('Ž', "vZ")
+  , ('ž', "vz")
+  , ('Ç', ",C")
+  , ('ç', ",c")
+  , ('Å', "oA")
+  , ('å', "oa")
+  , ('˝', "a\"")
+  , ('¯', "a-")
+  , ('˙', "a.")
+  , ('^', "a^")
+  , ('´', "aa")
+  , ('`', "ga")
+  , ('˘', "ab")
+  , ('¸', "ac")
+  , ('¨', "ad")
+  , ('ˇ', "ah")
+  , ('˚', "ao")
+  , ('~', "a~")
+  , ('˛', "ho")
+  , ('^', "ha")
+  , ('~', "ti")
+  , ('„', "Bq")
+  , ('‚', "bq")
+  , ('“', "lq")
+  , ('”', "rq")
+  , ('‘', "oq")
+  , ('’', "cq")
+  , ('\'', "aq")
+  , ('"', "dq")
+  , ('«', "Fo")
+  , ('»', "Fc")
+  , ('‹', "fo")
+  , ('›', "fc")
+  , ('¡', "r!")
+  , ('¿', "r?")
+  , ('—', "em")
+  , ('–', "en")
+  , ('‐', "hy")
+  , ('[', "lB")
+  , (']', "rB")
+  , ('{', "lC")
+  , ('}', "rC")
+  , ('⟨', "la")
+  , ('⟩', "ra")
+  , ('⎪', "bv")
+  , ('⎪', "braceex")
+  , ('⎡', "bracketlefttp")
+  , ('⎣', "bracketleftbt")
+  , ('⎢', "bracketleftex")
+  , ('⎤', "bracketrighttp")
+  , ('⎦', "bracketrightbt")
+  , ('⎥', "bracketrightex")
+  , ('╭', "lt")
+  , ('⎧', "bracelefttp")
+  , ('┥', "lk")
+  , ('⎨', "braceleftmid")
+  , ('╰', "lb")
+  , ('⎩', "braceleftbt")
+  , ('⎪', "braceleftex")
+  , ('╮', "rt")
+  , ('⎫', "bracerighttp")
+  , ('┝', "rk")
+  , ('⎬', "bracerightmid")
+  , ('╯', "rb")
+  , ('⎭', "bracerightbt")
+  , ('⎪', "bracerightex")
+  , ('⎛', "parenlefttp")
+  , ('⎝', "parenleftbt")
+  , ('⎜', "parenleftex")
+  , ('⎞', "parenrighttp")
+  , ('⎠', "parenrightbt")
+  , ('⎟', "parenrightex")
+  , ('←', "<-")
+  , ('→', "->")
+  , ('↔', "<>")
+  , ('↓', "da")
+  , ('↑', "ua")
+  , ('↕', "va")
+  , ('⇐', "lA")
+  , ('⇒', "rA")
+  , ('⇔', "hA")
+  , ('⇓', "dA")
+  , ('⇑', "uA")
+  , ('⇕', "vA")
+  , ('⎯', "an")
+  , ('|', "ba")
+  , ('│', "br")
+  , ('_', "ul")
+  , ('‾', "rn")
+  , ('_', "ru")
+  , ('¦', "bb")
+  , ('/', "sl")
+  , ('\\', "rs")
+  , ('○', "ci")
+  , ('·', "bu")
+  , ('‡', "dd")
+  , ('†', "dg")
+  , ('◊', "lz")
+  , ('□', "sq")
+  , ('¶', "ps")
+  , ('§', "sc")
+  , ('☜', "lh")
+  , ('☞', "rh")
+  , ('@', "at")
+  , ('#', "sh")
+  , ('↵', "CR")
+  , ('✓', "OK")
+  , ('©', "co")
+  , ('®', "rg")
+  , ('™', "tm")
+  , ('$', "Do")
+  , ('¢', "ct")
+  , ('€', "eu")
+  , ('€', "Eu")
+  , ('¥', "Ye")
+  , ('£', "Po")
+  , ('¤', "Cs")
+  , ('ƒ', "Fn")
+  , ('°', "de")
+  , ('‰', "%0")
+  , ('′', "fm")
+  , ('″', "sd")
+  , ('µ', "mc")
+  , ('ª', "Of")
+  , ('º', "Om")
+  , ('∧', "AN")
+  , ('∨', "OR")
+  , ('¬', "no")
+  , ('¬', "tno")
+  , ('∃', "te")
+  , ('∀', "fa")
+  , ('∋', "st")
+  , ('∴', "3d")
+  , ('∴', "tf")
+  , ('|', "or")
+  , ('½', "12")
+  , ('¼', "14")
+  , ('¾', "34")
+  , ('⅛', "18")
+  , ('⅜', "38")
+  , ('⅝', "58")
+  , ('⅞', "78")
+  , ('¹', "S1")
+  , ('²', "S2")
+  , ('³', "S3")
+  , ('+', "pl")
+  , ('−', "mi")
+  , ('∓', "-+")
+  , ('±', "+-")
+  , ('±', "t+-")
+  , ('·', "pc")
+  , ('⋅', "md")
+  , ('×', "mu")
+  , ('×', "tmu")
+  , ('⊗', "c*")
+  , ('⊕', "c+")
+  , ('÷', "di")
+  , ('÷', "tdi")
+  , ('⁄', "f/")
+  , ('∗', "**")
+  , ('≤', "<=")
+  , ('≥', ">=")
+  , ('≪', "<<")
+  , ('≫', ">>")
+  , ('=', "eq")
+  , ('≠', "!=")
+  , ('≡', "==")
+  , ('≢', "ne")
+  , ('≅', "=~")
+  , ('≃', "|=")
+  , ('∼', "ap")
+  , ('≈', "~~")
+  , ('≈', "~=")
+  , ('∝', "pt")
+  , ('∅', "es")
+  , ('∈', "mo")
+  , ('∉', "nm")
+  , ('⊂', "sb")
+  , ('⊄', "nb")
+  , ('⊃', "sp")
+  , ('⊅', "nc")
+  , ('⊆', "ib")
+  , ('⊇', "ip")
+  , ('∩', "ca")
+  , ('∪', "cu")
+  , ('∠', "/_")
+  , ('⊥', "pp")
+  , ('∫', "is")
+  , ('∫', "integral")
+  , ('∑', "sum")
+  , ('∏', "product")
+  , ('∐', "coproduct")
+  , ('∇', "gr")
+  , ('√', "sr")
+  , ('√', "sqrt")
+  -- , "radicalex"
+  -- "sqrtex"
+  , ('⌈', "lc")
+  , ('⌉', "rc")
+  , ('⌊', "lf")
+  , ('⌋', "rf")
+  , ('∞', "if")
+  , ('ℵ', "Ah")
+  , ('ℑ', "Im")
+  , ('ℜ', "Re")
+  , ('℘', "wp")
+  , ('∂', "pd")
+  , ('ℏ', "-h")
+  , ('ℏ', "hbar")
+  , ('Α', "*A")
+  , ('Β', "*B")
+  , ('Γ', "*G")
+  , ('Δ', "*D")
+  , ('Ε', "*E")
+  , ('Ζ', "*Z")
+  , ('Η', "*Y")
+  , ('Θ', "*H")
+  , ('Ι', "*I")
+  , ('Κ', "*K")
+  , ('Λ', "*L")
+  , ('Μ', "*M")
+  , ('Ν', "*N")
+  , ('Ξ', "*C")
+  , ('Ο', "*O")
+  , ('Π', "*P")
+  , ('Ρ', "*R")
+  , ('Σ', "*S")
+  , ('Τ', "*T")
+  , ('Υ', "*U")
+  , ('Φ', "*F")
+  , ('Χ', "*X")
+  , ('Ψ', "*Q")
+  , ('Ω', "*W")
+  , ('α', "*a")
+  , ('β', "*b")
+  , ('γ', "*g")
+  , ('δ', "*d")
+  , ('ε', "*e")
+  , ('ζ', "*z")
+  , ('η', "*y")
+  , ('θ', "*h")
+  , ('ι', "*i")
+  , ('κ', "*k")
+  , ('λ', "*l")
+  , ('μ', "*m")
+  , ('ν', "*n")
+  , ('ξ', "*c")
+  , ('ο', "*o")
+  , ('π', "*p")
+  , ('ρ', "*r")
+  , ('ς', "ts")
+  , ('σ', "*s")
+  , ('τ', "*t")
+  , ('υ', "*u")
+  , ('ϕ', "*f")
+  , ('χ', "*x")
+  , ('ψ', "*q")
+  , ('ω', "*w")
+  , ('ϑ', "+h")
+  , ('φ', "+f")
+  , ('ϖ', "+p")
+  , ('ϵ', "+e")
+  , ('♣', "CL")
+  , ('♠', "SP")
+  , ('♥', "HE")
+  , ('♦', "DI")
+  , ('˝' , "a\"")
+  , ('¯', "a-")
+  , ('˙', "a.")
+  , ('^', "a^")
+  , ('´', "aa")
+  , ('`', "ga")
+  , ('˘', "ab")
+  , ('¸', "ac")
+  , ('¨', "ad")
+  , ('ˇ', "ah")
+  , ('˚', "ao")
+  , ('~', "a~")
+  , ('˛', "ho")
+  , ('^', "ha")
+  , ('~', "ti")
+  ]
+
+-- use like: \\[E a^ aa]
+combiningAccents :: [(Char, T.Text)]
+combiningAccents =
+  [ ('\779' , "a\"")
+  , ('\772', "a-")
+  , ('\775', "a.")
+  , ('\770', "a^")
+  , ('\769', "aa")
+  , ('\768', "ga")
+  , ('\774', "ab")
+  , ('\807', "ac")
+  , ('\776', "ad")
+  , ('\780', "ah")
+  , ('\778', "ao")
+  , ('\771', "a~")
+  , ('\808', "ho")
+  , ('\770', "ha")
+  , ('\771', "ti")
+  ]
diff --git a/src/Text/Pandoc/Scripting.hs b/src/Text/Pandoc/Scripting.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Scripting.hs
@@ -0,0 +1,63 @@
+{-# LANGUAGE OverloadedStrings    #-}
+{-# LANGUAGE ImpredicativeTypes   #-}
+{-# LANGUAGE ScopedTypeVariables  #-}
+{- |
+Module      : Text.Pandoc.Scripting
+Copyright   : © 2022-2024 Albert Krewinkel
+License     : GPL-2.0-or-later
+Maintainer  : Albert Krewinkel <albert+pandoc@tarleb.com>
+
+Central data structure for scripting engines.
+-}
+module Text.Pandoc.Scripting
+  ( ScriptingEngine (..)
+  , CustomComponents(..)
+  , noEngine
+  )
+where
+
+import Control.Monad.Except (throwError)
+import Control.Monad.IO.Class (MonadIO)
+import Data.Text (Text)
+import Text.Pandoc.Class.PandocMonad (PandocMonad)
+import Text.Pandoc.Definition (Pandoc)
+import Text.Pandoc.Error (PandocError (PandocNoScriptingEngine))
+import Text.Pandoc.Filter.Environment (Environment)
+import Text.Pandoc.Format (ExtensionsConfig)
+import Text.Pandoc.Readers (Reader)
+import Text.Pandoc.Writers (Writer)
+
+-- | A component of a custom reader/writer: a custom reader,
+-- a custom writer, a template for a custom writer, or a specification
+-- of the extensions used by a script and their default values.
+-- Note that a single script can contain all of these.
+data CustomComponents m =
+  CustomComponents
+  { customReader :: Maybe (Reader m)
+  , customWriter :: Maybe (Writer m)
+  , customTemplate :: Maybe Text
+  , customExtensions :: Maybe ExtensionsConfig
+  }
+
+-- | Structure to define a scripting engine.
+data ScriptingEngine = ScriptingEngine
+  { engineName :: Text   -- ^ Name of the engine.
+
+  , engineApplyFilter :: forall m. (PandocMonad m, MonadIO m)
+                      => Environment -> [String] -> FilePath
+                      -> Pandoc -> m Pandoc
+    -- ^ Use the scripting engine to run a filter.
+
+  , engineLoadCustom :: forall m. (PandocMonad m, MonadIO m)
+                     => FilePath -> m (CustomComponents m)
+    -- ^ Function to load a custom reader/writer from a script.
+  }
+
+noEngine :: ScriptingEngine
+noEngine = ScriptingEngine
+  { engineName = "none"
+  , engineApplyFilter = \_env _args _fp _doc ->
+      throwError PandocNoScriptingEngine
+  , engineLoadCustom = \_fp ->
+      throwError PandocNoScriptingEngine
+  }
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,25 +1,10 @@
+{-# LANGUAGE ScopedTypeVariables #-}
 {-# LANGUAGE OverloadedStrings #-}
-{-
-Copyright (C) 2011-2017 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 LambdaCase        #-}
+{-# LANGUAGE TupleSections     #-}
 {- |
    Module      : Text.Pandoc.SelfContained
-   Copyright   : Copyright (C) 2011-2017 John MacFarlane
+   Copyright   : Copyright (C) 2011-2024 John MacFarlane
    License     : GNU GPL, version 2 or above
 
    Maintainer  : John MacFarlane <jgm@berkeley.edu>
@@ -33,77 +18,96 @@
 module Text.Pandoc.SelfContained ( makeDataURI, makeSelfContained ) where
 import Codec.Compression.GZip as Gzip
 import Control.Applicative ((<|>))
-import Control.Monad.Except (throwError)
-import Control.Monad.Trans (lift)
 import Data.ByteString (ByteString)
-import Data.ByteString.Base64
+import Data.ByteString.Base64 (encode)
 import qualified Data.ByteString.Char8 as B
 import qualified Data.ByteString.Lazy as L
-import Data.Char (isAlphaNum, isAscii, toLower)
-import Data.List (isPrefixOf)
-import Data.Monoid ((<>))
+import qualified Data.Text as T
+import Data.Char (isAlphaNum, isAscii)
+import Crypto.Hash (hashWith, SHA1(SHA1))
 import Network.URI (escapeURIString)
 import System.FilePath (takeDirectory, takeExtension, (</>))
 import Text.HTML.TagSoup
-import Text.Pandoc.Class (PandocMonad (..), fetchItem, getInputFiles, report,
-                          setInputFiles)
-import Text.Pandoc.Error
+import Text.Pandoc.Class.PandocMonad (PandocMonad (..), fetchItem,
+                                      getInputFiles, report, setInputFiles)
 import Text.Pandoc.Logging
+import Text.Pandoc.Error (PandocError(..))
 import Text.Pandoc.MIME (MimeType)
-import Text.Pandoc.Shared (isURI, renderTags', trim)
-import Text.Pandoc.UTF8 (toString)
-import Text.Parsec (ParsecT, runParserT)
-import qualified Text.Parsec as P
+import Text.Pandoc.Shared (renderTags', trim, tshow, safeRead)
+import Text.Pandoc.URI (isURI)
+import Text.Pandoc.UTF8 (toString, toText, fromText)
+import Text.Pandoc.Parsing (ParsecT, runParserT)
+import qualified Text.Pandoc.Parsing as P
+import Control.Monad.Except (throwError, catchError)
+import Data.Either (lefts, rights)
+import Data.Maybe (isNothing)
+import qualified Data.Map as M
+import Control.Monad.State
 
 isOk :: Char -> Bool
 isOk c = isAscii c && isAlphaNum c
 
-makeDataURI :: (MimeType, ByteString) -> String
+makeDataURI :: (MimeType, ByteString) -> T.Text
 makeDataURI (mime, raw) =
   if textual
-     then "data:" ++ mime' ++ "," ++ escapeURIString isOk (toString raw)
-     else "data:" ++ mime' ++ ";base64," ++ toString (encode raw)
-  where textual = "text/" `Data.List.isPrefixOf` mime
-        mime' = if textual && ';' `notElem` mime
-                   then mime ++ ";charset=utf-8"
+     then "data:" <> mime' <> "," <> T.pack (escapeURIString isOk (toString raw))
+     else "data:" <> mime' <> ";base64," <> toText (encode raw')
+  where textual = "text/" `T.isPrefixOf` mime
+        raw' = if "+xml" `T.isSuffixOf` mime
+                  then B.filter (/= '\r') raw  -- strip off CRs
+                  else raw
+        mime' = if textual && T.any (== ';') mime
+                   then mime <> ";charset=utf-8"
                    else mime  -- mime type already has charset
 
-convertTags :: PandocMonad m => [Tag String] -> m [Tag String]
+isSourceAttribute :: T.Text -> (T.Text, T.Text) -> Bool
+isSourceAttribute tagname (x,_) =
+  x == "src" ||
+  x == "data-src" ||
+  (x == "href" && tagname == "link") ||
+  x == "poster" ||
+  x == "data-background-image"
+
+data ConvertState =
+  ConvertState
+  { isHtml5 :: Bool
+  , svgMap  :: M.Map T.Text (T.Text, [Attribute T.Text])
+    -- map from hash to (id, svg attributes)
+  } deriving (Show)
+
+convertTags :: PandocMonad m =>
+               [Tag T.Text] -> StateT ConvertState m [Tag T.Text]
 convertTags [] = return []
 convertTags (t@TagOpen{}:ts)
   | fromAttrib "data-external" t == "1" = (t:) <$> convertTags ts
-convertTags (t@(TagOpen tagname as):ts)
-  | tagname `elem`
-     ["img", "embed", "video", "input", "audio", "source", "track",
-      "section"] = do
-       as' <- mapM processAttribute as
-       rest <- convertTags ts
-       return $ TagOpen tagname as' : rest
-  where processAttribute (x,y) =
-           if x `elem` ["src", "data-src", "href", "poster", "data-background-image"]
-              then do
-                enc <- getDataURI (fromAttrib "type" t) y
-                return (x, enc)
-              else return (x,y)
-convertTags (t@(TagOpen "script" as):TagClose "script":ts) =
+convertTags (t@(TagOpen "style" _):ts) =
+  case span isTagText ts of
+    (xs,rest) -> do
+      xs' <- mapM (\case
+                    TagText s -> TagText . toText <$> cssURLs "" (fromText s)
+                    tag -> return tag) xs
+      ((t:xs') ++) <$> convertTags rest
+convertTags (t@(TagOpen "script" as):tc@(TagClose "script"):ts) =
   case fromAttrib "src" t of
-       []  -> (t:) <$> convertTags ts
-       src    -> do
+       ""  -> ([t, tc] ++) <$> convertTags ts
+       src -> do
            let typeAttr = fromAttrib "type" t
            res <- getData typeAttr src
            rest <- convertTags ts
            case res of
-                Left dataUri -> return $ TagOpen "script"
+                AlreadyDataURI dataUri -> return $ TagOpen "script"
                      (("src",dataUri) : [(x,y) | (x,y) <- as, x /= "src"]) :
                      TagClose "script" : rest
-                Right (mime, bs)
-                  | ("text/javascript" `isPrefixOf` mime ||
-                     "application/javascript" `isPrefixOf` mime ||
-                     "application/x-javascript" `isPrefixOf` mime) &&
+                Fetched (mime, bs)
+                  | ("text/javascript" `T.isPrefixOf` mime ||
+                     "application/javascript" `T.isPrefixOf` mime ||
+                     "application/x-javascript" `T.isPrefixOf` mime) &&
                      not ("</script" `B.isInfixOf` bs) ->
                      return $
-                       TagOpen "script" [("type", typeAttr)|not (null typeAttr)]
-                       : TagText (toString bs)
+                       TagOpen "script" [(k,v) | (k,v) <- as
+                                               , k == "type" ||
+                                                 "data-" `T.isPrefixOf` k]
+                       : TagText (toText bs)
                        : TagClose "script"
                        : rest
                   | otherwise ->
@@ -111,26 +115,28 @@
                          (("src",makeDataURI (mime, bs)) :
                           [(x,y) | (x,y) <- as, x /= "src"]) :
                         TagClose "script" : rest
+                CouldNotFetch _ -> return $ t:tc:rest
 convertTags (t@(TagOpen "link" as):ts) =
   case fromAttrib "href" t of
-       []  -> (t:) <$> convertTags ts
+       ""  -> (t:) <$> convertTags ts
        src -> do
            res <- getData (fromAttrib "type" t) src
            case res of
-                Left dataUri -> do
+                AlreadyDataURI dataUri -> do
                   rest <- convertTags ts
                   return $ TagOpen "link"
                      (("href",dataUri) : [(x,y) | (x,y) <- as, x /= "href"]) :
                      rest
-                Right (mime, bs)
-                  | "text/css" `isPrefixOf` mime
-                    && null (fromAttrib "media" t)
+                Fetched (mime, bs)
+                  | ("text/css" `T.isPrefixOf` mime ||
+                      fromAttrib "rel" t == "stylesheet")
+                    && T.null (fromAttrib "media" t)
                     && not ("</" `B.isInfixOf` bs) -> do
                       rest <- convertTags $
                                  dropWhile (==TagClose "link") ts
                       return $
-                       TagOpen "style" [("type", mime)]
-                       : TagText (toString bs)
+                       TagOpen "style" [("type", "text/css")] -- see #5725
+                       : TagText (toText bs)
                        : TagClose "style"
                        : rest
                   | otherwise -> do
@@ -138,15 +144,158 @@
                       return $ TagOpen "link"
                        (("href",makeDataURI (mime, bs)) :
                          [(x,y) | (x,y) <- as, x /= "href"]) : rest
+                CouldNotFetch _ -> do
+                      rest <- convertTags ts
+                      return $ t:rest
+convertTags (t@(TagOpen tagname as):ts)
+  | any (isSourceAttribute tagname) as
+     = do
+       let inlineSvgs = tagname == "img" &&
+                        case T.words <$> lookup "class" as of
+                          Nothing -> False
+                          Just cs -> "inline-svg" `elem` cs
+       as' <- mapM (processAttribute inlineSvgs) as
+       let attrs = addRole "img" $ addAriaLabel $ rights as'
+       let svgContents = lefts as'
+       rest <- convertTags ts
+       case svgContents of
+         [] -> return $ TagOpen tagname attrs : rest
+         ((hash, tags) : _) -> do
+             -- drop "</img>" if present
+             let rest' = case rest of
+                           TagClose tn : xs | tn == tagname ->  xs
+                           _ -> rest
+             svgmap <- gets svgMap
+             case M.lookup hash svgmap of
+               Just (svgid, svgattrs) -> do
+                 let attrs' = [(k,v) | (k,v) <- combineSvgAttrs svgattrs attrs
+                                     , k /= "id"]
+                 return $ TagOpen "svg" attrs' :
+                          TagOpen "use" [("href", "#" <> svgid),
+                                         ("width", "100%"),
+                                         ("height", "100%")] :
+                          TagClose "use" :
+                          TagClose "svg" :
+                          rest'
+               Nothing ->
+                  case dropWhile (not . isTagOpenName "svg") tags of
+                    TagOpen "svg" svgattrs : tags' -> do
+                      let attrs' = combineSvgAttrs svgattrs attrs
+                      let svgid = case lookup "id" attrs' of
+                                     Just id' -> id'
+                                     Nothing -> "svg_" <> hash
+                      let attrs'' = ("id", svgid) :
+                                    [(k,v) | (k,v) <- attrs', k /= "id"]
+                      modify $ \st ->
+                        st{ svgMap = M.insert hash (svgid, attrs'') (svgMap st) }
+                      let fixUrl x =
+                            case T.breakOn "url(#" x of
+                              (_,"") -> x
+                              (before, after) -> before <>
+                                  "url(#" <> svgid <> "_" <> T.drop 5 after
+                      let addIdPrefix ("id", x) = ("id", svgid <> "_" <> x)
+                          addIdPrefix (k, x)
+                           | k == "xlink:href" || k == "href" =
+                            case T.uncons x of
+                              Just ('#', x') -> (k, "#" <> svgid <> "_" <> x')
+                              _ -> (k, x)
+                          -- this clause handles things like
+                          -- style="fill:url(#radialGradient46);stroke:none",
+                          -- adding the svg id prefix to the anchor:
+                          addIdPrefix (k, x) = (k, fixUrl x)
+                      let ensureUniqueId (TagOpen tname ats) =
+                            TagOpen tname (map addIdPrefix ats)
+                          ensureUniqueId x = x
+                      return $ TagOpen "svg" attrs'' :
+                                 map ensureUniqueId tags' ++ rest'
+                    _ -> return $ TagOpen tagname attrs : rest
+  where processAttribute inlineSvgs (x,y) =
+           if isSourceAttribute tagname (x,y)
+              then do
+                res <- getData (fromAttrib "type" t) y
+                case res of
+                  AlreadyDataURI enc -> return $ Right (x, enc)
+                  Fetched ("image/svg+xml", bs) | inlineSvgs -> do
+                    -- we filter CR in the hash to ensure that Windows
+                    -- and non-Windows tests agree:
+                    let hash = T.pack $ take 20 $ show $ hashWith SHA1
+                                             $ B.filter (/='\r') bs
+                    return $ Left (hash, getSvgTags (toText bs))
+                  Fetched (mt,bs) -> return $ Right (x, makeDataURI (mt,bs))
+                  CouldNotFetch _ -> return $ Right (x, y)
+              else return $ Right (x,y)
+
 convertTags (t:ts) = (t:) <$> convertTags ts
 
+addRole :: T.Text -> [(T.Text, T.Text)] -> [(T.Text, T.Text)]
+addRole role attrs =
+  case lookup "role" attrs of
+    Nothing -> ("role", role) : attrs
+    Just _ -> attrs
+
+addAriaLabel :: [(T.Text, T.Text)] -> [(T.Text, T.Text)]
+addAriaLabel attrs =
+  case lookup "aria-label" attrs of
+    Just _ -> attrs
+    Nothing -> case lookup "alt" attrs of
+                 Just alt -> ("aria-label", alt) : attrs
+                 Nothing -> attrs
+
+-- we want to drop spaces, <?xml>, and comments before <svg>
+-- and anything after </svg>:
+getSvgTags :: T.Text -> [Tag T.Text]
+getSvgTags t =
+  case takeWhile (not . isTagCloseName "svg") .
+       dropWhile (not . isTagOpenName "svg") $ parseTags t of
+    [] -> []
+    xs -> xs ++ [TagClose "svg"]
+
+combineSvgAttrs :: [(T.Text, T.Text)] -> [(T.Text, T.Text)] -> [(T.Text, T.Text)]
+combineSvgAttrs svgAttrs imgAttrs =
+  case (mbViewBox, mbHeight, mbWidth) of
+    (Nothing, Just h, Just w) -> -- calculate viewBox
+      combinedAttrs ++ [("viewBox", T.unwords ["0", "0", tshow w, tshow h])]
+    (Just (_minx,_miny,w,h), Nothing, Nothing) ->
+        combinedAttrs ++
+        [ ("width", dropPointZero (tshow w)) |
+            isNothing (lookup "width" combinedAttrs) ] ++
+        [ ("height", dropPointZero (tshow h)) |
+            isNothing (lookup "height" combinedAttrs) ]
+    _ -> combinedAttrs
+ where
+  dropPointZero t = case T.stripSuffix ".0" t of
+                       Nothing -> t
+                       Just t' -> t'
+  combinedAttrs =
+    [(k, v) | (k, v) <- imgAttrs
+            , k /= "class"] ++
+    [(k, v) | (k, v) <- svgAttrs
+            , isNothing (lookup k imgAttrs)
+            , k `notElem` ["xmlns", "xmlns:xlink", "version", "class"]] ++
+    mergedClasses
+  parseViewBox t =
+    case map (safeRead . addZero) $ T.words t of
+      [Just llx, Just lly, Just urx, Just ury] -> Just (llx, lly, urx, ury)
+      _ -> Nothing
+  addZero t =
+    if "-." `T.isPrefixOf` t
+       then "-0." <> T.drop 2 t -- safeRead fails on -.33, needs -0.33
+       else t
+  (mbViewBox :: Maybe (Double, Double, Double, Double)) =
+        lookup "viewBox" svgAttrs >>= parseViewBox
+  (mbHeight :: Maybe Int) = lookup "height" combinedAttrs >>= safeRead
+  (mbWidth :: Maybe Int) = lookup "width" combinedAttrs >>= safeRead
+  mergedClasses = case (lookup "class" imgAttrs, lookup "class" svgAttrs) of
+                    (Just c1, Just c2) -> [("class", c1 <> " " <> c2)]
+                    _ -> []
+
 cssURLs :: PandocMonad m
         => FilePath -> ByteString -> m ByteString
 cssURLs d orig = do
   res <- runParserT (parseCSSUrls d) () "css" orig
   case res of
        Left e    -> do
-         report $ CouldNotParseCSS (show e)
+         report $ CouldNotParseCSS $ T.pack $ show e
          return orig
        Right bs  -> return bs
 
@@ -192,87 +341,110 @@
        Left b -> return b
        Right (mt,b) -> do
          let enc = makeDataURI (mt, b)
-         return (B.pack $ "url(" ++ enc ++ ")")
+         return $ fromText $ "url(" <> enc <> ")"
 
 pQuoted :: PandocMonad m
-        => ParsecT ByteString () m (String, ByteString)
+        => ParsecT ByteString () m (T.Text, ByteString)
 pQuoted = P.try $ do
   quote <- P.oneOf "\"'"
-  url <- P.manyTill P.anyChar (P.char quote)
-  let fallback = B.pack ([quote] ++ trim url ++ [quote])
+  url <- T.pack <$> P.manyTill P.anyChar (P.char quote)
+  let fallback = fromText $ T.singleton quote <> trim url <> T.singleton quote
   return (url, fallback)
 
 pUrl :: PandocMonad m
-     => ParsecT ByteString () m (String, ByteString)
+     => ParsecT ByteString () m (T.Text, ByteString)
 pUrl = P.try $ do
   P.string "url("
   P.spaces
   quote <- P.option Nothing (Just <$> P.oneOf "\"'")
-  url <- P.manyTill P.anyChar (maybe (P.lookAhead (P.char ')')) P.char quote)
+  url <- T.pack <$> P.manyTill P.anyChar (maybe (P.lookAhead (P.char ')')) P.char quote)
   P.spaces
   P.char ')'
-  let fallback = B.pack ("url(" ++ maybe "" (:[]) quote ++ trim url ++
-                            maybe "" (:[]) quote ++ ")")
+  let fallback = fromText ("url(" <> maybe "" T.singleton quote <> trim url <>
+                            maybe "" T.singleton quote <> ")")
   return (url, fallback)
 
 handleCSSUrl :: PandocMonad m
-             => FilePath -> (String, ByteString)
+             => FilePath -> (T.Text, ByteString)
              -> ParsecT ByteString () m
                   (Either ByteString (MimeType, ByteString))
 handleCSSUrl d (url, fallback) =
-  case escapeURIString (/='|') (trim url) of
+  case escapeURIString (/='|') (T.unpack $ trim url) of
       '#':_ -> return $ Left fallback
       'd':'a':'t':'a':':':_ -> return $ Left fallback
-      u ->  do let url' = if isURI u then u else d </> u
+      u ->  do let url' = if isURI (T.pack u) then T.pack u else T.pack (d </> u)
                res <- lift $ getData "" url'
                case res of
-                    Left uri -> return $ Left (B.pack $ "url(" ++ uri ++ ")")
-                    Right (mt, raw) -> do
+                    AlreadyDataURI uri -> return $ Left (fromText $ "url(" <> uri <> ")")
+                    Fetched (mt', raw) -> do
                       -- note that the downloaded CSS may
                       -- itself contain url(...).
-                      b <- if "text/css" `isPrefixOf` mt
-                              then cssURLs d raw
-                              else return raw
+                      (mt, b) <- if "text/css" `T.isPrefixOf` mt'
+                                    -- see #5725: in HTML5, content type
+                                    -- isn't allowed on style type attribute
+                                    then ("text/css",) <$> cssURLs d raw
+                                    else return (mt', raw)
                       return $ Right (mt, b)
+                    CouldNotFetch _ -> return $ Left fallback
 
-getDataURI :: PandocMonad m => MimeType -> String -> m String
-getDataURI mimetype src = do
-  res <- getData mimetype src
-  case res of
-       Left uri -> return uri
-       Right x  -> return $ makeDataURI x
+data GetDataResult =
+    AlreadyDataURI T.Text
+  | CouldNotFetch PandocError
+  | Fetched (MimeType, ByteString)
+  deriving (Show)
 
 getData :: PandocMonad m
-        => MimeType -> String
-        -> m (Either String (MimeType, ByteString))
-getData _ src@('d':'a':'t':'a':':':_) = return $ Left src-- already data: uri
-getData mimetype src = do
-  let ext = map toLower $ takeExtension src
-  (raw, respMime) <- fetchItem src
-  let raw' = if ext == ".gz"
-                then B.concat $ L.toChunks $ Gzip.decompress $ L.fromChunks [raw]
-                else raw
-  mime <- case (mimetype, respMime) of
-                  ("",Nothing) -> throwError $ PandocSomeError
-                         $ "Could not determine mime type for `" ++ src ++ "'"
-                  (x, Nothing) -> return x
-                  (_, Just x ) -> return x
-  result <- if "text/css" `isPrefixOf` mime
-               then do
-                 oldInputs <- getInputFiles
-                 setInputFiles [src]
-                 res <- cssURLs (takeDirectory src) raw'
-                 setInputFiles oldInputs
-                 return res
+        => MimeType -> T.Text
+        -> m GetDataResult
+getData mimetype src
+  | "data:" `T.isPrefixOf` src = return $ AlreadyDataURI src -- already data: uri
+  | otherwise = catchError fetcher handler
+ where
+   fetcher = do
+      let ext = T.toLower $ T.pack $ takeExtension $ T.unpack src
+      (raw, respMime) <- fetchItem src
+      let raw' = if ext `elem` [".gz", ".svgz"]
+                 then B.concat $ L.toChunks $ Gzip.decompress $ L.fromChunks [raw]
+                 else raw
+      let mime = case (mimetype, respMime) of
+                  ("",Nothing) -> "application/octet-stream"
+                  (x, Nothing) -> x
+                  (_, Just x ) -> x
+      result <- if "text/css" `T.isPrefixOf` mime
+                then do
+                  oldInputs <- getInputFiles
+                  setInputFiles [T.unpack src]
+                  res <- cssURLs (takeDirectory $ T.unpack src) raw'
+                  setInputFiles oldInputs
+                  return res
                else return raw'
-  return $ Right (mime, result)
-
-
+      return $ Fetched (mime, result)
+   handler e
+      -- If fetch failed and we have a fragment and/or query,
+      -- try the fetch again without these, since the resource
+      -- may be local (see #1477, #11021)
+     | T.any (\c -> c == '?' || c == '#') src && not (isURI src)
+       = getData mimetype (removeQueryAndFragment src)
+     | otherwise
+       = case e of
+          PandocResourceNotFound r -> do
+            report $ CouldNotFetchResource r ""
+            return $ CouldNotFetch e
+          PandocHttpError u er -> do
+            report $ CouldNotFetchResource u er
+            return $ CouldNotFetch e
+          _ -> throwError e
+   removeQueryAndFragment = T.takeWhile (\c -> c /= '#' && c /= '?')
 
 -- | Convert HTML into self-contained HTML, incorporating images,
 -- scripts, and CSS using data: URIs.
-makeSelfContained :: PandocMonad m => String -> m String
+makeSelfContained :: PandocMonad m => T.Text -> m T.Text
 makeSelfContained inp = do
   let tags = parseTags inp
-  out' <- convertTags tags
+  let html5 = case tags of
+                  (TagOpen "!DOCTYPE" [("html","")]:_) -> True
+                  _ -> False
+  let convertState = ConvertState { isHtml5 = html5,
+                                    svgMap = mempty }
+  out' <- evalStateT (convertTags tags) convertState
   return $ renderTags' out'
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
@@ -1,31 +1,15 @@
+{-# LANGUAGE BangPatterns          #-}
 {-# LANGUAGE CPP                   #-}
-{-# LANGUAGE DeriveDataTypeable    #-}
 {-# LANGUAGE FlexibleContexts      #-}
 {-# LANGUAGE MultiParamTypeClasses #-}
-
 {-# LANGUAGE ScopedTypeVariables   #-}
 {-# LANGUAGE ViewPatterns          #-}
-{-
-Copyright (C) 2006-2017 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 LambdaCase            #-}
+{-# LANGUAGE OverloadedStrings     #-}
 {- |
    Module      : Text.Pandoc.Shared
-   Copyright   : Copyright (C) 2006-2017 John MacFarlane
+   Copyright   : Copyright (C) 2006-2024 John MacFarlane
    License     : GNU GPL, version 2 or above
 
    Maintainer  : John MacFarlane <jgm@berkeley.edu>
@@ -37,26 +21,25 @@
 module Text.Pandoc.Shared (
                      -- * List processing
                      splitBy,
-                     splitByIndices,
-                     splitStringByIndices,
-                     substitute,
-                     ordNub,
+                     splitTextBy,
+                     splitTextByIndices,
                      -- * Text processing
-                     backslashEscapes,
-                     escapeStringUsing,
+                     inquotes,
+                     tshow,
                      stripTrailingNewlines,
                      trim,
                      triml,
                      trimr,
+                     trimMath,
                      stripFirstAndLast,
                      camelCaseToHyphenated,
+                     camelCaseStrToHyphenated,
                      toRomanNumeral,
-                     escapeURI,
                      tabFilter,
-                     crFilter,
                      -- * Date/time
                      normalizeDate,
                      -- * Pandoc block and inline list processing
+                     addPandocAttributes,
                      orderedListMarkers,
                      extractSpaces,
                      removeFormatting,
@@ -66,38 +49,38 @@
                      compactify,
                      compactifyDL,
                      linesToPara,
-                     Element (..),
-                     hierarchicalize,
+                     figureDiv,
+                     makeSections,
+                     makeSectionsWithOffsets,
+                     combineAttr,
                      uniqueIdent,
                      inlineListToIdentifier,
+                     textToIdentifier,
                      isHeaderBlock,
-                     headerShift,
-                     stripEmptyParagraphs,
+                     hasLineBreaks,
+                     onlySimpleTableCells,
                      isTightList,
+                     taskListItemFromAscii,
+                     taskListItemToAscii,
+                     handleTaskListItem,
                      addMetaField,
-                     makeMeta,
-                     eastAsianLineBreakFilter,
-                     underlineSpan,
+                     htmlSpanLikeElements,
+                     formatCode,
                      -- * TagSoup HTML handling
                      renderTags',
                      -- * File handling
                      inDirectory,
+                     makeCanonical,
                      collapseFilePath,
                      filteredFilesFromArchive,
-                     -- * URI handling
-                     schemes,
-                     isURI,
-                     -- * Error handling
-                     mapLeft,
                      -- * for squashing blocks
                      blocksToInlines,
                      blocksToInlines',
+                     blocksToInlinesWithSep,
+                     defaultBlocksSeparator,
                      -- * Safe read
                      safeRead,
-                     -- * Temp directory
-                     withTempDir,
-                     -- * Version
-                     pandocVersion
+                     safeStrRead
                     ) where
 
 import Codec.Archive.Zip
@@ -105,36 +88,36 @@
 import Control.Monad (MonadPlus (..), msum, unless)
 import qualified Control.Monad.State.Strict as S
 import qualified Data.ByteString.Lazy as BL
-import Data.Char (isAlpha, isDigit, isLetter, isLower, isSpace, isUpper,
-                  toLower)
-import Data.Data (Data, Typeable)
-import Data.List (find, intercalate, intersperse, stripPrefix)
+import Data.Containers.ListUtils (nubOrd)
+import Data.Char (isAlpha, isLower, isSpace, isUpper, toLower, isAlphaNum,
+                  generalCategory, GeneralCategory(NonSpacingMark,
+                  SpacingCombiningMark, EnclosingMark, ConnectorPunctuation))
+import Data.List (find, groupBy, intercalate, intersperse, union)
+import qualified Data.List as L
 import qualified Data.Map as M
 import Data.Maybe (mapMaybe)
-import Data.Monoid ((<>))
+import Data.Monoid (Any (..) )
+import Data.Semigroup (Min (..))
 import Data.Sequence (ViewL (..), ViewR (..), viewl, viewr)
 import qualified Data.Set as Set
 import qualified Data.Text as T
-import Data.Version (showVersion)
-import Network.URI (URI (uriScheme), escapeURIString, parseURI)
-import Paths_pandoc (version)
+import qualified Text.Emoji as Emoji
 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 (..))
 import qualified Text.Pandoc.Builder as B
-import Text.Pandoc.Compat.Time
+import Data.Time
+import Text.Pandoc.Asciify (toAsciiText)
 import Text.Pandoc.Definition
-import Text.Pandoc.Generic (bottomUp)
-import Text.Pandoc.Pretty (charWidth)
+import Text.Pandoc.Extensions (Extensions, Extension(..), extensionEnabled)
+import Text.DocLayout (charWidth)
 import Text.Pandoc.Walk
-
--- | Version number of pandoc library.
-pandocVersion :: String
-pandocVersion = showVersion version
+-- for addPandocAttributes:
+import Commonmark.Pandoc (Cm(..))
+import Commonmark (HasAttributes(..))
 
 --
 -- List processing
@@ -145,115 +128,137 @@
 splitBy _ [] = []
 splitBy isSep lst =
   let (first, rest) = break isSep lst
-      rest'         = dropWhile isSep rest
-  in  first:splitBy isSep rest'
-
-splitByIndices :: [Int] -> [a] -> [[a]]
-splitByIndices [] lst = [lst]
-splitByIndices (x:xs) lst = first:splitByIndices (map (\y -> y - x)  xs) rest
-  where (first, rest) = splitAt x lst
-
--- | Split string into chunks divided at specified indices.
-splitStringByIndices :: [Int] -> [Char] -> [[Char]]
-splitStringByIndices [] lst = [lst]
-splitStringByIndices (x:xs) lst =
-  let (first, rest) = splitAt' x lst in
-  first : splitStringByIndices (map (\y -> y - x) xs) rest
+  in  first:splitBy isSep (dropWhile isSep rest)
 
-splitAt' :: Int -> [Char] -> ([Char],[Char])
-splitAt' _ []          = ([],[])
-splitAt' n xs | n <= 0 = ([],xs)
-splitAt' n (x:xs)      = (x:ys,zs)
-  where (ys,zs) = splitAt' (n - charWidth x) xs
+-- | Split text by groups of one or more separator.
+splitTextBy :: (Char -> Bool) -> T.Text -> [T.Text]
+splitTextBy isSep t
+  | T.null t = []
+  | otherwise = let (first, rest) = T.break isSep t
+                in  first : splitTextBy isSep (T.dropWhile isSep rest)
 
--- | Replace each occurrence of one sublist in a list with another.
-substitute :: (Eq a) => [a] -> [a] -> [a] -> [a]
-substitute _ _ [] = []
-substitute [] _ xs = xs
-substitute target replacement lst@(x:xs) =
-    case stripPrefix target lst of
-      Just lst' -> replacement ++ substitute target replacement lst'
-      Nothing   -> x : substitute target replacement xs
+-- | Split text at the given widths. Note that the break points are
+-- /not/ indices but text widths, which will be different for East Asian
+-- characters, emojis, etc.
+splitTextByIndices :: [Int] -> T.Text -> [T.Text]
+splitTextByIndices ns = splitByRelWidths (zipWith (-) ns (0:ns))
+ where
+  splitByRelWidths [] t = [t]
+  splitByRelWidths (w:ws) t =
+    let (first, rest) = splitAtWidth w t
+     in first : splitByRelWidths ws rest
 
-ordNub :: (Ord a) => [a] -> [a]
-ordNub l = go Set.empty l
+-- | Split a @Text@ at a given display width, where width is determined
+-- by 'charWidth' (East Asian characters, emojis, etc. count as 2).
+--
+-- Note: Do *not* replace this with 'T.splitAt', which is not sensitive
+-- to character widths!
+splitAtWidth :: Int -> T.Text -> (T.Text, T.Text)
+splitAtWidth n t
+  | n <= 0    = (T.empty, t)
+  | otherwise = T.splitAt (go 0 0 t) t
   where
-    go _ [] = []
-    go s (x:xs) = if x `Set.member` s then go s xs
-                                      else x : go (Set.insert x s) xs
+    go !idx !w t'
+      | w >= n    = idx
+      | T.null t' = idx
+      | otherwise = go (idx + 1) (w + charWidth (T.head t')) (T.tail t')
 
 --
 -- Text processing
 --
 
--- | Returns an association list of backslash escapes for the
--- designated characters.
-backslashEscapes :: [Char]    -- ^ list of special characters to escape
-                 -> [(Char, String)]
-backslashEscapes = map (\ch -> (ch, ['\\',ch]))
+-- | Wrap double quotes around a Text
+inquotes :: T.Text -> T.Text
+inquotes txt = T.cons '\"' (T.snoc txt '\"')
 
--- | Escape a string of characters, using an association list of
--- characters and strings.
-escapeStringUsing :: [(Char, String)] -> String -> String
-escapeStringUsing _ [] = ""
-escapeStringUsing escapeTable (x:xs) =
-  case lookup x escapeTable of
-       Just str -> str ++ rest
-       Nothing  -> x:rest
-  where rest = escapeStringUsing escapeTable xs
+-- | Like @'show'@, but returns a 'T.Text' instead of a 'String'.
+tshow :: Show a => a -> T.Text
+tshow = T.pack . show
 
 -- | Strip trailing newlines from string.
-stripTrailingNewlines :: String -> String
-stripTrailingNewlines = reverse . dropWhile (== '\n') . reverse
+stripTrailingNewlines :: T.Text -> T.Text
+stripTrailingNewlines = T.dropWhileEnd (== '\n')
 
+-- | Returns 'True' for an ASCII whitespace character, viz. space,
+-- carriage return, newline, and horizontal tab.
+isWS :: Char -> Bool
+isWS ' '  = True
+isWS '\r' = True
+isWS '\n' = True
+isWS '\t' = True
+isWS _    = False
+
 -- | Remove leading and trailing space (including newlines) from string.
-trim :: String -> String
-trim = triml . trimr
+trim :: T.Text -> T.Text
+trim = T.dropAround isWS
 
 -- | Remove leading space (including newlines) from string.
-triml :: String -> String
-triml = dropWhile (`elem` " \r\n\t")
+triml :: T.Text -> T.Text
+triml = T.dropWhile isWS
 
 -- | Remove trailing space (including newlines) from string.
-trimr :: String -> String
-trimr = reverse . triml . reverse
+trimr :: T.Text -> T.Text
+trimr = T.dropWhileEnd isWS
 
+-- | Trim leading space and trailing space unless after \.
+trimMath :: T.Text -> T.Text
+trimMath = triml . T.reverse . stripBeginSpace . T.reverse -- no Text.spanEnd
+  where
+    stripBeginSpace t
+      | T.null pref = t
+      | Just ('\\', _) <- T.uncons suff = T.cons (T.last pref) suff
+      | otherwise = suff
+      where
+        (pref, suff) = T.span isWS t
+
 -- | Strip leading and trailing characters from string
-stripFirstAndLast :: String -> String
-stripFirstAndLast str =
-  drop 1 $ take (length str - 1) str
+stripFirstAndLast :: T.Text -> T.Text
+stripFirstAndLast t = case T.uncons t of
+  Just (_, t') -> case T.unsnoc t' of
+    Just (t'', _) -> t''
+    _             -> t'
+  _               -> ""
 
 -- | Change CamelCase word to hyphenated lowercase (e.g., camel-case).
-camelCaseToHyphenated :: String -> String
-camelCaseToHyphenated [] = ""
-camelCaseToHyphenated (a:b:rest) | isLower a && isUpper b =
-  a:'-':toLower b:camelCaseToHyphenated rest
-camelCaseToHyphenated (a:rest) = toLower a:camelCaseToHyphenated rest
+camelCaseToHyphenated :: T.Text -> T.Text
+camelCaseToHyphenated = T.pack . camelCaseStrToHyphenated . T.unpack
 
+-- This may not work as expected on general Unicode, if it contains
+-- letters with a longer lower case form than upper case. I don't know
+-- what the camel case practices of affected scripts are, though.
+camelCaseStrToHyphenated :: String -> String
+camelCaseStrToHyphenated [] = ""
+camelCaseStrToHyphenated (a:b:rest)
+  | isLower a
+  , isUpper b = a:'-':toLower b:camelCaseStrToHyphenated rest
+-- handle ABCDef = abc-def
+camelCaseStrToHyphenated (a:b:c:rest)
+  | isUpper a
+  , isUpper b
+  , isLower c = toLower a:'-':toLower b:camelCaseStrToHyphenated (c:rest)
+camelCaseStrToHyphenated (a:rest) = toLower a:camelCaseStrToHyphenated rest
+
 -- | Convert number < 4000 to uppercase roman numeral.
-toRomanNumeral :: Int -> String
+toRomanNumeral :: Int -> T.Text
 toRomanNumeral x
   | x >= 4000 || x < 0 = "?"
-  | x >= 1000 = "M" ++ toRomanNumeral (x - 1000)
-  | x >= 900  = "CM" ++ toRomanNumeral (x - 900)
-  | x >= 500  = "D" ++ toRomanNumeral (x - 500)
-  | x >= 400  = "CD" ++ toRomanNumeral (x - 400)
-  | x >= 100  = "C" ++ toRomanNumeral (x - 100)
-  | x >= 90   = "XC" ++ toRomanNumeral (x - 90)
-  | x >= 50   = "L"  ++ toRomanNumeral (x - 50)
-  | x >= 40   = "XL" ++ toRomanNumeral (x - 40)
-  | x >= 10   = "X" ++ toRomanNumeral (x - 10)
-  | x == 9    = "IX"
-  | x >= 5    = "V" ++ toRomanNumeral (x - 5)
-  | x == 4    = "IV"
-  | x >= 1    = "I" ++ toRomanNumeral (x - 1)
-  | otherwise = ""
-
--- | Escape whitespace and some punctuation characters in URI.
-escapeURI :: String -> String
-escapeURI = escapeURIString (not . needsEscaping)
-  where needsEscaping c = isSpace c || c `elem`
-                           ['<','>','|','"','{','}','[',']','^', '`']
+  | otherwise = T.pack (go x)
+  where
+    go n
+      | n >= 1000 = 'M'       : go (n - 1000)
+      | n >= 900  = 'C' : 'M' : go (n - 900)
+      | n >= 500  = 'D'       : go (n - 500)
+      | n >= 400  = 'C' : 'D' : go (n - 400)
+      | n >= 100  = 'C'       : go (n - 100)
+      | n >= 90   = 'X' : 'C' : go (n - 90)
+      | n >= 50   = 'L'       : go (n - 50)
+      | n >= 40   = 'X' : 'L' : go (n - 40)
+      | n >= 10   = 'X'       : go (n - 10)
+      | n == 9    = "IX"
+      | n >= 5    = 'V'       : go (n - 5)
+      | n == 4    = "IV"
+      | n >= 1    = 'I'       : go (n - 1)
+      | otherwise = []
 
 -- | Convert tabs to spaces. Tabs will be preserved if tab stop is set to 0.
 tabFilter :: Int       -- ^ Tab stop
@@ -266,13 +271,9 @@
          in  if T.null s2
                 then s1
                 else s1 <> T.replicate
-                       (tabStop - (T.length s1 `mod` tabStop)) (T.pack " ")
+                       (tabStop - (T.length s1 `mod` tabStop)) " "
                        <> go (T.drop 1 s2)
 
--- | Strip out DOS line endings.
-crFilter :: T.Text -> T.Text
-crFilter = T.filter (/= '\r')
-
 --
 -- Date/time
 --
@@ -280,18 +281,17 @@
 -- | Parse a date and convert (if possible) to "YYYY-MM-DD" format. We
 -- limit years to the range 1601-9999 (ISO 8601 accepts greater than
 -- or equal to 1583, but MS Word only accepts dates starting 1601).
-normalizeDate :: String -> Maybe String
-normalizeDate s = fmap (formatTime defaultTimeLocale "%F")
+normalizeDate :: T.Text -> Maybe T.Text
+normalizeDate = fmap T.pack . normalizeDate' . T.unpack
+
+-- | Like @'normalizeDate'@, but acts on 'String' instead of 'T.Text'.
+normalizeDate' :: String -> Maybe String
+normalizeDate' s = fmap (formatTime defaultTimeLocale "%F")
   (msum $ map (\fs -> parsetimeWith fs s >>= rejectBadYear) formats :: Maybe Day)
   where rejectBadYear day = case toGregorian day of
           (y, _, _) | y >= 1601 && y <= 9999 -> Just day
           _         -> Nothing
-        parsetimeWith =
-#if MIN_VERSION_time(1,5,0)
-             parseTimeM True defaultTimeLocale
-#else
-             parseTime defaultTimeLocale
-#endif
+        parsetimeWith = parseTimeM True defaultTimeLocale
         formats = ["%x","%m/%d/%Y", "%D","%F", "%d %b %Y",
                     "%e %B %Y", "%b. %e, %Y", "%B %e, %Y",
                     "%Y%m%d", "%Y%m", "%Y"]
@@ -300,28 +300,38 @@
 -- Pandoc block and inline list processing
 --
 
+-- | Add key-value attributes to a pandoc element. If the element
+-- does not have a slot for attributes, create an enclosing Span
+-- (for Inlines) or Div (for Blocks).  Note that both 'Cm () Inlines'
+-- and 'Cm () Blocks' are instances of 'HasAttributes'.
+addPandocAttributes
+  :: forall b . HasAttributes (Cm () b) => [(T.Text, T.Text)] -> b -> b
+addPandocAttributes [] bs = bs
+addPandocAttributes kvs bs =
+  unCm . addAttributes kvs $ (Cm bs :: Cm () b)
+
 -- | Generate infinite lazy list of markers for an ordered list,
 -- depending on list attributes.
-orderedListMarkers :: (Int, ListNumberStyle, ListNumberDelim) -> [String]
+orderedListMarkers :: (Int, ListNumberStyle, ListNumberDelim) -> [T.Text]
 orderedListMarkers (start, numstyle, numdelim) =
-  let singleton c = [c]
-      nums = case numstyle of
-                     DefaultStyle -> map show [start..]
-                     Example      -> map show [start..]
-                     Decimal      -> map show [start..]
+  let nums = case numstyle of
+                     DefaultStyle -> map tshow [start..]
+                     Example      -> map tshow [start..]
+                     Decimal      -> map tshow [start..]
                      UpperAlpha   -> drop (start - 1) $ cycle $
-                                     map singleton ['A'..'Z']
+                                     map T.singleton ['A'..'Z']
                      LowerAlpha   -> drop (start - 1) $ cycle $
-                                     map singleton ['a'..'z']
+                                     map T.singleton ['a'..'z']
                      UpperRoman   -> map toRomanNumeral [start..]
-                     LowerRoman   -> map (map toLower . toRomanNumeral) [start..]
+                     LowerRoman   -> map (T.toLower . toRomanNumeral) [start..]
       inDelim str = case numdelim of
-                            DefaultDelim -> str ++ "."
-                            Period       -> str ++ "."
-                            OneParen     -> str ++ ")"
-                            TwoParens    -> "(" ++ str ++ ")"
+                            DefaultDelim -> str <> "."
+                            Period       -> str <> "."
+                            OneParen     -> str <> ")"
+                            TwoParens    -> "(" <> str <> ")"
   in  map inDelim nums
 
+
 -- | Extract the leading and trailing spaces from inside an inline element
 -- and place them outside the element.  SoftBreaks count as Spaces for
 -- these purposes.
@@ -350,32 +360,42 @@
         go LineBreak  = [Space]
         go _          = []
 
+-- | Replaces 'Note' elements with empty strings.
 deNote :: Inline -> Inline
 deNote (Note _) = Str ""
 deNote x        = x
 
-deQuote :: Inline -> Inline
-deQuote (Quoted SingleQuote xs) =
-  Span ("",[],[]) (Str "\8216" : xs ++ [Str "\8217"])
-deQuote (Quoted DoubleQuote xs) =
-  Span ("",[],[]) (Str "\8220" : xs ++ [Str "\8221"])
-deQuote x = x
-
 -- | Convert pandoc structure to a string with formatting removed.
 -- Footnotes are skipped (since we don't want their contents in link
 -- labels).
-stringify :: Walkable Inline a => a -> String
-stringify = query go . walk (deNote . deQuote)
-  where go :: Inline -> [Char]
+stringify :: Walkable Inline a => a -> T.Text
+stringify = query go . walk fixInlines
+  where go :: Inline -> T.Text
         go Space                                       = " "
         go SoftBreak                                   = " "
         go (Str x)                                     = x
         go (Code _ x)                                  = x
         go (Math _ x)                                  = x
-        go (RawInline (Format "html") ('<':'b':'r':_)) = " " -- see #2105
+        go (RawInline (Format "html") (T.unpack -> ('<':'b':'r':_)))
+                                                       = " " -- see #2105
         go LineBreak                                   = " "
         go _                                           = ""
 
+        fixInlines :: Inline -> Inline
+        fixInlines (Cite _ ils) = Cite [] ils
+        fixInlines (Note _) = Note []
+        fixInlines (q@Quoted{}) = deQuote q
+        fixInlines x = x
+
+-- | Unwrap 'Quoted' inline elements, enclosing the contents with
+-- English-style Unicode quotes instead.
+deQuote :: Inline -> Inline
+deQuote (Quoted SingleQuote xs) =
+  Span ("",[],[]) (Str "\8216" : xs ++ [Str "\8217"])
+deQuote (Quoted DoubleQuote xs) =
+  Span ("",[],[]) (Str "\8220" : xs ++ [Str "\8221"])
+deQuote x = x
+
 -- | Bring all regular text in a pandoc structure to uppercase.
 --
 -- This function correctly handles cases where a lowercase character doesn't
@@ -384,41 +404,44 @@
 capitalize :: Walkable Inline a => a -> a
 capitalize = walk go
   where go :: Inline -> Inline
-        go (Str s) = Str (T.unpack $ T.toUpper $ T.pack s)
+        go (Str s) = Str $ T.toUpper s
         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)
+             | not (any isPara xs || any (any isPara . B.toList) others)
+             -> others ++ [B.fromList (reverse (Plain a : xs))]
+           _ | not (any (any isPara . 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 =
-  let defs = concatMap snd items
-  in  case reverse (concatMap B.toList defs) of
-           (Para x:xs)
-             | not (any isPara xs) ->
-                   let (t,ds) = last items
-                       lastDef = B.toList $ last ds
-                       ds' = init ds ++
-                             if null lastDef
-                                then [B.fromList lastDef]
-                                else [B.fromList $ init lastDef ++ [Plain x]]
-                    in init items ++ [(t, ds')]
-             | otherwise           -> items
-           _                       -> items
+  case reverse items of
+        ((t,ds):ys) ->
+           case reverse (map (reverse . B.toList) ds) of
+             ((Para x:xs) : zs) | not (any isPara xs) ->
+                  reverse ys ++
+                    [(t, reverse (map B.fromList zs) ++
+                         [B.fromList (reverse (Plain x:xs))])]
+             _     -> items
+        _          -> items
 
+
 -- | Combine a list of lines by adding hard linebreaks.
 combineLines :: [[Inline]] -> [Inline]
 combineLines = intercalate [LineBreak]
@@ -428,127 +451,248 @@
 linesToPara :: [[Inline]] -> Block
 linesToPara = Para . combineLines
 
+-- | Creates a Div block from figure components. The intended use is in
+-- writers of formats that do not have markup support for figures.
+--
+-- The resulting div is given the class @figure@ and contains the figure
+-- body and the figure caption. The latter is wrapped in a 'Div' of
+-- class @caption@, with the stringified @short-caption@ as attribute.
+figureDiv :: Attr -> Caption -> [Block] -> Block
+figureDiv (ident, classes, kv) (Caption shortcapt longcapt) body =
+  let divattr = ( ident
+              , ["figure"] `union` classes
+              , kv
+              )
+      captkv = maybe mempty (\s -> [("short-caption", stringify s)]) shortcapt
+      capt = [Div ("", ["caption"], captkv) longcapt | not (null longcapt)]
+  in Div divattr (body ++ capt)
+
+-- | Returns 'True' iff the given element is a 'Para'.
 isPara :: Block -> Bool
 isPara (Para _) = True
 isPara _        = False
 
--- | Data structure for defining hierarchical Pandoc documents
-data Element = Blk Block
-             | Sec Int [Int] Attr [Inline] [Element]
-             --    lvl  num attributes label    contents
-             deriving (Eq, Read, Show, Typeable, Data)
-
-instance Walkable Inline Element where
-  walk f (Blk x) = Blk (walk f x)
-  walk f (Sec lev nums attr ils elts) = Sec lev nums attr (walk f ils) (walk f elts)
-  walkM f (Blk x) = Blk `fmap` walkM f x
-  walkM f (Sec lev nums attr ils elts) = do
-    ils' <- walkM f ils
-    elts' <- walkM f elts
-    return $ Sec lev nums attr ils' elts'
-  query f (Blk x)              = query f x
-  query f (Sec _ _ _ ils elts) = query f ils <> query f elts
+-- | Convert Pandoc inline list to plain text identifier.
+inlineListToIdentifier :: Extensions -> [Inline] -> T.Text
+inlineListToIdentifier exts =
+  textToIdentifier exts . stringify . unEmojify
+  where
+    unEmojify :: [Inline] -> [Inline]
+    unEmojify
+      | extensionEnabled Ext_gfm_auto_identifiers exts ||
+        extensionEnabled Ext_ascii_identifiers exts = walk unEmoji
+      | otherwise = id
+    unEmoji (Span ("",["emoji"],[("data-emoji",ename)]) _) = Str ename
+    unEmoji (Str t) = Str (Emoji.replaceEmojis emojisToAliases t)
+    unEmoji x = x
+    emojisToAliases t [] = t
+    emojisToAliases _ (a:_) = a
 
-instance Walkable Block Element where
-  walk f (Blk x) = Blk (walk f x)
-  walk f (Sec lev nums attr ils elts) = Sec lev nums attr (walk f ils) (walk f elts)
-  walkM f (Blk x) = Blk `fmap` walkM f x
-  walkM f (Sec lev nums attr ils elts) = do
-    ils' <- walkM f ils
-    elts' <- walkM f elts
-    return $ Sec lev nums attr ils' elts'
-  query f (Blk x)              = query f x
-  query f (Sec _ _ _ ils elts) = query f ils <> query f elts
+-- | Convert string to plain text identifier.
+textToIdentifier :: Extensions -> T.Text -> T.Text
+textToIdentifier exts =
+  dropNonLetter . filterAscii . toIdent
+  where
+    dropNonLetter
+      | extensionEnabled Ext_gfm_auto_identifiers exts = id
+      | otherwise = T.dropWhile (not . isAlpha)
+    filterAscii
+      | extensionEnabled Ext_ascii_identifiers exts
+        = toAsciiText
+      | otherwise = id
+    toIdent
+      | extensionEnabled Ext_gfm_auto_identifiers exts =
+        filterPunct . spaceToDash . T.toLower
+      | otherwise = T.intercalate "-" . T.words . filterPunct . T.toLower
+    filterPunct = T.filter (\c -> isSpace c || isAlphaNum c || isAllowedPunct c)
+    isAllowedPunct c
+      | extensionEnabled Ext_gfm_auto_identifiers exts
+        = c == '-' || c == '_' ||
+          generalCategory c `elem` [NonSpacingMark, SpacingCombiningMark,
+                                    EnclosingMark, ConnectorPunctuation]
+      | otherwise = c == '_' || c == '-' || c == '.'
+    spaceToDash = T.map (\c -> if isSpace c then '-' else c)
 
 
--- | Convert Pandoc inline list to plain text identifier.  HTML
--- identifiers must start with a letter, and may contain only
--- letters, digits, and the characters _-.
-inlineListToIdentifier :: [Inline] -> String
-inlineListToIdentifier =
-  dropWhile (not . isAlpha) . intercalate "-" . words .
-    map (nbspToSp . toLower) .
-    filter (\c -> isLetter c || isDigit c || c `elem` "_-. ") .
-    stringify
- where nbspToSp '\160' =  ' '
-       nbspToSp x      =  x
+-- | Put a list of Pandoc blocks into a hierarchical structure:
+-- a list of sections (each a Div with class "section" and first
+-- element a Header).  If the 'numbering' parameter is True, Header
+-- numbers are added via the number attribute on the header.
+-- If the baseLevel parameter is Just n, Header levels are
+-- adjusted so that the lowest header level is n.
+-- (There may still be gaps in header level if the author leaves them.)
+makeSections :: Bool -> Maybe Int -> [Block] -> [Block]
+makeSections = makeSectionsWithOffsets []
 
--- | Convert list of Pandoc blocks into (hierarchical) list of Elements
-hierarchicalize :: [Block] -> [Element]
-hierarchicalize blocks = S.evalState (hierarchicalizeWithIds blocks) []
+-- | Like 'makeSections', but with a parameter for number offsets
+-- (a list of 'Int's, the first of which is added to the level 1
+-- section number, the second to the level 2, and so on).
+makeSectionsWithOffsets :: [Int] -> Bool -> Maybe Int -> [Block] -> [Block]
+makeSectionsWithOffsets numoffsets numbering mbBaseLevel bs =
+  S.evalState (go bs) numoffsets
+ where
+  getLevel (Header level _ _) = Min level
+  getLevel _ = Min 99
+  minLevel = if all (== 0) numoffsets
+                then getMin $ query getLevel bs
+                else 1 -- see #5071, for backwards compatibility
+  go :: [Block] -> S.State [Int] [Block]
+  go (Header level (ident,classes,kvs) title':xs) = do
+    lastnum <- S.get
+    let level' = maybe level (\n -> n + level - minLevel) mbBaseLevel
+    let adjustNum lev numComponent
+          | lev < level = numComponent
+          | lev == level = numComponent + 1
+          | otherwise = 0
+    let newnum = zipWith adjustNum [minLevel..level]
+                    (lastnum ++ repeat 0)
+    unless (null newnum || "unnumbered" `elem` classes) $ S.put newnum
+    let (sectionContents, rest) = break (headerLtEq level) xs
+    sectionContents' <- go sectionContents
+    rest' <- go rest
+    let kvs' = -- don't touch number if already present
+               case lookup "number" kvs of
+                  Nothing | numbering
+                          , "unnumbered" `notElem` classes ->
+                        ("number", T.intercalate "." (map tshow newnum)) : kvs
+                  _ -> kvs
+    let divattr = (ident, "section":classes, kvs')
+    let isHeadingAttr ("epub:type",_) = False
+        isHeadingAttr ("role",v) =
+          v `elem` ["tab", "presentation", "none", "treeitem",
+                    "menuitem", "button", "heading"]
+        isHeadingAttr _ = True
+    let hattr = ("",classes, filter isHeadingAttr kvs')
+    return $
+      Div divattr (Header level' hattr title' : sectionContents') : rest'
+  go (Div divattr@(dident,dclasses,_) (Header level hattr title':ys) : xs)
+      | all (\case
+               Header level' _ _ -> level' > level
+               _                 -> True) ys
+      , "column" `notElem` dclasses
+      , "columns" `notElem` dclasses
+      , "fragment" `notElem` dclasses = do
+    inner <- go (Header level hattr title':ys)
+    rest <- go xs
+    return $
+      case inner of
+            [Div divattr'@(dident',_,_) zs]
+              | T.null dident || T.null dident' || dident == dident'
+              -> Div (combineAttr divattr' divattr) zs : rest
+            _ -> Div divattr inner : rest
+  go (Div attr xs : rest) = do
+    xs' <- go xs
+    rest' <- go rest
+    return $ Div attr xs' : rest'
+  go (x:xs) = (x :) <$> go xs
+  go [] = return []
 
-hierarchicalizeWithIds :: [Block] -> S.State [Int] [Element]
-hierarchicalizeWithIds [] = return []
-hierarchicalizeWithIds (Header level attr@(_,classes,_) title':xs) = do
-  lastnum <- S.get
-  let lastnum' = take level lastnum
-  let newnum = case length lastnum' of
-                    x | "unnumbered" `elem` classes -> []
-                      | x >= level -> init lastnum' ++ [last lastnum' + 1]
-                      | otherwise -> lastnum ++
-                           replicate (level - length lastnum - 1) 0 ++ [1]
-  unless (null newnum) $ S.put newnum
-  let (sectionContents, rest) = break (headerLtEq level) xs
-  sectionContents' <- hierarchicalizeWithIds sectionContents
-  rest' <- hierarchicalizeWithIds rest
-  return $ Sec level newnum attr title' sectionContents' : rest'
-hierarchicalizeWithIds (Div ("",["references"],[])
-                         (Header level (ident,classes,kvs) title' : xs):ys) =
-  hierarchicalizeWithIds (Header level (ident,("references":classes),kvs)
-                           title' : (xs ++ ys))
-hierarchicalizeWithIds (x:rest) = do
-  rest' <- hierarchicalizeWithIds rest
-  return $ Blk x : rest'
+-- | Combine two 'Attr'. Classes are concatenated.  For the id and key-value
+-- attributes, the first one takes precedence in case of duplicates.
+combineAttr :: Attr -> Attr -> Attr
+combineAttr (id1, classes1, kvs1) (id2, classes2, kvs2) =
+  (if T.null id1 then id2 else id1,
+   nubOrd (classes1 ++ classes2),
+   foldr (\(k,v) kvs -> case lookup k kvs of
+                           Nothing -> (k,v):kvs
+                           Just _  -> kvs) kvs1 kvs2)
 
 headerLtEq :: Int -> Block -> Bool
-headerLtEq level (Header l _ _)                                  = l <= level
-headerLtEq level (Div ("",["references"],[]) (Header l _ _ : _)) = l <= level
-headerLtEq _ _                                                   = False
+headerLtEq level (Header l _ _)  = l <= level
+headerLtEq level (Div _ (b:_))   = headerLtEq level b
+headerLtEq _ _                   = False
 
 -- | Generate a unique identifier from a list of inlines.
 -- Second argument is a list of already used identifiers.
-uniqueIdent :: [Inline] -> Set.Set String -> String
-uniqueIdent title' usedIdents
-  =  let baseIdent = case inlineListToIdentifier title' of
-                        "" -> "section"
-                        x  -> x
-         numIdent n = baseIdent ++ "-" ++ show n
-     in  if baseIdent `Set.member` usedIdents
-           then case find (\x -> not $ numIdent x `Set.member` usedIdents) ([1..60000] :: [Int]) of
-                  Just x  -> numIdent x
-                  Nothing -> baseIdent   -- if we have more than 60,000, allow repeats
-           else baseIdent
+uniqueIdent :: Extensions -> [Inline] -> Set.Set T.Text -> T.Text
+uniqueIdent exts title' usedIdents =
+  if baseIdent `Set.member` usedIdents
+     then maybe baseIdent numIdent
+          $ find (\x -> numIdent x `Set.notMember` usedIdents) ([1..60000] :: [Int])
+          -- if we have more than 60,000, allow repeats
+     else baseIdent
+  where
+    baseIdent = case inlineListToIdentifier exts title' of
+                     "" -> "section"
+                     x  -> x
+    numIdent n = baseIdent <> "-" <> tshow n
 
+-- | True if inlines include a LineBreak (possibly embedded), with the exception
+-- of line breaks in Notes.
+hasLineBreaks :: [Inline] -> Bool
+hasLineBreaks = getAny . query isLineBreak . walk removeNote
+  where
+    removeNote :: Inline -> Inline
+    removeNote (Note _) = Str ""
+    removeNote x        = x
+    isLineBreak :: Inline -> Any
+    isLineBreak LineBreak = Any True
+    isLineBreak _         = Any False
+
 -- | True if block is a Header block.
 isHeaderBlock :: Block -> Bool
 isHeaderBlock Header{} = True
 isHeaderBlock _        = False
 
--- | Shift header levels up or down.
-headerShift :: Int -> Pandoc -> Pandoc
-headerShift n = walk shift
-  where shift :: Block -> Block
-        shift (Header level attr inner) = Header (level + n) attr inner
-        shift x                         = x
-
--- | Remove empty paragraphs.
-stripEmptyParagraphs :: Pandoc -> Pandoc
-stripEmptyParagraphs = walk go
-  where go :: [Block] -> [Block]
-        go = filter (not . isEmptyParagraph)
-        isEmptyParagraph (Para []) = True
-        isEmptyParagraph _         = False
+-- | Detect if table rows contain only cells consisting of a single
+-- paragraph that has no @LineBreak@.
+onlySimpleTableCells :: [[[Block]]] -> Bool
+onlySimpleTableCells = all isSimpleCell . concat
+  where
+    isSimpleCell [Plain ils] = not (hasLineBreak ils)
+    isSimpleCell [Para ils ] = not (hasLineBreak ils)
+    isSimpleCell []          = True
+    isSimpleCell _           = False
+    hasLineBreak = getAny . query isLineBreak
+    isLineBreak LineBreak = Any True
+    isLineBreak _         = Any False
 
 -- | Detect if a list is tight.
 isTightList :: [[Block]] -> Bool
-isTightList = all firstIsPlain
-  where firstIsPlain (Plain _ : _) = True
-        firstIsPlain _             = False
+isTightList = all isPlainItem
+  where
+    isPlainItem [] = True
+    isPlainItem (Plain _ : _) = True
+    isPlainItem [BulletList xs] = isTightList xs
+    isPlainItem [OrderedList _ xs] = isTightList xs
+    isPlainItem _ = False
 
+-- | Convert a list item containing tasklist syntax (e.g. @[x]@)
+-- to using @U+2610 BALLOT BOX@ or @U+2612 BALLOT BOX WITH X@.
+taskListItemFromAscii :: Extensions -> [Block] -> [Block]
+taskListItemFromAscii = handleTaskListItem fromMd
+  where
+    fromMd (Str "[" : Space : Str "]" : Space : is) = Str "☐" : Space : is
+    fromMd (Str "[x]"                 : Space : is) = Str "☒" : Space : is
+    fromMd (Str "[X]"                 : Space : is) = Str "☒" : Space : is
+    fromMd is = is
+
+-- | Convert a list item containing text starting with @U+2610 BALLOT BOX@
+-- or @U+2612 BALLOT BOX WITH X@ to tasklist syntax (e.g. @[x]@).
+taskListItemToAscii :: Extensions -> [Block] -> [Block]
+taskListItemToAscii = handleTaskListItem toMd
+  where
+    toMd (Str "☐" : Space : is) = rawMd "[ ]" : Space : is
+    toMd (Str "☒" : Space : is) = rawMd "[x]" : Space : is
+    toMd (Str "❏" : Space : is) = rawMd "[ ]" : Space : is
+    toMd (Str "✓" : Space : is) = rawMd "[x]" : Space : is
+    toMd is = is
+    rawMd = RawInline (Format "markdown")
+
+handleTaskListItem :: ([Inline] -> [Inline]) -> Extensions -> [Block] -> [Block]
+handleTaskListItem handleInlines exts bls =
+  if Ext_task_lists `extensionEnabled` exts
+  then handleItem bls
+  else bls
+  where
+    handleItem (Plain is : bs) = Plain (handleInlines is) : bs
+    handleItem (Para is  : bs) = Para  (handleInlines is) : bs
+    handleItem bs = bs
+
 -- | Set a field of a 'Meta' object.  If the field already has a value,
 -- convert it into a list with the new value appended to the old value(s).
 addMetaField :: ToMetaValue a
-             => String
+             => T.Text
              -> a
              -> Meta
              -> Meta
@@ -559,42 +703,44 @@
         tolist (MetaList ys) = ys
         tolist y             = [y]
 
--- | Create 'Meta' from old-style title, authors, date.  This is
--- provided to ease the transition from the old API.
-makeMeta :: [Inline] -> [[Inline]] -> [Inline] -> Meta
-makeMeta title authors date =
-      addMetaField "title" (B.fromList title)
-    $ addMetaField "author" (map B.fromList authors)
-    $ addMetaField "date" (B.fromList date) nullMeta
-
--- | Remove soft breaks between East Asian characters.
-eastAsianLineBreakFilter :: Pandoc -> Pandoc
-eastAsianLineBreakFilter = bottomUp go
-  where go (x:SoftBreak:y:zs) =
-         case (stringify x, stringify y) of
-               (xs@(_:_), c:_)
-                 | charWidth (last xs) == 2 && charWidth c == 2 -> x:y:zs
-               _ -> x:SoftBreak:y:zs
-        go xs = xs
-
--- | Builder for underline.
--- This probably belongs in Builder.hs in pandoc-types.
--- Will be replaced once Underline is an element.
-underlineSpan :: Inlines -> Inlines
-underlineSpan = B.spanWith ("", ["underline"], [])
+-- | Set of HTML elements that are represented as Span with a class equal as
+-- the element tag itself.
+htmlSpanLikeElements :: Set.Set T.Text
+htmlSpanLikeElements = Set.fromList ["kbd", "mark", "dfn", "abbr"]
 
+-- | Reformat 'Inlines' as code, putting the stringlike parts in 'Code'
+-- elements while bringing other inline formatting outside.
+-- The idea is that e.g. `[Str "a",Space,Strong [Str "b"]]` should turn
+-- into `[Code ("",[],[]) "a ", Strong [Code ("",[],[]) "b"]]`.
+-- This helps work around the limitation that pandoc's Code element can
+-- only contain string content (see issue #7525).
+formatCode :: Attr -> Inlines -> Inlines
+formatCode attr = B.fromList . walk fmt . B.toList
+  where
+    isPlaintext (Str _) = True
+    isPlaintext Space = True
+    isPlaintext SoftBreak = True
+    isPlaintext (Quoted _ _) = True
+    isPlaintext _ = False
+    fmt = concatMap go . groupBy (\a b -> isPlaintext a && isPlaintext b)
+      where
+        go xs
+          | all isPlaintext xs = B.toList $ B.codeWith attr $ stringify xs
+          | otherwise = xs
 
 --
 -- TagSoup HTML handling
 --
 
 -- | Render HTML tags.
-renderTags' :: [Tag String] -> String
+renderTags' :: [Tag T.Text] -> T.Text
 renderTags' = renderTagsOptions
-               renderOptions{ optMinimize = matchTags ["hr", "br", "img",
-                                                       "meta", "link"]
-                            , optRawTag   = matchTags ["script", "style"] }
-              where matchTags tags = flip elem tags . map toLower
+               renderOptions{ optMinimize = \t -> T.toLower t `Set.member` minimizeTags
+                            , optRawTag   = \t -> T.toLower t `Set.member` rawTags }
+  where
+    minimizeTags = Set.fromList ["hr","br","img","meta","link","col",
+                                 "use","path","rect"]
+    rawTags = Set.fromList ["script","style"]
 
 --
 -- File handling
@@ -607,13 +753,14 @@
                              setCurrentDirectory
                              (const $ setCurrentDirectory path >> action)
 
---
--- Error reporting
---
-
-mapLeft :: (a -> b) -> Either a c -> Either b c
-mapLeft f (Left x)  = Left (f x)
-mapLeft _ (Right x) = Right x
+-- | Canonicalizes a file path by removing redundant @.@ and @..@.
+makeCanonical :: FilePath -> FilePath
+makeCanonical = Posix.joinPath . transformPathParts . splitDirectories
+ where  transformPathParts = reverse . L.foldl' go []
+        go as        "."  = as
+        go ("..":as) ".." = ["..", ".."] <> as
+        go (_:as)    ".." = as
+        go as        x    = x : as
 
 -- | Remove intermediate "." and ".." directories from a path.
 --
@@ -625,7 +772,7 @@
 -- > collapseFilePath "parent/foo/.." ==  "parent"
 -- > collapseFilePath "/parent/foo/../../bar" ==  "/bar"
 collapseFilePath :: FilePath -> FilePath
-collapseFilePath = Posix.joinPath . reverse . foldl go [] . splitDirectories
+collapseFilePath = Posix.joinPath . reverse . L.foldl' go [] . splitDirectories
   where
     go rs "." = rs
     go r@(p:rs) ".." = case p of
@@ -649,71 +796,6 @@
     fileAndBinary :: Archive -> FilePath -> Maybe (FilePath, BL.ByteString)
     fileAndBinary a fp = findEntryByPath fp a >>= \e -> Just (fp, fromEntry e)
 
-
---
--- IANA URIs
---
-
--- | Schemes from http://www.iana.org/assignments/uri-schemes.html plus
--- the unofficial schemes doi, javascript, isbn, pmid.
-schemes :: Set.Set String
-schemes = Set.fromList
-  -- Official IANA schemes
-  [ "aaa", "aaas", "about", "acap", "acct", "acr", "adiumxtra", "afp", "afs"
-  , "aim", "appdata", "apt", "attachment", "aw", "barion", "beshare", "bitcoin"
-  , "blob", "bolo", "browserext", "callto", "cap", "chrome", "chrome-extension"
-  , "cid", "coap", "coaps", "com-eventbrite-attendee", "content", "crid", "cvs"
-  , "data", "dav", "dict", "dis", "dlna-playcontainer", "dlna-playsingle"
-  , "dns", "dntp", "dtn", "dvb", "ed2k", "example", "facetime", "fax", "feed"
-  , "feedready", "file", "filesystem", "finger", "fish", "ftp", "geo", "gg"
-  , "git", "gizmoproject", "go", "gopher", "graph", "gtalk", "h323", "ham"
-  , "hcp", "http", "https", "hxxp", "hxxps", "hydrazone", "iax", "icap", "icon"
-  , "im", "imap", "info", "iotdisco", "ipn", "ipp", "ipps", "irc", "irc6"
-  , "ircs", "iris", "iris.beep", "iris.lwz", "iris.xpc", "iris.xpcs"
-  , "isostore", "itms", "jabber", "jar", "jms", "keyparc", "lastfm", "ldap"
-  , "ldaps", "lvlt", "magnet", "mailserver", "mailto", "maps", "market"
-  , "message", "mid", "mms", "modem", "mongodb", "moz", "ms-access"
-  , "ms-browser-extension", "ms-drive-to", "ms-enrollment", "ms-excel"
-  , "ms-gamebarservices", "ms-getoffice", "ms-help", "ms-infopath"
-  , "ms-media-stream-id", "ms-officeapp", "ms-project", "ms-powerpoint"
-  , "ms-publisher", "ms-search-repair", "ms-secondary-screen-controller"
-  , "ms-secondary-screen-setup", "ms-settings", "ms-settings-airplanemode"
-  , "ms-settings-bluetooth", "ms-settings-camera", "ms-settings-cellular"
-  , "ms-settings-cloudstorage", "ms-settings-connectabledevices"
-  , "ms-settings-displays-topology", "ms-settings-emailandaccounts"
-  , "ms-settings-language", "ms-settings-location", "ms-settings-lock"
-  , "ms-settings-nfctransactions", "ms-settings-notifications"
-  , "ms-settings-power", "ms-settings-privacy", "ms-settings-proximity"
-  , "ms-settings-screenrotation", "ms-settings-wifi", "ms-settings-workplace"
-  , "ms-spd", "ms-sttoverlay", "ms-transit-to", "ms-virtualtouchpad"
-  , "ms-visio", "ms-walk-to", "ms-whiteboard", "ms-whiteboard-cmd", "ms-word"
-  , "msnim", "msrp", "msrps", "mtqp", "mumble", "mupdate", "mvn", "news", "nfs"
-  , "ni", "nih", "nntp", "notes", "ocf", "oid", "onenote", "onenote-cmd"
-  , "opaquelocktoken", "pack", "palm", "paparazzi", "pkcs11", "platform", "pop"
-  , "pres", "prospero", "proxy", "pwid", "psyc", "qb", "query", "redis"
-  , "rediss", "reload", "res", "resource", "rmi", "rsync", "rtmfp", "rtmp"
-  , "rtsp", "rtsps", "rtspu", "secondlife", "service", "session", "sftp", "sgn"
-  , "shttp", "sieve", "sip", "sips", "skype", "smb", "sms", "smtp", "snews"
-  , "snmp", "soap.beep", "soap.beeps", "soldat", "spotify", "ssh", "steam"
-  , "stun", "stuns", "submit", "svn", "tag", "teamspeak", "tel", "teliaeid"
-  , "telnet", "tftp", "things", "thismessage", "tip", "tn3270", "tool", "turn"
-  , "turns", "tv", "udp", "unreal", "urn", "ut2004", "v-event", "vemmi"
-  , "ventrilo", "videotex", "vnc", "view-source", "wais", "webcal", "wpid"
-  , "ws", "wss", "wtai", "wyciwyg", "xcon", "xcon-userid", "xfire"
-  , "xmlrpc.beep", "xmlrpc.beeps", "xmpp", "xri", "ymsgr", "z39.50", "z39.50r"
-  , "z39.50s"
-  -- Inofficial schemes
-  , "doi", "isbn", "javascript", "pmid"
-  ]
-
--- | Check if the string is a valid URL with a IANA or frequently used but
--- unofficial scheme (see @schemes@).
-isURI :: String -> Bool
-isURI = maybe False hasKnownScheme . parseURI
-  where
-    hasKnownScheme = (`Set.member` schemes) . map toLower .
-                     filter (/= ':') . uriScheme
-
 ---
 --- Squash blocks into inlines
 ---
@@ -736,42 +818,44 @@
       mconcat (map blocksToInlines' blkslst)
 blockToInlines (Header _ _  ils) = B.fromList ils
 blockToInlines HorizontalRule = mempty
-blockToInlines (Table _ _ _ headers rows) =
+blockToInlines (Table _ _ _ (TableHead _ hbd) bodies (TableFoot _ fbd)) =
   mconcat $ intersperse B.linebreak $
-    map (mconcat . map blocksToInlines') (headers:rows)
+    map (mconcat . map blocksToInlines') (plainRowBody <$> hbd <> unTableBodies bodies <> fbd)
+  where
+    plainRowBody (Row _ body) = cellBody <$> body
+    cellBody (Cell _ _ _ _ body) = body
+    unTableBody (TableBody _ _ hd bd) = hd <> bd
+    unTableBodies = concatMap unTableBody
 blockToInlines (Div _ blks) = blocksToInlines' blks
-blockToInlines Null = mempty
+blockToInlines (Figure _ _ body) = blocksToInlines' body
 
 blocksToInlinesWithSep :: Inlines -> [Block] -> Inlines
 blocksToInlinesWithSep sep =
   mconcat . intersperse sep . map blockToInlines
 
 blocksToInlines' :: [Block] -> Inlines
-blocksToInlines' = blocksToInlinesWithSep parSep
-  where parSep = B.space <> B.str "¶" <> B.space
+blocksToInlines' = blocksToInlinesWithSep defaultBlocksSeparator
 
 blocksToInlines :: [Block] -> [Inline]
 blocksToInlines = B.toList . blocksToInlines'
 
+-- | Inline elements used to separate blocks when squashing blocks into
+-- inlines.
+defaultBlocksSeparator :: Inlines
+defaultBlocksSeparator =
+  -- This is used in the pandoc.utils.blocks_to_inlines function. Docs
+  -- there should be updated if this is changed.
+  B.linebreak
 
 --
 -- Safe read
 --
 
-safeRead :: (MonadPlus m, Read a) => String -> m a
-safeRead s = case reads s of
+safeRead :: (MonadPlus m, Read a) => T.Text -> m a
+safeRead = safeStrRead . T.unpack
+
+safeStrRead :: (MonadPlus m, Read a) => String -> m a
+safeStrRead s = case reads s of
                   (d,x):_
                     | all isSpace x -> return d
                   _                 -> mzero
-
---
--- Temp directory
---
-
-withTempDir :: String -> (FilePath -> IO a) -> IO a
-withTempDir =
-#ifdef _WINDOWS
-  withTempDirectory "."
-#else
-  withSystemTempDirectory
-#endif
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,24 +1,7 @@
-{-
-Copyright (C) 2012-2017 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 OverloadedStrings #-}
 {- |
    Module      : Text.Pandoc.Slides
-   Copyright   : Copyright (C) 2012-2017 John MacFarlane
+   Copyright   : Copyright (C) 2012-2024 John MacFarlane
    License     : GNU GPL, version 2 or above
 
    Maintainer  : John MacFarlane <jgm@berkeley.edu>
@@ -38,13 +21,14 @@
   where go least (Header n _ _ : x : xs)
                  | n < least && nonHOrHR x = go n xs
                  | otherwise               = go least (x:xs)
+        go least (Div _ bs : xs) = min (go least bs) (go least xs)
         go least (_ : xs) = go least xs
         go least [] = least
         nonHOrHR Header{}       = False
         nonHOrHR HorizontalRule = False
         nonHOrHR _              = True
 
--- | Prepare a block list to be passed to hierarchicalize.
+-- | Prepare a block list to be passed to makeSections.
 prepSlides :: Int -> [Block] -> [Block]
 prepSlides slideLevel = ensureStartWithH . splitHrule . extractRefsHeader
   where splitHrule (HorizontalRule : Header n attr xs : ys)
@@ -55,9 +39,12 @@
         splitHrule []                    = []
         extractRefsHeader bs             =
           case reverse bs of
-               (Div ("",["references"],[]) (Header n attrs xs : ys) : zs)
-                 -> reverse zs ++ (Header n attrs xs : [Div ("",["references"],[]) ys])
+               (Div ("refs",classes,kvs) (Header n attrs xs : ys) : zs)
+                 -> reverse zs ++ [Header n attrs xs,
+                                   Div ("refs",classes,kvs) ys]
                _ -> bs
         ensureStartWithH bs@(Header n _ _:_)
+                       | n <= slideLevel = bs
+        ensureStartWithH bs@(Div _ (Header n _ _:_) : _)
                        | n <= slideLevel = bs
         ensureStartWithH bs              = Header slideLevel nullAttr [Str "\0"] : bs
diff --git a/src/Text/Pandoc/Sources.hs b/src/Text/Pandoc/Sources.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Sources.hs
@@ -0,0 +1,207 @@
+{-# LANGUAGE BangPatterns #-}
+{-# LANGUAGE FlexibleInstances #-}
+{-# LANGUAGE FlexibleContexts #-}
+{-# LANGUAGE MultiParamTypeClasses #-}
+{-# LANGUAGE GeneralizedNewtypeDeriving #-}
+{-# LANGUAGE OverloadedStrings #-}
+{- |
+   Module      : Text.Pandoc.Sources
+   Copyright   : Copyright (C) 2021-2024 John MacFarlane
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : John MacFarlane <jgm@berkeley.edu>
+   Stability   : alpha
+   Portability : portable
+
+Defines Sources object to be used as input to pandoc parsers and redefines Char
+parsers so they get source position information from it.
+-}
+
+module Text.Pandoc.Sources
+  ( Sources(..)
+  , ToSources(..)
+  , UpdateSourcePos(..)
+  , sourcesToText
+  , initialSourceName
+  , addToSources
+  , ensureFinalNewlines
+  , addToInput
+  , satisfy
+  , oneOf
+  , noneOf
+  , anyChar
+  , char
+  , string
+  , newline
+  , space
+  , spaces
+  , letter
+  , digit
+  , hexDigit
+  , alphaNum
+  )
+where
+import qualified Text.Parsec as P
+import Text.Parsec (Stream(..), ParsecT)
+import Text.Parsec.Pos as P
+import Data.Text (Text)
+import qualified Data.Text as T
+import qualified Data.ByteString as BS
+import qualified Data.ByteString.Lazy as BL
+import Data.Char (isSpace, isLetter, isAlphaNum, isDigit, isHexDigit)
+import Data.String (IsString(..))
+import qualified Data.List.NonEmpty as NonEmpty
+
+-- | A list of inputs labeled with source positions.  It is assumed
+-- that the 'Text's have @\n@ line endings.
+newtype Sources = Sources { unSources :: [(SourcePos, Text)] }
+  deriving (Show, Semigroup, Monoid)
+
+instance Monad m => Stream Sources m Char where
+  uncons (Sources []) = return Nothing
+  uncons (Sources ((pos,t):rest)) =
+    case T.uncons t of
+      Nothing -> uncons (Sources rest)
+      Just (c,t') -> return $ Just (c, Sources ((pos,t'):rest))
+
+instance IsString Sources where
+  fromString s = Sources [(P.initialPos "", T.pack (filter (/='\r') s))]
+
+class ToSources a where
+  toSources :: a -> Sources
+
+instance ToSources Text where
+  toSources t = Sources [(P.initialPos "", T.filter (/='\r') t)]
+
+instance ToSources [(FilePath, Text)] where
+  toSources = Sources
+            . map (\(fp,t) ->
+                    (P.initialPos fp, T.snoc (T.filter (/='\r') t) '\n'))
+
+instance ToSources Sources where
+  toSources = id
+
+sourcesToText :: Sources -> Text
+sourcesToText (Sources xs) = mconcat $ map snd xs
+
+addToSources :: Monad m => SourcePos -> Text -> ParsecT Sources u m ()
+addToSources pos t = do
+  curpos <- P.getPosition
+  Sources xs <- P.getInput
+  let xs' = case xs of
+               [] -> []
+               ((_,t'):rest) -> (curpos,t'):rest
+  P.setInput $ Sources ((pos, T.filter (/='\r') t):xs')
+
+ensureFinalNewlines :: Int -- ^ number of trailing newlines
+                    -> Sources
+                    -> Sources
+ensureFinalNewlines n (Sources xs) =
+  case NonEmpty.nonEmpty xs of
+    Nothing -> Sources [(initialPos "", T.replicate n "\n")]
+    Just lst ->
+      case NonEmpty.last lst of
+        (spos, t) ->
+          case T.length (T.takeWhileEnd (=='\n') t) of
+            len | len >= n -> Sources xs
+                | otherwise -> Sources (NonEmpty.init lst ++
+                                        [(spos,
+                                          t <> T.replicate (n - len) "\n")])
+
+class UpdateSourcePos s c where
+  updateSourcePos :: SourcePos -> c -> s -> SourcePos
+
+instance UpdateSourcePos Text Char where
+   updateSourcePos pos c _ = updatePosChar pos c
+
+instance UpdateSourcePos [Char] Char where
+   updateSourcePos pos c _ = updatePosChar pos c
+
+instance UpdateSourcePos BS.ByteString Char where
+   updateSourcePos pos c _ = updatePosChar pos c
+
+instance UpdateSourcePos BL.ByteString Char where
+   updateSourcePos pos c _ = updatePosChar pos c
+
+instance UpdateSourcePos Sources Char where
+   updateSourcePos pos c sources =
+     case sources of
+       Sources [] -> updatePosChar pos c
+       Sources ((_,t):(pos',_):_)
+         | T.null t  -> pos'
+       Sources _ ->
+           case c of
+             '\n' -> incSourceLine (setSourceColumn pos 1) 1
+             '\t' -> incSourceColumn pos (4 - ((sourceColumn pos - 1) `mod` 4))
+             _    -> incSourceColumn pos 1
+
+-- | Get name of first source in 'Sources'.
+initialSourceName :: Sources -> FilePath
+initialSourceName (Sources []) = ""
+initialSourceName (Sources ((pos,_):_)) = sourceName pos
+
+-- | Add some text to the beginning of the input sources.
+-- This simplifies code that expands macros.
+addToInput :: Monad m => Text -> ParsecT Sources u m ()
+addToInput t = do
+  Sources xs <- P.getInput
+  case xs of
+    [] -> P.setInput $ Sources [(initialPos "",t)]
+    (pos,t'):rest -> P.setInput $ Sources ((pos, t <> t'):rest)
+
+-- We need to redefine the parsers in Text.Parsec.Char so that they
+-- update source positions properly from the Sources stream.
+
+satisfy :: (Monad m, Stream s m Char, UpdateSourcePos s Char)
+         => (Char -> Bool) -> ParsecT s u m Char
+satisfy f = P.tokenPrim show updateSourcePos matcher
+ where
+  matcher !c = if f c then Just c else Nothing
+
+oneOf :: (Monad m, Stream s m Char, UpdateSourcePos s Char)
+      => [Char] -> ParsecT s u m Char
+oneOf cs = satisfy (`elem` cs)
+
+noneOf :: (Monad m, Stream s m Char, UpdateSourcePos s Char)
+       => [Char] -> ParsecT s u m Char
+noneOf cs = satisfy (`notElem` cs)
+
+anyChar :: (Monad m, Stream s m Char, UpdateSourcePos s Char)
+        => ParsecT s u m Char
+anyChar = satisfy (const True)
+
+char :: (Monad m, Stream s m Char, UpdateSourcePos s Char)
+     => Char -> ParsecT s u m Char
+char c = satisfy (== c)
+
+string :: (Monad m, Stream s m Char, UpdateSourcePos s Char)
+       => [Char] -> ParsecT s u m [Char]
+string = mapM char
+
+newline :: (Monad m, Stream s m Char, UpdateSourcePos s Char)
+        => ParsecT s u m Char
+newline = satisfy (== '\n')
+
+space :: (Monad m, Stream s m Char, UpdateSourcePos s Char)
+      => ParsecT s u m Char
+space = satisfy isSpace
+
+spaces :: (Monad m, Stream s m Char, UpdateSourcePos s Char)
+       => ParsecT s u m ()
+spaces = P.skipMany space P.<?> "white space"
+
+letter :: (Monad m, Stream s m Char, UpdateSourcePos s Char)
+       => ParsecT s u m Char
+letter = satisfy isLetter
+
+alphaNum :: (Monad m, Stream s m Char, UpdateSourcePos s Char)
+         => ParsecT s u m Char
+alphaNum = satisfy isAlphaNum
+
+digit :: (Monad m, Stream s m Char, UpdateSourcePos s Char)
+      => ParsecT s u m Char
+digit = satisfy isDigit
+
+hexDigit :: (Monad m, Stream s m Char, UpdateSourcePos s Char)
+         => ParsecT s u m Char
+hexDigit = satisfy isHexDigit
diff --git a/src/Text/Pandoc/TeX.hs b/src/Text/Pandoc/TeX.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/TeX.hs
@@ -0,0 +1,54 @@
+{-# LANGUAGE FlexibleInstances #-}
+{- |
+   Module      : Text.Pandoc.TeX
+   Copyright   : Copyright (C) 2017-2024 John MacFarlane
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : John MacFarlane <jgm@berkeley.edu>
+   Stability   : alpha
+   Portability : portable
+
+Types for TeX tokens and macros.
+-}
+module Text.Pandoc.TeX ( Tok(..)
+                       , TokType(..)
+                       , Macro(..)
+                       , ArgSpec(..)
+                       , ExpansionPoint(..)
+                       , MacroScope(..)
+                       , SourcePos
+                       )
+where
+import Data.Text (Text)
+import Text.Parsec (SourcePos, sourceName)
+import Text.Pandoc.Sources
+import Data.List (groupBy)
+
+data TokType = CtrlSeq Text | Spaces | Newline | Symbol | Word | Comment |
+               Esc1    | Esc2   | Arg Int  | DeferredArg Int
+     deriving (Eq, Ord, Show)
+
+data Tok = Tok SourcePos TokType Text
+     deriving (Eq, Ord, Show)
+
+instance ToSources [Tok] where
+  toSources = Sources
+    . map (\ts -> case ts of
+                    Tok p _ _ : _ -> (p, mconcat $ map tokToText ts)
+                    _ -> error "toSources [Tok] encountered empty group")
+    . groupBy (\(Tok p1 _ _) (Tok p2 _ _) -> sourceName p1 == sourceName p2)
+
+tokToText :: Tok -> Text
+tokToText (Tok _ _ t) = t
+
+data ExpansionPoint = ExpandWhenDefined | ExpandWhenUsed
+     deriving (Eq, Ord, Show)
+
+data MacroScope = GlobalScope | GroupScope
+  deriving (Eq, Ord, Show)
+
+data Macro = Macro MacroScope ExpansionPoint [ArgSpec] (Maybe [Tok]) [Tok]
+     deriving Show
+
+data ArgSpec = ArgNum Int | Pattern [Tok]
+     deriving Show
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,84 +1,144 @@
-{-# LANGUAGE FlexibleInstances    #-}
-
-{-# LANGUAGE OverloadedStrings    #-}
-{-# LANGUAGE TypeSynonymInstances #-}
-{-
-Copyright (C) 2009-2017 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 GeneralizedNewtypeDeriving #-}
+{-# LANGUAGE MultiParamTypeClasses #-}
+{-# LANGUAGE ScopedTypeVariables #-}
+{-# LANGUAGE OverloadedStrings #-}
 {- |
    Module      : Text.Pandoc.Templates
-   Copyright   : Copyright (C) 2009-2017 John MacFarlane
+   Copyright   : Copyright (C) 2009-2024 John MacFarlane
    License     : GNU GPL, version 2 or above
 
    Maintainer  : John MacFarlane <jgm@berkeley.edu>
    Stability   : alpha
    Portability : portable
 
-A simple templating system with variable substitution and conditionals.
+Utility functions for working with pandoc templates.
 
+'WithDefaultPartials' and 'WithPartials' are Monad wrappers. Wrapping
+these around an instance of 'PandocMonad' gives different instances of
+'TemplateMonad', with different search behaviors when retrieving
+partials.
+
+To compile a template and limit partial search to pandoc’s data files,
+use @runWithDefaultPartials (compileTemplate ...)@.
+
+To compile a template and allow partials to be found locally (either on
+the file system or via HTTP, in the event that the main template has an
+absolute URL), ue @runWithPartials (compileTemplate ...)@.
+
+'getTemplate' seeks a template locally, or via HTTP if the template has
+an absolute URL, falling back to the data files if not found.
+
 -}
 
-module Text.Pandoc.Templates ( module Text.DocTemplates
-                             , renderTemplate'
+module Text.Pandoc.Templates ( Template
+                             , WithDefaultPartials(..)
+                             , WithPartials(..)
+                             , compileTemplate
+                             , renderTemplate
+                             , getTemplate
                              , getDefaultTemplate
+                             , compileDefaultTemplate
                              ) where
 
-import Control.Monad.Except (throwError)
-import Data.Aeson (ToJSON (..))
+import System.FilePath ((<.>), (</>), takeFileName)
+import Text.DocTemplates (Template, TemplateMonad(..), compileTemplate, renderTemplate)
+import Text.Pandoc.Class.CommonState (CommonState(..))
+import Text.Pandoc.Class.PandocMonad (PandocMonad, fetchItem,
+                                      getCommonState, modifyCommonState,
+                                      toTextM)
+import Text.Pandoc.Data (readDataFile)
+import Control.Monad.Except (catchError, throwError)
+import Data.Text (Text)
 import qualified Data.Text as T
-import System.FilePath ((<.>), (</>))
-import Text.DocTemplates (Template, TemplateTarget, applyTemplate,
-                          compileTemplate, renderTemplate, varListToJSON)
-import Text.Pandoc.Class (PandocMonad, readDataFile)
 import Text.Pandoc.Error
-import qualified Text.Pandoc.UTF8 as UTF8
+import System.IO.Error (isDoesNotExistError)
 
+-- | Wrap a Monad in this if you want partials to
+-- be taken only from the default data files.
+newtype WithDefaultPartials m a = WithDefaultPartials { runWithDefaultPartials :: m a }
+ deriving (Functor, Applicative, Monad)
+
+-- | Wrap a Monad in this if you want partials to
+-- be looked for locally (or, when the main template
+-- is at a URL, via HTTP), falling back to default data files.
+newtype WithPartials m a = WithPartials { runWithPartials :: m a }
+ deriving (Functor, Applicative, Monad)
+
+instance PandocMonad m => TemplateMonad (WithDefaultPartials m) where
+  getPartial fp = WithDefaultPartials $
+    readDataFile ("templates" </> takeFileName fp) >>= toTextM fp
+
+instance PandocMonad m => TemplateMonad (WithPartials m) where
+  getPartial fp = WithPartials $ getTemplate fp
+
+-- | Retrieve text for a template.
+getTemplate :: PandocMonad m => FilePath -> m Text
+getTemplate tp =
+  ((do surl <- stSourceURL <$> getCommonState
+       -- we don't want to look for templates remotely
+       -- unless the full URL is specified:
+       modifyCommonState $ \st -> st{
+         stSourceURL = Nothing }
+       (bs, _) <- fetchItem $ T.pack tp
+       modifyCommonState $ \st -> st{
+         stSourceURL = surl }
+       return bs)
+   `catchError`
+   (\e -> case e of
+             PandocResourceNotFound _ ->
+                -- see #5987 on reason for takeFileName
+                readDataFile ("templates" </> takeFileName tp)
+             PandocIOError _ ioe | isDoesNotExistError ioe ->
+                -- see #5987 on reason for takeFileName
+                readDataFile ("templates" </> takeFileName tp)
+             _ -> throwError e)) >>= toTextM tp
+
 -- | Get default template for the specified writer.
 getDefaultTemplate :: PandocMonad m
-                   => String           -- ^ Name of writer
-                   -> m String
-getDefaultTemplate writer = do
-  let format = takeWhile (`notElem` ("+-" :: String)) writer  -- strip off extensions
+                   => Text           -- ^ Name of writer
+                   -> m Text
+getDefaultTemplate format = do
   case format of
        "native"  -> return ""
+       "csljson" -> return ""
        "json"    -> return ""
-       "docx"    -> return ""
+       "xml"     -> return ""
        "fb2"     -> return ""
        "pptx"    -> return ""
+       "ipynb"   -> return ""
+       "asciidoctor" -> getDefaultTemplate "asciidoc"
+       "asciidoc_legacy" -> getDefaultTemplate "asciidoc"
+       "docx"    -> getDefaultTemplate "openxml"
        "odt"     -> getDefaultTemplate "opendocument"
        "html"    -> getDefaultTemplate "html5"
        "docbook" -> getDefaultTemplate "docbook5"
        "epub"    -> getDefaultTemplate "epub3"
-       "beamer"  -> getDefaultTemplate "latex"
+       "jats"    -> getDefaultTemplate "jats_archiving"
        "markdown_strict"   -> getDefaultTemplate "markdown"
        "multimarkdown"     -> getDefaultTemplate "markdown"
        "markdown_github"   -> getDefaultTemplate "markdown"
        "markdown_mmd"      -> getDefaultTemplate "markdown"
        "markdown_phpextra" -> getDefaultTemplate "markdown"
        "gfm"               -> getDefaultTemplate "commonmark"
-       _        -> let fname = "templates" </> "default" <.> format
-                   in  UTF8.toString <$> readDataFile fname
+       "commonmark_x"      -> getDefaultTemplate "commonmark"
+       "bbcode_phpbb"      -> getDefaultTemplate "bbcode"
+       "bbcode_fluxbb"     -> getDefaultTemplate "bbcode"
+       "bbcode_steam"      -> getDefaultTemplate "bbcode"
+       "bbcode_hubzilla"   -> getDefaultTemplate "bbcode"
+       "bbcode_xenforo"    -> getDefaultTemplate "bbcode"
+       _        -> do
+         let fname = "templates" </> "default" <.> T.unpack format
+         readDataFile fname >>= toTextM fname
 
--- | Like 'applyTemplate', but runs in PandocMonad and
--- raises an error if compilation fails.
-renderTemplate' :: (PandocMonad m, ToJSON a, TemplateTarget b)
-                => String -> a -> m b
-renderTemplate' template context =
-  case applyTemplate (T.pack template) context of
-       Left e  -> throwError (PandocTemplateError e)
-       Right r -> return r
+-- | Get and compile default template for the specified writer.
+-- Raise an error on compilation failure.
+compileDefaultTemplate :: PandocMonad m
+                       => Text
+                       -> m (Template Text)
+compileDefaultTemplate writer = do
+  res <- getDefaultTemplate writer >>=
+          runWithDefaultPartials .
+           compileTemplate ("templates/default." <> T.unpack writer)
+  case res of
+    Left e   -> throwError $ PandocTemplateError (T.pack e)
+    Right t  -> return t
diff --git a/src/Text/Pandoc/Transforms.hs b/src/Text/Pandoc/Transforms.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Transforms.hs
@@ -0,0 +1,169 @@
+{-# LANGUAGE OverloadedStrings   #-}
+{-# LANGUAGE StrictData          #-}
+{- |
+   Module      : Text.Pandoc.Transforms
+   Copyright   : © 2006-2024 John MacFarlane
+   License     : GPL-2.0-or-later
+   Maintainer  : John MacFarlane <jgm@berkeley@edu>
+
+Transformation of a Pandoc document post-parsing
+-}
+module Text.Pandoc.Transforms
+  ( Transform
+  , applyTransforms
+  , adjustLinksAndIds
+  , eastAsianLineBreakFilter
+  , filterIpynbOutput
+  , headerShift
+  ) where
+
+import Data.List (sortOn)
+import Data.Text (Text)
+import Network.URI (unEscapeString)
+import Text.DocLayout (charWidth)
+import Text.Pandoc.Definition
+  ( Pandoc (..), Attr, Block (..), Format (..), Inline (..) )
+import Text.Pandoc.Generic (bottomUp)
+import Text.Pandoc.Options (Extensions)
+import Text.Pandoc.Shared (stringify, textToIdentifier)
+import Text.Pandoc.Walk (walk)
+import qualified Data.Text as T
+import qualified Text.Pandoc.Builder as B
+
+-- | Transformation of a Pandoc document post-parsing
+type Transform = Pandoc -> Pandoc
+
+-- | Apply a list of transforms to a document, in order.
+applyTransforms :: Monad m => [Transform] -> Pandoc -> m Pandoc
+applyTransforms transforms d = return $ foldr ($) d transforms
+
+-- | Prefixes identifiers with a string derived from the filepath of
+-- @thisfile@; fixes links to targets in @allfiles@ accordingly.
+adjustLinksAndIds :: Extensions        -- ^ defines how IDs are generated
+                  -> Text              -- ^ thisfile
+                  -> [Text]            -- ^ allfiles
+                  -> Transform
+adjustLinksAndIds exts thisfile allfiles
+  | length allfiles > 1 = walk fixInline . walk fixBlock
+  | otherwise           = id
+ where
+  -- fix ids in blocks
+  fixBlock :: Block -> Block
+  fixBlock (CodeBlock attr t) = CodeBlock (fixAttrs attr) t
+  fixBlock (Header lev attr ils) = Header lev (fixAttrs attr) ils
+  fixBlock (Table attr cap cols th tbs tf) =
+     Table (fixAttrs attr) cap cols th tbs tf
+  fixBlock (Div attr bs) = Div (fixAttrs attr) bs
+  fixBlock x = x
+
+  -- fix ids and links in inlines
+  fixInline :: Inline -> Inline
+  fixInline (Code attr t) = Code (fixAttrs attr) t
+  fixInline (Link attr ils (url,tit)) =
+    Link (fixAttrs attr) ils (fixURL url,tit)
+  fixInline (Image attr ils (url,tit)) =
+    Image (fixAttrs attr) ils (fixURL url,tit)
+  fixInline (Span attr ils) = Span (fixAttrs attr) ils
+  fixInline x = x
+
+  -- add thisfile as prefix of identifier
+  fixAttrs :: Attr -> Attr
+  fixAttrs (i,cs,kvs)
+    | T.null i = (i,cs,kvs)
+    | otherwise =
+        (T.intercalate "__"
+          (filter (not . T.null) [toIdent thisfile, i]),
+        cs, kvs)
+
+  -- turns a filepath into an identifier
+  toIdent :: Text -> Text
+  toIdent = textToIdentifier exts . T.intercalate "__" .
+            T.split (\c -> c == '/' || c == '\\')
+
+  -- if URL begins with file from allfiles, convert to
+  -- an internal link with the appropriate identifier
+  fixURL :: Text -> Text
+  fixURL u =
+    let (a,b) = T.break (== '#') $ T.pack . unEscapeString . T.unpack $ u
+        filepart = if T.null a
+                      then toIdent thisfile
+                      else toIdent a
+        fragpart = T.dropWhile (== '#') b
+     in if T.null a || a `elem` allfiles
+           then "#" <> T.intercalate "__"
+                         (filter (not . T.null) [filepart, fragpart])
+           else u
+
+-- | Process ipynb output cells.  If mode is Nothing,
+-- remove all output.  If mode is Just format, select
+-- best output for the format.  If format is not ipynb,
+-- strip out ANSI escape sequences from CodeBlocks (see #5633).
+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) []
+            -- "best" for ipynb includes all formats:
+            Just fmt
+              | fmt == Format "ipynb"
+                          -> Div (ident, "output":os, kvs) bs
+              | otherwise -> Div (ident, "output":os, kvs) $
+                              walk removeANSI $
+                              take 1 $ sortOn rank bs
+                 where
+                  rank (RawBlock (Format "html") _)
+                    | fmt == Format "html" = 1 :: Int
+                    | fmt == Format "markdown" = 3
+                    | otherwise = 4
+                  rank (RawBlock (Format "latex") _)
+                    | fmt == Format "latex" = 1
+                    | fmt == Format "markdown" = 3
+                    | otherwise = 4
+                  rank (RawBlock f _)
+                    | fmt == f = 1
+                    | otherwise = 4
+                  rank (Para [Image{}]) = 2
+                  rank _ = 3
+                  removeANSI (CodeBlock attr code) =
+                    CodeBlock attr (removeANSIEscapes code)
+                  removeANSI x = x
+                  removeANSIEscapes t
+                    | Just cs <- T.stripPrefix "\x1b[" t =
+                        removeANSIEscapes $ T.drop 1 $ T.dropWhile (/='m') cs
+                    | Just (c, cs) <- T.uncons t = T.cons c $ removeANSIEscapes cs
+                    | otherwise = ""
+        go x = x
+
+-- | Remove soft breaks between East Asian characters.
+eastAsianLineBreakFilter :: Pandoc -> Pandoc
+eastAsianLineBreakFilter = bottomUp go
+  where go (x:SoftBreak:y:zs)
+          | Just (_, b) <- T.unsnoc $ stringify x
+          , Just (c, _) <- T.uncons $ stringify y
+          , charWidth b == 2
+          , charWidth c == 2
+          = x:y:zs
+          | otherwise
+          = x:SoftBreak:y:zs
+        go xs
+          = xs
+
+-- | Shift header levels up or down.
+headerShift :: Int -> Pandoc -> Pandoc
+headerShift n (Pandoc meta (Header m _ ils : bs))
+  | n < 0
+  , m + n == 0 = headerShift n $
+                 B.setTitle (B.fromList ils) $ Pandoc meta bs
+-- for this case, see #10459:
+headerShift n (Pandoc meta (Div attr@(_,"section":_,_) (Header m _ ils : as) : bs))
+  | n < 0
+  , m + n == 0 = headerShift n $
+                 B.setTitle (B.fromList ils) $ Pandoc meta (Div attr as : bs)
+headerShift n (Pandoc meta bs) = Pandoc meta (walk shift bs)
+
+ where
+   shift :: Block -> Block
+   shift (Header level attr inner)
+     | level + n > 0  = Header (level + n) attr inner
+     | otherwise      = Para inner
+   shift x            = x
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
@@ -1,112 +1,92 @@
-{-# LANGUAGE DeriveGeneric              #-}
-{-# LANGUAGE GeneralizedNewtypeDeriving #-}
-{-
-Copyright (C) 2017 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 CPP                        #-}
+{-# LANGUAGE OverloadedStrings          #-}
 {- |
    Module      : Text.Pandoc.Translations
-   Copyright   : Copyright (C) 2017 John MacFarlane
+   Copyright   : Copyright (C) 2017-2024 John MacFarlane
    License     : GNU GPL, version 2 or above
 
    Maintainer  : John MacFarlane <jgm@berkeley.edu>
    Stability   : alpha
    Portability : portable
 
-Data types for localization.
-
-Translations are stored in @data/translations/langname.trans@,
-where langname can be the full BCP47 language specifier, or
-just the language part.  File format is:
-
-> # A comment, ignored
-> Figure: Figura
-> Index: Indeksi
-
+Functions for getting localized translations of terms.
 -}
 module Text.Pandoc.Translations (
-                           Term(..)
-                         , Translations
-                         , lookupTerm
+                           module Text.Pandoc.Translations.Types
                          , readTranslations
+                         , getTranslations
+                         , setTranslations
+                         , translateTerm
                          )
 where
-import Data.Aeson.Types (typeMismatch)
-import qualified Data.HashMap.Strict as HM
-import qualified Data.Map as M
-import Data.Text as T
-import Data.Yaml as Yaml
-import GHC.Generics (Generic)
-import Text.Pandoc.Shared (safeRead)
+import Text.Pandoc.Translations.Types
+import Text.Pandoc.Class (PandocMonad(..), toTextM, report)
+import Text.Pandoc.Class.CommonState (CommonState(..))
+import Text.Pandoc.Data (readDataFile)
+import Data.Containers.ListUtils (nubOrd)
+import Text.Pandoc.Logging (LogMessage(..))
+import Control.Monad.Except (catchError)
+import qualified Data.Text as T
+import qualified Data.Yaml as Yaml
 import qualified Text.Pandoc.UTF8 as UTF8
-
-data Term =
-    Preface
-  | References
-  | Abstract
-  | Bibliography
-  | Chapter
-  | Appendix
-  | Contents
-  | ListOfFigures
-  | ListOfTables
-  | Index
-  | Figure
-  | Table
-  | Part
-  | Page
-  | See
-  | SeeAlso
-  | Encl
-  | Cc
-  | To
-  | Proof
-  | Glossary
-  | Listing
-  deriving (Show, Eq, Ord, Generic, Enum, Read)
-
-newtype Translations = Translations (M.Map Term String)
-        deriving (Show, Generic, Monoid)
+import Data.Yaml (prettyPrintParseException)
+import Text.Collate.Lang (Lang(..), renderLang)
 
-instance FromJSON Term where
-  parseJSON (String t) = case safeRead (T.unpack t) of
-                               Just t' -> pure t'
-                               Nothing -> fail $ "Invalid Term name " ++
-                                                 show t
-  parseJSON invalid = typeMismatch "Term" invalid
+-- | Parse YAML translations.
+readTranslations :: T.Text -> Either T.Text Translations
+readTranslations s =
+  case Yaml.decodeAllEither' $ UTF8.fromText s of
+       Left err' -> Left $ T.pack $ prettyPrintParseException err'
+       Right (t:_)     -> Right t
+       Right []        -> Left "empty YAML document"
 
-instance FromJSON Translations where
-  parseJSON (Object hm) = do
-    xs <- mapM addItem (HM.toList hm)
-    return $ Translations (M.fromList xs)
-    where addItem (k,v) =
-            case safeRead (T.unpack k) of
-                 Nothing -> fail $ "Invalid Term name " ++ show k
-                 Just t  ->
-                   case v of
-                        (String s) -> return (t, T.unpack $ T.strip s)
-                        inv        -> typeMismatch "String" inv
-  parseJSON invalid = typeMismatch "Translations" invalid
+-- | Select the language to use with 'translateTerm'.
+-- Note that this does not read a translation file;
+-- that is only done the first time 'translateTerm' is
+-- used.
+setTranslations :: PandocMonad m => Lang -> m ()
+setTranslations lang =
+  modifyCommonState $ \st -> st{ stTranslations = Just (lang, Nothing) }
 
-lookupTerm :: Term -> Translations -> Maybe String
-lookupTerm t (Translations tm) = M.lookup t tm
+-- | Load term map.
+getTranslations :: PandocMonad m => m Translations
+getTranslations = do
+  mbtrans <- getsCommonState stTranslations
+  case mbtrans of
+       Nothing -> return mempty  -- no language defined
+       Just (_, Just t) -> return t
+       Just (lang, Nothing) -> do  -- read from file
+         let translationFiles = map (\x -> "translations/" <> T.unpack x <> ".yaml")
+               (nubOrd [renderLang lang,
+                      langLanguage lang <> maybe "" ("-" <>) (langScript lang),
+                      langLanguage lang])
+         let getTrans [] = return mempty
+             getTrans (fp:fps) = do
+               result <- catchError (Right <$> (readDataFile fp >>= toTextM fp))
+                             (\_ -> pure (Left ""))
+               case result >>= readTranslations of
+                  Left e
+                    | null fps -> do
+                      report $ CouldNotLoadTranslations (renderLang lang)
+                                  (T.pack fp <> ": " <> e)
+                      -- make sure we don't try again...
+                      modifyCommonState $ \st ->
+                        st{ stTranslations = Nothing }
+                      return mempty
+                    | otherwise -> getTrans fps
+                  Right t -> do
+                    modifyCommonState $ \st ->
+                        st{ stTranslations = Just (lang, Just t) }
+                    return t
+         getTrans translationFiles
 
-readTranslations :: String -> Either String Translations
-readTranslations s =
-  case Yaml.decodeEither' $ UTF8.fromString s of
-       Left err' -> Left $ prettyPrintParseException err'
-       Right t   -> Right t
+-- | Get a translation from the current term map.
+-- Issue a warning if the term is not defined.
+translateTerm :: PandocMonad m => Term -> m T.Text
+translateTerm term = do
+  translations <- getTranslations
+  case lookupTerm term translations of
+       Just s -> return s
+       Nothing -> do
+         report $ NoTranslation $ T.pack $ show term
+         return ""
diff --git a/src/Text/Pandoc/Translations/Types.hs b/src/Text/Pandoc/Translations/Types.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Translations/Types.hs
@@ -0,0 +1,88 @@
+{-# LANGUAGE CPP                        #-}
+{-# LANGUAGE DeriveGeneric              #-}
+{-# LANGUAGE GeneralizedNewtypeDeriving #-}
+{-# LANGUAGE OverloadedStrings          #-}
+{- |
+   Module      : Text.Pandoc.Translations.Types
+   Copyright   : Copyright (C) 2017-2024 John MacFarlane
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : John MacFarlane <jgm@berkeley.edu>
+   Stability   : alpha
+   Portability : portable
+
+Data types for localization.
+
+Translations are stored in @data/translations/langname.trans@,
+where langname can be the full BCP47 language specifier, or
+just the language part.  File format is:
+
+> # A comment, ignored
+> Figure: Figura
+> Index: Indeksi
+
+-}
+module Text.Pandoc.Translations.Types (
+                           Term(..)
+                         , Translations
+                         , lookupTerm
+                         )
+where
+import Data.Aeson.Types (Value(..), FromJSON(..))
+import qualified Data.Aeson.Types as Aeson
+import qualified Data.Map as M
+import qualified Data.Text as T
+import GHC.Generics (Generic)
+import Text.Pandoc.Shared (safeRead)
+
+data Term =
+    Abstract
+  | Appendix
+  | Bibliography
+  | Cc
+  | Chapter
+  | Contents
+  | Encl
+  | Figure
+  | Glossary
+  | Index
+  | Listing
+  | ListOfFigures
+  | ListOfTables
+  | Page
+  | Part
+  | Preface
+  | Proof
+  | References
+  | See
+  | SeeAlso
+  | Table
+  | To
+  deriving (Show, Eq, Ord, Generic, Enum, Read)
+
+newtype Translations = Translations (M.Map Term T.Text)
+        deriving (Show, Generic, Semigroup, Monoid)
+
+instance FromJSON Term where
+  parseJSON (String t) = case safeRead t of
+                               Just t' -> pure t'
+                               Nothing -> Prelude.fail $ "Invalid Term name " ++
+                                                 show t
+  parseJSON invalid = Aeson.typeMismatch "Term" invalid
+
+instance FromJSON Translations where
+  parseJSON o@(Object{}) = do
+    xs <- parseJSON o >>= mapM addItem . M.toList
+    return $ Translations (M.fromList xs)
+    where addItem (k,v) =
+            case safeRead k of
+                 Nothing -> Prelude.fail $ "Invalid Term name " ++ show k
+                 Just t  ->
+                   case v of
+                        (String s) -> return (t, T.strip s)
+                        inv        -> Aeson.typeMismatch "String" inv
+  parseJSON invalid = Aeson.typeMismatch "Translations" invalid
+
+-- | Lookup a term in a 'Translations'.
+lookupTerm :: Term -> Translations -> Maybe T.Text
+lookupTerm t (Translations tm) = M.lookup t tm
diff --git a/src/Text/Pandoc/URI.hs b/src/Text/Pandoc/URI.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/URI.hs
@@ -0,0 +1,159 @@
+{-# LANGUAGE ViewPatterns #-}
+{-# LANGUAGE OverloadedStrings #-}
+{-# LANGUAGE CPP #-}
+{- |
+   Module      : Text.Pandoc.URI
+   Copyright   : Copyright (C) 2006-2024 John MacFarlane
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : John MacFarlane <jgm@berkeley.edu>
+   Stability   : alpha
+   Portability : portable
+-}
+module Text.Pandoc.URI ( urlEncode
+                       , escapeURI
+                       , isURI
+                       , schemes
+                       , uriPathToPath
+                       , pBase64DataURI
+                       ) where
+import qualified Network.HTTP.Types as HTTP
+import Data.ByteString.Base64 (decodeLenient)
+import Text.Pandoc.MIME (MimeType)
+import qualified Data.ByteString as B
+import qualified Text.Pandoc.UTF8 as UTF8
+import qualified Data.Text as T
+import qualified Data.Set as Set
+import Data.Char (isSpace, isAscii, isHexDigit, chr)
+import Safe (readMay)
+import Network.URI (URI (uriScheme), parseURI, escapeURIString)
+import qualified Data.Attoparsec.Text as A
+import Data.Text.Encoding (encodeUtf8)
+import Control.Applicative (many, (<|>))
+
+urlEncode :: T.Text -> T.Text
+urlEncode = UTF8.toText . HTTP.urlEncode True . UTF8.fromText
+
+-- | Escape whitespace and some punctuation characters in URI.
+escapeURI :: T.Text -> T.Text
+escapeURI = T.pack . escapeURIString (not . needsEscaping) . T.unpack
+  where needsEscaping c = isSpace c || T.any (== c) "<>|\"{}[]^`"
+
+--
+-- IANA URIs
+--
+
+-- | Schemes from http://www.iana.org/assignments/uri-schemes.html plus
+-- the unofficial schemes doi, javascript, isbn, pmid.
+schemes :: Set.Set T.Text
+schemes = Set.fromList
+  -- Official IANA schemes
+  [ "aaa", "aaas", "about", "acap", "acct", "acr", "adiumxtra", "afp", "afs"
+  , "aim", "appdata", "apt", "attachment", "aw", "barion", "beshare", "bitcoin"
+  , "blob", "bolo", "browserext", "callto", "cap", "chrome", "chrome-extension"
+  , "cid", "coap", "coaps", "com-eventbrite-attendee", "content", "crid", "cvs"
+  , "data", "dav", "dict", "dis", "dlna-playcontainer", "dlna-playsingle"
+  , "dns", "dntp", "dtn", "dvb", "ed2k", "example", "facetime", "fax", "feed"
+  , "feedready", "file", "filesystem", "finger", "fish", "ftp", "geo", "gg"
+  , "git", "gizmoproject", "go", "gopher", "graph", "gtalk", "h323", "ham"
+  , "hcp", "http", "https", "hxxp", "hxxps", "hydrazone", "iax", "icap", "icon"
+  , "im", "imap", "info", "iotdisco", "ipn", "ipp", "ipps", "irc", "irc6"
+  , "ircs", "iris", "iris.beep", "iris.lwz", "iris.xpc", "iris.xpcs"
+  , "isostore", "itms", "jabber", "jar", "jms", "keyparc", "lastfm", "ldap"
+  , "ldaps", "lvlt", "magnet", "mailserver", "mailto", "maps", "market"
+  , "message", "mid", "mms", "modem", "mongodb", "moz", "ms-access"
+  , "ms-browser-extension", "ms-drive-to", "ms-enrollment", "ms-excel"
+  , "ms-gamebarservices", "ms-getoffice", "ms-help", "ms-infopath"
+  , "ms-media-stream-id", "ms-officeapp", "ms-project", "ms-powerpoint"
+  , "ms-publisher", "ms-search-repair", "ms-secondary-screen-controller"
+  , "ms-secondary-screen-setup", "ms-settings", "ms-settings-airplanemode"
+  , "ms-settings-bluetooth", "ms-settings-camera", "ms-settings-cellular"
+  , "ms-settings-cloudstorage", "ms-settings-connectabledevices"
+  , "ms-settings-displays-topology", "ms-settings-emailandaccounts"
+  , "ms-settings-language", "ms-settings-location", "ms-settings-lock"
+  , "ms-settings-nfctransactions", "ms-settings-notifications"
+  , "ms-settings-power", "ms-settings-privacy", "ms-settings-proximity"
+  , "ms-settings-screenrotation", "ms-settings-wifi", "ms-settings-workplace"
+  , "ms-spd", "ms-sttoverlay", "ms-transit-to", "ms-virtualtouchpad"
+  , "ms-visio", "ms-walk-to", "ms-whiteboard", "ms-whiteboard-cmd", "ms-word"
+  , "msnim", "msrp", "msrps", "mtqp", "mumble", "mupdate", "mvn", "news", "nfs"
+  , "ni", "nih", "nntp", "notes", "ocf", "oid", "onenote", "onenote-cmd"
+  , "opaquelocktoken", "pack", "palm", "paparazzi", "pkcs11", "platform", "pop"
+  , "pres", "prospero", "proxy", "pwid", "psyc", "qb", "query", "redis"
+  , "rediss", "reload", "res", "resource", "rmi", "rsync", "rtmfp", "rtmp"
+  , "rtsp", "rtsps", "rtspu", "secondlife", "service", "session", "sftp", "sgn"
+  , "shttp", "sieve", "sip", "sips", "skype", "smb", "sms", "smtp", "snews"
+  , "snmp", "soap.beep", "soap.beeps", "soldat", "spotify", "ssh", "steam"
+  , "stun", "stuns", "submit", "svn", "tag", "teamspeak", "tel", "teliaeid"
+  , "telnet", "tftp", "things", "thismessage", "tip", "tn3270", "tool", "turn"
+  , "turns", "tv", "udp", "unreal", "urn", "ut2004", "v-event", "vemmi"
+  , "ventrilo", "videotex", "vnc", "view-source", "wais", "webcal", "wpid"
+  , "ws", "wss", "wtai", "wyciwyg", "xcon", "xcon-userid", "xfire"
+  , "xmlrpc.beep", "xmlrpc.beeps", "xmpp", "xri", "ymsgr", "z39.50", "z39.50r"
+  , "z39.50s"
+  -- Unofficial schemes
+  , "doi", "gemini", "isbn", "javascript", "pmid"
+  ]
+
+-- | Check if the string is a valid URL with a IANA or frequently used but
+-- unofficial scheme (see @schemes@).
+isURI :: T.Text -> Bool
+isURI t =
+  -- If it's a base 64 data: URI, avoid the expensive call to parseURI:
+  case A.parseOnly (pBase64DataURI *> A.endOfInput) t of
+    Right () -> True
+    Left _ ->
+      -- we URI-escape non-ASCII characters because otherwise parseURI will choke:
+      maybe False hasKnownScheme . parseURI . escapeURIString isAscii . T.unpack $ t
+  where
+    hasKnownScheme =
+      (`Set.member` schemes) . T.toLower . T.filter (/= ':') . T.pack . uriScheme
+
+-- | Converts the path part of a file: URI to a regular path.
+-- On windows, @/c:/foo@ should be @c:/foo@.
+-- On linux, @/foo@ should be @/foo@.
+uriPathToPath :: T.Text -> FilePath
+uriPathToPath (T.unpack -> path) =
+#ifdef _WINDOWS
+  case path of
+    '/':ps -> ps
+    ps     -> ps
+#else
+  path
+#endif
+
+pBase64DataURI :: A.Parser (B.ByteString, MimeType)
+pBase64DataURI = base64uri
+ where
+  base64uri = do
+    A.string "data:"
+    mime <- do
+      n1 <- restrictedName
+      A.char '/'
+      n2 <- restrictedName
+      mps <- many mediaParam
+      pure $ n1 <> "/" <> n2 <> mconcat mps
+    A.string ";base64,"
+    b64 <- mconcat <$> many
+              (A.takeWhile1 (A.inClass "A-Za-z0-9/+ \t\r\n") <|> percentOctet)
+    A.skipWhile (== '=')
+    -- this decode should be lazy:
+    pure (decodeLenient (encodeUtf8 b64), mime)
+  percentOctet = do
+    A.char '%'
+    x <- A.satisfy isHexDigit
+    y <- A.satisfy isHexDigit
+    case readMay ['0','x',x,y] of
+      Nothing -> fail $ "Could not read percent encoded byte " <> [x,y]
+      Just d -> pure $ T.singleton $ chr d
+  restrictedName = do
+    c <- A.satisfy (A.inClass "A-Za-z0-9")
+    rest <- A.takeWhile (A.inClass "A-Za-z0-9!#$&^_.+-")
+    pure $ T.singleton c <> rest
+  mediaParam = do
+    A.char ';'
+    A.skipWhile isSpace
+    k <- restrictedName
+    A.char '='
+    v <- A.takeWhile (/=';')
+    pure $ ";" <> k <> "=" <> v
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,32 +1,14 @@
 {-# LANGUAGE OverloadedStrings #-}
-{-
-Copyright (C) 2010-2017 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-2017 John MacFarlane
+   Copyright   : Copyright (C) 2010-2024 John MacFarlane
    License     : GNU GPL, version 2 or above
 
    Maintainer  : John MacFarlane <jgm@berkeley.edu>
    Stability   : alpha
    Portability : portable
 
-UTF-8 aware string IO functions that will work with GHC 6.10, 6.12, or 7.
+UTF-8 aware string IO functions.
 -}
 module Text.Pandoc.UTF8 ( readFile
                         , getContents
@@ -57,67 +39,65 @@
 
 import qualified Data.ByteString.Char8 as B
 import qualified Data.ByteString.Lazy.Char8 as BL
+import Data.Text (Text)
 import qualified Data.Text as T
+import qualified Data.Text.IO as TIO
 import qualified Data.Text.Encoding as T
 import qualified Data.Text.Lazy as TL
 import qualified Data.Text.Lazy.Encoding as TL
 import Prelude hiding (getContents, putStr, putStrLn, readFile, writeFile)
 import System.IO hiding (getContents, hGetContents, hPutStr, hPutStrLn, putStr,
                   putStrLn, readFile, writeFile)
-import qualified System.IO as IO
 
-readFile :: FilePath -> IO String
+readFile :: FilePath -> IO Text
 readFile f = do
   h <- openFile (encodePath f) ReadMode
   hGetContents h
 
-getContents :: IO String
+getContents :: IO Text
 getContents = hGetContents stdin
 
-writeFileWith :: Newline -> FilePath -> String -> IO ()
+writeFileWith :: Newline -> FilePath -> Text -> IO ()
 writeFileWith eol f s =
   withFile (encodePath f) WriteMode $ \h -> hPutStrWith eol h s
 
-writeFile :: FilePath -> String -> IO ()
+writeFile :: FilePath -> Text -> IO ()
 writeFile = writeFileWith nativeNewline
 
-putStrWith :: Newline -> String -> IO ()
+putStrWith :: Newline -> Text -> IO ()
 putStrWith eol s = hPutStrWith eol stdout s
 
-putStr :: String -> IO ()
+putStr :: Text -> IO ()
 putStr = putStrWith nativeNewline
 
-putStrLnWith :: Newline -> String -> IO ()
+putStrLnWith :: Newline -> Text -> IO ()
 putStrLnWith eol s = hPutStrLnWith eol stdout s
 
-putStrLn :: String -> IO ()
+putStrLn :: Text -> IO ()
 putStrLn = putStrLnWith nativeNewline
 
-hPutStrWith :: Newline -> Handle -> String -> IO ()
+hPutStrWith :: Newline -> Handle -> Text -> IO ()
 hPutStrWith eol h s =
   hSetNewlineMode h (NewlineMode eol eol) >>
-  hSetEncoding h utf8 >> IO.hPutStr h s
+  hSetEncoding h utf8 >> TIO.hPutStr h s
 
-hPutStr :: Handle -> String -> IO ()
+hPutStr :: Handle -> Text -> IO ()
 hPutStr = hPutStrWith nativeNewline
 
-hPutStrLnWith :: Newline -> Handle -> String -> IO ()
+hPutStrLnWith :: Newline -> Handle -> Text -> IO ()
 hPutStrLnWith eol h s =
   hSetNewlineMode h (NewlineMode eol eol) >>
-  hSetEncoding h utf8 >> IO.hPutStrLn h s
+  hSetEncoding h utf8 >> TIO.hPutStrLn h s
 
-hPutStrLn :: Handle -> String -> IO ()
+hPutStrLn :: Handle -> Text -> IO ()
 hPutStrLn = hPutStrLnWith nativeNewline
 
-hGetContents :: Handle -> IO String
-hGetContents = fmap toString . B.hGetContents
--- hGetContents h = hSetEncoding h utf8_bom
---                   >> hSetNewlineMode h universalNewlineMode
---                   >> IO.hGetContents h
+hGetContents :: Handle -> IO Text
+hGetContents = fmap toText . B.hGetContents
 
 -- | Convert UTF8-encoded ByteString to Text, also
--- removing '\r' characters.
-toText :: B.ByteString -> T.Text
+-- removing '\\r' characters.
+toText :: B.ByteString -> Text
 toText = T.decodeUtf8 . filterCRs . dropBOM
   where dropBOM bs =
          if "\xEF\xBB\xBF" `B.isPrefixOf` bs
@@ -126,12 +106,12 @@
         filterCRs = B.filter (/='\r')
 
 -- | Convert UTF8-encoded ByteString to String, also
--- removing '\r' characters.
+-- removing '\\r' characters.
 toString :: B.ByteString -> String
 toString = T.unpack . toText
 
 -- | Convert UTF8-encoded ByteString to Text, also
--- removing '\r' characters.
+-- removing '\\r' characters.
 toTextLazy :: BL.ByteString -> TL.Text
 toTextLazy = TL.decodeUtf8 . filterCRs . dropBOM
   where dropBOM bs =
@@ -141,11 +121,11 @@
         filterCRs = BL.filter (/='\r')
 
 -- | Convert UTF8-encoded ByteString to String, also
--- removing '\r' characters.
+-- removing '\\r' characters.
 toStringLazy :: BL.ByteString -> String
 toStringLazy = TL.unpack . toTextLazy
 
-fromText :: T.Text -> B.ByteString
+fromText :: Text -> B.ByteString
 fromText = T.encodeUtf8
 
 fromTextLazy :: TL.Text -> BL.ByteString
@@ -160,5 +140,6 @@
 encodePath :: FilePath -> FilePath
 encodePath = id
 
+{-# DEPRECATED decodeArg "decodeArg is now a no-op" #-}
 decodeArg :: String -> String
 decodeArg = id
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,24 +1,6 @@
-{-
-Copyright (C) 2010-2017 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-2017 John MacFarlane
+   Copyright   : Copyright (C) 2010-2024 John MacFarlane
    License     : GNU GPL, version 2 or above
 
    Maintainer  : John MacFarlane <jgm@berkeley.edu>
@@ -29,12 +11,13 @@
 in RFC4122. See http://tools.ietf.org/html/rfc4122
 -}
 
-module Text.Pandoc.UUID ( UUID(..), getRandomUUID, getUUID ) where
+module Text.Pandoc.UUID ( UUID(..), getRandomUUID ) where
 
 import Data.Bits (clearBit, setBit)
 import Data.Word
-import System.Random (RandomGen, getStdGen, randoms)
+import System.Random (RandomGen, randoms)
 import Text.Printf (printf)
+import Text.Pandoc.Class.PandocMonad
 
 data UUID = UUID Word8 Word8 Word8 Word8 Word8 Word8 Word8 Word8
                  Word8 Word8 Word8 Word8 Word8 Word8 Word8 Word8
@@ -65,13 +48,14 @@
 
 getUUID :: RandomGen g => g -> UUID
 getUUID gen =
-  let [a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p] = take 16 $ randoms gen :: [Word8]
-  -- set variant
-      i' = i `setBit` 7 `clearBit` 6
-  -- set version (0100 for random)
-      g' = g `clearBit` 7 `setBit` 6 `clearBit` 5 `clearBit` 4
-  in
-    UUID a b c d e f g' h i' j k l m n o p
+  case take 16 (randoms gen :: [Word8]) of
+       [a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p] ->
+         -- set variant
+         let i' = i `setBit` 7 `clearBit` 6
+         -- set version (0100 for random)
+             g' = g `clearBit` 7 `setBit` 6 `clearBit` 5 `clearBit` 4
+         in  UUID a b c d e f g' h i' j k l m n o p
+       _ -> error "not enough random numbers for UUID" -- should not happen
 
-getRandomUUID :: IO UUID
-getRandomUUID = getUUID <$> getStdGen
+getRandomUUID :: PandocMonad m => m UUID
+getRandomUUID = getUUID <$> newStdGen
diff --git a/src/Text/Pandoc/Version.hs b/src/Text/Pandoc/Version.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Version.hs
@@ -0,0 +1,28 @@
+{-# LANGUAGE CPP                   #-}
+{- |
+   Module      : Text.Pandoc.Version
+   Copyright   : Copyright (C) 2022-2024 John MacFarlane
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : John MacFarlane <jgm@berkeley.edu>
+   Stability   : alpha
+   Portability : portable
+
+Version information.
+-}
+module Text.Pandoc.Version (
+                     pandocVersion,
+                     pandocVersionText
+                    ) where
+
+import Data.Version (Version, showVersion)
+import Paths_pandoc (version)
+import qualified Data.Text as T
+
+-- | Version number of pandoc library.
+pandocVersion :: Version
+pandocVersion = version
+
+-- | Text representation of the library's version number.
+pandocVersionText :: T.Text
+pandocVersionText = T.pack $ showVersion version
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,27 +1,11 @@
-{-
-Copyright (C) 2006-2017 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 OverloadedStrings   #-}
 {-# LANGUAGE ScopedTypeVariables #-}
-
+{-# LANGUAGE TupleSections       #-}
 {- |
    Module      : Text.Pandoc
-   Copyright   : Copyright (C) 2006-2017 John MacFarlane
+   Copyright   : Copyright (C) 2006-2024 John MacFarlane
    License     : GNU GPL, version 2 or above
 
    Maintainer  : John MacFarlane <jgm@berkeley.edu>
@@ -35,19 +19,27 @@
     -- * Writers: converting /from/ Pandoc format
       Writer(..)
     , writers
+    , writeANSI
     , writeAsciiDoc
+    , writeAsciiDocLegacy
+    , writeAsciiDoctor
     , writeBeamer
+    , writeBibTeX
+    , writeBibLaTeX
+    , writeChunkedHTML
     , writeCommonMark
     , writeConTeXt
-    , writeCustom
+    , writeCslJson
     , writeDZSlides
-    , writeDocbook4
-    , writeDocbook5
+    , writeDjot
+    , writeDocBook4
+    , writeDocBook5
     , writeDocx
     , writeDokuWiki
     , writeEPUB2
     , writeEPUB3
     , writeFB2
+    , writeIpynb
     , writeHaddock
     , writeHtml4
     , writeHtml4String
@@ -55,10 +47,15 @@
     , writeHtml5String
     , writeICML
     , writeJATS
+    , writeJatsArchiving
+    , writeJatsArticleAuthoring
+    , writeJatsPublishing
     , writeJSON
+    , writeJira
     , writeLaTeX
     , writeMan
     , writeMarkdown
+    , writeMarkua
     , writeMediaWiki
     , writeMs
     , writeMuse
@@ -78,31 +75,49 @@
     , writeTEI
     , writeTexinfo
     , writeTextile
+    , writeTypst
+    , writeXML
+    , writeXWiki
     , writeZimWiki
+    , writeVimdoc
+    , writeBBCode
+    , writeBBCodeSteam
+    , writeBBCodeFluxBB
+    , writeBBCodePhpBB
+    , writeBBCodeHubzilla
+    , writeBBCodeXenforo
     , getWriter
     ) where
 
+import Control.Monad.Except (throwError)
 import Data.Aeson
 import qualified Data.ByteString.Lazy as BL
-import Data.List (intercalate)
 import Data.Text (Text)
 import Text.Pandoc.Class
 import Text.Pandoc.Definition
+import qualified Text.Pandoc.Format as Format
 import Text.Pandoc.Options
 import qualified Text.Pandoc.UTF8 as UTF8
+import Text.Pandoc.Error
+import Text.Pandoc.Writers.ANSI
 import Text.Pandoc.Writers.AsciiDoc
+import Text.Pandoc.Writers.BibTeX
+import Text.Pandoc.Writers.ChunkedHTML
 import Text.Pandoc.Writers.CommonMark
 import Text.Pandoc.Writers.ConTeXt
-import Text.Pandoc.Writers.Custom
-import Text.Pandoc.Writers.Docbook
+import Text.Pandoc.Writers.CslJson
+import Text.Pandoc.Writers.Djot
+import Text.Pandoc.Writers.DocBook
 import Text.Pandoc.Writers.Docx
 import Text.Pandoc.Writers.DokuWiki
 import Text.Pandoc.Writers.EPUB
 import Text.Pandoc.Writers.FB2
+import Text.Pandoc.Writers.Ipynb
 import Text.Pandoc.Writers.Haddock
 import Text.Pandoc.Writers.HTML
 import Text.Pandoc.Writers.ICML
 import Text.Pandoc.Writers.JATS
+import Text.Pandoc.Writers.Jira
 import Text.Pandoc.Writers.LaTeX
 import Text.Pandoc.Writers.Man
 import Text.Pandoc.Writers.Markdown
@@ -120,17 +135,28 @@
 import Text.Pandoc.Writers.TEI
 import Text.Pandoc.Writers.Texinfo
 import Text.Pandoc.Writers.Textile
+import Text.Pandoc.Writers.Typst
+import Text.Pandoc.Writers.XML
+import Text.Pandoc.Writers.XWiki
 import Text.Pandoc.Writers.ZimWiki
-import Text.Parsec.Error
+import Text.Pandoc.Writers.Vimdoc
+import Text.Pandoc.Writers.BBCode (
+  writeBBCode,
+  writeBBCodeFluxBB,
+  writeBBCodeHubzilla,
+  writeBBCodePhpBB,
+  writeBBCodeSteam,
+  writeBBCodeXenforo,
+ )
 
 data Writer m = TextWriter (WriterOptions -> Pandoc -> m Text)
               | ByteStringWriter (WriterOptions -> Pandoc -> m BL.ByteString)
 
 -- | Association list of formats and writers.
-writers :: PandocMonad m => [ ( String, Writer m) ]
+writers :: PandocMonad m => [ (Text, Writer m) ]
 writers = [
    ("native"       , TextWriter writeNative)
-  ,("json"         , TextWriter $ \o d -> return $ writeJSON o d)
+  ,("json"         , TextWriter writeJSON)
   ,("docx"         , ByteStringWriter writeDocx)
   ,("odt"          , ByteStringWriter writeODT)
   ,("pptx"         , ByteStringWriter writePowerpoint)
@@ -138,6 +164,7 @@
   ,("epub2"        , ByteStringWriter writeEPUB2)
   ,("epub3"        , ByteStringWriter writeEPUB3)
   ,("fb2"          , TextWriter writeFB2)
+  ,("ipynb"        , TextWriter writeIpynb)
   ,("html"         , TextWriter writeHtml5String)
   ,("html4"        , TextWriter writeHtml4String)
   ,("html5"        , TextWriter writeHtml5String)
@@ -147,10 +174,14 @@
   ,("slideous"     , TextWriter writeSlideous)
   ,("dzslides"     , TextWriter writeDZSlides)
   ,("revealjs"     , TextWriter writeRevealJs)
-  ,("docbook"      , TextWriter writeDocbook5)
-  ,("docbook4"     , TextWriter writeDocbook4)
-  ,("docbook5"     , TextWriter writeDocbook5)
-  ,("jats"         , TextWriter writeJATS)
+  ,("docbook"      , TextWriter writeDocBook5)
+  ,("docbook4"     , TextWriter writeDocBook4)
+  ,("docbook5"     , TextWriter writeDocBook5)
+  ,("jats"         , TextWriter writeJatsArchiving)
+  ,("jats_articleauthoring", TextWriter writeJatsArticleAuthoring)
+  ,("jats_publishing" , TextWriter writeJatsPublishing)
+  ,("jats_archiving" , TextWriter writeJatsArchiving)
+  ,("jira"         , TextWriter writeJira)
   ,("opml"         , TextWriter writeOPML)
   ,("opendocument" , TextWriter writeOpenDocument)
   ,("latex"        , TextWriter writeLaTeX)
@@ -168,28 +199,46 @@
   ,("rst"          , TextWriter writeRST)
   ,("mediawiki"    , TextWriter writeMediaWiki)
   ,("dokuwiki"     , TextWriter writeDokuWiki)
+  ,("xwiki"        , TextWriter writeXWiki)
   ,("zimwiki"      , TextWriter writeZimWiki)
   ,("textile"      , TextWriter writeTextile)
+  ,("typst"        , TextWriter writeTypst)
   ,("rtf"          , TextWriter writeRTF)
   ,("org"          , TextWriter writeOrg)
   ,("asciidoc"     , TextWriter writeAsciiDoc)
+  ,("asciidoctor"  , TextWriter writeAsciiDoc)
+  ,("asciidoc_legacy" , TextWriter writeAsciiDocLegacy)
   ,("haddock"      , TextWriter writeHaddock)
   ,("commonmark"   , TextWriter writeCommonMark)
+  ,("commonmark_x" , TextWriter writeCommonMark)
   ,("gfm"          , TextWriter writeCommonMark)
   ,("tei"          , TextWriter writeTEI)
   ,("muse"         , TextWriter writeMuse)
+  ,("csljson"      , TextWriter writeCslJson)
+  ,("bibtex"       , TextWriter writeBibTeX)
+  ,("biblatex"     , TextWriter writeBibLaTeX)
+  ,("markua"       , TextWriter writeMarkua)
+  ,("chunkedhtml"  , ByteStringWriter writeChunkedHTML)
+  ,("djot"         , TextWriter writeDjot)
+  ,("ansi"         , TextWriter writeANSI)
+  ,("xml"          , TextWriter writeXML)
+  ,("vimdoc"       , TextWriter writeVimdoc)
+  ,("bbcode"       , TextWriter writeBBCode)
+  ,("bbcode_steam" , TextWriter writeBBCodeSteam)
+  ,("bbcode_phpbb" , TextWriter writeBBCodePhpBB)
+  ,("bbcode_fluxbb", TextWriter writeBBCodeFluxBB)
+  ,("bbcode_hubzilla" , TextWriter writeBBCodeHubzilla)
+  ,("bbcode_xenforo" , TextWriter writeBBCodeXenforo)
   ]
 
 -- | Retrieve writer, extensions based on formatSpec (format+extensions).
-getWriter :: PandocMonad m => String -> Either String (Writer m, Extensions)
-getWriter s
-  = case parseFormatSpec s of
-         Left e  -> Left $ intercalate "\n" [m | Message m <- errorMessages e]
-         Right (writerName, setExts) ->
-             case lookup writerName writers of
-                     Nothing -> Left $ "Unknown writer: " ++ writerName
-                     Just r -> Right (r, setExts $
-                                  getDefaultExtensions writerName)
+getWriter :: PandocMonad m => Format.FlavoredFormat -> m (Writer m, Extensions)
+getWriter flvrd = do
+  let writerName = Format.formatName flvrd
+  case lookup writerName writers of
+    Nothing  -> throwError $ PandocUnknownWriterError writerName
+    Just  w  -> (w,) <$>
+      Format.applyExtensionsDiff (Format.getExtensionsConfig writerName) flvrd
 
-writeJSON :: WriterOptions -> Pandoc -> Text
-writeJSON _ = UTF8.toText . BL.toStrict . encode
+writeJSON :: PandocMonad m => WriterOptions -> Pandoc -> m Text
+writeJSON _ = return . UTF8.toText . BL.toStrict . encode
diff --git a/src/Text/Pandoc/Writers/ANSI.hs b/src/Text/Pandoc/Writers/ANSI.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Writers/ANSI.hs
@@ -0,0 +1,394 @@
+{-# LANGUAGE OverloadedStrings #-}
+{- |
+   Module      : Text.Pandoc.Writers.ANSI
+   Copyright   : © 2024 Evan Silberman
+                 © 2025 Pandoc contributors
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : John MacFarlane <jgm@berkeley.edu>
+   Stability   : alpha
+   Portability : portable
+
+Conversion of 'Pandoc' documents to Ansi terminal output.
+-}
+module Text.Pandoc.Writers.ANSI ( writeANSI ) where
+import Control.Monad.State.Strict ( StateT, gets, modify, evalStateT )
+import Control.Monad (foldM)
+import Data.List (intersperse)
+import qualified Data.Map as M
+import Data.Maybe (fromMaybe)
+import Data.Text (Text)
+import Text.DocLayout ((<+>), ($$), ($+$))
+import Text.DocTemplates (Context(..))
+import Text.Pandoc.Class.PandocMonad (PandocMonad, report)
+import Text.Pandoc.Definition
+import Text.Pandoc.Highlighting (highlight, formatANSI)
+import Text.Pandoc.Logging
+import Text.Pandoc.Options
+import Text.Pandoc.Shared
+import Text.Pandoc.Templates (renderTemplate)
+import Text.Pandoc.Writers.Math(texMathToInlines)
+import Text.Pandoc.Writers.Shared
+import qualified Data.Text as T
+import Data.Text.Lazy (toStrict)
+import qualified Text.DocLayout as D
+import qualified Text.Pandoc.Highlighting as HL
+
+hr :: D.HasChars a => D.Doc a
+hr = rule 20
+
+rule :: D.HasChars a => Int -> D.Doc a
+rule n = D.literal $ D.replicateChar n '─'
+
+data WriterState = WriterState {
+    stNotes     :: [D.Doc Text]        -- Footnotes
+  , stColumns   :: Int         -- Width of the rendered text block
+  , stInner     :: Bool    -- Are we at the document's top-level or in a nested construct?
+  , stNextFigureNum :: Int
+  , stInFigure :: Bool
+  , stInTable :: Bool
+  }
+
+type TW = StateT WriterState
+
+withFewerColumns :: PandocMonad m => Int -> TW m a -> TW m a
+withFewerColumns n a = do
+  cols <- gets stColumns
+  inner <- gets stInner
+  modify $ \s -> s{stColumns = max (cols - n) 4, stInner = True}
+  result <- a
+  modify $ \s -> s{stColumns = cols, stInner = inner}
+  return result
+
+-- | Convert Pandoc to ANSI
+writeANSI :: PandocMonad m => WriterOptions -> Pandoc -> m Text
+writeANSI opts document =
+  evalStateT (pandocToANSI opts document)
+            WriterState { stNotes = [],
+                          stColumns = (writerColumns opts),
+                          stInner = False,
+                          stNextFigureNum = 1,
+                          stInFigure = False,
+                          stInTable = False
+                        }
+
+-- | Return ANSI-styled version of document
+pandocToANSI :: PandocMonad m
+                => WriterOptions -> Pandoc -> TW m Text
+pandocToANSI opts (Pandoc meta blocks) = do
+  metadata <- metaToContext opts
+                 (blockListToANSI opts)
+                 (inlineListToANSI opts) meta
+  let colwidth = if writerWrapText opts == WrapAuto
+                    then Just $ writerColumns opts
+                    else Nothing
+  let title = titleBlock colwidth metadata
+  let blocks' = makeSections (writerNumberSections opts) Nothing blocks
+  body <- blockListToANSI opts blocks'
+  notes <- gets $ reverse . stNotes
+  let notemark x = D.literal (tshow (x :: Int) <> ".") <+> D.space
+  let marks = map notemark [1..length notes]
+  let hangWidth = foldr (max . D.offset) 0 marks
+  let notepretty
+       | not (null notes) =
+          (case colwidth of
+            Nothing -> hr
+            Just w  -> D.cblock w hr)
+          $+$ hangMarks hangWidth marks notes
+       | otherwise = D.empty
+  let main = body $+$ notepretty
+  let context = defField "body" main
+              $ defField "titleblock" title metadata
+  return $
+    case writerTemplate opts of
+         Nothing  -> toStrict $ D.renderANSI colwidth main
+         Just tpl -> toStrict $ D.renderANSI colwidth
+                              $ renderTemplate tpl context
+
+titleBlock :: Maybe Int -> Context Text -> D.Doc Text
+titleBlock width meta =
+  if null most
+     then D.empty
+     else (maybe id D.cblock width) $ most $+$ hr
+  where
+    title = D.bold (fromMaybe D.empty $ getField "title" meta)
+    subtitle = fromMaybe D.empty $ getField "subtitle" meta
+    author =  D.vcat $ fromMaybe [] $ getField "author" meta
+    date = D.italic (fromMaybe D.empty $ getField "date" meta)
+    most = (title $$ subtitle) $+$ author $+$ date
+
+hangMarks :: Int -> [D.Doc Text] -> [D.Doc Text] -> D.Doc Text
+hangMarks width markers contents =
+  D.vsep (zipWith hangMark markers contents) where
+    hangMark m d = D.rblock width m <+> D.nest (width + 1) d
+
+stackMarks :: [D.Doc Text] -> [D.Doc Text] -> D.Doc Text
+stackMarks markers contents = D.vsep (zipWith stack markers contents)
+  where stack m d = m $$ D.nest 4 d
+
+-- | Convert Pandoc block element to ANSI
+blockToANSI :: PandocMonad m
+               => WriterOptions -- ^ Options
+               -> Block         -- ^ Block element
+               -> TW m (D.Doc Text)
+
+blockToANSI opts (Div _ bs) = blockListToANSI opts bs
+
+blockToANSI opts (Plain inlines) = inlineListToANSI opts inlines
+
+blockToANSI opts (Para inlines) = inlineListToANSI opts inlines
+
+blockToANSI opts (LineBlock lns) = do
+  let go [] = return D.blankline
+      go xs = inlineListToANSI opts xs
+  lns' <- mapM go lns
+  return $ D.vcat lns'
+
+blockToANSI _ b@(RawBlock _ _) = do
+    report $ BlockNotRendered b
+    return D.empty
+
+blockToANSI _ HorizontalRule = return $ D.blankline $$ hr $$ D.blankline
+
+blockToANSI opts (Header level (_, classes, kvs) inlines) = do
+  contents <- inlineListToANSI opts inlines
+  let secnum = fromMaybe mempty $ lookup "number" kvs
+  let doNumber = writerNumberSections opts && not (T.null secnum) && "unnumbered" `notElem` classes
+  let number | doNumber = D.hang (D.realLength secnum + 1) (header level (D.literal secnum) <> D.space)
+             | otherwise = id
+  return $ number (header level contents) $$ D.blankline where
+    header 1 = (fmap T.toUpper) . D.bold
+    header 2 = D.bold
+    header _ = D.italic
+
+-- The approach to code blocks and highlighting here is a best-effort with
+-- existing tools. The Skylighting formatANSI function produces fully-rendered
+-- results, and its line numbers are followed by a tab character, which can
+-- produce less-than-ideal results depending on your terminal's tab stops. (See
+-- tabs(1)). A more ambitious approach here could process SourceLines into a
+-- Doc Text.
+blockToANSI opts (CodeBlock attr str) = do
+  table <- gets stInTable
+  let highlightWithStyle s = do
+        let fmt o = formatANSI o s
+            result = highlight (writerSyntaxMap opts) fmt attr str
+        return $ case result of
+          Left _ -> defaultStyle str
+          Right f -> D.literal f
+  inner <- case (table, writerHighlightMethod opts) of
+    (_, NoHighlighting) -> return $ defaultStyle str
+    (True, _) -> return $ defaultStyle str
+    (False, Skylighting s) -> highlightWithStyle s
+    (False, DefaultHighlighting) -> highlightWithStyle HL.defaultStyle
+    (False, IdiomaticHighlighting) -> do
+      report $ CouldNotHighlight "no idiomatic highlighting in ANSI"
+      return $ defaultStyle str
+  return $ nest table inner
+  where defaultStyle = (D.fg D.red) . D.literal
+        nest False = D.nest 4
+        nest True = id
+
+blockToANSI opts (BlockQuote blocks) = do
+  contents <- withFewerColumns 2 $ blockListToANSI opts blocks
+  return ( D.prefixed "│ " contents $$ D.blankline)
+
+blockToANSI opts (Table _ (Caption _ caption) colSpecs (TableHead _ thead) tbody (TableFoot _ tfoot)) = do
+  let captionInlines = blocksToInlines caption
+  captionMarkup <-
+    if null captionInlines
+       then return mempty
+       else D.nest 2 <$> inlineListToANSI opts (blocksToInlines caption)
+  wasTable <- gets stInTable
+  modify $ \s -> s{stInTable = True}
+  let tw = writerColumns opts
+  let ncol = length colSpecs
+  let inWidths = map snd colSpecs
+  let spaceForColumns = tw - ncol + 1  -- reserve a 1-char gutter between tcols
+  let claimWidth ColWidthDefault = 0
+      claimWidth (ColWidth n) = floor (n * fromIntegral spaceForColumns)
+  let usedSpace = sum (map claimWidth inWidths)
+  let remaining = spaceForColumns - usedSpace
+  let defWidth = remaining `div` length (filter (== ColWidthDefault) inWidths)
+  let maxWidth ColWidthDefault = defWidth
+      maxWidth k = claimWidth k
+  let widths = map maxWidth inWidths
+  let decor = [D.hsep $ map rule widths]
+  head' <- (makeRows widths . map unRow) thead
+  body' <- (makeRows widths . map unRow) (tableBodiesToRows tbody)
+  foot' <- (makeRows widths . map unRow) tfoot
+  modify $ \s -> s{stInTable = wasTable}
+  return $ D.vcat (head' <> decor <> body' <> decor <> foot') $+$ captionMarkup
+  where
+    unRow (Row _ cs) = cs
+    makeRows ws rows = do
+      (docs, _) <- foldM (goRow ws) ([], M.empty) rows
+      return $ reverse docs
+    goRow _ (r, spans) [] =
+      -- Empty rows are not displayed but previous row spans still apply for them.
+      let spans' = M.map decrementPreviousRowSpans spans
+      in  return (r, spans')
+    goRow ws (r, spans) cs = do
+      (d, (nextPos, spans'), _) <- foldM goCell ([], (0, spans), ws) cs
+      let spans'' = decrementTrailingRowSpans nextPos spans' -- Handle previous row spans next to the end of the current row
+      return (D.hcat (intersperse (D.vfill " ") $ reverse d):r, spans'')
+    goCell (r, (colPos, spans), ws) cell@(Cell _ aln (RowSpan rspan) (ColSpan cspan) inner)
+      | Just (ColSpan previousColSpan, spans') <- takePreviousSpansAtColumn colPos spans = do
+          (r', nextPos, ws') <- makeCell r colPos ws AlignDefault previousColSpan []
+          goCell (r', (nextPos, spans'), ws') cell
+      | otherwise = do
+          (r', nextPos, ws') <- makeCell r colPos ws aln cspan inner
+          let spans' = insertCurrentSpansAtColumn colPos spans (RowSpan rspan) (ColSpan cspan)
+          return (r', (nextPos, spans'), ws')
+    decrementPreviousRowSpans spans@(RowSpan rspan, cspan) =
+      if rspan >= 1
+        then (RowSpan rspan - 1, cspan)
+        else spans
+    makeCell r colPos ws aln cspan inner = do
+      let (ws', render) = next ws aln cspan
+      innerDoc <- blockListToANSI opts inner
+      return ((render innerDoc):r, colPos + cspan, ws')
+    tcell AlignLeft    = D.lblock
+    tcell AlignRight   = D.rblock
+    tcell AlignCenter  = D.cblock
+    tcell AlignDefault = D.lblock
+    next ws aln cspan =
+      let (this, ws') = splitAt cspan ws
+          w = sum this + cspan - 1
+          cell = (tcell aln) w
+       in (ws', cell)
+
+blockToANSI opts (BulletList items) = do
+  contents <- withFewerColumns 2 $ mapM (blockListToANSI opts) items
+  return $ D.vsep (fmap hangMark contents) where
+    hangMark d = D.hang 2 (D.literal "• ") d
+
+blockToANSI opts (OrderedList attribs items) = do
+  let markers = fmap D.literal $ take (length items) $ orderedListMarkers attribs
+  let hangWidth = foldr (max . D.offset) 0 markers
+  contents <- withFewerColumns hangWidth $ mapM (blockListToANSI opts) items
+  return $ hangMarks hangWidth markers contents <> D.cr
+
+blockToANSI opts (DefinitionList items) = do
+  labels <- mapM (inlineListToANSI opts . fst) items
+  columns <- gets stColumns
+  let hangWidth = foldr (max . D.offset) 0 labels
+  if hangWidth > floor (toRational columns / 10 * 3)
+     then do
+       contents <- withFewerColumns 4 $ mapM ((mapM (blockListToANSI opts)) . snd) items
+       return $ stackMarks (D.bold <$> labels) (D.vsep <$> contents) <> D.cr
+     else do
+       contents <- withFewerColumns hangWidth $ mapM ((mapM (blockListToANSI opts)) . snd) items
+       return $ hangMarks hangWidth (D.bold <$> labels) (D.vsep <$> contents) <> D.cr
+
+blockToANSI opts (Figure _ (Caption _ caption)  body) = do
+  let captionInlines = blocksToInlines caption
+  figState <- gets stInFigure
+  captionMarkup <-
+    if null captionInlines
+       then return mempty
+       else D.nest 2 <$> inlineListToANSI opts (blocksToInlines caption)
+  modify $ \s -> s{stInFigure = True}
+  contents <- blockListToANSI opts body
+  modify $ \s -> s{stInFigure = figState}
+  return $ contents $+$ captionMarkup
+
+-- Auxiliary functions for lists:
+
+-- | Convert list of Pandoc block elements to ANSI
+blockListToANSI :: PandocMonad m
+                   => WriterOptions -- ^ Options
+                   -> [Block]       -- ^ List of block elements
+                   -> TW m (D.Doc Text)
+blockListToANSI opts blocks =
+  D.vsep <$> mapM (blockToANSI opts) blocks
+
+-- | Convert list of Pandoc inline elements to ANSI
+inlineListToANSI :: PandocMonad m
+                    => WriterOptions -> [Inline] -> TW m (D.Doc Text)
+inlineListToANSI opts lst =
+  D.hcat <$> mapM (inlineToANSI opts) lst
+
+-- | Convert Pandoc inline element to ANSI
+inlineToANSI :: PandocMonad m => WriterOptions -> Inline -> TW m (D.Doc Text)
+
+inlineToANSI opts (Span _ lst) =
+  inlineListToANSI opts lst
+
+inlineToANSI opts (Emph lst) = do
+  contents <- inlineListToANSI opts lst
+  return $ D.italic contents
+
+inlineToANSI opts (Underline lst) = do
+  contents <- inlineListToANSI opts lst
+  return $ D.underlined contents
+
+inlineToANSI opts (Strong lst) = do
+  contents <- inlineListToANSI opts lst
+  return $ D.bold contents
+
+inlineToANSI opts (Strikeout lst) = do
+  contents <- inlineListToANSI opts lst
+  return $ D.strikeout contents
+
+inlineToANSI opts (Superscript lst) = do
+  case traverse toSuperscriptInline lst of
+    Just xs -> inlineListToANSI opts xs
+    Nothing -> D.parens <$> inlineListToANSI opts lst
+
+inlineToANSI opts (Subscript lst) = do
+  case traverse toSubscriptInline lst of
+    Just xs -> inlineListToANSI opts xs
+    Nothing -> D.parens <$> inlineListToANSI opts lst
+
+inlineToANSI opts (SmallCaps lst) = inlineListToANSI opts lst
+
+inlineToANSI opts (Quoted SingleQuote lst) = do
+  contents <- inlineListToANSI opts lst
+  return $ "‘" <> contents <> "’"
+
+inlineToANSI opts (Quoted DoubleQuote lst) = do
+  contents <- inlineListToANSI opts lst
+  return $ "“" <> contents <> "”"
+
+inlineToANSI opts (Cite _  lst) = inlineListToANSI opts lst
+
+-- Making a judgment call here that for ANSI-formatted output
+-- intended for reading, we want to reflow inline Code on spaces
+inlineToANSI _ (Code _ str) =
+  return $ D.bg D.white $ D.fg D.red $ " " <> D.hcat flow <> " "
+    where flow = intersperse D.space (D.literal <$> T.words str)
+
+inlineToANSI _ (Str str) = return $ D.literal str
+
+inlineToANSI opts (Math t str) = texMathToInlines t str >>= inlineListToANSI opts
+
+inlineToANSI _ il@RawInline{} = do
+  report $ InlineNotRendered il
+  return ""
+
+inlineToANSI _ LineBreak = return D.cr
+
+inlineToANSI _ SoftBreak = return D.space
+
+inlineToANSI _ Space = return D.space
+
+inlineToANSI opts (Link (_, _, _) txt (src, _)) = do
+  label <- inlineListToANSI opts txt
+  return $ D.underlined $ D.fg D.cyan $ D.link src label
+
+inlineToANSI opts (Image _ alt _) = do
+  infig <- gets stInFigure
+  if not infig then do
+    alt' <- inlineListToANSI opts alt
+    return $ D.brackets $ "image: " <> alt'
+  else return $ D.brackets "image"
+
+-- by construction, we should never be lacking in superscript characters
+-- for the footnote number, but we'll fall back to square brackets anyway
+inlineToANSI opts (Note contents) = do
+  curNotes <- gets stNotes
+  let newnum = tshow $ length curNotes + 1
+  contents' <- blockListToANSI opts contents
+  modify $ \s -> s { stNotes = contents' : curNotes }
+  let super = T.pack <$> (traverse toSuperscript (T.unpack newnum))
+  return $ D.literal $ fromMaybe ("[" <> newnum <> "]") super
diff --git a/src/Text/Pandoc/Writers/AnnotatedTable.hs b/src/Text/Pandoc/Writers/AnnotatedTable.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Writers/AnnotatedTable.hs
@@ -0,0 +1,322 @@
+{-# LANGUAGE BangPatterns #-}
+{-# LANGUAGE DeriveDataTypeable #-}
+{-# LANGUAGE DeriveGeneric #-}
+{-# LANGUAGE FlexibleContexts #-}
+{-# LANGUAGE FlexibleInstances #-}
+{-# LANGUAGE GeneralizedNewtypeDeriving #-}
+{-# LANGUAGE MultiParamTypeClasses #-}
+{-# LANGUAGE TupleSections #-}
+{-# LANGUAGE UndecidableInstances #-}
+
+{- |
+   Module      : Text.Pandoc.Writers.AnnotatedTable
+   Copyright   : Copyright 2020 Christian Despres
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : Christian Despres <christian.j.j.despres@gmail.com>
+   Stability   : alpha
+   Portability : portable
+
+Definitions and conversion functions for an intermediate 'Table' and
+related types, which annotates the existing Pandoc 'B.Table' types
+with additional inferred information. For use in writers that need to
+know the details of columns that cells span, row numbers, and the
+cells that are in the row head.
+-}
+
+module Text.Pandoc.Writers.AnnotatedTable
+  ( toTable
+  , fromTable
+  , Table(..)
+  , TableHead(..)
+  , TableBody(..)
+  , TableFoot(..)
+  , HeaderRow(..)
+  , BodyRow(..)
+  , RowNumber(..)
+  , RowHead
+  , RowBody
+  , Cell(..)
+  , ColNumber(..)
+  )
+where
+
+import           Control.Monad.RWS.Strict
+import           Data.Generics                  ( Data
+                                                , Typeable
+                                                )
+import           Data.List.NonEmpty             ( NonEmpty(..) )
+import           GHC.Generics                   ( Generic )
+import qualified Text.Pandoc.Builder           as B
+import           Text.Pandoc.Walk               ( Walkable (..) )
+
+-- | An annotated table type, corresponding to the Pandoc 'B.Table'
+-- constructor and the HTML @\<table\>@ element. It records the data
+-- of the columns that cells span, the cells in the row head, the row
+-- numbers of rows, and the column numbers of cells, in addition to
+-- the data in a 'B.Table'. The type itself does not enforce any
+-- guarantees about the consistency of this data. Use 'toTable' to
+-- produce a 'Table' from a Pandoc 'B.Table'.
+data Table = Table B.Attr B.Caption [B.ColSpec] TableHead [TableBody] TableFoot
+  deriving (Eq, Ord, Read, Show, Typeable, Data, Generic)
+
+-- | An annotated table head, corresponding to a Pandoc 'B.TableHead'
+-- and the HTML @\<thead\>@ element.
+data TableHead = TableHead B.Attr [HeaderRow]
+  deriving (Eq, Ord, Read, Show, Typeable, Data, Generic)
+
+-- | An annotated table body, with an intermediate head and body,
+-- corresponding to a Pandoc 'B.TableBody' and the HTML @\<tbody\>@
+-- element.
+data TableBody = TableBody B.Attr B.RowHeadColumns [HeaderRow] [BodyRow]
+  deriving (Eq, Ord, Read, Show, Typeable, Data, Generic)
+
+-- | An annotated table foot, corresponding to a Pandoc 'B.TableFoot'
+-- and the HTML @\<tfoot\>@ element.
+data TableFoot = TableFoot B.Attr [HeaderRow]
+  deriving (Eq, Ord, Read, Show, Typeable, Data, Generic)
+
+-- | An annotated header row, corresponding to a Pandoc 'B.Row' and
+-- the HTML @\<tr\>@ element, and also recording the row number of the
+-- row. All the cells in a 'HeaderRow' are header (@\<th\>@) cells.
+data HeaderRow = HeaderRow B.Attr RowNumber [Cell]
+  deriving (Eq, Ord, Read, Show, Typeable, Data, Generic)
+
+-- | An annotated body row, corresponding to a Pandoc 'B.Row' and the
+-- HTML @\<tr\>@ element, and also recording its row number and
+-- separating the row head cells from the row body cells.
+data BodyRow = BodyRow B.Attr RowNumber RowHead RowBody
+  deriving (Eq, Ord, Read, Show, Typeable, Data, Generic)
+
+-- | The row number of a row. Note that rows are numbered continuously
+-- from zero from the start of the table, so the first row in a table
+-- body, for instance, may have a large 'RowNumber'.
+newtype RowNumber = RowNumber Int
+  deriving (Eq, Ord, Read, Show, Typeable, Data, Generic, Num, Enum)
+
+-- | The head of a body row; the portion of the row lying in the stub
+-- of the 'TableBody'. Its cells correspond to HTML @\<th\>@ cells.
+type RowHead = [Cell]
+
+-- | The body of a body row; the portion of the row lying after the
+-- stub of the 'TableBody'. Its cells correspond to HTML @\<td\>@
+-- cells.
+type RowBody = [Cell]
+
+-- | An annotated table cell, wrapping a Pandoc 'B.Cell' with its
+-- 'ColNumber' and the 'B.ColSpec' data for the columns that the cell
+-- spans.
+data Cell = Cell (NonEmpty B.ColSpec) ColNumber B.Cell
+  deriving (Eq, Ord, Read, Show, Typeable, Data, Generic)
+
+-- | The column number of a cell, meaning the column number of the
+-- first column that the cell spans, if the table were laid on a
+-- grid. Columns are numbered starting from zero.
+newtype ColNumber = ColNumber Int
+  deriving (Eq, Ord, Read, Show, Typeable, Data, Generic, Num, Enum)
+
+-- | Convert a Pandoc 'B.Table' to an annotated 'Table'. This function
+-- also performs the same normalization that the 'B.table' builder
+-- does (fixing overlapping cells, cells that protrude out of their
+-- table section, and so on). If the input table happens to satisfy
+-- the conditions that 'B.table' guarantees, then the resulting
+-- 'Table' will be identical, save for the addition of the inferred
+-- table information.
+toTable
+  :: B.Attr
+  -> B.Caption
+  -> [B.ColSpec]
+  -> B.TableHead
+  -> [B.TableBody]
+  -> B.TableFoot
+  -> Table
+toTable attr cap cs th tbs tf = Table attr cap cs th' tbs' tf'
+ where
+  (th', tbs', tf') = fst $ evalRWS (annotateTable th tbs tf) (cs, length cs) 0
+
+-- | Internal monad for annotating a table, passing in the 'B.ColSpec'
+-- data for the table, the grid width, and the current 'RowNumber' to
+-- be referenced or updated.
+type AnnM a = RWS ([B.ColSpec], Int) () RowNumber a
+
+incRowNumber :: AnnM RowNumber
+incRowNumber = do
+  rn <- get
+  put $ rn + 1
+  return rn
+
+annotateTable
+  :: B.TableHead
+  -> [B.TableBody]
+  -> B.TableFoot
+  -> AnnM (TableHead, [TableBody], TableFoot)
+annotateTable th tbs tf = do
+  th'  <- annotateTableHead th
+  tbs' <- traverse annotateTableBody tbs
+  tf'  <- annotateTableFoot tf
+  return (th', tbs', tf')
+
+annotateTableHead :: B.TableHead -> AnnM TableHead
+annotateTableHead (B.TableHead attr rows) =
+  TableHead attr <$> annotateHeaderSection rows
+
+annotateTableBody :: B.TableBody -> AnnM TableBody
+annotateTableBody (B.TableBody attr rhc th tb) = do
+  twidth <- asks snd
+  let rhc' = max 0 $ min (B.RowHeadColumns twidth) rhc
+  th' <- annotateHeaderSection th
+  tb' <- annotateBodySection rhc' tb
+  return $ TableBody attr rhc' th' tb'
+
+annotateTableFoot :: B.TableFoot -> AnnM TableFoot
+annotateTableFoot (B.TableFoot attr rows) =
+  TableFoot attr <$> annotateHeaderSection rows
+
+annotateHeaderSection :: [B.Row] -> AnnM [HeaderRow]
+annotateHeaderSection rows = do
+  colspec <- asks fst
+  let hangcolspec = (1, ) <$> colspec
+  annotateHeaderSection' hangcolspec id $ B.clipRows rows
+ where
+  annotateHeaderSection' oldHang acc (B.Row attr cells : rs) = do
+    let (_, newHang, cells', _) =
+          annotateRowSection 0 oldHang $ cells <> repeat B.emptyCell
+    n <- incRowNumber
+    let annRow = HeaderRow attr n cells'
+    annotateHeaderSection' newHang (acc . (annRow :)) rs
+  annotateHeaderSection' _ acc [] = return $ acc []
+
+annotateBodySection :: B.RowHeadColumns -> [B.Row] -> AnnM [BodyRow]
+annotateBodySection (B.RowHeadColumns rhc) rows = do
+  colspec <- asks fst
+  let colspec'             = (1, ) <$> colspec
+  let (stubspec, bodyspec) = splitAt rhc colspec'
+  normalizeBodySection' stubspec bodyspec id $ B.clipRows rows
+ where
+  normalizeBodySection' headHang bodyHang acc (B.Row attr cells : rs) = do
+    let (colnum, headHang', rowStub, cells') =
+          annotateRowSection 0 headHang $ cells <> repeat B.emptyCell
+    let (_, bodyHang', rowBody, _) = annotateRowSection colnum bodyHang cells'
+    n <- incRowNumber
+    let annRow = BodyRow attr n rowStub rowBody
+    normalizeBodySection' headHang' bodyHang' (acc . (annRow :)) rs
+  normalizeBodySection' _ _ acc [] = return $ acc []
+
+-- | Lay out a section of a 'Table' row on a grid row, annotating the
+-- cells with the 'B.ColSpec' data for the columns that they
+-- span. Performs the same normalization as 'B.placeRowSection'.
+annotateRowSection
+  :: ColNumber -- ^ The current column number
+  -> [(B.RowSpan, B.ColSpec)] -- ^ The overhang of the previous grid row,
+                              -- with column data
+  -> [B.Cell] -- ^ The cells to annotate
+  -> (ColNumber, [(B.RowSpan, B.ColSpec)], [Cell], [B.Cell]) -- ^ The new
+                                                             -- column
+                                                             -- number,
+                                                             -- overhang,
+                                                             -- annotated
+                                                             -- cells,
+                                                             -- and
+                                                             -- remaining
+                                                             -- cells
+annotateRowSection !colnum oldHang cells
+  -- If the grid has overhang at our position, try to re-lay in
+  -- the next position.
+  | (o, colspec) : os <- oldHang
+  , o > 1
+  = let (colnum', newHang, newCell, cells') =
+            annotateRowSection (colnum + 1) os cells
+    in  (colnum', (o - 1, colspec) : newHang, newCell, cells')
+  -- Otherwise if there is any available width, place the cell and
+  -- continue.
+  | c : cells' <- cells
+  , (h, w) <- getDim c
+  , w' <- max 1 w
+  , (w'', cellHang@(chStart : chRest), oldHang') <- splitCellHang h w' oldHang
+  = let c'      = setW w'' c
+        annCell = Cell (snd <$> chStart :| chRest) colnum c'
+        colnum' = colnum + ColNumber (getColSpan w'')
+        (colnum'', newHang, newCells, remainCells) =
+            annotateRowSection colnum' oldHang' cells'
+    in  (colnum'', cellHang <> newHang, annCell : newCells, remainCells)
+  -- Otherwise there is no room in the section
+  | otherwise
+  = (colnum, [], [], cells)
+ where
+  getColSpan (B.ColSpan x) = x
+  getDim (B.Cell _ _ h w _) = (h, w)
+  setW w (B.Cell a b h _ c) = B.Cell a b h w c
+
+-- | In @'splitCellHang' rs cs coldata@, with @rs@ the height of a
+-- cell that lies at the beginning of @coldata@, and @cs@ its width
+-- (which is not assumed to fit in the available space), return the
+-- actual width of the cell (what will fit in the available space),
+-- the data for the columns that the cell spans (including updating
+-- the overhang to equal @rs@), and the remaining column data.
+splitCellHang
+  :: B.RowSpan
+  -> B.ColSpan
+  -> [(B.RowSpan, B.ColSpec)]
+  -> (B.ColSpan, [(B.RowSpan, B.ColSpec)], [(B.RowSpan, B.ColSpec)])
+splitCellHang h n = go 0
+ where
+  go acc ((1, spec) : ls) | acc < n =
+    let (acc', hang, ls') = go (acc + 1) ls in (acc', (h, spec) : hang, ls')
+  go acc l = (acc, [], l)
+
+-- | Convert an annotated 'Table' to a Pandoc
+-- 'B.Table'. This is the inverse of 'toTable' on
+-- well-formed tables (i.e. tables satisfying the guarantees of
+-- 'B.table').
+fromTable
+  :: Table
+  -> ( B.Attr
+     , B.Caption
+     , [B.ColSpec]
+     , B.TableHead
+     , [B.TableBody]
+     , B.TableFoot
+     )
+fromTable (Table attr cap cs th tbs tf) = (attr, cap, cs, th', tbs', tf')
+ where
+  th'  = fromTableHead th
+  tbs' = map fromTableBody tbs
+  tf'  = fromTableFoot tf
+
+fromTableHead :: TableHead -> B.TableHead
+fromTableHead (TableHead attr rows) = B.TableHead attr $ fromHeaderRow <$> rows
+
+fromTableBody :: TableBody -> B.TableBody
+fromTableBody (TableBody attr rhc th tb) =
+  B.TableBody attr rhc (fromHeaderRow <$> th) (fromBodyRow <$> tb)
+
+fromTableFoot :: TableFoot -> B.TableFoot
+fromTableFoot (TableFoot attr rows) = B.TableFoot attr $ fromHeaderRow <$> rows
+
+fromHeaderRow :: HeaderRow -> B.Row
+fromHeaderRow (HeaderRow attr _ cells) = B.Row attr $ fromCell <$> cells
+
+fromBodyRow :: BodyRow -> B.Row
+fromBodyRow (BodyRow attr _ rh rb) =
+  B.Row attr ((fromCell <$> rh) <> (fromCell <$> rb))
+
+fromCell :: Cell -> B.Cell
+fromCell (Cell _ _ c) = c
+
+--
+-- Instances
+--
+instance Walkable a B.Cell => Walkable a Cell where
+  walkM f (Cell colspecs colnum cell) =
+    Cell colspecs colnum <$> walkM f cell
+  query f (Cell _colspecs _colnum cell) = query f cell
+
+instance Walkable a B.Cell => Walkable a HeaderRow where
+  walkM f (HeaderRow attr rownum cells) =
+    HeaderRow attr rownum <$> walkM f cells
+  query f (HeaderRow _attr _rownum cells) = query f cells
+
+instance Walkable a B.Cell => Walkable a TableHead where
+  walkM f (TableHead attr rows) =
+    TableHead attr <$> walkM f rows
+  query f (TableHead _attr rows) = query f rows
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,25 +1,9 @@
+{-# LANGUAGE CPP  #-}
+{-# LANGUAGE LambdaCase        #-}
 {-# LANGUAGE OverloadedStrings #-}
-{-
-Copyright (C) 2006-2017 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-2017 John MacFarlane
+   Copyright   : Copyright (C) 2006-2024 John MacFarlane
    License     : GNU GPL, version 2 or above
 
    Maintainer  : John MacFarlane <jgm@berkeley.edu>
@@ -36,42 +20,90 @@
 
 AsciiDoc:  <http://www.methods.co.nz/asciidoc/>
 -}
-module Text.Pandoc.Writers.AsciiDoc (writeAsciiDoc) where
+module Text.Pandoc.Writers.AsciiDoc (
+  writeAsciiDoc,
+  writeAsciiDocLegacy,
+  writeAsciiDoctor
+  ) where
+import Control.Monad (foldM)
 import Control.Monad.State.Strict
-import Data.Aeson (Result (..), Value (String), fromJSON, toJSON)
+    ( StateT, MonadState(get), gets, modify, evalStateT )
 import Data.Char (isPunctuation, isSpace)
-import Data.List (intercalate, intersperse, stripPrefix)
+#if MIN_VERSION_base(4,19,0)
+import Data.List (delete, intercalate, intersperse, mapAccumL, uncons, sortOn, unsnoc)
+#else
+import Data.List (delete, intercalate, intersperse, mapAccumL, uncons, sortOn)
+#endif
+import Data.List.NonEmpty (NonEmpty((:|)), (<|))
+import qualified Data.List.NonEmpty as NonEmpty
+import Data.Maybe (fromMaybe, isJust, catMaybes)
 import qualified Data.Map as M
-import Data.Maybe (fromMaybe, isJust)
-import Data.Text (Text)
+import qualified Data.Set as Set
 import qualified Data.Text as T
-import Text.Pandoc.Class (PandocMonad, report)
+import Data.Text (Text)
+import Network.URI (parseURI, URI(uriScheme))
+import System.FilePath (dropExtension)
+import Text.Pandoc.Class.PandocMonad (PandocMonad, report)
 import Text.Pandoc.Definition
 import Text.Pandoc.ImageSize
 import Text.Pandoc.Logging
 import Text.Pandoc.Options
 import Text.Pandoc.Parsing hiding (blankline, space)
-import Text.Pandoc.Pretty
+import Text.DocLayout
+import Text.Pandoc.Builder (emptyCell)
 import Text.Pandoc.Shared
-import Text.Pandoc.Templates (renderTemplate')
+import Text.Pandoc.URI
+import Text.Pandoc.Templates (renderTemplate)
 import Text.Pandoc.Writers.Shared
+import Text.Pandoc.Walk (walk)
 
-data WriterState = WriterState { defListMarker    :: String
-                               , orderedListLevel :: Int
-                               , bulletListLevel  :: Int
-                               , intraword        :: Bool
+#if !MIN_VERSION_base(4,19,0)
+unsnoc :: [a] -> Maybe ([a], a)
+unsnoc = foldr (\x -> Just . maybe ([], x) (\(~(a, b)) -> (x : a, b))) Nothing
+#endif
+
+data WriterState = WriterState { defListMarker       :: Text
+                               , orderedListLevel    :: Int
+                               , bulletListLevel     :: Int
+                               , intraword           :: Bool
+                               , autoIds             :: Set.Set Text
+                               , legacy              :: Bool
+                               , inList              :: Bool
+                               , hasMath             :: Bool
+                               -- |0 is no table
+                               -- 1 is top level table
+                               -- 2 is a table in a table
+                               , tableNestingLevel   :: Int
                                }
 
+defaultWriterState :: WriterState
+defaultWriterState = WriterState { defListMarker      = "::"
+                                 , orderedListLevel   = 0
+                                 , bulletListLevel    = 0
+                                 , intraword          = False
+                                 , autoIds            = Set.empty
+                                 , legacy             = False
+                                 , inList             = False
+                                 , hasMath            = False
+                                 , tableNestingLevel  = 0
+                                 }
+
 -- | 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
-    }
+  evalStateT (pandocToAsciiDoc opts document) defaultWriterState
 
+{-# DEPRECATED writeAsciiDoctor "Use writeAsciiDoc instead" #-}
+-- | Deprecated synonym of 'writeAsciiDoc'.
+writeAsciiDoctor :: PandocMonad m => WriterOptions -> Pandoc -> m Text
+writeAsciiDoctor = writeAsciiDoc
+
+-- | Convert Pandoc to legacy AsciiDoc.
+writeAsciiDocLegacy :: PandocMonad m => WriterOptions -> Pandoc -> m Text
+writeAsciiDocLegacy opts document =
+  evalStateT (pandocToAsciiDoc opts document)
+    defaultWriterState{ legacy = True }
+
 type ADW = StateT WriterState
 
 -- | Return asciidoc representation of document.
@@ -82,37 +114,67 @@
   let colwidth = if writerWrapText opts == WrapAuto
                     then Just $ writerColumns opts
                     else Nothing
-  let render' :: Doc -> Text
-      render' = render colwidth
-  metadata <- metaToJSON opts
-              (fmap render' . blockListToAsciiDoc opts)
-              (fmap render' . inlineListToAsciiDoc opts)
+  metadata <- metaToContext opts
+              (blockListToAsciiDoc opts)
+              (fmap chomp . inlineListToAsciiDoc opts)
               meta
-  let addTitleLine (String t) = String $
-         t <> "\n" <> T.replicate (T.length t) "="
-      addTitleLine x = x
-  let metadata' = case fromJSON metadata of
-                        Success m  -> toJSON $ M.adjust addTitleLine
-                                                 ("title" :: T.Text) m
-                        _          -> metadata
-  body <- blockListToAsciiDoc opts blocks
-  let main = render colwidth body
+  main <- blockListToAsciiDoc opts $ makeSections False Nothing blocks
+  st <- get
   let context  = defField "body" main
                $ defField "toc"
                   (writerTableOfContents opts &&
                    isJust (writerTemplate opts))
-               $defField "titleblock" titleblock metadata'
-  case writerTemplate opts of
-       Nothing  -> return main
-       Just tpl -> renderTemplate' tpl context
+               $ defField "math" (hasMath st && not (legacy st))
+               $ defField "titleblock" titleblock metadata
+  return $ render colwidth $
+    case writerTemplate opts of
+       Nothing  -> main
+       Just tpl -> renderTemplate tpl context
 
+data EscContext = Normal | InTable
+  deriving (Show, Eq)
+
 -- | Escape special characters for AsciiDoc.
-escapeString :: String -> String
-escapeString = escapeStringUsing escs
-  where escs = backslashEscapes "{"
+escapeString :: EscContext -> Text -> Doc Text
+escapeString context t
+  | T.any needsEscape t
+  = literal $
+      case T.foldl' go (False, mempty) t of
+        (True, x) -> x <> "++" -- close passthrough context
+        (False, x) -> x
+  | otherwise = literal t
+ where
+  -- Bool is True when we are in a ++ passthrough context
+  go :: (Bool, Text) -> Char -> (Bool, Text)
+  go (True, x) '+' = (False, x <> "++" <> "{plus}") -- close context
+  go (False, x) '+' = (False, x <> "{plus}")
+  go (True, x) '|'
+    | context == InTable = (False, x <> "++" <> "{vbar}") -- close context
+  go (False, x) '|'
+    | context == InTable = (False, x <> "{vbar}")
+  go (True, x) c
+    | needsEscape c = (True, T.snoc x c)
+    | otherwise = (False, T.snoc (x <> "++") c)
+  go (False, x) c
+    | needsEscape c = (True, x <> "++" <> T.singleton c)
+    | otherwise = (False, T.snoc x c)
 
+  needsEscape '{' = True
+  needsEscape '+' = True
+  needsEscape '`' = True
+  needsEscape '*' = True
+  needsEscape '#' = True
+  needsEscape '_' = True
+  needsEscape '<' = True
+  needsEscape '>' = True
+  needsEscape '[' = True
+  needsEscape ']' = True
+  needsEscape '\\' = True
+  needsEscape '|' = True
+  needsEscape _ = False
+
 -- | Ordered list start parser for use in Para below.
-olMarker :: Parser [Char] ParserState Char
+olMarker :: Parsec Text ParserState Char
 olMarker = do (start, style', delim) <- anyOrderedListMarker
               if delim == Period &&
                           (style' == UpperAlpha || (style' == UpperRoman &&
@@ -121,28 +183,38 @@
                           else spaceChar
 
 -- | True if string begins with an ordered list marker
-beginsWithOrderedListMarker :: String -> Bool
-beginsWithOrderedListMarker str =
-  case runParser olMarker defaultParserState "para start" (take 10 str) of
-         Left  _ -> False
-         Right _ -> True
+-- or would be interpreted as an AsciiDoc option command
+needsEscaping :: Text -> Bool
+needsEscaping s = beginsWithOrderedListMarker s || isBracketed s
+  where
+    beginsWithOrderedListMarker str =
+      case runParser olMarker defaultParserState "para start" (T.take 10 str) of
+             Left  _ -> False
+             Right _ -> True
+    isBracketed t
+      | Just ('[', t') <- T.uncons t
+      , Just (_, ']')  <- T.unsnoc t'
+      = True
+      | otherwise = False
 
 -- | Convert Pandoc block element to asciidoc.
 blockToAsciiDoc :: PandocMonad m
                 => WriterOptions -- ^ Options
                 -> Block         -- ^ Block element
-                -> ADW m Doc
-blockToAsciiDoc _ Null = return empty
+                -> ADW m (Doc Text)
+blockToAsciiDoc opts (Div (id',"section":_,_)
+                       (Header level (_,cls,kvs) ils : xs)) = do
+  hdr <- blockToAsciiDoc opts (Header level (id',cls,kvs) ils)
+  rest <- blockListToAsciiDoc opts xs
+  return $ hdr $$ rest
 blockToAsciiDoc opts (Plain inlines) = do
   contents <- inlineListToAsciiDoc opts inlines
   return $ contents <> blankline
-blockToAsciiDoc opts (Para [Image attr alt (src,'f':'i':'g':':':tit)]) =
-  blockToAsciiDoc opts (Para [Image attr alt (src,tit)])
 blockToAsciiDoc opts (Para inlines) = do
   contents <- inlineListToAsciiDoc opts inlines
   -- escape if para starts with ordered list marker
-  let esc = if beginsWithOrderedListMarker (render Nothing contents)
-               then text "\\"
+  let esc = if needsEscaping (render Nothing contents)
+               then text "{empty}"
                else empty
   return $ esc <> contents <> blankline
 blockToAsciiDoc opts (LineBlock lns) = do
@@ -153,7 +225,7 @@
   contents <- joinWithLinefeeds <$> mapM docify lns
   return $ "[verse]" $$ text "--" $$ contents $$ text "--" $$ blankline
 blockToAsciiDoc _ b@(RawBlock f s)
-  | f == "asciidoc" = return $ text s
+  | f == "asciidoc" = return $ literal s
   | otherwise         = do
       report $ BlockNotRendered b
       return empty
@@ -161,29 +233,46 @@
   return $ blankline <> text "'''''" <> blankline
 blockToAsciiDoc opts (Header level (ident,_,_) inlines) = do
   contents <- inlineListToAsciiDoc opts inlines
-  let len = offset contents
-  -- ident seem to be empty most of the time and asciidoc will generate them automatically
-  -- so lets make them not show up when null
-  let identifier = if null ident then empty else "[[" <> text ident <> "]]"
-  let setext = writerSetextHeaders opts
-  return
-         (if setext
-            then
-              identifier $$ contents $$
-              (case level of
-               1 -> text $ replicate len '-'
-               2 -> text $ replicate len '~'
-               3 -> text $ replicate len '^'
-               4 -> text $ replicate len '+'
-               _ -> empty) <> blankline
-            else
-              identifier $$ text (replicate level '=') <> space <> contents <> blankline)
+  ids <- gets autoIds
+  let autoId = uniqueIdent (writerExtensions opts) inlines ids
+  modify $ \st -> st{ autoIds = Set.insert autoId ids }
+  let identifier = if T.null ident ||
+                      (isEnabled Ext_auto_identifiers opts && ident == autoId)
+                      then empty
+                      else "[[" <> literal ident <> "]]"
+  return $ identifier $$
+           nowrap (text (replicate (level + 1) '=') <> space <> contents) <>
+           blankline
+blockToAsciiDoc opts (Figure attr (Caption _ longcapt) body) = do
+  -- Images in figures all get rendered as individual block-level images
+  -- with the given caption. Non-image elements are rendered unchanged.
+  capt <- if null longcapt
+             then pure mempty
+             else ("." <>) . nowrap <$>
+                   inlineListToAsciiDoc opts (blocksToInlines longcapt)
+  let renderFigElement = \case
+        Plain [Image imgAttr alternate (src, tit)] -> do
+          args <- imageArguments opts imgAttr alternate src tit
+          let figAttributes = case attr of
+                ("", _, _)    -> empty
+                (ident, _, _) -> literal $ "[#" <> ident <> "]"
+          -- .Figure caption
+          -- image::images/logo.png[Company logo, title="blah"]
+          return $
+            capt $$
+            figAttributes $$
+            "image::" <> args <> blankline
+        blk -> blockToAsciiDoc opts blk
+  vcat <$> mapM renderFigElement body
 blockToAsciiDoc _ (CodeBlock (_,classes,_) str) = return $ flush (
   if null classes
-     then "...." $$ text str $$ "...."
-     else attrs $$ "----" $$ text str $$ "----")
+     then "...." $$ literal str $$ "...."
+     else attrs $$ "----" $$ literal str $$ "----")
   <> blankline
-    where attrs = "[" <> text (intercalate "," ("source" : classes)) <> "]"
+    where attrs = "[" <> literal (T.intercalate "," classes') <> "]"
+          classes' = if "numberLines" `elem` classes
+                        then "source%linesnum" : delete "numberLines" classes
+                        else "source" : classes
 blockToAsciiDoc opts (BlockQuote blocks) = do
   contents <- blockListToAsciiDoc opts blocks
   let isBlock (BlockQuote _) = True
@@ -192,10 +281,14 @@
   let contents' = if any isBlock blocks
                      then "--" $$ contents $$ "--"
                      else contents
-  let cols = offset contents'
-  let bar = text $ replicate cols '_'
+  let bar = text "____"
   return $ bar $$ chomp contents' $$ bar <> blankline
-blockToAsciiDoc opts (Table caption aligns widths headers rows) =  do
+blockToAsciiDoc opts block@(Table _ blkCapt specs thead@(TableHead _ originalHeaders) originalTbody tfoot@(TableFoot _ originalFooters)) = do
+  let (caption, aligns, widths, _, _) =
+        toLegacyTable blkCapt specs thead originalTbody tfoot
+  let headers = adjustEmptyRows originalHeaders
+  let rows = adjustEmptyRows $ tableBodiesToRows originalTbody
+  let footers = adjustEmptyRows originalFooters
   caption' <- inlineListToAsciiDoc opts caption
   let caption'' = if null caption
                      then empty
@@ -214,15 +307,19 @@
                      ws        -> ws
   let totalwidth :: Integer
       totalwidth = floor $ sum widths * 100
-  let colspec al wi = (case al of
-                         AlignLeft    -> "<"
-                         AlignCenter  -> "^"
-                         AlignRight   -> ">"
-                         AlignDefault -> "") ++
+  let alignmentOperator AlignLeft     = "<"
+      alignmentOperator AlignCenter   = "^"
+      alignmentOperator AlignRight    = ">"
+      alignmentOperator AlignDefault  = ""
+  let colspec al wi = (alignmentOperator al) ++
                       if wi == 0 then "" else show wi ++ "%"
-  let headerspec = if all null headers
+  let optionSpecForRows rowList spec = if allRowsEmpty rowList then Nothing else Just spec
+  let headerspec = optionSpecForRows headers "header"
+  let footerspec = optionSpecForRows footers "footer"
+  let optionsList = catMaybes [headerspec, footerspec]
+  let optionsspec = if null optionsList
                       then empty
-                      else text "options=\"header\","
+                      else text "options=\"" <> text (intercalate "," optionsList) <> text "\","
   let widthspec = if totalwidth == 0
                      then empty
                      else text "width="
@@ -234,92 +331,205 @@
          <> doubleQuotes (text $ intercalate ","
              $ zipWith colspec aligns widths')
          <> text ","
-         <> headerspec <> text "]"
+         <> optionsspec <> text "]"
+
+  -- construct cells and recurse in case of nested tables
+  parentTableLevel <- gets tableNestingLevel
+  let currentNestingLevel = parentTableLevel + 1
+
+  modify $ \st -> st{ tableNestingLevel = currentNestingLevel }
+
+  let separator = text (if parentTableLevel == 0
+                          then "|"  -- top level separator
+                          else "!") -- nested separator
+
   let makeCell [Plain x] = do d <- blockListToAsciiDoc opts [Plain x]
-                              return $ text "|" <> chomp d
+                              return $ separator <> chomp d
       makeCell [Para x]  = makeCell [Plain x]
-      makeCell []        = return $ text "|"
-      makeCell bs        = do d <- blockListToAsciiDoc opts bs
-                              return $ text "a|" $$ d
-  let makeRow cells = hsep `fmap` mapM makeCell cells
-  rows' <- mapM makeRow rows
-  head' <- makeRow headers
-  let head'' = if all null headers then empty else head'
+      makeCell []        = return separator
+      makeCell bs        = if currentNestingLevel == 2
+                             then do
+                               --asciidoc only supports nesting once
+                               report $ BlockNotRendered block
+                               return separator
+                             else do
+                               d <- blockListToAsciiDoc opts bs
+                               return $ (text "a" <> separator) $$ d
+
+  let colSpanFactor (ColSpan colSpan) = if colSpan > 1
+                                          then text $ show colSpan
+                                          else empty
+  let rowSpanFactor (RowSpan rowSpan) = if rowSpan > 1
+                                          then text $ "." ++ show rowSpan
+                                          else empty
+
+  let makeCellWithSpansAndAlignment (Cell _ alignment rowSpan colSpan blocks) = do
+        let spanFactor = colSpanFactor colSpan <> rowSpanFactor rowSpan
+        cell <- makeCell blocks
+        let alignedCell = alignmentOperator alignment <> cell
+
+        return $ if null spanFactor
+          then alignedCell
+          else spanFactor <> text "+" <> alignedCell
+
+  let makeRow (Row attr []) = makeRow $ Row attr $ replicate (length widths') emptyCell
+      makeRow (Row _ cells) = hsep `fmap` mapM makeCellWithSpansAndAlignment cells
+
+  -- AsciiDoc only supports 1 header row and 1 footer row.
+  let headerRow = Data.List.uncons $ adjustHeaders headers
+  let footerRow = unsnoc $ adjustFooters footers
+  let tailHeaderRows = if allRowsEmpty headers then [] else maybe [] snd headerRow
+  let initFooterRows = if allRowsEmpty footers then [] else maybe [] fst footerRow
+  rows' <- mapM makeRow $ tailHeaderRows ++ rows ++ initFooterRows
+  head' <- case headerRow of
+            Nothing -> return empty
+            Just (headerRow', _) -> makeRow headerRow'
+  foot <- case footerRow of
+            Nothing -> return empty
+            Just (_, footerRow') -> makeRow footerRow'
+  modify $ \st -> st{ tableNestingLevel = parentTableLevel }
+  let head'' = if allRowsEmpty headers then empty else head'
+  let foot' = if allRowsEmpty footers then empty else foot
   let colwidth = if writerWrapText opts == WrapAuto
                     then writerColumns opts
                     else 100000
-  let maxwidth = maximum $ map offset (head':rows')
+  let maxwidth = maximum $ fmap offset (foot <| (head' :| rows'))
   let body = if maxwidth > colwidth then vsep rows' else vcat rows'
-  let border = text $ "|" ++ replicate (max 5 (min maxwidth colwidth) - 1) '='
+  let border = separator <> text "==="
   return $
-    caption'' $$ tablespec $$ border $$ head'' $$ body $$ border $$ blankline
+    caption'' $$ tablespec $$ border $$ head'' $$ body $$ foot' $$ border $$ blankline
 blockToAsciiDoc opts (BulletList items) = do
+  inlist <- gets inList
+  modify $ \st -> st{ inList = True }
   contents <- mapM (bulletListItemToAsciiDoc opts) items
-  return $ cat contents <> blankline
-blockToAsciiDoc opts (OrderedList (_start, sty, _delim) items) = do
-  let sty' = case sty of
-                  UpperRoman -> UpperAlpha
-                  LowerRoman -> LowerAlpha
-                  x          -> x
-  let markers  = orderedListMarkers (1, sty', Period)  -- start num not used
-  let markers' = map (\m -> if length m < 3
-                               then m ++ replicate (3 - length m) ' '
-                               else m) markers
-  contents <- mapM (uncurry (orderedListItemToAsciiDoc opts)) $
-              zip markers' items
-  return $ cat contents <> blankline
+  modify $ \st -> st{ inList = inlist }
+  return $ mconcat contents <> blankline
+blockToAsciiDoc opts (OrderedList (start, sty, _delim) items) = do
+  let listStyle = case sty of
+                       DefaultStyle -> []
+                       Decimal      -> ["arabic"]
+                       Example      -> []
+                       _            -> [T.toLower (tshow sty)]
+  let listStart = ["start=" <> tshow start | start /= 1]
+  let listoptions = case T.intercalate ", " (listStyle ++ listStart) of
+                          "" -> empty
+                          x  -> brackets (literal x)
+  inlist <- gets inList
+  modify $ \st -> st{ inList = True }
+  contents <- mapM (orderedListItemToAsciiDoc opts) items
+  modify $ \st -> st{ inList = inlist }
+  return $ listoptions $$ mconcat contents <> blankline
 blockToAsciiDoc opts (DefinitionList items) = do
+  inlist <- gets inList
+  modify $ \st -> st{ inList = True }
   contents <- mapM (definitionListItemToAsciiDoc opts) items
-  return $ cat contents <> blankline
-blockToAsciiDoc opts (Div (ident,_,_) bs) = do
-  let identifier = if null ident then empty else ("[[" <> text ident <> "]]")
-  contents <- blockListToAsciiDoc opts bs
-  return $ identifier $$ contents
+  modify $ \st -> st{ inList = inlist }
+  return $ mconcat contents <> blankline
 
+-- convert admonition and sidebar divs to asicidoc
+blockToAsciiDoc opts (Div (ident,classes,_) bs) = do
+  let identifier = if T.null ident then empty else "[[" <> literal ident <> "]]"
+  let admonition_classes = ["attention","caution","danger","error","hint",
+                     "important","note","tip","warning"]
+  let sidebar_class = "sidebar"
+
+  contents <-
+       case classes of
+         (l:_) | l `elem` admonition_classes || T.toLower l == sidebar_class -> do
+             let (titleBs, bodyBs) =
+                     case bs of
+                       (Div (_,["title"],_) ts : rest) -> (ts, rest)
+                       _ -> ([], bs)
+             let fence = if l == "sidebar" then "****" else "===="
+             elemTitle <- if null titleBs ||
+                                   -- If title matches class, omit
+                                   (T.toLower (T.strip (stringify titleBs))) == l
+                                   then return mempty
+                                   else ("." <>) <$>
+                                         blockListToAsciiDoc opts titleBs
+             elemBody <- blockListToAsciiDoc opts bodyBs
+             return $ "[" <> literal (T.toUpper l) <> "]" $$
+                      chomp elemTitle $$
+                      fence $$
+                      chomp elemBody $$
+                      fence
+         _ -> blockListToAsciiDoc opts bs
+  return $ identifier $$ contents $$ blankline
+
 -- | Convert bullet list item (list of blocks) to asciidoc.
 bulletListItemToAsciiDoc :: PandocMonad m
-                         => WriterOptions -> [Block] -> ADW m Doc
+                         => WriterOptions -> [Block] -> ADW m (Doc Text)
 bulletListItemToAsciiDoc opts blocks = do
-  let addBlock :: PandocMonad m => Doc -> Block -> ADW m Doc
-      addBlock d b | isEmpty d    = chomp `fmap` blockToAsciiDoc opts b
-      addBlock d b@(BulletList _) = do x <- blockToAsciiDoc opts b
-                                       return $ d <> cr <> chomp x
-      addBlock d b@(OrderedList _ _) = do x <- blockToAsciiDoc opts b
-                                          return $ d <> cr <> chomp x
-      addBlock d b = do x <- blockToAsciiDoc opts b
-                        return $ d <> cr <> text "+" <> cr <> chomp x
   lev <- gets bulletListLevel
   modify $ \s -> s{ bulletListLevel = lev + 1 }
-  contents <- foldM addBlock empty blocks
+  isLegacy <- gets legacy
+  let blocksWithTasks = if isLegacy
+                          then blocks
+                          else (taskListItemToAsciiDoc blocks)
+  contents <- snd <$> foldM (addBlock opts) (False, empty) blocksWithTasks
   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 blocksWithTasks <>
+    contents <> cr
 
+-- | Convert a list item containing text starting with @U+2610 BALLOT BOX@
+-- or @U+2612 BALLOT BOX WITH X@ to asciidoctor checkbox syntax (e.g. @[x]@).
+taskListItemToAsciiDoc :: [Block] -> [Block]
+taskListItemToAsciiDoc = handleTaskListItem toAd listExt
+  where
+    toAd (Str "☐" : Space : is) = RawInline (Format "asciidoc") "[ ]" : Space : is
+    toAd (Str "☒" : Space : is) = RawInline (Format "asciidoc") "[x]" : Space : is
+    toAd is = is
+    listExt = extensionsFromList [Ext_task_lists]
+
+addBlock :: PandocMonad m
+         => WriterOptions -> (Bool, Doc Text) -> Block -> ADW m (Bool, Doc Text)
+addBlock opts (containsContinuation, d) b = do
+  x <- chomp <$> blockToAsciiDoc opts b
+  return $
+    case b of
+        BulletList{}
+          | containsContinuation -> (False, d <> blankline <> x)  -- see #11006
+          | otherwise -> (False, d <> cr <> x)
+        OrderedList (start, sty, _) _
+          | containsContinuation
+          , start == 1
+          , sty == DefaultStyle -> (False, d <> blankline <> x)  -- see #11006
+          | otherwise -> (False, d <> cr <> x)
+        Para (Math DisplayMath _:_) -> (containsContinuation, d <> cr <> x)
+        Plain (Math DisplayMath _:_) -> (containsContinuation, d <> cr <> x)
+        Para{} | isEmpty d -> (containsContinuation, x)
+        Plain{} | isEmpty d -> (containsContinuation, x)
+        _ -> (True, d <> cr <> text "+" <> cr <> x)
+
+listBegin :: [Block] -> Doc Text
+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
-                          -> String        -- ^ list item marker
                           -> [Block]       -- ^ list item (list of blocks)
-                          -> ADW m Doc
-orderedListItemToAsciiDoc opts marker blocks = do
-  let addBlock d b | isEmpty d    = chomp `fmap` blockToAsciiDoc opts b
-      addBlock d b@(BulletList _) = do x <- blockToAsciiDoc opts b
-                                       return $ d <> cr <> chomp x
-      addBlock d b@(OrderedList _ _) = do x <- blockToAsciiDoc opts b
-                                          return $ d <> cr <> chomp x
-      addBlock d b = do x <- blockToAsciiDoc opts b
-                        return $ d <> cr <> text "+" <> cr <> chomp x
+                          -> ADW m (Doc Text)
+orderedListItemToAsciiDoc opts blocks = do
   lev <- gets orderedListLevel
   modify $ \s -> s{ orderedListLevel = lev + 1 }
-  contents <- foldM addBlock empty blocks
+  contents <- snd <$> foldM (addBlock opts) (False, empty) blocks
   modify $ \s -> s{ orderedListLevel = lev }
-  return $ text 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
                              => WriterOptions
                              -> ([Inline],[[Block]])
-                             -> ADW m Doc
+                             -> ADW m (Doc Text)
 definitionListItemToAsciiDoc opts (label, defs) = do
   labelText <- inlineListToAsciiDoc opts label
   marker <- gets defListMarker
@@ -327,25 +537,29 @@
      then modify (\st -> st{ defListMarker = ";;"})
      else modify (\st -> st{ defListMarker = "::"})
   let divider = cr <> text "+" <> cr
-  let defsToAsciiDoc :: PandocMonad m => [Block] -> ADW m Doc
+  let defsToAsciiDoc :: PandocMonad m => [Block] -> ADW m (Doc Text)
       defsToAsciiDoc ds = (vcat . intersperse divider . map chomp)
            `fmap` mapM (blockToAsciiDoc opts) ds
   defs' <- mapM defsToAsciiDoc defs
   modify (\st -> st{ defListMarker = marker })
   let contents = nest 2 $ vcat $ intersperse divider $ map chomp defs'
-  return $ labelText <> text marker <> cr <> contents <> cr
+  return $ labelText <> literal marker <> cr <> contents <> cr
 
 -- | Convert list of Pandoc block elements to asciidoc.
 blockListToAsciiDoc :: PandocMonad m
                     => WriterOptions -- ^ Options
                     -> [Block]       -- ^ List of block elements
-                    -> ADW m Doc
-blockListToAsciiDoc opts blocks = cat `fmap` mapM (blockToAsciiDoc opts) blocks
+                    -> ADW m (Doc Text)
+blockListToAsciiDoc opts blocks =
+  mconcat `fmap` mapM (blockToAsciiDoc opts) blocks
 
 data SpacyLocation = End | Start
 
 -- | Convert list of Pandoc inline elements to asciidoc.
-inlineListToAsciiDoc :: PandocMonad m => WriterOptions -> [Inline] -> ADW m Doc
+inlineListToAsciiDoc :: PandocMonad m =>
+                        WriterOptions ->
+                        [Inline] ->
+                        ADW m (Doc Text)
 inlineListToAsciiDoc opts lst = do
   oldIntraword <- gets intraword
   setIntraword False
@@ -375,10 +589,13 @@
        isSpacy _ SoftBreak = True
        -- Note that \W characters count as spacy in AsciiDoc
        -- for purposes of determining interword:
-       isSpacy End (Str xs) = case reverse xs of
-                                   c:_ -> isPunctuation c || isSpace c
-                                   _   -> False
-       isSpacy Start (Str (c:_)) = isPunctuation c || isSpace c
+       isSpacy End (Str xs) = case T.unsnoc xs of
+                                   Just (_, c) -> isPunctuation c || isSpace c
+                                   _           -> False
+       isSpacy Start (Str xs)
+         | Just (c, _) <- T.uncons xs = isPunctuation c || isSpace c
+       isSpacy End (Link{}) = True
+       isSpacy End (Image{}) = True
        isSpacy _ _ = False
 
 setIntraword :: PandocMonad m => Bool -> ADW m ()
@@ -388,44 +605,82 @@
 withIntraword p = setIntraword True *> p <* setIntraword False
 
 -- | Convert Pandoc inline element to asciidoc.
-inlineToAsciiDoc :: PandocMonad m => WriterOptions -> Inline -> ADW m Doc
+inlineToAsciiDoc :: PandocMonad m => WriterOptions -> Inline -> ADW m (Doc Text)
+inlineToAsciiDoc opts (Emph [Strong xs]) =
+  inlineToAsciiDoc opts (Strong [Emph xs])  -- see #5565
 inlineToAsciiDoc opts (Emph lst) = do
   contents <- inlineListToAsciiDoc opts lst
   isIntraword <- gets intraword
   let marker = if isIntraword then "__" else "_"
-  return $ marker <> contents <> marker
+  return $ delimited marker marker contents
+inlineToAsciiDoc opts (Underline lst) = do
+  contents <- inlineListToAsciiDoc opts lst
+  return $ delimited "[.underline]#" "#" contents
 inlineToAsciiDoc opts (Strong lst) = do
   contents <- inlineListToAsciiDoc opts lst
   isIntraword <- gets intraword
   let marker = if isIntraword then "**" else "*"
-  return $ marker <> contents <> marker
+  return $ delimited marker marker contents
 inlineToAsciiDoc opts (Strikeout lst) = do
   contents <- inlineListToAsciiDoc opts lst
-  return $ "[line-through]*" <> contents <> "*"
+  return $ delimited "[line-through]#" "#" contents
 inlineToAsciiDoc opts (Superscript lst) = do
   contents <- inlineListToAsciiDoc opts lst
-  return $ "^" <> contents <> "^"
+  return $ delimited "^" "^" contents
 inlineToAsciiDoc opts (Subscript lst) = do
   contents <- inlineListToAsciiDoc opts lst
-  return $ "~" <> contents <> "~"
-inlineToAsciiDoc opts (SmallCaps lst) = inlineListToAsciiDoc opts lst
-inlineToAsciiDoc opts (Quoted SingleQuote lst) =
-  inlineListToAsciiDoc opts (Str "`" : lst ++ [Str "'"])
-inlineToAsciiDoc opts (Quoted DoubleQuote lst) =
-  inlineListToAsciiDoc opts (Str "``" : lst ++ [Str "''"])
-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 <> "\\]]"
+  return $ delimited "~" "~" contents
+inlineToAsciiDoc opts (SmallCaps lst) = do
+  contents <- inlineListToAsciiDoc opts lst
+  return $ delimited "[smallcaps]#" "#" contents
+inlineToAsciiDoc opts (Quoted qt lst) = do
+  isLegacy <- gets legacy
+  contents <- inlineListToAsciiDoc opts lst
+  pure $ case qt of
+    SingleQuote
+      | isLegacy     -> "`" <> contents <> "'"
+      | otherwise    -> "'`" <> contents <> "`'"
+    DoubleQuote
+      | isLegacy     -> "``" <> contents <> "''"
+      | otherwise    -> "\"`" <> contents <> "`\""
+inlineToAsciiDoc _ (Code _ str) = do
+  isLegacy <- gets legacy
+  let escChar '`' = "\\'"
+      escChar c   = T.singleton c
+  parentTableLevel <- gets tableNestingLevel
+  let content
+       | isLegacy = literal (T.concatMap escChar str)
+       | otherwise = escapeString
+                       (if parentTableLevel > 0 then InTable else Normal) str
+  return $ text "`" <> content <> "`"
+inlineToAsciiDoc _ (Str str) = do
+  parentTableLevel <- gets tableNestingLevel
+  pure $ escapeString (if parentTableLevel > 0 then InTable else Normal) str
+inlineToAsciiDoc _ (Math InlineMath str) = do
+  isLegacy <- gets legacy
+  modify $ \st -> st{ hasMath = True }
+  let content = if isLegacy
+                then "$" <> literal str <> "$"
+                else literal str
+  return $ "latexmath:[" <> content <> "]"
+inlineToAsciiDoc _ (Math DisplayMath str) = do
+  isLegacy <- gets legacy
+  modify $ \st -> st{ hasMath = True }
+  let content = if isLegacy
+                   then "\\[" <> literal str <> "\\]"
+                   else literal 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
+  | f == "asciidoc" = return $ literal s
   | otherwise         = do
       report $ InlineNotRendered il
       return empty
-  | otherwise       = return empty
 inlineToAsciiDoc _ LineBreak = return $ " +" <> cr
 inlineToAsciiDoc _ Space = return space
 inlineToAsciiDoc opts SoftBreak =
@@ -438,47 +693,220 @@
 -- relative:  link:downloads/foo.zip[download foo.zip]
 -- abs:  http://google.cod[Google]
 -- or my@email.com[email john]
-  linktext <- inlineListToAsciiDoc opts txt
-  let isRelative = ':' `notElem` src
-  let prefix = if isRelative
+  let fixCommas (Str t) =
+        intersperse (RawInline (Format "asciidoc") "&#44;")
+          $ map Str $ T.splitOn "," t -- see #8070
+      fixCommas x = [x]
+
+  linktext <- inlineListToAsciiDoc opts $ walk (concatMap fixCommas) txt
+  let needsLinkPrefix = case parseURI (T.unpack src) of
+                          Just u -> uriScheme u `notElem` ["http:","https:",
+                                                           "ftp:", "irc:",
+                                                            "mailto:"]
+                          _ -> True
+  let needsPassthrough = "--" `T.isInfixOf` src
+  let prefix = if needsLinkPrefix
                   then text "link:"
                   else empty
-  let srcSuffix = fromMaybe src (stripPrefix "mailto:" src)
+  let srcSuffix = fromMaybe src (T.stripPrefix "mailto:" src)
   let useAuto = case txt of
                       [Str s] | escapeURI s == srcSuffix -> True
                       _       -> False
-  return $ if useAuto
-              then text srcSuffix
-              else prefix <> text src <> "[" <> linktext <> "]"
-inlineToAsciiDoc opts (Image attr alternate (src, tit)) = do
--- image:images/logo.png[Company logo, title="blah"]
-  let txt = if (null alternate) || (alternate == [Str ""])
-               then [Str "image"]
-               else alternate
+  return $
+    if needsPassthrough
+       then
+         if useAuto
+            then "link:++" <> literal srcSuffix <> "++[]"
+            else "link:++" <> literal src <> "++[" <> linktext <> "]"
+       else
+         if useAuto
+            then literal srcSuffix
+            else prefix <> literal src <> "[" <> linktext <> "]"
+inlineToAsciiDoc opts (Image attr alternate (src, tit)) =
+  ("image:" <>) <$> imageArguments opts attr alternate src tit
+inlineToAsciiDoc opts (Note [Para inlines]) =
+  inlineToAsciiDoc opts (Note [Plain inlines])
+inlineToAsciiDoc opts (Note [Plain inlines]) = do
+  contents  <- inlineListToAsciiDoc opts inlines
+  return $ text "footnote:[" <> contents <> "]"
+-- asciidoc can't handle blank lines in notes
+inlineToAsciiDoc _ (Note _) = return "[multiblock footnote omitted]"
+inlineToAsciiDoc opts (Span (ident,classes,_) ils) = do
+  contents <- inlineListToAsciiDoc opts ils
+  isIntraword <- gets intraword
+  let marker = if isIntraword then "##" else "#"
+  case classes of
+    [] | T.null ident -> return contents
+    ["mark"] | T.null ident -> return $ marker <> contents <> marker
+    _ -> do
+       let modifier = brackets $ literal $ T.unwords $
+            [ "#" <> ident | not (T.null ident)] ++ map ("." <>) classes
+       return $ modifier <> marker <> contents <> marker
+
+-- | Provides the arguments for both `image:` and `image::`
+-- e.g.: sunset.jpg[Sunset,300,200]
+imageArguments :: PandocMonad m => WriterOptions ->
+  Attr -> [Inline] -> Text -> Text ->
+  ADW m (Doc Text)
+imageArguments opts attr altText src title = do
+  let txt = if null altText || (altText == [Str ""])
+               then [Str . T.pack . dropExtension $ T.unpack src]
+               else altText
   linktext <- inlineListToAsciiDoc opts txt
-  let linktitle = if null tit
+  let linktitle = if T.null title
                      then empty
-                     else ",title=\"" <> text tit <> "\""
+                     else ",title=\"" <> literal title <> "\""
       showDim dir = case dimension dir attr of
                       Just (Percent a) ->
                         ["scaledwidth=" <> text (show (Percent a))]
                       Just dim         ->
-                        [text (show dir) <> "=" <> text (showInPixel opts dim)]
+                        [text (show dir) <> "=" <>
+                          literal (showInPixel opts dim)]
                       Nothing          ->
                         []
       dimList = showDim Width ++ showDim Height
       dims = if null dimList
                 then empty
-                else "," <> cat (intersperse "," dimList)
-  return $ "image:" <> text src <> "[" <> linktext <> linktitle <> dims <> "]"
-inlineToAsciiDoc opts (Note [Para inlines]) =
-  inlineToAsciiDoc opts (Note [Plain inlines])
-inlineToAsciiDoc opts (Note [Plain inlines]) = do
-  contents  <- inlineListToAsciiDoc opts inlines
-  return $ text "footnote:[" <> contents <> "]"
--- asciidoc can't handle blank lines in notes
-inlineToAsciiDoc _ (Note _) = return "[multiblock footnote omitted]"
-inlineToAsciiDoc opts (Span (ident,_,_) ils) = do
-  let identifier = if null ident then empty else ("[[" <> text ident <> "]]")
-  contents <- inlineListToAsciiDoc opts ils
-  return $ identifier <> contents
+                else "," <> mconcat (intersperse "," dimList)
+  return $ literal src <> "[" <> linktext <> linktitle <> dims <> "]"
+
+-- | Adjust header rows for the fact that AsciiDoc only supports a single header row.
+--
+-- The first header row will become the single header row in AsciiDoc with the
+-- other rows becoming the top body rows.
+-- All cells of the first header row with a RowSpan > 1 will be mapped to
+-- RowSpan 1 and the remaining RowSpans of those cells wll be added as empty
+-- columns into the second row beneath them to preserve the original layout.
+adjustHeaders :: [Row] -> [Row]
+adjustHeaders [] = []
+adjustHeaders [row] = [row]
+adjustHeaders (Row attr firstHeaderCells:secondRow:remainingRows) =
+  let ((_, emptyHeaderCells), headerRow) = mapAccumL adjustHeaderRowCell (0, []) firstHeaderCells
+      secondRow' = applyEmptyCells secondRow emptyHeaderCells
+  in  Row attr headerRow:secondRow':remainingRows
+ where
+  adjustHeaderRowCell (columnPosition, emptyCells) cell@(Cell cellAttr alignment (RowSpan rowSpan) (ColSpan colSpan) blocks) =
+    let nextColumnPosition = columnPosition + colSpan
+        adjustedHeaderCell = Cell cellAttr alignment (RowSpan 1) (ColSpan colSpan) blocks
+        emptyHeaderRowCell = Cell nullAttr AlignDefault (RowSpan rowSpan - 1) (ColSpan colSpan) []
+        emptyCellPosition = (columnPosition, emptyHeaderRowCell)
+    in  if rowSpan > 1
+          then ((nextColumnPosition, emptyCellPosition:emptyCells), adjustedHeaderCell)
+          else ((nextColumnPosition, emptyCells), cell)
+
+-- | Adjust footer rows for the fact that AsciiDoc only supports a single footer row.
+--
+-- The last footer row will become the single footer row in AsciiDoc with the
+-- previous footer rows becoming the bottom body rows.
+-- All column indices of cells whose RowSpans would reach that last footer row
+-- are collected and subtracted by 1. Those collected column indices will then
+-- be applied as empty columns into the last footer row to preserve the original
+-- layout.
+adjustFooters :: [Row] -> [Row]
+adjustFooters [] = []
+adjustFooters [row] = [row]
+adjustFooters rows = adjustFooters' [] (0, length rows) M.empty rows
+ where
+  adjustFooters' _ _ _ [] = []
+  adjustFooters' columnIndices _ _ [row] = [applyEmptyCells row columnIndices]
+  adjustFooters' columnIndices rowInfo@(rowIndex, footerLength) previousRowSpans (row:rest) =
+    -- Need to keep track of RowSpans from previous rows and how they occupy
+    -- space in rows beneath them to be able to apply the correct column
+    -- position of RowSpans that would reach the last footer row.
+    let (previousRowSpans', row', columnIndices') = adjustFooterRow rowInfo previousRowSpans row
+        rows' = adjustFooters' (columnIndices ++ columnIndices') (rowIndex + 1, footerLength) previousRowSpans' rest
+    in  row':rows'
+
+  adjustFooterRow rowInfo previousRowSpans (Row attr cells) =
+    let ((nextColumnPosition, previousRowSpans'), cells') = mapAccumL (adjustFooterCell rowInfo) (0, previousRowSpans) cells
+        (cells'', columnIndices) = unzip cells'
+
+        -- Apply row spans from a previous row that are next to the end of the
+        -- current row's cells to keep track of the correct column position.
+        previousRowSpans'' = decrementTrailingRowSpans nextColumnPosition previousRowSpans'
+    in  (previousRowSpans'', Row attr cells'', catMaybes columnIndices)
+
+-- | Adjust footer cell for the fact that AsciiDoc only supports a single footer row.
+--
+-- Collects cells whose RowSpan would reach to the last footer row and applies
+-- them as empty cells to that last footer row.
+adjustFooterCell :: (Int, Int) -> (Int, M.Map Int (RowSpan, ColSpan)) -> Cell -> ((Int, M.Map Int (RowSpan, ColSpan)), (Cell, Maybe (Int, Cell)))
+adjustFooterCell rowInfo@(rowIndex, footerLength) (columnPosition, previousSpans) cell@(Cell _ _ (RowSpan rowSpan) (ColSpan colSpan) _)
+  | Just (ColSpan previousColSpan, previousSpans') <- takePreviousSpansAtColumn columnPosition previousSpans =
+      -- Apply row span from a previous row that occupies this column to keep
+      -- track of the correct column position.
+      adjustFooterCell rowInfo (columnPosition + previousColSpan, previousSpans') cell
+  | rowSpan > 1 && rowIndex + rowSpan >= footerLength =
+      -- Adjust row span that would reach all the way to the last footer row and
+      -- keep track of that to apply it to the last footer row.
+      ((nextColumnPosition, previousRowSpans'), (decrementRowSpanInCell cell, Just (columnPosition, emptyCellWithColSpan)))
+  | otherwise = ((nextColumnPosition, previousRowSpans'), (cell, Nothing))
+ where
+  -- Keep track of this cell's RowSpan for the rows following it.
+  previousRowSpans' = insertCurrentSpansAtColumn columnPosition previousSpans (RowSpan rowSpan) (ColSpan colSpan)
+  nextColumnPosition = columnPosition + colSpan
+  emptyCellWithColSpan = Cell nullAttr AlignDefault (RowSpan 1) (ColSpan colSpan) []
+
+-- | Adjust empty rows for AsciiDoc.
+--
+-- An empty row without any cells decrements RowSpans that cover it and is
+-- removed by them to adjust for being unable to express empty rows with no
+-- cells in AsciiDoc.
+adjustEmptyRows :: [Row] -> [Row]
+adjustEmptyRows = adjustEmptyRows' . map applyInitialRowsLeft
+ where
+  adjustEmptyRows' [] = []
+  adjustEmptyRows' (row:rest)
+    | maxRowSpan' <- maxRowSpan row
+    , maxRowSpan' > 1 =
+        -- Consume empty rows within the row's span.
+        let followingRows = take (maxRowSpan' - 1) rest
+            rows = consumeEmptyRows (row :| []) followingRows
+            rest' = drop (length followingRows) rest
+        in  rowFromCellsWithRowsLeft (NonEmpty.head rows) : adjustEmptyRows' (NonEmpty.tail rows ++ rest')
+    | otherwise = rowFromCellsWithRowsLeft row : adjustEmptyRows' rest
+
+  rowFromCellsWithRowsLeft (attr, cellsWithRowsLeft) = Row attr $ map fst cellsWithRowsLeft
+  cellRowSpan (Cell _ _ (RowSpan rowSpan) _ _) = rowSpan
+
+  consumeEmptyRows rows [] = NonEmpty.reverse rows
+  consumeEmptyRows rows (followingRow:restRows) =
+    if null (snd followingRow) && any rowHasRowSpanAndRowsLeft rows
+      then consumeEmptyRows (fmap (subtractRowsLeft decrementRowSpanInCell) rows) restRows -- Consume empty row for RowSpan and remove it
+      else consumeEmptyRows (followingRow <| fmap (subtractRowsLeft id) rows) restRows
+
+  rowHasRowSpanAndRowsLeft (_, cells) = any cellHasRowSpanAndRowsLeft cells
+  cellHasRowSpanAndRowsLeft (cell, rowsLeft) = cellRowSpan cell > 1 && rowsLeft >= 1
+
+  subtractRowsLeft changeCell (attr, cells) = (attr, map (subtractRowsLeftCell changeCell) cells)
+
+  subtractRowsLeftCell changeCell cellPair@(cell, rowsLeft)
+    | rowsLeft >= 1 = (changeCell cell, rowsLeft - 1)
+    | otherwise = cellPair
+
+  applyInitialRowsLeft (Row attr cells) = (attr, map applyInitialRowsLeftCell cells)
+
+  applyInitialRowsLeftCell cell
+    | rowSpan <- cellRowSpan cell, rowSpan > 1 = (cell, rowSpan - 1) -- Minus its own row
+    | otherwise = (cell, 0)
+
+  maxRowSpan (_, []) = 0
+  maxRowSpan (_, cells) = maximum $ map (cellRowSpan . fst) cells
+
+-- | Decrement the RowSpan of a Cell if that RowSpan > 1.
+decrementRowSpanInCell :: Cell -> Cell
+decrementRowSpanInCell cell@(Cell attr alignment (RowSpan rowSpan) colSpan blocks) =
+  if rowSpan > 1
+    then Cell attr alignment (RowSpan rowSpan - 1) colSpan blocks
+    else cell
+
+-- | Apply empty table cells at the given positions inside a Row.
+applyEmptyCells :: Row -> [(Int, Cell)] -> Row
+applyEmptyCells (Row attr cells) = Row attr . applyEmptyCells' 0 cells . sortOn fst
+ where
+  applyEmptyCells' _  cells' [] = cells'
+  applyEmptyCells' currentPosition cells' ((columnPosition, columnEmptyCell@(Cell _ _ _ (ColSpan colSpan) _)):rest)
+    | columnPosition == currentPosition = columnEmptyCell : applyEmptyCells' (currentPosition + colSpan) cells' rest
+  applyEmptyCells' _ [] _ = []
+  applyEmptyCells' currentPosition (cell@(Cell _ _ _ (ColSpan currentCellColSpan) _):restCells) emptyCellList =
+    cell : applyEmptyCells' (currentPosition + currentCellColSpan) restCells emptyCellList
diff --git a/src/Text/Pandoc/Writers/BBCode.hs b/src/Text/Pandoc/Writers/BBCode.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Writers/BBCode.hs
@@ -0,0 +1,1089 @@
+{-# LANGUAGE LambdaCase #-}
+{-# LANGUAGE OverloadedStrings #-}
+{-# LANGUAGE RankNTypes #-}
+{-# LANGUAGE Strict #-}
+{-# LANGUAGE TypeApplications #-}
+{- |
+   Module      : Text.Pandoc.Writers.BBCode
+   Copyright   : © 2025 Aleksey Myshko <git@crii.xyz>
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : Aleksey Myshko <git@crii.xyz>
+   Stability   : alpha
+   Portability : portable
+
+Conversion of 'Pandoc' documents to various BBCode flavors.
+-}
+
+module Text.Pandoc.Writers.BBCode (
+  -- * Predefined writers
+  -- Writers for different flavors of BBCode. 'writeBBCode' is a synonym for
+  -- 'writeBBCode_official'
+  writeBBCode,
+  writeBBCodeOfficial,
+  writeBBCodeSteam,
+  writeBBCodePhpBB,
+  writeBBCodeFluxBB,
+  writeBBCodeHubzilla,
+  writeBBCodeXenforo,
+
+  -- * Extending the writer
+  -- $extending
+  FlavorSpec (..),
+  WriterState (..),
+  RR,
+  writeBBCodeCustom,
+  inlineToBBCode,
+  inlineListToBBCode,
+  blockToBBCode,
+  blockListToBBCode,
+
+  -- ** Handling attributes
+  -- $wrapping_spans_divs
+  attrToMap,
+
+  -- * Predefined flavor specifications
+  officialSpec,
+  steamSpec,
+  phpbbSpec,
+  fluxbbSpec,
+  hubzillaSpec,
+  xenforoSpec,
+) where
+
+import Control.Applicative (some)
+import Control.Monad (forM)
+import Control.Monad.Reader (MonadReader (..), ReaderT (..), asks)
+import Control.Monad.State (MonadState (..), StateT, evalStateT, gets, modify)
+import Data.Default (Default (..))
+import Data.Either (isRight)
+import Data.Foldable (toList)
+import Data.Map.Strict (Map)
+import qualified Data.Map.Strict as Map
+import Data.Maybe (fromMaybe, isJust)
+import Data.Sequence (Seq, (|>))
+import qualified Data.Sequence as Seq
+import Data.Text (Text)
+import qualified Data.Text as T
+import Text.DocLayout hiding (char, link, text)
+import Text.Pandoc.Class.PandocMonad (PandocMonad, report)
+import Text.Pandoc.Definition
+import Text.Pandoc.Logging (LogMessage (..))
+import Text.Pandoc.Options (WriterOptions (..))
+import Text.Pandoc.Parsing (char, digit, eof, readWith)
+import Text.Pandoc.Shared (inquotes, onlySimpleTableCells, removeFormatting, trim, tshow)
+import Text.Pandoc.Templates (renderTemplate)
+import Text.Pandoc.URI (escapeURI)
+import Text.Pandoc.Writers.Shared (defField, metaToContext, toLegacyTable, unsmartify)
+import Text.Read (readMaybe)
+
+-- Type synonym to prevent haddock-generated HTML from overflowing
+type PandocTable =
+  (Attr, Caption, [ColSpec], TableHead, [TableBody], TableFoot)
+
+-- $extending
+-- If you want to support more Pandoc elements (or render some of them
+-- differently) you can do so by creating your own 'FlavorSpec'
+--
+-- The module exports the @'FlavorSpec'@s underlying @writeBBCode_*@ functions,
+-- namely 'officialSpec', 'steamSpec', 'phpbbSpec', 'fluxbbSpec',
+-- 'hubzillaSpec'.
+--
+-- You can create and use your own renderers, for instance here we define a
+-- renderer for 'CodeBlock' and use it to create a derivative format:
+--
+-- > renderCodeBlockCustom :: (PandocMonad m) => Attr -> Text -> RR m (Doc Text)
+-- > renderCodeBlockCustom (_, cls, _) code = do
+-- >   let opening = case cls of
+-- >         (lang : _) -> "[code=" <> lang <> "]"
+-- >         ("c++" : _) -> "[code=cpp]"
+-- >         _ -> "[code]"
+-- >   pure $ mconcat [literal opening, literal code, cr, "[/code]"]
+-- >
+-- > specCustom = officialSpec{renderCodeBlock = renderCodeBlockCustom}
+--
+-- Then we can use it to render 'Pandoc' document via 'writeBBCode_custom'
+
+{- | Data type that is a collection of renderers for most elements in a Pandoc
+AST (see 'Block' and 'Inline')
+
+The intention here is to allow inheritance between formats, for instance if
+format A and format @B@ differ only in rendering tables, @B@ can be implemented
+as @A{'renderTable' = renderTableB}@
+-}
+data FlavorSpec = FlavorSpec
+  { renderBlockQuote ::
+      forall m.
+      (PandocMonad m) =>
+      [Block] ->
+      RR m (Doc Text)
+  -- ^ Render 'BlockQuote'
+  , renderBulletList ::
+      forall m.
+      (PandocMonad m) =>
+      [[Block]] ->
+      RR m (Doc Text)
+  -- ^ Render 'BulletList'
+  , renderCodeBlock ::
+      forall m.
+      (PandocMonad m) =>
+      Attr ->
+      Text ->
+      RR m (Doc Text)
+  -- ^ Render 'CodeBlock'
+  , renderDefinitionList ::
+      forall m.
+      (PandocMonad m) =>
+      [([Inline], [[Block]])] ->
+      RR m (Doc Text)
+  -- ^ Render 'DefinitionList'
+  , renderHeader ::
+      forall m.
+      (PandocMonad m) =>
+      Int ->
+      Attr ->
+      [Inline] ->
+      RR m (Doc Text)
+  -- ^ Render 'Header'
+  , renderInlineCode ::
+      forall m.
+      (PandocMonad m) =>
+      Attr ->
+      Text ->
+      RR m (Doc Text)
+  -- ^ Render 'Code'
+  , renderLink ::
+      forall m.
+      (PandocMonad m) =>
+      Attr ->
+      [Inline] ->
+      Target ->
+      RR m (Doc Text)
+  -- ^ Render 'Link'
+  , renderOrderedList ::
+      forall m.
+      (PandocMonad m) =>
+      ListAttributes ->
+      [[Block]] ->
+      RR m (Doc Text)
+  -- ^ Render 'OrderedList'
+  , renderStrikeout ::
+      forall m.
+      (PandocMonad m) =>
+      [Inline] ->
+      RR m (Doc Text)
+  -- ^ Render 'Strikeout'
+  , renderTable :: forall m. (PandocMonad m) => PandocTable -> RR m (Doc Text)
+  -- ^ Render 'Table'
+  , renderHorizontalRule ::
+      forall m.
+      (PandocMonad m) =>
+      RR m (Doc Text)
+  -- ^ Render 'HorizontalRule'
+  , renderLineBlock ::
+      forall m.
+      (PandocMonad m) =>
+      [[Inline]] ->
+      RR m (Doc Text)
+  -- ^ Render 'LineBlock'
+  , renderPara ::
+      forall m.
+      (PandocMonad m) =>
+      [Inline] ->
+      RR m (Doc Text)
+  -- ^ Render 'Para'
+  , renderSuperscript ::
+      forall m.
+      (PandocMonad m) =>
+      [Inline] ->
+      RR m (Doc Text)
+  -- ^ Render 'Superscript'
+  , renderSubscript :: forall m. (PandocMonad m) => [Inline] -> RR m (Doc Text)
+  -- ^ Render 'Subscript'
+  , renderSmallCaps :: forall m. (PandocMonad m) => [Inline] -> RR m (Doc Text)
+  -- ^ Render 'SmallCaps'
+  , renderCite ::
+      forall m.
+      (PandocMonad m) =>
+      [Citation] ->
+      [Inline] ->
+      RR m (Doc Text)
+  -- ^ Render 'Cite'
+  , renderNote :: forall m. (PandocMonad m) => [Block] -> RR m (Doc Text)
+  -- ^ Render 'Note'
+  , renderFigure ::
+      forall m.
+      (PandocMonad m) =>
+      Attr ->
+      Caption ->
+      [Block] ->
+      RR m (Doc Text)
+  -- ^ Render 'Figure'
+  , renderQuoted ::
+      forall m.
+      (PandocMonad m) =>
+      QuoteType ->
+      [Inline] ->
+      RR m (Doc Text)
+  -- ^ Render 'Quoted'
+  , renderMath ::
+      forall m.
+      (PandocMonad m) =>
+      MathType ->
+      Text ->
+      RR m (Doc Text)
+  -- ^ Render 'Math'
+  , renderImage ::
+      forall m.
+      (PandocMonad m) =>
+      Attr ->
+      [Inline] ->
+      Target ->
+      RR m (Doc Text)
+  -- ^ Render 'Image'
+  , wrapSpanDiv :: Bool -> Map Text (Maybe Text) -> Doc Text -> Doc Text
+  -- ^ Wrap document in bbcode tags based on attributes/classes. Boolean flag
+  -- indicates whether passed argument is a Div or a Span (True means Div)
+  }
+
+data WriterState = WriterState
+  { writerOptions :: WriterOptions
+  , flavorSpec :: FlavorSpec
+  , inList :: Bool
+  }
+
+instance Default WriterState where
+  def =
+    WriterState
+      { writerOptions = def
+      , flavorSpec = officialSpec
+      , inList = False
+      }
+
+-- | The base of a renderer monad.
+type RR m a = StateT (Seq (Doc Text)) (ReaderT WriterState m) a
+
+pandocToBBCode :: (PandocMonad m) => Pandoc -> RR m Text
+pandocToBBCode (Pandoc meta body) = do
+  opts <- asks writerOptions
+  -- Run the rendering that mutates the state by producing footnotes
+  bodyContents <- blockListToBBCode body
+  -- Get the footnotes
+  footnotes <- get
+  -- Separate footnotes (if any) with a horizontal rule
+  footnotesSep <-
+    if null footnotes
+      then pure empty
+      else
+        (\hr -> blankline <> hr <> blankline)
+          <$> blockToBBCode HorizontalRule
+  -- Put footnotes after the main text
+  let docText = bodyContents <> footnotesSep <> vsep (toList footnotes)
+  metadata <- metaToContext opts blockListToBBCode inlineListToBBCode meta
+  let context = defField "body" docText metadata
+  case writerTemplate opts of
+    Just tpl -> pure $ render Nothing (renderTemplate tpl context)
+    Nothing -> pure $ render Nothing docText
+
+writeBBCode
+  , writeBBCodeOfficial
+  , writeBBCodeSteam
+  , writeBBCodePhpBB
+  , writeBBCodeFluxBB
+  , writeBBCodeHubzilla
+  , writeBBCodeXenforo ::
+    (PandocMonad m) => WriterOptions -> Pandoc -> m Text
+writeBBCode = writeBBCodeOfficial
+writeBBCodeOfficial = writeBBCodeCustom officialSpec
+writeBBCodeSteam = writeBBCodeCustom steamSpec
+writeBBCodePhpBB = writeBBCodeCustom phpbbSpec
+writeBBCodeFluxBB = writeBBCodeCustom fluxbbSpec
+writeBBCodeHubzilla = writeBBCodeCustom hubzillaSpec
+writeBBCodeXenforo = writeBBCodeCustom xenforoSpec
+
+{- | Convert a 'Pandoc' document to BBCode using the given 'FlavorSpec' and
+'WriterOptions'.
+-}
+writeBBCodeCustom ::
+  (PandocMonad m) => FlavorSpec -> WriterOptions -> Pandoc -> m Text
+writeBBCodeCustom spec opts document =
+  runRR mempty def{writerOptions = opts, flavorSpec = spec} $
+    pandocToBBCode document
+ where
+  runRR :: (Monad m) => Seq (Doc Text) -> WriterState -> RR m a -> m a
+  runRR footnotes writerState action =
+    runReaderT (evalStateT action footnotes) writerState
+
+blockListToBBCode :: (PandocMonad m) => [Block] -> RR m (Doc Text)
+blockListToBBCode blocks =
+  chomp . vsep . filter (not . null)
+    <$> mapM blockToBBCode blocks
+
+blockToBBCode :: (PandocMonad m) => Block -> RR m (Doc Text)
+blockToBBCode block = do
+  spec <- asks flavorSpec
+  case block of
+    Plain inlines -> inlineListToBBCode inlines
+    Para inlines -> renderPara spec inlines
+    LineBlock inliness -> renderLineBlock spec inliness
+    CodeBlock attr code -> renderCodeBlock spec attr code
+    RawBlock format raw -> case format of
+      "bbcode" -> pure $ literal raw
+      _ -> "" <$ report (BlockNotRendered block)
+    BlockQuote blocks -> renderBlockQuote spec blocks
+    OrderedList attr items -> renderOrderedList spec attr items
+    BulletList items -> renderBulletList spec items
+    DefinitionList items -> renderDefinitionList spec items
+    Header level attr inlines -> renderHeader spec level attr inlines
+    HorizontalRule -> renderHorizontalRule spec
+    Table attr blkCapt specs thead tbody tfoot ->
+      renderTable spec (attr, blkCapt, specs, thead, tbody, tfoot)
+    Figure attr caption blocks -> renderFigure spec attr caption blocks
+    Div attr blocks -> do
+      contents <- blockListToBBCode blocks
+      let kvcMap = attrToMap attr
+      -- whether passed contents is a Div (Block) element
+      --                      vvvv
+      pure $ wrapSpanDiv spec True kvcMap contents
+
+inlineToBBCode :: (PandocMonad m) => Inline -> RR m (Doc Text)
+inlineToBBCode inline = do
+  spec <- asks flavorSpec
+  case inline of
+    Str str -> do
+      opts <- asks writerOptions
+      pure . literal $ unsmartify opts str
+    Emph inlines -> do
+      contents <- inlineListToBBCode inlines
+      pure $ mconcat ["[i]", contents, "[/i]"]
+    Underline inlines -> do
+      contents <- inlineListToBBCode inlines
+      pure $ mconcat ["[u]", contents, "[/u]"]
+    Strong inlines -> do
+      contents <- inlineListToBBCode inlines
+      pure $ mconcat ["[b]", contents, "[/b]"]
+    Strikeout inlines -> renderStrikeout spec inlines
+    Superscript inlines -> renderSuperscript spec inlines
+    Subscript inlines -> renderSubscript spec inlines
+    SmallCaps inlines -> renderSmallCaps spec inlines
+    Quoted typ inlines -> renderQuoted spec typ inlines
+    Cite cits inlines -> renderCite spec cits inlines
+    Code attr code -> renderInlineCode spec attr code
+    Space -> pure space
+    SoftBreak -> pure space
+    LineBreak -> pure cr
+    Math typ math -> renderMath spec typ math
+    RawInline (Format format) text -> case format of
+      "bbcode" -> pure $ literal text
+      _ -> "" <$ report (InlineNotRendered inline)
+    Link attr txt target -> renderLink spec attr txt target
+    Image attr alt target -> renderImage spec attr alt target
+    Note blocks -> renderNote spec blocks
+    Span attr inlines -> do
+      contents <- inlineListToBBCode inlines
+      let kvcMap = attrToMap attr
+      -- whether passed contents is a Div (Block element)
+      --                      vvvvv
+      pure $ wrapSpanDiv spec False kvcMap contents
+
+renderImageDefault ::
+  (PandocMonad m) => Attr -> [Inline] -> Target -> RR m (Doc Text)
+renderImageDefault (_, _, kvList) alt (source, title) = do
+  altText <-
+    trim . render Nothing
+      <$> inlineListToBBCode (removeFormatting alt)
+  let kvMap = Map.fromList kvList
+  -- No BBCode flavor supported by the Writer has local images support, but we
+  -- still allow source to be plain path or anything else
+  pure . literal $
+    mconcat
+      [ "[img"
+      , if T.null altText
+          then ""
+          else " alt=" <> inquotes altText
+      , if T.null title
+          then ""
+          else " title=" <> inquotes title
+      , case Map.lookup "width" kvMap of
+          Just w
+            | isJust (readMaybe @Int $ T.unpack w) ->
+                " width=" <> inquotes w
+          _ -> ""
+      , case Map.lookup "height" kvMap of
+          Just h
+            | isJust (readMaybe @Int $ T.unpack h) ->
+                " height=" <> inquotes h
+          _ -> ""
+      , "]"
+      , source
+      , "[/img]"
+      ]
+
+renderImageOmit ::
+  (PandocMonad m) => Attr -> [Inline] -> Target -> RR m (Doc Text)
+renderImageOmit _ _ _ = pure ""
+
+{- | Basic phpBB doesn't support any attributes, although
+@[img src=https://example.com]whatever[/img]@ is supported, but text in tag has
+no effect
+-}
+renderImagePhpBB ::
+  (PandocMonad m) => Attr -> [Inline] -> Target -> RR m (Doc Text)
+renderImagePhpBB _ _ (source, _) =
+  pure . literal $ mconcat ["[img]", source, "[/img]"]
+
+renderImageXenforo ::
+  (PandocMonad m) => Attr -> [Inline] -> Target -> RR m (Doc Text)
+renderImageXenforo (_, _, kvList) alt (source, title) = do
+  altText <-
+    trim . render Nothing
+      <$> inlineListToBBCode (removeFormatting alt)
+  let kvMap = Map.fromList kvList
+  -- No BBCode flavor supported by the Writer has local images support, but we
+  -- still allow source to be plain path or anything else
+  pure . literal $
+    mconcat
+      [ "[img"
+      , if T.null altText
+          then ""
+          else " alt=" <> inquotes altText
+      , if T.null title
+          then ""
+          else " title=" <> inquotes title
+      , case Map.lookup "width" kvMap of
+          Just w
+            | isRight (readWith sizeP Nothing w) ->
+                " width=" <> w
+          _ -> ""
+      , "]"
+      , source
+      , "[/img]"
+      ]
+ where
+  sizeP = some digit >> char '%' >> eof
+
+{- | Check whether character is a bracket
+
+>>> T.filter notBracket "[a]b[[ó]qü]]n®"
+"ab\243q\252n\174"
+-}
+notBracket :: Char -> Bool
+notBracket = \case
+  '[' -> False
+  ']' -> False
+  _ -> True
+
+-- FluxBB uses [img=alt text] instead of [img alt="alt text"]
+renderImageFluxBB ::
+  (PandocMonad m) => Attr -> [Inline] -> Target -> RR m (Doc Text)
+renderImageFluxBB _ alt (source, _) = do
+  alt' <- T.filter notBracket . render Nothing <$> inlineListToBBCode alt
+  pure . literal $
+    mconcat
+      [ "[img"
+      , if T.null alt'
+          then ""
+          else "=" <> alt'
+      , "]"
+      , source
+      , "[/img]"
+      ]
+
+inlineListToBBCode :: (PandocMonad m) => [Inline] -> RR m (Doc Text)
+inlineListToBBCode inlines = mconcat <$> mapM inlineToBBCode inlines
+
+-- Taken from Data.Ord
+clamp :: (Ord a) => (a, a) -> a -> a
+clamp (low, high) a = min high (max a low)
+
+renderHeaderDefault ::
+  (PandocMonad m) => Int -> Attr -> [Inline] -> RR m (Doc Text)
+renderHeaderDefault level _attr inlines =
+  case clamp (1, 4) level of
+    1 -> inlineToBBCode $ Underline [Strong inlines]
+    2 -> inlineToBBCode $ Strong inlines
+    3 -> inlineToBBCode $ Underline inlines
+    _ -> inlineListToBBCode inlines
+
+-- Adapted from Text.Pandoc.Writers.Org
+renderLinkDefault ::
+  (PandocMonad m) => Attr -> [Inline] -> Target -> RR m (Doc Text)
+renderLinkDefault _ txt (src, _) =
+  case txt of
+    [Str x]
+      | escapeURI x == src ->
+          pure $ "[url]" <> literal x <> "[/url]"
+    _ -> do
+      contents <- inlineListToBBCode txt
+      let suffix = if T.null src then "" else "=" <> src
+      pure $ "[url" <> literal suffix <> "]" <> contents <> "[/url]"
+
+renderCodeBlockDefault :: (PandocMonad m) => Attr -> Text -> RR m (Doc Text)
+renderCodeBlockDefault (_, cls, _) code = do
+  let opening = case cls of
+        (lang : _) -> "[code=" <> lang <> "]"
+        _ -> "[code]"
+  pure $ mconcat [literal opening, literal code, cr, "[/code]"]
+
+renderCodeBlockSimple :: (PandocMonad m) => Attr -> Text -> RR m (Doc Text)
+renderCodeBlockSimple _ code = do
+  pure $ mconcat [literal "[code]", literal code, cr, "[/code]"]
+
+renderInlineCodeLiteral :: (PandocMonad m) => Attr -> Text -> RR m (Doc Text)
+renderInlineCodeLiteral _ code = pure $ literal code
+
+renderInlineCodeNoParse :: (PandocMonad m) => Attr -> Text -> RR m (Doc Text)
+renderInlineCodeNoParse _ code =
+  pure $ mconcat [literal "[noparse]", literal code, "[/noparse]"]
+
+renderInlineCodeHubzilla :: (PandocMonad m) => Attr -> Text -> RR m (Doc Text)
+renderInlineCodeHubzilla _ code =
+  pure $ mconcat [literal "[code]", literal code, "[/code]"]
+
+renderInlineCodeXenforo :: (PandocMonad m) => Attr -> Text -> RR m (Doc Text)
+renderInlineCodeXenforo _ code =
+  pure $ mconcat [literal "[icode]", literal code, "[/icode]"]
+
+renderStrikeoutDefault :: (PandocMonad m) => [Inline] -> RR m (Doc Text)
+renderStrikeoutDefault inlines = do
+  contents <- inlineListToBBCode inlines
+  pure $ mconcat ["[s]", contents, "[/s]"]
+
+renderStrikeoutSteam :: (PandocMonad m) => [Inline] -> RR m (Doc Text)
+renderStrikeoutSteam inlines = do
+  contents <- inlineListToBBCode inlines
+  pure $ mconcat ["[strike]", contents, "[/strike]"]
+
+renderDefinitionListDefault ::
+  (PandocMonad m) => [([Inline], [[Block]])] -> RR m (Doc Text)
+renderDefinitionListDefault items = do
+  items' <- forM items $ \(term, definitions) -> do
+    term' <- inlineListToBBCode term
+    definitions' <- blockToBBCode (BulletList definitions)
+    pure $ term' $$ definitions'
+  pure $ vcat items'
+
+renderDefinitionListHubzilla ::
+  (PandocMonad m) => [([Inline], [[Block]])] -> RR m (Doc Text)
+renderDefinitionListHubzilla items = do
+  items' <- forM items $ \(term, definitions) -> do
+    term' <- inlineListToBBCode term
+    let term'' = "[*= " <> term' <> "]"
+    definitions' <- forM definitions blockListToBBCode
+    pure $ vcat (term'' : definitions')
+  pure $ vcat (literal "[dl terms=\"b\"]" : items' ++ [literal "[/dl]"])
+
+listWithTags ::
+  (PandocMonad m) =>
+  Text ->
+  Text ->
+  ([[Block]] -> RR m [Doc Text]) ->
+  [[Block]] ->
+  RR m (Doc Text)
+listWithTags open close renderItems items = do
+  contents <- local (\s -> s{inList = True}) (renderItems items)
+  pure $ vcat $ literal open : contents ++ [literal close]
+
+starListItems :: (PandocMonad m) => [[Block]] -> RR m [Doc Text]
+starListItems items = forM items $ \item -> do
+  item' <- blockListToBBCode item
+  pure $ literal "[*]" <> item'
+
+listStyleCode :: ListNumberStyle -> Maybe Text
+listStyleCode = \case
+  Decimal -> Just "1"
+  DefaultStyle -> Just "1"
+  LowerAlpha -> Just "a"
+  UpperAlpha -> Just "A"
+  LowerRoman -> Just "i"
+  UpperRoman -> Just "I"
+  Example -> Nothing
+
+renderBulletListOfficial :: (PandocMonad m) => [[Block]] -> RR m (Doc Text)
+renderBulletListOfficial = listWithTags "[list]" "[/list]" starListItems
+
+renderBulletListHubzilla :: (PandocMonad m) => [[Block]] -> RR m (Doc Text)
+renderBulletListHubzilla = listWithTags "[ul]" "[/ul]" starListItems
+
+renderOrderedListHubzilla ::
+  (PandocMonad m) => ListAttributes -> [[Block]] -> RR m (Doc Text)
+renderOrderedListHubzilla (_, style, _) = case style of
+  DefaultStyle -> listWithTags "[ol]" "[/ol]" starListItems
+  Example -> listWithTags "[ol]" "[/ol]" starListItems
+  _ -> listWithTags ("[list=" <> suffix <> "]") "[/list]" starListItems
+ where
+  suffix = fromMaybe "1" $ listStyleCode style
+
+renderOrderedListOfficial ::
+  (PandocMonad m) => ListAttributes -> [[Block]] -> RR m (Doc Text)
+renderOrderedListOfficial (_, style, _) = do
+  let suffix = maybe "" ("=" <>) (listStyleCode style)
+  listWithTags ("[list" <> suffix <> "]") "[/list]" starListItems
+
+renderOrderedListSteam ::
+  (PandocMonad m) => ListAttributes -> [[Block]] -> RR m (Doc Text)
+renderOrderedListSteam _ =
+  listWithTags "[olist]" "[/olist]" starListItems
+
+renderHeaderSteam ::
+  (PandocMonad m) => Int -> Attr -> [Inline] -> RR m (Doc Text)
+renderHeaderSteam level _ inlines = do
+  body <- inlineListToBBCode inlines
+  let capped = clamp (1, 3) level
+      open = "[h" <> tshow capped <> "]"
+      close = "[/h" <> tshow capped <> "]"
+  pure $ literal open <> body <> literal close
+
+renderHeaderHubzilla ::
+  (PandocMonad m) => Int -> Attr -> [Inline] -> RR m (Doc Text)
+renderHeaderHubzilla level _ inlines = do
+  body <- inlineListToBBCode inlines
+  let capped = clamp (1, 6) level
+      open = "[h" <> tshow capped <> "]"
+      close = "[/h" <> tshow capped <> "]"
+  pure $ literal open <> body <> literal close
+
+-- xenForo supports levels 1--3, but levels other than 1--3 become div with
+-- .bbHeading class which can be linked to.
+renderHeaderXenforo ::
+  (PandocMonad m) => Int -> Attr -> [Inline] -> RR m (Doc Text)
+renderHeaderXenforo level _ inlines = do
+  body <- inlineListToBBCode inlines
+  let capped = max 1 level
+      open = "[heading=" <> tshow capped <> "]"
+      close = "[/heading]"
+  pure $ literal open <> body <> literal close
+
+renderTableGeneric ::
+  (PandocMonad m) =>
+  Text ->
+  Text ->
+  Text ->
+  (Attr, Caption, [ColSpec], TableHead, [TableBody], TableFoot) ->
+  RR m (Doc Text)
+renderTableGeneric tableTag headerCellTag bodyCellTag table = do
+  caption' <- inlineListToBBCode caption
+  table' <-
+    if not simpleCells
+      then "" <$ report (BlockNotRendered tableBlock)
+      else do
+        headerDocs <-
+          if null headers
+            then pure []
+            else pure <$> renderTableRow headerCellTag headers
+        rowDocs <- mapM (renderTableRow bodyCellTag) rows
+        pure $ renderTable' headerDocs rowDocs
+  pure $ caption' $$ table'
+ where
+  (attr, blkCapt, specs, thead, tbody, tfoot) = table
+  (caption, _, _, headers, rows) = toLegacyTable blkCapt specs thead tbody tfoot
+  tableBlock = Table attr blkCapt specs thead tbody tfoot
+  simpleCells = onlySimpleTableCells (headers : rows)
+  renderTable' headerDocs rowDocs =
+    vcat
+      [ literal ("[" <> tableTag <> "]")
+      , vcat headerDocs
+      , vcat rowDocs
+      , literal ("[/" <> tableTag <> "]")
+      ]
+  renderCell cellTag cellDoc =
+    mconcat
+      [ literal ("[" <> cellTag <> "]")
+      , cellDoc
+      , literal ("[/" <> cellTag <> "]")
+      ]
+  renderTableRow cellTag cells = do
+    renderedCells <- mapM blockListToBBCode cells
+    let cellsDoc = mconcat $ map (renderCell cellTag) renderedCells
+    pure $ literal "[tr]" <> cellsDoc <> literal "[/tr]"
+
+renderTableDefault ::
+  (PandocMonad m) =>
+  ( Attr
+  , Caption
+  , [ColSpec]
+  , TableHead
+  , [TableBody]
+  , TableFoot
+  ) ->
+  RR m (Doc Text)
+renderTableDefault = renderTableGeneric "table" "th" "td"
+
+renderTableOmit ::
+  (PandocMonad m) =>
+  ( Attr
+  , Caption
+  , [ColSpec]
+  , TableHead
+  , [TableBody]
+  , TableFoot
+  ) ->
+  RR m (Doc Text)
+renderTableOmit (_, blkCapt, specs, thead, tbody, tfoot) = do
+  let (caption, _, _, _, _) = toLegacyTable blkCapt specs thead tbody tfoot
+  caption' <- inlineListToBBCode caption
+  pure $ caption' $$ "(TABLE)"
+
+-- $wrapping_spans_divs
+-- Consider attribute a key-value pair with a Just value, and respectively
+-- class is key-value pair with Nothing value.
+-- For instance, given @("", ["cl1"], [("k", "v")]) :: 'Attr'@, respective Map
+-- should look like @'Map.fromList' [("cl1", 'Nothing'), ("k", 'Just' "v")]@
+--
+-- This transformation is handled by 'attrToMap'
+--
+-- Example definition of a wrapSpanDiv:
+--
+-- > {-# LANGUAGE OverloadedStrings #-}
+-- > import Data.Map (Map)
+-- > import qualified Data.Map as Map
+-- > import Text.DocLayout
+-- > import Data.Text (Text)
+-- > import qualified Data.Text as T
+-- >
+-- > wrapSpanDivSteam :: Bool -> Map Text (Maybe Text) -> Doc Text -> Doc Text
+-- > wrapSpanDivSteam isDiv kvc doc = Map.foldrWithKey wrap doc kvc
+-- >  where
+-- >   wrap "spoiler" (Just _) acc | isDiv = "[spoiler]" <> acc <> "[/spoiler]"
+-- >   wrap "spoiler" Nothing acc | isDiv = "[spoiler]" <> acc <> "[/spoiler]"
+-- >   wrap _ _ acc = acc
+--
+-- To verify it works, wrap some text in unnamed spoiler
+--
+-- >>> render Nothing $ wrapSpanDivSteam True (attrToMap ("", ["spoiler"], [])) "I am text"
+-- "[spoiler]I am text[/spoiler]"
+
+{- | The goal of the transformation is to treat classes and key-value pairs
+uniformly.
+
+Class list becomes Map where all values are Nothing, and list of key-value
+pairs is converted to Map via 'Map.toList'. Both Maps are then merged.
+-}
+attrToMap :: Attr -> Map Text (Maybe Text)
+attrToMap (_, classes, kvList) =
+  Map.fromList kvList' `Map.union` Map.fromList classes'
+ where
+  kvList' = map (\(k, v) -> (k, Just v)) kvList
+  classes' = map (\k -> (k, Nothing)) classes
+
+wrapSpanDivOfficial :: Bool -> Map Text (Maybe Text) -> Doc Text -> Doc Text
+wrapSpanDivOfficial isDiv kvc doc = Map.foldrWithKey wrap doc kvc
+ where
+  wrap "left" Nothing acc | isDiv = "[left]" <> acc <> "[/left]"
+  wrap "center" Nothing acc | isDiv = "[center]" <> acc <> "[/center]"
+  wrap "right" Nothing acc | isDiv = "[right]" <> acc <> "[/right]"
+  wrap "spoiler" Nothing acc | isDiv = "[spoiler]" <> acc <> "[/spoiler]"
+  wrap "spoiler" (Just v) acc
+    | isDiv =
+        literal ("[spoiler=" <> T.filter notBracket v <> "]")
+          <> acc
+          <> "[/spoiler]"
+  wrap "size" (Just v) acc
+    | Just v' <- readMaybe @Int (T.unpack v)
+    , v' > 0 =
+        literal ("[size=" <> v <> "]") <> acc <> "[/size]"
+  wrap "color" (Just v) acc =
+    literal ("[color=" <> v <> "]") <> acc <> "[/color]"
+  wrap _ _ acc = acc
+
+wrapSpanDivSteam :: Bool -> Map Text (Maybe Text) -> Doc Text -> Doc Text
+wrapSpanDivSteam isDiv kvc doc = Map.foldrWithKey wrap doc kvc
+ where
+  wrap "spoiler" (Just _) acc | isDiv = "[spoiler]" <> acc <> "[/spoiler]"
+  wrap "spoiler" Nothing acc | isDiv = "[spoiler]" <> acc <> "[/spoiler]"
+  wrap _ _ acc = acc
+
+wrapSpanDivPhpBB :: Bool -> Map Text (Maybe Text) -> Doc Text -> Doc Text
+wrapSpanDivPhpBB _ kvc doc = Map.foldrWithKey wrap doc kvc
+ where
+  wrap "color" (Just v) acc =
+    literal ("[color=" <> v <> "]") <> acc <> "[/color]"
+  wrap _ _ acc = acc
+
+wrapSpanDivFluxBB :: Bool -> Map Text (Maybe Text) -> Doc Text -> Doc Text
+wrapSpanDivFluxBB _ kvc doc = Map.foldrWithKey wrap doc kvc
+ where
+  wrap "color" (Just v) acc =
+    literal ("[color=" <> v <> "]") <> acc <> "[/color]"
+  wrap _ _ acc = acc
+
+wrapSpanDivHubzilla :: Bool -> Map Text (Maybe Text) -> Doc Text -> Doc Text
+wrapSpanDivHubzilla isDiv kvc doc = Map.foldrWithKey wrap doc kvc
+ where
+  wrap "center" Nothing acc | isDiv = "[center]" <> acc <> "[/center]"
+  wrap "spoiler" Nothing acc | isDiv = "[spoiler]" <> acc <> "[/spoiler]"
+  wrap "spoiler" (Just v) acc
+    | isDiv =
+        literal ("[spoiler=" <> T.filter notBracket v <> "]")
+          <> acc
+          <> "[/spoiler]"
+  wrap "size" (Just v) acc
+    | Just v' <- readMaybe @Int (T.unpack v)
+    , v' > 0 =
+        literal ("[size=" <> v <> "]") <> acc <> "[/size]"
+  wrap "color" (Just v) acc =
+    literal ("[color=" <> v <> "]") <> acc <> "[/color]"
+  wrap "font" (Just v) acc = literal ("[font=" <> v <> "]") <> acc <> "[/font]"
+  wrap _ _ acc = acc
+
+wrapSpanDivXenforo :: Bool -> Map Text (Maybe Text) -> Doc Text -> Doc Text
+wrapSpanDivXenforo isDiv kvc doc = Map.foldrWithKey wrap doc kvc
+ where
+  wrap "left" Nothing acc | isDiv = "[left]" <> acc <> "[/left]"
+  wrap "center" Nothing acc | isDiv = "[center]" <> acc <> "[/center]"
+  wrap "right" Nothing acc | isDiv = "[right]" <> acc <> "[/right]"
+  wrap "spoiler" _ acc | not isDiv = "[ispoiler]" <> acc <> "[/ispoiler]"
+  wrap "spoiler" Nothing acc | isDiv = "[spoiler]" <> acc <> "[/spoiler]"
+  wrap "spoiler" (Just v) acc
+    | isDiv =
+        literal ("[spoiler=" <> T.filter notBracket v <> "]")
+          <> acc
+          <> "[/spoiler]"
+  wrap "size" (Just v) acc
+    | Just v' <- readMaybe @Int (T.unpack v)
+    , v' > 0 =
+        literal ("[size=" <> v <> "]") <> acc <> "[/size]"
+  wrap "color" (Just v) acc =
+    literal ("[color=" <> v <> "]") <> acc <> "[/color]"
+  wrap "font" (Just v) acc = literal ("[font=" <> v <> "]") <> acc <> "[/font]"
+  wrap _ _ acc = acc
+
+renderOrderedListFluxbb ::
+  (PandocMonad m) =>
+  ListAttributes ->
+  [[Block]] ->
+  RR m (Doc Text)
+renderOrderedListFluxbb (_, style, _) =
+  let suffix = case style of
+        LowerAlpha -> "=a"
+        UpperAlpha -> "=a"
+        _ -> "=1"
+   in listWithTags ("[list" <> suffix <> "]") "[/list]" starListItems
+
+renderOrderedListXenforo ::
+  (PandocMonad m) =>
+  ListAttributes ->
+  [[Block]] ->
+  RR m (Doc Text)
+renderOrderedListXenforo _ =
+  listWithTags "[list=1]" "[/list]" starListItems
+
+renderLinkEmailAware ::
+  (PandocMonad m) =>
+  Attr ->
+  [Inline] ->
+  Target ->
+  RR m (Doc Text)
+renderLinkEmailAware attr txt target@(src, _) = do
+  case T.stripPrefix "mailto:" src of
+    Just address -> do
+      linkText <- inlineListToBBCode txt
+      let isAutoEmail = case txt of
+            [Str x] -> x == address
+            _ -> False
+      pure $
+        if isAutoEmail
+          then literal "[email]" <> literal address <> "[/email]"
+          else literal ("[email=" <> address <> "]") <> linkText <> "[/email]"
+    Nothing -> renderLinkDefault attr txt target
+
+renderBlockQuoteDefault :: (PandocMonad m) => [Block] -> RR m (Doc Text)
+renderBlockQuoteDefault blocks = do
+  contents <- blockListToBBCode blocks
+  pure $ vcat ["[quote]", contents, "[/quote]"]
+
+renderBlockQuoteFluxBB :: (PandocMonad m) => [Block] -> RR m (Doc Text)
+renderBlockQuoteFluxBB blocks = do
+  contents <- blockListToBBCode blocks
+  isInList <- asks inList
+  if isInList
+    then "" <$ report (BlockNotRendered $ BlockQuote blocks)
+    else pure $ vcat ["[quote]", contents, "[/quote]"]
+
+renderHorizontalRuleDefault :: (PandocMonad m) => RR m (Doc Text)
+renderHorizontalRuleDefault = pure "* * *"
+
+renderHorizontalRuleHR :: (PandocMonad m) => RR m (Doc Text)
+renderHorizontalRuleHR = pure "[hr]"
+
+renderLineBlockDefault :: (PandocMonad m) => [[Inline]] -> RR m (Doc Text)
+renderLineBlockDefault inliness = vcat <$> mapM inlineListToBBCode inliness
+
+renderParaDefault :: (PandocMonad m) => [Inline] -> RR m (Doc Text)
+renderParaDefault inlines = inlineListToBBCode inlines
+
+renderSuperscriptDefault :: (PandocMonad m) => [Inline] -> RR m (Doc Text)
+renderSuperscriptDefault = inlineListToBBCode
+
+renderSubscriptDefault :: (PandocMonad m) => [Inline] -> RR m (Doc Text)
+renderSubscriptDefault = inlineListToBBCode
+
+renderSmallCapsDefault :: (PandocMonad m) => [Inline] -> RR m (Doc Text)
+renderSmallCapsDefault = inlineListToBBCode
+
+renderCiteDefault ::
+  (PandocMonad m) => [Citation] -> [Inline] -> RR m (Doc Text)
+renderCiteDefault _ = inlineListToBBCode
+
+renderNoteDefault :: (PandocMonad m) => [Block] -> RR m (Doc Text)
+renderNoteDefault blocks = do
+  -- NOTE: no BBCode flavor has native syntax for footnotes.
+  newN <- gets (succ . Seq.length)
+  contents <- blockListToBBCode blocks
+  let pointer = "(" <> tshow newN <> ")"
+  let contents' = literal pointer <> space <> contents
+  modify (|> contents')
+  pure $ literal pointer
+
+renderFigureDefault ::
+  (PandocMonad m) => Attr -> Caption -> [Block] -> RR m (Doc Text)
+renderFigureDefault _ (Caption _ caption) blocks = do
+  caption' <- blockListToBBCode caption
+  contents <- blockListToBBCode blocks
+  pure $ contents $$ caption'
+
+renderQuotedDefault ::
+  (PandocMonad m) => QuoteType -> [Inline] -> RR m (Doc Text)
+renderQuotedDefault typ inlines = do
+  let quote = case typ of SingleQuote -> "'"; DoubleQuote -> "\""
+  contents <- inlineListToBBCode inlines
+  pure $ mconcat [quote, contents, quote]
+
+renderMathDefault :: (PandocMonad m) => MathType -> Text -> RR m (Doc Text)
+renderMathDefault typ math = case typ of
+  InlineMath ->
+    inlineToBBCode $
+      Code ("", ["latex"], []) ("$" <> math <> "$")
+  DisplayMath ->
+    blockToBBCode $
+      CodeBlock ("", ["latex"], []) ("$$" <> math <> "$$")
+
+{- | Format documentation: <https://www.bbcode.org/reference.php>
+
+There is no such thing as «Official» bbcode format, nonetheless this spec
+implements what is described on bbcode.org, which is a reasonable base that can
+be extended/contracted as needed.
+-}
+officialSpec :: FlavorSpec
+officialSpec =
+  FlavorSpec
+    { renderOrderedList = renderOrderedListOfficial
+    , renderBulletList = renderBulletListOfficial
+    , renderDefinitionList = renderDefinitionListDefault
+    , renderHeader = renderHeaderDefault
+    , renderTable = renderTableDefault
+    , renderLink = renderLinkEmailAware
+    , renderCodeBlock = renderCodeBlockDefault
+    , renderInlineCode = renderInlineCodeLiteral
+    , renderStrikeout = renderStrikeoutDefault
+    , renderBlockQuote = renderBlockQuoteDefault
+    , renderHorizontalRule = renderHorizontalRuleDefault
+    , renderLineBlock = renderLineBlockDefault
+    , renderPara = renderParaDefault
+    , renderSuperscript = renderSuperscriptDefault
+    , renderSubscript = renderSubscriptDefault
+    , renderSmallCaps = renderSmallCapsDefault
+    , renderCite = renderCiteDefault
+    , renderNote = renderNoteDefault
+    , renderFigure = renderFigureDefault
+    , renderMath = renderMathDefault
+    , renderQuoted = renderQuotedDefault
+    , renderImage = renderImageDefault
+    , wrapSpanDiv = wrapSpanDivOfficial
+    }
+
+{- | Format documentation: <https://steamcommunity.com/comment/ForumTopic/formattinghelp>
+
+Used at: <https://steamcommunity.com/discussions/forum>
+
+Quirks:
+
+- There seems to be no way to show external images on steam.
+  https://steamcommunity.com/sharedfiles/filedetails/?id=2807121939 shows [img]
+  and [previewimg] can (could?) be used to show images, although it is likely
+  reserved for steam urls only.
+-}
+steamSpec :: FlavorSpec
+steamSpec =
+  officialSpec
+    { renderOrderedList = renderOrderedListSteam
+    , renderHeader = renderHeaderSteam
+    , renderLink = renderLinkDefault
+    , renderInlineCode = renderInlineCodeNoParse
+    , renderStrikeout = renderStrikeoutSteam
+    , renderImage = renderImageOmit
+    , wrapSpanDiv = wrapSpanDivSteam
+    , renderHorizontalRule = renderHorizontalRuleHR
+    }
+
+{- | Format documentation: <https://www.phpbb.com/community/help/bbcode>
+
+Used at: <https://www.phpbb.com/community>
+
+Quirks:
+
+- PhpBB docs don't mention strikeout support, but their
+  [support forum](https://www.phpbb.com/community) does support it.
+- Same for named code blocks.
+- @[email=example\@example.com]the email[/url]@ is a valid use of [email]
+  tag on the phpBB community forum despite not being in the docs.
+-}
+phpbbSpec :: FlavorSpec
+phpbbSpec =
+  officialSpec
+    { renderTable = renderTableOmit
+    , renderImage = renderImagePhpBB
+    , wrapSpanDiv = wrapSpanDivPhpBB
+    }
+
+{- | Format documentation: <https://web.archive.org/web/20210623155046/https://fluxbb.org/forums/help.php#bbcode>
+
+Used at: https://bbs.archlinux.org
+-}
+fluxbbSpec :: FlavorSpec
+fluxbbSpec =
+  officialSpec
+    { renderOrderedList = renderOrderedListFluxbb
+    , renderCodeBlock = renderCodeBlockSimple
+    , renderTable = renderTableOmit
+    , renderBlockQuote = renderBlockQuoteFluxBB
+    , renderImage = renderImageFluxBB
+    , wrapSpanDiv = wrapSpanDivFluxBB
+    }
+
+{- | Format documentation: <https://hubzilla.org/help/member/bbcode>
+
+Used at: <https://hub.netzgemeinde.eu> (see [other hubs](https://hubzilla.org/pubsites))
+
+Quirks:
+
+- If link target is not a URI, it simply points to https://$BASEURL/ when
+  rendered by a hub.
+-}
+hubzillaSpec :: FlavorSpec
+hubzillaSpec =
+  officialSpec
+    { renderOrderedList = renderOrderedListHubzilla
+    , renderBulletList = renderBulletListHubzilla
+    , renderDefinitionList = renderDefinitionListHubzilla
+    , renderHeader = renderHeaderHubzilla
+    , renderInlineCode = renderInlineCodeHubzilla
+    , renderLink = renderLinkDefault
+    , wrapSpanDiv = wrapSpanDivHubzilla
+    , renderHorizontalRule = renderHorizontalRuleHR
+    }
+
+{- | Format documentation: <https://www.xenfocus.com/community/help/bb-codes/>
+
+Used at: see <https://xenforo.com/>
+-}
+xenforoSpec :: FlavorSpec
+xenforoSpec =
+  officialSpec
+    { wrapSpanDiv = wrapSpanDivXenforo
+    , renderHeader = renderHeaderXenforo
+    , renderInlineCode = renderInlineCodeXenforo
+    , renderHorizontalRule = renderHorizontalRuleHR
+    , renderOrderedList = renderOrderedListXenforo
+    , renderImage = renderImageXenforo
+    }
diff --git a/src/Text/Pandoc/Writers/BibTeX.hs b/src/Text/Pandoc/Writers/BibTeX.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Writers/BibTeX.hs
@@ -0,0 +1,59 @@
+{-# LANGUAGE OverloadedStrings #-}
+{- |
+   Module      : Text.Pandoc.Writers.BibTeX
+   Copyright   : Copyright (C) 2021-2024 John MacFarlane
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : John MacFarlane <jgm@berkeley.edu>
+   Stability   : alpha
+   Portability : portable
+
+Writes a BibTeX or BibLaTeX bibliographies based on the
+'references' metadata in a Pandoc document.
+-}
+module Text.Pandoc.Writers.BibTeX
+  ( writeBibTeX
+  , writeBibLaTeX
+  )
+where
+
+import Text.Pandoc.Options
+import Text.Pandoc.Definition
+import Data.Text (Text)
+import Data.Maybe (mapMaybe)
+import Citeproc (parseLang)
+import Text.Pandoc.Class (PandocMonad)
+import Text.Pandoc.Citeproc.BibTeX as BibTeX
+import Text.Pandoc.Citeproc.MetaValue (metaValueToReference)
+import Text.Pandoc.Writers.Shared (lookupMetaString, defField,
+                                    addVariablesToContext)
+import Text.DocLayout (render, vcat)
+import Text.DocTemplates (Context(..))
+import Text.Pandoc.Templates (renderTemplate)
+
+-- | Write BibTeX based on the references metadata from a Pandoc document.
+writeBibTeX :: PandocMonad m => WriterOptions -> Pandoc -> m Text
+writeBibTeX = writeBibTeX' BibTeX.Bibtex
+
+-- | Write BibLaTeX based on the references metadata from a Pandoc document.
+writeBibLaTeX :: PandocMonad m => WriterOptions -> Pandoc -> m Text
+writeBibLaTeX = writeBibTeX' BibTeX.Biblatex
+
+writeBibTeX' :: PandocMonad m => Variant -> WriterOptions -> Pandoc -> m Text
+writeBibTeX' variant opts (Pandoc meta _) = do
+  let mblang = case lookupMetaString "lang" meta of
+                 "" -> Nothing
+                 t  -> either (const Nothing) Just $ parseLang t
+  let refs = case lookupMeta "references" meta of
+               Just (MetaList xs) -> mapMaybe metaValueToReference xs
+               _ -> []
+  let main = vcat $ map (BibTeX.writeBibtexString opts variant mblang) refs
+  let context  = defField "body" main
+                 $ addVariablesToContext opts (mempty :: Context Text)
+  let colwidth = if writerWrapText opts == WrapAuto
+                    then Just $ writerColumns opts
+                    else Nothing
+  return $ render colwidth $
+    case writerTemplate opts of
+      Nothing  -> main
+      Just tpl -> renderTemplate tpl context
diff --git a/src/Text/Pandoc/Writers/Blaze.hs b/src/Text/Pandoc/Writers/Blaze.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Writers/Blaze.hs
@@ -0,0 +1,138 @@
+{-# LANGUAGE OverloadedStrings #-}
+{- |
+   Module      : Text.Pandoc.Writers.Blaze
+   Copyright   : Copyright (C) 2021-2024 John MacFarlane
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : John MacFarlane <jgm@berkeley.edu>
+   Stability   : alpha
+   Portability : portable
+
+Render blaze-html Html to DocLayout document (so it can be wrapped).
+-}
+module Text.Pandoc.Writers.Blaze ( layoutMarkup )
+where
+import Text.Blaze
+import qualified Data.ByteString as S
+import Data.List (isInfixOf)
+import Data.Text.Encoding (decodeUtf8)
+import qualified Data.Text as T
+import Data.Text (Text)
+import Text.DocLayout hiding (Text, Empty)
+import Text.Blaze.Internal (ChoiceString(..), getText, MarkupM(..))
+
+layoutMarkup :: Markup -> Doc T.Text
+layoutMarkup = go True mempty
+  where
+    go :: Bool -> Doc T.Text -> MarkupM b -> Doc T.Text
+    go wrap attrs (Parent _ open close content) =
+      let open' = getText open
+       in literal open'
+            <> attrs
+            <> char '>'
+            <> (case open' of
+                  "<code" -> go False mempty content
+                  t | t == "<pre" ||
+                      t == "<style" ||
+                      t == "<script" ||
+                      t == "<textarea" -> flush $ go False mempty content
+                    | otherwise -> go wrap mempty content)
+            <> literal (getText close)
+    go wrap attrs (CustomParent tag content) =
+        char '<'
+            <> fromChoiceString wrap tag
+            <> attrs
+            <> char '>'
+            <> go wrap mempty content
+            <> literal "</"
+            <> fromChoiceString wrap tag
+            <> char '>'
+    go _wrap attrs (Leaf _ begin end _) =
+        literal (getText begin)
+            <> attrs
+            <> literal (getText end)
+    go wrap attrs (CustomLeaf tag close _) =
+        char '<'
+            <> fromChoiceString wrap tag
+            <> attrs
+            <> (if close then literal " />" else char '>')
+    go wrap attrs (AddAttribute rawkey _ value h) =
+        go wrap
+          (space' wrap
+            <> literal (getText rawkey)
+            <> char '='
+            <> doubleQuotes (fromChoiceString False value)
+            <> attrs) h
+    go wrap attrs (AddCustomAttribute key value h) =
+        go wrap
+          (space' wrap
+            <> fromChoiceString wrap key
+            <> char '='
+            <> doubleQuotes (fromChoiceString False value)
+            <> attrs) h
+    go wrap _ (Content content _) = fromChoiceString wrap content
+    go wrap _ (Comment comment _) =
+        literal "<!--"
+            <> space' wrap
+            <> fromChoiceString False comment
+            <> space' wrap
+            <> "-->"
+    go wrap attrs (Append h1 h2) = go wrap attrs h1 <> go wrap attrs h2
+    go _ _ (Empty _) = mempty
+    space' wrap = if wrap then space else char ' '
+
+
+fromChoiceString :: Bool                  -- ^ Allow wrapping
+                 -> ChoiceString          -- ^ String to render
+                 -> Doc Text              -- ^ Resulting builder
+fromChoiceString wrap (Static s)     = withWrap wrap $ getText s
+fromChoiceString wrap (String s)     = withWrap wrap $
+                                         escapeMarkupEntities $ T.pack s
+fromChoiceString wrap (Text s)       = withWrap wrap $ escapeMarkupEntities s
+fromChoiceString wrap (ByteString s) = withWrap wrap $ decodeUtf8 s
+fromChoiceString _wrap (PreEscaped x) = -- don't wrap!
+  case x of
+    String s -> literal $ T.pack s
+    Text   s -> literal s
+    s        -> fromChoiceString False s
+fromChoiceString wrap (External x) = case x of
+    -- Check that the sequence "</" is *not* in the external data.
+    String s     -> if "</" `isInfixOf` s then mempty else withWrap wrap (T.pack s)
+    Text   s     -> if "</" `T.isInfixOf` s then mempty else withWrap wrap s
+    ByteString s -> if "</" `S.isInfixOf` s then mempty else withWrap wrap (decodeUtf8 s)
+    s            -> fromChoiceString wrap s
+fromChoiceString wrap (AppendChoiceString x y) =
+    fromChoiceString wrap x <> fromChoiceString wrap y
+fromChoiceString _ EmptyChoiceString = mempty
+
+withWrap :: Bool -> Text -> Doc Text
+withWrap wrap
+  | wrap = mconcat . toChunks
+  | otherwise = literal
+
+toChunks :: Text -> [Doc Text]
+toChunks = map toDoc . T.groupBy sameStatus
+  where
+   toDoc t
+     | t == " " = space
+     | t == "\n" = cr
+     | otherwise         = literal t
+   sameStatus c d =
+     (c == ' ' && d == ' ') ||
+     (c == '\n' && d == '\n') ||
+     (c /= ' ' && d /= ' ' && c /= '\n' && d /= '\n')
+
+
+-- | Escape predefined XML entities in a text value
+--
+escapeMarkupEntities :: Text     -- ^ Text to escape
+                     -> Text -- ^ Resulting Doc
+escapeMarkupEntities = T.concatMap escape
+  where
+    escape :: Char -> Text
+    escape '<'  = "&lt;"
+    escape '>'  = "&gt;"
+    escape '&'  = "&amp;"
+    escape '"'  = "&quot;"
+    escape '\'' = "&#39;"
+    escape x    = T.singleton x
diff --git a/src/Text/Pandoc/Writers/ChunkedHTML.hs b/src/Text/Pandoc/Writers/ChunkedHTML.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Writers/ChunkedHTML.hs
@@ -0,0 +1,173 @@
+{-# LANGUAGE OverloadedStrings   #-}
+{- |
+   Module      : Text.Pandoc.Writers.ChunkedHTML
+   Copyright   : Copyright (C) 2023 John MacFarlane
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : John MacFarlane <jgm@berkeley.edu>
+   Stability   : alpha
+   Portability : portable
+
+Conversion of 'Pandoc' documents to "chunked" HTML (a folder of
+linked HTML documents, split by sections.
+-}
+module Text.Pandoc.Writers.ChunkedHTML (
+  writeChunkedHTML
+  ) where
+import Text.Pandoc.Definition
+import Text.Pandoc.Options (WriterOptions(..))
+import Text.Pandoc.Shared (stringify, tshow)
+import Text.Pandoc.Class (PandocMonad, getPOSIXTime, runPure,
+                          fetchItem, insertMedia, getMediaBag)
+import Text.Pandoc.MediaBag (mediaItems)
+import qualified Data.ByteString.Lazy as BL
+import Text.Pandoc.Chunks (splitIntoChunks, Chunk(..), ChunkedDoc(..),
+                           SecInfo(..), tocToList)
+import Text.Pandoc.URI (isURI)
+import Data.Text (Text)
+import Data.Tree
+import qualified Data.Text as T
+import qualified Data.Text.Encoding as TE
+import Text.Pandoc.Writers.HTML (writeHtml5String)
+import Codec.Archive.Zip (Entry, addEntryToArchive, emptyArchive, toEntry,
+                          fromArchive)
+import qualified Data.Map as M
+import Text.DocTemplates (Context(..), Val(..))
+import Text.DocLayout (literal)
+import Text.Pandoc.Writers.Shared (defField)
+import Data.Aeson (toJSON, encode)
+import System.FilePath (isRelative, normalise)
+import Data.List (isInfixOf)
+import Text.Pandoc.Walk (walkM)
+import Text.Pandoc.Builder (setMeta)
+import Text.Pandoc.Templates (compileTemplate, WithDefaultPartials(..))
+import Control.Monad.Except (throwError)
+import Text.Pandoc.Error
+
+-- | Splits document into HTML chunks, dividing them by section,
+-- and returns a zip archive of a folder of files.
+writeChunkedHTML :: PandocMonad m
+                 => WriterOptions -> Pandoc -> m BL.ByteString
+writeChunkedHTML opts (Pandoc meta blocks) = do
+  walkM addMedia (Pandoc meta blocks)
+  epochtime <- floor <$> getPOSIXTime
+  let toMediaEntry (fp, _mt, bs) = toEntry fp epochtime bs
+  mediaEntries <- map toMediaEntry . mediaItems <$> getMediaBag
+  let chunkedDoc = splitIntoChunks (writerChunkTemplate opts)
+                     True
+                     (Just 1)
+                     (writerSplitLevel opts)
+                     (Pandoc meta blocks)
+  let topChunk =
+        Chunk
+          { chunkHeading = docTitle meta
+          , chunkId = "top"
+          , chunkLevel = 0
+          , chunkNumber = 0
+          , chunkSectionNumber = Nothing
+          , chunkPath = "index.html"
+          , chunkUp = Nothing
+          , chunkPrev = Nothing
+          , chunkNext = case chunkedChunks chunkedDoc of
+                          [] -> Nothing
+                          (x:_) -> Just x
+          , chunkUnlisted = True
+          , chunkContents = mempty
+          }
+
+  let chunks = map (\x -> case chunkUp x of
+                             Nothing -> x{ chunkUp = Just topChunk }
+                             _ -> x)
+               $ case chunkedChunks chunkedDoc of
+                   [] -> []
+                   (x:xs) -> x{ chunkPrev = Just topChunk } : xs
+
+  let Node secinfo secs = chunkedTOC chunkedDoc
+  let tocTree = Node secinfo{ secTitle = docTitle meta,
+                              secPath = "index.html" } secs
+  let tree = buildTOC opts tocTree
+  renderedTOC <- writeHtml5String opts{ writerTemplate = Nothing }
+                    (Pandoc nullMeta [tree])
+  -- see #8915 -- we need to set the math variable in the top chunk:
+  res <- runWithDefaultPartials $ compileTemplate "mathvar" "$math$"
+  mathVar <- case res of
+    Left e   -> throwError $ PandocTemplateError (T.pack e)
+    Right t  -> return t
+  tocMathVariable <- writeHtml5String opts{ writerTemplate = Just mathVar }
+                    (Pandoc meta (tree:blocks))
+  let opts' = opts{ writerVariables =
+                        defField "table-of-contents" renderedTOC
+                      . defField "math" tocMathVariable
+                      $ writerVariables opts }
+  entries <- mapM (chunkToEntry opts' meta topChunk) (topChunk : chunks)
+  let sitemap = toEntry "sitemap.json" epochtime
+                  (encode $ toJSON $ tocTreeToContext tocTree)
+  let archive = foldr addEntryToArchive emptyArchive
+                 (sitemap : entries ++ mediaEntries)
+  return $ fromArchive archive
+
+
+-- We include in the zip only local media that is in the working directory
+-- or below.
+addMedia :: PandocMonad m => Inline -> m Inline
+addMedia il@(Image _ _ (src,_))
+  | not (isURI src)
+  , fp <- normalise (T.unpack src)
+  , isRelative fp
+  , not (".." `isInfixOf` fp) = do
+  (bs, mbMime) <- fetchItem (T.pack fp)
+  insertMedia fp mbMime (BL.fromStrict bs)
+  return il
+addMedia il = return il
+
+buildTOC :: WriterOptions -> Tree SecInfo -> Block
+buildTOC opts = tocToList (writerNumberSections opts) (writerTOCDepth opts)
+
+chunkToEntry :: PandocMonad m
+             => WriterOptions -> Meta -> Chunk -> Chunk -> m Entry
+chunkToEntry opts meta topChunk chunk = do
+  html <- writeHtml5String opts' (Pandoc meta' blocks)
+  epochtime <- floor <$> getPOSIXTime
+  let htmlLBS = BL.fromStrict $ TE.encodeUtf8 html
+  return $ toEntry (chunkPath chunk) epochtime htmlLBS
+ where
+  opts' = opts{ writerVariables =
+                  addContextVars opts' topChunk chunk $ writerVariables opts }
+  meta' = setMeta "pagetitle" (MetaString (stringify $ chunkHeading chunk)) meta
+  blocks = chunkContents chunk
+
+tocTreeToContext :: Tree SecInfo -> Context Text
+tocTreeToContext (Node secinfo subs) =
+  Context $ M.fromList
+  [ ("section", MapVal $ secInfoToContext secinfo)
+  , ("subsections", ListVal $ map (MapVal . tocTreeToContext) subs)
+  ]
+
+secInfoToContext :: SecInfo -> Context Text
+secInfoToContext sec =
+  Context $ M.fromList
+  [ ("title", SimpleVal $ literal $ stringify $ secTitle sec)
+  , ("number", maybe NullVal (SimpleVal . literal) (secNumber sec))
+  , ("id", SimpleVal $ literal $ secId sec)
+  , ("path", SimpleVal $ literal $ secPath sec)
+  , ("level", SimpleVal $ literal $ tshow $ secLevel sec)
+  ]
+
+addContextVars
+  :: WriterOptions -> Chunk -> Chunk -> Context Text -> Context Text
+addContextVars opts topChunk chunk context =
+     maybe id (defField "next" . navlinks) (chunkNext chunk)
+   . maybe id (defField "previous" . navlinks) (chunkPrev chunk)
+   . maybe id (defField "up" . navlinks) (chunkUp chunk)
+   . maybe id (defField "top" . navlinks) (if chunk == topChunk
+                                              then Nothing
+                                              else Just topChunk)
+   . defField "toc" (chunk == topChunk && writerTableOfContents opts)
+    $ context
+ where
+  navlinks ch = toMapVal [("url", formatPath ch), ("title", formatHeading ch)]
+  toMapVal = MapVal . Context . M.fromList
+  formatPath = SimpleVal . literal . T.pack . chunkPath
+  formatHeading ch = SimpleVal . literal . either (const "") id . runPure $
+    writeHtml5String opts{ writerTemplate = Nothing }
+      (Pandoc nullMeta [Plain $ chunkHeading ch])
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,25 +1,6 @@
-{-# LANGUAGE OverloadedStrings #-}
-{-
-Copyright (C) 2015-2017 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-2017 John MacFarlane
+   Copyright   : Copyright (C) 2015-2024 John MacFarlane
    License     : GNU GPL, version 2 or above
 
    Maintainer  : John MacFarlane <jgm@berkeley.edu>
@@ -32,283 +13,4 @@
 -}
 module Text.Pandoc.Writers.CommonMark (writeCommonMark) where
 
-import CMarkGFM
-import Control.Monad.State.Strict (State, get, modify, runState)
-import Data.Foldable (foldrM)
-import Data.List (transpose)
-import Data.Monoid (Any (..), (<>))
-import Data.Text (Text)
-import qualified Data.Text as T
-import Network.HTTP (urlEncode)
-import Text.Pandoc.Class (PandocMonad)
-import Text.Pandoc.Definition
-import Text.Pandoc.Options
-import Text.Pandoc.Shared (isTightList, linesToPara, substitute)
-import Text.Pandoc.Templates (renderTemplate')
-import Text.Pandoc.Walk (query, walk, walkM)
-import Text.Pandoc.Writers.HTML (writeHtml5String, tagWithAttributes)
-import Text.Pandoc.Writers.Shared
-
--- | Convert Pandoc to CommonMark.
-writeCommonMark :: PandocMonad m => WriterOptions -> Pandoc -> m Text
-writeCommonMark opts (Pandoc meta blocks) = do
-  let (blocks', notes) = runState (walkM processNotes blocks) []
-      notes' = if null notes
-               then []
-               else [OrderedList (1, Decimal, Period) $ reverse notes]
-  main <-  blocksToCommonMark opts (blocks' ++ notes')
-  metadata <- metaToJSON opts
-              (blocksToCommonMark opts)
-              (inlinesToCommonMark opts)
-              meta
-  let context = defField "body" main metadata
-  case writerTemplate opts of
-       Nothing  -> return main
-       Just tpl -> renderTemplate' tpl context
-
-softBreakToSpace :: Inline -> Inline
-softBreakToSpace SoftBreak = Space
-softBreakToSpace x         = x
-
-processNotes :: Inline -> State [[Block]] Inline
-processNotes (Note bs) = do
-  modify (bs :)
-  notes <- get
-  return $ Str $ "[" ++ show (length notes) ++ "]"
-processNotes x = return x
-
-node :: NodeType -> [Node] -> Node
-node = Node Nothing
-
-blocksToCommonMark :: PandocMonad m => WriterOptions -> [Block] -> m Text
-blocksToCommonMark opts bs = do
-  let cmarkOpts = [optHardBreaks | isEnabled Ext_hard_line_breaks opts]
-      colwidth = if writerWrapText opts == WrapAuto
-                 then Just $ writerColumns opts
-                 else Nothing
-  nodes <- blocksToNodes opts bs
-  return $ T.stripEnd $
-    nodeToCommonmark cmarkOpts colwidth $
-    node DOCUMENT nodes
-
-inlinesToCommonMark :: PandocMonad m => WriterOptions -> [Inline] -> m Text
-inlinesToCommonMark opts ils = return $
-  nodeToCommonmark cmarkOpts colwidth $
-    node PARAGRAPH (inlinesToNodes opts ils)
-   where cmarkOpts = [optHardBreaks | isEnabled Ext_hard_line_breaks opts]
-         colwidth = if writerWrapText opts == WrapAuto
-                       then Just $ writerColumns opts
-                       else Nothing
-
-blocksToNodes :: PandocMonad m => WriterOptions -> [Block] -> m [Node]
-blocksToNodes opts = foldrM (blockToNodes opts) []
-
-blockToNodes :: PandocMonad m => WriterOptions -> Block -> [Node] -> m [Node]
-blockToNodes opts (Plain xs) ns =
-  return (node PARAGRAPH (inlinesToNodes opts xs) : ns)
-blockToNodes opts (Para xs) ns =
-  return (node PARAGRAPH (inlinesToNodes opts xs) : ns)
-blockToNodes opts (LineBlock lns) ns = blockToNodes opts (linesToPara lns) ns
-blockToNodes _ (CodeBlock (_,classes,_) xs) ns = return
-  (node (CODE_BLOCK (T.pack (unwords classes)) (T.pack xs)) [] : ns)
-blockToNodes opts (RawBlock fmt xs) ns
-  | fmt == Format "html" && isEnabled Ext_raw_html opts
-              = return (node (HTML_BLOCK (T.pack xs)) [] : ns)
-  | fmt == Format "latex" || fmt == Format "tex" && isEnabled Ext_raw_tex opts
-              = return (node (CUSTOM_BLOCK (T.pack xs) T.empty) [] : ns)
-  | otherwise = return ns
-blockToNodes opts (BlockQuote bs) ns = do
-  nodes <- blocksToNodes opts bs
-  return (node BLOCK_QUOTE nodes : ns)
-blockToNodes opts (BulletList items) ns = do
-  nodes <- mapM (blocksToNodes opts) items
-  return (node (LIST ListAttributes{
-                   listType = BULLET_LIST,
-                   listDelim = PERIOD_DELIM,
-                   listTight = isTightList items,
-                   listStart = 1 }) (map (node ITEM) nodes) : ns)
-blockToNodes opts (OrderedList (start, _sty, delim) items) ns = do
-  nodes <- mapM (blocksToNodes opts) items
-  return (node (LIST ListAttributes{
-                   listType = ORDERED_LIST,
-                   listDelim = case delim of
-                                 OneParen  -> PAREN_DELIM
-                                 TwoParens -> PAREN_DELIM
-                                 _         -> PERIOD_DELIM,
-                   listTight = isTightList items,
-                   listStart = start }) (map (node ITEM) nodes) : ns)
-blockToNodes _ HorizontalRule ns = return (node THEMATIC_BREAK [] : ns)
-blockToNodes opts (Header lev _ ils) ns =
-  return (node (HEADING lev) (inlinesToNodes opts ils) : ns)
-blockToNodes opts (Div attr bs) ns = do
-  nodes <- blocksToNodes opts bs
-  let op = tagWithAttributes opts True False "div" attr
-  if isEnabled Ext_raw_html opts
-     then return (node (HTML_BLOCK op) [] : nodes ++
-                  [node (HTML_BLOCK (T.pack "</div>")) []] ++ ns)
-     else return (nodes ++ ns)
-blockToNodes opts (DefinitionList items) ns =
-  blockToNodes opts (BulletList items') ns
-  where items' = map dlToBullet items
-        dlToBullet (term, (Para xs : ys) : zs)  =
-          Para (term ++ [LineBreak] ++ xs) : ys ++ concat zs
-        dlToBullet (term, (Plain xs : ys) : zs) =
-          Plain (term ++ [LineBreak] ++ xs) : ys ++ concat zs
-        dlToBullet (term, xs) =
-          Para term : concat xs
-blockToNodes opts t@(Table capt aligns _widths headers rows) ns = do
-  let allcells = concat (headers:rows)
-  let isLineBreak LineBreak = Any True
-      isLineBreak _         = Any False
-  let isPlainOrPara [Para _]  = True
-      isPlainOrPara [Plain _] = True
-      isPlainOrPara []        = True
-      isPlainOrPara _         = False
-  let isSimple = all isPlainOrPara allcells &&
-                 not ( getAny (query isLineBreak allcells) )
-  if isEnabled Ext_pipe_tables opts && isSimple
-     then do
-       -- We construct a table manually as a CUSTOM_BLOCK, for
-       -- two reasons:  (1) cmark-gfm currently doesn't support
-       -- rendering TABLE nodes; (2) we can align the column sides;
-       -- (3) we can render the caption as a regular paragraph.
-       let capt' = node PARAGRAPH (inlinesToNodes opts capt)
-       -- backslash | in code and raw:
-       let fixPipe (Code attr xs) =
-             Code attr (substitute "|" "\\|" xs)
-           fixPipe (RawInline format xs) =
-             RawInline format (substitute "|" "\\|" xs)
-           fixPipe x = x
-       let toCell [Plain ils] = T.strip
-                                $ nodeToCommonmark [] Nothing
-                                $ node (CUSTOM_INLINE mempty mempty)
-                                $ inlinesToNodes opts
-                                $ walk (fixPipe . softBreakToSpace) ils
-           toCell [Para  ils] = T.strip
-                                $ nodeToCommonmark [] Nothing
-                                $ node (CUSTOM_INLINE mempty mempty)
-                                $ inlinesToNodes opts
-                                $ walk (fixPipe . softBreakToSpace) ils
-           toCell []          = ""
-           toCell xs          = error $ "toCell encountered " ++ show xs
-       let separator = " | "
-       let starter = "| "
-       let ender   = " |"
-       let rawheaders = map toCell headers
-       let rawrows = map (map toCell) rows
-       let maximum' [] = 0
-           maximum' xs = maximum xs
-       let colwidths = map (maximum' . map T.length) $
-                        transpose (rawheaders:rawrows)
-       let toHeaderLine len AlignDefault = T.replicate len "-"
-           toHeaderLine len AlignLeft    = ":" <>
-                  T.replicate (max (len - 1) 1) "-"
-           toHeaderLine len AlignRight   =
-                  T.replicate (max (len - 1) 1) "-" <> ":"
-           toHeaderLine len AlignCenter  = ":" <>
-                  T.replicate (max (len - 2) 1) (T.pack "-") <> ":"
-       let rawheaderlines = zipWith toHeaderLine colwidths aligns
-       let headerlines = starter <> T.intercalate separator rawheaderlines <>
-                          ender
-       let padContent (align, w) t' =
-             let padding = w - T.length t'
-                 halfpadding = padding `div` 2
-             in  case align of
-                      AlignRight -> T.replicate padding " " <> t'
-                      AlignCenter -> T.replicate halfpadding " " <> t' <>
-                                     T.replicate (padding - halfpadding) " "
-                      _ -> t' <> T.replicate padding " "
-       let toRow xs = starter <> T.intercalate separator
-                      (zipWith padContent (zip aligns colwidths) xs) <>
-                      ender
-       let table' = toRow rawheaders <> "\n" <> headerlines <> "\n" <>
-                     T.intercalate "\n" (map toRow rawrows)
-       return (node (CUSTOM_BLOCK table' mempty) [] :
-               if null capt
-                  then ns
-                  else capt' : ns)
-     else do -- fall back to raw HTML
-       s <- writeHtml5String def $! Pandoc nullMeta [t]
-       return (node (HTML_BLOCK s) [] : ns)
-blockToNodes _ Null ns = return ns
-
-inlinesToNodes :: WriterOptions -> [Inline] -> [Node]
-inlinesToNodes opts  = foldr (inlineToNodes opts) []
-
-inlineToNodes :: WriterOptions -> Inline -> [Node] -> [Node]
-inlineToNodes opts (Str s) = (node (TEXT (T.pack s')) [] :)
-  where s' = if isEnabled Ext_smart opts
-                then unsmartify opts s
-                else s
-inlineToNodes _ Space   = (node (TEXT (T.pack " ")) [] :)
-inlineToNodes _ LineBreak = (node LINEBREAK [] :)
-inlineToNodes opts SoftBreak
-  | isEnabled Ext_hard_line_breaks opts = (node LINEBREAK [] :)
-  | writerWrapText opts == WrapNone     = (node (TEXT " ") [] :)
-  | otherwise                           = (node SOFTBREAK [] :)
-inlineToNodes opts (Emph xs) = (node EMPH (inlinesToNodes opts xs) :)
-inlineToNodes opts (Strong xs) = (node STRONG (inlinesToNodes opts xs) :)
-inlineToNodes opts (Strikeout xs) =
-  if isEnabled Ext_strikeout opts
-     then (node (CUSTOM_INLINE "~~" "~~") (inlinesToNodes opts xs) :)
-     else ((node (HTML_INLINE (T.pack "<s>")) [] : inlinesToNodes opts xs ++
-           [node (HTML_INLINE (T.pack "</s>")) []]) ++ )
-inlineToNodes opts (Superscript xs) =
-  ((node (HTML_INLINE (T.pack "<sup>")) [] : inlinesToNodes opts xs ++
-   [node (HTML_INLINE (T.pack "</sup>")) []]) ++ )
-inlineToNodes opts (Subscript xs) =
-  ((node (HTML_INLINE (T.pack "<sub>")) [] : inlinesToNodes opts xs ++
-   [node (HTML_INLINE (T.pack "</sub>")) []]) ++ )
-inlineToNodes opts (SmallCaps xs) =
-  ((node (HTML_INLINE (T.pack "<span class=\"smallcaps\">")) []
-    : inlinesToNodes opts xs ++
-    [node (HTML_INLINE (T.pack "</span>")) []]) ++ )
-inlineToNodes opts (Link _ ils (url,tit)) =
-  (node (LINK (T.pack url) (T.pack tit)) (inlinesToNodes opts ils) :)
--- title beginning with fig: indicates implicit figure
-inlineToNodes opts (Image alt ils (url,'f':'i':'g':':':tit)) =
-  inlineToNodes opts (Image alt ils (url,tit))
-inlineToNodes opts (Image _ ils (url,tit)) =
-  (node (IMAGE (T.pack url) (T.pack tit)) (inlinesToNodes opts ils) :)
-inlineToNodes opts (RawInline fmt xs)
-  | fmt == Format "html" && isEnabled Ext_raw_html opts
-              = (node (HTML_INLINE (T.pack xs)) [] :)
-  | (fmt == Format "latex" || fmt == Format "tex") && isEnabled Ext_raw_tex opts
-              = (node (CUSTOM_INLINE (T.pack xs) T.empty) [] :)
-  | otherwise = id
-inlineToNodes opts (Quoted qt ils) =
-  ((node (TEXT start) [] :
-   inlinesToNodes opts ils ++ [node (TEXT end) []]) ++)
-  where (start, end) = case qt of
-                          SingleQuote
-                            | isEnabled Ext_smart opts -> ("'","'")
-                            | otherwise -> ("‘", "’")
-                          DoubleQuote
-                            | isEnabled Ext_smart opts -> ("\"", "\"")
-                            | otherwise -> ("“", "”")
-inlineToNodes _ (Code _ str) = (node (CODE (T.pack str)) [] :)
-inlineToNodes opts (Math mt str) =
-  case writerHTMLMathMethod opts of
-       WebTeX url ->
-           let core = inlineToNodes opts
-                        (Image nullAttr [Str str] (url ++ urlEncode str, str))
-               sep = if mt == DisplayMath
-                        then (node LINEBREAK [] :)
-                        else id
-           in  (sep . core . sep)
-       _  ->
-           case mt of
-            InlineMath  ->
-              (node (HTML_INLINE (T.pack ("\\(" ++ str ++ "\\)"))) [] :)
-            DisplayMath ->
-              (node (HTML_INLINE (T.pack ("\\[" ++ str ++ "\\]"))) [] :)
-inlineToNodes opts (Span attr ils) =
-  let nodes = inlinesToNodes opts ils
-      op = tagWithAttributes opts True False "span" attr
-  in  if isEnabled Ext_raw_html opts
-         then ((node (HTML_INLINE op) [] : nodes ++
-                [node (HTML_INLINE (T.pack "</span>")) []]) ++)
-         else (nodes ++)
-inlineToNodes opts (Cite _ ils) = (inlinesToNodes opts ils ++)
-inlineToNodes _ (Note _) = id -- should not occur
--- we remove Note elements in preprocessing
+import Text.Pandoc.Writers.Markdown (writeCommonMark)
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,26 +1,10 @@
+{-# LANGUAGE LambdaCase          #-}
 {-# LANGUAGE OverloadedStrings   #-}
 {-# LANGUAGE ScopedTypeVariables #-}
-{-
-Copyright (C) 2007-2017 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 ViewPatterns        #-}
 {- |
    Module      : Text.Pandoc.Writers.ConTeXt
-   Copyright   : Copyright (C) 2007-2017 John MacFarlane
+   Copyright   : Copyright (C) 2007-2025 John MacFarlane
    License     : GNU GPL, version 2 or above
 
    Maintainer  : John MacFarlane <jgm@berkeley.edu>
@@ -30,41 +14,71 @@
 Conversion of 'Pandoc' format into ConTeXt.
 -}
 module Text.Pandoc.Writers.ConTeXt ( writeConTeXt ) where
+import Control.Monad (liftM, unless)
 import Control.Monad.State.Strict
+    ( StateT, MonadState(put, get), gets, modify, evalStateT )
 import Data.Char (ord, isDigit)
-import Data.List (intercalate, intersperse)
-import Data.Maybe (mapMaybe)
+import Data.List (intersperse)
+import Data.List.NonEmpty (NonEmpty ((:|)))
+import Data.Maybe (mapMaybe, catMaybes)
+import Data.Monoid (Any (Any, getAny))
 import Data.Text (Text)
+import qualified Data.Text as T
 import Network.URI (unEscapeString)
-import Text.Pandoc.BCP47
-import Text.Pandoc.Class (PandocMonad, report, toLang)
+import Text.Collate.Lang (Lang(..))
+import Text.Pandoc.Class.PandocMonad (PandocMonad, report, toLang)
 import Text.Pandoc.Definition
+import Text.Pandoc.Highlighting
+  (formatConTeXtBlock, formatConTeXtInline, highlight, styleToConTeXt)
 import Text.Pandoc.ImageSize
 import Text.Pandoc.Logging
 import Text.Pandoc.Options
-import Text.Pandoc.Pretty
+import Text.DocLayout
 import Text.Pandoc.Shared
-import Text.Pandoc.Templates (renderTemplate')
+import Text.Pandoc.URI (isURI)
+import Text.Pandoc.Templates (renderTemplate)
 import Text.Pandoc.Walk (query)
 import Text.Pandoc.Writers.Shared
 import Text.Printf (printf)
 
+import qualified Data.List.NonEmpty as NonEmpty
+import qualified Data.Map.Strict as Map
+import qualified Text.Pandoc.Writers.AnnotatedTable as Ann
+
 data WriterState =
-  WriterState { stNextRef          :: Int  -- number of next URL reference
-              , stOrderedListLevel :: Int  -- level of ordered list
-              , stOptions          :: WriterOptions -- writer options
-              }
+  WriterState
+  { stCslHangingIndent :: Bool -- CSL hanging indent
+  , stHasCslRefs       :: Bool -- has CSL citations
+  , stHighlighting     :: Bool -- has syntax-highlighted code blocks
+  , stNextRef          :: Int  -- number of next URL reference
+  , stOptions          :: WriterOptions -- writer options
+  , stOrderedListLevel :: Int  -- level of ordered list
+  , stEmphasisCommands :: Map.Map Text (Doc Text)
+  }
 
+-- | Table type
+data Tabl = Xtb  -- ^ Extreme tables
+          | Ntb  -- ^ Natural tables
+  deriving (Show, Eq)
+
+-- | Whether a heading belongs to a section environment or is standalone.
+data HeadingType = SectionHeading | NonSectionHeading
+
 orderedListStyles :: [Char]
 orderedListStyles = cycle "narg"
 
 -- | Convert Pandoc to ConTeXt.
 writeConTeXt :: PandocMonad m => WriterOptions -> Pandoc -> m Text
 writeConTeXt options document =
-  let defaultWriterState = WriterState { stNextRef = 1
-                                       , stOrderedListLevel = 0
-                                       , stOptions = options
-                                       }
+  let defaultWriterState = WriterState
+        { stCslHangingIndent = False
+        , stHasCslRefs = False
+        , stHighlighting = False
+        , stNextRef = 1
+        , stOptions = options
+        , stOrderedListLevel = 0
+        , stEmphasisCommands = mempty
+        }
   in evalStateT (pandocToConTeXt options document) defaultWriterState
 
 type WM = StateT WriterState
@@ -74,24 +88,26 @@
   let colwidth = if writerWrapText options == WrapAuto
                     then Just $ writerColumns options
                     else Nothing
-  let render' :: Doc -> Text
-      render' = render colwidth
-  metadata <- metaToJSON options
-              (fmap render' . blockListToConTeXt)
-              (fmap render' . inlineListToConTeXt)
+  metadata <- metaToContext options
+              blockListToConTeXt
+              (fmap chomp . inlineListToConTeXt)
               meta
-  body <- mapM (elementToConTeXt options) $ hierarchicalize blocks
-  let main = (render' . vcat) body
-  let layoutFromMargins = intercalate [','] $ mapMaybe (\(x,y) ->
-                                ((x ++ "=") ++) <$> getField y metadata)
+  main <- blockListToConTeXt $ makeSections False Nothing blocks
+  let layoutFromMargins = mconcat $ intersperse ("," :: Doc Text) $
+                          mapMaybe (\(x,y) ->
+                                ((x <> "=") <>) <$> getField y metadata)
                               [("leftmargin","margin-left")
                               ,("rightmargin","margin-right")
                               ,("top","margin-top")
                               ,("bottom","margin-bottom")
                               ]
   mblang <- fromBCP47 (getLang options meta)
+  st <- get
   let context =   defField "toc" (writerTableOfContents options)
-                $ defField "placelist" (intercalate ("," :: String) $
+                $ defField "lof" (writerListOfFigures options)
+                $ defField "lot" (writerListOfTables options)
+                $ defField "placelist"
+                   (mconcat . intersperse ("," :: Doc Text) $
                      take (writerTOCDepth options +
                            case writerTopLevelDivision options of
                              TopLevelPart    -> 0
@@ -101,26 +117,43 @@
                         "subsubsubsection","subsubsubsubsection"])
                 $ defField "body" main
                 $ defField "layout" layoutFromMargins
+                $ defField "tagging" (isEnabled Ext_tagging options)
                 $ defField "number-sections" (writerNumberSections options)
-                $ maybe id (defField "context-lang") mblang
-                $ (case getField "papersize" metadata of
+                $ defField "csl-refs" (stHasCslRefs st)
+                $ defField "csl-hanging-indent" (stCslHangingIndent st)
+                $ maybe id (\l ->
+                     defField "context-lang" (literal l :: Doc Text)) mblang
+                $ (case T.unpack . render Nothing <$>
+                      getField "papersize" metadata of
                         Just (('a':d:ds) :: String)
                           | all isDigit (d:ds) -> resetField "papersize"
-                                                     (('A':d:ds) :: String)
+                                                   (T.pack ('A':d:ds))
+                        _                     -> id)
+                $ defField "emphasis-commands"
+                    (mconcat $ Map.elems (stEmphasisCommands st))
+                $ (case writerHighlightMethod options of
+                      Skylighting sty | stHighlighting st ->
+                        defField "highlighting-commands" (styleToConTeXt sty)
+                      _ -> id)
+                $ (case T.toLower $ lookupMetaString "pdfa" meta of
+                        "true" -> resetField "pdfa" (T.pack "1b:2005")
                         _                     -> id) metadata
-  let context' = defField "context-dir" (toContextDir
+  let context' = defField "context-dir" (maybe mempty toContextDir
                                          $ getField "dir" context) context
-  case writerTemplate options of
-       Nothing  -> return main
-       Just tpl -> renderTemplate' tpl context'
+  return $ render colwidth $
+    case writerTemplate options of
+       Nothing  -> main
+       Just tpl -> renderTemplate tpl context'
 
-toContextDir :: Maybe String -> String
-toContextDir (Just "rtl") = "r2l"
-toContextDir (Just "ltr") = "l2r"
-toContextDir _            = ""
+-- change rtl to r2l, ltr to l2r
+toContextDir :: Doc Text -> Doc Text
+toContextDir = fmap (\t -> case t of
+                              "ltr" -> "l2r"
+                              "rtl" -> "r2l"
+                              _     -> t)
 
 -- | escape things as needed for ConTeXt
-escapeCharForConTeXt :: WriterOptions -> Char -> String
+escapeCharForConTeXt :: WriterOptions -> Char -> Text
 escapeCharForConTeXt opts ch =
  let ligatures = isEnabled Ext_smart opts in
  case ch of
@@ -139,62 +172,84 @@
     '\x2013' | ligatures -> "--"
     '\x2019' | ligatures -> "'"
     '\x2026' -> "\\ldots{}"
-    x        -> [x]
+    x        -> T.singleton x
 
 -- | Escape string for ConTeXt
-stringToConTeXt :: WriterOptions -> String -> String
-stringToConTeXt opts = concatMap (escapeCharForConTeXt opts)
+stringToConTeXt :: WriterOptions -> Text -> Text
+stringToConTeXt opts = T.concatMap (escapeCharForConTeXt opts)
 
 -- | Sanitize labels
-toLabel :: String -> String
-toLabel z = concatMap go z
+toLabel :: Text -> Text
+toLabel z = T.concatMap go z
  where go x
-         | x `elem` ("\\#[]\",{}%()|=" :: String) = "ux" ++ printf "%x" (ord x)
-         | otherwise = [x]
-
--- | Convert Elements to ConTeXt
-elementToConTeXt :: PandocMonad m => WriterOptions -> Element -> WM m Doc
-elementToConTeXt _ (Blk block) = blockToConTeXt block
-elementToConTeXt opts (Sec level _ attr title' elements) = do
-  header' <- sectionHeader attr level title'
-  innerContents <- mapM (elementToConTeXt opts) elements
-  return $ vcat (header' : innerContents)
+         | x `elem` ("\\#[]\",{}%()|=" :: String) = "ux" <> T.pack (printf "%x" (ord x))
+         | otherwise = T.singleton x
 
 -- | Convert Pandoc block element to ConTeXt.
-blockToConTeXt :: PandocMonad m => Block -> WM m Doc
-blockToConTeXt Null = return empty
-blockToConTeXt (Plain lst) = inlineListToConTeXt lst
--- title beginning with fig: indicates that the image is a figure
-blockToConTeXt (Para [Image attr txt (src,'f':'i':'g':':':_)]) = do
-  capt <- inlineListToConTeXt txt
-  img  <- inlineToConTeXt (Image attr txt (src, ""))
-  let (ident, _, _) = attr
-      label = if null ident
-                 then empty
-                 else "[]" <> brackets (text $ toLabel ident)
-  return $ blankline $$ "\\placefigure" <> label <> braces capt <> img <> blankline
+blockToConTeXt :: PandocMonad m => Block -> WM m (Doc Text)
+blockToConTeXt (Div attr@(_,"section":_,_)
+                 (Header level _ title' : xs)) = do
+  header' <- sectionHeader attr level title' SectionHeading
+  footer' <- sectionFooter attr level
+  innerContents <- blockListToConTeXt xs
+  return $ header' $$ innerContents $$ footer'
+blockToConTeXt (Plain lst) = do
+  opts <- gets stOptions
+  contents <- inlineListToConTeXt lst
+  return $
+    if isEnabled Ext_tagging opts
+    then "\\bpar{}" <> contents <> "\\epar{}"
+    else contents
 blockToConTeXt (Para lst) = do
+  opts <- gets stOptions
   contents <- inlineListToConTeXt lst
-  return $ contents <> blankline
+  return $
+    if isEnabled Ext_tagging opts
+    then "\\bpar" $$ contents $$ "\\epar" <> blankline
+    else contents <> blankline
 blockToConTeXt (LineBlock lns) = do
-  doclines <- nowrap . vcat <$> mapM inlineListToConTeXt lns
-  return $ "\\startlines" $$ doclines $$ "\\stoplines" <> blankline
+  let emptyToBlankline doc = if isEmpty doc
+                             then blankline
+                             else doc
+  doclines <- mapM inlineListToConTeXt lns
+  let contextLines = vcat . map emptyToBlankline $ doclines
+  return $ "\\startlines" $$ contextLines $$ "\\stoplines" <> blankline
 blockToConTeXt (BlockQuote lst) = do
   contents <- blockListToConTeXt lst
   return $ "\\startblockquote" $$ nest 0 contents $$ "\\stopblockquote" <> blankline
-blockToConTeXt (CodeBlock _ str) =
-  return $ flush ("\\starttyping" <> cr <> text str <> cr <> "\\stoptyping") $$ blankline
+blockToConTeXt (CodeBlock (_ident, classes, kv) str) = do
+  opts <- gets stOptions
+  let syntaxMap = writerSyntaxMap opts
+  let attr' = ("", classes, kv)
+  let unhighlighted = vcat ["\\starttyping", literal str, "\\stoptyping"]
+  let highlighted =
+        case highlight syntaxMap formatConTeXtBlock attr' str of
+          Left msg -> do
+            unless (T.null msg) $
+              report (CouldNotHighlight msg)
+            return unhighlighted
+          Right h  -> do
+            modify (\s -> s{ stHighlighting = True })
+            return (literal h)
   -- blankline because \stoptyping can't have anything after it, inc. '}'
-blockToConTeXt (RawBlock "context" str) = return $ text str <> blankline
-blockToConTeXt b@(RawBlock _ _ ) = do
-  report $ BlockNotRendered b
-  return empty
+  ($$ blankline) . flush <$>
+    case writerHighlightMethod opts of
+      Skylighting _ | not (null classes) -> pure unhighlighted
+      _ -> highlighted
+blockToConTeXt b@(RawBlock f str)
+  | f == Format "context" || f == Format "tex" = return $ literal str <> blankline
+  | otherwise = empty <$ report (BlockNotRendered b)
+blockToConTeXt (Div ("refs",classes,_) bs) = do
+  modify $ \st -> st{ stHasCslRefs = True
+                    , stCslHangingIndent = "hanging-indent" `elem` classes }
+  inner <- blockListToConTeXt bs
+  return $ "\\startcslreferences" $$ inner $$ "\\stopcslreferences"
 blockToConTeXt (Div (ident,_,kvs) bs) = do
   let align dir txt = "\\startalignment[" <> dir <> "]" $$ txt $$ "\\stopalignment"
   mblang <- fromBCP47 (lookup "lang" kvs)
-  let wrapRef txt = if null ident
+  let wrapRef txt = if T.null ident
                        then txt
-                       else ("\\reference" <> brackets (text $ toLabel ident) <>
+                       else ("\\reference" <> brackets (literal $ toLabel ident) <>
                               braces empty <> "%") $$ txt
       wrapDir = case lookup "dir" kvs of
                   Just "rtl" -> align "righttoleft"
@@ -202,38 +257,32 @@
                   _          -> id
       wrapLang txt = case mblang of
                        Just lng -> "\\start\\language["
-                                     <> text lng <> "]" $$ txt $$ "\\stop"
+                                     <> literal lng <> "]" $$ txt $$ "\\stop"
                        Nothing  -> txt
       wrapBlank txt = blankline <> txt <> blankline
-  (wrapBlank . wrapLang . wrapDir . wrapRef) <$> blockListToConTeXt bs
+  wrapBlank . wrapLang . wrapDir . wrapRef <$> blockListToConTeXt bs
 blockToConTeXt (BulletList lst) = do
   contents <- mapM listItemToConTeXt lst
   return $ ("\\startitemize" <> if isTightList lst
                                    then brackets "packed"
                                    else empty) $$
-    vcat contents $$ text "\\stopitemize" <> blankline
+    vcat contents $$ literal "\\stopitemize" <> blankline
 blockToConTeXt (OrderedList (start, style', delim) lst) = do
     st <- get
     let level = stOrderedListLevel st
     put st {stOrderedListLevel = level + 1}
     contents <- mapM listItemToConTeXt lst
     put st {stOrderedListLevel = level}
-    let start' = if start == 1 then "" else "start=" ++ show start
+    let start' = if start == 1 then "" else "start=" <> tshow start
     let delim' = case delim of
                         DefaultDelim -> ""
                         Period       -> "stopper=."
                         OneParen     -> "stopper=)"
                         TwoParens    -> "left=(,stopper=)"
-    let width = maximum $ map length $ take (length contents)
-                          (orderedListMarkers (start, style', delim))
-    let width' = (toEnum width + 1) / 2
-    let width'' = if width' > (1.5 :: Double)
-                     then "width=" ++ show width' ++ "em"
-                     else ""
-    let specs2Items = filter (not . null) [start', delim', width'']
+    let specs2Items = filter (not . T.null) [start', delim']
     let specs2 = if null specs2Items
                     then ""
-                    else "[" ++ intercalate "," specs2Items ++ "]"
+                    else "[" <> T.intercalate "," specs2Items <> "]"
     let style'' = '[': (case style' of
                           DefaultStyle -> orderedListStyles !! level
                           Decimal      -> 'n'
@@ -243,48 +292,257 @@
                           LowerAlpha   -> 'a'
                           UpperAlpha   -> 'A') :
                        if isTightList lst then ",packed]" else "]"
-    let specs = style'' ++ specs2
-    return $ "\\startitemize" <> text specs $$ vcat contents $$
-             "\\stopitemize" <> blankline
+    let specs = T.pack style'' <> specs2
+    return $ "\\startenumerate" <> literal specs $$ vcat contents $$
+             "\\stopenumerate" <> blankline
 blockToConTeXt (DefinitionList lst) =
   liftM vcat $ mapM defListItemToConTeXt lst
 blockToConTeXt HorizontalRule = return $ "\\thinrule" <> blankline
 -- If this is ever executed, provide a default for the reference identifier.
-blockToConTeXt (Header level attr lst) = sectionHeader attr level lst
-blockToConTeXt (Table caption aligns widths heads rows) = do
-    let colDescriptor colWidth alignment = (case alignment of
-                                               AlignLeft    -> 'l'
-                                               AlignRight   -> 'r'
-                                               AlignCenter  -> 'c'
-                                               AlignDefault -> 'l'):
-           if colWidth == 0
-              then "|"
-              else ("p(" ++ printf "%.2f" colWidth ++ "\\textwidth)|")
-    let colDescriptors = "|" ++ concat (
-                                 zipWith colDescriptor widths aligns)
-    headers <- if all null heads
-                  then return empty
-                  else liftM ($$ "\\HL") $ tableRowToConTeXt heads
-    captionText <- inlineListToConTeXt caption
-    rows' <- mapM tableRowToConTeXt rows
-    return $ "\\placetable" <> (if null caption
-                                   then brackets "none"
-                                   else empty)
-                            <> braces captionText $$
-             "\\starttable" <> brackets (text colDescriptors) $$
-             "\\HL" $$ headers $$
-             vcat rows' $$ "\\HL" $$ "\\stoptable" <> blankline
+blockToConTeXt (Header level attr lst) =
+  sectionHeader attr level lst NonSectionHeading
+blockToConTeXt (Table attr caption colspecs thead tbody tfoot) =
+  tableToConTeXt (Ann.toTable attr caption colspecs thead tbody tfoot)
+blockToConTeXt (Figure (ident, _, _) (Caption cshort clong) body) = do
+  title   <- inlineListToConTeXt (blocksToInlines clong)
+  list    <- maybe (pure empty) inlineListToConTeXt cshort
+  content <- blockListToConTeXt body
 
-tableRowToConTeXt :: PandocMonad m => [[Block]] -> WM m Doc
-tableRowToConTeXt cols = do
-  cols' <- mapM blockListToConTeXt cols
-  return $ vcat (map ("\\NC " <>) cols') $$ "\\NC\\AR"
+  let options =
+           ["reference=" <> literal (toLabel ident) | not (T.null ident)]
+        ++ ["title="     <> braces title | not (isEmpty title)]
+        ++ ["list="      <> braces list  | not (isEmpty list)]
+  let hasSubfigures = getAny $
+        query (Any . \case {Figure {} -> True; _ -> False}) body
+  return
+     $ "\\startplacefigure" <> brackets (mconcat $ intersperse "," options)
+    $$ (if hasSubfigures then "\\startfloatcombination" else empty)
+    $$ content
+    $$ (if hasSubfigures then "\\stopfloatcombination" else empty)
+    $$ "\\stopplacefigure"
+    $$ blankline
 
-listItemToConTeXt :: PandocMonad m => [Block] -> WM m Doc
-listItemToConTeXt list = blockListToConTeXt list >>=
-  return . ("\\item" $$) . nest 2
+tableToConTeXt :: PandocMonad m => Ann.Table -> WM m (Doc Text)
+tableToConTeXt (Ann.Table attr caption colspecs thead tbodies tfoot) = do
+  opts <- gets stOptions
+  let tabl = if isEnabled Ext_ntb opts
+             then Ntb
+             else Xtb
+  captionText <- case caption of
+                   Caption _ []       -> return mempty
+                   Caption _ longCapt -> blockListToConTeXt longCapt
+  head'  <- tableHeadToConTeXt tabl thead
+  bodies <- mapM (tableBodyToConTeXt tabl) tbodies
+  foot'  <- tableFootToConTeXt tabl tfoot
+  let body = case tabl of
+        Xtb -> "\\startxtable" $$
+               head' $$
+               "\\startxtablebody[body]" $$
+               vcat bodies $$
+               "\\stopxtablebody" $$
+               foot' $$
+               "\\stopxtable"
+        Ntb -> setupCols colspecs $$
+               "\\bTABLE" $$
+               head' $$
+               "\\bTABLEbody" $$
+               vcat bodies $$
+               "\\eTABLEbody" $$
+               foot' $$
+               "\\eTABLE"
+  let (ident, _classes, _attribs) = attr
+  let tblopts = filter (not . isEmpty)
+             [ if isEmpty captionText
+               then "location=none"
+               else "title=" <> braces captionText
+             , if T.null ident
+               then empty
+               else "reference=" <> braces (literal (toLabel ident))
+             ]
+  return $ vcat
+    [ "\\startplacetable" <> brackets (mconcat $ intersperse "," tblopts)
+    , body
+    , "\\stopplacetable" <> blankline
+    ]
 
-defListItemToConTeXt :: PandocMonad m => ([Inline], [[Block]]) -> WM m Doc
+setupCols :: [ColSpec] -> Doc Text
+setupCols = vcat . zipWith toColSetup [1::Int ..]
+  where
+    toColSetup i (align, width) =
+      let opts = filter (not . isEmpty)
+                 [ case align of
+                     AlignLeft    -> "align=right"
+                     AlignRight   -> "align=left"
+                     AlignCenter  -> "align=middle"
+                     AlignDefault -> "align=left"
+                 , case width of
+                     ColWidthDefault -> empty
+                     ColWidth w -> ("width=" <>) . braces . text $
+                                   printf "%.2f\\textwidth" w
+                 ]
+      in "\\setupTABLE[column]" <> brackets (text $ show i)
+                                <> brackets (mconcat $ intersperse "," opts)
+
+tableBodyToConTeXt :: PandocMonad m
+                   => Tabl
+                   -> Ann.TableBody
+                   -> WM m (Doc Text)
+tableBodyToConTeXt tabl (Ann.TableBody _attr _rowHeadCols inthead rows) = do
+  intermediateHead <-
+    if null inthead
+    then return mempty
+    else headerRowsToConTeXt tabl Thead inthead
+  bodyRows <- bodyRowsToConTeXt tabl rows
+  return $ intermediateHead <> bodyRows
+
+tableHeadToConTeXt :: PandocMonad m
+                   => Tabl
+                   -> Ann.TableHead
+                   -> WM m (Doc Text)
+tableHeadToConTeXt tabl (Ann.TableHead attr rows) =
+  tablePartToConTeXt tabl Thead attr rows
+
+tableFootToConTeXt :: PandocMonad m
+                   => Tabl
+                   -> Ann.TableFoot
+                   -> WM m (Doc Text)
+tableFootToConTeXt tbl (Ann.TableFoot attr rows) =
+  tablePartToConTeXt tbl Tfoot attr rows
+
+tablePartToConTeXt :: PandocMonad m
+                   => Tabl
+                   -> TablePart
+                   -> Attr
+                   -> [Ann.HeaderRow]
+                   -> WM m (Doc Text)
+tablePartToConTeXt tabl tblpart _attr rows = do
+  let (startCmd, stopCmd) = case (tabl, tblpart) of
+        (Ntb, Thead) -> ("\\bTABLEhead", "\\eTABLEhead")
+        (Ntb, Tfoot) -> ("\\bTABLEfoot", "\\eTABLEfoot")
+        (Xtb, Thead) -> ("\\startxtablehead[head]", "\\stopxtablehead")
+        (Xtb, Tfoot) -> ("\\startxtablefoot[foot]", "\\stopxtablefoot")
+        _            -> ("", "") -- this would be unexpected
+  contents <- headerRowsToConTeXt tabl tblpart rows
+  return $ startCmd $$ contents $$ stopCmd
+
+-- | The part of a table; header, footer, or body.
+data TablePart = Thead | Tfoot | Tbody
+  deriving (Eq)
+
+data CellType = HeaderCell | BodyCell
+
+data TableRow = TableRow TablePart Attr Ann.RowHead Ann.RowBody
+
+headerRowsToConTeXt :: PandocMonad m
+                    => Tabl
+                    -> TablePart
+                    -> [Ann.HeaderRow]
+                    -> WM m (Doc Text)
+headerRowsToConTeXt tabl tablepart = rowListToConTeXt tabl . map toTableRow
+  where
+    toTableRow (Ann.HeaderRow attr _rownum rowbody) =
+      TableRow tablepart attr [] rowbody
+
+bodyRowsToConTeXt :: PandocMonad m
+                  => Tabl
+                  -> [Ann.BodyRow]
+                  -> WM m (Doc Text)
+bodyRowsToConTeXt tabl = rowListToConTeXt tabl . map toTableRow
+  where
+    toTableRow (Ann.BodyRow attr _rownum rowhead rowbody) =
+      TableRow Tbody attr rowhead rowbody
+
+
+rowListToConTeXt :: PandocMonad m
+                 => Tabl
+                 -> [TableRow]
+                 -> WM m (Doc Text)
+rowListToConTeXt = \case
+  Ntb -> fmap vcat . mapM (tableRowToConTeXt Ntb)
+  Xtb -> \rows -> do
+    (butlast, lastrow) <-
+      case reverse rows of
+        []   -> pure ( []
+                     , empty
+                     )
+        r:rs -> (,) <$> (mapM (tableRowToConTeXt Xtb) (reverse rs))
+                    <*> tableRowToConTeXt Xtb r
+    return $
+      vcat butlast $$
+      if isEmpty lastrow
+      then empty
+      else "\\startxrowgroup[lastrow]" $$ lastrow $$ "\\stopxrowgroup"
+
+tableRowToConTeXt :: PandocMonad m
+               => Tabl
+               -> TableRow
+               -> WM m (Doc Text)
+tableRowToConTeXt tabl (TableRow tblpart _attr rowhead rowbody) = do
+  let celltype = case tblpart of
+                   Thead -> HeaderCell
+                   _     -> BodyCell
+  headcells <- mapM (tableCellToConTeXt tabl HeaderCell) rowhead
+  bodycells <- mapM (tableCellToConTeXt tabl celltype) rowbody
+  let cells = vcat headcells $$ vcat bodycells
+  return $ case tabl of
+    Xtb -> "\\startxrow" $$ cells $$ "\\stopxrow"
+    Ntb -> "\\bTR" $$ cells $$ "\\eTR"
+
+tableCellToConTeXt :: PandocMonad m
+                   => Tabl
+                   -> CellType
+                   -> Ann.Cell -> WM m (Doc Text)
+tableCellToConTeXt tabl celltype (Ann.Cell colspecs _colnum cell) = do
+  let Cell _attr cellalign rowspan colspan blocks = cell
+  let (colalign, _) :| _ = colspecs
+  let halign = alignToConTeXt $
+               case (cellalign, tabl) of
+                 (AlignDefault, Xtb) -> colalign
+                 _                   -> cellalign
+  let nx = case colspan of
+             ColSpan 1 -> empty
+             ColSpan n -> "nc=" <> literal (tshow n)
+  let ny = case rowspan of
+             RowSpan 1 -> empty
+             RowSpan n -> "nr=" <> literal (tshow n)
+  let widths = map snd (NonEmpty.toList colspecs)
+  let mbcolwidth = flip map widths $ \case
+        ColWidthDefault -> Nothing
+        ColWidth w      -> Just w
+  let colwidth = case catMaybes mbcolwidth of
+                   [] -> empty
+                   ws -> ("width=" <>) . braces . text $
+                         printf "%.2f\\textwidth" (sum ws)
+  let keys = hcat . intersperse "," $ filter (not . isEmpty) $
+             case tabl of
+               Xtb -> [halign, colwidth, nx, ny]
+               Ntb -> [halign, nx, ny]  -- no need for a column width
+  let options = (if isEmpty keys
+                 then empty
+                 else brackets keys) <> space
+  cellContents <- blockListToConTeXt blocks
+  return $ case tabl of
+             Xtb -> "\\startxcell" <> options <> cellContents <> " \\stopxcell"
+             Ntb -> case celltype of
+               BodyCell   -> "\\bTD" <> options <> cellContents <> "\\eTD"
+               HeaderCell -> "\\bTH" <> options <> cellContents <> "\\eTH"
+
+alignToConTeXt :: Alignment -> Doc Text
+alignToConTeXt = \case
+  AlignLeft    -> "align=right"
+  AlignRight   -> "align=left"
+  AlignCenter  -> "align=middle"
+  AlignDefault -> empty
+
+
+---
+--- Lists
+--
+
+listItemToConTeXt :: PandocMonad m => [Block] -> WM m (Doc Text)
+listItemToConTeXt list = ("\\item" $$) . nest 2 <$> blockListToConTeXt list
+
+defListItemToConTeXt :: PandocMonad m => ([Inline], [[Block]]) -> WM m (Doc Text)
 defListItemToConTeXt (term, defs) = do
   term' <- inlineListToConTeXt term
   def'  <- liftM vsep $ mapM blockListToConTeXt defs
@@ -292,13 +550,13 @@
            "\\stopdescription" <> blankline
 
 -- | Convert list of block elements to ConTeXt.
-blockListToConTeXt :: PandocMonad m => [Block] -> WM m Doc
+blockListToConTeXt :: PandocMonad m => [Block] -> WM m (Doc Text)
 blockListToConTeXt lst = liftM vcat $ mapM blockToConTeXt lst
 
 -- | Convert list of inline elements to ConTeXt.
 inlineListToConTeXt :: PandocMonad m
                     => [Inline]  -- ^ Inlines to convert
-                    -> WM m Doc
+                    -> WM m (Doc Text)
 inlineListToConTeXt lst = liftM hcat $ mapM inlineToConTeXt $ addStruts lst
   -- We add a \strut after a line break that precedes a space,
   -- or the space gets swallowed
@@ -307,20 +565,35 @@
              addStruts xs
         addStruts (x:xs) = x : addStruts xs
         addStruts [] = []
-        isSpacey Space            = True
-        isSpacey (Str ('\160':_)) = True
-        isSpacey _                = False
+        isSpacey Space                               = True
+        isSpacey (Str (T.uncons -> Just ('\160',_))) = True
+        isSpacey _                                   = False
 
+highlightInlines :: PandocMonad m
+                 => Text -> (Doc Text) -> [Inline]
+                 -> WM m (Doc Text)
+highlightInlines name style inlines = do
+  opts <- gets stOptions
+  contents <- inlineListToConTeXt inlines
+  if not (isEnabled Ext_tagging opts)
+    then return $ braces (style <> space <> contents)
+    else do
+      let cmd = "\\definehighlight " <> brackets (literal name) <>
+                brackets ("style=" <> braces style)
+      modify (\st -> st{ stEmphasisCommands =
+                         Map.insert name cmd (stEmphasisCommands st) })
+      return $ "\\" <> literal name <> braces contents
+
 -- | Convert inline element to ConTeXt
 inlineToConTeXt :: PandocMonad m
                 => Inline    -- ^ Inline to convert
-                -> WM m Doc
-inlineToConTeXt (Emph lst) = do
-  contents <- inlineListToConTeXt lst
-  return $ braces $ "\\em " <> contents
-inlineToConTeXt (Strong lst) = do
+                -> WM m (Doc Text)
+inlineToConTeXt (Emph lst)      = highlightInlines "emph"      "\\em" lst
+inlineToConTeXt (Strong lst)    = highlightInlines "strong"    "\\bf" lst
+inlineToConTeXt (SmallCaps lst) = highlightInlines "smallcaps" "\\setsmallcaps" lst
+inlineToConTeXt (Underline lst) = do
   contents <- inlineListToConTeXt lst
-  return $ braces $ "\\bf " <> contents
+  return $ "\\underbar" <> braces contents
 inlineToConTeXt (Strikeout lst) = do
   contents <- inlineListToConTeXt lst
   return $ "\\overstrikes" <> braces contents
@@ -330,14 +603,31 @@
 inlineToConTeXt (Subscript lst) = do
   contents <- inlineListToConTeXt lst
   return $ "\\low" <> braces contents
-inlineToConTeXt (SmallCaps lst) = do
-  contents <- inlineListToConTeXt lst
-  return $ braces $ "\\sc " <> contents
-inlineToConTeXt (Code _ str) | not ('{' `elem` str || '}' `elem` str) =
-  return $ "\\type" <> braces (text str)
-inlineToConTeXt (Code _ str) = do
+inlineToConTeXt (Code (_ident, classes, _kv) str) = do
+  let rawCode =
+        pure . literal $
+        case typeDelim str of
+          Just (open, close) ->
+            "\\type" <> (open `T.cons` str) `T.snoc` close
+          Nothing ->
+            "\\type[escape=yes]{" <>
+            (T.replace "{" "/BTEX\\letteropenbrace /ETEX" .
+             T.replace "}" "/BTEX\\letterclosebrace /ETEX" $
+             str) `T.snoc` '}'
   opts <- gets stOptions
-  return $ "\\mono" <> braces (text $ stringToConTeXt opts str)
+  let syntaxMap = writerSyntaxMap opts
+  let attr' = ("", classes, [])
+  let highlightCode =
+        case highlight syntaxMap formatConTeXtInline attr' str of
+          Left msg -> do
+            unless (T.null msg) $ report (CouldNotHighlight msg)
+            rawCode
+          Right h -> do
+            modify (\st -> st{ stHighlighting = True })
+            return (text (T.unpack h))
+  case writerHighlightMethod opts of
+    Skylighting _ | not (null classes) -> highlightCode
+    _ -> rawCode
 inlineToConTeXt (Quoted SingleQuote lst) = do
   contents <- inlineListToConTeXt lst
   return $ "\\quote" <> braces contents
@@ -347,17 +637,15 @@
 inlineToConTeXt (Cite _ lst) = inlineListToConTeXt lst
 inlineToConTeXt (Str str) = do
   opts <- gets stOptions
-  return $ text $ stringToConTeXt opts str
+  return $ literal $ stringToConTeXt opts str
 inlineToConTeXt (Math InlineMath str) =
-  return $ char '$' <> text str <> char '$'
+  return $ char '$' <> literal str <> char '$'
 inlineToConTeXt (Math DisplayMath str) =
-  return $ text "\\startformula "  <> text str <> text " \\stopformula" <> space
-inlineToConTeXt (RawInline "context" str) = return $ text str
-inlineToConTeXt (RawInline "tex" str) = return $ text str
-inlineToConTeXt il@(RawInline _ _) = do
-  report $ InlineNotRendered il
-  return empty
-inlineToConTeXt LineBreak = return $ text "\\crlf" <> cr
+  return $ literal "\\startformula "  <> literal str <> literal " \\stopformula" <> space
+inlineToConTeXt il@(RawInline f str)
+  | f == Format "tex" || f == Format "context" = return $ literal str
+  | otherwise = empty <$ report (InlineNotRendered il)
+inlineToConTeXt LineBreak = return $ literal "\\crlf" <> cr
 inlineToConTeXt SoftBreak = do
   wrapText <- gets (writerWrapText . stOptions)
   return $ case wrapText of
@@ -365,135 +653,187 @@
                WrapNone     -> space
                WrapPreserve -> cr
 inlineToConTeXt Space = return space
--- Handle HTML-like internal document references to sections
-inlineToConTeXt (Link _ txt ('#' : ref, _)) = do
-  opts <- gets stOptions
-  contents <-  inlineListToConTeXt txt
-  let ref' = toLabel $ stringToConTeXt opts ref
-  return $ text "\\goto"
-           <> braces contents
-           <> brackets (text ref')
-
 inlineToConTeXt (Link _ txt (src, _)) = do
-  let isAutolink = txt == [Str (unEscapeString src)]
-  st <- get
-  let next = stNextRef st
-  put $ st {stNextRef = next + 1}
-  let ref = "url" ++ show next
-  contents <-  inlineListToConTeXt txt
-  return $ "\\useURL"
-           <> brackets (text ref)
-           <> brackets (text $ escapeStringUsing [('#',"\\#"),('%',"\\%")] src)
-           <> (if isAutolink
-                  then empty
-                  else brackets empty <> brackets contents)
-           <> "\\from"
-           <> brackets (text ref)
+  let isAutolink = txt == [Str (T.pack $ unEscapeString $ T.unpack src)]
+  let escConTeXtURL = T.concatMap $ \case
+        '#' -> "\\#"
+        '%' -> "\\%"
+        c   -> T.singleton c
+  if isAutolink
+    then do
+      next <- gets stNextRef
+      modify $ \st -> st {stNextRef = next + 1}
+      let ref = "url" <> tshow next
+      return $ mconcat
+        [ "\\useURL"
+        , brackets (literal ref)
+        , brackets (literal $ escConTeXtURL src)
+        , "\\from"
+        , brackets (literal ref)
+        ]
+    else do
+      contents <- inlineListToConTeXt txt
+      -- Handle HTML-like internal document references to sections
+      reference <- case T.uncons src of
+        Just ('#', ref) -> toLabel <$>
+                           (stringToConTeXt <$> gets stOptions <*> pure ref)
+        _               -> pure $ "url(" <> escConTeXtURL src <> ")"
+      return $ mconcat
+        [ "\\goto"
+        , braces contents
+        , brackets (literal reference)
+        ]
 inlineToConTeXt (Image attr@(_,cls,_) _ (src, _)) = do
   opts <- gets stOptions
-  let showDim dir = let d = text (show dir) <> "="
+  let showDim dir = let d = literal (tshow dir) <> "="
                     in case dimension dir attr of
                          Just (Pixel a)   ->
-                           [d <> text (showInInch opts (Pixel a)) <> "in"]
+                           [d <> literal (showInInch opts (Pixel a)) <> "in"]
                          Just (Percent a) ->
-                           [d <> text (showFl (a / 100)) <> "\\textwidth"]
+                           [d <> literal (showFl (a / 100)) <> "\\textwidth"]
                          Just dim         ->
-                           [d <> text (show dim)]
+                           [d <> literal (tshow dim)]
                          Nothing          ->
                            []
       dimList = showDim Width ++ showDim Height
       dims = if null dimList
                 then empty
-                else brackets $ cat (intersperse "," dimList)
-      clas = if null cls
-                then empty
-                else brackets $ text $ toLabel $ head cls
-      src' = if isURI src
+                else brackets $ mconcat (intersperse "," dimList)
+      clas = case cls of
+               [] -> empty
+               (cl:_) -> brackets $ literal $ toLabel cl
+      -- Use / for path separators on Windows; see #4918
+      fixPathSeparators = T.map $ \c -> case c of
+                                          '\\' -> '/'
+                                          _    -> c
+      src' = fixPathSeparators $
+             if isURI src
                 then src
-                else unEscapeString src
-  return $ braces $ "\\externalfigure" <> brackets (text src') <> dims <> clas
+                else T.pack $ unEscapeString $ T.unpack src
+  return $ braces $ "\\externalfigure" <> brackets (literal src') <> clas <> dims
 inlineToConTeXt (Note contents) = do
   contents' <- blockListToConTeXt contents
   let codeBlock x@(CodeBlock _ _) = [x]
       codeBlock _                 = []
   let codeBlocks = query codeBlock contents
   return $ if null codeBlocks
-              then text "\\footnote{" <> nest 2 contents' <> char '}'
-              else text "\\startbuffer " <> nest 2 contents' <>
-                   text "\\stopbuffer\\footnote{\\getbuffer}"
-inlineToConTeXt (Span (_,_,kvs) ils) = do
+              then literal "\\footnote{" <> nest 2 (chomp contents') <> char '}'
+              else literal "\\startbuffer " <> nest 2 (chomp contents') <>
+                   literal "\\stopbuffer\\footnote{\\getbuffer}"
+inlineToConTeXt (Span (ident,_,kvs) ils) = do
   mblang <- fromBCP47 (lookup "lang" kvs)
   let wrapDir txt = case lookup "dir" kvs of
                       Just "rtl" -> braces $ "\\righttoleft " <> txt
                       Just "ltr" -> braces $ "\\lefttoright " <> txt
                       _          -> txt
       wrapLang txt = case mblang of
-                       Just lng -> "\\start\\language[" <> text lng
-                                      <> "]" <> txt <> "\\stop "
+                       Just lng -> braces ("\\language" <>
+                                           brackets (literal lng) <> txt)
                        Nothing -> txt
-  (wrapLang . wrapDir) <$> inlineListToConTeXt ils
+      addReference =
+        if T.null ident
+        then id
+        else (("\\reference" <> brackets (literal ident) <> "{}") <>)
+  addReference . wrapLang . wrapDir <$> inlineListToConTeXt ils
 
 -- | Craft the section header, inserting the section reference, if supplied.
 sectionHeader :: PandocMonad m
               => Attr
               -> Int
               -> [Inline]
-              -> WM m Doc
-sectionHeader (ident,classes,_) hdrLevel lst = do
+              -> HeadingType
+              -> WM m (Doc Text)
+sectionHeader (ident,classes,kvs) hdrLevel lst secenv = do
+  opts <- gets stOptions
   contents <- inlineListToConTeXt lst
-  st <- get
-  let opts = stOptions st
-  let level' = case writerTopLevelDivision opts of
-                 TopLevelPart    -> hdrLevel - 2
-                 TopLevelChapter -> hdrLevel - 1
-                 TopLevelSection -> hdrLevel
-                 TopLevelDefault -> hdrLevel
-  let ident' = if null ident
-                  then empty
-                  else brackets (text (toLabel ident))
-  let (section, chapter) = if "unnumbered" `elem` classes
-                              then (text "subject", text "title")
-                              else (text "section", text "chapter")
-  return $ case level' of
-             -1                   -> text "\\part" <> ident' <> braces contents
-             0                    -> char '\\' <> chapter <> ident' <>
-                                           braces contents
-             n | n >= 1 && n <= 5 -> char '\\'
-                                     <> text (concat (replicate (n - 1) "sub"))
-                                     <> section
-                                     <> ident'
-                                     <> braces contents
-                                     <> blankline
-             _                    -> contents <> blankline
+  levelText <- sectionLevelToText opts (ident,classes,kvs) hdrLevel secenv
+  let optsList = mconcat . filter (not . null) $
+        [ ["title=" <> braces contents | not (isEmpty contents)]
+        , ["reference=" <> braces (literal (toLabel ident)) | not (T.null ident)]
+        , ["number=no"          | "unnumbered" `elem` classes]
+        , ["incrementnumber=no" | "unnumbered" `elem` classes]
+        ]
+  let starter = case secenv of
+                  SectionHeading -> "\\start"
+                  NonSectionHeading -> "\\"
+  let options = if null optsList || isEmpty levelText
+                then empty
+                else brackets $ hcat (intersperse "," optsList)
+  return $ starter <> levelText <> options <> blankline
 
-fromBCP47 :: PandocMonad m => Maybe String -> WM m (Maybe String)
+-- | Craft the section footer
+sectionFooter :: PandocMonad m => Attr -> Int -> WM m (Doc Text)
+sectionFooter attr hdrLevel = do
+  opts <- gets stOptions
+  levelText <- sectionLevelToText opts attr hdrLevel SectionHeading
+  return $ "\\stop" <> levelText <> blankline
+
+-- | Generate a textual representation of the section level
+sectionLevelToText :: PandocMonad m
+                   => WriterOptions -> Attr -> Int -> HeadingType
+                   -> WM m (Doc Text)
+sectionLevelToText opts (_,classes,_) hdrLevel headingType = do
+  let unlisted = "unlisted" `elem` classes
+  let semanticSection shift = do
+        let (section, chapter) = if unlisted
+                                 then (literal "subject", literal "title")
+                                 else (literal "section", literal "chapter")
+        return $ case hdrLevel + shift of
+                   -1         -> literal "part"
+                   0          -> chapter
+                   n | n >= 1 -> text (concat (replicate (n - 1) "sub"))
+                                 <> section
+                   _          -> empty -- cannot happen
+
+  case writerTopLevelDivision opts of
+    TopLevelPart    -> semanticSection (-2)
+    TopLevelChapter -> semanticSection (-1)
+    TopLevelSection -> semanticSection 0
+    TopLevelDefault -> if unlisted
+                       then semanticSection 0
+                       else return . literal $
+                            case headingType of
+                              SectionHeading    -> "sectionlevel"
+                              NonSectionHeading -> ""
+
+-- | Finds a pair of symbols that can be used as delimiters.
+typeDelim :: Text -> Maybe (Char, Char)
+typeDelim t =
+  let delimChars = "{\"'`()-+=%,.:;"
+      go delims '}' = go delims '{'
+      go delims c = T.filter (/= c) delims
+  in case fmap fst . T.uncons $ T.foldl' go delimChars t of
+       Just '{' -> Just ('{', '}')
+       Just c   -> Just (c, c)
+       Nothing  -> Nothing
+
+fromBCP47 :: PandocMonad m => Maybe Text -> WM m (Maybe Text)
 fromBCP47 mbs = fromBCP47' <$> toLang mbs
 
 -- Takes a list of the constituents of a BCP 47 language code
 -- and irons out ConTeXt's exceptions
 -- https://tools.ietf.org/html/bcp47#section-2.1
 -- http://wiki.contextgarden.net/Language_Codes
-fromBCP47' :: Maybe Lang -> Maybe String
-fromBCP47' (Just (Lang "ar" _ "SY" _)     ) = Just "ar-sy"
-fromBCP47' (Just (Lang "ar" _ "IQ" _)     ) = Just "ar-iq"
-fromBCP47' (Just (Lang "ar" _ "JO" _)     ) = Just "ar-jo"
-fromBCP47' (Just (Lang "ar" _ "LB" _)     ) = Just "ar-lb"
-fromBCP47' (Just (Lang "ar" _ "DZ" _)     ) = Just "ar-dz"
-fromBCP47' (Just (Lang "ar" _ "MA" _)     ) = Just "ar-ma"
-fromBCP47' (Just (Lang "de" _ _ ["1901"]) ) = Just "deo"
-fromBCP47' (Just (Lang "de" _ "DE" _)     ) = Just "de-de"
-fromBCP47' (Just (Lang "de" _ "AT" _)     ) = Just "de-at"
-fromBCP47' (Just (Lang "de" _ "CH" _)     ) = Just "de-ch"
-fromBCP47' (Just (Lang "el" _ _ ["poly"]) ) = Just "agr"
-fromBCP47' (Just (Lang "en" _ "US" _)     ) = Just "en-us"
-fromBCP47' (Just (Lang "en" _ "GB" _)     ) = Just "en-gb"
-fromBCP47' (Just (Lang "grc"_  _ _)       ) = Just "agr"
-fromBCP47' (Just (Lang "el" _ _ _)        ) = Just "gr"
-fromBCP47' (Just (Lang "eu" _ _ _)        ) = Just "ba"
-fromBCP47' (Just (Lang "he" _ _ _)        ) = Just "il"
-fromBCP47' (Just (Lang "jp" _ _ _)        ) = Just "ja"
-fromBCP47' (Just (Lang "uk" _ _ _)        ) = Just "ua"
-fromBCP47' (Just (Lang "vi" _ _ _)        ) = Just "vn"
-fromBCP47' (Just (Lang "zh" _ _ _)        ) = Just "cn"
-fromBCP47' (Just (Lang l _ _ _)           ) = Just l
-fromBCP47' Nothing                          = Nothing
+fromBCP47' :: Maybe Lang -> Maybe Text
+fromBCP47' (Just (Lang "ar" _ (Just "SY") _ _ _)) = Just "ar-sy"
+fromBCP47' (Just (Lang "ar" _ (Just "IQ") _ _ _)) = Just "ar-iq"
+fromBCP47' (Just (Lang "ar" _ (Just "JO") _ _ _)) = Just "ar-jo"
+fromBCP47' (Just (Lang "ar" _ (Just "LB") _ _ _)) = Just "ar-lb"
+fromBCP47' (Just (Lang "ar" _ (Just "DZ") _ _ _)) = Just "ar-dz"
+fromBCP47' (Just (Lang "ar" _ (Just "MA") _ _ _)) = Just "ar-ma"
+fromBCP47' (Just (Lang "de" _ _ ["1901"] _ _))    = Just "deo"
+fromBCP47' (Just (Lang "de" _ (Just "DE") _ _ _)) = Just "de-de"
+fromBCP47' (Just (Lang "de" _ (Just "AT") _ _ _)) = Just "de-at"
+fromBCP47' (Just (Lang "de" _ (Just "CH") _ _ _)) = Just "de-ch"
+fromBCP47' (Just (Lang "el" _ _ ["poly"] _ _))    = Just "agr"
+fromBCP47' (Just (Lang "en" _ (Just "US") _ _ _)) = Just "en-us"
+fromBCP47' (Just (Lang "en" _ (Just "GB") _ _ _)) = Just "en-gb"
+fromBCP47' (Just (Lang "grc"_ _ _ _ _))           = Just "agr"
+fromBCP47' (Just (Lang "el" _ _ _ _ _))           = Just "gr"
+fromBCP47' (Just (Lang "eu" _ _ _ _ _))           = Just "ba"
+fromBCP47' (Just (Lang "he" _ _ _ _ _))           = Just "il"
+fromBCP47' (Just (Lang "uk" _ _ _ _ _))           = Just "ua"
+fromBCP47' (Just (Lang "vi" _ _ _ _ _))           = Just "vn"
+fromBCP47' (Just (Lang "zh" _ _ _ _ _))           = Just "cn"
+fromBCP47' (Just (Lang l _ _ _ _ _))              = Just l
+fromBCP47' Nothing                                = Nothing
diff --git a/src/Text/Pandoc/Writers/CslJson.hs b/src/Text/Pandoc/Writers/CslJson.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Writers/CslJson.hs
@@ -0,0 +1,92 @@
+{-# LANGUAGE OverloadedStrings #-}
+{- |
+   Module      : Text.Pandoc.Writers.CslJson
+   Copyright   : Copyright (C) 2020-2024 John MacFarlane
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : John MacFarlane <jgm@berkeley.edu>
+   Stability   : alpha
+   Portability : portable
+
+Conversion of references from 'Pandoc' metadata to CSL JSON:
+<https://citeproc-js.readthedocs.io/en/latest/csl-json/markup.html>.
+
+Note that this writer ignores everything in the body of the
+document and everything in the metadata except `references`.
+It assumes that the `references` field is a list with the structure
+of a CSL JSON bibliography.
+-}
+module Text.Pandoc.Writers.CslJson ( writeCslJson )
+where
+import Data.Text (Text)
+import qualified Data.Text as T
+import qualified Text.Pandoc.UTF8 as UTF8
+import Text.Pandoc.Error
+import Text.Pandoc.Class
+import Control.Monad.Except (throwError)
+import Data.ByteString.Lazy (toStrict)
+import Data.ByteString (ByteString)
+import Text.Pandoc.Definition
+import Text.Pandoc.Builder as B
+import Text.Pandoc.Citeproc.MetaValue (metaValueToReference, metaValueToText)
+import Citeproc (parseLang, Locale, Reference(..), Lang(..))
+import Control.Monad.Identity
+import Citeproc.Locale (getLocale)
+import Citeproc.CslJson
+import Text.Pandoc.Options (WriterOptions)
+import Data.Maybe (mapMaybe, fromMaybe)
+import Data.Aeson.Encode.Pretty         (Config (..), Indent (Spaces),
+                                         NumberFormat (Generic),
+                                         defConfig, encodePretty')
+
+writeCslJson :: PandocMonad m => WriterOptions -> Pandoc -> m Text
+writeCslJson _opts (Pandoc meta _) = do
+  let lang = fromMaybe (Lang "en" Nothing (Just "US") [] [] [])
+               (lookupMeta "lang" meta >>= metaValueToText >>=
+                  either (const Nothing) Just . parseLang)
+  locale <- case getLocale lang of
+               Left e  -> throwError $ PandocCiteprocError e
+               Right l -> return l
+  let rs = case lookupMeta "references" meta of
+             Just (MetaList xs) -> xs
+             _ -> []
+  return $ UTF8.toText
+           (toCslJson locale (mapMaybe metaValueToReference rs)) <> "\n"
+
+fromInlines :: [Inline] -> CslJson Text
+fromInlines = foldMap fromInline . B.fromList
+
+fromInline :: Inline -> CslJson Text
+fromInline (Str t) = CslText t
+fromInline (Emph ils) = CslItalic (fromInlines ils)
+fromInline (Strong ils) = CslBold (fromInlines ils)
+fromInline (Underline ils) = CslUnderline (fromInlines ils)
+fromInline (Strikeout ils) = fromInlines ils
+fromInline (Superscript ils) = CslSup (fromInlines ils)
+fromInline (Subscript ils) = CslSub (fromInlines ils)
+fromInline (SmallCaps ils) = CslSmallCaps (fromInlines ils)
+fromInline (Quoted _ ils) = CslQuoted (fromInlines ils)
+fromInline (Cite _ ils) = fromInlines ils
+fromInline (Code _ t) = CslText t
+fromInline Space = CslText " "
+fromInline SoftBreak = CslText " "
+fromInline LineBreak = CslText "\n"
+fromInline (Math InlineMath t) = CslText $ "$" <> t <> "$"
+fromInline (Math DisplayMath t) = CslText $ "$$" <> t <> "$$"
+fromInline (RawInline _ _) = CslEmpty
+fromInline (Link _ ils _) = fromInlines ils
+fromInline (Image _ ils _) = fromInlines ils
+fromInline (Note _) = CslEmpty
+fromInline (Span (_,[cl],_) ils)
+  | "csl-" `T.isPrefixOf` cl = CslDiv cl (fromInlines ils)
+  | cl == "nocase" = CslNoCase (fromInlines ils)
+fromInline (Span _ ils) = fromInlines ils
+
+toCslJson :: Locale -> [Reference Inlines] -> ByteString
+toCslJson locale = toStrict .
+  encodePretty' defConfig{ confIndent = Spaces 2
+                         , confCompare = compare
+                         , confNumFormat = Generic }
+  . map (runIdentity .  traverse (return .
+                                  renderCslJson False locale .
+                                  foldMap fromInline))
diff --git a/src/Text/Pandoc/Writers/Custom.hs b/src/Text/Pandoc/Writers/Custom.hs
deleted file mode 100644
--- a/src/Text/Pandoc/Writers/Custom.hs
+++ /dev/null
@@ -1,247 +0,0 @@
-{-# LANGUAGE DeriveDataTypeable   #-}
-{-# LANGUAGE FlexibleInstances    #-}
-{- Copyright (C) 2012-2017 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-2017 John MacFarlane
-   License     : GNU GPL, version 2 or above
-
-   Maintainer  : John MacFarlane <jgm@berkeley.edu>
-   Stability   : alpha
-   Portability : portable
-
-Conversion of 'Pandoc' documents to custom markup using
-a lua writer.
--}
-module Text.Pandoc.Writers.Custom ( writeCustom ) where
-import Control.Arrow ((***))
-import Control.Exception
-import Control.Monad (when)
-import Control.Monad.Trans (MonadIO (liftIO))
-import Data.Char (toLower)
-import Data.List (intersperse)
-import qualified Data.Map as M
-import Data.Text (Text, pack)
-import Data.Typeable
-import Foreign.Lua (Lua, ToLuaStack (..), callFunc)
-import Foreign.Lua.Api
-import Text.Pandoc.Class (PandocIO)
-import Text.Pandoc.Definition
-import Text.Pandoc.Error
-import Text.Pandoc.Lua.Init (runPandocLua)
-import Text.Pandoc.Lua.StackInstances ()
-import Text.Pandoc.Lua.Util (addValue, dostring')
-import Text.Pandoc.Options
-import Text.Pandoc.Templates
-import qualified Text.Pandoc.UTF8 as UTF8
-import Text.Pandoc.Writers.Shared
-
-attrToMap :: Attr -> M.Map String String
-attrToMap (id',classes,keyvals) = M.fromList
-    $ ("id", id')
-    : ("class", unwords classes)
-    : keyvals
-
-newtype Stringify a = Stringify a
-
-instance ToLuaStack (Stringify Format) where
-  push (Stringify (Format f)) = push (map toLower f)
-
-instance ToLuaStack (Stringify [Inline]) where
-  push (Stringify ils) = push =<< inlineListToCustom ils
-
-instance ToLuaStack (Stringify [Block]) where
-  push (Stringify blks) = push =<< blockListToCustom blks
-
-instance ToLuaStack (Stringify MetaValue) where
-  push (Stringify (MetaMap m))       = push (fmap Stringify m)
-  push (Stringify (MetaList xs))     = push (map Stringify xs)
-  push (Stringify (MetaBool x))      = push x
-  push (Stringify (MetaString s))    = push s
-  push (Stringify (MetaInlines ils)) = push (Stringify ils)
-  push (Stringify (MetaBlocks bs))   = push (Stringify bs)
-
-instance ToLuaStack (Stringify Citation) where
-  push (Stringify cit) = do
-    createtable 6 0
-    addValue "citationId" $ citationId cit
-    addValue "citationPrefix" . Stringify $ citationPrefix cit
-    addValue "citationSuffix" . Stringify $ citationSuffix cit
-    addValue "citationMode" $ show (citationMode cit)
-    addValue "citationNoteNum" $ citationNoteNum cit
-    addValue "citationHash" $ citationHash cit
-
--- | Key-value pair, pushed as a table with @a@ as the only key and @v@ as the
--- associated value.
-newtype KeyValue a b = KeyValue (a, b)
-
-instance (ToLuaStack a, ToLuaStack b) => ToLuaStack (KeyValue a b) where
-  push (KeyValue (k, v)) = do
-    newtable
-    addValue k v
-
-data PandocLuaException = PandocLuaException String
-    deriving (Show, Typeable)
-
-instance Exception PandocLuaException
-
--- | Convert Pandoc to custom markup.
-writeCustom :: FilePath -> WriterOptions -> Pandoc -> PandocIO Text
-writeCustom luaFile opts doc@(Pandoc meta _) = do
-  luaScript <- liftIO $ UTF8.readFile luaFile
-  res <- runPandocLua $ do
-    stat <- dostring' luaScript
-    -- check for error in lua script (later we'll change the return type
-    -- to handle this more gracefully):
-    when (stat /= OK) $
-      tostring 1 >>= throw . PandocLuaException . UTF8.toString
-    -- TODO - call hierarchicalize, so we have that info
-    rendered <- docToCustom opts doc
-    context <- metaToJSON opts
-               blockListToCustom
-               inlineListToCustom
-               meta
-    return (rendered, context)
-  let (body, context) = case res of
-        Left e -> throw (PandocLuaException (show e))
-        Right x -> x
-  case writerTemplate opts of
-       Nothing  -> return $ pack body
-       Just tpl ->
-         case applyTemplate (pack tpl) $ setField "body" body context of
-              Left e  -> throw (PandocTemplateError e)
-              Right r -> return (pack r)
-
-docToCustom :: WriterOptions -> Pandoc -> Lua String
-docToCustom opts (Pandoc (Meta metamap) blocks) = do
-  body <- blockListToCustom blocks
-  callFunc "Doc" body (fmap Stringify metamap) (writerVariables opts)
-
--- | Convert Pandoc block element to Custom.
-blockToCustom :: Block         -- ^ Block element
-              -> Lua String
-
-blockToCustom Null = return ""
-
-blockToCustom (Plain inlines) = callFunc "Plain" (Stringify inlines)
-
-blockToCustom (Para [Image attr txt (src,tit)]) =
-  callFunc "CaptionedImage" src tit (Stringify txt) (attrToMap attr)
-
-blockToCustom (Para inlines) = callFunc "Para" (Stringify inlines)
-
-blockToCustom (LineBlock linesList) = callFunc "LineBlock" (map Stringify linesList)
-
-blockToCustom (RawBlock format str) =
-  callFunc "RawBlock" (Stringify format) str
-
-blockToCustom HorizontalRule = callFunc "HorizontalRule"
-
-blockToCustom (Header level attr inlines) =
-  callFunc "Header" level (Stringify inlines) (attrToMap attr)
-
-blockToCustom (CodeBlock attr str) =
-  callFunc "CodeBlock" str (attrToMap attr)
-
-blockToCustom (BlockQuote blocks) = callFunc "BlockQuote" (Stringify blocks)
-
-blockToCustom (Table capt aligns widths headers rows) =
-  let aligns' = map show aligns
-      capt' = Stringify capt
-      headers' = map Stringify headers
-      rows' = map (map Stringify) rows
-  in callFunc "Table" capt' aligns' widths headers' rows'
-
-blockToCustom (BulletList items) = callFunc "BulletList" (map Stringify items)
-
-blockToCustom (OrderedList (num,sty,delim) items) =
-  callFunc "OrderedList" (map Stringify items) num (show sty) (show delim)
-
-blockToCustom (DefinitionList items) =
-  callFunc "DefinitionList"
-           (map (KeyValue . (Stringify *** map Stringify)) items)
-
-blockToCustom (Div attr items) =
-  callFunc "Div" (Stringify items) (attrToMap attr)
-
--- | Convert list of Pandoc block elements to Custom.
-blockListToCustom :: [Block]       -- ^ List of block elements
-                  -> Lua String
-blockListToCustom xs = do
-  blocksep <- callFunc "Blocksep"
-  bs <- mapM blockToCustom xs
-  return $ mconcat $ intersperse blocksep bs
-
--- | Convert list of Pandoc inline elements to Custom.
-inlineListToCustom :: [Inline] -> Lua String
-inlineListToCustom lst = do
-  xs <- mapM inlineToCustom lst
-  return $ mconcat xs
-
--- | Convert Pandoc inline element to Custom.
-inlineToCustom :: Inline -> Lua String
-
-inlineToCustom (Str str) = callFunc "Str" str
-
-inlineToCustom Space = callFunc "Space"
-
-inlineToCustom SoftBreak = callFunc "SoftBreak"
-
-inlineToCustom (Emph lst) = callFunc "Emph" (Stringify lst)
-
-inlineToCustom (Strong lst) = callFunc "Strong" (Stringify lst)
-
-inlineToCustom (Strikeout lst) = callFunc "Strikeout" (Stringify lst)
-
-inlineToCustom (Superscript lst) = callFunc "Superscript" (Stringify lst)
-
-inlineToCustom (Subscript lst) = callFunc "Subscript" (Stringify lst)
-
-inlineToCustom (SmallCaps lst) = callFunc "SmallCaps" (Stringify lst)
-
-inlineToCustom (Quoted SingleQuote lst) = callFunc "SingleQuoted" (Stringify lst)
-
-inlineToCustom (Quoted DoubleQuote lst) = callFunc "DoubleQuoted" (Stringify lst)
-
-inlineToCustom (Cite cs lst) = callFunc "Cite" (Stringify lst) (map Stringify cs)
-
-inlineToCustom (Code attr str) =
-  callFunc "Code" str (attrToMap attr)
-
-inlineToCustom (Math DisplayMath str) =
-  callFunc "DisplayMath" str
-
-inlineToCustom (Math InlineMath str) =
-  callFunc "InlineMath" str
-
-inlineToCustom (RawInline format str) =
-  callFunc "RawInline" (Stringify format) str
-
-inlineToCustom LineBreak = callFunc "LineBreak"
-
-inlineToCustom (Link attr txt (src,tit)) =
-  callFunc "Link" (Stringify txt) src tit (attrToMap attr)
-
-inlineToCustom (Image attr alt (src,tit)) =
-  callFunc "Image" (Stringify alt) src tit (attrToMap attr)
-
-inlineToCustom (Note contents) = callFunc "Note" (Stringify contents)
-
-inlineToCustom (Span attr items) =
-  callFunc "Span" (Stringify items) (attrToMap attr)
diff --git a/src/Text/Pandoc/Writers/Djot.hs b/src/Text/Pandoc/Writers/Djot.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Writers/Djot.hs
@@ -0,0 +1,300 @@
+{-# LANGUAGE OverloadedStrings   #-}
+{-# LANGUAGE ScopedTypeVariables #-}
+{- |
+   Module      : Text.Pandoc.Writers.Djot
+   Copyright   : Copyright (C) 2024 John MacFarlane
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : John MacFarlane <jgm@berkeley.edu>
+   Stability   : alpha
+   Portability : portable
+
+Conversion of 'Pandoc' format into Djot markup (<https://djot.net>).
+-}
+module Text.Pandoc.Writers.Djot (
+    writeDjot
+  ) where
+import Text.Pandoc.Definition
+import Text.Pandoc.Logging
+import Text.Pandoc.Class ( PandocMonad , report )
+import Text.Pandoc.Options ( WriterOptions(..), WrapOption(..))
+import Data.Text (Text)
+import Data.Set (Set)
+import qualified Data.Set as Set
+import qualified Data.ByteString as B
+import qualified Data.ByteString.Char8 as B8
+import Data.List (intersperse)
+import qualified Data.Text as T
+import qualified Data.Map as M
+import qualified Text.Pandoc.UTF8 as UTF8
+import Text.Pandoc.Writers.Shared ( metaToContext, defField, toLegacyTable )
+import Text.Pandoc.Shared (isTightList, tshow, stringify, onlySimpleTableCells,
+                           makeSections)
+import Text.DocLayout
+import Text.DocTemplates (renderTemplate)
+
+import Control.Monad.State (StateT(..), gets, modify)
+import Control.Monad (zipWithM, when)
+import Data.Maybe (fromMaybe)
+import qualified Djot.AST as D
+import Djot (renderDjot, RenderOptions(..), toIdentifier)
+import Text.Pandoc.UTF8 (fromText)
+
+-- | Convert Pandoc to Djot.
+writeDjot :: PandocMonad m => WriterOptions -> Pandoc -> m Text
+writeDjot opts (Pandoc meta blocks) = do
+  let colwidth = if writerWrapText opts == WrapAuto
+                    then Just $ writerColumns opts
+                    else Nothing
+  let ropts = RenderOptions{ preserveSoftBreaks =
+                               writerWrapText opts == WrapPreserve }
+  metadata <- metaToContext opts
+               (fmap (renderDjot ropts) . bodyToDjot opts)
+               (fmap (chomp . renderDjot ropts) . bodyToDjot opts .
+                  (:[]) . Plain)
+               meta
+  main <- renderDjot ropts <$>
+            bodyToDjot opts (makeSections False Nothing blocks)
+  let context  = defField "body" main metadata
+  return $ render colwidth $
+    case writerTemplate opts of
+       Nothing  -> main
+       Just tpl -> renderTemplate tpl context
+
+data DjotState =
+  DjotState
+  { footnotes :: D.NoteMap
+  , references :: D.ReferenceMap
+  , autoReferences :: D.ReferenceMap
+  , autoIds :: Set B.ByteString
+  , options :: WriterOptions }
+
+bodyToDjot :: PandocMonad m => WriterOptions -> [Block] -> m D.Doc
+bodyToDjot opts bls = do
+  (bs, st) <- runStateT (blocksToDjot bls)
+               (DjotState mempty mempty mempty mempty opts)
+  let D.ReferenceMap autos = autoReferences st
+  let D.ReferenceMap refs = references st
+  pure $ D.Doc{ D.docBlocks = bs
+              , D.docFootnotes = footnotes st
+              , D.docReferences = D.ReferenceMap $ M.difference refs autos
+              , D.docAutoReferences = D.ReferenceMap autos
+              , D.docAutoIdentifiers = autoIds st
+              }
+
+blocksToDjot :: PandocMonad m => [Block] -> StateT DjotState m D.Blocks
+blocksToDjot = fmap mconcat . mapM blockToDjot
+
+blockToDjot :: PandocMonad m => Block -> StateT DjotState m D.Blocks
+blockToDjot (Para ils) = D.para <$> inlinesToDjot ils
+blockToDjot (Plain ils) = D.para <$> inlinesToDjot ils
+blockToDjot (LineBlock ls) =
+  D.para . mconcat . intersperse D.hardBreak <$> mapM inlinesToDjot ls
+blockToDjot (CodeBlock attr@(_,_,kvs) t) = do
+  let lang = fromMaybe mempty $ lookup "lang" kvs
+  pure $ D.addAttr (toDjotAttr attr)
+       <$> D.codeBlock (fromText lang) (fromText t)
+blockToDjot (RawBlock (Format f) t) =
+  pure $ D.rawBlock (D.Format (fromText f)) (fromText t)
+blockToDjot (BlockQuote bls) = D.blockQuote <$> blocksToDjot bls
+blockToDjot (Header lev attr ils) =
+  fmap (D.addAttr (toDjotAttr attr)) . D.heading lev <$> inlinesToDjot ils
+blockToDjot HorizontalRule = pure D.thematicBreak
+blockToDjot (Div (ident,"section":cls,kvs)
+              (Header lev (_,hcls,hkvs) ils : bls)) = do
+  ilsBs <- D.inlinesToByteString <$> inlinesToDjot ils
+  let ident' = toIdentifier ilsBs
+  let label = D.normalizeLabel ilsBs
+  let autoid = UTF8.toText ident' == ident
+  when autoid $
+    modify $ \st -> st{ autoIds = Set.insert ident' (autoIds st) }
+  modify $ \st -> st{ autoReferences = D.insertReference label
+                          (B8.cons '#' ident', mempty) (autoReferences st) }
+  fmap
+    (D.addAttr (toDjotAttr (if autoid then "" else ident,
+                         filter (/= "section") cls,
+                         filter (\(k,_) -> k /= "wrapper") kvs) <>
+                toDjotAttr ("", [c | c <- hcls, c `notElem` cls], hkvs)))
+         . D.section
+     <$> blocksToDjot (Header lev mempty ils : bls)
+blockToDjot (Div attr@(ident,cls,kvs) bls)
+  | Just "1" <- lookup "wrapper" kvs
+    = fmap (D.addAttr
+             (toDjotAttr (ident,cls,filter (\(k,_) -> k /= "wrapper") kvs)))
+       <$> blocksToDjot bls
+  | otherwise
+    = fmap (D.addAttr (toDjotAttr attr)) . D.div <$> blocksToDjot bls
+blockToDjot (BulletList items) =
+  D.bulletList spacing <$> mapM blocksToDjot items
+ where
+   spacing = if isTightList items then D.Tight else D.Loose
+blockToDjot (OrderedList (start, sty, delim) items) =
+  D.orderedList listAttr spacing <$> mapM blocksToDjot items
+ where
+   spacing = if isTightList items then D.Tight else D.Loose
+   listAttr = D.OrderedListAttributes {
+                D.orderedListStyle =
+                  case sty of
+                    DefaultStyle -> D.Decimal
+                    Example -> D.Decimal
+                    Decimal -> D.Decimal
+                    LowerRoman -> D.RomanLower
+                    UpperRoman -> D.RomanUpper
+                    LowerAlpha -> D.LetterLower
+                    UpperAlpha -> D.LetterUpper,
+                D.orderedListDelim =
+                    case delim of
+                      DefaultDelim -> D.RightPeriod
+                      Period -> D.RightPeriod
+                      OneParen -> D.RightParen
+                      TwoParens -> D.LeftRightParen,
+                D.orderedListStart = start }
+blockToDjot (DefinitionList items) =
+  D.definitionList spacing <$> mapM toDLItem items
+ where
+   spacing = if isTightList (map (concat . snd) items)
+                then D.Tight
+                else D.Loose
+   toDLItem (term, defs) = do
+     term' <- inlinesToDjot term
+     def' <- mconcat <$> mapM blocksToDjot defs
+     pure (term', def')
+blockToDjot (Figure attr (Caption _ capt) bls) = do
+  content <- blocksToDjot bls
+  caption <- fmap (D.addAttr (D.Attr [("class","caption")])) . D.div <$>
+               blocksToDjot capt
+  pure $ fmap (D.addAttr (toDjotAttr attr)) $ D.div $ content <> caption
+blockToDjot (Table attr capt' colspecs thead tbodies tfoot) = do
+  let (capt, aligns, _, headRow, bodyRows) =
+        toLegacyTable capt' colspecs thead tbodies tfoot
+  if onlySimpleTableCells (headRow : bodyRows)
+     then do
+       let alignToAlign al = case al of
+                               AlignDefault -> D.AlignDefault
+                               AlignLeft -> D.AlignLeft
+                               AlignRight -> D.AlignRight
+                               AlignCenter -> D.AlignCenter
+       let defAligns = map alignToAlign aligns
+       let cellToCell isHeader bls al =
+             D.Cell (if isHeader then D.HeadCell else D.BodyCell) al
+               <$> case bls of
+                     [Para ils] -> inlinesToDjot ils
+                     [Plain ils] -> inlinesToDjot ils
+                     [] -> pure mempty
+                     bs -> do
+                       mapM_ (report . BlockNotRendered) bs
+                       pure $ D.str "((omitted))"
+       let rowToRow isHeader cells = zipWithM (cellToCell isHeader) cells defAligns
+       hrows <- if null headRow
+                   then pure []
+                   else (:[]) <$> rowToRow True headRow
+       rows <- mapM (rowToRow False) bodyRows
+       caption <- case capt of
+                       [] -> pure Nothing
+                       _ -> Just . D.Caption . D.para <$> inlinesToDjot capt
+       pure $ D.addAttr (toDjotAttr attr) <$> D.table caption (hrows <> rows)
+     else do -- table can't be represented as a simple pipe table, use list
+       tableList <- D.bulletList D.Loose <$> mapM
+                     (fmap (D.bulletList D.Loose) . mapM blocksToDjot)
+                      (headRow:bodyRows)
+       pure $ D.addAttr (D.Attr [("class", "table")]) <$> tableList
+
+inlinesToDjot :: PandocMonad m => [Inline] -> StateT DjotState m D.Inlines
+inlinesToDjot = fmap mconcat . mapM inlineToDjot
+
+inlineToDjot :: PandocMonad m => Inline -> StateT DjotState m D.Inlines
+inlineToDjot (Str t) = pure $ D.str (fromText t)
+inlineToDjot Space = pure $ D.str " "
+inlineToDjot SoftBreak = pure D.softBreak
+inlineToDjot LineBreak = pure D.hardBreak
+inlineToDjot (Emph ils) = D.emph <$> inlinesToDjot ils
+inlineToDjot (Underline ils) =
+  fmap (D.addAttr (D.Attr [("class","underline")])) . D.span_
+    <$> inlinesToDjot ils
+inlineToDjot (Strong ils) = D.strong <$> inlinesToDjot ils
+inlineToDjot (Strikeout ils) = D.delete <$> inlinesToDjot ils
+inlineToDjot (Subscript ils) = D.subscript <$> inlinesToDjot ils
+inlineToDjot (Superscript ils) = D.superscript <$> inlinesToDjot ils
+inlineToDjot (Span ("",["mark"],[]) ils) = D.highlight <$> inlinesToDjot ils
+inlineToDjot (Span attr@(ident,cls,kvs) ils)
+  | Just "1" <- lookup "wrapper" kvs
+    = fmap (D.addAttr
+            (toDjotAttr (ident,cls,filter (\(k,_) -> k /= "wrapper") kvs)))
+       <$> inlinesToDjot ils
+  | otherwise
+    = fmap (D.addAttr (toDjotAttr attr)) . D.span_ <$> inlinesToDjot ils
+inlineToDjot (SmallCaps ils) =
+  fmap (D.addAttr (D.Attr [("class","smallcaps")])) . D.span_
+    <$> inlinesToDjot ils
+inlineToDjot (Quoted DoubleQuote ils) = D.doubleQuoted <$> inlinesToDjot ils
+inlineToDjot (Quoted SingleQuote ils) = D.singleQuoted <$> inlinesToDjot ils
+inlineToDjot (Cite _cs ils) = inlinesToDjot ils
+inlineToDjot (Code attr t) =
+  pure $ D.addAttr (toDjotAttr attr) <$> D.verbatim (fromText t)
+inlineToDjot (Math mt t) =
+  pure $ (if mt == InlineMath
+             then D.inlineMath
+             else D.displayMath) (fromText t)
+inlineToDjot (RawInline (Format f) t) =
+  pure $ D.rawInline (D.Format (fromText f)) (fromText t)
+inlineToDjot (Link attr ils (src,tit)) = do
+  opts <- gets options
+  description <- inlinesToDjot ils
+  let ilstring = stringify ils
+  let autolink = ilstring == src
+  let email = ("mailto:" <> ilstring) == src
+  let removeClass name (ident, cls, kvs) = (ident, filter (/= name) cls, kvs)
+  let attr' = D.Attr [("title", fromText tit) | not (T.null tit)] <>
+               toDjotAttr ( (if autolink
+                                then removeClass "uri"
+                                else id) .
+                            (if email
+                                then removeClass "email"
+                                else id) $ attr)
+  case () of
+    _ | autolink -> pure $ D.addAttr attr' <$> D.urlLink (fromText ilstring)
+      | email -> pure $ D.addAttr attr' <$> D.emailLink (fromText ilstring)
+      | writerReferenceLinks opts
+        -> do refs@(D.ReferenceMap m) <- gets references
+              autoRefs <- gets autoReferences
+              let lab' = D.inlinesToByteString description
+              lab <- case D.lookupReference lab' (refs <> autoRefs) of
+                       Just _ -> pure lab'
+                       Nothing -> do
+                         let refnum = M.size m + 1
+                         let lab = fromText $ tshow refnum
+                         modify $ \st -> st{ references =
+                                               D.insertReference lab
+                                                 (fromText src, attr') refs }
+                         pure lab
+              pure $ D.addAttr attr' <$> D.link description (D.Reference lab)
+      | otherwise
+         -> pure $ D.addAttr attr' <$> D.link description (D.Direct (fromText src))
+inlineToDjot (Image attr ils (src,tit)) = do
+  opts <- gets options
+  description <- inlinesToDjot ils
+  let attr' = D.Attr [("title", fromText tit) | not (T.null tit)] <>
+                toDjotAttr attr
+  if writerReferenceLinks opts
+     then do
+       refs@(D.ReferenceMap m) <- gets references
+       let refnum = M.size m + 1
+       let lab = fromText $ tshow refnum
+       modify $ \st -> st{ references =
+                             D.insertReference lab
+                               (fromText src, attr') refs }
+       pure $ D.addAttr attr' <$> D.image description (D.Reference lab)
+     else pure $ D.addAttr attr' <$> D.image description (D.Direct (fromText src))
+inlineToDjot (Note bs) = do
+  notes@(D.NoteMap m) <- gets footnotes
+  let notenum = M.size m + 1
+  let lab = fromText $ tshow notenum
+  contents <- blocksToDjot bs
+  modify $ \st -> st{ footnotes = D.insertNote lab contents notes }
+  pure $ D.footnoteReference lab
+
+toDjotAttr :: (Text, [Text], [(Text, Text)]) -> D.Attr
+toDjotAttr (ident, classes, kvs) =
+  D.Attr $ [("id", fromText ident) | not (T.null ident)] ++
+           [("class", fromText (T.unwords classes)) | not (null classes)] ++
+           map (\(k,v) -> (fromText k, fromText v)) kvs
diff --git a/src/Text/Pandoc/Writers/DocBook.hs b/src/Text/Pandoc/Writers/DocBook.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Writers/DocBook.hs
@@ -0,0 +1,525 @@
+{-# LANGUAGE LambdaCase        #-}
+{-# LANGUAGE OverloadedStrings #-}
+{-# LANGUAGE PatternGuards     #-}
+{- |
+   Module      : Text.Pandoc.Writers.DocBook
+   Copyright   : Copyright (C) 2006-2024 John MacFarlane
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : John MacFarlane <jgm@berkeley.edu>
+   Stability   : alpha
+   Portability : portable
+
+Conversion of 'Pandoc' documents to DocBook XML.
+-}
+module Text.Pandoc.Writers.DocBook ( writeDocBook4, writeDocBook5 ) where
+import Control.Monad.Reader
+import Data.Generics (everywhere, mkT)
+import Data.List (nub, partition)
+import Data.Maybe (isNothing)
+import Data.Monoid (All (..))
+import Data.Text (Text)
+import qualified Data.Text as T
+import qualified Text.Pandoc.Builder as B
+import Text.Pandoc.Class.PandocMonad (PandocMonad, report)
+import Text.Pandoc.Definition
+import Text.Pandoc.Highlighting (languages, languagesByExtension)
+import Text.Pandoc.ImageSize
+import Text.Pandoc.Logging
+import Text.Pandoc.Options
+import Text.DocLayout
+import Text.Pandoc.Shared
+import Text.Pandoc.URI
+import Text.Pandoc.Templates (renderTemplate)
+import Text.Pandoc.Writers.Shared
+import Text.Pandoc.Walk
+import Text.Pandoc.Writers.Math
+import Text.Pandoc.XML
+import Text.TeXMath
+import qualified Text.XML.Light as Xml
+
+data DocBookVersion = DocBook4 | DocBook5
+     deriving (Eq, Show)
+
+type DB = ReaderT DocBookVersion
+
+-- | Get level of the top-level headers based on the configured top-level division.
+-- The header level can then be used to determine appropriate DocBook element
+-- for each subdivision associated with a header.
+-- The numbering here follows LaTeX's internal numbering
+getStartLvl :: WriterOptions -> Int
+getStartLvl opts =
+  case writerTopLevelDivision opts of
+       TopLevelPart    -> -1
+       TopLevelChapter -> 0
+       TopLevelSection -> 1
+       TopLevelDefault -> 1
+
+-- | Get correct name for the id attribute based on DocBook version.
+-- DocBook 4 used custom id attribute but DocBook 5 adopted the xml:id specification.
+-- https://www.w3.org/TR/xml-id/
+idName :: DocBookVersion -> Text
+idName DocBook5 = "xml:id"
+idName DocBook4 = "id"
+
+-- | Convert list of authors to a docbook <author> section
+authorToDocBook :: PandocMonad m => WriterOptions -> [Inline] -> DB m B.Inlines
+authorToDocBook opts name' = do
+  name <- render Nothing <$> inlinesToDocBook opts name'
+  let colwidth = if writerWrapText opts == WrapAuto
+                    then Just $ writerColumns opts
+                    else Nothing
+  return $ B.rawInline "docbook" $
+    render colwidth $ inTags True "personname" [] $
+      if T.any (== ',') name
+         then -- last name first
+              let (lastname, rest) = T.break (==',') name
+                  firstname = triml rest in
+              inTagsSimple "firstname" (literal $ escapeStringForXML firstname) <>
+              inTagsSimple "surname" (literal $ escapeStringForXML lastname)
+         else -- last name last
+              let namewords = T.words name
+                  lengthname = length namewords
+                  (firstname, lastname) = case lengthname of
+                    0 -> ("","")
+                    1 -> ("", name)
+                    n -> (T.unwords (take (n-1) namewords), last namewords)
+               in inTagsSimple "firstname" (literal $ escapeStringForXML firstname) $$
+                  inTagsSimple "surname" (literal $ escapeStringForXML lastname)
+
+writeDocBook4 :: PandocMonad m => WriterOptions -> Pandoc -> m Text
+writeDocBook4 opts d =
+  runReaderT (writeDocBook opts d) DocBook4
+
+writeDocBook5 :: PandocMonad m => WriterOptions -> Pandoc -> m Text
+writeDocBook5 opts d =
+  runReaderT (writeDocBook opts d) DocBook5
+
+-- | Convert Pandoc document to string in DocBook format.
+writeDocBook :: PandocMonad m => WriterOptions -> Pandoc -> DB m Text
+writeDocBook opts doc = do
+  let Pandoc meta blocks = ensureValidXmlIdentifiers doc
+  let colwidth = if writerWrapText opts == WrapAuto
+                    then Just $ writerColumns opts
+                    else Nothing
+  let startLvl = getStartLvl opts
+  let fromBlocks = blocksToDocBook opts .
+                   makeSections False (Just startLvl)
+  auths' <- mapM (authorToDocBook opts) $ docAuthors meta
+  let meta' = B.setMeta "author" auths' meta
+  metadata <- metaToContext opts
+                 fromBlocks
+                 (inlinesToDocBook opts)
+                 meta'
+  main <- fromBlocks blocks
+  let context = defField "body" main
+              $ defField "mathml" (case writerHTMLMathMethod opts of
+                                          MathML -> True
+                                          _      -> False) metadata
+  return $ render colwidth $
+    (if writerPreferAscii opts then fmap toEntities else id) $
+    case writerTemplate opts of
+         Nothing  -> main
+         Just tpl -> renderTemplate tpl context
+
+-- | Convert a list of Pandoc blocks to DocBook.
+blocksToDocBook :: PandocMonad m => WriterOptions -> [Block] -> DB m (Doc Text)
+blocksToDocBook opts = fmap vcat . mapM (blockToDocBook opts)
+
+-- | Auxiliary function to convert Plain block to Para.
+plainToPara :: Block -> Block
+plainToPara (Plain x) = Para x
+plainToPara x         = x
+
+-- | Convert a list of pairs of terms and definitions into a list of
+-- DocBook varlistentrys.
+deflistItemsToDocBook :: PandocMonad m
+                      => WriterOptions -> [([Inline],[[Block]])]
+                      -> DB m (Doc Text)
+deflistItemsToDocBook opts items =
+  vcat <$> mapM (uncurry (deflistItemToDocBook opts)) items
+
+-- | Convert a term and a list of blocks into a DocBook varlistentry.
+deflistItemToDocBook :: PandocMonad m
+                     => WriterOptions -> [Inline] -> [[Block]]
+                     -> DB m (Doc Text)
+deflistItemToDocBook opts term defs = do
+  term' <- inlinesToDocBook opts term
+  def' <- blocksToDocBook opts $ concatMap (map plainToPara) defs
+  return $ inTagsIndented "varlistentry" $
+      inTagsIndented "term" term' $$
+      inTagsIndented "listitem" def'
+
+-- | Convert a list of lists of blocks to a list of DocBook list items.
+listItemsToDocBook :: PandocMonad m
+                   => WriterOptions -> [[Block]] -> DB m (Doc Text)
+listItemsToDocBook opts items = vcat <$> mapM (listItemToDocBook opts) items
+
+-- | Convert a list of blocks into a DocBook list item.
+listItemToDocBook :: PandocMonad m
+                  => WriterOptions -> [Block] -> DB m (Doc Text)
+listItemToDocBook opts item =
+  inTagsIndented "listitem" <$> blocksToDocBook opts (map plainToPara item)
+
+imageToDocBook :: WriterOptions -> Attr -> Text -> Doc Text
+imageToDocBook _ attr src = selfClosingTag "imagedata" $
+  ("fileref", src) : idAndRole attr <> dims
+  where
+    dims = go Width "width" <> go Height "depth"
+    go dir dstr = case dimension dir attr of
+                    Just a  -> [(dstr, tshow a)]
+                    Nothing -> []
+
+-- | Convert a Pandoc block element to DocBook.
+blockToDocBook :: PandocMonad m => WriterOptions -> Block -> DB m (Doc Text)
+-- Add ids to paragraphs in divs with ids - this is needed for
+-- pandoc-citeproc to get link anchors in bibliographies:
+blockToDocBook opts (Div (id',"section":_classes,divattrs)
+                     (Header lvl (_,hclasses,_) ils : xs)) = do
+  version <- ask
+  -- DocBook doesn't allow sections with no content, so insert some if needed
+  let bs = if null xs
+              then [Para []]
+              else xs
+      tag = case lvl of
+                 -1                   -> "part"
+                 0                    -> "chapter"
+                 n | n >= 1 && n <= 5 -> if version == DocBook5
+                                              then "section"
+                                              else "sect" <> tshow n
+                 _                    -> "simplesect"
+      idAttr = [(idName version, writerIdentifierPrefix opts <> id') | not (T.null id')]
+      -- We want to add namespaces to the root (top-level) element.
+      nsAttr = if version == DocBook5 && lvl == getStartLvl opts && isNothing (writerTemplate opts)
+      -- Though, DocBook 4 does not support namespaces and
+      -- standalone documents will include them in the template.
+                 then [("xmlns", "http://docbook.org/ns/docbook")
+                      ,("xmlns:xlink", "http://www.w3.org/1999/xlink")]
+                 else []
+
+      -- Populate miscAttr with Header.Attr.attributes, filtering out non-valid DocBook section attributes, id, and xml:id
+      -- Also enrich the role attribute with certain class tokens
+      miscAttr = enrichRole (filter (isSectionAttr version) divattrs) hclasses
+      attribs = nsAttr <> idAttr <> miscAttr
+  title' <- inlinesToDocBook opts ils
+  contents <- blocksToDocBook opts bs
+  return $ inTags True tag attribs $ inTagsSimple "title" title' $$ contents
+blockToDocBook opts (Div (ident,classes,_) bs) = do
+  version <- ask
+  let identAttribs = [(idName version, ident) | not (T.null ident)]
+      admonitions = ["caution","danger","important","note","tip","warning"]
+  case classes of
+    (l:_) | l `elem` admonitions -> do
+        let (mTitleBs, bodyBs) =
+                case bs of
+                  -- Matches AST produced by the DocBook reader → Markdown writer → Markdown reader chain.
+                  (Div (_,["title"],_) [Para ts] : rest) -> (Just (inlinesToDocBook opts ts), rest)
+                  -- Matches AST produced by the DocBook reader.
+                  (Div (_,["title"],_) ts : rest) -> (Just (blocksToDocBook opts ts), rest)
+                  _ -> (Nothing, bs)
+        admonitionTitle <- case mTitleBs of
+                              Nothing -> return mempty
+                              -- id will be attached to the admonition so let’s pass empty identAttrs.
+                              Just titleBs -> inTagsSimple "title" <$> titleBs
+        admonitionBody <- handleDivBody [] bodyBs
+        return (inTags True l identAttribs (admonitionTitle $$ admonitionBody))
+    _ -> handleDivBody identAttribs bs
+  where
+    handleDivBody identAttribs [Para lst] =
+      if hasLineBreaks lst
+         then flush . nowrap . inTags False "literallayout" identAttribs
+                             <$> inlinesToDocBook opts lst
+         else inTags True "para" identAttribs <$> inlinesToDocBook opts lst
+    handleDivBody identAttribs bodyBs = do
+      contents <- blocksToDocBook opts (map plainToPara bodyBs)
+      return $
+        (if null identAttribs
+            then mempty
+            else selfClosingTag "anchor" identAttribs) $$ contents
+blockToDocBook _ h@Header{} = do
+  -- should be handled by Div section above, except inside lists/blockquotes
+  report $ BlockNotRendered h
+  return empty
+blockToDocBook opts (Plain lst) = inlinesToDocBook opts lst
+blockToDocBook opts (Para lst)
+  | hasLineBreaks lst = flush . nowrap . inTagsSimple "literallayout"
+                        <$> inlinesToDocBook opts lst
+  | otherwise         = inTagsIndented "para" <$> inlinesToDocBook opts lst
+blockToDocBook opts (LineBlock lns) =
+  inTags False "literallayout" [] . vcat <$> mapM (inlinesToDocBook opts) lns
+blockToDocBook opts (BlockQuote blocks) =
+  inTagsIndented "blockquote" <$> blocksToDocBook opts blocks
+blockToDocBook opts (CodeBlock (_,classes,_) str) = return $
+  literal ("<programlisting" <> lang <> ">") <> cr <>
+     flush (literal (escapeStringForXML str) <> cr <> literal "</programlisting>")
+    where lang  = case langs of
+                     [] -> ""
+                     (l:_) -> " language=\"" <> escapeStringForXML l <> "\""
+          syntaxMap = writerSyntaxMap opts
+          isLang l    = T.toLower l `elem` map T.toLower (languages syntaxMap)
+          langsFrom s = if isLang s
+                           then [s]
+                           else (languagesByExtension syntaxMap) . T.toLower $ s
+          langs       = concatMap langsFrom classes
+blockToDocBook opts (BulletList lst) = do
+  let attribs = [("spacing", "compact") | isTightList lst]
+  inTags True "itemizedlist" attribs <$> listItemsToDocBook opts lst
+blockToDocBook _ (OrderedList _ []) = return empty
+blockToDocBook opts (OrderedList (start, numstyle, _) items) = do
+  let numeration = case numstyle of
+                       DefaultStyle -> []
+                       Decimal      -> [("numeration", "arabic")]
+                       Example      -> [("numeration", "arabic")]
+                       UpperAlpha   -> [("numeration", "upperalpha")]
+                       LowerAlpha   -> [("numeration", "loweralpha")]
+                       UpperRoman   -> [("numeration", "upperroman")]
+                       LowerRoman   -> [("numeration", "lowerroman")]
+      spacing    = [("spacing", "compact") | isTightList items]
+      startnum   = [("startingnumber", tshow start) | start /= 1]
+      attribs    = numeration <> spacing <> startnum
+  inTags True "orderedlist" attribs <$> listItemsToDocBook opts items
+blockToDocBook opts (DefinitionList lst) = do
+  let attribs = [("spacing", "compact") | isTightList $ concatMap snd lst]
+  inTags True "variablelist" attribs <$> deflistItemsToDocBook opts lst
+blockToDocBook _ b@(RawBlock f str)
+  | f == "docbook" = return $ literal str -- raw XML block
+  | f == "html"    = do
+                     version <- ask
+                     if version == DocBook5
+                        then return empty -- No html in DocBook5
+                        else return $ literal str -- allow html for backwards
+                                                  -- compatibility
+  | otherwise      = do
+      report $ BlockNotRendered b
+      return empty
+blockToDocBook _ HorizontalRule = return empty -- not semantic
+blockToDocBook opts (Table _ blkCapt specs thead tbody tfoot) = do
+  let (caption, aligns, widths, headers, rows) =
+        toLegacyTable blkCapt specs thead tbody tfoot
+  captionDoc <- if null caption
+                   then return empty
+                   else inTagsSimple "title" <$>
+                         inlinesToDocBook opts caption
+  let tableType    = if isEmpty captionDoc then "informaltable" else "table"
+      percent w    = tshow (truncate (100*w) :: Integer) <> "*"
+      coltags = vcat $ zipWith (\w al -> selfClosingTag "colspec"
+                       ([("colwidth", percent w) | w > 0] <>
+                        [("align", alignmentToString al)])) widths aligns
+  head' <- if all null headers
+              then return empty
+              else inTagsIndented "thead" <$> tableRowToDocBook opts headers
+  body' <- inTagsIndented "tbody" . vcat <$>
+              mapM (tableRowToDocBook opts) rows
+  return $ inTagsIndented tableType $ captionDoc $$
+        inTags True "tgroup" [("cols", tshow (length aligns))] (
+         coltags $$ head' $$ body')
+blockToDocBook opts (Figure attr capt@(Caption _ caption) body) = do
+  -- TODO: probably better to handle nested figures as mediaobject
+  let isAcceptable = \case
+        Table {}  -> All False
+        Figure {} -> All False
+        _         -> All True
+  if not . getAll $ query isAcceptable body
+    -- Fallback to a div if the content cannot be included in a figure
+    then blockToDocBook opts $ figureDiv attr capt body
+    else do
+      title <- inlinesToDocBook opts (blocksToInlines caption)
+      let toMediaobject = \case
+            Plain [Image imgAttr inlns (src, _)] -> do
+              alt <- inlinesToDocBook opts inlns
+              pure $ inTagsIndented "mediaobject" (
+                inTagsIndented "imageobject"
+                (imageToDocBook opts imgAttr src) $$
+                if isEmpty alt
+                then empty
+                else inTagsSimple "textobject" (inTagsSimple "phrase" alt))
+            _ -> ask >>= \case
+                   DocBook4 -> pure mempty -- docbook4 requires media
+                   DocBook5 -> blocksToDocBook opts body
+      mediaobjects <- mapM toMediaobject body
+      return $
+        if isEmpty $ mconcat mediaobjects
+        then mempty -- figures must have at least some content
+        else inTagsIndented "figure" $
+             inTagsSimple "title" title $$
+             mconcat mediaobjects
+
+alignmentToString :: Alignment -> Text
+alignmentToString alignment = case alignment of
+                                 AlignLeft    -> "left"
+                                 AlignRight   -> "right"
+                                 AlignCenter  -> "center"
+                                 AlignDefault -> "left"
+
+tableRowToDocBook :: PandocMonad m
+                  => WriterOptions
+                  -> [[Block]]
+                  -> DB m (Doc Text)
+tableRowToDocBook opts cols =
+  inTagsIndented "row" . vcat <$> mapM (tableItemToDocBook opts) cols
+
+tableItemToDocBook :: PandocMonad m
+                   => WriterOptions
+                   -> [Block]
+                   -> DB m (Doc Text)
+tableItemToDocBook opts item =
+  inTags True "entry" [] . vcat <$> mapM (blockToDocBook opts) item
+
+-- | Convert a list of inline elements to DocBook.
+inlinesToDocBook :: PandocMonad m => WriterOptions -> [Inline] -> DB m (Doc Text)
+inlinesToDocBook opts lst = hcat <$> mapM (inlineToDocBook opts) lst
+
+-- | Convert an inline element to DocBook.
+inlineToDocBook :: PandocMonad m => WriterOptions -> Inline -> DB m (Doc Text)
+inlineToDocBook _ (Str str) = return $ literal $ escapeStringForXML str
+inlineToDocBook opts (Emph lst) =
+  inTagsSimple "emphasis" <$> inlinesToDocBook opts lst
+inlineToDocBook opts (Underline lst) =
+  inTags False "emphasis" [("role", "underline")] <$> inlinesToDocBook opts lst
+inlineToDocBook opts (Strong lst) =
+  inTags False "emphasis" [("role", "strong")] <$> inlinesToDocBook opts lst
+inlineToDocBook opts (Strikeout lst) =
+  inTags False "emphasis" [("role", "strikethrough")] <$>
+  inlinesToDocBook opts lst
+inlineToDocBook opts (Superscript lst) =
+  inTagsSimple "superscript" <$> inlinesToDocBook opts lst
+inlineToDocBook opts (Subscript lst) =
+  inTagsSimple "subscript" <$> inlinesToDocBook opts lst
+inlineToDocBook opts (SmallCaps lst) =
+  inTags False "emphasis" [("role", "smallcaps")] <$>
+  inlinesToDocBook opts lst
+inlineToDocBook opts (Quoted _ lst) =
+  inTagsSimple "quote" <$> inlinesToDocBook opts lst
+inlineToDocBook opts (Cite _ lst) =
+  inlinesToDocBook opts lst
+inlineToDocBook opts (Span (ident,_,_) ils) = do
+  version <- ask
+  ((if T.null ident
+       then mempty
+       else selfClosingTag "anchor" [(idName version, ident)]) <>) <$>
+    inlinesToDocBook opts ils
+inlineToDocBook _ (Code _ str) =
+  return $ inTagsSimple "literal" $ literal (escapeStringForXML str)
+inlineToDocBook opts (Math t str)
+  | isMathML (writerHTMLMathMethod opts) = do
+    res <- convertMath writeMathML t str
+    case res of
+         Right r  -> return $ inTagsSimple tagtype
+                     $ literal $ T.pack $ Xml.ppcElement conf
+                     $ fixNS
+                     $ removeAttr r
+         Left il  -> inlineToDocBook opts il
+  | otherwise =
+     texMathToInlines t str >>= inlinesToDocBook opts
+     where tagtype = case t of
+                       InlineMath  -> "inlineequation"
+                       DisplayMath -> "informalequation"
+           conf = Xml.useShortEmptyTags (const False) Xml.defaultConfigPP
+           removeAttr e = e{ Xml.elAttribs = [] }
+           fixNS' qname = qname{ Xml.qPrefix = Just "mml" }
+           fixNS = everywhere (mkT fixNS')
+inlineToDocBook _ il@(RawInline f x)
+  | f == "html" || f == "docbook" = return $ literal x
+  | otherwise                     = do
+      report $ InlineNotRendered il
+      return empty
+inlineToDocBook _ LineBreak = return $ literal "\n"
+-- currently ignore, would require the option to add custom
+-- styles to the document
+inlineToDocBook _ Space = return space
+-- because we use \n for LineBreak, we can't do soft breaks:
+inlineToDocBook _ SoftBreak = return space
+inlineToDocBook opts (Link attr txt (src, _))
+  | Just email <- T.stripPrefix "mailto:" src =
+      let emailLink = inTagsSimple "email" $ literal $
+                      escapeStringForXML email
+      in  case txt of
+           [Str s] | escapeURI s == email -> return emailLink
+           _             -> do contents <- inlinesToDocBook opts txt
+                               return $ contents <+>
+                                          char '(' <> emailLink <> char ')'
+  | otherwise = do
+      version <- ask
+      (if "#" `T.isPrefixOf` src
+            then let tag = if null txt then "xref" else "link"
+                 in  inTags False tag $
+                     ("linkend", writerIdentifierPrefix opts <> T.drop 1 src) :
+                     idAndRole attr
+            else if version == DocBook5
+                    then inTags False "link" $ ("xlink:href", src) : idAndRole attr
+                    else inTags False "ulink" $ ("url", src) : idAndRole attr )
+        <$> inlinesToDocBook opts txt
+inlineToDocBook opts (Image attr ils (src, tit)) = return $
+  let titleDoc = if T.null tit
+                   then empty
+                   else inTagsIndented "objectinfo" $
+                        inTagsSimple "title" (literal $ escapeStringForXML tit)
+      alt = if null ils
+               then mempty
+               else inTagsIndented "textobject" $
+                    inTagsSimple "phrase" $ literal (stringify ils)
+  in  inTagsIndented "inlinemediaobject" $
+        inTagsIndented "imageobject"
+          (titleDoc $$ imageToDocBook opts attr src)
+        $$ alt
+inlineToDocBook opts (Note contents) =
+  inTagsIndented "footnote" <$> blocksToDocBook opts contents
+
+isMathML :: HTMLMathMethod -> Bool
+isMathML MathML = True
+isMathML _      = False
+
+idAndRole :: Attr -> [(Text, Text)]
+idAndRole (id',cls,_) = ident <> role
+  where
+    ident = [("id", id') | not (T.null id')]
+    role  = [("role", T.unwords cls) | not (null cls)]
+
+-- Used in blockToDocBook for Header (section) to create or extend
+-- the role attribute with candidate class tokens
+enrichRole :: [(Text, Text)] -> [Text] -> [(Text, Text)]
+enrichRole mattrs cls = [("role", T.unwords roles) | roles /= []] <> nonRole
+  where
+    (roleAttr, nonRole) = partition (\(key, _v) -> key == "role") mattrs
+    roles = nub $ filter (`elem` cand) cls <> map snd roleAttr
+    cand = ["unnumbered"]
+
+isSectionAttr :: DocBookVersion -> (Text, Text) -> Bool
+isSectionAttr _ ("label",_) = True
+isSectionAttr _ ("status",_) = True
+isSectionAttr DocBook5 ("annotations",_) = True
+isSectionAttr DocBook5 ("dir","ltr") = True
+isSectionAttr DocBook5 ("dir","rtl") = True
+isSectionAttr DocBook5 ("dir","lro") = True
+isSectionAttr DocBook5 ("dir","rlo") = True
+isSectionAttr _ ("remap",_) = True
+isSectionAttr _ ("revisionflag","changed") = True
+isSectionAttr _ ("revisionflag","added") = True
+isSectionAttr _ ("revisionflag","deleted") = True
+isSectionAttr _ ("revisionflag","off") = True
+isSectionAttr _ ("role",_) = True
+isSectionAttr DocBook5 ("version",_) = True
+isSectionAttr DocBook5 ("xml:base",_) = True
+isSectionAttr DocBook5 ("xml:lang",_) = True
+isSectionAttr _ ("xreflabel",_) = True
+isSectionAttr DocBook5 ("linkend",_) = True
+isSectionAttr DocBook5 ("linkends",_) = True
+isSectionAttr DocBook5 ("xlink:actuate",_) = True
+isSectionAttr DocBook5 ("xlink:arcrole",_) = True
+isSectionAttr DocBook5 ("xlink:from",_) = True
+isSectionAttr DocBook5 ("xlink:href",_) = True
+isSectionAttr DocBook5 ("xlink:label",_) = True
+isSectionAttr DocBook5 ("xlink:role",_) = True
+isSectionAttr DocBook5 ("xlink:show",_) = True
+isSectionAttr DocBook5 ("xlink:title",_) = True
+isSectionAttr DocBook5 ("xlink:to",_) = True
+isSectionAttr DocBook5 ("xlink:type",_) = True
+isSectionAttr DocBook4 ("arch",_) = True
+isSectionAttr DocBook4 ("condition",_) = True
+isSectionAttr DocBook4 ("conformance",_) = True
+isSectionAttr DocBook4 ("lang",_) = True
+isSectionAttr DocBook4 ("os",_) = True
+isSectionAttr DocBook4 ("revision",_) = True
+isSectionAttr DocBook4 ("security",_) = True
+isSectionAttr DocBook4 ("vendor",_) = True
+isSectionAttr _ (_,_) = False
diff --git a/src/Text/Pandoc/Writers/Docbook.hs b/src/Text/Pandoc/Writers/Docbook.hs
deleted file mode 100644
--- a/src/Text/Pandoc/Writers/Docbook.hs
+++ /dev/null
@@ -1,445 +0,0 @@
-{-# LANGUAGE OverloadedStrings #-}
-{-# LANGUAGE PatternGuards     #-}
-{-
-Copyright (C) 2006-2017 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-2017 John MacFarlane
-   License     : GNU GPL, version 2 or above
-
-   Maintainer  : John MacFarlane <jgm@berkeley.edu>
-   Stability   : alpha
-   Portability : portable
-
-Conversion of 'Pandoc' documents to Docbook XML.
--}
-module Text.Pandoc.Writers.Docbook ( writeDocbook4, writeDocbook5 ) where
-import Control.Monad.Reader
-import Data.Char (toLower)
-import Data.Generics (everywhere, mkT)
-import Data.List (isPrefixOf, isSuffixOf, stripPrefix)
-import Data.Monoid (Any (..))
-import Data.Text (Text)
-import qualified Text.Pandoc.Builder as B
-import Text.Pandoc.Class (PandocMonad, report)
-import Text.Pandoc.Definition
-import Text.Pandoc.Highlighting (languages, languagesByExtension)
-import Text.Pandoc.ImageSize
-import Text.Pandoc.Logging
-import Text.Pandoc.Options
-import Text.Pandoc.Pretty
-import Text.Pandoc.Shared
-import Text.Pandoc.Templates (renderTemplate')
-import Text.Pandoc.Walk
-import Text.Pandoc.Writers.Math
-import Text.Pandoc.Writers.Shared
-import Text.Pandoc.XML
-import Text.TeXMath
-import qualified Text.XML.Light as Xml
-
-data DocBookVersion = DocBook4 | DocBook5
-     deriving (Eq, Show)
-
-type DB = ReaderT DocBookVersion
-
--- | Convert list of authors to a docbook <author> section
-authorToDocbook :: PandocMonad m => WriterOptions -> [Inline] -> DB m B.Inlines
-authorToDocbook opts name' = do
-  name <- render Nothing <$> inlinesToDocbook opts name'
-  let colwidth = if writerWrapText opts == WrapAuto
-                    then Just $ writerColumns opts
-                    else Nothing
-  return $ B.rawInline "docbook" $ render colwidth $
-      if ',' `elem` name
-         then -- last name first
-              let (lastname, rest) = break (==',') name
-                  firstname = triml rest in
-              inTagsSimple "firstname" (text $ escapeStringForXML firstname) <>
-              inTagsSimple "surname" (text $ escapeStringForXML lastname)
-         else -- last name last
-              let namewords = words name
-                  lengthname = length namewords
-                  (firstname, lastname) = case lengthname of
-                    0 -> ("","")
-                    1 -> ("", name)
-                    n -> (unwords (take (n-1) namewords), last namewords)
-               in inTagsSimple "firstname" (text $ escapeStringForXML firstname) $$
-                  inTagsSimple "surname" (text $ escapeStringForXML lastname)
-
-writeDocbook4 :: PandocMonad m => WriterOptions -> Pandoc -> m Text
-writeDocbook4 opts d =
-  runReaderT (writeDocbook opts d) DocBook4
-
-writeDocbook5 :: PandocMonad m => WriterOptions -> Pandoc -> m Text
-writeDocbook5 opts d =
-  runReaderT (writeDocbook opts d) DocBook5
-
--- | Convert Pandoc document to string in Docbook format.
-writeDocbook :: PandocMonad m => WriterOptions -> Pandoc -> DB m Text
-writeDocbook opts (Pandoc meta blocks) = do
-  let elements = hierarchicalize blocks
-  let colwidth = if writerWrapText opts == WrapAuto
-                    then Just $ writerColumns opts
-                    else Nothing
-  let render' :: Doc -> Text
-      render' = render colwidth
-  let opts'    = if maybe False (("/book>" `isSuffixOf`) . trimr)
-                            (writerTemplate opts) &&
-                     TopLevelDefault == writerTopLevelDivision opts
-                    then opts{ writerTopLevelDivision = TopLevelChapter }
-                    else opts
-  -- The numbering here follows LaTeX's internal numbering
-  let startLvl = case writerTopLevelDivision opts' of
-                   TopLevelPart    -> -1
-                   TopLevelChapter -> 0
-                   TopLevelSection -> 1
-                   TopLevelDefault -> 1
-  auths' <- mapM (authorToDocbook opts) $ docAuthors meta
-  let meta' = B.setMeta "author" auths' meta
-  metadata <- metaToJSON opts
-                 (fmap (render' . vcat) .
-                          mapM (elementToDocbook opts' startLvl) .
-                            hierarchicalize)
-                 (fmap render' . inlinesToDocbook opts')
-                 meta'
-  main <- (render' . vcat) <$> mapM (elementToDocbook opts' startLvl) elements
-  let context = defField "body" main
-              $
-                  defField "mathml" (case writerHTMLMathMethod opts of
-                                          MathML -> True
-                                          _      -> False) metadata
-  case writerTemplate opts of
-       Nothing  -> return main
-       Just tpl -> renderTemplate' tpl context
-
--- | Convert an Element to Docbook.
-elementToDocbook :: PandocMonad m => WriterOptions -> Int -> Element -> DB m Doc
-elementToDocbook opts _   (Blk block) = blockToDocbook opts block
-elementToDocbook opts lvl (Sec _ _num (id',_,_) title elements) = do
-  version <- ask
-  -- Docbook doesn't allow sections with no content, so insert some if needed
-  let elements' = if null elements
-                    then [Blk (Para [])]
-                    else elements
-      tag = case lvl of
-                 -1                   -> "part"
-                 0                    -> "chapter"
-                 n | n >= 1 && n <= 5 -> if version == DocBook5
-                                              then "section"
-                                              else "sect" ++ show n
-                 _                    -> "simplesect"
-      idName = if version == DocBook5
-                 then "xml:id"
-                 else "id"
-      idAttr = [(idName, writerIdentifierPrefix opts ++ id') | not (null id')]
-      nsAttr = if version == DocBook5 && lvl == 0 then [("xmlns", "http://docbook.org/ns/docbook"),("xmlns:xlink", "http://www.w3.org/1999/xlink")]
-                                      else []
-      attribs = nsAttr ++ idAttr
-  contents <- mapM (elementToDocbook opts (lvl + 1)) elements'
-  title' <- inlinesToDocbook opts title
-  return $ inTags True tag attribs $
-      inTagsSimple "title" title' $$ vcat contents
-
--- | Convert a list of Pandoc blocks to Docbook.
-blocksToDocbook :: PandocMonad m => WriterOptions -> [Block] -> DB m Doc
-blocksToDocbook opts = fmap vcat . mapM (blockToDocbook opts)
-
--- | Auxiliary function to convert Plain block to Para.
-plainToPara :: Block -> Block
-plainToPara (Plain x) = Para x
-plainToPara x         = x
-
--- | Convert a list of pairs of terms and definitions into a list of
--- Docbook varlistentrys.
-deflistItemsToDocbook :: PandocMonad m
-                      => WriterOptions -> [([Inline],[[Block]])] -> DB m Doc
-deflistItemsToDocbook opts items =
-  vcat <$> mapM (uncurry (deflistItemToDocbook opts)) items
-
--- | Convert a term and a list of blocks into a Docbook varlistentry.
-deflistItemToDocbook :: PandocMonad m
-                     => WriterOptions -> [Inline] -> [[Block]] -> DB m Doc
-deflistItemToDocbook opts term defs = do
-  term' <- inlinesToDocbook opts term
-  def' <- blocksToDocbook opts $ concatMap (map plainToPara) defs
-  return $ inTagsIndented "varlistentry" $
-      inTagsIndented "term" term' $$
-      inTagsIndented "listitem" def'
-
--- | Convert a list of lists of blocks to a list of Docbook list items.
-listItemsToDocbook :: PandocMonad m => WriterOptions -> [[Block]] -> DB m Doc
-listItemsToDocbook opts items = vcat <$> mapM (listItemToDocbook opts) items
-
--- | Convert a list of blocks into a Docbook list item.
-listItemToDocbook :: PandocMonad m => WriterOptions -> [Block] -> DB m Doc
-listItemToDocbook opts item =
-  inTagsIndented "listitem" <$> blocksToDocbook opts (map plainToPara item)
-
-imageToDocbook :: WriterOptions -> Attr -> String -> Doc
-imageToDocbook _ attr src = selfClosingTag "imagedata" $
-  ("fileref", src) : idAndRole attr ++ dims
-  where
-    dims = go Width "width" ++ go Height "depth"
-    go dir dstr = case dimension dir attr of
-                    Just a  -> [(dstr, show a)]
-                    Nothing -> []
-
--- | Convert a Pandoc block element to Docbook.
-blockToDocbook :: PandocMonad m => WriterOptions -> Block -> DB m Doc
-blockToDocbook _ Null = return empty
--- Add ids to paragraphs in divs with ids - this is needed for
--- pandoc-citeproc to get link anchors in bibliographies:
-blockToDocbook opts (Div (ident,_,_) [Para lst]) =
-  let attribs = [("id", ident) | not (null ident)] in
-  if hasLineBreaks lst
-     then (flush . nowrap . inTags False "literallayout" attribs)
-                         <$> inlinesToDocbook opts lst
-     else inTags True "para" attribs <$> inlinesToDocbook opts lst
-blockToDocbook opts (Div (ident,_,_) bs) = do
-  contents <- blocksToDocbook opts (map plainToPara bs)
-  return $
-    (if null ident
-        then mempty
-        else selfClosingTag "anchor" [("id", ident)]) $$ contents
-blockToDocbook _ h@Header{} = do
-  -- should not occur after hierarchicalize, except inside lists/blockquotes
-  report $ BlockNotRendered h
-  return empty
-blockToDocbook opts (Plain lst) = inlinesToDocbook opts lst
--- title beginning with fig: indicates that the image is a figure
-blockToDocbook opts (Para [Image attr txt (src,'f':'i':'g':':':_)]) = do
-  alt <- inlinesToDocbook opts txt
-  let capt = if null txt
-                then empty
-                else inTagsSimple "title" alt
-  return $ inTagsIndented "figure" $
-        capt $$
-        inTagsIndented "mediaobject" (
-           inTagsIndented "imageobject"
-             (imageToDocbook opts attr src) $$
-           inTagsSimple "textobject" (inTagsSimple "phrase" alt))
-blockToDocbook opts (Para lst)
-  | hasLineBreaks lst = (flush . nowrap . inTagsSimple "literallayout")
-                        <$> inlinesToDocbook opts lst
-  | otherwise         = inTagsIndented "para" <$> inlinesToDocbook opts lst
-blockToDocbook opts (LineBlock lns) =
-  blockToDocbook opts $ linesToPara lns
-blockToDocbook opts (BlockQuote blocks) =
-  inTagsIndented "blockquote" <$> blocksToDocbook opts blocks
-blockToDocbook _ (CodeBlock (_,classes,_) str) = return $
-  text ("<programlisting" ++ lang ++ ">") <> cr <>
-     flush (text (escapeStringForXML str) <> cr <> text "</programlisting>")
-    where lang  = if null langs
-                     then ""
-                     else " language=\"" ++ escapeStringForXML (head langs) ++
-                          "\""
-          isLang l    = map toLower l `elem` map (map toLower) languages
-          langsFrom s = if isLang s
-                           then [s]
-                           else languagesByExtension . map toLower $ s
-          langs       = concatMap langsFrom classes
-blockToDocbook opts (BulletList lst) = do
-  let attribs = [("spacing", "compact") | isTightList lst]
-  inTags True "itemizedlist" attribs <$> listItemsToDocbook opts lst
-blockToDocbook _ (OrderedList _ []) = return empty
-blockToDocbook opts (OrderedList (start, numstyle, _) (first:rest)) = do
-  let numeration = case numstyle of
-                       DefaultStyle -> []
-                       Decimal      -> [("numeration", "arabic")]
-                       Example      -> [("numeration", "arabic")]
-                       UpperAlpha   -> [("numeration", "upperalpha")]
-                       LowerAlpha   -> [("numeration", "loweralpha")]
-                       UpperRoman   -> [("numeration", "upperroman")]
-                       LowerRoman   -> [("numeration", "lowerroman")]
-      spacing    = [("spacing", "compact") | isTightList (first:rest)]
-      attribs    = numeration ++ spacing
-  items <- if start == 1
-              then listItemsToDocbook opts (first:rest)
-              else do
-                first' <- blocksToDocbook opts (map plainToPara first)
-                rest' <- listItemsToDocbook opts rest
-                return $
-                  inTags True "listitem" [("override",show start)] first' $$
-                   rest'
-  return $ inTags True "orderedlist" attribs items
-blockToDocbook opts (DefinitionList lst) = do
-  let attribs = [("spacing", "compact") | isTightList $ concatMap snd lst]
-  inTags True "variablelist" attribs <$> deflistItemsToDocbook opts lst
-blockToDocbook _ b@(RawBlock f str)
-  | f == "docbook" = return $ text str -- raw XML block
-  | f == "html"    = do
-                     version <- ask
-                     if version == DocBook5
-                        then return empty -- No html in Docbook5
-                        else return $ text str -- allow html for backwards compatibility
-  | otherwise      = do
-      report $ BlockNotRendered b
-      return empty
-blockToDocbook _ HorizontalRule = return empty -- not semantic
-blockToDocbook opts (Table caption aligns widths headers rows) = do
-  captionDoc <- if null caption
-                   then return empty
-                   else inTagsIndented "title" <$>
-                         inlinesToDocbook opts caption
-  let tableType    = if isEmpty captionDoc then "informaltable" else "table"
-      percent w    = show (truncate (100*w) :: Integer) ++ "*"
-      coltags = vcat $ zipWith (\w al -> selfClosingTag "colspec"
-                       ([("colwidth", percent w) | w > 0] ++
-                        [("align", alignmentToString al)])) widths aligns
-  head' <- if all null headers
-              then return empty
-              else inTagsIndented "thead" <$> tableRowToDocbook opts headers
-  body' <- (inTagsIndented "tbody" . vcat) <$>
-              mapM (tableRowToDocbook opts) rows
-  return $ inTagsIndented tableType $ captionDoc $$
-        inTags True "tgroup" [("cols", show (length headers))] (
-         coltags $$ head' $$ body')
-
-hasLineBreaks :: [Inline] -> Bool
-hasLineBreaks = getAny . query isLineBreak . walk removeNote
-  where
-    removeNote :: Inline -> Inline
-    removeNote (Note _) = Str ""
-    removeNote x        = x
-    isLineBreak :: Inline -> Any
-    isLineBreak LineBreak = Any True
-    isLineBreak _         = Any False
-
-alignmentToString :: Alignment -> [Char]
-alignmentToString alignment = case alignment of
-                                 AlignLeft    -> "left"
-                                 AlignRight   -> "right"
-                                 AlignCenter  -> "center"
-                                 AlignDefault -> "left"
-
-tableRowToDocbook :: PandocMonad m
-                  => WriterOptions
-                  -> [[Block]]
-                  -> DB m Doc
-tableRowToDocbook opts cols =
-  (inTagsIndented "row" . vcat) <$> mapM (tableItemToDocbook opts) cols
-
-tableItemToDocbook :: PandocMonad m
-                   => WriterOptions
-                   -> [Block]
-                   -> DB m Doc
-tableItemToDocbook opts item =
-  (inTags True "entry" [] . vcat) <$> mapM (blockToDocbook opts) item
-
--- | Convert a list of inline elements to Docbook.
-inlinesToDocbook :: PandocMonad m => WriterOptions -> [Inline] -> DB m Doc
-inlinesToDocbook opts lst = hcat <$> mapM (inlineToDocbook opts) lst
-
--- | Convert an inline element to Docbook.
-inlineToDocbook :: PandocMonad m => WriterOptions -> Inline -> DB m Doc
-inlineToDocbook _ (Str str) = return $ text $ escapeStringForXML str
-inlineToDocbook opts (Emph lst) =
-  inTagsSimple "emphasis" <$> inlinesToDocbook opts lst
-inlineToDocbook opts (Strong lst) =
-  inTags False "emphasis" [("role", "strong")] <$> inlinesToDocbook opts lst
-inlineToDocbook opts (Strikeout lst) =
-  inTags False "emphasis" [("role", "strikethrough")] <$>
-  inlinesToDocbook opts lst
-inlineToDocbook opts (Superscript lst) =
-  inTagsSimple "superscript" <$> inlinesToDocbook opts lst
-inlineToDocbook opts (Subscript lst) =
-  inTagsSimple "subscript" <$> inlinesToDocbook opts lst
-inlineToDocbook opts (SmallCaps lst) =
-  inTags False "emphasis" [("role", "smallcaps")] <$>
-  inlinesToDocbook opts lst
-inlineToDocbook opts (Quoted _ lst) =
-  inTagsSimple "quote" <$> inlinesToDocbook opts lst
-inlineToDocbook opts (Cite _ lst) =
-  inlinesToDocbook opts lst
-inlineToDocbook opts (Span (ident,_,_) ils) =
-  ((if null ident
-       then mempty
-       else selfClosingTag "anchor" [("id", ident)]) <>) <$>
-  inlinesToDocbook opts ils
-inlineToDocbook _ (Code _ str) =
-  return $ inTagsSimple "literal" $ text (escapeStringForXML str)
-inlineToDocbook opts (Math t str)
-  | isMathML (writerHTMLMathMethod opts) = do
-    res <- convertMath writeMathML t str
-    case res of
-         Right r  -> return $ inTagsSimple tagtype
-                     $ text $ Xml.ppcElement conf
-                     $ fixNS
-                     $ removeAttr r
-         Left il  -> inlineToDocbook opts il
-  | otherwise =
-     texMathToInlines t str >>= inlinesToDocbook opts
-     where tagtype = case t of
-                       InlineMath  -> "inlineequation"
-                       DisplayMath -> "informalequation"
-           conf = Xml.useShortEmptyTags (const False) Xml.defaultConfigPP
-           removeAttr e = e{ Xml.elAttribs = [] }
-           fixNS' qname = qname{ Xml.qPrefix = Just "mml" }
-           fixNS = everywhere (mkT fixNS')
-inlineToDocbook _ il@(RawInline f x)
-  | f == "html" || f == "docbook" = return $ text x
-  | otherwise                     = do
-      report $ InlineNotRendered il
-      return empty
-inlineToDocbook _ LineBreak = return $ text "\n"
--- currently ignore, would require the option to add custom
--- styles to the document
-inlineToDocbook _ Space = return space
--- because we use \n for LineBreak, we can't do soft breaks:
-inlineToDocbook _ SoftBreak = return space
-inlineToDocbook opts (Link attr txt (src, _))
-  | Just email <- stripPrefix "mailto:" src =
-      let emailLink = inTagsSimple "email" $ text $
-                      escapeStringForXML email
-      in  case txt of
-           [Str s] | escapeURI s == email -> return emailLink
-           _             -> do contents <- inlinesToDocbook opts txt
-                               return $ contents <+>
-                                          char '(' <> emailLink <> char ')'
-  | otherwise = do
-      version <- ask
-      (if "#" `isPrefixOf` src
-            then inTags False "link" $ ("linkend", writerIdentifierPrefix opts ++ drop 1 src) : idAndRole attr
-            else if version == DocBook5
-                    then inTags False "link" $ ("xlink:href", src) : idAndRole attr
-                    else inTags False "ulink" $ ("url", src) : idAndRole attr )
-        <$> inlinesToDocbook opts txt
-inlineToDocbook opts (Image attr _ (src, tit)) = return $
-  let titleDoc = if null tit
-                   then empty
-                   else inTagsIndented "objectinfo" $
-                        inTagsIndented "title" (text $ escapeStringForXML tit)
-  in  inTagsIndented "inlinemediaobject" $ inTagsIndented "imageobject" $
-      titleDoc $$ imageToDocbook opts attr src
-inlineToDocbook opts (Note contents) =
-  inTagsIndented "footnote" <$> blocksToDocbook opts contents
-
-isMathML :: HTMLMathMethod -> Bool
-isMathML MathML = True
-isMathML _      = False
-
-idAndRole :: Attr -> [(String, String)]
-idAndRole (id',cls,_) = ident ++ role
-  where
-    ident = if null id'
-               then []
-               else [("id", id')]
-    role  = if null cls
-               then []
-               else [("role", unwords cls)]
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
@@ -1,1401 +1,855 @@
-
-{-# LANGUAGE PatternGuards       #-}
-{-# LANGUAGE RankNTypes          #-}
-{-# LANGUAGE ScopedTypeVariables #-}
-{-# LANGUAGE ViewPatterns        #-}
-{-
-Copyright (C) 2012-2017 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-2017 John MacFarlane
-   License     : GNU GPL, version 2 or above
-
-   Maintainer  : John MacFarlane <jgm@berkeley.edu>
-   Stability   : alpha
-   Portability : portable
-
-Conversion of 'Pandoc' documents to docx.
--}
-module Text.Pandoc.Writers.Docx ( writeDocx ) where
-import Codec.Archive.Zip
-import Control.Applicative ((<|>))
-import Control.Monad.Except (catchError)
-import Control.Monad.Reader
-import Control.Monad.State.Strict
-import qualified Data.ByteString as B
-import qualified Data.ByteString.Lazy as BL
-import Data.Char (isSpace, ord, toLower)
-import Data.List (intercalate, isPrefixOf, isSuffixOf)
-import qualified Data.Map as M
-import Data.Maybe (fromMaybe, isNothing, mapMaybe, maybeToList)
-import qualified Data.Set as Set
-import qualified Data.Text as T
-import Data.Time.Clock.POSIX
-import Skylighting
-import System.Random (randomR)
-import Text.Pandoc.BCP47 (getLang, renderLang)
-import Text.Pandoc.Class (PandocMonad, report, toLang)
-import qualified Text.Pandoc.Class as P
-import Text.Pandoc.Compat.Time
-import Text.Pandoc.Definition
-import Text.Pandoc.Generic
-import Text.Pandoc.Highlighting (highlight)
-import Text.Pandoc.ImageSize
-import Text.Pandoc.Logging
-import Text.Pandoc.MIME (MimeType, extensionFromMimeType, getMimeType,
-                         getMimeTypeDef)
-import Text.Pandoc.Options
-import Text.Pandoc.Readers.Docx.StyleMap
-import Text.Pandoc.Shared hiding (Element)
-import Text.Pandoc.Walk
-import Text.Pandoc.Writers.Math
-import Text.Pandoc.Writers.Shared (fixDisplayMath)
-import Text.Printf (printf)
-import Text.TeXMath
-import Text.XML.Light as XML
-import Text.XML.Light.Cursor as XMLC
-import Text.Pandoc.Writers.OOXML
-
-data ListMarker = NoMarker
-                | BulletMarker
-                | NumberMarker ListNumberStyle ListNumberDelim Int
-                deriving (Show, Read, Eq, Ord)
-
-listMarkerToId :: ListMarker -> String
-listMarkerToId NoMarker = "990"
-listMarkerToId BulletMarker = "991"
-listMarkerToId (NumberMarker sty delim n) =
-  '9' : '9' : styNum : delimNum : show n
-  where styNum = case sty of
-                      DefaultStyle -> '2'
-                      Example      -> '3'
-                      Decimal      -> '4'
-                      LowerRoman   -> '5'
-                      UpperRoman   -> '6'
-                      LowerAlpha   -> '7'
-                      UpperAlpha   -> '8'
-        delimNum = case delim of
-                      DefaultDelim -> '0'
-                      Period       -> '1'
-                      OneParen     -> '2'
-                      TwoParens    -> '3'
-
-data WriterEnv = WriterEnv{ envTextProperties :: [Element]
-                          , envParaProperties :: [Element]
-                          , envRTL            :: Bool
-                          , envListLevel      :: Int
-                          , envListNumId      :: Int
-                          , envInDel          :: Bool
-                          , envChangesAuthor  :: String
-                          , envChangesDate    :: String
-                          , envPrintWidth     :: Integer
-                          }
-
-defaultWriterEnv :: WriterEnv
-defaultWriterEnv = WriterEnv{ envTextProperties = []
-                            , envParaProperties = []
-                            , envRTL = False
-                            , envListLevel = -1
-                            , envListNumId = 1
-                            , envInDel = False
-                            , envChangesAuthor  = "unknown"
-                            , envChangesDate    = "1969-12-31T19:00:00Z"
-                            , envPrintWidth     = 1
-                            }
-
-data WriterState = WriterState{
-         stFootnotes      :: [Element]
-       , stComments       :: [([(String,String)], [Inline])]
-       , stSectionIds     :: Set.Set String
-       , stExternalLinks  :: M.Map String String
-       , stImages         :: M.Map FilePath (String, String, Maybe MimeType, Element, B.ByteString)
-       , stLists          :: [ListMarker]
-       , stInsId          :: Int
-       , stDelId          :: Int
-       , stStyleMaps      :: StyleMaps
-       , stFirstPara      :: Bool
-       , stTocTitle       :: [Inline]
-       , stDynamicParaProps :: Set.Set String
-       , stDynamicTextProps :: Set.Set String
-       }
-
-defaultWriterState :: WriterState
-defaultWriterState = WriterState{
-        stFootnotes      = defaultFootnotes
-      , stComments       = []
-      , stSectionIds     = Set.empty
-      , stExternalLinks  = M.empty
-      , stImages         = M.empty
-      , stLists          = [NoMarker]
-      , stInsId          = 1
-      , stDelId          = 1
-      , stStyleMaps      = defaultStyleMaps
-      , stFirstPara      = False
-      , stTocTitle       = [Str "Table of Contents"]
-      , stDynamicParaProps = Set.empty
-      , stDynamicTextProps = Set.empty
-      }
-
-type WS m = ReaderT WriterEnv (StateT WriterState m)
-
-
-renumIdMap :: Int -> [Element] -> M.Map String String
-renumIdMap _ [] = M.empty
-renumIdMap n (e:es)
-  | Just oldId <- findAttr (QName "Id" Nothing Nothing) e =
-      M.insert oldId ("rId" ++ show n) (renumIdMap (n+1) es)
-  | otherwise = renumIdMap n es
-
-replaceAttr :: (QName -> Bool) -> String -> [XML.Attr] -> [XML.Attr]
-replaceAttr _ _ [] = []
-replaceAttr f val (a:as) | f (attrKey a) =
-                             XML.Attr (attrKey a) val : replaceAttr f val as
-                         | otherwise = a : replaceAttr f val as
-
-renumId :: (QName -> Bool) -> M.Map String String -> Element -> Element
-renumId f renumMap e
-  | Just oldId <- findAttrBy f e
-  , Just newId <- M.lookup oldId renumMap =
-    let attrs' = replaceAttr f newId (elAttribs e)
-    in
-     e { elAttribs = attrs' }
-  | otherwise = e
-
-renumIds :: (QName -> Bool) -> M.Map String String -> [Element] -> [Element]
-renumIds f renumMap = map (renumId f renumMap)
-
--- | Certain characters are invalid in XML even if escaped.
--- See #1992
-stripInvalidChars :: String -> String
-stripInvalidChars = filter isValidChar
-
--- | See XML reference
-isValidChar :: Char -> Bool
-isValidChar (ord -> c)
-  | c == 0x9                      = True
-  | c == 0xA                      = True
-  | c == 0xD                      = True
-  | 0x20 <= c &&  c <= 0xD7FF     = True
-  | 0xE000 <= c && c <= 0xFFFD    = True
-  | 0x10000 <= c && c <= 0x10FFFF = True
-  | otherwise                     = False
-
-metaValueToInlines :: MetaValue -> [Inline]
-metaValueToInlines (MetaString s)    = [Str s]
-metaValueToInlines (MetaInlines ils) = ils
-metaValueToInlines (MetaBlocks bs)   = query return bs
-metaValueToInlines (MetaBool b)      = [Str $ show b]
-metaValueToInlines _                 = []
-
-
-
-writeDocx :: (PandocMonad m)
-          => WriterOptions  -- ^ Writer options
-          -> Pandoc         -- ^ Document to convert
-          -> m BL.ByteString
-writeDocx opts doc@(Pandoc meta _) = do
-  let doc' = walk fixDisplayMath doc
-  username <- P.lookupEnv "USERNAME"
-  utctime <- P.getCurrentTime
-  distArchive <- (toArchive . BL.fromStrict) <$> do
-    oldUserDataDir <- P.getUserDataDir
-    P.setUserDataDir Nothing
-    res <- P.readDefaultDataFile "reference.docx"
-    P.setUserDataDir oldUserDataDir
-    return res
-  refArchive <- case writerReferenceDoc opts of
-                     Just f  -> toArchive <$> P.readFileLazy f
-                     Nothing -> (toArchive . BL.fromStrict) <$>
-                        P.readDataFile "reference.docx"
-
-  parsedDoc <- parseXml refArchive distArchive "word/document.xml"
-  let wname f qn = qPrefix qn == Just "w" && f (qName qn)
-  let mbsectpr = filterElementName (wname (=="sectPr")) parsedDoc
-
-  -- Gets the template size
-  let mbpgsz = mbsectpr >>= filterElementName (wname (=="pgSz"))
-  let mbAttrSzWidth = (elAttribs <$> mbpgsz) >>= lookupAttrBy ((=="w") . qName)
-
-  let mbpgmar = mbsectpr >>= filterElementName (wname (=="pgMar"))
-  let mbAttrMarLeft = (elAttribs <$> mbpgmar) >>= lookupAttrBy ((=="left") . qName)
-  let mbAttrMarRight = (elAttribs <$> mbpgmar) >>= lookupAttrBy ((=="right") . qName)
-
-  -- Get the avaible area (converting the size and the margins to int and
-  -- doing the difference
-  let pgContentWidth = (-) <$> (read <$> mbAttrSzWidth ::Maybe Integer)
-                       <*> (
-                         (+) <$> (read <$> mbAttrMarRight ::Maybe Integer)
-                         <*> (read <$> mbAttrMarLeft ::Maybe Integer)
-                       )
-
-  -- styles
-  mblang <- toLang $ getLang opts meta
-  let addLang :: Element -> Element
-      addLang e = case mblang >>= \l ->
-                         (return . XMLC.toTree . go (renderLang l)
-                                 . XMLC.fromElement) e of
-                    Just (Elem e') -> e'
-                    _              -> e -- return original
-        where go :: String -> Cursor -> Cursor
-              go l cursor = case XMLC.findRec (isLangElt . current) cursor of
-                              Nothing -> cursor
-                              Just t  -> XMLC.modifyContent (setval l) t
-              setval :: String -> Content -> Content
-              setval l (Elem e') = Elem $ e'{ elAttribs = map (setvalattr l) $
-                                               elAttribs e' }
-              setval _ x         = x
-              setvalattr :: String -> XML.Attr -> XML.Attr
-              setvalattr l (XML.Attr qn@(QName "val" _ _) _) = XML.Attr qn l
-              setvalattr _ x                                 = x
-              isLangElt (Elem e') = qName (elName e') == "lang"
-              isLangElt _         = False
-
-  let stylepath = "word/styles.xml"
-  styledoc <- addLang <$> parseXml refArchive distArchive stylepath
-
-  -- parse styledoc for heading styles
-  let styleMaps = getStyleMaps styledoc
-
-  let tocTitle = fromMaybe (stTocTitle defaultWriterState) $
-                    metaValueToInlines <$> lookupMeta "toc-title" meta
-
-  let initialSt = defaultWriterState {
-          stStyleMaps  = styleMaps
-        , stTocTitle   = tocTitle
-        }
-
-  let isRTLmeta = case lookupMeta "dir" meta of
-        Just (MetaString "rtl")        -> True
-        Just (MetaInlines [Str "rtl"]) -> True
-        _                              -> False
-
-  let env = defaultWriterEnv {
-          envRTL = isRTLmeta
-        , envChangesAuthor = fromMaybe "unknown" username
-        , envChangesDate   = formatTime defaultTimeLocale "%FT%XZ" utctime
-        , envPrintWidth = maybe 420 (\x -> quot x 20) pgContentWidth
-        }
-
-
-  ((contents, footnotes, comments), st) <- runStateT
-                         (runReaderT
-                          (writeOpenXML opts{writerWrapText = WrapNone} doc')
-                          env)
-                         initialSt
-  let epochtime = floor $ utcTimeToPOSIXSeconds utctime
-  let imgs = M.elems $ stImages st
-
-  -- create entries for images in word/media/...
-  let toImageEntry (_,path,_,_,img) = toEntry ("word/" ++ path) epochtime $ toLazy img
-  let imageEntries = map toImageEntry imgs
-
-  let stdAttributes =
-            [("xmlns:w","http://schemas.openxmlformats.org/wordprocessingml/2006/main")
-            ,("xmlns:m","http://schemas.openxmlformats.org/officeDocument/2006/math")
-            ,("xmlns:r","http://schemas.openxmlformats.org/officeDocument/2006/relationships")
-            ,("xmlns:o","urn:schemas-microsoft-com:office:office")
-            ,("xmlns:v","urn:schemas-microsoft-com:vml")
-            ,("xmlns:w10","urn:schemas-microsoft-com:office:word")
-            ,("xmlns:a","http://schemas.openxmlformats.org/drawingml/2006/main")
-            ,("xmlns:pic","http://schemas.openxmlformats.org/drawingml/2006/picture")
-            ,("xmlns:wp","http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing")]
-
-
-  parsedRels <- parseXml refArchive distArchive "word/_rels/document.xml.rels"
-  let isHeaderNode e = findAttr (QName "Type" Nothing Nothing) e == Just "http://schemas.openxmlformats.org/officeDocument/2006/relationships/header"
-  let isFooterNode e = findAttr (QName "Type" Nothing Nothing) e == Just "http://schemas.openxmlformats.org/officeDocument/2006/relationships/footer"
-  let headers = filterElements isHeaderNode parsedRels
-  let footers = filterElements isFooterNode parsedRels
-
-  let extractTarget = findAttr (QName "Target" Nothing Nothing)
-
-  -- we create [Content_Types].xml and word/_rels/document.xml.rels
-  -- from scratch rather than reading from reference.docx,
-  -- because Word sometimes changes these files when a reference.docx is modified,
-  -- e.g. deleting the reference to footnotes.xml or removing default entries
-  -- for image content types.
-
-  -- [Content_Types].xml
-  let mkOverrideNode (part', contentType') = mknode "Override"
-               [("PartName",part'),("ContentType",contentType')] ()
-  let mkImageOverride (_, imgpath, mbMimeType, _, _) =
-          mkOverrideNode ("/word/" ++ imgpath,
-                          fromMaybe "application/octet-stream" mbMimeType)
-  let mkMediaOverride imgpath =
-          mkOverrideNode ('/':imgpath, getMimeTypeDef imgpath)
-  let overrides = map mkOverrideNode (
-                  [("/word/webSettings.xml",
-                    "application/vnd.openxmlformats-officedocument.wordprocessingml.webSettings+xml")
-                  ,("/word/numbering.xml",
-                    "application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml")
-                  ,("/word/settings.xml",
-                    "application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml")
-                  ,("/word/theme/theme1.xml",
-                    "application/vnd.openxmlformats-officedocument.theme+xml")
-                  ,("/word/fontTable.xml",
-                    "application/vnd.openxmlformats-officedocument.wordprocessingml.fontTable+xml")
-                  ,("/docProps/app.xml",
-                    "application/vnd.openxmlformats-officedocument.extended-properties+xml")
-                  ,("/docProps/core.xml",
-                    "application/vnd.openxmlformats-package.core-properties+xml")
-                  ,("/word/styles.xml",
-                    "application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml")
-                  ,("/word/document.xml",
-                    "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml")
-                  ,("/word/comments.xml",
-                    "application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml")
-                  ,("/word/footnotes.xml",
-                    "application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml")
-                  ] ++
-                  map (\x -> (maybe "" ("/word/" ++) $ extractTarget x,
-                       "application/vnd.openxmlformats-officedocument.wordprocessingml.header+xml")) headers ++
-                  map (\x -> (maybe "" ("/word/" ++) $ extractTarget x,
-                       "application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml")) footers) ++
-                    map mkImageOverride imgs ++
-                    map mkMediaOverride [ eRelativePath e | e <- zEntries refArchive
-                                        , "word/media/" `isPrefixOf` eRelativePath e ]
-
-  let defaultnodes = [mknode "Default"
-              [("Extension","xml"),("ContentType","application/xml")] (),
-             mknode "Default"
-              [("Extension","rels"),("ContentType","application/vnd.openxmlformats-package.relationships+xml")] ()]
-  let contentTypesDoc = mknode "Types" [("xmlns","http://schemas.openxmlformats.org/package/2006/content-types")] $ defaultnodes ++ overrides
-  let contentTypesEntry = toEntry "[Content_Types].xml" epochtime
-        $ renderXml contentTypesDoc
-
-  -- word/_rels/document.xml.rels
-  let toBaseRel (url', id', target') = mknode "Relationship"
-                                          [("Type",url')
-                                          ,("Id",id')
-                                          ,("Target",target')] ()
-  let baserels' = map toBaseRel
-                    [("http://schemas.openxmlformats.org/officeDocument/2006/relationships/numbering",
-                      "rId1",
-                      "numbering.xml")
-                    ,("http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles",
-                      "rId2",
-                      "styles.xml")
-                    ,("http://schemas.openxmlformats.org/officeDocument/2006/relationships/settings",
-                      "rId3",
-                      "settings.xml")
-                    ,("http://schemas.openxmlformats.org/officeDocument/2006/relationships/webSettings",
-                      "rId4",
-                      "webSettings.xml")
-                    ,("http://schemas.openxmlformats.org/officeDocument/2006/relationships/fontTable",
-                      "rId5",
-                      "fontTable.xml")
-                    ,("http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme",
-                      "rId6",
-                      "theme/theme1.xml")
-                    ,("http://schemas.openxmlformats.org/officeDocument/2006/relationships/footnotes",
-                      "rId7",
-                      "footnotes.xml")
-                    ,("http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments",
-                      "rId8",
-                      "comments.xml")
-                    ]
-
-  let idMap = renumIdMap (length baserels' + 1) (headers ++ footers)
-  let renumHeaders = renumIds (\q -> qName q == "Id") idMap headers
-  let renumFooters = renumIds (\q -> qName q == "Id") idMap footers
-  let baserels = baserels' ++ renumHeaders ++ renumFooters
-  let toImgRel (ident,path,_,_,_) =  mknode "Relationship" [("Type","http://schemas.openxmlformats.org/officeDocument/2006/relationships/image"),("Id",ident),("Target",path)] ()
-  let imgrels = map toImgRel imgs
-  let toLinkRel (src,ident) =  mknode "Relationship" [("Type","http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink"),("Id",ident),("Target",src),("TargetMode","External") ] ()
-  let linkrels = map toLinkRel $ M.toList $ stExternalLinks st
-  let reldoc = mknode "Relationships" [("xmlns","http://schemas.openxmlformats.org/package/2006/relationships")] $ baserels ++ imgrels ++ linkrels
-  let relEntry = toEntry "word/_rels/document.xml.rels" epochtime
-        $ renderXml reldoc
-
-
-  -- adjust contents to add sectPr from reference.docx
-  let sectpr = case mbsectpr of
-        Just sectpr' -> let cs = renumIds
-                                 (\q -> qName q == "id" && qPrefix q == Just "r")
-                                 idMap
-                                 (elChildren sectpr')
-                        in
-                         add_attrs (elAttribs sectpr') $ mknode "w:sectPr" [] cs
-        Nothing      -> mknode "w:sectPr" [] ()
-
-  -- let sectpr = fromMaybe (mknode "w:sectPr" [] ()) mbsectpr'
-  let contents' = contents ++ [sectpr]
-  let docContents = mknode "w:document" stdAttributes
-                    $ mknode "w:body" [] contents'
-
-
-
-  -- word/document.xml
-  let contentEntry = toEntry "word/document.xml" epochtime
-                     $ renderXml docContents
-
-  -- footnotes
-  let notes = mknode "w:footnotes" stdAttributes footnotes
-  let footnotesEntry = toEntry "word/footnotes.xml" epochtime $ renderXml notes
-
-  -- footnote rels
-  let footnoteRelEntry = toEntry "word/_rels/footnotes.xml.rels" epochtime
-        $ renderXml $ mknode "Relationships" [("xmlns","http://schemas.openxmlformats.org/package/2006/relationships")]
-        linkrels
-
-  -- comments
-  let commentsEntry = toEntry "word/comments.xml" epochtime
-        $ renderXml $ mknode "w:comments" stdAttributes comments
-
-  -- styles
-
-  -- We only want to inject paragraph and text properties that
-  -- are not already in the style map. Note that keys in the stylemap
-  -- are normalized as lowercase.
-  let newDynamicParaProps = filter
-        (\sty -> isNothing $ M.lookup (toLower <$> sty) $ getMap $ sParaStyleMap styleMaps)
-        (Set.toList $ stDynamicParaProps st)
-
-      newDynamicTextProps = filter
-        (\sty -> isNothing $ M.lookup (toLower <$> sty) $ getMap $ sCharStyleMap styleMaps)
-        (Set.toList $ stDynamicTextProps st)
-
-  let newstyles = map newParaPropToOpenXml newDynamicParaProps ++
-                  map newTextPropToOpenXml newDynamicTextProps ++
-                  (case writerHighlightStyle opts of
-                        Nothing  -> []
-                        Just sty -> styleToOpenXml styleMaps sty)
-  let styledoc' = styledoc{ elContent = elContent styledoc ++
-                                           map Elem newstyles }
-  let styleEntry = toEntry stylepath epochtime $ renderXml styledoc'
-
-  -- construct word/numbering.xml
-  let numpath = "word/numbering.xml"
-  numbering <- parseXml refArchive distArchive numpath
-  newNumElts <- mkNumbering (stLists st)
-  let allElts = onlyElems (elContent numbering) ++ newNumElts
-  let numEntry = toEntry numpath epochtime $ renderXml numbering{ elContent =
-                       -- we want all the abstractNums first, then the nums,
-                       -- otherwise things break:
-                       [Elem e | e <- allElts
-                               , qName (elName e) == "abstractNum" ] ++
-                       [Elem e | e <- allElts
-                               , qName (elName e) == "num" ] }
-
-  let keywords = case lookupMeta "keywords" meta of
-                       Just (MetaList xs) -> map stringify xs
-                       _                  -> []
-
-  let docPropsPath = "docProps/core.xml"
-  let docProps = mknode "cp:coreProperties"
-          [("xmlns:cp","http://schemas.openxmlformats.org/package/2006/metadata/core-properties")
-          ,("xmlns:dc","http://purl.org/dc/elements/1.1/")
-          ,("xmlns:dcterms","http://purl.org/dc/terms/")
-          ,("xmlns:dcmitype","http://purl.org/dc/dcmitype/")
-          ,("xmlns:xsi","http://www.w3.org/2001/XMLSchema-instance")]
-          $ mknode "dc:title" [] (stringify $ docTitle meta)
-          : mknode "dc:creator" [] (intercalate "; " (map stringify $ docAuthors meta))
-          : mknode "cp:keywords" [] (intercalate ", " keywords)
-          : (\x -> [ mknode "dcterms:created" [("xsi:type","dcterms:W3CDTF")] x
-                   , mknode "dcterms:modified" [("xsi:type","dcterms:W3CDTF")] x
-                   ]) (formatTime defaultTimeLocale "%FT%XZ" utctime)
-  let docPropsEntry = toEntry docPropsPath epochtime $ renderXml docProps
-
-  let relsPath = "_rels/.rels"
-  let rels = mknode "Relationships" [("xmlns", "http://schemas.openxmlformats.org/package/2006/relationships")]
-        $ map (\attrs -> mknode "Relationship" attrs ())
-        [ [("Id","rId1")
-          ,("Type","http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument")
-          ,("Target","word/document.xml")]
-        , [("Id","rId4")
-          ,("Type","http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties")
-          ,("Target","docProps/app.xml")]
-        , [("Id","rId3")
-          ,("Type","http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties")
-          ,("Target","docProps/core.xml")]
-        ]
-  let relsEntry = toEntry relsPath epochtime $ renderXml rels
-
-  -- we use dist archive for settings.xml, because Word sometimes
-  -- adds references to footnotes or endnotes we don't have...
-  -- we do, however, copy some settings over from reference
-  let settingsPath = "word/settings.xml"
-      settingsList = [ "w:autoHyphenation"
-                     , "w:consecutiveHyphenLimit"
-                     , "w:hyphenationZone"
-                     , "w:doNotHyphenateCap"
-                     , "w:evenAndOddHeaders"
-                     ]
-  settingsEntry <- copyChildren refArchive distArchive settingsPath epochtime settingsList
-
-  let entryFromArchive arch path =
-         maybe (fail $ path ++ " missing in reference docx")
-               return
-               (findEntryByPath path arch `mplus` findEntryByPath path distArchive)
-  docPropsAppEntry <- entryFromArchive refArchive "docProps/app.xml"
-  themeEntry <- entryFromArchive refArchive "word/theme/theme1.xml"
-  fontTableEntry <- entryFromArchive refArchive "word/fontTable.xml"
-  webSettingsEntry <- entryFromArchive refArchive "word/webSettings.xml"
-  headerFooterEntries <- mapM (entryFromArchive refArchive) $
-                     mapMaybe (fmap ("word/" ++) . extractTarget)
-                     (headers ++ footers)
-  let miscRelEntries = [ e | e <- zEntries refArchive
-                       , "word/_rels/" `isPrefixOf` (eRelativePath e)
-                       , ".xml.rels" `isSuffixOf` (eRelativePath e)
-                       , eRelativePath e /= "word/_rels/document.xml.rels"
-                       , eRelativePath e /= "word/_rels/footnotes.xml.rels" ]
-  let otherMediaEntries = [ e | e <- zEntries refArchive
-                          , "word/media/" `isPrefixOf` eRelativePath e ]
-
-  -- Create archive
-  let archive = foldr addEntryToArchive emptyArchive $
-                  contentTypesEntry : relsEntry : contentEntry : relEntry :
-                  footnoteRelEntry : numEntry : styleEntry : footnotesEntry :
-                  commentsEntry :
-                  docPropsEntry : docPropsAppEntry : themeEntry :
-                  fontTableEntry : settingsEntry : webSettingsEntry :
-                  imageEntries ++ headerFooterEntries ++
-                  miscRelEntries ++ otherMediaEntries
-  return $ fromArchive archive
-
-
-newParaPropToOpenXml :: String -> Element
-newParaPropToOpenXml s =
-  let styleId = filter (not . isSpace) s
-  in mknode "w:style" [ ("w:type", "paragraph")
-                      , ("w:customStyle", "1")
-                      , ("w:styleId", styleId)]
-     [ mknode "w:name" [("w:val", s)] ()
-     , mknode "w:basedOn" [("w:val","BodyText")] ()
-     , mknode "w:qFormat" [] ()
-     ]
-
-newTextPropToOpenXml :: String -> Element
-newTextPropToOpenXml s =
-  let styleId = filter (not . isSpace) s
-  in mknode "w:style" [ ("w:type", "character")
-                      , ("w:customStyle", "1")
-                      , ("w:styleId", styleId)]
-     [ mknode "w:name" [("w:val", s)] ()
-     , mknode "w:basedOn" [("w:val","BodyTextChar")] ()
-     ]
-
-styleToOpenXml :: StyleMaps -> Style -> [Element]
-styleToOpenXml sm style =
-  maybeToList parStyle ++ mapMaybe toStyle alltoktypes
-  where alltoktypes = enumFromTo KeywordTok NormalTok
-        toStyle toktype | hasStyleName (show toktype) (sCharStyleMap sm) = Nothing
-                        | otherwise = Just $
-                          mknode "w:style" [("w:type","character"),
-                           ("w:customStyle","1"),("w:styleId",show toktype)]
-                             [ mknode "w:name" [("w:val",show toktype)] ()
-                             , mknode "w:basedOn" [("w:val","VerbatimChar")] ()
-                             , mknode "w:rPr" [] $
-                               [ mknode "w:color" [("w:val",tokCol toktype)] ()
-                                 | tokCol toktype /= "auto" ] ++
-                               [ mknode "w:shd" [("w:val","clear"),("w:fill",tokBg toktype)] ()
-                                 | tokBg toktype /= "auto" ] ++
-                               [ mknode "w:b" [] () | tokFeature tokenBold toktype ] ++
-                               [ mknode "w:i" [] () | tokFeature tokenItalic toktype ] ++
-                               [ mknode "w:u" [] () | tokFeature tokenUnderline toktype ]
-                             ]
-        tokStyles = tokenStyles style
-        tokFeature f toktype = maybe False f $ M.lookup toktype tokStyles
-        tokCol toktype = maybe "auto" (drop 1 . fromColor)
-                         $ (tokenColor =<< M.lookup toktype tokStyles)
-                           `mplus` defaultColor style
-        tokBg toktype = maybe "auto" (drop 1 . fromColor)
-                         $ (tokenBackground =<< M.lookup toktype tokStyles)
-                           `mplus` backgroundColor style
-        parStyle | hasStyleName "Source Code" (sParaStyleMap sm) = Nothing
-                 | otherwise = Just $
-                   mknode "w:style" [("w:type","paragraph"),
-                           ("w:customStyle","1"),("w:styleId","SourceCode")]
-                             [ mknode "w:name" [("w:val","Source Code")] ()
-                             , mknode "w:basedOn" [("w:val","Normal")] ()
-                             , mknode "w:link" [("w:val","VerbatimChar")] ()
-                             , mknode "w:pPr" []
-                               $ mknode "w:wordWrap" [("w:val","off")] ()
-                               :
-                         maybe [] (\col -> [mknode "w:shd" [("w:val","clear"),("w:fill",drop 1 $ fromColor col)] ()]) (backgroundColor style)
-                             ]
-
-copyChildren :: (PandocMonad m) => Archive -> Archive -> String -> Integer -> [String] -> m Entry
-copyChildren refArchive distArchive path timestamp elNames = do
-  ref  <- parseXml refArchive distArchive path
-  dist <- parseXml distArchive distArchive path
-  return $ toEntry path timestamp $ renderXml dist{
-      elContent = elContent dist ++ copyContent ref
-    }
-  where
-    strName QName{qName=name, qPrefix=prefix}
-      | Just p <- prefix = p++":"++name
-      | otherwise        = name
-    shouldCopy = (`elem` elNames) . strName
-    cleanElem el@Element{elName=name} = Elem el{elName=name{qURI=Nothing}}
-    copyContent = map cleanElem . filterChildrenName shouldCopy
-
--- this is the lowest number used for a list numId
-baseListId :: Int
-baseListId = 1000
-
-mkNumbering :: (PandocMonad m) => [ListMarker] -> m [Element]
-mkNumbering lists = do
-  elts <- mapM mkAbstractNum (ordNub lists)
-  return $ elts ++ zipWith mkNum lists [baseListId..(baseListId + length lists - 1)]
-
-maxListLevel :: Int
-maxListLevel = 8
-
-mkNum :: ListMarker -> Int -> Element
-mkNum marker numid =
-  mknode "w:num" [("w:numId",show numid)]
-   $ mknode "w:abstractNumId" [("w:val",listMarkerToId marker)] ()
-   : case marker of
-       NoMarker     -> []
-       BulletMarker -> []
-       NumberMarker _ _ start ->
-          map (\lvl -> mknode "w:lvlOverride" [("w:ilvl",show (lvl :: Int))]
-              $ mknode "w:startOverride" [("w:val",show start)] ())
-                [0..maxListLevel]
-
-mkAbstractNum :: (PandocMonad m) => ListMarker -> m Element
-mkAbstractNum marker = do
-  gen <- P.newStdGen
-  let (nsid, _) = randomR (0x10000000 :: Integer, 0xFFFFFFFF :: Integer) gen
-  return $ mknode "w:abstractNum" [("w:abstractNumId",listMarkerToId marker)]
-    $ mknode "w:nsid" [("w:val", printf "%8x" nsid)] ()
-    : mknode "w:multiLevelType" [("w:val","multilevel")] ()
-    : map (mkLvl marker)
-      [0..maxListLevel]
-
-mkLvl :: ListMarker -> Int -> Element
-mkLvl marker lvl =
-  mknode "w:lvl" [("w:ilvl",show lvl)] $
-    [ mknode "w:start" [("w:val",start)] ()
-      | marker /= NoMarker && marker /= BulletMarker ] ++
-    [ mknode "w:numFmt" [("w:val",fmt)] ()
-    , mknode "w:lvlText" [("w:val",lvltxt)] ()
-    , mknode "w:lvlJc" [("w:val","left")] ()
-    , mknode "w:pPr" []
-      [ mknode "w:tabs" []
-        $ mknode "w:tab" [("w:val","num"),("w:pos",show $ lvl * step)] ()
-      , mknode "w:ind" [("w:left",show $ lvl * step + hang),("w:hanging",show hang)] ()
-      ]
-    ]
-    where (fmt, lvltxt, start) =
-            case marker of
-                 NoMarker             -> ("bullet"," ","1")
-                 BulletMarker         -> ("bullet",bulletFor lvl,"1")
-                 NumberMarker st de n -> (styleFor st lvl
-                                         ,patternFor de ("%" ++ show (lvl + 1))
-                                         ,show n)
-          step = 720
-          hang = 480
-          bulletFor 0 = "\x2022"  -- filled circle
-          bulletFor 1 = "\x2013"  -- en dash
-          bulletFor 2 = "\x2022"  -- hyphen bullet
-          bulletFor 3 = "\x2013"
-          bulletFor 4 = "\x2022"
-          bulletFor 5 = "\x2013"
-          bulletFor x = bulletFor (x `mod` 6)
-          styleFor UpperAlpha _   = "upperLetter"
-          styleFor LowerAlpha _   = "lowerLetter"
-          styleFor UpperRoman _   = "upperRoman"
-          styleFor LowerRoman _   = "lowerRoman"
-          styleFor Decimal _      = "decimal"
-          styleFor DefaultStyle 1 = "decimal"
-          styleFor DefaultStyle 2 = "lowerLetter"
-          styleFor DefaultStyle 3 = "lowerRoman"
-          styleFor DefaultStyle 4 = "decimal"
-          styleFor DefaultStyle 5 = "lowerLetter"
-          styleFor DefaultStyle 0 = "lowerRoman"
-          styleFor DefaultStyle x = styleFor DefaultStyle (x `mod` 6)
-          styleFor _ _            = "decimal"
-          patternFor OneParen s  = s ++ ")"
-          patternFor TwoParens s = "(" ++ s ++ ")"
-          patternFor _ s         = s ++ "."
-
-getNumId :: (PandocMonad m) => WS m Int
-getNumId = (((baseListId - 1) +) . length) `fmap` gets stLists
-
-
-makeTOC :: (PandocMonad m) => WriterOptions -> WS m [Element]
-makeTOC opts | writerTableOfContents opts = do
-  let depth = "1-"++show (writerTOCDepth opts)
-  let tocCmd = "TOC \\o \""++depth++"\" \\h \\z \\u"
-  tocTitle <- gets stTocTitle
-  title <- withParaPropM (pStyleM "TOC Heading") (blocksToOpenXML opts [Para tocTitle])
-  return
-    [mknode "w:sdt" [] ([
-      mknode "w:sdtPr" [] (
-        mknode "w:docPartObj" [] (
-          [mknode "w:docPartGallery" [("w:val","Table of Contents")] (),
-          mknode "w:docPartUnique" [] ()]
-        ) -- w:docPartObj
-      ), -- w:sdtPr
-      mknode "w:sdtContent" [] (title++[
-        mknode "w:p" [] (
-          mknode "w:r" [] ([
-            mknode "w:fldChar" [("w:fldCharType","begin"),("w:dirty","true")] (),
-            mknode "w:instrText" [("xml:space","preserve")] tocCmd,
-            mknode "w:fldChar" [("w:fldCharType","separate")] (),
-            mknode "w:fldChar" [("w:fldCharType","end")] ()
-          ]) -- w:r
-        ) -- w:p
-      ])
-    ])] -- w:sdt
-makeTOC _ = return []
-
-
--- | Convert Pandoc document to two lists of
--- OpenXML elements (the main document and footnotes).
-writeOpenXML :: (PandocMonad m) => WriterOptions -> Pandoc -> WS m ([Element], [Element],[Element])
-writeOpenXML opts (Pandoc meta blocks) = do
-  let tit = docTitle meta ++ case lookupMeta "subtitle" meta of
-                                  Just (MetaBlocks [Plain xs]) -> LineBreak : xs
-                                  _ -> []
-  let auths = docAuthors meta
-  let dat = docDate meta
-  let abstract' = case lookupMeta "abstract" meta of
-                       Just (MetaBlocks bs)   -> bs
-                       Just (MetaInlines ils) -> [Plain ils]
-                       _                      -> []
-  let subtitle' = case lookupMeta "subtitle" meta of
-                       Just (MetaBlocks [Plain xs]) -> xs
-                       Just (MetaBlocks [Para  xs]) -> xs
-                       Just (MetaInlines xs)        -> xs
-                       _                            -> []
-  title <- withParaPropM (pStyleM "Title") $ blocksToOpenXML opts [Para tit | not (null tit)]
-  subtitle <- withParaPropM (pStyleM "Subtitle") $ blocksToOpenXML opts [Para subtitle' | not (null subtitle')]
-  authors <- withParaProp (pCustomStyle "Author") $ blocksToOpenXML opts $
-       map Para auths
-  date <- withParaPropM (pStyleM "Date") $ blocksToOpenXML opts [Para dat | not (null dat)]
-  abstract <- if null abstract'
-                 then return []
-                 else withParaProp (pCustomStyle "Abstract") $ blocksToOpenXML opts abstract'
-  let convertSpace (Str x : Space : Str y : xs) = Str (x ++ " " ++ y) : xs
-      convertSpace (Str x : Str y : xs)         = Str (x ++ y) : xs
-      convertSpace xs                           = xs
-  let blocks' = bottomUp convertSpace blocks
-  doc' <- setFirstPara >> blocksToOpenXML opts blocks'
-  notes' <- reverse <$> gets stFootnotes
-  comments <- reverse <$> gets stComments
-  let toComment (kvs, ils) = do
-        annotation <- inlinesToOpenXML opts ils
-        return $
-          mknode "w:comment" [('w':':':k,v) | (k,v) <- kvs]
-            [ mknode "w:p" [] $
-              [ mknode "w:pPr" []
-                [ mknode "w:pStyle" [("w:val", "CommentText")] () ]
-              , mknode "w:r" []
-                [ mknode "w:rPr" []
-                  [ mknode "w:rStyle" [("w:val", "CommentReference")] ()
-                  , mknode "w:annotationRef" [] ()
-                  ]
-                ]
-              ] ++ annotation
-            ]
-  comments' <- mapM toComment comments
-  toc <- makeTOC opts
-  let meta' = title ++ subtitle ++ authors ++ date ++ abstract ++ toc
-  return (meta' ++ doc', notes', comments')
-
--- | Convert a list of Pandoc blocks to OpenXML.
-blocksToOpenXML :: (PandocMonad m) => WriterOptions -> [Block] -> WS m [Element]
-blocksToOpenXML opts bls = concat `fmap` mapM (blockToOpenXML opts) bls
-
-pCustomStyle :: String -> Element
-pCustomStyle sty = mknode "w:pStyle" [("w:val",sty)] ()
-
-pStyleM :: (PandocMonad m) => String -> WS m XML.Element
-pStyleM styleName = do
-  styleMaps <- gets stStyleMaps
-  let sty' = getStyleId styleName $ sParaStyleMap styleMaps
-  return $ mknode "w:pStyle" [("w:val",sty')] ()
-
-rCustomStyle :: String -> Element
-rCustomStyle sty = mknode "w:rStyle" [("w:val",sty)] ()
-
-rStyleM :: (PandocMonad m) => String -> WS m XML.Element
-rStyleM styleName = do
-  styleMaps <- gets stStyleMaps
-  let sty' = getStyleId styleName $ sCharStyleMap styleMaps
-  return $ mknode "w:rStyle" [("w:val",sty')] ()
-
-getUniqueId :: (PandocMonad m) => m String
--- the + 20 is to ensure that there are no clashes with the rIds
--- already in word/document.xml.rel
-getUniqueId = (show . (+ 20)) <$> P.newUniqueHash
-
--- | Key for specifying user-defined docx styles.
-dynamicStyleKey :: String
-dynamicStyleKey = "custom-style"
-
--- | Convert a Pandoc block element to OpenXML.
-blockToOpenXML :: (PandocMonad m) => WriterOptions -> Block -> WS m [Element]
-blockToOpenXML opts blk = withDirection $ blockToOpenXML' opts blk
-
-blockToOpenXML' :: (PandocMonad m) => WriterOptions -> Block -> WS m [Element]
-blockToOpenXML' _ Null = return []
-blockToOpenXML' opts (Div (ident,classes,kvs) bs) = do
-  stylemod <- case lookup dynamicStyleKey kvs of
-                   Just sty -> do
-                      modify $ \s ->
-                        s{stDynamicParaProps = Set.insert sty
-                             (stDynamicParaProps s)}
-                      return $ withParaPropM (pStyleM sty)
-                   _ -> return id
-  dirmod <- case lookup "dir" kvs of
-                 Just "rtl" -> return $ local (\env -> env { envRTL = True })
-                 Just "ltr" -> return $ local (\env -> env { envRTL = False })
-                 _ -> return id
-  let (hs, bs') = if "references" `elem` classes
-                     then span isHeaderBlock bs
-                     else ([], bs)
-  let bibmod = if "references" `elem` classes
-                  then withParaPropM (pStyleM "Bibliography")
-                  else id
-  header <- dirmod $ stylemod $ blocksToOpenXML opts hs
-  contents <- dirmod $ bibmod $ stylemod $ blocksToOpenXML opts bs'
-  if null ident
-     then return $ header ++ contents
-     else do
-       id' <- getUniqueId
-       let bookmarkStart = mknode "w:bookmarkStart" [("w:id", id')
-                                                    ,("w:name",ident)] ()
-       let bookmarkEnd = mknode "w:bookmarkEnd" [("w:id", id')] ()
-       return $ bookmarkStart : header ++ contents ++ [bookmarkEnd]
-blockToOpenXML' opts (Header lev (ident,_,_) lst) = do
-  setFirstPara
-  paraProps <- withParaPropM (pStyleM ("Heading "++show lev)) $
-                    getParaProps False
-  contents <- inlinesToOpenXML opts lst
-  if null ident
-     then return [mknode "w:p" [] (paraProps ++contents)]
-     else do
-       let bookmarkName = ident
-       modify $ \s -> s{ stSectionIds = Set.insert bookmarkName
-                                      $ stSectionIds s }
-       id' <- getUniqueId
-       let bookmarkStart = mknode "w:bookmarkStart" [("w:id", id')
-                                               ,("w:name",bookmarkName)] ()
-       let bookmarkEnd = mknode "w:bookmarkEnd" [("w:id", id')] ()
-       return [mknode "w:p" [] (paraProps ++
-               [bookmarkStart] ++ contents ++ [bookmarkEnd])]
-blockToOpenXML' opts (Plain lst) = withParaProp (pCustomStyle "Compact")
-  $ blockToOpenXML opts (Para lst)
--- title beginning with fig: indicates that the image is a figure
-blockToOpenXML' opts (Para [Image attr alt (src,'f':'i':'g':':':tit)]) = do
-  setFirstPara
-  let prop = pCustomStyle $
-        if null alt
-        then "Figure"
-        else "CaptionedFigure"
-  paraProps <- local (\env -> env { envParaProperties = prop : envParaProperties env }) (getParaProps False)
-  contents <- inlinesToOpenXML opts [Image attr alt (src,tit)]
-  captionNode <- withParaProp (pCustomStyle "ImageCaption")
-                 $ blockToOpenXML opts (Para alt)
-  return $ mknode "w:p" [] (paraProps ++ contents) : captionNode
-blockToOpenXML' opts (Para lst)
-  | null lst && not (isEnabled Ext_empty_paragraphs opts) = return []
-  | otherwise = do
-      isFirstPara <- gets stFirstPara
-      paraProps <- getParaProps $ case lst of
-                                   [Math DisplayMath _] -> True
-                                   _                    -> False
-      bodyTextStyle <- pStyleM "Body Text"
-      let paraProps' = case paraProps of
-            [] | isFirstPara -> [mknode "w:pPr" []
-                                [pCustomStyle "FirstParagraph"]]
-            []               -> [mknode "w:pPr" [] [bodyTextStyle]]
-            ps               -> ps
-      modify $ \s -> s { stFirstPara = False }
-      contents <- inlinesToOpenXML opts lst
-      return [mknode "w:p" [] (paraProps' ++ contents)]
-blockToOpenXML' opts (LineBlock lns) = blockToOpenXML opts $ linesToPara lns
-blockToOpenXML' _ b@(RawBlock format str)
-  | format == Format "openxml" = return [ x | Elem x <- parseXML str ]
-  | otherwise                  = do
-      report $ BlockNotRendered b
-      return []
-blockToOpenXML' opts (BlockQuote blocks) = do
-  p <- withParaPropM (pStyleM "Block Text") $ blocksToOpenXML opts blocks
-  setFirstPara
-  return p
-blockToOpenXML' opts (CodeBlock attrs str) = do
-  p <- withParaProp (pCustomStyle "SourceCode") (blockToOpenXML opts $ Para [Code attrs str])
-  setFirstPara
-  return p
-blockToOpenXML' _ HorizontalRule = do
-  setFirstPara
-  return [
-    mknode "w:p" [] $ mknode "w:r" [] $ mknode "w:pict" []
-    $ mknode "v:rect" [("style","width:0;height:1.5pt"),
-                       ("o:hralign","center"),
-                       ("o:hrstd","t"),("o:hr","t")] () ]
-blockToOpenXML' opts (Table caption aligns widths headers rows) = do
-  setFirstPara
-  let captionStr = stringify caption
-  caption' <- if null caption
-                 then return []
-                 else withParaProp (pCustomStyle "TableCaption")
-                      $ blockToOpenXML opts (Para caption)
-  let alignmentFor al = mknode "w:jc" [("w:val",alignmentToString al)] ()
-  let cellToOpenXML (al, cell) = withParaProp (alignmentFor al)
-                                    $ blocksToOpenXML opts cell
-  headers' <- mapM cellToOpenXML $ zip aligns headers
-  rows' <- mapM (mapM cellToOpenXML . zip aligns) rows
-  let borderProps = mknode "w:tcPr" []
-                    [ mknode "w:tcBorders" []
-                      $ mknode "w:bottom" [("w:val","single")] ()
-                    , mknode "w:vAlign" [("w:val","bottom")] () ]
-  let emptyCell = [mknode "w:p" [] [mknode "w:pPr" [] [pCustomStyle "Compact"]]]
-  let mkcell border contents = mknode "w:tc" []
-                            $ [ borderProps | border ] ++
-                            if null contents
-                               then emptyCell
-                               else contents
-  let mkrow border cells = mknode "w:tr" [] $
-                        [mknode "w:trPr" [] [
-                          mknode "w:cnfStyle" [("w:firstRow","1")] ()] | border]
-                        ++ map (mkcell border) cells
-  let textwidth = 7920  -- 5.5 in in twips, 1/20 pt
-  let fullrow = 5000 -- 100% specified in pct
-  let rowwidth = fullrow * sum widths
-  let mkgridcol w = mknode "w:gridCol"
-                       [("w:w", show (floor (textwidth * w) :: Integer))] ()
-  let hasHeader = not (all null headers)
-  return $
-    caption' ++
-    [mknode "w:tbl" []
-      ( mknode "w:tblPr" []
-        (   mknode "w:tblStyle" [("w:val","Table")] () :
-            mknode "w:tblW" [("w:type", "pct"), ("w:w", show rowwidth)] () :
-            mknode "w:tblLook" [("w:firstRow","1") | hasHeader ] () :
-          [ mknode "w:tblCaption" [("w:val", captionStr)] ()
-          | not (null caption) ] )
-      : mknode "w:tblGrid" []
-        (if all (==0) widths
-            then []
-            else map mkgridcol widths)
-      : [ mkrow True headers' | hasHeader ] ++
-      map (mkrow False) rows'
-      )]
-blockToOpenXML' opts (BulletList lst) = do
-  let marker = BulletMarker
-  addList marker
-  numid  <- getNumId
-  l <- asList $ concat `fmap` mapM (listItemToOpenXML opts numid) lst
-  setFirstPara
-  return l
-blockToOpenXML' opts (OrderedList (start, numstyle, numdelim) lst) = do
-  let marker = NumberMarker numstyle numdelim start
-  addList marker
-  numid  <- getNumId
-  l <- asList $ concat `fmap` mapM (listItemToOpenXML opts numid) lst
-  setFirstPara
-  return l
-blockToOpenXML' opts (DefinitionList items) = do
-  l <- concat `fmap` mapM (definitionListItemToOpenXML opts) items
-  setFirstPara
-  return l
-
-definitionListItemToOpenXML  :: (PandocMonad m) => WriterOptions -> ([Inline],[[Block]]) -> WS m [Element]
-definitionListItemToOpenXML opts (term,defs) = do
-  term' <- withParaProp (pCustomStyle "DefinitionTerm")
-           $ blockToOpenXML opts (Para term)
-  defs' <- withParaProp (pCustomStyle "Definition")
-           $ concat `fmap` mapM (blocksToOpenXML opts) defs
-  return $ term' ++ defs'
-
-addList :: (PandocMonad m) => ListMarker -> WS m ()
-addList marker = do
-  lists <- gets stLists
-  modify $ \st -> st{ stLists = lists ++ [marker] }
-
-listItemToOpenXML :: (PandocMonad m) => WriterOptions -> Int -> [Block] -> WS m [Element]
-listItemToOpenXML _ _ []                   = return []
-listItemToOpenXML opts numid (first:rest) = do
-  first' <- withNumId numid $ blockToOpenXML opts first
-  -- baseListId is the code for no list marker:
-  rest'  <- withNumId baseListId $ blocksToOpenXML opts rest
-  return $ first' ++ rest'
-
-alignmentToString :: Alignment -> [Char]
-alignmentToString alignment = case alignment of
-                                 AlignLeft    -> "left"
-                                 AlignRight   -> "right"
-                                 AlignCenter  -> "center"
-                                 AlignDefault -> "left"
-
--- | Convert a list of inline elements to OpenXML.
-inlinesToOpenXML :: (PandocMonad m) => WriterOptions -> [Inline] -> WS m [Element]
-inlinesToOpenXML opts lst = concat `fmap` mapM (inlineToOpenXML opts) lst
-
-withNumId :: (PandocMonad m) => Int -> WS m a -> WS m a
-withNumId numid = local $ \env -> env{ envListNumId = numid }
-
-asList :: (PandocMonad m) => WS m a -> WS m a
-asList = local $ \env -> env{ envListLevel = envListLevel env + 1 }
-
-getTextProps :: (PandocMonad m) => WS m [Element]
-getTextProps = do
-  props <- asks envTextProperties
-  return $ if null props
-              then []
-              else [mknode "w:rPr" [] props]
-
-withTextProp :: PandocMonad m => Element -> WS m a -> WS m a
-withTextProp d p =
-  local (\env -> env {envTextProperties = d : envTextProperties env}) p
-
-withTextPropM :: PandocMonad m => WS m Element -> WS m a -> WS m a
-withTextPropM = (. flip withTextProp) . (>>=)
-
-getParaProps :: PandocMonad m => Bool -> WS m [Element]
-getParaProps displayMathPara = do
-  props <- asks envParaProperties
-  listLevel <- asks envListLevel
-  numid <- asks envListNumId
-  let listPr = if listLevel >= 0 && not displayMathPara
-                  then [ mknode "w:numPr" []
-                         [ mknode "w:numId" [("w:val",show numid)] ()
-                         , mknode "w:ilvl" [("w:val",show listLevel)] () ]
-                       ]
-                  else []
-  return $ case props ++ listPr of
-                [] -> []
-                ps -> [mknode "w:pPr" [] ps]
-
-withParaProp :: PandocMonad m => Element -> WS m a -> WS m a
-withParaProp d p =
-  local (\env -> env {envParaProperties = d : envParaProperties env}) p
-
-withParaPropM :: PandocMonad m => WS m Element -> WS m a -> WS m a
-withParaPropM = (. flip withParaProp) . (>>=)
-
-formattedString :: PandocMonad m => String -> WS m [Element]
-formattedString str =
-  -- properly handle soft hyphens
-  case splitBy (=='\173') str of
-      [w] -> formattedString' w
-      ws  -> do
-         sh <- formattedRun [mknode "w:softHyphen" [] ()]
-         intercalate sh <$> mapM formattedString' ws
-
-formattedString' :: PandocMonad m => String -> WS m [Element]
-formattedString' str = do
-  inDel <- asks envInDel
-  formattedRun [ mknode (if inDel then "w:delText" else "w:t")
-                 [("xml:space","preserve")] (stripInvalidChars str) ]
-
-formattedRun :: PandocMonad m => [Element] -> WS m [Element]
-formattedRun els = do
-  props <- getTextProps
-  return [ mknode "w:r" [] $ props ++ els ]
-
-setFirstPara :: PandocMonad m => WS m ()
-setFirstPara =  modify $ \s -> s { stFirstPara = True }
-
--- | Convert an inline element to OpenXML.
-inlineToOpenXML :: PandocMonad m => WriterOptions -> Inline -> WS m [Element]
-inlineToOpenXML opts il = withDirection $ inlineToOpenXML' opts il
-
-inlineToOpenXML' :: PandocMonad m => WriterOptions -> Inline -> WS m [Element]
-inlineToOpenXML' _ (Str str) =
-  formattedString str
-inlineToOpenXML' opts Space = inlineToOpenXML opts (Str " ")
-inlineToOpenXML' opts SoftBreak = inlineToOpenXML opts (Str " ")
-inlineToOpenXML' _ (Span (ident,["comment-start"],kvs) ils) = do
-  modify $ \st -> st{ stComments = (("id",ident):kvs, ils) : stComments st }
-  return [ mknode "w:commentRangeStart" [("w:id", ident)] () ]
-inlineToOpenXML' _ (Span (ident,["comment-end"],_) _) =
-  return [ mknode "w:commentRangeEnd" [("w:id", ident)] ()
-       , mknode "w:r" []
-         [ mknode "w:rPr" []
-           [ mknode "w:rStyle" [("w:val", "CommentReference")] () ]
-         , mknode "w:commentReference" [("w:id", ident)] () ]
-       ]
-inlineToOpenXML' opts (Span (ident,classes,kvs) ils) = do
-  stylemod <- case lookup dynamicStyleKey kvs of
-                   Just sty -> do
-                      modify $ \s ->
-                        s{stDynamicTextProps = Set.insert sty
-                              (stDynamicTextProps s)}
-                      return $ withTextProp (rCustomStyle sty)
-                   _ -> return id
-  let dirmod = case lookup "dir" kvs of
-                 Just "rtl" -> local (\env -> env { envRTL = True })
-                 Just "ltr" -> local (\env -> env { envRTL = False })
-                 _          -> id
-  let off x = withTextProp (mknode x [("w:val","0")] ())
-  let pmod =  (if "csl-no-emph" `elem` classes then off "w:i" else id) .
-              (if "csl-no-strong" `elem` classes then off "w:b" else id) .
-              (if "csl-no-smallcaps" `elem` classes
-                  then off "w:smallCaps"
-                  else id)
-  insmod <- if "insertion" `elem` classes
-               then do
-                 defaultAuthor <- asks envChangesAuthor
-                 defaultDate <- asks envChangesDate
-                 let author = fromMaybe defaultAuthor (lookup "author" kvs)
-                     date   = fromMaybe defaultDate (lookup "date" kvs)
-                 insId <- gets stInsId
-                 modify $ \s -> s{stInsId = insId + 1}
-                 return $ \f -> do
-                   x <- f
-                   return [ mknode "w:ins"
-                              [("w:id", (show insId)),
-                              ("w:author", author),
-                              ("w:date", date)] x ]
-               else return id
-  delmod <- if "insertion" `elem` classes
-               then do
-                 defaultAuthor <- asks envChangesAuthor
-                 defaultDate <- asks envChangesDate
-                 let author = fromMaybe defaultAuthor (lookup "author" kvs)
-                     date   = fromMaybe defaultDate (lookup "date" kvs)
-                 insId <- gets stInsId
-                 modify $ \s -> s{stInsId = insId + 1}
-                 return $ \f -> do
-                   x <- f
-                   return [mknode "w:ins"
-                           [("w:id", show insId),
-                           ("w:author", author),
-                           ("w:date", date)] x]
-               else return id
-  contents <- insmod $ delmod $ dirmod $ stylemod $ pmod
-                     $ inlinesToOpenXML opts ils
-  if null ident
-     then return contents
-     else do
-       id' <- getUniqueId
-       let bookmarkStart = mknode "w:bookmarkStart" [("w:id", id')
-                                                    ,("w:name",ident)] ()
-       let bookmarkEnd = mknode "w:bookmarkEnd" [("w:id", id')] ()
-       return $ bookmarkStart : contents ++ [bookmarkEnd]
-inlineToOpenXML' opts (Strong lst) =
-  withTextProp (mknode "w:b" [] ()) $ inlinesToOpenXML opts lst
-inlineToOpenXML' opts (Emph lst) =
-  withTextProp (mknode "w:i" [] ()) $ inlinesToOpenXML opts lst
-inlineToOpenXML' opts (Subscript lst) =
-  withTextProp (mknode "w:vertAlign" [("w:val","subscript")] ())
-  $ inlinesToOpenXML opts lst
-inlineToOpenXML' opts (Superscript lst) =
-  withTextProp (mknode "w:vertAlign" [("w:val","superscript")] ())
-  $ inlinesToOpenXML opts lst
-inlineToOpenXML' opts (SmallCaps lst) =
-  withTextProp (mknode "w:smallCaps" [] ())
-  $ inlinesToOpenXML opts lst
-inlineToOpenXML' opts (Strikeout lst) =
-  withTextProp (mknode "w:strike" [] ())
-  $ inlinesToOpenXML opts lst
-inlineToOpenXML' _ LineBreak = return [br]
-inlineToOpenXML' _ il@(RawInline f str)
-  | f == Format "openxml" = return [ x | Elem x <- parseXML str ]
-  | otherwise             = do
-      report $ InlineNotRendered il
-      return []
-inlineToOpenXML' opts (Quoted quoteType lst) =
-  inlinesToOpenXML opts $ [Str open] ++ lst ++ [Str close]
-    where (open, close) = case quoteType of
-                            SingleQuote -> ("\x2018", "\x2019")
-                            DoubleQuote -> ("\x201C", "\x201D")
-inlineToOpenXML' opts (Math mathType str) = do
-  when (mathType == DisplayMath) setFirstPara
-  res <- (lift . lift) (convertMath writeOMML mathType str)
-  case res of
-       Right r -> return [r]
-       Left il -> inlineToOpenXML' opts il
-inlineToOpenXML' opts (Cite _ lst) = inlinesToOpenXML opts lst
-inlineToOpenXML' opts (Code attrs str) = do
-  let unhighlighted = intercalate [br] `fmap`
-                       mapM formattedString (lines str)
-      formatOpenXML _fmtOpts = intercalate [br] . map (map toHlTok)
-      toHlTok (toktype,tok) = mknode "w:r" []
-                               [ mknode "w:rPr" []
-                                 [ rCustomStyle (show toktype) ]
-                               , mknode "w:t" [("xml:space","preserve")] (T.unpack tok) ]
-  withTextProp (rCustomStyle "VerbatimChar")
-    $ if isNothing (writerHighlightStyle opts)
-          then unhighlighted
-          else case highlight (writerSyntaxMap opts)
-                      formatOpenXML attrs str of
-                    Right h  -> return h
-                    Left msg -> do
-                      unless (null msg) $ report $ CouldNotHighlight msg
-                      unhighlighted
-inlineToOpenXML' opts (Note bs) = do
-  notes <- gets stFootnotes
-  notenum <- (lift . lift) getUniqueId
-  footnoteStyle <- rStyleM "Footnote Reference"
-  let notemarker = mknode "w:r" []
-                   [ mknode "w:rPr" [] footnoteStyle
-                   , mknode "w:footnoteRef" [] () ]
-  let notemarkerXml = RawInline (Format "openxml") $ ppElement notemarker
-  let insertNoteRef (Plain ils : xs) = Plain (notemarkerXml : Space : ils) : xs
-      insertNoteRef (Para ils  : xs) = Para  (notemarkerXml : Space : ils) : xs
-      insertNoteRef xs               = Para [notemarkerXml] : xs
-
-  contents <- local (\env -> env{ envListLevel = -1
-                                , envParaProperties = []
-                                , envTextProperties = [] })
-              (withParaPropM (pStyleM "Footnote Text") $ blocksToOpenXML opts
-                $ insertNoteRef bs)
-  let newnote = mknode "w:footnote" [("w:id", notenum)] contents
-  modify $ \s -> s{ stFootnotes = newnote : notes }
-  return [ mknode "w:r" []
-           [ mknode "w:rPr" [] footnoteStyle
-           , mknode "w:footnoteReference" [("w:id", notenum)] () ] ]
--- internal link:
-inlineToOpenXML' opts (Link _ txt ('#':xs,_)) = do
-  contents <- withTextPropM (rStyleM "Hyperlink") $ inlinesToOpenXML opts txt
-  return [ mknode "w:hyperlink" [("w:anchor",xs)] contents ]
--- external link:
-inlineToOpenXML' opts (Link _ txt (src,_)) = do
-  contents <- withTextPropM (rStyleM "Hyperlink") $ inlinesToOpenXML opts txt
-  extlinks <- gets stExternalLinks
-  id' <- case M.lookup src extlinks of
-            Just i   -> return i
-            Nothing  -> do
-              i <- ("rId"++) `fmap` (lift . lift) getUniqueId
-              modify $ \st -> st{ stExternalLinks =
-                        M.insert src i extlinks }
-              return i
-  return [ mknode "w:hyperlink" [("r:id",id')] contents ]
-inlineToOpenXML' opts (Image attr alt (src, title)) = do
-  -- first, check to see if we've already done this image
-  pageWidth <- asks envPrintWidth
-  imgs <- gets stImages
-  case M.lookup src imgs of
-    Just (_,_,_,elt,_) -> return [elt]
-    Nothing ->
-      catchError
-      (do (img, mt) <- P.fetchItem src
-          ident <- ("rId"++) `fmap` ((lift . lift) getUniqueId)
-          let (xpt,ypt) = desiredSizeInPoints opts attr
-                 (either (const def) id (imageSize opts img))
-          -- 12700 emu = 1 pt
-          let (xemu,yemu) = fitToPage (xpt * 12700, ypt * 12700)
-                                  (pageWidth * 12700)
-          let cNvPicPr = mknode "pic:cNvPicPr" [] $
-                           mknode "a:picLocks" [("noChangeArrowheads","1")
-                                               ,("noChangeAspect","1")] ()
-          let nvPicPr  = mknode "pic:nvPicPr" []
-                          [ mknode "pic:cNvPr"
-                              [("descr",src),("id","0"),("name","Picture")] ()
-                          , cNvPicPr ]
-          let blipFill = mknode "pic:blipFill" []
-                           [ mknode "a:blip" [("r:embed",ident)] ()
-                           , mknode "a:stretch" [] $
-                             mknode "a:fillRect" [] () ]
-          let xfrm =    mknode "a:xfrm" []
-                          [ mknode "a:off" [("x","0"),("y","0")] ()
-                          , mknode "a:ext" [("cx",show xemu)
-                                           ,("cy",show yemu)] () ]
-          let prstGeom = mknode "a:prstGeom" [("prst","rect")] $
-                           mknode "a:avLst" [] ()
-          let ln =      mknode "a:ln" [("w","9525")]
-                          [ mknode "a:noFill" [] ()
-                          , mknode "a:headEnd" [] ()
-                          , mknode "a:tailEnd" [] () ]
-          let spPr =    mknode "pic:spPr" [("bwMode","auto")]
-                          [xfrm, prstGeom, mknode "a:noFill" [] (), ln]
-          let graphic = mknode "a:graphic" [] $
-                          mknode "a:graphicData"
-                            [("uri","http://schemas.openxmlformats.org/drawingml/2006/picture")]
-                            [ mknode "pic:pic" []
-                              [ nvPicPr
-                              , blipFill
-                              , spPr ] ]
-          let imgElt = mknode "w:r" [] $
-               mknode "w:drawing" [] $
-                 mknode "wp:inline" []
-                  [ mknode "wp:extent" [("cx",show xemu),("cy",show yemu)] ()
-                  , mknode "wp:effectExtent"
-                       [("b","0"),("l","0"),("r","0"),("t","0")] ()
-                  , mknode "wp:docPr" [("descr",stringify alt)
-                                      ,("title", title)
-                                      ,("id","1")
-                                      ,("name","Picture")] ()
-                  , graphic ]
-          let imgext = case mt >>= extensionFromMimeType of
-                            Just x    -> '.':x
-                            Nothing   -> case imageType img of
-                                              Just Png  -> ".png"
-                                              Just Jpeg -> ".jpeg"
-                                              Just Gif  -> ".gif"
-                                              Just Pdf  -> ".pdf"
-                                              Just Eps  -> ".eps"
-                                              Just Svg  -> ".svg"
-                                              Nothing   -> ""
-          if null imgext
-             then -- without an extension there is no rule for content type
-               inlinesToOpenXML opts alt -- return alt to avoid corrupted docx
-             else do
-               let imgpath = "media/" ++ ident ++ imgext
-               let mbMimeType = mt <|> getMimeType imgpath
-               -- insert mime type to use in constructing [Content_Types].xml
-               modify $ \st -> st{ stImages =
-                   M.insert src (ident, imgpath, mbMimeType, imgElt, img)
-                           $ stImages st }
-               return [imgElt])
-      (\e -> do
-         report $ CouldNotFetchResource src (show e)
-         -- emit alt text
-         inlinesToOpenXML opts alt)
-
-br :: Element
-br = breakElement "textWrapping"
-
-breakElement :: String -> Element
-breakElement kind = mknode "w:r" [] [mknode "w:br" [("w:type",kind)] () ]
-
--- Word will insert these footnotes into the settings.xml file
--- (whether or not they're visible in the document). If they're in the
--- file, but not in the footnotes.xml file, it will produce
--- problems. So we want to make sure we insert them into our document.
-defaultFootnotes :: [Element]
-defaultFootnotes = [ mknode "w:footnote"
-                     [("w:type", "separator"), ("w:id", "-1")]
-                     [ mknode "w:p" [] $
-                       [mknode "w:r" [] $
-                        [ mknode "w:separator" [] ()]]]
-                   , mknode "w:footnote"
-                     [("w:type", "continuationSeparator"), ("w:id", "0")]
-                     [ mknode "w:p" [] $
-                       [ mknode "w:r" [] $
-                         [ mknode "w:continuationSeparator" [] ()]]]]
-
-
-withDirection :: PandocMonad m => WS m a -> WS m a
-withDirection x = do
-  isRTL <- asks envRTL
-  paraProps <- asks envParaProperties
-  textProps <- asks envTextProperties
-  -- We want to clean all bidirection (bidi) and right-to-left (rtl)
-  -- properties from the props first. This is because we don't want
-  -- them to stack up.
-  let paraProps' = filter (\e -> (qName . elName) e /= "bidi") paraProps
-      textProps' = filter (\e -> (qName . elName) e /= "rtl") textProps
-  if isRTL
-    -- if we are going right-to-left, we (re?)add the properties.
-    then flip local x $
-         \env -> env { envParaProperties = mknode "w:bidi" [] () : paraProps'
-                     , envTextProperties = mknode "w:rtl" [] () : textProps'
-                     }
-    else flip local x $ \env -> env { envParaProperties = paraProps'
-                                    , envTextProperties = textProps'
-                                    }
+{-# LANGUAGE PatternGuards       #-}
+{-# LANGUAGE RankNTypes          #-}
+{-# LANGUAGE ScopedTypeVariables #-}
+{-# LANGUAGE ViewPatterns        #-}
+{-# LANGUAGE FlexibleContexts    #-}
+{-# LANGUAGE OverloadedStrings   #-}
+{- |
+   Module      : Text.Pandoc.Writers.Docx
+   Copyright   : Copyright (C) 2012-2025 John MacFarlane
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : John MacFarlane <jgm@berkeley.edu>
+   Stability   : alpha
+   Portability : portable
+
+Conversion of 'Pandoc' documents to docx.
+-}
+module Text.Pandoc.Writers.Docx ( writeDocx ) where
+import Codec.Archive.Zip
+    ( Archive(zEntries),
+      addEntryToArchive,
+      emptyArchive,
+      findEntryByPath,
+      fromArchive,
+      toArchive,
+      toEntry,
+      Entry(eRelativePath) )
+import Control.Monad (MonadPlus(mplus), foldM)
+import Control.Monad.Except (throwError)
+import Control.Monad.Reader ( ReaderT(runReaderT) )
+import Control.Monad.State.Strict ( StateT(runStateT) )
+import qualified Data.ByteString as B
+import qualified Data.ByteString.Lazy as BL
+import Data.Containers.ListUtils (nubOrd)
+import Data.Char (isSpace)
+import Data.List (isPrefixOf, isSuffixOf)
+import Data.String (fromString)
+import qualified Data.Map as M
+import Data.Maybe (fromMaybe, mapMaybe, maybeToList)
+import qualified Data.Set as Set
+import qualified Data.Text as T
+import Data.Text (Text)
+import Data.Time.Clock.POSIX
+import Skylighting
+import Text.Pandoc.Class (PandocMonad, toLang)
+import qualified Text.Pandoc.Class.PandocMonad as P
+import Text.Pandoc.Data (readDataFile, readDefaultDataFile)
+import Data.Time
+import qualified Text.Pandoc.UTF8 as UTF8
+import Text.Pandoc.Definition
+import Text.Pandoc.Error
+import Text.Pandoc.Highlighting (defaultStyle)
+import Text.Pandoc.MIME (MimeType, getMimeTypeDef)
+import Text.Pandoc.Options
+import Text.Pandoc.Writers.Docx.StyleMap
+import Text.Pandoc.Writers.Docx.Types
+import Text.Pandoc.Writers.Docx.OpenXML (writeOpenXML, maxListLevel)
+import Text.Pandoc.Shared
+import Text.Pandoc.Walk
+import Text.Pandoc.Writers.Shared
+import Text.Pandoc.Writers.OOXML
+import Text.Pandoc.XML.Light as XML
+import Text.Collate.Lang (renderLang, Lang(..))
+
+writeDocx :: (PandocMonad m)
+          => WriterOptions  -- ^ Writer options
+          -> Pandoc         -- ^ Document to convert
+          -> m BL.ByteString
+writeDocx opts doc = do
+  -- Phase 1: Document preprocessing
+  let Pandoc meta blocks = walk fixDisplayMath doc
+  setupTranslations meta
+  let blocks' = makeSectionsWithOffsets (writerNumberOffset opts)
+                   True Nothing blocks
+  let doc' = Pandoc meta blocks'
+
+  -- Phase 2: Archive loading
+  (refArchive, distArchive, username, utctime) <- loadArchives opts
+  let epochtime = floor $ utcTimeToPOSIXSeconds utctime
+
+  -- Phase 3: Page layout extraction
+  (mbsectpr, pgContentWidth) <- extractPageLayout refArchive distArchive
+
+  -- Phase 4: Language & style setup
+  mblang <- toLang $ getLang opts meta
+  let addLang = mkLangTransformer mblang
+  styledoc <- addLang <$> parseXml refArchive distArchive "word/styles.xml"
+  let styleMaps = getStyleMaps refArchive
+
+  let tocTitle = case lookupMetaInlines "toc-title" meta of
+                   [] -> stTocTitle defaultWriterState
+                   ls -> ls
+
+  let isRTLmeta = case lookupMeta "dir" meta of
+        Just (MetaString "rtl")        -> True
+        Just (MetaInlines [Str "rtl"]) -> True
+        _                              -> False
+
+  let env = defaultWriterEnv {
+          envRTL = isRTLmeta
+        , envChangesAuthor = fromMaybe "unknown" username
+        , envChangesDate   = T.pack $ formatTime defaultTimeLocale "%FT%XZ" utctime
+        , envPrintWidth = maybe 420 (`quot` 20) pgContentWidth
+        }
+
+  -- Phase 5: Relationship extraction
+  (baserels, headers, footers, newMaxRelId) <- extractRelationships refArchive distArchive
+
+  let initialSt = defaultWriterState {
+          stStyleMaps  = styleMaps
+        , stTocTitle   = tocTitle
+        , stCurId      = newMaxRelId + 1
+        }
+
+  -- Phase 6: Core content generation
+  -- adjust contents to add sectPr from reference.docx
+  let sectpr = case mbsectpr of
+        Just sectpr' -> add_attrs (elAttribs sectpr') $ mknode "w:sectPr" []
+                             (elChildren sectpr')
+        Nothing      -> mknode "w:sectPr" []
+                          [ mknode "w:footnotePr" []
+                            [ mknode "w:numRestart" [("w:val","eachSect")] () ]
+                          ]
+
+  ((contents, footnotes, comments), st) <- runStateT
+                         (runReaderT
+                          (writeOpenXML opts{ writerWrapText = WrapNone }
+                                        doc')
+                          env{ envSectPr = Just sectpr })
+                         initialSt
+  let imgs = M.elems $ stImages st
+
+  -- Phase 7: XML document construction
+  -- We create [Content_Types].xml and word/_rels/document.xml.rels
+  -- from scratch rather than reading from reference.docx,
+  -- because Word sometimes changes these files when a reference.docx is modified,
+  -- e.g. deleting the reference to footnotes.xml or removing default entries
+  -- for image content types.
+  let contentTypesEntry = mkContentTypesEntry epochtime imgs headers footers refArchive
+  let relEntry = mkDocumentRelsEntry epochtime baserels imgs (stExternalLinks st)
+  let contentEntry = toEntry "word/document.xml" epochtime
+                       (BL.fromStrict $ UTF8.fromText contents)
+  let footnotesEntry = mkFootnotesEntry epochtime footnotes
+  let footnoteRelEntry = mkFootnoteRelsEntry epochtime (stExternalLinks st)
+  let commentsEntry = mkCommentsEntry epochtime comments
+  let styleEntry = mkStylesEntry epochtime styledoc styleMaps st opts
+  numEntry <- mkNumberingEntry refArchive distArchive epochtime (stLists st)
+  let docPropsEntry = mkCorePropsEntry epochtime utctime meta
+  let customPropsEntry = mkCustomPropsEntry epochtime meta
+  let relsEntry = mkPackageRelsEntry epochtime
+
+  -- we use dist archive for settings.xml, because Word sometimes
+  -- adds references to footnotes or endnotes we don't have...
+  -- we do, however, copy some settings over from reference
+  settingsEntry <- copyChildren refArchive distArchive "word/settings.xml"
+                     epochtime settingsElementNames
+
+  -- Phase 8: Archive assembly
+  let toImageEntry (_, path, _, img) = toEntry ("word/" ++ path) epochtime $ toLazy img
+  let imageEntries = map toImageEntry imgs
+
+  refEntries <- collectReferenceEntries refArchive distArchive headers footers
+
+  let archive = foldr addEntryToArchive emptyArchive $
+                  contentTypesEntry : relsEntry : contentEntry : relEntry :
+                  footnoteRelEntry : numEntry : styleEntry : footnotesEntry :
+                  commentsEntry :
+                  docPropsEntry : customPropsEntry :
+                  settingsEntry :
+                  imageEntries ++ refEntries
+  return $ fromArchive archive
+
+newParaPropToOpenXml :: ParaStyleName -> Element
+newParaPropToOpenXml (fromStyleName -> s) =
+  let styleId = T.filter (not . isSpace) s
+  in mknode "w:style" [ ("w:type", "paragraph")
+                      , ("w:customStyle", "1")
+                      , ("w:styleId", styleId)]
+     [ mknode "w:name" [("w:val", s)] ()
+     , mknode "w:basedOn" [("w:val","BodyText")] ()
+     , mknode "w:qFormat" [] ()
+     ]
+
+newTextPropToOpenXml :: CharStyleName -> Element
+newTextPropToOpenXml (fromStyleName -> s) =
+  let styleId = T.filter (not . isSpace) s
+  in mknode "w:style" [ ("w:type", "character")
+                      , ("w:customStyle", "1")
+                      , ("w:styleId", styleId)]
+     [ mknode "w:name" [("w:val", s)] ()
+     , mknode "w:basedOn" [("w:val","BodyTextChar")] ()
+     ]
+
+styleToOpenXml :: StyleMaps -> Style -> [Element]
+styleToOpenXml sm style =
+  maybeToList parStyle ++ mapMaybe toStyle alltoktypes
+  where alltoktypes = enumFromTo KeywordTok NormalTok
+        toStyle toktype | hasStyleName (fromString $ show toktype) (smCharStyle sm) = Nothing
+                        | otherwise = Just $
+                          mknode "w:style" [("w:type","character"),
+                           ("w:customStyle","1"),("w:styleId", tshow toktype)]
+                             [ mknode "w:name" [("w:val", tshow toktype)] ()
+                             , mknode "w:basedOn" [("w:val","VerbatimChar")] ()
+                             , mknode "w:rPr" [] $
+                               [ mknode "w:b" [] () | tokFeature tokenBold toktype ] ++
+                               [ mknode "w:i" [] () | tokFeature tokenItalic toktype ] ++
+                               [ mknode "w:color" [("w:val", tokCol toktype)] ()
+                                 | tokCol toktype /= "auto" ] ++
+                               [ mknode "w:u" [] () | tokFeature tokenUnderline toktype ] ++
+                               [ mknode "w:shd" [("w:val","clear")
+                                                ,("w:fill",tokBg toktype)] ()
+                                 | tokBg toktype /= "auto" ]
+                             ]
+        tokStyles = tokenStyles style
+        tokFeature f toktype = maybe False f $ M.lookup toktype tokStyles
+        tokCol toktype = maybe "auto" (T.pack . drop 1 . fromColor)
+                         $ (tokenColor =<< M.lookup toktype tokStyles)
+                           `mplus` defaultColor style
+        tokBg toktype = maybe "auto" (T.pack . drop 1 . fromColor)
+                         $ (tokenBackground =<< M.lookup toktype tokStyles)
+                           `mplus` backgroundColor style
+        parStyle | hasStyleName "Source Code" (smParaStyle sm) = Nothing
+                 | otherwise = Just $
+                   mknode "w:style" [("w:type","paragraph"),
+                           ("w:customStyle","1"),("w:styleId","SourceCode")]
+                             [ mknode "w:name" [("w:val","Source Code")] ()
+                             , mknode "w:basedOn" [("w:val","Normal")] ()
+                             , mknode "w:link" [("w:val","VerbatimChar")] ()
+                             , mknode "w:pPr" []
+                               $ mknode "w:wordWrap" [("w:val","off")] ()
+                               :
+                         maybe [] (\col -> [mknode "w:shd" [("w:val","clear"),("w:fill", T.pack $ drop 1 $ fromColor col)] ()]) (backgroundColor style)
+                             ]
+
+copyChildren :: (PandocMonad m)
+             => Archive -> Archive -> String -> Integer -> [Text] -> m Entry
+copyChildren refArchive distArchive path timestamp elNames = do
+  ref  <- parseXml refArchive distArchive path
+  dist <- parseXml distArchive distArchive path
+  els <- foldM (addEl ref dist) [] (reverse elNames)
+  return $ toEntry path timestamp
+         $ renderXml dist{ elContent = map cleanElem els }
+  where
+    addEl ref dist els name =
+      case filterChildName (hasName name) ref `mplus`
+             filterChildName (hasName name) dist of
+        Just el -> pure (el : els)
+        Nothing -> pure els
+    hasName name = (== name) . qName
+    cleanElem el@Element{elName=name} = Elem el{elName=name{qURI=Nothing}}
+
+-- this is the lowest number used for a list numId
+baseListId :: Int
+baseListId = 1000
+
+-- | Standard XML namespace attributes for docx elements
+stdAttributes :: [(Text, Text)]
+stdAttributes =
+  [("xmlns:w","http://schemas.openxmlformats.org/wordprocessingml/2006/main")
+  ,("xmlns:m","http://schemas.openxmlformats.org/officeDocument/2006/math")
+  ,("xmlns:r","http://schemas.openxmlformats.org/officeDocument/2006/relationships")
+  ,("xmlns:o","urn:schemas-microsoft-com:office:office")
+  ,("xmlns:v","urn:schemas-microsoft-com:vml")
+  ,("xmlns:w10","urn:schemas-microsoft-com:office:word")
+  ,("xmlns:a","http://schemas.openxmlformats.org/drawingml/2006/main")
+  ,("xmlns:pic","http://schemas.openxmlformats.org/drawingml/2006/picture")
+  ,("xmlns:wp","http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing")]
+
+-- | Settings elements to copy from reference.docx (order matters)
+settingsElementNames :: [Text]
+settingsElementNames =
+  [ "writeProtection"
+  , "view"
+  , "zoom"
+  , "removePersonalInformation"
+  , "removeDateAndTime"
+  , "doNotDisplayPageBoundaries"
+  , "displayBackgroundShape"
+  , "printPostScriptOverText"
+  , "printFractionalCharacterWidth"
+  , "printFormsData"
+  , "embedTrueTypeFonts"
+  , "embedSystemFonts"
+  , "saveSubsetFonts"
+  , "saveFormsData"
+  , "mirrorMargins"
+  , "alignBordersAndEdges"
+  , "bordersDoNotSurroundHeader"
+  , "bordersDoNotSurroundFooter"
+  , "gutterAtTop"
+  , "hideSpellingErrors"
+  , "hideGrammaticalErrors"
+  , "activeWritingStyle"
+  , "proofState"
+  , "formsDesign"
+  , "attachedTemplate"
+  , "linkStyles"
+  , "stylePaneFormatFilter"
+  , "stylePaneSortMethod"
+  , "documentType"
+  , "mailMerge"
+  , "revisionView"
+  , "trackRevisions"
+  , "doNotTrackMoves"
+  , "doNotTrackFormatting"
+  , "documentProtection"
+  , "autoFormatOverride"
+  , "styleLockTheme"
+  , "styleLockQFSet"
+  , "defaultTabStop"
+  , "autoHyphenation"
+  , "consecutiveHyphenLimit"
+  , "hyphenationZone"
+  , "doNotHyphenateCaps"
+  , "showEnvelope"
+  , "summaryLength"
+  , "clickAndTypeStyle"
+  , "defaultTableStyle"
+  , "evenAndOddHeaders"
+  , "bookFoldRevPrinting"
+  , "bookFoldPrinting"
+  , "bookFoldPrintingSheets"
+  , "drawingGridHorizontalSpacing"
+  , "drawingGridVerticalSpacing"
+  , "displayHorizontalDrawingGridEvery"
+  , "displayVerticalDrawingGridEvery"
+  , "doNotUseMarginsForDrawingGridOrigin"
+  , "drawingGridHorizontalOrigin"
+  , "drawingGridVerticalOrigin"
+  , "doNotShadeFormData"
+  , "noPunctuationKerning"
+  , "characterSpacingControl"
+  , "printTwoOnOne"
+  , "strictFirstAndLastChars"
+  , "noLineBreaksAfter"
+  , "noLineBreaksBefore"
+  , "savePreviewPicture"
+  , "doNotValidateAgainstSchema"
+  , "saveInvalidXml"
+  , "ignoreMixedContent"
+  , "alwaysShowPlaceholderText"
+  , "doNotDemarcateInvalidXml"
+  , "saveXmlDataOnly"
+  , "useXSLTWhenSaving"
+  , "saveThroughXslt"
+  , "showXMLTags"
+  , "alwaysMergeEmptyNamespace"
+  , "updateFields"
+  , "hdrShapeDefaults"
+  -- , "footnotePr" -- this can cause problems, see #9522
+  -- , "endnotePr"
+  , "compat"
+  , "docVars"
+  , "rsids"
+  , "attachedSchema"
+  , "themeFontLang"
+  , "clrSchemeMapping"
+  , "doNotIncludeSubdocsInStats"
+  , "doNotAutoCompressPictures"
+  , "forceUpgrade"
+  , "captions"
+  , "readModeInkLockDown"
+  , "smartTagType"
+  , "shapeDefaults"
+  , "doNotEmbedSmartTags"
+  , "decimalSymbol"
+  , "listSeparator" ]
+
+mkNumbering :: [ListMarker] -> [Element]
+mkNumbering lists =
+  elts ++ zipWith mkNum lists [baseListId..(baseListId + length lists - 1)]
+    where elts = map mkAbstractNum (nubOrd lists)
+
+mkNum :: ListMarker -> Int -> Element
+mkNum marker numid =
+  mknode "w:num" [("w:numId",tshow numid)]
+   $ mknode "w:abstractNumId" [("w:val",listMarkerToId marker)] ()
+   : case marker of
+       NoMarker     -> []
+       BulletMarker -> []
+       CheckboxMarker _ -> []
+       NumberMarker _ _ start ->
+          map (\lvl -> mknode "w:lvlOverride" [("w:ilvl",tshow (lvl :: Int))]
+              $ mknode "w:startOverride" [("w:val",tshow start)] ())
+                [0..maxListLevel]
+
+mkAbstractNum :: ListMarker -> Element
+mkAbstractNum marker =
+  mknode "w:abstractNum" [("w:abstractNumId",listMarkerToId marker)]
+    $ mknode "w:nsid" [("w:val", T.justifyRight 8 '0' ("A" <> listMarkerToId marker))] ()
+    : mknode "w:multiLevelType" [("w:val","multilevel")] ()
+    : map (mkLvl marker)
+      [0..maxListLevel]
+
+mkLvl :: ListMarker -> Int -> Element
+mkLvl marker lvl =
+  mknode "w:lvl" [("w:ilvl",tshow lvl)] $
+    (case marker of
+        NumberMarker{} -> [mknode "w:start" [("w:val",start)] ()]
+        _ -> []) ++
+    [ mknode "w:numFmt" [("w:val",fmt)] ()
+    , mknode "w:lvlText" [("w:val", lvltxt)] ()
+    , mknode "w:lvlJc" [("w:val","left")] ()
+    , mknode "w:pPr" [] $
+        mknode "w:ind" [ ("w:left",tshow $ lvl * step + step)
+                       , ("w:hanging",tshow hang)
+                       ] ()
+    ] ++
+    maybe [] (\font ->
+                [ mknode "w:rPr" []
+                  [ mknode "w:rFonts" [ ("w:ascii", font)
+                                      , ("w:hAnsi", font)
+                                      , ("w:cs", font)
+                                      , ("w:hint", "default") ] () ]]) mbfont
+    where (fmt, lvltxt, mbfont, start) =
+            case marker of
+                 NoMarker             -> ("bullet"," ", Nothing, "1")
+                 BulletMarker         -> bulletFor lvl
+                 CheckboxMarker False -> ("bullet","\9744", Nothing, "1")
+                 CheckboxMarker True  -> ("bullet","\9746", Nothing, "1")
+                 NumberMarker st de n -> (styleFor st lvl
+                                         ,patternFor de ("%" <> tshow (lvl + 1))
+                                         ,Nothing
+                                         ,tshow n)
+          step = 720
+          hang :: Int
+          hang = 360
+          bulletFor 0 = ("bullet", "\xf0b7", Just "Symbol", "1") -- filled circle
+          bulletFor 1 = ("bullet", "o", Just "Courier New", "1") -- open o
+          bulletFor 2 = ("bullet", "\xf0a7", Just "Wingdings", "1")  -- closed box
+          bulletFor x = bulletFor (x `mod` 3)
+          styleFor UpperAlpha _   = "upperLetter"
+          styleFor LowerAlpha _   = "lowerLetter"
+          styleFor UpperRoman _   = "upperRoman"
+          styleFor LowerRoman _   = "lowerRoman"
+          styleFor Decimal _      = "decimal"
+          styleFor DefaultStyle 0 = "decimal"
+          styleFor DefaultStyle 1 = "lowerLetter"
+          styleFor DefaultStyle 2 = "lowerRoman"
+          styleFor DefaultStyle 3 = "decimal"
+          styleFor DefaultStyle 4 = "lowerLetter"
+          styleFor DefaultStyle 5 = "lowerRoman"
+          styleFor DefaultStyle x = styleFor DefaultStyle (x `mod` 6)
+          styleFor _ _            = "decimal"
+          patternFor OneParen s  = s <> ")"
+          patternFor TwoParens s = "(" <> s <> ")"
+          patternFor _ s         = s <> "."
+
+-- | Build language transformer function for modifying XML elements.
+-- Navigates directly to w:docDefaults/w:rPr/w:lang instead of generic traversal.
+mkLangTransformer :: Maybe Lang -> (Element -> Element)
+mkLangTransformer Nothing  = id
+mkLangTransformer (Just lang) = modifyAtPath path updateLangAttrs
+  where
+    -- Path is: w:docDefaults / w:rPrDefault / w:rPr / w:lang
+    path = [named "docDefaults", named "rPrDefault", named "rPr", named "lang"]
+    named n = (== n) . qName
+
+    updateLangAttrs e
+      | isEastAsianLang lang = e{ elAttribs = map (setattr "eastAsia") $ elAttribs e }
+      | isBidiLang lang      = e{ elAttribs = map (setattr "bidi") $ elAttribs e }
+      | otherwise            = e{ elAttribs = map (setattr "val") $ elAttribs e }
+
+    setattr attrname (XML.Attr qn@(QName s _ _) _)
+      | s == attrname  = XML.Attr qn (renderLang lang)
+    setattr _ x        = x
+
+    isEastAsianLang Lang{ langLanguage = l } = l == "zh" || l == "ja" || l == "ko"
+    isBidiLang Lang{ langLanguage = l } = l == "he" || l == "ar"
+
+-- | Modify an element at a specific path in the XML tree.
+-- The path is a list of predicates that match element names at each level.
+modifyAtPath :: [(QName -> Bool)] -> (Element -> Element) -> Element -> Element
+modifyAtPath [] f e = f e
+modifyAtPath (p:ps) f e = e{ elContent = map go (elContent e) }
+  where
+    go (Elem el) | p (elName el) = Elem (modifyAtPath ps f el)
+    go c = c
+
+-- | Load reference and distribution archives
+loadArchives :: PandocMonad m
+             => WriterOptions
+             -> m (Archive, Archive, Maybe Text, UTCTime)
+loadArchives opts = do
+  username <- P.lookupEnv "USERNAME"
+  utctime <- P.getTimestamp
+  oldUserDataDir <- P.getUserDataDir
+  P.setUserDataDir Nothing
+  res <- readDefaultDataFile "reference.docx"
+  P.setUserDataDir oldUserDataDir
+  let distArchive = toArchive $ BL.fromStrict res
+  refArchive <- case writerReferenceDoc opts of
+                   Just f  -> toArchive . BL.fromStrict . fst
+                                 <$> P.fetchItem (T.pack f)
+                   Nothing -> toArchive . BL.fromStrict <$>
+                        readDataFile "reference.docx"
+  return (refArchive, distArchive, username, utctime)
+
+-- | Extract page dimensions from template
+extractPageLayout :: PandocMonad m
+                  => Archive -> Archive -> m (Maybe Element, Maybe Integer)
+extractPageLayout refArchive distArchive = do
+  parsedDoc <- parseXml refArchive distArchive "word/document.xml"
+  let wname f qn = qPrefix qn == Just "w" && f (qName qn)
+  let mbsectpr = filterElementName (wname (=="sectPr")) parsedDoc
+
+  -- Gets the template size
+  let mbpgsz = mbsectpr >>= filterElementName (wname (=="pgSz"))
+  let mbAttrSzWidth = mbpgsz >>= lookupAttrBy ((=="w") . qName) . elAttribs
+
+  let mbpgmar = mbsectpr >>= filterElementName (wname (=="pgMar"))
+  let mbAttrMarLeft = mbpgmar >>= lookupAttrBy ((=="left") . qName) . elAttribs
+  let mbAttrMarRight = mbpgmar >>= lookupAttrBy ((=="right") . qName) . elAttribs
+
+  -- Get the available area (converting the size and the margins to int and
+  -- doing the difference
+  let pgContentWidth = do
+                         w <- mbAttrSzWidth >>= safeRead
+                         r <- mbAttrMarRight >>= safeRead
+                         l <- mbAttrMarLeft >>= safeRead
+                         pure $ w - r - l
+
+  return (mbsectpr, pgContentWidth)
+
+-- | Parse and augment relationships from reference.docx
+extractRelationships :: PandocMonad m
+                     => Archive -> Archive
+                     -> m ([Element], [Element], [Element], Int)
+extractRelationships refArchive distArchive = do
+  let isImageNode e = findAttr (QName "Type" Nothing Nothing) e == Just "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image"
+  let isHeaderNode e = findAttr (QName "Type" Nothing Nothing) e == Just "http://schemas.openxmlformats.org/officeDocument/2006/relationships/header"
+  let isFooterNode e = findAttr (QName "Type" Nothing Nothing) e == Just "http://schemas.openxmlformats.org/officeDocument/2006/relationships/footer"
+  parsedRels <- filterElements
+                  (\e -> isImageNode e || isHeaderNode e || isFooterNode e)
+              <$> parseXml refArchive distArchive "word/_rels/document.xml.rels"
+  let getRelId e =
+        case findAttr (QName "Id" Nothing Nothing) e of
+          Just ident -> T.stripPrefix "rId" ident >>= safeRead
+          Nothing -> Nothing
+  let relIds = mapMaybe getRelId parsedRels
+  let maxRelId = if null relIds then 0 else maximum relIds
+
+  let headers = filter isHeaderNode parsedRels
+  let footers = filter isFooterNode parsedRels
+  -- word/_rels/document.xml.rels
+  let addBaseRel (url', target') (maxId, rels) =
+        case [e | e <- rels
+                , findAttr (QName "Target" Nothing Nothing) e ==
+                   Just target'] of
+          [] -> (maxId + 1, mknode "Relationship"
+                            [("Type",url')
+                            ,("Id","rId" <> tshow (maxId + 1))
+                            ,("Target",target')] () : rels)
+          _ -> (maxId, rels)
+
+  let (newMaxRelId, baserels) = foldr addBaseRel (maxRelId, parsedRels)
+                    [("http://schemas.openxmlformats.org/officeDocument/2006/relationships/numbering",
+                      "numbering.xml")
+                    ,("http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles",
+                      "styles.xml")
+                    ,("http://schemas.openxmlformats.org/officeDocument/2006/relationships/settings",
+                      "settings.xml")
+                    ,("http://schemas.openxmlformats.org/officeDocument/2006/relationships/webSettings",
+                      "webSettings.xml")
+                    ,("http://schemas.openxmlformats.org/officeDocument/2006/relationships/fontTable",
+                      "fontTable.xml")
+                    ,("http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme",
+                      "theme/theme1.xml")
+                    ,("http://schemas.openxmlformats.org/officeDocument/2006/relationships/footnotes",
+                      "footnotes.xml")
+                    ,("http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments",
+                      "comments.xml")
+                    ]
+
+  return (baserels, headers, footers, newMaxRelId)
+
+-- | Create footnotes XML entry
+mkFootnotesEntry :: Integer -> [Element] -> Entry
+mkFootnotesEntry epochtime footnotes =
+  let notes = mknode "w:footnotes" stdAttributes footnotes
+  in toEntry "word/footnotes.xml" epochtime $ renderXml notes
+
+-- | Create footnote relationships entry
+mkFootnoteRelsEntry :: Integer -> M.Map Text Text -> Entry
+mkFootnoteRelsEntry epochtime externalLinks =
+  let linkrels = map toLinkRel $ M.toList externalLinks
+      toLinkRel (src, ident) = mknode "Relationship"
+        [("Type","http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink")
+        ,("Id",ident)
+        ,("Target",src)
+        ,("TargetMode","External")] ()
+  in toEntry "word/_rels/footnotes.xml.rels" epochtime
+       $ renderXml $ mknode "Relationships"
+           [("xmlns","http://schemas.openxmlformats.org/package/2006/relationships")]
+           linkrels
+
+-- | Create comments XML entry
+mkCommentsEntry :: Integer -> [Element] -> Entry
+mkCommentsEntry epochtime comments =
+  toEntry "word/comments.xml" epochtime
+    $ renderXml $ mknode "w:comments" stdAttributes comments
+
+-- | Create package-level relationships entry
+mkPackageRelsEntry :: Integer -> Entry
+mkPackageRelsEntry epochtime =
+  let rels = mknode "Relationships"
+        [("xmlns", "http://schemas.openxmlformats.org/package/2006/relationships")]
+        $ map (\attrs -> mknode "Relationship" attrs ())
+        [ [("Id","rId1")
+          ,("Type","http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument")
+          ,("Target","word/document.xml")]
+        , [("Id","rId4")
+          ,("Type","http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties")
+          ,("Target","docProps/app.xml")]
+        , [("Id","rId3")
+          ,("Type","http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties")
+          ,("Target","docProps/core.xml")]
+        , [("Id","rId5")
+          ,("Type","http://schemas.openxmlformats.org/officeDocument/2006/relationships/custom-properties")
+          ,("Target","docProps/custom.xml")]
+        ]
+  in toEntry "_rels/.rels" epochtime $ renderXml rels
+
+-- | Create content types manifest entry
+mkContentTypesEntry :: Integer
+                    -> [(String, String, Maybe MimeType, B.ByteString)]  -- imgs
+                    -> [Element]  -- headers
+                    -> [Element]  -- footers
+                    -> Archive    -- refArchive
+                    -> Entry
+mkContentTypesEntry epochtime imgs headers footers refArchive =
+  let mkOverrideNode (part', contentType') = mknode "Override"
+           [("PartName", T.pack part')
+           ,("ContentType", contentType')] ()
+      mkImageOverride (_, imgpath, mbMimeType, _) =
+          mkOverrideNode ("/word/" <> imgpath,
+                          fromMaybe "application/octet-stream" mbMimeType)
+      mkMediaOverride imgpath =
+          mkOverrideNode ("/" <> imgpath, getMimeTypeDef imgpath)
+      unrelativize ('/':xs) = '/':xs
+      unrelativize xs = "/word/" ++ xs
+      overrides = map mkOverrideNode (
+                  [("/word/webSettings.xml",
+                    "application/vnd.openxmlformats-officedocument.wordprocessingml.webSettings+xml")
+                  ,("/word/numbering.xml",
+                    "application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml")
+                  ,("/word/settings.xml",
+                    "application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml")
+                  ,("/word/theme/theme1.xml",
+                    "application/vnd.openxmlformats-officedocument.theme+xml")
+                  ,("/word/fontTable.xml",
+                    "application/vnd.openxmlformats-officedocument.wordprocessingml.fontTable+xml")
+                  ,("/docProps/app.xml",
+                    "application/vnd.openxmlformats-officedocument.extended-properties+xml")
+                  ,("/docProps/core.xml",
+                    "application/vnd.openxmlformats-package.core-properties+xml")
+                  ,("/docProps/custom.xml",
+                    "application/vnd.openxmlformats-officedocument.custom-properties+xml")
+                  ,("/word/styles.xml",
+                    "application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml")
+                  ,("/word/document.xml",
+                    "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml")
+                  ,("/word/comments.xml",
+                    "application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml")
+                  ,("/word/footnotes.xml",
+                    "application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml")
+                  ] ++
+                  map (\x -> (maybe "" (unrelativize . T.unpack) (extractTarget x),
+                       "application/vnd.openxmlformats-officedocument.wordprocessingml.header+xml")) headers ++
+                  map (\x -> (maybe "" (unrelativize . T.unpack) (extractTarget x),
+                       "application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml")) footers) ++
+                    map mkImageOverride imgs ++
+                    [ mkMediaOverride (eRelativePath e)
+                        | e <- zEntries refArchive
+                        , "word/media/" `isPrefixOf` eRelativePath e
+                        , not ("/" `isSuffixOf` eRelativePath e) ]
+      mkDefaultNode (ext, mt) =
+        mknode "Default" [("Extension",ext),("ContentType",mt)] ()
+      defaultnodes = map mkDefaultNode
+        [("xml", "application/xml"),
+         ("rels", "application/vnd.openxmlformats-package.relationships+xml"),
+         ("odttf",
+           "application/vnd.openxmlformats-officedocument.obfuscatedFont")]
+      contentTypesDoc = mknode "Types"
+        [("xmlns","http://schemas.openxmlformats.org/package/2006/content-types")]
+        $ defaultnodes ++ overrides
+  in toEntry "[Content_Types].xml" epochtime $ renderXml contentTypesDoc
+
+-- | Create document relationships entry
+mkDocumentRelsEntry :: Integer
+                    -> [Element]  -- baserels
+                    -> [(String, String, Maybe MimeType, B.ByteString)]  -- imgs
+                    -> M.Map Text Text  -- externalLinks
+                    -> Entry
+mkDocumentRelsEntry epochtime baserels imgs externalLinks =
+  let toImgRel (ident, path, _, _) = mknode "Relationship"
+        [("Type","http://schemas.openxmlformats.org/officeDocument/2006/relationships/image")
+        ,("Id",T.pack ident)
+        ,("Target",T.pack path)] ()
+      imgrels = map toImgRel imgs
+      toLinkRel (src, ident) = mknode "Relationship"
+        [("Type","http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink")
+        ,("Id",ident)
+        ,("Target",src)
+        ,("TargetMode","External")] ()
+      linkrels = map toLinkRel $ M.toList externalLinks
+      reldoc = mknode "Relationships"
+        [("xmlns","http://schemas.openxmlformats.org/package/2006/relationships")]
+        $ baserels ++ imgrels ++ linkrels
+  in toEntry "word/_rels/document.xml.rels" epochtime $ renderXml reldoc
+
+-- | Create styles entry with dynamic additions
+mkStylesEntry :: Integer -> Element -> StyleMaps -> WriterState -> WriterOptions -> Entry
+mkStylesEntry epochtime styledoc styleMaps st opts =
+  let stylepath = "word/styles.xml"
+      -- We only want to inject paragraph and text properties that
+      -- are not already in the style map. Note that keys in the stylemap
+      -- are normalized as lowercase.
+      newDynamicParaProps = filter
+        (\sty -> not $ hasStyleName sty $ smParaStyle styleMaps)
+        (Set.toList $ stDynamicParaProps st)
+
+      newDynamicTextProps = filter
+        (\sty -> not $ hasStyleName sty $ smCharStyle styleMaps)
+        (Set.toList $ stDynamicTextProps st)
+
+      newstyles = map newParaPropToOpenXml newDynamicParaProps ++
+                  map newTextPropToOpenXml newDynamicTextProps ++
+                  (case writerHighlightMethod opts of
+                     Skylighting sty -> styleToOpenXml styleMaps sty
+                     DefaultHighlighting -> styleToOpenXml styleMaps
+                                              defaultStyle
+                     _ -> [])
+      styledoc' = styledoc{ elContent = elContent styledoc ++
+                                           map Elem newstyles }
+  in toEntry stylepath epochtime $ renderXml styledoc'
+
+-- | Create core document properties entry
+mkCorePropsEntry :: Integer -> UTCTime -> Meta -> Entry
+mkCorePropsEntry epochtime utctime meta =
+  let metaValueToText (MetaString s)    = s
+      metaValueToText (MetaInlines ils) = stringify ils
+      metaValueToText (MetaBlocks bs)   = stringify bs
+      metaValueToText (MetaBool b)      = T.pack (show b)
+      metaValueToText _                 = ""
+      keywords = case lookupMeta "keywords" meta of
+                       Just (MetaList xs) -> map metaValueToText xs
+                       _                  -> []
+      docPropsPath = "docProps/core.xml"
+      extraCoreProps = ["subject","lang","category","description"]
+      extraCorePropsMap = M.fromList $ zip extraCoreProps
+                       ["dc:subject","dc:language","cp:category","dc:description"]
+      lookupMetaString' :: Text -> Meta -> Text
+      lookupMetaString' key' meta' =
+        case key' of
+             "description" -> T.intercalate "_x000d_\n"
+                                (map stringify $ lookupMetaBlocks "description" meta')
+             key''         -> lookupMetaString key'' meta'
+
+      docProps = mknode "cp:coreProperties"
+          [("xmlns:cp","http://schemas.openxmlformats.org/package/2006/metadata/core-properties")
+          ,("xmlns:dc","http://purl.org/dc/elements/1.1/")
+          ,("xmlns:dcterms","http://purl.org/dc/terms/")
+          ,("xmlns:dcmitype","http://purl.org/dc/dcmitype/")
+          ,("xmlns:xsi","http://www.w3.org/2001/XMLSchema-instance")]
+          $ mktnode "dc:title" [] (stringify $ docTitle meta)
+          : mktnode "dc:creator" [] (T.intercalate "; " (map stringify $ docAuthors meta))
+          : [ mktnode (M.findWithDefault "" k extraCorePropsMap) [] (lookupMetaString' k meta)
+            | k <- M.keys (unMeta meta), k `elem` extraCoreProps]
+          ++ mknode "cp:keywords" [] (T.intercalate ", " keywords)
+          : (\x -> [ mknode "dcterms:created" [("xsi:type","dcterms:W3CDTF")] x
+                   , mknode "dcterms:modified" [("xsi:type","dcterms:W3CDTF")] x
+                   ]) (T.pack $ formatTime defaultTimeLocale "%FT%XZ" utctime)
+  in toEntry docPropsPath epochtime $ renderXml docProps
+
+-- | Create custom document properties entry
+mkCustomPropsEntry :: Integer -> Meta -> Entry
+mkCustomPropsEntry epochtime meta =
+  let extraCoreProps = ["subject","lang","category","description"]
+      customProperties :: [(Text, Text)]
+      customProperties = [ (k, lookupMetaString k meta)
+                         | k <- M.keys (unMeta meta)
+                         , k `notElem` (["title", "author", "keywords"]
+                                       ++ extraCoreProps)]
+      mkCustomProp (k, v) pid = mknode "property"
+         [("fmtid","{D5CDD505-2E9C-101B-9397-08002B2CF9AE}")
+         ,("pid", tshow pid)
+         ,("name", k)] $ mknode "vt:lpwstr" [] v
+      customPropsPath = "docProps/custom.xml"
+      customProps = mknode "Properties"
+          [("xmlns","http://schemas.openxmlformats.org/officeDocument/2006/custom-properties")
+          ,("xmlns:vt","http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes")
+          ] $ zipWith mkCustomProp customProperties [(2 :: Int)..]
+  in toEntry customPropsPath epochtime $ renderXml customProps
+
+-- | Create numbering entry
+mkNumberingEntry :: PandocMonad m
+                 => Archive -> Archive -> Integer -> [ListMarker] -> m Entry
+mkNumberingEntry refArchive distArchive epochtime lists = do
+  let numpath = "word/numbering.xml"
+  numbering <- parseXml refArchive distArchive numpath
+  let newNumElts = mkNumbering lists
+  let pandocAdded e =
+       case findAttrBy ((== "abstractNumId") . qName) e >>= safeRead of
+         Just numid -> numid >= (990 :: Int)
+         Nothing    ->
+           case findAttrBy ((== "numId") . qName) e >>= safeRead of
+             Just numid -> numid >= (1000 :: Int)
+             Nothing    -> False
+  let oldElts = filter (not . pandocAdded) $ onlyElems (elContent numbering)
+  let allElts = oldElts ++ newNumElts
+  return $ toEntry numpath epochtime $ renderXml numbering{ elContent =
+                       -- we want all the abstractNums first, then the nums,
+                       -- otherwise things break:
+                       [Elem e | e <- allElts
+                               , qName (elName e) == "abstractNum" ] ++
+                       [Elem e | e <- allElts
+                               , qName (elName e) == "num" ] }
+
+-- | Collect auxiliary entries from reference archive
+collectReferenceEntries :: PandocMonad m
+                        => Archive -> Archive -> [Element] -> [Element]
+                        -> m [Entry]
+collectReferenceEntries refArchive distArchive headers footers = do
+  let entryFromArchive arch path =
+         maybe (throwError $ PandocSomeError
+                           $ T.pack $ path ++ " missing in reference docx")
+               return
+               (findEntryByPath path arch `mplus` findEntryByPath path distArchive)
+  docPropsAppEntry <- entryFromArchive refArchive "docProps/app.xml"
+  themeEntry <- entryFromArchive refArchive "word/theme/theme1.xml"
+  fontTableEntry <- entryFromArchive refArchive "word/fontTable.xml"
+  let fontTableRelsEntries = maybeToList $
+       findEntryByPath "word/_rels/fontTable.xml.rels" refArchive
+  let fontEntries = [entry | entry <- zEntries refArchive
+                           , "word/fonts/" `isPrefixOf` (eRelativePath entry)]
+  webSettingsEntry <- entryFromArchive refArchive "word/webSettings.xml"
+  let unrelativize ('/':xs) = xs
+      unrelativize xs = "word/" ++ xs
+  headerFooterEntries <- mapM (entryFromArchive refArchive . unrelativize) $
+                         mapMaybe (fmap T.unpack . extractTarget)
+                         (headers ++ footers)
+  let miscRelEntries = [ e | e <- zEntries refArchive
+                       , "word/_rels/" `isPrefixOf` eRelativePath e
+                       , ".xml.rels" `isSuffixOf` eRelativePath e
+                       , eRelativePath e /= "word/_rels/document.xml.rels"
+                       , eRelativePath e /= "word/_rels/footnotes.xml.rels" ]
+  let otherMediaEntries = [ e | e <- zEntries refArchive
+                          , "word/media/" `isPrefixOf` eRelativePath e ]
+  return $ docPropsAppEntry : themeEntry : fontTableEntry : webSettingsEntry
+         : fontTableRelsEntries ++ fontEntries ++ headerFooterEntries
+         ++ miscRelEntries ++ otherMediaEntries
+
+extractTarget :: Element -> Maybe Text
+extractTarget = findAttr (QName "Target" Nothing Nothing)
diff --git a/src/Text/Pandoc/Writers/Docx/OpenXML.hs b/src/Text/Pandoc/Writers/Docx/OpenXML.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Writers/Docx/OpenXML.hs
@@ -0,0 +1,1146 @@
+{-# LANGUAGE PatternGuards       #-}
+{-# LANGUAGE RankNTypes          #-}
+{-# LANGUAGE ScopedTypeVariables #-}
+{-# LANGUAGE TupleSections       #-}
+{-# LANGUAGE ViewPatterns        #-}
+{-# LANGUAGE FlexibleContexts    #-}
+{-# LANGUAGE LambdaCase          #-}
+{-# LANGUAGE OverloadedStrings   #-}
+{-# LANGUAGE TypeApplications    #-}
+{- |
+   Module      : Text.Pandoc.Writers.Docx
+   Copyright   : Copyright (C) 2012-2025 John MacFarlane
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : John MacFarlane <jgm@berkeley.edu>
+   Stability   : alpha
+   Portability : portable
+
+Conversion of 'Pandoc' documents to docx.
+-}
+module Text.Pandoc.Writers.Docx.OpenXML ( writeOpenXML, maxListLevel ) where
+
+import Control.Monad (when, unless)
+import Control.Applicative ((<|>))
+import Control.Monad.Except (catchError)
+import Crypto.Hash (hashWith, SHA1(SHA1))
+import qualified Data.ByteString.Lazy as BL
+import Data.Char (isLetter, isSpace)
+import Text.Pandoc.Char (isCJK)
+import Data.Ord (comparing)
+import Data.String (fromString)
+import qualified Data.Map as M
+import Data.Maybe (fromMaybe, maybeToList, isJust)
+import Control.Monad.State ( gets, modify, MonadTrans(lift) )
+import Control.Monad.Reader ( asks, MonadReader(local) )
+import qualified Data.Set as Set
+import qualified Data.Text as T
+import Data.Text (Text)
+import Skylighting
+import Text.DocLayout (hcat, vcat, literal, render)
+import Text.Pandoc.Class (PandocMonad, report, getMediaBag)
+import Text.Pandoc.Translations (Term(Abstract), translateTerm)
+import Text.Pandoc.MediaBag (lookupMedia, MediaItem(..))
+import qualified Text.Pandoc.Translations as Term
+import qualified Text.Pandoc.Class.PandocMonad as P
+import qualified Text.Pandoc.Builder as B
+import Text.Pandoc.UTF8 (fromText)
+import Text.Pandoc.Definition
+import Text.Pandoc.Highlighting (highlight)
+import Text.Pandoc.Templates (compileDefaultTemplate, renderTemplate)
+import Text.Pandoc.ImageSize
+import Text.Pandoc.Logging
+import Text.Pandoc.MIME (extensionFromMimeType, getMimeType)
+import Text.Pandoc.Options
+import Text.Pandoc.Writers.Docx.StyleMap
+import Text.Pandoc.Writers.Docx.Table as Table
+import Text.Pandoc.Writers.Docx.Types
+import Text.Pandoc.Shared
+import Text.Pandoc.Walk
+import qualified Text.Pandoc.Writers.GridTable as Grid
+import Text.Pandoc.Writers.Math
+import Text.Pandoc.Writers.Shared
+import Text.TeXMath
+import Text.Pandoc.Writers.OOXML
+import Text.Pandoc.XML.Light as XML
+import Data.List (sortBy, intercalate, groupBy)
+
+-- from wml.xsd EG_RPrBase
+rPrTagOrder :: M.Map Text Int
+rPrTagOrder =
+  M.fromList
+  (zip [ "rStyle"
+    , "rFonts"
+    , "b"
+    , "bCs"
+    , "i"
+    , "iCs"
+    , "caps"
+    , "smallCaps"
+    , "strike"
+    , "dstrike"
+    , "outline"
+    , "shadow"
+    , "emboss"
+    , "imprint"
+    , "noProof"
+    , "snapToGrid"
+    , "vanish"
+    , "webHidden"
+    , "color"
+    , "spacing"
+    , "w"
+    , "kern"
+    , "position"
+    , "sz"
+    , "szCs"
+    , "highlight"
+    , "u"
+    , "effect"
+    , "bdr"
+    , "shd"
+    , "fitText"
+    , "vertAlign"
+    , "rtl"
+    , "cs"
+    , "em"
+    , "lang"
+    , "eastAsianLayout"
+    , "specVanish"
+    , "oMath"
+    ] [0..])
+
+sortSquashed :: [Element] -> [Element]
+sortSquashed l =
+  sortBy (comparing tagIndex) l
+  where
+    tagIndex :: Element -> Int
+    tagIndex el =
+      fromMaybe 0 (M.lookup tag rPrTagOrder)
+      where tag = (qName . elName) el
+
+squashProps :: EnvProps -> [Element]
+squashProps (EnvProps Nothing es) = sortSquashed es
+squashProps (EnvProps (Just e) es) = sortSquashed (e : es)
+
+-- | Certain characters are invalid in XML even if escaped.
+-- See #1992
+stripInvalidChars :: Text -> Text
+stripInvalidChars = T.filter isValidChar
+
+-- | See XML reference
+isValidChar :: Char -> Bool
+isValidChar '\t' = True
+isValidChar '\n' = True
+isValidChar '\r' = True
+isValidChar '\xFFFE' = False
+isValidChar '\xFFFF' = False
+isValidChar c = (' ' <= c && c <= '\xD7FF') || ('\xE000' <= c)
+
+-- this is the lowest number used for a list numId
+baseListId :: Int
+baseListId = 1000
+
+getNumId :: (PandocMonad m) => WS m Int
+getNumId = gets (((baseListId - 1) +) . length . stLists)
+
+makeTOC :: (PandocMonad m) => WriterOptions -> WS m [Element]
+makeTOC opts = do
+  let depth = "1-" <> tshow (writerTOCDepth opts)
+  let tocCmd = "TOC \\o \"" <> depth <> "\" \\h \\z \\u"
+  tocTitle <- gets stTocTitle
+  title <- withParaPropM (pStyleM "TOC Heading") (blocksToOpenXML opts [Para tocTitle])
+  return
+    [mknode "w:sdt" [] [
+      mknode "w:sdtPr" [] (
+        mknode "w:docPartObj" []
+          [mknode "w:docPartGallery" [("w:val","Table of Contents")] (),
+          mknode "w:docPartUnique" [] ()]
+         -- w:docPartObj
+      ), -- w:sdtPr
+      mknode "w:sdtContent" [] (title ++ [ Elem $
+        mknode "w:p" [] (
+          mknode "w:r" [] [
+            mknode "w:fldChar" [("w:fldCharType","begin"),("w:dirty","true")] (),
+            mknode "w:instrText" [("xml:space","preserve")] tocCmd,
+            mknode "w:fldChar" [("w:fldCharType","separate")] (),
+            mknode "w:fldChar" [("w:fldCharType","end")] ()
+          ] -- w:r
+        ) -- w:p
+      ])
+    ]] -- w:sdt
+
+makeLOF :: (PandocMonad m) => WriterOptions -> WS m [Element]
+makeLOF opts = do
+  let lofCmd = "TOC \\h \\z \\t \"Image Caption\" \\c" :: Text
+  lofTitle <- B.toList <$> B.text <$> translateTerm Term.ListOfFigures
+  title <- withParaPropM (pStyleM "TOC Heading") (blocksToOpenXML opts [Para lofTitle])
+  return
+    [mknode "w:sdt" [] [
+      mknode "w:sdtPr" [] (
+        mknode "w:docPartObj" []
+          [mknode "w:docPartGallery" [("w:val","List of Figures")] (),
+          mknode "w:docPartUnique" [] ()]
+         -- w:docPartObj
+      ), -- w:sdtPr
+      mknode "w:sdtContent" [] (title ++ [ Elem $
+        mknode "w:p" [] (
+          mknode "w:r" [] [
+            mknode "w:fldChar" [("w:fldCharType","begin"),("w:dirty","true")] (),
+            mknode "w:instrText" [("xml:space","preserve")] lofCmd,
+            mknode "w:fldChar" [("w:fldCharType","separate")] (),
+            mknode "w:fldChar" [("w:fldCharType","end")] ()
+          ] -- w:r
+        ) -- w:p
+      ]) -- w:sdtContent
+    ]] -- w:sdt
+
+makeLOT :: (PandocMonad m) => WriterOptions -> WS m [Element]
+makeLOT opts = do
+  let lotCmd = "TOC \\h \\z \\t \"Table Caption\" \\c" :: Text
+  lotTitle <- B.toList <$> B.text <$> translateTerm Term.ListOfTables
+  title <- withParaPropM (pStyleM "TOC Heading") (blocksToOpenXML opts [Para lotTitle])
+  return
+    [mknode "w:sdt" [] [
+      mknode "w:sdtPr" [] (
+        mknode "w:docPartObj" []
+          [mknode "w:docPartGallery" [("w:val","List of Tables")] (),
+          mknode "w:docPartUnique" [] ()]
+         -- w:docPartObj
+      ), -- w:sdtPr
+      mknode "w:sdtContent" [] (title ++ [ Elem $
+        mknode "w:p" [] (
+          mknode "w:r" [] [
+            mknode "w:fldChar" [("w:fldCharType","begin"),("w:dirty","true")] (),
+            mknode "w:instrText" [("xml:space","preserve")] lotCmd,
+            mknode "w:fldChar" [("w:fldCharType","separate")] (),
+            mknode "w:fldChar" [("w:fldCharType","end")] ()
+          ] -- w:r
+        ) -- w:p
+      ]) -- w:sdtContent
+    ]] -- w:sdt
+
+-- | Separator element between sections
+sectionSeparator :: PandocMonad m => WS m (Maybe Content)
+sectionSeparator = do
+  asks envSectPr >>= \case
+    Just sectPrElem -> pure $
+      Just $ Elem (mknode "w:p" [] (mknode "w:pPr" [] [sectPrElem]))
+    Nothing -> pure
+      Nothing
+
+-- | Convert Pandoc document to rendered document contents plus two lists of
+-- OpenXML elements (footnotes and comments).
+writeOpenXML :: PandocMonad m
+             => WriterOptions -> Pandoc
+             -> WS m (Text, [Element], [Element])
+writeOpenXML opts (Pandoc meta blocks) = do
+  setupTranslations meta
+  let includeTOC = writerTableOfContents opts || lookupMetaBool "toc" meta
+  let includeLOF = writerListOfFigures opts || lookupMetaBool "lof" meta
+  let includeLOT = writerListOfTables opts || lookupMetaBool "lot" meta
+  abstractTitle <- case lookupMeta "abstract-title" meta of
+      Just (MetaBlocks bs)   -> pure $ stringify bs
+      Just (MetaInlines ils) -> pure $ stringify ils
+      Just (MetaString s)    -> pure s
+      _                      -> translateTerm Abstract
+  abstract <-
+    case lookupMetaBlocks "abstract" meta of
+      [] -> return mempty
+      xs -> vcat . map (literal . showContent) <$>
+              withParaPropM (pStyleM "Abstract") (blocksToOpenXML opts xs)
+
+  let toInlineMeta field = hcat . map (literal . showContent) <$>
+         inlinesToOpenXML opts (lookupMetaInlines field meta)
+
+  title <- toInlineMeta "title"
+  subtitle <- toInlineMeta "subtitle"
+  date <- toInlineMeta "date"
+
+  author <- mapM
+             (fmap (hcat . map (literal . showContent)) . inlinesToOpenXML opts)
+             (docAuthors meta)
+
+  doc' <- setFirstPara >> blocksToOpenXML opts blocks
+  let body = vcat $ map (literal . showContent) doc'
+  notes' <- gets (reverse . stFootnotes)
+  comments <- gets (reverse . stComments)
+  let toComment (kvs, ils) = do
+        annotation <- inlinesToOpenXML opts ils
+        return $
+          mknode "w:comment" [("w:" <> k, v) | (k,v) <- kvs]
+            [ mknode "w:p" [] $
+              map Elem
+              [ mknode "w:pPr" []
+                [ mknode "w:pStyle" [("w:val", "CommentText")] () ]
+              , mknode "w:r" []
+                [ mknode "w:rPr" []
+                  [ mknode "w:rStyle" [("w:val", "CommentReference")] ()
+                  ]
+                  , mknode "w:annotationRef" [] ()
+                ]
+              ] ++ annotation
+            ]
+  comments' <- mapM toComment comments
+  toc <- if includeTOC
+            then makeTOC opts
+            else return []
+  lof <- if includeLOF
+            then makeLOF opts
+            else return []
+  lot <- if includeLOT
+            then makeLOT opts
+            else return []
+  metadata <- metaToContext opts
+                 (fmap (vcat . map (literal . showContent)) . blocksToOpenXML opts)
+                 (fmap (hcat . map (literal . showContent)) . inlinesToOpenXML opts)
+                 meta
+  cStyleMap <- gets (smParaStyle . stStyleMaps)
+  let styleIdOf name = fromStyleId $ getStyleIdFromName name cStyleMap
+  renderedSectPr <- maybe mempty ppElement <$> asks envSectPr
+
+  let context = resetField "body" body
+              . resetField "toc"
+                   (vcat (map (literal . showElement) toc))
+              . resetField "lof"
+                   (vcat (map (literal . showElement) lof))
+              . resetField "lot"
+                   (vcat (map (literal . showElement) lot))
+              . resetField "title" title
+              . resetField "subtitle" subtitle
+              . resetField "author" author
+              . resetField "date" date
+              . resetField "abstract-title" abstractTitle
+              . resetField "abstract" abstract
+              . resetField "title-style-id" (styleIdOf "Title")
+              . resetField "subtitle-style-id" (styleIdOf "Subtitle")
+              . resetField "author-style-id" (styleIdOf "Author")
+              . resetField "date-style-id" (styleIdOf "Date")
+              . resetField "abstract-title-style-id" (styleIdOf "AbstractTitle")
+              . resetField "abstract-style-id" (styleIdOf "Abstract")
+              . resetField "sectpr" renderedSectPr
+              $ metadata
+  tpl <- maybe (lift $ compileDefaultTemplate "openxml") pure $ writerTemplate opts
+  let rendered = render Nothing $ renderTemplate tpl context
+  return (rendered, notes', comments')
+
+-- | Convert a list of Pandoc blocks to OpenXML.
+blocksToOpenXML :: (PandocMonad m) => WriterOptions -> [Block] -> WS m [Content]
+blocksToOpenXML opts =
+  fmap concat . mapM (blockToOpenXML opts)
+  . separateTables . filter (not . isForeignRawBlock)
+
+isForeignRawBlock :: Block -> Bool
+isForeignRawBlock (RawBlock format _) = format /= "openxml"
+isForeignRawBlock _                   = False
+
+-- Word combines adjacent tables unless you put an empty paragraph between
+-- them.  See #4315.
+separateTables :: [Block] -> [Block]
+separateTables [] = []
+separateTables (x@Table{}:xs@(Table{}:_)) =
+  x : RawBlock (Format "openxml") "<w:p />" : separateTables xs
+separateTables (x:xs) = x : separateTables xs
+
+rStyleM :: (PandocMonad m) => CharStyleName -> WS m XML.Element
+rStyleM styleName = do
+  cStyleMap <- gets (smCharStyle . stStyleMaps)
+  let sty' = getStyleIdFromName styleName cStyleMap
+  return $ mknode "w:rStyle" [("w:val", fromStyleId sty')] ()
+
+getUniqueId :: (PandocMonad m) => WS m Text
+getUniqueId = do
+  n <- gets stCurId
+  modify $ \st -> st{stCurId = n + 1}
+  return $ tshow n
+
+-- | Key for specifying user-defined docx styles.
+dynamicStyleKey :: Text
+dynamicStyleKey = "custom-style"
+
+-- | Convert a Pandoc block element to OpenXML.
+blockToOpenXML :: (PandocMonad m) => WriterOptions -> Block -> WS m [Content]
+blockToOpenXML opts blk = withDirection $ blockToOpenXML' opts blk
+
+blockToOpenXML' :: (PandocMonad m) => WriterOptions -> Block -> WS m [Content]
+blockToOpenXML' opts (Div (ident,_classes,kvs) bs) = do
+  stylemod <- case lookup dynamicStyleKey kvs of
+                   Just (fromString . T.unpack -> sty) -> do
+                      modify $ \s ->
+                        s{stDynamicParaProps = Set.insert sty
+                             (stDynamicParaProps s)}
+                      return $ withParaPropM (pStyleM sty)
+                   _ -> return id
+  dirmod <- case lookup "dir" kvs of
+                 Just "rtl" -> return $ local (\env -> env { envRTL = True })
+                 Just "ltr" -> return $ local (\env -> env { envRTL = False })
+                 _ -> return id
+  let (hs, bs') = if ident == "refs"
+                     then span isHeaderBlock bs
+                     else ([], bs)
+  let bibmod = if ident == "refs"
+                  then withParaPropM (pStyleM "Bibliography")
+                  else id
+  let langmod = case lookup "lang" kvs of
+                  Nothing -> id
+                  Just lang -> local (\env -> env{envLang = Just lang})
+  header <- dirmod $ stylemod $ blocksToOpenXML opts hs
+  contents <- dirmod $ bibmod $ stylemod $ langmod $ blocksToOpenXML opts bs'
+  wrapBookmark ident $ header <> contents
+blockToOpenXML' opts (Header lev (ident,_,kvs) lst) = do
+  setFirstPara
+  let isSection = case writerTopLevelDivision opts of
+                     TopLevelChapter -> lev == 1
+                     TopLevelPart -> lev <= 2
+                     _ -> False
+  paraProps <- withParaPropM (pStyleM (fromString $ "Heading "++show lev)) $
+                    getParaProps False
+  number <-
+        if writerNumberSections opts
+           then
+             case lookup "number" kvs of
+                Just n -> do
+                   num <- withTextPropM (rStyleM "SectionNumber")
+                            (inlineToOpenXML opts (Str n))
+                   return $ num ++ [Elem $ mknode "w:r" [] [mknode "w:tab" [] ()]]
+                Nothing -> return []
+           else return []
+  contents <- (number ++) <$> inlinesToOpenXML opts lst
+  -- Add section break before section-level headers, but not for the first one
+  -- to avoid a blank first page (#10578, #11482).
+  addSectionBreak <- if isSection
+    then do
+      isFirst <- gets stFirstSectionHeader
+      if isFirst
+        then do
+          modify $ \s -> s { stFirstSectionHeader = False }
+          pure id
+        else sectionSeparator >>= \case
+          Just sep -> pure (sep:)
+          Nothing  -> pure id
+    else pure id
+  addSectionBreak <$>
+    if T.null ident
+       then return [Elem $ mknode "w:p" [] (map Elem paraProps ++ contents)]
+       else do
+         let bookmarkName = ident
+         modify $ \s -> s{ stSectionIds = Set.insert bookmarkName
+                                        $ stSectionIds s }
+         bookmarkedContents <- wrapBookmark bookmarkName contents
+         return [Elem $ mknode "w:p" [] (map Elem paraProps ++ bookmarkedContents)]
+blockToOpenXML' opts (Plain lst) = do
+  isInTable <- gets stInTable
+  isInList <- gets stInList
+  let block = blockToOpenXML opts (Para lst)
+  prop <- pStyleM "Compact"
+  if isInTable || isInList
+     then withParaProp prop block
+     else block
+blockToOpenXML' opts (Para lst)
+  | null lst && not (isEnabled Ext_empty_paragraphs opts) = return []
+  | [Math InlineMath _] <- lst
+     = blockToOpenXML' opts (Para (lst ++ [Str "\x200B"])) -- see #11674
+       -- we add a space to prevent Word from displaying the single
+       -- inline math element with display math style
+  | otherwise = do
+      isFirstPara <- gets stFirstPara
+      let displayMathPara = case lst of
+                                 [x] -> isDisplayMath x
+                                 _   -> False
+      paraProps <- getParaProps displayMathPara
+      bodyTextStyle <- pStyleM $ if isFirstPara
+                       then "First Paragraph"
+                       else "Body Text"
+      let paraProps' = case paraProps of
+            []               -> [mknode "w:pPr" [] [bodyTextStyle]]
+            ps               -> ps
+      modify $ \s -> s { stFirstPara = False }
+      contents <- inlinesToOpenXML opts lst
+      return [Elem $ mknode "w:p" [] (map Elem paraProps' ++ contents)]
+blockToOpenXML' opts (LineBlock lns) = blockToOpenXML opts $ linesToPara lns
+blockToOpenXML' _ b@(RawBlock format str)
+  | format == Format "openxml" = return [
+        Text (CData CDataRaw str Nothing)
+      ]
+  | otherwise                  = do
+      report $ BlockNotRendered b
+      return []
+blockToOpenXML' opts (BlockQuote blocks) = do
+  inNote <- asks envInNote
+  p <- withParaPropM (pStyleM
+                       (if inNote
+                           then "Footnote Block Text"
+                           else "Block Text"))
+       $ blocksToOpenXML opts blocks
+  setFirstPara
+  return p
+blockToOpenXML' opts (CodeBlock attrs@(ident, _, _) str) = do
+  p <- withParaPropM (pStyleM "Source Code") (blockToOpenXML opts $ Para [Code attrs str])
+  setFirstPara
+  wrapBookmark ident p
+blockToOpenXML' _ HorizontalRule = do
+  setFirstPara
+  return [ Elem $
+    mknode "w:p" [] $ mknode "w:r" [] $ mknode "w:pict" []
+    $ mknode "v:rect" [("style","width:0;height:1.5pt"),
+                       ("o:hralign","center"),
+                       ("o:hrstd","t"),("o:hr","t")] () ]
+blockToOpenXML' opts (Table attr caption colspecs thead tbodies tfoot) = do
+  -- Remove extra paragraph indentation due to list items (#5947).
+  -- This means that tables in lists will not be indented, but it
+  -- avoids unwanted indentation in each cell.
+  content <- tableToOpenXML opts
+              (local (\env -> env{ envListLevel = -1 }) . blocksToOpenXML opts)
+                 (Grid.toTable attr caption colspecs thead tbodies tfoot)
+  let (tableId, _, _) = attr
+  wrapBookmark tableId content
+blockToOpenXML' opts el
+  | BulletList lst <- el
+    = case mapM toTaskListItem lst of
+      Just items -> mconcat <$>
+        mapM (\(checked, bs) -> addOpenXMLList (CheckboxMarker checked) [bs]) items
+      Nothing -> addOpenXMLList BulletMarker lst
+  | OrderedList (start, numstyle, numdelim) lst <- el
+    = addOpenXMLList (NumberMarker numstyle numdelim start) lst
+  where
+    addOpenXMLList marker items = do
+      addList marker
+      numid <- getNumId
+      exampleid <- case marker of
+                     NumberMarker Example _ _ -> gets stExampleId
+                     _ -> return Nothing
+      l <- asList $ concat <$>
+             mapM (listItemToOpenXML opts $ fromMaybe numid exampleid) items
+      setFirstPara
+      return l
+blockToOpenXML' opts (DefinitionList items) = do
+  l <- concat `fmap` mapM (definitionListItemToOpenXML opts) items
+  setFirstPara
+  return l
+blockToOpenXML' opts (Figure (ident, _, _) (Caption _ longcapt) body) = do
+  setFirstPara
+  fignum <- gets stNextFigureNum
+  unless (null longcapt) $ modify $ \st -> st{ stNextFigureNum = fignum + 1 }
+  let refid = if T.null ident
+              then "ref_fig" <> tshow fignum
+              else "ref_" <> ident
+  figname <- translateTerm Term.Figure
+  prop <- pStyleM $
+    if null longcapt
+    then "Figure"
+    else "Captioned Figure"
+  paraProps <- local
+    (\env -> env { envParaProperties = EnvProps (Just prop) [] <>
+                                       envParaProperties env })
+    (getParaProps False)
+
+  -- Figure contents
+  let simpleImage x = do
+        imgXML <- inlineToOpenXML opts x
+        pure $ Elem (mknode "w:p" [] (map Elem paraProps ++ imgXML))
+  contentsNode <- case body of
+    [Plain [img@Image {}]] -> simpleImage img
+    [Para  [img@Image {}]] -> simpleImage img
+    _                      -> toFigureTable opts body
+  -- Caption
+  let imageCaption = withParaPropM (pStyleM "Image Caption")
+                   . blocksToOpenXML opts
+  let fstCaptionPara inlns = Para $
+        if not $ isEnabled Ext_native_numbering opts
+        then inlns
+        else let rawfld = RawInline (Format "openxml") $ mconcat
+                          [ "<w:fldSimple w:instr=\"SEQ Figure"
+                          , " \\* ARABIC \"><w:r><w:t>"
+                          , tshow fignum
+                          , "</w:t></w:r></w:fldSimple>"
+                          ]
+             in Span (refid,[],[]) [Str (figname <> "\160") , rawfld]
+                : Str ": " : inlns
+  captionNode <- case longcapt of
+    []              -> return []
+    (Para xs  : bs) -> imageCaption (fstCaptionPara xs : bs)
+    (Plain xs : bs) -> imageCaption (fstCaptionPara xs : bs)
+    _               -> imageCaption longcapt
+  wrapBookmark ident $
+    case writerFigureCaptionPosition opts of
+      CaptionBelow -> contentsNode : captionNode
+      CaptionAbove -> captionNode ++ [contentsNode]
+
+toFigureTable :: PandocMonad m
+              => WriterOptions -> [Block] -> WS m Content
+toFigureTable opts blks = do
+  modify $ \s -> s { stInTable = True }
+  let ncols = length blks
+  let textwidth = 7920  -- 5.5 in in twips       (1 twip == 1/20 pt)
+  let cellfrac = 1 / fromIntegral ncols
+  let colwidth = tshow @Integer $ floor (textwidth * cellfrac) -- twips
+  let gridCols = replicate ncols $ mknode "w:gridCol" [("w:w", colwidth)] ()
+  let scaleImage = \case
+        Image attr@(ident, classes, attribs) alt tgt ->
+          let dimWidth  = case dimension Width attr of
+                            Nothing -> Percent (cellfrac * 100)
+                            Just d  -> scaleDimension cellfrac d
+              dimHeight = scaleDimension cellfrac <$> dimension Height attr
+              attribs' = (tshow Width, tshow dimWidth) :
+                         (case dimHeight of
+                            Nothing -> id
+                            Just h  -> ((tshow Height, tshow h) :))
+                         [ (k, v) | (k, v) <- attribs
+                                  , k `notElem` ["width", "height"]
+                                  ]
+          in Image (ident, classes, attribs') alt tgt
+        x -> x
+  let blockToCell = Table.OOXMLCell nullAttr AlignCenter 1 1 . (:[])
+                  . walk scaleImage
+  tblBody <- Table.rowToOpenXML (blocksToOpenXML opts) .
+             Table.OOXMLRow Table.BodyRow nullAttr $
+             map blockToCell blks
+  let tbl = mknode "w:tbl" []
+        ( mknode "w:tblPr" []
+          [ mknode "w:tblStyle" [("w:val","FigureTable")] (),
+            mknode "w:tblW" [ ("w:type", "auto"), ("w:w", "0") ] (),
+            mknode "w:jc" [("w:val","center")] (),
+            mknode "w:tblLook" [ ("w:firstRow", "0")
+                               , ("w:lastRow", "0")
+                               , ("w:firstColumn", "0")
+                               , ("w:lastColumn", "0")
+                               ] ()
+          ]
+          : mknode "w:tblGrid" [] gridCols
+          : maybeToList tblBody
+        )
+  modify $ \s -> s { stInTable = False }
+  return $ Elem tbl
+
+
+definitionListItemToOpenXML  :: (PandocMonad m)
+                             => WriterOptions -> ([Inline],[[Block]])
+                             -> WS m [Content]
+definitionListItemToOpenXML opts (term,defs) = do
+  term' <- withParaPropM (pStyleM "Definition Term")
+           $ blockToOpenXML opts (Para term)
+  defs' <- withParaPropM (pStyleM "Definition")
+           $ concat `fmap` mapM (blocksToOpenXML opts) defs
+  return $ term' ++ defs'
+
+addList :: (PandocMonad m) => ListMarker -> WS m ()
+addList marker = do
+  lists <- gets stLists
+  lastExampleId <- gets stExampleId
+  modify $ \st -> st{ stLists = lists ++ case marker of
+                                         -- Use only first occurrence of Example for list declaration to avoid overhead
+                                         NumberMarker Example _ _ | isJust lastExampleId -> []
+                                         _ -> [marker]
+                    , stExampleId = case marker of
+                                         -- Reuse the same identifier for all other occurrences of Example
+                                         NumberMarker Example _ _ -> lastExampleId <|> Just (baseListId + length lists)
+                                         _ -> lastExampleId
+                  }
+
+listItemToOpenXML :: (PandocMonad m)
+                  => WriterOptions
+                  -> Int -> [Block]
+                  -> WS m [Content]
+listItemToOpenXML opts numid bs = do
+  oldInList <- gets stInList
+  modify $ \st -> st{ stInList = True }
+  let isListBlock = \case
+        BulletList{}  -> True
+        OrderedList{} -> True
+        _             -> False
+  -- Prepend an empty string if the first entry is another
+  -- list. Otherwise the outer bullet will disappear.
+  let bs' = case bs of
+                 [] -> []
+                 x:xs -> if isListBlock x
+                               then Plain [Str ""]:x:xs
+                               else x:xs
+  modify $ \st -> st{ stNumIdUsed = False }
+  contents <- withNumId numid $ blocksToOpenXML opts bs'
+  modify $ \st -> st{ stInList = oldInList }
+  return contents
+
+-- | Convert a list of inline elements to OpenXML.
+inlinesToOpenXML :: PandocMonad m => WriterOptions -> [Inline] -> WS m [Content]
+inlinesToOpenXML opts lst = concat `fmap` mapM (inlineToOpenXML opts) (convertSpace lst)
+
+withNumId :: (PandocMonad m) => Int -> WS m a -> WS m a
+withNumId numid = local $ \env -> env{ envListNumId = numid }
+
+asList :: (PandocMonad m) => WS m a -> WS m a
+asList = local $ \env -> env{ envListLevel = envListLevel env + 1 }
+
+getTextProps :: (PandocMonad m) => WS m [Element]
+getTextProps = do
+  props <- asks envTextProperties
+  mblang <- asks envLang
+  let langnode = case mblang of
+                   Nothing -> mempty
+                   Just l  -> EnvProps Nothing
+                               [mknode "w:lang" [("w:val", l)] ()]
+  let squashed = squashProps (props <> langnode)
+  return [mknode "w:rPr" [] squashed | (not . null) squashed]
+
+withTextProp :: PandocMonad m => Element -> WS m a -> WS m a
+withTextProp d p =
+  local (\env -> env {envTextProperties = ep <> envTextProperties env}) p
+  where ep = if isStyle d then EnvProps (Just d) [] else EnvProps Nothing [d]
+
+withTextPropM :: PandocMonad m => WS m Element -> WS m a -> WS m a
+withTextPropM md p = do
+  d <- md
+  withTextProp d p
+
+getParaProps :: PandocMonad m => Bool -> WS m [Element]
+getParaProps displayMathPara = do
+  props <- asks envParaProperties
+  listLevel <- asks envListLevel
+  numid <- asks envListNumId
+  numIdUsed <- gets stNumIdUsed
+  -- clear numId after first use to support multiple paragraphs in the same bullet
+  -- baseListId is the code for no list marker
+  let numid' = if numIdUsed then baseListId else numid
+  modify $ \st -> st{ stNumIdUsed = True }
+  let listPr = [mknode "w:numPr" []
+                [ mknode "w:ilvl" [("w:val",tshow listLevel)] ()
+                , mknode "w:numId" [("w:val",tshow numid')] () ] | listLevel >= 0 && not displayMathPara]
+  return $ case squashProps (EnvProps Nothing listPr <> props) of
+                [] -> []
+                ps -> [mknode "w:pPr" [] ps]
+
+formattedString :: PandocMonad m => Text -> WS m [Element]
+formattedString str =
+  -- properly handle soft hyphens
+  case splitTextBy (=='\173') str of
+      [w] -> formattedString' w
+      ws  -> do
+         sh <- formattedRun [mknode "w:softHyphen" [] ()]
+         intercalate [sh] <$> mapM formattedString' ws
+
+formattedString' :: PandocMonad m => Text -> WS m [Element]
+formattedString' str = do
+  inDel <- asks envInDel
+  let mkrun s =
+        (if T.any isCJK s
+            then withTextProp (mknode "w:rFonts" [("w:hint","eastAsia")] ())
+            else id) $ formattedRun
+                       [ mktnode (if inDel then "w:delText" else "w:t")
+                          [("xml:space","preserve")] $ s ]
+  mapM mkrun $ breakIntoChunks $ stripInvalidChars str
+
+-- For motivation see #9817.
+breakIntoChunks :: Text -> [Text]
+breakIntoChunks t
+  | T.null t = []
+  | T.any isCJK t
+    = let cs = T.groupBy (\c d -> (isSpace c && isSpace d) ||
+                                  not (isSpace c || isSpace d)) t
+          css = groupBy (\x y -> not (T.any isCJK x || T.any isCJK y)
+                                  || (T.all isSpace x && not (T.any isCJK y))
+                                  || (T.all isSpace y && not (T.any isCJK x)))
+                        cs
+       in map mconcat css
+  | otherwise = [t]
+
+formattedRun :: PandocMonad m => [Element] -> WS m Element
+formattedRun els = do
+  props <- getTextProps
+  return $ mknode "w:r" [] $ props ++ els
+
+-- | Convert an inline element to OpenXML.
+inlineToOpenXML :: PandocMonad m => WriterOptions -> Inline -> WS m [Content]
+inlineToOpenXML opts il = withDirection $ inlineToOpenXML' opts il
+
+inlineToOpenXML' :: PandocMonad m => WriterOptions -> Inline -> WS m [Content]
+inlineToOpenXML' _ (Str str) =
+  map Elem <$> formattedString str
+inlineToOpenXML' opts Space = inlineToOpenXML opts (Str " ")
+inlineToOpenXML' opts SoftBreak = inlineToOpenXML opts (Str " ")
+inlineToOpenXML' opts (Span ("",["mark"],[]) ils) =
+  withTextProp (mknode "w:highlight" [("w:val","yellow")] ()) $
+    inlinesToOpenXML opts ils
+inlineToOpenXML' opts (Span ("",["csl-block"],[]) ils) =
+  inlinesToOpenXML opts ils
+inlineToOpenXML' opts (Span ("",["csl-left-margin"],[]) ils) =
+  inlinesToOpenXML opts ils
+inlineToOpenXML' opts (Span ("",["csl-right-inline"],[]) ils) =
+   ([Elem $
+     mknode "w:r" []
+     (mknode "w:t"
+       [("xml:space","preserve")]
+       ("\t" :: Text))] ++)
+    <$> inlinesToOpenXML opts ils
+inlineToOpenXML' opts (Span ("",["csl-indent"],[]) ils) =
+  inlinesToOpenXML opts ils
+inlineToOpenXML' _ (Span (ident,["comment-start"],kvs) ils) = do
+  -- prefer the "id" in kvs, since that is the one produced by the docx
+  -- reader.
+  let ident' = fromMaybe ident (lookup "id" kvs)
+      kvs' = filter (("id" /=) . fst) kvs
+  modify $ \st -> st{ stComments = (("id",ident'):kvs', ils) : stComments st }
+  return [ Elem $ mknode "w:commentRangeStart" [("w:id", ident')] () ]
+inlineToOpenXML' opts (Span (ident,["comment-end"],kvs) content) = do
+  -- prefer the "id" in kvs, since that is the one produced by the docx
+  -- reader.
+  let ident' = fromMaybe ident (lookup "id" kvs)
+  -- process nested content: see #8189
+  nestedContent <- inlinesToOpenXML opts content
+  let thisCommentEnd =
+        [ mknode "w:commentRangeEnd" [("w:id", ident')] ()
+        , mknode "w:r" []
+          [ mknode "w:rPr" []
+            [ mknode "w:rStyle" [("w:val", "CommentReference")] () ]
+          , mknode "w:commentReference" [("w:id", ident')] () ]
+        ]
+  return $ map Elem thisCommentEnd ++ nestedContent
+inlineToOpenXML' opts (Span (ident,classes,kvs) ils) = do
+  stylemod <- case lookup dynamicStyleKey kvs of
+                   Just (fromString . T.unpack -> sty) -> do
+                      modify $ \s ->
+                        s{stDynamicTextProps = Set.insert sty
+                              (stDynamicTextProps s)}
+                      return $ withTextPropM (rStyleM sty)
+                   _ -> return id
+  let dirmod = case lookup "dir" kvs of
+                 Just "rtl" -> local (\env -> env { envRTL = True })
+                 Just "ltr" -> local (\env -> env { envRTL = False })
+                 _          -> id
+      off x = withTextProp (mknode x [("w:val","0")] ())
+      pmod =  (if "csl-no-emph" `elem` classes then off "w:i" else id) .
+              (if "csl-no-strong" `elem` classes then off "w:b" else id) .
+              (if "csl-no-smallcaps" `elem` classes
+                  then off "w:smallCaps"
+                  else id)
+      getChangeAuthorDate = do
+        defaultAuthor <- asks envChangesAuthor
+        let author = fromMaybe defaultAuthor (lookup "author" kvs)
+        let mdate = lookup "date" kvs
+        return $ ("w:author", author) :
+                   maybe [] (\date -> [("w:date", date)]) mdate
+  insmod <- if "insertion" `elem` classes
+               then do
+                 changeAuthorDate <- getChangeAuthorDate
+                 insId <- gets stInsId
+                 modify $ \s -> s{stInsId = insId + 1}
+                 return $ \f -> do
+                   x <- f
+                   return [Elem $
+                           mknode "w:ins"
+                             (("w:id", tshow insId) : changeAuthorDate) x]
+               else return id
+  delmod <- if "deletion" `elem` classes
+               then do
+                 changeAuthorDate <- getChangeAuthorDate
+                 delId <- gets stDelId
+                 modify $ \s -> s{stDelId = delId + 1}
+                 return $ \f -> local (\env->env{envInDel=True}) $ do
+                   x <- f
+                   return [Elem $ mknode "w:del"
+                             (("w:id", tshow delId) : changeAuthorDate) x]
+               else return id
+  let langmod = case lookup "lang" kvs of
+                  Nothing -> id
+                  Just lang -> local (\env -> env{envLang = Just lang})
+  contents <- insmod $ delmod $ dirmod $ stylemod $ pmod $
+              langmod $ inlinesToOpenXML opts ils
+  wrapBookmark ident contents
+inlineToOpenXML' opts (Strong lst) =
+  withTextProp (mknode "w:bCs" [] ()) $ -- needed for LTR, #6911
+  withTextProp (mknode "w:b" [] ()) $
+  inlinesToOpenXML opts lst
+inlineToOpenXML' opts (Emph lst) =
+  withTextProp (mknode "w:iCs" [] ()) $  -- needed for LTR, #6911
+  withTextProp (mknode "w:i" [] ()) $
+  inlinesToOpenXML opts lst
+inlineToOpenXML' opts (Underline lst) =
+  withTextProp (mknode "w:u" [("w:val","single")] ()) $
+    inlinesToOpenXML opts lst
+inlineToOpenXML' opts (Subscript lst) =
+  withTextProp (mknode "w:vertAlign" [("w:val","subscript")] ())
+  $ inlinesToOpenXML opts lst
+inlineToOpenXML' opts (Superscript lst) =
+  withTextProp (mknode "w:vertAlign" [("w:val","superscript")] ())
+  $ inlinesToOpenXML opts lst
+inlineToOpenXML' opts (SmallCaps lst) =
+  withTextProp (mknode "w:smallCaps" [] ())
+  $ inlinesToOpenXML opts lst
+inlineToOpenXML' opts (Strikeout lst) =
+  withTextProp (mknode "w:strike" [] ())
+  $ inlinesToOpenXML opts lst
+inlineToOpenXML' _ LineBreak = return [Elem br]
+inlineToOpenXML' _ il@(RawInline f str)
+  | f == Format "openxml" = return
+                            [Text (CData CDataRaw str Nothing)]
+  | otherwise             = do
+      report $ InlineNotRendered il
+      return []
+inlineToOpenXML' opts (Quoted quoteType lst) =
+  inlinesToOpenXML opts $ [Str open] ++ lst ++ [Str close]
+    where (open, close) = case quoteType of
+                            SingleQuote -> ("\x2018", "\x2019")
+                            DoubleQuote -> ("\x201C", "\x201D")
+inlineToOpenXML' opts (Math mathType str) = do
+  when (mathType == DisplayMath) setFirstPara
+  res <- (lift . lift) (convertMath writeOMML mathType str)
+  case res of
+       Right r -> return [Elem $ fromXLElement r]
+       Left il -> inlineToOpenXML' opts il
+inlineToOpenXML' opts (Cite _ lst) = inlinesToOpenXML opts lst
+inlineToOpenXML' opts (Code attrs str) = do
+  let alltoktypes = [KeywordTok ..]
+  tokTypesMap <- mapM (\tt -> (,) tt <$> rStyleM (fromString $ show tt)) alltoktypes
+  let unhighlighted = (map Elem . intercalate [br]) `fmap`
+                       mapM formattedString (T.lines str)
+      formatOpenXML _fmtOpts = intercalate [br] . map (map toHlTok)
+      toHlTok (toktype,tok) =
+        mknode "w:r" []
+          [ mknode "w:rPr" [] $
+            maybeToList (lookup toktype tokTypesMap)
+            , mknode "w:t" [("xml:space","preserve")] tok ]
+  let highlighted =
+        case highlight (writerSyntaxMap opts) formatOpenXML attrs str of
+            Right h  -> return (map Elem h)
+            Left msg -> do
+              unless (T.null msg) $ report $ CouldNotHighlight msg
+              unhighlighted
+  withTextPropM (rStyleM "Verbatim Char")
+    $ case writerHighlightMethod opts of
+        DefaultHighlighting -> highlighted
+        Skylighting _ -> highlighted
+        _ -> unhighlighted
+inlineToOpenXML' opts (Note bs) = do
+  notes <- gets stFootnotes
+  notenum <- getUniqueId
+  oldFirstPara <- gets stFirstPara
+  footnoteStyle <- rStyleM "Footnote Reference"
+  let notemarker = mknode "w:r" []
+                   [ mknode "w:rPr" [] footnoteStyle
+                   , mknode "w:footnoteRef" [] () ]
+  let notemarkerXml = RawInline (Format "openxml") $ ppElement notemarker
+  let insertNoteRef (Plain ils : xs) = Plain (notemarkerXml : Space : ils) : xs
+      insertNoteRef (Para ils  : xs) = Para  (notemarkerXml : Space : ils) : xs
+      insertNoteRef xs               = Para [notemarkerXml] : xs
+
+  contents <- local (\env -> env{ envListLevel = -1
+                                , envParaProperties = mempty
+                                , envTextProperties = mempty
+                                , envInNote = True })
+              (withParaPropM (pStyleM "Footnote Text") $
+               blocksToOpenXML opts $ insertNoteRef bs)
+  modify $ \s -> s{ stFirstPara = oldFirstPara }
+  let newnote = mknode "w:footnote" [("w:id", notenum)] contents
+  modify $ \s -> s{ stFootnotes = newnote : notes }
+  return [ Elem $ mknode "w:r" []
+           [ mknode "w:rPr" [] footnoteStyle
+           , mknode "w:footnoteReference" [("w:id", notenum)] () ] ]
+-- internal link:
+inlineToOpenXML' opts (Link _ txt (T.uncons -> Just ('#', xs),_)) = do
+  contents <- withTextPropM (rStyleM "Hyperlink") $ inlinesToOpenXML opts txt
+  return
+    [ Elem $ mknode "w:hyperlink" [("w:anchor", toBookmarkName xs)] contents ]
+-- external link:
+inlineToOpenXML' opts (Link _ txt (src,_)) = do
+  contents <- withTextPropM (rStyleM "Hyperlink") $ inlinesToOpenXML opts txt
+  extlinks <- gets stExternalLinks
+  id' <- case M.lookup src extlinks of
+            Just i   -> return i
+            Nothing  -> do
+              i <- ("rId" <>) <$> getUniqueId
+              modify $ \st -> st{ stExternalLinks =
+                        M.insert src i extlinks }
+              return i
+  return [ Elem $ mknode "w:hyperlink" [("r:id",id')] contents ]
+inlineToOpenXML' opts (Image attr@(imgident, _, _) alt (src, title)) = do
+  pageWidth <- asks envPrintWidth
+  imgs <- gets stImages
+  let
+    stImage = M.lookup (T.unpack src) imgs
+    generateImgElt (ident, _fp, mt, img) = do
+      docprid <- getUniqueId
+      nvpicprid <- getUniqueId
+      (blipAttrs, blipContents) <-
+        case T.takeWhile (/=';') <$> mt of
+          Just "image/svg+xml" -> do
+            -- get fallback png
+            mediabag <- getMediaBag
+            mbFallback <-
+              case lookupMedia (T.unpack (src <> ".png")) mediabag of
+                Just item -> do
+                  id' <- T.unpack . ("rId" <>) <$> getUniqueId
+                  let fp' = "media/" <> id' <> ".png"
+                  let imgdata = (id',
+                                 fp',
+                                 Just (mediaMimeType item),
+                                 BL.toStrict $ mediaContents item)
+                  modify $ \st -> st { stImages =
+                            M.insert fp' imgdata $ stImages st }
+                  return $ Just id'
+                Nothing -> return Nothing
+            let extLst = mknode "a:extLst" []
+                            [ mknode "a:ext"
+                              [("uri","{28A0092B-C50C-407E-A947-70E740481C1C}")]
+                              [ mknode "a14:useLocalDpi"
+                                [("xmlns:a14","http://schemas.microsoft.com/office/drawing/2010/main"),
+                                 ("val","0")] () ]
+                            , mknode "a:ext"
+                              [("uri","{96DAC541-7B7A-43D3-8B79-37D633B846F1}")]
+                              [ mknode "asvg:svgBlip"
+                                [("xmlns:asvg", "http://schemas.microsoft.com/office/drawing/2016/SVG/main"),
+                                 ("r:embed",T.pack ident)] () ]
+                            ]
+            return (maybe [] (\id'' -> [("r:embed", T.pack id'')]) mbFallback,
+                    [extLst])
+          _ -> return ([("r:embed", T.pack ident)], [])
+      let
+        (xpt,ypt) = desiredSizeInPoints opts attr
+               (either (const def) id (imageSize opts img))
+        -- 12700 emu = 1 pt
+        pageWidthPt = case dimension Width attr of
+                        Just (Percent a) -> pageWidth * floor (a * 127)
+                        _                -> pageWidth * 12700
+        (xemu,yemu) = fitToPage (xpt * 12700, ypt * 12700) pageWidthPt
+        cNvPicPr = mknode "pic:cNvPicPr" [] $
+                         mknode "a:picLocks" [("noChangeArrowheads","1")
+                                             ,("noChangeAspect","1")] ()
+        nvPicPr  = mknode "pic:nvPicPr" []
+                        [ mknode "pic:cNvPr"
+                            [("descr",src)
+                            ,("id", nvpicprid)
+                            ,("name","Picture")] ()
+                        , cNvPicPr ]
+        blipFill = mknode "pic:blipFill" []
+          [ mknode "a:blip" blipAttrs blipContents
+          , mknode "a:stretch" [] $
+              mknode "a:fillRect" [] ()
+          ]
+        xfrm =    mknode "a:xfrm" []
+                        [ mknode "a:off" [("x","0"),("y","0")] ()
+                        , mknode "a:ext" [("cx",tshow xemu)
+                                         ,("cy",tshow yemu)] () ]
+        prstGeom = mknode "a:prstGeom" [("prst","rect")] $
+                         mknode "a:avLst" [] ()
+        ln =      mknode "a:ln" [("w","9525")]
+                        [ mknode "a:noFill" [] ()
+                        , mknode "a:headEnd" [] ()
+                        , mknode "a:tailEnd" [] () ]
+        spPr =    mknode "pic:spPr" [("bwMode","auto")]
+                        [xfrm, prstGeom, mknode "a:noFill" [] (), ln]
+        graphic = mknode "a:graphic" [] $
+          mknode "a:graphicData"
+            [("uri","http://schemas.openxmlformats.org/drawingml/2006/picture")]
+            [ mknode "pic:pic" []
+              [ nvPicPr
+              , blipFill
+              , spPr
+              ]
+            ]
+        imgElt = mknode "w:r" [] $
+          mknode "w:drawing" [] $
+            mknode "wp:inline" []
+              [ mknode "wp:extent" [("cx",tshow xemu),("cy",tshow yemu)] ()
+              , mknode "wp:effectExtent"
+                [("b","0"),("l","0"),("r","0"),("t","0")] ()
+              , mknode "wp:docPr"
+                [ ("descr", stringify alt)
+                , ("title", title)
+                , ("id", docprid)
+                , ("name","Picture")
+                ] ()
+              , graphic
+              ]
+      return [Elem imgElt]
+
+  wrapBookmark imgident =<< case stImage of
+    Just imgData -> generateImgElt imgData
+    Nothing -> ( do --try
+      (img, mt) <- P.fetchItem src
+      ident <- ("rId" <>) <$> getUniqueId
+
+      let
+        imgext = case mt >>= extensionFromMimeType of
+          Just x    -> "." <> x
+          Nothing   -> case imageType img of
+            Just Png  -> ".png"
+            Just Jpeg -> ".jpeg"
+            Just Gif  -> ".gif"
+            Just Pdf  -> ".pdf"
+            Just Eps  -> ".eps"
+            Just Svg  -> ".svg"
+            Just Emf  -> ".emf"
+            Just Tiff -> ".tiff"
+            Just Webp -> ".webp"
+            Just Avif -> ".avif"
+            Nothing   -> ""
+        imgpath = "media/" <> ident <> imgext
+        mbMimeType = mt <|> getMimeType (T.unpack imgpath)
+
+        imgData = (T.unpack ident, T.unpack imgpath, mbMimeType, img)
+
+      if T.null imgext
+         then -- without an extension there is no rule for content type
+           inlinesToOpenXML opts alt -- return alt to avoid corrupted docx
+         else do
+           -- insert mime type to use in constructing [Content_Types].xml
+           modify $ \st -> st { stImages = M.insert (T.unpack src) imgData $ stImages st }
+           generateImgElt imgData
+      )
+      `catchError` ( \e -> do
+        report $ CouldNotFetchResource src $ T.pack (show e)
+        -- emit alt text
+        inlinesToOpenXML opts alt
+      )
+
+br :: Element
+br = mknode "w:r" [] [mknode "w:br" [] ()]
+
+
+withDirection :: PandocMonad m => WS m a -> WS m a
+withDirection x = do
+  isRTL <- asks envRTL
+  paraProps <- asks envParaProperties
+  textProps <- asks envTextProperties
+  -- We want to clean all bidirection (bidi) and right-to-left (rtl)
+  -- properties from the props first. This is because we don't want
+  -- them to stack up.
+  let paraProps' = filter (\e -> (qName . elName) e /= "bidi") (otherElements paraProps)
+      textProps' = filter (\e -> (qName . elName) e /= "rtl") (otherElements textProps)
+      paraStyle = styleElement paraProps
+      textStyle = styleElement textProps
+  if isRTL
+    -- if we are going right-to-left, we (re?)add the properties.
+    then flip local x $
+         \env -> env { envParaProperties = EnvProps paraStyle $ mknode "w:bidi" [] () : paraProps'
+                     , envTextProperties = EnvProps textStyle $ mknode "w:rtl" [] () : textProps'
+                     }
+    else flip local x $ \env -> env { envParaProperties = EnvProps paraStyle paraProps'
+                                    , envTextProperties = EnvProps textStyle textProps'
+                                    }
+
+wrapBookmark :: (PandocMonad m) => Text -> [Content] -> WS m [Content]
+wrapBookmark "" contents = return contents
+wrapBookmark ident contents = do
+  id' <- getUniqueId
+  let bookmarkStart = mknode "w:bookmarkStart"
+                       [("w:id", id')
+                       ,("w:name", toBookmarkName ident)] ()
+      bookmarkEnd = mknode "w:bookmarkEnd" [("w:id", id')] ()
+  return $ Elem bookmarkStart : contents ++ [Elem bookmarkEnd]
+
+-- Word imposes a 40 character limit on bookmark names and requires
+-- that they begin with a letter.  So we just use a hash of the
+-- identifier when otherwise we'd have an illegal bookmark name.
+toBookmarkName :: Text -> Text
+toBookmarkName s
+  | Just (c, _) <- T.uncons s
+  , isLetter c
+  , T.length s <= 40 = s
+  | otherwise = T.pack $ 'X' : drop 1 (show (hashWith SHA1 (fromText s)))
+
+maxListLevel :: Int
+maxListLevel = 8
+
+convertSpace :: [Inline] -> [Inline]
+convertSpace (Str x : Space : Str y : xs) = convertSpace (Str (x <> " " <> y) : xs)
+convertSpace (Str x : Str y : xs)         = convertSpace (Str (x <> y) : xs)
+convertSpace (x:xs)                       = x : convertSpace xs
+convertSpace []                           = []
diff --git a/src/Text/Pandoc/Writers/Docx/StyleMap.hs b/src/Text/Pandoc/Writers/Docx/StyleMap.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Writers/Docx/StyleMap.hs
@@ -0,0 +1,47 @@
+{-# LANGUAGE FlexibleContexts  #-}
+{- |
+   Module : Text.Pandoc.Writers.Docx.StyleMap
+   Copyright   : © 2014-2020 Jesse Rosenthal <jrosenthal@jhu.edu>,
+                   2014-2024 John MacFarlane <jgm@berkeley.edu>,
+                   2015-2019 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.Writers.Docx.StyleMap ( StyleMaps(..)
+                                         , ParaStyleName
+                                         , CharStyleName
+                                         , getStyleMaps
+                                         , getStyleIdFromName
+                                         , hasStyleName
+                                         , fromStyleId
+                                         , fromStyleName
+                                         ) where
+
+import Text.Pandoc.Readers.Docx.Parse.Styles
+import Codec.Archive.Zip
+import qualified Data.Map as M
+import qualified Data.Text as T
+import Data.String
+import Data.Char (isSpace)
+
+data StyleMaps = StyleMaps { smCharStyle :: CharStyleNameMap, smParaStyle :: ParaStyleNameMap }
+type ParaStyleNameMap = M.Map ParaStyleName ParStyle
+type CharStyleNameMap = M.Map CharStyleName CharStyle
+
+getStyleIdFromName :: (Ord sn, FromStyleName sn, IsString (StyleId sty), HasStyleId sty)
+                   => sn -> M.Map sn sty -> StyleId sty
+getStyleIdFromName s = maybe (fallback s) getStyleId . M.lookup s
+  where fallback = fromString . T.unpack . T.filter (not . isSpace) . fromStyleName
+
+hasStyleName :: (Ord sn, HasStyleId sty)
+             => sn -> M.Map sn sty -> Bool
+hasStyleName styleName = M.member styleName
+
+getStyleMaps :: Archive -> StyleMaps
+getStyleMaps = uncurry StyleMaps . archiveToStyles' getStyleName getStyleName
diff --git a/src/Text/Pandoc/Writers/Docx/Table.hs b/src/Text/Pandoc/Writers/Docx/Table.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Writers/Docx/Table.hs
@@ -0,0 +1,280 @@
+{-# LANGUAGE LambdaCase          #-}
+{-# LANGUAGE OverloadedStrings   #-}
+{-# LANGUAGE ScopedTypeVariables #-}
+{- |
+Module      : Text.Pandoc.Writers.Docx.Table
+Copyright   : Copyright (C) 2012-2024 John MacFarlane
+License     : GNU GPL, version 2 or above
+Maintainer  : John MacFarlane <jgm@berkeley.edu>
+
+Conversion of table blocks to docx.
+-}
+module Text.Pandoc.Writers.Docx.Table
+  ( tableToOpenXML
+  , rowToOpenXML
+  , OOXMLRow (..)
+  , OOXMLCell (..)
+  , RowType (..)
+  ) where
+
+import Control.Monad.State.Strict ( modify, gets )
+import Control.Monad ( unless , zipWithM )
+import Control.Monad.Except ( throwError )
+import Data.Array ( elems, (!), assocs, indices )
+import Data.Text (Text)
+import Data.Maybe (catMaybes, fromMaybe)
+import Text.Pandoc.Definition
+    ( ColSpec,
+      Caption(Caption),
+      Format(Format),
+      Attr,
+      Block(Para, Plain),
+      Inline(Str, Span, RawInline),
+      Alignment(..),
+      RowSpan(..),
+      ColSpan(..),
+      ColWidth(..) )
+import Text.Pandoc.Class.PandocMonad (PandocMonad)
+import Text.Pandoc.Translations (translateTerm)
+import Text.Pandoc.Writers.Docx.Types
+    ( WS,
+      WriterState(stNextTableNum, stInTable),
+      WriterEnv(..),
+      setFirstPara,
+      pStyleM,
+      withParaProp,
+      withParaPropM )
+import Control.Monad.Reader (asks)
+import Text.Pandoc.Shared ( tshow, stringify )
+import Text.Pandoc.Options (WriterOptions(..), isEnabled, CaptionPosition(..))
+import Text.Pandoc.Extensions (Extension(Ext_native_numbering))
+import Text.Pandoc.Error (PandocError(PandocSomeError))
+import Text.Printf (printf)
+import Text.Pandoc.Writers.GridTable
+    ( rowArray,
+      ColIndex,
+      GridCell(..),
+      Part(Part, partCellArray, partRowAttrs),
+      RowIndex )
+import Text.Pandoc.Writers.OOXML ( mknode )
+import Text.Pandoc.XML.Light.Proc ( onlyElems )
+import Text.Pandoc.XML.Light.Types
+    ( Content(Elem), Element(elName), QName(qName) )
+import qualified Data.Text as T
+import qualified Text.Pandoc.Translations as Term
+import qualified Text.Pandoc.Writers.GridTable as Grid
+
+tableToOpenXML :: PandocMonad m
+               => WriterOptions
+               -> ([Block] -> WS m [Content])
+               -> Grid.Table
+               -> WS m [Content]
+tableToOpenXML opts blocksToOpenXML gridTable = do
+  setFirstPara
+  let (Grid.Table (ident,_,tableAttr) caption colspecs _rowheads thead tbodies tfoot) =
+        gridTable
+  let (Caption _maybeShortCaption captionBlocks) = caption
+  tablenum <- gets stNextTableNum
+  unless (null captionBlocks) $
+    modify $ \st -> st{ stNextTableNum = tablenum + 1 }
+  let tableid = if T.null ident
+                   then "table" <> tshow tablenum
+                   else ident
+  tablename <- translateTerm Term.Table
+  let captionStr = stringify captionBlocks
+  let aligns = map fst $ elems colspecs
+  captionXml <- if null captionBlocks
+                then return []
+                else withParaPropM (pStyleM "Table Caption")
+                     $ blocksToOpenXML
+                     $ if isEnabled Ext_native_numbering opts
+                          then addLabel tableid tablename tablenum captionBlocks
+                          else captionBlocks
+  -- We set "in table" after processing the caption, because we don't
+  -- want the "Table Caption" style to be overwritten with "Compact".
+  modify $ \s -> s { stInTable = True }
+  head' <- cellGridToOpenXML blocksToOpenXML HeadRow aligns thead
+  bodies <- mapM (cellGridToOpenXML blocksToOpenXML BodyRow aligns) tbodies
+  foot' <- cellGridToOpenXML blocksToOpenXML FootRow aligns tfoot
+
+  let hasHeader = not . null . indices . partRowAttrs $ thead
+  let hasFooter = not . null . indices . partRowAttrs $ tfoot
+  -- for compatibility with Word <= 2007, we include a val with a bitmask
+  -- 0×0020  Apply first row conditional formatting
+  -- 0×0040  Apply last row conditional formatting
+  -- 0×0080  Apply first column conditional formatting
+  -- 0×0100  Apply last column conditional formatting
+  -- 0×0200  Do not apply row banding conditional formatting
+  -- 0×0400  Do not apply column banding conditional formattin
+  let tblLookVal = if hasHeader then (0x20 :: Int) else 0
+  let (gridCols, tblWattr) = tableLayout (elems colspecs)
+  listLevel <- asks envListLevel
+  let tblStyle =  fromMaybe "Table" (lookup "custom-style" tableAttr)
+  let indent = (listLevel + 1) * 720
+  let hasWidths = not $ all ((== ColWidthDefault) . snd) colspecs
+  let tbl = mknode "w:tbl" []
+        ( mknode "w:tblPr" []
+          ( [ mknode "w:tblStyle" [("w:val",tblStyle)] (),
+              mknode "w:tblW" tblWattr () ] ++
+            [ mknode "w:jc" [("w:val","left")] () | indent > 0 ] ++
+            [ mknode "w:tblInd" [("w:w", tshow indent),("w:type","dxa")] ()
+                | indent > 0 ] ++
+            [ mknode "w:tblLayout" [("w:type", "fixed")] () | hasWidths ] ++
+            [ mknode "w:tblLook" [("w:firstRow",if hasHeader then "1" else "0")
+                                 ,("w:lastRow",if hasFooter then "1" else "0")
+                                 ,("w:firstColumn","0")
+                                 ,("w:lastColumn","0")
+                                 ,("w:noHBand","0")
+                                 ,("w:noVBand","0")
+                                 ,("w:val", T.pack $ printf "%04x" tblLookVal)
+                                 ] () ] ++
+            [ mknode "w:tblCaption" [("w:val", captionStr)] ()
+            | not (T.null captionStr) ]
+          )
+          : mknode "w:tblGrid" [] gridCols
+          : head' ++ mconcat bodies ++ foot'
+        )
+  modify $ \s -> s { stInTable = False }
+  return $
+    case writerTableCaptionPosition opts of
+      CaptionAbove -> captionXml ++ [Elem tbl]
+      CaptionBelow -> Elem tbl : captionXml
+
+addLabel :: Text -> Text -> Int -> [Block] -> [Block]
+addLabel tableid tablename tablenum bs =
+  case bs of
+    (Para ils : rest)  -> Para (label : Str ": " : ils) : rest
+    (Plain ils : rest) -> Plain (label : Str ": " : ils) : rest
+    _ -> Para [label] : bs
+ where
+  label = Span (tableid,[],[])
+            [Str (tablename <> "\160"),
+             RawInline (Format "openxml")
+               ("<w:fldSimple w:instr=\"SEQ Table"
+               <> " \\* ARABIC \"><w:r><w:t>"
+               <> tshow tablenum
+               <> "</w:t></w:r></w:fldSimple>")]
+
+-- | Parts of a table
+data RowType = HeadRow | BodyRow | FootRow
+
+alignmentToString :: Alignment -> Text
+alignmentToString = \case
+  AlignLeft    -> "left"
+  AlignRight   -> "right"
+  AlignCenter  -> "center"
+  AlignDefault -> ""
+
+tableLayout :: [ColSpec] -> ([Element], [(Text, Text)])
+tableLayout specs =
+  let
+    textwidth = 7920  -- 5.5 in in twips       (1 twip == 1/20 pt)
+    fullrow   = 5000  -- 100% specified in pct (1 pct  == 1/50th of a percent)
+    ncols = length specs
+    getWidth = \case
+      ColWidth n -> n
+      _          -> 0
+    widths = map (getWidth . snd) specs
+    rowwidth  = round (fullrow * sum widths) :: Int
+    widthToTwips w = floor (textwidth * w)   :: Int
+    mkGridCol w = mknode "w:gridCol" [("w:w", tshow (widthToTwips w))] ()
+  in if all (== 0) widths
+     then ( replicate ncols $ mkGridCol (1.0 / fromIntegral ncols)
+          , [ ("w:type", "auto"), ("w:w", "0")])
+     else ( map mkGridCol widths
+          , [ ("w:type", "pct"), ("w:w", tshow rowwidth) ])
+
+cellGridToOpenXML :: PandocMonad m
+                  => ([Block] -> WS m [Content])
+                  -> RowType
+                  -> [Alignment]
+                  -> Part
+                  -> WS m [Element]
+cellGridToOpenXML blocksToOpenXML rowType aligns part@(Part _ cellArray _) =
+  if null (elems cellArray)
+  then return mempty
+  else partToRows rowType aligns part >>=
+       fmap catMaybes . mapM (rowToOpenXML blocksToOpenXML)
+
+data OOXMLCell
+  = OOXMLCell Attr Alignment RowSpan ColSpan [Block]
+  | OOXMLCellMerge ColSpan
+
+data OOXMLRow = OOXMLRow RowType Attr [OOXMLCell]
+
+partToRows :: PandocMonad m
+           => RowType -> [Alignment] -> Part -> WS m [OOXMLRow]
+partToRows rowType aligns part = do
+  let toOOXMLCell :: PandocMonad m =>
+        Alignment -> RowIndex -> ColIndex -> GridCell -> WS m [OOXMLCell]
+      toOOXMLCell columnAlign ridx cidx = \case
+        UnassignedCell ->
+          throwError $ PandocSomeError "Encountered unassigned table cell"
+        ContentCell attr align rowspan colspan blocks -> do
+          -- Respect non-default, cell specific alignment.
+          let align' = case align of
+                AlignDefault -> columnAlign
+                _            -> align
+          return [OOXMLCell attr align' rowspan colspan blocks]
+        ContinuationCell idx'@(ridx',cidx') | ridx /= ridx', cidx == cidx' -> do
+          case (partCellArray part)!idx' of
+            (ContentCell _ _ _ colspan _) -> return [OOXMLCellMerge colspan]
+            x -> error $ "Content cell expected, got, " ++ show x ++
+                         " at index " ++ show idx'
+        _ -> return mempty
+  let mkRow :: PandocMonad m => (RowIndex, Attr) -> WS m OOXMLRow
+      mkRow (ridx, attr) = do
+        cs <- zipWithM (\align -> uncurry $ toOOXMLCell align ridx)
+                        aligns
+                        (assocs . rowArray ridx $ partCellArray part)
+        return $ OOXMLRow rowType attr . mconcat $ cs
+  mapM mkRow $ assocs (partRowAttrs part)
+
+rowToOpenXML :: PandocMonad m
+             => ([Block] -> WS m [Content])
+             -> OOXMLRow
+             -> WS m (Maybe Element)
+rowToOpenXML blocksToOpenXML (OOXMLRow rowType _attr cells)
+  | null cells = return Nothing
+  | otherwise = do
+    xmlcells <- mapM (ooxmlCellToOpenXML blocksToOpenXML) cells
+    let addTrPr = case rowType of
+          HeadRow -> (mknode "w:trPr" []
+                      [mknode "w:tblHeader" [("w:val", "on")] ()] :)
+          BodyRow -> id
+          FootRow -> id
+    return $ Just $ mknode "w:tr" [] (addTrPr xmlcells)
+
+ooxmlCellToOpenXML :: PandocMonad m
+                   => ([Block] -> WS m [Content])
+                   -> OOXMLCell
+                   -> WS m Element
+ooxmlCellToOpenXML blocksToOpenXML = \case
+  OOXMLCellMerge (ColSpan colspan) -> do
+    return $ mknode "w:tc" []
+      [ mknode "w:tcPr" [] [ mknode "w:gridSpan" [("w:val", tshow colspan)] ()
+                           , mknode "w:vMerge"   [("w:val", "continue")] () ]
+      , mknode "w:p" [] [mknode "w:pPr" [] ()]]
+  OOXMLCell _attr align rowspan (ColSpan colspan) contents -> do
+    compactStyle <- pStyleM "Compact"
+    es <- maybe id withParaProp (alignmentFor align) $ blocksToOpenXML contents
+    -- Table cells require a <w:p> element, even an empty one!
+    -- Not in the spec but in Word 2007, 2010. See #4953. And
+    -- apparently the last element must be a <w:p>, see #6983.
+    return . mknode "w:tc" [] $
+      Elem
+       (mknode "w:tcPr" [] ([ mknode "w:gridSpan" [("w:val", tshow colspan)] ()
+                            | colspan > 1] ++
+                            [ mknode "w:vMerge" [("w:val", "restart")] ()
+                            | rowspan > RowSpan 1 ])) :
+      if null contents
+      then [Elem $ mknode "w:p" [] [mknode "w:pPr" [] [compactStyle]]]
+      else case reverse (onlyElems es) of
+             b:e:_ | qName (elName b) == "bookmarkEnd"  -- y tho?
+                   , qName (elName e) == "p" -> es
+             e:_   | qName (elName e) == "p" -> es
+             _ -> es ++ [Elem $ mknode "w:p" [] ()]
+
+alignmentFor :: Alignment -> Maybe Element
+alignmentFor AlignDefault = Nothing
+alignmentFor al = Just $ mknode "w:jc" [("w:val",alignmentToString al)] ()
diff --git a/src/Text/Pandoc/Writers/Docx/Types.hs b/src/Text/Pandoc/Writers/Docx/Types.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Writers/Docx/Types.hs
@@ -0,0 +1,201 @@
+{-# LANGUAGE OverloadedStrings   #-}
+{- |
+Module      : Text.Pandoc.Writers.Docx
+Copyright   : Copyright (C) 2012-2024 John MacFarlane
+License     : GNU GPL, version 2 or above
+Maintainer  : John MacFarlane <jgm@berkeley.edu>
+
+Conversion of table blocks to docx.
+-}
+module Text.Pandoc.Writers.Docx.Types
+  ( EnvProps (..)
+  , WriterEnv (..)
+  , defaultWriterEnv
+  , WriterState (..)
+  , defaultWriterState
+  , WS
+  , ListMarker (..)
+  , listMarkerToId
+  , pStyleM
+  , isStyle
+  , setFirstPara
+  , withParaProp
+  , withParaPropM
+  ) where
+
+import Control.Applicative ((<|>))
+import Control.Monad.Reader
+import Control.Monad.State.Strict
+import Data.Text (Text)
+import Text.Pandoc.Class.PandocMonad (PandocMonad)
+import Text.Pandoc.Definition
+import Text.Pandoc.MIME (MimeType)
+import Text.Pandoc.Writers.Docx.StyleMap
+import Text.Pandoc.Writers.OOXML
+import Text.Pandoc.XML.Light as XML
+import qualified Data.ByteString as B
+import qualified Data.Map as M
+import qualified Data.Set as Set
+import qualified Data.Text as T
+
+data ListMarker = NoMarker
+                | BulletMarker
+                | CheckboxMarker Bool
+                | NumberMarker ListNumberStyle ListNumberDelim Int
+                deriving (Show, Read, Eq, Ord)
+
+listMarkerToId :: ListMarker -> Text
+listMarkerToId NoMarker = "990"
+listMarkerToId BulletMarker = "991"
+listMarkerToId (CheckboxMarker False) = "992"
+listMarkerToId (CheckboxMarker True) = "993"
+listMarkerToId (NumberMarker sty delim n) = T.pack $
+  '9' : '9' : styNum : delimNum : show n
+  where styNum = case sty of
+                      DefaultStyle -> '2'
+                      Example      -> '3'
+                      Decimal      -> '4'
+                      LowerRoman   -> '5'
+                      UpperRoman   -> '6'
+                      LowerAlpha   -> '7'
+                      UpperAlpha   -> '8'
+        delimNum = case delim of
+                      DefaultDelim -> '0'
+                      Period       -> '1'
+                      OneParen     -> '2'
+                      TwoParens    -> '3'
+
+
+data EnvProps = EnvProps{ styleElement  :: Maybe Element
+                        , otherElements :: [Element]
+                        }
+
+instance Semigroup EnvProps where
+  EnvProps s es <> EnvProps s' es' = EnvProps (s <|> s') (es ++ es')
+
+instance Monoid EnvProps where
+  mempty = EnvProps Nothing []
+  mappend = (<>)
+
+data WriterEnv = WriterEnv
+  { envTextProperties :: EnvProps
+  , envParaProperties :: EnvProps
+  , envRTL            :: Bool
+  , envListLevel      :: Int
+  , envListNumId      :: Int
+  , envInDel          :: Bool
+  , envInNote         :: Bool
+  , envChangesAuthor  :: Text
+  , envChangesDate    :: Text
+  , envPrintWidth     :: Integer
+  , envLang           :: Maybe Text
+  , envSectPr         :: Maybe Element
+  }
+
+defaultWriterEnv :: WriterEnv
+defaultWriterEnv = WriterEnv
+  { envTextProperties = mempty
+  , envParaProperties = mempty
+  , envRTL = False
+  , envListLevel = -1
+  , envListNumId = 1
+  , envInDel = False
+  , envInNote = False
+  , envChangesAuthor  = "unknown"
+  , envChangesDate    = "1969-12-31T19:00:00Z"
+  , envPrintWidth     = 1
+  , envLang           = Nothing
+  , envSectPr         = Nothing
+  }
+
+
+data WriterState = WriterState{
+         stFootnotes      :: [Element]
+       , stComments       :: [([(Text, Text)], [Inline])]
+       , stSectionIds     :: Set.Set Text
+       , stExternalLinks  :: M.Map Text Text
+       , stImages         :: M.Map FilePath (String, String, Maybe MimeType, B.ByteString)
+       , stLists          :: [ListMarker]
+       , stExampleId      :: Maybe Int
+       , stInsId          :: Int
+       , stDelId          :: Int
+       , stStyleMaps      :: StyleMaps
+       , stFirstPara      :: Bool
+       , stFirstSectionHeader :: Bool  -- ^ True until first section header is processed
+       , stNumIdUsed      :: Bool  -- ^ True if the current numId (envListNumId) has been used.
+                                   --   Should only be used once, for the first paragraph.
+       , stInTable        :: Bool
+       , stInList         :: Bool
+       , stTocTitle       :: [Inline]
+       , stDynamicParaProps :: Set.Set ParaStyleName
+       , stDynamicTextProps :: Set.Set CharStyleName
+       , stCurId          :: Int
+       , stNextFigureNum  :: Int
+       , stNextTableNum   :: Int
+       }
+
+defaultWriterState :: WriterState
+defaultWriterState = WriterState{
+        stFootnotes      = defaultFootnotes
+      , stComments       = []
+      , stSectionIds     = Set.empty
+      , stExternalLinks  = M.empty
+      , stImages         = M.empty
+      , stLists          = [NoMarker]
+      , stExampleId      = Nothing
+      , stInsId          = 1
+      , stDelId          = 1
+      , stStyleMaps      = StyleMaps M.empty M.empty
+      , stFirstPara      = False
+      , stFirstSectionHeader = True
+      , stNumIdUsed      = False
+      , stInTable        = False
+      , stInList         = False
+      , stTocTitle       = [Str "Table of Contents"]
+      , stDynamicParaProps = Set.empty
+      , stDynamicTextProps = Set.empty
+      , stCurId          = 20
+      , stNextFigureNum  = 1
+      , stNextTableNum   = 1
+      }
+
+setFirstPara :: PandocMonad m => WS m ()
+setFirstPara =  modify $ \s -> s { stFirstPara = True }
+
+type WS m = ReaderT WriterEnv (StateT WriterState m)
+
+-- Word will insert these footnotes into the settings.xml file
+-- (whether or not they're visible in the document). If they're in the
+-- file, but not in the footnotes.xml file, it will produce
+-- problems. So we want to make sure we insert them into our document.
+defaultFootnotes :: [Element]
+defaultFootnotes = [ mknode "w:footnote"
+                     [("w:type", "separator"), ("w:id", "-1")]
+                     [ mknode "w:p" []
+                       [mknode "w:r" []
+                        [ mknode "w:separator" [] ()]]]
+                   , mknode "w:footnote"
+                     [("w:type", "continuationSeparator"), ("w:id", "0")]
+                     [ mknode "w:p" []
+                       [ mknode "w:r" []
+                         [ mknode "w:continuationSeparator" [] ()]]]]
+
+pStyleM :: (PandocMonad m) => ParaStyleName -> WS m XML.Element
+pStyleM styleName = do
+  pStyleMap <- gets (smParaStyle . stStyleMaps)
+  let sty' = getStyleIdFromName styleName pStyleMap
+  return $ mknode "w:pStyle" [("w:val", fromStyleId sty')] ()
+
+withParaProp :: PandocMonad m => Element -> WS m a -> WS m a
+withParaProp d p =
+  local (\env -> env {envParaProperties = ep <> envParaProperties env}) p
+  where ep = if isStyle d then EnvProps (Just d) [] else EnvProps Nothing [d]
+
+withParaPropM :: PandocMonad m => WS m Element -> WS m a -> WS m a
+withParaPropM md p = do
+  d <- md
+  withParaProp d p
+
+isStyle :: Element -> Bool
+isStyle e = isElem [] "w" "rStyle" e ||
+            isElem [] "w" "pStyle" e
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,24 +1,7 @@
-{-
-Copyright (C) 2008-2017 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 OverloadedStrings #-}
 {- |
    Module      : Text.Pandoc.Writers.DokuWiki
-   Copyright   : Copyright (C) 2008-2017 John MacFarlane
+   Copyright   : Copyright (C) 2008-2024 John MacFarlane
    License     : GNU GPL, version 2 or above
 
    Maintainer  : Clare Macrae <clare.macrae@googlemail.com>
@@ -31,7 +14,7 @@
 -}
 
 {-
-    [ ] Implement nested blockquotes (currently only ever does one level)
+    [x] Implement nested blockquotes (currently only ever does one level)
     [x] Implement alignment of text in tables
     [ ] Implement comments
     [ ] Work through the Dokuwiki spec, and check I've not missed anything out
@@ -40,28 +23,35 @@
 
 module Text.Pandoc.Writers.DokuWiki ( writeDokuWiki ) where
 import Control.Monad (zipWithM)
-import Control.Monad.Reader (ReaderT, ask, local, runReaderT)
+import Control.Monad.Reader (ReaderT, asks, local, runReaderT)
 import Control.Monad.State.Strict (StateT, evalStateT)
 import Data.Default (Default (..))
-import Data.List (intercalate, intersect, isPrefixOf, transpose)
-import Data.Text (Text, pack)
-import Text.Pandoc.Class (PandocMonad, report)
+import Data.List (transpose)
+import Data.List.NonEmpty (nonEmpty)
+import Data.Text (Text)
+import qualified Data.Text as T
+import Text.Pandoc.Class.PandocMonad (PandocMonad, report)
 import Text.Pandoc.Definition
+import Text.Pandoc.Extensions
 import Text.Pandoc.ImageSize
 import Text.Pandoc.Logging
-import Text.Pandoc.Options (WrapOption (..), WriterOptions (writerTableOfContents, writerTemplate, writerWrapText))
-import Text.Pandoc.Shared (camelCaseToHyphenated, escapeURI, isURI, linesToPara,
-                           removeFormatting, substitute, trimr)
-import Text.Pandoc.Templates (renderTemplate')
-import Text.Pandoc.Writers.Shared (defField, metaToJSON)
+import Text.Pandoc.Options (WrapOption (..), WriterOptions (writerTableOfContents,
+                            writerTemplate, writerWrapText), isEnabled)
+import Text.Pandoc.Shared (figureDiv, linesToPara, removeFormatting, trimr)
+import Text.Pandoc.URI (escapeURI, isURI)
+import Text.Pandoc.Templates (renderTemplate)
+import Text.DocLayout (render, literal)
+import Text.Pandoc.Writers.Shared (defField, metaToContext, toLegacyTable)
+import Data.Maybe (fromMaybe)
+import qualified Data.Map as M
 
 data WriterState = WriterState {
   }
 
 data WriterEnvironment = WriterEnvironment {
-    stIndent      :: String          -- Indent after the marker at the beginning of list items
-  , stUseTags     :: Bool            -- True if we should use HTML tags because we're in a complex list
+    stIndent      :: Text          -- Indent after the marker at the beginning of list items
   , stBackSlashLB :: Bool     -- True if we should produce formatted strings with newlines (as in a table cell)
+  , stBlockQuoteLevel :: Int   -- Block quote level
   }
 
 instance Default WriterState where
@@ -69,8 +59,8 @@
 
 instance Default WriterEnvironment where
   def = WriterEnvironment { stIndent = ""
-                          , stUseTags = False
-                          , stBackSlashLB = False }
+                          , stBackSlashLB = False
+                          , stBlockQuoteLevel = 0 }
 
 type DokuWiki m = ReaderT WriterEnvironment (StateT WriterState m)
 
@@ -86,68 +76,56 @@
 pandocToDokuWiki :: PandocMonad m
                  => WriterOptions -> Pandoc -> DokuWiki m Text
 pandocToDokuWiki opts (Pandoc meta blocks) = do
-  metadata <- metaToJSON opts
-              (fmap trimr . blockListToDokuWiki opts)
-              (inlineListToDokuWiki opts)
+  metadata <- metaToContext opts
+              (fmap (literal . trimr) . blockListToDokuWiki opts)
+              (fmap (literal . trimr) . inlineListToDokuWiki opts)
               meta
   body <- blockListToDokuWiki opts blocks
-  let main = pack body
-  let context = defField "body" main
-                $ defField "toc" (writerTableOfContents opts) metadata
-  case writerTemplate opts of
-       Nothing  -> return main
-       Just tpl -> renderTemplate' tpl context
+  let context = defField "body" body
+              $ defField "toc" (writerTableOfContents opts) metadata
+  return $
+    case writerTemplate opts of
+       Nothing  -> body
+       Just tpl -> render Nothing $ renderTemplate tpl context
 
 -- | Escape special characters for DokuWiki.
-escapeString :: String -> String
-escapeString = substitute "__" "%%__%%" .
-               substitute "**" "%%**%%" .
-               substitute "//" "%%//%%"
+escapeString :: Text -> Text
+escapeString = T.replace "__" "%%__%%" .
+               T.replace "**" "%%**%%" .
+               T.replace "//" "%%//%%"
 
 -- | Convert Pandoc block element to DokuWiki.
 blockToDokuWiki :: PandocMonad m
                 => WriterOptions -- ^ Options
                 -> Block         -- ^ Block element
-                -> DokuWiki m String
-
-blockToDokuWiki _ Null = return ""
+                -> DokuWiki m Text
 
 blockToDokuWiki opts (Div _attrs bs) = do
   contents <- blockListToDokuWiki opts bs
-  return $ contents ++ "\n"
+  indent <- asks stIndent
+  return $ contents <> if T.null indent then "\n" else ""
 
 blockToDokuWiki opts (Plain inlines) =
   inlineListToDokuWiki opts inlines
 
--- title beginning with fig: indicates that the image is a figure
--- dokuwiki doesn't support captions - so combine together alt and caption into alt
-blockToDokuWiki opts (Para [Image attr txt (src,'f':'i':'g':':':tit)]) = do
-  capt <- if null txt
-             then return ""
-             else (" " ++) `fmap` inlineListToDokuWiki opts txt
-  let opt = if null txt
-               then ""
-               else "|" ++ if null tit then capt else tit ++ capt
-      -- Relative links fail isURI and receive a colon
-      prefix = if isURI src then "" else ":"
-  return $ "{{" ++ prefix ++ src ++ imageDims opts attr ++ opt ++ "}}\n"
-
 blockToDokuWiki opts (Para inlines) = do
-  indent <- stIndent <$> ask
-  useTags <- stUseTags <$> ask
+  bqLevel <- asks stBlockQuoteLevel
+  let bqPrefix = case bqLevel of
+                    0 -> ""
+                    n -> T.replicate n ">" <> " "
+  indent <- asks stIndent
   contents <- inlineListToDokuWiki opts inlines
-  return $ if useTags
-              then "<HTML><p></HTML>" ++ contents ++ "<HTML></p></HTML>"
-              else contents ++ if null indent then "\n" else ""
+  return $ bqPrefix <> contents <> if T.null indent then "\n" else ""
 
 blockToDokuWiki opts (LineBlock lns) =
   blockToDokuWiki opts $ linesToPara lns
 
-blockToDokuWiki _ b@(RawBlock f str)
+blockToDokuWiki opts b@(RawBlock f str)
   | f == Format "dokuwiki" = return str
   -- See https://www.dokuwiki.org/wiki:syntax
   -- use uppercase HTML tag for block-level content:
-  | f == Format "html"     = return $ "<HTML>\n" ++ str ++ "\n</HTML>"
+  | f == Format "html"
+  , isEnabled Ext_raw_html opts = return $ "<HTML>\n" <> str <> "\n</HTML>"
   | otherwise              = "" <$
          report (BlockNotRendered b)
 
@@ -157,221 +135,187 @@
   -- emphasis, links etc. not allowed in headers, apparently,
   -- so we remove formatting:
   contents <- inlineListToDokuWiki opts $ removeFormatting inlines
-  let eqs = replicate ( 7 - level ) '='
-  return $ eqs ++ " " ++ contents ++ " " ++ eqs ++ "\n"
+  let eqs = T.replicate ( 7 - level ) "="
+  return $ eqs <> " " <> contents <> " " <> eqs <> "\n"
 
 blockToDokuWiki _ (CodeBlock (_,classes,_) str) = do
-  let at  = classes `intersect` ["actionscript", "ada", "apache", "applescript", "asm", "asp",
-                       "autoit", "bash", "blitzbasic", "bnf", "c", "c_mac", "caddcl", "cadlisp", "cfdg", "cfm",
-                       "cpp", "cpp-qt", "csharp", "css", "d", "delphi", "diff", "div", "dos", "eiffel", "fortran",
-                       "freebasic", "gml", "groovy", "html4strict", "idl", "ini", "inno", "io", "java", "java5",
-                       "javascript", "latex", "lisp", "lua", "matlab", "mirc", "mpasm", "mysql", "nsis", "objc",
-                       "ocaml", "ocaml-brief", "oobas", "oracle8", "pascal", "perl", "php", "php-brief", "plsql",
-                       "python", "qbasic", "rails", "reg", "robots", "ruby", "sas", "scheme", "sdlbasic",
-                       "smalltalk", "smarty", "sql", "tcl", "", "thinbasic", "tsql", "vb", "vbnet", "vhdl",
-                       "visualfoxpro", "winbatch", "xml", "xpp", "z80"]
-  return $ "<code" ++
-                (case at of
-                      []    -> ">\n"
-                      (x:_) -> " " ++ x ++ ">\n") ++ str ++ "\n</code>"
+  bqLevel <- asks stBlockQuoteLevel
+  let bqPrefix = case bqLevel of
+                    0 -> ""
+                    n -> T.replicate n ">" <> " "
+  return $ bqPrefix <>
+           "<code" <>
+           (case classes of
+               []    -> ""
+               (x:_) -> " " <> fromMaybe x (M.lookup x languageNames)) <>
+           ">\n" <> str <>
+           (if "\n" `T.isSuffixOf` str then "" else "\n") <> "</code>\n"
 
-blockToDokuWiki opts (BlockQuote blocks) = do
-  contents <- blockListToDokuWiki opts blocks
-  if isSimpleBlockQuote blocks
-     then return $ unlines $ map ("> " ++) $ lines contents
-     else return $ "<HTML><blockquote>\n" ++ contents ++ "</blockquote></HTML>"
+blockToDokuWiki opts (BlockQuote blocks) =
+  local (\st -> st{ stBlockQuoteLevel = stBlockQuoteLevel st + 1 })
+               (blockListToDokuWiki opts blocks)
 
-blockToDokuWiki opts (Table capt aligns _ headers rows) = do
+blockToDokuWiki opts (Table _ blkCapt specs thead tbody tfoot) = do
+  let (capt, aligns, _, headers, rows) = toLegacyTable blkCapt specs thead tbody tfoot
   captionDoc <- if null capt
                    then return ""
                    else do
                       c <- inlineListToDokuWiki opts capt
-                      return $ "" ++ c ++ "\n"
+                      return $ "" <> c <> "\n"
   headers' <- if all null headers
                  then return []
                  else zipWithM (tableItemToDokuWiki opts) aligns headers
   rows' <- mapM (zipWithM (tableItemToDokuWiki opts) aligns) rows
-  let widths = map (maximum . map length) $ transpose (headers':rows')
+  let widths = map (maybe 0 maximum . nonEmpty . map T.length)
+                   $ transpose (headers':rows')
   let padTo (width, al) s =
-          case width - length s of
+          case width - T.length s of
                x | x > 0 ->
                  if al == AlignLeft || al == AlignDefault
-                    then s ++ replicate x ' '
+                    then s <> T.replicate x " "
                     else if al == AlignRight
-                            then replicate x ' ' ++ s
-                            else replicate (x `div` 2) ' ' ++
-                                 s ++ replicate (x - x `div` 2) ' '
+                            then T.replicate x " " <> s
+                            else T.replicate (x `div` 2) " " <>
+                                 s <> T.replicate (x - x `div` 2) " "
                  | otherwise -> s
-  let renderRow sep cells = sep ++
-          intercalate sep (zipWith padTo (zip widths aligns) cells) ++ sep
-  return $ captionDoc ++
-           (if null headers' then "" else renderRow "^" headers' ++ "\n") ++
-           unlines (map (renderRow "|") rows')
+  let renderRow sep cells = sep <>
+          T.intercalate sep (zipWith padTo (zip widths aligns) cells) <> sep
+  return $ captionDoc <>
+           (if null headers' then "" else renderRow "^" headers' <> "\n") <>
+           T.unlines (map (renderRow "|") rows')
 
-blockToDokuWiki opts x@(BulletList items) = do
-  oldUseTags <- stUseTags <$> ask
-  indent <- stIndent <$> ask
-  backSlash <- stBackSlashLB <$> ask
-  let useTags = oldUseTags || not (isSimpleList x)
-  if useTags
-     then do
-        contents <- local (\s -> s { stUseTags = True })
-                      (mapM (listItemToDokuWiki opts) items)
-        return $ "<HTML><ul></HTML>\n" ++ vcat contents ++ "<HTML></ul></HTML>\n"
-     else do
-        contents <- local (\s -> s { stIndent = stIndent s ++ "  "
-                                   , stBackSlashLB = backSlash})
+blockToDokuWiki opts (BulletList items) = do
+  indent <- asks stIndent
+  backSlash <- asks stBackSlashLB
+  contents <- local (\s -> s { stIndent = stIndent s <> "  "
+                             , stBackSlashLB = backSlash})
                       (mapM (listItemToDokuWiki opts) items)
-        return $ vcat contents ++ if null indent then "\n" else ""
+  return $ vcat contents <> if T.null indent then "\n" else ""
 
-blockToDokuWiki opts x@(OrderedList attribs items) = do
-  oldUseTags <- stUseTags <$> ask
-  indent <- stIndent <$> ask
-  backSlash <- stBackSlashLB <$> ask
-  let useTags = oldUseTags || not (isSimpleList x)
-  if useTags
-     then do
-        contents <- local (\s -> s { stUseTags = True })
-                      (mapM (orderedListItemToDokuWiki opts) items)
-        return $ "<HTML><ol" ++ listAttribsToString attribs ++ "></HTML>\n" ++ vcat contents ++ "<HTML></ol></HTML>\n"
-     else do
-        contents <- local (\s -> s { stIndent = stIndent s ++ "  "
-                                   , stBackSlashLB = backSlash})
-                      (mapM (orderedListItemToDokuWiki opts) items)
-        return $ vcat contents ++ if null indent then "\n" else ""
+blockToDokuWiki opts (OrderedList _attribs items) = do
+  indent <- asks stIndent
+  backSlash <- asks stBackSlashLB
+  contents <- local (\s -> s { stIndent = stIndent s <> "  "
+                             , stBackSlashLB = backSlash})
+                (mapM (orderedListItemToDokuWiki opts) items)
+  return $ vcat contents <> if T.null indent then "\n" else ""
 
+blockToDokuWiki opts (Figure attr capt body) =
+  blockToDokuWiki opts $ figureDiv attr capt body
+
 -- TODO Need to decide how to make definition lists work on dokuwiki - I don't think there
 --      is a specific representation of them.
 -- TODO This creates double '; ; ' if there is a bullet or ordered list inside a definition list
-blockToDokuWiki opts x@(DefinitionList items) = do
-  oldUseTags <- stUseTags <$> ask
-  indent <- stIndent <$> ask
-  backSlash <- stBackSlashLB <$> ask
-  let useTags = oldUseTags || not (isSimpleList x)
-  if useTags
-     then do
-        contents <- local (\s -> s { stUseTags = True })
-                      (mapM (definitionListItemToDokuWiki opts) items)
-        return $ "<HTML><dl></HTML>\n" ++ vcat contents ++ "<HTML></dl></HTML>\n"
-     else do
-        contents <- local (\s -> s { stIndent = stIndent s ++ "  "
-                                   , stBackSlashLB = backSlash})
-                      (mapM (definitionListItemToDokuWiki opts) items)
-        return $ vcat contents ++ if null indent then "\n" else ""
+blockToDokuWiki opts (DefinitionList items) = do
+  indent <- asks stIndent
+  backSlash <- asks stBackSlashLB
+  contents <- local (\s -> s { stIndent = stIndent s <> "  "
+                             , stBackSlashLB = backSlash})
+                (mapM (definitionListItemToDokuWiki opts) items)
+  return $ vcat contents <> if T.null indent then "\n" else ""
 
 -- Auxiliary functions for lists:
 
--- | Convert ordered list attributes to HTML attribute string
-listAttribsToString :: ListAttributes -> String
-listAttribsToString (startnum, numstyle, _) =
-  let numstyle' = camelCaseToHyphenated $ show numstyle
-  in  (if startnum /= 1
-          then " start=\"" ++ show startnum ++ "\""
-          else "") ++
-      (if numstyle /= DefaultStyle
-          then " style=\"list-style-type: " ++ numstyle' ++ ";\""
-          else "")
-
 -- | Convert bullet list item (list of blocks) to DokuWiki.
 listItemToDokuWiki :: PandocMonad m
-                   => WriterOptions -> [Block] -> DokuWiki m String
+                   => WriterOptions -> [Block] -> DokuWiki m Text
 listItemToDokuWiki opts items = do
-  useTags <- stUseTags <$> ask
-  if useTags
-     then do
-       contents <- blockListToDokuWiki opts items
-       return $ "<HTML><li></HTML>" ++ contents ++ "<HTML></li></HTML>"
-     else do
-       bs <- mapM (blockToDokuWiki opts) items
-       let contents = case items of
-                           [_, CodeBlock _ _] -> concat bs
-                           _                  -> vcat bs
-       indent <- stIndent <$> ask
-       backSlash <- stBackSlashLB <$> ask
-       let indent' = if backSlash then drop 2 indent else indent
-       return $ indent' ++ "* " ++ contents
+  bqLevel <- asks stBlockQuoteLevel
+  let bqPrefix = case bqLevel of
+                    0 -> ""
+                    n -> T.replicate n ">" <> " "
+  let useWrap = not (isSimpleListItem items)
+  bs <- mapM (blockToDokuWiki opts) items
+  let contents = case items of
+                      [_, CodeBlock _ _] -> T.concat bs
+                      _                  -> vcat bs
+  indent <- asks stIndent
+  backSlash <- asks stBackSlashLB
+  let indent' = if backSlash then T.drop 2 indent else indent
+  return $ bqPrefix <> indent' <> "* " <>
+    if useWrap
+       then "<WRAP>\n" <> contents <> "\n</WRAP>"
+       else contents
 
 -- | Convert ordered list item (list of blocks) to DokuWiki.
 -- | TODO Emiminate dreadful duplication of text from listItemToDokuWiki
-orderedListItemToDokuWiki :: PandocMonad m => WriterOptions -> [Block] -> DokuWiki m String
+orderedListItemToDokuWiki :: PandocMonad m => WriterOptions -> [Block] -> DokuWiki m Text
 orderedListItemToDokuWiki opts items = do
-  contents <- blockListToDokuWiki opts items
-  useTags <- stUseTags <$> ask
-  if useTags
-     then return $ "<HTML><li></HTML>" ++ contents ++ "<HTML></li></HTML>"
-     else do
-       indent <- stIndent <$> ask
-       backSlash <- stBackSlashLB <$> ask
-       let indent' = if backSlash then drop 2 indent else indent
-       return $ indent' ++ "- " ++ contents
+  bqLevel <- asks stBlockQuoteLevel
+  let bqPrefix = case bqLevel of
+                    0 -> ""
+                    n -> T.replicate n ">" <> " "
+  let useWrap = not (isSimpleListItem items)
+  contents <- local (\st -> st{ stBlockQuoteLevel = 0 })
+               (blockListToDokuWiki opts items)
+  indent <- asks stIndent
+  backSlash <- asks stBackSlashLB
+  let indent' = if backSlash then T.drop 2 indent else indent
+  return $ bqPrefix <> indent' <> "- " <>
+    if useWrap
+       then "<WRAP>\n" <> contents <> "\n</WRAP>"
+       else contents
 
 -- | Convert definition list item (label, list of blocks) to DokuWiki.
 definitionListItemToDokuWiki :: PandocMonad m
                              => WriterOptions
                              -> ([Inline],[[Block]])
-                             -> DokuWiki m String
+                             -> DokuWiki m Text
 definitionListItemToDokuWiki opts (label, items) = do
+  let useWrap = not (all isSimpleListItem items)
+  bqLevel <- asks stBlockQuoteLevel
+  let bqPrefix = case bqLevel of
+                    0 -> ""
+                    n -> T.replicate n ">" <> " "
   labelText <- inlineListToDokuWiki opts label
-  contents <- mapM (blockListToDokuWiki opts) items
-  useTags <- stUseTags <$> ask
-  if useTags
-     then return $ "<HTML><dt></HTML>" ++ labelText ++ "<HTML></dt></HTML>\n" ++
-           intercalate "\n" (map (\d -> "<HTML><dd></HTML>" ++ d ++ "<HTML></dd></HTML>") contents)
-     else do
-       indent <- stIndent <$> ask
-       backSlash <- stBackSlashLB <$> ask
-       let indent' = if backSlash then drop 2 indent else indent
-       return $ indent' ++ "* **" ++ labelText ++ "** " ++ concat contents
-
--- | True if the list can be handled by simple wiki markup, False if HTML tags will be needed.
-isSimpleList :: Block -> Bool
-isSimpleList x =
-  case x of
-       BulletList items                 -> all isSimpleListItem items
-       OrderedList (num, sty, _) items  -> all isSimpleListItem items &&
-                                            num == 1 && sty `elem` [DefaultStyle, Decimal]
-       DefinitionList items             -> all isSimpleListItem $ concatMap snd items
-       _                                -> False
+  contents <- local (\st -> st{ stBlockQuoteLevel = 0 })
+               (mapM (blockListToDokuWiki opts) items)
+  indent <- asks stIndent
+  backSlash <- asks stBackSlashLB
+  let indent' = if backSlash then T.drop 2 indent else indent
+  return $ bqPrefix <> indent' <> "* **" <> labelText <> "** " <>
+    if useWrap
+       then "<WRAP>\n" <> vcat contents <> "\n</WRAP>"
+       else T.intercalate "; " contents
 
 -- | True if list item can be handled with the simple wiki syntax.  False if
---   HTML tags will be needed.
+--   WRAP tags will be needed.
 isSimpleListItem :: [Block] -> Bool
 isSimpleListItem []  = True
-isSimpleListItem [x] =
-  case x of
-       Plain _          -> True
-       Para  _          -> True
-       BulletList _     -> isSimpleList x
-       OrderedList _ _  -> isSimpleList x
-       DefinitionList _ -> isSimpleList x
-       _                -> False
-isSimpleListItem [x, y] | isPlainOrPara x =
-  case y of
-       BulletList _     -> isSimpleList y
-       OrderedList _ _  -> isSimpleList y
-       DefinitionList _ -> isSimpleList y
-       CodeBlock _ _    -> True
-       _                -> False
+isSimpleListItem [x, CodeBlock{}] | isPlainOrPara x = True
+isSimpleListItem (Div _ bs : ys) = -- see #8920
+  isSimpleListItem bs && all isSimpleList ys
+isSimpleListItem (x:ys) | isPlainOrPara x = all isSimpleList ys
 isSimpleListItem _ = False
+--- | True if the list can be handled by simple wiki markup, False if HTML tags will be needed.
 
+isSimpleList :: Block -> Bool
+isSimpleList x =
+  case x of
+       BulletList items            -> all isSimpleListItem items
+       OrderedList (1, _, _) items -> all isSimpleListItem items
+       DefinitionList items        -> all (all isSimpleListItem . snd) items
+       _                           -> False
+
 isPlainOrPara :: Block -> Bool
 isPlainOrPara (Plain _) = True
 isPlainOrPara (Para  _) = True
 isPlainOrPara _         = False
 
-isSimpleBlockQuote :: [Block] -> Bool
-isSimpleBlockQuote bs  = all isPlainOrPara bs
-
 -- | Concatenates strings with line breaks between them.
-vcat :: [String] -> String
-vcat = intercalate "\n"
+vcat :: [Text] -> Text
+vcat = T.intercalate "\n"
 
-backSlashLineBreaks :: String -> String
-backSlashLineBreaks cs = reverse $ g $ reverse $ concatMap f cs
-  where f '\n' = "\\\\ "
-        f c    = [c]
-        g (' ' : '\\':'\\': xs) = xs
-        g s                     = s
+-- | For each string in the input list, convert all newlines to
+-- dokuwiki escaped newlines. Then concat the list using double linebreaks.
+backSlashLineBreaks :: [Text] -> Text
+backSlashLineBreaks ls = vcatBackSlash $ map (T.pack . escape . T.unpack) ls
+  where
+    vcatBackSlash = T.intercalate "\\\\ \\\\ " -- simulate paragraphs.
+    escape ['\n']    = "" -- remove trailing newlines
+    escape ('\n':cs) = "\\\\ " <> escape cs
+    escape (c:cs)    = c : escape cs
+    escape []        = []
 
 -- Auxiliary functions for tables:
 
@@ -379,78 +323,83 @@
                     => WriterOptions
                     -> Alignment
                     -> [Block]
-                    -> DokuWiki m String
+                    -> DokuWiki m Text
 tableItemToDokuWiki opts align' item = do
   let mkcell x = (if align' == AlignRight || align' == AlignCenter
                      then "  "
-                     else "") ++ x ++
+                     else "") <> x <>
                  (if align' == AlignLeft || align' == AlignCenter
                      then "  "
                      else "")
-  contents <- local (\s -> s { stBackSlashLB = True }) $
-              blockListToDokuWiki opts item
+  contents <- local (\s -> s { stBackSlashLB = True
+                             , stBlockQuoteLevel = 0 }) $
+                blockListToDokuWiki opts item
   return $ mkcell contents
 
 -- | Convert list of Pandoc block elements to DokuWiki.
 blockListToDokuWiki :: PandocMonad m
                     => WriterOptions -- ^ Options
                     -> [Block]       -- ^ List of block elements
-                    -> DokuWiki m String
+                    -> DokuWiki m Text
 blockListToDokuWiki opts blocks = do
-  backSlash <- stBackSlashLB <$> ask
+  backSlash <- asks stBackSlashLB
   let blocks' = consolidateRawBlocks blocks
   if backSlash
-    then (backSlashLineBreaks . vcat) <$> mapM (blockToDokuWiki opts) blocks'
+    then backSlashLineBreaks <$> mapM (blockToDokuWiki opts) blocks'
     else vcat <$> mapM (blockToDokuWiki opts) blocks'
 
 consolidateRawBlocks :: [Block] -> [Block]
 consolidateRawBlocks [] = []
 consolidateRawBlocks (RawBlock f1 b1 : RawBlock f2 b2 : xs)
-  | f1 == f2 = consolidateRawBlocks (RawBlock f1 (b1 ++ "\n" ++ b2) : xs)
+  | f1 == f2 = consolidateRawBlocks (RawBlock f1 (b1 <> "\n" <> b2) : xs)
 consolidateRawBlocks (x:xs) = x : consolidateRawBlocks xs
 
 -- | Convert list of Pandoc inline elements to DokuWiki.
 inlineListToDokuWiki :: PandocMonad m
-                     => WriterOptions -> [Inline] -> DokuWiki m String
+                     => WriterOptions -> [Inline] -> DokuWiki m Text
 inlineListToDokuWiki opts lst =
-  concat <$> mapM (inlineToDokuWiki opts) lst
+  T.concat <$> mapM (inlineToDokuWiki opts) lst
 
 -- | Convert Pandoc inline element to DokuWiki.
 inlineToDokuWiki :: PandocMonad m
-                 => WriterOptions -> Inline -> DokuWiki m String
+                 => WriterOptions -> Inline -> DokuWiki m Text
 
 inlineToDokuWiki opts (Span _attrs ils) =
   inlineListToDokuWiki opts ils
 
 inlineToDokuWiki opts (Emph lst) = do
   contents <- inlineListToDokuWiki opts lst
-  return $ "//" ++ contents ++ "//"
+  return $ "//" <> contents <> "//"
 
+inlineToDokuWiki opts (Underline lst) = do
+  contents <- inlineListToDokuWiki opts lst
+  return $ "__" <> contents <> "__"
+
 inlineToDokuWiki opts (Strong lst) = do
   contents <- inlineListToDokuWiki opts lst
-  return $ "**" ++ contents ++ "**"
+  return $ "**" <> contents <> "**"
 
 inlineToDokuWiki opts (Strikeout lst) = do
   contents <- inlineListToDokuWiki opts lst
-  return $ "<del>" ++ contents ++ "</del>"
+  return $ "<del>" <> contents <> "</del>"
 
 inlineToDokuWiki opts (Superscript lst) = do
   contents <- inlineListToDokuWiki opts lst
-  return $ "<sup>" ++ contents ++ "</sup>"
+  return $ "<sup>" <> contents <> "</sup>"
 
 inlineToDokuWiki opts (Subscript lst) = do
   contents <- inlineListToDokuWiki opts lst
-  return $ "<sub>" ++ contents ++ "</sub>"
+  return $ "<sub>" <> contents <> "</sub>"
 
 inlineToDokuWiki opts (SmallCaps lst) = inlineListToDokuWiki opts lst
 
 inlineToDokuWiki opts (Quoted SingleQuote lst) = do
   contents <- inlineListToDokuWiki opts lst
-  return $ "\8216" ++ contents ++ "\8217"
+  return $ "\8216" <> contents <> "\8217"
 
 inlineToDokuWiki opts (Quoted DoubleQuote lst) = do
   contents <- inlineListToDokuWiki opts lst
-  return $ "\8220" ++ contents ++ "\8221"
+  return $ "\8220" <> contents <> "\8221"
 
 inlineToDokuWiki opts (Cite _  lst) = inlineListToDokuWiki opts lst
 
@@ -464,22 +413,27 @@
   -- characters.
   -- It does mean that if pandoc could ever read dokuwiki, and so round-trip the format,
   -- any formatting inside inlined code blocks would be lost, or presented incorrectly.
-  return $ "''%%" ++ str ++ "%%''"
+  return $ "''%%" <> str <> "%%''"
 
 inlineToDokuWiki _ (Str str) = return $ escapeString str
 
-inlineToDokuWiki _ (Math mathType str) = return $ delim ++ str ++ delim
+inlineToDokuWiki _ (Math mathType str) = return $ delim <> str <> delim
                                  -- note:  str should NOT be escaped
   where delim = case mathType of
                      DisplayMath -> "$$"
                      InlineMath  -> "$"
 
-inlineToDokuWiki _ il@(RawInline f str)
+inlineToDokuWiki opts il@(RawInline f str)
   | f == Format "dokuwiki" = return str
-  | f == Format "html"     = return $ "<html>" ++ str ++ "</html>"
+  | f == Format "html"
+  , isEnabled Ext_raw_html opts = return $ "<html>" <> str <> "</html>"
   | otherwise              = "" <$ report (InlineNotRendered il)
 
-inlineToDokuWiki _ LineBreak = return "\\\\\n"
+inlineToDokuWiki _ LineBreak = do
+  backSlash <- asks stBackSlashLB
+  return $ if backSlash
+           then "\n"
+           else "\\\\\n"
 
 inlineToDokuWiki opts SoftBreak =
   case writerWrapText opts of
@@ -492,36 +446,51 @@
 inlineToDokuWiki opts (Link _ txt (src, _)) = do
   label <- inlineListToDokuWiki opts txt
   case txt of
-     [Str s] | "mailto:" `isPrefixOf` src -> return $ "<" ++ s ++ ">"
+     [Str s] | "mailto:" `T.isPrefixOf` src -> return $ "<" <> s <> ">"
              | escapeURI s == src -> return src
      _  -> if isURI src
-              then return $ "[[" ++ src  ++ "|" ++ label ++ "]]"
-              else return $ "[[" ++ src' ++ "|" ++ label ++ "]]"
-                     where src' = case src of
-                                     '/':xs -> xs  -- with leading / it's a
-                                     _      -> src -- link to a help page
+              then return $ "[[" <> src  <> "|" <> label <> "]]"
+              else return $ "[[" <> src' <> "|" <> label <> "]]"
+                     where src' = case T.uncons src of
+                                     Just ('/',xs) -> xs  -- with leading / it's a
+                                     _             -> src -- link to a help page
 inlineToDokuWiki opts (Image attr alt (source, tit)) = do
   alt' <- inlineListToDokuWiki opts alt
   let txt = case (tit, alt) of
               ("", []) -> ""
-              ("", _ ) -> "|" ++ alt'
-              (_ , _ ) -> "|" ++ tit
-      -- Relative links fail isURI and receive a colon
-      prefix = if isURI source then "" else ":"
-  return $ "{{" ++ prefix ++ source ++ imageDims opts attr ++ txt ++ "}}"
+              ("", _ ) -> "|" <> alt'
+              (_ , _ ) -> "|" <> tit
+  return $ "{{" <> source <> imageDims opts attr <> txt <> "}}"
 
 inlineToDokuWiki opts (Note contents) = do
-  contents' <- blockListToDokuWiki opts contents
-  return $ "((" ++ contents' ++ "))"
+  contents' <- local (\st -> st{ stBlockQuoteLevel = 0 })
+                 (blockListToDokuWiki opts contents)
+  return $ "((" <> contents' <> "))"
   -- note - may not work for notes with multiple blocks
 
-imageDims :: WriterOptions -> Attr -> String
+imageDims :: WriterOptions -> Attr -> Text
 imageDims opts attr = go (toPx $ dimension Width attr) (toPx $ dimension Height attr)
   where
     toPx = fmap (showInPixel opts) . checkPct
     checkPct (Just (Percent _)) = Nothing
     checkPct maybeDim           = maybeDim
-    go (Just w) Nothing  = "?" ++ w
-    go (Just w) (Just h) = "?" ++ w ++ "x" ++ h
-    go Nothing  (Just h) = "?0x" ++ h
+    go (Just w) Nothing  = "?" <> w
+    go (Just w) (Just h) = "?" <> w <> "x" <> h
+    go Nothing  (Just h) = "?0x" <> h
     go Nothing  Nothing  = ""
+
+languageNames :: M.Map Text Text
+languageNames = M.fromList
+  [("cs", "csharp")
+  ,("coffee", "cofeescript")
+  ,("commonlisp", "lisp")
+  ,("gcc", "c")
+  ,("html", "html5")
+  ,("makefile", "make")
+  ,("objectivec", "objc")
+  ,("r", "rsplus")
+  ,("sqlmysql", "mysql")
+  ,("sqlpostgresql", "postgresql")
+  ,("sci", "scilab")
+  ,("xorg", "xorgconf")
+  ]
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
@@ -1,1328 +1,1564 @@
 {-# LANGUAGE CPP                 #-}
 {-# LANGUAGE FlexibleContexts    #-}
 {-# LANGUAGE PatternGuards       #-}
-{-# LANGUAGE ScopedTypeVariables #-}
-{-
-Copyright (C) 2010-2017 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-2017 John MacFarlane
-   License     : GNU GPL, version 2 or above
-
-   Maintainer  : John MacFarlane <jgm@berkeley.edu>
-   Stability   : alpha
-   Portability : portable
-
-Conversion of 'Pandoc' documents to EPUB.
--}
-module Text.Pandoc.Writers.EPUB ( writeEPUB2, writeEPUB3 ) where
-import Codec.Archive.Zip (Entry, addEntryToArchive, eRelativePath, emptyArchive,
-                          fromArchive, fromEntry, toEntry)
-import Control.Monad (mplus, unless, when, zipWithM)
-import Control.Monad.Except (catchError, throwError)
-import Control.Monad.State.Strict (State, StateT, evalState, evalStateT, get,
-                                   gets, lift, modify, put)
-import qualified Data.ByteString.Lazy as B
-import qualified Data.ByteString.Lazy.Char8 as B8
-import Data.Char (isAlphaNum, isAscii, isDigit, toLower)
-import Data.List (intercalate, isInfixOf, isPrefixOf)
-import qualified Data.Map as M
-import Data.Maybe (fromMaybe, isNothing, mapMaybe, isJust)
-import qualified Data.Set as Set
-import qualified Data.Text as TS
-import qualified Data.Text.Lazy as TL
-import Network.HTTP (urlEncode)
-import System.FilePath (takeExtension, takeFileName, makeRelative)
-import Text.HTML.TagSoup (Tag (TagOpen), fromAttrib, parseTags)
-import Text.Pandoc.Builder (fromList, setMeta)
-import Text.Pandoc.Class (PandocMonad, report)
-import qualified Text.Pandoc.Class as P
-import Text.Pandoc.Compat.Time
-import Text.Pandoc.Definition
-import Text.Pandoc.Error
-import Text.Pandoc.Logging
-import Text.Pandoc.MIME (MimeType, extensionFromMimeType, getMimeType)
-import Text.Pandoc.Options (EPUBVersion (..), HTMLMathMethod (..),
-                            ObfuscationMethod (NoObfuscation), WrapOption (..),
-                            WriterOptions (..))
-import Text.Pandoc.Shared (hierarchicalize, normalizeDate, renderTags',
-                           safeRead, stringify, trim, uniqueIdent)
-import qualified Text.Pandoc.Shared as S (Element (..))
-import qualified Text.Pandoc.UTF8 as UTF8
-import Text.Pandoc.UUID (getUUID)
-import Text.Pandoc.Walk (query, walk, walkM)
-import Text.Pandoc.Writers.HTML (writeHtmlStringForEPUB)
-import Text.Printf (printf)
-import Text.XML.Light (Attr (..), Element (..), Node (..), QName (..),
-                       add_attrs, lookupAttr, node, onlyElems, parseXML,
-                       ppElement, showElement, strContent, unode, unqual)
-
--- A Chapter includes a list of blocks and maybe a section
--- number offset.  Note, some chapters are unnumbered. The section
--- number is different from the index number, which will be used
--- in filenames, chapter0003.xhtml.
-data Chapter = Chapter (Maybe [Int]) [Block]
-
-data EPUBState = EPUBState {
-        stMediaPaths  :: [(FilePath, (FilePath, Maybe Entry))]
-      , stEpubSubdir  :: String
-      }
-
-type E m = StateT EPUBState m
-
-data EPUBMetadata = EPUBMetadata{
-    epubIdentifier    :: [Identifier]
-  , epubTitle         :: [Title]
-  , epubDate          :: [Date]
-  , epubLanguage      :: String
-  , epubCreator       :: [Creator]
-  , epubContributor   :: [Creator]
-  , epubSubject       :: [String]
-  , epubDescription   :: Maybe String
-  , epubType          :: Maybe String
-  , epubFormat        :: Maybe String
-  , epubPublisher     :: Maybe String
-  , epubSource        :: Maybe String
-  , epubRelation      :: Maybe String
-  , epubCoverage      :: Maybe String
-  , epubRights        :: Maybe String
-  , epubCoverImage    :: Maybe String
-  , epubStylesheets   :: [FilePath]
-  , epubPageDirection :: Maybe ProgressionDirection
-  , epubIbooksFields  :: [(String, String)]
-  } deriving Show
-
-data Date = Date{
-    dateText  :: String
-  , dateEvent :: Maybe String
-  } deriving Show
-
-data Creator = Creator{
-    creatorText   :: String
-  , creatorRole   :: Maybe String
-  , creatorFileAs :: Maybe String
-  } deriving Show
-
-data Identifier = Identifier{
-    identifierText   :: String
-  , identifierScheme :: Maybe String
-  } deriving Show
-
-data Title = Title{
-    titleText   :: String
-  , titleFileAs :: Maybe String
-  , titleType   :: Maybe String
-  } deriving Show
-
-data ProgressionDirection = LTR | RTL deriving Show
-
-dcName :: String -> QName
-dcName n = QName n Nothing (Just "dc")
-
-dcNode :: Node t => String -> t -> Element
-dcNode = node . dcName
-
-opfName :: String -> QName
-opfName n = QName n Nothing (Just "opf")
-
-toId :: FilePath -> String
-toId = map (\x -> if isAlphaNum x || x == '-' || x == '_'
-                     then x
-                     else '_') . takeFileName
-
-removeNote :: Inline -> Inline
-removeNote (Note _) = Str ""
-removeNote x        = x
-
-mkEntry :: PandocMonad m => FilePath -> B.ByteString -> E m Entry
-mkEntry path content = do
-  epubSubdir <- gets stEpubSubdir
-  let addEpubSubdir :: Entry -> Entry
-      addEpubSubdir e = e{ eRelativePath =
-          (if null epubSubdir
-              then ""
-              else epubSubdir ++ "/") ++ eRelativePath e }
-  epochtime <- floor <$> lift P.getPOSIXTime
-  return $
-       (if path == "mimetype" || "META-INF" `isPrefixOf` path
-           then id
-           else addEpubSubdir) $ toEntry path epochtime content
-
-getEPUBMetadata :: PandocMonad m => WriterOptions -> Meta -> E m EPUBMetadata
-getEPUBMetadata opts meta = do
-  let md = metadataFromMeta opts meta
-  let elts = maybe [] (onlyElems . parseXML) $ writerEpubMetadata opts
-  let md' = foldr addMetadataFromXML md elts
-  let addIdentifier m =
-       if null (epubIdentifier m)
-          then do
-            randomId <- (show . getUUID) <$> lift P.newStdGen
-            return $ m{ epubIdentifier = [Identifier randomId Nothing] }
-          else return m
-  let addLanguage m =
-       if null (epubLanguage m)
-          then case lookup "lang" (writerVariables opts) of
-                     Just x  -> return m{ epubLanguage = x }
-                     Nothing -> do
-                       mLang <- lift $ P.lookupEnv "LANG"
-                       let localeLang =
-                             case mLang of
-                               Just lang ->
-                                 map (\c -> if c == '_' then '-' else c) $
-                                 takeWhile (/='.') lang
-                               Nothing -> "en-US"
-                       return m{ epubLanguage = localeLang }
-          else return m
-  let fixDate m =
-       if null (epubDate m)
-          then do
-            currentTime <- lift P.getCurrentTime
-            return $ m{ epubDate = [ Date{
-                             dateText = showDateTimeISO8601 currentTime
-                           , dateEvent = Nothing } ] }
-          else return m
-  let addAuthor m =
-       if any (\c -> creatorRole c == Just "aut") $ epubCreator m
-          then return m
-          else do
-            let authors' = map stringify $ docAuthors meta
-            let toAuthor name = Creator{ creatorText = name
-                                       , creatorRole = Just "aut"
-                                       , creatorFileAs = Nothing }
-            return $ m{ epubCreator = map toAuthor authors' ++ epubCreator m }
-  addIdentifier md' >>= fixDate >>= addAuthor >>= addLanguage
-
-addMetadataFromXML :: Element -> EPUBMetadata -> EPUBMetadata
-addMetadataFromXML e@(Element (QName name _ (Just "dc")) attrs _ _) md
-  | name == "identifier" = md{ epubIdentifier =
-             Identifier{ identifierText = strContent e
-                       , identifierScheme = lookupAttr (opfName "scheme") attrs
-                       } : epubIdentifier md }
-  | name == "title" = md{ epubTitle =
-            Title{ titleText = strContent e
-                 , titleFileAs = getAttr "file-as"
-                 , titleType = getAttr "type"
-                 } : epubTitle md }
-  | name == "date" = md{ epubDate =
-             Date{ dateText = fromMaybe "" $ normalizeDate' $ strContent e
-                 , dateEvent = getAttr "event"
-                 } : epubDate md }
-  | name == "language" = md{ epubLanguage = strContent e }
-  | name == "creator" = md{ epubCreator =
-              Creator{ creatorText = strContent e
-                     , creatorRole = getAttr "role"
-                     , creatorFileAs = getAttr "file-as"
-                     } : epubCreator md }
-  | name == "contributor" = md{ epubContributor =
-              Creator  { creatorText = strContent e
-                       , creatorRole = getAttr "role"
-                       , creatorFileAs = getAttr "file-as"
-                       } : epubContributor md }
-  | name == "subject" = md{ epubSubject = strContent e : epubSubject md }
-  | name == "description" = md { epubDescription = Just $ strContent e }
-  | name == "type" = md { epubType = Just $ strContent e }
-  | name == "format" = md { epubFormat = Just $ strContent e }
-  | name == "type" = md { epubType = Just $ strContent e }
-  | name == "publisher" = md { epubPublisher = Just $ strContent e }
-  | name == "source" = md { epubSource = Just $ strContent e }
-  | name == "relation" = md { epubRelation = Just $ strContent e }
-  | name == "coverage" = md { epubCoverage = Just $ strContent e }
-  | name == "rights" = md { epubRights = Just $ strContent e }
-  | otherwise = md
-  where getAttr n = lookupAttr (opfName n) attrs
-addMetadataFromXML _ md = md
-
-metaValueToString :: MetaValue -> String
-metaValueToString (MetaString s)    = s
-metaValueToString (MetaInlines ils) = stringify ils
-metaValueToString (MetaBlocks bs)   = stringify bs
-metaValueToString (MetaBool True)   = "true"
-metaValueToString (MetaBool False)  = "false"
-metaValueToString _                 = ""
-
-metaValueToPaths:: MetaValue -> [FilePath]
-metaValueToPaths (MetaList xs) = map metaValueToString xs
-metaValueToPaths x             = [metaValueToString x]
-
-getList :: String -> Meta -> (MetaValue -> a) -> [a]
-getList s meta handleMetaValue =
-  case lookupMeta s meta of
-       Just (MetaList xs) -> map handleMetaValue xs
-       Just mv            -> [handleMetaValue mv]
-       Nothing            -> []
-
-getIdentifier :: Meta -> [Identifier]
-getIdentifier meta = getList "identifier" meta handleMetaValue
-  where handleMetaValue (MetaMap m) =
-           Identifier{ identifierText = maybe "" metaValueToString
-                                        $ M.lookup "text" m
-                     , identifierScheme = metaValueToString <$>
-                                          M.lookup "scheme" m }
-        handleMetaValue mv = Identifier (metaValueToString mv) Nothing
-
-getTitle :: Meta -> [Title]
-getTitle meta = getList "title" meta handleMetaValue
-  where handleMetaValue (MetaMap m) =
-           Title{ titleText = maybe "" metaValueToString $ M.lookup "text" m
-                , titleFileAs = metaValueToString <$> M.lookup "file-as" m
-                , titleType = metaValueToString <$> M.lookup "type" m }
-        handleMetaValue mv = Title (metaValueToString mv) Nothing Nothing
-
-getCreator :: String -> Meta -> [Creator]
-getCreator s meta = getList s meta handleMetaValue
-  where handleMetaValue (MetaMap m) =
-           Creator{ creatorText = maybe "" metaValueToString $ M.lookup "text" m
-                  , creatorFileAs = metaValueToString <$> M.lookup "file-as" m
-                  , creatorRole = metaValueToString <$> M.lookup "role" m }
-        handleMetaValue mv = Creator (metaValueToString mv) Nothing Nothing
-
-getDate :: String -> Meta -> [Date]
-getDate s meta = getList s meta handleMetaValue
-  where handleMetaValue (MetaMap m) =
-           Date{ dateText = fromMaybe "" $
-                   M.lookup "text" m >>= normalizeDate' . metaValueToString
-               , dateEvent = metaValueToString <$> M.lookup "event" m }
-        handleMetaValue mv = Date { dateText = fromMaybe "" $ normalizeDate' $ metaValueToString mv
-                                  , dateEvent = Nothing }
-
-simpleList :: String -> Meta -> [String]
-simpleList s meta =
-  case lookupMeta s meta of
-       Just (MetaList xs) -> map metaValueToString xs
-       Just x             -> [metaValueToString x]
-       Nothing            -> []
-
-metadataFromMeta :: WriterOptions -> Meta -> EPUBMetadata
-metadataFromMeta opts meta = EPUBMetadata{
-      epubIdentifier         = identifiers
-    , epubTitle              = titles
-    , epubDate               = date
-    , epubLanguage           = language
-    , epubCreator            = creators
-    , epubContributor        = contributors
-    , epubSubject            = subjects
-    , epubDescription        = description
-    , epubType               = epubtype
-    , epubFormat             = format
-    , epubPublisher          = publisher
-    , epubSource             = source
-    , epubRelation           = relation
-    , epubCoverage           = coverage
-    , epubRights             = rights
-    , epubCoverImage         = coverImage
-    , epubStylesheets        = stylesheets
-    , epubPageDirection      = pageDirection
-    , epubIbooksFields       = ibooksFields
-    }
-  where identifiers = getIdentifier meta
-        titles = getTitle meta
-        date = getDate "date" meta
-        language = maybe "" metaValueToString $
-           lookupMeta "language" meta `mplus` lookupMeta "lang" meta
-        creators = getCreator "creator" meta
-        contributors = getCreator "contributor" meta
-        subjects = simpleList "subject" meta
-        description = metaValueToString <$> lookupMeta "description" meta
-        epubtype = metaValueToString <$> lookupMeta "type" meta
-        format = metaValueToString <$> lookupMeta "format" meta
-        publisher = metaValueToString <$> lookupMeta "publisher" meta
-        source = metaValueToString <$> lookupMeta "source" meta
-        relation = metaValueToString <$> lookupMeta "relation" meta
-        coverage = metaValueToString <$> lookupMeta "coverage" meta
-        rights = metaValueToString <$> lookupMeta "rights" meta
-        coverImage = lookup "epub-cover-image" (writerVariables opts) `mplus`
-             (metaValueToString <$> lookupMeta "cover-image" meta)
-        stylesheets = fromMaybe []
-                        (metaValueToPaths <$> lookupMeta "stylesheet" meta) ++
-                      [f | ("css",f) <- writerVariables opts]
-        pageDirection = case map toLower . metaValueToString <$>
-                             lookupMeta "page-progression-direction" meta of
-                              Just "ltr" -> Just LTR
-                              Just "rtl" -> Just RTL
-                              _          -> Nothing
-        ibooksFields = case lookupMeta "ibooks" meta of
-                            Just (MetaMap mp)
-                               -> M.toList $ M.map metaValueToString mp
-                            _  -> []
-
--- | Produce an EPUB2 file from a Pandoc document.
-writeEPUB2 :: PandocMonad m
-          => WriterOptions  -- ^ Writer options
-          -> Pandoc         -- ^ Document to convert
-          -> m B.ByteString
-writeEPUB2 = writeEPUB EPUB2
-
--- | Produce an EPUB3 file from a Pandoc document.
-writeEPUB3 :: PandocMonad m
-          => WriterOptions  -- ^ Writer options
-          -> Pandoc         -- ^ Document to convert
-          -> m B.ByteString
-writeEPUB3 = writeEPUB EPUB3
-
--- | Produce an EPUB file from a Pandoc document.
-writeEPUB :: PandocMonad m
-          => EPUBVersion
-          -> WriterOptions  -- ^ Writer options
-          -> Pandoc         -- ^ Document to convert
-          -> m B.ByteString
-writeEPUB epubVersion opts doc = do
-  let epubSubdir = writerEpubSubdirectory opts
-  -- sanity check on epubSubdir
-  unless (all (\c -> isAscii c && isAlphaNum c) epubSubdir) $
-    throwError $ PandocEpubSubdirectoryError epubSubdir
-  let initState = EPUBState { stMediaPaths = [], stEpubSubdir = epubSubdir }
-  evalStateT (pandocToEPUB epubVersion opts doc) initState
-
-pandocToEPUB :: PandocMonad m
-             => EPUBVersion
-             -> WriterOptions
-             -> Pandoc
-             -> E m B.ByteString
-pandocToEPUB version opts doc@(Pandoc meta _) = do
-  epubSubdir <- gets stEpubSubdir
-  let epub3 = version == EPUB3
-  let writeHtml o = fmap (UTF8.fromTextLazy . TL.fromStrict) .
-                      writeHtmlStringForEPUB version o
-  metadata <- getEPUBMetadata opts meta
-
-  -- stylesheet
-  stylesheets <- case epubStylesheets metadata of
-                      [] -> (\x -> [B.fromChunks [x]]) <$>
-                             P.readDataFile "epub.css"
-                      fs -> mapM P.readFileLazy fs
-  stylesheetEntries <- zipWithM
-        (\bs n -> mkEntry ("styles/stylesheet" ++ show n ++ ".css") bs)
-        stylesheets [(1 :: Int)..]
-
-  let vars = ("epub3", if epub3 then "true" else "false")
-             : [(x,y) | (x,y) <- writerVariables opts, x /= "css"]
-
-  let cssvars useprefix = map (\e -> ("css",
-                               (if useprefix
-                                   then "../"
-                                   else "")
-                               ++ makeRelative epubSubdir (eRelativePath e)))
-                          stylesheetEntries
-
-  let opts' = opts{ writerEmailObfuscation = NoObfuscation
-                  , writerSectionDivs = True
-                  , writerVariables = vars
-                  , writerHTMLMathMethod =
-                       if epub3
-                          then MathML
-                          else writerHTMLMathMethod opts
-                  , writerWrapText = WrapAuto }
-
-  -- cover page
-  (cpgEntry, cpicEntry) <-
-                case epubCoverImage metadata of
-                     Nothing   -> return ([],[])
-                     Just img  -> do
-                       let coverImage = takeFileName img
-                       cpContent <- lift $ writeHtml
-                            opts'{ writerVariables =
-                                    ("coverpage","true"):
-                                     cssvars True ++ vars }
-                            (Pandoc meta [RawBlock (Format "html") $ "<div id=\"cover-image\">\n<img src=\"../media/" ++ coverImage ++ "\" alt=\"cover image\" />\n</div>"])
-                       imgContent <- lift $ P.readFileLazy img
-                       coverEntry <- mkEntry "text/cover.xhtml" cpContent
-                       coverImageEntry <- mkEntry ("media/" ++ coverImage)
-                                             imgContent
-                       return ( [ coverEntry ]
-                              , [ coverImageEntry ] )
-
-  -- title page
-  tpContent <- lift $ writeHtml opts'{
-                                  writerVariables = ("titlepage","true"):
-                                  cssvars True ++ vars }
-                               (Pandoc meta [])
-  tpEntry <- mkEntry "text/title_page.xhtml" tpContent
-
-  -- handle pictures
-  -- mediaRef <- P.newIORef []
-  Pandoc _ blocks <- walkM (transformInline opts') doc >>=
-                     walkM transformBlock
-  picEntries <- (mapMaybe (snd . snd)) <$> gets stMediaPaths
-  -- handle fonts
-  let matchingGlob f = do
-        xs <- lift $ P.glob f
-        when (null xs) $
-          report $ CouldNotFetchResource f "glob did not match any font files"
-        return xs
-  let mkFontEntry f = mkEntry ("fonts/" ++ takeFileName f) =<<
-                        lift (P.readFileLazy f)
-  fontFiles <- concat <$> mapM matchingGlob (writerEpubFonts opts')
-  fontEntries <- mapM mkFontEntry fontFiles
-
-  -- set page progression direction attribution
-  let progressionDirection = case epubPageDirection metadata of
-                                  Just LTR | epub3 ->
-                                    [("page-progression-direction", "ltr")]
-                                  Just RTL | epub3 ->
-                                    [("page-progression-direction", "rtl")]
-                                  _  -> []
-
-  -- body pages
-
-  -- add level 1 header to beginning if none there
-  let blocks' = addIdentifiers
-                $ case blocks of
-                      (Header 1 _ _ : _) -> blocks
-                      _                  -> Header 1 ("",["unnumbered"],[])
-                                                 (docTitle' meta) : blocks
-
-  let chapterHeaderLevel = writerEpubChapterLevel opts
-
-  let isChapterHeader (Header n _ _) = n <= chapterHeaderLevel
-      isChapterHeader (Div ("",["references"],[]) (Header n _ _:_)) =
-        n <= chapterHeaderLevel
-      isChapterHeader _ = False
-
-  let toChapters :: [Block] -> State [Int] [Chapter]
-      toChapters []     = return []
-      toChapters (Div ("",["references"],[]) bs@(Header 1 _ _:_) : rest) =
-        toChapters (bs ++ rest)
-      toChapters (Header n attr@(_,classes,_) ils : bs) = do
-        nums <- get
-        mbnum <- if "unnumbered" `elem` classes
-                    then return Nothing
-                    else case splitAt (n - 1) nums of
-                              (ks, m:_) -> do
-                                let nums' = ks ++ [m+1]
-                                put nums'
-                                return $ Just (ks ++ [m])
-                                -- note, this is the offset not the sec number
-                              (ks, []) -> do
-                                let nums' = ks ++ [1]
-                                put nums'
-                                return $ Just ks
-        let (xs,ys) = break isChapterHeader bs
-        (Chapter mbnum (Header n attr ils : xs) :) `fmap` toChapters ys
-      toChapters (b:bs) = do
-        let (xs,ys) = break isChapterHeader bs
-        (Chapter Nothing (b:xs) :) `fmap` toChapters ys
-
-  let chapters' = evalState (toChapters blocks') []
-
-  let extractLinkURL' :: Int -> Inline -> [(String, String)]
-      extractLinkURL' num (Span (ident, _, _) _)
-        | not (null ident) = [(ident, showChapter num ++ ('#':ident))]
-      extractLinkURL' _ _ = []
-
-  let extractLinkURL :: Int -> Block -> [(String, String)]
-      extractLinkURL num (Div (ident, _, _) _)
-        | not (null ident) = [(ident, showChapter num ++ ('#':ident))]
-      extractLinkURL num (Header _ (ident, _, _) _)
-        | not (null ident) = [(ident, showChapter num ++ ('#':ident))]
-      extractLinkURL num b = query (extractLinkURL' num) b
-
-  let reftable = concat $ zipWith (\(Chapter _ bs) num ->
-                                    query (extractLinkURL num) bs)
-                          chapters' [1..]
-
-  let fixInternalReferences :: Inline -> Inline
-      fixInternalReferences (Link attr lab ('#':xs, tit)) =
-        case lookup xs reftable of
-             Just ys -> Link attr lab (ys, tit)
-             Nothing -> Link attr lab ('#':xs, tit)
-      fixInternalReferences x = x
-
-  -- internal reference IDs change when we chunk the file,
-  -- so that '#my-header-1' might turn into 'chap004.xhtml#my-header'.
-  -- this fixes that:
-  let chapters = map (\(Chapter mbnum bs) ->
-                         Chapter mbnum $ walk fixInternalReferences bs)
-                 chapters'
-
-  let chapToEntry num (Chapter mbnum bs) =
-        mkEntry ("text/" ++ showChapter num) =<<
-        writeHtml opts'{ writerNumberOffset = fromMaybe [] mbnum
-                       , writerVariables = cssvars True ++ vars }
-                 (case bs of
-                     (Header _ _ xs : _) ->
-                       -- remove notes or we get doubled footnotes
-                       Pandoc (setMeta "title" (walk removeNote $ fromList xs)
-                                 nullMeta) bs
-                     _                   -> Pandoc nullMeta bs)
-
-  chapterEntries <- zipWithM chapToEntry [1..] chapters
-
-  -- incredibly inefficient (TODO):
-  let containsMathML ent = epub3 &&
-                           "<math" `isInfixOf`
-        B8.unpack (fromEntry ent)
-  let containsSVG ent    = epub3 &&
-                           "<svg" `isInfixOf`
-        B8.unpack (fromEntry ent)
-  let props ent = ["mathml" | containsMathML ent] ++ ["svg" | containsSVG ent]
-
-  -- contents.opf
-  let chapterNode ent = unode "item" !
-                           ([("id", toId $ makeRelative epubSubdir
-                                         $ eRelativePath ent),
-                             ("href", makeRelative epubSubdir
-                                      $ eRelativePath ent),
-                             ("media-type", "application/xhtml+xml")]
-                            ++ case props ent of
-                                    [] -> []
-                                    xs -> [("properties", unwords xs)])
-                        $ ()
-
-  let chapterRefNode ent = unode "itemref" !
-                             [("idref", toId $ makeRelative epubSubdir
-                                             $ eRelativePath ent)] $ ()
-  let pictureNode ent = unode "item" !
-                           [("id", toId $ makeRelative epubSubdir
-                                        $ eRelativePath ent),
-                            ("href", makeRelative epubSubdir
-                                     $ eRelativePath ent),
-                            ("media-type",
-                               fromMaybe "application/octet-stream"
-                               $ mediaTypeOf $ eRelativePath ent)] $ ()
-  let fontNode ent = unode "item" !
-                           [("id", toId $ makeRelative epubSubdir
-                                        $ eRelativePath ent),
-                            ("href", makeRelative epubSubdir
-                                     $ eRelativePath ent),
-                            ("media-type", fromMaybe "" $
-                                  getMimeType $ eRelativePath ent)] $ ()
-  let plainTitle = case docTitle' meta of
-                        [] -> case epubTitle metadata of
-                                   []    -> "UNTITLED"
-                                   (x:_) -> titleText x
-                        x  -> stringify x
-
-  let tocTitle = fromMaybe plainTitle $
-                   metaValueToString <$> lookupMeta "toc-title" meta
-  uuid <- case epubIdentifier metadata of
-            (x:_) -> return $ identifierText x  -- use first identifier as UUID
-            []    -> throwError $ PandocShouldNeverHappenError "epubIdentifier is null"  -- shouldn't happen
-  currentTime <- lift P.getCurrentTime
-  let contentsData = UTF8.fromStringLazy $ ppTopElement $
-        unode "package" !
-          ([("version", case version of
-                             EPUB2 -> "2.0"
-                             EPUB3 -> "3.0")
-           ,("xmlns","http://www.idpf.org/2007/opf")
-           ,("unique-identifier","epub-id-1")
-           ] ++
-           [("prefix","ibooks: http://vocabulary.itunes.apple.com/rdf/ibooks/vocabulary-extensions-1.0/") | version == EPUB3]) $
-          [ metadataElement version metadata currentTime
-          , unode "manifest" $
-             [ unode "item" ! [("id","ncx"), ("href","toc.ncx")
-                              ,("media-type","application/x-dtbncx+xml")] $ ()
-             , unode "item" ! ([("id","nav")
-                               ,("href","nav.xhtml")
-                               ,("media-type","application/xhtml+xml")] ++
-                               [("properties","nav") | epub3 ]) $ ()
-             ] ++
-             [ unode "item" ! [("id","style"), ("href",fp)
-                              ,("media-type","text/css")] $ () |
-                             fp <- map
-                               (makeRelative epubSubdir . eRelativePath)
-                               stylesheetEntries ] ++
-             map chapterNode (cpgEntry ++ (tpEntry : chapterEntries)) ++
-             (case cpicEntry of
-                    []    -> []
-                    (x:_) -> [add_attrs
-                              [Attr (unqual "properties") "cover-image" | epub3]
-                              (pictureNode x)]) ++
-             map pictureNode picEntries ++
-             map fontNode fontEntries
-          , unode "spine" ! (
-             ("toc","ncx") : progressionDirection) $
-              case epubCoverImage metadata of
-                    Nothing -> []
-                    Just _ -> [ unode "itemref" !
-                                [("idref", "cover_xhtml")] $ () ]
-              ++ ((unode "itemref" ! [("idref", "title_page_xhtml")
-                                     ,("linear",
-                                         case lookupMeta "title" meta of
-                                               Just _  -> "yes"
-                                               Nothing -> "no")] $ ()) :
-                  [unode "itemref" ! [("idref", "nav")] $ ()
-                         | writerTableOfContents opts ] ++
-                  map chapterRefNode chapterEntries)
-          , unode "guide" $
-             [ unode "reference" !
-                   [("type","toc"),("title", tocTitle),
-                    ("href","nav.xhtml")] $ ()
-             ] ++
-             [ unode "reference" !
-                   [("type","cover")
-                   ,("title","Cover")
-                   ,("href","text/cover.xhtml")] $ ()
-               | isJust (epubCoverImage metadata)
-             ]
-          ]
-  contentsEntry <- mkEntry "content.opf" contentsData
-
-  -- toc.ncx
-  let secs = hierarchicalize blocks'
-
-  let tocLevel = writerTOCDepth opts
-
-  let navPointNode :: PandocMonad m
-                   => (Int -> [Inline] -> String -> [Element] -> Element)
-                   -> S.Element -> StateT Int m Element
-      navPointNode formatter (S.Sec _ nums (ident,_,_) ils children) = do
-        n <- get
-        modify (+1)
-        let showNums :: [Int] -> String
-            showNums = intercalate "." . map show
-        let tit = if writerNumberSections opts && not (null nums)
-                     then Span ("", ["section-header-number"], [])
-                           [Str (showNums nums)] : Space : ils
-                     else ils
-        src <- case lookup ident reftable of
-                 Just x  -> return x
-                 Nothing -> throwError $ PandocSomeError $ ident ++ " not found in reftable"
-        let isSec (S.Sec lev _ _ _ _) = lev <= tocLevel
-            isSec _                   = False
-        let subsecs = filter isSec children
-        subs <- mapM (navPointNode formatter) subsecs
-        return $ formatter n tit src subs
-      navPointNode _ (S.Blk _) = throwError $ PandocSomeError "navPointNode encountered Blk"
-
-  let navMapFormatter :: Int -> [Inline] -> String -> [Element] -> Element
-      navMapFormatter n tit src subs = unode "navPoint" !
-               [("id", "navPoint-" ++ show n)] $
-                  [ unode "navLabel" $ unode "text" $ stringify tit
-                  , unode "content" ! [("src", "text/" ++ src)] $ ()
-                  ] ++ subs
-
-  let tpNode = unode "navPoint" !  [("id", "navPoint-0")] $
-                  [ unode "navLabel" $ unode "text" (stringify $ docTitle' meta)
-                  , unode "content" ! [("src", "text/title_page.xhtml")]
-                  $ () ]
-
-  navMap <- lift $ evalStateT (mapM (navPointNode navMapFormatter) secs) 1
-  let tocData = UTF8.fromStringLazy $ ppTopElement $
-        unode "ncx" ! [("version","2005-1")
-                       ,("xmlns","http://www.daisy.org/z3986/2005/ncx/")] $
-          [ unode "head" $
-             [ unode "meta" ! [("name","dtb:uid")
-                              ,("content", uuid)] $ ()
-             , unode "meta" ! [("name","dtb:depth")
-                              ,("content", "1")] $ ()
-             , unode "meta" ! [("name","dtb:totalPageCount")
-                              ,("content", "0")] $ ()
-             , unode "meta" ! [("name","dtb:maxPageNumber")
-                              ,("content", "0")] $ ()
-             ] ++ case epubCoverImage metadata of
-                        Nothing  -> []
-                        Just img -> [unode "meta" ! [("name","cover"),
-                                            ("content", toId img)] $ ()]
-          , unode "docTitle" $ unode "text" plainTitle
-          , unode "navMap" $
-              tpNode : navMap
-          ]
-  tocEntry <- mkEntry "toc.ncx" tocData
-
-  let navXhtmlFormatter :: Int -> [Inline] -> String -> [Element] -> Element
-      navXhtmlFormatter n tit src subs = unode "li" !
-                                       [("id", "toc-li-" ++ show n)] $
-                                            (unode "a" !
-                                                [("href", "text/" ++ src)]
-                                             $ titElements)
-                                            : case subs of
-                                                 []    -> []
-                                                 (_:_) -> [unode "ol" ! [("class","toc")] $ subs]
-          where titElements = parseXML titRendered
-                titRendered = case P.runPure
-                               (writeHtmlStringForEPUB version
-                                 opts{ writerTemplate = Nothing }
-                                 (Pandoc nullMeta
-                                   [Plain $ walk delink tit])) of
-                                Left _  -> TS.pack $ stringify tit
-                                Right x -> x
-                -- can't have a element inside a...
-                delink (Link _ ils _) = Span ("", [], []) ils
-                delink x              = x
-
-  let navtag = if epub3 then "nav" else "div"
-  tocBlocks <- lift $ evalStateT (mapM (navPointNode navXhtmlFormatter) secs) 1
-  let navBlocks = [RawBlock (Format "html")
-                  $ showElement $ -- prettyprinting introduces bad spaces
-                   unode navtag ! ([("epub:type","toc") | epub3] ++
-                                   [("id","toc")]) $
-                    [ unode "h1" ! [("id","toc-title")] $ tocTitle
-                    , unode "ol" ! [("class","toc")] $ tocBlocks ]]
-  let landmarks = if epub3
-                     then [RawBlock (Format "html") $ ppElement $
-                            unode "nav" ! [("epub:type","landmarks")
-                                          ,("hidden","hidden")] $
-                            [ unode "ol" $
-                              [ unode "li"
-                                [ unode "a" ! [("href", "text/cover.xhtml")
-                                              ,("epub:type", "cover")] $
-                                  "Cover"] |
-                                  epubCoverImage metadata /= Nothing
-                              ] ++
-                              [ unode "li"
-                                [ unode "a" ! [("href", "#toc")
-                                              ,("epub:type", "toc")] $
-                                    "Table of contents"
-                                ] | writerTableOfContents opts
-                              ]
-                            ]
-                          ]
-                     else []
-  navData <- lift $ writeHtml opts'{ writerVariables = ("navpage","true"):
-                     cssvars False ++ vars }
-            (Pandoc (setMeta "title"
-                     (walk removeNote $ fromList $ docTitle' meta) nullMeta)
-               (navBlocks ++ landmarks))
-  navEntry <- mkEntry "nav.xhtml" navData
-
-  -- mimetype
-  mimetypeEntry <- mkEntry "mimetype" $
-                        UTF8.fromStringLazy "application/epub+zip"
-
-  -- container.xml
-  let containerData = UTF8.fromStringLazy $ ppTopElement $
-       unode "container" ! [("version","1.0")
-              ,("xmlns","urn:oasis:names:tc:opendocument:xmlns:container")] $
-         unode "rootfiles" $
-           unode "rootfile" ! [("full-path",
-                    (if null epubSubdir
-                        then ""
-                        else epubSubdir ++ "/") ++ "content.opf")
-               ,("media-type","application/oebps-package+xml")] $ ()
-  containerEntry <- mkEntry "META-INF/container.xml" containerData
-
-  -- com.apple.ibooks.display-options.xml
-  let apple = UTF8.fromStringLazy $ ppTopElement $
-        unode "display_options" $
-          unode "platform" ! [("name","*")] $
-            unode "option" ! [("name","specified-fonts")] $ "true"
-  appleEntry <- mkEntry "META-INF/com.apple.ibooks.display-options.xml" apple
-
-  -- construct archive
-  let archive = foldr addEntryToArchive emptyArchive $
-                 [mimetypeEntry, containerEntry, appleEntry,
-                  contentsEntry, tocEntry, navEntry, tpEntry] ++
-                  stylesheetEntries ++ picEntries ++ cpicEntry ++
-                  cpgEntry ++ chapterEntries ++ fontEntries
-  return $ fromArchive archive
-
-metadataElement :: EPUBVersion -> EPUBMetadata -> UTCTime -> Element
-metadataElement version md currentTime =
-  unode "metadata" ! [("xmlns:dc","http://purl.org/dc/elements/1.1/")
-                     ,("xmlns:opf","http://www.idpf.org/2007/opf")] $ mdNodes
-  where mdNodes = identifierNodes ++ titleNodes ++ dateNodes
-                  ++ languageNodes ++ ibooksNodes
-                  ++ creatorNodes ++ contributorNodes ++ subjectNodes
-                  ++ descriptionNodes ++ typeNodes ++ formatNodes
-                  ++ publisherNodes ++ sourceNodes ++ relationNodes
-                  ++ coverageNodes ++ rightsNodes ++ coverImageNodes
-                  ++ modifiedNodes
-        withIds base f = concat . zipWith f (map (\x -> base ++ ('-' : show x))
-                         ([1..] :: [Int]))
-        identifierNodes = withIds "epub-id" toIdentifierNode $
-                          epubIdentifier md
-        titleNodes = withIds "epub-title" toTitleNode $ epubTitle md
-        dateNodes = if version == EPUB2
-                       then withIds "epub-date" toDateNode $ epubDate md
-                       else -- epub3 allows only one dc:date
-                            -- http://www.idpf.org/epub/30/spec/epub30-publications.html#sec-opf-dcdate
-                            case epubDate md of
-                                 [] -> []
-                                 (x:_) -> [dcNode "date" ! [("id","epub-date")]
-                                            $ dateText x]
-        ibooksNodes = map ibooksNode (epubIbooksFields md)
-        ibooksNode (k, v) = unode "meta" ! [("property", "ibooks:" ++ k)] $ v
-        languageNodes = [dcTag "language" $ epubLanguage md]
-        creatorNodes = withIds "epub-creator" (toCreatorNode "creator") $
-                       epubCreator md
-        contributorNodes = withIds "epub-contributor"
-                           (toCreatorNode "contributor") $ epubContributor md
-        subjectNodes = map (dcTag "subject") $ epubSubject md
-        descriptionNodes = maybe [] (dcTag' "description") $ epubDescription md
-        typeNodes = maybe [] (dcTag' "type") $ epubType md
-        formatNodes = maybe [] (dcTag' "format") $ epubFormat md
-        publisherNodes = maybe [] (dcTag' "publisher") $ epubPublisher md
-        sourceNodes = maybe [] (dcTag' "source") $ epubSource md
-        relationNodes = maybe [] (dcTag' "relation") $ epubRelation md
-        coverageNodes = maybe [] (dcTag' "coverage") $ epubCoverage md
-        rightsNodes = maybe [] (dcTag' "rights") $ epubRights md
-        coverImageNodes = maybe []
-            (\img -> [unode "meta" !  [("name","cover"),
-                                       ("content",toId img)] $ ()])
-            $ epubCoverImage md
-        modifiedNodes = [ unode "meta" ! [("property", "dcterms:modified")] $
-               showDateTimeISO8601 currentTime | version == EPUB3 ]
-        dcTag n s = unode ("dc:" ++ n) s
-        dcTag' n s = [dcTag n s]
-        toIdentifierNode id' (Identifier txt scheme)
-          | version == EPUB2 = [dcNode "identifier" !
-              ([("id",id')] ++ maybe [] (\x -> [("opf:scheme", x)]) scheme) $
-              txt]
-          | otherwise = [dcNode "identifier" ! [("id",id')] $ txt] ++
-              maybe [] (\x -> [unode "meta" !
-                  [("refines",'#':id'),("property","identifier-type"),
-                   ("scheme","onix:codelist5")] $ x])
-                (schemeToOnix `fmap` scheme)
-        toCreatorNode s id' creator
-          | version == EPUB2 = [dcNode s !
-             (("id",id') :
-              maybe [] (\x -> [("opf:file-as",x)]) (creatorFileAs creator) ++
-              maybe [] (\x -> [("opf:role",x)])
-               (creatorRole creator >>= toRelator)) $ creatorText creator]
-          | otherwise = [dcNode s ! [("id",id')] $ creatorText creator] ++
-              maybe [] (\x -> [unode "meta" !
-                   [("refines",'#':id'),("property","file-as")] $ x])
-                   (creatorFileAs creator) ++
-              maybe [] (\x -> [unode "meta" !
-                   [("refines",'#':id'),("property","role"),
-                     ("scheme","marc:relators")] $ x])
-                   (creatorRole creator >>= toRelator)
-        toTitleNode id' title
-          | version == EPUB2 = [dcNode "title" !
-             (("id",id') :
-              -- note: EPUB2 doesn't accept opf:title-type
-              maybe [] (\x -> [("opf:file-as",x)]) (titleFileAs title)) $
-              titleText title]
-          | otherwise = [dcNode "title" ! [("id",id')] $ titleText title]
-              ++
-              maybe [] (\x -> [unode "meta" !
-                   [("refines",'#':id'),("property","file-as")] $ x])
-                   (titleFileAs title) ++
-              maybe [] (\x -> [unode "meta" !
-                   [("refines",'#':id'),("property","title-type")] $ x])
-                   (titleType title)
-        toDateNode id' date = [dcNode "date" !
-             (("id",id') :
-                maybe [] (\x -> [("opf:event",x)]) (dateEvent date)) $
-                 dateText date]
-        schemeToOnix "ISBN-10"              = "02"
-        schemeToOnix "GTIN-13"              = "03"
-        schemeToOnix "UPC"                  = "04"
-        schemeToOnix "ISMN-10"              = "05"
-        schemeToOnix "DOI"                  = "06"
-        schemeToOnix "LCCN"                 = "13"
-        schemeToOnix "GTIN-14"              = "14"
-        schemeToOnix "ISBN-13"              = "15"
-        schemeToOnix "Legal deposit number" = "17"
-        schemeToOnix "URN"                  = "22"
-        schemeToOnix "OCLC"                 = "23"
-        schemeToOnix "ISMN-13"              = "25"
-        schemeToOnix "ISBN-A"               = "26"
-        schemeToOnix "JP"                   = "27"
-        schemeToOnix "OLCC"                 = "28"
-        schemeToOnix _                      = "01"
-
-showDateTimeISO8601 :: UTCTime -> String
-showDateTimeISO8601 = formatTime defaultTimeLocale "%FT%TZ"
-
-transformTag :: PandocMonad m
-             => Tag String
-             -> E m (Tag String)
-transformTag tag@(TagOpen name attr)
-  | name `elem` ["video", "source", "img", "audio"] &&
-    isNothing (lookup "data-external" attr) = do
-  let src = fromAttrib "src" tag
-  let poster = fromAttrib "poster" tag
-  newsrc <- modifyMediaRef src
-  newposter <- modifyMediaRef poster
-  let attr' = filter (\(x,_) -> x /= "src" && x /= "poster") attr ++
-              [("src", "../" ++ newsrc) | not (null newsrc)] ++
-              [("poster", "../" ++ newposter) | not (null newposter)]
-  return $ TagOpen name attr'
-transformTag tag = return tag
-
-modifyMediaRef :: PandocMonad m
-               => FilePath
-               -> E m FilePath
-modifyMediaRef "" = return ""
-modifyMediaRef oldsrc = do
-  media <- gets stMediaPaths
-  case lookup oldsrc media of
-         Just (n,_) -> return n
-         Nothing    -> catchError
-           (do (img, mbMime) <- P.fetchItem oldsrc
-               let new = "media/file" ++ show (length media) ++
-                          fromMaybe (takeExtension (takeWhile (/='?') oldsrc))
-                          (('.':) <$> (mbMime >>= extensionFromMimeType))
-               entry <- mkEntry new (B.fromChunks . (:[]) $ img)
-               modify $ \st -> st{ stMediaPaths =
-                            (oldsrc, (new, Just entry)):media}
-               return new)
-           (\e -> do
-                report $ CouldNotFetchResource oldsrc (show e)
-                return oldsrc)
-
-transformBlock  :: PandocMonad m
-                => Block
-                -> E m Block
-transformBlock (RawBlock fmt raw)
-  | fmt == Format "html" = do
-  let tags = parseTags raw
-  tags' <- mapM transformTag tags
-  return $ RawBlock fmt (renderTags' tags')
-transformBlock b = return b
-
-transformInline  :: PandocMonad m
-                 => WriterOptions
-                 -> Inline
-                 -> E m Inline
-transformInline _opts (Image attr lab (src,tit)) = do
-    newsrc <- modifyMediaRef src
-    return $ Image attr lab ("../" ++ newsrc, tit)
-transformInline opts (x@(Math t m))
-  | WebTeX url <- writerHTMLMathMethod opts = do
-    newsrc <- modifyMediaRef (url ++ urlEncode m)
-    let mathclass = if t == DisplayMath then "display" else "inline"
-    return $ Span ("",["math",mathclass],[])
-                [Image nullAttr [x] ("../" ++ newsrc, "")]
-transformInline _opts (RawInline fmt raw)
-  | fmt == Format "html" = do
-  let tags = parseTags raw
-  tags' <- mapM transformTag tags
-  return $ RawInline fmt (renderTags' tags')
-transformInline _ x = return x
-
-(!) :: (t -> Element) -> [(String, String)] -> t -> Element
-(!) f attrs n = add_attrs (map (\(k,v) -> Attr (unqual k) v) attrs) (f n)
-
--- | Version of 'ppTopElement' that specifies UTF-8 encoding.
-ppTopElement :: Element -> String
-ppTopElement = ("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" ++) . unEntity . ppElement
-  -- unEntity removes numeric  entities introduced by ppElement
-  -- (kindlegen seems to choke on these).
-  where unEntity [] = ""
-        unEntity ('&':'#':xs) =
-                   let (ds,ys) = break (==';') xs
-                       rest = drop 1 ys
-                   in  case safeRead ('\'':'\\':ds ++ "'") of
-                          Just x  -> x : unEntity rest
-                          Nothing -> '&':'#':unEntity xs
-        unEntity (x:xs) = x : unEntity xs
-
-mediaTypeOf :: FilePath -> Maybe MimeType
-mediaTypeOf x =
-  let mediaPrefixes = ["image", "video", "audio"] in
-  case getMimeType x of
-    Just y | any (`isPrefixOf` y) mediaPrefixes -> Just y
-    _      -> Nothing
-
--- Returns filename for chapter number.
-showChapter :: Int -> String
-showChapter = printf "ch%03d.xhtml"
-
--- Add identifiers to any headers without them.
-addIdentifiers :: [Block] -> [Block]
-addIdentifiers bs = evalState (mapM go bs) Set.empty
- where go (Header n (ident,classes,kvs) ils) = do
-         ids <- get
-         let ident' = if null ident
-                         then uniqueIdent ils ids
-                         else ident
-         modify $ Set.insert ident'
-         return $ Header n (ident',classes,kvs) ils
-       go x = return x
-
--- Variant of normalizeDate that allows partial dates: YYYY, YYYY-MM
-normalizeDate' :: String -> Maybe String
-normalizeDate' xs =
-  let xs' = trim xs in
-  case xs' of
-       [y1,y2,y3,y4] | all isDigit [y1,y2,y3,y4] -> Just xs'     -- YYYY
-       [y1,y2,y3,y4,'-',m1,m2] | all isDigit [y1,y2,y3,y4,m1,m2]  -- YYYY-MM
-                                                 -> Just xs'
-       _                                         -> normalizeDate xs'
-
-toRelator :: String -> Maybe String
-toRelator x
-  | x `elem` relators = Just x
-  | otherwise         = lookup (map toLower x) relatorMap
-
-relators :: [String]
-relators = map snd relatorMap
-
-relatorMap :: [(String, String)]
-relatorMap =
-           [("abridger", "abr")
-           ,("actor", "act")
-           ,("adapter", "adp")
-           ,("addressee", "rcp")
-           ,("analyst", "anl")
-           ,("animator", "anm")
-           ,("annotator", "ann")
-           ,("appellant", "apl")
-           ,("appellee", "ape")
-           ,("applicant", "app")
-           ,("architect", "arc")
-           ,("arranger", "arr")
-           ,("art copyist", "acp")
-           ,("art director", "adi")
-           ,("artist", "art")
-           ,("artistic director", "ard")
-           ,("assignee", "asg")
-           ,("associated name", "asn")
-           ,("attributed name", "att")
-           ,("auctioneer", "auc")
-           ,("author", "aut")
-           ,("author in quotations or text abstracts", "aqt")
-           ,("author of afterword, colophon, etc.", "aft")
-           ,("author of dialog", "aud")
-           ,("author of introduction, etc.", "aui")
-           ,("autographer", "ato")
-           ,("bibliographic antecedent", "ant")
-           ,("binder", "bnd")
-           ,("binding designer", "bdd")
-           ,("blurb writer", "blw")
-           ,("book designer", "bkd")
-           ,("book producer", "bkp")
-           ,("bookjacket designer", "bjd")
-           ,("bookplate designer", "bpd")
-           ,("bookseller", "bsl")
-           ,("braille embosser", "brl")
-           ,("broadcaster", "brd")
-           ,("calligrapher", "cll")
-           ,("cartographer", "ctg")
-           ,("caster", "cas")
-           ,("censor", "cns")
-           ,("choreographer", "chr")
-           ,("cinematographer", "cng")
-           ,("client", "cli")
-           ,("collection registrar", "cor")
-           ,("collector", "col")
-           ,("collotyper", "clt")
-           ,("colorist", "clr")
-           ,("commentator", "cmm")
-           ,("commentator for written text", "cwt")
-           ,("compiler", "com")
-           ,("complainant", "cpl")
-           ,("complainant-appellant", "cpt")
-           ,("complainant-appellee", "cpe")
-           ,("composer", "cmp")
-           ,("compositor", "cmt")
-           ,("conceptor", "ccp")
-           ,("conductor", "cnd")
-           ,("conservator", "con")
-           ,("consultant", "csl")
-           ,("consultant to a project", "csp")
-           ,("contestant", "cos")
-           ,("contestant-appellant", "cot")
-           ,("contestant-appellee", "coe")
-           ,("contestee", "cts")
-           ,("contestee-appellant", "ctt")
-           ,("contestee-appellee", "cte")
-           ,("contractor", "ctr")
-           ,("contributor", "ctb")
-           ,("copyright claimant", "cpc")
-           ,("copyright holder", "cph")
-           ,("corrector", "crr")
-           ,("correspondent", "crp")
-           ,("costume designer", "cst")
-           ,("court governed", "cou")
-           ,("court reporter", "crt")
-           ,("cover designer", "cov")
-           ,("creator", "cre")
-           ,("curator", "cur")
-           ,("dancer", "dnc")
-           ,("data contributor", "dtc")
-           ,("data manager", "dtm")
-           ,("dedicatee", "dte")
-           ,("dedicator", "dto")
-           ,("defendant", "dfd")
-           ,("defendant-appellant", "dft")
-           ,("defendant-appellee", "dfe")
-           ,("degree granting institution", "dgg")
-           ,("delineator", "dln")
-           ,("depicted", "dpc")
-           ,("depositor", "dpt")
-           ,("designer", "dsr")
-           ,("director", "drt")
-           ,("dissertant", "dis")
-           ,("distribution place", "dbp")
-           ,("distributor", "dst")
-           ,("donor", "dnr")
-           ,("draftsman", "drm")
-           ,("dubious author", "dub")
-           ,("editor", "edt")
-           ,("editor of compilation", "edc")
-           ,("editor of moving image work", "edm")
-           ,("electrician", "elg")
-           ,("electrotyper", "elt")
-           ,("enacting jurisdiction", "enj")
-           ,("engineer", "eng")
-           ,("engraver", "egr")
-           ,("etcher", "etr")
-           ,("event place", "evp")
-           ,("expert", "exp")
-           ,("facsimilist", "fac")
-           ,("field director", "fld")
-           ,("film director", "fmd")
-           ,("film distributor", "fds")
-           ,("film editor", "flm")
-           ,("film producer", "fmp")
-           ,("filmmaker", "fmk")
-           ,("first party", "fpy")
-           ,("forger", "frg")
-           ,("former owner", "fmo")
-           ,("funder", "fnd")
-           ,("geographic information specialist", "gis")
-           ,("honoree", "hnr")
-           ,("host", "hst")
-           ,("host institution", "his")
-           ,("illuminator", "ilu")
-           ,("illustrator", "ill")
-           ,("inscriber", "ins")
-           ,("instrumentalist", "itr")
-           ,("interviewee", "ive")
-           ,("interviewer", "ivr")
-           ,("inventor", "inv")
-           ,("issuing body", "isb")
-           ,("judge", "jud")
-           ,("jurisdiction governed", "jug")
-           ,("laboratory", "lbr")
-           ,("laboratory director", "ldr")
-           ,("landscape architect", "lsa")
-           ,("lead", "led")
-           ,("lender", "len")
-           ,("libelant", "lil")
-           ,("libelant-appellant", "lit")
-           ,("libelant-appellee", "lie")
-           ,("libelee", "lel")
-           ,("libelee-appellant", "let")
-           ,("libelee-appellee", "lee")
-           ,("librettist", "lbt")
-           ,("licensee", "lse")
-           ,("licensor", "lso")
-           ,("lighting designer", "lgd")
-           ,("lithographer", "ltg")
-           ,("lyricist", "lyr")
-           ,("manufacture place", "mfp")
-           ,("manufacturer", "mfr")
-           ,("marbler", "mrb")
-           ,("markup editor", "mrk")
-           ,("metadata contact", "mdc")
-           ,("metal-engraver", "mte")
-           ,("moderator", "mod")
-           ,("monitor", "mon")
-           ,("music copyist", "mcp")
-           ,("musical director", "msd")
-           ,("musician", "mus")
-           ,("narrator", "nrt")
-           ,("onscreen presenter", "osp")
-           ,("opponent", "opn")
-           ,("organizer of meeting", "orm")
-           ,("originator", "org")
-           ,("other", "oth")
-           ,("owner", "own")
-           ,("panelist", "pan")
-           ,("papermaker", "ppm")
-           ,("patent applicant", "pta")
-           ,("patent holder", "pth")
-           ,("patron", "pat")
-           ,("performer", "prf")
-           ,("permitting agency", "pma")
-           ,("photographer", "pht")
-           ,("plaintiff", "ptf")
-           ,("plaintiff-appellant", "ptt")
-           ,("plaintiff-appellee", "pte")
-           ,("platemaker", "plt")
-           ,("praeses", "pra")
-           ,("presenter", "pre")
-           ,("printer", "prt")
-           ,("printer of plates", "pop")
-           ,("printmaker", "prm")
-           ,("process contact", "prc")
-           ,("producer", "pro")
-           ,("production company", "prn")
-           ,("production designer", "prs")
-           ,("production manager", "pmn")
-           ,("production personnel", "prd")
-           ,("production place", "prp")
-           ,("programmer", "prg")
-           ,("project director", "pdr")
-           ,("proofreader", "pfr")
-           ,("provider", "prv")
-           ,("publication place", "pup")
-           ,("publisher", "pbl")
-           ,("publishing director", "pbd")
-           ,("puppeteer", "ppt")
-           ,("radio director", "rdd")
-           ,("radio producer", "rpc")
-           ,("recording engineer", "rce")
-           ,("recordist", "rcd")
-           ,("redaktor", "red")
-           ,("renderer", "ren")
-           ,("reporter", "rpt")
-           ,("repository", "rps")
-           ,("research team head", "rth")
-           ,("research team member", "rtm")
-           ,("researcher", "res")
-           ,("respondent", "rsp")
-           ,("respondent-appellant", "rst")
-           ,("respondent-appellee", "rse")
-           ,("responsible party", "rpy")
-           ,("restager", "rsg")
-           ,("restorationist", "rsr")
-           ,("reviewer", "rev")
-           ,("rubricator", "rbr")
-           ,("scenarist", "sce")
-           ,("scientific advisor", "sad")
-           ,("screenwriter", "aus")
-           ,("scribe", "scr")
-           ,("sculptor", "scl")
-           ,("second party", "spy")
-           ,("secretary", "sec")
-           ,("seller", "sll")
-           ,("set designer", "std")
-           ,("setting", "stg")
-           ,("signer", "sgn")
-           ,("singer", "sng")
-           ,("sound designer", "sds")
-           ,("speaker", "spk")
-           ,("sponsor", "spn")
-           ,("stage director", "sgd")
-           ,("stage manager", "stm")
-           ,("standards body", "stn")
-           ,("stereotyper", "str")
-           ,("storyteller", "stl")
-           ,("supporting host", "sht")
-           ,("surveyor", "srv")
-           ,("teacher", "tch")
-           ,("technical director", "tcd")
-           ,("television director", "tld")
-           ,("television producer", "tlp")
-           ,("thesis advisor", "ths")
-           ,("transcriber", "trc")
-           ,("translator", "trl")
-           ,("type designer", "tyd")
-           ,("typographer", "tyg")
-           ,("university place", "uvp")
-           ,("videographer", "vdg")
-           ,("witness", "wit")
-           ,("wood engraver", "wde")
-           ,("woodcutter", "wdc")
-           ,("writer of accompanying material", "wam")
-           ,("writer of added commentary", "wac")
-           ,("writer of added lyrics", "wal")
-           ,("writer of added text", "wat")
-           ]
-
-docTitle' :: Meta -> [Inline]
-docTitle' meta = fromMaybe [] $ go <$> lookupMeta "title" meta
+{-# LANGUAGE OverloadedStrings   #-}
+{-# LANGUAGE ScopedTypeVariables #-}
+{- |
+   Module      : Text.Pandoc.Writers.EPUB
+   Copyright   : Copyright (C) 2010-2024 John MacFarlane
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : John MacFarlane <jgm@berkeley.edu>
+   Stability   : alpha
+   Portability : portable
+
+Conversion of 'Pandoc' documents to EPUB.
+-}
+module Text.Pandoc.Writers.EPUB ( writeEPUB2, writeEPUB3 ) where
+import Codec.Archive.Zip (Entry, addEntryToArchive, eRelativePath, emptyArchive,
+                          fromArchive, fromEntry, toEntry)
+import Control.Applicative ( (<|>) )
+import Control.Monad (mplus, unless, when, zipWithM)
+import Control.Monad.Except (catchError, throwError)
+import Control.Monad.State.Strict (State, StateT, evalState, evalStateT, get,
+                                   gets, lift, modify)
+import qualified Data.ByteString.Lazy as B
+import qualified Data.ByteString.Lazy.Char8 as B8
+import Data.Char (isAlphaNum, isAscii, isDigit)
+import Data.List (isInfixOf, isPrefixOf)
+import qualified Data.Map as M
+import Data.Maybe (fromMaybe, isNothing, mapMaybe, isJust, catMaybes)
+import qualified Data.Set as Set
+import qualified Data.Text as T
+import Data.Text (Text)
+import qualified Data.Text.Lazy as TL
+import System.FilePath (takeExtension, takeFileName, makeRelative)
+import Text.HTML.TagSoup (Tag (TagOpen), fromAttrib, parseTags)
+import Text.Pandoc.Builder (fromList, setMeta)
+import Text.Pandoc.Writers.Shared (ensureValidXmlIdentifiers)
+import Data.Tree (Tree(..))
+import Text.Pandoc.Class (PandocMonad, report)
+import qualified Text.Pandoc.Class.PandocPure as P
+import Text.Pandoc.Data (readDataFile)
+import qualified Text.Pandoc.Class.PandocMonad as P
+import Data.Time
+import Text.Pandoc.Definition
+import Text.Pandoc.Error
+import Text.Pandoc.ImageSize
+import Text.Pandoc.Logging
+import Text.Pandoc.MIME (MimeType, extensionFromMimeType, getMimeType)
+import Text.Pandoc.URI (urlEncode)
+import Text.Pandoc.Options (EPUBVersion (..), HTMLMathMethod (..),
+                            ObfuscationMethod (NoObfuscation), WrapOption (..),
+                            WriterOptions (..))
+import Text.Pandoc.Shared (normalizeDate, renderTags',
+                           stringify, uniqueIdent, tshow)
+import qualified Text.Pandoc.UTF8 as UTF8
+import Text.Pandoc.UUID (getRandomUUID)
+import Text.Pandoc.Walk (walk, walkM)
+import Text.Pandoc.Writers.HTML (writeHtmlStringForEPUB)
+import Text.Printf (printf)
+import Text.Pandoc.XML.Light
+import Text.Pandoc.XML (escapeStringForXML)
+import Text.DocTemplates (FromContext(lookupContext), Context(..),
+                          ToContext(toVal), Val(..))
+import Text.Pandoc.Chunks (splitIntoChunks, Chunk(..), ChunkedDoc(..),
+                           SecInfo(..))
+
+-- A Chapter includes a list of blocks.
+newtype Chapter = Chapter [Block]
+  deriving (Show)
+
+data EPUBState = EPUBState {
+        stMediaPaths  :: [(FilePath, (FilePath, Maybe Entry))]
+      , stMediaNextId :: Int
+      , stEpubSubdir  :: FilePath
+      }
+
+type E m = StateT EPUBState m
+
+data EPUBMetadata = EPUBMetadata{
+    epubIdentifier          :: [Identifier]
+  , epubTitle               :: [Title]
+  , epubDate                :: [Date]
+  , epubLanguage            :: Text
+  , epubCreator             :: [Creator]
+  , epubContributor         :: [Creator]
+  , epubSubject             :: [Subject]
+  , epubDescription         :: Maybe Text
+  , epubType                :: Maybe Text
+  , epubFormat              :: Maybe Text
+  , epubPublisher           :: Maybe Text
+  , epubSource              :: Maybe Text
+  , epubRelation            :: Maybe Text
+  , epubCoverage            :: Maybe Text
+  , epubRights              :: Maybe Text
+  , epubBelongsToCollection :: Maybe Text
+  , epubGroupPosition       :: Maybe Text
+  , epubCoverImage          :: Maybe FilePath
+  , epubStylesheets         :: [FilePath]
+  , epubPageDirection       :: Maybe ProgressionDirection
+  , epubIbooksFields        :: [(Text, Text)]
+  , epubCalibreFields       :: [(Text, Text)]
+  , epubAccessModes         :: [Text] -- https://kb.daisy.org/publishing/docs/metadata/schema.org/accessMode.html
+  , epubAccessModeSufficient :: [Text] -- https://kb.daisy.org/publishing/docs/metadata/schema.org/accessModeSufficient.html
+  , epubAccessibilityFeatures :: [Text]  -- https://kb.daisy.org/publishing/docs/metadata/schema.org/accessibilityFeature.html
+  , epubAccessibilityHazards :: [Text] -- https://kb.daisy.org/publishing/docs/metadata/schema.org/accessibilityHazard.html
+  , epubAccessibilitySummary :: Maybe Text -- https://kb.daisy.org/publishing/docs/metadata/schema.org/accessibilitySummary.html
+  } deriving Show
+
+data Date = Date{
+    dateText  :: Text
+  , dateEvent :: Maybe Text
+  } deriving Show
+
+data Creator = Creator{
+    creatorText   :: Text
+  , creatorRole   :: Maybe Text
+  , creatorFileAs :: Maybe Text
+  } deriving Show
+
+data Identifier = Identifier{
+    identifierText   :: Text
+  , identifierScheme :: Maybe Text
+  } deriving Show
+
+data Title = Title{
+    titleText   :: Text
+  , titleFileAs :: Maybe Text
+  , titleType   :: Maybe Text
+  } deriving Show
+
+data ProgressionDirection = LTR | RTL deriving Show
+
+data Subject = Subject{
+    subjectText      :: Text
+  , subjectAuthority :: Maybe Text
+  , subjectTerm      :: Maybe Text
+  } deriving Show
+
+dcName :: Text -> QName
+dcName n = QName n Nothing (Just "dc")
+
+dcNode :: Node t => Text -> t -> Element
+dcNode = node . dcName
+
+opfName :: Text -> QName
+opfName n = QName n Nothing (Just "opf")
+
+toId :: FilePath -> Text
+toId = T.pack .
+       map (\x -> if isAlphaNum x || x == '-' || x == '_'
+                     then x
+                     else '_') . takeFileName
+
+removeNote :: Inline -> Inline
+removeNote (Note _) = Str ""
+removeNote x        = x
+
+toVal' :: Text -> Val T.Text
+toVal' = toVal
+
+mkEntry :: PandocMonad m => FilePath -> B.ByteString -> E m Entry
+mkEntry path content = do
+  epubSubdir <- gets stEpubSubdir
+  let addEpubSubdir :: Entry -> Entry
+      addEpubSubdir e = e{ eRelativePath =
+          (if null epubSubdir
+              then ""
+              else epubSubdir ++ "/") ++ eRelativePath e }
+  epochtime <- floor <$> lift P.getPOSIXTime
+  return $
+       (if path == "mimetype" || "META-INF" `isPrefixOf` path
+           then id
+           else addEpubSubdir) $ toEntry path epochtime content
+
+getEPUBMetadata :: PandocMonad m => WriterOptions -> Meta -> E m EPUBMetadata
+getEPUBMetadata opts meta = do
+  let md = metadataFromMeta opts meta
+  elts <- case writerEpubMetadata opts of
+            Nothing -> return []
+            Just t -> case parseXMLContents (TL.fromStrict t) of
+                          Left msg -> throwError $
+                            PandocXMLError "epub metadata" msg
+                          Right ns -> return (onlyElems ns)
+  let md' = foldr addMetadataFromXML md elts
+  let addIdentifier m =
+       if null (epubIdentifier m)
+          then do
+            randomId <- getRandomUUID
+            return $ m{ epubIdentifier = [Identifier (tshow randomId) Nothing] }
+          else return m
+  let addLanguage m =
+       if T.null (epubLanguage m)
+          then case lookupContext "lang" (writerVariables opts) of
+                     Just x  -> return m{ epubLanguage = x }
+                     Nothing -> do
+                       mLang <- lift $ P.lookupEnv "LANG"
+                       let localeLang =
+                             case mLang of
+                               Just lang ->
+                                 T.map (\c -> if c == '_' then '-' else c) $
+                                 T.takeWhile (/='.') lang
+                               Nothing -> "en-US"
+                       return m{ epubLanguage = localeLang }
+          else return m
+  let fixDate m =
+       if null (epubDate m)
+          then do
+            currentTime <- lift P.getTimestamp
+            return $ m{ epubDate = [ Date{
+                             dateText = showDateTimeISO8601 currentTime
+                           , dateEvent = Nothing } ] }
+          else return m
+  let addAuthor m =
+       if any (\c -> creatorRole c == Just "aut") $ epubCreator m
+          then return m
+          else do
+            let authors' = map stringify $ docAuthors meta
+            let toAuthor name = Creator{ creatorText = name
+                                       , creatorRole = Just "aut"
+                                       , creatorFileAs = Nothing }
+            return $ m{ epubCreator = map toAuthor authors' ++ epubCreator m }
+  addIdentifier md' >>= fixDate >>= addAuthor >>= addLanguage
+
+addMetadataFromXML :: Element -> EPUBMetadata -> EPUBMetadata
+addMetadataFromXML e@(Element (QName name _ (Just "dc")) attrs _ _) md
+  | name == "identifier" = md{ epubIdentifier =
+             Identifier{ identifierText = strContent e
+                       , identifierScheme = lookupAttr (opfName "scheme") attrs
+                       } : epubIdentifier md }
+  | name == "title" = md{ epubTitle =
+            Title{ titleText = strContent e
+                 , titleFileAs = getAttr "file-as"
+                 , titleType = getAttr "type"
+                 } : epubTitle md }
+  | name == "date" = md{ epubDate =
+             Date{ dateText = fromMaybe "" $ normalizeDate' $ strContent e
+                 , dateEvent = getAttr "event"
+                 } : epubDate md }
+  | name == "language" = md{ epubLanguage = strContent e }
+  | name == "creator" = md{ epubCreator =
+              Creator{ creatorText = strContent e
+                     , creatorRole = getAttr "role"
+                     , creatorFileAs = getAttr "file-as"
+                     } : epubCreator md }
+  | name == "contributor" = md{ epubContributor =
+              Creator  { creatorText = strContent e
+                       , creatorRole = getAttr "role"
+                       , creatorFileAs = getAttr "file-as"
+                       } : epubContributor md }
+  | name == "subject" = md{ epubSubject =
+              Subject  { subjectText = strContent e
+                       , subjectAuthority = getAttr "authority"
+                       , subjectTerm = getAttr "term"
+                       } : epubSubject md }
+  | name == "description" = md { epubDescription = Just $ strContent e }
+  | name == "type" = md { epubType = Just $ strContent e }
+  | name == "format" = md { epubFormat = Just $ strContent e }
+  | name == "publisher" = md { epubPublisher = Just $ strContent e }
+  | name == "source" = md { epubSource = Just $ strContent e }
+  | name == "relation" = md { epubRelation = Just $ strContent e }
+  | name == "coverage" = md { epubCoverage = Just $ strContent e }
+  | name == "rights" = md { epubRights = Just $ strContent e }
+  | name == "belongs-to-collection" = md { epubBelongsToCollection = Just $ strContent e }
+  | name == "group-position" = md { epubGroupPosition = Just $ strContent e }
+  | otherwise = md
+  where getAttr n = lookupAttr (opfName n) attrs
+addMetadataFromXML e@(Element (QName "meta" _ _) attrs _ _) md =
+  case getAttr "property" `mplus` getAttr "name" of
+       Just s | "ibooks:" `T.isPrefixOf` s ->
+                md{ epubIbooksFields = (T.drop 7 s, strContent e) :
+                       epubIbooksFields md }
+              | "calibre:" `T.isPrefixOf` s ->
+                   md{ epubCalibreFields =
+                         (T.drop 8 s, fromMaybe "" $ getAttr "content") :
+                          epubCalibreFields md }
+       _ -> md
+  where getAttr n = lookupAttr (unqual n) attrs
+addMetadataFromXML _ md = md
+
+metaValueToString :: MetaValue -> Text
+metaValueToString (MetaString s)    = s
+metaValueToString (MetaInlines ils) = stringify ils
+metaValueToString (MetaBlocks bs)   = stringify bs
+metaValueToString (MetaBool True)   = "true"
+metaValueToString (MetaBool False)  = "false"
+metaValueToString _                 = ""
+
+metaValueToPaths :: MetaValue -> [FilePath]
+metaValueToPaths (MetaList xs) = map (T.unpack . metaValueToString) xs
+metaValueToPaths x             = [T.unpack $ metaValueToString x]
+
+getList :: T.Text -> Meta -> (MetaValue -> a) -> [a]
+getList s meta handleMetaValue =
+  case lookupMeta s meta of
+       Just (MetaList xs) -> map handleMetaValue xs
+       Just mv            -> [handleMetaValue mv]
+       Nothing            -> []
+
+getIdentifier :: Meta -> [Identifier]
+getIdentifier meta = getList "identifier" meta handleMetaValue
+  where handleMetaValue (MetaMap m) =
+           Identifier{ identifierText = maybe "" metaValueToString
+                                        $ M.lookup "text" m
+                     , identifierScheme = metaValueToString <$>
+                                          M.lookup "scheme" m }
+        handleMetaValue mv = Identifier (metaValueToString mv) Nothing
+
+getTitle :: Meta -> [Title]
+getTitle meta = getList "title" meta handleMetaValue
+  where handleMetaValue (MetaMap m) =
+           Title{ titleText = maybe "" metaValueToString $ M.lookup "text" m
+                , titleFileAs = metaValueToString <$> M.lookup "file-as" m
+                , titleType = metaValueToString <$> M.lookup "type" m }
+        handleMetaValue mv = Title (metaValueToString mv) Nothing Nothing
+
+getCreator :: T.Text -> Meta -> [Creator]
+getCreator s meta = getList s meta handleMetaValue
+  where handleMetaValue (MetaMap m) =
+           Creator{ creatorText = maybe "" metaValueToString $ M.lookup "text" m
+                  , creatorFileAs = metaValueToString <$> M.lookup "file-as" m
+                  , creatorRole = metaValueToString <$> M.lookup "role" m }
+        handleMetaValue mv = Creator (metaValueToString mv) Nothing Nothing
+
+getDate :: T.Text -> Meta -> [Date]
+getDate s meta = getList s meta handleMetaValue
+  where handleMetaValue (MetaMap m) =
+           Date{ dateText = fromMaybe "" $
+                   M.lookup "text" m >>= normalizeDate' . metaValueToString
+               , dateEvent = metaValueToString <$> M.lookup "event" m }
+        handleMetaValue mv = Date { dateText = fromMaybe "" $ normalizeDate' $ metaValueToString mv
+                                  , dateEvent = Nothing }
+
+getSubject :: T.Text -> Meta -> [Subject]
+getSubject s meta = getList s meta handleMetaValue
+  where handleMetaValue (MetaMap m) =
+           Subject{ subjectText = maybe "" metaValueToString $ M.lookup "text" m
+                  , subjectAuthority = metaValueToString <$> M.lookup "authority" m
+                  , subjectTerm = metaValueToString <$> M.lookup "term" m }
+        handleMetaValue mv = Subject (metaValueToString mv) Nothing Nothing
+
+metadataFromMeta :: WriterOptions -> Meta -> EPUBMetadata
+metadataFromMeta opts meta = EPUBMetadata{
+      epubIdentifier           = identifiers
+    , epubTitle                = titles
+    , epubDate                 = date
+    , epubLanguage             = language
+    , epubCreator              = creators
+    , epubContributor          = contributors
+    , epubSubject              = subjects
+    , epubDescription          = description
+    , epubType                 = epubtype
+    , epubFormat               = format
+    , epubPublisher            = publisher
+    , epubSource               = source
+    , epubRelation             = relation
+    , epubCoverage             = coverage
+    , epubRights               = rights
+    , epubBelongsToCollection  = belongsToCollection
+    , epubGroupPosition        = groupPosition
+    , epubCoverImage           = coverImage
+    , epubStylesheets          = stylesheets
+    , epubPageDirection        = pageDirection
+    , epubIbooksFields         = ibooksFields
+    , epubCalibreFields        = calibreFields
+    , epubAccessModes          = accessModes
+    , epubAccessModeSufficient = accessModeSufficient
+    , epubAccessibilityFeatures = accessibilityFeatures
+    , epubAccessibilityHazards = accessibilityHazards
+    , epubAccessibilitySummary = accessibilitySummary
+    }
+  where identifiers = getIdentifier meta
+        titles = getTitle meta
+        date = getDate "date" meta
+        language = maybe "" metaValueToString $
+           lookupMeta "language" meta `mplus` lookupMeta "lang" meta
+        creators = getCreator "creator" meta
+        contributors = getCreator "contributor" meta
+        subjects = getSubject "subject" meta
+        description = metaValueToString <$> lookupMeta "description" meta
+        epubtype = metaValueToString <$> lookupMeta "type" meta
+        format = metaValueToString <$> lookupMeta "format" meta
+        publisher = metaValueToString <$> lookupMeta "publisher" meta
+        source = metaValueToString <$> lookupMeta "source" meta
+        relation = metaValueToString <$> lookupMeta "relation" meta
+        coverage = metaValueToString <$> lookupMeta "coverage" meta
+        rights = metaValueToString <$> lookupMeta "rights" meta
+        belongsToCollection = metaValueToString <$> lookupMeta "belongs-to-collection" meta
+        groupPosition = metaValueToString <$> lookupMeta "group-position" meta
+        coverImage = T.unpack <$>
+            lookupContext "epub-cover-image" (writerVariables opts)
+            `mplus` (metaValueToString <$> lookupMeta "cover-image" meta)
+        mCss = lookupMeta "css" meta <|> lookupMeta "stylesheet" meta
+        stylesheets = maybe [] metaValueToPaths mCss ++
+                      case lookupContext "css" (writerVariables opts) of
+                         Just xs -> map T.unpack xs
+                         Nothing ->
+                           case lookupContext "css" (writerVariables opts) of
+                             Just x  -> [T.unpack x]
+                             Nothing -> []
+        pageDirection = case T.toLower . metaValueToString <$>
+                             lookupMeta "page-progression-direction" meta of
+                              Just "ltr" -> Just LTR
+                              Just "rtl" -> Just RTL
+                              _          -> Nothing
+        ibooksFields = case lookupMeta "ibooks" meta of
+                            Just (MetaMap mp)
+                               -> M.toList $ M.map metaValueToString mp
+                            _  -> []
+        calibreFields = case lookupMeta "calibre" meta of
+                            Just (MetaMap mp)
+                               -> M.toList $ M.map metaValueToString mp
+                            _  -> []
+        accessModes = case lookupMeta "accessModes" meta of
+                         Just (MetaList xs) -> map metaValueToString xs
+                         _ -> ["textual"]
+        accessModeSufficient = case lookupMeta "accessModeSufficient" meta of
+                         Just (MetaList xs) -> map metaValueToString xs
+                         _ -> ["textual"]
+        accessibilityFeatures =
+                      case lookupMeta "accessibilityFeatures" meta of
+                         Just (MetaList xs) -> map metaValueToString xs
+                         _ -> ["alternativeText", "readingOrder",
+                               "structuralNavigation", "tableOfContents"]
+        accessibilityHazards =
+                       case lookupMeta "accessibilityHazards" meta of
+                         Just (MetaList xs) -> map metaValueToString xs
+                         _ -> ["none"]
+        accessibilitySummary = metaValueToString <$> lookupMeta "accessibilitySummary" meta
+
+-- | Produce an EPUB2 file from a Pandoc document.
+writeEPUB2 :: PandocMonad m
+          => WriterOptions  -- ^ Writer options
+          -> Pandoc         -- ^ Document to convert
+          -> m B.ByteString
+writeEPUB2 = writeEPUB EPUB2
+
+-- | Produce an EPUB3 file from a Pandoc document.
+writeEPUB3 :: PandocMonad m
+          => WriterOptions  -- ^ Writer options
+          -> Pandoc         -- ^ Document to convert
+          -> m B.ByteString
+writeEPUB3 = writeEPUB EPUB3
+
+-- | Produce an EPUB file from a Pandoc document.
+writeEPUB :: PandocMonad m
+          => EPUBVersion
+          -> WriterOptions  -- ^ Writer options
+          -> Pandoc         -- ^ Document to convert
+          -> m B.ByteString
+writeEPUB epubVersion opts doc = do
+  let epubSubdir = writerEpubSubdirectory opts
+  -- sanity check on epubSubdir
+  unless (T.all (\c -> isAscii c && isAlphaNum c) epubSubdir) $
+    throwError $ PandocEpubSubdirectoryError epubSubdir
+  let initState = EPUBState { stMediaPaths = []
+                            , stMediaNextId = 0
+                            , stEpubSubdir = T.unpack epubSubdir }
+  evalStateT (pandocToEPUB epubVersion opts doc) initState
+
+pandocToEPUB :: PandocMonad m
+             => EPUBVersion
+             -> WriterOptions
+             -> Pandoc
+             -> E m B.ByteString
+pandocToEPUB version opts doc = do
+  let doc' = ensureValidXmlIdentifiers doc
+  -- handle pictures
+  Pandoc meta blocks <- walkM (transformInline version opts) doc' >>=
+                        walkM (transformBlock version)
+  picEntries <- mapMaybe (snd . snd) <$> gets stMediaPaths
+
+  epubSubdir <- gets stEpubSubdir
+  let epub3 = version == EPUB3
+
+  let writeHtml o = fmap (UTF8.fromTextLazy . TL.fromStrict) .
+                      writeHtmlStringForEPUB version o
+  metadata <- getEPUBMetadata opts meta
+
+  -- retrieve title of document
+  let plainTitle :: Text
+      plainTitle = case docTitle' meta of
+                        [] -> case epubTitle metadata of
+                                   []    -> "UNTITLED"
+                                   (x:_) -> titleText x
+                        x  -> stringify x
+
+  -- stylesheet
+  stylesheets <- case epubStylesheets metadata of
+                      [] -> (\x -> [B.fromChunks [x]]) <$>
+                               readDataFile "epub.css"
+                      fs -> mapM P.readFileLazy fs
+  stylesheetEntries <- zipWithM
+        (\bs n -> mkEntry ("styles/stylesheet" ++ show n ++ ".css") bs)
+        stylesheets [(1 :: Int)..]
+
+  -- writer variables
+  let vars :: Context Text
+      vars = Context $
+               M.delete "css" .
+               M.insert "epub3"
+                 (toVal' $ if epub3 then "true" else "false") .
+               M.insert "lang" (toVal' $ epubLanguage metadata)
+             $ unContext $ writerVariables opts
+
+  -- If True create paths relative to parent folder
+  let cssvars :: Bool -> Context Text
+      cssvars useprefix = Context $ M.insert "css"
+                           (ListVal $ map
+                             (\e -> toVal' $
+                                (if useprefix then "../" else "") <>
+                                T.pack
+                                 (makeRelative epubSubdir (eRelativePath e)))
+                             stylesheetEntries)
+                             mempty
+
+  -- Add additional options for the writer
+  let opts' :: WriterOptions
+      opts' = opts{ writerEmailObfuscation = NoObfuscation
+                  , writerSectionDivs = True
+                  , writerVariables = vars
+                  , writerWrapText = WrapAuto }
+
+  -- cover page
+  (cpgEntry, cpicEntry, mbCoverImageName) <-
+    createCoverPage meta metadata opts' vars cssvars writeHtml plainTitle
+
+  -- title page
+  tpContent <- lift $ writeHtml opts'{
+                                  writerVariables =
+                                      Context (M.fromList [
+                                        ("titlepage", toVal' "true"),
+                                        ("body-type",  toVal' "frontmatter"),
+                                        ("pagetitle", toVal $
+                                            escapeStringForXML plainTitle)])
+                                      <> cssvars True <> vars }
+                               (Pandoc meta [])
+  tpEntry <- mkEntry "text/title_page.xhtml" tpContent
+
+
+  -- handle fonts
+  let matchingGlob f = do
+        xs <- lift $ P.glob f
+        when (null xs) $
+          report $ CouldNotFetchResource (T.pack f) "glob did not match any font files"
+        return xs
+
+  let mkFontEntry :: PandocMonad m => FilePath -> StateT EPUBState m Entry
+      mkFontEntry f = mkEntry ("fonts/" ++ takeFileName f) =<<
+                        lift (P.readFileLazy f)
+  fontFiles <- concat <$> mapM matchingGlob (writerEpubFonts opts')
+  fontEntries <- mapM mkFontEntry fontFiles
+
+  -- body pages
+
+  -- add level 1 header to beginning if none there
+  let blocks' = addIdentifiers opts
+                $ case blocks of
+                    (Div _
+                      (Header{}:_) : _) -> blocks
+                    (Header 1 _ _ : _)  -> blocks
+                    _                   -> Header 1 ("",["unnumbered"],[])
+                                               (docTitle' meta) : blocks
+
+  -- create the chapters
+  let chunkedDoc = splitIntoChunks "ch%n.xhtml"
+                     (writerNumberSections opts)
+                     Nothing
+                     (writerSplitLevel opts)
+                     (Pandoc meta blocks')
+
+
+  -- Create the chapter entries from the chapters.
+  -- Also requires access to the extended writer options and context
+  -- as well as the css Context and html writer
+  chapterEntries <- createChapterEntries opts' vars cssvars writeHtml
+                      (chunkedChunks chunkedDoc)
+
+
+
+  -- contents.opf
+
+  -- set page progression direction attribution
+  let progressionDirection :: [(Text, Text)]
+      progressionDirection = case epubPageDirection metadata of
+                                  Just LTR | epub3 ->
+                                    [("page-progression-direction", "ltr")]
+                                  Just RTL | epub3 ->
+                                    [("page-progression-direction", "rtl")]
+                                  _  -> []
+
+  -- incredibly inefficient (TODO):
+  let containsMathML ent = epub3 &&
+                           "<math" `isInfixOf`
+        B8.unpack (fromEntry ent)
+  let containsSVG ent    = epub3 &&
+                           "<svg" `isInfixOf`
+        B8.unpack (fromEntry ent)
+  let props ent = ["mathml" | containsMathML ent] ++ ["svg" | containsSVG ent]
+
+  let chapterNode ent = unode "item" !
+                           ([("id", toId $ makeRelative epubSubdir
+                                         $ eRelativePath ent),
+                             ("href", T.pack $ makeRelative epubSubdir
+                                      $ eRelativePath ent),
+                             ("media-type", "application/xhtml+xml")]
+                            ++ case props ent of
+                                    [] -> []
+                                    xs -> [("properties", T.unwords xs)])
+                        $ ()
+
+  let chapterRefNode ent = unode "itemref" !
+                             [("idref", toId $ makeRelative epubSubdir
+                                             $ eRelativePath ent)] $ ()
+  let pictureNode ent = unode "item" !
+                           [("id", toId $ makeRelative epubSubdir
+                                        $ eRelativePath ent),
+                            ("href", T.pack $ makeRelative epubSubdir
+                                     $ eRelativePath ent),
+                            ("media-type",
+                               fromMaybe "application/octet-stream"
+                               $ mediaTypeOf $ eRelativePath ent)] $ ()
+  let fontNode ent = unode "item" !
+                           [("id", toId $ makeRelative epubSubdir
+                                        $ eRelativePath ent),
+                            ("href", T.pack $ makeRelative epubSubdir
+                                     $ eRelativePath ent),
+                            ("media-type", fromMaybe "" $
+                                  getMimeType $ eRelativePath ent)] $ ()
+
+  -- The tocTitle is either the normal title or a specially configured title.
+  let tocTitle = maybe plainTitle
+                   metaValueToString $ lookupMeta "toc-title" meta
+  currentTime <- lift P.getTimestamp
+
+  -- Construct the contentsData
+  let contentsData = UTF8.fromTextLazy $ TL.fromStrict $ ppTopElement $
+        unode "package" !
+          ([("version", case version of
+                             EPUB2 -> "2.0"
+                             EPUB3 -> "3.0")
+           ,("xmlns","http://www.idpf.org/2007/opf")] ++
+           [("xml:lang", epubLanguage metadata) | version == EPUB3] ++
+           [("unique-identifier","epub-id-1")] ++
+           [("prefix","ibooks: http://vocabulary.itunes.apple.com/rdf/ibooks/vocabulary-extensions-1.0/") | version == EPUB3]) $
+          [ metadataElement version metadata mbCoverImageName currentTime
+          , unode "manifest" $
+             [ unode "item" ! [("id","ncx"), ("href","toc.ncx")
+                              ,("media-type","application/x-dtbncx+xml")] $ ()
+             , unode "item" ! ([("id","nav")
+                               ,("href","nav.xhtml")
+                               ,("media-type","application/xhtml+xml")] ++
+                               [("properties","nav") | epub3 ]) $ ()
+             ] ++
+             [ unode "item" ! [("id","stylesheet" <> tshow n)
+                              , ("href", T.pack fp)
+                              ,("media-type","text/css")] $ () |
+                             (n :: Int, fp) <- zip [1..] (map
+                               (makeRelative epubSubdir . eRelativePath)
+                               stylesheetEntries) ] ++
+             map chapterNode (cpgEntry ++
+                               [tpEntry | writerEpubTitlePage opts] ++
+                               chapterEntries) ++
+             (case cpicEntry of
+                    []    -> []
+                    (x:_) -> [add_attrs
+                              [Attr (unqual "properties") "cover-image" | epub3]
+                              (pictureNode x)]) ++
+             map pictureNode picEntries ++
+             map fontNode fontEntries
+          , unode "spine" ! (
+             ("toc","ncx") : progressionDirection) $
+              case epubCoverImage metadata of
+                    Nothing -> []
+                    Just _ -> [ unode "itemref" !
+                                [("idref", "cover_xhtml")] $ () ]
+              ++ ([unode "itemref" ! [("idref", "title_page_xhtml")
+                                     ,("linear",
+                                         case lookupMeta "title" meta of
+                                               Just _  -> "yes"
+                                               Nothing -> "no")] $ ()
+                     | writerEpubTitlePage opts] ++
+                  [unode "itemref" ! [("idref", "nav")] $ ()
+                         | writerTableOfContents opts ] ++
+                  map chapterRefNode chapterEntries)
+          , unode "guide" $
+             (unode "reference" !
+                 [("type","toc"),("title", tocTitle),
+                  ("href","nav.xhtml")] $ ()
+             ) :
+             [ unode "reference" !
+                   [("type","cover")
+                   ,("title","Cover")
+                   ,("href","text/cover.xhtml")] $ ()
+               | isJust (epubCoverImage metadata)
+             ]
+          ]
+  -- Content should be stored in content.opf
+  contentsEntry <- mkEntry "content.opf" contentsData
+
+  -- toc.ncx
+  -- Create the tocEntry from the metadata together with the sections and title.
+  tocEntry <- createTocEntry opts' meta metadata plainTitle
+                (chunkedTOC chunkedDoc)
+
+  -- Create the navEntry using the metadata, all of the various writer options,
+  -- the CSS and HTML helpers, the document and toc title as well as the epub version and all of the sections
+  navEntry <- createNavEntry opts' meta metadata vars cssvars
+                writeHtml tocTitle version (chunkedTOC chunkedDoc)
+
+  -- mimetype
+  mimetypeEntry <- mkEntry "mimetype" $
+                        UTF8.fromStringLazy "application/epub+zip"
+
+  -- container.xml
+  let containerData = B.fromStrict $ UTF8.fromText $ ppTopElement $
+       unode "container" ! [("version","1.0")
+              ,("xmlns","urn:oasis:names:tc:opendocument:xmlns:container")] $
+         unode "rootfiles" $
+           unode "rootfile" ! [("full-path",
+                    (if null epubSubdir
+                        then ""
+                        else T.pack epubSubdir <> "/") <> "content.opf")
+               ,("media-type","application/oebps-package+xml")] $ ()
+  containerEntry <- mkEntry "META-INF/container.xml" containerData
+
+  -- com.apple.ibooks.display-options.xml
+  let apple = B.fromStrict $ UTF8.fromText $ ppTopElement $
+        unode "display_options" $
+          unode "platform" ! [("name","*")] $
+            unode "option" ! [("name","specified-fonts")] $ ("true" :: Text)
+  appleEntry <- mkEntry "META-INF/com.apple.ibooks.display-options.xml" apple
+
+  -- construct archive
+  let archive = foldr addEntryToArchive emptyArchive $
+                 [mimetypeEntry, containerEntry, appleEntry,
+                  contentsEntry, tocEntry, navEntry] ++
+                  [tpEntry | writerEpubTitlePage opts] ++
+                  stylesheetEntries ++ picEntries ++ cpicEntry ++
+                  cpgEntry ++ chapterEntries ++ fontEntries
+  return $ fromArchive archive
+
+-- | Function used during conversion from pandoc to EPUB to create the cover page.
+-- The first Entry list is for the cover while the second one is for the cover image.
+-- If no cover images are specified, empty lists will be returned.
+-- The third value of the returned tuple is the cover image name.
+createCoverPage :: PandocMonad m =>
+                   Meta
+                   -> EPUBMetadata
+                   -> WriterOptions
+                   -> Context Text
+                   -> (Bool -> Context Text)
+                   -> (WriterOptions -> Pandoc -> m B8.ByteString)
+                   -> Text
+                   -> StateT EPUBState m ([Entry], [Entry], Maybe FilePath)
+createCoverPage meta metadata opts' vars cssvars writeHtml plainTitle =
+    case epubCoverImage metadata of
+        Nothing   -> return ([],[], Nothing)
+        Just img  -> do
+          let fp = takeFileName img
+          -- retrieve cover image file
+          coverImageName <- getMediaNextNewName (takeExtension fp) -- see #4206
+          -- image dimensions
+          imgContent <- lift $ P.readFileLazy img
+          (coverImageWidth, coverImageHeight) <-
+                case imageSize opts' (B.toStrict imgContent) of
+                  Right sz  -> return $ sizeInPixels sz
+                  Left err' -> (0, 0) <$ report
+                    (CouldNotDetermineImageSize (T.pack img) err')
+          -- write the HTML. Use the cssvars, vars and additional writer options.
+          cpContent <- lift $ writeHtml
+                opts'{ writerVariables =
+                      Context (M.fromList [
+                        ("coverpage", toVal' "true"),
+                        ("pagetitle", toVal $
+                          escapeStringForXML plainTitle),
+                        ("cover-image",
+                          toVal' $ T.pack coverImageName),
+                        ("cover-image-width", toVal' $
+                          tshow coverImageWidth),
+                        ("cover-image-height", toVal' $
+                          tshow coverImageHeight)]) <>
+                        cssvars True <> vars }
+                (Pandoc meta [])
+
+          coverEntry <- mkEntry "text/cover.xhtml" cpContent
+          coverImageEntry <- mkEntry ("media/" ++ coverImageName)
+                                imgContent
+
+          return ( [ coverEntry ], [ coverImageEntry ], Just coverImageName )
+
+-- | Converts the given chapters to entries using the writeHtml function
+-- and the various provided options
+createChapterEntries :: PandocMonad m =>
+                            WriterOptions
+                            -> Context Text
+                            -> (Bool -> Context Text)
+                            -> (WriterOptions -> Pandoc -> StateT EPUBState m B8.ByteString)
+                            -> [Chunk]
+                            -> StateT EPUBState m [Entry]
+createChapterEntries opts' vars cssvars writeHtml chapters = do
+  -- Create an entry from the chapter with the provided number.
+  -- chapToEntry :: Int -> Chapter -> StateT EPUBState m Entry
+  let chapToEntry num chunk =
+        mkEntry ("text/" ++ chunkPath chunk) =<<
+        -- Combine all provided options
+        writeHtml opts'{ writerVariables =
+                            Context (M.fromList
+                                     [("body-type", toVal' bodyType),
+                                      ("pagetitle", toVal' $
+                                           showChapter num)])
+                            <> cssvars True <> vars } pdoc
+         where bs = chunkContents chunk
+               meta' = setMeta "title" (fromList
+                         (walk removeNote
+                          (chunkHeading chunk))) nullMeta
+               (pdoc, bodyType) =
+                 case bs of
+                     (Div (_,"section":_,kvs) _ : _) ->
+                       -- remove notes or we get doubled footnotes
+                       (Pandoc meta' bs,
+                        -- Check if the chapters belongs to the frontmatter,
+                        -- backmatter of bodymatter defaulting to the body
+                        case lookup "epub:type" kvs of
+                             Nothing -> "bodymatter"
+                             Just x
+                               | x `elem` frontMatterTypes -> "frontmatter"
+                               | x `elem` backMatterTypes  -> "backmatter"
+                               | otherwise                 -> "bodymatter")
+                     _                   -> (Pandoc meta' bs, "bodymatter")
+               frontMatterTypes = ["prologue", "abstract", "acknowledgments",
+                                   "copyright-page", "dedication",
+                                   "credits", "keywords", "imprint",
+                                   "contributors", "other-credits",
+                                   "errata", "revision-history",
+                                   "titlepage", "halftitlepage", "seriespage",
+                                   "foreword", "preface", "frontispiece",
+                                   "seriespage", "titlepage"]
+               backMatterTypes = ["appendix", "colophon", "bibliography",
+                                  "index"]
+
+  zipWithM chapToEntry [1..] chapters
+
+createTocEntry :: PandocMonad m =>
+                  WriterOptions
+               -> Meta
+               -> EPUBMetadata
+               -> Text
+               -> Tree SecInfo
+               -> StateT EPUBState m Entry
+createTocEntry opts meta metadata plainTitle (Node _ secs) = do
+  let mkNavPoint :: Tree SecInfo -> State Int (Maybe Element)
+      mkNavPoint (Node secinfo subsecs)
+        | secLevel secinfo > writerTOCDepth opts = return Nothing
+        | otherwise = do
+          n <- get
+          modify (+ 1)
+          subs <- catMaybes <$> mapM mkNavPoint subsecs
+          let secnum' = case secNumber secinfo of
+                          Just t -> t <> " "
+                          Nothing -> ""
+          let title' = secnum' <> stringify (secTitle secinfo)
+          return $ Just $ unode "navPoint" !
+                   [("id", "navPoint-" <> tshow n)] $
+                      [ unode "navLabel" $ unode "text" title'
+                      , unode "content" !
+                          [("src", "text/" <> secPath secinfo)] $ ()
+                      ] ++ subs
+
+  let tpNode = unode "navPoint" !  [("id", "navPoint-0")] $
+                  [ unode "navLabel" $ unode "text"
+                     (stringify $ docTitle' meta)
+                  , unode "content" ! [("src", "text/title_page.xhtml")]
+                  $ () ]
+
+  let navMap = evalState (catMaybes <$> mapM mkNavPoint secs) 1
+
+  uuid <- case epubIdentifier metadata of
+          (x:_) -> return $ identifierText x  -- use first identifier as UUID
+          []    -> throwError $ PandocShouldNeverHappenError "epubIdentifier is null"  -- shouldn't happen
+  let tocData = B.fromStrict $ UTF8.fromText $ ppTopElement $
+        unode "ncx" ! [("version","2005-1")
+                       ,("xmlns","http://www.daisy.org/z3986/2005/ncx/")] $
+          [ unode "head" $
+             [ unode "meta" ! [("name","dtb:uid")
+                              ,("content", uuid)] $ ()
+             , unode "meta" ! [("name","dtb:depth")
+                              ,("content", "1")] $ ()
+             , unode "meta" ! [("name","dtb:totalPageCount")
+                              ,("content", "0")] $ ()
+             , unode "meta" ! [("name","dtb:maxPageNumber")
+                              ,("content", "0")] $ ()
+             ] ++ case epubCoverImage metadata of
+                        Nothing  -> []
+                        Just img -> [unode "meta" ! [("name","cover"),
+                                            ("content", toId img)] $ ()]
+          , unode "docTitle" $ unode "text" plainTitle
+          , unode "navMap" $ [tpNode | writerEpubTitlePage opts] ++ navMap
+          ]
+  mkEntry "toc.ncx" tocData
+
+
+createNavEntry  :: PandocMonad m
+                => WriterOptions
+                -> Meta
+                -> EPUBMetadata
+                -> Context Text
+                -> (Bool -> Context Text)
+                -> (WriterOptions -> Pandoc -> m B8.ByteString)
+                -> Text
+                -> EPUBVersion
+                -> Tree SecInfo
+                -> StateT EPUBState m Entry
+createNavEntry opts meta metadata
+               vars cssvars writeHtml tocTitle version (Node _ secs) = do
+  let mkItem :: Tree SecInfo -> State Int (Maybe Element)
+      mkItem (Node secinfo subsecs)
+        | secLevel secinfo > writerTOCDepth opts = return Nothing
+        | otherwise = do
+          n <- get
+          modify (+ 1)
+          subs <- catMaybes <$> mapM mkItem subsecs
+          let secnum' = case secNumber secinfo of
+                          Just num -> [Span ("", ["section-header-number"], [])
+                                       [Str num] , Str "\160"]
+                          Nothing -> []
+          let title' = secnum' <> secTitle secinfo
+          -- can't have <a> elements inside generated links...
+          let clean (Link _ ils _) = Span ("", [], []) ils
+              clean (Note _)       = Str ""
+              clean x              = x
+          let titRendered = case P.runPure
+                                  (writeHtmlStringForEPUB version
+                                    opts{ writerTemplate = Nothing }
+                                    (Pandoc nullMeta
+                                      [Plain $ walk clean title'])) of
+                                  Left _  -> stringify title'
+                                  Right x -> x
+          let titElements = either (const []) id $
+                                  parseXMLContents (TL.fromStrict titRendered)
+
+          return $ Just $ unode "li" !
+                   [("id", "toc-li-" <> tshow n)] $
+                      (unode "a" !
+                        [("href", "text/" <> secPath secinfo)]
+                        $ titElements)
+                       : case subs of
+                           [] -> []
+                           (_:_) -> [unode "ol" ! [("class","toc")] $ subs]
+
+  let navtag = if version == EPUB3 then "nav" else "div"
+  let tocBlocks = evalState (catMaybes <$> mapM mkItem secs) 1
+  let navBlocks = [RawBlock (Format "html")
+                  $ showElement $ -- prettyprinting introduces bad spaces
+                   unode navtag ! ([("epub:type","toc") | version == EPUB3] ++
+                                   [("role","doc-toc") | version == EPUB3] ++
+                                   [("id","toc")]) $
+                    [ unode "h1" ! [("id","toc-title")] $ tocTitle
+                    , unode "ol" ! [("class","toc")] $ tocBlocks ]]
+  let landmarkItems = if version == EPUB3
+                         then [ unode "li"
+                                [ unode "a" ! [("href",
+                                                  "text/title_page.xhtml")
+                                               ,("epub:type", "titlepage")] $
+                                  ("Title Page" :: Text) ] |
+                                  writerEpubTitlePage opts ] ++
+                              [ unode "li"
+                                [ unode "a" ! [("href", "text/cover.xhtml")
+                                              ,("epub:type", "cover")] $
+                                  ("Cover" :: Text)] |
+                                  isJust (epubCoverImage metadata)
+                              ] ++
+                              [ unode "li"
+                                [ unode "a" ! [("href", "#toc")
+                                              ,("epub:type", "toc")] $
+                                    ("Table of Contents" :: Text)
+                                ] | writerTableOfContents opts
+                              ]
+                         else []
+  let landmarks = [RawBlock (Format "html") $ ppElement $
+                    unode "nav" ! [("epub:type","landmarks")
+                                  ,("id","landmarks")
+                                  ,("hidden","hidden")] $
+                    [ unode "ol" landmarkItems ]
+                  | not (null landmarkItems)]
+  navData <- lift $ writeHtml opts{ writerVariables =
+                     Context (M.fromList [("navpage", toVal' "true")
+                                         ,("body-type",  toVal' "frontmatter")
+                                         ])
+                     <> cssvars False <> vars }
+            (Pandoc (setMeta "title"
+                     (walk removeNote $ fromList $ docTitle' meta) nullMeta)
+               (navBlocks ++ landmarks))
+  -- Return
+  mkEntry "nav.xhtml" navData
+
+metadataElement :: EPUBVersion -> EPUBMetadata -> Maybe FilePath -> UTCTime
+                -> Element
+metadataElement version md mbCoverImage currentTime =
+  unode "metadata" ! [("xmlns:dc","http://purl.org/dc/elements/1.1/")
+                     ,("xmlns:opf","http://www.idpf.org/2007/opf")] $ mdNodes
+  where mdNodes = identifierNodes ++ titleNodes ++ dateNodes
+                  ++ languageNodes ++ ibooksNodes ++ calibreNodes
+                  ++ creatorNodes ++ contributorNodes ++ subjectNodes
+                  ++ descriptionNodes ++ typeNodes ++ formatNodes
+                  ++ publisherNodes ++ sourceNodes ++ relationNodes
+                  ++ coverageNodes ++ rightsNodes ++ coverImageNodes
+                  ++ modifiedNodes ++ belongsToCollectionNodes
+                  ++ case version of
+                       EPUB2 -> []
+                       EPUB3 -> accessModeNodes ++
+                                accessModeSufficientNodes ++
+                                accessibilityFeatureNodes ++
+                                accessibilityHazardNodes ++
+                                accessibilitySummaryNodes
+        metaprop = if version == EPUB2 then "name" else "property"
+        withIds base f = concat . zipWith f (map (\x -> base <>
+                                                        T.cons '-' (tshow x))
+                         ([1..] :: [Int]))
+        identifierNodes = withIds "epub-id" toIdentifierNode $
+                          epubIdentifier md
+        titleNodes = withIds "epub-title" toTitleNode $ epubTitle md
+        dateNodes = if version == EPUB2
+                       then withIds "epub-date" toDateNode $ epubDate md
+                       else -- epub3 allows only one dc:date
+                            -- http://www.idpf.org/epub/30/spec/epub30-publications.html#sec-opf-dcdate
+                            case epubDate md of
+                                 [] -> []
+                                 (x:_) -> [dcNode "date" ! [("id","epub-date")]
+                                            $ dateText x]
+        ibooksNodes = map ibooksNode (epubIbooksFields md)
+        ibooksNode (k, v) = unode "meta" ! [(metaprop, "ibooks:" <> k)] $ v
+        calibreNodes = map calibreNode (epubCalibreFields md)
+        calibreNode (k, v) = unode "meta" ! [(metaprop, "calibre:" <> k),
+                                             ("content", v)] $ ()
+        languageNodes = [dcTag "language" $ epubLanguage md]
+        creatorNodes = withIds "epub-creator" (toCreatorNode "creator") $
+                       epubCreator md
+        contributorNodes = withIds "epub-contributor"
+                           (toCreatorNode "contributor") $ epubContributor md
+        subjectNodes = withIds "subject" toSubjectNode $ epubSubject md
+        descriptionNodes = maybe [] (dcTag' "description") $ epubDescription md
+        typeNodes = maybe [] (dcTag' "type") $ epubType md
+        formatNodes = maybe [] (dcTag' "format") $ epubFormat md
+        publisherNodes = maybe [] (dcTag' "publisher") $ epubPublisher md
+        sourceNodes = maybe [] (dcTag' "source") $ epubSource md
+        relationNodes = maybe [] (dcTag' "relation") $ epubRelation md
+        coverageNodes = maybe [] (dcTag' "coverage") $ epubCoverage md
+        rightsNodes = maybe [] (dcTag' "rights") $ epubRights md
+        coverImageNodes = maybe []
+            (\img -> [unode "meta" !  [("name","cover"),
+                                       ("content",toId img)] $ ()])
+            mbCoverImage
+        modifiedNodes = [ unode "meta" ! [(metaprop, "dcterms:modified")] $
+               showDateTimeISO8601 currentTime | version == EPUB3 ]
+        belongsToCollectionNodes =
+            maybe []
+                (\belongsToCollection -> (unode "meta" !  [(metaprop, "belongs-to-collection"), ("id", "epub-collection-1")] $ belongsToCollection )
+                :
+                [unode "meta" !  [("refines", "#epub-collection-1"), (metaprop, "collection-type")] $ ("series" :: Text) ])
+                (epubBelongsToCollection md)++
+            maybe []
+                (\groupPosition -> [unode "meta" !  [("refines", "#epub-collection-1"), (metaprop, "group-position")] $ groupPosition ])
+                (epubGroupPosition md)
+        schemanode k v = unode "meta" ! [(metaprop, "schema:" <> k)] $ v
+        accessModeNodes = map (schemanode "accessMode") (epubAccessModes md)
+        accessModeSufficientNodes = map (schemanode "accessModeSufficient") (epubAccessModeSufficient md)
+        accessibilityFeatureNodes = map (schemanode "accessibilityFeature")
+            (epubAccessibilityFeatures md)
+        accessibilityHazardNodes = map (schemanode "accessibilityHazard")
+            (epubAccessibilityHazards md)
+        accessibilitySummaryNodes = maybe [] (\summary -> [schemanode "accessibilitySummary" summary]) $ epubAccessibilitySummary md
+
+        dcTag n s = unode ("dc:" <> n) s
+        dcTag' n s = [dcTag n s]
+        toIdentifierNode id' (Identifier txt scheme)
+          | version == EPUB2 = [dcNode "identifier" !
+              (("id",id') : maybe [] (\x -> [("opf:scheme", x)]) scheme) $
+              txt]
+          | otherwise = (dcNode "identifier" ! [("id",id')] $ txt) :
+              maybe [] ((\x -> [unode "meta" !
+                                [ ("refines","#" <> id')
+                                , (metaprop,"identifier-type")
+                                , ("scheme","onix:codelist5")
+                                ]
+                                $ x
+                               ])
+                        . schemeToOnix)
+                    scheme
+        toCreatorNode s id' creator
+          | version == EPUB2 = [dcNode s !
+             (("id",id') :
+              maybe [] (\x -> [("opf:file-as",x)]) (creatorFileAs creator) ++
+              maybe [] (\x -> [("opf:role",x)])
+               (creatorRole creator >>= toRelator)) $ creatorText creator]
+          | otherwise = [dcNode s ! [("id",id')] $ creatorText creator] ++
+              maybe [] (\x -> [unode "meta" !
+                   [("refines","#" <> id'),(metaprop,"file-as")] $ x])
+                   (creatorFileAs creator) ++
+              maybe [] (\x -> [unode "meta" !
+                   [("refines","#" <> id'),(metaprop,"role"),
+                     ("scheme","marc:relators")] $ x])
+                   (creatorRole creator >>= toRelator)
+        toTitleNode id' title
+          | version == EPUB2 = [dcNode "title" !
+             (("id",id') :
+              -- note: EPUB2 doesn't accept opf:title-type
+              maybe [] (\x -> [("opf:file-as",x)]) (titleFileAs title)) $
+              titleText title]
+          | otherwise = [dcNode "title" ! [("id",id')] $ titleText title]
+              ++
+              maybe [] (\x -> [unode "meta" !
+                   [("refines","#" <> id'),(metaprop,"file-as")] $ x])
+                   (titleFileAs title) ++
+              maybe [] (\x -> [unode "meta" !
+                   [("refines","#" <> id'),(metaprop,"title-type")] $ x])
+                   (titleType title)
+        toDateNode id' date = [dcNode "date" !
+             (("id",id') :
+                maybe [] (\x -> [("opf:event",x)]) (dateEvent date)) $
+                 dateText date]
+        toSubjectNode id' subject
+          | version == EPUB2 = [dcNode "subject" !
+            [("id",id')] $ subjectText subject]
+          | otherwise = (dcNode "subject" ! [("id",id')] $ subjectText subject)
+            : maybe [] (\x -> (unode "meta" !
+                    [("refines", "#" <> id'),(metaprop,"authority")] $ x) :
+                    maybe [] (\y -> [unode "meta" !
+                         [("refines", "#" <> id'),(metaprop,"term")] $ y])
+                         (subjectTerm subject))
+                    (subjectAuthority subject)
+        schemeToOnix :: Text -> Text
+        schemeToOnix "ISBN-10"              = "02"
+        schemeToOnix "GTIN-13"              = "03"
+        schemeToOnix "UPC"                  = "04"
+        schemeToOnix "ISMN-10"              = "05"
+        schemeToOnix "DOI"                  = "06"
+        schemeToOnix "LCCN"                 = "13"
+        schemeToOnix "GTIN-14"              = "14"
+        schemeToOnix "ISBN-13"              = "15"
+        schemeToOnix "Legal deposit number" = "17"
+        schemeToOnix "URN"                  = "22"
+        schemeToOnix "OCLC number"          = "23"
+        schemeToOnix "Co-publisher’s ISBN-13" = "24"
+        schemeToOnix "ISMN-13"              = "25"
+        schemeToOnix "ISBN-A"               = "26"
+        schemeToOnix "JP e-code"            = "27"
+        schemeToOnix "OLCC number"          = "28"
+        schemeToOnix "JP Magazine ID"       = "29"
+        schemeToOnix "UPC-12+5"             = "30"
+        schemeToOnix "BNF Control number"   = "31"
+        schemeToOnix "ISSN-13"              = "34"
+        schemeToOnix "ARK"                  = "35"
+        schemeToOnix "Digital file internal version number" = "36"
+        schemeToOnix _                      = "01"
+
+showDateTimeISO8601 :: UTCTime -> Text
+showDateTimeISO8601 = T.pack . formatTime defaultTimeLocale "%FT%TZ"
+
+transformTag :: PandocMonad m
+             => Tag T.Text
+             -> E m (Tag T.Text)
+transformTag tag@(TagOpen name attr)
+  | name `elem` ["video", "source", "img", "audio"] &&
+    isNothing (lookup "data-external" attr) = do
+  let src = fromAttrib "src" tag
+  let poster = fromAttrib "poster" tag
+  newsrc <- modifyMediaRef $ T.unpack src
+  newposter <- modifyMediaRef $ T.unpack poster
+  let attr' = filter (\(x,_) -> x /= "src" && x /= "poster") attr ++
+              [("src", "../" <> newsrc) | not (T.null newsrc)] ++
+              [("poster", "../" <> newposter) | not (T.null newposter)]
+  return $ TagOpen name attr'
+transformTag tag = return tag
+
+modifyMediaRef :: PandocMonad m
+               => FilePath
+               -> E m T.Text
+modifyMediaRef "" = return ""
+modifyMediaRef oldsrc = do
+  media <- gets stMediaPaths
+  case lookup oldsrc media of
+         Just (n,_) -> return $ T.pack n
+         Nothing    -> catchError
+           (do (img, mbMime) <- P.fetchItem $ T.pack oldsrc
+               let ext = maybe
+                          (takeExtension (takeWhile (/='?') oldsrc))
+                          (T.unpack . ("." <>))
+                          (mbMime >>= extensionFromMimeType)
+               newName <- getMediaNextNewName ext
+               let newPath = "media/" ++ newName
+               entry <- mkEntry newPath (B.fromChunks . (:[]) $ img)
+               modify $ \st -> st{ stMediaPaths =
+                            (oldsrc, (newPath, Just entry)):media}
+               return $ T.pack newPath)
+           (\e -> do
+                report $ CouldNotFetchResource (T.pack oldsrc) (tshow e)
+                return $ T.pack oldsrc)
+
+getMediaNextNewName :: PandocMonad m => FilePath -> E m FilePath
+getMediaNextNewName ext = do
+  nextId <- gets stMediaNextId
+  modify $ \st -> st { stMediaNextId = nextId + 1 }
+  return $ "file" ++ show nextId ++ ext
+
+isHtmlFormat :: EPUBVersion -> Format -> Bool
+isHtmlFormat _ (Format "html") = True
+isHtmlFormat _ (Format "html4") = True
+isHtmlFormat _ (Format "html5") = True
+isHtmlFormat _ (Format "epub") = True
+isHtmlFormat EPUB2 (Format "epub2") = True
+isHtmlFormat EPUB3 (Format "epub3") = True
+isHtmlFormat _ _ = False
+
+transformBlock  :: PandocMonad m
+                => EPUBVersion
+                -> Block
+                -> E m Block
+transformBlock version (RawBlock fmt raw)
+  | isHtmlFormat version fmt = do
+  let tags = parseTags raw
+  tags' <- mapM transformTag tags
+  return $ RawBlock fmt (renderTags' tags')
+transformBlock _ b = return b
+
+transformInline  :: PandocMonad m
+                 => EPUBVersion
+                 -> WriterOptions
+                 -> Inline
+                 -> E m Inline
+transformInline _ _opts (Image attr@(_,_,kvs) lab (src,tit))
+  | isNothing (lookup "external" kvs) = do
+    newsrc <- modifyMediaRef $ T.unpack src
+    return $ Image attr lab ("../" <> newsrc, tit)
+transformInline _ opts x@(Math t m)
+  | WebTeX url <- writerHTMLMathMethod opts = do
+    newsrc <- modifyMediaRef (T.unpack (url <> urlEncode m))
+    let mathclass = if t == DisplayMath then "display" else "inline"
+    return $ Span ("",["math",mathclass],[])
+                [Image nullAttr [x] ("../" <> newsrc, "")]
+transformInline version _opts (RawInline fmt raw)
+  | isHtmlFormat version fmt = do
+  let tags = parseTags raw
+  tags' <- mapM transformTag tags
+  return $ RawInline fmt (renderTags' tags')
+transformInline _ _ x = return x
+
+(!) :: (t -> Element) -> [(Text, Text)] -> t -> Element
+(!) f attrs n = add_attrs (map (\(k,v) -> Attr (unqual k) v) attrs) (f n)
+
+mediaTypeOf :: FilePath -> Maybe MimeType
+mediaTypeOf x =
+  let mediaPrefixes = ["image", "video", "audio"] in
+  case getMimeType x of
+    Just y | any (`T.isPrefixOf` y) mediaPrefixes -> Just y
+    _      -> Nothing
+
+-- Returns filename for chapter number.
+showChapter :: Int -> Text
+showChapter = T.pack . printf "ch%03d.xhtml"
+
+-- Add identifiers to any headers without them.
+addIdentifiers :: WriterOptions -> [Block] -> [Block]
+addIdentifiers opts bs = evalState (mapM go bs) Set.empty
+ where go (Header n (ident,classes,kvs) ils) = do
+         ids <- get
+         let ident' = if T.null ident
+                         then uniqueIdent (writerExtensions opts) ils ids
+                         else ident
+         modify $ Set.insert ident'
+         return $ Header n (ident',classes,kvs) ils
+       go x = return x
+
+-- Variant of normalizeDate that allows partial dates: YYYY, YYYY-MM
+normalizeDate' :: Text -> Maybe Text
+normalizeDate' = go . T.strip
+  where
+    go xs
+      | T.length xs == 4            -- YYY
+      , T.all isDigit xs = Just xs
+      | (y, s) <- T.splitAt 4 xs    -- YYY-MM
+      , Just ('-', m) <- T.uncons s
+      , T.length m == 2
+      , T.all isDigit y && T.all isDigit m = Just xs
+      | otherwise = normalizeDate xs
+
+toRelator :: Text -> Maybe Text
+toRelator x
+  | x `elem` relators = Just x
+  | otherwise         = lookup (T.toLower x) relatorMap
+
+relators :: [Text]
+relators = map snd relatorMap
+
+relatorMap :: [(Text, Text)]
+relatorMap =
+           [("abridger", "abr")
+           ,("actor", "act")
+           ,("adapter", "adp")
+           ,("addressee", "rcp")
+           ,("analyst", "anl")
+           ,("animator", "anm")
+           ,("annotator", "ann")
+           ,("appellant", "apl")
+           ,("appellee", "ape")
+           ,("applicant", "app")
+           ,("architect", "arc")
+           ,("arranger", "arr")
+           ,("art copyist", "acp")
+           ,("art director", "adi")
+           ,("artist", "art")
+           ,("artistic director", "ard")
+           ,("assignee", "asg")
+           ,("associated name", "asn")
+           ,("attributed name", "att")
+           ,("auctioneer", "auc")
+           ,("author", "aut")
+           ,("author in quotations or text abstracts", "aqt")
+           ,("author of afterword, colophon, etc.", "aft")
+           ,("author of dialog", "aud")
+           ,("author of introduction, etc.", "aui")
+           ,("autographer", "ato")
+           ,("bibliographic antecedent", "ant")
+           ,("binder", "bnd")
+           ,("binding designer", "bdd")
+           ,("blurb writer", "blw")
+           ,("book designer", "bkd")
+           ,("book producer", "bkp")
+           ,("bookjacket designer", "bjd")
+           ,("bookplate designer", "bpd")
+           ,("bookseller", "bsl")
+           ,("braille embosser", "brl")
+           ,("broadcaster", "brd")
+           ,("calligrapher", "cll")
+           ,("cartographer", "ctg")
+           ,("caster", "cas")
+           ,("censor", "cns")
+           ,("choreographer", "chr")
+           ,("cinematographer", "cng")
+           ,("client", "cli")
+           ,("collection registrar", "cor")
+           ,("collector", "col")
+           ,("collotyper", "clt")
+           ,("colorist", "clr")
+           ,("commentator", "cmm")
+           ,("commentator for written text", "cwt")
+           ,("compiler", "com")
+           ,("complainant", "cpl")
+           ,("complainant-appellant", "cpt")
+           ,("complainant-appellee", "cpe")
+           ,("composer", "cmp")
+           ,("compositor", "cmt")
+           ,("conceptor", "ccp")
+           ,("conductor", "cnd")
+           ,("conservator", "con")
+           ,("consultant", "csl")
+           ,("consultant to a project", "csp")
+           ,("contestant", "cos")
+           ,("contestant-appellant", "cot")
+           ,("contestant-appellee", "coe")
+           ,("contestee", "cts")
+           ,("contestee-appellant", "ctt")
+           ,("contestee-appellee", "cte")
+           ,("contractor", "ctr")
+           ,("contributor", "ctb")
+           ,("copyright claimant", "cpc")
+           ,("copyright holder", "cph")
+           ,("corrector", "crr")
+           ,("correspondent", "crp")
+           ,("costume designer", "cst")
+           ,("court governed", "cou")
+           ,("court reporter", "crt")
+           ,("cover designer", "cov")
+           ,("creator", "cre")
+           ,("curator", "cur")
+           ,("dancer", "dnc")
+           ,("data contributor", "dtc")
+           ,("data manager", "dtm")
+           ,("dedicatee", "dte")
+           ,("dedicator", "dto")
+           ,("defendant", "dfd")
+           ,("defendant-appellant", "dft")
+           ,("defendant-appellee", "dfe")
+           ,("degree granting institution", "dgg")
+           ,("delineator", "dln")
+           ,("depicted", "dpc")
+           ,("depositor", "dpt")
+           ,("designer", "dsr")
+           ,("director", "drt")
+           ,("dissertant", "dis")
+           ,("distribution place", "dbp")
+           ,("distributor", "dst")
+           ,("donor", "dnr")
+           ,("draftsman", "drm")
+           ,("dubious author", "dub")
+           ,("editor", "edt")
+           ,("editor of compilation", "edc")
+           ,("editor of moving image work", "edm")
+           ,("electrician", "elg")
+           ,("electrotyper", "elt")
+           ,("enacting jurisdiction", "enj")
+           ,("engineer", "eng")
+           ,("engraver", "egr")
+           ,("etcher", "etr")
+           ,("event place", "evp")
+           ,("expert", "exp")
+           ,("facsimilist", "fac")
+           ,("field director", "fld")
+           ,("film director", "fmd")
+           ,("film distributor", "fds")
+           ,("film editor", "flm")
+           ,("film producer", "fmp")
+           ,("filmmaker", "fmk")
+           ,("first party", "fpy")
+           ,("forger", "frg")
+           ,("former owner", "fmo")
+           ,("funder", "fnd")
+           ,("geographic information specialist", "gis")
+           ,("honoree", "hnr")
+           ,("host", "hst")
+           ,("host institution", "his")
+           ,("illuminator", "ilu")
+           ,("illustrator", "ill")
+           ,("inscriber", "ins")
+           ,("instrumentalist", "itr")
+           ,("interviewee", "ive")
+           ,("interviewer", "ivr")
+           ,("inventor", "inv")
+           ,("issuing body", "isb")
+           ,("judge", "jud")
+           ,("jurisdiction governed", "jug")
+           ,("laboratory", "lbr")
+           ,("laboratory director", "ldr")
+           ,("landscape architect", "lsa")
+           ,("lead", "led")
+           ,("lender", "len")
+           ,("libelant", "lil")
+           ,("libelant-appellant", "lit")
+           ,("libelant-appellee", "lie")
+           ,("libelee", "lel")
+           ,("libelee-appellant", "let")
+           ,("libelee-appellee", "lee")
+           ,("librettist", "lbt")
+           ,("licensee", "lse")
+           ,("licensor", "lso")
+           ,("lighting designer", "lgd")
+           ,("lithographer", "ltg")
+           ,("lyricist", "lyr")
+           ,("manufacture place", "mfp")
+           ,("manufacturer", "mfr")
+           ,("marbler", "mrb")
+           ,("markup editor", "mrk")
+           ,("metadata contact", "mdc")
+           ,("metal-engraver", "mte")
+           ,("moderator", "mod")
+           ,("monitor", "mon")
+           ,("music copyist", "mcp")
+           ,("musical director", "msd")
+           ,("musician", "mus")
+           ,("narrator", "nrt")
+           ,("onscreen presenter", "osp")
+           ,("opponent", "opn")
+           ,("organizer of meeting", "orm")
+           ,("originator", "org")
+           ,("other", "oth")
+           ,("owner", "own")
+           ,("panelist", "pan")
+           ,("papermaker", "ppm")
+           ,("patent applicant", "pta")
+           ,("patent holder", "pth")
+           ,("patron", "pat")
+           ,("performer", "prf")
+           ,("permitting agency", "pma")
+           ,("photographer", "pht")
+           ,("plaintiff", "ptf")
+           ,("plaintiff-appellant", "ptt")
+           ,("plaintiff-appellee", "pte")
+           ,("platemaker", "plt")
+           ,("praeses", "pra")
+           ,("presenter", "pre")
+           ,("printer", "prt")
+           ,("printer of plates", "pop")
+           ,("printmaker", "prm")
+           ,("process contact", "prc")
+           ,("producer", "pro")
+           ,("production company", "prn")
+           ,("production designer", "prs")
+           ,("production manager", "pmn")
+           ,("production personnel", "prd")
+           ,("production place", "prp")
+           ,("programmer", "prg")
+           ,("project director", "pdr")
+           ,("proofreader", "pfr")
+           ,("provider", "prv")
+           ,("publication place", "pup")
+           ,("publisher", "pbl")
+           ,("publishing director", "pbd")
+           ,("puppeteer", "ppt")
+           ,("radio director", "rdd")
+           ,("radio producer", "rpc")
+           ,("recording engineer", "rce")
+           ,("recordist", "rcd")
+           ,("redaktor", "red")
+           ,("renderer", "ren")
+           ,("reporter", "rpt")
+           ,("repository", "rps")
+           ,("research team head", "rth")
+           ,("research team member", "rtm")
+           ,("researcher", "res")
+           ,("respondent", "rsp")
+           ,("respondent-appellant", "rst")
+           ,("respondent-appellee", "rse")
+           ,("responsible party", "rpy")
+           ,("restager", "rsg")
+           ,("restorationist", "rsr")
+           ,("reviewer", "rev")
+           ,("rubricator", "rbr")
+           ,("scenarist", "sce")
+           ,("scientific advisor", "sad")
+           ,("screenwriter", "aus")
+           ,("scribe", "scr")
+           ,("sculptor", "scl")
+           ,("second party", "spy")
+           ,("secretary", "sec")
+           ,("seller", "sll")
+           ,("set designer", "std")
+           ,("setting", "stg")
+           ,("signer", "sgn")
+           ,("singer", "sng")
+           ,("sound designer", "sds")
+           ,("speaker", "spk")
+           ,("sponsor", "spn")
+           ,("stage director", "sgd")
+           ,("stage manager", "stm")
+           ,("standards body", "stn")
+           ,("stereotyper", "str")
+           ,("storyteller", "stl")
+           ,("supporting host", "sht")
+           ,("surveyor", "srv")
+           ,("teacher", "tch")
+           ,("technical director", "tcd")
+           ,("television director", "tld")
+           ,("television producer", "tlp")
+           ,("thesis advisor", "ths")
+           ,("transcriber", "trc")
+           ,("translator", "trl")
+           ,("type designer", "tyd")
+           ,("typographer", "tyg")
+           ,("university place", "uvp")
+           ,("videographer", "vdg")
+           ,("witness", "wit")
+           ,("wood engraver", "wde")
+           ,("woodcutter", "wdc")
+           ,("writer of accompanying material", "wam")
+           ,("writer of added commentary", "wac")
+           ,("writer of added lyrics", "wal")
+           ,("writer of added text", "wat")
+           ]
+
+docTitle' :: Meta -> [Inline]
+docTitle' meta = maybe [] go $ lookupMeta "title" meta
   where go (MetaString s) = [Str s]
         go (MetaInlines xs) = xs
         go (MetaBlocks [Para xs]) = xs
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,28 +1,9 @@
-{-# LANGUAGE PatternGuards #-}
-
-{-
-Copyright (c) 2011-2012 Sergey Astanin
-              2012-2017 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
--}
-
+{-# LANGUAGE PatternGuards     #-}
+{-# LANGUAGE OverloadedStrings #-}
 {- |
 Module      : Text.Pandoc.Writers.FB2
 Copyright   : Copyright (C) 2011-2012 Sergey Astanin
-                            2012-2017 John MacFarlane
+                            2012-2024 John MacFarlane
 License     : GNU GPL, version 2 or above
 
 Maintainer  : John MacFarlane
@@ -37,33 +18,38 @@
 -}
 module Text.Pandoc.Writers.FB2 (writeFB2)  where
 
-import Control.Monad (zipWithM)
-import Control.Monad.Except (catchError)
-import Control.Monad.State.Strict (StateT, evalStateT, get, lift, liftM, modify)
+import Control.Monad (zipWithM, liftM)
+import Control.Monad.Except (catchError, throwError)
+import Control.Monad.State.Strict (StateT, evalStateT, get, gets, lift, modify)
 import Data.ByteString.Base64 (encode)
-import qualified Data.ByteString.Char8 as B8
-import Data.Char (isAscii, isControl, isSpace, toLower)
+import Data.Char (isAscii, isControl, isSpace)
 import Data.Either (lefts, rights)
-import Data.List (intercalate, intersperse, isPrefixOf, stripPrefix)
-import Data.Text (Text, pack)
-import Network.HTTP (urlEncode)
-import Text.XML.Light
-import qualified Text.XML.Light as X
-import qualified Text.XML.Light.Cursor as XC
-
-import Text.Pandoc.Class (PandocMonad, report)
-import qualified Text.Pandoc.Class as P
+import Data.List (intercalate)
+import Data.Text (Text)
+import qualified Data.Text as T
+import qualified Data.Text.Lazy as TL
+import qualified Data.Text.Encoding as TE
+import Text.Pandoc.URI (urlEncode, isURI)
+import Text.Pandoc.XML.Light as X
+import Text.Pandoc.Class.PandocMonad (PandocMonad, report)
+import qualified Text.Pandoc.Class.PandocMonad as P
 import Text.Pandoc.Definition
+import Text.Pandoc.Error (PandocError(..))
 import Text.Pandoc.Logging
 import Text.Pandoc.Options (HTMLMathMethod (..), WriterOptions (..), def)
-import Text.Pandoc.Shared (capitalize, isHeaderBlock, isURI, orderedListMarkers)
+import Text.Pandoc.Shared (blocksToInlines, capitalize, orderedListMarkers,
+                           makeSections, tshow, stringify)
+import Text.Pandoc.Walk (walk)
+import Text.Pandoc.Writers.Shared (lookupMetaString, toLegacyTable,
+                                   ensureValidXmlIdentifiers)
+import Data.Generics (everywhere, mkT)
 
 -- | Data to be written at the end of the document:
 -- (foot)notes, URLs, references, images.
 data FbRenderState = FbRenderState
-    { footnotes         :: [ (Int, String, [Content]) ]  -- ^ #, ID, text
-    , imagesToFetch     :: [ (String, String) ]  -- ^ filename, URL or path
-    , parentListMarker  :: String  -- ^ list marker of the parent ordered list
+    { footnotes         :: [ (Int, Text, [Content]) ]  -- ^ #, ID, text
+    , imagesToFetch     :: [ (Text, Text) ]  -- ^ filename, URL or path
+    , parentListMarker  :: Text  -- ^ list marker of the parent ordered list
     , writerOptions     :: WriterOptions
     } deriving (Show)
 
@@ -91,17 +77,18 @@
             => WriterOptions
             -> Pandoc
             -> FBM m Text
-pandocToFB2 opts (Pandoc meta blocks) = do
+pandocToFB2 opts doc = do
+     let Pandoc meta blocks = ensureValidXmlIdentifiers doc
      modify (\s -> s { writerOptions = opts })
      desc <- description meta
      title <- cMapM toXml . docTitle $ meta
      secs <- renderSections 1 blocks
      let body = el "body" $ el "title" (el "p" title) : secs
      notes <- renderFootnotes
-     (imgs,missing) <- fmap imagesToFetch get >>= \s -> lift (fetchImages s)
+     (imgs,missing) <- get >>= (lift . fetchImages . imagesToFetch)
      let body' = replaceImagesWithAlt missing body
      let fb2_xml = el "FictionBook" (fb2_attrs, [desc, body'] ++ notes ++ imgs)
-     return $ pack $ xml_head ++ showContent fb2_xml ++ "\n"
+     return $ xml_head <> showContent fb2_xml <> "\n"
   where
   xml_head = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
   fb2_attrs =
@@ -112,50 +99,53 @@
 
 description :: PandocMonad m => Meta -> FBM m Content
 description meta' = do
-  let genre = el "genre" "unrecognised"
+  let genre = case lookupMetaString "genre" meta' of
+                "" -> el "genre" ("unrecognised" :: Text)
+                s  -> el "genre" s
   bt <- booktitle meta'
   let as = authors meta'
   dd <- docdate meta'
+  annotation <- case lookupMeta "abstract" meta' of
+                  Just (MetaBlocks bs) -> list . el "annotation" <$> cMapM blockToXml (map unPlain bs)
+                  _ -> pure mempty
   let lang = case lookupMeta "lang" meta' of
                Just (MetaInlines [Str s]) -> [el "lang" $ iso639 s]
                Just (MetaString s)        -> [el "lang" $ iso639 s]
                _                          -> []
-             where iso639 = takeWhile (/= '-') -- Convert BCP 47 to ISO 639
+             where iso639 = T.takeWhile (/= '-') -- Convert BCP 47 to ISO 639
   let coverimage url = do
         let img = Image nullAttr mempty (url, "")
         im <- insertImage InlineImage img
         return [el "coverpage" im]
   coverpage <- case lookupMeta "cover-image" meta' of
-                    Just (MetaInlines [Str s]) -> coverimage s
+                    Just (MetaInlines ils) -> coverimage (stringify ils)
                     Just (MetaString s) -> coverimage s
                     _       -> return []
   return $ el "description"
-    [ el "title-info" (genre : (bt ++ as ++ dd ++ lang))
-    , el "document-info" ([ el "program-used" "pandoc" ] -- FIXME: +version
-                          ++ coverpage)
+    [ el "title-info" (genre :
+                      (as ++ bt ++ annotation ++ dd ++ coverpage ++ lang))
+    , el "document-info" [el "program-used" ("pandoc" :: Text)]
     ]
 
 booktitle :: PandocMonad m => Meta -> FBM m [Content]
 booktitle meta' = do
   t <- cMapM toXml . docTitle $ meta'
-  return $ if null t
-           then []
-           else [ el "book-title" t ]
+  return $ [el "book-title" t | not (null t)]
 
 authors :: Meta -> [Content]
 authors meta' = cMap author (docAuthors meta')
 
 author :: [Inline] -> [Content]
 author ss =
-  let ws = words . cMap plain $ ss
-      email = el "email" <$> take 1 (filter ('@' `elem`) ws)
-      ws' = filter ('@' `notElem`) ws
+  let ws = T.words $ mconcat $ map plain ss
+      email = el "email" <$> take 1 (filter (T.any (=='@')) ws)
+      ws' = filter (not . T.any (== '@')) ws
       names = case ws' of
                 [nickname] -> [ el "nickname" nickname ]
                 [fname, lname] -> [ el "first-name" fname
                                     , el "last-name" lname ]
                 (fname:rest) -> [ el "first-name" fname
-                                , el "middle-name" (concat . init $ rest)
+                                , el "middle-name" (T.concat . init $ rest)
                                 , el "last-name" (last rest) ]
                 [] -> []
   in  list $ el "author" (names ++ email)
@@ -164,35 +154,40 @@
 docdate meta' = do
   let ss = docDate meta'
   d <- cMapM toXml ss
-  return $ if null d
-           then []
-           else [el "date" d]
+  return $ [el "date" d | not (null d)]
 
 -- | Divide the stream of blocks into sections and convert to XML
 -- representation.
 renderSections :: PandocMonad m => Int -> [Block] -> FBM m [Content]
 renderSections level blocks = do
-    let secs = splitSections level blocks
-    mapM (renderSection level) secs
+    let blocks' = makeSections False Nothing blocks
+    let isSection (Div (_,"section":_,_) (Header{}:_)) = True
+        isSection _ = False
+    let (initialBlocks, secs) = break isSection blocks'
+    let blocks'' = if null initialBlocks
+        then blocks'
+        else Div ("",["section"],[])
+               (Header 1 nullAttr mempty : initialBlocks) : secs
+    cMapM (renderSection level) blocks''
 
-renderSection :: PandocMonad m => Int -> ([Inline], [Block]) -> FBM m Content
-renderSection level (ttl, body) = do
-    title <- if null ttl
+renderSection :: PandocMonad m =>  Int -> Block -> FBM m [Content]
+renderSection lvl (Div (id',"section":_,_) (Header _ _ title : xs)) = do
+  title' <- if null title
             then return []
-            else return . 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
+  content <- cMapM (renderSection (lvl + 1)) xs
+  let sectionContent = if T.null id'
+      then el "section" (title' ++ content)
+      else el "section" ([uattr "id" id'], title' ++ content)
+  return [sectionContent]
+renderSection lvl (Div _attr bs) =
+  cMapM (renderSection lvl) bs
+renderSection _ b = blockToXml b
 
 -- | Only <p> and <empty-line> are allowed within <title> in FB2.
-formatTitle :: [Inline] -> [Content]
+formatTitle :: PandocMonad m => [Inline] -> FBM m [Content]
 formatTitle inlines =
-  let lns = split isLineBreak inlines
-      lns' = map (el "p" . cMap plain) lns
-  in  intersperse (el "empty-line" ()) lns'
+  cMapM (blockToXml . Para) $ split (== LineBreak) inlines
 
 split :: (a -> Bool) -> [a] -> [[a]]
 split _ [] = []
@@ -203,24 +198,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
@@ -231,24 +208,24 @@
          el "body" ([uattr "name" "notes"], map renderFN (reverse fns))
   where
     renderFN (n, idstr, cs) =
-        let fn_texts = el "title" (el "p" (show n)) : cs
+        let fn_texts = el "title" (el "p" (tshow n)) : cs
         in  el "section" ([uattr "id" idstr], fn_texts)
 
 -- | Fetch images and encode them for the FictionBook XML.
 -- Return image data and a list of hrefs of the missing images.
-fetchImages :: PandocMonad m => [(String,String)] -> m ([Content],[String])
+fetchImages :: PandocMonad m => [(Text,Text)] -> m ([Content],[Text])
 fetchImages links = do
     imgs <- mapM (uncurry fetchImage) links
     return (rights imgs, lefts imgs)
 
 -- | Fetch image data from disk or from network and make a <binary> XML section.
 -- Return either (Left hrefOfMissingImage) or (Right xmlContent).
-fetchImage :: PandocMonad m => String -> String -> m (Either String Content)
+fetchImage :: PandocMonad m => Text -> Text -> m (Either Text Content)
 fetchImage href link = do
   mbimg <-
       case (isURI link, readDataURI link) of
        (True, Just (mime,_,True,base64)) ->
-           let mime' = map toLower mime
+           let mime' = T.toLower mime
            in if mime' == "image/png" || mime' == "image/jpeg"
               then return (Just (mime',base64))
               else return Nothing
@@ -260,9 +237,9 @@
                                report $ CouldNotDetermineMimeType link
                                return Nothing
                              Just mime -> return $ Just (mime,
-                                                      B8.unpack $ encode bs))
+                                                      TE.decodeUtf8 $ encode bs))
                     (\e ->
-                       do report $ CouldNotFetchResource link (show e)
+                       do report $ CouldNotFetchResource link (tshow e)
                           return Nothing)
   case mbimg of
     Just (imgtype, imgdata) ->
@@ -270,117 +247,111 @@
                    ( [uattr "id" href
                      , uattr "content-type" imgtype]
                    , txt imgdata )
-    _ -> return (Left ('#':href))
+    _ -> return (Left ("#" <> href))
 
 
 -- | Extract mime type and encoded data from the Data URI.
-readDataURI :: String -- ^ URI
-            -> Maybe (String,String,Bool,String)
+readDataURI :: Text -- ^ URI
+            -> Maybe (Text,Text,Bool,Text)
                -- ^ Maybe (mime,charset,isBase64,data)
 readDataURI uri =
-  case stripPrefix "data:" uri of
+  case T.stripPrefix "data:" uri of
     Nothing   -> Nothing
     Just rest ->
-      let meta = takeWhile (/= ',') rest  -- without trailing ','
-          uridata = drop (length meta + 1) rest
-          parts = split (== ';') meta
+      let meta = T.takeWhile (/= ',') rest  -- without trailing ','
+          uridata = T.drop (T.length meta + 1) rest
+          parts = T.split (== ';') meta
           (mime,cs,enc)=foldr upd ("text/plain","US-ASCII",False) parts
       in  Just (mime,cs,enc,uridata)
 
  where
    upd str m@(mime,cs,enc)
-       | isMimeType str                          = (str,cs,enc)
-       | Just str' <- stripPrefix "charset=" str = (mime,str',enc)
-       | str ==  "base64"                        = (mime,cs,True)
-       | otherwise                               = m
+       | isMimeType str                            = (str,cs,enc)
+       | Just str' <- T.stripPrefix "charset=" str = (mime,str',enc)
+       | str ==  "base64"                          = (mime,cs,True)
+       | otherwise                                 = m
 
 -- Without parameters like ;charset=...; see RFC 2045, 5.1
-isMimeType :: String -> Bool
+isMimeType :: Text -> Bool
 isMimeType s =
-    case split (=='/') s of
+    case T.split (=='/') s of
       [mtype,msubtype] ->
-          (map toLower mtype `elem` types
-           || "x-" `isPrefixOf` map toLower mtype)
-          && all valid mtype
-          && all valid msubtype
+          (T.toLower mtype `elem` types
+           || "x-" `T.isPrefixOf` T.toLower mtype)
+          && T.all valid mtype
+          && T.all valid msubtype
       _ -> False
  where
    types =  ["text","image","audio","video","application","message","multipart"]
    valid c = isAscii c && not (isControl c) && not (isSpace c) &&
-             c `notElem` "()<>@,;:\\\"/[]?="
+             c `notElem` ("()<>@,;:\\\"/[]?=" :: [Char])
 
-footnoteID :: Int -> String
-footnoteID i = "n" ++ show i
+footnoteID :: Int -> Text
+footnoteID i = "n" <> tshow i
 
-linkID :: Int -> String
-linkID i = "l" ++ show i
+mkitem :: PandocMonad m => Text -> [Block] -> FBM m [Content]
+mkitem mrk bs = do
+  pmrk <- gets parentListMarker
+  let nmrk = pmrk <> mrk <> " "
+  modify (\s -> s { parentListMarker = nmrk})
+  item <- cMapM blockToXml $ plainToPara $ indentBlocks nmrk bs
+  modify (\s -> s { parentListMarker = pmrk }) -- old parent marker
+  return item
 
 -- | Convert a block-level Pandoc's element to FictionBook XML representation.
 blockToXml :: PandocMonad m => Block -> FBM m [Content]
+blockToXml (Plain [img@Image {}]) = insertImage NormalImage img
 blockToXml (Plain ss) = cMapM toXml ss  -- FIXME: can lead to malformed FB2
+-- Special handling for singular images and display math elements
 blockToXml (Para [Math DisplayMath formula]) = insertMath NormalImage formula
--- title beginning with fig: indicates that the image is a figure
-blockToXml (Para [Image atr alt (src,'f':'i':'g':':':tit)]) =
-  insertImage NormalImage (Image atr alt (src,tit))
-blockToXml (Para ss) = (list . el "p") <$> cMapM toXml ss
+blockToXml (Para [img@(Image {})]) = insertImage NormalImage img
+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 []
+                             map (el "p" . el "code") . T.lines $ s
+blockToXml (RawBlock f str) =
+  if f == Format "fb2"
+    then
+      case parseXMLContents (TL.fromStrict str) of
+         Left msg  -> throwError $ PandocXMLError "" msg
+         Right nds -> return nds
+    else return []
 blockToXml (Div _ bs) = cMapM blockToXml bs
-blockToXml (BlockQuote bs) = (list . el "cite") <$> cMapM blockToXml bs
+blockToXml (BlockQuote bs) = list . el "cite" <$> cMapM blockToXml bs
 blockToXml (LineBlock lns) =
-  (list . el "poem") <$> mapM stanza (split null lns)
+  list . el "poem" <$> mapM stanza (split null lns)
   where
     v xs = el "v" <$> cMapM toXml xs
     stanza xs = el "stanza" <$> mapM v xs
-blockToXml (OrderedList a bss) = do
-    state <- get
-    let pmrk = parentListMarker state
-    let markers = (pmrk ++) <$> orderedListMarkers a
-    let mkitem mrk bs = do
-          modify (\s -> s { parentListMarker = mrk ++ " "})
-          item <- cMapM blockToXml $ plainToPara $ indentBlocks (mrk ++ " ") bs
-          modify (\s -> s { parentListMarker = pmrk }) -- old parent marker
-          return item
+blockToXml (OrderedList a bss) =
     concat <$> zipWithM mkitem markers bss
-blockToXml (BulletList bss) = do
-    state <- get
-    let pmrk = parentListMarker state
-    let mrk = pmrk ++ "•"
-    let mkitem bs = do
-          modify (\s -> s { parentListMarker = mrk ++ " "})
-          item <- cMapM blockToXml $ plainToPara $ indentBlocks (mrk ++ " ") bs
-          modify (\s -> s { parentListMarker = pmrk }) -- old parent marker
-          return item
-    cMapM mkitem bss
+    where
+      markers = orderedListMarkers a
+blockToXml (BulletList bss) =
+    cMapM (mkitem "•") bss
 blockToXml (DefinitionList defs) =
     cMapM mkdef defs
     where
       mkdef (term, bss) = do
-          items <- cMapM (cMapM blockToXml . plainToPara . indentBlocks (replicate 4 ' ')) bss
+          items <- cMapM (cMapM blockToXml . plainToPara . indentBlocks (T.replicate 4 " ")) bss
           t <- wrap "strong" term
           return (el "p" t : items)
 blockToXml h@Header{} = do
-  -- should not occur after hierarchicalize, except inside lists/blockquotes
+  -- should not occur after makeSections, except inside lists/blockquotes
   report $ BlockNotRendered h
   return []
-blockToXml HorizontalRule = return
-                            [ el "empty-line" ()
-                            , el "p" (txt (replicate 10 '—'))
-                            , el "empty-line" () ]
-blockToXml (Table caption aligns _ headers rows) = do
-    hd <- mkrow "th" headers aligns
+blockToXml HorizontalRule = return [ el "empty-line" () ]
+blockToXml (Table _ blkCapt specs thead tbody tfoot) = do
+    let (caption, aligns, _, headers, rows) = toLegacyTable blkCapt specs thead tbody tfoot
+    hd <- if null headers then pure [] else (:[]) <$> mkrow "th" headers aligns
     bd <- mapM (\r -> mkrow "td" r aligns) rows
     c <- el "emphasis" <$> cMapM toXml caption
-    return [el "table" (hd : bd), el "p" c]
+    return [el "table" (hd <> bd), el "p" c]
     where
-      mkrow :: PandocMonad m => String -> [TableCell] -> [Alignment] -> FBM m Content
+      mkrow :: PandocMonad m => Text -> [[Block]] -> [Alignment] -> FBM m Content
       mkrow tag cells aligns' =
         el "tr" <$> mapM (mkcell tag) (zip cells aligns')
       --
-      mkcell :: PandocMonad m => String -> (TableCell, Alignment) -> FBM m Content
+      mkcell :: PandocMonad m => Text -> ([Block], Alignment) -> FBM m Content
       mkcell tag (cell, align) = do
         cblocks <- cMapM blockToXml cell
         return $ el tag ([align_attr align], cblocks)
@@ -390,7 +361,11 @@
       align_str AlignCenter  = "center"
       align_str AlignRight   = "right"
       align_str AlignDefault = "left"
-blockToXml Null = return []
+blockToXml (Figure _attr (Caption _ longcapt) body) =
+  let alt = blocksToInlines longcapt
+      addAlt (Image imgattr [] tgt) = Image imgattr alt tgt
+      addAlt inln                   = inln
+  in cMapM blockToXml (walk addAlt body)
 
 -- Replace plain text with paragraphs and add line break after paragraphs.
 -- It is used to convert plain text from tight list items to paragraphs.
@@ -399,18 +374,23 @@
 plainToPara (Plain inlines : rest) =
     Para inlines : plainToPara rest
 plainToPara (Para inlines : rest) =
-    Para inlines : Plain [LineBreak] : plainToPara rest
+    Para inlines : HorizontalRule : plainToPara rest -- HorizontalRule will be converted to <empty-line />
 plainToPara (p:rest) = p : plainToPara rest
 
+-- Replace plain text with paragraphs
+unPlain :: Block -> Block
+unPlain (Plain inlines) = Para inlines
+unPlain x = x
+
 -- Simulate increased indentation level. Will not really work
 -- for multi-line paragraphs.
-indentPrefix :: String -> Block -> Block
+indentPrefix :: Text -> Block -> Block
 indentPrefix spacer = indentBlock
   where
   indentBlock (Plain ins) = Plain (Str spacer:ins)
   indentBlock (Para ins) = Para (Str spacer:ins)
   indentBlock (CodeBlock a s) =
-    let s' = unlines . map (spacer++) . lines $ s
+    let s' = T.unlines . map (spacer<>) . T.lines $ s
     in  CodeBlock a s'
   indentBlock (BlockQuote bs) = BlockQuote (map indent bs)
   indentBlock (Header l attr' ins) = Header l attr' (indentLines ins)
@@ -424,18 +404,19 @@
 indent = indentPrefix spacer
   where
   -- indentation space
-  spacer :: String
-  spacer = replicate 4 ' '
+  spacer :: Text
+  spacer = T.replicate 4 " "
 
-indentBlocks :: String -> [Block] -> [Block]
+indentBlocks :: Text -> [Block] -> [Block]
 indentBlocks _ [] = []
-indentBlocks prefix (x:xs) = indentPrefix prefix x : map (indentPrefix $ replicate (length prefix) ' ') xs
+indentBlocks prefix (x:xs) = indentPrefix prefix x : map (indentPrefix $ T.replicate (T.length prefix) " ") xs
 
 -- | Convert a Pandoc's Inline element to FictionBook XML representation.
 toXml :: PandocMonad m => Inline -> FBM m [Content]
 toXml (Str s) = return [txt s]
 toXml (Span _ ils) = cMapM toXml ils
 toXml (Emph ss) = list `liftM` wrap "emphasis" ss
+toXml (Underline ss) = list `liftM` wrap "underline" ss
 toXml (Strong ss) = list `liftM` wrap "strong" ss
 toXml (Strikeout ss) = list `liftM` wrap "strikethrough" ss
 toXml (Superscript ss) = list `liftM` wrap "sup" ss
@@ -450,29 +431,15 @@
 toXml (Cite _ ss) = cMapM toXml ss  -- FIXME: support citation styles
 toXml (Code _ s) = return [el "code" s]
 toXml Space = return [txt " "]
-toXml SoftBreak = return [txt " "]
-toXml LineBreak = return [el "empty-line" ()]
+toXml SoftBreak = return [txt "\n"]
+toXml LineBreak = return [txt "\n"]
 toXml (Math _ formula) = insertMath InlineImage formula
 toXml il@(RawInline _ _) = do
   report $ InlineNotRendered il
   return []  -- raw TeX and raw HTML are suppressed
-toXml (Link _ text (url,ttl)) = do
-  fns <- footnotes `liftM` get
-  let n = 1 + length fns
-  let ln_id = linkID n
-  let ln_ref = list . el "sup" . txt $ "[" ++ show n ++ "]"
+toXml (Link _ text (url,_)) = do
   ln_text <- cMapM toXml text
-  let ln_desc =
-          let ttl' = dropWhile isSpace ttl
-          in if null ttl'
-             then list . el "p" $ el "code" url
-             else list . el "p" $ [ txt (ttl' ++ ": "), el "code" url ]
-  modify (\s -> s { footnotes = (n, ln_id, ln_desc) : fns })
-  return $ ln_text ++
-         [ el "a"
-                  ( [ attr ("l","href") ('#':ln_id)
-                    , uattr "type" "note" ]
-                  , ln_ref) ]
+  return [ el "a" ( [ attr ("l","href") url ], ln_text) ]
 toXml img@Image{} = insertImage InlineImage img
 toXml (Note bs) = do
   fns <- footnotes `liftM` get
@@ -480,18 +447,18 @@
   let fn_id = footnoteID n
   fn_desc <- cMapM blockToXml bs
   modify (\s -> s { footnotes = (n, fn_id, fn_desc) : fns })
-  let fn_ref = el "sup" . txt $ "[" ++ show n ++ "]"
-  return . list $ el "a" ( [ attr ("l","href") ('#':fn_id)
+  let fn_ref = txt $ "[" <> tshow n <> "]"
+  return . list $ el "a" ( [ attr ("l","href") ("#" <> fn_id)
                            , uattr "type" "note" ]
                          , fn_ref )
 
-insertMath :: PandocMonad m => ImageMode -> String -> FBM m [Content]
+insertMath :: PandocMonad m => ImageMode -> Text -> FBM m [Content]
 insertMath immode formula = do
   htmlMath <- fmap (writerHTMLMathMethod . writerOptions) get
   case htmlMath of
     WebTeX url -> do
        let alt = [Code nullAttr formula]
-       let imgurl = url ++ urlEncode formula
+       let imgurl = url <> urlEncode formula
        let img = Image nullAttr alt (imgurl, "")
        insertImage immode img
     _ -> return [el "code" formula]
@@ -500,40 +467,25 @@
 insertImage immode (Image _ alt (url,ttl)) = do
   images <- imagesToFetch `liftM` get
   let n = 1 + length images
-  let fname = "image" ++ show n
+  let fname = "image" <> tshow n
   modify (\s -> s { imagesToFetch = (fname, url) : images })
-  let ttlattr = case (immode, null ttl) of
+  let ttlattr = case (immode, T.null ttl) of
                   (NormalImage, False) -> [ uattr "title" ttl ]
                   _                    -> []
   return . list $
          el "image" $
-            [ attr ("l","href") ('#':fname)
-            , attr ("l","type") (show immode)
-            , uattr "alt" (cMap plain alt) ]
+            [ attr ("l","href") ("#" <> fname)
+            , attr ("l","type") (tshow immode)
+            , uattr "alt" (mconcat $ map plain alt) ]
             ++ ttlattr
 insertImage _ _ = error "unexpected inline instead of image"
 
-replaceImagesWithAlt :: [String] -> Content -> Content
-replaceImagesWithAlt missingHrefs body =
-  let cur = XC.fromContent body
-      cur' = replaceAll cur
-  in  XC.toTree . XC.root $ cur'
+replaceImagesWithAlt :: [Text] -> Content -> Content
+replaceImagesWithAlt missingHrefs = everywhere (mkT go)
   where
-  --
-    replaceAll :: XC.Cursor -> XC.Cursor
-    replaceAll c =
-        let n = XC.current c
-            c' = if isImage n && isMissing n
-                 then XC.modifyContent replaceNode c
-                 else c
-        in  case XC.nextDF c' of
-              (Just cnext) -> replaceAll cnext
-              Nothing      -> c'  -- end of document
-  --
-    isImage :: Content -> Bool
-    isImage (Elem e) = elName e == uname "image"
-    isImage _        = False
-  --
+    go c = if isMissing c
+              then replaceNode c
+              else c
     isMissing (Elem img@Element{}) =
         let imgAttrs = elAttribs img
             badAttrs = map (attr ("l","href")) missingHrefs
@@ -543,18 +495,18 @@
     replaceNode :: Content -> Content
     replaceNode n@(Elem img@Element{}) =
         let attrs = elAttribs img
-            alt = getAttrVal attrs (uname "alt")
+            alt = getAttrVal attrs (unqual "alt")
             imtype = getAttrVal attrs (qname "l" "type")
         in case (alt, imtype) of
              (Just alt', Just imtype') ->
-                 if imtype' == show NormalImage
+                 if imtype' == tshow NormalImage
                  then el "p" alt'
                  else txt alt'
              (Just alt', Nothing) -> txt alt'  -- no type attribute
              _ -> n   -- don't replace if alt text is not found
     replaceNode n = n
   --
-    getAttrVal :: [X.Attr] -> QName -> Maybe String
+    getAttrVal :: [X.Attr] -> QName -> Maybe Text
     getAttrVal attrs name =
         case filter ((name ==) . attrKey) attrs of
            (a:_) -> Just (attrVal a)
@@ -562,7 +514,7 @@
 
 
 -- | Wrap all inlines with an XML tag (given its unqualified name).
-wrap :: PandocMonad m => String -> [Inline] -> FBM m Content
+wrap :: PandocMonad m => Text -> [Inline] -> FBM m Content
 wrap tagname inlines = el tagname `liftM` cMapM toXml inlines
 
 -- " Create a singleton list.
@@ -570,30 +522,31 @@
 list = (:[])
 
 -- | Convert an 'Inline' to plaintext.
-plain :: Inline -> String
+plain :: Inline -> Text
 plain (Str s)               = s
-plain (Emph ss)             = cMap plain ss
-plain (Span _ ss)           = cMap plain ss
-plain (Strong ss)           = cMap plain ss
-plain (Strikeout ss)        = cMap plain ss
-plain (Superscript ss)      = cMap plain ss
-plain (Subscript ss)        = cMap plain ss
-plain (SmallCaps ss)        = cMap plain ss
-plain (Quoted _ ss)         = cMap plain ss
-plain (Cite _ ss)           = cMap plain ss  -- FIXME
+plain (Emph ss)             = mconcat $ map plain ss
+plain (Underline ss)        = mconcat $ map plain ss
+plain (Span _ ss)           = mconcat $ map plain ss
+plain (Strong ss)           = mconcat $ map plain ss
+plain (Strikeout ss)        = mconcat $ map plain ss
+plain (Superscript ss)      = mconcat $ map plain ss
+plain (Subscript ss)        = mconcat $ map plain ss
+plain (SmallCaps ss)        = mconcat $ map plain ss
+plain (Quoted _ ss)         = mconcat $ map plain ss
+plain (Cite _ ss)           = mconcat $ map plain ss  -- FIXME
 plain (Code _ s)            = s
 plain Space                 = " "
 plain SoftBreak             = " "
 plain LineBreak             = "\n"
 plain (Math _ s)            = s
 plain (RawInline _ _)       = ""
-plain (Link _ text (url,_)) = concat (map plain text ++ [" <", url, ">"])
-plain (Image _ alt _)       = cMap plain alt
+plain (Link _ text (url,_)) = mconcat (map plain text ++ [" <", url, ">"])
+plain (Image _ alt _)       = mconcat $ map plain alt
 plain (Note _)              = ""  -- FIXME
 
 -- | Create an XML element.
 el :: (Node t)
-   => String   -- ^ unqualified element name
+   => Text     -- ^ unqualified element name
    -> t        -- ^ node contents
    -> Content  -- ^ XML content
 el name cs = Elem $ unode name cs
@@ -605,23 +558,19 @@
     in  [emptyline] ++ cs ++ [emptyline]
 
 -- | Create a plain-text XML content.
-txt :: String -> Content
+txt :: Text -> Content
 txt s = Text $ CData CDataText s Nothing
 
 -- | Create an XML attribute with an unqualified name.
-uattr :: String -> String -> Text.XML.Light.Attr
-uattr name = Attr (uname name)
+uattr :: Text -> Text -> X.Attr
+uattr name = Attr (unqual name)
 
 -- | Create an XML attribute with a qualified name from given namespace.
-attr :: (String, String) -> String -> Text.XML.Light.Attr
+attr :: (Text, Text) -> Text -> X.Attr
 attr (ns, name) = Attr (qname ns name)
 
--- | Unqualified name
-uname :: String -> QName
-uname name = QName name Nothing Nothing
-
 -- | Qualified name
-qname :: String -> String -> QName
+qname :: Text -> Text -> QName
 qname ns name = QName name Nothing (Just ns)
 
 -- | Abbreviation for 'concatMap'.
diff --git a/src/Text/Pandoc/Writers/GridTable.hs b/src/Text/Pandoc/Writers/GridTable.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Writers/GridTable.hs
@@ -0,0 +1,181 @@
+{-# LANGUAGE FlexibleContexts           #-}
+{-# LANGUAGE GeneralizedNewtypeDeriving #-}
+{-# LANGUAGE LambdaCase                 #-}
+{-# LANGUAGE TupleSections              #-}
+
+{- |
+Module      : Text.Pandoc.Writers.GridTable
+Copyright   : © 2020-2024 Albert Krewinkel
+License     : GNU GPL, version 2 or above
+
+Maintainer  : Albert Krewinkel <albert+pandoc@tarleb.com>
+
+Grid representation of pandoc tables. The structures in this module
+allow to describe 'Text.Pandoc.Definition.Table' elements without loss
+of information. However, they are simpler to use when the grid layout of
+a table must be known.
+
+The "grid tables" handled here are conceptually similar to grid tables
+in reStructuredText and Markdown, but are more general.
+-}
+module Text.Pandoc.Writers.GridTable
+  ( Table (..)
+  , GridCell (..)
+  , RowIndex (..)
+  , ColIndex (..)
+  , CellIndex
+  , Part (..)
+  , toTable
+  , rowArray
+  ) where
+
+import Control.Monad (forM_)
+import Control.Monad.ST
+import Data.Array
+import Data.Array.MArray
+import Data.Array.ST
+import Data.Maybe (listToMaybe)
+import Data.STRef
+import Text.Pandoc.Definition hiding (Table)
+import qualified Text.Pandoc.Builder as B
+
+-- | A grid cell contains either a real table cell, or is the
+-- continuation of a column or row-spanning cell. In the latter case,
+-- the index of the continued cell is provided.
+data GridCell
+  = ContentCell Attr Alignment RowSpan ColSpan [Block]
+  | ContinuationCell CellIndex
+  | UnassignedCell
+  deriving (Show)
+
+-- | Row index in a table part.
+newtype RowIndex = RowIndex Int deriving (Enum, Eq, Ix, Ord, Show)
+-- | Column index in a table part.
+newtype ColIndex = ColIndex Int deriving (Enum, Eq, Ix, Ord, Show)
+
+-- | Index to a cell in a table part.
+type CellIndex = (RowIndex, ColIndex)
+
+-- | Cells are placed on a grid. Row attributes are stored in a separate
+-- array.
+data Part = Part
+  { partAttr :: Attr
+  , partCellArray :: Array (RowIndex,ColIndex) GridCell
+  , partRowAttrs  :: Array RowIndex Attr
+  }
+
+data Table = Table
+  { tableAttr     :: Attr
+  , tableCaption  :: Caption
+  , tableColSpecs :: Array ColIndex ColSpec
+  , tableRowHeads :: RowHeadColumns
+  , tableHead     :: Part
+  , tableBodies   :: [Part]
+  , tableFoot     :: Part
+  }
+
+toTable
+  :: B.Attr
+  -> B.Caption
+  -> [B.ColSpec]
+  -> B.TableHead
+  -> [B.TableBody]
+  -> B.TableFoot
+  -> Table
+toTable attr caption colSpecs thead' tbodies' tfoot' =
+  Table attr caption colSpecs' rowHeads thGrid tbGrids tfGrid
+  where
+    -- normalize in case it's invalid shape:
+    thead = B.normalizeTableHead numcols thead'
+    tbodies = map (B.normalizeTableBody numcols) tbodies'
+    tfoot = B.normalizeTableFoot numcols tfoot'
+    numcols = length colSpecs
+    colSpecs' = listArray (ColIndex 1, ColIndex numcols) colSpecs
+    rowHeads = case listToMaybe tbodies of
+      Nothing -> RowHeadColumns 0
+      Just (TableBody _attr rowHeadCols _headerRows _rows) -> rowHeadCols
+    thGrid = let (TableHead headAttr rows) = thead
+             in rowsToPart headAttr rows
+    tbGrids = map bodyToGrid tbodies
+    tfGrid = let (TableFoot footAttr rows) = tfoot
+             in rowsToPart footAttr rows
+    bodyToGrid (TableBody bodyAttr _rowHeadCols headRows rows) =
+      rowsToPart bodyAttr (headRows ++ rows)
+
+data BuilderCell
+  = FilledCell GridCell
+  | FreeCell
+
+fromBuilderCell :: BuilderCell -> GridCell
+fromBuilderCell = \case
+  FilledCell c -> c
+  FreeCell -> UnassignedCell
+
+rowsToPart :: Attr -> [B.Row] -> Part
+rowsToPart attr = \case
+  [] -> Part
+        attr
+        (listArray ((RowIndex 1, ColIndex 1), (RowIndex 0, ColIndex 0)) [])
+        (listArray (RowIndex 1, RowIndex 0) [])
+  rows@(Row _attr firstRow:_) ->
+    let nrows = length rows
+        ncols = sum $ map (\(Cell _ _ _ (ColSpan cs) _) -> cs) firstRow
+        gbounds = ((RowIndex 1, ColIndex 1), (RowIndex nrows, ColIndex ncols))
+        mutableGrid :: ST s (STArray s CellIndex GridCell)
+        mutableGrid = do
+          grid <- newArray gbounds FreeCell
+          ridx <- newSTRef (RowIndex 1)
+          forM_ rows $ \(Row _attr cells) -> do
+            cidx <- newSTRef (ColIndex 1)
+            forM_ cells $ \(Cell cellAttr align rs cs blks) -> do
+              ridx' <- readSTRef ridx
+              let nextFreeInRow colindex@(ColIndex c) = do
+                    let idx = (ridx', colindex)
+                    if gbounds `inRange` idx
+                      then readArray grid idx >>= \case
+                             FreeCell -> pure (Just colindex)
+                             _ -> nextFreeInRow $ ColIndex (c + 1)
+                      else pure Nothing  -- invalid table
+              mcidx' <- readSTRef cidx >>= nextFreeInRow
+              -- If there is a FreeCell in the current row, then fill it
+              -- with the current cell and mark cells in this and the
+              -- following rows as continuation cells if necessary.
+              --
+              -- Just skip the current table cell if no FreeCell was
+              -- found; this can only happen with invalid tables.
+              case mcidx' of
+                Nothing -> pure () -- no FreeCell left in row -- skip cell
+                Just cidx' -> do
+                  writeArray grid (ridx', cidx') . FilledCell $
+                    ContentCell cellAttr align rs cs blks
+                  forM_ (continuationIndices ridx' cidx' rs cs) $ \idx -> do
+                    writeArray grid idx . FilledCell $
+                      ContinuationCell (ridx', cidx')
+                  -- go to new column
+                  writeSTRef cidx cidx'
+            -- go to next row
+            modifySTRef ridx (incrRowIndex 1)
+          -- Swap BuilderCells with normal GridCells.
+          mapArray fromBuilderCell grid
+    in Part
+       { partCellArray = runSTArray mutableGrid
+       , partRowAttrs = listArray (RowIndex 1, RowIndex nrows) $
+                        map (\(Row rowAttr _) -> rowAttr) rows
+       , partAttr = attr
+       }
+
+continuationIndices :: RowIndex -> ColIndex -> RowSpan -> ColSpan -> [CellIndex]
+continuationIndices (RowIndex ridx) (ColIndex cidx) rowspan colspan =
+  let (RowSpan rs) = rowspan
+      (ColSpan cs) = colspan
+  in [ (RowIndex r, ColIndex c) | r <- [ridx..(ridx + rs - 1)]
+                                , c <- [cidx..(cidx + cs - 1)]
+                                , (r, c) /= (ridx, cidx)]
+
+rowArray :: RowIndex -> Array CellIndex GridCell -> Array ColIndex GridCell
+rowArray ridx grid =
+  let ((_minRidx, minCidx), (_maxRidx, maxCidx)) = bounds grid
+  in ixmap (minCidx, maxCidx) (ridx,) grid
+
+incrRowIndex :: RowSpan -> RowIndex -> RowIndex
+incrRowIndex (RowSpan n) (RowIndex r) = RowIndex $ r + n
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
@@ -1,1422 +1,1834 @@
-{-# LANGUAGE CPP                 #-}
-{-# LANGUAGE OverloadedStrings   #-}
-{-# LANGUAGE ScopedTypeVariables #-}
-{-# LANGUAGE ViewPatterns        #-}
-{-
-Copyright (C) 2006-2017 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-2017 John MacFarlane
-   License     : GNU GPL, version 2 or above
-
-   Maintainer  : John MacFarlane <jgm@berkeley.edu>
-   Stability   : alpha
-   Portability : portable
-
-Conversion of 'Pandoc' documents to HTML.
--}
-module Text.Pandoc.Writers.HTML (
-  writeHtml4,
-  writeHtml4String,
-  writeHtml5,
-  writeHtml5String,
-  writeHtmlStringForEPUB,
-  writeS5,
-  writeSlidy,
-  writeSlideous,
-  writeDZSlides,
-  writeRevealJs,
-  tagWithAttributes
-  ) where
-import Control.Monad.State.Strict
-import Data.Char (ord, toLower)
-import Data.List (intercalate, intersperse, isPrefixOf, partition)
-import Data.Maybe (catMaybes, fromMaybe, isJust, isNothing)
-import Data.Monoid ((<>))
-import qualified Data.Set as Set
-import Data.String (fromString)
-import Data.Text (Text)
-import qualified Data.Text.Lazy as TL
-import Network.HTTP (urlEncode)
-import Network.URI (URI (..), parseURIReference, unEscapeString)
-import Numeric (showHex)
-import Text.Blaze.Internal (customLeaf, MarkupM(Empty))
-import Text.Blaze.Html hiding (contents)
-import Text.Pandoc.Definition
-import Text.Pandoc.Highlighting (formatHtmlBlock, formatHtmlInline, highlight,
-                                 styleToCss)
-import Text.Pandoc.ImageSize
-import Text.Pandoc.Options
-import Text.Pandoc.Shared
-import Text.Pandoc.Slides
-import Text.Pandoc.Templates
-import Text.Pandoc.Walk
-import Text.Pandoc.Writers.Math
-import Text.Pandoc.Writers.Shared
-import Text.Pandoc.XML (escapeStringForXML, fromEntities)
-#if MIN_VERSION_blaze_markup(0,6,3)
-#else
-import Text.Blaze.Internal (preEscapedString, preEscapedText)
-#endif
-#if MIN_VERSION_blaze_html(0,5,1)
-import qualified Text.Blaze.XHtml5 as H5
-#else
-import qualified Text.Blaze.Html5 as H5
-#endif
-import Control.Monad.Except (throwError)
-import Data.Aeson (Value)
-import System.FilePath (takeBaseName, takeExtension)
-import Text.Blaze.Html.Renderer.Text (renderHtml)
-import qualified Text.Blaze.XHtml1.Transitional as H
-import qualified Text.Blaze.XHtml1.Transitional.Attributes as A
-import Text.Pandoc.Class (PandocMonad, report, runPure)
-import Text.Pandoc.Error
-import Text.Pandoc.Logging
-import Text.TeXMath
-import Text.XML.Light (elChildren, unode, unqual)
-import qualified Text.XML.Light as XML
-import Text.XML.Light.Output
-
-data WriterState = WriterState
-    { stNotes        :: [Html]  -- ^ List of notes
-    , stMath         :: Bool    -- ^ Math is used in document
-    , stQuotes       :: Bool    -- ^ <q> tag is used
-    , stHighlighting :: Bool    -- ^ Syntax highlighting is used
-    , stSecNum       :: [Int]   -- ^ Number of current section
-    , stElement      :: Bool    -- ^ Processing an Element
-    , stHtml5        :: Bool    -- ^ Use HTML5
-    , stEPUBVersion  :: Maybe EPUBVersion -- ^ EPUB version if for epub
-    , stSlideVariant :: HTMLSlideVariant
-    , stCodeBlockNum :: Int     -- ^ Number of code block
-    }
-
-defaultWriterState :: WriterState
-defaultWriterState = WriterState {stNotes= [], stMath = False, stQuotes = False,
-                                  stHighlighting = False, stSecNum = [],
-                                  stElement = False, stHtml5 = False,
-                                  stEPUBVersion = Nothing,
-                                  stSlideVariant = NoSlides,
-                                  stCodeBlockNum = 0}
-
--- Helpers to render HTML with the appropriate function.
-
-strToHtml :: String -> Html
-strToHtml ('\'':xs) = preEscapedString "\'" `mappend` strToHtml xs
-strToHtml xs@(_:_)  = case break (=='\'') xs of
-                           (_ ,[]) -> toHtml xs
-                           (ys,zs) -> toHtml ys `mappend` strToHtml zs
-strToHtml [] = ""
-
--- | Hard linebreak.
-nl :: WriterOptions -> Html
-nl opts = if writerWrapText opts == WrapNone
-             then mempty
-             else preEscapedString "\n"
-
--- | Convert Pandoc document to Html 5 string.
-writeHtml5String :: PandocMonad m => WriterOptions -> Pandoc -> m Text
-writeHtml5String = writeHtmlString'
-                      defaultWriterState{ stHtml5 = True }
-
--- | Convert Pandoc document to Html 5 structure.
-writeHtml5 :: PandocMonad m => WriterOptions -> Pandoc -> m Html
-writeHtml5 = writeHtml' defaultWriterState{ stHtml5 = True }
-
--- | Convert Pandoc document to Html 4 string.
-writeHtml4String :: PandocMonad m => WriterOptions -> Pandoc -> m Text
-writeHtml4String = writeHtmlString'
-                      defaultWriterState{ stHtml5 = False }
-
--- | Convert Pandoc document to Html 4 structure.
-writeHtml4 :: PandocMonad m => WriterOptions -> Pandoc -> m Html
-writeHtml4 = writeHtml' defaultWriterState{ stHtml5 = False }
-
--- | Convert Pandoc document to Html appropriate for an epub version.
-writeHtmlStringForEPUB :: PandocMonad m
-                       => EPUBVersion -> WriterOptions -> Pandoc
-                       -> m Text
-writeHtmlStringForEPUB version o = writeHtmlString'
-                      defaultWriterState{ stHtml5 = version == EPUB3,
-                                          stEPUBVersion = Just version } o
-
--- | Convert Pandoc document to Reveal JS HTML slide show.
-writeRevealJs :: PandocMonad m
-              => WriterOptions -> Pandoc -> m Text
-writeRevealJs = writeHtmlSlideShow' RevealJsSlides
-
--- | Convert Pandoc document to S5 HTML slide show.
-writeS5 :: PandocMonad m
-        => WriterOptions -> Pandoc -> m Text
-writeS5 = writeHtmlSlideShow' S5Slides
-
--- | Convert Pandoc document to Slidy HTML slide show.
-writeSlidy :: PandocMonad m
-           => WriterOptions -> Pandoc -> m Text
-writeSlidy = writeHtmlSlideShow' SlidySlides
-
--- | Convert Pandoc document to Slideous HTML slide show.
-writeSlideous :: PandocMonad m
-              => WriterOptions -> Pandoc -> m Text
-writeSlideous = writeHtmlSlideShow' SlideousSlides
-
--- | Convert Pandoc document to DZSlides HTML slide show.
-writeDZSlides :: PandocMonad m
-              => WriterOptions -> Pandoc -> m Text
-writeDZSlides = writeHtmlSlideShow' DZSlides
-
-writeHtmlSlideShow' :: PandocMonad m
-                    => HTMLSlideVariant -> WriterOptions -> Pandoc -> m Text
-writeHtmlSlideShow' variant = writeHtmlString'
-    defaultWriterState{ stSlideVariant = variant
-                      , stHtml5 = case variant of
-                                       RevealJsSlides -> True
-                                       S5Slides       -> False
-                                       SlidySlides    -> False
-                                       DZSlides       -> True
-                                       SlideousSlides -> False
-                                       NoSlides       -> False
-                      }
-
-renderHtml' :: Html -> Text
-renderHtml' = TL.toStrict . renderHtml
-
-writeHtmlString' :: PandocMonad m
-                 => WriterState -> WriterOptions -> Pandoc -> m Text
-writeHtmlString' st opts d = do
-  (body, context) <- evalStateT (pandocToHtml opts d) st
-  case writerTemplate opts of
-       Nothing -> return $ renderHtml' body
-       Just tpl -> do
-         -- warn if empty lang
-         when (isNothing (getField "lang" context :: Maybe String)) $
-           report NoLangSpecified
-         -- check for empty pagetitle
-         context' <-
-            case getField "pagetitle" context of
-                 Just (s :: String) | not (null s) -> return context
-                 _ -> do
-                   let fallback = fromMaybe "Untitled" $ takeBaseName <$>
-                           lookup "sourcefile" (writerVariables opts)
-                   report $ NoTitleElement fallback
-                   return $ resetField "pagetitle" fallback context
-         renderTemplate' tpl $
-                    defField "body" (renderHtml' body) context'
-
-writeHtml' :: PandocMonad m => WriterState -> WriterOptions -> Pandoc -> m Html
-writeHtml' st opts d =
-  case writerTemplate opts of
-       Just _ -> preEscapedText <$> writeHtmlString' st opts d
-       Nothing  -> do
-        (body, _) <- evalStateT (pandocToHtml opts d) st
-        return body
-
--- result is (title, authors, date, toc, body, new variables)
-pandocToHtml :: PandocMonad m
-             => WriterOptions
-             -> Pandoc
-             -> StateT WriterState m (Html, Value)
-pandocToHtml opts (Pandoc meta blocks) = do
-  metadata <- metaToJSON opts
-              (fmap renderHtml' . blockListToHtml opts)
-              (fmap renderHtml' . inlineListToHtml opts)
-              meta
-  let stringifyHTML = escapeStringForXML . stringify
-  let authsMeta = map stringifyHTML $ docAuthors meta
-  let dateMeta  = stringifyHTML $ docDate meta
-  let slideLevel = fromMaybe (getSlideLevel blocks) $ writerSlideLevel opts
-  slideVariant <- gets stSlideVariant
-  let sects = hierarchicalize $
-              if slideVariant == NoSlides
-                 then blocks
-                 else prepSlides slideLevel blocks
-  toc <- if writerTableOfContents opts && slideVariant /= S5Slides
-            then fmap renderHtml' <$> tableOfContents opts sects
-            else return Nothing
-  blocks' <- liftM (mconcat . intersperse (nl opts)) $
-                 mapM (elementToHtml slideLevel opts) sects
-  st <- get
-  notes <- footnoteSection opts (reverse (stNotes st))
-  let thebody = blocks' >> notes
-  let  math = case writerHTMLMathMethod opts of
-                      LaTeXMathML (Just url) ->
-                         H.script ! A.src (toValue url)
-                                  ! A.type_ "text/javascript"
-                                  $ mempty
-                      MathJax url
-                        | slideVariant /= RevealJsSlides ->
-                        -- mathjax is handled via a special plugin in revealjs
-                         H.script ! A.src (toValue url)
-                                  ! A.type_ "text/javascript"
-                                  $ case slideVariant of
-                                         SlideousSlides ->
-                                            preEscapedString
-                                            "MathJax.Hub.Queue([\"Typeset\",MathJax.Hub]);"
-                                         _ -> mempty
-                      JsMath (Just url) ->
-                         H.script ! A.src (toValue url)
-                                  ! A.type_ "text/javascript"
-                                  $ mempty
-                      KaTeX url ->
-                         (H.script !
-                           A.src (toValue $ url ++ "katex.min.js") $ mempty) <>
-                         (H.script !
-                           A.src (toValue $ url ++ "contrib/auto-render.min.js")
-                             $ mempty) <>
-                         (
-                                  H.script
-                            "document.addEventListener(\"DOMContentLoaded\", function() {\n  renderMathInElement(document.body);\n});") <>
-                         (H.link ! A.rel "stylesheet" !
-                           A.href (toValue $ url ++ "katex.min.css"))
-
-                      _ -> case lookup "mathml-script" (writerVariables opts) of
-                                 Just s | not (stHtml5 st) ->
-                                   H.script ! A.type_ "text/javascript"
-                                      $ preEscapedString
-                                       ("/*<![CDATA[*/\n" ++ s ++ "/*]]>*/\n")
-                                        | otherwise -> mempty
-                                 Nothing -> mempty
-  let context =   (if stHighlighting st
-                      then case writerHighlightStyle opts of
-                                Just sty -> defField "highlighting-css"
-                                              (styleToCss sty)
-                                Nothing  -> id
-                      else id) $
-                  (if stMath st
-                      then defField "math" (renderHtml' math)
-                      else id) $
-                  defField "mathjax"
-                      (case writerHTMLMathMethod opts of
-                            MathJax _ -> True
-                            _         -> False) $
-                  defField "quotes" (stQuotes st) $
-                  -- for backwards compatibility we populate toc
-                  -- with the contents of the toc, rather than a
-                  -- boolean:
-                  maybe id (defField "toc") toc $
-                  maybe id (defField "table-of-contents") toc $
-                  defField "author-meta" authsMeta $
-                  maybe id (defField "date-meta") (normalizeDate dateMeta) $
-                  defField "pagetitle" (stringifyHTML (docTitle meta)) $
-                  defField "idprefix" (writerIdentifierPrefix opts) $
-                  -- these should maybe be set in pandoc.hs
-                  defField "slidy-url"
-                    ("https://www.w3.org/Talks/Tools/Slidy2" :: String) $
-                  defField "slideous-url" ("slideous" :: String) $
-                  defField "revealjs-url" ("reveal.js" :: String) $
-                  defField "s5-url" ("s5/default" :: String) $
-                  defField "html5" (stHtml5 st)
-                  metadata
-  return (thebody, context)
-
--- | Like Text.XHtml's identifier, but adds the writerIdentifierPrefix
-prefixedId :: WriterOptions -> String -> Attribute
-prefixedId opts s =
-  case s of
-    "" -> mempty
-    _  -> A.id $ toValue $ writerIdentifierPrefix opts ++ s
-
-toList :: PandocMonad m
-       => (Html -> Html)
-       -> WriterOptions
-       -> [Html]
-       -> StateT WriterState m Html
-toList listop opts items = do
-    slideVariant <- gets stSlideVariant
-    return $
-      if writerIncremental opts
-         then if slideVariant /= RevealJsSlides
-                 then  listop (mconcat items) ! A.class_ "incremental"
-                 else listop $ mconcat $ map (! A.class_ "fragment") items
-         else listop $ mconcat items
-
-unordList :: PandocMonad m
-          => WriterOptions -> [Html] -> StateT WriterState m Html
-unordList opts = toList H.ul opts . toListItems opts
-
-ordList :: PandocMonad m
-        => WriterOptions -> [Html] -> StateT WriterState m Html
-ordList opts = toList H.ol opts . toListItems opts
-
-defList :: PandocMonad m
-        => WriterOptions -> [Html] -> StateT WriterState m Html
-defList opts items = toList H.dl opts (items ++ [nl opts])
-
--- | Construct table of contents from list of elements.
-tableOfContents :: PandocMonad m => WriterOptions -> [Element] -> StateT WriterState m (Maybe Html)
-tableOfContents _ [] = return Nothing
-tableOfContents opts sects = do
-  contents  <- mapM (elementToListItem opts) sects
-  let tocList = catMaybes contents
-  if null tocList
-     then return Nothing
-     else Just <$> unordList opts tocList
-
--- | Convert section number to string
-showSecNum :: [Int] -> String
-showSecNum = intercalate "." . map show
-
--- | Converts an Element to a list item for a table of contents,
--- retrieving the appropriate identifier from state.
-elementToListItem :: PandocMonad m => WriterOptions -> Element -> StateT WriterState m (Maybe Html)
--- Don't include the empty headers created in slide shows
--- shows when an hrule is used to separate slides without a new title:
-elementToListItem _ (Sec _ _ _ [Str "\0"] _) = return Nothing
-elementToListItem opts (Sec lev num (id',classes,_) headerText subsecs)
-  | lev <= writerTOCDepth opts = do
-  let num' = zipWith (+) num (writerNumberOffset opts ++ repeat 0)
-  let sectnum = if writerNumberSections opts && not (null num) &&
-                   "unnumbered" `notElem` classes
-                   then (H.span ! A.class_ "toc-section-number"
-                        $ toHtml $ showSecNum num') >> preEscapedString " "
-                   else mempty
-  txt <- liftM (sectnum >>) $ inlineListToHtml opts $ walk deNote headerText
-  subHeads <- mapM (elementToListItem opts) subsecs >>= return . catMaybes
-  subList <- if null subHeads
-                then return mempty
-                else unordList opts subHeads
-  -- in reveal.js, we need #/apples, not #apples:
-  slideVariant <- gets stSlideVariant
-  let revealSlash = ['/' | slideVariant== RevealJsSlides]
-  return $ Just
-         $ if null id'
-              then  H.a (toHtml txt) >> subList
-              else (H.a ! A.href (toValue $ "#" ++ revealSlash ++
-                    writerIdentifierPrefix opts ++ id')
-                       $ toHtml txt) >> subList
-elementToListItem _ _ = return Nothing
-
--- | Convert an Element to Html.
-elementToHtml :: PandocMonad m => Int -> WriterOptions -> Element -> StateT WriterState m Html
-elementToHtml _slideLevel opts (Blk block) = blockToHtml opts block
-elementToHtml slideLevel opts (Sec level num (id',classes,keyvals) title' elements) = do
-  slideVariant <- gets stSlideVariant
-  let slide = slideVariant /= NoSlides && level <= slideLevel
-  let num' = zipWith (+) num (writerNumberOffset opts ++ repeat 0)
-  modify $ \st -> st{stSecNum = num'}  -- update section number
-  html5 <- gets stHtml5
-  let titleSlide = slide && level < slideLevel
-  header' <- if title' == [Str "\0"]  -- marker for hrule
-                then return mempty
-                else do
-                  modify (\st -> st{ stElement = True})
-                  let level' = if level <= slideLevel &&
-                                  slideVariant == SlidySlides
-                                  then 1 -- see #3566
-                                  else level
-                  res <- blockToHtml opts
-                           (Header level' (id',classes,keyvals) title')
-                  modify (\st -> st{ stElement = False})
-                  return res
-
-  let isSec (Sec{}) = True
-      isSec (Blk _) = False
-  let isPause (Blk x) = x == Para [Str ".",Space,Str ".",Space,Str "."]
-      isPause _       = False
-  let fragmentClass = case slideVariant of
-                           RevealJsSlides -> "fragment"
-                           _              -> "incremental"
-  let inDiv xs = Blk (RawBlock (Format "html") ("<div class=\""
-                       ++ fragmentClass ++ "\">")) :
-                   (xs ++ [Blk (RawBlock (Format "html") "</div>")])
-  innerContents <- mapM (elementToHtml slideLevel opts)
-                   $ if titleSlide
-                        -- title slides have no content of their own
-                        then filter isSec elements
-                        else case splitBy isPause elements of
-                                  []     -> []
-                                  (x:xs) -> x ++ concatMap inDiv xs
-  let inNl x = mconcat $ nl opts : intersperse (nl opts) x ++ [nl opts]
-  let classes' = ["title-slide" | titleSlide] ++ ["slide" | slide] ++
-                  ["section" | (slide || writerSectionDivs opts) &&
-                               not html5 ] ++
-                  ["level" ++ show level | slide || writerSectionDivs opts ]
-                  ++ classes
-  let secttag  = if html5
-                    then H5.section
-                    else H.div
-  let attr = (id',classes',keyvals)
-  if titleSlide
-     then do
-       t <- addAttrs opts attr $
-                   secttag header'
-       return $
-         (if slideVariant == RevealJsSlides
-                then H5.section
-                else id) $ mconcat $ t : innerContents
-     else if writerSectionDivs opts || slide
-          then addAttrs opts attr
-               $ secttag $ inNl $ header' : innerContents
-          else do
-            t <- addAttrs opts attr header'
-            return $ mconcat $ intersperse (nl opts) (t : innerContents)
-
--- | Convert list of Note blocks to a footnote <div>.
--- Assumes notes are sorted.
-footnoteSection :: PandocMonad m
-                => WriterOptions -> [Html] -> StateT WriterState m Html
-footnoteSection opts notes = do
-  html5 <- gets stHtml5
-  slideVariant <- gets stSlideVariant
-  let hrtag = if html5 then H5.hr else H.hr
-  let container x
-        | html5 = H5.section ! A.class_ "footnotes" $ x
-        | slideVariant /= NoSlides = H.div ! A.class_ "footnotes slide" $ x
-        | otherwise = H.div ! A.class_ "footnotes" $ x
-  return $
-    if null notes
-       then mempty
-       else nl opts >> container (nl opts >> hrtag >> nl opts >>
-              H.ol (mconcat notes >> nl opts) >> nl opts)
-
--- | Parse a mailto link; return Just (name, domain) or Nothing.
-parseMailto :: String -> Maybe (String, String)
-parseMailto s =
-  case break (==':') s of
-       (xs,':':addr) | map toLower xs == "mailto" -> do
-         let (name', rest) = span (/='@') addr
-         let domain = drop 1 rest
-         return (name', domain)
-       _ -> fail "not a mailto: URL"
-
--- | Obfuscate a "mailto:" link.
-obfuscateLink :: PandocMonad m
-              => WriterOptions -> Attr -> Html -> String
-              -> StateT WriterState m Html
-obfuscateLink opts attr txt s | writerEmailObfuscation opts == NoObfuscation =
-  addAttrs opts attr $ H.a ! A.href (toValue s) $ txt
-obfuscateLink opts attr (TL.unpack . renderHtml -> txt) s =
-  let meth = writerEmailObfuscation opts
-      s' = map toLower (take 7 s) ++ drop 7 s
-  in  case parseMailto s' of
-        (Just (name', domain)) ->
-          let domain'  = substitute "." " dot " domain
-              at'      = obfuscateChar '@'
-              (linkText, altText) =
-                 if txt == drop 7 s' -- autolink
-                    then ("e", name' ++ " at " ++ domain')
-                    else ("'" ++ obfuscateString txt ++ "'",
-                          txt ++ " (" ++ name' ++ " at " ++ domain' ++ ")")
-              (_, classNames, _) = attr
-              classNamesStr = concatMap (' ':) classNames
-          in  case meth of
-                ReferenceObfuscation ->
-                     -- need to use preEscapedString or &'s are escaped to &amp; in URL
-                     return $
-                     preEscapedString $ "<a href=\"" ++ obfuscateString s'
-                     ++ "\" class=\"email\">" ++ obfuscateString txt ++ "</a>"
-                JavascriptObfuscation ->
-                     return $
-                     (H.script ! A.type_ "text/javascript" $
-                     preEscapedString ("\n<!--\nh='" ++
-                     obfuscateString domain ++ "';a='" ++ at' ++ "';n='" ++
-                     obfuscateString name' ++ "';e=n+a+h;\n" ++
-                     "document.write('<a h'+'ref'+'=\"ma'+'ilto'+':'+e+'\" clas'+'s=\"em' + 'ail" ++
-                     classNamesStr ++ "\">'+" ++
-                     linkText  ++ "+'<\\/'+'a'+'>');\n// -->\n")) >>
-                     H.noscript (preEscapedString $ obfuscateString altText)
-                _ -> throwError $ PandocSomeError $ "Unknown obfuscation method: " ++ show meth
-        _ -> addAttrs opts attr $ H.a ! A.href (toValue s) $ toHtml txt  -- malformed email
-
--- | Obfuscate character as entity.
-obfuscateChar :: Char -> String
-obfuscateChar char =
-  let num    = ord char
-      numstr = if even num then show num else "x" ++ showHex num ""
-  in  "&#" ++ numstr ++ ";"
-
--- | Obfuscate string using entities.
-obfuscateString :: String -> String
-obfuscateString = concatMap obfuscateChar . fromEntities
-
--- | Create HTML tag with attributes.
-tagWithAttributes :: WriterOptions
-                  -> Bool -- ^ True for HTML5
-                  -> Bool -- ^ True if self-closing tag
-                  -> Text -- ^ Tag text
-                  -> Attr -- ^ Pandoc style tag attributes
-                  -> Text
-tagWithAttributes opts html5 selfClosing tagname attr =
-  let mktag = (TL.toStrict . renderHtml <$> evalStateT
-               (addAttrs opts attr (customLeaf (textTag tagname) selfClosing))
-               defaultWriterState{ stHtml5 = html5 })
-  in  case runPure mktag of
-           Left _  -> mempty
-           Right t -> t
-
-addAttrs :: PandocMonad m
-         => WriterOptions -> Attr -> Html -> StateT WriterState m Html
-addAttrs opts attr h = foldl (!) h <$> attrsToHtml opts attr
-
-toAttrs :: PandocMonad m
-        => [(String, String)] -> StateT WriterState m [Attribute]
-toAttrs kvs = do
-  html5 <- gets stHtml5
-  return $ map (\(x,y) ->
-     customAttribute
-        (fromString (if not html5 || x `Set.member` html5Attributes
-                                  || "data-" `isPrefixOf` x
-                        then x
-                        else "data-" ++ x)) (toValue y)) kvs
-
-attrsToHtml :: PandocMonad m
-            => WriterOptions -> Attr -> StateT WriterState m [Attribute]
-attrsToHtml opts (id',classes',keyvals) = do
-  attrs <- toAttrs keyvals
-  return $
-    [prefixedId opts id' | not (null id')] ++
-    [A.class_ (toValue $ unwords classes') | not (null classes')] ++ attrs
-
-imgAttrsToHtml :: PandocMonad m
-               => WriterOptions -> Attr -> StateT WriterState m [Attribute]
-imgAttrsToHtml opts attr = do
-  attrs <- attrsToHtml opts (ident,cls,kvs')
-  dimattrs <- toAttrs (dimensionsToAttrList attr)
-  return $ attrs ++ dimattrs
-  where
-    (ident,cls,kvs) = attr
-    kvs' = filter isNotDim kvs
-    isNotDim ("width", _)  = False
-    isNotDim ("height", _) = False
-    isNotDim _             = True
-
-dimensionsToAttrList :: Attr -> [(String, String)]
-dimensionsToAttrList attr = consolidateStyles $ go Width ++ go Height
-  where
-    consolidateStyles :: [(String, String)] -> [(String, String)]
-    consolidateStyles xs =
-      case partition isStyle xs of
-           ([], _)    -> xs
-           (ss, rest) -> ("style", intercalate ";" $ map snd ss) : rest
-    isStyle ("style", _) = True
-    isStyle _            = False
-    go dir = case dimension dir attr of
-               (Just (Pixel a)) -> [(show dir, show a)]
-               (Just x)         -> [("style", show dir ++ ":" ++ show x)]
-               Nothing          -> []
-
-imageExts :: [String]
-imageExts = [ "art", "bmp", "cdr", "cdt", "cpt", "cr2", "crw", "djvu", "erf",
-              "gif", "ico", "ief", "jng", "jpg", "jpeg", "nef", "orf", "pat", "pbm",
-              "pcx", "pgm", "png", "pnm", "ppm", "psd", "ras", "rgb", "svg", "tiff",
-              "wbmp", "xbm", "xpm", "xwd" ]
-
-treatAsImage :: FilePath -> Bool
-treatAsImage fp =
-  let path = fromMaybe fp (uriPath `fmap` parseURIReference fp)
-      ext  = map toLower $ drop 1 $ takeExtension path
-  in  null ext || ext `elem` imageExts
-
-figure :: PandocMonad m
-       => WriterOptions -> Attr -> [Inline] -> (String, String)
-       -> StateT WriterState m Html
-figure opts attr txt (s,tit) = do
-  img <- inlineToHtml opts (Image attr txt (s,tit))
-  html5 <- gets stHtml5
-  let tocapt = if html5
-                  then H5.figcaption
-                  else H.p ! A.class_ "caption"
-  capt <- if null txt
-             then return mempty
-             else tocapt `fmap` inlineListToHtml opts txt
-  return $ if html5
-              then H5.figure $ mconcat
-                    [nl opts, img, capt, nl opts]
-              else H.div ! A.class_ "figure" $ mconcat
-                    [nl opts, img, nl opts, capt, nl opts]
-
--- | Convert Pandoc block element to HTML.
-blockToHtml :: PandocMonad m => WriterOptions -> Block -> StateT WriterState m Html
-blockToHtml _ Null = return mempty
-blockToHtml opts (Plain lst) = inlineListToHtml opts lst
-blockToHtml opts (Para [Image attr@(_,classes,_) txt (src,tit)])
-  | "stretch" `elem` classes = do
-  slideVariant <- gets stSlideVariant
-  case slideVariant of
-       RevealJsSlides ->
-         -- a "stretched" image in reveal.js must be a direct child
-         -- of the slide container
-         inlineToHtml opts (Image attr txt (src, tit))
-       _ -> figure opts attr txt (src, tit)
--- title beginning with fig: indicates that the image is a figure
-blockToHtml opts (Para [Image attr txt (s,'f':'i':'g':':':tit)]) =
-  figure opts attr txt (s,tit)
-blockToHtml opts (Para lst)
-  | isEmptyRaw lst = return mempty
-  | null lst && not (isEnabled Ext_empty_paragraphs opts) = return mempty
-  | otherwise = do
-      contents <- inlineListToHtml opts lst
-      return $ H.p contents
-  where
-    isEmptyRaw [RawInline f _] = f `notElem` [Format "html",
-                                    Format "html4", Format "html5"]
-    isEmptyRaw _               = False
-blockToHtml opts (LineBlock lns) =
-  if writerWrapText opts == WrapNone
-  then blockToHtml opts $ linesToPara lns
-  else do
-    htmlLines <- inlineListToHtml opts $ intercalate [LineBreak] lns
-    return $ H.div ! A.class_ "line-block" $ htmlLines
-blockToHtml opts (Div attr@(ident, classes, kvs') bs) = do
-  html5 <- gets stHtml5
-  let kvs = [(k,v) | (k,v) <- kvs', k /= "width"] ++
-            [("style", "width:" ++ w ++ ";")
-             | ("width",w) <- kvs', "column" `elem` classes]
-  let speakerNotes = "notes" `elem` classes
-  -- we don't want incremental output inside speaker notes, see #1394
-  let opts' = if speakerNotes then opts{ writerIncremental = False } else opts
-  contents <- if "columns" `elem` classes
-                 then -- we don't use blockListToHtml because it inserts
-                      -- a newline between the column divs, which throws
-                      -- off widths! see #4028
-                      mconcat <$> mapM (blockToHtml opts) bs
-                 else blockListToHtml opts' bs
-  let contents' = nl opts >> contents >> nl opts
-  let (divtag, classes') = if html5 && "section" `elem` classes
-                              then (H5.section, filter (/= "section") classes)
-                              else (H.div, classes)
-  slideVariant <- gets stSlideVariant
-  if speakerNotes
-     then case slideVariant of
-               RevealJsSlides -> addAttrs opts' attr $
-                           H5.aside contents'
-               DZSlides       -> do
-                 t <- addAttrs opts' attr $
-                             H5.div contents'
-                 return $ t ! H5.customAttribute "role" "note"
-               NoSlides       -> addAttrs opts' attr $
-                           H.div contents'
-               _              -> return mempty
-     else addAttrs opts (ident, classes', kvs) $
-              divtag contents'
-blockToHtml opts (RawBlock f str) = do
-  ishtml <- isRawHtml f
-  if ishtml
-     then return $ preEscapedString str
-     else if (f == Format "latex" || f == Format "tex") &&
-             allowsMathEnvironments (writerHTMLMathMethod opts) &&
-             isMathEnvironment str
-             then blockToHtml opts $ Plain [Math DisplayMath str]
-             else do
-               report $ BlockNotRendered (RawBlock f str)
-               return mempty
-blockToHtml _ HorizontalRule = do
-  html5 <- gets stHtml5
-  return $ if html5 then H5.hr else H.hr
-blockToHtml opts (CodeBlock (id',classes,keyvals) rawCode) = do
-  id'' <- if null id'
-             then do
-               modify $ \st -> st{ stCodeBlockNum = stCodeBlockNum st + 1 }
-               codeblocknum <- gets stCodeBlockNum
-               return ("cb" ++ show codeblocknum)
-             else return id'
-  let tolhs = isEnabled Ext_literate_haskell opts &&
-                any (\c -> map toLower c == "haskell") classes &&
-                any (\c -> map toLower c == "literate") classes
-      classes' = if tolhs
-                    then map (\c -> if map toLower c == "haskell"
-                                       then "literatehaskell"
-                                       else c) classes
-                    else classes
-      adjCode  = if tolhs
-                    then unlines . map ("> " ++) . lines $ rawCode
-                    else rawCode
-      hlCode   = if isJust (writerHighlightStyle opts)
-                    then highlight (writerSyntaxMap opts) formatHtmlBlock
-                            (id'',classes',keyvals) adjCode
-                    else Left ""
-  case hlCode of
-         Left msg -> do
-           unless (null msg) $
-             report $ CouldNotHighlight msg
-           addAttrs opts (id',classes,keyvals)
-             $ H.pre $ H.code $ toHtml adjCode
-         Right h -> modify (\st -> st{ stHighlighting = True }) >>
-                    addAttrs opts (id'',[],keyvals) h
-blockToHtml opts (BlockQuote blocks) = do
-  -- in S5, treat list in blockquote specially
-  -- if default is incremental, make it nonincremental;
-  -- otherwise incremental
-  slideVariant <- gets stSlideVariant
-  if slideVariant /= NoSlides
-     then let inc = not (writerIncremental opts) in
-          case blocks of
-             [BulletList lst]  -> blockToHtml (opts {writerIncremental = inc})
-                                  (BulletList lst)
-             [OrderedList attribs lst] ->
-                                  blockToHtml (opts {writerIncremental = inc})
-                                  (OrderedList attribs lst)
-             [DefinitionList lst] ->
-                                  blockToHtml (opts {writerIncremental = inc})
-                                  (DefinitionList lst)
-             _                 -> do contents <- blockListToHtml opts blocks
-                                     return $ H.blockquote
-                                            $ nl opts >> contents >> nl opts
-     else do
-       contents <- blockListToHtml opts blocks
-       return $ H.blockquote $ nl opts >> contents >> nl opts
-blockToHtml opts (Header level attr@(_,classes,_) lst) = do
-  contents <- inlineListToHtml opts lst
-  secnum <- liftM stSecNum get
-  let contents' = if writerNumberSections opts && not (null secnum)
-                     && "unnumbered" `notElem` classes
-                     then (H.span ! A.class_ "header-section-number" $ toHtml
-                          $ showSecNum secnum) >> strToHtml " " >> contents
-                     else contents
-  inElement <- gets stElement
-  (if inElement then return else addAttrs opts attr)
-         $ case level of
-              1 -> H.h1 contents'
-              2 -> H.h2 contents'
-              3 -> H.h3 contents'
-              4 -> H.h4 contents'
-              5 -> H.h5 contents'
-              6 -> H.h6 contents'
-              _ -> H.p contents'
-blockToHtml opts (BulletList lst) = do
-  contents <- mapM (blockListToHtml opts) lst
-  unordList opts contents
-blockToHtml opts (OrderedList (startnum, numstyle, _) lst) = do
-  contents <- mapM (blockListToHtml opts) lst
-  html5 <- gets stHtml5
-  let numstyle' = case numstyle of
-                       Example -> "decimal"
-                       _       -> camelCaseToHyphenated $ show numstyle
-  let attribs = ([A.start $ toValue startnum | startnum /= 1]) ++
-                ([A.class_ "example" | numstyle == Example]) ++
-                (if numstyle /= DefaultStyle
-                   then if html5
-                           then [A.type_ $
-                                 case numstyle of
-                                      Decimal    -> "1"
-                                      LowerAlpha -> "a"
-                                      UpperAlpha -> "A"
-                                      LowerRoman -> "i"
-                                      UpperRoman -> "I"
-                                      _          -> "1"]
-                           else [A.style $ toValue $ "list-style-type: " ++
-                                   numstyle']
-                   else [])
-  l <- ordList opts contents
-  return $ foldl (!) l attribs
-blockToHtml opts (DefinitionList lst) = do
-  contents <- mapM (\(term, defs) ->
-                  do term' <- if null term
-                                 then return mempty
-                                 else liftM H.dt $ inlineListToHtml opts term
-                     defs' <- mapM (liftM (\x -> H.dd $ (x >> nl opts)) .
-                                    blockListToHtml opts) defs
-                     return $ mconcat $ nl opts : term' : nl opts :
-                                        intersperse (nl opts) defs') lst
-  defList opts contents
-blockToHtml opts (Table capt aligns widths headers rows') = do
-  captionDoc <- if null capt
-                   then return mempty
-                   else do
-                     cs <- inlineListToHtml opts capt
-                     return $ H.caption cs >> nl opts
-  html5 <- gets stHtml5
-  let percent w = show (truncate (100*w) :: Integer) ++ "%"
-  let coltags = if all (== 0.0) widths
-                   then mempty
-                   else do
-                     H.colgroup $ do
-                       nl opts
-                       mapM_ (\w -> do
-                            if html5
-                               then H.col ! A.style (toValue $ "width: " ++
-                                                      percent w)
-                               else H.col ! A.width (toValue $ percent w)
-                            nl opts) widths
-                     nl opts
-  head' <- if all null headers
-              then return mempty
-              else do
-                contents <- tableRowToHtml opts aligns 0 headers
-                return $ H.thead (nl opts >> contents) >> nl opts
-  body' <- liftM (\x -> H.tbody (nl opts >> mconcat x)) $
-               zipWithM (tableRowToHtml opts aligns) [1..] rows'
-  let tbl = H.table $
-              nl opts >> captionDoc >> coltags >> head' >> body' >> nl opts
-  let totalWidth = sum widths
-  -- When widths of columns are < 100%, we need to set width for the whole
-  -- table, or some browsers give us skinny columns with lots of space between:
-  return $ if totalWidth == 0 || totalWidth == 1
-              then tbl
-              else tbl ! A.style (toValue $ "width:" ++
-                              show (round (totalWidth * 100) :: Int) ++ "%;")
-
-tableRowToHtml :: PandocMonad m
-               => WriterOptions
-               -> [Alignment]
-               -> Int
-               -> [[Block]]
-               -> StateT WriterState m Html
-tableRowToHtml opts aligns rownum cols' = do
-  let mkcell = if rownum == 0 then H.th else H.td
-  let rowclass = case rownum of
-                      0 -> "header"
-                      x | x `rem` 2 == 1 -> "odd"
-                      _ -> "even"
-  cols'' <- zipWithM
-            (\alignment item -> tableItemToHtml opts mkcell alignment item)
-            aligns cols'
-  return $ (H.tr ! A.class_ rowclass $ nl opts >> mconcat cols'')
-          >> nl opts
-
-alignmentToString :: Alignment -> [Char]
-alignmentToString alignment = case alignment of
-                                 AlignLeft    -> "left"
-                                 AlignRight   -> "right"
-                                 AlignCenter  -> "center"
-                                 AlignDefault -> ""
-
-tableItemToHtml :: PandocMonad m
-                => WriterOptions
-                -> (Html -> Html)
-                -> Alignment
-                -> [Block]
-                -> StateT WriterState m Html
-tableItemToHtml opts tag' align' item = do
-  contents <- blockListToHtml opts item
-  html5 <- gets stHtml5
-  let alignStr = alignmentToString align'
-  let attribs = if html5
-                   then A.style (toValue $ "text-align: " ++ alignStr ++ ";")
-                   else A.align (toValue alignStr)
-  let tag'' = if null alignStr
-                 then tag'
-                 else tag' ! attribs
-  return $ tag'' contents >> nl opts
-
-toListItems :: WriterOptions -> [Html] -> [Html]
-toListItems opts items = map (toListItem opts) items ++ [nl opts]
-
-toListItem :: WriterOptions -> Html -> Html
-toListItem opts item = nl opts >> H.li item
-
-blockListToHtml :: PandocMonad m
-                => WriterOptions -> [Block] -> StateT WriterState m Html
-blockListToHtml opts lst =
-  (mconcat . intersperse (nl opts) . filter nonempty)
-    <$> mapM (blockToHtml opts) lst
-  where nonempty (Empty _) = False
-        nonempty _         = True
-
--- | Convert list of Pandoc inline elements to HTML.
-inlineListToHtml :: PandocMonad m => WriterOptions -> [Inline] -> StateT WriterState m Html
-inlineListToHtml opts lst =
-  mapM (inlineToHtml opts) lst >>= return . mconcat
-
--- | Annotates a MathML expression with the tex source
-annotateMML :: XML.Element -> String -> XML.Element
-annotateMML e tex = math (unode "semantics" [cs, unode "annotation" (annotAttrs, tex)])
-  where
-    cs = case elChildren e of
-          []  -> unode "mrow" ()
-          [x] -> x
-          xs  -> unode "mrow" xs
-    math childs = XML.Element q as [XML.Elem childs] l
-      where
-        (XML.Element q as _ l) = e
-    annotAttrs = [XML.Attr (unqual "encoding") "application/x-tex"]
-
-
--- | Convert Pandoc inline element to HTML.
-inlineToHtml :: PandocMonad m
-             => WriterOptions -> Inline -> StateT WriterState m Html
-inlineToHtml opts inline = do
-  html5 <- gets stHtml5
-  case inline of
-    (Str str)        -> return $ strToHtml str
-    Space          -> return $ strToHtml " "
-    SoftBreak      -> return $ case writerWrapText opts of
-                                     WrapNone     -> preEscapedString " "
-                                     WrapAuto     -> preEscapedString " "
-                                     WrapPreserve -> preEscapedString "\n"
-    LineBreak      -> return $ (if html5 then H5.br else H.br)
-                                 <> strToHtml "\n"
-    (Span (id',classes,kvs) ils)
-                     -> inlineListToHtml opts ils >>=
-                           addAttrs opts attr' . H.span
-                        where attr' = (id',classes',kvs')
-                              classes' = filter (`notElem` ["csl-no-emph",
-                                              "csl-no-strong",
-                                              "csl-no-smallcaps"]) classes
-                              kvs' = if null styles
-                                        then kvs
-                                        else ("style", concat styles) : kvs
-                              styles = ["font-style:normal;"
-                                         | "csl-no-emph" `elem` classes]
-                                    ++ ["font-weight:normal;"
-                                         | "csl-no-strong" `elem` classes]
-                                    ++ ["font-variant:normal;"
-                                         | "csl-no-smallcaps" `elem` classes]
-    (Emph lst)       -> inlineListToHtml opts lst >>= return . H.em
-    (Strong lst)     -> inlineListToHtml opts lst >>= return . H.strong
-    (Code attr str)  -> case hlCode of
-                             Left msg -> do
-                               unless (null msg) $
-                                 report $ CouldNotHighlight msg
-                               addAttrs opts attr $ H.code $ strToHtml str
-                             Right h -> do
-                               modify $ \st -> st{ stHighlighting = True }
-                               addAttrs opts (id',[],keyvals) h
-                        where (id',_,keyvals) = attr
-                              hlCode = if isJust (writerHighlightStyle opts)
-                                          then highlight
-                                                 (writerSyntaxMap opts)
-                                                 formatHtmlInline attr str
-                                          else Left ""
-    (Strikeout lst)  -> inlineListToHtml opts lst >>=
-                        return . H.del
-    (SmallCaps lst)   -> inlineListToHtml opts lst >>=
-                         return . (H.span ! A.class_ "smallcaps")
-    (Superscript lst) -> inlineListToHtml opts lst >>= return . H.sup
-    (Subscript lst)   -> inlineListToHtml opts lst >>= return . H.sub
-    (Quoted quoteType lst) ->
-                        let (leftQuote, rightQuote) = case quoteType of
-                              SingleQuote -> (strToHtml "‘",
-                                              strToHtml "’")
-                              DoubleQuote -> (strToHtml "“",
-                                              strToHtml "”")
-                        in  if writerHtmlQTags opts
-                               then do
-                                 modify $ \st -> st{ stQuotes = True }
-                                 H.q `fmap` inlineListToHtml opts lst
-                               else (\x -> leftQuote >> x >> rightQuote)
-                                    `fmap` inlineListToHtml opts lst
-    (Math t str) -> do
-      modify (\st -> st {stMath = True})
-      let mathClass = toValue $ ("math " :: String) ++
-                      if t == InlineMath then "inline" else "display"
-      case writerHTMLMathMethod opts of
-           LaTeXMathML _ ->
-              -- putting LaTeXMathML in container with class "LaTeX" prevents
-              -- non-math elements on the page from being treated as math by
-              -- the javascript
-              return $ H.span ! A.class_ "LaTeX" $
-                     case t of
-                       InlineMath  -> toHtml ("$" ++ str ++ "$")
-                       DisplayMath -> toHtml ("$$" ++ str ++ "$$")
-           JsMath _ -> do
-              let m = preEscapedString str
-              return $ case t of
-                       InlineMath  -> H.span ! A.class_ mathClass $ m
-                       DisplayMath -> H.div ! A.class_ mathClass $ m
-           WebTeX url -> do
-              let imtag = if html5 then H5.img else H.img
-              let m = imtag ! A.style "vertical-align:middle"
-                            ! A.src (toValue $ url ++ urlEncode str)
-                            ! A.alt (toValue str)
-                            ! A.title (toValue str)
-              let brtag = if html5 then H5.br else H.br
-              return $ case t of
-                        InlineMath  -> m
-                        DisplayMath -> brtag >> m >> brtag
-           GladTeX ->
-              return $ case t of
-                         InlineMath -> preEscapedString $ "<EQ ENV=\"math\">" ++ str ++ "</EQ>"
-                         DisplayMath -> preEscapedString $ "<EQ ENV=\"displaymath\">" ++ str ++ "</EQ>"
-           MathML -> do
-              let conf = useShortEmptyTags (const False)
-                           defaultConfigPP
-              res <- lift $ convertMath writeMathML t str
-              case res of
-                    Right r  -> return $ preEscapedString $
-                        ppcElement conf (annotateMML r str)
-                    Left il  -> (H.span ! A.class_ mathClass) <$>
-                                   inlineToHtml opts il
-           MathJax _ -> return $ H.span ! A.class_ mathClass $ toHtml $
-              case t of
-                InlineMath  -> "\\(" ++ str ++ "\\)"
-                DisplayMath -> "\\[" ++ str ++ "\\]"
-           KaTeX _ -> return $ H.span ! A.class_ mathClass $ toHtml $
-              case t of
-                InlineMath  -> "\\(" ++ str ++ "\\)"
-                DisplayMath -> "\\[" ++ str ++ "\\]"
-           PlainMath -> do
-              x <- lift (texMathToInlines t str) >>= inlineListToHtml opts
-              let m = H.span ! A.class_ mathClass $ x
-              let brtag = if html5 then H5.br else H.br
-              return  $ case t of
-                         InlineMath  -> m
-                         DisplayMath -> brtag >> m >> brtag
-    (RawInline f str) -> do
-      ishtml <- isRawHtml f
-      if ishtml
-         then return $ preEscapedString str
-         else if (f == Format "latex" || f == Format "tex") &&
-                "\\begin" `isPrefixOf` str &&
-                allowsMathEnvironments (writerHTMLMathMethod opts) &&
-                isMathEnvironment str
-                then inlineToHtml opts $ Math DisplayMath str
-                else do
-                  report $ InlineNotRendered inline
-                  return mempty
-    (Link attr txt (s,_)) | "mailto:" `isPrefixOf` s -> do
-                        linkText <- inlineListToHtml opts txt
-                        obfuscateLink opts attr linkText s
-    (Link (ident,classes,kvs) txt (s,tit)) -> do
-                        linkText <- inlineListToHtml opts txt
-                        slideVariant <- gets stSlideVariant
-                        let s' = case s of
-                                   '#':xs -> let prefix = if slideVariant == RevealJsSlides
-                                                             then "/"
-                                                             else writerIdentifierPrefix opts
-                                             in  '#' : prefix ++ xs
-                                   _ -> s
-                        let link = H.a ! A.href (toValue s') $ linkText
-                        let attr = if txt == [Str (unEscapeString s)]
-                                      then (ident, "uri" : classes, kvs)
-                                      else (ident, classes, kvs)
-                        link' <- addAttrs opts attr link
-                        return $ if null tit
-                                    then link'
-                                    else link' ! A.title (toValue tit)
-    (Image attr txt (s,tit)) | treatAsImage s -> do
-                        let alternate' = stringify txt
-                        slideVariant <- gets stSlideVariant
-                        let isReveal = slideVariant == RevealJsSlides
-                        attrs <- imgAttrsToHtml opts attr
-                        let attributes =
-                              -- reveal.js uses data-src for lazy loading
-                              (if isReveal
-                                  then customAttribute "data-src" $ toValue s
-                                  else A.src $ toValue s) :
-                              [A.title $ toValue tit | not (null tit)] ++
-                              [A.alt $ toValue alternate' | not (null txt)] ++
-                              attrs
-                        let tag = if html5 then H5.img else H.img
-                        return $ foldl (!) tag attributes
-                        -- note:  null title included, as in Markdown.pl
-    (Image attr _ (s,tit)) -> do
-                        slideVariant <- gets stSlideVariant
-                        let isReveal = slideVariant == RevealJsSlides
-                        attrs <- imgAttrsToHtml opts attr
-                        let attributes =
-                              (if isReveal
-                                  then customAttribute "data-src" $ toValue s
-                                  else A.src $ toValue s) :
-                              [A.title $ toValue tit | not (null tit)] ++
-                              attrs
-                        return $ foldl (!) H5.embed attributes
-                        -- note:  null title included, as in Markdown.pl
-    (Note contents) -> do
-                        notes <- gets stNotes
-                        let number = length notes + 1
-                        let ref = show number
-                        htmlContents <- blockListToNote opts ref contents
-                        epubVersion <- gets stEPUBVersion
-                        -- push contents onto front of notes
-                        modify $ \st -> st {stNotes = htmlContents:notes}
-                        slideVariant <- gets stSlideVariant
-                        let revealSlash = ['/' | slideVariant == RevealJsSlides]
-                        let link = H.a ! A.href (toValue $ "#" ++
-                                         revealSlash ++
-                                         writerIdentifierPrefix opts ++ "fn" ++ ref)
-                                       ! A.class_ "footnote-ref"
-                                       ! prefixedId opts ("fnref" ++ ref)
-                                       $ (if isJust epubVersion
-                                             then id
-                                             else H.sup)
-                                       $ toHtml ref
-                        return $ case epubVersion of
-                                      Just EPUB3 -> link ! customAttribute "epub:type" "noteref"
-                                      _          -> link
-    (Cite cits il)-> do contents <- inlineListToHtml opts 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 =
-  -- 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 "↩"] ("#" ++ writerIdentifierPrefix opts ++ "fnref" ++ ref,[])]
-      blocks'  = if null blocks
-                    then []
-                    else let lastBlock   = last blocks
-                             otherBlocks = init blocks
-                         in  case lastBlock of
-                                  (Para lst)  -> otherBlocks ++
-                                                 [Para (lst ++ backlink)]
-                                  (Plain lst) -> otherBlocks ++
-                                                 [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'
-
-isMathEnvironment :: String -> Bool
-isMathEnvironment s = "\\begin{" `isPrefixOf` s &&
-                         envName `elem` mathmlenvs
-  where envName = takeWhile (/= '}') (drop 7 s)
-        mathmlenvs = [ "align"
-                     , "align*"
-                     , "alignat"
-                     , "alignat*"
-                     , "aligned"
-                     , "alignedat"
-                     , "array"
-                     , "Bmatrix"
-                     , "bmatrix"
-                     , "cases"
-                     , "CD"
-                     , "eqnarray"
-                     , "eqnarray*"
-                     , "equation"
-                     , "equation*"
-                     , "gather"
-                     , "gather*"
-                     , "gathered"
-                     , "matrix"
-                     , "multline"
-                     , "multline*"
-                     , "pmatrix"
-                     , "smallmatrix"
-                     , "split"
-                     , "subarray"
-                     , "Vmatrix"
-                     , "vmatrix" ]
-
-allowsMathEnvironments :: HTMLMathMethod -> Bool
-allowsMathEnvironments (MathJax _) = True
-allowsMathEnvironments MathML      = True
-allowsMathEnvironments (WebTeX _)  = True
-allowsMathEnvironments _           = False
-
-isRawHtml :: PandocMonad m => Format -> StateT WriterState m Bool
-isRawHtml f = do
-  html5 <- gets stHtml5
-  return $ f == Format "html" ||
-           ((html5 && f == Format "html5") || f == Format "html4")
-
-html5Attributes :: Set.Set String
-html5Attributes = Set.fromList
-  [ "abbr"
-  , "accept"
-  , "accept-charset"
-  , "accesskey"
-  , "action"
-  , "allowfullscreen"
-  , "allowpaymentrequest"
-  , "allowusermedia"
-  , "alt"
-  , "as"
-  , "async"
-  , "autocomplete"
-  , "autofocus"
-  , "autoplay"
-  , "charset"
-  , "checked"
-  , "cite"
-  , "class"
-  , "color"
-  , "cols"
-  , "colspan"
-  , "content"
-  , "contenteditable"
-  , "controls"
-  , "coords"
-  , "crossorigin"
-  , "data"
-  , "datetime"
-  , "default"
-  , "defer"
-  , "dir"
-  , "dirname"
-  , "disabled"
-  , "download"
-  , "draggable"
-  , "enctype"
-  , "for"
-  , "form"
-  , "formaction"
-  , "formenctype"
-  , "formmethod"
-  , "formnovalidate"
-  , "formtarget"
-  , "headers"
-  , "height"
-  , "hidden"
-  , "high"
-  , "href"
-  , "hreflang"
-  , "http-equiv"
-  , "id"
-  , "inputmode"
-  , "integrity"
-  , "is"
-  , "ismap"
-  , "itemid"
-  , "itemprop"
-  , "itemref"
-  , "itemscope"
-  , "itemtype"
-  , "kind"
-  , "label"
-  , "lang"
-  , "list"
-  , "loop"
-  , "low"
-  , "manifest"
-  , "max"
-  , "maxlength"
-  , "media"
-  , "method"
-  , "min"
-  , "minlength"
-  , "multiple"
-  , "muted"
-  , "name"
-  , "nomodule"
-  , "nonce"
-  , "novalidate"
-  , "onabort"
-  , "onafterprint"
-  , "onauxclick"
-  , "onbeforeprint"
-  , "onbeforeunload"
-  , "onblur"
-  , "oncancel"
-  , "oncanplay"
-  , "oncanplaythrough"
-  , "onchange"
-  , "onclick"
-  , "onclose"
-  , "oncontextmenu"
-  , "oncopy"
-  , "oncuechange"
-  , "oncut"
-  , "ondblclick"
-  , "ondrag"
-  , "ondragend"
-  , "ondragenter"
-  , "ondragexit"
-  , "ondragleave"
-  , "ondragover"
-  , "ondragstart"
-  , "ondrop"
-  , "ondurationchange"
-  , "onemptied"
-  , "onended"
-  , "onerror"
-  , "onfocus"
-  , "onhashchange"
-  , "oninput"
-  , "oninvalid"
-  , "onkeydown"
-  , "onkeypress"
-  , "onkeyup"
-  , "onlanguagechange"
-  , "onload"
-  , "onloadeddata"
-  , "onloadedmetadata"
-  , "onloadend"
-  , "onloadstart"
-  , "onmessage"
-  , "onmessageerror"
-  , "onmousedown"
-  , "onmouseenter"
-  , "onmouseleave"
-  , "onmousemove"
-  , "onmouseout"
-  , "onmouseover"
-  , "onmouseup"
-  , "onoffline"
-  , "ononline"
-  , "onpagehide"
-  , "onpageshow"
-  , "onpaste"
-  , "onpause"
-  , "onplay"
-  , "onplaying"
-  , "onpopstate"
-  , "onprogress"
-  , "onratechange"
-  , "onrejectionhandled"
-  , "onreset"
-  , "onresize"
-  , "onscroll"
-  , "onsecuritypolicyviolation"
-  , "onseeked"
-  , "onseeking"
-  , "onselect"
-  , "onstalled"
-  , "onstorage"
-  , "onsubmit"
-  , "onsuspend"
-  , "ontimeupdate"
-  , "ontoggle"
-  , "onunhandledrejection"
-  , "onunload"
-  , "onvolumechange"
-  , "onwaiting"
-  , "onwheel"
-  , "open"
-  , "optimum"
-  , "pattern"
-  , "ping"
-  , "placeholder"
-  , "playsinline"
-  , "poster"
-  , "preload"
-  , "readonly"
-  , "referrerpolicy"
-  , "rel"
-  , "required"
-  , "reversed"
-  , "rows"
-  , "rowspan"
-  , "sandbox"
-  , "scope"
-  , "selected"
-  , "shape"
-  , "size"
-  , "sizes"
-  , "slot"
-  , "span"
-  , "spellcheck"
-  , "src"
-  , "srcdoc"
-  , "srclang"
-  , "srcset"
-  , "start"
-  , "step"
-  , "style"
-  , "tabindex"
-  , "target"
-  , "title"
-  , "translate"
-  , "type"
-  , "typemustmatch"
-  , "updateviacache"
-  , "usemap"
-  , "value"
-  , "width"
-  , "workertype"
-  , "wrap"
-  ]
+{-# LANGUAGE BangPatterns        #-}
+{-# LANGUAGE FlexibleContexts    #-}
+{-# LANGUAGE LambdaCase          #-}
+{-# LANGUAGE MultiWayIf          #-}
+{-# LANGUAGE OverloadedStrings   #-}
+{-# LANGUAGE ScopedTypeVariables #-}
+{-# LANGUAGE TypeApplications    #-}
+{-# LANGUAGE ViewPatterns        #-}
+{- |
+   Module      : Text.Pandoc.Writers.HTML
+   Copyright   : Copyright (C) 2006-2024 John MacFarlane
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : John MacFarlane <jgm@berkeley.edu>
+   Stability   : alpha
+   Portability : portable
+
+Conversion of 'Pandoc' documents to HTML.
+-}
+module Text.Pandoc.Writers.HTML (
+  writeHtml4,
+  writeHtml4String,
+  writeHtml5,
+  writeHtml5String,
+  writeHtmlStringForEPUB,
+  writeS5,
+  writeSlidy,
+  writeSlideous,
+  writeDZSlides,
+  writeRevealJs,
+  tagWithAttributes
+  ) where
+import Control.Monad.State.Strict
+    ( StateT, MonadState(get), gets, modify, evalStateT )
+import Control.Monad ( liftM, when, foldM, unless )
+import Control.Monad.Trans ( MonadTrans(lift) )
+import Data.Char (ord, isSpace, isAscii)
+import Data.List (intercalate, intersperse, partition, delete, (\\))
+import qualified Data.List as L
+import Data.List.NonEmpty (NonEmpty((:|)))
+import Data.Containers.ListUtils (nubOrd)
+import Data.Maybe (fromMaybe, isJust, isNothing)
+import qualified Data.Set as Set
+import Data.Text (Text)
+import qualified Data.Text as T
+import qualified Data.Text.Lazy as TL
+import Network.URI (URI (..), parseURIReference, escapeURIString)
+import Text.Pandoc.URI (urlEncode)
+import Numeric (showHex)
+import Text.DocLayout (render, literal, Doc)
+import Text.Blaze.Internal (MarkupM (Empty), customLeaf, customParent)
+import Text.DocTemplates (FromContext (lookupContext), Context (..), Val(..))
+import qualified Text.DocTemplates.Internal as DT
+import Text.Blaze.Html hiding (contents)
+import Text.Pandoc.Definition
+import Text.Pandoc.Highlighting (formatHtmlBlock, formatHtml4Block,
+                 formatHtmlInline, highlight, styleToCss, defaultStyle)
+import Text.Pandoc.ImageSize
+import Text.Pandoc.Options
+import Text.Pandoc.Shared
+import Text.Pandoc.Slides
+import Text.Pandoc.Templates (renderTemplate)
+import Text.Pandoc.Walk
+import Text.Pandoc.Writers.Math
+import Text.Pandoc.Writers.Shared
+import qualified Text.Pandoc.Writers.AnnotatedTable as Ann
+import Text.Pandoc.XML (escapeStringForXML, fromEntities, toEntities,
+                        html5Attributes, html4Attributes, rdfaAttributes)
+import qualified Text.Blaze.XHtml5 as H5
+import qualified Text.Blaze.XHtml5.Attributes as A5
+import Control.Monad.Except (throwError)
+import System.FilePath (takeBaseName)
+import Text.Blaze.Html.Renderer.Text (renderHtml)
+import qualified Text.Blaze.XHtml1.Transitional as H
+import qualified Text.Blaze.XHtml1.Transitional.Attributes as A
+import Text.Pandoc.Class.PandocMonad (PandocMonad, report)
+import Text.Pandoc.Translations (Term(Abstract), translateTerm)
+import Text.Pandoc.Class.PandocPure (runPure)
+import Text.Pandoc.Error
+import Text.Pandoc.Logging
+import Text.Pandoc.MIME (mediaCategory)
+import Text.Pandoc.Writers.Blaze (layoutMarkup)
+import Text.TeXMath
+import Text.XML.Light (elChildren, unode, unqual)
+import qualified Text.XML.Light as XML
+import Text.XML.Light.Output
+import Data.String (fromString)
+
+data WriterState = WriterState
+    { stNotes        :: [Html]  -- ^ List of notes
+    , stEmittedNotes :: Int     -- ^ How many notes we've already pushed out to the HTML
+    , stEmittedNoteBlocks :: Int  -- ^ How many @\<div class=footnote>@ blocks we've already pushed out
+    , stMath         :: Bool    -- ^ Math is used in document
+    , stQuotes       :: Bool    -- ^ <q> tag is used
+    , stHighlighting :: Bool    -- ^ Syntax highlighting is used
+    , stHtml5        :: Bool    -- ^ Use HTML5
+    , stEPUBVersion  :: Maybe EPUBVersion -- ^ EPUB version if for epub
+    , stSlideVariant :: HTMLSlideVariant
+    , stSlideLevel   :: Int     -- ^ Slide level
+    , stInSection    :: Bool    -- ^ Content is in a section (revealjs)
+    , stCodeBlockNum :: Int     -- ^ Number of code block
+    , stCsl          :: Bool    -- ^ Has CSL references
+    , stCslEntrySpacing :: Maybe Int  -- ^ CSL entry spacing
+    , stBlockLevel   :: Int     -- ^ Current block depth, excluding section divs
+    }
+
+defaultWriterState :: WriterState
+defaultWriterState = WriterState {stNotes= [],
+                                  stEmittedNotes = 0,
+                                  stEmittedNoteBlocks = 0,
+                                  stMath = False,
+                                  stQuotes = False,
+                                  stHighlighting = False,
+                                  stHtml5 = False,
+                                  stEPUBVersion = Nothing,
+                                  stSlideVariant = NoSlides,
+                                  stSlideLevel = 1,
+                                  stInSection = False,
+                                  stCodeBlockNum = 0,
+                                  stCsl = False,
+                                  stCslEntrySpacing = Nothing,
+                                  stBlockLevel = 0}
+
+-- Helpers to render HTML with the appropriate function.
+
+strToHtml :: Text -> Html
+strToHtml t
+    | T.any isSpecial t =
+       let !x = L.foldl' go mempty $ T.groupBy samegroup t
+        in x
+    | otherwise = toHtml t
+  where
+    samegroup c d = d == '\xFE0E' || not (isSpecial c || isSpecial d)
+    isSpecial '\'' = True
+    isSpecial '"' = True
+    isSpecial c = needsVariationSelector c
+    go h "\'" = h <> preEscapedString "\'"
+    go h "\"" = h <> preEscapedString "\""
+    go h txt | T.length txt == 1 && T.all needsVariationSelector txt
+           = h <> preEscapedString (T.unpack txt <> "\xFE0E")
+    go h txt = h <> toHtml txt
+
+-- See #5469: this prevents iOS from substituting emojis.
+needsVariationSelector :: Char -> Bool
+needsVariationSelector '↩' = True
+needsVariationSelector '↔' = True
+needsVariationSelector _   = False
+
+-- | Hard linebreak.
+nl :: Html
+nl = preEscapedString "\n"
+
+-- | Convert Pandoc document to Html 5 string.
+writeHtml5String :: PandocMonad m => WriterOptions -> Pandoc -> m Text
+writeHtml5String = writeHtmlString'
+                      defaultWriterState{ stHtml5 = True }
+
+-- | Convert Pandoc document to Html 5 structure.
+writeHtml5 :: PandocMonad m => WriterOptions -> Pandoc -> m Html
+writeHtml5 = writeHtml' defaultWriterState{ stHtml5 = True }
+
+-- | Convert Pandoc document to Html 4 string.
+writeHtml4String :: PandocMonad m => WriterOptions -> Pandoc -> m Text
+writeHtml4String opts = writeHtmlString'
+                         defaultWriterState{ stHtml5 = False } opts .
+                        ensureValidXmlIdentifiers
+
+-- | Convert Pandoc document to Html 4 structure.
+writeHtml4 :: PandocMonad m => WriterOptions -> Pandoc -> m Html
+writeHtml4 opts = writeHtml' defaultWriterState{ stHtml5 = False } opts .
+                    ensureValidXmlIdentifiers
+
+-- | Convert Pandoc document to Html appropriate for an epub version.
+writeHtmlStringForEPUB :: PandocMonad m
+                       => EPUBVersion -> WriterOptions -> Pandoc
+                       -> m Text
+writeHtmlStringForEPUB version o = writeHtmlString'
+                      defaultWriterState{ stHtml5 = version == EPUB3,
+                                          stEPUBVersion = Just version }
+                      o{ writerWrapText = WrapNone }
+   -- we don't use ensureValidXmlIdentifiers here because we
+   -- do that in the EPUB writer
+
+-- | Convert Pandoc document to Reveal JS HTML slide show.
+writeRevealJs :: PandocMonad m
+              => WriterOptions -> Pandoc -> m Text
+writeRevealJs = writeHtmlSlideShow' RevealJsSlides
+
+-- | Convert Pandoc document to S5 HTML slide show.
+writeS5 :: PandocMonad m
+        => WriterOptions -> Pandoc -> m Text
+writeS5 opts = writeHtmlSlideShow' S5Slides opts .
+               ensureValidXmlIdentifiers
+
+-- | Convert Pandoc document to Slidy HTML slide show.
+writeSlidy :: PandocMonad m
+           => WriterOptions -> Pandoc -> m Text
+writeSlidy opts = writeHtmlSlideShow' SlidySlides opts .
+                  ensureValidXmlIdentifiers
+
+-- | Convert Pandoc document to Slideous HTML slide show.
+writeSlideous :: PandocMonad m
+              => WriterOptions -> Pandoc -> m Text
+writeSlideous opts = writeHtmlSlideShow' SlideousSlides opts .
+                     ensureValidXmlIdentifiers
+
+-- | Convert Pandoc document to DZSlides HTML slide show.
+writeDZSlides :: PandocMonad m
+              => WriterOptions -> Pandoc -> m Text
+writeDZSlides opts = writeHtmlSlideShow' DZSlides opts
+
+writeHtmlSlideShow' :: PandocMonad m
+                    => HTMLSlideVariant -> WriterOptions -> Pandoc -> m Text
+writeHtmlSlideShow' variant = writeHtmlString'
+    defaultWriterState{ stSlideVariant = variant
+                      , stHtml5 = case variant of
+                                       RevealJsSlides -> True
+                                       S5Slides       -> False
+                                       SlidySlides    -> False
+                                       DZSlides       -> True
+                                       SlideousSlides -> False
+                                       NoSlides       -> False
+                      }
+
+renderHtml' :: Html -> Text
+renderHtml' = TL.toStrict . renderHtml
+
+writeHtmlString' :: PandocMonad m
+                 => WriterState -> WriterOptions -> Pandoc -> m Text
+writeHtmlString' st opts d = do
+  (body, context) <- evalStateT (pandocToHtml opts d) st
+  let colwidth = case writerWrapText opts of
+                    WrapAuto -> Just (writerColumns opts)
+                    _ -> Nothing
+  (if writerPreferAscii opts
+      then toEntities
+      else id) <$>
+    case writerTemplate opts of
+       Nothing -> return $
+         case colwidth of
+           Nothing -> renderHtml' body  -- optimization, skip layout
+           Just cols -> render (Just cols) $ layoutMarkup body
+       Just tpl -> do
+         -- warn if empty lang
+         when (isNothing (getField "lang" context :: Maybe Text) &&
+               hasVariable "lang" tpl) $
+           report NoLangSpecified
+         (context' :: Context Text) <-
+            -- check for empty pagetitle
+            case getField "pagetitle" context of
+                 Just (s :: Text) | not (T.null s) -> return context
+                 _ | hasVariable "pagetitle" tpl -> do
+                       let fallback = T.pack $
+                             case lookupContext "sourcefile"
+                                       (writerVariables opts) of
+                               Nothing    -> "Untitled"
+                               Just []    -> "Untitled"
+                               Just (x:_) -> takeBaseName $ T.unpack x
+                       report $ NoTitleElement fallback
+                       return $ resetField "pagetitle" (literal fallback) context
+                   | otherwise -> return context
+         return $ render colwidth $ renderTemplate tpl
+             (defField "body" (layoutMarkup body) context')
+
+writeHtml' :: PandocMonad m => WriterState -> WriterOptions -> Pandoc -> m Html
+writeHtml' st opts d =
+  case writerTemplate opts of
+       Just _ -> preEscapedText <$> writeHtmlString' st opts d
+       Nothing
+         | writerPreferAscii opts
+           -> preEscapedText <$> writeHtmlString' st opts d
+         | otherwise -> do
+            (body, _) <- evalStateT (pandocToHtml opts d) st
+            return body
+
+-- result is (title, authors, date, toc, body, new variables)
+pandocToHtml :: PandocMonad m
+             => WriterOptions
+             -> Pandoc
+             -> StateT WriterState m (Html, Context Text)
+pandocToHtml opts (Pandoc meta blocks) = do
+  lift $ setupTranslations meta
+  let slideLevel = fromMaybe (getSlideLevel blocks) $ writerSlideLevel opts
+  modify $ \st -> st{ stSlideLevel = slideLevel }
+  metadata <- metaToContext opts
+              (fmap layoutMarkup . blockListToHtml opts)
+              (fmap layoutMarkup . inlineListToHtml opts)
+              meta
+  let stringifyHTML = escapeStringForXML . stringify
+  let authsMeta = map (literal . stringifyHTML) $ docAuthors meta
+  let dateMeta  = stringifyHTML $ docDate meta
+  let descriptionMeta = literal $ escapeStringForXML $
+                          lookupMetaString "description" meta
+  slideVariant <- gets stSlideVariant
+  abstractTitle <- translateTerm Abstract
+  let sects = makeSectionsWithOffsets
+                (writerNumberOffset opts) (writerNumberSections opts) Nothing $
+              if slideVariant == NoSlides
+                 then blocks
+                 else prepSlides slideLevel blocks
+  toc <- if writerTableOfContents opts && slideVariant /= S5Slides
+            then fmap layoutMarkup <$> tableOfContents opts sects
+            else return Nothing
+  blocks' <- blockListToHtml opts sects
+  notes <- do
+    -- make the st private just to be safe, since we modify it right afterwards
+    st <- get
+    if null (stNotes st)
+      then return mempty
+      else do
+        notes <- footnoteSection opts EndOfDocument (stEmittedNotes st + 1) (reverse (stNotes st))
+        modify (\st' -> st'{ stNotes = mempty, stEmittedNotes = stEmittedNotes st' + length (stNotes st') })
+        return notes
+  st <- get
+  let html5 = stHtml5 st
+  let thebody = blocks' >> notes
+  let math = layoutMarkup $ case writerHTMLMathMethod opts of
+        MathJax url
+          | slideVariant /= RevealJsSlides ->
+          -- mathjax is handled via a special plugin in revealjs
+            H.script ! A.defer mempty
+                    ! A.src (toValue $ toURI html5 url)
+                    ! A.type_ "text/javascript"
+                    $ case slideVariant of
+                            SlideousSlides ->
+                              preEscapedString
+                              "MathJax.Hub.Queue([\"Typeset\",MathJax.Hub]);"
+                            _ -> mempty
+        KaTeX url -> do
+          H.script !
+            A.defer mempty !
+            A.src (toValue $ toURI html5 $ url <> "katex.min.js") $ mempty
+          nl
+          let katexFlushLeft =
+                case lookupContext "classoption" metadata of
+                  Just clsops | "fleqn" `elem` (clsops :: [Doc Text]) -> "true"
+                  _ -> "false"
+          H.script $ text $ T.unlines [
+              "document.addEventListener(\"DOMContentLoaded\", function () {"
+            , " var mathElements = document.getElementsByClassName(\"math\");"
+            , " var macros = [];"
+            , " for (var i = 0; i < mathElements.length; i++) {"
+            , "  var texText = mathElements[i].firstChild;"
+            , "  if (mathElements[i].tagName == \"SPAN\") {"
+            , "   katex.render(texText.data, mathElements[i], {"
+            , "    displayMode: mathElements[i].classList.contains('display'),"
+            , "    throwOnError: false,"
+            , "    macros: macros,"
+            , "    fleqn: " <> katexFlushLeft
+            , "   });"
+            , "}}});"
+            ]
+          nl
+          H.link ! A.rel "stylesheet" !
+            A.href (toValue $ toURI html5 url <> "katex.min.css")
+
+        _ -> mempty
+  let mCss :: Maybe [Text] = lookupContext "css" metadata
+  let context :: Context Text
+      context =   (if stHighlighting st
+                      then case writerHighlightMethod opts of
+                             Skylighting sty ->
+                               defField "highlighting-css"
+                                 (literal $ T.pack $ styleToCss sty)
+                             DefaultHighlighting ->
+                               defField "highlighting-css"
+                                 (literal $ T.pack $ styleToCss defaultStyle)
+                             _  -> id
+                      else id) .
+                  (if stCsl st
+                      then defField "csl-css" True .
+                           (case stCslEntrySpacing st of
+                              Nothing -> id
+                              Just n  ->
+                                defField "csl-entry-spacing"
+                                  (literal $ tshow n <> "em"))
+                      else id) .
+                  (if stMath st
+                      then defField "math" math
+                      else id) .
+                  defField "abstract-title" abstractTitle .
+                  (case writerHTMLMathMethod opts of
+                        MathJax u -> defField "mathjax" True .
+                                     defField "mathjaxurl"
+                                       (literal $ T.takeWhile (/='?') u)
+                        _         -> defField "mathjax" False) .
+                  (case writerHTMLMathMethod opts of
+                        PlainMath -> defField "displaymath-css" True
+                        WebTeX _  -> defField "displaymath-css" True
+                        _         -> id) .
+                  (if slideVariant == RevealJsSlides
+                      then -- set boolean options explicitly, since
+                           -- template can't distinguish False/undefined
+                         defField "controls" True .
+                         defField "controlsTutorial" True .
+                         defField "controlsLayout"
+                           ("bottom-right" :: Doc Text) .
+                         defField "controlsBackArrows" ("faded" :: Doc Text) .
+                         defField "progress" True .
+                         defField "slideNumber" False .
+                         defField "showSlideNumber" ("all" :: Doc Text) .
+                         defField "hashOneBasedIndex" False .
+                         defField "hash" True .
+                         defField "respondToHashChanges" True .
+                         defField "history" False .
+                         defField "keyboard" True .
+                         defField "overview" True .
+                         defField "disableLayout" False .
+                         defField "center" True .
+                         defField "touch" True .
+                         defField "loop" False .
+                         defField "rtl" False .
+                         defField "navigationMode" ("default" :: Doc Text) .
+                         defField "shuffle" False .
+                         defField "fragments" True .
+                         defField "fragmentInURL" True .
+                         defField "embedded" False .
+                         defField "help" True .
+                         defField "pause" True .
+                         defField "showNotes" False .
+                         defField "autoPlayMedia" ("null" :: Doc Text) .
+                         defField "preloadIframes" ("null" :: Doc Text) .
+                         defField "autoSlide" ("0" :: Doc Text) .
+                         defField "autoSlideStoppable" True .
+                         defField "autoSlideMethod" ("null" :: Doc Text) .
+                         defField "defaultTiming" ("null" :: Doc Text) .
+                         defField "mouseWheel" False .
+                         defField "display" ("block" :: Doc Text) .
+                         defField "hideInactiveCursor" True .
+                         defField "hideCursorTime" ("5000" :: Doc Text) .
+                         defField "previewLinks" False .
+                         defField "transition" ("slide" :: Doc Text) .
+                         defField "transitionSpeed" ("default" :: Doc Text) .
+                         defField "backgroundTransition" ("fade" :: Doc Text) .
+                         defField "viewDistance" ("3" :: Doc Text) .
+                         defField "mobileViewDistance" ("2" :: Doc Text) .
+                         (case (lookupContext "scrollProgress" metadata
+                                   :: Maybe (Val Text)) of
+                            Just (BoolVal False) -> id
+                            Just (BoolVal True) -> defField "scrollProgress" True
+                            _  -> defField "scrollProgressAuto" True) .
+                         defField "scrollActivationWidth" ("0" :: Doc Text) .
+                         defField "scrollSnap" ("mandatory" :: Doc Text) .
+                         defField "scrollLayout" ("full" :: Doc Text) .
+                         (case writerHighlightMethod opts of
+                            IdiomaticHighlighting
+                             | slideVariant == RevealJsSlides ->
+                              defField "highlight-js" True .
+                              defField "highlightjs-theme" ("monokai" :: Doc Text)
+                            _ -> id)
+                      else id) .
+                  defField "document-css" (isNothing mCss && slideVariant == NoSlides) .
+                  defField "quotes" (stQuotes st) .
+                  -- for backwards compatibility we populate toc
+                  -- with the contents of the toc, rather than a
+                  -- boolean:
+                  maybe id (defField "toc") toc .
+                  maybe id (defField "table-of-contents") toc .
+                  defField "author-meta" authsMeta .
+                  maybe id (defField "date-meta" . literal)
+                    (normalizeDate dateMeta) .
+                  defField "description-meta" descriptionMeta .
+                  defField "pagetitle"
+                      (literal . stringifyHTML . docTitle $ meta) .
+                  defField "idprefix" (literal $ writerIdentifierPrefix opts) .
+                  -- these should maybe be set in pandoc.hs
+                  defField "slidy-url"
+                    ("https://www.w3.org/Talks/Tools/Slidy2" :: Doc Text) .
+                  defField "slideous-url" ("slideous" :: Doc Text) .
+                  defField "revealjs-url" ("https://unpkg.com/reveal.js@^5" :: Doc Text) $
+                  defField "s5-url" ("s5/default" :: Doc Text) .
+                  defField "table-caption-below"
+                     (writerTableCaptionPosition opts == CaptionBelow) .
+                  defField "html5" (stHtml5 st) $
+                  metadata
+  return (thebody, context)
+
+-- | Like Text.XHtml's identifier, but adds the writerIdentifierPrefix
+prefixedId :: WriterOptions -> Text -> Attribute
+prefixedId opts s =
+  case s of
+    "" -> mempty
+    _  -> A.id $ toValue $ writerIdentifierPrefix opts <> s
+
+toList :: PandocMonad m
+       => (Html -> Html)
+       -> WriterOptions
+       -> [Html]
+       -> StateT WriterState m Html
+toList listop opts items = do
+    slideVariant <- gets stSlideVariant
+    return $
+      if writerIncremental opts
+         then if slideVariant /= RevealJsSlides
+                 then  listop (mconcat items) ! A.class_ "incremental"
+                 else listop $ mconcat $ map (! A.class_ "fragment") items
+         else listop $ mconcat items
+
+unordList :: PandocMonad m
+          => WriterOptions -> [Html] -> StateT WriterState m Html
+unordList opts = toList H.ul opts . toListItems
+
+ordList :: PandocMonad m
+        => WriterOptions -> [Html] -> StateT WriterState m Html
+ordList opts = toList H.ol opts . toListItems
+
+defList :: PandocMonad m
+        => WriterOptions -> [Html] -> StateT WriterState m Html
+defList opts items = toList H.dl opts (items ++ [nl])
+
+listItemToHtml :: PandocMonad m
+               => WriterOptions -> [Block] -> StateT WriterState m Html
+listItemToHtml opts bls =
+  case toTaskListItem bls of
+    Just (checked, (Para is:bs)) -> taskListItem checked H.p is bs
+    Just (checked, (Plain is:bs)) -> taskListItem checked id is bs
+    _ -> blockListToHtml opts bls
+  where
+    taskListItem checked constr is bs = do
+      let checkbox  = if checked
+                      then checkbox' ! A.checked ""
+                      else checkbox'
+          checkbox' = H.input ! A.type_ "checkbox"
+      isContents <- inlineListToHtml opts is
+      bsContents <- blockListToHtml opts bs
+      return $ constr (H.label (checkbox >> isContents)) >>
+               (if null bs then mempty else nl) >>
+               bsContents
+
+-- | Construct table of contents from list of elements.
+tableOfContents :: PandocMonad m => WriterOptions -> [Block]
+                -> StateT WriterState m (Maybe Html)
+tableOfContents _ [] = return Nothing
+tableOfContents opts sects = do
+  -- in reveal.js, we need #/apples, not #apples:
+  slideVariant <- gets stSlideVariant
+  let opts' = case slideVariant of
+                RevealJsSlides ->
+                  opts{ writerIdentifierPrefix =
+                          "/" <> writerIdentifierPrefix opts }
+                _ -> opts
+  case toTableOfContents opts sects of
+    bl@(BulletList (_:_)) -> Just <$> blockToHtml opts' bl
+    _                     -> return Nothing
+
+-- | Convert list of Note blocks to a footnote <div>.
+-- Assumes notes are sorted.
+footnoteSection ::
+  PandocMonad m => WriterOptions -> ReferenceLocation -> Int -> [Html] -> StateT WriterState m Html
+footnoteSection opts refLocation startCounter notes = do
+  html5 <- gets stHtml5
+  slideVariant <- gets stSlideVariant
+  let hrtag = if refLocation /= EndOfBlock
+                 then (if html5 then H5.hr else H.hr) <> nl
+                 else mempty
+  idName <- do
+    blockCount <- gets stEmittedNoteBlocks
+    modify $ \st -> st{ stEmittedNoteBlocks = blockCount + 1 }
+    return $
+      -- Keep the first note section's id undecorated to maintain a target for
+      -- old links which don't expect numbered sections, or for when the notes
+      -- are rendered all together at the end of the document.
+      if blockCount <= 0
+        then "footnotes"
+        else "footnotes-" <> show (blockCount + 1)
+  let additionalClassName = case refLocation of
+        EndOfBlock -> "footnotes-end-of-block"
+        EndOfDocument -> "footnotes-end-of-document"
+        EndOfSection -> "footnotes-end-of-section"
+  let className = "footnotes " <> additionalClassName
+  epubVersion <- gets stEPUBVersion
+  let container x
+        | html5
+        , epubVersion == Just EPUB3
+                = H5.section ! A.id (fromString idName)
+                             ! A.class_ className
+                             ! customAttribute "epub:type" "footnotes" $ x
+        | html5
+        , refLocation == EndOfDocument
+        -- Note: we need a section for a new slide in slide formats.
+                = H5.section ! prefixedId opts (fromString idName)
+                             ! A5.class_ className
+                             ! A5.role "doc-endnotes"
+                             $ x
+        | html5 = H5.aside   ! prefixedId opts (fromString idName)
+                             ! A5.class_ className
+                             ! A5.role "doc-footnote"
+                             $ x
+        | slideVariant /= NoSlides = H.div ! A.class_ "footnotes slide" $ x
+        | otherwise = H.div ! A.class_ className $ x
+  return $
+    if null notes
+       then mempty
+       else do
+         nl
+         container $ do
+           nl
+           hrtag
+           -- Keep the previous output exactly the same if we don't
+           -- have multiple notes sections
+           case epubVersion of
+             Just _ -> mconcat notes
+             Nothing | startCounter == 1 ->
+               (H.ol (nl >> mconcat notes)) >> nl
+             Nothing -> (H.ol ! A.start (fromString (show startCounter)) $
+                         nl >> mconcat notes) >> nl
+
+-- | Parse a mailto link; return Just (name, domain) or Nothing.
+parseMailto :: Text -> Maybe (Text, Text)
+parseMailto s =
+  case T.break (==':') s of
+       (xs,T.uncons -> Just (':',addr)) | T.toLower xs == "mailto" -> do
+         let (name', rest) = T.span (/='@') addr
+         let domain = T.drop 1 rest
+         return (name', domain)
+       _ -> Prelude.fail "not a mailto: URL"
+
+-- | Obfuscate a "mailto:" link.
+obfuscateLink :: PandocMonad m
+              => WriterOptions -> Attr -> Html -> Text
+              -> StateT WriterState m Html
+obfuscateLink opts attr txt s | writerEmailObfuscation opts == NoObfuscation = do
+  html5 <- gets stHtml5
+  addAttrs opts attr $ H.a ! A.href (toValue $ toURI html5 s) $ txt
+obfuscateLink opts attr (TL.toStrict . renderHtml -> txt) s = do
+  html5 <- gets stHtml5
+  let meth = writerEmailObfuscation opts
+  let s' = T.toLower (T.take 7 s) <> T.drop 7 s
+  case parseMailto s' of
+        (Just (name', domain)) ->
+          let domain'  = T.replace "." " dot " domain
+              at'      = obfuscateChar '@'
+              (linkText, altText) =
+                 if txt == T.drop 7 s' -- autolink
+                    then ("e", name' <> " at " <> domain')
+                    else ("'" <> obfuscateString txt <> "'",
+                          txt <> " (" <> name' <> " at " <> domain' <> ")")
+              (_, classNames, _) = attr
+              classNamesStr = T.concat $ map (" "<>) classNames
+          in  case meth of
+                ReferenceObfuscation ->
+                     -- need to use preEscapedString or &'s are escaped to &amp; in URL
+                     return $
+                     preEscapedText $ "<a href=\"" <> obfuscateString s'
+                     <> "\" class=\"email\">" <> obfuscateString txt <> "</a>"
+                JavascriptObfuscation ->
+                     return $
+                     (H.script ! A.type_ "text/javascript" $
+                     preEscapedText ("\n<!--\nh='" <>
+                     obfuscateString domain <> "';a='" <> at' <> "';n='" <>
+                     obfuscateString name' <> "';e=n+a+h;\n" <>
+                     "document.write('<a h'+'ref'+'=\"ma'+'ilto'+':'+e+'\" clas'+'s=\"em' + 'ail" <>
+                     classNamesStr <> "\">'+" <>
+                     linkText  <> "+'<\\/'+'a'+'>');\n// -->\n")) >>
+                     H.noscript (preEscapedText $ obfuscateString altText)
+                _ -> throwError $ PandocSomeError $ "Unknown obfuscation method: " <> tshow meth
+        _ -> addAttrs opts attr $ H.a ! A.href (toValue $ toURI html5 s)
+                                      $ toHtml txt  -- malformed email
+
+-- | Obfuscate character as entity.
+obfuscateChar :: Char -> Text
+obfuscateChar char =
+  let num    = ord char
+      numstr = if even num then show num else "x" <> showHex num ""
+  in  "&#" <> T.pack numstr <> ";"
+
+-- | Obfuscate string using entities.
+obfuscateString :: Text -> Text
+obfuscateString = T.concatMap obfuscateChar . fromEntities
+
+-- | Create HTML tag with attributes.
+tagWithAttributes :: WriterOptions
+                  -> Bool -- ^ True for HTML5
+                  -> Bool -- ^ True if self-closing tag
+                  -> Text -- ^ Tag text
+                  -> Attr -- ^ Pandoc style tag attributes
+                  -> Text
+tagWithAttributes opts html5 selfClosing tagname attr =
+  let mktag = (TL.toStrict . renderHtml <$> evalStateT
+               (addAttrs opts attr (customLeaf (textTag tagname) selfClosing))
+               defaultWriterState{ stHtml5 = html5 })
+  in  case runPure mktag of
+           Left _  -> mempty
+           Right t -> t
+
+addAttrs :: PandocMonad m
+         => WriterOptions -> Attr -> Html -> StateT WriterState m Html
+addAttrs opts attr h = L.foldl' (!) h <$> attrsToHtml opts attr
+
+toAttrs :: PandocMonad m
+        => [(Text, Text)] -> StateT WriterState m [Attribute]
+toAttrs kvs = do
+  html5 <- gets stHtml5
+  mbEpubVersion <- gets stEPUBVersion
+  reverse . snd <$> foldM (go html5 mbEpubVersion) (Set.empty, []) kvs
+ where
+  go html5 mbEpubVersion (keys, attrs) (k,v) = do
+    if k `Set.member` keys
+       then do
+         report $ DuplicateAttribute k v
+         return (keys, attrs)
+       else return (Set.insert k keys, addAttr html5 mbEpubVersion k v attrs)
+  addAttr html5 mbEpubVersion x y
+    | T.null x = id  -- see #7546
+    | html5
+      = if (x `Set.member` (html5Attributes <> rdfaAttributes)
+            && x /= "label") -- #10048
+             || T.any (== ':') x -- e.g. epub: namespace
+             || "data-" `T.isPrefixOf` x
+             || "aria-" `T.isPrefixOf` x
+           then (customAttribute (textTag x) (toValue y) :)
+           else (customAttribute (textTag ("data-" <> x)) (toValue y) :)
+    | mbEpubVersion == Just EPUB2
+    , not (x `Set.member` (html4Attributes <> rdfaAttributes) ||
+      "xml:" `T.isPrefixOf` x)
+      = id
+    | otherwise
+      = (customAttribute (textTag x) (toValue y) :)
+
+attrsToHtml :: PandocMonad m
+            => WriterOptions -> Attr -> StateT WriterState m [Attribute]
+attrsToHtml opts (id',classes',keyvals) = do
+  attrs <- toAttrs keyvals
+  let classes'' = nubOrd $ filter (not . T.null) classes'
+  return $
+    [prefixedId opts id' | not (T.null id')] ++
+    [A.class_ (toValue $ T.unwords classes'') | not (null classes'')] ++ attrs
+
+imgAttrsToHtml :: PandocMonad m
+               => WriterOptions -> Attr -> StateT WriterState m [Attribute]
+imgAttrsToHtml opts attr = do
+  attrsToHtml opts (ident,cls, consolidateStyles (kvs' ++ dimensionsToAttrList attr))
+  where
+    (ident,cls,kvs) = attr
+    kvs' = filter isNotDim kvs
+    isNotDim ("width", _)  = False
+    isNotDim ("height", _) = False
+    isNotDim _             = True
+    consolidateStyles :: [(Text, Text)] -> [(Text, Text)]
+    consolidateStyles xs =
+      case partition isStyle xs of
+           ([], _)    -> xs
+           (ss, rest) -> ("style", T.intercalate ";" $ map snd ss) : rest
+    isStyle ("style", _) = True
+    isStyle _            = False
+
+dimensionsToAttrList :: Attr -> [(Text, Text)]
+dimensionsToAttrList attr = go Width ++ go Height
+  where
+    go dir = case dimension dir attr of
+               (Just (Pixel a)) -> [(tshow dir, tshow a)]
+               (Just x)         -> [("style", tshow dir <> ":" <> tshow x)]
+               Nothing          -> []
+
+blockToHtmlInner :: PandocMonad m => WriterOptions -> Block -> StateT WriterState m Html
+blockToHtmlInner opts (Plain lst) = inlineListToHtml opts lst
+blockToHtmlInner opts (Para lst) = do
+  slideVariant <- gets stSlideVariant
+  case (slideVariant, lst) of
+    (RevealJsSlides, [Image attr@(_,classes,_) txt (src,tit)])
+      | "r-stretch" `elem` classes -> do
+          -- a "stretched" image in reveal.js must be a direct child
+          -- of the slide container
+          inlineToHtml opts (Image attr txt (src, tit))
+    _ -> do
+      contents <- inlineListToHtml opts lst
+      case contents of
+        Empty _ | not (isEnabled Ext_empty_paragraphs opts) -> return mempty
+        _ -> return $ H.p contents
+blockToHtmlInner opts (LineBlock lns) = do
+  htmlLines <- inlineListToHtml opts $ intercalate [LineBreak] lns
+  return $ H.div ! A.class_ "line-block" $ htmlLines
+blockToHtmlInner opts (Div (ident, "section":dclasses, dkvs)
+                   (Header level
+                     hattr@(hident,hclasses,hkvs) ils : xs)) = do
+  slideVariant <- gets stSlideVariant
+  slideLevel <- gets stSlideLevel
+  let slide = slideVariant /= NoSlides &&
+               level <= slideLevel {- DROPPED old fix for #5168 here -}
+  html5 <- gets stHtml5
+  let titleSlide = slide && level < slideLevel
+  let level' = if level <= slideLevel && slideVariant == SlidySlides
+                  then 1 -- see #3566
+                  else level
+  header' <- if ils == [Str "\0"]  -- marker for hrule
+                then return mempty
+                else blockToHtml opts (Header level' hattr ils)
+  let isSec (Div (_,"section":_,_) _) = True
+      isSec (Div _ zs)                = any isSec zs
+      isSec _                         = False
+  let isPause (Para [Str ".",Space,Str ".",Space,Str "."]) = True
+      isPause _                                            = False
+  let fragmentClass = case slideVariant of
+                           RevealJsSlides -> "fragment"
+                           _              -> "incremental"
+  let inDiv' zs = RawBlock (Format "html") ("<div class=\""
+                       <> fragmentClass <> "\">") :
+                   (zs ++ [RawBlock (Format "html") "</div>"])
+  let breakOnPauses zs
+        | slide = case splitBy isPause zs of
+                           []   -> []
+                           y:ys -> y ++ concatMap inDiv' ys
+        | otherwise = zs
+  let (titleBlocks, innerSecs) =
+        if titleSlide
+           -- title slides have no content of their own
+           then let (as, bs) = break isSec xs
+                in  (walk breakOnPauses as, bs)
+           else ([], walk breakOnPauses xs)
+  let secttag  = if html5
+                    then H5.section
+                    else H.div
+  titleContents <- blockListToHtml opts titleBlocks
+  inSection <- gets stInSection
+  innerContents <- do
+    modify $ \st -> st{ stInSection = True }
+    res <- blockListToHtml opts innerSecs
+    modify $ \st -> st{ stInSection = inSection }
+    notes <- gets stNotes
+    let emitNotes = writerReferenceLocation opts == EndOfSection &&
+                     not (null notes)
+    if emitNotes
+      then do
+        st <- get
+        renderedNotes <- footnoteSection opts (writerReferenceLocation opts)
+                           (stEmittedNotes st + 1) (reverse notes)
+        modify (\st' -> st'{ stNotes = mempty,
+                             stEmittedNotes = stEmittedNotes st' + length notes })
+        return (res <> renderedNotes)
+      else return res
+  let classes' = ["title-slide" | titleSlide] ++ ["slide" | slide] ++
+                  ["section" | (slide || writerSectionDivs opts) &&
+                               not html5 ] ++
+                  ["level" <> tshow level | slide || writerSectionDivs opts ]
+                  <> [d | d <- dclasses,
+                               slideVariant /= RevealJsSlides ||
+                               d /= "r-fit-text"] -- see #5965
+  let attr = (ident, classes', dkvs)
+  if titleSlide
+     then do
+       t <- addAttrs opts attr $
+             secttag $ nl <> header' <> nl <> titleContents <> nl
+       -- ensure 2D nesting for revealjs, but only for one level;
+       -- revealjs doesn't like more than one level of nesting
+       return $
+         if slideVariant == RevealJsSlides && not inSection &&
+              not (null innerSecs)
+            then H5.section (nl <> t <> nl <> innerContents)
+            else t <> nl <> if null innerSecs
+                                    then mempty
+                                    else innerContents <> nl
+     else if writerSectionDivs opts || slide ||
+              (hident /= ident && not (T.null hident || T.null ident)) ||
+              (hclasses /= dclasses) || (hkvs /= dkvs)
+          then addAttrs opts attr
+               $ secttag
+               $ nl <> header' <> nl <>
+                 if null innerSecs
+                    then mempty
+                    else innerContents <> nl
+          else do
+            let attr' = (ident, classes' \\ hclasses, dkvs \\ hkvs)
+            t <- addAttrs opts attr' header'
+            return $ t <>
+                     if null innerSecs
+                        then mempty
+                        else nl <> innerContents
+blockToHtmlInner opts (Div (ident, classes, kvs) [b])
+  | Just "1" <- lookup "wrapper" kvs
+    -- unwrap "wrapper" div, putting attr on child
+  = blockToHtmlInner opts b >>=
+      addAttrs opts (ident, classes, [(k,v) | (k,v) <- kvs, k /= "wrapper"])
+blockToHtmlInner opts (Div attr@(ident, classes, kvs') bs) = do
+  html5 <- gets stHtml5
+  slideVariant <- gets stSlideVariant
+  let isCslBibBody = ident == "refs" || "csl-bib-body" `elem` classes
+  when isCslBibBody $ modify $ \st -> st{ stCsl = True
+                                        , stCslEntrySpacing =
+                                           lookup "entry-spacing" kvs' >>=
+                                           safeRead }
+  let isCslBibEntry = "csl-entry" `elem` classes
+  let kvs = [(k,v) | (k,v) <- kvs'
+                   , k /= "width" || "column" `notElem` classes] ++
+            [("style", "width:" <> w <> ";") | "column" `elem` classes
+                                             , ("width", w) <- kvs'] ++
+            [("role", "list") | isCslBibBody && html5] ++
+            [("role", "listitem") | isCslBibEntry && html5]
+  let speakerNotes = "notes" `elem` classes
+  -- we don't want incremental output inside speaker notes, see #1394
+  let (opts', isIncrDiv) =
+        if | speakerNotes ->
+             (opts{ writerIncremental = False }, False)
+           | "incremental" `elem` classes ->
+             (opts{ writerIncremental = True }, True)
+           | "nonincremental" `elem` classes ->
+             (opts{ writerIncremental = False }, True)
+           | otherwise ->
+             (opts, False)
+      -- we remove "incremental" and "nonincremental" if we're in a
+      -- slide presentation format.
+      classes' = case slideVariant of
+        NoSlides -> classes
+        _ -> filter (\k -> k /= "incremental" && k /= "nonincremental") classes
+  let paraToPlain (Para ils) = Plain ils
+      paraToPlain x          = x
+  let bs' = if "csl-entry" `elem` classes'
+               then walk paraToPlain bs
+               else bs
+  contents <- if "columns" `elem` classes'
+                 then -- we don't use blockListToHtml because it inserts
+                      -- a newline between the column divs, which throws
+                      -- off widths! see #4028
+                      mconcat <$> mapM (blockToHtml opts) bs'
+                 else blockListToHtml opts' bs'
+  let contents' = nl >> contents >> nl
+  let (divtag, classes'') = if html5 && "section" `elem` classes'
+                            then (H5.section, filter (/= "section") classes')
+                            else (H.div, classes')
+  if | isIncrDiv && (ident, classes'', kvs) == nullAttr ->
+         -- Unwrap divs that only have (non)increment information
+         pure contents
+     | speakerNotes ->
+         case slideVariant of
+              RevealJsSlides -> addAttrs opts' attr $
+                          H5.aside contents'
+              DZSlides       -> do
+                t <- addAttrs opts' attr $
+                            H5.div contents'
+                return $ t ! A5.role "note"
+              NoSlides       -> addAttrs opts' attr $
+                          H.div contents'
+              _              -> return mempty
+     | otherwise ->
+          addAttrs opts (ident, classes'', kvs) $
+              divtag contents'
+blockToHtmlInner opts (RawBlock f str) = do
+  ishtml <- isRawHtml f
+  if ishtml
+     then return $ preEscapedText str
+     else if (f == Format "latex" || f == Format "tex") &&
+             allowsMathEnvironments (writerHTMLMathMethod opts) &&
+             isMathEnvironment str
+             then do
+               modify (\st -> st {stMath = True})
+               blockToHtml opts $ Plain [Math DisplayMath str]
+             else do
+               report $ BlockNotRendered (RawBlock f str)
+               return mempty
+blockToHtmlInner _ HorizontalRule = do
+  html5 <- gets stHtml5
+  return $ if html5 then H5.hr else H.hr
+blockToHtmlInner opts (CodeBlock (id',classes,keyvals) rawCode) = do
+  html5 <- gets stHtml5
+  slideVariant <- gets stSlideVariant
+  id'' <- if T.null id'
+             then do
+               modify $ \st -> st{ stCodeBlockNum = stCodeBlockNum st + 1 }
+               codeblocknum <- gets stCodeBlockNum
+               return (writerIdentifierPrefix opts <> "cb" <> tshow codeblocknum)
+             else return (writerIdentifierPrefix opts <> id')
+  let tolhs = isEnabled Ext_literate_haskell opts &&
+                any (\c -> T.toLower c == "haskell") classes &&
+                any (\c -> T.toLower c == "literate") classes
+      classes' = if tolhs
+                    then map (\c -> if T.toLower c == "haskell"
+                                       then "literatehaskell"
+                                       else c) classes
+                    else classes
+      adjCode  = if tolhs
+                    then T.unlines . map ("> " <>) . T.lines $ rawCode
+                    else rawCode
+      isIdiomaticRevealJs = slideVariant == RevealJsSlides &&
+                            writerHighlightMethod opts == IdiomaticHighlighting
+  if isIdiomaticRevealJs
+     then do
+       -- For idiomatic reveal.js highlighting, put attributes on <code>
+       -- with language- prefix, and let highlight.js do the highlighting.
+       modify (\st -> st{ stHighlighting = True })
+       let (langClasses, otherClasses) = case classes' of
+             (lang:rest) -> (["language-" <> lang], rest)
+             []          -> ([], [])
+           codeAttrs = (id', langClasses ++ otherClasses, keyvals)
+       codeTag <- addAttrs opts codeAttrs $ H.code $ toHtml adjCode
+       return $ H.pre codeTag
+     else do
+       let highlighted = highlight (writerSyntaxMap opts)
+                           (if html5 then formatHtmlBlock else formatHtml4Block)
+                           (id'',classes',keyvals) adjCode
+           hlCode   = case writerHighlightMethod opts of
+                        Skylighting _ -> highlighted
+                        DefaultHighlighting -> highlighted
+                        _ -> Left ""
+       case hlCode of
+              Left msg -> do
+                unless (T.null msg) $
+                  report $ CouldNotHighlight msg
+                addAttrs opts (id',classes,keyvals)
+                  $ H.pre $ H.code $ toHtml adjCode
+              Right h -> modify (\st -> st{ stHighlighting = True }) >>
+                         -- we set writerIdentifierPrefix to "" since id'' already
+                         -- includes it:
+                         addAttrs opts{writerIdentifierPrefix = ""} (id'',[],keyvals) h
+blockToHtmlInner opts (BlockQuote blocks) = do
+  -- in S5, treat list in blockquote specially
+  -- if default is incremental, make it nonincremental;
+  -- otherwise incremental
+  slideVariant <- gets stSlideVariant
+  if slideVariant /= NoSlides
+     then let inc = not (writerIncremental opts) in
+          case blocks of
+             [BulletList lst]  -> blockToHtml (opts {writerIncremental = inc})
+                                  (BulletList lst)
+             [OrderedList attribs lst] ->
+                                  blockToHtml (opts {writerIncremental = inc})
+                                  (OrderedList attribs lst)
+             [DefinitionList lst] ->
+                                  blockToHtml (opts {writerIncremental = inc})
+                                  (DefinitionList lst)
+             _                 -> do contents <- blockListToHtml opts blocks
+                                     return $ H.blockquote
+                                            $ nl >> contents >> nl
+     else do
+       contents <- blockListToHtml opts blocks
+       return $ H.blockquote $ nl >> contents >> nl
+blockToHtmlInner opts (Header level (ident,classes,kvs) lst) = do
+  contents <- inlineListToHtml opts lst
+  let secnum = fromMaybe mempty $ lookup "number" kvs
+  let contents' = if writerNumberSections opts && not (T.null secnum)
+                     && "unnumbered" `notElem` classes
+                     then (H.span ! A.class_ "header-section-number"
+                             $ toHtml secnum) >> toHtml ' ' >> contents
+                     else contents
+  html5 <- gets stHtml5
+  let kvs' = if html5
+             then kvs
+             else [ (k, v) | (k, v) <- kvs
+                           , k `elem` (["lang", "dir", "title", "style"
+                                      , "align"] ++ intrinsicEventsHTML4)]
+  let classes' = if level > 6 then "heading":classes else classes
+  addAttrs opts (ident,classes',kvs')
+         $ case level of
+              1 -> H.h1 contents'
+              2 -> H.h2 contents'
+              3 -> H.h3 contents'
+              4 -> H.h4 contents'
+              5 -> H.h5 contents'
+              6 -> H.h6 contents'
+              _ -> H.p  contents'
+blockToHtmlInner opts (BulletList lst) = do
+  contents <- mapM (listItemToHtml opts) lst
+  (if isJust (mapM toTaskListItem lst) then (! A.class_ "task-list") else id) <$>
+    unordList opts contents
+blockToHtmlInner opts (OrderedList (startnum, numstyle, _) lst) = do
+  contents <- mapM (listItemToHtml opts) lst
+  html5 <- gets stHtml5
+  let numstyle' = case numstyle of
+                       Example -> "decimal"
+                       _       -> camelCaseToHyphenated $ tshow numstyle
+  let attribs = [A.start $ toValue startnum | startnum /= 1] ++
+                [A.class_ "example" | numstyle == Example] ++
+                (if numstyle /= DefaultStyle
+                   then if html5
+                           then [A.type_ $
+                                 case numstyle of
+                                      Decimal    -> "1"
+                                      LowerAlpha -> "a"
+                                      UpperAlpha -> "A"
+                                      LowerRoman -> "i"
+                                      UpperRoman -> "I"
+                                      _          -> "1"]
+                           else [A.style $ toValue $ "list-style-type: " <>
+                                   numstyle']
+                   else [])
+  l <- ordList opts contents
+  return $ L.foldl' (!) l attribs
+blockToHtmlInner opts (DefinitionList lst) = do
+  contents <- mapM (\(term, defs) ->
+                  do term' <- liftM H.dt $ inlineListToHtml opts term
+                     defs' <- mapM (liftM (\x -> H.dd (nl >> x >> nl)) .
+                                    blockListToHtml opts) defs
+                     return $ mconcat $ nl : term' : nl :
+                                        intersperse (nl) defs') lst
+  defList opts contents
+blockToHtmlInner opts (Table attr caption colspecs thead tbody tfoot) =
+  tableToHtml opts (Ann.toTable attr caption colspecs thead tbody tfoot)
+blockToHtmlInner opts (Figure attrs (Caption _ captBody)  body) = do
+  html5 <- gets stHtml5
+
+  figAttrs <- attrsToHtml opts attrs
+  contents <- blockListToHtml opts body
+  captCont <- blockListToHtml opts captBody
+  let figCaption = mconcat $
+                    if html5
+                    then let fcattr = if captionIsAlt captBody body
+                                      then H5.customAttribute
+                                           (textTag "aria-hidden")
+                                           (toValue @Text "true")
+                                      else mempty
+                         in [ H5.figcaption ! fcattr $ captCont ]
+                    else [ (H.div ! A.class_ "figcaption") captCont ]
+  let innards = mconcat $
+                if null captBody
+                   then [nl, contents, nl]
+                   else case writerFigureCaptionPosition opts of
+                         CaptionAbove -> [nl, figCaption, nl, contents, nl]
+                         CaptionBelow -> [nl, contents, nl, figCaption, nl]
+  return $
+    if html5
+    then foldl (!) H5.figure figAttrs innards
+    else foldl (!) H.div (A.class_ "float" : figAttrs) innards
+ where
+  captionIsAlt capt [Plain [Image (_, _, kv) desc _]] =
+    let alt = fromMaybe (stringify desc) $ lookup "alt" kv
+    in stringify capt == alt
+  captionIsAlt _ _ = False
+
+-- | Convert Pandoc block element to HTML. All the legwork is done by
+-- 'blockToHtmlInner', this just takes care of emitting the notes after
+-- the block if necessary.
+blockToHtml :: PandocMonad m => WriterOptions -> Block -> StateT WriterState m Html
+blockToHtml opts block = do
+  let isSection = case block of
+        Div (_, classes, _) _ | "section" `elem` classes -> True
+        _ -> False
+  let increaseLevel = not isSection
+  when increaseLevel $
+    modify (\st -> st{ stBlockLevel = stBlockLevel st + 1 })
+  doc <- blockToHtmlInner opts block
+  st <- get
+  let emitNotes =
+        writerReferenceLocation opts == EndOfBlock && stBlockLevel st == 1
+  res <- if emitNotes
+    then do
+      notes <- if null (stNotes st)
+        then return mempty
+        else footnoteSection opts (writerReferenceLocation opts)
+                             (stEmittedNotes st + 1) (reverse (stNotes st))
+      modify (\st' -> st'{ stNotes = mempty, stEmittedNotes = stEmittedNotes st' + length (stNotes st') })
+      return (doc <> notes)
+    else return doc
+  when increaseLevel $
+    modify (\st' -> st'{ stBlockLevel = stBlockLevel st' - 1 })
+  return res
+
+tableToHtml :: PandocMonad m
+            => WriterOptions
+            -> Ann.Table
+            -> StateT WriterState m Html
+tableToHtml opts (Ann.Table attr caption colspecs thead tbodies tfoot) = do
+  captionDoc <- case caption of
+    Caption _ [] -> return mempty
+    Caption _ longCapt -> do
+      cs <- blockListToHtml opts longCapt
+      return $ do
+        H.caption cs
+        nl
+  coltags <- colSpecListToHtml colspecs
+  head' <- tableHeadToHtml opts thead
+  bodies <- intersperse (nl) <$> mapM (tableBodyToHtml opts) tbodies
+  foot' <- tableFootToHtml opts tfoot
+  let (ident,classes,kvs) = attr
+  -- When widths of columns are < 100%, we need to set width for the whole
+  -- table, or some browsers give us skinny columns with lots of space
+  -- between:
+  let colWidth = \case
+        ColWidth d -> d
+        ColWidthDefault -> 0
+  let totalWidth = sum . map (colWidth . snd) $ colspecs
+  let attr' = case lookup "style" kvs of
+                Nothing | totalWidth < 1 && totalWidth > 0
+                  -> (ident,classes, ("style","width:" <>
+                         T.pack (show (round (totalWidth * 100) :: Int))
+                         <> "%;"):kvs)
+                _ -> attr
+  addAttrs opts attr' $ H.table $ do
+    nl
+    captionDoc
+    coltags
+    head'
+    mconcat bodies
+    foot'
+    nl
+
+tableBodyToHtml :: PandocMonad m
+                => WriterOptions
+                -> Ann.TableBody
+                -> StateT WriterState m Html
+tableBodyToHtml opts (Ann.TableBody attr _rowHeadCols inthead rows) =
+  addAttrs opts attr . H.tbody =<< do
+    intermediateHead <-
+      if null inthead
+      then return mempty
+      else headerRowsToHtml opts Thead inthead
+    bodyRows <- bodyRowsToHtml opts rows
+    return $ intermediateHead <> bodyRows
+
+tableHeadToHtml :: PandocMonad m
+                => WriterOptions
+                -> Ann.TableHead
+                -> StateT WriterState m Html
+tableHeadToHtml opts (Ann.TableHead attr rows) =
+  tablePartToHtml opts Thead attr rows
+
+tableFootToHtml :: PandocMonad m
+                => WriterOptions
+                -> Ann.TableFoot
+                -> StateT WriterState m Html
+tableFootToHtml opts (Ann.TableFoot attr rows) =
+  tablePartToHtml opts Tfoot attr rows
+
+tablePartToHtml :: PandocMonad m
+                => WriterOptions
+                -> TablePart
+                -> Attr
+                -> [Ann.HeaderRow]
+                -> StateT WriterState m Html
+tablePartToHtml opts tblpart attr rows =
+  if null rows || all isEmptyRow rows
+  then return mempty
+  else do
+    let tag' = case tblpart of
+                 Thead -> H.thead
+                 Tfoot -> H.tfoot
+                 Tbody -> H.tbody -- this would be unexpected
+    contents <- headerRowsToHtml opts tblpart rows
+    tablePartElement <- addAttrs opts attr $ tag' contents
+    return $ do
+      tablePartElement
+      nl
+  where
+    isEmptyRow (Ann.HeaderRow _attr _rownum cells) = all isEmptyCell cells
+    isEmptyCell (Ann.Cell _colspecs _colnum cell) =
+      cell == Cell nullAttr AlignDefault (RowSpan 1) (ColSpan 1) []
+
+-- | The part of a table; header, footer, or body.
+data TablePart = Thead | Tfoot | Tbody
+  deriving (Eq)
+
+data CellType = HeaderCell | BodyCell
+
+data TableRow = TableRow TablePart Attr Ann.RowNumber Ann.RowHead Ann.RowBody
+
+headerRowsToHtml :: PandocMonad m
+                 => WriterOptions
+                 -> TablePart
+                 -> [Ann.HeaderRow]
+                 -> StateT WriterState m Html
+headerRowsToHtml opts tablepart =
+  rowListToHtml opts . map toTableRow
+  where
+    toTableRow (Ann.HeaderRow attr rownum rowbody) =
+      TableRow tablepart attr rownum [] rowbody
+
+bodyRowsToHtml :: PandocMonad m
+               => WriterOptions
+               -> [Ann.BodyRow]
+               -> StateT WriterState m Html
+bodyRowsToHtml opts =
+  rowListToHtml opts . zipWith toTableRow [1..]
+  where
+    toTableRow rownum (Ann.BodyRow attr _rownum rowhead rowbody) =
+      TableRow Tbody attr rownum rowhead rowbody
+
+
+rowListToHtml :: PandocMonad m
+              => WriterOptions
+              -> [TableRow]
+              -> StateT WriterState m Html
+rowListToHtml opts rows =
+  (\x -> nl *> mconcat x) <$>
+     mapM (tableRowToHtml opts) rows
+
+colSpecListToHtml :: PandocMonad m
+                  => [ColSpec]
+                  -> StateT WriterState m Html
+colSpecListToHtml colspecs = do
+  html5 <- gets stHtml5
+  let hasDefaultWidth (_, ColWidthDefault) = True
+      hasDefaultWidth _                    = False
+
+  let percent w = show (truncate (100*w) :: Integer) <> "%"
+
+  let col :: ColWidth -> Html
+      col cw = do
+        H.col ! case cw of
+          ColWidthDefault -> mempty
+          ColWidth w -> if html5
+                        then A.style (toValue $ "width: " <> percent w)
+                        else A.width (toValue $ percent w)
+        nl
+
+  return $
+    if all hasDefaultWidth colspecs
+    then mempty
+    else do
+      H.colgroup $ do
+        nl
+        mapM_ (col . snd) colspecs
+      nl
+
+tableRowToHtml :: PandocMonad m
+               => WriterOptions
+               -> TableRow
+               -> StateT WriterState m Html
+tableRowToHtml opts (TableRow tblpart attr _rownum rowhead rowbody) = do
+  let celltype = case tblpart of
+                   Thead -> HeaderCell
+                   _     -> BodyCell
+  headcells <- mapM (cellToHtml opts HeaderCell) rowhead
+  bodycells <- mapM (cellToHtml opts celltype) rowbody
+  rowHtml <- addAttrs opts attr $ H.tr $ do
+    nl
+    mconcat headcells
+    mconcat bodycells
+  return $ do
+    rowHtml
+    nl
+
+colspanAttrib :: ColSpan -> Attribute
+colspanAttrib = \case
+  ColSpan 1 -> mempty
+  ColSpan n -> A.colspan (toValue n)
+
+rowspanAttrib :: RowSpan -> Attribute
+rowspanAttrib = \case
+  RowSpan 1 -> mempty
+  RowSpan n -> A.rowspan (toValue n)
+
+cellToHtml :: PandocMonad m
+           => WriterOptions
+           -> CellType
+           -> Ann.Cell
+           -> StateT WriterState m Html
+cellToHtml opts celltype (Ann.Cell (colspec :| _) _colNum cell) =
+  let align = fst colspec
+  in tableCellToHtml opts celltype align cell
+
+tableCellToHtml :: PandocMonad m
+                => WriterOptions
+                -> CellType
+                -> Alignment
+                -> Cell
+                -> StateT WriterState m Html
+tableCellToHtml opts ctype colAlign (Cell attr align rowspan colspan item) = do
+  contents <- blockListToHtml opts item
+  html5 <- gets stHtml5
+  let (ident, cls, kvs) = attr
+  let tag' = case ctype of
+        BodyCell   -> H.td
+        HeaderCell -> H.th
+  let align' = case align of
+        AlignDefault -> colAlign
+        _            -> align
+  let kvs' = case htmlAlignmentToString align' of
+               Nothing ->
+                 kvs
+               Just alignStr ->
+                 if html5
+                 then htmlAddStyle ("text-align", alignStr) kvs
+                 else case break ((== "align") . fst) kvs of
+                   (_, []) -> ("align", alignStr) : kvs
+                   (xs, _:rest) -> xs ++ ("align", alignStr) : rest
+  otherAttribs <- attrsToHtml opts (ident, cls, kvs')
+  let attribs = mconcat
+              $ colspanAttrib colspan
+              : rowspanAttrib rowspan
+              : otherAttribs
+  return $ do
+    tag' ! attribs $ contents
+    nl
+
+toListItems :: [Html] -> [Html]
+toListItems items = map toListItem items ++ [nl]
+
+toListItem :: Html -> Html
+toListItem item = nl *> H.li item
+
+blockListToHtml :: PandocMonad m
+                => WriterOptions -> [Block] -> StateT WriterState m Html
+blockListToHtml opts lst =
+  mconcat . intersperse (nl) . filter nonempty
+    <$> mapM (blockToHtml opts) lst
+  where nonempty (Empty _) = False
+        nonempty _         = True
+
+-- | Convert list of Pandoc inline elements to HTML.
+inlineListToHtml :: PandocMonad m => WriterOptions -> [Inline] -> StateT WriterState m Html
+inlineListToHtml opts lst = mconcat <$> mapM (inlineToHtml opts) lst
+
+-- | Annotates a MathML expression with the tex source
+annotateMML :: XML.Element -> Text -> XML.Element
+annotateMML e tex = math (unode "semantics" [cs, unode "annotation" (annotAttrs, T.unpack tex)])
+  where
+    cs = case elChildren e of
+          []  -> unode "mrow" ()
+          [x] -> x
+          xs  -> unode "mrow" xs
+    math childs = XML.Element q as [XML.Elem childs] l
+      where
+        (XML.Element q as _ l) = e
+    annotAttrs = [XML.Attr (unqual "encoding") "application/x-tex"]
+
+
+-- | Convert Pandoc inline element to HTML.
+inlineToHtml :: PandocMonad m
+             => WriterOptions -> Inline -> StateT WriterState m Html
+inlineToHtml opts inline = do
+  html5 <- gets stHtml5
+  case inline of
+    (Str str)      -> return $ strToHtml str
+    Space          -> return $ toHtml ' '
+    SoftBreak      -> return $ case writerWrapText opts of
+                                     WrapNone     -> toHtml ' '
+                                     WrapAuto     -> toHtml ' '
+                                     WrapPreserve -> toHtml '\n'
+    LineBreak      -> return $ do
+                        if html5 then H5.br else H.br
+                        toHtml '\n'
+    (Span ("",[cls],[]) ils)
+        | cls == "csl-block" || cls == "csl-left-margin" ||
+          cls == "csl-right-inline" || cls == "csl-indent"
+        -> inlineListToHtml opts ils >>= inDiv cls
+
+    (Span (id',classes,kvs) ils) ->
+                        let go Nothing c
+                             | c `Set.member` htmlSpanLikeElements
+                               = Just (customParent (textTag c), [])
+                             | c == "smallcaps"
+                               = Just (H.span ! A.class_ "smallcaps", [])
+                             | c == "underline"
+                               = Just (H.u, [])
+                             | otherwise = Nothing
+                            go (Just (t,cs)) c
+                             | c `Set.member` htmlSpanLikeElements
+                               = Just (t . customParent (textTag c), cs)
+                             | c == "smallcaps"
+                               = Just (t . (H.span ! A.class_ "smallcaps"), cs)
+                             | c == "underline"
+                               = Just (t . H.u, cs)
+                             | otherwise
+                               = Just (t, c:cs)
+                            spanLikeTags = L.foldl' go Nothing
+                        in case spanLikeTags classes of
+                            Just (tag, cs) -> do
+                              h <- inlineListToHtml opts ils
+                              addAttrs opts (id',cs,kvs') $ tag h
+                            Nothing -> do
+                              h <- inlineListToHtml opts ils
+                              addAttrs opts (id',classes',kvs') (H.span h)
+                            where
+                              styles = ["font-style:normal;"
+                                       | "csl-no-emph" `elem` classes]
+                                    ++ ["font-weight:normal;"
+                                       | "csl-no-strong" `elem` classes]
+                                    ++ ["font-variant:normal;"
+                                       | "csl-no-smallcaps" `elem` classes]
+                              kvs' = if null styles
+                                        then kvs
+                                        else ("style", T.concat styles) : kvs
+                              classes' = [ c | c <- classes
+                                         , c `notElem` [ "csl-no-emph"
+                                                       , "csl-no-strong"
+                                                       , "csl-no-smallcaps"
+                                                       ]
+                                         ]
+
+    (Emph lst)       -> H.em <$> inlineListToHtml opts lst
+    (Underline lst)  -> H.u <$> inlineListToHtml opts lst
+    (Strong lst)     -> H.strong <$> inlineListToHtml opts lst
+    (Code attr@(ids,cs,kvs) str)
+                     -> case hlCode of
+                             Left msg -> do
+                               unless (T.null msg) $
+                                 report $ CouldNotHighlight msg
+                               addAttrs opts (ids,cs',kvs) $
+                                 fromMaybe H.code sampOrVar $
+                                 strToHtml str
+                             Right h -> do
+                               modify $ \st -> st{ stHighlighting = True }
+                               addAttrs opts (ids,[],kvs) $
+                                 fromMaybe id sampOrVar h
+                        where hlCode = case writerHighlightMethod opts of
+                                          Skylighting _ -> highlighted
+                                          DefaultHighlighting -> highlighted
+                                          _ -> Left ""
+                              highlighted =  highlight (writerSyntaxMap opts)
+                                                       formatHtmlInline attr str
+                              (sampOrVar,cs')
+                                | "sample" `elem` cs =
+                                      (Just H.samp,"sample" `delete` cs)
+                                | "variable" `elem` cs =
+                                      (Just H.var,"variable" `delete` cs)
+                                | otherwise = (Nothing,cs)
+    (Strikeout lst)  -> H.del <$> inlineListToHtml opts lst
+    (SmallCaps lst)   -> (H.span ! A.class_ "smallcaps") <$>
+                           inlineListToHtml opts lst
+    (Superscript lst) -> H.sup <$> inlineListToHtml opts lst
+    (Subscript lst)   -> H.sub <$> inlineListToHtml opts lst
+    (Quoted quoteType lst) ->
+                        let (leftQuote, rightQuote) = case quoteType of
+                              SingleQuote -> (toHtml '‘',
+                                              toHtml '’')
+                              DoubleQuote -> (toHtml '“',
+                                              toHtml '”')
+
+                        in if writerHtmlQTags opts
+                               then do
+                                 modify $ \st -> st{ stQuotes = True }
+                                 let (maybeAttr, lst') = case lst of
+                                      [Span attr@(_, _, kvs) cs]
+                                        | any ((=="cite") . fst) kvs
+                                          -> (Just attr, cs)
+                                      cs -> (Nothing, cs)
+                                 let addAttrsMb = maybe return (addAttrs opts)
+                                 inlineListToHtml opts lst' >>=
+                                   addAttrsMb maybeAttr . H.q
+                               else (\x -> leftQuote >> x >> rightQuote)
+                                    `fmap` inlineListToHtml opts lst
+    (Math t str) -> do
+      modify (\st -> st {stMath = True})
+      let mathClass = toValue $ ("math " :: Text) <>
+                      if t == InlineMath then "inline" else "display"
+      case writerHTMLMathMethod opts of
+           WebTeX url -> do
+              let imtag = if html5 then H5.img else H.img
+              let str' = T.strip str
+              let s = case t of
+                           InlineMath  -> "\\textstyle "
+                           DisplayMath -> "\\displaystyle "
+              return $ imtag ! A.style "vertical-align:middle"
+                             ! A.src (toValue . (url <>) . urlEncode $ s <> str')
+                             ! A.alt (toValue str')
+                             ! A.title (toValue str')
+                             ! A.class_ mathClass
+           GladTeX ->
+              return $
+                customParent (textTag "eq") !
+                  customAttribute "env"
+                    (toValue $ if t == InlineMath
+                                  then ("math" :: Text)
+                                  else "displaymath") $ strToHtml str
+           MathML -> do
+              let conf = useShortEmptyTags (const False)
+                           defaultConfigPP
+              res <- lift $ convertMath writeMathML t str
+              case res of
+                    Right r  -> return $ preEscapedString $
+                        ppcElement conf (annotateMML r str)
+                    Left il  -> (H.span ! A.class_ mathClass) <$>
+                                   inlineToHtml opts il
+           MathJax _ -> return $ H.span ! A.class_ mathClass $ toHtml $
+              case t of
+                InlineMath  -> "\\(" <> str <> "\\)"
+                DisplayMath -> "\\[" <> str <> "\\]"
+           KaTeX _ -> return $ H.span ! A.class_ mathClass $ toHtml $
+              case t of
+                InlineMath  -> str
+                DisplayMath -> str
+           PlainMath -> do
+              x <- lift (texMathToInlines t str) >>= inlineListToHtml opts
+              return $ H.span ! A.class_ mathClass $ x
+    (RawInline f str) -> do
+      ishtml <- isRawHtml f
+      if ishtml
+         then return $ preEscapedText str
+         else do
+           let istex = f == Format "latex" || f == Format "tex"
+           let mm = writerHTMLMathMethod opts
+           case istex of
+             True
+               | allowsMathEnvironments mm && isMathEnvironment str
+                 -> do
+                    modify (\st -> st {stMath = True})
+                    inlineToHtml opts $ Math DisplayMath str
+               | allowsRef mm && isRef str
+                 -> do
+                    modify (\st -> st {stMath = True})
+                    inlineToHtml opts $ Math InlineMath str
+             _ -> do report $ InlineNotRendered inline
+                     return mempty
+    (Link attr txt (s,_)) | "mailto:" `T.isPrefixOf` s -> do
+                        -- We need to remove links from link text, because an
+                        -- <a> element is not allowed inside another <a>
+                        -- element.
+                        linkText <- inlineListToHtml opts (removeLinks txt)
+                        obfuscateLink opts attr linkText s
+    (Link (ident,classes,kvs) txt (s,tit)) -> do
+                        linkText <- inlineListToHtml opts (removeLinks txt)
+                        slideVariant <- gets stSlideVariant
+                        let s' = case T.uncons s of
+                                   Just ('#',xs) -> let prefix = if slideVariant == RevealJsSlides
+                                                             then "/"
+                                                             else writerIdentifierPrefix opts
+                                             in  "#" <> prefix <> xs
+                                   _ -> s
+                        let link = H.a ! A.href (toValue $ toURI html5 s')
+                                       $ linkText
+                        link' <- addAttrs opts (ident, classes, kvs) link
+                        return $ if T.null tit
+                                    then link'
+                                    else link' ! A.title (toValue tit)
+    (Image attr@(_, _, attrList) txt (s, tit)) -> do
+                        epubVersion <- gets stEPUBVersion
+                        let alternate = stringify txt
+                        slideVariant <- gets stSlideVariant
+                        let isReveal = slideVariant == RevealJsSlides
+                        attrs <- imgAttrsToHtml opts attr
+                        let attributes =
+                              -- reveal.js uses data-src for lazy loading
+                              (if isReveal
+                                  then customAttribute "data-src" $ toValue s
+                                  else A.src $ toValue $ toURI html5 s) :
+                              [A.title $ toValue tit | not (T.null tit)] ++
+                              attrs
+                            imageTag = (if html5 then H5.img else H.img
+                              , [A.alt $ toValue alternate |
+                                  isNothing (lookup "alt" attrList) &&
+                                  (isJust epubVersion || not (null txt))] )
+                            mediaTag tg fallbackTxt =
+                              let linkTxt = if null txt
+                                            then fallbackTxt
+                                            else alternate
+                              in (tg $ H.a ! A.href (toValue $ toURI html5 s)
+                                           $ toHtml linkTxt
+                                 , [A5.controls ""] )
+                            s' = fromMaybe s $ T.stripSuffix ".gz" s
+                            category =
+                              if "data:" `T.isPrefixOf` s
+                                 then Just . T.takeWhile (/= '/') . T.drop 5 $ s
+                                 else case parseURIReference (T.unpack s') of
+                                        Just u -> mediaCategory $ uriPath u
+                                        Nothing -> mediaCategory (T.unpack s)
+                            (tag, specAttrs) = case category of
+                              Just "image" -> imageTag
+                              Just "video" -> mediaTag H5.video "Video"
+                              Just "audio" -> mediaTag H5.audio "Audio"
+                              Just _       -> (H5.embed, [])
+                              _            -> imageTag
+                        return $ L.foldl' (!) tag $ attributes ++ specAttrs
+                        -- note:  null title included, as in Markdown.pl
+    (Note contents) -> do
+                        notes <- gets stNotes
+                        emittedNotes <- gets stEmittedNotes
+                        let number = emittedNotes + length notes + 1
+                        let ref = tshow number
+                        htmlContents <- blockListToNote opts ref contents
+                        epubVersion <- gets stEPUBVersion
+                        -- push contents onto front of notes
+                        modify $ \st -> st {stNotes = htmlContents:notes}
+                        slideVariant <- gets stSlideVariant
+                        let revealSlash = T.pack ['/' | slideVariant == RevealJsSlides]
+                        let link = H.a ! A.href (toValue $ toURI html5 $ "#" <>
+                                         revealSlash <>
+                                         writerIdentifierPrefix opts <> "fn" <> ref)
+                                       ! A.class_ "footnote-ref"
+                                       ! prefixedId opts ("fnref" <> ref)
+                                       $ (if isJust epubVersion
+                                             then id
+                                             else H.sup)
+                                       $ toHtml ref
+                        return $ case epubVersion of
+                                      Just EPUB3 -> link ! customAttribute "epub:type" "noteref" ! customAttribute "role" "doc-noteref"
+                                      _ | html5  -> link ! A5.role "doc-noteref"
+                                      _          -> link
+    (Cite cits il)-> do contents <- inlineListToHtml opts
+                                      (if html5
+                                          then walk addBibliorefRole il
+                                          else il)
+                        let citationIds = T.unwords $ map citationId cits
+                        let result = H.span ! A.class_ "citation" $ contents
+                        return $ if html5
+                                    then result ! customAttribute "data-cites" (toValue citationIds)
+                                    else result
+
+addBibliorefRole :: Inline -> Inline
+addBibliorefRole (Link (id',classes,kvs) ils (src,tit))
+   | "#ref-" `T.isPrefixOf` src =
+  Link (id',classes,("role","doc-biblioref"):kvs) ils (src,tit)
+addBibliorefRole x = x
+
+blockListToNote :: PandocMonad m
+                => WriterOptions -> Text -> [Block]
+                -> StateT WriterState m Html
+blockListToNote opts ref blocks = do
+  epubVersion <- gets stEPUBVersion
+  html5 <- gets stHtml5
+  case epubVersion of
+    Nothing -> do -- web page
+      -- 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 kvs = [("role","doc-backlink") | html5]
+      let backlink = [Link ("",["footnote-back"],kvs)
+                        [Str "↩"] ("#" <> "fnref" <> ref,"")]
+      let blocks'  = if null blocks
+                        then []
+                        else let lastBlock   = last blocks
+                                 otherBlocks = init blocks
+                             in  case lastBlock of
+                                      Para [Image (_,cls,_) _ (_,tit)]
+                                          | "fig:" `T.isPrefixOf` tit
+                                            || "r-stretch" `elem` cls
+                                                -> otherBlocks ++ [lastBlock,
+                                                      Plain backlink]
+                                      Para lst  -> otherBlocks ++
+                                                     [Para (lst ++ backlink)]
+                                      Plain lst -> otherBlocks ++
+                                                     [Plain (lst ++ backlink)]
+                                      _         -> otherBlocks ++ [lastBlock,
+                                                     Plain backlink]
+      contents <- blockListToHtml opts blocks'
+      let noteItem = H.li ! prefixedId opts ("fn" <> ref) $ contents
+      return $ noteItem >> nl
+    Just epubv -> do
+      let kvs = [("role","doc-backlink") | html5]
+      let backlink = Link ("",["footnote-back"],kvs)
+                        [Str ref] ("#" <> "fnref" <> ref,"")
+      let addBacklinkInlines bs
+             | epubv == EPUB3 = bs
+             | otherwise =
+                 case bs of
+                   (Para ils : rest) ->
+                     Para (backlink : Str "." : Space : ils) : rest
+                   (Plain ils : rest) ->
+                     Plain (backlink : Str "." : Space : ils) : rest
+                   _ -> Para [backlink , Str "."] : blocks
+      contents <- blockListToHtml opts (addBacklinkInlines blocks)
+      let noteItem = (if epubv == EPUB3
+                         then H5.aside ! customAttribute "epub:type" "footnote" ! customAttribute "role" "doc-footnote"
+                         else H.div) ! prefixedId opts ("fn" <> ref)
+                      $ nl >> contents >> nl
+      return $ noteItem >> nl
+
+inDiv :: PandocMonad m=> Text -> Html -> StateT WriterState m Html
+inDiv cls x = do
+  html5 <- gets stHtml5
+  return $
+    (if html5 then H5.div else H.div)
+                x ! A.class_ (toValue cls)
+
+isRef :: Text -> Bool
+isRef t = "\\ref{" `T.isPrefixOf` t || "\\eqref{" `T.isPrefixOf` t
+
+isMathEnvironment :: Text -> Bool
+isMathEnvironment s = "\\begin{" `T.isPrefixOf` s &&
+                         envName `elem` mathmlenvs
+  where envName = T.takeWhile (/= '}') (T.drop 7 s)
+        mathmlenvs = [ "align"
+                     , "align*"
+                     , "alignat"
+                     , "alignat*"
+                     , "aligned"
+                     , "alignedat"
+                     , "array"
+                     , "Bmatrix"
+                     , "bmatrix"
+                     , "cases"
+                     , "CD"
+                     , "eqnarray"
+                     , "eqnarray*"
+                     , "equation"
+                     , "equation*"
+                     , "gather"
+                     , "gather*"
+                     , "gathered"
+                     , "matrix"
+                     , "multline"
+                     , "multline*"
+                     , "pmatrix"
+                     , "prooftree" -- bussproofs
+                     , "smallmatrix"
+                     , "split"
+                     , "subarray"
+                     , "Vmatrix"
+                     , "vmatrix" ]
+
+allowsMathEnvironments :: HTMLMathMethod -> Bool
+allowsMathEnvironments (MathJax _) = True
+allowsMathEnvironments (KaTeX _)   = True
+allowsMathEnvironments MathML      = True
+allowsMathEnvironments (WebTeX _)  = True
+allowsMathEnvironments _           = False
+
+allowsRef :: HTMLMathMethod -> Bool
+allowsRef (MathJax _) = True
+allowsRef _           = False
+
+-- | List of intrinsic event attributes allowed on all elements in HTML4.
+intrinsicEventsHTML4 :: [Text]
+intrinsicEventsHTML4 =
+  [ "onclick", "ondblclick", "onmousedown", "onmouseup", "onmouseover"
+  , "onmouseout", "onmouseout", "onkeypress", "onkeydown", "onkeyup"]
+
+
+-- | Check to see if Format is valid HTML
+isRawHtml :: PandocMonad m => Format -> StateT WriterState m Bool
+isRawHtml f = do
+  html5 <- gets stHtml5
+  epubVersion <- gets stEPUBVersion
+  return $ f == Format "html" ||
+           ((html5 && f == Format "html5") || f == Format "html4") ||
+           isEpubFormat epubVersion f ||
+           isSlideVariant f
+
+-- | Check to see if Format matches with an EPUB variant
+isEpubFormat :: Maybe EPUBVersion -> Format -> Bool
+isEpubFormat Nothing _ = False
+isEpubFormat (Just EPUB2) f =
+  f == Format "epub" || f == Format "epub2"
+isEpubFormat (Just EPUB3) f =
+  f == Format "epub" || f == Format "epub3"
+
+-- | Check to see if Format matches with an HTML slide variant
+isSlideVariant :: Format -> Bool
+isSlideVariant f = f `elem` [Format "s5", Format "slidy", Format "slideous",
+                             Format "dzslides", Format "revealjs"]
+
+toURI :: Bool -> Text -> Text
+toURI isHtml5 t = if isHtml5 then t else escapeURI t
+ where
+   escapeURI = T.pack . escapeURIString (not . needsEscaping) . T.unpack
+   needsEscaping c = isSpace c || T.any (== c) "<>|\"{}[]^`" || not (isAscii c)
+
+hasVariable :: Text -> DT.Template a -> Bool
+hasVariable var = checkVar
+ where
+   matches v' = T.intercalate "." (DT.varParts v') == var
+   checkVar (DT.Interpolate v) = matches v
+   checkVar (DT.Conditional v t1 t2) = matches v || checkVar t1 || checkVar t2
+   checkVar (DT.Iterate v t1 t2) = matches v || checkVar t1 || checkVar t2
+   checkVar (DT.Nested t) = checkVar t
+   checkVar (DT.Partial _ t) = checkVar t
+   checkVar (DT.Concat t1 t2) = checkVar t1 || checkVar t2
+   checkVar (DT.Literal _) = False
+   checkVar DT.Empty = False
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,24 +1,5 @@
 {-# LANGUAGE OverloadedStrings   #-}
 {-# LANGUAGE ScopedTypeVariables #-}
-{-# LANGUAGE TupleSections       #-}
-{-
-Copyright (C) 2014-2015, 2017 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
@@ -33,22 +14,25 @@
 Haddock:  <http://www.haskell.org/haddock/doc/html/>
 -}
 module Text.Pandoc.Writers.Haddock (writeHaddock) where
+import Control.Monad (zipWithM)
 import Control.Monad.State.Strict
+    ( StateT, MonadState(get), modify, evalStateT )
+import Data.Char (isAlphaNum)
 import Data.Default
-import Data.List (intersperse, transpose)
 import Data.Text (Text)
-import Text.Pandoc.Class (PandocMonad, report)
+import qualified Data.Text as T
+import Text.Pandoc.Class.PandocMonad (PandocMonad, report)
 import Text.Pandoc.Definition
 import Text.Pandoc.Logging
 import Text.Pandoc.Options
-import Text.Pandoc.Pretty
+import Text.DocLayout
 import Text.Pandoc.Shared
-import Text.Pandoc.Templates (renderTemplate')
-import Text.Pandoc.Writers.Math (texMathToInlines)
+import Text.Pandoc.URI
+import Text.Pandoc.Templates (renderTemplate)
 import Text.Pandoc.Writers.Shared
 
 type Notes = [[Block]]
-data WriterState = WriterState { stNotes :: Notes }
+newtype WriterState = WriterState { stNotes :: Notes }
 instance Default WriterState
   where def = WriterState{ stNotes = [] }
 
@@ -68,22 +52,20 @@
   body <- blockListToHaddock opts blocks
   st <- get
   notes' <- notesToHaddock opts (reverse $ stNotes st)
-  let render' :: Doc -> Text
-      render' = render colwidth
-  let main = render' $ body <>
-               (if isEmpty notes' then empty else blankline <> notes')
-  metadata <- metaToJSON opts
-               (fmap render' . blockListToHaddock opts)
-               (fmap render' . inlineListToHaddock opts)
+  let main = body <> (if isEmpty notes' then empty else blankline <> notes')
+  metadata <- metaToContext opts
+               (blockListToHaddock opts)
+               (fmap chomp . inlineListToHaddock opts)
                meta
   let context  = defField "body" main metadata
-  case writerTemplate opts of
-          Nothing  -> return main
-          Just tpl -> renderTemplate' tpl context
+  return $ render colwidth $
+    case writerTemplate opts of
+          Nothing  -> main
+          Just tpl -> renderTemplate tpl context
 
 -- | Return haddock representation of notes.
 notesToHaddock :: PandocMonad m
-               => WriterOptions -> [[Block]] -> StateT WriterState m Doc
+               => WriterOptions -> [[Block]] -> StateT WriterState m (Doc Text)
 notesToHaddock opts notes =
   if null notes
      then return empty
@@ -92,25 +74,31 @@
        return $ text "#notes#" <> blankline <> contents
 
 -- | Escape special characters for Haddock.
-escapeString :: String -> String
-escapeString = escapeStringUsing haddockEscapes
-  where haddockEscapes = backslashEscapes "\\/'`\"@<"
+escapeString :: Text -> Text
+escapeString t
+  | T.all isAlphaNum t = t
+  | otherwise = T.concatMap escChar t
+ where
+  escChar '\\' = "\\\\"
+  escChar '/'  = "\\/"
+  escChar '\'' = "\\'"
+  escChar '`'  = "\\`"
+  escChar '"'  = "\\\""
+  escChar '@'  = "\\@"
+  escChar '<'  = "\\<"
+  escChar c    = T.singleton c
 
 -- | Convert Pandoc block element to haddock.
 blockToHaddock :: PandocMonad m
                => WriterOptions -- ^ Options
                -> Block         -- ^ Block element
-               -> StateT WriterState m Doc
-blockToHaddock _ Null = return empty
+               -> StateT WriterState m (Doc Text)
 blockToHaddock opts (Div _ ils) = do
   contents <- blockListToHaddock opts ils
   return $ contents <> blankline
 blockToHaddock opts (Plain inlines) = do
   contents <- inlineListToHaddock opts inlines
   return $ contents <> cr
--- title beginning with fig: indicates figure
-blockToHaddock opts (Para [Image attr alt (src,'f':'i':'g':':':tit)]) =
-  blockToHaddock opts (Para [Image attr alt (src,tit)])
 blockToHaddock opts (Para inlines) =
   -- TODO:  if it contains linebreaks, we need to use a @...@ block
   (<> blankline) `fmap` blockToHaddock opts (Plain inlines)
@@ -118,7 +106,7 @@
   blockToHaddock opts $ linesToPara lns
 blockToHaddock _ b@(RawBlock f str)
   | f == "haddock" =
-      return $ text str <> text "\n"
+      return $ literal str <> text "\n"
   | otherwise = do
     report $ BlockNotRendered b
     return empty
@@ -126,161 +114,114 @@
   return $ blankline <> text (replicate (writerColumns opts) '_') <> blankline
 blockToHaddock opts (Header level (ident,_,_) inlines) = do
   contents <- inlineListToHaddock opts inlines
-  let attr' = if null ident
+  let attr' = if T.null ident
                  then empty
-                 else cr <> text "#" <> text ident <> text "#"
+                 else cr <> text "#" <> literal ident <> text "#"
   return $ nowrap (text (replicate level '=') <> space <> contents)
                  <> attr' <> blankline
 blockToHaddock _ (CodeBlock (_,_,_) str) =
-  return $ prefixed "> " (text str) <> blankline
+  return $ prefixed "> " (literal str) <> blankline
 -- Nothing in haddock corresponds to block quotes:
 blockToHaddock opts (BlockQuote blocks) =
   blockListToHaddock opts blocks
--- Haddock doesn't have tables.  Use haddock tables in code.
-blockToHaddock opts (Table caption aligns widths headers rows) = do
-  caption' <- inlineListToHaddock opts caption
+blockToHaddock opts (Table _ blkCapt specs thead tbody tfoot) = do
+  let Caption _ caption = blkCapt
+  caption' <- blockListToHaddock opts caption
   let caption'' = if null caption
                      then empty
                      else blankline <> caption' <> blankline
-  rawHeaders <- mapM (blockListToHaddock opts) headers
-  rawRows <- mapM (mapM (blockListToHaddock opts)) rows
-  let isSimple = all (==0) widths
-  let isPlainBlock (Plain _) = True
-      isPlainBlock _         = False
-  let hasBlocks = not (all isPlainBlock $ concat . concat $ headers:rows)
-  (nst,tbl) <- case True of
-                _ | isSimple -> (nest 2,) <$>
-                         pandocTable opts (all null headers) aligns widths
-                             rawHeaders rawRows
-                  | not hasBlocks -> (nest 2,) <$>
-                         pandocTable opts (all null headers) aligns widths
-                             rawHeaders rawRows
-                  | otherwise -> (id,) <$>
-                         gridTable opts blockListToHaddock
-                          (all null headers) aligns widths headers rows
-  return $ prefixed "> " (nst $ tbl $$ blankline $$ caption'') $$ blankline
+  tbl <- gridTable opts blockListToHaddock specs thead tbody tfoot
+  return $ (tbl $$ blankline $$ caption'') $$ blankline
 blockToHaddock opts (BulletList items) = do
   contents <- mapM (bulletListItemToHaddock opts) items
-  return $ cat contents <> blankline
+  return $ (if isTightList items then vcat else vsep) contents <> blankline
 blockToHaddock opts (OrderedList (start,_,delim) items) = do
   let attribs = (start, Decimal, delim)
   let markers  = orderedListMarkers attribs
-  let markers' = map (\m -> if length m < 3
-                               then m ++ replicate (3 - length m) ' '
+  let markers' = map (\m -> if T.length m < 3
+                               then m <> T.replicate (3 - T.length m) " "
                                else m) markers
-  contents <- mapM (uncurry (orderedListItemToHaddock opts)) $
-              zip markers' items
-  return $ cat contents <> blankline
+  contents <- zipWithM (orderedListItemToHaddock opts) markers' items
+  return $ (if isTightList items then vcat else vsep) contents <> blankline
 blockToHaddock opts (DefinitionList items) = do
   contents <- mapM (definitionListItemToHaddock opts) items
-  return $ cat contents <> blankline
-
-pandocTable :: PandocMonad m
-            => WriterOptions -> Bool -> [Alignment] -> [Double]
-            -> [Doc] -> [[Doc]] -> StateT WriterState m Doc
-pandocTable opts headless aligns widths rawHeaders rawRows =  do
-  let isSimple = all (==0) widths
-  let alignHeader alignment = case alignment of
-                                AlignLeft    -> lblock
-                                AlignCenter  -> cblock
-                                AlignRight   -> rblock
-                                AlignDefault -> lblock
-  let numChars = maximum . map offset
-  let widthsInChars = if isSimple
-                         then map ((+2) . numChars)
-                              $ transpose (rawHeaders : rawRows)
-                         else map
-                              (floor . (fromIntegral (writerColumns opts) *))
-                              widths
-  let makeRow = hcat . intersperse (lblock 1 (text " ")) .
-                   zipWith3 alignHeader aligns widthsInChars
-  let rows' = map makeRow rawRows
-  let head' = makeRow rawHeaders
-  let maxRowHeight = maximum $ map height (head':rows')
-  let underline = cat $ intersperse (text " ") $
-                  map (\width -> text (replicate width '-')) widthsInChars
-  let border
-        | maxRowHeight > 1 = text (replicate (sum widthsInChars +
-                 length widthsInChars - 1) '-')
-        | headless = underline
-        | otherwise = empty
-  let head'' = if headless
-                  then empty
-                  else border <> cr <> head'
-  let body = if maxRowHeight > 1
-                then vsep rows'
-                else vcat rows'
-  let bottom = if headless
-                  then underline
-                  else border
-  return $ head'' $$ underline $$ body $$ bottom
+  return $ vcat contents <> blankline
+blockToHaddock opts (Figure _ (Caption _ longcapt) body) =
+  -- Haddock has no concept of figures, floats, or captions.
+  fmap (<> blankline) (blockListToHaddock opts (body ++ longcapt))
 
 -- | Convert bullet list item (list of blocks) to haddock
 bulletListItemToHaddock :: PandocMonad m
-                        => WriterOptions -> [Block] -> StateT WriterState m Doc
+                        => WriterOptions -> [Block] -> StateT WriterState m (Doc Text)
 bulletListItemToHaddock opts items = do
   contents <- blockListToHaddock opts items
   let sps = replicate (writerTabStop opts - 2) ' '
   let start = text ('-' : ' ' : sps)
-  -- remove trailing blank line if it is a tight list
-  let contents' = case reverse items of
-                       (BulletList xs:_) | isTightList xs ->
-                            chomp contents <> cr
-                       (OrderedList _ xs:_) | isTightList xs ->
-                            chomp contents <> cr
-                       _ -> contents
-  return $ hang (writerTabStop opts) start $ contents' <> cr
+  return $ hang (writerTabStop opts) start contents $$
+           if endsWithPlain items
+              then cr
+              else blankline
 
 -- | Convert ordered list item (a list of blocks) to haddock
 orderedListItemToHaddock :: PandocMonad m
                          => WriterOptions -- ^ options
-                         -> String        -- ^ list item marker
+                         -> Text        -- ^ list item marker
                          -> [Block]       -- ^ list item (list of blocks)
-                         -> StateT WriterState m Doc
+                         -> StateT WriterState m (Doc Text)
 orderedListItemToHaddock opts marker items = do
   contents <- blockListToHaddock opts items
-  let sps = case length marker - writerTabStop opts of
+  let sps = case T.length marker - writerTabStop opts of
                    n | n > 0 -> text $ replicate n ' '
                    _ -> text " "
-  let start = text marker <> sps
-  return $ hang (writerTabStop opts) start $ contents <> cr
+  let start = literal marker <> sps
+  return $ hang (writerTabStop opts) start contents $$
+           if endsWithPlain items
+              then cr
+              else blankline
 
 -- | Convert definition list item (label, list of blocks) to haddock
 definitionListItemToHaddock :: PandocMonad m
                             => WriterOptions
                             -> ([Inline],[[Block]])
-                            -> StateT WriterState m Doc
+                            -> StateT WriterState m (Doc Text)
 definitionListItemToHaddock opts (label, defs) = do
   labelText <- inlineListToHaddock opts label
   defs' <- mapM (mapM (blockToHaddock opts)) defs
-  let contents = vcat $ map (\d -> hang 4 empty $ vcat d <> cr) defs'
-  return $ nowrap (brackets labelText) <> cr <> contents <> cr
+  let contents = (if isTightList defs then vcat else vsep) $
+                 map (\d -> hang 4 empty $ vcat d <> cr) defs'
+  return $ nowrap (brackets labelText) $$ contents $$
+           if isTightList defs
+              then cr
+              else blankline
 
 -- | Convert list of Pandoc block elements to haddock
 blockListToHaddock :: PandocMonad m
                    => WriterOptions -- ^ Options
                    -> [Block]       -- ^ List of block elements
-                   -> StateT WriterState m Doc
+                   -> StateT WriterState m (Doc Text)
 blockListToHaddock opts blocks =
-  mapM (blockToHaddock opts) blocks >>= return . cat
+  mconcat <$> mapM (blockToHaddock opts) blocks
 
 -- | Convert list of Pandoc inline elements to haddock.
 inlineListToHaddock :: PandocMonad m
-                    => WriterOptions -> [Inline] -> StateT WriterState m Doc
+                    => WriterOptions -> [Inline] -> StateT WriterState m (Doc Text)
 inlineListToHaddock opts lst =
-  mapM (inlineToHaddock opts) lst >>= return . cat
+  mconcat <$> mapM (inlineToHaddock opts) lst
 
 -- | Convert Pandoc inline element to haddock.
 inlineToHaddock :: PandocMonad m
-                => WriterOptions -> Inline -> StateT WriterState m Doc
+                => WriterOptions -> Inline -> StateT WriterState m (Doc Text)
 inlineToHaddock opts (Span (ident,_,_) ils) = do
   contents <- inlineListToHaddock opts ils
-  if not (null ident) && null ils
-     then return $ "#" <> text ident <> "#"
+  if not (T.null ident) && null ils
+     then return $ "#" <> literal ident <> "#"
      else return contents
 inlineToHaddock opts (Emph lst) = do
   contents <- inlineListToHaddock opts lst
   return $ "/" <> contents <> "/"
+-- Underline is not supported, treat the same as Emph
+inlineToHaddock opts (Underline lst) =
+  inlineToHaddock opts (Emph lst)
 inlineToHaddock opts (Strong lst) = do
   contents <- inlineListToHaddock opts lst
   return $ "__" <> contents <> "__"
@@ -301,16 +242,15 @@
   contents <- inlineListToHaddock opts lst
   return $ "“" <> contents <> "”"
 inlineToHaddock _ (Code _ str) =
-  return $ "@" <> text (escapeString str) <> "@"
+  return $ "@" <> literal (escapeString str) <> "@"
 inlineToHaddock _ (Str str) =
-  return $ text $ escapeString str
-inlineToHaddock opts (Math mt str) = do
-  let adjust x = case mt of
-                      DisplayMath -> cr <> x <> cr
-                      InlineMath  -> x
-  adjust <$> (lift (texMathToInlines mt str) >>= inlineListToHaddock opts)
+  return $ literal $ escapeString str
+inlineToHaddock _ (Math mt str) =
+  return $ case mt of
+    DisplayMath -> cr <> "\\[" <> literal str <> "\\]" <> cr
+    InlineMath  -> "\\(" <> literal str <> "\\)"
 inlineToHaddock _ il@(RawInline f str)
-  | f == "haddock" = return $ text str
+  | f == "haddock" = return $ literal str
   | otherwise = do
     report $ InlineNotRendered il
     return empty
@@ -324,12 +264,12 @@
 inlineToHaddock _ Space = return space
 inlineToHaddock opts (Cite _ lst) = inlineListToHaddock opts lst
 inlineToHaddock _ (Link _ txt (src, _)) = do
-  let linktext = text $ escapeString $ stringify txt
+  let linktext = literal $ escapeString $ stringify txt
   let useAuto = isURI src &&
                 case txt of
                       [Str s] | escapeURI s == src -> True
                       _       -> False
-  return $ nowrap $ "<" <> text src <>
+  return $ nowrap $ "<" <> literal src <>
            (if useAuto then empty else space <> linktext) <> ">"
 inlineToHaddock opts (Image attr alternate (source, tit)) = do
   linkhaddock <- inlineToHaddock opts (Link attr alternate (source, tit))
@@ -338,5 +278,5 @@
 inlineToHaddock opts (Note contents) = do
   modify (\st -> st{ stNotes = contents : stNotes st })
   st <- get
-  let ref = text $ writerIdentifierPrefix opts ++ show (length $ stNotes st)
+  let ref = literal $ writerIdentifierPrefix opts <> tshow (length $ stNotes st)
   return $ "<#notes [" <> ref <> "]>"
diff --git a/src/Text/Pandoc/Writers/ICML.hs b/src/Text/Pandoc/Writers/ICML.hs
--- a/src/Text/Pandoc/Writers/ICML.hs
+++ b/src/Text/Pandoc/Writers/ICML.hs
@@ -1,10 +1,10 @@
-{-# LANGUAGE FlexibleContexts    #-}
-{-# LANGUAGE OverloadedStrings   #-}
+{-# LANGUAGE FlexibleContexts #-}
+{-# LANGUAGE OverloadedStrings #-}
 {-# LANGUAGE ScopedTypeVariables #-}
 
 {- |
    Module      : Text.Pandoc.Writers.ICML
-   Copyright   : Copyright (C) 2013-2017 github.com/mb21
+   Copyright   : Copyright (C) 2013-2020 github.com/mb21
    License     : GNU GPL, version 2 or above
 
    Stability   : alpha
@@ -17,31 +17,34 @@
 -}
 module Text.Pandoc.Writers.ICML (writeICML) where
 import Control.Monad.Except (catchError)
+import Control.Monad (liftM2)
 import Control.Monad.State.Strict
-import Data.List (intersperse, isInfixOf, isPrefixOf, stripPrefix)
-import Data.Maybe (fromMaybe)
+    ( MonadTrans(lift), StateT(runStateT), MonadState(state, get, put) )
+import Data.List (intersperse)
+import Data.Maybe (fromMaybe, maybeToList)
 import qualified Data.Set as Set
-import Data.Text as Text (breakOnAll, pack)
+import qualified Data.Text as Text
 import Data.Text (Text)
-import Text.Pandoc.Class (PandocMonad, report)
-import qualified Text.Pandoc.Class as P
+import Text.Pandoc.Class.PandocMonad (PandocMonad, fetchItem, report)
 import Text.Pandoc.Definition
 import Text.Pandoc.ImageSize
 import Text.Pandoc.Logging
 import Text.Pandoc.Options
-import Text.Pandoc.Pretty
-import Text.Pandoc.Shared (isURI, linesToPara, splitBy)
-import Text.Pandoc.Templates (renderTemplate')
+import Text.DocLayout hiding (link)
+import Text.Pandoc.Shared
+import Text.Pandoc.URI (isURI)
+import Text.Pandoc.Templates (renderTemplate)
 import Text.Pandoc.Writers.Math (texMathToInlines)
 import Text.Pandoc.Writers.Shared
 import Text.Pandoc.XML
 
-type Style = [String]
-type Hyperlink = [(Int, String)]
+type Style = [Text]
+type Hyperlink = [(Int, Text)]
 
 data WriterState = WriterState{
-    blockStyles  :: Set.Set String
-  , inlineStyles :: Set.Set String
+    blockStyles  :: Set.Set Text
+  , inlineStyles :: Set.Set Text
+  , objectStyles :: Set.Set Text
   , links        :: Hyperlink
   , listDepth    :: Int
   , maxListDepth :: Int
@@ -53,21 +56,24 @@
 defaultWriterState = WriterState{
     blockStyles  = Set.empty
   , inlineStyles = Set.empty
+  , objectStyles = Set.empty
   , links        = []
   , listDepth    = 1
   , maxListDepth = 0
   }
 
 -- inline names (appear in InDesign's character styles pane)
-emphName        :: String
-strongName      :: String
-strikeoutName   :: String
-superscriptName :: String
-subscriptName   :: String
-smallCapsName   :: String
-codeName        :: String
-linkName        :: String
+emphName        :: Text
+underlineName   :: Text
+strongName      :: Text
+strikeoutName   :: Text
+superscriptName :: Text
+subscriptName   :: Text
+smallCapsName   :: Text
+codeName        :: Text
+linkName        :: Text
 emphName        = "Italic"
+underlineName   = "Underline"
 strongName      = "Bold"
 strikeoutName   = "Strikeout"
 superscriptName = "Superscript"
@@ -77,31 +83,31 @@
 linkName        = "Link"
 
 -- block element names (appear in InDesign's paragraph styles pane)
-paragraphName     :: String
-figureName        :: String
-imgCaptionName    :: String
-codeBlockName     :: String
-blockQuoteName    :: String
-orderedListName   :: String
-bulletListName    :: String
-defListTermName   :: String
-defListDefName    :: String
-headerName        :: String
-tableName         :: String
-tableHeaderName   :: String
-tableCaptionName  :: String
-alignLeftName     :: String
-alignRightName    :: String
-alignCenterName   :: String
-firstListItemName :: String
-beginsWithName    :: String
-lowerRomanName    :: String
-upperRomanName    :: String
-lowerAlphaName    :: String
-upperAlphaName    :: String
-subListParName    :: String
-footnoteName      :: String
-citeName          :: String
+paragraphName     :: Text
+figureName        :: Text
+imgCaptionName    :: Text
+codeBlockName     :: Text
+blockQuoteName    :: Text
+orderedListName   :: Text
+bulletListName    :: Text
+defListTermName   :: Text
+defListDefName    :: Text
+headerName        :: Text
+tableName         :: Text
+tableHeaderName   :: Text
+tableCaptionName  :: Text
+alignLeftName     :: Text
+alignRightName    :: Text
+alignCenterName   :: Text
+firstListItemName :: Text
+beginsWithName    :: Text
+lowerRomanName    :: Text
+upperRomanName    :: Text
+lowerAlphaName    :: Text
+upperAlphaName    :: Text
+subListParName    :: Text
+footnoteName      :: Text
+citeName          :: Text
 paragraphName     = "Paragraph"
 figureName        = "Figure"
 imgCaptionName    = "Caption"
@@ -130,34 +136,40 @@
 
 -- | Convert Pandoc document to string in ICML format.
 writeICML :: PandocMonad m => WriterOptions -> Pandoc -> m Text
-writeICML opts (Pandoc meta blocks) = do
+writeICML opts doc = do
+  let Pandoc meta blocks = ensureValidXmlIdentifiers doc
   let colwidth = if writerWrapText opts == WrapAuto
                     then Just $ writerColumns opts
                     else Nothing
-      render' :: Doc -> Text
-      render' = render colwidth
-      renderMeta f s = liftM (render' . fst) $ runStateT (f opts [] s) defaultWriterState
-  metadata <- metaToJSON opts
-             (renderMeta blocksToICML)
-             (renderMeta inlinesToICML)
+      renderBlockMeta f s = fst <$> runStateT (f opts [] s) defaultWriterState
+      renderInlineMeta f s = fst <$> runStateT (f opts [] "" s) defaultWriterState
+  metadata <- metaToContext opts
+             (renderBlockMeta blocksToICML)
+             (renderInlineMeta inlinesToICML)
              meta
-  (doc, st) <- runStateT (blocksToICML opts [] blocks) defaultWriterState
-  let main    = render' doc
-      context = defField "body" main
-              $ defField "charStyles" (render' $ charStylesToDoc st)
-              $ defField "parStyles"  (render' $ parStylesToDoc st)
-              $ defField "hyperlinks" (render' $ hyperlinksToDoc $ links st) metadata
-  case writerTemplate opts of
-       Nothing  -> return main
-       Just tpl -> renderTemplate' tpl context
+  (main, st) <- runStateT (blocksToICML opts [] blocks) defaultWriterState
+  let context = defField "body" main
+              $ defField "charStyles"   (charStylesToDoc st)
+              $ defField "parStyles"    (parStylesToDoc st)
+              $ defField "objectStyles" (objectStylesToDoc st)
+              $ defField "hyperlinks"   (hyperlinksToDoc $ links st) metadata
+  return $ render colwidth $
+    (if writerPreferAscii opts then fmap toEntities else id) $
+    case writerTemplate opts of
+       Nothing  -> main
+       Just tpl -> renderTemplate tpl context
 
--- | Auxilary functions for parStylesToDoc and charStylesToDoc.
-contains :: String -> (String, (String, String)) -> [(String, String)]
-contains s rule =
-  [snd rule | isInfixOf (fst rule) s]
+-- | Auxiliary functions for parStylesToDoc and charStylesToDoc.
+contains :: Text -> (Text, (Text, Text)) -> [(Text, Text)] -> [(Text, Text)]
+contains s (t, (k,v)) attrs =
+  if t `Text.isInfixOf` s
+     then case lookup k attrs of -- avoid duplicates, #9158
+            Nothing -> (k, v) : attrs
+            Just _ -> attrs
+     else attrs
 
 -- | The monospaced font to use as default.
-monospacedFont :: Doc
+monospacedFont :: Doc Text
 monospacedFont = inTags False "AppliedFont" [("type", "string")] $ text "Courier New"
 
 -- | How much to indent blockquotes etc.
@@ -169,30 +181,30 @@
 defaultListIndent = 10
 
 -- other constants
-lineSeparator :: String
+lineSeparator :: Text
 lineSeparator = "&#x2028;"
 
 -- | Convert a WriterState with its block styles to the ICML listing of Paragraph Styles.
-parStylesToDoc :: WriterState -> Doc
+parStylesToDoc :: WriterState -> Doc Text
 parStylesToDoc st = vcat $ map makeStyle $ Set.toAscList $ blockStyles st
   where
     makeStyle s =
-      let countSubStrs sub str = length $ Text.breakOnAll (Text.pack sub) (Text.pack str)
-          attrs = concatMap (contains s) [
+      let countSubStrs sub str = length $ Text.breakOnAll sub str
+          attrs = foldr (contains s) [] [
                                (defListTermName, ("BulletsAndNumberingListType", "BulletList"))
                              , (defListTermName, ("FontStyle", "Bold"))
                              , (tableHeaderName, ("FontStyle", "Bold"))
                              , (alignLeftName,   ("Justification", "LeftAlign"))
                              , (alignRightName,  ("Justification", "RightAlign"))
                              , (alignCenterName, ("Justification", "CenterAlign"))
-                             , (headerName++"1", ("PointSize", "36"))
-                             , (headerName++"2", ("PointSize", "30"))
-                             , (headerName++"3", ("PointSize", "24"))
-                             , (headerName++"4", ("PointSize", "18"))
-                             , (headerName++"5", ("PointSize", "14"))
+                             , (headerName<>"1", ("PointSize", "36"))
+                             , (headerName<>"2", ("PointSize", "30"))
+                             , (headerName<>"3", ("PointSize", "24"))
+                             , (headerName<>"4", ("PointSize", "18"))
+                             , (headerName<>"5", ("PointSize", "14"))
                              ]
           -- what is the most nested list type, if any?
-          (isBulletList, isOrderedList) = findList $ reverse $ splitBy (==' ') s
+          (isBulletList, isOrderedList) = findList $ reverse $ splitTextBy (==' ') s
             where
               findList [] = (False, False)
               findList (x:xs) | x == bulletListName  = (True, False)
@@ -200,23 +212,23 @@
                               | otherwise = findList xs
           nBuls = countSubStrs bulletListName s
           nOrds = countSubStrs orderedListName s
-          attrs' = numbering ++ listType ++ indent ++ attrs
+          attrs' = numbering <> listType <> indent <> attrs
             where
-              numbering | isOrderedList = [("NumberingExpression", "^#.^t"), ("NumberingLevel", show nOrds)]
+              numbering | isOrderedList = [("NumberingExpression", "^#.^t"), ("NumberingLevel", tshow nOrds)]
                         | otherwise     = []
-              listType | isOrderedList && not (subListParName `isInfixOf` s)
+              listType | isOrderedList && not (subListParName `Text.isInfixOf` s)
                            = [("BulletsAndNumberingListType", "NumberedList")]
-                       | isBulletList && not (subListParName `isInfixOf` s)
+                       | isBulletList && not (subListParName `Text.isInfixOf` s)
                            = [("BulletsAndNumberingListType", "BulletList")]
                        | otherwise = []
-              indent = [("LeftIndent", show indt)]
+              indent = [("LeftIndent", tshow indt)]
                 where
                   nBlockQuotes = countSubStrs blockQuoteName s
                   nDefLists = countSubStrs defListDefName s
                   indt = max 0 $ defaultListIndent*(nBuls + nOrds - 1) + defaultIndent*(nBlockQuotes + nDefLists)
           props = inTags True "Properties" [] (basedOn $$ tabList $$ numbForm)
             where
-              font = if codeBlockName `isInfixOf` s
+              font = if codeBlockName `Text.isInfixOf` s
                         then monospacedFont
                         else empty
               basedOn = inTags False "BasedOn" [("type", "object")] (text "$ID/NormalParagraphStyle") $$ font
@@ -231,80 +243,98 @@
                                   ]
                            else empty
               makeNumb name = inTags False "NumberingFormat" [("type", "string")] (text name)
-              numbForm | isInfixOf lowerRomanName s = makeNumb "i, ii, iii, iv..."
-                       | isInfixOf upperRomanName s = makeNumb "I, II, III, IV..."
-                       | isInfixOf lowerAlphaName s = makeNumb "a, b, c, d..."
-                       | isInfixOf upperAlphaName s = makeNumb "A, B, C, D..."
+              numbForm | Text.isInfixOf lowerRomanName s = makeNumb "i, ii, iii, iv..."
+                       | Text.isInfixOf upperRomanName s = makeNumb "I, II, III, IV..."
+                       | Text.isInfixOf lowerAlphaName s = makeNumb "a, b, c, d..."
+                       | Text.isInfixOf upperAlphaName s = makeNumb "A, B, C, D..."
                        | otherwise = empty
-      in  inTags True "ParagraphStyle" ([("Self", "ParagraphStyle/"++s), ("Name", s)] ++ attrs') props
+      in  inTags True "ParagraphStyle" ([("Self", "ParagraphStyle/"<>s), ("Name", s)] ++ attrs') props
 
 -- | Convert a WriterState with its inline styles to the ICML listing of Character Styles.
-charStylesToDoc :: WriterState -> Doc
+charStylesToDoc :: WriterState -> Doc Text
 charStylesToDoc st = vcat $ map makeStyle $ Set.toAscList $ inlineStyles st
   where
     makeStyle s =
-      let attrs = concatMap (contains s) [
+      let attrs = foldr (contains s) [] [
                                (strikeoutName,   ("StrikeThru", "true"))
                              , (superscriptName, ("Position", "Superscript"))
                              , (subscriptName,   ("Position", "Subscript"))
                              , (smallCapsName,   ("Capitalization", "SmallCaps"))
                              ]
-          attrs' | isInfixOf emphName s && isInfixOf strongName s = ("FontStyle", "Bold Italic") : attrs
-                 | isInfixOf strongName s                         = ("FontStyle", "Bold") : attrs
-                 | isInfixOf emphName s                           = ("FontStyle", "Italic") : attrs
-                 | otherwise                                      = attrs
+          attrs' | Text.isInfixOf emphName s && Text.isInfixOf strongName s
+                                               = ("FontStyle", "Bold Italic") : attrs
+                 | Text.isInfixOf strongName s = ("FontStyle", "Bold") : attrs
+                 | Text.isInfixOf emphName s   = ("FontStyle", "Italic") : attrs
+                 | otherwise                   = attrs
           props = inTags True "Properties" [] $
                     inTags False "BasedOn" [("type", "object")] (text "$ID/NormalCharacterStyle") $$ font
                   where
                     font =
-                      if codeName `isInfixOf` s
+                      if codeName `Text.isInfixOf` s
                          then monospacedFont
                          else empty
-      in  inTags True "CharacterStyle" ([("Self", "CharacterStyle/"++s), ("Name", s)] ++ attrs') props
+      in  inTags True "CharacterStyle" ([("Self", "CharacterStyle/"<>s), ("Name", s)] ++ attrs') props
 
+-- | Convert a WriterState with its object styles to the ICML listing of Object Styles.
+objectStylesToDoc :: WriterState -> Doc Text
+objectStylesToDoc st = vcat $ map makeStyle $ Set.toAscList $ objectStyles st
+  where
+    makeStyle s =
+      let attrs = []
+          props = inTags True "Properties" [] $
+                    inTags False "BasedOn" [("type", "string")] (text "$ID/None")
+      in  inTags True "ObjectStyle" ([("Self", "ObjectStyle/"<>s), ("Name", s)] ++ attrs) props
+
 -- | Escape colon characters as %3a
-escapeColons :: String -> String
-escapeColons (x:xs)
-  | x == ':' = "%3a" ++ escapeColons xs
-  | otherwise = x : escapeColons xs
-escapeColons []     = []
+escapeColons :: Text -> Text
+escapeColons txt = Text.replace ":" "%3a" txt
 
+-- | figure out the link destination for a given URL
+-- | HyperlinkURLDestination with more than one colon crashes CS6
+makeDest :: Text -> Doc Text
+makeDest txt = literal $
+  if "#" `Text.isPrefixOf` txt
+  then "HyperlinkTextDestination/" <> escTxt
+  else "HyperlinkURLDestination/" <> escTxt
+  where
+    escTxt = escapeColons $ escapeStringForXML txt
+
 -- | Convert a list of (identifier, url) pairs to the ICML listing of hyperlinks.
-hyperlinksToDoc :: Hyperlink -> Doc
+hyperlinksToDoc :: Hyperlink -> Doc Text
 hyperlinksToDoc []     = empty
 hyperlinksToDoc (x:xs) = hyp x $$ hyperlinksToDoc xs
   where
     hyp (ident, url) = hdest $$ hlink
       where
-        hdest = selfClosingTag "HyperlinkURLDestination"
-                  [("Self", "HyperlinkURLDestination/"++escapeColons url), ("Name","link"), ("DestinationURL",url), ("DestinationUniqueKey","1")] -- HyperlinkURLDestination with more than one colon crashes CS6
-        hlink = inTags True "Hyperlink" [("Self","uf-"++show ident),  ("Name",url),
-                    ("Source","htss-"++show ident), ("Visible","true"), ("DestinationUniqueKey","1")]
+        hdest = if "#" `Text.isPrefixOf` url
+                then empty
+                else selfClosingTag "HyperlinkURLDestination"
+                  [("Self", "HyperlinkURLDestination/"<>escapeColons url), ("Name","link"), ("DestinationURL",url), ("DestinationUniqueKey","1")] -- HyperlinkURLDestination with more than one colon crashes CS6
+        hlink = inTags True "Hyperlink" [("Self","uf-"<>tshow ident),  ("Name",url),
+                    ("Source","htss-"<>tshow ident), ("Visible","false"), ("DestinationUniqueKey","1")]
                   $ inTags True "Properties" []
                   $ inTags False "BorderColor" [("type","enumeration")] (text "Black")
-                  $$ inTags False "Destination" [("type","object")] (text $ "HyperlinkURLDestination/"++(escapeColons (escapeStringForXML url))) -- HyperlinkURLDestination with more than one colon crashes CS6
+                 $$ inTags False "Destination" [("type","object")] (makeDest url)
 
+-- | Key for specifying user-defined styles
+dynamicStyleKey :: Text
+dynamicStyleKey = "custom-style"
 
 -- | Convert a list of Pandoc blocks to ICML.
-blocksToICML :: PandocMonad m => WriterOptions -> Style -> [Block] -> WS m Doc
+blocksToICML :: PandocMonad m => WriterOptions -> Style -> [Block] -> WS m (Doc Text)
 blocksToICML opts style lst = do
   docs <- mapM (blockToICML opts style) lst
   return $ intersperseBrs docs
 
 -- | Convert a Pandoc block element to ICML.
-blockToICML :: PandocMonad m => WriterOptions -> Style -> Block -> WS m Doc
-blockToICML opts style (Plain lst) = parStyle opts style lst
--- title beginning with fig: indicates that the image is a figure
-blockToICML opts style (Para img@[Image _ txt (_,'f':'i':'g':':':_)]) = do
-  figure  <- parStyle opts (figureName:style) img
-  caption <- parStyle opts (imgCaptionName:style) txt
-  return $ intersperseBrs [figure, caption]
-blockToICML opts style (Para lst) = parStyle opts (paragraphName:style) lst
+blockToICML :: PandocMonad m => WriterOptions -> Style -> Block -> WS m (Doc Text)
+blockToICML opts style (Plain lst) = parStyle opts style "" lst
+blockToICML opts style (Para lst) = parStyle opts (paragraphName:style) "" lst
 blockToICML opts style (LineBlock lns) =
   blockToICML opts style $ linesToPara lns
-blockToICML opts style (CodeBlock _ str) = parStyle opts (codeBlockName:style) [Str str]
+blockToICML opts style (CodeBlock _ str) = parStyle opts (codeBlockName:style) "" [Str str]
 blockToICML _ _ b@(RawBlock f str)
-  | f == Format "icml" = return $ text str
+  | f == Format "icml" = return $ literal str
   | otherwise          = do
       report $ BlockNotRendered b
       return empty
@@ -312,20 +342,25 @@
 blockToICML opts style (OrderedList attribs lst) = listItemsToICML opts orderedListName style (Just attribs) lst
 blockToICML opts style (BulletList lst) = listItemsToICML opts bulletListName style Nothing lst
 blockToICML opts style (DefinitionList lst) = intersperseBrs `fmap` mapM (definitionListItemToICML opts style) lst
-blockToICML opts style (Header lvl _ lst) =
-  let stl = (headerName ++ show lvl):style
-  in parStyle opts stl lst
+blockToICML opts style (Header lvl (ident, cls, _) lst) =
+  let stl = (headerName <> tshow lvl <> unnumbered):style
+      unnumbered = if "unnumbered" `elem` cls
+                   then " (unnumbered)"
+                   else ""
+  in parStyle opts stl ident lst
 blockToICML _ _ HorizontalRule = return empty -- we could insert a page break instead
-blockToICML opts style (Table caption aligns widths headers rows) =
-  let style' = tableName : style
+blockToICML opts style (Table attr blkCapt specs thead tbody tfoot) =
+  let (caption, aligns, widths, headers, rows) =
+        toLegacyTable blkCapt specs thead tbody tfoot
+      style' = tableName : style
       noHeader  = all null headers
       nrHeaders = if noHeader
                      then "0"
                      else "1"
       nrRows = length rows
-      nrCols = if null rows
-                  then 0
-                  else length $ head rows
+      nrCols = case rows of
+                   [] -> 0
+                   (r:_) -> length r
       rowsToICML [] _ = return empty
       rowsToICML (col:rest) rowNr =
         liftM2 ($$) (colsToICML col aligns rowNr (0::Int)) $ rowsToICML rest (rowNr+1)
@@ -341,7 +376,7 @@
                  | otherwise = stl
         c <- blocksToICML opts stl' cell
         let cl = return $ inTags True "Cell"
-                   [("Name", show colNr ++":"++ show rowNr), ("AppliedCellStyle","CellStyle/Cell")] c
+                   [("Name", tshow colNr <>":"<> tshow rowNr), ("AppliedCellStyle","CellStyle/Cell")] c
         liftM2 ($$) cl $ colsToICML rest restAligns rowNr (colNr+1)
   in  do
       let tabl = if noHeader
@@ -349,21 +384,34 @@
                     else headers:rows
       cells <- rowsToICML tabl (0::Int)
       let colWidths w =
-            [("SingleColumnWidth",show $ 500 * w) | w > 0]
-      let tupToDoc tup = selfClosingTag "Column" $ ("Name",show $ fst tup) : colWidths (snd tup)
+            [("SingleColumnWidth",tshow $ 500 * w) | w > 0]
+      let tupToDoc tup = selfClosingTag "Column" $ ("Name",tshow $ fst tup) : colWidths (snd tup)
       let colDescs = vcat $ zipWith (curry tupToDoc) [0..nrCols-1] widths
+      let (_,_,kvs) = attr
+      let dynamicStyle = fromMaybe "Table" (lookup dynamicStyleKey kvs)
       let tableDoc = return $ inTags True "Table" [
-                         ("AppliedTableStyle","TableStyle/Table")
+                         ("AppliedTableStyle","TableStyle/" <> dynamicStyle)
                        , ("HeaderRowCount", nrHeaders)
-                       , ("BodyRowCount", show nrRows)
-                       , ("ColumnCount", show nrCols)
+                       , ("BodyRowCount", tshow nrRows)
+                       , ("ColumnCount", tshow nrCols)
                        ] (colDescs $$ cells)
-      liftM2 ($$) tableDoc $ parStyle opts (tableCaptionName:style) caption
-blockToICML opts style (Div _ lst) = blocksToICML opts style lst
-blockToICML _ _ Null = return empty
+      liftM2 ($$) tableDoc $ parStyle opts (tableCaptionName:style) "" caption
+blockToICML opts style (Div (_ident, _, kvs) lst) =
+  let dynamicStyle = maybeToList $ lookup dynamicStyleKey kvs
+  in  blocksToICML opts (dynamicStyle <> style) lst
+blockToICML opts style (Figure attr capt@(Caption _ longcapt) body) =
+  case body of
+    [Plain [img@(Image {})]] -> do
+      figure  <- parStyle opts (figureName:style) "" [img]
+      caption <- parStyle opts (imgCaptionName:style) "" $
+                 blocksToInlines longcapt
+      return $ intersperseBrs [figure, caption]
+    _ -> -- fallback to rendering the figure as a Div
+      blockToICML opts style $ figureDiv attr capt body
 
+
 -- | Convert a list of lists of blocks to ICML list items.
-listItemsToICML :: PandocMonad m => WriterOptions -> String -> Style -> Maybe ListAttributes -> [[Block]] -> WS m Doc
+listItemsToICML :: PandocMonad m => WriterOptions -> Text -> Style -> Maybe ListAttributes -> [[Block]] -> WS m (Doc Text)
 listItemsToICML _ _ _ _ [] = return empty
 listItemsToICML opts listType style attribs (first:rest) = do
   st <- get
@@ -378,7 +426,7 @@
   return $ intersperseBrs docs
 
 -- | Convert a list of blocks to ICML list items.
-listItemToICML :: PandocMonad m => WriterOptions -> Style -> Bool-> Maybe ListAttributes -> [Block] -> WS m Doc
+listItemToICML :: PandocMonad m => WriterOptions -> Style -> Bool-> Maybe ListAttributes -> [Block] -> WS m (Doc Text)
 listItemToICML opts style isFirst attribs item =
   let makeNumbStart (Just (beginsWith, numbStl, _)) =
         let doN DefaultStyle = []
@@ -388,77 +436,87 @@
             doN UpperAlpha   = [upperAlphaName]
             doN _            = []
             bw =
-              [beginsWithName ++ show beginsWith | beginsWith > 1]
+              [beginsWithName <> tshow beginsWith | beginsWith > 1]
         in  doN numbStl ++ bw
       makeNumbStart Nothing = []
       stl = if isFirst
                then firstListItemName:style
                else style
       stl' = makeNumbStart attribs ++ stl
-  in  if length item > 1
-         then do
-           let insertTab (Para lst) = blockToICML opts (subListParName:style) $ Para $ Str "\t":lst
-               insertTab block      = blockToICML opts style block
-           f <- blockToICML opts stl' $ head item
-           r <- mapM insertTab $ tail item
-           return $ intersperseBrs (f : r)
-         else blocksToICML opts stl' item
+  in  case item of
+          (i:rest@(_:_)) -> do
+             let insertTab (Para lst) = blockToICML opts (subListParName:style)
+                                         (Para (Str "\t":lst))
+                 insertTab block      = blockToICML opts style block
+             f <- blockToICML opts stl' i
+             r <- mapM insertTab rest
+             return $ intersperseBrs (f : r)
+          _ -> blocksToICML opts stl' item
 
-definitionListItemToICML :: PandocMonad m => WriterOptions -> Style -> ([Inline],[[Block]]) -> WS m Doc
+definitionListItemToICML :: PandocMonad m => WriterOptions -> Style -> ([Inline],[[Block]]) -> WS m (Doc Text)
 definitionListItemToICML opts style (term,defs) = do
-  term' <- parStyle opts (defListTermName:style) term
+  term' <- parStyle opts (defListTermName:style) "" term
   defs' <- mapM (blocksToICML opts (defListDefName:style)) defs
   return $ intersperseBrs (term' : defs')
 
 
 -- | Convert a list of inline elements to ICML.
-inlinesToICML :: PandocMonad m => WriterOptions -> Style -> [Inline] -> WS m Doc
-inlinesToICML opts style lst = vcat `fmap` mapM (inlineToICML opts style) (mergeSpaces lst)
+inlinesToICML :: PandocMonad m => WriterOptions -> Style -> Text -> [Inline] -> WS m (Doc Text)
+inlinesToICML opts style ident lst = vcat `fmap` mapM (inlineToICML opts style ident) (mergeStrings opts lst)
 
 -- | Convert an inline element to ICML.
-inlineToICML :: PandocMonad m => WriterOptions -> Style -> Inline -> WS m Doc
-inlineToICML _    style (Str str) = charStyle style $ text $ escapeStringForXML str
-inlineToICML opts style (Emph lst) = inlinesToICML opts (emphName:style) lst
-inlineToICML opts style (Strong lst) = inlinesToICML opts (strongName:style) lst
-inlineToICML opts style (Strikeout lst) = inlinesToICML opts (strikeoutName:style) lst
-inlineToICML opts style (Superscript lst) = inlinesToICML opts (superscriptName:style) lst
-inlineToICML opts style (Subscript lst) = inlinesToICML opts (subscriptName:style) lst
-inlineToICML opts style (SmallCaps lst) = inlinesToICML opts (smallCapsName:style) lst
-inlineToICML opts style (Quoted SingleQuote lst) = inlinesToICML opts style $ [Str "‘"] ++ lst ++ [Str "’"]
-inlineToICML opts style (Quoted DoubleQuote lst) = inlinesToICML opts style $ [Str "“"] ++ lst ++ [Str "”"]
-inlineToICML opts style (Cite _ lst) = inlinesToICML opts (citeName:style) lst
-inlineToICML _    style (Code _ str) = charStyle (codeName:style) $ text $ escapeStringForXML str
-inlineToICML _    style Space = charStyle style space
-inlineToICML opts style SoftBreak =
+inlineToICML :: PandocMonad m => WriterOptions -> Style -> Text -> Inline -> WS m (Doc Text)
+inlineToICML _    style ident (Str str) = charStyle style ident $ literal $ escapeStringForXML str
+inlineToICML opts style ident (Emph lst) = inlinesToICML opts (emphName:style) ident lst
+inlineToICML opts style ident (Underline lst) = inlinesToICML opts (underlineName:style) ident lst
+inlineToICML opts style ident (Strong lst) = inlinesToICML opts (strongName:style) ident lst
+inlineToICML opts style ident (Strikeout lst) = inlinesToICML opts (strikeoutName:style) ident lst
+inlineToICML opts style ident (Superscript lst) = inlinesToICML opts (superscriptName:style) ident lst
+inlineToICML opts style ident (Subscript lst) = inlinesToICML opts (subscriptName:style) ident lst
+inlineToICML opts style ident (SmallCaps lst) = inlinesToICML opts (smallCapsName:style) ident lst
+inlineToICML opts style ident (Quoted SingleQuote lst) = inlinesToICML opts style ident $
+  mergeStrings opts $ [Str "‘"] ++ lst ++ [Str "’"]
+inlineToICML opts style ident (Quoted DoubleQuote lst) = inlinesToICML opts style ident $
+  mergeStrings opts $ [Str "“"] ++ lst ++ [Str "”"]
+inlineToICML opts style ident (Cite _ lst) = inlinesToICML opts (citeName:style) ident lst
+inlineToICML _    style ident (Code _ str) = charStyle (codeName:style) ident $ literal $ escapeStringForXML str
+inlineToICML _    style ident Space = charStyle style ident space
+inlineToICML opts style ident SoftBreak =
   case writerWrapText opts of
-       WrapAuto     -> charStyle style space
-       WrapNone     -> charStyle style space
-       WrapPreserve -> charStyle style cr
-inlineToICML _ style LineBreak = charStyle style $ text lineSeparator
-inlineToICML opts style (Math mt str) =
+       WrapAuto     -> charStyle style ident space
+       WrapNone     -> charStyle style ident space
+       WrapPreserve -> charStyle style ident cr
+inlineToICML _ style ident LineBreak = charStyle style ident $ literal lineSeparator
+inlineToICML opts style ident (Math mt str) =
   lift (texMathToInlines mt str) >>=
-    (fmap cat . mapM (inlineToICML opts style))
-inlineToICML _ _ il@(RawInline f str)
-  | f == Format "icml" = return $ text str
+    (fmap mconcat . mapM (inlineToICML opts style ident))
+inlineToICML _ _ _ il@(RawInline f str)
+  | f == Format "icml" = return $ literal str
   | otherwise          = do
       report $ InlineNotRendered il
       return empty
-inlineToICML opts style (Link _ lst (url, title)) = do
-  content <- inlinesToICML opts (linkName:style) lst
+inlineToICML opts style ident (Link _ lst (url, title)) = do
+  content <- inlinesToICML opts (linkName:style) ident lst
   state $ \st ->
-            let ident = if null $ links st
-                           then 1::Int
-                           else 1 + fst (head $ links st)
-                newst = st{ links = (ident, url):links st }
+            let link_id = case links st of
+                              [] -> 1 :: Int
+                              ((n,_):_) -> 1 + n
+                newst = st{ links = (link_id, url):links st }
                 cont  = inTags True "HyperlinkTextSource"
-                         [("Self","htss-"++show ident), ("Name",title), ("Hidden","false")] content
+                         [("Self","htss-"<>tshow link_id), ("Name",title), ("Hidden","false")] content
             in  (cont, newst)
-inlineToICML opts style (Image attr _ target) = imageICML opts style attr target
-inlineToICML opts style (Note lst) = footnoteToICML opts style lst
-inlineToICML opts style (Span _ lst) = inlinesToICML opts style lst
+inlineToICML opts style _ident (Image attr _ target) = imageICML opts style attr target
+inlineToICML opts style _ (Note lst) = footnoteToICML opts style lst
+inlineToICML opts style _ (Span (ident, _, kvs) lst) =
+  let dynamicStyle = maybeToList $ lookup dynamicStyleKey kvs
+  in  inlinesToICML opts (dynamicStyle <> style) ident lst
+-- ident will be the id of the span, that we need to use down in the hyperlink setter
+--  if T.null ident
+--     then
+--     else do
 
 -- | Convert a list of block elements to an ICML footnote.
-footnoteToICML :: PandocMonad m => WriterOptions -> Style -> [Block] -> WS m Doc
+footnoteToICML :: PandocMonad m => WriterOptions -> Style -> [Block] -> WS m (Doc Text)
 footnoteToICML opts style lst =
   let insertTab (Para ls) = blockToICML opts (footnoteName:style) $ Para $ Str "\t":ls
       insertTab block     = blockToICML opts (footnoteName:style) block
@@ -471,109 +529,166 @@
       $ inTags True "Footnote" [] $ number $$ intersperseBrs contents
 
 -- | Auxiliary function to merge Space elements into the adjacent Strs.
-mergeSpaces :: [Inline] -> [Inline]
-mergeSpaces (Str s:(x:(Str s':xs))) | isSp x =
-  mergeSpaces $ Str(s++" "++s') : xs
-mergeSpaces (x:(Str s:xs)) | isSp x = mergeSpaces $ Str (" "++s) : xs
-mergeSpaces (Str s:(x:xs)) | isSp x = mergeSpaces $ Str (s++" ") : xs
-mergeSpaces (x:xs) = x : mergeSpaces xs
-mergeSpaces []     = []
+mergeStrings :: WriterOptions -> [Inline] -> [Inline]
+mergeStrings opts = mergeStrings' . map spaceToStr
+  where spaceToStr Space = Str " "
+        spaceToStr SoftBreak = case writerWrapText opts of
+                                    WrapPreserve  -> Str "\n"
+                                    _             -> Str " "
+        spaceToStr x = x
 
-isSp :: Inline -> Bool
-isSp Space     = True
-isSp SoftBreak = True
-isSp _         = False
+        mergeStrings' (Str x : Str y : zs) = mergeStrings' (Str (x <> y) : zs)
+        mergeStrings' (x : xs) = x : mergeStrings' xs
+        mergeStrings' []       = []
 
 -- | Intersperse line breaks
-intersperseBrs :: [Doc] -> Doc
+intersperseBrs :: [Doc Text] -> Doc Text
 intersperseBrs = vcat . intersperse (selfClosingTag "Br" []) . filter (not . isEmpty)
 
 -- | Wrap a list of inline elements in an ICML Paragraph Style
-parStyle :: PandocMonad m => WriterOptions -> Style -> [Inline] -> WS m Doc
-parStyle opts style lst =
-  let slipIn x y = if null y
+parStyle :: PandocMonad m => WriterOptions -> Style -> Text -> [Inline] -> WS m (Doc Text)
+parStyle opts style ident lst =
+  let slipIn x y = if Text.null y
                       then x
-                      else x ++ " > " ++ y
-      stlStr = foldr slipIn [] $ reverse style
-      stl    = if null stlStr
+                      else x <> " > " <> y
+      stlStr = foldr slipIn "" $ reverse style
+      stl    = if Text.null stlStr
                   then ""
-                  else "ParagraphStyle/" ++ stlStr
+                  else "ParagraphStyle/" <> stlStr
       attrs  = ("AppliedParagraphStyle", stl)
       attrs' =  if firstListItemName `elem` style
                    then let ats = attrs : [("NumberingContinue", "false")]
-                            begins = filter (isPrefixOf beginsWithName) style
-                        in  if null begins
-                               then ats
-                               else let i = fromMaybe "" $ stripPrefix beginsWithName $ head begins
-                                    in  ("NumberingStartAt", i) : ats
+                            begins = filter (Text.isPrefixOf beginsWithName) style
+                        in  case begins of
+                                [] -> ats
+                                (b:_) ->
+                                   let i = fromMaybe ""
+                                             (Text.stripPrefix beginsWithName b)
+                                   in  ("NumberingStartAt", i) : ats
                    else [attrs]
   in  do
-      content <- inlinesToICML opts [] lst
+      content <- inlinesToICML opts [] ident lst
       let cont = inTags True "ParagraphStyleRange" attrs' content
       state $ \st -> (cont, st{ blockStyles = Set.insert stlStr $ blockStyles st })
 
+-- | Create the destination name
+makeDestName :: Text -> Text
+makeDestName name = "#" <> Text.replace " " "-" name
+
+-- | Create a HyperlinkTextDestination for a given identifier
+makeLinkDest :: Text -> Doc Text -> Doc Text
+makeLinkDest ident cont = vcat [
+    selfClosingTag "HyperlinkTextDestination"
+      [("Self", "HyperlinkTextDestination/"<>makeDestName ident), ("Name","Destination"), ("DestinationUniqueKey","1")]
+    , inTagsSimple "Content" $ flush cont
+  ]
+
+-- | Create the markup for the content (incl. named destinations)
+-- |  NOTE: since we have no easy way to get actual named dests, we just create them for any short content blocks
+makeContent :: Text -> Doc Text -> Doc Text
+makeContent ident cont
+              | isEmpty cont = empty
+              | not (Text.null ident) = makeLinkDest ident cont
+              | otherwise = inTagsSimple "Content" $ flush cont
+
 -- | Wrap a Doc in an ICML Character Style.
-charStyle :: PandocMonad m => Style -> Doc -> WS m Doc
-charStyle style content =
+charStyle :: PandocMonad m => Style -> Text -> Doc Text -> WS m (Doc Text)
+charStyle style ident content =
   let (stlStr, attrs) = styleToStrAttr style
-      doc = inTags True "CharacterStyleRange" attrs $ inTagsSimple "Content" $ flush content
+      doc = inTags True "CharacterStyleRange" attrs
+              $ makeContent ident content
   in
       state $ \st ->
-    let styles = if null stlStr
+    let styles = if Text.null stlStr
                     then st
                     else st{ inlineStyles = Set.insert stlStr $ inlineStyles st }
     in  (doc, styles)
 
 -- | Transform a Style to a tuple of String (eliminating duplicates and ordered) and corresponding attribute.
-styleToStrAttr :: Style -> (String, [(String, String)])
+styleToStrAttr :: Style -> (Text, [(Text, Text)])
 styleToStrAttr style =
-  let stlStr = unwords $ Set.toAscList $ Set.fromList style
+  let stlStr = Text.unwords $ Set.toAscList $ Set.fromList style
       stl    = if null style
                   then "$ID/NormalCharacterStyle"
-                  else "CharacterStyle/" ++ stlStr
+                  else "CharacterStyle/" <> stlStr
       attrs = [("AppliedCharacterStyle", stl)]
   in  (stlStr, attrs)
 
+-- | Key for specifying user-defined object (image) styles
+objectStyleKey :: Text
+objectStyleKey = "object-style"
+
 -- | Assemble an ICML Image.
-imageICML :: PandocMonad m => WriterOptions -> Style -> Attr -> Target -> WS m Doc
+imageICML :: PandocMonad m => WriterOptions -> Style -> Attr -> Target -> WS m (Doc Text)
 imageICML opts style attr (src, _) = do
   imgS <- catchError
-          (do (img, _) <- P.fetchItem src
+          (do (img, _) <- fetchItem src
               case imageSize opts img of
                 Right size -> return size
                 Left msg   -> do
                   report $ CouldNotDetermineImageSize src msg
                   return def)
            (\e -> do
-               report $ CouldNotFetchResource src (show e)
+               report $ CouldNotFetchResource src $ tshow e
                return def)
   let (ow, oh) = sizeInPoints imgS
       (imgWidth, imgHeight) = desiredSizeInPoints opts attr imgS
       hw = showFl $ ow / 2
       hh = showFl $ oh / 2
-      scale = showFl (imgWidth / ow) ++ " 0 0 " ++ showFl (imgHeight / oh)
-      src' = if isURI src then src else "file:" ++ src
+      scale = showFl (imgWidth / ow) <> " 0 0 " <> showFl (imgHeight / oh)
+      src' = if isURI src then src else "file:" <> src
       (stlStr, attrs) = styleToStrAttr style
       props  = inTags True "Properties" [] $ inTags True "PathGeometry" []
                  $ inTags True "GeometryPathType" [("PathOpen","false")]
                  $ inTags True "PathPointArray" []
                  $ vcat [
-                     selfClosingTag "PathPointType" [("Anchor", "-"++hw++" -"++hh),
-                       ("LeftDirection", "-"++hw++" -"++hh), ("RightDirection", "-"++hw++" -"++hh)]
-                   , selfClosingTag "PathPointType" [("Anchor", "-"++hw++" "++hh),
-                       ("LeftDirection", "-"++hw++" "++hh), ("RightDirection", "-"++hw++" "++hh)]
-                   , selfClosingTag "PathPointType" [("Anchor", hw++" "++hh),
-                       ("LeftDirection", hw++" "++hh), ("RightDirection", hw++" "++hh)]
-                   , selfClosingTag "PathPointType" [("Anchor", hw++" -"++hh),
-                       ("LeftDirection", hw++" -"++hh), ("RightDirection", hw++" -"++hh)]
-                   ]
-      image  = inTags True "Image"
-                   [("Self","ue6"), ("ItemTransform", scale++" -"++hw++" -"++hh)]
-                 $ vcat [
-                     inTags True "Properties" [] $ inTags True "Profile" [("type","string")] $ text "$ID/Embedded"
-                   , selfClosingTag "Link" [("Self", "ueb"), ("LinkResourceURI", src')]
+                     selfClosingTag "PathPointType" [("Anchor", "-"<>hw<>" -"<>hh),
+                       ("LeftDirection", "-"<>hw<>" -"<>hh), ("RightDirection", "-"<>hw<>" -"<>hh)]
+                   , selfClosingTag "PathPointType" [("Anchor", "-"<>hw<>" "<>hh),
+                       ("LeftDirection", "-"<>hw<>" "<>hh), ("RightDirection", "-"<>hw<>" "<>hh)]
+                   , selfClosingTag "PathPointType" [("Anchor", hw<>" "<>hh),
+                       ("LeftDirection", hw<>" "<>hh), ("RightDirection", hw<>" "<>hh)]
+                   , selfClosingTag "PathPointType" [("Anchor", hw<>" -"<>hh),
+                       ("LeftDirection", hw<>" -"<>hh), ("RightDirection", hw<>" -"<>hh)]
                    ]
-      doc    = inTags True "CharacterStyleRange" attrs
-                 $ inTags True "Rectangle" [("Self","uec"), ("StrokeWeight", "0"),
-                     ("ItemTransform", scale++" "++hw++" -"++hh)] (props $$ image)
-  state $ \st -> (doc, st{ inlineStyles = Set.insert stlStr $ inlineStyles st } )
+
+      isdata = "data:" `Text.isPrefixOf` src' && "base64," `Text.isInfixOf` src'
+      contents =
+            if isdata
+               then -- see #8398
+                  inTags True "Contents" [] $
+                    literal ("<![CDATA[" <> Text.replace "%20" ""
+                            (Text.drop 1 (Text.dropWhile (/=',') src')) <> "]]>")
+               else mempty
+      link = if isdata
+                then mempty
+                else  selfClosingTag "Link" [("Self", "ueb"),
+                                             ("LinkResourceURI", src')]
+      (_,_,kvs) = attr
+      applyObjectStyle = lookup objectStyleKey kvs
+      image = inTags True "Image"
+            [("Self","ue6"), ("ItemTransform", scale <> " -" <> hw <> " -" <> hh)]
+            $ vcat [
+                inTags True "Properties" [] $ vcat [
+                    inTags True "Profile" [("type","string")] $ text "$ID/Embedded",
+                    selfClosingTag "GraphicBounds" [("Left","0"), ("Top","0"),
+                    ("Right", showFl $ ow * ow / imgWidth),
+                    ("Bottom", showFl $ oh * oh / imgHeight)],
+                    contents
+                ],
+                link
+            ]
+      doc   = inTags True "CharacterStyleRange" attrs
+          $ inTags True "Rectangle"
+              ([("Self","uec"),
+                ("StrokeWeight", "0"),
+                ("ItemTransform", scale <> " " <> hw <> " -" <> hh)] ++
+                maybe [] (\aos -> [("AppliedObjectStyle", "ObjectStyle/" <> aos)]) applyObjectStyle
+              )
+              (props $$ image)
+  state $ \st -> (doc, st{
+      inlineStyles = Set.insert stlStr $ inlineStyles st,
+      objectStyles = case applyObjectStyle of
+          Just styleName -> Set.insert styleName $ objectStyles st
+          Nothing        -> objectStyles st
+    })
diff --git a/src/Text/Pandoc/Writers/Ipynb.hs b/src/Text/Pandoc/Writers/Ipynb.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Writers/Ipynb.hs
@@ -0,0 +1,279 @@
+{-# LANGUAGE OverloadedStrings #-}
+{-# LANGUAGE ScopedTypeVariables #-}
+{- |
+   Module      : Text.Pandoc.Writers.Ipynb
+   Copyright   : Copyright (C) 2019-2024 John MacFarlane
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : John MacFarlane <jgm@berkeley.edu>
+   Stability   : alpha
+   Portability : portable
+
+Ipynb (Jupyter notebook JSON format) writer for pandoc.
+
+-}
+module Text.Pandoc.Writers.Ipynb ( writeIpynb )
+where
+import Control.Monad (foldM)
+import Control.Monad.State ( StateT(runStateT), modify )
+import qualified Data.Map as M
+import Data.Maybe (catMaybes, fromMaybe)
+import Text.Pandoc.Options
+import Text.Pandoc.Definition
+import Data.Ipynb as Ipynb
+import Text.Pandoc.Walk (walkM)
+import qualified Text.Pandoc.Builder as B
+import Text.Pandoc.Class.PandocMonad
+import Text.Pandoc.Logging
+import Data.Text (Text)
+import qualified Data.Text as T
+import qualified Data.Text.Lazy as TL
+import Data.Aeson as Aeson
+import qualified Text.Pandoc.UTF8 as UTF8
+import Text.Pandoc.Shared (safeRead)
+import Text.Pandoc.URI (isURI)
+import Text.Pandoc.Writers.Shared (metaToContext')
+import Text.Pandoc.Writers.Markdown (writePlain, writeMarkdown)
+import qualified Data.Text.Encoding as TE
+import qualified Data.ByteString.Lazy as BL
+import Data.Aeson.Encode.Pretty (Config(..), defConfig,
+           encodePretty', keyOrder, Indent(Spaces))
+import Text.DocLayout (literal)
+import Text.Pandoc.UUID (getRandomUUID)
+import Data.Char (isAscii, isAlphaNum)
+
+writeIpynb :: PandocMonad m => WriterOptions -> Pandoc -> m Text
+writeIpynb opts d = do
+  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",
+                 "execution_count", "metadata",
+                 "outputs", "source",
+                 "data", "name", "text" ] <> compare }
+         $ notebook
+
+pandocToNotebook :: PandocMonad m
+                 => WriterOptions -> Pandoc -> m (Notebook NbV4)
+pandocToNotebook opts (Pandoc meta blocks) = do
+  -- we use writePlain w/ default options because e.g. we don't want
+  -- to add backslash escapes or convert en dashes, see #7928
+  let blockWriter bs = literal <$> writePlain def (Pandoc nullMeta bs)
+  let inlineWriter ils = literal . T.stripEnd <$>
+                            writePlain def (Pandoc nullMeta [Plain ils])
+  let jupyterMeta =
+        case lookupMeta "jupyter" meta of
+          Just (MetaMap m) -> Meta m
+          _ -> mempty
+  let nbformat =
+         case (lookupMeta "nbformat" jupyterMeta,
+               lookupMeta "nbformat_minor" jupyterMeta) of
+               (Just (MetaInlines [Str "4"]), Just (MetaInlines [Str y])) ->
+                 case safeRead y of
+                        Just z  -> (4, z)
+                        Nothing -> (4, 5)
+               _                -> (4, 5) -- write as v4.5
+  metadata' <- toJSON <$> metaToContext' blockWriter inlineWriter
+                 (B.deleteMeta "nbformat" .
+                  B.deleteMeta "nbformat_minor" $
+                  jupyterMeta)
+  -- convert from a Value (JSON object) to a M.Map Text Value:
+  let metadata = case fromJSON metadata' of
+                   Error _ -> mempty -- TODO warning here? shouldn't happen
+                   Success x -> x
+  cells <- extractCells nbformat opts blocks
+  return $ Notebook{
+       notebookMetadata = metadata
+     , notebookFormat = nbformat
+     , notebookCells = cells }
+
+addAttachment :: PandocMonad m
+              => Inline
+              -> StateT (M.Map Text MimeBundle) m Inline
+addAttachment (Image attr lab (src,tit))
+  | not (isURI src) = do
+  (img, mbmt) <- fetchItem src
+  let mt = fromMaybe "application/octet-stream" mbmt
+  modify $ M.insert src
+          (MimeBundle (M.insert mt (BinaryData img) mempty))
+  return $ Image attr lab ("attachment:" <> src, tit)
+addAttachment x = return x
+
+extractCells :: PandocMonad m
+             => (Int, Int) -> WriterOptions -> [Block] -> m [Ipynb.Cell a]
+extractCells _ _ [] = return []
+extractCells nbformat opts (Div (ident,classes,kvs) xs : bs)
+  | "cell" `elem` classes
+  , "markdown" `elem` classes = do
+      let meta = pairsToJSONMeta kvs
+      (newdoc, attachments) <-
+        runStateT (walkM addAttachment (Pandoc nullMeta xs)) mempty
+      source <- writeMarkdown opts{ writerTemplate = Nothing } newdoc
+      uuid <- uuidFrom nbformat ident
+      (Ipynb.Cell{
+          cellType = Markdown
+        , cellId = uuid
+        , cellSource = Source $ breakLines $ T.stripEnd source
+        , cellMetadata = meta
+        , cellAttachments = if M.null attachments
+                               then Nothing
+                               else Just $ MimeAttachments attachments } :)
+            <$> extractCells nbformat opts bs
+  | "cell" `elem` classes
+  , "code" `elem` classes = do
+      let (codeContent, rest) =
+            case xs of
+               (CodeBlock _ t : ys) -> (t, ys)
+               ys                   -> (mempty, ys)
+      let meta = pairsToJSONMeta kvs
+      outputs <- catMaybes <$> mapM blockToOutput rest
+      let exeCount = lookup "execution_count" kvs >>= safeRead
+      uuid <- uuidFrom nbformat ident
+      (Ipynb.Cell{
+          cellType = Ipynb.Code {
+                codeExecutionCount = exeCount
+              , codeOutputs = outputs
+              }
+        , cellId = uuid
+        , cellSource = Source $ breakLines codeContent
+        , cellMetadata = meta
+        , cellAttachments = Nothing } :) <$> extractCells nbformat opts bs
+  | "cell" `elem` classes
+  , "raw" `elem` classes =
+      case consolidateAdjacentRawBlocks xs of
+        [RawBlock (Format f) raw] -> do
+          let format' =
+                case T.toLower f of
+                  "html"     -> "text/html"
+                  "html4"    -> "text/html"
+                  "html5"    -> "text/html"
+                  "s5"       -> "text/html"
+                  "slidy"    -> "text/html"
+                  "slideous" -> "text/html"
+                  "dzslides" -> "text/html"
+                  "revealjs" -> "text/html"
+                  "latex"    -> "text/latex"
+                  "markdown" -> "text/markdown"
+                  "rst"      -> "text/restructuredtext"
+                  "asciidoc" -> "text/asciidoc"
+                  _          -> f
+          uuid <- uuidFrom nbformat ident
+          (Ipynb.Cell{
+              cellType = Raw
+            , cellId = uuid
+            , cellSource = Source $ breakLines raw
+            , cellMetadata = if format' == "ipynb" -- means no format given
+                                then mempty
+                                else JSONMeta $ M.insert "raw_mimetype"
+                                       (Aeson.String format') mempty
+            , cellAttachments = Nothing } :) <$> extractCells nbformat opts bs
+        _ -> extractCells nbformat opts bs
+extractCells nbformat opts (CodeBlock (ident,classes,kvs) raw : bs)
+  | "code" `elem` classes = do
+      let meta = pairsToJSONMeta kvs
+      let exeCount = lookup "execution_count" kvs >>= safeRead
+      uuid <- uuidFrom nbformat ident
+      (Ipynb.Cell{
+          cellType = Ipynb.Code {
+                codeExecutionCount = exeCount
+              , codeOutputs = []
+              }
+        , cellId = uuid
+        , cellSource = Source $ breakLines raw
+        , cellMetadata = meta
+        , cellAttachments = Nothing } :) <$> extractCells nbformat opts bs
+extractCells nbformat opts (b:bs) = do
+      let isCodeOrDiv (CodeBlock (_,cl,_) _) = "code" `elem` cl
+          isCodeOrDiv (Div (_,cl,_) _)       = "cell" `elem` cl
+          isCodeOrDiv _                      = False
+      let (mds, rest) = break isCodeOrDiv bs
+      extractCells nbformat opts
+        (Div ("",["cell","markdown"],[]) (b:mds) : rest)
+
+-- Return Nothing if nbformat < 4.5.
+-- Otherwise construct a UUID, using the existing identifier
+-- if it is a valid UUID, otherwise constructing a new one.
+uuidFrom :: PandocMonad m => (Int, Int) -> Text -> m (Maybe Text)
+uuidFrom nbformat ident =
+  if nbformat >= (4,5)
+     then
+       if isValidUUID ident
+          then return $ Just ident
+          else Just . T.pack . drop 9 . show <$> getRandomUUID
+     else return Nothing
+ where
+  isValidUUID t = not (T.null t) && T.length t <= 64 &&
+                  T.all isValidUUIDChar t
+  isValidUUIDChar c = isAscii c && (isAlphaNum c || c == '-' || c == '_')
+
+blockToOutput :: PandocMonad m => Block -> m (Maybe (Output a))
+blockToOutput (Div (_,["output","stream",sname],_) (CodeBlock _ t:_)) =
+  return $ Just
+         $ Stream{ streamName = sname
+               , streamText = Source (breakLines t) }
+blockToOutput (Div (_,["output","error"],kvs) (CodeBlock _ t:_)) =
+  return $ Just
+         $ Err{ errName = fromMaybe mempty (lookup "ename" kvs)
+              , errValue = fromMaybe mempty (lookup "evalue" kvs)
+              , errTraceback = breakLines t }
+blockToOutput (Div (_,["output","execute_result"],kvs) bs) = do
+  (data', metadata') <- extractData bs
+  return $ Just
+         $ ExecuteResult{ executeCount = fromMaybe 0 $
+                          lookup "execution_count" kvs >>= safeRead
+                        , executeData = data'
+                        , executeMetadata = pairsToJSONMeta kvs <> metadata'}
+blockToOutput (Div (_,["output","display_data"],kvs) bs) = do
+  (data', metadata') <- extractData bs
+  return $ Just
+         $ DisplayData { displayData = data'
+                       , displayMetadata = pairsToJSONMeta kvs <> metadata'}
+blockToOutput _ = return Nothing
+
+extractData :: PandocMonad m => [Block] -> m (MimeBundle, JSONMeta)
+extractData bs = do
+  (mmap, meta) <- foldM go mempty $ consolidateAdjacentRawBlocks bs
+  return (MimeBundle mmap, meta)
+  where
+    go (mmap, meta) b@(Para [Image (_,_,kvs) _ (src,_)]) = do
+      (img, mbmt) <- fetchItem src
+      case mbmt of
+        Just mt -> return
+          (M.insert mt (BinaryData img) mmap,
+           meta <> pairsToJSONMeta kvs)
+        Nothing -> (mmap, meta) <$ report (BlockNotRendered b)
+    go (mmap, meta) b@(CodeBlock (_,["json"],_) code) =
+      case decode (UTF8.fromTextLazy $ TL.fromStrict code) of
+        Just v  -> return
+                    (M.insert "application/json" (JsonData v) mmap, meta)
+        Nothing -> (mmap, meta) <$ report (BlockNotRendered b)
+    go (mmap, meta) (CodeBlock ("",[],[]) code) =
+       return (M.insert "text/plain" (TextualData code) mmap, meta)
+    go (mmap, meta) (RawBlock (Format "html") raw) =
+       return (M.insert "text/html" (TextualData raw) mmap, meta)
+    go (mmap, meta) (RawBlock (Format "latex") raw) =
+       return (M.insert "text/latex" (TextualData raw) mmap, meta)
+    go (mmap, meta) (RawBlock (Format "markdown") raw) =
+       return (M.insert "text/markdown" (TextualData raw) mmap, meta)
+    go (mmap, meta) (Div _ bs') = foldM go (mmap, meta) bs'
+    go (mmap, meta) b = (mmap, meta) <$ report (BlockNotRendered b)
+
+pairsToJSONMeta :: [(Text, Text)] -> JSONMeta
+pairsToJSONMeta kvs = JSONMeta $
+  M.fromList [(k, case Aeson.decode (UTF8.fromTextLazy $ TL.fromStrict v) of
+                           Just val -> val
+                           Nothing  -> String v)
+             | (k,v) <- kvs
+             , k /= "execution_count"
+             ]
+
+consolidateAdjacentRawBlocks :: [Block] -> [Block]
+consolidateAdjacentRawBlocks [] = []
+consolidateAdjacentRawBlocks (RawBlock f1 x : RawBlock f2 y : xs)
+  | f1 == f2
+  = consolidateAdjacentRawBlocks (RawBlock f1 (x <> "\n" <> y) : xs)
+consolidateAdjacentRawBlocks (x : xs) =
+  x : consolidateAdjacentRawBlocks xs
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,25 +1,10 @@
-{-# LANGUAGE OverloadedStrings #-}
-
-{-
-Copyright (C) 2006-2017 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 LambdaCase          #-}
+{-# LANGUAGE OverloadedStrings   #-}
+{-# LANGUAGE ScopedTypeVariables #-}
+{-# LANGUAGE ViewPatterns        #-}
 {- |
    Module      : Text.Pandoc.Writers.JATS
-   Copyright   : Copyright (C) 2017 John MacFarlane
+   Copyright   : 2017-2024 John MacFarlane
    License     : GNU GPL, version 2 or above
 
    Maintainer  : John MacFarlane <jgm@berkeley.edu>
@@ -28,98 +13,233 @@
 
 Conversion of 'Pandoc' documents to JATS XML.
 Reference:
-https://jats.nlm.nih.gov/publishing/tag-library/1.1d3/element/mml-math.html
+https://jats.nlm.nih.gov/publishing/tag-library
 -}
-module Text.Pandoc.Writers.JATS ( writeJATS ) where
+module Text.Pandoc.Writers.JATS
+  ( writeJATS
+  , writeJatsArchiving
+  , writeJatsPublishing
+  , writeJatsArticleAuthoring
+  ) where
+import Control.Applicative ((<|>))
+import Control.Monad
 import Control.Monad.Reader
-import Data.Char (toLower)
+import Control.Monad.State
 import Data.Generics (everywhere, mkT)
-import Data.List (isSuffixOf, partition)
-import Data.Maybe (fromMaybe)
+import qualified Data.Map as M
+import Data.Maybe (fromMaybe, listToMaybe, isNothing)
+import Data.Time (toGregorian, Day, parseTimeM, defaultTimeLocale, formatTime)
+import qualified Data.Text as T
 import Data.Text (Text)
-import Text.Pandoc.Class (PandocMonad, report)
+import Text.Pandoc.Citeproc (getReferences)
+import Text.Pandoc.Class.PandocMonad (PandocMonad, report)
 import Text.Pandoc.Definition
 import Text.Pandoc.Highlighting (languages, languagesByExtension)
 import Text.Pandoc.Logging
 import Text.Pandoc.MIME (getMimeType)
+import Text.Pandoc.Walk (walk)
 import Text.Pandoc.Options
-import Text.Pandoc.Pretty
+import Text.DocLayout
 import Text.Pandoc.Shared
-import Text.Pandoc.Templates (renderTemplate')
+import Text.Pandoc.URI
+import Text.Pandoc.Templates (renderTemplate)
+import Text.DocTemplates (Context(..), Val(..), toVal)
+import Text.Pandoc.Writers.JATS.References (referencesToJATS)
+import Text.Pandoc.Writers.JATS.Table (tableToJATS)
+import Text.Pandoc.Writers.JATS.Types
 import Text.Pandoc.Writers.Math
 import Text.Pandoc.Writers.Shared
 import Text.Pandoc.XML
 import Text.TeXMath
+import qualified Text.Pandoc.Writers.AnnotatedTable as Ann
 import qualified Text.XML.Light as Xml
 
-data JATSVersion = JATS1_1
-     deriving (Eq, Show)
+-- | Default human-readable names for roles in the Contributor Role
+-- Taxonomy (CRediT). This is useful for generating JATS that annotate
+-- contributor roles
+creditNames :: M.Map Text Text
+creditNames = M.fromList [
+    ("conceptualization", "Conceptualization"),
+    ("data-curation", "Data curation"),
+    ("formal-analysis", "Formal analysis"),
+    ("funding-acquisition", "Funding acquisition"),
+    ("investigation", "Investigation"),
+    ("methodology", "Methodology"),
+    ("project-administration", "Project administration"),
+    ("resources", "Resources"),
+    ("software", "Software"),
+    ("supervision", "Supervision"),
+    ("validation", "Validation"),
+    ("visualization", "Visualization"),
+    ("writing-original-draft", "Writing – original draft"),
+    ("writing-review-editing", "Writing – review &amp; editing")]
 
-type JATS = ReaderT JATSVersion
+-- | Ensure every role with a `credit` key also has a `credit-name`,
+-- using a default value if necessary
+addCreditNames :: Context Text -> Context Text
+addCreditNames context =
+  case getField "author" context of
+    -- If there is an "authors" key, then we replace the existing value
+    -- with one we mutate by running the addCreditNamesToAuthor helper
+    -- function on each
+    Just (ListVal authors) ->
+      resetField "author" (map addCreditNamesToAuthor authors) context
+    -- If there is no "authors" key in the context, then we don't have to do
+    -- anything, and just return the context as is
+    _ -> context
+  where
+    addCreditNamesToAuthor :: Val Text -> Val Text
+    addCreditNamesToAuthor val = fromMaybe val $ do
+      MapVal authorCtx <- pure val
+      ListVal roles <- getField "roles" authorCtx
+      return $ toVal $ resetField "roles" (map addCreditNameToRole roles) authorCtx
 
+    addCreditNameToRole :: Val Text -> Val Text
+    addCreditNameToRole val = fromMaybe val $ do
+      MapVal roleCtx <- pure val
+      guard $ isNothing (getField "credit-name" roleCtx :: Maybe (Val Text))
+      creditId <- getField "credit" roleCtx
+      creditName <- M.lookup creditId creditNames
+      return $ toVal $ resetField "credit-name" creditName roleCtx
+
+-- | Convert a @'Pandoc'@ document to JATS (Archiving and Interchange
+-- Tag Set.)
+writeJatsArchiving :: PandocMonad m => WriterOptions -> Pandoc -> m Text
+writeJatsArchiving = writeJats TagSetArchiving
+
+-- | Convert a @'Pandoc'@ document to JATS (Journal Publishing Tag Set.)
+writeJatsPublishing :: PandocMonad m => WriterOptions -> Pandoc -> m Text
+writeJatsPublishing = writeJats TagSetPublishing
+
+-- | Convert a @'Pandoc'@ document to JATS (Archiving and Interchange
+-- Tag Set.)
+writeJatsArticleAuthoring :: PandocMonad m => WriterOptions -> Pandoc -> m Text
+writeJatsArticleAuthoring = writeJats TagSetArticleAuthoring
+
+-- | Alias for @'writeJatsArchiving'@. This function exists for backwards
+-- compatibility, but will be deprecated in the future. Use
+-- @'writeJatsArchiving'@ instead.
+{-# DEPRECATED writeJATS "Use writeJatsArchiving instead" #-}
 writeJATS :: PandocMonad m => WriterOptions -> Pandoc -> m Text
-writeJATS opts d =
-  runReaderT (docToJATS opts d) JATS1_1
+writeJATS = writeJatsArchiving
 
+-- | Convert a @'Pandoc'@ document to JATS.
+writeJats :: PandocMonad m => JATSTagSet -> WriterOptions -> Pandoc -> m Text
+writeJats tagSet opts d = do
+  refs <- if extensionEnabled Ext_element_citations $ writerExtensions opts
+          then getReferences Nothing d
+          else pure []
+  let environment = JATSEnv
+          { jatsTagSet = tagSet
+          , jatsInlinesWriter = inlinesToJATS
+          , jatsBlockWriter = wrappedBlocksToJATS
+          , jatsReferences = refs
+          }
+  let initialState = JATSState { jatsNotes = [] }
+  runReaderT (evalStateT (docToJATS opts d) initialState)
+             environment
+
+-- see #9017 for motivation
+ensureReferenceHeader :: [Block] -> [Block]
+ensureReferenceHeader [] = []
+ensureReferenceHeader (h@(Header{}):refs@(Div ("refs",_,_) _) : xs) =
+  h:refs:xs
+ensureReferenceHeader (refs@(Div ("refs",_,_) _) : xs) =
+  Header 1 nullAttr mempty : refs : xs
+ensureReferenceHeader (x:xs) = x :ensureReferenceHeader xs
+
 -- | Convert Pandoc document to string in JATS format.
 docToJATS :: PandocMonad m => WriterOptions -> Pandoc -> JATS m Text
-docToJATS opts (Pandoc meta blocks) = do
-  let isBackBlock (Div ("refs",_,_) _) = True
-      isBackBlock _                    = False
-  let (backblocks, bodyblocks) = partition isBackBlock blocks
-  let elements = hierarchicalize bodyblocks
-  let backElements = hierarchicalize backblocks
-  let colwidth = if writerWrapText opts == WrapAuto
-                    then Just $ writerColumns opts
-                    else Nothing
-  let render'  :: Doc -> Text
-      render'  = render colwidth
-  let opts'    = if maybe False (("/book>" `isSuffixOf`) . trimr)
-                            (writerTemplate opts) &&
-                     TopLevelDefault == writerTopLevelDivision opts
-                    then opts{ writerTopLevelDivision = TopLevelChapter }
-                    else opts
+docToJATS opts (Pandoc meta blocks') = do
   -- The numbering here follows LaTeX's internal numbering
-  let startLvl = case writerTopLevelDivision opts' of
+  let startLvl = case writerTopLevelDivision opts of
                    TopLevelPart    -> -1
                    TopLevelChapter -> 0
                    TopLevelSection -> 1
                    TopLevelDefault -> 1
-  metadata <- metaToJSON opts
-                 (fmap (render' . vcat) .
-                          mapM (elementToJATS opts' startLvl) .
-                            hierarchicalize)
-                 (fmap render' . inlinesToJATS opts')
+  let blocks = makeSections (writerNumberSections opts) (Just startLvl)
+                  $ ensureReferenceHeader blocks'
+  let splitBackBlocks b@(Div ("refs",_,_) _) (fs, bs) = (fs, b:bs)
+      splitBackBlocks (Div (ident,("section":_),_)
+                               ( Header lev (_,hcls,hkvs) hils
+                               : (Div rattrs@("refs",_,_) rs)
+                               : rest
+                               )) (fs, bs)
+                       = (fs ++ rest,
+                            Div rattrs
+                             (Header lev (ident,hcls,hkvs) hils : rs) : bs)
+      splitBackBlocks b (fs, bs) = (b:fs, bs)
+  let (bodyblocks, backblocks) = foldr splitBackBlocks ([],[]) blocks
+  let colwidth = if writerWrapText opts == WrapAuto
+                    then Just $ writerColumns opts
+                    else Nothing
+  metadata <- metaToContext opts
+                 (blocksToJATS opts . makeSections False (Just startLvl))
+                 (fmap chomp . inlinesToJATS opts)
                  meta
-  main <- (render' . vcat) <$>
-            mapM (elementToJATS opts' startLvl) elements
-  back <- (render' . vcat) <$>
-            mapM (elementToJATS opts' startLvl) backElements
+  main <- blocksToJATS opts bodyblocks
+  notes <- gets (reverse . map snd . jatsNotes)
+  backs <- blocksToJATS opts backblocks
+  tagSet <- asks jatsTagSet
+  -- In the "Article Authoring" tag set, occurrence of fn-group elements
+  -- is restricted to table footers. Footnotes have to be placed inline.
+  let fns = if null notes || tagSet == TagSetArticleAuthoring
+            then mempty
+            else inTagsIndented "fn-group" $ vcat notes
+  let back = backs $$ fns
+  let date =
+        case getField "date" metadata of
+          Nothing -> NullVal
+          Just (SimpleVal (x :: Doc Text)) ->
+             case parseDate (render Nothing x) of
+               Nothing  -> NullVal
+               Just day ->
+                 let (y,m,d) = toGregorian day
+                 in  MapVal . Context $ M.fromList
+                      [("year" :: Text, SimpleVal $ text $ show y)
+                      ,("month", SimpleVal $ text $ show m)
+                      ,("day", SimpleVal $ text $ show d)
+                      ,("iso-8601", SimpleVal $ text $
+                            formatTime defaultTimeLocale "%F" day)
+                      ]
+          Just x -> x
+  title' <- inlinesToJATS opts $ map fixLineBreak
+               (lookupMetaInlines "title" meta)
   let context = defField "body" main
               $ defField "back" back
+              $ addCreditNames
+              $ resetField "title" title'
+              $ resetField "date" date
               $ defField "mathml" (case writerHTMLMathMethod opts of
                                         MathML -> True
                                         _      -> False) metadata
-  case writerTemplate opts of
-       Nothing  -> return main
-       Just tpl -> renderTemplate' tpl context
-
--- | Convert an Element to JATS.
-elementToJATS :: PandocMonad m => WriterOptions -> Int -> Element -> JATS m Doc
-elementToJATS opts _   (Blk block) = blockToJATS opts block
-elementToJATS opts lvl (Sec _ _num (id',_,kvs) title elements) = do
-  let idAttr = [("id", writerIdentifierPrefix opts ++ id') | not (null id')]
-  let otherAttrs = ["sec-type", "specific-use"]
-  let attribs = idAttr ++ [(k,v) | (k,v) <- kvs, k `elem` otherAttrs]
-  contents <- mapM (elementToJATS opts (lvl + 1)) elements
-  title' <- inlinesToJATS opts title
-  return $ inTags True "sec" attribs $
-      inTagsSimple "title" title' $$ vcat contents
+  return $ render colwidth $
+    (if writerPreferAscii opts then fmap toEntities else id) $
+    case writerTemplate opts of
+       Nothing  -> main
+       Just tpl -> renderTemplate tpl context
 
 -- | Convert a list of Pandoc blocks to JATS.
-blocksToJATS :: PandocMonad m => WriterOptions -> [Block] -> JATS m Doc
-blocksToJATS opts = fmap vcat . mapM (blockToJATS opts)
+blocksToJATS :: PandocMonad m => WriterOptions -> [Block] -> JATS m (Doc Text)
+blocksToJATS = wrappedBlocksToJATS (const False)
 
+-- | Like @'blocksToJATS'@, but wraps top-level blocks into a @<p>@
+-- element if the @needsWrap@ predicate evaluates to @True@.
+wrappedBlocksToJATS :: PandocMonad m
+                    => (Block -> Bool)
+                    -> WriterOptions
+                    -> [Block]
+                    -> JATS m (Doc Text)
+wrappedBlocksToJATS needsWrap opts =
+  fmap vcat . mapM wrappedBlockToJATS
+  where
+    wrappedBlockToJATS b = do
+      inner <- blockToJATS opts b
+      return $
+        if needsWrap b
+           then inTags True "p" [("specific-use","wrapper")] inner
+           else inner
+
 -- | Auxiliary function to convert Plain block to Para.
 plainToPara :: Block -> Block
 plainToPara (Plain x) = Para x
@@ -128,23 +248,28 @@
 -- | Convert a list of pairs of terms and definitions into a list of
 -- JATS varlistentrys.
 deflistItemsToJATS :: PandocMonad m
-                      => WriterOptions -> [([Inline],[[Block]])] -> JATS m Doc
+                   => WriterOptions
+                   -> [([Inline],[[Block]])] -> JATS m (Doc Text)
 deflistItemsToJATS opts items =
   vcat <$> mapM (uncurry (deflistItemToJATS opts)) items
 
 -- | Convert a term and a list of blocks into a JATS varlistentry.
 deflistItemToJATS :: PandocMonad m
-                     => WriterOptions -> [Inline] -> [[Block]] -> JATS m Doc
+                  => WriterOptions
+                  -> [Inline] -> [[Block]] -> JATS m (Doc Text)
 deflistItemToJATS opts term defs = do
   term' <- inlinesToJATS opts term
-  def' <- blocksToJATS opts $ concatMap (map plainToPara) defs
+  def' <- wrappedBlocksToJATS (not . isPara)
+              opts $ concatMap (walk demoteHeaderAndRefs .
+                                map plainToPara) defs
   return $ inTagsIndented "def-item" $
-      inTagsIndented "term" term' $$
+      inTagsSimple "term" term' $$
       inTagsIndented "def" def'
 
 -- | Convert a list of lists of blocks to a list of JATS list items.
 listItemsToJATS :: PandocMonad m
-                => WriterOptions -> Maybe [String] -> [[Block]] -> JATS m Doc
+                => WriterOptions
+                -> Maybe [Text] -> [[Block]] -> JATS m (Doc Text)
 listItemsToJATS opts markers items =
   case markers of
        Nothing -> vcat <$> mapM (listItemToJATS opts Nothing) items
@@ -152,127 +277,151 @@
 
 -- | Convert a list of blocks into a JATS list item.
 listItemToJATS :: PandocMonad m
-               => WriterOptions -> Maybe String -> [Block] -> JATS m Doc
+               => WriterOptions
+               -> Maybe Text -> [Block] -> JATS m (Doc Text)
 listItemToJATS opts mbmarker item = do
-  contents <- blocksToJATS opts item
+  contents <- wrappedBlocksToJATS (not . isParaOrList) opts
+                 (walk demoteHeaderAndRefs item)
   return $ inTagsIndented "list-item" $
-           maybe empty (\lbl -> inTagsIndented "label" (text lbl)) mbmarker
+           maybe empty (inTagsSimple "label" . text . T.unpack) mbmarker
            $$ contents
 
-imageMimeType :: String -> [(String, String)] -> (String, String)
-imageMimeType src kvs =
-  let mbMT = getMimeType src
-      maintype = fromMaybe "image" $
-                  lookup "mimetype" kvs `mplus`
-                  (takeWhile (/='/') <$> mbMT)
-      subtype = fromMaybe "" $
-                  lookup "mime-subtype" kvs `mplus`
-                  ((drop 1 . dropWhile (/='/')) <$> mbMT)
-  in (maintype, subtype)
-
-languageFor :: [String] -> String
-languageFor classes =
+languageFor :: WriterOptions -> [Text] -> Text
+languageFor opts classes =
   case langs of
      (l:_) -> escapeStringForXML l
      []    -> ""
-    where isLang l    = map toLower l `elem` map (map toLower) languages
+    where
+          syntaxMap = writerSyntaxMap opts
+          isLang l    = T.toLower l `elem` map T.toLower (languages syntaxMap)
           langsFrom s = if isLang s
                            then [s]
-                           else languagesByExtension . map toLower $ s
+                           else (languagesByExtension syntaxMap) . T.toLower $ s
           langs       = concatMap langsFrom classes
 
-codeAttr :: Attr -> (String, [(String, String)])
-codeAttr (ident,classes,kvs) = (lang, attr)
+codeAttr :: WriterOptions -> Attr -> (Text, [(Text, Text)])
+codeAttr opts (ident,classes,kvs) = (lang, attr)
     where
-       attr = [("id",ident) | not (null ident)] ++
-              [("language",lang) | not (null lang)] ++
+       attr = [("id", escapeNCName ident) | not (T.null ident)] ++
+              [("language",lang) | not (T.null lang)] ++
               [(k,v) | (k,v) <- kvs, k `elem` ["code-type",
                 "code-version", "executable",
                 "language-version", "orientation",
                     "platforms", "position", "specific-use"]]
-       lang  = languageFor classes
+       lang  = languageFor opts classes
 
+-- <break/> is only allowed as a direct child of <td> or <title> or
+-- <article-title>
+fixLineBreak :: Inline -> Inline
+fixLineBreak LineBreak = RawInline (Format "jats") "<break/>"
+fixLineBreak x = x
+
 -- | Convert a Pandoc block element to JATS.
-blockToJATS :: PandocMonad m => WriterOptions -> Block -> JATS m Doc
-blockToJATS _ Null = return empty
+blockToJATS :: PandocMonad m => WriterOptions -> Block -> JATS m (Doc Text)
+blockToJATS opts (Div (id',"section":_,kvs) (Header _lvl (_,_,hkvs) ils : xs)) = do
+  let idAttr = [ ("id", writerIdentifierPrefix opts <> escapeNCName id')
+               | not (T.null id')]
+  let otherAttrs = ["sec-type", "specific-use"]
+  let attribs = idAttr ++ [(k,v) | (k,v) <- kvs, k `elem` otherAttrs]
+  title' <- inlinesToJATS opts (map fixLineBreak ils)
+  let label = if writerNumberSections opts
+                 then
+                   case lookup "number" hkvs of
+                     Just num -> inTagsSimple "label" (literal num)
+                     Nothing -> mempty
+                 else mempty
+  contents <- blocksToJATS opts xs
+  return $ inTags True "sec" attribs $
+      label $$
+      inTagsSimple "title" title' $$ contents
 -- Bibliography reference:
-blockToJATS opts (Div ('r':'e':'f':'-':_,_,_) [Para lst]) =
+blockToJATS opts (Div (ident,_,_) [Para lst]) | "ref-" `T.isPrefixOf` ident =
+  inTags True "ref" [("id", escapeNCName ident)] .
+  inTagsSimple "mixed-citation" <$>
   inlinesToJATS opts lst
 blockToJATS opts (Div ("refs",_,_) xs) = do
-  contents <- blocksToJATS opts xs
+  refs <- asks jatsReferences
+  contents <- if null refs
+              then blocksToJATS opts xs
+              else do
+                titleElement <- case xs of
+                  (Header _ _ title:_) ->
+                    inTagsSimple "title" <$> inlinesToJATS opts title
+                  _ -> return mempty
+                elementRefs <- referencesToJATS opts refs
+                return $ titleElement $$ elementRefs
   return $ inTagsIndented "ref-list" contents
 blockToJATS opts (Div (ident,[cls],kvs) bs) | cls `elem` ["fig", "caption", "table-wrap"] = do
   contents <- blocksToJATS opts bs
-  let attr = [("id", ident) | not (null ident)] ++
+  let attr = [("id", escapeNCName ident) | not (T.null ident)] ++
              [("xml:lang",l) | ("lang",l) <- kvs] ++
              [(k,v) | (k,v) <- kvs, k `elem` ["specific-use",
                  "content-type", "orientation", "position"]]
   return $ inTags True cls attr contents
 blockToJATS opts (Div (ident,_,kvs) bs) = do
   contents <- blocksToJATS opts bs
-  let attr = [("id", ident) | not (null ident)] ++
-             [("xml:lang",l) | ("lang",l) <- kvs] ++
-             [(k,v) | (k,v) <- kvs, k `elem` ["specific-use",
-                 "content-type", "orientation", "position"]]
-  return $ inTags True "boxed-text" attr contents
+  -- Attributes that are allowed on both @<p>@ and @<boxed-text>@ elements
+  let generic_attr = [("id", escapeNCName ident) | not (T.null ident)] ++
+                     [("xml:lang",l) | ("lang",l) <- kvs] ++
+                     [(k,v) | (k,v) <- kvs, k `elem` ["specific-use",
+                                                      "content-type"]]
+  let boxed_attr = [(k,v) | (k,v) <- kvs, k `elem` ["orientation", "position"]]
+  let attr = generic_attr <> boxed_attr
+  return $
+    if null attr
+    then contents
+    else -- The contents must be wrapped in an appropriate element.
+      let element = if null boxed_attr
+                    then "p"
+                    else "boxed-text"
+      in inTags True element (generic_attr <> boxed_attr) contents
 blockToJATS opts (Header _ _ title) = do
-  title' <- inlinesToJATS opts title
+  title' <- inlinesToJATS opts (map fixLineBreak title)
   return $ inTagsSimple "title" title'
+-- Special cases for bare images, which are rendered as graphics
+blockToJATS _opts (Plain [Image attr alt tgt]) =
+  return $ graphic attr alt tgt
+blockToJATS _opts (Para [Image attr alt tgt]) =
+  return $ graphic attr alt tgt
 -- No Plain, everything needs to be in a block-level tag
 blockToJATS opts (Plain lst) = blockToJATS opts (Para lst)
--- title beginning with fig: indicates that the image is a figure
-blockToJATS opts (Para [Image (ident,_,kvs) txt
-  (src,'f':'i':'g':':':tit)]) = do
-  alt <- inlinesToJATS opts txt
-  let (maintype, subtype) = imageMimeType src kvs
-  let capt = if null txt
-                then empty
-                else inTagsSimple "caption" alt
-  let attr = [("id", ident) | not (null ident)] ++
-             [(k,v) | (k,v) <- kvs, k `elem` ["fig-type", "orientation",
-                                              "position", "specific-use"]]
-  let graphicattr = [("mimetype",maintype),
-                     ("mime-subtype",subtype),
-                     ("xlink:href",src),  -- do we need to URL escape this?
-                     ("xlink:title",tit)]
-  return $ inTags True "fig" attr $
-              capt $$ selfClosingTag "graphic" graphicattr
-blockToJATS _ (Para [Image (ident,_,kvs) _ (src, tit)]) = do
-  let (maintype, subtype) = imageMimeType src kvs
-  let attr = [("id", ident) | not (null ident)] ++
-             [("mimetype", maintype),
-              ("mime-subtype", subtype),
-              ("xlink:href", src)] ++
-             [("xlink:title", tit) | not (null tit)] ++
-             [(k,v) | (k,v) <- kvs, k `elem` ["baseline-shift",
-                        "content-type", "specific-use", "xlink:actuate",
-                        "xlink:href", "xlink:role", "xlink:show",
-                        "xlink:type"]]
-  return $ selfClosingTag "graphic" attr
 blockToJATS opts (Para lst) =
-  inTagsIndented "p" <$> inlinesToJATS opts lst
+  inTagsSimple "p" <$> inlinesToJATS opts lst
 blockToJATS opts (LineBlock lns) =
   blockToJATS opts $ linesToPara lns
-blockToJATS opts (BlockQuote blocks) =
-  inTagsIndented "disp-quote" <$> blocksToJATS opts blocks
-blockToJATS _ (CodeBlock a str) = return $
-  inTags False tag attr (flush (text (escapeStringForXML str)))
-    where (lang, attr) = codeAttr a
-          tag          = if null lang then "preformat" else "code"
+blockToJATS opts (BlockQuote blocks) = do
+  tagSet <- asks jatsTagSet
+  let needsWrap = if tagSet == TagSetArticleAuthoring
+                  then not . isPara
+                  else \case
+                    Header{}       -> True
+                    HorizontalRule -> True
+                    _              -> False
+  inTagsIndented "disp-quote" <$> wrappedBlocksToJATS needsWrap opts blocks
+blockToJATS opts (CodeBlock a str) = return $
+  inTags False tag attr (flush (text (T.unpack $ escapeStringForXML str)))
+    where (lang, attr) = codeAttr opts a
+          tag          = if T.null lang then "preformat" else "code"
 blockToJATS _ (BulletList []) = return empty
 blockToJATS opts (BulletList lst) =
   inTags True "list" [("list-type", "bullet")] <$>
   listItemsToJATS opts Nothing lst
 blockToJATS _ (OrderedList _ []) = return empty
 blockToJATS opts (OrderedList (start, numstyle, delimstyle) items) = do
-  let listType = case numstyle of
-                       DefaultStyle -> "order"
-                       Decimal      -> "order"
-                       Example      -> "order"
-                       UpperAlpha   -> "alpha-upper"
-                       LowerAlpha   -> "alpha-lower"
-                       UpperRoman   -> "roman-upper"
-                       LowerRoman   -> "roman-lower"
+  tagSet <- asks jatsTagSet
+  let listType =
+        -- The Article Authoring tag set doesn't allow a more specific
+        -- @list-type@ attribute than "order".
+        if tagSet == TagSetArticleAuthoring
+        then "order"
+        else case numstyle of
+               DefaultStyle -> "order"
+               Decimal      -> "order"
+               Example      -> "order"
+               UpperAlpha   -> "alpha-upper"
+               LowerAlpha   -> "alpha-lower"
+               UpperRoman   -> "roman-upper"
+               LowerRoman   -> "roman-lower"
   let simpleList = start == 1 && (delimstyle == DefaultDelim ||
                                   delimstyle == Period)
   let markers = if simpleList
@@ -284,65 +433,78 @@
 blockToJATS opts (DefinitionList lst) =
   inTags True "def-list" [] <$> deflistItemsToJATS opts lst
 blockToJATS _ b@(RawBlock f str)
-  | f == "jats"    = return $ text str -- raw XML block
+  | f == "jats"    = return $ text $ T.unpack str -- raw XML block
   | otherwise      = do
       report $ BlockNotRendered b
       return empty
 blockToJATS _ HorizontalRule = return empty -- not semantic
-blockToJATS opts (Table [] aligns widths headers rows) = do
-  let percent w    = show (truncate (100*w) :: Integer) ++ "*"
-  let coltags = vcat $ zipWith (\w al -> selfClosingTag "col"
-                       ([("width", percent w) | w > 0] ++
-                        [("align", alignmentToString al)])) widths aligns
-  thead <- if all null headers
-              then return empty
-              else inTagsIndented "thead" <$> tableRowToJATS opts True headers
-  tbody <- (inTagsIndented "tbody" . vcat) <$>
-                mapM (tableRowToJATS opts False) rows
-  return $ inTags True "table" [] $ coltags $$ thead $$ tbody
-blockToJATS opts (Table caption aligns widths headers rows) = do
-  captionDoc <- inTagsIndented "caption" <$> blockToJATS opts (Para caption)
-  tbl <- blockToJATS opts (Table [] aligns widths headers rows)
-  return $ inTags True "table-wrap" [] $ captionDoc $$ tbl
-
-alignmentToString :: Alignment -> [Char]
-alignmentToString alignment = case alignment of
-                                 AlignLeft    -> "left"
-                                 AlignRight   -> "right"
-                                 AlignCenter  -> "center"
-                                 AlignDefault -> "left"
+blockToJATS opts (Table attr caption colspecs thead tbody tfoot) =
+  tableToJATS opts (Ann.toTable attr caption colspecs thead tbody tfoot)
+blockToJATS opts (Figure (ident, _, kvs) (Caption _short longcapt) body) = do
+  -- Remove the alt text from images if it's the same as the caption text.
+  let unsetAltIfDupl = \case
+        Image attr alt tgt
+          | stringify alt == stringify longcapt -> Image attr [] tgt
+        inline -> inline
+  capt <- if null longcapt
+          then pure empty
+          else inTagsSimple "caption" <$> blocksToJATS opts longcapt
 
-tableRowToJATS :: PandocMonad m
-                  => WriterOptions
-                  -> Bool
-                  -> [[Block]]
-                  -> JATS m Doc
-tableRowToJATS opts isHeader cols =
-  (inTagsIndented "tr" . vcat) <$> mapM (tableItemToJATS opts isHeader) cols
+  -- We handle the element specially if it's a figure with subfigures, i.e., if
+  -- all immediate children are figures themselves.
+  let hasSubfigures = all (\case { Figure{} -> True; _ -> False}) body
+      needsWrapping = if hasSubfigures
+                      then (const False)
+                      else \case
+                        -- Wrap all figure content elements, except for those
+                        -- allowed as direct subelements.
+                        BlockQuote{}    -> False
+                        CodeBlock{}     -> False
+                        Para{}          -> False
+                        Plain [Image{}] -> False
+                        Plain [Math{}]  -> False
+                        Table{}         -> False
+                        _               -> True
 
-tableItemToJATS :: PandocMonad m
-                   => WriterOptions
-                   -> Bool
-                   -> [Block]
-                   -> JATS m Doc
-tableItemToJATS opts isHeader [Plain item] =
-  inTags True (if isHeader then "th" else "td") [] <$>
-    inlinesToJATS opts item
-tableItemToJATS opts isHeader item =
-  (inTags True (if isHeader then "th" else "td") [] . vcat) <$>
-    mapM (blockToJATS opts) item
+  children <- wrappedBlocksToJATS needsWrapping opts $ walk unsetAltIfDupl body
+  let (tag, allowedAttributes) =
+        if hasSubfigures
+        then ( "fig-group"
+             , ["content-type", "orientation", "position", "specific-use"]
+             )
+        else ("fig"
+             , ["fig-type", "orientation", "position", "specific-use"]
+             )
+  let xmlattr =  [("id", escapeNCName ident) | not (T.null ident)] ++
+                 [(k,v) | (k,v) <- kvs
+                        , k `elem` allowedAttributes]
+  return $ inTags True tag xmlattr $ capt $$ children
 
 -- | Convert a list of inline elements to JATS.
-inlinesToJATS :: PandocMonad m => WriterOptions -> [Inline] -> JATS m Doc
-inlinesToJATS opts lst = hcat <$> mapM (inlineToJATS opts) lst
+inlinesToJATS :: PandocMonad m => WriterOptions -> [Inline] -> JATS m (Doc Text)
+inlinesToJATS opts lst = hcat <$> mapM (inlineToJATS opts) (fixCitations lst)
+  where
+   fixCitations [] = []
+   fixCitations (x:xs) | needsFixing x =
+     x : Str (stringify ys) : fixCitations zs
+     where
+       needsFixing (RawInline (Format "jats") z) =
+           "<pub-id pub-id-type=" `T.isPrefixOf` z
+       needsFixing _           = False
+       isRawInline RawInline{} = True
+       isRawInline _           = False
+       (ys,zs)                 = break isRawInline xs
+   fixCitations (x:xs) = x : fixCitations xs
 
 -- | Convert an inline element to JATS.
-inlineToJATS :: PandocMonad m => WriterOptions -> Inline -> JATS m Doc
-inlineToJATS _ (Str str) = return $ text $ escapeStringForXML str
+inlineToJATS :: PandocMonad m => WriterOptions -> Inline -> JATS m (Doc Text)
+inlineToJATS _ (Str str) = return $ text $ T.unpack $ escapeStringForXML str
 inlineToJATS opts (Emph lst) =
   inTagsSimple "italic" <$> inlinesToJATS opts lst
+inlineToJATS opts (Underline lst) =
+  inTagsSimple "underline" <$> inlinesToJATS opts lst
 inlineToJATS opts (Strong lst) =
-  inTags False "bold" [("role", "strong")] <$> inlinesToJATS opts lst
+  inTagsSimple "bold" <$> inlinesToJATS opts lst
 inlineToJATS opts (Strikeout lst) =
   inTagsSimple "strike" <$> inlinesToJATS opts lst
 inlineToJATS opts (Superscript lst) =
@@ -350,44 +512,74 @@
 inlineToJATS opts (Subscript lst) =
   inTagsSimple "sub" <$> inlinesToJATS opts lst
 inlineToJATS opts (SmallCaps lst) =
-  inTags False "sc" [("role", "smallcaps")] <$>
-  inlinesToJATS opts lst
+  inTagsSimple "sc" <$> inlinesToJATS opts lst
 inlineToJATS opts (Quoted SingleQuote lst) = do
   contents <- inlinesToJATS opts lst
   return $ char '‘' <> contents <> char '’'
 inlineToJATS opts (Quoted DoubleQuote lst) = do
   contents <- inlinesToJATS opts lst
   return $ char '“' <> contents <> char '”'
-inlineToJATS _ (Code a str) =
-  return $ inTags False tag attr $ text (escapeStringForXML str)
-    where (lang, attr) = codeAttr a
-          tag          = if null lang then "monospace" else "code"
+inlineToJATS opts (Code a str) =
+  return $ inTags False "monospace" attr $ literal (escapeStringForXML str)
+    where (_lang, attr) = codeAttr opts a
 inlineToJATS _ il@(RawInline f x)
-  | f == "jats" = return $ text x
+  | f == "jats" = return $ literal x
   | otherwise   = do
       report $ InlineNotRendered il
       return empty
-inlineToJATS _ LineBreak = return $ selfClosingTag "break" []
+inlineToJATS _ LineBreak = return cr -- not allowed as child of p
+-- see https://jats.nlm.nih.gov/publishing/tag-library/1.2/element/break.html
 inlineToJATS _ Space = return space
 inlineToJATS opts SoftBreak
   | writerWrapText opts == WrapPreserve = return cr
   | otherwise = return space
-inlineToJATS opts (Note contents) =
-  -- TODO technically only <p> tags are allowed inside
-  inTagsIndented "fn" <$> blocksToJATS opts contents
+inlineToJATS opts (Note contents) = do
+  tagSet <- asks jatsTagSet
+  -- Footnotes must occur inline when using the Article Authoring tag set.
+  if tagSet == TagSetArticleAuthoring
+    then inTagsIndented "fn" <$> wrappedBlocksToJATS (not . isPara) opts contents
+    else do
+      notes <- gets jatsNotes
+      let notenum = case notes of
+                      (n, _):_ -> n + 1
+                      []       -> 1
+      thenote <- inTags True "fn" [("id", "fn" <> tshow notenum)]
+                     . (inTagsSimple "label" (literal $ tshow notenum) <>)
+                    <$> wrappedBlocksToJATS (not . isPara) opts
+                         (walk demoteHeaderAndRefs contents)
+      modify $ \st -> st{ jatsNotes = (notenum, thenote) : notes }
+      return $ inTags False "xref" [("ref-type", "fn"),
+                                    ("rid", "fn" <> tshow notenum)]
+             $ text (show notenum)
 inlineToJATS opts (Cite _ lst) =
-  -- TODO revisit this after examining the jats.csl pipeline
   inlinesToJATS opts lst
-inlineToJATS opts (Span ("",_,[]) ils) = inlinesToJATS opts ils
-inlineToJATS opts (Span (ident,_,kvs) ils) = do
+inlineToJATS opts (Span (ident,classes,kvs) ils) = do
   contents <- inlinesToJATS opts ils
-  let attr = [("id",ident) | not (null ident)] ++
-             [("xml:lang",l) | ("lang",l) <- kvs] ++
-             [(k,v) | (k,v) <- kvs
-                    ,  k `elem` ["content-type", "rationale",
-                                 "rid", "specific-use"]]
-  return $ selfClosingTag "milestone-start" attr <> contents <>
-           selfClosingTag "milestone-end" []
+  let commonAttr = [("id", escapeNCName ident) | not (T.null ident)] ++
+                   [("xml:lang",l) | ("lang",l) <- kvs] ++
+                   [(k,v) | (k,v) <- kvs,  k `elem` ["alt", "specific-use"]]
+  -- A named-content element is a good fit for spans, but requires a
+  -- content-type attribute to be present. We use either the explicit
+  -- attribute or the first class as content type. If neither is
+  -- available, then we fall back to using a @styled-content@ element.
+  let (tag, specificAttr) =
+        case lookup "content-type" kvs <|> listToMaybe classes of
+          Just ct -> ( "named-content"
+                     , ("content-type", ct) :
+                       [(k, v) | (k, v) <- kvs
+                       , k `elem` ["rid", "vocab", "vocab-identifier",
+                                   "vocab-term", "vocab-term-identifier"]])
+          -- Fall back to styled-content
+          Nothing -> ("styled-content"
+                     , [(k, v) | (k,v) <- kvs
+                       , k `elem` ["style", "style-type", "style-detail",
+                                   "toggle"]])
+  let attr = commonAttr ++ specificAttr
+  -- unwrap if wrapping element would have no attributes
+  return $
+    if null attr
+    then contents
+    else inTags False tag attr contents
 inlineToJATS _ (Math t str) = do
   let addPref (Xml.Attr q v)
          | Xml.qName q == "xmlns" = Xml.Attr q{ Xml.qName = "xmlns:mml" } v
@@ -401,55 +593,117 @@
   let tagtype = case t of
                      DisplayMath -> "disp-formula"
                      InlineMath  -> "inline-formula"
-  let rawtex = inTagsSimple "tex-math"
-                                $ text "<![CDATA[" <>
-                                  text str <>
-                                  text "]]>"
-  return $ inTagsSimple tagtype $
-             case res of
-                   Right r  -> inTagsSimple "alternatives" $
-                                  cr <> rawtex $$
-                                  text (Xml.ppcElement conf $ fixNS r)
-                   Left _   -> rawtex
-inlineToJATS _ (Link _attr [Str t] ('m':'a':'i':'l':'t':'o':':':email, _))
+
+  let rawtex = text "<![CDATA[" <> literal str <> text "]]>"
+  let texMath = inTagsSimple "tex-math" rawtex
+
+  tagSet <- asks jatsTagSet
+  return . inTagsSimple tagtype $
+    case res of
+      Right r  -> let mathMl = text (Xml.ppcElement conf $ fixNS r)
+                  -- tex-math is unsupported in Article Authoring tag set
+                  in if tagSet == TagSetArticleAuthoring
+                     then mathMl
+                     else inTagsSimple "alternatives" $
+                          cr <> texMath $$ mathMl
+      Left _   -> if tagSet /= TagSetArticleAuthoring
+                  then texMath
+                  else rawtex
+inlineToJATS _ (Link _attr [Str t] (T.stripPrefix "mailto:" -> Just email, _))
   | escapeURI t == email =
-  return $ inTagsSimple "email" $ text (escapeStringForXML email)
-inlineToJATS opts (Link (ident,_,kvs) txt ('#':src, _)) = do
-  let attr = [("id", ident) | not (null ident)] ++
-             [("alt", stringify txt) | not (null txt)] ++
-             [("rid", src)] ++
-             [(k,v) | (k,v) <- kvs, k `elem` ["ref-type", "specific-use"]]
+  return $ inTagsSimple "email" $ literal (escapeStringForXML email)
+inlineToJATS opts (Link (ident,_,kvs) txt (T.uncons -> Just ('#', src), _)) = do
+  let attr = mconcat
+             [ [("id", escapeNCName ident) | not (T.null ident)]
+             , [("alt", stringify txt) | not (null txt)]
+             , [("rid", escapeNCName src)]
+             , [(k,v) | (k,v) <- kvs, k `elem` ["ref-type", "specific-use"]]
+             , [("ref-type", "bibr") | "ref-" `T.isPrefixOf` src]
+             ]
   if null txt
      then return $ selfClosingTag "xref" attr
      else do
         contents <- inlinesToJATS opts txt
         return $ inTags False "xref" attr contents
 inlineToJATS opts (Link (ident,_,kvs) txt (src, tit)) = do
-  let attr = [("id", ident) | not (null ident)] ++
+  let attr = [("id", escapeNCName ident) | not (T.null ident)] ++
              [("ext-link-type", "uri"),
               ("xlink:href", src)] ++
-             [("xlink:title", tit) | not (null tit)] ++
+             [("xlink:title", tit) | not (T.null tit)] ++
              [(k,v) | (k,v) <- kvs, k `elem` ["assigning-authority",
                                               "specific-use", "xlink:actuate",
                                               "xlink:role", "xlink:show",
                                               "xlink:type"]]
   contents <- inlinesToJATS opts txt
   return $ inTags False "ext-link" attr contents
-inlineToJATS _ (Image (ident,_,kvs) _ (src, tit)) = do
-  let mbMT = getMimeType src
-  let maintype = fromMaybe "image" $
+inlineToJATS _ (Image attr alt tgt) = do
+  let elattr = graphicAttr attr alt tgt
+  return $ case altToJATS alt of
+             Nothing -> selfClosingTag "inline-graphic" elattr
+             Just altTag -> inTags True "inline-graphic" elattr altTag
+
+graphic :: Attr -> [Inline] -> Target -> (Doc Text)
+graphic attr alt tgt =
+  let elattr = graphicAttr attr alt tgt
+  in case altToJATS alt of
+       Nothing -> selfClosingTag "graphic" elattr
+       Just altTag -> inTags True "graphic" elattr altTag
+
+graphicAttr :: Attr -> [Inline] -> Target -> [(Text, Text)]
+graphicAttr (ident, _, kvs) _alt (src, tit) =
+  let (maintype, subtype) = imageMimeType src kvs
+  in [("id", escapeNCName ident) | not (T.null ident)] ++
+     [ ("mimetype", maintype)
+     , ("mime-subtype", subtype)
+     , ("xlink:href", src)
+     ] ++
+     [("xlink:title", tit) | not (T.null tit)] ++
+     [(k,v) | (k,v) <- kvs
+            , k `elem` [ "baseline-shift", "content-type", "specific-use"
+                       , "xlink:actuate", "xlink:href", "xlink:role"
+                       , "xlink:show", "xlink:type"]
+            ]
+
+altToJATS :: [Inline] -> Maybe (Doc Text)
+altToJATS alt =
+  if null alt
+  then Nothing
+  else Just . inTagsSimple "alt-text" .
+       hsep . map literal . T.words $ stringify alt
+
+imageMimeType :: Text -> [(Text, Text)] -> (Text, Text)
+imageMimeType src kvs =
+  let mbMT = getMimeType (T.unpack src)
+      maintype = fromMaybe "image" $
                   lookup "mimetype" kvs `mplus`
-                  (takeWhile (/='/') <$> mbMT)
-  let subtype = fromMaybe "" $
+                  (T.takeWhile (/='/') <$> mbMT)
+      subtype = fromMaybe "" $
                   lookup "mime-subtype" kvs `mplus`
-                  ((drop 1 . dropWhile (/='/')) <$> mbMT)
-  let attr = [("id", ident) | not (null ident)] ++
-             [("mimetype", maintype),
-              ("mime-subtype", subtype),
-              ("xlink:href", src)] ++
-             [("xlink:title", tit) | not (null tit)] ++
-             [(k,v) | (k,v) <- kvs, k `elem` ["baseline-shift",
-                        "content-type", "specific-use", "xlink:actuate",
-                        "xlink:href", "xlink:role", "xlink:show",
-                        "xlink:type"]]
-  return $ selfClosingTag "inline-graphic" attr
+                  (T.drop 1 . T.dropWhile (/='/') <$> mbMT)
+  in (maintype, subtype)
+
+isParaOrList :: Block -> Bool
+isParaOrList Para{}           = True
+isParaOrList Plain{}          = True
+isParaOrList BulletList{}     = True
+isParaOrList OrderedList{}    = True
+isParaOrList DefinitionList{} = True
+isParaOrList _                = False
+
+isPara :: Block -> Bool
+isPara Para{}  = True
+isPara Plain{} = True
+isPara _       = False
+
+demoteHeaderAndRefs :: Block -> Block
+demoteHeaderAndRefs (Header _ _ ils) = Para ils
+demoteHeaderAndRefs (Div ("refs",cls,kvs) bs) =
+                       Div ("",cls,kvs) bs
+demoteHeaderAndRefs x = x
+
+parseDate :: Text -> Maybe Day
+parseDate s = msum (map (`parsetimeWith` T.unpack s) formats)
+  where parsetimeWith = parseTimeM True defaultTimeLocale
+        formats = ["%x","%m/%d/%Y", "%D","%F", "%d %b %Y",
+                    "%e %B %Y", "%b. %e, %Y", "%B %e, %Y",
+                    "%Y%m%d", "%Y%m", "%Y"]
diff --git a/src/Text/Pandoc/Writers/JATS/References.hs b/src/Text/Pandoc/Writers/JATS/References.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Writers/JATS/References.hs
@@ -0,0 +1,171 @@
+{-# LANGUAGE LambdaCase        #-}
+{-# LANGUAGE OverloadedStrings #-}
+{- |
+   Module      : Text.Pandoc.Writers.JATS.References
+   Copyright   : © 2021-2024 Albert Krewinkel
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : Albert Krewinkel <albert+pandoc@tarleb.com>
+   Stability   : alpha
+   Portability : portable
+
+Creation of a bibliography list using @<element-citation>@ elements in
+reference items.
+-}
+module Text.Pandoc.Writers.JATS.References
+  ( referencesToJATS
+  , referenceToJATS
+  ) where
+
+import Citeproc.Pandoc ()
+import Citeproc.Types
+  ( Date (..), DateParts (..), ItemId (..), Name (..), Reference (..)
+  , Val (..) , lookupVariable, valToText
+  )
+import Data.Text (Text)
+import Text.DocLayout (Doc, empty, isEmpty, literal, vcat)
+import Text.Pandoc.Class.PandocMonad (PandocMonad)
+import Text.Pandoc.Builder (Inlines)
+import Text.Pandoc.Options (WriterOptions)
+import Text.Pandoc.Shared (tshow)
+import Text.Pandoc.Writers.JATS.Types
+import Text.Pandoc.XML (escapeNCName, escapeStringForXML, inTags)
+import qualified Data.Text as T
+
+referencesToJATS :: PandocMonad m
+                 => WriterOptions
+                 -> [Reference Inlines]
+                 -> JATS m (Doc Text)
+referencesToJATS opts =
+  fmap vcat . mapM (referenceToJATS opts)
+
+referenceToJATS :: PandocMonad m
+                => WriterOptions
+                -> Reference Inlines
+                -> JATS m (Doc Text)
+referenceToJATS _opts ref = do
+  let refType = referenceType ref
+  let pubType = [("publication-type", refType) | not (T.null refType)]
+  let ident = escapeNCName $ "ref-" <> unItemId (referenceId ref)
+  let wrap = inTags True "ref" [("id", ident)]
+           . inTags True "element-citation" pubType
+  return . wrap . vcat $
+    [ authors
+    , "title" `varInTag`
+      if refType == "book"
+      then "source"
+      else "article-title"
+    , if refType == "book"
+      then empty
+      else "container-title" `varInTag` "source"
+    , editors
+    , "publisher"       `varInTag` "publisher-name"
+    , "publisher-place" `varInTag` "publisher-loc"
+    , yearTag
+    , accessed
+    , "volume"          `varInTag` "volume"
+    , "issue"           `varInTag` "issue"
+    , "edition"         `varInTag` "edition"
+    , "page-first"      `varInTag` "fpage"
+    , "ISBN"            `varInTag` "isbn"
+    , "ISSN"            `varInTag` "issn"
+    , "URL"             `varInTag` "uri"
+    , varInTagWith "doi"  "pub-id" [("pub-id-type", "doi")]
+    , varInTagWith "pmid" "pub-id" [("pub-id-type", "pmid")]
+    ] ++
+    case lookupVariable "page" ref >>= valToText of
+      Nothing -> []
+      Just val ->
+        let isdash c = c == '-' || c == '\x2013'
+            (fpage, lpage) = T.dropWhile isdash <$> T.break isdash val
+         in [ inTags' "fpage" [] $ literal $ escapeStringForXML fpage,
+              inTags' "lpage" [] $ literal $ escapeStringForXML lpage ]
+  where
+    varInTag var tagName = varInTagWith var tagName []
+
+    varInTagWith var tagName tagAttribs =
+      case lookupVariable var ref >>= valToText of
+        Nothing  -> mempty
+        Just val -> inTags' tagName tagAttribs . literal $
+                    escapeStringForXML val
+
+    authors = case lookupVariable "author" ref of
+      Just (NamesVal names) ->
+        inTags True "person-group" [("person-group-type", "author")] . vcat $
+        map toNameElements names
+      _                     -> empty
+
+    editors = case lookupVariable "editor" ref of
+      Just (NamesVal names) ->
+        inTags True "person-group" [("person-group-type", "editor")] . vcat $
+        map toNameElements names
+      _                     -> empty
+
+    yearTag =
+      case lookupVariable "issued" ref of
+        Just (DateVal date) -> toDateElements date
+        _ -> empty
+
+    accessed =
+      case lookupVariable "accessed" ref of
+        Just (DateVal d) -> inTags' "date-in-citation"
+                                    [("content-type", "access-date")]
+                                    (toDateElements d)
+        _ -> empty
+
+toDateElements :: Date -> Doc Text
+toDateElements date =
+  case dateParts date of
+    dp@(DateParts (y:m:d:_)):_ -> yearElement y dp <>
+                                  monthElement m <>
+                                  dayElement d
+    dp@(DateParts (y:m:_)):_   -> yearElement y dp <> monthElement m
+    dp@(DateParts (y:_)):_     -> yearElement y dp
+    _                          -> empty
+
+yearElement :: Int -> DateParts -> Doc Text
+yearElement year dp =
+  inTags' "year" [("iso-8601-date", iso8601 dp)] $ literal (fourDigits year)
+
+monthElement :: Int -> Doc Text
+monthElement month = inTags' "month" [] . literal $ twoDigits month
+
+dayElement :: Int -> Doc Text
+dayElement day = inTags' "day" [] . literal $ twoDigits day
+
+iso8601 :: DateParts -> Text
+iso8601 = T.intercalate "-" . \case
+  DateParts (y:m:d:_) -> [fourDigits y, twoDigits m, twoDigits d]
+  DateParts (y:m:_)   -> [fourDigits y, twoDigits m]
+  DateParts (y:_)     -> [fourDigits y]
+  _                   -> []
+
+twoDigits :: Int -> Text
+twoDigits n = T.takeEnd 2 $ '0' `T.cons` tshow n
+
+fourDigits :: Int -> Text
+fourDigits n = T.takeEnd 4 $ "000" <> tshow n
+
+toNameElements :: Name -> Doc Text
+toNameElements name
+  | not (isEmpty nameTags) = inTags' "name" [] nameTags
+  | nameLiteral name == Just "others" = "<etal/>"
+  | otherwise = nameLiteral name `inNameTag` "string-name"
+  where
+      inNameTag mVal tag = case mVal of
+        Nothing  -> empty
+        Just val -> inTags' tag [] . literal $ escapeStringForXML val
+      surnamePrefix = maybe mempty (`T.snoc` ' ') $
+                      nameNonDroppingParticle name
+      givenSuffix = maybe mempty (T.cons ' ') $
+                    nameDroppingParticle name
+      nameTags = mconcat
+        [ ((surnamePrefix <>) <$> nameFamily name) `inNameTag` "surname"
+        , ((<> givenSuffix) <$> nameGiven name) `inNameTag` "given-names"
+        , nameSuffix name `inNameTag` "suffix"
+        ]
+
+-- | Put the supplied contents between start and end tags of tagType,
+--   with specified attributes.
+inTags' :: Text -> [(Text, Text)] -> Doc Text -> Doc Text
+inTags' = inTags False
diff --git a/src/Text/Pandoc/Writers/JATS/Table.hs b/src/Text/Pandoc/Writers/JATS/Table.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Writers/JATS/Table.hs
@@ -0,0 +1,273 @@
+{-# LANGUAGE LambdaCase #-}
+{-# LANGUAGE OverloadedStrings #-}
+{-# LANGUAGE TupleSections #-}
+{- |
+   Module      : Text.Pandoc.Writers.JATS.Table
+   Copyright   : © 2020-2024 Albert Krewinkel
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : Albert Krewinkel <albert+pandoc@tarleb.com>
+   Stability   : alpha
+   Portability : portable
+
+Conversion of 'Pandoc' tables to JATS XML.
+-}
+module Text.Pandoc.Writers.JATS.Table
+  ( tableToJATS
+  ) where
+import Control.Monad.Reader (asks)
+import Data.List.NonEmpty (NonEmpty ((:|)))
+import Data.Text (Text)
+import Text.DocLayout (Doc, empty, vcat, ($$))
+import Text.Pandoc.Class.PandocMonad (PandocMonad)
+import Text.Pandoc.Definition
+import Text.Pandoc.Options (WriterOptions)
+import Text.Pandoc.Shared (tshow)
+import Text.Pandoc.Writers.JATS.Types
+import Text.Pandoc.XML (escapeNCName, inTags, inTagsIndented, selfClosingTag)
+import qualified Data.Text as T
+import qualified Text.Pandoc.Writers.AnnotatedTable as Ann
+
+tableToJATS :: PandocMonad m
+            => WriterOptions
+            -> Ann.Table
+            -> JATS m (Doc Text)
+tableToJATS opts (Ann.Table attr caption colspecs thead tbodies tfoot) = do
+  let (Caption _maybeShortCaption captionBlocks) = caption
+  -- Only paragraphs are allowed in captions, all other blocks must be
+  -- wrapped in @<p>@ elements.
+  let needsWrapping = \case
+        Plain{} -> False
+        Para{}  -> False
+        _       -> True
+  tbl <- captionlessTable opts attr colspecs thead tbodies tfoot
+  captionDoc <- if null captionBlocks
+                then return empty
+                else do
+                  blockToJATS <- asks jatsBlockWriter
+                  inTagsIndented "caption" <$>
+                    blockToJATS needsWrapping opts captionBlocks
+  return $ inTags True "table-wrap" [] $ captionDoc $$ tbl
+
+captionlessTable :: PandocMonad m
+                 => WriterOptions
+                 -> Attr
+                 -> [ColSpec]
+                 -> Ann.TableHead
+                 -> [Ann.TableBody]
+                 -> Ann.TableFoot
+                 -> JATS m (Doc Text)
+captionlessTable opts attr colspecs thead tbodies tfoot = do
+  head' <- tableHeadToJats opts thead
+  bodies <- mapM (tableBodyToJats opts) tbodies
+  foot' <- tableFootToJats opts tfoot
+  let validAttribs = [ "border", "cellpadding", "cellspacing", "content-type"
+                     , "frame", "rules", "specific-use", "style", "summary"
+                     , "width"
+                     ]
+  let attribs = toAttribs attr validAttribs
+  return $ inTags True "table" attribs $ vcat
+    [ colSpecListToJATS colspecs
+    , head'
+    , foot'
+    , vcat bodies
+    ]
+
+validTablePartAttribs :: [Text]
+validTablePartAttribs =
+  [ "align", "char", "charoff", "content-type", "style", "valign" ]
+
+tableBodyToJats :: PandocMonad m
+                => WriterOptions
+                -> Ann.TableBody
+                -> JATS m (Doc Text)
+tableBodyToJats opts (Ann.TableBody attr _rowHeadCols inthead rows) = do
+  let attribs = toAttribs attr validTablePartAttribs
+  intermediateHead <- if null inthead
+                      then return mempty
+                      else headerRowsToJats opts Thead inthead
+  bodyRows <- bodyRowsToJats opts rows
+  return $ inTags True "tbody" attribs $ intermediateHead $$ bodyRows
+
+tableHeadToJats :: PandocMonad m
+                => WriterOptions
+                -> Ann.TableHead
+                -> JATS m (Doc Text)
+tableHeadToJats opts (Ann.TableHead attr rows) =
+  tablePartToJats opts Thead attr rows
+
+tableFootToJats :: PandocMonad m
+                => WriterOptions
+                -> Ann.TableFoot
+                -> JATS m (Doc Text)
+tableFootToJats opts (Ann.TableFoot attr rows) =
+  tablePartToJats opts Tfoot attr rows
+
+tablePartToJats :: PandocMonad m
+                => WriterOptions
+                -> TablePart
+                -> Attr
+                -> [Ann.HeaderRow]
+                -> JATS m (Doc Text)
+tablePartToJats opts tblpart attr rows =
+  if null rows || all isEmptyRow rows
+  then return mempty
+  else do
+    let tag' = case tblpart of
+                 Thead -> "thead"
+                 Tfoot -> "tfoot"
+                 Tbody -> "tbody" -- this would be unexpected
+    let attribs = toAttribs attr validTablePartAttribs
+    inTags True tag' attribs <$> headerRowsToJats opts tblpart rows
+  where
+    isEmptyRow (Ann.HeaderRow _attr _rownum cells) = all isEmptyCell cells
+    isEmptyCell (Ann.Cell _colspecs _colnum cell) =
+      cell == Cell nullAttr AlignDefault (RowSpan 1) (ColSpan 1) []
+
+-- | The part of a table; header, footer, or body.
+data TablePart = Thead | Tfoot | Tbody
+  deriving (Eq)
+
+data CellType = HeaderCell | BodyCell
+
+data TableRow = TableRow TablePart Attr Ann.RowNumber Ann.RowHead Ann.RowBody
+
+headerRowsToJats :: PandocMonad m
+                 => WriterOptions
+                 -> TablePart
+                 -> [Ann.HeaderRow]
+                 -> JATS m (Doc Text)
+headerRowsToJats opts tablepart =
+  rowListToJats opts . map toTableRow
+  where
+    toTableRow (Ann.HeaderRow attr rownum rowbody) =
+      TableRow tablepart attr rownum [] rowbody
+
+bodyRowsToJats :: PandocMonad m
+               => WriterOptions
+               -> [Ann.BodyRow]
+               -> JATS m (Doc Text)
+bodyRowsToJats opts =
+  rowListToJats opts . zipWith toTableRow [1..]
+  where
+    toTableRow rownum (Ann.BodyRow attr _rownum rowhead rowbody) =
+      TableRow Tbody attr rownum rowhead rowbody
+
+rowListToJats :: PandocMonad m
+              => WriterOptions
+              -> [TableRow]
+              -> JATS m (Doc Text)
+rowListToJats opts = fmap vcat . mapM (tableRowToJats opts)
+
+colSpecListToJATS :: [ColSpec] -> Doc Text
+colSpecListToJATS colspecs =
+  let hasDefaultWidth (_, ColWidthDefault) = True
+      hasDefaultWidth _                    = False
+
+      percent w = tshow (round (100*w) :: Integer) <> "%"
+
+      col :: ColWidth -> Doc Text
+      col = selfClosingTag "col" . \case
+        ColWidthDefault -> mempty
+        ColWidth w -> [("width", percent w)]
+
+   in if all hasDefaultWidth colspecs
+      then mempty
+      else inTags True "colgroup" [] $ vcat $ map (col . snd) colspecs
+
+tableRowToJats :: PandocMonad m
+               => WriterOptions
+               -> TableRow
+               -> JATS m (Doc Text)
+tableRowToJats opts (TableRow tblpart attr _rownum rowhead rowbody) = do
+  let validAttribs = [ "align", "char", "charoff", "content-type"
+                     , "style", "valign"
+                     ]
+  let attr' = toAttribs attr validAttribs
+  let celltype = case tblpart of
+                   Thead -> HeaderCell
+                   _     -> BodyCell
+  headcells <- mapM (cellToJats opts HeaderCell) rowhead
+  bodycells <- mapM (cellToJats opts celltype) rowbody
+  return $ inTags True "tr" attr' $ mconcat
+    [ vcat headcells
+    , vcat bodycells
+    ]
+
+alignmentAttrib :: Alignment -> Maybe (Text, Text)
+alignmentAttrib = fmap ("align",) . \case
+  AlignLeft    -> Just "left"
+  AlignRight   -> Just "right"
+  AlignCenter  -> Just "center"
+  AlignDefault -> Nothing
+
+colspanAttrib :: ColSpan -> Maybe (Text, Text)
+colspanAttrib = \case
+  ColSpan 1 -> Nothing
+  ColSpan n -> Just ("colspan", tshow n)
+
+rowspanAttrib :: RowSpan -> Maybe (Text, Text)
+rowspanAttrib = \case
+  RowSpan 1 -> Nothing
+  RowSpan n -> Just ("rowspan", tshow n)
+
+cellToJats :: PandocMonad m
+           => WriterOptions
+           -> CellType
+           -> Ann.Cell
+           -> JATS m (Doc Text)
+cellToJats opts celltype (Ann.Cell (colspec :| _) _colNum cell) =
+  let align = fst colspec
+  in tableCellToJats opts celltype align cell
+
+toAttribs :: Attr -> [Text] -> [(Text, Text)]
+toAttribs (ident, _classes, kvs) knownAttribs =
+  (if T.null ident then id else (("id", escapeNCName ident) :)) $
+  filter ((`elem` knownAttribs) . fst) kvs
+
+tableCellToJats :: PandocMonad m
+                => WriterOptions
+                -> CellType
+                -> Alignment
+                -> Cell
+                -> JATS m (Doc Text)
+tableCellToJats opts ctype colAlign (Cell attr align rowspan colspan item) = do
+  blockToJats   <- asks jatsBlockWriter
+  inlinesToJats <- asks jatsInlinesWriter
+  let fixBreak LineBreak = RawInline (Format "jats") "<break/>"
+      fixBreak x         = x
+  let cellContents = \case
+        [Plain inlines] -> inlinesToJats opts
+                             (map fixBreak inlines)
+                             -- Note: <break/> is allowed only as a direct
+                             -- child of <td>, so we don't use walk.
+        blocks          -> blockToJats needsWrapInCell opts blocks
+  let tag' = case ctype of
+        BodyCell   -> "td"
+        HeaderCell -> "th"
+  let align' = case align of
+        AlignDefault -> colAlign
+        _            -> align
+  let maybeCons = maybe id (:)
+  let validAttribs = [ "abbr", "align", "axis", "char", "charoff"
+                     , "content-type", "headers", "scope", "style", "valign"
+                     ]
+  let attribs = maybeCons (alignmentAttrib align')
+              . maybeCons (rowspanAttrib rowspan)
+              . maybeCons (colspanAttrib colspan)
+              $ toAttribs attr validAttribs
+  inTags False tag' attribs <$> cellContents item
+
+-- | Whether the JATS produced from this block should be wrapped in a
+-- @<p>@ element when put directly below a @<td>@ element.
+needsWrapInCell :: Block -> Bool
+needsWrapInCell = \case
+  Plain{}          -> False  -- should be unwrapped anyway
+  Para{}           -> False
+  BulletList{}     -> False
+  OrderedList{}    -> False
+  DefinitionList{} -> False
+  HorizontalRule   -> False
+  CodeBlock{}      -> False
+  RawBlock{}       -> False  -- responsibility of the user
+  _                -> True
diff --git a/src/Text/Pandoc/Writers/JATS/Types.hs b/src/Text/Pandoc/Writers/JATS/Types.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Writers/JATS/Types.hs
@@ -0,0 +1,57 @@
+{- |
+   Module      : Text.Pandoc.Writers.JATS.Types
+   Copyright   : Copyright (C) 2017-2024 John MacFarlane
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : John MacFarlane <jgm@berkeley.edu>
+   Stability   : alpha
+   Portability : portable
+
+Types for pandoc's JATS writer.
+-}
+module Text.Pandoc.Writers.JATS.Types
+  ( JATS
+  , JATSEnv (..)
+  , JATSState (..)
+  , JATSTagSet (..)
+  )
+where
+
+import Citeproc.Types (Reference)
+import Control.Monad.Reader (ReaderT)
+import Control.Monad.State (StateT)
+import Data.Text (Text)
+import Text.DocLayout (Doc)
+import Text.Pandoc.Builder (Block, Inline, Inlines)
+import Text.Pandoc.Options (WriterOptions)
+
+-- | JATS tag set variant
+data JATSTagSet
+  = TagSetArchiving         -- ^ Archiving and Interchange Tag Set
+  | TagSetPublishing        -- ^ Journal Publishing Tag Set
+  | TagSetArticleAuthoring  -- ^ Article Authoring Tag Set
+  deriving (Eq)
+
+-- | Internal state used by the writer.
+newtype JATSState = JATSState
+  { jatsNotes :: [(Int, Doc Text)]
+  }
+
+-- | Environment containing all information relevant for rendering.
+data JATSEnv m = JATSEnv
+  { jatsTagSet :: JATSTagSet  -- ^ The tag set that's being output
+
+  , jatsBlockWriter   :: (Block -> Bool)
+                      -> WriterOptions -> [Block]  -> JATS m (Doc Text)
+    -- ^ Converts a block list to JATS, wrapping top-level blocks into a
+    -- @<p>@ element if the property evaluates to @True@.
+    -- See #7227.
+
+  , jatsInlinesWriter :: WriterOptions -> [Inline] -> JATS m (Doc Text)
+    -- ^ Converts an inline list to JATS.
+
+  , jatsReferences    :: [Reference Inlines] -- ^ List of references
+  }
+
+-- | JATS writer type
+type JATS m = StateT JATSState (ReaderT (JATSEnv m) m)
diff --git a/src/Text/Pandoc/Writers/Jira.hs b/src/Text/Pandoc/Writers/Jira.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Writers/Jira.hs
@@ -0,0 +1,329 @@
+{-# LANGUAGE LambdaCase #-}
+{-# LANGUAGE OverloadedStrings #-}
+{-# LANGUAGE PatternGuards #-}
+{- |
+   Module      : Text.Pandoc.Writers.Jira
+   Copyright   : © 2010-2024 Albert Krewinkel, John MacFarlane
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : Albert Krewinkel <albert+pandoc@tarleb.com>
+   Stability   : alpha
+   Portability : portable
+
+Conversion of 'Pandoc' documents to Jira markup.
+
+JIRA:
+<https://jira.atlassian.com/secure/WikiRendererHelpAction.jspa?section=all>
+-}
+module Text.Pandoc.Writers.Jira ( writeJira ) where
+import Control.Monad.Reader (ReaderT, ask, asks, runReaderT)
+import Control.Monad.State.Strict (StateT, evalStateT, gets, modify)
+import Data.Text (Text)
+import Text.Jira.Parser (plainText)
+import Text.Jira.Printer (prettyBlocks, prettyInlines)
+import Text.Pandoc.Class.PandocMonad (PandocMonad)
+import Text.Pandoc.Definition
+import Text.Pandoc.Options (WriterOptions (writerTemplate, writerWrapText),
+                            WrapOption (..))
+import Text.Pandoc.Shared (linesToPara, stringify)
+import Text.Pandoc.Templates (renderTemplate)
+import Text.Pandoc.Writers.Math (texMathToInlines)
+import Text.Pandoc.Writers.Shared (defField, metaToContext, toLegacyTable)
+import Text.DocLayout (literal, render)
+import qualified Data.Text as T
+import qualified Text.Jira.Markup as Jira
+
+-- | Convert Pandoc to Jira.
+writeJira :: PandocMonad m => WriterOptions -> Pandoc -> m Text
+writeJira opts = runDefaultConverter (writerWrapText opts) (pandocToJira opts)
+
+-- | State to keep track of footnotes.
+data ConverterState = ConverterState
+  { stNotes   :: [Text] -- ^ Footnotes to be appended to the end of the text
+  , stInPanel :: Bool   -- ^ whether we are in a @{panel}@ block
+  }
+
+-- | Initial converter state.
+startState :: ConverterState
+startState = ConverterState
+  { stNotes = []
+  , stInPanel = False
+  }
+
+-- | Converter monad
+type JiraConverter m = ReaderT WrapOption (StateT ConverterState m)
+
+-- | Run a converter using the default state
+runDefaultConverter :: PandocMonad m
+                    => WrapOption
+                    -> (a -> JiraConverter m Text)
+                    -> a
+                    -> m Text
+runDefaultConverter wrap c x = evalStateT (runReaderT (c x) wrap) startState
+
+-- | Return Jira representation of document.
+pandocToJira :: PandocMonad m
+             => WriterOptions -> Pandoc -> JiraConverter m Text
+pandocToJira opts (Pandoc meta blocks) = do
+  wrap <- ask
+  metadata <- metaToContext opts
+                 (fmap literal . runDefaultConverter wrap blockListToJira)
+                 (fmap literal . runDefaultConverter wrap inlineListToJira) meta
+  body <- blockListToJira blocks
+  notes <- gets $ T.intercalate "\n" . reverse . stNotes
+  let main = body <> if T.null notes then mempty else "\n\n" <> notes
+  let context = defField "body" main metadata
+  return $
+    case writerTemplate opts of
+      Nothing  -> main
+      Just tpl -> render Nothing $ renderTemplate tpl context
+
+blockListToJira :: PandocMonad m => [Block] -> JiraConverter m Text
+blockListToJira = fmap prettyBlocks . toJiraBlocks
+
+inlineListToJira :: PandocMonad m => [Inline] -> JiraConverter m Text
+inlineListToJira = fmap prettyInlines . toJiraInlines
+
+toJiraBlocks :: PandocMonad m => [Block] -> JiraConverter m [Jira.Block]
+toJiraBlocks blocks = do
+  let convert = \case
+        BlockQuote bs        -> singleton . Jira.BlockQuote
+                                <$> toJiraBlocks bs
+        BulletList items     -> singleton . Jira.List Jira.CircleBullets
+                                <$> toJiraItems items
+        CodeBlock attr cs    -> toJiraCode attr cs
+        DefinitionList items -> toJiraDefinitionList items
+        Div attr bs          -> toJiraPanel attr bs
+        Header lvl attr xs   -> toJiraHeader lvl attr xs
+        HorizontalRule       -> return . singleton $ Jira.HorizontalRule
+        LineBlock xs         -> toJiraBlocks [linesToPara xs]
+        OrderedList _ items  -> singleton . Jira.List Jira.Enumeration
+                                <$> toJiraItems items
+        Para xs              -> singleton . Jira.Para <$> toJiraInlines xs
+        Plain xs             -> singleton . Jira.Para <$> toJiraInlines xs
+        RawBlock fmt cs      -> rawBlockToJira fmt cs
+        Table _ blkCapt specs thead tbody tfoot -> singleton <$> do
+          let (_, _, _, hd, body) = toLegacyTable blkCapt specs thead tbody tfoot
+          headerRow <- if all null hd
+                       then pure Nothing
+                       else Just <$> toRow Jira.HeaderCell hd
+          bodyRows <- mapM (toRow Jira.BodyCell) body
+          let rows = case headerRow of
+                       Just header -> header : bodyRows
+                       Nothing     -> bodyRows
+          return $ Jira.Table rows
+        Figure attr _ body         -> toJiraPanel attr body
+  jiraBlocks <- mapM convert blocks
+  return $ mconcat jiraBlocks
+
+toRow :: PandocMonad m
+      => ([Jira.Block] -> Jira.Cell)
+      -> [[Block]]
+      -> JiraConverter m Jira.Row
+toRow mkCell cells = Jira.Row <$>
+  mapM (fmap mkCell . toJiraBlocks) cells
+
+toJiraItems :: PandocMonad m => [[Block]] -> JiraConverter m [[Jira.Block]]
+toJiraItems = mapM toJiraBlocks
+
+toJiraCode :: PandocMonad m
+           => Attr
+           -> Text
+           -> JiraConverter m [Jira.Block]
+toJiraCode (ident, classes, _attribs) code = do
+  return . addAnchor ident . singleton $
+    case classes of
+      []  -> Jira.NoFormat mempty code
+      l:_ -> Jira.Code (Jira.Language l) mempty code
+
+-- | Prepends an anchor with the given identifier.
+addAnchor :: Text -> [Jira.Block] -> [Jira.Block]
+addAnchor ident =
+  if T.null ident
+  then id
+  else \case
+    Jira.Para xs : bs -> (Jira.Para (Jira.Anchor ident : xs) : bs)
+    bs                -> (Jira.Para (singleton (Jira.Anchor ident)) : bs)
+
+-- | Creates a Jira definition list
+toJiraDefinitionList :: PandocMonad m
+                     => [([Inline], [[Block]])]
+                     -> JiraConverter m [Jira.Block]
+toJiraDefinitionList defItems = do
+  let convertDefItem (term, defs) = do
+        jiraTerm <- Jira.Para <$> styled Jira.Strong term
+        jiraDefs <- mconcat <$> mapM toJiraBlocks defs
+        return $ jiraTerm : jiraDefs
+  singleton . Jira.List Jira.CircleBullets <$> mapM convertDefItem defItems
+
+-- | Creates a Jira panel
+toJiraPanel :: PandocMonad m
+            => Attr -> [Block]
+            -> JiraConverter m [Jira.Block]
+toJiraPanel (ident, classes, attribs) blocks = do
+  inPanel <- gets stInPanel
+  if inPanel || ("panel" `notElem` classes && null attribs)
+    then addAnchor ident <$> toJiraBlocks blocks
+    else do
+      modify $ \st -> st{ stInPanel = True }
+      jiraBlocks <- toJiraBlocks blocks
+      modify $ \st -> st{ stInPanel = inPanel }
+      let params = map (uncurry Jira.Parameter) attribs
+      return $ singleton (Jira.Panel params $ addAnchor ident jiraBlocks)
+
+-- | Creates a Jira header
+toJiraHeader :: PandocMonad m
+             => Int -> Attr -> [Inline]
+             -> JiraConverter m [Jira.Block]
+toJiraHeader lvl (ident, _, _) inlines =
+  let anchor = Jira.Anchor ident
+  in singleton . Jira.Header lvl . (anchor :) <$> toJiraInlines inlines
+
+-- | Handles raw block. Jira is included verbatim, everything else is
+-- discarded.
+rawBlockToJira :: PandocMonad m
+               => Format -> Text
+               -> JiraConverter m [Jira.Block]
+rawBlockToJira fmt cs = do
+  rawInlines <- toJiraRaw fmt cs
+  return $
+    if null rawInlines
+    then mempty
+    else singleton (Jira.Para rawInlines)
+
+toJiraRaw :: PandocMonad m
+          => Format -> Text -> JiraConverter m [Jira.Inline]
+toJiraRaw fmt cs = case fmt of
+  Format "jira" -> return . singleton $ Jira.Str cs
+  _             -> return mempty
+
+
+--
+-- Inlines
+--
+
+toJiraInlines :: PandocMonad m => [Inline] -> JiraConverter m [Jira.Inline]
+toJiraInlines inlines = do
+  let convert = \case
+        Cite _ xs          -> toJiraInlines xs
+        Code _ cs          -> return . singleton $
+                              Jira.Monospaced (escapeSpecialChars cs)
+        Emph xs            -> styled Jira.Emphasis xs
+        Underline xs       -> styled Jira.Insert xs
+        Image attr cap tgt -> uncurry (imageToJira attr cap) tgt
+        LineBreak          -> pure . singleton $ Jira.Linebreak
+        Link attr xs tgt   -> toJiraLink attr tgt xs
+        Math mtype cs      -> mathToJira mtype cs
+        Note bs            -> registerNotes bs
+        Quoted qt xs       -> quotedToJira qt xs
+        RawInline fmt cs   -> toJiraRaw fmt cs
+        SmallCaps xs       -> styled Jira.Strong xs
+        SoftBreak          -> do
+                                preserveBreak <- asks (== WrapPreserve)
+                                pure . singleton $ if preserveBreak
+                                  then Jira.Linebreak
+                                  else Jira.Space
+        Space              -> pure . singleton $ Jira.Space
+        Span attr xs       -> spanToJira attr xs
+        Str s              -> pure $ escapeSpecialChars s
+        Strikeout xs       -> styled Jira.Strikeout xs
+        Strong xs          -> styled Jira.Strong xs
+        Subscript xs       -> styled Jira.Subscript xs
+        Superscript xs     -> styled Jira.Superscript xs
+  jiraInlines <- mapM convert inlines
+  return $ mconcat jiraInlines
+
+singleton :: a -> [a]
+singleton = (:[])
+
+styled :: PandocMonad m
+       => Jira.InlineStyle -> [Inline]
+       -> JiraConverter m [Jira.Inline]
+styled s = fmap (singleton . Jira.Styled s) . toJiraInlines
+
+-- | Converts a plain text value to Jira inlines, ensuring that all
+-- special characters will be handled appropriately.
+escapeSpecialChars :: Text -> [Jira.Inline]
+escapeSpecialChars t = case plainText t of
+  Right xs -> xs
+  Left _  -> singleton $ Jira.Str t
+
+imageToJira :: PandocMonad m
+            => Attr -> [Inline] -> Text -> Text
+            -> JiraConverter m [Jira.Inline]
+imageToJira (_, classes, kvs) caption src title =
+  let imageWithParams ps = Jira.Image ps (Jira.URL src)
+      alt = stringify caption
+  in pure . singleton . imageWithParams $
+     if "thumbnail" `elem` classes
+     then [Jira.Parameter "thumbnail" ""]
+     else map (uncurry Jira.Parameter)
+          . (if T.null title then id else (("title", title):))
+          . (if T.null alt then id else (("alt", alt):))
+          $ kvs
+
+-- | Creates a Jira Link element.
+toJiraLink :: PandocMonad m
+           => Attr
+           -> Target
+           -> [Inline]
+           -> JiraConverter m [Jira.Inline]
+toJiraLink (_, classes, _) (url, _) alias = do
+  let (linkType, url') = toLinkType url
+  description <- if url `elem` [stringify alias, "mailto:" <> stringify alias]
+                 then pure mempty
+                 else toJiraInlines alias
+  pure . singleton $ Jira.Link linkType description (Jira.URL url')
+ where
+  toLinkType url'
+    | Just email <- T.stripPrefix "mailto:" url' = (Jira.Email, email)
+    | "user-account" `elem` classes              = (Jira.User, dropTilde url)
+    | "attachment" `elem` classes                = (Jira.Attachment, url)
+    | "smart-card" `elem` classes                = (Jira.SmartCard, url)
+    | "smart-link" `elem` classes                = (Jira.SmartLink, url)
+    | otherwise                                  = (Jira.External, url)
+  dropTilde txt = case T.uncons txt of
+    Just ('~', username) -> username
+    _                    -> txt
+
+mathToJira :: PandocMonad m
+           => MathType
+           -> Text
+           -> JiraConverter m [Jira.Inline]
+mathToJira mtype cs = do
+  mathInlines <- toJiraInlines =<< texMathToInlines mtype cs
+  return $ case mtype of
+    InlineMath  -> mathInlines
+    DisplayMath -> Jira.Linebreak : mathInlines ++ [Jira.Linebreak]
+
+quotedToJira :: PandocMonad m
+             => QuoteType
+             -> [Inline]
+             -> JiraConverter m [Jira.Inline]
+quotedToJira qtype xs = do
+  let quoteChar = case qtype of
+                    DoubleQuote -> "\""
+                    SingleQuote -> "'"
+  let surroundWithQuotes = (Jira.Str quoteChar :) . (++ [Jira.Str quoteChar])
+  surroundWithQuotes <$> toJiraInlines xs
+
+spanToJira :: PandocMonad m
+           => Attr -> [Inline]
+           -> JiraConverter m [Jira.Inline]
+spanToJira (ident, _classes, attribs) inls =
+  let wrap = case lookup "color" attribs of
+               Nothing -> id
+               Just color -> singleton . Jira.ColorInline (Jira.ColorName color)
+  in wrap <$> case ident of
+    "" -> toJiraInlines inls
+    _  -> (Jira.Anchor ident :) <$> toJiraInlines inls
+
+registerNotes :: PandocMonad m => [Block] -> JiraConverter m [Jira.Inline]
+registerNotes contents = do
+  curNotes <- gets stNotes
+  let newnum = length curNotes + 1
+  contents' <- blockListToJira contents
+  let thisnote = "\\[" <> T.pack (show newnum) <> "] " <> contents' <> "\n"
+  modify $ \s -> s { stNotes = thisnote : curNotes }
+  return . singleton . Jira.Str $
+    "[" <> T.pack (show newnum) <> "]"
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
@@ -1,1500 +1,1511 @@
 {-# LANGUAGE OverloadedStrings   #-}
-{-# LANGUAGE PatternGuards       #-}
-{-# LANGUAGE ScopedTypeVariables #-}
-{-
-Copyright (C) 2006-2017 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-2017 John MacFarlane
-   License     : GNU GPL, version 2 or above
-
-   Maintainer  : John MacFarlane <jgm@berkeley.edu>
-   Stability   : alpha
-   Portability : portable
-
-Conversion of 'Pandoc' format into LaTeX.
--}
-module Text.Pandoc.Writers.LaTeX (
-    writeLaTeX
-  , writeBeamer
-  ) where
-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.List (foldl', intercalate, intersperse, isInfixOf, nubBy,
-                  stripPrefix, (\\))
-import Data.Maybe (catMaybes, fromMaybe, isJust, mapMaybe)
-import Data.Text (Text)
-import qualified Data.Text as T
-import Network.URI (unEscapeString)
-import Text.Pandoc.BCP47 (Lang (..), getLang, renderLang)
-import Text.Pandoc.Class (PandocMonad, report, toLang)
-import Text.Pandoc.Definition
-import Text.Pandoc.Highlighting (formatLaTeXBlock, formatLaTeXInline, highlight,
-                                 styleToLaTeX, toListingsLanguage)
-import Text.Pandoc.ImageSize
-import Text.Pandoc.Logging
-import Text.Pandoc.Options
-import Text.Pandoc.Pretty
-import Text.Pandoc.Shared
-import Text.Pandoc.Slides
-import Text.Pandoc.Templates
-import Text.Pandoc.Walk
-import Text.Pandoc.Writers.Shared
-import qualified Text.Parsec as P
-import Text.Printf (printf)
-
-data WriterState =
-  WriterState { stInNote        :: Bool          -- true if we're in a note
-              , stInQuote       :: Bool          -- true if in a blockquote
-              , stInMinipage    :: Bool          -- true if in minipage
-              , stInHeading     :: Bool          -- true if in a section heading
-              , stInItem        :: Bool          -- true if in \item[..]
-              , stNotes         :: [Doc]         -- notes in a minipage
-              , stOLLevel       :: Int           -- level of ordered list nesting
-              , stOptions       :: WriterOptions -- writer options, so they don't have to be parameter
-              , stVerbInNote    :: Bool          -- true if document has verbatim text in note
-              , stTable         :: Bool          -- true if document has a table
-              , stStrikeout     :: Bool          -- true if document has strikeout
-              , stUrl           :: Bool          -- true if document has visible URL link
-              , stGraphics      :: Bool          -- true if document contains images
-              , stLHS           :: Bool          -- true if document has literate haskell code
-              , stBook          :: Bool          -- true if document uses book or memoir class
-              , stCsquotes      :: Bool          -- true if document uses csquotes
-              , stHighlighting  :: Bool          -- true if document has highlighted code
-              , stIncremental   :: Bool          -- true if beamer lists should be displayed bit by bit
-              , stInternalLinks :: [String]      -- list of internal link targets
-              , stBeamer        :: Bool          -- produce beamer
-              , stEmptyLine     :: Bool          -- true if no content on line
-              }
-
-startingState :: WriterOptions -> WriterState
-startingState options = WriterState {
-                  stInNote = False
-                , stInQuote = False
-                , stInMinipage = False
-                , stInHeading = False
-                , stInItem = False
-                , stNotes = []
-                , stOLLevel = 1
-                , stOptions = options
-                , stVerbInNote = False
-                , stTable = False
-                , stStrikeout = False
-                , stUrl = False
-                , stGraphics = False
-                , stLHS = False
-                , stBook = case writerTopLevelDivision options of
-                                TopLevelPart    -> True
-                                TopLevelChapter -> True
-                                _               -> False
-                , stCsquotes = False
-                , stHighlighting = False
-                , stIncremental = writerIncremental options
-                , stInternalLinks = []
-                , stBeamer = False
-                , stEmptyLine = True }
-
--- | Convert Pandoc to LaTeX.
-writeLaTeX :: PandocMonad m => WriterOptions -> Pandoc -> m Text
-writeLaTeX options document =
-  evalStateT (pandocToLaTeX options document) $
-    startingState options
-
--- | Convert Pandoc to LaTeX Beamer.
-writeBeamer :: PandocMonad m => WriterOptions -> Pandoc -> m Text
-writeBeamer options document =
-  evalStateT (pandocToLaTeX options document) $
-    (startingState options){ stBeamer = True }
-
-type LW m = StateT WriterState m
-
-pandocToLaTeX :: PandocMonad m
-              => WriterOptions -> Pandoc -> LW m Text
-pandocToLaTeX options (Pandoc meta blocks) = do
-  -- Strip off final 'references' header if --natbib or --biblatex
-  let method = writerCiteMethod options
-  let blocks' = if method == Biblatex || method == Natbib
-                   then case reverse blocks of
-                             Div (_,["references"],_) _:xs -> reverse xs
-                             _                             -> blocks
-                   else blocks
-  -- see if there are internal links
-  let isInternalLink (Link _ _ ('#':xs,_)) = [xs]
-      isInternalLink _                     = []
-  modify $ \s -> s{ stInternalLinks = query isInternalLink blocks' }
-  let template = fromMaybe "" $ writerTemplate options
-  -- set stBook depending on documentclass
-  let colwidth = if writerWrapText options == WrapAuto
-                    then Just $ writerColumns options
-                    else Nothing
-  let render' :: Doc -> Text
-      render' = render colwidth
-  metadata <- metaToJSON options
-              (fmap render' . blockListToLaTeX)
-              (fmap render' . inlineListToLaTeX)
-              meta
-  let bookClasses = ["memoir","book","report","scrreprt","scrbook"]
-  let documentClass = case P.parse pDocumentClass "template" template of
-                              Right r -> r
-                              Left _  -> ""
-  case lookup "documentclass" (writerVariables options) `mplus`
-        fmap stringify (lookupMeta "documentclass" meta) of
-         Just x  | x `elem` bookClasses -> modify $ \s -> s{stBook = True}
-                 | otherwise            -> return ()
-         Nothing | documentClass `elem` bookClasses
-                                        -> modify $ \s -> s{stBook = True}
-                 | otherwise               -> return ()
-  -- check for \usepackage...{csquotes}; if present, we'll use
-  -- \enquote{...} for smart quotes:
-  let headerIncludesField :: FromJSON a => Maybe a
-      headerIncludesField = getField "header-includes" metadata
-  let headerIncludes = fromMaybe [] $ mplus
-                       (fmap return headerIncludesField)
-                       headerIncludesField
-  when (any (isInfixOf "{csquotes}") (template : headerIncludes)) $
-    modify $ \s -> s{stCsquotes = True}
-  let (blocks'', lastHeader) = if writerCiteMethod options == Citeproc then
-                                 (blocks', [])
-                               else case last blocks' of
-                                 Header 1 _ il -> (init blocks', il)
-                                 _             -> (blocks', [])
-  beamer <- gets stBeamer
-  blocks''' <- if beamer
-                  then toSlides blocks''
-                  else return blocks''
-  body <- mapM (elementToLaTeX options) $ hierarchicalize blocks'''
-  (biblioTitle :: Text) <- render' <$> inlineListToLaTeX lastHeader
-  let main = render' $ vsep body
-  st <- get
-  titleMeta <- stringToLaTeX TextString $ stringify $ docTitle meta
-  authorsMeta <- mapM (stringToLaTeX TextString . stringify) $ docAuthors meta
-  docLangs <- catMaybes <$>
-      mapM (toLang . Just) (ordNub (query (extract "lang") blocks))
-  let hasStringValue x = isJust (getField x metadata :: Maybe String)
-  let geometryFromMargins = intercalate [','] $ mapMaybe (\(x,y) ->
-                                ((x ++ "=") ++) <$> getField y metadata)
-                              [("lmargin","margin-left")
-                              ,("rmargin","margin-right")
-                              ,("tmargin","margin-top")
-                              ,("bmargin","margin-bottom")
-                              ]
-  let toPolyObj lang = object [ "name"    .= T.pack name
-                              , "options" .= T.pack opts ]
-        where
-          (name, opts) = toPolyglossia lang
-  mblang <- toLang $ case getLang options meta of
-                          Just l -> Just l
-                          Nothing | null docLangs -> Nothing
-                                  | otherwise     -> Just "en"
-  -- we need a default here since lang is used in template conditionals
-
-  let dirs = query (extract "dir") blocks
-
-  let context  =  defField "toc" (writerTableOfContents options) $
-                  defField "toc-depth" (show (writerTOCDepth options -
-                                              if stBook st
-                                                 then 1
-                                                 else 0)) $
-                  defField "body" main $
-                  defField "title-meta" titleMeta $
-                  defField "author-meta" (intercalate "; " authorsMeta) $
-                  defField "documentclass" (if beamer
-                                               then ("beamer" :: String)
-                                               else if stBook st
-                                                    then "book"
-                                                    else "article") $
-                  defField "verbatim-in-note" (stVerbInNote st) $
-                  defField "tables" (stTable st) $
-                  defField "strikeout" (stStrikeout st) $
-                  defField "url" (stUrl st) $
-                  defField "numbersections" (writerNumberSections options) $
-                  defField "lhs" (stLHS st) $
-                  defField "graphics" (stGraphics st) $
-                  defField "book-class" (stBook st) $
-                  defField "listings" (writerListings options || stLHS st) $
-                  defField "beamer" beamer $
-                  (if stHighlighting st
-                      then case writerHighlightStyle options of
-                                Just sty ->
-                                   defField "highlighting-macros"
-                                      (styleToLaTeX sty)
-                                Nothing -> id
-                      else id) $
-                  (case writerCiteMethod options of
-                         Natbib   -> defField "biblio-title" biblioTitle .
-                                     defField "natbib" True
-                         Biblatex -> defField "biblio-title" biblioTitle .
-                                     defField "biblatex" True
-                         _        -> id) $
-                  defField "colorlinks" (any hasStringValue
-                           ["citecolor", "urlcolor", "linkcolor", "toccolor"]) $
-                  (if null dirs
-                     then id
-                     else defField "dir" ("ltr" :: String)) $
-                  defField "section-titles" True $
-                  defField "geometry" geometryFromMargins $
-                  (case getField "papersize" metadata of
-                        -- uppercase a4, a5, etc.
-                        Just (('A':d:ds) :: String)
-                          | all isDigit (d:ds) -> resetField "papersize"
-                                                    (('a':d:ds) :: String)
-                        _                     -> id)
-                  metadata
-  let context' =
-          -- note: lang is used in some conditionals in the template,
-          -- so we need to set it if we have any babel/polyglossia:
-          maybe id (defField "lang" . renderLang) mblang
-        $ maybe id (defField "babel-lang" . toBabel) mblang
-        $ defField "babel-otherlangs" (map toBabel docLangs)
-        $ defField "babel-newcommands" (concatMap (\(poly, babel) ->
-            -- \textspanish and \textgalician are already used by babel
-            -- save them as \oritext... and let babel use that
-            if poly `elem` ["spanish", "galician"]
-               then "\\let\\oritext" ++ poly ++ "\\text" ++ poly ++ "\n" ++
-                    "\\AddBabelHook{" ++ poly ++ "}{beforeextras}" ++
-                      "{\\renewcommand{\\text" ++ poly ++ "}{\\oritext"
-                      ++ poly ++ "}}\n" ++
-                    "\\AddBabelHook{" ++ poly ++ "}{afterextras}" ++
-                      "{\\renewcommand{\\text" ++ poly ++ "}[2][]{\\foreignlanguage{"
-                      ++ poly ++ "}{##2}}}\n"
-               else (if poly == "latin" -- see #4161
-                        then "\\providecommand{\\textlatin}{}\n\\renewcommand"
-                        else "\\newcommand") ++ "{\\text" ++ poly ++
-                    "}[2][]{\\foreignlanguage{" ++ babel ++ "}{#2}}\n" ++
-                    "\\newenvironment{" ++ poly ++
-                    "}[2][]{\\begin{otherlanguage}{" ++
-                    babel ++ "}}{\\end{otherlanguage}}\n"
-            )
-            -- eliminate duplicates that have same polyglossia name
-            $ nubBy (\a b -> fst a == fst b)
-            -- find polyglossia and babel names of languages used in the document
-            $ map (\l -> (fst $ toPolyglossia l, toBabel l)) docLangs
-          )
-        $ maybe id (defField "polyglossia-lang" . toPolyObj) mblang
-        $ defField "polyglossia-otherlangs" (map toPolyObj docLangs)
-        $
-                  defField "latex-dir-rtl"
-           (getField "dir" context == Just ("rtl" :: String)) context
-  case writerTemplate options of
-       Nothing  -> return main
-       Just tpl -> renderTemplate' tpl context'
-
--- | Convert Elements to LaTeX
-elementToLaTeX :: PandocMonad m => WriterOptions -> Element -> LW m Doc
-elementToLaTeX _ (Blk block) = blockToLaTeX block
-elementToLaTeX opts (Sec level _ (id',classes,_) title' elements) = do
-  modify $ \s -> s{stInHeading = True}
-  header' <- sectionHeader ("unnumbered" `elem` classes) id' level title'
-  modify $ \s -> s{stInHeading = False}
-  innerContents <- mapM (elementToLaTeX opts) elements
-  return $ vsep (header' : innerContents)
-
-data StringContext = TextString
-                   | URLString
-                   | CodeString
-                   deriving (Eq)
-
--- escape things as needed for LaTeX
-stringToLaTeX :: PandocMonad m => StringContext -> String -> LW m String
-stringToLaTeX  _     []     = return ""
-stringToLaTeX  ctx (x:xs) = do
-  opts <- gets stOptions
-  rest <- stringToLaTeX ctx xs
-  let ligatures = isEnabled Ext_smart opts && ctx == TextString
-  let isUrl = ctx == URLString
-  return $
-    case x of
-       '{' -> "\\{" ++ rest
-       '}' -> "\\}" ++ rest
-       '`' | ctx == CodeString -> "\\textasciigrave{}" ++ rest
-       '$' | not isUrl -> "\\$" ++ rest
-       '%' -> "\\%" ++ rest
-       '&' -> "\\&" ++ rest
-       '_' | not isUrl -> "\\_" ++ rest
-       '#' -> "\\#" ++ rest
-       '-' | not isUrl -> case xs of
-                   -- prevent adjacent hyphens from forming ligatures
-                   ('-':_) -> "-\\/" ++ rest
-                   _       -> '-' : rest
-       '~' | not isUrl -> "\\textasciitilde{}" ++ rest
-       '^' -> "\\^{}" ++ rest
-       '\\'| isUrl     -> '/' : rest  -- NB. / works as path sep even on Windows
-           | otherwise -> "\\textbackslash{}" ++ rest
-       '|' | not isUrl -> "\\textbar{}" ++ rest
-       '<' -> "\\textless{}" ++ rest
-       '>' -> "\\textgreater{}" ++ rest
-       '[' -> "{[}" ++ rest  -- to avoid interpretation as
-       ']' -> "{]}" ++ rest  -- optional arguments
-       '\'' | ctx == CodeString -> "\\textquotesingle{}" ++ rest
-       '\160' -> "~" ++ rest
-       '\x202F' -> "\\," ++ rest
-       '\x2026' -> "\\ldots{}" ++ rest
-       '\x2018' | ligatures -> "`" ++ rest
-       '\x2019' | ligatures -> "'" ++ rest
-       '\x201C' | ligatures -> "``" ++ rest
-       '\x201D' | ligatures -> "''" ++ rest
-       '\x2014' | ligatures -> "---" ++ rest
-       '\x2013' | ligatures -> "--" ++ rest
-       _        -> x : rest
-
-toLabel :: PandocMonad m => String -> LW m String
-toLabel z = go `fmap` stringToLaTeX URLString z
- where go [] = ""
-       go (x:xs)
-         | (isLetter x || isDigit x) && isAscii x = x:go xs
-         | x `elem` ("_-+=:;." :: String) = x:go xs
-         | otherwise = "ux" ++ printf "%x" (ord x) ++ go xs
-
--- | Puts contents into LaTeX command.
-inCmd :: String -> Doc -> Doc
-inCmd cmd contents = char '\\' <> text cmd <> braces contents
-
-toSlides :: PandocMonad m => [Block] -> LW m [Block]
-toSlides bs = do
-  opts <- gets stOptions
-  let slideLevel = fromMaybe (getSlideLevel bs) $ writerSlideLevel opts
-  let bs' = prepSlides slideLevel bs
-  concat `fmap` mapM (elementToBeamer slideLevel) (hierarchicalize bs')
-
-elementToBeamer :: PandocMonad m => Int -> Element -> LW m [Block]
-elementToBeamer _slideLevel (Blk (Div attr bs)) = do
-  -- make sure we support "blocks" inside divs
-  bs' <- concat `fmap` mapM (elementToBeamer 0) (hierarchicalize bs)
-  return [Div attr bs']
-elementToBeamer _slideLevel (Blk b) = return [b]
-elementToBeamer slideLevel  (Sec lvl _num (ident,classes,kvs) tit elts)
-  | lvl >  slideLevel = do
-      bs <- concat `fmap` mapM (elementToBeamer slideLevel) elts
-      return $ Para ( RawInline "latex" "\\begin{block}{"
-                    : tit ++ [RawInline "latex" "}"] )
-             : bs ++ [RawBlock "latex" "\\end{block}"]
-  | lvl <  slideLevel = do
-      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
-      let hasCodeBlock (CodeBlock _ _) = [True]
-          hasCodeBlock _               = []
-      let hasCode (Code _ _) = [True]
-          hasCode _          = []
-      let fragile = "fragile" `elem` classes ||
-                    not (null $ query hasCodeBlock elts ++ query hasCode elts)
-      let frameoptions = ["allowdisplaybreaks", "allowframebreaks", "fragile",
-                          "b", "c", "t", "environment",
-                          "label", "plain", "shrink", "standout"]
-      let optionslist = ["fragile" | fragile && lookup "fragile" kvs == Nothing] ++
-                        [k | k <- classes, k `elem` frameoptions] ++
-                        [k ++ "=" ++ v | (k,v) <- kvs, k `elem` frameoptions]
-      let options = if null optionslist
-                       then ""
-                       else "[" ++ intercalate "," optionslist ++ "]"
-      let latex = RawInline (Format "latex")
-      slideTitle <-
-            if tit == [Str "\0"] -- marker for hrule
-               then return []
-               else
-                 if null ident
-                    then return $ latex "{" : tit ++ [latex "}"]
-                    else do
-                      ref <- toLabel ident
-                      return $ latex ("{%\n\\protect\\hypertarget{" ++
-                                ref ++ "}{%\n") : tit ++ [latex "}}"]
-      let slideStart = Para $
-              RawInline "latex" ("\\begin{frame}" ++ options) : slideTitle
-      let slideEnd = RawBlock "latex" "\\end{frame}"
-      -- now carve up slide into blocks if there are sections inside
-      bs <- concat `fmap` mapM (elementToBeamer slideLevel) elts
-      return $ slideStart : bs ++ [slideEnd]
-
-isListBlock :: Block -> Bool
-isListBlock (BulletList _)     = True
-isListBlock (OrderedList _ _)  = True
-isListBlock (DefinitionList _) = True
-isListBlock _                  = False
-
-isLineBreakOrSpace :: Inline -> Bool
-isLineBreakOrSpace LineBreak = True
-isLineBreakOrSpace SoftBreak = True
-isLineBreakOrSpace Space     = True
-isLineBreakOrSpace _         = False
-
--- | Convert Pandoc block element to LaTeX.
-blockToLaTeX :: PandocMonad m
-             => Block     -- ^ Block to convert
-             -> LW m Doc
-blockToLaTeX Null = return empty
-blockToLaTeX (Div (identifier,classes,kvs) bs) = do
-  beamer <- gets stBeamer
-  linkAnchor' <- hypertarget True identifier empty
-  -- see #2704 for the motivation for adding \leavevmode:
-  let linkAnchor =
-       case bs of
-            Para _ : _
-              | not (isEmpty linkAnchor')
-              -> "\\leavevmode" <> linkAnchor' <> "%"
-            _ -> linkAnchor'
-  let align dir txt = inCmd "begin" dir $$ txt $$ inCmd "end" dir
-  lang <- toLang $ lookup "lang" kvs
-  let wrapColumns = if "columns" `elem` classes
-                       then \contents ->
-                          inCmd "begin" "columns" <> brackets "T"
-                              $$ contents
-                              $$ inCmd "end" "columns"
-                       else id
-      wrapColumn  = if "column" `elem` classes
-                       then \contents ->
-                          let fromPct xs =
-                                case reverse xs of
-                                     '%':ds -> '0':'.': reverse ds
-                                     _      -> xs
-                              w = maybe "0.48" fromPct (lookup "width" kvs)
-                          in  inCmd "begin" "column" <>
-                              braces (text w <> "\\textwidth")
-                              $$ contents
-                              $$ inCmd "end" "column"
-                       else id
-      wrapDir = case lookup "dir" kvs of
-                  Just "rtl" -> align "RTL"
-                  Just "ltr" -> align "LTR"
-                  _          -> id
-      wrapLang txt = case lang of
-                       Just lng -> let (l, o) = toPolyglossiaEnv lng
-                                       ops = if null o
-                                                then ""
-                                                else brackets $ text o
-                                   in  inCmd "begin" (text l) <> ops
-                                       $$ blankline <> txt <> blankline
-                                       $$ inCmd "end" (text l)
-                       Nothing  -> txt
-      wrapNotes txt = if beamer && "notes" `elem` classes
-                          then "\\note" <> braces txt -- speaker notes
-                          else linkAnchor $$ txt
-  (wrapColumns . wrapColumn . wrapDir . wrapLang . wrapNotes)
-    <$> blockListToLaTeX bs
-blockToLaTeX (Plain lst) =
-  inlineListToLaTeX $ dropWhile isLineBreakOrSpace lst
--- title beginning with fig: indicates that the image is a figure
-blockToLaTeX (Para [Image attr@(ident, _, _) txt (src,'f':'i':'g':':':tit)]) = do
-  inNote <- gets stInNote
-  inMinipage <- gets stInMinipage
-  modify $ \st -> st{ stInMinipage = True, stNotes = [] }
-  capt <- inlineListToLaTeX txt
-  notes <- gets stNotes
-  modify $ \st -> st{ stInMinipage = False, stNotes = [] }
-
-  -- We can't have footnotes in the list of figures, so remove them:
-  captForLof <- if null notes
-                   then return empty
-                   else brackets <$> inlineListToLaTeX (walk deNote txt)
-  img <- inlineToLaTeX (Image attr txt (src,tit))
-  let footnotes = notesToLaTeX notes
-  lab <- labelFor ident
-  let caption = "\\caption" <> captForLof <> braces capt <> lab
-  let figure = cr <> "\\begin{figure}" $$ "\\centering" $$ img $$
-              caption $$ "\\end{figure}" <> cr
-  figure' <- hypertarget True ident figure
-  return $ if inNote || inMinipage
-              -- can't have figures in notes or minipage (here, table cell)
-              -- http://www.tex.ac.uk/FAQ-ouparmd.html
-              then "\\begin{center}" $$ img $+$ capt $$ "\\end{center}"
-              else figure' $$ footnotes
--- . . . indicates pause in beamer slides
-blockToLaTeX (Para [Str ".",Space,Str ".",Space,Str "."]) = do
-  beamer <- gets stBeamer
-  if beamer
-     then blockToLaTeX (RawBlock "latex" "\\pause")
-     else inlineListToLaTeX [Str ".",Space,Str ".",Space,Str "."]
-blockToLaTeX (Para lst) =
-  inlineListToLaTeX $ dropWhile isLineBreakOrSpace lst
-blockToLaTeX (LineBlock lns) =
-  blockToLaTeX $ linesToPara lns
-blockToLaTeX (BlockQuote lst) = do
-  beamer <- gets stBeamer
-  case lst of
-       [b] | beamer && isListBlock b -> do
-         oldIncremental <- gets stIncremental
-         modify $ \s -> s{ stIncremental = not oldIncremental }
-         result <- blockToLaTeX b
-         modify $ \s -> s{ stIncremental = oldIncremental }
-         return result
-       _ -> do
-         oldInQuote <- gets stInQuote
-         modify (\s -> s{stInQuote = True})
-         contents <- blockListToLaTeX lst
-         modify (\s -> s{stInQuote = oldInQuote})
-         return $ "\\begin{quote}" $$ contents $$ "\\end{quote}"
-blockToLaTeX (CodeBlock (identifier,classes,keyvalAttr) str) = do
-  opts <- gets stOptions
-  lab <- labelFor identifier
-  linkAnchor' <- hypertarget True identifier lab
-  let linkAnchor = if isEmpty linkAnchor'
-                      then empty
-                      else linkAnchor' <> "%"
-  let lhsCodeBlock = do
-        modify $ \s -> s{ stLHS = True }
-        return $ flush (linkAnchor $$ "\\begin{code}" $$ text str $$
-                            "\\end{code}") $$ cr
-  let rawCodeBlock = do
-        st <- get
-        env <- if stInNote st
-                  then modify (\s -> s{ stVerbInNote = True }) >>
-                       return "Verbatim"
-                  else return "verbatim"
-        return $ flush (linkAnchor $$ text ("\\begin{" ++ env ++ "}") $$
-                 text str $$ text ("\\end{" ++ env ++ "}")) <> cr
-  let listingsCodeBlock = do
-        st <- get
-        ref <- toLabel identifier
-        let params = if writerListings (stOptions st)
-                     then (case getListingsLanguage classes of
-                                Just l  -> [ "language=" ++ mbBraced l ]
-                                Nothing -> []) ++
-                          [ "numbers=left" | "numberLines" `elem` classes
-                             || "number" `elem` classes
-                             || "number-lines" `elem` classes ] ++
-                          [ (if key == "startFrom"
-                                then "firstnumber"
-                                else key) ++ "=" ++ mbBraced attr |
-                                (key,attr) <- keyvalAttr ] ++
-                          (if identifier == ""
-                                then []
-                                else [ "label=" ++ ref ])
-
-                     else []
-            printParams
-                | null params = empty
-                | otherwise   = brackets $ hcat (intersperse ", "
-                      (map text params))
-        return $ flush ("\\begin{lstlisting}" <> printParams $$ text str $$
-                 "\\end{lstlisting}") $$ cr
-  let highlightedCodeBlock =
-        case highlight (writerSyntaxMap opts)
-                 formatLaTeXBlock ("",classes,keyvalAttr) str of
-               Left msg -> do
-                 unless (null msg) $
-                   report $ CouldNotHighlight msg
-                 rawCodeBlock
-               Right h -> do
-                  st <- get
-                  when (stInNote st) $ modify (\s -> s{ stVerbInNote = True })
-                  modify (\s -> s{ stHighlighting = True })
-                  return (flush $ linkAnchor $$ text (T.unpack h))
-  case () of
-     _ | isEnabled Ext_literate_haskell opts && "haskell" `elem` classes &&
-         "literate" `elem` classes           -> lhsCodeBlock
-       | writerListings opts                 -> listingsCodeBlock
-       | not (null classes) && isJust (writerHighlightStyle opts)
-                                             -> highlightedCodeBlock
-       | otherwise                           -> rawCodeBlock
-blockToLaTeX b@(RawBlock f x)
-  | f == Format "latex" || f == Format "tex"
-                        = return $ text x
-  | otherwise           = do
-      report $ BlockNotRendered b
-      return empty
-blockToLaTeX (BulletList []) = return empty  -- otherwise latex error
-blockToLaTeX (BulletList lst) = do
-  incremental <- gets stIncremental
-  beamer <- gets stBeamer
-  let inc = if beamer && incremental then "[<+->]" else ""
-  items <- mapM listItemToLaTeX lst
-  let spacing = if isTightList lst
-                   then text "\\tightlist"
-                   else empty
-  return $ text ("\\begin{itemize}" ++ inc) $$ spacing $$ vcat items $$
-             "\\end{itemize}"
-blockToLaTeX (OrderedList _ []) = return empty -- otherwise latex error
-blockToLaTeX (OrderedList (start, numstyle, numdelim) lst) = do
-  st <- get
-  let inc = if stIncremental st then "[<+->]" else ""
-  let oldlevel = stOLLevel st
-  put $ st {stOLLevel = oldlevel + 1}
-  items <- mapM listItemToLaTeX lst
-  modify (\s -> s {stOLLevel = oldlevel})
-  let beamer = stBeamer st
-  let tostyle x = case numstyle of
-                       Decimal      -> "\\arabic" <> braces x
-                       UpperRoman   -> "\\Roman" <> braces x
-                       LowerRoman   -> "\\roman" <> braces x
-                       UpperAlpha   -> "\\Alph" <> braces x
-                       LowerAlpha   -> "\\alph" <> braces x
-                       Example      -> "\\arabic" <> braces x
-                       DefaultStyle -> "\\arabic" <> braces x
-  let todelim x = case numdelim of
-                       OneParen  -> x <> ")"
-                       TwoParens -> parens x
-                       Period    -> x <> "."
-                       _         -> x <> "."
-  let exemplar = case numstyle of
-                       Decimal      -> "1"
-                       UpperRoman   -> "I"
-                       LowerRoman   -> "i"
-                       UpperAlpha   -> "A"
-                       LowerAlpha   -> "a"
-                       Example      -> "1"
-                       DefaultStyle -> "1"
-  let enum = text $ "enum" ++ map toLower (toRomanNumeral oldlevel)
-  let stylecommand
-        | numstyle == DefaultStyle && numdelim == DefaultDelim = empty
-        | beamer = brackets (todelim exemplar)
-        | otherwise = "\\def" <> "\\label" <> enum <>
-          braces (todelim $ tostyle enum)
-  let resetcounter = if start == 1 || oldlevel > 4
-                        then empty
-                        else "\\setcounter" <> braces enum <>
-                              braces (text $ show $ start - 1)
-  let spacing = if isTightList lst
-                   then text "\\tightlist"
-                   else empty
-  return $ text ("\\begin{enumerate}" ++ inc)
-         $$ stylecommand
-         $$ resetcounter
-         $$ spacing
-         $$ vcat items
-         $$ "\\end{enumerate}"
-blockToLaTeX (DefinitionList []) = return empty
-blockToLaTeX (DefinitionList lst) = do
-  incremental <- gets stIncremental
-  let inc = if incremental then "[<+->]" else ""
-  items <- mapM defListItemToLaTeX lst
-  let spacing = if all isTightList (map snd lst)
-                   then text "\\tightlist"
-                   else empty
-  return $ text ("\\begin{description}" ++ inc) $$ spacing $$ vcat items $$
-               "\\end{description}"
-blockToLaTeX HorizontalRule =
-            return
-  "\\begin{center}\\rule{0.5\\linewidth}{\\linethickness}\\end{center}"
-blockToLaTeX (Header level (id',classes,_) lst) = do
-  modify $ \s -> s{stInHeading = True}
-  hdr <- sectionHeader ("unnumbered" `elem` classes) id' level lst
-  modify $ \s -> s{stInHeading = False}
-  return hdr
-blockToLaTeX (Table caption aligns widths heads rows) = do
-  let toHeaders hs = do contents <- tableRowToLaTeX True aligns widths hs
-                        return ("\\toprule" $$ contents $$ "\\midrule")
-  let removeNote (Note _) = Span ("", [], []) []
-      removeNote x        = x
-  captionText <- inlineListToLaTeX caption
-  firsthead <- if isEmpty captionText || all null heads
-                  then return empty
-                  else ($$ text "\\endfirsthead") <$> toHeaders heads
-  head' <- if all null heads
-              then return "\\toprule"
-              -- avoid duplicate notes in head and firsthead:
-              else toHeaders (if isEmpty firsthead
-                                 then heads
-                                 else walk removeNote heads)
-  let capt = if isEmpty captionText
-                then empty
-                else text "\\caption" <>
-                      braces captionText <> "\\tabularnewline"
-  rows' <- mapM (tableRowToLaTeX False aligns widths) rows
-  let colDescriptors = text $ concatMap toColDescriptor aligns
-  modify $ \s -> s{ stTable = True }
-  return $ "\\begin{longtable}[]" <>
-              braces ("@{}" <> colDescriptors <> "@{}")
-              -- the @{} removes extra space at beginning and end
-         $$ capt
-         $$ firsthead
-         $$ head'
-         $$ "\\endhead"
-         $$ vcat rows'
-         $$ "\\bottomrule"
-         $$ "\\end{longtable}"
-
-toColDescriptor :: Alignment -> String
-toColDescriptor align =
-  case align of
-         AlignLeft    -> "l"
-         AlignRight   -> "r"
-         AlignCenter  -> "c"
-         AlignDefault -> "l"
-
-blockListToLaTeX :: PandocMonad m => [Block] -> LW m Doc
-blockListToLaTeX lst =
-  vsep `fmap` mapM (\b -> setEmptyLine True >> blockToLaTeX b) lst
-
-tableRowToLaTeX :: PandocMonad m
-                => Bool
-                -> [Alignment]
-                -> [Double]
-                -> [[Block]]
-                -> LW m Doc
-tableRowToLaTeX header aligns widths cols = do
-  -- scale factor compensates for extra space between columns
-  -- so the whole table isn't larger than columnwidth
-  let scaleFactor = 0.97 ** fromIntegral (length aligns)
-  let isSimple [Plain _] = True
-      isSimple [Para  _] = True
-      isSimple []        = True
-      isSimple _         = False
-  -- simple tables have to have simple cells:
-  let widths' = if not (all isSimple cols)
-                   then replicate (length aligns)
-                          (0.97 / fromIntegral (length aligns))
-                   else map (scaleFactor *) widths
-  cells <- mapM (tableCellToLaTeX header) $ zip3 widths' aligns cols
-  return $ hsep (intersperse "&" cells) <> "\\tabularnewline"
-
--- For simple latex tables (without minipages or parboxes),
--- we need to go to some lengths to get line breaks working:
--- as LineBreak bs = \vtop{\hbox{\strut as}\hbox{\strut bs}}.
-fixLineBreaks :: Block -> Block
-fixLineBreaks (Para ils)  = Para $ fixLineBreaks' ils
-fixLineBreaks (Plain ils) = Plain $ fixLineBreaks' ils
-fixLineBreaks x           = x
-
-fixLineBreaks' :: [Inline] -> [Inline]
-fixLineBreaks' ils = case splitBy (== LineBreak) ils of
-                       []     -> []
-                       [xs]   -> xs
-                       chunks -> RawInline "tex" "\\vtop{" :
-                                 concatMap tohbox chunks ++
-                                 [RawInline "tex" "}"]
-  where tohbox ys = RawInline "tex" "\\hbox{\\strut " : ys ++
-                    [RawInline "tex" "}"]
-
--- We also change display math to inline math, since display
--- math breaks in simple tables.
-displayMathToInline :: Inline -> Inline
-displayMathToInline (Math DisplayMath x) = Math InlineMath x
-displayMathToInline x                    = x
-
-tableCellToLaTeX :: PandocMonad m => Bool -> (Double, Alignment, [Block])
-                 -> LW m Doc
-tableCellToLaTeX _      (0,     _,     blocks) =
-  blockListToLaTeX $ walk fixLineBreaks $ walk displayMathToInline blocks
-tableCellToLaTeX header (width, align, blocks) = do
-  modify $ \st -> st{ stInMinipage = True, stNotes = [] }
-  cellContents <- blockListToLaTeX blocks
-  notes <- gets stNotes
-  modify $ \st -> st{ stInMinipage = False, stNotes = [] }
-  let valign = text $ if header then "[b]" else "[t]"
-  let halign = case align of
-               AlignLeft    -> "\\raggedright"
-               AlignRight   -> "\\raggedleft"
-               AlignCenter  -> "\\centering"
-               AlignDefault -> "\\raggedright"
-  return $ ("\\begin{minipage}" <> valign <>
-            braces (text (printf "%.2f\\columnwidth" width)) <>
-            (halign <> cr <> cellContents <> "\\strut" <> cr) <>
-            "\\end{minipage}") $$
-            notesToLaTeX notes
-
-notesToLaTeX :: [Doc] -> Doc
-notesToLaTeX [] = empty
-notesToLaTeX ns = (case length ns of
-                              n | n > 1 -> "\\addtocounter" <>
-                                           braces "footnote" <>
-                                           braces (text $ show $ 1 - n)
-                                | otherwise -> empty)
-                   $$
-                   vcat (intersperse
-                     ("\\addtocounter" <> braces "footnote" <> braces "1")
-                     $ map (\x -> "\\footnotetext" <> braces x)
-                     $ reverse ns)
-
-listItemToLaTeX :: PandocMonad m => [Block] -> LW m Doc
-listItemToLaTeX lst
-  -- we need to put some text before a header if it's the first
-  -- element in an item. This will look ugly in LaTeX regardless, but
-  -- this will keep the typesetter from throwing an error.
-  | (Header _ _ _ :_) <- lst =
-    blockListToLaTeX lst >>= return . (text "\\item ~" $$) . nest 2
-  | otherwise = blockListToLaTeX lst >>= return .  (text "\\item" $$) .
-                      nest 2
-
-defListItemToLaTeX :: PandocMonad m => ([Inline], [[Block]]) -> LW m Doc
-defListItemToLaTeX (term, defs) = do
-    -- needed to turn off 'listings' because it breaks inside \item[...]:
-    modify $ \s -> s{stInItem = True}
-    term' <- inlineListToLaTeX term
-    modify $ \s -> s{stInItem = False}
-    -- put braces around term if it contains an internal link,
-    -- since otherwise we get bad bracket interactions: \item[\hyperref[..]
-    let isInternalLink (Link _ _ ('#':_,_)) = True
-        isInternalLink _                    = False
-    let term'' = if any isInternalLink term
-                    then braces term'
-                    else term'
-    def'  <- liftM vsep $ mapM blockListToLaTeX defs
-    return $ case defs of
-     ((Header{} : _) : _) ->
-       "\\item" <> brackets term'' <> " ~ " $$ def'
-     _                          ->
-       "\\item" <> brackets term'' $$ def'
-
--- | Craft the section header, inserting the secton reference, if supplied.
-sectionHeader :: PandocMonad m
-              => Bool    -- True for unnumbered
-              -> [Char]
-              -> Int
-              -> [Inline]
-              -> LW m Doc
-sectionHeader unnumbered ident level lst = do
-  txt <- inlineListToLaTeX lst
-  plain <- stringToLaTeX TextString $ concatMap stringify lst
-  let removeInvalidInline (Note _)             = []
-      removeInvalidInline (Span (id', _, _) _) | not (null id') = []
-      removeInvalidInline (Image{})            = []
-      removeInvalidInline x                    = [x]
-  let lstNoNotes = foldr (mappend . (\x -> walkM removeInvalidInline x)) mempty lst
-  txtNoNotes <- inlineListToLaTeX lstNoNotes
-  -- footnotes in sections don't work (except for starred variants)
-  -- unless you specify an optional argument:
-  -- \section[mysec]{mysec\footnote{blah}}
-  optional <- if unnumbered || lstNoNotes == lst || null lstNoNotes
-                 then return empty
-                 else
-                   return $ brackets txtNoNotes
-  let contents = if render Nothing txt == plain
-                    then braces txt
-                    else braces (text "\\texorpdfstring"
-                         <> braces txt
-                         <> braces (text plain))
-  book <- gets stBook
-  opts <- gets stOptions
-  let topLevelDivision = if book && writerTopLevelDivision opts == TopLevelDefault
-                         then TopLevelChapter
-                         else writerTopLevelDivision opts
-  beamer <- gets stBeamer
-  let level' = if beamer &&
-                  topLevelDivision `elem` [TopLevelPart, TopLevelChapter]
-               -- beamer has parts but no chapters
-               then if level == 1 then -1 else level - 1
-               else case topLevelDivision of
-                      TopLevelPart    -> level - 2
-                      TopLevelChapter -> level - 1
-                      TopLevelSection -> level
-                      TopLevelDefault -> level
-  let sectionType = case level' of
-                          -1 -> "part"
-                          0  -> "chapter"
-                          1  -> "section"
-                          2  -> "subsection"
-                          3  -> "subsubsection"
-                          4  -> "paragraph"
-                          5  -> "subparagraph"
-                          _  -> ""
-  inQuote <- gets stInQuote
-  let prefix = if inQuote && level' >= 4
-                  then text "\\mbox{}%"
-                  -- needed for \paragraph, \subparagraph in quote environment
-                  -- see http://tex.stackexchange.com/questions/169830/
-                  else empty
-  lab <- labelFor ident
-  let star = if unnumbered && level' < 4 then text "*" else empty
-  let stuffing = star <> optional <> contents
-  stuffing' <- hypertarget True ident $
-                  text ('\\':sectionType) <> stuffing <> lab
-  return $ if level' > 5
-              then txt
-              else prefix $$ stuffing'
-                   $$ if unnumbered
-                         then "\\addcontentsline{toc}" <>
-                                braces (text sectionType) <>
-                                braces txtNoNotes
-                         else empty
-
-hypertarget :: PandocMonad m => Bool -> String -> Doc -> LW m Doc
-hypertarget _ "" x    = return x
-hypertarget addnewline ident x = do
-  ref <- text `fmap` toLabel ident
-  return $ text "\\hypertarget"
-              <> braces ref
-              <> braces ((if addnewline && not (isEmpty x)
-                             then ("%" <> cr)
-                             else empty) <> x)
-
-labelFor :: PandocMonad m => String -> LW m Doc
-labelFor ""    = return empty
-labelFor ident = do
-  ref <- text `fmap` toLabel ident
-  return $ text "\\label" <> braces ref
-
--- | Convert list of inline elements to LaTeX.
-inlineListToLaTeX :: PandocMonad m
-                  => [Inline]  -- ^ Inlines to convert
-                  -> LW m Doc
-inlineListToLaTeX lst =
-  mapM inlineToLaTeX (fixLineInitialSpaces lst)
-    >>= return . hcat
-    -- nonbreaking spaces (~) in LaTeX don't work after line breaks,
-    -- so we turn nbsps after hard breaks to \hspace commands.
-    -- this is mostly used in verse.
- where fixLineInitialSpaces [] = []
-       fixLineInitialSpaces (LineBreak : Str s@('\160':_) : xs) =
-         LineBreak : fixNbsps s ++ fixLineInitialSpaces xs
-       fixLineInitialSpaces (x:xs) = x : fixLineInitialSpaces xs
-       fixNbsps s = let (ys,zs) = span (=='\160') s
-                    in  replicate (length ys) hspace ++ [Str zs]
-       hspace = RawInline "latex" "\\hspace*{0.333em}"
-
-isQuoted :: Inline -> Bool
-isQuoted (Quoted _ _) = True
-isQuoted _            = False
-
--- | Convert inline element to LaTeX
-inlineToLaTeX :: PandocMonad m
-              => Inline    -- ^ Inline to convert
-              -> LW m Doc
-inlineToLaTeX (Span (id',classes,kvs) ils) = do
-  linkAnchor <- hypertarget False id' empty
-  lang <- toLang $ lookup "lang" kvs
-  let cmds = ["textup" | "csl-no-emph" `elem` classes] ++
-             ["textnormal" | "csl-no-strong" `elem` classes ||
-                             "csl-no-smallcaps" `elem` classes] ++
-             ["RL" | ("dir", "rtl") `elem` kvs] ++
-             ["LR" | ("dir", "ltr") `elem` kvs] ++
-             (case lang of
-                Just lng -> let (l, o) = toPolyglossia lng
-                                ops = if null o then "" else ("[" ++ o ++ "]")
-                            in  ["text" ++ l ++ ops]
-                Nothing  -> [])
-  contents <- inlineListToLaTeX ils
-  return $ (if null id'
-               then empty
-               else "\\protect" <> linkAnchor) <>
-           (if null cmds
-               then braces contents
-               else foldr inCmd contents cmds)
-inlineToLaTeX (Emph lst) =
-  inlineListToLaTeX lst >>= return . inCmd "emph"
-inlineToLaTeX (Strong lst) =
-  inlineListToLaTeX lst >>= return . inCmd "textbf"
-inlineToLaTeX (Strikeout lst) = do
-  -- we need to protect VERB in an mbox or we get an error
-  -- see #1294
-  contents <- inlineListToLaTeX $ protectCode lst
-  modify $ \s -> s{ stStrikeout = True }
-  return $ inCmd "sout" contents
-inlineToLaTeX (Superscript lst) =
-  inlineListToLaTeX lst >>= return . inCmd "textsuperscript"
-inlineToLaTeX (Subscript lst) =
-  inlineListToLaTeX lst >>= return . inCmd "textsubscript"
-inlineToLaTeX (SmallCaps lst) =
-  inlineListToLaTeX lst >>= return . inCmd "textsc"
-inlineToLaTeX (Cite cits lst) = do
-  st <- get
-  let opts = stOptions st
-  case writerCiteMethod opts of
-     Natbib   -> citationsToNatbib cits
-     Biblatex -> citationsToBiblatex cits
-     _        -> inlineListToLaTeX lst
-
-inlineToLaTeX (Code (_,classes,_) str) = do
-  opts <- gets stOptions
-  inHeading <- gets stInHeading
-  inItem <- gets stInItem
-  let listingsCode = do
-        let listingsopt = case getListingsLanguage classes of
-                               Just l  -> "[language=" ++ mbBraced l ++ "]"
-                               Nothing -> ""
-        inNote <- gets stInNote
-        when inNote $ modify $ \s -> s{ stVerbInNote = True }
-        let chr = case "!\"&'()*,-./:;?@_" \\ str of
-                       (c:_) -> c
-                       []    -> '!'
-        let str' = escapeStringUsing (backslashEscapes "\\{}%~_") str
-        -- we always put lstinline in a dummy 'passthrough' command
-        -- (defined in the default template) so that we don't have
-        -- to change the way we escape characters depending on whether
-        -- the lstinline is inside another command.  See #1629:
-        return $ text $ "\\passthrough{\\lstinline" ++ listingsopt ++ [chr] ++ str' ++ [chr] ++ "}"
-  let rawCode = liftM (text . (\s -> "\\texttt{" ++ escapeSpaces s ++ "}"))
-                 $ stringToLaTeX CodeString str
-                where escapeSpaces =  concatMap
-                         (\c -> if c == ' ' then "\\ " else [c])
-  let highlightCode =
-        case highlight (writerSyntaxMap opts)
-                 formatLaTeXInline ("",classes,[]) str of
-               Left msg -> do
-                 unless (null msg) $ report $ CouldNotHighlight msg
-                 rawCode
-               Right h -> modify (\st -> st{ stHighlighting = True }) >>
-                          return (text (T.unpack h))
-  case () of
-     _ | writerListings opts  && not (inHeading || inItem) -> listingsCode
-       | isJust (writerHighlightStyle opts) && not (null classes)
-                                                    -> highlightCode
-       | otherwise                                  -> rawCode
-inlineToLaTeX (Quoted qt lst) = do
-  contents <- inlineListToLaTeX lst
-  csquotes <- liftM stCsquotes get
-  opts <- gets stOptions
-  if csquotes
-     then return $ "\\enquote" <> braces contents
-     else do
-       let s1 = if not (null lst) && isQuoted (head lst)
-                   then "\\,"
-                   else empty
-       let s2 = if not (null lst) && isQuoted (last lst)
-                   then "\\,"
-                   else empty
-       let inner = s1 <> contents <> s2
-       return $ case qt of
-                DoubleQuote ->
-                   if isEnabled Ext_smart opts
-                      then text "``" <> inner <> text "''"
-                      else char '\x201C' <> inner <> char '\x201D'
-                SingleQuote ->
-                   if isEnabled Ext_smart opts
-                      then char '`' <> inner <> char '\''
-                      else char '\x2018' <> inner <> char '\x2019'
-inlineToLaTeX (Str str) = do
-  setEmptyLine False
-  liftM text $ stringToLaTeX TextString str
-inlineToLaTeX (Math InlineMath str) = do
-  setEmptyLine False
-  return $ "\\(" <> text str <> "\\)"
-inlineToLaTeX (Math DisplayMath str) = do
-  setEmptyLine False
-  return $ "\\[" <> text str <> "\\]"
-inlineToLaTeX il@(RawInline f str)
-  | f == Format "latex" || f == Format "tex"
-                        = do
-      setEmptyLine False
-      return $ text str
-  | otherwise           = do
-      report $ InlineNotRendered il
-      return empty
-inlineToLaTeX LineBreak = do
-  emptyLine <- gets stEmptyLine
-  setEmptyLine True
-  return $ (if emptyLine then "~" else "") <> "\\\\" <> cr
-inlineToLaTeX SoftBreak = do
-  wrapText <- gets (writerWrapText . stOptions)
-  case wrapText of
-       WrapAuto     -> return space
-       WrapNone     -> return space
-       WrapPreserve -> return cr
-inlineToLaTeX Space = return space
-inlineToLaTeX (Link _ txt ('#':ident, _)) = do
-  contents <- inlineListToLaTeX txt
-  lab <- toLabel ident
-  return $ text "\\protect\\hyperlink" <> braces (text lab) <> braces contents
-inlineToLaTeX (Link _ txt (src, _)) =
-  case txt of
-        [Str x] | escapeURI x == src ->  -- autolink
-             do modify $ \s -> s{ stUrl = True }
-                src' <- stringToLaTeX URLString (escapeURI src)
-                return $ text $ "\\url{" ++ src' ++ "}"
-        [Str x] | Just rest <- stripPrefix "mailto:" src,
-                  escapeURI x == rest -> -- email autolink
-             do modify $ \s -> s{ stUrl = True }
-                src' <- stringToLaTeX URLString (escapeURI src)
-                contents <- inlineListToLaTeX txt
-                return $ "\\href" <> braces (text src') <>
-                   braces ("\\nolinkurl" <> braces contents)
-        _ -> do contents <- inlineListToLaTeX txt
-                src' <- stringToLaTeX URLString (escapeURI src)
-                return $ text ("\\href{" ++ src' ++ "}{") <>
-                         contents <> char '}'
-inlineToLaTeX il@(Image _ _ ('d':'a':'t':'a':':':_, _)) = do
-  report $ InlineNotRendered il
-  return empty
-inlineToLaTeX (Image attr _ (source, _)) = do
-  setEmptyLine False
-  modify $ \s -> s{ stGraphics = True }
-  opts <- gets stOptions
-  let showDim dir = let d = text (show dir) <> "="
-                    in case dimension dir attr of
-                         Just (Pixel a)   ->
-                           [d <> text (showInInch opts (Pixel a)) <> "in"]
-                         Just (Percent a) ->
-                           [d <> text (showFl (a / 100)) <> "\\textwidth"]
-                         Just dim         ->
-                           [d <> text (show dim)]
-                         Nothing          ->
-                           case dir of
-                                Width | isJust (dimension Height attr) ->
-                                  [d <> "\\textwidth"]
-                                Height | isJust (dimension Width attr) ->
-                                  [d <> "\\textheight"]
-                                _ -> []
-      dimList = showDim Width ++ showDim Height
-      dims = if null dimList
-                then empty
-                else brackets $ cat (intersperse "," dimList)
-      source' = if isURI source
-                   then source
-                   else unEscapeString source
-  source'' <- stringToLaTeX URLString source'
-  inHeading <- gets stInHeading
-  return $
-    (if inHeading then "\\protect\\includegraphics" else "\\includegraphics") <>
-    dims <> braces (text source'')
-inlineToLaTeX (Note contents) = do
-  setEmptyLine False
-  inMinipage <- gets stInMinipage
-  modify (\s -> s{stInNote = True})
-  contents' <- blockListToLaTeX contents
-  modify (\s -> s {stInNote = False})
-  let optnl = case reverse contents of
-                   (CodeBlock _ _ : _) -> cr
-                   _                   -> empty
-  let noteContents = nest 2 contents' <> optnl
-  beamer <- gets stBeamer
-  -- in beamer slides, display footnote from current overlay forward
-  let beamerMark = if beamer
-                      then text "<.->"
-                      else empty
-  modify $ \st -> st{ stNotes = noteContents : stNotes st }
-  return $
-    if inMinipage
-       then "\\footnotemark{}"
-       -- note: a \n before } needed when note ends with a Verbatim environment
-       else "\\footnote" <> beamerMark <> braces noteContents
-
-protectCode :: [Inline] -> [Inline]
-protectCode [] = []
-protectCode (x@(Code ("",[],[]) _) : xs) = x : protectCode xs
-protectCode (x@(Code _ _) : xs) = ltx "\\mbox{" : x : ltx "}" : xs
-  where ltx = RawInline (Format "latex")
-protectCode (x : xs) = x : protectCode xs
-
-setEmptyLine :: PandocMonad m => Bool -> LW m ()
-setEmptyLine b = modify $ \st -> st{ stEmptyLine = b }
-
-citationsToNatbib :: PandocMonad m => [Citation] -> LW m Doc
-citationsToNatbib
-            [one]
-  = citeCommand c p s k
-  where
-    Citation { citationId = k
-             , citationPrefix = p
-             , citationSuffix = s
-             , citationMode = m
-             }
-      = one
-    c = case m of
-             AuthorInText   -> "citet"
-             SuppressAuthor -> "citeyearpar"
-             NormalCitation -> "citep"
-
-citationsToNatbib cits
-  | noPrefix (tail cits) && noSuffix (init cits) && ismode NormalCitation cits
-  = citeCommand "citep" p s ks
-  where
-     noPrefix  = all (null . citationPrefix)
-     noSuffix  = all (null . citationSuffix)
-     ismode m  = all ((==) m  . citationMode)
-     p         = citationPrefix  $
-                 head cits
-     s         = citationSuffix  $
-                 last cits
-     ks        = intercalate ", " $ map citationId cits
-
-citationsToNatbib (c:cs) | citationMode c == AuthorInText = do
-     author <- citeCommand "citeauthor" [] [] (citationId c)
-     cits   <- citationsToNatbib (c { citationMode = SuppressAuthor } : cs)
-     return $ author <+> cits
-
-citationsToNatbib cits = do
-  cits' <- mapM convertOne cits
-  return $ text "\\citetext{" <> foldl' combineTwo empty cits' <> text "}"
-  where
-    combineTwo a b | isEmpty a = b
-                   | otherwise = a <> text "; " <> b
-    convertOne Citation { citationId = k
-                        , citationPrefix = p
-                        , citationSuffix = s
-                        , citationMode = m
-                        }
-        = case m of
-               AuthorInText   -> citeCommand "citealt"  p s k
-               SuppressAuthor -> citeCommand "citeyear" p s k
-               NormalCitation -> citeCommand "citealp"  p s k
-
-citeCommand :: PandocMonad m
-            => String -> [Inline] -> [Inline] -> String -> LW m Doc
-citeCommand c p s k = do
-  args <- citeArguments p s k
-  return $ text ("\\" ++ c) <> args
-
-citeArguments :: PandocMonad m
-              => [Inline] -> [Inline] -> String -> LW m Doc
-citeArguments p s k = do
-  let s' = case s of
-        (Str
-                    [x] : r) | isPunctuation x -> dropWhile (== Space) r
-        (Str (x:xs) : r) | isPunctuation x -> Str xs : r
-        _                -> s
-  pdoc <- inlineListToLaTeX p
-  sdoc <- inlineListToLaTeX s'
-  let optargs = case (isEmpty pdoc, isEmpty sdoc) of
-                     (True, True ) -> empty
-                     (True, False) -> brackets sdoc
-                     (_   , _    ) -> brackets pdoc <> brackets sdoc
-  return $ optargs <> braces (text k)
-
-citationsToBiblatex :: PandocMonad m => [Citation] -> LW m Doc
-citationsToBiblatex
-            [one]
-  = citeCommand cmd p s k
-    where
-       Citation { citationId = k
-                , citationPrefix = p
-                , citationSuffix = s
-                , citationMode = m
-                } = one
-       cmd = case m of
-                  SuppressAuthor -> "autocite*"
-                  AuthorInText   -> "textcite"
-                  NormalCitation -> "autocite"
-
-citationsToBiblatex (c:cs) = do
-  args <- mapM convertOne (c:cs)
-  return $ text cmd <> foldl' (<>) empty args
-    where
-       cmd = case citationMode c of
-                  SuppressAuthor -> "\\autocites*"
-                  AuthorInText   -> "\\textcites"
-                  NormalCitation -> "\\autocites"
-       convertOne Citation { citationId = k
-                           , citationPrefix = p
-                           , citationSuffix = s
-                           }
-              = citeArguments p s k
-
-citationsToBiblatex _ = return empty
-
--- Determine listings language from list of class attributes.
-getListingsLanguage :: [String] -> Maybe String
-getListingsLanguage xs
-  = foldr ((<|>) . toListingsLanguage) Nothing xs
-
-mbBraced :: String -> String
-mbBraced x = if not (all isAlphaNum x)
-                then "{" <> x <> "}"
-                else x
-
--- Extract a key from divs and spans
-extract :: String -> Block -> [String]
-extract key (Div attr _)     = lookKey key attr
-extract key (Plain ils)      = query (extractInline key) ils
-extract key (Para ils)       = query (extractInline key) ils
-extract key (Header _ _ ils) = query (extractInline key) ils
-extract _ _                  = []
-
--- Extract a key from spans
-extractInline :: String -> Inline -> [String]
-extractInline key (Span attr _) = lookKey key attr
-extractInline _ _               = []
-
--- Look up a key in an attribute and give a list of its values
-lookKey :: String -> Attr -> [String]
-lookKey key (_,_,kvs) =  maybe [] words $ lookup key kvs
-
--- In environments \Arabic instead of \arabic is used
-toPolyglossiaEnv :: Lang -> (String, String)
-toPolyglossiaEnv l =
-  case toPolyglossia l of
-    ("arabic", o) -> ("Arabic", o)
-    x             -> x
-
--- Takes a list of the constituents of a BCP 47 language code and
--- converts it to a Polyglossia (language, options) tuple
--- http://mirrors.ctan.org/macros/latex/contrib/polyglossia/polyglossia.pdf
-toPolyglossia :: Lang -> (String, String)
-toPolyglossia (Lang "ar" _ "DZ" _)        = ("arabic", "locale=algeria")
-toPolyglossia (Lang "ar" _ "IQ" _)        = ("arabic", "locale=mashriq")
-toPolyglossia (Lang "ar" _ "JO" _)        = ("arabic", "locale=mashriq")
-toPolyglossia (Lang "ar" _ "LB" _)        = ("arabic", "locale=mashriq")
-toPolyglossia (Lang "ar" _ "LY" _)        = ("arabic", "locale=libya")
-toPolyglossia (Lang "ar" _ "MA" _)        = ("arabic", "locale=morocco")
-toPolyglossia (Lang "ar" _ "MR" _)        = ("arabic", "locale=mauritania")
-toPolyglossia (Lang "ar" _ "PS" _)        = ("arabic", "locale=mashriq")
-toPolyglossia (Lang "ar" _ "SY" _)        = ("arabic", "locale=mashriq")
-toPolyglossia (Lang "ar" _ "TN" _)        = ("arabic", "locale=tunisia")
-toPolyglossia (Lang "de" _ _ vars)
-  | "1901" `elem` vars                    = ("german", "spelling=old")
-toPolyglossia (Lang "de" _ "AT" vars)
-  | "1901" `elem` vars                    = ("german", "variant=austrian, spelling=old")
-toPolyglossia (Lang "de" _ "AT" _)        = ("german", "variant=austrian")
-toPolyglossia (Lang "de" _ "CH" vars)
-  | "1901" `elem` vars                    = ("german", "variant=swiss, spelling=old")
-toPolyglossia (Lang "de" _ "CH" _)        = ("german", "variant=swiss")
-toPolyglossia (Lang "de" _ _ _)           = ("german", "")
-toPolyglossia (Lang "dsb" _ _ _)          = ("lsorbian", "")
-toPolyglossia (Lang "el" _ "polyton" _)   = ("greek",   "variant=poly")
-toPolyglossia (Lang "en" _ "AU" _)        = ("english", "variant=australian")
-toPolyglossia (Lang "en" _ "CA" _)        = ("english", "variant=canadian")
-toPolyglossia (Lang "en" _ "GB" _)        = ("english", "variant=british")
-toPolyglossia (Lang "en" _ "NZ" _)        = ("english", "variant=newzealand")
-toPolyglossia (Lang "en" _ "UK" _)        = ("english", "variant=british")
-toPolyglossia (Lang "en" _ "US" _)        = ("english", "variant=american")
-toPolyglossia (Lang "grc" _ _ _)          = ("greek",   "variant=ancient")
-toPolyglossia (Lang "hsb" _ _  _)         = ("usorbian", "")
-toPolyglossia (Lang "la" _ _ vars)
-  | "x-classic" `elem` vars               = ("latin", "variant=classic")
-toPolyglossia (Lang "sl" _ _ _)           = ("slovenian", "")
-toPolyglossia x                           = (commonFromBcp47 x, "")
-
--- Takes a list of the constituents of a BCP 47 language code and
--- converts it to a Babel language string.
--- http://mirrors.ctan.org/macros/latex/required/babel/base/babel.pdf
--- List of supported languages (slightly outdated):
--- http://tug.ctan.org/language/hyph-utf8/doc/generic/hyph-utf8/hyphenation.pdf
-toBabel :: Lang -> String
-toBabel (Lang "de" _ "AT" vars)
-  | "1901" `elem` vars                  = "austrian"
-  | otherwise                           = "naustrian"
-toBabel (Lang "de" _ "CH" vars)
-  | "1901" `elem` vars                  = "swissgerman"
-  | otherwise                           = "nswissgerman"
-toBabel (Lang "de" _ _ vars)
-  | "1901" `elem` vars                  = "german"
-  | otherwise                           = "ngerman"
-toBabel (Lang "dsb" _ _ _)              = "lowersorbian"
-toBabel (Lang "el" _ _ vars)
-  | "polyton" `elem` vars               = "polutonikogreek"
-toBabel (Lang "en" _ "AU" _)            = "australian"
-toBabel (Lang "en" _ "CA" _)            = "canadian"
-toBabel (Lang "en" _ "GB" _)            = "british"
-toBabel (Lang "en" _ "NZ" _)            = "newzealand"
-toBabel (Lang "en" _ "UK" _)            = "british"
-toBabel (Lang "en" _ "US" _)            = "american"
-toBabel (Lang "fr" _ "CA" _)            = "canadien"
-toBabel (Lang "fra" _ _ vars)
-  | "aca" `elem` vars                   = "acadian"
-toBabel (Lang "grc" _ _ _)              = "polutonikogreek"
-toBabel (Lang "hsb" _ _ _)              = "uppersorbian"
-toBabel (Lang "la" _ _ vars)
-  | "x-classic" `elem` vars             = "classiclatin"
-toBabel (Lang "sl" _ _ _)               = "slovene"
-toBabel x                               = commonFromBcp47 x
-
--- Takes a list of the constituents of a BCP 47 language code
--- and converts it to a string shared by Babel and Polyglossia.
--- https://tools.ietf.org/html/bcp47#section-2.1
-commonFromBcp47 :: Lang -> String
-commonFromBcp47 (Lang "pt" _ "BR" _)            = "brazil"
--- Note: documentation says "brazilian" works too, but it doesn't seem to work
--- on some systems.  See #2953.
-commonFromBcp47 (Lang "sr" "Cyrl" _ _)          = "serbianc"
-commonFromBcp47 (Lang "zh" "Latn" _ vars)
-  | "pinyin" `elem` vars                        = "pinyin"
-commonFromBcp47 (Lang l _ _ _) = fromIso l
-  where
-    fromIso "af"  = "afrikaans"
-    fromIso "am"  = "amharic"
-    fromIso "ar"  = "arabic"
-    fromIso "as"  = "assamese"
-    fromIso "ast" = "asturian"
-    fromIso "bg"  = "bulgarian"
-    fromIso "bn"  = "bengali"
-    fromIso "bo"  = "tibetan"
-    fromIso "br"  = "breton"
-    fromIso "ca"  = "catalan"
-    fromIso "cy"  = "welsh"
-    fromIso "cs"  = "czech"
-    fromIso "cop" = "coptic"
-    fromIso "da"  = "danish"
-    fromIso "dv"  = "divehi"
-    fromIso "el"  = "greek"
-    fromIso "en"  = "english"
-    fromIso "eo"  = "esperanto"
-    fromIso "es"  = "spanish"
-    fromIso "et"  = "estonian"
-    fromIso "eu"  = "basque"
-    fromIso "fa"  = "farsi"
-    fromIso "fi"  = "finnish"
-    fromIso "fr"  = "french"
-    fromIso "fur" = "friulan"
-    fromIso "ga"  = "irish"
-    fromIso "gd"  = "scottish"
-    fromIso "gez" = "ethiopic"
-    fromIso "gl"  = "galician"
-    fromIso "he"  = "hebrew"
-    fromIso "hi"  = "hindi"
-    fromIso "hr"  = "croatian"
-    fromIso "hu"  = "magyar"
-    fromIso "hy"  = "armenian"
-    fromIso "ia"  = "interlingua"
-    fromIso "id"  = "indonesian"
-    fromIso "ie"  = "interlingua"
-    fromIso "is"  = "icelandic"
-    fromIso "it"  = "italian"
-    fromIso "jp"  = "japanese"
-    fromIso "km"  = "khmer"
-    fromIso "kmr" = "kurmanji"
-    fromIso "kn"  = "kannada"
-    fromIso "ko"  = "korean"
-    fromIso "la"  = "latin"
-    fromIso "lo"  = "lao"
-    fromIso "lt"  = "lithuanian"
-    fromIso "lv"  = "latvian"
-    fromIso "ml"  = "malayalam"
-    fromIso "mn"  = "mongolian"
-    fromIso "mr"  = "marathi"
-    fromIso "nb"  = "norsk"
-    fromIso "nl"  = "dutch"
-    fromIso "nn"  = "nynorsk"
-    fromIso "no"  = "norsk"
-    fromIso "nqo" = "nko"
-    fromIso "oc"  = "occitan"
-    fromIso "pa"  = "panjabi"
-    fromIso "pl"  = "polish"
-    fromIso "pms" = "piedmontese"
-    fromIso "pt"  = "portuguese"
-    fromIso "rm"  = "romansh"
-    fromIso "ro"  = "romanian"
-    fromIso "ru"  = "russian"
-    fromIso "sa"  = "sanskrit"
-    fromIso "se"  = "samin"
-    fromIso "sk"  = "slovak"
-    fromIso "sq"  = "albanian"
-    fromIso "sr"  = "serbian"
-    fromIso "sv"  = "swedish"
-    fromIso "syr" = "syriac"
-    fromIso "ta"  = "tamil"
-    fromIso "te"  = "telugu"
-    fromIso "th"  = "thai"
-    fromIso "ti"  = "ethiopic"
-    fromIso "tk"  = "turkmen"
-    fromIso "tr"  = "turkish"
-    fromIso "uk"  = "ukrainian"
-    fromIso "ur"  = "urdu"
-    fromIso "vi"  = "vietnamese"
-    fromIso _     = ""
-
-pDocumentOptions :: P.Parsec String () [String]
-pDocumentOptions = do
-  P.char '['
-  opts <- P.sepBy
-    (P.many $ P.spaces *> P.noneOf (" ,]" :: String) <* P.spaces)
-    (P.char ',')
-  P.char ']'
-  return opts
-
-pDocumentClass :: P.Parsec String () String
-pDocumentClass =
-  do P.skipMany (P.satisfy (/='\\'))
-     P.string "\\documentclass"
-     classOptions <- pDocumentOptions <|> return []
-     if ("article" :: String) `elem` classOptions
-       then return "article"
-       else do P.skipMany (P.satisfy (/='{'))
-               P.char '{'
-               P.manyTill P.letter (P.char '}')
+{-# LANGUAGE LambdaCase          #-}
+{-# LANGUAGE TupleSections       #-}
+{-# LANGUAGE PatternGuards       #-}
+{-# LANGUAGE ScopedTypeVariables #-}
+{-# LANGUAGE TypeApplications    #-}
+{-# LANGUAGE ViewPatterns        #-}
+{- |
+   Module      : Text.Pandoc.Writers.LaTeX
+   Copyright   : Copyright (C) 2006-2025 John MacFarlane
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : John MacFarlane <jgm@berkeley.edu>
+   Stability   : alpha
+   Portability : portable
+
+Conversion of 'Pandoc' format into LaTeX.
+-}
+module Text.Pandoc.Writers.LaTeX (
+    writeLaTeX
+  , writeBeamer
+  ) where
+import Control.Monad.State.Strict
+    ( MonadState(get, put),
+      gets,
+      modify,
+      evalStateT )
+import Control.Monad
+    ( MonadPlus(mplus),
+      liftM,
+      when,
+      unless )
+import Crypto.Hash (hashWith, MD5(MD5))
+import Data.Containers.ListUtils (nubOrd)
+import Data.Char (isDigit, isAscii, isLetter)
+import Data.List (intersperse, partition, (\\))
+import qualified Data.Set as Set
+import Data.Maybe (catMaybes, fromMaybe, isJust, listToMaybe, mapMaybe, isNothing)
+import Data.Monoid (Any (..))
+import Data.Text (Text)
+import qualified Data.Text as T
+import Network.URI (unEscapeString)
+import Text.DocTemplates (Context(..), FromContext(lookupContext), Val(..), renderTemplate)
+import qualified Data.Map as M
+import Text.Collate.Lang (renderLang)
+import Text.Pandoc.Class.PandocMonad (PandocMonad, getPOSIXTime, lookupEnv,
+                                      report, toLang)
+import Text.Pandoc.Definition
+import Text.Pandoc.Highlighting (formatLaTeXBlock, formatLaTeXInline, highlight,
+                                 defaultStyle, styleToLaTeX)
+import Text.Pandoc.ImageSize
+import Text.Pandoc.Logging
+import Text.Pandoc.Options
+import Text.DocLayout
+import Text.Pandoc.Shared
+import Text.Pandoc.URI
+import Text.Pandoc.Slides
+import Text.Pandoc.Walk (query, walk, walkM)
+import Text.Pandoc.Writers.LaTeX.Caption (getCaption)
+import Text.Pandoc.Writers.LaTeX.Table (tableToLaTeX)
+import Text.Pandoc.Writers.LaTeX.Citation (citationsToNatbib,
+                                           citationsToBiblatex)
+import Text.Pandoc.Writers.LaTeX.Types (LW, WriterState (..), startingState,
+                                        PdfStandard (..))
+import Text.Pandoc.Writers.LaTeX.Lang (toBabel)
+import Text.Pandoc.Writers.LaTeX.Util (stringToLaTeX, StringContext(..),
+                                       toLabel, inCmd,
+                                       wrapDiv, hypertarget, labelFor,
+                                       getListingsLanguage, mbBraced)
+import Text.Pandoc.Writers.Shared
+import qualified Data.Attoparsec.Text as A
+import qualified Text.Pandoc.UTF8 as UTF8
+import qualified Text.Pandoc.Writers.AnnotatedTable as Ann
+import Control.Applicative ((<|>))
+
+-- Work around problems with notes inside emphasis (see #8982)
+isolateBigNotes :: ([Inline] -> Inline) -> [Inline] -> [Inline]
+isolateBigNotes constructor xs =
+  let (before, after) = break isBigNote xs
+  in case after of
+       (noteInline:rest) -> constructor before :
+                            noteInline :
+                            isolateBigNotes constructor rest
+       [] -> [constructor xs]
+
+isBigNote :: Inline -> Bool
+isBigNote (Note [Plain _]) = False  -- A small note
+isBigNote (Note [Para _]) =  False  -- A small note
+isBigNote (Note _) = True  -- A big note
+isBigNote _ = False  -- Not a note
+
+raiseBigNotes :: [Inline] -> [Inline]
+raiseBigNotes (Emph inner : xs)
+  = isolateBigNotes Emph (raiseBigNotes inner) ++ raiseBigNotes xs
+raiseBigNotes (Strong inner : xs)
+  = isolateBigNotes Strong (raiseBigNotes inner) ++ raiseBigNotes xs
+raiseBigNotes (Underline inner : xs)
+  = isolateBigNotes Underline (raiseBigNotes inner) ++ raiseBigNotes xs
+raiseBigNotes (Strikeout inner : xs)
+  = isolateBigNotes Strikeout (raiseBigNotes inner) ++ raiseBigNotes xs
+raiseBigNotes (x : xs)          = x : raiseBigNotes xs
+raiseBigNotes [] = []
+
+-- | Convert Pandoc to LaTeX.
+writeLaTeX :: PandocMonad m => WriterOptions -> Pandoc -> m Text
+writeLaTeX options document = do
+  let Any hasBigNotes =
+       query (\il -> if isBigNote il then Any True else Any False) document
+  let document' = if hasBigNotes
+                     then walk raiseBigNotes document
+                     else document
+  evalStateT (pandocToLaTeX options document') $ startingState options
+
+-- | Convert Pandoc to LaTeX Beamer.
+writeBeamer :: PandocMonad m => WriterOptions -> Pandoc -> m Text
+writeBeamer options document =
+  evalStateT (pandocToLaTeX options document) $
+    (startingState options){ stBeamer = True }
+
+pandocToLaTeX :: PandocMonad m
+              => WriterOptions -> Pandoc -> LW m Text
+pandocToLaTeX options (Pandoc meta blocks) = do
+  -- Strip off 'references' header if --natbib or --biblatex
+  let method = writerCiteMethod options
+  let isRefsDiv (Div ("refs",_,_) _) = True
+      isRefsDiv _ = False
+  let blocks' = if method == Biblatex || method == Natbib
+                   then filter (not . isRefsDiv) blocks
+                   else blocks
+  -- see if there are internal links
+  let isInternalLink (Link _ _ (s,_))
+        | Just ('#', xs) <- T.uncons s = [xs]
+      isInternalLink _                 = []
+  modify $ \s -> s{ stInternalLinks = query isInternalLink blocks' }
+  let colwidth = if writerWrapText options == WrapAuto
+                    then Just $ writerColumns options
+                    else Nothing
+  docLangs <- catMaybes <$>
+      mapM (toLang . Just) (nubOrd (query (extract "lang") blocks))
+  mblang <- toLang $ case getLang options meta of
+                          Just l -> Just l
+                          Nothing | null docLangs -> Nothing
+                                  | otherwise     -> Just "en"
+  modify $ \s -> s{ stLang = mblang }
+  metadata <- metaToContext options
+              blockListToLaTeX
+              (fmap chomp . inlineListToLaTeX)
+              meta
+  let chaptersClasses = ["memoir","book","report","scrreprt","scrreport",
+                        "scrbook","extreport","extbook","tufte-book",
+                        "ctexrep","ctexbook","elegantbook"]
+  let frontmatterClasses = ["memoir","book","scrbook","extbook","tufte-book",
+                           "ctexbook","elegantbook"]
+  -- these have \frontmatter etc.
+  beamer <- gets stBeamer
+  let documentClass =
+        case lookupContext "documentclass" (writerVariables options) `mplus`
+              (stringify <$> lookupMeta "documentclass" meta) of
+                 Just x -> x
+                 Nothing | beamer    -> "beamer"
+                         | otherwise -> case writerTopLevelDivision options of
+                                          TopLevelPart    -> "book"
+                                          TopLevelChapter -> "book"
+                                          _               -> "article"
+  when (documentClass `elem` chaptersClasses) $
+     modify $ \s -> s{ stHasChapters = True }
+  let csquotes =
+        case lookupContext "csquotes" (writerVariables options) of
+          Just (BoolVal v) -> v
+          Just (SimpleVal (Text _ t)) -> t /= ("false" :: Text)
+          _ -> case stringify <$> lookupMeta "csquotes" meta of
+                  Nothing -> False
+                  Just "false" -> False
+                  Just _ -> True
+  when csquotes $ modify $ \s -> s{stCsquotes = True}
+  let (blocks'', lastHeader) = if writerCiteMethod options == Citeproc then
+                                 (blocks', [])
+                               else case reverse blocks' of
+                                 Header 1 _ il : _ -> (init blocks', il)
+                                 _                 -> (blocks', [])
+  blocks''' <- if beamer
+                  then toSlides blocks''
+                  else return $ makeSections False Nothing blocks''
+  main <- blockListToLaTeX blocks'''
+  biblioTitle <- inlineListToLaTeX lastHeader
+  st <- get
+  titleMeta <- escapeCommas <$> -- see #10501
+                stringToLaTeX TextString (stringify $ docTitle meta)
+  subtitleMeta <- stringToLaTeX TextString (stringify $ lookupMetaInlines "subtitle" meta)
+  authorsMeta <- mapM (stringToLaTeX TextString . stringify) $ docAuthors meta
+  -- The trailer ID is as hash used to identify the PDF. Taking control of its
+  -- value is important when aiming for reproducible PDF generation. Setting
+  -- `SOURCE_DATE_EPOCH` is the traditional method used to control
+  -- reproducible builds. There are no cryptographic requirements for the ID,
+  -- so the 128bits (16 bytes) of MD5 are appropriate.
+  reproduciblePDF <- isJust <$> lookupEnv "SOURCE_DATE_EPOCH"
+  trailerID <- do
+    time <- getPOSIXTime
+    let hash = T.pack . show . hashWith MD5 $ mconcat
+               [ UTF8.fromString $ show time
+               , UTF8.fromText $ render Nothing main
+               ]
+    pure $ mconcat [ "<", hash, "> <", hash, ">" ]
+  -- we need a default here since lang is used in template conditionals
+  let hasStringValue x = isJust (getField x metadata :: Maybe (Doc Text))
+  let geometryFromMargins = mconcat $ intersperse ("," :: Doc Text) $
+                            mapMaybe (\(x,y) ->
+                                ((x <> "=") <>) <$> getField y metadata)
+                              [("lmargin","margin-left")
+                              ,("rmargin","margin-right")
+                              ,("tmargin","margin-top")
+                              ,("bmargin","margin-bottom")
+                              ]
+
+  let dirs = query (extract "dir") blocks
+
+  let nociteIds = query (\case
+                           Cite cs _ -> map citationId cs
+                           _         -> [])
+                    $ lookupMetaInlines "nocite" meta
+
+   -- see #7414, avoid escaped underscores
+  let unescapeUnderscore = T.replace "\\_" "_"
+  let bibliography' = map unescapeUnderscore <$>
+                        getField "bibliography" metadata
+
+  -- Process PDF standard metadata for DocumentMetadata
+  pdfStd <- processPdfStandard metadata
+
+  let context  =  (case bibliography' of
+                     Nothing -> id
+                     Just xs -> resetField "bibliography" xs) $
+                  defField "toc" (writerTableOfContents options) $
+                  defField "lof" (writerListOfFigures options) $
+                  defField "lot" (writerListOfTables options) $
+                  defField "toc-depth" (tshow
+                                        (writerTOCDepth options -
+                                              if stHasChapters st
+                                                 then 1
+                                                 else 0)) $
+                  defField "body" main $
+                  defField "title-meta" titleMeta $
+                  defField "subtitle-meta" subtitleMeta $
+                  defField "author-meta"
+                        (T.intercalate "; " authorsMeta) $
+                  defField "documentclass" documentClass $
+                  defField "verbatim-in-note" (stVerbInNote st) $
+                  defField "tables" (stTable st) $
+                  defField "multirow" (stMultiRow st) $
+                  defField "cancel" (stCancel st) $
+                  defField "strikeout" (stStrikeout st) $
+                  defField "url" (stUrl st) $
+                  defField "numbersections" (writerNumberSections options) $
+                  defField "lhs" (stLHS st) $
+                  defField "graphics" (stGraphics st) $
+                  defField "subfigure" (stSubfigure st) $
+                  defField "svg" (stSVG st) $
+                  defField "has-chapters" (stHasChapters st) $
+                  defField "has-frontmatter" (documentClass `elem` frontmatterClasses) $
+                  defField "listings" (writerHighlightMethod options ==
+                                       IdiomaticHighlighting
+                                       || stLHS st) $
+                  defField "zero-width-non-joiner" (stZwnj st) $
+                  defField "beamer" beamer $
+                  (if stHighlighting st
+                      then case writerHighlightMethod options of
+                             Skylighting sty ->
+                                   defField "highlighting-macros"
+                                      (T.stripEnd $ styleToLaTeX sty)
+                             DefaultHighlighting ->
+                                   defField "highlighting-macros"
+                                      (T.stripEnd $ styleToLaTeX defaultStyle)
+                             _ -> id
+                      else id) $
+                  (case writerCiteMethod options of
+                         Natbib   -> defField "biblio-title" biblioTitle .
+                                     defField "natbib" True .
+                                     defField "nocite-ids" nociteIds
+                         Biblatex -> defField "biblio-title" biblioTitle .
+                                     defField "biblatex" True .
+                                     defField "nocite-ids" nociteIds
+                         _        -> id) $
+                  defField "colorlinks" (any hasStringValue
+                           ["citecolor", "urlcolor", "linkcolor", "toccolor",
+                            "filecolor"]) $
+                  (if null dirs
+                     then id
+                     else defField "dir" ("ltr" :: Text)) $
+                  defField "section-titles" True $
+                  defField "csl-refs" (stHasCslRefs st) $
+                  defField "geometry" geometryFromMargins $
+                  (case T.uncons . render Nothing <$>
+                        getField "papersize" metadata of
+                      -- uppercase a4, a5, etc.
+                      Just (Just ('A', ds))
+                        | not (T.null ds) && T.all isDigit ds
+                          -> resetField "papersize" ("a" <> ds)
+                      _   -> id) .
+                  (if reproduciblePDF
+                    then defField "pdf-trailer-id" trailerID
+                    else id) $
+                  (if not (null (pdfStandards pdfStd)) || isJust (pdfVersion pdfStd)
+                    then resetField "pdfstandard" $ MapVal $ Context $ M.fromList
+                           [ ("standards", ListVal $ map (SimpleVal . literal) (pdfStandards pdfStd))
+                           , ("version", maybe NullVal (SimpleVal . literal) (pdfVersion pdfStd))
+                           , ("tagging", BoolVal (pdfTagging pdfStd))
+                           ]
+                    else id) $
+                  metadata
+  let babelLang = mblang >>= toBabel
+  let context' =
+          -- note: lang is used in some conditionals in the template,
+          -- so we need to set it if we have any babel/polyglossia:
+          maybe id (\l -> defField "lang"
+                      (literal $ renderLang l)) mblang
+        $ maybe id (\l -> defField "babel-lang"
+                      (literal l)) babelLang
+        $ (case babelLang of -- see #8283
+                Just l | l `notElem` ldfLanguages
+                         -> defField "babeloptions" ("provide=*" :: Text)
+                _ -> id)
+        $ defField "babel-otherlangs"
+             (map literal
+               (filter (`elem` ldfLanguages) .
+                nubOrd . catMaybes .
+                filter (/= babelLang)
+                $ map toBabel docLangs))
+        $ defField "latex-dir-rtl"
+           ((render Nothing <$> getField "dir" context) ==
+               Just ("rtl" :: Text)) context
+  return $ render colwidth $
+    case writerTemplate options of
+       Nothing  -> main
+       Just tpl -> renderTemplate tpl context'
+
+-- Commas in title-meta need to be put in braces; see #10501
+escapeCommas :: Text -> Text
+escapeCommas = T.replace "," "{,}"
+
+toSlides :: PandocMonad m => [Block] -> LW m [Block]
+toSlides bs = do
+  opts <- gets stOptions
+  let slideLevel = fromMaybe (getSlideLevel bs) $ writerSlideLevel opts
+  let bs' = prepSlides slideLevel bs
+  walkM (elementToBeamer slideLevel) $ makeSections False Nothing bs'
+
+-- this creates section slides and marks slides with class "slide","block"
+elementToBeamer :: PandocMonad m => Int -> Block -> LW m Block
+elementToBeamer slideLevel (Div (ident,"section":dclasses,dkvs)
+                              xs@(h@(Header lvl _ _) : ys))
+  | lvl >  slideLevel
+    = return $ Div (ident,"block":dclasses,dkvs) xs
+  | lvl <  slideLevel
+    = do let isSlide (Div (_,"slide":_,_) _)   = True
+             isSlide (Div (_,"section":_,_) _) = True
+             isSlide _                         = False
+         let (titleBs, slideBs) = break isSlide ys
+         return $
+           case titleBs of
+              [] -> Div (ident,"section":dclasses,dkvs) xs
+              [Div (_,"notes":_,_) _] ->  -- see #7857, don't create frame
+                    -- just for speaker notes after section heading
+                    Div (ident,"section":dclasses,dkvs) xs
+              _  -> Div (ident,"section":dclasses,dkvs)
+                     (h : Div ("","slide":dclasses,dkvs) (h:titleBs) : slideBs)
+  | otherwise
+    = return $ Div (ident,"slide":dclasses,dkvs) xs
+elementToBeamer _ x = return x
+
+isListBlock :: Block -> Bool
+isListBlock (BulletList _)     = True
+isListBlock (OrderedList _ _)  = True
+isListBlock (DefinitionList _) = True
+isListBlock _                  = False
+
+-- | Convert Pandoc block element to LaTeX.
+blockToLaTeX :: PandocMonad m
+             => Block     -- ^ Block to convert
+             -> LW m (Doc Text)
+blockToLaTeX (Div attr@(identifier,"block":dclasses,_)
+             (Header _ _ ils : bs)) = do
+  let blockname
+        | "example" `elem` dclasses = "exampleblock"
+        | "alert" `elem` dclasses = "alertblock"
+        | otherwise = "block"
+  anchor <- if T.null identifier
+               then pure empty
+               else (cr <>) <$> hypertarget identifier
+  title' <- inlineListToLaTeX ils
+  contents <- blockListToLaTeX bs
+  wrapDiv attr $ ("\\begin" <> braces blockname <> braces title' <> anchor) $$
+                 contents $$ "\\end" <> braces blockname
+blockToLaTeX (Div (identifier,"slide":dclasses,dkvs)
+               (Header _ (_,hclasses,hkvs) ils : bs)) = do
+  -- note: [fragile] is required or verbatim breaks
+  let hasCodeBlock (CodeBlock _ _) = [True]
+      hasCodeBlock _               = []
+  let hasCode (Code _ _) = [True]
+      hasCode _          = []
+  let classes = nubOrd $ dclasses ++ hclasses
+  let kvs = nubOrd $ dkvs ++ hkvs
+  let fragile = "fragile" `elem` classes ||
+                not (null $ query hasCodeBlock bs ++ query hasCode bs)
+  let frameoptions = ["allowdisplaybreaks", "allowframebreaks", "fragile",
+                      "b", "c", "t", "environment", "s", "squeeze",
+                      "label", "plain", "shrink", "standout",
+                      "noframenumbering", "containsverbatim"]
+  let optionslist = ["fragile" | fragile
+                               , isNothing (lookup "fragile" kvs)
+                               , "fragile" `notElem` classes
+                               , "containsverbatim" `notElem` classes] ++
+                    [k | k <- classes, k `elem` frameoptions] ++
+                    [k <> "=" <> v | (k,v) <- kvs, k `elem` frameoptions] ++
+                    [v | ("frameoptions", v) <- kvs]
+  let options = if null optionslist
+                   then empty
+                   else brackets (literal (T.intercalate "," optionslist))
+  slideTitle <- if ils == [Str "\0"] -- marker for hrule
+                   then return empty
+                   else braces <$> inlineListToLaTeX ils
+  slideAnchor <- if T.null identifier
+                    then pure empty
+                    else (cr <>) <$> hypertarget identifier
+  contents <- blockListToLaTeX bs >>= wrapDiv (identifier,classes,kvs)
+  return $ ("\\begin{frame}" <> options <> slideTitle <> slideAnchor) $$
+             contents $$ "\\end{frame}"
+blockToLaTeX (Div (identifier@(T.uncons -> Just (_,_)),dclasses,dkvs)
+               (Header lvl ("",hclasses,hkvs) ils : bs)) =
+  -- move identifier from div to header
+  blockToLaTeX (Div ("",dclasses,dkvs)
+               (Header lvl (identifier,hclasses,hkvs) ils : bs))
+blockToLaTeX (Div (identifier,classes,kvs) bs) = do
+  beamer <- gets stBeamer
+  oldIncremental <- gets stIncremental
+  if beamer && "incremental" `elem` classes
+     then modify $ \st -> st{ stIncremental = True }
+     else when (beamer && "nonincremental" `elem` classes) $
+             modify $ \st -> st { stIncremental = False }
+  result <- if (identifier == "refs" || -- <- for backwards compatibility
+                "csl-bib-body" `elem` classes) &&
+               (not (null bs))
+               then do
+                 modify $ \st -> st{ stHasCslRefs = True }
+                 inner <- blockListToLaTeX bs
+                 return $ ("\\begin{CSLReferences}"
+                            <> braces
+                                (if "hanging-indent" `elem` classes
+                                    then "1"
+                                    else "0")
+                            <> braces
+                               (maybe "1" literal (lookup "entry-spacing" kvs)))
+                          $$ inner
+                          $+$ "\\end{CSLReferences}"
+               else blockListToLaTeX bs
+  modify $ \st -> st{ stIncremental = oldIncremental }
+  let wrap txt
+       | beamer && "notes" `elem` classes
+         = pure ("\\note" <> braces txt) -- speaker notes
+       | "ref-" `T.isPrefixOf` identifier
+         = do
+             lab <- toLabel identifier
+             pure $ ("\\bibitem" <> brackets "\\citeproctext"
+                      <> braces (literal lab)) $$ txt
+         | otherwise = do
+             linkAnchor <- hypertarget identifier
+             pure $ linkAnchor $$ txt
+  wrapDiv (identifier,classes,kvs) result >>= wrap
+blockToLaTeX (Plain lst) =
+  inlineListToLaTeX lst
+-- . . . indicates pause in beamer slides
+blockToLaTeX (Para [Str ".",Space,Str ".",Space,Str "."]) = do
+  beamer <- gets stBeamer
+  if beamer
+     then blockToLaTeX (RawBlock "latex" "\\pause")
+     else inlineListToLaTeX [Str ".",Space,Str ".",Space,Str "."]
+blockToLaTeX (Para lst) =
+  if null lst
+     then do
+       opts <- gets stOptions
+       if isEnabled Ext_empty_paragraphs opts
+          then pure "\\hfill\\par"
+          else pure mempty
+     else inlineListToLaTeX lst
+blockToLaTeX (LineBlock lns) =
+  blockToLaTeX $ linesToPara lns
+blockToLaTeX (BlockQuote lst) = do
+  beamer <- gets stBeamer
+  csquotes <- liftM stCsquotes get
+  case lst of
+       [b] | beamer && isListBlock b -> do
+         oldIncremental <- gets stIncremental
+         modify $ \s -> s{ stIncremental = not oldIncremental }
+         result <- blockToLaTeX b
+         modify $ \s -> s{ stIncremental = oldIncremental }
+         return result
+       _ -> do
+         oldInQuote <- gets stInQuote
+         modify (\s -> s{stInQuote = True})
+         contents <- blockListToLaTeX lst
+         modify (\s -> s{stInQuote = oldInQuote})
+         let envname = if csquotes then "displayquote" else "quote"
+         return $ ("\\begin" <> braces envname) $$
+                  contents $$
+                  ("\\end" <> braces envname)
+blockToLaTeX (CodeBlock (identifier,classes,keyvalAttr) str) = do
+  opts <- gets stOptions
+  inNote <- stInNote <$> get
+  linkAnchor <- if T.null identifier
+                   then pure empty
+                   else ((<> cr) . (<> "%")) <$> hypertarget identifier
+  let lhsCodeBlock = do
+        modify $ \s -> s{ stLHS = True }
+        return $ flush (linkAnchor $$ "\\begin{code}" $$ literal str $$
+                            "\\end{code}") $$ cr
+  let rawCodeBlock = do
+        env <- if inNote
+                  then modify (\s -> s{ stVerbInNote = True }) >>
+                       return "Verbatim"
+                  else return "verbatim"
+        return $ flush (linkAnchor $$ literal ("\\begin{" <> env <> "}") $$
+                 literal str $$ literal ("\\end{" <> env <> "}")) <> cr
+  let listingsCodeBlock = do
+        st <- get
+        ref <- toLabel identifier
+        kvs <- mapM (\(k,v) -> (k,) <$>
+                       stringToLaTeX TextString v) keyvalAttr
+        let params = if writerHighlightMethod (stOptions st)
+                        == IdiomaticHighlighting
+                     then (case getListingsLanguage classes of
+                                Just l  -> [ "language=" <> mbBraced l ]
+                                Nothing -> []) ++
+                          [ "numbers=left" | "numberLines" `elem` classes
+                             || "number" `elem` classes
+                             || "number-lines" `elem` classes ] ++
+                          [ (if key == "startFrom"
+                                then "firstnumber"
+                                else key) <> "=" <> mbBraced attr |
+                                (key,attr) <- kvs,
+                                key `notElem` ["exports", "tangle", "results"]
+                                -- see #4889
+                          ] ++
+                          ["label=" <> ref | not (T.null identifier)]
+
+                     else []
+            printParams
+                | null params = empty
+                | otherwise   = brackets $ hcat (intersperse ", "
+                      (map literal params))
+        return $ flush ("\\begin{lstlisting}" <> printParams $$ literal str $$
+                 "\\end{lstlisting}") $$ cr
+  let highlightedCodeBlock =
+        case highlight (writerSyntaxMap opts)
+                 formatLaTeXBlock ("",classes ++ ["default"],keyvalAttr) str of
+               Left msg -> do
+                 unless (T.null msg) $
+                   report $ CouldNotHighlight msg
+                 rawCodeBlock
+               Right h -> do
+                  when inNote $ modify (\s -> s{ stVerbInNote = True })
+                  modify (\s -> s{ stHighlighting = True })
+                  return (flush $ linkAnchor $$ literal h)
+  case () of
+     _ | isEnabled Ext_literate_haskell opts && "haskell" `elem` classes &&
+         "literate" `elem` classes           -> lhsCodeBlock
+       | writerHighlightMethod opts == IdiomaticHighlighting
+                                             -> listingsCodeBlock
+       | not (null classes), Skylighting _ <- writerHighlightMethod opts
+                                             -> highlightedCodeBlock
+       | not (null classes), DefaultHighlighting <- writerHighlightMethod opts
+                                             -> highlightedCodeBlock
+       -- we don't want to use \begin{verbatim} if our code
+       -- contains \end{verbatim}:
+       | inNote
+       , "\\end{Verbatim}" `T.isInfixOf` str -> highlightedCodeBlock
+       | not inNote
+       , "\\end{verbatim}" `T.isInfixOf` str -> highlightedCodeBlock
+       | otherwise                           -> rawCodeBlock
+blockToLaTeX b@(RawBlock f x) = do
+  beamer <- gets stBeamer
+  if f == Format "latex" || f == Format "tex" ||
+       (f == Format "beamer" && beamer)
+     then return $ literal x
+     else do
+       report $ BlockNotRendered b
+       return empty
+blockToLaTeX (BulletList []) = return empty  -- otherwise latex error
+blockToLaTeX (BulletList lst) = do
+  incremental <- gets stIncremental
+  isFirstInDefinition <- gets stIsFirstInDefinition
+  beamer <- gets stBeamer
+  let inc = if beamer && incremental then "[<+->]" else ""
+  items <- mapM (listItemToLaTeX False) lst
+  let spacing = if isTightList lst
+                   then text "\\tightlist"
+                   else empty
+  return $ -- force list to start on new line if in a defn list
+             (if isFirstInDefinition then "\\hfill" else mempty) $$
+             text ("\\begin{itemize}" <> inc) $$
+             spacing $$
+             -- force list at beginning of definition to start on new line
+             vcat items $$
+             "\\end{itemize}"
+blockToLaTeX (OrderedList _ []) = return empty -- otherwise latex error
+blockToLaTeX (OrderedList (start, numstyle, numdelim) lst) = do
+  st <- get
+  let inc = if stBeamer st && stIncremental st then "[<+->]" else ""
+  let oldlevel = stOLLevel st
+  isFirstInDefinition <- gets stIsFirstInDefinition
+  put $ st {stOLLevel = oldlevel + 1}
+  items <- mapM (listItemToLaTeX True) lst
+  modify (\s -> s {stOLLevel = oldlevel})
+  let beamer = stBeamer st
+  let tostyle x = case numstyle of
+                       Decimal      -> "\\arabic" <> braces x
+                       UpperRoman   -> "\\Roman" <> braces x
+                       LowerRoman   -> "\\roman" <> braces x
+                       UpperAlpha   -> "\\Alph" <> braces x
+                       LowerAlpha   -> "\\alph" <> braces x
+                       Example      -> "\\arabic" <> braces x
+                       DefaultStyle -> "\\arabic" <> braces x
+  let todelim x = case numdelim of
+                       OneParen  -> x <> ")"
+                       TwoParens -> parens x
+                       Period    -> x <> "."
+                       _         -> x <> "."
+  let exemplar = case numstyle of
+                       Decimal      -> "1"
+                       UpperRoman   -> "I"
+                       LowerRoman   -> "i"
+                       UpperAlpha   -> "A"
+                       LowerAlpha   -> "a"
+                       Example      -> "1"
+                       DefaultStyle -> "1"
+  let enum = literal $ "enum" <> T.toLower (toRomanNumeral oldlevel)
+  let stylecommand
+        | numstyle == DefaultStyle && numdelim == DefaultDelim = empty
+        | beamer && numstyle == Decimal && numdelim == Period = empty
+        | beamer = brackets (todelim exemplar)
+        | otherwise = "\\def" <> "\\label" <> enum <>
+          braces (todelim $ tostyle enum)
+  let resetcounter = if start == 1 || oldlevel > 4
+                        then empty
+                        else "\\setcounter" <> braces enum <>
+                              braces (text $ show $ start - 1)
+  let spacing = if isTightList lst
+                   then text "\\tightlist"
+                   else empty
+  return $ -- force list at beginning of definition to start on new line
+           (if isFirstInDefinition then "\\hfill" else mempty)
+         $$ text ("\\begin{enumerate}" <> inc)
+         $$ stylecommand
+         $$ resetcounter
+         $$ spacing
+         $$ vcat items
+         $$ "\\end{enumerate}"
+blockToLaTeX (DefinitionList []) = return empty
+blockToLaTeX (DefinitionList lst) = do
+  incremental <- gets stIncremental
+  beamer <- gets stBeamer
+  let inc = if beamer && incremental then "[<+->]" else ""
+  items <- mapM defListItemToLaTeX lst
+  let spacing = if all (isTightList . snd) lst
+                   then text "\\tightlist"
+                   else empty
+  return $ text ("\\begin{description}" <> inc) $$ spacing $$ vcat items $$
+               "\\end{description}"
+blockToLaTeX HorizontalRule =
+            return
+  "\\begin{center}\\rule{0.5\\linewidth}{0.5pt}\\end{center}"
+blockToLaTeX (Header level (id',classes,_) lst) = do
+  modify $ \s -> s{stInHeading = True}
+  hdr <- sectionHeader classes id' level lst
+  modify $ \s -> s{stInHeading = False}
+  return hdr
+blockToLaTeX (Table attr blkCapt specs thead tbodies tfoot) =
+  tableToLaTeX inlineListToLaTeX blockListToLaTeX
+               (Ann.toTable attr blkCapt specs thead tbodies tfoot)
+blockToLaTeX (Figure (ident, _, kvs) captnode body) = do
+  opts <- gets stOptions
+  (capt, captForLof, footnotes) <- getCaption inlineListToLaTeX True captnode
+  lab <- labelFor ident
+  let caption = "\\caption" <> captForLof <> braces capt <> lab
+      placement = case lookup "latex-placement" kvs of
+        Just p -> brackets (text (T.unpack p))
+        _      -> text ""
+
+  isSubfigure <- gets stInFigure
+  modify $ \st -> st{ stInFigure = True }
+  contents <- case body of
+    [b] -> blockToLaTeX b
+    bs  -> mconcat . intersperse (cr <> "\\hfill") <$>
+           mapM (toSubfigure (length bs)) bs
+  let innards = "\\centering" $$
+                (case writerFigureCaptionPosition opts of
+                  CaptionBelow -> contents $$ caption
+                  CaptionAbove -> caption $$ contents) <> cr
+  modify $ \st ->
+    st{ stInFigure = isSubfigure
+      , stSubfigure = stSubfigure st || isSubfigure
+      }
+
+  let containsTable = getAny . query (\case
+        Table {}  -> Any True
+        _         -> Any False)
+  st <- get
+  return $ (case () of
+    _ | containsTable body ->
+          -- placing a longtable in a figure or center environment does
+          -- not make sense.
+          cr <> contents
+    _ | stInMinipage st ->
+          -- can't have figures in notes or minipage (here, table cell)
+          -- http://www.tex.ac.uk/FAQ-ouparmd.html
+          cr <> "\\begin{center}" $$ contents $+$ capt $$ "\\end{center}"
+    _ | isSubfigure ->
+          innards
+    _ ->  cr <> "\\begin{figure}" <> placement $$ innards $$ "\\end{figure}")
+    $$ footnotes
+
+toSubfigure :: PandocMonad m => Int -> Block -> LW m (Doc Text)
+toSubfigure nsubfigs blk = do
+  contents <- blockToLaTeX blk
+  let linewidth = tshow @Double (0.9 / fromIntegral nsubfigs) <> "\\linewidth"
+  return $ cr <> case blk of
+    Figure {}    -> vcat
+                    [ "\\begin{subfigure}[t]" <> braces (literal linewidth)
+                    , contents
+                    , "\\end{subfigure}"
+                    ]
+    _            -> vcat
+                    [ "\\begin{minipage}[t]" <> braces (literal linewidth)
+                    , contents
+                    , "\\end{minipage}"
+                    ]
+
+blockListToLaTeX :: PandocMonad m => [Block] -> LW m (Doc Text)
+blockListToLaTeX lst =
+  vsep `fmap` mapM (\b -> setEmptyLine True >> blockToLaTeX b) lst
+
+listItemToLaTeX :: PandocMonad m => Bool -> [Block] -> LW m (Doc Text)
+listItemToLaTeX isOrdered lst
+  -- we need to put some text before a header if it's the first
+  -- element in an item. This will look ugly in LaTeX regardless, but
+  -- this will keep the typesetter from throwing an error.
+  | (Header{} :_) <- lst =
+    (text "\\item ~" $$) . nest 2 <$> blockListToLaTeX lst
+  | not isOrdered
+  , Just (checked, bs) <- toTaskListItem lst
+   = taskListItem checked bs
+  | otherwise = (text "\\item" $$) . nest 2 <$> blockListToLaTeX lst
+  where
+    taskListItem checked bs = do
+      let checkbox  = if checked
+                      then "$\\boxtimes$"
+                      else "$\\square$"
+      let bs' = case bs of
+                  Plain ils : xs -> Para ils : xs
+                  _ -> bs
+      bsContents <- blockListToLaTeX bs'
+      return $ "\\item" <> brackets checkbox $$ nest 2 bsContents
+
+defListItemToLaTeX :: PandocMonad m => ([Inline], [[Block]]) -> LW m (Doc Text)
+defListItemToLaTeX (term, defs) = do
+    -- needed to turn off 'listings' because it breaks inside \item[...]:
+    modify $ \s -> s{stInItem = True}
+    term' <- inlineListToLaTeX term
+    modify $ \s -> s{stInItem = False}
+    -- put braces around term if it contains an internal link,
+    -- since otherwise we get bad bracket interactions: \item[\hyperref[..]
+    let isInternalLink (Link _ _ (src,_))
+          | Just ('#', _) <- T.uncons src = True
+        isInternalLink _                  = False
+    let term'' = if any isInternalLink term
+                    then braces term'
+                    else term'
+    def'  <- case concat defs of
+               [] -> return mempty
+               (x:xs) -> do
+                 modify $ \s -> s{stIsFirstInDefinition = True }
+                 firstitem <- blockToLaTeX x
+                 modify $ \s -> s{stIsFirstInDefinition = False }
+                 rest <- blockListToLaTeX xs
+                 return $ firstitem $+$ rest
+    return $ case defs of
+     ((Header{} : _) : _)    ->
+       "\\item" <> brackets term'' <> " ~ " $$ def'
+     ((CodeBlock{} : _) : _) -> -- see #4662
+       "\\item" <> brackets term'' <> " ~ " $$ def'
+     _                       ->
+       "\\item" <> brackets term'' $$ def'
+
+-- | Craft the section header, inserting the section reference, if supplied.
+sectionHeader :: PandocMonad m
+              => [Text]  -- classes
+              -> Text
+              -> Int
+              -> [Inline]
+              -> LW m (Doc Text)
+sectionHeader classes ident level lst = do
+  let unnumbered = "unnumbered" `elem` classes
+  let unlisted = "unlisted" `elem` classes
+  txt <- inlineListToLaTeX lst
+  plain <- stringToLaTeX TextString $ T.concat $ map stringify lst
+  let removeInvalidInline (Note _)             = []
+      removeInvalidInline (Span (id', _, _) _) | not (T.null id') = []
+      removeInvalidInline Image{}            = []
+      removeInvalidInline x                    = [x]
+  let lstNoNotes = foldr (mappend . (\x -> walkM removeInvalidInline x)) mempty lst
+  txtNoNotes <- inlineListToLaTeX lstNoNotes
+  txtNoLinksNoNotes <- inlineListToLaTeX (removeLinks lstNoNotes)
+  -- footnotes in sections don't work (except for starred variants)
+  -- unless you specify an optional argument:
+  -- \section[mysec]{mysec\footnote{blah}}
+  optional <- if unnumbered || lstNoNotes == lst || null lstNoNotes
+                 then return empty
+                 else
+                   return $ brackets txtNoNotes
+  let contents = if render Nothing txt == plain
+                    then braces txt
+                    else braces (text "\\texorpdfstring"
+                         <> braces txt
+                         <> braces (literal plain))
+  book <- gets stHasChapters
+  opts <- gets stOptions
+  let topLevelDivision = if book && writerTopLevelDivision opts == TopLevelDefault
+                         then TopLevelChapter
+                         else writerTopLevelDivision opts
+  beamer <- gets stBeamer
+  let level' = if beamer &&
+                  topLevelDivision `elem` [TopLevelPart, TopLevelChapter]
+               -- beamer has parts but no chapters
+               then if level == 1 then -1 else level - 1
+               else case topLevelDivision of
+                      TopLevelPart    -> level - 2
+                      TopLevelChapter -> level - 1
+                      TopLevelSection -> level
+                      TopLevelDefault -> level
+  let sectionType = case level' of
+                          -1 -> "part"
+                          0  -> "chapter"
+                          1  -> "section"
+                          2  -> "subsection"
+                          3  -> "subsubsection"
+                          4  -> "paragraph"
+                          5  -> "subparagraph"
+                          _  -> ""
+  inQuote <- gets stInQuote
+  let prefix = if inQuote
+                  then text "\\mbox{}%"
+                  -- needed for \paragraph, \subparagraph in quote environment
+                  -- see http://tex.stackexchange.com/questions/169830/
+                  else empty
+  lab <- labelFor ident
+  let star = if unnumbered then text "*" else empty
+  let title = star <> optional <> contents
+  return $ if level' > 5
+              then txt
+              else prefix
+                   $$ text ('\\':sectionType) <> title <> lab
+                   $$ if unnumbered && not unlisted
+                         then "\\addcontentsline{toc}" <>
+                                braces (text sectionType) <>
+                                braces txtNoLinksNoNotes
+                         else empty
+
+-- | Convert list of inline elements to LaTeX.
+inlineListToLaTeX :: PandocMonad m
+                  => [Inline]  -- ^ Inlines to convert
+                  -> LW m (Doc Text)
+inlineListToLaTeX lst = hcat <$>
+  mapM inlineToLaTeX
+    (addKerns . fixLineInitialSpaces . fixInitialLineBreaks $ lst)
+    -- nonbreaking spaces (~) in LaTeX don't work after line breaks,
+    -- so we insert a strut: this is mostly used in verse.
+ where fixLineInitialSpaces [] = []
+       fixLineInitialSpaces (LineBreak : Str s : xs)
+         | Just ('\160', _) <- T.uncons s
+         = LineBreak : RawInline "latex" "\\strut " : Str s
+            : fixLineInitialSpaces xs
+       fixLineInitialSpaces (x:xs) = x : fixLineInitialSpaces xs
+       -- We need \hfill\break for a line break at the start
+       -- of a paragraph. See #5591.
+       fixInitialLineBreaks (LineBreak:xs) =
+         RawInline (Format "latex") "\\hfill\\break\n" :
+           fixInitialLineBreaks xs
+       fixInitialLineBreaks xs = xs
+       addKerns [] = []
+       addKerns (Str s : q@Quoted{} : rest)
+         | isQuote (T.takeEnd 1 s) =
+           Str s : RawInline (Format "latex") "\\," : addKerns (q:rest)
+       addKerns (q@Quoted{} : Str s : rest)
+         | isQuote (T.take 1 s) =
+           q : RawInline (Format "latex") "\\," : addKerns (Str s : rest)
+       addKerns (x:xs) = x : addKerns xs
+       isQuote "\"" = True
+       isQuote "'" = True
+       isQuote "\x2018" = True
+       isQuote "\x2019" = True
+       isQuote "\x201C" = True
+       isQuote "\x201D" = True
+       isQuote _ = False
+
+-- | Convert inline element to LaTeX
+inlineToLaTeX :: PandocMonad m
+              => Inline    -- ^ Inline to convert
+              -> LW m (Doc Text)
+inlineToLaTeX (Span ("",["mark"],[]) lst) = do
+  modify $ \st -> st{ stStrikeout = True } -- this gives us the soul package
+  inCmd "hl" <$> inSoulCommand (inlineListToLaTeX lst)
+inlineToLaTeX (Span (id',classes,kvs) ils) = do
+  linkAnchor <- hypertarget id'
+  lang <- toLang $ lookup "lang" kvs
+  let classToCmd "csl-no-emph" = Just "textup"
+      classToCmd "csl-no-strong" = Just "textnormal"
+      classToCmd "csl-no-smallcaps" = Just "textnormal"
+      classToCmd "csl-block" = Just "CSLBlock"
+      classToCmd "csl-left-margin" = Just "CSLLeftMargin"
+      classToCmd "csl-right-inline" = Just "CSLRightInline"
+      classToCmd "csl-indent" = Just "CSLIndent"
+      classToCmd _ = Nothing
+      kvToCmd ("dir","rtl") = Just "RL"
+      kvToCmd ("dir","ltr") = Just "LR"
+      kvToCmd _ = Nothing
+      langCmds =
+        case lang >>= toBabel of
+           Just l  -> ["foreignlanguage{" <> l <> "}"]
+           Nothing -> []
+  let cmds = mapMaybe classToCmd classes ++ mapMaybe kvToCmd kvs ++ langCmds
+  contents <- inlineListToLaTeX ils
+  return $
+    (if "csl-right-inline" `elem` classes
+        then ("%" <>) -- see #7932
+        else id) $
+    (if any (`elem` classes)
+            ["csl-block","csl-left-margin","csl-right-inline","csl-indent"]
+        then (cr <>)
+        else id) $
+    (if T.null id'
+        then empty
+        else linkAnchor) <>
+    (if null cmds
+        then braces contents
+        else foldr inCmd contents cmds)
+inlineToLaTeX (Emph lst) = inCmd "emph" <$> inlineListToLaTeX lst
+inlineToLaTeX (Underline lst) = do
+  modify $ \st -> st{ stStrikeout = True } -- this gives us the soul package
+  inCmd "ul" <$> inSoulCommand (inlineListToLaTeX lst)
+inlineToLaTeX (Strong lst) = inCmd "textbf" <$> inlineListToLaTeX lst
+inlineToLaTeX (Strikeout lst) = do
+  modify $ \s -> s{ stStrikeout = True }
+  inCmd "st" <$> inSoulCommand (inlineListToLaTeX lst)
+inlineToLaTeX (Superscript lst) =
+  inCmd "textsuperscript" <$> inlineListToLaTeX lst
+inlineToLaTeX (Subscript lst) =
+  inCmd "textsubscript" <$> inlineListToLaTeX lst
+inlineToLaTeX (SmallCaps lst) =
+  inCmd "textsc"<$> inlineListToLaTeX lst
+inlineToLaTeX (Cite cits lst) = do
+  opts <- gets stOptions
+  modify $ \st -> st{ stInCite = True }
+  res <- case writerCiteMethod opts of
+           Natbib   -> citationsToNatbib inlineListToLaTeX cits
+           Biblatex -> citationsToBiblatex inlineListToLaTeX cits
+           _        -> inlineListToLaTeX lst
+  modify $ \st -> st{ stInCite = False }
+  pure res
+
+inlineToLaTeX (Code (_,classes,kvs) str) = do
+  opts <- gets stOptions
+  inHeading <- gets stInHeading
+  inItem <- gets stInItem
+  inSoul <- gets stInSoulCommand
+  inCaption <- gets stInCaption
+  let listingsCode = do
+        let listingsopts = (case getListingsLanguage classes of
+                                Just l  -> (("language", mbBraced l):)
+                                Nothing -> id)
+                           [(k,v) | (k,v) <- kvs
+                                  , k `notElem` ["exports","tangle","results"]]
+        let listingsopt = if null listingsopts
+                             then ""
+                             else "[" <>
+                                  T.intercalate ", "
+                                  (map (\(k,v) -> k <> "=" <> v)
+                                   listingsopts) <> "]"
+        inNote <- gets stInNote
+        when inNote $ modify $ \s -> s{ stVerbInNote = True }
+        let chr = case "!\"'()*,-./:;?@" \\ T.unpack str of
+                       (c:_) -> c
+                       []    -> '!'
+        let isEscapable '\\' = True
+            isEscapable '{'  = True
+            isEscapable '}'  = True
+            isEscapable '%'  = True
+            isEscapable '~'  = True
+            isEscapable '_'  = True
+            isEscapable '&'  = True
+            isEscapable '#'  = True
+            isEscapable '^'  = True
+            isEscapable _    = False
+        let escChar c | isEscapable c = T.pack ['\\',c]
+                      | otherwise     = T.singleton c
+        let str' = T.concatMap escChar str
+        -- we always put lstinline in a dummy 'passthrough' command
+        -- (defined in the default template) so that we don't have
+        -- to change the way we escape characters depending on whether
+        -- the lstinline is inside another command.  See #1629:
+        return $ literal $ "\\passthrough{\\lstinline" <>
+                        listingsopt <> T.singleton chr <> str' <> T.singleton chr <> "}"
+  let rawCode = liftM (literal . (\s -> "\\texttt{" <> escapeSpaces s <> "}"))
+                 $ stringToLaTeX CodeString str
+                where escapeSpaces = T.concatMap
+                         (\c -> if c == ' ' then "\\ " else T.singleton c)
+  let highlightCode =
+        case highlight (writerSyntaxMap opts)
+                 formatLaTeXInline ("",classes,[]) str of
+               Left msg -> do
+                 unless (T.null msg) $ report $ CouldNotHighlight msg
+                 rawCode
+               Right h -> modify (\st -> st{ stHighlighting = True }) >>
+                          return (text (T.unpack h))
+  -- for soul commands we need to protect VERB in an mbox or we get an error
+  -- (see #1294). with regular texttt we don't get an error, but we get
+  -- incorrect results if there is a space (see #5529).
+  let inMbox x = "\\mbox" <> braces x
+
+  -- for captions we need to protect VERB with \protect (see #6821)
+  let protect x = "\\protect" <> x
+
+  let optionalProtect = case () of _ | inSoul -> inMbox
+                                     | inCaption -> protect
+                                     | otherwise -> id
+  optionalProtect <$>
+   case writerHighlightMethod opts of
+     _ | inHeading || inItem  -> rawCode  -- see #5574
+     IdiomaticHighlighting    -> listingsCode
+     Skylighting _ | not (null classes)
+                              -> highlightCode
+     DefaultHighlighting | not (null classes)
+                              -> highlightCode
+     _noHighlighting          -> rawCode
+inlineToLaTeX (Quoted qt lst) = do
+  contents <- inlineListToLaTeX lst
+  csquotes <- liftM stCsquotes get
+  opts <- gets stOptions
+  if csquotes
+     then return $ case qt of
+               DoubleQuote -> "\\enquote" <> braces contents
+               SingleQuote -> "\\enquote*" <> braces contents
+     else do
+       let endsWithQuote xs =
+             case reverse xs of
+                   Quoted{}:_ -> True
+                   Span _ ys : _ -> endsWithQuote ys
+                   Str s:_ -> T.takeEnd 1 s == "'"
+                   _ -> False
+       let beginsWithQuote xs =
+             case xs of
+                   Quoted{}:_ -> True
+                   Span _ ys : _ -> beginsWithQuote ys
+                   Str s:_ -> T.take 1 s == "`"
+                   _ -> False
+       let inner = (if beginsWithQuote lst then "\\," else mempty)
+                    <> contents
+                    <> (if endsWithQuote lst then "\\," else mempty)
+       return $ case qt of
+                DoubleQuote ->
+                   if isEnabled Ext_smart opts
+                      then text "``" <> inner <> text "''"
+                      else char '\x201C' <> inner <> char '\x201D'
+                SingleQuote ->
+                   if isEnabled Ext_smart opts
+                      then char '`' <> inner <> char '\''
+                      else char '\x2018' <> inner <> char '\x2019'
+inlineToLaTeX (Str str) = do
+  setEmptyLine False
+  liftM literal $ stringToLaTeX TextString str
+inlineToLaTeX (Math _ str)
+  | isMathEnv str -- see #9711
+  = do setEmptyLine False
+       when (needsCancel str) $ modify $ \st -> st{ stCancel = True }
+       pure $ literal str
+inlineToLaTeX (Math InlineMath str) = do
+  setEmptyLine False
+  inSoul <- gets stInSoulCommand
+  let contents = literal (handleMathComment str)
+  when (needsCancel str) $ modify $ \st -> st{ stCancel = True }
+  return $
+    if inSoul -- #9597
+       then "$" <> contents <> "$"
+       else "\\(" <> contents <> "\\)"
+inlineToLaTeX (Math DisplayMath str) = do
+  setEmptyLine False
+  inSoul <- gets stInSoulCommand
+  let contents = literal (handleMathComment str)
+  when (needsCancel str) $ modify $ \st -> st{ stCancel = True }
+  return $
+    if inSoul -- # 9597
+       then "$$" <> contents <> "$$"
+       else "\\[" <> contents <> "\\]"
+inlineToLaTeX il@(RawInline f str) = do
+  beamer <- gets stBeamer
+  if f == Format "latex" || f == Format "tex" ||
+        (f == Format "beamer" && beamer)
+     then do
+       setEmptyLine False
+       return $ literal str
+     else do
+       report $ InlineNotRendered il
+       return empty
+inlineToLaTeX LineBreak = do
+  emptyLine <- gets stEmptyLine
+  setEmptyLine True
+  return $ (if emptyLine then "\\strut " else "") <> "\\\\" <> cr
+inlineToLaTeX SoftBreak = do
+  wrapText <- gets (writerWrapText . stOptions)
+  case wrapText of
+       WrapAuto     -> return space
+       WrapNone     -> return space
+       WrapPreserve -> return cr
+inlineToLaTeX Space = return space
+inlineToLaTeX (Link (id',_,_) txt (src,_)) =
+   (case T.uncons src of
+     Just ('#', ident) -> do
+        contents <- inlineListToLaTeX txt
+        lab <- toLabel ident
+        inCite <- gets stInCite
+        beamer <- gets stBeamer
+        return $
+          if inCite && "#ref-" `T.isPrefixOf` src
+             then "\\citeproc" <> braces (literal lab) <> braces contents
+             else if beamer
+                     then "\\hyperlink" <> braces (literal lab) <> braces contents
+                     else "\\hyperref" <> brackets (literal lab) <> braces contents
+     _ -> case txt of
+          -- For soul sommands we need to protect \url and \href in an mbox or
+          -- we get an error (see #9366)
+          [Str x] | T.all isAscii x  -- see #8802
+                  , unEscapeString (T.unpack x) ==
+                    unEscapeString (T.unpack src) ->  -- autolink
+               do modify $ \s -> s{ stUrl = True }
+                  src' <- stringToLaTeX URLString (escapeURI src)
+                  protectInMboxIfInSoul $ literal $ "\\url{" <> src' <> "}"
+          [Str x] | Just rest <- T.stripPrefix "mailto:" src,
+                    unEscapeString (T.unpack x) == unEscapeString (T.unpack rest) -> -- email autolink
+               do modify $ \s -> s{ stUrl = True }
+                  src' <- stringToLaTeX URLString (escapeURI src)
+                  contents <- inlineListToLaTeX txt
+                  protectInMboxIfInSoul $ "\\href" <> braces (literal src') <>
+                     braces ("\\nolinkurl" <> braces contents)
+          _ -> do contents <- inlineListToLaTeX txt
+                  src' <- stringToLaTeX URLString (escapeURI src)
+                  protectInMboxIfInSoul $ literal ("\\href{" <> src' <> "}{") <>
+                    contents <> char '}')
+     >>= (if T.null id'
+             then return
+             else \x -> do
+               linkAnchor <- hypertarget id'
+               return (linkAnchor <> x))
+inlineToLaTeX il@(Image _ _ (src, _))
+  | Just _ <- T.stripPrefix "data:" src = do
+      report $ InlineNotRendered il
+      return empty
+inlineToLaTeX (Image attr@(_,_,kvs) description (source, _)) = do
+  setEmptyLine False
+  let isSVG = ".svg" `T.isSuffixOf` source || ".SVG" `T.isSuffixOf` source
+  modify $ \s -> s{ stGraphics = True
+                  , stSVG = stSVG s || isSVG }
+  opts <- gets stOptions
+  mbalt <- if isSVG
+              then pure Nothing
+              else case lookup "alt" kvs of
+                     Just x -> Just <$> stringToLaTeX TextString x
+                     Nothing
+                       | null description -> pure Nothing
+                       | otherwise -> Just <$> stringToLaTeX TextString
+                                                  (stringify description)
+  let showDim dir = let d = text (show dir) <> "="
+                    in case dimension dir attr of
+                         Just (Pixel a)   ->
+                           [d <> literal (showInInch opts (Pixel a)) <> "in"]
+                         Just (Percent a) ->
+                           [d <> literal (showFl (a / 100)) <>
+                             case dir of
+                                Width  -> "\\linewidth"
+                                Height -> "\\textheight"
+                           ]
+                         Just dim         ->
+                           [d <> text (show dim)]
+                         Nothing          ->
+                           case dir of
+                                Width | isJust (dimension Height attr) ->
+                                  [d <> "\\linewidth"]
+                                Height | isJust (dimension Width attr) ->
+                                  [d <> "\\textheight"]
+                                _ -> []
+      optList = showDim Width <> showDim Height <>
+                (case (dimension Height attr, dimension Width attr) of
+                  (Just _, Just _) -> []
+                  _ -> ["keepaspectratio"]) <>
+                maybe [] (\x -> ["page=" <> literal x]) (lookup "page" kvs) <>
+                maybe [] (\x -> ["trim=" <> literal x]) (lookup "trim" kvs) <>
+                maybe [] (\x -> ["alt=" <> braces (literal x)]) mbalt <>
+                maybe [] (const ["clip"]) (lookup "clip" kvs)
+      options = if null optList
+                   then empty
+                   else brackets $ mconcat (intersperse "," optList)
+      source' = if isURI source
+                   then source
+                   else T.pack $ unEscapeString $ T.unpack source
+  source'' <- stringToLaTeX URLString source'
+  inHeading <- gets stInHeading
+  return $
+    (if inHeading then "\\protect" else "") <>
+    (case dimension Width attr `mplus` dimension Height attr of
+       Just _ -> id
+       Nothing -> ("\\pandocbounded" <>) . braces)
+      ((if isSVG then "\\includesvg" else "\\includegraphics") <>
+        options <> braces (literal source''))
+inlineToLaTeX (Note contents) = do
+  setEmptyLine False
+  externalNotes <- gets stExternalNotes
+  modify (\s -> s{stInNote = True, stExternalNotes = True})
+  contents' <- blockListToLaTeX contents
+  modify (\s -> s {stInNote = False, stExternalNotes = externalNotes})
+  let optnl = case reverse contents of
+                   (CodeBlock _ _ : _) -> cr
+                   _                   -> empty
+  let noteContents = nest 2 contents' <> optnl
+  beamer <- gets stBeamer
+  -- in beamer slides, display footnote from current overlay forward
+  -- and ensure that the note is on the frame, not e.g. the column (#5769, #5954)
+  incremental <- gets stIncremental
+  let beamerMark = if beamer
+                      then if incremental
+                           then text "<.->[frame]"
+                           else text "<\\value{beamerpauses}->[frame]"
+                      else empty
+  if externalNotes
+     then do
+       modify $ \st -> st{ stNotes = noteContents : stNotes st }
+       return "\\footnotemark{}"
+       -- note: a \n before } needed when note ends with a Verbatim environment
+       else return $ "\\footnote" <> beamerMark <> braces noteContents
+
+-- A comment at the end of math needs to be followed by a newline,
+-- or the closing delimiter gets swallowed.
+handleMathComment :: Text -> Text
+handleMathComment s =
+  let (_, ys) = T.break (\c -> c == '\n' || c == '%') $ T.reverse s -- no T.breakEnd
+  in  case T.uncons ys of
+        Just ('%', ys') -> case T.uncons ys' of
+          Just ('\\', _) -> s
+          _              -> s <> "\n"
+        _                -> s
+
+setEmptyLine :: PandocMonad m => Bool -> LW m ()
+setEmptyLine b = modify $ \st -> st{ stEmptyLine = b }
+
+-- Extract a key from divs and spans
+extract :: Text -> Block -> [Text]
+extract key (Div attr _)     = lookKey key attr
+extract key (Plain ils)      = query (extractInline key) ils
+extract key (Para ils)       = query (extractInline key) ils
+extract key (Header _ _ ils) = query (extractInline key) ils
+extract _ _                  = []
+
+-- Extract a key from spans
+extractInline :: Text -> Inline -> [Text]
+extractInline key (Span attr _) = lookKey key attr
+extractInline _ _               = []
+
+-- Look up a key in an attribute and give a list of its values
+lookKey :: Text -> Attr -> [Text]
+lookKey key (_,_,kvs) =  maybe [] T.words $ lookup key kvs
+
+-- soul doesn't like \(..\) delimiters, so we change these to $ (#9597)
+-- when processing their contents.
+inSoulCommand :: PandocMonad m => LW m a -> LW m a
+inSoulCommand pa = do
+  oldInSoulCommand <- gets stInSoulCommand
+  modify $ \st -> st{ stInSoulCommand = True }
+  result <- pa
+  modify $ \st -> st{ stInSoulCommand = oldInSoulCommand }
+  pure result
+
+-- Inside soul commands some commands need to be protected in an mbox
+-- or we get an error (e.g. see #1294)
+protectInMboxIfInSoul :: (PandocMonad m, HasChars a) => Doc a -> LW m (Doc a)
+protectInMboxIfInSoul command = do
+  inSoul <- gets stInSoulCommand
+  return $ if inSoul
+    then "\\mbox" <> braces command
+    else command
+
+-- Babel languages with a .ldf that works well with all engines (see #8283).
+-- We follow the guidance from the Babel documentation:
+-- "In general, you should do this for European languages written in Latin
+-- and Cyrillic scripts, as well as for Vietnamese."
+ldfLanguages :: [Text]
+ldfLanguages =
+  [ "magyar"
+  , "croatian"
+  , "ngerman"
+  , "germanb"
+  , "german"
+  , "austrian"
+  , "ngermanb"
+  , "naustrian"
+  , "nswissgerman"
+  , "swissgerman"
+  , "italian"
+  , "greek"
+  , "azerbaijani"
+  , "american"
+  , "newzealand"
+  , "UKenglish"
+  , "USenglish"
+  , "australian"
+  , "british"
+  , "canadian"
+  , "english"
+  , "bahasa"
+  , "slovak"
+  , "finnish"
+  , "occitan"
+  , "swedish"
+  , "brazil"
+  , "portuguese"
+  , "portuges"
+  , "brazilian"
+  , "spanish"
+  , "norwegian"
+  , "norsk"
+  , "nynorsk"
+  , "bulgarian"
+  , "breton"
+  , "belarusian"
+  , "piedmontese"
+  , "esperanto"
+  , "lithuanian"
+  , "ukraineb"
+  , "scottishgaelic"
+  , "scottish"
+  , "dutch"
+  , "afrikaans"
+  , "czech"
+  , "serbian"
+  , "latvian"
+  , "catalan"
+  , "basque"
+  , "albanian"
+  , "irish"
+  , "serbianc"
+  , "interlingua"
+  , "bosnian"
+  , "friulan"
+  , "romanian"
+  , "icelandic"
+  , "classiclatin"
+  , "ecclesiasticlatin"
+  , "medievallatin"
+  , "latin"
+  , "georgian"
+  , "macedonian"
+  , "welsh"
+  , "vietnamese"
+  , "romansh"
+  , "danish"
+  , "lsorbian"
+  , "usorbian"
+  , "polish-compat"
+  , "polish"
+  , "estonian"
+  , "french"
+  , "frenchb"
+  , "canadien"
+  , "acadian"
+  , "francais"
+  , "turkish"
+  , "hindi"
+  , "northernsami"
+  , "samin"
+  , "russianb"
+  , "galician"
+  , "slovene"
+  ]
+
+isMathEnv :: Text -> Bool
+isMathEnv t =
+  case T.stripPrefix "\\begin{" (T.dropWhile isSpaceChar t) of
+    Nothing -> False
+    Just t' -> T.takeWhile (/= '}') t' `elem`
+      [ "align", "align*"
+      , "flalign", "flalign*"
+      , "alignat", "alignat*"
+      , "dmath", "dmath*"
+      , "dgroup", "dgroup*"
+      , "darray", "darray*"
+      , "gather", "gather*"
+      , "multline", "multline*"
+      , "subequations"
+      , "equation", "equation*"
+      , "eqnarray"
+      , "displaymath"
+      ]
+ where
+   isSpaceChar '\n' = True
+   isSpaceChar '\r' = True
+   isSpaceChar '\t' = True
+   isSpaceChar ' ' = True
+   isSpaceChar _ = False
+
+-- True if the math needs the cancel package
+needsCancel :: Text -> Bool
+needsCancel t =
+  case A.parseOnly pCancel t of
+    Right True -> True
+    _ -> False
+ where
+  pCancel = (False <$ A.endOfInput) <|> do
+    c <- A.anyChar
+    case c of
+      '\\' -> do
+        x <- A.takeWhile isLetter
+        if x == "cancel" || x == "xcancel" || x == "bcancel"
+           then return True
+           else pCancel
+      _ -> pCancel
+
+-- PDF standard support for DocumentMetadata
+
+-- | PDF standards supported by LaTeX's DocumentMetadata
+-- See: https://github.com/latex3/latex2e documentmetadata-support.dtx
+latexSupportedStandards :: Set.Set Text
+latexSupportedStandards = Set.fromList
+  [ -- PDF/A standards (note: a-1a is NOT supported by LaTeX, only a-1b)
+    "a-1b", "a-2a", "a-2b", "a-2u", "a-3a", "a-3b", "a-3u"
+  , "a-4", "a-4e", "a-4f"
+    -- PDF/X standards
+  , "x-4", "x-4p", "x-5g", "x-5n", "x-5pg", "x-6", "x-6n", "x-6p"
+    -- PDF/UA standards
+  , "ua-1", "ua-2"
+  ]
+
+-- | Standards that require PDF tagging (document structure)
+-- PDF/A level "a" variants and PDF/UA require tagged structure
+taggingRequiredStandards :: Set.Set Text
+taggingRequiredStandards = Set.fromList
+  ["a-2a", "a-3a", "ua-1", "ua-2"]
+
+-- | Valid PDF versions for DocumentMetadata
+validPdfVersions :: Set.Set Text
+validPdfVersions = Set.fromList
+  ["1.4", "1.5", "1.6", "1.7", "2.0"]
+
+-- | PDF version required by each standard
+-- LaTeX defaults to PDF 2.0 with \DocumentMetadata, but some standards
+-- have maximum version requirements that are incompatible with 2.0
+standardRequiredVersion :: M.Map Text Text
+standardRequiredVersion = M.fromList
+  [ ("a-1b", "1.4")  -- PDF/A-1 requires exactly PDF 1.4
+    -- PDF/A-2 and PDF/A-3 require 1.7; must set explicitly since LaTeX defaults to 2.0
+  , ("a-2a", "1.7"), ("a-2b", "1.7"), ("a-2u", "1.7")
+  , ("a-3a", "1.7"), ("a-3b", "1.7"), ("a-3u", "1.7")
+    -- PDF/A-4, PDF/UA-1, PDF/UA-2 work with PDF 2.0 (the default)
+  ]
+
+-- | Normalize a PDF standard string: lowercase, strip "pdf" prefix
+normalizePdfStandard :: Text -> Text
+normalizePdfStandard t =
+  let lower = T.toLower t
+  in case T.stripPrefix "pdf" lower of
+       Just rest -> T.dropWhile (`elem` ['-', '/']) rest
+       Nothing   -> lower
+
+-- | Normalize a PDF version string
+-- Handles YAML parsing quirk where 2.0 becomes integer 2, then string "2"
+normalizeVersion :: Text -> Text
+normalizeVersion t
+  | t == "2" = "2.0"
+  | otherwise = t
+
+-- | Check if text is a valid PDF version (after normalization)
+isPdfVersion :: Text -> Bool
+isPdfVersion t = Set.member (normalizeVersion t) validPdfVersions
+
+-- | Process pdfstandard metadata, returning PDF standard settings
+processPdfStandard :: PandocMonad m
+                   => Context Text
+                   -> m PdfStandard
+processPdfStandard ctx = do
+  let standards = fromMaybe [] $ getField "pdfstandard" ctx
+      normalized = map normalizePdfStandard standards
+      (versions, pdfStds) = partition isPdfVersion normalized
+      validStandards = filter (`Set.member` latexSupportedStandards) pdfStds
+      invalidStandards = filter (\s -> not (Set.member s latexSupportedStandards)
+                                    && not (isPdfVersion s)) pdfStds
+      needsTagging = any (`Set.member` taggingRequiredStandards) validStandards
+      -- Use explicit version if provided, otherwise infer from standards
+      -- Apply normalizeVersion to handle YAML parsing "2" -> "2.0"
+      explicitVersion = normalizeVersion <$> listToMaybe versions
+      inferredVersion = listToMaybe $ mapMaybe (`M.lookup` standardRequiredVersion) validStandards
+      version = explicitVersion <|> inferredVersion
+  -- Warn about unsupported standards
+  mapM_ (report . UnsupportedPdfStandard) invalidStandards
+  return PdfStandard
+    { pdfStandards = validStandards
+    , pdfVersion = version
+    , pdfTagging = needsTagging
+    }
diff --git a/src/Text/Pandoc/Writers/LaTeX/Caption.hs b/src/Text/Pandoc/Writers/LaTeX/Caption.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Writers/LaTeX/Caption.hs
@@ -0,0 +1,58 @@
+{- |
+   Module      : Text.Pandoc.Writers.LaTeX.Caption
+   Copyright   : Copyright (C) 2006-2024 John MacFarlane
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : John MacFarlane <jgm@berkeley.edu>
+   Stability   : alpha
+   Portability : portable
+
+Write figure or table captions as LaTeX.
+-}
+module Text.Pandoc.Writers.LaTeX.Caption
+  ( getCaption
+  ) where
+
+import Control.Monad.State.Strict
+import Data.Monoid (Any(..))
+import Data.Text (Text)
+import Text.Pandoc.Class.PandocMonad (PandocMonad)
+import Text.Pandoc.Definition
+import Text.DocLayout (Doc, brackets, empty)
+import Text.Pandoc.Shared
+import Text.Pandoc.Walk
+import Text.Pandoc.Writers.LaTeX.Notes (notesToLaTeX)
+import Text.Pandoc.Writers.LaTeX.Types
+  ( LW, WriterState (stExternalNotes, stNotes, stInCaption) )
+
+
+-- | Produces the components of a LaTeX 'caption' command. Returns a triple
+-- containing the caption text, the short caption for the list of
+-- figures/tables, and the footnote definitions.
+getCaption :: PandocMonad m
+           => ([Inline] -> LW m (Doc Text)) -- ^ inlines converter
+           -> Bool                          -- ^ whether to extract notes
+           -> Caption
+           -> LW m (Doc Text, Doc Text, Doc Text)
+getCaption inlineListToLaTeX externalNotes (Caption maybeShort long) = do
+  modify $ \st -> st{ stInCaption = True }
+  let long' = blocksToInlines long
+  oldExternalNotes <- gets stExternalNotes
+  modify $ \st -> st{ stExternalNotes = externalNotes, stNotes = [] }
+  capt <- inlineListToLaTeX long'
+  footnotes <- if externalNotes
+                  then notesToLaTeX <$> gets stNotes
+                  else return empty
+  modify $ \st -> st{ stExternalNotes = oldExternalNotes, stNotes = [] }
+  -- We can't have footnotes in the list of figures/tables, so remove them:
+  let getNote (Note _) = Any True
+      getNote _        = Any False
+  let hasNotes = getAny . query getNote
+  let toShortCapt = fmap brackets . inlineListToLaTeX . walk deNote
+  captForLof <- case maybeShort of
+                  Nothing -> if hasNotes long'
+                             then toShortCapt long'
+                             else return empty
+                  Just short -> toShortCapt short
+  modify $ \st -> st{ stInCaption = False }
+  return (capt, captForLof, footnotes)
diff --git a/src/Text/Pandoc/Writers/LaTeX/Citation.hs b/src/Text/Pandoc/Writers/LaTeX/Citation.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Writers/LaTeX/Citation.hs
@@ -0,0 +1,209 @@
+{-# LANGUAGE OverloadedStrings #-}
+{- |
+   Module      : Text.Pandoc.Writers.LaTeX.Citation
+   Copyright   : Copyright (C) 2006-2024 John MacFarlane
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : John MacFarlane <jgm@berkeley.edu>
+   Stability   : alpha
+   Portability : portable
+-}
+module Text.Pandoc.Writers.LaTeX.Citation
+  ( citationsToNatbib,
+    citationsToBiblatex
+  ) where
+
+import Data.Text (Text)
+import Data.Char (isPunctuation)
+import Control.Monad.State (gets)
+import Data.Maybe (fromMaybe)
+import qualified Data.Text as T
+import Text.Pandoc.Options
+import Text.Pandoc.Class.PandocMonad (PandocMonad)
+import Text.Pandoc.Definition
+import qualified Data.List as L
+import Text.DocLayout (Doc, brackets, empty, (<+>), text, isEmpty, literal,
+                       braces)
+import Text.Pandoc.Walk
+import Text.Pandoc.Writers.LaTeX.Types ( LW, WriterState(stLang, stOptions) )
+import Text.Pandoc.Citeproc.Locator (parseLocator, LocatorInfo(..),
+                                     toLocatorMap)
+import Citeproc.Types (Lang(..))
+import Citeproc.Locale (getLocale)
+import Safe (headMay, lastMay)
+
+citationsToNatbib :: PandocMonad m
+                  => ([Inline] -> LW m (Doc Text))
+                  -> [Citation]
+                  -> LW m (Doc Text)
+citationsToNatbib inlineListToLaTeX [one]
+  = citeCommand inlineListToLaTeX c p s k
+  where
+    Citation { citationId = k
+             , citationPrefix = p
+             , citationSuffix = s
+             , citationMode = m
+             }
+      = one
+    c = case m of
+             AuthorInText   -> "citet"
+             SuppressAuthor -> "citeyearpar"
+             NormalCitation -> "citep"
+
+citationsToNatbib inlineListToLaTeX cits
+  | noInnerPrefix cits && noInnerSuffix cits && ismode NormalCitation cits
+  = citeCommand inlineListToLaTeX "citep" p s ks
+  where
+     noInnerPrefix []     = True
+     noInnerPrefix (_:xs) = all (null . citationPrefix) xs
+     noInnerSuffix []     = True
+     noInnerSuffix [_]    = True
+     noInnerSuffix (x:xs) = null (citationSuffix x) && noInnerSuffix xs
+     ismode m  = all ((==) m  . citationMode)
+     p         = maybe mempty citationPrefix $ headMay cits
+     s         = maybe mempty citationSuffix $ lastMay cits
+     ks        = T.intercalate ", " $ map citationId cits
+
+citationsToNatbib inlineListToLaTeX (c:cs)
+  | citationMode c == AuthorInText = do
+     author <- citeCommand inlineListToLaTeX "citeauthor" [] [] (citationId c)
+     cits   <- citationsToNatbib inlineListToLaTeX
+                  (c { citationMode = SuppressAuthor } : cs)
+     return $ author <+> cits
+
+citationsToNatbib inlineListToLaTeX cits = do
+  cits' <- mapM convertOne cits
+  return $ text "\\citetext{" <> L.foldl' combineTwo empty cits' <> text "}"
+  where
+    citeCommand' = citeCommand inlineListToLaTeX
+    combineTwo a b | isEmpty a = b
+                   | otherwise = a <> text "; " <> b
+    convertOne Citation { citationId = k
+                        , citationPrefix = p
+                        , citationSuffix = s
+                        , citationMode = m
+                        }
+        = case m of
+               AuthorInText   -> citeCommand' "citealt"  p s k
+               SuppressAuthor -> citeCommand' "citeyear" p s k
+               NormalCitation -> citeCommand' "citealp"  p s k
+
+citeCommand :: PandocMonad m
+            => ([Inline] -> LW m (Doc Text))
+            -> Text
+            -> [Inline]
+            -> [Inline]
+            -> Text
+            -> LW m (Doc Text)
+citeCommand inlineListToLaTeX c p s k = do
+  args <- citeArguments inlineListToLaTeX p s k
+  return $ literal ("\\" <> c) <> args
+
+type Prefix = [Inline]
+type Suffix = [Inline]
+type CiteId = Text
+data CiteGroup = CiteGroup Prefix Suffix [CiteId]
+
+citeArgumentsList :: PandocMonad m
+              => ([Inline] -> LW m (Doc Text))
+              -> CiteGroup
+              -> LW m (Doc Text)
+citeArgumentsList _inlineListToLaTeX (CiteGroup _ _ []) = return empty
+citeArgumentsList inlineListToLaTeX (CiteGroup pfxs sfxs ids) = do
+      opts <- gets stOptions
+      mblang <- gets stLang
+      let sfxs' = (case writerCiteMethod opts of
+                     -- In biblatex, the label p. or pp. can be omitted;
+                     -- ranges are treated as page ranges by default. See #9275.
+                     Biblatex -> removePageLabel mblang
+                     _ -> id) $
+              stripLocatorBraces $ case sfxs of
+                (Str t : r) -> case T.uncons t of
+                  Just (x, xs)
+                    | T.null xs
+                    , isPunctuation x -> dropWhile (== Space) r
+                    | isPunctuation x -> Str xs : r
+                  _ -> sfxs
+                _   -> sfxs
+          optargs pdoc sdoc = case (isEmpty pdoc, isEmpty sdoc) of
+                 (True, True ) -> empty
+                 (True, False) -> brackets sdoc
+                 (_   , _    ) -> brackets pdoc <> brackets sdoc
+      pdoc <- inlineListToLaTeX pfxs
+      sdoc <- inlineListToLaTeX sfxs'
+      return $ optargs pdoc sdoc <>
+              braces (literal (T.intercalate "," (reverse ids)))
+
+citeArguments :: PandocMonad m
+              => ([Inline] -> LW m (Doc Text))
+              -> [Inline]
+              -> [Inline]
+              -> Text
+              -> LW m (Doc Text)
+citeArguments inlineListToLaTeX p s k =
+  citeArgumentsList inlineListToLaTeX (CiteGroup p s [k])
+
+-- strip off {} used to define locator in pandoc-citeproc; see #5722
+stripLocatorBraces :: [Inline] -> [Inline]
+stripLocatorBraces = walk go
+  where go (Str xs) = Str $ T.filter (\c -> c /= '{' && c /= '}') xs
+        go x        = x
+
+citationsToBiblatex :: PandocMonad m
+                    => ([Inline] -> LW m (Doc Text))
+                    -> [Citation] -> LW m (Doc Text)
+citationsToBiblatex inlineListToLaTeX [one]
+  = citeCommand inlineListToLaTeX cmd p s k
+    where
+       Citation { citationId = k
+                , citationPrefix = p
+                , citationSuffix = s
+                , citationMode = m
+                } = one
+       cmd = case m of
+                  SuppressAuthor -> "autocite*"
+                  AuthorInText   -> "textcite"
+                  NormalCitation -> "autocite"
+
+citationsToBiblatex inlineListToLaTeX (c:cs)
+  | all (\cit -> null (citationPrefix cit) && null (citationSuffix cit)) (c:cs)
+    = do
+      let cmd = case citationMode c of
+                    SuppressAuthor -> "\\autocite*"
+                    AuthorInText   -> "\\textcite"
+                    NormalCitation -> "\\autocite"
+      return $ text cmd <>
+               braces (literal (T.intercalate "," (map citationId (c:cs))))
+  | otherwise
+    = do
+      let cmd = case citationMode c of
+                    SuppressAuthor -> "\\autocites*"
+                    AuthorInText   -> "\\textcites"
+                    NormalCitation -> "\\autocites"
+
+      groups <- mapM (citeArgumentsList inlineListToLaTeX)
+                     (reverse (L.foldl' grouper [] (c:cs)))
+
+      return $ text cmd <> mconcat groups
+
+  where grouper prev cit = case prev of
+         ((CiteGroup oPfx [] ids):rest)
+             | null pfx && null sfx
+           -> CiteGroup oPfx sfx (cid:ids) : rest
+         _ -> CiteGroup pfx sfx [cid] : prev
+         where pfx = citationPrefix cit
+               sfx = citationSuffix cit
+               cid = citationId cit
+
+citationsToBiblatex _ _ = return empty
+
+removePageLabel :: Maybe Lang -> [Inline] -> [Inline]
+removePageLabel mblang ils =
+  case mbLocinfo of
+    Just locinfo | locatorLabel locinfo == "page"
+      -> Str (locatorLoc locinfo) : ils'
+    _ -> ils
+ where
+   (mbLocinfo, ils') = parseLocator (toLocatorMap locale) ils
+   lang = fromMaybe (Lang "en" Nothing (Just "US") [] [] []) mblang
+   locale = either mempty id $ getLocale lang
diff --git a/src/Text/Pandoc/Writers/LaTeX/Lang.hs b/src/Text/Pandoc/Writers/LaTeX/Lang.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Writers/LaTeX/Lang.hs
@@ -0,0 +1,152 @@
+{-# LANGUAGE OverloadedStrings   #-}
+{-# LANGUAGE ScopedTypeVariables #-}
+{- |
+   Module      : Text.Pandoc.Writers.LaTeX.Lang
+   Copyright   : Copyright (C) 2006-2024 John MacFarlane
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : John MacFarlane <jgm@berkeley.edu>
+   Stability   : alpha
+   Portability : portable
+-}
+module Text.Pandoc.Writers.LaTeX.Lang
+  ( toBabel
+  ) where
+import Data.Text (Text)
+import Text.Collate.Lang (Lang(..))
+
+
+-- Takes a list of the constituents of a BCP47 language code and
+-- converts it to a Babel language string.
+-- http://mirrors.ctan.org/macros/latex/required/babel/base/babel.pdf
+-- List of supported languages (slightly outdated):
+-- http://tug.ctan.org/language/hyph-utf8/doc/generic/hyph-utf8/hyphenation.pdf
+toBabel :: Lang -> Maybe Text
+toBabel (Lang "de" _ (Just "AT") vars _ _)
+  | "1901" `elem` vars                  = Just "austrian"
+  | otherwise                           = Just "naustrian"
+toBabel (Lang "de" _ (Just "CH") vars _ _)
+  | "1901" `elem` vars                  = Just "swissgerman"
+  | otherwise                           = Just "nswissgerman"
+toBabel (Lang "de" _ _ vars _ _)
+  | "1901" `elem` vars                  = Just "german"
+  | otherwise                           = Just "ngerman"
+toBabel (Lang "dsb" _ _ _ _ _)          = Just "lowersorbian"
+toBabel (Lang "el" _ _ vars _ _)
+  | "polyton" `elem` vars               = Just "polytonicgreek"
+toBabel (Lang "en" _ (Just "AU") _ _ _) = Just "australian"
+toBabel (Lang "en" _ (Just "CA") _ _ _) = Just "canadian"
+toBabel (Lang "en" _ (Just "GB") _ _ _) = Just "british"
+toBabel (Lang "en" _ (Just "NZ") _ _ _) = Just "newzealand"
+toBabel (Lang "en" _ (Just "UK") _ _ _) = Just "british"
+toBabel (Lang "en" _ (Just "US") _ _ _) = Just "american"
+toBabel (Lang "fr" _ (Just "CA") _ _ _) = Just "french"
+toBabel (Lang "fra" _ _ vars _ _)
+  | "aca" `elem` vars                   = Just "acadian"
+toBabel (Lang "grc" _ _ _ _ _)          = Just "ancientgreek"
+toBabel (Lang "hsb" _ _ _ _ _)          = Just "uppersorbian"
+toBabel (Lang "la" _ _ vars _ _)
+  | "x-classic" `elem` vars             = Just "classiclatin"
+toBabel (Lang "pt" _ (Just "BR") _ _ _) = Just "brazilian"
+toBabel (Lang "sl" _ _ _ _ _)           = Just "slovene"
+toBabel (Lang "zh" (Just "Hant") (Just "HK") _ _ _) = Just "chinese-hant-hk"
+toBabel (Lang "zh" (Just "Hant") (Just "MO") _ _ _) = Just "chinese-hant-mo"
+toBabel (Lang "zh" (Just "Hans") (Just "HK") _ _ _) = Just "chinese-hans-hk"
+toBabel (Lang "zh" (Just "Hans") (Just "MO") _ _ _) = Just "chinese-hans-mo"
+toBabel (Lang "zh" (Just "Hans") _ _ _ _) = Just "chinese-hans"
+toBabel (Lang "zh" (Just "Hant") _ _ _ _) = Just "chinese-hant"
+toBabel (Lang "zh" _ _ _ _ _)             = Just "chinese"
+toBabel x                                 = commonFromBcp47 x
+
+-- Takes a list of the constituents of a BCP47 language code
+-- and converts it to a string shared by Babel and Polyglossia.
+-- https://tools.ietf.org/html/bcp47#section-2.1
+commonFromBcp47 :: Lang -> Maybe Text
+commonFromBcp47 (Lang "sr" (Just "Cyrl") _ _ _ _)      = Just "serbianc"
+commonFromBcp47 (Lang "zh" (Just "Latn") _ vars _ _)
+  | "pinyin" `elem` vars                               = Just "pinyin"
+commonFromBcp47 (Lang l _ _ _ _ _) = fromIso l
+  where
+    fromIso "af"  = Just "afrikaans"
+    fromIso "am"  = Just "amharic"
+    fromIso "ar"  = Just "arabic"
+    fromIso "as"  = Just "assamese"
+    fromIso "ast" = Just "asturian"
+    fromIso "bg"  = Just "bulgarian"
+    fromIso "bn"  = Just "bengali"
+    fromIso "bo"  = Just "tibetan"
+    fromIso "br"  = Just "breton"
+    fromIso "ca"  = Just "catalan"
+    fromIso "cy"  = Just "welsh"
+    fromIso "cs"  = Just "czech"
+    fromIso "cop" = Just "coptic"
+    fromIso "da"  = Just "danish"
+    fromIso "dv"  = Just "divehi"
+    fromIso "el"  = Just "greek"
+    fromIso "en"  = Just "english"
+    fromIso "eo"  = Just "esperanto"
+    fromIso "es"  = Just "spanish"
+    fromIso "et"  = Just "estonian"
+    fromIso "eu"  = Just "basque"
+    fromIso "fa"  = Just "persian"
+    fromIso "fi"  = Just "finnish"
+    fromIso "fr"  = Just "french"
+    fromIso "fur" = Just "friulan"
+    fromIso "ga"  = Just "irish"
+    fromIso "gd"  = Just "scottish"
+    fromIso "gez" = Just "ethiopic"
+    fromIso "gl"  = Just "galician"
+    fromIso "gu"  = Just "gujarati"
+    fromIso "he"  = Just "hebrew"
+    fromIso "hi"  = Just "hindi"
+    fromIso "hr"  = Just "croatian"
+    fromIso "hu"  = Just "magyar"
+    fromIso "hy"  = Just "armenian"
+    fromIso "ia"  = Just "interlingua"
+    fromIso "id"  = Just "indonesian"
+    fromIso "ie"  = Just "interlingua"
+    fromIso "is"  = Just "icelandic"
+    fromIso "it"  = Just "italian"
+    fromIso "ja"  = Just "japanese"
+    fromIso "km"  = Just "khmer"
+    fromIso "kmr" = Just "kurmanji"
+    fromIso "kn"  = Just "kannada"
+    fromIso "ko"  = Just "korean"
+    fromIso "la"  = Just "latin"
+    fromIso "lo"  = Just "lao"
+    fromIso "lt"  = Just "lithuanian"
+    fromIso "lv"  = Just "latvian"
+    fromIso "ml"  = Just "malayalam"
+    fromIso "mn"  = Just "mongolian"
+    fromIso "mr"  = Just "marathi"
+    fromIso "nb"  = Just "norsk"
+    fromIso "nl"  = Just "dutch"
+    fromIso "nn"  = Just "nynorsk"
+    fromIso "no"  = Just "norsk"
+    fromIso "nqo" = Just "nko"
+    fromIso "oc"  = Just "occitan"
+    fromIso "or"  = Just "oriya"
+    fromIso "pa"  = Just "punjabi"
+    fromIso "pl"  = Just "polish"
+    fromIso "pms" = Just "piedmontese"
+    fromIso "pt"  = Just "portuguese"
+    fromIso "rm"  = Just "romansh"
+    fromIso "ro"  = Just "romanian"
+    fromIso "ru"  = Just "russian"
+    fromIso "sa"  = Just "sanskrit"
+    fromIso "se"  = Just "samin"
+    fromIso "sk"  = Just "slovak"
+    fromIso "sq"  = Just "albanian"
+    fromIso "sr"  = Just "serbian"
+    fromIso "sv"  = Just "swedish"
+    fromIso "syr" = Just "syriac"
+    fromIso "ta"  = Just "tamil"
+    fromIso "te"  = Just "telugu"
+    fromIso "th"  = Just "thai"
+    fromIso "ti"  = Just "ethiopic"
+    fromIso "tk"  = Just "turkmen"
+    fromIso "tr"  = Just "turkish"
+    fromIso "uk"  = Just "ukrainian"
+    fromIso "ur"  = Just "urdu"
+    fromIso "vi"  = Just "vietnamese"
+    fromIso _     = Nothing
diff --git a/src/Text/Pandoc/Writers/LaTeX/Notes.hs b/src/Text/Pandoc/Writers/LaTeX/Notes.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Writers/LaTeX/Notes.hs
@@ -0,0 +1,34 @@
+{-# LANGUAGE LambdaCase        #-}
+{-# LANGUAGE OverloadedStrings #-}
+{- |
+   Module      : Text.Pandoc.Writers.LaTeX.Notes
+   Copyright   : Copyright (C) 2006-2024 John MacFarlane
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : John MacFarlane <jgm@berkeley.edu>
+   Stability   : alpha
+   Portability : portable
+
+Output tables as LaTeX.
+-}
+module Text.Pandoc.Writers.LaTeX.Notes
+  ( notesToLaTeX
+  ) where
+
+import Data.List (intersperse)
+import Text.DocLayout ( Doc, braces, empty, text, vcat, ($$))
+import Data.Text (Text)
+
+notesToLaTeX :: [Doc Text] -> Doc Text
+notesToLaTeX = \case
+  [] -> empty
+  ns -> (case length ns of
+            n | n > 1 -> "\\addtocounter" <>
+                         braces "footnote" <>
+                         braces (text $ show $ 1 - n)
+              | otherwise -> empty)
+        $$
+        vcat (intersperse
+               ("\\addtocounter" <> braces "footnote" <> braces "1")
+               $ map (\x -> "\\footnotetext" <> braces x)
+               $ reverse ns)
diff --git a/src/Text/Pandoc/Writers/LaTeX/Table.hs b/src/Text/Pandoc/Writers/LaTeX/Table.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Writers/LaTeX/Table.hs
@@ -0,0 +1,434 @@
+{-# LANGUAGE LambdaCase        #-}
+{-# LANGUAGE OverloadedStrings #-}
+{- |
+   Module      : Text.Pandoc.Writers.LaTeX.Table
+   Copyright   : Copyright (C) 2006-2024 John MacFarlane
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : John MacFarlane <jgm@berkeley.edu>
+   Stability   : alpha
+   Portability : portable
+
+Output LaTeX formatted tables.
+-}
+module Text.Pandoc.Writers.LaTeX.Table
+  ( tableToLaTeX
+  ) where
+import Control.Monad.State.Strict ( gets, modify )
+import Control.Monad (when)
+import Data.List (intersperse)
+import qualified Data.List.NonEmpty as NonEmpty
+import Data.List.NonEmpty (NonEmpty ((:|)))
+import Data.Text (Text)
+import qualified Data.Text as T
+import Text.Pandoc.Class.PandocMonad (PandocMonad)
+import Text.Pandoc.Definition
+import Text.DocLayout
+  ( Doc, braces, cr, empty, hcat, hsep, isEmpty, literal, nest
+  , text, vcat, ($$) )
+import Text.Pandoc.Shared (splitBy, tshow)
+import Text.Pandoc.Walk (walk, query)
+import Data.Monoid (Any(..))
+import Text.Pandoc.Writers.LaTeX.Caption (getCaption)
+import Text.Pandoc.Writers.LaTeX.Notes (notesToLaTeX)
+import Text.Pandoc.Writers.LaTeX.Types
+  ( LW, WriterState (stBeamer, stExternalNotes, stInMinipage, stMultiRow
+                    , stNotes, stTable, stOptions) )
+import Text.Pandoc.Writers.LaTeX.Util (labelFor)
+import Text.Printf (printf)
+import qualified Text.Pandoc.Builder as B
+import qualified Text.Pandoc.Writers.AnnotatedTable as Ann
+import Text.Pandoc.Options (CaptionPosition(..), WriterOptions(..))
+
+tableToLaTeX :: PandocMonad m
+             => ([Inline] -> LW m (Doc Text))
+             -> ([Block]  -> LW m (Doc Text))
+             -> Ann.Table
+             -> LW m (Doc Text)
+tableToLaTeX inlnsToLaTeX blksToLaTeX tbl = do
+  opts <- gets stOptions
+  let (Ann.Table (ident, _, _) caption specs thead tbodies tfoot) = tbl
+  CaptionDocs capt captNotes <- captionToLaTeX inlnsToLaTeX caption ident
+  let hasTopCaption = not (isEmpty capt) &&
+                        writerTableCaptionPosition opts == CaptionAbove
+  let hasBottomCaption = not (isEmpty capt) &&
+                          writerTableCaptionPosition opts == CaptionBelow
+  let isSimpleTable =
+        all ((== ColWidthDefault) . snd) specs &&
+        all (all isSimpleCell)
+          (mconcat [ headRows thead
+                   , concatMap bodyRows tbodies
+                   , footRows tfoot
+                   ])
+  let removeNote (Note _) = Span ("", [], []) []
+      removeNote x        = x
+  let colCount = ColumnCount $ length specs
+  -- The first head is not repeated on the following pages. If we were to just
+  -- use a single head, without a separate first head, then the caption would be
+  -- repeated on all pages that contain a part of the table. We avoid this by
+  -- making the caption part of the first head. The downside is that we must
+  -- duplicate the header rows for this.
+  head' <- do
+    let mkHead = headToLaTeX blksToLaTeX isSimpleTable colCount
+    case (hasTopCaption, isEmptyHead thead) of
+      (False, True) -> return "\\toprule\\noalign{}"
+      (False, False)  -> mkHead thead
+      (True, True)  -> return (capt <> "\\tabularnewline"
+                                $$ "\\toprule\\noalign{}"
+                                $$ "\\endfirsthead")
+      (True, False)   -> do
+        -- avoid duplicate notes in head and firsthead:
+        firsthead <- mkHead thead
+        repeated  <- mkHead (walk removeNote thead)
+        return $ capt <> "\\tabularnewline"
+                 $$ firsthead
+                 $$ "\\endfirsthead"
+                 $$ repeated
+  rows' <- mapM (rowToLaTeX blksToLaTeX isSimpleTable colCount BodyCell) $
+                mconcat (map bodyRows tbodies)
+  lastfoot <- mapM (rowToLaTeX blksToLaTeX isSimpleTable colCount BodyCell) $
+                    footRows tfoot
+  let foot' = (if isEmptyFoot tfoot
+                  then mempty
+                  else "\\midrule\\noalign{}" $$ vcat lastfoot)
+              $$ "\\bottomrule\\noalign{}"
+              $$ (if hasBottomCaption
+                     then "\\tabularnewline" $$ capt
+                     else mempty)
+  modify $ \s -> s{ stTable = True }
+  notes <- notesToLaTeX <$> gets stNotes
+  beamer <- gets stBeamer
+  let makeUnnumbered x = "{\\def\\LTcaptype{none} % do not increment counter" $$ x $$ "}"
+  return
+    $ (if null capt then makeUnnumbered else id)
+    $ "\\begin{longtable}[]" <>
+          braces ("@{}" <> colDescriptors isSimpleTable tbl <> "@{}")
+          -- the @{} removes extra space at beginning and end
+    $$ head'
+    $$ "\\endhead"
+    $$ vcat
+       -- Longtable is not able to detect pagebreaks in Beamer; this
+       -- causes problems with the placement of the footer, so make
+       -- footer and bottom rule part of the body when targeting Beamer.
+       -- See issue #8638.
+       (if beamer
+             then [ vcat rows'
+                  , foot'
+                  ]
+             else [ foot'
+                  , "\\endlastfoot"
+                  ,  vcat rows'
+                  ])
+    $$ "\\end{longtable}"
+    $$ captNotes
+    $$ notes
+
+isSimpleCell :: Ann.Cell -> Bool
+isSimpleCell (Ann.Cell _ _ (Cell _attr _align _rowspan _colspan blocks)) =
+  case blocks of
+    [Para _]  -> not (hasLineBreak blocks)
+    [Plain _] -> not (hasLineBreak blocks)
+    []        -> True
+    _         -> False
+  where
+    hasLineBreak = getAny . query isLineBreak
+    isLineBreak LineBreak = Any True
+    isLineBreak _         = Any False
+
+-- | Total number of columns in a table.
+newtype ColumnCount = ColumnCount Int
+
+-- | Creates column descriptors for the table.
+colDescriptors :: Bool -> Ann.Table -> Doc Text
+colDescriptors isSimpleTable
+               (Ann.Table _attr _caption specs _thead _tbodies _tfoot) =
+  let (aligns, widths) = unzip specs
+
+      defaultWidthsOnly = all (== ColWidthDefault) widths
+
+      relativeWidths = if defaultWidthsOnly
+                       then replicate (length specs)
+                            (1 / fromIntegral (length specs))
+                       else map toRelWidth widths
+  in if null aligns
+        then "l"  -- #9350, table needs at least one column spec
+        else if defaultWidthsOnly && isSimpleTable
+                then hcat $ map (literal . colAlign) aligns
+                else (cr <>) . nest 2 . vcat . map literal $
+                     zipWith (toColDescriptor (length specs))
+                             aligns
+                             relativeWidths
+  where
+    toColDescriptor :: Int -> Alignment -> Double -> Text
+    toColDescriptor numcols align width =
+      T.pack $ printf
+      ">{%s\\arraybackslash}p{(\\linewidth - %d\\tabcolsep) * \\real{%0.4f}}"
+      (T.unpack (alignCommand align))
+      ((numcols - 1) * 2)
+      width
+
+    toRelWidth ColWidthDefault = 0
+    toRelWidth (ColWidth w)    = w
+
+alignCommand :: Alignment -> Text
+alignCommand = \case
+  AlignLeft    -> "\\raggedright"
+  AlignRight   -> "\\raggedleft"
+  AlignCenter  -> "\\centering"
+  AlignDefault -> "\\raggedright"
+
+colAlign :: Alignment -> Text
+colAlign = \case
+  AlignLeft    -> "l"
+  AlignRight   -> "r"
+  AlignCenter  -> "c"
+  AlignDefault -> "l"
+
+data CaptionDocs =
+  CaptionDocs
+  { captionCommand :: Doc Text
+  , captionNotes :: Doc Text
+  }
+
+captionToLaTeX :: PandocMonad m
+               => ([Inline] -> LW m (Doc Text))
+               -> Caption
+               -> Text     -- ^ table identifier (label)
+               -> LW m CaptionDocs
+captionToLaTeX inlnsToLaTeX caption ident = do
+  (captionText, captForLot, captNotes) <- getCaption inlnsToLaTeX False caption
+  label <- labelFor ident
+  return $ CaptionDocs
+    { captionNotes = captNotes
+    , captionCommand = if isEmpty captionText && isEmpty label
+                       then empty
+                       else "\\caption" <> captForLot <>
+                            braces captionText
+                            <> label
+    }
+
+type BlocksWriter m = [Block] -> LW m (Doc Text)
+
+headToLaTeX :: PandocMonad m
+            => BlocksWriter m
+            -> Bool
+            -> ColumnCount
+            -> Ann.TableHead
+            -> LW m (Doc Text)
+headToLaTeX blocksWriter isSimpleTable
+            colCount (Ann.TableHead _attr headerRows) = do
+  rowsContents <-
+    mapM (rowToLaTeX blocksWriter isSimpleTable
+           colCount HeaderCell . headerRowCells)
+         headerRows
+  return ("\\toprule\\noalign{}" $$ vcat rowsContents $$ "\\midrule\\noalign{}")
+
+-- | Converts a row of table cells into a LaTeX row.
+rowToLaTeX :: PandocMonad m
+           => BlocksWriter m
+           -> Bool
+           -> ColumnCount
+           -> CellType
+           -> [Ann.Cell]
+           -> LW m (Doc Text)
+rowToLaTeX blocksWriter isSimpleTable colCount celltype row = do
+  cellsDocs <- mapM (cellToLaTeX blocksWriter isSimpleTable
+                      colCount celltype) (fillRow row)
+  return $ hsep (intersperse "&" cellsDocs) <> " \\\\"
+
+-- | Pads row with empty cells to adjust for rowspans above this row.
+fillRow :: [Ann.Cell] -> [Ann.Cell]
+fillRow = go 0
+  where
+    go _ [] = []
+    go n (acell@(Ann.Cell _spec (Ann.ColNumber colnum) cell):cells) =
+      let (Cell _ _ _ (ColSpan colspan) _) = cell
+      in map mkEmptyCell [n .. colnum - 1] ++
+         acell : go (colnum + colspan) cells
+
+    mkEmptyCell :: Int -> Ann.Cell
+    mkEmptyCell colnum =
+      Ann.Cell ((AlignDefault, ColWidthDefault):|[])
+               (Ann.ColNumber colnum)
+               B.emptyCell
+
+isEmptyHead :: Ann.TableHead -> Bool
+isEmptyHead (Ann.TableHead _attr []) = True
+isEmptyHead (Ann.TableHead _attr rows) = all (null . headerRowCells) rows
+
+isEmptyFoot :: Ann.TableFoot -> Bool
+isEmptyFoot (Ann.TableFoot _attr []) = True
+isEmptyFoot (Ann.TableFoot _attr rows) = all (null . headerRowCells) rows
+
+-- | Gets all cells in a header row.
+headerRowCells :: Ann.HeaderRow -> [Ann.Cell]
+headerRowCells (Ann.HeaderRow _attr _rownum cells) = cells
+
+-- | Gets all cells in a body row.
+bodyRowCells :: Ann.BodyRow -> [Ann.Cell]
+bodyRowCells (Ann.BodyRow _attr _rownum rowhead cells) = rowhead <> cells
+
+-- | Gets a list of rows of the table body, where a row is a simple
+-- list of cells.
+bodyRows :: Ann.TableBody -> [[Ann.Cell]]
+bodyRows (Ann.TableBody _attr _rowheads headerRows rows) =
+  map headerRowCells headerRows <> map bodyRowCells rows
+
+-- | Gets a list of rows of the table head, where a row is a simple
+-- list of cells.
+headRows :: Ann.TableHead -> [[Ann.Cell]]
+headRows (Ann.TableHead _attr rows) = map headerRowCells rows
+
+-- | Gets a list of rows from the foot, where a row is a simple list
+-- of cells.
+footRows :: Ann.TableFoot -> [[Ann.Cell]]
+footRows (Ann.TableFoot _attr rows) = map headerRowCells rows
+
+-- For simple latex tables (without minipages or parboxes),
+-- we need to go to some lengths to get line breaks working:
+-- as LineBreak bs = \vtop{\hbox{\strut as}\hbox{\strut bs}}.
+fixLineBreaks :: Block -> Block
+fixLineBreaks = walk fixLineBreaks'
+
+fixLineBreaks' :: [Inline] -> [Inline]
+fixLineBreaks' ils = case splitBy (== LineBreak) ils of
+                       []     -> []
+                       [xs]   -> xs
+                       chunks -> RawInline "tex" "\\vtop{" :
+                                 concatMap tohbox chunks <>
+                                 [RawInline "tex" "}"]
+  where tohbox ys = RawInline "tex" "\\hbox{\\strut " : ys <>
+                    [RawInline "tex" "}"]
+
+-- We also change display math to inline math, since display
+-- math breaks in simple tables.
+displayMathToInline :: Inline -> Inline
+displayMathToInline (Math DisplayMath x) = Math InlineMath x
+displayMathToInline x                    = x
+
+cellToLaTeX :: PandocMonad m
+            => BlocksWriter m
+            -> Bool
+            -> ColumnCount
+            -> CellType
+            -> Ann.Cell
+            -> LW m (Doc Text)
+cellToLaTeX blockListToLaTeX isSimpleTable colCount celltype annotatedCell = do
+  let (Ann.Cell specs colnum cell) = annotatedCell
+  let colWidths = NonEmpty.map snd specs
+  let hasWidths = NonEmpty.head colWidths /= ColWidthDefault
+  let specAlign = fst (NonEmpty.head specs)
+  let (Cell _attr align' rowspan colspan blocks) = cell
+  let align = case align' of
+                AlignDefault -> specAlign
+                _            -> align'
+  beamer <- gets stBeamer
+  externalNotes <- gets stExternalNotes
+  -- See #5367 -- footnotehyper/footnote don't work in beamer,
+  -- so we need to produce the notes outside the table...
+  modify $ \st -> st{ stExternalNotes = beamer }
+  let isPlainOrPara = \case
+        Para{}  -> True
+        Plain{} -> True
+        _       -> False
+  let hasLineBreak LineBreak = Any True
+      hasLineBreak _ = Any False
+  let hasLineBreaks = getAny $ query hasLineBreak blocks
+  result <-
+    if not hasWidths || (celltype /= HeaderCell
+                           && all isPlainOrPara blocks
+                           && not hasLineBreaks)
+       then
+         blockListToLaTeX $ walk fixLineBreaks $ walk displayMathToInline blocks
+       else do
+         cellContents <- inMinipage $ blockListToLaTeX blocks
+         let valign = text $ case celltype of
+                               HeaderCell -> "[b]"
+                               BodyCell   -> "[t]"
+         let halign = literal $ alignCommand align
+         return $ "\\begin{minipage}" <> valign <>
+                  braces "\\linewidth" <> halign <> cr <>
+                  cellContents <>
+                  (if hasLineBreaks then "\\strut" else mempty)
+                  <> cr <>
+                  "\\end{minipage}"
+  modify $ \st -> st{ stExternalNotes = externalNotes }
+  when (rowspan /= RowSpan 1) $
+    modify (\st -> st{ stMultiRow = True })
+  let inMultiColumn x = case colspan of
+                          (ColSpan 1) -> x
+                          (ColSpan n) ->
+                            let colDescr = multicolumnDescriptor isSimpleTable
+                                                                 align
+                                                                 colWidths
+                                                                 colCount
+                                                                 colnum
+                            in "\\multicolumn"
+                               <> braces (literal (tshow n))
+                               <> braces (literal colDescr)
+                               <> braces ("%\n" <> x)
+                                  -- linebreak for readability
+  let hasColWidths = not (all (== ColWidthDefault) colWidths)
+  let aligncmd = case specAlign of
+                   AlignCenter -> "\\centering\\arraybackslash "
+                   AlignRight -> "\\raggedright\\arraybackslash "
+                   _ -> mempty
+  let inMultiRow x = case rowspan of
+                       (RowSpan 1) -> x
+                       (RowSpan n) -> let nrows = literal (tshow n)
+                                      in "\\multirow" <> braces nrows
+                                         <> braces -- width of column
+                                             (if hasColWidths
+                                                 then "=" -- max width
+                                                 else "*") -- natural width
+                                         <> braces (aligncmd <> x)
+  return . inMultiColumn . inMultiRow $ result
+
+-- | Returns the width of a cell spanning @n@ columns.
+multicolumnDescriptor :: Bool
+                      -> Alignment
+                      -> NonEmpty ColWidth
+                      -> ColumnCount
+                      -> Ann.ColNumber
+                      -> Text
+multicolumnDescriptor isSimpleTable
+  align
+  colWidths
+  (ColumnCount numcols)
+  (Ann.ColNumber colnum) =
+  let toWidth = \case
+        ColWidthDefault -> (1 / fromIntegral numcols)
+        ColWidth x      -> x
+      colspan = length colWidths
+      width = sum $ NonEmpty.map toWidth colWidths
+
+      -- no column separators at beginning of first and end of last column.
+      skipColSep = "@{}" :: String
+  in T.pack $
+     if isSimpleTable
+        then printf "%s%s%s"
+              (if colnum == 0 then skipColSep else "")
+              (T.unpack (colAlign align))
+              (if colnum + colspan >= numcols then skipColSep else "")
+
+        else printf "%s>{%s\\arraybackslash}p{(\\linewidth - %d\\tabcolsep) * \\real{%0.4f} + %d\\tabcolsep}%s"
+              (if colnum == 0 then skipColSep else "")
+              (T.unpack (alignCommand align))
+              (2 * (numcols - 1))
+              width
+              (2 * (colspan - 1))
+              (if colnum + colspan >= numcols then skipColSep else "")
+
+-- | Perform a conversion, assuming that the context is a minipage.
+inMinipage :: Monad m => LW m a -> LW m a
+inMinipage action = do
+  isInMinipage <- gets stInMinipage
+  modify $ \st -> st{ stInMinipage = True }
+  result <- action
+  modify $ \st -> st{ stInMinipage = isInMinipage }
+  return result
+
+data CellType
+  = HeaderCell
+  | BodyCell
+  deriving Eq
diff --git a/src/Text/Pandoc/Writers/LaTeX/Types.hs b/src/Text/Pandoc/Writers/LaTeX/Types.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Writers/LaTeX/Types.hs
@@ -0,0 +1,108 @@
+module Text.Pandoc.Writers.LaTeX.Types
+  ( LW
+  , WriterState (..)
+  , startingState
+  , PdfStandard (..)
+  ) where
+
+import Control.Monad.State.Strict (StateT)
+import Data.Text (Text)
+import Text.DocLayout (Doc)
+import Text.Pandoc.Options
+  ( WriterOptions (writerIncremental, writerTopLevelDivision)
+  , TopLevelDivision (..)
+  )
+import Citeproc.Types (Lang)
+
+-- | LaTeX writer type. The type constructor @m@ will typically be an
+-- instance of PandocMonad.
+type LW m = StateT WriterState m
+
+data WriterState =
+  WriterState
+  { stInNote        :: Bool          -- ^ true if we're in a note
+  , stInQuote       :: Bool          -- ^ true if in a blockquote
+  , stExternalNotes :: Bool          -- ^ true if in context where
+                                     --   we need to store footnotes
+  , stInMinipage    :: Bool          -- ^ true if in minipage
+  , stInHeading     :: Bool          -- ^ true if in a section heading
+  , stInItem        :: Bool          -- ^ true if in \item[..]
+  , stInFigure      :: Bool          -- ^ true if in figure environment
+  , stInCite        :: Bool          -- ^ true if in a Cite
+  , stNotes         :: [Doc Text]    -- ^ notes in a minipage
+  , stOLLevel       :: Int           -- ^ level of ordered list nesting
+  , stOptions       :: WriterOptions -- ^ writer options, so they don't have to
+                                     --   be parameter
+  , stVerbInNote    :: Bool          -- ^ true if document has verbatim text in note
+  , stTable         :: Bool          -- ^ true if document has a table
+  , stSubfigure     :: Bool          -- ^ true if document has subfigures
+  , stMultiRow      :: Bool          -- ^ true if document has multirow cells
+  , stStrikeout     :: Bool          -- ^ true if document has strikeout
+  , stUrl           :: Bool          -- ^ true if document has visible URL link
+  , stGraphics      :: Bool          -- ^ true if document contains images
+  , stSVG           :: Bool          -- ^ true if document contains SVGs
+  , stLHS           :: Bool          -- ^ true if document has literate haskell code
+  , stHasChapters   :: Bool          -- ^ true if document has chapters
+  , stCsquotes      :: Bool          -- ^ true if document uses csquotes
+  , stHighlighting  :: Bool          -- ^ true if document has highlighted code
+  , stIncremental   :: Bool          -- ^ true if beamer lists should be
+  , stZwnj          :: Bool          -- ^ true if document has a ZWNJ character
+  , stInternalLinks :: [Text]        -- ^ list of internal link targets
+  , stBeamer        :: Bool          -- ^ produce beamer
+  , stEmptyLine     :: Bool          -- ^ true if no content on line
+  , stHasCslRefs    :: Bool          -- ^ has a Div with class refs
+  , stIsFirstInDefinition :: Bool    -- ^ first block in a defn list
+  , stLang          :: Maybe Lang    -- ^ lang specified in metadata
+  , stInSoulCommand :: Bool          -- ^ in a soul command like ul
+  , stCancel        :: Bool          -- ^ true if document uses \cancel
+  , stInCaption     :: Bool          -- ^ true if in a caption
+  }
+
+-- | PDF standard settings for DocumentMetadata
+data PdfStandard = PdfStandard
+  { pdfStandards :: [Text]     -- ^ list of standards (e.g., ["a-2b", "ua-1"])
+  , pdfVersion   :: Maybe Text -- ^ PDF version (e.g., "1.7", "2.0")
+  , pdfTagging   :: Bool       -- ^ whether tagging is required
+  }
+
+startingState :: WriterOptions -> WriterState
+startingState options =
+  WriterState
+  { stInNote = False
+  , stInQuote = False
+  , stExternalNotes = False
+  , stInHeading = False
+  , stInMinipage = False
+  , stInItem = False
+  , stInFigure = False
+  , stInCite = False
+  , stNotes = []
+  , stOLLevel = 1
+  , stOptions = options
+  , stVerbInNote = False
+  , stTable = False
+  , stSubfigure = False
+  , stMultiRow = False
+  , stStrikeout = False
+  , stUrl = False
+  , stGraphics = False
+  , stSVG = False
+  , stLHS = False
+  , stHasChapters = case writerTopLevelDivision options of
+                      TopLevelPart    -> True
+                      TopLevelChapter -> True
+                      _               -> False
+  , stCsquotes = False
+  , stHighlighting = False
+  , stIncremental = writerIncremental options
+  , stZwnj = False
+  , stInternalLinks = []
+  , stBeamer = False
+  , stEmptyLine = True
+  , stHasCslRefs = False
+  , stIsFirstInDefinition = False
+  , stLang = Nothing
+  , stInSoulCommand = False
+  , stCancel = False
+  , stInCaption = False
+  }
diff --git a/src/Text/Pandoc/Writers/LaTeX/Util.hs b/src/Text/Pandoc/Writers/LaTeX/Util.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Writers/LaTeX/Util.hs
@@ -0,0 +1,287 @@
+{-# LANGUAGE OverloadedStrings   #-}
+{- |
+   Module      : Text.Pandoc.Writers.LaTeX.Util
+   Copyright   : Copyright (C) 2006-2024 John MacFarlane
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : John MacFarlane <jgm@berkeley.edu>
+   Stability   : alpha
+   Portability : portable
+-}
+module Text.Pandoc.Writers.LaTeX.Util (
+    stringToLaTeX
+  , StringContext(..)
+  , toLabel
+  , inCmd
+  , wrapDiv
+  , hypertarget
+  , labelFor
+  , getListingsLanguage
+  , mbBraced
+  )
+where
+
+import Control.Applicative ((<|>))
+import Control.Monad (when)
+import Text.Pandoc.Class (PandocMonad, toLang)
+import Text.Pandoc.Options (WriterOptions(..), isEnabled)
+import Text.Pandoc.Writers.LaTeX.Types (LW, WriterState(..))
+import Text.Pandoc.Writers.LaTeX.Lang (toBabel)
+import Text.Pandoc.Highlighting (toListingsLanguage)
+import Text.DocLayout
+import Text.Pandoc.Definition
+import Text.Pandoc.ImageSize (showFl)
+import Control.Monad.State.Strict (gets, modify)
+import Data.Text (Text)
+import qualified Data.Text as T
+import Text.Pandoc.Extensions (Extension(Ext_smart))
+import Data.Char (isLetter, isSpace, isDigit, isAscii, ord, isAlphaNum)
+import Text.Printf (printf)
+import Text.Pandoc.Shared (safeRead)
+import qualified Data.Text.Normalize as Normalize
+import Data.List (uncons)
+
+data StringContext = TextString
+                   | URLString
+                   | CodeString
+                   deriving (Eq)
+
+-- escape things as needed for LaTeX
+stringToLaTeX :: PandocMonad m => StringContext -> Text -> LW m Text
+stringToLaTeX context zs = do
+  opts <- gets stOptions
+  when (T.any (== '\x200c') zs) $
+    modify (\s -> s { stZwnj = True })
+  return $ T.pack $
+    foldr (go opts context) mempty $ T.unpack $
+    if writerPreferAscii opts
+       then Normalize.normalize Normalize.NFD zs
+       else zs
+ where
+  go :: WriterOptions -> StringContext -> Char -> String -> String
+  go opts ctx x xs   =
+    let ligatures = isEnabled Ext_smart opts && ctx == TextString
+        isUrl = ctx == URLString
+        mbAccentCmd =
+          if writerPreferAscii opts && ctx == TextString
+             then uncons xs >>= \(c,_) -> lookupAccent c
+             else Nothing
+        emits s =
+          case mbAccentCmd of
+               Just cmd ->
+                 cmd <> "{" <> s <> "}" <> drop 1 xs -- drop combining accent
+               Nothing  -> s <> xs
+        emitc c =
+          case mbAccentCmd of
+               Just cmd ->
+                 cmd <> "{" <> [c] <> "}" <> drop 1 xs -- drop combining accent
+               Nothing  -> c : xs
+        emitcseq cs =
+          case xs of
+            c:_ | isLetter c
+                , ctx == TextString
+                             -> cs <> " " <> xs
+                | isSpace c  -> cs <> "{}" <> xs
+                | ctx == TextString
+                             -> cs <> xs
+            _ -> cs <> "{}" <> xs
+        emitquote cs =
+          case xs of
+            '`':_  -> cs <> "\\," <> xs -- add thin space
+            '\'':_ -> cs <> "\\," <> xs -- add thin space
+            _      -> cs <> xs
+    in case x of
+         _ | isUrl ->
+           case x of
+             '\\' -> emitc '/' -- NB / works as path sep even on Windows
+             '#' -> emits "\\#" -- #9014
+             '%' -> emits "\\%" -- #9014
+             '{' -> emits "\\%7B"
+             '}' -> emits "\\%7D"
+             '|' -> emits "\\%7C"
+             '^' -> emits "\\%5E"
+             '[' -> emits "\\%5B"
+             ']' -> emits "\\%5D"
+             '`' -> emits "\\%60"
+             _ -> emitc x
+         '{' -> emits "\\{"
+         '}' -> emits "\\}"
+         '?' | ligatures ->  -- avoid ?` ligature
+           case xs of
+             '`':_ -> emits "?{\\kern0pt}" -- se #10610
+             _     -> emitc x
+         '!' | ligatures ->  -- avoid !` ligature
+           case xs of
+             '`':_ -> emits "!{\\kern0pt}"
+             _     -> emitc x
+         '`' | ctx == CodeString -> emitcseq "\\textasciigrave"
+         '$' -> emits "\\$"
+         '%' -> emits "\\%"
+         '&' -> emits "\\&"
+         '_' -> emits "\\_"
+         '#' -> emits "\\#"
+         '-' -> case xs of
+                     -- prevent adjacent hyphens from forming ligatures
+                     ('-':_) -> emits "-\\/"
+                     _       -> emitc '-'
+         '~' -> emitcseq "\\textasciitilde"
+         '^' -> emits "\\^{}"
+         '\\' -> emitcseq "\\textbackslash"
+         '|'  -> emitcseq "\\textbar"
+         '<'  -> emitcseq "\\textless"
+         '>'  -> emitcseq "\\textgreater"
+         '['  -> emits "{[}"  -- to avoid interpretation as
+         ']'  -> emits "{]}"  -- optional arguments
+         '\'' -> emitcseq "\\textquotesingle"
+         '\160' -> emits "~"
+         '\x00AD' -> emits "\\-"  -- shy hyphen
+         '\x200B' -> emits "\\hspace{0pt}"  -- zero-width space
+         '\x202F' -> emits "\\,"
+         '\x2026' | ligatures -> emitcseq "\\ldots"
+         '\x2018' | ligatures -> emitquote "`"
+         '\x2019' | ligatures -> emitquote "'"
+         '\x201C' | ligatures -> emitquote "``"
+         '\x201D' | ligatures -> emitquote "''"
+         '\x2014' | ligatures -> emits "---"
+         '\x2013' | ligatures -> emits "--"
+         _ | writerPreferAscii opts
+             -> case x of
+                  'ı' -> 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
+
+lookupAccent :: Char -> Maybe String
+lookupAccent '\779'  = Just "\\H"
+lookupAccent '\768'  = Just "\\`"
+lookupAccent '\769'  = Just "\\'"
+lookupAccent '\770'  = Just "\\^"
+lookupAccent '\771'  = Just "\\~"
+lookupAccent '\776'  = Just "\\\""
+lookupAccent '\775'  = Just "\\."
+lookupAccent '\772'  = Just "\\="
+lookupAccent '\781'  = Just "\\|"
+lookupAccent '\817'  = Just "\\b"
+lookupAccent '\807'  = Just "\\c"
+lookupAccent '\783'  = Just "\\G"
+lookupAccent '\777'  = Just "\\h"
+lookupAccent '\803'  = Just "\\d"
+lookupAccent '\785'  = Just "\\f"
+lookupAccent '\778'  = Just "\\r"
+lookupAccent '\865'  = Just "\\t"
+lookupAccent '\782'  = Just "\\U"
+lookupAccent '\780'  = Just "\\v"
+lookupAccent '\774'  = Just "\\u"
+lookupAccent '\808'  = Just "\\k"
+lookupAccent '\8413' = Just "\\textcircled"
+lookupAccent _       = Nothing
+
+toLabel :: PandocMonad m => Text -> LW m Text
+toLabel z = go `fmap` stringToLaTeX URLString z
+ where
+   go = T.concatMap $ \x -> case x of
+     _ | (isLetter x || isDigit x) && isAscii x -> T.singleton x
+       | T.any (== x) "_-+=:;." -> T.singleton x
+       | otherwise -> T.pack $ "ux" <> printf "%x" (ord x)
+
+-- | Puts contents into LaTeX command.
+inCmd :: Text -> Doc Text -> Doc Text
+inCmd cmd contents = char '\\' <> literal cmd <> braces contents
+
+mapAlignment :: Text -> Text
+mapAlignment a = case a of
+                   "top" -> "T"
+                   "top-baseline" -> "t"
+                   "bottom" -> "b"
+                   "center" -> "c"
+                   _ -> a
+
+wrapDiv :: PandocMonad m => Attr -> Doc Text -> LW m (Doc Text)
+wrapDiv (_,classes,kvs) t = do
+  beamer <- gets stBeamer
+  let align dir txt = inCmd "begin" dir $$ txt $$ inCmd "end" dir
+  lang <- toLang $ lookup "lang" kvs
+  let wrapColumns = if beamer && "columns" `elem` classes
+                    then \contents ->
+                           let valign = maybe "T" mapAlignment (lookup "align" kvs)
+                               totalwidth = maybe [] (\x -> ["totalwidth=" <> x])
+                                 (lookup "totalwidth" kvs)
+                               onlytextwidth = filter ("onlytextwidth" ==) classes
+                               options = text $ T.unpack $ T.intercalate "," $
+                                 valign : totalwidth ++ onlytextwidth
+                           in inCmd "begin" "columns" <> brackets options
+                              $$ contents
+                              $$ inCmd "end" "columns"
+                    else id
+      wrapColumn  = if beamer && "column" `elem` classes
+                    then \contents ->
+                           let valign =
+                                 maybe ""
+                                 (brackets . text . T.unpack . mapAlignment)
+                                 (lookup "align" kvs)
+                               w = maybe "0.48" fromPct (lookup "width" kvs)
+                           in  inCmd "begin" "column" <>
+                               valign <>
+                               braces (literal w <> "\\linewidth")
+                               $$ contents
+                               $$ inCmd "end" "column"
+                    else id
+      fromPct xs =
+        case T.unsnoc xs of
+          Just (ds, '%') -> case safeRead ds of
+                              Just digits -> showFl (digits / 100 :: Double)
+                              Nothing -> xs
+          _              -> xs
+      wrapDir = case lookup "dir" kvs of
+                  Just "rtl" -> align "RTL"
+                  Just "ltr" -> align "LTR"
+                  _          -> id
+      wrapLang txt = case lang >>= toBabel of
+                       Just l -> inCmd "begin" "otherlanguage"
+                                            <> (braces (literal l))
+                                       $$ blankline <> txt <> blankline
+                                       $$ inCmd "end" "otherlanguage"
+                       Nothing  -> txt
+  return $ wrapColumns . wrapColumn . wrapDir . wrapLang $ t
+
+hypertarget :: PandocMonad m => Text -> LW m (Doc Text)
+hypertarget "" = return mempty
+hypertarget ident = do
+  inHeading <- gets stInHeading
+  if inHeading
+     then do -- see #9209 (these cases should be rare)
+      ref <- literal <$> toLabel ident
+      return $ text "\\protect\\hypertarget" <> braces ref <> "{}"
+     else do
+      label <- labelFor ident
+      return $ text "\\protect\\phantomsection" <> label
+
+labelFor :: PandocMonad m => Text -> LW m (Doc Text)
+labelFor ""    = return empty
+labelFor ident = do
+  ref <- literal `fmap` toLabel ident
+  return $ text "\\label" <> braces ref
+
+-- Determine listings language from list of class attributes.
+getListingsLanguage :: [Text] -> Maybe Text
+getListingsLanguage xs
+  = foldr ((<|>) . toListingsLanguage) Nothing xs
+
+mbBraced :: Text -> Text
+mbBraced x = if not (T.all isAlphaNum x)
+                then "{" <> x <> "}"
+                else x
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,82 +1,58 @@
+{-# LANGUAGE LambdaCase        #-}
 {-# LANGUAGE OverloadedStrings #-}
-{-
-Copyright (C) 2007-2017 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 ViewPatterns      #-}
 {- |
    Module      : Text.Pandoc.Writers.Man
-   Copyright   : Copyright (C) 2007-2017 John MacFarlane
+   Copyright   : Copyright (C) 2007-2024 John MacFarlane
    License     : GNU GPL, version 2 or above
 
    Maintainer  : John MacFarlane <jgm@berkeley.edu>
    Stability   : alpha
    Portability : portable
 
-Conversion of 'Pandoc' documents to groff man page format.
+Conversion of 'Pandoc' documents to roff man page format.
 
 -}
-module Text.Pandoc.Writers.Man ( writeMan) where
-import Control.Monad.State.Strict
-import Data.List (intercalate, intersperse, sort, stripPrefix)
-import qualified Data.Map as Map
+module Text.Pandoc.Writers.Man ( writeMan ) where
+import Control.Monad ( liftM, zipWithM, unless )
+import Control.Monad.State.Strict ( StateT, gets, modify, evalStateT )
+import Control.Monad.Trans (MonadTrans(lift))
+import Data.List (intersperse)
+import Data.List.NonEmpty (nonEmpty)
 import Data.Maybe (fromMaybe)
+import qualified Data.Map as M
 import Data.Text (Text)
 import qualified Data.Text as T
 import Text.Pandoc.Builder (deleteMeta)
-import Text.Pandoc.Class (PandocMonad, report)
+import Text.Pandoc.Class.PandocMonad (PandocMonad, report)
 import Text.Pandoc.Definition
 import Text.Pandoc.Logging
 import Text.Pandoc.Options
-import Text.Pandoc.Pretty
+import Text.DocLayout
 import Text.Pandoc.Shared
-import Text.Pandoc.Templates
+import Text.Pandoc.URI
+import Text.Pandoc.Templates (renderTemplate)
 import Text.Pandoc.Writers.Math
 import Text.Pandoc.Writers.Shared
+import Text.Pandoc.Writers.Roff
+import Text.Pandoc.Highlighting
 import Text.Printf (printf)
-
-type Notes = [[Block]]
-data WriterState = WriterState { stNotes        :: Notes
-                               , stFontFeatures :: Map.Map Char Bool
-                               , stHasTables    :: Bool }
-
-defaultWriterState :: WriterState
-defaultWriterState = WriterState { stNotes = []
-                                 , stFontFeatures  = Map.fromList [
-                                                       ('I',False)
-                                                     , ('B',False)
-                                                     , ('C',False)
-                                                     ]
-                                 , stHasTables  = False }
+import Skylighting (TokenType(..), SourceLine, FormatOptions, defaultFormatOpts,
+                    defStyle, TokenStyle(..), Style(..))
 
 -- | Convert Pandoc to Man.
 writeMan :: PandocMonad m => WriterOptions -> Pandoc -> m Text
 writeMan opts document =
   evalStateT (pandocToMan opts document) defaultWriterState
 
--- | Return groff man representation of document.
+-- | Return roff man representation of document.
 pandocToMan :: PandocMonad m => WriterOptions -> Pandoc -> StateT WriterState m Text
 pandocToMan opts (Pandoc meta blocks) = do
   let colwidth = if writerWrapText opts == WrapAuto
                     then Just $ writerColumns opts
                     else Nothing
-  let render' :: Doc -> Text
-      render' = render colwidth
   titleText <- inlineListToMan opts $ docTitle meta
-  let title' = render' titleText
+  let title' = render Nothing titleText
   let setFieldsFromTitle =
        case T.break (== ' ') title' of
            (cmdName, rest) -> case T.break (=='(') cmdName of
@@ -91,130 +67,90 @@
                                                (T.strip $ mconcat hds)
                                           [] -> id
                                    _  -> defField "title" title'
-  metadata <- metaToJSON opts
-              (fmap render' . blockListToMan opts)
-              (fmap render' . inlineListToMan opts)
+  metadata <- metaToContext opts
+              (blockListToMan opts)
+              (fmap chomp . inlineListToMan opts)
               $ deleteMeta "title" meta
   body <- blockListToMan opts blocks
   notes <- gets stNotes
   notes' <- notesToMan opts (reverse notes)
-  let main = render' $ body $$ notes' $$ text ""
+  let main = body $$ notes' $$ text ""
   hasTables <- gets stHasTables
   let context = defField "body" main
               $ setFieldsFromTitle
               $ defField "has-tables" hasTables
-              $ defField "hyphenate" True
-              $ defField "pandoc-version" pandocVersion metadata
-  case writerTemplate opts of
-       Nothing  -> return main
-       Just tpl -> renderTemplate' tpl context
+                metadata
+  return $ render colwidth $
+    case writerTemplate opts of
+       Nothing  -> main
+       Just tpl -> renderTemplate tpl context
 
+escString :: WriterOptions -> Text -> Text
+escString opts = escapeString True (if writerPreferAscii opts
+                                       then AsciiOnly
+                                       else AllowUTF8)
+
 -- | Return man representation of notes.
-notesToMan :: PandocMonad m => WriterOptions -> [[Block]] -> StateT WriterState m Doc
+notesToMan :: PandocMonad m => WriterOptions -> [[Block]] -> StateT WriterState m (Doc Text)
 notesToMan opts notes =
   if null notes
      then return empty
-     else mapM (uncurry (noteToMan opts)) (zip [1..] notes) >>=
-          return . (text ".SH NOTES" $$) . vcat
+     else (text ".SH NOTES" $$) . vcat <$> zipWithM (noteToMan opts) [1..] notes
 
 -- | Return man representation of a note.
-noteToMan :: PandocMonad m => WriterOptions -> Int -> [Block] -> StateT WriterState m Doc
+noteToMan :: PandocMonad m => WriterOptions -> Int -> [Block] -> StateT WriterState m (Doc Text)
 noteToMan opts num note = do
   contents <- blockListToMan opts note
   let marker = cr <> text ".SS " <> brackets (text (show num))
   return $ marker $$ contents
 
--- | Association list of characters to escape.
-manEscapes :: [(Char, String)]
-manEscapes = [ ('\160', "\\ ")
-             , ('\'', "\\[aq]")
-             , ('’', "'")
-             , ('\x2014', "\\[em]")
-             , ('\x2013', "\\[en]")
-             , ('\x2026', "\\&...")
-             ] ++ backslashEscapes "-@\\"
-
--- | Escape special characters for Man.
-escapeString :: String -> String
-escapeString = escapeStringUsing manEscapes
-
--- | Escape a literal (code) section for Man.
-escapeCode :: String -> String
-escapeCode = intercalate "\n" . map escapeLine . lines  where
-  escapeLine codeline =
-    case escapeStringUsing (manEscapes ++ backslashEscapes "\t ") codeline of
-      a@('.':_) -> "\\&" ++ a
-      b         -> b
-
 -- We split inline lists into sentences, and print one sentence per
--- line.  groff/troff treats the line-ending period differently.
+-- line.  roff treats the line-ending period differently.
 -- See http://code.google.com/p/pandoc/issues/detail?id=148.
 
--- | Returns the first sentence in a list of inlines, and the rest.
-breakSentence :: [Inline] -> ([Inline], [Inline])
-breakSentence [] = ([],[])
-breakSentence xs =
-  let isSentenceEndInline (Str ys@(_:_)) | last ys == '.' = True
-      isSentenceEndInline (Str ys@(_:_)) | last ys == '?' = True
-      isSentenceEndInline LineBreak      = True
-      isSentenceEndInline _              = False
-      (as, bs) = break isSentenceEndInline xs
-  in  case bs of
-           []             -> (as, [])
-           [c]            -> (as ++ [c], [])
-           (c:Space:cs)   -> (as ++ [c], cs)
-           (c:SoftBreak:cs) -> (as ++ [c], cs)
-           (Str ".":Str (')':ys):cs) -> (as ++ [Str ".", Str (')':ys)], cs)
-           (x@(Str ('.':')':_)):cs) -> (as ++ [x], cs)
-           (LineBreak:x@(Str ('.':_)):cs) -> (as ++[LineBreak], x:cs)
-           (c:cs)         -> (as ++ [c] ++ ds, es)
-              where (ds, es) = breakSentence cs
-
--- | Split a list of inlines into sentences.
-splitSentences :: [Inline] -> [[Inline]]
-splitSentences xs =
-  let (sent, rest) = breakSentence xs
-  in  if null rest then [sent] else sent : splitSentences rest
-
 -- | Convert Pandoc block element to man.
 blockToMan :: PandocMonad m
            => WriterOptions -- ^ Options
            -> Block         -- ^ Block element
-           -> StateT WriterState m Doc
-blockToMan _ Null = return empty
+           -> StateT WriterState m (Doc Text)
 blockToMan opts (Div _ bs) = blockListToMan opts bs
 blockToMan opts (Plain inlines) =
-  liftM vcat $ mapM (inlineListToMan opts) $ splitSentences inlines
+  splitSentences <$> inlineListToMan opts inlines
 blockToMan opts (Para inlines) = do
-  contents <- liftM vcat $ mapM (inlineListToMan opts) $
-    splitSentences inlines
-  return $ text ".PP" $$ contents
+  contents <- inlineListToMan opts inlines
+  return $ text ".PP" $$ splitSentences contents
 blockToMan opts (LineBlock lns) =
   blockToMan opts $ linesToPara lns
 blockToMan _ b@(RawBlock f str)
-  | f == Format "man" = return $ text str
+  | f == Format "man" = return $ literal str
   | otherwise         = do
       report $ BlockNotRendered b
       return empty
-blockToMan _ HorizontalRule = return $ text ".PP" $$ text "   *   *   *   *   *"
+blockToMan _ HorizontalRule = return $ literal ".PP" $$ literal "   *   *   *   *   *"
 blockToMan opts (Header level _ inlines) = do
   contents <- inlineListToMan opts inlines
   let heading = case level of
                   1 -> ".SH "
                   _ -> ".SS "
-  return $ text heading <> contents
-blockToMan _ (CodeBlock _ str) = return $
-  text ".IP" $$
-  text ".nf" $$
-  text "\\f[C]" $$
-  text (escapeCode str) $$
-  text "\\f[]" $$
-  text ".fi"
+  return $ nowrap $ literal heading <> contents
+blockToMan opts (CodeBlock attr str) = do
+  hlCode <- case highlight (writerSyntaxMap opts) (formatSource opts)
+                  attr str of
+              Right d -> pure d
+              Left msg -> do
+                unless (T.null msg) $ report $ CouldNotHighlight msg
+                pure $ formatSource opts defaultFormatOpts
+                          (map (\t -> [(NormalTok,t)]) $ T.lines str)
+  pure $ literal ".IP" $$
+         literal ".EX" $$
+         hlCode $$
+         literal ".EE"
 blockToMan opts (BlockQuote blocks) = do
   contents <- blockListToMan opts blocks
-  return $ text ".RS" $$ contents $$ text ".RE"
-blockToMan opts (Table caption alignments widths headers rows) =
-  let aligncode AlignLeft    = "l"
+  return $ literal ".RS" $$ contents $$ literal ".RE"
+blockToMan opts (Table _ blkCapt specs thead tbody tfoot) =
+  let (caption, alignments, widths, headers, rows) = toLegacyTable blkCapt specs thead tbody tfoot
+      aligncode AlignLeft    = "l"
       aligncode AlignRight   = "r"
       aligncode AlignCenter  = "c"
       aligncode AlignDefault = "l"
@@ -223,64 +159,64 @@
   modify $ \st -> st{ stHasTables = True }
   let iwidths = if all (== 0) widths
                    then repeat ""
-                   else map (printf "w(%0.1fn)" . (70 *)) widths
+                   else map (T.pack . printf "w(%0.1fn)" . (70 *)) widths
   -- 78n default width - 8n indent = 70n
-  let coldescriptions = text $ unwords
-                        (zipWith (\align width -> aligncode align ++ width)
-                        alignments iwidths) ++ "."
+  let coldescriptions = literal $ T.unwords
+                        (zipWith (\align width -> aligncode align <> width)
+                        alignments iwidths) <> "."
   colheadings <- mapM (blockListToMan opts) headers
-  let makeRow cols = text "T{" $$
-                     vcat (intersperse (text "T}@T{") cols) $$
-                     text "T}"
+  let makeRow cols = literal "T{" $$
+                     vcat (intersperse (literal "T}@T{") cols) $$
+                     literal "T}"
   let colheadings' = if all null headers
                         then empty
                         else makeRow colheadings $$ char '_'
   body <- mapM (\row -> do
                          cols <- mapM (blockListToMan opts) row
                          return $ makeRow cols) rows
-  return $ text ".PP" $$ caption' $$
-           text ".TS" $$ text "tab(@);" $$ coldescriptions $$
-           colheadings' $$ vcat body $$ text ".TE"
-
+  return $ literal ".PP" $$ caption' $$
+           literal ".TS" $$ literal "tab(@);" $$ coldescriptions $$
+           colheadings' $$ vcat body $$ literal ".TE"
 blockToMan opts (BulletList items) = do
   contents <- mapM (bulletListItemToMan opts) items
   return (vcat contents)
 blockToMan opts (OrderedList attribs items) = do
   let markers = take (length items) $ orderedListMarkers attribs
-  let indent = 1 +
-                     maximum (map length markers)
+  let indent = 1 + maybe 0 maximum (nonEmpty (map T.length markers))
   contents <- mapM (\(num, item) -> orderedListItemToMan opts num indent item) $
               zip markers items
   return (vcat contents)
 blockToMan opts (DefinitionList items) = do
   contents <- mapM (definitionListItemToMan opts) items
   return (vcat contents)
+blockToMan opts (Figure attr capt body) = do
+  blockToMan opts (figureDiv attr capt body)
 
 -- | Convert bullet list item (list of blocks) to man.
-bulletListItemToMan :: PandocMonad m => WriterOptions -> [Block] -> StateT WriterState m Doc
+bulletListItemToMan :: PandocMonad m => WriterOptions -> [Block] -> StateT WriterState m (Doc Text)
 bulletListItemToMan _ [] = return empty
 bulletListItemToMan opts (Para first:rest) =
   bulletListItemToMan opts (Plain first:rest)
 bulletListItemToMan opts (Plain first:rest) = do
   first' <- blockToMan opts (Plain first)
   rest' <- blockListToMan opts rest
-  let first'' = text ".IP \\[bu] 2" $$ first'
+  let first'' = literal ".IP \\(bu 2" $$ first'
   let rest''  = if null rest
                    then empty
-                   else text ".RS 2" $$ rest' $$ text ".RE"
+                   else literal ".RS 2" $$ rest' $$ literal ".RE"
   return (first'' $$ rest'')
 bulletListItemToMan opts (first:rest) = do
   first' <- blockToMan opts first
   rest' <- blockListToMan opts rest
-  return $ text "\\[bu] .RS 2" $$ first' $$ rest' $$ text ".RE"
+  return $ literal "\\(bu .RS 2" $$ first' $$ rest' $$ literal ".RE"
 
 -- | Convert ordered list item (a list of blocks) to man.
 orderedListItemToMan :: PandocMonad m
                      => WriterOptions -- ^ options
-                     -> String   -- ^ order marker for list item
+                     -> Text   -- ^ order marker for list item
                      -> Int      -- ^ number of spaces to indent
                      -> [Block]  -- ^ list item (list of blocks)
-                     -> StateT WriterState m Doc
+                     -> StateT WriterState m (Doc Text)
 orderedListItemToMan _ _ _ [] = return empty
 orderedListItemToMan opts num indent (Para first:rest) =
   orderedListItemToMan opts num indent (Plain first:rest)
@@ -288,23 +224,24 @@
   first' <- blockToMan opts first
   rest' <- blockListToMan opts rest
   let num' = printf ("%" ++ show (indent - 1) ++ "s") num
-  let first'' = text (".IP \"" ++ num' ++ "\" " ++ show indent) $$ first'
+  let first'' = literal (".IP \"" <> T.pack num' <> "\" " <> tshow indent) $$ first'
   let rest''  = if null rest
                    then empty
-                   else text ".RS 4" $$ rest' $$ text ".RE"
+                   else literal ".RS 4" $$ rest' $$ literal ".RE"
   return $ first'' $$ rest''
 
 -- | Convert definition list item (label, list of blocks) to man.
 definitionListItemToMan :: PandocMonad m
                         => WriterOptions
                         -> ([Inline],[[Block]])
-                        -> StateT WriterState m Doc
+                        -> StateT WriterState m (Doc Text)
 definitionListItemToMan opts (label, defs) = do
+  -- in most man pages, option and other code in option lists is boldface,
+  -- but not other things, so we try to reproduce this style:
   labelText <- inlineListToMan opts label
   contents <- if null defs
                  then return empty
-                 else liftM vcat $ forM defs $ \blocks ->
-                        case blocks of
+                 else case mconcat defs of
                           (x:xs) -> do
                             first' <- blockToMan opts $
                                       case x of
@@ -313,32 +250,43 @@
                             rest' <- liftM vcat $ mapM
                                         (\item -> blockToMan opts item) xs
                             return $ first' $$
-                                     text ".RS" $$ rest' $$ text ".RE"
+                                     if null xs
+                                        then empty
+                                        else literal ".RS" $$ rest' $$ literal ".RE"
                           [] -> return empty
-  return $ text ".TP" $$ nowrap (text ".B " <> labelText) $$ contents
+  return $ literal ".TP" $$ nowrap labelText $$ contents
 
 -- | Convert list of Pandoc block elements to man.
 blockListToMan :: PandocMonad m
                => WriterOptions -- ^ Options
                -> [Block]       -- ^ List of block elements
-               -> StateT WriterState m Doc
+               -> StateT WriterState m (Doc Text)
 blockListToMan opts blocks =
-  mapM (blockToMan opts) blocks >>= (return . vcat)
+  vcat <$> mapM (blockToMan opts) (go blocks)
+ where
+   -- Avoid .PP right after .SH; this is a no-op in groff man and mandoc
+   -- but may cause unwanted extra space in some renderers (see #9020)
+   go [] = []
+   go (h@Header{} : Para ils : rest) = h : Plain ils : go rest
+   go (x : xs) = x : go xs
 
 -- | Convert list of Pandoc inline elements to man.
-inlineListToMan :: PandocMonad m => WriterOptions -> [Inline] -> StateT WriterState m Doc
-inlineListToMan opts lst = mapM (inlineToMan opts) lst >>= (return . hcat)
+inlineListToMan :: PandocMonad m => WriterOptions -> [Inline] -> StateT WriterState m (Doc Text)
+inlineListToMan opts lst = hcat <$> mapM (inlineToMan opts) lst
 
 -- | Convert Pandoc inline element to man.
-inlineToMan :: PandocMonad m => WriterOptions -> Inline -> StateT WriterState m Doc
+inlineToMan :: PandocMonad m => WriterOptions -> Inline -> StateT WriterState m (Doc Text)
 inlineToMan opts (Span _ ils) = inlineListToMan opts ils
 inlineToMan opts (Emph lst) =
   withFontFeature 'I' (inlineListToMan opts lst)
+-- Underline is not supported, so treat the same as Emph
+inlineToMan opts (Underline lst) =
+  withFontFeature 'I' (inlineListToMan opts lst)
 inlineToMan opts (Strong lst) =
   withFontFeature 'B' (inlineListToMan opts lst)
 inlineToMan opts (Strikeout lst) = do
   contents <- inlineListToMan opts lst
-  return $ text "[STRIKEOUT:" <> contents <> char ']'
+  return $ literal "[STRIKEOUT:" <> contents <> char ']'
 inlineToMan opts (Superscript lst) = do
   contents <- inlineListToMan opts lst
   return $ char '^' <> contents <> char '^'
@@ -351,66 +299,81 @@
   return $ char '`' <> contents <> char '\''
 inlineToMan opts (Quoted DoubleQuote lst) = do
   contents <- inlineListToMan opts lst
-  return $ text "\\[lq]" <> contents <> text "\\[rq]"
+  return $ literal "\\(lq" <> contents <> literal "\\(rq"
 inlineToMan opts (Cite _ lst) =
   inlineListToMan opts lst
-inlineToMan _ (Code _ str) =
-  withFontFeature 'C' (return (text $ escapeCode str))
-inlineToMan _ (Str str@('.':_)) =
-  return $ afterBreak "\\&" <> text (escapeString str)
-inlineToMan _ (Str str) = return $ text $ escapeString str
+inlineToMan opts (Code _ str) =
+  withFontFeature 'C' (return (literal $ escString opts str))
+inlineToMan opts (Str str@(T.uncons -> Just ('.',_))) =
+  return $ afterBreak "\\&" <> literal (escString opts str)
+inlineToMan opts (Str str) = return $ literal $ escString opts str
 inlineToMan opts (Math InlineMath str) =
   lift (texMathToInlines InlineMath str) >>= inlineListToMan opts
 inlineToMan opts (Math DisplayMath str) = do
   contents <- lift (texMathToInlines DisplayMath str) >>= inlineListToMan opts
-  return $ cr <> text ".RS" $$ contents $$ text ".RE"
+  return $ cr <> literal ".RS" $$ contents $$ literal ".RE"
 inlineToMan _ il@(RawInline f str)
-  | f == Format "man" = return $ text str
+  | f == Format "man" = return $ literal str
   | otherwise         = do
       report $ InlineNotRendered il
       return empty
 inlineToMan _ LineBreak = return $
-  cr <> text ".PD 0" $$ text ".P" $$ text ".PD" <> cr
-inlineToMan _ SoftBreak = return space
-inlineToMan _ Space = return space
-inlineToMan opts (Link _ txt ('#':_, _)) =
-  inlineListToMan opts txt -- skip internal links
-inlineToMan opts (Link _ txt (src, _)) = do
-  linktext <- inlineListToMan opts txt
-  let srcSuffix = fromMaybe src (stripPrefix "mailto:" src)
-  return $ case txt of
-           [Str s]
-             | escapeURI s == srcSuffix ->
-                                 char '<' <> text srcSuffix <> char '>'
-           _                  -> linktext <> text " (" <> text src <> char ')'
+  cr <> literal ".PD 0" $$ literal ".P" $$ literal ".PD" <> cr
+inlineToMan _ SoftBreak = return $ afterBreak "\\" <> space
+inlineToMan _ Space = return $ afterBreak "\\" <> space
+inlineToMan opts (Link _ txt (src, _))
+  | not (isURI src) = inlineListToMan opts txt -- skip relative links
+  | otherwise       = do
+  let srcSuffix = fromMaybe src (T.stripPrefix "mailto:" src)
+  linktext <- case txt of
+                [Str s] | escapeURI s == srcSuffix -> pure mempty
+                _ -> inlineListToMan opts txt
+  let (start, end) = if "mailto:" `T.isPrefixOf` src
+                        then (".MT", ".ME")
+                        else (".UR", ".UE")
+  return $ "\\c" <> cr -- \c avoids extra space
+        $$ nowrap (start <+> literal srcSuffix)
+        $$ linktext
+        $$ (end <+> "\\c" <> cr)  -- \c avoids space after
 inlineToMan opts (Image attr alternate (source, tit)) = do
   let txt = if null alternate || (alternate == [Str ""]) ||
                (alternate == [Str source]) -- to prevent autolinks
                then [Str "image"]
                else alternate
   linkPart <- inlineToMan opts (Link attr txt (source, tit))
-  return $ char '[' <> text "IMAGE: " <> linkPart <> char ']'
+  return $ char '[' <> literal "IMAGE: " <> linkPart <> char ']'
 inlineToMan _ (Note contents) = do
   -- add to notes in state
   modify $ \st -> st{ stNotes = contents : stNotes st }
   notes <- gets stNotes
-  let ref = show (length notes)
-  return $ char '[' <> text ref <> char ']'
+  let ref = tshow (length notes)
+  return $ char '[' <> literal ref <> char ']'
 
-fontChange :: PandocMonad m => StateT WriterState m Doc
-fontChange = do
-  features <- gets stFontFeatures
-  let filling = sort [c | (c,True) <- Map.toList features]
-  return $ text $ "\\f[" ++ filling ++ "]"
+formatSource :: WriterOptions -> FormatOptions -> [SourceLine] -> Doc Text
+formatSource wopts fopts = vcat . map (formatSourceLine wopts fopts)
 
-withFontFeature :: PandocMonad m
-                => Char
-                -> StateT WriterState m Doc
-                -> StateT WriterState m Doc
-withFontFeature c action = do
-  modify $ \st -> st{ stFontFeatures = Map.adjust not c $ stFontFeatures st }
-  begin <- fontChange
-  d <- action
-  modify $ \st -> st{ stFontFeatures = Map.adjust not c $ stFontFeatures st }
-  end <- fontChange
-  return $ begin <> d <> end
+formatSourceLine :: WriterOptions -> FormatOptions -> SourceLine -> Doc Text
+formatSourceLine _wopts _fopts [] = blankline
+formatSourceLine wopts fopts ts@((_,firstTxt):_) =
+  (case T.uncons firstTxt of
+     Just ('.',_) -> literal "\\&"
+     _ -> mempty) <> mconcat (map (formatTok wopts fopts) ts) <> literal "\n"
+
+formatTok :: WriterOptions -> FormatOptions -> (TokenType, Text) -> Doc Text
+formatTok wopts _fopts (toktype, t) =
+  let txt = literal (escString wopts t)
+      styleMap = case writerHighlightMethod wopts of
+        Skylighting style   -> Just $ tokenStyles style
+        DefaultHighlighting -> Just $ tokenStyles defaultStyle
+        _ -> Nothing
+      tokStyle = fromMaybe defStyle $ styleMap >>= M.lookup toktype
+  in  if toktype == NormalTok
+         then txt
+         else
+           let fonts = ['B' | tokenBold tokStyle] ++
+                       ['I' | tokenItalic tokStyle || tokenUnderline tokStyle]
+            in if null fonts
+                  then txt
+                  else literal ("\\f[" <> T.pack fonts <> "]") <>
+                       txt <>
+                       literal "\\f[R]"
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
@@ -2,1258 +2,967 @@
 {-# LANGUAGE OverloadedStrings   #-}
 {-# LANGUAGE ScopedTypeVariables #-}
 {-# LANGUAGE TupleSections       #-}
-{-
-Copyright (C) 2006-2017 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-2017 John MacFarlane
-   License     : GNU GPL, version 2 or above
-
-   Maintainer  : John MacFarlane <jgm@berkeley.edu>
-   Stability   : alpha
-   Portability : portable
-
-Conversion of 'Pandoc' documents to markdown-formatted plain text.
-
-Markdown:  <http://daringfireball.net/projects/markdown/>
--}
-module Text.Pandoc.Writers.Markdown (writeMarkdown, writePlain) where
-import Control.Monad.Reader
-import Control.Monad.State.Strict
-import Data.Char (chr, isPunctuation, isSpace, ord)
-import Data.Default
-import qualified Data.HashMap.Strict as H
-import Data.List (find, group, intersperse, sortBy, stripPrefix, transpose)
-import qualified Data.Map as M
-import Data.Maybe (fromMaybe)
-import Data.Monoid (Any (..))
-import Data.Ord (comparing)
-import qualified Data.Set as Set
-import Data.Text (Text)
-import qualified Data.Text as T
-import qualified Data.Vector as V
-import Data.Yaml (Value (Array, Bool, Number, Object, String))
-import Network.HTTP (urlEncode)
-import Text.HTML.TagSoup (Tag (..), isTagText, parseTags)
-import Text.Pandoc.Class (PandocMonad, report)
-import Text.Pandoc.Definition
-import Text.Pandoc.Logging
-import Text.Pandoc.Options
-import Text.Pandoc.Parsing hiding (blankline, blanklines, char, space)
-import Text.Pandoc.Pretty
-import Text.Pandoc.Shared
-import Text.Pandoc.Templates (renderTemplate')
-import Text.Pandoc.Walk
-import Text.Pandoc.Writers.HTML (writeHtml5String)
-import Text.Pandoc.Writers.Math (texMathToInlines)
-import Text.Pandoc.Writers.Shared
-
-type Notes = [[Block]]
-type Ref   = (Doc, Target, Attr)
-type Refs  = [Ref]
-
-type MD m = ReaderT WriterEnv (StateT WriterState m)
-
-evalMD :: PandocMonad m => MD m a -> WriterEnv -> WriterState -> m a
-evalMD md env st = evalStateT (runReaderT md env) st
-
-data WriterEnv = WriterEnv { envInList          :: Bool
-                           , envPlain           :: Bool
-                           , envRefShortcutable :: Bool
-                           , envBlockLevel      :: Int
-                           , envEscapeSpaces    :: Bool
-                           }
-
-instance Default WriterEnv
-  where def = WriterEnv { envInList         = False
-                        , envPlain          = False
-                        , envRefShortcutable = True
-                        , envBlockLevel      = 0
-                        , envEscapeSpaces    = False
-                        }
-
-data WriterState = WriterState { stNotes   :: Notes
-                               , stRefs    :: Refs
-                               , stKeys    :: M.Map Key
-                                                (M.Map (Target, Attr) Int)
-                               , stLastIdx  :: Int
-                               , stIds     :: Set.Set String
-                               , stNoteNum :: Int
-                               }
-
-instance Default WriterState
-  where def = WriterState{ stNotes = []
-                         , stRefs = []
-                         , stKeys = M.empty
-                         , stLastIdx = 0
-                         , stIds = Set.empty
-                         , stNoteNum = 1
-                         }
-
--- | Convert Pandoc to Markdown.
-writeMarkdown :: PandocMonad m => WriterOptions -> Pandoc -> m Text
-writeMarkdown opts document =
-  evalMD (pandocToMarkdown opts{
-             writerWrapText = if isEnabled Ext_hard_line_breaks opts
-                              then WrapNone
-                              else writerWrapText opts }
-             document) def def
-
--- | Convert Pandoc to plain text (like markdown, but without links,
--- pictures, or inline formatting).
-writePlain :: PandocMonad m => WriterOptions -> Pandoc -> m Text
-writePlain opts document =
-  evalMD (pandocToMarkdown opts document) def{ envPlain = True } def
-
-pandocTitleBlock :: Doc -> [Doc] -> Doc -> Doc
-pandocTitleBlock tit auths dat =
-  hang 2 (text "% ") tit <> cr <>
-  hang 2 (text "% ") (vcat $ map nowrap auths) <> cr <>
-  hang 2 (text "% ") dat <> cr
-
-mmdTitleBlock :: Value -> Doc
-mmdTitleBlock (Object hashmap) =
-  vcat $ map go $ sortBy (comparing fst) $ H.toList hashmap
-  where go (k,v) =
-          case (text (T.unpack k), v) of
-               (k', Array vec)
-                 | V.null vec     -> empty
-                 | otherwise      -> k' <> ":" <> space <>
-                                      hcat (intersperse "; "
-                                           (map fromstr $ V.toList vec))
-               (_, String "")  -> empty
-               (k', x)         -> k' <> ":" <> space <> nest 2 (fromstr x)
-        fromstr (String s) = text (removeBlankLines $ T.unpack s)
-        fromstr (Bool b)   = text (show b)
-        fromstr (Number n) = text (show n)
-        fromstr _          = empty
-        -- blank lines not allowed in MMD metadata - we replace with .
-        removeBlankLines   = trimr . unlines . map (\x ->
-                               if all isSpace x then "." else x) . lines
-mmdTitleBlock _ = empty
-
-plainTitleBlock :: Doc -> [Doc] -> Doc -> Doc
-plainTitleBlock tit auths dat =
-  tit <> cr <>
-  (hcat (intersperse (text "; ") auths)) <> cr <>
-  dat <> cr
-
-yamlMetadataBlock :: Value -> Doc
-yamlMetadataBlock v = "---" $$ (jsonToYaml v) $$ "---"
-
-jsonToYaml :: Value -> Doc
-jsonToYaml (Object hashmap) =
-  vcat $ map (\(k,v) ->
-          case (text (T.unpack k), v, jsonToYaml v) of
-               (k', Array vec, x)
-                 | V.null vec     -> empty
-                 | otherwise      -> (k' <> ":") $$ x
-               (k', Object _, x)  -> (k' <> ":") $$ nest 2 x
-               (_, String "", _)  -> empty
-               (k', _, x)         -> k' <> ":" <> space <> hang 2 "" x)
-       $ sortBy (comparing fst) $ H.toList hashmap
-jsonToYaml (Array vec) =
-  vcat $ map (\v -> hang 2 "- " (jsonToYaml v)) $ V.toList vec
-jsonToYaml (String "") = empty
-jsonToYaml (String s) =
-  case T.unpack s of
-     x | '\n' `elem` x -> hang 2 ("|" <> cr) $ text x
-       | not (any isPunctuation x) -> text x
-       | otherwise     -> text $ "'" ++ substitute "'" "''" x ++ "'"
-jsonToYaml (Bool b) = text $ show b
-jsonToYaml (Number n) = text $ show n
-jsonToYaml _ = empty
-
--- | Return markdown representation of document.
-pandocToMarkdown :: PandocMonad m => WriterOptions -> Pandoc -> MD m Text
-pandocToMarkdown opts (Pandoc meta blocks) = do
-  let colwidth = if writerWrapText opts == WrapAuto
-                    then Just $ writerColumns opts
-                    else Nothing
-  isPlain <- asks envPlain
-  let render' :: Doc -> Text
-      render' = render colwidth . chomp
-  metadata <- metaToJSON'
-               (fmap render' . blockListToMarkdown opts)
-               (fmap render' . blockToMarkdown opts . Plain)
-               meta
-  let title' = maybe empty text $ getField "title" metadata
-  let authors' = maybe [] (map text) $ getField "author" metadata
-  let date' = maybe empty text $ getField "date" metadata
-  let titleblock = case writerTemplate opts of
-                        Just _ | isPlain ->
-                                 plainTitleBlock title' authors' date'
-                               | isEnabled Ext_yaml_metadata_block opts ->
-                                   yamlMetadataBlock metadata
-                               | isEnabled Ext_pandoc_title_block opts ->
-                                   pandocTitleBlock title' authors' date'
-                               | isEnabled Ext_mmd_title_block opts ->
-                                   mmdTitleBlock metadata
-                               | otherwise -> empty
-                        Nothing -> empty
-  let headerBlocks = filter isHeaderBlock blocks
-  toc <- if writerTableOfContents opts
-         then render' <$> tableOfContents opts headerBlocks
-         else return ""
-  -- Strip off final 'references' header if markdown citations enabled
-  let blocks' = if isEnabled Ext_citations opts
-                   then case reverse blocks of
-                             (Div (_,["references"],_) _):xs -> reverse xs
-                             _                               -> blocks
-                   else blocks
-  body <- blockListToMarkdown opts blocks'
-  notesAndRefs' <- notesAndRefs opts
-  let main = render' $ body <> notesAndRefs'
-  let context  = -- for backwards compatibility we populate toc
-                 -- with the contents of the toc, rather than a
-                 -- boolean:
-                 defField "toc" toc
-               $ defField "table-of-contents" toc
-               $ defField "body" main
-               $ (if isNullMeta meta
-                     then id
-                     else defField "titleblock" (render' titleblock))
-               $ addVariablesToJSON opts metadata
-  case writerTemplate opts of
-       Nothing  -> return main
-       Just tpl -> renderTemplate' tpl context
-
--- | Return markdown representation of reference key table.
-refsToMarkdown :: PandocMonad m => WriterOptions -> Refs -> MD m Doc
-refsToMarkdown opts refs = mapM (keyToMarkdown opts) refs >>= return . vcat
-
--- | Return markdown representation of a reference key.
-keyToMarkdown :: PandocMonad m
-              => WriterOptions
-              -> Ref
-              -> MD m Doc
-keyToMarkdown opts (label', (src, tit), attr) = do
-  let tit' = if null tit
-                then empty
-                else space <> "\"" <> text tit <> "\""
-  return $ nest 2 $ hang 2
-            ("[" <> label' <> "]:" <> space) (text src <> tit')
-            <+> linkAttributes opts attr
-
--- | Return markdown representation of notes.
-notesToMarkdown :: PandocMonad m => WriterOptions -> [[Block]] -> MD m Doc
-notesToMarkdown opts notes = do
-  n <- gets stNoteNum
-  notes' <- mapM (\(num, note) -> noteToMarkdown opts num note) (zip [n..] notes)
-  modify $ \st -> st { stNoteNum = stNoteNum st + length notes }
-  return $ vsep notes'
-
--- | Return markdown representation of a note.
-noteToMarkdown :: PandocMonad m => WriterOptions -> Int -> [Block] -> MD m Doc
-noteToMarkdown opts num blocks = do
-  contents  <- blockListToMarkdown opts blocks
-  let num' = text $ writerIdentifierPrefix opts ++ show num
-  let marker = if isEnabled Ext_footnotes opts
-                  then text "[^" <> num' <> text "]:"
-                  else text "[" <> num' <> text "]"
-  let markerSize = 4 + offset num'
-  let spacer = case writerTabStop opts - markerSize of
-                     n | n > 0  -> text $ replicate n ' '
-                     _ -> text " "
-  return $ if isEnabled Ext_footnotes opts
-              then hang (writerTabStop opts) (marker <> spacer) contents
-              else marker <> spacer <> contents
-
--- | Escape special characters for Markdown.
-escapeString :: WriterOptions -> String -> String
-escapeString _  [] = []
-escapeString opts (c:cs) =
-  case c of
-       '<' | isEnabled Ext_all_symbols_escapable opts ->
-              '\\' : '<' : escapeString opts cs
-           | otherwise -> "&lt;" ++ escapeString opts cs
-       '>' | isEnabled Ext_all_symbols_escapable opts ->
-              '\\' : '>' : escapeString opts cs
-           | otherwise -> "&gt;" ++ escapeString opts cs
-       _ | c `elem` ['\\','`','*','_','[',']','#'] ->
-              '\\':c:escapeString opts cs
-       '|' | isEnabled Ext_pipe_tables opts -> '\\':'|':escapeString opts cs
-       '^' | isEnabled Ext_superscript opts -> '\\':'^':escapeString opts cs
-       '~' | isEnabled Ext_subscript opts -> '\\':'~':escapeString opts cs
-       '$' | isEnabled Ext_tex_math_dollars opts -> '\\':'$':escapeString opts cs
-       '\'' | isEnabled Ext_smart opts -> '\\':'\'':escapeString opts cs
-       '"' | isEnabled Ext_smart opts -> '\\':'"':escapeString opts cs
-       '-' | isEnabled Ext_smart opts ->
-              case cs of
-                   '-':_ -> '\\':'-':escapeString opts cs
-                   _     -> '-':escapeString opts cs
-       '.' | isEnabled Ext_smart opts ->
-              case cs of
-                   '.':'.':rest -> '\\':'.':'.':'.':escapeString opts rest
-                   _            -> '.':escapeString opts cs
-       _ -> c : escapeString opts cs
-
--- | Construct table of contents from list of header blocks.
-tableOfContents :: PandocMonad m => WriterOptions -> [Block] -> MD m Doc
-tableOfContents opts headers = do
-  contents <- BulletList <$> mapM (elementToListItem opts) (hierarchicalize headers)
-  blockToMarkdown opts contents
-
--- | Converts an Element to a list item for a table of contents,
-elementToListItem :: PandocMonad m => WriterOptions -> Element -> MD m [Block]
-elementToListItem opts (Sec lev _nums (ident,_,_) headerText subsecs)
-  = do isPlain <- asks envPlain
-       let headerLink = if null ident || isPlain
-                         then walk deNote headerText
-                         else [Link nullAttr (walk deNote headerText)
-                                 ('#':ident, "")]
-       listContents <- if null subsecs || lev >= writerTOCDepth opts
-                          then return []
-                          else mapM (elementToListItem opts) subsecs
-       return [Plain headerLink, BulletList listContents]
-elementToListItem _ (Blk _) = return []
-
-attrsToMarkdown :: Attr -> Doc
-attrsToMarkdown attribs = braces $ hsep [attribId, attribClasses, attribKeys]
-        where attribId = case attribs of
-                                ([],_,_) -> empty
-                                (i,_,_)  -> "#" <> text i
-              attribClasses = case attribs of
-                                (_,[],_) -> empty
-                                (_,cs,_) -> hsep $
-                                            map (text . ('.':))
-                                            cs
-              attribKeys = case attribs of
-                                (_,_,[]) -> empty
-                                (_,_,ks) -> hsep $
-                                            map (\(k,v) -> text k
-                                              <> "=\"" <> text v <> "\"") ks
-
-linkAttributes :: WriterOptions -> Attr -> Doc
-linkAttributes opts attr =
-  if isEnabled Ext_link_attributes opts && attr /= nullAttr
-     then attrsToMarkdown attr
-     else empty
-
--- | Ordered list start parser for use in Para below.
-olMarker :: Parser [Char] ParserState Char
-olMarker = do (start, style', delim) <- anyOrderedListMarker
-              if delim == Period &&
-                          (style' == UpperAlpha || (style' == UpperRoman &&
-                          start `elem` [1, 5, 10, 50, 100, 500, 1000]))
-                          then spaceChar >> spaceChar
-                          else spaceChar
-
--- | True if string begins with an ordered list marker
-beginsWithOrderedListMarker :: String -> Bool
-beginsWithOrderedListMarker str =
-  case runParser olMarker defaultParserState "para start" (take 10 str) of
-         Left  _ -> False
-         Right _ -> True
-
-notesAndRefs :: PandocMonad m => WriterOptions -> MD m Doc
-notesAndRefs opts = do
-  notes' <- reverse <$> gets stNotes >>= notesToMarkdown opts
-  modify $ \s -> s { stNotes = [] }
-  refs' <- reverse <$> gets stRefs >>= refsToMarkdown opts
-  modify $ \s -> s { stRefs = [] }
-
-  let endSpacing =
-        if | writerReferenceLocation opts == EndOfDocument -> empty
-           | isEmpty notes' && isEmpty refs' -> empty
-           | otherwise -> blankline
-
-  return $
-    (if isEmpty notes' then empty else blankline <> notes') <>
-    (if isEmpty refs' then empty else blankline <> refs') <>
-    endSpacing
-
--- | Convert Pandoc block element to markdown.
-blockToMarkdown :: PandocMonad m
-                => WriterOptions -- ^ Options
-                -> Block         -- ^ Block element
-                -> MD m Doc
-blockToMarkdown opts blk =
-  local (\env -> env {envBlockLevel = envBlockLevel env + 1}) $
-  do doc <- blockToMarkdown' opts blk
-     blkLevel <- asks envBlockLevel
-     if writerReferenceLocation opts == EndOfBlock && blkLevel == 1
-       then notesAndRefs opts >>= (\d -> return $ doc <> d)
-       else return doc
-
-blockToMarkdown' :: PandocMonad m
-                 => WriterOptions -- ^ Options
-                 -> Block         -- ^ Block element
-                 -> MD m Doc
-blockToMarkdown' _ Null = return empty
-blockToMarkdown' opts (Div attrs ils) = do
-  contents <- blockListToMarkdown opts ils
-  return $
-    case () of
-         _ | isEnabled Ext_fenced_divs opts &&
-             attrs /= nullAttr ->
-                nowrap (text ":::" <+> attrsToMarkdown attrs) $$
-                chomp contents $$
-                text ":::" <> blankline
-           | isEnabled Ext_native_divs opts ||
-             (isEnabled Ext_raw_html opts &&
-              isEnabled Ext_markdown_in_html_blocks opts) ->
-                tagWithAttrs "div" attrs <> blankline <>
-                contents <> blankline <> "</div>" <> blankline
-           | otherwise -> contents <> blankline
-blockToMarkdown' opts (Plain inlines) = do
-  contents <- inlineListToMarkdown opts inlines
-  -- escape if para starts with ordered list marker
-  isPlain <- asks envPlain
-  let colwidth = if writerWrapText opts == WrapAuto
-                    then Just $ writerColumns opts
-                    else Nothing
-  let rendered = render colwidth contents
-  let escapeMarker (x:xs) | x `elem` (".()" :: String) = '\\':x:xs
-                          | otherwise                  = x : escapeMarker xs
-      escapeMarker []                                  = []
-  let contents' =
-       case rendered of
-            '%':_ | isEnabled Ext_pandoc_title_block opts &&
-                    isEnabled Ext_all_symbols_escapable opts ->
-                    "\\" <> contents
-            '+':s:_ | not isPlain && isSpace s -> "\\" <> contents
-            '*':s:_ | not isPlain && isSpace s -> "\\" <> contents
-            '-':s:_ | not isPlain && isSpace s -> "\\" <> contents
-            '+':[]  | not isPlain -> "\\" <> contents
-            '*':[]  | not isPlain -> "\\" <> contents
-            '-':[]  | not isPlain -> "\\" <> contents
-            '|':_ | (isEnabled Ext_line_blocks opts ||
-                     isEnabled Ext_pipe_tables opts)
-                    && isEnabled Ext_all_symbols_escapable opts
-                  -> "\\" <> contents
-            _ | not isPlain && beginsWithOrderedListMarker rendered
-                  && isEnabled Ext_all_symbols_escapable opts
-                  -> text $ escapeMarker rendered
-              | otherwise -> contents
-  return $ contents' <> cr
--- title beginning with fig: indicates figure
-blockToMarkdown' opts (Para [Image attr alt (src,'f':'i':'g':':':tit)]) =
-  blockToMarkdown opts (Para [Image attr alt (src,tit)])
-blockToMarkdown' opts (Para inlines) =
-  (<> blankline) `fmap` blockToMarkdown opts (Plain inlines)
-blockToMarkdown' opts (LineBlock lns) =
-  if isEnabled Ext_line_blocks opts
-  then do
-    mdLines <- mapM (inlineListToMarkdown opts) lns
-    return $ (vcat $ map (hang 2 (text "| ")) mdLines) <> blankline
-  else blockToMarkdown opts $ linesToPara lns
-blockToMarkdown' opts b@(RawBlock f str)
-  | f `elem` ["markdown", "markdown_github", "markdown_phpextra",
-              "markdown_mmd", "markdown_strict"]
-              = return $ text str <> text "\n"
-  | f `elem` ["html", "html5", "html4"] && isEnabled Ext_raw_html opts = do
-    plain <- asks envPlain
-    return $ if plain
-                then empty
-                else if isEnabled Ext_markdown_attribute opts
-                        then text (addMarkdownAttribute str) <> text "\n"
-                        else text str <> text "\n"
-  | f `elem` ["latex", "tex"] && isEnabled Ext_raw_tex opts = do
-    plain <- asks envPlain
-    return $ if plain
-                then empty
-                else text str <> text "\n"
-  | otherwise = do
-      report $ BlockNotRendered b
-      return empty
-blockToMarkdown' opts HorizontalRule = do
-  return $ blankline <> text (replicate (writerColumns opts) '-') <> blankline
-blockToMarkdown' opts (Header level attr inlines) = do
-  -- first, if we're putting references at the end of a section, we
-  -- put them here.
-  blkLevel <- asks envBlockLevel
-  refs <- if writerReferenceLocation opts == EndOfSection && blkLevel == 1
-          then notesAndRefs opts
-          else return empty
-
-  plain <- asks envPlain
-  -- we calculate the id that would be used by auto_identifiers
-  -- so we know whether to print an explicit identifier
-  ids <- gets stIds
-  let autoId = uniqueIdent inlines ids
-  modify $ \st -> st{ stIds = Set.insert autoId ids }
-  let attr' = case attr of
-                   ("",[],[]) -> empty
-                   (id',[],[]) | isEnabled Ext_auto_identifiers opts
-                                 && id' == autoId -> empty
-                   (id',_,_)   | isEnabled Ext_mmd_header_identifiers opts ->
-                                    space <> brackets (text id')
-                   _ | isEnabled Ext_header_attributes opts ->
-                                    space <> attrsToMarkdown attr
-                     | otherwise -> empty
-  contents <- inlineListToMarkdown opts $
-                 -- ensure no newlines; see #3736
-                 walk lineBreakToSpace $
-                 if level == 1 && plain
-                    then capitalize inlines
-                    else inlines
-  let setext = writerSetextHeaders opts
-      hdr = nowrap $ case level of
-            1 | plain -> blanklines 3 <> contents <> blanklines 2
-              | setext ->
-                  contents <> attr' <> cr <> text (replicate (offset contents) '=') <>
-                  blankline
-            2 | plain -> blanklines 2 <> contents <> blankline
-              | setext ->
-                  contents <> attr' <> cr <> text (replicate (offset contents) '-') <>
-                  blankline
-            -- ghc interprets '#' characters in column 1 as linenum specifiers.
-            _ | plain || isEnabled Ext_literate_haskell opts ->
-                contents <> blankline
-            _ -> text (replicate level '#') <> space <> contents <> attr' <> blankline
-
-  return $ refs <> hdr
-blockToMarkdown' opts (CodeBlock (_,classes,_) str)
-  | "haskell" `elem` classes && "literate" `elem` classes &&
-    isEnabled Ext_literate_haskell opts =
-  return $ prefixed "> " (text str) <> blankline
-blockToMarkdown' opts (CodeBlock attribs str) = return $
-  case attribs == nullAttr of
-     False | isEnabled Ext_backtick_code_blocks opts ->
-          backticks <> attrs <> cr <> text str <> cr <> backticks <> blankline
-           | isEnabled Ext_fenced_code_blocks opts ->
-          tildes <> attrs <> cr <> text str <> cr <> tildes <> blankline
-     _ -> nest (writerTabStop opts) (text str) <> blankline
-   where tildes    = text $ case [ln | ln <- lines str, all (=='~') ln] of
-                               [] -> "~~~~"
-                               xs -> case maximum $ map length xs of
-                                          n | n < 3 -> "~~~~"
-                                            | otherwise -> replicate (n+1) '~'
-         backticks = text $ case [ln | ln <- lines str, all (=='`') ln] of
-                               [] -> "```"
-                               xs -> case maximum $ map length xs of
-                                          n | n < 3 -> "```"
-                                            | otherwise -> replicate (n+1) '`'
-         attrs  = if isEnabled Ext_fenced_code_attributes opts
-                     then nowrap $ " " <> attrsToMarkdown attribs
-                     else case attribs of
-                                (_,(cls:_),_) -> " " <> text cls
-                                _             -> empty
-blockToMarkdown' opts (BlockQuote blocks) = do
-  plain <- asks envPlain
-  -- if we're writing literate haskell, put a space before the bird tracks
-  -- so they won't be interpreted as lhs...
-  let leader = if isEnabled Ext_literate_haskell opts
-                  then " > "
-                  else if plain then "  " else "> "
-  contents <- blockListToMarkdown opts blocks
-  return $ (prefixed leader contents) <> blankline
-blockToMarkdown' opts t@(Table caption aligns widths headers rows) =  do
-  let numcols = maximum (length aligns : length widths :
-                           map length (headers:rows))
-  caption' <- inlineListToMarkdown opts caption
-  let caption'' = if null caption || not (isEnabled Ext_table_captions opts)
-                     then blankline
-                     else blankline $$ (": " <> caption') $$ blankline
-  let isLineBreak LineBreak = Any True
-      isLineBreak _         = Any False
-  let hasLineBreak = getAny . query isLineBreak
-  let isSimpleCell [Plain ils] = not (hasLineBreak ils)
-      isSimpleCell [Para ils ] = not (hasLineBreak ils)
-      isSimpleCell []          = True
-      isSimpleCell _           = False
-  let hasSimpleCells = all isSimpleCell (concat (headers:rows))
-  let isSimple = hasSimpleCells && all (==0) widths
-  let isPlainBlock (Plain _) = True
-      isPlainBlock _         = False
-  let hasBlocks = not (all isPlainBlock $ concat . concat $ headers:rows)
-  let padRow r = case numcols - length r of
-                       x | x > 0 -> r ++ replicate x empty
-                         | otherwise -> r
-  let aligns' = case numcols - length aligns of
-                     x | x > 0 -> aligns ++ replicate x AlignDefault
-                       | otherwise -> aligns
-  let widths' = case numcols - length widths of
-                     x | x > 0 -> widths ++ replicate x 0.0
-                       | otherwise -> widths
-  (nst,tbl) <-
-     case True of
-          _ | isSimple &&
-              isEnabled Ext_simple_tables opts -> do
-                rawHeaders <- padRow <$> mapM (blockListToMarkdown opts) headers
-                rawRows <- mapM (fmap padRow . mapM (blockListToMarkdown opts))
-                           rows
-                (nest 2,) <$> pandocTable opts False (all null headers)
-                                aligns' widths' rawHeaders rawRows
-            | isSimple &&
-              isEnabled Ext_pipe_tables opts -> do
-                rawHeaders <- padRow <$> mapM (blockListToMarkdown opts) headers
-                rawRows <- mapM (fmap padRow . mapM (blockListToMarkdown opts))
-                           rows
-                (id,) <$> pipeTable (all null headers) aligns' rawHeaders rawRows
-            | not hasBlocks &&
-              isEnabled Ext_multiline_tables opts -> do
-                rawHeaders <- padRow <$> mapM (blockListToMarkdown opts) headers
-                rawRows <- mapM (fmap padRow . mapM (blockListToMarkdown opts))
-                           rows
-                (nest 2,) <$> pandocTable opts True (all null headers)
-                                aligns' widths' rawHeaders rawRows
-            | isEnabled Ext_grid_tables opts &&
-               writerColumns opts >= 8 * numcols -> (id,) <$>
-                gridTable opts blockListToMarkdown
-                  (all null headers) aligns' widths' headers rows
-            | isEnabled Ext_raw_html opts -> fmap (id,) $
-                   (text . T.unpack) <$>
-                   (writeHtml5String def $ Pandoc nullMeta [t])
-            | hasSimpleCells &&
-              isEnabled Ext_pipe_tables opts -> do
-                rawHeaders <- padRow <$> mapM (blockListToMarkdown opts) headers
-                rawRows <- mapM (fmap padRow . mapM (blockListToMarkdown opts))
-                           rows
-                (id,) <$> pipeTable (all null headers) aligns' rawHeaders rawRows
-            | otherwise -> return $ (id, text "[TABLE]")
-  return $ nst $ tbl $$ caption'' $$ blankline
-blockToMarkdown' opts (BulletList items) = do
-  contents <- inList $ mapM (bulletListItemToMarkdown opts) items
-  return $ cat contents <> blankline
-blockToMarkdown' opts (OrderedList (start,sty,delim) items) = do
-  let start' = if isEnabled Ext_startnum opts then start else 1
-  let sty'   = if isEnabled Ext_fancy_lists opts then sty else DefaultStyle
-  let delim' = if isEnabled Ext_fancy_lists opts then delim else DefaultDelim
-  let attribs = (start', sty', delim')
-  let markers  = orderedListMarkers attribs
-  let markers' = map (\m -> if length m < 3
-                               then m ++ replicate (3 - length m) ' '
-                               else m) markers
-  contents <- inList $
-              mapM (\(item, num) -> orderedListItemToMarkdown opts item num) $
-              zip markers' items
-  return $ cat contents <> blankline
-blockToMarkdown' opts (DefinitionList items) = do
-  contents <- inList $ mapM (definitionListItemToMarkdown opts) items
-  return $ cat contents <> blankline
-
-inList :: Monad m => MD m a -> MD m a
-inList p = local (\env -> env {envInList = True}) p
-
-addMarkdownAttribute :: String -> String
-addMarkdownAttribute s =
-  case span isTagText $ reverse $ parseTags s of
-       (xs,(TagOpen t attrs:rest)) ->
-            renderTags' $ reverse rest ++ (TagOpen t attrs' : reverse xs)
-              where attrs' = ("markdown","1"):[(x,y) | (x,y) <- attrs,
-                                 x /= "markdown"]
-       _ -> s
-
-pipeTable :: PandocMonad m => Bool -> [Alignment] -> [Doc] -> [[Doc]] -> MD m Doc
-pipeTable headless aligns rawHeaders rawRows = do
-  let sp = text " "
-  let blockFor AlignLeft   x y = lblock (x + 2) (sp <> y) <> lblock 0 empty
-      blockFor AlignCenter x y = cblock (x + 2) (sp <> y) <> lblock 0 empty
-      blockFor AlignRight  x y = rblock (x + 2) (sp <> y) <> lblock 0 empty
-      blockFor _           x y = lblock (x + 2) (sp <> y) <> lblock 0 empty
-  let widths = map (max 3 . maximum . map offset) $ transpose (rawHeaders : rawRows)
-  let torow cs = nowrap $ text "|" <>
-                    hcat (intersperse (text "|") $
-                          zipWith3 blockFor aligns widths (map chomp cs))
-                    <> text "|"
-  let toborder (a, w) = text $ case a of
-                             AlignLeft    -> ':':replicate (w + 1) '-'
-                             AlignCenter  -> ':':replicate w '-' ++ ":"
-                             AlignRight   -> replicate (w + 1) '-' ++ ":"
-                             AlignDefault -> replicate (w + 2) '-'
-  -- note:  pipe tables can't completely lack a
-  -- header; for a headerless table, we need a header of empty cells.
-  -- see jgm/pandoc#1996.
-  let header = if headless
-                  then torow (replicate (length aligns) empty)
-                  else torow rawHeaders
-  let border = nowrap $ text "|" <> hcat (intersperse (text "|") $
-                        map toborder $ zip aligns widths) <> text "|"
-  let body   = vcat $ map torow rawRows
-  return $ header $$ border $$ body
-
-pandocTable :: PandocMonad m
-            => WriterOptions -> Bool -> Bool -> [Alignment] -> [Double]
-            -> [Doc] -> [[Doc]] -> MD m Doc
-pandocTable opts multiline headless aligns widths rawHeaders rawRows = do
-  let isSimple = all (==0) widths
-  let alignHeader alignment = case alignment of
-                                AlignLeft    -> lblock
-                                AlignCenter  -> cblock
-                                AlignRight   -> rblock
-                                AlignDefault -> lblock
-  -- Number of characters per column necessary to output every cell
-  -- without requiring a line break.
-  -- The @+2@ is needed for specifying the alignment.
-  let numChars    = (+ 2) . maximum . map offset
-  -- Number of characters per column necessary to output every cell
-  -- without requiring a line break *inside a word*.
-  -- The @+2@ is needed for specifying the alignment.
-  let minNumChars = (+ 2) . maximum . map minOffset
-  let columns = transpose (rawHeaders : rawRows)
-  -- minimal column width without wrapping a single word
-  let relWidth w col =
-         max (floor $ fromIntegral (writerColumns opts) * w)
-             (if writerWrapText opts == WrapAuto
-                 then minNumChars col
-                 else numChars col)
-  let widthsInChars
-        | isSimple  = map numChars columns
-        | otherwise = zipWith relWidth widths columns
-  let makeRow = hcat . intersperse (lblock 1 (text " ")) .
-                   (zipWith3 alignHeader aligns widthsInChars)
-  let rows' = map makeRow rawRows
-  let head' = makeRow rawHeaders
-  let underline = cat $ intersperse (text " ") $
-                  map (\width -> text (replicate width '-')) widthsInChars
-  let border = if multiline
-                  then text (replicate (sum widthsInChars +
-                          length widthsInChars - 1) '-')
-                  else if headless
-                          then underline
-                          else empty
-  let head'' = if headless
-                  then empty
-                  else border <> cr <> head'
-  let body = if multiline
-                then vsep rows'
-                else vcat rows'
-  let bottom = if headless
-                  then underline
-                  else border
-  return $ head'' $$ underline $$ body $$ bottom
-
-itemEndsWithTightList :: [Block] -> Bool
-itemEndsWithTightList bs =
-  case bs of
-        [Plain _, BulletList xs]    -> isTightList xs
-        [Plain _, OrderedList _ xs] -> isTightList xs
-        _                           -> False
-
--- | Convert bullet list item (list of blocks) to markdown.
-bulletListItemToMarkdown :: PandocMonad m => WriterOptions -> [Block] -> MD m Doc
-bulletListItemToMarkdown opts bs = do
-  contents <- blockListToMarkdown opts bs
-  let sps = replicate (writerTabStop opts - 2) ' '
-  let start = text ('-' : ' ' : sps)
-  -- remove trailing blank line if item ends with a tight list
-  let contents' = if itemEndsWithTightList bs
-                     then chomp contents <> cr
-                     else contents
-  return $ hang (writerTabStop opts) start $ contents' <> cr
-
--- | Convert ordered list item (a list of blocks) to markdown.
-orderedListItemToMarkdown :: PandocMonad m
-                          => WriterOptions -- ^ options
-                          -> String        -- ^ list item marker
-                          -> [Block]       -- ^ list item (list of blocks)
-                          -> MD m Doc
-orderedListItemToMarkdown opts marker bs = do
-  contents <- blockListToMarkdown opts bs
-  let sps = case length marker - writerTabStop opts of
-                   n | n > 0 -> text $ replicate n ' '
-                   _ -> text " "
-  let start = text marker <> sps
-  -- remove trailing blank line if item ends with a tight list
-  let contents' = if itemEndsWithTightList bs
-                     then chomp contents <> cr
-                     else contents
-  return $ hang (writerTabStop opts) start $ contents' <> cr
-
--- | Convert definition list item (label, list of blocks) to markdown.
-definitionListItemToMarkdown :: PandocMonad m
-                             => WriterOptions
-                             -> ([Inline],[[Block]])
-                             -> MD m Doc
-definitionListItemToMarkdown opts (label, defs) = do
-  labelText <- inlineListToMarkdown opts label
-  defs' <- mapM (mapM (blockToMarkdown opts)) defs
-  if isEnabled Ext_definition_lists opts
-     then do
-       let tabStop = writerTabStop opts
-       isPlain <- asks envPlain
-       let leader  = if isPlain then "   " else ":  "
-       let sps = case writerTabStop opts - 3 of
-                      n | n > 0   -> text $ replicate n ' '
-                      _ -> text " "
-       if isEnabled Ext_compact_definition_lists opts
-          then do
-            let contents = vcat $ map (\d -> hang tabStop (leader <> sps)
-                                $ vcat d <> cr) defs'
-            return $ nowrap labelText <> cr <> contents <> cr
-          else do
-            let contents = vcat $ map (\d -> hang tabStop (leader <> sps)
-                                $ vcat d <> cr) defs'
-            let isTight = case defs of
-                               ((Plain _ : _): _) -> True
-                               _                  -> False
-            return $ blankline <> nowrap labelText <>
-                     (if isTight then cr else blankline) <> contents <> blankline
-     else do
-       return $ nowrap labelText <> text "  " <> cr <>
-                vsep (map vsep defs') <> blankline
-
--- | Convert list of Pandoc block elements to markdown.
-blockListToMarkdown :: PandocMonad m
-                    => WriterOptions -- ^ Options
-                    -> [Block]       -- ^ List of block elements
-                    -> MD m Doc
-blockListToMarkdown opts blocks = do
-  inlist <- asks envInList
-  isPlain <- asks envPlain
-  -- a) insert comment between list and indented code block, or the
-  -- code block will be treated as a list continuation paragraph
-  -- b) change Plain to Para unless it's followed by a RawBlock
-  -- or has a list as its parent (#3487)
-  let fixBlocks (b : CodeBlock attr x : rest)
-         | (not (isEnabled Ext_fenced_code_blocks opts) || attr == nullAttr)
-             && isListBlock b = b : commentSep : CodeBlock attr x :
-                                fixBlocks rest
-      fixBlocks (b1@(BulletList _) : b2@(BulletList _) : bs) =
-           b1 : commentSep : fixBlocks (b2:bs)
-      fixBlocks (b1@(OrderedList _ _) : b2@(OrderedList _ _) : bs) =
-           b1 : commentSep : fixBlocks (b2:bs)
-      fixBlocks (b1@(DefinitionList _) : b2@(DefinitionList _) : bs) =
-           b1 : commentSep : fixBlocks (b2:bs)
-      fixBlocks (Plain ils : bs@(RawBlock{}:_)) =
-           Plain ils : fixBlocks bs
-      fixBlocks (Plain ils : bs) | inlist =
-           Plain ils : fixBlocks bs
-      fixBlocks (Plain ils : bs) =
-           Para ils : fixBlocks bs
-      fixBlocks (x : xs)             = x : fixBlocks xs
-      fixBlocks []                   = []
-      isListBlock (BulletList _)     = True
-      isListBlock (OrderedList _ _)  = True
-      isListBlock (DefinitionList _) = True
-      isListBlock _                  = False
-      commentSep  = if isPlain
-                       then Null
-                       else if isEnabled Ext_raw_html opts
-                            then RawBlock "html" "<!-- -->\n"
-                            else RawBlock "markdown" "&nbsp;\n"
-  mapM (blockToMarkdown opts) (fixBlocks blocks) >>= return . cat
-
-getKey :: Doc -> Key
-getKey = toKey . render Nothing
-
--- | Get reference for target; if none exists, create unique one and return.
---   Prefer label if possible; otherwise, generate a unique key.
-getReference :: PandocMonad m => Attr -> Doc -> Target -> MD m Doc
-getReference attr label target = do
-  refs <- gets stRefs
-  case find (\(_,t,a) -> t == target && a == attr) refs of
-    Just (ref, _, _) -> return ref
-    Nothing       -> do
-      keys <- gets stKeys
-      case M.lookup (getKey label) keys of
-           Nothing -> do -- no other refs with this label
-             (lab', idx) <- if isEmpty label
-                               then do
-                                 i <- (+ 1) <$> gets stLastIdx
-                                 modify $ \s -> s{ stLastIdx = i }
-                                 return (text (show i), i)
-                               else return (label, 0)
-             modify (\s -> s{
-               stRefs = (lab', target, attr) : refs,
-               stKeys = M.insert (getKey label)
-                           (M.insert (target, attr) idx mempty)
-                                 (stKeys s) })
-             return lab'
-
-           Just km -> do -- we have refs with this label
-             case M.lookup (target, attr) km of
-                  Just i -> do
-                    let lab' = label <> if i == 0
-                                           then mempty
-                                           else text (show i)
-                    -- make sure it's in stRefs; it may be
-                    -- a duplicate that was printed in a previous
-                    -- block:
-                    when ((lab', target, attr) `notElem` refs) $
-                       modify (\s -> s{
-                         stRefs = (lab', target, attr) : refs })
-                    return lab'
-                  Nothing -> do -- but this one is to a new target
-                    i <- (+ 1) <$> gets stLastIdx
-                    modify $ \s -> s{ stLastIdx = i }
-                    let lab' = text (show i)
-                    modify (\s -> s{
-                       stRefs = (lab', target, attr) : refs,
-                       stKeys = M.insert (getKey label)
-                                   (M.insert (target, attr) i km)
-                                         (stKeys s) })
-                    return lab'
-
--- | Convert list of Pandoc inline elements to markdown.
-inlineListToMarkdown :: PandocMonad m => WriterOptions -> [Inline] -> MD m Doc
-inlineListToMarkdown opts lst = do
-  inlist <- asks envInList
-  go (if inlist then avoidBadWrapsInList lst else lst)
-  where go [] = return empty
-        go (i:is) = case i of
-            (Link _ _ _) -> case is of
-                -- If a link is followed by another link, or '[', '(' or ':'
-                -- then we don't shortcut
-                (Link _ _ _):_                    -> unshortcutable
-                Space:(Link _ _ _):_              -> unshortcutable
-                Space:(Str('[':_)):_              -> unshortcutable
-                Space:(RawInline _ ('[':_)):_     -> unshortcutable
-                Space:(Cite _ _):_                -> unshortcutable
-                SoftBreak:(Link _ _ _):_          -> unshortcutable
-                SoftBreak:(Str('[':_)):_          -> unshortcutable
-                SoftBreak:(RawInline _ ('[':_)):_ -> unshortcutable
-                SoftBreak:(Cite _ _):_            -> unshortcutable
-                LineBreak:(Link _ _ _):_          -> unshortcutable
-                LineBreak:(Str('[':_)):_          -> unshortcutable
-                LineBreak:(RawInline _ ('[':_)):_ -> unshortcutable
-                LineBreak:(Cite _ _):_            -> unshortcutable
-                (Cite _ _):_                      -> unshortcutable
-                Str ('[':_):_                     -> unshortcutable
-                Str ('(':_):_                     -> unshortcutable
-                Str (':':_):_                     -> unshortcutable
-                (RawInline _ ('[':_)):_           -> unshortcutable
-                (RawInline _ ('(':_)):_           -> unshortcutable
-                (RawInline _ (':':_)):_           -> unshortcutable
-                (RawInline _ (' ':'[':_)):_       -> unshortcutable
-                _                                 -> shortcutable
-            _ -> shortcutable
-          where shortcutable = liftM2 (<>) (inlineToMarkdown opts i) (go is)
-                unshortcutable = do
-                    iMark <- local
-                             (\env -> env { envRefShortcutable = False })
-                             (inlineToMarkdown opts i)
-                    fmap (iMark <>) (go is)
-
-isSp :: Inline -> Bool
-isSp Space     = True
-isSp SoftBreak = True
-isSp _         = False
-
-avoidBadWrapsInList :: [Inline] -> [Inline]
-avoidBadWrapsInList [] = []
-avoidBadWrapsInList (s:Str ('>':cs):xs) | isSp s =
-  Str (' ':'>':cs) : avoidBadWrapsInList xs
-avoidBadWrapsInList (s:Str [c]:[])
-  | isSp s && c `elem` ['-','*','+'] = Str [' ', c] : []
-avoidBadWrapsInList (s:Str [c]:Space:xs)
-  | isSp s && c `elem` ['-','*','+'] =
-    Str [' ', c] : Space : avoidBadWrapsInList xs
-avoidBadWrapsInList (s:Str cs:Space:xs)
-  | isSp s && isOrderedListMarker cs =
-    Str (' ':cs) : Space : avoidBadWrapsInList xs
-avoidBadWrapsInList (s:Str cs:[])
-  | isSp s && isOrderedListMarker cs = Str (' ':cs) : []
-avoidBadWrapsInList (x:xs) = x : avoidBadWrapsInList xs
-
-isOrderedListMarker :: String -> Bool
-isOrderedListMarker xs = not (null xs) && (last xs `elem` ['.',')']) &&
-              isRight (runParser (anyOrderedListMarker >> eof)
-                       defaultParserState "" xs)
-
-isRight :: Either a b -> Bool
-isRight (Right _) = True
-isRight (Left  _) = False
-
--- | Convert Pandoc inline element to markdown.
-inlineToMarkdown :: PandocMonad m => WriterOptions -> Inline -> MD m Doc
-inlineToMarkdown opts (Span attrs ils) = do
-  plain <- asks envPlain
-  contents <- inlineListToMarkdown opts ils
-  return $ case plain of
-                True -> contents
-                False | attrs == nullAttr -> contents
-                      | isEnabled Ext_bracketed_spans opts ->
-                        let attrs' = if attrs /= nullAttr
-                                        then attrsToMarkdown attrs
-                                        else empty
-                        in "[" <> contents <> "]" <> attrs'
-                      | isEnabled Ext_raw_html opts ||
-                        isEnabled Ext_native_spans opts ->
-                        tagWithAttrs "span" attrs <> contents <> text "</span>"
-                      | otherwise -> contents
-inlineToMarkdown _ (Emph []) = return empty
-inlineToMarkdown opts (Emph lst) = do
-  plain <- asks envPlain
-  contents <- inlineListToMarkdown opts lst
-  return $ if plain
-              then "_" <> contents <> "_"
-              else "*" <> contents <> "*"
-inlineToMarkdown _ (Strong []) = return empty
-inlineToMarkdown opts (Strong lst) = do
-  plain <- asks envPlain
-  if plain
-     then inlineListToMarkdown opts $ capitalize lst
-     else do
-       contents <- inlineListToMarkdown opts lst
-       return $ "**" <> contents <> "**"
-inlineToMarkdown _ (Strikeout []) = return empty
-inlineToMarkdown opts (Strikeout lst) = do
-  contents <- inlineListToMarkdown opts lst
-  return $ if isEnabled Ext_strikeout opts
-              then "~~" <> contents <> "~~"
-              else if isEnabled Ext_raw_html opts
-                       then "<s>" <> contents <> "</s>"
-                       else contents
-inlineToMarkdown _ (Superscript []) = return empty
-inlineToMarkdown opts (Superscript lst) =
-  local (\env -> env {envEscapeSpaces = True}) $ do
-    contents <- inlineListToMarkdown opts lst
-    return $ if isEnabled Ext_superscript opts
-                then "^" <> contents <> "^"
-                else if isEnabled Ext_raw_html opts
-                         then "<sup>" <> contents <> "</sup>"
-                         else
-                           let rendered = render Nothing contents
-                           in  case mapM toSuperscript rendered of
-                                    Just r  -> text r
-                                    Nothing -> text $ "^(" ++ rendered ++ ")"
-inlineToMarkdown _ (Subscript []) = return empty
-inlineToMarkdown opts (Subscript lst) =
-  local (\env -> env {envEscapeSpaces = True}) $ do
-    contents <- inlineListToMarkdown opts lst
-    return $ if isEnabled Ext_subscript opts
-                then "~" <> contents <> "~"
-                else if isEnabled Ext_raw_html opts
-                         then "<sub>" <> contents <> "</sub>"
-                         else
-                           let rendered = render Nothing contents
-                           in  case mapM toSubscript rendered of
-                                    Just r  -> text r
-                                    Nothing -> text $ "_(" ++ rendered ++ ")"
-inlineToMarkdown opts (SmallCaps lst) = do
-  plain <- asks envPlain
-  if not plain &&
-     (isEnabled Ext_raw_html opts || isEnabled Ext_native_spans opts)
-     then inlineToMarkdown opts (Span ("",["smallcaps"],[]) lst)
-     else inlineListToMarkdown opts $ capitalize lst
-inlineToMarkdown opts (Quoted SingleQuote lst) = do
-  contents <- inlineListToMarkdown opts lst
-  return $ if isEnabled Ext_smart opts
-              then "'" <> contents <> "'"
-              else "‘" <> contents <> "’"
-inlineToMarkdown opts (Quoted DoubleQuote lst) = do
-  contents <- inlineListToMarkdown opts lst
-  return $ if isEnabled Ext_smart opts
-              then "\"" <> contents <> "\""
-              else "“" <> contents <> "”"
-inlineToMarkdown opts (Code attr str) = do
-  let tickGroups = filter (\s -> '`' `elem` s) $ group str
-  let longest    = if null tickGroups
-                     then 0
-                     else maximum $ map length tickGroups
-  let marker     = replicate (longest + 1) '`'
-  let spacer     = if (longest == 0) then "" else " "
-  let attrs      = if isEnabled Ext_inline_code_attributes opts && attr /= nullAttr
-                      then attrsToMarkdown attr
-                      else empty
-  plain <- asks envPlain
-  if plain
-     then return $ text str
-     else return $ text (marker ++ spacer ++ str ++ spacer ++ marker) <> attrs
-inlineToMarkdown opts (Str str) = do
-  isPlain <- asks envPlain
-  let str' = (if isEnabled Ext_smart opts
-                 then unsmartify opts
-                 else id) $
-              if isPlain
-                 then str
-                 else escapeString opts str
-  return $ text str'
-inlineToMarkdown opts (Math InlineMath str) =
-  case writerHTMLMathMethod opts of
-       WebTeX url -> inlineToMarkdown opts
-                       (Image nullAttr [Str str] (url ++ urlEncode str, str))
-       _ | isEnabled Ext_tex_math_dollars opts ->
-             return $ "$" <> text str <> "$"
-         | isEnabled Ext_tex_math_single_backslash opts ->
-             return $ "\\(" <> text str <> "\\)"
-         | isEnabled Ext_tex_math_double_backslash opts ->
-             return $ "\\\\(" <> text str <> "\\\\)"
-         | otherwise -> do
-             plain <- asks envPlain
-             texMathToInlines InlineMath str >>=
-               inlineListToMarkdown opts .
-                 (if plain then makeMathPlainer else id)
-inlineToMarkdown opts (Math DisplayMath str) =
-  case writerHTMLMathMethod opts of
-      WebTeX url -> (\x -> blankline <> x <> blankline) `fmap`
-             inlineToMarkdown opts (Image nullAttr [Str str]
-                    (url ++ urlEncode str, str))
-      _ | isEnabled Ext_tex_math_dollars opts ->
-            return $ "$$" <> text str <> "$$"
-        | isEnabled Ext_tex_math_single_backslash opts ->
-            return $ "\\[" <> text str <> "\\]"
-        | isEnabled Ext_tex_math_double_backslash opts ->
-            return $ "\\\\[" <> text str <> "\\\\]"
-        | otherwise -> (\x -> cr <> x <> cr) `fmap`
-            (texMathToInlines DisplayMath str >>= inlineListToMarkdown opts)
-inlineToMarkdown opts il@(RawInline f str) = do
-  plain <- asks envPlain
-  if (plain && f == "plain") || (not plain &&
-     ( f `elem` ["markdown", "markdown_github", "markdown_phpextra",
-                 "markdown_mmd", "markdown_strict"] ||
-       (isEnabled Ext_raw_tex opts && (f == "latex" || f == "tex")) ||
-       (isEnabled Ext_raw_html opts && f `elem` ["html", "html4", "html5"])
-     ))
-    then return $ text str
-    else do
-      report $ InlineNotRendered il
-      return empty
-inlineToMarkdown opts (LineBreak) = do
-  plain <- asks envPlain
-  if plain || isEnabled Ext_hard_line_breaks opts
-     then return cr
-     else return $
-          if isEnabled Ext_escaped_line_breaks opts
-             then "\\" <> cr
-             else "  " <> cr
-inlineToMarkdown _ Space = do
-  escapeSpaces <- asks envEscapeSpaces
-  return $ if escapeSpaces then "\\ " else space
-inlineToMarkdown opts SoftBreak = do
-  escapeSpaces <- asks envEscapeSpaces
-  let space' = if escapeSpaces then "\\ " else space
-  return $ case writerWrapText opts of
-                WrapNone     -> space'
-                WrapAuto     -> space'
-                WrapPreserve -> cr
-inlineToMarkdown opts (Cite [] lst) = inlineListToMarkdown opts lst
-inlineToMarkdown opts (Cite (c:cs) lst)
-  | not (isEnabled Ext_citations opts) = inlineListToMarkdown opts lst
-  | otherwise =
-      if citationMode c == AuthorInText
-         then do
-           suffs <- inlineListToMarkdown opts $ citationSuffix c
-           rest <- mapM convertOne cs
-           let inbr = suffs <+> joincits rest
-               br   = if isEmpty inbr then empty else char '[' <> inbr <> char ']'
-           return $ text ("@" ++ citationId c) <+> br
-         else do
-           cits <- mapM convertOne (c:cs)
-           return $ text "[" <> joincits cits <> text "]"
-  where
-        joincits = hcat . intersperse (text "; ") . filter (not . isEmpty)
-        convertOne Citation { citationId      = k
-                            , citationPrefix  = pinlines
-                            , citationSuffix  = sinlines
-                            , citationMode    = m }
-                               = do
-           pdoc <- inlineListToMarkdown opts pinlines
-           sdoc <- inlineListToMarkdown opts sinlines
-           let k' = text (modekey m ++ "@" ++ k)
-               r = case sinlines of
-                        Str (y:_):_ | y `elem` (",;]@" :: String) -> k' <> sdoc
-                        _                                         -> k' <+> sdoc
-           return $ pdoc <+> r
-        modekey SuppressAuthor = "-"
-        modekey _              = ""
-inlineToMarkdown opts lnk@(Link attr txt (src, tit))
-  | isEnabled Ext_raw_html opts &&
-    not (isEnabled Ext_link_attributes opts) &&
-    attr /= nullAttr = -- use raw HTML
-    (text . T.unpack . T.strip) <$>
-      writeHtml5String def (Pandoc nullMeta [Plain [lnk]])
-  | otherwise = do
-  plain <- asks envPlain
-  linktext <- inlineListToMarkdown opts txt
-  let linktitle = if null tit
-                     then empty
-                     else text $ " \"" ++ tit ++ "\""
-  let srcSuffix = fromMaybe src (stripPrefix "mailto:" src)
-  let useAuto = isURI src &&
-                case txt of
-                      [Str s] | escapeURI s == srcSuffix -> True
-                      _       -> False
-  let useRefLinks = writerReferenceLinks opts && not useAuto
-  shortcutable <- asks envRefShortcutable
-  let useShortcutRefLinks = shortcutable &&
-                            isEnabled Ext_shortcut_reference_links opts
-  reftext <- if useRefLinks then getReference attr linktext (src, tit)
-                            else return empty
-  return $ if useAuto
-              then if plain
-                      then text srcSuffix
-                      else "<" <> text srcSuffix <> ">"
-              else if useRefLinks
-                      then let first  = "[" <> linktext <> "]"
-                               second = if getKey linktext == getKey reftext
-                                           then if useShortcutRefLinks
-                                                   then ""
-                                                   else "[]"
-                                           else "[" <> reftext <> "]"
-                           in  first <> second
-                      else if plain
-                              then linktext
-                              else "[" <> linktext <> "](" <>
-                                   text src <> linktitle <> ")" <>
-                                   linkAttributes opts attr
-inlineToMarkdown opts img@(Image attr alternate (source, tit))
-  | isEnabled Ext_raw_html opts &&
-    not (isEnabled Ext_link_attributes opts) &&
-    attr /= nullAttr = -- use raw HTML
-    (text . T.unpack . T.strip) <$>
-      writeHtml5String def (Pandoc nullMeta [Plain [img]])
-  | otherwise = do
-  plain <- asks envPlain
-  let txt = if null alternate || alternate == [Str source]
-                                 -- to prevent autolinks
-               then [Str ""]
-               else alternate
-  linkPart <- inlineToMarkdown opts (Link attr txt (source, tit))
-  return $ if plain
-              then "[" <> linkPart <> "]"
-              else "!" <> linkPart
-inlineToMarkdown opts (Note contents) = do
-  modify (\st -> st{ stNotes = contents : stNotes st })
-  st <- get
-  let ref = text $ writerIdentifierPrefix opts ++ show (stNoteNum st + (length $ stNotes st) - 1)
-  if isEnabled Ext_footnotes opts
-     then return $ "[^" <> ref <> "]"
-     else return $ "[" <> ref <> "]"
-
-makeMathPlainer :: [Inline] -> [Inline]
-makeMathPlainer = walk go
-  where
-  go (Emph xs) = Span nullAttr xs
-  go x         = x
-
-toSuperscript :: Char -> Maybe Char
-toSuperscript '1' = Just '\x00B9'
-toSuperscript '2' = Just '\x00B2'
-toSuperscript '3' = Just '\x00B3'
-toSuperscript '+' = Just '\x207A'
-toSuperscript '-' = Just '\x207B'
-toSuperscript '=' = Just '\x207C'
-toSuperscript '(' = Just '\x207D'
-toSuperscript ')' = Just '\x207E'
-toSuperscript c
-  | c >= '0' && c <= '9' =
-                 Just $ chr (0x2070 + (ord c - 48))
-  | isSpace c = Just c
-  | otherwise = Nothing
-
-toSubscript :: Char -> Maybe Char
-toSubscript '+' = Just '\x208A'
-toSubscript '-' = Just '\x208B'
-toSubscript '=' = Just '\x208C'
-toSubscript '(' = Just '\x208D'
-toSubscript ')' = Just '\x208E'
-toSubscript c
-  | c >= '0' && c <= '9' =
-                 Just $ chr (0x2080 + (ord c - 48))
-  | isSpace c = Just c
-  | otherwise = Nothing
-
-lineBreakToSpace :: Inline -> Inline
-lineBreakToSpace LineBreak = Space
-lineBreakToSpace SoftBreak = Space
-lineBreakToSpace x         = x
+{-# LANGUAGE BangPatterns        #-}
+{- |
+   Module      : Text.Pandoc.Writers.Markdown
+   Copyright   : Copyright (C) 2006-2024 John MacFarlane
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : John MacFarlane <jgm@berkeley.edu>
+   Stability   : alpha
+   Portability : portable
+
+Conversion of 'Pandoc' documents to markdown-formatted plain text.
+
+Markdown:  <https://daringfireball.net/projects/markdown/>
+-}
+module Text.Pandoc.Writers.Markdown (
+  writeMarkdown,
+  writeCommonMark,
+  writeMarkua,
+  writePlain) where
+import Control.Monad (foldM, zipWithM, MonadPlus(..), when, liftM)
+import Control.Monad.Reader ( asks, MonadReader(local) )
+import Control.Monad.State.Strict ( gets, modify )
+import Data.Default
+import Data.List (intersperse, sortOn, union, find)
+import Data.List.NonEmpty (nonEmpty, NonEmpty(..))
+import qualified Data.Map as M
+import Data.Maybe (fromMaybe, mapMaybe, isNothing)
+import qualified Data.Set as Set
+import Data.Text (Text)
+import Data.Char (isSpace)
+import qualified Data.Text as T
+import Text.HTML.TagSoup (Tag (..), isTagText, parseTags)
+import Text.Pandoc.Class.PandocMonad (PandocMonad, report)
+import Text.Pandoc.Definition
+import Text.Pandoc.Logging
+import Text.Pandoc.Options
+import Text.Pandoc.Parsing hiding (blankline, blanklines, char, space)
+import Text.DocLayout
+import Text.Pandoc.Shared
+import Text.Pandoc.Writers.Shared
+import Text.Pandoc.Templates (renderTemplate)
+import Text.DocTemplates (Val(..), Context(..), FromContext(..))
+import Text.Pandoc.Walk
+import Text.Pandoc.Writers.HTML (writeHtml5String)
+import Text.Pandoc.Writers.Markdown.Inline (inlineListToMarkdown,
+                                            linkAttributes,
+                                            attrsToMarkdown,
+                                            attrsToMarkua)
+import Text.Pandoc.Writers.Markdown.Table (pipeTable, pandocTable)
+import Text.Pandoc.Writers.Markdown.Types (MarkdownVariant(..),
+                                           WriterState(..),
+                                           WriterEnv(..),
+                                           Ref, Refs, MD, evalMD)
+
+-- | Convert Pandoc to Markdown.
+writeMarkdown :: PandocMonad m => WriterOptions -> Pandoc -> m Text
+writeMarkdown opts document =
+  evalMD (pandocToMarkdown opts{
+             writerWrapText = if isEnabled Ext_hard_line_breaks opts
+                              then WrapNone
+                              else writerWrapText opts }
+             document) def def
+
+-- | Convert Pandoc to plain text (like markdown, but without links,
+-- pictures, or inline formatting).
+writePlain :: PandocMonad m => WriterOptions -> Pandoc -> m Text
+writePlain opts document =
+  evalMD (pandocToMarkdown opts document) def{ envVariant = PlainText } def
+
+-- | Convert Pandoc to Commonmark.
+writeCommonMark :: PandocMonad m => WriterOptions -> Pandoc -> m Text
+writeCommonMark opts document =
+  evalMD (pandocToMarkdown opts' document) def{ envVariant = Commonmark } def
+ where
+  opts' = opts{ writerExtensions =
+                   -- These extensions can't be enabled or disabled
+                   -- for commonmark because they're part of the core;
+                   -- we set them here so that escapeText will behave
+                   -- properly.
+                   enableExtension Ext_all_symbols_escapable $
+                   enableExtension Ext_intraword_underscores $
+                     writerExtensions opts ,
+                writerWrapText =
+                  if isEnabled Ext_hard_line_breaks opts
+                     then WrapNone
+                     else writerWrapText opts }
+
+-- | Convert Pandoc to Markua.
+writeMarkua :: PandocMonad m => WriterOptions -> Pandoc -> m Text
+writeMarkua opts document =
+  evalMD (pandocToMarkdown opts' document) def{ envVariant = Markua } def
+ where
+  opts' = opts{ writerExtensions =
+                  enableExtension Ext_hard_line_breaks $
+                  enableExtension Ext_pipe_tables $
+                  -- required for fancy list enumerators
+                  enableExtension Ext_fancy_lists $
+                  enableExtension Ext_startnum $
+                  enableExtension Ext_strikeout $
+                  enableExtension Ext_subscript $
+                  enableExtension Ext_superscript $
+                  enableExtension Ext_definition_lists $
+                  enableExtension Ext_smart $
+                  enableExtension Ext_footnotes
+                    mempty ,
+                writerWrapText =
+                  if isEnabled Ext_hard_line_breaks opts
+                     then WrapNone
+                     else writerWrapText opts }
+
+
+pandocTitleBlock :: Doc Text -> [Doc Text] -> Doc Text -> Doc Text
+pandocTitleBlock tit auths dat =
+  hang 2 (text "% ") tit <> cr <>
+  hang 2 (text "% ") (vcat $ map nowrap auths) <> cr <>
+  hang 2 (text "% ") dat <> cr
+
+mmdTitleBlock :: Context Text -> Doc Text
+mmdTitleBlock (Context hashmap) =
+  vcat $ map go $ sortOn (T.toCaseFold . fst) $ M.toList hashmap
+  where go (k,v) =
+          case (text (T.unpack k), v) of
+               (k', ListVal xs)
+                 | null xs        -> empty
+                 | otherwise      -> k' <> ":" <> space <>
+                                      hcat (intersperse "; " $
+                                            mapMaybe fromVal xs)
+               (k', SimpleVal x)
+                      | isEmpty x -> empty
+                      | otherwise -> k' <> ":" <> space <>
+                                     nest 2 (removeBlankLines (chomp x))
+               _                  -> empty
+        removeBlankLines BlankLines{} = cr <> text "." <> cr
+        removeBlankLines (Concat x y) = removeBlankLines x <>
+                                        removeBlankLines y
+        removeBlankLines x            = x
+
+plainTitleBlock :: Doc Text -> [Doc Text] -> Doc Text -> Doc Text
+plainTitleBlock tit auths dat =
+  tit <> cr <>
+  hcat (intersperse (text "; ") auths) <> cr <>
+  dat <> cr
+
+yamlMetadataBlock :: Context Text -> Doc Text
+yamlMetadataBlock v = "---" $$ contextToYaml v $$ "---"
+
+contextToYaml :: Context Text -> Doc Text
+contextToYaml (Context o) =
+  vcat $ map keyvalToYaml $ sortOn (T.toCaseFold . fst) $ M.toList o
+ where
+  keyvalToYaml (k,v) =
+          case (text (T.unpack k), v) of
+               (k', ListVal vs)
+                 | null vs        -> empty
+                 | otherwise      -> (k' <> ":") $$ valToYaml v
+               (k', MapVal (Context m))
+                 | M.null m       -> k' <> ": {}"
+                 | otherwise      -> (k' <> ":") $$ nest 2 (valToYaml v)
+               (_, SimpleVal x)
+                     | isEmpty x  -> empty
+               (_, NullVal)       -> empty
+               (k', _)            -> k' <> ":" <+> hang 2 "" (valToYaml v)
+
+valToYaml :: Val Text -> Doc Text
+valToYaml (ListVal xs) =
+  vcat $ map (\v -> hang 2 "- " (valToYaml v)) xs
+valToYaml (MapVal c) = contextToYaml c
+valToYaml (BoolVal True) = "true"
+valToYaml (BoolVal False) = "false"
+valToYaml (SimpleVal x)
+  | isEmpty x = empty
+  | otherwise =
+      if hasNewlines x
+         then hang 0 ("|" <> cr) x
+         else case x of
+                Text _ t | isSpecialString t ->
+                         "\"" <> fmap escapeInDoubleQuotes x <> "\""
+                _ | isNothing (foldM needsDoubleQuotes True x) ->
+                         "\"" <> fmap escapeInDoubleQuotes x <> "\""
+                  | otherwise -> x
+    where
+      isSpecialString t = Set.member t specialStrings
+      specialStrings = Set.fromList
+       ["y", "Y", "yes", "Yes", "YES", "n", "N",
+        "no", "No", "NO", "true", "True", "TRUE",
+        "false", "False", "FALSE", "on", "On", "ON",
+        "off", "Off", "OFF", "null", "Null",
+        "NULL", "~", "*"]
+      needsDoubleQuotes isFirst t
+        = if T.any isBadAnywhere t ||
+             (isFirst && T.any isYamlPunct (T.take 1 t))
+              then Nothing
+              else Just False
+      isBadAnywhere '#' = True
+      isBadAnywhere ':' = True
+      isBadAnywhere _   = False
+      hasNewlines NewLine = True
+      hasNewlines BlankLines{} = True
+      hasNewlines CarriageReturn = True
+      hasNewlines (Concat w z) = hasNewlines w || hasNewlines z
+      hasNewlines _ = False
+      isYamlPunct = (`elem` ['-','?',':',',','[',']','{','}',
+                             '#','&','*','!','|','>','\'','"', '%','@','`'])
+      escapeInDoubleQuotes = T.replace "\"" "\\\"" . T.replace "\\" "\\\\"
+valToYaml _ = empty
+
+-- | Return markdown representation of document.
+pandocToMarkdown :: PandocMonad m => WriterOptions -> Pandoc -> MD m Text
+pandocToMarkdown opts (Pandoc meta blocks) = do
+  let colwidth = if writerWrapText opts == WrapAuto
+                    then Just $ writerColumns opts
+                    else Nothing
+  variant <- asks envVariant
+  metadata <- metaToContext'
+               (blockListToMarkdown opts)
+               (inlineListToMarkdown opts)
+               meta
+  let title' = fromMaybe empty $ getField "title" metadata
+  let authors' = fromMaybe [] $ getField "author" metadata
+  let date' = fromMaybe empty $ getField "date" metadata
+  let titleblock = case writerTemplate opts of
+                        Just _ | variant == PlainText ->
+                                 plainTitleBlock title' authors' date'
+                               | isEnabled Ext_yaml_metadata_block opts ->
+                                   yamlMetadataBlock metadata
+                               | isEnabled Ext_pandoc_title_block opts ->
+                                   pandocTitleBlock title' authors' date'
+                               | isEnabled Ext_mmd_title_block opts ->
+                                   mmdTitleBlock metadata
+                               | otherwise -> empty
+                        Nothing -> empty
+  let modifyTOC =
+        if isEnabled Ext_link_attributes opts || isEnabled Ext_attributes opts
+        then id
+        else walk $ \inln -> case inln of
+          Link _attr contents tgt -> Link nullAttr contents tgt
+          _                       -> inln
+  toc <- if writerTableOfContents opts
+         then blockToMarkdown opts . modifyTOC $ toTableOfContents opts blocks
+         else return mempty
+  -- Strip off final 'references' header if markdown citations enabled
+  let blocks' = if isEnabled Ext_citations opts
+                   then case reverse blocks of
+                             (Div ("refs",_,_) _):xs -> reverse xs
+                             _                       -> blocks
+                   else blocks
+  body <- blockListToMarkdown opts blocks'
+  notesAndRefs' <- notesAndRefs opts
+  let main = body <> notesAndRefs'
+  let context  = -- for backwards compatibility we populate toc
+                 -- with the contents of the toc, rather than a
+                 -- boolean:
+                 defField "toc" toc
+               $ defField "table-of-contents" toc
+               $ defField "body" main
+               $ (if isNullMeta meta
+                     then id
+                     else defField "titleblock" titleblock)
+               $ addVariablesToContext opts metadata
+  return $ render colwidth $
+    case writerTemplate opts of
+       Nothing  -> main
+       Just tpl -> renderTemplate tpl context
+
+-- | Return markdown representation of reference key table.
+refsToMarkdown :: PandocMonad m => WriterOptions -> Refs -> MD m (Doc Text)
+refsToMarkdown opts refs = vcat <$> mapM (keyToMarkdown opts) refs
+
+-- | Return markdown representation of a reference key.
+keyToMarkdown :: PandocMonad m
+              => WriterOptions
+              -> Ref
+              -> MD m (Doc Text)
+keyToMarkdown opts (label', (src, tit), attr) = do
+  let tit' = if T.null tit
+                then empty
+                else space <> "\"" <> literal tit <> "\""
+  return $ nest 2 $ hang 2
+            ("[" <> literal label' <> "]:" <> space) (literal src <> tit')
+            <+> linkAttributes opts attr
+
+-- | Return markdown representation of notes.
+notesToMarkdown :: PandocMonad m => WriterOptions -> [[Block]] -> MD m (Doc Text)
+notesToMarkdown opts notes = do
+  n <- gets stNoteNum
+  notes' <- zipWithM (noteToMarkdown opts) [n..] notes
+  modify $ \st -> st { stNoteNum = stNoteNum st + length notes }
+  return $ vsep notes'
+
+-- | Return markdown representation of a note.
+noteToMarkdown :: PandocMonad m => WriterOptions -> Int -> [Block] -> MD m (Doc Text)
+noteToMarkdown opts num blocks = do
+  contents  <- blockListToMarkdown opts blocks
+  let num' = literal $ writerIdentifierPrefix opts <> tshow num
+  let marker = if isEnabled Ext_footnotes opts
+                  then literal "[^" <> num' <> literal "]:"
+                  else literal "[" <> num' <> literal "]"
+  let markerSize = 4 + offset num'
+  let hspacer = case writerTabStop opts - markerSize of
+                      n | n > 0  -> literal $ T.replicate n " "
+                      _ -> literal " "
+  let spacer = case blocks of
+                    Para{}:_ -> hspacer
+                    Plain{}:_ -> hspacer
+                    _ -> cr
+  return $ if isEnabled Ext_footnotes opts
+              then hang (writerTabStop opts) (marker <> spacer) contents
+              else marker <> spacer <> contents
+
+-- | (Code) blocks with a single class and no attributes can just use it
+-- standalone, no need to bother with curly braces.
+classOrAttrsToMarkdown :: WriterOptions -> Attr -> Doc Text
+classOrAttrsToMarkdown _ ("",[cls],[]) = literal cls
+classOrAttrsToMarkdown opts attrs = attrsToMarkdown opts attrs
+
+-- | Ordered list start parser for use in Para below.
+olMarker :: Parsec Text ParserState ()
+olMarker = do (start, style', delim) <- anyOrderedListMarker
+              if delim == Period &&
+                          (style' == UpperAlpha || (style' == UpperRoman &&
+                          start `elem` [1, 5, 10, 50, 100, 500, 1000]))
+                          then mzero -- it needs 2 spaces anyway
+                          else eof
+
+-- | True if string begins with an ordered list marker
+beginsWithOrderedListMarker :: Text -> Bool
+beginsWithOrderedListMarker str =
+  case runParser olMarker defaultParserState "para start" (T.take 10 str) of
+         Left  _ -> False
+         Right _ -> True
+
+notesAndRefs :: PandocMonad m => WriterOptions -> MD m (Doc Text)
+notesAndRefs opts = do
+  notes' <- gets stNotes >>= notesToMarkdown opts . reverse
+  modify $ \s -> s { stNotes = [] }
+  refs' <- gets stRefs >>= refsToMarkdown opts . reverse
+  modify $ \s -> s { stPrevRefs = stPrevRefs s ++ stRefs s
+                   , stRefs = []}
+
+  let endSpacing =
+        if | writerReferenceLocation opts == EndOfDocument -> empty
+           | isEmpty notes' && isEmpty refs' -> empty
+           | otherwise -> blankline
+
+  return $
+    (if isEmpty notes' then empty else blankline <> notes') <>
+    (if isEmpty refs' then empty else blankline <> refs') <>
+    endSpacing
+
+-- | Convert Pandoc block element to markdown.
+blockToMarkdown :: PandocMonad m
+                => WriterOptions -- ^ Options
+                -> Block         -- ^ Block element
+                -> MD m (Doc Text)
+blockToMarkdown opts blk =
+  local (\env -> env {envBlockLevel = envBlockLevel env + 1}) $
+  do doc <- blockToMarkdown' opts blk
+     blkLevel <- asks envBlockLevel
+     if writerReferenceLocation opts == EndOfBlock && blkLevel == 1
+       then notesAndRefs opts >>= (\d -> return $ doc <> d)
+       else return doc
+
+blockToMarkdown' :: PandocMonad m
+                 => WriterOptions -- ^ Options
+                 -> Block         -- ^ Block element
+                 -> MD m (Doc Text)
+blockToMarkdown' opts (Div attrs@(_,classes,_) bs)
+  | ("sourceCode":_) <- classes
+  , [CodeBlock (_,"sourceCode":_,_) _] <- bs
+     -- skip pandoc-generated Div wrappers around code blocks
+   = blockListToMarkdown opts bs
+  | isEnabled Ext_alerts opts
+  , (cls:_) <- classes
+  , cls `elem` ["note", "tip", "warning", "caution", "important"]
+  , (Div ("", ["title"], []) _ : bs') <- bs = do
+    contents <- blockListToMarkdown opts bs'
+    let alertLabel = literal $ "[!" <> T.toUpper cls <> "]"
+    pure $ text "> " <> alertLabel $$ prefixed "> " contents $$ blankline
+  | otherwise = do
+    contents <- blockListToMarkdown opts bs
+    variant <- asks envVariant
+    return $
+       case () of
+           _ | variant == Markua ->
+                 case () of
+                      () | "blurb" `elem` classes'
+                           -> prefixed "B> " contents <> blankline
+                         | "aside" `elem` classes'
+                           -> prefixed "A> " contents <> blankline
+                         -- necessary to enable option to create a bibliography
+                         | (take 3 (T.unpack id')) == "ref"
+                           -> contents <> blankline
+                         | otherwise -> contents <> blankline
+             | isEnabled Ext_fenced_divs opts ->
+                  let attrsToMd = if variant == Commonmark
+                                  then attrsToMarkdown opts
+                                  else classOrAttrsToMarkdown opts
+                      divNesting = computeDivNestingLevel bs
+                      numcolons = 3 + divNesting
+                      colons = literal $ T.replicate numcolons ":"
+                  in nowrap (colons <+> attrsToMd attrs) $$
+                     chomp contents $$
+                     colons <> blankline
+             | isEnabled Ext_native_divs opts ||
+               (isEnabled Ext_raw_html opts &&
+                (variant == Commonmark ||
+                 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
+  -- escape if para starts with ordered list marker
+  variant <- asks envVariant
+  let escapeMarker = T.concatMap $ \x -> if T.any (== x) ".()"
+                                         then T.pack ['\\', x]
+                                         else T.singleton x
+  let startsWithSpace (Space:_)     = True
+      startsWithSpace (SoftBreak:_) = True
+      startsWithSpace _             = False
+  let inlines' =
+        if variant == PlainText
+           then inlines
+           else case inlines of
+                  (Str t:ys)
+                    | null ys || startsWithSpace ys
+                    , beginsWithOrderedListMarker t
+                    -> RawInline (Format "markdown") (escapeMarker t):ys
+                  (Str t:_)
+                    | t == "+" || t == "-" ||
+                      (t == "%" && isEnabled Ext_pandoc_title_block opts &&
+                                   isEnabled Ext_all_symbols_escapable opts)
+                    -> RawInline (Format "markdown") "\\" : inlines
+                  _ -> inlines
+  contents <- inlineListToMarkdown opts inlines'
+  return $ contents <> cr
+blockToMarkdown' opts (Para inlines) =
+  (<> blankline) `fmap` blockToMarkdown opts (Plain inlines)
+blockToMarkdown' opts (LineBlock lns) = do
+  variant <- asks envVariant
+  case variant of
+    PlainText -> do
+      let emptyToBlank l = if isEmpty l then blankline else l
+      mdLines <- mapM (liftM emptyToBlank . inlineListToMarkdown opts) lns
+      return $ vcat mdLines <> blankline
+    _ ->
+      if isEnabled Ext_line_blocks opts
+      then do
+        mdLines <- mapM (inlineListToMarkdown opts) lns
+        return $ vcat (map (hang 2 (literal "| ")) mdLines) <> blankline
+      else blockToMarkdown opts $ linesToPara lns
+blockToMarkdown' opts b@(RawBlock f str) = do
+  variant <- asks envVariant
+  let Format fmt = f
+  let rawAttribBlock = return $
+         (literal "```{=" <> literal fmt <> "}") $$
+         literal str $$
+         (literal "```" <> literal "\n")
+  let renderEmpty = mempty <$ report (BlockNotRendered b)
+  case variant of
+    PlainText
+      | f == "plain" -> return $ nest 0 (literal str) <> literal "\n"
+    Commonmark
+      | f `elem` ["gfm", "commonmark", "commonmark_x", "markdown"]
+         -> return $ nest 0 (literal str) $$ blankline
+      | f `elem` ["html", "html5", "html4"]
+         -> return $ literal (removeBlankLinesInHTML str) $$ blankline
+    Markdown
+      | f `elem` ["markdown", "markdown_github", "markdown_phpextra",
+                  "markdown_mmd", "markdown_strict"]
+        -- the 'nest 0' ensures that leading and trailing newlines
+        -- don't get collapsed. See #10477 for context;
+         -> return $ nest 0 (literal str) <> literal "\n"
+    Markua -> renderEmpty
+    _ | f `elem` ["html", "html5", "html4"]
+      , isEnabled Ext_markdown_attribute opts
+         -> return $ literal (addMarkdownAttribute str) <> literal "\n"
+      | f `elem` ["html", "html5", "html4"]
+      , isEnabled Ext_raw_html opts
+         -> return $ literal str <> literal "\n"
+      | f `elem` ["latex", "tex"]
+      , isEnabled Ext_raw_tex opts
+         -> return $ literal str <> literal "\n"
+      | isEnabled Ext_raw_attribute opts -> rawAttribBlock
+    _ -> renderEmpty
+blockToMarkdown' opts HorizontalRule = do
+  variant <- asks envVariant
+  let indicator = case variant of
+                        Markua -> "* * *"
+                        _ -> T.replicate (writerColumns opts) "-"
+  return $ blankline <> literal indicator <> blankline
+blockToMarkdown' opts (Header level attr inlines) = do
+  -- first, if we're putting references at the end of a section, we
+  -- put them here.
+  blkLevel <- asks envBlockLevel
+  refs <- if writerReferenceLocation opts == EndOfSection && blkLevel == 1
+          then notesAndRefs opts
+          else return empty
+  variant <- asks envVariant
+  -- we calculate the id that would be used by auto_identifiers
+  -- or gfm_auto_identifiers
+  -- so we know whether to print an explicit identifier
+  ids <- gets stIds
+  let autoId = uniqueIdent (writerExtensions opts) inlines ids
+  modify $ \st -> st{ stIds = Set.insert autoId ids }
+  let attr' = case attr of
+                   ("",[],[]) -> empty
+                   (id',[],[]) | (isEnabled Ext_auto_identifiers opts
+                                  || isEnabled Ext_gfm_auto_identifiers opts)
+                                 && id' == autoId -> empty
+                   (id',_,_)   | isEnabled Ext_mmd_header_identifiers opts ->
+                                    space <> brackets (literal id')
+                   _ | variant == Markua -> attrsToMarkua opts attr
+                     | isEnabled Ext_header_attributes opts ||
+                       isEnabled Ext_attributes opts ->
+                                    space <> attrsToMarkdown opts attr
+                     | otherwise -> empty
+  let setext = level <= 2 && writerSetextHeaders opts ||
+                              (variant == Commonmark &&
+                               hasLineBreaks inlines) -- #11341
+  contents <- inlineListToMarkdown opts $
+                 (if variant == Commonmark && setext
+                     then id
+                     else -- ensure no newlines; see #3736
+                          walk lineBreakToSpace) $
+                   if level == 1 && variant == PlainText &&
+                      isEnabled Ext_gutenberg opts
+                      then capitalize inlines
+                      else inlines
+
+  when (not setext && isEnabled Ext_literate_haskell opts) $
+    report $ ATXHeadingInLHS level (render Nothing contents)
+
+  let hdr = nowrap $ case level of
+            1 | variant == PlainText ->
+                if isEnabled Ext_gutenberg opts
+                   then blanklines 3 <> contents <> blanklines 2
+                   else contents <> blankline
+              | setext ->
+                  contents <> attr' <> cr <> literal (T.replicate (offset contents) "=") <>
+                  blankline
+            2 | variant == PlainText ->
+                if isEnabled Ext_gutenberg opts
+                   then blanklines 2 <> contents <> blankline
+                   else contents <> blankline
+              | setext ->
+                  contents <> attr' <> cr <> literal (T.replicate (offset contents) "-") <>
+                  blankline
+            -- ghc interprets '#' characters in column 1 as linenum specifiers.
+            _ | variant == PlainText || isEnabled Ext_literate_haskell opts ->
+                contents <> blankline
+            _ | variant == Markua -> attr' <> cr <> literal (T.replicate level "#")
+                                        <> space <> contents <> blankline
+            _ -> literal (T.replicate level "#") <> space <> contents <> attr' <> blankline
+
+  return $ refs <> hdr
+blockToMarkdown' opts (CodeBlock (_,classes,_) str)
+  | "haskell" `elem` classes && "literate" `elem` classes &&
+    isEnabled Ext_literate_haskell opts =
+  return $ prefixed "> " (literal str) <> blankline
+blockToMarkdown' opts (CodeBlock attribs str) = do
+  variant <- asks envVariant
+  return $
+   case attribs == nullAttr of
+     False | variant == Commonmark ||
+             isEnabled Ext_backtick_code_blocks opts ->
+          backticks <> attrs <> cr <> literal str <> cr <> backticks <> blankline
+           | isEnabled Ext_fenced_code_blocks opts ->
+          tildes <> attrs <> cr <> literal str <> cr <> tildes <> blankline
+     _ | variant == Markua -> blankline <> attrsToMarkua opts attribs <> cr <> backticks <> cr <>
+                                literal str <> cr <> backticks <> cr <> blankline
+       | otherwise -> -- don't use nest: see #11542
+           let addIndent "" = "\n"
+               addIndent x  = (T.replicate (writerTabStop opts) " ") <> x <> "\n"
+          in  literal (mconcat $ map addIndent (T.lines str)) $$ blankline
+   where
+     endlineLen c = maybe 3 ((+1) . maximum) $ nonEmpty
+                        [T.length ln
+                         | ln <- map trim (T.lines str)
+                         , T.pack [c,c,c] `T.isPrefixOf` ln
+                         , T.all (== c) ln]
+     endline c = literal $ T.replicate (endlineLen c) $ T.singleton c
+     backticks = endline '`'
+     tildes = endline '~'
+     attrs  = if isEnabled Ext_fenced_code_attributes opts ||
+                 isEnabled Ext_attributes opts
+                 then nowrap $ " " <> classOrAttrsToMarkdown opts attribs
+                 else
+                   let (_,cls,_) = attribs
+                    in case getLangFromClasses cls of
+                              Just l -> " " <> literal l
+                              Nothing -> empty
+blockToMarkdown' opts (BlockQuote blocks) = do
+  variant <- asks envVariant
+  -- if we're writing literate haskell, put a space before the bird tracks
+  -- so they won't be interpreted as lhs...
+  let leader
+        | isEnabled Ext_literate_haskell opts = " > "
+        | variant == PlainText = "  "
+        | otherwise            = "> "
+  contents <- blockListToMarkdown opts blocks
+  return $ text leader <> prefixed leader contents <> blankline
+blockToMarkdown' opts t@(Table attr blkCapt specs thead tbody tfoot) = do
+  let (caption, aligns, widths, headers, rows) = toLegacyTable blkCapt specs thead tbody tfoot
+  let isColRowSpans (Cell _ _ rs cs _) = rs > 1 || cs > 1
+  let rowHasColRowSpans (Row _ cs) = any isColRowSpans cs
+  let hasFooter = case tfoot of
+                    TableFoot _ [] -> False
+                    _ -> True
+  let tbodyHasColRowSpans (TableBody _ _ rhs rs) =
+        any rowHasColRowSpans rhs || any rowHasColRowSpans rs
+  let theadHasColRowSpans (TableHead _ rs) = any rowHasColRowSpans rs
+  let tfootHasColRowSpans (TableFoot _ rs) = any rowHasColRowSpans rs
+  let hasColRowSpans = theadHasColRowSpans thead ||
+                       any tbodyHasColRowSpans tbody ||
+                       tfootHasColRowSpans tfoot
+  let numcols = maximum (length aligns :| length widths :
+                           map length (headers:rows))
+  caption' <- inlineListToMarkdown opts caption
+  let caption'' = if attr == nullAttr
+                     then caption'
+                     else caption' <+> attrsToMarkdown opts attr
+  let caption'''
+        | null caption = blankline
+        | isEnabled Ext_table_captions opts
+        = blankline $$ (": " <> caption'') $$ blankline
+        | otherwise = blankline $$ caption'' $$ blankline
+  let hasSimpleCells = onlySimpleTableCells $ headers : rows
+  let isSimple = hasSimpleCells && not hasFooter &&
+                 all (==0) widths && not hasColRowSpans
+  let isPlainBlock (Plain _) = True
+      isPlainBlock _         = False
+  let hasBlocks = not (all (all (all isPlainBlock)) $ headers:rows)
+  let padRow r = case numcols - length r of
+                       x | x > 0 -> r ++ replicate x empty
+                         | otherwise -> r
+  let aligns' = case numcols - length aligns of
+                     x | x > 0 -> aligns ++ replicate x AlignDefault
+                       | otherwise -> aligns
+  let widths' = case numcols - length widths of
+                     x | x > 0 -> widths ++ replicate x 0.0
+                       | otherwise -> widths
+  let mkTable f = do
+       rawHeaders <- padRow <$> mapM (blockListToMarkdown opts) headers
+       rawRows <- mapM (fmap padRow . mapM (blockListToMarkdown opts)) rows
+       f (all null headers) aligns' widths' rawHeaders rawRows
+  case True of
+     _ | isSimple &&
+         isEnabled Ext_simple_tables opts -> do
+           tbl <- mkTable (pandocTable opts False)
+           return $ nest 2 (tbl $$ caption''') $$ blankline
+       | isSimple &&
+         isEnabled Ext_pipe_tables opts -> do
+           tbl <- mkTable (pipeTable opts)
+           return $ (tbl $$ caption''') $$ blankline
+       | not (hasBlocks || hasColRowSpans || hasFooter) &&
+         isEnabled Ext_multiline_tables opts -> do
+           tbl <- mkTable (pandocTable opts True)
+           return $ nest 2 (tbl $$ caption''') $$ blankline
+       | isEnabled Ext_grid_tables opts &&
+          (hasColRowSpans || writerColumns opts >= 8 * numcols
+                          || hasFooter) -> do
+           tbl <- gridTable opts blockListToMarkdown
+                     specs thead tbody tfoot
+           return $ (tbl $$ caption''') $$ blankline
+       | hasSimpleCells,
+         not hasColRowSpans,
+         isEnabled Ext_pipe_tables opts -> do
+           tbl <- mkTable (pipeTable opts)
+           return $ (tbl $$ caption''') $$ blankline
+       | isEnabled Ext_raw_html opts -> do -- HTML fallback
+           tbl <- literal . removeBlankLinesInHTML <$>
+                     writeHtml5String opts{ writerTemplate = Nothing }
+                     (Pandoc nullMeta [t])
+           return $ tbl $$ blankline  -- caption is in the HTML table
+       | hasSimpleCells,
+         hasColRowSpans,
+         isEnabled Ext_pipe_tables opts -> do
+           -- In this case an approximate pipe table will be rendered,
+           -- without col/row spans. This is better than nothing, since
+           -- we have no other way to render the table correctly (#11128).
+           tbl <- mkTable (pipeTable opts)
+           return $ (tbl $$ caption''') $$ blankline
+       | otherwise
+         -> do
+           report (BlockNotRendered t)
+           return $ (literal "[TABLE]" $$ caption''') $$ blankline
+blockToMarkdown' opts (BulletList items) = do
+  contents <- inList $ mapM (bulletListItemToMarkdown opts) items
+  return $ (if isTightList items then vcat else vsep)
+                  contents <> blankline
+blockToMarkdown' opts (OrderedList (start,sty,delim) items) = do
+  variant <- asks envVariant
+  let start' = if variant == Commonmark || isEnabled Ext_startnum opts
+                  then start
+                  else 1
+  let sty'   = if isEnabled Ext_fancy_lists opts then sty else DefaultStyle
+  let delim' | isEnabled Ext_fancy_lists opts =
+               case variant of
+                   -- Markua supports 'fancy' enumerators, but no TwoParens
+                   Markua -> if delim == TwoParens then OneParen else delim
+                   _ -> delim
+             | variant == Commonmark && --commonmark only supports one paren
+                   (delim == OneParen || delim == TwoParens) = OneParen
+             | otherwise = DefaultDelim
+  let attribs = (start', sty', delim')
+  let markers  = orderedListMarkers attribs
+  let markers' = case variant of
+                        Markua -> markers
+                        _ -> map (\m -> if T.length m < 3
+                                   then m <> T.replicate (3 - T.length m) " "
+                                   else m) markers
+  contents <- inList $
+              zipWithM (orderedListItemToMarkdown opts) markers' items
+  return $ (if isTightList items then vcat else vsep) contents <> blankline
+blockToMarkdown' opts (DefinitionList items) = do
+  contents <- inList $ mapM (definitionListItemToMarkdown opts) items
+  return $ mconcat contents <> blankline
+blockToMarkdown' opts (Figure figattr capt body) = do
+  let combinedAttr imgattr = case imgattr of
+        ("", cls, kvs)
+          | (figid, [], []) <- figattr
+            -> Just (figid, cls, [(k,v) | (k,v) <- kvs
+                                        , k /= "alt" ||
+                                          v /= "" && v /= trim (stringify capt)])
+        _ -> Nothing
+  case body of
+    [Plain [Image imgAttr alt (src, ttl)]]
+      | isEnabled Ext_implicit_figures opts
+      , Just imgAttr' <- combinedAttr imgAttr
+      , isEnabled Ext_link_attributes opts || imgAttr' == nullAttr
+        -> do
+          -- use implicit figures if possible
+          let tgt' = (src, fromMaybe ttl $ T.stripPrefix "fig:" ttl)
+          let descr = case capt of
+                        Caption _ bs -> blocksToInlines bs
+          -- add alt attribute if image description different from caption,
+          -- so this won't be lost:
+          let imgAttr'' = case imgAttr' of
+                            (i,c,kv)
+                              | not (null alt)
+                              , Nothing <- lookup "alt" kv
+                              , stringify descr /= stringify alt ->
+                                 (i, c, ("alt", stringify alt) : kv)
+                            _ -> imgAttr'
+          contents <- inlineListToMarkdown opts [Image imgAttr'' descr tgt']
+          return $ contents <> blankline
+    _ ->
+      -- fallback to raw html if possible or div otherwise
+      if isEnabled Ext_raw_html opts
+      then figureToMarkdown opts figattr capt body
+      else if (isEnabled Ext_fenced_divs opts || isEnabled Ext_native_divs opts) ||
+                  not (isEnabled Ext_implicit_figures opts)
+              then blockToMarkdown' opts $ figureDiv figattr capt body
+              else blockListToMarkdown opts body
+
+inList :: Monad m => MD m a -> MD m a
+inList p = local (\env -> env {envInList = True}) p
+
+addMarkdownAttribute :: Text -> Text
+addMarkdownAttribute s =
+  case span isTagText $ reverse $ parseTags s of
+       (xs, TagOpen t attrs:rest) ->
+            renderTags' $ reverse rest ++ (TagOpen t attrs' : reverse xs)
+              where attrs' = ("markdown","1"):[(x,y) | (x,y) <- attrs,
+                                 x /= "markdown"]
+       _ -> s
+
+-- | Converts a figure to Markdown by wrapping it in a div named `figure`.
+figureToMarkdown :: PandocMonad m
+                 => WriterOptions
+                 -> Attr
+                 -> Caption
+                 -> [Block]
+                 -> MD m (Doc Text)
+figureToMarkdown opts attr@(ident, classes, kvs) capt body
+  | isEnabled Ext_raw_html opts =
+      (<> blankline) . literal . T.strip <$>
+      writeHtml5String
+        opts{ writerTemplate = Nothing }
+        (Pandoc nullMeta [Figure attr capt body])
+  | otherwise = do
+      let attr' = (ident, ["figure"] `union` classes, kvs)
+      let Caption _mbshort caption = capt
+      let captionBs = [Div ("",["caption"],[]) caption | not (null caption)]
+      blockToMarkdown' opts (Div attr' (body <> captionBs))
+
+itemEndsWithTightList :: [Block] -> Bool
+itemEndsWithTightList bs =
+  case bs of
+        [Plain _, BulletList xs]    -> isTightList xs
+        [Plain _, OrderedList _ xs] -> isTightList xs
+        _                           -> False
+
+-- | Convert bullet list item (list of blocks) to markdown.
+bulletListItemToMarkdown :: PandocMonad m => WriterOptions -> [Block] -> MD m (Doc Text)
+bulletListItemToMarkdown opts bs = do
+  variant <- asks envVariant
+  let exts = writerExtensions opts
+  contents <- blockListToMarkdown opts $ taskListItemToAscii exts bs
+  let start = case variant of
+              Markua -> "* "
+              Commonmark -> "- "
+              Markdown
+                | isEnabled Ext_four_space_rule opts
+                  -> "- " <> T.replicate (writerTabStop opts - 2) " "
+              PlainText
+                | isEnabled Ext_four_space_rule opts
+                  -> "- " <> T.replicate (writerTabStop opts - 2) " "
+              _ -> "- "
+  -- remove trailing blank line if item ends with a tight list
+  let contents' = if itemEndsWithTightList bs
+                     then chomp contents <> cr
+                     else contents
+  return $ hang (T.length start) (literal start) contents'
+
+-- | Convert ordered list item (a list of blocks) to markdown.
+orderedListItemToMarkdown :: PandocMonad m
+                          => WriterOptions -- ^ options
+                          -> Text          -- ^ list item marker
+                          -> [Block]       -- ^ list item (list of blocks)
+                          -> MD m (Doc Text)
+orderedListItemToMarkdown opts marker bs = do
+  let exts = writerExtensions opts
+  contents <- blockListToMarkdown opts $ taskListItemToAscii exts bs
+  variant <- asks envVariant
+  let sps = case writerTabStop opts - T.length marker of
+                   n | n > 0 -> literal $ T.replicate n " "
+                   _ -> literal " "
+  let ind = if isEnabled Ext_four_space_rule opts
+               then writerTabStop opts
+               else max (writerTabStop opts) (T.length marker + 1)
+  let start = case variant of
+              Markua -> literal marker <> " "
+              _      -> literal marker <> sps
+  -- remove trailing blank line if item ends with a tight list
+  let contents' = if itemEndsWithTightList bs
+                     then chomp contents <> cr
+                     else contents
+  return $ hang ind start contents'
+
+-- | Convert definition list item (label, list of blocks) to markdown.
+definitionListItemToMarkdown :: PandocMonad m
+                             => WriterOptions
+                             -> ([Inline],[[Block]])
+                             -> MD m (Doc Text)
+definitionListItemToMarkdown opts (label, defs) = do
+  labelText <- blockToMarkdown opts (Plain label)
+  defs' <- mapM (mapM (blockToMarkdown opts)) defs
+  if isEnabled Ext_definition_lists opts
+     then do
+       let tabStop = writerTabStop opts
+       variant <- asks envVariant
+       let leader  = case variant of
+                        PlainText -> " "
+                        _ -> ":"
+       let leadingChars = case tabStop of
+                            -- Always use two leading characters for Markua
+                            n | variant == Markua -> 2
+                              | isEnabled Ext_four_space_rule opts
+                              , n >= 2 -> n
+                              | otherwise -> 2
+       let sps = literal $ T.replicate (leadingChars - 1) " "
+       let isTight = case defs of
+                        ((Plain _ : _): _) -> True
+                        _                  -> False
+       let contents = (if isTight then vcat else vsep) $ map
+                       (\d -> hang leadingChars (leader <> sps) $ vcat d)
+                       defs'
+       return $ blankline <> nowrap labelText $$
+                (if isTight then empty else blankline) <> contents <> blankline
+     else
+       return $ nowrap (chomp labelText <> literal "  " <> cr) <>
+                vsep (map vsep defs') <> blankline
+
+-- | Convert list of Pandoc block elements to markdown.
+blockListToMarkdown :: PandocMonad m
+                    => WriterOptions -- ^ Options
+                    -> [Block]       -- ^ List of block elements
+                    -> MD m (Doc Text)
+blockListToMarkdown opts blocks = do
+  inlist <- asks envInList
+  variant <- asks envVariant
+  -- a) insert comment between list and indented code block, or the
+  -- code block will be treated as a list continuation paragraph
+  -- b) change Plain to Para unless it's followed by a RawBlock
+  -- or has a list as its parent (#3487)
+  let fixBlocks (b : CodeBlock attr x : rest)
+       | (not (variant == Commonmark ||
+               isEnabled Ext_backtick_code_blocks opts ||
+                 isEnabled Ext_fenced_code_blocks opts) ||
+              attr == nullAttr)
+            && isListBlock b
+              = b : commentSep : CodeBlock attr x : fixBlocks rest
+      fixBlocks (b1@(BulletList _) : b2@(BulletList _) : bs) =
+           b1 : commentSep : fixBlocks (b2:bs)
+      fixBlocks (b1@(OrderedList _ _) : b2@(OrderedList _ _) : bs) =
+           b1 : commentSep : fixBlocks (b2:bs)
+      fixBlocks (b1@(DefinitionList _) : b2@(DefinitionList _) : bs) =
+           b1 : commentSep : fixBlocks (b2:bs)
+      fixBlocks (Plain ils : bs@(RawBlock{}:_)) =
+           Plain ils : fixBlocks bs
+      fixBlocks (Plain ils : bs@(Div{}:_))
+          | isEnabled Ext_fenced_divs opts =
+           Para ils : fixBlocks bs
+      fixBlocks (Plain ils : bs) | inlist =
+           Plain ils : fixBlocks bs
+      fixBlocks (Plain ils : bs) =
+           Para ils : fixBlocks bs
+      fixBlocks (r@(RawBlock f raw) : b : bs)
+        | not (T.null raw)
+        , T.last raw /= '\n' =
+        case b of
+             Plain{}    -> r : fixBlocks (b:bs)
+             RawBlock{} -> r : fixBlocks (b:bs)
+             _          -> RawBlock f (raw <> "\n") : fixBlocks (b:bs) -- #4629
+      fixBlocks (x : xs)             = x : fixBlocks xs
+      fixBlocks []                   = []
+      isListBlock (BulletList _)     = True
+      isListBlock (OrderedList _ _)  = True
+      isListBlock (DefinitionList _) = True
+      isListBlock _                  = False
+      commentSep
+        | variant == PlainText        = Plain []
+        | variant == Markua           = Plain []
+        | isEnabled Ext_raw_html opts = RawBlock "html" "<!-- -->\n"
+        | otherwise                   = RawBlock "markdown" "&nbsp;\n"
+  mconcat <$> mapM (blockToMarkdown opts) (fixBlocks blocks)
+
+lineBreakToSpace :: Inline -> Inline
+lineBreakToSpace LineBreak = Space
+lineBreakToSpace SoftBreak = Space
+lineBreakToSpace x         = x
+
+removeBlankLinesInHTML :: Text -> Text
+removeBlankLinesInHTML = T.pack . go False . T.unpack
+  where go _ [] = []
+        go True ('\n':cs) = "&#10;" <> go False cs
+        go False ('\n':cs) = '\n' : go True cs
+        go !afternewline (!c:cs)
+          | isSpace c = c : go afternewline cs
+          | otherwise = c : go False cs
+
+computeDivNestingLevel :: [Block] -> Int
+computeDivNestingLevel = foldr go 0
+ where
+   go (Div _ bls') n = max (n + 1) (foldr go (n + 1) bls')
+   go _ n = n
+
+-- Identify the class in a list of classes that corresponds to
+-- the language syntax.  language-X turns to X.
+getLangFromClasses :: [Text] -> Maybe Text
+getLangFromClasses cs =
+  case find ("language-" `T.isPrefixOf`) cs of
+    Just x -> Just (T.drop 9 x)
+    Nothing ->
+      case filter (/= "sourceCode") cs of
+        (x:_) -> Just x
+        [] -> Nothing
diff --git a/src/Text/Pandoc/Writers/Markdown/Inline.hs b/src/Text/Pandoc/Writers/Markdown/Inline.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Writers/Markdown/Inline.hs
@@ -0,0 +1,740 @@
+{-# LANGUAGE OverloadedStrings   #-}
+{-# LANGUAGE ScopedTypeVariables #-}
+{-# LANGUAGE ViewPatterns        #-}
+{- |
+   Module      : Text.Pandoc.Writers.Markdown.Inline
+   Copyright   : Copyright (C) 2006-2024 John MacFarlane
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : John MacFarlane <jgm@berkeley.edu>
+   Stability   : alpha
+   Portability : portable
+-}
+module Text.Pandoc.Writers.Markdown.Inline (
+  inlineListToMarkdown,
+  linkAttributes,
+  attrsToMarkdown,
+  attrsToMarkua
+  ) where
+import Control.Monad (when, liftM2)
+import Control.Monad.Reader
+    ( asks, MonadReader(local) )
+import Control.Monad.State.Strict
+    ( MonadState(get), gets, modify )
+import Data.Char (isAlphaNum, isDigit)
+import Data.List (find, intersperse)
+import Data.List.NonEmpty (nonEmpty)
+import qualified Data.Map as M
+import Data.Maybe (fromMaybe)
+import Data.Text (Text)
+import qualified Data.Text as T
+import Text.Pandoc.Class.PandocMonad (PandocMonad, report)
+import Text.Pandoc.Definition
+import Text.Pandoc.Logging
+import Text.Pandoc.Options
+import Text.Pandoc.Parsing hiding (blankline, blanklines, char, space)
+import Text.DocLayout
+import Text.Pandoc.Shared
+import Text.Pandoc.URI (urlEncode, escapeURI, isURI)
+import Text.Pandoc.Writers.Shared
+import Text.Pandoc.Walk
+import Text.Pandoc.Writers.HTML (writeHtml5String)
+import Text.Pandoc.Writers.Math (texMathToInlines)
+import Text.Pandoc.XML (toHtml5Entities)
+import Data.Coerce (coerce)
+import Text.Pandoc.Writers.Markdown.Types (MarkdownVariant(..),
+                                           WriterState(..),
+                                           WriterEnv(..), MD)
+
+-- | Escape special characters for Markdown.
+escapeText :: WriterOptions -> Text -> Text
+escapeText opts = T.pack . go' . T.unpack
+ where
+  startsWithSpace (' ':_) = True
+  startsWithSpace ('\t':_) = True
+  startsWithSpace [] = True
+  startsWithSpace _ = False
+  go' ('#':cs)
+    | isEnabled Ext_space_in_atx_header opts
+    = if startsWithSpace (dropWhile (=='#') cs)
+         then '\\':'#':go cs
+         else '#':go cs
+    | otherwise = '\\':'#':go cs
+  go' ('@':cs)
+    | isEnabled Ext_citations opts =
+        case cs of
+             (d:_)
+               | isAlphaNum d || d == '_' || d == '{'
+                  -> '\\':'@':go cs
+             _ -> '@':go cs
+  go' cs = go cs
+  go [] = []
+  go ['\\'] = ['\\','\\']
+  go ('-':'-':cs)
+    | isEnabled Ext_smart opts = '\\':'-':go('-':cs)
+  go ('.':'.':'.':cs)
+    | isEnabled Ext_smart opts = '\\':'.':'.':'.':go cs
+  go (':':':':':':cs)
+    | isEnabled Ext_fenced_divs opts -- see #11571
+    = '\\':':':':':':': (takeWhile (==':') cs ++ go cs)
+  go (c:'_':d:cs)
+    | isAlphaNum c
+    , isAlphaNum d =
+      if isEnabled Ext_intraword_underscores opts
+         then c:'_':go (d:cs)
+         else c:'\\':'_':go (d:cs)
+  go ('\\':c:cs)
+    | isEnabled Ext_raw_tex opts = '\\':'\\':go (c:cs)
+    | isAlphaNum c = '\\' : go (c:cs)
+    | otherwise = '\\':'\\': go cs
+  go ('!':'[':cs) = '\\':'!':'[': go cs
+  go ('=':'=':cs)
+    | isEnabled Ext_mark opts = '\\':'=':go ('=':cs)
+  go ('~':'~':cs)
+    | isEnabled Ext_strikeout opts = '\\':'~':go ('~':cs)
+  go ('&':cs)
+    | Right _ <- parse characterReference "" ('&':cs)
+    = '\\':'&': go cs
+  go (c:cs) =
+    case c of
+       '[' -> '\\':c:go cs
+       ']' -> '\\':c:go cs
+       '`' -> '\\':c:go cs
+       '*' -> '\\':c:go cs
+       '_' -> '\\':c:go cs
+       '>' | isEnabled Ext_all_symbols_escapable opts -> '\\':'>':go cs
+           | otherwise -> "&gt;" ++ go cs
+       '<' | isEnabled Ext_all_symbols_escapable opts -> '\\':'<':go cs
+           | otherwise -> "&lt;" ++ go cs
+       '|' | isEnabled Ext_pipe_tables opts -> '\\':'|':go cs
+       '^' | isEnabled Ext_superscript opts -> '\\':'^':go cs
+       '~' | isEnabled Ext_subscript opts -> '\\':'~':go cs
+       '$' | isEnabled Ext_tex_math_dollars opts -> '\\':'$':go cs
+       '\'' | isEnabled Ext_smart opts -> '\\':'\'':go cs
+       '"' | isEnabled Ext_smart opts -> '\\':'"':go cs
+       _   -> c : go cs
+
+-- Escape the escape character, as well as formatting pairs
+escapeMarkuaString :: Text -> Text
+escapeMarkuaString s = foldr (uncurry T.replace) s [("--","~-~-"),
+                        ("**","~*~*"),("//","~/~/"),("^^","~^~^"),(",,","~,~,")]
+
+attrsToMarkdown :: WriterOptions -> Attr -> Doc Text
+attrsToMarkdown opts attribs = braces $ hsep [attribId, attribClasses, attribKeys]
+        where attribId = case attribs of
+                                ("",_,_) -> empty
+                                (i,_,_)  -> "#" <> escAttr (writerIdentifierPrefix opts <> i)
+              attribClasses = case attribs of
+                                (_,[],_) -> empty
+                                (_,cs,_) -> hsep $
+                                            map (escAttr . ("."<>)) $
+                                            filter (not . T.null) cs
+              attribKeys = case attribs of
+                                (_,_,[]) -> empty
+                                (_,_,ks) -> hsep $
+                                            map (\(k,v) -> escAttr k
+                                              <> "=\"" <>
+                                              escAttr v <> "\"") ks
+              escAttr          = mconcat . map escAttrChar . T.unpack
+              escAttrChar '"'  = literal "\\\""
+              escAttrChar '\\' = literal "\\\\"
+              escAttrChar c    = literal $ T.singleton c
+
+attrsToMarkua:: WriterOptions -> Attr -> Doc Text
+attrsToMarkua opts attributes
+     | null list = empty
+     | otherwise = braces $ intercalateDocText list
+        where attrId = case attributes of
+                        ("",_,_) -> []
+                        (i,_,_)  -> [literal $ "id: " <> writerIdentifierPrefix opts <> i]
+              -- all non explicit (key,value) attributes besides id are getting
+              -- a default class key to be Markua conform
+              attrClasses = case attributes of
+                             (_,[],_) -> []
+                             (_,classes,_) -> map (escAttr . ("class: " <>))
+                                classes
+              attrKeyValues = case attributes of
+                               (_,_,[]) -> []
+                               (_,_,keyvalues) -> map ((\(k,v) -> escAttr k
+                                              <> ": " <> escAttr v) .
+                                              preprocessKeyValues) keyvalues
+              escAttr          = mconcat . map escAttrChar . T.unpack
+              escAttrChar '"'  = literal "\""
+              escAttrChar c    = literal $ T.singleton c
+
+              list = concat [attrId, attrClasses, attrKeyValues]
+
+              -- if attribute key is alt, caption, title then content
+              -- gets wrapped inside quotes
+              -- attribute gets removed
+              preprocessKeyValues :: (Text, Text) -> (Text, Text)
+              preprocessKeyValues (key,value)
+                 | key == "alt" ||
+                   key == "caption" ||
+                   key == "title" = (key, inquotes value)
+                 | otherwise = (key,value)
+              intercalateDocText :: [Doc Text] -> Doc Text
+              intercalateDocText [] = empty
+              intercalateDocText [x] = x
+              intercalateDocText (x:xs) = x <> ", " <> (intercalateDocText xs)
+
+-- | Add a (key, value) pair to Pandoc attr type
+addKeyValueToAttr :: Attr -> (Text,Text) -> Attr
+addKeyValueToAttr (ident,classes,kvs) (key,value)
+    | not (T.null key) && not (T.null value) = (ident,
+                                                classes,
+                                                (key,value): kvs)
+    | otherwise = (ident,classes,kvs)
+
+linkAttributes :: WriterOptions -> Attr -> Doc Text
+linkAttributes opts attr =
+  if (isEnabled Ext_link_attributes opts ||
+        isEnabled Ext_attributes opts) && attr /= nullAttr
+     then attrsToMarkdown opts attr
+     else empty
+
+getKey :: Doc Text -> Key
+getKey = toKey . render Nothing
+
+findUsableIndex :: [Text] -> Int -> Int
+findUsableIndex lbls i = if tshow i `elem` lbls
+                         then findUsableIndex lbls (i + 1)
+                         else i
+
+getNextIndex :: PandocMonad m => MD m Int
+getNextIndex = do
+  prevRefs <- gets stPrevRefs
+  refs <- gets stRefs
+  i <- (+ 1) <$> gets stLastIdx
+  modify $ \s -> s{ stLastIdx = i }
+  let refLbls = map (\(r,_,_) -> r) $ prevRefs ++ refs
+  return $ findUsableIndex refLbls i
+
+-- | Get reference for target; if none exists, create unique one and return.
+--   Prefer label if possible; otherwise, generate a unique key.
+getReference :: PandocMonad m => Attr -> Doc Text -> Target -> MD m Text
+getReference attr label target = do
+  refs <- gets stRefs
+  case find (\(_,t,a) -> t == target && a == attr) refs of
+    Just (ref, _, _) -> return ref
+    Nothing       -> do
+      keys <- gets stKeys
+      let key = getKey label
+      let rawkey = coerce key
+      case M.lookup key keys of
+           Nothing -> do -- no other refs with this label
+             (lab', idx) <- if T.null rawkey ||
+                                 T.length rawkey > 999 ||
+                                 T.any (\c -> c == '[' || c == ']') rawkey
+                               then do
+                                 i <- getNextIndex
+                                 return (tshow i, i)
+                               else
+                                 return (render Nothing label, 0)
+             modify (\s -> s{
+               stRefs = (lab', target, attr) : refs,
+               stKeys = M.insert (getKey label)
+                           (M.insert (target, attr) idx mempty)
+                                 (stKeys s) })
+             return lab'
+
+           Just km ->    -- we have refs with this label
+             case M.lookup (target, attr) km of
+                  Just i -> do
+                    let lab' = render Nothing $
+                               label <> if i == 0
+                                           then mempty
+                                           else literal (tshow i)
+                    -- make sure it's in stRefs; it may be
+                    -- a duplicate that was printed in a previous
+                    -- block:
+                    when ((lab', target, attr) `notElem` refs) $
+                       modify (\s -> s{
+                         stRefs = (lab', target, attr) : refs })
+                    return lab'
+                  Nothing -> do -- but this one is to a new target
+                    i <- getNextIndex
+                    let lab' = tshow i
+                    modify (\s -> s{
+                       stRefs = (lab', target, attr) : refs,
+                       stKeys = M.insert key
+                                   (M.insert (target, attr) i km)
+                                         (stKeys s) })
+                    return lab'
+
+
+
+-- | Convert list of Pandoc inline elements to markdown.
+inlineListToMarkdown :: PandocMonad m => WriterOptions -> [Inline] -> MD m (Doc Text)
+inlineListToMarkdown opts ils = do
+    inlist <- asks envInList
+    avoidBadWraps inlist <$> go ils
+  where go [] = return empty
+        go (x@Math{}:y@(Str t):zs)
+          | T.all isDigit (T.take 1 t) -- starts with digit -- see #7058
+          = liftM2 (<>) (inlineToMarkdown opts x)
+              (go (RawInline (Format "html") "<!-- -->" : y : zs))
+        go (Str t : i : is)
+          | isLinkOrSpan i
+          , T.takeEnd 1 t == "!"
+          = do x <- inlineToMarkdown opts (Str (T.dropEnd 1 t))
+               ((x <> "\\!") <>) <$> go (i:is)
+        go (i:is) = case i of
+            Link {} -> case is of
+                -- If a link is followed by another link, or '[', '(' or ':'
+                -- then we don't shortcut
+                Link {}:_                                       -> unshortcutable
+                Space:Link {}:_                                 -> unshortcutable
+                Space:(Str(thead -> Just '[')):_                -> unshortcutable
+                Space:(RawInline _ (thead -> Just '[')):_       -> unshortcutable
+                Space:(Cite _ _):_                              -> unshortcutable
+                SoftBreak:Link {}:_                             -> unshortcutable
+                SoftBreak:(Str(thead -> Just '[')):_            -> unshortcutable
+                SoftBreak:(RawInline _ (thead -> Just '[')):_   -> unshortcutable
+                SoftBreak:(Cite _ _):_                          -> unshortcutable
+                LineBreak:Link {}:_                             -> unshortcutable
+                LineBreak:(Str(thead -> Just '[')):_            -> unshortcutable
+                LineBreak:(RawInline _ (thead -> Just '[')):_   -> unshortcutable
+                LineBreak:(Cite _ _):_                          -> unshortcutable
+                (Cite _ _):_                                    -> unshortcutable
+                Str (thead -> Just '['):_                       -> unshortcutable
+                Str (thead -> Just '('):_                       -> unshortcutable
+                Str (thead -> Just ':'):_                       -> unshortcutable
+                (RawInline _ (thead -> Just '[')):_             -> unshortcutable
+                (RawInline _ (thead -> Just '(')):_             -> unshortcutable
+                (RawInline _ (thead -> Just ':')):_             -> unshortcutable
+                (RawInline _ (T.stripPrefix " [" -> Just _ )):_ -> unshortcutable
+                _                                               -> shortcutable
+            _ -> shortcutable
+          where
+           shortcutable = liftM2 (<>) (inlineToMarkdown opts i) (go is)
+           unshortcutable = do
+               iMark <- local
+                        (\env -> env { envRefShortcutable = False })
+                        (inlineToMarkdown opts i)
+               fmap (iMark <>) (go is)
+           thead = fmap fst . T.uncons
+        isLinkOrSpan Link{} = True
+        isLinkOrSpan Span{} = True
+        isLinkOrSpan _ = False
+
+-- Remove breaking spaces that might cause bad wraps.
+avoidBadWraps :: Bool -> Doc Text -> Doc Text
+avoidBadWraps inListItem = go . toList
+ where
+  go [] = mempty
+  go (BreakingSpace : Text len t : BreakingSpace : xs)
+    = case T.uncons t of
+        Just (c,t')
+          | c == '>'
+             || ((c == '-' || c == '*' || c == '+') && T.null t')
+             || (inListItem && isOrderedListMarker t)
+             || (t == "1." || t == "1)")
+            -> Text (len + 1) (" " <> t) <> go (BreakingSpace : xs)
+        _   -> BreakingSpace <> Text len t <> go (BreakingSpace : xs)
+  go (x:xs) = x <> go xs
+
+  toList (Concat (Concat a b) c) = toList (Concat a (Concat b c))
+  toList (Concat a b) = a : toList b
+  toList x = [x]
+
+-- | Convert Pandoc inline element to markdown.
+inlineToMarkdown :: PandocMonad m => WriterOptions -> Inline -> MD m (Doc Text)
+inlineToMarkdown opts (Span ("",["emoji"],kvs) [Str s]) =
+  case lookup "data-emoji" kvs of
+       Just emojiname | isEnabled Ext_emoji opts ->
+            return $ ":" <> literal emojiname <> ":"
+       _ -> inlineToMarkdown opts (Str s)
+inlineToMarkdown opts (Span ("",["mark"],[]) ils)
+  | isEnabled Ext_mark opts
+    = do contents <- inlineListToMarkdown opts ils
+         return $ "==" <> contents <> "=="
+inlineToMarkdown opts (Span attrs ils) = do
+  variant <- asks envVariant
+  contents <- inlineListToMarkdown opts ils
+  return $ case attrs of
+             (_,["csl-block"],_) -> (cr <>)
+             (_,["csl-left-margin"],_) -> (cr <>)
+             (_,["csl-indent"],_) -> (cr <>)
+             _ -> id
+         $ case variant of
+                PlainText -> contents
+                Markua -> "`" <> contents <> "`" <> attrsToMarkua opts attrs
+                _     | attrs == nullAttr -> contents
+                      | isEnabled Ext_bracketed_spans opts ->
+                        let attrs' = if attrs /= nullAttr
+                                        then attrsToMarkdown opts attrs
+                                        else empty
+                        in "[" <> contents <> "]" <> attrs'
+                      | isEnabled Ext_raw_html opts ||
+                        isEnabled Ext_native_spans opts ->
+                        tagWithAttrs "span" attrs <> contents <> literal "</span>"
+                      | otherwise -> contents
+inlineToMarkdown _ (Emph []) = return empty
+inlineToMarkdown opts (Emph [Emph ils]) = -- #10642
+  inlineListToMarkdown opts ils
+inlineToMarkdown opts (Emph lst) = do
+  variant <- asks envVariant
+  contents <- inlineListToMarkdown opts lst
+  return $ case variant of
+             PlainText
+               | isEnabled Ext_gutenberg opts -> delimited "_" "_" contents
+               | otherwise ->  contents
+             _ -> delimited "*" "*" contents
+inlineToMarkdown _ (Underline []) = return empty
+inlineToMarkdown opts (Underline lst) = do
+  variant <- asks envVariant
+  contents <- inlineListToMarkdown opts lst
+  case variant of
+    PlainText -> return contents
+    _     | isEnabled Ext_bracketed_spans opts ->
+            return $ delimited "[" "]{.underline}" contents
+          | isEnabled Ext_native_spans opts ->
+            return $ tagWithAttrs "span" ("", ["underline"], [])
+              <> contents
+              <> literal "</span>"
+          | isEnabled Ext_raw_html opts ->
+            return $ "<u>" <> contents <> "</u>"
+          | otherwise -> inlineToMarkdown opts (Emph lst)
+inlineToMarkdown _ (Strong []) = return empty
+inlineToMarkdown opts (Strong lst) = do
+  variant <- asks envVariant
+  case variant of
+    PlainText ->
+             inlineListToMarkdown opts $
+               if isEnabled Ext_gutenberg opts
+                  then capitalize lst
+                  else lst
+    _ -> do
+       contents <- inlineListToMarkdown opts lst
+       return $ delimited "**" "**" contents
+inlineToMarkdown _ (Strikeout []) = return empty
+inlineToMarkdown opts (Strikeout lst) = do
+  contents <- inlineListToMarkdown opts lst
+  return $ if isEnabled Ext_strikeout opts
+              then delimited "~~" "~~" contents
+              else if isEnabled Ext_raw_html opts
+                       then "<s>" <> contents <> "</s>"
+                       else contents
+inlineToMarkdown _ (Superscript []) = return empty
+inlineToMarkdown opts (Superscript lst) =
+  local (\env -> env {envEscapeSpaces = envVariant env == Markdown}) $ do
+    contents <- inlineListToMarkdown opts lst
+    if isEnabled Ext_superscript opts
+       then return $ delimited "^" "^" contents
+       else if isEnabled Ext_raw_html opts
+                then return $ "<sup>" <> contents <> "</sup>"
+                else
+                  case traverse toSuperscriptInline lst of
+                    Just xs' | not (writerPreferAscii opts)
+                      -> inlineListToMarkdown opts xs'
+                    _ -> do
+                      let rendered = render Nothing contents
+                      return $
+                        case mapM toSuperscript (T.unpack rendered) of
+                           Just r  -> literal $ T.pack r
+                           Nothing -> literal $ "^(" <> rendered <> ")"
+inlineToMarkdown _ (Subscript []) = return empty
+inlineToMarkdown opts (Subscript lst) =
+  local (\env -> env {envEscapeSpaces = envVariant env == Markdown}) $ do
+    contents <- inlineListToMarkdown opts lst
+    if isEnabled Ext_subscript opts
+       then return $ delimited "~" "~" contents
+       else if isEnabled Ext_raw_html opts
+                then return $ "<sub>" <> contents <> "</sub>"
+                else
+                  case traverse toSubscriptInline lst of
+                    Just xs' | not (writerPreferAscii opts)
+                      -> inlineListToMarkdown opts xs'
+                    _ -> do
+                      let rendered = render Nothing contents
+                      return $
+                        case mapM toSuperscript (T.unpack rendered) of
+                           Just r  -> literal $ T.pack r
+                           Nothing -> literal $ "_(" <> rendered <> ")"
+inlineToMarkdown opts (SmallCaps lst) = do
+  variant <- asks envVariant
+  if variant /= PlainText &&
+     (isEnabled Ext_raw_html opts || isEnabled Ext_native_spans opts)
+     then inlineToMarkdown opts (Span ("",["smallcaps"],[]) lst)
+     else inlineListToMarkdown opts $ capitalize lst
+inlineToMarkdown opts (Quoted SingleQuote lst) = do
+  contents <- inlineListToMarkdown opts lst
+  return $ if isEnabled Ext_smart opts
+              then "'" <> contents <> "'"
+              else
+                if writerPreferAscii opts
+                   then "&lsquo;" <> contents <> "&rsquo;"
+                   else "‘" <> contents <> "’"
+inlineToMarkdown opts (Quoted DoubleQuote lst) = do
+  contents <- inlineListToMarkdown opts lst
+  return $ if isEnabled Ext_smart opts
+              then "\"" <> contents <> "\""
+              else
+                if writerPreferAscii opts
+                   then "&ldquo;" <> contents <> "&rdquo;"
+                   else "“" <> contents <> "”"
+inlineToMarkdown opts (Code attr str) = do
+  variant <- asks envVariant
+  let tickGroups   = filter (T.any (== '`')) $ T.group str
+  let longest      = maybe 0 maximum $ nonEmpty $ map T.length tickGroups
+  let marker       = T.replicate (longest + 1) "`"
+  let spacer       = if longest == 0 then "" else " "
+  let attrsEnabled = isEnabled Ext_inline_code_attributes opts ||
+                     isEnabled Ext_attributes opts
+  let attrs = case variant of
+                       Markua -> attrsToMarkua opts attr
+                       _   -> if attrsEnabled && attr /= nullAttr
+                                        then attrsToMarkdown opts attr
+                                        else empty
+  case variant of
+     PlainText -> return $ literal str
+     _     ->  return $ literal
+                  (marker <> spacer <> str <> spacer <> marker) <> attrs
+inlineToMarkdown opts (Str str) = do
+  variant <- asks envVariant
+  let str' = case variant of
+                Markua -> escapeMarkuaString str
+                _ -> (if writerPreferAscii opts
+                        then toHtml5Entities
+                        else id) .
+                     (if isEnabled Ext_smart opts
+                        then unsmartify opts
+                        else id) .
+                     (if variant == PlainText
+                        then id
+                        else escapeText opts) $ str
+  return $ literal str'
+inlineToMarkdown opts (Math InlineMath str) = do
+  let str' = T.strip str
+  variant <- asks envVariant
+  case () of
+    _ | variant == Markua -> return $ "`" <> literal str <> "`" <> "$"
+      | otherwise -> case writerHTMLMathMethod opts of
+          WebTeX url ->
+             inlineToMarkdown opts
+                  (Image nullAttr [Str str'] (url <> urlEncode str', str'))
+          _ | isEnabled Ext_tex_math_gfm opts ->
+                return $ "$`" <> literal str' <> "`$"
+            | isEnabled Ext_tex_math_dollars opts ->
+                return $ "$" <> literal str' <> "$"
+            | isEnabled Ext_tex_math_single_backslash opts ->
+                return $ "\\(" <> literal str' <> "\\)"
+            | isEnabled Ext_tex_math_double_backslash opts ->
+                return $ "\\\\(" <> literal str' <> "\\\\)"
+            | otherwise ->
+                texMathToInlines InlineMath str' >>=
+                  inlineListToMarkdown opts .
+                    (if variant == PlainText then makeMathPlainer else id)
+
+inlineToMarkdown opts (Math DisplayMath str) = do
+  variant <- asks envVariant
+  case () of
+    _ | variant == Markua -> do
+        let attributes = attrsToMarkua opts (addKeyValueToAttr ("",[],[])
+                                                        ("format", "latex"))
+        return $ blankline <> attributes <> cr <> literal "```" <> cr
+            <> literal str <> cr <> literal "```" <> blankline
+      | otherwise -> case writerHTMLMathMethod opts of
+          WebTeX url ->
+            let str' = T.strip str
+             in (\x -> blankline <> x <> blankline) `fmap`
+                 inlineToMarkdown opts (Image nullAttr [Str str']
+                        (url <> urlEncode str', str'))
+          _ | isEnabled Ext_tex_math_gfm opts ->
+                return $ cr <> (literal "``` math"
+                             $$ literal (T.dropAround (=='\n') str)
+                             $$ literal "```") <> cr
+            | isEnabled Ext_tex_math_dollars opts ->
+                return $ "$$" <> literal str <> "$$"
+            | isEnabled Ext_tex_math_single_backslash opts ->
+                return $ "\\[" <> literal str <> "\\]"
+            | isEnabled Ext_tex_math_double_backslash opts ->
+                return $ "\\\\[" <> literal str <> "\\\\]"
+            | otherwise -> (\x -> cr <> x <> cr) `fmap`
+                (texMathToInlines DisplayMath str >>= inlineListToMarkdown opts)
+
+inlineToMarkdown opts il@(RawInline f str) = do
+  let tickGroups = filter (T.any (== '`')) $ T.group str
+  let numticks   = 1 + maybe 0 maximum (nonEmpty (map T.length tickGroups))
+  variant <- asks envVariant
+  let Format fmt = f
+  let rawAttribInline = return $
+         literal (T.replicate numticks "`") <> literal str <>
+         literal (T.replicate numticks "`") <> literal "{=" <> literal fmt <> literal "}"
+  let renderEmpty = mempty <$ report (InlineNotRendered il)
+  case variant of
+    PlainText
+      | f == "plain" -> return $ literal str
+    Commonmark
+      | f `elem` ["gfm", "commonmark", "commonmark_x", "markdown"]
+         -> return $ literal str
+    Markdown
+      | f `elem` ["markdown", "markdown_github", "markdown_phpextra",
+                  "markdown_mmd", "markdown_strict"]
+         -> return $ literal str
+    Markua -> renderEmpty
+    _ | isEnabled Ext_raw_attribute opts -> rawAttribInline
+      | f `elem` ["html", "html5", "html4"]
+      , isEnabled Ext_raw_html opts
+         -> return $ literal str
+      | f `elem` ["latex", "tex"]
+      , isEnabled Ext_raw_tex opts
+         -> return $ literal str
+    _ -> renderEmpty
+
+
+inlineToMarkdown opts LineBreak = do
+  variant <- asks envVariant
+  if variant == PlainText || isEnabled Ext_hard_line_breaks opts
+     then return cr
+     else return $
+          if variant == Commonmark || isEnabled Ext_escaped_line_breaks opts
+             then "\\" <> cr
+             else "  " <> cr
+inlineToMarkdown _ Space = do
+  escapeSpaces <- asks envEscapeSpaces
+  return $ if escapeSpaces then "\\ " else space
+inlineToMarkdown opts SoftBreak = do
+  escapeSpaces <- asks envEscapeSpaces
+  let space' = if escapeSpaces then "\\ " else space
+  return $ case writerWrapText opts of
+                WrapNone     -> space'
+                WrapAuto     -> space'
+                WrapPreserve -> cr
+inlineToMarkdown opts (Cite [] lst) = inlineListToMarkdown opts lst
+inlineToMarkdown opts (Cite (c:cs) lst)
+  | not (isEnabled Ext_citations opts) = inlineListToMarkdown opts lst
+  | otherwise =
+      if citationMode c == AuthorInText
+         then do
+           suffs <- inlineListToMarkdown opts $ citationSuffix c
+           rest <- mapM convertOne cs
+           let inbr = suffs <>
+                      (if not (null (citationSuffix c)) && not (null rest)
+                          then text ";"
+                          else mempty)
+                      <+> joincits rest
+               br   = if isEmpty inbr then empty else char '[' <> inbr <> char ']'
+           return $ literal ("@" <> maybeInBraces (citationId c)) <+> br
+         else do
+           cits <- mapM convertOne (c:cs)
+           return $ literal "[" <> joincits cits <> literal "]"
+  where
+        maybeInBraces key =
+          case readWith (citeKey False >> spaces >> eof)
+                 defaultParserState ("@" <> key) of
+            Left _  -> "{" <> key <> "}"
+            Right _ -> key
+        joincits = hcat . intersperse (literal "; ") . filter (not . isEmpty)
+        convertOne Citation { citationId      = k
+                            , citationPrefix  = pinlines
+                            , citationSuffix  = sinlines
+                            , citationMode    = m }
+                               = do
+           pdoc <- inlineListToMarkdown opts pinlines
+           sdoc <- inlineListToMarkdown opts sinlines
+           let k' = literal (modekey m <> "@" <> maybeInBraces k)
+               r = case sinlines of
+                        Str (T.uncons -> Just (y,_)):_
+                          | y `elem` (",;]@" :: String) -> k' <> sdoc
+                        Space:_                         -> k' <> sdoc
+                        _                               -> k' <+> sdoc
+           return $ pdoc <+> r
+        modekey SuppressAuthor = "-"
+        modekey _              = ""
+inlineToMarkdown opts lnk@(Link attr@(ident,classes,kvs) txt (src, tit)) = do
+  variant <- asks envVariant
+  linktext <- inlineListToMarkdown opts txt
+  let linktitle = if T.null tit
+                     then empty
+                     else literal $ " \"" <> tit <> "\""
+  let srcSuffix = fromMaybe src (T.stripPrefix "mailto:" src)
+  let useAuto = isURI src &&
+                T.null ident &&
+                null kvs &&
+               (null classes || classes == ["uri"] || classes == ["email"]) &&
+                case txt of
+                      [Str s] | escapeURI s == srcSuffix -> True
+                      _       -> False
+  let useWikilink = "wikilink" `elem` classes &&
+                    (isEnabled Ext_wikilinks_title_after_pipe opts ||
+                     isEnabled Ext_wikilinks_title_before_pipe opts)
+  let useRefLinks = writerReferenceLinks opts && not useAuto
+  shortcutable <- asks envRefShortcutable
+  let useShortcutRefLinks = shortcutable &&
+                             (variant == Commonmark ||
+                              isEnabled Ext_shortcut_reference_links opts)
+  reftext <- if useRefLinks
+                then literal <$> getReference attr linktext (src, tit)
+                else return mempty
+  case variant of
+    PlainText
+      | useAuto -> return $ literal srcSuffix
+      | otherwise -> return linktext
+    Markua
+      | T.null tit -> return $ result <> attrsToMarkua opts attr
+      | otherwise ->  return $ result <> attrsToMarkua opts attributes
+        where result = "[" <> linktext <> "](" <> (literal src) <> ")"
+              attributes = addKeyValueToAttr attr ("title", tit)
+    -- Use wikilinks where possible
+    _ | src == stringify txt && useWikilink ->
+        return $ "[[" <> literal (stringify txt) <> "]]"
+      | useAuto -> return $ "<" <> literal srcSuffix <> ">"
+      | useWikilink && isEnabled Ext_wikilinks_title_after_pipe opts -> return $
+        "[[" <> literal src <> "|" <> literal (stringify txt) <> "]]"
+      | useWikilink && isEnabled Ext_wikilinks_title_before_pipe opts -> return $
+        "[[" <> literal (stringify txt) <> "|" <> literal src <> "]]"
+      | useRefLinks ->
+           let first  = "[" <> linktext <> "]"
+               second = if getKey linktext == getKey reftext
+                           then if useShortcutRefLinks
+                                   then ""
+                                   else "[]"
+                           else "[" <> reftext <> "]"
+           in  return $ first <> second
+      | isEnabled Ext_raw_html opts
+      , not (isEnabled Ext_link_attributes opts || isEnabled Ext_attributes opts)
+      , attr /= nullAttr -> -- use raw HTML to render attributes
+          literal . T.strip <$>
+            writeHtml5String opts{ writerTemplate = Nothing }
+            (Pandoc nullMeta [Plain [lnk]])
+      | otherwise -> return $
+         "[" <> linktext <> "](" <> literal src <> linktitle <> ")" <>
+         linkAttributes opts attr
+inlineToMarkdown opts img@(Image attr alternate (source, tit))
+  | isEnabled Ext_raw_html opts &&
+    not (isEnabled Ext_link_attributes opts || isEnabled Ext_attributes opts) &&
+    attr /= nullAttr = -- use raw HTML
+    literal . T.strip <$>
+      writeHtml5String opts{ writerTemplate = Nothing } (Pandoc nullMeta [Plain [img]])
+  | otherwise = do
+  variant <- asks envVariant
+  let txt = if null alternate || alternate == [Str source]
+                                 -- to prevent autolinks
+               then [Str ""]
+               else alternate
+  linkPart <- inlineToMarkdown opts (Link attr txt (source, tit))
+  alt <- inlineListToMarkdown opts alternate
+  let attributes | variant == Markua = attrsToMarkua opts $
+            addKeyValueToAttr (addKeyValueToAttr attr ("title", tit))
+            ("alt", render (Just (writerColumns opts)) alt)
+                 | otherwise = empty
+  return $ case variant of
+                PlainText -> "[" <> linkPart <> "]"
+                Markua -> cr <> attributes <> cr <> literal "![](" <>
+                            literal source <> ")" <> cr
+                _ -> "!" <> linkPart
+inlineToMarkdown opts (Note contents) = do
+  modify (\st -> st{ stNotes = contents : stNotes st })
+  st <- get
+  let ref = literal $ writerIdentifierPrefix opts <> tshow (stNoteNum st + length (stNotes st) - 1)
+  if isEnabled Ext_footnotes opts
+     then return $ "[^" <> ref <> "]"
+     else return $ "[" <> ref <> "]"
+
+makeMathPlainer :: [Inline] -> [Inline]
+makeMathPlainer = walk go
+  where
+  go (Emph xs) = Span nullAttr xs
+  go x         = x
diff --git a/src/Text/Pandoc/Writers/Markdown/Table.hs b/src/Text/Pandoc/Writers/Markdown/Table.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Writers/Markdown/Table.hs
@@ -0,0 +1,141 @@
+{-# LANGUAGE OverloadedStrings   #-}
+{- |
+   Module      : Text.Pandoc.Writers.Markdown
+   Copyright   : © 2006-2024 John MacFarlane
+   License     : GPL-2.0-or-later
+   Maintainer  : John MacFarlane <jgm@berkeley.edu>
+
+Create Markdown pipe-tables and pandoc-style tables.
+-}
+module Text.Pandoc.Writers.Markdown.Table
+  ( pipeTable
+  , pandocTable
+  ) where
+
+import Control.Monad.Reader (asks)
+import Data.List (intersperse, transpose)
+import Data.List.NonEmpty (nonEmpty)
+import Data.Text (Text)
+import qualified Data.Text as T
+import Text.DocLayout
+import Text.Pandoc.Class.PandocMonad (PandocMonad)
+import Text.Pandoc.Definition (Alignment (..))
+import Text.Pandoc.Options (WriterOptions (writerColumns, writerWrapText),
+                            WrapOption(WrapAuto))
+import Text.Pandoc.Writers.Markdown.Types (MarkdownVariant(Markdown),
+                                           WriterEnv(..), MD)
+
+-- | Creates a Markdown pipe table.
+pipeTable :: PandocMonad m
+          => WriterOptions
+          -> Bool            -- ^ headless?
+          -> [Alignment]     -- ^ column alignments
+          -> [Double]        -- ^ column widhts
+          -> [Doc Text]      -- ^ table header cells
+          -> [[Doc Text]]    -- ^ table body rows
+          -> MD m (Doc Text)
+pipeTable opts headless aligns widths rawHeaders rawRows = do
+  let sp = literal " "
+  let contentWidths = map (max 3 . maybe 3 maximum . nonEmpty . map offset) $
+                       transpose (rawHeaders : rawRows)
+  let colwidth = writerColumns opts
+  let numcols = length contentWidths
+  let maxwidth = sum contentWidths
+  -- if cell contents are > COLUMNS, adding padding looks bad
+  let pad = maxwidth <= writerColumns opts
+  let blockFor _ _ y | not pad = sp <> y <> sp <> lblock 0 empty
+      blockFor AlignLeft   x y = lblock (x + 2) (sp <> y) <> lblock 0 empty
+      blockFor AlignCenter x y = cblock (x + 2) (sp <> y <> sp) <> lblock 0 empty
+      blockFor AlignRight  x y = rblock (x + 2) (y <> sp) <> lblock 0 empty
+      blockFor AlignDefault x y = lblock (x + 2) (sp <> y) <> lblock 0 empty
+  variant <- asks envVariant
+  let pipeWidths = if variant == Markdown &&
+                      not (all (== 0) widths) &&
+                      maxwidth + (numcols + 1) > colwidth
+                      then map
+                            (max 0 .
+                              floor .
+                                (* fromIntegral (colwidth - (numcols +1))))
+                            widths
+                      else if pad
+                              then contentWidths
+                              else map (const 2) widths
+  let torow cs = nowrap $ literal "|" <>
+                    hcat (intersperse (literal "|") $
+                          zipWith3 blockFor aligns contentWidths (map chomp cs))
+                    <> literal "|"
+  let toborder a w = literal $ case a of
+                          AlignLeft    -> ":" <> T.replicate (w + 1) "-"
+                          AlignCenter  -> ":" <> T.replicate w "-" <> ":"
+                          AlignRight   -> T.replicate (w + 1) "-" <> ":"
+                          AlignDefault -> T.replicate (w + 2) "-"
+  -- note:  pipe tables can't completely lack a
+  -- header; for a headerless table, we need a header of empty cells.
+  -- see jgm/pandoc#1996.
+  let header = if headless
+                  then torow (replicate (length aligns) empty)
+                  else torow rawHeaders
+  let border = nowrap $ literal "|" <> hcat (intersperse (literal "|") $
+                        zipWith toborder aligns pipeWidths) <> literal "|"
+  let body   = vcat $ map torow rawRows
+  return $ header $$ border $$ body
+
+-- | Write a pandoc-style Markdown table.
+pandocTable :: PandocMonad m
+            => WriterOptions
+            -> Bool            -- ^ whether this is a multiline table
+            -> Bool            -- ^ whether the table has a header
+            -> [Alignment]     -- ^ column alignments
+            -> [Double]        -- ^ column widths
+            -> [Doc Text]      -- ^ table header cells
+            -> [[Doc Text]]    -- ^ table body rows
+            -> MD m (Doc Text)
+pandocTable opts multiline headless aligns widths rawHeaders rawRows = do
+  let isSimple = all (==0) widths
+  let alignHeader alignment = case alignment of
+                                AlignLeft    -> lblock
+                                AlignCenter  -> cblock
+                                AlignRight   -> rblock
+                                AlignDefault -> lblock
+  -- Number of characters per column necessary to output every cell
+  -- without requiring a line break.
+  -- The @+2@ is needed for specifying the alignment.
+  let numChars    = (+ 2) . maybe 0 maximum . nonEmpty . map offset
+  -- Number of characters per column necessary to output every cell
+  -- without requiring a line break *inside a word*.
+  -- The @+2@ is needed for specifying the alignment.
+  let minNumChars = (+ 2) . maybe 0 maximum . nonEmpty . map minOffset
+  let columns = transpose (rawHeaders : rawRows)
+  -- minimal column width without wrapping a single word
+  let relWidth w col =
+         max (floor $ fromIntegral (writerColumns opts - 1) * w)
+             (if writerWrapText opts == WrapAuto
+                 then minNumChars col
+                 else numChars col)
+  let widthsInChars
+        | isSimple  = map numChars columns
+        | otherwise = zipWith relWidth widths columns
+  let makeRow = hcat . intersperse (lblock 1 (literal " ")) .
+                   zipWith3 alignHeader aligns widthsInChars
+  let rows' = map makeRow rawRows
+  let head' = makeRow rawHeaders
+  let underline = mconcat $ intersperse (literal " ") $
+                  map (\width -> literal (T.replicate width "-")) widthsInChars
+  let border
+        | multiline = literal (T.replicate (sum widthsInChars +
+                        length widthsInChars - 1) "-")
+        | headless  = underline
+        | otherwise = empty
+  let head'' = if headless
+                  then empty
+                  else border <> cr <> head'
+  let body = if multiline
+                then vsep rows' $$
+                     if length rows' < 2
+                        then blankline -- #4578
+                        else empty
+                else vcat rows'
+  let bottom = if headless
+                  then underline
+                  else border
+  return $ head'' $$ underline $$ body $$ bottom
diff --git a/src/Text/Pandoc/Writers/Markdown/Types.hs b/src/Text/Pandoc/Writers/Markdown/Types.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Writers/Markdown/Types.hs
@@ -0,0 +1,79 @@
+{- |
+   Module      : Text.Pandoc.Writers.Markdown.Types
+   Copyright   : Copyright (C) 2006-2024 John MacFarlane
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : John MacFarlane <jgm@berkeley.edu>
+   Stability   : alpha
+   Portability : portable
+-}
+module Text.Pandoc.Writers.Markdown.Types (
+  MarkdownVariant(..),
+  WriterState(..),
+  WriterEnv(..),
+  Notes,
+  Ref,
+  Refs,
+  MD,
+  evalMD
+  ) where
+import Control.Monad.Reader
+import Control.Monad.State.Strict
+import Data.Default
+import qualified Data.Map as M
+import qualified Data.Set as Set
+import Data.Text (Text)
+import Text.Pandoc.Parsing (Key)
+import Text.Pandoc.Class.PandocMonad (PandocMonad)
+import Text.Pandoc.Definition
+
+type Notes = [[Block]]
+type Ref   = (Text, Target, Attr)
+type Refs  = [Ref]
+
+type MD m = ReaderT WriterEnv (StateT WriterState m)
+
+evalMD :: PandocMonad m => MD m a -> WriterEnv -> WriterState -> m a
+evalMD md env st = evalStateT (runReaderT md env) st
+
+data WriterEnv = WriterEnv { envInList          :: Bool
+                           , envVariant         :: MarkdownVariant
+                           , envRefShortcutable :: Bool
+                           , envBlockLevel      :: Int
+                           , envEscapeSpaces    :: Bool
+                           }
+
+data MarkdownVariant =
+      Markua
+    | PlainText
+    | Commonmark
+    | Markdown
+    deriving (Show, Eq)
+
+instance Default WriterEnv
+  where def = WriterEnv { envInList          = False
+                        , envVariant         = Markdown
+                        , envRefShortcutable = True
+                        , envBlockLevel      = 0
+                        , envEscapeSpaces    = False
+                        }
+
+data WriterState = WriterState { stNotes   :: Notes
+                               , stPrevRefs :: Refs
+                               , stRefs    :: Refs
+                               , stKeys    :: M.Map Key
+                                                (M.Map (Target, Attr) Int)
+                               , stLastIdx  :: Int
+                               , stIds     :: Set.Set Text
+                               , stNoteNum :: Int
+                               }
+
+instance Default WriterState
+  where def = WriterState{ stNotes = []
+                         , stPrevRefs = []
+                         , stRefs = []
+                         , stKeys = M.empty
+                         , stLastIdx = 0
+                         , stIds = Set.empty
+                         , stNoteNum = 1
+                         }
diff --git a/src/Text/Pandoc/Writers/Math.hs b/src/Text/Pandoc/Writers/Math.hs
--- a/src/Text/Pandoc/Writers/Math.hs
+++ b/src/Text/Pandoc/Writers/Math.hs
@@ -1,3 +1,4 @@
+{-# LANGUAGE OverloadedStrings #-}
 module Text.Pandoc.Writers.Math
   ( texMathToInlines
   , convertMath
@@ -6,17 +7,19 @@
   )
 where
 
-import Text.Pandoc.Class
+import qualified Data.Text as T
+import Text.Pandoc.Class.PandocMonad
 import Text.Pandoc.Definition
 import Text.Pandoc.Logging
 import Text.TeXMath (DisplayType (..), Exp, readTeX, writePandoc)
+import Text.Pandoc.Options (defaultMathJaxURL, defaultKaTeXURL)
 
 -- | Converts a raw TeX math formula to a list of 'Pandoc' inlines.
 -- Defaults to raw formula between @$@ or @$$@ characters if entire formula
 -- can't be converted.
 texMathToInlines :: PandocMonad m
                  => MathType
-                 -> String    -- ^ String to parse (assumes @'\n'@ line endings)
+                 -> T.Text         -- ^ String to parse (assumes @'\n'@ line endings)
                  -> m [Inline]
 texMathToInlines mt inp = do
   res <- convertMath writePandoc mt inp
@@ -27,8 +30,8 @@
          return [mkFallback mt inp]
        Left il           -> return [il]
 
-mkFallback :: MathType -> String -> Inline
-mkFallback mt str = Str (delim ++ str ++ delim)
+mkFallback :: MathType -> T.Text -> Inline
+mkFallback mt str = Str (delim <> str <> delim)
    where delim = case mt of
                       DisplayMath -> "$$"
                       InlineMath  -> "$"
@@ -37,7 +40,7 @@
 -- issuing a warning and producing a fallback (a raw string)
 -- on failure.
 convertMath :: PandocMonad m
-            => (DisplayType -> [Exp] -> a) -> MathType -> String
+            => (DisplayType -> [Exp] -> a) -> MathType -> T.Text
             -> m (Either Inline a)
 convertMath writer mt str =
   case writer dt <$> readTeX str of
@@ -48,9 +51,3 @@
    where dt = case mt of
                    DisplayMath -> DisplayBlock
                    InlineMath  -> DisplayInline
-
-defaultMathJaxURL :: String
-defaultMathJaxURL = "https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.2/"
-
-defaultKaTeXURL :: String
-defaultKaTeXURL = "https://cdnjs.cloudflare.com/ajax/libs/KaTeX/0.8.3/"
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,24 +1,7 @@
-{-
-Copyright (C) 2008-2017 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 OverloadedStrings #-}
 {- |
    Module      : Text.Pandoc.Writers.MediaWiki
-   Copyright   : Copyright (C) 2008-2017 John MacFarlane
+   Copyright   : Copyright (C) 2008-2024 John MacFarlane
    License     : GNU GPL, version 2 or above
 
    Maintainer  : John MacFarlane <jgm@berkeley.edu>
@@ -29,31 +12,37 @@
 
 MediaWiki:  <http://www.mediawiki.org/wiki/MediaWiki>
 -}
-module Text.Pandoc.Writers.MediaWiki ( writeMediaWiki ) where
+module Text.Pandoc.Writers.MediaWiki ( writeMediaWiki, highlightingLangs ) where
 import Control.Monad.Reader
 import Control.Monad.State.Strict
-import Data.List (intercalate)
+import Data.Maybe (fromMaybe)
+import qualified Data.List as DL
 import qualified Data.Set as Set
-import Data.Text (Text, pack)
-import Text.Pandoc.Class (PandocMonad, report)
+import Data.Text (Text)
+import qualified Data.Text as T
+import Data.List.NonEmpty (NonEmpty((:|)))
+import Text.Pandoc.Class.PandocMonad (PandocMonad, report)
 import Text.Pandoc.Definition
 import Text.Pandoc.ImageSize
 import Text.Pandoc.Logging
 import Text.Pandoc.Options
-import Text.Pandoc.Pretty (render)
+import Text.DocLayout
 import Text.Pandoc.Shared
-import Text.Pandoc.Templates (renderTemplate')
+import Text.Pandoc.URI
+import Text.Pandoc.Templates (renderTemplate)
+import qualified Text.Pandoc.Writers.AnnotatedTable as Ann
 import Text.Pandoc.Writers.Shared
 import Text.Pandoc.XML (escapeStringForXML)
 
 data WriterState = WriterState {
     stNotes   :: Bool            -- True if there are notes
   , stOptions :: WriterOptions   -- writer options
+  , stInDefLabel :: Bool         -- True if in definition list label
   }
 
 data WriterReader = WriterReader {
     options   :: WriterOptions -- Writer options
-  , listLevel :: String        -- String at beginning of list items, e.g. "**"
+  , listLevel :: [Char]        -- String at beginning of list items, e.g. "**"
   , useTags   :: Bool          -- True if we should use HTML tags because we're in a complex list
   }
 
@@ -62,7 +51,8 @@
 -- | Convert Pandoc to MediaWiki.
 writeMediaWiki :: PandocMonad m => WriterOptions -> Pandoc -> m Text
 writeMediaWiki opts document =
-  let initialState = WriterState { stNotes = False, stOptions = opts }
+  let initialState = WriterState {
+        stNotes = False, stOptions = opts, stInDefLabel = False }
       env = WriterReader { options = opts, listLevel = [], useTags = False }
   in  evalStateT (runReaderT (pandocToMediaWiki document) env) initialState
 
@@ -70,175 +60,207 @@
 pandocToMediaWiki :: PandocMonad m => Pandoc -> MediaWikiWriter m Text
 pandocToMediaWiki (Pandoc meta blocks) = do
   opts <- asks options
-  metadata <- metaToJSON opts
-              (fmap trimr . blockListToMediaWiki)
-              inlineListToMediaWiki
+  metadata <- metaToContext opts
+              (fmap chomp . blockListToMediaWiki)
+              (fmap chomp . inlineListToMediaWiki)
               meta
   body <- blockListToMediaWiki blocks
   notesExist <- gets stNotes
   let notes = if notesExist
-                 then "\n<references />"
-                 else ""
-  let main = body ++ notes
+                 then cr <> literal "<references />"
+                 else mempty
+  let main = body <> notes
   let context = defField "body" main
                 $ defField "toc" (writerTableOfContents opts) metadata
-  pack <$> case writerTemplate opts of
-                Nothing  -> return main
-                Just tpl -> renderTemplate' tpl context
+  return $ render Nothing $
+    case writerTemplate opts of
+         Nothing  -> main
+         Just tpl -> renderTemplate tpl context
 
 -- | Escape special characters for MediaWiki.
-escapeString :: String -> String
-escapeString =  escapeStringForXML
+escapeText :: Text -> Text
+escapeText =  escapeStringForXML
 
 -- | Convert Pandoc block element to MediaWiki.
 blockToMediaWiki :: PandocMonad m
                  => Block         -- ^ Block element
-                 -> MediaWikiWriter m String
-
-blockToMediaWiki Null = return ""
+                 -> MediaWikiWriter m (Doc Text)
 
 blockToMediaWiki (Div attrs bs) = do
   contents <- blockListToMediaWiki bs
-  return $ render Nothing (tagWithAttrs "div" attrs) ++ "\n\n" ++
-                     contents ++ "\n\n" ++ "</div>"
+  return $ tagWithAttrs "div" attrs $$
+            contents $$
+            literal "</div>" $$
+            blankline
 
 blockToMediaWiki (Plain inlines) =
   inlineListToMediaWiki inlines
 
--- title beginning with fig: indicates that the image is a figure
-blockToMediaWiki (Para [Image attr txt (src,'f':'i':'g':':':tit)]) = do
-  capt <- if null txt
-             then return ""
-             else ("|caption " ++) `fmap` inlineListToMediaWiki txt
+blockToMediaWiki (SimpleFigure attr txt (src, tit)) = do
+  capt <- inlineListToMediaWiki txt
   img  <- imageToMediaWiki attr
-  let opt = if null txt
-               then ""
-               else "|alt=" ++ if null tit then capt else tit ++ capt
-  return $ "[[File:" ++ src ++ "|frame|none" ++ img ++ opt ++ "]]\n"
+  let capt' = render Nothing capt
+  let opt = if T.null tit
+               then
+                 if T.null capt'
+                    then ""
+                    else "alt=" <> capt'
+               else "alt=" <> tit
+  let separator = "<nowiki></nowiki>"
+  -- External images (URIs) cannot use [[File:...]] syntax;
+  -- they must be rendered as bare URLs. MediaWiki will auto-embed
+  -- them when $wgAllowExternalImages is enabled.
+  return $ if isURI src
+           then literal (separator <> src <> separator) <> cr
+           else literal ("[[" <>
+                  T.intercalate "|"
+                  (filter (not . T.null) ["File:" <> src
+                                       , "thumb"
+                                       , "none"
+                                       , img
+                                       , opt
+                                       , capt'
+                                       ]) <>
+                  "]]") <> cr
 
 blockToMediaWiki (Para inlines) = do
   tags <- asks useTags
   lev <- asks listLevel
   contents <- inlineListToMediaWiki inlines
+  let contents' = render Nothing contents
+  let initEsc = if startsWithListMarker contents'
+                   then literal "<nowiki></nowiki>"
+                   else mempty
   return $ if tags
-              then  "<p>" ++ contents ++ "</p>"
-              else contents ++ if null lev then "\n" else ""
+              then literal "<p>" <> contents <> literal "</p>"
+              else initEsc <> contents $$
+                   if null lev then blankline else mempty
 
 blockToMediaWiki (LineBlock lns) =
   blockToMediaWiki $ linesToPara lns
 
 blockToMediaWiki b@(RawBlock f str)
-  | f == Format "mediawiki" = return str
-  | f == Format "html"      = return str
-  | otherwise               = "" <$ report (BlockNotRendered b)
+  | f == Format "mediawiki" = return $ literal str
+  | f == Format "html"      = return $ literal str
+  | otherwise               = mempty <$ report (BlockNotRendered b)
 
-blockToMediaWiki HorizontalRule = return "\n-----\n"
+blockToMediaWiki HorizontalRule = return $ blankline <> literal "-----" <> blankline
 
-blockToMediaWiki (Header level _ inlines) = do
+blockToMediaWiki (Header level (ident,_,_) inlines) = do
+  let autoId = T.replace " " "_" $ stringify inlines
   contents <- inlineListToMediaWiki inlines
-  let eqs = replicate level '='
-  return $ eqs ++ " " ++ contents ++ " " ++ eqs ++ "\n"
+  let eqs = literal $ T.replicate level "="
+  return $
+    (if T.null ident || autoId == ident
+        then mempty
+        else literal ("<span id=\"" <> ident <> "\"></span>") <> cr)
+    <> eqs <> space <> contents <> space <> eqs <> blankline
 
-blockToMediaWiki (CodeBlock (_,classes,_) str) = do
+blockToMediaWiki (CodeBlock (_,classes,keyvals) str) = do
   let at  = Set.fromList classes `Set.intersection` highlightingLangs
-  return $
+  let numberLines = any (`elem` ["number","numberLines", "number-lines"])
+                    classes
+  let start = lookup "startFrom" keyvals
+  return $ literal $
     case Set.toList at of
-       [] -> "<pre" ++ (if null classes
+       [] -> "<pre" <> (if null classes
                            then ">"
-                           else " class=\"" ++ unwords classes ++ "\">") ++
-             escapeString str ++ "</pre>"
-       (l:_) -> "<source lang=\"" ++ l ++ "\">" ++ str ++ "</source>"
+                           else " class=\"" <> T.unwords classes <> "\">") <>
+             escapeText str <> "</pre>"
+       (l:_) -> "<syntaxhighlight lang=\"" <> l <> "\"" <>
+                (if numberLines then " line" else "") <>
+                maybe "" (\x -> " start=\"" <> x <> "\"") start <>
+                ">" <> str <>
+                "</syntaxhighlight>"
             -- note:  no escape!  even for <!
 
 blockToMediaWiki (BlockQuote blocks) = do
   contents <- blockListToMediaWiki blocks
-  return $ "<blockquote>" ++ contents ++ "</blockquote>"
+  return $ literal "<blockquote>" <> chomp contents <> cr <> literal "</blockquote>"
 
-blockToMediaWiki (Table capt aligns widths headers rows') = do
-  caption <- if null capt
-                then return ""
-                else do
-                   c <- inlineListToMediaWiki capt
-                   return $ "|+ " ++ trimr c ++ "\n"
-  let headless = all null headers
-  let allrows = if headless then rows' else headers:rows'
-  tableBody <- intercalate "|-\n" `fmap`
-                mapM (tableRowToMediaWiki headless aligns widths)
-                     (zip [1..] allrows)
-  return $ "{|\n" ++ caption ++ tableBody ++ "|}\n"
+blockToMediaWiki (Table attr capt colSpecs thead tbody tfoot) = do
+    tableToMediaWiki (Ann.toTable attr capt colSpecs thead tbody tfoot)
 
 blockToMediaWiki x@(BulletList items) = do
-  tags <- fmap (|| not (isSimpleList x)) $ asks useTags
+  tags <-
+    (|| not (isSimpleList x)) <$> asks useTags
   if tags
      then do
         contents <- local (\ s -> s { useTags = True }) $ mapM listItemToMediaWiki items
-        return $ "<ul>\n" ++ vcat contents ++ "</ul>\n"
+        return $ literal "<ul>" <> cr <> vcat contents <> literal "</ul>" <> blankline
      else do
         lev <- asks listLevel
-        contents <- local (\s -> s { listLevel = listLevel s ++ "*" }) $ mapM listItemToMediaWiki items
-        return $ vcat contents ++ if null lev then "\n" else ""
+        contents <- local (\s -> s { listLevel = listLevel s <> "*" }) $ mapM listItemToMediaWiki items
+        return $ vcat contents <> if null lev then blankline else mempty
 
 blockToMediaWiki x@(OrderedList attribs items) = do
-  tags <- fmap (|| not (isSimpleList x)) $ asks useTags
+  tags <-
+    (|| not (isSimpleList x)) <$> asks useTags
   if tags
      then do
         contents <- local (\s -> s { useTags = True }) $ mapM listItemToMediaWiki items
-        return $ "<ol" ++ listAttribsToString attribs ++ ">\n" ++ vcat contents ++ "</ol>\n"
+        return $ literal ("<ol" <> listAttribsToText attribs <> ">") <> cr <> vcat contents <> literal "</ol>" <> blankline
      else do
         lev <- asks listLevel
-        contents <- local (\s -> s { listLevel = listLevel s ++ "#" }) $ mapM listItemToMediaWiki items
-        return $ vcat contents ++ if null lev then "\n" else ""
+        contents <- local (\s -> s { listLevel = listLevel s <> "#" }) $ mapM listItemToMediaWiki items
+        return $ vcat contents <> if null lev then blankline else mempty
 
 blockToMediaWiki x@(DefinitionList items) = do
-  tags <- fmap (|| not (isSimpleList x)) $ asks useTags
+  tags <-
+    (|| not (isSimpleList x)) <$> asks useTags
   if tags
      then do
         contents <- local (\s -> s { useTags = True }) $ mapM definitionListItemToMediaWiki items
-        return $ "<dl>\n" ++ vcat contents ++ "</dl>\n"
+        return $ literal "<dl>" <> cr <> vcat contents <> literal "</dl>" <> blankline
      else do
         lev <- asks listLevel
-        contents <- local (\s -> s { listLevel = listLevel s ++ ";" }) $ mapM definitionListItemToMediaWiki items
-        return $ vcat contents ++ if null lev then "\n" else ""
+        contents <- local (\s -> s { listLevel = listLevel s <> ";" }) $ mapM definitionListItemToMediaWiki items
+        return $ vcat contents <> if null lev then blankline else mempty
 
+blockToMediaWiki (Figure (ident, classes, kvs) _ body) =
+  blockToMediaWiki (Div (ident, ["figure"] `DL.union` classes, kvs) body)
+
 -- Auxiliary functions for lists:
 
 -- | Convert ordered list attributes to HTML attribute string
-listAttribsToString :: ListAttributes -> String
-listAttribsToString (startnum, numstyle, _) =
-  let numstyle' = camelCaseToHyphenated $ show numstyle
+listAttribsToText :: ListAttributes -> Text
+listAttribsToText (startnum, numstyle, _) =
+  let numstyle' = camelCaseToHyphenated $ tshow numstyle
   in  (if startnum /= 1
-          then " start=\"" ++ show startnum ++ "\""
-          else "") ++
+          then " start=\"" <> tshow startnum <> "\""
+          else "") <>
       (if numstyle /= DefaultStyle
-          then " style=\"list-style-type: " ++ numstyle' ++ ";\""
+          then " style=\"list-style-type: " <> numstyle' <> ";\""
           else "")
 
 -- | Convert bullet or ordered list item (list of blocks) to MediaWiki.
-listItemToMediaWiki :: PandocMonad m => [Block] -> MediaWikiWriter m String
+listItemToMediaWiki :: PandocMonad m => [Block] -> MediaWikiWriter m (Doc Text)
 listItemToMediaWiki items = do
   contents <- blockListToMediaWiki items
   tags <- asks useTags
   if tags
-     then return $ "<li>" ++ contents ++ "</li>"
+     then return $ literal "<li>" <> chomp contents <> literal "</li>"
      else do
        marker <- asks listLevel
-       return $ marker ++ " " ++ contents
+       return $ literal (T.pack marker) <> space <> chomp contents
 
 -- | Convert definition list item (label, list of blocks) to MediaWiki.
 definitionListItemToMediaWiki :: PandocMonad m
                               => ([Inline],[[Block]])
-                              -> MediaWikiWriter m String
+                              -> MediaWikiWriter m (Doc Text)
 definitionListItemToMediaWiki (label, items) = do
+  modify $ \st -> st{ stInDefLabel = True }
   labelText <- inlineListToMediaWiki label
+  modify $ \st -> st{ stInDefLabel = False }
   contents <- mapM blockListToMediaWiki items
   tags <- asks useTags
   if tags
-     then return $ "<dt>" ++ labelText ++ "</dt>\n" ++
-           intercalate "\n" (map (\d -> "<dd>" ++ d ++ "</dd>") contents)
+     then return $ literal "<dt>" <> chomp labelText <> literal "</dt>" <> cr <>
+           vcat (map (\d -> literal "<dd>" <> chomp d <> literal "</dd>") contents)
      else do
        marker <- asks listLevel
-       return $ marker ++ " " ++ labelText ++ "\n" ++
-           intercalate "\n" (map (\d -> init marker ++ ": " ++ d) contents)
+       return $ literal (T.pack marker) <> space <> chomp labelText <> cr <>
+           vcat (map (\d -> literal (T.pack (init marker)) <> literal ": " <> chomp d) contents)
 
 -- | True if the list can be handled by simple wiki markup, False if HTML tags will be needed.
 isSimpleList :: Block -> Bool
@@ -275,178 +297,242 @@
 isPlainOrPara (Para  _) = True
 isPlainOrPara _         = False
 
--- | Concatenates strings with line breaks between them.
-vcat :: [String] -> String
-vcat = intercalate "\n"
-
 -- Auxiliary functions for tables:
 
-tableRowToMediaWiki :: PandocMonad m
-                    => Bool
-                    -> [Alignment]
-                    -> [Double]
-                    -> (Int, [[Block]])
-                    -> MediaWikiWriter m String
-tableRowToMediaWiki headless alignments widths (rownum, cells) = do
-  cells' <- mapM (tableCellToMediaWiki headless rownum)
-          $ zip3 alignments widths cells
-  return $ unlines cells'
+tableToMediaWiki :: PandocMonad m => Ann.Table -> MediaWikiWriter m (Doc Text)
+tableToMediaWiki (Ann.Table attr capt _ thead tbodies tfoot) = do
+    let (ident,classes,kvs) = attr
+    caption <- case capt of
+        Caption _ [] -> return mempty
+        Caption _ longCapt -> do
+            c <- blockListToMediaWiki longCapt
+            return $ literal "|+ " <> chomp c <> cr
+    head' <- tableHeadToMW thead
+    bodies' <- mconcat <$> mapM tableBodyToMW tbodies
+    foot' <- tableFootToMW tfoot
+    return $ literal "{|" <> htmlAttrs (ident, "wikitable":classes, kvs) <> cr
+             <> caption <> head' <> bodies' <> foot'
+             <> literal "|}" <> blankline
 
-tableCellToMediaWiki :: PandocMonad m
-                     => Bool
-                     -> Int
-                     -> (Alignment, Double, [Block])
-                     -> MediaWikiWriter m String
-tableCellToMediaWiki headless rownum (alignment, width, bs) = do
-  contents <- blockListToMediaWiki bs
-  let marker = if rownum == 1 && not headless then "!" else "|"
-  let percent w = show (truncate (100*w) :: Integer) ++ "%"
-  let attrs = ["align=" ++ show (alignmentToString alignment) |
-                 alignment /= AlignDefault && alignment /= AlignLeft] ++
-              ["width=\"" ++ percent width ++ "\"" |
-                 width /= 0.0 && rownum == 1]
-  let attr = if null attrs
-                then ""
-                else unwords attrs ++ "|"
-  let sep = case bs of
-                 [Plain _] -> " "
-                 [Para  _] -> " "
-                 _         -> "\n"
-  return $ marker ++ attr ++ sep ++ trimr contents
+tableHeadToMW :: PandocMonad m => Ann.TableHead -> MediaWikiWriter m (Doc Text)
+tableHeadToMW (Ann.TableHead _ rows) = headerRowsToMW rows
 
-alignmentToString :: Alignment -> String
-alignmentToString alignment = case alignment of
-                                 AlignLeft    -> "left"
-                                 AlignRight   -> "right"
-                                 AlignCenter  -> "center"
-                                 AlignDefault -> "left"
+tableFootToMW :: PandocMonad m => Ann.TableFoot -> MediaWikiWriter m (Doc Text)
+tableFootToMW (Ann.TableFoot _ rows) = headerRowsToMW rows
 
-imageToMediaWiki :: PandocMonad m => Attr -> MediaWikiWriter m String
+tableBodyToMW :: PandocMonad m => Ann.TableBody -> MediaWikiWriter m (Doc Text)
+tableBodyToMW (Ann.TableBody _ _ headerRows bodyRows) = do
+  headerRows' <- headerRowsToMW headerRows
+  bodyRows' <- bodyRowsToMW bodyRows
+  return $ headerRows' <> bodyRows'
+
+headerRowsToMW :: PandocMonad m => [Ann.HeaderRow] -> MediaWikiWriter m (Doc Text)
+headerRowsToMW rows = mconcat <$> mapM headerRowToMW rows
+
+headerRowToMW :: PandocMonad m => Ann.HeaderRow -> MediaWikiWriter m (Doc Text)
+headerRowToMW (Ann.HeaderRow attr _ cells) = do
+  cells' <- mconcat <$> mapM (cellToMW "!") cells
+  return $ literal "|-" <> htmlAttrs attr <> cr <> cells'
+
+bodyRowsToMW :: PandocMonad m => [Ann.BodyRow] -> MediaWikiWriter m (Doc Text)
+bodyRowsToMW rows = mconcat <$> mapM bodyRowToMW rows
+
+bodyRowToMW :: PandocMonad m => Ann.BodyRow -> MediaWikiWriter m (Doc Text)
+bodyRowToMW (Ann.BodyRow attr _ headCells bodyCells) = do
+  headCells' <- mconcat <$> mapM (cellToMW "!") headCells
+  bodyCells' <- mconcat <$> mapM (cellToMW "|") bodyCells
+  return $ literal "|-" <> htmlAttrs attr <> cr <> headCells' <> bodyCells'
+
+cellToMW :: PandocMonad m => Text -> Ann.Cell -> MediaWikiWriter m (Doc Text)
+cellToMW marker (Ann.Cell (colSpec :| _) _ (Cell attr align rowspan colspan content)) = do
+  content' <- blockListToMediaWiki content
+  let (ident,classes,keyVals) = attr
+
+  let align' = case align of
+        AlignDefault -> fst colSpec
+        _            -> align
+  let keyVals' = case (htmlAlignmentToString align') of
+                  Nothing -> keyVals
+                  Just alignStr -> htmlAddStyle ("text-align", alignStr) keyVals
+  let rowspan' = case rowspan of
+                  RowSpan 1 -> mempty
+                  RowSpan n -> [("rowspan", T.pack(show n))]
+  let colspan' = case colspan of
+                  ColSpan 1 -> mempty
+                  ColSpan n -> [("colspan", T.pack(show n))]
+  let attrs' = htmlAttrs (ident, classes, rowspan' <> colspan' <> keyVals')
+  let attrsRendered = render Nothing attrs'
+  let pipeAttr = if T.null attrsRendered then mempty else attrs' <> literal "|"
+  let contentRendered = render Nothing content'
+  let spaceContent = if T.null contentRendered then mempty else space <> chomp content'
+  return $ literal marker <> pipeAttr <> spaceContent <> cr
+
+imageToMediaWiki :: PandocMonad m => Attr -> MediaWikiWriter m Text
 imageToMediaWiki attr = do
   opts <- gets stOptions
   let (_, cls, _) = attr
       toPx = fmap (showInPixel opts) . checkPct
       checkPct (Just (Percent _)) = Nothing
       checkPct maybeDim           = maybeDim
-      go (Just w) Nothing  = '|':w ++ "px"
-      go (Just w) (Just h) = '|':w ++ "x" ++ h ++ "px"
-      go Nothing  (Just h) = "|x" ++ h ++ "px"
+      go (Just w) Nothing  = w <> "px"
+      go (Just w) (Just h) = w <> "x" <> h <> "px"
+      go Nothing  (Just h) = "x" <> h <> "px"
       go Nothing  Nothing  = ""
       dims = go (toPx $ dimension Width attr) (toPx $ dimension Height attr)
       classes = if null cls
                    then ""
-                   else "|class=" ++ unwords cls
-  return $ dims ++ classes
+                   else "class=" <> T.unwords cls
+  return $ T.intercalate "|" $ filter (not . T.null) [dims, classes]
 
 -- | Convert list of Pandoc block elements to MediaWiki.
 blockListToMediaWiki :: PandocMonad m
                      => [Block]       -- ^ List of block elements
-                     -> MediaWikiWriter m String
+                     -> MediaWikiWriter m (Doc Text)
 blockListToMediaWiki blocks =
-  fmap vcat $ mapM blockToMediaWiki blocks
+  vcat <$> mapM blockToMediaWiki blocks
 
 -- | Convert list of Pandoc inline elements to MediaWiki.
-inlineListToMediaWiki :: PandocMonad m => [Inline] -> MediaWikiWriter m String
+inlineListToMediaWiki :: PandocMonad m => [Inline] -> MediaWikiWriter m (Doc Text)
 inlineListToMediaWiki lst =
-  fmap concat $ mapM inlineToMediaWiki lst
+  hcat <$> mapM inlineToMediaWiki (fixup lst)
+    where
+     fixup [] = []
+     fixup (Str t : x : xs)
+       | not (T.null t) && T.last t == '['
+       , isLinkOrImage x =
+          Str t : RawInline (Format "mediawiki") "<nowiki/>" : x : fixup xs
+     fixup (x:xs) = x : fixup xs
+     isLinkOrImage Link{}  = True
+     isLinkOrImage Image{} = True
+     isLinkOrImage _         = False
 
 -- | Convert Pandoc inline element to MediaWiki.
-inlineToMediaWiki :: PandocMonad m => Inline -> MediaWikiWriter m String
+inlineToMediaWiki :: PandocMonad m => Inline -> MediaWikiWriter m (Doc Text)
 
 inlineToMediaWiki (Span attrs ils) = do
   contents <- inlineListToMediaWiki ils
-  return $ render Nothing (tagWithAttrs "span" attrs) ++ contents ++ "</span>"
+  return $ tagWithAttrs "span" attrs <> contents <> literal "</span>"
 
 inlineToMediaWiki (Emph lst) = do
   contents <- inlineListToMediaWiki lst
-  return $ "''" ++ contents ++ "''"
+  return $ literal "''" <> contents <> literal "''"
 
+inlineToMediaWiki (Underline lst) = do
+  contents <- inlineListToMediaWiki lst
+  return $ literal "<u>" <> contents <> literal "</u>"
+
 inlineToMediaWiki (Strong lst) = do
   contents <- inlineListToMediaWiki lst
-  return $ "'''" ++ contents ++ "'''"
+  return $ literal "'''" <> contents <> literal "'''"
 
 inlineToMediaWiki (Strikeout lst) = do
   contents <- inlineListToMediaWiki lst
-  return $ "<s>" ++ contents ++ "</s>"
+  return $ literal "<s>" <> contents <> literal "</s>"
 
 inlineToMediaWiki (Superscript lst) = do
   contents <- inlineListToMediaWiki lst
-  return $ "<sup>" ++ contents ++ "</sup>"
+  return $ literal "<sup>" <> contents <> literal "</sup>"
 
 inlineToMediaWiki (Subscript lst) = do
   contents <- inlineListToMediaWiki lst
-  return $ "<sub>" ++ contents ++ "</sub>"
+  return $ literal "<sub>" <> contents <> literal "</sub>"
 
 inlineToMediaWiki (SmallCaps lst) = inlineListToMediaWiki lst
 
 inlineToMediaWiki (Quoted SingleQuote lst) = do
   contents <- inlineListToMediaWiki lst
-  return $ "\8216" ++ contents ++ "\8217"
+  return $ literal "\8216" <> contents <> literal "\8217"
 
 inlineToMediaWiki (Quoted DoubleQuote lst) = do
   contents <- inlineListToMediaWiki lst
-  return $ "\8220" ++ contents ++ "\8221"
+  return $ literal "\8220" <> contents <> literal "\8221"
 
 inlineToMediaWiki (Cite _  lst) = inlineListToMediaWiki lst
 
 inlineToMediaWiki (Code _ str) =
-  return $ "<code>" ++ escapeString str ++ "</code>"
+  return $ literal $ "<code>" <> escapeText str <> "</code>"
 
-inlineToMediaWiki (Str str) = return $ escapeString str
+inlineToMediaWiki (Str str) = do
+  inDefLabel <- gets stInDefLabel
+  return $ literal $
+    if inDefLabel
+       then T.intercalate "<nowiki>:</nowiki>" $
+              map escapeText $ T.splitOn ":" str
+       else escapeText str
 
-inlineToMediaWiki (Math mt str) = return $
-  "<math display=\"" ++
-  (if mt == DisplayMath then "block" else "inline") ++
-  "\">" ++ str ++ "</math>"
+inlineToMediaWiki (Math mt str) = return $ literal $
+  "<math display=\"" <>
+  (if mt == DisplayMath then "block" else "inline") <>
+  "\">" <> str <> "</math>"
   -- note:  str should NOT be escaped
 
 inlineToMediaWiki il@(RawInline f str)
-  | f == Format "mediawiki" = return str
-  | f == Format "html"      = return str
-  | otherwise               = "" <$ report (InlineNotRendered il)
+  | f == Format "mediawiki" = return $ literal str
+  | f == Format "html"      = return $ literal str
+  | otherwise               = mempty <$ report (InlineNotRendered il)
 
-inlineToMediaWiki LineBreak = return "<br />\n"
+inlineToMediaWiki LineBreak = return $ literal "<br />" <> cr
 
 inlineToMediaWiki SoftBreak = do
   wrapText <- gets (writerWrapText . stOptions)
   listlevel <- asks listLevel
   case wrapText of
-       WrapAuto     -> return " "
-       WrapNone     -> return " "
+       WrapAuto     -> return space
+       WrapNone     -> return space
        WrapPreserve -> if null listlevel
-                          then return "\n"
-                          else return " "
+                          then return cr
+                          else return space
 
-inlineToMediaWiki Space = return " "
+inlineToMediaWiki Space = return space
 
 inlineToMediaWiki (Link _ txt (src, _)) = do
-  label <- inlineListToMediaWiki txt
+  -- We need to remove links from link text, because an <a> element is
+  -- not allowed inside another <a> element.
+  label <- inlineListToMediaWiki (removeLinks txt)
+  let label' = render Nothing label
   case txt of
-     [Str s] | isURI src && escapeURI s == src -> return src
-     _  -> return $ if isURI src
-              then "[" ++ src ++ " " ++ label ++ "]"
-              else "[[" ++ src' ++ "|" ++ label ++ "]]"
-                     where src' = case src of
-                                     '/':xs -> xs  -- with leading / it's a
-                                     _      -> src -- link to a help page
+     [Str s] | isURI src && escapeURI s == src -> return $ literal src
+     _  -> return $ literal $ if isURI (T.takeWhile (/= '#') src) -- see #11562
+       then "[" <> src <> " " <> label' <> "]"
+       else
+         if src == label'
+           then "[[" <> src' <> "]]"
+           else "[[" <> src' <> "|" <> label' <> "]]"
+       -- with leading / it's a link to a help page
+       where src' = fromMaybe src $ T.stripPrefix "/" src
 
 inlineToMediaWiki (Image attr alt (source, tit)) = do
-  img  <- imageToMediaWiki attr
-  alt' <- inlineListToMediaWiki alt
-  let txt = if null tit
-               then if null alt
-                       then ""
-                       else '|' : alt'
-               else '|' : tit
-  return $ "[[File:" ++ source ++ img ++ txt ++ "]]"
+  let separator = "<nowiki></nowiki>"
+  -- External images (URIs) cannot use [[File:...]] syntax;
+  -- they must be rendered as bare URLs. MediaWiki will auto-embed
+  -- them when $wgAllowExternalImages is enabled.
+  if isURI source
+     then return $ literal $ separator <> source <> separator
+     else do
+       img  <- imageToMediaWiki attr
+       alt' <- inlineListToMediaWiki alt
+       let altText = render Nothing alt'
+       let txt = if T.null altText
+                    then if T.null tit
+                            then ""
+                            else tit
+                    else altText
+       return $ literal $ "[[" <>
+                T.intercalate "|"
+                (filter (not . T.null)
+                 [ "File:" <> source
+                 , img
+                 , txt
+                 ]) <> "]]"
 
 inlineToMediaWiki (Note contents) = do
   contents' <- blockListToMediaWiki contents
   modify (\s -> s { stNotes = True })
-  return $ "<ref>" ++ stripTrailingNewlines contents' ++ "</ref>"
+  let rendered = render Nothing contents'
+  return $ literal $ "<ref>" <> stripTrailingNewlines rendered <> "</ref>"
   -- note - does not work for notes with multiple blocks
 
-highlightingLangs :: Set.Set String
+highlightingLangs :: Set.Set Text
 highlightingLangs = Set.fromList [
   "abap",
   "abl",
@@ -630,6 +716,7 @@
   "ex",
   "exs",
   "ezhil",
+  "f#",
   "factor",
   "fan",
   "fancy",
@@ -1076,3 +1163,9 @@
   "yaml",
   "yaml+jinja",
   "zephir" ]
+
+startsWithListMarker :: Text -> Bool
+startsWithListMarker t =
+  case T.uncons t of
+    Nothing -> False
+    Just (c,_) -> c == '#' || c == ':' || c == ';' || c == '*'
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,31 +1,15 @@
-{-
-Copyright (C) 2007-2017 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 OverloadedStrings #-}
+{-# LANGUAGE ViewPatterns      #-}
 {- |
    Module      : Text.Pandoc.Writers.Ms
-   Copyright   : Copyright (C) 2007-2017 John MacFarlane
+   Copyright   : Copyright (C) 2007-2024 John MacFarlane
    License     : GNU GPL, version 2 or above
 
    Maintainer  : John MacFarlane <jgm@berkeley.edu>
    Stability   : alpha
    Portability : portable
 
-Conversion of 'Pandoc' documents to groff ms format.
+Conversion of 'Pandoc' documents to roff ms format.
 
 TODO:
 
@@ -37,317 +21,290 @@
 
 module Text.Pandoc.Writers.Ms ( writeMs ) where
 import Control.Monad.State.Strict
-import Data.Char (isLower, isUpper, toUpper)
-import Data.List (intercalate, intersperse, sort)
+    ( gets, modify, evalStateT )
+import Control.Monad ( MonadPlus(mplus), liftM, unless, forM )
+import Data.Containers.ListUtils (nubOrd)
+import Data.Char (isAscii, isLower, isUpper, ord)
+import Data.List (intercalate, intersperse)
+import Data.List.NonEmpty (nonEmpty)
 import qualified Data.Map as Map
-import Data.Maybe (catMaybes, fromMaybe)
+import Data.Maybe (catMaybes, isNothing)
 import Data.Text (Text)
 import qualified Data.Text as T
 import Network.URI (escapeURIString, isAllowedInURI)
 import Skylighting
 import System.FilePath (takeExtension)
-import Text.Pandoc.Class (PandocMonad, report)
+import Text.Pandoc.Asciify (toAsciiChar)
+import Text.Pandoc.Class.PandocMonad (PandocMonad, report)
 import Text.Pandoc.Definition
 import Text.Pandoc.Highlighting
 import Text.Pandoc.ImageSize
 import Text.Pandoc.Logging
 import Text.Pandoc.Options
-import Text.Pandoc.Pretty
+import Text.DocLayout hiding (Color)
+import Text.DocTemplates (lookupContext)
 import Text.Pandoc.Shared
-import Text.Pandoc.Templates
+import Text.Pandoc.Templates (renderTemplate)
 import Text.Pandoc.Writers.Math
 import Text.Pandoc.Writers.Shared
+import Text.Pandoc.Writers.Roff
+import Text.Pandoc.Writers.Markdown (writePlain)
 import Text.Printf (printf)
 import Text.TeXMath (writeEqn)
-
-data WriterState = WriterState { stHasInlineMath :: Bool
-                               , stFirstPara     :: Bool
-                               , stNotes         :: [Note]
-                               , stSmallCaps     :: Bool
-                               , stHighlighting  :: Bool
-                               , stFontFeatures  :: Map.Map Char Bool
-                               }
-
-defaultWriterState :: WriterState
-defaultWriterState = WriterState{ stHasInlineMath = False
-                                , stFirstPara     = True
-                                , stNotes         = []
-                                , stSmallCaps     = False
-                                , stHighlighting  = False
-                                , stFontFeatures  = Map.fromList [
-                                                       ('I',False)
-                                                     , ('B',False)
-                                                     , ('C',False)
-                                                     ]
-                                }
-
-type Note = [Block]
-
-type MS = StateT WriterState
+import qualified Data.Text.Encoding as TE
+import qualified Data.ByteString as B
 
 -- | Convert Pandoc to Ms.
 writeMs :: PandocMonad m => WriterOptions -> Pandoc -> m Text
 writeMs opts document =
   evalStateT (pandocToMs opts document) defaultWriterState
 
--- | Return groff ms representation of document.
+-- | Return roff ms representation of document.
 pandocToMs :: PandocMonad m => WriterOptions -> Pandoc -> MS m Text
 pandocToMs opts (Pandoc meta blocks) = do
   let colwidth = if writerWrapText opts == WrapAuto
                     then Just $ writerColumns opts
                     else Nothing
-  let render' :: Doc -> Text
-      render' = render colwidth
-  metadata <- metaToJSON opts
-              (fmap render' . blockListToMs opts)
-              (fmap render' . inlineListToMs' opts)
+  title <- chomp <$> inlineListToMs' opts (lookupMetaInlines "title" meta)
+  metadata <- metaToContext opts
+              (blockListToMs opts)
+              (fmap chomp . inlineListToMs' opts)
               meta
-  body <- blockListToMs opts blocks
-  let main = render' body
+  main <- blockListToMs opts blocks
   hasInlineMath <- gets stHasInlineMath
-  let titleMeta = (escapeString . stringify) $ docTitle meta
-  let authorsMeta = map (escapeString . stringify) $ docAuthors meta
+  let titleMeta = (escapeStr opts . stringify) $ docTitle meta
+  let authorsMeta = map (escapeStr opts . stringify) $ docAuthors meta
   hasHighlighting <- gets stHighlighting
   let highlightingMacros = if hasHighlighting
-                              then case writerHighlightStyle opts of
-                                        Nothing  -> mempty
-                                        Just sty -> render' $ styleToMs sty
+                              then case writerHighlightMethod opts of
+                                     Skylighting sty -> styleToMs sty
+                                     _ -> mempty
                               else mempty
 
   let context = defField "body" main
               $ defField "has-inline-math" hasInlineMath
               $ defField "hyphenate" True
-              $ defField "pandoc-version" pandocVersion
               $ defField "toc" (writerTableOfContents opts)
               $ defField "title-meta" titleMeta
-              $ defField "author-meta" (intercalate "; " authorsMeta)
-              $ defField "highlighting-macros" highlightingMacros metadata
-  case writerTemplate opts of
-       Nothing  -> return main
-       Just tpl -> renderTemplate' tpl context
-
--- | Association list of characters to escape.
-msEscapes :: Map.Map Char String
-msEscapes = Map.fromList
-              [ ('\160', "\\~")
-              , ('\'', "\\[aq]")
-              , ('`', "\\`")
-              , ('\8217', "'")
-              , ('"', "\\[dq]")
-              , ('\x2014', "\\[em]")
-              , ('\x2013', "\\[en]")
-              , ('\x2026', "\\&...")
-              , ('~', "\\[ti]")
-              , ('^', "\\[ha]")
-              , ('-', "\\-")
-              , ('@', "\\@")
-              , ('\\', "\\\\")
-              ]
-
-escapeChar :: Char -> String
-escapeChar c = fromMaybe [c] (Map.lookup c msEscapes)
-
--- | Escape | character, used to mark inline math, inside math.
-escapeBar :: String -> String
-escapeBar = concatMap go
-  where go '|' = "\\[u007C]"
-        go c   = [c]
+              $ defField "author-meta" (T.intercalate "; " authorsMeta)
+              $ defField "highlighting-macros" highlightingMacros
+              $ resetField "title" title metadata
+  return $ render colwidth $
+    case writerTemplate opts of
+       Nothing  -> main
+       Just tpl -> renderTemplate tpl context
 
--- | Escape special characters for Ms.
-escapeString :: String -> String
-escapeString = concatMap escapeChar
+escapeStr :: WriterOptions -> Text -> Text
+escapeStr opts =
+  escapeString False (if writerPreferAscii opts then AsciiOnly else AllowUTF8)
 
-escapeUri :: String -> String
-escapeUri = escapeURIString (\c -> c /= '@' && isAllowedInURI c)
+-- In PDFs we need to escape parentheses and backslash.
+-- In PDF we need to encode as UTF-16 BE.
+escapePDFString :: Text -> Text
+escapePDFString t
+  | T.all (\c -> isAscii c && c /= '(' && c /= ')' && c /= '\\' && c /= '"') t = t
+  | otherwise = ("\\376\\377" <>) .  -- add bom
+    mconcat . map encodeChar .  T.unpack $ t
+ where
+  encodeChar c =
+    if isAscii c && c /= '\\' && c /= '(' && c /= ')'
+       then "\\000" <> T.singleton c
+       else mconcat . map toOctal . B.unpack . TE.encodeUtf16BE $ T.singleton c
+  toOctal n = "\\" <> T.pack (printf "%03o" n)
 
-toSmallCaps :: String -> String
-toSmallCaps [] = []
-toSmallCaps (c:cs)
-  | isLower c = let (lowers,rest) = span isLower (c:cs)
-                in  "\\s-2" ++ escapeString (map toUpper lowers) ++
-                    "\\s0" ++ toSmallCaps rest
-  | isUpper c = let (uppers,rest) = span isUpper (c:cs)
-                in  escapeString uppers ++ toSmallCaps rest
-  | otherwise = escapeChar c ++ toSmallCaps cs
+escapeUri :: Text -> Text
+escapeUri = T.pack . escapeURIString (\c -> c /= '@' && isAllowedInURI c) . T.unpack
 
--- | Escape a literal (code) section for Ms.
-escapeCode :: String -> String
-escapeCode = intercalate "\n" . map escapeLine . lines
-  where escapeCodeChar ' '  = "\\ "
-        escapeCodeChar '\t' = "\\\t"
-        escapeCodeChar c    = escapeChar c
-        escapeLine codeline =
-          case concatMap escapeCodeChar codeline of
-            a@('.':_) -> "\\&" ++ a
-            b         -> b
+toSmallCaps :: WriterOptions -> Text -> Text
+toSmallCaps opts s = case T.uncons s of
+  Nothing -> ""
+  Just (c, cs)
+    | isLower c -> let (lowers,rest) = T.span isLower s
+                   in  "\\s-2" <> escapeStr opts (T.toUpper lowers) <>
+                       "\\s0" <> toSmallCaps opts rest
+    | isUpper c -> let (uppers,rest) = T.span isUpper s
+                   in  escapeStr opts uppers <> toSmallCaps opts rest
+    | otherwise -> escapeStr opts (T.singleton c) <> toSmallCaps opts cs
 
 -- We split inline lists into sentences, and print one sentence per
--- line.  groff/troff treats the line-ending period differently.
+-- line.  roff treats the line-ending period differently.
 -- See http://code.google.com/p/pandoc/issues/detail?id=148.
 
--- | Returns the first sentence in a list of inlines, and the rest.
-breakSentence :: [Inline] -> ([Inline], [Inline])
-breakSentence [] = ([],[])
-breakSentence xs =
-  let isSentenceEndInline (Str ys@(_:_)) | last ys == '.' = True
-      isSentenceEndInline (Str ys@(_:_)) | last ys == '?' = True
-      isSentenceEndInline LineBreak      = True
-      isSentenceEndInline _              = False
-      (as, bs) = break isSentenceEndInline xs
-  in  case bs of
-           []             -> (as, [])
-           [c]            -> (as ++ [c], [])
-           (c:Space:cs)   -> (as ++ [c], cs)
-           (c:SoftBreak:cs) -> (as ++ [c], cs)
-           (Str ".":Str (')':ys):cs) -> (as ++ [Str ".", Str (')':ys)], cs)
-           (x@(Str ('.':')':_)):cs) -> (as ++ [x], cs)
-           (LineBreak:x@(Str ('.':_)):cs) -> (as ++[LineBreak], x:cs)
-           (c:cs)         -> (as ++ [c] ++ ds, es)
-              where (ds, es) = breakSentence cs
-
--- | Split a list of inlines into sentences.
-splitSentences :: [Inline] -> [[Inline]]
-splitSentences xs =
-  let (sent, rest) = breakSentence xs
-  in  if null rest then [sent] else sent : splitSentences rest
+getPdfEngine :: WriterOptions -> Maybe Text
+getPdfEngine opts = lookupContext "pdf-engine" (writerVariables opts)
 
 blockToMs :: PandocMonad m
           => WriterOptions -- ^ Options
           -> Block         -- ^ Block element
-          -> MS m Doc
-blockToMs _ Null = return empty
-blockToMs opts (Div _ bs) = do
-  setFirstPara
-  res <- blockListToMs opts bs
-  setFirstPara
-  return res
+          -> MS m (Doc Text)
+blockToMs opts (Div (ident,cls,kvs) bs) = do
+  let anchor = if isNothing (getPdfEngine opts) || T.null ident
+                  then empty
+                  else nowrap $
+                         literal ".pdfhref M "
+                         <> doubleQuotes (literal (toAscii ident))
+  case cls of
+    _ | "csl-entry" `elem` cls ->
+       (".CSLENTRY" $$) . vcat <$> mapM (cslEntryToMs True opts) bs
+      | "csl-bib-body" `elem` cls -> do
+       res <- blockListToMs opts bs
+       return $ anchor $$
+                -- so that XP paragraphs are indented:
+                ".nr PI 3n" $$
+                -- space between entries
+                ".de CSLENTRY" $$
+                (case lookup "entry-spacing" kvs >>= safeRead of
+                   Just n | n > (0 :: Int) -> ".sp"
+                   _ -> mempty) $$
+                ".." $$
+                ".de CSLP" $$
+                (if "hanging-indent" `elem` cls
+                    then ".XP"
+                    else ".LP") $$
+                ".." $$
+                res
+    _ -> do
+       setFirstPara
+       res <- blockListToMs opts bs
+       setFirstPara
+       return $ anchor $$ res
 blockToMs opts (Plain inlines) =
-  liftM vcat $ mapM (inlineListToMs' opts) $ splitSentences inlines
-blockToMs opts (Para [Image attr alt (src,_tit)])
-  | let ext = takeExtension src in (ext == ".ps" || ext == ".eps") = do
-  let (mbW,mbH) = (inPoints opts <$> dimension Width attr,
-                   inPoints opts <$> dimension Height attr)
-  let sizeAttrs = case (mbW, mbH) of
-                       (Just wp, Nothing) -> space <> doubleQuotes
-                              (text (show (floor wp :: Int) ++ "p"))
-                       (Just wp, Just hp) -> space <> doubleQuotes
-                              (text (show (floor wp :: Int) ++ "p")) <>
-                              space <>
-                              doubleQuotes (text (show (floor hp :: Int)))
-                       _ -> empty
-  capt <- inlineListToMs' opts alt
-  return $ nowrap (text ".PSPIC -C " <>
-             doubleQuotes (text (escapeString src)) <>
-             sizeAttrs) $$
-           text ".ce 1000" $$
-           capt $$
-           text ".ce 0"
+  splitSentences <$> inlineListToMs' opts inlines
 blockToMs opts (Para inlines) = do
   firstPara <- gets stFirstPara
   resetFirstPara
-  contents <- liftM vcat $ mapM (inlineListToMs' opts) $
-    splitSentences inlines
-  return $ text (if firstPara then ".LP" else ".PP") $$ contents
+  contents <- inlineListToMs' opts inlines
+  return $ literal (if firstPara then ".LP" else ".PP") $$
+           splitSentences contents
 blockToMs _ b@(RawBlock f str)
-  | f == Format "ms" = return $ text str
+  | f == Format "ms" = return $ literal str
   | otherwise        = do
       report $ BlockNotRendered b
       return empty
 blockToMs _ HorizontalRule = do
   resetFirstPara
-  return $ text ".HLINE"
+  return $ literal ".HLINE"
 blockToMs opts (Header level (ident,classes,_) inlines) = do
   setFirstPara
-  contents <- inlineListToMs' opts $ map breakToSpace inlines
+  modify $ \st -> st{ stInHeader = True }
+  let inlines' = map breakToSpace inlines
+  contents <- inlineListToMs' opts inlines'
+  plainContents <- inlinesToPlain inlines'
+  modify $ \st -> st{ stInHeader = False }
   let (heading, secnum) = if writerNumberSections opts &&
                               "unnumbered" `notElem` classes
                              then (".NH", "\\*[SN]")
                              else (".SH", "")
-  let anchor = if null ident
+  let mbPdfEngine = getPdfEngine opts
+  let anchor = if T.null ident
                   then empty
                   else nowrap $
-                         text ".pdfhref M " <> doubleQuotes (text ident)
-  let bookmark = text ".pdfhref O " <> text (show level ++ " ") <>
-                      doubleQuotes (text $ secnum ++
-                                      (if null secnum
+                         literal ".pdfhref M "
+                         <> doubleQuotes (literal (toAscii ident))
+  let bookmark = literal ".pdfhref O " <> literal (tshow level <> " ") <>
+                      nowrap (doubleQuotes
+                              (literal $ secnum <>
+                                      (if T.null secnum
                                           then ""
-                                          else "  ") ++
-                                      escapeString (stringify inlines))
-  let backlink = nowrap (text ".pdfhref L -D " <>
-       doubleQuotes (text ident) <> space <> text "\\") <> cr <>
-       text " -- "
+                                          else "  ") <>
+                                      (case mbPdfEngine of
+                                         Just "groff" -> id
+                                         _ -> escapePDFString)
+                                        plainContents))
+  let backlink = nowrap (literal ".pdfhref L -D " <>
+       doubleQuotes (literal (toAscii ident)) <> space <> literal "\\") <> cr <>
+       literal " -- "
   let tocEntry = if writerTableOfContents opts &&
                      level <= writerTOCDepth opts
-                    then text ".XS"
+                    then literal ".XS"
                          $$ backlink <> doubleQuotes (
-                            nowrap (text (replicate level '\t') <>
-                             (if null secnum
+                            nowrap (literal (T.replicate level "\t") <>
+                             (if T.null secnum
                                  then empty
-                                 else text secnum <> text "\\~\\~")
+                                 else literal secnum <> literal "\\~\\~")
                               <> contents))
-                         $$ text ".XE"
+                         $$ literal ".XE"
                     else empty
   modify $ \st -> st{ stFirstPara = True }
-  return $ (text heading <> space <> text (show level)) $$
+  return $ (literal heading <> space <> literal (tshow level)) $$
            contents $$
-           bookmark $$
-           anchor $$
-           tocEntry
+           case mbPdfEngine of
+             Nothing -> mempty
+             Just _ -> bookmark $$ anchor $$ tocEntry
 blockToMs opts (CodeBlock attr str) = do
   hlCode <- highlightCode opts attr str
   setFirstPara
   return $
-    text ".IP" $$
-    text ".nf" $$
-    text "\\f[C]" $$
-    hlCode $$
-    text "\\f[]" $$
-    text ".fi"
+    literal ".IP" $$
+    literal ".nf" $$
+    literal "\\f[C]" $$
+    ((case T.uncons str of
+      Just ('.',_) -> literal "\\&"
+      _            -> mempty) <> hlCode) $$
+    literal "\\f[]" $$
+    literal ".fi"
 blockToMs opts (LineBlock ls) = do
-  resetFirstPara
+  setFirstPara  -- use .LP, see #5588
   blockToMs opts $ Para $ intercalate [LineBreak] ls
 blockToMs opts (BlockQuote blocks) = do
   setFirstPara
   contents <- blockListToMs opts blocks
   setFirstPara
-  return $ text ".RS" $$ contents $$ text ".RE"
-blockToMs opts (Table caption alignments widths headers rows) =
-  let aligncode AlignLeft    = "l"
+  return $ literal ".QS" $$ contents $$ literal ".QE"
+blockToMs opts (Table _ blkCapt specs thead tbody tfoot) =
+  let (caption, alignments, widths, headers, rows) = toLegacyTable blkCapt specs thead tbody tfoot
+      aligncode AlignLeft    = "l"
       aligncode AlignRight   = "r"
       aligncode AlignCenter  = "c"
       aligncode AlignDefault = "l"
   in do
   caption' <- inlineListToMs' opts caption
-  let iwidths = if all (== 0) widths
-                   then repeat ""
-                   else map (printf "w(%0.1fn)" . (70 *)) widths
+  let isSimple = all (== 0) widths
+  let totalWidth = 70
   -- 78n default width - 8n indent = 70n
-  let coldescriptions = text $ unwords
-                        (zipWith (\align width -> aligncode align ++ width)
-                        alignments iwidths) ++ "."
+  let coldescriptions = literal $ T.unwords
+                        (zipWith (\align width -> aligncode align <>
+                                    if width == 0
+                                       then ""
+                                       else T.pack $
+                                              printf "w(%0.1fn)"
+                                              (totalWidth * width))
+                        alignments widths) <> "."
   colheadings <- mapM (blockListToMs opts) headers
-  let makeRow cols = text "T{" $$
-                     vcat (intersperse (text "T}\tT{") cols) $$
-                     text "T}"
+  let makeRow cols = literal "T{" $$
+                     vcat (intersperse (literal "T}\tT{") cols) $$
+                     literal "T}"
   let colheadings' = if all null headers
                         then empty
                         else makeRow colheadings $$ char '_'
   body <- mapM (\row -> do
-                         cols <- mapM (blockListToMs opts) row
+                         cols <- mapM (\(cell, w) ->
+                                   (if isSimple
+                                       then id
+                                       else (literal (".nr LL " <>
+                                              T.pack (printf "%0.1fn"
+                                                (w * totalWidth))) $$)) <$>
+                                   blockListToMs opts cell) (zip row widths)
                          return $ makeRow cols) rows
   setFirstPara
-  return $ text ".PP" $$ caption' $$
-           text ".TS" $$ text "delim(@@) tab(\t);" $$ coldescriptions $$
-           colheadings' $$ vcat body $$ text ".TE"
-
+  return $ literal ".PP" $$ caption' $$
+           literal ".na" $$ -- we don't want justification in table cells
+           (if isSimple
+               then ""
+               else ".nr LLold \\n[LL]") $$
+           literal ".TS" $$ literal "delim(@@) tab(\t);" $$ coldescriptions $$
+           colheadings' $$ vcat body $$ literal ".TE" $$
+           (if isSimple
+               then ""
+               else ".nr LL \\n[LLold]") $$
+           literal ".ad"
 blockToMs opts (BulletList items) = do
   contents <- mapM (bulletListItemToMs opts) items
   setFirstPara
   return (vcat contents)
 blockToMs opts (OrderedList attribs items) = do
   let markers = take (length items) $ orderedListMarkers attribs
-  let indent = 2 +
-                     maximum (map length markers)
+  let indent = 2 + maybe 0 maximum (nonEmpty (map T.length markers))
   contents <- mapM (\(num, item) -> orderedListItemToMs opts num indent item) $
               zip markers items
   setFirstPara
@@ -356,53 +313,73 @@
   contents <- mapM (definitionListItemToMs opts) items
   setFirstPara
   return (vcat contents)
+blockToMs opts (Figure figattr (Caption _ caption) body) =
+  case body of
+    [Plain [ Image attr _alt (src, _tit) ]] -> do
+       let ext = takeExtension (T.unpack src)
+       let sizeAttrs = getSizeAttrs opts attr
+       capt <- blockToMs opts (Div figattr caption)
+       let captlines = height capt
+       let cmd = case ext of
+                   ".ps" -> ".PSPIC"
+                   ".eps" -> ".PSPIC"
+                   ".pdf" -> ".PDFPIC"
+                   _ -> "\\\" .IMAGE"
+       return $ nowrap (literal cmd <+>
+                    doubleQuotes (literal src) <>
+                    sizeAttrs) $$
+                  literal (".ce " <> tshow captlines) $$
+                  capt $$
+                  literal ".sp 1"
+    _ -> blockToMs opts $ Div figattr body
 
 -- | Convert bullet list item (list of blocks) to ms.
-bulletListItemToMs :: PandocMonad m => WriterOptions -> [Block] -> MS m Doc
+bulletListItemToMs :: PandocMonad m => WriterOptions -> [Block] -> MS m (Doc Text)
 bulletListItemToMs _ [] = return empty
 bulletListItemToMs opts (Para first:rest) =
   bulletListItemToMs opts (Plain first:rest)
 bulletListItemToMs opts (Plain first:rest) = do
   first' <- blockToMs opts (Plain first)
   rest' <- blockListToMs opts rest
-  let first'' = text ".IP \\[bu] 3" $$ first'
+  let first'' = literal ".IP \\(bu 3" $$ first'
   let rest''  = if null rest
                    then empty
-                   else text ".RS 3" $$ rest' $$ text ".RE"
+                   else literal ".RS 3" $$ rest' $$ literal ".RE"
   return (first'' $$ rest'')
 bulletListItemToMs opts (first:rest) = do
   first' <- blockToMs opts first
   rest' <- blockListToMs opts rest
-  return $ text "\\[bu] .RS 3" $$ first' $$ rest' $$ text ".RE"
+  return $ literal "\\(bu .RS 3" $$ first' $$ rest' $$ literal ".RE"
 
 -- | Convert ordered list item (a list of blocks) to ms.
 orderedListItemToMs :: PandocMonad m
                     => WriterOptions -- ^ options
-                    -> String   -- ^ order marker for list item
+                    -> Text   -- ^ order marker for list item
                     -> Int      -- ^ number of spaces to indent
                     -> [Block]  -- ^ list item (list of blocks)
-                    -> MS m Doc
+                    -> MS m (Doc Text)
 orderedListItemToMs _ _ _ [] = return empty
 orderedListItemToMs opts num indent (Para first:rest) =
   orderedListItemToMs opts num indent (Plain first:rest)
 orderedListItemToMs opts num indent (first:rest) = do
   first' <- blockToMs opts first
   rest' <- blockListToMs opts rest
-  let num' = printf ("%" ++ show (indent - 1) ++ "s") num
-  let first'' = text (".IP \"" ++ num' ++ "\" " ++ show indent) $$ first'
+  let num' = T.pack $ printf ("%" <> show (indent - 1) <> "s") num
+  let first'' = literal (".IP \"" <> num' <> "\" " <> tshow indent) $$ first'
   let rest''  = if null rest
                    then empty
-                   else text ".RS " <> text (show indent) $$
-                         rest' $$ text ".RE"
+                   else literal ".RS " <> literal (tshow indent) $$
+                         rest' $$ literal ".RE"
   return $ first'' $$ rest''
 
 -- | Convert definition list item (label, list of blocks) to ms.
 definitionListItemToMs :: PandocMonad m
                        => WriterOptions
                        -> ([Inline],[[Block]])
-                       -> MS m Doc
+                       -> MS m (Doc Text)
 definitionListItemToMs opts (label, defs) = do
-  labelText <- inlineListToMs' opts $ map breakToSpace label
+  labelText <- withFontFeature 'B' $
+                 inlineListToMs' opts $ map breakToSpace label
   contents <- if null defs
                  then return empty
                  else liftM vcat $ forM defs $ \blocks -> do
@@ -414,49 +391,52 @@
                         rest' <- liftM vcat $
                                   mapM (\item -> blockToMs opts item) rest
                         first' <- blockToMs opts first
-                        return $ first' $$ text ".RS" $$ rest' $$ text ".RE"
-  return $ nowrap (text ".IP " <> doubleQuotes labelText) $$ contents
+                        return $ first' $$ literal ".RS 3" $$ rest' $$ literal ".RE"
+  return $ nowrap (literal ".IP " <> doubleQuotes labelText <> " 3") $$
+           contents
 
 -- | Convert list of Pandoc block elements to ms.
 blockListToMs :: PandocMonad m
               => WriterOptions -- ^ Options
               -> [Block]       -- ^ List of block elements
-              -> MS m Doc
+              -> MS m (Doc Text)
 blockListToMs opts blocks =
-  mapM (blockToMs opts) blocks >>= (return . vcat)
+  vcat <$> mapM (blockToMs opts) blocks
 
 -- | Convert list of Pandoc inline elements to ms.
-inlineListToMs :: PandocMonad m => WriterOptions -> [Inline] -> MS m Doc
+inlineListToMs :: PandocMonad m => WriterOptions -> [Inline] -> MS m (Doc Text)
 -- if list starts with ., insert a zero-width character \& so it
 -- won't be interpreted as markup if it falls at the beginning of a line.
 inlineListToMs opts lst = hcat <$> mapM (inlineToMs opts) lst
 
 -- This version to be used when there is no further inline content;
 -- forces a note at the end.
-inlineListToMs' :: PandocMonad m => WriterOptions -> [Inline] -> MS m Doc
+inlineListToMs' :: PandocMonad m => WriterOptions -> [Inline] -> MS m (Doc Text)
 inlineListToMs' opts lst = do
   x <- hcat <$> mapM (inlineToMs opts) lst
   y <- handleNotes opts empty
   return $ x <> y
 
 -- | Convert Pandoc inline element to ms.
-inlineToMs :: PandocMonad m => WriterOptions -> Inline -> MS m Doc
+inlineToMs :: PandocMonad m => WriterOptions -> Inline -> MS m (Doc Text)
 inlineToMs opts (Span _ ils) = inlineListToMs opts ils
 inlineToMs opts (Emph lst) =
   withFontFeature 'I' (inlineListToMs opts lst)
+inlineToMs opts (Underline lst) =
+  inlineToMs opts (Emph lst)
 inlineToMs opts (Strong lst) =
   withFontFeature 'B' (inlineListToMs opts lst)
 inlineToMs opts (Strikeout lst) = do
   contents <- inlineListToMs opts lst
   -- we use grey color instead of strikeout, which seems quite
-  -- hard to do in groff for arbitrary bits of text
-  return $ text "\\m[strikecolor]" <> contents <> text "\\m[]"
+  -- hard to do in roff for arbitrary bits of text
+  return $ literal "\\m[strikecolor]" <> contents <> literal "\\m[]"
 inlineToMs opts (Superscript lst) = do
   contents <- inlineListToMs opts lst
-  return $ text "\\*{" <> contents <> text "\\*}"
+  return $ literal "\\*{" <> contents <> literal "\\*}"
 inlineToMs opts (Subscript lst) = do
   contents <- inlineListToMs opts lst
-  return $ text "\\*<" <> contents <> text "\\*>"
+  return $ literal "\\*<" <> contents <> literal "\\*>"
 inlineToMs opts (SmallCaps lst) = do
   -- see https://lists.gnu.org/archive/html/groff/2015-01/msg00016.html
   modify $ \st -> st{ stSmallCaps = not (stSmallCaps st) }
@@ -468,40 +448,40 @@
   return $ char '`' <> contents <> char '\''
 inlineToMs opts (Quoted DoubleQuote lst) = do
   contents <- inlineListToMs opts lst
-  return $ text "\\[lq]" <> contents <> text "\\[rq]"
+  return $ literal "\\(lq" <> contents <> literal "\\(rq"
 inlineToMs opts (Cite _ lst) =
   inlineListToMs opts lst
 inlineToMs opts (Code attr str) = do
   hlCode <- highlightCode opts attr str
   withFontFeature 'C' (return hlCode)
-inlineToMs _ (Str str) = do
-  let shim = case str of
-                  '.':_ -> afterBreak "\\&"
-                  _     -> empty
+inlineToMs opts (Str str) = do
+  let shim = case T.uncons str of
+                  Just ('.',_) -> afterBreak "\\&"
+                  _            -> empty
   smallcaps <- gets stSmallCaps
   if smallcaps
-     then return $ shim <> text (toSmallCaps str)
-     else return $ shim <> text (escapeString str)
+     then return $ shim <> literal (toSmallCaps opts str)
+     else return $ shim <> literal (escapeStr opts str)
 inlineToMs opts (Math InlineMath str) = do
   modify $ \st -> st{ stHasInlineMath = True }
   res <- convertMath writeEqn InlineMath str
   case res of
        Left il -> inlineToMs opts il
-       Right r -> return $ text "@" <> text (escapeBar r) <> text "@"
+       Right r -> return $ literal "@" <> literal r <> literal "@"
 inlineToMs opts (Math DisplayMath str) = do
-  res <- convertMath writeEqn InlineMath str
+  res <- convertMath writeEqn DisplayMath str
   case res of
        Left il -> do
          contents <- inlineToMs opts il
-         return $ cr <> text ".RS" $$ contents $$ text ".RE"
+         return $ cr <> literal ".RS 3" $$ contents $$ literal ".RE"
        Right r -> return $
-            cr <> text ".EQ" $$ text (escapeBar r) $$ text ".EN"
+            cr <> literal ".EQ" $$ literal r $$ literal ".EN" <> cr
 inlineToMs _ il@(RawInline f str)
-  | f == Format "ms" = return $ text str
+  | f == Format "ms" = return $ literal str
   | otherwise        = do
     report $ InlineNotRendered il
     return empty
-inlineToMs _ LineBreak = return $ cr <> text ".br" <> cr
+inlineToMs _ LineBreak = return $ cr <> literal ".br" <> cr
 inlineToMs opts SoftBreak =
   handleNotes opts $
     case writerWrapText opts of
@@ -509,28 +489,80 @@
          WrapNone     -> space
          WrapPreserve -> cr
 inlineToMs opts Space = handleNotes opts space
-inlineToMs opts (Link _ txt ('#':ident, _)) = do
+inlineToMs opts (Link _ txt (T.uncons -> Just ('#',ident), _)) = do
   -- internal link
   contents <- inlineListToMs' opts $ map breakToSpace txt
-  return $ text "\\c" <> cr <> nowrap (text ".pdfhref L -D " <>
-       doubleQuotes (text ident) <> text " -A " <>
-       doubleQuotes (text "\\c") <> space <> text "\\") <> cr <>
-       text " -- " <> doubleQuotes (nowrap contents) <> cr <> text "\\&"
+  return $
+    case getPdfEngine opts of
+      Just _ -> literal "\\c" <> cr <> nowrap (literal ".pdfhref L -D " <>
+            doubleQuotes (literal (toAscii ident)) <> literal " -A " <>
+            doubleQuotes (literal "\\c") <> space <> literal "\\") <> cr <>
+            literal " -- " <> doubleQuotes (nowrap contents) <> cr <>
+            literal "\\&"
+      Nothing -> contents
 inlineToMs opts (Link _ txt (src, _)) = do
   -- external link
   contents <- inlineListToMs' opts $ map breakToSpace txt
-  return $ text "\\c" <> cr <> nowrap (text ".pdfhref W -D " <>
-       doubleQuotes (text (escapeUri src)) <> text " -A " <>
-       doubleQuotes (text "\\c") <> space <> text "\\") <> cr <>
-       text " -- " <> doubleQuotes (nowrap contents) <> cr <> text "\\&"
-inlineToMs _ (Image _ alternate (_, _)) =
-  return $ char '[' <> text "IMAGE: " <>
-           text (escapeString (stringify alternate)) <> char ']'
+  return $
+    case getPdfEngine opts of
+      Just _ -> literal "\\c" <> cr <> nowrap (literal ".pdfhref W -D " <>
+            doubleQuotes (literal (escapeUri src)) <> literal " -A " <>
+            doubleQuotes (literal "\\c") <> space <> literal "\\") <> cr <>
+            literal " -- " <> doubleQuotes (nowrap contents) <> cr <>
+            literal "\\&"
+      Nothing -> contents
+inlineToMs opts (Image attr alternate (src, _)) = do
+  let desc = literal "[IMAGE: " <>
+             literal (escapeStr opts (stringify alternate)) <> char ']'
+  let sizeAttrs = getSizeAttrs opts attr
+  let ext = takeExtension (T.unpack src)
+  let cmd = case ext of
+             ".ps" -> ".PSPIC"
+             ".eps" -> ".PSPIC"
+             ".pdf" -> ".PDFPIC"
+             _ -> ""
+  return $ cr <> nowrap
+    (if T.null cmd
+        then desc <> " \\\" " <> doubleQuotes (literal src) <> sizeAttrs
+        else literal cmd <+> doubleQuotes (literal src) <> sizeAttrs) <> cr
 inlineToMs _ (Note contents) = do
   modify $ \st -> st{ stNotes = contents : stNotes st }
-  return $ text "\\**"
+  return $ literal "\\**"
 
-handleNotes :: PandocMonad m => WriterOptions -> Doc -> MS m Doc
+cslEntryToMs :: PandocMonad m
+             => Bool
+             -> WriterOptions
+             -> Block
+             -> MS m (Doc Text)
+cslEntryToMs atStart opts (Para xs) =
+  case xs of
+    (Span ("",["csl-left-margin"],[]) lils :
+      rest@(Span ("",["csl-right-inline"],[]) _ : _))
+      -> do lils' <- inlineListToMs' opts lils
+            ((cr <> literal ".IP " <>
+              doubleQuotes (nowrap lils') <>
+              literal " 5") $$)
+                <$> cslEntryToMs False opts (Para rest)
+    (Span ("",["csl-block"],[]) ils : rest)
+      -> ((cr <> literal ".LP") $$)
+                <$> cslEntryToMs False opts (Para (ils ++ rest))
+    (Span ("",["csl-left-margin"],[]) ils : rest)
+      -> ((cr <> literal ".LP") $$)
+              <$> cslEntryToMs False opts (Para (ils ++ rest))
+    (Span ("",["csl-indented"],[]) ils : rest)
+      -> ((cr <> literal ".LP") $$)
+              <$> cslEntryToMs False opts (Para (ils ++ rest))
+    _ | atStart
+         -> (".CSLP" $$) <$> cslEntryToMs False opts (Para xs)
+      | otherwise
+         -> case xs of
+           [] -> return mempty
+           (x:rest) -> (<>) <$> inlineToMs opts x
+                            <*> cslEntryToMs False opts (Para rest)
+cslEntryToMs _ opts x = blockToMs opts x
+
+
+handleNotes :: PandocMonad m => WriterOptions -> Doc Text -> MS m (Doc Text)
 handleNotes opts fallback = do
   notes <- gets stNotes
   if null notes
@@ -539,7 +571,7 @@
        modify $ \st -> st{ stNotes = [] }
        vcat <$> mapM (handleNote opts) notes
 
-handleNote :: PandocMonad m => WriterOptions -> Note -> MS m Doc
+handleNote :: PandocMonad m => WriterOptions -> Note -> MS m (Doc Text)
 handleNote opts bs = do
   -- don't start with Paragraph or we'll get a spurious blank
   -- line after the note ref:
@@ -547,22 +579,7 @@
                  (Para ils : rest) -> Plain ils : rest
                  _                 -> bs
   contents <- blockListToMs opts bs'
-  return $ cr <> text ".FS" $$ contents $$ text ".FE" <> cr
-
-fontChange :: PandocMonad m => MS m Doc
-fontChange = do
-  features <- gets stFontFeatures
-  let filling = sort [c | (c,True) <- Map.toList features]
-  return $ text $ "\\f[" ++ filling ++ "]"
-
-withFontFeature :: PandocMonad m => Char -> MS m Doc -> MS m Doc
-withFontFeature c action = do
-  modify $ \st -> st{ stFontFeatures = Map.adjust not c $ stFontFeatures st }
-  begin <- fontChange
-  d <- action
-  modify $ \st -> st{ stFontFeatures = Map.adjust not c $ stFontFeatures st }
-  end <- fontChange
-  return $ begin <> d <> end
+  return $ cr <> literal ".FS" $$ contents $$ literal ".FE" <> cr
 
 setFirstPara :: PandocMonad m => MS m ()
 setFirstPara = modify $ \st -> st{ stFirstPara = True }
@@ -577,63 +594,90 @@
 
 -- Highlighting
 
-styleToMs :: Style -> Doc
-styleToMs sty = vcat $ colordefs ++ map (toMacro sty) alltoktypes
+styleToMs :: Style -> Doc Text
+styleToMs sty = vcat $ colordefs <> map (toMacro sty) alltoktypes
   where alltoktypes = enumFromTo KeywordTok NormalTok
         colordefs = map toColorDef allcolors
-        toColorDef c = text (".defcolor " ++
-            hexColor c ++ " rgb #" ++ hexColor c)
-        allcolors = catMaybes $ ordNub $
+        toColorDef c = literal (".defcolor " <>
+            hexColor c <> " rgb #" <> hexColor c)
+        allcolors = catMaybes $ nubOrd $
           [defaultColor sty, backgroundColor sty,
-           lineNumberColor sty, lineNumberBackgroundColor sty] ++
+           lineNumberColor sty, lineNumberBackgroundColor sty] <>
            concatMap (colorsForToken. snd) (Map.toList (tokenStyles sty))
         colorsForToken ts = [tokenColor ts, tokenBackground ts]
 
-hexColor :: Color -> String
-hexColor (RGB r g b) = printf "%02x%02x%02x" r g b
+hexColor :: Color -> Text
+hexColor (RGB r g b) = T.pack $ printf "%02x%02x%02x" r g b
 
-toMacro :: Style -> TokenType -> Doc
+toMacro :: Style -> TokenType -> Doc Text
 toMacro sty toktype =
-  nowrap (text ".ds " <> text (show toktype) <> text " " <>
+  nowrap (literal ".ds " <> literal (tshow toktype) <> literal " \\&" <>
             setbg <> setcolor <> setfont <>
-            text "\\\\$1" <>
+            literal "\\\\$1" <>
             resetfont <> resetcolor <> resetbg)
   where setcolor = maybe empty fgcol tokCol
-        resetcolor = maybe empty (const $ text "\\\\m[]") tokCol
+        resetcolor = maybe empty (const $ literal "\\\\m[]") tokCol
         setbg = empty -- maybe empty bgcol tokBg
         resetbg = empty -- maybe empty (const $ text "\\\\M[]") tokBg
-        fgcol c = text $ "\\\\m[" ++ hexColor c ++ "]"
-        -- bgcol c = text $ "\\\\M[" ++ hexColor c ++ "]"
+        fgcol c = literal $ "\\\\m[" <> hexColor c <> "]"
+        -- bgcol c = literal $ "\\\\M[" <> hexColor c <> "]"
         setfont = if tokBold || tokItalic
-                     then text $ "\\\\f[C" ++ ['B' | tokBold] ++
-                          ['I' | tokItalic] ++ "]"
+                     then literal $ T.pack $ "\\\\f[C" <> ['B' | tokBold] <>
+                          ['I' | tokItalic] <> "]"
                      else empty
         resetfont = if tokBold || tokItalic
-                       then text "\\\\f[C]"
+                       then literal "\\\\f[C]"
                        else empty
         tokSty = Map.lookup toktype (tokenStyles sty)
         tokCol = (tokSty >>= tokenColor) `mplus` defaultColor sty
         -- tokBg  = (tokSty >>= tokenBackground) `mplus` backgroundColor sty
-        tokBold = fromMaybe False (tokenBold <$> tokSty)
-        tokItalic = fromMaybe False (tokenItalic <$> tokSty)
+        tokBold = maybe False tokenBold tokSty
+        tokItalic = maybe False tokenItalic tokSty
         -- tokUnderline = fromMaybe False (tokSty >>= tokUnderline)
         -- lnColor = lineNumberColor sty
         -- lnBkgColor = lineNumberBackgroundColor sty
 
-msFormatter :: FormatOptions -> [SourceLine] -> Doc
-msFormatter _fmtopts =
-  vcat . map fmtLine
-  where fmtLine = hcat . map fmtToken
-        fmtToken (toktype, tok) = text "\\*" <>
-           brackets (text (show toktype) <> text " \""
-             <> text (escapeCode (T.unpack tok)) <> text "\"")
+msFormatter :: WriterOptions -> FormatOptions -> [SourceLine] -> Doc Text
+msFormatter opts _fmtopts =
+  literal . T.intercalate "\n" . map fmtLine
+ where
+  fmtLine = mconcat . map fmtToken
+  fmtToken (toktype, tok) =
+    "\\*[" <> tshow toktype <> " \"" <> escapeStr opts tok <> "\"]"
 
-highlightCode :: PandocMonad m => WriterOptions -> Attr -> String -> MS m Doc
+highlightCode :: PandocMonad m => WriterOptions -> Attr -> Text -> MS m (Doc Text)
 highlightCode opts attr str =
-  case highlight (writerSyntaxMap opts) msFormatter attr str of
+  case highlight (writerSyntaxMap opts) (msFormatter opts) attr str of
          Left msg -> do
-           unless (null msg) $ report $ CouldNotHighlight msg
-           return $ text (escapeCode str)
+           unless (T.null msg) $ report $ CouldNotHighlight msg
+           return $ literal (escapeStr opts str)
          Right h -> do
            modify (\st -> st{ stHighlighting = True })
            return h
+
+-- This is used for PDF anchors.
+toAscii :: Text -> Text
+toAscii = T.concatMap
+  (\c -> case toAsciiChar c of
+              Nothing -> "_u" <> tshow (ord c) <> "_"
+              Just '/' -> "_u" <> tshow (ord c) <> "_" -- see #4515
+              Just c' -> T.singleton c')
+
+getSizeAttrs :: WriterOptions -> Attr -> Doc Text
+getSizeAttrs opts attr =
+  case (mbW, mbH) of
+     (Just wp, Nothing) -> space <> doubleQuotes
+            (literal (tshow (floor wp :: Int) <> "p"))
+     (Just wp, Just hp) -> space <> doubleQuotes
+            (literal (tshow (floor wp :: Int) <> "p"))
+            <> space <>
+            doubleQuotes
+             (literal (tshow (floor hp :: Int) <> "p"))
+     _ -> empty
+ where
+  mbW = inPoints opts <$> dimension Width attr
+  mbH = inPoints opts <$> dimension Height attr
+
+inlinesToPlain :: PandocMonad m => [Inline] -> m Text
+inlinesToPlain ils = T.strip <$> writePlain def{ writerWrapText = WrapNone }
+                                    (Pandoc nullMeta [Plain ils])
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,25 +1,8 @@
 {-# LANGUAGE OverloadedStrings #-}
-{-
-Copyright (C) 2017 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
--}
-
+{-# LANGUAGE ViewPatterns      #-}
 {- |
    Module      : Text.Pandoc.Writers.Muse
-   Copyright   : Copyright (C) 2017 Alexander Krotov
+   Copyright   : Copyright (C) 2017-2020 Alexander Krotov
    License     : GNU GPL, version 2 or above
 
    Maintainer  : Alexander Krotov <ilabdsf@gmail.com>
@@ -42,83 +25,122 @@
 even though it is supported only in Emacs Muse.
 -}
 module Text.Pandoc.Writers.Muse (writeMuse) where
+import Control.Monad (zipWithM)
+import Control.Monad.Except (throwError)
+import Control.Monad.Reader
+    ( asks, MonadReader(local), ReaderT(runReaderT) )
 import Control.Monad.State.Strict
+    ( StateT, gets, modify, evalStateT )
+import Data.Char (isAlphaNum, isAsciiLower, isAsciiUpper, isDigit, isSpace)
+import Data.Default
+import Data.List (intersperse, transpose)
+import Data.List.NonEmpty (nonEmpty, NonEmpty(..))
+import qualified Data.Set as Set
+import qualified Data.Text as T
 import Data.Text (Text)
-import Data.List (intersperse, transpose, isInfixOf)
 import System.FilePath (takeExtension)
-import Text.Pandoc.Class (PandocMonad)
+import Text.Pandoc.Class.PandocMonad (PandocMonad)
 import Text.Pandoc.Definition
+import Text.Pandoc.Error
+import Text.Pandoc.ImageSize
 import Text.Pandoc.Options
-import Text.Pandoc.Pretty
+import Text.DocLayout
 import Text.Pandoc.Shared
-import Text.Pandoc.Templates (renderTemplate')
+import Text.Pandoc.URI
+import Text.Pandoc.Templates (renderTemplate)
 import Text.Pandoc.Writers.Math
 import Text.Pandoc.Writers.Shared
-import qualified Data.Set as Set
 
 type Notes = [[Block]]
+
+type Muse m = ReaderT WriterEnv (StateT WriterState m)
+
+data WriterEnv =
+  WriterEnv { envOptions               :: WriterOptions
+            , envTopLevel              :: Bool
+            , envInsideBlock           :: Bool
+            , envInlineStart           :: Bool -- ^ True if there is only whitespace since last newline
+            , envInsideLinkDescription :: Bool -- ^ Escape ] if True
+            , envAfterSpace            :: Bool -- ^ There is whitespace (not just newline) before
+            , envOneLine               :: Bool -- ^ True if newlines are not allowed
+            , envInsideAsterisks       :: Bool -- ^ True if outer element is emphasis with asterisks
+            , envNearAsterisks         :: Bool -- ^ Rendering inline near asterisks
+            }
+
 data WriterState =
-  WriterState { stNotes       :: Notes
-              , stOptions     :: WriterOptions
-              , stTopLevel    :: Bool
-              , stInsideBlock :: Bool
-              , stIds         :: Set.Set String
+  WriterState { stNotes   :: Notes
+              , stNoteNum :: Int
+              , stIds     :: Set.Set Text
+              , stUseTags :: Bool -- ^ Use tags for emphasis, for example because previous character is a letter
               }
 
+instance Default WriterState
+  where def = WriterState { stNotes = []
+                          , stNoteNum = 1
+                          , stIds = Set.empty
+                          , stUseTags = False
+                          }
+
+evalMuse :: PandocMonad m => Muse m a -> WriterEnv -> WriterState -> m a
+evalMuse document env = evalStateT $ runReaderT document env
+
 -- | Convert Pandoc to Muse.
 writeMuse :: PandocMonad m
           => WriterOptions
           -> Pandoc
           -> m Text
 writeMuse opts document =
-  let st = WriterState { stNotes = []
-                       , stOptions = opts
-                       , stTopLevel = True
-                       , stInsideBlock = False
-                       , stIds = Set.empty
-                       }
-  in evalStateT (pandocToMuse document) st
+  evalMuse (pandocToMuse document) env def
+  where env = WriterEnv { envOptions = opts
+                        , envTopLevel = True
+                        , envInsideBlock = False
+                        , envInlineStart = True
+                        , envInsideLinkDescription = False
+                        , envAfterSpace = False
+                        , envOneLine = False
+                        , envInsideAsterisks = False
+                        , envNearAsterisks = False
+                        }
 
 -- | Return Muse representation of document.
 pandocToMuse :: PandocMonad m
              => Pandoc
-             -> StateT WriterState m Text
+             -> Muse m Text
 pandocToMuse (Pandoc meta blocks) = do
-  opts <- gets stOptions
+  opts <- asks envOptions
   let colwidth = if writerWrapText opts == WrapAuto
                     then Just $ writerColumns opts
                     else Nothing
-  let render' :: Doc -> Text
-      render' = render Nothing
-  metadata <- metaToJSON opts
-               (fmap render' . blockListToMuse)
-               (fmap render' . inlineListToMuse)
+  metadata <- metaToContext opts
+               blockListToMuse
+               (fmap chomp . inlineListToMuse)
                meta
   body <- blockListToMuse blocks
-  notes <- liftM (reverse . stNotes) get >>= notesToMuse
-  let main = render colwidth $ body $+$ notes
+  notes <- currentNotesToMuse
+  let main = body $+$ notes
   let context = defField "body" main metadata
-  case writerTemplate opts of
-       Nothing  -> return main
-       Just tpl -> renderTemplate' tpl context
+  return $ render colwidth $
+    case writerTemplate opts of
+       Nothing  -> main
+       Just tpl -> renderTemplate tpl context
 
 -- | Helper function for flatBlockListToMuse
 -- | Render all blocks and insert blank lines between the first two
 catWithBlankLines :: PandocMonad m
                   => [Block]       -- ^ List of block elements
                   -> Int           -- ^ Number of blank lines
-                  -> StateT WriterState m Doc
+                  -> Muse m (Doc Text)
 catWithBlankLines (b : bs) n = do
-  b' <- blockToMuse b
+  b' <- blockToMuseWithNotes b
   bs' <- flatBlockListToMuse bs
   return $ b' <> blanklines n <> bs'
 catWithBlankLines _ _ = error "Expected at least one block"
 
 -- | Convert list of Pandoc block elements to Muse
--- | without setting stTopLevel.
+-- | without setting envTopLevel.
 flatBlockListToMuse :: PandocMonad m
                 => [Block]       -- ^ List of block elements
-                -> StateT WriterState m Doc
+                -> Muse m (Doc Text)
 flatBlockListToMuse bs@(BulletList _ : BulletList _ : _) = catWithBlankLines bs 2
 flatBlockListToMuse bs@(OrderedList (_, style1, _) _ : OrderedList (_, style2, _) _ : _) =
   catWithBlankLines bs (if style1' == style2' then 2 else 0)
@@ -126,49 +148,61 @@
       style1' = normalizeStyle style1
       style2' = normalizeStyle style2
       normalizeStyle DefaultStyle = Decimal
-      normalizeStyle s = s
+      normalizeStyle s            = s
 flatBlockListToMuse bs@(DefinitionList _ : DefinitionList _ : _) = catWithBlankLines bs 2
 flatBlockListToMuse bs@(_ : _) = catWithBlankLines bs 0
 flatBlockListToMuse [] = return mempty
 
+simpleTable :: PandocMonad m
+            => [Inline]
+            -> [[Block]]
+            -> [[[Block]]]
+            -> Muse m (Doc Text)
+simpleTable caption headers rows = do
+  topLevel <- asks envTopLevel
+  caption' <- inlineListToMuse caption
+  headers' <- mapM blockListToMuse headers
+  rows' <- mapM (mapM blockListToMuse) rows
+  let widthsInChars = maybe 0 maximum . nonEmpty . map offset <$>
+                       transpose (headers' : rows')
+  let hpipeBlocks sep blocks = hcat $ intersperse sep' blocks
+        where sep' = lblock (T.length sep) $ literal sep
+  let makeRow sep = hpipeBlocks sep . zipWith lblock widthsInChars
+  let head' = makeRow " || " headers'
+  rows'' <- mapM (\row -> makeRow rowSeparator <$> mapM blockListToMuse row) rows
+  let body = vcat rows''
+  return $ (if topLevel then nest 1 else id) ((if noHeaders then empty else head')
+                                             $$ body
+                                             $$ (if null caption then empty else "|+ " <> caption' <> " +|"))
+         $$ blankline
+  where noHeaders = all null headers
+        rowSeparator = if noHeaders then " | " else " |  "
+
 -- | Convert list of Pandoc block elements to Muse.
 blockListToMuse :: PandocMonad m
                 => [Block]       -- ^ List of block elements
-                -> StateT WriterState m Doc
-blockListToMuse blocks = do
-  oldState <- get
-  modify $ \s -> s { stTopLevel = not $ stInsideBlock s
-                   , stInsideBlock = True
-                   }
-  result <- flatBlockListToMuse blocks
-  modify $ \s -> s { stTopLevel = stTopLevel oldState
-                   , stInsideBlock = stInsideBlock oldState
-                   }
-  return result
+                -> Muse m (Doc Text)
+blockListToMuse =
+  local (\env -> env { envTopLevel = not (envInsideBlock env)
+                     , envInsideBlock = True
+                     }) . flatBlockListToMuse
 
 -- | Convert Pandoc block element to Muse.
 blockToMuse :: PandocMonad m
             => Block         -- ^ Block element
-            -> StateT WriterState m Doc
-blockToMuse (Plain inlines) = inlineListToMuse inlines
+            -> Muse m (Doc Text)
+blockToMuse (Plain inlines) = inlineListToMuse' inlines
 blockToMuse (Para inlines) = do
-  contents <- inlineListToMuse inlines
+  contents <- inlineListToMuse' inlines
   return $ contents <> blankline
 blockToMuse (LineBlock lns) = do
-  let splitStanza [] = []
-      splitStanza xs = case break (== mempty) xs of
-        (l, [])  -> [l]
-        (l, _:r) -> l : splitStanza r
-  let joinWithLinefeeds  = nowrap . mconcat . intersperse cr
-  let joinWithBlankLines = mconcat . intersperse blankline
-  let prettyfyStanza ls  = joinWithLinefeeds <$> mapM inlineListToMuse ls
-  contents <- joinWithBlankLines <$> mapM prettyfyStanza (splitStanza lns)
-  return $ blankline $$ "<verse>" $$ contents $$ "</verse>" <> blankline
+  lns' <- local (\env -> env { envOneLine = True }) $ mapM inlineListToMuse lns
+  return $ nowrap $ vcat (map (literal "> " <>) lns') <> blankline
 blockToMuse (CodeBlock (_,_,_) str) =
-  return $ "<example>" $$ text str $$ "</example>" $$ blankline
+  return $ "<example>" $$ literal str $$ "</example>" $$ blankline
 blockToMuse (RawBlock (Format format) str) =
-  return $ blankline $$ "<literal style=\"" <> text format <> "\">" $$
-           text str $$ "</literal>" $$ blankline
+  return $ blankline $$ "<literal style=\"" <> literal format <> "\">" $$
+           literal str $$ "</literal>" $$ blankline
 blockToMuse (BlockQuote blocks) = do
   contents <- flatBlockListToMuse blocks
   return $ blankline
@@ -179,225 +213,520 @@
 blockToMuse (OrderedList (start, style, _) items) = do
   let markers = take (length items) $ orderedListMarkers
                                       (start, style, Period)
-  let maxMarkerLength = maximum $ map length markers
-  let markers' = map (\m -> let s = maxMarkerLength - length m
-                            in  m ++ replicate s ' ') markers
-  contents <- zipWithM orderedListItemToMuse markers' items
-  -- ensure that sublists have preceding blank line
-  topLevel <- gets stTopLevel
-  return $ cr $$ (if topLevel then nest 1 else id) (vcat contents) $$ blankline
+  contents <- zipWithM orderedListItemToMuse markers items
+  topLevel <- asks envTopLevel
+  return $ (if topLevel then nest 1 else id) (vcat contents) $$ blankline
   where orderedListItemToMuse :: PandocMonad m
-                              => String   -- ^ marker for list item
-                              -> [Block]  -- ^ list item (list of blocks)
-                              -> StateT WriterState m Doc
-        orderedListItemToMuse marker item = do
-        contents <- blockListToMuse item
-        return $ hang (length marker + 1) (text marker <> space) contents
+                              => Text     -- marker for list item
+                              -> [Block]  -- list item (list of blocks)
+                              -> Muse m (Doc Text)
+        orderedListItemToMuse marker item = hang (T.length marker + 1) (literal marker <> space)
+          <$> blockListToMuse item
 blockToMuse (BulletList items) = do
   contents <- mapM bulletListItemToMuse items
-  -- ensure that sublists have preceding blank line
-  topLevel <- gets stTopLevel
-  return $ cr $$ (if topLevel then nest 1 else id) (vcat contents) $$ blankline
+  topLevel <- asks envTopLevel
+  return $ (if topLevel then nest 1 else id) (vcat contents) $$ blankline
   where bulletListItemToMuse :: PandocMonad m
                              => [Block]
-                             -> StateT WriterState m Doc
+                             -> Muse m (Doc Text)
         bulletListItemToMuse item = do
-          contents <- blockListToMuse item
-          return $ hang 2 "- " contents
+          modify $ \st -> st { stUseTags = False }
+          hang 2 "- " <$> blockListToMuse item
 blockToMuse (DefinitionList items) = do
   contents <- mapM definitionListItemToMuse items
-  return $ cr $$ nest 1 (vcat contents) $$ blankline
+  topLevel <- asks envTopLevel
+  return $ (if topLevel then nest 1 else id) (vcat contents) $$ blankline
   where definitionListItemToMuse :: PandocMonad m
                                  => ([Inline], [[Block]])
-                                 -> StateT WriterState m Doc
+                                 -> Muse m (Doc Text)
         definitionListItemToMuse (label, defs) = do
-          label' <- inlineListToMuse label
-          contents <- liftM vcat $ mapM blockListToMuse defs
-          let label'' = label' <> " :: "
-          let ind = offset label''
-          return $ hang ind label'' contents
+          modify $ \st -> st { stUseTags = False }
+          label' <- local (\env -> env { envOneLine = True, envAfterSpace = True }) $ inlineListToMuse' label
+          let ind = offset' label' -- using Text.DocLayout.offset results in round trip failures
+          hang ind (nowrap label') . vcat <$> mapM descriptionToMuse defs
+          where offset' d = maximum (0 :| map T.length
+                                         (T.lines $ render Nothing d))
+        descriptionToMuse :: PandocMonad m
+                          => [Block]
+                          -> Muse m (Doc Text)
+        descriptionToMuse desc = hang 4 " :: " <$> blockListToMuse desc
 blockToMuse (Header level (ident,_,_) inlines) = do
-  opts <- gets stOptions
-  contents <- inlineListToMuse inlines
-
+  opts <- asks envOptions
+  topLevel <- asks envTopLevel
+  contents <- local (\env -> env { envOneLine = True }) $ inlineListToMuse' inlines
   ids <- gets stIds
-  let autoId = uniqueIdent inlines ids
+  let autoId = uniqueIdent (writerExtensions opts) inlines ids
   modify $ \st -> st{ stIds = Set.insert autoId ids }
 
-  let attr' = if null ident || (isEnabled Ext_auto_identifiers opts && ident == autoId)
+  let attr' = if T.null ident || (isEnabled Ext_auto_identifiers opts && ident == autoId)
                  then empty
-                 else "#" <> text ident <> cr
-  let header' = text $ replicate level '*'
-  return $ blankline <> nowrap (header' <> space <> contents)
-                 $$ attr' <> blankline
+                 else "#" <> literal ident <> cr
+  let header' = if topLevel then literal (T.replicate level "*") <> space else mempty
+  return $ blankline <> attr' $$ nowrap (header' <> contents) <> blankline
 -- https://www.gnu.org/software/emacs-muse/manual/muse.html#Horizontal-Rules-and-Anchors
 blockToMuse HorizontalRule = return $ blankline $$ "----" $$ blankline
-blockToMuse (Table caption _ _ headers rows) =  do
-  caption' <- inlineListToMuse caption
-  headers' <- mapM blockListToMuse headers
-  rows' <- mapM (mapM blockListToMuse) rows
-  let noHeaders = all null headers
+blockToMuse (Table _ blkCapt specs thead@(TableHead hattr hrows) tbody tfoot) =
+  if isSimple && numcols > 1
+    then simpleTable caption headers rows
+    else do
+      opts <- asks envOptions
+      let tbody' = case hrows of
+                     [] -> tbody
+                     _  -> TableBody nullAttr 0 [] hrows : tbody
+      gridTable opts blocksToDoc specs (TableHead hattr []) tbody' tfoot
+  where
+    (caption, aligns, widths, headers, rows) = toLegacyTable blkCapt specs thead tbody tfoot
+    blocksToDoc opts blocks =
+      local (\env -> env { envOptions = opts }) $ blockListToMuse blocks
+    numcols = maximum
+              (length aligns :| length widths : map length (headers:rows))
+    isSimple = onlySimpleTableCells (headers : rows) && all (== 0) widths
+blockToMuse (Div _ bs) = flatBlockListToMuse bs
+blockToMuse (Figure attr capt body) = do
+  blockToMuse (figureDiv attr capt body)
 
-  let numChars = maximum . map offset
-  -- FIXME: width is not being used.
-  let widthsInChars =
-       map numChars $ transpose (headers' : rows')
-  -- FIXME: Muse doesn't allow blocks with height more than 1.
-  let hpipeBlocks sep blocks = hcat $ intersperse sep' blocks
-        where h      = maximum (1 : map height blocks)
-              sep'   = lblock (length sep) $ vcat (replicate h (text sep))
-  let makeRow sep = (" " <>) . hpipeBlocks sep . zipWith lblock widthsInChars
-  let head' = makeRow " || " headers'
-  let rowSeparator = if noHeaders then " | " else " |  "
-  rows'' <- mapM (\row -> do cols <- mapM blockListToMuse row
-                             return $ makeRow rowSeparator cols) rows
-  let body = vcat rows''
-  return $  (if noHeaders then empty else head')
-         $$ body
-         $$ (if null caption then empty else " |+ " <> caption' <> " +|")
-         $$ blankline
-blockToMuse (Div _ bs) = blockListToMuse bs
-blockToMuse Null = return empty
+-- | Return Muse representation of notes collected so far.
+currentNotesToMuse :: PandocMonad m
+                   => Muse m (Doc Text)
+currentNotesToMuse = do
+  notes <- reverse <$> gets stNotes
+  modify $ \st -> st { stNotes = mempty }
+  notesToMuse notes
 
 -- | Return Muse representation of notes.
 notesToMuse :: PandocMonad m
             => Notes
-            -> StateT WriterState m Doc
-notesToMuse notes = liftM vsep (zipWithM noteToMuse [1 ..] notes)
+            -> Muse m (Doc Text)
+notesToMuse notes = do
+  n <- gets stNoteNum
+  modify $ \st -> st { stNoteNum = stNoteNum st + length notes }
+  vsep <$> zipWithM noteToMuse [n ..] notes
 
 -- | Return Muse representation of a note.
 noteToMuse :: PandocMonad m
            => Int
            -> [Block]
-           -> StateT WriterState m Doc
+           -> Muse m (Doc Text)
 noteToMuse num note = do
-  contents <- blockListToMuse note
-  let marker = "[" ++ show num ++ "] "
-  return $ hang (length marker) (text marker) contents
+  res <- hang (T.length marker) (literal marker) <$>
+    local (\env -> env { envInsideBlock = True
+                       , envInlineStart = True
+                       , envAfterSpace = True
+                       }) (blockListToMuse note)
+  return $ res <> blankline
+  where
+    marker = "[" <> tshow num <> "] "
 
+-- | Return Muse representation of block and accumulated notes.
+blockToMuseWithNotes :: PandocMonad m
+                     => Block
+                     -> Muse m (Doc Text)
+blockToMuseWithNotes blk = do
+  topLevel <- asks envTopLevel
+  opts <- asks envOptions
+  let hdrToMuse hdr@Header{} = do
+        b <- blockToMuse hdr
+        if topLevel && writerReferenceLocation opts == EndOfSection
+          then do
+            notes <- currentNotesToMuse
+            return $ notes $+$ b
+          else
+            return b
+      hdrToMuse b = blockToMuse b
+  b <- hdrToMuse blk
+  if topLevel && writerReferenceLocation opts == EndOfBlock
+    then do
+           notes <- currentNotesToMuse
+           return $ b $+$ notes <> blankline
+    else return b
+
 -- | Escape special characters for Muse.
-escapeString :: String -> String
-escapeString s =
-  "<verbatim>" ++
-  substitute "</verbatim>" "<</verbatim><verbatim>/verbatim>" s ++
+escapeText :: Text -> Text
+escapeText s =
+  "<verbatim>" <>
+  T.replace "</verbatim>" "<</verbatim><verbatim>/verbatim>" s <>
   "</verbatim>"
 
+-- | Replace newlines with spaces
+replaceNewlines :: Text -> Text
+replaceNewlines = T.map $ \c ->
+  if c == '\n' then ' ' else c
+
+startsWithMarker :: (Char -> Bool) -> Text -> Bool
+startsWithMarker f t = case T.uncons $ T.dropWhile f' t of
+  Just ('.', xs) -> T.null xs || isSpace (T.head xs)
+  _              -> False
+  where
+    f' c = c == ' ' || f c
+
+containsNotes :: Char -> Char -> Text -> Bool
+containsNotes left right = p . T.unpack -- This ought to be a parser
+  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
+          | otherwise = p xs
+        q [] = False
+        r ('0':xs) = r xs || p xs
+        r xs       = s xs || q xs || p xs
+        s (right':xs)
+          | right' == right = True
+          | otherwise = p xs
+        s []      = False
+
+-- | Return True if string should be escaped with <verbatim> tags
+shouldEscapeText :: PandocMonad m
+                   => Text
+                   -> Muse m Bool
+shouldEscapeText s = do
+  insideLink <- asks envInsideLinkDescription
+  return $ T.null s ||
+           T.any (`elem` ("#*<=|" :: String)) s ||
+           "::" `T.isInfixOf` s ||
+           "~~" `T.isInfixOf` s ||
+           "[[" `T.isInfixOf` s ||
+           ">>>" `T.isInfixOf` s ||
+           ("]" `T.isInfixOf` s && insideLink) ||
+           containsNotes '[' ']' s ||
+           containsNotes '{' '}' s
+
 -- | Escape special characters for Muse if needed.
-conditionalEscapeString :: String -> String
-conditionalEscapeString s =
-  if any (`elem` ("#*<=>[]|" :: String)) s ||
-     "::" `isInfixOf` s ||
-     "----" `isInfixOf` s
-    then escapeString s
-    else s
+conditionalEscapeText :: PandocMonad m
+                        => Text
+                        -> Muse m Text
+conditionalEscapeText s = do
+  shouldEscape <- shouldEscapeText s
+  return $ if shouldEscape
+             then escapeText s
+             else s
 
+-- Expand Math and Cite before normalizing inline list
+preprocessInlineList :: PandocMonad m
+                     => [Inline]
+                     -> m [Inline]
+preprocessInlineList (Math t str:xs) = (++) <$> texMathToInlines t str <*> preprocessInlineList xs
+-- Amusewiki does not support <cite> tag,
+-- and Emacs Muse citation support is limited
+-- (https://www.gnu.org/software/emacs-muse/manual/html_node/Citations.html#Citation)
+-- so just fallback to expanding inlines.
+preprocessInlineList (Cite _  lst:xs) = (lst ++) <$> preprocessInlineList xs
+preprocessInlineList (x:xs) = (x:) <$> preprocessInlineList xs
+preprocessInlineList [] = return []
+
+replaceSmallCaps :: Inline -> Inline
+replaceSmallCaps (SmallCaps lst) = Emph lst
+replaceSmallCaps x               = x
+
+removeKeyValues :: Inline -> Inline
+removeKeyValues (Code (i, cls, _) xs) = Code (i, cls, []) xs
+-- Do not remove attributes from Link
+-- Do not remove attributes, such as "width", from Image
+-- Do not remove attributes, such as "dir", from Span
+removeKeyValues x                     = x
+
 normalizeInlineList :: [Inline] -> [Inline]
+normalizeInlineList (Str "" : xs)
+  = normalizeInlineList xs
+normalizeInlineList (x : Str "" : xs)
+  = normalizeInlineList (x:xs)
+normalizeInlineList (Str x1 : Str x2 : xs)
+  = normalizeInlineList $ Str (x1 <> x2) : xs
 normalizeInlineList (Emph x1 : Emph x2 : ils)
-  = normalizeInlineList $ Emph (x1 ++ x2) : ils
+  = normalizeInlineList $ Emph (x1 <> x2) : ils
 normalizeInlineList (Strong x1 : Strong x2 : ils)
-  = normalizeInlineList $ Strong (x1 ++ x2) : ils
+  = normalizeInlineList $ Strong (x1 <> x2) : ils
 normalizeInlineList (Strikeout x1 : Strikeout x2 : ils)
-  = normalizeInlineList $ Strikeout (x1 ++ x2) : ils
+  = normalizeInlineList $ Strikeout (x1 <> x2) : ils
 normalizeInlineList (Superscript x1 : Superscript x2 : ils)
-  = normalizeInlineList $ Superscript (x1 ++ x2) : ils
+  = normalizeInlineList $ Superscript (x1 <> x2) : ils
 normalizeInlineList (Subscript x1 : Subscript x2 : ils)
-  = normalizeInlineList $ Subscript (x1 ++ x2) : ils
+  = normalizeInlineList $ Subscript (x1 <> x2) : ils
 normalizeInlineList (SmallCaps x1 : SmallCaps x2 : ils)
-  = normalizeInlineList $ SmallCaps (x1 ++ x2) : ils
-normalizeInlineList (Code a1 x1 : Code a2 x2 : ils) | a1 == a2
-  = normalizeInlineList $ Code a1 (x1 ++ x2) : ils
+  = normalizeInlineList $ SmallCaps (x1 <> x2) : ils
+normalizeInlineList (Code _ x1 : Code _ x2 : ils)
+  = normalizeInlineList $ Code nullAttr (x1 <> x2) : ils
 normalizeInlineList (RawInline f1 x1 : RawInline f2 x2 : ils) | f1 == f2
-  = normalizeInlineList $ RawInline f1 (x1 ++ x2) : ils
-normalizeInlineList (Span a1 x1 : Span a2 x2 : ils) | a1 == a2
-  = normalizeInlineList $ Span a1 (x1 ++ x2) : ils
+  = normalizeInlineList $ RawInline f1 (x1 <> x2) : ils
+-- Do not join Span's during normalization
 normalizeInlineList (x:xs) = x : normalizeInlineList xs
 normalizeInlineList [] = []
 
 fixNotes :: [Inline] -> [Inline]
-fixNotes [] = []
-fixNotes (Space : n@Note{} : rest) = Str " " : n : fixNotes rest
+fixNotes []                            = []
+fixNotes (Space : n@Note{} : rest)     = Str " " : n : fixNotes rest
 fixNotes (SoftBreak : n@Note{} : rest) = Str " " : n : fixNotes rest
-fixNotes (x:xs) = x : fixNotes xs
+fixNotes (x:xs)                        = x : fixNotes xs
 
--- | Convert list of Pandoc inline elements to Muse.
+startsWithSpace :: [Inline] -> Bool
+startsWithSpace (Space:_)     = True
+startsWithSpace (SoftBreak:_) = True
+startsWithSpace (Str s:_)     = stringStartsWithSpace s
+startsWithSpace _             = False
+
+endsWithSpace :: [Inline] -> Bool
+endsWithSpace [Space]     = True
+endsWithSpace [SoftBreak] = True
+endsWithSpace [Str s]     = stringEndsWithSpace s
+endsWithSpace (_:xs)      = endsWithSpace xs
+endsWithSpace []          = False
+
+urlEscapeBrackets :: Text -> Text
+urlEscapeBrackets = T.concatMap $ \c -> case c of
+  ']' -> "%5D"
+  _   -> T.singleton c
+
+isHorizontalRule :: Text -> Bool
+isHorizontalRule s = T.length s >= 4 && T.all (== '-') s
+
+stringStartsWithSpace :: Text -> Bool
+stringStartsWithSpace = maybe False (isSpace . fst) . T.uncons
+
+stringEndsWithSpace :: Text -> Bool
+stringEndsWithSpace = maybe False (isSpace . snd) . T.unsnoc
+
+fixOrEscape :: Bool -> Inline -> Bool
+fixOrEscape b (Str s) = fixOrEscapeStr b s
+  where
+    fixOrEscapeStr sp t = case T.uncons t of
+      Just ('-', xs)
+        | T.null xs -> sp
+        | otherwise -> (sp && isSpace (T.head xs)) || isHorizontalRule t
+      Just (';', xs)
+        | T.null xs -> not sp
+        | otherwise -> not sp && isSpace (T.head xs)
+      Just ('>', xs)
+        | T.null xs -> True
+        | otherwise -> isSpace (T.head xs)
+      _             -> (sp && (startsWithMarker isDigit s ||
+                               startsWithMarker isAsciiLower s ||
+                               startsWithMarker isAsciiUpper s))
+                       || stringStartsWithSpace s
+fixOrEscape _ Space = True
+fixOrEscape _ SoftBreak = True
+fixOrEscape _ _ = False
+
+inlineListStartsWithAlnum :: PandocMonad m
+                          => [Inline]
+                          -> Muse m Bool
+inlineListStartsWithAlnum (Str s:_) = do
+  esc <- shouldEscapeText s
+  return $ esc || isAlphaNum (T.head s)
+inlineListStartsWithAlnum _ = return False
+
+-- | Convert list of Pandoc inline elements to Muse
+renderInlineList :: PandocMonad m
+                 => [Inline]
+                 -> Muse m (Doc Text)
+renderInlineList [] = pure ""
+renderInlineList (x:xs) = do
+  start <- asks envInlineStart
+  afterSpace <- asks envAfterSpace
+  topLevel <- asks envTopLevel
+  insideAsterisks <- asks envInsideAsterisks
+  nearAsterisks <- asks envNearAsterisks
+  useTags <- gets stUseTags
+  alnumNext <- inlineListStartsWithAlnum xs
+  let newUseTags = useTags || alnumNext
+  modify $ \st -> st { stUseTags = newUseTags }
+
+  r <- local (\env -> env { envInlineStart = False
+                          , envInsideAsterisks = False
+                          , envNearAsterisks = nearAsterisks || (null xs && insideAsterisks)
+                          }) $ inlineToMuse x
+  opts <- asks envOptions
+  let isNewline = (x == SoftBreak && writerWrapText opts == WrapPreserve) || x == LineBreak
+  lst' <- local (\env -> env { envInlineStart = isNewline
+                             , envAfterSpace = x == Space || (not topLevel && isNewline)
+                             , envNearAsterisks = False
+                             }) $ renderInlineList xs
+  if start && fixOrEscape afterSpace x
+    then pure (literal "<verbatim></verbatim>" <> r <> lst')
+    else pure (r <> lst')
+
+-- | Normalize and convert list of Pandoc inline elements to Muse.
 inlineListToMuse :: PandocMonad m
                  => [Inline]
-                 -> StateT WriterState m Doc
-inlineListToMuse lst = hcat <$> mapM inlineToMuse (fixNotes $ normalizeInlineList lst)
+                 -> Muse m (Doc Text)
+inlineListToMuse lst = do
+  lst' <- normalizeInlineList . fixNotes <$> preprocessInlineList (map (removeKeyValues . replaceSmallCaps) lst)
+  insideAsterisks <- asks envInsideAsterisks
+  start <- asks envInlineStart
+  modify $ \st -> st { stUseTags = False } -- Previous character is likely a '>' or some other markup
+  if start && null lst'
+    then pure "<verbatim></verbatim>"
+    else local (\env -> env { envNearAsterisks = insideAsterisks }) $ renderInlineList lst'
 
+inlineListToMuse' :: PandocMonad m => [Inline] -> Muse m (Doc Text)
+inlineListToMuse' lst = do
+  topLevel <- asks envTopLevel
+  afterSpace <- asks envAfterSpace
+  local (\env -> env { envInlineStart = True
+                     , envAfterSpace = afterSpace || not topLevel
+                     }) $ inlineListToMuse lst
+
+emphasis :: PandocMonad m => Text -> Text -> [Inline] -> Muse m (Doc Text)
+emphasis b e lst = do
+  contents <- local (\env -> env { envInsideAsterisks = inAsterisks }) $ inlineListToMuse lst
+  modify $ \st -> st { stUseTags = useTags }
+  return $ literal b <> contents <> literal e
+  where inAsterisks = T.last b == '*' || T.head e == '*'
+        useTags = T.last e /= '>'
+
 -- | Convert Pandoc inline element to Muse.
 inlineToMuse :: PandocMonad m
              => Inline
-             -> StateT WriterState m Doc
-inlineToMuse (Str str) = return $ text $ conditionalEscapeString str
+             -> Muse m (Doc Text)
+inlineToMuse (Str str) = do
+  escapedStr <- conditionalEscapeText $ replaceNewlines str
+  let useTags = isAlphaNum $ T.last escapedStr -- escapedStr is never empty because empty strings are escaped
+  modify $ \st -> st { stUseTags = useTags }
+  return $ literal escapedStr
+inlineToMuse (Emph [Strong lst]) = do
+  useTags <- gets stUseTags
+  let lst' = normalizeInlineList lst
+  if useTags
+    then emphasis "<em>**" "**</em>" lst'
+    else if null lst' || startsWithSpace lst' || endsWithSpace lst'
+           then emphasis "*<strong>" "</strong>*" lst'
+           else emphasis "***" "***" lst'
 inlineToMuse (Emph lst) = do
+  useTags <- gets stUseTags
+  let lst' = normalizeInlineList lst
+  if useTags || null lst' || startsWithSpace lst' || endsWithSpace lst'
+    then emphasis "<em>" "</em>" lst'
+    else emphasis "*" "*" lst'
+inlineToMuse (Strong [Emph lst]) = do
+  useTags <- gets stUseTags
+  let lst' = normalizeInlineList lst
+  if useTags
+    then emphasis "<strong>*" "*</strong>" lst'
+    else if null lst' || startsWithSpace lst' || endsWithSpace lst'
+           then emphasis "**<em>" "</em>**" lst'
+           else emphasis "***" "***" lst'
+-- Underline is only supported in Emacs Muse mode.
+inlineToMuse (Underline lst) = do
+  opts <- asks envOptions
   contents <- inlineListToMuse lst
-  return $ "<em>" <> contents <> "</em>"
+  if isEnabled Ext_amuse opts
+     then return $ "_" <> contents <> "_"
+     else inlineToMuse (Emph lst)
 inlineToMuse (Strong lst) = do
-  contents <- inlineListToMuse lst
-  return $ "<strong>" <> contents <> "</strong>"
+  useTags <- gets stUseTags
+  let lst' = normalizeInlineList lst
+  if useTags || null lst' || startsWithSpace lst' || endsWithSpace lst'
+    then emphasis "<strong>" "</strong>" lst'
+    else emphasis "**" "**" lst'
 inlineToMuse (Strikeout lst) = do
   contents <- inlineListToMuse lst
+  modify $ \st -> st { stUseTags = False }
   return $ "<del>" <> contents <> "</del>"
 inlineToMuse (Superscript lst) = do
   contents <- inlineListToMuse lst
+  modify $ \st -> st { stUseTags = False }
   return $ "<sup>" <> contents <> "</sup>"
 inlineToMuse (Subscript lst) = do
   contents <- inlineListToMuse lst
+  modify $ \st -> st { stUseTags = False }
   return $ "<sub>" <> contents <> "</sub>"
-inlineToMuse (SmallCaps lst) = inlineListToMuse lst
+inlineToMuse SmallCaps {} =
+  throwError $ PandocShouldNeverHappenError
+    "SmallCaps should be expanded before normalization"
 inlineToMuse (Quoted SingleQuote lst) = do
   contents <- inlineListToMuse lst
-  return $ "'" <> contents <> "'"
+  modify $ \st -> st { stUseTags = False }
+  return $ "‘" <> contents <> "’"
 inlineToMuse (Quoted DoubleQuote lst) = do
   contents <- inlineListToMuse lst
-  return $ "\"" <> contents <> "\""
--- Amusewiki does not support <cite> tag,
--- and Emacs Muse citation support is limited
--- (https://www.gnu.org/software/emacs-muse/manual/html_node/Citations.html#Citation)
--- so just fallback to expanding inlines.
-inlineToMuse (Cite _  lst) = inlineListToMuse lst
-inlineToMuse (Code _ str) = return $
-  "<code>" <> text (substitute "</code>" "<</code><code>/code>" str) <> "</code>"
-inlineToMuse (Math InlineMath str) =
-  lift (texMathToInlines InlineMath str) >>= inlineListToMuse
-inlineToMuse (Math DisplayMath str) = do
-  contents <- lift (texMathToInlines DisplayMath str) >>= inlineListToMuse
-  return $ "<verse>" <> contents <> "</verse>" <> blankline
-inlineToMuse (RawInline (Format f) str) =
-  return $ "<literal style=\"" <> text f <> "\">" <> text str <> "</literal>"
-inlineToMuse LineBreak = return $ "<br>" <> cr
-inlineToMuse Space = return space
+  modify $ \st -> st { stUseTags = False }
+  return $ "“" <> contents <> "”"
+inlineToMuse Cite {} =
+  throwError $ PandocShouldNeverHappenError
+               "Citations should be expanded before normalization"
+inlineToMuse (Code _ str) = do
+  useTags <- gets stUseTags
+  modify $ \st -> st { stUseTags = False }
+  return $ if useTags || T.null str || T.any (== '=') str
+              || isSpace (T.head str) || isSpace (T.last str)
+             then "<code>" <> literal (T.replace "</code>" "<</code><code>/code>" str) <> "</code>"
+             else "=" <> literal str <> "="
+inlineToMuse Math{} =
+  throwError $ PandocShouldNeverHappenError
+    "Math should be expanded before normalization"
+inlineToMuse (RawInline (Format f) str) = do
+  modify $ \st -> st { stUseTags = False }
+  return $ "<literal style=\"" <> literal f <> "\">" <> literal str <> "</literal>"
+inlineToMuse LineBreak = do
+  oneline <- asks envOneLine
+  modify $ \st -> st { stUseTags = False }
+  return $ if oneline then "<br>" else "<br>" <> cr
+inlineToMuse Space = do
+  modify $ \st -> st { stUseTags = False }
+  return space
 inlineToMuse SoftBreak = do
-  wrapText <- gets $ writerWrapText . stOptions
-  return $ if wrapText == WrapPreserve then cr else space
+  oneline <- asks envOneLine
+  wrapText <- asks $ writerWrapText . envOptions
+  modify $ \st -> st { stUseTags = False }
+  return $ if not oneline && wrapText == WrapPreserve then cr else space
 inlineToMuse (Link _ txt (src, _)) =
   case txt of
-        [Str x] | escapeURI x == src ->
-             return $ "[[" <> text (escapeLink x) <> "]]"
-        _ -> do contents <- inlineListToMuse txt
-                return $ "[[" <> text (escapeLink src) <> "][" <> contents <> "]]"
-  where escapeLink lnk = escapeURI (if isImageUrl lnk then "URL:" ++ lnk else lnk)
+        [Str x] | escapeURI x == src -> do
+             modify $ \st -> st { stUseTags = False }
+             return $ "[[" <> literal (escapeLink x) <> "]]"
+        _ -> do contents <- local (\env -> env { envInsideLinkDescription = True }) $ inlineListToMuse txt
+                modify $ \st -> st { stUseTags = False }
+                return $ "[[" <> literal (escapeLink src) <> "][" <> contents <> "]]"
+  where escapeLink lnk = if isImageUrl lnk then "URL:" <> urlEscapeBrackets lnk else urlEscapeBrackets lnk
         -- Taken from muse-image-regexp defined in Emacs Muse file lisp/muse-regexps.el
         imageExtensions = [".eps", ".gif", ".jpg", ".jpeg", ".pbm", ".png", ".tiff", ".xbm", ".xpm"]
-        isImageUrl = (`elem` imageExtensions) . takeExtension
-inlineToMuse (Image attr alt (source,'f':'i':'g':':':title)) =
+        isImageUrl = (`elem` imageExtensions) . takeExtension . T.unpack
+inlineToMuse (Image attr alt (source,T.stripPrefix "fig:" -> Just title)) =
   inlineToMuse (Image attr alt (source,title))
-inlineToMuse (Image _ inlines (source, title)) = do
-  alt <- inlineListToMuse inlines
-  let title' = if null title
-                  then if null inlines
-                          then ""
-                          else "[" <> alt <> "]"
-                  else "[" <> text title <> "]"
-  return $ "[[" <> text source <> "]" <> title' <> "]"
+inlineToMuse (Image attr@(_, classes, _) inlines (source, title)) = do
+  opts <- asks envOptions
+  alt <- local (\env -> env { envInsideLinkDescription = True }) $ inlineListToMuse inlines
+  title' <- if T.null title
+            then if null inlines
+                 then return ""
+                 else return $ "[" <> alt <> "]"
+            else do s <- local (\env -> env { envInsideLinkDescription = True }) $ conditionalEscapeText title
+                    return $ "[" <> literal s <> "]"
+  let width = case dimension Width attr of
+                Just (Percent x) | isEnabled Ext_amuse opts -> " " <> tshow (round x :: Integer)
+                _ -> ""
+  let leftalign = if "align-left" `elem` classes
+                  then " l"
+                  else ""
+  let rightalign = if "align-right" `elem` classes
+                   then " r"
+                   else ""
+  modify $ \st -> st { stUseTags = False }
+  return $ "[[" <> literal (urlEscapeBrackets source <> width <> leftalign <> rightalign) <> "]" <> title' <> "]"
 inlineToMuse (Note contents) = do
   -- add to notes in state
   notes <- gets stNotes
-  modify $ \st -> st { stNotes = contents:notes }
-  let ref = show $ length notes + 1
-  return $ "[" <> text ref <> "]"
-inlineToMuse (Span (_,name:_,_) inlines) = do
+  modify $ \st -> st { stNotes = contents:notes
+                     , stUseTags = False
+                     }
+  n <- gets stNoteNum
+  let ref = tshow $ n + length notes
+  return $ "[" <> literal ref <> "]"
+inlineToMuse (Span (anchor,names,kvs) inlines) = do
   contents <- inlineListToMuse inlines
-  return $ "<class name=\"" <> text name <> "\">" <> contents <> "</class>"
-inlineToMuse (Span _ lst) = inlineListToMuse lst
+  let (contents', hasDir) = case lookup "dir" kvs of
+                              Just "rtl" -> ("<<<" <> contents <> ">>>", True)
+                              Just "ltr" -> (">>>" <> contents <> "<<<", True)
+                              _ -> (contents, False)
+  let anchorDoc = if T.null anchor
+                     then mempty
+                     else literal ("#" <> anchor) <> space
+  modify $ \st -> st { stUseTags = False }
+  return $ anchorDoc <>
+   if null inlines && not (T.null anchor)
+      then mempty
+      else case names of
+             [] | hasDir -> contents'
+                | otherwise -> "<class>" <> contents' <> "</class>"
+             (n:_) -> "<class name=\"" <> literal n <> "\">" <>
+                         contents' <> "</class>"
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,25 +1,6 @@
-{-# LANGUAGE OverloadedStrings #-}
-{-
-Copyright (C) 2006-2017 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-2017 John MacFarlane
+   Copyright   : Copyright (C) 2006-2024 John MacFarlane
    License     : GNU GPL, version 2 or above
 
    Maintainer  : John MacFarlane <jgm@berkeley.edu>
@@ -30,52 +11,20 @@
 -}
 module Text.Pandoc.Writers.Native ( writeNative )
 where
-import Data.List (intersperse)
 import Data.Text (Text)
-import Text.Pandoc.Class (PandocMonad)
+import qualified Data.Text as T
+import Text.Pandoc.Class.PandocMonad (PandocMonad)
 import Text.Pandoc.Definition
-import Text.Pandoc.Options (WrapOption (..), WriterOptions (..))
-import Text.Pandoc.Pretty
-
-prettyList :: [Doc] -> Doc
-prettyList ds =
-  "[" <>
-  cat (intersperse (cr <> ",") $ map (nest 1) ds) <> "]"
-
--- | Prettyprint Pandoc block element.
-prettyBlock :: Block -> Doc
-prettyBlock (LineBlock lines') =
-  "LineBlock" $$ prettyList (map (text . show) lines')
-prettyBlock (BlockQuote blocks) =
-  "BlockQuote" $$ prettyList (map prettyBlock blocks)
-prettyBlock (OrderedList attribs blockLists) =
-  "OrderedList" <> space <> text (show attribs) $$
-  prettyList (map (prettyList . map prettyBlock) blockLists)
-prettyBlock (BulletList blockLists) =
-  "BulletList" $$
-  prettyList (map (prettyList . map prettyBlock) blockLists)
-prettyBlock (DefinitionList items) = "DefinitionList" $$
-  prettyList (map deflistitem items)
-    where deflistitem (term, defs) = "(" <> text (show term) <> "," <> cr <>
-           nest 1 (prettyList $ map (prettyList . map prettyBlock) defs) <> ")"
-prettyBlock (Table caption aligns widths header rows) =
-  "Table " <> text (show caption) <> " " <> text (show aligns) <> " " <>
-  text (show widths) $$
-  prettyRow header $$
-  prettyList (map prettyRow rows)
-    where prettyRow cols = prettyList (map (prettyList . map prettyBlock) cols)
-prettyBlock (Div attr blocks) =
-  text ("Div " <> show attr) $$ prettyList (map prettyBlock blocks)
-prettyBlock block = text $ show block
+import Text.Pandoc.Options (WriterOptions (..))
+import Text.Show.Pretty (ppDoc)
+import Text.PrettyPrint (renderStyle, Style(..), style, char)
 
 -- | Prettyprint Pandoc document.
 writeNative :: PandocMonad m => WriterOptions -> Pandoc -> m Text
-writeNative opts (Pandoc meta blocks) = return $
-  let colwidth = if writerWrapText opts == WrapAuto
-                    then Just $ writerColumns opts
-                    else Nothing
-      withHead = case writerTemplate opts of
-                      Just _  -> \bs -> text ("Pandoc (" ++ show meta ++ ")") $$
-                                  bs $$ cr
-                      Nothing -> id
-  in  render colwidth $ withHead $ prettyList $ map prettyBlock blocks
+writeNative opts (Pandoc meta blocks) = do
+  let style' = style{ lineLength = writerColumns opts,
+                      ribbonsPerLine = 1.2 }
+  return $ T.pack $ renderStyle style' $
+    case writerTemplate opts of
+      Just _  -> ppDoc (Pandoc meta blocks) <> char '\n'
+      Nothing -> ppDoc blocks
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,25 +1,8 @@
 {-# LANGUAGE ScopedTypeVariables #-}
-{-
-Copyright (C) 2008-2017 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 OverloadedStrings   #-}
 {- |
    Module      : Text.Pandoc.Writers.ODT
-   Copyright   : Copyright (C) 2008-2017 John MacFarlane
+   Copyright   : Copyright (C) 2008-2024 John MacFarlane
    License     : GNU GPL, version 2 or above
 
    Maintainer  : John MacFarlane <jgm@berkeley.edu>
@@ -30,33 +13,46 @@
 -}
 module Text.Pandoc.Writers.ODT ( writeODT ) where
 import Codec.Archive.Zip
-import Control.Monad.Except (catchError)
-import Control.Monad.State.Strict
+import Control.Monad.Except (catchError, throwError)
+import Control.Monad.State.Strict (StateT, evalStateT, gets, modify, lift)
+import Control.Monad (MonadPlus(mplus))
 import qualified Data.ByteString.Lazy as B
+import Data.Maybe (fromMaybe)
 import Data.Generics (everywhere', mkT)
 import Data.List (isPrefixOf)
-import Data.Maybe (fromMaybe)
+import qualified Data.Map as Map
+import qualified Data.Text as T
 import qualified Data.Text.Lazy as TL
-import System.FilePath (takeDirectory, takeExtension, (<.>))
-import Text.Pandoc.BCP47 (Lang (..), getLang, renderLang)
-import Text.Pandoc.Class (PandocMonad, report, toLang)
-import qualified Text.Pandoc.Class as P
+import Data.Time
+import System.FilePath (takeDirectory, takeExtension, (<.>), (</>), isAbsolute)
+import Text.Collate.Lang (Lang (..), renderLang)
+import Text.Pandoc.Class.PandocMonad (PandocMonad, report, toLang)
+import qualified Text.Pandoc.Class.PandocMonad as P
+import Text.Pandoc.Data (readDataFile)
 import Text.Pandoc.Definition
+import Text.Pandoc.Error (PandocError(..))
 import Text.Pandoc.ImageSize
 import Text.Pandoc.Logging
 import Text.Pandoc.MIME (extensionFromMimeType, getMimeType)
-import Text.Pandoc.Options (WrapOption (..), WriterOptions (..))
-import Text.Pandoc.Pretty
-import Text.Pandoc.Shared (stringify)
-import Text.Pandoc.UTF8 (fromStringLazy, fromTextLazy, toStringLazy)
+import Text.Pandoc.Options (WrapOption (..), WriterOptions (..),
+                            HighlightMethod(Skylighting))
+import Text.DocLayout
+import Text.Pandoc.Shared (stringify, tshow)
+import Text.Pandoc.Version (pandocVersionText)
+import Text.Pandoc.Writers.Shared (lookupMetaString, lookupMetaBlocks,
+                                   fixDisplayMath, getLang,
+                                   ensureValidXmlIdentifiers)
+import Text.Pandoc.UTF8 (fromStringLazy, fromTextLazy, toTextLazy)
 import Text.Pandoc.Walk
 import Text.Pandoc.Writers.OpenDocument (writeOpenDocument)
-import Text.Pandoc.Writers.Shared (fixDisplayMath)
 import Text.Pandoc.XML
+import Text.Pandoc.XML.Light
 import Text.TeXMath
-import Text.XML.Light
+import qualified Text.XML.Light as XL
+import Network.URI (parseRelativeReference, URI(uriPath), isURI)
+import Skylighting
 
-data ODTState = ODTState { stEntries :: [Entry]
+newtype ODTState = ODTState { stEntries :: [Entry]
                          }
 
 type O m = StateT ODTState m
@@ -69,9 +65,25 @@
 writeODT  opts doc =
   let initState = ODTState{ stEntries = []
                           }
+      doc' = fixInternalLinks . ensureValidXmlIdentifiers $ doc
   in
-    evalStateT (pandocToODT opts doc) initState
+    evalStateT (pandocToODT opts doc') initState
 
+-- | ODT internal links are evaluated relative to an imaginary folder
+-- structure that mirrors the zip structure.  The result is that relative
+-- links in the document need to start with `..`.  See #3524.
+fixInternalLinks :: Pandoc -> Pandoc
+fixInternalLinks = walk go
+ where
+  go (Link attr ils (src,tit)) =
+    Link attr ils (fixRel src,tit)
+  go x = x
+  fixRel uri =
+    case parseRelativeReference (T.unpack uri) of
+      Just u
+        | not (null (uriPath u)) -> tshow $ u{ uriPath = "../" <> uriPath u }
+      _ -> uri
+
 -- | Produce an ODT file from a Pandoc document.
 pandocToODT :: PandocMonad m
             => WriterOptions  -- ^ Writer options
@@ -79,12 +91,15 @@
             -> O m B.ByteString
 pandocToODT opts doc@(Pandoc meta _) = do
   let title = docTitle meta
+  let authors = docAuthors meta
+  utctime <- P.getTimestamp
   lang <- toLang (getLang opts meta)
   refArchive <-
        case writerReferenceDoc opts of
-             Just f -> liftM toArchive $ lift $ P.readFileLazy f
-             Nothing -> lift $ (toArchive . B.fromStrict) <$>
-                                P.readDataFile "reference.odt"
+             Just f -> lift $ toArchive . B.fromStrict . fst <$>
+                                (P.fetchItem (T.pack f))
+             Nothing -> lift $ toArchive . B.fromStrict <$>
+                                readDataFile "reference.odt"
   -- handle formulas and pictures
   -- picEntriesRef <- P.newIORef ([] :: [Entry])
   doc' <- walkM (transformPicMath opts) $ walk fixDisplayMath doc
@@ -100,8 +115,7 @@
                         Nothing  -> empty
                         Just m   -> selfClosingTag "manifest:file-entry"
                                      [("manifest:media-type", m)
-                                     ,("manifest:full-path", fp)
-                                     ,("manifest:version", "1.2")
+                                     ,("manifest:full-path", T.pack fp)
                                      ]
   let files = [ ent | ent <- filesInArchive archive,
                              not ("META-INF" `isPrefixOf` ent) ]
@@ -111,68 +125,181 @@
         $ fromStringLazy $ render Nothing
         $ text "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
         $$
-         (inTags True "manifest:manifest"
+         inTags True "manifest:manifest"
             [("xmlns:manifest","urn:oasis:names:tc:opendocument:xmlns:manifest:1.0")
-            ,("manifest:version","1.2")] ( selfClosingTag "manifest:file-entry"
+            ,("manifest:version","1.3")] ( selfClosingTag "manifest:file-entry"
                  [("manifest:media-type","application/vnd.oasis.opendocument.text")
-                 ,("manifest:full-path","/")]
+                 ,("manifest:full-path","/")
+                 ,("manifest:version", "1.3")]
                 $$ vcat ( map toFileEntry files )
                 $$ vcat ( map toFileEntry formulas )
               )
-         )
   let archive' = addEntryToArchive manifestEntry archive
+  -- create meta.xml
+  let userDefinedMetaFields = [k | k <- Map.keys (unMeta meta)
+                              , k `notElem` ["title", "lang", "author"
+                                           , "description", "subject", "keywords"]]
+  let escapedText = text . T.unpack . escapeStringForXML
+  let keywords = case lookupMeta "keywords" meta of
+                      Just (MetaList xs) -> map stringify xs
+                      _                  -> []
+  let userDefinedMeta =
+        map (\k -> inTags False "meta:user-defined"
+              [ ("meta:name", escapeStringForXML k)
+              ,("meta:value-type", "string")
+              ] (escapedText $ lookupMetaString k meta)) userDefinedMetaFields
+  let metaTag metafield = inTagsSimple metafield . escapedText
   let metaEntry = toEntry "meta.xml" epochtime
        $ fromStringLazy $ render Nothing
        $ text "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
        $$
-        (inTags True "office:document-meta"
+        inTags True "office:document-meta"
            [("xmlns:office","urn:oasis:names:tc:opendocument:xmlns:office:1.0")
            ,("xmlns:xlink","http://www.w3.org/1999/xlink")
            ,("xmlns:dc","http://purl.org/dc/elements/1.1/")
            ,("xmlns:meta","urn:oasis:names:tc:opendocument:xmlns:meta:1.0")
            ,("xmlns:ooo","http://openoffice.org/2004/office")
            ,("xmlns:grddl","http://www.w3.org/2003/g/data-view#")
-           ,("office:version","1.2")] ( inTagsSimple "office:meta" $
-                 ( inTagsSimple "dc:title"
-                      (text $ escapeStringForXML (stringify title))
+           ,("office:version","1.3")] ( inTags True "office:meta" []
+                 ( metaTag "meta:generator" ("Pandoc/" <> pandocVersionText)
                    $$
+                   metaTag "dc:title" (stringify title)
+                   $$
+                   metaTag "dc:description"
+                          (T.intercalate "\n" (map stringify $
+                                         lookupMetaBlocks "description" meta))
+                   $$
+                   metaTag "dc:subject" (lookupMetaString "subject" meta)
+                   $$
+                   metaTag "meta:keyword" (T.intercalate ", " keywords)
+                   $$
                    case lang of
-                        Just l -> inTagsSimple "dc:language"
-                                    (text (escapeStringForXML (renderLang l)))
+                        Just l  -> metaTag "dc:language" (renderLang l)
                         Nothing -> empty
+                   $$
+                   (\d a -> metaTag "meta:initial-creator" a
+                         $$ metaTag "dc:creator" a
+                         $$ metaTag "meta:creation-date" d
+                         $$ metaTag "dc:date" d
+                   ) (T.pack $ formatTime defaultTimeLocale "%FT%XZ" utctime)
+                     (T.intercalate "; " (map stringify authors))
+                   $$
+                   vcat userDefinedMeta
                  )
              )
-        )
   -- make sure mimetype is first
   let mimetypeEntry = toEntry "mimetype" epochtime
                       $ fromStringLazy "application/vnd.oasis.opendocument.text"
-  archive'' <- updateStyleWithLang lang
+  archive'' <- updateStyle opts lang
                   $ addEntryToArchive mimetypeEntry
                   $ addEntryToArchive metaEntry archive'
   return $ fromArchive archive''
 
-updateStyleWithLang :: PandocMonad m => Maybe Lang -> Archive -> O m Archive
-updateStyleWithLang Nothing arch = return arch
-updateStyleWithLang (Just lang) arch = do
+updateStyle :: forall m . PandocMonad m
+            => WriterOptions -> Maybe Lang -> Archive -> O m Archive
+updateStyle opts mbLang arch = do
   epochtime <- floor `fmap` lift P.getPOSIXTime
-  return arch{ zEntries = [if eRelativePath e == "styles.xml"
-                              then case parseXMLDoc
-                                      (toStringLazy (fromEntry e)) of
-                                      Nothing -> e
-                                      Just d ->
-                                        toEntry "styles.xml" epochtime
-                                        ( fromStringLazy
-                                        . ppTopElement
-                                        . addLang lang $ d )
-                              else e
-                            | e <- zEntries arch] }
+  let goEntry :: Entry -> O m Entry
+      goEntry e
+        | eRelativePath e == "styles.xml"
+          = case parseXMLElement (toTextLazy (fromEntry e)) of
+              Left msg -> throwError $ PandocXMLError "styles.xml" msg
+              Right d -> return $
+                toEntry "styles.xml" epochtime
+                ( fromTextLazy
+                . TL.fromStrict
+                . showTopElement
+                . maybe id addLang mbLang
+                . transformElement (\qn -> qName qn == "styles" &&
+                                      qPrefix qn == Just "office" )
+                     (addListItemStyles .
+                      (case writerHighlightMethod opts of
+                        Skylighting style -> addHlStyles style
+                        _ -> id))
+                $ d )
+        | otherwise = pure e
+  entries <- mapM goEntry (zEntries arch)
+  return arch{ zEntries = entries }
 
+addHlStyles :: Style -> Element -> Element
+addHlStyles sty el =
+  el{ elContent = filter (not . isHlStyle) (elContent el) ++
+                styleToOpenDocument sty }
+ where
+   isHlStyle (Elem e) = "Tok" `T.isSuffixOf` (qName (elName e))
+   isHlStyle _ = False
+
+-- | Ensure the office:styles element contains paragraph styles for
+-- list items used by the OpenDocument writer.  This injects only the
+-- styles that are missing, so a user-supplied reference.odt may
+-- override any of them.
+addListItemStyles :: Element -> Element
+addListItemStyles el =
+  el{ elContent = elContent el ++ map Elem missingStyles }
+ where
+   existing = [ T.concat [ attrVal a
+                         | a <- elAttribs e
+                         , qName (attrKey a) == "name"
+                         , qPrefix (attrKey a) == Just "style" ]
+              | Elem e <- elContent el
+              , qName (elName e) == "style"
+              , qPrefix (elName e) == Just "style" ]
+   missingStyles =
+     [ s | s <- listItemStyleElements
+         , styleNameOf s `notElem` existing ]
+   styleNameOf e = T.concat [ attrVal a
+                            | a <- elAttribs e
+                            , qName (attrKey a) == "name"
+                            , qPrefix (attrKey a) == Just "style" ]
+
+listItemStyleElements :: [Element]
+listItemStyleElements =
+  [ mkParaStyle "List_20_Bullet" "List Bullet" Nothing
+  , mkParaStyle "List_20_Bullet_20_Tight" "List Bullet Tight" (Just tightProps)
+  , mkParaStyle "List_20_Number" "List Number" Nothing
+  , mkParaStyle "List_20_Number_20_Tight" "List Number Tight" (Just tightProps)
+  ]
+ where
+   styleQN n p = QName n Nothing (Just p)
+   mkAttr p n v = Attr (styleQN n p) v
+   tightProps =
+     Element (styleQN "paragraph-properties" "style")
+       [ mkAttr "fo" "margin-top" "0in"
+       , mkAttr "fo" "margin-bottom" "0in"
+       , mkAttr "style" "contextual-spacing" "false"
+       ] [] Nothing
+   mkParaStyle name display mbProps =
+     Element (styleQN "style" "style")
+       [ mkAttr "style" "name" name
+       , mkAttr "style" "display-name" display
+       , mkAttr "style" "family" "paragraph"
+       , mkAttr "style" "parent-style-name" "List"
+       , mkAttr "style" "class" "list"
+       ]
+       (maybe [] (\p -> [Elem p]) mbProps)
+       Nothing
+
+-- top-down search
+transformElement :: (QName -> Bool)
+                 -> (Element -> Element)
+                 -> Element
+                 -> Element
+transformElement g f el
+  | g (elName el)
+    = f el
+  | otherwise
+    = el{ elContent = map go (elContent el) }
+ where
+   go (Elem e) = Elem (transformElement g f e)
+   go x = x
+
+-- TODO FIXME avoid this generic traversal!
 addLang :: Lang -> Element -> Element
 addLang lang = everywhere' (mkT updateLangAttr)
     where updateLangAttr (Attr n@(QName "language" _ (Just "fo")) _)
                            = Attr n (langLanguage lang)
           updateLangAttr (Attr n@(QName "country" _ (Just "fo")) _)
-                           = Attr n (langRegion lang)
+                           = Attr n (fromMaybe "" $ langRegion lang)
           updateLangAttr x = x
 
 -- | transform both Image and Math elements
@@ -186,12 +313,12 @@
                          return (100, 100)
        let dims =
              case (getDim Width, getDim Height) of
-               (Just w, Just h)              -> [("width", show w), ("height", show h)]
-               (Just w@(Percent p), Nothing) -> [("width", show w), ("height", show (p / ratio) ++ "%")]
-               (Nothing, Just h@(Percent p)) -> [("width", show (p * ratio) ++ "%"), ("height", show h)]
-               (Just w@(Inch i), Nothing)    -> [("width", show w), ("height", show (i / ratio) ++ "in")]
-               (Nothing, Just h@(Inch i))    -> [("width", show (i * ratio) ++ "in"), ("height", show h)]
-               _                             -> [("width", show ptX ++ "pt"), ("height", show ptY ++ "pt")]
+               (Just w, Just h)              -> [("width", tshow w), ("height", tshow h)]
+               (Just w@(Percent _), Nothing) -> [("rel-width", tshow w),("rel-height", "scale"),("width", tshow ptX <> "pt"),("height", tshow ptY <> "pt")]
+               (Nothing, Just h@(Percent _)) -> [("rel-width", "scale"),("rel-height", tshow h),("width", tshow ptX <> "pt"),("height", tshow ptY <> "pt")]
+               (Just w@(Inch i), Nothing)    -> [("width", tshow w), ("height", tshow (i / ratio) <> "in")]
+               (Nothing, Just h@(Inch i))    -> [("width", tshow (i * ratio) <> "in"), ("height", tshow h)]
+               _                             -> [("width", tshow ptX <> "pt"), ("height", tshow ptY <> "pt")]
              where
                ratio = ptX / ptY
                getDim dir = case dimension dir attr of
@@ -199,17 +326,25 @@
                               Just dim         -> Just $ Inch $ inInch opts dim
                               Nothing          -> Nothing
        let  newattr = (id', cls, dims)
-       entries <- gets stEntries
-       let extension = fromMaybe (takeExtension $ takeWhile (/='?') src)
-                           (mbMimeType >>= extensionFromMimeType)
-       let newsrc = "Pictures/" ++ show (length entries) <.> extension
-       let toLazy = B.fromChunks . (:[])
-       epochtime <- floor `fmap` lift P.getPOSIXTime
-       let entry = toEntry newsrc epochtime $ toLazy img
-       modify $ \st -> st{ stEntries = entry : entries }
-       return $ Image newattr lab (newsrc, t))
+       src' <- if writerLinkImages opts
+                  then
+                    case T.unpack src of
+                      s | isURI s -> return src
+                        | isAbsolute s -> return src
+                        | otherwise -> return $ T.pack $ ".." </> s
+                  else do
+                    entries <- gets stEntries
+                    let extension = maybe (takeExtension $ takeWhile (/='?') $ T.unpack src) T.unpack
+                                        (mbMimeType >>= extensionFromMimeType)
+                    let newsrc = "Pictures/" ++ show (length entries) <.> extension
+                    let toLazy = B.fromChunks . (:[])
+                    epochtime <- floor `fmap` lift P.getPOSIXTime
+                    let entry = toEntry newsrc epochtime $ toLazy img
+                    modify $ \st -> st{ stEntries = entry : entries }
+                    return $ T.pack newsrc
+       return $ Image newattr lab (src', t))
    (\e -> do
-       report $ CouldNotFetchResource src (show e)
+       report $ CouldNotFetchResource src $ T.pack (show e)
        return $ Emph lab)
 
 transformPicMath _ (Math t math) = do
@@ -218,23 +353,78 @@
   case writeMathML dt <$> readTeX math of
        Left  _ -> return $ Math t math
        Right r -> do
-         let conf = useShortEmptyTags (const False) defaultConfigPP
-         let mathml = ppcTopElement conf r
-         epochtime <- floor `fmap` (lift P.getPOSIXTime)
+         let conf = XL.useShortEmptyTags (const False) XL.defaultConfigPP
+         let mathml = XL.ppcTopElement conf r
+         epochtime <- floor `fmap` lift P.getPOSIXTime
          let dirname = "Formula-" ++ show (length entries) ++ "/"
          let fname = dirname ++ "content.xml"
          let entry = toEntry fname epochtime (fromStringLazy mathml)
-         modify $ \st -> st{ stEntries = entry : entries }
+         let fname' = dirname ++ "settings.xml"
+         let entry' = toEntry fname' epochtime $ documentSettings (t == InlineMath)
+         modify $ \st -> st{ stEntries = entry' : (entry : entries) }
          return $ RawInline (Format "opendocument") $ render Nothing $
-           inTags False "draw:frame" [("text:anchor-type",
-                                       if t == DisplayMath
-                                          then "paragraph"
-                                          else "as-char")
-                                     ,("style:vertical-pos", "middle")
-                                     ,("style:vertical-rel", "text")] $
-             selfClosingTag "draw:object" [("xlink:href", dirname)
+           inTags False "draw:frame" (if t == DisplayMath
+                                      then [("draw:style-name","fr2")
+                                           -- `draw:frame` does not support either
+                                           -- `style:vertical-pos` or `style:vertical-rel`,
+                                           -- therefore those attributes must go into the
+                                           -- `style:style` element
+                                           ,("text:anchor-type","paragraph")]
+                                      else [("draw:style-name","fr1")
+                                           ,("text:anchor-type","as-char")]) $
+             selfClosingTag "draw:object" [("xlink:href", T.pack dirname)
                                         , ("xlink:type", "simple")
                                         , ("xlink:show", "embed")
                                         , ("xlink:actuate", "onLoad")]
 
 transformPicMath _ x = return x
+
+documentSettings :: Bool -> B.ByteString
+documentSettings isTextMode = fromStringLazy $ render Nothing
+    $ text "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
+    $$
+    inTags True "office:document-settings"
+      [("xmlns:office","urn:oasis:names:tc:opendocument:xmlns:office:1.0")
+      ,("xmlns:xlink","http://www.w3.org/1999/xlink")
+      ,("xmlns:config","urn:oasis:names:tc:opendocument:xmlns:config:1.0")
+      ,("xmlns:ooo","http://openoffice.org/2004/office")
+      ,("office:version","1.3")] (
+       inTagsSimple "office:settings" $
+         inTags False "config:config-item-set"
+           [("config:name", "ooo:configuration-settings")] $
+           inTags False "config:config-item" [("config:name", "IsTextMode")
+                                             ,("config:type", "boolean")] $
+                                              text $ if isTextMode then "true" else "false")
+
+styleToOpenDocument :: Style -> [Content]
+styleToOpenDocument style = map (Elem . toStyle) alltoktypes
+  where alltoktypes = enumFromTo KeywordTok NormalTok
+        styleName x =
+          case T.break (== ':') x of
+            (b, a) | T.null a  -> QName x Nothing (Just "style")
+                   | otherwise -> QName (T.drop 1 a) Nothing (Just b)
+        styleAttr (x, y) = Attr (styleName x) y
+        styleAttrs = map styleAttr
+        styleElement x attrs cs =
+          Element (styleName x) (styleAttrs attrs) cs Nothing
+        toStyle toktype =
+          styleElement "style"
+            [("name", tshow toktype), ("family", "text")]
+            [Elem (styleElement "text-properties"
+                      (tokColor toktype ++ tokBgColor toktype ++
+                        [("fo:font-style", "italic") |
+                           tokFeature tokenItalic toktype ] ++
+                        [("fo:font-weight", "bold") |
+                           tokFeature tokenBold toktype ] ++
+                        [("style:text-underline-style", "solid") |
+                           tokFeature tokenUnderline toktype ])
+                        [])]
+        tokStyles = tokenStyles style
+        tokFeature f toktype = maybe False f $ Map.lookup toktype tokStyles
+        tokColor toktype =
+          maybe [] (\c -> [("fo:color", T.pack (fromColor c))])
+                        ((tokenColor =<< Map.lookup toktype tokStyles)
+                           `mplus` defaultColor style)
+        tokBgColor toktype =
+          maybe [] (\c -> [("fo:background-color", T.pack (fromColor c))])
+                    (tokenBackground =<< Map.lookup toktype tokStyles)
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,102 +1,93 @@
+{-# LANGUAGE OverloadedStrings #-}
+{- |
+   Module      : Text.Pandoc.Writers.OOXML
+   Copyright   : Copyright (C) 2012-2024 John MacFarlane
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : John MacFarlane <jgm@berkeley.edu>
+   Stability   : alpha
+   Portability : portable
+
+Functions common to OOXML writers (Docx and Powerpoint)
+-}
 module Text.Pandoc.Writers.OOXML ( mknode
-                                , nodename
-                                , toLazy
-                                , renderXml
-                                , parseXml
-                                , elemToNameSpaces
-                                , elemName
-                                , isElem
-                                , NameSpaces
-                                , fitToPage
-                                ) where
+                                 , mktnode
+                                 , nodename
+                                 , toLazy
+                                 , renderXml
+                                 , parseXml
+                                 , elemToNameSpaces
+                                 , elemName
+                                 , isElem
+                                 , NameSpaces
+                                 , fitToPage
+                                 ) where
+
 import Codec.Archive.Zip
---import Control.Applicative ((<|>))
--- import Control.Monad.Except (catchError)
-import Control.Monad.Reader
--- import Control.Monad.State
+import Control.Monad (mplus)
+import Control.Monad.Except (throwError)
+import Text.Pandoc.Error
 import qualified Data.ByteString as B
 import qualified Data.ByteString.Lazy as BL
-import qualified Data.ByteString.Lazy.Char8 as BL8
--- import Data.Char (isSpace, ord, toLower)
--- import Data.List (intercalate, isPrefixOf, isSuffixOf)
--- import qualified Data.Map as M
 import Data.Maybe (mapMaybe)
-import Data.Monoid ((<>))
--- import qualified Data.Set as Set
--- import qualified Data.Text as T
--- import Data.Time.Clock.POSIX
--- import Skylighting
--- import System.Random (randomR)
-import Text.Pandoc.Class (PandocMonad)
--- import qualified Text.Pandoc.Class as P
--- import Text.Pandoc.Compat.Time
--- import Text.Pandoc.Definition
--- import Text.Pandoc.Generic
--- import Text.Pandoc.Highlighting (highlight)
--- import Text.Pandoc.ImageSize
--- import Text.Pandoc.Logging
--- import Text.Pandoc.MIME (MimeType, extensionFromMimeType, getMimeType,
---                          getMimeTypeDef)
--- import Text.Pandoc.Options
--- import Text.Pandoc.Readers.Docx.StyleMap
--- import Text.Pandoc.Shared hiding (Element)
+import qualified Data.Text as T
+import Data.Text (Text)
+import Text.Pandoc.Class.PandocMonad (PandocMonad)
 import qualified Text.Pandoc.UTF8 as UTF8
--- import Text.Pandoc.Walk
--- import Text.Pandoc.Writers.Math
--- import Text.Pandoc.Writers.Shared (fixDisplayMath)
--- import Text.Printf (printf)
--- import Text.TeXMath
-import Text.XML.Light as XML
--- import Text.XML.Light.Cursor as XMLC
-
+import Text.Pandoc.XML.Light
 
-mknode :: Node t => String -> [(String,String)] -> t -> Element
+mknode :: Node t => Text -> [(Text,Text)] -> t -> Element
 mknode s attrs =
   add_attrs (map (\(k,v) -> Attr (nodename k) v) attrs) .  node (nodename s)
 
-nodename :: String -> QName
+mktnode :: Text -> [(Text,Text)] -> T.Text -> Element
+mktnode s attrs = mknode s attrs
+
+nodename :: Text -> QName
 nodename s = QName{ qName = name, qURI = Nothing, qPrefix = prefix }
- where (name, prefix) = case break (==':') s of
-                             (xs,[])    -> (xs, Nothing)
-                             (ys, _:zs) -> (zs, Just ys)
+ where (name, prefix) = case T.break (==':') s of
+                          (xs,ys) -> case T.uncons ys of
+                                       Nothing     -> (xs, Nothing)
+                                       Just (_,zs) -> (zs, Just xs)
 
 toLazy :: B.ByteString -> BL.ByteString
 toLazy = BL.fromChunks . (:[])
 
 renderXml :: Element -> BL.ByteString
-renderXml elt = BL8.pack "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" <>
-  UTF8.fromStringLazy (showElement elt)
+renderXml elt = BL.fromStrict (UTF8.fromText (showTopElement elt))
 
-parseXml :: (PandocMonad m) => Archive -> Archive -> String -> m Element
+parseXml :: PandocMonad m => Archive -> Archive -> String -> m Element
 parseXml refArchive distArchive relpath =
   case findEntryByPath relpath refArchive `mplus`
          findEntryByPath relpath distArchive of
-            Nothing -> fail $ relpath ++ " missing in reference file"
-            Just e  -> case parseXMLDoc . UTF8.toStringLazy . fromEntry $ e of
-                       Nothing -> fail $ relpath ++ " corrupt in reference file"
-                       Just d  -> return d
+            Nothing -> throwError $ PandocSomeError $
+                        T.pack relpath <> " missing in reference file"
+            Just e  -> case parseXMLElement . UTF8.toTextLazy . fromEntry $ e of
+                       Left msg ->
+                         throwError $ PandocXMLError (T.pack relpath) msg
+                       Right d  -> return d
 
 -- Copied from Util
 
-attrToNSPair :: XML.Attr -> Maybe (String, String)
-attrToNSPair (XML.Attr (QName s _ (Just "xmlns")) val) = Just (s, val)
+attrToNSPair :: Attr -> Maybe (Text, Text)
+attrToNSPair (Attr (QName s _ (Just "xmlns")) val) = Just (s, val)
 attrToNSPair _                                     = Nothing
 
 
 elemToNameSpaces :: Element -> NameSpaces
 elemToNameSpaces = mapMaybe attrToNSPair . elAttribs
 
-elemName :: NameSpaces -> String -> String -> QName
+elemName :: NameSpaces -> Text -> Text -> QName
 elemName ns prefix name =
-  QName name (lookup prefix ns) (if null prefix then Nothing else Just prefix)
+  QName name (lookup prefix ns) (if T.null prefix then Nothing else Just prefix)
 
-isElem :: NameSpaces -> String -> String -> Element -> Bool
+isElem :: NameSpaces -> Text -> Text -> Element -> Bool
 isElem ns prefix name element =
   let ns' = ns ++ elemToNameSpaces element
   in qName (elName element) == name &&
      qURI (elName element) == lookup prefix ns'
 
-type NameSpaces = [(String, String)]
+type NameSpaces = [(Text, Text)]
 
 -- | Scales the image to fit the page
 -- sizes are passed in emu
@@ -104,6 +95,5 @@
 fitToPage (x, y) pageWidth
   -- Fixes width to the page width and scales the height
   | x > fromIntegral pageWidth =
-    (pageWidth, floor $ ((fromIntegral pageWidth) / x) * y)
+    (pageWidth, floor $ (fromIntegral pageWidth / x) * y)
   | otherwise = (floor x, floor y)
-
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,25 +1,8 @@
-{-# LANGUAGE CPP #-}
-{-
-Copyright (C) 2013-2017 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 OverloadedStrings #-}
+{-# LANGUAGE CPP               #-}
 {- |
    Module      : Text.Pandoc.Writers.OPML
-   Copyright   : Copyright (C) 2013-2017 John MacFarlane
+   Copyright   : Copyright (C) 2013-2024 John MacFarlane
    License     : GNU GPL, version 2 or above
 
    Maintainer  : John MacFarlane <jgm@berkeley.edu>
@@ -29,18 +12,16 @@
 Conversion of 'Pandoc' documents to OPML XML.
 -}
 module Text.Pandoc.Writers.OPML ( writeOPML) where
-import Control.Monad.Except (throwError)
-import Data.Text (Text, unpack)
+import Data.Text (Text)
 import qualified Data.Text as T
 import qualified Text.Pandoc.Builder as B
-import Text.Pandoc.Class (PandocMonad)
-import Text.Pandoc.Compat.Time
+import Text.Pandoc.Class.PandocMonad (PandocMonad)
+import Data.Time
 import Text.Pandoc.Definition
-import Text.Pandoc.Error
 import Text.Pandoc.Options
-import Text.Pandoc.Pretty
+import Text.DocLayout
 import Text.Pandoc.Shared
-import Text.Pandoc.Templates (renderTemplate')
+import Text.Pandoc.Templates (renderTemplate)
 import Text.Pandoc.Writers.HTML (writeHtml5String)
 import Text.Pandoc.Writers.Markdown (writeMarkdown)
 import Text.Pandoc.Writers.Shared
@@ -49,58 +30,55 @@
 -- | Convert Pandoc document to string in OPML format.
 writeOPML :: PandocMonad m => WriterOptions -> Pandoc -> m Text
 writeOPML opts (Pandoc meta blocks) = do
-  let elements = hierarchicalize blocks
-      colwidth = if writerWrapText opts == WrapAuto
+  let colwidth = if writerWrapText opts == WrapAuto
                     then Just $ writerColumns opts
                     else Nothing
       meta' = B.setMeta "date" (B.str $ convertDate $ docDate meta) meta
-  metadata <- metaToJSON opts
-              (writeMarkdown def . Pandoc nullMeta)
-              (\ils -> T.stripEnd <$> writeMarkdown def (Pandoc nullMeta [Plain ils]))
+  metadata <- metaToContext opts
+              (fmap literal . writeMarkdown' opts . Pandoc nullMeta)
+              (\ils -> literal . T.stripEnd <$>
+                writeMarkdown' opts (Pandoc nullMeta [Plain ils]))
               meta'
-  main <- (render colwidth . vcat) <$> mapM (elementToOPML opts) elements
+  let blocks' = makeSections False (Just 1) blocks
+  main <- render colwidth . vcat <$>
+             mapM (blockToOPML opts) blocks'
   let context = defField "body" main metadata
-  case writerTemplate opts of
-       Nothing  -> return main
-       Just tpl -> renderTemplate' tpl context
+  return $
+    (if writerPreferAscii opts then toEntities else id) $
+    case writerTemplate opts of
+       Nothing  -> main
+       Just tpl -> render colwidth $ renderTemplate tpl context
 
+writeMarkdown' :: PandocMonad m => WriterOptions -> Pandoc -> m Text
+writeMarkdown' opts = writeMarkdown def{ writerWrapText = writerWrapText opts
+                                       , writerColumns = writerColumns opts
+                                       , writerExtensions = pandocExtensions
+                                       }
 
 writeHtmlInlines :: PandocMonad m => [Inline] -> m Text
 writeHtmlInlines ils =
   T.strip <$> writeHtml5String def (Pandoc nullMeta [Plain ils])
 
 -- date format: RFC 822: Thu, 14 Jul 2005 23:41:05 GMT
-showDateTimeRFC822 :: UTCTime -> String
-showDateTimeRFC822 = formatTime defaultTimeLocale "%a, %d %b %Y %X %Z"
+showDateTimeRFC822 :: UTCTime -> Text
+showDateTimeRFC822 = T.pack . formatTime defaultTimeLocale "%a, %d %b %Y %X %Z"
 
-convertDate :: [Inline] -> String
+convertDate :: [Inline] -> Text
 convertDate ils = maybe "" showDateTimeRFC822 $
-#if MIN_VERSION_time(1,5,0)
-  parseTimeM True
-#else
-  parseTime
-#endif
-  defaultTimeLocale "%F" =<< normalizeDate (stringify ils)
-
--- | Convert an Element to OPML.
-elementToOPML :: PandocMonad m => WriterOptions -> Element -> m Doc
-elementToOPML _ (Blk _) = return empty
-elementToOPML opts (Sec _ _num _ title elements) = do
-  let isBlk :: Element -> Bool
-      isBlk (Blk _) = True
-      isBlk _       = False
-
-      fromBlk :: PandocMonad m => Element -> m Block
-      fromBlk (Blk x) = return x
-      fromBlk _ = throwError $ PandocSomeError "fromBlk called on non-block"
+  parseTimeM True defaultTimeLocale "%F" . T.unpack =<< normalizeDate (stringify ils)
 
-      (blocks, rest) = span isBlk elements
+-- | Convert a Block to OPML.
+blockToOPML :: PandocMonad m => WriterOptions -> Block -> m (Doc Text)
+blockToOPML opts (Div (_,"section":_,_) (Header _ _ title : xs)) = do
+  let isSect (Div (_,"section":_,_) (Header{}:_)) = True
+      isSect _ = False
+  let (blocks, rest) = break isSect xs
   htmlIls <- writeHtmlInlines title
   md <- if null blocks
         then return mempty
-        else do blks <- mapM fromBlk blocks
-                writeMarkdown def $ Pandoc nullMeta blks
-  let attrs = ("text", unpack htmlIls) :
-              [("_note", unpack md) | not (null blocks)]
-  o <- mapM (elementToOPML opts) rest
-  return $ inTags True "outline" attrs $ vcat o
+        else writeMarkdown' opts $ Pandoc nullMeta blocks
+  let attrs = ("text", htmlIls) :
+              [("_note", T.stripEnd md) | not (null blocks)]
+  rest' <- vcat <$> mapM (blockToOPML opts) rest
+  return $ inTags True "outline" attrs rest'
+blockToOPML _ _ = return empty
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
@@ -1,651 +1,973 @@
 {-# LANGUAGE FlexibleContexts  #-}
-{-# LANGUAGE OverloadedStrings #-}
-{-# LANGUAGE PatternGuards     #-}
-{-
-Copyright (C) 2008-2017 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-2017 Andrea Rossato and John MacFarlane
-   License     : GNU GPL, version 2 or above
-
-   Maintainer  : Andrea Rossato <andrea.rossato@ing.unitn.it>
-   Stability   : alpha
-   Portability : portable
-
-Conversion of 'Pandoc' documents to OpenDocument XML.
--}
-module Text.Pandoc.Writers.OpenDocument ( writeOpenDocument ) where
-import Control.Arrow ((***), (>>>))
-import Control.Monad.State.Strict hiding (when)
-import Data.Char (chr)
-import Data.List (sortBy)
-import qualified Data.Map as Map
-import Data.Ord (comparing)
-import qualified Data.Set as Set
-import Data.Text (Text)
-import Text.Pandoc.BCP47 (Lang (..), parseBCP47)
-import Text.Pandoc.Class (PandocMonad, report)
-import Text.Pandoc.Definition
-import Text.Pandoc.Logging
-import Text.Pandoc.Options
-import Text.Pandoc.Pretty
-import Text.Pandoc.Shared (linesToPara)
-import Text.Pandoc.Templates (renderTemplate')
-import Text.Pandoc.Writers.Math
-import Text.Pandoc.Writers.Shared
-import Text.Pandoc.XML
-import Text.Printf (printf)
-
--- | Auxiliary function to convert Plain block to Para.
-plainToPara :: Block -> Block
-plainToPara (Plain x) = Para x
-plainToPara x         = x
-
---
--- OpenDocument writer
---
-
-type OD m = StateT WriterState m
-
-data WriterState =
-    WriterState { stNotes         :: [Doc]
-                , stTableStyles   :: [Doc]
-                , stParaStyles    :: [Doc]
-                , stListStyles    :: [(Int, [Doc])]
-                , stTextStyles    :: Map.Map (Set.Set TextStyle) (String, Doc)
-                , stTextStyleAttr :: Set.Set TextStyle
-                , stIndentPara    :: Int
-                , stInDefinition  :: Bool
-                , stTight         :: Bool
-                , stFirstPara     :: Bool
-                , stImageId       :: Int
-                }
-
-defaultWriterState :: WriterState
-defaultWriterState =
-    WriterState { stNotes         = []
-                , stTableStyles   = []
-                , stParaStyles    = []
-                , stListStyles    = []
-                , stTextStyles    = Map.empty
-                , stTextStyleAttr = Set.empty
-                , stIndentPara    = 0
-                , stInDefinition  = False
-                , stTight         = False
-                , stFirstPara     = False
-                , stImageId       = 1
-                }
-
-when :: Bool -> Doc -> Doc
-when p a = if p then a else empty
-
-addTableStyle :: PandocMonad m => Doc -> OD m ()
-addTableStyle i = modify $ \s -> s { stTableStyles = i : stTableStyles s }
-
-addNote :: PandocMonad m => Doc -> OD m ()
-addNote i = modify $ \s -> s { stNotes = i : stNotes s }
-
-addParaStyle :: PandocMonad m => Doc -> OD m ()
-addParaStyle i = modify $ \s -> s { stParaStyles = i : stParaStyles s }
-
-addTextStyle :: PandocMonad m => Set.Set TextStyle -> (String, Doc) -> OD m ()
-addTextStyle attrs i = modify $ \s ->
-  s { stTextStyles = Map.insert attrs i (stTextStyles s) }
-
-addTextStyleAttr :: PandocMonad m => TextStyle -> OD m ()
-addTextStyleAttr t = modify $ \s ->
-  s { stTextStyleAttr = Set.insert t (stTextStyleAttr s) }
-
-increaseIndent :: PandocMonad m => OD m ()
-increaseIndent = modify $ \s -> s { stIndentPara = 1 + stIndentPara s }
-
-resetIndent :: PandocMonad m => OD m ()
-resetIndent = modify $ \s -> s { stIndentPara = stIndentPara s - 1 }
-
-inTightList :: PandocMonad m => OD m a -> OD m a
-inTightList  f = modify (\s -> s { stTight = True  }) >> f >>= \r ->
-                 modify (\s -> s { stTight = False }) >> return r
-
-setInDefinitionList :: PandocMonad m => Bool -> OD m ()
-setInDefinitionList b = modify $  \s -> s { stInDefinition = b }
-
-setFirstPara :: PandocMonad m => OD m ()
-setFirstPara =  modify $  \s -> s { stFirstPara = True }
-
-inParagraphTags :: PandocMonad m => Doc -> OD m Doc
-inParagraphTags d = do
-  b <- gets stFirstPara
-  a <- if b
-       then do modify $ \st -> st { stFirstPara = False }
-               return [("text:style-name", "First_20_paragraph")]
-       else    return   [("text:style-name", "Text_20_body")]
-  return $ inTags False "text:p" a d
-
-inParagraphTagsWithStyle :: String -> Doc -> Doc
-inParagraphTagsWithStyle sty = inTags False "text:p" [("text:style-name", sty)]
-
-inSpanTags :: String -> Doc -> Doc
-inSpanTags s = inTags False "text:span" [("text:style-name",s)]
-
-withTextStyle :: PandocMonad m => TextStyle -> OD m a -> OD m a
-withTextStyle s f = do
-  oldTextStyleAttr <- gets stTextStyleAttr
-  addTextStyleAttr s
-  res <- f
-  modify $ \st -> st{ stTextStyleAttr = oldTextStyleAttr }
-  return res
-
-inTextStyle :: PandocMonad m => Doc -> OD m Doc
-inTextStyle d = do
-  at <- gets stTextStyleAttr
-  if Set.null at
-     then return d
-     else do
-       styles <- gets stTextStyles
-       case Map.lookup at styles of
-            Just (styleName, _) -> return $
-              inTags False "text:span" [("text:style-name",styleName)] d
-            Nothing -> do
-              let styleName = "T" ++ show (Map.size styles + 1)
-              addTextStyle at (styleName,
-                     inTags False "style:style"
-                       [("style:name", styleName)
-                       ,("style:family", "text")]
-                       $ selfClosingTag "style:text-properties"
-                          (concatMap textStyleAttr (Set.toList at)))
-              return $ inTags False
-                  "text:span" [("text:style-name",styleName)] d
-
-inHeaderTags :: PandocMonad m => Int -> Doc -> OD m Doc
-inHeaderTags i d =
-  return $ inTags False "text:h" [ ("text:style-name", "Heading_20_" ++ show i)
-                                 , ("text:outline-level", show i)] d
-
-inQuotes :: QuoteType -> Doc -> Doc
-inQuotes SingleQuote s = char '\8216' <> s <> char '\8217'
-inQuotes DoubleQuote s = char '\8220' <> s <> char '\8221'
-
-handleSpaces :: String -> Doc
-handleSpaces s
-    | ( ' ':_) <- s = genTag s
-    | ('\t':x) <- s = selfClosingTag "text:tab" [] <> rm x
-    | otherwise     = rm s
-    where
-        genTag       = span (==' ') >>> tag . length *** rm >>> uncurry (<>)
-        tag n        = when (n /= 0) $ selfClosingTag "text:s" [("text:c", show n)]
-        rm ( ' ':xs) = char ' ' <> genTag xs
-        rm ('\t':xs) = selfClosingTag "text:tab" [] <> genTag xs
-        rm (   x:xs) = char  x  <> rm xs
-        rm        [] = empty
-
--- | Convert Pandoc document to string in OpenDocument format.
-writeOpenDocument :: PandocMonad m => WriterOptions -> Pandoc -> m Text
-writeOpenDocument opts (Pandoc meta blocks) = do
-  let colwidth = if writerWrapText opts == WrapAuto
-                    then Just $ writerColumns opts
-                    else Nothing
-  let render' :: Doc -> Text
-      render' = render colwidth
-  ((body, metadata),s) <- flip runStateT
-        defaultWriterState $ do
-           m <- metaToJSON opts
-                  (fmap render' . blocksToOpenDocument opts)
-                  (fmap render' . inlinesToOpenDocument opts)
-                  meta
-           b <- render' `fmap` blocksToOpenDocument opts blocks
-           return (b, m)
-  let styles   = stTableStyles s ++ stParaStyles s ++
-                     map snd (sortBy (flip (comparing fst)) (
-                        Map.elems (stTextStyles s)))
-      listStyle (n,l) = inTags True "text:list-style"
-                          [("style:name", "L" ++ show n)] (vcat l)
-  let listStyles  = map listStyle (stListStyles s)
-  let automaticStyles = vcat $ reverse $ styles ++ listStyles
-  let context = defField "body" body
-              $ defField "toc" (writerTableOfContents opts)
-              $defField "automatic-styles" (render' automaticStyles) metadata
-  case writerTemplate opts of
-       Nothing  -> return body
-       Just tpl -> renderTemplate' tpl context
-
-withParagraphStyle :: PandocMonad m
-                   => WriterOptions -> String -> [Block] -> OD m Doc
-withParagraphStyle  o s (b:bs)
-    | Para l <- b = go =<< inParagraphTagsWithStyle s <$> inlinesToOpenDocument o l
-    | otherwise   = go =<< blockToOpenDocument o b
-    where go i = (<>) i <$>  withParagraphStyle o s bs
-withParagraphStyle _ _ [] = return empty
-
-inPreformattedTags :: PandocMonad m => String -> OD m Doc
-inPreformattedTags s = do
-  n <- paraStyle [("style:parent-style-name","Preformatted_20_Text")]
-  return . inParagraphTagsWithStyle ("P" ++ show n) . handleSpaces $ s
-
-orderedListToOpenDocument :: PandocMonad m
-                          => WriterOptions -> Int -> [[Block]] -> OD m Doc
-orderedListToOpenDocument o pn bs =
-    vcat . map (inTagsIndented "text:list-item") <$>
-    mapM (orderedItemToOpenDocument o pn . map plainToPara) bs
-
-orderedItemToOpenDocument :: PandocMonad m
-                          => WriterOptions -> Int -> [Block] -> OD m Doc
-orderedItemToOpenDocument  o n bs = vcat <$> mapM go bs
- where go (OrderedList a l) = newLevel a l
-       go (Para          l) = inParagraphTagsWithStyle ("P" ++ show n) <$>
-                                inlinesToOpenDocument o l
-       go b                 = blockToOpenDocument o b
-       newLevel a l = do
-         nn <- length <$> gets stParaStyles
-         ls <- head   <$> gets stListStyles
-         modify $ \s -> s { stListStyles = orderedListLevelStyle a ls :
-                                 drop 1 (stListStyles s) }
-         inTagsIndented "text:list" <$> orderedListToOpenDocument o nn l
-
-isTightList :: [[Block]] -> Bool
-isTightList []          = False
-isTightList (b:_)
-    | Plain {} : _ <- b = True
-    | otherwise         = False
-
-newOrderedListStyle :: PandocMonad m
-                    => Bool -> ListAttributes -> OD m (Int,Int)
-newOrderedListStyle b a = do
-  ln <- (+) 1 . length  <$> gets stListStyles
-  let nbs = orderedListLevelStyle a (ln, [])
-  pn <- if b then inTightList (paraListStyle ln) else paraListStyle ln
-  modify $ \s -> s { stListStyles = nbs : stListStyles s }
-  return (ln,pn)
-
-bulletListToOpenDocument :: PandocMonad m
-                         => WriterOptions -> [[Block]] -> OD m Doc
-bulletListToOpenDocument o b = do
-  ln <- (+) 1 . length <$> gets stListStyles
-  (pn,ns) <- if isTightList b then inTightList (bulletListStyle ln) else bulletListStyle ln
-  modify $ \s -> s { stListStyles = ns : stListStyles s }
-  is <- listItemsToOpenDocument ("P" ++ show pn) o b
-  return $ inTags True "text:list" [("text:style-name", "L" ++ show ln)] is
-
-listItemsToOpenDocument :: PandocMonad m
-                        => String -> WriterOptions -> [[Block]] -> OD m Doc
-listItemsToOpenDocument s o is =
-    vcat . map (inTagsIndented "text:list-item") <$> mapM (withParagraphStyle o s . map plainToPara) is
-
-deflistItemToOpenDocument :: PandocMonad m
-                          => WriterOptions -> ([Inline],[[Block]]) -> OD m Doc
-deflistItemToOpenDocument o (t,d) = do
-  let ts = if isTightList d
-           then "Definition_20_Term_20_Tight"       else "Definition_20_Term"
-      ds = if isTightList d
-           then "Definition_20_Definition_20_Tight" else "Definition_20_Definition"
-  t' <- withParagraphStyle o ts [Para t]
-  d' <- liftM vcat $ mapM (withParagraphStyle o ds . map plainToPara) d
-  return $ t' $$ d'
-
-inBlockQuote :: PandocMonad m
-             => WriterOptions -> Int -> [Block] -> OD m Doc
-inBlockQuote  o i (b:bs)
-    | BlockQuote l <- b = do increaseIndent
-                             ni <- paraStyle
-                                   [("style:parent-style-name","Quotations")]
-                             go =<< inBlockQuote o ni (map plainToPara l)
-    | Para       l <- b = go =<< inParagraphTagsWithStyle ("P" ++ show  i) <$> inlinesToOpenDocument o l
-    | otherwise         = go =<< blockToOpenDocument o b
-    where go  block  = ($$) block <$> inBlockQuote o i bs
-inBlockQuote     _ _ [] =  resetIndent >> return empty
-
--- | Convert a list of Pandoc blocks to OpenDocument.
-blocksToOpenDocument :: PandocMonad m => WriterOptions -> [Block] -> OD m Doc
-blocksToOpenDocument o b = vcat <$> mapM (blockToOpenDocument o) b
-
--- | Convert a Pandoc block element to OpenDocument.
-blockToOpenDocument :: PandocMonad m => WriterOptions -> Block -> OD m Doc
-blockToOpenDocument o bs
-    | Plain          b <- bs = if null b
-                                  then return empty
-                                  else inParagraphTags =<< inlinesToOpenDocument o b
-    | Para [Image attr c (s,'f':'i':'g':':':t)] <- bs
-                             = figure attr c s t
-    | Para           b <- bs = if null b &&
-                                    not (isEnabled Ext_empty_paragraphs o)
-                                  then return empty
-                                  else inParagraphTags =<< inlinesToOpenDocument o b
-    | LineBlock      b <- bs = blockToOpenDocument o $ linesToPara b
-    | Div attr xs      <- bs = withLangFromAttr attr
-                                  (blocksToOpenDocument o xs)
-    | Header     i _ b <- bs = setFirstPara >>
-                               (inHeaderTags  i =<< inlinesToOpenDocument o b)
-    | BlockQuote     b <- bs = setFirstPara >> mkBlockQuote b
-    | DefinitionList b <- bs = setFirstPara >> defList b
-    | BulletList     b <- bs = setFirstPara >> bulletListToOpenDocument o b
-    | OrderedList  a b <- bs = setFirstPara >> orderedList a b
-    | CodeBlock    _ s <- bs = setFirstPara >> preformatted s
-    | Table  c a w h r <- bs = setFirstPara >> table c a w h r
-    | HorizontalRule   <- bs = setFirstPara >> return (selfClosingTag "text:p"
-                                [ ("text:style-name", "Horizontal_20_Line") ])
-    | RawBlock f     s <- bs = if f == Format "opendocument"
-                                  then return $ text s
-                                  else do
-                                    report $ BlockNotRendered bs
-                                    return empty
-    | Null             <- bs = return empty
-    | otherwise              = return empty
-    where
-      defList       b = do setInDefinitionList True
-                           r <- vcat  <$> mapM (deflistItemToOpenDocument o) b
-                           setInDefinitionList False
-                           return r
-      preformatted  s = (flush . vcat) <$> mapM (inPreformattedTags . escapeStringForXML) (lines s)
-      mkBlockQuote  b = do increaseIndent
-                           i <- paraStyle
-                                 [("style:parent-style-name","Quotations")]
-                           inBlockQuote o i (map plainToPara b)
-      orderedList a b = do (ln,pn) <- newOrderedListStyle (isTightList b) a
-                           inTags True "text:list" [ ("text:style-name", "L" ++ show ln)]
-                                      <$> orderedListToOpenDocument o pn b
-      table c a w h r = do
-        tn <- length <$> gets stTableStyles
-        pn <- length <$> gets stParaStyles
-        let  genIds      = map chr [65..]
-             name        = "Table" ++ show (tn + 1)
-             columnIds   = zip genIds w
-             mkColumn  n = selfClosingTag "table:table-column" [("table:style-name", name ++ "." ++ [fst n])]
-             columns     = map mkColumn columnIds
-             paraHStyles = paraTableStyles "Heading"  pn a
-             paraStyles  = paraTableStyles "Contents" (pn + length (newPara paraHStyles)) a
-             newPara     = map snd . filter (not . isEmpty . snd)
-        addTableStyle $ tableStyle tn columnIds
-        mapM_ addParaStyle . newPara $ paraHStyles ++ paraStyles
-        captionDoc <- if null c
-                      then return empty
-                      else withParagraphStyle o "Table" [Para c]
-        th <- if all null h
-                 then return empty
-                 else colHeadsToOpenDocument o name (map fst paraHStyles) h
-        tr <- mapM (tableRowToOpenDocument o name (map fst paraStyles)) r
-        return $ inTags True "table:table" [ ("table:name"      , name)
-                                           , ("table:style-name", name)
-                                           ] (vcat columns $$ th $$ vcat tr) $$ captionDoc
-      figure attr caption source title | null caption =
-        withParagraphStyle o "Figure" [Para [Image attr caption (source,title)]]
-                                  | otherwise    = do
-        imageDoc <- withParagraphStyle o "FigureWithCaption" [Para [Image attr caption (source,title)]]
-        captionDoc <- withParagraphStyle o "FigureCaption" [Para caption]
-        return $ imageDoc $$ captionDoc
-
-colHeadsToOpenDocument :: PandocMonad m
-                       => WriterOptions -> String -> [String] -> [[Block]]
-                       -> OD m Doc
-colHeadsToOpenDocument o tn ns hs =
-    inTagsIndented "table:table-header-rows" . inTagsIndented "table:table-row" . vcat <$>
-    mapM (tableItemToOpenDocument o tn) (zip ns hs)
-
-tableRowToOpenDocument :: PandocMonad m
-                       => WriterOptions -> String -> [String] -> [[Block]]
-                       -> OD m Doc
-tableRowToOpenDocument o tn ns cs =
-    inTagsIndented "table:table-row" . vcat <$>
-    mapM (tableItemToOpenDocument o tn) (zip ns cs)
-
-tableItemToOpenDocument :: PandocMonad m
-                        => WriterOptions -> String -> (String,[Block])
-                        -> OD m Doc
-tableItemToOpenDocument o tn (n,i) =
-  let a = [ ("table:style-name" , tn ++ ".A1" )
-          , ("office:value-type", "string"     )
-          ]
-  in  inTags True "table:table-cell" a <$>
-      withParagraphStyle o n (map plainToPara i)
-
--- | Convert a list of inline elements to OpenDocument.
-inlinesToOpenDocument :: PandocMonad m => WriterOptions -> [Inline] -> OD m Doc
-inlinesToOpenDocument o l = hcat <$> toChunks o l
-
-toChunks :: PandocMonad m => WriterOptions -> [Inline] -> OD m [Doc]
-toChunks _ [] = return []
-toChunks o (x : xs)
-  | isChunkable x = do
-        contents <- (inTextStyle . hcat) =<<
-                     mapM (inlineToOpenDocument o) (x:ys)
-        rest <- toChunks o zs
-        return (contents : rest)
-  | otherwise     = do
-        contents <- inlineToOpenDocument o x
-        rest <- toChunks o xs
-        return (contents : rest)
-  where (ys, zs) = span isChunkable xs
-
-isChunkable :: Inline -> Bool
-isChunkable (Str _)   = True
-isChunkable Space     = True
-isChunkable SoftBreak = True
-isChunkable _         = False
-
--- | Convert an inline element to OpenDocument.
-inlineToOpenDocument :: PandocMonad m => WriterOptions -> Inline -> OD m Doc
-inlineToOpenDocument o ils
-  = case ils of
-    Space         -> return space
-    SoftBreak
-     | writerWrapText o == WrapPreserve
-                  -> return $ preformatted "\n"
-     | otherwise  ->return space
-    Span attr xs  -> withLangFromAttr attr (inlinesToOpenDocument o xs)
-    LineBreak     -> return $ selfClosingTag "text:line-break" []
-    Str         s -> return $ handleSpaces $ escapeStringForXML s
-    Emph        l -> withTextStyle Italic $ inlinesToOpenDocument o l
-    Strong      l -> withTextStyle Bold   $ inlinesToOpenDocument o l
-    Strikeout   l -> withTextStyle Strike $ inlinesToOpenDocument o l
-    Superscript l -> withTextStyle Sup    $ inlinesToOpenDocument o l
-    Subscript   l -> withTextStyle Sub    $ inlinesToOpenDocument o l
-    SmallCaps   l -> withTextStyle SmallC $ inlinesToOpenDocument o l
-    Quoted    t l -> inQuotes t <$> inlinesToOpenDocument o l
-    Code      _ s -> inlinedCode $ preformatted s
-    Math      t s -> lift (texMathToInlines t s) >>=
-                         inlinesToOpenDocument o
-    Cite      _ l -> inlinesToOpenDocument o l
-    RawInline f s -> if f == Format "opendocument"
-                       then return $ text s
-                       else do
-                         report $ InlineNotRendered ils
-                         return empty
-    Link _ l (s,t) ->  mkLink s t <$> inlinesToOpenDocument o l
-    Image attr _ (s,t) -> mkImg attr s t
-    Note        l  -> mkNote l
-    where
-      preformatted s = handleSpaces $ escapeStringForXML s
-      inlinedCode s = return $ inTags False "text:span" [("text:style-name", "Source_Text")] s
-      mkLink   s t = inTags False "text:a" [ ("xlink:type" , "simple")
-                                           , ("xlink:href" , s       )
-                                           , ("office:name", t       )
-                                           ] . inSpanTags "Definition"
-      mkImg (_, _, kvs) s _ = do
-               id' <- gets stImageId
-               modify (\st -> st{ stImageId = id' + 1 })
-               let getDims [] = []
-                   getDims (("width", w) :xs) = ("svg:width", w)  : getDims xs
-                   getDims (("height", h):xs) = ("svg:height", h) : getDims xs
-                   getDims (_:xs) =                             getDims xs
-               return $ inTags False "draw:frame"
-                        (("draw:name", "img" ++ show id') : getDims kvs) $
-                     selfClosingTag "draw:image" [ ("xlink:href"   , s       )
-                                                 , ("xlink:type"   , "simple")
-                                                 , ("xlink:show"   , "embed" )
-                                                 , ("xlink:actuate", "onLoad")]
-      mkNote     l = do
-        n <- length <$> gets stNotes
-        let footNote t = inTags False "text:note"
-                         [ ("text:id"        , "ftn" ++ show n)
-                         , ("text:note-class", "footnote"     )] $
-                         inTagsSimple "text:note-citation" (text . show $ n + 1) <>
-                         inTagsSimple "text:note-body" t
-        nn <- footNote <$> withParagraphStyle o "Footnote" l
-        addNote nn
-        return nn
-
-bulletListStyle :: PandocMonad m => Int -> OD m (Int,(Int,[Doc]))
-bulletListStyle l = do
-  let doStyles  i = inTags True "text:list-level-style-bullet"
-                    [ ("text:level"      , show (i + 1)       )
-                    , ("text:style-name" , "Bullet_20_Symbols")
-                    , ("style:num-suffix", "."                )
-                    , ("text:bullet-char", [bulletList !! i]  )
-                    ] (listLevelStyle (1 + i))
-      bulletList  = map chr $ cycle [8226,9702,9642]
-      listElStyle = map doStyles [0..9]
-  pn <- paraListStyle l
-  return (pn, (l, listElStyle))
-
-orderedListLevelStyle :: ListAttributes -> (Int, [Doc]) -> (Int,[Doc])
-orderedListLevelStyle (s,n, d) (l,ls) =
-    let suffix    = case d of
-                      OneParen  -> [("style:num-suffix", ")")]
-                      TwoParens -> [("style:num-prefix", "(")
-                                   ,("style:num-suffix", ")")]
-                      _         -> [("style:num-suffix", ".")]
-        format    = case n of
-                      UpperAlpha -> "A"
-                      LowerAlpha -> "a"
-                      UpperRoman -> "I"
-                      LowerRoman -> "i"
-                      _          -> "1"
-        listStyle = inTags True "text:list-level-style-number"
-                    ([ ("text:level"      , show $ 1 + length ls  )
-                     , ("text:style-name" , "Numbering_20_Symbols")
-                     , ("style:num-format", format                )
-                     , ("text:start-value", show s                )
-                     ] ++ suffix) (listLevelStyle (1 + length ls))
-    in  (l, ls ++ [listStyle])
-
-listLevelStyle :: Int -> Doc
-listLevelStyle i =
-    let indent = show (0.4 * fromIntegral (i - 1) :: Double) in
-    selfClosingTag "style:list-level-properties"
-                       [ ("text:space-before"   , indent ++ "in")
-                       , ("text:min-label-width",       "0.4in")]
-
-tableStyle :: Int -> [(Char,Double)] -> Doc
-tableStyle num wcs =
-    let tableId        = "Table" ++ show (num + 1)
-        table          = inTags True "style:style"
-                         [("style:name", tableId)
-                         ,("style:family", "table")] $
-                         selfClosingTag "style:table-properties"
-                         [("table:align"    , "center")]
-        colStyle (c,0) = selfClosingTag "style:style"
-                         [ ("style:name"  , tableId ++ "." ++ [c])
-                         , ("style:family", "table-column"       )]
-        colStyle (c,w) = inTags True "style:style"
-                         [ ("style:name"  , tableId ++ "." ++ [c])
-                         , ("style:family", "table-column"       )] $
-                         selfClosingTag "style:table-column-properties"
-                         [("style:rel-column-width", printf "%d*" (floor $ w * 65535 :: Integer))]
-        cellStyle      = inTags True "style:style"
-                         [ ("style:name"  , tableId ++ ".A1")
-                         , ("style:family", "table-cell"    )] $
-                         selfClosingTag "style:table-cell-properties"
-                         [ ("fo:border", "none")]
-        columnStyles   = map colStyle wcs
-    in  table $$ vcat columnStyles $$ cellStyle
-
-paraStyle :: PandocMonad m => [(String,String)] -> OD m Int
-paraStyle attrs = do
-  pn <- (+)   1 . length       <$> gets stParaStyles
-  i  <- (*) (0.5 :: Double) . fromIntegral <$> gets stIndentPara
-  b  <- gets stInDefinition
-  t  <- gets stTight
-  let styleAttr = [ ("style:name"             , "P" ++ show pn)
-                  , ("style:family"           , "paragraph"   )]
-      indentVal = flip (++) "in" . show $ if b then max 0.5 i else i
-      tight     = if t then [ ("fo:margin-top"          , "0in"    )
-                            , ("fo:margin-bottom"       , "0in"    )]
-                       else []
-      indent    = if (i /= 0 || b)
-                      then [ ("fo:margin-left"         , indentVal)
-                           , ("fo:margin-right"        , "0in"    )
-                           , ("fo:text-indent"         , "0in"    )
-                           , ("style:auto-text-indent" , "false"  )]
-                      else []
-      attributes = indent ++ tight
-      paraProps = if null attributes
-                     then mempty
-                     else selfClosingTag
-                             "style:paragraph-properties" attributes
-  addParaStyle $ inTags True "style:style" (styleAttr ++ attrs) paraProps
-  return pn
-
-paraListStyle :: PandocMonad m => Int -> OD m Int
-paraListStyle l = paraStyle
-  [("style:parent-style-name","Text_20_body")
-  ,("style:list-style-name", "L" ++ show l )]
-
-paraTableStyles :: String -> Int -> [Alignment] -> [(String, Doc)]
-paraTableStyles _ _ [] = []
-paraTableStyles t s (a:xs)
-    | AlignRight  <- a = (         pName s, res s "end"   ) : paraTableStyles t (s + 1) xs
-    | AlignCenter <- a = (         pName s, res s "center") : paraTableStyles t (s + 1) xs
-    | otherwise        = ("Table_20_" ++ t, empty         ) : paraTableStyles t  s      xs
-    where pName sn = "P" ++ show (sn + 1)
-          res sn x = inTags True "style:style"
-                     [ ("style:name"             , pName sn        )
-                     , ("style:family"           , "paragraph"     )
-                     , ("style:parent-style-name", "Table_20_" ++ t)] $
-                     selfClosingTag "style:paragraph-properties"
-                     [ ("fo:text-align", x)
-                     , ("style:justify-single-word", "false")]
-
-data TextStyle = Italic
-               | Bold
-               | Strike
-               | Sub
-               | Sup
-               | SmallC
-               | Pre
-               | Language Lang
-               deriving ( Eq,Ord )
-
-textStyleAttr :: TextStyle -> [(String,String)]
-textStyleAttr s
-    | Italic <- s = [("fo:font-style"                ,"italic"    )
-                    ,("style:font-style-asian"       ,"italic"    )
-                    ,("style:font-style-complex"     ,"italic"    )]
-    | Bold   <- s = [("fo:font-weight"               ,"bold"      )
-                    ,("style:font-weight-asian"      ,"bold"      )
-                    ,("style:font-weight-complex"    ,"bold"      )]
-    | Strike <- s = [("style:text-line-through-style", "solid"    )]
-    | Sub    <- s = [("style:text-position"          ,"sub 58%"   )]
-    | Sup    <- s = [("style:text-position"          ,"super 58%" )]
-    | SmallC <- s = [("fo:font-variant"              ,"small-caps")]
-    | Pre    <- s = [("style:font-name"              ,"Courier New")
-                    ,("style:font-name-asian"        ,"Courier New")
-                    ,("style:font-name-complex"      ,"Courier New")]
-    | Language lang <- s
-                  = [("fo:language"                  ,langLanguage lang)
-                    ,("fo:country"                   ,langRegion lang)]
-    | otherwise   = []
-
-withLangFromAttr :: PandocMonad m => Attr -> OD m a -> OD m a
-withLangFromAttr (_,_,kvs) action =
-  case lookup "lang" kvs of
-       Nothing -> action
-       Just l  ->
-         case parseBCP47 l of
+{-# LANGUAGE LambdaCase        #-}
+{-# LANGUAGE OverloadedStrings #-}
+{-# LANGUAGE PatternGuards     #-}
+{- |
+   Module      : Text.Pandoc.Writers.OpenDocument
+   Copyright   : Copyright (C) 2008-2020 Andrea Rossato and John MacFarlane
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : Andrea Rossato <andrea.rossato@ing.unitn.it>
+   Stability   : alpha
+   Portability : portable
+
+Conversion of 'Pandoc' documents to OpenDocument XML.
+-}
+module Text.Pandoc.Writers.OpenDocument ( writeOpenDocument ) where
+import Control.Arrow ((***), (>>>))
+import Control.Monad (unless, liftM)
+import Control.Monad.State.Strict ( StateT(..), modify, gets, lift )
+import Data.Char (chr)
+import Data.Foldable (find)
+import Data.List (sortOn, sortBy)
+import qualified Data.List as L
+import qualified Data.Map as Map
+import Data.Ord (comparing, Down (Down))
+import qualified Data.Set as Set
+import Data.Text (Text)
+import qualified Data.Text as T
+import Text.Collate.Lang (Lang (..), parseLang)
+import Text.Pandoc.Class.PandocMonad (PandocMonad, report)
+import Text.Pandoc.Translations (translateTerm)
+import Text.Pandoc.Definition
+import qualified Text.Pandoc.Builder as B
+import Text.Pandoc.Logging
+import Text.Pandoc.Options
+import Text.DocLayout hiding (link)
+import Text.Pandoc.Shared (linesToPara, tshow, blocksToInlines)
+import Text.Pandoc.Templates (renderTemplate)
+import qualified Text.Pandoc.Translations as Term (Term(Figure, Table))
+import Text.Pandoc.Walk
+import Text.Pandoc.Writers.Math
+import Text.Pandoc.Writers.Shared
+import qualified Text.Pandoc.Writers.AnnotatedTable as Ann
+import Text.Pandoc.XML
+import Text.Printf (printf)
+import Text.Pandoc.Highlighting (highlight)
+import Skylighting (FormatOptions(..), SourceLine, Token)
+
+-- | Auxiliary function to convert Plain block to Para.
+plainToPara :: Block -> Block
+plainToPara (Plain x) = Para x
+plainToPara x         = x
+
+-- Names of predefined styles in the reference.odt; see data/odt/styles.xml.
+defaultBulletListStyleName, defaultNumberedListStyleName :: Text
+defaultBulletListStyleName   = "List_20_1"
+defaultNumberedListStyleName = "Numbering_20_1"
+
+bulletItemStyleName, bulletItemTightStyleName,
+  numberItemStyleName, numberItemTightStyleName :: Text
+bulletItemStyleName      = "List_20_Bullet"
+bulletItemTightStyleName = "List_20_Bullet_20_Tight"
+numberItemStyleName      = "List_20_Number"
+numberItemTightStyleName = "List_20_Number_20_Tight"
+
+-- | Predefined inline style names for single-style spans.
+wellKnownTextStyle :: Set.Set TextStyle -> Maybe Text
+wellKnownTextStyle s = case Set.toList s of
+  [Italic] -> Just "Emphasis"
+  [Bold]   -> Just "Strong_20_Emphasis"
+  [Strike] -> Just "Strikeout"
+  [Sub]    -> Just "Subscript"
+  [Sup]    -> Just "Superscript"
+  [Pre]    -> Just "Source_20_Text"
+  _        -> Nothing
+
+--
+-- OpenDocument writer
+--
+
+type OD m = StateT WriterState m
+
+data ReferenceType
+  = HeaderRef
+  | TableRef
+  | FigureRef
+
+data WriterState =
+    WriterState { stNotes          :: [Doc Text]
+                , stTableStyles    :: [Doc Text]
+                , stParaStyles     :: [Doc Text]
+                , stListOverrides  :: Map.Map (ListNumberStyle,ListNumberDelim)
+                                        (Text, Doc Text)
+                , stTextStyles     :: Map.Map (Set.Set TextStyle)
+                                        (Text, Doc Text)
+                , stTextStyleAttr  :: Set.Set TextStyle
+                , stIndentPara     :: Int
+                , stInDefinition   :: Bool
+                , stTight          :: Bool
+                , stFirstPara      :: Bool
+                , stImageId        :: Int
+                , stTableCaptionId :: Int
+                , stImageCaptionId :: Int
+                , stIdentTypes     :: [(Text,ReferenceType)]
+                }
+
+defaultWriterState :: WriterState
+defaultWriterState =
+    WriterState { stNotes          = []
+                , stTableStyles    = []
+                , stParaStyles     = []
+                , stListOverrides  = Map.empty
+                , stTextStyles     = Map.empty
+                , stTextStyleAttr  = Set.empty
+                , stIndentPara     = 0
+                , stInDefinition   = False
+                , stTight          = False
+                , stFirstPara      = False
+                , stImageId        = 1
+                , stTableCaptionId = 1
+                , stImageCaptionId = 1
+                , stIdentTypes     = []
+                }
+
+when :: Bool -> Doc Text -> Doc Text
+when p a = if p then a else empty
+
+addTableStyle :: PandocMonad m => Doc Text -> OD m ()
+addTableStyle i = modify $ \s -> s { stTableStyles = i : stTableStyles s }
+
+addNote :: PandocMonad m => Doc Text -> OD m ()
+addNote i = modify $ \s -> s { stNotes = i : stNotes s }
+
+addParaStyle :: PandocMonad m => Doc Text -> OD m ()
+addParaStyle i = modify $ \s -> s { stParaStyles = i : stParaStyles s }
+
+addTextStyle :: PandocMonad m
+             => Set.Set TextStyle -> (Text, Doc Text) -> OD m ()
+addTextStyle attrs i = modify $ \s ->
+  s { stTextStyles = Map.insert attrs i (stTextStyles s) }
+
+increaseIndent :: PandocMonad m => OD m ()
+increaseIndent = modify $ \s -> s { stIndentPara = 1 + stIndentPara s }
+
+resetIndent :: PandocMonad m => OD m ()
+resetIndent = modify $ \s -> s { stIndentPara = stIndentPara s - 1 }
+
+setInDefinitionList :: PandocMonad m => Bool -> OD m ()
+setInDefinitionList b = modify $  \s -> s { stInDefinition = b }
+
+setFirstPara :: PandocMonad m => OD m ()
+setFirstPara =  modify $  \s -> s { stFirstPara = True }
+
+inParagraphTags :: PandocMonad m => Doc Text -> OD m (Doc Text)
+inParagraphTags d = do
+  b <- gets stFirstPara
+  a <- if b
+       then do modify $ \st -> st { stFirstPara = False }
+               return [("text:style-name", "First_20_paragraph")]
+       else    return   [("text:style-name", "Text_20_body")]
+  return $ inTags False "text:p" a d
+
+inParagraphTagsWithStyle :: Text -> Doc Text -> Doc Text
+inParagraphTagsWithStyle sty = inTags False "text:p" [("text:style-name", sty)]
+
+inSpanTags :: Text -> Doc Text -> Doc Text
+inSpanTags s = inTags False "text:span" [("text:style-name",s)]
+
+withAlteredTextStyles :: PandocMonad m
+                       => (Set.Set TextStyle -> Set.Set TextStyle) -> OD m a -> OD m a
+withAlteredTextStyles f action = do
+  oldTextStyleAttr <- gets stTextStyleAttr
+  modify $ \st -> st{ stTextStyleAttr = f oldTextStyleAttr }
+  res <- action
+  modify $ \st -> st{ stTextStyleAttr = oldTextStyleAttr }
+  return res
+
+withTextStyle :: PandocMonad m => TextStyle -> OD m a -> OD m a
+withTextStyle s = withAlteredTextStyles (Set.insert s)
+
+inTextStyle :: PandocMonad m => Doc Text -> OD m (Doc Text)
+inTextStyle d = do
+  at <- gets stTextStyleAttr
+  if Set.null at
+     then return d
+     else case wellKnownTextStyle at of
+       Just styleName -> return $
+         inTags False "text:span" [("text:style-name", styleName)] d
+       Nothing -> do
+         styles <- gets stTextStyles
+         case Map.lookup at styles of
+              Just (styleName, _) -> return $
+                inTags False "text:span" [("text:style-name",styleName)] d
+              Nothing -> do
+                let styleName = "T" <> tshow (Map.size styles + 1)
+                addTextStyle at (styleName,
+                       inTags False "style:style"
+                         [("style:name", styleName)
+                         ,("style:family", "text")]
+                         $ selfClosingTag "style:text-properties"
+                            (sortOn fst . Map.toList
+                                  $ L.foldl' textStyleAttr mempty (Set.toList at)))
+                return $ inTags False
+                    "text:span" [("text:style-name",styleName)] d
+
+formulaStyles :: [Doc Text]
+formulaStyles = [formulaStyle InlineMath, formulaStyle DisplayMath]
+
+formulaStyle :: MathType -> Doc Text
+formulaStyle mt = inTags False "style:style"
+  [("style:name", if mt == InlineMath then "fr1" else "fr2")
+  ,("style:family", "graphic")
+  ,("style:parent-style-name", "Formula")]
+  $ selfClosingTag "style:graphic-properties" $ if mt == InlineMath then
+                                                  [("style:vertical-pos", "middle")
+                                                  ,("style:vertical-rel", "text")]
+                                                else
+                                                  [("style:vertical-pos",   "middle")
+                                                  ,("style:vertical-rel",   "text")
+                                                  ,("style:horizontal-pos", "center")
+                                                  ,("style:horizontal-rel", "paragraph-content")
+                                                  ,("style:wrap",           "none")]
+
+inBookmarkTags :: Text -> Doc Text -> Doc Text
+inBookmarkTags ident d =
+  selfClosingTag "text:bookmark-start" [ ("text:name", ident) ]
+  <> d <>
+  selfClosingTag "text:bookmark-end" [ ("text:name", ident) ]
+
+selfClosingBookmark :: Text -> Doc Text
+selfClosingBookmark ident =
+  selfClosingTag "text:bookmark" [("text:name", ident)]
+
+inHeaderTags :: PandocMonad m => Int -> Text -> Doc Text -> OD m (Doc Text)
+inHeaderTags i ident d =
+  return $ inTags False "text:h" [ ("text:style-name", "Heading_20_" <> tshow i)
+                                 , ("text:outline-level", tshow i)]
+         $ if T.null ident
+              then d
+              else inBookmarkTags ident d
+
+inQuotes :: QuoteType -> Doc Text -> Doc Text
+inQuotes SingleQuote s = char '\8216' <> s <> char '\8217'
+inQuotes DoubleQuote s = char '\8220' <> s <> char '\8221'
+
+handleSpaces :: Text -> Doc Text
+handleSpaces s = case T.uncons s of
+  Just (' ', _) -> genTag s
+  Just ('\t',x) -> selfClosingTag "text:tab" [] <> rm x
+  _             -> rm s
+  where
+    genTag = T.span (==' ') >>> tag . T.length *** rm >>> uncurry (<>)
+    tag n  = when (n /= 0) $ selfClosingTag "text:s" [("text:c", tshow n)]
+    rm t   = case T.uncons t of
+      Just ( ' ',xs) -> char ' ' <> genTag xs
+      Just ('\t',xs) -> selfClosingTag "text:tab" [] <> genTag xs
+      Just (   x,xs) -> char x <> rm xs
+      Nothing        -> empty
+
+-- | Convert Pandoc document to string in OpenDocument format.
+writeOpenDocument :: PandocMonad m => WriterOptions -> Pandoc -> m Text
+writeOpenDocument opts (Pandoc meta blocks) = do
+  setupTranslations meta
+  let colwidth = if writerWrapText opts == WrapAuto
+                    then Just $ writerColumns opts
+                    else Nothing
+  let meta' = case lookupMetaBlocks "abstract" meta of
+                [] -> meta
+                xs -> B.setMeta "abstract"
+                        (B.divWith ("",[],[("custom-style","Abstract")])
+                          (B.fromList xs))
+                        meta
+  ((body, metadata),s) <- flip runStateT
+        defaultWriterState $ do
+           let collectBlockIdent (Header _ (ident,_,_) _)      = [(ident,HeaderRef)]
+               collectBlockIdent (Figure (ident,_,_) _ _ )     = [(ident,FigureRef)]
+               collectBlockIdent (Table (ident,_,_) _ _ _ _ _) = [(ident,TableRef)]
+               collectBlockIdent _                             = []
+           modify $ \s -> s{ stIdentTypes = query collectBlockIdent blocks }
+           m <- metaToContext opts
+                  (inlinesToOpenDocument opts . blocksToInlines)
+                  (fmap chomp . inlinesToOpenDocument opts)
+                  meta'
+           b <- blocksToOpenDocument opts blocks
+           return (b, m)
+  let styles   = stTableStyles s ++ stParaStyles s ++ formulaStyles ++
+                     map snd (sortBy (comparing (Down . fst)) (
+                        Map.elems (stTextStyles s)))
+  let listStyles  = map snd (Map.elems (stListOverrides s))
+  let automaticStyles = vcat $ reverse styles ++ listStyles
+  let context = defField "body" body
+              . defField "toc" (writerTableOfContents opts)
+              . defField "toc-depth" (tshow $ writerTOCDepth opts)
+              . defField "automatic-styles" automaticStyles
+              $ metadata
+  return $ render colwidth $
+    case writerTemplate opts of
+       Nothing  -> body
+       Just tpl -> renderTemplate tpl context
+
+withParagraphStyle :: PandocMonad m
+                   => WriterOptions -> Text -> [Block] -> OD m (Doc Text)
+withParagraphStyle  o s (b:bs)
+    | Para l <- b = go =<< inParagraphTagsWithStyle s <$> inlinesToOpenDocument o l
+    | otherwise   = go =<< blockToOpenDocument o b
+    where go i = (<>) i <$>  withParagraphStyle o s bs
+withParagraphStyle _ _ [] = return empty
+
+inPreformattedTags :: PandocMonad m => [Doc Text] -> OD m (Doc Text)
+inPreformattedTags s =
+  return $ inParagraphTagsWithStyle "Preformatted_20_Text" $ hcat s
+
+-- | Get the list-style name to use for an ordered list with the given
+-- numbering style and delimiter, registering an override automatic style
+-- if needed.  Lists with default style/delimiter use the predefined
+-- @Numbering_20_1@ style and no override is generated.
+orderedListStyleName :: PandocMonad m
+                     => ListNumberStyle -> ListNumberDelim -> OD m Text
+orderedListStyleName ns nd
+  | (ns == DefaultStyle || ns == Decimal) &&
+    (nd == DefaultDelim || nd == Period) =
+      return defaultNumberedListStyleName
+  | otherwise = do
+      overrides <- gets stListOverrides
+      case Map.lookup (ns, nd) overrides of
+        Just (name, _) -> return name
+        Nothing -> do
+          let name = "Pandoc_5f_Numbering_5f_" <>
+                       tshow (Map.size overrides + 1)
+              doc = inTags True "text:list-style"
+                      [("style:name", name)]
+                      (vcat (map (orderedListLevel ns nd) [1..10]))
+          modify $ \s -> s { stListOverrides =
+                               Map.insert (ns, nd) (name, doc)
+                                          (stListOverrides s) }
+          return name
+
+orderedListLevel :: ListNumberStyle -> ListNumberDelim -> Int -> Doc Text
+orderedListLevel ns nd lvl =
+    let suffix = case nd of
+                   OneParen  -> [("style:num-suffix", ")")]
+                   TwoParens -> [("style:num-prefix", "(")
+                                ,("style:num-suffix", ")")]
+                   _         -> [("style:num-suffix", ".")]
+        format = case ns of
+                   UpperAlpha -> "A"
+                   LowerAlpha -> "a"
+                   UpperRoman -> "I"
+                   LowerRoman -> "i"
+                   _          -> "1"
+    in inTags True "text:list-level-style-number"
+              ([ ("text:level"      , tshow lvl)
+               , ("text:style-name" , "Numbering_20_Symbols")
+               , ("style:num-format", format)
+               ] ++ suffix)
+              (selfClosingTag "style:list-level-properties"
+                 [ ("text:space-before",
+                      T.pack (printf "%.4fin" (0.1972 * fromIntegral (lvl - 1) :: Double)))
+                 , ("text:min-label-width", "0.1965in")
+                 , ("text:min-label-distance", "0.1in")
+                 ])
+
+orderedListToOpenDocument :: PandocMonad m
+                          => WriterOptions -> Text -> [[Block]]
+                          -> OD m (Doc Text)
+orderedListToOpenDocument o paraName bs =
+    vcat . map (inTagsIndented "text:list-item") <$>
+    mapM (orderedItemToOpenDocument o paraName . map plainToPara) bs
+
+orderedItemToOpenDocument :: PandocMonad m
+                          => WriterOptions -> Text -> [Block]
+                          -> OD m (Doc Text)
+orderedItemToOpenDocument  o paraName bs = vcat <$> mapM go bs
+ where go (OrderedList a l) = orderedList a l
+       go (Para          l) = inParagraphTagsWithStyle paraName <$>
+                                inlinesToOpenDocument o l
+       go b                 = blockToOpenDocument o b
+       orderedList a@(_,ns,nd) l = do
+         lstName <- orderedListStyleName ns nd
+         let pn = if isTightList l then numberItemTightStyleName
+                                   else numberItemStyleName
+         let listAttrs = ("text:style-name", lstName) : startValueAttr a
+         inTags True "text:list" listAttrs <$>
+           orderedListToOpenDocument o pn l
+
+-- | Generate a @text:start-value@ attribute when the start value is not 1.
+startValueAttr :: ListAttributes -> [(Text, Text)]
+startValueAttr (s,_,_) | s /= 1 = [("text:start-value", tshow s)]
+startValueAttr _                = []
+
+isTightList :: [[Block]] -> Bool
+isTightList []          = False
+isTightList (b:_)
+    | Plain {} : _ <- b = True
+    | otherwise         = False
+
+bulletListToOpenDocument :: PandocMonad m
+                         => WriterOptions -> [[Block]] -> OD m (Doc Text)
+bulletListToOpenDocument o b = do
+  let pn = if isTightList b then bulletItemTightStyleName
+                            else bulletItemStyleName
+  is <- listItemsToOpenDocument pn o b
+  return $ inTags True "text:list"
+             [("text:style-name", defaultBulletListStyleName)] is
+
+listItemsToOpenDocument :: PandocMonad m
+                        => Text -> WriterOptions -> [[Block]] -> OD m (Doc Text)
+listItemsToOpenDocument s o is =
+    vcat . map (inTagsIndented "text:list-item") <$> mapM (withParagraphStyle o s . map plainToPara) is
+
+deflistItemToOpenDocument :: PandocMonad m
+                          => WriterOptions -> ([Inline],[[Block]]) -> OD m (Doc Text)
+deflistItemToOpenDocument o (t,d) = do
+  let ts = if isTightList d
+           then "Definition_20_Term_20_Tight"       else "Definition_20_Term"
+      ds = if isTightList d
+           then "Definition_20_Definition_20_Tight" else "Definition_20_Definition"
+  t' <- withParagraphStyle o ts [Para t]
+  d' <- liftM vcat $ mapM (withParagraphStyle o ds . map plainToPara) d
+  return $ t' $$ d'
+
+inBlockQuote :: PandocMonad m
+             => WriterOptions -> Text -> [Block] -> OD m (Doc Text)
+inBlockQuote  o sty (b:bs)
+    | BlockQuote l <- b = do increaseIndent
+                             ni <- paraStyle
+                                   [("style:parent-style-name","Quotations")]
+                             inner <- inBlockQuote o ni (map plainToPara l)
+                             resetIndent
+                             go inner
+    | Para       l <- b = go =<< inParagraphTagsWithStyle sty <$> inlinesToOpenDocument o l
+    | otherwise         = go =<< blockToOpenDocument o b
+    where go  block  = ($$) block <$> inBlockQuote o sty bs
+inBlockQuote     _ _ [] = return empty
+
+-- | Convert a list of Pandoc blocks to OpenDocument.
+blocksToOpenDocument :: PandocMonad m => WriterOptions -> [Block] -> OD m (Doc Text)
+blocksToOpenDocument o b = vcat <$> mapM (blockToOpenDocument o) b
+
+-- | Convert a Pandoc block element to OpenDocument.
+blockToOpenDocument :: PandocMonad m => WriterOptions -> Block -> OD m (Doc Text)
+blockToOpenDocument o = \case
+    Plain          b -> if null b
+                        then return empty
+                        else inParagraphTags =<< inlinesToOpenDocument o b
+    Para           b -> if null b &&
+                           not (isEnabled Ext_empty_paragraphs o)
+                        then return empty
+                        else inParagraphTags =<< inlinesToOpenDocument o b
+    LineBlock      b -> blockToOpenDocument o $ linesToPara b
+    Div attr xs      -> mkDiv attr xs
+    Header     i (ident,_,_) b -> do
+      setFirstPara
+      inHeaderTags i ident =<< inlinesToOpenDocument o b
+    BlockQuote     b -> setFirstPara >> mkBlockQuote b
+    DefinitionList b -> setFirstPara >> defList b
+    BulletList     b -> setFirstPara >> bulletListToOpenDocument o b
+    OrderedList  a b -> setFirstPara >> orderedList a b
+    CodeBlock attrs s -> do
+      setFirstPara
+      case writerHighlightMethod o of
+        Skylighting {} ->
+          case highlight (writerSyntaxMap o) formatOpenDocument attrs s of
+                Right h  -> return $ flush . vcat $ map (inTags True "text:p"
+                                          [("text:style-name",
+                                            "Preformatted_20_Text")] . hcat) h
+                Left msg -> do
+                  unless (T.null msg) $ report $ CouldNotHighlight msg
+                  unhighlighted s
+        _ -> unhighlighted s
+    Table a bc s th tb tf -> setFirstPara >>
+                              table o (Ann.toTable a bc s th tb tf)
+    HorizontalRule   -> setFirstPara >> return (selfClosingTag "text:p"
+                         [ ("text:style-name", "Horizontal_20_Line") ])
+    b@(RawBlock f s) -> if f == Format "opendocument"
+                        then return $ text $ T.unpack s
+                        else empty <$ report (BlockNotRendered b)
+    Figure a capt b  -> figure o a capt b
+    where
+      defList       b = do setInDefinitionList True
+                           r <- vcat  <$> mapM (deflistItemToOpenDocument o) b
+                           setInDefinitionList False
+                           return r
+      unhighlighted s = flush . vcat <$>
+            (mapM ((inPreformattedTags . (:[])) . preformatted) (T.lines s))
+      mkDiv    attr s = do
+        let (ident,_,kvs) = attr
+            i = withLangFromAttr attr $
+                case lookup "custom-style" kvs of
+                  Just sty -> withParagraphStyle o sty s
+                  _        -> blocksToOpenDocument o s
+            mkBookmarkedDiv = inTags False "text:section" [("text:name", ident)]
+        if T.null ident
+          then i
+          else fmap mkBookmarkedDiv i
+      mkBlockQuote  b = do sty <- paraStyle
+                                    [("style:parent-style-name","Quotations")]
+                           inBlockQuote o sty (map plainToPara b)
+      orderedList a@(_,ns,nd) b = do
+        lstName <- orderedListStyleName ns nd
+        let pn = if isTightList b then numberItemTightStyleName
+                                  else numberItemStyleName
+        let listAttrs = ("text:style-name", lstName) : startValueAttr a
+        inTags True "text:list" listAttrs <$>
+          orderedListToOpenDocument o pn b
+      table :: PandocMonad m => WriterOptions -> Ann.Table -> OD m (Doc Text)
+      table opts
+          (Ann.Table (ident, _, _) (Caption _ c) colspecs thead tbodies tfoot) = do
+        tn <- length <$> gets stTableStyles
+        pn <- length <$> gets stParaStyles
+        let  genIds      = map chr [65..]
+             name        = "Table" <> tshow (tn + 1)
+             (aligns, mwidths) = unzip colspecs
+             fromWidth (ColWidth w) | w > 0 = w
+             fromWidth _                    = 0
+             widths = map fromWidth mwidths
+             textWidth   = sum widths
+             columnIds   = zip genIds widths
+             mkColumn  n = selfClosingTag "table:table-column" [("table:style-name", name <> "." <> T.singleton (fst n))]
+             columns     = map mkColumn columnIds
+             paraHStyles = paraTableStyles "Heading"  pn aligns
+             paraStyles  = paraTableStyles "Contents" (pn + length (newPara paraHStyles)) aligns
+             newPara     = map snd . filter (not . isEmpty . snd)
+        addTableStyle $ tableStyle tn textWidth columnIds
+        mapM_ addParaStyle . newPara $ paraHStyles ++ paraStyles
+        captionDoc <- if null c
+                      then return empty
+                      else inlinesToOpenDocument o (blocksToInlines c) >>=
+                             if isEnabled Ext_native_numbering o
+                                then numberedTableCaption ident
+                                else unNumberedCaption "TableCaption"
+        th <- colHeadsToOpenDocument o (map fst paraHStyles) thead
+        tr <- mapM (tableBodyToOpenDocument o (map fst paraHStyles) (map fst paraStyles)) tbodies
+        tf <- tableFootToOpenDocument o (map fst paraStyles) tfoot
+        let tableDoc = inTags True "table:table" [
+                            ("table:name"      , name)
+                          , ("table:style-name", name)
+                          ] (vcat columns $$ th $$ vcat tr $$ tf)
+        return $
+          case writerTableCaptionPosition opts of
+            CaptionAbove -> captionDoc $$ tableDoc
+            CaptionBelow -> tableDoc $$ captionDoc
+      figure opts (ident, _, _) (Caption _ longcapt) body =
+        case blocksToInlines longcapt of
+          [] ->
+            withParagraphStyle o "Figure" body
+          caption -> do
+            imageDoc <- withParagraphStyle o "FigureWithCaption" $
+                        map (\case {Plain i -> Para i; b -> b}) body
+            captionDoc <- inlinesToOpenDocument o caption >>=
+                          if isEnabled Ext_native_numbering o
+                          then numberedFigureCaption ident
+                          else unNumberedCaption "FigureCaption"
+            return $
+              case writerFigureCaptionPosition opts of
+                CaptionAbove -> captionDoc $$ imageDoc
+                CaptionBelow -> imageDoc $$ captionDoc
+
+
+numberedTableCaption :: PandocMonad m => Text -> Doc Text -> OD m (Doc Text)
+numberedTableCaption ident caption = do
+    id' <- gets stTableCaptionId
+    modify (\st -> st{ stTableCaptionId = id' + 1 })
+    capterm <- translateTerm Term.Table
+    return $ numberedCaption "TableCaption" capterm "Table" id' ident caption
+
+numberedFigureCaption :: PandocMonad m => Text -> Doc Text -> OD m (Doc Text)
+numberedFigureCaption ident caption = do
+    id' <- gets stImageCaptionId
+    modify (\st -> st{ stImageCaptionId = id' + 1 })
+    capterm <- translateTerm Term.Figure
+    return $ numberedCaption "FigureCaption" capterm  "Illustration" id' ident caption
+
+numberedCaption :: Text -> Text -> Text -> Int -> Text -> Doc Text -> Doc Text
+numberedCaption style term name num ident caption =
+    let t = text $ T.unpack term
+        r = num - 1
+        ident' = case ident of
+          "" -> "ref" <> name <> tshow r
+          _ -> ident
+        s = inTags False "text:sequence" [ ("text:ref-name", ident'),
+                                           ("text:name", name),
+                                           ("text:formula", "ooow:" <> name <> "+1"),
+                                           ("style:num-format", "1") ] $ text $ show num
+        c = text ": "
+    in inParagraphTagsWithStyle style $ hcat [ t, text " ", s, c, caption ]
+
+unNumberedCaption :: Monad m => Text -> Doc Text -> OD m (Doc Text)
+unNumberedCaption style caption = return $ inParagraphTagsWithStyle style caption
+
+colHeadsToOpenDocument :: PandocMonad m
+                       => WriterOptions -> [Text] -> Ann.TableHead
+                       -> OD m (Doc Text)
+colHeadsToOpenDocument o ns (Ann.TableHead _ hs) =
+  case hs of
+    [] -> return empty
+    xs -> inTagsIndented "table:table-header-rows" <$>
+      tableHeaderRowsToOpenDocument o ns "TableHeaderRowCell" xs
+
+tableHeaderRowsToOpenDocument :: PandocMonad m
+                              => WriterOptions -> [Text] -> Text -> [Ann.HeaderRow]
+                              -> OD m (Doc Text)
+tableHeaderRowsToOpenDocument o ns s headerRows =
+  vcat <$> mapM headerRowToOpenDocument headerRows
+  where
+    headerRowToOpenDocument (Ann.HeaderRow _ _ c) =
+      inTagsIndented "table:table-row" .
+      vcat <$> mapM (tableItemToOpenDocument o s) (zip ns c)
+
+tableBodyToOpenDocument:: PandocMonad m
+                       => WriterOptions -> [Text] -> [Text] -> Ann.TableBody
+                       -> OD m (Doc Text)
+tableBodyToOpenDocument o headns bodyns tb = do
+    let (Ann.TableBody _ _ hs r) = tb
+    tableRowHeaders <- tableHeaderRowsToOpenDocument o headns "TableRowCell" hs
+    tableRows <- mapM (tableRowToOpenDocument o headns bodyns) r
+    return $ tableRowHeaders $$ vcat tableRows
+
+tableFootToOpenDocument :: PandocMonad m
+                        => WriterOptions -> [Text] -> Ann.TableFoot
+                        -> OD m (Doc Text)
+tableFootToOpenDocument o ns (Ann.TableFoot _ r) =
+  tableHeaderRowsToOpenDocument o ns "TableRowCell" r
+
+tableRowToOpenDocument :: PandocMonad m
+                       => WriterOptions -> [Text] -> [Text] -> Ann.BodyRow
+                       -> OD m (Doc Text)
+
+tableRowToOpenDocument o headns bodyns r =
+    let (Ann.BodyRow _ _ rowheaders cs) = r
+    in inTagsIndented "table:table-row" . vcat <$>
+    mapM (tableItemToOpenDocument o "TableRowCell")
+        ((zip headns rowheaders) ++ (zip (drop (length rowheaders) bodyns) cs))
+
+colspanAttrib :: ColSpan -> [(Text, Text)]
+colspanAttrib cs =
+  case cs of
+    ColSpan 1 -> mempty
+    ColSpan n -> [("table:number-columns-spanned", tshow n)]
+
+rowspanAttrib :: RowSpan -> [(Text, Text)]
+rowspanAttrib rs =
+  case rs of
+    RowSpan 1 -> mempty
+    RowSpan n -> [("table:number-rows-spanned", tshow n)]
+
+alignAttrib :: Alignment -> [(Text,Text)]
+alignAttrib a = case a of
+  AlignRight  -> ("fo:text-align","end") : style
+  AlignCenter -> ("fo:text-align","center") : style
+  _ -> []
+  where
+    style = [("style:justify-single-word","false")]
+
+tableItemToOpenDocument :: PandocMonad m
+                        => WriterOptions -> Text -> (Text,Ann.Cell)
+                        -> OD m (Doc Text)
+tableItemToOpenDocument o s (n,c) = do
+  let (Ann.Cell _colspecs _colnum (Cell _ align rs cs i) ) = c
+      csa = colspanAttrib cs
+      rsa = rowspanAttrib rs
+      aa = alignAttrib align
+      a = [ ("table:style-name" , s )
+          , ("office:value-type", "string" ) ] ++ csa ++ rsa
+  itemParaStyle <- paraStyleFromParent n aa
+  inTags True "table:table-cell" a <$>
+    withParagraphStyle o itemParaStyle (map plainToPara i)
+
+-- | Convert a list of inline elements to OpenDocument.
+inlinesToOpenDocument :: PandocMonad m => WriterOptions -> [Inline] -> OD m (Doc Text)
+inlinesToOpenDocument o l = hcat <$> toChunks o l
+
+toChunks :: PandocMonad m => WriterOptions -> [Inline] -> OD m [Doc Text]
+toChunks _ [] = return []
+toChunks o (x : xs)
+  | isChunkable x = do
+        contents <- (inTextStyle . hcat) =<<
+                     mapM (inlineToOpenDocument o) (x:ys)
+        rest <- toChunks o zs
+        return (contents : rest)
+  | otherwise     = do
+        contents <- inlineToOpenDocument o x
+        rest <- toChunks o xs
+        return (contents : rest)
+  where (ys, zs) = span isChunkable xs
+
+isChunkable :: Inline -> Bool
+isChunkable (Str _)   = True
+isChunkable Space     = True
+isChunkable SoftBreak = True
+isChunkable _         = False
+
+-- | Convert an inline element to OpenDocument.
+inlineToOpenDocument :: PandocMonad m => WriterOptions -> Inline -> OD m (Doc Text)
+inlineToOpenDocument o ils
+  = case ils of
+    Space         -> return space
+    SoftBreak
+     | writerWrapText o == WrapPreserve
+                  -> return $ preformatted "\n"
+     | otherwise  -> return space
+    Span ("", ["mark"], []) xs ->
+      inTags False "text:span" [("text:style-name","Highlighted")] <$>
+        inlinesToOpenDocument o xs
+    Span attr xs  -> mkSpan attr xs
+    LineBreak     -> return $ selfClosingTag "text:line-break" []
+    Str         s -> return $ handleSpaces $ escapeStringForXML s
+    Emph        l -> withTextStyle Italic $ inlinesToOpenDocument o l
+    Underline   l -> withTextStyle Under  $ inlinesToOpenDocument o l
+    Strong      l -> withTextStyle Bold   $ inlinesToOpenDocument o l
+    Strikeout   l -> withTextStyle Strike $ inlinesToOpenDocument o l
+    Superscript l -> withTextStyle Sup    $ inlinesToOpenDocument o l
+    Subscript   l -> withTextStyle Sub    $ inlinesToOpenDocument o l
+    SmallCaps   l -> withTextStyle SmallC $ inlinesToOpenDocument o l
+    Quoted    t l -> inQuotes t <$> inlinesToOpenDocument o l
+    Code      attrs s -> case writerHighlightMethod o of
+      Skylighting {} ->
+        case highlight (writerSyntaxMap o) formatOpenDocument attrs s of
+                Right h  -> inlinedCode $ mconcat $ mconcat h
+                Left msg -> do
+                  unless (T.null msg) $ report $ CouldNotHighlight msg
+                  unhighlighted s
+      _ -> unhighlighted s
+    Math      t s -> lift (texMathToInlines t s) >>=
+                         inlinesToOpenDocument o
+    Cite      _ l -> inlinesToOpenDocument o l
+    RawInline f s -> if f == Format "opendocument"
+                       then return $ text $ T.unpack s
+                       else do
+                         report $ InlineNotRendered ils
+                         return empty
+    Link _ l (s,t) -> do
+      identTypes <- gets stIdentTypes
+      mkLink o identTypes s t <$> inlinesToOpenDocument o l
+    Image attr _ (s,t) -> mkImg attr s t
+    Note        l  -> mkNote l
+    where
+      unhighlighted s = inlinedCode $ preformatted s
+      inlinedCode s = return $ inTags False "text:span"
+                                 [("text:style-name", "Source_20_Text")] s
+      mkImg (_, _, kvs) s _ = do
+               id' <- gets stImageId
+               modify (\st -> st{ stImageId = id' + 1 })
+               let getDims [] = []
+                   getDims (("width", w) :xs) = ("svg:width", w)  : getDims xs
+                   getDims (("rel-width", w):xs) = ("style:rel-width", w) : getDims xs
+                   getDims (("height", h):xs) = ("svg:height", h) : getDims xs
+                   getDims (("rel-height", w):xs) = ("style:rel-height", w) : getDims xs
+                   getDims (_:xs) =                             getDims xs
+               return $ inTags False "draw:frame"
+                        (("draw:name", "img" <> tshow id') : getDims kvs) $
+                     selfClosingTag "draw:image" [ ("xlink:href"   , s       )
+                                                 , ("xlink:type"   , "simple")
+                                                 , ("xlink:show"   , "embed" )
+                                                 , ("xlink:actuate", "onLoad")]
+      mkSpan attr xs =  do
+        let (ident,_,kvs) = attr
+            i = maybe id (\sty ->
+                           fmap (inTags False "text:span"
+                                  [ ("text:style-name", sty) ]))
+                  (lookup "custom-style" kvs) .
+                 withLangFromAttr attr $ inlinesToOpenDocument o xs
+            mkBookmarkedSpan b =
+              if isEmpty b
+                then selfClosingBookmark ident
+                else inBookmarkTags ident b
+        if T.null ident
+          then i
+          else fmap mkBookmarkedSpan i
+      mkNote     l = do
+        n <- length <$> gets stNotes
+        let footNote t = inTags False "text:note"
+                         [ ("text:id"        , "ftn" <> tshow n)
+                         , ("text:note-class", "footnote"     )] $
+                         inTagsSimple "text:note-citation" (text . show $ n + 1) <>
+                         inTagsSimple "text:note-body" t
+        nn <- footNote <$> withAlteredTextStyles (const mempty)
+                            (withParagraphStyle o "Footnote" l)
+        addNote nn
+        return nn
+
+formatOpenDocument :: FormatOptions -> [SourceLine] -> [[Doc Text]]
+formatOpenDocument _fmtOpts = map (map toHlTok)
+toHlTok :: Token -> Doc Text
+toHlTok (toktype,tok) =
+  inTags False "text:span" [("text:style-name", T.pack $ show toktype)] $ preformatted tok
+
+preformatted :: Text -> Doc Text
+preformatted s = handleSpaces $ escapeStringForXML s
+
+mkLink :: WriterOptions -> [(Text,ReferenceType)] -> Text -> Text -> Doc Text -> Doc Text
+mkLink o identTypes s t d =
+  let maybeIdentAndType = case T.uncons s of
+                            Just ('#', ident) -> find ((ident ==) . fst) identTypes
+                            _                 -> Nothing
+      d' = inSpanTags "Definition" d
+      ref refType format ident       = inTags False refType
+                                       [ ("text:reference-format", format ),
+                                         ("text:ref-name", ident) ]
+      inlineSpace                    = selfClosingTag "text:s" []
+      bookmarkRef                    = ref "text:bookmark-ref"
+      bookmarkRefNumber ident        = bookmarkRef "number" ident mempty
+      bookmarkRefName ident          = bookmarkRef "text" ident d
+      bookmarkRefNameNumber ident    = bookmarkRefNumber ident <> inlineSpace <> bookmarkRefName ident
+      bookmarkRef'
+        | isEnabled Ext_xrefs_number o && isEnabled Ext_xrefs_name o = bookmarkRefNameNumber
+        | isEnabled Ext_xrefs_name o                                 = bookmarkRefName
+        | otherwise                                                  = bookmarkRefNumber
+      sequenceRef                    = ref "text:sequence-ref"
+      sequenceRefNumber ident        = sequenceRef "value" ident mempty
+      sequenceRefName ident          = sequenceRef "caption" ident d
+      sequenceRefNameNumber ident    = sequenceRefNumber ident <> inlineSpace <> sequenceRefName ident
+      sequenceRef'
+        | isEnabled Ext_xrefs_number o && isEnabled Ext_xrefs_name o = sequenceRefNameNumber
+        | isEnabled Ext_xrefs_name o                                 = sequenceRefName
+        | otherwise                                                  = sequenceRefNumber
+      link = inTags False "text:a" [ ("xlink:type" , "simple")
+                                          , ("xlink:href" , s       )
+                                          , ("office:name", t       )
+                                          ] d'
+      linkOrReference = case maybeIdentAndType of
+                          Just (ident, HeaderRef) -> bookmarkRef' ident
+                          Just (ident, TableRef)  -> sequenceRef' ident
+                          Just (ident, FigureRef) -> sequenceRef' ident
+                          _                       -> link
+      in if isEnabled Ext_xrefs_name o || isEnabled Ext_xrefs_number o
+            then linkOrReference
+            else link
+
+tableStyle :: Int -> Double -> [(Char,Double)] -> Doc Text
+tableStyle num textWidth wcs =
+    let tableId        = "Table" <> tshow (num + 1)
+        tableWidthAttr :: [(Text,Text)]
+        tableWidthAttr
+          | textWidth <= 1 && textWidth > 0 = [("style:rel-width",
+                                                T.pack (show (round (textWidth * 100) :: Int) <> "%"))]
+          | otherwise    = []
+        table          = inTags True "style:style"
+                         [("style:name", tableId)
+                         ,("style:family", "table")] $
+                         selfClosingTag "style:table-properties"
+                         (("table:align", "center") : tableWidthAttr)
+        colStyle (c,0) = selfClosingTag "style:style"
+                         [ ("style:name"  , tableId <> "." <> T.singleton c)
+                         , ("style:family", "table-column"       )]
+        colStyle (c,w) = inTags True "style:style"
+                         [ ("style:name"  , tableId <> "." <> T.singleton c)
+                         , ("style:family", "table-column"       )] $
+                         selfClosingTag "style:table-column-properties"
+                         [("style:rel-column-width", T.pack $ printf "%d*" (floor $ w * 65535 :: Integer))]
+        headerRowCellStyle = inTags True "style:style"
+                         [ ("style:name"  , "TableHeaderRowCell")
+                         , ("style:family", "table-cell"    )] $
+                         selfClosingTag "style:table-cell-properties"
+                         [ ("fo:border", "none")]
+        rowCellStyle = inTags True "style:style"
+                         [ ("style:name"  , "TableRowCell")
+                         , ("style:family", "table-cell"    )] $
+                         selfClosingTag "style:table-cell-properties"
+                         [ ("fo:border", "none")]
+        cellStyles = if num == 0
+                     then headerRowCellStyle $$ rowCellStyle
+                     else empty
+        columnStyles   = map colStyle wcs
+    in cellStyles $$ table $$ vcat columnStyles
+
+-- | Generate (or reuse) a paragraph style with the given attributes.
+-- When the only attribute is @style:parent-style-name@ and no
+-- indent/tight overrides are active, the parent name is returned
+-- directly (no @Pn@ automatic style is created), so that the
+-- predefined style passes through unchanged.
+paraStyle :: PandocMonad m => [(Text,Text)] -> OD m Text
+paraStyle attrs = do
+  i  <- (*) (0.5 :: Double) . fromIntegral <$> gets stIndentPara
+  b  <- gets stInDefinition
+  t  <- gets stTight
+  let indentVal = flip (<>) "in" . tshow $ if b then max 0.5 i else i
+      tight     = if t then [ ("fo:margin-top"          , "0in"    )
+                            , ("fo:margin-bottom"       , "0in"    )]
+                       else []
+      indent    = if i /= 0 || b
+                      then [ ("fo:margin-left"         , indentVal)
+                           , ("fo:margin-right"        , "0in"    )
+                           , ("fo:text-indent"         , "0in"    )
+                           , ("style:auto-text-indent" , "false"  )]
+                      else []
+      attributes = indent <> tight
+  case (attributes, attrs) of
+    ([], [("style:parent-style-name", parent)]) -> return parent
+    _ -> do
+      pn <- (+) 1 . length <$> gets stParaStyles
+      let name      = "P" <> tshow pn
+          styleAttr = [ ("style:name"  , name)
+                      , ("style:family", "paragraph") ]
+          paraProps = if null attributes
+                         then mempty
+                         else selfClosingTag
+                                 "style:paragraph-properties" attributes
+      addParaStyle $ inTags True "style:style" (styleAttr <> attrs) paraProps
+      return name
+
+paraStyleFromParent :: PandocMonad m => Text -> [(Text,Text)] -> OD m Text
+paraStyleFromParent parent attrs
+  | null attrs = return parent
+  | otherwise  = do
+      pn <- (+) 1 . length <$> gets stParaStyles
+      let name      = "P" <> tshow pn
+          styleAttr = [ ("style:name"             , name)
+                      , ("style:family"           , "paragraph")
+                      , ("style:parent-style-name", parent)]
+          paraProps = selfClosingTag "style:paragraph-properties" attrs
+      addParaStyle $ inTags True "style:style" styleAttr paraProps
+      return name
+
+paraTableStyles :: Text -> Int -> [Alignment] -> [(Text, Doc Text)]
+paraTableStyles _ _ [] = []
+paraTableStyles t s (a:xs)
+    | AlignRight  <- a = (         pName s, res s "end"   ) : paraTableStyles t (s + 1) xs
+    | AlignCenter <- a = (         pName s, res s "center") : paraTableStyles t (s + 1) xs
+    | otherwise        = ("Table_20_" <> t, empty         ) : paraTableStyles t  s      xs
+    where pName sn = "P" <> tshow (sn + 1)
+          res sn x = inTags True "style:style"
+                     [ ("style:name"             , pName sn        )
+                     , ("style:family"           , "paragraph"     )
+                     , ("style:parent-style-name", "Table_20_" <> t)] $
+                     selfClosingTag "style:paragraph-properties"
+                     [ ("fo:text-align", x)
+                     , ("style:justify-single-word", "false")]
+
+data TextStyle = Italic
+               | Bold
+               | Under
+               | Strike
+               | Sub
+               | Sup
+               | SmallC
+               | Pre
+               | Language Lang
+               deriving ( Eq,Ord )
+
+textStyleAttr :: Map.Map Text Text
+              -> TextStyle
+              -> Map.Map Text Text
+textStyleAttr m = \case
+  Italic -> Map.insert "fo:font-style" "italic" .
+                Map.insert "style:font-style-asian" "italic" .
+                Map.insert "style:font-style-complex" "italic" $ m
+  Bold   -> Map.insert "fo:font-weight" "bold" .
+                Map.insert "style:font-weight-asian" "bold" .
+                Map.insert "style:font-weight-complex" "bold" $ m
+  Under  -> Map.insert "style:text-underline-style" "solid" .
+                Map.insert "style:text-underline-width" "auto" .
+                Map.insert "style:text-underline-color" "font-color" $ m
+  Strike -> Map.insert "style:text-line-through-style" "solid" m
+  Sub    -> Map.insert "style:text-position" "sub 58%" m
+  Sup    -> Map.insert "style:text-position" "super 58%" m
+  SmallC -> Map.insert "fo:font-variant" "small-caps" m
+  Pre    -> Map.insert "style:font-name" "Courier New" .
+            Map.insert "style:font-name-asian" "Courier New" .
+            Map.insert "style:font-name-complex" "Courier New" $ m
+  Language lang ->
+            Map.insert "fo:language" (langLanguage lang) .
+            maybe id (Map.insert "fo:country") (langRegion lang) $ m
+
+withLangFromAttr :: PandocMonad m => Attr -> OD m a -> OD m a
+withLangFromAttr (_,_,kvs) action =
+  case lookup "lang" kvs of
+       Nothing -> action
+       Just l  ->
+         case parseLang l of
               Right lang -> withTextStyle (Language lang) action
               Left _ -> do
                 report $ InvalidLang l
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,32 +1,13 @@
 {-# LANGUAGE OverloadedStrings #-}
-{-
-Copyright (C) 2010-2015 Puneeth Chaganti <punchagan@gmail.com>
-              2010-2017 John MacFarlane <jgm@berkeley.edu>
-              2016-2017 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 PatternGuards #-}
 {- |
    Module      : Text.Pandoc.Writers.Org
-  Copyright    : © 2010-2015 Puneeth Chaganti <punchagan@gmail.com>
-                   2010-2017 John MacFarlane <jgm@berkeley.edu>
-                   2016-2017 Albert Krewinkel <tarleb+pandoc@moltkeplatz.de>
+   Copyright   : © 2010-2015 Puneeth Chaganti <punchagan@gmail.com>
+                   2010-2025 John MacFarlane <jgm@berkeley.edu>
+                   2016-2025 Albert Krewinkel <albert+pandoc@tarleb.com>
    License     : GNU GPL, version 2 or above
 
-   Maintainer  : Albert Krewinkel <tarleb+pandoc@moltkeplatz.de>
+   Maintainer  : Albert Krewinkel <albert+pandoc@tarleb.com>
    Stability   : alpha
    Portability : portable
 
@@ -35,17 +16,26 @@
 Org-Mode:  <http://orgmode.org>
 -}
 module Text.Pandoc.Writers.Org (writeOrg) where
+import Control.Monad (zipWithM)
 import Control.Monad.State.Strict
-import Data.Char (isAlphaNum, toLower)
-import Data.List (intersect, intersperse, isPrefixOf, partition, transpose)
+    ( StateT, gets, modify, evalStateT )
+import Data.Char (isAlphaNum, isDigit)
+import Data.List (intersperse, partition, dropWhileEnd, transpose)
+import Data.List.NonEmpty (nonEmpty)
+import Data.Maybe (isJust)
 import Data.Text (Text)
-import Text.Pandoc.Class (PandocMonad, report)
+import qualified Data.Text as T
+import qualified Data.Map as M
+import Text.DocLayout
+import Text.Pandoc.Class.PandocMonad (PandocMonad, report)
 import Text.Pandoc.Definition
 import Text.Pandoc.Logging
 import Text.Pandoc.Options
-import Text.Pandoc.Pretty
 import Text.Pandoc.Shared
-import Text.Pandoc.Templates (renderTemplate')
+import Text.Pandoc.URI
+import Text.Pandoc.Templates (renderTemplate)
+import Text.Pandoc.Citeproc.Locator (parseLocator, LocatorMap(..), LocatorInfo(..))
+import Text.Pandoc.Walk (query)
 import Text.Pandoc.Writers.Shared
 
 data WriterState =
@@ -71,43 +61,67 @@
   let colwidth = if writerWrapText opts == WrapAuto
                     then Just $ writerColumns opts
                     else Nothing
-  let render' :: Doc -> Text
-      render' = render colwidth
-  metadata <- metaToJSON opts
-               (fmap render' . blockListToOrg)
-               (fmap render' . inlineListToOrg)
+  metadata <- metaToContext opts
+               blockListToOrg
+               (fmap chomp . inlineListToOrg)
                meta
   body <- blockListToOrg blocks
   notes <- gets (reverse . stNotes) >>= notesToOrg
   hasMath <- gets stHasMath
-  let main = render colwidth . foldl ($+$) empty $ [body, notes]
+  let main = body $+$ notes
   let context = defField "body" main
               . defField "math" hasMath
+              . defField "options"
+                         (M.fromList
+                          ((if isEnabled Ext_smart_quotes opts
+                            then (("'", "t"):)
+                            else id) .
+                           (if not (isEnabled Ext_special_strings opts)
+                            then (("-", "nil"):)
+                            else id)
+                           $ ([] :: [(Text, Text)])))
+              . defField "option-special-strings"
+                         (isEnabled Ext_special_strings opts)
               $ metadata
-  case writerTemplate opts of
-       Nothing  -> return main
-       Just tpl -> renderTemplate' tpl context
+  return $ render colwidth $
+    case writerTemplate opts of
+       Nothing  -> main
+       Just tpl -> renderTemplate tpl context
 
 -- | Return Org representation of notes.
-notesToOrg :: PandocMonad m => [[Block]] -> Org m Doc
+notesToOrg :: PandocMonad m => [[Block]] -> Org m (Doc Text)
 notesToOrg notes =
   vsep <$> zipWithM noteToOrg [1..] notes
 
 -- | Return Org representation of a note.
-noteToOrg :: PandocMonad m => Int -> [Block] -> Org m Doc
+noteToOrg :: PandocMonad m => Int -> [Block] -> Org m (Doc Text)
 noteToOrg num note = do
   contents <- blockListToOrg note
   let marker = "[fn:" ++ show num ++ "] "
   return $ hang (length marker) (text marker) contents
 
+-- | Replace Unicode characters with their ASCII representation
+replaceSpecialStrings :: Text -> Text
+replaceSpecialStrings =
+  let expand c = case c of
+        '\x00ad' -> "\\-"
+        '\x2013' -> "--"
+        '\x2014' -> "---"
+        '\x2019' -> "'"
+        '\x2026' -> "..."
+        _        -> T.singleton c
+  in T.concatMap expand
+
 -- | Escape special characters for Org.
-escapeString :: String -> String
-escapeString = escapeStringUsing $
-               [ ('\x2014',"---")
-               , ('\x2013',"--")
-               , ('\x2019',"'")
-               , ('\x2026',"...")
-               ] ++ backslashEscapes "^_"
+escapeString :: Text -> Doc Text
+escapeString t
+  | T.all isAlphaNum t = literal t
+  | otherwise = mconcat $ map escChar (T.unpack t)
+  where
+    -- escape special chars with ZERO WIDTH SPACE as org manual suggests
+   escChar c = if c == '*' || c == '#' || c == '|'
+     then afterBreak "\x200B" <> char c
+     else char c
 
 isRawFormat :: Format -> Bool
 isRawFormat f =
@@ -116,46 +130,22 @@
 -- | Convert Pandoc block element to Org.
 blockToOrg :: PandocMonad m
            => Block         -- ^ Block element
-           -> Org m Doc
-blockToOrg Null = return empty
-blockToOrg (Div (_,classes@(cls:_),kvs) bs) | "drawer" `elem` classes = do
-  contents <- blockListToOrg bs
-  let drawerNameTag = ":" <> text cls <> ":"
-  let keys = vcat $ map (\(k,v) ->
-                       ":" <> text k <> ":"
-                       <> space <> text v) kvs
-  let drawerEndTag = text ":END:"
-  return $ drawerNameTag $$ cr $$ keys $$
-           blankline $$ contents $$
-           blankline $$ drawerEndTag $$
-           blankline
-blockToOrg (Div (ident, classes, kv) bs) = do
-  contents <- blockListToOrg bs
-  -- if one class looks like the name of a greater block then output as such:
-  -- The ID, if present, is added via the #+NAME keyword; other classes and
-  -- key-value pairs are kept as #+ATTR_HTML attributes.
-  let isGreaterBlockClass = (`elem` ["center", "quote"]) . map toLower
-      (blockTypeCand, classes') = partition isGreaterBlockClass classes
-  return $ case blockTypeCand of
-    (blockType:classes'') ->
-      blankline $$ attrHtml (ident, classes'' <> classes', kv) $$
-      "#+BEGIN_" <> text blockType $$ contents $$
-      "#+END_" <> text blockType $$ blankline
-    _                     ->
-      -- fallback with id: add id as an anchor if present, discard classes and
-      -- key-value pairs, unwrap the content.
-      let contents' = if not (null ident)
-                      then "<<" <> text ident <> ">>" $$ contents
-                      else contents
-      in blankline $$ contents' $$ blankline
+           -> Org m (Doc Text)
+blockToOrg (Div (_, ["cell", "code"], _) (CodeBlock attr t : bs)) = do
+  -- ipynb code cell
+  let (ident, classes, kvs) = attr
+  blockListToOrg (CodeBlock (ident, classes ++ ["code"], kvs) t : bs)
+blockToOrg (Div (_, ["output", "execute_result"], _) [CodeBlock _attr t]) = do
+  -- ipynb code result
+  return $ "#+RESULTS:" $$
+    (prefixed ": " . vcat . map literal $ T.split (== '\n') t)
+blockToOrg (Div attr@(ident,_,_) bs) = do
+  opts <- gets stOptions
+  -- Strip off bibliography if citations enabled
+  if ident == "refs" && isEnabled Ext_citations opts
+     then return mempty
+     else divToOrg attr bs
 blockToOrg (Plain inlines) = inlineListToOrg inlines
--- title beginning with fig: indicates that the image is a figure
-blockToOrg (Para [Image attr txt (src,'f':'i':'g':':':tit)]) = do
-  capt <- if null txt
-             then return empty
-             else ("#+CAPTION: " <>) `fmap` inlineListToOrg txt
-  img <- inlineToOrg (Image attr txt (src,tit))
-  return $ capt $$ img $$ blankline
 blockToOrg (Para inlines) = do
   contents <- inlineListToOrg inlines
   return $ contents <> blankline
@@ -166,55 +156,93 @@
         (l, _:r) -> l : splitStanza r
   let joinWithLinefeeds  = nowrap . mconcat . intersperse cr
   let joinWithBlankLines = mconcat . intersperse blankline
-  let prettyfyStanza ls  = joinWithLinefeeds <$> mapM inlineListToOrg ls
-  contents <- joinWithBlankLines <$> mapM prettyfyStanza (splitStanza lns)
-  return $ blankline $$ "#+BEGIN_VERSE" $$
-           nest 2 contents $$ "#+END_VERSE" <> blankline
+  let prettifyStanza ls  = joinWithLinefeeds <$> mapM inlineListToOrg ls
+  contents <- joinWithBlankLines <$> mapM prettifyStanza (splitStanza lns)
+  return $ blankline $$ "#+begin_verse" $$
+           nest 2 contents $$ "#+end_verse" <> blankline
 blockToOrg (RawBlock "html" str) =
-  return $ blankline $$ "#+BEGIN_HTML" $$
-           nest 2 (text str) $$ "#+END_HTML" $$ blankline
+  return $ blankline $$ "#+begin_html" $$
+           nest 2 (literal str) $$ "#+end_html" $$ blankline
 blockToOrg b@(RawBlock f str)
-  | isRawFormat f = return $ text str
+  | isRawFormat f = return $ literal str
   | otherwise     = do
       report $ BlockNotRendered b
       return empty
 blockToOrg HorizontalRule = return $ blankline $$ "--------------" $$ blankline
 blockToOrg (Header level attr inlines) = do
-  contents <- inlineListToOrg inlines
-  let headerStr = text $ if level > 999 then " " else replicate level '*'
+  let tagName inline = case inline of
+        Span (_, _, kv) _ -> (:[]) <$> lookup "tag-name" kv
+        _                 -> Nothing
+  let (htext, tagsInlines) = break (isJust . tagName) inlines
+  contents <- inlineListToOrg $ dropWhileEnd (== Space) htext
+  columns  <- writerColumns <$> gets stOptions
+  let headerDoc = mconcat
+        [ text $ if level > 999 then " " else replicate level '*'
+        , literal " "
+        , contents
+        ]
+  let tags = case query tagName tagsInlines of
+               Nothing -> ""
+               Just ts -> T.cons ':' (T.intercalate ":" ts) `T.snoc` ':'
+  let tagsDoc = if T.null tags
+                then empty
+                else (<> literal tags) . text . (`replicate` ' ') . max 1 $
+                     columns - offset headerDoc - realLength tags
   let drawerStr = if attr == nullAttr
                   then empty
-                  else cr <> nest (level + 1) (propertiesDrawer attr)
-  return $ headerStr <> " " <> contents <> drawerStr <> blankline
-blockToOrg (CodeBlock (_,classes,_) str) = do
-  opts <- gets stOptions
-  let tabstop = writerTabStop opts
-  let at = map pandocLangToOrg classes `intersect` orgLangIdentifiers
-  let (beg, end) = case at of
-                      []    -> ("#+BEGIN_EXAMPLE", "#+END_EXAMPLE")
-                      (x:_) -> ("#+BEGIN_SRC " ++ x, "#+END_SRC")
-  return $ text beg $$ nest tabstop (text str) $$ text end $$ blankline
+                  else cr <> propertiesDrawer attr
+  return $ nowrap (headerDoc <> tagsDoc) <> drawerStr <> cr
+blockToOrg (CodeBlock (ident,classes,kvs) str) = do
+  let name = if T.null ident
+             then empty
+             else literal $ "#+name: " <> ident
+  let startnum = maybe "" (\x -> " " <> trimr x) $ lookup "startFrom" kvs
+  let numberlines = if "numberLines" `elem` classes
+                      then if "continuedSourceBlock" `elem` classes
+                             then " +n" <> startnum
+                             else " -n" <> startnum
+                      else ""
+  let lang = case filter (`notElem` ["example","code"]) classes of
+        []  -> Nothing
+        l:_ -> if "code" `elem` classes    -- check for ipynb code cell
+               then Just ("jupyter-" <> pandocLangToOrg l)
+               else Just (pandocLangToOrg l)
+  let args = mconcat $
+             [ " :" <> k <> " " <> v
+             | (k, v) <- kvs, k `notElem` ["startFrom", "org-language"]]
+  let (beg, end) = case lang of
+        Nothing -> ("#+begin_example" <> numberlines, "#+end_example")
+        Just x  -> ("#+begin_src " <> x <> numberlines <> args, "#+end_src")
+  -- escape special lines
+  let escape_line line =
+        let (spaces, code) = T.span (\c -> c == ' ' || c == '\t') line
+        in spaces <>
+           (if T.isPrefixOf "#+" code || T.isPrefixOf "*" code
+            then T.cons ',' code
+            else code)
+  let escaped = T.unlines . map escape_line . T.lines $ str
+  return $ name $$ literal beg $$ literal escaped $$ literal end $$ blankline
 blockToOrg (BlockQuote blocks) = do
   contents <- blockListToOrg blocks
-  return $ blankline $$ "#+BEGIN_QUOTE" $$
-           nest 2 contents $$ "#+END_QUOTE" $$ blankline
-blockToOrg (Table caption' _ _ headers rows) =  do
+  return $ blankline $$ "#+begin_quote" $$
+           chomp contents $$ "#+end_quote" $$ blankline
+blockToOrg (Table _ blkCapt specs thead tbody tfoot) =  do
+  let (caption', _, _, headers, rows) = toLegacyTable blkCapt specs thead tbody tfoot
   caption'' <- inlineListToOrg caption'
   let caption = if null caption'
                    then empty
-                   else "#+CAPTION: " <> caption''
+                   else "#+caption: " <> caption''
   headers' <- mapM blockListToOrg headers
   rawRows <- mapM (mapM blockListToOrg) rows
-  let numChars = maximum . map offset
+  let numChars = maybe 0 maximum . nonEmpty . map offset
   -- FIXME: width is not being used.
   let widthsInChars =
-       map ((+2) . numChars) $ transpose (headers' : rawRows)
+       map numChars $ transpose (headers' : rawRows)
   -- FIXME: Org doesn't allow blocks with height more than 1.
   let hpipeBlocks blocks = hcat [beg, middle, end]
-        where h      = maximum (1 : map height blocks)
-              sep'   = lblock 3 $ vcat (replicate h (text " | "))
-              beg    = lblock 2 $ vcat (replicate h (text "| "))
-              end    = lblock 2 $ vcat (replicate h (text " |"))
+        where sep'   = vfill " | "
+              beg    = vfill "| "
+              end    = vfill " |"
               middle = hcat $ intersperse sep' blocks
   let makeRow = hpipeBlocks . zipWith lblock widthsInChars
   let head' = makeRow headers'
@@ -231,105 +259,239 @@
   return $ head'' $$ body $$ caption $$ blankline
 blockToOrg (BulletList items) = do
   contents <- mapM bulletListItemToOrg items
-  -- ensure that sublists have preceding blank line
-  return $ blankline $+$ vcat contents $$ blankline
+  return $ (if isTightList items then vcat else vsep) contents $$
+           blankline
 blockToOrg (OrderedList (start, _, delim) items) = do
   let delim' = case delim of
                     TwoParens -> OneParen
                     x         -> x
   let markers = take (length items) $ orderedListMarkers
                                       (start, Decimal, delim')
-  let maxMarkerLength = maximum $ map length markers
-  let markers' = map (\m -> let s = maxMarkerLength - length m
-                            in  m ++ replicate s ' ') markers
-  contents <- zipWithM orderedListItemToOrg markers' items
-  -- ensure that sublists have preceding blank line
-  return $ blankline $$ vcat contents $$ blankline
+      counters = (case start of 1 -> Nothing; n -> Just n) : repeat Nothing
+  contents <- zipWithM (\x f -> f x) items $
+              zipWith orderedListItemToOrg markers counters
+  return $ (if isTightList items then vcat else vsep) contents $$
+           blankline
 blockToOrg (DefinitionList items) = do
   contents <- mapM definitionListItemToOrg items
   return $ vcat contents $$ blankline
+blockToOrg (Figure (ident, _, _) caption body) = do
+  -- Represent the figure as content that can be internally linked from other
+  -- parts of the document.
+  capt <- case caption of
+            Caption _ []  -> pure empty
+            Caption _ cpt -> ("#+caption: " <>) <$>
+                             inlineListToOrg (blocksToInlines cpt)
+  contents <-  blockListToOrg body
+  let anchor = if T.null ident
+               then empty
+               else "<<" <> literal ident <> ">>"
+  return (capt $$ anchor $$ contents $$ blankline)
 
 -- | Convert bullet list item (list of blocks) to Org.
-bulletListItemToOrg :: PandocMonad m => [Block] -> Org m Doc
+bulletListItemToOrg :: PandocMonad m => [Block] -> Org m (Doc Text)
 bulletListItemToOrg items = do
-  contents <- blockListToOrg items
-  return $ hang 2 "- " (contents <> cr)
+  exts <- gets $ writerExtensions . stOptions
+  contents <- blockListToOrg (taskListItemToOrg exts items)
+  -- if list item starts with non-paragraph, it must go on
+  -- the next line:
+  let contents' = (case items of
+                    Plain{}:_ -> mempty
+                    Para{}:_ -> mempty
+                    _ -> cr) <> chomp contents
+  return $ hang 2 "- " contents' $$
+          if null items || endsWithPlain items
+             then cr
+             else blankline
 
 -- | Convert ordered list item (a list of blocks) to Org.
 orderedListItemToOrg :: PandocMonad m
-                     => String   -- ^ marker for list item
+                     => Text   -- ^ marker for list item
+                     -> Maybe Int -- ^ maybe number for a counter cookie
                      -> [Block]  -- ^ list item (list of blocks)
-                     -> Org m Doc
-orderedListItemToOrg marker items = do
-  contents <- blockListToOrg items
-  return $ hang (length marker + 1) (text marker <> space) (contents <> cr)
+                     -> Org m (Doc Text)
+orderedListItemToOrg marker counter items = do
+  exts <- gets $ writerExtensions . stOptions
+  contents <- blockListToOrg (taskListItemToOrg exts items)
+  -- if list item starts with non-paragraph, it must go on
+  -- the next line:
+  let contents' = (case items of
+                    Plain{}:_ -> mempty
+                    Para{}:_ -> mempty
+                    _ -> cr) <> chomp contents
+  let cookie = maybe empty
+               (\n -> space <> literal "[@" <> literal (tshow n) <> literal "]")
+               counter
+  return $ hang (T.length marker + 1)
+                (literal marker <> cookie <> space) contents' $$
+          if null items || endsWithPlain items
+             then cr
+             else blankline
 
--- | Convert defintion list item (label, list of blocks) to Org.
+-- | Convert a list item containing text starting with @U+2610 BALLOT BOX@
+-- or @U+2612 BALLOT BOX WITH X@ to org checkbox syntax (e.g. @[X]@).
+taskListItemToOrg :: Extensions -> [Block] -> [Block]
+taskListItemToOrg = handleTaskListItem toOrg
+  where
+    toOrg (Str "☐" : Space : is) = Str "[ ]" : Space : is
+    toOrg (Str "☒" : Space : is) = Str "[X]" : Space : is
+    toOrg is = is
+
+-- | Convert definition list item (label, list of blocks) to Org.
 definitionListItemToOrg :: PandocMonad m
-                        => ([Inline], [[Block]]) -> Org m Doc
+                        => ([Inline], [[Block]]) -> Org m (Doc Text)
 definitionListItemToOrg (label, defs) = do
   label' <- inlineListToOrg label
   contents <- vcat <$> mapM blockListToOrg defs
-  return . hang 2 "- " $ label' <> " :: " <> (contents <> cr)
+  return $ hang 2 "- " (label' <> " :: " <> contents) $$
+      if isTightList defs
+         then cr
+         else blankline
 
 -- | Convert list of key/value pairs to Org :PROPERTIES: drawer.
-propertiesDrawer :: Attr -> Doc
+propertiesDrawer :: Attr -> Doc Text
 propertiesDrawer (ident, classes, kv) =
   let
     drawerStart = text ":PROPERTIES:"
     drawerEnd   = text ":END:"
-    kv'  = if classes == mempty then kv  else ("CLASS", unwords classes):kv
+    kv'  = if classes == mempty then kv  else ("CLASS", T.unwords classes):kv
     kv'' = if ident == mempty   then kv' else ("CUSTOM_ID", ident):kv'
     properties = vcat $ map kvToOrgProperty kv''
   in
     drawerStart <> cr <> properties <> cr <> drawerEnd
  where
-   kvToOrgProperty :: (String, String) -> Doc
+   kvToOrgProperty :: (Text, Text) -> Doc Text
    kvToOrgProperty (key, value) =
-     text ":" <> text key <> text ": " <> text value <> cr
+     text ":" <> literal key <> text ": " <> literal value <> cr
 
-attrHtml :: Attr -> Doc
+-- | The different methods to represent a Div block.
+data DivBlockType
+  = GreaterBlock Text Attr   -- ^ Greater block like @center@ or @quote@.
+  | Drawer Text Attr         -- ^ Org drawer with of given name; keeps
+                             --   key-value pairs.
+  | UnwrappedWithAnchor Text -- ^ Not mapped to other type, only
+                             --   identifier is retained (if any).
+  deriving (Show)
+
+-- | Gives the most suitable method to render a list of blocks
+-- with attributes.
+divBlockType :: Attr-> DivBlockType
+divBlockType (ident, classes, kvs)
+  -- if any class is named "drawer", then output as org :drawer:
+  | ([_], drawerName:classes') <- partition (== "drawer") classes
+  = Drawer drawerName (ident, classes', kvs)
+  -- if any class is either @center@ or @quote@, then use a org block.
+  | (blockName:classes'', classes') <- partition isGreaterBlockClass classes
+  = GreaterBlock blockName (ident, classes' <> classes'', kvs)
+  -- if no better method is found, unwrap div and set anchor
+  | otherwise
+  = UnwrappedWithAnchor ident
+ where
+  isGreaterBlockClass :: Text -> Bool
+  isGreaterBlockClass t = case T.toLower t of
+                            "center" -> True
+                            "quote" -> True
+                            x -> isAdmonition x
+
+isAdmonition :: Text -> Bool
+isAdmonition "warning" = True
+isAdmonition "important" = True
+isAdmonition "tip" = True
+isAdmonition "note" = True
+isAdmonition "caution" = True
+isAdmonition _ = False
+
+-- | Converts a Div to an org-mode element.
+divToOrg :: PandocMonad m
+         => Attr -> [Block] -> Org m (Doc Text)
+divToOrg attr bs = do
+  case divBlockType attr of
+    GreaterBlock blockName attr' -> do
+      -- Write as greater block. The ID, if present, is added via
+      -- the #+name keyword; other classes and key-value pairs
+      -- are kept as #+attr_html attributes.
+      contents <- case bs of
+                    (Div ("",["title"],[]) _ : bs')
+                      | isAdmonition blockName -> blockListToOrg bs'
+                    _ -> blockListToOrg bs
+      return $ blankline
+            $$ attrHtml attr'
+            $$ "#+begin_" <> literal blockName
+            $$ chomp contents
+            $$ "#+end_" <> literal blockName $$ blankline
+    Drawer drawerName (_,_,kvs) -> do
+      contents <- blockListToOrg bs
+      -- Write as drawer. Only key-value pairs are retained.
+      let keys = vcat $ map (\(k,v) ->
+                               ":" <> literal k <> ":"
+                              <> space <> literal v) kvs
+      return $ ":" <> literal drawerName <> ":" $$ cr
+            $$ keys $$ blankline
+            $$ contents $$ blankline
+            $$ text ":END:" $$ blankline
+    UnwrappedWithAnchor ident -> do
+      contents <- blockListToOrg bs
+      -- Unwrap the div. All attributes are discarded, except for
+      -- the identifier, which is added as an anchor before the
+      -- div contents.
+      let contents' = if T.null ident
+                      then contents
+                      else  "<<" <> literal ident <> ">>" $$ contents
+      return (blankline $$ contents' $$ blankline)
+
+attrHtml :: Attr -> Doc Text
 attrHtml (""   , []     , []) = mempty
 attrHtml (ident, classes, kvs) =
   let
-    name = if null ident then mempty else "#+NAME: " <> text ident <> cr
-    keyword = "#+ATTR_HTML"
-    classKv = ("class", unwords classes)
-    kvStrings = map (\(k,v) -> ":" <> k <> " " <> v) (classKv:kvs)
-  in name <> keyword <> ": " <> text (unwords kvStrings) <> cr
+    name = if T.null ident then mempty else "#+name: " <> literal ident <> cr
+    keyword = "#+attr_html"
+    addClassKv = if null classes
+                    then id
+                    else (("class", T.unwords classes):)
+    kvStrings = map (\(k,v) -> ":" <> k <> " " <> v) (addClassKv kvs)
+  in name <> if null kvStrings
+                then mempty
+                else keyword <> ": " <> literal (T.unwords kvStrings) <> cr
 
 -- | Convert list of Pandoc block elements to Org.
 blockListToOrg :: PandocMonad m
                => [Block]       -- ^ List of block elements
-               -> Org m Doc
+               -> Org m (Doc Text)
 blockListToOrg blocks = vcat <$> mapM blockToOrg blocks
 
 -- | Convert list of Pandoc inline elements to Org.
 inlineListToOrg :: PandocMonad m
                 => [Inline]
-                -> Org m Doc
+                -> Org m (Doc Text)
 inlineListToOrg lst = hcat <$> mapM inlineToOrg (fixMarkers lst)
-  where fixMarkers [] = []  -- prevent note refs and list markers from wrapping, see #4171
+  where -- Prevent note refs and list markers from wrapping, see #4171
+        -- and #7132.
+        fixMarkers [] = []
         fixMarkers (Space : x : rest) | shouldFix x =
           Str " " : x : fixMarkers rest
         fixMarkers (SoftBreak : x : rest) | shouldFix x =
           Str " " : x : fixMarkers rest
         fixMarkers (x : rest) = x : fixMarkers rest
 
-        shouldFix Note{} = True -- Prevent footnotes
+        shouldFix Note{} = True    -- Prevent footnotes
         shouldFix (Str "-") = True -- Prevent bullet list items
-        -- TODO: prevent ordered list items
+        shouldFix (Str x)          -- Prevent ordered list items
+          | Just (cs, c) <- T.unsnoc x = T.all isDigit cs &&
+                                         (c == '.' || c == ')')
         shouldFix _ = False
 
 -- | Convert Pandoc inline element to Org.
-inlineToOrg :: PandocMonad m => Inline -> Org m Doc
+inlineToOrg :: PandocMonad m => Inline -> Org m (Doc Text)
 inlineToOrg (Span (uid, [], []) []) =
-  return $ "<<" <> text uid <> ">>"
+  return $ "<<" <> literal uid <> ">>"
 inlineToOrg (Span _ lst) =
   inlineListToOrg lst
 inlineToOrg (Emph lst) = do
   contents <- inlineListToOrg lst
   return $ "/" <> contents <> "/"
+inlineToOrg (Underline lst) = do
+  contents <- inlineListToOrg lst
+  return $ "_" <> contents <> "_"
 inlineToOrg (Strong lst) = do
   contents <- inlineListToOrg lst
   return $ "*" <> contents <> "*"
@@ -345,20 +507,63 @@
 inlineToOrg (SmallCaps lst) = inlineListToOrg lst
 inlineToOrg (Quoted SingleQuote lst) = do
   contents <- inlineListToOrg lst
-  return $ "'" <> contents <> "'"
+  opts <- gets stOptions
+  return $
+    if isEnabled Ext_smart opts || isEnabled Ext_smart_quotes opts
+    then "'" <> contents <> "'"
+    else "‘" <> contents <> "’"
 inlineToOrg (Quoted DoubleQuote lst) = do
   contents <- inlineListToOrg lst
-  return $ "\"" <> contents <> "\""
-inlineToOrg (Cite _  lst) = inlineListToOrg lst
-inlineToOrg (Code _ str) = return $ "=" <> text str <> "="
-inlineToOrg (Str str) = return . text $ escapeString str
+  opts <- gets stOptions
+  return $
+    if isEnabled Ext_smart opts || isEnabled Ext_smart_quotes opts
+    then "\"" <> contents <> "\""
+    else "“" <> contents <> "”"
+inlineToOrg (Cite cs lst) = do
+  opts <- gets stOptions
+  if isEnabled Ext_citations opts
+     then do
+       let renderCiteItem c = do
+             citePref <- inlineListToOrg (citationPrefix c)
+             let (locinfo, suffix) = parseLocator locmap (citationSuffix c)
+             citeSuff <- inlineListToOrg suffix
+             let locator = case locinfo of
+                            Just info -> literal $
+                              T.replace "\160" " " $
+                              T.replace "{" "" $
+                              T.replace "}" "" $ locatorRaw info
+                            Nothing -> mempty
+             return $ hsep [ citePref
+                           , ("@" <> literal (citationId c))
+                           , locator
+                           , citeSuff ]
+       citeItems <- mconcat . intersperse "; " <$> mapM renderCiteItem cs
+       let sty = case cs of
+                   (d:_)
+                     | citationMode d == AuthorInText
+                     -> literal "/t"
+                   [d]
+                     | citationMode d == SuppressAuthor
+                     -> literal "/na"
+                   _ -> mempty
+       return $ "[cite" <> sty <> ":" <> citeItems <> "]"
+     else inlineListToOrg lst
+inlineToOrg (Code _ str) = return $ "=" <> literal str <> "="
+inlineToOrg (Str str) = do
+  opts <- gets stOptions
+  let str' = if isEnabled Ext_smart opts || isEnabled Ext_special_strings opts
+             then replaceSpecialStrings str
+             else str
+  return $ escapeString str'
 inlineToOrg (Math t str) = do
   modify $ \st -> st{ stHasMath = True }
   return $ if t == InlineMath
-              then "$" <> text str <> "$"
-              else "$$" <> text str <> "$$"
+              then "\\(" <> literal str <> "\\)"
+              else "\\[" <> literal str <> "\\]"
 inlineToOrg il@(RawInline f str)
-  | isRawFormat f = return $ text str
+  | elem f ["tex", "latex"] && T.isPrefixOf "\\begin" str =
+    return $ cr <> literal str <> cr
+  | isRawFormat f = return $ literal str
   | otherwise     = do
       report $ InlineNotRendered il
       return empty
@@ -373,54 +578,99 @@
 inlineToOrg (Link _ txt (src, _)) =
   case txt of
         [Str x] | escapeURI x == src ->  -- autolink
-             return $ "[[" <> text (orgPath x) <> "]]"
-        _ -> do contents <- inlineListToOrg txt
-                return $ "[[" <> text (orgPath src) <> "][" <> contents <> "]]"
+             return $ "[[" <> literal (orgPath x) <> "]]"
+        _ -> do contents <- nowrap <$> inlineListToOrg txt
+                return $ "[[" <> literal (orgPath src) <> "][" <> contents <> "]]"
 inlineToOrg (Image _ _ (source, _)) =
-  return $ "[[" <> text (orgPath source) <> "]]"
+  return $ "[[" <> literal (orgPath source) <> "]]"
 inlineToOrg (Note contents) = do
   -- add to notes in state
   notes <- gets stNotes
   modify $ \st -> st { stNotes = contents:notes }
-  let ref = show $ length notes + 1
-  return $ "[fn:" <> text ref <> "]"
+  let ref = tshow $ length notes + 1
+  return $ "[fn:" <> literal ref <> "]"
 
-orgPath :: String -> String
-orgPath src =
-  case src of
-    []      -> mempty         -- wiki link
-    ('#':_) -> src            -- internal link
-    _       | isUrl src      -> src
-    _       | isFilePath src -> src
-    _       -> "file:" <> src
- where
-   isFilePath :: String -> Bool
-   isFilePath cs = any (`isPrefixOf` cs) ["/", "./", "../", "file:"]
+orgPath :: Text -> Text
+orgPath src = case T.uncons src of
+  Nothing            -> ""             -- wiki link
+  Just ('#', _)      -> src            -- internal link
+  _ | isUrl src      -> src
+  _ | isFilePath src -> src
+  _                  -> "file:" <> src
+  where
+    isFilePath :: Text -> Bool
+    isFilePath cs = any (`T.isPrefixOf` cs) ["/", "./", "../", "file:"]
 
-   isUrl :: String -> Bool
-   isUrl cs =
-     let (scheme, path) = break (== ':') cs
-     in all (\c -> isAlphaNum c || c `elem` (".-"::String)) scheme
-          && not (null path)
+    isUrl :: Text -> Bool
+    isUrl cs =
+      let (scheme, path) = T.break (== ':') cs
+       in T.all (\c -> isAlphaNum c || T.any (== c) ".-") scheme
+          && not (T.null path)
 
 -- | Translate from pandoc's programming language identifiers to those used by
 -- org-mode.
-pandocLangToOrg :: String -> String
+pandocLangToOrg :: Text -> Text
 pandocLangToOrg cs =
   case cs of
     "c"          -> "C"
-    "cpp"        -> "C++"
     "commonlisp" -> "lisp"
     "r"          -> "R"
     "bash"       -> "sh"
     _            -> cs
 
--- | List of language identifiers recognized by org-mode.
-orgLangIdentifiers :: [String]
-orgLangIdentifiers =
-  [ "asymptote", "awk", "C", "C++", "clojure", "css", "d", "ditaa", "dot"
-  , "calc", "emacs-lisp", "fortran", "gnuplot", "haskell", "java", "js"
-  , "latex", "ledger", "lisp", "lilypond", "matlab", "mscgen", "ocaml"
-  , "octave", "org", "oz", "perl", "plantuml", "processing", "python", "R"
-  , "ruby", "sass", "scheme", "screen", "sed", "sh", "sql", "sqlite"
-  ]
+-- taken from oc-csl.el in the org source tree:
+locmap :: LocatorMap
+locmap = LocatorMap $ M.fromList
+  [ ("bk."       , "book")
+  , ("bks."      , "book")
+  , ("book"      , "book")
+  , ("chap."     , "chapter")
+  , ("chaps."    , "chapter")
+  , ("chapter"   , "chapter")
+  , ("col."      , "column")
+  , ("cols."     , "column")
+  , ("column"    , "column")
+  , ("figure"    , "figure")
+  , ("fig."      , "figure")
+  , ("figs."     , "figure")
+  , ("folio"     , "folio")
+  , ("fol."      , "folio")
+  , ("fols."     , "folio")
+  , ("number"    , "number")
+  , ("no."       , "number")
+  , ("nos."      , "number")
+  , ("line"      , "line")
+  , ("l."        , "line")
+  , ("ll."       , "line")
+  , ("note"      , "note")
+  , ("n."        , "note")
+  , ("nn."       , "note")
+  , ("opus"      , "opus")
+  , ("op."       , "opus")
+  , ("opp."      , "opus")
+  , ("page"      , "page")
+  , ("p"         , "page")
+  , ("p."        , "page")
+  , ("pp."       , "page")
+  , ("paragraph" , "paragraph")
+  , ("para."     , "paragraph")
+  , ("paras."    , "paragraph")
+  , ("¶"         , "paragraph")
+  , ("¶¶"        , "paragraph")
+  , ("part"      , "part")
+  , ("pt."       , "part")
+  , ("pts."      , "part")
+  , ("§"         , "section")
+  , ("§§"        , "section")
+  , ("section"   , "section")
+  , ("sec."      , "section")
+  , ("secs."     , "section")
+  , ("sub verbo" , "sub verbo")
+  , ("s.v."      , "sub verbo")
+  , ("s.vv."     , "sub verbo")
+  , ("verse"     , "verse")
+  , ("v."        , "verse")
+  , ("vv."       , "verse")
+  , ("volume"    , "volume")
+  , ("vol."      , "volume")
+  , ("vols."     , "volume") ]
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,1746 +1,43 @@
-{-# LANGUAGE PatternGuards, MultiWayIf, OverloadedStrings #-}
-
-{-
-Copyright (C) 2017 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 Jesse Rosenthal
-   License     : GNU GPL, version 2 or above
-
-   Maintainer  : Jesse Rosenthal <jrosenthal@jhu.edu>
-   Stability   : alpha
-   Portability : portable
-
-Conversion of 'Pandoc' documents to powerpoint (pptx).
--}
-
-module Text.Pandoc.Writers.Powerpoint (writePowerpoint) where
-
-import Control.Monad.Except (throwError)
-import Control.Monad.Reader
-import Control.Monad.State
-import Codec.Archive.Zip
-import Data.List (intercalate, stripPrefix, isPrefixOf, nub)
--- import Control.Monad (mplus)
-import Data.Default
-import Data.Time.Clock (UTCTime)
-import Data.Time.Clock.POSIX (utcTimeToPOSIXSeconds, posixSecondsToUTCTime)
-import System.FilePath.Posix (splitDirectories, splitExtension)
-import Text.XML.Light
-import Text.Pandoc.Definition
-import qualified Text.Pandoc.UTF8 as UTF8
-import Text.Pandoc.Class (PandocMonad)
-import Text.Pandoc.Error (PandocError(..))
-import qualified Text.Pandoc.Class as P
-import Text.Pandoc.Options
-import Text.Pandoc.MIME
-import Text.Pandoc.Logging
-import qualified Data.ByteString.Lazy as BL
--- import qualified Data.ByteString.Lazy.Char8 as BL8
--- import qualified Text.Pandoc.UTF8 as UTF8
-import Text.Pandoc.Walk
-import Text.Pandoc.Writers.Shared (fixDisplayMath)
-import Text.Pandoc.Writers.OOXML
-import qualified Data.Map as M
-import Data.Maybe (mapMaybe, listToMaybe)
-import Text.Pandoc.ImageSize
-import Control.Applicative ((<|>))
-
-import Text.TeXMath
-import Text.Pandoc.Writers.Math (convertMath)
-
-
-writePowerpoint :: (PandocMonad m)
-                => WriterOptions  -- ^ Writer options
-                -> Pandoc         -- ^ Document to convert
-                -> m BL.ByteString
-writePowerpoint opts (Pandoc meta blks) = do
-  let blks' = walk fixDisplayMath blks
-  distArchive <- (toArchive . BL.fromStrict) <$>
-                      P.readDefaultDataFile "reference.pptx"
-  refArchive <- case writerReferenceDoc opts of
-                     Just f  -> toArchive <$> P.readFileLazy f
-                     Nothing -> (toArchive . BL.fromStrict) <$>
-                        P.readDataFile "reference.pptx"
-
-  utctime <- P.getCurrentTime
-
-  let env = def { envMetadata = meta
-                , envRefArchive = refArchive
-                , envDistArchive = distArchive
-                , envUTCTime = utctime
-                , envOpts = opts
-                , envSlideLevel = case writerSlideLevel opts of
-                                    Just n -> n
-                                    Nothing -> 2
-                }
-  runP env def $ do pres <- blocksToPresentation blks'
-                    archv <- presentationToArchive pres
-                    return $ fromArchive archv
-
-concatMapM        :: (Monad m) => (a -> m [b]) -> [a] -> m [b]
-concatMapM f xs   =  liftM concat (mapM f xs)
-
-data WriterEnv = WriterEnv { envMetadata :: Meta
-                           , envRunProps :: RunProps
-                           , envParaProps :: ParaProps
-                           , envSlideLevel :: Int
-                           , envRefArchive :: Archive
-                           , envDistArchive :: Archive
-                           , envUTCTime :: UTCTime
-                           , envOpts :: WriterOptions
-                           , envPresentationSize :: PresentationSize
-                           , envSlideHasHeader :: Bool
-                           , envInList :: Bool
-                           , envInNoteSlide :: Bool
-                           }
-                 deriving (Show)
-
-instance Default WriterEnv where
-  def = WriterEnv { envMetadata = mempty
-                  , envRunProps = def
-                  , envParaProps = def
-                  , envSlideLevel = 2
-                  , envRefArchive = emptyArchive
-                  , envDistArchive = emptyArchive
-                  , envUTCTime = posixSecondsToUTCTime 0
-                  , envOpts = def
-                  , envPresentationSize = def
-                  , envSlideHasHeader = False
-                  , envInList = False
-                  , envInNoteSlide = False
-                  }
-
-data MediaInfo = MediaInfo { mInfoFilePath :: FilePath
-                           , mInfoLocalId  :: Int
-                           , mInfoGlobalId :: Int
-                           , mInfoMimeType :: Maybe MimeType
-                           , mInfoExt      :: Maybe String
-                           , mInfoCaption  :: Bool
-                           } deriving (Show, Eq)
-
-data WriterState = WriterState { stCurSlideId :: Int
-                               -- the difference between the number at
-                               -- the end of the slide file name and
-                               -- the rId number
-                               , stSlideIdOffset :: Int
-                               , stLinkIds :: M.Map Int (M.Map Int (URL, String))
-                               -- (FP, Local ID, Global ID, Maybe Mime)
-                               , stMediaIds :: M.Map Int [MediaInfo]
-                               , stMediaGlobalIds :: M.Map FilePath Int
-                               , stNoteIds :: M.Map Int [Block]
-                               } deriving (Show, Eq)
-
-instance Default WriterState where
-  def = WriterState { stCurSlideId = 0
-                    , stSlideIdOffset = 1
-                    , stLinkIds = mempty
-                    , stMediaIds = mempty
-                    , stMediaGlobalIds = mempty
-                    , stNoteIds = mempty
-                    }
-
-type P m = ReaderT WriterEnv (StateT WriterState m)
-
-runP :: Monad m => WriterEnv -> WriterState -> P m a -> m a
-runP env st p = evalStateT (runReaderT p env) st
-
-type Pixels = Integer
-
-data Presentation = Presentation PresentationSize [Slide]
-  deriving (Show)
-
-data PresentationSize = PresentationSize { presSizeWidth :: Pixels
-                                         , presSizeRatio :: PresentationRatio
-                                         }
-                      deriving (Show, Eq)
-
-data PresentationRatio = Ratio4x3
-                       | Ratio16x9
-                       | Ratio16x10
-                       deriving (Show, Eq)
-
--- Note that right now we're only using Ratio4x3.
-getPageHeight :: PresentationSize -> Pixels
-getPageHeight sz = case presSizeRatio sz of
-  Ratio4x3 -> floor (((fromInteger (presSizeWidth sz)) / 4) * 3 :: Double)
-  Ratio16x9 -> floor (((fromInteger (presSizeWidth sz)) / 16) * 9 :: Double)
-  Ratio16x10 -> floor (((fromInteger (presSizeWidth sz)) / 16) * 10 :: Double)
-
-instance Default PresentationSize where
-  def = PresentationSize 720 Ratio4x3
-
-data Slide = MetadataSlide { metadataSlideTitle :: [ParaElem]
-                            , metadataSlideSubtitle :: [ParaElem]
-                            , metadataSlideAuthors :: [[ParaElem]]
-                            , metadataSlideDate :: [ParaElem]
-                            }
-           | TitleSlide { titleSlideHeader :: [ParaElem]}
-           | ContentSlide { contentSlideHeader :: [ParaElem]
-                          , contentSlideContent :: [Shape]
-                          }
-           deriving (Show, Eq)
-
-data SlideElement = SlideElement Pixels Pixels Pixels Pixels Shape
-  deriving (Show, Eq)
-
-data Shape = Pic FilePath Text.Pandoc.Definition.Attr [ParaElem]
-           | GraphicFrame [Graphic] [ParaElem]
-           | TextBox [Paragraph]
-  deriving (Show, Eq)
-
-type Cell = [Paragraph]
-
-data TableProps = TableProps { tblPrFirstRow :: Bool
-                             , tblPrBandRow :: Bool
-                             } deriving (Show, Eq)
-
-type ColWidth = Integer
-
-data Graphic = Tbl TableProps [ColWidth] [Cell] [[Cell]]
-  deriving (Show, Eq)
-
-
-data Paragraph = Paragraph { paraProps :: ParaProps
-                           , paraElems  :: [ParaElem]
-                           } deriving (Show, Eq)
-
-data HeaderType = TitleHeader | SlideHeader | InternalHeader Int
-                deriving (Show, Eq)
-
--- type StartingAt = Int
-
--- data AutoNumType = ArabicNum
---                  | AlphaUpperNum
---                  | AlphaLowerNum
---                  | RomanUpperNum
---                  | RomanLowerNum
---                  deriving (Show, Eq)
-
--- data AutoNumDelim = PeriodDelim
---                   | OneParenDelim
---                   | TwoParensDelim
---                   deriving (Show, Eq)
-
-autoNumberingToType :: ListAttributes -> String
-autoNumberingToType (_, numStyle, numDelim) =
-  typeString ++ delimString
-  where
-    typeString = case numStyle of
-      Decimal -> "arabic"
-      UpperAlpha -> "alphaUc"
-      LowerAlpha -> "alphaLc"
-      UpperRoman -> "romanUc"
-      LowerRoman -> "romanLc"
-      _          -> "arabic"
-    delimString = case numDelim of
-      Period -> "Period"
-      OneParen -> "ParenR"
-      TwoParens -> "ParenBoth"
-      _         -> "Period"
-
-data BulletType = Bullet
-                | AutoNumbering ListAttributes
-  deriving (Show, Eq)
-
-data Algnment = AlgnLeft | AlgnRight | AlgnCenter
-  deriving (Show, Eq)
-
-data ParaProps = ParaProps { pPropHeaderType :: Maybe HeaderType
-                           , pPropMarginLeft :: Maybe Pixels
-                           , pPropMarginRight :: Maybe Pixels
-                           , pPropLevel :: Int
-                           , pPropBullet :: Maybe BulletType
-                           , pPropAlign :: Maybe Algnment
-                           } deriving (Show, Eq)
-
-instance Default ParaProps where
-  def = ParaProps { pPropHeaderType = Nothing
-                  , pPropMarginLeft = Just 0
-                  , pPropMarginRight = Just 0
-                  , pPropLevel = 0
-                  , pPropBullet = Nothing
-                  , pPropAlign = Nothing
-                  }
-
-newtype TeXString = TeXString {unTeXString :: String}
-  deriving (Eq, Show)
-
-data ParaElem = Break
-              | Run RunProps String
-              -- It would be more elegant to have native TeXMath
-              -- Expressions here, but this allows us to use
-              -- `convertmath` from T.P.Writers.Math. Will perhaps
-              -- revisit in the future.
-              | MathElem MathType TeXString
-              deriving (Show, Eq)
-
-data Strikethrough = NoStrike | SingleStrike | DoubleStrike
-  deriving (Show, Eq)
-
-data Capitals = NoCapitals | SmallCapitals | AllCapitals
-  deriving (Show, Eq)
-
-type URL = String
-
-data RunProps = RunProps { rPropBold :: Bool
-                         , rPropItalics :: Bool
-                         , rStrikethrough :: Maybe Strikethrough
-                         , rBaseline :: Maybe Int
-                         , rCap :: Maybe Capitals
-                         , rLink :: Maybe (URL, String)
-                         , rPropCode :: Bool
-                         , rPropBlockQuote :: Bool
-                         , rPropForceSize :: Maybe Pixels
-                         } deriving (Show, Eq)
-
-instance Default RunProps where
-  def = RunProps { rPropBold = False
-                 , rPropItalics = False
-                 , rStrikethrough = Nothing
-                 , rBaseline = Nothing
-                 , rCap = Nothing
-                 , rLink = Nothing
-                 , rPropCode = False
-                 , rPropBlockQuote = False
-                 , rPropForceSize = Nothing
-                 }
-
---------------------------------------------------
-
-inlinesToParElems :: Monad m => [Inline] -> P m [ParaElem]
-inlinesToParElems ils = concatMapM inlineToParElems ils
-
-inlineToParElems :: Monad m => Inline -> P m [ParaElem]
-inlineToParElems (Str s) = do
-  pr <- asks envRunProps
-  return [Run pr s]
-inlineToParElems (Emph ils) =
-  local (\r -> r{envRunProps = (envRunProps r){rPropItalics=True}}) $
-  inlinesToParElems ils
-inlineToParElems (Strong ils) =
-  local (\r -> r{envRunProps = (envRunProps r){rPropBold=True}}) $
-  inlinesToParElems ils
-inlineToParElems (Strikeout ils) =
-  local (\r -> r{envRunProps = (envRunProps r){rStrikethrough=Just SingleStrike}}) $
-  inlinesToParElems ils
-inlineToParElems (Superscript ils) =
-  local (\r -> r{envRunProps = (envRunProps r){rBaseline=Just 30000}}) $
-  inlinesToParElems ils
-inlineToParElems (Subscript ils) =
-  local (\r -> r{envRunProps = (envRunProps r){rBaseline=Just (-25000)}}) $
-  inlinesToParElems ils
-inlineToParElems (SmallCaps ils) =
-  local (\r -> r{envRunProps = (envRunProps r){rCap = Just SmallCapitals}}) $
-  inlinesToParElems ils
-inlineToParElems Space = inlineToParElems (Str " ")
-inlineToParElems SoftBreak = inlineToParElems (Str " ")
-inlineToParElems LineBreak = return [Break]
-inlineToParElems (Link _ ils (url, title)) = do
-  local (\r ->r{envRunProps = (envRunProps r){rLink = Just (url, title)}}) $
-    inlinesToParElems ils
-inlineToParElems (Code _ str) = do
-  local (\r ->r{envRunProps = def{rPropCode = True}}) $
-    inlineToParElems $ Str str
-inlineToParElems (Math mathtype str) =
-  return [MathElem mathtype (TeXString str)]
-inlineToParElems (Note blks) = do
-  notes <- gets stNoteIds
-  let maxNoteId = case M.keys notes of
-        [] -> 0
-        lst -> maximum lst
-      curNoteId = maxNoteId + 1
-  modify $ \st -> st { stNoteIds = M.insert curNoteId blks notes }
-  inlineToParElems $ Superscript [Str $ show curNoteId]
-inlineToParElems (Span _ ils) = concatMapM inlineToParElems ils
-inlineToParElems (RawInline _ _) = return []
-inlineToParElems _ = return []
-
-isListType :: Block -> Bool
-isListType (OrderedList _ _) = True
-isListType (BulletList _) = True
-isListType (DefinitionList _) = True
-isListType _ = False
-
-blockToParagraphs :: PandocMonad m => Block -> P m [Paragraph]
-blockToParagraphs (Plain ils) = do
-  parElems <- inlinesToParElems ils
-  pProps <- asks envParaProps
-  return [Paragraph pProps parElems]
-blockToParagraphs (Para ils) = do
-  parElems <- inlinesToParElems ils
-  pProps <- asks envParaProps
-  return [Paragraph pProps parElems]
-blockToParagraphs (LineBlock ilsList) = do
-  parElems <- inlinesToParElems $ intercalate [LineBreak] ilsList
-  pProps <- asks envParaProps
-  return [Paragraph pProps parElems]
--- TODO: work out the attributes
-blockToParagraphs (CodeBlock attr str) =
-  local (\r -> r{envParaProps = def{pPropMarginLeft = Just 100}}) $
-  blockToParagraphs $ Para [Code attr str]
--- We can't yet do incremental lists, but we should render a
--- (BlockQuote List) as a list to maintain compatibility with other
--- formats.
-blockToParagraphs (BlockQuote (blk : blks)) | isListType blk = do
-  ps  <- blockToParagraphs blk
-  ps' <- blockToParagraphs $ BlockQuote blks
-  return $ ps ++ ps'
-blockToParagraphs (BlockQuote blks) =
-  local (\r -> r{ envParaProps = (envParaProps r){pPropMarginLeft = Just 100}
-                , envRunProps = (envRunProps r){rPropForceSize = Just blockQuoteSize}})$
-  concatMapM blockToParagraphs blks
--- TODO: work out the format
-blockToParagraphs (RawBlock _ _) = return []
-  -- parElems <- inlinesToParElems [Str str]
-  -- paraProps <- asks envParaProps
-  -- return [Paragraph paraProps parElems]
--- TODO: work out the format
-blockToParagraphs (Header n _ ils) = do
-  slideLevel <- asks envSlideLevel
-  parElems <- inlinesToParElems ils
-  -- For the time being we're not doing headers inside of bullets, but
-  -- we might change that.
-  let headerType = case n `compare` slideLevel of
-                     LT -> TitleHeader
-                     EQ -> SlideHeader
-                     GT -> InternalHeader (n - slideLevel)
-  return [Paragraph def{pPropHeaderType = Just headerType} parElems]
-blockToParagraphs (BulletList blksLst) = do
-  pProps <- asks envParaProps
-  let lvl = pPropLevel pProps
-  local (\env -> env{ envInList = True
-                    , envParaProps = pProps{ pPropLevel = lvl + 1
-                                           , pPropBullet = Just Bullet
-                                           , pPropMarginLeft = Nothing
-                                           }}) $
-    concatMapM multiParBullet blksLst
-blockToParagraphs (OrderedList listAttr blksLst) = do
-  pProps <- asks envParaProps
-  let lvl = pPropLevel pProps
-  local (\env -> env{ envInList = True
-                    , envParaProps = pProps{ pPropLevel = lvl + 1
-                                           , pPropBullet = Just (AutoNumbering listAttr)
-                                           , pPropMarginLeft = Nothing
-                                           }}) $
-    concatMapM multiParBullet blksLst
-blockToParagraphs (DefinitionList entries) = do
-  let go :: PandocMonad m => ([Inline], [[Block]]) -> P m [Paragraph]
-      go (ils, blksLst) = do
-        term <-blockToParagraphs $ Para [Strong ils]
-        -- For now, we'll treat each definition term as a
-        -- blockquote. We can extend this further later.
-        definition <- concatMapM (blockToParagraphs . BlockQuote) blksLst
-        return $ term ++ definition
-  concatMapM go entries
-blockToParagraphs (Div _ blks)  = concatMapM blockToParagraphs blks
--- TODO
-blockToParagraphs blk = do
-  P.report $ BlockNotRendered blk
-  return []
-
--- Make sure the bullet env gets turned off after the first para.
-multiParBullet :: PandocMonad m => [Block] -> P m [Paragraph]
-multiParBullet [] = return []
-multiParBullet (b:bs) = do
-  pProps <- asks envParaProps
-  p <- blockToParagraphs b
-  ps <- local (\env -> env{envParaProps = pProps{pPropBullet = Nothing}}) $
-    concatMapM blockToParagraphs bs
-  return $ p ++ ps
-
-cellToParagraphs :: PandocMonad m => Alignment -> TableCell -> P m [Paragraph]
-cellToParagraphs algn tblCell = do
-  paras <- mapM (blockToParagraphs) tblCell
-  let alignment = case algn of
-        AlignLeft -> Just AlgnLeft
-        AlignRight -> Just AlgnRight
-        AlignCenter -> Just AlgnCenter
-        AlignDefault -> Nothing
-      paras' = map (map (\p -> p{paraProps = (paraProps p){pPropAlign = alignment}})) paras
-  return $ concat paras'
-
-rowToParagraphs :: PandocMonad m => [Alignment] -> [TableCell] -> P m [[Paragraph]]
-rowToParagraphs algns tblCells = do
-  -- We have to make sure we have the right number of alignments
-  let pairs = zip (algns ++ repeat AlignDefault) tblCells
-  mapM (\(a, tc) -> cellToParagraphs a tc) pairs
-
-blockToShape :: PandocMonad m => Block -> P m Shape
-blockToShape (Plain (il:_)) | Image attr ils (url, _) <- il =
-      Pic url attr <$> (inlinesToParElems ils)
-blockToShape (Para (il:_))  | Image attr ils (url, _) <- il =
-      Pic url attr <$> (inlinesToParElems ils)
-blockToShape (Table caption algn _ hdrCells rows) = do
-  caption' <- inlinesToParElems caption
-  pageWidth <- presSizeWidth <$> asks envPresentationSize
-  hdrCells' <- rowToParagraphs algn hdrCells
-  rows' <- mapM (rowToParagraphs algn) rows
-  let tblPr = if null hdrCells
-              then TableProps { tblPrFirstRow = False
-                              , tblPrBandRow = True
-                              }
-              else TableProps { tblPrFirstRow = True
-                              , tblPrBandRow = True
-                              }
-      colWidths = if null hdrCells
-                 then case rows of
-                        r : _ | not (null r) -> replicate (length r) $
-                                                (pageWidth - (2 * hardcodedTableMargin))`div` (toInteger $ length r)
-                        -- satisfy the compiler. This is the same as
-                        -- saying that rows is empty, but the compiler
-                        -- won't understand that `[]` exhausts the
-                        -- alternatives.
-                        _ -> []
-                 else replicate (length hdrCells) $
-                      (pageWidth - (2 * hardcodedTableMargin)) `div` (toInteger $ length hdrCells)
-
-  return $ GraphicFrame [Tbl tblPr colWidths hdrCells' rows'] caption'
-blockToShape blk = TextBox <$> blockToParagraphs blk
-
-blocksToShapes :: PandocMonad m => [Block] -> P m [Shape]
-blocksToShapes blks = combineShapes <$> mapM blockToShape blks
-
-splitBlocks' :: Monad m => [Block] -> [[Block]] -> [Block] -> P m [[Block]]
-splitBlocks' cur acc [] = return $ acc ++ (if null cur then [] else [cur])
-splitBlocks' cur acc (HorizontalRule : blks) =
-  splitBlocks' [] (acc ++ (if null cur then [] else [cur])) blks
-splitBlocks' cur acc (h@(Header n _ _) : blks) = do
-  slideLevel <- asks envSlideLevel
-  case compare n slideLevel of
-    LT -> splitBlocks' [] (acc ++ (if null cur then [] else [cur]) ++ [[h]]) blks
-    EQ -> splitBlocks' [h] (acc ++ (if null cur then [] else [cur])) blks
-    GT -> splitBlocks' (cur ++ [h]) acc blks
-splitBlocks' cur acc ((Para (img@(Image _ _ _):ils)) : blks) = do
-  slideLevel <- asks envSlideLevel
-  case cur of
-    (Header n _ _) : [] | n == slideLevel ->
-                            splitBlocks' []
-                            (acc ++ [cur ++ [Para [img]]])
-                            (if null ils then blks else (Para ils) : blks)
-    _ ->  splitBlocks' []
-          (acc ++ (if null cur then [] else [cur]) ++ [[Para [img]]])
-          (if null ils then blks else (Para ils) : blks)
-splitBlocks' cur acc ((Plain (img@(Image _ _ _):ils)) : blks) = do
-  slideLevel <- asks envSlideLevel
-  case cur of
-    (Header n _ _) : [] | n == slideLevel ->
-                            splitBlocks' []
-                            (acc ++ [cur ++ [Para [img]]])
-                            (if null ils then blks else (Plain ils) : blks)
-    _ ->  splitBlocks' []
-          (acc ++ (if null cur then [] else [cur]) ++ [[Para [img]]])
-          (if null ils then blks else (Plain ils) : blks)
-splitBlocks' cur acc (tbl@(Table _ _ _ _ _) : blks) = do
-  slideLevel <- asks envSlideLevel
-  case cur of
-    (Header n _ _) : [] | n == slideLevel ->
-                            splitBlocks' [] (acc ++ [cur ++ [tbl]]) blks
-    _ ->  splitBlocks' [] (acc ++ (if null cur then [] else [cur]) ++ [[tbl]]) blks
-splitBlocks' cur acc (blk : blks) = splitBlocks' (cur ++ [blk]) acc blks
-
-splitBlocks :: Monad m => [Block] -> P m [[Block]]
-splitBlocks = splitBlocks' [] []
-
-blocksToSlide' :: PandocMonad m => Int -> [Block] -> P m Slide
-blocksToSlide' lvl ((Header n _ ils) : blks)
-  | n < lvl = do
-      hdr <- inlinesToParElems ils
-      return $ TitleSlide {titleSlideHeader = hdr}
-  | n == lvl = do
-      hdr <- inlinesToParElems ils
-      inNoteSlide <- asks envInNoteSlide
-      shapes <- if inNoteSlide
-                then forceFontSize noteSize $ blocksToShapes blks
-                else blocksToShapes blks
-      return $ ContentSlide { contentSlideHeader = hdr
-                            , contentSlideContent = shapes
-                            }
-blocksToSlide' _ (blk : blks) = do
-      inNoteSlide <- asks envInNoteSlide
-      shapes <- if inNoteSlide
-                then forceFontSize noteSize $ blocksToShapes (blk : blks)
-                else blocksToShapes (blk : blks)
-      return $ ContentSlide { contentSlideHeader = []
-                            , contentSlideContent = shapes
-                            }
-blocksToSlide' _ [] = return $ ContentSlide { contentSlideHeader = []
-                                            , contentSlideContent = []
-                                            }
-
-blocksToSlide :: PandocMonad m => [Block] -> P m Slide
-blocksToSlide blks = do
-  slideLevel <- asks envSlideLevel
-  blocksToSlide' slideLevel blks
-
-makeNoteEntry :: Int -> [Block] -> [Block]
-makeNoteEntry n blks =
-  let enum = Str (show n ++ ".")
-  in
-    case blks of
-      (Para ils : blks') -> (Para $ enum : Space : ils) : blks'
-      _ -> (Para [enum]) : blks
-
-forceFontSize :: PandocMonad m => Pixels -> P m a -> P m a
-forceFontSize px x = do
-  rpr <- asks envRunProps
-  local (\r -> r {envRunProps = rpr{rPropForceSize = Just px}}) x
-
--- Right now, there's no logic for making more than one slide, but I
--- want to leave the option open to make multiple slides if we figure
--- out how to guess at how much space the text of the notes will take
--- up (or if we allow a way for it to be manually controlled). Plus a
--- list will make it easier to put together in the final
--- `blocksToPresentation` function (since we can just add an empty
--- list without checking the state).
-makeNotesSlides :: PandocMonad m => P m [Slide]
-makeNotesSlides = local (\env -> env{envInNoteSlide=True}) $ do
-  noteIds <- gets stNoteIds
-  if M.null noteIds
-    then return []
-    else do let hdr = Header 2 nullAttr [Str "Notes"]
-            blks <- return $
-                    concatMap (\(n, bs) -> makeNoteEntry n bs) $
-                    M.toList noteIds
-            sld <- blocksToSlide $ hdr : blks
-            return [sld]
-
-getMetaSlide :: PandocMonad m => P m (Maybe Slide)
-getMetaSlide  = do
-  meta <- asks envMetadata
-  title <- inlinesToParElems $ docTitle meta
-  subtitle <- inlinesToParElems $
-    case lookupMeta "subtitle" meta of
-      Just (MetaString s)           -> [Str s]
-      Just (MetaInlines ils)        -> ils
-      Just (MetaBlocks [Plain ils]) -> ils
-      Just (MetaBlocks [Para ils])  -> ils
-      _                             -> []
-  authors <- mapM inlinesToParElems $ docAuthors meta
-  date <- inlinesToParElems $ docDate meta
-  if null title && null subtitle && null authors && null date
-    then return Nothing
-    else return $ Just $ MetadataSlide { metadataSlideTitle = title
-                                       , metadataSlideSubtitle = subtitle
-                                       , metadataSlideAuthors = authors
-                                       , metadataSlideDate = date
-                                       }
-
-blocksToPresentation :: PandocMonad m => [Block] -> P m Presentation
-blocksToPresentation blks = do
-  blksLst <- splitBlocks blks
-  slides <- mapM blocksToSlide blksLst
-  noteSlides <- makeNotesSlides
-  let slides' = slides ++ noteSlides
-  metadataslide <- getMetaSlide
-  presSize <- asks envPresentationSize
-  return $ case metadataslide of
-             Just metadataslide' -> Presentation presSize $ metadataslide' : slides'
-             Nothing            -> Presentation presSize slides'
-
---------------------------------------------------------------------
-
-copyFileToArchive :: PandocMonad m => Archive -> FilePath -> P m Archive
-copyFileToArchive arch fp = do
-  refArchive <- asks envRefArchive
-  distArchive <- asks envDistArchive
-  case findEntryByPath fp refArchive `mplus` findEntryByPath fp distArchive of
-    Nothing -> fail $ fp ++ " missing in reference file"
-    Just e -> return $ addEntryToArchive e arch
-
-getMediaFiles :: PandocMonad m => P m [FilePath]
-getMediaFiles = do
-  refArchive <- asks envRefArchive
-  distArchive <- asks envDistArchive
-  let allEntries = nub $ filesInArchive refArchive ++ filesInArchive distArchive
-  return $ filter (isPrefixOf "ppt/media") allEntries
-
-
-copyFileToArchiveIfExists :: PandocMonad m => Archive -> FilePath -> P m Archive
-copyFileToArchiveIfExists arch fp = do
-  refArchive <- asks envRefArchive
-  distArchive <- asks envDistArchive
-  case findEntryByPath fp refArchive `mplus` findEntryByPath fp distArchive of
-    Nothing -> return $ arch
-    Just e -> return $ addEntryToArchive e arch
-
-inheritedFiles :: [FilePath]
-inheritedFiles = [ "_rels/.rels"
-                 , "docProps/app.xml"
-                 , "docProps/core.xml"
-                 , "ppt/slideLayouts/slideLayout4.xml"
-                 , "ppt/slideLayouts/_rels/slideLayout9.xml.rels"
-                 , "ppt/slideLayouts/_rels/slideLayout2.xml.rels"
-                 , "ppt/slideLayouts/_rels/slideLayout10.xml.rels"
-                 , "ppt/slideLayouts/_rels/slideLayout1.xml.rels"
-                 , "ppt/slideLayouts/_rels/slideLayout3.xml.rels"
-                 , "ppt/slideLayouts/_rels/slideLayout5.xml.rels"
-                 , "ppt/slideLayouts/_rels/slideLayout7.xml.rels"
-                 , "ppt/slideLayouts/_rels/slideLayout8.xml.rels"
-                 , "ppt/slideLayouts/_rels/slideLayout11.xml.rels"
-                 , "ppt/slideLayouts/_rels/slideLayout4.xml.rels"
-                 , "ppt/slideLayouts/_rels/slideLayout6.xml.rels"
-                 , "ppt/slideLayouts/slideLayout2.xml"
-                 , "ppt/slideLayouts/slideLayout8.xml"
-                 , "ppt/slideLayouts/slideLayout11.xml"
-                 , "ppt/slideLayouts/slideLayout3.xml"
-                 , "ppt/slideLayouts/slideLayout6.xml"
-                 , "ppt/slideLayouts/slideLayout9.xml"
-                 , "ppt/slideLayouts/slideLayout5.xml"
-                 , "ppt/slideLayouts/slideLayout7.xml"
-                 , "ppt/slideLayouts/slideLayout1.xml"
-                 , "ppt/slideLayouts/slideLayout10.xml"
-                 -- , "ppt/_rels/presentation.xml.rels"
-                 , "ppt/theme/theme1.xml"
-                 , "ppt/presProps.xml"
-                 -- , "ppt/slides/_rels/slide1.xml.rels"
-                 -- , "ppt/slides/_rels/slide2.xml.rels"
-                 -- This is the one we're
-                 -- going to build
-                 -- , "ppt/slides/slide2.xml"
-                 -- , "ppt/slides/slide1.xml"
-                 , "ppt/viewProps.xml"
-                 , "ppt/tableStyles.xml"
-                 , "ppt/slideMasters/_rels/slideMaster1.xml.rels"
-                 , "ppt/slideMasters/slideMaster1.xml"
-                 -- , "ppt/presentation.xml"
-                 -- , "[Content_Types].xml"
-                 ]
-
--- Here are some that might not be there. We won't fail if they're not
-possibleInheritedFiles :: [FilePath]
-possibleInheritedFiles = [ "ppt/theme/_rels/theme1.xml.rels" ]
-
-presentationToArchive :: PandocMonad m => Presentation -> P m Archive
-presentationToArchive p@(Presentation _ slides) = do
-  newArch <- foldM copyFileToArchive emptyArchive inheritedFiles
-  mediaDir <- getMediaFiles
-  newArch' <- foldM copyFileToArchiveIfExists newArch $
-              possibleInheritedFiles ++ mediaDir
-  -- presentation entry and rels. We have to do the rels first to make
-  -- sure we know the correct offset for the rIds.
-  presEntry <- presentationToPresEntry p
-  presRelsEntry <- presentationToRelsEntry p
-  slideEntries <- mapM (\(s, n) -> slideToEntry s n) $ zip slides [1..]
-  slideRelEntries <- mapM (\(s,n) -> slideToSlideRelEntry s n) $ zip slides [1..]
-  -- These have to come after everything, because they need the info
-  -- built up in the state.
-  mediaEntries <- makeMediaEntries
-  contentTypesEntry <- presentationToContentTypes p >>= contentTypesToEntry
-  -- fold everything into our inherited archive and return it.
-  return $ foldr addEntryToArchive newArch' $
-    slideEntries ++
-    slideRelEntries ++
-    mediaEntries ++
-    [contentTypesEntry, presEntry, presRelsEntry]
-
---------------------------------------------------
-
-combineShapes :: [Shape] -> [Shape]
-combineShapes [] = []
-combineShapes (s : []) = [s]
-combineShapes (pic@(Pic _ _ _) : ss) = pic : combineShapes ss
-combineShapes ((TextBox []) : ss) = combineShapes ss
-combineShapes (s : TextBox [] : ss) = combineShapes (s : ss)
-combineShapes (s@(TextBox (p:ps)) : s'@(TextBox (p':ps')) : ss)
-  | pPropHeaderType (paraProps p) == Just TitleHeader ||
-    pPropHeaderType (paraProps p) == Just SlideHeader =
-      TextBox [p] : (combineShapes $ TextBox ps : s' : ss)
-  | pPropHeaderType (paraProps p') == Just TitleHeader ||
-    pPropHeaderType (paraProps p') == Just SlideHeader =
-      s : TextBox [p'] : (combineShapes $ TextBox ps' : ss)
-  | otherwise = combineShapes $ TextBox ((p:ps) ++ (p':ps')) : ss
-combineShapes (s:ss) = s : combineShapes ss
-
---------------------------------------------------
-
-getLayout :: PandocMonad m => Slide -> P m Element
-getLayout slide = do
-  let layoutpath = case slide of
-        (MetadataSlide _ _ _ _) -> "ppt/slideLayouts/slideLayout1.xml"
-        (TitleSlide _)          -> "ppt/slideLayouts/slideLayout3.xml"
-        (ContentSlide _ _)      -> "ppt/slideLayouts/slideLayout2.xml"
-  distArchive <- asks envDistArchive
-  root <- case findEntryByPath layoutpath distArchive of
-        Just e -> case parseXMLDoc $ UTF8.toStringLazy $ fromEntry e of
-                    Just element -> return $ element
-                    Nothing      -> throwError $
-                                    PandocSomeError $
-                                    layoutpath ++ " corrupt in reference file"
-        Nothing -> throwError $
-                   PandocSomeError $
-                   layoutpath ++ " missing in reference file"
-  return root
-  -- let ns = elemToNameSpaces root
-  -- case findChild (elemName ns "p" "cSld") root of
-  --   Just element' -> return element'
-  --   Nothing       -> throwError $
-  --                    PandocSomeError $
-  --                    layoutpath ++ " not correctly formed layout file"
-
-shapeHasName :: NameSpaces -> String -> Element -> Bool
-shapeHasName ns name element
-  | Just nvSpPr <- findChild (elemName ns "p" "nvSpPr") element
-  , Just cNvPr <- findChild (elemName ns "p" "cNvPr") nvSpPr
-  , Just nm <- findAttr (QName "name" Nothing Nothing) cNvPr =
-      nm == name
-  | otherwise = False
-
--- getContentTitleShape :: NameSpaces -> Element -> Maybe Element
--- getContentTitleShape ns spTreeElem
---   | isElem ns "p" "spTree" spTreeElem =
---   filterChild (\e -> (isElem ns "p" "sp" e) && (shapeHasName ns "Title 1" e)) spTreeElem
---   | otherwise = Nothing
-
--- getSubtitleShape :: NameSpaces -> Element -> Maybe Element
--- getSubtitleShape ns spTreeElem
---   | isElem ns "p" "spTree" spTreeElem =
---   filterChild (\e -> (isElem ns "p" "sp" e) && (shapeHasName ns "Subtitle 2" e)) spTreeElem
---   | otherwise = Nothing
-
--- getDateShape :: NameSpaces -> Element -> Maybe Element
--- getDateShape ns spTreeElem
---   | isElem ns "p" "spTree" spTreeElem =
---   filterChild (\e -> (isElem ns "p" "sp" e) && (shapeHasName ns "Date Placeholder 3" e)) spTreeElem
---   | otherwise = Nothing
-
-getContentShape :: NameSpaces -> Element -> Maybe Element
-getContentShape ns spTreeElem
-  | isElem ns "p" "spTree" spTreeElem =
-  filterChild (\e -> (isElem ns "p" "sp" e) && (shapeHasName ns "Content Placeholder 2" e)) spTreeElem
-  | otherwise = Nothing
-
-
--- cursorHasName :: QName -> XMLC.Cursor -> Bool
--- cursorHasName nm cur = case XMLC.current cur of
---   Elem element -> case XMLC.tagName $ XMLC.getTag element of
---                        nm -> True
---                        _ -> False
---   _ -> False
-
--- fillInTxBody :: NameSpaces -> [Paragraph] -> Element -> Element
--- fillInTxBody ns paras txBodyElem
---   | isElem ns "p" "txBody" txBodyElem =
---       replaceNamedChildren ns "a" "p" (map paragraphToElement paras) txBodyElem
---   | otherwise = txBodyElem
-
--- fillInShape :: NameSpaces -> Shape -> Element -> Element
--- fillInShape ns shape spElem
---   | TextBox paras <- shape
---   , isElemn ns "p" "sp" spElem =
---       replaceNamedChildren ns "p" "txBody" (fillInTxBody ns paras sp
-
-
--- fillInShape :: NameSpaces -> Element -> Shape -> Element
--- fillInShape ns spElem (TextBox paras) = fillInParagraphs ns spElem paras
--- fillInShape _ spElem pic = spElem
-
-contentIsElem :: NameSpaces -> String -> String -> Content -> Bool
-contentIsElem ns prefix name (Elem element) = isElem ns prefix name element
-contentIsElem _ _ _ _ = False
-
-replaceNamedChildren :: NameSpaces -> String -> String -> [Element] -> Element -> Element
-replaceNamedChildren ns prefix name newKids element =
-  let content = elContent element
-      content' = filter (\c -> not (contentIsElem ns prefix name c)) content
-  in
-    element{elContent = content' ++ map Elem newKids}
-
-
-----------------------------------------------------------------
-
-registerLink :: PandocMonad m => (URL, String) -> P m Int
-registerLink link = do
-  curSlideId <- gets stCurSlideId
-  linkReg <- gets stLinkIds
-  mediaReg <- gets stMediaIds
-  let maxLinkId = case M.lookup curSlideId linkReg of
-        Just mp -> case M.keys mp of
-          [] -> 1
-          ks -> maximum ks
-        Nothing -> 1
-      maxMediaId = case M.lookup curSlideId mediaReg of
-        Just [] -> 1
-        Just mInfos -> maximum $ map mInfoLocalId mInfos
-        Nothing -> 1
-      maxId = max maxLinkId maxMediaId
-      slideLinks = case M.lookup curSlideId linkReg of
-        Just mp -> M.insert (maxId + 1) link mp
-        Nothing -> M.singleton (maxId + 1) link
-  modify $ \st -> st{ stLinkIds = M.insert curSlideId slideLinks linkReg}
-  return $ maxId + 1
-
-registerMedia :: PandocMonad m => FilePath -> [ParaElem] -> P m MediaInfo
-registerMedia fp caption = do
-  curSlideId <- gets stCurSlideId
-  linkReg <- gets stLinkIds
-  mediaReg <- gets stMediaIds
-  globalIds <- gets stMediaGlobalIds
-  let maxLinkId = case M.lookup curSlideId linkReg of
-        Just mp -> case M.keys mp of
-          [] -> 1
-          ks -> maximum ks
-        Nothing -> 1
-      maxMediaId = case M.lookup curSlideId mediaReg of
-        Just [] -> 1
-        Just mInfos -> maximum $ map mInfoLocalId mInfos
-        Nothing -> 1
-      maxLocalId = max maxLinkId maxMediaId
-
-      maxGlobalId = case M.elems globalIds of
-        [] -> 0
-        ids -> maximum ids
-
-  (imgBytes, mbMt) <- P.fetchItem fp
-  let imgExt = (mbMt >>= extensionFromMimeType >>= (\x -> return $ '.':x))
-               <|>
-               case imageType imgBytes of
-                 Just Png  -> Just ".png"
-                 Just Jpeg -> Just ".jpeg"
-                 Just Gif  -> Just ".gif"
-                 Just Pdf  -> Just ".pdf"
-                 Just Eps  -> Just ".eps"
-                 Just Svg  -> Just ".svg"
-                 Nothing   -> Nothing
-
-  let newGlobalId = case M.lookup fp globalIds of
-        Just ident -> ident
-        Nothing    -> maxGlobalId + 1
-
-  let newGlobalIds = M.insert fp newGlobalId globalIds
-
-  let mediaInfo = MediaInfo { mInfoFilePath = fp
-                            , mInfoLocalId = maxLocalId + 1
-                            , mInfoGlobalId = newGlobalId
-                            , mInfoMimeType = mbMt
-                            , mInfoExt = imgExt
-                            , mInfoCaption = (not . null) caption
-                            }
-
-  let slideMediaInfos = case M.lookup curSlideId mediaReg of
-        Just minfos -> mediaInfo : minfos
-        Nothing     -> [mediaInfo]
-
-
-  modify $ \st -> st{ stMediaIds = M.insert curSlideId slideMediaInfos mediaReg
-                    , stMediaGlobalIds = newGlobalIds
-                    }
-  return mediaInfo
-
-makeMediaEntry :: PandocMonad m => MediaInfo -> P m Entry
-makeMediaEntry mInfo = do
-  epochtime <- (floor . utcTimeToPOSIXSeconds) <$> asks envUTCTime
-  (imgBytes, _) <- P.fetchItem (mInfoFilePath mInfo)
-  let ext = case mInfoExt mInfo of
-              Just e -> e
-              Nothing -> ""
-  let fp = "ppt/media/image" ++ (show $ mInfoGlobalId mInfo) ++ ext
-  return $ toEntry fp epochtime $ BL.fromStrict imgBytes
-
-makeMediaEntries :: PandocMonad m => P m [Entry]
-makeMediaEntries = do
-  mediaInfos <- gets stMediaIds
-  let allInfos = mconcat $ M.elems mediaInfos
-  mapM makeMediaEntry allInfos
-
--- | Scales the image to fit the page
--- sizes are passed in emu
-fitToPage' :: (Double, Double)  -- image size in emu
-           -> Integer           -- pageWidth
-           -> Integer           -- pageHeight
-           -> (Integer, Integer) -- imagesize
-fitToPage' (x, y) pageWidth pageHeight
-  -- Fixes width to the page width and scales the height
-  | x <= fromIntegral pageWidth && y <= fromIntegral pageHeight =
-      (floor x, floor y)
-  | x / fromIntegral pageWidth > y / fromIntegral pageWidth =
-      (pageWidth, floor $ ((fromIntegral pageWidth) / x) * y)
-  | otherwise =
-      (floor $ ((fromIntegral pageHeight) / y) * x, pageHeight)
-
-positionImage :: (Double, Double) -> Integer -> Integer -> (Integer, Integer)
-positionImage (x, y) pageWidth pageHeight =
-  let (x', y') = fitToPage' (x, y) pageWidth pageHeight
-  in
-    ((pageWidth - x') `div` 2, (pageHeight - y') `div`  2)
-
-getMaster :: PandocMonad m => P m Element
-getMaster = do
-  refArchive <- asks envRefArchive
-  distArchive <- asks envDistArchive
-  parseXml refArchive distArchive "ppt/slideMasters/slideMaster1.xml"
-
--- We want to get the header dimensions, so we can make sure that the
--- image goes underneath it. We only use this in a content slide if it
--- has a header.
-
-getHeaderSize :: PandocMonad m => P m ((Integer, Integer), (Integer, Integer))
-getHeaderSize = do
-  master <- getMaster
-  let ns = elemToNameSpaces master
-      sps = [master] >>=
-            findChildren (elemName ns "p" "cSld") >>=
-            findChildren (elemName ns "p" "spTree") >>=
-            findChildren (elemName ns "p" "sp")
-      mbXfrm =
-        listToMaybe (filter (shapeHasName ns "Title Placeholder 1") sps) >>=
-        findChild (elemName ns "p" "spPr") >>=
-        findChild (elemName ns "a" "xfrm")
-      xoff = mbXfrm >>=
-             findChild (elemName ns "a" "off") >>=
-             findAttr (QName "x" Nothing Nothing) >>=
-             (listToMaybe . (\s -> reads s :: [(Integer, String)]))
-      yoff = mbXfrm >>=
-             findChild (elemName ns "a" "off") >>=
-             findAttr (QName "y" Nothing Nothing) >>=
-             (listToMaybe . (\s -> reads s :: [(Integer, String)]))
-      xext = mbXfrm >>=
-             findChild (elemName ns "a" "ext") >>=
-             findAttr (QName "cx" Nothing Nothing) >>=
-             (listToMaybe . (\s -> reads s :: [(Integer, String)]))
-      yext = mbXfrm >>=
-             findChild (elemName ns "a" "ext") >>=
-             findAttr (QName "cy" Nothing Nothing) >>=
-             (listToMaybe . (\s -> reads s :: [(Integer, String)]))
-      off = case xoff of
-              Just (xoff', _) | Just (yoff',_) <- yoff -> (xoff', yoff')
-              _                               -> (1043490, 1027664)
-      ext = case xext of
-              Just (xext', _) | Just (yext',_) <- yext -> (xext', yext')
-              _                               -> (7024744, 1143000)
-  return $ (off, ext)
-
-
--- Hard-coded for now
-captionPosition :: ((Integer, Integer), (Integer, Integer))
-captionPosition = ((457200, 6061972), (8229600, 527087))
-
-createCaption :: PandocMonad m => [ParaElem] -> P m Element
-createCaption paraElements = do
-  let para = Paragraph def{pPropAlign = Just AlgnCenter} paraElements
-  elements <- mapM paragraphToElement [para]
-  let ((x, y), (cx, cy)) = captionPosition
-  let txBody = mknode "p:txBody" [] $
-               [mknode "a:bodyPr" [] (), mknode "a:lstStyle" [] ()] ++ elements
-  return $
-    mknode "p:sp" [] [ mknode "p:nvSpPr" []
-                       [ mknode "p:cNvPr" [("id","1"), ("name","TextBox 3")] ()
-                       , mknode "p:cNvSpPr" [("txBox", "1")] ()
-                       , mknode "p:nvPr" [] ()
-                       ]
-                     , mknode "p:spPr" []
-                       [ mknode "a:xfrm" []
-                         [ mknode "a:off" [("x", show x), ("y", show y)] ()
-                         , mknode "a:ext" [("cx", show cx), ("cy", show cy)] ()
-                         ]
-                       , mknode "a:prstGeom" [("prst", "rect")]
-                         [ mknode "a:avLst" [] ()
-                         ]
-                       , mknode "a:noFill" [] ()
-                       ]
-                     , txBody
-                     ]
-
--- Largely lifted from inlineToOpenXML' in T.P.W.Docx. Can't be easily
--- abstracted because of some different namespaces and monads. TODO.
-makePicElement :: PandocMonad m
-               => MediaInfo
-               -> Text.Pandoc.Definition.Attr
-               -> P m Element
-makePicElement mInfo attr = do
-  opts <- asks envOpts
-  pageWidth <- presSizeWidth <$> asks envPresentationSize
-  pageHeight <- getPageHeight <$> asks envPresentationSize
-  hasHeader <- asks envSlideHasHeader
-  let hasCaption = mInfoCaption mInfo
-  (imgBytes, _) <- P.fetchItem (mInfoFilePath mInfo)
-  -- We're not using x exts
-  ((hXoff, hYoff), (_, hYext)) <- if hasHeader
-                                  then getHeaderSize
-                                  else return ((0, 0), (0, 0))
-
-  let ((capX, capY), (_, _)) = if hasCaption
-                               then captionPosition
-                               else ((0,0), (0,0))
-  let (xpt,ypt) = desiredSizeInPoints opts attr
-                  (either (const def) id (imageSize opts imgBytes))
-  -- 12700 emu = 1 pt
-  let (xemu,yemu) = fitToPage' (xpt * 12700, ypt * 12700)
-                    ((pageWidth * 12700) - (2 * hXoff) - (2 * capX))
-                    ((if hasCaption then capY else (pageHeight * 12700)) - (hYoff + hYext))
-      (xoff, yoff) = positionImage (xpt * 12700, ypt * 12700) (pageWidth * 12700) (pageHeight * 12700)
-      xoff' = if hasHeader then xoff + hXoff else xoff
-      xoff'' = if hasCaption then xoff' + capX else xoff'
-      yoff' = if hasHeader then hYoff + hYext else yoff
-      -- let (xemu,yemu)=((floor $ xpt * 12700), (floor $ ypt * 12700))
-  let cNvPicPr = mknode "p:cNvPicPr" [] $
-                 mknode "a:picLocks" [("noGrp","1")
-                                     ,("noChangeAspect","1")] ()
-  let nvPicPr  = mknode "p:nvPicPr" []
-                 [ mknode "p:cNvPr"
-                   [("descr", mInfoFilePath mInfo),("id","0"),("name","Picture 1")] ()
-                 , cNvPicPr
-                 , mknode "p:nvPr" [] ()]
-  let blipFill = mknode "p:blipFill" []
-                 [ mknode "a:blip" [("r:embed", "rId" ++ (show $ mInfoLocalId mInfo))] ()
-                 , mknode "a:stretch" [] $
-                   mknode "a:fillRect" [] () ]
-  let xfrm =    mknode "a:xfrm" []
-                [ mknode "a:off" [("x",show xoff''), ("y",show yoff')] ()
-                , mknode "a:ext" [("cx",show xemu)
-                                 ,("cy",show yemu)] () ]
-  let prstGeom = mknode "a:prstGeom" [("prst","rect")] $
-                 mknode "a:avLst" [] ()
-  let ln =      mknode "a:ln" [("w","9525")]
-                [ mknode "a:noFill" [] ()
-                , mknode "a:headEnd" [] ()
-                , mknode "a:tailEnd" [] () ]
-  let spPr =    mknode "p:spPr" [("bwMode","auto")]
-                [xfrm, prstGeom, mknode "a:noFill" [] (), ln]
-  return $
-    mknode "p:pic" []
-      [ nvPicPr
-      , blipFill
-      , spPr ]
-
--- Currently hardcoded, until I figure out how to make it dynamic.
-blockQuoteSize :: Pixels
-blockQuoteSize = 20
-
-noteSize :: Pixels
-noteSize = 18
-
-paraElemToElement :: PandocMonad m => ParaElem -> P m Element
-paraElemToElement Break = return $ mknode "a:br" [] ()
-paraElemToElement (Run rpr s) = do
-  let attrs =
-        if rPropCode rpr
-        then []
-        else (case rPropForceSize rpr of
-                Just n -> [("sz", (show $ n * 100))]
-                Nothing -> []) ++
-             (if rPropBold rpr then [("b", "1")] else []) ++
-             (if rPropItalics rpr then [("i", "1")] else []) ++
-             (case rStrikethrough rpr of
-                Just NoStrike     -> [("strike", "noStrike")]
-                Just SingleStrike -> [("strike", "sngStrike")]
-                Just DoubleStrike -> [("strike", "dblStrike")]
-                Nothing -> []) ++
-             (case rBaseline rpr of
-                Just n -> [("baseline", show n)]
-                Nothing -> []) ++
-             (case rCap rpr of
-                Just NoCapitals -> [("cap", "none")]
-                Just SmallCapitals -> [("cap", "small")]
-                Just AllCapitals -> [("cap", "all")]
-                Nothing -> []) ++
-             []
-  linkProps <- case rLink rpr of
-                 Just link -> do idNum <- registerLink link
-                                 return [mknode "a:hlinkClick"
-                                          [("r:id", "rId" ++ show idNum)]
-                                          ()
-                                        ]
-                 Nothing -> return []
-  let propContents = if rPropCode rpr
-                     then [mknode "a:latin" [("typeface", "Courier")] ()]
-                     else linkProps
-  return $ mknode "a:r" [] [ mknode "a:rPr" attrs propContents
-                           , mknode "a:t" [] s
-                           ]
-paraElemToElement (MathElem mathType texStr) = do
-  res <- convertMath writeOMML mathType (unTeXString texStr)
-  case res of
-    Right r -> return $ mknode "a14:m" [] $ addMathInfo r
-    Left (Str s) -> paraElemToElement (Run def s)
-    Left _       -> throwError $ PandocShouldNeverHappenError "non-string math fallback"
-
--- This is a bit of a kludge -- really requires adding an option to
--- TeXMath, but since that's a different package, we'll do this one
--- step at a time.
-addMathInfo :: Element -> Element
-addMathInfo element =
-  let mathspace = Attr { attrKey = (QName "m" Nothing (Just "xmlns"))
-                       , attrVal = "http://schemas.openxmlformats.org/officeDocument/2006/math"
-                       }
-  in add_attr mathspace element
-
--- We look through the element to see if it contains an a14:m
--- element. If so, we surround it. This is a bit ugly, but it seems
--- more dependable than looking through shapes for math. Plus this is
--- an xml implementation detail, so it seems to make sense to do it at
--- the xml level.
-surroundWithMathAlternate :: Element -> Element
-surroundWithMathAlternate element =
-  case findElement (QName "m" Nothing (Just "a14")) element of
-    Just _ ->
-      mknode "mc:AlternateContent"
-         [("xmlns:mc", "http://schemas.openxmlformats.org/markup-compatibility/2006")
-         ] [ mknode "mc:Choice"
-             [ ("xmlns:a14", "http://schemas.microsoft.com/office/drawing/2010/main")
-             , ("Requires", "a14")] [ element ]
-           ]
-    Nothing -> element
-
-paragraphToElement :: PandocMonad m => Paragraph -> P m Element
-paragraphToElement par = do
-  let
-    attrs = [("lvl", show $ pPropLevel $ paraProps par)] ++
-            (case pPropMarginLeft (paraProps par) of
-               Just px -> [("marL", show $ 12700 * px), ("indent", "0")]
-               Nothing -> []
-            ) ++
-            (case pPropAlign (paraProps par) of
-               Just AlgnLeft -> [("algn", "l")]
-               Just AlgnRight -> [("algn", "r")]
-               Just AlgnCenter -> [("algn", "ctr")]
-               Nothing -> []
-            )
-    props = [] ++
-            (case pPropBullet $ paraProps par of
-               Just Bullet -> []
-               Just (AutoNumbering attrs') ->
-                 [mknode "a:buAutoNum" [("type", autoNumberingToType attrs')] ()]
-               Nothing -> [mknode "a:buNone" [] ()]
-            )
-  paras <- mapM paraElemToElement (paraElems par)
-  return $ mknode "a:p" [] $ [mknode "a:pPr" attrs props] ++ paras
-
-shapeToElement :: PandocMonad m => Element -> Shape -> P m Element
-shapeToElement layout (TextBox paras)
-  | ns <- elemToNameSpaces layout
-  , Just cSld <- findChild (elemName ns "p" "cSld") layout
-  , Just spTree <- findChild (elemName ns "p" "spTree") cSld
-  , Just sp <- getContentShape ns spTree = do
-      elements <- mapM paragraphToElement paras
-      let txBody = mknode "p:txBody" [] $
-                   [mknode "a:bodyPr" [] (), mknode "a:lstStyle" [] ()] ++ elements
-          emptySpPr = mknode "p:spPr" [] ()
-      return $
-        surroundWithMathAlternate $
-        replaceNamedChildren ns "p" "txBody" [txBody] $
-        replaceNamedChildren ns "p" "spPr" [emptySpPr] $
-        sp
-  -- XXX: TODO
-  | otherwise = return $ mknode "p:sp" [] ()
--- XXX: TODO
-shapeToElement layout (Pic fp attr alt) = do
-  mInfo <- registerMedia fp alt
-  case mInfoExt mInfo of
-    Just _ -> makePicElement mInfo attr
-    Nothing -> shapeToElement layout $ TextBox [Paragraph def alt]
-shapeToElement _ (GraphicFrame tbls _) = do
-  elements <- mapM graphicToElement tbls
-  return $ mknode "p:graphicFrame" [] $
-    [ mknode "p:nvGraphicFramePr" [] $
-      [ mknode "p:cNvPr" [("id", "6"), ("name", "Content Placeholder 5")] ()
-      , mknode "p:cNvGraphicFramePr" [] $
-        [mknode "a:graphicFrameLocks" [("noGrp", "1")] ()]
-      , mknode "p:nvPr" [] $
-        [mknode "p:ph" [("idx", "1")] ()]
-      ]
-    , mknode "p:xfrm" [] $
-      [ mknode "a:off" [("x", "457200"), ("y", "1600200")] ()
-      , mknode "a:ext" [("cx", "8029388"), ("cy", "3644152")] ()
-      ]
-    ] ++ elements
-
-shapeToElements :: PandocMonad m => Element -> Shape -> P m [Element]
-shapeToElements layout shp = do
-  case shp of
-    (Pic _ _ alt) | (not . null) alt -> do
-      element <- shapeToElement layout shp
-      caption <- createCaption alt
-      return [element, caption]
-    (GraphicFrame _ cptn) | (not . null) cptn -> do
-      element <- shapeToElement layout shp
-      caption <- createCaption cptn
-      return [element, caption]
-    _ -> do
-      element <- shapeToElement layout shp
-      return [element]
-
-shapesToElements :: PandocMonad m => Element -> [Shape] -> P m [Element]
-shapesToElements layout shps = do
- concat <$> mapM (shapeToElements layout) shps
-
-hardcodedTableMargin :: Integer
-hardcodedTableMargin = 36
-
-
-graphicToElement :: PandocMonad m => Graphic -> P m Element
-graphicToElement (Tbl tblPr colWidths hdrCells rows) = do
-  let cellToOpenXML paras = do elements <- mapM paragraphToElement paras
-                               return $
-                                 [mknode "a:txBody" [] $
-                                  ([ mknode "a:bodyPr" [] ()
-                                   , mknode "a:lstStyle" [] ()]
-                                   ++ elements)]
-  headers' <- mapM cellToOpenXML hdrCells
-  rows' <- mapM (mapM cellToOpenXML) rows
-  let borderProps = mknode "a:tcPr" [] ()
-  let emptyCell = [mknode "a:p" [] [mknode "a:pPr" [] ()]]
-  let mkcell border contents = mknode "a:tc" []
-                            $ (if null contents
-                               then emptyCell
-                               else contents) ++ [ borderProps | border ]
-  let mkrow border cells = mknode "a:tr" [("h", "0")] $ map (mkcell border) cells
-  -- let textwidth = 14400  -- 5.5 in in twips, 1/20 pt
-  -- let fullrow = 14400 -- 100% specified in pct
-  -- let rowwidth = fullrow * sum colWidths
-
-  let mkgridcol w = mknode "a:gridCol"
-                       [("w", show ((12700 * w) :: Integer))] ()
-  let hasHeader = not (all null hdrCells)
-  return $ mknode "a:graphic" [] $
-    [mknode "a:graphicData" [("uri", "http://schemas.openxmlformats.org/drawingml/2006/table")] $
-     [mknode "a:tbl" [] $
-      [ mknode "a:tblPr" [ ("firstRow", if tblPrFirstRow tblPr then "1" else "0")
-                         , ("bandRow", if tblPrBandRow tblPr then "1" else "0")
-                         ] ()
-      , mknode "a:tblGrid" [] (if all (==0) colWidths
-                               then []
-                               else map mkgridcol colWidths)
-      ]
-      ++ [ mkrow True headers' | hasHeader ] ++ map (mkrow False) rows'
-     ]
-    ]
-
-getShapeByName :: NameSpaces -> Element -> String -> Maybe Element
-getShapeByName ns spTreeElem name
-  | isElem ns "p" "spTree" spTreeElem =
-  filterChild (\e -> (isElem ns "p" "sp" e) && (shapeHasName ns name e)) spTreeElem
-  | otherwise = Nothing
-
-nonBodyTextToElement :: PandocMonad m => Element -> String -> [ParaElem] -> P m Element
-nonBodyTextToElement layout shapeName paraElements
-  | ns <- elemToNameSpaces layout
-  , Just cSld <- findChild (elemName ns "p" "cSld") layout
-  , Just spTree <- findChild (elemName ns "p" "spTree") cSld
-  , Just sp <- getShapeByName ns spTree shapeName = do
-      let hdrPara = Paragraph def paraElements
-      element <- paragraphToElement hdrPara
-      let txBody = mknode "p:txBody" [] $
-                   [mknode "a:bodyPr" [] (), mknode "a:lstStyle" [] ()] ++
-                   [element]
-      return $ replaceNamedChildren ns "p" "txBody" [txBody] sp
-  -- XXX: TODO
-  | otherwise = return $ mknode "p:sp" [] ()
-
-
--- hdrToElement :: Element -> [ParaElem] -> Element
--- hdrToElement layout paraElems
---   | ns <- elemToNameSpaces layout
---   , Just cSld <- findChild (elemName ns "p" "cSld") layout
---   , Just spTree <- findChild (elemName ns "p" "spTree") cSld
---   , Just sp <- getContentTitleShape ns spTree =
---   let hdrPara = Paragraph def paraElems
---       txBody = mknode "p:txBody" [] $
---                [mknode "a:bodyPr" [] (), mknode "a:lstStyle" [] ()] ++
---                [paragraphToElement hdrPara]
---   in
---     replaceNamedChildren ns "p" "txBody" [txBody] sp
---   -- XXX: TODO
---   | otherwise = mknode "p:sp" [] ()
--- -- XXX: TODO
--- hdrToElement _ _ = mknode "p:sp" [] ()
-
-contentToElement :: PandocMonad m => Element -> [ParaElem] -> [Shape] -> P m Element
-contentToElement layout hdrShape shapes
-  | ns <- elemToNameSpaces layout
-  , Just cSld <- findChild (elemName ns "p" "cSld") layout
-  , Just spTree <- findChild (elemName ns "p" "spTree") cSld = do
-      element <- nonBodyTextToElement layout "Title 1" hdrShape
-      let hdrShapeElements = if null hdrShape
-                             then []
-                             else [element]
-      contentElements <- shapesToElements layout shapes
-      return $
-        replaceNamedChildren ns "p" "sp"
-        (hdrShapeElements ++ contentElements)
-        spTree
-contentToElement _ _ _ = return $ mknode "p:sp" [] ()
-
-titleToElement :: PandocMonad m => Element -> [ParaElem] -> P m Element
-titleToElement layout titleElems
-  | ns <- elemToNameSpaces layout
-  , Just cSld <- findChild (elemName ns "p" "cSld") layout
-  , Just spTree <- findChild (elemName ns "p" "spTree") cSld = do
-      element <- nonBodyTextToElement layout "Title 1" titleElems
-      let titleShapeElements = if null titleElems
-                               then []
-                               else [element]
-      return $ replaceNamedChildren ns "p" "sp" titleShapeElements spTree
-titleToElement _ _ = return $ mknode "p:sp" [] ()
-
-metadataToElement :: PandocMonad m => Element -> [ParaElem] -> [ParaElem] -> [[ParaElem]] -> [ParaElem] -> P m Element
-metadataToElement layout titleElems subtitleElems authorsElems dateElems
-  | ns <- elemToNameSpaces layout
-  , Just cSld <- findChild (elemName ns "p" "cSld") layout
-  , Just spTree <- findChild (elemName ns "p" "spTree") cSld = do
-      titleShapeElements <- if null titleElems
-                            then return []
-                            else sequence [nonBodyTextToElement layout "Title 1" titleElems]
-      let combinedAuthorElems = intercalate [Break] authorsElems
-          subtitleAndAuthorElems = intercalate [Break, Break] [subtitleElems, combinedAuthorElems]
-      subtitleShapeElements <- if null subtitleAndAuthorElems
-                               then return []
-                               else sequence [nonBodyTextToElement layout "Subtitle 2" subtitleAndAuthorElems]
-      dateShapeElements <- if null dateElems
-                           then return []
-                           else sequence [nonBodyTextToElement layout "Date Placeholder 3" dateElems]
-      return $ replaceNamedChildren ns "p" "sp"
-        (titleShapeElements ++ subtitleShapeElements ++ dateShapeElements)
-        spTree
-metadataToElement _ _ _ _ _ = return $ mknode "p:sp" [] ()
-
-slideToElement :: PandocMonad m => Slide -> P m Element
-slideToElement s@(ContentSlide hdrElems shapes) = do
-  layout <- getLayout s
-  spTree <- local (\env -> if null hdrElems
-                           then env
-                           else env{envSlideHasHeader=True}) $
-            contentToElement layout hdrElems shapes
-  return $ mknode "p:sld"
-    [ ("xmlns:a", "http://schemas.openxmlformats.org/drawingml/2006/main"),
-      ("xmlns:r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships"),
-      ("xmlns:p", "http://schemas.openxmlformats.org/presentationml/2006/main")
-    ] [mknode "p:cSld" [] [spTree]]
-slideToElement s@(TitleSlide hdrElems) = do
-  layout <- getLayout s
-  spTree <- titleToElement layout hdrElems
-  return $ mknode "p:sld"
-    [ ("xmlns:a", "http://schemas.openxmlformats.org/drawingml/2006/main"),
-      ("xmlns:r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships"),
-      ("xmlns:p", "http://schemas.openxmlformats.org/presentationml/2006/main")
-    ] [mknode "p:cSld" [] [spTree]]
-slideToElement s@(MetadataSlide titleElems subtitleElems authorElems dateElems) = do
-  layout <- getLayout s
-  spTree <- metadataToElement layout titleElems subtitleElems authorElems dateElems
-  return $ mknode "p:sld"
-    [ ("xmlns:a", "http://schemas.openxmlformats.org/drawingml/2006/main"),
-      ("xmlns:r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships"),
-      ("xmlns:p", "http://schemas.openxmlformats.org/presentationml/2006/main")
-    ] [mknode "p:cSld" [] [spTree]]
-
------------------------------------------------------------------------
-
-slideToFilePath :: Slide -> Int -> FilePath
-slideToFilePath _ idNum = "slide" ++ (show $ idNum) ++ ".xml"
-
-slideToSlideId :: Monad m => Slide -> Int -> P m String
-slideToSlideId _ idNum = do
-  n <- gets stSlideIdOffset
-  return $ "rId" ++ (show $ idNum + n)
-
-
-data Relationship = Relationship { relId :: Int
-                                 , relType :: MimeType
-                                 , relTarget :: FilePath
-                                 } deriving (Show, Eq)
-
-elementToRel :: Element -> Maybe Relationship
-elementToRel element
-  | elName element == QName "Relationship" (Just "http://schemas.openxmlformats.org/package/2006/relationships") Nothing =
-      do rId <- findAttr (QName "Id" Nothing Nothing) element
-         numStr <- stripPrefix "rId" rId
-         num <- case reads numStr :: [(Int, String)] of
-           (n, _) : _ -> Just n
-           []         -> Nothing
-         type' <- findAttr (QName "Type" Nothing Nothing) element
-         target <- findAttr (QName "Target" Nothing Nothing) element
-         return $ Relationship num type' target
-  | otherwise = Nothing
-
-slideToPresRel :: Monad m => Slide -> Int -> P m Relationship
-slideToPresRel slide idNum = do
-  n <- gets stSlideIdOffset
-  let rId = idNum + n
-      fp = "slides/" ++ slideToFilePath slide idNum
-  return $ Relationship { relId = rId
-                        , relType = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/slide"
-                        , relTarget = fp
-                        }
-
-getRels :: PandocMonad m => P m [Relationship]
-getRels = do
-  refArchive <- asks envRefArchive
-  distArchive <- asks envDistArchive
-  relsElem <- parseXml refArchive distArchive "ppt/_rels/presentation.xml.rels"
-  let globalNS = "http://schemas.openxmlformats.org/package/2006/relationships"
-  let relElems = findChildren (QName "Relationship" (Just globalNS) Nothing) relsElem
-  return $ mapMaybe elementToRel relElems
-
-presentationToRels :: PandocMonad m => Presentation -> P m [Relationship]
-presentationToRels (Presentation _ slides) = do
-  mySlideRels <- mapM (\(s, n) -> slideToPresRel s n) $ zip slides [1..]
-  rels <- getRels
-  let relsWithoutSlides = filter (\r -> relType r /= "http://schemas.openxmlformats.org/officeDocument/2006/relationships/slide") rels
-  -- We want to make room for the slides in the id space. The slides
-  -- will start at Id2 (since Id1 is for the slide master). There are
-  -- two slides in the data file, but that might change in the future,
-  -- so we will do this:
-  --
-  -- 1. We look to see what the minimum relWithoutSlide id (greater than 1) is.
-  -- 2. We add the difference between this and the number of slides to
-  -- all relWithoutSlide rels (unless they're 1)
-
-  let minRelNotOne = case filter (1<) $ map relId relsWithoutSlides of
-        [] -> 0                 -- doesn't matter in this case, since
-                                -- there will be nothing to map the
-                                -- function over
-        l  -> minimum l
-
-      modifyRelNum :: Int -> Int
-      modifyRelNum 1 = 1
-      modifyRelNum n = n - minRelNotOne + 2 + length slides
-
-      relsWithoutSlides' = map (\r -> r{relId = modifyRelNum $ relId r}) relsWithoutSlides
-
-  return $ mySlideRels ++ relsWithoutSlides'
-
-relToElement :: Relationship -> Element
-relToElement rel = mknode "Relationship" [ ("Id", "rId" ++ (show $ relId rel))
-                                         , ("Type", relType rel)
-                                         , ("Target", relTarget rel) ] ()
-
-relsToElement :: [Relationship] -> Element
-relsToElement rels = mknode "Relationships"
-                     [("xmlns", "http://schemas.openxmlformats.org/package/2006/relationships")]
-                     (map relToElement rels)
-
-presentationToRelsEntry :: PandocMonad m => Presentation -> P m Entry
-presentationToRelsEntry pres = do
-  rels <- presentationToRels pres
-  elemToEntry "ppt/_rels/presentation.xml.rels" $ relsToElement rels
-
-elemToEntry :: PandocMonad m => FilePath -> Element -> P m Entry
-elemToEntry fp element = do
-  epochtime <- (floor . utcTimeToPOSIXSeconds) <$> asks envUTCTime
-  return $ toEntry fp epochtime $ renderXml element
-
-slideToEntry :: PandocMonad m => Slide -> Int -> P m Entry
-slideToEntry slide idNum = do
-  modify $ \st -> st{stCurSlideId = idNum}
-  element <- slideToElement slide
-  elemToEntry ("ppt/slides/" ++ slideToFilePath slide idNum) element
-
-slideToSlideRelEntry :: PandocMonad m => Slide -> Int -> P m Entry
-slideToSlideRelEntry slide idNum = do
-  element <- slideToSlideRelElement slide idNum
-  elemToEntry ("ppt/slides/_rels/" ++ slideToFilePath slide idNum ++ ".rels") element
-
-linkRelElement :: Int -> (URL, String) -> Element
-linkRelElement idNum (url, _) =
-  mknode "Relationship" [ ("Id", "rId" ++ show idNum)
-                        , ("Type", "http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink")
-                        , ("Target", url)
-                        , ("TargetMode", "External")
-                        ] ()
-
-linkRelElements :: M.Map Int (URL, String) -> [Element]
-linkRelElements mp = map (\(n, lnk) -> linkRelElement n lnk) (M.toList mp)
-
-mediaRelElement :: MediaInfo -> Element
-mediaRelElement mInfo =
-  let ext = case mInfoExt mInfo of
-              Just e -> e
-              Nothing -> ""
-  in
-    mknode "Relationship" [ ("Id", "rId" ++ (show $ mInfoLocalId mInfo))
-                          , ("Type", "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image")
-                          , ("Target", "../media/image" ++ (show $ mInfoGlobalId mInfo) ++ ext)
-                          ] ()
-
-slideToSlideRelElement :: PandocMonad m => Slide -> Int -> P m Element
-slideToSlideRelElement slide idNum = do
-  let target =  case slide of
-        (MetadataSlide _ _ _ _) -> "../slideLayouts/slideLayout1.xml"
-        (TitleSlide _)        -> "../slideLayouts/slideLayout3.xml"
-        (ContentSlide _ _)    -> "../slideLayouts/slideLayout2.xml"
-
-  linkIds <- gets stLinkIds
-  mediaIds <- gets stMediaIds
-
-  let linkRels = case M.lookup idNum linkIds of
-                   Just mp -> linkRelElements mp
-                   Nothing -> []
-      mediaRels = case M.lookup idNum mediaIds of
-                   Just mInfos -> map mediaRelElement mInfos
-                   Nothing -> []
-
-  return $
-    mknode "Relationships"
-    [("xmlns", "http://schemas.openxmlformats.org/package/2006/relationships")]
-    ([mknode "Relationship" [ ("Id", "rId1")
-                           , ("Type", "http://schemas.openxmlformats.org/officeDocument/2006/relationships/slideLayout")
-                           , ("Target", target)] ()
-    ] ++ linkRels ++ mediaRels)
-
--- slideToSlideRelEntry :: PandocMonad m => Slide -> Int -> P m Entry
--- slideToSlideRelEntry slide idNum = do
---   let fp = "ppt/slides/_rels/slide" ++ (show idNum) ++ ".xml.rels"
---   elemToEntry fp $ slideToSlideRelElement slide
-
-slideToSldIdElement :: PandocMonad m => Slide -> Int -> P m Element
-slideToSldIdElement slide idNum = do
-  let id' = show $ idNum + 255
-  rId <- slideToSlideId slide idNum
-  return $ mknode "p:sldId" [("id", id'), ("r:id", rId)] ()
-
-presentationToSldIdLst :: PandocMonad m => Presentation -> P m Element
-presentationToSldIdLst (Presentation _ slides) = do
-  ids <- mapM (\(s,n) -> slideToSldIdElement s n) (zip slides [1..])
-  return $ mknode "p:sldIdLst" [] ids
-
-presentationToPresentationElement :: PandocMonad m => Presentation -> P m Element
-presentationToPresentationElement pres = do
-  refArchive <- asks envRefArchive
-  distArchive <- asks envDistArchive
-  element <- parseXml refArchive distArchive "ppt/presentation.xml"
-  sldIdLst <- presentationToSldIdLst pres
-
-  let modifySldIdLst :: Content -> Content
-      modifySldIdLst (Elem e) = case elName e of
-        (QName "sldIdLst" _ _) -> Elem sldIdLst
-        _                      -> Elem e
-      modifySldIdLst ct = ct
-
-      newContent = map modifySldIdLst $ elContent element
-
-  return $ element{elContent = newContent}
-
-presentationToPresEntry :: PandocMonad m => Presentation -> P m Entry
-presentationToPresEntry pres = presentationToPresentationElement pres >>=
-  elemToEntry "ppt/presentation.xml"
-
-
-
-
-defaultContentTypeToElem :: DefaultContentType -> Element
-defaultContentTypeToElem dct =
-  mknode "Default"
-  [("Extension", defContentTypesExt dct),
-    ("ContentType", defContentTypesType dct)]
-  ()
-
-overrideContentTypeToElem :: OverrideContentType -> Element
-overrideContentTypeToElem oct =
-  mknode "Override"
-  [("PartName", overrideContentTypesPart oct),
-    ("ContentType", overrideContentTypesType oct)]
-  ()
-
-contentTypesToElement :: ContentTypes -> Element
-contentTypesToElement ct =
-  let ns = "http://schemas.openxmlformats.org/package/2006/content-types"
-  in
-    mknode "Types" [("xmlns", ns)] $
-    (map defaultContentTypeToElem $ contentTypesDefaults ct) ++
-    (map overrideContentTypeToElem $ contentTypesOverrides ct)
-
-data DefaultContentType = DefaultContentType
-                           { defContentTypesExt :: String
-                           , defContentTypesType:: MimeType
-                           }
-                         deriving (Show, Eq)
-
-data OverrideContentType = OverrideContentType
-                           { overrideContentTypesPart :: FilePath
-                           , overrideContentTypesType :: MimeType
-                           }
-                          deriving (Show, Eq)
-
-data ContentTypes = ContentTypes { contentTypesDefaults :: [DefaultContentType]
-                                 , contentTypesOverrides :: [OverrideContentType]
-                                 }
-                    deriving (Show, Eq)
-
-contentTypesToEntry :: PandocMonad m => ContentTypes -> P m Entry
-contentTypesToEntry ct = elemToEntry "[Content_Types].xml" $ contentTypesToElement ct
-
-pathToOverride :: FilePath -> Maybe OverrideContentType
-pathToOverride fp = OverrideContentType ("/" ++ fp) <$> (getContentType fp)
-
-mediaContentType :: MediaInfo -> Maybe DefaultContentType
-mediaContentType mInfo
-  | Just ('.' : ext) <- mInfoExt mInfo =
-      Just $ DefaultContentType { defContentTypesExt = ext
-                                , defContentTypesType =
-                                    case mInfoMimeType mInfo of
-                                      Just mt -> mt
-                                      Nothing -> "application/octet-stream"
-                                }
-  | otherwise = Nothing
-
-presentationToContentTypes :: PandocMonad m => Presentation -> P m ContentTypes
-presentationToContentTypes (Presentation _ slides) = do
-  mediaInfos <- (mconcat . M.elems) <$> gets stMediaIds
-  let defaults = [ DefaultContentType "xml" "application/xml"
-                 , DefaultContentType "rels" "application/vnd.openxmlformats-package.relationships+xml"
-                 ]
-      mediaDefaults = nub $ mapMaybe mediaContentType mediaInfos
-      inheritedOverrides = mapMaybe pathToOverride inheritedFiles
-      presOverride = mapMaybe pathToOverride ["ppt/presentation.xml"]
-      slideOverrides =
-        mapMaybe
-        (\(s, n) ->
-           pathToOverride $ "ppt/slides/" ++ slideToFilePath s n)
-        (zip slides [1..])
-      -- propOverride = mapMaybe pathToOverride ["docProps/core.xml"]
-  return $ ContentTypes
-    (defaults ++ mediaDefaults)
-    (inheritedOverrides ++ presOverride ++ slideOverrides)
-
--- slideToElement :: Element -> Slide -> Element
--- slideToElement layout (ContentSlide _ shapes) =
---   let sps = map (shapeToElement layout) shapes
-
-presML :: String
-presML = "application/vnd.openxmlformats-officedocument.presentationml"
-
-noPresML :: String
-noPresML = "application/vnd.openxmlformats-officedocument"
-
-getContentType :: FilePath -> Maybe MimeType
-getContentType fp
-  | fp == "ppt/presentation.xml" = Just $ presML ++ ".presentation.main+xml"
-  | fp == "ppt/presProps.xml" = Just $ presML ++ ".presProps+xml"
-  | fp == "ppt/viewProps.xml" = Just $ presML ++ ".viewProps+xml"
-  | fp == "ppt/tableStyles.xml" = Just $ presML ++ ".tableStyles+xml"
-  | fp == "docProps/core.xml" = Just $ "application/vnd.openxmlformats-package.core-properties+xml"
-  | fp == "docProps/app.xml" = Just $ noPresML ++ ".extended-properties+xml"
-  | "ppt" : "slideMasters" : f : [] <- splitDirectories fp
-  , (_, ".xml") <- splitExtension f =
-      Just $ presML ++ ".slideMaster+xml"
-  | "ppt" : "slides" : f : [] <- splitDirectories fp
-  , (_, ".xml") <- splitExtension f =
-      Just $ presML ++ ".slide+xml"
-  | "ppt" : "notesMasters"  : f : [] <- splitDirectories fp
-  , (_, ".xml") <- splitExtension f =
-      Just $ presML ++ ".notesMaster+xml"
-  | "ppt" : "notesSlides"  : f : [] <- splitDirectories fp
-  , (_, ".xml") <- splitExtension f =
-      Just $ presML ++ ".notesSlide+xml"
-  | "ppt" : "theme" : f : [] <- splitDirectories fp
-  , (_, ".xml") <- splitExtension f =
-      Just $ noPresML ++ ".theme+xml"
-  | "ppt" : "slideLayouts" : _ : [] <- splitDirectories fp=
-      Just $ presML ++ ".slideLayout+xml"
-  | otherwise = Nothing
+{- |
+   Module      : Text.Pandoc.Writers.Powerpoint
+   Copyright   : Copyright (C) 2017-2020 Jesse Rosenthal
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : Jesse Rosenthal <jrosenthal@jhu.edu>
+   Stability   : alpha
+   Portability : portable
+
+Conversion of 'Pandoc' documents to powerpoint (pptx). -}
+
+{-
+This is a wrapper around two modules:
+
+  - Text.Pandoc.Writers.Powerpoint.Presentation (which converts a
+    pandoc document into a Presentation datatype), and
+
+  - Text.Pandoc.Writers.Powerpoint.Output (which converts a
+    Presentation into a zip archive, which can be output).
+-}
+
+module Text.Pandoc.Writers.Powerpoint (writePowerpoint) where
+
+import Codec.Archive.Zip
+import Text.Pandoc.Definition
+import Text.Pandoc.Walk
+import Text.Pandoc.Class.PandocMonad (PandocMonad, report)
+import Text.Pandoc.Options (WriterOptions)
+import Text.Pandoc.Writers.Shared (fixDisplayMath)
+import Text.Pandoc.Writers.Powerpoint.Presentation (documentToPresentation)
+import Text.Pandoc.Writers.Powerpoint.Output (presentationToArchive)
+import qualified Data.ByteString.Lazy as BL
+
+writePowerpoint :: (PandocMonad m)
+                => WriterOptions  -- ^ Writer options
+                -> Pandoc         -- ^ Document to convert
+                -> m BL.ByteString
+writePowerpoint opts (Pandoc meta blks) = do
+  let blks' = walk fixDisplayMath blks
+  let (pres, logMsgs) = documentToPresentation opts (Pandoc meta blks')
+  mapM_ report logMsgs
+  archv <- presentationToArchive opts meta pres
+  return $ fromArchive archv
diff --git a/src/Text/Pandoc/Writers/Powerpoint/Output.hs b/src/Text/Pandoc/Writers/Powerpoint/Output.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Writers/Powerpoint/Output.hs
@@ -0,0 +1,2869 @@
+{-# LANGUAGE DeriveTraversable #-}
+{-# LANGUAGE NamedFieldPuns #-}
+{-# LANGUAGE OverloadedStrings #-}
+{-# LANGUAGE PatternGuards #-}
+{-# LANGUAGE RankNTypes #-}
+{-# LANGUAGE RecordWildCards #-}
+{-# LANGUAGE TupleSections #-}
+{- |
+   Module      : Text.Pandoc.Writers.Powerpoint.Output
+   Copyright   : Copyright (C) 2017-2020 Jesse Rosenthal
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : Jesse Rosenthal <jrosenthal@jhu.edu>
+   Stability   : alpha
+   Portability : portable
+
+Conversion of Presentation datatype (defined in
+Text.Pandoc.Writers.Powerpoint.Presentation) to a zip archive.
+-}
+
+module Text.Pandoc.Writers.Powerpoint.Output ( presentationToArchive
+                                             ) where
+
+import Control.Monad ( MonadPlus(mplus), foldM, unless )
+import Control.Monad.Except (throwError, catchError)
+import Control.Monad.Reader
+    ( asks, MonadReader(local), ReaderT(runReaderT) )
+import Control.Monad.State
+    ( StateT, gets, modify, evalStateT )
+import Codec.Archive.Zip
+import Data.List (intercalate, stripPrefix, nub, union, isPrefixOf, intersperse)
+import Data.Bifunctor (bimap)
+import Data.CaseInsensitive (CI)
+import qualified Data.CaseInsensitive as CI
+import Data.Default
+import Data.Foldable (toList)
+import Data.List.NonEmpty (nonEmpty, NonEmpty ((:|)))
+import Data.Ratio ((%), Ratio)
+import Data.Text (Text)
+import qualified Data.Text as T
+import Data.Text.Read (decimal)
+import Data.Time (formatTime, defaultTimeLocale)
+import Data.Time.Clock (UTCTime)
+import Data.Time.Clock.POSIX (utcTimeToPOSIXSeconds, posixSecondsToUTCTime)
+import Data.Traversable (for)
+import System.FilePath.Posix (splitDirectories, splitExtension, takeExtension, takeFileName)
+import Text.Pandoc.XML.Light as XML
+import Text.Pandoc.Definition
+import qualified Text.Pandoc.UTF8 as UTF8
+import Text.Pandoc.Class.PandocMonad (PandocMonad)
+import Text.Pandoc.Error (PandocError(..))
+import qualified Text.Pandoc.Class.PandocMonad as P
+import Text.Pandoc.Data (readDataFile, readDefaultDataFile)
+import Text.Pandoc.Options
+import Text.Pandoc.MIME
+import qualified Data.ByteString.Lazy as BL
+import Text.Pandoc.Writers.Shared (metaToContext)
+import Text.Pandoc.Writers.OOXML
+import qualified Data.Map as M
+import Data.Maybe (mapMaybe, listToMaybe, fromMaybe, maybeToList, catMaybes, isJust)
+import Text.Pandoc.ImageSize
+import Control.Applicative ((<|>))
+import System.FilePath.Glob
+import Text.DocTemplates (FromContext(lookupContext), Context)
+import Text.DocLayout (literal)
+import Text.TeXMath
+import Text.Pandoc.Logging (LogMessage(PowerpointTemplateWarning))
+import Text.Pandoc.Writers.Math (convertMath)
+import Text.Pandoc.Writers.Powerpoint.Presentation
+import Text.Pandoc.Shared (tshow, stringify)
+import Skylighting (fromColor)
+
+-- |The 'EMU' type is used to specify sizes in English Metric Units.
+type EMU = Integer
+
+-- |The 'pixelsToEmu' function converts a size in pixels to one
+-- in English Metric Units. It assumes a DPI of 72.
+pixelsToEmu :: Pixels -> EMU
+pixelsToEmu = (12700 *)
+
+-- This populates the global ids map with images already in the
+-- template, so the ids won't be used by images introduced by the
+-- user.
+initialGlobalIds :: Archive -> Archive -> M.Map FilePath Int
+initialGlobalIds refArchive distArchive =
+  let archiveFiles = filesInArchive refArchive `union` filesInArchive distArchive
+      mediaPaths = filter (isPrefixOf "ppt/media/image") archiveFiles
+
+      go :: FilePath -> Maybe (FilePath, Int)
+      go fp = do
+        s <- stripPrefix "ppt/media/image" $ fst $ splitExtension fp
+        (n, _) <- listToMaybe $ reads s
+        return (fp, n)
+  in
+    M.fromList $ mapMaybe go mediaPaths
+
+getPresentationSize :: Archive -> Archive -> Maybe (Integer, Integer)
+getPresentationSize refArchive distArchive = do
+  entry <- findEntryByPath "ppt/presentation.xml" refArchive  `mplus`
+           findEntryByPath "ppt/presentation.xml" distArchive
+  presElement <- either (const Nothing) return $
+                   parseXMLElement $ UTF8.toTextLazy $ fromEntry entry
+  let ns = elemToNameSpaces presElement
+  sldSize <- findChild (elemName ns "p" "sldSz") presElement
+  cxS <- findAttr (QName "cx" Nothing Nothing) sldSize
+  cyS <- findAttr (QName "cy" Nothing Nothing) sldSize
+  cx <- readTextAsInteger cxS
+  cy <- readTextAsInteger cyS
+  return (cx `div` 12700, cy `div` 12700)
+
+readTextAsInteger :: Text -> Maybe Integer
+readTextAsInteger = either (const Nothing) (Just . fst) . Data.Text.Read.decimal
+
+data WriterEnv = WriterEnv { envRefArchive :: Archive
+                           , envDistArchive :: Archive
+                           , envUTCTime :: UTCTime
+                           , envOpts :: WriterOptions
+                           , envContext :: Context Text
+                           , envPresentationSize :: (Integer, Integer)
+                           , envSlideHasHeader :: Bool
+                           , envInList :: Bool
+                           , envInNoteSlide :: Bool
+                           , envCurSlideId :: Int
+                           , envPlaceholder :: Placeholder
+                           , envSlideIdMap :: M.Map SlideId Int
+                           -- maps the slide number to the
+                           -- corresponding notes id number. If there
+                           -- are no notes for a slide, there will be
+                           -- no entry in the map for it.
+                           , envSpeakerNotesIdMap :: M.Map Int Int
+                           , envInSpeakerNotes :: Bool
+                           , envSlideLayouts :: Maybe SlideLayouts
+                           , envOtherStyleIndents :: Maybe Indents
+                           }
+                 deriving (Show)
+
+instance Default WriterEnv where
+  def = WriterEnv { envRefArchive = emptyArchive
+                  , envDistArchive = emptyArchive
+                  , envUTCTime = posixSecondsToUTCTime 0
+                  , envOpts = def
+                  , envContext = mempty
+                  , envPresentationSize = (720, 540)
+                  , envSlideHasHeader = False
+                  , envInList = False
+                  , envInNoteSlide = False
+                  , envCurSlideId = 1
+                  , envPlaceholder = Placeholder ObjType 0
+                  , envSlideIdMap = mempty
+                  , envSpeakerNotesIdMap = mempty
+                  , envInSpeakerNotes = False
+                  , envSlideLayouts = Nothing
+                  , envOtherStyleIndents = Nothing
+                  }
+
+type SlideLayouts = SlideLayoutsOf SlideLayout
+
+data SlideLayoutsOf a = SlideLayouts
+  { metadata :: a
+  , title :: a
+  , content :: a
+  , twoColumn :: a
+  , comparison :: a
+  , contentWithCaption :: a
+  , blank :: a
+  } deriving (Show, Eq, Functor, Foldable, Traversable)
+
+data SlideLayout = SlideLayout
+  { slElement :: Element
+  , slInReferenceDoc :: Bool
+    -- ^ True if the layout is in the provided reference doc, False if it's in
+    -- the default reference doc.
+  , slPath :: FilePath
+  , slEntry :: Entry
+  } deriving (Show)
+
+getSlideLayouts :: PandocMonad m => P m SlideLayouts
+getSlideLayouts = asks envSlideLayouts >>= maybe (throwError e) pure
+  where
+    e = PandocSomeError ("Slide layouts aren't defined, even though they should "
+      <> "always be. This is a bug in pandoc.")
+
+-- | A placeholder within a layout, identified by type and index.
+--
+-- E.g., @Placeholder ObjType 2@ is the third placeholder of type 'ObjType' in
+-- the layout.
+data Placeholder = Placeholder
+  { placeholderType :: PHType
+  , index :: Int
+  } deriving (Show, Eq)
+
+-- | Paragraph indentation info.
+data Indents = Indents
+  { level1 :: Maybe LevelIndents
+  , level2 :: Maybe LevelIndents
+  , level3 :: Maybe LevelIndents
+  , level4 :: Maybe LevelIndents
+  , level5 :: Maybe LevelIndents
+  , level6 :: Maybe LevelIndents
+  , level7 :: Maybe LevelIndents
+  , level8 :: Maybe LevelIndents
+  , level9 :: Maybe LevelIndents
+  } deriving (Show, Eq)
+
+levelIndent :: Indents -> Int -> Maybe LevelIndents
+levelIndent is index = getter is
+  where
+    getter = case index of
+      0 -> level1
+      1 -> level2
+      2 -> level3
+      3 -> level4
+      4 -> level5
+      5 -> level6
+      6 -> level7
+      7 -> level8
+      8 -> level9
+      _ -> const Nothing
+
+data LevelIndents = LevelIndents
+  { marL :: EMU
+  , indent :: EMU
+  } deriving (Show, Eq)
+
+data MediaInfo = MediaInfo { mInfoFilePath :: FilePath
+                           , mInfoLocalId  :: Int
+                           , mInfoGlobalId :: Int
+                           , mInfoMimeType :: Maybe MimeType
+                           , mInfoExt      :: Maybe T.Text
+                           , mInfoCaption  :: Bool
+                           } deriving (Show, Eq)
+
+data WriterState = WriterState { stLinkIds :: M.Map Int (M.Map Int LinkTarget)
+                               -- (FP, Local ID, Global ID, Maybe Mime)
+                               , stMediaIds :: M.Map Int [MediaInfo]
+                               , stMediaGlobalIds :: M.Map FilePath Int
+                               , stFooterInfo :: Maybe FooterInfo
+                               } deriving (Show, Eq)
+
+instance Default WriterState where
+  def = WriterState { stLinkIds = mempty
+                    , stMediaIds = mempty
+                    , stMediaGlobalIds = mempty
+                    , stFooterInfo = Nothing
+                    }
+
+type P m = ReaderT WriterEnv (StateT WriterState m)
+
+runP :: Monad m => WriterEnv -> WriterState -> P m a -> m a
+runP env st p = evalStateT (runReaderT p env) st
+
+--------------------------------------------------------------------
+
+monospaceFont :: Monad m => P m T.Text
+monospaceFont = do
+  vars <- asks envContext
+  case lookupContext "monofont" vars of
+    Just s -> return s
+    Nothing -> return "Courier"
+
+fontSizeAttributes :: Monad m => RunProps -> P m [(Text, Text)]
+fontSizeAttributes RunProps { rPropForceSize = Just sz } =
+  return [("sz", tshow $ sz * 100)]
+fontSizeAttributes _ = return []
+
+copyFileToArchive :: PandocMonad m => Archive -> FilePath -> P m Archive
+copyFileToArchive arch fp = do
+  refArchive <- asks envRefArchive
+  distArchive <- asks envDistArchive
+  case findEntryByPath fp refArchive `mplus` findEntryByPath fp distArchive of
+    Nothing -> throwError $ PandocSomeError
+                          $ T.pack
+                          $ fp <> " missing in reference file"
+    Just e -> return $ addEntryToArchive e arch
+
+alwaysInheritedPatterns :: [Pattern]
+alwaysInheritedPatterns =
+  map compile [ "docProps/app.xml"
+              , "ppt/slideLayouts/slideLayout*.xml"
+              , "ppt/slideLayouts/_rels/slideLayout*.xml.rels"
+              , "ppt/slideMasters/slideMaster1.xml"
+              , "ppt/slideMasters/_rels/slideMaster1.xml.rels"
+              , "ppt/theme/theme*.xml"
+              , "ppt/theme/_rels/theme*.xml.rels"
+              , "ppt/presProps.xml"
+              , "ppt/tableStyles.xml"
+              , "ppt/media/image*"
+              , "ppt/fonts/*"
+              ]
+
+-- We only look for these under special conditions
+contingentInheritedPatterns :: Presentation -> [Pattern]
+contingentInheritedPatterns pres = [] <>
+  if presHasSpeakerNotes pres
+  then map compile [ "ppt/notesMasters/notesMaster*.xml"
+                   , "ppt/notesMasters/_rels/notesMaster*.xml.rels"
+                   ]
+  else []
+
+inheritedPatterns :: Presentation -> [Pattern]
+inheritedPatterns pres =
+  alwaysInheritedPatterns <> contingentInheritedPatterns pres
+
+patternToFilePaths :: PandocMonad m => Pattern -> P m [FilePath]
+patternToFilePaths pat = do
+  refArchive <- asks envRefArchive
+  distArchive <- asks envDistArchive
+
+  let archiveFiles = filesInArchive refArchive `union` filesInArchive distArchive
+  return $ filter (match pat) archiveFiles
+
+patternsToFilePaths :: PandocMonad m => [Pattern] -> P m [FilePath]
+patternsToFilePaths pats = concat <$> mapM patternToFilePaths pats
+
+-- Here are the files we'll require to make a Powerpoint document. If
+-- any of these are missing, we should error out of our build.
+requiredFiles :: [FilePath]
+requiredFiles = [ "docProps/app.xml"
+                , "ppt/presProps.xml"
+                , "ppt/slideLayouts/slideLayout1.xml"
+                , "ppt/slideLayouts/_rels/slideLayout1.xml.rels"
+                , "ppt/slideLayouts/slideLayout2.xml"
+                , "ppt/slideLayouts/_rels/slideLayout2.xml.rels"
+                , "ppt/slideLayouts/slideLayout3.xml"
+                , "ppt/slideLayouts/_rels/slideLayout3.xml.rels"
+                , "ppt/slideLayouts/slideLayout4.xml"
+                , "ppt/slideLayouts/_rels/slideLayout4.xml.rels"
+                , "ppt/slideMasters/slideMaster1.xml"
+                , "ppt/slideMasters/_rels/slideMaster1.xml.rels"
+                , "ppt/theme/theme1.xml"
+                , "ppt/tableStyles.xml"
+                ]
+
+presentationToArchiveP :: PandocMonad m => Presentation -> P m Archive
+presentationToArchiveP p@(Presentation docProps slides) = do
+  filePaths <- patternsToFilePaths $ inheritedPatterns p
+
+  -- make sure all required files are available:
+  let missingFiles = filter (`notElem` filePaths) requiredFiles
+  unless (null missingFiles)
+    (throwError $
+      PandocSomeError $
+      "The following required files are missing:\n" <>
+      T.unlines (map (T.pack . ("  " <>)) missingFiles)
+    )
+
+  newArch <- foldM copyFileToArchive emptyArchive filePaths
+
+  -- Add any layouts taken from the default archive,
+  -- overwriting any already added.
+  slideLayouts <- getSlideLayouts
+  let f layout =
+        if not (slInReferenceDoc layout)
+        then addEntryToArchive (slEntry layout)
+        else id
+  let newArch' = foldr f newArch slideLayouts
+
+  master <- getMaster
+  refArchive <- asks envRefArchive
+  distArchive <- asks envDistArchive
+  presentationElement <- parseXml refArchive distArchive "ppt/presentation.xml"
+  modify (\s ->
+    s {stFooterInfo =
+        getFooterInfo (dcDate docProps) slideLayouts master presentationElement
+      })
+
+  -- Update the master to make sure it includes any layouts we've just added
+  masterRels <- getMasterRels
+  let (updatedMasterElem, updatedMasterRelElem) = updateMasterElems slideLayouts master masterRels
+  updatedMasterEntry <- elemToEntry "ppt/slideMasters/slideMaster1.xml" updatedMasterElem
+  updatedMasterRelEntry <- elemToEntry "ppt/slideMasters/_rels/slideMaster1.xml.rels" updatedMasterRelElem
+
+  -- we make a modified ppt/viewProps.xml out of the presentation viewProps
+  viewPropsEntry <- makeViewPropsEntry
+  -- we make a docProps/core.xml entry out of the presentation docprops
+  docPropsEntry <- docPropsToEntry docProps
+  -- we make a docProps/custom.xml entry out of the custom properties
+  docCustomPropsEntry <- docCustomPropsToEntry docProps
+  -- we make this ourself in case there's something unexpected in the
+  -- one in the reference doc.
+  relsEntry <- topLevelRelsEntry
+  -- presentation entry and rels.
+  (presentationRIdUpdateData, presRelsEntry) <- presentationToRelsEntry p
+  presEntry <- presentationToPresEntry presentationRIdUpdateData p
+  slideEntries <- mapM slideToEntry slides
+  slideRelEntries <- mapM slideToSlideRelEntry slides
+  spkNotesEntries <- catMaybes <$> mapM slideToSpeakerNotesEntry slides
+  spkNotesRelEntries <- catMaybes <$> mapM slideToSpeakerNotesRelEntry slides
+  -- These have to come after everything, because they need the info
+  -- built up in the state.
+  mediaEntries <- makeMediaEntries
+  contentTypesEntry <- presentationToContentTypes p >>= contentTypesToEntry
+  -- fold everything into our inherited archive and return it.
+  return $ foldr addEntryToArchive newArch' $
+    slideEntries <>
+    slideRelEntries <>
+    spkNotesEntries <>
+    spkNotesRelEntries <>
+    mediaEntries <>
+    [updatedMasterEntry, updatedMasterRelEntry]  <>
+    [contentTypesEntry, docPropsEntry, docCustomPropsEntry, relsEntry,
+     presEntry, presRelsEntry, viewPropsEntry]
+
+updateMasterElems :: SlideLayouts -> Element -> Element -> (Element, Element)
+updateMasterElems layouts master masterRels = (updatedMaster, updatedMasterRels)
+  where
+    updatedMaster = master { elContent = updateSldLayoutIdLst <$> elContent master }
+    (updatedRelationshipIds, updatedMasterRels) = addLayoutRels masterRels
+
+    updateSldLayoutIdLst :: Content -> Content
+    updateSldLayoutIdLst (Elem e) = case elName e of
+      (QName "sldLayoutIdLst" _ _) -> let
+        mkChild relationshipId (lastId, children) = let
+          thisId = lastId + 1
+          newChild = Element
+            { elName = QName "sldLayoutId" Nothing (Just "p")
+            , elAttribs =
+              [ Attr (QName "id" Nothing Nothing) (T.pack (show thisId))
+              , Attr (QName "id" Nothing (Just "r")) relationshipId
+              ]
+            , elContent = []
+            , elLine = Nothing
+            }
+          in (thisId, Elem newChild : children)
+        newChildren = snd (foldr mkChild (maxIdNumber' e, []) updatedRelationshipIds)
+        in Elem e { elContent = elContent e <> newChildren }
+      _ -> Elem e
+    updateSldLayoutIdLst c = c
+
+    addLayoutRels ::
+      Element ->
+      ([Text], Element)
+    addLayoutRels e = let
+      layoutsToAdd = filter (\l -> not (slInReferenceDoc l) && isNew e l)
+                            (toList layouts)
+      newRelationships = snd (foldr mkRelationship (maxIdNumber e, []) layoutsToAdd)
+      newRelationshipIds =
+        mapMaybe (findElemAttr (QName "Id" Nothing Nothing)) newRelationships
+      mkRelationship layout (lastId, relationships) = let
+        thisId = lastId + 1
+        slideLayoutPath = "../slideLayouts/" <> T.pack (takeFileName (slPath layout))
+        newRelationship = Element
+          { elName = QName "Relationship" Nothing Nothing
+          , elAttribs =
+            [ Attr (QName "Id" Nothing Nothing) ("rId" <> T.pack (show thisId))
+            , Attr (QName "Type" Nothing Nothing) "http://schemas.openxmlformats.org/officeDocument/2006/relationships/slideLayout"
+            , Attr (QName "Target" Nothing Nothing) slideLayoutPath
+            ]
+          , elContent = []
+          , elLine = Nothing
+          }
+        in (thisId, Elem newRelationship : relationships)
+      in (newRelationshipIds, e {elContent = elContent e <> newRelationships})
+
+    -- Whether the layout needs to be added to the Relationships element.
+    isNew :: Element -> SlideLayout -> Bool
+    isNew relationships SlideLayout{..} = let
+      toDetails = fmap (takeFileName . T.unpack)
+        . findElemAttr (QName "Target" Nothing Nothing)
+      in takeFileName slPath `notElem` mapMaybe toDetails (elContent relationships)
+
+    findElemAttr :: QName -> Content -> Maybe Text
+    findElemAttr attr (Elem e) = findAttr attr e
+    findElemAttr _ _ = Nothing
+
+    maxIdNumber :: Element -> Integer
+    maxIdNumber relationships = maximum (0 : idNumbers)
+      where
+        idNumbers = mapMaybe (readTextAsInteger . T.drop 3) idAttributes
+        idAttributes = mapMaybe getIdAttribute (elContent relationships)
+        getIdAttribute (Elem e) = findAttr (QName "Id" Nothing Nothing) e
+        getIdAttribute _ = Nothing
+
+    maxIdNumber' :: Element -> Integer
+    maxIdNumber' sldLayouts = maximum (0 : idNumbers)
+      where
+        idNumbers = mapMaybe readTextAsInteger idAttributes
+        idAttributes = mapMaybe getIdAttribute (elContent sldLayouts)
+        getIdAttribute (Elem e) = findAttr (QName "id" Nothing Nothing) e
+        getIdAttribute _ = Nothing
+
+data FooterInfo = FooterInfo
+  { fiDate :: SlideLayoutsOf (Maybe Element)
+  , fiFooter :: SlideLayoutsOf (Maybe Element)
+  , fiSlideNumber :: SlideLayoutsOf (Maybe Element)
+  , fiShowOnFirstSlide :: Bool
+  } deriving (Show, Eq)
+
+getFooterInfo :: Maybe Text -> SlideLayouts -> Element -> Element -> Maybe FooterInfo
+getFooterInfo date layouts master presentation = do
+  let ns = elemToNameSpaces master
+  hf <- findChild (elemName ns "p" "hf") master
+  let fiDate = let
+        f layoutDate =
+          case date of
+            Nothing -> layoutDate
+            Just d ->
+              if dateIsAutomatic (elemToNameSpaces layoutDate) layoutDate
+              then layoutDate
+              else replaceDate d layoutDate
+        in fmap f . getShape "dt" hf . slElement <$> layouts
+      fiFooter = getShape "ftr" hf . slElement <$> layouts
+      fiSlideNumber = getShape "sldNum" hf . slElement <$> layouts
+      fiShowOnFirstSlide =
+        fromMaybe True
+        (getBooleanAttribute "showSpecialPlsOnTitleSld" presentation)
+  pure FooterInfo{..}
+    where
+      getShape t hf layout =
+        if fromMaybe True (getBooleanAttribute t hf)
+        then do
+          let ns = elemToNameSpaces layout
+          cSld <- findChild (elemName ns "p" "cSld") layout
+          spTree <- findChild (elemName ns "p" "spTree") cSld
+          let containsPlaceholder sp = fromMaybe False $ do
+                nvSpPr <- findChild (elemName ns "p" "nvSpPr") sp
+                nvPr <- findChild (elemName ns "p" "nvPr") nvSpPr
+                ph <- findChild (elemName ns "p" "ph") nvPr
+                placeholderType <- findAttr (QName "type" Nothing Nothing) ph
+                pure (placeholderType == t)
+          listToMaybe (filterChildren containsPlaceholder spTree)
+        else Nothing
+
+      dateIsAutomatic :: NameSpaces -> Element -> Bool
+      dateIsAutomatic ns shape = isJust $ do
+        txBody <- findChild (elemName ns "p" "txBody") shape
+        p <- findChild (elemName ns "a" "p") txBody
+        findChild (elemName ns "a" "fld") p
+
+      replaceDate :: Text -> Element -> Element
+      replaceDate newDate e =
+        e { elContent =
+            case (elName e) of
+              QName "t" _ (Just "a") ->
+                [ Text (CData { cdVerbatim = CDataText
+                              , cdData = newDate
+                              , cdLine = Nothing
+                              })
+                ]
+              _ -> ifElem (replaceDate newDate) <$> elContent e
+           }
+
+      ifElem :: (Element -> Element) -> (Content -> Content)
+      ifElem f (Elem e) = Elem (f e)
+      ifElem _ c = c
+
+      getBooleanAttribute t e =
+        (`elem` ["1", "true"]) <$>
+          (findAttr (QName t Nothing Nothing) e)
+
+footerElements ::
+  PandocMonad m =>
+  (forall a. SlideLayoutsOf a -> a) ->
+  P m [Content]
+footerElements layout = do
+  footerInfo <- gets stFooterInfo
+  pure
+    $ Elem <$>
+      (toList (footerInfo >>= layout . fiDate)
+       <> toList (footerInfo >>= layout . fiFooter)
+       <> toList (footerInfo >>= layout . fiSlideNumber))
+
+makeSlideIdMap :: Presentation -> M.Map SlideId Int
+makeSlideIdMap (Presentation _ slides) =
+  M.fromList $ map slideId slides `zip` [1..]
+
+makeSpeakerNotesMap :: Presentation -> M.Map Int Int
+makeSpeakerNotesMap (Presentation _ slides) =
+  M.fromList $
+    mapMaybe f (slides `zip` [1..]) `zip` [1..]
+  where f (Slide _ _ notes _, n) = if notes == mempty
+                                   then Nothing
+                                   else Just n
+
+presentationToArchive :: PandocMonad m
+                      => WriterOptions -> Meta -> Presentation -> m Archive
+presentationToArchive opts meta pres = do
+  distArchive <- toArchive . BL.fromStrict <$>
+                        readDefaultDataFile "reference.pptx"
+  refArchive <- case writerReferenceDoc opts of
+                     Just f  -> toArchive . BL.fromStrict . fst
+                                  <$> P.fetchItem (T.pack f)
+                     Nothing -> toArchive . BL.fromStrict <$>
+                        readDataFile "reference.pptx"
+
+  let (referenceLayouts, defaultReferenceLayouts) =
+        (getLayoutsFromArchive refArchive, getLayoutsFromArchive distArchive)
+  let layoutTitles = SlideLayouts { metadata = "Title Slide" :: Text
+                                  , title = "Section Header"
+                                  , content = "Title and Content"
+                                  , twoColumn = "Two Content"
+                                  , comparison = "Comparison"
+                                  , contentWithCaption = "Content with Caption"
+                                  , blank = "Blank"
+                                  }
+  layouts <- for layoutTitles $ \layoutTitle -> do
+        let layout = M.lookup (CI.mk layoutTitle) referenceLayouts
+        let defaultLayout = M.lookup (CI.mk layoutTitle) defaultReferenceLayouts
+        case (layout, defaultLayout) of
+          (Nothing, Nothing) ->
+            throwError (PandocSomeError ("Couldn't find layout named \""
+                                         <> layoutTitle <> "\" in the provided "
+                                         <> "reference doc or in the default "
+                                         <> "reference doc included with pandoc."))
+          (Nothing, Just ((element, path, entry) :| _)) -> do
+            P.report (PowerpointTemplateWarning
+                                     ("Couldn't find layout named \""
+                                      <> layoutTitle <> "\" in provided "
+                                      <> "reference doc. Falling back to "
+                                      <> "the default included with pandoc."))
+            pure SlideLayout { slElement = element
+                             , slPath = path
+                             , slEntry = entry
+                             , slInReferenceDoc = False
+                             }
+          (Just ((element, path, entry) :| _), _ ) ->
+            pure SlideLayout { slElement = element
+                             , slPath = path
+                             , slEntry = entry
+                             , slInReferenceDoc = True
+                             }
+
+  master <- getMaster' refArchive distArchive
+
+  let otherStyleIndents = do
+        let ns = elemToNameSpaces master
+        txStyles <- findChild (elemName ns "p" "txStyles") master
+        otherStyle <- findChild (elemName ns "p" "otherStyle") txStyles
+        let makeLevelIndents name = do
+              e <- findChild (elemName ns "a" name) otherStyle
+              pure LevelIndents
+                { indent = fromMaybe (-342900)
+                    (findAttr (QName "indent" Nothing Nothing) e
+                    >>= readTextAsInteger)
+                , marL = fromMaybe 347663
+                    (findAttr (QName "marL" Nothing Nothing) e
+                     >>= readTextAsInteger)
+                }
+        pure Indents
+          { level1 = makeLevelIndents "lvl1pPr"
+          , level2 = makeLevelIndents "lvl2pPr"
+          , level3 = makeLevelIndents "lvl3pPr"
+          , level4 = makeLevelIndents "lvl4pPr"
+          , level5 = makeLevelIndents "lvl5pPr"
+          , level6 = makeLevelIndents "lvl6pPr"
+          , level7 = makeLevelIndents "lvl7pPr"
+          , level8 = makeLevelIndents "lvl8pPr"
+          , level9 = makeLevelIndents "lvl9pPr"
+          }
+
+  utctime <- P.getTimestamp
+
+  presSize <- case getPresentationSize refArchive distArchive of
+                Just sz -> return sz
+                Nothing -> throwError $
+                           PandocSomeError
+                           "Could not determine presentation size"
+
+  -- note, we need writerTemplate to be Just _ or metaToContext does
+  -- nothing
+  context <- metaToContext opts{ writerTemplate =
+                                  writerTemplate opts <|> Just mempty }
+                (return . literal . stringify)
+                (return . literal . stringify) meta
+
+  let env = def { envRefArchive = refArchive
+                , envDistArchive = distArchive
+                , envUTCTime = utctime
+                , envOpts = opts
+                , envContext = context
+                , envPresentationSize = presSize
+                , envSlideIdMap = makeSlideIdMap pres
+                , envSpeakerNotesIdMap = makeSpeakerNotesMap pres
+                , envSlideLayouts = Just layouts
+                , envOtherStyleIndents = otherStyleIndents
+                }
+
+  let st = def { stMediaGlobalIds = initialGlobalIds refArchive distArchive
+               }
+
+  runP env st $ presentationToArchiveP pres
+
+-- | Get all slide layouts from an archive, as a map where the layout's name
+-- gives the map key.
+--
+-- For each layout, the map contains its XML representation, its path within
+-- the archive, and the archive entry.
+getLayoutsFromArchive :: Archive -> M.Map (CI Text) (NonEmpty (Element, FilePath, Entry))
+getLayoutsFromArchive archive =
+  M.fromListWith (<>) ((\t@(e, _, _) -> (CI.mk (name e), pure t)) <$> layouts)
+  where
+    layouts :: [(Element, FilePath, Entry)]
+    layouts = mapMaybe findElementByPath paths
+    parseXml' entry = case parseXMLElement (UTF8.toTextLazy (fromEntry entry)) of
+            Left _ -> Nothing
+            Right element -> Just element
+    findElementByPath :: FilePath -> Maybe (Element, FilePath, Entry)
+    findElementByPath path = do
+      entry <- findEntryByPath path archive
+      element <- parseXml' entry
+      pure (element, path, entry)
+    paths = filter (match (compile "ppt/slideLayouts/slideLayout*.xml")) (filesInArchive archive)
+    name element = fromMaybe "Untitled layout" $ do
+            let ns = elemToNameSpaces element
+            cSld <- findChild (elemName ns "p" "cSld") element
+            findAttr (QName "name" Nothing Nothing) cSld
+
+--------------------------------------------------
+
+-- Check to see if the presentation has speaker notes. This will
+-- influence whether we import the notesMaster template.
+presHasSpeakerNotes :: Presentation -> Bool
+presHasSpeakerNotes (Presentation _ slides) =
+  not $ all ((mempty ==) . slideSpeakerNotes) slides
+
+curSlideHasSpeakerNotes :: PandocMonad m => P m Bool
+curSlideHasSpeakerNotes =
+  M.member <$> asks envCurSlideId <*> asks envSpeakerNotesIdMap
+
+--------------------------------------------------
+
+getLayout :: PandocMonad m => Layout -> P m Element
+getLayout layout = getElement <$> getSlideLayouts
+  where
+    getElement =
+      slElement . case layout of
+        MetadataSlide{}           -> metadata
+        TitleSlide{}              -> title
+        ContentSlide{}            -> content
+        TwoColumnSlide{}          -> twoColumn
+        ComparisonSlide{}         -> comparison
+        ContentWithCaptionSlide{} -> contentWithCaption
+        BlankSlide{}              -> blank
+
+shapeHasId :: NameSpaces -> T.Text -> Element -> Bool
+shapeHasId ns ident element = getShapeId ns element == Just ident
+
+getShapeId :: NameSpaces -> Element -> Maybe Text
+getShapeId ns element = do
+  nvSpPr <- findChild (elemName ns "p" "nvSpPr") element
+  cNvPr <- findChild (elemName ns "p" "cNvPr") nvSpPr
+  findAttr (QName "id" Nothing Nothing) cNvPr
+
+type ShapeId = Integer
+
+getContentShape :: PandocMonad m => NameSpaces -> Element -> P m (Maybe ShapeId, Element)
+getContentShape ns spTreeElem
+  | isElem ns "p" "spTree" spTreeElem = do
+      ph@Placeholder{index, placeholderType} <- asks envPlaceholder
+      case drop index (getShapesByPlaceHolderType ns spTreeElem placeholderType) of
+        sp : _ -> let
+          shapeId = getShapeId ns sp >>= readTextAsInteger
+          in return (shapeId, sp)
+        [] -> throwError $ PandocSomeError $ missingPlaceholderMessage ph
+getContentShape _ _ = throwError $ PandocSomeError
+                      "Attempted to find content on non shapeTree"
+
+missingPlaceholderMessage :: Placeholder -> Text
+missingPlaceholderMessage Placeholder{..} =
+  "Could not find a " <> ordinal
+  <> " placeholder of type " <> placeholderText
+  where
+    ordinal = T.pack (show index) <>
+      case (index `mod` 100, index `mod` 10) of
+        (11, _) -> "th"
+        (12, _) -> "th"
+        (13, _) -> "th"
+        (_,  1) -> "st"
+        (_,  2) -> "nd"
+        (_,  3) -> "rd"
+        _       -> "th"
+    placeholderText = case placeholderType of
+      ObjType -> "obj (or nothing)"
+      PHType t -> t
+
+getShapeDimensions :: NameSpaces
+                   -> Element
+                   -> Maybe ((Integer, Integer), (Integer, Integer))
+getShapeDimensions ns element
+  | isElem ns "p" "sp" element = do
+      spPr <- findChild (elemName ns "p" "spPr") element
+      xfrm <- findChild (elemName ns "a" "xfrm") spPr
+      off <- findChild (elemName ns "a" "off") xfrm
+      xS <- findAttr (QName "x" Nothing Nothing) off
+      yS <- findAttr (QName "y" Nothing Nothing) off
+      ext <- findChild (elemName ns "a" "ext") xfrm
+      cxS <- findAttr (QName "cx" Nothing Nothing) ext
+      cyS <- findAttr (QName "cy" Nothing Nothing) ext
+      x <- readTextAsInteger xS
+      y <- readTextAsInteger yS
+      cx <- readTextAsInteger cxS
+      cy <- readTextAsInteger cyS
+      return ((x `div` 12700, y `div` 12700),
+              (cx `div` 12700, cy `div` 12700))
+  | otherwise = Nothing
+
+
+getMasterShapeDimensionsById :: T.Text
+                             -> Element
+                             -> Maybe ((Integer, Integer), (Integer, Integer))
+getMasterShapeDimensionsById ident master = do
+  let ns = elemToNameSpaces master
+  cSld <- findChild (elemName ns "p" "cSld") master
+  spTree <- findChild (elemName ns "p" "spTree") cSld
+  sp <- filterChild (\e -> isElem ns "p" "sp" e && shapeHasId ns ident e) spTree
+  getShapeDimensions ns sp
+
+getContentShapeSize :: PandocMonad m
+                    => NameSpaces
+                    -> Element
+                    -> Element
+                    -> P m ((Integer, Integer), (Integer, Integer))
+getContentShapeSize ns layout master
+  | isElem ns "p" "sldLayout" layout
+  , Just cSld <- findChild (elemName ns "p" "cSld") layout
+  , Just spTree <- findChild (elemName ns "p" "spTree") cSld = do
+      (_, sp)  <- getContentShape ns spTree
+      case getShapeDimensions ns sp of
+        Just sz -> return sz
+        Nothing -> do let mbSz =
+                            findChild (elemName ns "p" "nvSpPr") sp >>=
+                            findChild (elemName ns "p" "cNvPr") >>=
+                            findAttr (QName "id" Nothing Nothing) >>=
+                            flip getMasterShapeDimensionsById master
+                      case mbSz of
+                        Just sz' -> return sz'
+                        Nothing -> throwError $ PandocSomeError
+                                   "Couldn't find necessary content shape size"
+getContentShapeSize _ _ _ = throwError $ PandocSomeError
+                            "Attempted to find content shape size in non-layout"
+
+buildSpTree :: NameSpaces -> Element -> [Content] -> Element
+buildSpTree ns spTreeElem newShapes =
+  emptySpTreeElem { elContent = newContent }
+  where newContent = elContent emptySpTreeElem <> newShapes
+        emptySpTreeElem = spTreeElem { elContent = filter fn (elContent spTreeElem) }
+        fn :: Content -> Bool
+        fn (Elem e) = isElem ns "p" "nvGrpSpPr" e ||
+                      isElem ns "p" "grpSpPr" e
+        fn _        = True
+
+replaceNamedChildren :: NameSpaces
+                     -> Text
+                     -> Text
+                     -> [Element]
+                     -> Element
+                     -> Element
+replaceNamedChildren ns prefix name newKids element =
+  element { elContent = concat $ fun True $ elContent element }
+  where
+    fun :: Bool -> [Content] -> [[Content]]
+    fun _ [] = []
+    fun switch (Elem e : conts) | isElem ns prefix name e =
+                                      if switch
+                                      then map Elem newKids : fun False conts
+                                      else fun False conts
+    fun switch (cont : conts) = [cont] : fun switch conts
+
+----------------------------------------------------------------
+
+registerLink :: PandocMonad m => LinkTarget -> P m Int
+registerLink link = do
+  curSlideId <- asks envCurSlideId
+  linkReg <- gets stLinkIds
+  mediaReg <- gets stMediaIds
+  hasSpeakerNotes <- curSlideHasSpeakerNotes
+  let maxLinkId = case M.lookup curSlideId linkReg >>= nonEmpty . M.keys of
+        Just xs -> maximum xs
+        Nothing
+          | hasSpeakerNotes -> 2
+          | otherwise       -> 1
+      maxMediaId = case M.lookup curSlideId mediaReg >>= nonEmpty of
+        Just mInfos -> maximum $ fmap mInfoLocalId mInfos
+        Nothing
+          | hasSpeakerNotes -> 2
+          | otherwise       -> 1
+      maxId = max maxLinkId maxMediaId
+      slideLinks = case M.lookup curSlideId linkReg of
+        Just mp -> M.insert (maxId + 1) link mp
+        Nothing -> M.singleton (maxId + 1) link
+  modify $ \st -> st{ stLinkIds = M.insert curSlideId slideLinks linkReg}
+  return $ maxId + 1
+
+registerMedia :: PandocMonad m => FilePath -> [ParaElem] -> P m MediaInfo
+registerMedia fp caption = do
+  curSlideId <- asks envCurSlideId
+  linkReg <- gets stLinkIds
+  mediaReg <- gets stMediaIds
+  globalIds <- gets stMediaGlobalIds
+  hasSpeakerNotes <- curSlideHasSpeakerNotes
+  let maxLinkId = case M.lookup curSlideId linkReg >>= nonEmpty . M.keys of
+          Just ks -> maximum ks
+          Nothing
+            | hasSpeakerNotes -> 2
+            | otherwise       -> 1
+      maxMediaId = case M.lookup curSlideId mediaReg >>= nonEmpty of
+          Just mInfos -> maximum $ fmap mInfoLocalId mInfos
+          Nothing
+            | hasSpeakerNotes -> 2
+            | otherwise       -> 1
+      maxLocalId = max maxLinkId maxMediaId
+
+      maxGlobalId = maybe 0 maximum $ nonEmpty $ M.elems globalIds
+
+  (imgBytes, mbMt) <- P.fetchItem $ T.pack fp
+  let imgExt = (mbMt >>= extensionFromMimeType >>= (\x -> return $ "." <> x))
+               <|>
+               case imageType imgBytes of
+                 Just Png  -> Just ".png"
+                 Just Jpeg -> Just ".jpeg"
+                 Just Gif  -> Just ".gif"
+                 Just Pdf  -> Just ".pdf"
+                 Just Eps  -> Just ".eps"
+                 Just Svg  -> Just ".svg"
+                 Just Emf  -> Just ".emf"
+                 Just Tiff -> Just ".tiff"
+                 Just Webp -> Just ".webp"
+                 Just Avif -> Just ".avif"
+                 Nothing   -> Nothing
+
+  let newGlobalId = fromMaybe (maxGlobalId + 1) (M.lookup fp globalIds)
+
+  let newGlobalIds = M.insert fp newGlobalId globalIds
+
+  let mediaInfo = MediaInfo { mInfoFilePath = fp
+                            , mInfoLocalId = maxLocalId + 1
+                            , mInfoGlobalId = newGlobalId
+                            , mInfoMimeType =
+                                case mbMt of
+                                  -- see #9113
+                                  Just t | ";base64" `T.isSuffixOf` t
+                                     -> T.stripSuffix ";base64" t
+                                  x -> x
+                            , mInfoExt = imgExt
+                            , mInfoCaption = (not . null) caption
+                            }
+
+  let slideMediaInfos = case M.lookup curSlideId mediaReg of
+        Just minfos -> mediaInfo : minfos
+        Nothing     -> [mediaInfo]
+
+
+  modify $ \st -> st{ stMediaIds = M.insert curSlideId slideMediaInfos mediaReg
+                    , stMediaGlobalIds = newGlobalIds
+                    }
+  return mediaInfo
+
+makeMediaEntry :: PandocMonad m => MediaInfo -> P m Entry
+makeMediaEntry mInfo = do
+  epochtime <- floor . utcTimeToPOSIXSeconds <$> asks envUTCTime
+  (imgBytes, _) <- P.fetchItem (T.pack $ mInfoFilePath mInfo)
+  let ext = fromMaybe "" (mInfoExt mInfo)
+  let fp = "ppt/media/image" <>
+          show (mInfoGlobalId mInfo) <> T.unpack ext
+  return $ toEntry fp epochtime $ BL.fromStrict imgBytes
+
+makeMediaEntries :: PandocMonad m => P m [Entry]
+makeMediaEntries = do
+  mediaInfos <- gets stMediaIds
+  let allInfos = mconcat $ M.elems mediaInfos
+  mapM makeMediaEntry allInfos
+
+-- -- | Scales the image to fit the page
+-- -- sizes are passed in emu
+-- fitToPage' :: (Double, Double)  -- image size in emu
+--            -> Integer           -- pageWidth
+--            -> Integer           -- pageHeight
+--            -> (Integer, Integer) -- imagesize
+-- fitToPage' (x, y) pageWidth pageHeight
+--   -- Fixes width to the page width and scales the height
+--   | x <= fromIntegral pageWidth && y <= fromIntegral pageHeight =
+--       (floor x, floor y)
+--   | x / fromIntegral pageWidth > y / fromIntegral pageWidth =
+--       (pageWidth, floor $ ((fromIntegral pageWidth) / x) * y)
+--   | otherwise =
+--       (floor $ ((fromIntegral pageHeight) / y) * x, pageHeight)
+
+-- positionImage :: (Double, Double) -> Integer -> Integer -> (Integer, Integer)
+-- positionImage (x, y) pageWidth pageHeight =
+--   let (x', y') = fitToPage' (x, y) pageWidth pageHeight
+--   in
+--     ((pageWidth - x') `div` 2, (pageHeight - y') `div`  2)
+
+getMaster :: PandocMonad m => P m Element
+getMaster = do
+  refArchive <- asks envRefArchive
+  distArchive <- asks envDistArchive
+  getMaster' refArchive distArchive
+
+getMaster' :: PandocMonad m => Archive -> Archive -> m Element
+getMaster' refArchive distArchive =
+  parseXml refArchive distArchive "ppt/slideMasters/slideMaster1.xml"
+
+getMasterRels :: PandocMonad m => P m Element
+getMasterRels = do
+  refArchive <- asks envRefArchive
+  distArchive <- asks envDistArchive
+  parseXml refArchive distArchive "ppt/slideMasters/_rels/slideMaster1.xml.rels"
+
+-- We want to get the header dimensions, so we can make sure that the
+-- image goes underneath it. We only use this in a content slide if it
+-- has a header.
+
+-- getHeaderSize :: PandocMonad m => P m ((Integer, Integer), (Integer, Integer))
+-- getHeaderSize = do
+--   master <- getMaster
+--   let ns = elemToNameSpaces master
+--       sps = [master] >>=
+--             findChildren (elemName ns "p" "cSld") >>=
+--             findChildren (elemName ns "p" "spTree") >>=
+--             findChildren (elemName ns "p" "sp")
+--       mbXfrm =
+--         listToMaybe (filter (shapeHasName ns "Title Placeholder 1") sps) >>=
+--         findChild (elemName ns "p" "spPr") >>=
+--         findChild (elemName ns "a" "xfrm")
+--       xoff = mbXfrm >>=
+--              findChild (elemName ns "a" "off") >>=
+--              findAttr (QName "x" Nothing Nothing) >>=
+--              (listToMaybe . (\s -> reads s :: [(Integer, String)]))
+--       yoff = mbXfrm >>=
+--              findChild (elemName ns "a" "off") >>=
+--              findAttr (QName "y" Nothing Nothing) >>=
+--              (listToMaybe . (\s -> reads s :: [(Integer, String)]))
+--       xext = mbXfrm >>=
+--              findChild (elemName ns "a" "ext") >>=
+--              findAttr (QName "cx" Nothing Nothing) >>=
+--              (listToMaybe . (\s -> reads s :: [(Integer, String)]))
+--       yext = mbXfrm >>=
+--              findChild (elemName ns "a" "ext") >>=
+--              findAttr (QName "cy" Nothing Nothing) >>=
+--              (listToMaybe . (\s -> reads s :: [(Integer, String)]))
+--       off = case xoff of
+--               Just (xoff', _) | Just (yoff',_) <- yoff -> (xoff', yoff')
+--               _                               -> (1043490, 1027664)
+--       ext = case xext of
+--               Just (xext', _) | Just (yext',_) <- yext -> (xext', yext')
+--               _                               -> (7024744, 1143000)
+--   return $ (off, ext)
+
+-- Hard-coded for now
+-- captionPosition :: ((Integer, Integer), (Integer, Integer))
+-- captionPosition = ((457200, 6061972), (8229600, 527087))
+
+captionHeight :: Integer
+captionHeight = 40
+
+createCaption :: PandocMonad m
+              => ((Integer, Integer), (Integer, Integer))
+              -> [ParaElem]
+              -> P m (ShapeId, Element)
+createCaption contentShapeDimensions paraElements = do
+  let para = Paragraph def{pPropAlign = Just AlgnCenter} paraElements
+  elements <- mapM paragraphToElement [para]
+  let ((x, y), (cx, cy)) = contentShapeDimensions
+  let txBody = mknode "p:txBody" [] $
+               [mknode "a:bodyPr" [] (), mknode "a:lstStyle" [] ()] <> elements
+  return
+    ( 1
+    ,  surroundWithMathAlternate $
+       mknode "p:sp" [] [ mknode "p:nvSpPr" []
+                          [ mknode "p:cNvPr" [("id","1"), ("name","TextBox 3")] ()
+                          , mknode "p:cNvSpPr" [("txBox", "1")] ()
+                          , mknode "p:nvPr" []
+                            [mknode "p:ph" [("idx", "1")] ()]
+                          ]
+                        , mknode "p:spPr" []
+                          [ mknode "a:xfrm" []
+                            [ mknode "a:off" [("x", tshow $ 12700 * x),
+                                              ("y", tshow $ 12700 * (y + cy - captionHeight))] ()
+                            , mknode "a:ext" [("cx", tshow $ 12700 * cx),
+                                              ("cy", tshow $ 12700 * captionHeight)] ()
+                            ]
+                          , mknode "a:prstGeom" [("prst", "rect")]
+                            [ mknode "a:avLst" [] ()
+                            ]
+                          , mknode "a:noFill" [] ()
+                          ]
+                        , txBody
+                        ]
+    )
+
+makePicElements :: PandocMonad m
+                => Element
+                -> PicProps
+                -> MediaInfo
+                -> Text
+                -> [ParaElem]
+                -> P m [(ShapeId, Element)]
+makePicElements layout picProps mInfo titleText alt = do
+  opts <- asks envOpts
+  (pageWidth, pageHeight) <- asks envPresentationSize
+  -- hasHeader <- asks envSlideHasHeader
+  let hasCaption = mInfoCaption mInfo
+  (imgBytes, _) <- P.fetchItem (T.pack $ mInfoFilePath mInfo)
+  let (pxX, pxY) = case imageSize opts imgBytes of
+        Right sz -> sizeInPixels sz
+        Left _   -> sizeInPixels def
+  master <- getMaster
+  let ns = elemToNameSpaces layout
+  ((x, y), (cx, cytmp)) <- getContentShapeSize ns layout master
+                           `catchError`
+                           (\_ -> return ((0, 0), (pageWidth, pageHeight)))
+
+  let cy = if hasCaption then cytmp - captionHeight else cytmp
+
+  let imgRatio = fromIntegral pxX / fromIntegral pxY :: Double
+      boxRatio = fromIntegral cx / fromIntegral cy :: Double
+      (dimX, dimY) = if imgRatio > boxRatio
+                     then (fromIntegral cx, fromIntegral cx / imgRatio)
+                     else (fromIntegral cy * imgRatio, fromIntegral cy)
+
+      (dimX', dimY') = (round dimX * 12700, round dimY * 12700) :: (Integer, Integer)
+      (xoff, yoff) = (fromIntegral x + (fromIntegral cx - dimX) / 2,
+                      fromIntegral y + (fromIntegral cy - dimY) / 2)
+      (xoff', yoff') = (round xoff * 12700, round yoff * 12700) :: (Integer, Integer)
+
+  let cNvPicPr = mknode "p:cNvPicPr" [] $
+                 mknode "a:picLocks" [("noGrp","1")
+                                     ,("noChangeAspect","1")] ()
+  -- cNvPr will contain the link information so we do that separately,
+  -- and register the link if necessary.
+  let description = (if T.null titleText
+                      then ""
+                      else titleText <> "\n\n")
+                      <> T.pack (mInfoFilePath mInfo)
+  let cNvPrAttr = [("descr", description),
+                   ("id","0"),
+                   ("name","Picture 1")]
+  cNvPr <- case picPropLink picProps of
+    Just link -> do idNum <- registerLink link
+                    return $ mknode "p:cNvPr" cNvPrAttr $
+                      mknode "a:hlinkClick" [("r:id", "rId" <> tshow idNum)] ()
+    Nothing   -> return $ mknode "p:cNvPr" cNvPrAttr ()
+  let nvPicPr  = mknode "p:nvPicPr" []
+                 [ cNvPr
+                 , cNvPicPr
+                 , mknode "p:nvPr" [] ()]
+  let blipFill = mknode "p:blipFill" []
+                 [ mknode "a:blip" [("r:embed", "rId" <>
+                     tshow (mInfoLocalId mInfo))] ()
+                 , mknode "a:stretch" [] $
+                   mknode "a:fillRect" [] () ]
+  let xfrm =    mknode "a:xfrm" []
+                [ mknode "a:off" [("x", tshow xoff'), ("y", tshow yoff')] ()
+                , mknode "a:ext" [("cx", tshow dimX')
+                                 ,("cy", tshow dimY')] () ]
+  let prstGeom = mknode "a:prstGeom" [("prst","rect")] $
+                 mknode "a:avLst" [] ()
+  let ln =      mknode "a:ln" [("w","9525")]
+                [ mknode "a:noFill" [] ()
+                , mknode "a:headEnd" [] ()
+                , mknode "a:tailEnd" [] () ]
+  let spPr =    mknode "p:spPr" [("bwMode","auto")]
+                [xfrm, prstGeom, mknode "a:noFill" [] (), ln]
+
+  let picShape = ( 0
+                 , mknode "p:pic" []
+                   [ nvPicPr
+                   , blipFill
+                   , spPr ]
+                 )
+
+  -- And now, maybe create the caption:
+  if hasCaption
+    then do cap <- createCaption ((x, y), (cx, cytmp)) alt
+            return [picShape, cap]
+    else return [picShape]
+
+consolidateRuns :: [ParaElem] -> [ParaElem]
+consolidateRuns [] = []
+consolidateRuns (Run pr1 s1 : Run pr2 s2 : xs)
+  | pr1 == pr2 = consolidateRuns (Run pr1 (s1 <> s2) : xs)
+consolidateRuns (x:xs) = x : consolidateRuns xs
+
+
+paraElemToElements :: PandocMonad m => ParaElem -> P m [Content]
+paraElemToElements Break = return [Elem $ mknode "a:br" [] ()]
+paraElemToElements (Run rpr s) = do
+  sizeAttrs <- fontSizeAttributes rpr
+  let attrs = sizeAttrs <>
+        (
+        [("b", "1") | rPropBold rpr]) <>
+        (
+        [("i", "1") | rPropItalics rpr]) <>
+        (
+        [("u", "sng") | rPropUnderline rpr]) <>
+        (case rStrikethrough rpr of
+            Just NoStrike     -> [("strike", "noStrike")]
+            Just SingleStrike -> [("strike", "sngStrike")]
+            Just DoubleStrike -> [("strike", "dblStrike")]
+            Nothing -> []) <>
+        (case rBaseline rpr of
+            Just n -> [("baseline", tshow n)]
+            Nothing -> []) <>
+        (case rCap rpr of
+            Just NoCapitals -> [("cap", "none")]
+            Just SmallCapitals -> [("cap", "small")]
+            Just AllCapitals -> [("cap", "all")]
+            Nothing -> []) <>
+        []
+  linkProps <- case rLink rpr of
+                 Just link -> do
+                   idNum <- registerLink link
+                   -- first we have to make sure that if it's an
+                   -- anchor, it's in the anchor map. If not, there's
+                   -- no link.
+                   return $ case link of
+                     InternalTarget _ ->
+                       let linkAttrs =
+                             [ ("r:id", "rId" <> tshow idNum)
+                             , ("action", "ppaction://hlinksldjump")
+                             ]
+                       in [mknode "a:hlinkClick" linkAttrs ()]
+                     -- external
+                     ExternalTarget _ ->
+                       let linkAttrs =
+                             [ ("r:id", "rId" <> tshow idNum)
+                             ]
+                       in [mknode "a:hlinkClick" linkAttrs ()]
+                 Nothing -> return []
+  let colorContents = case rSolidFill rpr of
+                        Just color ->
+                          case fromColor color of
+                            '#':hx ->
+                              [mknode "a:solidFill" []
+                                [mknode "a:srgbClr"
+                                  [("val", T.toUpper $ T.pack hx)] ()]]
+                            _ -> []
+                        Nothing -> []
+  codeFont <- monospaceFont
+  let codeContents =
+        [mknode "a:latin" [("typeface", codeFont)] () | rPropCode rpr]
+  let propContents = linkProps <> colorContents <> codeContents
+  return [Elem $ mknode "a:r" [] [ mknode "a:rPr" attrs propContents
+                                 , mknode "a:t" [] s
+                                 ]]
+paraElemToElements (MathElem mathType texStr) = do
+  isInSpkrNotes <- asks envInSpeakerNotes
+  if isInSpkrNotes
+    then paraElemToElements $ Run def $ unTeXString texStr
+    else do res <- convertMath writeOMML mathType (unTeXString texStr)
+            case fromXLElement <$> res of
+              Right r -> return [Elem $ mknode "a14:m" [] $ addMathInfo r]
+              Left (Str s) -> paraElemToElements (Run def s)
+              Left _       -> throwError $ PandocShouldNeverHappenError "non-string math fallback"
+paraElemToElements (RawOOXMLParaElem str) = return
+  [Text (CData CDataRaw str Nothing)]
+
+
+-- This is a bit of a kludge -- really requires adding an option to
+-- TeXMath, but since that's a different package, we'll do this one
+-- step at a time.
+addMathInfo :: Element -> Element
+addMathInfo element =
+  let mathspace =
+        Attr { attrKey = QName "m" Nothing (Just "xmlns")
+             , attrVal = "http://schemas.openxmlformats.org/officeDocument/2006/math"
+             }
+  in add_attr mathspace element
+
+-- We look through the element to see if it contains an a14:m
+-- element. If so, we surround it. This is a bit ugly, but it seems
+-- more dependable than looking through shapes for math. Plus this is
+-- an xml implementation detail, so it seems to make sense to do it at
+-- the xml level.
+surroundWithMathAlternate :: Element -> Element
+surroundWithMathAlternate element =
+  case findElement (QName "m" Nothing (Just "a14")) element of
+    Just _ ->
+      mknode "mc:AlternateContent"
+         [("xmlns:mc", "http://schemas.openxmlformats.org/markup-compatibility/2006")
+         ] [ mknode "mc:Choice"
+             [ ("xmlns:a14", "http://schemas.microsoft.com/office/drawing/2010/main")
+             , ("Requires", "a14")] [ element ]
+           ]
+    Nothing -> element
+
+paragraphToElement :: PandocMonad m => Paragraph -> P m Element
+paragraphToElement par = do
+  indents <- asks envOtherStyleIndents
+  let
+    lvl = pPropLevel (paraProps par)
+    attrs = [("lvl", tshow lvl)] <>
+            (case (pPropIndent (paraProps par), pPropMarginLeft (paraProps par)) of
+               (Just px1, Just px2) -> [ ("indent", tshow $ pixelsToEmu px1)
+                                       , ("marL", tshow $ pixelsToEmu px2)
+                                       ]
+               (Just px1, Nothing) -> [("indent", tshow $ pixelsToEmu px1)]
+               (Nothing, Just px2) -> [("marL", tshow $ pixelsToEmu px2)]
+               (Nothing, Nothing) -> fromMaybe [] $ do
+                 indents' <- indents
+                 thisLevel <- levelIndent indents' lvl
+                 nextLevel <- levelIndent indents' (lvl + 1)
+                 let (m, i) =
+                       case pPropBullet (paraProps par) of
+                         Nothing ->
+                           (Just (marL thisLevel), Just 0)
+                         Just (AutoNumbering _) ->
+                           ( Just (marL nextLevel)
+                           , Just (marL thisLevel - marL nextLevel)
+                           )
+                         Just Bullet -> (Nothing, Nothing)
+                 pure ( toList ((,) "indent" . tshow <$> i)
+                      <> toList ((,) "marL" . tshow <$> m)
+                      )
+            ) <>
+            (case pPropAlign (paraProps par) of
+               Just AlgnLeft -> [("algn", "l")]
+               Just AlgnRight -> [("algn", "r")]
+               Just AlgnCenter -> [("algn", "ctr")]
+               Nothing -> []
+            )
+    props = [] <>
+            (case pPropSpaceBefore $ paraProps par of
+               Just px -> [mknode "a:spcBef" [] [
+                              mknode "a:spcPts" [("val", tshow $ 100 * px)] ()
+                              ]
+                          ]
+               Nothing -> []
+            ) <>
+            (case pPropBullet $ paraProps par of
+               Just Bullet -> []
+               Just (AutoNumbering attrs') ->
+                 [mknode "a:buAutoNum" (autoNumAttrs attrs') ()]
+               Nothing -> [mknode "a:buNone" [] ()]
+            )
+  paras <- mconcat <$> mapM paraElemToElements (consolidateRuns (paraElems par))
+  return $ mknode "a:p" [] $ [Elem $ mknode "a:pPr" attrs props] <> paras
+
+shapeToElement :: PandocMonad m => Element -> Shape -> P m (Maybe ShapeId, Element)
+shapeToElement layout (TextBox paras)
+  | ns <- elemToNameSpaces layout
+  , Just cSld <- findChild (elemName ns "p" "cSld") layout
+  , Just spTree <- findChild (elemName ns "p" "spTree") cSld = do
+      (shapeId, sp) <- getContentShape ns spTree
+      elements <- mapM paragraphToElement paras
+      let txBody = mknode "p:txBody" [] $
+                   [mknode "a:bodyPr" [] (), mknode "a:lstStyle" [] ()] <> elements
+          emptySpPr = mknode "p:spPr" [] ()
+      return
+        . (shapeId,)
+        . surroundWithMathAlternate
+        . replaceNamedChildren ns "p" "txBody" [txBody]
+        . replaceNamedChildren ns "p" "spPr" [emptySpPr]
+        $ sp
+-- GraphicFrame and Pic should never reach this.
+shapeToElement _ _ = return (Nothing, mknode "p:sp" [] ())
+
+shapeToElements :: PandocMonad m => Element -> Shape -> P m [(Maybe ShapeId, Content)]
+shapeToElements layout (Pic picProps fp titleText alt) = do
+  mInfo <- registerMedia fp alt
+  case mInfoExt mInfo of
+    Just _ -> map (bimap Just Elem) <$>
+      makePicElements layout picProps mInfo titleText alt
+    Nothing -> shapeToElements layout $ TextBox [Paragraph def alt]
+shapeToElements layout (GraphicFrame tbls cptn) = map (bimap Just Elem) <$>
+  graphicFrameToElements layout tbls cptn
+shapeToElements _ (RawOOXMLShape str) = return
+  [(Nothing, Text (CData CDataRaw str Nothing))]
+shapeToElements layout shp@(TextBox _) = do
+  (shapeId, element) <- shapeToElement layout shp
+  return [(shapeId, Elem element)]
+
+shapesToElements :: PandocMonad m => Element -> [Shape] -> P m [(Maybe ShapeId, Content)]
+shapesToElements layout shps =
+ concat <$> mapM (shapeToElements layout) shps
+
+graphicFrameToElements ::
+  PandocMonad m =>
+  Element ->
+  [Graphic] ->
+  [ParaElem] ->
+  P m [(ShapeId, Element)]
+graphicFrameToElements layout tbls caption = do
+  -- get the sizing
+  master <- getMaster
+  (pageWidth, pageHeight) <- asks envPresentationSize
+  let ns = elemToNameSpaces layout
+  ((x, y), (cx, cytmp)) <- getContentShapeSize ns layout master
+                           `catchError`
+                           (\_ -> return ((0, 0), (pageWidth, pageHeight)))
+
+  let cy = if not $ null caption then cytmp - captionHeight else cytmp
+
+  elements <- mapM (graphicToElement cx) tbls
+  let graphicFrameElts =
+        ( 6
+        , mknode "p:graphicFrame" [] $
+          [ mknode "p:nvGraphicFramePr" []
+            [ mknode "p:cNvPr" [("id", "6"), ("name", "Content Placeholder 5")] ()
+            , mknode "p:cNvGraphicFramePr" []
+              [mknode "a:graphicFrameLocks" [("noGrp", "1")] ()]
+            , mknode "p:nvPr" []
+              [mknode "p:ph" [("idx", "1")] ()]
+            ]
+          , mknode "p:xfrm" []
+            [ mknode "a:off" [("x", tshow $ 12700 * x),
+                              ("y", tshow $ 12700 * y)] ()
+            , mknode "a:ext" [("cx", tshow $ 12700 * cx),
+                              ("cy", tshow $ 12700 * cy)] ()
+            ]
+          ] <> elements
+        )
+
+  if not $ null caption
+    then do capElt <- createCaption ((x, y), (cx, cytmp)) caption
+            return [graphicFrameElts, capElt]
+    else return [graphicFrameElts]
+
+getDefaultTableStyle :: PandocMonad m => P m (Maybe T.Text)
+getDefaultTableStyle = do
+  refArchive <- asks envRefArchive
+  distArchive <- asks envDistArchive
+  tblStyleLst <- parseXml refArchive distArchive "ppt/tableStyles.xml"
+  return $ findAttr (QName "def" Nothing Nothing) tblStyleLst
+
+graphicToElement :: PandocMonad m => Integer -> Graphic -> P m Element
+graphicToElement tableWidth (Tbl widths tblPr hdrCells rows) = do
+  let totalWidth = sum widths
+  let colWidths = if 0.0 `elem` widths
+                  then if null hdrCells
+                      then case rows of
+                         r@(_:_) : _ -> replicate (length r) $
+                                                 tableWidth `div` toInteger (length r)
+                         []: _ -> []
+                         [] -> []
+                      else replicate (length hdrCells) $
+                           tableWidth `div` toInteger (length hdrCells)
+                  else map (\w -> round $ w / totalWidth * fromIntegral tableWidth) widths
+
+  let cellToOpenXML paras =
+        do elements <- mapM paragraphToElement paras
+           let elements' = if null elements
+                           then [mknode "a:p" [] [mknode "a:endParaRPr" [] ()]]
+                           else elements
+
+           return
+             [mknode "a:txBody" [] $
+               [ mknode "a:bodyPr" [] ()
+               , mknode "a:lstStyle" [] ()]
+               <> elements']
+  headers' <- mapM cellToOpenXML hdrCells
+  rows' <- mapM (mapM cellToOpenXML) rows
+  let borderProps = mknode "a:tcPr" [] ()
+  let emptyCell' = [mknode "a:p" [] [mknode "a:pPr" [] ()]]
+  let mkcell border contents = mknode "a:tc" []
+                            $ (if null contents
+                               then emptyCell'
+                               else contents) <> [ borderProps | border ]
+  let mkrow border cells = mknode "a:tr" [("h", "0")] $ map (mkcell border) cells
+
+  let mkgridcol w = mknode "a:gridCol"
+                       [("w", tshow ((12700 * w) :: Integer))] ()
+  let hasHeader = not (all null hdrCells)
+
+  mbDefTblStyle <- getDefaultTableStyle
+  let tblPrElt = mknode "a:tblPr"
+                 [ ("firstRow", if tblPrFirstRow tblPr then "1" else "0")
+                 , ("bandRow", if tblPrBandRow tblPr then "1" else "0")
+                 ] (case mbDefTblStyle of
+                      Nothing -> []
+                      Just sty -> [mknode "a:tableStyleId" [] sty])
+
+  return $ mknode "a:graphic" []
+    [mknode "a:graphicData" [("uri", "http://schemas.openxmlformats.org/drawingml/2006/table")]
+     [mknode "a:tbl" [] $
+      [ tblPrElt
+      , mknode "a:tblGrid" [] (if all (==0) colWidths
+                               then []
+                               else map mkgridcol colWidths)
+      ]
+      <> [ mkrow True headers' | hasHeader ] <> map (mkrow False) rows'
+     ]
+    ]
+
+
+-- We get the shape by placeholder type. If there is NO type, it
+-- defaults to a content placeholder.
+
+data PHType = PHType T.Text | ObjType
+  deriving (Show, Eq)
+
+findPHType :: NameSpaces -> Element -> PHType -> Bool
+findPHType ns spElem phType
+  | isElem ns "p" "sp" spElem =
+    let mbPHElem = (Just spElem >>=
+                   findChild (elemName ns "p" "nvSpPr") >>=
+                   findChild (elemName ns "p" "nvPr") >>=
+                   findChild (elemName ns "p" "ph"))
+    in
+      case mbPHElem of
+        -- if it's a named PHType, we want to check that the attribute
+        -- value matches.
+        Just phElem | (PHType tp) <- phType ->
+                        case findAttr (QName "type" Nothing Nothing) phElem of
+                          Just tp' -> tp == tp'
+                          Nothing -> False
+        -- if it's an ObjType, we want to check that there is NO
+        -- "type" attribute. In other words, a lookup should return nothing.
+        Just phElem | ObjType <- phType ->
+                        case findAttr (QName "type" Nothing Nothing) phElem of
+                          Just _ -> False
+                          Nothing -> True
+        Nothing -> False
+findPHType _ _ _ = False
+
+getShapesByPlaceHolderType :: NameSpaces -> Element -> PHType -> [Element]
+getShapesByPlaceHolderType ns spTreeElem phType
+  | isElem ns "p" "spTree" spTreeElem =
+      filterChildren (\e -> findPHType ns e phType) spTreeElem
+  | otherwise = []
+
+getShapeByPlaceHolderType :: NameSpaces -> Element -> PHType -> Maybe Element
+getShapeByPlaceHolderType ns spTreeElem phType =
+  listToMaybe $ getShapesByPlaceHolderType ns spTreeElem phType
+
+-- Like the above, but it tries a number of different placeholder types
+getShapeByPlaceHolderTypes :: NameSpaces -> Element -> [PHType] -> Maybe Element
+getShapeByPlaceHolderTypes _ _ [] = Nothing
+getShapeByPlaceHolderTypes ns spTreeElem (s:ss) =
+  case getShapeByPlaceHolderType ns spTreeElem s of
+    Just element -> Just element
+    Nothing -> getShapeByPlaceHolderTypes ns spTreeElem ss
+
+nonBodyTextToElement ::
+  PandocMonad m =>
+  Element ->
+  [PHType] ->
+  [ParaElem] ->
+  P m (Maybe ShapeId, Element)
+nonBodyTextToElement layout phTypes paraElements
+  | ns <- elemToNameSpaces layout
+  , Just cSld <- findChild (elemName ns "p" "cSld") layout
+  , Just spTree <- findChild (elemName ns "p" "spTree") cSld
+  , Just sp <- getShapeByPlaceHolderTypes ns spTree phTypes
+  , Just nvSpPr <- findChild (elemName ns "p" "nvSpPr") sp
+  , Just cNvPr <- findChild (elemName ns "p" "cNvPr") nvSpPr
+  , Just shapeId <- findAttr (nodename "id") cNvPr
+  , Right (shapeIdNum, _) <- decimal shapeId = do
+      let hdrPara = Paragraph def paraElements
+      element <- paragraphToElement hdrPara
+      let txBody = mknode "p:txBody" [] $
+                   [mknode "a:bodyPr" [] (), mknode "a:lstStyle" [] ()] <>
+                   [element]
+      return (Just shapeIdNum,
+              surroundWithMathAlternate $
+                replaceNamedChildren ns "p" "txBody" [txBody] sp)
+  -- XXX: TODO
+  | otherwise = return (Nothing, mknode "p:sp" [] ())
+
+data ContentShapeIds = ContentShapeIds
+  { contentHeaderId :: Maybe ShapeId
+  , contentContentIds :: [ShapeId]
+  }
+
+contentToElement ::
+  PandocMonad m =>
+  Element ->
+  [ParaElem] ->
+  [Shape] ->
+  P m (Maybe ContentShapeIds, Element)
+contentToElement layout hdrShape shapes
+  | ns <- elemToNameSpaces layout
+  , Just cSld <- findChild (elemName ns "p" "cSld") layout
+  , Just spTree <- findChild (elemName ns "p" "spTree") cSld = do
+      (shapeId, element) <- nonBodyTextToElement layout [PHType "title"] hdrShape
+      let hdrShapeElements = [Elem element | not (null hdrShape)]
+          contentHeaderId = if null hdrShape then Nothing else shapeId
+      content' <- local
+                         (\env -> env {envPlaceholder = Placeholder ObjType 0})
+                         (shapesToElements layout shapes)
+      let contentContentIds = mapMaybe fst content'
+          contentElements = snd <$> content'
+      footer <- footerElements content
+      return ( Just ContentShapeIds{..}
+             , buildSpTree ns spTree (hdrShapeElements <> contentElements <> footer)
+             )
+contentToElement _ _ _ = return (Nothing, mknode "p:sp" [] ())
+
+data TwoColumnShapeIds = TwoColumnShapeIds
+  { twoColumnHeaderId :: Maybe ShapeId
+  , twoColumnLeftIds :: [ShapeId]
+  , twoColumnRightIds :: [ShapeId]
+  }
+
+twoColumnToElement ::
+  PandocMonad m =>
+  Element ->
+  [ParaElem] ->
+  [Shape] ->
+  [Shape] ->
+  P m (Maybe TwoColumnShapeIds, Element)
+twoColumnToElement layout hdrShape shapesL shapesR
+  | ns <- elemToNameSpaces layout
+  , Just cSld <- findChild (elemName ns "p" "cSld") layout
+  , Just spTree <- findChild (elemName ns "p" "spTree") cSld = do
+      (headerId, element) <- nonBodyTextToElement layout [PHType "title"] hdrShape
+      let hdrShapeElements = [Elem element | not (null hdrShape)]
+          twoColumnHeaderId = if null hdrShape then Nothing else headerId
+      contentL <- local (\env -> env {envPlaceholder = Placeholder ObjType 0})
+                        (shapesToElements layout shapesL)
+      let twoColumnLeftIds = mapMaybe fst contentL
+          contentElementsL = snd <$> contentL
+      contentR <- local (\env -> env {envPlaceholder = Placeholder ObjType 1})
+                        (shapesToElements layout shapesR)
+      let (twoColumnRightIds) = (mapMaybe fst contentR)
+          contentElementsR = snd <$> contentR
+      -- let contentElementsL' = map (setIdx ns "1") contentElementsL
+      --     contentElementsR' = map (setIdx ns "2") contentElementsR
+      footer <- footerElements twoColumn
+      return
+        $ (Just TwoColumnShapeIds{..}, )
+        $ buildSpTree ns spTree
+        $ hdrShapeElements <> contentElementsL <> contentElementsR <> footer
+twoColumnToElement _ _ _ _ = return (Nothing, mknode "p:sp" [] ())
+
+data ComparisonShapeIds = ComparisonShapeIds
+  { comparisonHeaderId :: Maybe ShapeId
+  , comparisonLeftTextIds :: [ShapeId]
+  , comparisonLeftContentIds :: [ShapeId]
+  , comparisonRightTextIds :: [ShapeId]
+  , comparisonRightContentIds :: [ShapeId]
+  }
+
+comparisonToElement ::
+  PandocMonad m =>
+  Element ->
+  [ParaElem] ->
+  ([Shape], [Shape]) ->
+  ([Shape], [Shape]) ->
+  P m (Maybe ComparisonShapeIds, Element)
+comparisonToElement layout hdrShape (shapesL1, shapesL2) (shapesR1, shapesR2)
+  | ns <- elemToNameSpaces layout
+  , Just cSld <- findChild (elemName ns "p" "cSld") layout
+  , Just spTree <- findChild (elemName ns "p" "spTree") cSld = do
+      (headerShapeId, element) <- nonBodyTextToElement layout [PHType "title"] hdrShape
+      let hdrShapeElements = [Elem element | not (null hdrShape)]
+          comparisonHeaderId = if null hdrShape then Nothing else headerShapeId
+      contentL1 <- local (\env -> env {envPlaceholder = Placeholder (PHType "body") 0})
+                         (shapesToElements layout shapesL1)
+      let comparisonLeftTextIds = mapMaybe fst contentL1
+          contentElementsL1 = snd <$> contentL1
+      contentL2 <- local (\env -> env {envPlaceholder = Placeholder ObjType 0})
+                         (shapesToElements layout shapesL2)
+      let comparisonLeftContentIds = mapMaybe fst contentL2
+          contentElementsL2 = snd <$> contentL2
+      contentR1 <- local (\env -> env {envPlaceholder = Placeholder (PHType "body") 1})
+                         (shapesToElements layout shapesR1)
+      let comparisonRightTextIds = mapMaybe fst contentR1
+          contentElementsR1 = snd <$> contentR1
+      contentR2 <- local (\env -> env {envPlaceholder = Placeholder ObjType 1})
+                         (shapesToElements layout shapesR2)
+      let comparisonRightContentIds = mapMaybe fst contentR2
+          contentElementsR2 = snd <$> contentR2
+      footer <- footerElements comparison
+      return
+        $ (Just ComparisonShapeIds{..}, )
+        $ buildSpTree ns spTree
+        $ mconcat [ hdrShapeElements
+                  , contentElementsL1
+                  , contentElementsL2
+                  , contentElementsR1
+                  , contentElementsR2
+                  ] <> footer
+comparisonToElement _ _ _ _= return (Nothing, mknode "p:sp" [] ())
+
+data ContentWithCaptionShapeIds = ContentWithCaptionShapeIds
+  { contentWithCaptionHeaderId :: Maybe ShapeId
+  , contentWithCaptionCaptionIds :: [ShapeId]
+  , contentWithCaptionContentIds :: [ShapeId]
+  }
+
+contentWithCaptionToElement ::
+  PandocMonad m =>
+  Element ->
+  [ParaElem] ->
+  [Shape] ->
+  [Shape] ->
+  P m (Maybe ContentWithCaptionShapeIds, Element)
+contentWithCaptionToElement layout hdrShape textShapes contentShapes
+  | ns <- elemToNameSpaces layout
+  , Just cSld <- findChild (elemName ns "p" "cSld") layout
+  , Just spTree <- findChild (elemName ns "p" "spTree") cSld = do
+      (shapeId, element) <- nonBodyTextToElement layout [PHType "title"] hdrShape
+      let hdrShapeElements = [Elem element | not (null hdrShape)]
+          contentWithCaptionHeaderId = if null hdrShape then Nothing else shapeId
+      text <- local (\env -> env {envPlaceholder = Placeholder (PHType "body") 0})
+                    (shapesToElements layout textShapes)
+      let contentWithCaptionCaptionIds = mapMaybe fst text
+          textElements = snd <$> text
+      content <- local (\env -> env {envPlaceholder = Placeholder ObjType 0})
+                       (shapesToElements layout contentShapes)
+      let contentWithCaptionContentIds = mapMaybe fst content
+          contentElements = snd <$> content
+      footer <- footerElements contentWithCaption
+      return
+        $ (Just ContentWithCaptionShapeIds{..}, )
+        $ buildSpTree ns spTree
+        $ mconcat [ hdrShapeElements
+                  , textElements
+                  , contentElements
+                  ] <> footer
+contentWithCaptionToElement _ _ _ _ = return (Nothing, mknode "p:sp" [] ())
+
+blankToElement ::
+  PandocMonad m =>
+  Element ->
+  P m Element
+blankToElement layout
+  | ns <- elemToNameSpaces layout
+  , Just cSld <- findChild (elemName ns "p" "cSld") layout
+  , Just spTree <- findChild (elemName ns "p" "spTree") cSld =
+      buildSpTree ns spTree <$> footerElements blank
+blankToElement _ = return $ mknode "p:sp" [] ()
+
+newtype TitleShapeIds = TitleShapeIds
+  { titleHeaderId :: Maybe ShapeId
+  }
+
+titleToElement ::
+  PandocMonad m =>
+  Element ->
+  [ParaElem] ->
+  P m (Maybe TitleShapeIds, Element)
+titleToElement layout titleElems
+  | ns <- elemToNameSpaces layout
+  , Just cSld <- findChild (elemName ns "p" "cSld") layout
+  , Just spTree <- findChild (elemName ns "p" "spTree") cSld = do
+      (shapeId, element) <- nonBodyTextToElement layout [PHType "title", PHType "ctrTitle"] titleElems
+      let titleShapeElements = [Elem element | not (null titleElems)]
+          titleHeaderId = if null titleElems then Nothing else shapeId
+      footer <- footerElements title
+      return
+        $ (Just TitleShapeIds{..}, )
+        $ buildSpTree ns spTree (titleShapeElements <> footer)
+titleToElement _ _ = return (Nothing, mknode "p:sp" [] ())
+
+data MetadataShapeIds = MetadataShapeIds
+  { metadataTitleId :: Maybe ShapeId
+  , metadataSubtitleId :: Maybe ShapeId
+  , metadataDateId :: Maybe ShapeId
+  }
+
+metadataToElement ::
+  PandocMonad m =>
+  Element ->
+  [ParaElem] ->
+  [ParaElem] ->
+  [[ParaElem]] ->
+  [ParaElem] ->
+  P m (Maybe MetadataShapeIds, Element)
+metadataToElement layout titleElems subtitleElems authorsElems dateElems
+  | ns <- elemToNameSpaces layout
+  , Just cSld <- findChild (elemName ns "p" "cSld") layout
+  , Just spTree <- findChild (elemName ns "p" "spTree") cSld = do
+      let combinedAuthorElems = intercalate [Break] authorsElems
+          subtitleAndAuthorElems = intercalate [Break, Break] $
+                                    filter (not . null)
+                                     [subtitleElems, combinedAuthorElems]
+      (titleId, titleElement) <- nonBodyTextToElement layout [PHType "ctrTitle"] titleElems
+      (subtitleId, subtitleElement) <- nonBodyTextToElement layout [PHType "subTitle"] subtitleAndAuthorElems
+      (dateId, dateElement) <- nonBodyTextToElement layout [PHType "dt"] dateElems
+      let titleShapeElements = [titleElement | not (null titleElems)]
+          metadataTitleId = if null titleElems then Nothing else titleId
+          subtitleShapeElements = [subtitleElement | not (null subtitleAndAuthorElems)]
+          metadataSubtitleId = if null subtitleAndAuthorElems then Nothing else subtitleId
+      footerInfo <- gets stFooterInfo
+      footer <- (if maybe False fiShowOnFirstSlide footerInfo
+                 then id
+                 else const []) <$> footerElements metadata
+      let dateShapeElements = [dateElement
+                              | not (null dateElems
+                                || isJust (footerInfo >>= metadata . fiDate))
+                              ]
+          metadataDateId = if null dateElems then Nothing else dateId
+      return
+        $ (Just MetadataShapeIds{..}, )
+        $ buildSpTree ns spTree
+        $ map Elem (titleShapeElements <> subtitleShapeElements <> dateShapeElements)
+        <> footer
+metadataToElement _ _ _ _ _ = return (Nothing, mknode "p:sp" [] ())
+
+slideToElement :: PandocMonad m => Slide -> P m Element
+slideToElement (Slide _ l@(ContentSlide hdrElems shapes) _ backgroundImage) = do
+  layout <- getLayout l
+  backgroundImageElement <- traverse backgroundImageToElement backgroundImage
+  (shapeIds, spTree)
+     <- local (\env -> if null hdrElems
+                       then env
+                       else env{envSlideHasHeader=True})
+              (contentToElement layout hdrElems shapes)
+  let animations = case shapeIds of
+        Nothing -> []
+        Just ContentShapeIds{..} ->
+          slideToIncrementalAnimations (zip contentContentIds shapes)
+  return $ mknode "p:sld"
+    [ ("xmlns:a", "http://schemas.openxmlformats.org/drawingml/2006/main"),
+      ("xmlns:r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships"),
+      ("xmlns:p", "http://schemas.openxmlformats.org/presentationml/2006/main")
+    ] (mknode "p:cSld" [] (toList backgroundImageElement <> [spTree]) : animations)
+slideToElement (Slide _ l@(TwoColumnSlide hdrElems shapesL shapesR) _ backgroundImage) = do
+  layout <- getLayout l
+  backgroundImageElement <- traverse backgroundImageToElement backgroundImage
+  (shapeIds, spTree) <- local (\env -> if null hdrElems
+                           then env
+                           else env{envSlideHasHeader=True}) $
+            twoColumnToElement layout hdrElems shapesL shapesR
+  let animations = case shapeIds of
+        Nothing -> []
+        Just TwoColumnShapeIds{..} ->
+          slideToIncrementalAnimations (zip twoColumnLeftIds shapesL
+                                        <> zip twoColumnRightIds shapesR)
+  return $ mknode "p:sld"
+    [ ("xmlns:a", "http://schemas.openxmlformats.org/drawingml/2006/main"),
+      ("xmlns:r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships"),
+      ("xmlns:p", "http://schemas.openxmlformats.org/presentationml/2006/main")
+    ] (mknode "p:cSld" [] (toList backgroundImageElement <> [spTree]) : animations)
+slideToElement (Slide _ l@(ComparisonSlide hdrElems shapesL shapesR) _ backgroundImage) = do
+  layout <- getLayout l
+  backgroundImageElement <- traverse backgroundImageToElement backgroundImage
+  (shapeIds, spTree) <- local (\env -> if null hdrElems
+                           then env
+                           else env{envSlideHasHeader=True}) $
+            comparisonToElement layout hdrElems shapesL shapesR
+  let animations = case shapeIds of
+        Nothing -> []
+        Just ComparisonShapeIds{..} ->
+          slideToIncrementalAnimations
+            (zip comparisonLeftTextIds (fst shapesL)
+            <> zip comparisonLeftContentIds (snd shapesL)
+            <> zip comparisonRightTextIds (fst shapesR)
+            <> zip comparisonRightContentIds (snd shapesR))
+  return $ mknode "p:sld"
+    [ ("xmlns:a", "http://schemas.openxmlformats.org/drawingml/2006/main"),
+      ("xmlns:r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships"),
+      ("xmlns:p", "http://schemas.openxmlformats.org/presentationml/2006/main")
+    ] (mknode "p:cSld" [] (toList backgroundImageElement <> [spTree]) : animations)
+slideToElement (Slide _ l@(TitleSlide hdrElems) _ backgroundImage) = do
+  layout <- getLayout l
+  backgroundImageElement <- traverse backgroundImageToElement backgroundImage
+  (_, spTree) <- titleToElement layout hdrElems
+  return $ mknode "p:sld"
+    [ ("xmlns:a", "http://schemas.openxmlformats.org/drawingml/2006/main"),
+      ("xmlns:r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships"),
+      ("xmlns:p", "http://schemas.openxmlformats.org/presentationml/2006/main")
+    ] [mknode "p:cSld" [] (toList backgroundImageElement <> [spTree])]
+slideToElement (Slide
+                _
+                l@(MetadataSlide titleElems subtitleElems authorElems dateElems)
+                _
+                backgroundImage) = do
+  layout <- getLayout l
+  backgroundImageElement <- traverse backgroundImageToElement backgroundImage
+  (_, spTree) <- metadataToElement layout titleElems subtitleElems authorElems dateElems
+  return $ mknode "p:sld"
+    [ ("xmlns:a", "http://schemas.openxmlformats.org/drawingml/2006/main"),
+      ("xmlns:r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships"),
+      ("xmlns:p", "http://schemas.openxmlformats.org/presentationml/2006/main")
+    ] [mknode "p:cSld" [] (toList backgroundImageElement <> [spTree])]
+slideToElement (Slide
+                _
+                l@(ContentWithCaptionSlide hdrElems captionShapes contentShapes)
+                _
+                backgroundImage) = do
+  layout <- getLayout l
+  backgroundImageElement <- traverse backgroundImageToElement backgroundImage
+  (shapeIds, spTree) <- contentWithCaptionToElement layout hdrElems captionShapes contentShapes
+  let animations = case shapeIds of
+        Nothing -> []
+        Just ContentWithCaptionShapeIds{..} ->
+          slideToIncrementalAnimations
+            (zip contentWithCaptionCaptionIds captionShapes
+             <> zip contentWithCaptionContentIds contentShapes)
+  return $ mknode "p:sld"
+    [ ("xmlns:a", "http://schemas.openxmlformats.org/drawingml/2006/main"),
+      ("xmlns:r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships"),
+      ("xmlns:p", "http://schemas.openxmlformats.org/presentationml/2006/main")
+    ] (mknode "p:cSld" [] (toList backgroundImageElement <> [spTree]) : animations)
+slideToElement (Slide _ BlankSlide _ backgroundImage) = do
+  layout <- getLayout BlankSlide
+  backgroundImageElement <- traverse backgroundImageToElement backgroundImage
+  spTree <- blankToElement layout
+  return $ mknode "p:sld"
+    [ ("xmlns:a", "http://schemas.openxmlformats.org/drawingml/2006/main"),
+      ("xmlns:r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships"),
+      ("xmlns:p", "http://schemas.openxmlformats.org/presentationml/2006/main")
+    ] [mknode "p:cSld" [] (toList backgroundImageElement <> [spTree])]
+
+backgroundImageToElement :: PandocMonad m => FilePath -> P m Element
+backgroundImageToElement path = do
+  MediaInfo{mInfoLocalId, mInfoFilePath} <- registerMedia path []
+  (imgBytes, _) <- P.fetchItem (T.pack mInfoFilePath)
+  opts <- asks envOpts
+  let imageDimensions = either (const Nothing)
+                               (Just . sizeInPixels)
+                               (imageSize opts imgBytes)
+  pageSize <- asks envPresentationSize
+  let fillRectAttributes = maybe [] (offsetAttributes pageSize) imageDimensions
+  let rId = "rId" <> T.pack (show mInfoLocalId)
+  return
+    $ mknode "p:bg" []
+    $ mknode "p:bgPr" []
+    [ mknode "a:blipFill" [("dpi", "0"), ("rotWithShape", "1")]
+      [ mknode "a:blip" [("r:embed", rId)]
+        $ mknode "a:lum" [] ()
+      , mknode "a:srcRect" [] ()
+      , mknode "a:stretch" []
+        $ mknode "a:fillRect" fillRectAttributes ()
+      ]
+    , mknode "a:effectsLst" [] ()
+    ]
+  where
+    offsetAttributes :: (Integer, Integer) -> (Integer, Integer) -> [(Text, Text)]
+    offsetAttributes (pageWidth, pageHeight) (pictureWidth, pictureHeight) = let
+      widthRatio = pictureWidth % pageWidth
+      heightRatio = pictureHeight % pageHeight
+      getOffset :: Ratio Integer -> Text
+      getOffset proportion = let
+          percentageOffset = (proportion - 1) * (-100 % 2)
+          integerOffset = round percentageOffset * 1000 :: Integer
+        in T.pack (show integerOffset)
+      in case compare widthRatio heightRatio of
+        EQ -> []
+        LT -> let
+          offset = getOffset ((pictureHeight % pageHeight) / widthRatio)
+          in [ ("t", offset)
+             , ("b", offset)
+             ]
+        GT -> let
+          offset = getOffset ((pictureWidth % pageWidth) / heightRatio)
+          in [ ("l", offset)
+             , ("r", offset)
+             ]
+
+
+slideToIncrementalAnimations ::
+  [(ShapeId, Shape)] ->
+  [Element]
+slideToIncrementalAnimations shapes = let
+  incrementals :: [(ShapeId, [Bool])]
+  incrementals = do
+    (shapeId, TextBox ps) <- shapes
+    pure . (shapeId,) $ do
+      Paragraph ParaProps{pPropIncremental} _ <- ps
+      pure pPropIncremental
+  toIndices :: [Bool] -> Maybe (NonEmpty (Integer, Integer))
+  toIndices bs = do
+        let indexed = zip [0..] bs
+        ts <- nonEmpty (filter snd indexed)
+        pure (fmap (\(n, _) -> (n, n)) ts)
+  indices :: [(ShapeId, NonEmpty (Integer, Integer))]
+  indices = do
+    (shapeId, bs) <- incrementals
+    toList ((,) shapeId <$> toIndices bs)
+  in toList (incrementalAnimation <$> nonEmpty indices)
+
+--------------------------------------------------------------------
+-- Notes:
+
+getNotesMaster :: PandocMonad m => P m Element
+getNotesMaster = do
+  refArchive <- asks envRefArchive
+  distArchive <- asks envDistArchive
+  parseXml refArchive distArchive "ppt/notesMasters/notesMaster1.xml"
+
+getSlideNumberFieldId :: PandocMonad m => Element -> P m T.Text
+getSlideNumberFieldId notesMaster
+  | ns <- elemToNameSpaces notesMaster
+  , Just cSld <- findChild (elemName ns "p" "cSld") notesMaster
+  , Just spTree <- findChild (elemName ns "p" "spTree") cSld
+  , Just sp <- getShapeByPlaceHolderType ns spTree (PHType "sldNum")
+  , Just txBody <- findChild (elemName ns "p" "txBody") sp
+  , Just p <- findChild (elemName ns "a" "p") txBody
+  , Just fld <- findChild (elemName ns "a" "fld") p
+  , Just fldId <- findAttr (QName "id" Nothing Nothing) fld =
+      return fldId
+  | otherwise = throwError $
+                PandocSomeError
+                "No field id for slide numbers in notesMaster.xml"
+
+speakerNotesSlideImage :: Element
+speakerNotesSlideImage =
+  mknode "p:sp" []
+  [ mknode "p:nvSpPr" []
+    [ mknode "p:cNvPr" [ ("id", "2")
+                       , ("name", "Slide Image Placeholder 1")
+                       ] ()
+    , mknode "p:cNvSpPr" []
+      [ mknode "a:spLocks" [ ("noGrp", "1")
+                           , ("noRot", "1")
+                           , ("noChangeAspect", "1")
+                           ] ()
+      ]
+    , mknode "p:nvPr" []
+      [ mknode "p:ph" [("type", "sldImg")] ()]
+    ]
+  , mknode "p:spPr" [] ()
+  ]
+
+-- we want to wipe links from the speaker notes in the
+-- paragraphs. Powerpoint doesn't allow you to input them, and it
+-- would provide extra complications.
+removeParaLinks :: Paragraph -> Paragraph
+removeParaLinks paragraph = paragraph{paraElems = map f (paraElems paragraph)}
+  where f (Run rProps s) = Run rProps{rLink=Nothing} s
+        f pe             = pe
+
+-- put an empty paragraph between paragraphs for more expected spacing.
+spaceParas :: [Paragraph] -> [Paragraph]
+spaceParas = intersperse (Paragraph def [])
+
+speakerNotesBody :: PandocMonad m => [Paragraph] -> P m Element
+speakerNotesBody paras = do
+  elements <- local (\env -> env{envInSpeakerNotes = True}) $
+              mapM paragraphToElement $ spaceParas $ map removeParaLinks paras
+  let txBody = mknode "p:txBody" [] $
+               [mknode "a:bodyPr" [] (), mknode "a:lstStyle" [] ()] <> elements
+  return $
+    surroundWithMathAlternate $
+    mknode "p:sp" []
+    [ mknode "p:nvSpPr" []
+      [ mknode "p:cNvPr" [ ("id", "3")
+                         , ("name", "Notes Placeholder 2")
+                         ] ()
+      , mknode "p:cNvSpPr" []
+        [ mknode "a:spLocks" [("noGrp", "1")] ()]
+      , mknode "p:nvPr" []
+        [ mknode "p:ph" [("type", "body"), ("idx", "1")] ()]
+      ]
+    , mknode "p:spPr" [] ()
+    , txBody
+    ]
+
+speakerNotesSlideNumber :: Int -> T.Text -> Element
+speakerNotesSlideNumber pgNum fieldId =
+  mknode "p:sp" []
+  [ mknode "p:nvSpPr" []
+    [ mknode "p:cNvPr" [ ("id", "4")
+                       , ("name", "Slide Number Placeholder 3")
+                       ] ()
+    , mknode "p:cNvSpPr" []
+      [ mknode "a:spLocks" [("noGrp", "1")] ()]
+    , mknode "p:nvPr" []
+      [ mknode "p:ph" [ ("type", "sldNum")
+                      , ("sz", "quarter")
+                      , ("idx", "10")
+                      ] ()
+      ]
+    ]
+  , mknode "p:spPr" [] ()
+  , mknode "p:txBody" []
+    [ mknode "a:bodyPr" [] ()
+    , mknode "a:lstStyle" [] ()
+    , mknode "a:p" []
+      [ mknode "a:fld" [ ("id", fieldId)
+                       , ("type", "slidenum")
+                       ]
+        [ mknode "a:rPr" [("lang", "en-US")] ()
+        , mknode "a:t" [] (tshow pgNum)
+        ]
+      , mknode "a:endParaRPr" [("lang", "en-US")] ()
+      ]
+    ]
+  ]
+
+slideToSpeakerNotesElement :: PandocMonad m => Slide -> P m (Maybe Element)
+slideToSpeakerNotesElement (Slide _ _ (SpeakerNotes []) _) = return Nothing
+slideToSpeakerNotesElement slide@(Slide _ _ (SpeakerNotes paras) _) = do
+  master <- getNotesMaster
+  fieldId  <- getSlideNumberFieldId master
+  num <- slideNum slide
+  let imgShape = speakerNotesSlideImage
+      sldNumShape = speakerNotesSlideNumber num fieldId
+  bodyShape <- speakerNotesBody paras
+  return $ Just $
+    mknode "p:notes"
+    [ ("xmlns:a", "http://schemas.openxmlformats.org/drawingml/2006/main")
+    , ("xmlns:r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships")
+    , ("xmlns:p", "http://schemas.openxmlformats.org/presentationml/2006/main")
+    ] [ mknode "p:cSld" []
+        [ mknode "p:spTree" []
+          [ mknode "p:nvGrpSpPr" []
+            [ mknode "p:cNvPr" [("id", "1"), ("name", "")] ()
+            , mknode "p:cNvGrpSpPr" [] ()
+            , mknode "p:nvPr" [] ()
+            ]
+          , mknode "p:grpSpPr" []
+            [ mknode "a:xfrm" []
+              [ mknode "a:off" [("x", "0"), ("y", "0")] ()
+              , mknode "a:ext" [("cx", "0"), ("cy", "0")] ()
+              , mknode "a:chOff" [("x", "0"), ("y", "0")] ()
+              , mknode "a:chExt" [("cx", "0"), ("cy", "0")] ()
+              ]
+            ]
+          , imgShape
+          , bodyShape
+          , sldNumShape
+          ]
+        ]
+      ]
+
+-----------------------------------------------------------------------
+
+getSlideIdNum :: PandocMonad m => SlideId -> P m Int
+getSlideIdNum sldId = do
+  slideIdMap <- asks envSlideIdMap
+  case  M.lookup sldId slideIdMap of
+    Just n -> return n
+    Nothing -> throwError $
+               PandocShouldNeverHappenError $
+               "Slide Id " <> tshow sldId <> " not found."
+
+slideNum :: PandocMonad m => Slide -> P m Int
+slideNum slide = getSlideIdNum $ slideId slide
+
+idNumToFilePath :: Int -> FilePath
+idNumToFilePath idNum = "slide" <> show idNum <> ".xml"
+
+slideToFilePath :: PandocMonad m => Slide -> P m FilePath
+slideToFilePath slide = do
+  idNum <- slideNum slide
+  return $ "slide" <> show idNum <> ".xml"
+
+slideToRelId ::
+  PandocMonad m =>
+  MinimumRId ->
+  Slide ->
+  P m T.Text
+slideToRelId minSlideRId slide = do
+  n <- slideNum slide
+  return $ "rId" <> tshow (n + minSlideRId - 1)
+
+
+data Relationship = Relationship { relId :: Int
+                                 , relType :: MimeType
+                                 , relTarget :: FilePath
+                                 } deriving (Show, Eq)
+
+elementToRel :: Element -> Maybe Relationship
+elementToRel element
+  | elName element == QName "Relationship" (Just "http://schemas.openxmlformats.org/package/2006/relationships") Nothing =
+      do rId <- findAttr (QName "Id" Nothing Nothing) element
+         numStr <- T.stripPrefix "rId" rId
+         num <- fromIntegral <$> readTextAsInteger numStr
+         type' <- findAttr (QName "Type" Nothing Nothing) element
+         target <- findAttr (QName "Target" Nothing Nothing) element
+         return $ Relationship num type' (T.unpack target)
+  | otherwise = Nothing
+
+slideToPresRel :: PandocMonad m => Int -> Slide -> P m Relationship
+slideToPresRel minimumSlideRId slide = do
+  idNum <- slideNum slide
+  let rId = idNum + minimumSlideRId - 1
+      fp = "slides/" <> idNumToFilePath idNum
+  return $ Relationship { relId = rId
+                        , relType = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/slide"
+                        , relTarget = fp
+                        }
+
+getPresentationRels :: PandocMonad m => P m [Relationship]
+getPresentationRels = do
+  refArchive <- asks envRefArchive
+  distArchive <- asks envDistArchive
+  relsElem <- parseXml refArchive distArchive "ppt/_rels/presentation.xml.rels"
+  let globalNS = "http://schemas.openxmlformats.org/package/2006/relationships"
+  let relElems = findChildren (QName "Relationship" (Just globalNS) Nothing) relsElem
+  return $ mapMaybe elementToRel relElems
+
+-- | Info required to update a presentation rId from the reference doc for the
+-- output.
+type PresentationRIdUpdateData = (ReferenceMinRIdAfterSlides, NewRIdBounds)
+
+-- | The minimum and maximum rIds for presentation relationships created from
+-- the presentation content (as opposed to from the reference doc).
+--
+-- Relationships taken from the reference doc should have their rId number
+-- adjusted to make sure it sits outside this range.
+type NewRIdBounds = (MinimumRId, MaximumRId)
+
+-- | The minimum presentation rId from the reference doc which comes after the
+-- first slide rId (in the reference doc).
+type ReferenceMinRIdAfterSlides = Int
+type MinimumRId = Int
+type MaximumRId = Int
+
+-- | Given a presentation rId from the reference doc, return the value it should
+-- have in the output.
+updatePresentationRId :: PresentationRIdUpdateData -> Int -> Int
+updatePresentationRId (minOverlappingRId, (minNewId, maxNewId)) n
+  | n < minNewId = n
+  | otherwise = n - minOverlappingRId + maxNewId + 1
+
+presentationToRels ::
+  PandocMonad m =>
+  Presentation ->
+  P m (PresentationRIdUpdateData, [Relationship])
+presentationToRels pres@(Presentation _ slides) = do
+  rels <- getPresentationRels
+
+  -- We want to make room for the slides in the id space. We'll assume the slide
+  -- masters come first (this seems to be what PowerPoint does by default, and
+  -- is true of the reference doc), and we'll put the slides next. So we find
+  -- the starting rId for the slides by finding the maximum rId for the masters
+  -- and adding 1.
+  --
+  -- Then:
+  -- 1. We look to see what the minimum rId which is greater than or equal to
+  --    the minimum slide rId is, in the rels we're keeping from the reference
+  --    doc (i.e. the minimum rId which might overlap with the slides).
+  -- 2. We increase this minimum overlapping rId to 1 higher than the last slide
+  --    rId (or the notesMaster rel, if we're including one), and increase all
+  --    rIds higher than this minimum by the same amount.
+
+  let masterRels = filter (T.isSuffixOf "slideMaster" . relType) rels
+      slideStartId = maybe 1 ((+ 1) . maximum . fmap relId) (nonEmpty masterRels)
+      -- we remove the slide rels and the notesmaster (if it's
+      -- there). We'll put these back in ourselves, if necessary.
+      relsWeKeep = filter
+                   (\r -> relType r /= "http://schemas.openxmlformats.org/officeDocument/2006/relationships/slide" &&
+                          relType r /= "http://schemas.openxmlformats.org/officeDocument/2006/relationships/notesMaster")
+                   rels
+      minOverlappingRel = maybe 0 minimum
+                                 (nonEmpty (filter (slideStartId <=)
+                                                   (relId <$> relsWeKeep)))
+
+  mySlideRels <- mapM (slideToPresRel slideStartId) slides
+
+  let notesMasterRels =
+        [Relationship { relId = slideStartId + length mySlideRels
+                         , relType = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/notesMaster"
+                         , relTarget = "notesMasters/notesMaster1.xml"
+                         } | presHasSpeakerNotes pres]
+      insertedRels = mySlideRels <> notesMasterRels
+      newRIdBounds = (slideStartId, slideStartId + length insertedRels - 1)
+      updateRId = updatePresentationRId (minOverlappingRel, newRIdBounds)
+
+      relsWeKeep' = map (\r -> r{relId = updateRId $ relId r}) relsWeKeep
+
+  return ((minOverlappingRel, newRIdBounds), insertedRels <> relsWeKeep')
+
+-- We make this ourselves, in case there's a thumbnail in the one from
+-- the template.
+topLevelRels :: [Relationship]
+topLevelRels =
+  [ Relationship { relId = 1
+                 , relType = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument"
+                 , relTarget = "ppt/presentation.xml"
+                 }
+  , Relationship { relId = 2
+                 , relType = "http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties"
+                 , relTarget = "docProps/core.xml"
+                 }
+  , Relationship { relId = 3
+                 , relType = "http://schemas.openxmlformats.org/package/2006/relationships/metadata/extended-properties"
+                 , relTarget = "docProps/app.xml"
+                 }
+  , Relationship { relId = 4
+                 , relType = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/custom-properties"
+                 , relTarget = "docProps/custom.xml"
+                 }
+  ]
+
+topLevelRelsEntry :: PandocMonad m => P m Entry
+topLevelRelsEntry = elemToEntry "_rels/.rels" $ relsToElement topLevelRels
+
+relToElement :: Relationship -> Element
+relToElement rel = mknode "Relationship" [ ("Id", "rId" <> tshow (relId rel))
+                                         , ("Type", relType rel)
+                                         , ("Target", T.pack $ relTarget rel) ] ()
+
+relsToElement :: [Relationship] -> Element
+relsToElement rels = mknode "Relationships"
+                     [("xmlns", "http://schemas.openxmlformats.org/package/2006/relationships")]
+                     (map relToElement rels)
+
+presentationToRelsEntry ::
+  PandocMonad m =>
+  Presentation ->
+  P m (PresentationRIdUpdateData, Entry)
+presentationToRelsEntry pres = do
+  (presentationRIdUpdateData, rels) <- presentationToRels pres
+  element <- elemToEntry "ppt/_rels/presentation.xml.rels" $ relsToElement rels
+  pure (presentationRIdUpdateData, element)
+
+elemToEntry :: PandocMonad m => FilePath -> Element -> P m Entry
+elemToEntry fp element = do
+  epochtime <- floor . utcTimeToPOSIXSeconds <$> asks envUTCTime
+  return $ toEntry fp epochtime $ renderXml element
+
+slideToEntry :: PandocMonad m => Slide -> P m Entry
+slideToEntry slide = do
+  idNum <- slideNum slide
+  local (\env -> env{envCurSlideId = idNum}) $ do
+    element <- slideToElement slide
+    elemToEntry ("ppt/slides/" <> idNumToFilePath idNum) element
+
+slideToSpeakerNotesEntry :: PandocMonad m => Slide -> P m (Maybe Entry)
+slideToSpeakerNotesEntry slide = do
+  idNum <- slideNum slide
+  local (\env -> env{envCurSlideId = idNum}) $ do
+    mbElement <- slideToSpeakerNotesElement slide
+    mbNotesIdNum <- do mp <- asks envSpeakerNotesIdMap
+                       return $ M.lookup idNum mp
+    case mbElement of
+      Just element | Just notesIdNum <- mbNotesIdNum ->
+                       Just <$>
+                       elemToEntry
+                       ("ppt/notesSlides/notesSlide" <> show notesIdNum <>
+                        ".xml")
+                       element
+      _ -> return Nothing
+
+slideToSpeakerNotesRelElement :: PandocMonad m => Slide -> P m (Maybe Element)
+slideToSpeakerNotesRelElement (Slide _ _ (SpeakerNotes []) _) = return Nothing
+slideToSpeakerNotesRelElement slide@Slide{} = do
+  idNum <- slideNum slide
+  return $ Just $
+    mknode "Relationships"
+    [("xmlns", "http://schemas.openxmlformats.org/package/2006/relationships")]
+    [ mknode "Relationship" [ ("Id", "rId2")
+                            , ("Type", "http://schemas.openxmlformats.org/officeDocument/2006/relationships/slide")
+                            , ("Target", "../slides/slide" <> tshow idNum <> ".xml")
+                            ] ()
+    , mknode "Relationship" [ ("Id", "rId1")
+                            , ("Type", "http://schemas.openxmlformats.org/officeDocument/2006/relationships/notesMaster")
+                            , ("Target", "../notesMasters/notesMaster1.xml")
+                            ] ()
+    ]
+
+
+slideToSpeakerNotesRelEntry :: PandocMonad m => Slide -> P m (Maybe Entry)
+slideToSpeakerNotesRelEntry slide = do
+  idNum <- slideNum slide
+  mbElement <- slideToSpeakerNotesRelElement slide
+  mp <- asks envSpeakerNotesIdMap
+  let mbNotesIdNum = M.lookup idNum mp
+  case mbElement of
+    Just element | Just notesIdNum <- mbNotesIdNum ->
+      Just <$>
+      elemToEntry
+      ("ppt/notesSlides/_rels/notesSlide" <> show notesIdNum <> ".xml.rels")
+      element
+    _ -> return Nothing
+
+slideToSlideRelEntry :: PandocMonad m => Slide -> P m Entry
+slideToSlideRelEntry slide = do
+  idNum <- slideNum slide
+  element <- slideToSlideRelElement slide
+  elemToEntry ("ppt/slides/_rels/" <> idNumToFilePath idNum <> ".rels") element
+
+linkRelElement :: PandocMonad m => (Int, LinkTarget) -> P m Element
+linkRelElement (rIdNum, InternalTarget targetId) = do
+  targetIdNum <- getSlideIdNum targetId
+  return $
+    mknode "Relationship" [ ("Id", "rId" <> tshow rIdNum)
+                          , ("Type", "http://schemas.openxmlformats.org/officeDocument/2006/relationships/slide")
+                          , ("Target", "slide" <> tshow targetIdNum <> ".xml")
+                          ] ()
+linkRelElement (rIdNum, ExternalTarget (url, _)) =
+  return $
+    mknode "Relationship" [ ("Id", "rId" <> tshow rIdNum)
+                          , ("Type", "http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink")
+                          , ("Target", url)
+                          , ("TargetMode", "External")
+                          ] ()
+
+linkRelElements :: PandocMonad m => M.Map Int LinkTarget -> P m [Element]
+linkRelElements mp = mapM linkRelElement (M.toList mp)
+
+mediaRelElement :: MediaInfo -> Element
+mediaRelElement mInfo =
+  let ext = fromMaybe "" (mInfoExt mInfo)
+  in
+    mknode "Relationship" [ ("Id", "rId" <>
+      tshow (mInfoLocalId mInfo))
+                          , ("Type", "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image")
+                          , ("Target", "../media/image" <>
+      tshow (mInfoGlobalId mInfo) <> ext)
+                          ] ()
+
+speakerNotesSlideRelElement :: PandocMonad m => Slide -> P m (Maybe Element)
+speakerNotesSlideRelElement slide = do
+  idNum <- slideNum slide
+  mp <- asks envSpeakerNotesIdMap
+  return $ case M.lookup idNum mp of
+    Nothing -> Nothing
+    Just n ->
+      let target = "../notesSlides/notesSlide" <> tshow n <> ".xml"
+      in Just $
+         mknode "Relationship" [ ("Id", "rId2")
+                               , ("Type", "http://schemas.openxmlformats.org/officeDocument/2006/relationships/notesSlide")
+                               , ("Target", target)
+                               ] ()
+
+slideToSlideRelElement :: PandocMonad m => Slide -> P m Element
+slideToSlideRelElement slide = do
+  idNum <- slideNum slide
+  target <- flip fmap getSlideLayouts $
+    T.pack . ("../slideLayouts/" <>) . takeFileName .
+    slPath . case slide of
+        (Slide _ MetadataSlide{} _ _)           -> metadata
+        (Slide _ TitleSlide{} _ _)              -> title
+        (Slide _ ContentSlide{} _ _)            -> content
+        (Slide _ TwoColumnSlide{} _ _)          -> twoColumn
+        (Slide _ ComparisonSlide{} _ _)         -> comparison
+        (Slide _ ContentWithCaptionSlide{} _ _) -> contentWithCaption
+        (Slide _ BlankSlide _ _)                -> blank
+
+  speakerNotesRels <- maybeToList <$> speakerNotesSlideRelElement slide
+
+  linkIds <- gets stLinkIds
+  mediaIds <- gets stMediaIds
+
+  linkRels <- case M.lookup idNum linkIds of
+                Just mp -> linkRelElements mp
+                Nothing -> return []
+  let mediaRels = case M.lookup idNum mediaIds of
+                   Just mInfos -> map mediaRelElement mInfos
+                   Nothing -> []
+
+  return $
+    mknode "Relationships"
+    [("xmlns", "http://schemas.openxmlformats.org/package/2006/relationships")]
+    ([mknode "Relationship" [ ("Id", "rId1")
+                           , ("Type", "http://schemas.openxmlformats.org/officeDocument/2006/relationships/slideLayout")
+                           , ("Target", target)] ()
+    ] <> speakerNotesRels <> linkRels <> mediaRels)
+
+slideToSldIdElement ::
+  PandocMonad m =>
+  MinimumRId ->
+  Slide ->
+  P m Element
+slideToSldIdElement minimumSlideRId slide = do
+  n <- slideNum slide
+  let id' = tshow $ n + 255
+  rId <- slideToRelId minimumSlideRId slide
+  return $ mknode "p:sldId" [("id", id'), ("r:id", rId)] ()
+
+presentationToSldIdLst ::
+  PandocMonad m =>
+  MinimumRId ->
+  Presentation ->
+  P m Element
+presentationToSldIdLst minimumSlideRId (Presentation _ slides) = do
+  ids <- mapM (slideToSldIdElement minimumSlideRId) slides
+  return $ mkNodeSldIdLst ids
+
+mkNodeSldIdLst :: [Element] -> Element
+mkNodeSldIdLst = mknode "p:sldIdLst" []
+
+presentationToPresentationElement ::
+  PandocMonad m =>
+  PresentationRIdUpdateData ->
+  Presentation ->
+  P m Element
+presentationToPresentationElement presentationUpdateRIdData pres = do
+  let (_, (minSlideRId, maxSlideRId)) = presentationUpdateRIdData
+  refArchive <- asks envRefArchive
+  distArchive <- asks envDistArchive
+  element <- parseXml refArchive distArchive "ppt/presentation.xml"
+  sldIdLst <- presentationToSldIdLst minSlideRId pres
+
+  let modifySldIdLst :: Content -> Content
+      modifySldIdLst ct = if isSldIdLst ct
+                          then Elem sldIdLst
+                          else ct
+
+      notesMasterRId = maxSlideRId
+
+      notesMasterElem =  mknode "p:notesMasterIdLst" []
+                         [ mknode
+                           "p:notesMasterId"
+                           [("r:id", "rId" <> tshow notesMasterRId)]
+                           ()
+                         ]
+
+      -- if there's a notesMasterIdLst in the presentation.xml file,
+      -- we want to remove it. We then want to put our own, if
+      -- necessary, after the slideMasterIdLst element. We also remove
+      -- handouts master, since we don't want it.
+
+      removeUnwantedMaster' :: Content -> [Content]
+      removeUnwantedMaster' (Elem e) = case elName e of
+        (QName "notesMasterIdLst" _ _) -> []
+        (QName "handoutMasterIdLst" _ _) -> []
+        _                              -> [Elem e]
+      removeUnwantedMaster' ct = [ct]
+
+      removeUnwantedMaster :: [Content] -> [Content]
+      removeUnwantedMaster = concatMap removeUnwantedMaster'
+
+      insertNotesMaster :: [Content] -> [Content]
+      insertNotesMaster = if presHasSpeakerNotes pres
+                          then insertAfterSldMasterIdLst notesMasterElem
+                          else id
+
+      updateRIds :: Content -> Content
+      updateRIds (Elem el) =
+        Elem (el { elAttribs = fmap updateRIdAttribute (elAttribs el)
+                 , elContent = fmap updateRIds (elContent el)
+                 })
+      updateRIds content = content
+
+      updateRIdAttribute :: XML.Attr -> XML.Attr
+      updateRIdAttribute attr = fromMaybe attr $ do
+        oldValue <- case attrKey attr of
+          QName "id" _ (Just "r") ->
+            T.stripPrefix "rId" (attrVal attr)
+            >>= fmap fromIntegral . readTextAsInteger
+          _ -> Nothing
+        let newValue = updatePresentationRId presentationUpdateRIdData oldValue
+        pure attr {attrVal = "rId" <> T.pack (show newValue)}
+
+      -- if there is no sldIdLst in the presentation.xml file, add an empty one
+      -- after the sldMasterIdLst so modifySldIdLst can replace it.
+
+      insertSldIdListIfMissing :: [Content] -> [Content]
+      insertSldIdListIfMissing contentList = if any isSldIdLst contentList
+                                             then contentList
+                                             else insertAfterSldMasterIdLst (mkNodeSldIdLst []) contentList
+
+      insertAfterSldMasterIdLst' :: Content -> Content -> [Content]
+      insertAfterSldMasterIdLst' newElement ct = if isElemName "sldMasterIdLst" ct
+                                                 then [ct, newElement]
+                                                 else [ct]
+
+      insertAfterSldMasterIdLst :: Element -> [Content] -> [Content]
+      insertAfterSldMasterIdLst newElement = concatMap $ insertAfterSldMasterIdLst' $ Elem newElement
+
+      isElemName :: T.Text -> Content -> Bool
+      isElemName name (Elem e) = qName (elName e) == name
+      isElemName _ _ = False
+
+      isSldIdLst :: Content -> Bool
+      isSldIdLst = isElemName "sldIdLst"
+
+      newContent = insertNotesMaster $
+                   removeUnwantedMaster $
+                   (modifySldIdLst . updateRIds) <$>
+                   insertSldIdListIfMissing (elContent element)
+
+  return $ element{elContent = newContent}
+
+presentationToPresEntry :: PandocMonad m => PresentationRIdUpdateData -> Presentation -> P m Entry
+presentationToPresEntry presentationRIdUpdateData pres =
+  presentationToPresentationElement presentationRIdUpdateData pres >>=
+    elemToEntry "ppt/presentation.xml"
+
+-- adapted from the Docx writer
+docPropsElement :: PandocMonad m => DocProps -> P m Element
+docPropsElement docProps = do
+  utctime <- asks envUTCTime
+  let keywords = case dcKeywords docProps of
+        Just xs -> T.intercalate ", " xs
+        Nothing -> ""
+  return $
+    mknode "cp:coreProperties"
+    [("xmlns:cp","http://schemas.openxmlformats.org/package/2006/metadata/core-properties")
+    ,("xmlns:dc","http://purl.org/dc/elements/1.1/")
+    ,("xmlns:dcterms","http://purl.org/dc/terms/")
+    ,("xmlns:dcmitype","http://purl.org/dc/dcmitype/")
+    ,("xmlns:xsi","http://www.w3.org/2001/XMLSchema-instance")]
+    $
+      mknode "dc:title" [] (fromMaybe "" $ dcTitle docProps)
+    :
+      mknode "dc:creator" [] (fromMaybe "" $ dcCreator docProps)
+    :
+      mknode "cp:keywords" [] keywords
+    : ( [mknode "dc:subject" [] $ fromMaybe "" $ dcSubject docProps | isJust (dcSubject docProps)])
+    <> ( [mknode "dc:description" [] $ fromMaybe "" $ dcDescription docProps | isJust (dcDescription docProps)])
+    <> ( [mknode "cp:category" [] $ fromMaybe "" $ cpCategory docProps | isJust (cpCategory docProps)])
+    <> (\x -> [ mknode "dcterms:created" [("xsi:type","dcterms:W3CDTF")] x
+              , mknode "dcterms:modified" [("xsi:type","dcterms:W3CDTF")] x
+              ]) (T.pack $ formatTime defaultTimeLocale "%FT%XZ" utctime)
+
+docPropsToEntry :: PandocMonad m => DocProps -> P m Entry
+docPropsToEntry docProps = docPropsElement docProps >>=
+                           elemToEntry "docProps/core.xml"
+
+-- adapted from the Docx writer
+docCustomPropsElement :: PandocMonad m => DocProps -> P m Element
+docCustomPropsElement docProps = do
+  let mkCustomProp (k, v) pid = mknode "property"
+         [("fmtid","{D5CDD505-2E9C-101B-9397-08002B2CF9AE}")
+         ,("pid", tshow pid)
+         ,("name", k)] $ mknode "vt:lpwstr" [] v
+  return $ mknode "Properties"
+          [("xmlns","http://schemas.openxmlformats.org/officeDocument/2006/custom-properties")
+          ,("xmlns:vt","http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes")
+          ] $ zipWith mkCustomProp (fromMaybe [] $ customProperties docProps) [(2 :: Int)..]
+
+docCustomPropsToEntry :: PandocMonad m => DocProps -> P m Entry
+docCustomPropsToEntry docProps = docCustomPropsElement docProps >>=
+                           elemToEntry "docProps/custom.xml"
+
+-- We read from the template, but we remove the lastView, so it always
+-- opens on slide view. Templates will sometimes be open in master
+-- view for editing.
+viewPropsElement :: PandocMonad m => P m Element
+viewPropsElement = do
+  refArchive <- asks envRefArchive
+  distArchive <- asks envDistArchive
+  viewPrElement <- parseXml refArchive distArchive "ppt/viewProps.xml"
+  -- remove  "lastView" if it exists:
+  let notLastView :: XML.Attr -> Bool
+      notLastView attr =
+          qName (attrKey attr) /= "lastView"
+  return $
+    viewPrElement {elAttribs = filter notLastView (elAttribs viewPrElement)}
+
+makeViewPropsEntry :: PandocMonad m => P m Entry
+makeViewPropsEntry = viewPropsElement >>= elemToEntry "ppt/viewProps.xml"
+
+defaultContentTypeToElem :: DefaultContentType -> Element
+defaultContentTypeToElem dct =
+  mknode "Default"
+  [("Extension", defContentTypesExt dct),
+    ("ContentType", defContentTypesType dct)]
+  ()
+
+overrideContentTypeToElem :: OverrideContentType -> Element
+overrideContentTypeToElem oct =
+  mknode "Override"
+  [("PartName", T.pack $ overrideContentTypesPart oct),
+   ("ContentType", overrideContentTypesType oct)]
+  ()
+
+contentTypesToElement :: ContentTypes -> Element
+contentTypesToElement ct =
+  let ns = "http://schemas.openxmlformats.org/package/2006/content-types"
+  in
+    mknode "Types" [("xmlns", ns)] $
+
+      map defaultContentTypeToElem (contentTypesDefaults ct) <>
+      map overrideContentTypeToElem (contentTypesOverrides ct)
+
+data DefaultContentType = DefaultContentType
+                           { defContentTypesExt :: T.Text
+                           , defContentTypesType:: MimeType
+                           }
+                         deriving (Show, Eq)
+
+data OverrideContentType = OverrideContentType
+                           { overrideContentTypesPart :: FilePath
+                           , overrideContentTypesType :: MimeType
+                           }
+                          deriving (Show, Eq)
+
+data ContentTypes = ContentTypes { contentTypesDefaults :: [DefaultContentType]
+                                 , contentTypesOverrides :: [OverrideContentType]
+                                 }
+                    deriving (Show, Eq)
+
+contentTypesToEntry :: PandocMonad m => ContentTypes -> P m Entry
+contentTypesToEntry ct = elemToEntry "[Content_Types].xml" $ contentTypesToElement ct
+
+pathToOverride :: FilePath -> Maybe OverrideContentType
+pathToOverride fp = OverrideContentType ("/" <> fp) <$> getContentType fp
+
+mediaFileContentType :: FilePath -> Maybe DefaultContentType
+mediaFileContentType fp = case takeExtension fp of
+  '.' : ext -> Just $
+               DefaultContentType { defContentTypesExt = T.pack ext
+                                  , defContentTypesType =
+                                      fromMaybe "application/octet-stream" (getMimeType fp)
+                                  }
+  _ -> Nothing
+
+mediaContentType :: MediaInfo -> Maybe DefaultContentType
+mediaContentType mInfo
+  | Just t <- mInfoExt mInfo
+  , Just ('.', ext) <- T.uncons t =
+      Just $ DefaultContentType { defContentTypesExt = ext
+                                , defContentTypesType =
+                                    fromMaybe "application/octet-stream" (mInfoMimeType mInfo)
+                                }
+  | otherwise = Nothing
+
+getSpeakerNotesFilePaths :: PandocMonad m => P m [FilePath]
+getSpeakerNotesFilePaths = do
+  mp <- asks envSpeakerNotesIdMap
+  let notesIdNums = M.elems mp
+  return $ map (\n -> "ppt/notesSlides/notesSlide" <> show n <> ".xml")
+               notesIdNums
+
+presentationToContentTypes :: PandocMonad m => Presentation -> P m ContentTypes
+presentationToContentTypes p@(Presentation _ slides) = do
+  mediaInfos <- mconcat . M.elems <$> gets stMediaIds
+  filePaths <- patternsToFilePaths $ inheritedPatterns p
+  let mediaFps = filter (match (compile "ppt/media/image*")) filePaths
+      fontFps = filter (match (compile "ppt/fonts/*")) filePaths
+  let defaults = [ DefaultContentType "xml" "application/xml"
+                 , DefaultContentType "rels" "application/vnd.openxmlformats-package.relationships+xml"
+                 ]
+      mediaDefaults = nub $
+                      mapMaybe mediaContentType mediaInfos <>
+                      mapMaybe mediaFileContentType mediaFps
+      fontDefaults = [ DefaultContentType "fntdata" "application/x-fontdata"
+                     | any (\fp -> takeExtension fp == ".fntdata") fontFps
+                     ]
+
+      inheritedOverrides = mapMaybe pathToOverride filePaths
+      createdOverrides = mapMaybe pathToOverride [ "docProps/core.xml"
+                                                 , "docProps/custom.xml"
+                                                 , "ppt/presentation.xml"
+                                                 , "ppt/viewProps.xml"
+                                                 ]
+  relativePaths <- mapM slideToFilePath slides
+  let slideOverrides = mapMaybe
+                       (\fp -> pathToOverride $ "ppt/slides/" <> fp)
+                       relativePaths
+  speakerNotesOverrides <- mapMaybe pathToOverride <$> getSpeakerNotesFilePaths
+  return $ ContentTypes
+    (defaults <> mediaDefaults <> fontDefaults)
+    (inheritedOverrides <> createdOverrides <> slideOverrides <> speakerNotesOverrides)
+
+presML :: T.Text
+presML = "application/vnd.openxmlformats-officedocument.presentationml"
+
+noPresML :: T.Text
+noPresML = "application/vnd.openxmlformats-officedocument"
+
+getContentType :: FilePath -> Maybe MimeType
+getContentType fp
+  | fp == "ppt/presentation.xml" = Just $ presML <> ".presentation.main+xml"
+  | fp == "ppt/presProps.xml" = Just $ presML <> ".presProps+xml"
+  | fp == "ppt/viewProps.xml" = Just $ presML <> ".viewProps+xml"
+  | fp == "ppt/tableStyles.xml" = Just $ presML <> ".tableStyles+xml"
+  | fp == "docProps/core.xml" = Just "application/vnd.openxmlformats-package.core-properties+xml"
+  | fp == "docProps/custom.xml" = Just "application/vnd.openxmlformats-officedocument.custom-properties+xml"
+  | fp == "docProps/app.xml" = Just $ noPresML <> ".extended-properties+xml"
+  | ["ppt", "slideMasters", f] <- splitDirectories fp
+  , (_, ".xml") <- splitExtension f =
+      Just $ presML <> ".slideMaster+xml"
+  | ["ppt", "slides", f] <- splitDirectories fp
+  , (_, ".xml") <- splitExtension f =
+      Just $ presML <> ".slide+xml"
+  | ["ppt", "notesMasters", f] <- splitDirectories fp
+  , (_, ".xml") <- splitExtension f =
+      Just $ presML <> ".notesMaster+xml"
+  | ["ppt", "notesSlides", f] <- splitDirectories fp
+  , (_, ".xml") <- splitExtension f =
+      Just $ presML <> ".notesSlide+xml"
+  | ["ppt", "theme", f] <- splitDirectories fp
+  , (_, ".xml") <- splitExtension f =
+      Just $ noPresML <> ".theme+xml"
+  | ["ppt", "slideLayouts", _] <- splitDirectories fp=
+      Just $ presML <> ".slideLayout+xml"
+  | otherwise = Nothing
+
+-- Kept as String for XML.Light
+autoNumAttrs :: ListAttributes -> [(Text, Text)]
+autoNumAttrs (startNum, numStyle, numDelim) =
+  numAttr <> typeAttr
+  where
+    numAttr = [("startAt", tshow startNum) | startNum /= 1]
+    typeAttr = [("type", typeString <> delimString)]
+    typeString = case numStyle of
+      Decimal -> "arabic"
+      UpperAlpha -> "alphaUc"
+      LowerAlpha -> "alphaLc"
+      UpperRoman -> "romanUc"
+      LowerRoman -> "romanLc"
+      _          -> "arabic"
+    delimString = case numDelim of
+      Period -> "Period"
+      OneParen -> "ParenR"
+      TwoParens -> "ParenBoth"
+      _         -> "Period"
+
+-- | The XML required to insert an "appear" animation for each of the given
+-- groups of paragraphs, identified by index.
+incrementalAnimation ::
+  -- | (ShapeId, [(startParagraphIndex, endParagraphIndex)])
+  NonEmpty (ShapeId, NonEmpty (Integer, Integer)) ->
+  Element
+incrementalAnimation indices = mknode "p:timing" [] [tnLst, bldLst]
+  where
+    triples :: NonEmpty (ShapeId, Integer, Integer)
+    triples = do
+      (shapeId, paragraphIds) <- indices
+      (start, end) <- paragraphIds
+      pure (shapeId, start, end)
+
+    tnLst = mknode "p:tnLst" []
+      $ mknode "p:par" []
+      $ mknode "p:cTn" [ ("id", "1")
+                       , ("dur", "indefinite")
+                       , ("restart", "never")
+                       , ("nodeType", "tmRoot")
+                       ]
+      $ mknode "p:childTnLst" []
+      $ mknode "p:seq" [ ("concurrent", "1")
+                       , ("nextAc", "seek")
+                       ]
+      [ mknode "p:cTn" [ ("id", "2")
+                       , ("dur", "indefinite")
+                       , ("nodeType", "mainSeq")
+                       ]
+        $ mknode "p:childTnLst" []
+        $ zipWith makePar [3, 7 ..] (toList triples)
+      , mknode "p:prevCondLst" []
+        $ mknode "p:cond" ([("evt", "onPrev"), ("delay", "0")])
+        $ mknode "p:tgtEl" []
+        $ mknode "p:sldTgt" [] ()
+      , mknode "p:nextCondLst" []
+        $ mknode "p:cond" ([("evt", "onNext"), ("delay", "0")])
+        $ mknode "p:tgtEl" []
+        $ mknode "p:sldTgt" [] ()
+      ]
+    bldLst = mknode "p:bldLst" []
+      [ mknode "p:bldP" [ ("spid", T.pack (show shapeId))
+                        , ("grpId", "0")
+                        , ("uiExpand", "1")
+                        , ("build", "p")
+                        ]
+        () | (shapeId, _) <- toList indices
+      ]
+
+    makePar :: Integer -> (ShapeId, Integer, Integer) -> Element
+    makePar nextId (shapeId, start, end) =
+      mknode "p:par" []
+        $ mknode "p:cTn" [("id", T.pack (show nextId)), ("fill", "hold")]
+        [ mknode "p:stCondLst" []
+          $ mknode "p:cond" [("delay", "indefinite")] ()
+        , mknode "p:childTnLst" []
+          $ mknode "p:par" []
+          $ mknode "p:cTn" [ ("id", T.pack (show (nextId + 1)))
+                           , ("fill", "hold")
+                           ]
+          [ mknode "p:stCondLst" []
+            $ mknode "p:cond" [("delay", "0")] ()
+          , mknode "p:childTnLst" []
+            $ mknode "p:par" []
+            $ mknode "p:cTn" [ ("id", T.pack (show (nextId + 2)))
+                             , ("presetID", "1")
+                             , ("presetClass", "entr")
+                             , ("presetSubtype", "0")
+                             , ("fill", "hold")
+                             , ("grpId", "0")
+                             , ("nodeType", "clickEffect")
+                             ]
+            [ mknode "p:stCondLst" []
+              $ mknode "p:cond" [("delay", "0")] ()
+            , mknode "p:childTnLst" []
+              $ mknode "p:set" []
+              [ mknode "p:cBhvr" []
+                [ mknode "p:cTn" [ ("id", T.pack (show (nextId + 3)))
+                                 , ("dur", "1")
+                                 , ("fill", "hold")
+                                 ]
+                  $ mknode "p:stCondLst" []
+                  $ mknode "p:cond" [("delay", "0")] ()
+                , mknode "p:tgtEl" []
+                  $ mknode "p:spTgt" [("spid", T.pack (show shapeId))]
+                  $ mknode "p:txEl" []
+                  $ mknode "p:pRg" [ ("st", T.pack (show start))
+                                   , ("end", T.pack (show end))]
+                    ()
+                , mknode "p:attrNameLst" []
+                  $ mknode "p:attrName" [] ("style.visibility" :: Text)
+                ]
+              , mknode "p:to" []
+                $ mknode "p:strVal" [("val", "visible")] ()
+              ]
+            ]
+          ]
+        ]
diff --git a/src/Text/Pandoc/Writers/Powerpoint/Presentation.hs b/src/Text/Pandoc/Writers/Powerpoint/Presentation.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Writers/Powerpoint/Presentation.hs
@@ -0,0 +1,1222 @@
+{-# LANGUAGE GeneralizedNewtypeDeriving #-}
+{-# LANGUAGE LambdaCase                 #-}
+{-# LANGUAGE MultiWayIf                 #-}
+{-# LANGUAGE OverloadedStrings          #-}
+{-# LANGUAGE PatternGuards              #-}
+{-# LANGUAGE ViewPatterns               #-}
+{- |
+   Module      : Text.Pandoc.Writers.Powerpoint.Presentation
+   Copyright   : Copyright (C) 2017-2020 Jesse Rosenthal
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : Jesse Rosenthal <jrosenthal@jhu.edu>
+   Stability   : alpha
+   Portability : portable
+
+Definition of Presentation datatype, modeling a MS Powerpoint (pptx)
+document, and functions for converting a Pandoc document to
+Presentation.
+-}
+
+module Text.Pandoc.Writers.Powerpoint.Presentation ( documentToPresentation
+                                                   , Presentation(..)
+                                                   , DocProps(..)
+                                                   , Slide(..)
+                                                   , Layout(..)
+                                                   , SpeakerNotes(..)
+                                                   , SlideId(..)
+                                                   , Shape(..)
+                                                   , Graphic(..)
+                                                   , BulletType(..)
+                                                   , Algnment(..)
+                                                   , Paragraph(..)
+                                                   , ParaElem(..)
+                                                   , ParaProps(..)
+                                                   , RunProps(..)
+                                                   , TableProps(..)
+                                                   , Strikethrough(..)
+                                                   , Capitals(..)
+                                                   , Pixels
+                                                   , PicProps(..)
+                                                   , URL
+                                                   , TeXString(..)
+                                                   , LinkTarget(..)
+                                                   ) where
+
+import Control.Monad
+import Control.Monad.Reader
+import Control.Monad.State
+import Data.List (intercalate)
+import Data.List.NonEmpty (nonEmpty)
+import Data.Default
+import Text.Pandoc.Definition
+import Text.Pandoc.ImageSize
+import Text.Pandoc.Slides (getSlideLevel)
+import Text.Pandoc.Options
+import Text.Pandoc.Logging
+import Text.Pandoc.Walk
+import qualified Text.Pandoc.Shared as Shared -- so we don't overlap "Element"
+import Text.Pandoc.Shared (tshow)
+import Text.Pandoc.Writers.Shared (lookupMetaInlines, lookupMetaBlocks
+                                 , lookupMetaString, toTableOfContents
+                                 , toLegacyTable)
+import qualified Data.Map as M
+import qualified Data.Set as S
+import Data.Maybe (maybeToList, fromMaybe, listToMaybe, isNothing)
+import Text.Pandoc.Highlighting
+import qualified Data.Text as T
+import Control.Applicative ((<|>))
+import Skylighting
+import Data.Bifunctor (bimap)
+import Data.Char (isSpace)
+
+data WriterEnv = WriterEnv { envMetadata :: Meta
+                           , envRunProps :: RunProps
+                           , envParaProps :: ParaProps
+                           , envSlideLevel :: Int
+                           , envOpts :: WriterOptions
+                           , envSlideHasHeader :: Bool
+                           , envInList :: Bool
+                           , envInNoteSlide :: Bool
+                           , envCurSlideId :: SlideId
+                           , envInSpeakerNotes :: Bool
+                           , envInIncrementalDiv :: Maybe InIncrementalDiv
+                           , envInListInBlockQuote :: Bool
+                           }
+                 deriving (Show)
+
+instance Default WriterEnv where
+  def = WriterEnv { envMetadata = mempty
+                  , envRunProps = def
+                  , envParaProps = def
+                  , envSlideLevel = 2
+                  , envOpts = def
+                  , envSlideHasHeader = False
+                  , envInList = False
+                  , envInNoteSlide = False
+                  , envCurSlideId = SlideId "Default"
+                  , envInSpeakerNotes = False
+                  , envInIncrementalDiv = Nothing
+                  , envInListInBlockQuote = False
+                  }
+
+
+data WriterState = WriterState { stNoteIds :: M.Map Int [Block]
+                               -- associate anchors with slide id
+                               , stAnchorMap :: M.Map T.Text SlideId
+                               , stSlideIdSet :: S.Set SlideId
+                               , stLog :: [LogMessage]
+                               , stSpeakerNotes :: SpeakerNotes
+                               } deriving (Show, Eq)
+
+instance Default WriterState where
+  def = WriterState { stNoteIds = mempty
+                    , stAnchorMap = mempty
+                    -- we reserve this s
+                    , stSlideIdSet = reservedSlideIds
+                    , stLog = []
+                    , stSpeakerNotes = mempty
+                    }
+
+data InIncrementalDiv
+  = InIncremental
+  -- ^ The current content is contained within an "incremental" div.
+  | InNonIncremental
+  -- ^ The current content is contained within a "nonincremental" div.
+  deriving (Show)
+
+listShouldBeIncremental :: Pres Bool
+listShouldBeIncremental = do
+  incrementalOption <- asks (writerIncremental . envOpts)
+  inIncrementalDiv <- asks envInIncrementalDiv
+  inBlockQuote <- asks envInListInBlockQuote
+  let toBoolean = (\case InIncremental -> True
+                         InNonIncremental -> False)
+      maybeInvert = if inBlockQuote then not else id
+  pure (maybeInvert (maybe incrementalOption toBoolean inIncrementalDiv))
+
+metadataSlideId :: SlideId
+metadataSlideId = SlideId "Metadata"
+
+tocSlideId :: SlideId
+tocSlideId = SlideId "TOC"
+
+endNotesSlideId :: SlideId
+endNotesSlideId = SlideId "EndNotes"
+
+reservedSlideIds :: S.Set SlideId
+reservedSlideIds = S.fromList [ metadataSlideId
+                              , tocSlideId
+                              , endNotesSlideId
+                              ]
+
+uniqueSlideId' :: Integer -> S.Set SlideId -> T.Text -> SlideId
+uniqueSlideId' n idSet s =
+  let s' = if n == 0 then s else s <> "-" <> tshow n
+  in if SlideId s' `S.member` idSet
+     then uniqueSlideId' (n+1) idSet s
+     else SlideId s'
+
+uniqueSlideId :: S.Set SlideId -> T.Text -> SlideId
+uniqueSlideId = uniqueSlideId' 0
+
+runUniqueSlideId :: T.Text -> Pres SlideId
+runUniqueSlideId s = do
+  idSet <- gets stSlideIdSet
+  let sldId = uniqueSlideId idSet s
+  modify $ \st -> st{stSlideIdSet = S.insert sldId idSet}
+  return sldId
+
+addLogMessage :: LogMessage -> Pres ()
+addLogMessage msg = modify $ \st -> st{stLog = msg : stLog st}
+
+type Pres = ReaderT WriterEnv (State WriterState)
+
+runPres :: WriterEnv -> WriterState -> Pres a -> (a, [LogMessage])
+runPres env st p = (pres, reverse $ stLog finalSt)
+  where (pres, finalSt) = runState (runReaderT p env) st
+
+type Pixels = Integer
+
+data Presentation = Presentation DocProps [Slide]
+  deriving (Show)
+
+data DocProps = DocProps { dcTitle :: Maybe T.Text
+                         , dcSubject :: Maybe T.Text
+                         , dcCreator :: Maybe T.Text
+                         , dcKeywords :: Maybe [T.Text]
+                         , dcDescription :: Maybe T.Text
+                         , cpCategory :: Maybe T.Text
+                         , dcDate :: Maybe T.Text
+                         , customProperties :: Maybe [(T.Text, T.Text)]
+                         } deriving (Show, Eq)
+
+
+data Slide = Slide { slideId :: SlideId
+                   , slideLayout :: Layout
+                   , slideSpeakerNotes :: SpeakerNotes
+                   , slideBackgroundImage :: Maybe FilePath
+                   } deriving (Show, Eq)
+
+newtype SlideId = SlideId T.Text
+  deriving (Show, Eq, Ord)
+
+-- In theory you could have anything on a notes slide but it seems
+-- designed mainly for one textbox, so we'll just put in the contents
+-- of that textbox, to avoid other shapes that won't work as well.
+newtype SpeakerNotes = SpeakerNotes {fromSpeakerNotes :: [Paragraph]}
+  deriving (Show, Eq, Monoid, Semigroup)
+
+data Layout = MetadataSlide [ParaElem] [ParaElem] [[ParaElem]] [ParaElem]
+            --              title      subtitle   authors      date
+            | TitleSlide [ParaElem]
+            --           heading
+            | ContentSlide [ParaElem] [Shape]
+            --             heading    content
+            | TwoColumnSlide [ParaElem] [Shape] [Shape]
+            --               heading    left    right
+            | ComparisonSlide [ParaElem] ([Shape], [Shape]) ([Shape], [Shape])
+            --                heading  left@(text, content) right@(text, content)
+            | ContentWithCaptionSlide [ParaElem] [Shape] [Shape]
+            --                        heading     text    content
+            | BlankSlide
+            deriving (Show, Eq)
+
+data Shape = Pic PicProps FilePath T.Text [ParaElem]
+           --                      title  alt-text
+           | GraphicFrame [Graphic] [ParaElem]
+           | TextBox [Paragraph]
+           | RawOOXMLShape T.Text
+  deriving (Show, Eq)
+
+type TableCell = [Paragraph]
+
+-- TODO: remove when better handling of new
+-- tables is implemented
+type SimpleCell = [Block]
+
+data TableProps = TableProps { tblPrFirstRow :: Bool
+                             , tblPrBandRow :: Bool
+                             } deriving (Show, Eq)
+
+data Graphic = Tbl [Double] TableProps [TableCell] [[TableCell]]
+  deriving (Show, Eq)
+
+
+data Paragraph = Paragraph { paraProps :: ParaProps
+                           , paraElems :: [ParaElem]
+                           } deriving (Show, Eq)
+
+data BulletType = Bullet
+                | AutoNumbering ListAttributes
+  deriving (Show, Eq)
+
+data Algnment = AlgnLeft | AlgnRight | AlgnCenter
+  deriving (Show, Eq)
+
+data ParaProps = ParaProps { pPropMarginLeft :: Maybe Pixels
+                           , pPropMarginRight :: Maybe Pixels
+                           , pPropLevel :: Int
+                           , pPropBullet :: Maybe BulletType
+                           , pPropAlign :: Maybe Algnment
+                           , pPropSpaceBefore :: Maybe Pixels
+                           , pPropIndent :: Maybe Pixels
+                           , pPropIncremental :: Bool
+                           } deriving (Show, Eq)
+
+instance Default ParaProps where
+  def = ParaProps { pPropMarginLeft = Just 0
+                  , pPropMarginRight = Just 0
+                  , pPropLevel = 0
+                  , pPropBullet = Nothing
+                  , pPropAlign = Nothing
+                  , pPropSpaceBefore = Nothing
+                  , pPropIndent = Just 0
+                  , pPropIncremental = False
+                  }
+
+newtype TeXString = TeXString {unTeXString :: T.Text}
+  deriving (Eq, Show)
+
+data ParaElem = Break
+              | Run RunProps T.Text
+              -- It would be more elegant to have native TeXMath
+              -- Expressions here, but this allows us to use
+              -- `convertmath` from T.P.Writers.Math. Will perhaps
+              -- revisit in the future.
+              | MathElem MathType TeXString
+              | RawOOXMLParaElem T.Text
+              deriving (Show, Eq)
+
+data Strikethrough = NoStrike | SingleStrike | DoubleStrike
+  deriving (Show, Eq)
+
+data Capitals = NoCapitals | SmallCapitals | AllCapitals
+  deriving (Show, Eq)
+
+type URL = T.Text
+
+data LinkTarget = ExternalTarget (URL, T.Text)
+                | InternalTarget SlideId
+                deriving (Show, Eq)
+
+data RunProps = RunProps { rPropBold :: Bool
+                         , rPropItalics :: Bool
+                         , rStrikethrough :: Maybe Strikethrough
+                         , rBaseline :: Maybe Int
+                         , rCap :: Maybe Capitals
+                         , rLink :: Maybe LinkTarget
+                         , rPropCode :: Bool
+                         , rPropBlockQuote :: Bool
+                         , rPropForceSize :: Maybe Pixels
+                         , rSolidFill :: Maybe Color
+                         -- TODO: Make a full underline data type with
+                         -- the different options.
+                         , rPropUnderline :: Bool
+                         } deriving (Show, Eq)
+
+instance Default RunProps where
+  def = RunProps { rPropBold = False
+                 , rPropItalics = False
+                 , rStrikethrough = Nothing
+                 , rBaseline = Nothing
+                 , rCap = Nothing
+                 , rLink = Nothing
+                 , rPropCode = False
+                 , rPropBlockQuote = False
+                 , rPropForceSize = Nothing
+                 , rSolidFill = Nothing
+                 , rPropUnderline = False
+                 }
+
+data PicProps = PicProps { picPropLink :: Maybe LinkTarget
+                         , picWidth    :: Maybe Dimension
+                         , picHeight   :: Maybe Dimension
+                         } deriving (Show, Eq)
+
+instance Default PicProps where
+  def = PicProps { picPropLink = Nothing
+                 , picWidth = Nothing
+                 , picHeight = Nothing
+                 }
+
+--------------------------------------------------
+
+inlinesToParElems :: [Inline] -> Pres [ParaElem]
+inlinesToParElems = fmap mconcat . mapM inlineToParElems
+
+inlineToParElems :: Inline -> Pres [ParaElem]
+inlineToParElems (Str s) = do
+  pr <- asks envRunProps
+  return [Run pr s]
+inlineToParElems (Emph ils) =
+  local (\r -> r{envRunProps = (envRunProps r){rPropItalics=True}}) $
+  inlinesToParElems ils
+inlineToParElems (Underline ils) =
+  local (\r -> r{envRunProps = (envRunProps r){rPropUnderline=True}}) $
+  inlinesToParElems ils
+inlineToParElems (Strong ils) =
+  local (\r -> r{envRunProps = (envRunProps r){rPropBold=True}}) $
+  inlinesToParElems ils
+inlineToParElems (Strikeout ils) =
+  local (\r -> r{envRunProps = (envRunProps r){rStrikethrough=Just SingleStrike}}) $
+  inlinesToParElems ils
+inlineToParElems (Superscript ils) =
+  local (\r -> r{envRunProps = (envRunProps r){rBaseline=Just 30000}}) $
+  inlinesToParElems ils
+inlineToParElems (Subscript ils) =
+  local (\r -> r{envRunProps = (envRunProps r){rBaseline=Just (-25000)}}) $
+  inlinesToParElems ils
+inlineToParElems (SmallCaps ils) =
+  local (\r -> r{envRunProps = (envRunProps r){rCap = Just SmallCapitals}}) $
+  inlinesToParElems ils
+inlineToParElems Space = inlineToParElems (Str " ")
+inlineToParElems SoftBreak = inlineToParElems (Str " ")
+inlineToParElems LineBreak = return [Break]
+inlineToParElems (Link _ ils (url, title)) =
+  local (\r ->r{envRunProps = (envRunProps r){rLink = Just $ ExternalTarget (url, title)}}) $
+  inlinesToParElems ils
+inlineToParElems (Code _ str) =
+  local (\r ->r{envRunProps = (envRunProps r){rPropCode = True}}) $
+  inlineToParElems $ Str str
+inlineToParElems (Math mathtype str) =
+  return [MathElem mathtype (TeXString str)]
+-- We ignore notes if we're in a speaker notes div. Otherwise this
+-- would add an entry to the endnotes slide, which would put speaker
+-- notes in the public presentation. In the future, we can entertain a
+-- way of adding a speakernotes-specific note that would just add
+-- paragraphs to the bottom of the notes page.
+inlineToParElems (Note blks) = do
+  inSpNotes <- asks envInSpeakerNotes
+  if inSpNotes
+    then return []
+    else do
+    notes <- gets stNoteIds
+    let maxNoteId = maybe 0 maximum $ nonEmpty $ M.keys notes
+        curNoteId = maxNoteId + 1
+    modify $ \st -> st { stNoteIds = M.insert curNoteId blks notes }
+    local (\env -> env{envRunProps = (envRunProps env){rLink = Just $ InternalTarget endNotesSlideId}}) $
+      inlineToParElems $ Superscript [Str $ tshow curNoteId]
+inlineToParElems (Span _ ils) = inlinesToParElems ils
+inlineToParElems (Quoted quoteType ils) =
+  inlinesToParElems $ [Str open] ++ ils ++ [Str close]
+  where (open, close) = case quoteType of
+                          SingleQuote -> ("\x2018", "\x2019")
+                          DoubleQuote -> ("\x201C", "\x201D")
+inlineToParElems il@(RawInline fmt s) =
+  case fmt of
+    Format "openxml" -> return [RawOOXMLParaElem s]
+    _                -> do addLogMessage $ InlineNotRendered il
+                           return []
+inlineToParElems (Cite _ ils) = inlinesToParElems ils
+-- Note: we shouldn't reach this, because images should be handled at
+-- the shape level, but should that change in the future, we render
+-- the alt text.
+inlineToParElems (Image _ alt _) = inlinesToParElems alt
+
+
+
+isListType :: Block -> Bool
+isListType (OrderedList _ _) = True
+isListType (BulletList _) = True
+isListType (DefinitionList _) = True
+isListType _ = False
+
+registerAnchorId :: T.Text -> Pres ()
+registerAnchorId anchor = do
+  anchorMap <- gets stAnchorMap
+  sldId <- asks envCurSlideId
+  unless (T.null anchor) $
+    modify $ \st -> st {stAnchorMap = M.insert anchor sldId anchorMap}
+
+-- Currently hardcoded, until I figure out how to make it dynamic.
+blockQuoteSize :: Pixels
+blockQuoteSize = 20
+
+noteSize :: Pixels
+noteSize = 18
+
+blockToParagraphs :: Block -> Pres [Paragraph]
+blockToParagraphs (Plain ils) = blockToParagraphs (Para ils)
+blockToParagraphs (Para ils) = do
+  parElems <- inlinesToParElems ils
+  pProps <- asks envParaProps
+  return [Paragraph pProps parElems]
+blockToParagraphs (LineBlock ilsList) = do
+  parElems <- inlinesToParElems $ intercalate [LineBreak] ilsList
+  pProps <- asks envParaProps
+  return [Paragraph pProps parElems]
+-- TODO: work out the attributes
+blockToParagraphs (CodeBlock attr str) = do
+  pProps <- asks envParaProps
+  local (\r -> r{ envParaProps = def{ pPropMarginLeft = Nothing
+                                    , pPropBullet = Nothing
+                                    , pPropLevel = pPropLevel pProps
+                                    , pPropIndent = Just 0
+                                    }
+                , envRunProps = (envRunProps r){rPropCode = True}}) $ do
+    highlightOpt <- writerHighlightMethod <$> asks envOpts
+    synMap <- writerSyntaxMap <$> asks envOpts
+    let highlightWithStyle style = do
+          case highlight synMap (formatSourceLines style) attr str of
+            Right pElems -> do pPropsNew <- asks envParaProps
+                               return [Paragraph pPropsNew pElems]
+            Left _ -> blockToParagraphs $ Para [Str str]
+    case highlightOpt of
+      Skylighting sty -> highlightWithStyle sty
+      DefaultHighlighting -> highlightWithStyle defaultStyle
+      _ -> blockToParagraphs $ Para [Str str]
+-- We can't yet do incremental lists, but we should render a
+-- (BlockQuote List) as a list to maintain compatibility with other
+-- formats.
+blockToParagraphs (BlockQuote (blk : blks)) | isListType blk = do
+  ps  <- local (\env -> env { envInListInBlockQuote = True })
+           (blockToParagraphs blk)
+  ps' <- blockToParagraphs $ BlockQuote blks
+  return $ ps ++ ps'
+blockToParagraphs (BlockQuote blks) =
+  local (\r -> r{ envParaProps = (envParaProps r){ pPropMarginLeft = Just 100
+                                                 , pPropIndent = Just 0
+                                                 }
+                , envRunProps = (envRunProps r){rPropForceSize = Just blockQuoteSize}})$
+  mconcat <$> mapM blockToParagraphs blks
+-- TODO: work out the format
+blockToParagraphs blk@(RawBlock _ _) = do addLogMessage $ BlockNotRendered blk
+                                          return []
+blockToParagraphs (Header _ (ident, _, _) ils) = do
+  -- Note that this function only deals with content blocks, so it
+  -- will only touch headers that are above the current slide level --
+  -- slides at or below the slidelevel will be taken care of by
+  -- `blocksToSlide'`. We have the register anchors in both of them.
+  registerAnchorId ident
+  -- we set the subeader to bold
+  parElems <- local (\e->e{envRunProps = (envRunProps e){rPropBold=True}}) $
+              inlinesToParElems ils
+  -- and give it a bit of space before it.
+  return [Paragraph def{pPropSpaceBefore = Just 30} parElems]
+blockToParagraphs (BulletList blksLst) = do
+  pProps <- asks envParaProps
+  incremental <- listShouldBeIncremental
+  local (\env -> env{ envInList = True
+                    , envParaProps = pProps{ pPropBullet = Just Bullet
+                                           , pPropMarginLeft = Nothing
+                                           , pPropIndent = Nothing
+                                           , pPropIncremental = incremental
+                                           }}) $
+    mconcat <$> mapM multiParList blksLst
+blockToParagraphs (OrderedList listAttr blksLst) = do
+  pProps <- asks envParaProps
+  incremental <- listShouldBeIncremental
+  local (\env -> env{ envInList = True
+                    , envParaProps = pProps{ pPropBullet = Just (AutoNumbering listAttr)
+                                           , pPropMarginLeft = Nothing
+                                           , pPropIndent = Nothing
+                                           , pPropIncremental = incremental
+                                           }}) $
+    mconcat <$> mapM multiParList blksLst
+blockToParagraphs (DefinitionList entries) = do
+  incremental <- listShouldBeIncremental
+  let go :: ([Inline], [[Block]]) -> Pres [Paragraph]
+      go (ils, blksLst) = do
+        term <-blockToParagraphs $ Para [Strong ils]
+        -- For now, we'll treat each definition term as a
+        -- blockquote. We can extend this further later.
+        definition <-
+          mconcat <$> mapM (blockToParagraphs . BlockQuote) blksLst
+        return $ term ++ definition
+  local (\env -> env {envParaProps =
+                       (envParaProps env) {pPropIncremental = incremental}})
+    $ mconcat <$> mapM go entries
+blockToParagraphs (Div (_, classes, _) blks) = let
+  hasIncremental = "incremental" `elem` classes
+  hasNonIncremental = "nonincremental" `elem` classes
+  incremental = if | hasIncremental -> Just InIncremental
+                   | hasNonIncremental -> Just InNonIncremental
+                   | otherwise -> Nothing
+  addIncremental env = env { envInIncrementalDiv = incremental }
+  in local addIncremental (mconcat <$> mapM blockToParagraphs blks)
+blockToParagraphs (Figure attr capt blks) = -- This never seems to be used:
+  blockToParagraphs (Shared.figureDiv attr capt blks)
+blockToParagraphs hr@HorizontalRule = notRendered hr
+blockToParagraphs tbl@Table{} = notRendered tbl
+
+-- | Report that a block cannot be rendered.
+notRendered :: Block -> Pres [Paragraph]
+notRendered blk = do
+  addLogMessage $ BlockNotRendered blk
+  return []
+
+-- | Make sure the bullet env gets turned off after the first para.
+multiParList :: [Block] -> Pres [Paragraph]
+multiParList [] = return []
+multiParList (b:bs) = do
+  pProps <- asks envParaProps
+  p <- blockToParagraphs b
+  let level = pPropLevel pProps
+  ps <- local (\env -> env
+                { envParaProps = pProps
+                  { pPropBullet = Nothing
+                  , pPropLevel = level + 1
+                  }
+                })
+        $ mconcat <$> mapM blockToParagraphs bs
+  return $ p ++ ps
+
+cellToParagraphs :: Alignment -> SimpleCell -> Pres [Paragraph]
+cellToParagraphs algn tblCell = do
+  paras <- mapM blockToParagraphs tblCell
+  let alignment = case algn of
+        AlignLeft -> Just AlgnLeft
+        AlignRight -> Just AlgnRight
+        AlignCenter -> Just AlgnCenter
+        AlignDefault -> Nothing
+      paras' = map (map (\p -> p{paraProps = (paraProps p){pPropAlign = alignment}})) paras
+  return $ concat paras'
+
+rowToParagraphs :: [Alignment] -> [SimpleCell] -> Pres [[Paragraph]]
+rowToParagraphs algns tblCells = do
+  -- We have to make sure we have the right number of alignments
+  let pairs = zip (algns ++ repeat AlignDefault) tblCells
+  mapM (uncurry cellToParagraphs) pairs
+
+withAttr :: Attr -> Shape -> Shape
+withAttr attr (Pic picPr url title caption) =
+  let picPr' = picPr { picWidth = dimension Width attr
+                     , picHeight = dimension Height attr
+                     }
+  in
+    Pic picPr' url title caption
+withAttr _ sp = sp
+
+blockToShape :: Block -> Pres Shape
+blockToShape (Plain ils) = blockToShape (Para ils)
+blockToShape (Para (il:_))  | Image attr ils (url, title) <- il =
+      withAttr attr . Pic def (T.unpack url) title <$> inlinesToParElems ils
+blockToShape (Para (il:_))  | Link _ (il':_) target <- il
+                            , Image attr ils (url, title) <- il' =
+      withAttr attr .
+      Pic def{picPropLink = Just $ ExternalTarget target} (T.unpack url) title
+      <$> inlinesToParElems ils
+blockToShape (Figure _figattr _caption [b]) = blockToShape b
+blockToShape (Table _ blkCapt specs thead tbody tfoot) = do
+  let (caption, algn, widths, hdrCells, rows) = toLegacyTable blkCapt specs thead tbody tfoot
+  caption' <- inlinesToParElems caption
+  hdrCells' <- rowToParagraphs algn hdrCells
+  rows' <- mapM (rowToParagraphs algn) rows
+  let tblPr = if null hdrCells
+              then TableProps { tblPrFirstRow = False
+                              , tblPrBandRow = True
+                              }
+              else TableProps { tblPrFirstRow = True
+                              , tblPrBandRow = True
+                              }
+
+  return $ GraphicFrame [Tbl widths tblPr hdrCells' rows'] caption'
+-- If the format isn't openxml, we fall through to blockToPargraphs
+blockToShape (RawBlock (Format "openxml") str) = return $ RawOOXMLShape str
+blockToShape blk = do paras <- blockToParagraphs blk
+                      let paras' = map (\par -> par{paraElems = combineParaElems $ paraElems par}) paras
+                      return $ TextBox paras'
+
+combineShapes :: [Shape] -> [Shape]
+combineShapes [] = []
+combineShapes (pic@Pic{} : ss) = pic : combineShapes ss
+combineShapes (TextBox [] : ss) = combineShapes ss
+combineShapes (s : TextBox [] : ss) = combineShapes (s : ss)
+combineShapes (TextBox (p:ps) : TextBox (p':ps') : ss) =
+  combineShapes $ TextBox ((p:ps) ++ (p':ps')) : ss
+combineShapes (s:ss) = s : combineShapes ss
+
+isNotesDiv :: Block -> Bool
+isNotesDiv (Div (_, ["notes"], _) _) = True
+isNotesDiv _ = False
+
+blocksToShapes :: [Block] -> Pres [Shape]
+blocksToShapes blks = combineShapes <$> mapM blockToShape blks
+
+isImage :: Inline -> Bool
+isImage Image{} = True
+isImage (Link _ (Image{} : _) _) = True
+isImage _ = False
+
+plainOrPara :: Block -> Maybe [Inline]
+plainOrPara (Plain ils) = Just ils
+plainOrPara (Para ils) = Just ils
+plainOrPara _ = Nothing
+
+notText :: Block -> Bool
+notText block | startsWithImage block = True
+notText Table{} = True
+notText Figure{} = True
+notText _ = False
+
+startsWithImage :: Block -> Bool
+startsWithImage block = fromMaybe False $ do
+  inline <- plainOrPara block >>= listToMaybe
+  pure (isImage inline)
+
+-- | Group blocks into a number of "splits"
+splitBlocks' ::
+  -- | Blocks so far in the current split
+  [Block] ->
+  -- | Splits so far
+  [[Block]] ->
+  -- | All remaining blocks
+  [Block] ->
+  Pres [[Block]]
+splitBlocks' cur acc [] = return $ acc ++ ([cur | not (null cur)])
+splitBlocks' cur acc (HorizontalRule : blks) =
+  splitBlocks' [] (acc ++ ([cur | not (null cur)])) blks
+splitBlocks' cur acc (h@(Header n _ _) : blks) = do
+  slideLevel <- asks envSlideLevel
+  let (nts, blks') = span isNotesDiv blks
+  case compare n slideLevel of
+    LT -> splitBlocks' [] (acc ++ ([cur | not (null cur)]) ++ [h : nts]) blks'
+    EQ -> splitBlocks' (h:nts) (acc ++ ([cur | not (null cur)])) blks'
+    GT -> splitBlocks' (cur ++ (h:nts)) acc blks'
+-- `blockToParagraphs` treats Plain and Para the same, so we can save
+-- some code duplication by treating them the same here.
+splitBlocks' cur acc (Plain ils : blks) = splitBlocks' cur acc (Para ils : blks)
+splitBlocks' cur acc (Para (il:ils) : blks) | isImage il = do
+  slideLevel <- asks envSlideLevel
+  let (nts, blks') = if null ils
+                     then span isNotesDiv blks
+                     else ([], blks)
+  case cur of
+    [Header n _ _] | n == slideLevel || slideLevel == 0 ->
+                            splitBlocks' []
+                            (acc ++ [cur ++ [Para [il]] ++ nts])
+                            (if null ils then blks' else Para ils : blks')
+    _ -> splitBlocks' []
+         (if any notText cur
+          then acc ++ ([cur | not (null cur)]) ++ [Para [il] : nts]
+          else acc ++ [cur ++ [Para [il]] ++ nts])
+         (if null ils then blks' else Para ils : blks')
+splitBlocks' cur acc (tbl@Table{} : blks) = do
+  slideLevel <- asks envSlideLevel
+  let (nts, blks') = span isNotesDiv blks
+  case cur of
+    [Header n _ _] | n == slideLevel || slideLevel == 0 ->
+                            splitBlocks' [] (acc ++ [cur ++ [tbl] ++ nts]) blks'
+    _ -> splitBlocks' []
+         (if any notText cur
+          then acc ++ ([cur | not (null cur)]) ++ [tbl : nts]
+          else acc ++ ([cur ++ [tbl] ++ nts]))
+         blks'
+splitBlocks' cur acc (d@(Div (_, classes, _) _): blks) | "columns" `elem` classes =  do
+  slideLevel <- asks envSlideLevel
+  let (nts, blks') = span isNotesDiv blks
+  case cur of
+    [Header n _ _] | n == slideLevel || slideLevel == 0 ->
+                            splitBlocks' [] (acc ++ [cur ++ [d] ++ nts]) blks'
+    _ ->  splitBlocks' [] (acc ++ ([cur | not (null cur)]) ++ [d : nts]) blks'
+splitBlocks' cur acc (blk : blks) = splitBlocks' (cur ++ [blk]) acc blks
+
+splitBlocks :: [Block] -> Pres [[Block]]
+splitBlocks = splitBlocks' [] []
+
+-- | Assuming the slide title is already handled, convert these blocks to the
+-- body content for the slide.
+bodyBlocksToSlide :: Int -> [Block] -> SpeakerNotes -> Pres Slide
+bodyBlocksToSlide _ (blk : blks) spkNotes
+  | Div (_, classes, _) divBlks <- blk
+  , "columns" `elem` classes
+  , Div (_, clsL, _) blksL : Div (_, clsR, _) blksR : remaining <- divBlks
+  , "column" `elem` clsL, "column" `elem` clsR = do
+      -- At least 2 column elements
+      mapM_ (addLogMessage . BlockNotRendered) (blks ++ remaining)
+      let mkTwoColumn left right = do
+            blksL' <- join . take 1 <$> splitBlocks left
+            blksR' <- join . take 1 <$> splitBlocks right
+            shapesL <- blocksToShapes blksL'
+            shapesR <- blocksToShapes blksR'
+            sldId <- asks envCurSlideId
+            return $ Slide
+              sldId
+              (TwoColumnSlide [] shapesL shapesR)
+              spkNotes
+              Nothing
+      let mkComparison blksL1  blksL2 blksR1 blksR2 = do
+            shapesL1 <- blocksToShapes blksL1
+            shapesL2 <- blocksToShapes blksL2
+            shapesR1 <- blocksToShapes blksR1
+            shapesR2 <- blocksToShapes blksR2
+            sldId <- asks envCurSlideId
+            return $ Slide
+              sldId
+              (ComparisonSlide [] (shapesL1, shapesL2) (shapesR1, shapesR2))
+              spkNotes
+              Nothing
+      let (blksL1, blksL2) = break notText blksL
+          (blksR1, blksR2) = break notText blksR
+      if (any null [blksL1, blksL2]) && (any null [blksR1, blksR2])
+      then mkTwoColumn blksL blksR
+      else mkComparison blksL1 blksL2 blksR1 blksR2
+  | Div (_, classes, _) divBlks <- blk
+  , "columns" `elem` classes
+  , Div (_, cls, _) columnBlks : remaining <- divBlks
+  , "column" `elem` cls = do
+      -- Only 1 column element.
+      mapM_ (addLogMessage . BlockNotRendered) (blks ++ remaining)
+      clBlks' <- join . take 1 <$> splitBlocks columnBlks
+      shapes <- blocksToShapes clBlks'
+      sldId <- asks envCurSlideId
+      return $ Slide sldId (ContentSlide [] shapes) spkNotes Nothing
+bodyBlocksToSlide _ (blk : blks) spkNotes = do
+      sldId <- asks envCurSlideId
+      inNoteSlide <- asks envInNoteSlide
+      let mkSlide s =
+            Slide sldId s spkNotes Nothing
+      if inNoteSlide
+      then mkSlide . ContentSlide [] <$>
+          forceFontSize noteSize (blocksToShapes (blk : blks))
+      else let
+        contentOrBlankSlide =
+          if makesBlankSlide (blk : blks)
+          then pure (mkSlide BlankSlide)
+          else mkSlide . ContentSlide [] <$> blocksToShapes (blk : blks)
+        in case break notText (blk : blks) of
+          ([], _) -> contentOrBlankSlide
+          (_, []) -> contentOrBlankSlide
+          (textBlocks, contentBlocks) -> do
+            textShapes <- blocksToShapes textBlocks
+            contentShapes <- blocksToShapes contentBlocks
+            return (mkSlide (ContentWithCaptionSlide [] textShapes contentShapes))
+bodyBlocksToSlide _ [] spkNotes = do
+  sldId <- asks envCurSlideId
+  return $
+    Slide
+    sldId
+    BlankSlide
+    spkNotes
+    Nothing
+
+blocksToSlide' :: Int -> [Block] -> SpeakerNotes -> Pres Slide
+blocksToSlide' lvl (Header n (ident, _, attributes) ils : blks) spkNotes
+  | n < lvl = do
+      registerAnchorId ident
+      sldId <- asks envCurSlideId
+      hdr <- inlinesToParElems ils
+      return $ Slide sldId (TitleSlide hdr) spkNotes backgroundImage
+  | n == lvl || lvl == 0 = do
+      registerAnchorId ident
+      hdr <- inlinesToParElems ils
+      -- Now get the slide without the header, and then add the header
+      -- in.
+      slide <- bodyBlocksToSlide lvl blks spkNotes
+      let layout = case slideLayout slide of
+            ContentSlide _ cont          -> ContentSlide hdr cont
+            TwoColumnSlide _ contL contR -> TwoColumnSlide hdr contL contR
+            ComparisonSlide _ contL contR -> ComparisonSlide hdr contL contR
+            ContentWithCaptionSlide _ text content -> ContentWithCaptionSlide hdr text content
+            BlankSlide -> if all inlineIsBlank ils then BlankSlide else ContentSlide hdr []
+            layout'                     -> layout'
+      return $ slide{slideLayout = layout, slideBackgroundImage = backgroundImage}
+  where
+    backgroundImage = T.unpack <$> (lookup "background-image" attributes
+                                   <|> lookup "data-background-image" attributes)
+blocksToSlide' lvl blks spkNotes = bodyBlocksToSlide lvl blks spkNotes
+
+blockToSpeakerNotes :: Block -> Pres SpeakerNotes
+blockToSpeakerNotes (Div (_, ["notes"], _) blks) =
+  local (\env -> env{envInSpeakerNotes=True}) $
+  SpeakerNotes . mconcat <$> mapM blockToParagraphs blks
+blockToSpeakerNotes _ = return mempty
+
+handleSpeakerNotes :: Block -> Pres ()
+handleSpeakerNotes blk = do
+  spNotes <- blockToSpeakerNotes blk
+  modify $ \st -> st{stSpeakerNotes = stSpeakerNotes st <> spNotes}
+
+handleAndFilterSpeakerNotes' :: [Block] -> Pres [Block]
+handleAndFilterSpeakerNotes' blks = do
+  mapM_ handleSpeakerNotes blks
+  return $ filter (not . isNotesDiv) blks
+
+handleAndFilterSpeakerNotes :: [Block] -> Pres ([Block], SpeakerNotes)
+handleAndFilterSpeakerNotes blks = do
+  modify $ \st -> st{stSpeakerNotes = mempty}
+  blks' <- walkM handleAndFilterSpeakerNotes' blks
+  spkNotes <- gets stSpeakerNotes
+  return (blks', spkNotes)
+
+blocksToSlide :: [Block] -> Pres Slide
+blocksToSlide blks = do
+  (blks', spkNotes) <- handleAndFilterSpeakerNotes blks
+  slideLevel <- asks envSlideLevel
+  blocksToSlide' slideLevel blks' spkNotes
+
+makeNoteEntry :: (Int, [Block]) -> [Block]
+makeNoteEntry (n, blks) =
+  let enum = Str (tshow n <> ".")
+  in
+    case blks of
+      (Para ils : blks') -> Para (enum : Space : ils) : blks'
+      _ -> Para [enum] : blks
+
+forceFontSize :: Pixels -> Pres a -> Pres a
+forceFontSize px x = do
+  rpr <- asks envRunProps
+  local (\r -> r {envRunProps = rpr{rPropForceSize = Just px}}) x
+
+-- We leave these as blocks because we will want to include them in
+-- the TOC.
+makeEndNotesSlideBlocks :: Pres [Block]
+makeEndNotesSlideBlocks = do
+  noteIds <- gets stNoteIds
+  slideLevel <- asks envSlideLevel
+  exts <- writerExtensions <$> asks envOpts
+  meta <- asks envMetadata
+  -- Get identifiers so we can give the notes section a unique ident.
+  anchorSet <- M.keysSet <$> gets stAnchorMap
+  if M.null noteIds
+    then return []
+    else let title = case lookupMetaInlines "notes-title" meta of
+                       [] -> [Str "Notes"]
+                       ls -> ls
+             ident = Shared.uniqueIdent exts title anchorSet
+             hdr = Header slideLevel (ident, [], []) title
+             blks = concatMap makeNoteEntry $
+                    M.toList noteIds
+         in return $ hdr : blks
+
+getMetaSlide :: Pres (Maybe Slide)
+getMetaSlide  = do
+  meta <- asks envMetadata
+  title <- inlinesToParElems $ docTitle meta
+  subtitle <- inlinesToParElems $ lookupMetaInlines "subtitle" meta
+  authors <- mapM inlinesToParElems $ docAuthors meta
+  date <- inlinesToParElems $ docDate meta
+  -- Get speaker notes from metadata "notes" field
+  let notesBlocks = lookupMetaBlocks "notes" meta
+  speakerNotes <- if null notesBlocks
+                  then return mempty
+                  else local (\env -> env{envInSpeakerNotes=True}) $
+                       SpeakerNotes . mconcat <$> mapM blockToParagraphs notesBlocks
+  if null title && null subtitle && null authors && null date
+    then return Nothing
+    else return $
+         Just $
+         Slide
+         metadataSlideId
+         (MetadataSlide title subtitle authors date)
+         speakerNotes
+         Nothing
+
+addSpeakerNotesToMetaSlide :: Slide -> [Block] -> Pres (Slide, [Block])
+addSpeakerNotesToMetaSlide (Slide sldId layout@MetadataSlide{} spkNotes backgroundImage) blks =
+  do let (ntsBlks, blks') = span isNotesDiv blks
+     spkNotes' <- mconcat <$> mapM blockToSpeakerNotes ntsBlks
+     return (Slide sldId layout (spkNotes <> spkNotes') backgroundImage, blks')
+addSpeakerNotesToMetaSlide sld blks = return (sld, blks)
+
+makeTOCSlide :: [Block] -> Pres Slide
+makeTOCSlide blks = local (\env -> env{envCurSlideId = tocSlideId}) $ do
+  opts <- asks envOpts
+  let contents = toTableOfContents opts blks
+  meta <- asks envMetadata
+  slideLevel <- asks envSlideLevel
+  let tocTitle = case lookupMetaInlines "toc-title" meta of
+                   [] -> [Str "Table of Contents"]
+                   ls -> ls
+      hdr = Header slideLevel nullAttr tocTitle
+  blocksToSlide [hdr, contents]
+
+combineParaElems' :: Maybe ParaElem -> [ParaElem] -> [ParaElem]
+combineParaElems' mbPElem [] = maybeToList mbPElem
+combineParaElems' Nothing (pElem : pElems) =
+  combineParaElems' (Just pElem) pElems
+combineParaElems' (Just pElem') (pElem : pElems)
+  | Run rPr' s' <- pElem'
+  , Run rPr s <- pElem
+  , rPr == rPr' =
+    combineParaElems' (Just $ Run rPr' $ s' <> s) pElems
+  | otherwise =
+    pElem' : combineParaElems' (Just pElem) pElems
+
+combineParaElems :: [ParaElem] -> [ParaElem]
+combineParaElems = combineParaElems' Nothing
+
+applyToParagraph :: Monad m => (ParaElem -> m ParaElem) -> Paragraph -> m Paragraph
+applyToParagraph f para = do
+  paraElems' <- mapM f $ paraElems para
+  return $ para {paraElems = paraElems'}
+
+applyToShape :: Monad m => (ParaElem -> m ParaElem) -> Shape -> m Shape
+applyToShape f (Pic pPr fp title pes) = Pic pPr fp title <$> mapM f pes
+applyToShape f (GraphicFrame gfx pes) = GraphicFrame gfx <$> mapM f pes
+applyToShape f (TextBox paras) = TextBox <$> mapM (applyToParagraph f) paras
+applyToShape _ (RawOOXMLShape str) = return $ RawOOXMLShape str
+
+applyToLayout :: Monad m => (ParaElem -> m ParaElem) -> Layout -> m Layout
+applyToLayout f (MetadataSlide title subtitle authors date) = do
+  title' <- mapM f title
+  subtitle' <- mapM f subtitle
+  authors' <- mapM (mapM f) authors
+  date' <- mapM f date
+  return $ MetadataSlide title' subtitle' authors' date'
+applyToLayout f (TitleSlide title) = TitleSlide <$> mapM f title
+applyToLayout f (ContentSlide hdr content) = do
+  hdr' <- mapM f hdr
+  content' <- mapM (applyToShape f) content
+  return $ ContentSlide hdr' content'
+applyToLayout f (TwoColumnSlide hdr contentL contentR) = do
+  hdr' <- mapM f hdr
+  contentL' <- mapM (applyToShape f) contentL
+  contentR' <- mapM (applyToShape f) contentR
+  return $ TwoColumnSlide hdr' contentL' contentR'
+applyToLayout f (ComparisonSlide hdr (contentL1, contentL2) (contentR1, contentR2)) = do
+  hdr' <- mapM f hdr
+  contentL1' <- mapM (applyToShape f) contentL1
+  contentL2' <- mapM (applyToShape f) contentL2
+  contentR1' <- mapM (applyToShape f) contentR1
+  contentR2' <- mapM (applyToShape f) contentR2
+  return $ ComparisonSlide hdr' (contentL1', contentL2') (contentR1', contentR2')
+applyToLayout f (ContentWithCaptionSlide hdr textShapes contentShapes) = do
+  hdr' <- mapM f hdr
+  textShapes' <- mapM (applyToShape f) textShapes
+  contentShapes' <- mapM (applyToShape f) contentShapes
+  return $ ContentWithCaptionSlide hdr' textShapes' contentShapes'
+applyToLayout _ BlankSlide = pure BlankSlide
+
+applyToSlide :: Monad m => (ParaElem -> m ParaElem) -> Slide -> m Slide
+applyToSlide f slide = do
+  layout' <- applyToLayout f $ slideLayout slide
+  let paras = fromSpeakerNotes $ slideSpeakerNotes slide
+  notes' <- SpeakerNotes <$> mapM (applyToParagraph f) paras
+  return slide{slideLayout = layout', slideSpeakerNotes = notes'}
+
+replaceAnchor :: ParaElem -> Pres ParaElem
+replaceAnchor (Run rProps s)
+  | Just (ExternalTarget (T.uncons -> Just ('#', anchor), _)) <- rLink rProps
+  = do
+      anchorMap <- gets stAnchorMap
+      -- If the anchor is not in the anchormap, we just remove the
+      -- link.
+      let rProps' = case M.lookup anchor anchorMap of
+                      Just n  -> rProps{rLink = Just $ InternalTarget n}
+                      Nothing -> rProps{rLink = Nothing}
+      return $ Run rProps' s
+replaceAnchor pe = return pe
+
+emptyParaElem :: ParaElem -> Bool
+emptyParaElem (Run _ s) =
+  T.null $ Shared.trim s
+emptyParaElem (MathElem _ ts) =
+  T.null $ Shared.trim $ unTeXString ts
+emptyParaElem _ = False
+
+emptyParagraph :: Paragraph -> Bool
+emptyParagraph para = all emptyParaElem $ paraElems para
+
+
+emptyShape :: Shape -> Bool
+emptyShape (TextBox paras) = all emptyParagraph paras
+emptyShape _ = False
+
+emptyLayout :: Layout -> Bool
+emptyLayout layout = case layout of
+  MetadataSlide title subtitle authors date ->
+    all emptyParaElem title &&
+    all emptyParaElem subtitle &&
+    all (all emptyParaElem) authors &&
+    all emptyParaElem date
+  TitleSlide hdr -> all emptyParaElem hdr
+  ContentSlide hdr shapes ->
+    all emptyParaElem hdr &&
+    all emptyShape shapes
+  TwoColumnSlide hdr shapes1 shapes2 ->
+    all emptyParaElem hdr &&
+    all emptyShape shapes1 &&
+    all emptyShape shapes2
+  ComparisonSlide hdr (shapesL1, shapesL2) (shapesR1, shapesR2) ->
+    all emptyParaElem hdr &&
+    all emptyShape shapesL1 &&
+    all emptyShape shapesL2 &&
+    all emptyShape shapesR1 &&
+    all emptyShape shapesR2
+  ContentWithCaptionSlide hdr textShapes contentShapes ->
+    all emptyParaElem hdr &&
+    all emptyShape textShapes &&
+    all emptyShape contentShapes
+  BlankSlide -> False
+
+
+emptySlide :: Slide -> Bool
+emptySlide (Slide _ layout notes backgroundImage)
+  = (notes == mempty)
+  && emptyLayout layout
+  && isNothing backgroundImage
+
+makesBlankSlide :: [Block] -> Bool
+makesBlankSlide = all blockIsBlank
+
+blockIsBlank :: Block -> Bool
+blockIsBlank
+  = \case
+      Plain ins -> all inlineIsBlank ins
+      Para ins -> all inlineIsBlank ins
+      LineBlock inss -> all (all inlineIsBlank) inss
+      CodeBlock _ txt -> textIsBlank txt
+      RawBlock _ txt -> textIsBlank txt
+      BlockQuote bls -> all blockIsBlank bls
+      OrderedList _ blss -> all (all blockIsBlank) blss
+      BulletList blss -> all (all blockIsBlank) blss
+      DefinitionList ds -> all (uncurry (&&) . bimap (all inlineIsBlank) (all (all blockIsBlank))) ds
+      Header _ _ ils -> all inlineIsBlank ils
+      HorizontalRule -> True
+      Figure _ _ bls -> all blockIsBlank bls
+      Table{} -> False
+      Div _ bls -> all blockIsBlank bls
+
+textIsBlank :: T.Text -> Bool
+textIsBlank = T.all isSpace
+
+inlineIsBlank :: Inline -> Bool
+inlineIsBlank
+  = \case
+      (Str txt) -> textIsBlank txt
+      (Emph ins) -> all inlineIsBlank ins
+      (Underline ins) -> all inlineIsBlank ins
+      (Strong ins) -> all inlineIsBlank ins
+      (Strikeout ins) -> all inlineIsBlank ins
+      (Superscript ins) -> all inlineIsBlank ins
+      (Subscript ins) -> all inlineIsBlank ins
+      (SmallCaps ins) -> all inlineIsBlank ins
+      (Quoted _ ins) -> all inlineIsBlank ins
+      (Cite _ _) -> False
+      (Code _ txt) -> textIsBlank txt
+      Space -> True
+      SoftBreak -> True
+      LineBreak -> True
+      (Math _ txt) -> textIsBlank txt
+      (RawInline _ txt) -> textIsBlank txt
+      (Link _ ins (t1, t2)) -> all inlineIsBlank ins && textIsBlank t1 && textIsBlank t2
+      (Image _ ins (t1, t2)) -> all inlineIsBlank ins && textIsBlank t1 && textIsBlank t2
+      (Note bls) -> all blockIsBlank bls
+      (Span _ ins) -> all inlineIsBlank ins
+
+blocksToPresentationSlides :: [Block] -> Pres [Slide]
+blocksToPresentationSlides blks = do
+  opts <- asks envOpts
+  mbMetadataSlide <- getMetaSlide
+  -- if the metadata slide exists, we try to add any speakerNotes
+  -- which immediately follow it. We also convert from maybe to a
+  -- list, so that it will be able to add together more easily with
+  -- the other lists of slides.
+  (metadataslides, blks') <- case mbMetadataSlide of
+                                 Just sld ->
+                                   do (s, bs) <- addSpeakerNotesToMetaSlide sld blks
+                                      return ([s], bs)
+                                 Nothing -> return ([], blks)
+  -- As far as I can tell, if we want to have a variable-length toc in
+  -- the future, we'll have to make it twice. Once to get the length,
+  -- and a second time to include the notes slide. We can't make the
+  -- notes slide before the body slides because we need to know if
+  -- there are notes, and we can't make either before the toc slide,
+  -- because we need to know its length to get slide numbers right.
+  --
+  -- For now, though, since the TOC slide is only length 1, if it
+  -- exists, we'll just get the length, and then come back to make the
+  -- slide later
+  blksLst <- splitBlocks blks'
+  bodySlideIds <- mapM
+                  (\n -> runUniqueSlideId $ "BodySlide" <> tshow n)
+                  (take (length blksLst) [1..] :: [Integer])
+  bodyslides <- mapM
+                (\(bs, ident) ->
+                    local (\st -> st{envCurSlideId = ident}) (blocksToSlide bs))
+                (zip blksLst bodySlideIds)
+  endNotesSlideBlocks <- makeEndNotesSlideBlocks
+  -- now we come back and make the real toc...
+  tocSlides <- if writerTableOfContents opts
+               then do toc <- makeTOCSlide $ blks' ++ endNotesSlideBlocks
+                       return [toc]
+               else return []
+  -- ... and the notes slide. We test to see if the blocks are empty,
+  -- because we don't want to make an empty slide.
+  endNotesSlides <- if null endNotesSlideBlocks
+                    then return []
+                    else do endNotesSlide <- local
+                              (\env -> env { envCurSlideId = endNotesSlideId
+                                           , envInNoteSlide = True
+                                           })
+                              (blocksToSlide endNotesSlideBlocks)
+                            return [endNotesSlide]
+
+  let slides = metadataslides ++ tocSlides ++ bodyslides ++ endNotesSlides
+      slides' = filter (not . emptySlide) slides
+  mapM (applyToSlide replaceAnchor) slides'
+
+metaToDocProps :: Meta -> DocProps
+metaToDocProps meta =
+  let keywords = case lookupMeta "keywords" meta of
+                   Just (MetaList xs) -> Just $ map Shared.stringify xs
+                   _                  -> Nothing
+
+      authors = case map Shared.stringify $ docAuthors meta of
+                  [] -> Nothing
+                  ss -> Just $ T.intercalate "; " ss
+
+      description = case map Shared.stringify $ lookupMetaBlocks "description" meta of
+                  [] -> Nothing
+                  ss -> Just $ T.intercalate "_x000d_\n" ss
+
+      customProperties' = case [(k, lookupMetaString k meta) | k <- M.keys (unMeta meta)
+                               , k `notElem` ["title", "author", "keywords", "description"
+                                             , "subject","lang","category"]] of
+                  [] -> Nothing
+                  ss -> Just ss
+  in
+    DocProps{ dcTitle = Shared.stringify <$> lookupMeta "title" meta
+            , dcSubject = Shared.stringify <$> lookupMeta "subject" meta
+            , dcCreator = authors
+            , dcKeywords = keywords
+            , dcDescription = description
+            , cpCategory = Shared.stringify <$> lookupMeta "category" meta
+            , dcDate =
+              let t = Shared.stringify (docDate meta)
+              in if T.null t
+                 then Nothing
+                 else Just t
+            , customProperties = customProperties'
+            }
+
+documentToPresentation :: WriterOptions
+                       -> Pandoc
+                       -> (Presentation, [LogMessage])
+documentToPresentation opts (Pandoc meta blks) =
+  let env = def { envOpts = opts
+                , envMetadata = meta
+                , envSlideLevel = fromMaybe (getSlideLevel blks) (writerSlideLevel opts)
+                }
+      (presSlides, msgs) = runPres env def $ blocksToPresentationSlides blks
+      docProps = metaToDocProps meta
+  in
+    (Presentation docProps presSlides, msgs)
+
+-- --------------------------------------------------------------
+
+applyTokStyToRunProps :: TokenStyle -> RunProps -> RunProps
+applyTokStyToRunProps tokSty rProps =
+  rProps{ rSolidFill     = tokenColor tokSty <|> rSolidFill rProps
+        , rPropBold      = tokenBold tokSty || rPropBold rProps
+        , rPropItalics   = tokenItalic tokSty || rPropItalics rProps
+        , rPropUnderline = tokenUnderline tokSty || rPropUnderline rProps
+        }
+
+formatToken :: Style -> Token -> ParaElem
+formatToken sty (tokType, txt) =
+  let rProps = def{rPropCode = True, rSolidFill = defaultColor sty}
+      rProps' = case M.lookup tokType (tokenStyles sty) of
+        Just tokSty -> applyTokStyToRunProps tokSty rProps
+        Nothing     -> rProps
+  in
+    Run rProps' txt
+
+formatSourceLine :: Style -> FormatOptions -> SourceLine -> [ParaElem]
+formatSourceLine sty _ srcLn = map (formatToken sty) srcLn
+
+formatSourceLines :: Style -> FormatOptions -> [SourceLine] -> [ParaElem]
+formatSourceLines sty opts srcLns = intercalate [Break] $
+                                    map (formatSourceLine sty opts) srcLns
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,25 +1,8 @@
 {-# LANGUAGE OverloadedStrings #-}
-{-
-Copyright (C) 2006-2017 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 ViewPatterns      #-}
 {- |
    Module      : Text.Pandoc.Writers.RST
-   Copyright   : Copyright (C) 2006-2017 John MacFarlane
+   Copyright   : Copyright (C) 2006-2024 John MacFarlane
    License     : GNU GPL, version 2 or above
 
    Maintainer  : John MacFarlane <jgm@berkeley.edu>
@@ -30,34 +13,44 @@
 
 reStructuredText:  <http://docutils.sourceforge.net/rst.html>
 -}
-module Text.Pandoc.Writers.RST ( writeRST ) where
-import Control.Monad.State.Strict
-import Data.Char (isSpace, toLower)
-import Data.List (isPrefixOf, stripPrefix)
+module Text.Pandoc.Writers.RST ( writeRST, flatten ) where
+import Control.Monad.State.Strict ( StateT, gets, modify, evalStateT )
+import Control.Monad (zipWithM, liftM)
+import Data.Char (isSpace, generalCategory, isAscii, isAlphaNum,
+                  GeneralCategory(
+                        ClosePunctuation, OpenPunctuation, InitialQuote,
+                         FinalQuote, DashPunctuation, OtherPunctuation))
+import Data.List (transpose, intersperse)
+import qualified Data.List as L
+import qualified Data.List.NonEmpty as NE
 import Data.Maybe (fromMaybe)
-import Data.Text (Text, stripEnd)
+import qualified Data.Text as T
+import Data.Text (Text)
 import qualified Text.Pandoc.Builder as B
-import Text.Pandoc.Class (PandocMonad, report)
+import Text.Pandoc.Class.PandocMonad (PandocMonad, report)
 import Text.Pandoc.Definition
 import Text.Pandoc.ImageSize
 import Text.Pandoc.Logging
 import Text.Pandoc.Options
-import Text.Pandoc.Pretty
+import Text.DocLayout
 import Text.Pandoc.Shared
-import Text.Pandoc.Templates (renderTemplate')
+import Text.Pandoc.URI
+import Text.Pandoc.Templates (renderTemplate)
 import Text.Pandoc.Writers.Shared
+import Text.Pandoc.Walk
+import Safe (lastMay, headMay)
 
 type Refs = [([Inline], Target)]
 
 data WriterState =
   WriterState { stNotes       :: [[Block]]
               , stLinks       :: Refs
-              , stImages      :: [([Inline], (Attr, String, String, Maybe String))]
+              , stImages      :: [([Inline], (Attr, Text, Text, Maybe Text))]
               , stHasMath     :: Bool
               , stHasRawTeX   :: Bool
               , stOptions     :: WriterOptions
               , stTopLevel    :: Bool
-              , stLastNested  :: Bool
+              , stImageId     :: Int
               }
 
 type RST = StateT WriterState
@@ -68,7 +61,7 @@
   let st = WriterState { stNotes = [], stLinks = [],
                          stImages = [], stHasMath = False,
                          stHasRawTeX = False, stOptions = opts,
-                         stTopLevel = True, stLastNested = False}
+                         stTopLevel = True, stImageId = 1 }
   evalStateT (pandocToRST document) st
 
 -- | Return RST representation of document.
@@ -78,16 +71,12 @@
   let colwidth = if writerWrapText opts == WrapAuto
                     then Just $ writerColumns opts
                     else Nothing
-  let render' :: Doc -> Text
-      render' = render colwidth
-  let subtit = case lookupMeta "subtitle" meta of
-                    Just (MetaBlocks [Plain xs]) -> xs
-                    _                            -> []
+  let subtit = lookupMetaInlines "subtitle" meta
   title <- titleToRST (docTitle meta) subtit
-  metadata <- metaToJSON opts
-                (fmap render' . blockListToRST)
-                (fmap (stripEnd . render') . inlineListToRST)
-                $ B.deleteMeta "title" $ B.deleteMeta "subtitle" meta
+  metadata <- metaToContext opts
+                blockListToRST
+                (fmap chomp . inlineListToRST)
+                meta
   body <- blockListToRST' True $ case writerTemplate opts of
                                       Just _  -> normalizeHeadings 1 blocks
                                       Nothing -> blocks
@@ -97,17 +86,19 @@
   pics <- gets (reverse . stImages) >>= pictRefsToRST
   hasMath <- gets stHasMath
   rawTeX <- gets stHasRawTeX
-  let main = render' $ foldl ($+$) empty [body, notes, refs, pics]
+  let main = vsep [body, notes, refs, pics]
   let context = defField "body" main
               $ defField "toc" (writerTableOfContents opts)
-              $ defField "toc-depth" (show $ writerTOCDepth opts)
+              $ defField "toc-depth" (tshow $ writerTOCDepth opts)
+              $ defField "number-sections" (writerNumberSections opts)
               $ defField "math" hasMath
-              $ defField "title" (render Nothing title :: String)
+              $ defField "titleblock" (render Nothing title :: Text)
               $ defField "math" hasMath
               $ defField "rawtex" rawTeX metadata
-  case writerTemplate opts of
-       Nothing  -> return main
-       Just tpl -> renderTemplate' tpl context
+  return $ render colwidth $
+    case writerTemplate opts of
+       Nothing  -> main
+       Just tpl -> renderTemplate tpl context
   where
     normalizeHeadings lev (Header l a i:bs) =
       Header lev a i:normalizeHeadings (lev+1) cont ++ normalizeHeadings lev bs'
@@ -118,26 +109,26 @@
     normalizeHeadings _   []     = []
 
 -- | Return RST representation of reference key table.
-refsToRST :: PandocMonad m => Refs -> RST m Doc
-refsToRST refs = mapM keyToRST refs >>= return . vcat
+refsToRST :: PandocMonad m => Refs -> RST m (Doc Text)
+refsToRST refs =
+   vcat <$> mapM keyToRST refs
 
 -- | Return RST representation of a reference key.
-keyToRST :: PandocMonad m => ([Inline], (String, String)) -> RST m Doc
+keyToRST :: PandocMonad m => ([Inline], (Text, Text)) -> RST m (Doc Text)
 keyToRST (label, (src, _)) = do
   label' <- inlineListToRST label
-  let label'' = if ':' `elem` (render Nothing label' :: String)
+  let label'' = if (==':') `T.any` (render Nothing label' :: Text)
                    then char '`' <> label' <> char '`'
                    else label'
-  return $ nowrap $ ".. _" <> label'' <> ": " <> text src
+  return $ nowrap $ ".. _" <> label'' <> ": " <> literal src
 
 -- | Return RST representation of notes.
-notesToRST :: PandocMonad m => [[Block]] -> RST m Doc
+notesToRST :: PandocMonad m => [[Block]] -> RST m (Doc Text)
 notesToRST notes =
-  mapM (uncurry noteToRST) (zip [1..] notes) >>=
-  return . vsep
+   vsep <$> zipWithM noteToRST [1..] notes
 
 -- | Return RST representation of a note.
-noteToRST :: PandocMonad m => Int -> [Block] -> RST m Doc
+noteToRST :: PandocMonad m => Int -> [Block] -> RST m (Doc Text)
 noteToRST num note = do
   contents <- blockListToRST note
   let marker = ".. [" <> text (show num) <> "]"
@@ -145,85 +136,138 @@
 
 -- | Return RST representation of picture reference table.
 pictRefsToRST :: PandocMonad m
-              => [([Inline], (Attr, String, String, Maybe String))]
-              -> RST m Doc
-pictRefsToRST refs = mapM pictToRST refs >>= return . vcat
+              => [([Inline], (Attr, Text, Text, Maybe Text))]
+              -> RST m (Doc Text)
+pictRefsToRST refs =
+   vcat <$> mapM pictToRST refs
 
 -- | Return RST representation of a picture substitution reference.
 pictToRST :: PandocMonad m
-          => ([Inline], (Attr, String, String, Maybe String))
-          -> RST m Doc
+          => ([Inline], (Attr, Text, Text, Maybe Text))
+          -> RST m (Doc Text)
 pictToRST (label, (attr, src, _, mbtarget)) = do
   label' <- inlineListToRST label
   dims   <- imageDimsToRST attr
   let (_, cls, _) = attr
-      classes = if null cls
-                   then empty
-                   else ":class: " <> text (unwords cls)
+      classes = case cls of
+                   []               -> empty
+                   ["align-top"]    -> ":align: top"
+                   ["align-middle"] -> ":align: middle"
+                   ["align-bottom"] -> ":align: bottom"
+                   ["align-center"] -> empty
+                   ["align-right"]  -> empty
+                   ["align-left"]   -> empty
+                   _                -> ":class: " <> literal (T.unwords cls)
   return $ nowrap
-         $ ".. |" <> label' <> "| image:: " <> text src $$ hang 3 empty (classes $$ dims)
+         $ ".. |" <> label' <> "| image:: " <> literal src $$ hang 3 empty (classes $$ dims)
          $$ case mbtarget of
                  Nothing -> empty
-                 Just t  -> "   :target: " <> text t
+                 Just t  -> "   :target: " <> literal t
 
 -- | Escape special characters for RST.
-escapeString :: WriterOptions -> String -> String
-escapeString = escapeString' True
-  where
-  escapeString' _ _  [] = []
-  escapeString' firstChar opts (c:cs) =
-    case c of
-         _ | c `elem` ['\\','`','*','_','|'] &&
-             (firstChar || null cs) -> '\\':c:escapeString' False opts cs
-         '\'' | isEnabled Ext_smart opts -> '\\':'\'':escapeString' False opts cs
-         '"' | isEnabled Ext_smart opts -> '\\':'"':escapeString' False opts cs
-         '-' | isEnabled Ext_smart opts ->
-                case cs of
-                     '-':_ -> '\\':'-':escapeString' False opts cs
-                     _     -> '-':escapeString' False opts cs
-         '.' | isEnabled Ext_smart opts ->
-                case cs of
-                     '.':'.':rest -> '\\':'.':'.':'.':escapeString' False opts rest
-                     _            -> '.':escapeString' False opts cs
-         _ -> c : escapeString' False opts cs
+escapeText :: WriterOptions -> Text -> Text
+escapeText opts t =
+  if T.any isSpecial t
+     then T.pack . escapeString' True . T.unpack $ t
+     else t -- optimization
+ where
+  isSmart = isEnabled Ext_smart opts
+  isSpecial c = c == '\\' || c == '_' || c == '`' || c == '*' || c == '|'
+                || (isSmart && (c == '-' || c == '.' || c == '"' || c == '\''))
+  canFollowInlineMarkup c = c == '-' || c == '.' || c == ',' || c == ':'
+                    || c == ';' || c == '!' || c == '?' || c == '\''
+                    || c == '"' || c == ')' || c == ']' || c == '}'
+                    || c == '>' || isSpace c
+                    || (not (isAscii c) &&
+                        generalCategory c `elem`
+                        [OpenPunctuation, InitialQuote, FinalQuote,
+                         DashPunctuation, OtherPunctuation])
+  canPrecedeInlineMarkup c = c == '-' || c == ':' || c == '/' || c == '\''
+                     || c == '"' || c == '<' || c == '(' || c == '['
+                     || c == '{' || isSpace c
+                     || (not (isAscii c) &&
+                          generalCategory c `elem`
+                          [ClosePunctuation, InitialQuote, FinalQuote,
+                          DashPunctuation, OtherPunctuation])
+  escapeString' canStart cs =
+    case cs of
+      [] -> []
+      d:ds
+        | d == '\\'
+        -> '\\' : d : escapeString' False ds
+      '\'':ds
+        | isSmart
+        -> '\\' : '\'' : escapeString' True ds
+      '"':ds
+        | isSmart
+        -> '\\' : '"' : escapeString' True ds
+      '-':'-':ds
+        | isSmart
+        -> '\\' : '-' : escapeString' False ('-':ds)
+      '.':'.':'.':ds
+        | isSmart
+        -> '\\' : '.' : escapeString' False ('.':'.':ds)
+      [e]
+        | e == '*' || e == '_' || e == '|' || e == '`'
+        -> ['\\',e]
+      d:ds
+        | canPrecedeInlineMarkup d
+        -> d : escapeString' True ds
+      e:d:ds
+        | e == '*' || e == '_' || e == '|' || e == '`'
+        , (not canStart && canFollowInlineMarkup d)
+          || (canStart && not (isSpace d))
+        -> '\\' : e : escapeString' False (d:ds)
+      '_':d:ds
+        | not (isAlphaNum d)
+        -> '\\' : '_' : escapeString' False (d:ds)
+      d:ds -> d : escapeString' False ds
 
-titleToRST :: PandocMonad m => [Inline] -> [Inline] -> RST m Doc
+titleToRST :: PandocMonad m => [Inline] -> [Inline] -> RST m (Doc Text)
 titleToRST [] _ = return empty
 titleToRST tit subtit = do
   title <- inlineListToRST tit
   subtitle <- inlineListToRST subtit
   return $ bordered title '=' $$ bordered subtitle '-'
 
-bordered :: Doc -> Char -> Doc
+bordered :: Doc Text -> Char -> Doc Text
 bordered contents c =
   if len > 0
      then border $$ contents $$ border
      else empty
    where len = offset contents
-         border = text (replicate len c)
+         border = literal (T.replicate len $ T.singleton c)
 
 -- | Convert Pandoc block element to RST.
 blockToRST :: PandocMonad m
            => Block         -- ^ Block element
-           -> RST m Doc
-blockToRST Null = return empty
-blockToRST (Div attr bs) = do
+           -> RST m (Doc Text)
+blockToRST (Div ("",["title"],[]) _) = return empty
+  -- this is generated by the rst reader and can safely be
+  -- omitted when we're generating rst
+blockToRST (Div (ident,classes,_kvs) bs) = do
   contents <- blockListToRST bs
-  let startTag = ".. raw:: html" $+$ nest 3 (tagWithAttrs "div" attr)
-  let endTag = ".. raw:: html" $+$ nest 3 "</div>"
-  return $ blankline <> startTag $+$ contents $+$ endTag $$ blankline
+  let admonitions = ["attention","caution","danger","error","hint",
+                     "important","note","tip","warning","admonition"]
+  let admonition = case classes of
+                        (cl:_)
+                          | cl `elem` admonitions
+                          -> blankline <> ".. " <> literal cl <> "::"
+                        cls -> blankline <> ".. container::" <> space <>
+                                   literal (T.unwords (filter (/= "container") cls))
+  -- if contents start with block quote, we need to insert
+  -- an empty comment to fix the indentation point (#10236)
+  let contents' = case bs of
+                    BlockQuote{}:_-> ".." $+$ contents
+                    _ -> contents
+  return $ blankline $$
+           admonition $$
+           (if T.null ident
+               then blankline
+               else "   :name: " <> literal ident $$ blankline) $$
+           nest 3 contents' $$
+           blankline
 blockToRST (Plain inlines) = inlineListToRST inlines
--- title beginning with fig: indicates that the image is a figure
-blockToRST (Para [Image attr txt (src,'f':'i':'g':':':tit)]) = do
-  capt <- inlineListToRST txt
-  dims <- imageDimsToRST attr
-  let fig = "figure:: " <> text src
-      alt = ":alt: " <> if null tit then capt else text tit
-      (_,cls,_) = attr
-      classes = if null cls
-                   then empty
-                   else ":figclass: " <> text (unwords cls)
-  return $ hang 3 ".. " (fig $$ alt $$ classes $$ dims $+$ capt) $$ blankline
 blockToRST (Para inlines)
   | LineBreak `elem` inlines =
       linesToLineBlock $ splitBy (==LineBreak) inlines
@@ -233,53 +277,61 @@
 blockToRST (LineBlock lns) =
   linesToLineBlock lns
 blockToRST (RawBlock f@(Format f') str)
-  | f == "rst" = return $ text str
+  | f == "rst" = return $ literal str
+  | f == "tex" = blockToRST (RawBlock (Format "latex") str)
   | otherwise  = return $ blankline <> ".. raw:: " <>
-                    text (map toLower f') $+$
-                    nest 3 (text str) $$ blankline
+                    literal (T.toLower f') $+$
+                    nest 3 (literal str) $$ blankline
 blockToRST HorizontalRule =
   return $ blankline $$ "--------------" $$ blankline
 blockToRST (Header level (name,classes,_) inlines) = do
   contents <- inlineListToRST inlines
   -- we calculate the id that would be used by auto_identifiers
   -- so we know whether to print an explicit identifier
-  let autoId = uniqueIdent inlines mempty
+  opts <- gets stOptions
+  let autoId = uniqueIdent (writerExtensions opts) inlines mempty
   isTopLevel <- gets stTopLevel
   if isTopLevel
     then do
           let headerChar = if level > 5 then ' ' else "=-~^'" !! (level - 1)
-          let border = text $ replicate (offset contents) headerChar
-          let anchor | null name || name == autoId = empty
-                     | otherwise = ".. _" <> text name <> ":" $$ blankline
+          let border = literal $ T.replicate (offset contents) $ T.singleton headerChar
+          let anchor | T.null name || name == autoId = empty
+                     | otherwise = ".. _" <>
+                                   (if T.any (==':') name ||
+                                        T.take 1 name == "_"
+                                       then "`" <> literal name <> "`"
+                                       else literal name) <>
+                                   ":" $$ blankline
           return $ nowrap $ anchor $$ contents $$ border $$ blankline
     else do
           let rub     = "rubric:: " <> contents
-          let name' | null name    = empty
-                    | otherwise    = ":name: " <> text name
-          let cls   | null classes = empty
-                    | otherwise    = ":class: " <> text (unwords classes)
+          let name' | T.null name    = empty
+                    | otherwise      = ":name: " <> literal name
+          let cls   | null classes   = empty
+                    | otherwise      = ":class: " <> literal (T.unwords classes)
           return $ nowrap $ hang 3 ".. " (rub $$ name' $$ cls) $$ blankline
 blockToRST (CodeBlock (_,classes,kvs) str) = do
   opts <- gets stOptions
-  let tabstop = writerTabStop opts
-  let startnum = maybe "" (\x -> " " <> text x) $ lookup "startFrom" kvs
+  let startnum = maybe "" (\x -> " " <> literal x) $ lookup "startFrom" kvs
   let numberlines = if "numberLines" `elem` classes
                        then "   :number-lines:" <> startnum
                        else empty
   if "haskell" `elem` classes && "literate" `elem` classes &&
                   isEnabled Ext_literate_haskell opts
-     then return $ prefixed "> " (text str) $$ blankline
+     then return $ prefixed "> " (literal str) $$ blankline
      else return $
           (case [c | c <- classes,
-                     c `notElem` ["sourceCode","literate","numberLines"]] of
+                     c `notElem` ["sourceCode","literate","numberLines",
+                                  "number-lines","example"]] of
              []       -> "::"
-             (lang:_) -> (".. code:: " <> text lang) $$ numberlines)
-          $+$ nest tabstop (text str) $$ blankline
+             (lang:_) -> (blankline <> ".. code:: " <> literal lang) $$ numberlines)
+          $+$ nest 3 (literal str) $$ blankline
 blockToRST (BlockQuote blocks) = do
-  tabstop <- gets $ writerTabStop . stOptions
   contents <- blockListToRST blocks
-  return $ nest tabstop contents <> blankline
-blockToRST (Table caption aligns widths headers rows) = do
+  return $ nest 3 contents <> blankline
+blockToRST (Table _attrs blkCapt specs thead@(TableHead _ theadRows) tbody tfoot@(TableFoot _ tfootRows)) = do
+  let (caption, aligns, widths, headers, rows) =
+        toLegacyTable blkCapt specs thead tbody tfoot
   caption' <- inlineListToRST caption
   let blocksToDoc opts bs = do
          oldOpts <- gets stOptions
@@ -288,109 +340,261 @@
          modify $ \st -> st{ stOptions = oldOpts }
          return result
   opts <- gets stOptions
-  tbl <- gridTable opts blocksToDoc (all null headers)
-            (map (const AlignDefault) aligns) widths
-            headers rows
-  return $ if null caption
-              then tbl $$ blankline
-              else (".. table:: " <> caption') $$ blankline $$ nest 3 tbl $$
-                   blankline
+  let specs' = map (\(_,width) -> (AlignDefault, width)) specs
+      renderGrid = gridTable opts blocksToDoc specs' thead tbody tfoot
+      rowHasRowSpan (Row _ cells) = any cellHasRowSpan cells
+      cellHasRowSpan (Cell _ _ rowSpan _ _) = rowSpan > 1
+      isSimple = all (== 0) widths && length widths > 1 && not (any rowHasRowSpan $ theadRows ++ tableBodiesToRows tbody ++ tfootRows)
+      renderSimple = do
+        tbl' <- simpleTable opts blocksToDoc thead tbody tfoot
+        if offset tbl' > writerColumns opts
+          then renderGrid
+          else return tbl'
+      isList = writerListTables opts
+      renderList = tableToRSTList caption (map (const AlignDefault) aligns)
+                    widths headers rows
+      rendered
+        | isList    = renderList
+        | isSimple  = renderSimple
+        | otherwise = renderGrid
+  tbl <- rendered
+  return $ blankline $$
+           (if null caption || isList
+               then tbl
+               else (blankline <> ".. table:: " <> caption') $$ blankline $$ nest 3 tbl) $$
+           blankline
 blockToRST (BulletList items) = do
   contents <- mapM bulletListItemToRST items
   -- ensure that sublists have preceding blank line
-  return $ blankline $$ chomp (vcat contents) $$ blankline
+  return $ blankline $$
+           (if isTightList items then vcat else vsep) contents $$
+           blankline
 blockToRST (OrderedList (start, style', delim) items) = do
   let markers = if start == 1 && style' == DefaultStyle && delim == DefaultDelim
                    then replicate (length items) "#."
                    else take (length items) $ orderedListMarkers
                                               (start, style', delim)
-  let maxMarkerLength = maximum $ map length markers
-  let markers' = map (\m -> let s = maxMarkerLength - length m
-                            in  m ++ replicate s ' ') markers
-  contents <- mapM (uncurry orderedListItemToRST) $
-              zip markers' items
+  let maxMarkerLength = maybe 0 maximum $ NE.nonEmpty $ map T.length markers
+  let markers' = map (\m -> let s = maxMarkerLength - T.length m
+                            in  m <> T.replicate s " ") markers
+  contents <- zipWithM orderedListItemToRST markers' items
   -- ensure that sublists have preceding blank line
-  return $ blankline $$ chomp (vcat contents) $$ blankline
+  return $ blankline $$
+           (if isTightList items then vcat else vsep) contents $$
+           blankline
 blockToRST (DefinitionList items) = do
   contents <- mapM definitionListItemToRST items
   -- ensure that sublists have preceding blank line
-  return $ blankline $$ chomp (vcat contents) $$ blankline
+  return $ blankline $$ vcat contents $$ blankline
 
+blockToRST (Figure (ident, classes, _kvs)
+             (Caption _ longCapt) body) = do
+  let figure attr txt (src, tit) = do
+        description <- inlineListToRST txt
+        capt <- blockListToRST longCapt
+        dims <- imageDimsToRST attr
+        let fig = "figure::" <+> literal src
+            alt = if null txt
+                     then if T.null tit
+                              then empty
+                              else ":alt:" <+> literal tit
+                     else ":alt:" <+> description
+            name = if T.null ident
+                      then empty
+                      else "name:" <+> literal ident
+            (_,cls,_) = attr
+            align = case cls of
+                      []               -> empty
+                      ["align-right"]  -> ":align: right"
+                      ["align-left"]   -> ":align: left"
+                      ["align-center"] -> ":align: center"
+                      _ -> ":figclass: " <> literal (T.unwords cls)
+        return $ hang 3 ".. " (fig $$ name $$ alt $$ align $$ dims $+$ capt)
+              $$ blankline
+  case body of
+    [Para  [Image attr txt tgt]] -> figure attr txt tgt
+    [Plain [Image attr txt tgt]] -> figure attr txt tgt
+    _ -> do
+      content <- blockListToRST body
+      return $ blankline $$ (
+        ".. container:: float" <> space <>
+        literal (T.unwords (filter (/= "container") classes))) $$
+        (if T.null ident
+         then blankline
+         else "   :name: " <> literal ident $$ blankline) $$
+        nest 3 content $$
+        blankline
+
 -- | Convert bullet list item (list of blocks) to RST.
-bulletListItemToRST :: PandocMonad m => [Block] -> RST m Doc
+bulletListItemToRST :: PandocMonad m => [Block] -> RST m (Doc Text)
 bulletListItemToRST items = do
   contents <- blockListToRST items
-  return $ hang 3 "-  " $ contents <> cr
+  -- if a list item starts with block quote, we need to insert
+  -- an empty comment to fix the indentation point (#10236)
+  let contents' = case items of
+                    BlockQuote{}:_-> ".." $+$ contents
+                    _ -> contents
+  return $ hang 2 "- " contents' $$
+      if null items || (endsWithPlain items && not (endsWithList items))
+         then cr
+         else blankline
 
 -- | Convert ordered list item (a list of blocks) to RST.
 orderedListItemToRST :: PandocMonad m
-                     => String   -- ^ marker for list item
+                     => Text   -- ^ marker for list item
                      -> [Block]  -- ^ list item (list of blocks)
-                     -> RST m Doc
+                     -> RST m (Doc Text)
 orderedListItemToRST marker items = do
   contents <- blockListToRST items
-  let marker' = marker ++ " "
-  return $ hang (length marker') (text marker') $ contents <> cr
+  let marker' = marker <> " "
+  -- if a list item starts with block quote, we need to insert
+  -- an empty comment to fix the indentation point (#10236)
+  let contents' = case items of
+                    BlockQuote{}:_-> ".." $+$ contents
+                    _ -> contents
+  return $ hang (T.length marker') (literal marker') contents' $$
+      if null items || (endsWithPlain items && not (endsWithList items))
+         then cr
+         else blankline
 
--- | Convert defintion list item (label, list of blocks) to RST.
-definitionListItemToRST :: PandocMonad m => ([Inline], [[Block]]) -> RST m Doc
+endsWithList :: [Block] -> Bool
+endsWithList bs = case lastMay bs of
+                    Just (BulletList{}) -> True
+                    Just (OrderedList{}) -> True
+                    _ -> False
+
+-- | Convert definition list item (label, list of blocks) to RST.
+definitionListItemToRST :: PandocMonad m => ([Inline], [[Block]]) -> RST m (Doc Text)
 definitionListItemToRST (label, defs) = do
   label' <- inlineListToRST label
   contents <- liftM vcat $ mapM blockListToRST defs
-  tabstop <- gets $ writerTabStop . stOptions
-  return $ nowrap label' $$ nest tabstop (nestle contents <> cr)
+  -- if definition list starts with block quote, we need to insert
+  -- an empty comment to fix the indentation point (#10236)
+  let contents' = case defs of
+                    (BlockQuote{}:_):_ -> ".." $+$ contents
+                    _ -> contents
+  return $ nowrap label' $$ nest 3 (nestle contents') $$
+      if isTightList defs
+         then cr
+         else blankline
 
 -- | Format a list of lines as line block.
-linesToLineBlock :: PandocMonad m => [[Inline]] -> RST m Doc
+linesToLineBlock :: PandocMonad m => [[Inline]] -> RST m (Doc Text)
 linesToLineBlock inlineLines = do
   lns <- mapM inlineListToRST inlineLines
   return $
-                      vcat (map (hang 2 (text "| ")) lns) <> blankline
+                      vcat (map (hang 2 (literal "| ")) lns) <> blankline
 
 -- | Convert list of Pandoc block elements to RST.
 blockListToRST' :: PandocMonad m
                 => Bool
                 -> [Block]       -- ^ List of block elements
-                -> RST m Doc
+                -> RST m (Doc Text)
 blockListToRST' topLevel blocks = do
+  -- insert comment between list and quoted blocks, see #4248 and #3675
+  let fixBlocks (b1:b2@(BlockQuote _):bs)
+        | toClose b1 = b1 : commentSep : b2 : fixBlocks bs
+        where
+          toClose Plain{}                  = False
+          toClose Header{}                 = False
+          toClose LineBlock{}              = False
+          toClose HorizontalRule           = False
+          toClose SimpleFigure{}           = True
+          toClose Para{}                   = False
+          toClose _                        = True
+          commentSep  = RawBlock "rst" "..\n\n"
+      fixBlocks (b:bs) = b : fixBlocks bs
+      fixBlocks [] = []
   tl <- gets stTopLevel
-  modify (\s->s{stTopLevel=topLevel, stLastNested=False})
-  res <- vcat `fmap` mapM blockToRST' blocks
+  modify (\s->s{stTopLevel=topLevel})
+  res <- vcat `fmap` mapM blockToRST (fixBlocks blocks)
   modify (\s->s{stTopLevel=tl})
   return res
 
-blockToRST' :: PandocMonad m => Block -> RST m Doc
-blockToRST' (x@BlockQuote{}) = do
-  lastNested <- gets stLastNested
-  res <- blockToRST x
-  modify (\s -> s{stLastNested = True})
-  return $ if lastNested
-              then ".." $+$ res
-              else res
-blockToRST' x = do
-  modify (\s -> s{stLastNested =
-    case x of
-         Para [Image _ _ (_,'f':'i':'g':':':_)] -> True
-         Para{}                                 -> False
-         Plain{}                                -> False
-         Header{}                               -> False
-         LineBlock{}                            -> False
-         HorizontalRule                         -> False
-         _                                      -> True
-    })
-  blockToRST x
-
 blockListToRST :: PandocMonad m
                => [Block]       -- ^ List of block elements
-               -> RST m Doc
+               -> RST m (Doc Text)
 blockListToRST = blockListToRST' False
 
--- | Convert list of Pandoc inline elements to RST.
-inlineListToRST :: PandocMonad m => [Inline] -> RST m Doc
-inlineListToRST lst =
-  mapM inlineToRST (removeSpaceAfterDisplayMath $ insertBS lst) >>=
-    return . hcat
-  where -- remove spaces after displaymath, as they screw up indentation:
+{-
+
+http://docutils.sourceforge.net/docs/ref/rst/restructuredtext.html#directives
+
+According to the terminology used in the spec, a marker includes a
+final whitespace and a block includes the directive arguments. Here
+the variable names have slightly different meanings because we don't
+want to finish the line with a space if there are no arguments, it
+would produce rST that differs from what users expect in a way that's
+not easy to detect
+
+-}
+toRSTDirective :: Doc Text -> Doc Text -> [(Doc Text, Doc Text)] -> Doc Text -> Doc Text
+toRSTDirective typ args options content = marker <> spaceArgs <> cr <> block
+  where marker = ".. " <> typ <> "::"
+        block = nest 3 (fieldList $$
+                        blankline $$
+                        content $$
+                        blankline)
+        spaceArgs = if isEmpty args then "" else " " <> args
+        -- a field list could end up being an empty doc thus being
+        -- omitted by $$
+        fieldList = foldl ($$) "" $ map joinField options
+        -- a field body can contain multiple lines
+        joinField (name, body) = ":" <> name <> ": " <> body
+
+tableToRSTList :: PandocMonad m
+             => [Inline]
+             -> [Alignment]
+             -> [Double]
+             -> [[Block]]
+             -> [[[Block]]]
+             -> RST m (Doc Text)
+tableToRSTList caption _ propWidths headers rows = do
+  captionRST <- inlineListToRST caption
+  opts       <- gets stOptions
+  content    <- listTableContent toWrite
+  pure $ toRSTDirective "list-table" captionRST (directiveOptions opts) content
+  where directiveOptions opts = widths (writerColumns opts) propWidths <>
+                                headerRows
+        toWrite = if noHeaders then rows else headers:rows
+        headerRows = [("header-rows", text $ show (1 :: Int)) | not noHeaders]
+        widths tot pro = [("widths", showWidths tot pro) |
+                          not (null propWidths || all (==0.0) propWidths)]
+        noHeaders = all null headers
+        -- >>> showWidths 70 [0.5, 0.5]
+        -- "35 35"
+        showWidths :: Int -> [Double] -> Doc Text
+        showWidths tot = text . unwords . map (show . toColumns tot)
+        -- toColumns converts a width expressed as a proportion of the
+        -- total into a width expressed as a number of columns
+        toColumns :: Int -> Double -> Int
+        toColumns t p = round (p * fromIntegral t)
+        listTableContent :: PandocMonad m => [[[Block]]] -> RST m (Doc Text)
+        listTableContent = fmap vcat .
+          mapM (fmap (hang 2 (text "* ") . vcat) . mapM bulletListItemToRST)
+
+transformInlines :: [Inline] -> [Inline]
+transformInlines =  insertBS .
+                    filter hasContents .
+                    removeSpaceAfterDisplayMath .
+                    concatMap (transformNested . flatten)
+  where -- empty inlines are not valid RST syntax
+        hasContents :: Inline -> Bool
+        hasContents (Str "")              = False
+        hasContents (Emph [])             = False
+        hasContents (Underline [])        = False
+        hasContents (Strong [])           = False
+        hasContents (Strikeout [])        = False
+        hasContents (Superscript [])      = False
+        hasContents (Subscript [])        = False
+        hasContents (SmallCaps [])        = False
+        hasContents (Quoted _ [])         = False
+        hasContents (Cite _ [])           = False
+        hasContents (Span _ [])           = False
+        hasContents (Link _ [] ("", ""))  = False
+        hasContents (Image _ [] ("", "")) = False
+        hasContents _                     = True
+        -- remove spaces after displaymath, as they screw up indentation:
         removeSpaceAfterDisplayMath (Math DisplayMath x : zs) =
               Math DisplayMath x : dropWhile (==Space) zs
         removeSpaceAfterDisplayMath (x:xs) = x : removeSpaceAfterDisplayMath xs
@@ -408,30 +612,48 @@
               x : insertBS (y : zs)
         insertBS (x:ys) = x : insertBS ys
         insertBS [] = []
+        transformNested :: [Inline] -> [Inline]
+        transformNested = concatMap exportLeadingTrailingSpace
+        exportLeadingTrailingSpace :: Inline -> [Inline]
+        exportLeadingTrailingSpace il
+          | isComplex il =
+             let contents = dropInlineParent il
+                 headSpace = headMay contents == Just Space
+                 lastSpace = lastMay contents == Just Space
+              in (if headSpace then (Space:) else id) .
+                 (if lastSpace then (++ [Space]) else id) $
+                 [setInlineChildren il (stripLeadingTrailingSpace contents)]
+          | otherwise = [il]
+
         surroundComplex :: Inline -> Inline -> Bool
-        surroundComplex (Str s@(_:_)) (Str s'@(_:_)) =
-          case (last s, head s') of
-             ('\'','\'') -> True
-             ('"','"')   -> True
-             ('<','>')   -> True
-             ('[',']')   -> True
-             ('{','}')   -> True
-             _           -> False
+        surroundComplex (Str s) (Str s')
+          | Just (_, c)  <- T.unsnoc s
+          , Just (c', _) <- T.uncons s'
+          = case (c, c') of
+              ('\'','\'') -> True
+              ('"','"')   -> True
+              ('<','>')   -> True
+              ('[',']')   -> True
+              ('{','}')   -> True
+              _           -> False
         surroundComplex _ _ = False
         okAfterComplex :: Inline -> Bool
         okAfterComplex Space = True
         okAfterComplex SoftBreak = True
         okAfterComplex LineBreak = True
-        okAfterComplex (Str (c:_)) = isSpace c || c `elem` ("-.,:;!?\\/'\")]}>–—" :: String)
+        okAfterComplex (Str (T.uncons -> Just (c,_)))
+          = isSpace c || T.any (== c) "-.,:;!?\\/'\")]}>–—"
         okAfterComplex _ = False
         okBeforeComplex :: Inline -> Bool
         okBeforeComplex Space = True
         okBeforeComplex SoftBreak = True
         okBeforeComplex LineBreak = True
-        okBeforeComplex (Str (c:_)) = isSpace c || c `elem` ("-:/'\"<([{–—" :: String)
+        okBeforeComplex (Str (T.unsnoc -> Just (_,c)))
+          = isSpace c || T.any (== c) "-:/'\"<([{–—"
         okBeforeComplex _ = False
         isComplex :: Inline -> Bool
         isComplex (Emph _)        = True
+        isComplex (Underline _)   = True
         isComplex (Strong _)      = True
         isComplex (SmallCaps _)   = True
         isComplex (Strikeout _)   = True
@@ -445,72 +667,171 @@
         isComplex (Span _ (x:_))  = isComplex x
         isComplex _               = False
 
+-- | Flattens nested inlines. Extracts nested inlines and goes through
+-- them either collapsing them in the outer inline container or
+-- pulling them out of it
+flatten :: Inline -> [Inline]
+flatten outer
+  | null contents = [outer]
+  | otherwise     = combineAll contents
+  where contents = dropInlineParent outer
+        combineAll = L.foldl' combine []
+
+        combine :: [Inline] -> Inline -> [Inline]
+        combine f i =
+          case (outer, i) of
+          -- quotes are not rendered using RST inlines, so we can keep
+          -- them and they will be readable and parsable
+          (Quoted _ _, _)          -> keep f i
+          (_, Quoted _ _)          -> keep f i
+          -- spans are not rendered using RST inlines, so we can keep them
+          (Span (_,_,[]) _, _)   -> keep f i
+          (_, Span (_,_,[]) _)   -> keep f i
+          -- inlineToRST handles this case properly so it's safe to keep
+          ( Link{}, Image{})       -> keep f i
+          -- parent inlines would prevent links from being correctly
+          -- parsed, in this case we prioritise the content over the
+          -- style
+          (_, Link{})              -> emerge f i
+          -- always give priority to strong text over emphasis
+          (Emph _, Strong _)       -> emerge f i
+          -- drop all other nested styles
+          (_, _)                   -> collapse f i
+
+        emerge f i = f <> [i]
+        keep f i = appendToLast f [i]
+        collapse f i = appendToLast f $ dropInlineParent i
+
+        appendToLast :: [Inline] -> [Inline] -> [Inline]
+        appendToLast flattened toAppend =
+          case NE.nonEmpty flattened of
+            Nothing -> [setInlineChildren outer toAppend]
+            Just xs ->
+              if isOuter lastFlat
+                 then NE.init xs <> [appendTo lastFlat toAppend]
+                 else flattened <> [setInlineChildren outer toAppend]
+               where
+                lastFlat = NE.last xs
+                appendTo o i = mapNested (<> i) o
+                isOuter i = emptyParent i == emptyParent outer
+                emptyParent i = setInlineChildren i []
+
+mapNested :: ([Inline] -> [Inline]) -> Inline -> Inline
+mapNested f i = setInlineChildren i (f (dropInlineParent i))
+
+dropInlineParent :: Inline -> [Inline]
+dropInlineParent (Link _ i _)    = i
+dropInlineParent (Emph i)        = i
+dropInlineParent (Underline i)   = i
+dropInlineParent (Strong i)      = i
+dropInlineParent (Strikeout i)   = i
+dropInlineParent (Superscript i) = i
+dropInlineParent (Subscript i)   = i
+dropInlineParent (SmallCaps i)   = i
+dropInlineParent (Cite _ i)      = i
+dropInlineParent (Image _ i _)   = i
+dropInlineParent (Span _ i)      = i
+dropInlineParent (Quoted _ i)    = i
+dropInlineParent i               = [i] -- not a parent, like Str or Space
+
+setInlineChildren :: Inline -> [Inline] -> Inline
+setInlineChildren (Link a _ t) i    = Link a i t
+setInlineChildren (Emph _) i        = Emph i
+setInlineChildren (Underline _) i   = Underline i
+setInlineChildren (Strong _) i      = Strong i
+setInlineChildren (Strikeout _) i   = Strikeout i
+setInlineChildren (Superscript _) i = Superscript i
+setInlineChildren (Subscript _) i   = Subscript i
+setInlineChildren (SmallCaps _) i   = SmallCaps i
+setInlineChildren (Quoted q _) i    = Quoted q i
+setInlineChildren (Cite c _) i      = Cite c i
+setInlineChildren (Image a _ t) i   = Image a i t
+setInlineChildren (Span a _) i      = Span a i
+setInlineChildren leaf _            = leaf
+
+inlineListToRST :: PandocMonad m => [Inline] -> RST m (Doc Text)
+inlineListToRST = writeInlines . walk transformInlines
+
+-- | Convert list of Pandoc inline elements to RST.
+writeInlines :: PandocMonad m => [Inline] -> RST m (Doc Text)
+writeInlines lst =
+   hcat <$> mapM inlineToRST lst
+
 -- | Convert Pandoc inline element to RST.
-inlineToRST :: PandocMonad m => Inline -> RST m Doc
+inlineToRST :: PandocMonad m => Inline -> RST m (Doc Text)
+inlineToRST (Span ("",["mark"],[]) ils) = do
+  contents <- writeInlines ils
+  return $ ":mark:`" <> contents <> "`"
 inlineToRST (Span (_,_,kvs) ils) = do
-  contents <- inlineListToRST ils
+  contents <- writeInlines ils
   return $
     case lookup "role" kvs of
-          Just role -> ":" <> text role <> ":`" <> contents <> "`"
+          Just role -> ":" <> literal role <> ":`" <> contents <> "`"
           Nothing   -> contents
 inlineToRST (Emph lst) = do
-  contents <- inlineListToRST lst
+  contents <- writeInlines lst
   return $ "*" <> contents <> "*"
+-- Underline is not supported, fall back to Emph
+inlineToRST (Underline lst) =
+  inlineToRST (Emph lst)
 inlineToRST (Strong lst) = do
-  contents <- inlineListToRST lst
+  contents <- writeInlines lst
   return $ "**" <> contents <> "**"
 inlineToRST (Strikeout lst) = do
-  contents <- inlineListToRST lst
+  contents <- writeInlines lst
   return $ "[STRIKEOUT:" <> contents <> "]"
 inlineToRST (Superscript lst) = do
-  contents <- inlineListToRST lst
+  contents <- writeInlines lst
   return $ ":sup:`" <> contents <> "`"
 inlineToRST (Subscript lst) = do
-  contents <- inlineListToRST lst
+  contents <- writeInlines lst
   return $ ":sub:`" <> contents <> "`"
-inlineToRST (SmallCaps lst) = inlineListToRST lst
+inlineToRST (SmallCaps lst) = writeInlines lst
 inlineToRST (Quoted SingleQuote lst) = do
-  contents <- inlineListToRST lst
+  contents <- writeInlines lst
   opts <- gets stOptions
   if isEnabled Ext_smart opts
      then return $ "'" <> contents <> "'"
      else return $ "‘" <> contents <> "’"
 inlineToRST (Quoted DoubleQuote lst) = do
-  contents <- inlineListToRST lst
+  contents <- writeInlines lst
   opts <- gets stOptions
   if isEnabled Ext_smart opts
      then return $ "\"" <> contents <> "\""
      else return $ "“" <> contents <> "”"
 inlineToRST (Cite _  lst) =
-  inlineListToRST lst
+  writeInlines lst
+inlineToRST (Code (_,["interpreted-text"],[("role",role)]) str) =
+  return $ ":" <> literal role <> ":`" <> literal str <> "`"
 inlineToRST (Code _ str) = do
   opts <- gets stOptions
   -- we trim the string because the delimiters must adjoin a
   -- non-space character; see #3496
   -- we use :literal: when the code contains backticks, since
   -- :literal: allows backslash-escapes; see #3974
-  return $ if '`' `elem` str
-              then ":literal:`" <> text (escapeString opts (trim str)) <> "`"
-              else "``" <> text (trim str) <> "``"
+  return $
+    if T.any (== '`') str
+       then ":literal:`" <> literal (escapeText opts (trim str)) <> "`"
+       else "``" <> literal (trim str) <> "``"
 inlineToRST (Str str) = do
   opts <- gets stOptions
-  return $ text $
+  return $ literal $
     (if isEnabled Ext_smart opts
         then unsmartify opts
-        else id) $ escapeString opts str
+        else id) $ escapeText opts str
 inlineToRST (Math t str) = do
   modify $ \st -> st{ stHasMath = True }
   return $ if t == InlineMath
-              then ":math:`" <> text str <> "`"
-              else if '\n' `elem` str
+              then ":math:`" <> literal str <> "`"
+              else if T.any (== '\n') str
                    then blankline $$ ".. math::" $$
-                        blankline $$ nest 3 (text str) $$ blankline
-                   else blankline $$ (".. math:: " <> text str) $$ blankline
+                        blankline $$ nest 3 (literal str) $$ blankline
+                   else blankline $$ (".. math:: " <> literal str) $$ blankline
 inlineToRST il@(RawInline f x)
-  | f == "rst" = return $ text x
+  | f == "rst" = return $ literal x
   | f == "latex" || f == "tex" = do
       modify $ \st -> st{ stHasRawTeX = True }
-      return $ ":raw-latex:`" <> text x <> "`"
+      return $ ":raw-latex:`" <> literal x <> "`"
   | otherwise  = empty <$ report (InlineNotRendered il)
 inlineToRST LineBreak = return cr -- there's no line break in RST (see Para)
 inlineToRST Space = return space
@@ -523,17 +844,17 @@
 -- autolink
 inlineToRST (Link _ [Str str] (src, _))
   | isURI src &&
-    if "mailto:" `isPrefixOf` src
-       then src == escapeURI ("mailto:" ++ str)
+    if "mailto:" `T.isPrefixOf` src
+       then src == escapeURI ("mailto:" <> str)
        else src == escapeURI str = do
-  let srcSuffix = fromMaybe src (stripPrefix "mailto:" src)
-  return $ text srcSuffix
+  let srcSuffix = fromMaybe src (T.stripPrefix "mailto:" src)
+  return $ literal srcSuffix
 inlineToRST (Link _ [Image attr alt (imgsrc,imgtit)] (src, _tit)) = do
   label <- registerImage attr alt (imgsrc,imgtit) (Just src)
   return $ "|" <> label <> "|"
 inlineToRST (Link _ txt (src, tit)) = do
   useReferenceLinks <- gets $ writerReferenceLinks . stOptions
-  linktext <- inlineListToRST $ B.toList . B.trimInlines . B.fromList $ txt
+  linktext <- writeInlines $ B.toList . B.trimInlines . B.fromList $ txt
   if useReferenceLinks
     then do refs <- gets stLinks
             case lookup txt refs of
@@ -541,11 +862,11 @@
                    if src == src' && tit == tit'
                       then return $ "`" <> linktext <> "`_"
                       else
-                        return $ "`" <> linktext <> " <" <> text src <> ">`__"
+                        return $ "`" <> linktext <> " <" <> literal src <> ">`__"
                  Nothing -> do
                    modify $ \st -> st { stLinks = (txt,(src,tit)):refs }
                    return $ "`" <> linktext <> "`_"
-    else return $ "`" <> linktext <> " <" <> text src <> ">`__"
+    else return $ "`" <> linktext <> " <" <> literal src <> ">`__"
 inlineToRST (Image attr alternate (source, tit)) = do
   label <- registerImage attr alternate (source,tit) Nothing
   return $ "|" <> label <> "|"
@@ -556,27 +877,37 @@
   let ref = show $ length notes + 1
   return $ " [" <> text ref <> "]_"
 
-registerImage :: PandocMonad m => Attr -> [Inline] -> Target -> Maybe String -> RST m Doc
+registerImage :: PandocMonad m => Attr -> [Inline] -> Target -> Maybe Text -> RST m (Doc Text)
 registerImage attr alt (src,tit) mbtarget = do
   pics <- gets stImages
+  imgId <- gets stImageId
+  let getImageName = do
+        modify $ \st -> st{ stImageId = imgId + 1 }
+        return [Str ("image" <> tshow imgId)]
   txt <- case lookup alt pics of
-               Just (a,s,t,mbt) | (a,s,t,mbt) == (attr,src,tit,mbtarget)
-                 -> return alt
-               _ -> do
-                 let alt' = if null alt || alt == [Str ""]
-                               then [Str $ "image" ++ show (length pics)]
-                               else alt
+               Just (a,s,t,mbt) ->
+                 if (a,s,t,mbt) == (attr,src,tit,mbtarget)
+                    then return alt
+                    else do
+                        alt' <- getImageName
+                        modify $ \st -> st { stImages =
+                           (alt', (attr,src,tit, mbtarget)):stImages st }
+                        return alt'
+               Nothing -> do
+                 alt' <- if null alt || alt == [Str ""]
+                            then getImageName
+                            else return alt
                  modify $ \st -> st { stImages =
                         (alt', (attr,src,tit, mbtarget)):stImages st }
                  return alt'
   inlineListToRST txt
 
-imageDimsToRST :: PandocMonad m => Attr -> RST m Doc
+imageDimsToRST :: PandocMonad m => Attr -> RST m (Doc Text)
 imageDimsToRST attr = do
   let (ident, _, _) = attr
-      name = if null ident
+      name = if T.null ident
                 then empty
-                else ":name: " <> text ident
+                else ":name: " <> literal ident
       showDim dir = let cols d = ":" <> text (show dir) <> ": " <> text (show d)
                     in  case dimension dir attr of
                           Just (Percent a) ->
@@ -586,3 +917,74 @@
                           Just dim -> cols dim
                           Nothing  -> empty
   return $ cr <> name $$ showDim Width $$ showDim Height
+
+simpleTable :: PandocMonad m
+            => WriterOptions
+            -> (WriterOptions -> [Block] -> m (Doc Text))
+            -> TableHead
+            -> [TableBody]
+            -> TableFoot
+            -> m (Doc Text)
+simpleTable opts blocksToDoc (TableHead _ headers) tbody (TableFoot _ footers) = do
+  headerDocs <- if allRowsEmpty headers
+                   then return []
+                   else fixEmpties <$> mapM rowToDoc headers
+  rowDocs <- fixEmpties <$> mapM rowToDoc ((tableBodiesToRows tbody) ++ footers)
+  let numChars = maybe 0 maximum . NE.nonEmpty . map (offset . fst)
+  let colWidths = map numChars $ transpose (headerDocs ++ rowDocs)
+  let hline = nowrap $ hsep (map (\n -> literal (T.replicate n "=")) colWidths)
+  let hdr = if allRowsEmpty headers
+               then mempty
+               else hline $$ mapToRow colWidths headerDocs
+  let bdy = mapToRow colWidths rowDocs
+  return $ hdr $$ hline $$ bdy $$ hline
+  where
+    -- can't have empty cells in first column:
+    fixEmpties (d:ds) = fixEmpties' d : ds
+    fixEmpties [] = []
+
+    fixEmpties' ((d, colSpan):ds) = if isEmpty d
+                                     then (literal "\\ ", colSpan) : ds
+                                     else (d, colSpan) : ds
+    fixEmpties' [] = []
+
+    rowToDoc (Row _ cells) = concat <$> mapM cellToDocs cells
+
+    cellToDocs (Cell _ _ _ colSpan blocks) = applyColSpan colSpan <$> (blocksToDoc opts) blocks
+
+    applyColSpan col@(ColSpan colSpan) doc
+      | colSpan > 1 =
+          -- Fill up columns for the col spans by adding empty docs without a ColSpan.
+          let emptyDoc = (literal "", Nothing)
+          in  (doc, Just col) : replicate (colSpan - 1) emptyDoc
+      | otherwise = [(doc, Just col)]
+
+    mapToRow colWidths = vcat . concatMap (toRow colWidths)
+
+    toRow colWidths rowDocsWithColSpans =
+      let (rowDocs, colSpans) = unzip rowDocsWithColSpans
+          row = intersperseDivider $ zipWith lblock colWidths rowDocs
+          colSpanRow = intersperseDivider $ writeColSpans colSpans colWidths
+      in  if any (maybe False (> 1)) colSpans
+           then [row, colSpanRow]
+           else [row] -- Don't write out col spans if they are all just 1.
+
+    intersperseDivider = mconcat . intersperse (lblock 1 " ")
+
+    -- Write col span dashes to match the length of the col widths.
+    writeColSpans [] _ = []
+    writeColSpans _ [] = []
+    writeColSpans (Nothing : remainingColSpans) colWidths = writeColSpans remainingColSpans colWidths
+    writeColSpans (Just (ColSpan colSpan) : remainingColSpans) colWidths =
+      let (colWidths', remainingColWidths) = splitAt colSpan colWidths
+      in  writeColSpanDashes colWidths' : writeColSpans remainingColSpans remainingColWidths
+
+    writeColSpanDashes colWidths =
+      let colWidthsLength = length colWidths
+          colWidthsSum = sum colWidths
+          dashLength = if colWidthsLength > 1
+            -- Offset by 1 for the white spaces between columns so that the col
+            -- span dashes align with the end of the columns correctly.
+            then colWidthsSum + colWidthsLength - 1
+            else colWidthsSum
+      in  literal $ T.replicate dashLength "-"
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,25 +1,8 @@
 {-# LANGUAGE ScopedTypeVariables #-}
-{-
-Copyright (C) 2006-2017 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 OverloadedStrings   #-}
 {- |
    Module      : Text.Pandoc.Writers.RTF
-   Copyright   : Copyright (C) 2006-2017 John MacFarlane
+   Copyright   : Copyright (C) 2006-2024 John MacFarlane
    License     : GNU GPL, version 2 or above
 
    Maintainer  : John MacFarlane <jgm@berkeley.edu>
@@ -31,21 +14,22 @@
 module Text.Pandoc.Writers.RTF ( writeRTF
                                ) where
 import Control.Monad.Except (catchError, throwError)
+import Control.Monad
 import qualified Data.ByteString as B
-import Data.Char (chr, isDigit, ord)
-import Data.List (intercalate, isSuffixOf)
+import Data.Char (chr, isDigit, ord, isAlphaNum)
 import qualified Data.Map as M
 import Data.Text (Text)
 import qualified Data.Text as T
-import Text.Pandoc.Class (PandocMonad, report)
-import qualified Text.Pandoc.Class as P
+import Text.Pandoc.Class.PandocMonad (PandocMonad, report)
+import qualified Text.Pandoc.Class.PandocMonad as P
 import Text.Pandoc.Definition
 import Text.Pandoc.Error
 import Text.Pandoc.ImageSize
 import Text.Pandoc.Logging
 import Text.Pandoc.Options
 import Text.Pandoc.Shared
-import Text.Pandoc.Templates (renderTemplate')
+import Text.Pandoc.Templates (renderTemplate)
+import Text.DocLayout (render, literal)
 import Text.Pandoc.Walk
 import Text.Pandoc.Writers.Math
 import Text.Pandoc.Writers.Shared
@@ -59,29 +43,30 @@
   (do result <- P.fetchItem src
       case result of
            (imgdata, Just mime)
-             | mime == "image/jpeg" || mime == "image/png" -> do
-             let bytes = map (printf "%02x") $ B.unpack imgdata
+             | mime' <- T.takeWhile (/=';') mime
+             , mime' == "image/jpeg" || mime' == "image/png" -> do
+             let bytes = map (T.pack . printf "%02x") $ B.unpack imgdata
              filetype <-
-                case mime of
+                case mime' of
                      "image/jpeg" -> return "\\jpegblip"
                      "image/png"  -> return "\\pngblip"
                      _            -> throwError $
                                          PandocShouldNeverHappenError $
-                                         "Unknown file type " ++ mime
+                                         "Unknown file type " <> mime
              sizeSpec <-
                 case imageSize opts imgdata of
                      Left msg -> do
                        report $ CouldNotDetermineImageSize src msg
                        return ""
-                     Right sz -> return $ "\\picw" ++ show xpx ++
-                                "\\pich" ++ show ypx ++
-                                "\\picwgoal" ++ show (floor (xpt * 20) :: Integer)
-                                ++ "\\pichgoal" ++ show (floor (ypt * 20) :: Integer)
+                     Right sz -> return $ "\\picw" <> tshow xpx <>
+                                "\\pich" <> tshow ypx <>
+                                "\\picwgoal" <> tshow (floor (xpt * 20) :: Integer)
+                                <> "\\pichgoal" <> tshow (floor (ypt * 20) :: Integer)
                         -- twip = 1/1440in = 1/20pt
                         where (xpx, ypx) = sizeInPixels sz
                               (xpt, ypt) = desiredSizeInPoints opts attr sz
-             let raw = "{\\pict" ++ filetype ++ sizeSpec ++ "\\bin " ++
-                        concat bytes ++ "}"
+             let raw = "{\\pict" <> filetype <> sizeSpec <> " " <>
+                        T.concat bytes <> "}"
              if B.null imgdata
                 then do
                   report $ CouldNotFetchResource src "image contained no data"
@@ -94,7 +79,7 @@
              report $ CouldNotDetermineMimeType src
              return x)
   (\e -> do
-     report $ CouldNotFetchResource src (show e)
+     report $ CouldNotFetchResource src $ tshow e
      return x)
 rtfEmbedImage _ x = return x
 
@@ -111,114 +96,103 @@
                     . M.adjust toPlain "author"
                     . M.adjust toPlain "date"
                     $ metamap
-  metadata <- metaToJSON options
-              (fmap concat . mapM (blockToRTF 0 AlignDefault))
-              inlinesToRTF
+  metadata <- metaToContext options
+              (fmap (literal . T.concat) .
+                mapM (blockToRTF 0 AlignDefault))
+              (fmap literal . inlinesToRTF)
               meta'
   body <- blocksToRTF 0 AlignDefault blocks
-  let isTOCHeader (Header lev _ _) = lev <= writerTOCDepth options
-      isTOCHeader _                = False
-  toc <- tableOfContents $ filter isTOCHeader blocks
+  toc <- blocksToRTF 0 AlignDefault [toTableOfContents options blocks]
   let context = defField "body" body
               $ defField "spacer" spacer
-              $(if writerTableOfContents options
-                   then defField "table-of-contents" toc
-                        -- for backwards compatibility,
-                        -- we populate toc with the contents
-                        -- of the toc rather than a boolean:
-                        . defField "toc" toc
-                   else id) metadata
-  T.pack <$>
-      case writerTemplate options of
-           Just tpl -> renderTemplate' tpl context
-           Nothing  -> return $
-                       case reverse body of
-                            ('\n':_) -> body
-                            _        -> body ++ "\n"
-
--- | Construct table of contents from list of header blocks.
-tableOfContents :: PandocMonad m => [Block] -> m String
-tableOfContents headers = do
-  let contents = map elementToListItem $ hierarchicalize headers
-  blocksToRTF 0 AlignDefault
-      [Header 1 nullAttr [Str "Contents"], BulletList contents]
-
-elementToListItem :: Element -> [Block]
-elementToListItem (Blk _) = []
-elementToListItem (Sec _ _ _ sectext subsecs) = Plain sectext :
-  if null subsecs
-     then []
-     else [BulletList (map elementToListItem subsecs)]
+              $ (if writerTableOfContents options
+                    then defField "table-of-contents" toc
+                         -- for backwards compatibility,
+                         -- we populate toc with the contents
+                         -- of the toc rather than a boolean:
+                         . defField "toc" toc
+                    else id) metadata
+  return $
+    case writerTemplate options of
+       Just tpl -> render Nothing $ renderTemplate tpl context
+       Nothing  -> case T.unsnoc body of
+                        Just (_,'\n') -> body
+                        _             -> body <> T.singleton '\n'
 
 -- | Convert unicode characters (> 127) into rich text format representation.
-handleUnicode :: String -> String
-handleUnicode [] = []
-handleUnicode (c:cs) =
+handleUnicode :: Text -> Text
+handleUnicode = T.concatMap $ \c ->
   if ord c > 127
      then if surrogate c
           then let x = ord c - 0x10000
                    (q, r) = x `divMod` 0x400
                    upper = q + 0xd800
                    lower = r + 0xDC00
-               in enc (chr upper) ++ enc (chr lower) ++ handleUnicode cs
-          else enc c ++ handleUnicode cs
-     else c:handleUnicode cs
+               in enc (chr upper) <> enc (chr lower)
+          else enc c
+     else T.singleton c
   where
     surrogate x = not (   (0x0000 <= ord x && ord x <= 0xd7ff)
                        || (0xe000 <= ord x && ord x <= 0xffff) )
-    enc x = '\\':'u':show (ord x) ++ "?"
+    enc x = "\\u" <> tshow (ord x) <> " ?"
 
 -- | Escape special characters.
-escapeSpecial :: String -> String
-escapeSpecial = escapeStringUsing $
-  [ ('\t',"\\tab ")
-  , ('\8216',"\\u8216'")
-  , ('\8217',"\\u8217'")
-  , ('\8220',"\\u8220\"")
-  , ('\8221',"\\u8221\"")
-  , ('\8211',"\\u8211-")
-  , ('\8212',"\\u8212-")
-  ] ++ backslashEscapes "{\\}"
+escapeSpecial :: Text -> Text
+escapeSpecial t
+  | T.all isAlphaNum t = t
+  | otherwise          = T.concatMap escChar t
+ where
+  escChar '\t' = "\\tab "
+  escChar '\8216' = "\\u8216'"
+  escChar '\8217' = "\\u8217'"
+  escChar '\8220' = "\\u8220\""
+  escChar '\8221' = "\\u8221\""
+  escChar '\8211' = "\\u8211-"
+  escChar '\8212' = "\\u8212-"
+  escChar '{'     = "\\{"
+  escChar '}'     = "\\}"
+  escChar '\\'    = "\\\\"
+  escChar c       = T.singleton c
 
 -- | Escape strings as needed for rich text format.
-stringToRTF :: String -> String
+stringToRTF :: Text -> Text
 stringToRTF = handleUnicode . escapeSpecial
 
 -- | Escape things as needed for code block in RTF.
-codeStringToRTF :: String -> String
-codeStringToRTF str = intercalate "\\line\n" $ lines (stringToRTF str)
+codeStringToRTF :: Text -> Text
+codeStringToRTF str = T.intercalate "\\line\n" $ T.lines (stringToRTF str)
 
 -- | Make a paragraph with first-line indent, block indent, and space after.
 rtfParSpaced :: Int       -- ^ space after (in twips)
              -> Int       -- ^ block indent (in twips)
              -> Int       -- ^ first line indent (relative to block) (in twips)
              -> Alignment -- ^ alignment
-             -> String    -- ^ string with content
-             -> String
+             -> Text    -- ^ string with content
+             -> Text
 rtfParSpaced spaceAfter indent firstLineIndent alignment content =
   let alignString = case alignment of
                            AlignLeft    -> "\\ql "
                            AlignRight   -> "\\qr "
                            AlignCenter  -> "\\qc "
                            AlignDefault -> "\\ql "
-  in  "{\\pard " ++ alignString ++
-      "\\f0 \\sa" ++ show spaceAfter ++ " \\li" ++ show indent ++
-      " \\fi" ++ show firstLineIndent ++ " " ++ content ++ "\\par}\n"
+  in  "{\\pard " <> alignString <>
+      "\\f0 \\sa" <> tshow spaceAfter <> " \\li" <> T.pack (show indent) <>
+      " \\fi" <> tshow firstLineIndent <> " " <> content <> "\\par}\n"
 
 -- | Default paragraph.
 rtfPar :: Int       -- ^ block indent (in twips)
        -> Int       -- ^ first line indent (relative to block) (in twips)
        -> Alignment -- ^ alignment
-       -> String    -- ^ string with content
-       -> String
+       -> Text    -- ^ string with content
+       -> Text
 rtfPar = rtfParSpaced 180
 
 -- | Compact paragraph (e.g. for compact list items).
 rtfCompact ::  Int       -- ^ block indent (in twips)
            ->  Int       -- ^ first line indent (relative to block) (in twips)
            ->  Alignment -- ^ alignment
-           ->  String    -- ^ string with content
-           ->  String
+           ->  Text    -- ^ string with content
+           ->  Text
 rtfCompact = rtfParSpaced 0
 
 -- number of twips to indent
@@ -229,13 +203,13 @@
 listIncrement = 360
 
 -- | Returns appropriate bullet list marker for indent level.
-bulletMarker :: Int -> String
+bulletMarker :: Int -> Text
 bulletMarker indent = case indent `mod` 720 of
                              0 -> "\\bullet "
                              _ -> "\\endash "
 
 -- | Returns appropriate (list of) ordered list markers for indent level.
-orderedMarkers :: Int -> ListAttributes -> [String]
+orderedMarkers :: Int -> ListAttributes -> [Text]
 orderedMarkers indent (start, style, delim) =
   if style == DefaultStyle && delim == DefaultDelim
      then case indent `mod` 720 of
@@ -247,16 +221,15 @@
             => Int
             -> Alignment
             -> [Block]
-            -> m String
-blocksToRTF indent align = fmap concat . mapM (blockToRTF indent align)
+            -> m Text
+blocksToRTF indent align = fmap T.concat . mapM (blockToRTF indent align)
 
 -- | Convert Pandoc block element to RTF.
 blockToRTF :: PandocMonad m
            => Int       -- ^ indent level
            -> Alignment -- ^ alignment
            -> Block     -- ^ block to convert
-           -> m String
-blockToRTF _ _ Null = return ""
+           -> m Text
 blockToRTF indent alignment (Div _ bs) =
   blocksToRTF indent alignment bs
 blockToRTF indent alignment (Plain lst) =
@@ -268,156 +241,169 @@
 blockToRTF indent alignment (BlockQuote lst) =
   blocksToRTF (indent + indentIncrement) alignment lst
 blockToRTF indent _ (CodeBlock _ str) =
-  return $ rtfPar indent 0 AlignLeft ("\\f1 " ++ codeStringToRTF str)
+  return $ rtfPar indent 0 AlignLeft ("\\f1 " <> codeStringToRTF str)
 blockToRTF _ _ b@(RawBlock f str)
   | f == Format "rtf" = return str
   | otherwise         = do
       report $ BlockNotRendered b
       return ""
-blockToRTF indent alignment (BulletList lst) = (spaceAtEnd . concat) <$>
+blockToRTF indent alignment (BulletList lst) = spaceAtEnd . T.concat <$>
   mapM (listItemToRTF alignment indent (bulletMarker indent)) lst
 blockToRTF indent alignment (OrderedList attribs lst) =
-  (spaceAtEnd . concat) <$>
-   mapM (uncurry (listItemToRTF alignment indent))
-   (zip (orderedMarkers indent attribs) lst)
-blockToRTF indent alignment (DefinitionList lst) = (spaceAtEnd . concat) <$>
+  spaceAtEnd . T.concat <$>
+   zipWithM (listItemToRTF alignment indent) (orderedMarkers indent attribs) lst
+blockToRTF indent alignment (DefinitionList lst) = spaceAtEnd . T.concat <$>
   mapM (definitionListItemToRTF alignment indent) lst
 blockToRTF indent _ HorizontalRule = return $
   rtfPar indent 0 AlignCenter "\\emdash\\emdash\\emdash\\emdash\\emdash"
 blockToRTF indent alignment (Header level _ lst) = do
   contents <- inlinesToRTF lst
   return $ rtfPar indent 0 alignment $
-             "\\b \\fs" ++ show (40 - (level * 4)) ++ " " ++ contents
-blockToRTF indent alignment (Table caption aligns sizes headers rows) = do
+             "\\outlinelevel" <> tshow (level - 1) <>
+             " \\b \\fs" <> tshow (40 - (level * 4)) <> " " <> contents
+blockToRTF indent alignment (Table _ blkCapt specs thead tbody tfoot) = do
+  let (caption, aligns, sizes, headers, rows) = toLegacyTable blkCapt specs thead tbody tfoot
   caption' <- inlinesToRTF caption
   header' <- if all null headers
                 then return ""
                 else tableRowToRTF True indent aligns sizes headers
-  rows' <- concat <$> mapM (tableRowToRTF False indent aligns sizes) rows
-  return $ header' ++ rows' ++ rtfPar indent 0 alignment caption'
+  rows' <- T.concat <$> mapM (tableRowToRTF False indent aligns sizes) rows
+  return $ header' <> rows' <> rtfPar indent 0 alignment caption'
+blockToRTF indent alignment (Figure attr capt body) =
+  blockToRTF indent alignment $ figureDiv attr capt body
 
 tableRowToRTF :: PandocMonad m
-              => Bool -> Int -> [Alignment] -> [Double] -> [[Block]] -> m String
+              => Bool -> Int -> [Alignment] -> [Double] -> [[Block]] -> m Text
 tableRowToRTF header indent aligns sizes' cols = do
   let totalTwips = 6 * 1440 -- 6 inches
   let sizes = if all (== 0) sizes'
                  then replicate (length cols) (1.0 / fromIntegral (length cols))
                  else sizes'
-  columns <- concat <$> mapM (uncurry (tableItemToRTF indent))
-                         (zip aligns cols)
-  let rightEdges = tail $ scanl (\sofar new -> sofar + floor (new * totalTwips))
-                                (0 :: Integer) sizes
+  columns <- T.concat <$>
+     zipWithM (tableItemToRTF indent) aligns cols
+  let rightEdges = drop 1 $
+                    scanl (\sofar new -> sofar + floor (new * totalTwips))
+                          (0 :: Integer) sizes
   let cellDefs = map (\edge -> (if header
                                    then "\\clbrdrb\\brdrs"
-                                   else "") ++ "\\cellx" ++ show edge)
+                                   else "") <> "\\cellx" <> tshow edge)
                      rightEdges
-  let start = "{\n\\trowd \\trgaph120\n" ++ concat cellDefs ++ "\n" ++
+  let start = "{\n\\trowd \\trgaph120\n" <> T.concat cellDefs <> "\n" <>
               "\\trkeep\\intbl\n{\n"
   let end = "}\n\\intbl\\row}\n"
-  return $ start ++ columns ++ end
+  return $ start <> columns <> end
 
-tableItemToRTF :: PandocMonad m => Int -> Alignment -> [Block] -> m String
+tableItemToRTF :: PandocMonad m => Int -> Alignment -> [Block] -> m Text
 tableItemToRTF indent alignment item = do
   contents <- blocksToRTF indent alignment item
-  return $ "{" ++ substitute "\\pard" "\\pard\\intbl" contents ++ "\\cell}\n"
+  return $ "{" <> T.replace "\\pard" "\\pard\\intbl" contents <> "\\cell}\n"
 
 -- | Ensure that there's the same amount of space after compact
 -- lists as after regular lists.
-spaceAtEnd :: String -> String
-spaceAtEnd str =
-  if "\\par}\n" `isSuffixOf` str
-     then take (length str - 6) str ++ "\\sa180\\par}\n"
-     else str
+spaceAtEnd :: Text -> Text
+spaceAtEnd str = maybe str (<> "\\sa180\\par}\n") $ T.stripSuffix "\\par}\n" str
 
 -- | Convert list item (list of blocks) to RTF.
 listItemToRTF :: PandocMonad m
               => Alignment  -- ^ alignment
               -> Int        -- ^ indent level
-              -> String     -- ^ list start marker
+              -> Text     -- ^ list start marker
               -> [Block]    -- ^ list item (list of blocks)
-              -> m String
+              -> m Text
 listItemToRTF alignment indent marker [] = return $
   rtfCompact (indent + listIncrement) (negate listIncrement) alignment
-             (marker ++ "\\tx" ++ show listIncrement ++ "\\tab ")
-listItemToRTF alignment indent marker list = do
-  (first:rest) <- mapM (blockToRTF (indent + listIncrement) alignment) list
-  let listMarker = "\\fi" ++ show (negate listIncrement) ++ " " ++ marker ++
-                   "\\tx" ++ show listIncrement ++ "\\tab"
-  let insertListMarker ('\\':'f':'i':'-':d:xs) | isDigit d =
-        listMarker ++ dropWhile isDigit xs
-      insertListMarker ('\\':'f':'i':d:xs) | isDigit d =
-        listMarker ++ dropWhile isDigit xs
-      insertListMarker (x:xs) =
-        x : insertListMarker xs
-      insertListMarker [] = []
+             (marker <> "\\tx" <> tshow listIncrement <> "\\tab ")
+listItemToRTF alignment indent marker (listFirst:listRest) = do
+  let f = blockToRTF (indent + listIncrement) alignment
+  first <- f listFirst
+  rest <- mapM f listRest
+  let listMarker = "\\fi" <> tshow (negate listIncrement) <> " " <> marker <>
+                   "\\tx" <> tshow listIncrement <> "\\tab"
+  -- Find the first occurrence of \\fi or \\fi-, then replace it and the following
+  -- digits with the list marker.
+  let insertListMarker t = case popDigit $ optionDash $ T.drop 3 suff of
+        Just suff' -> pref <> listMarker <> T.dropWhile isDigit suff'
+        Nothing    -> t
+        where
+          (pref, suff) = T.breakOn "\\fi" t
+          optionDash x = case T.uncons x of
+            Just ('-', xs) -> xs
+            _              -> x
+          popDigit x
+            | Just (d, xs) <- T.uncons x
+            , isDigit d = Just xs
+            | otherwise = Nothing
    -- insert the list marker into the (processed) first block
-  return $ insertListMarker first ++ concat rest
+  return $ insertListMarker first <> T.concat rest
 
 -- | Convert definition list item (label, list of blocks) to RTF.
 definitionListItemToRTF :: PandocMonad m
                         => Alignment          -- ^ alignment
                         -> Int                -- ^ indent level
                         -> ([Inline],[[Block]]) -- ^ list item (list of blocks)
-                        -> m String
+                        -> m Text
 definitionListItemToRTF alignment indent (label, defs) = do
   labelText <- blockToRTF indent alignment (Plain label)
   itemsText <- blocksToRTF (indent + listIncrement) alignment (concat defs)
-  return $ labelText ++ itemsText
+  return $ labelText <> itemsText
 
 -- | Convert list of inline items to RTF.
 inlinesToRTF :: PandocMonad m
              => [Inline]   -- ^ list of inlines to convert
-             -> m String
-inlinesToRTF lst = concat <$> mapM inlineToRTF lst
+             -> m Text
+inlinesToRTF lst = T.concat <$> mapM inlineToRTF lst
 
 -- | Convert inline item to RTF.
 inlineToRTF :: PandocMonad m
             => Inline         -- ^ inline to convert
-            -> m String
+            -> m Text
 inlineToRTF (Span _ lst) = inlinesToRTF lst
 inlineToRTF (Emph lst) = do
   contents <- inlinesToRTF lst
-  return $ "{\\i " ++ contents ++ "}"
+  return $ "{\\i " <> contents <> "}"
+inlineToRTF (Underline lst) = do
+  contents <- inlinesToRTF lst
+  return $ "{\\ul " <> contents <> "}"
 inlineToRTF (Strong lst) = do
   contents <- inlinesToRTF lst
-  return $ "{\\b " ++ contents ++ "}"
+  return $ "{\\b " <> contents <> "}"
 inlineToRTF (Strikeout lst) = do
   contents <- inlinesToRTF lst
-  return $ "{\\strike " ++ contents ++ "}"
+  return $ "{\\strike " <> contents <> "}"
 inlineToRTF (Superscript lst) = do
   contents <- inlinesToRTF lst
-  return $ "{\\super " ++ contents ++ "}"
+  return $ "{\\super " <> contents <> "}"
 inlineToRTF (Subscript lst) = do
   contents <- inlinesToRTF lst
-  return $ "{\\sub " ++ contents ++ "}"
+  return $ "{\\sub " <> contents <> "}"
 inlineToRTF (SmallCaps lst) = do
   contents <- inlinesToRTF lst
-  return $ "{\\scaps " ++ contents ++ "}"
+  return $ "{\\scaps " <> contents <> "}"
 inlineToRTF (Quoted SingleQuote lst) = do
   contents <- inlinesToRTF lst
-  return $ "\\u8216'" ++ contents ++ "\\u8217'"
+  return $ "\\u8216'" <> contents <> "\\u8217'"
 inlineToRTF (Quoted DoubleQuote lst) = do
   contents <- inlinesToRTF lst
-  return $ "\\u8220\"" ++ contents ++ "\\u8221\""
-inlineToRTF (Code _ str) = return $ "{\\f1 " ++ codeStringToRTF str ++ "}"
+  return $ "\\u8220\"" <> contents <> "\\u8221\""
+inlineToRTF (Code _ str) = return $ "{\\f1 " <> codeStringToRTF str <> "}"
 inlineToRTF (Str str) = return $ stringToRTF str
 inlineToRTF (Math t str) = texMathToInlines t str >>= inlinesToRTF
 inlineToRTF (Cite _ lst) = inlinesToRTF lst
 inlineToRTF il@(RawInline f str)
   | f == Format "rtf" = return str
   | otherwise         = do
-      return $ InlineNotRendered il
+      report $ InlineNotRendered il
       return ""
 inlineToRTF LineBreak = return "\\line "
 inlineToRTF SoftBreak = return " "
 inlineToRTF Space = return " "
 inlineToRTF (Link _ text (src, _)) = do
   contents <- inlinesToRTF text
-  return $ "{\\field{\\*\\fldinst{HYPERLINK \"" ++ codeStringToRTF src ++
-    "\"}}{\\fldrslt{\\ul\n" ++ contents ++ "\n}}}\n"
+  return $ "{\\field{\\*\\fldinst{HYPERLINK \"" <> codeStringToRTF src <>
+    "\"}}{\\fldrslt{\\ul\n" <> contents <> "\n}}}\n"
 inlineToRTF (Image _ _ (source, _)) =
-  return $ "{\\cf1 [image: " ++ source ++ "]\\cf0}"
+  return $ "{\\cf1 [image: " <> source <> "]\\cf0}"
 inlineToRTF (Note contents) = do
-  body <- concat <$> mapM (blockToRTF 0 AlignDefault) contents
-  return $ "{\\super\\chftn}{\\*\\footnote\\chftn\\~\\plain\\pard " ++
-    body ++ "}"
+  body <- T.concat <$> mapM (blockToRTF 0 AlignDefault) contents
+  return $ "{\\super\\chftn}{\\*\\footnote\\chftn\\~\\plain\\pard " <>
+    body <> "}"
diff --git a/src/Text/Pandoc/Writers/Roff.hs b/src/Text/Pandoc/Writers/Roff.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Writers/Roff.hs
@@ -0,0 +1,129 @@
+{-# LANGUAGE OverloadedStrings #-}
+{- |
+   Module      : Text.Pandoc.Writers.Roff
+   Copyright   : Copyright (C) 2007-2024 John MacFarlane
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : John MacFarlane <jgm@berkeley.edu>
+   Stability   : alpha
+   Portability : portable
+
+Common functions for roff writers (man, ms).
+-}
+
+module Text.Pandoc.Writers.Roff (
+      WriterState(..)
+    , defaultWriterState
+    , MS
+    , Note
+    , EscapeMode(..)
+    , escapeString
+    , withFontFeature
+    ) where
+import Data.Char (ord, isAscii)
+import Control.Monad.State.Strict
+import qualified Data.Map as Map
+import Data.Text (Text)
+import qualified Data.Text as Text
+import Data.String
+import Data.Maybe (fromMaybe)
+import Text.Pandoc.Class.PandocMonad (PandocMonad)
+import Text.Pandoc.Definition
+import Text.DocLayout
+import Text.Printf (printf)
+import Text.Pandoc.RoffChar (standardEscapes, characterCodes)
+
+data WriterState = WriterState { stHasInlineMath :: Bool
+                               , stFirstPara     :: Bool
+                               , stNotes         :: [Note]
+                               , stSmallCaps     :: Bool
+                               , stHighlighting  :: Bool
+                               , stInHeader      :: Bool
+                               , stFontFeatures  :: Map.Map Char Bool
+                               , stHasTables     :: Bool
+                               }
+
+defaultWriterState :: WriterState
+defaultWriterState = WriterState{ stHasInlineMath = False
+                                , stFirstPara     = True
+                                , stNotes         = []
+                                , stSmallCaps     = False
+                                , stHighlighting  = False
+                                , stInHeader      = False
+                                , stFontFeatures  = Map.fromList [
+                                                       ('I',False)
+                                                     , ('B',False)
+                                                     , ('C',False)
+                                                     , ('V',False)
+                                                     ]
+                                , stHasTables     = False
+                                }
+
+type Note = [Block]
+
+type MS = StateT WriterState
+
+data EscapeMode = AllowUTF8        -- ^ use preferred man escapes
+                | AsciiOnly        -- ^ escape everything
+                deriving Show
+
+essentialEscapes :: Map.Map Char Text
+essentialEscapes = Map.fromList standardEscapes
+
+-- | Escape special characters for roff. If the first parameter is
+-- True, escape @-@ as @\-@, as required by current versions of groff man;
+-- otherwise leave it unescaped, as neededfor ms.
+escapeString :: Bool -> EscapeMode -> Text -> Text
+escapeString escapeHyphen e = Text.concat . escapeString' e . Text.unpack
+  where
+    escapeString' _ [] = []
+    escapeString' escapeMode ('\n':'.':xs) =
+      "\n\\&." : escapeString' escapeMode xs
+    -- see #10533; we need to escape hyphens as \- in man but not in ms:
+    escapeString' escapeMode ('-':xs) | escapeHyphen =
+      "\\-" : escapeString' escapeMode xs
+    escapeString' escapeMode (x:xs) =
+      case Map.lookup x essentialEscapes of
+        Just s  -> s : escapeString' escapeMode xs
+        Nothing
+          | isAscii x -> Text.singleton x : escapeString' escapeMode xs
+          | otherwise ->
+              (case escapeMode of
+                AllowUTF8 -> Text.singleton x
+                AsciiOnly ->
+                   case Map.lookup x characterCodeMap of
+                      Just t
+                        | Text.length t == 2 -> "\\(" <> t -- see #10716
+                        | otherwise -> "\\C'" <> t <> "'"
+                      Nothing ->
+                        "\\C'" <> Text.pack (printf "u%04X" (ord x)) <> "'")
+               : escapeString' escapeMode xs
+
+characterCodeMap :: Map.Map Char Text
+characterCodeMap = Map.fromList characterCodes
+
+fontChange :: (HasChars a, IsString a, PandocMonad m) => MS m (Doc a)
+fontChange = do
+  features <- gets stFontFeatures
+  inHeader <- gets stInHeader
+  let filling = ['C' | fromMaybe False $ Map.lookup 'C' features] ++
+                ['V' | fromMaybe False $ Map.lookup 'V' features] ++
+                ['B' | inHeader ||
+                       fromMaybe False (Map.lookup 'B' features)] ++
+                ['I' | fromMaybe False $ Map.lookup 'I' features]
+  return $
+    case filling of
+      [] -> text "\\f[R]"
+      -- see #9020. C is not a font, use CR.
+      ['C'] -> text "\\f[CR]"
+      _ -> text $ "\\f[" ++ filling ++ "]"
+
+withFontFeature :: (HasChars a, IsString a, PandocMonad m)
+                => Char -> MS m (Doc a) -> MS m (Doc a)
+withFontFeature c action = do
+  modify $ \st -> st{ stFontFeatures = Map.adjust not c $ stFontFeatures st }
+  begin <- fontChange
+  d <- action
+  modify $ \st -> st{ stFontFeatures = Map.adjust not c $ stFontFeatures st }
+  end <- fontChange
+  return $ begin <> d <> end
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,310 +1,967 @@
-{-# LANGUAGE OverloadedStrings #-}
-{-
-Copyright (C) 2013-2017 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-2017 John MacFarlane
-   License     : GNU GPL, version 2 or above
-
-   Maintainer  : John MacFarlane <jgm@berkeley.edu>
-   Stability   : alpha
-   Portability : portable
-
-Shared utility functions for pandoc writers.
--}
-module Text.Pandoc.Writers.Shared (
-                       metaToJSON
-                     , metaToJSON'
-                     , addVariablesToJSON
-                     , getField
-                     , setField
-                     , resetField
-                     , defField
-                     , tagWithAttrs
-                     , fixDisplayMath
-                     , unsmartify
-                     , gridTable
-                     )
-where
-import Control.Monad (zipWithM)
-import Data.Aeson (FromJSON (..), Result (..), ToJSON (..), Value (Object),
-                   encode, fromJSON)
-import qualified Data.HashMap.Strict as H
-import Data.List (groupBy, intersperse, transpose)
-import qualified Data.Map as M
-import Data.Maybe (isJust)
-import qualified Data.Text as T
-import qualified Data.Traversable as Traversable
-import qualified Text.Pandoc.Builder as Builder
-import Text.Pandoc.Definition
-import Text.Pandoc.Options
-import Text.Pandoc.Pretty
-import Text.Pandoc.UTF8 (toStringLazy)
-import Text.Pandoc.XML (escapeStringForXML)
-
--- | Create JSON value for template from a 'Meta' and an association list
--- of variables, specified at the command line or in the writer.
--- Variables overwrite metadata fields with the same names.
--- If multiple variables are set with the same name, a list is
--- assigned.  Does nothing if 'writerTemplate' is Nothing.
-metaToJSON :: (Functor m, Monad m, ToJSON a)
-           => WriterOptions
-           -> ([Block] -> m a)
-           -> ([Inline] -> m a)
-           -> Meta
-           -> m Value
-metaToJSON opts blockWriter inlineWriter meta
-  | isJust (writerTemplate opts) =
-    addVariablesToJSON opts <$> metaToJSON' blockWriter inlineWriter meta
-  | otherwise = return (Object H.empty)
-
--- | Like 'metaToJSON', but does not include variables and is
--- not sensitive to 'writerTemplate'.
-metaToJSON' :: (Functor m, Monad m, ToJSON a)
-           => ([Block] -> m a)
-           -> ([Inline] -> m a)
-           -> Meta
-           -> m Value
-metaToJSON' blockWriter inlineWriter (Meta metamap) = do
-  renderedMap <- Traversable.mapM
-                 (metaValueToJSON blockWriter inlineWriter)
-                 metamap
-  return $ M.foldrWithKey defField (Object H.empty) renderedMap
-
--- | Add variables to JSON object, replacing any existing values.
--- Also include @meta-json@, a field containing a string representation
--- of the original JSON object itself, prior to addition of variables.
-addVariablesToJSON :: WriterOptions -> Value -> Value
-addVariablesToJSON opts metadata =
-  foldl (\acc (x,y) -> setField x y acc)
-       (defField "meta-json" (toStringLazy $ encode metadata) (Object mempty))
-       (writerVariables opts)
-    `combineMetadata` metadata
-  where combineMetadata (Object o1) (Object o2) = Object $ H.union o1 o2
-        combineMetadata x _                     = x
-
-metaValueToJSON :: (Functor m, Monad m, ToJSON a)
-                => ([Block] -> m a)
-                -> ([Inline] -> m a)
-                -> MetaValue
-                -> m Value
-metaValueToJSON blockWriter inlineWriter (MetaMap metamap) = toJSON <$>
-  Traversable.mapM (metaValueToJSON blockWriter inlineWriter) metamap
-metaValueToJSON blockWriter inlineWriter (MetaList xs) = toJSON <$>
-  Traversable.mapM (metaValueToJSON blockWriter inlineWriter) xs
-metaValueToJSON _ _ (MetaBool b) = return $ toJSON b
-metaValueToJSON _ inlineWriter (MetaString s) = toJSON <$>
-  inlineWriter (Builder.toList (Builder.text s))
-metaValueToJSON blockWriter _ (MetaBlocks bs) = toJSON <$> blockWriter bs
-metaValueToJSON _ inlineWriter (MetaInlines is) = toJSON <$> inlineWriter is
-
--- | Retrieve a field value from a JSON object.
-getField :: FromJSON a
-         => String
-         -> Value
-         -> Maybe a
-getField field (Object hashmap) = do
-  result <- H.lookup (T.pack field) hashmap
-  case fromJSON result of
-       Success x -> return x
-       _         -> fail "Could not convert from JSON"
-getField _ _ = fail "Not a JSON object"
-
-setField :: ToJSON a
-         => String
-         -> a
-         -> Value
-         -> Value
--- | Set a field of a JSON object.  If the field already has a value,
--- convert it into a list with the new value appended to the old value(s).
--- This is a utility function to be used in preparing template contexts.
-setField field val (Object hashmap) =
-  Object $ H.insertWith combine (T.pack field) (toJSON val) hashmap
-  where combine newval oldval =
-          case fromJSON oldval of
-                Success xs -> toJSON $ xs ++ [newval]
-                _          -> toJSON [oldval, newval]
-setField _ _  x = x
-
-resetField :: ToJSON a
-           => String
-           -> a
-           -> Value
-           -> Value
--- | Reset a field of a JSON object.  If the field already has a value,
--- the new value replaces it.
--- This is a utility function to be used in preparing template contexts.
-resetField field val (Object hashmap) =
-  Object $ H.insert (T.pack field) (toJSON val) hashmap
-resetField _ _  x = x
-
-defField :: ToJSON a
-         => String
-         -> a
-         -> Value
-         -> Value
--- | Set a field of a JSON object if it currently has no value.
--- If it has a value, do nothing.
--- This is a utility function to be used in preparing template contexts.
-defField field val (Object hashmap) =
-  Object $ H.insertWith f (T.pack field) (toJSON val) hashmap
-    where f _newval oldval = oldval
-defField _ _  x = x
-
--- Produce an HTML tag with the given pandoc attributes.
-tagWithAttrs :: String -> Attr -> Doc
-tagWithAttrs tag (ident,classes,kvs) = hsep
-  ["<" <> text tag
-  ,if null ident
-      then empty
-      else "id=" <> doubleQuotes (text ident)
-  ,if null classes
-      then empty
-      else "class=" <> doubleQuotes (text (unwords classes))
-  ,hsep (map (\(k,v) -> text k <> "=" <>
-                doubleQuotes (text (escapeStringForXML v))) kvs)
-  ] <> ">"
-
-isDisplayMath :: Inline -> Bool
-isDisplayMath (Math DisplayMath _) = True
-isDisplayMath _                    = False
-
-stripLeadingTrailingSpace :: [Inline] -> [Inline]
-stripLeadingTrailingSpace = go . reverse . go . reverse
-  where go (Space:xs)     = xs
-        go (SoftBreak:xs) = xs
-        go xs             = xs
-
--- Put display math in its own block (for ODT/DOCX).
-fixDisplayMath :: Block -> Block
-fixDisplayMath (Plain lst)
-  | any isDisplayMath lst && not (all isDisplayMath lst) =
-    -- chop into several paragraphs so each displaymath is its own
-    Div ("",["math"],[]) $
-       map Plain $
-       filter (not . null) $
-       map stripLeadingTrailingSpace $
-       groupBy (\x y -> (isDisplayMath x && isDisplayMath y) ||
-                         not (isDisplayMath x || isDisplayMath y)) lst
-fixDisplayMath (Para lst)
-  | any isDisplayMath lst && not (all isDisplayMath lst) =
-    -- chop into several paragraphs so each displaymath is its own
-    Div ("",["math"],[]) $
-       map Para $
-       filter (not . null) $
-       map stripLeadingTrailingSpace $
-       groupBy (\x y -> (isDisplayMath x && isDisplayMath y) ||
-                         not (isDisplayMath x || isDisplayMath y)) lst
-fixDisplayMath x = x
-
-unsmartify :: WriterOptions -> String -> String
-unsmartify opts ('\8217':xs) = '\'' : unsmartify opts xs
-unsmartify opts ('\8230':xs) = "..." ++ unsmartify opts xs
-unsmartify opts ('\8211':xs)
-  | isEnabled Ext_old_dashes opts = '-' : unsmartify opts xs
-  | otherwise                     = "--" ++ unsmartify opts xs
-unsmartify opts ('\8212':xs)
-  | isEnabled Ext_old_dashes opts = "--" ++ unsmartify opts xs
-  | otherwise                     = "---" ++ unsmartify opts xs
-unsmartify opts ('\8220':xs) = '"' : unsmartify opts xs
-unsmartify opts ('\8221':xs) = '"' : unsmartify opts xs
-unsmartify opts ('\8216':xs) = '\'' : unsmartify opts xs
-unsmartify opts (x:xs) = x : unsmartify opts xs
-unsmartify _ [] = []
-
-gridTable :: Monad m
-          => WriterOptions
-          -> (WriterOptions -> [Block] -> m Doc)
-          -> Bool -- ^ headless
-          -> [Alignment]
-          -> [Double]
-          -> [[Block]]
-          -> [[[Block]]]
-          -> m Doc
-gridTable opts blocksToDoc headless aligns widths headers rows = do
-  let numcols = maximum (length aligns : length widths :
-                           map length (headers:rows))
-  let handleGivenWidths widths' = do
-        let widthsInChars' = map (
-                      (\x -> if x < 1 then 1 else x) .
-                      (\x -> x - 3) . floor .
-                      (fromIntegral (writerColumns opts) *)
-                      ) widths'
-        rawHeaders' <- zipWithM blocksToDoc
-            (map (\w -> opts{writerColumns =
-                      min (w - 2) (writerColumns opts)}) widthsInChars')
-            headers
-        rawRows' <- mapM
-             (\cs -> zipWithM blocksToDoc
-               (map (\w -> opts{writerColumns =
-                         min (w - 2) (writerColumns opts)}) widthsInChars')
-               cs)
-             rows
-        return (widthsInChars', rawHeaders', rawRows')
-  let handleZeroWidths = do
-        rawHeaders' <- mapM (blocksToDoc opts) headers
-        rawRows' <- mapM (mapM (blocksToDoc opts)) rows
-        let numChars [] = 0
-            numChars xs = maximum . map offset $ xs
-        let widthsInChars' =
-                map numChars $ transpose (rawHeaders' : rawRows')
-        if sum widthsInChars' > writerColumns opts
-           then -- use even widths
-                handleGivenWidths
-                  (replicate numcols (1.0 / fromIntegral numcols) :: [Double])
-           else return (widthsInChars', rawHeaders', rawRows')
-  (widthsInChars, rawHeaders, rawRows) <- if all (== 0) widths
-                                             then handleZeroWidths
-                                             else handleGivenWidths widths
-  let hpipeBlocks blocks = hcat [beg, middle, end]
-        where h       = maximum (1 : map height blocks)
-              sep'    = lblock 3 $ vcat (replicate h (text " | "))
-              beg     = lblock 2 $ vcat (replicate h (text "| "))
-              end     = lblock 2 $ vcat (replicate h (text " |"))
-              middle  = chomp $ hcat $ intersperse sep' blocks
-  let makeRow = hpipeBlocks . zipWith lblock widthsInChars
-  let head' = makeRow rawHeaders
-  let rows' = map (makeRow . map chomp) rawRows
-  let borderpart ch align widthInChars =
-           (if align == AlignLeft || align == AlignCenter
-               then char ':'
-               else char ch) <>
-           text (replicate widthInChars ch) <>
-           (if align == AlignRight || align == AlignCenter
-               then char ':'
-               else char ch)
-  let border ch aligns' widthsInChars' =
-        char '+' <>
-        hcat (intersperse (char '+') (zipWith (borderpart ch)
-                aligns' widthsInChars')) <> char '+'
-  let body = vcat $ intersperse (border '-' (repeat AlignDefault) widthsInChars)
-                    rows'
-  let head'' = if headless
-                  then empty
-                  else head' $$ border '=' aligns widthsInChars
-  if headless
-     then return $
-           border '-' aligns widthsInChars $$
-           body $$
-           border '-' (repeat AlignDefault) widthsInChars
-     else return $
-           border '-' (repeat AlignDefault) widthsInChars $$
-           head'' $$
-           body $$
-           border '-' (repeat AlignDefault) widthsInChars
+{-# LANGUAGE FlexibleContexts #-}
+{-# LANGUAGE MultiParamTypeClasses #-}
+{-# LANGUAGE ScopedTypeVariables #-}
+{-# LANGUAGE OverloadedStrings #-}
+{-# LANGUAGE LambdaCase #-}
+{- |
+   Module      : Text.Pandoc.Writers.Shared
+   Copyright   : Copyright (C) 2013-2024 John MacFarlane
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : John MacFarlane <jgm@berkeley.edu>
+   Stability   : alpha
+   Portability : portable
+
+Shared utility functions for pandoc writers.
+-}
+module Text.Pandoc.Writers.Shared (
+                       metaToContext
+                     , metaToContext'
+                     , addVariablesToContext
+                     , getField
+                     , setField
+                     , resetField
+                     , defField
+                     , getLang
+                     , tagWithAttrs
+                     , htmlAddStyle
+                     , htmlAlignmentToString
+                     , htmlAttrs
+                     , isDisplayMath
+                     , fixDisplayMath
+                     , unsmartify
+                     , gridTable
+                     , lookupMetaBool
+                     , lookupMetaBlocks
+                     , lookupMetaInlines
+                     , lookupMetaString
+                     , stripLeadingTrailingSpace
+                     , toSubscript
+                     , toSuperscript
+                     , toSubscriptInline
+                     , toSuperscriptInline
+                     , toTableOfContents
+                     , endsWithPlain
+                     , toLegacyTable
+                     , splitSentences
+                     , ensureValidXmlIdentifiers
+                     , removeLinks
+                     , setupTranslations
+                     , isOrderedListMarker
+                     , toTaskListItem
+                     , delimited
+                     , allRowsEmpty
+                     , tableBodiesToRows
+                     , insertCurrentSpansAtColumn
+                     , takePreviousSpansAtColumn
+                     , decrementTrailingRowSpans
+                     )
+where
+import Safe (lastMay, maximumMay)
+import qualified Data.ByteString.Lazy as BL
+import Control.Monad (MonadPlus, mzero)
+import Data.Either (isRight)
+import Data.Aeson (ToJSON (..), encode)
+import Data.Char (chr, ord, isSpace, isLetter, isUpper)
+import Data.List (groupBy, intersperse, transpose, zipWith4)
+import qualified Data.List as L
+import Data.List.NonEmpty (NonEmpty((:|)))
+import Data.Text.Conversions (FromText(..))
+import qualified Data.Map as M
+import qualified Data.Text as T
+import Data.Text (Text)
+import qualified Text.Pandoc.Builder as Builder
+import Text.Pandoc.CSS (cssAttributes)
+import Text.Pandoc.Definition
+import Text.Pandoc.Options
+import Text.Pandoc.Parsing (runParser, eof, defaultParserState,
+                            anyOrderedListMarker)
+import Text.DocLayout
+import Text.Pandoc.Shared (stringify, makeSections, blocksToInlines)
+import Text.Pandoc.Walk (Walkable(..))
+import qualified Text.Pandoc.UTF8 as UTF8
+import Text.Pandoc.XML (escapeStringForXML, rdfaAttributes, html5Attributes)
+import Text.DocTemplates (Context(..), Val(..), TemplateTarget,
+                          ToContext(..), FromContext(..))
+import Text.Pandoc.Chunks (tocToList, toTOCTree)
+import Text.Collate.Lang (Lang (..))
+import Text.Pandoc.Class (PandocMonad, toLang)
+import Text.Pandoc.Translations (setTranslations)
+import Data.Maybe (fromMaybe)
+import qualified Text.Pandoc.Writers.AnnotatedTable as Ann
+import qualified Data.Set as Set
+
+-- import Debug.Trace
+
+-- | Create template Context from a 'Meta' and an association list
+-- of variables, specified at the command line or in the writer.
+-- Variables overwrite metadata fields with the same names.
+-- If multiple variables are set with the same name, a list is
+-- assigned.  Does nothing if 'writerTemplate' is Nothing.
+metaToContext :: (Monad m, TemplateTarget a)
+              => WriterOptions
+              -> ([Block] -> m (Doc a))
+              -> ([Inline] -> m (Doc a))
+              -> Meta
+              -> m (Context a)
+metaToContext opts blockWriter inlineWriter meta =
+  case writerTemplate opts of
+    Nothing -> return mempty
+    Just _  -> addVariablesToContext opts <$>
+                metaToContext' blockWriter inlineWriter meta
+
+-- | Like 'metaToContext, but does not include variables and is
+-- not sensitive to 'writerTemplate'.
+metaToContext' :: (Monad m, TemplateTarget a)
+           => ([Block] -> m (Doc a))     -- ^ block writer
+           -> ([Inline] -> m (Doc a))    -- ^ inline writer
+           -> Meta
+           -> m (Context a)
+metaToContext' blockWriter inlineWriter (Meta metamap) =
+  Context <$> mapM (metaValueToVal blockWriter inlineWriter) metamap
+
+-- | Add variables to a template Context, using monoidal append.
+-- Also add `meta-json`.  Note that metadata values are used
+-- in template contexts only when like-named variables aren't set.
+addVariablesToContext :: TemplateTarget a
+                      => WriterOptions -> Context a -> Context a
+addVariablesToContext opts c1 =
+  c2 <> (fromText <$> writerVariables opts) <> c1
+ where
+   c2 = Context $
+          M.insert "meta-json" (SimpleVal $ literal $ fromText jsonrep)
+                               mempty
+   jsonrep = UTF8.toText $ BL.toStrict $ encode $ toJSON c1
+
+-- | Converts a 'MetaValue' into a doctemplate 'Val', using the given
+-- converter functions.
+metaValueToVal :: (Monad m, TemplateTarget a)
+               => ([Block] -> m (Doc a))    -- ^ block writer
+               -> ([Inline] -> m (Doc a))   -- ^ inline writer
+               -> MetaValue
+               -> m (Val a)
+metaValueToVal blockWriter inlineWriter (MetaMap metamap) =
+  MapVal . Context <$> mapM (metaValueToVal blockWriter inlineWriter) metamap
+metaValueToVal blockWriter inlineWriter (MetaList xs) = ListVal <$>
+  mapM (metaValueToVal blockWriter inlineWriter) xs
+metaValueToVal _ _ (MetaBool b) = return $ BoolVal b
+metaValueToVal _ inlineWriter (MetaString s) =
+   SimpleVal <$> inlineWriter (Builder.toList (Builder.text s))
+metaValueToVal blockWriter _ (MetaBlocks bs) = SimpleVal <$> blockWriter bs
+metaValueToVal _ inlineWriter (MetaInlines is) = SimpleVal <$> inlineWriter is
+
+
+-- | Retrieve a field value from a template context.
+getField   :: FromContext a b => Text -> Context a -> Maybe b
+getField field (Context m) = M.lookup field m >>= fromVal
+
+-- | Set a field of a template context.  If the field already has a value,
+-- convert it into a list with the new value appended to the old value(s).
+-- This is a utility function to be used in preparing template contexts.
+setField   :: ToContext a b => Text -> b -> Context a -> Context a
+setField field val (Context m) =
+  Context $ M.insertWith combine field (toVal val) m
+ where
+  combine newval (ListVal xs)   = ListVal (xs ++ [newval])
+  combine newval x              = ListVal [x, newval]
+
+-- | Reset a field of a template context.  If the field already has a
+-- value, the new value replaces it.
+-- This is a utility function to be used in preparing template contexts.
+resetField :: ToContext a b => Text -> b -> Context a -> Context a
+resetField field val (Context m) =
+  Context (M.insert field (toVal val) m)
+
+-- | Set a field of a template context if it currently has no value.
+-- If it has a value, do nothing.
+-- This is a utility function to be used in preparing template contexts.
+defField   :: ToContext a b => Text -> b -> Context a -> Context a
+defField field val (Context m) =
+  Context (M.insertWith f field (toVal val) m)
+  where
+    f _newval oldval = oldval
+
+-- | Get the contents of the `lang` metadata field or variable.
+getLang :: WriterOptions -> Meta -> Maybe Text
+getLang opts meta =
+  case lookupContext "lang" (writerVariables opts) of
+        Just s -> Just s
+        _      ->
+          case lookupMeta "lang" meta of
+               Just (MetaBlocks [Para [Str s]])  -> Just s
+               Just (MetaBlocks [Plain [Str s]]) -> Just s
+               Just (MetaInlines [Str s])        -> Just s
+               Just (MetaString s)               -> Just s
+               _                                 -> Nothing
+
+-- | Produce an HTML tag with the given pandoc attributes.
+tagWithAttrs :: HasChars a => a -> Attr -> Doc a
+tagWithAttrs tag attr = "<" <> literal tag <> (htmlAttrs attr) <> ">"
+
+-- | Produce HTML for the given pandoc attributes, to be used in HTML tags
+htmlAttrs :: HasChars a => Attr -> Doc a
+htmlAttrs (ident, classes, kvs) = addSpaceIfNotEmpty (hsep [
+  if T.null ident
+      then empty
+      else "id=" <> doubleQuotes (text $ T.unpack ident)
+  ,if null classes
+      then empty
+      else "class=" <> doubleQuotes (text $ T.unpack (T.unwords classes))
+  ,hsep (map (\(k,v) -> formatKey k <> "=" <>
+                doubleQuotes (text $ T.unpack (escapeStringForXML v))) kvs)
+  ])
+ where
+   formatKey x = text . T.unpack $
+        if (x `Set.member` (html5Attributes <> rdfaAttributes)
+            && x /= "label") -- #10048
+             || T.any (== ':') x -- e.g. epub: namespace
+             || "data-" `T.isPrefixOf` x
+             || "aria-" `T.isPrefixOf` x
+           then x
+           else "data-" <> x
+
+addSpaceIfNotEmpty :: HasChars a => Doc a -> Doc a
+addSpaceIfNotEmpty f = if isEmpty f then f else " " <> f
+
+-- | Adds a key-value pair to the @style@ attribute.
+htmlAddStyle :: (Text, Text) -> [(Text, Text)] -> [(Text, Text)]
+htmlAddStyle (key, value) kvs =
+  let cssToStyle = T.intercalate " " . map (\(k, v) -> k <> ": " <> v <> ";")
+  in case break ((== "style") . fst) kvs of
+    (_, []) ->
+      -- no style attribute yet, add new one
+      ("style", cssToStyle [(key, value)]) : kvs
+    (xs, (_,cssStyles):rest) ->
+      -- modify the style attribute
+      xs ++ ("style", cssToStyle modifiedCssStyles) : rest
+      where
+        modifiedCssStyles =
+          case break ((== key) . fst) $ cssAttributes cssStyles of
+            (cssAttribs, []) -> (key, value) : cssAttribs
+            (pre, _:post)    -> pre ++ (key, value) : post
+
+-- | Get the html representation of an alignment key
+htmlAlignmentToString :: Alignment -> Maybe Text
+htmlAlignmentToString = \case
+  AlignLeft    -> Just "left"
+  AlignRight   -> Just "right"
+  AlignCenter  -> Just "center"
+  AlignDefault -> Nothing
+
+-- | Returns 'True' iff the argument is an inline 'Math' element of type
+-- 'DisplayMath'.
+isDisplayMath :: Inline -> Bool
+isDisplayMath (Math DisplayMath _)          = True
+isDisplayMath (Span _ [Math DisplayMath _]) = True
+isDisplayMath _                             = False
+
+-- | Remove leading and trailing 'Space' and 'SoftBreak' elements.
+stripLeadingTrailingSpace :: [Inline] -> [Inline]
+stripLeadingTrailingSpace = go . reverse . go . reverse
+  where go (Space:xs)     = xs
+        go (SoftBreak:xs) = xs
+        go xs             = xs
+
+-- | Put display math in its own block (for ODT/DOCX).
+fixDisplayMath :: Block -> Block
+fixDisplayMath (Plain lst)
+  | any isDisplayMath lst && not (all isDisplayMath lst) =
+    -- chop into several paragraphs so each displaymath is its own
+    Div ("",["math"],[]) $
+       map Plain $
+       filter (not . null) $
+       map stripLeadingTrailingSpace $
+       groupBy (\x y -> (isDisplayMath x && isDisplayMath y) ||
+                         not (isDisplayMath x || isDisplayMath y)) lst
+fixDisplayMath (Para lst)
+  | any isDisplayMath lst && not (all isDisplayMath lst) =
+    -- chop into several paragraphs so each displaymath is its own
+    Div ("",["math"],[]) $
+       map Para $
+       filter (not . null) $
+       map stripLeadingTrailingSpace $
+       groupBy (\x y -> (isDisplayMath x && isDisplayMath y) ||
+                         not (isDisplayMath x || isDisplayMath y)) lst
+fixDisplayMath x = x
+
+-- | Converts a Unicode character into the ASCII sequence used to
+-- represent the character in "smart" Markdown.
+unsmartify :: WriterOptions -> Text -> Text
+unsmartify opts = T.concatMap $ \c -> case c of
+  '\8217' -> "'"
+  '\8230' -> "..."
+  '\8211'
+    | isEnabled Ext_old_dashes opts -> "-"
+    | otherwise                     -> "--"
+  '\8212'
+    | isEnabled Ext_old_dashes opts -> "--"
+    | otherwise                     -> "---"
+  '\8220' -> "\""
+  '\8221' -> "\""
+  '\8216' -> "'"
+  _       -> T.singleton c
+
+-- | Writes a grid table.
+gridTable :: Monad m
+           => WriterOptions
+           -> (WriterOptions -> [Block] -> m (Doc Text)) -- ^ format Doc writer
+           -> [ColSpec]
+           -> TableHead
+           -> [TableBody]
+           -> TableFoot
+           -> m (Doc Text)
+gridTable opts blocksToDoc colspecs' thead' tbodies' tfoot' = do
+  let Ann.Table _ _ colspecs thead tbodies tfoot =
+        Ann.toTable mempty (Caption Nothing mempty)
+                    colspecs' thead' tbodies' tfoot'
+  let renderRows = fmap addDummies . mapM (gridRow opts blocksToDoc)
+  let getHeadCells (Ann.HeaderRow _ _ cells) = cells
+  let getHeadRows (Ann.TableHead _ rs) = map getHeadCells rs
+  headCells <- renderRows (getHeadRows thead)
+  let getFootRows (Ann.TableFoot _ xs) = map getHeadCells xs
+  footCells <- renderRows (getFootRows tfoot)
+  -- We don't distinguish between row head and regular cells here:
+  let getBodyCells (Ann.BodyRow _ _ rhcells cells) = rhcells ++ cells
+  let getBody (Ann.TableBody _ _ hs xs) = map getHeadCells hs <> map getBodyCells xs
+  bodyCells <- mapM (renderRows . getBody) tbodies
+  let rows = (setTopBorder SingleLine . setBottomBorder DoubleHeaderLine) headCells ++
+             (setTopBorder (if null headCells
+                               then SingleHeaderLine
+                               else SingleLine) . setBottomBorder SingleLine)
+                   (mconcat bodyCells) ++
+             (setTopBorder DoubleLine . setBottomBorder DoubleLine) footCells
+  pure $ gridRows $ redoWidths opts colspecs rows
+
+data ColWidthInfo =
+  ColWidthInfo
+  { colWidthSpecified :: Int
+  , colWidthFull :: Int
+  , colWidthMin :: Int
+  , colWidthUsed :: Int }
+  deriving (Show, Ord, Eq)
+
+-- Returns (current widths, full widths, min widths)
+extractColWidths :: WriterOptions -> [[RenderedCell Text]] -> [ColWidthInfo]
+extractColWidths opts rows =
+  zipWith4 ColWidthInfo specifiedwidths fullwidths minwidths currentwidths
+ where
+   getWidths calcOffset =
+     map (fromMaybe 0 . maximumMay) (transpose (map (concatMap (getCellWidths calcOffset)) rows))
+   getCellWidths calcOffset c = replicate (cellColSpan c)
+                                 (calcOffset c `div` (cellColSpan c) +
+                                  calcOffset c `rem` (cellColSpan c))
+   fullwidths = getWidths (max 1 . offset . cellContents)
+   minwidths =
+     case writerWrapText opts of
+       WrapNone -> fullwidths
+       _ -> getWidths (minOffset . cellContents)
+   specifiedwidths = getWidths cellWidth
+   currentwidths = zipWith (\specw minw -> if specw == 0
+                                              then 0
+                                              else max specw minw)
+                           specifiedwidths minwidths
+
+resetWidths :: [Int] -> [RenderedCell Text] -> [RenderedCell Text]
+resetWidths _ [] = []
+resetWidths [] cs = cs
+resetWidths (w:ws) (c:cs) =
+  case cellColSpan c of
+    1 -> c{ cellWidth = w } : resetWidths ws cs
+    n | n < 1 -> c : resetWidths ws cs
+      | otherwise -> c{ cellWidth = w + sum (take (n - 1) ws) + (3 * (n-1)) }
+                               : resetWidths (drop (n - 1) ws) cs
+
+redoWidths :: WriterOptions -> [ColSpec] -> [[RenderedCell Text]] -> [[RenderedCell Text]]
+redoWidths _ _ [] = []
+redoWidths opts colspecs rows = map (resetWidths newwidths) rows
+ where
+  numcols = length colspecs
+  widthInfos = extractColWidths opts rows
+  colsAvailable = writerColumns opts - (3 * numcols) - 1
+  -- now, we need to change colWidthUsed 0 to an appropriate number;
+  -- either the full width if it fits easily, or an appropriate fraction
+  -- of the remaining width.  This must be done recursively, because
+  -- once we decide that the full width can fit, that may leave less
+  -- space for the remaining columns with default width to fill.
+  recalculateWidths finalRun numRuns infos =
+    let numUnassigned = length (filter ((== 0) . colWidthUsed) infos)
+        unusedCols = colsAvailable - sum (map colWidthUsed infos)
+        defwidth = if numUnassigned == 0
+                      then 0
+                      else unusedCols `div` numUnassigned
+        infos' = map (\info -> if colWidthUsed info == 0
+                                  then if finalRun
+                                          then info{ colWidthUsed =
+                                                      max (colWidthMin info) defwidth }
+                                          else if colWidthFull info <= defwidth
+                                               then info{ colWidthUsed = colWidthFull info }
+                                               else info
+                                  else info) infos
+     in if finalRun || numRuns > 4
+           then infos'
+           else if infos == infos'
+                 then recalculateWidths True (numRuns + 1) infos
+                       -- run again, filling in unassigned widths with a fraction of the
+                       -- remaining width
+                 else recalculateWidths False (numRuns + 1) infos'
+                       -- run again, filling in unassigned widths only if the full with
+                       -- would be less than the fraction of remaining width
+  newwidths = map colWidthUsed $ recalculateWidths False (1 :: Int) widthInfos
+
+makeDummy :: RenderedCell Text -> RenderedCell Text
+makeDummy c =
+    RenderedCell{ cellColNum = cellColNum c,
+                  cellColSpan = cellColSpan c,
+                  cellColSpecs = cellColSpecs c,
+                  cellAlign = AlignDefault,
+                  cellRowSpan = cellRowSpan c - 1,
+                  cellWidth = cellWidth c,
+                  cellContents = mempty,
+                  cellBottomBorder = NoLine,
+                  cellTopBorder = NoLine }
+
+addDummies :: [[RenderedCell Text]] -> [[RenderedCell Text]]
+addDummies = reverse . L.foldl' go []
+ where
+   go [] cs = [cs]
+   go (prevRow:rs) cs = addDummiesToRow prevRow cs : prevRow : rs
+   addDummiesToRow [] cs = cs
+   addDummiesToRow ds [] = map makeDummy ds
+   addDummiesToRow (d:ds) (c:cs) =
+     if cellColNum d < cellColNum c
+        then makeDummy d : addDummiesToRow ds (c:cs)
+        else c : addDummiesToRow
+                   (dropWhile (\x ->
+                       cellColNum x < cellColNum c + cellColSpan c) (d:ds))
+                   cs
+
+
+setTopBorder :: LineStyle -> [[RenderedCell Text]] -> [[RenderedCell Text]]
+setTopBorder _ [] = []
+setTopBorder sty (cs:rest) = (map (\c -> c{ cellTopBorder = sty }) cs) : rest
+
+setBottomBorder :: LineStyle -> [[RenderedCell Text]] -> [[RenderedCell Text]]
+setBottomBorder _ [] = []
+setBottomBorder sty [cs] = [map (\c -> c{ cellBottomBorder = sty }) cs]
+setBottomBorder sty (c:cs) = c : setBottomBorder sty cs
+
+gridRows :: [[RenderedCell Text]] -> Doc Text
+gridRows [] = mempty
+gridRows (x:xs) =
+  (case x of
+     [] -> mempty
+     (c:_) | isHeaderStyle (cellTopBorder c)
+            -> formatHeaderLine (cellTopBorder c) (x:xs)
+           | otherwise
+            -> formatBorder cellTopBorder False x)
+  $$
+  vcat (zipWith (rowAndBottom (x:xs)) (x:xs) (xs ++ [[]]))
+ where
+  -- generate wrapped contents. include pipe borders, bottom and left
+
+  renderCellContents c =
+    -- we don't use cblock or lblock because the content might
+    -- be interpreted as an indented code block...even though it
+    -- would look better to right-align right-aligned cells...
+    -- (TODO: change this on parsing side?)
+    lblock (cellWidth c) (cellContents c)
+
+  formatRow cs = vfill "| " <>
+   hcat (intersperse (vfill " | ") (map renderCellContents cs)) <> vfill " |"
+
+  rowAndBottom allRows thisRow nextRow =
+    let isLastRow = null nextRow
+        border1 = case thisRow of
+                     [] -> mempty
+                     (c:_) -> if isHeaderStyle (cellBottomBorder c)
+                                 then formatHeaderLine (cellBottomBorder c) allRows
+                                 else formatBorder cellBottomBorder False thisRow
+        border2 = case nextRow of
+                     [] -> mempty
+                     (c:_) -> if isHeaderStyle (cellTopBorder c)
+                                 then formatHeaderLine (cellTopBorder c) allRows
+                                 else formatBorder cellTopBorder False nextRow
+        combinedBorder = if isLastRow
+                            then border1
+                            else literal $ combineBorders
+                                  (render Nothing border1) (render Nothing border2)
+    in formatRow thisRow $$ combinedBorder
+
+combineBorders :: Text -> Text -> Text
+combineBorders t1 t2 =
+  if T.null t1
+     then t2
+     else T.zipWith go t1 t2
+ where
+   go '+' _ = '+'
+   go _ '+' = '+'
+   go ':' _ = ':'
+   go _ ':' = ':'
+   go '|' '-' = '+'
+   go '-' '|' = '+'
+   go '|' '=' = '+'
+   go '=' '|' = '+'
+   go '=' _ = '='
+   go _ '=' = '='
+   go ' ' d = d
+   go c _   = c
+
+formatHeaderLine :: Show a => LineStyle -> [[RenderedCell a]] -> Doc Text
+formatHeaderLine lineStyle rows =
+  literal $ L.foldl'
+    (\t row -> combineBorders t (render Nothing $ formatBorder (const lineStyle) True row))
+    mempty rows
+
+formatBorder :: Show a => (RenderedCell a -> LineStyle) -> Bool
+             -> [RenderedCell a] -> Doc Text
+formatBorder borderStyle alignMarkers cs =
+  borderParts <> if lastBorderStyle == NoLine
+                            then char '|'
+                            else char '+'
+ where
+   (lastBorderStyle, borderParts) = L.foldl' addBorder (NoLine, mempty) cs
+   addBorder (prevBorderStyle, accum) c =
+     (borderStyle c, accum <> char junctionChar <> toBorderSection c)
+      where junctionChar = case (borderStyle c, prevBorderStyle) of
+                               (NoLine, NoLine) -> '|'
+                               _ -> '+'
+   toBorderSection c =
+       text $ leftalign : replicate (cellWidth c) lineChar ++ [rightalign]
+     where
+       lineChar = case borderStyle c of
+                     NoLine -> ' '
+                     SingleLine -> '-'
+                     SingleHeaderLine -> '-'
+                     DoubleLine -> '='
+                     DoubleHeaderLine -> '='
+       (leftalign, rightalign) =
+           case cellAlign c of
+             _ | not alignMarkers -> (lineChar,lineChar)
+             AlignLeft -> (':',lineChar)
+             AlignCenter -> (':',':')
+             AlignRight -> (lineChar,':')
+             AlignDefault -> (lineChar,lineChar)
+
+data LineStyle = NoLine
+               | SingleLine
+               | DoubleLine
+               | SingleHeaderLine
+               | DoubleHeaderLine
+    deriving (Show, Ord, Eq)
+
+isHeaderStyle :: LineStyle -> Bool
+isHeaderStyle SingleHeaderLine = True
+isHeaderStyle DoubleHeaderLine = True
+isHeaderStyle _ = False
+
+data RenderedCell a =
+  RenderedCell{ cellColNum :: Int
+              , cellColSpan :: Int
+              , cellColSpecs :: NonEmpty ColSpec
+              , cellAlign :: Alignment
+              , cellRowSpan :: Int
+              , cellWidth :: Int
+              , cellContents :: Doc a
+              , cellBottomBorder :: LineStyle
+              , cellTopBorder :: LineStyle
+              }
+  deriving (Show)
+
+getColWidth :: ColSpec -> Double
+getColWidth (_, ColWidth n) = n
+getColWidth (_, ColWidthDefault) = 0 -- TODO?
+
+toCharWidth :: WriterOptions -> Double -> Int
+toCharWidth opts width =
+  max 0 (floor (width * fromIntegral (writerColumns opts)) - 3)
+
+gridRow :: (Monad m, HasChars a)
+        => WriterOptions
+        -> (WriterOptions -> [Block] -> m (Doc a)) -- ^ format Doc writer
+        -> [Ann.Cell]
+        -> m [RenderedCell a]
+gridRow opts blocksToDoc = mapM renderCell
+ where
+  renderer = blocksToDoc opts
+  renderCell (Ann.Cell cellcolspecs (Ann.ColNumber colnum)
+               (Cell _ _ (RowSpan rowspan) _ blocks)) = do
+    let ((align,_):|_) = cellcolspecs
+    let width = toCharWidth opts $ sum (fmap getColWidth cellcolspecs)
+    rendered <- renderer blocks
+    pure $ RenderedCell{ cellColNum = colnum,
+                         cellColSpan = length cellcolspecs,
+                         cellColSpecs = cellcolspecs,
+                         cellAlign = align,
+                         cellRowSpan = rowspan,
+                         cellWidth = width,
+                         cellContents = rendered,
+                         cellBottomBorder = if rowspan < 2
+                                               then SingleLine
+                                               else NoLine,
+                         cellTopBorder = SingleLine }
+
+
+-- | Retrieve the metadata value for a given @key@
+-- and convert to Bool.
+lookupMetaBool :: Text -> Meta -> Bool
+lookupMetaBool key meta =
+  case lookupMeta key meta of
+      Just (MetaBlocks _)  -> True
+      Just (MetaInlines _) -> True
+      Just (MetaString x)  -> not (T.null x)
+      Just (MetaBool True) -> True
+      _                    -> False
+
+-- | Retrieve the metadata value for a given @key@
+-- and extract blocks.
+--
+-- Note that an empty list is returned for maps, lists, and booleans.
+lookupMetaBlocks :: Text -> Meta -> [Block]
+lookupMetaBlocks key meta =
+  case lookupMeta key meta of
+         Just (MetaBlocks bs)   -> bs
+         Just (MetaInlines ils) -> [Plain ils]
+         Just (MetaString s)    -> [Plain [Str s]]
+         _                      -> []
+
+-- | Retrieve the metadata value for a given @key@
+-- and extract inlines.
+--
+-- Note that an empty list is returned for maps and lists.
+lookupMetaInlines :: Text -> Meta -> [Inline]
+lookupMetaInlines key meta =
+  case lookupMeta key meta of
+         Just (MetaString s)           -> [Str s]
+         Just (MetaInlines ils)        -> ils
+         Just (MetaBlocks [Plain ils]) -> ils
+         Just (MetaBlocks [Para ils])  -> ils
+         _                             -> []
+
+-- | Retrieve the metadata value for a given @key@
+-- and convert to String.
+--
+-- Note that an empty list is returned for maps, lists, and booleans.
+lookupMetaString :: Text -> Meta -> Text
+lookupMetaString key meta =
+  case lookupMeta key meta of
+         Just (MetaString s)    -> s
+         Just (MetaInlines ils) -> stringify ils
+         Just (MetaBlocks bs)   -> stringify bs
+         Just (MetaBool b)      -> T.pack (show b)
+         _                      -> ""
+
+-- | Tries to convert a character into a unicode superscript version of
+-- the character.
+toSuperscript :: Char -> Maybe Char
+toSuperscript '1' = Just '\x00B9'
+toSuperscript '2' = Just '\x00B2'
+toSuperscript '3' = Just '\x00B3'
+toSuperscript '+' = Just '\x207A'
+toSuperscript '-' = Just '\x207B'
+toSuperscript '\x2212' = Just '\x207B' -- unicode minus
+toSuperscript '=' = Just '\x207C'
+toSuperscript '(' = Just '\x207D'
+toSuperscript ')' = Just '\x207E'
+toSuperscript c
+  | c >= '0' && c <= '9' =
+                 Just $ chr (0x2070 + (ord c - 48))
+  | isSpace c = Just c
+  | otherwise = Nothing
+
+-- | Tries to convert a character into a unicode subscript version of
+-- the character.
+toSubscript :: Char -> Maybe Char
+toSubscript '+' = Just '\x208A'
+toSubscript '-' = Just '\x208B'
+toSubscript '=' = Just '\x208C'
+toSubscript '(' = Just '\x208D'
+toSubscript ')' = Just '\x208E'
+toSubscript c
+  | c >= '0' && c <= '9' =
+                 Just $ chr (0x2080 + (ord c - 48))
+  | isSpace c = Just c
+  | otherwise = Nothing
+
+toSubscriptInline :: Inline -> Maybe Inline
+toSubscriptInline Space = Just Space
+toSubscriptInline (Span attr ils) = Span attr <$> traverse toSubscriptInline ils
+toSubscriptInline (Str s) = Str . T.pack <$> traverse toSubscript (T.unpack s)
+toSubscriptInline LineBreak = Just LineBreak
+toSubscriptInline SoftBreak = Just SoftBreak
+toSubscriptInline _ = Nothing
+
+toSuperscriptInline :: Inline -> Maybe Inline
+toSuperscriptInline Space = Just Space
+toSuperscriptInline (Span attr ils) = Span attr <$> traverse toSuperscriptInline ils
+toSuperscriptInline (Str s) = Str . T.pack <$> traverse toSuperscript (T.unpack s)
+toSuperscriptInline LineBreak = Just LineBreak
+toSuperscriptInline SoftBreak = Just SoftBreak
+toSuperscriptInline _ = Nothing
+
+-- | Construct table of contents (as a bullet list) from document body.
+toTableOfContents :: WriterOptions
+                  -> [Block]
+                  -> Block
+toTableOfContents opts =
+  tocToList (writerNumberSections opts) (writerTOCDepth opts)
+  . toTOCTree
+  . makeSections (writerNumberSections opts) Nothing
+
+-- | Returns 'True' iff the list of blocks has a @'Plain'@ as its last
+-- element.
+endsWithPlain :: [Block] -> Bool
+endsWithPlain xs =
+  case lastMay xs of
+    Just Plain{} -> True
+    Just (BulletList is) -> maybe False endsWithPlain (lastMay is)
+    Just (OrderedList _ is) -> maybe False endsWithPlain (lastMay is)
+    _ -> False
+
+-- | Convert the relevant components of a new-style table (with block
+-- caption, row headers, row and column spans, and so on) to those of
+-- an old-style table (inline caption, table head with one row, no
+-- foot, and so on). Cells with a 'RowSpan' and 'ColSpan' of @(h, w)@
+-- will be cut up into @h * w@ cells of dimension @(1, 1)@, with the
+-- content placed in the upper-left corner.
+toLegacyTable :: Caption
+              -> [ColSpec]
+              -> TableHead
+              -> [TableBody]
+              -> TableFoot
+              -> ([Inline], [Alignment], [Double], [[Block]], [[[Block]]])
+toLegacyTable (Caption _ cbody) specs thead tbodies tfoot
+  = (cbody', aligns, widths, th', tb')
+  where
+    numcols = length specs
+    (aligns, mwidths) = unzip specs
+    fromWidth (ColWidth w) | w > 0 = w
+    fromWidth _                    = 0
+    widths = map fromWidth mwidths
+    unRow (Row _ x) = x
+    unBody (TableBody _ _ hd bd) = hd <> bd
+    unBodies = concatMap unBody
+
+    TableHead _ th = Builder.normalizeTableHead numcols thead
+    tb = map (Builder.normalizeTableBody numcols) tbodies
+    TableFoot _ tf = Builder.normalizeTableFoot numcols tfoot
+
+    cbody' = blocksToInlines cbody
+
+    (th', tb') = case th of
+      r:rs -> let (pendingPieces, r') = placeCutCells [] $ unRow r
+                  rs' = cutRows pendingPieces $ rs <> unBodies tb <> tf
+              in (r', rs')
+      []    -> ([], cutRows [] $ unBodies tb <> tf)
+
+    -- Adapted from placeRowSection in Builders. There is probably a
+    -- more abstract foldRowSection that unifies them both.
+    placeCutCells pendingPieces cells
+      -- If there are any pending pieces for a column, add
+      -- them. Pending pieces have preference over cells due to grid
+      -- layout rules.
+      | (p:ps):pendingPieces' <- pendingPieces
+      = let (pendingPieces'', rowPieces) = placeCutCells pendingPieces' cells
+        in (ps : pendingPieces'', p : rowPieces)
+      -- Otherwise cut up a cell on the row and deal with its pieces.
+      | c:cells' <- cells
+      = let (h, w, cBody) = getComponents c
+            cRowPieces = cBody : replicate (w - 1) mempty
+            cPendingPieces = replicate w $ replicate (h - 1) mempty
+            pendingPieces' = drop w pendingPieces
+            (pendingPieces'', rowPieces) = placeCutCells pendingPieces' cells'
+        in (cPendingPieces <> pendingPieces'', cRowPieces <> rowPieces)
+      | otherwise = ([], [])
+
+    cutRows pendingPieces (r:rs)
+      = let (pendingPieces', r') = placeCutCells pendingPieces $ unRow r
+            rs' = cutRows pendingPieces' rs
+        in r' : rs'
+    cutRows _ [] = []
+
+    getComponents (Cell _ _ (RowSpan h) (ColSpan w) body)
+      = (h, w, body)
+
+splitSentences :: Doc Text -> Doc Text
+splitSentences = go . toList
+ where
+  go [] = mempty
+  go (Text len t : AfterBreak _ : BreakingSpace : xs)
+    | isSentenceEnding t = Text len t <> NewLine <> go xs
+  go (Text len t : BreakingSpace : xs)
+    | isSentenceEnding t = Text len t <> NewLine <> go xs
+  go (x:xs) = x <> go xs
+
+  toList (Concat (Concat a b) c) = toList (Concat a (Concat b c))
+  toList (Concat a b) = a : toList b
+  toList x = [x]
+
+  isSentenceEnding t =
+    case T.unsnoc t of
+      Just (t',c)
+        | c == '.' || c == '!' || c == '?'
+        , not (isInitial t') -> True
+        | c == ')' || c == ']' || c == '"' || c == '\x201D' ->
+           case T.unsnoc t' of
+             Just (t'',d) -> d == '.' || d == '!' || d == '?' &&
+                             not (isInitial t'')
+             _ -> False
+      _ -> False
+   where
+    isInitial x = T.length x == 1 && T.all isUpper x
+
+-- | Ensure that all identifiers start with a letter,
+-- and modify internal links accordingly. (Yes, XML allows an
+-- underscore, but HTML 4 doesn't, so we are more conservative.)
+ensureValidXmlIdentifiers :: Pandoc -> Pandoc
+ensureValidXmlIdentifiers = walk fixLinks . walkAttr fixIdentifiers
+ where
+  fixIdentifiers (ident, classes, kvs) =
+    (case T.uncons ident of
+      Nothing -> ident
+      Just (c, _) | isLetter c -> ident
+      _ -> "id_" <> ident,
+     classes, kvs)
+  needsFixing src =
+    case T.uncons src of
+      Just ('#',t) ->
+        case T.uncons t of
+          Just (c,_) | not (isLetter c) -> Just ("#id_" <> t)
+          _ -> Nothing
+      _ -> Nothing
+  fixLinks (Link attr ils (src, tit))
+    | Just src' <- needsFixing src = Link attr ils (src', tit)
+  fixLinks (Image attr ils (src, tit))
+    | Just src' <- needsFixing src = Image attr ils (src', tit)
+  fixLinks x = x
+
+-- | Walk Pandoc document, modifying attributes.
+walkAttr :: (Attr -> Attr) -> Pandoc -> Pandoc
+walkAttr f = walk goInline . walk goBlock
+ where
+  goInline (Span attr ils) = Span (f attr) ils
+  goInline (Link attr ils target) = Link (f attr) ils target
+  goInline (Image attr ils target) = Image (f attr) ils target
+  goInline (Code attr txt) = Code (f attr) txt
+  goInline x = x
+
+  goBlock (Header lev attr ils) = Header lev (f attr) ils
+  goBlock (CodeBlock attr txt) = CodeBlock (f attr) txt
+  goBlock (Table attr cap colspecs thead tbodies tfoot) =
+    Table (f attr) cap colspecs thead tbodies tfoot
+  goBlock (Div attr bs) = Div (f attr) bs
+  goBlock x = x
+
+-- | Convert links to spans; most useful when writing elements that must not
+-- contain links, e.g. to avoid nested links.
+removeLinks :: [Inline] -> [Inline]
+removeLinks = walk go
+ where
+  go (Link attr ils _) = Span attr ils
+  go x = x
+
+-- | Set translations based on the `lang` in metadata.
+setupTranslations :: PandocMonad m => Meta -> m ()
+setupTranslations meta = do
+  let defLang = Lang "en" (Just "US") Nothing [] [] []
+  lang <- case lookupMetaString "lang" meta of
+            "" -> pure defLang
+            s  -> fromMaybe defLang <$> toLang (Just s)
+  setTranslations lang
+
+-- True if the string would count as a Markdown ordered list marker.
+isOrderedListMarker :: Text -> Bool
+isOrderedListMarker xs = not (T.null xs) && (T.last xs `elem` ['.',')']) &&
+              isRight (runParser (anyOrderedListMarker >> eof)
+                       defaultParserState "" xs)
+
+toTaskListItem :: MonadPlus m => [Block] -> m (Bool, [Block])
+toTaskListItem (Plain (Str "☐":Space:ils):xs) = pure (False, Plain ils:xs)
+toTaskListItem (Plain (Str "☒":Space:ils):xs) = pure (True, Plain ils:xs)
+toTaskListItem (Para  (Str "☐":Space:ils):xs) = pure (False, Para ils:xs)
+toTaskListItem (Para  (Str "☒":Space:ils):xs) = pure (True, Para ils:xs)
+toTaskListItem _                              = mzero
+
+-- | Add an opener and closer to a Doc. If the Doc begins or ends
+-- with whitespace, export this outside the opener or closer.
+-- This is used for formats, like Markdown, which don't allow spaces
+-- after opening or before closing delimiters.
+delimited :: Doc Text -> Doc Text -> Doc Text -> Doc Text
+delimited opener closer content =
+  mconcat initialWS <> opener <> mconcat middle <> closer <> mconcat finalWS
+ where
+  contents = toList content
+  (initialWS, rest) = span isWS contents
+  (reverseFinalWS, reverseMiddle) = span isWS (reverse rest)
+  finalWS = reverse reverseFinalWS
+  middle = reverse reverseMiddle
+  isWS NewLine = True
+  isWS CarriageReturn = True
+  isWS BreakingSpace = True
+  isWS BlankLines{} = True
+  isWS _ = False
+  toList (Concat (Concat a b) c) = toList (Concat a (Concat b c))
+  toList (Concat a b) = a : toList b
+  toList x = [x]
+
+-- | Determine whether all rows and their cells are empty.
+allRowsEmpty :: [Row] -> Bool
+allRowsEmpty = all isEmptyRow
+ where
+  isEmptyRow (Row _ cells) = all isEmptyCell cells
+  isEmptyCell (Cell _ _ _ _ blocks) = null blocks
+
+-- | Concatenates the header and body Rows of a List of TableBody into a flat
+-- List of Rows.
+tableBodiesToRows :: [TableBody] -> [Row]
+tableBodiesToRows = concatMap tableBodyToRows
+  where
+    tableBodyToRows (TableBody _ _ headerRows bodyRows) = headerRows ++ bodyRows
+
+-- | Insert the current span information of a table cell to keep track of it in
+-- subsequent rows.
+--
+-- If 'RowSpan' @> 1@, the current span information will be inserted. Otherwise
+-- the previous span information will be left unchanged.
+--
+-- Use 'takePreviousSpansAtColumn' to take previous span information at
+-- subsequent rows. Use 'decrementTrailingRowSpans' to handle previous trailing
+-- spans at the end of a row.
+--
+-- For writers that need to manually apply the 'RowSpan' of cells over multiple
+-- rows or otherwise have to keep track of it.
+insertCurrentSpansAtColumn :: Int -> M.Map Int (RowSpan, ColSpan) -> RowSpan -> ColSpan -> M.Map Int (RowSpan, ColSpan)
+insertCurrentSpansAtColumn columnPosition previousSpans (RowSpan rowSpan) colSpan =
+  if (rowSpan > 1)
+    then M.insert columnPosition (RowSpan rowSpan - 1, colSpan) previousSpans -- Minus its own row.
+    else previousSpans
+
+-- | Take previous span information at a column position that was added with
+-- 'insertCurrentSpansAtColumn' if available.
+--
+-- If the previous 'RowSpan' @>= 1@, this will return 'Just' the previous
+-- 'ColSpan' and an adjusted span information where that 'RowSpan' is either
+-- decremented or deleted if it would fall to 0. Otherwise this will return
+-- 'Nothing'.
+takePreviousSpansAtColumn :: Int -> M.Map Int (RowSpan, ColSpan) -> Maybe (ColSpan, M.Map Int (RowSpan, ColSpan))
+takePreviousSpansAtColumn columnPosition previousSpans
+  | Just previous@(RowSpan previousRowSpan, previousColSpan) <- M.lookup columnPosition previousSpans
+  , previousRowSpan >= 1 = Just (previousColSpan, decrementPreviousRowSpans previous)
+  | otherwise = Nothing
+ where
+  decrementPreviousRowSpans (RowSpan previousRowSpan, previousColSpan) =
+    if previousRowSpan > 1
+      then M.insert columnPosition (RowSpan previousRowSpan - 1, previousColSpan) previousSpans
+      else M.delete columnPosition previousSpans
+
+-- | Decrement all previously tracked trailing 'RowSpan' elements at or after a
+-- column position.
+--
+-- For handling previous row spans that are next to the end of a row's cells
+-- that were previously added with 'insertCurrentSpansAtColumn'.
+decrementTrailingRowSpans :: Int -> M.Map Int (RowSpan, ColSpan) -> M.Map Int (RowSpan, ColSpan)
+decrementTrailingRowSpans columnPosition = M.mapWithKey decrementTrailing
+  where
+    decrementTrailing previousColumnPosition previousSpan@(RowSpan rowSpan, colSpan) =
+      if previousColumnPosition >= columnPosition && rowSpan >= 1
+        then (RowSpan rowSpan - 1, colSpan)
+        else previousSpan
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,114 +1,61 @@
 {-# LANGUAGE OverloadedStrings #-}
 {-# LANGUAGE PatternGuards     #-}
-{-
-Copyright (C) 2006-2017 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-2017 John MacFarlane
+   Module      : Text.Pandoc.Writers.TEI
+   Copyright   : Copyright (C) 2006-2024 John MacFarlane
    License     : GNU GPL, version 2 or above
 
    Maintainer  : John MacFarlane <jgm@berkeley.edu>
    Stability   : alpha
    Portability : portable
 
-Conversion of 'Pandoc' documents to Docbook XML.
+Conversion of 'Pandoc' documents to TEI XML
 -}
 module Text.Pandoc.Writers.TEI (writeTEI) where
-import Data.Char (toLower)
-import Data.List (isPrefixOf, stripPrefix)
 import Data.Text (Text)
-import qualified Text.Pandoc.Builder as B
-import Text.Pandoc.Class (PandocMonad, report)
+import qualified Data.Text as T
+import Text.Pandoc.Class.PandocMonad (PandocMonad, report)
 import Text.Pandoc.Definition
 import Text.Pandoc.Highlighting (languages, languagesByExtension)
 import Text.Pandoc.ImageSize
 import Text.Pandoc.Logging
 import Text.Pandoc.Options
-import Text.Pandoc.Pretty
+import Text.DocLayout
 import Text.Pandoc.Shared
-import Text.Pandoc.Templates (renderTemplate')
+import Text.Pandoc.URI
+import Text.Pandoc.Templates (renderTemplate)
 import Text.Pandoc.Writers.Shared
 import Text.Pandoc.XML
 
--- | Convert list of authors to a docbook <author> section
-authorToTEI :: PandocMonad m => WriterOptions -> [Inline] -> m B.Inlines
-authorToTEI opts name' = do
-  name <- render Nothing <$> inlinesToTEI opts name'
-  let colwidth = if writerWrapText opts == WrapAuto
-                    then Just $ writerColumns opts
-                    else Nothing
-  return $ B.rawInline "tei" $ render colwidth $
-      inTagsSimple "author" (text $ escapeStringForXML name)
-
--- | Convert Pandoc document to string in Docbook format.
+-- | Convert Pandoc document to string in TEI XML format.
 writeTEI :: PandocMonad m => WriterOptions -> Pandoc -> m Text
-writeTEI opts (Pandoc meta blocks) = do
-  let elements = hierarchicalize blocks
-      colwidth = if writerWrapText opts == WrapAuto
+writeTEI opts doc = do
+  let Pandoc meta blocks = ensureValidXmlIdentifiers doc
+  let colwidth = if writerWrapText opts == WrapAuto
                     then Just $ writerColumns opts
                     else Nothing
-      render' :: Doc -> Text
-      render' = render colwidth
-      startLvl = case writerTopLevelDivision opts of
+  let startLvl = case writerTopLevelDivision opts of
                    TopLevelPart    -> -1
                    TopLevelChapter -> 0
                    TopLevelSection -> 1
                    TopLevelDefault -> 1
-  auths'      <- mapM (authorToTEI opts) $ docAuthors meta
-  let meta'    = B.setMeta "author" auths' meta
-  metadata <- metaToJSON opts
-                 (fmap (render' . vcat) .
-                   mapM (elementToTEI opts startLvl) . hierarchicalize)
-                 (fmap render' . inlinesToTEI opts)
-                 meta'
-  main    <- (render' . vcat) <$> mapM (elementToTEI opts startLvl) elements
+  let fromBlocks = blocksToTEI opts . makeSections False (Just startLvl)
+  metadata <- metaToContext opts
+                 fromBlocks
+                 (fmap chomp . inlinesToTEI opts)
+                 meta
+  main    <- fromBlocks blocks
   let context = defField "body" main
-              $
-                  defField "mathml" (case writerHTMLMathMethod opts of
+              $ defField "mathml" (case writerHTMLMathMethod opts of
                                           MathML -> True
                                           _      -> False) metadata
-  case writerTemplate opts of
-       Nothing  -> return main
-       Just tpl -> renderTemplate' tpl context
-
--- | Convert an Element to TEI.
-elementToTEI :: PandocMonad m => WriterOptions -> Int -> Element -> m Doc
-elementToTEI opts _   (Blk block) = blockToTEI opts block
-elementToTEI opts lvl (Sec _ _num (id',_,_) title elements) = do
-  -- TEI doesn't allow sections with no content, so insert some if needed
-  let elements' = if null elements
-                    then [Blk (Para [])]
-                    else elements
-      -- level numbering correspond to LaTeX internals
-      divType = case lvl of
-                 n | n == -1          -> "part"
-                   | n == 0           -> "chapter"
-                   | n >= 1 && n <= 5 -> "level" ++ show n
-                   | otherwise        -> "section"
-  contents <- vcat <$> mapM (elementToTEI opts (lvl + 1)) elements'
-  titleContents <- inlinesToTEI opts title
-  return $ inTags True "div" (("type", divType) :
-    [("id", writerIdentifierPrefix opts ++ id') | not (null id')]) $
-      inTagsSimple "head" titleContents $$ contents
+  return $ render colwidth $
+    case writerTemplate opts of
+       Nothing  -> main
+       Just tpl -> renderTemplate tpl context
 
 -- | Convert a list of Pandoc blocks to TEI.
-blocksToTEI :: PandocMonad m => WriterOptions -> [Block] -> m Doc
+blocksToTEI :: PandocMonad m => WriterOptions -> [Block] -> m (Doc Text)
 blocksToTEI opts bs = vcat <$> mapM (blockToTEI opts) bs
 
 -- | Auxiliary function to convert Plain block to Para.
@@ -119,13 +66,13 @@
 -- | Convert a list of pairs of terms and definitions into a TEI
 -- list with labels and items.
 deflistItemsToTEI :: PandocMonad m
-                  => WriterOptions -> [([Inline],[[Block]])] -> m Doc
+                  => WriterOptions -> [([Inline],[[Block]])] -> m (Doc Text)
 deflistItemsToTEI opts items =
  vcat <$> mapM (uncurry (deflistItemToTEI opts)) items
 
 -- | Convert a term and a list of blocks into a TEI varlistentry.
 deflistItemToTEI :: PandocMonad m
-                 => WriterOptions -> [Inline] -> [[Block]] -> m Doc
+                 => WriterOptions -> [Inline] -> [[Block]] -> m (Doc Text)
 deflistItemToTEI opts term defs = do
   term' <- inlinesToTEI opts term
   defs' <- blocksToTEI opts $ concatMap (map plainToPara) defs
@@ -133,68 +80,72 @@
            inTagsIndented "item" defs'
 
 -- | Convert a list of lists of blocks to a list of TEI list items.
-listItemsToTEI :: PandocMonad m => WriterOptions -> [[Block]] -> m Doc
+listItemsToTEI :: PandocMonad m => WriterOptions -> [[Block]] -> m (Doc Text)
 listItemsToTEI opts items = vcat <$> mapM (listItemToTEI opts) items
 
 -- | Convert a list of blocks into a TEI list item.
-listItemToTEI :: PandocMonad m => WriterOptions -> [Block] -> m Doc
+listItemToTEI :: PandocMonad m => WriterOptions -> [Block] -> m (Doc Text)
 listItemToTEI opts item =
   inTagsIndented "item" <$> blocksToTEI opts (map plainToPara item)
 
-imageToTEI :: PandocMonad m => WriterOptions -> Attr -> String -> m Doc
-imageToTEI _ attr src = return $ selfClosingTag "graphic" $
-  ("url", src) : idAndRole attr ++ dims
+imageToTEI :: PandocMonad m => WriterOptions -> Attr -> Text -> m (Doc Text)
+imageToTEI opts attr src = return $ selfClosingTag "graphic" $
+  ("url", src) : idFromAttr opts attr ++ dims
   where
-    dims = go Width "width" ++ go Height "depth"
+    dims = go Width "width" ++ go Height "height"
     go dir dstr = case dimension dir attr of
-                    Just a  -> [(dstr, show a)]
+                    Just a  -> [(dstr, tshow a)]
                     Nothing -> []
 
 -- | Convert a Pandoc block element to TEI.
-blockToTEI :: PandocMonad m => WriterOptions -> Block -> m Doc
-blockToTEI _ Null = return empty
+blockToTEI :: PandocMonad m => WriterOptions -> Block -> m (Doc Text)
+blockToTEI opts (Div attr@(_,"section":_,_) (Header lvl _ ils : xs)) =
+  do
+  -- TEI doesn't allow sections with no content, so insert some if needed
+  let xs' = if null xs
+               then [Para []]
+               else xs
+      -- level numbering correspond to LaTeX internals
+      divType = case lvl of
+                 n | n == -1          -> "part"
+                   | n == 0           -> "chapter"
+                   | n >= 1 && n <= 5 -> "level" <> tshow n
+                   | otherwise        -> "section"
+  titleContents <- inlinesToTEI opts ils
+  contents <- blocksToTEI opts xs'
+  return $ inTags True "div" (("type", divType) : idFromAttr opts attr) $
+      inTagsSimple "head" titleContents $$ contents
 -- Add ids to paragraphs in divs with ids - this is needed for
 -- pandoc-citeproc to get link anchors in bibliographies:
-blockToTEI opts (Div (ident,_,_) [Para lst]) = do
-  let attribs = [("id", ident) | not (null ident)]
+blockToTEI opts (Div attr [Para lst]) = do
+  let attribs = idFromAttr opts attr
   inTags False "p" attribs <$> inlinesToTEI opts lst
 blockToTEI opts (Div _ bs) = blocksToTEI opts $ map plainToPara bs
 blockToTEI _ h@Header{} = do
-  -- should not occur after hierarchicalize, except inside lists/blockquotes
+  -- should not occur after makeSections, except inside lists/blockquotes
   report $ BlockNotRendered h
   return empty
 -- For TEI simple, text must be within containing block element, so
 -- we use treat as Para to ensure that Plain text ends up contained by
 -- something:
 blockToTEI opts (Plain lst) = blockToTEI opts $ Para lst
--- title beginning with fig: indicates that the image is a figure
---blockToTEI opts (Para [Image attr txt (src,'f':'i':'g':':':_)]) =
---  let alt  = inlinesToTEI opts txt
---      capt = if null txt
---                then empty
---                else inTagsSimple "title" alt
---  in  inTagsIndented "figure" $
---        capt $$
---        (inTagsIndented "mediaobject" $
---           (inTagsIndented "imageobject"
---             (imageToTEI opts attr src)) $$
---           inTagsSimple "textobject" (inTagsSimple "phrase" alt))
 blockToTEI opts (Para lst) =
   inTags False "p" [] <$> inlinesToTEI opts lst
 blockToTEI opts (LineBlock lns) =
   blockToTEI opts $ linesToPara lns
 blockToTEI opts (BlockQuote blocks) =
   inTagsIndented "quote" <$> blocksToTEI opts blocks
-blockToTEI _ (CodeBlock (_,classes,_) str) =
-  return $ text ("<ab type='codeblock " ++ lang ++ "'>") <> cr <>
-     flush (text (escapeStringForXML str) <> cr <> text "</ab>")
-    where lang  = if null langs
-                     then ""
-                     else escapeStringForXML (head langs)
-          isLang l    = map toLower l `elem` map (map toLower) languages
+blockToTEI opts (CodeBlock (_,classes,_) str) =
+  return $ literal ("<ab type='codeblock " <> lang <> "'>") <> cr <>
+     flush (literal (escapeStringForXML str) <> cr <> text "</ab>")
+    where lang  = case langs of
+                    [] -> ""
+                    (l:_) -> escapeStringForXML l
+          syntaxMap = writerSyntaxMap opts
+          isLang l    = T.toLower l `elem` map T.toLower (languages syntaxMap)
           langsFrom s = if isLang s
                            then [s]
-                           else languagesByExtension . map toLower $ s
+                           else (languagesByExtension syntaxMap) . T.toLower $ s
           langs       = concatMap langsFrom classes
 blockToTEI opts (BulletList lst) = do
   let attribs = [("type", "unordered")]
@@ -214,13 +165,13 @@
               else do
                 fi <- blocksToTEI opts $ map plainToPara first
                 re <- listItemsToTEI opts rest
-                return $ inTags True "item" [("n",show start)] fi $$ re
+                return $ inTags True "item" [("n",tshow start)] fi $$ re
   return $ inTags True "list" attribs items
 blockToTEI opts (DefinitionList lst) = do
   let attribs = [("type", "definition")]
   inTags True "list" attribs <$> deflistItemsToTEI opts lst
 blockToTEI _ b@(RawBlock f str)
-  | f == "tei"     = return $ text str
+  | f == "tei"     = return $ literal str
   -- raw TEI block (should such a thing exist).
   | otherwise      = do
     report $ BlockNotRendered b
@@ -229,46 +180,51 @@
   selfClosingTag "milestone" [("unit","undefined")
                              ,("type","separator")
                              ,("rendition","line")]
+blockToTEI opts (Figure attr capt bs) =
+  blockToTEI opts (figureDiv attr capt bs)
 
--- | TEI Tables
+-- TEI Tables
 -- TEI Simple's tables are composed of cells and rows; other
 -- table info in the AST is here lossily discard.
-blockToTEI opts (Table _ _ _ headers rows) = do
-  headers' <- tableHeadersToTEI opts headers
+blockToTEI opts (Table _ blkCapt specs thead tbody tfoot) = do
+  let (_, _, _, headers, rows) = toLegacyTable blkCapt specs thead tbody tfoot
+  headers' <- if null headers then pure mempty else tableHeadersToTEI opts headers
   rows' <- mapM (tableRowToTEI opts) rows
   return $ inTags True "table" [] $ headers' $$ vcat rows'
 
 tableRowToTEI :: PandocMonad m
               => WriterOptions
               -> [[Block]]
-              -> m Doc
+              -> m (Doc Text)
 tableRowToTEI opts cols =
-  (inTagsIndented "row" . vcat) <$> mapM (tableItemToTEI opts) cols
+  inTagsIndented "row" . vcat <$> mapM (tableItemToTEI opts) cols
 
 tableHeadersToTEI :: PandocMonad m
                   => WriterOptions
                   -> [[Block]]
-                  -> m Doc
+                  -> m (Doc Text)
 tableHeadersToTEI opts cols =
-  (inTags True "row" [("role","label")] . vcat) <$>
+  inTags True "row" [("role","label")] . vcat <$>
     mapM (tableItemToTEI opts) cols
 
 tableItemToTEI :: PandocMonad m
                => WriterOptions
                -> [Block]
-               -> m Doc
+               -> m (Doc Text)
 tableItemToTEI opts item =
-  (inTags False "cell" [] . vcat) <$> mapM (blockToTEI opts) item
+  inTags False "cell" [] . vcat <$> mapM (blockToTEI opts) item
 
 -- | Convert a list of inline elements to TEI.
-inlinesToTEI :: PandocMonad m => WriterOptions -> [Inline] -> m Doc
+inlinesToTEI :: PandocMonad m => WriterOptions -> [Inline] -> m (Doc Text)
 inlinesToTEI opts lst = hcat <$> mapM (inlineToTEI opts) lst
 
 -- | Convert an inline element to TEI.
-inlineToTEI :: PandocMonad m => WriterOptions -> Inline -> m Doc
-inlineToTEI _ (Str str) = return $ text $ escapeStringForXML str
+inlineToTEI :: PandocMonad m => WriterOptions -> Inline -> m (Doc Text)
+inlineToTEI _ (Str str) = return $ literal $ escapeStringForXML str
 inlineToTEI opts (Emph lst) =
   inTags False "hi" [("rendition","simple:italic")] <$> inlinesToTEI opts lst
+inlineToTEI opts (Underline lst) =
+  inTags False "hi" [("rendition","simple:underline")] <$> inlinesToTEI opts lst
 inlineToTEI opts (Strong lst) =
   inTags False "hi" [("rendition", "simple:bold")] <$> inlinesToTEI opts lst
 inlineToTEI opts (Strikeout lst) =
@@ -290,16 +246,16 @@
 inlineToTEI opts (Span _ ils) =
   inlinesToTEI opts ils
 inlineToTEI _ (Code _ str) = return $
-  inTags False "seg" [("type","code")] $ text (escapeStringForXML str)
+  inTags False "seg" [("type","code")] $ literal (escapeStringForXML str)
 -- Distinguish display from inline math by wrapping the former in a "figure."
 inlineToTEI _ (Math t str) = return $
   case t of
     InlineMath  -> inTags False "formula" [("notation","TeX")] $
-                   text str
+                   literal str
     DisplayMath -> inTags True "figure" [("type","math")] $
-                   inTags False "formula" [("notation","TeX")] $ text str
+                   inTags False "formula" [("notation","TeX")] $ literal str
 
-inlineToTEI _ il@(RawInline f x) | f == "tei"     = return $ text x
+inlineToTEI _ il@(RawInline f x) | f == "tei"     = return $ literal x
                                  | otherwise      = empty <$
                                      report (InlineNotRendered il)
 inlineToTEI _ LineBreak = return $ selfClosingTag "lb" []
@@ -309,8 +265,8 @@
 inlineToTEI _ SoftBreak =
             return space
 inlineToTEI opts (Link attr txt (src, _))
-  | Just email <- stripPrefix "mailto:" src = do
-      let emailLink = text $
+  | Just email <- T.stripPrefix "mailto:" src = do
+      let emailLink = literal $
                       escapeStringForXML email
       case txt of
            [Str s] | escapeURI s == email ->
@@ -319,15 +275,13 @@
               linktext <- inlinesToTEI opts txt
               return $ linktext <+> char '(' <> emailLink <> char ')'
   | otherwise =
-      (if "#" `isPrefixOf` src
-            then inTags False "ref" $ ("target", drop 1 src) : idAndRole attr
-            else inTags False "ref" $ ("target", src) : idAndRole attr ) <$>
-        inlinesToTEI opts txt
+      inTags False "ref" (("target", src) : idFromAttr opts attr)
+                 <$> inlinesToTEI opts txt
 inlineToTEI opts (Image attr description (src, tit)) = do
-  let titleDoc = if null tit
+  let titleDoc = if T.null tit
                    then empty
                    else inTags False "figDesc" []
-                           (text $ escapeStringForXML tit)
+                           (literal $ escapeStringForXML tit)
   imageDesc <- if null description
                   then return empty
                   else inTags False "head" []
@@ -337,12 +291,6 @@
 inlineToTEI opts (Note contents) =
   inTagsIndented "note" <$> blocksToTEI opts contents
 
-idAndRole :: Attr -> [(String, String)]
-idAndRole (id',cls,_) = ident ++ role
-  where
-    ident = if null id'
-               then []
-               else [("id", id')]
-    role  = if null cls
-               then []
-               else [("role", unwords cls)]
+idFromAttr :: WriterOptions -> Attr -> [(Text, Text)]
+idFromAttr opts (id',_,_) =
+  [("xml:id", writerIdentifierPrefix opts <> id') | not (T.null id')]
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,26 +1,7 @@
 {-# LANGUAGE OverloadedStrings #-}
-{-
-Copyright (C) 2008-2017 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-2017 John MacFarlane
+   Copyright   : Copyright (C) 2008-2024 John MacFarlane
                                2012 Peter Wang
    License     : GNU GPL, version 2 or above
 
@@ -31,36 +12,56 @@
 Conversion of 'Pandoc' format into Texinfo.
 -}
 module Text.Pandoc.Writers.Texinfo ( writeTexinfo ) where
+import Control.Monad (zipWithM, unless)
 import Control.Monad.Except (throwError)
 import Control.Monad.State.Strict
-import Data.Char (chr, ord)
+    ( StateT, MonadState(get), gets, modify, evalStateT )
+import Data.Char (chr, ord, isAlphaNum)
 import Data.List (maximumBy, transpose)
+import qualified Data.List as L
+import Data.List.NonEmpty (nonEmpty)
 import Data.Ord (comparing)
-import qualified Data.Set as Set
+import qualified Data.Map as M
 import Data.Text (Text)
+import qualified Data.Text as T
 import Network.URI (unEscapeString)
 import System.FilePath
-import Text.Pandoc.Class (PandocMonad, report)
+import Text.Pandoc.Class.PandocMonad (PandocMonad, report)
 import Text.Pandoc.Definition
+import Text.Pandoc.Walk (walkM)
 import Text.Pandoc.Error
 import Text.Pandoc.ImageSize
 import Text.Pandoc.Logging
 import Text.Pandoc.Options
-import Text.Pandoc.Pretty
+import Text.DocLayout
 import Text.Pandoc.Shared
-import Text.Pandoc.Templates (renderTemplate')
+import Text.Pandoc.URI
+import Text.Pandoc.Templates (renderTemplate)
 import Text.Pandoc.Writers.Shared
 import Text.Printf (printf)
 
 data WriterState =
   WriterState { stStrikeout   :: Bool  -- document contains strikeout
-              , stSuperscript :: Bool -- document contains superscript
-              , stSubscript   :: Bool -- document contains subscript
-              , stEscapeComma :: Bool -- in a context where we need @comma
-              , stIdentifiers :: Set.Set String -- header ids used already
+              , stContext     :: Context
+              , stNodes       :: M.Map Text Int -- maps node to number of duplicates
+              , stHeadings    :: M.Map Text Text -- header ids to node texts
               , stOptions     :: WriterOptions -- writer options
               }
 
+data Context = NormalContext | NodeContext
+  deriving (Eq, Show)
+
+withContext :: PandocMonad m => Context -> TI m a -> TI m a
+withContext context pa = do
+  oldContext <- gets stContext
+  modify $ \s -> s{ stContext = context }
+  res <- pa
+  modify $ \s -> s{ stContext = oldContext }
+  pure res
+
+disallowedInNode :: Char -> Bool
+disallowedInNode c = c `elem` ['.',':',',','(',')']
+
 {- TODO:
  - internal cross references a la HTML
  - generated .texi files don't work when run through texi2dvi
@@ -72,90 +73,111 @@
 writeTexinfo :: PandocMonad m => WriterOptions -> Pandoc -> m Text
 writeTexinfo options document =
   evalStateT (pandocToTexinfo options $ wrapTop document)
-  WriterState { stStrikeout = False, stSuperscript = False,
-                stEscapeComma = False, stSubscript = False,
-                stIdentifiers = Set.empty, stOptions = options}
+  WriterState { stStrikeout = False,
+                stContext = NormalContext,
+                stNodes = mempty,
+                stHeadings = mempty,
+                stOptions = options}
 
 -- | Add a "Top" node around the document, needed by Texinfo.
 wrapTop :: Pandoc -> Pandoc
 wrapTop (Pandoc meta blocks) =
   Pandoc meta (Header 0 nullAttr (docTitle meta) : blocks)
 
+addNodeText :: PandocMonad m => Block -> TI m Block
+addNodeText (Header lev (ident,_,_) ils) | lev >= 1 && lev <= 4 = do
+  node <- render Nothing <$> withContext NodeContext (inlineListToTexinfo ils)
+  nodes <- gets stNodes
+  node' <- case M.lookup node nodes of
+                Just i -> do
+                  modify $ \st -> st{ stNodes = M.adjust (+ 1) node nodes }
+                  pure $ node <> " " <> tshow (i + 1)
+                Nothing -> do
+                  modify $ \st -> st{ stNodes = M.insert node 1 nodes }
+                  pure node
+  unless (T.null ident) $
+    modify $ \st -> st{ stHeadings = M.insert ident node' (stHeadings st) }
+  pure $ Header lev (ident,[],[("node", node')]) ils
+addNodeText x = pure  x
+
 pandocToTexinfo :: PandocMonad m => WriterOptions -> Pandoc -> TI m Text
-pandocToTexinfo options (Pandoc meta blocks) = do
+pandocToTexinfo options (Pandoc meta blocks') = do
+  blocks <- walkM addNodeText blocks'
   let titlePage = not $ all null
                       $ docTitle meta : docDate meta : docAuthors meta
   let colwidth = if writerWrapText options == WrapAuto
                     then Just $ writerColumns options
                     else Nothing
-  let render' :: Doc -> Text
-      render' = render colwidth
-  metadata <- metaToJSON options
-              (fmap render' . blockListToTexinfo)
-              (fmap render' . inlineListToTexinfo)
+  metadata <- metaToContext options
+              blockListToTexinfo
+              (fmap chomp .inlineListToTexinfo)
               meta
-  main <- blockListToTexinfo blocks
+  body <- blockListToTexinfo blocks
   st <- get
-  let body = render colwidth main
   let context = defField "body" body
               $ defField "toc" (writerTableOfContents options)
               $ defField "titlepage" titlePage
-              $ defField "subscript" (stSubscript st)
-              $ defField "superscript" (stSuperscript st)
-              $
-        defField "strikeout" (stStrikeout st) metadata
-  case writerTemplate options of
-       Nothing  -> return body
-       Just tpl -> renderTemplate' tpl context
+              $ defField "strikeout" (stStrikeout st) metadata
+  return $ render colwidth $
+    case writerTemplate options of
+       Nothing  -> body
+       Just tpl -> renderTemplate tpl context
 
 -- | Escape things as needed for Texinfo.
-stringToTexinfo :: String -> String
-stringToTexinfo = escapeStringUsing texinfoEscapes
-  where texinfoEscapes = [ ('{', "@{")
-                         , ('}', "@}")
-                         , ('@', "@@")
-                         , ('\160', "@ ")
-                         , ('\x2014', "---")
-                         , ('\x2013', "--")
-                         , ('\x2026', "@dots{}")
-                         , ('\x2019', "'")
-                         ]
-
-escapeCommas :: PandocMonad m => TI m Doc -> TI m Doc
-escapeCommas parser = do
-  oldEscapeComma <- gets stEscapeComma
-  modify $ \st -> st{ stEscapeComma = True }
-  res <- parser
-  modify $ \st -> st{ stEscapeComma = oldEscapeComma }
-  return res
+stringToTexinfo :: PandocMonad m => Text -> TI m Text
+stringToTexinfo t
+  | T.all isAlphaNum t = pure t
+  | otherwise = do
+      context <- gets stContext
+      let escChar '{'      = "@{"
+          escChar '}'      = "@}"
+          escChar '@'      = "@@"
+          escChar '\160'   = "@ "
+          escChar '\x2014' = "---"
+          escChar '\x2013' = "--"
+          escChar '\x2026' = "@dots{}"
+          escChar '\x2019' = "'"
+          escChar ',' | context == NodeContext = ""
+          escChar ':' | context == NodeContext = ""
+          escChar '.' | context == NodeContext = ""
+          escChar '(' | context == NodeContext = ""
+          escChar ')' | context == NodeContext = ""
+          escChar c        = T.singleton c
+      pure $ T.concatMap escChar t
 
 -- | Puts contents into Texinfo command.
-inCmd :: String -> Doc -> Doc
-inCmd cmd contents = char '@' <> text cmd <> braces contents
+inCmd :: Text -> Doc Text -> Doc Text
+inCmd cmd contents = char '@' <> literal cmd <> braces contents
 
+isCodeOrBreak :: Inline -> Bool
+isCodeOrBreak (Code{}) = True
+isCodeOrBreak LineBreak = True
+isCodeOrBreak _ = False
+
+isCode :: Inline -> Bool
+isCode (Code{}) = True
+isCode _ = False
+
+codeToStr :: Inline -> Inline
+codeToStr (Code _ s) = Str s
+codeToStr x = x
+
 -- | Convert Pandoc block element to Texinfo.
 blockToTexinfo :: PandocMonad m
                => Block     -- ^ Block to convert
-               -> TI m Doc
-
-blockToTexinfo Null = return empty
+               -> TI m (Doc Text)
 
 blockToTexinfo (Div _ bs) = blockListToTexinfo bs
 
 blockToTexinfo (Plain lst) =
   inlineListToTexinfo lst
 
--- title beginning with fig: indicates that the image is a figure
-blockToTexinfo (Para [Image attr txt (src,'f':'i':'g':':':tit)]) = do
-  capt <- if null txt
-             then return empty
-             else (\c -> text "@caption" <> braces c) `fmap`
-                    inlineListToTexinfo txt
-  img  <- inlineToTexinfo (Image attr txt (src,tit))
-  return $ text "@float" $$ img $$ capt $$ text "@end float"
-
-blockToTexinfo (Para lst) =
-  inlineListToTexinfo lst    -- this is handled differently from Plain in blockListToTexinfo
+-- this is handled differently from Plain in blockListToTexinfo
+blockToTexinfo (Para lst)
+  | all isCodeOrBreak lst
+      = (\xs -> "@example" $$ vcat xs $$ "@end example")
+          <$> mapM (inlineToTexinfo . codeToStr) (filter isCode lst)
+  | otherwise = inlineListToTexinfo lst
 
 blockToTexinfo (LineBlock lns) =
   blockToTexinfo $ linesToPara lns
@@ -169,13 +191,13 @@
 blockToTexinfo (CodeBlock _ str) =
   return $ blankline $$
          text "@verbatim" $$
-         flush (text str) $$
+         flush (literal str) $$
          text "@end verbatim" <> blankline
 
 blockToTexinfo b@(RawBlock f str)
-  | f == "texinfo" = return $ text str
+  | f == "texinfo" = return $ literal str
   | f == "latex" || f == "tex" =
-                      return $ text "@tex" $$ text str $$ text "@end tex"
+                      return $ text "@tex" $$ literal str $$ text "@end tex"
   | otherwise      = do
       report $ BlockNotRendered b
       return empty
@@ -228,29 +250,26 @@
   return $ text "@node Top" $$
            text "@top " <> txt <> blankline
 
-blockToTexinfo (Header level _ lst)
-  | level < 1 || level > 4 = blockToTexinfo (Para lst)
-  | otherwise = do
-    node <- inlineListForNode lst
+blockToTexinfo (Header level (_,_,[("node",node)]) lst) = do
     txt <- inlineListToTexinfo lst
-    idsUsed <- gets stIdentifiers
-    let id' = uniqueIdent lst idsUsed
-    modify $ \st -> st{ stIdentifiers = Set.insert id' idsUsed }
     sec <- seccmd level
     return $ if (level > 0) && (level <= 4)
-                then blankline <> text "@node " <> node $$
-                     text sec <> txt $$
-                     text "@anchor" <> braces (text $ '#':id')
+                then blankline <> text "@node " <> literal node $$
+                     literal sec <> txt
                 else txt
     where
-      seccmd :: PandocMonad m => Int -> TI m String
+      seccmd :: PandocMonad m => Int -> TI m Text
       seccmd 1 = return "@chapter "
       seccmd 2 = return "@section "
       seccmd 3 = return "@subsection "
       seccmd 4 = return "@subsubsection "
       seccmd _ = throwError $ PandocSomeError "illegal seccmd level"
 
-blockToTexinfo (Table caption aligns widths heads rows) = do
+-- non-node header:
+blockToTexinfo (Header _ _ lst) = blockToTexinfo (Para lst)
+
+blockToTexinfo (Table _ blkCapt specs thead tbody tfoot) = do
+  let (caption, aligns, widths, heads, rows) = toLegacyTable blkCapt specs thead tbody tfoot
   headers <- if all null heads
                 then return empty
                 else tableHeadToTexinfo aligns heads
@@ -259,9 +278,13 @@
   colDescriptors <-
     if all (== 0) widths
        then do -- use longest entry instead of column widths
-            cols <- mapM (mapM (liftM (render Nothing . hcat) . mapM blockToTexinfo)) $
+            cols <- mapM (mapM (fmap (T.unpack . render Nothing . hcat) .
+                           mapM blockToTexinfo)) $
                         transpose $ heads : rows
-            return $ concatMap ((\x -> "{"++x++"} ") .  maximumBy (comparing length)) cols
+            return $ concatMap
+                ((\x -> "{"++x++"} ") .
+                        maybe "" (maximumBy (comparing length)) . nonEmpty)
+                cols
        else return $ "@columnfractions " ++ concatMap (printf "%.2f ") widths
   let tableBody = text ("@multitable " ++ colDescriptors) $$
                   headers $$
@@ -269,37 +292,69 @@
                   text "@end multitable"
   return $ if isEmpty captionText
               then tableBody <> blankline
-              else text "@float" $$
+              else text "@float Table" $$
                    tableBody $$
                    inCmd "caption" captionText $$
                    text "@end float"
 
+blockToTexinfo (Figure _ caption [SimpleFigure attr figCaption tgt]) = do
+  let capt = if null figCaption
+             then let (Caption _ cblks) = caption
+                  in blocksToInlines cblks
+             else figCaption
+  captionText <- if null capt
+                 then return empty
+                 else (text "@caption" <>) . braces <$> inlineListToTexinfo capt
+  img  <- inlineToTexinfo (Image attr figCaption tgt)
+  return $ text "@float Figure" $$ img $$ captionText $$ text "@end float"
+
+blockToTexinfo (Figure _ fCaption [
+    Table attr tCaption@(Caption _ cbody) specs thead tbody tfoot]) = do
+  let caption = case cbody of
+                  [] -> fCaption
+                  _  -> tCaption
+  blockToTexinfo (Table attr caption specs thead tbody tfoot)
+
+blockToTexinfo (Figure _ (Caption _ caption) body) = do
+  captionText <- inlineListToTexinfo $ blocksToInlines caption
+  content <- blockListToTexinfo body
+  return $ text ("@float" ++ floatType body) $$ content $$ (
+      if isEmpty captionText
+         then empty
+         else inCmd "caption" captionText
+    ) $$ text "@end float"
+  where
+  -- floatType according to
+  -- https://www.gnu.org/software/texinfo/manual/texinfo/html_node/_0040float.html
+  floatType [SimpleFigure {}] = " Figure"
+  floatType [Table {}] = " Table"
+  floatType _ = ""
+
 tableHeadToTexinfo :: PandocMonad m
                    => [Alignment]
                    -> [[Block]]
-                   -> TI m Doc
+                   -> TI m (Doc Text)
 tableHeadToTexinfo = tableAnyRowToTexinfo "@headitem "
 
 tableRowToTexinfo :: PandocMonad m
                   => [Alignment]
                   -> [[Block]]
-                  -> TI m Doc
+                  -> TI m (Doc Text)
 tableRowToTexinfo = tableAnyRowToTexinfo "@item "
 
 tableAnyRowToTexinfo :: PandocMonad m
-                     => String
+                     => Text
                      -> [Alignment]
                      -> [[Block]]
-                     -> TI m Doc
+                     -> TI m (Doc Text)
 tableAnyRowToTexinfo itemtype aligns cols =
-  zipWithM alignedBlock aligns cols >>=
-  return . (text itemtype $$) . foldl (\row item -> row $$
-  (if isEmpty row then empty else text " @tab ") <> item) empty
+  (literal itemtype $$) . L.foldl' (\row item -> row $$
+  (if isEmpty row then empty else text " @tab ") <> item) empty <$> zipWithM alignedBlock aligns cols
 
 alignedBlock :: PandocMonad m
              => Alignment
              -> [Block]
-             -> TI m Doc
+             -> TI m (Doc Text)
 -- XXX @flushleft and @flushright text won't get word wrapped.  Since word
 -- wrapping is more important than alignment, we ignore the alignment.
 alignedBlock _ = blockListToTexinfo
@@ -316,7 +371,7 @@
 -- | Convert Pandoc block elements to Texinfo.
 blockListToTexinfo :: PandocMonad m
                    => [Block]
-                   -> TI m Doc
+                   -> TI m (Doc Text)
 blockListToTexinfo [] = return empty
 blockListToTexinfo (x:xs) = do
   x' <- blockToTexinfo x
@@ -331,7 +386,8 @@
       lines' <- mapM makeMenuLine menu
       let menu' = if null lines'
                     then empty
-                    else text "@menu" $$
+                    else blankline $$
+                         text "@menu" $$
                          vcat lines' $$
                          text "@end menu"
       after' <- blockListToTexinfo after
@@ -349,26 +405,27 @@
 collectNodes _ [] = []
 collectNodes level (x:xs) =
   case x of
-    (Header hl _ _) ->
-      if hl < level
-         then []
-         else if hl == level
-                 then x : collectNodes level xs
-                 else collectNodes level xs
+    (Header hl _ _)
+      | hl < level -> []
+      | hl == level -> x : collectNodes level xs
+      | otherwise -> collectNodes level xs
     _ ->
       collectNodes level xs
 
 makeMenuLine :: PandocMonad m
              => Block
-             -> TI m Doc
-makeMenuLine (Header _ _ lst) = do
-  txt <- inlineListForNode lst
-  return $ text "* " <> txt <> text "::"
-makeMenuLine _ = throwError $ PandocSomeError "makeMenuLine called with non-Header block"
+             -> TI m (Doc Text)
+makeMenuLine (Header _ (_,_,[("node", node)]) lst) = do
+  txt <- withContext NodeContext $ inlineListToTexinfo lst
+  pure $ nowrap $ text "* " <>
+    if render Nothing txt == node
+       then literal node <> "::"
+       else txt <> ": " <> literal node <> "."
+makeMenuLine _ = throwError $ PandocSomeError "makeMenuLine called with non-node"
 
 listItemToTexinfo :: PandocMonad m
                   => [Block]
-                  -> TI m Doc
+                  -> TI m (Doc Text)
 listItemToTexinfo lst = do
   contents <- blockListToTexinfo lst
   let spacer = case reverse lst of
@@ -378,7 +435,7 @@
 
 defListItemToTexinfo :: PandocMonad m
                      => ([Inline], [[Block]])
-                     -> TI m Doc
+                     -> TI m (Doc Text)
 defListItemToTexinfo (term, defs) = do
     term' <- inlineListToTexinfo term
     let defToTexinfo bs = do d <- blockListToTexinfo bs
@@ -391,33 +448,26 @@
 -- | Convert list of inline elements to Texinfo.
 inlineListToTexinfo :: PandocMonad m
                     => [Inline]  -- ^ Inlines to convert
-                    -> TI m Doc
-inlineListToTexinfo lst = mapM inlineToTexinfo lst >>= return . hcat
-
--- | Convert list of inline elements to Texinfo acceptable for a node name.
-inlineListForNode :: PandocMonad m
-                  => [Inline]  -- ^ Inlines to convert
-                  -> TI m Doc
-inlineListForNode = return . text . stringToTexinfo .
-                    filter (not . disallowedInNode) . stringify
-
--- periods, commas, colons, and parentheses are disallowed in node names
-disallowedInNode :: Char -> Bool
-disallowedInNode c = c `elem` (".,:()" :: String)
+                    -> TI m (Doc Text)
+inlineListToTexinfo lst = hcat <$> mapM inlineToTexinfo lst
 
 -- | Convert inline element to Texinfo
 inlineToTexinfo :: PandocMonad m
                 => Inline    -- ^ Inline to convert
-                -> TI m Doc
+                -> TI m (Doc Text)
 
 inlineToTexinfo (Span _ lst) =
   inlineListToTexinfo lst
 
 inlineToTexinfo (Emph lst) =
-  inlineListToTexinfo lst >>= return . inCmd "emph"
+  inCmd "emph" <$> inlineListToTexinfo lst
 
+-- Underline isn't supported, fall back to Emph
+inlineToTexinfo (Underline lst) =
+  inlineToTexinfo (Emph lst)
+
 inlineToTexinfo (Strong lst) =
-  inlineListToTexinfo lst >>= return . inCmd "strong"
+  inCmd "strong" <$> inlineListToTexinfo lst
 
 inlineToTexinfo (Strikeout lst) = do
   modify $ \st -> st{ stStrikeout = True }
@@ -425,21 +475,24 @@
   return $ text "@textstrikeout{" <> contents <> text "}"
 
 inlineToTexinfo (Superscript lst) = do
-  modify $ \st -> st{ stSuperscript = True }
   contents <- inlineListToTexinfo lst
-  return $ text "@textsuperscript{" <> contents <> char '}'
+  return $ text "@sup{" <> contents <> char '}'
 
 inlineToTexinfo (Subscript lst) = do
-  modify $ \st -> st{ stSubscript = True }
   contents <- inlineListToTexinfo lst
-  return $ text "@textsubscript{" <> contents <> char '}'
+  return $ text "@sub{" <> contents <> char '}'
 
 inlineToTexinfo (SmallCaps lst) =
-  inlineListToTexinfo lst >>= return . inCmd "sc"
+  inCmd "sc" <$> inlineListToTexinfo lst
 
-inlineToTexinfo (Code _ str) =
-  return $ text $ "@code{" ++ stringToTexinfo str ++ "}"
+inlineToTexinfo (Code (_, cls , _) str) | T.pack "variable" `elem` cls  = do
+  code <- stringToTexinfo str
+  return $ literal $ "@code{@var{" <> code <> "}}"
 
+inlineToTexinfo (Code _ str) = do
+  code <- stringToTexinfo str
+  return $ literal $ "@code{" <> code <> "}"
+
 inlineToTexinfo (Quoted SingleQuote lst) = do
   contents <- inlineListToTexinfo lst
   return $ char '`' <> contents <> char '\''
@@ -450,12 +503,12 @@
 
 inlineToTexinfo (Cite _ lst) =
   inlineListToTexinfo lst
-inlineToTexinfo (Str str) = return $ text (stringToTexinfo str)
-inlineToTexinfo (Math _ str) = return $ inCmd "math" $ text str
+inlineToTexinfo (Str str) = literal <$> stringToTexinfo str
+inlineToTexinfo (Math _ str) = return $ inCmd "math" $ literal str
 inlineToTexinfo il@(RawInline f str)
   | f == "latex" || f == "tex" =
-                      return $ text "@tex" $$ text str $$ text "@end tex"
-  | f == "texinfo" =  return $ text str
+                      return $ text "@tex" $$ literal str $$ text "@end tex"
+  | f == "texinfo" =  return $ literal str
   | otherwise      =  do
       report $ InlineNotRendered il
       return empty
@@ -468,35 +521,43 @@
       WrapPreserve -> return cr
 inlineToTexinfo Space = return space
 
-inlineToTexinfo (Link _ txt (src@('#':_), _)) = do
-  contents <- escapeCommas $ inlineListToTexinfo txt
-  return $ text "@ref" <>
-           braces (text (stringToTexinfo src) <> text "," <> contents)
-inlineToTexinfo (Link _ txt (src, _)) =
-  case txt of
-        [Str x] | escapeURI x == src ->  -- autolink
-             do return $ text $ "@url{" ++ x ++ "}"
-        _ -> do contents <- escapeCommas $ inlineListToTexinfo txt
-                let src1 = stringToTexinfo src
-                return $ text ("@uref{" ++ src1 ++ ",") <> contents <>
-                         char '}'
+inlineToTexinfo (Link _ txt (src, _))
+  | Just ('#', ident) <- T.uncons src = do
+      headings <- gets stHeadings
+      target <- case M.lookup ident headings of
+                  Nothing -> literal <$> stringToTexinfo
+                                    (T.filter (not . disallowedInNode) src)
+                  Just node -> pure $ literal node
+      contents <- withContext NodeContext $ inlineListToTexinfo txt
+      return $ text "@ref"
+        <> braces (target <> if contents == target
+                                then mempty
+                                else text ",," <> contents)
+  | otherwise = case txt of
+      [Str x] | escapeURI x == src ->  -- autolink
+                  return $ literal $ "@url{" <> x <> "}"
+      _ -> do
+        contents <- withContext NodeContext $ inlineListToTexinfo txt
+        src1 <- stringToTexinfo src
+        return $ literal ("@uref{" <> src1 <> ",") <> contents <>
+                 char '}'
 
 inlineToTexinfo (Image attr alternate (source, _)) = do
-  content <- escapeCommas $ inlineListToTexinfo alternate
+  content <- withContext NodeContext $ inlineListToTexinfo alternate
   opts <- gets stOptions
   let showDim dim = case dimension dim attr of
-                      (Just (Pixel a))   -> showInInch opts (Pixel a) ++ "in"
+                      (Just (Pixel a))   -> showInInch opts (Pixel a) <> "in"
                       (Just (Percent _)) -> ""
-                      (Just d)           -> show d
+                      (Just d)           -> tshow d
                       Nothing            -> ""
-  return $ text ("@image{" ++ base ++ ',':(showDim Width) ++ ',':(showDim Height) ++ ",")
-           <> content <> text "," <> text (ext ++ "}")
+  return $ literal ("@image{" <> base <> "," <> showDim Width <> "," <> showDim Height <> ",")
+           <> content <> text "," <> literal (ext <> "}")
   where
-    ext     = drop 1 $ takeExtension source'
-    base    = dropExtension source'
+    ext     = T.drop 1 $ T.pack $ takeExtension source'
+    base    = T.pack $ dropExtension source'
     source' = if isURI source
-                 then source
-                 else unEscapeString source
+              then T.unpack source
+              else unEscapeString $ T.unpack source
 
 inlineToTexinfo (Note contents) = do
   contents' <- blockListToTexinfo contents
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,24 +1,7 @@
-{-
-Copyright (C) 2010-2017 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 OverloadedStrings #-}
 {- |
    Module      : Text.Pandoc.Writers.Textile
-   Copyright   : Copyright (C) 2010-2017 John MacFarlane
+   Copyright   : Copyright (C) 2010-2024 John MacFarlane
    License     : GNU GPL, version 2 or above
 
    Maintainer  : John MacFarlane <jgm@berkeley.edu>
@@ -30,26 +13,27 @@
 Textile:  <http://thresholdstate.com/articles/4312/the-textile-reference-manual>
 -}
 module Text.Pandoc.Writers.Textile ( writeTextile ) where
-import Control.Monad.State.Strict
+import Control.Monad (zipWithM, liftM)
+import Control.Monad.State.Strict ( StateT, gets, modify, evalStateT )
 import Data.Char (isSpace)
-import Data.List (intercalate)
-import Data.Text (Text, pack)
-import Text.Pandoc.Class (PandocMonad, report)
+import Data.Text (Text)
+import qualified Data.Text as T
+import Text.Pandoc.Class.PandocMonad (PandocMonad, report)
 import Text.Pandoc.Definition
 import Text.Pandoc.ImageSize
 import Text.Pandoc.Logging
 import Text.Pandoc.Options
-import Text.Pandoc.Pretty (render)
+import Text.DocLayout (render, literal)
 import Text.Pandoc.Shared
-import Text.Pandoc.Templates (renderTemplate')
+import Text.Pandoc.Templates (renderTemplate)
 import Text.Pandoc.Writers.Shared
 import Text.Pandoc.XML (escapeStringForXML)
 
 data WriterState = WriterState {
-    stNotes     :: [String]        -- Footnotes
-  , stListLevel :: [Char]          -- String at beginning of list items, e.g. "**"
-  , stStartNum  :: Maybe Int       -- Start number if first list item
-  , stUseTags   :: Bool            -- True if we should use HTML tags because we're in a complex list
+    stNotes     :: [Text]        -- Footnotes
+  , stListLevel :: [Char]        -- String at beginning of list items, e.g. "**"
+  , stStartNum  :: Maybe Int     -- Start number if first list item
+  , stUseTags   :: Bool          -- True if we should use HTML tags because we're in a complex list
   }
 
 type TW = StateT WriterState
@@ -67,15 +51,17 @@
 pandocToTextile :: PandocMonad m
                 => WriterOptions -> Pandoc -> TW m Text
 pandocToTextile opts (Pandoc meta blocks) = do
-  metadata <- metaToJSON opts (blockListToTextile opts)
-                 (inlineListToTextile opts) meta
+  metadata <- metaToContext opts
+                 (fmap literal . blockListToTextile opts)
+                 (fmap literal . inlineListToTextile opts) meta
   body <- blockListToTextile opts blocks
-  notes <- gets $ unlines . reverse . stNotes
-  let main = pack $ body ++ if null notes then "" else ("\n\n" ++ notes)
+  notes <- gets $ T.unlines . reverse . stNotes
+  let main = body <> if T.null notes then "" else "\n\n" <> notes
   let context = defField "body" main metadata
-  case writerTemplate opts of
-         Nothing  -> return main
-         Just tpl -> renderTemplate' tpl context
+  return $
+    case writerTemplate opts of
+         Nothing  -> main
+         Just tpl -> render Nothing $ renderTemplate tpl context
 
 withUseTags :: PandocMonad m => TW m a -> TW m a
 withUseTags action = do
@@ -86,7 +72,7 @@
   return result
 
 -- | Escape one character as needed for Textile.
-escapeCharForTextile :: Char -> String
+escapeCharForTextile :: Char -> Text
 escapeCharForTextile x = case x of
                          '&'      -> "&amp;"
                          '<'      -> "&lt;"
@@ -102,42 +88,34 @@
                          '\x2013' -> " - "
                          '\x2019' -> "'"
                          '\x2026' -> "..."
-                         c        -> [c]
+                         c        -> T.singleton c
 
 -- | Escape string as needed for Textile.
-escapeStringForTextile :: String -> String
-escapeStringForTextile = concatMap escapeCharForTextile
+escapeTextForTextile :: Text -> Text
+escapeTextForTextile = T.concatMap escapeCharForTextile
 
 -- | Convert Pandoc block element to Textile.
 blockToTextile :: PandocMonad m
                => WriterOptions -- ^ Options
                -> Block         -- ^ Block element
-               -> TW m String
-
-blockToTextile _ Null = return ""
+               -> TW m Text
 
 blockToTextile opts (Div attr bs) = do
   let startTag = render Nothing $ tagWithAttrs "div" attr
   let endTag = "</div>"
   contents <- blockListToTextile opts bs
-  return $ startTag ++ "\n\n" ++ contents ++ "\n\n" ++ endTag ++ "\n"
+  return $ startTag <> "\n\n" <> contents <> "\n\n" <> endTag <> "\n"
 
 blockToTextile opts (Plain inlines) =
   inlineListToTextile opts inlines
 
--- title beginning with fig: indicates that the image is a figure
-blockToTextile opts (Para [Image attr txt (src,'f':'i':'g':':':tit)]) = do
-  capt <- blockToTextile opts (Para txt)
-  im <- inlineToTextile opts (Image attr txt (src,tit))
-  return $ im ++ "\n" ++ capt
-
 blockToTextile opts (Para inlines) = do
   useTags <- gets stUseTags
   listLevel <- gets stListLevel
   contents <- inlineListToTextile opts inlines
   return $ if useTags
-              then "<p>" ++ contents ++ "</p>"
-              else contents ++ if null listLevel then "\n" else ""
+              then "<p>" <> contents <> "</p>"
+              else contents <> if null listLevel then "\n" else ""
 
 blockToTextile opts (LineBlock lns) =
   blockToTextile opts $ linesToPara lns
@@ -152,74 +130,74 @@
 
 blockToTextile opts (Header level (ident,classes,keyvals) inlines) = do
   contents <- inlineListToTextile opts inlines
-  let identAttr = if null ident then "" else ('#':ident)
-  let attribs = if null identAttr && null classes
+  let identAttr = if T.null ident then "" else "#" <> ident
+  let attribs = if T.null identAttr && null classes
                    then ""
-                   else "(" ++ unwords classes ++ identAttr ++ ")"
-  let lang = maybe "" (\x -> "[" ++ x ++ "]") $ lookup "lang" keyvals
-  let styles = maybe "" (\x -> "{" ++ x ++ "}") $ lookup "style" keyvals
-  let prefix = 'h' : show level ++ attribs ++ styles ++ lang ++ ". "
-  return $ prefix ++ contents ++ "\n"
+                   else "(" <> T.unwords classes <> identAttr <> ")"
+  let lang = maybe "" (\x -> "[" <> x <> "]") $ lookup "lang" keyvals
+  let styles = maybe "" (\x -> "{" <> x <> "}") $ lookup "style" keyvals
+  let prefix = "h" <> tshow level <> attribs <> styles <> lang <> ". "
+  return $ prefix <> contents <> "\n"
 
-blockToTextile _ (CodeBlock (_,classes,_) str) | any (all isSpace) (lines str) =
-  return $ "<pre"  ++ classes' ++ ">\n" ++ escapeStringForXML str ++
+blockToTextile _ (CodeBlock (_,classes,_) str) | any (T.all isSpace) (T.lines str) =
+  return $ "<pre"  <> classes' <> ">\n" <> escapeStringForXML str <>
            "\n</pre>\n"
     where classes' = if null classes
                         then ""
-                        else " class=\"" ++ unwords classes ++ "\""
+                        else " class=\"" <> T.unwords classes <> "\""
 
 blockToTextile _ (CodeBlock (_,classes,_) str) =
-  return $ "bc" ++ classes' ++ ". " ++ str ++ "\n\n"
+  return $ "bc" <> classes' <> ". " <> str <> "\n\n"
     where classes' = if null classes
                         then ""
-                        else "(" ++ unwords classes ++ ")"
+                        else "(" <> T.unwords classes <> ")"
 
 blockToTextile opts (BlockQuote bs@[Para _]) = do
   contents <- blockListToTextile opts bs
-  return $ "bq. " ++ contents ++ "\n\n"
+  return $ "bq. " <> contents <> "\n\n"
 
 blockToTextile opts (BlockQuote blocks) = do
   contents <- blockListToTextile opts blocks
-  return $ "<blockquote>\n\n" ++ contents ++ "\n</blockquote>\n"
-
-blockToTextile opts (Table [] aligns widths headers rows') |
-         all (==0) widths = do
-  hs <- mapM (liftM (("_. " ++) . stripTrailingNewlines) . blockListToTextile opts) headers
-  let cellsToRow cells = "|" ++ intercalate "|" cells ++ "|"
-  let header = if all null headers then "" else cellsToRow hs ++ "\n"
-  let blocksToCell (align, bs) = do
-        contents <- stripTrailingNewlines <$> blockListToTextile opts bs
-        let alignMarker = case align of
-                               AlignLeft    -> "<. "
-                               AlignRight   -> ">. "
-                               AlignCenter  -> "=. "
-                               AlignDefault -> ""
-        return $ alignMarker ++ contents
-  let rowToCells = mapM blocksToCell . zip aligns
-  bs <- mapM rowToCells rows'
-  let body = unlines $ map cellsToRow bs
-  return $ header ++ body
+  return $ "<blockquote>\n\n" <> contents <> "\n</blockquote>\n"
 
-blockToTextile opts (Table capt aligns widths headers rows') = do
-  let alignStrings = map alignmentToString aligns
-  captionDoc <- if null capt
-                   then return ""
-                   else do
-                      c <- inlineListToTextile opts capt
-                      return $ "<caption>" ++ c ++ "</caption>\n"
-  let percent w = show (truncate (100*w) :: Integer) ++ "%"
-  let coltags = if all (== 0.0) widths
-                   then ""
-                   else unlines $ map
-                         (\w -> "<col width=\"" ++ percent w ++ "\" />") widths
-  head' <- if all null headers
-              then return ""
-              else do
-                 hs <- tableRowToTextile opts alignStrings 0 headers
-                 return $ "<thead>\n" ++ hs ++ "\n</thead>\n"
-  body' <- zipWithM (tableRowToTextile opts alignStrings) [1..] rows'
-  return $ "<table>\n" ++ captionDoc ++ coltags ++ head' ++
-            "<tbody>\n" ++ unlines body' ++ "</tbody>\n</table>\n"
+blockToTextile opts (Table _ blkCapt specs thead tbody tfoot)
+  = case toLegacyTable blkCapt specs thead tbody tfoot of
+      ([], aligns, widths, headers, rows') | all (==0) widths -> do
+        hs <- mapM (liftM (("_. " <>) . stripTrailingNewlines) . blockListToTextile opts) headers
+        let cellsToRow cells = "|" <> T.intercalate "|" cells <> "|"
+        let header = if all null headers then "" else cellsToRow hs <> "\n"
+        let blocksToCell (align, bs) = do
+              contents <- stripTrailingNewlines <$> blockListToTextile opts bs
+              let alignMarker = case align of
+                                     AlignLeft    -> "<. "
+                                     AlignRight   -> ">. "
+                                     AlignCenter  -> "=. "
+                                     AlignDefault -> ""
+              return $ alignMarker <> contents
+        let rowToCells = mapM blocksToCell . zip aligns
+        bs <- mapM rowToCells rows'
+        let body = T.unlines $ map cellsToRow bs
+        return $ header <> body
+      (capt, aligns, widths, headers, rows') -> do
+        let alignStrings = map alignmentToText aligns
+        captionDoc <- if null capt
+                         then return ""
+                         else do
+                            c <- inlineListToTextile opts capt
+                            return $ "<caption>" <> c <> "</caption>\n"
+        let percent w = tshow (truncate (100*w) :: Integer) <> "%"
+        let coltags = if all (== 0.0) widths
+                         then ""
+                         else T.unlines $ map
+                               (\w -> "<col width=\"" <> percent w <> "\" />") widths
+        head' <- if all null headers
+                    then return ""
+                    else do
+                       hs <- tableRowToTextile opts alignStrings 0 headers
+                       return $ "<thead>\n" <> hs <> "\n</thead>\n"
+        body' <- zipWithM (tableRowToTextile opts alignStrings) [1..] rows'
+        return $ "<table>\n" <> captionDoc <> coltags <> head' <>
+                  "<tbody>\n" <> T.unlines body' <> "</tbody>\n</table>\n"
 
 blockToTextile opts x@(BulletList items) = do
   oldUseTags <- gets stUseTags
@@ -227,13 +205,13 @@
   if useTags
      then do
         contents <- withUseTags $ mapM (listItemToTextile opts) items
-        return $ "<ul>\n" ++ vcat contents ++ "\n</ul>\n"
+        return $ "<ul>\n" <> vcat contents <> "\n</ul>\n"
      else do
-        modify $ \s -> s { stListLevel = stListLevel s ++ "*" }
+        modify $ \s -> s { stListLevel = stListLevel s <> "*" }
         level <- gets $ length . stListLevel
         contents <- mapM (listItemToTextile opts) items
         modify $ \s -> s { stListLevel = init (stListLevel s) }
-        return $ vcat contents ++ (if level > 1 then "" else "\n")
+        return $ vcat contents <> (if level > 1 then "" else "\n")
 
 blockToTextile opts x@(OrderedList attribs@(start, _, _) items) = do
   oldUseTags <- gets stUseTags
@@ -241,10 +219,10 @@
   if useTags
      then do
         contents <- withUseTags $ mapM (listItemToTextile opts) items
-        return $ "<ol" ++ listAttribsToString attribs ++ ">\n" ++ vcat contents ++
+        return $ "<ol" <> listAttribsToString attribs <> ">\n" <> vcat contents <>
                    "\n</ol>\n"
      else do
-        modify $ \s -> s { stListLevel = stListLevel s ++ "#"
+        modify $ \s -> s { stListLevel = stListLevel s <> "#"
                          , stStartNum = if start > 1
                                            then Just start
                                            else Nothing }
@@ -252,52 +230,65 @@
         contents <- mapM (listItemToTextile opts) items
         modify $ \s -> s { stListLevel = init (stListLevel s),
                            stStartNum = Nothing }
-        return $ vcat contents ++ (if level > 1 then "" else "\n")
+        return $ vcat contents <> (if level > 1 then "" else "\n")
 
 blockToTextile opts (DefinitionList items) = do
   contents <- withUseTags $ mapM (definitionListItemToTextile opts) items
-  return $ "<dl>\n" ++ vcat contents ++ "\n</dl>\n"
+  return $ "<dl>\n" <> vcat contents <> "\n</dl>\n"
 
+blockToTextile opts (Figure attr (Caption _ caption)  body) = do
+  let startTag = render Nothing $ tagWithAttrs "figure" attr
+  let endTag = "</figure>"
+  let captionInlines = blocksToInlines caption
+  captionMarkup <- if null captionInlines
+                      then return ""
+                      else ((<> "\n\n</figcaption>\n\n") .  ("<figcaption>\n\n" <>)) <$>
+                          inlineListToTextile opts (blocksToInlines caption)
+  contents <- blockListToTextile opts body
+  return $ startTag <> "\n\n" <>
+    captionMarkup <>
+    contents <> "\n\n" <> endTag <> "\n"
+
 -- Auxiliary functions for lists:
 
 -- | Convert ordered list attributes to HTML attribute string
-listAttribsToString :: ListAttributes -> String
+listAttribsToString :: ListAttributes -> Text
 listAttribsToString (startnum, numstyle, _) =
-  let numstyle' = camelCaseToHyphenated $ show numstyle
+  let numstyle' = camelCaseToHyphenated $ tshow numstyle
   in  (if startnum /= 1
-          then " start=\"" ++ show startnum ++ "\""
-          else "") ++
+          then " start=\"" <> tshow startnum <> "\""
+          else "") <>
       (if numstyle /= DefaultStyle
-          then " style=\"list-style-type: " ++ numstyle' ++ ";\""
+          then " style=\"list-style-type: " <> numstyle' <> ";\""
           else "")
 
 -- | Convert bullet or ordered list item (list of blocks) to Textile.
 listItemToTextile :: PandocMonad m
-                  => WriterOptions -> [Block] -> TW m String
+                  => WriterOptions -> [Block] -> TW m Text
 listItemToTextile opts items = do
   contents <- blockListToTextile opts items
   useTags <- gets stUseTags
   if useTags
-     then return $ "<li>" ++ contents ++ "</li>"
+     then return $ "<li>" <> contents <> "</li>"
      else do
        marker <- gets stListLevel
        mbstart <- gets stStartNum
        case mbstart of
             Just n -> do
               modify $ \s -> s{ stStartNum = Nothing }
-              return $ marker ++ show n ++ " " ++ contents
-            Nothing -> return $ marker ++ " " ++ contents
+              return $ T.pack marker <> tshow n <> " " <> contents
+            Nothing -> return $ T.pack marker <> " " <> contents
 
 -- | Convert definition list item (label, list of blocks) to Textile.
 definitionListItemToTextile :: PandocMonad m
                             => WriterOptions
                              -> ([Inline],[[Block]])
-                             -> TW m String
+                             -> TW m Text
 definitionListItemToTextile opts (label, items) = do
   labelText <- inlineListToTextile opts label
   contents <- mapM (blockListToTextile opts) items
-  return $ "<dt>" ++ labelText ++ "</dt>\n" ++
-          intercalate "\n" (map (\d -> "<dd>" ++ d ++ "</dd>") contents)
+  return $ "<dt>" <> labelText <> "</dt>\n" <>
+          T.intercalate "\n" (map (\d -> "<dd>" <> d <> "</dd>") contents)
 
 -- | True if the list can be handled by simple wiki markup, False if HTML tags will be needed.
 isSimpleList :: Block -> Bool
@@ -332,31 +323,27 @@
 isPlainOrPara _         = False
 
 -- | Concatenates strings with line breaks between them.
-vcat :: [String] -> String
-vcat = intercalate "\n"
+vcat :: [Text] -> Text
+vcat = T.intercalate "\n"
 
 -- Auxiliary functions for tables. (TODO: these are common to HTML, MediaWiki,
 -- and Textile writers, and should be abstracted out.)
 
 tableRowToTextile :: PandocMonad m
                   => WriterOptions
-                  -> [String]
+                  -> [Text]
                   -> Int
                   -> [[Block]]
-                  -> TW m String
+                  -> TW m Text
 tableRowToTextile opts alignStrings rownum cols' = do
   let celltype = if rownum == 0 then "th" else "td"
-  let rowclass = case rownum of
-                      0 -> "header"
-                      x | x `rem` 2 == 1 -> "odd"
-                      _ -> "even"
   cols'' <- zipWithM
             (\alignment item -> tableItemToTextile opts celltype alignment item)
             alignStrings cols'
-  return $ "<tr class=\"" ++ rowclass ++ "\">\n" ++ unlines cols'' ++ "</tr>"
+  return $ "<tr>\n" <> T.unlines cols'' <> "</tr>"
 
-alignmentToString :: Alignment -> [Char]
-alignmentToString alignment = case alignment of
+alignmentToText :: Alignment -> Text
+alignmentToText alignment = case alignment of
                                  AlignLeft    -> "left"
                                  AlignRight   -> "right"
                                  AlignCenter  -> "center"
@@ -364,13 +351,13 @@
 
 tableItemToTextile :: PandocMonad m
                    => WriterOptions
-                   -> String
-                   -> String
+                   -> Text
+                   -> Text
                    -> [Block]
-                   -> TW m String
+                   -> TW m Text
 tableItemToTextile opts celltype align' item = do
-  let mkcell x = "<" ++ celltype ++ " align=\"" ++ align' ++ "\">" ++
-                    x ++ "</" ++ celltype ++ ">"
+  let mkcell x = "<" <> celltype <> " align=\"" <> align' <> "\">" <>
+                    x <> "</" <> celltype <> ">"
   contents <- blockListToTextile opts item
   return $ mkcell contents
 
@@ -378,73 +365,79 @@
 blockListToTextile :: PandocMonad m
                    => WriterOptions -- ^ Options
                    -> [Block]       -- ^ List of block elements
-                   -> TW m String
+                   -> TW m Text
 blockListToTextile opts blocks =
-  mapM (blockToTextile opts) blocks >>= return . vcat
+  vcat <$> mapM (blockToTextile opts) blocks
 
 -- | Convert list of Pandoc inline elements to Textile.
 inlineListToTextile :: PandocMonad m
-                    => WriterOptions -> [Inline] -> TW m String
+                    => WriterOptions -> [Inline] -> TW m Text
 inlineListToTextile opts lst =
-  mapM (inlineToTextile opts) lst >>= return . concat
+  T.concat <$> mapM (inlineToTextile opts) lst
 
 -- | Convert Pandoc inline element to Textile.
-inlineToTextile :: PandocMonad m => WriterOptions -> Inline -> TW m String
+inlineToTextile :: PandocMonad m => WriterOptions -> Inline -> TW m Text
 
 inlineToTextile opts (Span _ lst) =
   inlineListToTextile opts lst
 
 inlineToTextile opts (Emph lst) = do
   contents <- inlineListToTextile opts lst
-  return $ if '_' `elem` contents
-              then "<em>" ++ contents ++ "</em>"
-              else "_" ++ contents ++ "_"
+  return $ if T.any (== '_') contents
+              then "<em>" <> contents <> "</em>"
+              else "_" <> contents <> "_"
 
+inlineToTextile opts (Underline lst) = do
+  contents <- inlineListToTextile opts lst
+  return $ if T.any (== '+') contents
+              then "<u>" <> contents <> "</u>"
+              else "+" <> contents <> "+"
+
 inlineToTextile opts (Strong lst) = do
   contents <- inlineListToTextile opts lst
-  return $ if '*' `elem` contents
-              then "<strong>" ++ contents ++ "</strong>"
-              else "*" ++ contents ++ "*"
+  return $ if T.any (== '*') contents
+              then "<strong>" <> contents <> "</strong>"
+              else "*" <> contents <> "*"
 
 inlineToTextile opts (Strikeout lst) = do
   contents <- inlineListToTextile opts lst
-  return $ if '-' `elem` contents
-              then "<del>" ++ contents ++ "</del>"
-              else "-" ++ contents ++ "-"
+  return $ if T.any (== '-') contents
+              then "<del>" <> contents <> "</del>"
+              else "-" <> contents <> "-"
 
 inlineToTextile opts (Superscript lst) = do
   contents <- inlineListToTextile opts lst
-  return $ if '^' `elem` contents
-              then "<sup>" ++ contents ++ "</sup>"
-              else "[^" ++ contents ++ "^]"
+  return $ if T.any (== '^') contents
+              then "<sup>" <> contents <> "</sup>"
+              else "[^" <> contents <> "^]"
 
 inlineToTextile opts (Subscript lst) = do
   contents <- inlineListToTextile opts lst
-  return $ if '~' `elem` contents
-              then "<sub>" ++ contents ++ "</sub>"
-              else "[~" ++ contents ++ "~]"
+  return $ if T.any (== '~') contents
+              then "<sub>" <> contents <> "</sub>"
+              else "[~" <> contents <> "~]"
 
 inlineToTextile opts (SmallCaps lst) = inlineListToTextile opts lst
 
 inlineToTextile opts (Quoted SingleQuote lst) = do
   contents <- inlineListToTextile opts lst
-  return $ "'" ++ contents ++ "'"
+  return $ "'" <> contents <> "'"
 
 inlineToTextile opts (Quoted DoubleQuote lst) = do
   contents <- inlineListToTextile opts lst
-  return $ "\"" ++ contents ++ "\""
+  return $ "\"" <> contents <> "\""
 
 inlineToTextile opts (Cite _  lst) = inlineListToTextile opts lst
 
 inlineToTextile _ (Code _ str) =
-  return $ if '@' `elem` str
-           then "<tt>" ++ escapeStringForXML str ++ "</tt>"
-           else "@" ++ str ++ "@"
+  return $ if T.any (== '@') str
+           then "<tt>" <> escapeStringForXML str <> "</tt>"
+           else "@" <> str <> "@"
 
-inlineToTextile _ (Str str) = return $ escapeStringForTextile str
+inlineToTextile _ (Str str) = return $ escapeTextForTextile str
 
 inlineToTextile _ (Math _ str) =
-  return $ "<span class=\"math\">" ++ escapeStringForXML str ++ "</math>"
+  return $ "<span class=\"math\">" <> escapeStringForXML str <> "</span>"
 
 inlineToTextile opts il@(RawInline f str)
   | f == Format "html" || f == Format "textile" = return str
@@ -461,44 +454,44 @@
 inlineToTextile _ Space = return " "
 
 inlineToTextile opts (Link (_, cls, _) txt (src, _)) = do
-  let classes = if null cls
-                   then ""
-                   else "(" ++ unwords cls ++ ")"
   label <- case txt of
                 [Code _ s]
                  | s == src -> return "$"
                 [Str s]
                  | s == src -> return "$"
                 _           -> inlineListToTextile opts txt
-  return $ "\"" ++ classes ++ label ++ "\":" ++ src
+  let classes = if null cls || cls == ["uri"] && label == "$"
+                   then ""
+                   else "(" <> T.unwords cls <> ")"
+  return $ "\"" <> classes <> label <> "\":" <> src
 
 inlineToTextile opts (Image attr@(_, cls, _) alt (source, tit)) = do
   alt' <- inlineListToTextile opts alt
-  let txt = if null tit
-               then if null alt'
+  let txt = if T.null tit
+               then if T.null alt'
                        then ""
-                       else "(" ++ alt' ++ ")"
-               else "(" ++ tit ++ ")"
+                       else "(" <> alt' <> ")"
+               else "(" <> tit <> ")"
       classes = if null cls
                    then ""
-                   else "(" ++ unwords cls ++ ")"
-      showDim dir = let toCss str = Just $ show dir ++ ":" ++ str ++ ";"
+                   else "(" <> T.unwords cls <> ")"
+      showDim dir = let toCss str = Just $ tshow dir <> ":" <> str <> ";"
                     in case dimension dir attr of
-                         Just (Percent a) -> toCss $ show (Percent a)
-                         Just dim         -> toCss $ showInPixel opts dim ++ "px"
+                         Just (Percent a) -> toCss $ tshow (Percent a)
+                         Just dim         -> toCss $ showInPixel opts dim <> "px"
                          Nothing          -> Nothing
       styles = case (showDim Width, showDim Height) of
-                 (Just w, Just h)   -> "{" ++ w ++ h ++ "}"
-                 (Just w, Nothing)  -> "{" ++ w ++ "height:auto;}"
-                 (Nothing, Just h)  -> "{" ++ "width:auto;" ++ h ++ "}"
+                 (Just w, Just h)   -> "{" <> w <> h <> "}"
+                 (Just w, Nothing)  -> "{" <> w <> "height:auto;}"
+                 (Nothing, Just h)  -> "{" <> "width:auto;" <> h <> "}"
                  (Nothing, Nothing) -> ""
-  return $ "!" ++ classes ++ styles ++ source ++ txt ++ "!"
+  return $ "!" <> classes <> styles <> source <> txt <> "!"
 
 inlineToTextile opts (Note contents) = do
   curNotes <- gets stNotes
   let newnum = length curNotes + 1
   contents' <- blockListToTextile opts contents
-  let thisnote = "fn" ++ show newnum ++ ". " ++ contents' ++ "\n"
+  let thisnote = "fn" <> tshow newnum <> ". " <> contents' <> "\n"
   modify $ \s -> s { stNotes = thisnote : curNotes }
-  return $ "[" ++ show newnum ++ "]"
+  return $ "[" <> tshow newnum <> "]"
   -- note - may not work for notes with multiple blocks
diff --git a/src/Text/Pandoc/Writers/Typst.hs b/src/Text/Pandoc/Writers/Typst.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Writers/Typst.hs
@@ -0,0 +1,730 @@
+{-# LANGUAGE OverloadedStrings   #-}
+{-# LANGUAGE BangPatterns        #-}
+{-# LANGUAGE LambdaCase          #-}
+{-# LANGUAGE ScopedTypeVariables #-}
+{- |
+   Module      : Text.Pandoc.Writers.Typst
+   Copyright   : Copyright (C) 2023 John MacFarlane
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : John MacFarlane <jgm@berkeley.edu>
+   Stability   : alpha
+   Portability : portable
+
+Conversion of 'Pandoc' format into Typst markup
+(<https://typst.app>).
+-}
+module Text.Pandoc.Writers.Typst (
+    writeTypst
+  ) where
+import Text.Pandoc.Definition
+import Text.Pandoc.Class ( PandocMonad, report, runPure, fetchItem )
+import Text.Pandoc.ImageSize ( dimension, Dimension(Pixel), Direction(..),
+                               showInInch )
+import Text.Pandoc.Options ( WriterOptions(..), WrapOption(..), isEnabled,
+                             CaptionPosition(..), HighlightMethod(..) )
+import Data.Text (Text)
+import Data.List (intercalate, intersperse)
+import Data.Bifunctor (first, second)
+import Network.URI (unEscapeString)
+import qualified Data.Text as T
+import Control.Monad (unless)
+import Control.Monad.State ( StateT, evalStateT, gets, modify )
+import Text.Pandoc.Writers.Shared ( lookupMetaInlines, lookupMetaString,
+                                    metaToContext, defField, resetField,
+                                    setupTranslations )
+import Text.Pandoc.Shared (isTightList, orderedListMarkers, tshow, stringify)
+import Text.Pandoc.Highlighting (highlight, formatTypstBlock, formatTypstInline,
+                                 styleToTypst)
+import Text.Pandoc.Translations (Term(Abstract), translateTerm)
+import Text.Pandoc.Error (PandocError(PandocSomeError))
+import Text.Pandoc.Walk (query)
+import Text.Pandoc.Writers.Math (convertMath)
+import qualified Text.TeXMath as TM
+import Text.DocLayout
+import Text.DocTemplates (renderTemplate)
+import Text.Pandoc.Extensions (Extension(..))
+import Text.Pandoc.Logging (LogMessage(..))
+import qualified Text.Pandoc.UTF8 as UTF8
+import Text.Collate.Lang (Lang(..), parseLang)
+import Text.Printf (printf)
+import Data.Char (isDigit)
+import Data.Maybe (fromMaybe)
+import Unicode.Char (isXIDContinue)
+import qualified Data.ByteString as B
+
+-- | Convert Pandoc to Typst.
+writeTypst :: PandocMonad m => WriterOptions -> Pandoc -> m Text
+writeTypst options document =
+  evalStateT (pandocToTypst options document)
+    WriterState{ stOptions = options,
+                 stEscapeContext = NormalContext,
+                 stHighlighting = False }
+
+data EscapeContext = NormalContext | TermContext
+  deriving (Show, Eq)
+
+data WriterState =
+  WriterState {
+    stOptions :: WriterOptions,
+    stEscapeContext :: EscapeContext,
+    stHighlighting :: Bool
+    }
+
+type TW m = StateT WriterState m
+
+pandocToTypst :: PandocMonad m
+              => WriterOptions -> Pandoc -> TW m Text
+pandocToTypst options (Pandoc meta blocks) = do
+  let colwidth = if writerWrapText options == WrapAuto
+                    then Just $ writerColumns options
+                    else Nothing
+  setupTranslations meta
+  metadata <- metaToContext options
+              blocksToTypst
+              (fmap chomp . inlinesToTypst)
+              meta
+  main <- blocksToTypst blocks
+  abstractTitle <- translateTerm Abstract
+  let toPosition :: CaptionPosition -> Text
+      toPosition CaptionAbove = "top"
+      toPosition CaptionBelow = "bottom"
+  let nociteIds = query (\case
+                           Cite cs _ -> map citationId cs
+                           _         -> [])
+                  $ lookupMetaInlines "nocite" meta
+  hasHighlighting <- gets stHighlighting
+
+  let context = defField "body" main
+              $ defField "toc" (writerTableOfContents options)
+              $ (if isEnabled Ext_citations options
+                    then defField "citations" True
+                       . defField "nocite-ids" (filter (/= "*") nociteIds)
+                       . defField "full-bibliography" ("*" `elem` nociteIds)
+                    else id)
+              $ (case lookupMetaString "lang" meta of
+                    "" -> id
+                    lang ->
+                      case parseLang lang of
+                        Left _ -> id
+                        Right l ->
+                          resetField "lang" (langLanguage l) .
+                          maybe id (resetField "region") (langRegion l))
+              $ defField "csl" (lookupMetaString "citation-style" meta) -- #10661
+              $ defField "smart" (isEnabled Ext_smart options)
+              $ defField "abstract-title" abstractTitle
+              $ defField "toc-depth" (tshow $ writerTOCDepth options)
+              $ (if hasHighlighting
+                    then case writerHighlightMethod options of
+                           Skylighting sty ->
+                              defField "highlighting-definitions"
+                                (T.stripEnd $ styleToTypst sty)
+                           _ -> id
+                    else id)
+              $ defField "figure-caption-position"
+                   (toPosition $ writerFigureCaptionPosition options)
+              $ defField "table-caption-position"
+                   (toPosition $ writerTableCaptionPosition options)
+              $ defField "page-numbering" ("1" :: Text)
+              $ (if writerNumberSections options
+                    then defField "section-numbering" ("1.1.1.1.1" :: Text)
+                    else id)
+              metadata
+  return $ render colwidth $
+    case writerTemplate options of
+       Nothing  -> main
+       Just tpl -> renderTemplate tpl context
+
+pickTypstAttrs :: [(Text, Text)] -> ([(Text, Text)],[(Text, Text)])
+pickTypstAttrs = foldr go ([],[])
+  where
+    go (k,v) =
+      case T.splitOn ":" k of
+        ["typst", "text", x] -> second ((x,v):)
+        ["typst", x] -> first ((x,v):)
+        _ -> id
+
+formatTypstProp :: (Text, Text) -> Text
+formatTypstProp (k,v) = k <> ": " <> v
+
+toTypstPropsListSep :: [(Text, Text)] -> Doc Text
+toTypstPropsListSep = hsep . intersperse "," . map (literal . formatTypstProp)
+
+toTypstPropsListTerm :: [(Text, Text)] -> Doc Text
+toTypstPropsListTerm [] = ""
+toTypstPropsListTerm typstAttrs = toTypstPropsListSep typstAttrs <> ","
+
+toTypstPropsListParens :: [(Text, Text)] -> Doc Text
+toTypstPropsListParens [] = ""
+toTypstPropsListParens typstAttrs = parens $ toTypstPropsListSep typstAttrs
+
+toTypstTextElement :: [(Text, Text)] -> Doc Text -> Doc Text
+toTypstTextElement [] content = content
+toTypstTextElement typstTextAttrs content = "#text" <> toTypstPropsListParens typstTextAttrs <> brackets content
+
+toTypstSetText :: [(Text, Text)] -> Doc Text
+toTypstSetText [] = ""
+toTypstSetText typstTextAttrs = "set text" <> parens (toTypstPropsListSep typstTextAttrs) <> ";"
+
+toTypstPoundSetText :: [(Text, Text)] -> Doc Text
+toTypstPoundSetText [] = mempty
+toTypstPoundSetText typstTextAttrs = "#" <> toTypstSetText typstTextAttrs
+
+toTypstBracesSetText :: [(Text, Text)] -> Doc Text -> Doc Text
+toTypstBracesSetText [] x = "#" <> x
+toTypstBracesSetText typstTextAttrs x = "#" <> braces (toTypstSetText typstTextAttrs <> x)
+
+blocksToTypst :: PandocMonad m => [Block] -> TW m (Doc Text)
+blocksToTypst blocks = vcat <$> mapM blockToTypst blocks
+
+blockToTypst :: PandocMonad m => Block -> TW m (Doc Text)
+blockToTypst block =
+  case block of
+    Plain inlines -> inlinesToTypst inlines
+    Para inlines -> do
+      ($$ blankline) <$> inlinesToTypst inlines
+    Header level (ident,cls,_) inlines -> do
+      contents <- inlinesToTypst inlines
+      let lab = toLabel FreestandingLabel ident
+      let headingAttrs =
+            ["outlined: false" | "unlisted" `elem` cls] ++
+            ["numbering: none" | "unnumbered" `elem` cls]
+      return $
+        if null headingAttrs
+           then nowrap
+                 (literal (T.replicate level "=") <> space <> contents) <>
+                 cr <> lab
+           else literal "#heading" <>
+                  parens (literal (T.intercalate ", "
+                              ("level: " <> tshow level : headingAttrs))) <>
+                  brackets contents <> cr <> lab
+    RawBlock fmt str ->
+      case fmt of
+        Format "typst" -> return $ literal str
+        _ -> return mempty
+    CodeBlock (ident,cls,kvs) code -> do
+      let go :: Char -> (Int, Int) -> (Int, Int)
+          go '`' (longest, current) =
+            let !new = current + 1 in (max longest new, new)
+          go _ (longest, _) = (longest, 0)
+      let (longestBacktickSequence, _) = T.foldr go (0,0) code
+      let fence = literal $ T.replicate (max 3 (longestBacktickSequence + 1)) "`"
+      let lang = case cls of
+                   (cl:_) -> literal cl
+                   _ -> mempty
+      opts <-  gets stOptions
+      case writerHighlightMethod opts of
+        Skylighting _ ->
+          case highlight (writerSyntaxMap opts) formatTypstBlock
+                (ident,cls ++ ["default"],kvs) code of
+            Left msg -> do
+              unless (T.null msg) $ report $ CouldNotHighlight msg
+              return $ fence <> lang <> cr <> literal code <> cr <> fence <> blankline
+            Right h -> do
+              modify (\s -> s{ stHighlighting = True })
+              return (literal h)
+        NoHighlighting -> return $ fence <> cr <> literal code <> cr <> fence <> blankline
+        _ -> return $ fence <> lang <> cr <> literal code <> cr <> fence <> blankline
+    LineBlock lns -> do
+      contents <- inlinesToTypst (intercalate [LineBreak] lns)
+      return $ contents <> blankline
+    BlockQuote blocks -> do
+      contents <- blocksToTypst blocks
+      return $ "#quote(block: true)[" $$ chomp contents $$ "]" $$ blankline
+    HorizontalRule ->
+      return $ blankline <> "#horizontalrule" <> blankline
+    OrderedList attribs items -> do
+      let addBlock = case attribs of
+                       (1, DefaultStyle, DefaultDelim) -> id
+                       (1, Decimal, Period) -> id
+                       (start, sty, delim) -> \x ->
+                              "#block[" $$
+                               ("#set enum" <>
+                                  parens (
+                                    "numbering: " <>
+                                    doubleQuoted
+                                     (case orderedListMarkers (1, sty, delim) of
+                                          (m:_) -> m
+                                          [] -> "1.") <>
+                                    ", start: " <>
+                                      text (show start) )) $$
+                               x $$
+                               "]"
+      items' <- mapM (fmap chomp . listItemToTypst 2 ("+")) items
+      return $ addBlock
+               (if isTightList items
+                   then vcat items'
+                   else vsep items')
+              $$ blankline
+    BulletList items -> do
+      items' <- mapM (fmap chomp . listItemToTypst 2 "-") items
+      return $ (if isTightList items
+                   then vcat items'
+                   else vsep items') $$ blankline
+    DefinitionList items ->
+      ($$ blankline) . vsep <$> mapM defListItemToTypst items
+    Table (ident,tabclasses,tabkvs) (Caption _ caption) colspecs thead tbodies tfoot -> do
+      let lab = toLabel FreestandingLabel ident
+      capt' <- if null caption
+                  then return mempty
+                  else do
+                    captcontents <- blocksToTypst caption
+                    return $ ", caption: " <> brackets captcontents
+      let typstFigureKind = literal (", kind: " <> fromMaybe "table" (lookup "typst:figure:kind" tabkvs))
+      let numcols = length colspecs
+      let (aligns, widths) = unzip colspecs
+      let commaSep = hcat . intersperse ", "
+      let toPercentage (ColWidth w) =
+            literal $ (T.dropWhileEnd (== '.') . T.dropWhileEnd (== '0'))
+                         (T.pack (printf "%0.2f" (w * 100))) <> "%"
+          toPercentage ColWidthDefault = literal "auto"
+      let columns = if all (== ColWidthDefault) widths
+                       then literal $ tshow numcols
+                       else parens (commaSep (map toPercentage widths))
+      let formatalign AlignLeft = "left,"
+          formatalign AlignRight = "right,"
+          formatalign AlignCenter = "center,"
+          formatalign AlignDefault = "auto,"
+      let alignarray = parens $ mconcat $ map formatalign aligns
+
+      let fromCell (Cell (_,_,kvs) alignment rowspan colspan bs) = do
+            let (typstAttrs, typstTextAttrs) = pickTypstAttrs kvs
+            let valign =
+                  (case lookup "align" typstAttrs of
+                    Just va -> [va]
+                    _ -> [])
+            let typstAttrs2 = filter ((/="align") . fst) typstAttrs
+            let halign =
+                  (case alignment of
+                    AlignDefault -> []
+                    AlignLeft -> [ "left" ]
+                    AlignRight -> [ "right" ]
+                    AlignCenter -> [ "center" ])
+            let cellaligns = valign ++ halign
+            let cellattrs =
+                  (case cellaligns of
+                    [] -> []
+                    _ -> [ "align: " <> T.intercalate " + " cellaligns ]) ++
+                  (case rowspan of
+                     RowSpan 1 -> []
+                     RowSpan n -> [ "rowspan: " <> tshow n ]) ++
+                  (case colspan of
+                     ColSpan 1 -> []
+                     ColSpan n -> [ "colspan: " <> tshow n ]) ++
+                  map formatTypstProp typstAttrs2
+            cellContents <- blocksToTypst bs
+            let contents2 = brackets (toTypstPoundSetText typstTextAttrs $$ cellContents)
+            pure $ if null cellattrs
+                      then contents2
+                      else "table.cell" <>
+                            parens
+                             (literal (T.intercalate ", " cellattrs)) <>
+                            contents2
+      let fromRow (Row _ cs) =
+            (<> ",") . commaSep <$> mapM fromCell cs
+      let fromHead (TableHead _attr headRows) =
+            if null headRows
+               then pure mempty
+               else (($$ "table.hline(),") .
+                      (<> ",") . ("table.header" <>) . parens . nest 2 . vcat)
+                      <$> mapM fromRow headRows
+      let fromFoot (TableFoot _attr footRows) =
+            if null footRows
+               then pure mempty
+               else (("table.hline()," $$) .
+                      (<> ",") . ("table.footer" <>) . parens . nest 2 . vcat)
+                      <$> mapM fromRow footRows
+      let fromTableBody (TableBody _attr _rowHeadCols headRows bodyRows) = do
+            hrows <- mapM fromRow headRows
+            brows <- mapM fromRow bodyRows
+            pure $ vcat (hrows ++ ["table.hline()," | not (null hrows)] ++ brows)
+      let (typstAttrs, typstTextAttrs) = pickTypstAttrs tabkvs
+      header <- fromHead thead
+      footer <- fromFoot tfoot
+      body <- vcat <$> mapM fromTableBody tbodies
+      let table = "table("
+            $$ nest 2
+                (  "columns: " <> columns <> ","
+                $$ "align: " <> alignarray <> ","
+                $$ toTypstPropsListTerm typstAttrs
+                $$ header
+                $$ body
+                $$ footer
+            )
+            $$ ")"
+      return $ if "typst:no-figure" `elem` tabclasses
+        then toTypstBracesSetText typstTextAttrs table
+        else "#figure("
+            $$
+            nest 2
+            ("align(center)[" <> toTypstPoundSetText typstTextAttrs <> "#" <> table <> "]"
+              $$ capt'
+              $$ typstFigureKind
+              $$ ")")
+            $$ lab
+          $$ blankline
+    Figure (ident,_,_) (Caption _mbshort capt) blocks -> do
+      caption <- blocksToTypst capt
+      opts <-  gets stOptions
+      let toImage (Image attr inlines (src, _)) =
+            Just $ mkImage opts False src attr (getAlt attr inlines)
+          toImage _ = Nothing
+      contents <- case blocks of
+                     -- don't need #box around block-level image
+                     [Para [img]] | Just i <- toImage img -> pure i
+                     [Plain [img]] | Just i <- toImage img -> pure i
+                     _ -> brackets <$> blocksToTypst blocks
+      let lab = toLabel FreestandingLabel ident
+      return $ "#figure(" <> nest 2 ((contents <> ",")
+                                     $$
+                                     ("caption: [" $$ nest 2 caption $$ "]")
+                                    )
+                          $$ ")" $$ lab $$ blankline
+    Div (ident,_,_) (Header lev ("",cls,kvs) ils:rest) ->
+      blocksToTypst (Header lev (ident,cls,kvs) ils:rest)
+    Div (ident,_,kvs) blocks -> do
+      let lab = toLabel FreestandingLabel ident
+      let (typstAttrs,typstTextAttrs) = pickTypstAttrs kvs
+      -- Handle lang attribute for Div elements
+      let langAttrs = case lookup "lang" kvs of
+                        Nothing -> []
+                        Just lang -> case parseLang lang of
+                                       Left _ -> []
+                                       Right l -> [("lang",
+                                                    tshow (langLanguage l))]
+      let allTypstTextAttrs = typstTextAttrs ++ langAttrs
+      contents <- blocksToTypst blocks
+      return $ "#block" <> toTypstPropsListParens typstAttrs <> "["
+        $$ toTypstPoundSetText allTypstTextAttrs
+        $$ contents
+        $$ ("]" <+> lab)
+
+defListItemToTypst :: PandocMonad m => ([Inline], [[Block]]) -> TW m (Doc Text)
+defListItemToTypst (term, defns) = do
+  modify $ \st -> st{ stEscapeContext = TermContext }
+  term' <- inlinesToTypst term
+  modify $ \st -> st{ stEscapeContext = NormalContext }
+  defns' <- mapM blocksToTypst defns
+  return $ nowrap ("/ " <> term' <> ": " <> "#block[") $$
+            chomp (vsep defns') $$ "]"
+
+listItemToTypst :: PandocMonad m => Int -> Doc Text -> [Block] -> TW m (Doc Text)
+listItemToTypst ind marker blocks = do
+  contents <- blocksToTypst blocks
+  return $ hang ind (marker <> space) contents
+
+inlinesToTypst :: PandocMonad m => [Inline] -> TW m (Doc Text)
+inlinesToTypst (i@(Span (ident,_,_) _):is) | not (T.null ident) =
+  -- insert a zero-width space U+200B before the label
+  -- because a typst label refers to preceding element (see #11568)
+  ("\x200B" <>) . hcat <$> mapM inlineToTypst (escapeParens (i:is))
+inlinesToTypst ils = hcat <$> mapM inlineToTypst (escapeParens ils)
+
+-- Add an escape before a parenthesis right after a non-space element.
+-- Otherwise we risk `#emph[test](3)` which will error. See #11210.
+escapeParens :: [Inline] -> [Inline]
+escapeParens [] = []
+escapeParens (s : x : xs)
+  | isSpacey s
+    = s : x : escapeParens xs
+escapeParens (Str t : xs)
+  | Just ('(',_) <- T.uncons t
+    = RawInline (Format "typst") "\\" : Str t : escapeParens xs
+escapeParens (x : xs) = x : escapeParens xs
+
+isSpacey :: Inline -> Bool
+isSpacey Space = True
+isSpacey SoftBreak = True
+isSpacey LineBreak = True
+isSpacey _ = False
+
+inlineToTypst :: PandocMonad m => Inline -> TW m (Doc Text)
+inlineToTypst inline =
+  case inline of
+    Str txt -> do
+      opts <-  gets stOptions
+      context <- gets stEscapeContext
+      return $ escapeTypst (isEnabled Ext_smart opts) context txt
+    Space -> return space
+    SoftBreak -> do
+      wrapText <- gets $ writerWrapText . stOptions
+      case wrapText of
+        WrapPreserve -> return cr
+        WrapAuto     -> return space
+        WrapNone     -> return space
+    LineBreak -> return (space <> "\\" <> space)
+    Math mathType str -> do
+      res <- convertMath TM.writeTypst mathType str
+      case res of
+          Left il -> inlineToTypst il
+          Right r ->
+            (case extractLabel str of -- #10805
+              Nothing -> id
+              Just lab -> (<> (toLabel FreestandingLabel lab))) <$>
+             case mathType of
+               InlineMath -> return $ "$" <> literal r <> "$"
+               DisplayMath -> return $ "$ " <> literal r <> " $"
+    Code (ident,cls,kvs) code -> do
+      opts <- gets stOptions
+      let defaultHighlightedCode =
+            case cls of
+              (lang:_) | writerHighlightMethod opts /= NoHighlighting
+                       -> "#raw(lang:" <> doubleQuoted lang <>
+                              ", " <> doubleQuoted code <> ")"
+              _ | T.any (=='`') code -> "#raw(" <> doubleQuoted code <> ")"
+                | otherwise -> "`" <> literal code <> "`"
+      case writerHighlightMethod opts of
+        Skylighting _ ->
+          case highlight (writerSyntaxMap opts) formatTypstInline
+                (ident,cls ++ ["default"],kvs) code of
+            Left msg -> do
+              unless (T.null msg) $ report $ CouldNotHighlight msg
+              return defaultHighlightedCode
+            Right h -> do
+              modify (\s -> s{ stHighlighting = True })
+              return (literal h)
+        _ -> return defaultHighlightedCode
+    RawInline fmt str ->
+      case fmt of
+        Format "typst" -> return $ literal str
+        _ -> return mempty
+    Strikeout inlines -> textstyle "#strike" inlines
+    Emph inlines -> textstyle "#emph" inlines
+    Underline inlines -> textstyle "#underline" inlines
+    Strong inlines -> textstyle "#strong" inlines
+    Superscript inlines -> textstyle "#super" inlines
+    Subscript inlines -> textstyle "#sub" inlines
+    SmallCaps inlines -> textstyle "#smallcaps" inlines
+    Span (ident,cls,kvs) inlines -> do
+      let lab = toLabel FreestandingLabel ident
+      let (_, typstTextAttrs) = pickTypstAttrs kvs
+      contents <- inlinesToTypst inlines
+      let addHl x = "#highlight" <> brackets x
+      return $ (if "mark" `elem` cls
+                   then addHl
+                   else id)
+               (toTypstTextElement typstTextAttrs contents) <> lab
+    Quoted quoteType inlines -> do
+      opts <- gets stOptions
+      let smart = isEnabled Ext_smart opts
+      contents <- inlinesToTypst inlines
+      return $
+        case quoteType of
+           DoubleQuote
+             | smart -> "\"" <> contents <> "\""
+             | otherwise -> "“" <> contents <> "”"
+           SingleQuote
+             | smart -> "'" <> contents <> "'"
+             | otherwise -> "‘" <> contents <> "’"
+    Cite citations inlines -> do
+      opts <-  gets stOptions
+      if isEnabled Ext_citations opts
+         -- Note: this loses prefix
+         then mconcat <$> mapM toCite citations
+         else inlinesToTypst inlines
+    Link (_,_,kvs) inlines (src,_tit) -> do
+      case lookup "reference-type" kvs of
+        Just "ref"
+          | Just ('#', ident) <- T.uncons src
+          -> if T.all isIdentChar ident
+                then pure $ literal $ "@" <> ident
+                else pure $ "#ref" <> parens (toLabel ArgumentLabel ident)
+        _ -> do
+          contents <- inlinesToTypst inlines
+          let dest = case T.uncons src of
+                       Just ('#', ident) -> toLabel ArgumentLabel ident
+                       _ -> doubleQuoted src
+          pure $ "#link" <> parens dest <>
+                    (if inlines == [Str src]
+                          then mempty
+                          else nowrap $ brackets contents)
+    Image attr inlines (src,_tit) -> do
+      opts <-  gets stOptions
+      pure $ mkImage opts True src attr (getAlt attr inlines)
+    Note blocks -> do
+      contents <- blocksToTypst blocks
+      return $ "#footnote" <> brackets (chomp contents)
+
+-- see #9104; need box or image is treated as block-level
+mkImage :: WriterOptions -> Bool -> Text -> Attr -> Maybe Text -> Doc Text
+mkImage opts useBox src attr mbAlt
+  | useBox = "#box" <> parens coreImage
+  | otherwise = coreImage
+ where
+  src' = T.pack $ unEscapeString $ T.unpack src -- #9389
+  showDim (Pixel a) = literal (showInInch opts (Pixel a) <> "in")
+  showDim dim = text (show dim)
+  dimAttrs =
+     (case dimension Height attr of
+        Nothing -> mempty
+        Just dim -> ", height: " <> showDim dim) <>
+     (case dimension Width attr of
+        Nothing -> mempty
+        Just dim -> ", width: " <> showDim dim)
+  altAttr = case mbAlt of
+              Just alt -> ", alt: " <> doubleQuoted alt
+              Nothing -> mempty
+  isData = "data:" `T.isPrefixOf` src'
+  eitherImageData = if isData
+                       then runPure (fetchItem src)
+                       else Left $ PandocSomeError "not a data URI"
+  toArray = parens . hcat . intersperse "," . map (literal . tshow) . B.unpack
+  attrs = dimAttrs <> altAttr
+  coreImage = "image" <> parens
+    (case eitherImageData of
+      Right (contents, Just "image/svg+xml")
+        -> "bytes" <> parens (doubleQuoted (UTF8.toText contents)) <> attrs
+      Right (bytes, _mime) -> "bytes" <> parens (toArray bytes) <> attrs
+      Left _ -> doubleQuoted src' <> attrs)
+
+-- | Extract alt text from image attributes and inlines.
+-- Use explicit alt attribute if present; otherwise use inlines.
+-- Empty alt="" means decorative image (no alt text).
+getAlt :: Attr -> [Inline] -> Maybe Text
+getAlt (_, _, kvs) imgInlines =
+  case lookup "alt" kvs of
+    Just "" -> Nothing  -- decorative
+    Just alt -> Just alt
+    Nothing -> case imgInlines of
+                 [] -> Nothing
+                 _ -> Just (stringify imgInlines)
+
+textstyle :: PandocMonad m => Doc Text -> [Inline] -> TW m (Doc Text)
+textstyle s inlines = do
+  (s <>) . brackets . fixInitialAfterBreakEscape
+    <$> inlinesToTypst inlines
+
+fixInitialAfterBreakEscape :: Doc Text -> Doc Text
+fixInitialAfterBreakEscape (Concat x y) =
+  Concat (fixInitialAfterBreakEscape x) y
+-- make an initial AfterBreak escape unconditional (it will be rendered
+-- in a block [..] and there won't be an actual break to trigger it, but
+-- typst still needs the escape)
+fixInitialAfterBreakEscape (AfterBreak "\\") = Text 1 "\\"
+fixInitialAfterBreakEscape x = x
+
+isOrderedListMarker :: Text -> Bool
+isOrderedListMarker t = not (T.null ds) && rest == "."
+  where (ds, rest) = T.span isDigit t
+
+escapeTypst :: Bool -> EscapeContext -> Text -> Doc Text
+escapeTypst smart context t =
+  (case T.uncons t of
+    Just (c, rest)
+      | c == ';' -> char '\\' -- see #9252
+      | c == '.'
+      , not (T.null rest) -> char '\\' -- see #11511
+      | needsEscapeAtLineStart c || isOrderedListMarker t
+        -> afterBreak "\\"
+    _ -> mempty) <>
+   literal (snd $ T.foldl' go ('\n', mempty) t)
+  where
+    go (lastc, t') c
+      | needsEscape c = (c, t' <> escapeChar c)
+      | c == '-', lastc == '-', smart = (c, t' <> T.pack ['\\',c])
+      | c == '/', lastc == '/' = (c, t' <> T.pack ['\\',c])
+      | otherwise = (c, T.snoc t' c)
+    escapeChar c
+      | c == '\160' = "~"
+      | c == '\8216', smart = "'" -- left quote
+      | c == '\8217', smart = "'" -- apostrophe
+      | c == '\8220', smart = "\"" -- left double quote
+      | c == '\8221', smart = "\"" -- right double quote
+      | c == '\8212', smart = "---" -- em dash
+      | c == '\8211', smart = "--" -- en dash
+      | needsEscape c = "\\" <> T.singleton c
+      | otherwise = T.singleton c
+    needsEscape '\160' = True
+    needsEscape '\8216' = smart
+    needsEscape '\8217' = smart
+    needsEscape '\8220' = smart
+    needsEscape '\8221' = smart
+    needsEscape '\8212' = smart
+    needsEscape '\8211' = smart
+    needsEscape '\'' = smart
+    needsEscape '"' = smart
+    needsEscape '[' = True
+    needsEscape ']' = True
+    needsEscape '#' = True
+    needsEscape '<' = True
+    needsEscape '>' = True
+    needsEscape '@' = True
+    needsEscape '$' = True
+    needsEscape '\\' = True
+    needsEscape '`' = True
+    needsEscape '_' = True
+    needsEscape '*' = True
+    needsEscape '~' = True
+    needsEscape ':' = context == TermContext
+    needsEscape _ = False
+
+needsEscapeAtLineStart :: Char -> Bool
+needsEscapeAtLineStart '/' = True
+needsEscapeAtLineStart '+' = True
+needsEscapeAtLineStart '-' = True
+needsEscapeAtLineStart '=' = True
+needsEscapeAtLineStart _ = False
+
+data LabelType =
+    FreestandingLabel
+  | ArgumentLabel
+  deriving (Show, Eq)
+
+toLabel :: LabelType -> Text -> Doc Text
+toLabel labelType ident
+  | T.null ident = mempty
+  | T.all isIdentChar ident'
+    = "<" <> literal ident' <> ">"
+  | otherwise
+     = case labelType of
+          FreestandingLabel -> "#label" <> parens (doubleQuoted ident')
+          ArgumentLabel -> "label" <> parens (doubleQuoted ident')
+ where
+   ident' = T.pack $ unEscapeString $ T.unpack ident
+
+isIdentChar :: Char -> Bool
+isIdentChar c = isXIDContinue c || c == '_' || c == '-' || c == '.' || c == ':'
+
+toCite :: PandocMonad m => Citation -> TW m (Doc Text)
+toCite cite = do
+  let ident' = T.pack $ unEscapeString $ T.unpack $ citationId cite
+  -- typst inserts comma and we get a doubled one if supplement contains it:
+  let eatComma (Str "," : Space : xs) = xs
+      eatComma xs = xs
+  if citationMode cite == NormalCitation && T.all isIdentChar ident'
+     then do
+       suppl <- case citationSuffix cite of
+                  [] -> pure mempty
+                  suff -> brackets <$> inlinesToTypst (eatComma suff)
+       pure $ "@" <> literal ident' <> suppl
+     else do
+       let label = if T.all isIdentChar ident'
+                      then "<" <> literal ident' <> ">"
+                      else "label" <> parens (doubleQuoted ident')
+       let form = case citationMode cite of
+                     NormalCitation -> mempty
+                     SuppressAuthor -> ", form: \"year\""
+                     AuthorInText -> ", form: \"prose\""
+       suppl <- case citationSuffix cite of
+                  [] -> pure mempty
+                  suff -> (", supplement: " <>) . brackets
+                             <$> inlinesToTypst (eatComma suff)
+       pure $ (if citationMode cite == SuppressAuthor  -- see #11044
+                  then parens
+                  else id)
+            $ "#cite" <> parens (label <> form <> suppl)
+
+doubleQuoted :: Text -> Doc Text
+doubleQuoted = doubleQuotes . literal . escape
+ where
+  escape = T.concatMap escapeChar
+  escapeChar '\\' = "\\\\"
+  escapeChar '"' = "\\\""
+  escapeChar c = T.singleton c
+
+extractLabel :: Text -> Maybe Text
+extractLabel = go . T.unpack
+ where
+   go [] = Nothing
+   go ('\\':'l':'a':'b':'e':'l':'{':xs) = Just (T.pack (takeWhile (/='}') xs))
+   go (_:xs) = go xs
diff --git a/src/Text/Pandoc/Writers/Vimdoc.hs b/src/Text/Pandoc/Writers/Vimdoc.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Writers/Vimdoc.hs
@@ -0,0 +1,615 @@
+{-# LANGUAGE LambdaCase #-}
+{-# LANGUAGE MultiWayIf #-}
+{-# LANGUAGE OverloadedStrings #-}
+{-# LANGUAGE Strict #-}
+
+module Text.Pandoc.Writers.Vimdoc (writeVimdoc) where
+
+import Control.Applicative (optional, (<|>))
+import Control.Monad (forM)
+import Control.Monad.Reader (MonadReader (..), ReaderT (..), asks)
+import Control.Monad.State (MonadState (..), StateT, evalStateT, gets, modify)
+import Data.Default (Default (..))
+import Data.List (intercalate, intersperse, transpose)
+import Data.List.NonEmpty (NonEmpty (..), nonEmpty)
+import Data.Maybe (fromMaybe)
+import Data.Text (Text)
+import qualified Data.Text as T
+import Text.DocLayout hiding (char, link, text)
+import Text.Pandoc.Class.PandocMonad ( report, PandocMonad )
+import Text.Pandoc.Definition
+import Text.Pandoc.Error (PandocError)
+import Text.Pandoc.Logging (LogMessage (..))
+import Text.Pandoc.Options (WrapOption (..), WriterOptions (..))
+import Text.Pandoc.Parsing.General (many1Till, many1TillChar, readWith)
+import Text.Pandoc.Shared (capitalize, onlySimpleTableCells, orderedListMarkers, isTightList, makeSections, removeFormatting, tshow)
+import Text.Pandoc.Templates (renderTemplate)
+import Text.Pandoc.URI (escapeURI, isURI)
+import Text.Pandoc.Writers.Shared (defField, metaToContext, toLegacyTable)
+import Text.Parsec (anyChar, char, eof, string, try)
+import Text.Read (readMaybe)
+import Text.Pandoc.Chunks (toTOCTree, SecInfo (..))
+import Data.Tree (Tree(..))
+import Data.Functor ((<&>))
+import Data.Sequence (Seq, (|>), (<|))
+import qualified Data.Sequence as Seq
+import Data.Foldable (toList)
+
+data WriterState = WriterState
+  { indentLevel :: Int -- How much to indent the block. Inlines shouldn't
+                       -- be concerned with indent level (I guess?)
+  , shiftWidth :: Int -- spaces per indentation level
+  , writerOptions :: WriterOptions
+  , vimdocPrefix :: Maybe Text
+  }
+
+instance Default WriterState where
+  def =
+    WriterState
+      { indentLevel = 0
+      , shiftWidth = 4
+      , writerOptions = def
+      , vimdocPrefix = Nothing
+      }
+
+indent :: (Monad m) => Int -> (VW m a) -> (VW m a)
+indent n = local (\s -> s{indentLevel = indentLevel s + n})
+
+type VW m = StateT (Seq (Doc Text)) (ReaderT WriterState m)
+
+runRR :: (Monad m) => Seq (Doc Text) -> WriterState -> VW m a -> m a
+runRR footnotes opts action = runReaderT (evalStateT action footnotes) opts
+
+docShiftWidth :: Meta -> Maybe Int
+docShiftWidth meta = case lookupMeta "shiftwidth" meta of
+  Just (MetaInlines [Str sw]) -> readMaybe (T.unpack sw)
+  Just (MetaString sw) -> readMaybe (T.unpack sw)
+  _ -> Nothing
+
+docVimdocPrefix :: Meta -> Maybe Text
+docVimdocPrefix meta = case lookupMeta "vimdoc-prefix" meta of
+  Just (MetaInlines [Str pref]) -> Just pref
+  Just (MetaString pref) -> Just pref
+  _ -> Nothing
+
+{- | Build a vim modeline
+>>> makeModeLine def
+"vim:tw=72:sw=4:ts=4:ft=help:norl:et:"
+-}
+makeModeLine :: WriterState -> Text
+makeModeLine ws =
+  T.pack . intercalate ":" $
+    [ "vim"
+    , "tw=" <> show tw
+    , "sw=" <> show sw
+    , "ts=" <> show sw
+    , "ft=help"
+    , "norl" -- left-to-right text
+    , "et:" -- expandtab and finishing ":"
+    ]
+ where
+  tw = writerColumns . writerOptions $ ws
+  sw = shiftWidth ws
+
+-- | Build a single formatted TOC line
+tocEntryToLine :: (PandocMonad m) => SecInfo -> VW m Text
+tocEntryToLine secinfo = do
+  rightRef <- mkVimdocRef (secId secinfo)
+  let numberStr = case secNumber secinfo of
+        Nothing -> ""
+        Just x | '.' `T.elem` x -> x <> " "
+        Just x -> x <> ". "
+  title <- inlineListToVimdoc $ removeFormatting (secTitle secinfo)
+  let titlePlain = render Nothing (title <> " ")
+
+  -- length sub 2 because vertical bars are concealed
+  let rightRefLen = max 0 (T.length rightRef - 2)
+  let numberLen = T.length numberStr
+  let leftLen = numberLen + T.length titlePlain
+  let padForRight = 1
+  textWidth <- asks (writerColumns . writerOptions)
+  il <- asks indentLevel
+
+  -- positive when we lack space (i.e. content is too long)
+  let lack = (il + leftLen + padForRight + rightRefLen) - textWidth
+
+  -- when lacking, truncate title reserving 3+ chars for ellipsis
+  let finalTitle =
+        if lack >= 0
+          then
+            let trunc = T.dropEnd (lack + 3) titlePlain
+                stripped = T.stripEnd trunc
+                ellipsis =
+                  T.replicate (3 + T.length trunc - T.length stripped) "."
+             in stripped <> ellipsis
+          else titlePlain
+
+  -- Negative lack means we have an excess of space, so we fill it with dots
+  let dots = T.replicate (negate lack) "."
+
+  pure . T.concat $ [numberStr, finalTitle, dots, " ", rightRef]
+
+vimdocTOC :: (PandocMonad m) => WriterState -> [Block] -> VW m (Doc Text)
+vimdocTOC (WriterState{writerOptions = opts}) blocks = do
+  let (Node _ subtrees) =
+        toTOCTree $ makeSections (writerNumberSections opts) Nothing blocks
+  let tocDepth = writerTOCDepth opts
+  let isBelowTocDepth (Node sec _) = secLevel sec <= tocDepth
+
+  let makeItem :: (PandocMonad m) => Tree SecInfo -> VW m (Doc Text)
+      makeItem (Node secinfo xs) = do
+        line <- tocEntryToLine secinfo
+        -- When unnumbered, indent constantly by two,
+        -- otherwise indent by (length of marker + 1)
+        let markerLen = 1 + maybe 1 T.length (secNumber secinfo)
+        childItems <-
+          indent markerLen $
+            traverse makeItem (filter isBelowTocDepth xs)
+        pure (literal line $$ nest markerLen (vcat childItems))
+
+  items <- traverse makeItem (filter isBelowTocDepth subtrees)
+  pure $ vcat items
+
+writeVimdoc :: (PandocMonad m) => WriterOptions -> Pandoc -> m Text
+writeVimdoc opts document@(Pandoc meta _) =
+  let
+    sw = fromMaybe (shiftWidth def) $ docShiftWidth meta
+    vp = docVimdocPrefix meta
+    footnotes = Seq.empty
+    initialEnv = def{shiftWidth = sw, writerOptions = opts, vimdocPrefix = vp}
+   in
+    runRR footnotes initialEnv $ pandocToVimdoc document
+
+pandocToVimdoc :: (PandocMonad m) => Pandoc -> VW m Text
+pandocToVimdoc (Pandoc meta body) = do
+  st <- ask
+  let opts = writerOptions st
+
+  metadata <- metaToContext opts blockListToVimdoc inlineListToVimdoc meta
+  main <- do
+    body' <- blockListToVimdoc body
+    footnotes <- get
+    rule <- blockToVimdoc HorizontalRule
+    let footnotes' = if Seq.null footnotes
+          then Empty
+          else vsep (toList $ rule <| footnotes)
+    pure $ body' <> blankline <> footnotes'
+
+  title <- inlineListToVimdoc $ docTitle meta
+  authors <- traverse inlineListToVimdoc $ docAuthors meta
+  let authors' = mconcat $ intersperse ("," <> space) (fmap nowrap authors)
+  let tw = writerColumns . writerOptions $ st
+
+  let combinedTitle =
+        render (Just tw) . cblock tw $
+            (title <> space)
+              <> (if null authors' then "" else "by" <> space <> authors')
+
+  -- This is placed here because I couldn't find a way to right-align text
+  -- inside template to the width specified by a variable
+  let toc_reminder =
+        render Nothing . rblock tw $
+          ("Type |gO| to see the table of contents." :: Doc Text)
+
+  toc <- render (Just tw) <$> vimdocTOC st body
+
+  let modeline = makeModeLine st
+  let context =
+        defField "body" main
+          . defField "toc" (if writerTableOfContents opts then toc else "")
+          . defField "modeline" modeline
+          . defField "combined-title" combinedTitle
+          . defField "toc-reminder" toc_reminder
+          $ metadata
+
+  pure $
+    case writerTemplate opts of
+      Just tpl -> render (Just tw) $ renderTemplate tpl context
+      Nothing -> render (Just tw) main
+
+blockListToVimdoc :: (PandocMonad m) => [Block] -> VW m (Doc Text)
+blockListToVimdoc blocks = vcat <$> mapM blockToVimdoc blocks
+
+blockToVimdoc :: (PandocMonad m) => Block -> VW m (Doc Text)
+
+blockToVimdoc (Plain inlines) = inlineListToVimdoc inlines
+
+blockToVimdoc (Para inlines) = do
+  contents <- inlineListToVimdoc inlines
+  pure $ contents <> blankline
+
+blockToVimdoc (LineBlock inliness) = vcat <$> mapM inlineListToVimdoc inliness
+
+blockToVimdoc (CodeBlock (_, cls, _) code) = do
+  sw <- asks shiftWidth
+  let lang = case cls of
+        (lang' : _) -> lang'
+        _ -> ""
+  -- NOTE: No blankline after the codeblock because closing `<` is concealed
+  pure . vcat $
+    [ ">" <> literal lang
+    , nest sw (literal code)
+    , flush "<"
+    ]
+
+blockToVimdoc block@(RawBlock format raw) = case format of
+  "vimdoc" -> pure $ literal raw
+  _ -> "" <$ report (BlockNotRendered block)
+
+blockToVimdoc (BlockQuote blocks) = do
+  content <- blockListToVimdoc blocks
+  pure $ nest 2 content <> blankline
+
+blockToVimdoc (OrderedList listAttr items) = do
+  let itemSpacer = if isTightList items then empty else blankline
+  let itemsWithMarkers = zip (orderedListMarkers listAttr) items
+  items' <- forM itemsWithMarkers $ \(marker, blocks) -> do
+    let markerLen = T.length marker
+
+    item' <- indent (markerLen + 1) $ blockListToVimdoc blocks
+    pure $ literal marker <> space <> nest (markerLen + 1) item' <> itemSpacer
+  pure $ vcat items' <> blankline
+
+blockToVimdoc (BulletList items) = do
+  let itemSpacer = if isTightList items then empty else blankline
+  items' <- forM items $ \blocks -> do
+    let marker = "-"
+    item <- indent 2 $ blockListToVimdoc blocks
+    pure $ marker <> " " <> nest 2 item <> itemSpacer
+  pure $ vcat items' <> blankline
+
+blockToVimdoc (DefinitionList items) = do
+  sw <- asks shiftWidth
+  let sepAll = if all (isTightList . snd) items then vcat else vsep
+  items' <- forM items $ \(term, definitions) -> do
+    let sepCur = if isTightList definitions then vcat else vsep
+    labeledTerm <- mkVimdocDefinitionTerm term
+    definitions' <- indent sw $ traverse blockListToVimdoc definitions
+    pure $ labeledTerm <> cr <> nest sw (sepCur definitions')
+  pure $ sepAll items' <> blankline
+
+blockToVimdoc (Header level (ref, _, _) inlines) = do
+  tw <- asks (writerColumns . writerOptions)
+  let rule = case level of
+        1 -> T.replicate tw "="
+        2 -> T.replicate tw "-"
+        _ -> ""
+  title <- fmap (render Nothing) . inlineListToVimdoc $ case level of
+    3 -> capitalize inlines
+    _ -> inlines
+
+  label <- mkVimdocTag ref
+  -- One manual space that ensures that even if spaceLeft is 0, title and ref
+  -- don't touch each other
+  let label' = " " <> label
+  -- (+ 2) due to stars concealment
+  let spaceLeft = tw - T.length title + 2
+
+  pure $ vcat
+      [ blankline
+      , literal rule
+      , literal $ title <> T.justifyRight spaceLeft ' ' label'
+      , blankline
+      ]
+
+blockToVimdoc HorizontalRule = do
+  tw <- asks (writerColumns . writerOptions)
+  pure $ literal (T.replicate (tw `div` 2) " *") <> blankline
+
+-- Based on blockToMarkdown' from Text.Pandoc.Writers.Markdown
+blockToVimdoc t@(Table (_, _, _) blkCapt specs thead tbody tfoot) = do
+  let isColRowSpans (Cell _ _ rs cs _) = rs > 1 || cs > 1
+  let rowHasColRowSpans (Row _ cs) = any isColRowSpans cs
+  let tbodyHasColRowSpans (TableBody _ _ rhs rs) =
+        any rowHasColRowSpans rhs || any rowHasColRowSpans rs
+  let theadHasColRowSpans (TableHead _ rs) = any rowHasColRowSpans rs
+  let tfootHasColRowSpans (TableFoot _ rs) = any rowHasColRowSpans rs
+  let hasColRowSpans =
+        theadHasColRowSpans thead
+          || any tbodyHasColRowSpans tbody
+          || tfootHasColRowSpans tfoot
+  let (caption, aligns, widths, headers, rows) =
+        toLegacyTable blkCapt specs thead tbody tfoot
+  let numcols =
+        maximum $
+          length aligns :| length widths : map length (headers : rows)
+  caption' <- inlineListToVimdoc caption
+  let caption''
+        | null caption = blankline
+        | otherwise = blankline $$ caption' $$ blankline
+  let hasSimpleCells = onlySimpleTableCells $ headers : rows
+  let isSimple = hasSimpleCells && all (== 0) widths && not hasColRowSpans
+  let isPlainBlock (Plain _) = True
+      isPlainBlock _ = False
+  let hasBlocks = not (all (all (all isPlainBlock)) $ headers : rows)
+  let padRow r = r ++ replicate x empty
+       where
+        x = numcols - length r
+  let aligns' = aligns ++ replicate x AlignDefault
+       where
+        x = numcols - length aligns
+  let widths' = widths ++ replicate x 0.0
+       where
+        x = numcols - length widths
+  sw <- asks shiftWidth
+  rawHeaders <- padRow <$> mapM blockListToVimdoc headers
+  rawRows <- mapM (fmap padRow . mapM blockListToVimdoc) rows
+  let hasHeader = all null headers
+  if
+    | isSimple -> do
+        -- Simple table
+        tbl <-
+          indent sw $
+            vimdocTable False hasHeader aligns' widths' rawHeaders rawRows
+        pure $ nest sw (tbl $$ caption'') $$ blankline
+    | not (hasBlocks || hasColRowSpans) -> do
+        -- Multiline table
+        tbl <-
+          indent sw $
+            vimdocTable True hasHeader aligns' widths' rawHeaders rawRows
+        pure $ nest sw (tbl $$ caption'') $$ blankline
+    | otherwise -> ("[TABLE]" $$ caption'') <$ report (BlockNotRendered t)
+
+blockToVimdoc (Figure _ _ blocks) = blockListToVimdoc blocks
+
+blockToVimdoc (Div _ blocks) = blockListToVimdoc blocks
+
+{- | Create a vimdoc tag. Tag is prefixed with "$vimdocPrefix-" if vimdocPrefix
+is a Just value.
+>>> runReader (mkVimdocTag "abc") def
+"*abc*"
+>>> runReader (mkVimdocTag "abc") (def{vimdocPrefix = Just "myCoolProject"})
+"*myCoolProject-abc*"
+-}
+mkVimdocTag :: (Monad m) => Text -> VW m Text
+mkVimdocTag tag = do
+  asks vimdocPrefix <&> \case
+    _ | T.null tag -> ""
+    Nothing -> "*" <> tag <> "*"
+    Just pref' -> "*" <> pref' <> "-" <> tag <> "*"
+
+{- | Create a hotlink for a tag, ie. a followable vimdoc link. Tag is prefixed
+ - with "$vimdocPrefix-" if vimdocPrefix is a Just value
+>>> runReader (mkVimdocRef "abc") def
+"|abc|"
+>>> runReader (mkVimdocRef "abc") (def{vimdocPrefix = Just "myCoolProject"})
+"|myCoolProject-abc|"
+-}
+mkVimdocRef :: (Monad m) => Text -> VW m Text
+mkVimdocRef ref =
+  asks vimdocPrefix <&> \case
+    _ | T.null ref -> ""
+    Nothing -> "|" <> ref <> "|"
+    Just pref' -> "|" <> pref' <> "-" <> ref <> "|"
+
+mkVimdocDefinitionTerm ::
+  (PandocMonad m) =>
+  [Inline] ->
+  VW m (Doc Text)
+mkVimdocDefinitionTerm inlines = do
+  il <- asks indentLevel
+  tw <- asks (writerColumns . writerOptions)
+  label <- case inlines of
+    -- NOTE: commands in vim are unique, so they get no prefix
+    [Code (ref, _, _) code]
+      | T.isPrefixOf ":" code ->
+          pure . Just $ "*" <> ref <> "*"
+    [Code (ref, _, _) _] | not (T.null ref) -> Just <$> mkVimdocTag ref
+    [Span (ref, _, _) _] | not (T.null ref) -> Just <$> mkVimdocTag ref
+    _ -> pure Nothing
+
+  term <- case inlines of
+    [Code _ code] | T.isPrefixOf ":" code -> pure $ literal code
+    _ -> inlineListToVimdoc inlines
+  let termLen = offset term
+  let labelLen = maybe 0 T.length label
+
+  if il + termLen + labelLen > tw
+    then
+      pure . mconcat $
+        [ case label of
+            Nothing -> empty
+            -- (+2) due to stars concealment
+            Just l -> flush (rblock (tw + 2) $ literal l) <> cr
+        , term
+        ]
+    else
+      pure . mconcat $
+        [ -- Since we calculated that label fits on the same line as
+          -- term and since label actually must exceed textwidth to align
+          -- properly, we disable wrapping.
+          -- vvvvvvvv
+          nowrap term
+        , case label of
+            Nothing -> empty
+            -- (+2) due to stars concealment
+            Just l -> rblock (tw - termLen - il + 2) (literal l)
+        ]
+
+-- | Write a vimdoc table
+vimdocTable ::
+  (Monad m) =>
+  -- | whether this is a multiline table
+  Bool ->
+  -- | whether the table has a header
+  Bool ->
+  -- | column alignments
+  [Alignment] ->
+  -- | column widths
+  [Double] ->
+  -- | table header cells
+  [Doc Text] ->
+  -- | table body rows
+  [[Doc Text]] ->
+  VW m (Doc Text)
+vimdocTable multiline headless aligns widths rawHeaders rawRows = do
+  let isSimple = all (== 0) widths
+  let alignHeader alignment = case alignment of
+        AlignLeft -> lblock
+        AlignCenter -> cblock
+        AlignRight -> rblock
+        AlignDefault -> lblock
+  -- Number of characters per column necessary to output every cell
+  -- without requiring a line break.
+  -- The @+2@ is needed for specifying the alignment.
+  let numChars = (+ 2) . maybe 0 maximum . nonEmpty . map offset
+  -- Number of characters per column necessary to output every cell
+  -- without requiring a line break *inside a word*.
+  -- The @+2@ is needed for specifying the alignment.
+  let minNumChars = (+ 2) . maybe 0 maximum . nonEmpty . map minOffset
+  let columns = transpose (rawHeaders : rawRows)
+
+  il <- asks indentLevel
+
+  -- x = (2 * length columns)         -- spaces for specifying the alignment
+  -- y = (length columns - 1)         -- spaces between the columns
+  -- x + y = (3 * length columns - 1) -- total needed correction
+  tw <- asks (writerColumns . writerOptions)
+  let tw' = tw - il - 3 * length columns + 1
+  wrap <- asks (writerWrapText . writerOptions)
+
+  -- minimal column width without wrapping a single word
+  let relWidth w col =
+        max
+          (floor $ fromIntegral (tw' - 1) * w)
+          ( if wrap == WrapAuto
+              then minNumChars col
+              else numChars col
+          )
+  let widthsInChars
+        | isSimple = map numChars columns
+        | otherwise = zipWith relWidth widths columns
+  let makeRow =
+        hcat
+          . intersperse (lblock 1 (literal " "))
+          . zipWith3 alignHeader aligns widthsInChars
+  let rows' = map makeRow rawRows
+  -- TODO: reduce tw in case head is not empty
+  let head' = makeRow rawHeaders <> " ~"
+  let head'' =
+        if headless
+          then empty
+          else head'
+  let body =
+        if multiline
+          then
+            vsep rows'
+              $$ if length rows' < 2
+                then blankline
+                else empty
+          else vcat rows'
+  return $
+    blankline
+      $$ head''
+      $$ (if multiline then blankline else empty)
+      $$ body
+
+-- | Replace Unicode characters with their ASCII representation
+replaceSpecialStrings :: Text -> Text
+replaceSpecialStrings =
+  let expand c = case c of
+        '\x00ad' -> ""
+        '\x2013' -> "--"
+        '\x2014' -> "---"
+        '\x2019' -> "'"
+        '\x2026' -> "..."
+        _        -> T.singleton c
+  in T.concatMap expand
+
+inlineListToVimdoc :: (PandocMonad m) => [Inline] -> VW m (Doc Text)
+inlineListToVimdoc inlines = hcat <$> mapM inlineToVimdoc inlines
+
+inlineToVimdoc :: (PandocMonad m) => Inline -> VW m (Doc Text)
+
+inlineToVimdoc (Str str) = pure . literal $ replaceSpecialStrings str
+
+-- Neither `:h help-writing`, nor neovim's grammar.js for vimdoc and
+-- highlights.scm say anything about styling text, so we strip all the
+-- formatting
+inlineToVimdoc (Emph inlines) = inlineListToVimdoc inlines
+inlineToVimdoc (Underline inlines) = inlineListToVimdoc inlines
+inlineToVimdoc (Strong inlines) = inlineListToVimdoc inlines
+inlineToVimdoc (Strikeout inlines) = inlineListToVimdoc inlines
+inlineToVimdoc (Superscript inlines) = inlineListToVimdoc inlines
+inlineToVimdoc (Subscript inlines) = inlineListToVimdoc inlines
+inlineToVimdoc (SmallCaps inlines) = inlineListToVimdoc inlines
+
+inlineToVimdoc (Quoted typ inlines) =
+  let quote = case typ of SingleQuote -> "'"; DoubleQuote -> "\""
+   in inlineListToVimdoc inlines >>= \text -> pure (quote <> text <> quote)
+
+inlineToVimdoc (Cite _citations inlines) = inlineListToVimdoc inlines
+
+inlineToVimdoc (Code (_, cls, _) code) = do
+  let hasNoLang = null cls
+  pure . literal $ case T.words code of
+    [":help", ref] | hasNoLang -> "|" <> ref <> "|"
+    [":h", ref]    | hasNoLang -> "|" <> ref <> "|"
+    _                          -> "`" <> code <> "`"
+
+inlineToVimdoc Space = pure space
+inlineToVimdoc SoftBreak =
+  asks (writerWrapText . writerOptions) >>= \case
+    WrapAuto -> pure space
+    WrapNone -> pure " "
+    WrapPreserve -> pure "\n"
+
+inlineToVimdoc LineBreak = pure "\n"
+
+inlineToVimdoc (Math _ math) = pure . literal $ "`$" <> math <> "$`"
+
+inlineToVimdoc inline@(RawInline (Format format) text) = case format of
+  "vimdoc" -> pure $ literal text
+  _ -> "" <$ report (InlineNotRendered inline)
+
+inlineToVimdoc (Link _ txt (src, _)) = do
+  let srcSuffix = fromMaybe src (T.stripPrefix "mailto:" src)
+  linkText <- render Nothing <$> inlineListToVimdoc txt
+
+  let isAutolink = case txt of
+        [Str x] | escapeURI x `elem` [src, srcSuffix] -> True
+        _ -> False
+
+  pure $ case refdocLinkToLink src of
+    Right link | isAutolink -> "|" <> literal link <> "|"
+    Right link ->
+      literal (T.stripEnd linkText) <> space <> "|" <> literal link <> "|"
+    Left _ | isURI src, isAutolink -> literal srcSuffix
+    Left _ -> literal (T.stripEnd linkText) <> space <> literal srcSuffix
+
+inlineToVimdoc (Image {}) = pure ""
+
+inlineToVimdoc (Note blocks) = do
+  newN <- gets (succ . Seq.length)
+  contents <- blockListToVimdoc blocks
+  tag <- mkVimdocTag ("footnote" <> tshow newN)
+  tw <- asks (writerColumns . writerOptions)
+
+  -- (+2) due to concealment of stars
+  --                     vvvvvvvv
+  let taggedContents = rblock (tw + 2) (literal tag) $$ contents
+  modify (|> taggedContents)
+
+  ref <- mkVimdocRef ("footnote" <> tshow newN)
+  pure $ space <> literal ref
+
+inlineToVimdoc (Span _ inlines) = inlineListToVimdoc inlines
+
+
+refdocLinkToLink :: Text -> Either PandocError Text
+refdocLinkToLink x = (\parser -> readWith parser Nothing x) $ do
+  string "http" >> optional (char 's') >> string "://"
+
+  let vimhelpP = do
+        try (string "vimhelp.org/") <|> string "neo.vimhelp.org/"
+
+        try (many1Till anyChar (char '#') >> many1TillChar anyChar eof)
+          <|> many1TillChar anyChar (try $ string ".html" >> eof)
+
+  let neovimP = do
+        string "neovim.io/doc/user/"
+        try (many1Till anyChar (char '#') >> many1TillChar anyChar eof)
+          <|> do base <- many1TillChar anyChar (try $ string ".html" >> eof)
+                 pure $ base <> ".txt"
+
+  try vimhelpP <|> neovimP
diff --git a/src/Text/Pandoc/Writers/XML.hs b/src/Text/Pandoc/Writers/XML.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Writers/XML.hs
@@ -0,0 +1,365 @@
+{-# LANGUAGE FlexibleContexts #-}
+{-# LANGUAGE OverloadedStrings #-}
+{-# LANGUAGE ScopedTypeVariables #-}
+
+-- |
+--   Module      : Text.Pandoc.Writers.XML
+--   Copyright   : Copyright (C) 2025- Massimiliano Farinella and John MacFarlane
+--   License     : GNU GPL, version 2 or above
+--
+--   Maintainer  : Massimiliano Farinella <massifrg@gmail.com>
+--   Stability   : WIP
+--   Portability : portable
+--
+-- Conversion of 'Pandoc' documents to (pandoc specific) xml markup.
+module Text.Pandoc.Writers.XML (writeXML) where
+
+import Data.Map (Map, toList)
+import Data.Maybe (mapMaybe)
+import qualified Data.Text as T
+import Data.Version (versionBranch)
+import Text.Pandoc.Class.PandocMonad (PandocMonad)
+import Text.Pandoc.Definition
+import Text.Pandoc.Options (WriterOptions (..))
+import Text.Pandoc.XML.Light
+import qualified Text.Pandoc.XML.Light as XML
+import Text.Pandoc.XMLFormat
+import Text.XML.Light (xml_header)
+
+type PandocAttr = Text.Pandoc.Definition.Attr
+
+writeXML :: (PandocMonad m) => WriterOptions -> Pandoc -> m T.Text
+writeXML _ doc = do
+  return $ pandocToXmlText doc
+
+text_node :: T.Text -> Content
+text_node text = Text (CData CDataText text Nothing)
+
+emptyElement :: T.Text -> Element
+emptyElement tag =
+  Element
+    { elName = unqual tag,
+      elAttribs = [],
+      elContent = [],
+      elLine = Nothing
+    }
+
+elementWithContents :: T.Text -> [Content] -> Element
+elementWithContents tag contents =
+  Element
+    { elName = unqual tag,
+      elAttribs = [],
+      elContent = contents,
+      elLine = Nothing
+    }
+
+elementWithAttributes :: T.Text -> [XML.Attr] -> Element
+elementWithAttributes tag attributes =
+  Element
+    { elName = unqual tag,
+      elAttribs = attributes,
+      elContent = [],
+      elLine = Nothing
+    }
+
+elementWithAttrAndContents :: T.Text -> PandocAttr -> [Content] -> Element
+elementWithAttrAndContents tag attr contents = addAttrAttributes attr $ elementWithContents tag contents
+
+asBlockOfInlines :: Element -> [Content]
+asBlockOfInlines el = [Elem el, text_node "\n"]
+
+asBlockOfBlocks :: Element -> [Content]
+asBlockOfBlocks el = [Elem newline_before_first, newline]
+  where
+    newline = text_node "\n"
+    newline_before_first = if null (elContent el) then el else prependContents [newline] el
+
+itemName :: (Show a) => a -> T.Text
+itemName a = T.pack $ takeWhile (/= ' ') (show a)
+
+intAsText :: Int -> T.Text
+intAsText i = T.pack $ show i
+
+itemAsEmptyElement :: (Show a) => a -> Element
+itemAsEmptyElement item = emptyElement $ itemName item
+
+pandocToXmlText :: Pandoc -> T.Text
+pandocToXmlText (Pandoc (Meta meta) blocks) = with_header . with_blocks . with_meta . with_version $ el
+  where
+    el = prependContents [text_node "\n"] $ emptyElement "Pandoc"
+    with_version = addAttribute atNameApiVersion (T.intercalate "," $ map (T.pack . show) $ versionBranch pandocTypesVersion)
+    with_meta = appendContents (metaMapToXML meta "meta")
+    with_blocks = appendContents (asBlockOfBlocks $ elementWithContents "blocks" $ blocksToXML blocks)
+    with_header :: Element -> T.Text
+    with_header e = T.concat [T.pack xml_header, "\n", showElement e]
+
+metaMapToXML :: Map T.Text MetaValue -> T.Text -> [Content]
+metaMapToXML mmap tag = asBlockOfBlocks $ elementWithContents tag entries
+  where
+    entries = concatMap to_entry $ toList mmap
+    to_entry :: (T.Text, MetaValue) -> [Content]
+    to_entry (text, metavalue) = asBlockOfBlocks with_key
+      where
+        entry = elementWithContents tgNameMetaMapEntry $ metaValueToXML metavalue
+        with_key = addAttribute atNameMetaMapEntryKey text entry
+
+metaValueToXML :: MetaValue -> [Content]
+metaValueToXML value =
+  let name = itemName value
+      el = itemAsEmptyElement value
+   in case (value) of
+        MetaBool b -> asBlockOfInlines $ addAttribute atNameMetaBoolValue bool_value el
+          where
+            bool_value = if b then "true" else "false"
+        MetaString s -> asBlockOfInlines $ appendContents [text_node s] el
+        MetaInlines inlines -> asBlockOfInlines $ appendContents (inlinesToXML inlines) el
+        MetaBlocks blocks -> asBlockOfBlocks $ appendContents (blocksToXML blocks) el
+        MetaList items -> asBlockOfBlocks $ appendContents (concatMap metaValueToXML items) el
+        MetaMap mm -> metaMapToXML mm name
+
+blocksToXML :: [Block] -> [Content]
+blocksToXML blocks = concatMap blockToXML blocks
+
+inlinesToXML :: [Inline] -> [Content]
+inlinesToXML inlines = concatMap inlineContentToContents (ilsToIlsContent inlines [])
+
+data InlineContent
+  = NormalInline Inline
+  | ElSpace Int
+  | ElStr T.Text
+
+ilsToIlsContent :: [Inline] -> [InlineContent] -> [InlineContent]
+ilsToIlsContent (Space : xs) [] = ilsToIlsContent xs [ElSpace 1]
+ilsToIlsContent (Space : xs) (NormalInline Space : cs) = ilsToIlsContent xs (ElSpace 2 : cs)
+ilsToIlsContent (Space : xs) (ElSpace n : cs) = ilsToIlsContent xs (ElSpace (n + 1) : cs)
+-- empty Str are always encoded as <Str />
+ilsToIlsContent (Str "" : xs) ilct = ilsToIlsContent xs (ElStr "" : ilct)
+-- Str s1, Str s2 -> s1<Str content="s2">
+ilsToIlsContent (Str s2 : xs) (NormalInline str1@(Str _) : ilct) = ilsToIlsContent xs (ElStr s2 : NormalInline str1 : ilct)
+--
+ilsToIlsContent (Str s : xs) ilct =
+  if T.any (== ' ') s
+    then ilsToIlsContent xs (ElStr s : ilct)
+    else ilsToIlsContent xs (NormalInline (Str s) : ilct)
+ilsToIlsContent (x : xs) ilct = ilsToIlsContent xs (NormalInline x : ilct)
+ilsToIlsContent [] ilct = reverse $ lastSpaceAsElem ilct
+  where
+    lastSpaceAsElem :: [InlineContent] -> [InlineContent]
+    lastSpaceAsElem (NormalInline Space : xs) = ElSpace 1 : xs
+    lastSpaceAsElem ilcts = ilcts
+
+inlineContentToContents :: InlineContent -> [Content]
+inlineContentToContents (NormalInline il) = inlineToXML il
+inlineContentToContents (ElSpace 1) = [Elem $ emptyElement "Space"]
+inlineContentToContents (ElSpace n) = [Elem $ addAttribute atNameSpaceCount (intAsText n) (emptyElement "Space")]
+inlineContentToContents (ElStr "") = [Elem $ emptyElement "Str"]
+inlineContentToContents (ElStr s) = [Elem $ addAttribute atNameStrContent s (emptyElement "Str")]
+
+asContents :: Element -> [Content]
+asContents el = [Elem el]
+
+wrapBlocks :: T.Text -> [Block] -> [Content]
+wrapBlocks tag blocks = asBlockOfBlocks $ elementWithContents tag $ blocksToXML blocks
+
+wrapArrayOfBlocks :: T.Text -> [[Block]] -> [Content]
+wrapArrayOfBlocks tag array = concatMap (wrapBlocks tag) array
+
+-- wrapInlines :: T.Text -> [Inline] -> [Content]
+-- wrapInlines tag inlines = asBlockOfInlines $ element_with_contents tag $ inlinesToXML inlines
+
+blockToXML :: Block -> [Content]
+blockToXML block =
+  let el = itemAsEmptyElement block
+   in case (block) of
+        Para inlines -> asBlockOfInlines $ appendContents (inlinesToXML inlines) el
+        Header level (idn, cls, attrs) inlines -> asBlockOfInlines $ appendContents (inlinesToXML inlines) with_attr
+          where
+            with_attr = addAttrAttributes (idn, cls, attrs ++ [(atNameLevel, intAsText level)]) el
+        Plain inlines -> asBlockOfInlines $ appendContents (inlinesToXML inlines) el
+        Div attr blocks -> asBlockOfBlocks $ appendContents (blocksToXML blocks) with_attr
+          where
+            with_attr = addAttrAttributes attr el
+        BulletList items -> asBlockOfBlocks $ appendContents (wrapArrayOfBlocks tgNameListItem items) el
+        OrderedList (start, style, delim) items -> asBlockOfBlocks $ with_contents . with_attrs $ el
+          where
+            with_attrs =
+              addAttributes
+                ( validAttributes
+                    [ (atNameStart, intAsText start),
+                      (atNameNumberStyle, itemName style),
+                      (atNameNumberDelim, itemName delim)
+                    ]
+                )
+            with_contents = appendContents (wrapArrayOfBlocks tgNameListItem items)
+        BlockQuote blocks -> asBlockOfBlocks $ appendContents (blocksToXML blocks) el
+        HorizontalRule -> asBlockOfInlines el
+        CodeBlock attr text -> asBlockOfInlines $ with_contents . with_attr $ el
+          where
+            with_contents = appendContents [text_node text]
+            with_attr = addAttrAttributes attr
+        LineBlock lins -> asBlockOfBlocks $ appendContents (concatMap wrapInlines lins) el
+          where
+            wrapInlines inlines = asContents $ appendContents (inlinesToXML inlines) $ emptyElement tgNameLineItem
+        Table attr caption colspecs thead tbodies tfoot -> asBlockOfBlocks $ with_foot . with_bodies . with_head . with_colspecs . with_caption . with_attr $ el
+          where
+            with_attr = addAttrAttributes attr
+            with_caption = appendContents (captionToXML caption)
+            with_colspecs = appendContents (colSpecsToXML colspecs)
+            with_head = appendContents (tableHeadToXML thead)
+            with_bodies = appendContents (concatMap tableBodyToXML tbodies)
+            with_foot = appendContents (tableFootToXML tfoot)
+        Figure attr caption blocks -> asBlockOfBlocks $ with_contents . with_caption . with_attr $ el
+          where
+            with_attr = addAttrAttributes attr
+            with_caption = appendContents (captionToXML caption)
+            with_contents = appendContents (blocksToXML blocks)
+        RawBlock (Format format) text -> asContents $ appendContents [text_node text] raw
+          where
+            raw = addAttribute atNameFormat format el
+        DefinitionList items -> asBlockOfBlocks $ appendContents (map definitionListItemToXML items) el
+
+inlineToXML :: Inline -> [Content]
+inlineToXML inline =
+  let el = itemAsEmptyElement inline
+      wrapInlines inlines = asContents $ appendContents (inlinesToXML inlines) el
+   in case (inline) of
+        Space -> [text_node " "]
+        Str s -> [text_node s]
+        Emph inlines -> wrapInlines inlines
+        Strong inlines -> wrapInlines inlines
+        Quoted quote_type inlines -> asContents $ appendContents (inlinesToXML inlines) quoted
+          where
+            quoted = addAttribute atNameQuoteType (itemName quote_type) el
+        Underline inlines -> wrapInlines inlines
+        Strikeout inlines -> wrapInlines inlines
+        SmallCaps inlines -> wrapInlines inlines
+        Superscript inlines -> wrapInlines inlines
+        Subscript inlines -> wrapInlines inlines
+        SoftBreak -> asContents el
+        LineBreak -> asContents el
+        Span attr inlines -> asContents $ appendContents (inlinesToXML inlines) with_attr
+          where
+            with_attr = addAttrAttributes attr el
+        Link (idn, cls, attrs) inlines (url, title) -> asContents $ appendContents (inlinesToXML inlines) with_attr
+          where
+            with_attr = addAttrAttributes (idn, cls, attrs ++ [(atNameLinkUrl, url), (atNameTitle, title)]) el
+        Image (idn, cls, attrs) inlines (url, title) -> asContents $ appendContents (inlinesToXML inlines) with_attr
+          where
+            with_attr = addAttrAttributes (idn, cls, attrs ++ [(atNameImageUrl, url), (atNameTitle, title)]) el
+        RawInline (Format format) text -> asContents $ appendContents [text_node text] raw
+          where
+            raw = addAttribute atNameFormat format el
+        Math math_type text -> asContents $ appendContents [text_node text] math
+          where
+            math = addAttribute atNameMathType (itemName math_type) el
+        Code attr text -> asContents $ appendContents [text_node text] with_attr
+          where
+            with_attr = addAttrAttributes attr el
+        Note blocks -> asContents $ appendContents (blocksToXML blocks) el
+        Cite citations inlines -> asContents $ appendContents (inlinesToXML inlines) with_citations
+          where
+            with_citations = addCitations citations el
+
+-- TODO: don't let an attribute overwrite id or class
+maybeAttribute :: (T.Text, T.Text) -> Maybe XML.Attr
+maybeAttribute (_, "") = Nothing
+maybeAttribute ("", _) = Nothing
+maybeAttribute (name, value) = Just $ XML.Attr (unqual name) value
+
+validAttributes :: [(T.Text, T.Text)] -> [XML.Attr]
+validAttributes pairs = mapMaybe maybeAttribute pairs
+
+appendContents :: [Content] -> Element -> Element
+appendContents newContents el = el {elContent = (elContent el) ++ newContents}
+
+prependContents :: [Content] -> Element -> Element
+prependContents newContents el = el {elContent = newContents ++ (elContent el)}
+
+addAttributes :: [XML.Attr] -> Element -> Element
+addAttributes newAttrs el = el {elAttribs = newAttrs ++ elAttribs el}
+
+addAttribute :: T.Text -> T.Text -> Element -> Element
+addAttribute attr_name attr_value el = el {elAttribs = new_attr : elAttribs el}
+  where
+    new_attr = XML.Attr (unqual attr_name) attr_value
+
+addAttrAttributes :: PandocAttr -> Element -> Element
+addAttrAttributes (identifier, classes, attributes) el = addAttributes attrs' el
+  where
+    attrs' = mapMaybe maybeAttribute (("id", identifier) : ("class", T.intercalate " " classes) : attributes)
+
+addCitations :: [Citation] -> Element -> Element
+addCitations citations el = appendContents [Elem $ elementWithContents tgNameCitations $ (text_node "\n") : concatMap citation_to_elem citations] el
+  where
+    citation_to_elem :: Citation -> [Content]
+    citation_to_elem citation = asBlockOfInlines with_suffix
+      where
+        cit_elem = elementWithAttributes (itemName citation) attrs
+        prefix = citationPrefix citation
+        suffix = citationSuffix citation
+        with_prefix =
+          if null prefix
+            then cit_elem
+            else appendContents [Elem $ elementWithContents tgNameCitationPrefix $ inlinesToXML prefix] cit_elem
+        with_suffix =
+          if null suffix
+            then with_prefix
+            else appendContents [Elem $ elementWithContents tgNameCitationSuffix $ inlinesToXML suffix] with_prefix
+        attrs =
+          map
+            (\(n, v) -> XML.Attr (unqual n) v)
+            [ ("id", citationId citation),
+              (atNameCitationMode, T.pack $ show $ citationMode citation),
+              (atNameCitationNoteNum, intAsText $ citationNoteNum citation),
+              (atNameCitationHash, intAsText $ citationHash citation)
+            ]
+
+definitionListItemToXML :: ([Inline], [[Block]]) -> Content
+definitionListItemToXML (inlines, defs) = Elem $ elementWithContents tgNameDefListItem $ term ++ wrapArrayOfBlocks tgNameDefListDef defs
+  where
+    term = asBlockOfInlines $ appendContents (inlinesToXML inlines) $ emptyElement tgNameDefListTerm
+
+captionToXML :: Caption -> [Content]
+captionToXML (Caption short blocks) = asBlockOfBlocks with_short_caption
+  where
+    el = elementWithContents "Caption" $ blocksToXML blocks
+    with_short_caption = case (short) of
+      Just inlines -> prependContents (asBlockOfInlines $ elementWithContents tgNameShortCaption $ inlinesToXML inlines) el
+      _ -> el
+
+colSpecToXML :: (Alignment, ColWidth) -> [Content]
+colSpecToXML (align, cw) = asBlockOfInlines colspec
+  where
+    colspec = elementWithAttributes "ColSpec" $ validAttributes [(atNameAlignment, itemName align), (atNameColWidth, colwidth)]
+    colwidth = case (cw) of
+      ColWidth d -> T.pack $ show d
+      ColWidthDefault -> "0"
+
+colSpecsToXML :: [(Alignment, ColWidth)] -> [Content]
+colSpecsToXML colspecs = asBlockOfBlocks $ elementWithContents tgNameColspecs $ concatMap colSpecToXML colspecs
+
+tableHeadToXML :: TableHead -> [Content]
+tableHeadToXML (TableHead attr rows) = asBlockOfBlocks $ elementWithAttrAndContents "TableHead" attr $ concatMap rowToXML rows
+
+tableBodyToXML :: TableBody -> [Content]
+tableBodyToXML (TableBody (idn, cls, attrs) (RowHeadColumns headcols) hrows brows) = asBlockOfBlocks $ elementWithAttrAndContents "TableBody" attr children
+  where
+    attr = (idn, cls, (atNameRowHeadColumns, intAsText headcols) : attrs)
+    header_rows = asBlockOfBlocks $ elementWithContents tgNameBodyHeader $ concatMap rowToXML hrows
+    body_rows = asBlockOfBlocks $ elementWithContents tgNameBodyBody $ concatMap rowToXML brows
+    children = header_rows ++ body_rows
+
+tableFootToXML :: TableFoot -> [Content]
+tableFootToXML (TableFoot attr rows) = asBlockOfBlocks $ elementWithAttrAndContents "TableFoot" attr $ concatMap rowToXML rows
+
+rowToXML :: Row -> [Content]
+rowToXML (Row attr cells) = asBlockOfBlocks $ elementWithAttrAndContents "Row" attr $ concatMap cellToXML cells
+
+cellToXML :: Cell -> [Content]
+cellToXML (Cell (idn, cls, attrs) alignment (RowSpan rowspan) (ColSpan colspan) blocks) = asBlockOfBlocks $ elementWithAttrAndContents "Cell" attr $ blocksToXML blocks
+  where
+    with_alignment a = (atNameAlignment, itemName alignment) : a
+    with_rowspan a = if rowspan > 1 then (atNameRowspan, intAsText rowspan) : a else a
+    with_colspan a = if colspan > 1 then (atNameColspan, intAsText colspan) : a else a
+    attrs' = (with_colspan . with_rowspan . with_alignment) attrs
+    attr = (idn, cls, attrs')
diff --git a/src/Text/Pandoc/Writers/XWiki.hs b/src/Text/Pandoc/Writers/XWiki.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Writers/XWiki.hs
@@ -0,0 +1,284 @@
+{-# LANGUAGE OverloadedStrings #-}
+{-
+Copyright (C) 2008-2024 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.XWiki
+   Copyright   : Copyright (C) 2008-2024 John MacFarlane
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : Derek Chen-Becker <dchenbecker@gmail.com>
+   Stability   : alpha
+   Portability : portable
+
+Conversion of 'Pandoc' documents to XWiki markup.
+
+XWiki:  <http://www.xwiki.org/>
+XWiki Syntax:  <http://www.xwiki.org/xwiki/bin/view/Documentation/UserGuide/Features/XWikiSyntax/>
+-}
+
+module Text.Pandoc.Writers.XWiki ( writeXWiki ) where
+import Control.Monad.Reader (ReaderT, asks, local, runReaderT)
+import qualified Data.Set as Set
+import qualified Data.Text as Text
+import Data.Text (Text, intercalate, replace, split)
+import Text.Pandoc.Class.PandocMonad (PandocMonad, report)
+import Text.Pandoc.Definition
+import Text.Pandoc.Logging
+import Text.Pandoc.Options
+import Text.Pandoc.Shared
+import Text.Pandoc.URI
+import Text.Pandoc.Writers.MediaWiki (highlightingLangs)
+import Text.Pandoc.Templates (renderTemplate)
+import Text.Pandoc.Writers.Shared (defField, metaToContext, toLegacyTable)
+import Text.DocLayout (render, literal)
+
+newtype WriterState = WriterState {
+  listLevel :: Text -- String at the beginning of items
+}
+
+type XWikiReader m = ReaderT WriterState m
+
+-- | Convert Pandoc to XWiki.
+writeXWiki :: PandocMonad m => WriterOptions -> Pandoc -> m Text
+writeXWiki opts (Pandoc meta blocks) = do
+  let env = WriterState { listLevel = "" }
+  metadata <- metaToContext opts
+              (fmap (literal . trimr) . (\bs -> runReaderT (blockListToXWiki bs) env))
+              (fmap (literal . trimr) . (\is -> runReaderT (inlineListToXWiki is) env))
+              meta
+  body <- runReaderT (blockListToXWiki blocks) env
+  let context = defField "body" body
+                $ defField "toc" (writerTableOfContents opts) metadata
+  return $
+    case writerTemplate opts of
+       Just tpl -> render Nothing $ renderTemplate tpl context
+       Nothing  -> body
+
+-- | Concatenates strings with line breaks between them.
+vcat :: [Text] -> Text
+vcat = intercalate "\n"
+
+-- If an id is provided, we can generate an anchor using the id macro
+-- https://extensions.xwiki.org/xwiki/bin/view/Extension/Id%20Macro
+genAnchor :: Text -> Text
+genAnchor id' = if Text.null id'
+  then ""
+  else "{{id name=\"" <> id' <> "\" /}}"
+
+blockListToXWiki :: PandocMonad m => [Block] -> XWikiReader m Text
+blockListToXWiki blocks =
+  vcat <$> mapM blockToXWiki blocks
+
+blockToXWiki :: PandocMonad m => Block -> XWikiReader m Text
+
+blockToXWiki (Div (id', _, _) blocks) = do
+  content <- blockListToXWiki blocks
+  return $ genAnchor id' <> content
+
+blockToXWiki (Plain inlines) =
+  inlineListToXWiki inlines
+
+blockToXWiki (Para inlines) = do
+  contents <- inlineListToXWiki inlines
+  return $ contents <> "\n"
+
+blockToXWiki (LineBlock lns) =
+  blockToXWiki $ linesToPara lns
+
+blockToXWiki b@(RawBlock f str)
+  | f == Format "xwiki" = return str
+  | otherwise           = "" <$ report (BlockNotRendered b)
+
+blockToXWiki HorizontalRule = return "\n----\n"
+
+blockToXWiki (Header level (id', _, _) inlines) = do
+  contents <- inlineListToXWiki inlines
+  let eqs = Text.replicate level "="
+  return $ eqs <> " " <> contents <> " " <> genAnchor id' <> eqs <> "\n"
+
+-- XWiki doesn't appear to differentiate between inline and block-form code, so we delegate
+-- We do amend the text to ensure that the code markers are on their own lines, since this is a block
+blockToXWiki (CodeBlock attrs str) = do
+  contents <- inlineToXWiki (Code attrs ("\n" <> str <> "\n"))
+  return $ "\n" <> contents <> "\n"
+
+blockToXWiki (BlockQuote blocks) = do
+  blockText <- blockListToXWiki blocks
+  let quoteLines = split (== '\n') blockText
+  let prefixed = map (">" <>) quoteLines
+  return $ vcat prefixed
+
+blockToXWiki (BulletList contents) = blockToXWikiList "*" contents
+
+blockToXWiki (OrderedList _ contents) = blockToXWikiList "1" contents
+
+blockToXWiki (DefinitionList items) = do
+  lev <- asks listLevel
+  contents <- local (\s -> s { listLevel = listLevel s <> ";" }) $ mapM definitionListItemToMediaWiki items
+  return $ vcat contents <> if Text.null lev then "\n" else ""
+
+-- Create a group according to
+-- https://www.xwiki.org/xwiki/bin/view/Documentation/UserGuide/Features/XWikiSyntax/?syntax=2.1&section=Groups
+blockToXWiki (Figure attr _ body) = do
+  content <- blockToXWiki $ Div attr body
+  return $ intercalate content ["(((\n", "\n)))"]
+
+-- TODO: support more features
+blockToXWiki (Table _ blkCapt specs thead tbody tfoot) = do
+  let (_, _, _, headers, rows') = toLegacyTable blkCapt specs thead tbody tfoot
+  headers' <- mapM (tableCellXWiki True) $ take (length specs) $ headers ++ repeat []
+  otherRows <- mapM formRow rows'
+  return $ Text.unlines (Text.unwords headers':otherRows)
+
+formRow :: PandocMonad m => [[Block]] -> XWikiReader m Text
+formRow row = do
+  cellStrings <- mapM (tableCellXWiki False) row
+  return $ Text.unwords cellStrings
+
+
+tableCellXWiki :: PandocMonad m => Bool -> [Block] -> XWikiReader m Text
+tableCellXWiki isHeader cell = do
+  contents <- blockListToXWiki cell
+  let isMultiline = (length . split (== '\n')) contents > 1
+  let contents' = intercalate contents $ if isMultiline then ["(((", ")))"] else [mempty, mempty]
+  let cellBorder = if isHeader then "|=" else "|"
+  return $ cellBorder <> contents'
+
+
+inlineListToXWiki :: PandocMonad m => [Inline] -> XWikiReader m Text
+inlineListToXWiki lst =
+  mconcat <$> mapM inlineToXWiki lst
+
+inlineToXWiki :: PandocMonad m => Inline -> XWikiReader m Text
+
+inlineToXWiki (Str str) = return $ escapeXWikiString str
+
+inlineToXWiki Space = return " "
+
+-- Special syntax for XWiki 2.0. This won't break table cells
+inlineToXWiki LineBreak = return "\\\\"
+
+inlineToXWiki SoftBreak = return " "
+
+inlineToXWiki (Emph lst) = do
+  contents <- inlineListToXWiki lst
+  return $ "//" <> contents <> "//"
+
+inlineToXWiki (Underline lst) = do
+  contents <- inlineListToXWiki lst
+  return $ "__" <> contents <> "__"
+
+inlineToXWiki (Strong lst) = do
+  contents <- inlineListToXWiki lst
+  return $ "**" <> contents <> "**"
+
+inlineToXWiki (Strikeout lst) = do
+  contents <- inlineListToXWiki lst
+  return $ "--" <> contents <> "--"
+
+inlineToXWiki (Superscript lst) = do
+  contents <- inlineListToXWiki lst
+  return $ "^^" <> contents <> "^^"
+
+inlineToXWiki (Subscript lst) = do
+  contents <- inlineListToXWiki lst
+  return $ ",," <> contents <> ",,"
+
+-- TODO: Not supported. Maybe escape to HTML?
+inlineToXWiki (SmallCaps lst) =
+  inlineListToXWiki lst
+
+inlineToXWiki (Quoted SingleQuote lst) = do
+  contents <- inlineListToXWiki lst
+  return $ "‘" <> contents <> "’"
+
+inlineToXWiki (Quoted DoubleQuote lst) = do
+  contents <- inlineListToXWiki lst
+  return $ "“" <> contents <> "”"
+
+inlineToXWiki (Code (_,classes,_) contents) = do
+  let at  = Set.fromList classes `Set.intersection` highlightingLangs
+  return $
+    case Set.toList at of
+      [] -> "{{code}}" <> contents <> "{{/code}}"
+      (l:_) -> "{{code language=\"" <> l <> "\"}}" <> contents <> "{{/code}}"
+
+inlineToXWiki (Cite _ lst) = inlineListToXWiki lst
+
+-- FIXME: optionally support this (plugin?)
+inlineToXWiki (Math _ str) = return $ "{{formula}}" <> str <> "{{/formula}}"
+
+inlineToXWiki il@(RawInline frmt str)
+  | frmt == Format "xwiki" = return str
+  | otherwise              = "" <$ report (InlineNotRendered il)
+
+-- TODO: Handle anchors
+inlineToXWiki (Link (id', _, _) txt (src, _)) = do
+  label <- inlineListToXWiki txt
+  case txt of
+     [Str s] | isURI src && escapeURI s == src -> return $ src <> genAnchor id'
+     _  -> return $ "[[" <> label <> ">>" <> src <> "]]" <> genAnchor id'
+
+inlineToXWiki (Image _ alt (source, tit)) = do
+  alt' <- inlineListToXWiki alt
+  let
+    params = Text.unwords $ filter (not . Text.null) [
+        if Text.null alt' then "" else "alt=\"" <> alt' <> "\"",
+          if Text.null tit then "" else "title=\"" <> tit <> "\""
+        ]
+  return $ "[[image:" <> source <> (if Text.null params then "" else "||" <> params) <> "]]"
+
+inlineToXWiki (Note contents) = do
+  contents' <- blockListToXWiki contents
+  return $ "{{footnote}}" <> Text.strip contents' <> "{{/footnote}}"
+
+-- TODO: support attrs other than id (anchor)
+inlineToXWiki (Span (id', _, _) contents) = do
+  contents' <- inlineListToXWiki contents
+  return $ genAnchor id' <> contents'
+
+-- Utility method since (for now) all lists are handled the same way
+blockToXWikiList :: PandocMonad m => Text -> [[Block]] -> XWikiReader m Text
+blockToXWikiList marker contents = do
+  lev <- asks listLevel
+  contents' <- local (\s -> s { listLevel = listLevel s <> marker } ) $ mapM listItemToXWiki contents
+  return $ vcat contents' <> if Text.null lev then "\n" else ""
+
+
+listItemToXWiki :: PandocMonad m => [Block] -> XWikiReader m Text
+listItemToXWiki contents = do
+  marker <- asks listLevel
+  contents' <- blockListToXWiki contents
+  return $ marker <> ". " <> Text.strip contents'
+
+
+-- | Convert definition list item (label, list of blocks) to MediaWiki.
+definitionListItemToMediaWiki :: PandocMonad m
+                              => ([Inline],[[Block]])
+                              -> XWikiReader m Text
+definitionListItemToMediaWiki (label, items) = do
+  labelText <- inlineListToXWiki label
+  contents <- mapM blockListToXWiki items
+  marker <- asks listLevel
+  return $ marker <> " " <> labelText <> "\n" <>
+    intercalate "\n" (map (\d -> Text.init marker <> ": " <> d) contents)
+
+-- Escape the escape character, as well as formatting pairs
+escapeXWikiString :: Text -> Text
+escapeXWikiString s = foldr (uncurry replace) s $ zip ["--", "**", "//", "^^", ",,", "~"] ["~-~-", "~*~*", "~/~/", "~^~^", "~,~,", "~~"]
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,25 +1,8 @@
-{-
-Copyright (C) 2008-2017 John MacFarlane <jgm@berkeley.edu>
-              2017 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
--}
-
+{-# LANGUAGE OverloadedStrings #-}
 {- |
    Module      : Text.Pandoc.Writers.ZimWiki
-   Copyright   : Copyright (C) 2008-2017 John MacFarlane, 2017 Alex Ivkin
+   Copyright   : © 2008-2024 John MacFarlane,
+                   2017-2019 Alex Ivkin
    License     : GNU GPL, version 2 or above
 
    Maintainer  : Alex Ivkin <alex@ivkin.net>
@@ -35,29 +18,33 @@
 import Control.Monad (zipWithM)
 import Control.Monad.State.Strict (StateT, evalStateT, gets, modify)
 import Data.Default (Default (..))
-import Data.List (intercalate, isInfixOf, isPrefixOf, transpose)
+import Data.List (transpose)
+import Data.List.NonEmpty (nonEmpty)
 import qualified Data.Map as Map
+import Text.DocLayout (render, literal)
 import Data.Maybe (fromMaybe)
-import Data.Text (Text, breakOnAll, pack)
-import Text.Pandoc.Class (PandocMonad, report)
+import Data.Text (Text)
+import qualified Data.Text as T
+import Text.Pandoc.Class.PandocMonad (PandocMonad, report)
 import Text.Pandoc.Definition
 import Text.Pandoc.ImageSize
 import Text.Pandoc.Logging
-import Text.Pandoc.Options (WrapOption (..), WriterOptions (writerTableOfContents, writerTemplate, writerWrapText))
-import Text.Pandoc.Shared (escapeURI, isURI, linesToPara, removeFormatting,
-                           substitute, trimr)
-import Text.Pandoc.Templates (renderTemplate')
-import Text.Pandoc.Writers.Shared (defField, metaToJSON)
+import Text.Pandoc.Options (WrapOption (..),
+           WriterOptions (writerTableOfContents, writerTemplate,
+                          writerWrapText))
+import Text.Pandoc.Shared (figureDiv, linesToPara, removeFormatting, trimr)
+import Text.Pandoc.URI (escapeURI, isURI)
+import Text.Pandoc.Templates (renderTemplate)
+import Text.Pandoc.Writers.Shared (defField, metaToContext, toLegacyTable)
 
 data WriterState = WriterState {
-    stItemNum :: Int,
-    stIndent  :: String,         -- Indent after the marker at the beginning of list items
+    stIndent  :: Text,           -- Indent after the marker at the beginning of list items
     stInTable :: Bool,           -- Inside a table
     stInLink  :: Bool            -- Inside a link description
   }
 
 instance Default WriterState where
-  def = WriterState { stItemNum = 1, stIndent = "", stInTable = False, stInLink = False }
+  def = WriterState { stIndent = "", stInTable = False, stInLink = False }
 
 type ZW = StateT WriterState
 
@@ -68,55 +55,40 @@
 -- | Return ZimWiki representation of document.
 pandocToZimWiki :: PandocMonad m => WriterOptions -> Pandoc -> ZW m Text
 pandocToZimWiki opts (Pandoc meta blocks) = do
-  metadata <- metaToJSON opts
-              (fmap trimr . blockListToZimWiki opts)
-              (inlineListToZimWiki opts)
+  metadata <- metaToContext opts
+              (fmap (literal . trimr) . blockListToZimWiki opts)
+              (fmap (literal . trimr) . inlineListToZimWiki opts)
               meta
-  body <- pack <$> blockListToZimWiki opts blocks
+  main <- blockListToZimWiki opts blocks
   --let header = "Content-Type: text/x-zim-wiki\nWiki-Format: zim 0.4\n"
-  let main = body
   let context = defField "body" main
                 $ defField "toc" (writerTableOfContents opts) metadata
-  case writerTemplate opts of
-       Just tpl -> renderTemplate' tpl context
-       Nothing  -> return main
+  return $
+    case writerTemplate opts of
+       Just tpl -> render Nothing $ renderTemplate tpl context
+       Nothing  -> main
 
 -- | Escape special characters for ZimWiki.
-escapeString :: String -> String
-escapeString = substitute "__" "''__''" .
-               substitute "**" "''**''" .
-               substitute "~~" "''~~''" .
-               substitute "//" "''//''"
+escapeText :: Text -> Text
+escapeText = T.replace "__" "''__''" .
+               T.replace "**" "''**''" .
+               T.replace "~~" "''~~''" .
+               T.replace "//" "''//''"
 
 -- | Convert Pandoc block element to ZimWiki.
-blockToZimWiki :: PandocMonad m => WriterOptions -> Block -> ZW m String
-
-blockToZimWiki _ Null = return ""
+blockToZimWiki :: PandocMonad m => WriterOptions -> Block -> ZW m Text
 
 blockToZimWiki opts (Div _attrs bs) = do
   contents <- blockListToZimWiki opts bs
-  return $ contents ++ "\n"
+  return $ contents <> "\n"
 
 blockToZimWiki opts (Plain inlines) = inlineListToZimWiki opts inlines
 
--- title beginning with fig: indicates that the image is a figure
--- ZimWiki doesn't support captions - so combine together alt and caption into alt
-blockToZimWiki opts (Para [Image attr txt (src,'f':'i':'g':':':tit)]) = do
-  capt <- if null txt
-             then return ""
-             else (" " ++) `fmap` inlineListToZimWiki opts txt
-  let opt = if null txt
-               then ""
-               else "|" ++ if null tit then capt else tit ++ capt
-      -- Relative links fail isURI and receive a colon
-      prefix = if isURI src then "" else ":"
-  return $ "{{" ++ prefix ++ src ++ imageDims opts attr ++ opt ++ "}}\n"
-
 blockToZimWiki opts (Para inlines) = do
   indent <- gets stIndent
   -- useTags <- gets stUseTags
   contents <- inlineListToZimWiki opts inlines
-  return $ contents ++ if null indent then "\n" else ""
+  return $ contents <> if T.null indent then "\n" else ""
 
 blockToZimWiki opts (LineBlock lns) =
   blockToZimWiki opts $ linesToPara lns
@@ -131,140 +103,144 @@
 blockToZimWiki _ HorizontalRule = return "\n----\n"
 
 blockToZimWiki opts (Header level _ inlines) = do
-  contents <- inlineListToZimWiki opts $ removeFormatting inlines   -- emphasis, links etc. not allowed in headers
-  let eqs = replicate ( 7 - level ) '='
-  return $ eqs ++ " " ++ contents ++ " " ++ eqs ++ "\n"
+  contents <- inlineListToZimWiki opts inlines
+  let eqs = T.replicate ( 7 - level ) "="
+  return $ eqs <> " " <> contents <> " " <> eqs <> "\n"
 
 blockToZimWiki _ (CodeBlock (_,classes,_) str) = do
   -- Remap languages into the gtksourceview2 convention that ZimWiki source code plugin is using
   let langal = [("javascript", "js"), ("bash", "sh"), ("winbatch", "dosbatch")]
   let langmap = Map.fromList langal
   return $ case classes of
-                []      -> "'''\n" ++ cleanupCode str ++ "\n'''\n"   -- turn no lang block into a quote block
-                (x:_)   -> "{{{code: lang=\"" ++
-                        fromMaybe x (Map.lookup x langmap) ++ "\" linenumbers=\"True\"\n" ++ str ++ "\n}}}\n"  -- for zim's code plugin, go verbatim on the lang spec
+                []      -> "'''\n" <> cleanupCode str <> "\n'''\n"   -- turn no lang block into a quote block
+                (x:_)   -> "{{{code: lang=\"" <>
+                        fromMaybe x (Map.lookup x langmap) <> "\" linenumbers=\"True\"\n" <> str <> "\n}}}\n"  -- for zim's code plugin, go verbatim on the lang spec
 
 blockToZimWiki opts (BlockQuote blocks) = do
   contents <- blockListToZimWiki opts blocks
-  return $ unlines $ map ("> " ++) $ lines contents
+  return $ T.unlines $ map ("> " <>) $ T.lines contents
 
-blockToZimWiki opts (Table capt aligns _ headers rows) = do
+blockToZimWiki opts (Table _ blkCapt specs thead tbody tfoot) = do
+  let (capt, aligns, _, headers, rows) = toLegacyTable blkCapt specs thead tbody tfoot
   captionDoc <- if null capt
                    then return ""
                    else do
                       c <- inlineListToZimWiki opts capt
-                      return $ "" ++ c ++ "\n"
+                      return $ "" <> c <> "\n"
   headers' <- if all null headers
-                 then zipWithM (tableItemToZimWiki opts) aligns (head rows)
+                 then case rows of
+                        [] -> pure mempty
+                        (r:_) -> zipWithM (tableItemToZimWiki opts) aligns r
                  else mapM (inlineListToZimWiki opts . removeFormatting)headers  -- emphasis, links etc. are not allowed in table headers
   rows' <- mapM (zipWithM (tableItemToZimWiki opts) aligns) rows
-  let widths = map (maximum . map length) $ transpose (headers':rows')
+  let widths = map (maybe 0 maximum . nonEmpty . map T.length) $
+                  transpose (headers':rows')
   let padTo (width, al) s =
-          case width - length s of
+          case width - T.length s of
                x | x > 0 ->
                  if al == AlignLeft || al == AlignDefault
-                    then s ++ replicate x ' '
+                    then s <> T.replicate x " "
                     else if al == AlignRight
-                            then replicate x ' ' ++ s
-                            else replicate (x `div` 2) ' ' ++
-                                 s ++ replicate (x - x `div` 2) ' '
+                            then T.replicate x " " <> s
+                            else T.replicate (x `div` 2) " " <>
+                                 s <> T.replicate (x - x `div` 2) " "
                  | otherwise -> s
   let borderCell (width, al) _
-        | al == AlignLeft = ":"++ replicate (width-1) '-'
-        | al == AlignDefault = replicate width '-'
-        | al == AlignRight = replicate (width-1) '-' ++ ":"
-        | otherwise = ":" ++ replicate (width-2) '-' ++ ":"
-  let underheader  = "|" ++ intercalate "|" (zipWith borderCell (zip widths aligns) headers') ++ "|"
-  let renderRow cells = "|" ++ intercalate "|" (zipWith padTo (zip widths aligns) cells) ++ "|"
-  return $ captionDoc ++
-           (if null headers' then "" else renderRow headers' ++ "\n") ++ underheader ++ "\n" ++
-           unlines (map renderRow rows')
+        | al == AlignLeft = ":"<> T.replicate (width-1) "-"
+        | al == AlignDefault = T.replicate width "-"
+        | al == AlignRight = T.replicate (width-1) "-" <> ":"
+        | otherwise = ":" <> T.replicate (width-2) "-" <> ":"
+  let underheader  = "|" <> T.intercalate "|" (zipWith borderCell (zip widths aligns) headers') <> "|"
+  let renderRow cells = "|" <> T.intercalate "|" (zipWith padTo (zip widths aligns) cells) <> "|"
+  return $ captionDoc <>
+           (if null headers' then "" else renderRow headers' <> "\n") <> underheader <> "\n" <>
+           T.unlines (map renderRow rows')
 
 blockToZimWiki opts (BulletList items) = do
-  indent <- gets stIndent
-  modify $ \s -> s { stIndent = stIndent s ++ "\t" }
   contents <- mapM (listItemToZimWiki opts) items
-  modify $ \s -> s{ stIndent = indent } -- drop 1 (stIndent s) }
-  return $ vcat contents ++ if null indent then "\n" else ""
+  indent <- gets stIndent
+  return $ vcat contents <> if T.null indent then "\n" else ""
 
 blockToZimWiki opts (OrderedList _ items) = do
+  contents <- zipWithM (orderedListItemToZimWiki opts) [1..] items
   indent <- gets stIndent
-  modify $ \s -> s { stIndent = stIndent s ++ "\t", stItemNum = 1 }
-  contents <- mapM (orderedListItemToZimWiki opts) items
-  modify $ \s -> s{ stIndent = indent } -- drop 1 (stIndent s) }
-  return $ vcat contents ++ if null indent then "\n" else ""
+  return $ vcat contents <> if T.null indent then "\n" else ""
 
 blockToZimWiki opts (DefinitionList items) = do
   contents <- mapM (definitionListItemToZimWiki opts) items
   return $ vcat contents
 
+blockToZimWiki opts (Figure attr capt body) = do
+  blockToZimWiki opts (figureDiv attr capt body)
+
 definitionListItemToZimWiki :: PandocMonad m
                             => WriterOptions
                             -> ([Inline],[[Block]])
-                            -> ZW m String
+                            -> ZW m Text
 definitionListItemToZimWiki opts (label, items) = do
   labelText <- inlineListToZimWiki opts label
   contents <- mapM (blockListToZimWiki opts) items
   indent <- gets stIndent
-  return $ indent ++ "* **" ++ labelText ++ "** " ++ concat contents
+  return $ indent <> "* **" <> labelText <> "** " <> T.concat contents
 
 -- Auxiliary functions for lists:
-indentFromHTML :: PandocMonad m => WriterOptions -> String -> ZW m String
+indentFromHTML :: PandocMonad m => WriterOptions -> Text -> ZW m Text
 indentFromHTML _ str = do
    indent <- gets stIndent
-   itemnum <- gets stItemNum
-   if "<li>" `isInfixOf` str then return $ indent ++ show itemnum ++ "."
-        else if "</li>" `isInfixOf` str then return "\n"
-                else if "<li value=" `isInfixOf` str then do
-                        -- poor man's cut
-                        let val = drop 10 $ reverse $ drop 1 $ reverse str
-                        --let val = take ((length valls) - 2) valls
-                        modify $ \s -> s { stItemNum = read val }
-                        return ""
-                        else if "<ol>" `isInfixOf` str then do
-                                let olcount=countSubStrs "<ol>" str
-                                modify $ \s -> s { stIndent = stIndent s ++ replicate olcount '\t', stItemNum = 1 }
-                                return ""
-                                else if "</ol>" `isInfixOf` str then do
-                                        let olcount=countSubStrs "/<ol>" str
-                                        modify $ \s -> s{ stIndent = drop olcount (stIndent s) }
-                                        return ""
-                                        else
-                                                return ""
+   if "<li>" `T.isInfixOf` str
+      then return indent
+      else if "</li>" `T.isInfixOf` str
+        then return "\n"
+        else if "<li value=" `T.isInfixOf` str
+          then return ""
+          else if "<ol>" `T.isInfixOf` str
+            then do
+              let olcount=countSubStrs "<ol>" str
+              modify $ \s -> s { stIndent = stIndent s <>
+                                 T.replicate olcount "\t" }
+              return ""
+            else if "</ol>" `T.isInfixOf` str
+              then do
+                let olcount=countSubStrs "/<ol>" str
+                modify $ \s -> s{ stIndent = T.drop olcount (stIndent s) }
+                return ""
+              else return ""
 
-countSubStrs :: String -> String -> Int
-countSubStrs sub str = length $ breakOnAll (pack sub) (pack str)
+countSubStrs :: Text -> Text -> Int
+countSubStrs sub str = length $ T.breakOnAll sub str
 
-cleanupCode :: String -> String
-cleanupCode = substitute "<nowiki>" "" . substitute "</nowiki>" ""
+cleanupCode :: Text -> Text
+cleanupCode = T.replace "<nowiki>" "" . T.replace "</nowiki>" ""
 
-vcat :: [String] -> String
-vcat = intercalate "\n"
+vcat :: [Text] -> Text
+vcat = T.intercalate "\n"
 
 -- | Convert bullet list item (list of blocks) to ZimWiki.
-listItemToZimWiki :: PandocMonad m => WriterOptions -> [Block] -> ZW m String
+listItemToZimWiki :: PandocMonad m => WriterOptions -> [Block] -> ZW m Text
 listItemToZimWiki opts items = do
-  contents <- blockListToZimWiki opts items
   indent <- gets stIndent
-  return $ indent ++ "* " ++ contents
+  modify $ \s -> s { stIndent = indent <> "\t" }
+  contents <- blockListToZimWiki opts items
+  modify $ \s -> s{ stIndent = indent }
+  return $ indent <> "* " <> contents
 
 -- | Convert ordered list item (list of blocks) to ZimWiki.
 orderedListItemToZimWiki :: PandocMonad m
-                         => WriterOptions -> [Block] -> ZW m String
-orderedListItemToZimWiki opts items = do
-  contents <- blockListToZimWiki opts items
+                         => WriterOptions -> Int -> [Block] -> ZW m Text
+orderedListItemToZimWiki opts itemnum items = do
   indent <- gets stIndent
-  itemnum <- gets stItemNum
-  --modify $ \s -> s { stItemNum = itemnum + 1 } -- this is not strictly necessary for zim as zim does its own renumbering
-  return $ indent ++ show itemnum ++ ". " ++ contents
+  modify $ \s -> s { stIndent = indent <> "\t" }
+  contents <- blockListToZimWiki opts items
+  modify $ \s -> s{ stIndent = indent }
+  return $ indent <> T.pack (show itemnum) <> ". " <> contents
 
 -- Auxiliary functions for tables:
 tableItemToZimWiki :: PandocMonad m
-                   => WriterOptions -> Alignment -> [Block] -> ZW m String
+                   => WriterOptions -> Alignment -> [Block] -> ZW m Text
 tableItemToZimWiki opts align' item = do
   let mkcell x = (if align' == AlignRight || align' == AlignCenter
                      then "  "
-                     else "") ++ x ++
+                     else "") <> x <>
                  (if align' == AlignLeft || align' == AlignCenter
                      then "  "
                      else "")
@@ -275,45 +251,49 @@
 
 -- | Convert list of Pandoc block elements to ZimWiki.
 blockListToZimWiki :: PandocMonad m
-                   => WriterOptions -> [Block] -> ZW m String
+                   => WriterOptions -> [Block] -> ZW m Text
 blockListToZimWiki opts blocks = vcat <$> mapM (blockToZimWiki opts) blocks
 
 -- | Convert list of Pandoc inline elements to ZimWiki.
 inlineListToZimWiki :: PandocMonad m
-                    => WriterOptions -> [Inline] -> ZW m String
-inlineListToZimWiki opts lst =  concat <$> mapM (inlineToZimWiki opts) lst
+                    => WriterOptions -> [Inline] -> ZW m Text
+inlineListToZimWiki opts lst = T.concat <$> mapM (inlineToZimWiki opts) lst
 
 -- | Convert Pandoc inline element to ZimWiki.
 inlineToZimWiki :: PandocMonad m
-                => WriterOptions -> Inline -> ZW m String
+                => WriterOptions -> Inline -> ZW m Text
 
 inlineToZimWiki opts (Emph lst) = do
   contents <- inlineListToZimWiki opts lst
-  return $ "//" ++ contents ++ "//"
+  return $ "//" <> contents <> "//"
 
+inlineToZimWiki opts (Underline lst) = do
+  contents <- inlineListToZimWiki opts lst
+  return $ "__" <> contents <> "__"
+
 inlineToZimWiki opts (Strong lst) = do
   contents <- inlineListToZimWiki opts lst
-  return $ "**" ++ contents ++ "**"
+  return $ "**" <> contents <> "**"
 
 inlineToZimWiki opts (Strikeout lst) = do
   contents <- inlineListToZimWiki opts lst
-  return $ "~~" ++ contents ++ "~~"
+  return $ "~~" <> contents <> "~~"
 
 inlineToZimWiki opts (Superscript lst) = do
   contents <- inlineListToZimWiki opts lst
-  return $ "^{" ++ contents ++ "}"
+  return $ "^{" <> contents <> "}"
 
 inlineToZimWiki opts (Subscript lst) = do
   contents <- inlineListToZimWiki opts lst
-  return $ "_{" ++ contents ++ "}"
+  return $ "_{" <> contents <> "}"
 
 inlineToZimWiki opts (Quoted SingleQuote lst) = do
   contents <- inlineListToZimWiki opts lst
-  return $ "\8216" ++ contents ++ "\8217"
+  return $ "\8216" <> contents <> "\8217"
 
 inlineToZimWiki opts (Quoted DoubleQuote lst) = do
   contents <- inlineListToZimWiki opts lst
-  return $ "\8220" ++ contents ++ "\8221"
+  return $ "\8220" <> contents <> "\8221"
 
 inlineToZimWiki opts (Span _attrs ils) = inlineListToZimWiki opts ils
 
@@ -321,28 +301,28 @@
 
 inlineToZimWiki opts (Cite _  lst) = inlineListToZimWiki opts lst
 
-inlineToZimWiki _ (Code _ str) = return $ "''" ++ str ++ "''"
+inlineToZimWiki _ (Code _ str) = return $ "''" <> str <> "''"
 
 inlineToZimWiki _ (Str str) = do
   inTable <- gets stInTable
   inLink  <- gets stInLink
   if inTable
-      then return $ substitute "|" "\\|" . escapeString $ str
+      then return $ T.replace "|" "\\|" . escapeText $ str
       else
           if inLink
           then return str
-          else return $ escapeString str
+          else return $ escapeText str
 
-inlineToZimWiki _ (Math mathType str) = return $ delim ++ str ++ delim   -- note:  str should NOT be escaped
+inlineToZimWiki _ (Math mathType str) = return $ delim <> str <> delim   -- note:  str should NOT be escaped
   where delim = case mathType of
                      DisplayMath -> "$$"
                      InlineMath  -> "$"
 
--- | f == Format "html"     = return $ "<html>" ++ str ++ "</html>"
+-- f == Format "html"     = return $ "<html>" <> str <> "</html>"
 inlineToZimWiki opts il@(RawInline f str)
   | f == Format "zimwiki" = return str
-  | f == Format "html"     = indentFromHTML opts str
-  | otherwise              = do
+  | f == Format "html"    = indentFromHTML opts str
+  | otherwise             = do
       report $ InlineNotRendered il
       return ""
 
@@ -367,40 +347,39 @@
   modify $ \s -> s { stInLink = False }
   let label'= if inTable
             then "" -- no label is allowed in a table
-            else "|"++label
+            else "|"<>label
   case txt of
-     [Str s] | "mailto:" `isPrefixOf` src -> return $ "<" ++ s ++ ">"
+     [Str s] | "mailto:" `T.isPrefixOf` src -> return $ "<" <> s <> ">"
              | escapeURI s == src -> return src
      _  -> if isURI src
-              then return $ "[[" ++ src  ++ label' ++ "]]"
-              else return $ "[[" ++ src' ++ label' ++ "]]"
-                     where src' = case src of
-                                     '/':xs -> xs  -- with leading / it's a
-                                     _      -> src -- link to a help page
+              then return $ "[[" <> src  <> label' <> "]]"
+              else return $ "[[" <> src' <> label' <> "]]"
+  where
+    -- with leading / it's a link to a help page
+    src' = fromMaybe src $ T.stripPrefix "/" src
+
 inlineToZimWiki opts (Image attr alt (source, tit)) = do
   alt' <- inlineListToZimWiki opts alt
   inTable <- gets stInTable
   let txt = case (tit, alt, inTable) of
               ("",[], _)      -> ""
-              ("", _, False ) -> "|" ++ alt'
-              (_ , _, False ) -> "|" ++ tit
+              ("", _, False ) -> "|" <> alt'
+              (_ , _, False ) -> "|" <> tit
               (_ , _, True )  -> ""
-      -- Relative links fail isURI and receive a colon
-      prefix = if isURI source then "" else ":"
-  return $ "{{" ++ prefix ++ source ++ imageDims opts attr ++ txt ++ "}}"
+  return $ "{{" <> source <> imageDims opts attr <> txt <> "}}"
 
 inlineToZimWiki opts (Note contents) = do
   -- no concept of notes in zim wiki, use a text block
   contents' <- blockListToZimWiki opts contents
-  return $ " **{Note:** " ++ trimr contents' ++ "**}**"
+  return $ " **{Note:** " <> trimr contents' <> "**}**"
 
-imageDims :: WriterOptions -> Attr -> String
+imageDims :: WriterOptions -> Attr -> Text
 imageDims opts attr = go (toPx $ dimension Width attr) (toPx $ dimension Height attr)
   where
     toPx = fmap (showInPixel opts) . checkPct
     checkPct (Just (Percent _)) = Nothing
     checkPct maybeDim           = maybeDim
-    go (Just w) Nothing  = "?" ++ w
-    go (Just w) (Just h) = "?" ++ w ++ "x" ++ h
-    go Nothing  (Just h) = "?0x" ++ h
+    go (Just w) Nothing  = "?" <> w
+    go (Just w) (Just h) = "?" <> w <> "x" <> h
+    go Nothing  (Just h) = "?0x" <> h
     go Nothing  Nothing  = ""
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,24 +1,8 @@
-{-
-Copyright (C) 2006-2017 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 LambdaCase        #-}
+{-# LANGUAGE OverloadedStrings #-}
 {- |
    Module      : Text.Pandoc.XML
-   Copyright   : Copyright (C) 2006-2017 John MacFarlane
+   Copyright   : Copyright (C) 2006-2024 John MacFarlane
    License     : GNU GPL, version 2 or above
 
    Maintainer  : John MacFarlane <jgm@berkeley.edu>
@@ -29,88 +13,510 @@
 -}
 module Text.Pandoc.XML ( escapeCharForXML,
                          escapeStringForXML,
+                         escapeNCName,
                          inTags,
                          selfClosingTag,
                          inTagsSimple,
                          inTagsIndented,
                          toEntities,
-                         fromEntities ) where
+                         toHtml5Entities,
+                         fromEntities,
+                         lookupEntity,
+                         html4Attributes,
+                         html5Attributes,
+                         rdfaAttributes ) where
 
-import Data.Char (isAscii, isSpace, ord)
+import Data.Char (isAscii, isSpace, ord, isLetter, isDigit)
 import Data.Text (Text)
 import qualified Data.Text as T
-import Text.HTML.TagSoup.Entity (lookupEntity)
-import Text.Pandoc.Pretty
+import Commonmark.Entity (lookupEntity)
+import Text.HTML.TagSoup.Entity (htmlEntities)
+import Text.DocLayout
+    ( ($$), char, hcat, nest, text, Doc, HasChars )
+import Text.Printf (printf)
+import qualified Data.Map as M
+import Data.String ( IsString )
+import qualified Data.Set as Set
 
 -- | Escape one character as needed for XML.
-escapeCharForXML :: Char -> String
+escapeCharForXML :: Char -> Text
 escapeCharForXML x = case x of
                        '&' -> "&amp;"
                        '<' -> "&lt;"
                        '>' -> "&gt;"
                        '"' -> "&quot;"
-                       c   -> [c]
+                       c   -> T.singleton c
 
 -- | Escape string as needed for XML.  Entity references are not preserved.
-escapeStringForXML :: String -> String
-escapeStringForXML = concatMap escapeCharForXML
+escapeStringForXML :: Text -> Text
+escapeStringForXML = T.concatMap escapeCharForXML . T.filter isLegalXMLChar
+  where isLegalXMLChar c = c == '\t' || c == '\n' || c == '\r' ||
+                           (c >= '\x20' && c <= '\xD7FF') ||
+                           (c >= '\xE000' && c <= '\xFFFD') ||
+                           (c >= '\x10000' && c <= '\x10FFFF')
+  -- see https://www.w3.org/TR/xml/#charsets
 
 -- | Escape newline characters as &#10;
-escapeNls :: String -> String
-escapeNls (x:xs)
-  | x == '\n' = "&#10;" ++ escapeNls xs
-  | otherwise = x : escapeNls xs
-escapeNls []     = []
+escapeNls :: Text -> Text
+escapeNls = T.concatMap $ \case
+  '\n' -> "&#10;"
+  c    -> T.singleton c
 
 -- | Return a text object with a string of formatted XML attributes.
-attributeList :: [(String, String)] -> Doc
+attributeList :: (HasChars a, IsString a) => [(Text, Text)] -> Doc a
 attributeList = hcat . map
-  (\(a, b) -> text (' ' : escapeStringForXML a ++ "=\"" ++
-  escapeNls (escapeStringForXML b) ++ "\""))
+  (\(a, b) -> text (T.unpack $ " " <> escapeStringForXML a <> "=\"" <>
+  escapeNls (escapeStringForXML b) <> "\""))
 
 -- | Put the supplied contents between start and end tags of tagType,
 --   with specified attributes and (if specified) indentation.
-inTags:: Bool -> String -> [(String, String)] -> Doc -> Doc
+inTags :: (HasChars a, IsString a)
+      => Bool -> Text -> [(Text, Text)] -> Doc a -> Doc a
 inTags isIndented tagType attribs contents =
-  let openTag = char '<' <> text tagType <> attributeList attribs <>
+  let openTag = char '<' <> text (T.unpack tagType) <> attributeList attribs <>
                 char '>'
-      closeTag  = text "</" <> text tagType <> char '>'
+      closeTag  = text "</" <> text (T.unpack tagType) <> char '>'
   in  if isIndented
          then openTag $$ nest 2 contents $$ closeTag
          else openTag <> contents <> closeTag
 
 -- | Return a self-closing tag of tagType with specified attributes
-selfClosingTag :: String -> [(String, String)] -> Doc
+selfClosingTag :: (HasChars a, IsString a)
+               => Text -> [(Text, Text)] -> Doc a
 selfClosingTag tagType attribs =
-  char '<' <> text tagType <> attributeList attribs <> text " />"
+  char '<' <> text (T.unpack tagType) <> attributeList attribs <> text " />"
 
 -- | Put the supplied contents between start and end tags of tagType.
-inTagsSimple :: String -> Doc -> Doc
+inTagsSimple :: (HasChars a, IsString a)
+             => Text -> Doc a -> Doc a
 inTagsSimple tagType = inTags False tagType []
 
 -- | Put the supplied contents in indented block btw start and end tags.
-inTagsIndented :: String -> Doc -> Doc
+inTagsIndented :: (HasChars a, IsString a)
+               => Text -> Doc a -> Doc a
 inTagsIndented tagType = inTags True tagType []
 
 -- | Escape all non-ascii characters using numerical entities.
 toEntities :: Text -> Text
 toEntities = T.concatMap go
   where go c | isAscii c = T.singleton c
-             | otherwise = T.pack ("&#" ++ show (ord c) ++ ";")
+             | otherwise = T.pack (printf "&#x%X;" (ord c))
 
--- Unescapes XML entities
-fromEntities :: String -> String
-fromEntities ('&':xs) =
-  case lookupEntity ent' of
-        Just c  -> c ++ fromEntities rest
-        Nothing -> '&' : fromEntities xs
-    where (ent, rest) = case break (\c -> isSpace c || c == ';') xs of
-                             (zs,';':ys) -> (zs,ys)
-                             (zs,    ys) -> (zs,ys)
-          ent' = case ent of
-                      '#':'X':ys -> '#':'x':ys  -- workaround tagsoup bug
-                      '#':_      -> ent
-                      _          -> ent ++ ";"
+-- | Escape all non-ascii characters using HTML5 entities, falling
+-- back to numerical entities.
+toHtml5Entities :: Text -> Text
+toHtml5Entities = T.concatMap go
+  where go c | isAscii c = T.singleton c
+             | otherwise =
+                 case M.lookup c html5EntityMap of
+                   Just t  -> T.singleton '&' <> t <> T.singleton ';'
+                   Nothing -> T.pack ("&#" ++ show (ord c) ++ ";")
 
-fromEntities (x:xs) = x : fromEntities xs
-fromEntities [] = []
+html5EntityMap :: M.Map Char Text
+html5EntityMap = foldr go mempty htmlEntities
+  where go (ent, s) entmap =
+         case s of
+           [c] -> M.insertWith
+                   (\new old -> if T.length new > T.length old
+                                   then old
+                                   else new) c ent' entmap
+                  where ent' = T.takeWhile (/=';') (T.pack ent)
+           _ -> entmap
+
+-- | Converts a string into an NCName, i.e., an XML name without colons.
+-- Disallowed characters are escaped using @ux%x@, where @%x@ is the
+-- hexadecimal unicode identifier of the escaped character.
+escapeNCName :: Text -> Text
+escapeNCName t = case T.uncons t of
+  Nothing -> T.empty
+  Just (c, cs) -> escapeStartChar c <> T.concatMap escapeNCNameChar cs
+  where
+    escapeStartChar :: Char -> Text
+    escapeStartChar c = if isLetter c || c == '_'
+                        then T.singleton c
+                        else escapeChar c
+
+    escapeNCNameChar :: Char -> Text
+    escapeNCNameChar c = if isNCNameChar c
+                         then T.singleton c
+                         else escapeChar c
+
+    isNCNameChar :: Char -> Bool
+    isNCNameChar c = isLetter c || c `elem` ("_-.·" :: String) || isDigit c
+      || '\x0300' <= c && c <= '\x036f'
+      || '\x203f' <= c && c <= '\x2040'
+
+    escapeChar :: Char -> Text
+    escapeChar = T.pack . printf "U%04X" . ord
+
+-- | Unescapes XML entities
+fromEntities :: Text -> Text
+fromEntities t
+  = let (x, y) = T.break (== '&') t
+     in if T.null y
+           then t
+           else x <>
+             let (ent, rest) = T.break (\c -> isSpace c || c == ';') y
+                 rest' = case T.uncons rest of
+                            Just (';',ys) -> ys
+                            _ -> rest
+                 ent' = T.drop 1 ent <> ";"
+              in case lookupEntity ent' of
+                   Just c  -> c <> fromEntities rest'
+                   Nothing  -> ent <> fromEntities rest
+
+
+html5Attributes :: Set.Set Text
+html5Attributes = Set.fromList
+  [ "abbr"
+  , "accept"
+  , "accept-charset"
+  , "accesskey"
+  , "action"
+  , "allow"
+  , "allowfullscreen"
+  , "allowpaymentrequest"
+  , "allowusermedia"
+  , "alt"
+  , "as"
+  , "async"
+  , "autocapitalize"
+  , "autocomplete"
+  , "autofocus"
+  , "autoplay"
+  , "charset"
+  , "checked"
+  , "cite"
+  , "class"
+  , "color"
+  , "cols"
+  , "colspan"
+  , "content"
+  , "contenteditable"
+  , "controls"
+  , "coords"
+  , "crossorigin"
+  , "data"
+  , "datetime"
+  , "decoding"
+  , "default"
+  , "defer"
+  , "dir"
+  , "dirname"
+  , "disabled"
+  , "download"
+  , "draggable"
+  , "enctype"
+  , "enterkeyhint"
+  , "fetchpriority"
+  , "for"
+  , "form"
+  , "formaction"
+  , "formenctype"
+  , "formmethod"
+  , "formnovalidate"
+  , "formtarget"
+  , "headers"
+  , "height"
+  , "hidden"
+  , "high"
+  , "href"
+  , "hreflang"
+  , "http-equiv"
+  , "id"
+  , "imagesizes"
+  , "imagesrcset"
+  , "inputmode"
+  , "integrity"
+  , "is"
+  , "ismap"
+  , "itemid"
+  , "itemprop"
+  , "itemref"
+  , "itemscope"
+  , "itemtype"
+  , "kind"
+  , "label"
+  , "lang"
+  , "list"
+  , "loading"
+  , "loop"
+  , "low"
+  , "manifest"
+  , "max"
+  , "maxlength"
+  , "media"
+  , "method"
+  , "min"
+  , "minlength"
+  , "multiple"
+  , "muted"
+  , "name"
+  , "nomodule"
+  , "nonce"
+  , "novalidate"
+  , "onabort"
+  , "onafterprint"
+  , "onauxclick"
+  , "onbeforeprint"
+  , "onbeforeunload"
+  , "onblur"
+  , "oncancel"
+  , "oncanplay"
+  , "oncanplaythrough"
+  , "onchange"
+  , "onclick"
+  , "onclose"
+  , "oncontextmenu"
+  , "oncopy"
+  , "oncuechange"
+  , "oncut"
+  , "ondblclick"
+  , "ondrag"
+  , "ondragend"
+  , "ondragenter"
+  , "ondragexit"
+  , "ondragleave"
+  , "ondragover"
+  , "ondragstart"
+  , "ondrop"
+  , "ondurationchange"
+  , "onemptied"
+  , "onended"
+  , "onerror"
+  , "onfocus"
+  , "onhashchange"
+  , "oninput"
+  , "oninvalid"
+  , "onkeydown"
+  , "onkeypress"
+  , "onkeyup"
+  , "onlanguagechange"
+  , "onload"
+  , "onloadeddata"
+  , "onloadedmetadata"
+  , "onloadend"
+  , "onloadstart"
+  , "onmessage"
+  , "onmessageerror"
+  , "onmousedown"
+  , "onmouseenter"
+  , "onmouseleave"
+  , "onmousemove"
+  , "onmouseout"
+  , "onmouseover"
+  , "onmouseup"
+  , "onoffline"
+  , "ononline"
+  , "onpagehide"
+  , "onpageshow"
+  , "onpaste"
+  , "onpause"
+  , "onplay"
+  , "onplaying"
+  , "onpopstate"
+  , "onprogress"
+  , "onratechange"
+  , "onrejectionhandled"
+  , "onreset"
+  , "onresize"
+  , "onscroll"
+  , "onsecuritypolicyviolation"
+  , "onseeked"
+  , "onseeking"
+  , "onselect"
+  , "onstalled"
+  , "onstorage"
+  , "onsubmit"
+  , "onsuspend"
+  , "ontimeupdate"
+  , "ontoggle"
+  , "onunhandledrejection"
+  , "onunload"
+  , "onvolumechange"
+  , "onwaiting"
+  , "onwheel"
+  , "open"
+  , "optimum"
+  , "pattern"
+  , "ping"
+  , "placeholder"
+  , "playsinline"
+  , "poster"
+  , "preload"
+  , "readonly"
+  , "referrerpolicy"
+  , "rel"
+  , "required"
+  , "reversed"
+  , "role"
+  , "rows"
+  , "rowspan"
+  , "sandbox"
+  , "scope"
+  , "selected"
+  , "shape"
+  , "size"
+  , "sizes"
+  , "slot"
+  , "span"
+  , "spellcheck"
+  , "src"
+  , "srcdoc"
+  , "srclang"
+  , "srcset"
+  , "start"
+  , "step"
+  , "style"
+  , "tabindex"
+  , "target"
+  , "title"
+  , "translate"
+  , "type"
+  , "typemustmatch"
+  , "updateviacache"
+  , "usemap"
+  , "value"
+  , "width"
+  , "workertype"
+  , "wrap"
+  ]
+
+-- See https://en.wikipedia.org/wiki/RDFa, https://www.w3.org/TR/rdfa-primer/
+rdfaAttributes :: Set.Set Text
+rdfaAttributes = Set.fromList
+  [ "about"
+  , "rel"
+  , "rev"
+  , "src"
+  , "href"
+  , "resource"
+  , "property"
+  , "content"
+  , "datatype"
+  , "typeof"
+  , "vocab"
+  , "prefix"
+  ]
+
+html4Attributes :: Set.Set Text
+html4Attributes = Set.fromList
+  [ "abbr"
+  , "accept"
+  , "accept-charset"
+  , "accesskey"
+  , "action"
+  , "align"
+  , "alink"
+  , "alt"
+  , "archive"
+  , "axis"
+  , "background"
+  , "bgcolor"
+  , "border"
+  , "cellpadding"
+  , "cellspacing"
+  , "char"
+  , "charoff"
+  , "charset"
+  , "checked"
+  , "cite"
+  , "class"
+  , "classid"
+  , "clear"
+  , "code"
+  , "codebase"
+  , "codetype"
+  , "color"
+  , "cols"
+  , "colspan"
+  , "compact"
+  , "content"
+  , "coords"
+  , "data"
+  , "datetime"
+  , "declare"
+  , "defer"
+  , "dir"
+  , "disabled"
+  , "enctype"
+  , "face"
+  , "for"
+  , "frame"
+  , "frameborder"
+  , "headers"
+  , "height"
+  , "href"
+  , "hreflang"
+  , "hspace"
+  , "http-equiv"
+  , "id"
+  , "ismap"
+  , "label"
+  , "lang"
+  , "language"
+  , "link"
+  , "longdesc"
+  , "marginheight"
+  , "marginwidth"
+  , "maxlength"
+  , "media"
+  , "method"
+  , "multiple"
+  , "name"
+  , "nohref"
+  , "noresize"
+  , "noshade"
+  , "nowrap"
+  , "object"
+  , "onblur"
+  , "onchange"
+  , "onclick"
+  , "ondblclick"
+  , "onfocus"
+  , "onkeydown"
+  , "onkeypress"
+  , "onkeyup"
+  , "onload"
+  , "onmousedown"
+  , "onmousemove"
+  , "onmouseout"
+  , "onmouseover"
+  , "onmouseup"
+  , "onreset"
+  , "onselect"
+  , "onsubmit"
+  , "onunload"
+  , "profile"
+  , "prompt"
+  , "readonly"
+  , "rel"
+  , "rev"
+  , "rows"
+  , "rowspan"
+  , "rules"
+  , "scheme"
+  , "scope"
+  , "scrolling"
+  , "selected"
+  , "shape"
+  , "size"
+  , "span"
+  , "src"
+  , "standby"
+  , "start"
+  , "style"
+  , "summary"
+  , "tabindex"
+  , "target"
+  , "text"
+  , "title"
+  , "usemap"
+  , "valign"
+  , "value"
+  , "valuetype"
+  , "version"
+  , "vlink"
+  , "vspace"
+  , "width"
+  ]
diff --git a/src/Text/Pandoc/XMLFormat.hs b/src/Text/Pandoc/XMLFormat.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/XMLFormat.hs
@@ -0,0 +1,188 @@
+{-# LANGUAGE OverloadedStrings #-}
+{-# LANGUAGE ScopedTypeVariables #-}
+
+module Text.Pandoc.XMLFormat
+  ( atNameAlignment,
+    atNameApiVersion,
+    atNameCitationHash,
+    atNameCitationMode,
+    atNameCitationNoteNum,
+    atNameColspan,
+    atNameColWidth,
+    atNameFormat,
+    atNameImageUrl,
+    atNameLevel,
+    atNameLinkUrl,
+    atNameMathType,
+    atNameMetaBoolValue,
+    atNameMetaMapEntryKey,
+    atNameNumberDelim,
+    atNameNumberStyle,
+    atNameQuoteType,
+    atNameRowHeadColumns,
+    atNameRowspan,
+    atNameSpaceCount,
+    atNameStart,
+    atNameStrContent,
+    atNameTitle,
+    tgNameBodyBody,
+    tgNameBodyHeader,
+    tgNameCitations,
+    tgNameCitationPrefix,
+    tgNameCitationSuffix,
+    tgNameColspecs,
+    tgNameDefListDef,
+    tgNameDefListItem,
+    tgNameDefListTerm,
+    tgNameLineItem,
+    tgNameListItem,
+    tgNameMetaMapEntry,
+    tgNameShortCaption,
+  )
+where
+
+import Data.Text (Text)
+
+-- the attribute carrying the API version of pandoc types in the main Pandoc element
+atNameApiVersion :: Text
+atNameApiVersion = "api-version"
+
+-- the element of a <meta> or <MetaMap> entry
+tgNameMetaMapEntry :: Text
+tgNameMetaMapEntry = "entry"
+
+-- the attribute carrying the key name of a <meta> or <MetaMap> entry
+atNameMetaMapEntryKey :: Text
+atNameMetaMapEntryKey = "key"
+
+-- the attribute carrying the boolean value ("true" or "false") of a MetaBool
+atNameMetaBoolValue :: Text
+atNameMetaBoolValue = "value"
+
+-- level of a Header
+atNameLevel :: Text
+atNameLevel = "level"
+
+-- start number of an OrderedList
+atNameStart :: Text
+atNameStart = "start"
+
+-- number delimiter of an OrderedList
+atNameNumberDelim :: Text
+atNameNumberDelim = "number-delim"
+
+-- number style of an OrderedList
+atNameNumberStyle :: Text
+atNameNumberStyle = "number-style"
+
+-- target title in Image and Link
+atNameTitle :: Text
+atNameTitle = "title"
+
+-- target url in Image
+atNameImageUrl :: Text
+atNameImageUrl = "src"
+
+-- target url in Link
+atNameLinkUrl :: Text
+atNameLinkUrl = "href"
+
+-- QuoteType of a Quoted
+atNameQuoteType :: Text
+atNameQuoteType = "quote-type"
+
+-- MathType of a Math
+atNameMathType :: Text
+atNameMathType = "math-type"
+
+-- format of a RawInline or a RawBlock
+atNameFormat :: Text
+atNameFormat = "format"
+
+-- alignment attribute in a ColSpec or in a Cell
+atNameAlignment :: Text
+atNameAlignment = "alignment"
+
+-- ColWidth attribute in a ColSpec
+atNameColWidth :: Text
+atNameColWidth = "col-width"
+
+-- RowHeadColumns attribute in a TableBody
+atNameRowHeadColumns :: Text
+atNameRowHeadColumns = "row-head-columns"
+
+-- RowSpan attribute in a Cell
+atNameRowspan :: Text
+atNameRowspan = "row-span"
+
+-- ColSpan attribute in a Cell
+atNameColspan :: Text
+atNameColspan = "col-span"
+
+-- the citationMode of a Citation
+atNameCitationMode :: Text
+atNameCitationMode = "mode"
+
+-- the citationHash of a Citation
+atNameCitationHash :: Text
+atNameCitationHash = "hash"
+
+-- the citationNoteNum of a Citation
+atNameCitationNoteNum :: Text
+atNameCitationNoteNum = "note-num"
+
+-- the number of consecutive spaces of the <Space> element
+atNameSpaceCount :: Text
+atNameSpaceCount = "count"
+
+-- the content of the <Str> element
+atNameStrContent :: Text
+atNameStrContent = "content"
+
+-- container of Citation elements in Cite inlines
+tgNameCitations :: Text
+tgNameCitations = "citations"
+
+-- element around the prefix inlines of a Citation
+tgNameCitationPrefix :: Text
+tgNameCitationPrefix = "prefix"
+
+-- element around the suffix inlines of a Citation
+tgNameCitationSuffix :: Text
+tgNameCitationSuffix = "suffix"
+
+-- list item for BulletList and OrderedList
+tgNameListItem :: Text
+tgNameListItem = "item"
+
+-- list item for DefinitionList
+tgNameDefListItem :: Text
+tgNameDefListItem = "item"
+
+-- element around the inlines of the term of a DefinitionList item
+tgNameDefListTerm :: Text
+tgNameDefListTerm = "term"
+
+-- element around the blocks of a definition in a DefinitionList item
+tgNameDefListDef :: Text
+tgNameDefListDef = "def"
+
+-- optional element of the ShortCaption
+tgNameShortCaption :: Text
+tgNameShortCaption = "ShortCaption"
+
+-- element around the ColSpec of a Table
+tgNameColspecs :: Text
+tgNameColspecs = "colspecs"
+
+-- element around the header rows of a TableBody
+tgNameBodyHeader :: Text
+tgNameBodyHeader = "header"
+
+-- element around the body rows of a TableBody
+tgNameBodyBody :: Text
+tgNameBodyBody = "body"
+
+-- element around the inlines of a line in a LineBlock
+tgNameLineItem :: Text
+tgNameLineItem = "line"
diff --git a/stack.yaml b/stack.yaml
deleted file mode 100644
--- a/stack.yaml
+++ /dev/null
@@ -1,16 +0,0 @@
-flags:
-  pandoc:
-    trypandoc: false
-    embed_data_files: true
-    old-locale: false
-    network-uri: true
-  pandoc-citeproc:
-    bibutils: true
-    embed_data_files: true
-    unicode_collation: false
-    test_citeproc: false
-    debug: false
-packages:
-- '.'
-extra-deps: []
-resolver: lts-10.1
diff --git a/test/Tests/Command.hs b/test/Tests/Command.hs
--- a/test/Tests/Command.hs
+++ b/test/Tests/Command.hs
@@ -1,62 +1,89 @@
-module Tests.Command (findPandoc, runTest, tests)
+{-# LANGUAGE BangPatterns #-}
+{- |
+   Module      : Tests.Command
+   Copyright   : © 2006-2024 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.
+
+A command test is a code block with the following format:
+
+> ```
+> % pandoc -f markdown -t latex
+> *hi*
+> ^D
+> \emph{hi}
+> ```
+
+- The first line, after "%", should contain a command to run.
+- Then comes zero or more lines of text which will be passed
+  to the command as stdin.
+- The stdin terminates with a line containing "^D".
+- The following lines are typically the expected output
+  on stdout.
+- If any output on stderr is expected, it should come first
+  and each stderr line should be preceded by the string "2> ".
+- If a nonzero exit status is expected, the last line should
+  contain "=> " followed by the exit status.
+
+-}
+module Tests.Command (tests)
 where
 
+import Data.Maybe (fromMaybe)
 import Data.Algorithm.Diff
+import System.Environment (getExecutablePath)
 import qualified Data.ByteString as BS
+import qualified Data.Text as T
 import Data.List (isSuffixOf)
-import Prelude hiding (readFile)
 import System.Directory
 import System.Exit
-import System.FilePath (joinPath, splitDirectories, takeDirectory, (</>))
-import System.IO (hPutStr, stderr)
+import System.FilePath ((</>))
 import System.IO.Unsafe (unsafePerformIO)
 import System.Process
 import Test.Tasty
 import Test.Tasty.HUnit
+import Test.Tasty.Golden.Advanced (goldenTest)
 import Tests.Helpers
 import Text.Pandoc
 import qualified Text.Pandoc.UTF8 as UTF8
 
--- | Run a test with normalize function, return True if test passed.
-runTest :: String    -- ^ Title of test
-        -> FilePath  -- ^ Path to pandoc
-        -> String    -- ^ Shell command
-        -> String    -- ^ Input text
-        -> String    -- ^ Expected output
-        -> TestTree
-runTest testname pandocpath cmd inp norm = testCase testname $ do
-  let findDynlibDir []           = Nothing
-      findDynlibDir ("build":xs) = Just $ joinPath (reverse xs) </> "build"
-      findDynlibDir (_:xs)       = findDynlibDir xs
-  let mbDynlibDir = findDynlibDir (reverse $ splitDirectories $
-                                   takeDirectory $ takeWhile (/=' ') cmd)
-  let dynlibEnv = case mbDynlibDir of
-                       Nothing  -> []
-                       Just d   -> [("DYLD_LIBRARY_PATH", d),
-                                    ("LD_LIBRARY_PATH", d)]
-  let env' = dynlibEnv ++ [("PATH",takeDirectory pandocpath),("TMP","."),("LANG","en_US.UTF-8"),("HOME", "./"),("pandoc_datadir", "..")]
-  let pr = (shell cmd){ env = Just env' }
-  (ec, out', err') <- readCreateProcessWithExitCode pr inp
+-- | Run a test with and return output.
+execTest :: String    -- ^ Path to test executable
+         -> String    -- ^ Shell command
+         -> String    -- ^ Input text
+         -> IO (ExitCode, String)  -- ^ Exit code and actual output
+execTest testExePath cmd inp = do
+  env' <- setupEnvironment testExePath
+  let pr = (shell (pandocToEmulate True cmd)){ env = Just env' }
+  (!ec, out', err') <- readCreateProcessWithExitCode pr inp
+  let err = unlines . map ("2> " ++) . lines $ err'
   -- filter \r so the tests will work on Windows machines
-  let out = filter (/= '\r') $ err' ++ out'
-  result  <- if ec == ExitSuccess
-                then do
-                  if out == norm
-                     then return TestPassed
-                     else return
-                          $ TestFailed cmd "expected"
-                          $ getDiff (lines out) (lines norm)
-                else do
-                  hPutStr stderr err'
-                  return $ TestError ec
-  assertBool (show result) (result == TestPassed)
+  let out'' = filter (/= '\r') $ err ++ out'
+  let out = out'' ++ case ec of
+                        ExitFailure !n -> "=> " ++ show n ++ "\n"
+                        ExitSuccess    -> ""
+  return (ec, out)
 
+pandocToEmulate :: Bool -> String -> String
+pandocToEmulate True ('p':'a':'n':'d':'o':'c':cs) =
+  "test-pandoc --emulate" ++ pandocToEmulate False cs
+pandocToEmulate False ('|':' ':'p':'a':'n':'d':'o':'c':cs) =
+  "| " ++ "test-pandoc --emulate" ++ pandocToEmulate False cs
+pandocToEmulate _ (c:cs) = c : pandocToEmulate False cs
+pandocToEmulate _ [] = []
+
 tests :: TestTree
+{-# NOINLINE tests #-}
 tests = unsafePerformIO $ do
-  pandocpath <- findPandoc
   files <- filter (".md" `isSuffixOf`) <$>
                getDirectoryContents "command"
-  let cmds = map (extractCommandTest pandocpath) files
+  testExePath <- getExecutablePath
+  let cmds = map (extractCommandTest testExePath) files
   return $ testGroup "Command:" cmds
 
 isCodeBlock :: Block -> Bool
@@ -64,32 +91,51 @@
 isCodeBlock _               = False
 
 extractCode :: Block -> String
-extractCode (CodeBlock _ code) = code
+extractCode (CodeBlock _ code) = T.unpack code
 extractCode _                  = ""
 
-dropPercent :: String -> String
-dropPercent ('%':xs) = dropWhile (== ' ') xs
-dropPercent xs       = xs
+dropPercent :: String -> Maybe String
+dropPercent ('%':xs) = Just $ dropWhile (== ' ') xs
+dropPercent _        = Nothing
 
-runCommandTest :: FilePath -> (Int, String) -> TestTree
-runCommandTest pandocpath (num, code) =
-  let codelines = lines code
-      (continuations, r1) = span ("\\" `isSuffixOf`) codelines
-      (cmd, r2) = (dropPercent (unwords (map init continuations ++ take 1 r1)),
-                   drop 1 r1)
-      (inplines, r3) = break (=="^D") r2
-      normlines = takeWhile (/=".") (drop 1 r3)
-      input = unlines inplines
-      norm = unlines normlines
-      shcmd = cmd -- trimr $ takeDirectory pandocpath </> cmd
-  in  runTest ("#" ++ show num) pandocpath shcmd input norm
+runCommandTest :: FilePath -> FilePath -> Int -> String -> TestTree
+runCommandTest testExePath fp num code = do
+  goldenTest testname getExpected getActual compareValues' updateGolden
+ where
+  testname = "#" <> show num
+  codelines = lines code
+  (continuations, r1) = span ("\\" `isSuffixOf`) codelines
+  cmd = fromMaybe (error "Command test line does not begin with %")
+            (dropPercent (unwords (map init continuations ++ take 1 r1)))
+  r2 = drop 1 r1
+  (inplines, r3) = break (=="^D") r2
+  normlines = takeWhile (/=".") (drop 1 r3)
+  input = unlines inplines
+  norm = unlines normlines
+  getExpected = return norm
+  getActual = snd <$> execTest testExePath cmd input
+  compareValues' expected actual
+    | actual == expected = return Nothing
+    | otherwise = return $ Just $ "--- test/command/" ++ fp ++ "\n+++ " ++
+                                cmd ++ "\n" ++ showDiff (1,1)
+                                   (getDiff (lines actual) (lines expected))
+  updateGolden newnorm = do
+    let fp' = "command" </> fp
+    raw <- UTF8.readFile fp'
+    let cmdline = "% " <> cmd
+    let x = cmdline <> "\n" <> input <> "^D\n" <> norm
+    let y = cmdline <> "\n" <> input <> "^D\n" <> newnorm
+    let updated = T.replace (T.pack x) (T.pack y) raw
+    UTF8.writeFile fp' updated
 
 extractCommandTest :: FilePath -> FilePath -> TestTree
-extractCommandTest pandocpath fp = unsafePerformIO $ do
+extractCommandTest testExePath fp = unsafePerformIO $ do
   contents <- UTF8.toText <$> BS.readFile ("command" </> fp)
   Pandoc _ blocks <- runIOorExplode (readMarkdown
                         def{ readerExtensions = pandocExtensions } contents)
-  let codeblocks = map extractCode $ filter isCodeBlock $ blocks
-  let cases = map (runCommandTest pandocpath) $ zip [1..] codeblocks
-  return $ testGroup fp cases
-
+  let codeblocks = map extractCode $ filter isCodeBlock blocks
+  let cases = zipWith (runCommandTest testExePath fp) [1..] codeblocks
+  return $ testGroup fp
+         $ if null cases
+              then [testCase "!!" $ assertFailure "No command tests defined"]
+              else cases
diff --git a/test/Tests/Helpers.hs b/test/Tests/Helpers.hs
--- a/test/Tests/Helpers.hs
+++ b/test/Tests/Helpers.hs
@@ -1,11 +1,23 @@
+{-# LANGUAGE CPP #-}
+{-# LANGUAGE TupleSections #-}
 {-# LANGUAGE FlexibleInstances    #-}
-{-# LANGUAGE TypeSynonymInstances #-}
--- Utility functions for the test suite.
+{- |
+   Module      : Tests.Helpers
+   Copyright   : © 2006-2024 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(..)
+                     , setupEnvironment
                      , showDiff
-                     , findPandoc
+                     , nativeDiff
+                     , testGolden
                      , (=?>)
                      , purely
                      , ToString(..)
@@ -13,16 +25,19 @@
                      )
                      where
 
+import System.FilePath
 import Data.Algorithm.Diff
 import qualified Data.Map as M
+import qualified Text.Pandoc.UTF8 as UTF8
 import Data.Text (Text, unpack)
-import System.Directory
-import System.Environment.Executable (getExecutablePath)
+import qualified Data.Text as T
 import System.Exit
-import System.FilePath
+import qualified System.Environment as Env
 import Test.Tasty
+import Test.Tasty.Golden.Advanced (goldenTest)
 import Test.Tasty.HUnit
 import Text.Pandoc.Builder (Blocks, Inlines, doc, plain)
+import qualified Text.Pandoc.Builder as B
 import Text.Pandoc.Class
 import Text.Pandoc.Definition
 import Text.Pandoc.Options
@@ -30,7 +45,7 @@
 import Text.Pandoc.Writers.Native (writeNative)
 import Text.Printf
 
-test :: (ToString a, ToString b, ToString c)
+test :: (ToString a, ToString b, ToString c, HasCallStack)
      => (a -> b)  -- ^ function to test
      -> String    -- ^ name of test case
      -> (a, c)    -- ^ (input, expected value)
@@ -52,6 +67,44 @@
            dashes "" = replicate 72 '-'
            dashes x  = replicate (72 - length x - 5) '-' ++ " " ++ x ++ " ---"
 
+testGolden :: TestName -> FilePath -> FilePath -> (Text -> IO Text) -> TestTree
+testGolden  name expectedPath inputPath fn =
+  goldenTest
+    name
+    (UTF8.readFile expectedPath)
+    (UTF8.readFile inputPath >>= fn)
+    compareVals
+    (UTF8.writeFile expectedPath)
+ where
+  compareVals expected actual
+    | expected == actual = return Nothing
+    | otherwise =  return $ Just $
+        "\n--- " ++ expectedPath ++ "\n+++\n" ++
+        showDiff (1,1)
+          (getDiff (lines . filter (/='\r') $ T.unpack actual)
+                   (lines . filter (/='\r') $ T.unpack expected))
+
+-- | Set up environment for pandoc command tests.
+setupEnvironment :: FilePath -> IO [(String, String)]
+setupEnvironment testExePath = do
+  mldpath   <- Env.lookupEnv "LD_LIBRARY_PATH"
+  mdyldpath <- Env.lookupEnv "DYLD_LIBRARY_PATH"
+  mpdd <- Env.lookupEnv "pandoc_datadir"
+  mbpath <- Env.lookupEnv "PATH"
+  -- Note that Cabal sets the pandoc_datadir environment variable
+  -- to point to the source directory, since otherwise getDataFilename
+  -- will look in the data directory into which pandoc will be installed
+  -- (but has not yet been).  So when we spawn a new process with
+  -- pandoc, we need to make sure this environment variable is set.
+  return $ ("PATH",takeDirectory testExePath <>
+                    maybe mempty (searchPathSeparator:) mbpath) :
+           ("TMP",".") :
+           ("LANG","en_US.UTF-8") :
+           ("HOME", "./") :
+           maybe [] ((:[]) . ("pandoc_datadir",)) mpdd ++
+           maybe [] ((:[]) . ("LD_LIBRARY_PATH",)) mldpath ++
+           maybe [] ((:[]) . ("DYLD_LIBRARY_PATH",)) mdyldpath
+
 data TestResult = TestPassed
                 | TestError ExitCode
                 | TestFailed String FilePath [Diff String]
@@ -75,26 +128,24 @@
 showDiff (l,r) (Both _ _ : ds) =
   showDiff (l+1,r+1) ds
 
--- | Find pandoc executable relative to test-pandoc
--- First, try in same directory (e.g. if both in ~/.cabal/bin)
--- Second, try ../pandoc (e.g. if in dist/XXX/build/test-pandoc)
-findPandoc :: IO FilePath
-findPandoc = do
-  testExePath <- getExecutablePath
-  let testExeDir = takeDirectory testExePath
-  found <- doesFileExist (testExeDir </> "pandoc")
-  return $ if found
-              then testExeDir </> "pandoc"
-              else case splitDirectories testExeDir of
-                         [] -> error "test-pandoc: empty testExeDir"
-                         xs -> joinPath (init xs) </> "pandoc" </> "pandoc"
-
-
 vividize :: Diff String -> String
 vividize (Both s _) = "  " ++ s
 vividize (First s)  = "- " ++ s
 vividize (Second s) = "+ " ++ s
 
+nativeDiff :: FilePath -> Pandoc -> Pandoc -> IO (Maybe String)
+nativeDiff normPath expectedNative actualNative
+  | expectedNative == actualNative = return Nothing
+  | otherwise = Just <$> do
+      expected <- T.unpack <$> runIOorExplode (writeNative def expectedNative)
+      actual <- T.unpack <$> runIOorExplode (writeNative def actualNative)
+      let dash = replicate 72 '-'
+      let diff = getDiff (lines actual) (lines expected)
+      return $ '\n' : dash ++
+               "\n--- " ++ normPath ++
+               "\n+++ " ++ "test" ++ "\n" ++
+               showDiff (1,1) diff ++ dash
+
 purely :: (b -> PandocPure a) -> b -> a
 purely f = either (error . show) id . runPure . f
 
@@ -111,13 +162,19 @@
    where s = case d of
                   (Pandoc (Meta m) _)
                     | M.null m  -> Nothing
-                    | otherwise -> Just "" -- need this to get meta output
+                    | otherwise -> Just mempty -- need this to get meta output
 
 instance ToString Blocks where
   toString = unpack . purely (writeNative def) . toPandoc
 
+instance ToString [Block] where
+  toString = toString . B.fromList
+
+instance ToString Block where
+  toString = toString . B.singleton
+
 instance ToString Inlines where
-  toString = trimr . unpack . purely (writeNative def) . toPandoc
+  toString = unpack . trimr . purely (writeNative def) . toPandoc
 
 instance ToString String where
   toString = id
diff --git a/test/Tests/Lua.hs b/test/Tests/Lua.hs
deleted file mode 100644
--- a/test/Tests/Lua.hs
+++ /dev/null
@@ -1,138 +0,0 @@
-{-# LANGUAGE OverloadedStrings #-}
-module Tests.Lua ( tests ) where
-
-import Control.Monad (when)
-import System.FilePath ((</>))
-import Test.Tasty (TestTree, localOption)
-import Test.Tasty.HUnit (Assertion, assertEqual, testCase)
-import Test.Tasty.QuickCheck (QuickCheckTests (..), ioProperty, testProperty)
-import Text.Pandoc.Arbitrary ()
-import Text.Pandoc.Builder (bulletList, divWith, doc, doubleQuoted, emph,
-                            header, linebreak, para, plain, rawBlock,
-                            singleQuoted, space, str, strong, (<>))
-import Text.Pandoc.Class (runIOorExplode, setUserDataDir)
-import Text.Pandoc.Definition (Block, Inline, Meta, Pandoc)
-import Text.Pandoc.Lua (runLuaFilter, runPandocLua)
-
-import qualified Foreign.Lua as Lua
-
-tests :: [TestTree]
-tests = map (localOption (QuickCheckTests 20))
-  [ testProperty "inline elements can be round-tripped through the lua stack" $
-    \x -> ioProperty (roundtripEqual (x::Inline))
-
-  , testProperty "block elements can be round-tripped through the lua stack" $
-    \x -> ioProperty (roundtripEqual (x::Block))
-
-  , testProperty "meta blocks can be round-tripped through the lua stack" $
-    \x -> ioProperty (roundtripEqual (x::Meta))
-
-  , testProperty "documents can be round-tripped through the lua stack" $
-    \x -> ioProperty (roundtripEqual (x::Pandoc))
-
-  , testCase "macro expansion via filter" $
-    assertFilterConversion "a '{{helloworld}}' string is expanded"
-      "strmacro.lua"
-      (doc . para $ str "{{helloworld}}")
-      (doc . para . emph $ str "Hello, World")
-
-  , testCase "convert all plains to paras" $
-    assertFilterConversion "plains become para"
-      "plain-to-para.lua"
-      (doc $ bulletList [plain (str "alfa"), plain (str "bravo")])
-      (doc $ bulletList [para (str "alfa"), para (str "bravo")])
-
-  , testCase "make hello world document" $
-    assertFilterConversion "Document contains 'Hello, World!'"
-      "hello-world-doc.lua"
-      (doc . para $ str "Hey!" <> linebreak <> str "What's up?")
-      (doc . para $ str "Hello," <> space <> str "World!")
-
-  , testCase "implicit doc filter" $
-    assertFilterConversion "Document contains 'Hello, World!'"
-      "implicit-doc-filter.lua"
-      (doc . plain $ linebreak)
-      (doc . para $ str "Hello," <> space <> str "World!")
-
-  , testCase "parse raw markdown blocks" $
-    assertFilterConversion "raw markdown block is converted"
-      "markdown-reader.lua"
-      (doc $ rawBlock "markdown" "*charly* **delta**")
-      (doc . para $ emph "charly" <> space <> strong "delta")
-
-  , testCase "allow shorthand functions for quote types" $
-    assertFilterConversion "single quoted becomes double quoted string"
-      "single-to-double-quoted.lua"
-      (doc . para . singleQuoted $ str "simple")
-      (doc . para . doubleQuoted $ str "simple")
-
-  , testCase "Count inlines via metatable catch-all" $
-    assertFilterConversion "filtering with metatable catch-all failed"
-      "metatable-catch-all.lua"
-      (doc . para $ "four words, three spaces")
-      (doc . para $ str "7")
-
-  , testCase "Count blocks via Block-specific catch-all" $
-    assertFilterConversion "filtering with Block catch-all failed"
-      "block-count.lua"
-      (doc $ para "one" <> para "two")
-      (doc $ para "2")
-
-  , testCase "Convert header upper case" $
-    assertFilterConversion "converting header to upper case failed"
-      "uppercase-header.lua"
-      (doc $ header 1 "les états-unis" <> para "text")
-      (doc $ header 1 "LES ÉTATS-UNIS" <> para "text")
-
-  , testCase "Attribute lists are convenient to use" $
-    let kv_before = [("one", "1"), ("two", "2"), ("three", "3")]
-        kv_after  = [("one", "eins"), ("three", "3"), ("five", "5")]
-    in assertFilterConversion "Attr doesn't behave as expected"
-      "attr-test.lua"
-      (doc $ divWith ("", [], kv_before) (para "nil"))
-      (doc $ divWith ("", [], kv_after) (para "nil"))
-
-  , testCase "Test module pandoc.utils" $
-    assertFilterConversion "pandoc.utils doesn't work as expected."
-      "test-pandoc-utils.lua"
-      (doc $ para "doesn't matter")
-      (doc $ mconcat [ plain (str "hierarchicalize: OK")
-                     , plain (str "normalize_date: OK")
-                     , plain (str "pipe: OK")
-                     , plain (str "failing pipe: OK")
-                     , plain (str "read: OK")
-                     , plain (str "failing read: OK")
-                     , plain (str "sha1: OK")
-                     , plain (str "stringify: OK")
-                     , plain (str "to_roman_numeral: OK")
-                     ])
-  ]
-
-assertFilterConversion :: String -> FilePath -> Pandoc -> Pandoc -> Assertion
-assertFilterConversion msg filterPath docIn docExpected = do
-  docEither <- runIOorExplode $ do
-    setUserDataDir (Just "../data")
-    runLuaFilter ("lua" </> filterPath) [] docIn
-  case docEither of
-    Left _       -> fail "lua filter failed"
-    Right docRes -> assertEqual msg docExpected docRes
-
-roundtripEqual :: (Eq a, Lua.FromLuaStack a, Lua.ToLuaStack a) => a -> IO Bool
-roundtripEqual x = (x ==) <$> roundtripped
- where
-  roundtripped :: (Lua.FromLuaStack a, Lua.ToLuaStack a) => IO a
-  roundtripped = runIOorExplode $ do
-    setUserDataDir (Just "../data")
-    res <- runPandocLua $ do
-      oldSize <- Lua.gettop
-      Lua.push x
-      size <- Lua.gettop
-      when (size - oldSize /= 1) $
-        error ("not exactly one additional element on the stack: " ++ show size)
-      res <- Lua.peekEither (-1)
-      case res of
-        Left _  -> error "could not read from stack"
-        Right y -> return y
-    case res of
-      Left e -> error (show e)
-      Right y -> return y
diff --git a/test/Tests/MediaBag.hs b/test/Tests/MediaBag.hs
new file mode 100644
--- /dev/null
+++ b/test/Tests/MediaBag.hs
@@ -0,0 +1,56 @@
+{-# LANGUAGE OverloadedStrings #-}
+module Tests.MediaBag (tests) where
+
+import Test.Tasty
+import Test.Tasty.HUnit
+-- import Tests.Helpers
+import Text.Pandoc.Class.IO (extractMedia)
+import Text.Pandoc.Class (fillMediaBag, runIOorExplode)
+import System.IO.Temp (withTempDirectory)
+import System.FilePath
+import Text.Pandoc.Builder as B
+import qualified Data.Text as T
+import System.Directory (doesFileExist, makeAbsolute)
+
+tests :: [TestTree]
+tests = [
+  testCase "test fillMediaBag & extractMedia" $
+      withTempDirectory "." "extractMediaTest" $ \tmpdir -> do
+        -- Use absolute paths so the test does not need to change
+        -- the process-wide current directory (which is not thread-safe
+        -- and breaks other tests running in parallel).
+        absTmpdir <- makeAbsolute tmpdir
+        absLalune <- makeAbsolute "lalune.jpg"
+        let d = B.doc $
+                  -- simple relative path -> extracted with original name
+                  B.para (B.image "lalune.jpg" "" mempty) <>
+                  -- absolute path -> extracted with hashed name
+                  B.para (B.image (T.pack absLalune) "" mempty) <>
+                  B.para (B.image "data:image/png;base64,cHJpbnQgImhlbGxvIgo=;.lua+%2f%2e%2e%2f%2e%2e%2fa%2elua" "" mempty) <>
+                  B.para (B.image "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" "" mempty)
+        let fooDir = absTmpdir </> "foo"
+        runIOorExplode $ do
+          fillMediaBag d
+          extractMedia fooDir d
+        exists1 <- doesFileExist (fooDir </> "lalune.jpg")
+        assertBool "file in directory is not extracted with original name" exists1
+        exists2 <- doesFileExist (fooDir </> "f9d88c3dbe18f6a7f5670e994a947d51216cdf0e.jpg")
+        assertBool "file with absolute path is not extracted with hashed name" exists2
+        exists3 <- doesFileExist (fooDir </> "2a0eaa89f43fada3e6c577beea4f2f8f53ab6a1d.png")
+        exists4 <- doesFileExist (absTmpdir </> "a.lua")
+        assertBool "data uri with malicious payload gets written outside of destination dir"
+          (exists3 && not exists4)
+        exists5 <- doesFileExist (fooDir </> "d5fceb6532643d0d84ffe09c40c481ecdf59e15a.gif")
+        assertBool "data uri with gif is not properly decoded" exists5
+        -- double-encoded version:
+        let e = B.doc $
+                  B.para (B.image "data:image/png;base64,cHJpbnQgInB3bmVkIgo=;.lua+%252f%252e%252e%252f%252e%252e%252fb%252elua" "" mempty)
+        let barDir = absTmpdir </> "bar"
+        runIOorExplode $ do
+          fillMediaBag e
+          extractMedia barDir e
+        exists6 <- doesFileExist (barDir </> "772ceca21a2751863ec46cb23db0e7fc35b9cff8.png")
+        exists7 <- doesFileExist (absTmpdir </> "b.lua")
+        assertBool "data uri with double-encoded malicious payload gets written outside of destination dir"
+          (exists6 && not exists7)
+  ]
diff --git a/test/Tests/Old.hs b/test/Tests/Old.hs
--- a/test/Tests/Old.hs
+++ b/test/Tests/Old.hs
@@ -1,227 +1,368 @@
+{- |
+   Module      : Tests.Old
+   Copyright   : © 2006-2024 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 Data.Algorithm.Diff
-import Prelude hiding (readFile)
 import System.Exit
-import System.FilePath (joinPath, splitDirectories, (<.>), (</>))
-import System.IO.Temp (withTempFile)
-import System.Process (runProcess, waitForProcess)
+import System.FilePath ((<.>), (</>))
+import System.Environment (getExecutablePath)
+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
+import qualified Data.Text as T
 
-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","-m","-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 "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"
-          ]
+tests :: FilePath -> [TestTree]
+tests pandocPath =
+  [ testGroup "markdown"
+    [ testGroup "writer"
+      $ writerTests' "markdown" ++ lhsWriterTests' "markdown" ++ extWriterTests' "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"
+        (extWriterTests' "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" $ mconcat
+      [ extWriterTests' "html4"
+      , extWriterTests' "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 "asciidoc"
+    [ testGroup "writer" (writerTests' "asciidoc" ++
+                          writerTests' "asciidoc_legacy")
+    , testGroup "reader"
+      [ test' "basic" ["-f", "asciidoc", "-t", "native", "-s"]
+          "asciidoc-reader.adoc" "asciidoc-reader.native"
+      ]
+    ]
+  , testGroup "textile"
+    [ testGroup "writer" $ writerTests' "textile"
+    , test' "reader" ["-r", "textile", "-w", "native", "-s"]
+      "textile-reader.textile" "textile-reader.native"
+    ]
+  , testGroup "djot"
+    [ testGroup "writer" $ writerTests' "djot"
+    , test' "reader" ["-f", "djot", "-t" ,"native", "-s"]
+       "djot-reader.djot" "djot-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-chapter.docbook" "docbook-chapter.native"
+    , test' "reader" ["-r", "docbook", "-w", "native", "-s"]
+      "docbook-xref.docbook" "docbook-xref.native"
+    ]
+  , testGroup "docbook5"
+    [ testGroup "writer" $ writerTests' "docbook5"
+    ]
+  , testGroup "jats"
+    [ testGroup "writer"
+      [ testGroup "jats_archiving" $
+        extWriterTests' "jats_archiving"
+      , testGroup "jats_articleauthoring" $
+        writerTests' "jats_articleauthoring"
+      , testGroup "jats_publishing" $
+        writerTests' "jats_publishing"
+      ]
+    , test' "reader" ["-r", "jats", "-w", "native", "-s"]
+      "jats-reader.xml" "jats-reader.native"
+    ]
+  , testGroup "jira"
+    [ testGroup "writer" $ writerTests' "jira"
+    , test' "reader" ["-r", "jira", "-w", "native", "-s"]
+      "jira-reader.jira" "jira-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" $ mconcat [
+      writerTests' "mediawiki"
+      , extWriterTests' "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=80", "-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", "-s"]
+        "epub/features.epub" "epub/features.native"
+    , test' "wasteland" ["-r", "epub", "-w", "native", "-s"]
+        "epub/wasteland.epub" "epub/wasteland.native"
+    , test' "formatting" ["-r", "epub", "-w", "native", "-s"]
+        "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" , "xwiki", "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"
+    [ test' "basic"  ["-f", "native", "-t", "ms", "--columns=80",
+                      "--variable", "pandoc-version=",
+                      "--pdf-engine", "pdfroff", "-s"]
+      "testsuite.native" "writer.ms"
+    , test' "tables" ["-f", "native", "-t", "ms", "--columns=80",
+                      "--variable", "pandoc-version=",
+                      "--pdf-engine", "pdfroff"]
+      "tables.native"  "tables.ms"
+    ]
+  , testGroup "typst"
+    [ testGroup "writer" $ writerTests' "typst" ++ extWriterTests' "typst"
+    , testGroup "reader"
+       [ test' "typst-reader" ["-r", "typst", "-w", "native", "-s"]
+          "typst-reader.typ" "typst-reader.native"
+       ]
+    ]
+
+  , testGroup "creole"
+    [ test' "reader" ["-r", "creole", "-w", "native", "-s"]
+      "creole-reader.txt" "creole-reader.native"
+    ]
+  , 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 "writer" $ writerTests' "org"
+    ]
+  , testGroup "rtf"
+    [ testGroup "writer" $ writerTests' "rtf" ]
+  , testGroup "endnotexml"
+    [ test' "reader" ["-r", "endnotexml", "-w", "native", "-s"]
+        "endnotexml-reader.xml" "endnotexml-reader.native" ]
+  , testGroup "ipynb"
+    [ test' "reader" ["-f", "ipynb-raw_html-raw_tex+raw_attribute",
+                      "-t", "native", "-s"]
+      "ipynb/simple.ipynb" "ipynb/simple.out.native"
+    , test' "writer" ["-f", "native",
+                      "--markdown-headings=setext", "-t",
+                      "ipynb-raw_html-raw_tex+raw_attribute", "-s"]
+      "ipynb/simple.in.native" "ipynb/simple.ipynb"
+    , test' "reader" ["-t", "native", "-f", "ipynb",
+                      "--ipynb-output=all"]
+      "ipynb/mime.ipynb" "ipynb/mime.native"
+    , test' "writer" ["-f", "native", "-t", "ipynb",
+                      "--wrap=preserve"]
+      "ipynb/mime.native" "ipynb/mime.out.ipynb"
+    , test' "reader" ["-f", "ipynb", "-t", "html"]
+      "ipynb/rank.ipynb" "ipynb/rank.out.html"
+    ]
+  , testGroup "markua" [ testGroup "writer" $ writerTests' "markua"]
+  , testGroup "ansi"
+      [ test' "ansi" ["-f", "markdown", "-t", "ansi"]
+        "ansi-test.txt" "ansi-test.ansi"
+      ]
+  , testGroup "pod"
+      [ test' "pod" ["-f", "pod", "-t", "native"]
+        "pod-reader.pod" "pod-reader.native"
+      ]
+  , testGroup "vimdoc" [ testGroup "writer" $
+      writerTests' "vimdoc" ++
+        [ test' "vimdoc-specific definition lists"
+            ["-s", "-r", "markdown", "-w", "vimdoc", "--toc", "--columns=78"]
+            "vimdoc/definition-lists.markdown" "vimdoc/definition-lists.vimdoc"
+        , test' "linking to docs"
+            ["-s", "-r", "markdown", "-w", "vimdoc", "--toc", "--columns=78"]
+            "vimdoc/vim-online-doc.markdown" "vimdoc/vim-online-doc.vimdoc"
+        , test' "unnumbered TOC up to level 2 headers"
+            ["-s", "-r", "markdown", "-w", "vimdoc", "--toc", "--columns=78",
+             "--toc-depth=2"]
+            "vimdoc/headers.markdown" "vimdoc/headers.vimdoc"
+        , test' "numbered TOC"
+            ["-s", "-r", "markdown", "-w", "vimdoc", "--toc", "--columns=78",
+             "-N"]
+            "vimdoc/headers.markdown" "vimdoc/headers-numbered.vimdoc"
         ]
+    ]
+  , testGroup "bbcode" [testGroup "writer" $ writerTests' "bbcode"]
+  ]
+ where
+    test'           = test pandocPath
+    writerTests'    = writerTests pandocPath
+    s5WriterTest'   = s5WriterTest pandocPath
+    fb2WriterTest'  = fb2WriterTest pandocPath
+    lhsWriterTests' = lhsWriterTests pandocPath
+    lhsReaderTest'  = lhsReaderTest pandocPath
+    extWriterTests' = extendedWriterTests 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)
+                 return $! (T.length s `seq` T.unpack 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",
+              "--markdown-headings=setext", "-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",
+    opts = ["-r", "native", "-w", format, "--columns=80",
             "--variable", "pandoc-version="]
 
-s5WriterTest :: String -> [String] -> String -> TestTree
-s5WriterTest modifier opts format
-  = test (format ++ " writer (" ++ modifier ++ ")")
-    (["-r", "native", "-w", format] ++ opts)
+extendedWriterTests :: FilePath -> String -> [TestTree]
+extendedWriterTests pandocPath format
+  = writerTests pandocPath format ++
+    let testForTable name =
+          test pandocPath
+               (name ++ " table")
+               opts
+               ("tables" </> name <.> "native")
+               ("tables" </> name <.> format)
+    in map testForTable ["planets", "nordics", "students"]
+  where
+    opts = ["-r", "native", "-w", format, "--columns=80",
+            "--variable", "pandoc-version="]
+
+s5WriterTest :: FilePath -> String -> [String] -> String -> TestTree
+s5WriterTest pandocPath modifier opts format
+  = test pandocPath (format ++ " writer (" ++ modifier ++ ")")
+    (["-r", "native", "-w", format] ++ opts ++ ["--variable", "pandoc-version="])
     "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)
     splitTags []               = []
-    splitTags [end]            = fst end : snd end : []
+    splitTags [end]            = [fst end, snd end]
     splitTags (('>','<'):rest) = ">\n" ++ splitTags rest
     splitTags ((c,_):rest)     = c : splitTags rest
     ignoreBinary = unlines . filter (not . startsWith "<binary ") . lines
     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
@@ -230,48 +371,32 @@
 
 -- | 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
-              let mbDynlibDir = findDynlibDir (reverse $
-                                 splitDirectories pandocPath)
-              let dynlibEnv = case mbDynlibDir of
-                                   Nothing  -> []
-                                   Just d   -> [("DYLD_LIBRARY_PATH", d),
-                                                ("LD_LIBRARY_PATH", d)]
-              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
+        getActual   = do
+              env <- setupEnvironment pandocPath
+              (ec, out) <- pipeProcess (Just env) pandocPath
+                             ("--emulate":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
-        updateGolden = UTF8.writeFile norm
+                 else fail $ "Pandoc failed with error code " ++ show ec
+        updateGolden = UTF8.writeFile norm . T.pack
         options = ["--quiet"] ++ [inp] ++ opts
 
 compareValues :: FilePath -> [String] -> String -> String -> IO (Maybe String)
 compareValues norm options expected actual = do
-  pandocPath <- findPandoc
-  let cmd  = pandocPath ++ " " ++ unwords options
+  testExePath <- getExecutablePath
+  let cmd  = testExePath ++ " --emulate " ++ unwords options
   let dash = replicate 72 '-'
   let diff = getDiff (lines actual) (lines expected)
   if expected == actual
@@ -281,9 +406,3 @@
         "\n--- " ++ norm ++
         "\n+++ " ++ cmd ++ "\n" ++
         showDiff (1,1) diff ++ dash
-
-findDynlibDir :: [FilePath] -> Maybe FilePath
-findDynlibDir []           = Nothing
-findDynlibDir ("build":xs) = Just $ joinPath (reverse xs) </> "build"
-findDynlibDir (_:xs)       = findDynlibDir xs
-
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,9 +1,22 @@
 {-# LANGUAGE OverloadedStrings #-}
+{- |
+   Module      : Tests.Readers.Creole
+   Copyright   : © 2017 Sascha Wilde
+                   2017-2024 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 Data.Text (Text)
 import qualified Data.Text as T
 import Test.Tasty
+import Test.Tasty.HUnit (HasCallStack)
 import Tests.Helpers
 import Text.Pandoc
 import Text.Pandoc.Arbitrary ()
@@ -13,7 +26,7 @@
 creole = purely $ readCreole def{ readerStandalone = True }
 
 infix 4 =:
-(=:) :: ToString c
+(=:) :: (ToString c, HasCallStack)
      => String -> (Text, c) -> TestTree
 (=:) = test creole
 
@@ -106,7 +119,7 @@
                          , plain "blubb" ]
         , "nested many unordered lists, one separating space" =:
           ("* foo\n** bar\n*** third\n*** third two\n** baz\n*** third again\n"
-           <> "**** fourth\n***** fith\n* blubb")
+           <> "**** fourth\n***** fifth\n* blubb")
           =?> bulletList [ plain "foo"
                            <> bulletList [ plain "bar"
                                            <> bulletList [ plain "third"
@@ -116,7 +129,7 @@
                                                          <> bulletList [
                                                              plain "fourth"
                                                              <> bulletList [
-                                                                 plain "fith"
+                                                                 plain "fifth"
                                                                  ]
                                                              ]
                                                          ]
@@ -153,7 +166,7 @@
                          , plain "blubb" ]
         , "nested many ordered lists, one separating space" =:
           ("# foo\n## bar\n### third\n### third two\n## baz\n### third again\n"
-           <> "#### fourth\n##### fith\n# blubb")
+           <> "#### fourth\n##### fifth\n# blubb")
           =?> orderedList [ plain "foo"
                            <> orderedList [ plain "bar"
                                            <> orderedList [ plain "third"
@@ -163,7 +176,7 @@
                                                          <> orderedList [
                                                              plain "fourth"
                                                              <> orderedList [
-                                                                 plain "fith"
+                                                                 plain "fifth"
                                                                  ]
                                                              ]
                                                          ]
@@ -176,7 +189,7 @@
                          , plain "blubb" ]
         , "mixed nested ordered and unordered lists, one separating space" =:
           ("# foo\n** bar\n### third\n### third two\n** baz\n### third again\n"
-           <> "#### fourth\n***** fith\n# blubb")
+           <> "#### fourth\n***** fifth\n# blubb")
           =?> orderedList [ plain "foo"
                            <> bulletList [ plain "bar"
                                            <> orderedList [ plain "third"
@@ -186,7 +199,7 @@
                                                          <> orderedList [
                                                              plain "fourth"
                                                              <> bulletList [
-                                                                 plain "fith"
+                                                                 plain "fifth"
                                                                  ]
                                                              ]
                                                          ]
@@ -224,7 +237,7 @@
                     <> " bar")
         , "escaped auto link" =:
           "foo ~http://foo.example.com/bar/baz.html bar"
-          =?> para ("foo http://foo.example.com/bar/baz.html bar")
+          =?> para "foo http://foo.example.com/bar/baz.html bar"
         , "wiki link simple" =:
           "foo [[http://foo.example.com/foo.png]] bar"
           =?> para ("foo "
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,71 +1,56 @@
+{-# LANGUAGE OverloadedStrings #-}
+{- |
+   Module      : Tests.Readers.Docx
+   Copyright   : © 2017-2020 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 Codec.Archive.Zip
 import qualified Data.ByteString as BS
 import qualified Data.ByteString.Lazy as B
-import qualified Data.Map as M
 import qualified Data.Text as T
+import Data.Maybe
 import System.IO.Unsafe
 import Test.Tasty
+import Test.Tasty.Golden.Advanced
 import Test.Tasty.HUnit
 import Tests.Helpers
 import Text.Pandoc
 import qualified Text.Pandoc.Class as P
-import Text.Pandoc.MediaBag (MediaBag, lookupMedia, mediaDirectory)
+import qualified Text.Pandoc.MediaBag as MB
 import Text.Pandoc.UTF8 as UTF8
 
--- We define a wrapper around pandoc that doesn't normalize in the
--- tests. Since we do our own normalization, we want to make sure
--- we're doing it right.
-
-data NoNormPandoc = NoNormPandoc {unNoNorm :: Pandoc}
-                 deriving Show
-
-noNorm :: Pandoc -> NoNormPandoc
-noNorm = NoNormPandoc
-
 defopts :: ReaderOptions
 defopts = def{ readerExtensions = getDefaultExtensions "docx" }
 
-instance ToString NoNormPandoc where
-  toString d = T.unpack $ purely (writeNative def{ writerTemplate = s }) $ toPandoc d
-   where s = case d of
-                  NoNormPandoc (Pandoc (Meta m) _)
-                    | M.null m  -> Nothing
-                    | otherwise -> Just "" -- need this to get meta output
-
-instance ToPandoc NoNormPandoc where
-  toPandoc = unNoNorm
-
-compareOutput :: ReaderOptions
-                 -> FilePath
-                 -> FilePath
-                 -> IO (NoNormPandoc, NoNormPandoc)
-compareOutput opts docxFile nativeFile = do
-  df <- B.readFile docxFile
-  nf <- UTF8.toText <$> BS.readFile nativeFile
-  p <- runIOorExplode $ readDocx opts df
-  df' <- runIOorExplode $ readNative def nf
-  return $ (noNorm p, noNorm df')
-
-testCompareWithOptsIO :: ReaderOptions -> String -> FilePath -> FilePath -> IO TestTree
-testCompareWithOptsIO opts name docxFile nativeFile = do
-  (dp, np) <- compareOutput opts docxFile nativeFile
-  return $ test id name (dp, np)
-
-testCompareWithOpts :: ReaderOptions -> String -> FilePath -> FilePath -> TestTree
-testCompareWithOpts opts name docxFile nativeFile =
-  unsafePerformIO $ testCompareWithOptsIO opts name docxFile nativeFile
-
 testCompare :: String -> FilePath -> FilePath -> TestTree
 testCompare = testCompareWithOpts defopts
 
+testCompareWithOpts :: ReaderOptions -> String -> FilePath -> FilePath -> TestTree
+testCompareWithOpts opts testName docxFP nativeFP =
+  goldenTest
+  testName
+  (do nf <- UTF8.toText <$> BS.readFile nativeFP
+      runIOorExplode (readNative def nf))
+  (do df <- B.readFile docxFP
+      runIOorExplode (readDocx opts df))
+  (nativeDiff nativeFP)
+  (\a -> runIOorExplode (writeNative def{ writerTemplate = Just mempty} a)
+            >>= BS.writeFile nativeFP . UTF8.fromText)
+
 testForWarningsWithOptsIO :: ReaderOptions -> String -> FilePath -> [String] -> IO TestTree
 testForWarningsWithOptsIO opts name docxFile expected = do
   df <- B.readFile docxFile
   logs <-  runIOorExplode $ setVerbosity ERROR >> readDocx opts df >> P.getLog
   let warns = [m | DocxParserWarning m <- logs]
-  return $ test id name (unlines warns, unlines expected)
+  return $ test id name (T.unlines warns, unlines expected)
 
 testForWarningsWithOpts :: ReaderOptions -> String -> FilePath -> [String] -> TestTree
 testForWarningsWithOpts opts name docxFile expected =
@@ -75,23 +60,20 @@
 -- testForWarnings = testForWarningsWithOpts defopts
 
 getMedia :: FilePath -> FilePath -> IO (Maybe B.ByteString)
-getMedia archivePath mediaPath = do
-  zf <- B.readFile archivePath >>= return . toArchive
-  return $ findEntryByPath ("word/" ++ mediaPath) zf >>= (Just . fromEntry)
+getMedia archivePath mediaPath = fmap fromEntry . findEntryByPath
+    ("word/" ++ mediaPath) . toArchive <$> B.readFile archivePath
 
-compareMediaPathIO :: FilePath -> MediaBag -> FilePath -> IO Bool
+compareMediaPathIO :: FilePath -> MB.MediaBag -> FilePath -> IO Bool
 compareMediaPathIO mediaPath mediaBag docxPath = do
   docxMedia <- getMedia docxPath mediaPath
-  let mbBS   = case lookupMedia mediaPath mediaBag of
-                 Just (_, bs) -> bs
+  let mbBS   = case MB.lookupMedia mediaPath mediaBag of
+                 Just item    -> MB.mediaContents item
                  Nothing      -> error ("couldn't find " ++
                                         mediaPath ++
                                         " in media bag")
-      docxBS = case docxMedia of
-                 Just bs -> bs
-                 Nothing -> error ("couldn't find " ++
-                                   mediaPath ++
-                                   " in media bag")
+      docxBS = fromMaybe (error ("couldn't find " ++
+                        mediaPath ++
+                        " in media bag")) docxMedia
   return $ mbBS == docxBS
 
 compareMediaBagIO :: FilePath -> IO Bool
@@ -100,7 +82,7 @@
     mb <- runIOorExplode $ readDocx defopts df >> P.getMediaBag
     bools <- mapM
              (\(fp, _, _) -> compareMediaPathIO fp mb docxFile)
-             (mediaDirectory mb)
+             (MB.mediaDirectory mb)
     return $ and bools
 
 testMediaBagIO :: String -> FilePath -> IO TestTree
@@ -114,8 +96,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"
@@ -128,6 +116,22 @@
             "docx/links.docx"
             "docx/links.native"
           , testCompare
+            "hyperlinks in <w:instrText> tag"
+            "docx/instrText_hyperlink.docx"
+            "docx/instrText_hyperlink.native"
+          , testCompare
+            "nested fields with <w:instrText> tag"
+            "docx/nested_instrText.docx"
+            "docx/nested_instrText.native"
+          , testCompare
+            "empty fields with <w:instrText> tag"
+            "docx/empty_field.docx"
+            "docx/empty_field.native"
+          , testCompare
+            "pageref hyperlinks in <w:instrText> tag"
+            "docx/pageref.docx"
+            "docx/pageref.native"
+          , testCompare
             "inline image"
             "docx/image.docx"
             "docx/image_no_embed.native"
@@ -136,6 +140,10 @@
             "docx/image_vml.docx"
             "docx/image_vml.native"
           , testCompare
+            "VML image as object"
+            "docx/image_vml_as_object.docx"
+            "docx/image_vml_as_object.native"
+          , testCompare
             "inline image in links"
             "docx/inline_images.docx"
             "docx/inline_images.native"
@@ -164,6 +172,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"
@@ -175,6 +187,46 @@
             "inlines inside of Structured Document Tags"
             "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"
+          , testCompare
+            "nested Smart Tags"
+            "docx/nested_smart_tags.docx"
+            "docx/nested_smart_tags.native"
+          , testCompare
+            "remove anchor spans with nothing pointing to them"
+            "docx/unused_anchors.docx"
+            "docx/unused_anchors.native"
+          , testCompare
+            "collapse overlapping targets (anchor spans)"
+            "docx/overlapping_targets.docx"
+            "docx/overlapping_targets.native"
+          , testCompare
+            "anchor in header after anchor"
+            "docx/anchor_header_after_anchor.docx"
+            "docx/anchor_header_after_anchor.native"
+          , testCompare
+            "text in shape format"
+            "docx/text_in_shape_format.docx"
+            "docx/text_in_shape_format.native"
+          , testCompare
+            "image inside textbox content"
+            "docx/textbox_image.docx"
+            "docx/textbox_image.native"
+          , testCompare
+            "image inside textbox content with duplicate encoding"
+            "docx/textbox_image_duplicate_encoding.docx"
+            "docx/textbox_image_duplicate_encoding.native"
+          , testCompare
+            "image with textbox caption in same paragraph"
+            "docx/image_with_textbox_caption.docx"
+            "docx/image_with_textbox_caption.native"
           ]
         , testGroup "blocks"
           [ testCompare
@@ -210,6 +262,14 @@
             "docx/lists.docx"
             "docx/lists.native"
           , testCompare
+            "compact lists"
+            "docx/lists-compact.docx"
+            "docx/lists-compact.native"
+          , testCompare
+            "lists with level overrides"
+            "docx/lists_level_override.docx"
+            "docx/lists_level_override.native"
+          , testCompare
             "lists continuing after interruption"
             "docx/lists_continuing.docx"
             "docx/lists_continuing.native"
@@ -218,10 +278,18 @@
             "docx/lists_restarting.docx"
             "docx/lists_restarting.native"
           , testCompare
+            "sublists reset numbering to 1"
+            "docx/lists_sublist_reset.docx"
+            "docx/lists_sublist_reset.native"
+          , testCompare
             "definition lists"
             "docx/definition_list.docx"
             "docx/definition_list.native"
           , testCompare
+            "task lists"
+            "docx/task_list.docx"
+            "docx/task_list.native"
+          , testCompare
             "custom defined lists in styles"
             "docx/german_styled_lists.docx"
             "docx/german_styled_lists.native"
@@ -244,8 +312,12 @@
           , testCompare
             "blockquotes (parsing indent as blockquote)"
             "docx/block_quotes.docx"
-            "docx/block_quotes_parse_indent.native"
+            "docx/block_quotes.native"
           , testCompare
+            "blockquotes (parsing indent relative to the indent of the parent style as blockquote)"
+            "docx/relative_indentation_blockquotes.docx"
+            "docx/relative_indentation_blockquotes.native"
+          , testCompare
             "hanging indents"
             "docx/hanging_indent.docx"
             "docx/hanging_indent.native"
@@ -258,18 +330,66 @@
             "docx/table_with_list_cell.docx"
             "docx/table_with_list_cell.native"
           , testCompare
+            "a table with gridBefore"
+            "docx/table_gridbefore.docx"
+            "docx/table_gridbefore.native"
+          , testCompare
+            "a table with a header which contains rowspans greater than 1"
+            "docx/table_header_rowspan.docx"
+            "docx/table_header_rowspan.native"
+          , testCompare
             "tables with one row"
             "docx/table_one_row.docx"
             "docx/table_one_row.native"
           , testCompare
+            "tables with just one row, which is a header"
+            "docx/table_one_header_row.docx"
+            "docx/table_one_header_row.native"
+          , testCompare
+            "tables with variable width"
+            "docx/table_variable_width.docx"
+            "docx/table_variable_width.native"
+          , testCompare
+            "tables with captions which contain a Table field"
+            "docx/table_captions_with_field.docx"
+            "docx/table_captions_with_field.native"
+          , testCompare
+            "tables with captions which don't contain a Table field"
+            "docx/table_captions_no_field.docx"
+            "docx/table_captions_no_field.native"
+          , testCompare
             "code block"
             "docx/codeblock.docx"
             "docx/codeblock.native"
           , testCompare
+            "combine adjacent code blocks"
+            "docx/adjacent_codeblocks.docx"
+            "docx/adjacent_codeblocks.native"
+          , testCompare
             "dropcap paragraphs"
             "docx/drop_cap.docx"
             "docx/drop_cap.native"
           ]
+        , testGroup "citations"
+          [ testCompare
+            "zotero with -citations"
+            "docx/zotero_citations.docx"
+            "docx/zotero_citations_minus.native"
+          , testCompareWithOpts def{readerExtensions =
+                  extensionsFromList [Ext_citations]}
+            "zotero with +citations"
+            "docx/zotero_citations.docx"
+            "docx/zotero_citations_plus.native"
+          , testCompare
+            "mendeley with -citations"
+            "docx/mendeley_citations.docx"
+            "docx/mendeley_citations_minus.native"
+          , testCompareWithOpts def{readerExtensions =
+                  extensionsFromList [Ext_citations]}
+            "mendeley with +citations"
+            "docx/mendeley_citations.docx"
+            "docx/mendeley_citations_plus.native"
+          ]
         , testGroup "track changes"
           [ testCompare
             "insertion (default)"
@@ -327,6 +447,22 @@
             "comments (all comments)"
             "docx/comments.docx"
             "docx/comments.native"
+          , testCompareWithOpts def{readerTrackChanges=AcceptChanges}
+            "paragraph insertion/deletion (accept)"
+            "docx/paragraph_insertion_deletion.docx"
+            "docx/paragraph_insertion_deletion_accept.native"
+          , testCompareWithOpts def{readerTrackChanges=RejectChanges}
+            "paragraph insertion/deletion (reject)"
+            "docx/paragraph_insertion_deletion.docx"
+            "docx/paragraph_insertion_deletion_reject.native"
+          , testCompareWithOpts def{readerTrackChanges=AllChanges}
+            "paragraph insertion/deletion (all)"
+            "docx/paragraph_insertion_deletion.docx"
+            "docx/paragraph_insertion_deletion_all.native"
+          , testCompareWithOpts def{readerTrackChanges=AllChanges}
+            "paragraph insertion/deletion (all)"
+            "docx/track_changes_scrubbed_metadata.docx"
+            "docx/track_changes_scrubbed_metadata.native"
           , testForWarningsWithOpts def{readerTrackChanges=AcceptChanges}
             "comment warnings (accept -- no warnings)"
             "docx/comments_warning.docx"
@@ -339,12 +475,42 @@
             "comment warnings (all)"
             "docx/comments_warning.docx"
             ["Docx comment 1 will not retain formatting"]
+          , testForWarningsWithOpts def{readerTrackChanges=AllChanges,
+                                        readerExtensions=extensionsFromList [Ext_styles]}
+            "comments (with styles extension)"
+            "docx/comments.docx"
+            []
           ]
         , testGroup "media"
           [ testMediaBag
             "image extraction"
             "docx/image.docx"
+          , testMediaBag
+            "image inside textbox content populates media bag"
+            "docx/textbox_image.docx"
+          , testMediaBag
+            "image inside textbox content with duplicate encoding populates media bag"
+            "docx/textbox_image_duplicate_encoding.docx"
+          , testMediaBag
+            "image with textbox caption in same paragraph populates media bag"
+            "docx/image_with_textbox_caption.docx"
           ]
+        , testGroup "custom styles"
+          [ testCompare
+            "custom styles (`+styles`) not enabled (default)"
+            "docx/custom-style-reference.docx"
+            "docx/custom-style-no-styles.native"
+          , testCompareWithOpts
+            def{readerExtensions=extensionsFromList [Ext_styles]}
+            "custom styles (`+styles`) enabled"
+            "docx/custom-style-reference.docx"
+            "docx/custom-style-with-styles.native"
+          , testCompareWithOpts
+            def{readerExtensions=extensionsFromList [Ext_styles]}
+            "custom styles (`+styles`): Compact style is removed from output"
+            "docx/compact-style-removal.docx"
+            "docx/compact-style-removal.native"
+          ]
         , testGroup "metadata"
           [ testCompareWithOpts def{readerStandalone=True}
             "metadata fields"
@@ -355,5 +521,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
new file mode 100644
--- /dev/null
+++ b/test/Tests/Readers/DokuWiki.hs
@@ -0,0 +1,335 @@
+{-# LANGUAGE OverloadedStrings   #-}
+{-# LANGUAGE ScopedTypeVariables #-}
+{-# LANGUAGE TupleSections #-}
+{- |
+   Module      : Tests.Readers.DokuWiki
+   Copyright   : © 2018-2020 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 Data.Text (Text)
+import qualified Data.Text as T
+import Test.Tasty
+import Test.Tasty.HUnit (HasCallStack)
+import Tests.Helpers
+import Text.Pandoc
+import Text.Pandoc.Arbitrary ()
+import Text.Pandoc.Builder
+
+dokuwiki :: Text -> Pandoc
+dokuwiki = purely $ readDokuWiki def{ readerStandalone = True }
+
+infix 4 =:
+(=:) :: (ToString c, HasCallStack)
+     => String -> (Text, c) -> TestTree
+(=:) = test dokuwiki
+
+tests :: [TestTree]
+tests = [ testGroup "inlines"
+          [ "Bold" =:
+            "**bold**" =?>
+            para (strong "bold")
+          , "Italic" =:
+            "//italic//" =?>
+            para (emph "italic")
+          , "Underlined" =:
+            "__underlined__" =?>
+            para (underline "underlined")
+          , "Monospaced" =:
+            "''monospaced''" =?>
+            para (code "monospaced")
+          , "Monospaced with nowiki" =:
+            "''%%monospaced%%''" =?>
+            para (code "monospaced")
+          , "Combined" =:
+            "**__//''combine''//__**" =?>
+            para (strong $ underline $ emph $ code "combine")
+          , "Nowiki" =:
+            T.unlines [ "<nowiki>"
+                      , "This is some text which contains addresses like this: http://www.splitbrain.org and **formatting**, but nothing is done with it."
+                      , "</nowiki>"
+                      ] =?>
+            para "This is some text which contains addresses like this: http://www.splitbrain.org and **formatting**, but nothing is done with it."
+          , "Percent" =:
+            "The same is true for %%//__this__ text// with a smiley ;-)%%." =?>
+            para "The same is true for //__this__ text// with a smiley ;-)."
+          , "Subscript" =:
+            "<sub>subscript</sub>" =?>
+            para (subscript "subscript")
+          , "Superscript" =:
+            "<sup>superscript</sup>" =?>
+            para (superscript "superscript")
+          , "Deleted" =:
+            "<del>deleted</del>" =?>
+            para (strikeout "deleted")
+          , "Inline code" =:
+            "foo <code java>public static void main</code> bar" =?>
+            para (text "foo") <> codeBlockWith ("", ["java"], []) "public static void main"
+              <> para (text "bar")
+          , "Inline file" =:
+            "foo <file></code></file> bar" =?>
+            para (text "foo") <> codeBlock "</code>" <> para (text "bar")
+          , "Inline HTML" =:
+            "<html>\nThis is some <span style=\"color:red;font-size:150%;\">inline HTML</span>\n</html>" =?>
+            para (rawInline "html" "\nThis is some <span style=\"color:red;font-size:150%;\">inline HTML</span>\n")
+          , "Inline PHP" =:
+            "<php>echo '<p>Hello World</p>';</php>" =?>
+            para (rawInline "html" "<?php echo '<p>Hello World</p>'; ?>")
+          , "Linebreak" =:
+            T.unlines [ "This is some text with some linebreaks\\\\ Note that the"
+                      , "two backslashes are only recognized at the end of a line\\\\"
+                      , "or followed by\\\\ a whitespace \\\\this happens without it."
+                      ] =?>
+            para ("This is some text with some linebreaks" <> linebreak <> "Note that the\n" <>
+                  "two backslashes are only recognized at the end of a line" <> linebreak <>
+                  "or followed by" <> linebreak <> "a whitespace \\\\this happens without it.")
+          , testGroup "External links"
+            [ "Autolink" =:
+              "http://www.google.com" =?>
+              para (link "http://www.google.com" "" (str "http://www.google.com"))
+            , "Link without description" =:
+              "[[https://example.com]]" =?>
+              para (link "https://example.com" "" (str "https://example.com"))
+            , "Link with description" =:
+              "[[http://www.google.com|This Link points to google]]" =?>
+              para (link "http://www.google.com" "" (text "This Link points to google"))
+            , "Trim whitespace around link and description" =:
+              "[[   http://www.google.com    |   This Link points to google   ]]" =?>
+              para (link "http://www.google.com" "" (text "This Link points to google"))
+            , "Email address" =:
+              "<andi@splitbrain.org>" =?>
+              para (link "mailto:andi@splitbrain.org" "" (str "andi@splitbrain.org"))
+            ]
+          , testGroup "Internal links"
+            [ "Current namespace" =:
+              "[[example]]" =?>
+              para (link "example" "" (str "example"))
+            , "Current namespace starting with dot" =:
+              "[[.example]]" =?>
+              para (link "example" "" (str ".example"))
+            , "Current namespace starting with dot and colon" =:
+              "[[.:example]]" =?>
+              para (link "example" "" (str "example"))
+            , "Root namespace" =:
+              "[[:example]]" =?>
+              para (link "/example" "" (str "example"))
+            , "Parent namespace" =:
+              "[[..example]]" =?>
+              para (link "../example" "" (str "..example"))
+            , "Parent namespace with colon" =:
+              "[[..:example]]" =?>
+              para (link "../example" "" (str "example"))
+            , "Beneath the root namespace" =:
+              "[[wiki:example]]" =?>
+              para (link "/wiki/example" "" (str "example"))
+            , "Explicitly beneath the root namespace" =:
+              "[[:wiki:example]]" =?>
+              para (link "/wiki/example" "" (str "example"))
+            ]
+          , testGroup "Interwiki links"
+            [ "Interwiki without description" =:
+              "[[doku>DokuWiki]]" =?>
+              para (link "https://www.dokuwiki.org/DokuWiki" "" (str "DokuWiki"))
+            , "Interwiki link with description" =:
+              "[[doku>toolbar|quickbuttons]]" =?>
+              para (link "https://www.dokuwiki.org/toolbar" "" (str "quickbuttons"))
+            ]
+          , "Footnote" =:
+            "((This is a footnote))" =?>
+            para (note (para "This is a footnote"))
+          , testGroup "Images"
+            [ "Image" =:
+              "{{image.jpg}}" =?>
+              para (image "image.jpg" "" (str "image.jpg"))
+            , "Image with caption" =:
+              "{{image.png|This is the caption}}" =?>
+              para (image "image.png" "" "This is the caption")
+            , "Image with } in caption" =:
+              "{{image.png|There is an } in the caption}}" =?>
+              para (image "image.png" "" "There is an } in the caption")
+            , "Wiki namespace starting with dot" =:
+              "{{.wiki:image.jpg}}" =?>
+              para (image "wiki/image.jpg" "" (str "image.jpg"))
+            , "Left aligned image" =:
+              "{{wiki:dokuwiki-128.png }}" =?>
+              para (imageWith ("", ["align-left"], []) "/wiki/dokuwiki-128.png" "" (str "dokuwiki-128.png"))
+            , "Right aligned image" =:
+              "{{ wiki:dokuwiki-128.png}}" =?>
+              para (imageWith ("", ["align-right"], []) "/wiki/dokuwiki-128.png" "" (str "dokuwiki-128.png"))
+            , "Centered image" =:
+              "{{ wiki:dokuwiki-128.png }}" =?>
+              para (imageWith ("", ["align-center"], []) "/wiki/dokuwiki-128.png" "" (str "dokuwiki-128.png"))
+            , "Image with width" =:
+              "{{wiki:dokuwiki-128.png?50}}" =?>
+              para (imageWith ("", [], [("width", "50"), ("query", "?50")]) "/wiki/dokuwiki-128.png" "" (str "dokuwiki-128.png"))
+            , "Image with width and height" =:
+              "{{wiki:dokuwiki-128.png?nocache&50x100}}" =?>
+              para (imageWith ("", [], [("width", "50"), ("height", "100"), ("query", "?nocache&50x100")]) "/wiki/dokuwiki-128.png" "" (str "dokuwiki-128.png"))
+            , "Linkonly" =:
+              "{{wiki:dokuwiki-128.png?linkonly}}" =?>
+              para (link "/wiki/dokuwiki-128.png" "" (str "dokuwiki-128.png"))
+            ]
+          , "Ignore ~~NOTOC~~" =:
+            "Here is a ~~NOTOC~~ macro" =?>
+            para "Here is a macro"
+          , "Ignore ~~NOCACHE~~" =:
+            "Here is a ~~NOCACHE~~ macro" =?>
+            para "Here is a macro"
+          ]
+        , testGroup "Sectioning"
+          [ "Headline level 1" =:
+            "====== Headline Level 1 ======" =?>
+            header 1 "Headline Level 1"
+          , "Headline level 2" =:
+            "===== Headline Level 2 =====" =?>
+            header 2 "Headline Level 2"
+          , "Headline level 3" =:
+            "==== Headline Level 3 ====" =?>
+            header 3 "Headline Level 3"
+          , "Headline level 4" =:
+            "=== Headline Level 4 ===" =?>
+            header 4 "Headline Level 4"
+          , "Headline level 5" =:
+            "== Headline Level 5 ==" =?>
+            header 5 "Headline Level 5"
+          , "Only two closing = are required" =:
+            "====== Headline Level 1 ==" =?>
+            header 1 "Headline Level 1"
+          , "One closing = is not enough" =:
+            "====== Headline Level 1 =" =?>
+            para "====== Headline Level 1 ="
+          , "One closing = is not enough" =:
+            "== Headline with = sign ==" =?>
+            header 5 "Headline with = sign"
+          ]
+        , "Horizontal line" =:
+          "----" =?>
+          horizontalRule
+        , testGroup "Lists"
+          [ "Unordered list" =:
+            T.unlines [ "  * This is a list"
+                      , "  * The second item"
+                      , "    * You may have different levels"
+                      , "  * Another item"
+                      ] =?>
+            bulletList [ plain "This is a list"
+                       , plain "The second item" <>
+                         bulletList [ plain "You may have different levels" ]
+                       , plain "Another item"
+                       ]
+          , "Ordered list" =:
+            T.unlines [ "  - The same list but ordered"
+                      , "  - Another item"
+                      , "    - Just use indentation for deeper levels"
+                      , "  - That's it"
+                      ] =?>
+            orderedList [ plain "The same list but ordered"
+                        , plain "Another item" <>
+                          orderedList [ plain "Just use indentation for deeper levels" ]
+                        , plain "That's it"
+                        ]
+          , "Multiline list items" =: -- https://www.dokuwiki.org/faq:lists
+            T.unlines [ "  - first item"
+                      , "  - second item with linebreak\\\\ second line"
+                      , "  - third item with code: <code>"
+                      , "some code"
+                      , "comes here"
+                      , "</code>"
+                      , "  - fourth item"
+                      ] =?>
+            orderedList [ plain "first item"
+                        , plain ("second item with linebreak" <> linebreak <> " second line")
+                        , plain "third item with code: " <> codeBlock "some code\ncomes here\n"
+                        , plain "fourth item"
+                        ]
+          ]
+        , "Block HTML" =:
+          T.unlines [ "<HTML>"
+                    , "<p style=\"border:2px dashed red;\">And this is some block HTML</p>"
+                    , "</HTML>"
+                    ] =?>
+          rawBlock "html" "<p style=\"border:2px dashed red;\">And this is some block HTML</p>\n"
+        , "Block PHP" =:
+          T.unlines [ "<PHP>"
+                    , "echo '<p>Hello World</p>';"
+                    , "</PHP>"
+                    ] =?>
+          rawBlock "html" "<?php echo '<p>Hello World</p>';\n ?>"
+        , "Quote" =:
+          T.unlines [ "> foo"
+                    , ">no space is required after >"
+                    , "> bar"
+                    , ">> baz"
+                    , "> bat"
+                    ] =?>
+          blockQuote (plain (text "foo" <> linebreak <>
+                        text "no space is required after >" <> linebreak <>
+                        text "bar") <>
+                      blockQuote (plain "baz") <>
+                      plain "bat")
+        , "Code block" =:
+          T.unlines [ "<code>"
+                    , "foo bar baz"
+                    , "</code>"
+                    ] =?>
+          codeBlock "foo bar baz\n"
+        , "Java code block" =:
+          T.unlines [ "<code java>"
+                    , "public static void main"
+                    , "</code>"
+                    ] =?>
+          codeBlockWith ("", ["java"], []) "public static void main\n"
+        , "File with filename and no language" =:
+          T.unlines [ "<file - foo.bar>"
+                    , "file contents"
+                    , "</file>"
+                    ] =?>
+          codeBlock "file contents\n"
+        , "Table" =:
+          T.unlines [ "| foo | bar |"
+                    , "| bat | baz |"
+                    ] =?>
+          simpleTable [] [[plain "foo", plain "bar"]
+                         ,[plain "bat", plain "baz"]]
+        , "Table with header" =:
+          T.unlines [ "^ foo ^ bar ^"
+                    , "| bat | baz |"
+                    ] =?>
+          simpleTable [plain "foo", plain "bar"] [[plain "bat", plain "baz"]]
+        , "Table with alignment" =:
+          T.unlines [ "^ 0  ^  1  ^  2 ^ 3 ^"
+                    , "| a  | b   | c  |d  |"
+                    ] =?>
+          table emptyCaption
+                (map (, ColWidthDefault) [AlignLeft, AlignCenter, AlignRight, AlignDefault])
+                (TableHead nullAttr
+                          [Row nullAttr . map (simpleCell . plain) $ ["0", "1", "2", "3"]])
+                [TableBody nullAttr 0 []
+                          [Row nullAttr . map (simpleCell . plain) $ ["a", "b", "c", "d"]]]
+                (TableFoot nullAttr [])
+        , "Table with colspan" =:
+          T.unlines [ "^ 0,0 ^ 0,1 ^ 0,2 ^"
+                    , "| 1,0 | 1,1 ||"
+                    , "| 2,0 | 2,1 | 2,2 |"
+                    ] =?>
+          simpleTable [plain "0,0", plain "0,1", plain "0,2"]
+                      [[plain "1,0", plain "1,1", mempty]
+                      ,[plain "2,0", plain "2,1", plain "2,2"]
+                      ]
+        , "Indented code block" =:
+          T.unlines [ "foo"
+                    , "  bar"
+                    , "    bat"
+                    , "baz"
+                    ] =?>
+          para "foo" <>
+          codeBlock "bar\n  bat\n" <>
+          para "baz"
+        ]
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,6 +1,18 @@
+{- |
+   Module      : Tests.Readers.EPUB
+   Copyright   : © 2006-2024 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 qualified Data.ByteString.Lazy as BL
+import qualified Data.Text as T
 import Test.Tasty
 import Test.Tasty.HUnit
 import qualified Text.Pandoc.Class as P
@@ -17,12 +29,14 @@
 
 testMediaBag :: FilePath -> [(String, String, Int)] -> IO ()
 testMediaBag fp bag = do
-  actBag <- (mediaDirectory <$> getMediaBag fp)
+  actBag <- mediaDirectory <$> getMediaBag fp
   assertBool (show "MediaBag did not match:\nExpected: "
              ++ show bag
              ++ "\nActual: "
              ++ show actBag)
-             (actBag == bag)
+             (actBag == packBag bag)
+  where
+    packBag = map $ \(x, y, z) -> (x, T.pack y, z)
 
 featuresBag :: [(String, String, Int)]
 featuresBag = [("img/check.gif","image/gif",1340)
@@ -31,10 +45,42 @@
               ,("img/multiscripts_and_greek_alphabet.png","image/png",10060)
               ]
 
+-- with additional meta tag for cover in EPUB2 format
+epub3CoverBag :: [(String, String, Int)]
+epub3CoverBag = [("wasteland-cover.jpg","image/jpeg", 16586)]
+
+epub3NoCoverBag :: [(String, String, Int)]
+epub3NoCoverBag = [("img/check.gif","image/gif",1340)
+                  ,("img/check.jpg","image/jpeg",2661)
+                  ,("img/check.png","image/png",2815)
+                  ]
+
+-- content.opf uses the word `picture` to refer to the cover as much as validly possible
+-- to check if references are resolved correctly
+epub2PictureBag :: [(String, String, Int)]
+epub2PictureBag = [("image/image.jpg","image/jpeg",9713)]
+
+-- content.opf contains the word `cover` as much as possible, to check if possible multiple matches cause errors
+epub2CoverBag :: [(String, String, Int)]
+epub2CoverBag = [("image/cover.jpg","image/jpeg",9713)]
+
+epub2NoCoverBag :: [(String, String, Int)]
+epub2NoCoverBag = []
+
 tests :: [TestTree]
 tests =
   [ testGroup "EPUB Mediabag"
     [ testCase "features bag"
-      (testMediaBag "epub/img.epub" featuresBag)
+      (testMediaBag "epub/img.epub" featuresBag),
+      testCase "EPUB3 cover bag"
+      (testMediaBag "epub/wasteland.epub" epub3CoverBag),
+      testCase "EPUB3 no cover bag"
+      (testMediaBag "epub/img_no_cover.epub" epub3NoCoverBag),
+      testCase "EPUB2 picture bag"
+      (testMediaBag "epub/epub2_picture.epub" epub2PictureBag),
+      testCase "EPUB2 cover bag"
+      (testMediaBag "epub/epub2_cover.epub" epub2CoverBag),
+      testCase "EPUB2 no cover bag"
+      (testMediaBag "epub/epub2_no_cover.epub" epub2NoCoverBag)
     ]
   ]
diff --git a/test/Tests/Readers/FB2.hs b/test/Tests/Readers/FB2.hs
new file mode 100644
--- /dev/null
+++ b/test/Tests/Readers/FB2.hs
@@ -0,0 +1,39 @@
+{- |
+   Module      : Tests.Readers.FB2
+   Copyright   : © 2018-2020 Alexander Krotov
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : © 2018-2020 Alexander Krotov <ilabdsf@gmail.com>
+   Stability   : alpha
+   Portability : portable
+
+Tests for the FB2 reader.
+-}
+module Tests.Readers.FB2 (tests) where
+
+import Test.Tasty
+import Tests.Helpers
+import Test.Tasty.Golden (goldenVsString)
+import qualified Data.ByteString as BS
+import Text.Pandoc
+import Text.Pandoc.UTF8 (toText, fromStringLazy)
+import Data.Text (Text, unpack)
+import System.FilePath (replaceExtension)
+
+fb2ToNative :: Text -> Text
+fb2ToNative = purely (writeNative def{ writerTemplate = Just mempty }) . purely (readFB2 def)
+
+fb2Test :: TestName -> FilePath -> TestTree
+fb2Test name path = goldenVsString name native
+  (fromStringLazy . filter (/='\r') . unpack . fb2ToNative . toText
+    <$> BS.readFile path)
+  where native = replaceExtension path ".native"
+
+tests :: [TestTree]
+tests = [ fb2Test "Emphasis" "fb2/reader/emphasis.fb2"
+        , fb2Test "Titles" "fb2/reader/titles.fb2"
+        , fb2Test "Epigraph" "fb2/reader/epigraph.fb2"
+        , fb2Test "Poem" "fb2/reader/poem.fb2"
+        , fb2Test "Meta" "fb2/reader/meta.fb2"
+        , fb2Test "Notes" "fb2/reader/notes.fb2"
+        ]
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,12 +1,28 @@
 {-# LANGUAGE OverloadedStrings #-}
+{- |
+   Module      : Tests.Readers.HTML
+   Copyright   : © 2006-2024 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 Data.Text (Text)
+import qualified Data.Text as T
 import Test.Tasty
+import Test.Tasty.QuickCheck
+import Test.Tasty.Options (IsOption(defaultValue))
 import Tests.Helpers
 import Text.Pandoc
+import Text.Pandoc.Shared (isHeaderBlock)
 import Text.Pandoc.Arbitrary ()
 import Text.Pandoc.Builder
+import Text.Pandoc.Walk (walk)
 
 html :: Text -> Pandoc
 html = purely $ readHtml def
@@ -14,6 +30,31 @@
 htmlNativeDivs :: Text -> Pandoc
 htmlNativeDivs = purely $ readHtml def { readerExtensions = enableExtension Ext_native_divs $ readerExtensions def }
 
+makeRoundTrip :: Block -> Block
+makeRoundTrip CodeBlock{} = Para [Str "code block was here"]
+makeRoundTrip LineBlock{} = Para [Str "line block was here"]
+makeRoundTrip RawBlock{} = Para [Str "raw block was here"]
+makeRoundTrip (Div attr bs) = Div attr $ filter (not . isHeaderBlock) bs
+-- avoids round-trip failures related to makeSections
+-- e.g. with [Div ("loc",[],[("a","11"),("b_2","a b c")]) [Header 3 ("",[],[]) []]]
+makeRoundTrip Table{} = Para [Str "table block was here"]
+makeRoundTrip x           = x
+
+removeRawInlines :: Inline -> Inline
+removeRawInlines RawInline{} = Str "raw inline was here"
+removeRawInlines x           = x
+
+roundTrip :: Blocks -> Bool
+roundTrip b = d'' == d'''
+  where d = walk removeRawInlines $
+            walk makeRoundTrip $ Pandoc nullMeta $ toList b
+        d' = rewrite d
+        d'' = rewrite d'
+        d''' = rewrite d''
+        rewrite = html . (`T.snoc` '\n') .
+                  purely (writeHtml5String def
+                            { writerWrapText = WrapPreserve })
+
 tests :: [TestTree]
 tests = [ testGroup "base tag"
           [ test html "simple" $
@@ -33,6 +74,12 @@
           [ test html "anchor without href" $ "<a name=\"anchor\"/>" =?>
             plain (spanWith ("anchor",[],[]) mempty)
           ]
+        , testGroup "img"
+          [ test html "data-external attribute" $ "<img data-external=\"1\" src=\"http://example.com/stickman.gif\">" =?>
+            plain (imageWith ("", [], [("external", "1")]) "http://example.com/stickman.gif" "" "")
+          , test html "title" $ "<img title=\"The title\" src=\"http://example.com/stickman.gif\">" =?>
+            plain (imageWith ("", [], []) "http://example.com/stickman.gif" "The title" "")
+          ]
         , testGroup "lang"
           [ test html "lang on <html>" $ "<html lang=\"es\">hola" =?>
             setMeta "lang" (text "es") (doc (plain (text "hola")))
@@ -40,15 +87,59 @@
             setMeta "lang" (text "es") (doc (plain (text "hola")))
           ]
         , testGroup "main"
-          [ test htmlNativeDivs "<main> becomes <div role=main>" $ "<main>hello</main>" =?>
-            doc (divWith ("", [], [("role", "main")]) (plain (text "hello")))
+          [ test htmlNativeDivs "<main> contents are parsed" $ "<header>ignore me</header><nav><p>ignore me</p><main>hello</main><footer>ignore me</footer>" =?>
+            doc (plain (text "hello"))
           , test htmlNativeDivs "<main role=X> becomes <div role=X>" $ "<main role=foobar>hello</main>" =?>
             doc (divWith ("", [], [("role", "foobar")]) (plain (text "hello")))
           , test htmlNativeDivs "<main> has attributes preserved" $ "<main id=foo class=bar data-baz=qux>hello</main>" =?>
-            doc (divWith ("foo", ["bar"], [("role", "main"), ("data-baz", "qux")]) (plain (text "hello")))
+            doc (divWith ("foo", ["bar"], [("role", "main"), ("baz", "qux")]) (plain (text "hello")))
           , test htmlNativeDivs "<main> closes <p>" $ "<p>hello<main>main content</main>" =?>
-            doc (para (text "hello") <> divWith ("", [], [("role", "main")]) (plain (text "main content")))
+            doc (plain (text "main content"))
           , test htmlNativeDivs "<main> followed by text" $ "<main>main content</main>non-main content" =?>
-            doc (divWith ("", [], [("role", "main")]) (plain (text "main content")) <> plain (text "non-main content"))
+            doc (plain (text "main content"))
           ]
+        , testGroup "code"
+          [
+            test html "inline code block" $
+            "<code>Answer is 42</code>" =?>
+            plain (codeWith ("",[],[]) "Answer is 42")
+          ]
+        , testGroup "tt"
+          [
+            test html "inline tt block" $
+            "<tt>Answer is 42</tt>" =?>
+            plain (codeWith ("",[],[]) "Answer is 42")
+          ]
+        , testGroup "samp"
+          [
+            test html "inline samp block" $
+            "<samp>Answer is 42</samp>" =?>
+            plain (codeWith ("",["sample"],[]) "Answer is 42")
+          ]
+        , testGroup "var"
+          [ test html "inline var block" $
+            "<var>result</var>" =?>
+            plain (codeWith ("",["variable"],[]) "result")
+          ]
+        , testGroup "header"
+          [ test htmlNativeDivs "<header> is parsed as a div" $
+            "<header id=\"title\">Title</header>" =?>
+            divWith ("title", ["header"], mempty) (plain "Title")
+          ]
+        , testGroup "code block"
+          [ test html "attributes in pre > code element" $
+            "<pre><code id=\"a\" class=\"python\">\nprint('hi')\n</code></pre>"
+            =?>
+            codeBlockWith ("a", ["python"], []) "\nprint('hi')"
+
+          , test html "attributes in pre take precedence" $
+            "<pre id=\"c\"><code id=\"d\">print('hi mom!')\n</code></pre>"
+            =?>
+            codeBlockWith ("c", [], []) "print('hi mom!')"
+          ]
+        , askOption $ \(QuickCheckTests numtests) ->
+            testProperty "Round trip" $
+              withMaxSuccess (if QuickCheckTests numtests == defaultValue
+                                 then 25
+                                 else numtests) roundTrip
         ]
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,4 +1,15 @@
 {-# 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 Data.Text (Text)
@@ -8,13 +19,14 @@
 import Text.Pandoc.Arbitrary ()
 import Text.Pandoc.Builder
 
+import qualified Data.Text as T
+
 jats :: Text -> Pandoc
 jats = purely $ readJATS def
 
 tests :: [TestTree]
 tests = [ testGroup "inline code"
           [ test jats "basic" $ "<p>\n  <monospace>@&amp;</monospace>\n</p>" =?> para (code "@&")
-          , test jats "lang" $ "<p>\n  <code language=\"c\">@&amp;</code>\n</p>" =?> para (codeWith ("", ["c"], []) "@&")
           ]
         , testGroup "block code"
           [ test jats "basic" $ "<preformat>@&amp;</preformat>" =?> codeBlock "@&"
@@ -23,6 +35,42 @@
         , testGroup "images"
           [ test jats "basic" $ "<graphic mimetype=\"image\" mime-subtype=\"\" xlink:href=\"/url\" xlink:title=\"title\" />"
             =?> para (image "/url" "title" mempty)
+            , test jats "alt-text" $ 
+                          "<graphic id=\"graphic001\"\n\
+                          \ xlink:href=\"https://lh3.googleusercontent.com/dB7iirJ3ncQaVMBGE2YX-WCeoAVIChb6NAzoFcKCFChMsrixJvD7ZRbvcaC-ceXEzXYaoH4K5vaoRDsUyBHFkpIDPnsn3bnzovbvi0a2Gg=s660\"\n\
+                          \ xlink:title=\"This is the title of the graphic\"\n\
+                          \ xlink:role=\"This is the role of the graphic\">\n\
+                          \ <alt-text>Alternative text of the graphic</alt-text>\n\
+                          \ <caption>\n\
+                          \ <title>This is the title of the caption</title>\n\
+                          \ <p>Google doodle from 14 March 2003</p></caption>\n\
+                          \ </graphic>"
+            =?> Para [ Image
+              ( "graphic001"
+              , [ "This"
+                , "is"
+                , "the"
+                , "role"
+                , "of"
+                , "the"
+                , "graphic"
+                ]
+              , []
+              )
+              [ Str "Alternative"
+              , Space
+              , Str "text"
+              , Space
+              , Str "of"
+              , Space
+              , Str "the"
+              , Space
+              , Str "graphic"
+              ]
+              ( "https://lh3.googleusercontent.com/dB7iirJ3ncQaVMBGE2YX-WCeoAVIChb6NAzoFcKCFChMsrixJvD7ZRbvcaC-ceXEzXYaoH4K5vaoRDsUyBHFkpIDPnsn3bnzovbvi0a2Gg=s660"
+              , "This is the title of the graphic"
+              )
+              ]
           ]
         , test jats "bullet list" $
                             "<list list-type=\"bullet\">\n\
@@ -75,6 +123,7 @@
             "<p>\n\
             \  <inline-formula><alternatives>\n\
             \  <tex-math><![CDATA[\\sigma|_{\\{x\\}}]]></tex-math>\n\
+            \  </alternatives></inline-formula>\n\
             \</p>"
             =?> para (math "\\sigma|_{\\{x\\}}")
           , test jats "math ml only" $
@@ -112,5 +161,20 @@
             \  <title><inline-graphic mimetype=\"image\" mime-subtype=\"jpeg\" xlink:href=\"imgs/foo.jpg\" /></title>\n\
             \</sec>"
             =?> header 1 (image "imgs/foo.jpg" "" mempty)
+          ]
+
+        , testGroup "metadata"
+          [ test jats "abstract" $
+            T.unlines [ "<front>"
+                      , "<article-meta>"
+                      , "<abstract>"
+                      , "<p>Paragraph 1</p>"
+                      , "<p>Paragraph 2</p>"
+                      , "</abstract>"
+                      , "</article-meta>"
+                      , "</front>"
+                      ] =?>
+            let abstract = para "Paragraph 1" <> para "Paragraph 2"
+            in setMeta "abstract" abstract $ doc mempty
           ]
         ]
diff --git a/test/Tests/Readers/Jira.hs b/test/Tests/Readers/Jira.hs
new file mode 100644
--- /dev/null
+++ b/test/Tests/Readers/Jira.hs
@@ -0,0 +1,205 @@
+{-# LANGUAGE OverloadedStrings   #-}
+{-# LANGUAGE ScopedTypeVariables #-}
+{- |
+   Module      : Tests.Readers.Jira
+   Copyright   : © 2019-2024 Albert Krewinel
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : Albert Krewinkel <albert+pandoc@tarleb.com>
+   Stability   : alpha
+   Portability : portable
+
+Tests for the RST reader.
+-}
+module Tests.Readers.Jira (tests) where
+
+import Prelude hiding (unlines)
+import Data.Text (Text, unlines)
+import Test.Tasty (TestTree, testGroup)
+import Test.Tasty.HUnit (HasCallStack)
+import Tests.Helpers (ToString, purely, test, (=?>))
+import Text.Pandoc (def)
+import Text.Pandoc.Readers.Jira (readJira)
+import Text.Pandoc.Builder
+
+jira :: Text -> Pandoc
+jira = purely $ readJira def
+
+infix 4 =:
+(=:) :: (ToString c, HasCallStack)
+     => String -> (Text, c) -> TestTree
+(=:) = test jira
+
+tests :: [TestTree]
+tests =
+  [ testGroup "para"
+    [ "Simple sentence" =:
+      "Hello, World!" =?> para "Hello, World!"
+
+    , "leading blank lines" =:
+      "\n\ntext" =?> para "text"
+    ]
+
+  , testGroup "header"
+    [ "header" =:
+      "h1. Main\n" =?> header 1 "Main"
+    ]
+
+  , testGroup "list"
+    [ "simple list" =:
+      "* foo\n* bar\n" =?> bulletList [para "foo", para "bar"]
+
+    , "list with minus as bullets" =:
+      "- foo\n- bar\n" =?> bulletList [para "foo", para "bar"]
+
+    , "ordered list / enumeration" =:
+      "# first\n# second\n" =?> orderedList [para "first", para "second"]
+    ]
+
+  , testGroup "block quote"
+    [ "simple block quote" =:
+      "bq. _Don't_ quote me on this." =?>
+      blockQuote (para $ emph "Don't" <> space <> "quote me on this.")
+
+    , "block quote between paragraphs" =:
+      unlines [ "Regular text."
+              , "bq.This is a blockquote"
+              , "More text."
+              ] =?>
+      mconcat [ para "Regular text."
+              , blockQuote (para "This is a blockquote")
+              , para "More text."
+              ]
+    ]
+
+  , testGroup "table"
+    [ "table without header" =:
+      "| one | two |\n| three | four |\n" =?>
+      simpleTable []
+                  [ [para "one", para "two"]
+                  , [para "three", para "four"]]
+
+    , "table with header" =:
+      "|| one || two ||\n| three | four |\n| five | six |\n" =?>
+      simpleTable [para "one", para "two"]
+                  [ [para "three", para "four"]
+                  , [para "five", para "six"]]
+
+    , "table with column header" =:
+      "|| language | haskell | lua |\n|| type | static | dynamic |\n" =?>
+      simpleTable []
+                  [ [para "language", para "haskell", para "lua"]
+                  , [para "type", para "static", para "dynamic"]]
+
+    , "table after paragraph" =:
+      "*tabletest*\n||Name|\n|Test|\n" =?>
+      para (strong "tabletest") <>
+      simpleTable [para "Name"] [[para "Test"]]
+    ]
+
+  , testGroup "panel"
+    [ "simple panel" =:
+      "{panel}\nInterviewer: Jane Doe{panel}\n" =?>
+      divWith ("", ["panel"], []) (para "Interviewer: Jane Doe")
+    ]
+
+  , testGroup "inlines"
+    [ "emphasis" =:
+      "*quid pro quo*" =?>
+      para (strong "quid pro quo")
+
+    , "deleted" =:
+      "-old-" =?>
+      para (strikeout "old")
+
+    , "monospaced" =:
+      "{{this *is* monospace}}" =?>
+      para (code "this is monospace")
+
+    , "sub- and superscript" =:
+      "HCO ~3~^-^" =?>
+      para ("HCO " <> subscript "3" <> superscript "-")
+
+    , "citation" =:
+      "Et tu, Brute? ??Caesar??" =?>
+      para ("Et tu, Brute? — " <> emph "Caesar")
+
+    , "color" =:
+      "This is {color:red}red{color}." =?>
+      para ("This is " <> spanWith ("", [], [("color", "red")]) "red" <> ".")
+
+    , "hexcolor" =:
+      "{color:#00875A}green{color}" =?>
+      para (spanWith ("", [], [("color", "#00875A")]) "green")
+
+    , "linebreak" =:
+      "first\nsecond" =?>
+      para ("first" <> linebreak <> "second")
+
+    , testGroup "links"
+      [ "external" =:
+        "[Example|https://example.org]" =?>
+        para (link "https://example.org" "" "Example")
+
+      , "URL in alias" =:
+        "[See https://example.com|https://example.com]" =?>
+        para (link "https://example.com" "" "See https://example.com")
+
+      , "email" =:
+        "[mailto:me@example.org]" =?>
+        para (link "mailto:me@example.org" "" "me@example.org")
+
+      , "email with description" =:
+        "[email|mailto:me@example.org]" =?>
+        para (link "mailto:me@example.org" "" "email")
+
+      , "attachment" =:
+        "[^example.txt]" =?>
+        para (linkWith ("", ["attachment"], []) "example.txt" "" "example.txt")
+
+      , "attachment with description" =:
+        "[an example^example.txt]" =?>
+        para (linkWith ("", ["attachment"], []) "example.txt" "" "an example")
+
+      , "user" =:
+        "[~johndoe]" =?>
+        para (linkWith ("", ["user-account"], []) "~johndoe" "" "~johndoe")
+
+      , "user with description" =:
+        "[John Doe|~johndoe]" =?>
+        para (linkWith ("", ["user-account"], []) "~johndoe" "" "John Doe")
+
+      , "'smart' link" =:
+        "[x|http://example.com|smart-link]" =?>
+        para (linkWith ("", ["smart-link"], []) "http://example.com" "" "x")
+
+      , "'smart' card" =:
+        "[x|http://example.com|smart-card]" =?>
+        para (linkWith ("", ["smart-card"], []) "http://example.com" "" "x")
+      ]
+
+    , "image" =:
+      "!https://example.com/image.jpg!" =?>
+      para (image "https://example.com/image.jpg" "" mempty)
+
+    , "thumbnail image" =:
+      "!image.jpg|thumbnail!" =?>
+      para (imageWith ("", ["thumbnail"], []) "image.jpg" "" mempty)
+
+    , "image with attributes" =:
+      "!image.gif|align=right, vspace=4, title=Hello!" =?>
+      let attr = ("", [], [("align", "right"), ("vspace", "4")])
+      in para $ imageWith attr "image.gif" "Hello" mempty
+
+    , "inserted text" =:
+      "+the new version+" =?>
+      para (underline "the new version")
+
+    , "HTML entity" =:
+      "me &amp; you" =?> para "me & you"
+
+    , "non-strikeout dashes" =:
+      "20.09-15 2-678" =?>
+      para "20.09-15 2-678"
+    ]
+  ]
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,13 +1,21 @@
 {-# LANGUAGE OverloadedStrings #-}
+{- |
+   Module      : Tests.Readers.LaTeX
+   Copyright   : © 2006-2024 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 Data.Text (Text)
 import qualified Data.Text as T
-import qualified Text.Pandoc.UTF8 as UTF8
-import Text.Pandoc.Readers.LaTeX (tokenize, untokenize)
 import Test.Tasty
-import Test.Tasty.HUnit
-import Test.Tasty.QuickCheck
+import Test.Tasty.HUnit (HasCallStack)
 import Tests.Helpers
 import Text.Pandoc
 import Text.Pandoc.Arbitrary ()
@@ -18,29 +26,26 @@
                    readerExtensions = getDefaultExtensions "latex" }
 
 infix 4 =:
-(=:) :: ToString c
+(=:) :: (ToString c, HasCallStack)
      => String -> (Text, c) -> TestTree
 (=:) = test latex
 
-simpleTable' :: [Alignment] -> [[Blocks]] -> Blocks
-simpleTable' aligns = table "" (zip aligns (repeat 0.0))
-                      (map (const mempty) aligns)
+table' :: [Alignment] -> [Row] -> Blocks
+table' aligns rows
+  = table emptyCaption
+          (zip aligns (repeat ColWidthDefault))
+          (TableHead nullAttr [])
+          [TableBody nullAttr 0 [] rows]
+          (TableFoot nullAttr [])
 
-tokUntokRt :: String -> Bool
-tokUntokRt s = untokenize (tokenize "random" t) == t
-  where t = T.pack s
+simpleTable' :: [Alignment] -> [[Blocks]] -> Blocks
+simpleTable' aligns rows
+  = table' aligns (map toRow rows)
+  where
+    toRow = Row nullAttr . map simpleCell
 
 tests :: [TestTree]
-tests = [ testGroup "tokenization"
-          [ testCase "tokenizer round trip on test case" $ do
-                 orig <- T.pack <$> UTF8.readFile "../test/latex-reader.latex"
-                 let new = untokenize $ tokenize "../test/latex-reader.latex"
-                             orig
-                 assertEqual "untokenize . tokenize is identity" orig new
-          , testProperty "untokenize . tokenize is identity" tokUntokRt
-          ]
-
-        , testGroup "basic"
+tests = [ testGroup "basic"
           [ "simple" =:
             "word" =?> para "word"
           , "space" =:
@@ -118,6 +123,90 @@
           , "Table with vertical alignment argument" =:
             "\\begin{tabular}[t]{r|r}One & Two\\\\ \\end{tabular}" =?>
             simpleTable' [AlignRight,AlignRight] [[plain "One", plain "Two"]]
+          , "Table with multicolumn item" =:
+            "\\begin{tabular}{l c r}\\multicolumn{2}{c}{One} & Two\\\\ \\end{tabular}" =?>
+            table' [AlignLeft, AlignCenter, AlignRight]
+                   [ Row nullAttr [ cell AlignCenter (RowSpan 1) (ColSpan 2) (plain "One")
+                                  , simpleCell (plain "Two")
+                                  ]
+                   ]
+          , "table with multicolumn item (#6596)" =:
+            "\\begin{tabular}{l c r}One & \\multicolumn{2}{c}{Two} & \\\\ \\end{tabular}" =?>
+            table' [AlignLeft, AlignCenter, AlignRight]
+                   [ Row nullAttr [ simpleCell (plain "One")
+                                  , cell AlignCenter (RowSpan 1) (ColSpan 2) (plain "Two")
+                                  ]
+                   ]
+          , "Table with multirow item" =:
+            T.unlines ["\\begin{tabular}{c}"
+                      ,"\\multirow{2}{5em}{One}\\\\Two\\\\"
+                      ,"\\end{tabular}"
+                      ] =?>
+            table' [AlignCenter]
+                  [ Row nullAttr [ cell AlignDefault (RowSpan 2) (ColSpan 1) (plain "One") ]
+                  , Row nullAttr [ simpleCell (plain "Two") ]
+                  ]
+          , "Table with multirow item using full prototype" =:
+            T.unlines ["\\begin{tabular}{c}"
+                      ,"\\multirow[c]{2}[3]{5em}[1in]{One}\\\\Two\\\\"
+                      ,"\\end{tabular}"
+                      ] =?>
+            table' [AlignCenter]
+                  [ Row nullAttr [ cell AlignDefault (RowSpan 2) (ColSpan 1) (plain "One") ]
+                  , Row nullAttr [ simpleCell (plain "Two") ]
+                  ]
+          , "Table with nested multirow/multicolumn item" =:
+            T.unlines [ "\\begin{tabular}{c c c c}"
+                      , "\\multicolumn{3}{c}{\\multirow{2}{5em}{One}}&Two\\\\"
+                      , "\\multicolumn{2}{c}{} & & Three\\\\"
+                      , "Four&Five&Six&Seven\\\\"
+                      , "\\end{tabular}"
+                      ] =?>
+            table' [AlignCenter, AlignCenter, AlignCenter, AlignCenter]
+                   [ Row nullAttr [ cell AlignCenter (RowSpan 2) (ColSpan 3) (plain "One")
+                                  , simpleCell (plain "Two")
+                                  ]
+                   , Row nullAttr [ simpleCell (plain "Three") ]
+                   , Row nullAttr [ simpleCell (plain "Four")
+                                  , simpleCell (plain "Five")
+                                  , simpleCell (plain "Six")
+                                  , simpleCell (plain "Seven")
+                                  ]
+                   ]
+          , "Table with multicolumn header" =:
+            T.unlines [ "\\begin{tabular}{ |l|l| }"
+                      , "\\hline\\multicolumn{2}{|c|}{Header}\\\\"
+                      , "\\hline key & val\\\\"
+                      , "\\hline\\end{tabular}"
+                      ] =?>
+            table emptyCaption
+                  (zip [AlignLeft, AlignLeft] (repeat ColWidthDefault))
+                  (TableHead nullAttr [ Row nullAttr [cell AlignCenter (RowSpan 1) (ColSpan 2) (plain "Header")]])
+                  [TableBody nullAttr 0 [] [Row nullAttr [ simpleCell (plain "key")
+                                                         , simpleCell (plain "val")
+                                                         ]
+                                           ]
+                  ]
+                  (TableFoot nullAttr [])
+          , "Table with normal empty cells" =:
+            T.unlines [ "\\begin{tabular}{|r|r|r|}"
+                      , "A &   & B \\\\"
+                      , "  & C &"
+                      , "\\end{tabular}"
+                      ] =?>
+            table emptyCaption
+                  (replicate 3 (AlignRight, ColWidthDefault))
+                  (TableHead nullAttr [])
+                  [TableBody nullAttr 0 []
+                    [Row nullAttr [ simpleCell (plain "A")
+                                  , emptyCell
+                                  , simpleCell (plain "B")
+                                  ]
+                    ,Row nullAttr [ emptyCell
+                                  , simpleCell (plain "C")
+                                  , emptyCell
+                                  ]]]
+                  (TableFoot nullAttr [])
           ]
 
         , testGroup "citations"
@@ -156,10 +245,10 @@
           testGroup "Character Escapes"
           [ "Two-character escapes" =:
             mconcat ["^^" <> T.pack [i,j] | i <- hex, j <- hex] =?>
-            para (str ['\0'..'\255'])
+            para (str $ T.pack ['\0'..'\255'])
           , "One-character escapes" =:
             mconcat ["^^" <> T.pack [i] | i <- hex] =?>
-            para (str $ ['p'..'y']++['!'..'&'])
+            para (str $ T.pack $ ['p'..'y']++['!'..'&'])
           ]
         , testGroup "memoir scene breaks"
           [ "plainbreak" =:
@@ -242,7 +331,7 @@
                        }
 
 rt :: String -> Inlines
-rt = rawInline "latex"
+rt = rawInline "latex" . T.pack
 
 natbibCitations :: TestTree
 natbibCitations = testGroup "natbib"
diff --git a/test/Tests/Readers/Man.hs b/test/Tests/Readers/Man.hs
new file mode 100644
--- /dev/null
+++ b/test/Tests/Readers/Man.hs
@@ -0,0 +1,144 @@
+{-# LANGUAGE OverloadedStrings #-}
+{- |
+   Module      : Tests.Readers.Man
+   Copyright   : © 2018-2019 Yan Pas <yanp.bugz@gmail.com>,
+                   2018-2024 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 Data.Text (Text)
+import Test.Tasty
+import Test.Tasty.HUnit (HasCallStack)
+import Tests.Helpers
+import Text.Pandoc
+import Text.Pandoc.Arbitrary ()
+import Text.Pandoc.Builder
+
+man :: Text -> Pandoc
+man = purely $ readMan def
+
+infix 4 =:
+(=:) :: (ToString c, HasCallStack)
+     => String -> (Text, c) -> TestTree
+(=:) = test man
+
+toRow :: [Blocks] -> Row
+toRow = Row nullAttr . map simpleCell
+
+tests :: [TestTree]
+tests = [
+  -- .SH "HEllo bbb" "aaa"" as"
+  testGroup "Macros" [
+      "Bold" =:
+      ".B foo"
+      =?> para (strong "foo")
+    , "Italic" =:
+      ".I bar\n"
+      =?> para (emph "bar")
+    , "BoldItalic" =:
+      ".BI foo bar"
+      =?> para (strong (str "foo") <> emph (str "bar"))
+    , "H1" =:
+      ".SH The header\n"
+      =?> header 1 (text "The header")
+    , "H2" =:
+      ".SS \"The header 2\""
+      =?> header 2 (text "The header 2")
+    , "Macro args" =:
+      ".B \"single arg with \"\"Q\"\"\""
+      =?>para (strong $ text "single arg with \"Q\"")
+    , "Argument from next line" =:
+      ".B\nsingle arg with \"Q\""
+      =?>para (strong $ text "single arg with \"Q\"")
+    , "comment" =:
+      ".\\\"bla\naaa"
+      =?>para (str "aaa")
+    , "link" =:
+      ".BR aa (1)"
+      =?> para (strong (str "aa") <> str "(1)")
+    ],
+  testGroup "Escapes" [
+      "fonts" =:
+      "aa\\fIbb\\fRcc"
+      =?>para (str "aa" <> emph (str "bb") <> str "cc")
+    , "nested fonts" =:
+      "\\f[BI]hi\\f[I] there\\f[R]"
+      =?> para (emph (strong (text "hi") <> text " there"))
+    , "nested fonts 2" =:
+      "\\f[R]hi \\f[I]there \\f[BI]bold\\f[R] ok"
+      =?> para (text "hi " <> emph (text "there " <> strong (text "bold")) <>
+                                   text " ok")
+    , "skip" =:
+      "a\\%\\\n\\:b\\0"
+      =?>para (str "ab\8199")
+    , "replace" =:
+      "\\-\\ \\\\\\[lq]\\[rq]\\[em]\\[en]\\*(lq\\*(rq"
+      =?>para (text "- \\“”—–“”")
+    , "replace2" =:
+      "\\t\\e\\`\\^\\|\\'" =?>para (text "\\`\8202\8198'")
+    , "comment  with \\\"" =:
+      "Foo \\\" bar\n" =?>para (text "Foo")
+    , "comment with \\#" =:
+      "Foo\\#\nbar\n" =?>para (text "Foobar")
+    , "two letter escapes" =:
+      "\\(oA\\(~O" =?>para (text "ÅÕ")
+    , "bracketed escapes" =:
+      "\\[oA]\\[~O]\\[Do]\\[Ye]\\[product]\\[ul]" =?>para (text "ÅÕ$¥∏_")
+    , "unicode escapes" =:
+      "\\[u2020]" =?>para (text "†")
+    , "unicode escapes (combined)" =:
+      "\\[u0075_u0301]" =?>para (text "\250")
+    , "unknown escape (#5034)" =:
+       "\\9" =?>para (text "9")
+    ],
+  testGroup "Lists" [
+      "bullet" =:
+      ".IP \"\\[bu]\"\nfirst\n.IP \"\\[bu]\"\nsecond"
+      =?> bulletList [para $ str "first", para $ str "second"]
+    , "ordered" =:
+      ".IP 2 a\nfirst\n.IP 3 a\nsecond"
+      =?> orderedListWith (2,Decimal,DefaultDelim) [para $ str "first", para $ str "second"]
+    , "upper" =:
+      ".IP A) a\nfirst\n.IP B) a\nsecond"
+      =?> orderedListWith (1,UpperAlpha,OneParen) [para $ str "first", para $ str "second"]
+    , "nested" =:
+      ".IP \"\\[bu]\"\nfirst\n.RS\n.IP \"\\[bu]\"\n1a\n.IP \"\\[bu]\"\n1b\n.RE"
+      =?> bulletList [para (str "first") <> bulletList [para $ str "1a", para $ str "1b"]]
+    , "change in list style" =:
+      ".IP \\[bu]\nfirst\n.IP 1\nsecond"
+      =?> bulletList [para (str "first")] <>
+            orderedListWith (1,Decimal,DefaultDelim) [para (str "second")]
+    ],
+  testGroup "CodeBlocks" [
+      "cb1"=:
+      ".nf\naa\n\tbb\n.fi"
+      =?> codeBlock "aa\n\tbb"
+    ],
+  testGroup "Tables" [
+      "t1" =:
+      ".TS\nallbox;\nl l l.\na\tb\tc\nd\te\tf\n.TE"
+      =?> table
+            emptyCaption
+            (replicate 3 (AlignLeft, ColWidthDefault))
+            (TableHead nullAttr [])
+            [TableBody nullAttr 0 [] $ map toRow
+              [map (plain . str ) ["a", "b", "c"],
+               map (plain . str ) ["d", "e", "f"]]]
+            (TableFoot nullAttr []),
+      "longcell" =:
+      ".TS\n;\nr.\nT{\na\nb\nc d\nT}\nf\n.TE"
+      =?> table
+            emptyCaption
+            [(AlignRight, ColWidthDefault)]
+            (TableHead nullAttr [])
+            [TableBody nullAttr 0 [] $ map toRow [[plain $ text "a b c d"], [plain $ str "f"]]]
+            (TableFoot nullAttr [])
+    ]
+  ]
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,9 +1,21 @@
 {-# LANGUAGE OverloadedStrings #-}
+{- |
+   Module      : Tests.Readers.Markdown
+   Copyright   : © 2006-2024 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 Data.Text (Text, unpack)
 import qualified Data.Text as T
 import Test.Tasty
+import Test.Tasty.HUnit (HasCallStack)
 import Tests.Helpers
 import Text.Pandoc
 import Text.Pandoc.Arbitrary ()
@@ -17,16 +29,15 @@
 markdownSmart = purely $  readMarkdown def { readerExtensions =
                              enableExtension Ext_smart pandocExtensions }
 
-markdownCDL :: Text -> Pandoc
-markdownCDL = purely $ readMarkdown def { readerExtensions = enableExtension
-                 Ext_compact_definition_lists pandocExtensions }
-
 markdownGH :: Text -> Pandoc
-markdownGH = purely $ readMarkdown def {
-                readerExtensions = githubMarkdownExtensions }
+markdownGH = purely $ readMarkdown def {readerExtensions = enableExtension
+                 Ext_wikilinks_title_before_pipe githubMarkdownExtensions }
 
+markdownMMD :: Text -> Pandoc
+markdownMMD = purely $ readMarkdown def {
+                 readerExtensions = multimarkdownExtensions }
 infix 4 =:
-(=:) :: ToString c
+(=:) :: (ToString c, HasCallStack)
      => String -> (Text, c) -> TestTree
 (=:) = test markdown
 
@@ -37,11 +48,15 @@
        (unpack inp) (inp, doc $ para ils)
 
 autolink :: String -> Inlines
-autolink = autolinkWith nullAttr
+autolink = autolinkWith ("",["uri"],[])
 
 autolinkWith :: Attr -> String -> Inlines
-autolinkWith attr s = linkWith attr s "" (str s)
+autolinkWith attr s = linkWith attr s' "" (str s')
+  where s' = T.pack s
 
+wikilink :: Attr
+wikilink = (mempty, ["wikilink"], mempty)
+
 bareLinkTests :: [(Text, Inlines)]
 bareLinkTests =
   [ ("http://google.com is a search engine.",
@@ -70,10 +85,12 @@
   , ("http://en.wikipedia.org/wiki/Sprite_(computer_graphics)",
       autolink "http://en.wikipedia.org/wiki/Sprite_(computer_graphics)")
   , ("http://en.wikipedia.org/wiki/Sprite_[computer_graphics]",
-      link "http://en.wikipedia.org/wiki/Sprite_%5Bcomputer_graphics%5D" ""
+      linkWith ("",["uri"],[])
+        "http://en.wikipedia.org/wiki/Sprite_%5Bcomputer_graphics%5D" ""
         (str "http://en.wikipedia.org/wiki/Sprite_[computer_graphics]"))
   , ("http://en.wikipedia.org/wiki/Sprite_{computer_graphics}",
-      link "http://en.wikipedia.org/wiki/Sprite_%7Bcomputer_graphics%7D" ""
+      linkWith ("",["uri"],[])
+        "http://en.wikipedia.org/wiki/Sprite_%7Bcomputer_graphics%7D" ""
         (str "http://en.wikipedia.org/wiki/Sprite_{computer_graphics}"))
   , ("http://example.com/Notification_Center-GitHub-20101108-140050.jpg",
       autolink "http://example.com/Notification_Center-GitHub-20101108-140050.jpg")
@@ -155,6 +172,46 @@
             =?> para (code "*" <> space <> str "{.haskell" <> space <>
                       str ".special" <> space <> str "x=\"7\"}")
           ]
+        , testGroup "inline code in lists (regression tests for #6284)" $
+          let lists = [("ordered", "1. ", ol), ("bullet", "- ", ul)]
+              ol = orderedListWith (1, Decimal, Period)
+              ul = bulletList
+              items =
+                [ ("in text"                , ["If `(1) x`, then `2`"], [text "If " <> code "(1) x" <> text ", then " <> code "2"])
+                , ("at start"               , ["`#. x`"              ], [code "#. x"                                             ])
+                , ("at start"               , ["`- x`"               ], [code "- x"                                              ])
+                , ("after literal backticks", ["`x``#. x`"           ], [code "x``#. x"                                          ])
+                , ("after literal backticks", ["`x``- x`"            ], [code "x``- x"                                           ])
+                ]
+              lis = ["`text","y","x`"]
+              bldLsts w lsts txts
+                = let (res, res', f) =
+                         foldr (\((_, _, lt), lc) (acc, tacc, t) ->
+                             if lt [] == t []
+                             then (acc, lc : tacc, lt)
+                             else (join t tacc acc, [lc], lt))
+                           (mempty, [], mconcat)
+                           (zip lsts (map text txts))
+                      join t tacc acc = case tacc of
+                          [] -> acc
+                          [x] -> t [plain x] <> acc
+                          xs -> t (map w xs) <> acc
+                  in join f res' res
+          in ["code with list marker "<>mp<>" in " <> ln <> " list" =:
+              T.intercalate "\n" (map (lstr <>) istrs) =?> lbld (map plain iblds)
+              | (ln, lstr, lbld) <- lists, (mp, istrs, iblds) <- items]
+          <> [ "lists with newlines in backticks" =:
+               T.intercalate "\n" (zipWith (\i (_, lt, _) -> lt <> i) lis lsts)
+               =?> bldLsts plain lsts lis
+             | lsts <- [ [i, j, k] | i <- lists, j <- lists, k <- lists]
+             ]
+          <> [ "lists with blank lines and indent in backticks" =:
+               T.intercalate ("\n\n" <> T.replicate 4 " ") (zipWith (\i (_, lt, _) -> lt <> i) lis (l:ls))
+               <> "\n"
+               =?> let (_, _, f) = l
+                   in f . pure $ (para . text $ "`text") <> bldLsts para ls (drop 1 lis)
+             | (l:ls) <- [ [i, j, k] | i <- lists, j <- lists, k <- lists]
+             ]
         , testGroup "emph and strong"
           [ "two strongs in emph" =:
              "***a**b **c**d*" =?> para (emph (strong (str "a") <> str "b" <> space
@@ -197,7 +254,9 @@
           ]
         , testGroup "emoji"
           [ test markdownGH "emoji symbols" $
-            ":smile: and :+1:" =?> para (text "😄 and 👍")
+            ":smile: and :+1:" =?> para (spanWith ("", ["emoji"], [("data-emoji", "smile")]) "😄" <>
+                                         space <> str "and" <> space <>
+                                         spanWith ("", ["emoji"], [("data-emoji", "+1")]) "👍")
           ]
         , "unbalanced brackets" =:
             "[[[[[[[[[[[[hi" =?> para (text "[[[[[[[[[[[[hi")
@@ -242,6 +301,26 @@
             "[https://example.org(](url)" =?>
             para (link "url" "" (text "https://example.org("))
           ]
+        , testGroup "Github wiki links"
+          [ test markdownGH "autolink" $
+            "[[https://example.org]]" =?>
+            para (linkWith wikilink "https://example.org" "" (str "https://example.org"))
+          , test markdownGH "link with title" $
+            "[[title|https://example.org]]" =?>
+            para (linkWith wikilink "https://example.org" "" (str "title"))
+          , test markdownGH "bad link with title" $
+            "[[title|random string]]" =?>
+            para (linkWith wikilink "random string" "" (str "title"))
+          , test markdownGH "autolink not being a link" $
+            "[[Name of page]]" =?>
+            para (linkWith wikilink "Name of page" "" (text "Name of page"))
+          , test markdownGH "autolink not being a link with a square bracket" $
+            "[[Name of ]page]]" =?>
+            para (linkWith wikilink "Name of ]page" "" (text "Name of ]page"))
+          , test markdownGH "link with inline start should be a link" $
+            "[[t`i*t_le|https://example.org]]" =?>
+            para (linkWith wikilink "https://example.org" "" (str "t`i*t_le"))
+          ]
         , testGroup "Headers"
           [ "blank line before header" =:
             "\n# Header\n"
@@ -293,7 +372,61 @@
           , test markdownSmart "apostrophe after math" $ -- issue #1909
               "The value of the $x$'s and the systems' condition." =?>
               para (text "The value of the " <> math "x" <> text "\8217s and the systems\8217 condition.")
+          , test markdownSmart "unclosed double quote"
+            ("**this should \"be bold**"
+            =?> para (strong "this should \8220be bold"))
+          , test markdownSmart "single quote in inline note within single quotes" $ -- issue #11613
+              "'a^['b'.] c.'" =?>
+              para (singleQuoted ("a" <> note (para (singleQuoted "b" <> ".")) <> space <> "c."))
+          , test markdownSmart "double quote in inline note within double quotes" $ -- issue #11613
+              "\"a^[\"b\".] c.\"" =?>
+              para (doubleQuoted ("a" <> note (para (doubleQuoted "b" <> ".")) <> space <> "c."))
           ]
+        , testGroup "sub- and superscripts"
+          [
+            test markdownMMD "normal subscript"
+            ("H~2~"
+            =?> para ("H" <> subscript "2"))
+          , test markdownMMD "normal superscript"
+            ("x^3^"
+            =?> para ("x" <> superscript "3"))
+          , test markdownMMD "short subscript delimited by space"
+            ("O~2 is dangerous"
+            =?> para ("O" <> subscript "2" <> space <> "is dangerous"))
+          , test markdownMMD "short subscript delimited by newline"
+            ("O~2\n"
+            =?> para ("O" <> subscript "2"))
+          , test markdownMMD "short subscript delimited by EOF"
+            ("O~2"
+            =?> para ("O" <> subscript "2"))
+          , test markdownMMD "short subscript delimited by punctuation"
+            ("O~2."
+            =?> para ("O" <> subscript "2" <> "."))
+          , test markdownMMD "short subscript delimited by emph"
+            ("O~2*combustible!*"
+            =?> para ("O" <> subscript "2" <> emph "combustible!"))
+          , test markdownMMD "no nesting in short subscripts"
+            ("y~*2*"
+            =?> para ("y~" <> emph "2"))
+          , test markdownMMD "short superscript delimited by space"
+            ("x^2 = y"
+            =?> para ("x" <> superscript "2" <> space <> "= y"))
+          , test markdownMMD "short superscript delimited by newline"
+            ("x^2\n"
+            =?> para ("x" <> superscript "2"))
+          , test markdownMMD "short superscript delimited by ExF"
+            ("x^2"
+            =?> para ("x" <> superscript "2"))
+          , test markdownMMD "short superscript delimited by punctuation"
+            ("x^2."
+            =?> para ("x" <> superscript "2" <> "."))
+          , test markdownMMD "short superscript delimited by emph"
+            ("x^2*combustible!*"
+            =?> para ("x" <> superscript "2" <> emph "combustible!"))
+          , test markdownMMD "no nesting in short superscripts"
+            ("y^*2*"
+            =?> para ("y^" <> emph "2"))
+          ]
         , testGroup "footnotes"
           [ "indent followed by newline and flush-left text" =:
             "[^1]\n\n[^1]: my note\n\n     \nnot in note\n"
@@ -308,13 +441,13 @@
         , testGroup "lhs"
           [ test (purely $ readMarkdown def{ readerExtensions = enableExtension
                        Ext_literate_haskell pandocExtensions })
-              "inverse bird tracks and html" $
-              "> a\n\n< b\n\n<div>\n"
-              =?> codeBlockWith ("",["sourceCode","literate","haskell"],[]) "a"
+              "inverse bird tracks and html"
+              $ ("> a\n\n< b\n\n<div>\n" :: Text)
+              =?> codeBlockWith ("",["haskell","literate"],[]) "a"
                   <>
-                  codeBlockWith ("",["sourceCode","haskell"],[]) "b"
+                  codeBlockWith ("",["haskell"],[]) "b"
                   <>
-                  rawBlock "html" "<div>\n\n"
+                  divWith ("",[],[]) mempty
           ]
 -- the round-trip properties frequently fail
 --        , testGroup "round trip"
@@ -330,14 +463,14 @@
           , "blank space before first def" =:
             "foo1\n\n  :  bar\n\nfoo2\n\n  : bar2\n  : bar3\n" =?>
             definitionList [ (text "foo1", [para (text "bar")])
-                           , (text "foo2", [para (text "bar2"),
-                                            plain (text "bar3")])
+                           , (text "foo2", [plain (text "bar2"),
+                                            para (text "bar3")])
                            ]
           , "blank space before second def" =:
             "foo1\n  :  bar\n\nfoo2\n  : bar2\n\n  : bar3\n" =?>
             definitionList [ (text "foo1", [plain (text "bar")])
                            , (text "foo2", [plain (text "bar2"),
-                                            para (text "bar3")])
+                                            plain (text "bar3")])
                            ]
           , "laziness" =:
             "foo1\n  :  bar\nbaz\n  : bar2\n" =?>
@@ -347,8 +480,8 @@
                            ]
           , "no blank space before first of two paragraphs" =:
             "foo1\n  : bar\n\n    baz\n" =?>
-            definitionList [ (text "foo1", [para (text "bar") <>
-                                            para (text "baz")])
+            definitionList [ (text "foo1", [plain (text "bar") <>
+                                            plain (text "baz")])
                            ]
           , "first line not indented" =:
             "foo\n: bar\n" =?>
@@ -361,14 +494,6 @@
             divWith nullAttr (definitionList
               [ (text "foo", [bulletList [plain (text "bar")]]) ])
           ]
-        , testGroup "+compact_definition_lists"
-          [ test markdownCDL "basic compact list" $
-            "foo1\n:   bar\n    baz\nfoo2\n:   bar2\n" =?>
-            definitionList [ (text "foo1", [plain (text "bar" <> softbreak <>
-                                                     text "baz")])
-                           , (text "foo2", [plain (text "bar2")])
-                           ]
-          ]
         , testGroup "lists"
           [ "issue #1154" =:
               " -  <div>\n    first div breaks\n    </div>\n\n    <button>if this button exists</button>\n\n    <div>\n    with this div too.\n    </div>\n"
@@ -403,7 +528,7 @@
                         , citationPrefix  = []
                         , citationSuffix  = []
                         , citationMode    = AuthorInText
-                        , citationNoteNum = 0
+                        , citationNoteNum = 1
                         , citationHash    = 0
                         }
                 ] "@item1")
@@ -413,12 +538,12 @@
                         , citationPrefix  = []
                         , citationSuffix  = []
                         , citationMode    = AuthorInText
-                        , citationNoteNum = 0
+                        , citationNoteNum = 1
                         , citationHash    = 0
                         }
                 ] "@1657:huyghens")
           ]
-        , let citation = cite [Citation "cita" [] [] AuthorInText 0 0] (str "@cita")
+        , let citation = cite [Citation "cita" [] [] AuthorInText 1 0] (str "@cita")
           in testGroup "footnote/link following citation" -- issue #2083
           [ "footnote" =:
               T.unlines [ "@cita[^note]"
@@ -455,8 +580,15 @@
           , "regular citation" =:
               "@cita [foo]" =?>
               para (
-                cite [Citation "cita" [] [Str "foo"] AuthorInText 0 0]
+                cite [Citation "cita" [] [Str "foo"] AuthorInText 1 0]
                   (str "@cita" <> space <> str "[foo]")
               )
           ]
+      , testGroup "figures"
+        [ "latex placement" =:
+          "![caption](img.jpg){latex-placement=\"htbp\" alt=\"alt text\"}" =?>
+          figureWith ("", [], [("latex-placement", "htbp")])
+            (simpleCaption $ plain "caption")
+            (plain $ image (T.pack "img.jpg") (T.pack "") (text "alt text"))
         ]
+      ]
diff --git a/test/Tests/Readers/Mdoc.hs b/test/Tests/Readers/Mdoc.hs
new file mode 100644
--- /dev/null
+++ b/test/Tests/Readers/Mdoc.hs
@@ -0,0 +1,321 @@
+{-# LANGUAGE OverloadedStrings #-}
+{- |
+   Module      : Tests.Readers.Mdoc
+   Copyright   : © 2024 Evan Silberman
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : 
+   Stability   : alpha
+   Portability : portable
+
+Tests for the Mdoc reader.
+-}
+
+module Tests.Readers.Mdoc (tests) where
+
+import Data.Text (Text)
+import qualified Data.Text as T
+import Test.Tasty
+import Test.Tasty.HUnit (HasCallStack)
+import Tests.Helpers
+import Text.Pandoc
+import Text.Pandoc.Arbitrary ()
+import Text.Pandoc.Builder
+
+mdoc :: Text -> Pandoc
+mdoc = purely $ readMdoc def
+
+infix 4 =:
+(=:) :: (ToString c, HasCallStack)
+     => String -> (Text, c) -> TestTree
+(=:) = test mdoc
+
+cls :: Text -> Attr
+cls x = (mempty, [x], mempty)
+
+tests :: [TestTree]
+tests = [
+  testGroup "one-line enclosures"
+    [ "Dq" =:
+        ".Dq hello world" =?>
+        para (doubleQuoted "hello world")
+    , "Sq" =:
+        ".Sq hello world" =?>
+        para (singleQuoted "hello world")
+    , "empty" =:
+        ".Dq" =?>
+        para (doubleQuoted mempty)
+    , "nested" =:
+        ".Dq Pq hello world" =?>
+        para (doubleQuoted "(hello world)")
+    , "nested with closing delimiters" =:
+        ".Dq Pq hi mom !" =?>
+        para (doubleQuoted "(hi mom)" <> "!")
+    , "nested multiline enclosure" =:
+        ".Dq Po a \\&; b \\&; c Pc ." =?>
+        para (doubleQuoted "(a ; b ; c)" <> ".")
+    , "with inlines" =:
+        ".Dq hello Sy world ." =?>
+        para (doubleQuoted ("hello" <> space <> strong "world" <> "."))
+    , "with text production" =:
+        ".Dq I love the St -iso8601 standard!" =?>
+        para (doubleQuoted "I love the ISO 8601 standard!")
+    , "with Ns" =:
+        ".Op , Ns Ar value ..." =?>
+        para ("[," <> (codeWith (cls "variable") "value ...") <> "]")
+    , "ending with open delimiter" =:
+        ".Dq hi (" =?>
+        para (doubleQuoted "hi (")
+    ]
+  , testGroup "multiline enclosures"
+    [ "nested multiline" =:
+        T.unlines [".Bo", ".Po", "hi", ".Pc", ".Bc"] =?>
+        para ("[(hi)]")
+    , "nested on one line" =:
+        ".Bo Po hi Pc Bc" =?>
+        para ("[(hi)]")
+    , "with wacky delimiters" =:
+        ".Bo ( | hi ! Bc ?" =?>
+        para ("([| hi!]?")
+    ]
+  , testGroup "simple inlines"
+    [ "Sy" =:
+        ".Sy hello world" =?>
+        para (strong "hello world")
+    , "Em" =:
+        ".Em hello world" =?>
+        para (emph "hello world")
+    , "Ev" =:
+        ".Ev HELLO_WORLD ," =?>
+        para (codeWith (cls "Ev") "HELLO_WORLD" <> ",")
+    , "Ar" =:
+        ".Ar ) z" =?>
+        para (codeWith (cls "variable") "file ..." <> ") " <> codeWith (cls "variable") "z")
+    , "In" =:
+        ".In ( math.h ) b c" =?>
+        para ("(" <> codeWith (cls "In") "<math.h>" <> ") b c")
+    , "Mt" =:
+        ".Mt a@example.org , b@example.org" =?>
+        para ((link "mailto:a@example.org" "" "a@example.org") <>
+               "," <> space <> (link "mailto:b@example.org" "" "b@example.org"))
+    , "No" =:
+        ".No ( hello , world ! )" =?>
+        para "(hello, world!)"
+    , "empty Pa with closing punctuation" =:
+        ".Pa ) z" =?>
+        para (spanWith (cls "Pa") "~" <> ")" <> space <> spanWith (mempty, ["Pa"], mempty) "z")
+    , "delimiters" =:
+        ".Sy ( hello world )" =?>
+        para (mconcat ["(", strong "hello world", ")"])
+    , "multiple" =:
+        ".Sy hello Em world" =?>
+        para (strong "hello" <> space <> emph "world")
+    ]
+  , testGroup "Fl"
+    [ "simple" =:
+        ".Fl w" =?>
+        para (codeWith (cls "Fl") "-w")
+    , "multiple" =:
+        ".Fl W all" =?>
+        para (codeWith (cls "Fl") "-W" <> space <> codeWith (cls "Fl") "-all")
+    , "empty with following macro" =:
+        ".Fl Cm x" =?>
+        para (codeWith (cls "Fl") "-" <> codeWith (cls "Cm") "x")
+    , "enclosed with following macro" =:
+        ".Pq Fl Cm x" =?>
+        para ("(" <> codeWith (cls "Fl") "-" <> codeWith (cls "Cm") "x" <> ")")
+    -- XXX this is a mandoc delta, the period is meant to land outside
+    -- the enclosure. parseInline has learned how to defer eols but not
+    -- closing delimiters
+    , "enclosed with following delimiters" =:
+        ".Pq Fl x ." =?>
+        para ("(" <> codeWith (cls "Fl") "-x" <> ".)")
+    , "following Ns" =:
+        ".Fl W Ns Cm all" =?>
+        para (codeWith (cls "Fl") "-W" <> codeWith (cls "Cm") "all")
+    , "GNU" =:
+        ".Fl -help" =?>
+        para (codeWith (cls "Fl") "--help")
+    , "GNU escaped" =:
+        ".Fl \\-help" =?>
+        para (codeWith (cls "Fl") "--help")
+    , "GNU Fl Fl" =:
+        ".Fl Fl help" =?>
+        para (codeWith (cls "Fl") "--help")
+    , "punctuation" =:
+        ".Op Fl a | b" =?>
+        para ("[" <> codeWith (cls "Fl") "-a" <> " | " <> codeWith (cls "Fl") "-b" <> "]")
+    , "middle close paren" =:
+        ".Fl a ) z" =?>
+        para (codeWith (cls "Fl") "-a" <> ") " <> codeWith (cls "Fl") "-z")
+    , "empty with close paren" =:
+        ".Fl ) z" =?>
+        para (codeWith (cls "Fl") "-" <> ") " <> codeWith (cls "Fl") "-z")
+    , "empty with pipe" =:
+        ".Fl | z" =?>
+        para (codeWith (cls "Fl") "-" <> " | " <> codeWith (cls "Fl") "-z")
+    , "empty with parens" =:
+        ".Fl ( )" =?>
+        para ("(" <> codeWith (cls "Fl") "-" <> ")")
+    ]
+  , testGroup "links"
+    [ "basic" =:
+        ".Lk href name" =?>
+        para (link "href" "" "name")
+    , "complicated" =:
+        ".Lk , ( href name )" =?>
+        para ("," <> space <> "(" <> link "href" "" "name" <> ")")
+    , "unnamed" =:
+        ".Lk href" =?>
+        para (link "href" "" "href")
+    ]
+  , testGroup "Ns macro"
+    [ "at the beginning of a macro line (mandoc delta)" =:
+        T.unlines [".Op before", ".Ns Op after"] =?>
+        para "[before] [after]"  -- mandoc: warning
+    , "after a block closing macro" =:
+        T.unlines [".Oo before", ".Oc Ns Op after"] =?>
+        para "[before][after]"
+    , "in the middle of a macro line" =:
+        ".Oo before Oc Ns Op after" =?>
+        para "[before][after]"
+    , "before closing punctuation" =:
+        ".Oo before Oc Ns : Op after" =?>
+        para "[before]: [after]"  -- mandoc: warning
+    , "after closing punctuation" =:
+        ".Oo before Oc : Ns Op after" =?>
+        para "[before]:[after]"
+    , "at the end of a macro line" =:
+        T.unlines [".Oo before Oc Ns", ".Op after"] =?>
+        para "[before][after]"
+    , "at the end of a partial-implicit line" =:
+        T.unlines [".Op before Ns", ".Op after"] =?>
+        para "[before][after]"
+    , "normal words" =:
+        ".No no Ns ns No no" =?>
+        para ("nons" <> space <> "no")
+    , "opening punctuation" =:
+        ".No no Ns \"(\" ns No no" =?>
+        para ("no(ns" <> space <> "no")
+    , "closing punctuation" =:
+        ".No no \"Ns\" ns \")\" No no" =?>
+        para ("nons)" <> space <> "no")
+    ]
+  , testGroup "spacing mode"
+    [ "all text" =:
+        T.unlines ["a", ".Sm off", "b c", "d", ".Sm on", "e"] =?>
+        para ("a b c d e")
+    , "text around macro" =:
+        T.unlines ["a", ".Sm off", ".Sy b c", ".Sm on", "d"] =?>
+        para ("a" <> space <> strong "bc" <> space <> "d")
+    , "mulitple macros" =:
+        T.unlines ["a", ".Sm off", ".Sy b Em c", ".Sm on", "d"] =?>
+        para ("a" <> space <> strong "b" <> emph "c" <> space <> "d")
+    , "mulitple control lines" =:
+        T.unlines ["a", ".Sm off", ".Sy b", ".Em c", ".Sm on", "d"] =?>
+        para ("a" <> space <> strong "b" <> emph "c" <> space <> "d")
+    , "mixed control and text lines" =:
+        T.unlines ["a", ".Sm off", ".Sy b", "c", ".Em d", ".Sm on", "d"] =?>
+        para ("a" <> space <> strong "b" <> "c" <> emph "d" <> space <> "d")
+    , "delimiters" =:
+        T.unlines [".Sm off", ".Em a ", ".Em [ b | c ]", ".Sm on"] =?>
+        para (emph "a" <> "[" <> emph "b" <> "|" <> emph "c" <> "]")
+    ]
+  , testGroup "Ap macro"
+    [ "in the middle of a macro line" =:
+        ".Xr mandoc 1 Ap s" =?>
+        para (spanWith (cls "Xr") "mandoc(1)" <> "'s")
+    -- mandoc difference: the edge case of "Ap (" tested in this mandoc regress
+    -- isn't present in any actual OpenBSD base system manuals, where Ap is
+    -- only ever followed by a letter. Furthermore, "Ap" is generally uncommon
+    -- compared to "Ns '" (e.g. ".Xr mandoc 1 Ns 's"). I'm accepting a
+    -- difference from mandoc here because correctly suppressing space after
+    -- the "(" here would require more refactoring than I feel like doing at
+    -- time of writing.
+    -- per mandoc, should be: para (strong "bold" <> "'(" <> strong "bold")
+    , "with punctuation and called macro" =:
+        ".Sy bold Ap ( \"Sy\" bold" =?>
+        para (strong "bold" <> "'( " <> strong "bold")
+    ]
+  , testGroup "Pf macro"
+    [ "closing punctuation" =:
+        ".Pf . right ." =?>
+        para ".right."
+    , "double punctuation" =:
+        ".Pf . . double" =?>
+        para ".. double"
+    , "opening punctuation" =:
+        ".Pf ( left ." =?>
+        para "(left."
+    , "unparsed argument" =:
+        ".Pf Ar Sy gument " =?>
+        para ("Ar" <> strong "gument")
+    ]
+  , testGroup "text production"
+    [ "early NetBSD versions" =:
+        T.unlines [".Nx 0.9a", "and", ".Nx 9.4b"] =?>
+        para "NetBSD 0.9A and NetBSD 9.4b"
+    , "with Ns" =:
+        ".Ox Ns -specific" =?>
+        para "OpenBSD-specific"
+    , "with punctuation" =:
+        ".Fx ," =?>
+        para "FreeBSD,"
+    , "with argument and punctuation" =:
+        ".Fx 12.0 ." =?>
+        para "FreeBSD 12.0."
+    , "BSD alone" =:
+        ".Bx ." =?>
+        para "BSD."
+    , "BSD with macro" =:
+        ".Bx No rocks" =?>
+        para "BSD rocks"
+    , "BSD with version" =:
+        ".Bx 4.4 ," =?>
+        para "4.4BSD,"
+    , "BSD with variant" =:
+        ".Bx 4.3 tahoe !" =?>
+        para "4.3BSD-Tahoe!"
+    ]
+  , testGroup "inline punctuation"
+    [ testGroup "leading punctuation"
+      [ "open paren"           =: ".Em ( b"     =?> para ("(" <> emph "b")
+      , "open square bracket"  =: ".Em \"[\" b" =?> para ("[" <> emph "b")
+      , "pipe"                 =: ".Em | b"     =?> para ("|" <> space <> emph "b")
+      , "period"               =: ".Em . b"     =?> para ("." <> space <> emph "b")
+      , "comma"                =: ".Em , b"     =?> para ("," <> space <> emph "b")
+      , "semicolon"            =: ".Em ; b"     =?> para (";" <> space <> emph "b")
+      , "colon"                =: ".Em : b"     =?> para (":" <> space <> emph "b")
+      , "question mark"        =: ".Em ? b"     =?> para ("?" <> space <> emph "b")
+      , "exclamation"          =: ".Em ! b"     =?> para ("!" <> space <> emph "b")
+      , "close paren"          =: ".Em ) b"     =?> para (")" <> space <> emph "b")
+      , "close square bracket" =: ".Em \"]\" b" =?> para ("]" <> space <> emph "b")
+      ]
+    , testGroup "trailing punctuation"
+      [ "open paren"           =: ".Em a ("     =?> para (emph "a" <> space <> "(")
+      , "open square bracket"  =: ".Em a ["     =?> para (emph "a" <> space <> "[")
+      , "pipe"                 =: ".Em a |"     =?> para (emph "a" <> space <> "|")
+      , "period"               =: ".Em a ."     =?> para (emph "a" <> ".")
+      , "comma"                =: ".Em a ,"     =?> para (emph "a" <> ",")
+      , "semicolon"            =: ".Em a ;"     =?> para (emph "a" <> ";")
+      , "colon"                =: ".Em a :"     =?> para (emph "a" <> ":")
+      , "question mark"        =: ".Em a ?"     =?> para (emph "a" <> "?")
+      , "exclamation"          =: ".Em a !"     =?> para (emph "a" <> "!")
+      , "close parens"         =: ".Em a \")\"" =?> para (emph "a" <> ")")
+      , "close square bracket" =: ".Em a ]"     =?> para (emph "a" <> "]")
+      ]
+    , testGroup "middle punctuation"
+      [ "open paren"           =: ".Em a ( b"     =?> para (mconcat [emph "a", space, "(", emph "b"])
+      , "open square bracket"  =: ".Em a [ b"     =?> para (mconcat [emph "a", space, "[", emph "b"])
+      , "pipe"                 =: ".Em a \"|\" b" =?> para (mconcat [emph "a", space, "|", space, emph "b"])
+      , "period"               =: ".Em a . b"     =?> para (mconcat [emph "a", ".", space, emph "b"])
+      , "comma"                =: ".Em a , b"     =?> para (mconcat [emph "a", ",", space, emph "b"])
+      , "semicolon"            =: ".Em a ; b"     =?> para (mconcat [emph "a", ";", space, emph "b"])
+      , "colon"                =: ".Em a \":\" b" =?> para (mconcat [emph "a", ":", space, emph "b"])
+      , "question mark"        =: ".Em a ? b"     =?> para (mconcat [emph "a", "?", space, emph "b"])
+      , "exclamation"          =: ".Em a ! b"     =?> para (mconcat [emph "a", "!", space, emph "b"])
+      , "close paren"          =: ".Em a ) b"     =?> para (mconcat [emph "a", ")", space, emph "b"])
+      , "close square bracket" =: ".Em a ] b"     =?> para (mconcat [emph "a", "]", space, emph "b"])
+      ]
+    ]
+  ]
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,17 +1,26 @@
 {-# LANGUAGE OverloadedStrings #-}
+{- |
+   Module      : Tests.Readers.Muse
+   Copyright   : © 2017-2020 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 Data.List (intersperse)
 import Data.Text (Text)
 import qualified Data.Text as T
 import Test.Tasty
--- import Test.Tasty.QuickCheck
+import Test.Tasty.HUnit (HasCallStack)
 import Tests.Helpers
 import Text.Pandoc
 import Text.Pandoc.Arbitrary ()
 import Text.Pandoc.Builder
-import Text.Pandoc.Shared (underlineSpan)
--- import Text.Pandoc.Walk (walk)
 
 amuse :: Text -> Pandoc
 amuse = purely $ readMuse def { readerExtensions = extensionsFromList [Ext_amuse]}
@@ -20,34 +29,23 @@
 emacsMuse = purely $ readMuse def { readerExtensions = emptyExtensions }
 
 infix 4 =:
-(=:) :: ToString c
+(=:) :: (ToString c, HasCallStack)
      => String -> (Text, c) -> TestTree
 (=:) = test amuse
 
 spcSep :: [Inlines] -> Inlines
 spcSep = mconcat . intersperse space
 
-{-
--- Tables and code blocks don't round-trip yet
-
-removeTables :: Block -> Block
-removeTables (Table{}) = Para [Str "table was here"]
-removeTables x = x
-
--- Demand that any AST produced by Muse reader and written by Muse writer can be read back exactly the same way.
--- Currently we remove code blocks and tables and compare third rewrite to the second.
--- First and second rewrites are not equal yet.
-roundTrip :: Block -> Bool
-roundTrip b = d'' == d'''
-  where d = walk removeTables $ Pandoc nullMeta [b]
-        d' = rewrite d
-        d'' = rewrite d'
-        d''' = rewrite d''
-        rewrite = amuse . T.pack . (++ "\n") . T.unpack .
-                  (purely $ writeMuse def { writerExtensions = extensionsFromList [Ext_amuse]
-                                          , writerWrapText = WrapPreserve
-                                          })
--}
+simpleTable' :: Int -> Caption -> [Blocks] -> [[Blocks]] -> Blocks
+simpleTable' n capt headers rows
+  = table capt
+          (replicate n (AlignDefault, ColWidthDefault))
+          (TableHead nullAttr $ toHeaderRow headers)
+          [TableBody nullAttr 0 [] $ map toRow rows]
+          (TableFoot nullAttr [])
+  where
+    toRow = Row nullAttr . map simpleCell
+    toHeaderRow l = [toRow l | not (null l)]
 
 tests :: [TestTree]
 tests =
@@ -62,6 +60,13 @@
         "*Foo bar*" =?>
         para (emph . spcSep $ ["Foo", "bar"])
 
+      , "Newline in the beginning of emphasis" =:
+        "*\nFoo bar*" =?>
+        para (text "*\nFoo bar*")
+      , "Newline in the end of emphasis" =:
+        "*Foo bar\n*" =?>
+        para (text "*Foo bar\n*")
+
       , "Comma after closing *" =:
         "Foo *bar*, baz" =?>
         para ("Foo " <> emph "bar" <> ", baz")
@@ -74,6 +79,10 @@
         "Foo x*bar* baz" =?>
         para "Foo x*bar* baz"
 
+      , "Digit after closing *" =:
+        "Foo *bar*0 baz" =?>
+        para "Foo *bar*0 baz"
+
       , "Emphasis tag" =:
         "<em>Foo bar</em>" =?>
         para (emph . spcSep $ ["Foo", "bar"])
@@ -88,8 +97,48 @@
           "***strength***" =?>
           para (strong . emph $ "strength")
 
+      , "Strong inside emphasis" =:
+        "*foo **bar** baz*" =?>
+        para (emph (text "foo " <> strong (text "bar") <> text " baz"))
+
+      , "Emphasis inside strong" =:
+        "**foo *bar* baz**" =?>
+        para (strong (text "foo " <> emph (text "bar") <> text " baz"))
+
+      , "Opening asterisk can't be preceded by another one" =:
+        "**foo*" =?>
+        para "**foo*"
+
+      , "Asterisk between words does not terminate emphasis" =:
+        "*foo*bar*" =?>
+        para (emph "foo*bar")
+
+      , "Two asterisks between words do not terminate emphasis" =:
+        "*foo**bar*" =?>
+        para (emph "foo**bar")
+
+      , "Three asterisks between words do not terminate emphasis" =:
+        "*foo***bar*" =?>
+        para (emph "foo***bar")
+
+      , "Two asterisks between words do not terminate strong" =:
+        "**foo**bar**" =?>
+        para (strong "foo**bar")
+
+      , "Three asterisks between words do not terminate strong" =:
+        "**foo***bar**" =?>
+        para (strong "foo***bar")
+
+      , "Three asterisks between words do not terminate strong emphasis" =:
+        "***foo***bar***" =?>
+        para (strong . emph $ "foo***bar")
+
+      , "Six asterisks between words do not terminate strong emphasis" =:
+        "***foo******bar***" =?>
+        para (strong . emph $ "foo******bar")
+
       , test emacsMuse "Underline"
-        ("_Underline_" =?> para (underlineSpan "Underline"))
+        ("_Underline_" =?> para (underline "Underline"))
 
       , "Superscript tag" =: "<sup>Superscript</sup>" =?> para (superscript "Superscript")
 
@@ -115,9 +164,15 @@
 
       , "Linebreak" =: "Line <br>  break" =?> para ("Line" <> linebreak <> "break")
 
-      , test emacsMuse "Non-breaking space"
-        ("Foo~~bar" =?> para "Foo\160bar")
+      , "Trailing whitespace inside paragraph" =:
+        T.unlines [ "First line " -- trailing whitespace here
+                  , "second line"
+                  ]
+        =?> para "First line\nsecond line"
 
+      , "Non-breaking space" =: "Foo~~bar" =?> para "Foo\160bar"
+      , "Single ~" =: "Foo~bar" =?> para "Foo~bar"
+
       , testGroup "Code markup"
         [ "Code" =: "=foo(bar)=" =?> para (code "foo(bar)")
 
@@ -132,8 +187,14 @@
           "Foo =bar=, baz" =?>
           para (text "Foo " <> code "bar" <> text ", baz")
 
+        , "Not code if followed by digit" =:
+          "Foo =bar=0 baz" =?>
+          para (text "Foo =bar=0 baz")
+
         , "One character code" =: "=c=" =?> para (code "c")
 
+        , "Code with equal sign" =: "=foo = bar=" =?> para (code "foo = bar")
+
         , "Three = characters is not a code" =: "===" =?> para "==="
 
         , "Multiline code markup" =:
@@ -154,14 +215,37 @@
                     ] =?>
           para "foo =bar" <>
           para "baz= foo"
+
+        , "Code at the beginning of paragraph but not first column" =:
+          " - =foo=" =?> bulletList [ para $ code "foo" ]
         ]
 
       , "Code tag" =: "<code>foo(bar)</code>" =?> para (code "foo(bar)")
 
+      , "Math tag" =: "<math>\\sum_{i=0}^n i^2</math>" =?> para (math "\\sum_{i=0}^n i^2")
+
       , "Verbatim tag" =: "*<verbatim>*</verbatim>*" =?> para (emph "*")
 
       , "Verbatim inside code" =: "<code><verbatim>foo</verbatim></code>" =?> para (code "<verbatim>foo</verbatim>")
 
+      , "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")
+
+      , "RTL" =: "<<<foo bar>>>" =?> para (spanWith ("", [], [("dir", "rtl")]) "foo bar")
+      , "LTR" =: ">>>foo bar<<<" =?> para (spanWith ("", [], [("dir", "ltr")]) "foo bar")
+
+      -- <em> tag should match with the last </em> tag, not verbatim one
+      , "Nested \"</em>\" inside em tag" =: "<em>foo<verbatim></em></verbatim>bar</em>" =?> para (emph "foo</em>bar")
+
       , testGroup "Links"
         [ "Link without description" =:
           "[[https://amusewiki.org/]]" =?>
@@ -169,12 +253,33 @@
         , "Link with description" =:
           "[[https://amusewiki.org/][A Muse Wiki]]" =?>
           para (link "https://amusewiki.org/" "" (text "A Muse Wiki"))
+        , "Link with empty description" =:
+          "[[https://amusewiki.org/][]]" =?>
+          para (link "https://amusewiki.org/" "" (text ""))
         , "Image" =:
           "[[image.jpg]]" =?>
           para (image "image.jpg" "" mempty)
+        , "Closing bracket is not allowed in image filename" =:
+          "[[foo]bar.jpg]]" =?>
+          para (text "[[foo]bar.jpg]]")
         , "Image with description" =:
           "[[image.jpg][Image]]" =?>
           para (image "image.jpg" "" (text "Image"))
+        , "Image with space in filename" =:
+          "[[image name.jpg]]" =?>
+          para (image "image name.jpg" "" mempty)
+        , "Image with width" =:
+          "[[image.jpg 60]]" =?>
+          para (imageWith ("", [], [("width", "60%")]) "image.jpg" mempty mempty)
+        , "At least one space is required between image filename and width" =:
+          "[[image.jpg60]]" =?>
+          para (link "image.jpg60" mempty (str "image.jpg60"))
+        , "Left-aligned image with width" =:
+          "[[image.png 60 l][Image]]" =?>
+          para (imageWith ("", ["align-left"], [("width", "60%")]) "image.png" "" (str "Image"))
+        , "Right-aligned image with width" =:
+          "[[image.png 60 r][Image]]" =?>
+          para (imageWith ("", ["align-right"], [("width", "60%")]) "image.png" "" (str "Image"))
         , "Image link" =:
           "[[URL:image.jpg]]" =?>
           para (link "image.jpg" "" (str "image.jpg"))
@@ -187,21 +292,30 @@
         -- This test also makes sure '=' without whitespace is not treated as code markup
         , "No implicit links" =: "http://example.org/index.php?action=view&id=1"
                =?> para "http://example.org/index.php?action=view&id=1"
+        , "Link with empty URL" =: "[[][empty URL]]" =?> para (link "" "" (text "empty URL"))
+        , "No footnotes inside links" =:
+          "[[https://amusewiki.org/][foo[1]]" =?>
+          para (link "https://amusewiki.org/" "" (text "foo[1"))
+        , "Image inside link" =:
+          "[[https://amusewiki.org/][Image [[image.png][with it's own description]] inside link description]]" =?>
+          para (link "https://amusewiki.org/" "" (text "Image " <> image "image.png" "" (text "with it's own description") <> text " inside link description"))
+        , "Link inside image description" =:
+          "[[image.jpg][Image from [[https://amusewiki.org/]]]]" =?>
+          para (image "image.jpg" "" (text "Image from " <> link "https://amusewiki.org/" "" (str "https://amusewiki.org/")))
         ]
 
       , testGroup "Literal"
         [ test emacsMuse "Inline literal"
           ("Foo<literal style=\"html\">lit</literal>bar" =?>
           para (text "Foo" <> rawInline "html" "lit" <> text "bar"))
-        , "No literal in Text::Amuse" =:
-          "Foo<literal style=\"html\">lit</literal>bar" =?>
-          para "Foo<literal style=\"html\">lit</literal>bar"
+        , test emacsMuse "Single inline literal in paragraph"
+          ("<literal style=\"html\">lit</literal>" =?>
+          para (rawInline "html" "lit"))
         ]
       ]
 
   , testGroup "Blocks"
-      [ -- testProperty "Round trip" roundTrip,
-        "Block elements end paragraphs" =:
+      [ "Block elements end paragraphs" =:
         T.unlines [ "First paragraph"
                   , "----"
                   , "Second paragraph"
@@ -212,6 +326,14 @@
         , "5 dashes is a horizontal rule" =: "-----" =?> horizontalRule
         , "4 dashes with spaces is a horizontal rule" =: "----  " =?> horizontalRule
         ]
+      , testGroup "Page breaks"
+        [ "Page break" =:
+          "      * * * * *" =?>
+          divWith ("", [], [("style", "page-break-before: always;")]) mempty
+        , "Page break with trailing space" =:
+          "      * * * * * " =?>
+          divWith ("", [], [("style", "page-break-before: always;")]) mempty
+        ]
       , testGroup "Paragraphs"
         [ "Simple paragraph" =:
           T.unlines [ "First line"
@@ -234,6 +356,12 @@
         , "Quote" =:
           "  This is a quotation\n" =?>
           blockQuote (para "This is a quotation")
+        , "Indentation does not indicate quote inside quote tag" =:
+          T.unlines [ "<quote>"
+                    , "  Not a nested quote"
+                    , "</quote>"
+                    ] =?>
+          blockQuote (para "Not a nested quote")
         , "Multiline quote" =:
           T.unlines [ "  This is a quotation"
                     , "  with a continuation"
@@ -241,12 +369,35 @@
           blockQuote (para "This is a quotation\nwith a continuation")
         , testGroup "Div"
           [ "Div without id" =:
-            "<div>Foo bar</div>" =?>
+            T.unlines [ "<div>"
+                      , "Foo bar"
+                      , "</div>"
+                      ] =?>
             divWith nullAttr (para "Foo bar")
           , "Div with id" =:
-            "<div id=\"foo\">Foo bar</div>" =?>
+            T.unlines [ "<div id=\"foo\">"
+                      , "Foo bar"
+                      , "</div>"
+                      ] =?>
             divWith ("foo", [], []) (para "Foo bar")
           ]
+        , "Biblio" =:
+          T.unlines [ "<biblio>"
+                    , ""
+                    , "Author, *Title*, description"
+                    , ""
+                    , "Another author, *Another title*, another description"
+                    , ""
+                    , "</biblio>"
+                    ] =?>
+          divWith ("", ["biblio"], []) (para (text "Author, " <> emph "Title" <> ", description") <>
+                                        para (text "Another author, " <> emph "Another title" <> text ", another description"))
+        , "Play" =:
+          T.unlines [ "<play>"
+                    , "Foo bar"
+                    , "</play>"
+                    ] =?>
+          divWith ("", ["play"], []) (para "Foo bar")
         , "Verse" =:
           T.unlines [ "> This is"
                     , "> First stanza"
@@ -272,7 +423,45 @@
                     , "\160\160\160is here"
                     ]
         ]
-      , "Quote tag" =: "<quote>Hello, world</quote>" =?> blockQuote (para $ text "Hello, world")
+      , "Verse in list" =: " - > foo" =?> bulletList [ lineBlock [ "foo" ] ]
+      , "Verse line starting with emphasis" =: "> *foo* bar" =?> lineBlock [ emph "foo" <> text " bar" ]
+      , "Multiline verse in list" =:
+        T.unlines [ " - > foo"
+                  , "   > bar"
+                  ] =?>
+        bulletList [ lineBlock [ "foo", "bar" ] ]
+      , "Paragraph after verse in list" =:
+        T.unlines [ " - > foo"
+                  , "   bar"
+                  ] =?>
+        bulletList [ lineBlock [ "foo" ] <> para "bar" ]
+      , "Empty quote tag" =:
+        T.unlines [ "<quote>"
+                  , "</quote>"
+                  ]
+        =?> blockQuote mempty
+      , "Quote tag" =:
+        T.unlines [ "<quote>"
+                  , "Hello, world"
+                  , "</quote>"
+                  ]
+        =?> blockQuote (para $ text "Hello, world")
+      , "Nested quote tag" =:
+        T.unlines [ "<quote>"
+                  , "foo"
+                  , "<quote>"
+                  , "bar"
+                  , "</quote>"
+                  , "baz"
+                  , "</quote>"
+                  ] =?>
+        blockQuote (para "foo" <> blockQuote (para "bar") <> para "baz")
+      , "Indented quote inside list" =:
+        T.unlines [ " -  <quote>"
+                  , "    foo"
+                  , "    </quote>"
+                  ] =?>
+        bulletList [ blockQuote (para "foo") ]
       , "Verse tag" =:
         T.unlines [ "<verse>"
                   , ""
@@ -280,20 +469,24 @@
                   , "  One two three"
                   , ""
                   , "</verse>"
-                  , "<verse>Foo bar</verse>"
-                  , "<verse>"
-                  , "Foo bar</verse>"
-                  , "<verse>"
-                  , "   Foo</verse>"
                   ] =?>
         lineBlock [ ""
                   , text "Foo bar baz"
                   , text "\160\160One two three"
                   , ""
-                  ] <>
-        lineBlock [ "Foo bar" ] <>
-        lineBlock [ "Foo bar" ] <>
-        lineBlock [ "\160\160\160Foo" ]
+                  ]
+      , "Verse tag with empty line inside" =:
+        T.unlines [ "<verse>"
+                  , ""
+                  , "</verse>"
+                  ] =?>
+        lineBlock [ "" ]
+      , "Verse tag with verbatim close tag inside" =:
+        T.unlines [ "<verse>"
+                  , "<verbatim></verse></verbatim>"
+                  , "</verse>"
+                  ] =?>
+        lineBlock [ "</verse>" ]
       , testGroup "Example"
         [ "Braces on separate lines" =:
           T.unlines [ "{{{"
@@ -321,6 +514,20 @@
                     , "}}}"
                     ] =?>
           codeBlock "Example line\n"
+        , "Indented braces" =:
+          T.unlines [ " - {{{"
+                    , "   Example line"
+                    , "   }}}"
+                    ] =?>
+          bulletList [ codeBlock "Example line" ]
+        , "Tabs" =:
+          T.unlines [ "{{{"
+                    , "\t  foo"
+                    , "\t\t"
+                    , "\t  bar"
+                    , "}}}"
+                    ] =?>
+          codeBlock "  foo\n\t\n  bar"
         -- Amusewiki requires braces to be on separate line,
         -- this is an extension.
         , "One line" =:
@@ -357,6 +564,11 @@
                     , "   </example>"
                     ] =?>
           bulletList [ codeBlock "foo" ]
+        , "Empty example inside list" =:
+          T.unlines [ " - <example>"
+                    , "   </example>"
+                    ] =?>
+          bulletList [ codeBlock "" ]
         , "Example inside list with empty lines" =:
           T.unlines [ " - <example>"
                     , "   foo"
@@ -409,15 +621,19 @@
                     , "</literal>"
                     ] =?>
           rawBlock "latex" "\\newpage")
-        , "No literal blocks in Text::Amuse" =:
-          T.unlines [ "<literal style=\"latex\">"
-                    , "\\newpage"
-                    , "</literal>"
-                    ] =?>
-          para "<literal style=\"latex\">\n\\newpage\n</literal>"
         ]
-      , "Center" =: "<center>Hello, world</center>" =?> para (text "Hello, world")
-      , "Right" =: "<right>Hello, world</right>" =?> para (text "Hello, world")
+      , "Center" =:
+        T.unlines [ "<center>"
+                  , "Hello, world"
+                  , "</center>"
+                  ] =?>
+        para (text "Hello, world")
+      , "Right" =:
+        T.unlines [ "<right>"
+                  , "Hello, world"
+                  , "</right>"
+                  ] =?>
+        para (text "Hello, world")
       , testGroup "Comments"
         [ "Comment tag" =: "<comment>\nThis is a comment\n</comment>" =?> (mempty::Blocks)
         , "Line comment" =: "; Comment" =?> (mempty::Blocks)
@@ -425,6 +641,7 @@
         , "Text after empty comment" =: ";\nfoo" =?> para "foo" -- Make sure we don't consume newline while looking for whitespace
         , "Not a comment (does not start with a semicolon)" =: " ; Not a comment" =?> para (text "; Not a comment")
         , "Not a comment (has no space after semicolon)" =: ";Not a comment" =?> para (text ";Not a comment")
+        , "Not a comment (semicolon not in the first column)" =: " - ; foo" =?> bulletList [para "; foo"]
         ]
       , testGroup "Headers"
         [ "Part" =:
@@ -456,17 +673,57 @@
                     ] =?>
           blockQuote (para "* Hi")
         , "Headers consume anchors" =:
-          T.unlines [ "** Foo"
+          T.unlines [ "; A comment to make sure anchor is not parsed as a directive"
                     , "#bar"
+                    , "** Foo"
                     ] =?>
           headerWith ("bar",[],[]) 2 "Foo"
         , "Headers don't consume anchors separated with a blankline" =:
-          T.unlines [ "** Foo"
-                    , ""
+          T.unlines [ "; A comment to make sure anchor is not parsed as a directive"
                     , "#bar"
+                    , ""
+                    , "** Foo"
                     ] =?>
-          header 2 "Foo" <>
-          para (spanWith ("bar", [], []) mempty)
+          para (spanWith ("bar", [], []) mempty) <>
+          header 2 "Foo"
+        , "Headers terminate paragraph" =:
+          T.unlines [ "foo"
+                    , "* bar"
+                    ] =?>
+          para "foo" <> header 1 "bar"
+        , "Headers terminate lists" =:
+          T.unlines [ " - foo"
+                    , "* bar"
+                    ] =?>
+          bulletList [ para "foo" ] <>
+          header 1 "bar"
+        , test emacsMuse "Paragraphs terminate Emacs Muse headers"
+          (T.unlines [ "* Foo"
+                    , "bar"
+                    ] =?> header 1 "Foo" <> para "bar")
+        , "Paragraphs don't terminate Text::Amuse headers" =:
+          T.unlines [ "* Foo"
+                    , "bar"
+                    ] =?> header 1 "Foo\nbar"
+        , "Empty header" =:
+          T.unlines [ "Foo"
+                    , ""
+                    , "* "
+                    , ""
+                    , "bar"
+                    ] =?> para (text "Foo") <> header 1 "" <> para (text "bar")
+        , test (purely $ readMuse def { readerExtensions = extensionsFromList [Ext_amuse, Ext_auto_identifiers]})
+               "Auto identifiers"
+          (T.unlines [ "* foo"
+                     , "** Foo"
+                     , "* bar"
+                     , "** foo"
+                     , "* foo"
+                     ] =?> headerWith ("foo",[],[]) 1 "foo" <>
+                           headerWith ("foo-1",[],[]) 2 "Foo" <>
+                           headerWith ("bar",[],[]) 1 "bar" <>
+                           headerWith ("foo-2",[],[]) 2 "foo" <>
+                           headerWith ("foo-3",[],[]) 1 "foo")
         ]
       , testGroup "Directives"
         [ "Title" =:
@@ -480,6 +737,26 @@
         , test emacsMuse "Disable tables"
           ("#disable-tables t" =?>
           Pandoc (setMeta "disable-tables" (MetaInlines $ toList "t") nullMeta) mempty)
+        , "Multiple directives" =:
+          T.unlines [ "#title Document title"
+                    , "#subtitle Document subtitle"
+                    ] =?>
+          Pandoc (setMeta "title" (MetaInlines $ toList "Document title") $
+                  setMeta "subtitle" (MetaInlines $ toList "Document subtitle") nullMeta) mempty
+        , "Multiline directive" =:
+          T.unlines [ "#title Document title"
+                    , "#notes First line"
+                    , "and second line"
+                    , "#author Name"
+                    ] =?>
+          Pandoc (setMeta "title" (MetaInlines $ toList "Document title") $
+                  setMeta "notes" (MetaInlines $ toList "First line\nand second line") $
+                  setMeta "author" (MetaInlines $ toList "Name") nullMeta) mempty
+        , "Amusewiki's #cover is translated to pandoc's #cover-image" =:
+          "#cover cover.png" =?>
+          let titleInline = toList "cover.png"
+              meta = setMeta "cover-image" (MetaInlines titleInline) nullMeta
+          in Pandoc meta mempty
         ]
       , testGroup "Anchors"
         [ "Anchor" =:
@@ -500,6 +777,11 @@
                     , "#anchor and ends here."
                     ] =?>
           para ("Paragraph starts here\n" <> spanWith ("anchor", [], []) mempty <> "and ends here.")
+        , "Anchor with \"-\"" =:
+          T.unlines [ "; A comment to make sure anchor is not parsed as a directive"
+                    , "#anchor-id Target"
+                    ] =?>
+          para (spanWith ("anchor-id", [], []) mempty <> "Target")
         ]
       , testGroup "Footnotes"
         [ "Simple footnote" =:
@@ -510,6 +792,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]"
                     , ""
@@ -517,6 +816,15 @@
                     ] =?>
           para (text "Start recursion here" <>
                 note (para "Recursion continues here[1]"))
+        , "Nested footnotes" =:
+          T.unlines [ "Footnote: [1]"
+                    , ""
+                    , "[1] Nested: [2]"
+                    , ""
+                    , "[2] No recursion: [1]"
+                    ] =?>
+          para (text "Footnote: " <>
+                note (para (text "Nested: " <> note (para $ text "No recursion: [1]"))))
         , "No zero footnotes" =:
           T.unlines [ "Here is a footnote[0]."
                     , ""
@@ -538,15 +846,51 @@
                       , "[1] First footnote paragraph"
                       , ""
                       , "    Second footnote paragraph"
+                      , "with continuation"
+                      , ""
                       , "Not a note"
                       , "[2] Second footnote"
                       ] =?>
             para (text "Multiparagraph" <>
                   note (para "First footnote paragraph" <>
-                        para "Second footnote paragraph") <>
+                        para "Second footnote paragraph\nwith continuation") <>
                   text " footnotes" <>
                   note (para "Second footnote")) <>
             para (text "Not a note")
+
+          -- Verse requires precise indentation, so it is good to test indentation requirements
+          , "Note continuation with verse" =:
+            T.unlines [ "Foo[1]"
+                      , ""
+                      , "[1] Bar"
+                      , ""
+                      , "    > Baz"
+                      ] =?>
+            para ("Foo" <> note (para "Bar" <> lineBlock ["Baz"]))
+          , "Footnote ending in self-terminating element and followed by paragraph" =:
+            T.unlines [ "Foo[1]"
+                      , ""
+                      , "[1] > bar"
+                      , "baz"
+                      ] =?>
+            para (str "Foo" <> note (lineBlock ["bar"])) <> para (str "baz")
+
+          , "Footnote starting with empty line" =:
+            T.unlines [ "Foo[1]"
+                      , ""
+                      , "[1]" -- No space character after note marker
+                      , ""
+                      , "    Bar"
+                      ] =?>
+            para (str "Foo" <> note (para $ text "Bar"))
+          , "Indentation in footnote starting with empty line" =:
+            T.unlines [ "Foo[1]"
+                      , ""
+                      , "[1]" -- No space character after note marker
+                      , ""
+                      , "   Bar"
+                      ] =?>
+            para (str "Foo" <> note mempty) <> blockQuote (para $ text "Bar")
           , test emacsMuse "Emacs multiparagraph footnotes"
             (T.unlines
               [ "First footnote reference[1] and second footnote reference[2]."
@@ -573,14 +917,10 @@
     , testGroup "Tables"
         [ "Two cell table" =:
           "One | Two" =?>
-          table mempty [(AlignDefault, 0.0), (AlignDefault, 0.0)]
-                       []
-                       [[plain "One", plain "Two"]]
+          simpleTable [] [[plain "One", plain "Two"]]
         , "Table with multiple words" =:
           "One two | three four" =?>
-          table mempty [(AlignDefault, 0.0), (AlignDefault, 0.0)]
-                       []
-                       [[plain "One two", plain "three four"]]
+          simpleTable [] [[plain "One two", plain "three four"]]
         , "Not a table" =:
           "One| Two" =?>
           para (text "One| Two")
@@ -592,38 +932,30 @@
             [ "One |  Two"
             , "Three  | Four"
             ] =?>
-          table mempty [(AlignDefault, 0.0), (AlignDefault, 0.0)]
-                       []
-                       [[plain "One", plain "Two"],
-                       [plain "Three", plain "Four"]]
+          simpleTable [] [[plain "One", plain "Two"],
+                          [plain "Three", plain "Four"]]
         , "Table with one header" =:
           T.unlines
             [ "First || Second"
             , "Third | Fourth"
             ] =?>
-          table mempty [(AlignDefault, 0.0), (AlignDefault, 0.0)]
-            [plain "First", plain "Second"]
-            [[plain "Third", plain "Fourth"]]
+          simpleTable [plain "First", plain "Second"] [[plain "Third", plain "Fourth"]]
         , "Table with two headers" =:
           T.unlines
             [ "First || header"
             , "Second || header"
             , "Foo | bar"
             ] =?>
-          table mempty [(AlignDefault, 0.0), (AlignDefault, 0.0)]
-            [plain "First", plain "header"]
-            [[plain "Second", plain "header"],
-             [plain "Foo", plain "bar"]]
+          simpleTable [plain "First", plain "header"] [[plain "Second", plain "header"],
+                                                       [plain "Foo", plain "bar"]]
         , "Header and footer reordering" =:
           T.unlines
             [ "Foo ||| bar"
             , "Baz || foo"
             , "Bar | baz"
             ] =?>
-          table mempty [(AlignDefault, 0.0), (AlignDefault, 0.0)]
-            [plain "Baz", plain "foo"]
-            [[plain "Bar", plain "baz"],
-             [plain "Foo", plain "bar"]]
+          simpleTable [plain "Baz", plain "foo"] [[plain "Bar", plain "baz"],
+                                                  [plain "Foo", plain "bar"]]
         , "Table with caption" =:
           T.unlines
             [ "Foo || bar || baz"
@@ -631,24 +963,30 @@
             , "Second | row | there"
             , "|+ Table caption +|"
             ] =?>
-          table (text "Table caption") (replicate 3 (AlignDefault, 0.0))
-            [plain "Foo", plain "bar", plain "baz"]
-            [[plain "First", plain "row", plain "here"],
-             [plain "Second", plain "row", plain "there"]]
+          simpleTable' 3 (simpleCaption $ plain $ text "Table caption")
+                       [plain "Foo", plain "bar", plain "baz"]
+                       [[plain "First", plain "row", plain "here"],
+                        [plain "Second", plain "row", plain "there"]]
+        , "Table caption with +" =:
+          T.unlines
+            [ "Foo | bar"
+            , "|+ Table + caption +|"
+            ] =?>
+          simpleTable' 2 (simpleCaption $ plain $ text "Table + caption")
+                       []
+                       [[plain "Foo", plain "bar"]]
         , "Caption without table" =:
           "|+ Foo bar baz +|" =?>
-          table (text "Foo bar baz") [] [] []
+          simpleTable' 0 (simpleCaption $ plain $ text "Foo bar baz") [] []
         , "Table indented with space" =:
           T.unlines
             [ " Foo | bar"
             , " Baz | foo"
             , " Bar | baz"
             ] =?>
-          table mempty [(AlignDefault, 0.0), (AlignDefault, 0.0)]
-            []
-            [[plain "Foo", plain "bar"],
-             [plain "Baz", plain "foo"],
-             [plain "Bar", plain "baz"]]
+          simpleTable [] [[plain "Foo", plain "bar"],
+                          [plain "Baz", plain "foo"],
+                          [plain "Bar", plain "baz"]]
         , "Empty cells" =:
           T.unlines
             [ " | Foo"
@@ -656,11 +994,61 @@
             , " bar |"
             , " || baz"
             ] =?>
-          table mempty [(AlignDefault, 0.0), (AlignDefault, 0.0)]
-            [plain "", plain "baz"]
-            [[plain "", plain "Foo"],
-             [plain "", plain ""],
-             [plain "bar", plain ""]]
+          simpleTable [plain "", plain "baz"] [[plain "", plain "Foo"],
+                                               [plain "", plain ""],
+                                               [plain "bar", plain ""]]
+        , "Empty cell in the middle" =:
+          T.unlines
+            [ " 1 | 2 | 3"
+            , " 4 |   | 6"
+            , " 7 | 8 | 9"
+            ] =?>
+          simpleTable []
+                      [[plain "1", plain "2", plain "3"],
+                       [plain "4", mempty,    plain "6"],
+                       [plain "7", plain "8", plain "9"]]
+        , "Grid table" =:
+          T.unlines
+            [ "+-----+-----+"
+            , "| foo | bar |"
+            , "+-----+-----+"
+            ] =?>
+          simpleTable [] [[para "foo", para "bar"]]
+        , "Grid table inside list" =:
+          T.unlines
+            [ " - +-----+-----+"
+            , "   | foo | bar |"
+            , "   +-----+-----+"
+            ] =?>
+          bulletList [simpleTable [] [[para "foo", para "bar"]]]
+        , "Grid table with two rows" =:
+          T.unlines
+            [ "+-----+-----+"
+            , "| foo | bar |"
+            , "+-----+-----+"
+            , "| bat | baz |"
+            , "+-----+-----+"
+            ] =?>
+          simpleTable [] [[para "foo", para "bar"]
+                         ,[para "bat", para "baz"]]
+        , "Grid table inside grid table" =:
+          T.unlines
+            [ "+-----+"
+            , "|+---+|"
+            , "||foo||"
+            , "|+---+|"
+            , "+-----+"
+            ] =?>
+          simpleTable [] [[simpleTable [] [[para "foo"]]]]
+        , "Grid table with example" =:
+          T.unlines
+            [ "+------------+"
+            , "| <example>  |"
+            , "| foo        |"
+            , "| </example> |"
+            , "+------------+"
+            ] =?>
+          simpleTable [] [[codeBlock "foo"]]
         ]
     , testGroup "Lists"
       [ "Bullet list" =:
@@ -693,6 +1081,18 @@
                                              , para "Item2"
                                              , para "Item3"
                                              ]
+      , "Ordered list with roman numerals" =:
+        T.unlines
+          [ " i. First"
+          , " ii. Second"
+          , " iii. Third"
+          , " iv. Fourth"
+          ] =?>
+        orderedListWith (1, LowerRoman, Period) [ para "First"
+                                                , para "Second"
+                                                , para "Third"
+                                                , para "Fourth"
+                                                ]
       , "Bullet list with empty items" =:
         T.unlines
           [ " -"
@@ -714,8 +1114,48 @@
                                              , mempty
                                              , para "Item3"
                                              ]
+      , "Bullet list with last item empty" =:
+        T.unlines
+          [ " -"
+          , ""
+          , "foo"
+          ] =?>
+        bulletList [ mempty ] <>
+        para "foo"
       , testGroup "Nested lists"
-        [ "Nested list" =:
+        [ "Nested bullet list" =:
+          T.unlines [ " - Item1"
+                    , "   - Item2"
+                    , "     - Item3"
+                    , "   - Item4"
+                    , "     - Item5"
+                    , " - Item6"
+                    ] =?>
+          bulletList [ para "Item1" <>
+                       bulletList [ para "Item2" <>
+                                    bulletList [ para "Item3" ]
+                                  , para "Item4" <>
+                                    bulletList [ para "Item5" ]
+                                  ]
+                     , para "Item6"
+                     ]
+        , "Nested ordered list" =:
+          T.unlines [ " 1. Item1"
+                    , "    1. Item2"
+                    , "       1. Item3"
+                    , "    2. Item4"
+                    , "       1. Item5"
+                    , " 2. Item6"
+                    ] =?>
+          orderedListWith (1, Decimal, Period) [ para "Item1" <>
+                                                 orderedListWith (1, Decimal, Period) [ para "Item2" <>
+                                                                                        orderedListWith (1, Decimal, Period) [ para "Item3" ]
+                                                                                      , para "Item4" <>
+                                                                                        orderedListWith (1, Decimal, Period) [ para "Item5" ]
+                                                                                      ]
+                                               , para "Item6"
+                                               ]
+        , "Mixed nested list" =:
           T.unlines
             [ " - Item1"
             , "   - Item2"
@@ -737,12 +1177,6 @@
                                                                       ]
                                ]
                      ]
-        , "Incorrectly indented Text::Amuse nested list" =:
-          T.unlines
-            [ " - First item"
-            , "  - Not nested item"
-            ] =?>
-          bulletList [ para "First item", para "Not nested item"]
         , "Text::Amuse includes only one space in list marker" =:
           T.unlines
             [ " -    First item"
@@ -763,6 +1197,15 @@
                               , para "c"
                               ]
                     ]
+      , "List continuation after nested list" =:
+         T.unlines
+           [ " - - foo"
+           , ""
+           , "   bar"
+           ] =?>
+         bulletList [ bulletList [ para "foo" ] <>
+                      para "bar"
+                    ]
       -- Emacs Muse allows to separate lists with two or more blank lines.
       -- Text::Amuse (Amusewiki engine) always creates a single list as of version 0.82.
       -- pandoc follows Emacs Muse behavior
@@ -851,7 +1294,60 @@
             , " - Baz"
             ] =?>
           bulletList [ para "Foo" <> para "bar" ] <> bulletList [ para "Baz" ]
+        , "No blank line after blockquote" =:
+          T.unlines
+            [ " - <quote>"
+            , "   foo"
+            , "   </quote>"
+            , " - bar"
+            ] =?>
+          bulletList [ blockQuote $ para "foo", para "bar" ]
+        , "One blank line after blockquote" =:
+          T.unlines
+            [ " - <quote>"
+            , "   foo"
+            , "   </quote>"
+            , ""
+            , " - bar"
+            ] =?>
+          bulletList [ blockQuote $ para "foo", para "bar" ]
+        , "Two blank lines after blockquote" =:
+          T.unlines
+            [ " - <quote>"
+            , "   foo"
+            , "   </quote>"
+            , ""
+            , ""
+            , " - bar"
+            ] =?>
+          bulletList [ blockQuote $ para "foo" ] <> bulletList [ para "bar" ]
+        , "No blank line after verse" =:
+          T.unlines
+            [ " - > foo"
+            , " - bar"
+            ] =?>
+          bulletList [ lineBlock [ "foo" ], para "bar" ]
+        , "One blank line after verse" =:
+          T.unlines
+            [ " - > foo"
+            , ""
+            , " - bar"
+            ] =?>
+          bulletList [ lineBlock [ "foo" ], para "bar" ]
+        , "Two blank lines after verse" =:
+          T.unlines
+            [ " - > foo"
+            , ""
+            , ""
+            , " - bar"
+            ] =?>
+          bulletList [ lineBlock [ "foo" ] ] <> bulletList [ para "bar" ]
         ]
+      , "List ending in self-terminating element and followed by paragraph" =:
+        T.unlines [ " - > Foo"
+                  , "bar"
+                  ] =?>
+        bulletList [lineBlock ["Foo"]] <> para (str "bar")
       -- Test that definition list requires a leading space.
       -- Emacs Muse does not require a space, we follow Amusewiki here.
       , "Not a definition list" =:
@@ -885,8 +1381,13 @@
         definitionList [ ("Bar", [ para "baz" ]) ]
       , "One-line definition list" =: " foo :: bar" =?>
         definitionList [ ("foo", [ para "bar" ]) ]
+      , "Definition list term may include single colon" =:
+        " foo:bar :: baz" =?>
+        definitionList [ ("foo:bar", [ para "baz" ]) ]
       , "Definition list term with emphasis" =: " *Foo* :: bar\n" =?>
         definitionList [ (emph "Foo", [ para "bar" ]) ]
+      , "Definition list term with :: inside code" =: " foo <code> :: </code> :: bar <code> :: </code> baz\n" =?>
+        definitionList [ ("foo " <> code " :: ", [ para $ "bar " <> code " :: " <> " baz" ]) ]
       , "Multi-line definition lists" =:
         T.unlines
           [ " First term :: Definition of first term"
@@ -896,6 +1397,32 @@
         definitionList [ ("First term", [ para "Definition of first term\nand its continuation." ])
                        , ("Second term", [ para "Definition of second term." ])
                        ]
+      , "Definition list with verse" =:
+        T.unlines
+          [ " First term :: Definition of first term"
+          , "  > First verse"
+          , "  > Second line of first verse"
+          , ""
+          , "               > Second verse"
+          , "               > Second line of second verse"
+          ] =?>
+        definitionList [ ("First term", [ para "Definition of first term" <>
+                                          lineBlock [ text "First verse"
+                                                    , text "Second line of first verse"
+                                                    ] <>
+                                          lineBlock [ text "Second verse"
+                                                    , text "Second line of second verse"
+                                                    ]
+                                        ])
+                       ]
+      , "Definition list with table" =:
+        " foo :: bar | baz" =?>
+        definitionList [ ("foo", [ simpleTable [] [[plain "bar", plain "baz"]]
+                                 ])]
+      , "Definition list with table inside bullet list" =:
+        " - foo :: bar | baz" =?>
+        bulletList [definitionList [ ("foo", [ simpleTable [] [[plain "bar", plain "baz"]]
+                                             ])]]
       , test emacsMuse "Multi-line definition lists from Emacs Muse manual"
         (T.unlines
           [ "Term1 ::"
@@ -921,17 +1448,38 @@
          definitionList [ ("Term1", [ para "This is a first definition\nAnd it has two lines;\nno, make that three."])
                         , ("Term2", [ para "This is a second definition"])
                         ])
-      -- Emacs Muse creates two separate lists when indentation of items is different.
-      -- We follow Amusewiki and allow different indentation within one list.
-      , "Changing indentation" =:
+      , "One-line nested definition list" =:
+        " Foo :: bar :: baz" =?>
+        definitionList [ ("Foo", [ definitionList [ ("bar", [ para "baz" ])]])]
+      , "Nested definition list" =:
         T.unlines
-          [ " First term :: Definition of first term"
-          , "and its continuation."
-          , "   Second term :: Definition of second term."
-          ] =?>
-        definitionList [ ("First term", [ para "Definition of first term\nand its continuation." ])
-                       , ("Second term", [ para "Definition of second term." ])
+        [ " First :: Second :: Third"
+        , "          Fourth :: Fifth :: Sixth"
+        , " Seventh :: Eighth"
+        ] =?>
+        definitionList [ ("First", [ definitionList [ ("Second", [ para "Third" ]),
+                                                      ("Fourth", [ definitionList [ ("Fifth", [ para "Sixth"] ) ] ] ) ] ] )
+                       , ("Seventh", [ para "Eighth" ])
                        ]
+      , testGroup "Definition lists with multiple descriptions"
+        [ "Correctly indented second description" =:
+          T.unlines
+          [ " First term :: first description"
+          , "  :: second description"
+          ] =?>
+          definitionList [ ("First term", [ para "first description"
+                                          , para "second description"
+                                          ])
+                         ]
+        , "Incorrectly indented second description" =:
+          T.unlines
+          [ " First term :: first description"
+          , " :: second description"
+          ] =?>
+          definitionList [ ("First term", [ para "first description" ])
+                         , ("", [ para "second description" ])
+                         ]
+        ]
       , "Two blank lines separate definition lists" =:
         T.unlines
           [ " First :: list"
@@ -952,9 +1500,23 @@
                              , para "* Bar"
                              ]
                    ]
-      , "List inside a tag" =:
+      , "Bullet list inside a tag" =:
         T.unlines
           [ "<quote>"
+          , " - First"
+          , ""
+          , " - Second"
+          , ""
+          , " - Third"
+          , "</quote>"
+          ] =?>
+        blockQuote (bulletList [ para "First"
+                               , para "Second"
+                               , para "Third"
+                               ])
+      , "Ordered list inside a tag" =:
+        T.unlines
+          [ "<quote>"
           , " 1. First"
           , ""
           , " 2. Second"
@@ -966,19 +1528,53 @@
                                                          , para "Second"
                                                          , para "Third"
                                                          ])
-      -- Amusewiki requires block tags to be on separate lines,
-      -- but Emacs Muse allows them to be on the same line as contents.
-      , "List inside an inline tag" =:
+      -- Regression test for a bug caught by round-trip test
+      , "Do not consume whitespace while looking for end tag" =:
         T.unlines
-          [ "<quote> 1. First"
+          [ "<quote>"
+          , " - <quote>"
+          , "   foo"
+          , "   </quote>"
+          , " bar" -- Do not consume whitespace while looking for arbitrarily indented </quote>
+          , "</quote>"
+          ] =?>
+        blockQuote (bulletList [ blockQuote $ para "foo" ] <> para "bar")
+
+      , "Unclosed quote tag" =:
+        T.unlines
+          [ "<quote>"
+          , "<verse>"
+          , "</quote>"
+          , "</verse>"
+          ] =?>
+        para "<quote>" <> lineBlock [ "</quote>" ]
+
+      , "Unclosed quote tag inside list" =:
+        T.unlines
+          [ " - <quote>"
+          , "   <verse>"
+          , "   </quote>"
+          , "   </verse>"
+          ] =?>
+        bulletList [ para "<quote>" <> lineBlock [ "</quote>" ] ]
+
+      -- Allowing indented closing tags is dangerous,
+      -- as they may terminate lists
+      , "No indented closing tags" =:
+        T.unlines
+          [ "<quote>"
           , ""
-          , " 2. Second"
+          , " - Foo"
           , ""
-          , " 3. Third</quote>"
+          , "   </quote>"
+          , ""
+          , "   bar"
+          , ""
+          , "   <verse>"
+          , "   </quote>"
+          , "   </verse>"
+          , "</quote>"
           ] =?>
-        blockQuote (orderedListWith (1, Decimal, Period) [ para "First"
-                                                         , para "Second"
-                                                         , para "Third"
-                                                         ])
+        blockQuote (bulletList [ para "Foo" <> para "</quote>" <> para "bar" <> lineBlock [ "</quote>" ] ])
       ]
   ]
diff --git a/test/Tests/Readers/ODT.hs b/test/Tests/Readers/ODT.hs
new file mode 100644
--- /dev/null
+++ b/test/Tests/Readers/ODT.hs
@@ -0,0 +1,196 @@
+{-# LANGUAGE OverloadedStrings #-}
+{- |
+   Module      : Tests.Readers.ODT
+   Copyright   : © 2015-2024 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 Control.Monad (liftM)
+import qualified Data.ByteString as BS
+import qualified Data.ByteString.Lazy as B
+import qualified Data.Map as M
+import Data.Text (unpack)
+import System.IO.Unsafe (unsafePerformIO)
+import Test.Tasty
+import Tests.Helpers
+import Text.Pandoc
+import qualified Text.Pandoc.UTF8 as UTF8
+
+defopts :: ReaderOptions
+defopts = def{ readerExtensions = getDefaultExtensions "odt" }
+
+tests :: [TestTree]
+tests = testsComparingToMarkdown ++ testsComparingToNative
+
+testsComparingToMarkdown :: [TestTree]
+testsComparingToMarkdown    = map nameToTest namesOfTestsComparingToMarkdown
+  where nameToTest     name = createTest
+                                compareODTToMarkdown
+                                name
+                                (toODTPath      name)
+                                (toMarkdownPath name)
+        toODTPath      name = "odt/odt/"      ++ name ++ ".odt"
+        toMarkdownPath name = "odt/markdown/" ++ name ++ ".md"
+
+testsComparingToNative   :: [TestTree]
+testsComparingToNative      = map nameToTest namesOfTestsComparingToNative
+  where nameToTest     name = createTest
+                                compareODTToNative
+                                name
+                                (toODTPath      name)
+                                (toNativePath   name)
+        toODTPath      name = "odt/odt/"      ++ name ++ ".odt"
+        toNativePath   name = "odt/native/"   ++ name ++ ".native"
+
+
+newtype NoNormPandoc = NoNormPandoc {unNoNorm :: Pandoc}
+  deriving ( Show )
+
+instance ToString NoNormPandoc where
+  toString d = unpack $
+               purely (writeNative def{ writerTemplate = s }) $ toPandoc d
+   where s = case d of
+                  NoNormPandoc (Pandoc (Meta m) _)
+                    | M.null m  -> Nothing
+                    | otherwise -> Just mempty -- need this for Meta output
+
+instance ToPandoc NoNormPandoc where
+  toPandoc = unNoNorm
+
+getNoNormVia :: (a -> Pandoc) -> String -> Either PandocError a -> NoNormPandoc
+getNoNormVia _ readerName (Left  _) = error (readerName ++ " reader failed")
+getNoNormVia f _          (Right a) = NoNormPandoc (f a)
+
+type TestCreator =  ReaderOptions
+                 -> FilePath -> FilePath
+                 -> IO (NoNormPandoc, NoNormPandoc)
+
+compareODTToNative   :: TestCreator
+compareODTToNative opts odtPath nativePath = do
+   nativeFile   <- UTF8.toText <$> BS.readFile nativePath
+   odtFile      <- B.readFile       odtPath
+   native       <- getNoNormVia id  "native" <$> runIO (readNative def nativeFile)
+   odt          <- getNoNormVia id  "odt"    <$> runIO (readODT  opts odtFile)
+   return (odt,native)
+
+compareODTToMarkdown :: TestCreator
+compareODTToMarkdown opts odtPath markdownPath = do
+   markdownFile <- UTF8.toText <$> BS.readFile markdownPath
+   odtFile      <- B.readFile       odtPath
+   markdown     <- getNoNormVia id "markdown" <$>
+                      runIO (readMarkdown def{ readerExtensions = pandocExtensions }
+                              markdownFile)
+   odt          <- getNoNormVia id "odt"      <$> runIO (readODT      opts odtFile)
+   return (odt,markdown)
+
+
+createTest :: TestCreator
+           -> TestName
+           -> FilePath -> FilePath
+           -> TestTree
+createTest   creator name path1 path2 =
+  unsafePerformIO $ liftM (test id name) (creator defopts path1 path2)
+
+{-
+--
+
+getMedia :: FilePath -> FilePath -> IO (Maybe B.ByteString)
+getMedia archivePath mediaPath = do
+  zf <- B.readFile archivePath >>= return . toArchive
+  return $ findEntryByPath ("Pictures/" ++ mediaPath) zf >>= (Just . fromEntry)
+
+compareMediaPathIO :: FilePath -> MediaBag -> FilePath -> IO Bool
+compareMediaPathIO mediaPath mediaBag odtPath = do
+  odtMedia <- getMedia odtPath mediaPath
+  let mbBS   = case lookupMedia mediaPath mediaBag of
+                 Just (_, bs) -> bs
+                 Nothing      -> error ("couldn't find " ++
+                                        mediaPath ++
+                                        " in media bag")
+      odtBS = case odtMedia of
+                 Just bs -> bs
+                 Nothing -> error ("couldn't find " ++
+                                   mediaPath ++
+                                   " in media bag")
+  return $ mbBS == odtBS
+
+compareMediaBagIO :: FilePath -> IO Bool
+compareMediaBagIO odtFile = do
+    df <- B.readFile odtFile
+    let (_, mb) = readODT def df
+    bools <- mapM
+             (\(fp, _, _) -> compareMediaPathIO fp mb odtFile)
+             (mediaDirectory mb)
+    return $ and bools
+
+testMediaBagIO :: String -> FilePath -> IO TestTree
+testMediaBagIO name odtFile = do
+  outcome <- compareMediaBagIO odtFile
+  return $ testCase name (assertBool
+                          ("Media didn't match media bag in file " ++ odtFile)
+                          outcome)
+
+testMediaBag :: String -> FilePath -> TestTree
+testMediaBag name odtFile = buildTest $ testMediaBagIO name odtFile
+-}
+--
+
+
+
+namesOfTestsComparingToMarkdown :: [ String ]
+namesOfTestsComparingToMarkdown  = [ "blockquote2"
+                                   , "bold"
+--                                 , "citation"
+                                   , "endnote"
+                                   , "externalLink"
+                                   , "footnote"
+                                   , "formula"
+                                   , "headers"
+--                                 , "horizontalRule"
+                                   , "italic"
+--                                 , "listBlocks"
+                                   , "paragraph"
+                                   , "strikeout"
+--                                 , "trackedChanges"
+                                   , "underlined"
+                                   ]
+
+namesOfTestsComparingToNative  :: [ String ]
+namesOfTestsComparingToNative   = [ "blockquote"
+                                  , "image"
+                                  , "imageIndex"
+                                  , "imageRelative"
+                                  , "imageWithCaption"
+                                  , "inlinedCode"
+                                  , "listContinueNumbering"
+                                  , "listContinueNumbering2"
+                                  , "orderedListMixed"
+                                  , "orderedListRoman"
+                                  , "orderedListSimple"
+                                  , "orderedListHeader"
+                                  , "preformattedText"
+                                  , "preformattedTextParentStyle"
+                                  , "referenceToChapter"
+                                  , "referenceToListItem"
+                                  , "referenceToText"
+                                  , "simpleTable"
+                                  , "simpleTableWithCaption"
+                                  , "simpleTableWithHeader"
+                                  , "simpleTableWithMultipleHeaderRows"
+                                  , "tab"
+--                                , "table"
+                                  , "textMixedStyles"
+                                  , "tableWithContents"
+                                  , "tableWithSpans"
+                                  , "unicode"
+                                  , "unorderedList"
+                                  , "unorderedListHeader"
+                                  ]
diff --git a/test/Tests/Readers/Odt.hs b/test/Tests/Readers/Odt.hs
deleted file mode 100644
--- a/test/Tests/Readers/Odt.hs
+++ /dev/null
@@ -1,170 +0,0 @@
-module Tests.Readers.Odt (tests) where
-
-import Control.Monad (liftM)
-import qualified Data.ByteString as BS
-import qualified Data.ByteString.Lazy as B
-import qualified Data.Map as M
-import Data.Text (unpack)
-import System.IO.Unsafe (unsafePerformIO)
-import Test.Tasty
-import Tests.Helpers
-import Text.Pandoc
-import qualified Text.Pandoc.UTF8 as UTF8
-
-defopts :: ReaderOptions
-defopts = def{ readerExtensions = getDefaultExtensions "odt" }
-
-tests :: [TestTree]
-tests = testsComparingToMarkdown ++ testsComparingToNative
-
-testsComparingToMarkdown :: [TestTree]
-testsComparingToMarkdown    = map nameToTest namesOfTestsComparingToMarkdown
-  where nameToTest     name = createTest
-                                compareOdtToMarkdown
-                                name
-                                (toOdtPath      name)
-                                (toMarkdownPath name)
-        toOdtPath      name = "odt/odt/"      ++ name ++ ".odt"
-        toMarkdownPath name = "odt/markdown/" ++ name ++ ".md"
-
-testsComparingToNative   :: [TestTree]
-testsComparingToNative      = map nameToTest namesOfTestsComparingToNative
-  where nameToTest     name = createTest
-                                compareOdtToNative
-                                name
-                                (toOdtPath      name)
-                                (toNativePath   name)
-        toOdtPath      name = "odt/odt/"      ++ name ++ ".odt"
-        toNativePath   name = "odt/native/"   ++ name ++ ".native"
-
-
-newtype NoNormPandoc = NoNormPandoc {unNoNorm :: Pandoc}
-  deriving ( Show )
-
-instance ToString NoNormPandoc where
-  toString d = unpack $
-               purely (writeNative def{ writerTemplate = s }) $ toPandoc d
-   where s = case d of
-                  NoNormPandoc (Pandoc (Meta m) _)
-                    | M.null m  -> Nothing
-                    | otherwise -> Just "" -- need this for Meta output
-
-instance ToPandoc NoNormPandoc where
-  toPandoc = unNoNorm
-
-getNoNormVia :: (a -> Pandoc) -> String -> Either PandocError a -> NoNormPandoc
-getNoNormVia _ readerName (Left  _) = error (readerName ++ " reader failed")
-getNoNormVia f _          (Right a) = NoNormPandoc (f a)
-
-type TestCreator =  ReaderOptions
-                 -> FilePath -> FilePath
-                 -> IO (NoNormPandoc, NoNormPandoc)
-
-compareOdtToNative   :: TestCreator
-compareOdtToNative opts odtPath nativePath = do
-   nativeFile   <- UTF8.toText <$> BS.readFile nativePath
-   odtFile      <- B.readFile       odtPath
-   native       <- getNoNormVia id  "native" <$> runIO (readNative def nativeFile)
-   odt          <- getNoNormVia id  "odt"    <$> runIO (readOdt  opts odtFile)
-   return (odt,native)
-
-compareOdtToMarkdown :: TestCreator
-compareOdtToMarkdown opts odtPath markdownPath = do
-   markdownFile <- UTF8.toText <$> BS.readFile markdownPath
-   odtFile      <- B.readFile       odtPath
-   markdown     <- getNoNormVia id "markdown" <$>
-                      runIO (readMarkdown def{ readerExtensions = pandocExtensions }
-                              markdownFile)
-   odt          <- getNoNormVia id "odt"      <$> runIO (readOdt      opts odtFile)
-   return (odt,markdown)
-
-
-createTest :: TestCreator
-           -> TestName
-           -> FilePath -> FilePath
-           -> TestTree
-createTest   creator name path1 path2 =
-  unsafePerformIO $ liftM (test id name) (creator defopts path1 path2)
-
-{-
---
-
-getMedia :: FilePath -> FilePath -> IO (Maybe B.ByteString)
-getMedia archivePath mediaPath = do
-  zf <- B.readFile archivePath >>= return . toArchive
-  return $ findEntryByPath ("Pictures/" ++ mediaPath) zf >>= (Just . fromEntry)
-
-compareMediaPathIO :: FilePath -> MediaBag -> FilePath -> IO Bool
-compareMediaPathIO mediaPath mediaBag odtPath = do
-  odtMedia <- getMedia odtPath mediaPath
-  let mbBS   = case lookupMedia mediaPath mediaBag of
-                 Just (_, bs) -> bs
-                 Nothing      -> error ("couldn't find " ++
-                                        mediaPath ++
-                                        " in media bag")
-      odtBS = case odtMedia of
-                 Just bs -> bs
-                 Nothing -> error ("couldn't find " ++
-                                   mediaPath ++
-                                   " in media bag")
-  return $ mbBS == odtBS
-
-compareMediaBagIO :: FilePath -> IO Bool
-compareMediaBagIO odtFile = do
-    df <- B.readFile odtFile
-    let (_, mb) = readOdt def df
-    bools <- mapM
-             (\(fp, _, _) -> compareMediaPathIO fp mb odtFile)
-             (mediaDirectory mb)
-    return $ and bools
-
-testMediaBagIO :: String -> FilePath -> IO TestTree
-testMediaBagIO name odtFile = do
-  outcome <- compareMediaBagIO odtFile
-  return $ testCase name (assertBool
-                          ("Media didn't match media bag in file " ++ odtFile)
-                          outcome)
-
-testMediaBag :: String -> FilePath -> TestTree
-testMediaBag name odtFile = buildTest $ testMediaBagIO name odtFile
--}
---
-
-
-
-namesOfTestsComparingToMarkdown :: [ String ]
-namesOfTestsComparingToMarkdown  = [ "bold"
---                                 , "citation"
-                                   , "endnote"
-                                   , "externalLink"
-                                   , "footnote"
-                                   , "headers"
---                                 , "horizontalRule"
-                                   , "italic"
---                                 , "listBlocks"
-                                   , "paragraph"
-                                   , "strikeout"
---                                 , "trackedChanges"
-                                   , "underlined"
-                                   ]
-
-namesOfTestsComparingToNative  :: [ String ]
-namesOfTestsComparingToNative   = [ "blockquote"
-                                  , "image"
-                                  , "imageIndex"
-                                  , "imageWithCaption"
-                                  , "inlinedCode"
-                                  , "orderedListMixed"
-                                  , "orderedListRoman"
-                                  , "orderedListSimple"
-                                  , "referenceToChapter"
-                                  , "referenceToListItem"
-                                  , "referenceToText"
-                                  , "simpleTable"
-                                  , "simpleTableWithCaption"
---                                , "table"
-                                  , "textMixedStyles"
-                                  , "tableWithContents"
-                                  , "unicode"
-                                  , "unorderedList"
-                                  ]
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-2024 Albert Krewinkel
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : Albert Krewinkel <albert+pandoc@tarleb.com>
+   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,4 +1,15 @@
 {-# LANGUAGE OverloadedStrings #-}
+{- |
+   Module      : Tests.Readers.Org.Block
+   Copyright   : © 2014-2024 Albert Krewinkel
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : Albert Krewinkel <albert+pandoc@tarleb.com>
+   Stability   : alpha
+   Portability : portable
+
+Tests parsing of org blocks.
+-}
 module Tests.Readers.Org.Block (tests) where
 
 import Test.Tasty (TestTree, testGroup)
@@ -32,7 +43,7 @@
       T.unlines [ ": echo hello"
                 , ": echo dear tester"
                 ] =?>
-      codeBlockWith ("", ["example"], []) "echo hello\necho dear tester\n"
+      codeBlockWith ("", [], []) "echo hello\necho dear tester\n"
 
   , "Example block surrounded by text" =:
       T.unlines [ "Greetings"
@@ -41,7 +52,7 @@
                 , "Bye"
                 ] =?>
       mconcat [ para "Greetings"
-              , codeBlockWith ("", ["example"], [])
+              , codeBlockWith ("", [], [])
                               "echo hello\necho dear tester\n"
               , para "Bye"
               ]
@@ -60,25 +71,35 @@
       "----- em and en dash" =?>
       para "\8212\8211 em and en dash"
 
-  , "Comment Block" =:
-      T.unlines [ "#+BEGIN_COMMENT"
+  , testGroup "Comments"
+    [ "Comment Block" =:
+      T.unlines [ "#+begin_comment"
                 , "stuff"
                 , "bla"
-                , "#+END_COMMENT"] =?>
+                , "#+end_comment"] =?>
       (mempty::Blocks)
 
+    , "Comment line" =:
+      T.unlines [ "# this is a comment" ] =?>
+      (mempty :: Blocks)
+
+    , "Empty comment line" =:
+      T.unlines [ "  #" ] =?>
+      (mempty :: Blocks)
+    ]
+
   , testGroup "Blocks and fragments"
     [ "HTML block" =:
-      T.unlines [ "#+BEGIN_HTML"
+      T.unlines [ "#+begin_html"
                 , "<aside>HTML5 is pretty nice.</aside>"
-                , "#+END_HTML"
+                , "#+end_html"
                 ] =?>
       rawBlock "html" "<aside>HTML5 is pretty nice.</aside>\n"
 
     , "Quote block" =:
-      T.unlines [ "#+BEGIN_QUOTE"
+      T.unlines [ "#+begin_quote"
                 , "/Niemand/ hat die Absicht, eine Mauer zu errichten!"
-                , "#+END_QUOTE"
+                , "#+end_quote"
                 ] =?>
       blockQuote (para (spcSep [ emph "Niemand", "hat", "die", "Absicht,"
                                , "eine", "Mauer", "zu", "errichten!"
@@ -105,31 +126,31 @@
         ]
 
     , "Verse block with blank lines" =:
-      T.unlines [ "#+BEGIN_VERSE"
+      T.unlines [ "#+begin_verse"
                 , "foo"
                 , ""
                 , "bar"
-                , "#+END_VERSE"
+                , "#+end_verse"
                 ] =?>
       lineBlock [ "foo", mempty, "bar" ]
 
     , "Verse block with varying indentation" =:
-      T.unlines [ "#+BEGIN_VERSE"
+      T.unlines [ "#+begin_verse"
                 , "  hello darkness"
                 , "my old friend"
-                , "#+END_VERSE"
+                , "#+end_verse"
                 ] =?>
       lineBlock [ "\160\160hello darkness", "my old friend" ]
 
     , "Raw block LaTeX" =:
-      T.unlines [ "#+BEGIN_LaTeX"
+      T.unlines [ "#+begin_latex"
                 , "The category $\\cat{Set}$ is adhesive."
-                , "#+END_LaTeX"
+                , "#+end_latex"
                 ] =?>
       rawBlock "latex" "The category $\\cat{Set}$ is adhesive.\n"
 
     , "Raw LaTeX line" =:
-      "#+LATEX: \\let\\foo\\bar" =?>
+      "#+latex: \\let\\foo\\bar" =?>
       rawBlock "latex" "\\let\\foo\\bar"
 
     , "Raw Beamer line" =:
@@ -137,33 +158,52 @@
       rawBlock "beamer" "\\pause"
 
     , "Raw HTML line" =:
-      "#+HTML: <aside>not important</aside>" =?>
+      "#+html: <aside>not important</aside>" =?>
       rawBlock "html" "<aside>not important</aside>"
 
     , "Export block HTML" =:
-      T.unlines [ "#+BEGIN_export html"
+      T.unlines [ "#+begin_export html"
                 , "<samp>Hello, World!</samp>"
-                , "#+END_export"
+                , "#+end_export"
                 ] =?>
       rawBlock "html" "<samp>Hello, World!</samp>\n"
 
     , "LaTeX fragment" =:
-      T.unlines [ "\\begin{equation}"
-                , "X_i = \\begin{cases}"
-                , "      G_{\\alpha(i)} & \\text{if }\\alpha(i-1) = \\alpha(i)\\\\"
-                , "      C_{\\alpha(i)} & \\text{otherwise}"
-                , "      \\end{cases}"
-                , "\\end{equation}"
+      "\\begin{equation}\n\
+      \X_i = \\begin{cases}\n\
+      \      G_{\\alpha(i)} & \\text{if }\\alpha(i-1) = \\alpha(i)\\\\\n\
+      \      C_{\\alpha(i)} & \\text{otherwise}\n\
+      \      \\end{cases}\n\
+      \\\end{equation}"
+      =?>
+      para (rawInline "latex"
+             "\\begin{equation}\n\
+             \X_i = \\begin{cases}\n\
+             \      G_{\\alpha(i)} & \\text{if }\\alpha(i-1) = \\alpha(i)\\\\\n\
+             \      C_{\\alpha(i)} & \\text{otherwise}\n\
+             \      \\end{cases}\n\
+             \\\end{equation}")
+
+    , "One-line LaTeX fragment" =:
+      "\\begin{equation} 2 + 3 \\end{equation}" =?>
+      para (rawInline "latex" "\\begin{equation} 2 + 3 \\end{equation}")
+
+    , "LaTeX fragment with more arguments" =:
+      T.unlines [ "\\begin{tikzcd}[ampersand replacement=\\&]"
+                , "  A \\& B \\\\"
+                , "  C \\& D"
+                , "  \\arrow[from=1-1, to=1-2]"
+                , "  \\arrow[\"f\", from=2-1, to=2-2]"
+                , "\\end{tikzcd}"
                 ] =?>
       rawBlock "latex"
-      (unlines [ "\\begin{equation}"
-               , "X_i = \\begin{cases}"
-               , "      G_{\\alpha(i)} & \\text{if }\\alpha(i-1) =" <>
-                 " \\alpha(i)\\\\"
-               , "      C_{\\alpha(i)} & \\text{otherwise}"
-               , "      \\end{cases}"
-               , "\\end{equation}"
-               ])
+      (T.unlines [ "\\begin{tikzcd}[ampersand replacement=\\&]"
+                 , "  A \\& B \\\\"
+                 , "  C \\& D"
+                 , "  \\arrow[from=1-1, to=1-2]"
+                 , "  \\arrow[\"f\", from=2-1, to=2-2]"
+                 , "\\end{tikzcd}"
+                 ])
 
     , "Convert blank lines in blocks to single newlines" =:
       T.unlines [ "#+begin_html"
@@ -174,13 +214,13 @@
                 ] =?>
       rawBlock "html" "\n<span>boring</span>\n\n"
 
-    , "Accept `ATTR_HTML` attributes for generic block" =:
-      T.unlines [ "#+ATTR_HTML: :title hello, world :id test :class fun code"
-                , "#+BEGIN_TEST"
+    , "Accept `attr_html` attributes for generic block" =:
+      T.unlines [ "#+attr_html: :title hello, world :id test :class fun code"
+                , "#+begin_test"
                 , "nonsense"
-                , "#+END_TEST"
+                , "#+end_test"
                 ] =?>
-      let attr = ("test", ["fun", "code", "TEST"], [("title", "hello, world")])
+      let attr = ("test", ["fun", "code", "test"], [("title", "hello, world")])
       in divWith attr (para "nonsense")
     ]
 
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,4 +1,15 @@
 {-# LANGUAGE OverloadedStrings #-}
+{- |
+   Module      : Tests.Readers.Org.Block.CodeBlock
+   Copyright   : © 2014-2024 Albert Krewinkel
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : Albert Krewinkel <albert+pandoc@tarleb.com>
+   Stability   : alpha
+   Portability : portable
+
+Test parsing of org code blocks.
+-}
 module Tests.Readers.Org.Block.CodeBlock (tests) where
 
 import Test.Tasty (TestTree)
@@ -10,48 +21,48 @@
 tests :: [TestTree]
 tests =
   [ "Source block" =:
-       T.unlines [ "  #+BEGIN_SRC haskell"
+       T.unlines [ "  #+begin_src haskell"
                  , "  main = putStrLn greeting"
                  , "    where greeting = \"moin\""
-                 , "  #+END_SRC" ] =?>
+                 , "  #+end_src" ] =?>
        let attr' = ("", ["haskell"], [])
            code' = "main = putStrLn greeting\n" <>
                    "  where greeting = \"moin\"\n"
        in codeBlockWith attr' code'
 
   , "Source block with indented code" =:
-       T.unlines [ "  #+BEGIN_SRC haskell"
+       T.unlines [ "  #+begin_src haskell"
                  , "    main = putStrLn greeting"
                  , "      where greeting = \"moin\""
-                 , "  #+END_SRC" ] =?>
+                 , "  #+end_src" ] =?>
        let attr' = ("", ["haskell"], [])
            code' = "main = putStrLn greeting\n" <>
                    "  where greeting = \"moin\"\n"
        in codeBlockWith attr' code'
 
   , "Source block with tab-indented code" =:
-       T.unlines [ "\t#+BEGIN_SRC haskell"
+       T.unlines [ "\t#+begin_src haskell"
                  , "\tmain = putStrLn greeting"
                  , "\t  where greeting = \"moin\""
-                 , "\t#+END_SRC" ] =?>
+                 , "\t#+end_src" ] =?>
        let attr' = ("", ["haskell"], [])
            code' = "main = putStrLn greeting\n" <>
                    "  where greeting = \"moin\"\n"
        in codeBlockWith attr' code'
 
   , "Empty source block" =:
-       T.unlines [ "  #+BEGIN_SRC haskell"
-                 , "  #+END_SRC" ] =?>
+       T.unlines [ "  #+begin_src haskell"
+                 , "  #+end_src" ] =?>
        let attr' = ("", ["haskell"], [])
            code' = ""
        in codeBlockWith attr' code'
 
   , "Source block between paragraphs" =:
        T.unlines [ "Low German greeting"
-                 , "  #+BEGIN_SRC haskell"
+                 , "  #+begin_src haskell"
                  , "  main = putStrLn greeting"
                  , "    where greeting = \"Moin!\""
-                 , "  #+END_SRC" ] =?>
+                 , "  #+end_src" ] =?>
        let attr' = ("", ["haskell"], [])
            code' = "main = putStrLn greeting\n" <>
                     "  where greeting = \"Moin!\"\n"
@@ -59,23 +70,23 @@
                   , codeBlockWith attr' code'
                   ]
   , "Source block with babel arguments" =:
-       T.unlines [ "#+BEGIN_SRC emacs-lisp :exports both"
+       T.unlines [ "#+begin_src emacs-lisp :exports both"
                  , "(progn (message \"Hello, World!\")"
                  , "       (+ 23 42))"
-                 , "#+END_SRC" ] =?>
+                 , "#+end_src" ] =?>
        let classes = [ "commonlisp" ] -- as kate doesn't know emacs-lisp syntax
            params = [ ("org-language", "emacs-lisp")
                     , ("exports", "both")
                     ]
-           code' = unlines [ "(progn (message \"Hello, World!\")"
+           code' = T.unlines [ "(progn (message \"Hello, World!\")"
                            , "       (+ 23 42))" ]
        in codeBlockWith ("", classes, params) code'
 
   , "Source block with results and :exports both" =:
-       T.unlines [ "#+BEGIN_SRC emacs-lisp :exports both"
+       T.unlines [ "#+begin_src emacs-lisp :exports both"
                  , "(progn (message \"Hello, World!\")"
                  , "       (+ 23 42))"
-                 , "#+END_SRC"
+                 , "#+end_src"
                  , ""
                  , "#+RESULTS:"
                  , ": 65"] =?>
@@ -83,18 +94,18 @@
            params = [ ("org-language", "emacs-lisp")
                     , ("exports", "both")
                     ]
-           code' = unlines [ "(progn (message \"Hello, World!\")"
-                           , "       (+ 23 42))" ]
+           code' = T.unlines [ "(progn (message \"Hello, World!\")"
+                             , "       (+ 23 42))" ]
            results' = "65\n"
        in codeBlockWith ("", classes, params) code'
           <>
-          codeBlockWith ("", ["example"], []) results'
+          codeBlockWith ("", [], []) results'
 
   , "Source block with results and :exports code" =:
-       T.unlines [ "#+BEGIN_SRC emacs-lisp :exports code"
+       T.unlines [ "#+begin_src emacs-lisp :exports code"
                  , "(progn (message \"Hello, World!\")"
                  , "       (+ 23 42))"
-                 , "#+END_SRC"
+                 , "#+end_src"
                  , ""
                  , "#+RESULTS:"
                  , ": 65" ] =?>
@@ -102,53 +113,53 @@
            params = [ ("org-language", "emacs-lisp")
                     , ("exports", "code")
                     ]
-           code' = unlines [ "(progn (message \"Hello, World!\")"
-                           , "       (+ 23 42))" ]
+           code' = T.unlines [ "(progn (message \"Hello, World!\")"
+                             , "       (+ 23 42))" ]
        in codeBlockWith ("", classes, params) code'
 
   , "Source block with results and :exports results" =:
-       T.unlines [ "#+BEGIN_SRC emacs-lisp :exports results"
+       T.unlines [ "#+begin_src emacs-lisp :exports results"
                  , "(progn (message \"Hello, World!\")"
                  , "       (+ 23 42))"
-                 , "#+END_SRC"
+                 , "#+end_src"
                  , ""
                  , "#+RESULTS:"
                  , ": 65" ] =?>
        let results' = "65\n"
-       in codeBlockWith ("", ["example"], []) results'
+       in codeBlockWith ("", [], []) results'
 
   , "Source block with results and :exports none" =:
-       T.unlines [ "#+BEGIN_SRC emacs-lisp :exports none"
+       T.unlines [ "#+begin_src emacs-lisp :exports none"
                  , "(progn (message \"Hello, World!\")"
                  , "       (+ 23 42))"
-                 , "#+END_SRC"
+                 , "#+end_src"
                  , ""
                  , "#+RESULTS:"
                  , ": 65" ] =?>
        (mempty :: Blocks)
 
   , "Source block with toggling header arguments" =:
-    T.unlines [ "#+BEGIN_SRC sh :noeval"
+    T.unlines [ "#+begin_src sh :noeval"
               , "echo $HOME"
-              , "#+END_SRC"
+              , "#+end_src"
               ] =?>
     let classes = [ "bash" ]
         params = [ ("org-language", "sh"), ("noeval", "yes") ]
     in codeBlockWith ("", classes, params) "echo $HOME\n"
 
   , "Source block with line number switch" =:
-    T.unlines [ "#+BEGIN_SRC sh -n 10"
+    T.unlines [ "#+begin_src sh -n 10"
               , ":() { :|:& };:"
-              , "#+END_SRC"
+              , "#+end_src"
               ] =?>
     let classes = [ "bash", "numberLines" ]
         params = [ ("org-language", "sh"), ("startFrom", "10") ]
     in codeBlockWith ("", classes, params) ":() { :|:& };:\n"
 
   , "Source block with multi-word parameter values" =:
-    T.unlines [ "#+BEGIN_SRC dot :cmdline -Kdot -Tpng "
+    T.unlines [ "#+begin_src dot :cmdline -Kdot -Tpng "
               , "digraph { id [label=\"ID\"] }"
-              , "#+END_SRC"
+              , "#+end_src"
               ] =?>
     let classes = [ "dot" ]
         params = [ ("cmdline", "-Kdot -Tpng") ]
@@ -160,31 +171,31 @@
                  , "a rule."
                  , "#+eND_exAMPle"
                  ] =?>
-       codeBlockWith ("", ["example"], [])
+       codeBlockWith ("", [], [])
                      "A chosen representation of\na rule.\n"
 
   , "Code block with caption" =:
-      T.unlines [ "#+CAPTION: Functor laws in Haskell"
-                , "#+NAME: functor-laws"
-                , "#+BEGIN_SRC haskell"
+      T.unlines [ "#+caption: Functor laws in Haskell"
+                , "#+name: functor-laws"
+                , "#+begin_src haskell"
                 , "fmap id = id"
                 , "fmap (p . q) = (fmap p) . (fmap q)"
-                , "#+END_SRC"
+                , "#+end_src"
                 ] =?>
       divWith
-         nullAttr
+         ("", ["captioned-content"], [] )
          (mappend
-          (plain $ spanWith ("", ["label"], [])
-                            (spcSep [ "Functor", "laws", "in", "Haskell" ]))
+          (divWith ("", ["caption"], []) $
+           plain (spcSep [ "Functor", "laws", "in", "Haskell" ]))
           (codeBlockWith ("functor-laws", ["haskell"], [])
-                         (unlines [ "fmap id = id"
-                                  , "fmap (p . q) = (fmap p) . (fmap q)"
-                                  ])))
+                         (T.unlines [ "fmap id = id"
+                                    , "fmap (p . q) = (fmap p) . (fmap q)"
+                                    ])))
 
   , "Non-letter chars in source block parameters" =:
-      T.unlines [ "#+BEGIN_SRC C :tangle xxxx.c :city Zürich"
+      T.unlines [ "#+begin_src C :tangle xxxx.c :city Zürich"
                 , "code body"
-                , "#+END_SRC"
+                , "#+end_src"
                 ] =?>
       let params  = [ ("org-language", "C")
                     , ("tangle", "xxxx.c")
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,57 +1,85 @@
 {-# LANGUAGE OverloadedStrings #-}
+{- |
+   Module      : Tests.Readers.Org.Block.Figure
+   Copyright   : © 2014-2024 Albert Krewinkel
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : Albert Krewinkel <albert+pandoc@tarleb.com>
+   Stability   : alpha
+   Portability : portable
+
+Test parsing of org figures.
+-}
 module Tests.Readers.Org.Block.Figure (tests) where
 
 import Test.Tasty (TestTree)
 import Tests.Helpers ((=?>))
 import Tests.Readers.Org.Shared ((=:))
-import Text.Pandoc.Builder (image, imageWith, para)
+import Text.Pandoc.Builder ( emptyCaption, figure, figureWith, image
+                           , plain, simpleCaption, simpleFigure )
 import qualified Data.Text as T
 
 tests :: [TestTree]
 tests =
   [ "Figure" =:
-      T.unlines [ "#+caption: A very courageous man."
-                , "#+name: goodguy"
+      T.unlines [ "#+caption: A courageous man."
+                , "#+name: ed"
                 , "[[file:edward.jpg]]"
                 ] =?>
-      para (image "edward.jpg" "fig:goodguy" "A very courageous man.")
+      figureWith ("ed", mempty, mempty)
+             (plainCaption "A courageous man.")
+             (plain $ image "edward.jpg" mempty "")
 
   , "Figure with no name" =:
       T.unlines [ "#+caption: I've been through the desert on this"
                 , "[[file:horse.png]]"
                 ] =?>
-      para (image "horse.png" "fig:" "I've been through the desert on this")
+      figure (plainCaption "I've been through the desert on this")
+             (plain $ image "horse.png" "" "")
 
   , "Figure with `fig:` prefix in name" =:
       T.unlines [ "#+caption: Used as a metapher in evolutionary biology."
                 , "#+name: fig:redqueen"
                 , "[[./the-red-queen.jpg]]"
                 ] =?>
-      para (image "./the-red-queen.jpg" "fig:redqueen"
-                  "Used as a metapher in evolutionary biology.")
+      figureWith ("fig:redqueen", mempty, mempty)
+             (plainCaption "Used as a metapher in evolutionary biology.")
+             (plain $ image "./the-red-queen.jpg" mempty "")
 
   , "Figure with HTML attributes" =:
-      T.unlines [ "#+CAPTION: mah brain just explodid"
-                , "#+NAME: lambdacat"
-                , "#+ATTR_HTML: :style color: blue :role button"
+      T.unlines [ "#+caption: mah brain just explodid"
+                , "#+name: lambdacat"
+                , "#+attr_html: :style color: blue :role button"
                 , "[[file:lambdacat.jpg]]"
                 ] =?>
       let kv = [("style", "color: blue"), ("role", "button")]
-          name = "fig:lambdacat"
-          caption = "mah brain just explodid"
-      in para (imageWith (mempty, mempty, kv) "lambdacat.jpg" name caption)
+          name = "lambdacat"
+          capt = plain "mah brain just explodid"
+      in figureWith (name, mempty, kv) (simpleCaption capt)
+         (plain $ image "lambdacat.jpg" mempty "")
 
+  , "LaTeX attributes are ignored" =:
+      T.unlines [ "#+caption: Attribute after caption"
+                , "#+attr_latex: :float nil"
+                , "[[file:test.png]]"
+                ] =?>
+      simpleFigure "Attribute after caption"
+                   "test.png" ""
+
   , "Labelled figure" =:
-      T.unlines [ "#+CAPTION: My figure"
-                , "#+LABEL: fig:myfig"
+      T.unlines [ "#+caption: My figure"
+                , "#+label: fig:myfig"
                 , "[[file:blub.png]]"
                 ] =?>
-      let attr = ("fig:myfig", mempty, mempty)
-      in para (imageWith attr "blub.png" "fig:" "My figure")
+      figureWith ("fig:myfig", mempty, mempty)
+                 (simpleCaption $ plain "My figure")
+                 (plain (image "blub.png" "" ""))
 
   , "Figure with empty caption" =:
-      T.unlines [ "#+CAPTION:"
+      T.unlines [ "#+caption:"
                 , "[[file:guess.jpg]]"
                 ] =?>
-      para (image "guess.jpg" "fig:" "")
+      figure emptyCaption (plain (image "guess.jpg" "" ""))
   ]
+ where
+  plainCaption = simpleCaption . plain
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,4 +1,15 @@
 {-# LANGUAGE OverloadedStrings #-}
+{- |
+   Module      : Tests.Readers.Org.Block.Header
+   Copyright   : © 2014-2024 Albert Krewinkel
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : Albert Krewinkel <albert+pandoc@tarleb.com>
+   Stability   : alpha
+   Portability : portable
+
+Test parsing of org header blocks.
+-}
 module Tests.Readers.Org.Block.Header (tests) where
 
 import Test.Tasty (TestTree, testGroup)
@@ -74,12 +85,19 @@
         let todoSpan = spanWith ("", ["done", "DONE"], []) "DONE"
         in headerWith ("header", [], []) 1 (todoSpan <> space <> "header")
 
+    , "emphasis in first word" =:
+        "** TODO /fix/ this" =?>
+        let todoSpan = spanWith ("", ["todo", "TODO"], []) "TODO"
+        in headerWith ("fix-this", [], [])
+                      2
+                      (todoSpan <> space <> emph "fix" <> space <> "this")
+
     , "Header with unknown todo keyword" =:
         "* WAITING header" =?>
         headerWith ("waiting-header", [], []) 1 "WAITING header"
 
     , "Custom todo keywords" =:
-        T.unlines [ "#+TODO: WAITING CANCELLED"
+        T.unlines [ "#+todo: WAITING CANCELLED"
                   , "* WAITING compile"
                   , "* CANCELLED lunch"
                   ] =?>
@@ -89,7 +107,7 @@
         <> headerWith ("lunch", [], []) 1 (doneSpan <> space <> "lunch")
 
     , "Custom todo keywords with multiple done-states" =:
-        T.unlines [ "#+TODO: WAITING | DONE CANCELLED "
+        T.unlines [ "#+todo: WAITING | DONE CANCELLED "
                   , "* WAITING compile"
                   , "* CANCELLED lunch"
                   , "* DONE todo-feature"
@@ -100,6 +118,13 @@
         in headerWith ("compile", [], []) 1 (waiting <> space <> "compile")
         <> headerWith ("lunch", [], []) 1 (cancelled <> space <> "lunch")
         <> headerWith ("todo-feature", [], []) 1 (done <> space <> "todo-feature")
+
+    , "Fast access TODO states" =:
+        T.unlines [ "#+TODO: TODO(t) | DONE(d)"
+                  , "* TODO test"
+                  ] =?>
+        let todoSpan = spanWith ("", ["todo", "TODO"], []) "TODO"
+        in headerWith ("test", [], []) 1 (todoSpan <> space <> "test")
     ]
 
   , "Tagged headers" =:
@@ -122,6 +147,16 @@
       "* This: is not: tagged" =?>
       headerWith ("this-is-not-tagged", [], []) 1 "This: is not: tagged"
 
+  , "Untagged header time followed by colon" =:
+      "** Meeting at 5:23: free food" =?>
+      let attr = ("meeting-at-523-free-food", [], [])
+      in headerWith attr 2 "Meeting at 5:23: free food"
+
+  , "tag followed by text" =:
+      "*** Looks like a :tag: but isn't" =?>
+      let attr = ("looks-like-a-tag-but-isnt", [], [])
+      in headerWith attr 3 "Looks like a :tag: but isn't"
+
   , "Header starting with strokeout text" =:
       T.unlines [ "foo"
                 , ""
@@ -130,7 +165,7 @@
       mconcat [ para "foo"
               , headerWith ("thing-other-thing", [], [])
                            1
-                           ((strikeout "thing") <> " other thing")
+                           (strikeout "thing" <> " other thing")
               ]
 
   , "Comment Trees" =:
@@ -179,4 +214,66 @@
                 , "  :END:"
                 ] =?>
       headerWith ("not-numbered", ["unnumbered"], []) 1 "Not numbered"
+
+  , testGroup "planning information"
+    [ "Planning info is not included in output" =:
+      T.unlines [ "* important"
+                , T.unwords
+                  [ "CLOSED: [2018-09-05 Wed 13:58]"
+                  , "DEADLINE: <2018-09-17 Mon>"
+                  , "SCHEDULED: <2018-09-10 Mon>"
+                  ]
+                ] =?>
+      headerWith ("important", [], []) 1 "important"
+
+    , "Properties after planning info are recognized" =:
+      T.unlines [ "* important "
+                , "  " <> T.unwords
+                  [ "CLOSED: [2018-09-05 Wed 13:58]"
+                  , "DEADLINE: <2018-09-17 Mon>"
+                  , "SCHEDULED: <2018-09-10 Mon>"
+                  ]
+                , "  :PROPERTIES:"
+                , "  :custom_id: look"
+                , "  :END:"
+                ] =?>
+      headerWith ("look", [], []) 1 "important"
+
+    , "Planning info followed by test" =:
+      T.unlines [ "* important "
+                , "  " <> T.unwords
+                  [ "CLOSED: [2018-09-05 Wed 13:58]"
+                  , "DEADLINE: <2018-09-17 Mon>"
+                  , "SCHEDULED: <2018-09-10 Mon>"
+                  ]
+                , "  :PROPERTIES:"
+                , "  :custom_id: look"
+                , "  :END:"
+                ] =?>
+      headerWith ("look", [], []) 1 "important"
+
+    , "third and forth level headers" =:
+      T.unlines [ "#+options: p:t h:3"
+                , "*** Third"
+                , "    CLOSED: [2018-09-05 Wed 13:58]"
+                , "    Text 3"
+                , "**** Fourth"
+                , "SCHEDULED: <2019-05-13 Mon 22:42>"
+                , "Text 4"
+                ] =?>
+      mconcat
+      [ headerWith ("third", [], mempty) 3 "Third"
+      , plain $
+        strong "CLOSED:" <> space <> emph (str "[2018-09-05 Wed 13:58]")
+      , para "Text 3"
+      , orderedList [
+          mconcat
+          [ para "Fourth"
+          , plain $ strong "SCHEDULED:"
+                    <> space
+                    <> emph (str "<2019-05-13 Mon 22:42>")
+          , para "Text 4"
+          ]]
+      ]
+    ]
   ]
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,12 +1,32 @@
 {-# LANGUAGE OverloadedStrings #-}
+{- |
+   Module      : Tests.Readers.Org.Block.Header
+   Copyright   : © 2014-2024 Albert Krewinkel
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : Albert Krewinkel <albert+pandoc@tarleb.com>
+   Stability   : alpha
+   Portability : portable
+
+Test parsing of org lists.
+-}
 module Tests.Readers.Org.Block.List (tests) where
 
+import Data.Text (Text)
 import Test.Tasty (TestTree)
-import Tests.Helpers ((=?>))
+import Tests.Helpers ((=?>), purely, test)
 import Tests.Readers.Org.Shared ((=:), spcSep)
+import Text.Pandoc (ReaderOptions (readerExtensions),
+                    Extension (Ext_fancy_lists), def, enableExtension,
+                    getDefaultExtensions, readOrg)
 import Text.Pandoc.Builder
 import qualified Data.Text as T
 
+orgFancyLists :: Text -> Pandoc
+orgFancyLists = purely $
+  let extensionsFancy = enableExtension Ext_fancy_lists (getDefaultExtensions "org")
+  in readOrg def{ readerExtensions = extensionsFancy }
+
 tests :: [TestTree]
 tests =
   [ "Simple Bullet Lists" =:
@@ -16,6 +36,13 @@
                  , plain "Item2"
                  ]
 
+  , "Simple Bullet List with Ignored Counter Cookie" =:
+      ("- [@4] Item1\n" <>
+       "- Item2\n") =?>
+      bulletList [ plain "Item1"
+                 , plain "Item2"
+                 ]
+
   , "Indented Bullet Lists" =:
       ("   - Item1\n" <>
        "   - Item2\n") =?>
@@ -75,16 +102,16 @@
                  ]
 
   , "Bullet List with Decreasing Indent" =:
-       ("  - Discovery\n\
-        \ - Human After All\n") =?>
+       "  - Discovery\n\
+        \ - Human After All\n" =?>
        mconcat [ bulletList [ plain "Discovery" ]
                , bulletList [ plain ("Human" <> space <> "After" <> space <> "All")]
                ]
 
   , "Header follows Bullet List" =:
-      ("  - Discovery\n\
+      "  - Discovery\n\
        \  - Human After All\n\
-       \* Homework") =?>
+       \* Homework" =?>
       mconcat [ bulletList [ plain "Discovery"
                            , plain ("Human" <> space <> "After" <> space <> "All")
                            ]
@@ -92,9 +119,9 @@
               ]
 
   , "Bullet List Unindented with trailing Header" =:
-      ("- Discovery\n\
+      "- Discovery\n\
        \- Homework\n\
-       \* NotValidListItem") =?>
+       \* NotValidListItem" =?>
       mconcat [ bulletList [ plain "Discovery"
                            , plain "Homework"
                            ]
@@ -107,6 +134,49 @@
                 ] =?>
       bulletList [ plain "", plain "" ]
 
+  , "Task list" =:
+    T.unlines [ "- [ ] nope"
+              , "- [X] yup"
+              , "- [-] started"
+              , "  1. [X] sure"
+              , "  2. [ ] nuh-uh"
+              ] =?>
+    bulletList [ plain "☐ nope", plain "☒ yup"
+               , mconcat [ plain "☐ started"
+                         , orderedList [plain "☒ sure", plain "☐ nuh-uh"]
+                         ]
+               ]
+
+  , "Task List with Counter Cookies" =:
+    T.unlines [ "- [ ] nope"
+              , "- [@9] [X] yup"
+              , "- [@a][-] started"
+              , "  1. [@3][X] sure"
+              , "  2. [@b] [ ] nuh-uh"
+              ] =?>
+    bulletList [ plain "☐ nope", plain "☒ yup"
+               , mconcat [ plain "☐ started"
+                         , orderedListWith
+                           (3, DefaultStyle, DefaultDelim)
+                           [plain "☒ sure", plain "☐ nuh-uh"]
+                         ]
+               ]
+
+  , test orgFancyLists "Task with alphabetical markers and counter cookie" $
+    T.unlines [ "- [ ] nope"
+              , "- [@9] [X] yup"
+              , "- [@a][-] started"
+              , "  a) [@D][X] sure"
+              , "  b) [@8] [ ] nuh-uh"
+              ] =?>
+    bulletList [ plain "☐ nope", plain "☒ yup"
+               , mconcat [ plain "☐ started"
+                         , orderedListWith
+                           (4, LowerAlpha, OneParen)
+                           [plain "☒ sure", plain "☐ nuh-uh"]
+                         ]
+               ]
+
   , "Simple Ordered List" =:
       ("1. Item1\n" <>
        "2. Item2\n") =?>
@@ -116,6 +186,60 @@
                           ]
       in orderedListWith listStyle listStructure
 
+  , test orgFancyLists "Simple Ordered List with fancy lists extension" $
+      ("1. Item1\n" <>
+       "2. Item2\n") =?>
+      let listStyle = (1, Decimal, Period)
+          listStructure = [ plain "Item1"
+                          , plain "Item2"
+                          ]
+      in orderedListWith listStyle listStructure
+
+  , test orgFancyLists "Simple Ordered List with lower alpha marker" $
+      ("a) Item1\n" <>
+       "b) Item2\n") =?>
+      let listStyle = (1, LowerAlpha, OneParen)
+          listStructure = [ plain "Item1"
+                          , plain "Item2"
+                          ]
+      in orderedListWith listStyle listStructure
+
+  , test orgFancyLists "Simple Ordered List with upper and lower alpha markers" $
+      ("A. Item1\n" <>
+       "b) Item2\n") =?>
+      let listStyle = (1, UpperAlpha, Period)
+          listStructure = [ plain "Item1"
+                          , plain "Item2"
+                          ]
+      in orderedListWith listStyle listStructure
+
+  , "Simple Ordered List with Counter Cookie" =:
+      ("1. [@1234] Item1\n" <>
+       "2. Item2\n") =?>
+      let listStyle = (1234, DefaultStyle, DefaultDelim)
+          listStructure = [ plain "Item1"
+                          , plain "Item2"
+                          ]
+      in orderedListWith listStyle listStructure
+
+  , "Simple Ordered List with Alphabetical Counter Cookie" =:
+      ("1. [@c] Item1\n" <>
+       "2. Item2\n") =?>
+      let listStyle = (3, DefaultStyle, DefaultDelim)
+          listStructure = [ plain "Item1"
+                          , plain "Item2"
+                          ]
+      in orderedListWith listStyle listStructure
+
+  , "Simple Ordered List with Ignored Counter Cookie" =:
+      ("1. Item1\n" <>
+       "2. [@4] Item2\n") =?>
+      let listStyle = (1, DefaultStyle, DefaultDelim)
+          listStructure = [ plain "Item1"
+                          , plain "Item2"
+                          ]
+      in orderedListWith listStyle listStructure
+
   , "Simple Ordered List with Parens" =:
       ("1) Item1\n" <>
        "2) Item2\n") =?>
@@ -140,6 +264,19 @@
                 ] =?>
       orderedList [ plain "", plain "" ]
 
+  , test orgFancyLists "Empty ordered list item with fancy lists extension" $
+      T.unlines [ "a."
+                , "2. "
+                ] =?>
+      orderedListWith (1, LowerAlpha, Period) [ plain "", plain "" ]
+
+  , "Empty ordered list item with counter cookie" =:
+      T.unlines [ "1. [@5]"
+                , "3. [@e] "
+                ] =?>
+      let listStyle = (5, DefaultStyle, DefaultDelim)
+      in orderedListWith listStyle [ plain "", plain "" ]
+
   , "Nested Ordered Lists" =:
       ("1. One\n" <>
        "   1. One-One\n" <>
@@ -166,14 +303,14 @@
   , "Ordered List in Bullet List" =:
       ("- Emacs\n" <>
        "  1. Org\n") =?>
-      bulletList [ (plain "Emacs") <>
-                   (orderedList [ plain "Org"])
+      bulletList [ plain "Emacs" <>
+                   orderedList [ plain "Org"]
                  ]
 
   , "Bullet List in Ordered List" =:
       ("1. GNU\n" <>
        "   - Freedom\n") =?>
-      orderedList [ (plain "GNU") <> bulletList [ (plain "Freedom") ] ]
+      orderedList [ plain "GNU" <> bulletList [ plain "Freedom" ] ]
 
   , "Definition List" =:
       T.unlines [ "- PLL :: phase-locked loop"
@@ -240,5 +377,16 @@
                 ] =?>
       mconcat [ para "CLOSED: [2015-10-19 Mon 15:03]"
               , bulletList [ plain "Note taken on [2015-10-19 Mon 13:24]" ]
+              ]
+
+  , "Markup after header and list" =:
+      T.unlines [ "* headline"
+                , "- list"
+                , ""
+                , "~variable name~"
+                ] =?>
+      mconcat [ headerWith ("headline", [], []) 1 "headline"
+              , bulletList [ plain "list" ]
+              , para (code "variable name")
               ]
   ]
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,4 +1,15 @@
 {-# LANGUAGE OverloadedStrings #-}
+{- |
+   Module      : Tests.Readers.Org.Block.Table
+   Copyright   : © 2014-2024 Albert Krewinkel
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : Albert Krewinkel <albert+pandoc@tarleb.com>
+   Stability   : alpha
+   Portability : portable
+
+Test parsing of org tables.
+-}
 module Tests.Readers.Org.Block.Table (tests) where
 
 import Test.Tasty (TestTree)
@@ -11,8 +22,23 @@
              -> [Blocks]
              -> [[Blocks]]
              -> Blocks
-simpleTable' n = table "" (replicate n (AlignDefault, 0.0))
+simpleTable' n = simpleTable'' emptyCaption $ replicate n (AlignDefault, ColWidthDefault)
 
+simpleTable'' :: Caption -> [ColSpec] -> [Blocks] -> [[Blocks]] -> Blocks
+simpleTable'' = simpleTableWith'' (mempty, [], [])
+
+simpleTableWith'' :: Attr -> Caption -> [ColSpec] -> [Blocks] -> [[Blocks]] -> Blocks
+simpleTableWith'' attr capt spec headers rows
+  = tableWith attr
+              capt
+              spec
+              (TableHead nullAttr $ toHeaderRow headers)
+              [TableBody nullAttr 0 [] $ map toRow rows]
+              (TableFoot nullAttr [])
+  where
+    toRow = Row nullAttr . map simpleCell
+    toHeaderRow l = [toRow l | not (null l)]
+
 tests :: [TestTree]
 tests =
   [ "Single cell table" =:
@@ -108,12 +134,16 @@
                 , "| 1       | One  | foo  |"
                 , "| 2       | Two  | bar  |"
                 ] =?>
-      table "" (zip [AlignCenter, AlignRight, AlignDefault] [0, 0, 0])
-            []
-            [ [ plain "Numbers", plain "Text", plain "More" ]
-            , [ plain "1"      , plain "One" , plain "foo"  ]
-            , [ plain "2"      , plain "Two" , plain "bar"  ]
-            ]
+      simpleTable''
+        emptyCaption
+        (zip
+          [AlignCenter, AlignRight, AlignDefault]
+          [ColWidthDefault, ColWidthDefault, ColWidthDefault])
+        []
+        [ [ plain "Numbers", plain "Text", plain "More" ]
+        , [ plain "1"      , plain "One" , plain "foo"  ]
+        , [ plain "2"      , plain "Two" , plain "bar"  ]
+        ]
 
   , "Pipe within text doesn't start a table" =:
       "Ceci n'est pas une | pipe " =?>
@@ -130,21 +160,34 @@
                 , "| 1       | One  | foo  |"
                 , "| 2"
                 ] =?>
-      table "" (zip [AlignCenter, AlignRight] [0, 0])
-            [ plain "Numbers", plain "Text" ]
-            [ [ plain "1" , plain "One" , plain "foo" ]
-            , [ plain "2" ]
-            ]
+      simpleTable''
+        emptyCaption
+        (zip [AlignCenter, AlignRight] [ColWidthDefault, ColWidthDefault])
+        [ plain "Numbers", plain "Text" ]
+        [ [ plain "1" , plain "One" , plain "foo" ]
+        , [ plain "2" ]
+        ]
 
   , "Table with caption" =:
-      T.unlines [ "#+CAPTION: Hitchhiker's Multiplication Table"
+      T.unlines [ "#+caption: Hitchhiker's Multiplication Table"
                 , "| x |  6 |"
                 , "| 9 | 42 |"
                 ] =?>
-      table "Hitchhiker's Multiplication Table"
-            [(AlignDefault, 0), (AlignDefault, 0)]
-            []
-            [ [ plain "x", plain "6" ]
-            , [ plain "9", plain "42" ]
-            ]
+      simpleTable''
+        (simpleCaption $ plain "Hitchhiker's Multiplication Table")
+        [(AlignDefault, ColWidthDefault), (AlignDefault, ColWidthDefault)]
+        []
+        [ [ plain "x", plain "6" ]
+        , [ plain "9", plain "42" ]
+        ]
+
+  , "named table" =:
+      T.unlines [ "#+name: x-marks-the-spot"
+                , "| x |"
+                ] =?>
+      simpleTableWith'' ("x-marks-the-spot", mempty, mempty)
+                        emptyCaption
+                        (replicate 1 (AlignDefault, ColWidthDefault))
+                        mempty
+                        [ [ plain "x" ] ]
   ]
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,4 +1,15 @@
 {-# LANGUAGE OverloadedStrings #-}
+{- |
+   Module      : Tests.Readers.Org.Directive
+   Copyright   : © 2014-2024 Albert Krewinkel
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : Albert Krewinkel <albert+pandoc@tarleb.com>
+   Stability   : alpha
+   Portability : portable
+
+Tests parsing of org directives (like @#+OPTIONS@).
+-}
 module Tests.Readers.Org.Directive (tests) where
 
 import Data.Time (UTCTime (UTCTime), secondsToDiffTime)
@@ -17,7 +28,7 @@
               -> (T.Text, c)    -- ^ (input, expected value)
               -> TestTree
 testWithFiles fileDefs = test (orgWithFiles fileDefs)
-  where
+
 orgWithFiles :: [(FilePath, BS.ByteString)] -> T.Text -> Pandoc
 orgWithFiles fileDefs input =
   let readOrg' = readOrg def{ readerExtensions = getDefaultExtensions "org" }
@@ -107,8 +118,8 @@
                   ] =?>
         mconcat [ para "first block"
                 , orderedList
-                  [ (para "top-level section 1" <>
-                     orderedList [ para "subsection" ])
+                  [ para "top-level section 1" <>
+                     orderedList [ para "subsection" ]
                   , para "top-level section 2" ]
                 ]
 
@@ -137,6 +148,28 @@
                   ] =?>
         Pandoc nullMeta mempty
 
+    , "disable MathML-like entities" =:
+        T.unlines [ "#+OPTIONS: e:nil"
+                  , "Icelandic letter: \\thorn"
+                  ] =?>
+        para "Icelandic letter: \\thorn"
+
+    , testGroup "Option f"
+      [ "disable inline footnotes" =:
+        T.unlines [ "#+OPTIONS: f:nil"
+                  , "Funny![fn:funny:or not]"
+                  ] =?>
+        para "Funny!"
+
+      , "disable reference footnotes" =:
+        T.unlines [ "#+OPTIONS: f:nil"
+                  , "Burn everything[fn:1] down!"
+                  , ""
+                  , "[fn:2] Not quite everything."
+                  ] =?>
+        para "Burn everything down!"
+      ]
+
     , "disable inclusion of todo keywords" =:
         T.unlines [ "#+OPTIONS: todo:nil"
                   , "** DONE todo export"
@@ -148,6 +181,128 @@
                   , "* Headline :hello:world:"
                   ] =?>
         headerWith ("headline", [], mempty) 1 "Headline"
+
+    , testGroup "LaTeX"
+      [ testGroup "Include LaTeX fragments"
+        [ "Inline command" =:
+          T.unlines [ "#+OPTIONS: tex:t"
+                    , "Hello \\emph{Name}"
+                    ] =?>
+          para ("Hello" <> space <> rawInline "latex" "\\emph{Name}")
+
+        , "Alpha" =:
+          T.unlines [ "#+OPTIONS: tex:t"
+                    , "\\alpha"
+                    ] =?>
+          para "α"
+
+        , "equation environment" =:
+          "#+OPTIONS: tex:t\n\
+          \\\begin{equation}\n\
+          \f(x) = x^2\n\
+          \\\end{equation}"
+          =?>
+          para (rawInline "latex"
+                 "\\begin{equation}\n\
+                 \f(x) = x^2\n\
+                 \\\end{equation}")
+        ]
+
+      , testGroup "Ignore LaTeX fragments"
+        [ "Inline command" =:
+          T.unlines [ "#+OPTIONS: tex:nil"
+                    , "Hello \\emph{Emphasised}"
+                    ] =?>
+          para "Hello"
+
+        , "MathML symbol (alpha)" =:
+          T.unlines [ "#+OPTIONS: tex:nil"
+                    , "\\alpha"
+                    ] =?>
+          para "α"
+
+        , "equation environment" =:
+          T.unlines [ "#+OPTIONS: tex:nil"
+                    , "\\begin{equation}"
+                    , "f(x) = x^2"
+                    , "\\end{equation}"
+                    ] =?>
+          (para mempty)
+        ]
+
+      , testGroup "Verbatim LaTeX"
+        [ "Inline command" =:
+          T.unlines [ "#+OPTIONS: tex:verbatim"
+                    , "Hello \\emph{Emphasised}"
+                    ] =?>
+          para "Hello \\emph{Emphasised}"
+
+        , "MathML symbol (alpha)" =:
+          T.unlines [ "#+OPTIONS: tex:verbatim"
+                    , "\\alpha"
+                    ] =?>
+          para "α"
+
+        , "equation environment" =:
+          T.unlines [ "#+OPTIONS: tex:verbatim"
+                    , "\\begin{equation}"
+                    , "f(x) = x^2"
+                    , "\\end{equation}"
+                    ] =?>
+          para (str "\\begin{equation}" <> softbreak <>
+                text "f(x) = x^2" <> softbreak <>
+                str "\\end{equation}")
+        ]
+      ]
+
+    , testGroup "planning information"
+      [ "include planning info after headlines" =:
+        T.unlines [ "#+OPTIONS: p:t"
+                  , "* important"
+                  , "  DEADLINE: <2018-10-01 Mon> SCHEDULED: <2018-09-15 Sat>"
+                  ] =?>
+        mconcat [ headerWith ("important", mempty, mempty) 1 "important"
+                , plain $ strong "DEADLINE:"
+                       <> space
+                       <> emph (str "<2018-10-01 Mon>")
+                       <> space
+                       <> strong "SCHEDULED:"
+                       <> space
+                       <> emph (str "<2018-09-15 Sat>")
+                ]
+
+      , "empty planning info is not included" =:
+        T.unlines [ "#+OPTIONS: p:t"
+                  , "* Wichtig"
+                  ] =?>
+        headerWith ("wichtig", mempty, mempty) 1 "Wichtig"
+      ]
+
+    , testGroup "Option |"
+      [ "disable export of tables" =:
+        T.unlines [ "#+OPTIONS: |:nil"
+                  , "| chair |"
+                  ] =?>
+        (mempty :: Blocks)
+      ]
+
+    , testGroup "unknown options"
+      [ "unknown options are ignored" =:
+          T.unlines [ "#+OPTIONS: does-not-exist:t "] =?>
+          (mempty :: Pandoc)
+
+      , "highlighting after unknown option" =:
+          T.unlines [ "#+OPTIONS: nope"
+                    , "/yup/"
+                    ] =?>
+          para (emph "yup")
+
+      , "unknown option interleaved with known" =:
+          T.unlines [ "#+OPTIONS: tags:nil foo:bar todo:nil"
+                    , "* DONE ignore things  :easy:"
+                    ] =?>
+          headerWith ("ignore-things", [], mempty) 1 "ignore things"
+      ]
     ]
 
   , testGroup "Include"
@@ -167,9 +322,14 @@
        headerWith ("level3", [], []) 3 "Level3")
 
     , testWithFiles [("./level3.org", "*** Level3\n\n")]
-      "Minlevel shifts level"
+      "Minlevel shifts level leftward"
       (T.unlines [ "#+include: \"level3.org\" :minlevel 1" ] =?>
        headerWith ("level3", [], []) 1 "Level3")
+
+    , testWithFiles [("./level1.org", "* Level1\n\n")]
+      "Minlevel shifts level rightward"
+      (T.unlines [ "#+include: \"level1.org\" :minlevel 3" ] =?>
+       headerWith ("level1", [], []) 3 "Level1")
 
     , testWithFiles [("./src.hs", "putStrLn outString\n")]
       "Include file as source code snippet"
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,14 +1,24 @@
 {-# LANGUAGE OverloadedStrings #-}
+{- |
+   Module      : Tests.Readers.Org.Inline
+   Copyright   : © 2014-2024 Albert Krewinkel
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : Albert Krewinkel <albert+pandoc@tarleb.com>
+   Stability   : alpha
+   Portability : portable
+
+Tests parsing of org inlines.
+-}
 module Tests.Readers.Org.Inline (tests) where
 
 import Data.List (intersperse)
 import Test.Tasty (TestTree, testGroup)
 import Tests.Helpers ((=?>))
 import Tests.Readers.Org.Shared ((=:), spcSep)
-import Text.Pandoc
 import Text.Pandoc.Builder
-import Text.Pandoc.Shared (underlineSpan)
 import qualified Data.Text as T
+import qualified Tests.Readers.Org.Inline.Citation as Citation
 import qualified Tests.Readers.Org.Inline.Note as Note
 import qualified Tests.Readers.Org.Inline.Smart as Smart
 
@@ -36,7 +46,7 @@
 
   , "Underline" =:
       "_underline_" =?>
-      para (underlineSpan $ "underline")
+      para (underline "underline")
 
   , "Strikeout" =:
       "+Kill Bill+" =?>
@@ -44,7 +54,7 @@
 
   , "Verbatim" =:
       "=Robot.rock()=" =?>
-      para (code "Robot.rock()")
+      para (codeWith ("", ["verbatim"], []) "Robot.rock()")
 
   , "Code" =:
       "~word for word~" =?>
@@ -78,6 +88,10 @@
       "2^{n-1}" =?>
       para (str "2" <> superscript "n-1")
 
+  , "Superscript-like, but not after string" =:
+      "a ^caret" =?>
+      para "a ^caret"
+
   , "Subscript simple expression" =:
       "a_n" =?>
       para (str "a" <> subscript "n")
@@ -86,6 +100,14 @@
       "a_{n+1}" =?>
       para (str "a" <> subscript "n+1")
 
+  , "Subscript-like, but not after string" =:
+      "_underscore" =?>
+      para "_underscore"
+
+  , "Subscript takes precedence before underline" =:
+      "text_subscript_" =?>
+      para (str "text" <> subscript "subscript" <> str "_")
+
   , "Linebreak" =:
       "line \\\\ \nbreak" =?>
       para ("line" <> linebreak <> "break")
@@ -94,8 +116,10 @@
       "[fn::Schreib mir eine E-Mail]" =?>
       para (note $ para "Schreib mir eine E-Mail")
 
-  , "Markup-chars not occuring on word break are symbols" =:
-      T.unlines [ "this+that+ +so+on"
+  , "By default, markup-chars not occurring on word break are symbols" =:
+      T.unlines [ "#+pandoc-emphasis-pre:"
+                , "#+pandoc-emphasis-post:"
+                , "this+that+ +so+on"
                 , "seven*eight* nine*"
                 , "+not+funny+"
                 ] =?>
@@ -108,12 +132,13 @@
       para (spcSep [ "//", "**", "__", "<>", "==", "~~", "$$" ])
 
   , "Adherence to Org's rules for markup borders" =:
-      "/t/& a/ / ./r/ (*l*) /e/! /b/." =?>
+      "/t/& a/ / ./r/ (*l*) /e/! ze\x200b/r/\x200bo /b/." =?>
       para (spcSep [ emph $ "t/&" <> space <> "a"
                    , "/"
                    , "./r/"
                    , "(" <> strong "l" <> ")"
                    , emph "e" <> "!"
+                   , "ze\x200b" <> emph "r" <> "\x200bo"
                    , emph "b" <> "."
                    ])
 
@@ -125,13 +150,18 @@
       "/nada /" =?>
       para "/nada /"
 
+  , "Zero width spaces are forbidden border chars" =:
+      "/emph\x200b/asis" =?>
+      para "/emph\x200b/asis"
+
   , "Markup should work properly after a blank line" =:
     T.unlines ["foo", "", "/bar/"] =?>
-    (para $ text "foo") <> (para $ emph $ text "bar")
+    para (text "foo") <>
+    para (emph $ text "bar")
 
   , "Inline math must stay within three lines" =:
       T.unlines [ "$a", "b", "c$", "$d", "e", "f", "g$" ] =?>
-      para ((math "a\nb\nc") <> softbreak <>
+      para (math "a\nb\nc" <> softbreak <>
             "$d" <> softbreak <> "e" <> softbreak <>
             "f" <> softbreak <> "g$")
 
@@ -139,7 +169,7 @@
       "$a$ $b$! $c$?" =?>
       para (spcSep [ math "a"
                    , "$b$!"
-                   , (math "c") <> "?"
+                   , math "c" <> "?"
                    ])
 
   , "Markup may not span more than two lines" =:
@@ -166,109 +196,129 @@
      para (mconcat $ intersperse softbreak
                   [ "a" <> subscript "(a(b)(c)d)"
                   , "e" <> superscript "(f(g)h)"
-                  , "i" <> (subscript "(jk)") <> "l)"
-                  , "m" <> (superscript "()") <> "n"
+                  , "i" <> subscript "(jk)" <> "l)"
+                  , "m" <> superscript "()" <> "n"
                   , "o" <> subscript "p{q{}r}"
                   , "s" <> superscript "t{u}v"
-                  , "w" <> (subscript "xy") <> "z}"
-                  , "1" <> (superscript "") <> "2"
+                  , "w" <> subscript "xy" <> "z}"
+                  , "1" <> superscript "" <> "2"
                   , "3" <> subscript "{}"
                   , "4" <> superscript ("(a(" <> strong "b(c" <> ")d))")
                   ])
-  , "Verbatim text can contain equal signes (=)" =:
+  , "Verbatim text can contain equal signs (=)" =:
       "=is_subst = True=" =?>
-      para (code "is_subst = True")
+      para (codeWith ("", ["verbatim"], []) "is_subst = True")
 
   , testGroup "Images"
     [ "Image" =:
-        "[[./sunset.jpg]]" =?>
-        (para $ image "./sunset.jpg" "" "")
+      "[[./sunset.jpg]]" =?>
+      para (image "./sunset.jpg" "" "")
 
     , "Image with explicit file: prefix" =:
-        "[[file:sunrise.jpg]]" =?>
-        (para $ image "sunrise.jpg" "" "")
+      "[[file:sunrise.jpg]]" =?>
+      para (image "sunrise.jpg" "" "")
 
     , "Multiple images within a paragraph" =:
-        T.unlines [ "[[file:sunrise.jpg]]"
-                  , "[[file:sunset.jpg]]"
-                  ] =?>
-        (para $ (image "sunrise.jpg" "" "")
+      T.unlines [ "[[file:sunrise.jpg]]"
+                , "[[file:sunset.jpg]]"
+                ] =?>
+      para (image "sunrise.jpg" "" ""
              <> softbreak
-             <> (image "sunset.jpg" "" ""))
+             <> image "sunset.jpg" "" "")
 
     , "Image with html attributes" =:
-        T.unlines [ "#+ATTR_HTML: :width 50%"
-                  , "[[file:guinea-pig.gif]]"
-                  ] =?>
-        (para $ imageWith ("", [], [("width", "50%")]) "guinea-pig.gif" "" "")
+      T.unlines [ "#+attr_html: :width 50%"
+                , "[[file:guinea-pig.gif]]"
+                ] =?>
+      para (imageWith ("", [], [("width", "50%")]) "guinea-pig.gif" "" "")
+
+    , "HTML attributes can have trailing spaces" =:
+      T.unlines [ "#+attr_html: :width 100% :height 360px  "
+                , "[[file:fireworks.jpg]]"
+                ] =?>
+      let kv = [("width", "100%"), ("height", "360px")]
+      in para (imageWith (mempty, mempty, kv) "fireworks.jpg" mempty mempty)
+
+
+    , "Uppercase extension" =:
+      "[[file:test.PNG]]" =?>
+      para (image "test.PNG" "" "")
     ]
 
   , "Explicit link" =:
       "[[http://zeitlens.com/][pseudo-random /nonsense/]]" =?>
-      (para $ link "http://zeitlens.com/" ""
+    para (link "http://zeitlens.com/" ""
                    ("pseudo-random" <> space <> emph "nonsense"))
 
   , "Self-link" =:
       "[[http://zeitlens.com/]]" =?>
-      (para $ link "http://zeitlens.com/" "" "http://zeitlens.com/")
+    para (link "http://zeitlens.com/" "" "http://zeitlens.com/")
 
+  , "Internal self-link (reference)" =:
+    "[[#rabbit]]" =?>
+    para (link "#rabbit" "" "#rabbit")
+
   , "Absolute file link" =:
       "[[/url][hi]]" =?>
-      (para $ link "file:///url" "" "hi")
+    para (link "file:///url" "" "hi")
 
   , "Link to file in parent directory" =:
       "[[../file.txt][moin]]" =?>
-      (para $ link "../file.txt" "" "moin")
+    para (link "../file.txt" "" "moin")
 
   , "Empty link (for gitit interop)" =:
       "[[][New Link]]" =?>
-      (para $ link "" "" "New Link")
+    para (link "" "" "New Link")
 
   , "Image link" =:
       "[[sunset.png][file:dusk.svg]]" =?>
-      (para $ link "sunset.png" "" (image "dusk.svg" "" ""))
+    para (link "sunset.png" "" (image "dusk.svg" "" ""))
 
   , "Image link with non-image target" =:
       "[[http://example.com][./logo.png]]" =?>
-      (para $ link "http://example.com" "" (image "./logo.png" "" ""))
+    para (link "http://example.com" "" (image "./logo.png" "" ""))
 
+  , "Link to image" =:
+    "[[https://example.com/image.jpg][Look!]]" =?>
+    para (link "https://example.com/image.jpg" "" (str "Look!"))
+
   , "Plain link" =:
       "Posts on http://zeitlens.com/ can be funny at times." =?>
-      (para $ spcSep [ "Posts", "on"
+    para (spcSep [ "Posts", "on"
                      , link "http://zeitlens.com/" "" "http://zeitlens.com/"
                      , "can", "be", "funny", "at", "times."
                      ])
 
   , "Angle link" =:
       "Look at <http://moltkeplatz.de> for fnords." =?>
-      (para $ spcSep [ "Look", "at"
+    para (spcSep [ "Look", "at"
                      , link "http://moltkeplatz.de" "" "http://moltkeplatz.de"
                      , "for", "fnords."
                      ])
 
   , "Absolute file link" =:
       "[[file:///etc/passwd][passwd]]" =?>
-      (para $ link "file:///etc/passwd" "" "passwd")
+    para (link "file:///etc/passwd" "" "passwd")
 
   , "File link" =:
       "[[file:target][title]]" =?>
-      (para $ link "target" "" "title")
+    para (link "target" "" "title")
 
   , "Anchor" =:
       "<<anchor>> Link here later." =?>
-      (para $ spanWith ("anchor", [], []) mempty <>
+    para (spanWith ("anchor", [], []) mempty <>
               "Link" <> space <> "here" <> space <> "later.")
 
   , "Inline code block" =:
       "src_emacs-lisp{(message \"Hello\")}" =?>
-      (para $ codeWith ( ""
+    para (codeWith ( ""
                        , [ "commonlisp" ]
                        , [ ("org-language", "emacs-lisp") ])
                        "(message \"Hello\")")
 
   , "Inline code block with arguments" =:
       "src_sh[:export both :results output]{echo 'Hello, World'}" =?>
-      (para $ codeWith ( ""
+    para (codeWith ( ""
                        , [ "bash" ]
                        , [ ("org-language", "sh")
                          , ("export", "both")
@@ -277,9 +327,16 @@
                        )
                        "echo 'Hello, World'")
 
+  , "Inline code block with a blank argument array" =:
+      "src_sh[]{echo 'Hello, World'}" =?>
+    para (codeWith ( ""
+                       , [ "bash" ]
+                       , [ ("org-language", "sh") ])
+                       "echo 'Hello, World'")
+
   , "Inline code block with toggle" =:
       "src_sh[:toggle]{echo $HOME}" =?>
-      (para $ codeWith ( ""
+    para (codeWith ( ""
                        , [ "bash" ]
                        , [ ("org-language", "sh")
                          , ("toggle", "yes")
@@ -287,161 +344,6 @@
                        )
                        "echo $HOME")
 
-  , "Citation" =:
-      "[@nonexistent]" =?>
-      let citation = Citation
-                     { citationId = "nonexistent"
-                     , citationPrefix = []
-                     , citationSuffix = []
-                     , citationMode = NormalCitation
-                     , citationNoteNum = 0
-                     , citationHash = 0}
-      in (para $ cite [citation] "[@nonexistent]")
-
-  , "Citation containing text" =:
-      "[see @item1 p. 34-35]" =?>
-      let citation = Citation
-                     { citationId = "item1"
-                     , citationPrefix = [Str "see"]
-                     , citationSuffix = [Space ,Str "p.",Space,Str "34-35"]
-                     , citationMode = NormalCitation
-                     , citationNoteNum = 0
-                     , citationHash = 0}
-      in (para $ cite [citation] "[see @item1 p. 34-35]")
-
-  , "Org-ref simple citation" =:
-    "cite:pandoc" =?>
-    let citation = Citation
-                   { citationId = "pandoc"
-                   , citationPrefix = mempty
-                   , citationSuffix = mempty
-                   , citationMode = AuthorInText
-                   , citationNoteNum = 0
-                   , citationHash = 0
-                   }
-    in (para $ cite [citation] "cite:pandoc")
-
-  , "Org-ref simple citation with underscores" =:
-    "cite:pandoc_org_ref" =?>
-    let citation = Citation
-                   { citationId = "pandoc_org_ref"
-                   , citationPrefix = mempty
-                   , citationSuffix = mempty
-                   , citationMode = AuthorInText
-                   , citationNoteNum = 0
-                   , citationHash = 0
-                   }
-    in (para $ cite [citation] "cite:pandoc_org_ref")
-
-  , "Org-ref simple citation succeeded by comma" =:
-    "cite:pandoc," =?>
-    let citation = Citation
-                   { citationId = "pandoc"
-                   , citationPrefix = mempty
-                   , citationSuffix = mempty
-                   , citationMode = AuthorInText
-                   , citationNoteNum = 0
-                   , citationHash = 0
-                   }
-    in (para $ cite [citation] "cite:pandoc" <> str ",")
-
-  , "Org-ref simple citation succeeded by dot" =:
-    "cite:pandoc." =?>
-    let citation = Citation
-                   { citationId = "pandoc"
-                   , citationPrefix = mempty
-                   , citationSuffix = mempty
-                   , citationMode = AuthorInText
-                   , citationNoteNum = 0
-                   , citationHash = 0
-                   }
-    in (para $ cite [citation] "cite:pandoc" <> str ".")
-
-  , "Org-ref simple citation succeeded by colon" =:
-    "cite:pandoc:" =?>
-    let citation = Citation
-                   { citationId = "pandoc"
-                   , citationPrefix = mempty
-                   , citationSuffix = mempty
-                   , citationMode = AuthorInText
-                   , citationNoteNum = 0
-                   , citationHash = 0
-                   }
-    in (para $ cite [citation] "cite:pandoc" <> str ":")
-
-  , "Org-ref simple citep citation" =:
-    "citep:pandoc" =?>
-    let citation = Citation
-                   { citationId = "pandoc"
-                   , citationPrefix = mempty
-                   , citationSuffix = mempty
-                   , citationMode = NormalCitation
-                   , citationNoteNum = 0
-                   , citationHash = 0
-                   }
-    in (para $ cite [citation] "citep:pandoc")
-
-  , "Org-ref extended citation" =:
-    "[[citep:Dominik201408][See page 20::, for example]]" =?>
-    let citation = Citation
-                   { citationId = "Dominik201408"
-                   , citationPrefix = toList "See page 20"
-                   , citationSuffix = toList ", for example"
-                   , citationMode = NormalCitation
-                   , citationNoteNum = 0
-                   , citationHash = 0
-                   }
-    in (para $ cite [citation] "[[citep:Dominik201408][See page 20::, for example]]")
-
-  , testGroup "Berkeley-style citations" $
-    let pandocCite = Citation
-          { citationId = "Pandoc"
-          , citationPrefix = mempty
-          , citationSuffix = mempty
-          , citationMode = NormalCitation
-          , citationNoteNum = 0
-          , citationHash = 0
-          }
-        pandocInText = pandocCite { citationMode = AuthorInText }
-        dominikCite = Citation
-          { citationId = "Dominik201408"
-          , citationPrefix = mempty
-          , citationSuffix = mempty
-          , citationMode = NormalCitation
-          , citationNoteNum = 0
-          , citationHash = 0
-          }
-        dominikInText = dominikCite { citationMode = AuthorInText }
-    in [
-        "Berkeley-style in-text citation" =:
-          "See @Dominik201408." =?>
-            (para $ "See "
-                  <> cite [dominikInText] "@Dominik201408"
-                  <> ".")
-
-      , "Berkeley-style parenthetical citation list" =:
-          "[(cite): see; @Dominik201408;also @Pandoc; and others]" =?>
-          let pandocCite'  = pandocCite {
-                               citationPrefix = toList "also"
-                             , citationSuffix = toList "and others"
-                             }
-              dominikCite' = dominikCite {
-                               citationPrefix = toList "see"
-                             }
-          in (para $ cite [dominikCite', pandocCite'] "")
-
-      , "Berkeley-style plain citation list" =:
-          "[cite: See; @Dominik201408; and @Pandoc; and others]" =?>
-          let pandocCite' = pandocInText {
-                              citationPrefix = toList "and"
-                            }
-          in (para $ "See "
-                  <> cite [dominikInText] ""
-                  <> "," <> space
-                  <> cite [pandocCite'] ""
-                  <> "," <> space <> "and others")
-    ]
-
   , "Inline LaTeX symbol" =:
       "\\dots" =?>
       para "…"
@@ -452,12 +354,16 @@
 
   , "Inline LaTeX command with spaces" =:
       "\\emph{Emphasis mine}" =?>
-      para (emph "Emphasis mine")
+      para (rawInline "latex" "\\emph{Emphasis mine}")
 
-  , "Inline LaTeX math symbol" =:
-      "\\tau" =?>
-      para (emph "τ")
+  , "Inline math symbols" =:
+      "\\tau \\oplus \\alpha" =?>
+      para "τ ⊕ α"
 
+  , "Inline LaTeX math command" =:
+      "\\crarr" =?>
+      para "↵"
+
   , "Unknown inline LaTeX command" =:
       "\\notacommand{foo}" =?>
       para (rawInline "latex" "\\notacommand{foo}")
@@ -468,7 +374,7 @@
 
   , "MathML symbol in LaTeX-style" =:
       "There is a hackerspace in Lübeck, Germany, called nbsp (unicode symbol: '\\nbsp')." =?>
-      para ("There is a hackerspace in Lübeck, Germany, called nbsp (unicode symbol: ' ').")
+      para "There is a hackerspace in Lübeck, Germany, called nbsp (unicode symbol: ' ')."
 
   , "MathML symbol in LaTeX-style, including braces" =:
       "\\Aacute{}stor" =?>
@@ -482,24 +388,13 @@
       "\\ForAll \\Auml" =?>
       para "∀ Ä"
 
-  , "LaTeX citation" =:
-      "\\cite{Coffee}" =?>
-      let citation = Citation
-                     { citationId = "Coffee"
-                     , citationPrefix = []
-                     , citationSuffix = []
-                     , citationMode = NormalCitation
-                     , citationNoteNum = 0
-                     , citationHash = 0}
-      in (para . cite [citation] $ rawInline "latex" "\\cite{Coffee}")
-
   , "Macro" =:
       T.unlines [ "#+MACRO: HELLO /Hello, $1/"
                 , "{{{HELLO(World)}}}"
                 ] =?>
       para (emph "Hello, World")
 
-  , "Macro repeting its argument" =:
+  , "Macro duplicating its argument" =:
       T.unlines [ "#+MACRO: HELLO $1$1"
                 , "{{{HELLO(moin)}}}"
                 ] =?>
@@ -510,7 +405,13 @@
                 , "{{{HELLO()}}}"
                 ] =?>
       para "Foo Bar"
+  , "Macro called with an escaped comma" =:
+      T.unlines [ "#+MACRO: HELLO Foo $1"
+                , "{{{HELLO(moin\\, niom)}}}"
+                ] =?>
+      para "Foo moin, niom"
 
+  , testGroup "Citations" Citation.tests
   , testGroup "Footnotes" Note.tests
   , testGroup "Smart punctuation" Smart.tests
   ]
diff --git a/test/Tests/Readers/Org/Inline/Citation.hs b/test/Tests/Readers/Org/Inline/Citation.hs
new file mode 100644
--- /dev/null
+++ b/test/Tests/Readers/Org/Inline/Citation.hs
@@ -0,0 +1,206 @@
+{-# LANGUAGE OverloadedStrings #-}
+{- |
+   Module      : Tests.Readers.Org.Inline.Citation
+   Copyright   : © 2014-2024 Albert Krewinkel
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : Albert Krewinkel <albert+pandoc@tarleb.com>
+   Stability   : alpha
+   Portability : portable
+
+Test parsing of citations in org input.
+-}
+module Tests.Readers.Org.Inline.Citation (tests) where
+
+import Test.Tasty (TestTree, testGroup)
+import Tests.Helpers ((=?>))
+import Tests.Readers.Org.Shared ((=:))
+import Text.Pandoc.Builder
+
+tests :: [TestTree]
+tests =
+  [ testGroup "Org-cite citations"
+    [ "Citation" =:
+      "[cite:@nonexistent]" =?>
+      let citation = Citation
+                     { citationId = "nonexistent"
+                     , citationPrefix = []
+                     , citationSuffix = []
+                     , citationMode = NormalCitation
+                     , citationNoteNum = 0
+                     , citationHash = 0}
+      in (para $ cite [citation] "[cite:@nonexistent]")
+
+    , "Citation containing text" =:
+      "[cite:see @item1 p. 34-35]" =?>
+      let citation = Citation
+                     { citationId = "item1"
+                     , citationPrefix = [Str "see"]
+                     , citationSuffix = [Space ,Str "p.",Space,Str "34-35"]
+                     , citationMode = NormalCitation
+                     , citationNoteNum = 0
+                     , citationHash = 0}
+      in (para $ cite [citation] "[cite:see @item1 p. 34-35]")
+
+    , "Author-in-text citation with locator and suffix" =:
+      "[cite/t:see @item1 p. 34-35 and *passim*; @item2]" =?>
+      let citations =
+            [ Citation
+                { citationId = "item1"
+                , citationPrefix = [ Str "see" ]
+                , citationSuffix =
+                    [ Str "p."
+                    , Space
+                    , Str "34-35"
+                    , Space
+                    , Str "and"
+                    , Space
+                    , Strong [ Str "passim" ]
+                    ]
+                , citationMode = AuthorInText
+                , citationNoteNum = 0
+                , citationHash = 0
+                }
+            , Citation
+                { citationId = "item2"
+                , citationPrefix = []
+                , citationSuffix = []
+                , citationMode = NormalCitation
+                , citationNoteNum = 0
+                , citationHash = 0
+                }
+            ]
+      in (para $ cite citations "[cite/t:see @item1 p. 34-35 and *passim*; @item2]")
+    ]
+
+  , testGroup "org-ref citations"
+    [ "simple citation" =:
+      "cite:pandoc" =?>
+      let citation = Citation
+                     { citationId = "pandoc"
+                     , citationPrefix = mempty
+                     , citationSuffix = mempty
+                     , citationMode = AuthorInText
+                     , citationNoteNum = 0
+                     , citationHash = 0
+                     }
+      in (para $ cite [citation] "cite:pandoc")
+
+    , "simple citation with underscores" =:
+      "cite:pandoc_org_ref" =?>
+      let citation = Citation
+                     { citationId = "pandoc_org_ref"
+                     , citationPrefix = mempty
+                     , citationSuffix = mempty
+                     , citationMode = AuthorInText
+                     , citationNoteNum = 0
+                     , citationHash = 0
+                     }
+      in (para $ cite [citation] "cite:pandoc_org_ref")
+
+    , "simple citation succeeded by comma" =:
+      "cite:pandoc," =?>
+      let citation = Citation
+                     { citationId = "pandoc"
+                     , citationPrefix = mempty
+                     , citationSuffix = mempty
+                     , citationMode = AuthorInText
+                     , citationNoteNum = 0
+                     , citationHash = 0
+                     }
+      in (para $ cite [citation] "cite:pandoc" <> str ",")
+
+    , "simple citation succeeded by dot" =:
+      "cite:pandoc." =?>
+      let citation = Citation
+                     { citationId = "pandoc"
+                     , citationPrefix = mempty
+                     , citationSuffix = mempty
+                     , citationMode = AuthorInText
+                     , citationNoteNum = 0
+                     , citationHash = 0
+                     }
+      in (para $ cite [citation] "cite:pandoc" <> str ".")
+
+    , "simple citation succeeded by colon" =:
+      "cite:pandoc:" =?>
+      let citation = Citation
+                     { citationId = "pandoc"
+                     , citationPrefix = mempty
+                     , citationSuffix = mempty
+                     , citationMode = AuthorInText
+                     , citationNoteNum = 0
+                     , citationHash = 0
+                     }
+      in (para $ cite [citation] "cite:pandoc" <> str ":")
+
+    , "simple citep citation" =:
+      "citep:pandoc" =?>
+      let citation = Citation
+                     { citationId = "pandoc"
+                     , citationPrefix = mempty
+                     , citationSuffix = mempty
+                     , citationMode = NormalCitation
+                     , citationNoteNum = 0
+                     , citationHash = 0
+                     }
+      in (para $ cite [citation] "citep:pandoc")
+
+    , "multiple simple citations" =:
+      "citep:picard,riker" =?>
+      let picard = Citation
+                 { citationId = "picard"
+                 , citationPrefix = mempty
+                 , citationSuffix = mempty
+                 , citationMode = NormalCitation
+                 , citationNoteNum = 0
+                 , citationHash = 0
+                 }
+          riker  = Citation
+                 { citationId = "riker"
+                 , citationPrefix = mempty
+                 , citationSuffix = mempty
+                 , citationMode = NormalCitation
+                 , citationNoteNum = 0
+                 , citationHash = 0
+                 }
+      in (para $ cite [picard,riker] "citep:picard,riker")
+
+    , "multiple simple citations succeeded by comma" =:
+      "citep:picard,riker," =?>
+      let picard = Citation
+                 { citationId = "picard"
+                 , citationPrefix = mempty
+                 , citationSuffix = mempty
+                 , citationMode = NormalCitation
+                 , citationNoteNum = 0
+                 , citationHash = 0
+                 }
+          riker  = Citation
+                 { citationId = "riker"
+                 , citationPrefix = mempty
+                 , citationSuffix = mempty
+                 , citationMode = NormalCitation
+                 , citationNoteNum = 0
+                 , citationHash = 0
+                 }
+      in (para $ cite [picard,riker] "citep:picard,riker" <> str ",")
+
+    , "extended citation" =:
+      "[[citep:Dominik201408][See page 20::, for example]]" =?>
+      let citation = Citation
+                     { citationId = "Dominik201408"
+                     , citationPrefix = toList "See page 20"
+                     , citationSuffix = toList ", for example"
+                     , citationMode = NormalCitation
+                     , citationNoteNum = 0
+                     , citationHash = 0
+                     }
+      in (para $ cite [citation] "[[citep:Dominik201408][See page 20::, for example]]")
+    ]
+
+  , "LaTeX citation" =:
+    "\\cite{Coffee}" =?>
+      para (rawInline "latex" "\\cite{Coffee}")
+
+  ]
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,4 +1,15 @@
 {-# LANGUAGE OverloadedStrings #-}
+{- |
+   Module      : Tests.Readers.Org.Inline.Note
+   Copyright   : © 2014-2024 Albert Krewinkel
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : Albert Krewinkel <albert+pandoc@tarleb.com>
+   Stability   : alpha
+   Portability : portable
+
+Test parsing of footnotes in org input.
+-}
 module Tests.Readers.Org.Inline.Note (tests) where
 
 import Test.Tasty (TestTree)
@@ -84,4 +95,3 @@
       , para "next"
       ]
   ]
-  
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,4 +1,15 @@
 {-# LANGUAGE OverloadedStrings #-}
+{- |
+   Module      : Tests.Readers.Org.Inline.Smart
+   Copyright   : © 2014-2024 Albert Krewinkel
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : Albert Krewinkel <albert+pandoc@tarleb.com>
+   Stability   : alpha
+   Portability : portable
+
+Test smart parsing of quotes, apostrophe, etc.
+-}
 module Tests.Readers.Org.Inline.Smart (tests) where
 
 import Data.Text (Text)
@@ -36,11 +47,15 @@
     ("/foo---/" =?>
      para (emph "foo—"))
 
+  , test orgSmart "Support for shy (soft) hyphen"
+    ("Ur\\-instinkt" =?>
+     para "Ur\173instinkt")
+
   , test orgSmart "Single quotes can be followed by emphasized text"
     ("Singles on the '/meat market/'" =?>
-     para ("Singles on the " <> (singleQuoted $ emph "meat market")))
+     para ("Singles on the " <> singleQuoted (emph "meat market")))
 
   , test orgSmart "Double quotes can be followed by emphasized text"
     ("Double income, no kids: \"/DINK/\"" =?>
-     para ("Double income, no kids: " <> (doubleQuoted $ emph "DINK")))
+     para ("Double income, no kids: " <> doubleQuoted (emph "DINK")))
   ]
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,7 +1,18 @@
 {-# LANGUAGE OverloadedStrings #-}
+{- |
+   Module      : Tests.Readers.Org.Meta
+   Copyright   : © 2014-2024 Albert Krewinkel
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : Albert Krewinkel <albert+pandoc@tarleb.com>
+   Stability   : alpha
+   Portability : portable
+
+Tests parsing of org meta data (mostly lines starting with @#+@).
+-}
 module Tests.Readers.Org.Meta (tests) where
 
-import Test.Tasty (TestTree)
+import Test.Tasty (TestTree, testGroup)
 import Tests.Helpers ((=?>))
 import Tests.Readers.Org.Shared ((=:), spcSep)
 import Text.Pandoc
@@ -10,15 +21,16 @@
 
 tests :: [TestTree]
 tests =
-  [ "Comment" =:
+  [ testGroup "Comments"
+    [ "Comment" =:
       "# Nothing to see here" =?>
       (mempty::Blocks)
 
-  , "Not a comment" =:
+    , "Hash not followed by space is text" =:
       "#-tag" =?>
       para "#-tag"
 
-  , "Comment surrounded by Text" =:
+    , "Comment surrounded by Text" =:
       T.unlines [ "Before"
                 , "# Comment"
                 , "After"
@@ -26,77 +38,215 @@
       mconcat [ para "Before"
               , para "After"
               ]
+    ]
 
-  , "Title" =:
-    "#+TITLE: Hello, World" =?>
-    let titleInline = toList $ "Hello," <> space <> "World"
-        meta = setMeta "title" (MetaInlines titleInline) $ nullMeta
-    in Pandoc meta mempty
+  , testGroup "Export settings"
+    [ "Title" =:
+      "#+title: Hello, World" =?>
+      let titleInline = toList $ "Hello," <> space <> "World"
+          meta = setMeta "title" (MetaInlines titleInline) nullMeta
+      in Pandoc meta mempty
 
-  , "Author" =:
-    "#+author: John /Emacs-Fanboy/ Doe" =?>
-    let author = toList . spcSep $ [ "John", emph "Emacs-Fanboy", "Doe" ]
-        meta = setMeta "author" (MetaList [MetaInlines author]) $ nullMeta
-    in Pandoc meta mempty
+    , testGroup "Author"
+      [ "sets 'author' field" =:
+        "#+author: John /Emacs-Fanboy/ Doe" =?>
+        let author = toList . spcSep $ [ "John", emph "Emacs-Fanboy", "Doe" ]
+            meta = setMeta "author" (MetaInlines author) nullMeta
+        in Pandoc meta mempty
 
-  , "Multiple authors" =:
-    "#+author: James Dewey Watson, Francis Harry Compton Crick " =?>
-    let watson = MetaInlines $ toList "James Dewey Watson"
-        crick = MetaInlines $ toList "Francis Harry Compton Crick"
-        meta = setMeta "author" (MetaList [watson, crick]) $ nullMeta
-    in Pandoc meta mempty
+      , "Multiple author lines" =:
+        T.unlines [ "#+author: James Dewey Watson,"
+                  , "#+author: Francis Harry Compton Crick"
+                  ] =?>
+        let watson = toList "James Dewey Watson,"
+            crick = toList "Francis Harry Compton Crick"
+            meta = setMeta "author"
+                           (MetaInlines (watson ++ SoftBreak : crick))
+                           nullMeta
+        in Pandoc meta mempty
+      ]
 
-  , "Date" =:
-    "#+Date: Feb. *28*, 2014" =?>
-    let date = toList . spcSep $ [ "Feb.", (strong "28") <> ",", "2014" ]
-        meta = setMeta "date" (MetaInlines date) $ nullMeta
-    in Pandoc meta mempty
+    , "Date" =:
+      "#+date: Feb. *28*, 2014" =?>
+      let date = toList . spcSep $ [ "Feb.", strong "28" <> ",", "2014" ]
+          meta = setMeta "date" (MetaInlines date) nullMeta
+      in Pandoc meta mempty
 
-  , "Description" =:
-    "#+DESCRIPTION: Explanatory text" =?>
-    let description = "Explanatory text"
-        meta = setMeta "description" (MetaString description) $ nullMeta
-    in Pandoc meta mempty
+    , testGroup "Description"
+      [ "Single line" =:
+        "#+description: Explanatory text" =?>
+        let description = [Str "Explanatory", Space, Str "text"]
+            meta = setMeta "description" (MetaInlines description) nullMeta
+        in Pandoc meta mempty
 
-  , "Properties drawer" =:
-      T.unlines [ "  :PROPERTIES:"
-                , "  :setting: foo"
-                , "  :END:"
+      , "Multiline" =:
+        T.unlines [ "#+description: /Short/ introduction"
+                  , "#+description: to Org-mode"
+                  ] =?>
+        let description = [ Emph [Str "Short"], Space, Str "introduction"
+                          , SoftBreak
+                          , Str "to", Space, Str "Org-mode"
+                          ]
+            meta = setMeta "description" (MetaInlines description) nullMeta
+        in Pandoc meta mempty
+      ]
+
+    , "Subtitle" =:
+      T.unlines [ "#+subtitle: Your Life in"
+                , "#+subtitle: /Plain/ Text"
                 ] =?>
-      (mempty::Blocks)
+      let subtitle = "Your Life in" <> softbreak <> emph "Plain" <> " Text"
+      in Pandoc (setMeta "subtitle" (toMetaValue subtitle) nullMeta) mempty
 
-  , "LaTeX_headers options are translated to header-includes" =:
-      "#+LaTeX_header: \\usepackage{tikz}" =?>
-      let latexInlines = rawInline "latex" "\\usepackage{tikz}"
-          inclList = MetaList [MetaInlines (toList latexInlines)]
-          meta = setMeta "header-includes" inclList nullMeta
+    , "Keywords" =:
+      T.unlines [ "#+keywords: pandoc, testing,"
+                , "#+keywords: Org"
+                ] =?>
+      let keywords = toList $ "pandoc, testing," <> softbreak <> "Org"
+          meta = setMeta "keywords" (MetaInlines keywords) nullMeta
       in Pandoc meta mempty
 
-  , "LaTeX_class option is translated to documentclass" =:
-      "#+LATEX_CLASS: article" =?>
-      let meta = setMeta "documentclass" (MetaString "article") nullMeta
-      in Pandoc meta mempty
+    , "Institute" =:
+      "#+institute: ACME Inc." =?>
+      Pandoc (setMeta "institute" ("ACME Inc." :: Inlines) nullMeta) mempty
 
-  , "LaTeX_class_options is translated to classoption" =:
-      "#+LATEX_CLASS_OPTIONS: [a4paper]" =?>
-      let meta = setMeta "classoption" (MetaString "a4paper") nullMeta
-      in Pandoc meta mempty
+    , "Document language" =:
+      "#+LANGUAGE: de-DE" =?>
+      Pandoc (setMeta "lang" (MetaString "de-DE") nullMeta) mempty
 
-  , "LaTeX_class_options is translated to classoption" =:
-      "#+html_head: <meta/>" =?>
-      let html = rawInline "html" "<meta/>"
-          inclList = MetaList [MetaInlines (toList html)]
-          meta = setMeta "header-includes" inclList nullMeta
-      in Pandoc meta mempty
+    , testGroup "Todo sequences"
+      [ "not included in document" =:
+        "#+todo: WAITING | FINISHED" =?>
+        Pandoc mempty mempty
 
-  , "later meta definitions take precedence" =:
-      T.unlines [ "#+AUTHOR: this will not be used"
-                , "#+author: Max"
+      , "can contain multiple pipe characters" =:
+        "#+todo: UNFINISHED | RESEARCH | NOTES | CHART\n" =?>
+        Pandoc mempty mempty
+      ]
+
+    , testGroup "LaTeX"
+      [ "LATEX_HEADER" =:
+        "#+latex_header: \\usepackage{tikz}" =?>
+        let latexInlines = rawInline "latex" "\\usepackage{tikz}"
+            inclList = MetaList [MetaInlines (toList latexInlines)]
+            meta = setMeta "header-includes" inclList nullMeta
+        in Pandoc meta mempty
+
+      , "LATEX_HEADER_EXTRA" =:
+        "#+latex_header_extra: \\usepackage{calc}" =?>
+        let latexInlines = rawInline "latex" "\\usepackage{calc}"
+            inclList = toMetaValue [latexInlines]
+        in Pandoc (setMeta "header-includes" inclList nullMeta) mempty
+
+      , testGroup "LaTeX_CLASS"
+        [ "stored as documentclass" =:
+          "#+latex_class: article" =?>
+          let meta = setMeta "documentclass" (MetaString "article") nullMeta
+          in Pandoc meta mempty
+
+        , "last definition takes precedence" =:
+          T.unlines [ "#+latex_class: this will not be used"
+                    , "#+latex_class: report"
+                    ] =?>
+          let meta = setMeta "documentclass" (MetaString "report") nullMeta
+          in Pandoc meta mempty
+        ]
+
+      , "LATEX_CLASS_OPTIONS as classoption" =:
+        "#+latex_class_options: [a4paper]" =?>
+        let meta = setMeta "classoption" (MetaString "a4paper") nullMeta
+        in Pandoc meta mempty
+      ]
+
+    , testGroup "HTML"
+      [ "HTML_HEAD values are added to header-includes" =:
+        "#+html_head: <meta/>" =?>
+        let html = rawInline "html" "<meta/>"
+            inclList = MetaList [MetaInlines (toList html)]
+            meta = setMeta "header-includes" inclList nullMeta
+        in Pandoc meta mempty
+
+      , "HTML_HEAD_EXTRA behaves like HTML_HEAD" =:
+        T.unlines [ "#+html_head: <meta name=\"generator\" content=\"pandoc\">"
+                  , "#+html_head_extra: <meta charset=\"utf-8\">"
+                  ] =?>
+        let generator = rawInline "html"
+                                  "<meta name=\"generator\" content=\"pandoc\">"
+            charset = rawInline "html" "<meta charset=\"utf-8\">"
+            inclList = toMetaValue [generator, charset]
+        in Pandoc (setMeta "header-includes" inclList nullMeta) mempty
+      ]
+    ]
+
+  , testGroup "Non-export keywords"
+    [ testGroup "#+link"
+      [ "Link abbreviation" =:
+        T.unlines [ "#+link: wp https://en.wikipedia.org/wiki/%s"
+                  , "[[wp:Org_mode][Wikipedia on Org-mode]]"
+                  ] =?>
+        para (link "https://en.wikipedia.org/wiki/Org_mode" ""
+               ("Wikipedia" <> space <> "on" <> space <> "Org-mode"))
+
+      , "Link abbreviation, defined after first use" =:
+        T.unlines [ "[[zl:non-sense][Non-sense articles]]"
+                  , "#+link: zl http://zeitlens.com/tags/%s.html"
+                  ] =?>
+        para (link "http://zeitlens.com/tags/non-sense.html" ""
+               ("Non-sense" <> space <> "articles"))
+
+      , "Link abbreviation, URL encoded arguments" =:
+        T.unlines [ "#+link: expl http://example.com/%h/foo"
+                  , "[[expl:Hello, World!][Moin!]]"
+                  ] =?>
+        para (link "http://example.com/Hello%2C%20World%21/foo" "" "Moin!")
+
+      , "Link abbreviation, append arguments" =:
+        T.unlines [ "#+link: expl http://example.com/"
+                  , "[[expl:foo][bar]]"
+                  ] =?>
+        para (link "http://example.com/foo" "" "bar")
+      ]
+
+    , testGroup "emphasis config"
+      [ "Changing pre chars for emphasis" =:
+        T.unlines [ "#+pandoc-emphasis-pre: \"[)$a1%\""
+                  , "[/emph/.)*strong*.a~code~"
+                  ] =?>
+        para ("[" <> emph "emph" <> ".)" <> strong "strong" <>
+              ".a" <> code "code")
+
+      , "Changing post chars for emphasis" =:
+        T.unlines [ "#+pandoc-emphasis-post: \"(]$a1%\""
+                  , "/emph/('*strong*]'~code~a"
+                  ] =?>
+        para (emph "emph" <> "('" <> strong "strong" <> "]'" <>
+              code "code" <> "a")
+
+      , "setting an invalid value restores the default" =:
+        T.unlines [ "#+pandoc-emphasis-pre: \"[\""
+                  , "#+pandoc-emphasis-post: \"]\""
+                  , "#+pandoc-emphasis-pre:"
+                  , "#+pandoc-emphasis-post:"
+                  , "[/noemph/]"
+                  ] =?>
+        para "[/noemph/]"
+      ]
+
+    , "Unknown keyword" =:
+      T.unlines [ "#+unknown_keyword: Chumbawamba"
+                , "#+another_unknown: Blur"
                 ] =?>
-      let author = MetaInlines [Str "Max"]
-          meta = setMeta "author" (MetaList [author]) $ nullMeta
-      in Pandoc meta mempty
+      rawBlock "org" "#+unknown_keyword: Chumbawamba" <>
+      rawBlock "org" "#+another_unknown: Blur"
+    ]
 
+  , "Properties drawer" =:
+      T.unlines [ "  :PROPERTIES:"
+                , "  :setting: foo"
+                , "  :END:"
+                ] =?>
+      (setMeta "setting" ("foo" :: T.Text) (doc mempty))
+
   , "Logbook drawer" =:
       T.unlines [ "  :LogBook:"
                 , "  - State \"DONE\"       from \"TODO\"       [2014-03-03 Mon 11:00]"
@@ -135,7 +285,8 @@
 
   , "Search links are read as emph" =:
       "[[Wally][Where's Wally?]]" =?>
-      (para (emph $ "Where's" <> space <> "Wally?"))
+      para (spanWith ("", ["spurious-link"], [("target", "Wally")])
+                     (emph $ "Where's" <> space <> "Wally?"))
 
   , "Link to nonexistent anchor" =:
       T.unlines [ "<<link-here>> Target."
@@ -143,31 +294,6 @@
                 , "[[link$here][See here!]]"
                 ] =?>
       (para (spanWith ("link-here", [], []) mempty <> "Target.") <>
-       para (emph ("See" <> space <> "here!")))
-
-  , "Link abbreviation" =:
-      T.unlines [ "#+LINK: wp https://en.wikipedia.org/wiki/%s"
-                , "[[wp:Org_mode][Wikipedia on Org-mode]]"
-                ] =?>
-      (para (link "https://en.wikipedia.org/wiki/Org_mode" ""
-                  ("Wikipedia" <> space <> "on" <> space <> "Org-mode")))
-
-  , "Link abbreviation, defined after first use" =:
-      T.unlines [ "[[zl:non-sense][Non-sense articles]]"
-                , "#+LINK: zl http://zeitlens.com/tags/%s.html"
-                ] =?>
-      (para (link "http://zeitlens.com/tags/non-sense.html" ""
-                  ("Non-sense" <> space <> "articles")))
-
-  , "Link abbreviation, URL encoded arguments" =:
-      T.unlines [ "#+link: expl http://example.com/%h/foo"
-                , "[[expl:Hello, World!][Moin!]]"
-                ] =?>
-      (para (link "http://example.com/Hello%2C%20World%21/foo" "" "Moin!"))
-
-  , "Link abbreviation, append arguments" =:
-      T.unlines [ "#+link: expl http://example.com/"
-                , "[[expl:foo][bar]]"
-                ] =?>
-      (para (link "http://example.com/foo" "" "bar"))
+       para (spanWith ("", ["spurious-link"], [("target", "link$here")])
+                      (emph ("See" <> space <> "here!"))))
   ]
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,3 +1,15 @@
+{-# LANGUAGE OverloadedStrings #-}
+{- |
+   Module      : Tests.Readers.Org.Shared
+   Copyright   : © 2014-2024 Albert Krewinkel
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : Albert Krewinkel <albert+pandoc@tarleb.com>
+   Stability   : alpha
+   Portability : portable
+
+Helper functions used by other org tests.
+-}
 module Tests.Readers.Org.Shared
   ( (=:)
   , org
@@ -9,6 +21,7 @@
 import Data.Text (Text)
 import Tests.Helpers (ToString, purely, test)
 import Test.Tasty (TestTree)
+import Test.Tasty.HUnit (HasCallStack)
 import Text.Pandoc (Pandoc, ReaderOptions (readerExtensions),
                     def, getDefaultExtensions, readOrg)
 import Text.Pandoc.Builder (Inlines, smallcaps, space, spanWith, str)
@@ -17,7 +30,7 @@
 org = purely $ readOrg def{ readerExtensions = getDefaultExtensions "org" }
 
 infix 4 =:
-(=:) :: ToString c
+(=:) :: (ToString c, HasCallStack)
      => String -> (Text, c) -> TestTree
 (=:) = test org
 
@@ -25,5 +38,5 @@
 spcSep = mconcat . intersperse space
 
 -- | Create a span for the given tag.
-tagSpan :: String -> Inlines
+tagSpan :: Text -> Inlines
 tagSpan t = spanWith ("", ["tag"], [("tag-name", t)]) . smallcaps $ str t
diff --git a/test/Tests/Readers/Pod.hs b/test/Tests/Readers/Pod.hs
new file mode 100644
--- /dev/null
+++ b/test/Tests/Readers/Pod.hs
@@ -0,0 +1,187 @@
+{-# LANGUAGE OverloadedStrings #-}
+{- |
+   Module      : Tests.Readers.Pod
+   Copyright   : © 2024 Evan Silberman
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : 
+   Stability   : alpha
+   Portability : portable
+
+Tests for the Pod reader.
+-}
+
+module Tests.Readers.Pod (tests) where
+
+import Data.Text (Text, pack)
+import Test.Tasty
+import Test.Tasty.HUnit (HasCallStack)
+import Tests.Helpers
+import Text.Pandoc
+import Text.Pandoc.Arbitrary ()
+import Text.Pandoc.Builder
+
+pod :: Text -> Pandoc
+pod t = (purely $ readPod def) ("=pod\n\n" <> t <> "\n\n=cut\n")
+
+manLink :: Text -> Maybe Text -> Inlines -> Inlines
+manLink nm Nothing = linkWith (mempty, mempty, [("manual", nm)]) "" ""
+manLink nm (Just sc) = linkWith (mempty, mempty, [("manual", nm), ("section", sc)]) "" ""
+
+bogusEntity :: String -> TestTree
+bogusEntity t = t =: "E<" <> pack t <> ">" =?> para ("E<" <> str (pack t) <> ">")
+
+infix 4 =:
+(=:) :: (ToString c, HasCallStack)
+     => String -> (Text, c) -> TestTree
+(=:) = test pod
+
+tests :: [TestTree]
+tests = [
+  testGroup "inlines"
+    [ "code with nested inlines" =:
+        "C</I<A> (*PRUNE) I<B>/>" =?>
+        para (code "/A (*PRUNE) B/")
+    , "compact in compact" =:
+        "I<B<strong> emphasis>" =?>
+        para (emph $ (strong "strong") <> " emphasis")
+    , "expanded in compact" =:
+        "I<B<< strong >> emphasis>" =?>
+        para (emph $ (strong "strong") <> " emphasis")
+    , "compact in expanded" =:
+        "I<<< B<strong> emphasis >>>" =?>
+        para (emph $ (strong "strong") <> " emphasis")
+    , "expanded in expanded" =:
+        "I<<< B<<< strong >>> emphasis >>>" =?>
+        para (emph $ (strong "strong") <> " emphasis")
+    ]
+  , testGroup "links"
+    [ testGroup "compact"
+      [ "URL" =:
+          "L<https://example.org>" =?>
+          para (link "https://example.org" "" "https://example.org")
+      , "URL with link text" =:
+          "L<link|https://example.org/index.html>" =?>
+          para (link "https://example.org/index.html" "" "link")
+      , "perl manual" =:
+          "L<Foo::Bar>" =?>
+          para (manLink "Foo::Bar" Nothing "Foo::Bar")
+      , "manual with quoted section" =:
+          "L<crontab(5)/\"DESCRIPTION\">" =?>
+          para (manLink "crontab(5)" (Just "DESCRIPTION") (doubleQuoted "DESCRIPTION" <> " in crontab(5)"))
+      , "manual with section and formatted link text" =:
+          "L<B<< extravagant >> link|HTTP::Simple/is_info>" =?>
+          para (manLink "HTTP::Simple" (Just "is_info") (strong "extravagant" <> " link"))
+      , "internal link" =:
+          "L</section name>" =?>
+          para (link "#section-name" "" (doubleQuoted "section name"))
+      , "internal link with formatting" =:
+          "L</The C<pod2html> command>" =?>
+          para (link "#the-pod2html-command" "" (doubleQuoted ("The " <> code "pod2html" <> " command")))
+      , "link with angle bracket" =:
+          "L<m<>" =?>
+          para (manLink "m<" Nothing "m<")
+      , "empty name" =:
+          "L<|https://example.org>" =?>
+          para (link "https://example.org" "" mempty)
+      ]
+    , testGroup "expanded"
+      [ "URL" =:
+          "L<< https://example.org >>" =?>
+          para (link "https://example.org" "" "https://example.org")
+      , "URL with link text" =:
+          "L<< link|https://example.org/index.html >>" =?>
+          para (link "https://example.org/index.html" "" "link")
+      , "perl manual" =:
+          "L<<< Foo::Bar >>>" =?>
+          para (manLink "Foo::Bar" Nothing "Foo::Bar")
+      , "manual with quoted section" =:
+          "L<< crontab(5)/\"DESCRIPTION\"     >>" =?>
+          para (manLink "crontab(5)" (Just "DESCRIPTION") (doubleQuoted "DESCRIPTION" <> " in crontab(5)"))
+      , "manual with section and formatted link text" =:
+          "L<< B<< extravagant >> link|HTTP::Simple/is_info >>" =?>
+          para (manLink "HTTP::Simple" (Just "is_info") (strong "extravagant" <> " link"))
+      , "internal link" =:
+          "L<<   /section name  >>" =?>
+          para (link "#section-name" "" (doubleQuoted "section name"))
+      , "internal link with formatting" =:
+          "L<<<<<          /The C<pod2html> command    >>>>>" =?>
+          para (link "#the-pod2html-command" "" (doubleQuoted ("The " <> code "pod2html" <> " command")))
+      , "link with angle bracket" =:
+          "L<< m< >>" =?>
+          para (manLink "m<" Nothing "m<")
+      , "empty name" =:
+          "L<< |https://example.org >>" =?>
+          para (link "https://example.org" "" mempty)
+      ]
+    ]
+  , testGroup "entities"
+      [ testGroup "required"
+        [ "quot" =:
+            "E<quot>" =?>
+          para "\""
+        , "amp" =:
+            "E<amp>" =?>
+            para "&"
+        , "apos" =:
+            "E<apos>" =?>
+            para "'"
+        , "lt" =:
+            "E<lt>" =?>
+            para "<"
+        , "gt" =:
+            "E<gt>" =?>
+            para ">"
+        , "sol" =:
+            "E<sol>" =?>
+            para "/"
+        , "verbar" =:
+            "E<verbar>" =?>
+            para "|"
+        , "lchevron" =:
+            "E<lchevron>" =?>
+            para "«"
+        , "rchevron" =:
+            "E<rchevron>" =?>
+            para "»"
+        ]
+      , testGroup "html"
+        [ "trade" =:
+           "E<trade>" =?>
+           para "™"
+        , "ccaron" =:
+           "E<ccaron>" =?>
+           para "č"
+        , "cent" =:
+           "E<cent>" =?>
+           para "¢"
+        ]
+      , testGroup "numeric"
+        [ "decimal" =:
+            "E<162>" =?>
+            para "¢"
+        , "octal" =:
+            "E<0242>" =?>
+            para "¢"
+        , "hexadecimal" =:
+            "E<0xA2>" =?>
+            para "¢"
+        , "hexadecimal variant" =:
+            "E<0x00A2>" =?>
+            para "¢"
+        , "actually decimal" =:
+            "E<099>" =?>
+            para "c"
+        ]
+      , testGroup "bogus"
+        [ bogusEntity "0XA2"
+        , bogusEntity "not a real entity"
+        , bogusEntity "162 1"
+        , bogusEntity "99 bottles of beer"
+        , bogusEntity "0xhh"
+        , bogusEntity "077x"
+        , bogusEntity "0x63 skidoo"
+        , bogusEntity "trade;"
+        ]
+      ]
+    ]
diff --git a/test/Tests/Readers/Pptx.hs b/test/Tests/Readers/Pptx.hs
new file mode 100644
--- /dev/null
+++ b/test/Tests/Readers/Pptx.hs
@@ -0,0 +1,48 @@
+{-# LANGUAGE OverloadedStrings #-}
+{- |
+   Module      : Tests.Readers.Pptx
+   Copyright   : © 2025 Anton Antic
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : Anton Antic <anton@everworker.ai>
+   Stability   : alpha
+   Portability : portable
+
+Tests for the PPTX reader.
+-}
+module Tests.Readers.Pptx (tests) where
+
+import qualified Data.ByteString as BS
+import qualified Data.ByteString.Lazy as B
+import Test.Tasty
+import Test.Tasty.Golden.Advanced
+import Tests.Helpers
+import Text.Pandoc
+import Text.Pandoc.UTF8 as UTF8
+
+defopts :: ReaderOptions
+defopts = def{ readerExtensions = getDefaultExtensions "pptx" }
+
+testCompare :: String -> FilePath -> FilePath -> TestTree
+testCompare = testCompareWithOpts defopts
+
+testCompareWithOpts :: ReaderOptions -> String -> FilePath -> FilePath -> TestTree
+testCompareWithOpts opts testName pptxFP nativeFP =
+  goldenTest
+  testName
+  (do nf <- UTF8.toText <$> BS.readFile nativeFP
+      runIOorExplode (readNative def nf))
+  (do df <- B.readFile pptxFP
+      runIOorExplode (readPptx opts df))
+  (nativeDiff nativeFP)
+  (\a -> runIOorExplode (writeNative def{ writerTemplate = Just mempty} a)
+            >>= BS.writeFile nativeFP . UTF8.fromText)
+
+tests :: [TestTree]
+tests = [ testGroup "basic"
+          [ testCompare
+            "text extraction"
+            "pptx-reader/basic.pptx"
+            "pptx-reader/basic.native"
+          ]
+        ]
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,10 +1,22 @@
 {-# LANGUAGE OverloadedStrings   #-}
 {-# LANGUAGE ScopedTypeVariables #-}
+{- |
+   Module      : Tests.Readers.RST
+   Copyright   : © 2006-2024 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 Data.Text (Text)
 import qualified Data.Text as T
 import Test.Tasty
+import Test.Tasty.HUnit (HasCallStack)
 import Tests.Helpers
 import Text.Pandoc
 import Text.Pandoc.Arbitrary ()
@@ -14,7 +26,7 @@
 rst = purely $ readRST def{ readerStandalone = True }
 
 infix 4 =:
-(=:) :: ToString c
+(=:) :: (ToString c, HasCallStack)
      => String -> (Text, c) -> TestTree
 (=:) = test rst
 
@@ -36,15 +48,15 @@
              , ":Parameter i: integer"
              , ":Final: item"
              , "  on two lines" ]
-             =?> ( doc
-                 $ para "para" <>
-                   definitionList [ (str "Hostname", [para "media08"])
-                                  , (text "IP address", [para "10.0.0.19"])
-                                  , (str "Size", [para "3ru"])
-                                  , (str "Version", [para "1"])
-                                  , (str "Indentation", [para "Since the field marker may be quite long, the second\nand subsequent lines of the field body do not have to line up\nwith the first line, but they must be indented relative to the\nfield name marker, and they must line up with each other."])
-                                  , (text "Parameter i", [para "integer"])
-                                  , (str "Final", [para "item\non two lines"])
+             =?>
+              doc (para "para" <>
+                   definitionList [ (str "Hostname", [plain "media08"])
+                                  , (text "IP address", [plain "10.0.0.19"])
+                                  , (str "Size", [plain "3ru"])
+                                  , (str "Version", [plain "1"])
+                                  , (str "Indentation", [plain "Since the field marker may be quite long, the second\nand subsequent lines of the field body do not have to line up\nwith the first line, but they must be indented relative to the\nfield name marker, and they must line up with each other."])
+                                  , (text "Parameter i", [plain "integer"])
+                                  , (str "Final", [plain "item\non two lines"])
                                   ])
           , "metadata" =: T.unlines
              [ "====="
@@ -56,10 +68,10 @@
              , ""
              , ":Version: 1"
              ]
-             =?> ( setMeta "version" (para "1")
-                 $ setMeta "title" ("Title" :: Inlines)
+             =?>
+              setMeta "version" (str "1") (setMeta "title" ("Title" :: Inlines)
                  $ setMeta "subtitle" ("Subtitle" :: Inlines)
-                 $ doc mempty )
+                 $ doc mempty)
           , "with inline markup" =: T.unlines
              [ ":*Date*: today"
              , ""
@@ -73,12 +85,12 @@
              , ".. _two: http://example.com"
              , ".. _three: http://example.org"
              ]
-             =?> ( setMeta "date" (str "today")
-                 $ doc
-                 $ definitionList [ (emph "one", [para "emphasis"])
-                                  , (link "http://example.com" "" "two", [para "reference"])
-                                  , (link "http://example.org" "" "three", [para "another one"])
-                                  , (code "four", [para "literal"])
+             =?>
+              setMeta "date" (str "today") (doc
+                 $ definitionList [ (emph "one", [plain "emphasis"])
+                                  , (link "http://example.com" "" "two", [plain "reference"])
+                                  , (link "http://example.org" "" "three", [plain "another one"])
+                                  , (code "four", [plain "literal"])
                                   ])
           ]
         , "URLs with following punctuation" =:
@@ -102,27 +114,25 @@
             , "  def func(x):"
             , "    return y"
             ]  =?>
-              ( doc $ codeBlockWith
+              doc (codeBlockWith
                   ( ""
-                  , ["sourceCode", "python", "numberLines", "class1", "class2", "class3"]
+                  , ["python", "numberLines", "class1", "class2", "class3"]
                   , [ ("startFrom", "34") ]
                   )
-                  "def func(x):\n  return y"
-              )
+                  "def func(x):\n  return y")
         , "Code directive with number-lines, no line specified" =: T.unlines
             [ ".. code::python"
-            , "   :number-lines: "
+            , "   :number-lines:"
             , ""
             , "  def func(x):"
             , "    return y"
             ]  =?>
-              ( doc $ codeBlockWith
+              doc (codeBlockWith
                   ( ""
-                  , ["sourceCode", "python", "numberLines"]
-                  , [ ("startFrom", "") ]
+                  , ["python", "numberLines"]
+                  , []
                   )
-                  "def func(x):\n  return y"
-              )
+                  "def func(x):\n  return y")
         , testGroup "literal / line / code blocks"
           [ "indented literal block" =: T.unlines
             [ "::"
@@ -131,7 +141,8 @@
             , ""
             , "  can go on for many lines"
             , "but must stop here"]
-            =?> (doc $
+            =?>
+              doc (
                  codeBlock "block quotes\n\ncan go on for many lines" <>
                  para "but must stop here")
           , "line block with 3 lines" =: "| a\n| b\n| c"
@@ -163,20 +174,29 @@
           [ "literal role prefix" =: ":literal:`a`" =?> para (code "a")
           , "literal role postfix" =: "`a`:literal:" =?> para (code "a")
           , "literal text" =: "``text``" =?> para (code "text")
-          , "code role" =: ":code:`a`" =?> para (codeWith ("", ["sourceCode"], []) "a")
+          , "code role" =: ":code:`a`" =?> para (codeWith ("", [], []) "a")
           , "inherited code role" =: ".. role:: codeLike(code)\n\n:codeLike:`a`"
-            =?> para (codeWith ("", ["codeLike", "sourceCode"], []) "a")
+            =?> para (codeWith ("", ["codeLike"], []) "a")
           , "custom code role with language field"
             =: ".. role:: lhs(code)\n    :language: haskell\n\n:lhs:`a`"
-            =?> para (codeWith ("", ["lhs", "haskell","sourceCode"], []) "a")
+            =?> para (codeWith ("", ["lhs", "haskell"], []) "a")
+          , "custom role with class field"
+            =: ".. role:: classy\n    :class: myclass\n\n:classy:`a`"
+            =?> para (spanWith ("", ["myclass"], []) "a")
+          , "custom role with class field containing multiple whitespace-separated classes"
+            =: ".. role:: classy\n    :class: myclass1 myclass2\n       myclass3\n\n:classy:`a`"
+            =?> para (spanWith ("", ["myclass1", "myclass2", "myclass3"], []) "a")
+          , "custom role with inherited class field"
+            =: ".. role:: classy\n    :class: myclass1\n.. role:: classier(classy)\n    :class: myclass2\n\n:classier:`a`"
+            =?> para (spanWith ("", ["myclass2", "myclass1"], []) "a")
           , "custom role with unspecified parent role"
             =: ".. role:: classy\n\n:classy:`text`"
             =?> para (spanWith ("", ["classy"], []) "text")
           , "role with recursive inheritance"
             =: ".. role:: haskell(code)\n.. role:: lhs(haskell)\n\n:lhs:`text`"
-            =?> para (codeWith ("", ["lhs", "haskell", "sourceCode"], []) "text")
+            =?> para (codeWith ("", ["lhs", "haskell"], []) "text")
           , "unknown role" =: ":unknown:`text`" =?>
-              para (spanWith ("",[],[("role","unknown")]) (str "text"))
+              para (codeWith ("",["interpreted-text"],[("role","unknown")]) "text")
           ]
         , testGroup "footnotes"
           [ "remove space before note" =: T.unlines
@@ -185,6 +205,20 @@
             , ".. [1]"
             , "   bar"
             ] =?>
-            (para $ "foo" <> (note $ para "bar"))
+              para ("foo" <> note (para "bar"))
+          ]
+        , testGroup "inlines"
+          [ "links can contain an URI without being parsed twice (#4581)" =:
+            "`http://loc <http://loc>`__" =?>
+            para (link "http://loc" "" "http://loc")
+          , "inline markup cannot be nested" =:
+            "**a*b*c**" =?>
+            para (strong "a*b*c")
+          , "bare URI parsing disabled inside emphasis (#4561)" =:
+            "*http://location*" =?>
+            para (emph (text "http://location"))
+          , "include newlines" =:
+            "**before\nafter**" =?>
+            para (strong (text "before\nafter"))
           ]
         ]
diff --git a/test/Tests/Readers/RTF.hs b/test/Tests/Readers/RTF.hs
new file mode 100644
--- /dev/null
+++ b/test/Tests/Readers/RTF.hs
@@ -0,0 +1,41 @@
+{- |
+   Module      : Tests.Readers.RTF
+   Copyright   : © 2021-2024 John MacFarlane
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : jgm@berkeley.edu
+   Stability   : alpha
+   Portability : portable
+
+Tests for the RTF reader.
+-}
+module Tests.Readers.RTF (tests) where
+
+import Test.Tasty
+import Tests.Helpers
+import Text.Pandoc
+import System.FilePath (replaceExtension, (</>), (<.>))
+
+rtfTest :: TestName -> TestTree
+rtfTest name = testGolden name native path
+   (\t -> runIOorExplode
+            (readRTF def t >>=
+              writeNative def{ writerTemplate = Just mempty }))
+  where native = replaceExtension path ".native"
+        path = "rtf" </> name <.> "rtf"
+
+
+tests :: [TestTree]
+tests = map rtfTest [ "footnote"
+                    , "accent"
+                    , "unicode"
+                    , "image"
+                    , "link"
+                    , "heading"
+                    , "formatting"
+                    , "list_simple"
+                    , "list_complex"
+                    , "bookmark"
+                    , "table_simple"
+                    , "table_error_codes"
+                    ]
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,15 +1,27 @@
 {-# LANGUAGE OverloadedStrings #-}
+{- |
+   Module      : Tests.Readers.Txt2Tags
+   Copyright   : © 2014-2024 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 Data.List (intersperse)
 import Data.Text (Text)
 import qualified Data.Text as T
 import Test.Tasty
+import Test.Tasty.HUnit (HasCallStack)
 import Tests.Helpers
 import Text.Pandoc
 import Text.Pandoc.Arbitrary ()
 import Text.Pandoc.Builder
-import Text.Pandoc.Shared (underlineSpan)
 
 t2t :: Text -> Pandoc
 -- t2t = handleError . readTxt2Tags (T2TMeta "date" "mtime" "in" "out") def
@@ -19,7 +31,7 @@
   readTxt2Tags def s
 
 infix 4 =:
-(=:) :: ToString c
+(=:) :: (ToString c, HasCallStack)
      => String -> (Text, c) -> TestTree
 (=:) = test t2t
 
@@ -30,11 +42,22 @@
              -> [Blocks]
              -> [[Blocks]]
              -> Blocks
-simpleTable' n = table "" (take n $ repeat (AlignCenter, 0.0))
+simpleTable' n = simpleTable'' $ replicate n (AlignCenter, ColWidthDefault)
 
+simpleTable'' :: [ColSpec] -> [Blocks] -> [[Blocks]] -> Blocks
+simpleTable'' spec headers rows
+  = table emptyCaption
+          spec
+          (TableHead nullAttr $ toHeaderRow headers)
+          [TableBody nullAttr 0 [] $ map toRow rows]
+          (TableFoot nullAttr [])
+  where
+    toRow = Row nullAttr . map simpleCell
+    toHeaderRow l = [toRow l | not (null l)]
+
 tests :: [TestTree]
 tests =
-  [ testGroup "Inlines" $
+  [ testGroup "Inlines"
       [ "Plain String" =:
           "Hello, World" =?>
           para (spcSep [ "Hello,", "World" ])
@@ -69,12 +92,12 @@
 
       , "Inline markup is greedy" =:
           "***** ///// _____ ----- ````` \"\"\"\"\" '''''" =?>
-          para (spcSep [strong "*", emph "/", underlineSpan "_"
+          para (spcSep [strong "*", emph "/", underline "_"
                        , strikeout "-", code "`", text "\""
                        , rawInline "html" "'"])
       , "Markup must be greedy" =:
           "**********    //////////    __________    ----------    ``````````   \"\"\"\"\"\"\"\"\"\"   ''''''''''" =?>
-                      para (spcSep [strong "******", emph "//////", underlineSpan "______"
+                      para (spcSep [strong "******", emph "//////", underline "______"
                        , strikeout "------", code "``````", text "\"\"\"\"\"\""
                        , rawInline "html" "''''''"])
       , "Inlines must be glued" =:
@@ -96,9 +119,12 @@
       , "Autolink" =:
           "http://www.google.com" =?>
             para (link "http://www.google.com" "" (str "http://www.google.com"))
-      , "Image" =:
+      , "JPEG Image" =:
           "[image.jpg]" =?>
             para (image "image.jpg" "" mempty)
+      , "PNG Image" =:
+          "[image.png]" =?>
+            para (image "image.png" "" mempty)
 
       , "Link" =:
           "[title http://google.com]" =?>
@@ -114,7 +140,7 @@
 
       ]
 
-  , testGroup "Basic Blocks" $
+  , testGroup "Basic Blocks"
       ["Paragraph, lines grouped together" =:
           "A paragraph\n A blank line ends the \n current paragraph\n"
             =?> para "A paragraph\n A blank line ends the\n current paragraph"
@@ -140,7 +166,7 @@
 
       , "Header with label" =:
           "= header =[label]" =?>
-            headerWith ("label", [], []) 1 ("header")
+            headerWith ("label", [], []) 1 "header"
 
       , "Invalid header, mismatched delimiters" =:
           "== header =" =?>
@@ -197,7 +223,7 @@
 
     ]
 
-  , testGroup "Lists" $
+  , testGroup "Lists"
       [ "Simple Bullet Lists" =:
           ("- Item1\n" <>
            "- Item2\n") =?>
@@ -294,14 +320,14 @@
       , "Ordered List in Bullet List" =:
           ("- Emacs\n" <>
            "  + Org\n") =?>
-          bulletList [ (plain "Emacs") <>
-                       (orderedList [ plain "Org"])
+          bulletList [ plain "Emacs" <>
+                       orderedList [ plain "Org"]
                      ]
 
       , "Bullet List in Ordered List" =:
           ("+ GNU\n" <>
            "   - Freedom\n") =?>
-          orderedList [ (plain "GNU") <> bulletList [ (plain "Freedom") ] ]
+          orderedList [ plain "GNU" <> bulletList [ plain "Freedom" ] ]
 
       , "Definition List" =:
           T.unlines [ ": PLL"
@@ -381,12 +407,15 @@
                   , "| 1 |    One  |    foo  |"
                   , "| 2 |    Two  | bar  |"
                   ] =?>
-          table "" (zip [AlignCenter, AlignRight, AlignDefault] [0, 0, 0])
-                []
-                [ [ plain "Numbers", plain "Text", plain "More" ]
-                , [ plain "1"      , plain "One" , plain "foo"  ]
-                , [ plain "2"      , plain "Two" , plain "bar"  ]
-                ]
+          simpleTable''
+            (zip
+              [AlignCenter, AlignRight, AlignDefault]
+              [ColWidthDefault, ColWidthDefault, ColWidthDefault])
+            []
+            [ [ plain "Numbers", plain "Text", plain "More" ]
+            , [ plain "1"      , plain "One" , plain "foo"  ]
+            , [ plain "2"      , plain "Two" , plain "bar"  ]
+            ]
 
       , "Pipe within text doesn't start a table" =:
           "Ceci n'est pas une | pipe " =?>
@@ -398,11 +427,14 @@
                   , "| 1 | One  | foo  |"
                   , "| 2 "
                   ] =?>
-          table "" (zip [AlignCenter, AlignLeft, AlignLeft] [0, 0, 0])
-                [ plain "Numbers", plain "Text" , plain mempty ]
-                [ [ plain "1"      , plain "One"  , plain "foo"  ]
-                , [ plain "2"      , plain mempty , plain mempty  ]
-                ]
+          simpleTable''
+            (zip
+              [AlignCenter, AlignLeft, AlignLeft]
+              [ColWidthDefault, ColWidthDefault, ColWidthDefault])
+            [ plain "Numbers", plain "Text" , plain mempty ]
+            [ [ plain "1"      , plain "One"  , plain "foo"  ]
+            , [ plain "2"      , plain mempty , plain mempty  ]
+            ]
 
       ]
 
diff --git a/test/Tests/Readers/Xlsx.hs b/test/Tests/Readers/Xlsx.hs
new file mode 100644
--- /dev/null
+++ b/test/Tests/Readers/Xlsx.hs
@@ -0,0 +1,48 @@
+{-# LANGUAGE OverloadedStrings #-}
+{- |
+   Module      : Tests.Readers.Xlsx
+   Copyright   : © 2025 Anton Antic
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : Anton Antic <anton@everworker.ai>
+   Stability   : alpha
+   Portability : portable
+
+Tests for the XLSX reader.
+-}
+module Tests.Readers.Xlsx (tests) where
+
+import qualified Data.ByteString as BS
+import qualified Data.ByteString.Lazy as B
+import Test.Tasty
+import Test.Tasty.Golden.Advanced
+import Tests.Helpers
+import Text.Pandoc
+import Text.Pandoc.UTF8 as UTF8
+
+defopts :: ReaderOptions
+defopts = def{ readerExtensions = getDefaultExtensions "xlsx" }
+
+testCompare :: String -> FilePath -> FilePath -> TestTree
+testCompare = testCompareWithOpts defopts
+
+testCompareWithOpts :: ReaderOptions -> String -> FilePath -> FilePath -> TestTree
+testCompareWithOpts opts testName xlsxFP nativeFP =
+  goldenTest
+  testName
+  (do nf <- UTF8.toText <$> BS.readFile nativeFP
+      runIOorExplode (readNative def nf))
+  (do df <- B.readFile xlsxFP
+      runIOorExplode (readXlsx opts df))
+  (nativeDiff nativeFP)
+  (\a -> runIOorExplode (writeNative def{ writerTemplate = Just mempty} a)
+            >>= BS.writeFile nativeFP . UTF8.fromText)
+
+tests :: [TestTree]
+tests = [ testGroup "basic"
+          [ testCompare
+            "sheet extraction"
+            "xlsx-reader/basic.xlsx"
+            "xlsx-reader/basic.native"
+          ]
+        ]
diff --git a/test/Tests/Shared.hs b/test/Tests/Shared.hs
--- a/test/Tests/Shared.hs
+++ b/test/Tests/Shared.hs
@@ -1,11 +1,28 @@
+{-# LANGUAGE OverloadedStrings #-}
+{- |
+   Module      : Tests.Shared
+   Copyright   : © 2006-2024 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 System.FilePath.Posix (joinPath)
 import Test.Tasty
-import Test.Tasty.HUnit (assertBool, testCase, (@?=))
 import Text.Pandoc.Arbitrary ()
+import Test.Tasty.QuickCheck (testProperty)
 import Text.Pandoc.Builder
 import Text.Pandoc.Shared
+import Test.Tasty.HUnit
+import Tests.Helpers
+import Text.Pandoc
+import Text.Pandoc.Writers.Shared
+import qualified Data.Text as T
 
 tests :: [TestTree]
 tests = [ testGroup "compactifyDL"
@@ -15,25 +32,147 @@
                in  compactifyDL x == x)
           ]
         , testGroup "collapseFilePath" testCollapse
+        , testGroup "toLegacyTable" testLegacyTable
+        , testGroup "table of contents" testTOC
+        , testGroup "makeSections"
+          [ testProperty "makeSections is idempotent" makeSectionsIsIdempotent
+          , testCase "makeSections is idempotent for test case" $
+              let d = header 1 "H1" <> header 2 "H2" <> header 3 "H3" <>
+                      header 2 "H2a" <> header 4 "H4" <> header 1 "H1a"
+                  d' = makeSections False Nothing $ toList d
+               in assertBool "makeSections is idempotent for test case"
+                      (makeSections False Nothing d' == d')
+          ]
         ]
 
+makeSectionsIsIdempotent :: [Block] -> Bool
+makeSectionsIsIdempotent d =
+  let d' = makeSections False Nothing d
+   in d' == makeSections False Nothing d'
+
+givesTOC :: String -> (Blocks, Blocks) -> TestTree
+givesTOC desc (blocks, toc) =
+  test (singleton . toTableOfContents def) desc (toList blocks, toc)
+
+linkId :: T.Text -> T.Text -> T.Text -> Inlines -> Inlines
+linkId lId = linkWith (lId,[],[])
+
+headerId :: T.Text -> Int -> Inlines -> Blocks
+headerId hId = headerWith (hId,[],[])
+
+testTOC :: [TestTree]
+testTOC = [ givesTOC "empty case" $ mempty =?> bulletList []
+          , givesTOC "no headers" $ horizontalRule =?> bulletList []
+          , givesTOC "unlinked header" $
+              header 1 "H1" =?>
+              bulletList [plain "H1"]
+          , givesTOC "linked header" $
+              headerId "h1" 1 "H1" =?>
+              bulletList [plain $ linkId "toc-h1" "#h1" "" "H1"]
+          , givesTOC "nested headlines" $
+              header 1 "H1a" <> header 2 "H2" =?>
+              bulletList [plain "H1a" <> bulletList [plain "H2"]]
+          , givesTOC "only referenced headers" $
+              header 1 "H1a" <> headerId "h2" 2 "H2" =?>
+              bulletList [plain "H1a" <>
+                          bulletList [plain $ linkId "toc-h2" "#h2" "" "H2"]]
+          , givesTOC "section id used as backup" $
+              divWith ("sec",["section"],[]) (header 1 "H1") =?>
+              bulletList [plain $ linkId "toc-sec" "#sec" "" "H1"]
+          ]
+
 testCollapse :: [TestTree]
 testCollapse = map (testCase "collapse")
- [  (collapseFilePath (joinPath [ ""]) @?= (joinPath [ ""]))
- ,  (collapseFilePath (joinPath [ ".","foo"]) @?= (joinPath [ "foo"]))
- ,  (collapseFilePath (joinPath [ ".",".","..","foo"]) @?= (joinPath [ joinPath ["..", "foo"]]))
- ,  (collapseFilePath (joinPath [ "..","foo"]) @?= (joinPath [ "..","foo"]))
- ,  (collapseFilePath (joinPath [ "","bar","..","baz"]) @?= (joinPath [ "","baz"]))
- ,  (collapseFilePath (joinPath [ "","..","baz"]) @?= (joinPath [ "","..","baz"]))
- ,  (collapseFilePath (joinPath [ ".","foo","..",".","bar","..",".",".","baz"]) @?= (joinPath [ "baz"]))
- ,  (collapseFilePath (joinPath [ ".",""]) @?= (joinPath [ ""]))
- ,  (collapseFilePath (joinPath [ ".",".",""]) @?= (joinPath [ ""]))
- ,  (collapseFilePath (joinPath [ "..",""]) @?= (joinPath [ ".."]))
- ,  (collapseFilePath (joinPath [ "..",".",""]) @?= (joinPath [ ".."]))
- ,  (collapseFilePath (joinPath [ ".","..",""]) @?= (joinPath [ ".."]))
- ,  (collapseFilePath (joinPath [ "..","..",""]) @?= (joinPath [ "..",".."]))
- ,  (collapseFilePath (joinPath [ "parent","foo","baz","..","bar"]) @?= (joinPath [ "parent","foo","bar"]))
- ,  (collapseFilePath (joinPath [ "parent","foo","baz","..","..","bar"]) @?= (joinPath [ "parent","bar"]))
- ,  (collapseFilePath (joinPath [ "parent","foo",".."]) @?= (joinPath [ "parent"]))
- ,  (collapseFilePath (joinPath [ "","parent","foo","..","..","bar"]) @?= (joinPath [ "","bar"]))
- ,  (collapseFilePath (joinPath [ "",".","parent","foo"]) @?= (joinPath [ "","parent","foo"]))]
+ [  collapseFilePath (joinPath [ ""]) @?= joinPath [ ""]
+ ,  collapseFilePath (joinPath [ ".","foo"]) @?= joinPath [ "foo"]
+ ,  collapseFilePath (joinPath [ ".",".","..","foo"]) @?= joinPath [ joinPath ["..", "foo"]]
+ ,  collapseFilePath (joinPath [ "..","foo"]) @?= joinPath [ "..","foo"]
+ ,  collapseFilePath (joinPath [ "","bar","..","baz"]) @?= joinPath [ "","baz"]
+ ,  collapseFilePath (joinPath [ "","..","baz"]) @?= joinPath [ "","..","baz"]
+ ,  collapseFilePath (joinPath [ ".","foo","..",".","bar","..",".",".","baz"]) @?= joinPath [ "baz"]
+ ,  collapseFilePath (joinPath [ ".",""]) @?= joinPath [ ""]
+ ,  collapseFilePath (joinPath [ ".",".",""]) @?= joinPath [ ""]
+ ,  collapseFilePath (joinPath [ "..",""]) @?= joinPath [ ".."]
+ ,  collapseFilePath (joinPath [ "..",".",""]) @?= joinPath [ ".."]
+ ,  collapseFilePath (joinPath [ ".","..",""]) @?= joinPath [ ".."]
+ ,  collapseFilePath (joinPath [ "..","..",""]) @?= joinPath [ "..",".."]
+ ,  collapseFilePath (joinPath [ "parent","foo","baz","..","bar"]) @?= joinPath [ "parent","foo","bar"]
+ ,  collapseFilePath (joinPath [ "parent","foo","baz","..","..","bar"]) @?= joinPath [ "parent","bar"]
+ ,  collapseFilePath (joinPath [ "parent","foo",".."]) @?= joinPath [ "parent"]
+ ,  collapseFilePath (joinPath [ "","parent","foo","..","..","bar"]) @?= joinPath [ "","bar"]
+ ,  collapseFilePath (joinPath [ "",".","parent","foo"]) @?= joinPath [ "","parent","foo"]]
+
+testLegacyTable :: [TestTree]
+testLegacyTable =
+  [ testCase "decomposes a table with head" $ gen1 @?= expect1
+  , testCase "decomposes a table without head" $ gen2 @?= expect2
+  , testCase "decomposes the table from issue 7683" $ gen3 @?= expect3
+  ]
+  where
+    pln = toList . plain . str
+    cl a h w = Cell ("", [], []) AlignDefault h w $ pln a
+    rws = map $ Row nullAttr
+    th = TableHead nullAttr . rws
+    tb n x y = TableBody nullAttr n (rws x) (rws y)
+    tf = TableFoot nullAttr . rws
+
+    headRows1 =
+      [[cl "a" 1 1, cl "b" 2 2]
+      ,[cl "c" 1 1]
+      ]
+    body1 = tb 1
+      [[cl "e" 3 1,cl "f" 3 2]
+      ,[]
+      ,[]
+      ]
+      [[emptyCell,emptyCell,emptyCell]
+      ,[cl "g" 1 1,emptyCell,emptyCell]
+      ]
+    footRows1 =
+      [[cl "h" 1 2,cl "i" 2 1]
+      ,[cl "j" 1 2]]
+    caption1 = simpleCaption $ plain "caption"
+    spec1 = replicate 2 (AlignDefault, ColWidth 0.5) ++ [(AlignRight, ColWidthDefault)]
+    expect1 = ( [Str "caption"]
+              , replicate 2 AlignDefault ++ [AlignRight]
+              , replicate 2 0.5 ++ [0]
+              , [pln "a", pln "b", mempty]
+              , [[pln "c", mempty, mempty]
+                ,[pln "e", pln "f", mempty]
+                ,[mempty, mempty, mempty]
+                ,[mempty, mempty, mempty]
+                ,[mempty, mempty, mempty]
+                ,[pln "g", mempty, mempty]
+                ,[pln "h", mempty, pln "i"]
+                ,[pln "j", mempty, mempty]]
+              )
+    gen1 = toLegacyTable caption1 spec1 (th headRows1) [body1] (tf footRows1)
+
+    expect2 = ( []
+              , replicate 2 AlignDefault ++ [AlignRight]
+              , replicate 2 0.5 ++ [0]
+              , []
+              , [[pln "e", pln "f", mempty]
+                ,[mempty, mempty, mempty]
+                ,[mempty, mempty, mempty]
+                ,[mempty, mempty, mempty]
+                ,[pln "g", mempty, mempty]
+                ,[pln "h", mempty, pln "i"]
+                ,[pln "j", mempty, mempty]]
+              )
+    gen2 = toLegacyTable emptyCaption spec1 (th []) [body1] (tf footRows1)
+
+    spec3 = replicate 4 (AlignDefault, ColWidthDefault)
+    body3 = tb 0
+      []
+      [[cl "a" 2 1, cl "b" 1 2, cl "c" 2 1]
+      ,[cl "d" 1 1, cl "e" 1 1]
+      ]
+    expect3 = ( []
+              , replicate 4 AlignDefault
+              , replicate 4 0
+              , []
+              , [[pln "a", pln "b", mempty, pln "c"]
+                ,[mempty, pln "d", pln "e", mempty]]
+              )
+    gen3 = toLegacyTable emptyCaption spec3 (th []) [body3] (tf [])
diff --git a/test/Tests/Writers/AnnotatedTable.hs b/test/Tests/Writers/AnnotatedTable.hs
new file mode 100644
--- /dev/null
+++ b/test/Tests/Writers/AnnotatedTable.hs
@@ -0,0 +1,253 @@
+{-# LANGUAGE OverloadedStrings #-}
+{- |
+   Module      : Tests.Writers.AnnotatedTable
+   Copyright   : 2020 Christian Despres
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : Christian Despres <christian.j.j.despres@gmail.com>
+   Stability   : alpha
+   Portability : portable
+
+Tests for the table helper functions.
+-}
+module Tests.Writers.AnnotatedTable
+  ( tests
+  )
+where
+
+import           Prelude
+import qualified Data.Foldable                 as F
+import qualified Data.List.NonEmpty            as NonEmpty
+import           Test.Tasty
+import           Test.Tasty.HUnit               ( testCase
+                                                , (@?=)
+                                                )
+import           Test.Tasty.QuickCheck          ( QuickCheckTests(..)
+                                                , Property
+                                                , Testable
+                                                , conjoin
+                                                , forAll
+                                                , testProperty
+                                                , (===)
+                                                , vectorOf
+                                                , choose
+                                                , arbitrary
+                                                , elements
+                                                )
+import           Text.Pandoc.Arbitrary          ( )
+import           Text.Pandoc.Builder
+import qualified Text.Pandoc.Writers.AnnotatedTable
+                                               as Ann
+
+tests :: [TestTree]
+tests = [testGroup "toTable" $ testAnnTable <> annTableProps]
+
+getSpec :: Ann.Cell -> [ColSpec]
+getSpec (Ann.Cell colspec _ _) = F.toList colspec
+
+catHeaderSpec :: Ann.HeaderRow -> [ColSpec]
+catHeaderSpec (Ann.HeaderRow _ _ x) = concatMap getSpec x
+
+catBodySpec :: Ann.BodyRow -> [ColSpec]
+catBodySpec (Ann.BodyRow _ _ x y) = concatMap getSpec x <> concatMap getSpec y
+
+-- Test if the first list can be obtained from the second by deleting
+-- elements from it.
+isSubsetOf :: Eq a => [a] -> [a] -> Bool
+isSubsetOf (x : xs) (y : ys) | x == y    = isSubsetOf xs ys
+                             | otherwise = isSubsetOf (x : xs) ys
+isSubsetOf [] _  = True
+isSubsetOf _  [] = False
+
+testAnnTable :: [TestTree]
+testAnnTable =
+  [testCase "annotates a sample table properly" $ generated @?= expected]
+ where
+  spec1 = (AlignRight, ColWidthDefault)
+  spec2 = (AlignLeft, ColWidthDefault)
+  spec3 = (AlignCenter, ColWidthDefault)
+  spec  = [spec1, spec2, spec3]
+
+  cl a h w = Cell (a, [], []) AlignDefault h w []
+  rws = map $ Row nullAttr
+  th  = TableHead nullAttr . rws
+  tb n x y = TableBody nullAttr n (rws x) (rws y)
+  tf           = TableFoot nullAttr . rws
+  initialHeads = [[cl "a" 1 1, cl "b" 3 2], [cl "c" 2 2, cl "d" 1 1]]
+  initialTB1   = tb 1
+                    [[], [cl "e" 5 1, cl "f" (-7) 0]]
+                    [[cl "g" 4 3, cl "h" 4 3], [], [emptyCell]]
+  initialTB2 = tb 2 [] [[cl "i" 4 3, cl "j" 4 3]]
+  generated  = Ann.toTable nullAttr
+                           emptyCaption
+                           spec
+                           (th initialHeads)
+                           [initialTB1, initialTB2]
+                           (tf initialHeads)
+
+  acl al n a h w =
+    Ann.Cell (NonEmpty.fromList al) n $ Cell (a, [], []) AlignDefault h w []
+  emptyAnnCell al n = acl al n "" 1 1
+  ahrw    = Ann.HeaderRow nullAttr
+  abrw    = Ann.BodyRow nullAttr
+  ath     = Ann.TableHead nullAttr
+  atb     = Ann.TableBody nullAttr
+  atf     = Ann.TableFoot nullAttr
+
+  finalTH = ath
+    [ ahrw 0 [acl [spec1] 0 "a" 1 1, acl [spec2, spec3] 1 "b" 2 2]
+    , ahrw 1 [acl [spec1] 0 "c" 1 1]
+    ]
+  finalTB1 = atb
+    1
+    [ ahrw
+      2
+      [emptyAnnCell [spec1] 0, emptyAnnCell [spec2] 1, emptyAnnCell [spec3] 2]
+    , ahrw
+      3
+      [acl [spec1] 0 "e" 1 1, acl [spec2] 1 "f" 1 1, emptyAnnCell [spec3] 2]
+    ]
+    [ abrw 4 [acl [spec1] 0 "g" 3 1] [acl [spec2, spec3] 1 "h" 3 2]
+    , abrw 5 []                      []
+    , abrw 6 []                      []
+    ]
+  finalTB2 =
+    atb 2 [] [abrw 7 [acl [spec1, spec2] 0 "i" 1 2] [acl [spec3] 2 "j" 1 1]]
+  finalTF = atf
+    [ ahrw 8 [acl [spec1] 0 "a" 1 1, acl [spec2, spec3] 1 "b" 2 2]
+    , ahrw 9 [acl [spec1] 0 "c" 1 1]
+    ]
+  expected =
+    Ann.Table nullAttr emptyCaption spec finalTH [finalTB1, finalTB2] finalTF
+
+withColSpec :: Testable prop => ([ColSpec] -> prop) -> Property
+withColSpec = forAll arbColSpec
+ where
+  arbColSpec = do
+    cs <- choose (1 :: Int, 6)
+    vectorOf
+      cs
+      ((,) <$> arbitrary <*> elements
+        [ColWidthDefault, ColWidth (1 / 3), ColWidth 0.25]
+      )
+
+annTableProps :: [TestTree]
+annTableProps =
+  localOption (QuickCheckTests 50)
+    <$> [ testProperty "normalizes like the table builder"  propBuilderAnnTable
+        , testProperty "has valid final cell columns"       propColNumber
+        , testProperty "has valid first row column data"    propFirstRowCols
+        , testProperty "has valid all row column data"      propColSubsets
+        , testProperty "has valid cell column data lengths" propCellColLengths
+        ]
+
+-- The property that Ann.toTable will normalize a table identically to
+-- the table builder. This should mean that Ann.toTable is at least as
+-- rigorous as Builder.table in that respect without repeating those
+-- tests here (see the pandoc-types Table tests for examples).
+propBuilderAnnTable :: TableHead -> [TableBody] -> TableFoot -> Property
+propBuilderAnnTable th tbs tf = withColSpec $ \cs ->
+  convertTable (table emptyCaption cs th tbs tf)
+    === convertAnnTable (Ann.toTable nullAttr emptyCaption cs th tbs tf)
+ where
+  convertTable blks = case toList blks of
+    [Table _ _ colspec a b c] -> Right (colspec, a, b, c)
+    x                         -> Left x
+  convertAnnTable x = case Ann.fromTable x of
+    (_, _, colspec, a, b, c) -> Right (colspec, a, b, c)
+
+-- The property of Ann.toTable that if the last cell in the first row
+-- of a table section has ColSpan w and ColNumber n, then w + n is the
+-- width of the table.
+propColNumber :: TableHead -> [TableBody] -> TableFoot -> Property
+propColNumber th tbs tf = withColSpec $ \cs ->
+  let twidth = length cs
+      Ann.Table _ _ _ ath atbs atf =
+          Ann.toTable nullAttr emptyCaption cs th tbs tf
+  in  conjoin
+        $  [colNumTH twidth ath]
+        <> (colNumTB twidth <$> atbs)
+        <> [colNumTF twidth atf]
+ where
+  colNumTH n (Ann.TableHead _ rs) = firstly (isHeaderValid n) rs
+  colNumTB n (Ann.TableBody _ _ rs ts) =
+    firstly (isHeaderValid n) rs && firstly (isBodyValid n) ts
+  colNumTF n (Ann.TableFoot _ rs) = firstly (isHeaderValid n) rs
+
+  isHeaderValid n (Ann.HeaderRow _ _ x) = isSegmentValid n x
+  isBodyValid n (Ann.BodyRow _ _ _ x) = isSegmentValid n x
+
+  firstly f (x : _) = f x
+  firstly _ []      = True
+  lastly f [x     ] = f x
+  lastly f (_ : xs) = lastly f xs
+  lastly _ []       = True
+
+  isSegmentValid twidth cs =
+    flip lastly cs
+      $ \(Ann.Cell _ (Ann.ColNumber n) (Cell _ _ _ (ColSpan w) _)) ->
+          n + w == twidth
+
+-- The property of an Ann.Table from Ann.toTable that if the NonEmpty
+-- ColSpec data of the cells in the first row of a table section are
+-- concatenated, the result should equal the [ColSpec] of the entire
+-- table.
+propFirstRowCols :: TableHead -> [TableBody] -> TableFoot -> Property
+propFirstRowCols th tbs tf = withColSpec $ \cs ->
+  let Ann.Table _ _ _ ath atbs atf =
+          Ann.toTable nullAttr emptyCaption cs th tbs tf
+  in  conjoin
+        $  [firstRowTH cs ath]
+        <> (firstRowTB cs <$> atbs)
+        <> [firstRowTF cs atf]
+ where
+  firstly f (x : _) = f x
+  firstly _ []      = True
+
+  firstHeaderValid cs = firstly $ \r -> cs == catHeaderSpec r
+  firstBodyValid cs = firstly $ \r -> cs == catBodySpec r
+
+  firstRowTH cs (Ann.TableHead _ rs) = firstHeaderValid cs rs
+  firstRowTB cs (Ann.TableBody _ _ rs ts) =
+    firstHeaderValid cs rs && firstBodyValid cs ts
+  firstRowTF cs (Ann.TableFoot _ rs) = firstHeaderValid cs rs
+
+-- The property that in any row in an Ann.Table from Ann.toTable, the
+-- NonEmpty ColSpec annotations on cells, when concatenated, form a
+-- subset (really sublist) of the [ColSpec] of the entire table.
+propColSubsets :: TableHead -> [TableBody] -> TableFoot -> Property
+propColSubsets th tbs tf = withColSpec $ \cs ->
+  let Ann.Table _ _ _ ath atbs atf =
+          Ann.toTable nullAttr emptyCaption cs th tbs tf
+  in  conjoin
+        $  subsetTH cs ath
+        <> concatMap (subsetTB cs) atbs
+        <> subsetTF cs atf
+ where
+  subsetTH cs (Ann.TableHead _ rs) = map (subsetHeader cs) rs
+  subsetTB cs (Ann.TableBody _ _ rs ts) =
+    map (subsetHeader cs) rs <> map (subsetBody cs) ts
+  subsetTF cs (Ann.TableFoot _ rs) = map (subsetHeader cs) rs
+
+  subsetHeader cs r = catHeaderSpec r `isSubsetOf` cs
+  subsetBody cs r = catBodySpec r `isSubsetOf` cs
+
+-- The property that in any cell in an Ann.Table from Ann.toTable, the
+-- NonEmpty ColSpec annotation on a cell is equal in length to its
+-- ColSpan.
+propCellColLengths :: TableHead -> [TableBody] -> TableFoot -> Property
+propCellColLengths th tbs tf = withColSpec $ \cs ->
+  let Ann.Table _ _ _ ath atbs atf =
+          Ann.toTable nullAttr emptyCaption cs th tbs tf
+  in  conjoin $ cellColTH ath <> concatMap cellColTB atbs <> cellColTF atf
+ where
+  cellColTH (Ann.TableHead _ rs) = concatMap cellColHeader rs
+  cellColTB (Ann.TableBody _ _ rs ts) =
+    concatMap cellColHeader rs <> concatMap cellColBody ts
+  cellColTF (Ann.TableFoot _ rs) = concatMap cellColHeader rs
+
+  cellColHeader (Ann.HeaderRow _ _ x) = fmap validLength x
+  cellColBody (Ann.BodyRow _ _ x y) = fmap validLength x <> fmap validLength y
+
+  validLength (Ann.Cell colspec _ (Cell _ _ _ (ColSpan w) _)) =
+    length colspec == w
diff --git a/test/Tests/Writers/AsciiDoc.hs b/test/Tests/Writers/AsciiDoc.hs
--- a/test/Tests/Writers/AsciiDoc.hs
+++ b/test/Tests/Writers/AsciiDoc.hs
@@ -1,3 +1,4 @@
+{-# LANGUAGE OverloadedStrings #-}
 module Tests.Writers.AsciiDoc (tests) where
 
 import Data.Text (unpack)
@@ -8,49 +9,100 @@
 import Text.Pandoc.Builder
 
 asciidoc :: (ToPandoc a) => a -> String
-asciidoc = unpack . purely (writeAsciiDoc def{ writerWrapText = WrapNone }) . toPandoc
+asciidoc = unpack . purely (writeAsciiDocLegacy def) . toPandoc
 
+asciidoctor :: (ToPandoc a) => a -> String
+asciidoctor = unpack . purely (writeAsciiDoc def) . toPandoc
+
+testAsciidoc :: (ToString a, ToPandoc a)
+             => String
+             -> (a, String)
+             -> TestTree
+testAsciidoc = test asciidoc
+
+testAsciidoctor :: (ToString a, ToPandoc a)
+             => String
+             -> (a, String)
+             -> TestTree
+testAsciidoctor = test asciidoctor
+
 tests :: [TestTree]
 tests = [ testGroup "emphasis"
-          [ test asciidoc "emph word before" $
+          [ testAsciidoc "emph word before" $
                para (text "foo" <> emph (text "bar")) =?>
                  "foo__bar__"
-          , test asciidoc "emph word after" $
+          , testAsciidoc "emph word after" $
                para (emph (text "foo") <> text "bar") =?>
                  "__foo__bar"
-          , test asciidoc "emph quoted" $
+          , testAsciidoc "emph quoted" $
                para (doubleQuoted (emph (text "foo"))) =?>
-                 "``__foo__''"
-          , test asciidoc "strong word before" $
+                 "``_foo_''"
+          , testAsciidoc "strong word before" $
                para (text "foo" <> strong (text "bar")) =?>
                  "foo**bar**"
-          , test asciidoc "strong word after" $
+          , testAsciidoc "strong word after" $
                para (strong (text "foo") <> text "bar") =?>
                  "**foo**bar"
-          , test asciidoc "strong quoted" $
+          , testAsciidoc "strong quoted" $
                para (singleQuoted (strong (text "foo"))) =?>
-                 "`**foo**'"
+                 "`*foo*'"
           ]
+        , testGroup "blocks"
+          [ testAsciidoc "code block without line numbers" $
+               codeBlockWith ("", [ "haskell" ], []) "foo" =?> unlines
+                                           [ "[source,haskell]"
+                                           , "----"
+                                           , "foo"
+                                           , "----"
+                                           ]
+          , testAsciidoc "code block with line numbers" $
+               codeBlockWith ("", [ "haskell", "numberLines" ], []) "foo" =?> unlines
+                                           [ "[source%linesnum,haskell]"
+                                           , "----"
+                                           , "foo"
+                                           , "----"
+                                           ]
+          , testAsciidoc "sidebar block" $
+               divWith ("sidebar_id", ["sidebar"], [])
+                                           (divWith ("", ["title"], [])
+                                           (plain "Sidebar Title")
+                                           <> para "Sidebar paragraph"
+                                           ) =?> unlines
+                                           [ "[[sidebar_id]]"
+                                           , "[SIDEBAR]"
+                                           , ".Sidebar Title"
+                                           , "****"
+                                           , "Sidebar paragraph"
+                                           , "****"
+                                           ]
+          ]
         , testGroup "tables"
-          [ test asciidoc "empty cells" $
+          [ testAsciidoc "empty cells" $
                simpleTable [] [[mempty],[mempty]] =?> unlines
                                            [ "[cols=\"\",]"
-                                           , "|===="
+                                           , "|==="
                                            , "|"
                                            , "|"
-                                           , "|===="
+                                           , "|==="
                                            ]
           , test asciidoc "multiblock cells" $
                simpleTable [] [[para (text "Para 1") <> para (text "Para 2")]]
                                            =?> unlines
                                            [ "[cols=\"\",]"
-                                           , "|====="
+                                           , "|==="
                                            , "a|"
                                            , "Para 1"
                                            , ""
                                            , "Para 2"
                                            , ""
-                                           , "|====="
+                                           , "|==="
+                                           ]
+          ]
+        , testGroup "lists"
+          [ testAsciidoctor "bullet task list" $
+               bulletList [plain "☐ a", plain "☒ b"] =?> unlines
+                                           [ "* [ ] a"
+                                           , "* [x] b"
                                            ]
           ]
         ]
diff --git a/test/Tests/Writers/BBCode.hs b/test/Tests/Writers/BBCode.hs
new file mode 100644
--- /dev/null
+++ b/test/Tests/Writers/BBCode.hs
@@ -0,0 +1,355 @@
+{-# LANGUAGE OverloadedStrings #-}
+{-# LANGUAGE TypeApplications #-}
+
+module Tests.Writers.BBCode (tests) where
+
+import Data.Maybe (isNothing)
+import Data.Text as T
+import Test.Tasty
+import Test.Tasty.HUnit (HasCallStack)
+import Test.Tasty.QuickCheck
+import Tests.Helpers
+import Text.Pandoc
+import Text.Pandoc.Arbitrary ()
+import Text.Pandoc.Builder
+import Text.Pandoc.Shared (tshow)
+import Text.Read (readMaybe)
+
+bbcodeDefault
+  , bbcodeSteam
+  , bbcodePhpBB
+  , bbcodeFluxBB
+  , bbcodeHubzilla
+  , bbcodeXenforo ::
+    (ToPandoc a) => a -> Text
+bbcodeDefault = purely (writeBBCode def) . toPandoc
+bbcodeSteam = purely (writeBBCodeSteam def) . toPandoc
+bbcodePhpBB = purely (writeBBCodePhpBB def) . toPandoc
+bbcodeFluxBB = purely (writeBBCodeFluxBB def) . toPandoc
+bbcodeHubzilla = purely (writeBBCodeHubzilla def) . toPandoc
+bbcodeXenforo = purely (writeBBCodeXenforo def) . toPandoc
+
+infix 4 =:, `steam`, `phpbb`, `fluxbb`, `hubzilla`, `xenforo`
+(=:)
+  , steam
+  , phpbb
+  , fluxbb
+  , hubzilla
+  , xenforo ::
+    (ToString a, ToPandoc a, HasCallStack) =>
+    String ->
+    (a, Text) ->
+    TestTree
+(=:) = test bbcodeDefault
+steam = test bbcodeSteam
+phpbb = test bbcodePhpBB
+fluxbb = test bbcodeFluxBB
+hubzilla = test bbcodeHubzilla
+xenforo = test bbcodeXenforo
+
+spanClasses :: [Text] -> Inlines -> Inlines
+spanClasses cls = spanWith ("", cls, [])
+
+spanAttrs :: [(Text, Text)] -> Inlines -> Inlines
+spanAttrs kvList = spanWith ("", [], kvList)
+
+divClasses :: [Text] -> Blocks -> Blocks
+divClasses cls = divWith ("", cls, [])
+
+divAttrs :: [(Text, Text)] -> Blocks -> Blocks
+divAttrs kvList = divWith ("", [], kvList)
+
+tests :: [TestTree]
+tests =
+  [ testGroup
+      "spans classes"
+      [ "left" =: spanClasses ["left"] "foo" =?> "foo"
+      , "center" =: spanClasses ["center"] "foo" =?> "foo"
+      , "right" =: spanClasses ["right"] "foo" =?> "foo"
+      , "spoiler" =: spanClasses ["spoiler"] "foo" =?> "foo"
+      ]
+  , testGroup
+      "spans attributes"
+      [ testProperty "incorrect size ignored" . property $ do
+          n <- arbitrary @String
+          let nInt = readMaybe @Int n
+          let actual = bbcodeDefault (spanAttrs [("size", T.pack n)] "foo")
+          pure $ isNothing nInt ==> actual === "foo"
+      , testProperty "size<=0 ignored" . property $ do
+          NonPositive n <- arbitrary @(NonPositive Int)
+          let actual = bbcodeDefault (spanAttrs [("size", tshow n)] "foo")
+          pure $ actual === "foo"
+      , testProperty "size>0" . property $ do
+          Positive n <- arbitrary @(Positive Int)
+          let actual = bbcodeDefault (spanAttrs [("size", tshow n)] "foo")
+          let expected = "[size=" <> tshow n <> "]" <> "foo[/size]"
+          pure $ actual === expected
+      , "size=20" =: spanAttrs [("size", "20")] "foo" =?> "[size=20]foo[/size]"
+      , "color=#AAAAAA"
+          =: spanAttrs [("color", "#AAAAAA")] "foo"
+          =?> "[color=#AAAAAA]foo[/color]"
+      , "spoiler ignored"
+          =: spanAttrs [("spoiler", "name with spaces and ]brackets[]")] "foo"
+          =?> "foo"
+      ]
+  , testGroup
+      "divs classes"
+      [ "left"
+          =: divClasses ["left"] (para "foo")
+          =?> "[left]foo[/left]"
+      , "center"
+          =: divClasses ["center"] (para "foo")
+          =?> "[center]foo[/center]"
+      , "right"
+          =: divClasses ["right"] (para "foo")
+          =?> "[right]foo[/right]"
+      , "spoiler"
+          =: divClasses ["spoiler"] (para "foo")
+          =?> "[spoiler]foo[/spoiler]"
+      ]
+  , testGroup
+      "divs attributes"
+      [ testProperty "incorrect size ignored" . property $ do
+          n <- arbitrary @String
+          let nInt = readMaybe @Int n
+          let actual = bbcodeDefault (divAttrs [("size", T.pack n)] $ para "foo")
+          pure $ isNothing nInt ==> actual === "foo"
+      , testProperty "size<=0 ignored" . property $ do
+          NonPositive n <- arbitrary @(NonPositive Int)
+          let actual = bbcodeDefault (divAttrs [("size", tshow n)] $ para "foo")
+          pure $ actual === "foo"
+      , testProperty "size>0" . property $ do
+          Positive n <- arbitrary @(Positive Int)
+          let actual = bbcodeDefault (divAttrs [("size", tshow n)] $ para "foo")
+          let expected = "[size=" <> tshow n <> "]" <> "foo[/size]"
+          pure $ actual === expected
+      , "size=20"
+          =: divAttrs [("size", "20")] (para "foo")
+          =?> "[size=20]foo[/size]"
+      , "color=#AAAAAA"
+          =: divAttrs [("color", "#AAAAAA")] (para "foo")
+          =?> "[color=#AAAAAA]foo[/color]"
+      , "spoiler"
+          =: divAttrs
+            [("spoiler", "name with spaces and ]brackets[]")]
+            (para "foo")
+          =?> "[spoiler=name with spaces and brackets]foo[/spoiler]"
+      ]
+  , testGroup
+      "default flavor"
+      [ "link"
+          =: link "https://example.com" "title" "label"
+          =?> "[url=https://example.com]label[/url]"
+      , "autolink"
+          =: link "https://example.com" "title" "https://example.com"
+          =?> "[url]https://example.com[/url]"
+      , "email autolink"
+          =: link
+            "mailto:example@example.com"
+            "title"
+            "example@example.com"
+          =?> "[email]example@example.com[/email]"
+      , "named email"
+          =: link "mailto:example@example.com" "title" "example email"
+          =?> "[email=example@example.com]example email[/email]"
+      , "h0" =: header 0 "heading 0" =?> "[u][b]heading 0[/b][/u]"
+      , "h1" =: header 1 "heading 1" =?> "[u][b]heading 1[/b][/u]"
+      , "h2" =: header 2 "heading 2" =?> "[b]heading 2[/b]"
+      , "h3" =: header 3 "heading 3" =?> "[u]heading 3[/u]"
+      , "h4" =: header 4 "heading 4" =?> "heading 4"
+      , "h5" =: header 5 "heading 5" =?> "heading 5"
+      ]
+  , testGroup
+      "steam"
+      [ test bbcodeSteam "dename spoiler" $
+          divAttrs [("spoiler", "bar")] (para "foo")
+            =?> ("[spoiler]foo[/spoiler]" :: Text)
+      , testProperty "ordered list styleless" . property $ do
+          let listItems = [para "foo", para "bar", para "baz"]
+          attrsRand <- (,,) <$> arbitrary <*> arbitrary <*> arbitrary
+          let actual = bbcodeSteam $ orderedListWith attrsRand listItems
+          let expected = "[olist]\n[*]foo\n[*]bar\n[*]baz\n[/olist]"
+          pure $ actual === expected
+      , "h0" `steam` header 0 "heading 0" =?> "[h1]heading 0[/h1]"
+      , "h1" `steam` header 1 "heading 1" =?> "[h1]heading 1[/h1]"
+      , "h2" `steam` header 2 "heading 2" =?> "[h2]heading 2[/h2]"
+      , "h3" `steam` header 3 "heading 3" =?> "[h3]heading 3[/h3]"
+      , "h4" `steam` header 4 "heading 4" =?> "[h3]heading 4[/h3]"
+      , "code"
+          `steam` codeWith ("id", ["haskell"], []) "map (2^) [1..5]"
+          =?> "[noparse]map (2^) [1..5][/noparse]"
+      ]
+  , testGroup
+      "phpBB"
+      [ "image"
+          `phpbb` imageWith
+            ("id", [], [("width", "100")])
+            "https://example.com"
+            "title"
+            "alt text"
+          =?> "[img]https://example.com[/img]"
+      ]
+  , testGroup
+      "FluxBB"
+      [ "image"
+          `fluxbb` imageWith
+            ("id", [], [("width", "100")])
+            "https://example.com"
+            "title"
+            "alt text"
+          =?> "[img=alt text]https://example.com[/img]"
+      , testProperty "ordered list" . property $ do
+          let listItems = [para "foo", para "bar", para "baz"]
+          attrsRand <- (,,) <$> arbitrary <*> arbitrary <*> arbitrary
+          let actual = bbcodeFluxBB $ orderedListWith attrsRand listItems
+          let opening = case attrsRand of
+                (_, LowerAlpha, _) -> "[list=a]"
+                (_, UpperAlpha, _) -> "[list=a]"
+                _ -> "[list=1]"
+          let expected = opening <> "\n[*]foo\n[*]bar\n[*]baz\n[/list]"
+          pure $ actual === expected
+      , "ulist > BlockQuote not rendered"
+          `fluxbb` bulletList [blockQuote (para "foo") <> para "bar"]
+          =?> "[list]\n[*]bar\n[/list]"
+      , "code block"
+          `fluxbb` codeBlockWith
+            ("id", ["haskell"], [])
+            ( T.intercalate "\n" $
+                [ "vals ="
+                , "  take 10"
+                , "    . filter (\\x -> (x - 5) `mod` 3 == 0)"
+                , "    $ map (2 ^) [1 ..]"
+                ]
+            )
+          =?> T.intercalate
+            "\n"
+            [ "[code]vals ="
+            , "  take 10"
+            , "    . filter (\\x -> (x - 5) `mod` 3 == 0)"
+            , "    $ map (2 ^) [1 ..]"
+            , "[/code]"
+            ]
+      ]
+  , testGroup
+      "Hubzilla"
+      [ "unordered list"
+          `hubzilla` bulletList [para "foo", para "bar", para "baz"]
+          =?> "[ul]\n[*]foo\n[*]bar\n[*]baz\n[/ul]"
+      , testProperty "ordered list" . property $ do
+          let listItems = [para "foo", para "bar", para "baz"]
+          attrsRand <- (,,) <$> arbitrary <*> arbitrary <*> arbitrary
+          let actual = bbcodeHubzilla $ orderedListWith attrsRand listItems
+          let (opening, closing) = case attrsRand of
+                (_, Decimal, _) -> ("[list=1]", "[/list]")
+                (_, DefaultStyle, _) -> ("[ol]", "[/ol]")
+                (_, Example, _) -> ("[ol]", "[/ol]")
+                (_, LowerAlpha, _) -> ("[list=a]", "[/list]")
+                (_, UpperAlpha, _) -> ("[list=A]", "[/list]")
+                (_, LowerRoman, _) -> ("[list=i]", "[/list]")
+                (_, UpperRoman, _) -> ("[list=I]", "[/list]")
+          let expected =
+                opening <> "\n[*]foo\n[*]bar\n[*]baz\n" <> closing
+          pure $ actual === expected
+      , "definition list"
+          `hubzilla` definitionList
+            [ ("term_foo", [para "def_foo1", para "def_foo2"])
+            , ("term_bar", [para "def_bar1", para "def_bar2"])
+            , ("term_baz", [para "def_baz1", para "def_baz2"])
+            ]
+          =?> mconcat
+            [ "[dl terms=\"b\"]\n"
+            , "[*= term_foo]\ndef_foo1\ndef_foo2\n"
+            , "[*= term_bar]\ndef_bar1\ndef_bar2\n"
+            , "[*= term_baz]\ndef_baz1\ndef_baz2\n"
+            , "[/dl]"
+            ]
+      , "h0" `hubzilla` header 0 "heading 0" =?> "[h1]heading 0[/h1]"
+      , "h1" `hubzilla` header 1 "heading 1" =?> "[h1]heading 1[/h1]"
+      , "h2" `hubzilla` header 2 "heading 2" =?> "[h2]heading 2[/h2]"
+      , "h3" `hubzilla` header 3 "heading 3" =?> "[h3]heading 3[/h3]"
+      , "h4" `hubzilla` header 4 "heading 4" =?> "[h4]heading 4[/h4]"
+      , "h5" `hubzilla` header 5 "heading 5" =?> "[h5]heading 5[/h5]"
+      , "h6" `hubzilla` header 6 "heading 6" =?> "[h6]heading 6[/h6]"
+      , "h7" `hubzilla` header 7 "heading 7" =?> "[h6]heading 7[/h6]"
+      , "link"
+          `hubzilla` link "https://example.com" "title" "label"
+          =?> "[url=https://example.com]label[/url]"
+      , "autolink"
+          `hubzilla` link "https://example.com" "title" "https://example.com"
+          =?> "[url]https://example.com[/url]"
+      , "email autolink"
+          `hubzilla` link
+            "mailto:example@example.com"
+            "title"
+            "example@example.com"
+          =?> "[url=mailto:example@example.com]example@example.com[/url]"
+      , "named email"
+          `hubzilla` link "mailto:example@example.com" "title" "example email"
+          =?> "[url=mailto:example@example.com]example email[/url]"
+      , "inline code"
+          `hubzilla` ( "inline code: "
+                        <> codeWith ("id", ["haskell"], []) "map (2^) [1..5]"
+                     )
+          =?> "inline code: [code]map (2^) [1..5][/code]"
+      , "font"
+          `hubzilla` divAttrs [("font", "serif")] (para "foo")
+          =?> "[font=serif]foo[/font]"
+      ]
+  , testGroup
+      "xenForo"
+      [ "unordered list"
+          `xenforo` bulletList [para "foo", para "bar", para "baz"]
+          =?> "[list]\n[*]foo\n[*]bar\n[*]baz\n[/list]"
+      , testProperty "ordered list styleless" . property $ do
+          let listItems = [para "foo", para "bar", para "baz"]
+          attrsRand <- (,,) <$> arbitrary <*> arbitrary <*> arbitrary
+          let actual = bbcodeXenforo $ orderedListWith attrsRand listItems
+          let expected = "[list=1]\n[*]foo\n[*]bar\n[*]baz\n[/list]"
+          pure $ actual === expected
+      , "h0" `xenforo` header 0 "heading 0" =?> "[heading=1]heading 0[/heading]"
+      , "h1" `xenforo` header 1 "heading 1" =?> "[heading=1]heading 1[/heading]"
+      , "h2" `xenforo` header 2 "heading 2" =?> "[heading=2]heading 2[/heading]"
+      , "h3" `xenforo` header 3 "heading 3" =?> "[heading=3]heading 3[/heading]"
+      , "h4" `xenforo` header 4 "heading 4" =?> "[heading=4]heading 4[/heading]"
+      , "link"
+          `xenforo` link "https://example.com" "title" "label"
+          =?> "[url=https://example.com]label[/url]"
+      , "autolink"
+          `xenforo` link "https://example.com" "title" "https://example.com"
+          =?> "[url]https://example.com[/url]"
+      , "email autolink"
+          `xenforo` link
+            "mailto:example@example.com"
+            "title"
+            "example@example.com"
+          =?> "[email]example@example.com[/email]"
+      , "named email"
+          `xenforo` link "mailto:example@example.com" "title" "example email"
+          =?> "[email=example@example.com]example email[/email]"
+      , "inline code"
+          `xenforo` ( "inline code: "
+                        <> codeWith ("id", ["haskell"], []) "map (2^) [1..5]"
+                    )
+          =?> "inline code: [icode]map (2^) [1..5][/icode]"
+      , "font"
+          `xenforo` divAttrs [("font", "serif")] (para "foo")
+          =?> "[font=serif]foo[/font]"
+      , "inline spoiler"
+          `xenforo` ("It was " <> spanClasses ["spoiler"] ("DNS") <> "!")
+          =?> "It was [ispoiler]DNS[/ispoiler]!"
+      , "image w=50% h=50%"
+          `xenforo` imageWith
+            ("", [], [("width", "50%"), ("height", "50%")])
+            "https://example.com"
+            "title text"
+            "alt text"
+          =?> "[img alt=\"alt text\" title=\"title text\" width=50%]https://example.com[/img]"
+      , "image w=50 h=50"
+          `xenforo` imageWith
+            ("", [], [("width", "50"), ("height", "50")])
+            "https://example.com"
+            ""
+            ""
+          =?> "[img]https://example.com[/img]"
+      ]
+  ]
diff --git a/test/Tests/Writers/ConTeXt.hs b/test/Tests/Writers/ConTeXt.hs
--- a/test/Tests/Writers/ConTeXt.hs
+++ b/test/Tests/Writers/ConTeXt.hs
@@ -1,13 +1,15 @@
 {-# LANGUAGE OverloadedStrings #-}
 module Tests.Writers.ConTeXt (tests) where
 
-import Data.Text (unpack)
+import Data.Text (unpack, pack)
 import Test.Tasty
+import Test.Tasty.HUnit (HasCallStack)
 import Test.Tasty.QuickCheck
 import Tests.Helpers
 import Text.Pandoc
 import Text.Pandoc.Arbitrary ()
 import Text.Pandoc.Builder
+import qualified Data.Text as T
 
 context :: (ToPandoc a) => a -> String
 context = unpack . purely (writeConTeXt def) . toPandoc
@@ -15,6 +17,14 @@
 context' :: (ToPandoc a) => a -> String
 context' = unpack . purely (writeConTeXt def{ writerWrapText = WrapNone }) . toPandoc
 
+contextNtb :: (ToPandoc a) => a -> String
+contextNtb = unpack . purely (writeConTeXt def{ writerExtensions = enableExtension Ext_ntb pandocExtensions }) . toPandoc
+
+contextSection :: (ToPandoc a) => a -> String
+contextSection = unpack
+  . purely (writeConTeXt def{ writerTopLevelDivision = TopLevelSection })
+  . toPandoc
+
 {-
   "my test" =: X =?> Y
 
@@ -28,45 +38,141 @@
 -}
 
 infix 4 =:
-(=:) :: (ToString a, ToPandoc a)
+(=:) :: (ToString a, ToPandoc a, HasCallStack)
      => String -> (a, String) -> TestTree
 (=:) = test context
 
 tests :: [TestTree]
-tests = [ testGroup "inline code"
-          [ "with '}'" =: code "}" =?> "\\mono{\\}}"
-          , "without '}'" =: code "]" =?> "\\type{]}"
-          , testProperty "code property" $ \s -> null s ||
-                if '{' `elem` s || '}' `elem` s
-                   then (context' $ code s) == "\\mono{" ++
-                             (context' $ str s) ++ "}"
-                   else (context' $ code s) == "\\type{" ++ s ++ "}"
-          ]
-        , testGroup "headers"
-          [ "level 1" =:
-            headerWith ("my-header",[],[]) 1 "My header" =?> "\\section[my-header]{My header}"
-          ]
-        , testGroup "bullet lists"
-          [ "nested" =:
-            bulletList [
-               plain (text "top")
-                 <> bulletList [
-                   plain (text "next")
-                    <> bulletList [plain (text "bot")]
-                 ]
-            ] =?> unlines
-                [ "\\startitemize[packed]"
-                , "\\item"
-                , "  top"
-                , "  \\startitemize[packed]"
-                , "  \\item"
-                , "    next"
-                , "    \\startitemize[packed]"
-                , "    \\item"
-                , "      bot"
-                , "    \\stopitemize"
-                , "  \\stopitemize"
-                , "\\stopitemize" ]
-          ]
-        ]
-
+tests =
+  [ testGroup "inline code"
+    [ "with '}'" =: code "}" =?> "\\type\"}\""
+    , "without '}'" =: code "]" =?> "\\type{]}"
+    , "span with ID" =:
+      spanWith ("city", [], []) "Berlin" =?>
+      "\\reference[city]{}Berlin"
+    , testProperty "code property" $ \s ->
+        null s || '\n' `elem` s ||
+        case T.stripPrefix "\\type" (pack $ context' (code $ pack s))
+             >>= T.uncons of
+          Just (c, _) -> c `notElem` s
+          Nothing     -> False
+    ]
+  , testGroup "headers"
+    [ "level 1" =:
+      headerWith ("my-header",[],[]) 1 "My header" =?>
+      "\\startsectionlevel[title={My header},reference={my-header}]\n" <>
+      "\n" <>
+      "\\stopsectionlevel"
+    , test contextSection "Section as top-level" $
+      (   headerWith ("header1", [], []) 1 (text "Header1")
+       <> headerWith ("header2", [], []) 2 (text "Header2")
+       <> headerWith ("header3", [], []) 3 (text "Header3")
+       <> headerWith ("header4", [], []) 4 (text "Header4")
+       <> headerWith ("header5", [], []) 5 (text "Header5")
+       <> headerWith ("header6", [], []) 6 (text "Header6"))
+      =?>
+      unlines
+      [ "\\startsection[title={Header1},reference={header1}]\n"
+      , "\\startsubsection[title={Header2},reference={header2}]\n"
+      , "\\startsubsubsection[title={Header3},reference={header3}]\n"
+      , "\\startsubsubsubsection[title={Header4},reference={header4}]\n"
+      , "\\startsubsubsubsubsection[title={Header5},reference={header5}]\n"
+      , "\\startsubsubsubsubsubsection[title={Header6},reference={header6}]\n"
+      , "\\stopsubsubsubsubsubsection\n"
+      , "\\stopsubsubsubsubsection\n"
+      , "\\stopsubsubsubsection\n"
+      , "\\stopsubsubsection\n"
+      , "\\stopsubsection\n"
+      , "\\stopsection" ]
+    ]
+  , testGroup "bullet lists"
+    [ "nested" =:
+      bulletList [
+         plain (text "top")
+           <> bulletList [
+             plain (text "next")
+              <> bulletList [plain (text "bot")]
+           ]
+      ] =?> unlines
+          [ "\\startitemize[packed]"
+          , "\\item"
+          , "  top"
+          , "  \\startitemize[packed]"
+          , "  \\item"
+          , "    next"
+          , "    \\startitemize[packed]"
+          , "    \\item"
+          , "      bot"
+          , "    \\stopitemize"
+          , "  \\stopitemize"
+          , "\\stopitemize" ]
+    ]
+  , testGroup "natural tables"
+    [ test contextNtb "table with header and caption" $
+      let capt = text "Table 1"
+          aligns = [ (AlignRight, ColWidthDefault)
+                   , (AlignLeft, ColWidthDefault)
+                   , (AlignCenter, ColWidthDefault)
+                   , (AlignDefault, ColWidthDefault) ]
+          headers = [plain $ text "Right",
+                     plain $ text "Left",
+                     plain $ text "Center",
+                     plain $ text "Default"]
+          rows = [[plain $ text "1.1",
+                   plain $ text "1.2",
+                   plain $ text "1.3",
+                   plain $ text "1.4"]
+                 ,[plain $ text "2.1",
+                   plain $ text "2.2",
+                   plain $ text "2.3",
+                   plain $ text "2.4"]
+                 ,[plain $ text "3.1",
+                   plain $ text "3.2",
+                   plain $ text "3.3",
+                   plain $ text "3.4"]]
+          toRow = Row nullAttr . map simpleCell
+      in table (simpleCaption $ plain capt)
+               aligns
+               (TableHead nullAttr [toRow headers])
+               [TableBody nullAttr 0 [] $ map toRow rows]
+               (TableFoot nullAttr [])
+      =?> unlines [ "\\startplacetable[title={Table 1}]"
+                  , "\\setupTABLE[column][1][align=left]"
+                  , "\\setupTABLE[column][2][align=right]"
+                  , "\\setupTABLE[column][3][align=middle]"
+                  , "\\setupTABLE[column][4][align=left]"
+                  , "\\bTABLE"
+                  , "\\bTABLEhead"
+                  , "\\bTR"
+                  , "\\bTH Right\\eTH"
+                  , "\\bTH Left\\eTH"
+                  , "\\bTH Center\\eTH"
+                  , "\\bTH Default\\eTH"
+                  , "\\eTR"
+                  , "\\eTABLEhead"
+                  , "\\bTABLEbody"
+                  , "\\bTR"
+                  , "\\bTD 1.1\\eTD"
+                  , "\\bTD 1.2\\eTD"
+                  , "\\bTD 1.3\\eTD"
+                  , "\\bTD 1.4\\eTD"
+                  , "\\eTR"
+                  , "\\bTR"
+                  , "\\bTD 2.1\\eTD"
+                  , "\\bTD 2.2\\eTD"
+                  , "\\bTD 2.3\\eTD"
+                  , "\\bTD 2.4\\eTD"
+                  , "\\eTR"
+                  , "\\bTR"
+                  , "\\bTD 3.1\\eTD"
+                  , "\\bTD 3.2\\eTD"
+                  , "\\bTD 3.3\\eTD"
+                  , "\\bTD 3.4\\eTD"
+                  , "\\eTR"
+                  , "\\eTABLEbody"
+                  , "\\bTABLEfoot"
+                  , "\\eTABLEfoot"
+                  , "\\eTABLE"
+                  , "\\stopplacetable" ]
+    ]
+  ]
diff --git a/test/Tests/Writers/DocBook.hs b/test/Tests/Writers/DocBook.hs
new file mode 100644
--- /dev/null
+++ b/test/Tests/Writers/DocBook.hs
@@ -0,0 +1,431 @@
+{-# LANGUAGE OverloadedStrings #-}
+module Tests.Writers.DocBook (tests) where
+
+import Data.Text (unpack)
+import Test.Tasty
+import Tests.Helpers
+import Text.Pandoc
+import Text.Pandoc.Arbitrary ()
+import Text.Pandoc.Builder
+
+docbook :: (ToPandoc a) => a -> String
+docbook = docbookWithOpts def{ writerWrapText = WrapNone }
+
+docbook5 :: (ToPandoc a) => a -> String
+docbook5 = docbook5WithOpts def{ writerWrapText = WrapNone }
+
+docbookWithOpts :: ToPandoc a => WriterOptions -> a -> String
+docbookWithOpts opts = unpack . purely (writeDocBook4 opts) . toPandoc
+
+docbook5WithOpts :: ToPandoc a => WriterOptions -> a -> String
+docbook5WithOpts opts = unpack . purely (writeDocBook5 opts) . toPandoc
+{-
+  "my test" =: X =?> Y
+
+is shorthand for
+
+  test docbook "my test" $ X =?> Y
+
+which is in turn shorthand for
+
+  test docbook "my test" (X,Y)
+-}
+
+infix 4 =:
+(=:), testDb4, testDb5 :: (ToString a, ToPandoc a)
+                       => String -> (a, String) -> TestTree
+(=:) = test docbook
+testDb4 = test docbook
+testDb5 = test docbook5
+
+lineblock :: Blocks
+lineblock = para ("some text" <> linebreak <>
+                  "and more lines" <> linebreak <>
+                  "and again")
+lineblock_out :: [String]
+lineblock_out = [ "<literallayout>some text"
+                , "and more lines"
+                , "and again</literallayout>"
+                ]
+
+tests :: [TestTree]
+tests = [ testGroup "inline elements"
+          [ testGroup "links"
+            [ testDb4 "db4 external link" $ link "https://example.com" "" "Hello"
+                                            =?> "<ulink url=\"https://example.com\">Hello</ulink>"
+            , testDb5 "db5 external link" $ link "https://example.com" "" "Hello"
+                                            =?> "<link xlink:href=\"https://example.com\">Hello</link>"
+            , testDb5 "anchor"            $ link "#foo" "" "Hello"
+                                            =?> "<link linkend=\"foo\">Hello</link>"
+            , testDb5 "automatic anchor"  $ link "#foo" "" ""
+                                            =?> "<xref linkend=\"foo\"></xref>"
+            ]
+          ]
+        , testGroup "line blocks"
+          [ "none"       =: para "This is a test"
+                              =?> unlines
+                                    [ "<para>"
+                                    , "  This is a test"
+                                    , "</para>"
+                                    ]
+          , "basic"      =: lineblock
+                              =?> unlines lineblock_out
+          , "blockquote" =: blockQuote lineblock
+                              =?> unlines
+                                    ( [ "<blockquote>" ] ++
+                                      lineblock_out ++
+                                      [ "</blockquote>" ]
+                                    )
+          , "footnote"   =: para ("This is a test" <>
+                                  note lineblock <>
+                                  " of footnotes")
+                              =?> unlines
+                                    ( [ "<para>"
+                                      , "  This is a test<footnote>" ] ++
+                                      lineblock_out ++
+                                      [ "  </footnote> of footnotes"
+                                      , "</para>" ]
+                                    )
+          ]
+        , testGroup "divs"
+          [ "admonition" =: divWith ("foo", ["warning"], []) (para "This is a test")
+                              =?> unlines
+                                    [ "<warning id=\"foo\">"
+                                    , "  <para>"
+                                    , "    This is a test"
+                                    , "  </para>"
+                                    , "</warning>"
+                                    ]
+          , "admonition-with-title" =:
+                            divWith ("foo", ["note"], []) (
+                              divWith ("foo", ["title"], [])
+                                (plain (text "This is title")) <>
+                              para "This is a test"
+                            )
+                              =?> unlines
+                                    [ "<note id=\"foo\">"
+                                    , "  <title>This is title</title>"
+                                    , "  <para>"
+                                    , "    This is a test"
+                                    , "  </para>"
+                                    , "</note>"
+                                    ]
+          , "admonition-with-title-in-para" =:
+                            divWith ("foo", ["note"], []) (
+                              divWith ("foo", ["title"], [])
+                                (para "This is title") <>
+                              para "This is a test"
+                            )
+                              =?> unlines
+                                    [ "<note id=\"foo\">"
+                                    , "  <title>This is title</title>"
+                                    , "  <para>"
+                                    , "    This is a test"
+                                    , "  </para>"
+                                    , "</note>"
+                                    ]
+          , "single-child" =:
+                            divWith ("foo", [], []) (para "This is a test")
+                              =?> unlines
+                                    [ "<para id=\"foo\">"
+                                    , "  This is a test"
+                                    , "</para>"
+                                    ]
+          , "single-literal-child" =:
+                            divWith ("foo", [], []) lineblock
+                              =?> unlines
+                                    [ "<literallayout id=\"foo\">some text"
+                                    , "and more lines"
+                                    , "and again</literallayout>"
+                                    ]
+          , "multiple-children" =:
+                            divWith ("foo", [], []) (
+                              para "This is a test" <>
+                              para "This is an another test"
+                            )
+                              =?> unlines
+                                    [ "<anchor id=\"foo\" />"
+                                    , "<para>"
+                                    , "  This is a test"
+                                    , "</para>"
+                                    , "<para>"
+                                    , "  This is an another test"
+                                    , "</para>"
+                                    ]
+          ]
+        , testGroup "compact lists"
+          [ testGroup "bullet"
+            [ "compact"    =: bulletList [plain "a", plain "b", plain "c"]
+                                =?> unlines
+                                      [ "<itemizedlist spacing=\"compact\">"
+                                      , "  <listitem>"
+                                      , "    <para>"
+                                      , "      a"
+                                      , "    </para>"
+                                      , "  </listitem>"
+                                      , "  <listitem>"
+                                      , "    <para>"
+                                      , "      b"
+                                      , "    </para>"
+                                      , "  </listitem>"
+                                      , "  <listitem>"
+                                      , "    <para>"
+                                      , "      c"
+                                      , "    </para>"
+                                      , "  </listitem>"
+                                      , "</itemizedlist>"
+                                      ]
+            , "loose"      =: bulletList [para "a", para "b", para "c"]
+                                =?> unlines
+                                      [ "<itemizedlist>"
+                                      , "  <listitem>"
+                                      , "    <para>"
+                                      , "      a"
+                                      , "    </para>"
+                                      , "  </listitem>"
+                                      , "  <listitem>"
+                                      , "    <para>"
+                                      , "      b"
+                                      , "    </para>"
+                                      , "  </listitem>"
+                                      , "  <listitem>"
+                                      , "    <para>"
+                                      , "      c"
+                                      , "    </para>"
+                                      , "  </listitem>"
+                                      , "</itemizedlist>"
+                                      ]
+            ]
+          , testGroup "ordered"
+            [ "compact"    =: orderedList [plain "a", plain "b", plain "c"]
+                                =?> unlines
+                                      [ "<orderedlist spacing=\"compact\">"
+                                      , "  <listitem>"
+                                      , "    <para>"
+                                      , "      a"
+                                      , "    </para>"
+                                      , "  </listitem>"
+                                      , "  <listitem>"
+                                      , "    <para>"
+                                      , "      b"
+                                      , "    </para>"
+                                      , "  </listitem>"
+                                      , "  <listitem>"
+                                      , "    <para>"
+                                      , "      c"
+                                      , "    </para>"
+                                      , "  </listitem>"
+                                      , "</orderedlist>"
+                                      ]
+            , "loose"      =: orderedList [para "a", para "b", para "c"]
+                                =?> unlines
+                                      [ "<orderedlist>"
+                                      , "  <listitem>"
+                                      , "    <para>"
+                                      , "      a"
+                                      , "    </para>"
+                                      , "  </listitem>"
+                                      , "  <listitem>"
+                                      , "    <para>"
+                                      , "      b"
+                                      , "    </para>"
+                                      , "  </listitem>"
+                                      , "  <listitem>"
+                                      , "    <para>"
+                                      , "      c"
+                                      , "    </para>"
+                                      , "  </listitem>"
+                                      , "</orderedlist>"
+                                      ]
+            ]
+          , testGroup "definition"
+            [ "compact"    =: definitionList [ ("an", [plain "apple" ])
+                                             , ("a",  [plain "banana"])
+                                             , ("an", [plain "orange"])]
+                                =?> unlines
+                                      [ "<variablelist spacing=\"compact\">"
+                                      , "  <varlistentry>"
+                                      , "    <term>"
+                                      , "      an"
+                                      , "    </term>"
+                                      , "    <listitem>"
+                                      , "      <para>"
+                                      , "        apple"
+                                      , "      </para>"
+                                      , "    </listitem>"
+                                      , "  </varlistentry>"
+                                      , "  <varlistentry>"
+                                      , "    <term>"
+                                      , "      a"
+                                      , "    </term>"
+                                      , "    <listitem>"
+                                      , "      <para>"
+                                      , "        banana"
+                                      , "      </para>"
+                                      , "    </listitem>"
+                                      , "  </varlistentry>"
+                                      , "  <varlistentry>"
+                                      , "    <term>"
+                                      , "      an"
+                                      , "    </term>"
+                                      , "    <listitem>"
+                                      , "      <para>"
+                                      , "        orange"
+                                      , "      </para>"
+                                      , "    </listitem>"
+                                      , "  </varlistentry>"
+                                      , "</variablelist>"
+                                      ]
+            , "loose"      =: definitionList [ ("an", [para "apple" ])
+                                             , ("a",  [para "banana"])
+                                             , ("an", [para "orange"])]
+                                =?> unlines
+                                      [ "<variablelist>"
+                                      , "  <varlistentry>"
+                                      , "    <term>"
+                                      , "      an"
+                                      , "    </term>"
+                                      , "    <listitem>"
+                                      , "      <para>"
+                                      , "        apple"
+                                      , "      </para>"
+                                      , "    </listitem>"
+                                      , "  </varlistentry>"
+                                      , "  <varlistentry>"
+                                      , "    <term>"
+                                      , "      a"
+                                      , "    </term>"
+                                      , "    <listitem>"
+                                      , "      <para>"
+                                      , "        banana"
+                                      , "      </para>"
+                                      , "    </listitem>"
+                                      , "  </varlistentry>"
+                                      , "  <varlistentry>"
+                                      , "    <term>"
+                                      , "      an"
+                                      , "    </term>"
+                                      , "    <listitem>"
+                                      , "      <para>"
+                                      , "        orange"
+                                      , "      </para>"
+                                      , "    </listitem>"
+                                      , "  </varlistentry>"
+                                      , "</variablelist>"
+                                      ]
+            ]
+          ]
+        , testGroup "writer options"
+          [ testGroup "top-level division" $
+            let
+              headers =  header 1 (text "header1")
+                      <> header 2 (text "header2")
+                      <> header 3 (text "header3")
+
+              docbookTopLevelDiv :: (ToPandoc a)
+                                 => TopLevelDivision -> a -> String
+              docbookTopLevelDiv division =
+                docbookWithOpts def{ writerTopLevelDivision = division }
+            in
+            [ test (docbookTopLevelDiv TopLevelSection) "sections as top-level" $
+              headers =?>
+              unlines [ "<sect1>"
+                      , "  <title>header1</title>"
+                      , "  <sect2>"
+                      , "    <title>header2</title>"
+                      , "    <sect3>"
+                      , "      <title>header3</title>"
+                      , "      <para>"
+                      , "      </para>"
+                      , "    </sect3>"
+                      , "  </sect2>"
+                      , "</sect1>"
+                      ]
+            , test (docbookTopLevelDiv TopLevelChapter) "chapters as top-level" $
+              headers =?>
+              unlines [ "<chapter>"
+                      , "  <title>header1</title>"
+                      , "  <sect1>"
+                      , "    <title>header2</title>"
+                      , "    <sect2>"
+                      , "      <title>header3</title>"
+                      , "      <para>"
+                      , "      </para>"
+                      , "    </sect2>"
+                      , "  </sect1>"
+                      , "</chapter>"
+                      ]
+            , test (docbookTopLevelDiv TopLevelPart) "parts as top-level" $
+              headers =?>
+              unlines [ "<part>"
+                      , "  <title>header1</title>"
+                      , "  <chapter>"
+                      , "    <title>header2</title>"
+                      , "    <sect1>"
+                      , "      <title>header3</title>"
+                      , "      <para>"
+                      , "      </para>"
+                      , "    </sect1>"
+                      , "  </chapter>"
+                      , "</part>"
+                      ]
+            , test (docbookTopLevelDiv TopLevelDefault) "default top-level" $
+              headers =?>
+              unlines [ "<sect1>"
+                      , "  <title>header1</title>"
+                      , "  <sect2>"
+                      , "    <title>header2</title>"
+                      , "    <sect3>"
+                      , "      <title>header3</title>"
+                      , "      <para>"
+                      , "      </para>"
+                      , "    </sect3>"
+                      , "  </sect2>"
+                      , "</sect1>"
+                      ]
+            ]
+          ]
+          , testGroup "section attributes" $
+            let
+              headers =  headerWith ("myid1",["unnumbered","ignored"],[("role","internal"),("xml:id","anotherid"),("dir","rtl")]) 1 "header1"
+                      <> headerWith ("myid2",["unnumbered"],[("invalidname","value"),("arch","linux"),("dir","invaliddir")]) 1 "header2"
+                      <> headerWith ("myid3",["ignored"],[]) 1 "header3"
+            in
+            [ test docbook5 "sections with attributes (db5)" $
+              headers =?>
+              unlines [ "<section xmlns=\"http://docbook.org/ns/docbook\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" xml:id=\"myid1\" role=\"unnumbered internal\" dir=\"rtl\">"
+                      , "  <title>header1</title>"
+                      , "  <para>"
+                      , "  </para>"
+                      , "</section>"
+                      , "<section xmlns=\"http://docbook.org/ns/docbook\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" xml:id=\"myid2\" role=\"unnumbered\">"
+                      , "  <title>header2</title>"
+                      , "  <para>"
+                      , "  </para>"
+                      , "</section>"
+                      , "<section xmlns=\"http://docbook.org/ns/docbook\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" xml:id=\"myid3\">"
+                      , "  <title>header3</title>"
+                      , "  <para>"
+                      , "  </para>"
+                      , "</section>"
+                      ]
+            , test docbook "sections with attributes (db4)" $
+              headers =?>
+              unlines [ "<sect1 id=\"myid1\" role=\"unnumbered internal\">"
+                      , "  <title>header1</title>"
+                      , "  <para>"
+                      , "  </para>"
+                      , "</sect1>"
+                      , "<sect1 id=\"myid2\" role=\"unnumbered\" arch=\"linux\">"
+                      , "  <title>header2</title>"
+                      , "  <para>"
+                      , "  </para>"
+                      , "</sect1>"
+                      , "<sect1 id=\"myid3\">"
+                      , "  <title>header3</title>"
+                      , "  <para>"
+                      , "  </para>"
+                      , "</sect1>"
+                      ]
+            ]
+        ]
diff --git a/test/Tests/Writers/Docbook.hs b/test/Tests/Writers/Docbook.hs
deleted file mode 100644
--- a/test/Tests/Writers/Docbook.hs
+++ /dev/null
@@ -1,303 +0,0 @@
-{-# LANGUAGE OverloadedStrings #-}
-module Tests.Writers.Docbook (tests) where
-
-import Data.Text (unpack)
-import Test.Tasty
-import Tests.Helpers
-import Text.Pandoc
-import Text.Pandoc.Arbitrary ()
-import Text.Pandoc.Builder
-
-docbook :: (ToPandoc a) => a -> String
-docbook = docbookWithOpts def{ writerWrapText = WrapNone }
-
-docbookWithOpts :: ToPandoc a => WriterOptions -> a -> String
-docbookWithOpts opts = unpack . purely (writeDocbook4 opts) . toPandoc
-
-{-
-  "my test" =: X =?> Y
-
-is shorthand for
-
-  test docbook "my test" $ X =?> Y
-
-which is in turn shorthand for
-
-  test docbook "my test" (X,Y)
--}
-
-infix 4 =:
-(=:) :: (ToString a, ToPandoc a)
-     => String -> (a, String) -> TestTree
-(=:) = test docbook
-
-lineblock :: Blocks
-lineblock = para ("some text" <> linebreak <>
-                  "and more lines" <> linebreak <>
-                  "and again")
-lineblock_out :: [String]
-lineblock_out = [ "<literallayout>some text"
-                , "and more lines"
-                , "and again</literallayout>"
-                ]
-
-tests :: [TestTree]
-tests = [ testGroup "line blocks"
-          [ "none"       =: para "This is a test"
-                              =?> unlines
-                                    [ "<para>"
-                                    , "  This is a test"
-                                    , "</para>"
-                                    ]
-          , "basic"      =: lineblock
-                              =?> unlines lineblock_out
-          , "blockquote" =: blockQuote lineblock
-                              =?> unlines
-                                    ( [ "<blockquote>" ] ++
-                                      lineblock_out ++
-                                      [ "</blockquote>" ]
-                                    )
-          , "footnote"   =: para ("This is a test" <>
-                                  note lineblock <>
-                                  " of footnotes")
-                              =?> unlines
-                                    ( [ "<para>"
-                                      , "  This is a test<footnote>" ] ++
-                                      lineblock_out ++
-                                      [ "  </footnote> of footnotes"
-                                      , "</para>" ]
-                                    )
-          ]
-        , testGroup "compact lists"
-          [ testGroup "bullet"
-            [ "compact"    =: bulletList [plain "a", plain "b", plain "c"]
-                                =?> unlines
-                                      [ "<itemizedlist spacing=\"compact\">"
-                                      , "  <listitem>"
-                                      , "    <para>"
-                                      , "      a"
-                                      , "    </para>"
-                                      , "  </listitem>"
-                                      , "  <listitem>"
-                                      , "    <para>"
-                                      , "      b"
-                                      , "    </para>"
-                                      , "  </listitem>"
-                                      , "  <listitem>"
-                                      , "    <para>"
-                                      , "      c"
-                                      , "    </para>"
-                                      , "  </listitem>"
-                                      , "</itemizedlist>"
-                                      ]
-            , "loose"      =: bulletList [para "a", para "b", para "c"]
-                                =?> unlines
-                                      [ "<itemizedlist>"
-                                      , "  <listitem>"
-                                      , "    <para>"
-                                      , "      a"
-                                      , "    </para>"
-                                      , "  </listitem>"
-                                      , "  <listitem>"
-                                      , "    <para>"
-                                      , "      b"
-                                      , "    </para>"
-                                      , "  </listitem>"
-                                      , "  <listitem>"
-                                      , "    <para>"
-                                      , "      c"
-                                      , "    </para>"
-                                      , "  </listitem>"
-                                      , "</itemizedlist>"
-                                      ]
-            ]
-          , testGroup "ordered"
-            [ "compact"    =: orderedList [plain "a", plain "b", plain "c"]
-                                =?> unlines
-                                      [ "<orderedlist spacing=\"compact\">"
-                                      , "  <listitem>"
-                                      , "    <para>"
-                                      , "      a"
-                                      , "    </para>"
-                                      , "  </listitem>"
-                                      , "  <listitem>"
-                                      , "    <para>"
-                                      , "      b"
-                                      , "    </para>"
-                                      , "  </listitem>"
-                                      , "  <listitem>"
-                                      , "    <para>"
-                                      , "      c"
-                                      , "    </para>"
-                                      , "  </listitem>"
-                                      , "</orderedlist>"
-                                      ]
-            , "loose"      =: orderedList [para "a", para "b", para "c"]
-                                =?> unlines
-                                      [ "<orderedlist>"
-                                      , "  <listitem>"
-                                      , "    <para>"
-                                      , "      a"
-                                      , "    </para>"
-                                      , "  </listitem>"
-                                      , "  <listitem>"
-                                      , "    <para>"
-                                      , "      b"
-                                      , "    </para>"
-                                      , "  </listitem>"
-                                      , "  <listitem>"
-                                      , "    <para>"
-                                      , "      c"
-                                      , "    </para>"
-                                      , "  </listitem>"
-                                      , "</orderedlist>"
-                                      ]
-            ]
-          , testGroup "definition"
-            [ "compact"    =: definitionList [ ("an", [plain "apple" ])
-                                             , ("a",  [plain "banana"])
-                                             , ("an", [plain "orange"])]
-                                =?> unlines
-                                      [ "<variablelist spacing=\"compact\">"
-                                      , "  <varlistentry>"
-                                      , "    <term>"
-                                      , "      an"
-                                      , "    </term>"
-                                      , "    <listitem>"
-                                      , "      <para>"
-                                      , "        apple"
-                                      , "      </para>"
-                                      , "    </listitem>"
-                                      , "  </varlistentry>"
-                                      , "  <varlistentry>"
-                                      , "    <term>"
-                                      , "      a"
-                                      , "    </term>"
-                                      , "    <listitem>"
-                                      , "      <para>"
-                                      , "        banana"
-                                      , "      </para>"
-                                      , "    </listitem>"
-                                      , "  </varlistentry>"
-                                      , "  <varlistentry>"
-                                      , "    <term>"
-                                      , "      an"
-                                      , "    </term>"
-                                      , "    <listitem>"
-                                      , "      <para>"
-                                      , "        orange"
-                                      , "      </para>"
-                                      , "    </listitem>"
-                                      , "  </varlistentry>"
-                                      , "</variablelist>"
-                                      ]
-            , "loose"      =: definitionList [ ("an", [para "apple" ])
-                                             , ("a",  [para "banana"])
-                                             , ("an", [para "orange"])]
-                                =?> unlines
-                                      [ "<variablelist>"
-                                      , "  <varlistentry>"
-                                      , "    <term>"
-                                      , "      an"
-                                      , "    </term>"
-                                      , "    <listitem>"
-                                      , "      <para>"
-                                      , "        apple"
-                                      , "      </para>"
-                                      , "    </listitem>"
-                                      , "  </varlistentry>"
-                                      , "  <varlistentry>"
-                                      , "    <term>"
-                                      , "      a"
-                                      , "    </term>"
-                                      , "    <listitem>"
-                                      , "      <para>"
-                                      , "        banana"
-                                      , "      </para>"
-                                      , "    </listitem>"
-                                      , "  </varlistentry>"
-                                      , "  <varlistentry>"
-                                      , "    <term>"
-                                      , "      an"
-                                      , "    </term>"
-                                      , "    <listitem>"
-                                      , "      <para>"
-                                      , "        orange"
-                                      , "      </para>"
-                                      , "    </listitem>"
-                                      , "  </varlistentry>"
-                                      , "</variablelist>"
-                                      ]
-            ]
-          ]
-        , testGroup "writer options" $
-          [ testGroup "top-level division" $
-            let
-              headers =  header 1 (text "header1")
-                      <> header 2 (text "header2")
-                      <> header 3 (text "header3")
-
-              docbookTopLevelDiv :: (ToPandoc a)
-                                 => TopLevelDivision -> a -> String
-              docbookTopLevelDiv division =
-                docbookWithOpts def{ writerTopLevelDivision = division }
-            in
-            [ test (docbookTopLevelDiv TopLevelSection) "sections as top-level" $
-              headers =?>
-              unlines [ "<sect1>"
-                      , "  <title>header1</title>"
-                      , "  <sect2>"
-                      , "    <title>header2</title>"
-                      , "    <sect3>"
-                      , "      <title>header3</title>"
-                      , "      <para>"
-                      , "      </para>"
-                      , "    </sect3>"
-                      , "  </sect2>"
-                      , "</sect1>"
-                      ]
-            , test (docbookTopLevelDiv TopLevelChapter) "chapters as top-level" $
-              headers =?>
-              unlines [ "<chapter>"
-                      , "  <title>header1</title>"
-                      , "  <sect1>"
-                      , "    <title>header2</title>"
-                      , "    <sect2>"
-                      , "      <title>header3</title>"
-                      , "      <para>"
-                      , "      </para>"
-                      , "    </sect2>"
-                      , "  </sect1>"
-                      , "</chapter>"
-                      ]
-            , test (docbookTopLevelDiv TopLevelPart) "parts as top-level" $
-              headers =?>
-              unlines [ "<part>"
-                      , "  <title>header1</title>"
-                      , "  <chapter>"
-                      , "    <title>header2</title>"
-                      , "    <sect1>"
-                      , "      <title>header3</title>"
-                      , "      <para>"
-                      , "      </para>"
-                      , "    </sect1>"
-                      , "  </chapter>"
-                      , "</part>"
-                      ]
-            , test (docbookTopLevelDiv TopLevelDefault) "default top-level" $
-              headers =?>
-              unlines [ "<sect1>"
-                      , "  <title>header1</title>"
-                      , "  <sect2>"
-                      , "    <title>header2</title>"
-                      , "    <sect3>"
-                      , "      <title>header3</title>"
-                      , "      <para>"
-                      , "      </para>"
-                      , "    </sect3>"
-                      , "  </sect2>"
-                      , "</sect1>"
-                      ]
-            ]
-          ]
-        ]
diff --git a/test/Tests/Writers/Docx.hs b/test/Tests/Writers/Docx.hs
--- a/test/Tests/Writers/Docx.hs
+++ b/test/Tests/Writers/Docx.hs
@@ -1,161 +1,377 @@
+{-# LANGUAGE OverloadedStrings #-}
 module Tests.Writers.Docx (tests) where
 
-import qualified Data.ByteString as BS
-import System.FilePath ((</>))
-import System.IO.Unsafe (unsafePerformIO)
+import Codec.Archive.Zip (findEntryByPath, fromEntry, toArchive)
+import qualified Data.ByteString.Lazy as BL
+import Data.List (isInfixOf, isPrefixOf)
+import qualified Data.Map as M
+import Data.Text (Text)
+import qualified Data.Text as Text
+import qualified Data.Text.IO as T
 import Test.Tasty
-import Tests.Helpers
-import Text.Pandoc.Class (runIOorExplode, setUserDataDir)
-import Text.Pandoc.Definition
-import Text.Pandoc.Options
-import Text.Pandoc.Readers.Docx
-import Text.Pandoc.Readers.Native
-import qualified Text.Pandoc.UTF8 as UTF8
-import Text.Pandoc.Walk
-import Text.Pandoc.Writers.Docx
-
-type Options = (WriterOptions, ReaderOptions)
-
-compareOutput :: Options
-              -> FilePath
-              -> FilePath
-              -> IO (Pandoc, Pandoc)
-compareOutput (wopts, ropts) nativeFileIn nativeFileOut = do
-  nf <- UTF8.toText <$> BS.readFile nativeFileIn
-  nf' <- UTF8.toText <$> BS.readFile nativeFileOut
-  runIOorExplode $ do
-    setUserDataDir $ Just (".." </> "data")
-    roundtripped <- readNative def nf >>=
-            writeDocx wopts >>= readDocx ropts
-    orig <- readNative def nf'
-    return (walk fixImages roundtripped, walk fixImages orig)
-
--- make all image filenames "image", since otherwise round-trip
--- tests fail because of different behavior of Data.Unique in
--- different ghc versions...
-fixImages :: Inline -> Inline
-fixImages (Image attr alt (_,tit)) = Image attr alt ("image",tit)
-fixImages x                        = x
-
-testCompareWithOptsIO :: Options -> String -> FilePath -> FilePath -> IO TestTree
-testCompareWithOptsIO opts name nativeFileIn nativeFileOut = do
-  (dp, np) <- compareOutput opts nativeFileIn nativeFileOut
-  return $ test id name (dp, np)
-
-testCompareWithOpts :: Options -> String -> FilePath -> FilePath -> TestTree
-testCompareWithOpts opts name nativeFileIn nativeFileOut =
-  unsafePerformIO $ testCompareWithOptsIO opts name nativeFileIn nativeFileOut
-
-roundTripCompareWithOpts :: Options -> String -> FilePath -> TestTree
-roundTripCompareWithOpts opts name nativeFile =
-  testCompareWithOpts opts name nativeFile nativeFile
-
--- testCompare :: String -> FilePath -> FilePath -> TestTree
--- testCompare = testCompareWithOpts def
+import Test.Tasty.HUnit
+import Tests.Writers.OOXML
+import Text.Pandoc
+import Text.XML.Light (QName(QName), findAttr, findElements, parseXMLDoc)
 
-roundTripCompare :: String -> FilePath -> TestTree
-roundTripCompare = roundTripCompareWithOpts def
+-- we add an extra check to make sure that we're not writing in the
+-- toplevel docx directory. We don't want to accidentally overwrite an
+-- Word-generated docx file used to test the reader.
+docxTest :: String -> WriterOptions -> FilePath -> FilePath -> TestTree
+docxTest testName opts nativeFP goldenFP =
+  if "docx/golden/" `isPrefixOf` goldenFP
+  then ooxmlTest writeDocx testName opts nativeFP goldenFP
+  else testCase testName $
+       assertFailure $
+       goldenFP ++ " is not in `test/docx/golden`"
 
 tests :: [TestTree]
 tests = [ testGroup "inlines"
-          [ roundTripCompare
+          [ docxTest
             "font formatting"
-            "docx/inline_formatting_writer.native"
-          , roundTripCompare
-            "font formatting with character styles"
-            "docx/char_styles.native"
-          , roundTripCompare
+            def
+            "docx/inline_formatting.native"
+            "docx/golden/inline_formatting.docx"
+          , docxTest
             "hyperlinks"
-            "docx/links_writer.native"
-          , roundTripCompare
+            def
+            "docx/links.native"
+            "docx/golden/links.docx"
+          , docxTest
             "inline image"
-            "docx/image_no_embed_writer.native"
-          , roundTripCompare
-            "inline image in links"
-            "docx/inline_images_writer.native"
-          , roundTripCompare
+            def{ writerExtensions =
+                   enableExtension Ext_native_numbering (writerExtensions def) }
+            "docx/image_writer_test.native"
+            "docx/golden/image.docx"
+          , docxTest
+            "inline images"
+            def
+            "docx/inline_images_writer_test.native"
+            "docx/golden/inline_images.docx"
+          , docxTest
             "handling unicode input"
+            def
             "docx/unicode.native"
-          , roundTripCompare
-            "literal tabs"
-            "docx/tabs.native"
-          , roundTripCompare
-            "normalizing inlines"
-            "docx/normalize.native"
-          , roundTripCompare
-            "normalizing inlines deep inside blocks"
-            "docx/deep_normalize.native"
-          , roundTripCompare
-            "move trailing spaces outside of formatting"
-            "docx/trailing_spaces_in_formatting.native"
-          , roundTripCompare
-            "inline code (with VerbatimChar style)"
+            "docx/golden/unicode.docx"
+          , docxTest
+            "inline code"
+            def
             "docx/inline_code.native"
-          , roundTripCompare
+            "docx/golden/inline_code.docx"
+          , docxTest
             "inline code in subscript and superscript"
+            def
             "docx/verbatim_subsuper.native"
+            "docx/golden/verbatim_subsuper.docx"
           ]
         , testGroup "blocks"
-          [ roundTripCompare
+          [ docxTest
             "headers"
+            def
             "docx/headers.native"
-          , roundTripCompare
-            "headers already having auto identifiers"
-            "docx/already_auto_ident.native"
-          , roundTripCompare
-            "numbered headers automatically made into list"
-            "docx/numbered_header.native"
-          , roundTripCompare
-            "i18n blocks (headers and blockquotes)"
-            "docx/i18n_blocks.native"
-          -- Continuation does not survive round-trip
-          , roundTripCompare
+            "docx/golden/headers.docx"
+          , docxTest
+            "nested anchor spans in header"
+            def
+            "docx/nested_anchors_in_header.native"
+            "docx/golden/nested_anchors_in_header.docx"
+          , docxTest
             "lists"
-            "docx/lists_writer.native"
-          , roundTripCompare
+            def
+            "docx/lists.native"
+            "docx/golden/lists.docx"
+          , docxTest
+            "lists continuing after interruption"
+            def
+            "docx/lists_continuing.native"
+            "docx/golden/lists_continuing.docx"
+          , docxTest
+            "lists restarting after interruption"
+            def
+            "docx/lists_restarting.native"
+            "docx/golden/lists_restarting.docx"
+          , docxTest
+            "lists with multiple initial list levels"
+            def
+            "docx/lists_multiple_initial.native"
+            "docx/golden/lists_multiple_initial.docx"
+          , docxTest
+            "lists with div bullets"
+            def
+            "docx/lists_div_bullets.native"
+            "docx/golden/lists_div_bullets.docx"
+          , docxTest
             "definition lists"
+            def
             "docx/definition_list.native"
-          , roundTripCompare
-            "custom defined lists in styles"
-            "docx/german_styled_lists.native"
-          , roundTripCompare
+            "docx/golden/definition_list.docx"
+          , docxTest
+            "task lists"
+            def
+            "docx/task_list.native"
+            "docx/golden/task_list.docx"
+          , docxTest
+            "issue 9994"
+            def
+            "docx/lists_9994.native"
+            "docx/golden/lists_9994.docx"
+          , docxTest
             "footnotes and endnotes"
+            def
             "docx/notes.native"
-          , roundTripCompare
-            "blockquotes (parsing indent as blockquote)"
-            "docx/block_quotes_parse_indent.native"
-          , roundTripCompare
-            "hanging indents"
-            "docx/hanging_indent.native"
-          -- tables headers do not survive round-trip, should look into that
-          , roundTripCompare
+            "docx/golden/notes.docx"
+          , docxTest
+            "links in footnotes and endnotes"
+            def
+            "docx/link_in_notes.native"
+            "docx/golden/link_in_notes.docx"
+          , docxTest
+            "blockquotes"
+            def
+            "docx/block_quotes.native"
+            "docx/golden/block_quotes.docx"
+          , docxTest
             "tables"
+            def
             "docx/tables.native"
-          , roundTripCompare
+            "docx/golden/tables.docx"
+          , docxTest
+            "tables without explicit column widths"
+            def
+            "docx/tables-default-widths.native"
+            "docx/golden/tables-default-widths.docx"
+          , docxTest
             "tables with lists in cells"
+            def
             "docx/table_with_list_cell.native"
-          , roundTripCompare
+            "docx/golden/table_with_list_cell.docx"
+          , docxTest
+            "tables with one row"
+            def
+            "docx/table_one_row.native"
+            "docx/golden/table_one_row.docx"
+          , docxTest
+            "tables separated with RawBlock"
+            def
+            "docx/tables_separated_with_rawblock.native"
+            "docx/golden/tables_separated_with_rawblock.docx"
+          , docxTest
             "code block"
+            def
             "docx/codeblock.native"
-          , roundTripCompare
-            "dropcap paragraphs"
-            "docx/drop_cap.native"
+            "docx/golden/codeblock.docx"
+          , docxTest
+            "raw OOXML blocks"
+            def
+            "docx/raw-blocks.native"
+            "docx/golden/raw-blocks.docx"
+          , docxTest
+            "raw bookmark markers"
+            def
+            "docx/raw-bookmarks.native"
+            "docx/golden/raw-bookmarks.docx"
           ]
+        , testGroup "track changes"
+          [ docxTest
+            "insertion"
+            def
+            "docx/track_changes_insertion_all.native"
+            "docx/golden/track_changes_insertion.docx"
+          , docxTest
+            "deletion"
+            def
+            "docx/track_changes_deletion_all.native"
+            "docx/golden/track_changes_deletion.docx"
+          , docxTest
+            "move text"
+            def
+            "docx/track_changes_move_all.native"
+            "docx/golden/track_changes_move.docx"
+          , docxTest
+            "comments"
+            def
+            "docx/comments.native"
+            "docx/golden/comments.docx"
+          , docxTest
+            "scrubbed metadata"
+            def
+            "docx/track_changes_scrubbed_metadata.native"
+            "docx/golden/track_changes_scrubbed_metadata.docx"
+          ]
+        , testGroup "custom styles"
+          [ docxTest "custom styles without reference.docx"
+            def
+            "docx/custom_style.native"
+            "docx/golden/custom_style_no_reference.docx"
+          , docxTest "custom styles with reference.docx"
+            def{writerReferenceDoc = Just "docx/custom-style-reference.docx"}
+            "docx/custom_style.native"
+            "docx/golden/custom_style_reference.docx"
+          , docxTest "suppress custom style for headers and blockquotes"
+            def
+            "docx/custom-style-preserve.native"
+            "docx/golden/custom_style_preserve.docx"
+          ]
         , testGroup "metadata"
-          [ roundTripCompareWithOpts (def,def{readerStandalone=True})
-            "metadata fields"
-            "docx/metadata.native"
-          , roundTripCompareWithOpts (def,def{readerStandalone=True})
-            "stop recording metadata with normal text"
-            "docx/metadata_after_normal.native"
+          [ docxTest "document properties (core, custom)"
+            def
+            "docx/document-properties.native"
+            "docx/golden/document-properties.docx"
+          , docxTest "document properties (short description)"
+            def
+            "docx/document-properties-short-desc.native"
+            "docx/golden/document-properties-short-desc.docx"
           ]
-        , testGroup "customized styles"
-          [ testCompareWithOpts
-            ( def{writerReferenceDoc=Just "docx/custom-style-reference.docx"}
-            , def)
-            "simple customized blocks and inlines"
-            "docx/custom-style-roundtrip-start.native"
-            "docx/custom-style-roundtrip-end.native"
+        , testGroup "top-level-division"
+          -- Helper to count occurrences of a substring
+          -- Note: counts by splitting on "<w:sectPr" which marks section properties
+          [ testCase "no section break before first chapter (#10578)" $ do
+              -- With --top-level-division=chapter, there should be no section
+              -- break before the first chapter (to avoid blank first page)
+              let opts = def{ writerTopLevelDivision = TopLevelChapter }
+              bs <- runIOorExplode $ do
+                setVerbosity ERROR
+                let doc = Pandoc mempty
+                          [ Header 1 ("ch1", [], []) [Str "Chapter", Space, Str "1"]
+                          , Para [Str "First", Space, Str "chapter."]
+                          ]
+                writeDocx opts doc
+              let archive = toArchive bs
+              entry <- case findEntryByPath "word/document.xml" archive of
+                Nothing -> assertFailure "Missing word/document.xml in output docx"
+                Just e -> return e
+              let docXml = show (fromEntry entry)
+              -- Count occurrences of "<w:sectPr" (opening tag for section properties)
+              let countOccurrences needle haystack =
+                    length (filter (needle `isPrefixOf`) (tails haystack))
+                    where tails [] = []; tails s@(_:xs) = s : tails xs
+              let sectPrCount = countOccurrences "<w:sectPr" docXml
+              -- Should have exactly 1 sectPr (the final document section),
+              -- not 2 (which would mean one before the chapter heading)
+              assertBool ("Expected 1 sectPr (final section only), found " ++ show sectPrCount)
+                (sectPrCount == 1)
+          , testCase "section breaks between chapters (#11482)" $ do
+              -- With --top-level-division=chapter, there should be section
+              -- breaks between chapters (but not before the first one)
+              let opts = def{ writerTopLevelDivision = TopLevelChapter }
+              bs <- runIOorExplode $ do
+                setVerbosity ERROR
+                let doc = Pandoc mempty
+                          [ Header 1 ("ch1", [], []) [Str "Chapter", Space, Str "1"]
+                          , Para [Str "First", Space, Str "chapter."]
+                          , Header 1 ("ch2", [], []) [Str "Chapter", Space, Str "2"]
+                          , Para [Str "Second", Space, Str "chapter."]
+                          , Header 1 ("ch3", [], []) [Str "Chapter", Space, Str "3"]
+                          , Para [Str "Third", Space, Str "chapter."]
+                          ]
+                writeDocx opts doc
+              let archive = toArchive bs
+              entry <- case findEntryByPath "word/document.xml" archive of
+                Nothing -> assertFailure "Missing word/document.xml in output docx"
+                Just e -> return e
+              let docXml = show (fromEntry entry)
+              -- Count occurrences of "<w:sectPr" (opening tag for section properties)
+              let countOccurrences needle haystack =
+                    length (filter (needle `isPrefixOf`) (tails haystack))
+                    where tails [] = []; tails s@(_:xs) = s : tails xs
+              let sectPrCount = countOccurrences "<w:sectPr" docXml
+              -- Should have 3 sectPr elements:
+              -- - 1 before chapter 2
+              -- - 1 before chapter 3
+              -- - 1 final document section
+              -- (No section break before chapter 1)
+              assertBool ("Expected 3 sectPr elements, found " ++ show sectPrCount)
+                (sectPrCount == 3)
           ]
-
+        , testGroup "reference docx"
+          [ testCase "no media directory override in content types" $ do
+              let opts = def{ writerReferenceDoc = Just "docx/inline_images.docx" }
+              txt <- T.readFile "docx/inline_formatting.native"
+              bs <- runIOorExplode $ do
+                mblang <- toLang (Just (Text.pack "en-US") :: Maybe Text)
+                maybe (return ()) setTranslations mblang
+                setVerbosity ERROR
+                readNative def txt >>= writeDocx opts
+              let archive = toArchive bs
+              entry <- case findEntryByPath "[Content_Types].xml" archive of
+                Nothing -> assertFailure "Missing [Content_Types].xml in output docx"
+                Just e -> return e
+              doc <- case parseXMLDoc (fromEntry entry) of
+                Nothing -> assertFailure "Failed to parse [Content_Types].xml"
+                Just d -> return d
+              let partNameAttr = QName "PartName" Nothing Nothing
+              let overrideName = QName "Override" Nothing Nothing
+              let overrides = findElements overrideName doc
+              let hasBadOverride =
+                    any (\el -> findAttr partNameAttr el == Just "/word/media/")
+                        overrides
+              assertBool "Found invalid /word/media/ Override in [Content_Types].xml"
+                (not hasBadOverride)
+          , testCase "language from reference docx is preserved" $ do
+              -- First, verify that the german-reference.docx actually has de-DE
+              refBs <- BL.readFile "docx/german-reference.docx"
+              let refArchive = toArchive refBs
+              refEntry <- case findEntryByPath "word/styles.xml" refArchive of
+                Nothing -> assertFailure "Missing word/styles.xml in german-reference.docx"
+                Just e -> return e
+              let refStylesXml = show (fromEntry refEntry)
+              let getLangLines = filter ("w:lang" `isInfixOf`) . lines
+              assertBool ("german-reference.docx w:lang line: " ++
+                  unlines (getLangLines refStylesXml))
+                (any ("de-DE" `isInfixOf`) (getLangLines refStylesXml))
+              -- Now test that using this reference preserves the language
+              let opts = def{ writerReferenceDoc = Just "docx/german-reference.docx" }
+              txt <- T.readFile "docx/inline_formatting.native"
+              bs <- runIOorExplode $ do
+                setVerbosity ERROR
+                readNative def txt >>= writeDocx opts
+              let archive = toArchive bs
+              entry <- case findEntryByPath "word/styles.xml" archive of
+                Nothing -> assertFailure "Missing word/styles.xml in output docx"
+                Just e -> return e
+              let stylesXml = show (fromEntry entry)
+              -- Find the w:lang line for debugging
+              -- Check that the styles.xml contains the German language
+              assertBool ("Language from reference docx not preserved. w:lang lines: " ++ unlines (getLangLines stylesXml))
+                (any ("de-DE" `isInfixOf`) (getLangLines stylesXml))
+          , testCase "language from metadata overrides reference docx" $ do
+              -- Use a reference docx with German language, but specify French in metadata
+              let opts = def{ writerReferenceDoc = Just "docx/german-reference.docx" }
+              bs <- runIOorExplode $ do
+                setVerbosity ERROR
+                -- Create a document with French language metadata
+                let doc = Pandoc (Meta $ M.fromList [("lang", MetaString "fr-FR")])
+                                 [Para [Str "Test"]]
+                writeDocx opts doc
+              let archive = toArchive bs
+              entry <- case findEntryByPath "word/styles.xml" archive of
+                Nothing -> assertFailure "Missing word/styles.xml in output docx"
+                Just e -> return e
+              let stylesXml = show (fromEntry entry)
+              -- Check that the styles.xml contains the French language (not German)
+              let getLangLines = filter ("w:lang" `isInfixOf`) . lines
+              assertBool "Language from metadata did not override reference docx (expected fr-FR)"
+                (any ("fr-FR" `isInfixOf`) (getLangLines stylesXml))
+          ]
+        , testGroup "paragraph styles"
+          [ testCase "FirstParagraph after heading with footnote (#11573)" $ do
+              let opts = def
+              bs <- runIOorExplode $ do
+                setVerbosity ERROR
+                let doc = Pandoc mempty
+                          [ Header 3 ("heading-with-note", [], [])
+                              [Note [Para [Str "note"]], Str "Heading"]
+                          , Para [Str "Para", Space, Str "after."]
+                          ]
+                writeDocx opts doc
+              let archive = toArchive bs
+              entry <- case findEntryByPath "word/document.xml" archive of
+                Nothing -> assertFailure "Missing word/document.xml in output docx"
+                Just e -> return e
+              let docXml = show (fromEntry entry)
+              assertBool
+                ("Expected FirstParagraph style after heading with footnote, got: "
+                  ++ docXml)
+                ("FirstParagraph" `isInfixOf` docXml)
+          ]
         ]
diff --git a/test/Tests/Writers/FB2.hs b/test/Tests/Writers/FB2.hs
--- a/test/Tests/Writers/FB2.hs
+++ b/test/Tests/Writers/FB2.hs
@@ -2,6 +2,7 @@
 module Tests.Writers.FB2 (tests) where
 
 import Test.Tasty
+import Test.Tasty.HUnit (HasCallStack)
 import Tests.Helpers
 import Text.Pandoc
 import Text.Pandoc.Arbitrary ()
@@ -12,7 +13,7 @@
         "<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>" ++ x ++ "</section></body></FictionBook>"
 
 infix 4 =:
-(=:) :: (ToString a, ToPandoc a)
+(=:) :: (ToString a, ToPandoc a, HasCallStack)
      => String -> (a, String) -> TestTree
 (=:) = test (purely (writeFB2 def) . toPandoc)
 
@@ -23,8 +24,8 @@
           ]
         , testGroup "inlines"
           [
-            "Emphasis"      =:  emph ("emphasized")
-                            =?> fb2 "<emphasis>emphasized</emphasis>"
+            "Emphasis"      =:  para (emph "emphasized")
+                            =?> fb2 "<p><emphasis>emphasized</emphasis></p>"
           ]
         , "bullet list" =: bulletList [ plain $ text "first"
                                       , plain $ text "second"
diff --git a/test/Tests/Writers/HTML.hs b/test/Tests/Writers/HTML.hs
--- a/test/Tests/Writers/HTML.hs
+++ b/test/Tests/Writers/HTML.hs
@@ -2,15 +2,25 @@
 module Tests.Writers.HTML (tests) where
 
 import Data.Text (unpack)
+import qualified Data.Text as T
 import Test.Tasty
+import Test.Tasty.HUnit (HasCallStack)
 import Tests.Helpers
 import Text.Pandoc
 import Text.Pandoc.Arbitrary ()
 import Text.Pandoc.Builder
 
+htmlWithOpts :: (ToPandoc a) => WriterOptions -> a -> String
+htmlWithOpts opts = unpack . purely (writeHtml4String opts{ writerWrapText = WrapNone }) . toPandoc
+
 html :: (ToPandoc a) => a -> String
-html = unpack . purely (writeHtml4String def{ writerWrapText = WrapNone }) . toPandoc
+html = htmlWithOpts def
 
+htmlQTags :: (ToPandoc a) => a -> String
+htmlQTags = unpack
+  . purely (writeHtml4String def{ writerWrapText = WrapNone, writerHtmlQTags = True })
+  . toPandoc
+
 {-
   "my test" =: X =?> Y
 
@@ -24,21 +34,182 @@
 -}
 
 infix 4 =:
-(=:) :: (ToString a, ToPandoc a)
+(=:) :: (ToString a, ToPandoc a, HasCallStack)
      => String -> (a, String) -> TestTree
 (=:) = test html
 
+noteTestDoc :: Blocks
+noteTestDoc =
+  header 1 "Page title" <>
+  header 2 "First section" <>
+  para ("This is a footnote." <>
+        note (para "Down here.") <>
+        " And this is a " <>
+        link "https://www.google.com" "" "link" <>
+        ".") <>
+  blockQuote (para ("A note inside a block quote." <>
+                    note (para "The second note.")) <>
+              para "A second paragraph.") <>
+  header 2 "Second section" <>
+  para "Some more text."
+
 tests :: [TestTree]
-tests = [ testGroup "inline code"
-          [ "basic" =: code "@&" =?> "<code>@&amp;</code>"
-          , "haskell" =: codeWith ("",["haskell"],[]) ">>="
-            =?> "<code class=\"sourceCode haskell\"><span class=\"fu\">&gt;&gt;=</span></code>"
-          , "nolanguage" =: codeWith ("",["nolanguage"],[]) ">>="
-            =?> "<code class=\"nolanguage\">&gt;&gt;=</code>"
+tests =
+  [ testGroup "inline code"
+    [ "basic" =: code "@&" =?> "<code>@&amp;</code>"
+    , "haskell" =: codeWith ("",["haskell"],[]) ">>="
+      =?> "<code class=\"sourceCode haskell\"><span class=\"op\">&gt;&gt;=</span></code>"
+    , "nolanguage" =: codeWith ("",["nolanguage"],[]) ">>="
+      =?> "<code class=\"nolanguage\">&gt;&gt;=</code>"
+    ]
+  , testGroup "images"
+    [ "alt with formatting" =:
+      image "/url" "title" ("my " <> emph "image")
+      =?> "<img src=\"/url\" title=\"title\" alt=\"my image\" />"
+    ]
+  , testGroup "blocks"
+    [ "definition list with empty <dt>" =:
+      definitionList [(mempty, [para $ text "foo bar"])]
+      =?> "<dl>\n<dt></dt>\n<dd>\n<p>foo bar</p>\n</dd>\n</dl>"
+    , "heading with disallowed attributes" =:
+      headerWith ("", [], [("invalid","1"), ("lang", "en")]) 1 "test"
+      =?>
+      "<h1 lang=\"en\">test</h1>"
+    ]
+  , testGroup "quotes"
+    [ "quote with cite attribute (without q-tags)" =:
+      doubleQuoted (spanWith ("", [], [("cite", "http://example.org")]) (str "examples"))
+      =?> "“<span cite=\"http://example.org\">examples</span>”"
+    , tQ "quote with cite attribute (with q-tags)" $
+      doubleQuoted (spanWith ("", [], [("cite", "http://example.org")]) (str "examples"))
+      =?> "<q cite=\"http://example.org\">examples</q>"
+    ]
+  , testGroup "code"
+    [ "code should be rendered correctly" =:
+      plain (codeWith ("",[],[]) "Answer is 42") =?>
+      "<code>Answer is 42</code>"
+    ]
+  , testGroup "sample"
+    [ "sample should be rendered correctly" =:
+      plain (codeWith ("",["sample"],[]) "Answer is 42") =?>
+      "<samp>Answer is 42</samp>"
+    ]
+  , testGroup "variable"
+    [ "variable should be rendered correctly" =:
+      plain (codeWith ("",["variable"],[]) "result") =?>
+      "<var>result</var>"
+    ]
+  , testGroup "sample with style"
+    [ "samp should wrap highlighted code" =:
+      codeWith ("",["sample","haskell"],[]) ">>="
+      =?> ("<samp><code class=\"sourceCode haskell sample\">" ++
+          "<span class=\"op\">&gt;&gt;=</span></code></samp>")
+    ]
+  , testGroup "variable with style"
+    [ "var should wrap highlighted code" =:
+      codeWith ("",["haskell","variable"],[]) ">>="
+      =?> ("<var><code class=\"sourceCode haskell variable\">" ++
+          "<span class=\"op\">&gt;&gt;=</span></code></var>")
+    ]
+  , testGroup "footnotes"
+      [ test (htmlWithOpts def{writerReferenceLocation=EndOfDocument})
+        "at the end of a document" $
+        noteTestDoc =?>
+        T.unlines
+          [ "<h1>Page title</h1>"
+          , "<h2>First section</h2>"
+          , "<p>This is a footnote.<a href=\"#fn1\" class=\"footnote-ref\" id=\"fnref1\"><sup>1</sup></a> And this is a <a href=\"https://www.google.com\">link</a>.</p>"
+          , "<blockquote>"
+          , "<p>A note inside a block quote.<a href=\"#fn2\" class=\"footnote-ref\" id=\"fnref2\"><sup>2</sup></a></p>"
+          , "<p>A second paragraph.</p>"
+          , "</blockquote>"
+          , "<h2>Second section</h2>"
+          , "<p>Some more text.</p>"
+          , "<div class=\"footnotes footnotes-end-of-document\">"
+          , "<hr />"
+          , "<ol>"
+          , "<li id=\"fn1\"><p>Down here.<a href=\"#fnref1\" class=\"footnote-back\">↩︎</a></p></li>"
+          , "<li id=\"fn2\"><p>The second note.<a href=\"#fnref2\" class=\"footnote-back\">↩︎</a></p></li>"
+          , "</ol>"
+          , "</div>"
           ]
-        , testGroup "images"
-          [ "alt with formatting" =:
-            image "/url" "title" ("my " <> emph "image")
-            =?> "<img src=\"/url\" title=\"title\" alt=\"my image\" />"
+      , test (htmlWithOpts def{writerReferenceLocation=EndOfBlock})
+        "at the end of a block" $
+        noteTestDoc =?>
+        T.unlines
+          [ "<h1>Page title</h1>"
+          , "<h2>First section</h2>"
+          , "<p>This is a footnote.<a href=\"#fn1\" class=\"footnote-ref\" id=\"fnref1\"><sup>1</sup></a> And this is a <a href=\"https://www.google.com\">link</a>.</p>"
+          , "<div class=\"footnotes footnotes-end-of-block\">"
+          , "<ol>"
+          , "<li id=\"fn1\"><p>Down here.<a href=\"#fnref1\" class=\"footnote-back\">↩︎</a></p></li>"
+          , "</ol>"
+          , "</div>"
+          , "<blockquote>"
+          , "<p>A note inside a block quote.<a href=\"#fn2\" class=\"footnote-ref\" id=\"fnref2\"><sup>2</sup></a></p>"
+          , "<p>A second paragraph.</p>"
+          , "</blockquote>"
+          , "<div class=\"footnotes footnotes-end-of-block\">"
+          , "<ol start=\"2\">"
+          , "<li id=\"fn2\"><p>The second note.<a href=\"#fnref2\" class=\"footnote-back\">↩︎</a></p></li>"
+          , "</ol>"
+          , "</div>"
+          , "<h2>Second section</h2>"
+          , "<p>Some more text.</p>"
           ]
-        ]
+      , test (htmlWithOpts def{writerReferenceLocation=EndOfSection})
+        "at the end of a section" $
+        noteTestDoc =?>
+        T.unlines
+          [ "<h1>Page title</h1>"
+          , "<h2>First section</h2>"
+          , "<p>This is a footnote.<a href=\"#fn1\" class=\"footnote-ref\" id=\"fnref1\"><sup>1</sup></a> And this is a <a href=\"https://www.google.com\">link</a>.</p>"
+          , "<blockquote>"
+          , "<p>A note inside a block quote.<a href=\"#fn2\" class=\"footnote-ref\" id=\"fnref2\"><sup>2</sup></a></p>"
+          , "<p>A second paragraph.</p>"
+          , "</blockquote>"
+          , "<div class=\"footnotes footnotes-end-of-section\">"
+          , "<hr />"
+          , "<ol>"
+          , "<li id=\"fn1\"><p>Down here.<a href=\"#fnref1\" class=\"footnote-back\">↩︎</a></p></li>"
+          , "<li id=\"fn2\"><p>The second note.<a href=\"#fnref2\" class=\"footnote-back\">↩︎</a></p></li>"
+          , "</ol>"
+          , "</div>"
+          , "<h2>Second section</h2>"
+          , "<p>Some more text.</p>"
+          ]
+      , test (htmlWithOpts def{writerReferenceLocation=EndOfSection, writerSectionDivs=True})
+        "at the end of a section, with section divs" $
+        noteTestDoc =?>
+        -- Footnotes are rendered _after_ their section (in this case after the level2 section
+        -- that contains it).
+        T.unlines
+          [ "<div class=\"section level1\">"
+          , "<h1>Page title</h1>"
+          , "<div class=\"section level2\">"
+          , "<h2>First section</h2>"
+          , "<p>This is a footnote.<a href=\"#fn1\" class=\"footnote-ref\" id=\"fnref1\"><sup>1</sup></a> And this is a <a href=\"https://www.google.com\">link</a>.</p>"
+          , "<blockquote>"
+          , "<p>A note inside a block quote.<a href=\"#fn2\" class=\"footnote-ref\" id=\"fnref2\"><sup>2</sup></a></p>"
+          , "<p>A second paragraph.</p>"
+          , "</blockquote>"
+          , "<div class=\"footnotes footnotes-end-of-section\">"
+          , "<hr />"
+          , "<ol>"
+          , "<li id=\"fn1\"><p>Down here.<a href=\"#fnref1\" class=\"footnote-back\">↩︎</a></p></li>"
+          , "<li id=\"fn2\"><p>The second note.<a href=\"#fnref2\" class=\"footnote-back\">↩︎</a></p></li>"
+          , "</ol>"
+          , "</div>"
+          , "</div>"
+          , "<div class=\"section level2\">"
+          , "<h2>Second section</h2>"
+          , "<p>Some more text.</p>"
+          , "</div>"
+          , "</div>"
+          ]
+      ]
+  ]
+  where
+    tQ :: (ToString a, ToPandoc a)
+         => String -> (a, String) -> TestTree
+    tQ = test htmlQTags
diff --git a/test/Tests/Writers/JATS.hs b/test/Tests/Writers/JATS.hs
--- a/test/Tests/Writers/JATS.hs
+++ b/test/Tests/Writers/JATS.hs
@@ -1,16 +1,24 @@
 {-# LANGUAGE OverloadedStrings #-}
 module Tests.Writers.JATS (tests) where
 
-import Data.Text (unpack)
+import Data.Text (Text)
 import Test.Tasty
+import Test.Tasty.HUnit (HasCallStack)
 import Tests.Helpers
 import Text.Pandoc
 import Text.Pandoc.Arbitrary ()
 import Text.Pandoc.Builder
+import qualified Data.Text as T
 
-jats :: (ToPandoc a) => a -> String
-jats = unpack . purely (writeJATS def{ writerWrapText = WrapNone }) . toPandoc
+jats :: (ToPandoc a) => a -> Text
+jats = purely (writeJatsArchiving def{ writerWrapText = WrapNone })
+     . toPandoc
 
+jatsArticleAuthoring :: (ToPandoc a) => a -> Text
+jatsArticleAuthoring =
+    purely (writeJatsArticleAuthoring def{ writerWrapText = WrapNone })
+  . toPandoc
+
 {-
   "my test" =: X =?> Y
 
@@ -24,101 +32,153 @@
 -}
 
 infix 4 =:
-(=:) :: (ToString a, ToPandoc a)
-     => String -> (a, String) -> TestTree
+(=:) :: (ToString a, ToPandoc a, HasCallStack)
+     => String -> (a, Text) -> TestTree
 (=:) = test jats
 
 tests :: [TestTree]
-tests = [ testGroup "inline code"
-          [ "basic" =: code "@&" =?> "<p>\n  <monospace>@&amp;</monospace>\n</p>"
-          , "lang" =: codeWith ("", ["c"], []) "@&" =?> "<p>\n  <code language=\"c\">@&amp;</code>\n</p>"
-          ]
-        , testGroup "block code"
-          [ "basic" =: codeBlock "@&" =?> "<preformat>@&amp;</preformat>"
-          , "lang" =: codeBlockWith ("", ["c"], []) "@&" =?> "<code language=\"c\">@&amp;</code>"
-          ]
-        , testGroup "images"
-          [ "basic" =:
-            image "/url" "title" mempty
-            =?> "<graphic mimetype=\"image\" mime-subtype=\"\" xlink:href=\"/url\" xlink:title=\"title\" />"
-          ]
-        , testGroup "inlines"
-          [ "Emphasis" =: emph "emphasized"
-            =?> "<p>\n  <italic>emphasized</italic>\n</p>"
-          ]
-        , "bullet list" =: bulletList [ plain $ text "first"
-                                      , plain $ text "second"
-                                      , plain $ text "third"
-                                      ]
-            =?> "<list list-type=\"bullet\">\n\
-                \  <list-item>\n\
-                \    <p>\n\
-                \      first\n\
-                \    </p>\n\
-                \  </list-item>\n\
-                \  <list-item>\n\
-                \    <p>\n\
-                \      second\n\
-                \    </p>\n\
-                \  </list-item>\n\
-                \  <list-item>\n\
-                \    <p>\n\
-                \      third\n\
-                \    </p>\n\
-                \  </list-item>\n\
-                \</list>"
-        , testGroup "definition lists"
-          [ "with internal link" =: definitionList [(link "#go" "" (str "testing"),
-             [plain (text "hi there")])] =?>
-            "<def-list>\n\
-            \  <def-item>\n\
-            \    <term>\n\
-            \      <xref alt=\"testing\" rid=\"go\">testing</xref>\n\
-            \    </term>\n\
-            \    <def>\n\
-            \      <p>\n\
-            \        hi there\n\
-            \      </p>\n\
-            \    </def>\n\
-            \  </def-item>\n\
-            \</def-list>"
-          ]
-        , testGroup "math"
-          [ "escape |" =: para (math "\\sigma|_{\\{x\\}}") =?>
-            "<p>\n\
-            \  <inline-formula><alternatives>\n\
-            \  <tex-math><![CDATA[\\sigma|_{\\{x\\}}]]></tex-math>\n\
-            \  <mml:math display=\"inline\" xmlns:mml=\"http://www.w3.org/1998/Math/MathML\"><mml:mrow><mml:mi>σ</mml:mi><mml:msub><mml:mo stretchy=\"false\" form=\"prefix\">|</mml:mo><mml:mrow><mml:mo stretchy=\"false\" form=\"prefix\">{</mml:mo><mml:mi>x</mml:mi><mml:mo stretchy=\"false\" form=\"postfix\">}</mml:mo></mml:mrow></mml:msub></mml:mrow></mml:math></alternatives></inline-formula>\n\
-            \</p>"
-          ]
-        , testGroup "headers"
-          [ "unnumbered header" =:
-            headerWith ("foo",["unnumbered"],[]) 1
-              (text "Header 1" <> note (plain $ text "note")) =?>
-            "<sec id=\"foo\">\n\
-            \  <title>Header 1<fn>\n\
-            \    <p>\n\
-            \      note\n\
-            \    </p>\n\
-            \  </fn></title>\n\
-            \</sec>"
-          , "unnumbered sub header" =:
-            headerWith ("foo",["unnumbered"],[]) 1
-              (text "Header")
-            <> headerWith ("foo",["unnumbered"],[]) 2
-              (text "Sub-Header") =?>
-            "<sec id=\"foo\">\n\
-            \  <title>Header</title>\n\
-            \  <sec id=\"foo\">\n\
-            \    <title>Sub-Header</title>\n\
-            \  </sec>\n\
-            \</sec>"
-          , "containing image" =:
-            header 1 (image "imgs/foo.jpg" "" (text "Alt text")) =?>
-            "<sec>\n\
-            \  <title><inline-graphic mimetype=\"image\" mime-subtype=\"jpeg\" xlink:href=\"imgs/foo.jpg\" /></title>\n\
-            \</sec>"
-          ]
+tests =
+  [ testGroup "inline code"
+    [ "basic" =: code "@&" =?> "<p><monospace>@&amp;</monospace></p>"
+    ]
+  , testGroup "block code"
+    [ "basic" =: codeBlock "@&" =?> "<preformat>@&amp;</preformat>"
+    , "lang" =: codeBlockWith ("", ["c"], []) "@&" =?> "<code language=\"c\">@&amp;</code>"
+    ]
+  , testGroup "images"
+    [ "basic" =:
+      image "/url" "title" mempty
+      =?> "<graphic mimetype=\"image\" mime-subtype=\"\" xlink:href=\"/url\" xlink:title=\"title\" />"
+    ]
+  , testGroup "inlines"
+    [ "Emphasis" =: emph "emphasized"
+      =?> "<p><italic>emphasized</italic></p>"
+
+    , test jatsArticleAuthoring "footnote in articleauthoring tag set"
+      ("test" <> note (para "footnote") =?>
+        unlines [ "<p>test<fn>"
+                , "  <p>footnote</p>"
+                , "</fn></p>"
+                ])
+    ]
+  , testGroup "bullet list"
+    [ "plain items" =: bulletList [ plain $ text "first"
+                                  , plain $ text "second"
+                                  , plain $ text "third"
+                                  ]
+      =?> "<list list-type=\"bullet\">\n\
+          \  <list-item>\n\
+          \    <p>first</p>\n\
+          \  </list-item>\n\
+          \  <list-item>\n\
+          \    <p>second</p>\n\
+          \  </list-item>\n\
+          \  <list-item>\n\
+          \    <p>third</p>\n\
+          \  </list-item>\n\
+          \</list>"
+
+    , "item with implicit figure" =:
+      bulletList [ simpleFigure (text "caption") "a.png" "" ] =?>
+      T.unlines
+        [ "<list list-type=\"bullet\">"
+        , "  <list-item>"
+        , "    <p specific-use=\"wrapper\">"
+        , "      <fig>"
+        , "        <caption><p>caption</p></caption>"
+        , "        <graphic mimetype=\"image\" mime-subtype=\"png\"" <>
+          " xlink:href=\"a.png\" />"
+        , "      </fig>"
+        , "    </p>"
+        , "  </list-item>"
+        , "</list>"
         ]
+    ]
+  , testGroup "definition lists"
+    [ "with internal link" =: definitionList [(link "#go" "" (str "testing"),
+                                               [plain (text "hi there")])] =?>
+      "<def-list>\n\
+      \  <def-item>\n\
+      \    <term><xref alt=\"testing\" rid=\"go\">testing</xref></term>\n\
+      \    <def>\n\
+      \      <p>hi there</p>\n\
+      \    </def>\n\
+      \  </def-item>\n\
+      \</def-list>"
+    ]
+  , testGroup "math"
+    [ "escape |" =: para (math "\\sigma|_{\\{x\\}}") =?>
+      "<p><inline-formula><alternatives>\n\
+      \<tex-math><![CDATA[\\sigma|_{\\{x\\}}]]></tex-math>\n\
+      \<mml:math display=\"inline\" xmlns:mml=\"http://www.w3.org/1998/Math/MathML\"><mml:mrow><mml:mi>σ</mml:mi><mml:msub><mml:mo stretchy=\"false\" form=\"prefix\">|</mml:mo><mml:mrow><mml:mo stretchy=\"false\" form=\"prefix\">{</mml:mo><mml:mi>x</mml:mi><mml:mo stretchy=\"false\" form=\"postfix\">}</mml:mo></mml:mrow></mml:msub></mml:mrow></mml:math></alternatives></inline-formula></p>"
+    ]
+  , testGroup "headers"
+    [ "unnumbered header" =:
+      headerWith ("foo",["unnumbered"],[]) 1
+      (text "Header 1" <> note (plain $ text "note")) =?>
+      "<sec id=\"foo\">\n\
+      \  <title>Header 1<xref ref-type=\"fn\" rid=\"fn1\">1</xref></title>\n\
+      \</sec>"
+    , "unnumbered sub header" =:
+      headerWith ("foo",["unnumbered"],[]) 1
+      (text "Header")
+      <> headerWith ("foo",["unnumbered"],[]) 2
+      (text "Sub-Header") =?>
+      "<sec id=\"foo\">\n\
+      \  <title>Header</title>\n\
+      \  <sec id=\"foo\">\n\
+      \    <title>Sub-Header</title>\n\
+      \  </sec>\n\
+      \</sec>"
+    , "containing image" =:
+      header 1 (image "imgs/foo.jpg" "" (text "Alt text")) =?>
+      "<sec>\n\
+      \  <title><inline-graphic mimetype=\"image\" mime-subtype=\"jpeg\" xlink:href=\"imgs/foo.jpg\">\n\
+      \    <alt-text>Alt text</alt-text>\n\
+      \  </inline-graphic></title>\n\
+      \</sec>"
+    ]
 
+  , testGroup "ids"
+    [ "non-ASCII in header ID" =:
+      headerWith ("smørbrød",[],[]) 1 (text "smørbrød") =?>
+      T.unlines [ "<sec id=\"smørbrød\">"
+                , "  <title>smørbrød</title>"
+                , "</sec>"
+                ]
 
+    , "disallowed symbol in header id" =:
+      headerWith ("i/o",[],[]) 1 (text "I/O") =?>
+      T.unlines [ "<sec id=\"iU002Fo\">"
+                , "  <title>I/O</title>"
+                , "</sec>"
+                ]
+
+    , "disallowed symbols in internal link target" =:
+      link "#foo:bar" "" "baz" =?>
+      "<p><xref alt=\"baz\" rid=\"fooU003Abar\">baz</xref></p>"
+
+    , "code id starting with a number" =:
+      codeWith ("7y",[],[]) "print 5" =?>
+      "<p><monospace id=\"U0037y\">print 5</monospace></p>"
+    ]
+
+  , testGroup "spans"
+    [ "unwrapped if no attributes given" =:
+      spanWith nullAttr "text in span" =?>
+      "<p>text in span</p>"
+
+    , "converted to named-content element if class given" =:
+      spanWith ("a", ["genus-species"], [("alt", "aa")]) "C. elegans" =?>
+      ("<p><named-content id=\"a\" alt=\"aa\" content-type=\"genus-species\">"
+       <> "C. elegans</named-content></p>")
+
+    , "unwrapped if styled-content element would have no attributes" =:
+      spanWith ("", [], [("hidden", "true")]) "text in span" =?>
+      "<p>text in span</p>"
+
+    , "use content-type attribute if present" =:
+      spanWith ("", [], [("content-type", "species")]) "E. coli" =?>
+      "<p><named-content content-type=\"species\">E. coli</named-content></p>"
+    ]
+  ]
diff --git a/test/Tests/Writers/Jira.hs b/test/Tests/Writers/Jira.hs
new file mode 100644
--- /dev/null
+++ b/test/Tests/Writers/Jira.hs
@@ -0,0 +1,124 @@
+{-# LANGUAGE OverloadedStrings #-}
+module Tests.Writers.Jira (tests) where
+
+import Data.Text (unpack)
+import Test.Tasty
+import Test.Tasty.HUnit (HasCallStack)
+import Tests.Helpers
+import Text.Pandoc
+import Text.Pandoc.Arbitrary ()
+import Text.Pandoc.Builder
+
+jira :: (ToPandoc a) => a -> String
+jira = unpack . purely (writeJira def) . toPandoc
+
+infix 4 =:
+(=:) :: (ToString a, ToPandoc a, HasCallStack)
+     => String -> (a, String) -> TestTree
+(=:) = test jira
+
+tests :: [TestTree]
+tests =
+  [ testGroup "inlines"
+    [ "underlined text" =:
+      underline "underlined text" =?>
+      "+underlined text+"
+
+    , "image with attributes" =:
+      imageWith ("", [], [("align", "right"), ("height", "50")])
+                "image.png" "" mempty =?>
+      "!image.png|align=right, height=50!"
+
+    , testGroup "links"
+      [ "external link" =:
+        link "https://example.com/test.php" "" "test" =?>
+        "[test|https://example.com/test.php]"
+
+      , "external link without description" =:
+        link "https://example.com/tmp.js" "" "https://example.com/tmp.js" =?>
+        "[https://example.com/tmp.js]"
+
+      , "email link" =:
+        link "mailto:me@example.com" "" "Jane" =?>
+        "[Jane|mailto:me@example.com]"
+
+      , "email link without description" =:
+        link "mailto:me@example.com" "" "me@example.com" =?>
+        "[mailto:me@example.com]"
+
+      , "attachment link" =:
+        linkWith ("", ["attachment"], []) "foo.txt" "" "My file" =?>
+        "[My file^foo.txt]"
+
+      , "attachment link without description" =:
+        linkWith ("", ["attachment"], []) "foo.txt" "" "foo.txt" =?>
+        "[^foo.txt]"
+
+      , "user link" =:
+        linkWith ("", ["user-account"], []) "~johndoe" "" "John Doe" =?>
+        "[John Doe|~johndoe]"
+
+      , "user link with user as description" =:
+        linkWith ("", ["user-account"], []) "~johndoe" "" "~johndoe" =?>
+        "[~johndoe]"
+
+      , "'smart' link" =:
+        para (linkWith ("", ["smart-link"], []) "http://example.com" "" "x") =?>
+        "[x|http://example.com|smart-link]"
+
+      , "'smart' card" =:
+        para (linkWith ("", ["smart-card"], []) "http://example.org" "" "x") =?>
+        "[x|http://example.org|smart-card]"
+      ]
+
+    , testGroup "spans"
+      [ "id is used as anchor" =:
+        spanWith ("unicorn", [], []) (str "Unicorn") =?>
+        "{anchor:unicorn}Unicorn"
+
+      , "use `color` attribute" =:
+        spanWith ("",[],[("color","red")]) "ruby" =?>
+        "{color:red}ruby{color}"
+      ]
+
+    , testGroup "code"
+      [ "code block with known language" =:
+        codeBlockWith ("", ["java"], []) "Book book = new Book(\"Algebra\")" =?>
+        "{code:java}\nBook book = new Book(\"Algebra\")\n{code}"
+
+      , "code block without language" =:
+        codeBlockWith ("", [], []) "preformatted\n  text.\n" =?>
+        "{noformat}\npreformatted\n  text.\n{noformat}"
+      ]
+    ]
+
+  , testGroup "blocks"
+    [ testGroup "div"
+      [ "empty attributes" =:
+        divWith nullAttr (para "interesting text") =?>
+        "interesting text"
+
+      , "just identifier" =:
+        divWith ("a", [], []) (para "interesting text") =?>
+        "{anchor:a}interesting text"
+
+      , "with class 'panel'" =:
+        divWith ("", ["panel"], []) (para "Contents!") =?>
+        "{panel}\nContents\\!\n{panel}\n"
+
+      , "panel with id" =:
+        divWith ("b", ["panel"], []) (para "text") =?>
+        "{panel}\n{anchor:b}text\n{panel}\n"
+
+      , "title attribute" =:
+        divWith ("", [], [("title", "Gimme!")]) (para "Contents!") =?>
+        "{panel:title=Gimme!}\nContents\\!\n{panel}\n"
+
+      , "nested panels" =:
+        let panelAttr = ("", ["panel"], [])
+        in divWith panelAttr (para "hi" <>
+                              divWith panelAttr (para "wassup?")) =?>
+        "{panel}\nhi\n\nwassup?\n{panel}\n"
+      ]
+    ]
+  ]
diff --git a/test/Tests/Writers/LaTeX.hs b/test/Tests/Writers/LaTeX.hs
--- a/test/Tests/Writers/LaTeX.hs
+++ b/test/Tests/Writers/LaTeX.hs
@@ -1,8 +1,9 @@
 {-# LANGUAGE OverloadedStrings #-}
 module Tests.Writers.LaTeX (tests) where
 
-import Data.Text (unpack)
+import Data.Text (pack, unpack)
 import Test.Tasty
+import Test.Tasty.HUnit (HasCallStack)
 import Tests.Helpers
 import Text.Pandoc
 import Text.Pandoc.Arbitrary ()
@@ -12,7 +13,7 @@
 latex = latexWithOpts def
 
 latexListing :: (ToPandoc a) => a -> String
-latexListing = latexWithOpts def{ writerListings = True }
+latexListing = latexWithOpts def{ writerHighlightMethod = IdiomaticHighlighting }
 
 latexWithOpts :: (ToPandoc a) => WriterOptions -> a -> String
 latexWithOpts opts = unpack . purely (writeLaTeX opts) . toPandoc
@@ -33,7 +34,7 @@
 -}
 
 infix 4 =:
-(=:) :: (ToString a, ToPandoc a)
+(=:) :: (ToString a, ToPandoc a, HasCallStack)
      => String -> (a, String) -> TestTree
 (=:) = test latex
 
@@ -49,7 +50,7 @@
         , testGroup "definition lists"
           [ "with internal link" =: definitionList [(link "#go" "" (str "testing"),
              [plain (text "hi there")])] =?>
-            "\\begin{description}\n\\tightlist\n\\item[{\\protect\\hyperlink{go}{testing}}]\nhi there\n\\end{description}"
+            "\\begin{description}\n\\tightlist\n\\item[{\\hyperref[go]{testing}}]\nhi there\n\\end{description}"
           ]
         , testGroup "math"
           [ "escape |" =: para (math "\\sigma|_{\\{x\\}}") =?>
@@ -59,7 +60,7 @@
           [ "unnumbered header" =:
             headerWith ("foo",["unnumbered"],[]) 1
               (text "Header 1" <> note (plain $ text "note")) =?>
-            "\\hypertarget{foo}{%\n\\section*{\\texorpdfstring{Header 1\\footnote{note}}{Header 1}}\\label{foo}}\n\\addcontentsline{toc}{section}{Header 1}\n"
+            "\\section*{\\texorpdfstring{Header 1\\footnote{note}}{Header 1}}\\label{foo}\n\\addcontentsline{toc}{section}{Header 1}\n"
           , "in list item" =:
             bulletList [header 2 (text "foo")] =?>
             "\\begin{itemize}\n\\item ~\n  \\subsection{foo}\n\\end{itemize}"
@@ -69,22 +70,90 @@
             "\\begin{description}\n\\item[foo] ~ \n\\subsection{bar}\n\nbaz\n\\end{description}"
           , "containing image" =:
             header 1 (image "imgs/foo.jpg" "" (text "Alt text")) =?>
-            "\\section{\\texorpdfstring{\\protect\\includegraphics{imgs/foo.jpg}}{Alt text}}"
+            "\\section{\\texorpdfstring{\\protect\\pandocbounded{\\includegraphics[keepaspectratio,alt={Alt text}]{imgs/foo.jpg}}}{Alt text}}"
           ]
         , testGroup "inline code"
           [ "struck out and highlighted" =:
             strikeout (codeWith ("",["haskell"],[]) "foo" <> space
               <> str "bar") =?>
-            "\\sout{\\mbox{\\VERB|\\NormalTok{foo}|} bar}"
+            "\\st{\\mbox{\\VERB|\\NormalTok{foo}|} bar}"
           , "struck out and not highlighted" =:
             strikeout (code "foo" <> space
               <> str "bar") =?>
-            "\\sout{\\texttt{foo} bar}"
+            "\\st{\\mbox{\\texttt{foo}} bar}"
           , "single quotes" =:
               code "dog's" =?> "\\texttt{dog\\textquotesingle{}s}"
           , "backtick" =:
               code "`nu?`" =?> "\\texttt{\\textasciigrave{}nu?\\textasciigrave{}}"
           ]
+        , testGroup "inline note"
+          [ "Big note in emph" =:
+              emph (str "This sentence"
+                    <> note (para (str "paragraph1")
+                             <> para (str "paragraph2"))
+                    <> str " has footnote.")
+              =?>
+                 "\\emph{This sentence}\\footnote{paragraph1\n\n  paragraph2}"
+                 <> "\\emph{ has footnote.}"
+           , "Big note in strong" =:
+              strong (str "This sentence"
+                      <> note (para (str "paragraph1")
+                               <> para (str "paragraph2"))
+                      <> str " has footnote.")
+              =?>
+                 "\\textbf{This sentence}\\footnote{paragraph1\n\n  paragraph2}"
+                 <> "\\textbf{ has footnote.}"
+
+           , "Big note in underline" =:
+              underline (str "This sentence"
+                         <> note (para (str "paragraph1")
+                                  <> para (str "paragraph2"))
+                         <> str " has footnote.")
+              =?>
+                 "\\ul{This sentence}\\footnote{paragraph1\n\n  paragraph2}"
+                 <> "\\ul{ has footnote.}"
+
+           , "Big note in strikeout" =:
+              strikeout (str "This sentence"
+                         <> note (para (str "paragraph1")
+                                  <> para (str "paragraph2"))
+                         <> str " has footnote.")
+              =?>
+                 "\\st{This sentence}\\footnote{paragraph1\n\n  paragraph2}"
+                 <> "\\st{ has footnote.}"
+
+           , "Small note in emph" =:
+              emph (str "This sentence"
+                    <> note (para (str "paragraph"))
+                    <> str " has footnote.")
+              =?>
+                 "\\emph{This sentence\\footnote{paragraph} has footnote.}"
+
+           , "Big note nested in emph and strong" =:
+              emph (str "This "
+                    <> strong (str "nested sentence "
+                               <> note (para (str "paragraph1")
+                                        <> para (str "paragraph2"))
+                               <> str "has ")
+                    <> str "footnote."
+              )
+              =?>
+                 "\\emph{This \\textbf{nested sentence }}\\footnote{paragraph1\n\n"
+                 <> "  paragraph2}\\emph{\\textbf{has }footnote.}"
+
+          , "Two Big notes in emph" =:
+              emph (str "This sentence"
+                    <> note (para (str "1-paragraph1")
+                             <> para (str "1-paragraph2"))
+                    <> str " has"
+                    <> note (para (str "2-paragraph1")
+                             <> para (str "2-paragraph2"))
+                    <> str " footnote.")
+              =?>
+                 "\\emph{This sentence}\\footnote{1-paragraph1\n\n  1-paragraph2}"
+                 <> "\\emph{ has}\\footnote{2-paragraph1\n\n  2-paragraph2}"
+                 <> "\\emph{ footnote.}"
+          ]
         , testGroup "writer options"
           [ testGroup "top-level division" $
             let
@@ -168,9 +237,19 @@
                       , "\\addcontentsline{toc}{subsection}{header4}\n"
                       , "\\subsubsection*{header5}"
                       , "\\addcontentsline{toc}{subsubsection}{header5}\n"
-                      , "\\paragraph{header6}"
+                      , "\\paragraph*{header6}"
                       , "\\addcontentsline{toc}{paragraph}{header6}"
                       ]
             ]
+          ]
+        , testGroup "figures"
+          [ "placement" =:
+            figureWith ("", [], [("latex-placement", "htbp")])
+            (simpleCaption $ plain "caption")
+            (plain $ image (pack "img.jpg") (pack "") (text "alt text"))
+            =?>
+              "\\begin{figure}[htbp]\n\\centering\n"
+              <> "\\pandocbounded{\\includegraphics[keepaspectratio,alt={alt text}]{img.jpg}}\n"
+              <> "\\caption{caption}\n\\end{figure}"
           ]
         ]
diff --git a/test/Tests/Writers/Markdown.hs b/test/Tests/Writers/Markdown.hs
--- a/test/Tests/Writers/Markdown.hs
+++ b/test/Tests/Writers/Markdown.hs
@@ -4,13 +4,16 @@
 
 import Data.Text (unpack)
 import Test.Tasty
+import Test.Tasty.HUnit (HasCallStack)
 import Tests.Helpers
 import Text.Pandoc
 import Text.Pandoc.Arbitrary ()
 import Text.Pandoc.Builder
 
 defopts :: WriterOptions
-defopts = def{ writerExtensions = pandocExtensions }
+defopts = def
+  { writerExtensions = pandocExtensions
+  , writerSetextHeaders = True }
 
 markdown :: (ToPandoc a) => a -> String
 markdown = unpack . purely (writeMarkdown defopts) . toPandoc
@@ -31,7 +34,7 @@
 -}
 
 infix 4 =:
-(=:) :: (ToString a, ToPandoc a)
+(=:) :: (ToString a, ToPandoc a, HasCallStack)
      => String -> (a, String) -> TestTree
 (=:) = test markdown
 
@@ -42,7 +45,10 @@
         , "list with tight sublist"
              =: bulletList [ plain "foo" <> bulletList [ plain "bar" ],
                              plain "baz" ]
-             =?> "-   foo\n    -   bar\n-   baz\n"
+             =?> "- foo\n  - bar\n- baz\n"
+        , "emph/strong with spaces (#10696)"
+             =: emph (str "f" <> strong (space <> str "d" <> space)) <> str "l" =?>
+             "*f **d*** l"
         ] ++ [noteTests] ++ [shortcutLinkRefsTests]
 
 {-
@@ -80,7 +86,7 @@
         ".") <>
   blockQuote (para ("A note inside a block quote." <>
                     note (para "The second note.")) <>
-              para ("A second paragraph.")) <>
+              para "A second paragraph.") <>
   header 1 "Second Header" <>
   para "Some more text."
 
@@ -91,7 +97,7 @@
   [ test (markdownWithOpts defopts)
     "footnotes at the end of a document" $
     noteTestDoc =?>
-    (unlines $ [ "First Header"
+    unlines [ "First Header"
                , "============"
                , ""
                , "This is a footnote.[^1] And this is a [link](https://www.google.com)."
@@ -108,11 +114,11 @@
                , "[^1]: Down here."
                , ""
                , "[^2]: The second note."
-               ])
+               ]
   , test (markdownWithOpts defopts{writerReferenceLocation=EndOfBlock})
     "footnotes at the end of blocks" $
     noteTestDoc =?>
-    (unlines $ [ "First Header"
+    unlines [ "First Header"
                , "============"
                , ""
                , "This is a footnote.[^1] And this is a [link](https://www.google.com)."
@@ -129,11 +135,11 @@
                , "============="
                , ""
                , "Some more text."
-               ])
+               ]
   , test (markdownWithOpts defopts{writerReferenceLocation=EndOfBlock, writerReferenceLinks=True})
     "footnotes and reference links at the end of blocks" $
     noteTestDoc =?>
-    (unlines $ [ "First Header"
+    unlines [ "First Header"
                , "============"
                , ""
                , "This is a footnote.[^1] And this is a [link]."
@@ -152,11 +158,11 @@
                , "============="
                , ""
                , "Some more text."
-               ])
+               ]
   , test (markdownWithOpts defopts{writerReferenceLocation=EndOfSection})
     "footnotes at the end of section" $
     noteTestDoc =?>
-    (unlines $ [ "First Header"
+    unlines [ "First Header"
                , "============"
                , ""
                , "This is a footnote.[^1] And this is a [link](https://www.google.com)."
@@ -173,40 +179,40 @@
                , "============="
                , ""
                , "Some more text."
-               ])
+               ]
 
   ]
 
 shortcutLinkRefsTests :: TestTree
 shortcutLinkRefsTests =
   let infix 4 =:
-      (=:) :: (ToString a, ToPandoc a)
+      (=:) :: (ToString a, ToPandoc a, HasCallStack)
 
         => String -> (a, String) -> TestTree
       (=:) = test (purely (writeMarkdown defopts{writerReferenceLinks = True}) . toPandoc)
   in testGroup "Shortcut reference links"
      [ "Simple link (shortcutable)"
-           =: (para (link "/url" "title" "foo"))
+           =: para (link "/url" "title" "foo")
            =?> "[foo]\n\n  [foo]: /url \"title\""
      , "Followed by another link (unshortcutable)"
-           =: (para ((link "/url1" "title1" "first")
-                  <> (link "/url2" "title2" "second")))
+           =: para (link "/url1" "title1" "first"
+                  <> link "/url2" "title2" "second")
            =?> unlines [ "[first][][second]"
                        , ""
                        , "  [first]: /url1 \"title1\""
                        , "  [second]: /url2 \"title2\""
                        ]
      , "Followed by space and another link (unshortcutable)"
-           =: (para ((link "/url1" "title1" "first") <> " "
-                  <> (link "/url2" "title2" "second")))
+           =: para (link "/url1" "title1" "first" <> " "
+                  <> link "/url2" "title2" "second")
            =?> unlines [ "[first][] [second]"
                        , ""
                        , "  [first]: /url1 \"title1\""
                        , "  [second]: /url2 \"title2\""
                        ]
      , "Reference link is used multiple times (unshortcutable)"
-           =: (para ((link "/url1" "" "foo") <> (link "/url2" "" "foo")
-                                             <> (link "/url3" "" "foo")))
+           =: para (link "/url1" "" "foo" <> link "/url2" "" "foo"
+                                             <> link "/url3" "" "foo")
            =?> unlines [ "[foo][][foo][1][foo][2]"
                        , ""
                        , "  [foo]: /url1"
@@ -214,8 +220,8 @@
                        , "  [2]: /url3"
                        ]
      , "Reference link is used multiple times (unshortcutable)"
-           =: (para ((link "/url1" "" "foo") <> " " <> (link "/url2" "" "foo")
-                                             <> " " <> (link "/url3" "" "foo")))
+           =: para (link "/url1" "" "foo" <> " " <> link "/url2" "" "foo"
+                                             <> " " <> link "/url3" "" "foo")
            =?> unlines [ "[foo][] [foo][1] [foo][2]"
                        , ""
                        , "  [foo]: /url1"
@@ -223,43 +229,43 @@
                        , "  [2]: /url3"
                        ]
      , "Reference link is followed by text in brackets"
-          =:  (para ((link "/url" "" "link") <> "[text in brackets]"))
+          =:  para (link "/url" "" "link" <> "[text in brackets]")
           =?> unlines [ "[link][]\\[text in brackets\\]"
                       , ""
                       , "  [link]: /url"
                       ]
      , "Reference link is followed by space and text in brackets"
-          =:  (para ((link "/url" "" "link") <> " [text in brackets]"))
+          =:  para (link "/url" "" "link" <> " [text in brackets]")
           =?> unlines [ "[link][] \\[text in brackets\\]"
                       , ""
                       , "  [link]: /url"
                       ]
      , "Reference link is followed by RawInline"
-          =: (para ((link "/url" "" "link") <> rawInline "markdown" "[rawText]"))
+          =: para (link "/url" "" "link" <> rawInline "markdown" "[rawText]")
           =?> unlines [ "[link][][rawText]"
                       , ""
                       , "  [link]: /url"
                       ]
      , "Reference link is followed by space and RawInline"
-          =: (para ((link "/url" "" "link") <> space <> rawInline "markdown" "[rawText]"))
+          =: para (link "/url" "" "link" <> space <> rawInline "markdown" "[rawText]")
           =?> unlines [ "[link][] [rawText]"
                       , ""
                       , "  [link]: /url"
                       ]
      , "Reference link is followed by RawInline with space"
-          =: (para ((link "/url" "" "link") <> rawInline "markdown" " [rawText]"))
+          =: para (link "/url" "" "link" <> rawInline "markdown" " [rawText]")
           =?> unlines [ "[link][] [rawText]"
                       , ""
                       , "  [link]: /url"
                       ]
      , "Reference link is followed by citation"
-          =: (para ((link "/url" "" "link") <> cite [Citation "author" [] [] NormalCitation 0 0] (str "[@author]")))
+          =: para (link "/url" "" "link" <> cite [Citation "author" [] [] NormalCitation 0 0] (str "[@author]"))
           =?> unlines [ "[link][][@author]"
                       , ""
                       , "  [link]: /url"
                       ]
      , "Reference link is followed by space and citation"
-          =: (para ((link "/url" "" "link") <> space <> cite [Citation "author" [] [] NormalCitation 0 0] (str "[@author]")))
+          =: para (link "/url" "" "link" <> space <> cite [Citation "author" [] [] NormalCitation 0 0] (str "[@author]"))
           =?> unlines [ "[link][] [@author]"
                       , ""
                       , "  [link]: /url"
diff --git a/test/Tests/Writers/Markua.hs b/test/Tests/Writers/Markua.hs
new file mode 100644
--- /dev/null
+++ b/test/Tests/Writers/Markua.hs
@@ -0,0 +1,41 @@
+{-# LANGUAGE OverloadedStrings #-}
+module Tests.Writers.Markua (tests) where
+
+import Test.Tasty
+import Test.Tasty.HUnit (HasCallStack)
+import Tests.Helpers
+import Text.Pandoc
+import Text.Pandoc.Arbitrary ()
+import Text.Pandoc.Builder
+
+{-
+  "my test" =: X =?> Y
+
+is shorthand for
+
+  test html "my test" $ X =?> Y
+
+which is in turn shorthand for
+
+  test html "my test" (X,Y)
+-}
+
+infix 4 =:
+(=:) :: (ToString a, ToPandoc a, HasCallStack)
+     => String -> (a, String) -> TestTree
+(=:) = test (purely (writeMarkua def) . toPandoc)
+
+tests :: [TestTree]
+tests = [ testGroup "simple blurb/aside"
+          ["blurb"          =: divWith ("",["blurb"],[]) (bulletList [para "blurb content"])
+                           =?> "B> * blurb content"
+          ,"aside"          =: divWith ("",["aside"],[]) (bulletList [para "aside list"])
+                           =?> "A> * aside list"
+          ]
+         ,testGroup "multiclass blurb/aside"
+          ["blurb"          =: divWith ("",["blurb", "otherclass"],[]) (bulletList [para "blurb content"])
+                           =?> "B> * blurb content"
+          ,"aside"          =: divWith ("",["otherclass", "aside"],[]) (bulletList [para "aside list"])
+                           =?> "A> * aside list"
+          ]
+         ]
diff --git a/test/Tests/Writers/Ms.hs b/test/Tests/Writers/Ms.hs
new file mode 100644
--- /dev/null
+++ b/test/Tests/Writers/Ms.hs
@@ -0,0 +1,36 @@
+{-# LANGUAGE OverloadedStrings #-}
+module Tests.Writers.Ms (tests) where
+
+import Test.Tasty
+import Test.Tasty.HUnit (HasCallStack)
+import Tests.Helpers
+import Text.Pandoc
+import Text.Pandoc.Builder
+
+infix 4 =:
+(=:) :: (ToString a, ToPandoc a, HasCallStack)
+     => String -> (a, String) -> TestTree
+(=:) = test (purely (writeMs def . toPandoc))
+
+tests :: [TestTree]
+tests = [ testGroup "code blocks"
+          [ "basic"
+              =: codeBlock "hello"
+              =?> unlines
+              [ ".IP"
+              , ".nf"
+              , "\\f[C]"
+              , "hello"
+              , "\\f[]"
+              , ".fi"]
+          , "escape starting ."
+              =: codeBlock ". hello"
+              =?> unlines
+              [ ".IP"
+              , ".nf"
+              , "\\f[C]"
+              , "\\&. hello"
+              , "\\f[]"
+              , ".fi"]
+          ]
+        ]
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
@@ -1,44 +1,126 @@
+{-# LANGUAGE OverloadedStrings #-}
 module Tests.Writers.Muse (tests) where
 
-import Data.Text (unpack)
+import Prelude hiding (unlines)
+import Data.Text (Text, unlines)
 import Test.Tasty
+import Test.Tasty.HUnit (HasCallStack)
 import Tests.Helpers
 import Text.Pandoc
 import Text.Pandoc.Arbitrary ()
 import Text.Pandoc.Builder
 
-muse :: (ToPandoc a) => a -> String
-muse = museWithOpts def{ writerWrapText = WrapNone,
-                         writerExtensions = extensionsFromList [Ext_amuse,
-                                                                Ext_auto_identifiers] }
+defopts :: WriterOptions
+defopts = def{ writerWrapText = WrapPreserve,
+               writerExtensions = extensionsFromList [Ext_amuse,
+                                                      Ext_auto_identifiers] }
 
-museWithOpts :: (ToPandoc a) => WriterOptions -> a -> String
-museWithOpts opts = unpack . purely (writeMuse opts) . toPandoc
+muse :: (ToPandoc a) => a -> Text
+muse = museWithOpts defopts
 
+museWithOpts :: (ToPandoc a) => WriterOptions -> a -> Text
+museWithOpts opts = purely (writeMuse opts) . toPandoc
+
 infix 4 =:
-(=:) :: (ToString a, ToPandoc a)
-     => String -> (a, String) -> TestTree
+(=:) :: (ToString a, ToPandoc a, HasCallStack)
+     => String -> (a, Text) -> TestTree
 (=:) = test muse
 
+noteLocationTestDoc :: Blocks
+noteLocationTestDoc =
+  header 1 "First Header" <>
+  para ("This is a footnote." <>
+        note (para "First note.")) <>
+  blockQuote (para ("A note inside a block quote." <>
+                    note (para "The second note.")) <>
+              para "A second paragraph.") <>
+  header 1 "Second Header" <>
+  para "Some more text."
+
+noteLocationTests :: TestTree
+noteLocationTests = testGroup "note location"
+  [ test (museWithOpts defopts {writerReferenceLocation=EndOfDocument})
+    "footnotes at the end of document" $
+    noteLocationTestDoc =?>
+    unlines [ "* First Header"
+            , ""
+            , "This is a footnote.[1]"
+            , ""
+            , "<quote>"
+            , "A note inside a block quote.[2]"
+            , ""
+            , "A second paragraph."
+            , "</quote>"
+            , ""
+            , "* Second Header"
+            , ""
+            , "Some more text."
+            , ""
+            , "[1] First note."
+            , ""
+            , "[2] The second note."
+            ]
+  , test (museWithOpts defopts {writerReferenceLocation=EndOfBlock})
+    "footnotes at the end of block" $
+    noteLocationTestDoc =?>
+    unlines [ "* First Header"
+            , ""
+            , "This is a footnote.[1]"
+            , ""
+            , "[1] First note."
+            , ""
+            , "<quote>"
+            , "A note inside a block quote.[2]"
+            , ""
+            , "[2] The second note."
+            , ""
+            , "A second paragraph."
+            , "</quote>"
+            , ""
+            , "* Second Header"
+            , ""
+            , "Some more text."
+            ]
+  , test (museWithOpts defopts {writerReferenceLocation=EndOfSection})
+    "footnotes at the end of section" $
+    noteLocationTestDoc =?>
+    unlines [ "* First Header"
+            , ""
+            , "This is a footnote.[1]"
+            , ""
+            , "<quote>"
+            , "A note inside a block quote.[2]"
+            , ""
+            , "A second paragraph."
+            , "</quote>"
+            , ""
+            , "[1] First note."
+            , ""
+            , "[2] The second note."
+            , ""
+            , "* Second Header"
+            , ""
+            , "Some more text."
+            ]
+  ]
+
 tests :: [TestTree]
 tests = [ testGroup "block elements"
-          [ "plain" =: plain (text "Foo bar.") =?> "Foo bar."
+          [ "plain" =: plain "Foo bar." =?> "Foo bar."
           , testGroup "paragraphs"
-            [ "single paragraph" =: para (text "Sample paragraph.")
+            [ "single paragraph" =: para "Sample paragraph."
                                  =?> "Sample paragraph."
-            , "two paragraphs" =: para (text "First paragraph.") <>
-                                  para (text "Second paragraph.")
+            , "two paragraphs" =: para "First paragraph." <>
+                                  para "Second paragraph."
                                =?> unlines [ "First paragraph."
                                            , ""
                                            , "Second paragraph."
                                            ]
             ]
-          , "line block" =: lineBlock [text "Foo", text "bar", text "baz"]
-                         =?> unlines [ "<verse>"
-                                     , "Foo"
-                                     , "bar"
-                                     , "baz"
-                                     , "</verse>"
+          , "line block" =: lineBlock ["Foo", "bar", "baz"]
+                         =?> unlines [ "> Foo"
+                                     , "> bar"
+                                     , "> baz"
                                      ]
           , "code block" =: codeBlock "int main(void) {\n\treturn 0;\n}"
                          =?> unlines [ "<example>"
@@ -52,7 +134,7 @@
                                          , "<hr>"
                                          , "</literal>"
                                          ]
-          , "block quote" =: blockQuote (para (text "Foo"))
+          , "block quote" =: blockQuote (para "Foo")
                           =?> unlines [ "<quote>"
                                       , "Foo"
                                       , "</quote>"
@@ -60,9 +142,9 @@
           , testGroup "lists"
             [ testGroup "simple lists"
               [
-                "ordered list" =: orderedList [ plain $ text "first"
-                                              , plain $ text "second"
-                                              , plain $ text "third"
+                "ordered list" =: orderedList [ plain "first"
+                                              , plain "second"
+                                              , plain "third"
                                               ]
                                =?> unlines [ " 1. first"
                                            , " 2. second"
@@ -70,40 +152,77 @@
                                            ]
               , "ordered list with Roman numerals"
                 =: orderedListWith (1, UpperRoman, DefaultDelim)
-                   [ plain $ text "first"
-                   , plain $ text "second"
-                   , plain $ text "third"
+                   [ plain "first"
+                   , plain "second"
+                   , plain "third"
                    ]
-                =?> unlines [ " I.   first"
-                            , " II.  second"
+                =?> unlines [ " I. first"
+                            , " II. second"
                             , " III. third"
                             ]
-              , "bullet list" =: bulletList [ plain $ text "first"
-                                            , plain $ text "second"
-                                            , plain $ text "third"
+              , "bullet list" =: bulletList [ plain "first"
+                                            , plain "second"
+                                            , plain "third"
                                             ]
                               =?> unlines [ " - first"
                                           , " - second"
                                           , " - third"
                                           ]
-              , "definition list" =: definitionList [ (text "first definition", [plain $ text "first description"])
-                                                    , (text "second definition", [plain $ text "second description"])
-                                                    , (text "third definition", [plain $ text "third description"])
+              , "definition list" =: definitionList [ ("first definition", [plain "first description"])
+                                                    , ("second definition", [plain "second description"])
+                                                    , ("third definition", [plain "third description"])
                                                     ]
                                   =?> unlines [ " first definition :: first description"
                                               , " second definition :: second description"
                                               , " third definition :: third description"
                                               ]
+              , "definition list with multiple descriptions" =:
+                definitionList [ ("first definition", [ plain "first description"
+                                                      , plain "second description"
+                                                      ])
+                               , ("second definition", [plain "third description"])
+                               ]
+                =?> unlines [ " first definition :: first description"
+                            , "                  :: second description"
+                            , " second definition :: third description"
+                            ]
+              , "definition list with empty term" =:
+                definitionList [ ("first definition", [plain "first description"])
+                               , (mempty, [plain "second description"])
+                               , (str "", [plain "third description"])
+                               ]
+                =?> unlines [ " first definition :: first description"
+                            , " <verbatim></verbatim> :: second description"
+                            , " <verbatim></verbatim> :: third description"
+                            ]
+              , "definition list terms starting with space" =:
+                definitionList [ ("first definition", [plain "first description"])
+                               , (space <> str "foo", [plain "second description"])
+                               , (str " > bar", [plain "third description"])
+                               ]
+                =?> unlines [ " first definition :: first description"
+                            , " <verbatim></verbatim> foo :: second description"
+                            , " <verbatim></verbatim> > bar :: third description"
+                            ]
+              , "definition list terms starting with list markers" =:
+                definitionList [ ("first definition", [plain "first description"])
+                               , (str "-", [plain "second description"])
+                               , (str "1.", [plain "third description"])
+                               ]
+                =?> unlines [ " first definition :: first description"
+                            , " <verbatim></verbatim>- :: second description"
+                            , " <verbatim></verbatim>1. :: third description"
+                            ]
               ]
             -- Test that lists of the same type and style are separated with two blanklines
             , testGroup "sequential lists"
               [ "bullet lists" =:
-                bulletList [ para $ text "First"
-                           , para $ text "Second"
-                           , para $ text "Third"
+                bulletList [ para "First"
+                           , para "Second"
+                           , para "Third"
                            ] <>
-                bulletList [ para $ text "Fourth"
-                           , para $ text "Fifth"
+                bulletList [ para "Fourth"
+                           , para "Fifth"
                            ] =?>
                 unlines [ " - First"
                         , " - Second"
@@ -114,25 +233,25 @@
                         , " - Fifth"
                         ]
               , "ordered lists of the same style" =:
-                orderedListWith (1, UpperRoman, DefaultDelim) [ para $ text "First"
-                                                              , para $ text "Second"
+                orderedListWith (1, UpperRoman, DefaultDelim) [ para "First"
+                                                              , para "Second"
                                                               ] <>
-                orderedListWith (1, UpperRoman, DefaultDelim) [ para $ text "Third"
-                                                              , para $ text "Fourth"
+                orderedListWith (1, UpperRoman, DefaultDelim) [ para "Third"
+                                                              , para "Fourth"
                                                               ] =?>
-                unlines [ " I.  First"
+                unlines [ " I. First"
                         , " II. Second"
                         , ""
                         , ""
-                        , " I.  Third"
+                        , " I. Third"
                         , " II. Fourth"
                         ]
               , "ordered lists with equal styles" =:
-                orderedList [ para $ text "First"
-                            , para $ text "Second"
+                orderedList [ para "First"
+                            , para "Second"
                             ] <>
-                orderedListWith (1, Decimal, DefaultDelim) [ para $ text "Third"
-                                                           , para $ text "Fourth"
+                orderedListWith (1, Decimal, DefaultDelim) [ para "Third"
+                                                           , para "Fourth"
                                                            ] =?>
                 unlines [ " 1. First"
                         , " 2. Second"
@@ -142,26 +261,26 @@
                         , " 2. Fourth"
                         ]
               , "bullet and ordered lists" =:
-                bulletList [ para $ text "First"
-                           , para $ text "Second"
+                bulletList [ para "First"
+                           , para "Second"
                            ] <>
-                orderedListWith (1, UpperRoman, DefaultDelim) [ para $ text "Third"
-                                                              , para $ text "Fourth"
+                orderedListWith (1, UpperRoman, DefaultDelim) [ para "Third"
+                                                              , para "Fourth"
                                                               ] =?>
                 unlines [ " - First"
                         , " - Second"
                         , ""
-                        , " I.  Third"
+                        , " I. Third"
                         , " II. Fourth"
                         ]
               , "different style ordered lists" =:
-                orderedListWith (1, UpperRoman, DefaultDelim) [ para $ text "First"
-                                                              , para $ text "Second"
+                orderedListWith (1, UpperRoman, DefaultDelim) [ para "First"
+                                                              , para "Second"
                                                               ] <>
-                orderedListWith (1, Decimal, DefaultDelim) [ para $ text "Third"
-                                                           , para $ text "Fourth"
+                orderedListWith (1, Decimal, DefaultDelim) [ para "Third"
+                                                           , para "Fourth"
                                                            ] =?>
-                unlines [ " I.  First"
+                unlines [ " I. First"
                         , " II. Second"
                         , ""
                         , " 1. Third"
@@ -169,12 +288,12 @@
                         ]
               ]
             , testGroup "nested lists"
-              [ "nested ordered list" =: orderedList [ plain $ text "First outer"
-                                                     , plain (text "Second outer:") <>
-                                                       orderedList [ plain $ text "first"
-                                                                   , plain $ text "second"
+              [ "nested ordered list" =: orderedList [ plain "First outer"
+                                                     , plain "Second outer:" <>
+                                                       orderedList [ plain "first"
+                                                                   , plain "second"
                                                                    ]
-                                                     , plain $ text "Third outer"
+                                                     , plain "Third outer"
                                                      ]
                                       =?> unlines [ " 1. First outer"
                                                   , " 2. Second outer:"
@@ -182,12 +301,12 @@
                                                   , "    2. second"
                                                   , " 3. Third outer"
                                                   ]
-              , "nested bullet lists" =: bulletList [ plain $ text "First outer"
-                                                    , plain (text "Second outer:") <>
-                                                      bulletList [ plain $ text "first"
-                                                                 , plain $ text "second"
+              , "nested bullet lists" =: bulletList [ plain "First outer"
+                                                    , plain "Second outer:" <>
+                                                      bulletList [ plain "first"
+                                                                 , plain "second"
                                                                  ]
-                                                    , plain $ text "Third outer"
+                                                    , plain "Third outer"
                                                     ]
                                       =?> unlines [ " - First outer"
                                                   , " - Second outer:"
@@ -195,27 +314,28 @@
                                                   , "   - second"
                                                   , " - Third outer"
                                                   ]
-              , "nested definition lists" =: definitionList [ (text "first definition", [plain $ text "first description"])
-                                                            , (text "second definition",
-                                                               [ plain (text "second description")
-                                                               , definitionList [ ( text "first inner definition"
-                                                                                  , [plain $ text "first inner description"])
-                                                                                , ( text "second inner definition"
-                                                                                  , [plain $ text "second inner description"])
+              , "nested definition lists" =: definitionList [ ("first definition", [plain "first description"])
+                                                            , ("second definition",
+                                                               [ plain "second description" <>
+                                                                 definitionList [ ("first inner definition"
+                                                                                  , [plain "first inner description"])
+                                                                                , ( "second inner definition"
+                                                                                  , [plain "second inner description"])
                                                                                 ]
                                                                ]
                                                               )
                                                             ]
                                           =?> unlines [ " first definition :: first description"
                                                       , " second definition :: second description"
-                                                      , "                       first inner definition :: first inner description"
-                                                      , "                       second inner definition :: second inner description"
+                                                      , "                      first inner definition :: first inner description"
+                                                      , "                      second inner definition :: second inner description"
                                                       ]
+              , "list item starting with list" =: bulletList [ bulletList [ plain "foo"] ] =?> " - - foo"
               ]
             -- Check that list is intended with one space even inside a quote
-            , "List inside block quote" =: blockQuote (orderedList [ plain $ text "first"
-                                                                   , plain $ text "second"
-                                                                   , plain $ text "third"
+            , "List inside block quote" =: blockQuote (orderedList [ plain "first"
+                                                                   , plain "second"
+                                                                   , plain "third"
                                                                    ])
                                         =?> unlines [ "<quote>"
                                                     , " 1. first"
@@ -226,35 +346,46 @@
             ]
           , testGroup "headings"
             [ "normal heading" =:
-              header 1 (text "foo") =?> "* foo"
+              header 1 "foo" =?> "* foo"
             , "heading levels" =:
-              header 1 (text "First level") <>
-              header 3 (text "Third level") =?>
+              header 1 "First level" <>
+              header 3 "Third level" =?>
               unlines [ "* First level"
                       , ""
                       , "*** Third level"
                       ]
             , "heading with ID" =:
-               headerWith ("bar", [], []) 2 (text "Foo") =?>
-               unlines [ "** Foo"
-                       , "#bar"
+               headerWith ("bar", [], []) 2 "Foo" =?>
+               unlines [ "#bar"
+                       , "** Foo"
                       ]
+            , "empty heading" =: header 4 mempty =?> "**** <verbatim></verbatim>"
             ]
           , "horizontal rule" =: horizontalRule =?> "----"
-          , "escape horizontal rule" =: para (text "----") =?> "<verbatim>----</verbatim>"
+          , "escape horizontal rule" =: para "----" =?> "<verbatim></verbatim>----"
+          , "escape long horizontal rule" =: para "----------" =?> "<verbatim></verbatim>----------"
+          , "don't escape horizontal inside paragraph" =: para "foo ---- bar" =?> "foo ---- bar"
+          , "escape nonbreaking space" =: para "~~" =?> "<verbatim>~~</verbatim>"
+          , "escape > in the beginning of line" =: para "> foo bar" =?> "<verbatim></verbatim>> foo bar"
+          , "escape string with > and space in the beginning of line" =: para (str "> foo bar") =?> "<verbatim></verbatim>> foo bar"
           , testGroup "tables"
             [ "table without header" =:
-              let rows = [[para $ text "Para 1.1", para $ text "Para 1.2"]
-                         ,[para $ text "Para 2.1", para $ text "Para 2.2"]]
-              in simpleTable [] rows
+              let rows = [[para "Para 1.1", para "Para 1.2"]
+                         ,[para "Para 2.1", para "Para 2.2"]]
+                  toRow = Row nullAttr . map simpleCell
+              in table emptyCaption
+                       [(AlignDefault,ColWidthDefault),(AlignDefault,ColWidthDefault)]
+                       (TableHead nullAttr [toRow [mempty, mempty]])
+                       [TableBody nullAttr 0 [] $ map toRow rows]
+                       (TableFoot nullAttr [])
               =?>
               unlines [ " Para 1.1 | Para 1.2"
                       , " Para 2.1 | Para 2.2"
                       ]
             , "table with header" =:
-              let headers = [plain $ text "header 1", plain $ text "header 2"]
-                  rows = [[para $ text "Para 1.1", para $ text "Para 1.2"]
-                         ,[para $ text "Para 2.1", para $ text "Para 2.2"]]
+              let headers = [plain "header 1", plain "header 2"]
+                  rows = [[para "Para 1.1", para "Para 1.2"]
+                         ,[para "Para 2.1", para "Para 2.2"]]
               in simpleTable headers rows
               =?>
               unlines [ " header 1 || header 2"
@@ -262,63 +393,175 @@
                       , " Para 2.1 |  Para 2.2"
                       ]
             , "table with header and caption" =:
-              let caption = text "Table 1"
-                  headers = [plain $ text "header 1", plain $ text "header 2"]
-                  rows = [[para $ text "Para 1.1", para $ text "Para 1.2"]
-                         ,[para $ text "Para 2.1", para $ text "Para 2.2"]]
-              in table caption mempty headers rows
+              let capt = simpleCaption $ plain "Table 1"
+                  toRow = Row nullAttr . map simpleCell
+                  headers = [toRow [plain "header 1", plain "header 2"]]
+                  rows = map toRow [[para "Para 1.1", para  "Para 1.2"]
+                                   ,[para "Para 2.1", para  "Para 2.2"]]
+              in table capt
+                       [(AlignDefault,ColWidthDefault),(AlignDefault,ColWidthDefault)]
+                       (TableHead nullAttr headers)
+                       [TableBody nullAttr 0 [] rows]
+                       (TableFoot nullAttr [])
               =?> unlines [ " header 1 || header 2"
                           , " Para 1.1 |  Para 1.2"
                           , " Para 2.1 |  Para 2.2"
                           , " |+ Table 1 +|"
                           ]
+            , "table inside bullet list" =:
+              bulletList [simpleTable [] [[para "foo", para "bar"]
+                                         ,[para "bat", para "baz"]]]
+              =?> unlines [ " - foo | bar"
+                          , "   bat | baz"
+                          ]
+            , "table with one column" =:
+              let headers = []
+                  rows = [[para "Para 1"]
+                         ,[para "Para 2"]]
+              in simpleTable headers rows
+              =?>
+              unlines [ "+--------+"
+                      , "| Para 1 |"
+                      , "+--------+"
+                      , "| Para 2 |"
+                      , "+--------+"
+                      ]
             ]
-          -- Div is trivial
-          -- Null is trivial
+          , "div with bullet list" =:
+            divWith nullAttr (bulletList [para "foo"]) =?>
+            unlines [ " - foo" ] -- Making sure bullets are indented
           ]
         , testGroup "inline elements"
           [ 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>"
+            , "escape link-like text" =: str "[[https://www.example.org]]"
+               =?> "<verbatim>[[https://www.example.org]]</verbatim>"
             , "escape pipe to avoid accidental tables" =: str "foo | bar"
                =?> "<verbatim>foo | bar</verbatim>"
             , "escape hash to avoid accidental anchors" =: text "#foo bar"
               =?> "<verbatim>#foo</verbatim> bar"
             , "escape definition list markers" =: str "::" =?> "<verbatim>::</verbatim>"
+            , "normalize strings before escaping" =: fromList [Str ":", Str ":"] =?> "<verbatim>::</verbatim>"
             -- We don't want colons to be escaped if they can't be confused
             -- with definition list item markers.
             , "do not escape colon" =: str ":" =?> ":"
+            , "escape - to avoid accidental unordered lists" =: text " - foo" =?> "<verbatim></verbatim> - foo"
+            , "escape - inside a list to avoid accidental nested unordered lists" =:
+              bulletList [ para "foo" <>
+                           para "- bar"
+                         ] =?>
+              unlines [ " - foo"
+                      , ""
+                      , "   <verbatim></verbatim>- bar"
+                      ]
+            , "escape strings starting with - inside a list" =:
+              bulletList [ para (str "foo") <>
+                           para (str "- bar")
+                         ] =?>
+              unlines [ " - foo"
+                      , ""
+                      , "   <verbatim></verbatim>- bar"
+                      ]
+            , "escape - inside a note" =:
+              note (para "- foo") =?>
+              unlines [ "[1]"
+                      , ""
+                      , "[1] <verbatim></verbatim>- foo"
+                      ]
+            , "escape - after softbreak in note" =:
+              note (para (str "foo" <> softbreak <> str "- bar")) =?>
+              unlines [ "[1]"
+                      , ""
+                      , "[1] foo"
+                      , "    <verbatim></verbatim>- bar"
+                      ]
+            , "escape ; to avoid accidental comments" =: text "; foo" =?> "<verbatim></verbatim>; foo"
+            , "escape strings starting with ; and space" =: str "; foo" =?> "<verbatim></verbatim>; foo"
+            , "escape ; after softbreak" =: "foo" <> softbreak <> "; bar" =?> "foo\n<verbatim></verbatim>; bar"
+            , "escape ; after linebreak" =: "foo" <> linebreak <> "; bar" =?> "foo<br>\n<verbatim></verbatim>; bar"
+            , "do not escape ; inside paragraph" =: text "foo ; bar" =?> "foo ; bar"
+            , "escape newlines" =: str "foo\nbar" =?> "foo bar"
             ]
           , testGroup "emphasis"
-            [ "emph" =: emph (text "foo") =?> "<em>foo</em>"
-            , "strong" =: strong (text "foo") =?> "<strong>foo</strong>"
-            , "strikeout" =: strikeout (text "foo") =?> "<del>foo</del>"
+            [ "emphasis" =: emph "foo" =?> "*foo*"
+            , "emphasis inside word" =: "foo" <> emph "bar" <> "baz" =?> "foo<em>bar</em>baz"
+            , "emphasis before comma" =: emph "foo" <> ", bar" =?> "*foo*, bar"
+            , "emphasis before period" =: emph "foobar" <> "." =?> "*foobar*."
+            , "empty emphasis" =: emph mempty =?> "<em></em>"
+            , "empty strong" =: strong mempty =?> "<strong></strong>"
+            , "empty strong emphasis" =: strong (emph mempty) =?> "**<em></em>**"
+            , "empty emphasized strong" =: emph (strong mempty) =?> "*<strong></strong>*"
+            , "emphasized empty string" =: emph (str "") =?> "<em></em>"
+            , "strong empty string" =: strong (str "") =?> "<strong></strong>"
+            , "strong emphasized empty string" =: strong (emph (str "")) =?> "**<em></em>**"
+            , "emphasized strong empty string" =: emph (strong (str "")) =?> "*<strong></strong>*"
+            , "emphasized string with space" =: emph (str " ") =?> "<em> </em>"
+            , "emphasized string ending with space" =: emph (str "foo ") =?> "<em>foo </em>"
+            , "emphasized string with tab" =: emph (str "\t") =?> "<em>\t</em>"
+            , "emphasized space between empty strings" =: emph (str "" <> space <> str "") =?> "<em> </em>"
+            , "strong" =: strong "foo" =?> "**foo**"
+            , "strong inside word" =: "foo" <> strong "bar" <> "baz" =?> "foo<strong>bar</strong>baz"
+            , "strong emphasis" =: strong (emph "foo") =?> "***foo***"
+            , "strong after emphasis" =: emph "foo" <> strong "bar" =?> "*foo*<strong>bar</strong>"
+            , "strong emphasis after emphasis" =: emph "foo" <> strong (emph "bar") =?> "*foo*<strong>*bar*</strong>"
+            , "strong in the end of emphasis" =: emph ("foo" <> strong "bar") =?> "*foo<strong>bar</strong>*"
+            , "switch to lightweight markup after <em> tag" =:
+              strong (str "foo") <> emph (str "bar") <> strong (str "baz") =?>
+              "**foo**<em>bar</em>**baz**"
+            , "strikeout" =: strikeout "foo" =?> "<del>foo</del>"
+            , "space at the beginning of emphasis" =: emph " foo" =?> "<em> foo</em>"
+            , "space at the end of emphasis" =: emph "foo " =?> "<em>foo </em>"
+            , "space at the beginning of strong" =: strong " foo" =?> "<strong> foo</strong>"
+            , "space at the end of strong" =: strong "foo " =?> "<strong>foo </strong>"
+            , "space at the beginning of strong emphasis" =: strong (emph " foo") =?> "**<em> foo</em>**"
+            , "space at the end of strong emphasis" =: strong (emph "foo ") =?> "**<em>foo </em>**"
+            , "space at the beginning of emphasiszed strong" =: emph (strong " foo") =?> "*<strong> foo</strong>*"
+            , "space at the end of emphasized strong" =: emph (strong "foo ") =?> "*<strong>foo </strong>*"
             ]
-          , "superscript" =: superscript (text "foo") =?> "<sup>foo</sup>"
-          , "subscript" =: subscript (text "foo") =?> "<sub>foo</sub>"
-          , "smallcaps" =: smallcaps (text "foo") =?> "foo"
-          , "single quoted" =: singleQuoted (text "foo") =?> "'foo'"
-          , "double quoted" =: doubleQuoted (text "foo") =?> "\"foo\""
+          , "superscript" =: superscript "foo" =?> "<sup>foo</sup>"
+          , "subscript" =: subscript "foo" =?> "<sub>foo</sub>"
+          , "smallcaps" =: smallcaps "foo" =?> "*foo*"
+          , "smallcaps near emphasis" =: emph (str "foo") <> smallcaps (str "bar") =?> "*foobar*"
+          , "single quoted" =: singleQuoted "foo" =?> "‘foo’"
+          , "double quoted" =: doubleQuoted "foo" =?> "“foo”"
           -- Cite is trivial
           , testGroup "code"
-            [ "simple" =: code "foo" =?> "<code>foo</code>"
+            [ "simple" =: code "foo" =?> "=foo="
+            , "empty" =: code "" =?> "<code></code>"
+            , "space" =: code " " =?> "<code> </code>"
+            , "space at the beginning" =: code " foo" =?> "<code> foo</code>"
+            , "space at the end" =: code "foo " =?> "<code>foo </code>"
+            , "use tags for =" =: code "foo = bar" =?> "<code>foo = bar</code>"
             , "escape tag" =: code "<code>foo = bar</code> baz" =?> "<code><code>foo = bar<</code><code>/code> baz</code>"
-            , "normalization" =: code "</co" <> code "de>" =?> "<code><</code><code>/code></code>"
+            , "normalization with attributes" =: codeWith ("",["haskell"],[]) "foo" <> code "bar" =?> "=foobar="
+            , "code tag" =: code "<code>foo</code>" =?> "=<code>foo</code>="
+            , "normalization" =: code "</co" <> code "de>" <> code "=" =?> "<code><</code><code>/code>=</code>"
+            , "normalization with empty string" =: code "</co" <> str "" <> code "de>" <> code "=" =?> "<code><</code><code>/code>=</code>"
+            , "emphasized code" =: emph (code "foo") =?> "*=foo=*"
+            , "strong code" =: strong (code "foo") =?> "**=foo=**"
             ]
           , testGroup "spaces"
-            [ "space" =: text "a" <> space <> text "b" =?> "a b"
-            , "soft break" =: text "a" <> softbreak <> text "b" =?> "a b"
-            , test (museWithOpts def{ writerWrapText = WrapPreserve })
-                   "preserve soft break" $ text "a" <> softbreak <> text "b"
-                   =?> "a\nb"
-            , "line break" =: text "a" <> linebreak <> text "b" =?> "a<br>\nb"
+            [ "space" =: "a" <> space <> "b" =?> "a b"
+            , "soft break" =: "a" <> softbreak <> "b" =?> "a\nb"
+            , test (museWithOpts def{ writerWrapText = WrapNone })
+                   "remove soft break" $ "a" <> softbreak <> "b"
+                   =?> ("a b" :: String)
+            , "line break" =: "a" <> linebreak <> "b" =?> "a<br>\nb"
+            , "line break at the end" =: "a" <> linebreak =?> "a<br>"
+            , "no newline after line break in header" =: header 1 ("a" <> linebreak <> "b") =?> "* a<br>b"
+            , "no softbreak in header" =: header 1 ("a" <> softbreak <> "b") =?> "* a b"
             ]
           , testGroup "math"
             [ "inline math" =: math "2^3" =?> "2<sup>3</sup>"
-            , "display math" =: displayMath "2^3" =?> "<verse>2<sup>3</sup></verse>"
-            , "multiple letters in inline math" =: math "abc" =?> "<em>abc</em>"
+            , "display math" =: displayMath "2^3" =?> "2<sup>3</sup>"
+            , "multiple letters in inline math" =: math "abc" =?> "*abc*"
+            , "expand math before normalization" =: math "[" <> str "2]" =?> "<verbatim>[2]</verbatim>"
+            , "multiple math expressions inside one inline list" =: math "5_4" <> ", " <> displayMath "3^2" =?> "5<sub>4</sub>, 3<sup>2</sup>"
             ]
           , "raw inline"
             =: rawInline "html" "<mark>marked text</mark>"
@@ -336,34 +579,80 @@
                                                =?> "[[URL:1.png][Link to image]]"
             , "link to image without description" =: link "1.png" "" (str "1.png")
                                                   =?> "[[URL:1.png]]"
+
+            , testGroup "escape brackets in links"
+              [ "link with description"
+                =: link "https://example.com/foo].txt" "" (str "Description")
+                =?> "[[https://example.com/foo%5D.txt][Description]]"
+              , "link without description"
+                =: link "https://example.com/foo].txt" "" (str "https://example.com/foo].txt")
+                =?> "[[https://example.com/foo%5D.txt][<verbatim>https://example.com/foo].txt</verbatim>]]"
+              , "image link with description"
+                =: link "foo]bar.png" "" (str "Image link")
+                =?> "[[URL:foo%5Dbar.png][Image link]]"
+              , "image link without description"
+                =: link "foo]bar.png" "" (str "foo]bar.png")
+                =?> "[[URL:foo%5Dbar.png][<verbatim>foo]bar.png</verbatim>]]"
+              ]
             ]
           , "image" =: image "image.png" "Image 1" (str "") =?> "[[image.png][Image 1]]"
-          , "note" =: note (plain (text "Foo"))
+          , "image with width" =:
+            imageWith ("", [], [("width", "60%")]) "image.png" "Image" (str "") =?>
+            "[[image.png 60][Image]]"
+          , "left-aligned image with width" =:
+            imageWith ("", ["align-left"], [("width", "60%")]) "image.png" "Image" (str "") =?>
+            "[[image.png 60 l][Image]]"
+          , "right-aligned image with width" =:
+            imageWith ("", ["align-right"], [("width", "60%")]) "image.png" "Image" (str "") =?>
+            "[[image.png 60 r][Image]]"
+          , "escape brackets in image title" =: image "image.png" "Foo]bar" (str "") =?> "[[image.png][<verbatim>Foo]bar</verbatim>]]"
+          , "note" =: note (plain "Foo")
                    =?> unlines [ "[1]"
                                , ""
                                , "[1] Foo"
                                ]
-          , "span" =: spanWith ("",["foobar"],[]) (str "Some text")
-                   =?> "<class name=\"foobar\">Some text</class>"
+          , noteLocationTests
+          , "span with class" =: spanWith ("",["foobar"],[]) "Some text"
+                              =?> "<class name=\"foobar\">Some text</class>"
+          , "span without class" =: spanWith ("",[],[]) "Some text"
+                                 =?> "<class>Some text</class>"
+          , "span with anchor" =: spanWith ("anchor", [], []) mempty <> "Foo bar"
+                               =?> "#anchor Foo bar"
+          , "empty span with anchor" =: spanWith ("anchor", [], []) mempty
+                                     =?> "#anchor"
+          , "empty span without class and anchor" =: spanWith ("", [], []) mempty
+                                                  =?> "<class></class>"
+          , "span with class and anchor" =: spanWith ("anchor", ["foo"], []) "bar"
+                                         =?> "#anchor <class name=\"foo\">bar</class>"
+          , "adjacent spans" =: spanWith ("", ["syllable"], []) (str "wa") <>
+                                spanWith ("", ["syllable"], []) (str "ter")
+                             =?> "<class name=\"syllable\">wa</class><class name=\"syllable\">ter</class>"
+          , testGroup "RTL"
+            [ "RTL span" =: spanWith ("",[],[("dir", "rtl")]) (text "foo bar") =?> "<<<foo bar>>>"
+            , "LTR span" =: spanWith ("",[],[("dir", "ltr")]) (text "foo bar") =?> ">>>foo bar<<<"
+            , "RTL span with a class" =: spanWith ("",["foobar"],[("dir", "rtl")]) (text "foo bar") =?> "<class name=\"foobar\"><<<foo bar>>></class>"
+            , "LTR span with a class" =: spanWith ("",["foobar"],[("dir", "ltr")]) (text "foo bar") =?> "<class name=\"foobar\">>>>foo bar<<<</class>"
+            , "Escape <<< and >>>" =: plain (text "<<< foo bar >>>") =?> "<verbatim><<<</verbatim> foo bar <verbatim>>>></verbatim>"
+            ]
           , testGroup "combined"
             [ "emph word before" =:
-                para (text "foo" <> emph (text "bar")) =?>
+                para ("foo" <> emph "bar") =?>
                     "foo<em>bar</em>"
             , "emph word after" =:
-                para (emph (text "foo") <> text "bar") =?>
+                para (emph "foo" <> "bar") =?>
                     "<em>foo</em>bar"
             , "emph quoted" =:
-                para (doubleQuoted (emph (text "foo"))) =?>
-                    "\"<em>foo</em>\""
+                para (doubleQuoted (emph "foo")) =?>
+                    "“*foo*”"
             , "strong word before" =:
-                para (text "foo" <> strong (text "bar")) =?>
+                para ("foo" <> strong "bar") =?>
                     "foo<strong>bar</strong>"
             , "strong word after" =:
-                para (strong (text "foo") <> text "bar") =?>
+                para (strong "foo" <> "bar") =?>
                     "<strong>foo</strong>bar"
             , "strong quoted" =:
-                para (singleQuoted (strong (text "foo"))) =?>
-                    "'<strong>foo</strong>'"
+                para (singleQuoted (strong "foo")) =?>
+                    "‘**foo**’"
             ]
          ]
        ]
diff --git a/test/Tests/Writers/Native.hs b/test/Tests/Writers/Native.hs
--- a/test/Tests/Writers/Native.hs
+++ b/test/Tests/Writers/Native.hs
@@ -9,7 +9,7 @@
 
 p_write_rt :: Pandoc -> Bool
 p_write_rt d =
-  read (unpack $ purely (writeNative def{ writerTemplate = Just "" }) d) == d
+  read (unpack $ purely (writeNative def{ writerTemplate = Just mempty }) d) == d
 
 p_write_blocks_rt :: [Block] -> Bool
 p_write_blocks_rt bs =
@@ -18,5 +18,5 @@
 tests :: [TestTree]
 tests = [ testProperty "p_write_rt" p_write_rt
         , testProperty "p_write_blocks_rt" $ mapSize
-             (\x -> if x > 3 then 3 else x) $ p_write_blocks_rt
+             (\x -> if x > 3 then 3 else x) p_write_blocks_rt
         ]
diff --git a/test/Tests/Writers/OOXML.hs b/test/Tests/Writers/OOXML.hs
new file mode 100644
--- /dev/null
+++ b/test/Tests/Writers/OOXML.hs
@@ -0,0 +1,223 @@
+{-# LANGUAGE PatternGuards     #-}
+{-# LANGUAGE OverloadedStrings #-}
+
+module Tests.Writers.OOXML (ooxmlTest) where
+
+import Text.Pandoc hiding (Attr)
+import Test.Tasty
+import Test.Tasty.Golden.Advanced
+import Control.Applicative ((<|>))
+import Codec.Archive.Zip
+import Text.XML.Light
+import qualified Data.ByteString as BS
+import qualified Data.ByteString.Lazy as BL
+import Data.Foldable (asum)
+import qualified Data.Text.IO as T
+import Data.List (isSuffixOf, sort, (\\), intercalate, union)
+import Data.Maybe (catMaybes, mapMaybe)
+import Tests.Helpers
+import Data.Algorithm.Diff
+import System.FilePath.Glob (compile, match)
+
+compareXML :: Content -> Content -> Maybe XMLDifference
+-- We make a special exception for times at the moment, and just pass
+-- them because we can't control the utctime when running IO. Besides,
+-- so long as we have two times, we're okay.
+compareXML (Elem goodElem) (Elem myElem)
+  | (QName "created" _ (Just "dcterms")) <- elName myElem
+  , (QName "created" _ (Just "dcterms")) <- elName goodElem =
+      Nothing
+compareXML (Elem goodElem) (Elem myElem)
+  | (QName "modified" _ (Just "dcterms")) <- elName myElem
+  , (QName "modified" _ (Just "dcterms")) <- elName goodElem =
+      Nothing
+compareXML (Elem goodElem) (Elem myElem) =
+  (if elName myElem == elName goodElem
+   then Nothing
+   else Just
+    (ElemNamesDiffer
+     (Comparison {mine = elName myElem, good = elName goodElem}))
+  )
+  <|> (if sort (elAttribs myElem) == sort (elAttribs goodElem)
+   then Nothing
+   else Just
+    (ElemAttributesDiffer
+     (Comparison { mine = sort (elAttribs myElem)
+                 , good = sort (elAttribs goodElem)
+                 })))
+  <|> (if length (elContent myElem) == length (elContent goodElem)
+   then Nothing
+   else Just
+    (ElemChildrenDiffer
+      (Comparison { mine = elContent myElem, good = elContent goodElem})))
+  <|> asum (zipWith compareXML (elContent myElem) (elContent goodElem))
+compareXML (Text goodCData) (Text myCData) =
+  (if cdVerbatim myCData == cdVerbatim goodCData
+    && cdData myCData == cdData goodCData
+   then Nothing
+   else Just (CDatasDiffer (Comparison { mine = myCData, good = goodCData })))
+compareXML (CRef goodStr) (CRef myStr) =
+  if myStr == goodStr
+  then Nothing
+  else Just (CRefsDiffer (Comparison { mine = myStr, good = goodStr }))
+compareXML g m = Just (OtherContentsDiffer (Comparison {mine = m, good = g}))
+
+data XMLDifference
+  = ElemNamesDiffer (Comparison QName)
+  | ElemAttributesDiffer (Comparison [Attr])
+  | ElemChildrenDiffer (Comparison [Content])
+  | CDatasDiffer (Comparison CData)
+  | CRefsDiffer (Comparison String)
+  | OtherContentsDiffer (Comparison Content)
+  deriving (Show)
+
+data Comparison a = Comparison { good :: a, mine :: a }
+  deriving (Show)
+
+displayDiff :: Element -> Element -> String
+displayDiff elemA elemB =
+  showDiff (1,1)
+    (getDiff (lines $ ppElement elemA) (lines $ ppElement elemB))
+
+goldenArchive :: FilePath -> IO Archive
+goldenArchive fp = toArchive . BL.fromStrict <$> BS.readFile fp
+
+testArchive :: (WriterOptions -> Pandoc -> PandocIO BL.ByteString)
+            -> WriterOptions
+            -> FilePath
+            -> IO Archive
+testArchive writerFn opts fp = do
+  txt <- T.readFile fp
+  bs <- runIOorExplode $ do
+    setTranslations "en-US"
+    setVerbosity ERROR -- otherwise test output is confusingly noisy
+    readNative def txt >>= writerFn opts
+  return $ toArchive bs
+
+compareFileList :: FilePath -> Archive -> Archive -> Maybe String
+compareFileList goldenFP goldenArch testArch =
+  let testFiles = filesInArchive testArch
+      goldenFiles = filesInArchive goldenArch
+      diffTestGolden = testFiles \\ goldenFiles
+      diffGoldenTest = goldenFiles \\ testFiles
+
+      results =
+        [ if null diffGoldenTest
+          then Nothing
+          else Just $
+               "Files in " ++ goldenFP ++ " but not in generated archive:\n" ++
+               intercalate ", " diffGoldenTest
+        , if null diffTestGolden
+          then Nothing
+          else Just $
+               "Files in generated archive but not in " ++ goldenFP ++ ":\n" ++
+               intercalate ", " diffTestGolden
+        ]
+  in
+    if null $ catMaybes results
+    then Nothing
+    else Just $ intercalate "\n" $ catMaybes results
+
+compareXMLFile' :: FilePath -> Archive -> Archive -> Either String ()
+compareXMLFile' fp goldenArch testArch = do
+  testEntry <- case findEntryByPath fp testArch of
+                 Just entry -> Right entry
+                 Nothing -> Left $
+                   "Can't extract " ++ fp ++ " from generated archive"
+  testXMLDoc <- case parseXMLDoc $ fromEntry testEntry of
+                  Just doc -> Right doc
+                  Nothing -> Left $
+                    "Can't parse xml in  " ++ fp ++ " from generated archive"
+
+  goldenEntry <- case findEntryByPath fp goldenArch of
+                 Just entry -> Right entry
+                 Nothing -> Left $
+                   "Can't extract " ++ fp ++ " from archive in stored file"
+  goldenXMLDoc <- case parseXMLDoc $ fromEntry goldenEntry of
+                  Just doc -> Right doc
+                  Nothing -> Left $
+                    "Can't parse xml in  " ++ fp ++ " from archive in stored file"
+
+  let testContent = Elem testXMLDoc
+      goldenContent = Elem goldenXMLDoc
+      display difference = "Non-matching xml in "
+        ++ fp ++ ":\n"
+        ++ "* " ++ show difference ++ "\n"
+        ++ displayDiff testXMLDoc goldenXMLDoc
+
+
+  maybe (Right ()) (Left . display) (compareXML goldenContent testContent)
+
+compareXMLFile :: FilePath -> Archive -> Archive -> Maybe String
+compareXMLFile fp goldenArch testArch =
+  case compareXMLFile' fp goldenArch testArch of
+    Right _ -> Nothing
+    Left s -> Just s
+
+compareAllXMLFiles :: Archive -> Archive -> Maybe String
+compareAllXMLFiles goldenArch testArch =
+  let allFiles = filesInArchive goldenArch `union` filesInArchive testArch
+      allXMLFiles = sort $
+        filter
+        (\fp -> ".xml" `isSuffixOf` fp || ".rels" `isSuffixOf` fp)
+        allFiles
+      results =
+        mapMaybe (\fp -> compareXMLFile fp goldenArch testArch) allXMLFiles
+  in
+    if null results
+    then Nothing
+    else Just $ unlines results
+
+compareMediaFile' :: FilePath -> Archive -> Archive -> Either String ()
+compareMediaFile' fp goldenArch testArch = do
+  testEntry <- case findEntryByPath fp testArch of
+                 Just entry -> Right entry
+                 Nothing -> Left $
+                   "Can't extract " ++ fp ++ " from generated archive"
+  goldenEntry <- case findEntryByPath fp goldenArch of
+                 Just entry -> Right entry
+                 Nothing -> Left $
+                   "Can't extract " ++ fp ++ " from archive in stored file"
+
+  if fromEntry testEntry == fromEntry goldenEntry
+    then Right ()
+    else Left $
+    "Non-matching binary file: " ++ fp
+
+compareMediaFile :: FilePath -> Archive -> Archive -> Maybe String
+compareMediaFile fp goldenArch testArch =
+  case compareMediaFile' fp goldenArch testArch of
+    Right _ -> Nothing
+    Left s -> Just s
+
+compareAllMediaFiles :: Archive -> Archive -> Maybe String
+compareAllMediaFiles goldenArch testArch =
+  let allFiles = filesInArchive goldenArch `union` filesInArchive testArch
+      mediaPattern = compile "*/media/*"
+      allMediaFiles = sort $
+        filter (match mediaPattern) allFiles
+      results =
+        mapMaybe (\fp -> compareMediaFile fp goldenArch testArch) allMediaFiles
+  in
+    if null results
+    then Nothing
+    else Just $ unlines results
+
+ooxmlTest :: (WriterOptions -> Pandoc -> PandocIO BL.ByteString)
+          -> String
+          -> WriterOptions
+          -> FilePath
+          -> FilePath
+          -> TestTree
+ooxmlTest writerFn testName opts nativeFP goldenFP =
+  goldenTest
+  testName
+  (goldenArchive goldenFP)
+  (testArchive writerFn opts nativeFP)
+  (\goldenArch testArch ->
+     let res = catMaybes [ compareFileList goldenFP goldenArch testArch
+                         , compareAllXMLFiles goldenArch testArch
+                         , compareAllMediaFiles goldenArch testArch
+                         ]
+     in return $ if null res then Nothing else Just $ unlines res)
+  (\a -> BL.writeFile goldenFP $ fromArchive a)
diff --git a/test/Tests/Writers/Org.hs b/test/Tests/Writers/Org.hs
--- a/test/Tests/Writers/Org.hs
+++ b/test/Tests/Writers/Org.hs
@@ -1,25 +1,89 @@
 {-# LANGUAGE OverloadedStrings #-}
 module Tests.Writers.Org (tests) where
 
+import Data.Text as T
 import Test.Tasty
+import Test.Tasty.HUnit (HasCallStack)
 import Tests.Helpers
 import Text.Pandoc
 import Text.Pandoc.Arbitrary ()
 import Text.Pandoc.Builder
 
 infix 4 =:
-(=:) :: (ToString a, ToPandoc a)
-     => String -> (a, String) -> TestTree
-(=:) = test (purely (writeOrg def . toPandoc))
+(=:) :: (ToString a, ToPandoc a, HasCallStack)
+     => String -> (a, Text) -> TestTree
+(=:) = test org
 
+defopts :: WriterOptions
+defopts = def
+  { writerExtensions = getDefaultExtensions "org"
+  }
+
+org :: (ToPandoc a) => a -> Text
+org = orgWithOpts defopts
+
+orgWithOpts :: (ToPandoc a) => WriterOptions -> a -> Text
+orgWithOpts opts x = purely (writeOrg opts) $ toPandoc x
+
+
 tests :: [TestTree]
-tests = [ testGroup "links"
-          -- See http://orgmode.org/manual/Internal-links.html#Internal-links
-          [ "simple link"
-              =: link "/url" "" "foo"
-              =?> "[[/url][foo]]"
-          , "internal link to anchor"
-              =: link "#my-custom-id" "" "#my-custom-id"
-              =?> "[[#my-custom-id]]"
+tests =
+  [ testGroup "links"
+    -- See http://orgmode.org/manual/Internal-links.html#Internal-links
+    [ "simple link"
+      =: link "/url" "" "foo"
+      =?> "[[/url][foo]]"
+    , "internal link to anchor"
+      =: link "#my-custom-id" "" "#my-custom-id"
+      =?> "[[#my-custom-id]]"
+    ]
+
+  , testGroup "lists"
+    [ "bullet task list"
+      =: bulletList [plain "☐ a", plain "☒ b"]
+      =?> T.unlines
+          [ "- [ ] a"
+          , "- [X] b"
           ]
-        ]
+    , "ordered task list"
+      =: orderedList [plain ("☐" <> space <> "a"), plain "☒ b"]
+      =?> T.unlines
+          [ "1. [ ] a"
+          , "2. [X] b"
+          ]
+    , "ordered task list with starting number"
+      =: orderedListWith
+         (9, DefaultStyle, DefaultDelim)
+         [plain ("☐" <> space <> "a"), plain "☒ b"]
+      =?> T.unlines
+          [ "9. [@9] [ ] a"
+          , "10. [X] b"
+          ]
+    , test (orgWithOpts def) "bullet without task_lists" $
+      bulletList [plain "☐ a", plain "☒ b"]
+      =?> T.unlines
+          [ "- ☐ a"
+          , "- ☒ b"
+          ]
+    ]
+
+  , testGroup "code blocks"
+    [ "identifier"
+      =: codeBlockWith ("abc", ["python"], []) "return True"
+      =?> T.unlines
+      [ "#+name: abc"
+      , "#+begin_src python"
+      , "return True"
+      , "#+end_src"
+      ]
+
+    , "attributes"
+      =: codeBlockWith ("", ["python"], [("cache", "yes"), ("noweb", "yes")])
+                       "'Hello'"
+      =?> T.unlines
+      [ "#+begin_src python :cache yes :noweb yes"
+      , "'Hello'"
+      , "#+end_src"
+      ]
+    ]
+  ]
diff --git a/test/Tests/Writers/Plain.hs b/test/Tests/Writers/Plain.hs
--- a/test/Tests/Writers/Plain.hs
+++ b/test/Tests/Writers/Plain.hs
@@ -2,6 +2,7 @@
 module Tests.Writers.Plain (tests) where
 
 import Test.Tasty
+import Test.Tasty.HUnit (HasCallStack)
 import Tests.Helpers
 import Text.Pandoc
 import Text.Pandoc.Arbitrary ()
@@ -9,9 +10,11 @@
 
 
 infix 4 =:
-(=:) :: (ToString a, ToPandoc a)
+(=:) :: (ToString a, ToPandoc a, HasCallStack)
      => String -> (a, String) -> TestTree
-(=:) = test (purely (writePlain def) . toPandoc)
+(=:) = test (purely (writePlain def{ writerExtensions =
+                          enableExtension Ext_gutenberg plainExtensions }) .
+                      toPandoc)
 
 
 tests :: [TestTree]
diff --git a/test/Tests/Writers/Powerpoint.hs b/test/Tests/Writers/Powerpoint.hs
--- a/test/Tests/Writers/Powerpoint.hs
+++ b/test/Tests/Writers/Powerpoint.hs
@@ -1,101 +1,296 @@
-{-# LANGUAGE OverloadedStrings #-}
-
 module Tests.Writers.Powerpoint (tests) where
 
-import Control.Exception (throwIO)
+import Control.Arrow ((***))
+import Tests.Writers.OOXML (ooxmlTest)
 import Text.Pandoc
-import Text.Pandoc.Builder
 import Test.Tasty
-import Test.Tasty.HUnit
-import Codec.Archive.Zip
-import Data.List (isPrefixOf, isSuffixOf)
+import System.FilePath
+import Text.DocTemplates (ToContext(toVal), Context(..))
+import qualified Data.Map as M
+import Data.Text (pack)
 
------ Number of Slides -----------
+-- templating is important enough, and can break enough things, that
+-- we want to run all our tests with both default formatting and a
+-- template.
 
-numberOfSlides :: WriterOptions -> Pandoc -> IO Int
-numberOfSlides opts pd = do
-  mbs <- runIO $
-        do setUserDataDir $ Just "../data"
-           writePowerpoint opts pd
-  case mbs of
-       Left e   -> throwIO e
-       Right bs -> do
-         let archive = toArchive bs
-         return $
-           length $
-           filter (isSuffixOf ".xml") $
-           filter (isPrefixOf "ppt/slides/slide") $
-           filesInArchive archive
+modifyPptxName :: FilePath -> String -> FilePath
+modifyPptxName fp suffix =
+  addExtension (takeDirectory fp ++ suffix) "pptx"
 
-testNumberOfSlides :: TestName -> Int -> WriterOptions -> Pandoc -> TestTree
-testNumberOfSlides name n opts pd =
-  testCase name $ do
-    n' <- numberOfSlides opts pd
-    n' @=? n
+pptxTests :: String -> WriterOptions -> FilePath -> FilePath -> (TestTree, TestTree)
+pptxTests name opts native pptx =
+  let referenceDoc = "pptx/reference-depth.pptx"
+  in
+    ( ooxmlTest
+      writePowerpoint
+      name
+      opts{writerReferenceDoc=Nothing}
+      native
+      pptx
+    , ooxmlTest
+      writePowerpoint
+      name
+      opts{writerReferenceDoc=Just referenceDoc}
+      native
+      (modifyPptxName pptx "/templated")
+    )
 
-numSlideTests :: TestTree
-numSlideTests = testGroup "Number of slides in output"
-  [ testNumberOfSlides
-    "simple one-slide deck" 1
-    def
-    (doc $ para "foo")
-  , testNumberOfSlides
-    "with metadata (header slide)" 2
-    def
-    (setTitle "My Title" $ doc $ para "foo")
-  , testNumberOfSlides
-    "With h1 slide (using default slide-level)" 2
-    def
-    (doc $ header 1 "Header" <> para "foo")
-  , testNumberOfSlides
-    "With h2 slide (using default slide-level)" 2
-    def
-    (doc $ header 1 "Header" <> header 2 "subeader" <> para "foo")
-  , testNumberOfSlides
-    "With h1 slide (using default slide-level)" 2
-    def
-    (doc $ header 1 "Header" <> para "foo")
-  , testNumberOfSlides
-    "With h2 slide (using default slide-level)" 2
-    def
-    (doc $ header 1 "Header" <> header 2 "subeader" <> para "foo")
-  , testNumberOfSlides
-    "With image slide, no header" 3
-    def
-    (doc $
-      para "first slide" <>
-      (para $ image "lalune.jpg" "" "") <>
-      para "foo")
-  , testNumberOfSlides
-    "With image slide, header" 3
-    def
-    (doc $
-      para "first slide" <>
-      header 2 "image header" <>
-      (para $ image "lalune.jpg" "" "") <>
-      para "foo")
-  , testNumberOfSlides
-    "With table, no header" 3
-    def
-    (doc $
-     para "first slide" <>
-     (simpleTable [para "foo" <> para "bar"] [[para "this" <> para "that"]]) <>
-     para "foo")
-  , testNumberOfSlides
-    "With table, header" 3
-    def
-    (doc $
-     para "first slide" <>
-     header 2 "table header" <>
-     (simpleTable [para "foo" <> para "bar"] [[para "this" <> para "that"]]) <>
-     para "foo")
-  , testNumberOfSlides
-    "hrule" 2
-    def
-    (doc $
-     para "first slide" <> horizontalRule <> para "last slide")
-  ]
+groupPptxTests :: [(TestTree, TestTree)] -> [TestTree]
+groupPptxTests pairs =
+  let (noRefs, refs) = unzip pairs
+  in
+    [ testGroup "Default slide formatting" noRefs
+    , testGroup "With `--reference-doc` pptx file" refs
+    ]
 
+testGroup' :: String -> [(TestTree, TestTree)] -> (TestTree, TestTree)
+testGroup' descr = (testGroup descr *** testGroup descr) . unzip
 
+
 tests :: [TestTree]
-tests = [numSlideTests]
+tests = let
+  regularTests = groupPptxTests
+    [ pptxTests "Inline formatting"
+      def
+      "pptx/inline-formatting/input.native"
+      "pptx/inline-formatting/output.pptx"
+    , pptxTests "Slide breaks (default slide-level)"
+      def
+      "pptx/slide-breaks/input.native"
+      "pptx/slide-breaks/output.pptx"
+    , pptxTests "slide breaks (slide-level set to 1)"
+      def{ writerSlideLevel = Just 1 }
+      "pptx/slide-breaks/input.native"
+      "pptx/slide-breaks-slide-level-1/output.pptx"
+    , pptxTests "lists"
+      def
+      "pptx/lists/input.native"
+      "pptx/lists/output.pptx"
+    , pptxTests "start ordered list at specified num"
+      def
+      "pptx/start-numbering-at/input.native"
+      "pptx/start-numbering-at/output.pptx"
+    , pptxTests "List continuation paragraph indentation"
+      def
+      "pptx/list-level/input.native"
+      "pptx/list-level/output.pptx"
+    , pptxTests "tables"
+      def
+      "pptx/tables/input.native"
+      "pptx/tables/output.pptx"
+    , pptxTests "table of contents"
+      def{ writerTableOfContents = True }
+      "pptx/slide-breaks/input.native"
+      "pptx/slide-breaks-toc/output.pptx"
+    , pptxTests "end notes"
+      def
+      "pptx/endnotes/input.native"
+      "pptx/endnotes/output.pptx"
+    , pptxTests "end notes, with table of contents"
+      def { writerTableOfContents = True }
+      "pptx/endnotes/input.native"
+      "pptx/endnotes-toc/output.pptx"
+    , pptxTests "images"
+      def
+      "pptx/images/input.native"
+      "pptx/images/output.pptx"
+    , pptxTests "two-column layout"
+      def
+      "pptx/two-column/all-text/input.native"
+      "pptx/two-column/all-text/output.pptx"
+    , pptxTests "two-column (not comparison)"
+      def
+      "pptx/two-column/text-and-image/input.native"
+      "pptx/two-column/text-and-image/output.pptx"
+    , pptxTests "single column text"
+      def
+      "pptx/single-column/text/input.native"
+      "pptx/single-column/text/output.pptx"
+    , pptxTests "single column image"
+      def
+      "pptx/single-column/image/input.native"
+      "pptx/single-column/image/output.pptx"
+    , pptxTests "speaker notes"
+      def
+      "pptx/speaker-notes/input.native"
+      "pptx/speaker-notes/output.pptx"
+    , pptxTests "speaker notes after a separating block"
+      def
+      "pptx/speaker-notes-afterseps/input.native"
+      "pptx/speaker-notes-afterseps/output.pptx"
+    , pptxTests "speaker notes after a separating header"
+      def
+      "pptx/speaker-notes-afterheader/input.native"
+      "pptx/speaker-notes-afterheader/output.pptx"
+    , pptxTests "speaker notes after metadata"
+      def
+      "pptx/speaker-notes-after-metadata/input.native"
+      "pptx/speaker-notes-after-metadata/output.pptx"
+    , pptxTests "speaker notes from metadata field"
+      def
+      "pptx/metadata-speaker-notes/input.native"
+      "pptx/metadata-speaker-notes/output.pptx"
+    , pptxTests "remove empty slides"
+      def
+      "pptx/remove-empty-slides/input.native"
+      "pptx/remove-empty-slides/output.pptx"
+    , pptxTests "raw ooxml"
+      def
+      "pptx/raw-ooxml/input.native"
+      "pptx/raw-ooxml/output.pptx"
+    , pptxTests "metadata, custom properties"
+      def
+      "pptx/document-properties/input.native"
+      "pptx/document-properties/output.pptx"
+    , pptxTests "metadata, short description"
+      def
+      "pptx/document-properties-short-desc/input.native"
+      "pptx/document-properties-short-desc/output.pptx"
+    , pptxTests "inline code and code blocks"
+      def
+      "pptx/code/input.native"
+      "pptx/code/output.pptx"
+    , pptxTests "inline code and code blocks, custom formatting"
+      def { writerVariables = Context $ M.fromList
+              [(pack "monofont", toVal $ pack "Consolas")] }
+      "pptx/code/input.native"
+      "pptx/code-custom/output.pptx"
+    , testGroup' "Using slide level 0, if the first thing on a slide is"
+      [ pptxTests ("a h1 it's used as the slide title")
+        def { writerSlideLevel = Just 0 }
+        "pptx/slide-level-0/h1-with-image/input.native"
+        "pptx/slide-level-0/h1-with-image/output.pptx"
+      , pptxTests ("a h2 it's used as the "
+                   <> "slide title")
+        def { writerSlideLevel = Just 0 }
+        "pptx/slide-level-0/h2-with-image/input.native"
+        "pptx/slide-level-0/h2-with-image/output.pptx"
+      , testGroup' "a heading it's used as the slide title"
+        [ pptxTests "(works with a table)"
+          def { writerSlideLevel = Just 0 }
+          "pptx/slide-level-0/h1-with-table/input.native"
+          "pptx/slide-level-0/h1-with-table/output.pptx"
+        , pptxTests ("(content with caption layout)")
+          def { writerSlideLevel = Just 0 }
+          "pptx/slide-level-0/h1-h2-with-table/input.native"
+          "pptx/slide-level-0/h1-h2-with-table/output.pptx"
+        ]
+      ]
+    , testGroup' "comparison layout"
+      [ testGroup' "comparison layout is used..."
+        [ pptxTests "when two columns contain text + non-text"
+          def
+          "pptx/comparison/both-columns/input.native"
+          "pptx/comparison/both-columns/output.pptx"
+        , pptxTests "even when only one col contains text + non-text"
+          def
+          "pptx/comparison/one-column/input.native"
+          "pptx/comparison/one-column/output.pptx"
+        ]
+      , testGroup' "extra ... in one column gets overlaid"
+        [ pptxTests "text"
+          def
+          "pptx/comparison/extra-text/input.native"
+          "pptx/comparison/extra-text/output.pptx"
+        , pptxTests "image"
+          def
+          "pptx/comparison/extra-image/input.native"
+          "pptx/comparison/extra-image/output.pptx"
+        ]
+      , pptxTests "is not used if the non-text comes first"
+        def
+        "pptx/comparison/non-text-first/input.native"
+        "pptx/comparison/non-text-first/output.pptx"
+      ]
+    , testGroup' "Content with Caption layout is ..."
+      [ pptxTests "used for heading, text, image on the same slide"
+        def
+        "pptx/content-with-caption/heading-text-image/input.native"
+        "pptx/content-with-caption/heading-text-image/output.pptx"
+      , pptxTests "used for text and an image on the same slide"
+        def
+        "pptx/content-with-caption/text-image/input.native"
+        "pptx/content-with-caption/text-image/output.pptx"
+      , pptxTests "not used if the image comes first"
+        def
+        "pptx/content-with-caption/image-text/input.native"
+        "pptx/content-with-caption/image-text/output.pptx"
+      ]
+    , testGroup' "The Blank layout is used if a slide contains only..."
+      [ pptxTests "speaker notes"
+        def
+        "pptx/blanks/just-speaker-notes/input.native"
+        "pptx/blanks/just-speaker-notes/output.pptx"
+      , pptxTests "an empty heading with a body of only NBSPs"
+        def
+        "pptx/blanks/nbsp-in-body/input.native"
+        "pptx/blanks/nbsp-in-body/output.pptx"
+      , pptxTests "a heading containing only non-breaking spaces"
+        def
+        "pptx/blanks/nbsp-in-heading/input.native"
+        "pptx/blanks/nbsp-in-heading/output.pptx"
+      ]
+    , pptxTests ("Incremental lists are supported")
+      def { writerIncremental = True }
+      "pptx/incremental-lists/with-flag/input.native"
+      "pptx/incremental-lists/with-flag/output.pptx"
+    , pptxTests ("One-off incremental lists are supported")
+      def
+      "pptx/incremental-lists/without-flag/input.native"
+      "pptx/incremental-lists/without-flag/output.pptx"
+    , pptxTests "Background images"
+      def
+      "pptx/background-image/input.native"
+      "pptx/background-image/output.pptx"
+    ]
+  referenceSpecificTests =
+    [ ooxmlTest
+      writePowerpoint
+      "Basic footer"
+      def { writerReferenceDoc = Just "pptx/footer/basic/reference.pptx"}
+      "pptx/footer/input.native"
+      "pptx/footer/basic/output.pptx"
+    , ooxmlTest
+      writePowerpoint
+      "Footer with fixed date, replaced by meta block date"
+      def { writerReferenceDoc = Just "pptx/footer/fixed-date/reference.pptx"}
+      "pptx/footer/input.native"
+      "pptx/footer/fixed-date/output.pptx"
+    , ooxmlTest
+      writePowerpoint
+      "Footer not shown on title slide"
+      def { writerReferenceDoc = Just "pptx/footer/no-title-slide/reference.pptx"}
+      "pptx/footer/input.native"
+      "pptx/footer/no-title-slide/output.pptx"
+    , ooxmlTest
+      writePowerpoint
+      "Footer with slide number starting from 3"
+      def { writerReferenceDoc = Just "pptx/footer/higher-slide-number/reference.pptx"}
+      "pptx/footer/input.native"
+      "pptx/footer/higher-slide-number/output.pptx"
+    , ooxmlTest
+      writePowerpoint
+      "Layouts can be moved around in reference doc"
+      def {writerReferenceDoc = Just "pptx/reference-moved-layouts.pptx"}
+      "pptx/layouts/input.native"
+      "pptx/layouts/moved.pptx"
+    , ooxmlTest
+      writePowerpoint
+      "Layouts can be missing from the reference doc"
+      def {writerReferenceDoc = Just "pptx/reference-deleted-layouts.pptx"}
+      "pptx/layouts/input.native"
+      "pptx/layouts/deleted.pptx"
+    , ooxmlTest
+      writePowerpoint
+      "Slides can be missing from the reference doc"
+      def {writerReferenceDoc = Just "pptx/reference-no-slides.pptx"}
+      "pptx/reference-no-slides/add-slides/input.native"
+      "pptx/reference-no-slides/add-slides/output.pptx"
+    , ooxmlTest
+      writePowerpoint
+      "Notes are placed at the right position with a reference doc without slides"
+      def {writerReferenceDoc = Just "pptx/reference-no-slides.pptx"}
+      "pptx/reference-no-slides/with-notes/input.native"
+      "pptx/reference-no-slides/with-notes/output.pptx"
+    ]
+  in regularTests <> referenceSpecificTests
diff --git a/test/Tests/Writers/RST.hs b/test/Tests/Writers/RST.hs
--- a/test/Tests/Writers/RST.hs
+++ b/test/Tests/Writers/RST.hs
@@ -1,45 +1,112 @@
 {-# LANGUAGE OverloadedStrings #-}
 module Tests.Writers.RST (tests) where
 
+import Control.Monad.Identity
 import Test.Tasty
+import Test.Tasty.HUnit
 import Tests.Helpers
 import Text.Pandoc
 import Text.Pandoc.Arbitrary ()
 import Text.Pandoc.Builder
+import Text.Pandoc.Writers.RST
+import qualified Data.Text as T
 
 infix 4 =:
-(=:) :: (ToString a, ToPandoc a)
+(=:) :: (ToString a, ToPandoc a, HasCallStack)
      => String -> (a, String) -> TestTree
 (=:) = test (purely (writeRST def . toPandoc))
 
+testTemplate :: (ToString a, ToString c, ToPandoc a) =>
+                String -> String -> (a, c) -> TestTree
+testTemplate t = case runIdentity (compileTemplate [] (T.pack t)) of
+    Left e -> error $ "Could not compile RST template: " ++ e
+    Right templ -> test (purely (writeRST def{ writerTemplate = Just templ }) . toPandoc)
+
+bodyTemplate :: Template T.Text
+bodyTemplate = case runIdentity (compileTemplate [] "$body$\n") of
+                    Left e      -> error $
+                      "Could not compile RST bodyTemplate" ++ e
+                    Right templ -> templ
+
 tests :: [TestTree]
 tests = [ testGroup "rubrics"
           [ "in list item" =:
               bulletList [header 2 (text "foo")] =?>
-              "-  .. rubric:: foo"
+              "- .. rubric:: foo"
           , "in definition list item" =:
               definitionList [(text "foo", [header 2 (text "bar"),
                                             para $ text "baz"])] =?>
               unlines
               [ "foo"
-              , "    .. rubric:: bar"
+              , "   .. rubric:: bar"
               , ""
-              , "    baz"]
+              , "   baz"]
           , "in block quote" =:
               blockQuote (header 1 (text "bar")) =?>
-              "    .. rubric:: bar"
+              "   .. rubric:: bar"
           , "with id" =:
               blockQuote (headerWith ("foo",[],[]) 1 (text "bar")) =?>
               unlines
-              [ "    .. rubric:: bar"
-              , "       :name: foo"]
+              [ "   .. rubric:: bar"
+              , "      :name: foo"]
           , "with id class" =:
               blockQuote (headerWith ("foo",["baz"],[]) 1 (text "bar")) =?>
               unlines
-              [ "    .. rubric:: bar"
-              , "       :name: foo"
-              , "       :class: baz"]
+              [ "   .. rubric:: bar"
+              , "      :name: foo"
+              , "      :class: baz"]
           ]
+        , testGroup "ligatures" -- handling specific sequences of blocks
+          [ "a list is closed by a comment before a quote" =: -- issue 4248
+            bulletList [plain "bulleted"] <> blockQuote (plain "quoted") =?>
+              unlines
+              [ "- bulleted"
+              , ""
+              , ".."
+              , ""
+              , "   quoted"]
+          ]
+        , testGroup "flatten"
+          [ testCase "emerges nested styles as expected" $
+            flatten (Emph [Str "1", Strong [Str "2"], Str "3"]) @?=
+            [Emph [Str "1"], Strong [Str "2"], Emph [Str "3"]]
+          , testCase "could introduce trailing spaces" $
+            flatten (Emph [Str "f", Space, Strong [Str "2"]]) @?=
+            [Emph [Str "f", Space], Strong [Str "2"]]
+            -- the test above is the reason why we call
+            -- stripLeadingTrailingSpace through transformNested after
+            -- flatten
+          , testCase "preserves empty parents" $
+            flatten (Image ("",[],[]) [] ("loc","title")) @?=
+            [Image ("",[],[]) [] ("loc","title")]
+          ]
+        , testGroup "inlines"
+          [ "are removed when empty" =: -- #4434
+            plain (strong (str "")) =?> ""
+          , "do not cause the introduction of extra spaces when removed" =:
+            plain (strong (str "") <> emph (str "text")) =?> "*text*"
+          , "spaces are stripped at beginning and end" =:
+            -- pandoc issue 4327 "The text within inline markup may not
+            -- begin or end with whitespace"
+            -- http://docutils.sourceforge.net/docs/ref/rst/restructuredtext.html#inline-markup
+            strong (space <> str "text" <> space <> space) =?> "**text**"
+          , "single space stripped" =:
+            strong space =?> ""
+          , "give priority to strong style over emphasis" =:
+            strong (emph (strong (str "s"))) =?> "**s**"
+          , "links are not elided by outer style" =:
+            strong (emph (link "loc" "" (str "text"))) =?>
+            "`text <loc>`__"
+          , "RST inlines cannot start nor end with spaces" =:
+            emph (str "f" <> strong (space <> str "d" <> space) <> str "l") =?>
+            "*f* **d** *l*"
+          , "keeps quotes" =:
+            strong (str "f" <> doubleQuoted (str "d") <> str "l") =?>
+            "**f“d”l**"
+          , "backslash inserted between str and code" =:
+            str "/api?query=" <> code "foo" =?>
+            "/api?query=\\ ``foo``"
+          ]
         , testGroup "headings"
           [ "normal heading" =:
               header 1 (text "foo") =?>
@@ -47,7 +114,8 @@
               [ "foo"
               , "==="]
           -- note: heading normalization is only done in standalone mode
-          , test (purely (writeRST def{ writerTemplate = Just "$body$\n" }) . toPandoc)
+          , test (purely (writeRST def{ writerTemplate = Just bodyTemplate })
+                       . toPandoc)
             "heading levels" $
               header 1 (text "Header 1") <>
               header 3 (text "Header 2") <>
@@ -77,7 +145,7 @@
               , ""
               , "Header 2"
               , "--------"]
-          , test (purely (writeRST def{ writerTemplate = Just "$body$\n" }) . toPandoc)
+          , test (purely (writeRST def{ writerTemplate = Just bodyTemplate }) . toPandoc)
             "minimal heading levels" $
               header 2 (text "Header 1") <>
               header 3 (text "Header 2") <>
@@ -104,4 +172,7 @@
               , "Header 2"
               , "--------"]
           ]
+        , testTemplate "$subtitle$\n" "subtitle" $
+          setMeta "subtitle" ("subtitle" :: Inlines) (doc $ plain "") =?>
+          ("subtitle" :: String)
         ]
diff --git a/test/Tests/Writers/TEI.hs b/test/Tests/Writers/TEI.hs
--- a/test/Tests/Writers/TEI.hs
+++ b/test/Tests/Writers/TEI.hs
@@ -2,6 +2,7 @@
 module Tests.Writers.TEI (tests) where
 
 import Test.Tasty
+import Test.Tasty.HUnit (HasCallStack)
 import Tests.Helpers
 import Text.Pandoc
 import Text.Pandoc.Arbitrary ()
@@ -20,7 +21,7 @@
 -}
 
 infix 4 =:
-(=:) :: (ToString a, ToPandoc a)
+(=:) :: (ToString a, ToPandoc a, HasCallStack)
      => String -> (a, String) -> TestTree
 (=:) = test (purely (writeTEI def) . toPandoc)
 
@@ -31,7 +32,7 @@
           ]
         , testGroup "inlines"
           [
-            "Emphasis"      =:  emph ("emphasized")
+            "Emphasis"      =:  emph "emphasized"
                             =?> "<p><hi rendition=\"simple:italic\">emphasized</hi></p>"
            ,"SingleQuoted"  =:  singleQuoted (text "quoted material")
                             =?> "<p><quote>quoted material</quote></p>"
diff --git a/test/Tests/XML.hs b/test/Tests/XML.hs
new file mode 100644
--- /dev/null
+++ b/test/Tests/XML.hs
@@ -0,0 +1,28 @@
+{-# LANGUAGE OverloadedStrings #-}
+{- |
+--   Module      : Tests.XML
+--   Copyright   : Copyright (C) 2025- Massimiliano Farinella and John MacFarlane
+--   License     : GNU GPL, version 2 or above
+--
+--   Maintainer  : Massimiliano Farinella <massifrg@gmail.com>
+--   Stability   : WIP
+--   Portability : portable
+Runs a roundtrip conversion of an AST trough the XML format:
+- first from AST to XML (XML Writer),
+- then back to AST (XML Reader),
+- and checks that the two ASTs are the same
+-}
+module Tests.XML (tests) where
+
+import Control.Monad ((>=>))
+import Test.Tasty (TestTree)
+import Test.Tasty.QuickCheck
+import Tests.Helpers
+import Text.Pandoc
+import Text.Pandoc.Arbitrary ()
+
+p_xml_roundtrip :: Pandoc -> Bool
+p_xml_roundtrip d = d == purely (writeXML def {writerTemplate = Just mempty} >=> readXML def) d
+
+tests :: [TestTree]
+tests = [testProperty "p_xml_roundtrip" p_xml_roundtrip]
diff --git a/test/ansi-test.ansi b/test/ansi-test.ansi
new file mode 100644
--- /dev/null
+++ b/test/ansi-test.ansi
@@ -0,0 +1,122 @@
+[1m[23m[39m[49m[24m[29mLEVEL 1 HEADING[0m
+
+Text
+
+[1m[23m[39m[49m[24m[29mLevel 2 heading[0m
+
+Text
+
+[22m[3m[39m[49m[24m[29mLevel 3 heading[0m
+
+Text
+
+[22m[3m[39m[49m[24m[29mLevel 4 heading[0m
+
+Text
+
+[22m[3m[39m[49m[24m[29mLevel 5 heading[0m
+
+Text
+
+• list
+
+  • nested
+
+    1) numbered
+
+       continuation paragraph
+
+[22m[23m[36m[49m[4m[29m]8;;http://example.com\link[0m]8;;\
+
+[22m[23m[36m[49m[4m[29m]8;;mailto:mail@example.com\mail@example.com[0m]8;;\
+
+│ Block quote
+│
+│ │ Nested block quote
+
+Multiline table with caption:
+
+Centered    Left       Right        Default aligned
+Header      Aligned    Aligned      
+─────────── ────────── ──────────── ──────────────────────────
+First       row        12.0         Example of a row that
+                                    spans multiple lines.
+Second      row        5.0          Here’s another one. Note
+                                    the blank line between
+                                    rows.
+─────────── ────────── ──────────── ──────────────────────────
+
+  Here’s the caption. It may span multiple lines.
+
+Multiline table without caption:
+
+Centered    Left       Right        Default aligned
+Header      Aligned    Aligned      
+─────────── ────────── ──────────── ──────────────────────────
+First       row        12.0         Example of a row that
+                                    spans multiple lines.
+Second      row        5.0          Here’s another one. Note
+                                    the blank line between
+                                    rows.
+─────────── ────────── ──────────── ──────────────────────────
+
+Table without column headers:
+
+───────────────── ───────────────── ───────────────── ─────────────────
+12                12                12                12
+123               123               123               123
+1                 1                 1                 1
+───────────────── ───────────────── ───────────────── ─────────────────
+
+Footnote¹
+
+Multiple blocks in a cell
+
+────────────────── ─────────── ────────────
+[1m[23m[39m[49m[24m[29mCOL 1[0m              [1m[23m[39m[49m[24m[29mCOL 2[0m       [1m[23m[39m[49m[24m[29mCOL 3[0m
+                               
+col 1              col 2       col 3
+r1 a               • b         c c 2 c 2
+                               
+r1 bis             • b 2       
+                               
+                   • b 2       
+────────────────── ─────────── ────────────
+
+East Asian characters have double width
+
+── ────
+魚 fish
+── ────
+
+This is inline code: [22m[23m[31m[47m[24m[29m x >>= y ++ 3 [0m.
+
+    [22m[23m[31m[49m[24m[29mcode block[0m
+    [22m[23m[31m[49m[24m[29m   >>> ## ``[0m
+
+Highlighted:
+
+    [0m[0m[22;23;24m[31;22;23;24m<[0m[22;23;24m[32;1;23;24mp[0m[22;23;24m[31;22;23;24m><[0m[22;23;24m[32;1;23;24ma[0m[22;23;24m[32;22;23;24m href[0m[22;23;24m[90;22;23;24m=[0m[22;23;24m[36;22;23;24m"foobar"[0m[22;23;24m[32;22;23;24m title[0m[22;23;24m[90;22;23;24m=[0m[22;23;24m[36;22;23;24m"title"[0m[22;23;24m[31;22;23;24m>[0m[22;23;24m[0m[22;23;24mThis is a link[0m[22;23;24m[31;22;23;24m</[0m[22;23;24m[32;1;23;24ma[0m[22;23;24m[31;22;23;24m></[0m[22;23;24m[32;1;23;24mp[0m[22;23;24m[31;22;23;24m>[0m[22;23;24m
+    [90;22;3;24m<!-- comment -->[0m[22;23;24m[0m
+
+Math: $\pi^2 = \frac{1}{2}$
+
+[22m[3m[39m[49m[24m[29me[0m = [22m[3m[39m[49m[24m[29mmc[0m²
+
+────────────────────
+
+More text.
+
+[1m[23m[39m[49m[24m[29mboldface text[0m, [22m[23m[39m[49m[4m[29munderlined text[0m, [22m[3m[39m[49m[24m[29memphasized text[0m.
+
+small caps
+
+We see a log₁₀ reduction in 2⁹ seconds.
+
+Hello
+
+Goodbye
+
+                          ────────────────────
+
+  1. Here’s the note.[0m]8;;\
diff --git a/test/ansi-test.txt b/test/ansi-test.txt
new file mode 100644
--- /dev/null
+++ b/test/ansi-test.txt
@@ -0,0 +1,127 @@
+---
+title: My Document
+author: John Doe
+date: July 25, 1933
+...
+
+# Level 1 heading
+
+Text
+
+## Level 2 heading
+
+Text
+
+### Level 3 heading
+
+Text
+
+#### Level 4 heading
+
+Text
+
+##### Level 5 heading
+
+Text
+
+- list
+  - nested
+    1) numbered
+
+       continuation paragraph
+
+[link](http://example.com)
+
+<mail@example.com>
+
+> Block quote
+>
+> > Nested block quote
+
+Multiline table with caption:
+
+:  Here's the caption.
+It may span multiple lines.
+
+---------------------------------------------------------------
+ Centered   Left             Right
+  Header    Aligned        Aligned  Default aligned
+----------  ---------  -----------  ---------------------------
+   First    row               12.0  Example of a row that spans
+                                    multiple lines.
+
+   Second   row                5.0  Here's another one.  Note
+                                    the blank line between rows.
+---------------------------------------------------------------
+
+Multiline table without caption:
+
+---------------------------------------------------------------
+ Centered   Left             Right
+  Header    Aligned        Aligned  Default aligned
+----------  ---------  -----------  ---------------------------
+   First    row               12.0  Example of a row that spans
+                                    multiple lines.
+
+   Second   row                5.0  Here's another one.  Note
+                                    the blank line between rows.
+---------------------------------------------------------------
+
+Table without column headers:
+
+-------     ------ ----------   -------
+     12     12        12             12
+    123     123       123           123
+      1     1          1              1
+-------     ------ ----------   -------
+
+Footnote^[Here's the note.]
+
+Multiple blocks in a cell
+
++------------------+-----------+------------+
+| # col 1          | # col 2   | # col 3    |
+| col 1            | col 2     | col 3      |
++------------------+-----------+------------+
+| r1 a             | - b       | c          |
+|                  | - b 2     | c 2        |
+| r1 bis           | - b 2     | c 2        |
++------------------+-----------+------------+
+
+East Asian characters have double width
+
++--+----+
+|魚|fish|
++--+----+
+
+This is inline code: `x >>= y ++ 3`.
+
+```
+code block
+   >>> ## ``
+```
+
+Highlighted:
+
+```html
+<p><a href="foobar" title="title">This is a link</a></p>
+<!-- comment -->
+```
+
+Math: $\pi^2 = \frac{1}{2}$
+
+$$e = mc^2$$
+
+----
+
+More text.
+
+**boldface text**, [underlined text]{.underline}, *emphasized text*.
+
+[small caps]{.smallcaps}
+
+We see a log~10~ reduction in 2^9^ seconds.
+
+| Hello
+|
+| Goodbye
diff --git a/test/asciidoc-reader-include.adoc b/test/asciidoc-reader-include.adoc
new file mode 100644
--- /dev/null
+++ b/test/asciidoc-reader-include.adoc
@@ -0,0 +1,4 @@
+This is a test!
+
+. one
+.. two
diff --git a/test/asciidoc-reader-include.rb b/test/asciidoc-reader-include.rb
new file mode 100644
--- /dev/null
+++ b/test/asciidoc-reader-include.rb
@@ -0,0 +1,4 @@
+# A function
+def foo
+  return 42
+end
diff --git a/test/asciidoc-reader.adoc b/test/asciidoc-reader.adoc
new file mode 100644
--- /dev/null
+++ b/test/asciidoc-reader.adoc
@@ -0,0 +1,908 @@
+// Some comment here.
+= AsciiDoc reader test
+John MacFarlane <jgm@berkeley.edu>; John Doe <doe@example.com>
+v1.0, 2025-11-24
+:custom: Foo bar \
+baz
+:flag:
+:stem: latexmath
+
+[#firsty]
+== Inline markup
+
+=== Characters and escapes
+
+Dog's has a curved apostrophe, but dog\'s does not.
+
+An escaped symbol: \*star\*.
+
+Character references: &auml;&#160;&#x22E0; 
+
+=== Line breaks
+
+This is a hard +
+break.
+
+Or set it for a whole paragraph
+
+[%hardbreaks]
+These are
+all
+hard
+breaks.
+
+=== Autolinks
+
+http://example.com/foobar?a=333&b=no%20body, me@example.com
+
+<http://example.com/foobar?a=333&b=no%20body>, <me@example.com>
+
+=== Cross-reference
+
+See <<firsty>>
+
+See <<firsty,My great section on Inline markup>>
+
+Go to <<anch,an inline anchor>>
+
+=== Anchors
+
+An [[anch]]inline anchor.
+
+[[[bibanchor]]Doe, John. A Book.
+
+=== Inline macros
+
+kbd:[F11]
+
+kbd:[Ctrl+Shift+F]
+
+menu:File[Save]
+
+menu:Reader[Markdown > Pandoc]
+
+btn:[Cancel]
+
+icon:heart[2x,role=red]
+
+anchor:tiger
+
+pass:[<b>*bold*</b>]
+
+link:downloads/report.pdf[Get Report]
+
+link:tools.html#editors[]
+
+link:file:///home/username[Your files]
+
+Tricky cases:
+
+link:pass:[My Documents/report.pdf][Get Report]
+
+link:My&#32;Documents/report.pdf[Get Report]
+
+link:My%20Documents/report.pdf[Get Report]
+
+link:++https://example.org/now_this__link_works.html++[]
+
+mailto:join@discuss.example.org[Subscribe]
+
+mailto:join@discuss.example.org["Click, subscribe, and participate!",role=mail]
+
+xref:link-macro-attributes[use attributes within the link macro]
+
+image::sunset.jpg[Sunset]
+
+image::name.png[]
+
+image::sunset.jpg[Sunset,300,400]
+
+image::sunset.jpg[alt=Sunset,width=300,height=400]
+
+[latexmath]
+++++
+e=mc^2
+++++
+
+[asciimath]
+++++
+sin n / 3
+++++
+
+[stem]
+++++
+e^i
+++++
+
+=== Attribute substitutions
+
+{custom}
+
+{nonexistent}
+
+Built in: x{blank}y{empty}z{sp}a{nbsp}b{zwsp}c{apos}d{lsquo}
+
+=== Bold and italic
+
+Constrained: *this is bold _and italic_*.
+
+Unconstrained: wild**content__with italic__stuff**.
+
+=== Monospace
+
+`simple`
+
+`complex *with bold* text and a link:foo.html[]`
+
+unconstrained``wwow``okay
+
+=== Span and inline attributes
+
+[.red]#Bonjour *monsieur*#
+
+Un[.red]##constrained##content
+
+With #no attribute# it's highlighted.
+
+=== Sub and superscript
+
+H~2~O
+
+H~a{sp}b~O
+
+Not subscript: H~a b~O.
+
+H^2&O
+
+H^a{sp}b^O
+
+Not subscript: H^a b^O.
+
+=== Passthrough
+
+Here the special characters just come through as literal:
+
++<b>*test*</b>+
+
+xx++<b>*test*</b>++xx
+
+But here they are passed through:
+
+xx+++<b>*test*</b>+++xx
+
+=== Quoted
+
+"`double quoted`"
+
+'`single quoted`'
+
+=== Footnotes
+
+Doublefootnote:[The double hail-and-rainbow level makes my toes tingle.]
+
+A bold statement!footnote:disclaimer[Opinions are my own.]
+Another outrageous statement.footnote:disclaimer[]
+
+== Block markup
+
+=== Sections
+
+==== Another level
+
+===== Level 5
+
+#### Markdown style
+
+##### Level 5
+
+=== Discrete heading
+
+[discrete]
+==== A discrete heading, not a section
+
+=== Paragraph
+
+This is a paragraph
+whose source fits on two lines.
+
+{.This is my title}
+A paragraph with a title.
+
+=== Example block
+
+.Optional title
+[example]
+This is an example of an example block.
+
+.Optional title
+====
+Paragraph *one*.
+
+Paragraph *two*.
+====
+
+=== Admonition
+
+Simple form:
+
+WARNING: This is very dangerous.
+Don't do it unless you understand the risks.
+
+[IMPORTANT]
+.Title of the admonition
+====
+Remember:
+
+. Don't do this.
+. And don't do that.
+====
+
+=== Sidebar
+
+[sidebar]
+A simple sidebar.
+
+.Optional Title *with strong emphasis*
+****
+Here is a sidebar.
+
+TIP: It can contain any type of content.
+****
+
+=== Literal block
+
+Short indented code:
+
+  $ ls -a
+  $ cat /foo/bar/baz \
+       /bi/bim/bop
+
+[literal]
+This is
+  a literal block too.
+
+....
+  Fenced
+    $+ *a* literal
+
+****
+not a sidebar
+****
+....
+
+=== Listing
+
+[source,ruby]
+----
+require 'sinatra'
+
+get '/hi' do
+  "Hello World!"
+end
+----
+
+Implied:
+
+[source,ruby]
+----
+require 'sinatra'
+
+get '/hi' do
+  "Hello World!"
+end
+----
+
+[,ruby]
+----
+include::asciidoc-reader-include.rb[]
+----
+
+[#hello.haskell]
+----
+putStrLn $ unwords ["Hello", "world"]
+----
+
+Line numbering:
+
+[%linenums,ruby]
+----
+puts 1
+puts 2
+puts 3
+----
+
+----
+This doesn't have a language.
+  +="hi"
+----
+
+And with a callout list:
+
+[source,ruby]
+----
+require 'sinatra' <1>
+
+get '/hi' do <2> <3>
+  "Hello World!"
+end
+----
+<1> Library import
+<2> URL mapping
+<3> Response block
+
+Markdown-style fenced:
+
+```ruby
+def foo
+  return 5
+end
+```
+
+=== Verse
+
+[verse,Carl Sandburg, two lines from the poem Fog]
+The fog comes
+on little cat feet.
+
+[verse,Carl Sandburg,Fog]
+____
+The fog comes
+on little cat feet.
+It sits looking
+over harbor and city
+on silent haunches
+and then moves on.
+____
+
+=== Collapsible
+
+Click here for more.
+[%collapsible%open]
+====
+This is collapsible.
+
+It can be hidden.
+====
+
+.Click me!
+[%collapsible]
+This paragraph is
+also collapsible.
+
+=== Quote
+
+[quote,Captain James T. Kirk,Star Trek IV: The Voyage Home]
+Everybody remember where we parked.
+
+[quote,Monty Python and the Holy Grail]
+____
+Dennis: Come and see the violence inherent in the system. Help! Help! I'm being
+repressed.
+
+King Arthur: Bloody peasant!
+
+Dennis: Oh, what a giveaway! Did you hear that? Did you hear that, eh? That's what I'm
+on about! Did you see him repressing me? You saw him, Didn't you?
+____
+
+[quote.movie#roads,Dr. Emmett Brown]
+____
+Roads? Where we're going, we don't need roads.
+____
+
+=== Pass
+
+++++
+<p>pass <em>through</em>
+  </p>
+++++
+
+=== Open block
+
+.A title.
+[key="a value"]
+--
+Any content can go here:
+
+. one
+. two
+--
+
+=== Anchor
+
+[[goals]]
+* one
+* two
+
+=== Breaks
+
+Asciidoc thematic break:
+
+'''
+
+Markdown style:
+
+---
+- - -
+***
+* * *
+
+Page breaks:
+
+<<<
+
+[%always]
+<<<
+
+=== List
+
+* Edgar Allan Poe
+* Sheri S. Tepper
+* Bill Bryson
+
+// titled
+
+.Kizmet's Favorite Authors
+* Edgar Allan Poe
+* Sheri S. Tepper
+* Bill Bryson
+
+// hyphen
+
+- Edgar Allan Poe
+- Sheri S. Tepper
+- Bill Bryson
+
+. Nested list
+* West wood maze
+** Maze heart
+*** Reflection pool
+** Secret exit
+* Level 1 list item
+** Level 2 list item
+*** Level 3 list item
+**** Level 4 list item
+***** Level 5 list item
+****** etc.
+* Level 1 list item
+
+// attributes
+
+[square]
+* one
+* two
+* three
+
+// ordered with actual numbers
+
+1. Protons
+2. Electrons
+3. Neutrons
+
+// ordered with .
+
+. Protons
+. Electrons
+. Neutrons
+
+Start with 4:
+
+4. Step four
+5. Step five
+6. Step six
+
+or
+
+[start=4]
+. Step four
+. Step five
+. Step six
+
+Reversed:
+
+[%reversed]
+.Parts of an atom
+. Protons
+. Electrons
+. Neutrons
+
+Nested
+
+. Step 1
+. Step 2
+.. Step 2a
+.. Step 2b
+. Step 3
+
+Mixed nested
+
+. Linux
+* Fedora
+* Ubuntu
+* Slackware
+. BSD
+* FreeBSD
+* NetBSD
+
+With spacing
+
+. Linux
+* Fedora
+* Ubuntu
+* Slackware
+. BSD
+* FreeBSD
+* NetBSD
+
+With number styles
+
+[lowerroman,start=5]
+. Five
+. Six
+[loweralpha]
+.. a
+.. b
+.. c
+. Seven
+
+Checklist
+
+* [*] checked
+* [x] also checked
+* [ ] not checked
+* normal list item
+
+Separate lists with block attribute
+
+* Apples
+* Oranges
+[]
+. Wash
+. Slice
+
+Multiline items
+
+* Blah blah.
+Blah blah.
+* The document header in AsciiDoc is optional.
+If present, it must start with a document title.
+
+* Optional author and revision information lines
+immediately follow the document title.
+
+* The document header must be separated from
+  the remainder of the document by one or more
+  empty lines and it cannot contain empty lines.
+
+Complex item
+
+* The header in AsciiDoc must start with a document title.
++
+----
+= Document Title
+----
++
+Keep in mind that the header is optional.
+* Optional author and revision information lines immediately follow the document
+title.
++
+----
+= Document Title
+Doc Writer <doc.writer@asciidoc.org>
+v1.0, 2022-01-01
+----
+* Second item
+
+Empty principle element:
+
+. {empty}
++
+----
+test
+----
+
+=== Table
+
+==== Simple with column specs
+
+[cols="3,2,3"]
+|===
+|This content is placed in the first cell of column 1
+|This line starts with a vertical bar so this content is placed in a new cell in
+column 2 |When the processor encounters a whitespace followed by a vertical bar it
+ends the previous cell and starts a new cell
+|===
+
+==== Repeated column in specs
+
+[cols="2*"]
+|===
+>s|This cell's specifier indicates that this cell's content is right-aligned and bold.
+|The cell specifier on this cell hasn't been set explicitly, so the default
+properties are applied.
+|===
+
+==== Simple without column specs
+
+|===
+|Column 1, header row |Column 2, header row
+
+|Cell in column 1, row 2
+|Cell in column 2, row 2
+
+|Cell in column 1, row 3
+|Cell in column 2, row 3
+|===
+
+==== With caption
+
+.My cool table.
+|===
+|Column 1, header row |Column 2, header row
+
+|Cell in column 1, row 2
+|Cell in column 2, row 2
+
+|Cell in column 1, row 3
+|Cell in column 2, row 3
+|===
+
+==== No header
+
+By default the first line should turn into the header, but this
+can be disabled:
+
+[%noheader]
+|===
+|Cell in column 1, row 1 |Cell in column 2, row 1
+|Cell in column 1, row 2 |Cell in column 2, row 2
+|===
+
+And also explicitly enabled:
+
+[%header%footer%autowidth,cols=2*~]
+|===
+|Cell A1 |Cell B1
+|Cell A2 |Cell B2
+|Cell A3 |Cell B3
+|===
+
+==== Footer
+
+[%header%footer,cols="2,2,1"]
+|===
+|Column 1, header row
+|Column 2, header row
+|Column 3, header row
+|Cell in column 1, row 2
+|Cell in column 2, row 2
+|Cell in column 3, row 2
+|Column 1, footer row
+|Column 2, footer row
+|Column 3, footer row
+|===
+
+or
+
+[options="footer"]
+|===
+|Column 1, header row |Column 2, header row
+|Cell in column 1, row 2
+|Cell in column 2, row 2
+|Cell in column 1, row 3
+|Cell in column 2, row 3
+|Column 1, footer row
+|Column 2, footer row
+|===
+
+==== Alignment
+
+|===
+|Column Name |Column Name
+2+^|This cell spans two columns, and its content is horizontally centered because the
+cell specifier includes the `+^+` operator.
+2*^|This content is duplicated in two adjacent columns.
+Its content is horizontally centered because the cell specifier
+includes the `+^+` operator.
+|===
+
+==== Multiple paragraphs in cells
+
+|===
+
+|Single paragraph on row 1
+
+|First paragraph on row 2
+
+Second paragraph on row 2
+|===
+
+==== Complex table
+
+|===
+
+2*>m|This content is duplicated across two columns.
+
+It is aligned right horizontally.
+
+And it is monospaced.
+
+.3+^.>s|This cell spans 3 rows. The content is centered horizontally, aligned to the bottom of the cell, and strong.
+e|This content is emphasized.
+
+.^l|This content is aligned to the top of the cell and literal.
+
+a|
+[source]
+puts "This is a source block!"
+
+|===
+
+==== Column styles
+
+[cols="m,m"]
+|===
+|monospace | mono
+d|default | mono
+|===
+
+==== Block elements in cells
+
+|===
+|Normal Style |AsciiDoc Style
+|This cell isn't prefixed with an `a`, so the processor doesn't interpret the
+following lines as an AsciiDoc list.
+
+* List item 1
+* List item 2
+* List item 3
+
+a|This cell is prefixed with an `a`, so the processor interprets the following lines
+as an AsciiDoc list.
+
+* List item 1
+* List item 2
+* List item 3
+
+|This cell isn't prefixed with an `a`, so the processor doesn't interpret the listing
+block delimiters or the `source` style.
+
+[source,python]
+----
+import os
+print ("%s" %(os.uname()))
+----
+
+a|This cell is prefixed with an `a`, so the listing block is processed and rendered
+according to the `source` style rules.
+
+[source,python]
+----
+import os
+print "%s" %(os.uname())
+----
+|===
+
+==== Col and rowspan
+
+|===
+|Column 1, header row |Column 2, header row | Column 3, header row
+2.2+|This cell spans 2 cols and 2 rows
+|Cell in column 3, row 2
+|Cell in column 3, row 3
+3+|Cell in column 1-3, row 4
+|===
+
+==== CSV table
+
+[%header,format=csv]
+|===
+Artist,Track,Genre
+Baauer,Harlem Shake,Hip Hop
+The Lumineers,Ho Hey,Folk Rock
+|===
+
+or
+
+,===
+Artist,Track,Genre
+Baauer,Harlem Shake,Hip Hop
+,===
+
+==== DSV table
+
+[format=dsv,separator=;]
+|===
+a;b;c
+d;e;f
+|===
+
+or
+
+:===
+Artist:Track:Genre
+Robyn:Indestructible:Dance
+:===
+
+=== Definition list
+
+CPU:: The brain of the computer.
+Hard drive:: Permanent storage for operating system and/or user files.
+
+Mixed
+
+Dairy::
+* Milk
+* Eggs
+Bakery::
+* Bread
+Produce::
+* Bananas
+
+With spaces
+
+Dairy::
+
+  * Milk
+  * Eggs
+
+Bakery::
+
+  * Bread
+
+Produce::
+
+  * Bananas
+
+Nested
+
+Operating Systems::
+Linux:::
+ . Fedora
+  * Desktop
+ . Ubuntu
+  * Desktop
+  * Server
+BSD:::
+ . FreeBSD
+ . NetBSD
+Cloud Providers::
+ PaaS:::
+  . OpenShift
+  . CloudBees
+ IaaS:::
+  . Amazon EC2
+
+This just affects the output:
+
+[horizontal,labelwidth=25,itemwidth=75]
+CPU:: The brain of the computer.
+RAM:: Temporarily stores information the CPU uses during operation.
+
+Q&A list
+
+[qanda]
+What is the answer?::
+This is the answer.
+Are cameras allowed?::
+Are backpacks allowed?::
+No.
+
+Ordered description list (with numbers)
+
+[ordered]
+&:: ampersand
+>:: greater than
+
+=== Block macros
+
+image::sunset.jpg[Sunset,300,200]
+
+video::mymovie.mp4[]
+
+audio::mysong.mp3[]
+
+toc::[]
+
+include::asciidoc-reader-include.adoc[]
+
diff --git a/test/asciidoc-reader.native b/test/asciidoc-reader.native
new file mode 100644
--- /dev/null
+++ b/test/asciidoc-reader.native
@@ -0,0 +1,4418 @@
+Pandoc
+  Meta
+    { unMeta =
+        fromList
+          [ ( "author"
+            , MetaList
+                [ MetaInlines
+                    [ Str "John"
+                    , Space
+                    , Str "MacFarlane"
+                    , Space
+                    , Str "("
+                    , Link
+                        ( "" , [] , [] )
+                        [ Str "jgm@berkeley.edu" ]
+                        ( "mailto:jgm@berkeley.edu" , "" )
+                    , Str ")"
+                    ]
+                , MetaInlines
+                    [ Str "John"
+                    , Space
+                    , Str "Doe"
+                    , Space
+                    , Str "("
+                    , Link
+                        ( "" , [] , [] )
+                        [ Str "doe@example.com" ]
+                        ( "mailto:doe@example.com" , "" )
+                    , Str ")"
+                    ]
+                ]
+            )
+          , ( "custom" , MetaString "Foo bar baz" )
+          , ( "date" , MetaString "2025-11-24" )
+          , ( "flag" , MetaBool True )
+          , ( "title"
+            , MetaInlines
+                [ Str "AsciiDoc"
+                , Space
+                , Str "reader"
+                , Space
+                , Str "test"
+                ]
+            )
+          , ( "version" , MetaString "1.0" )
+          ]
+    }
+  [ Header
+      1
+      ( "firsty" , [] , [] )
+      [ Str "Inline" , Space , Str "markup" ]
+  , Header
+      2
+      ( "_characters_and_escapes" , [] , [] )
+      [ Str "Characters"
+      , Space
+      , Str "and"
+      , Space
+      , Str "escapes"
+      ]
+  , Para
+      [ Str "Dog\8217s"
+      , Space
+      , Str "has"
+      , Space
+      , Str "a"
+      , Space
+      , Str "curved"
+      , Space
+      , Str "apostrophe,"
+      , Space
+      , Str "but"
+      , Space
+      , Str "dog's"
+      , Space
+      , Str "does"
+      , Space
+      , Str "not."
+      ]
+  , Para
+      [ Str "An"
+      , Space
+      , Str "escaped"
+      , Space
+      , Str "symbol:"
+      , Space
+      , Str "*star*."
+      ]
+  , Para
+      [ Str "Character"
+      , Space
+      , Str "references:"
+      , Space
+      , Str "\228\160\8928"
+      ]
+  , Header
+      2
+      ( "_line_breaks" , [] , [] )
+      [ Str "Line" , Space , Str "breaks" ]
+  , Para
+      [ Str "This"
+      , Space
+      , Str "is"
+      , Space
+      , Str "a"
+      , Space
+      , Str "hard"
+      , LineBreak
+      , Str "break."
+      ]
+  , Para
+      [ Str "Or"
+      , Space
+      , Str "set"
+      , Space
+      , Str "it"
+      , Space
+      , Str "for"
+      , Space
+      , Str "a"
+      , Space
+      , Str "whole"
+      , Space
+      , Str "paragraph"
+      ]
+  , Div
+      ( ""
+      , []
+      , [ ( "wrapper" , "1" ) , ( "options" , "hardbreaks" ) ]
+      )
+      [ Para
+          [ Str "These"
+          , Space
+          , Str "are"
+          , LineBreak
+          , Str "all"
+          , LineBreak
+          , Str "hard"
+          , LineBreak
+          , Str "breaks."
+          ]
+      ]
+  , Header 2 ( "_autolinks" , [] , [] ) [ Str "Autolinks" ]
+  , Para
+      [ Link
+          ( "" , [] , [] )
+          [ Str "http://example.com/foobar?a=333&b=no%20body" ]
+          ( "http://example.com/foobar?a=333&b=no%20body" , "" )
+      , Str ","
+      , Space
+      , Link
+          ( "" , [] , [] )
+          [ Str "me@example.com" ]
+          ( "me@example.com" , "" )
+      ]
+  , Para
+      [ Link
+          ( "" , [] , [] )
+          [ Str "http://example.com/foobar?a=333&b=no%20body" ]
+          ( "http://example.com/foobar?a=333&b=no%20body" , "" )
+      , Str ","
+      , Space
+      , Str "<"
+      , Link
+          ( "" , [] , [] )
+          [ Str "me@example.com" ]
+          ( "me@example.com" , "" )
+      , Str ">"
+      ]
+  , Header
+      2 ( "_cross_reference" , [] , [] ) [ Str "Cross-reference" ]
+  , Para
+      [ Str "See"
+      , Space
+      , Link
+          ( "" , [ "cross-reference" ] , [] )
+          [ Str "Inline" , Space , Str "markup" ]
+          ( "#firsty" , "" )
+      ]
+  , Para
+      [ Str "See"
+      , Space
+      , Link
+          ( "" , [ "cross-reference" ] , [] )
+          [ Str "My"
+          , Space
+          , Str "great"
+          , Space
+          , Str "section"
+          , Space
+          , Str "on"
+          , Space
+          , Str "Inline"
+          , Space
+          , Str "markup"
+          ]
+          ( "#firsty" , "" )
+      ]
+  , Para
+      [ Str "Go"
+      , Space
+      , Str "to"
+      , Space
+      , Link
+          ( "" , [ "cross-reference" ] , [] )
+          [ Str "an" , Space , Str "inline" , Space , Str "anchor" ]
+          ( "#anch" , "" )
+      ]
+  , Header 2 ( "_anchors" , [] , [] ) [ Str "Anchors" ]
+  , Para
+      [ Str "An"
+      , Space
+      , Span ( "anch" , [] , [] ) []
+      , Str "inline"
+      , Space
+      , Str "anchor."
+      ]
+  , Para
+      [ Span ( "[bibanchor" , [] , [] ) []
+      , Str "Doe,"
+      , Space
+      , Str "John."
+      , Space
+      , Str "A"
+      , Space
+      , Str "Book."
+      ]
+  , Header
+      2
+      ( "_inline_macros" , [] , [] )
+      [ Str "Inline" , Space , Str "macros" ]
+  , Para
+      [ Span ( "" , [ "kbd" ] , [] ) [ Strong [ Str "F11" ] ] ]
+  , Para
+      [ Span ( "" , [ "kbd" ] , [] ) [ Strong [ Str "Ctrl" ] ]
+      , Str "+"
+      , Span ( "" , [ "kbd" ] , [] ) [ Strong [ Str "Shift" ] ]
+      , Str "+"
+      , Span ( "" , [ "kbd" ] , [] ) [ Strong [ Str "F" ] ]
+      ]
+  , Para
+      [ Span
+          ( "" , [ "menu" ] , [] )
+          [ Strong [ Str "File\160\8250\160Save" ] ]
+      ]
+  , Para
+      [ Span
+          ( "" , [ "menu" ] , [] )
+          [ Strong
+              [ Str "Reader\160\8250\160Markdown\160\8250\160Pandoc" ]
+          ]
+      ]
+  , Para
+      [ Span
+          ( "" , [ "button" ] , [] ) [ Strong [ Str "[Cancel]" ] ]
+      ]
+  , Para
+      [ Image
+          ( "" , [ "red icon" ] , [] )
+          []
+          ( "./images/icons/heart.png" , "" )
+      ]
+  , Para [ Str "anchor:tiger" ]
+  , Para [ Strong [ Str "*bold*" ] ]
+  , Para
+      [ Link
+          ( "" , [] , [] )
+          [ Str "Get" , Space , Str "Report" ]
+          ( "downloads/report.pdf" , "" )
+      ]
+  , Para
+      [ Link
+          ( "" , [] , [] )
+          [ Str "tools.html#editors" ]
+          ( "tools.html#editors" , "" )
+      ]
+  , Para
+      [ Link
+          ( "" , [] , [] )
+          [ Str "Your" , Space , Str "files" ]
+          ( "file:///home/username" , "" )
+      ]
+  , Para [ Str "Tricky" , Space , Str "cases:" ]
+  , Para
+      [ Link
+          ( "" , [] , [] )
+          [ Str "Get" , Space , Str "Report" ]
+          ( "My Documents/report.pdf" , "" )
+      ]
+  , Para
+      [ Link
+          ( "" , [] , [] )
+          [ Str "Get" , Space , Str "Report" ]
+          ( "My&#32;Documents/report.pdf" , "" )
+      ]
+  , Para
+      [ Link
+          ( "" , [] , [] )
+          [ Str "Get" , Space , Str "Report" ]
+          ( "My%20Documents/report.pdf" , "" )
+      ]
+  , Para
+      [ Link
+          ( "" , [] , [] )
+          [ Str "https://example.org/now_this__link_works.html" ]
+          ( "https://example.org/now_this__link_works.html" , "" )
+      ]
+  , Para
+      [ Link
+          ( "" , [] , [] )
+          [ Str "Subscribe" ]
+          ( "join@discuss.example.org" , "" )
+      ]
+  , Para
+      [ Link
+          ( "" , [ "mail" ] , [] )
+          [ Str "Click,"
+          , Space
+          , Str "subscribe,"
+          , Space
+          , Str "and"
+          , Space
+          , Str "participate!"
+          ]
+          ( "join@discuss.example.org" , "" )
+      ]
+  , Para
+      [ Link
+          ( "" , [ "cross-reference" ] , [] )
+          [ Str "use"
+          , Space
+          , Str "attributes"
+          , Space
+          , Str "within"
+          , Space
+          , Str "the"
+          , Space
+          , Str "link"
+          , Space
+          , Str "macro"
+          ]
+          ( "#link-macro-attributes" , "" )
+      ]
+  , Figure
+      ( "" , [] , [] )
+      (Caption Nothing [])
+      [ Plain
+          [ Image
+              ( "" , [] , [] ) [ Str "Sunset" ] ( "sunset.jpg" , "" )
+          ]
+      ]
+  , Figure
+      ( "" , [] , [] )
+      (Caption Nothing [])
+      [ Plain [ Image ( "" , [] , [] ) [] ( "name.png" , "" ) ] ]
+  , Figure
+      ( "" , [] , [] )
+      (Caption Nothing [])
+      [ Plain
+          [ Image
+              ( ""
+              , []
+              , [ ( "width" , "300px" ) , ( "height" , "400px" ) ]
+              )
+              [ Str "Sunset" ]
+              ( "sunset.jpg" , "" )
+          ]
+      ]
+  , Div
+      ( ""
+      , []
+      , [ ( "wrapper" , "1" )
+        , ( "alt" , "Sunset" )
+        , ( "height" , "400" )
+        , ( "width" , "300" )
+        ]
+      )
+      [ Figure
+          ( "" , [] , [] )
+          (Caption Nothing [])
+          [ Plain [ Image ( "" , [] , [] ) [] ( "sunset.jpg" , "" ) ]
+          ]
+      ]
+  , Para [ Math DisplayMath "e=mc^2\n" ]
+  , Para [ Math DisplayMath "sin n / 3\n" ]
+  , Para [ Math DisplayMath "e^i\n" ]
+  , Header
+      2
+      ( "_attribute_substitutions" , [] , [] )
+      [ Str "Attribute" , Space , Str "substitutions" ]
+  , Para [ Str "Foo" , Space , Str "bar" , Space , Str "baz" ]
+  , Para [ Str "{nonexistent}" ]
+  , Para
+      [ Str "Built"
+      , Space
+      , Str "in:"
+      , Space
+      , Str "xyz"
+      , Space
+      , Str "a\160b\8203c'd\8216"
+      ]
+  , Header
+      2
+      ( "_bold_and_italic" , [] , [] )
+      [ Str "Bold" , Space , Str "and" , Space , Str "italic" ]
+  , Para
+      [ Str "Constrained:"
+      , Space
+      , Strong
+          [ Str "this"
+          , Space
+          , Str "is"
+          , Space
+          , Str "bold"
+          , Space
+          , Emph [ Str "and" , Space , Str "italic" ]
+          ]
+      , Str "."
+      ]
+  , Para
+      [ Str "Unconstrained:"
+      , Space
+      , Str "wild"
+      , Strong
+          [ Str "content"
+          , Emph [ Str "with" , Space , Str "italic" ]
+          , Str "stuff"
+          ]
+      , Str "."
+      ]
+  , Header 2 ( "_monospace" , [] , [] ) [ Str "Monospace" ]
+  , Para [ Code ( "" , [] , [] ) "simple" ]
+  , Para
+      [ Code ( "" , [] , [] ) "complex"
+      , Space
+      , Strong
+          [ Code ( "" , [] , [] ) "with"
+          , Space
+          , Code ( "" , [] , [] ) "bold"
+          ]
+      , Space
+      , Code ( "" , [] , [] ) "text"
+      , Space
+      , Code ( "" , [] , [] ) "and"
+      , Space
+      , Code ( "" , [] , [] ) "a"
+      , Space
+      , Link
+          ( "" , [] , [] )
+          [ Code ( "" , [] , [] ) "foo.html" ]
+          ( "foo.html" , "" )
+      ]
+  , Para
+      [ Str "unconstrained"
+      , Code ( "" , [] , [] ) "wwow"
+      , Str "okay"
+      ]
+  , Header
+      2
+      ( "_span_and_inline_attributes" , [] , [] )
+      [ Str "Span"
+      , Space
+      , Str "and"
+      , Space
+      , Str "inline"
+      , Space
+      , Str "attributes"
+      ]
+  , Para
+      [ Span
+          ( "" , [ "red" ] , [] )
+          [ Str "Bonjour" , Space , Strong [ Str "monsieur" ] ]
+      ]
+  , Para
+      [ Str "Un"
+      , Span ( "" , [ "red" ] , [] ) [ Str "constrained" ]
+      , Str "content"
+      ]
+  , Para
+      [ Str "With"
+      , Space
+      , Span
+          ( "" , [ "mark" ] , [] )
+          [ Str "no" , Space , Str "attribute" ]
+      , Space
+      , Str "it\8217s"
+      , Space
+      , Str "highlighted."
+      ]
+  , Header
+      2
+      ( "_sub_and_superscript" , [] , [] )
+      [ Str "Sub"
+      , Space
+      , Str "and"
+      , Space
+      , Str "superscript"
+      ]
+  , Para [ Str "H" , Subscript [ Str "2" ] , Str "O" ]
+  , Para
+      [ Str "H"
+      , Subscript [ Str "a" , Space , Str "b" ]
+      , Str "O"
+      ]
+  , Para
+      [ Str "Not"
+      , Space
+      , Str "subscript:"
+      , Space
+      , Str "H~a"
+      , Space
+      , Str "b~O."
+      ]
+  , Para [ Str "H^2&O" ]
+  , Para
+      [ Str "H"
+      , Superscript [ Str "a" , Space , Str "b" ]
+      , Str "O"
+      ]
+  , Para
+      [ Str "Not"
+      , Space
+      , Str "subscript:"
+      , Space
+      , Str "H^a"
+      , Space
+      , Str "b^O."
+      ]
+  , Header
+      2 ( "_passthrough" , [] , [] ) [ Str "Passthrough" ]
+  , Para
+      [ Str "Here"
+      , Space
+      , Str "the"
+      , Space
+      , Str "special"
+      , Space
+      , Str "characters"
+      , Space
+      , Str "just"
+      , Space
+      , Str "come"
+      , Space
+      , Str "through"
+      , Space
+      , Str "as"
+      , Space
+      , Str "literal:"
+      ]
+  , Para [ Str "<b>*test*</b>" ]
+  , Para [ Str "xx<b>*test*</b>xx" ]
+  , Para
+      [ Str "But"
+      , Space
+      , Str "here"
+      , Space
+      , Str "they"
+      , Space
+      , Str "are"
+      , Space
+      , Str "passed"
+      , Space
+      , Str "through:"
+      ]
+  , Para [ Str "xx" , Strong [ Str "*test*" ] , Str "xx" ]
+  , Header 2 ( "_quoted" , [] , [] ) [ Str "Quoted" ]
+  , Para
+      [ Quoted DoubleQuote [ Str "double" , Space , Str "quoted" ]
+      ]
+  , Para
+      [ Quoted SingleQuote [ Str "single" , Space , Str "quoted" ]
+      ]
+  , Header 2 ( "_footnotes" , [] , [] ) [ Str "Footnotes" ]
+  , Para
+      [ Str "Double"
+      , Note
+          [ Para
+              [ Str "The"
+              , Space
+              , Str "double"
+              , Space
+              , Str "hail-and-rainbow"
+              , Space
+              , Str "level"
+              , Space
+              , Str "makes"
+              , Space
+              , Str "my"
+              , Space
+              , Str "toes"
+              , Space
+              , Str "tingle."
+              ]
+          ]
+      ]
+  , Para
+      [ Str "A"
+      , Space
+      , Str "bold"
+      , Space
+      , Str "statement!"
+      , Note
+          [ Para
+              [ Str "Opinions"
+              , Space
+              , Str "are"
+              , Space
+              , Str "my"
+              , Space
+              , Str "own."
+              ]
+          ]
+      , SoftBreak
+      , Str "Another"
+      , Space
+      , Str "outrageous"
+      , Space
+      , Str "statement."
+      , Note
+          [ Para
+              [ Str "Opinions"
+              , Space
+              , Str "are"
+              , Space
+              , Str "my"
+              , Space
+              , Str "own."
+              ]
+          ]
+      ]
+  , Header
+      1
+      ( "_block_markup" , [] , [] )
+      [ Str "Block" , Space , Str "markup" ]
+  , Header 2 ( "_sections" , [] , [] ) [ Str "Sections" ]
+  , Header
+      3
+      ( "_another_level" , [] , [] )
+      [ Str "Another" , Space , Str "level" ]
+  , Header
+      4 ( "_level_5" , [] , [] ) [ Str "Level" , Space , Str "5" ]
+  , Header
+      3
+      ( "_markdown_style" , [] , [] )
+      [ Str "Markdown" , Space , Str "style" ]
+  , Header
+      4
+      ( "_level_5_2" , [] , [] )
+      [ Str "Level" , Space , Str "5" ]
+  , Header
+      2
+      ( "_discrete_heading" , [] , [] )
+      [ Str "Discrete" , Space , Str "heading" ]
+  , Header
+      3
+      ( "" , [] , [] )
+      [ Str "A"
+      , Space
+      , Str "discrete"
+      , Space
+      , Str "heading,"
+      , Space
+      , Str "not"
+      , Space
+      , Str "a"
+      , Space
+      , Str "section"
+      ]
+  , Header 2 ( "_paragraph" , [] , [] ) [ Str "Paragraph" ]
+  , Para
+      [ Str "This"
+      , Space
+      , Str "is"
+      , Space
+      , Str "a"
+      , Space
+      , Str "paragraph"
+      , SoftBreak
+      , Str "whose"
+      , Space
+      , Str "source"
+      , Space
+      , Str "fits"
+      , Space
+      , Str "on"
+      , Space
+      , Str "two"
+      , Space
+      , Str "lines."
+      ]
+  , Para
+      [ Str "{.This"
+      , Space
+      , Str "is"
+      , Space
+      , Str "my"
+      , Space
+      , Str "title}"
+      , SoftBreak
+      , Str "A"
+      , Space
+      , Str "paragraph"
+      , Space
+      , Str "with"
+      , Space
+      , Str "a"
+      , Space
+      , Str "title."
+      ]
+  , Header
+      2
+      ( "_example_block" , [] , [] )
+      [ Str "Example" , Space , Str "block" ]
+  , Div
+      ( "" , [] , [] )
+      [ Div
+          ( "" , [ "title" ] , [] )
+          [ Para [ Str "Optional" , Space , Str "title" ] ]
+      , Para
+          [ Str "This"
+          , Space
+          , Str "is"
+          , Space
+          , Str "an"
+          , Space
+          , Str "example"
+          , Space
+          , Str "of"
+          , Space
+          , Str "an"
+          , Space
+          , Str "example"
+          , Space
+          , Str "block."
+          ]
+      ]
+  , Div
+      ( "" , [ "example" ] , [] )
+      [ Div
+          ( "" , [ "title" ] , [] )
+          [ Para [ Str "Optional" , Space , Str "title" ] ]
+      , Para
+          [ Str "Paragraph" , Space , Strong [ Str "one" ] , Str "." ]
+      , Para
+          [ Str "Paragraph" , Space , Strong [ Str "two" ] , Str "." ]
+      ]
+  , Header 2 ( "_admonition" , [] , [] ) [ Str "Admonition" ]
+  , Para [ Str "Simple" , Space , Str "form:" ]
+  , Div
+      ( "" , [ "warning" ] , [] )
+      [ Div ( "" , [ "title" ] , [] ) [ Para [ Str "Warning" ] ]
+      , Para
+          [ Str "This"
+          , Space
+          , Str "is"
+          , Space
+          , Str "very"
+          , Space
+          , Str "dangerous."
+          , SoftBreak
+          , Str "Don\8217t"
+          , Space
+          , Str "do"
+          , Space
+          , Str "it"
+          , Space
+          , Str "unless"
+          , Space
+          , Str "you"
+          , Space
+          , Str "understand"
+          , Space
+          , Str "the"
+          , Space
+          , Str "risks."
+          ]
+      ]
+  , Div
+      ( "" , [ "important" ] , [] )
+      [ Div
+          ( "" , [ "title" ] , [] )
+          [ Para
+              [ Str "Title"
+              , Space
+              , Str "of"
+              , Space
+              , Str "the"
+              , Space
+              , Str "admonition"
+              ]
+          ]
+      , Para [ Str "Remember:" ]
+      , OrderedList
+          ( 1 , DefaultStyle , DefaultDelim )
+          [ [ Para
+                [ Str "Don\8217t"
+                , Space
+                , Str "do"
+                , Space
+                , Str "this."
+                ]
+            ]
+          , [ Para
+                [ Str "And"
+                , Space
+                , Str "don\8217t"
+                , Space
+                , Str "do"
+                , Space
+                , Str "that."
+                ]
+            ]
+          ]
+      ]
+  , Header 2 ( "_sidebar" , [] , [] ) [ Str "Sidebar" ]
+  , Para
+      [ Str "A" , Space , Str "simple" , Space , Str "sidebar." ]
+  , Div
+      ( "" , [ "sidebar" ] , [] )
+      [ Div
+          ( "" , [ "title" ] , [] )
+          [ Para
+              [ Str "Optional"
+              , Space
+              , Str "Title"
+              , Space
+              , Strong
+                  [ Str "with"
+                  , Space
+                  , Str "strong"
+                  , Space
+                  , Str "emphasis"
+                  ]
+              ]
+          ]
+      , Para
+          [ Str "Here"
+          , Space
+          , Str "is"
+          , Space
+          , Str "a"
+          , Space
+          , Str "sidebar."
+          ]
+      , Div
+          ( "" , [ "tip" ] , [] )
+          [ Div ( "" , [ "title" ] , [] ) [ Para [ Str "Tip" ] ]
+          , Para
+              [ Str "It"
+              , Space
+              , Str "can"
+              , Space
+              , Str "contain"
+              , Space
+              , Str "any"
+              , Space
+              , Str "type"
+              , Space
+              , Str "of"
+              , Space
+              , Str "content."
+              ]
+          ]
+      ]
+  , Header
+      2
+      ( "_literal_block" , [] , [] )
+      [ Str "Literal" , Space , Str "block" ]
+  , Para
+      [ Str "Short"
+      , Space
+      , Str "indented"
+      , Space
+      , Str "code:"
+      ]
+  , CodeBlock
+      ( "" , [] , [] )
+      "$ ls -a\n$ cat /foo/bar/baz \\\n     /bi/bim/bop\n"
+  , CodeBlock
+      ( "" , [] , [] ) "This is\n  a literal block too.\n"
+  , CodeBlock
+      ( "" , [] , [] )
+      "  Fenced\n    $+ *a* literal\n\n****\nnot a sidebar\n****\n"
+  , Header 2 ( "_listing" , [] , [] ) [ Str "Listing" ]
+  , CodeBlock
+      ( "" , [ "ruby" ] , [] )
+      "require 'sinatra'\n\nget '/hi' do\n  \"Hello World!\"\nend"
+  , Para [ Str "Implied:" ]
+  , CodeBlock
+      ( "" , [ "ruby" ] , [] )
+      "require 'sinatra'\n\nget '/hi' do\n  \"Hello World!\"\nend"
+  , CodeBlock
+      ( "" , [ "ruby" ] , [] )
+      "# A function\ndef foo\n  return 42\nend"
+  , CodeBlock
+      ( "hello" , [ "haskell" ] , [] )
+      "putStrLn $ unwords [\"Hello\", \"world\"]"
+  , Para [ Str "Line" , Space , Str "numbering:" ]
+  , CodeBlock
+      ( "" , [] , [ ( "options" , "linenums" ) ] )
+      "puts 1\nputs 2\nputs 3"
+  , CodeBlock
+      ( "" , [] , [] ) "This doesn't have a language.\n  +=\"hi\""
+  , Para
+      [ Str "And"
+      , Space
+      , Str "with"
+      , Space
+      , Str "a"
+      , Space
+      , Str "callout"
+      , Space
+      , Str "list:"
+      ]
+  , CodeBlock
+      ( "" , [ "ruby" ] , [] )
+      "require 'sinatra' \9312\n\nget '/hi' do \9313 \9314\n  \"Hello World!\"\nend"
+  , Div
+      ( "" , [ "callout-list" ] , [] )
+      [ OrderedList
+          ( 1 , DefaultStyle , DefaultDelim )
+          [ [ Para [ Str "Library" , Space , Str "import" ] ]
+          , [ Para [ Str "URL" , Space , Str "mapping" ] ]
+          , [ Para [ Str "Response" , Space , Str "block" ] ]
+          ]
+      ]
+  , Para [ Str "Markdown-style" , Space , Str "fenced:" ]
+  , CodeBlock
+      ( "" , [ "ruby" ] , [] ) "def foo\n  return 5\nend"
+  , Header 2 ( "_verse" , [] , [] ) [ Str "Verse" ]
+  , BlockQuote
+      [ Para
+          [ Str "The"
+          , Space
+          , Str "fog"
+          , Space
+          , Str "comes"
+          , LineBreak
+          , Str "on"
+          , Space
+          , Str "little"
+          , Space
+          , Str "cat"
+          , Space
+          , Str "feet."
+          ]
+      , Para
+          [ Str "\8212"
+          , Space
+          , Str "Carl"
+          , Space
+          , Str "Sandburg,"
+          , Space
+          , Str "two"
+          , Space
+          , Str "lines"
+          , Space
+          , Str "from"
+          , Space
+          , Str "the"
+          , Space
+          , Str "poem"
+          , Space
+          , Str "Fog"
+          ]
+      ]
+  , BlockQuote
+      [ Para
+          [ Str "The"
+          , Space
+          , Str "fog"
+          , Space
+          , Str "comes"
+          , LineBreak
+          , Str "on"
+          , Space
+          , Str "little"
+          , Space
+          , Str "cat"
+          , Space
+          , Str "feet."
+          , LineBreak
+          , Str "It"
+          , Space
+          , Str "sits"
+          , Space
+          , Str "looking"
+          , LineBreak
+          , Str "over"
+          , Space
+          , Str "harbor"
+          , Space
+          , Str "and"
+          , Space
+          , Str "city"
+          , LineBreak
+          , Str "on"
+          , Space
+          , Str "silent"
+          , Space
+          , Str "haunches"
+          , LineBreak
+          , Str "and"
+          , Space
+          , Str "then"
+          , Space
+          , Str "moves"
+          , Space
+          , Str "on."
+          ]
+      , Para
+          [ Str "\8212"
+          , Space
+          , Str "Carl"
+          , Space
+          , Str "Sandburg,"
+          , Space
+          , Str "Fog"
+          ]
+      ]
+  , Header
+      2 ( "_collapsible" , [] , [] ) [ Str "Collapsible" ]
+  , Para
+      [ Str "Click"
+      , Space
+      , Str "here"
+      , Space
+      , Str "for"
+      , Space
+      , Str "more."
+      ]
+  , Div
+      ( ""
+      , [ "example" ]
+      , [ ( "options" , "collapsible,open" ) ]
+      )
+      [ Para
+          [ Str "This"
+          , Space
+          , Str "is"
+          , Space
+          , Str "collapsible."
+          ]
+      , Para
+          [ Str "It"
+          , Space
+          , Str "can"
+          , Space
+          , Str "be"
+          , Space
+          , Str "hidden."
+          ]
+      ]
+  , Div
+      ( "" , [] , [ ( "options" , "collapsible" ) ] )
+      [ Div
+          ( "" , [ "title" ] , [] )
+          [ Para [ Str "Click" , Space , Str "me!" ] ]
+      , Para
+          [ Str "This"
+          , Space
+          , Str "paragraph"
+          , Space
+          , Str "is"
+          , SoftBreak
+          , Str "also"
+          , Space
+          , Str "collapsible."
+          ]
+      ]
+  , Header 2 ( "_quote" , [] , [] ) [ Str "Quote" ]
+  , BlockQuote
+      [ Para
+          [ Str "Everybody"
+          , Space
+          , Str "remember"
+          , Space
+          , Str "where"
+          , Space
+          , Str "we"
+          , Space
+          , Str "parked."
+          ]
+      , Para
+          [ Str "\8212"
+          , Space
+          , Str "Captain"
+          , Space
+          , Str "James"
+          , Space
+          , Str "T."
+          , Space
+          , Str "Kirk,"
+          , Space
+          , Str "Star"
+          , Space
+          , Str "Trek"
+          , Space
+          , Str "IV:"
+          , Space
+          , Str "The"
+          , Space
+          , Str "Voyage"
+          , Space
+          , Str "Home"
+          ]
+      ]
+  , BlockQuote
+      [ Para
+          [ Str "Dennis:"
+          , Space
+          , Str "Come"
+          , Space
+          , Str "and"
+          , Space
+          , Str "see"
+          , Space
+          , Str "the"
+          , Space
+          , Str "violence"
+          , Space
+          , Str "inherent"
+          , Space
+          , Str "in"
+          , Space
+          , Str "the"
+          , Space
+          , Str "system."
+          , Space
+          , Str "Help!"
+          , Space
+          , Str "Help!"
+          , Space
+          , Str "I\8217m"
+          , Space
+          , Str "being"
+          , SoftBreak
+          , Str "repressed."
+          ]
+      , Para
+          [ Str "King"
+          , Space
+          , Str "Arthur:"
+          , Space
+          , Str "Bloody"
+          , Space
+          , Str "peasant!"
+          ]
+      , Para
+          [ Str "Dennis:"
+          , Space
+          , Str "Oh,"
+          , Space
+          , Str "what"
+          , Space
+          , Str "a"
+          , Space
+          , Str "giveaway!"
+          , Space
+          , Str "Did"
+          , Space
+          , Str "you"
+          , Space
+          , Str "hear"
+          , Space
+          , Str "that?"
+          , Space
+          , Str "Did"
+          , Space
+          , Str "you"
+          , Space
+          , Str "hear"
+          , Space
+          , Str "that,"
+          , Space
+          , Str "eh?"
+          , Space
+          , Str "That\8217s"
+          , Space
+          , Str "what"
+          , Space
+          , Str "I\8217m"
+          , SoftBreak
+          , Str "on"
+          , Space
+          , Str "about!"
+          , Space
+          , Str "Did"
+          , Space
+          , Str "you"
+          , Space
+          , Str "see"
+          , Space
+          , Str "him"
+          , Space
+          , Str "repressing"
+          , Space
+          , Str "me?"
+          , Space
+          , Str "You"
+          , Space
+          , Str "saw"
+          , Space
+          , Str "him,"
+          , Space
+          , Str "Didn\8217t"
+          , Space
+          , Str "you?"
+          ]
+      , Para
+          [ Str "\8212"
+          , Space
+          , Str "Monty"
+          , Space
+          , Str "Python"
+          , Space
+          , Str "and"
+          , Space
+          , Str "the"
+          , Space
+          , Str "Holy"
+          , Space
+          , Str "Grail"
+          ]
+      ]
+  , Div
+      ( "roads" , [ "movie" ] , [ ( "wrapper" , "1" ) ] )
+      [ BlockQuote
+          [ Para
+              [ Str "Roads?"
+              , Space
+              , Str "Where"
+              , Space
+              , Str "we\8217re"
+              , Space
+              , Str "going,"
+              , Space
+              , Str "we"
+              , Space
+              , Str "don\8217t"
+              , Space
+              , Str "need"
+              , Space
+              , Str "roads."
+              ]
+          , Para
+              [ Str "\8212"
+              , Space
+              , Str "Dr."
+              , Space
+              , Str "Emmett"
+              , Space
+              , Str "Brown"
+              ]
+          ]
+      ]
+  , Header 2 ( "_pass" , [] , [] ) [ Str "Pass" ]
+  , Para [ Str "pass" , Space , Emph [ Str "through" ] ]
+  , Header
+      2
+      ( "_open_block" , [] , [] )
+      [ Str "Open" , Space , Str "block" ]
+  , Div
+      ( "" , [] , [ ( "key" , "a value" ) ] )
+      [ Div
+          ( "" , [ "title" ] , [] )
+          [ Para [ Str "A" , Space , Str "title." ] ]
+      , Para
+          [ Str "Any"
+          , Space
+          , Str "content"
+          , Space
+          , Str "can"
+          , Space
+          , Str "go"
+          , Space
+          , Str "here:"
+          ]
+      , OrderedList
+          ( 1 , DefaultStyle , DefaultDelim )
+          [ [ Para [ Str "one" ] ] , [ Para [ Str "two" ] ] ]
+      ]
+  , Header 2 ( "_anchor" , [] , [] ) [ Str "Anchor" ]
+  , Div
+      ( "goals" , [] , [ ( "wrapper" , "1" ) ] )
+      [ BulletList
+          [ [ Para [ Str "one" ] ] , [ Para [ Str "two" ] ] ]
+      ]
+  , Header 2 ( "_breaks" , [] , [] ) [ Str "Breaks" ]
+  , Para
+      [ Str "Asciidoc"
+      , Space
+      , Str "thematic"
+      , Space
+      , Str "break:"
+      ]
+  , HorizontalRule
+  , Para [ Str "Markdown" , Space , Str "style:" ]
+  , HorizontalRule
+  , HorizontalRule
+  , HorizontalRule
+  , HorizontalRule
+  , Para [ Str "Page" , Space , Str "breaks:" ]
+  , Div
+      ( "" , [ "page-break" ] , [ ( "wrapper" , "1" ) ] )
+      [ HorizontalRule ]
+  , Div
+      ( ""
+      , [ "page-break" ]
+      , [ ( "options" , "always" ) , ( "wrapper" , "1" ) ]
+      )
+      [ HorizontalRule ]
+  , Header 2 ( "_list" , [] , [] ) [ Str "List" ]
+  , BulletList
+      [ [ Para
+            [ Str "Edgar" , Space , Str "Allan" , Space , Str "Poe" ]
+        ]
+      , [ Para
+            [ Str "Sheri" , Space , Str "S." , Space , Str "Tepper" ]
+        ]
+      , [ Para [ Str "Bill" , Space , Str "Bryson" ] ]
+      ]
+  , Div
+      ( "" , [] , [] )
+      [ Div
+          ( "" , [ "title" ] , [] )
+          [ Para
+              [ Str "Kizmet\8217s"
+              , Space
+              , Str "Favorite"
+              , Space
+              , Str "Authors"
+              ]
+          ]
+      , BulletList
+          [ [ Para
+                [ Str "Edgar"
+                , Space
+                , Str "Allan"
+                , Space
+                , Str "Poe"
+                ]
+            ]
+          , [ Para
+                [ Str "Sheri"
+                , Space
+                , Str "S."
+                , Space
+                , Str "Tepper"
+                ]
+            ]
+          , [ Para [ Str "Bill" , Space , Str "Bryson" ] ]
+          ]
+      ]
+  , BulletList
+      [ [ Para
+            [ Str "Edgar" , Space , Str "Allan" , Space , Str "Poe" ]
+        ]
+      , [ Para
+            [ Str "Sheri" , Space , Str "S." , Space , Str "Tepper" ]
+        ]
+      , [ Para [ Str "Bill" , Space , Str "Bryson" ] ]
+      ]
+  , OrderedList
+      ( 1 , DefaultStyle , DefaultDelim )
+      [ [ Para [ Str "Nested" , Space , Str "list" ]
+        , BulletList
+            [ [ Para
+                  [ Str "West"
+                  , Space
+                  , Str "wood"
+                  , Space
+                  , Str "maze"
+                  ]
+              , BulletList
+                  [ [ Para [ Str "Maze" , Space , Str "heart" ]
+                    , BulletList
+                        [ [ Para
+                              [ Str "Reflection" , Space , Str "pool" ]
+                          ]
+                        ]
+                    ]
+                  , [ Para [ Str "Secret" , Space , Str "exit" ] ]
+                  ]
+              ]
+            , [ Para
+                  [ Str "Level"
+                  , Space
+                  , Str "1"
+                  , Space
+                  , Str "list"
+                  , Space
+                  , Str "item"
+                  ]
+              , BulletList
+                  [ [ Para
+                        [ Str "Level"
+                        , Space
+                        , Str "2"
+                        , Space
+                        , Str "list"
+                        , Space
+                        , Str "item"
+                        ]
+                    , BulletList
+                        [ [ Para
+                              [ Str "Level"
+                              , Space
+                              , Str "3"
+                              , Space
+                              , Str "list"
+                              , Space
+                              , Str "item"
+                              ]
+                          , BulletList
+                              [ [ Para
+                                    [ Str "Level"
+                                    , Space
+                                    , Str "4"
+                                    , Space
+                                    , Str "list"
+                                    , Space
+                                    , Str "item"
+                                    ]
+                                , BulletList
+                                    [ [ Para
+                                          [ Str "Level"
+                                          , Space
+                                          , Str "5"
+                                          , Space
+                                          , Str "list"
+                                          , Space
+                                          , Str "item"
+                                          ]
+                                      , BulletList
+                                          [ [ Para [ Str "etc." ] ] ]
+                                      ]
+                                    ]
+                                ]
+                              ]
+                          ]
+                        ]
+                    ]
+                  ]
+              ]
+            , [ Para
+                  [ Str "Level"
+                  , Space
+                  , Str "1"
+                  , Space
+                  , Str "list"
+                  , Space
+                  , Str "item"
+                  ]
+              ]
+            ]
+        ]
+      ]
+  , BulletList
+      [ [ Para [ Str "one" ] ]
+      , [ Para [ Str "two" ] ]
+      , [ Para [ Str "three" ] ]
+      ]
+  , OrderedList
+      ( 1 , DefaultStyle , DefaultDelim )
+      [ [ Para [ Str "Protons" ] ]
+      , [ Para [ Str "Electrons" ] ]
+      , [ Para [ Str "Neutrons" ] ]
+      ]
+  , OrderedList
+      ( 1 , DefaultStyle , DefaultDelim )
+      [ [ Para [ Str "Protons" ] ]
+      , [ Para [ Str "Electrons" ] ]
+      , [ Para [ Str "Neutrons" ] ]
+      ]
+  , Para
+      [ Str "Start" , Space , Str "with" , Space , Str "4:" ]
+  , OrderedList
+      ( 4 , DefaultStyle , DefaultDelim )
+      [ [ Para [ Str "Step" , Space , Str "four" ] ]
+      , [ Para [ Str "Step" , Space , Str "five" ] ]
+      , [ Para [ Str "Step" , Space , Str "six" ] ]
+      ]
+  , Para [ Str "or" ]
+  , OrderedList
+      ( 4 , DefaultStyle , DefaultDelim )
+      [ [ Para [ Str "Step" , Space , Str "four" ] ]
+      , [ Para [ Str "Step" , Space , Str "five" ] ]
+      , [ Para [ Str "Step" , Space , Str "six" ] ]
+      ]
+  , Para [ Str "Reversed:" ]
+  , Div
+      ( "" , [] , [ ( "options" , "reversed" ) ] )
+      [ Div
+          ( "" , [ "title" ] , [] )
+          [ Para
+              [ Str "Parts"
+              , Space
+              , Str "of"
+              , Space
+              , Str "an"
+              , Space
+              , Str "atom"
+              ]
+          ]
+      , OrderedList
+          ( 1 , DefaultStyle , DefaultDelim )
+          [ [ Para [ Str "Protons" ] ]
+          , [ Para [ Str "Electrons" ] ]
+          , [ Para [ Str "Neutrons" ] ]
+          ]
+      ]
+  , Para [ Str "Nested" ]
+  , OrderedList
+      ( 1 , DefaultStyle , DefaultDelim )
+      [ [ Para [ Str "Step" , Space , Str "1" ] ]
+      , [ Para [ Str "Step" , Space , Str "2" ]
+        , OrderedList
+            ( 1 , DefaultStyle , DefaultDelim )
+            [ [ Para [ Str "Step" , Space , Str "2a" ] ]
+            , [ Para [ Str "Step" , Space , Str "2b" ] ]
+            ]
+        ]
+      , [ Para [ Str "Step" , Space , Str "3" ] ]
+      ]
+  , Para [ Str "Mixed" , Space , Str "nested" ]
+  , OrderedList
+      ( 1 , DefaultStyle , DefaultDelim )
+      [ [ Para [ Str "Linux" ]
+        , BulletList
+            [ [ Para [ Str "Fedora" ] ]
+            , [ Para [ Str "Ubuntu" ] ]
+            , [ Para [ Str "Slackware" ] ]
+            ]
+        ]
+      , [ Para [ Str "BSD" ]
+        , BulletList
+            [ [ Para [ Str "FreeBSD" ] ] , [ Para [ Str "NetBSD" ] ] ]
+        ]
+      ]
+  , Para [ Str "With" , Space , Str "spacing" ]
+  , OrderedList
+      ( 1 , DefaultStyle , DefaultDelim )
+      [ [ Para [ Str "Linux" ]
+        , BulletList
+            [ [ Para [ Str "Fedora" ] ]
+            , [ Para [ Str "Ubuntu" ] ]
+            , [ Para [ Str "Slackware" ] ]
+            ]
+        ]
+      , [ Para [ Str "BSD" ]
+        , BulletList
+            [ [ Para [ Str "FreeBSD" ] ] , [ Para [ Str "NetBSD" ] ] ]
+        ]
+      ]
+  , Para
+      [ Str "With" , Space , Str "number" , Space , Str "styles" ]
+  , OrderedList
+      ( 5 , LowerRoman , DefaultDelim )
+      [ [ Para [ Str "Five" ] ]
+      , [ Para [ Str "Six" ]
+        , OrderedList
+            ( 1 , LowerAlpha , DefaultDelim )
+            [ [ Para [ Str "a" ] ]
+            , [ Para [ Str "b" ] ]
+            , [ Para [ Str "c" ] ]
+            ]
+        ]
+      , [ Para [ Str "Seven" ] ]
+      ]
+  , Para [ Str "Checklist" ]
+  , BulletList
+      [ [ Para [ Str "\9746" , Space , Str "checked" ] ]
+      , [ Para
+            [ Str "\9746" , Space , Str "also" , Space , Str "checked" ]
+        ]
+      , [ Para
+            [ Str "\9744" , Space , Str "not" , Space , Str "checked" ]
+        ]
+      , [ Para
+            [ Str "normal" , Space , Str "list" , Space , Str "item" ]
+        ]
+      ]
+  , Para
+      [ Str "Separate"
+      , Space
+      , Str "lists"
+      , Space
+      , Str "with"
+      , Space
+      , Str "block"
+      , Space
+      , Str "attribute"
+      ]
+  , BulletList
+      [ [ Para [ Str "Apples" ] ]
+      , [ Para [ Str "Oranges" ]
+        , OrderedList
+            ( 1 , DefaultStyle , DefaultDelim )
+            [ [ Para [ Str "Wash" ] ] , [ Para [ Str "Slice" ] ] ]
+        ]
+      ]
+  , Para [ Str "Multiline" , Space , Str "items" ]
+  , BulletList
+      [ [ Para
+            [ Str "Blah"
+            , Space
+            , Str "blah."
+            , SoftBreak
+            , Str "Blah"
+            , Space
+            , Str "blah."
+            ]
+        ]
+      , [ Para
+            [ Str "The"
+            , Space
+            , Str "document"
+            , Space
+            , Str "header"
+            , Space
+            , Str "in"
+            , Space
+            , Str "AsciiDoc"
+            , Space
+            , Str "is"
+            , Space
+            , Str "optional."
+            , SoftBreak
+            , Str "If"
+            , Space
+            , Str "present,"
+            , Space
+            , Str "it"
+            , Space
+            , Str "must"
+            , Space
+            , Str "start"
+            , Space
+            , Str "with"
+            , Space
+            , Str "a"
+            , Space
+            , Str "document"
+            , Space
+            , Str "title."
+            ]
+        ]
+      ]
+  , BulletList
+      [ [ Para
+            [ Str "Optional"
+            , Space
+            , Str "author"
+            , Space
+            , Str "and"
+            , Space
+            , Str "revision"
+            , Space
+            , Str "information"
+            , Space
+            , Str "lines"
+            , SoftBreak
+            , Str "immediately"
+            , Space
+            , Str "follow"
+            , Space
+            , Str "the"
+            , Space
+            , Str "document"
+            , Space
+            , Str "title."
+            ]
+        ]
+      ]
+  , BulletList
+      [ [ Para
+            [ Str "The"
+            , Space
+            , Str "document"
+            , Space
+            , Str "header"
+            , Space
+            , Str "must"
+            , Space
+            , Str "be"
+            , Space
+            , Str "separated"
+            , Space
+            , Str "from"
+            , SoftBreak
+            , Str "the"
+            , Space
+            , Str "remainder"
+            , Space
+            , Str "of"
+            , Space
+            , Str "the"
+            , Space
+            , Str "document"
+            , Space
+            , Str "by"
+            , Space
+            , Str "one"
+            , Space
+            , Str "or"
+            , Space
+            , Str "more"
+            , SoftBreak
+            , Str "empty"
+            , Space
+            , Str "lines"
+            , Space
+            , Str "and"
+            , Space
+            , Str "it"
+            , Space
+            , Str "cannot"
+            , Space
+            , Str "contain"
+            , Space
+            , Str "empty"
+            , Space
+            , Str "lines."
+            ]
+        ]
+      ]
+  , Para [ Str "Complex" , Space , Str "item" ]
+  , BulletList
+      [ [ Para
+            [ Str "The"
+            , Space
+            , Str "header"
+            , Space
+            , Str "in"
+            , Space
+            , Str "AsciiDoc"
+            , Space
+            , Str "must"
+            , Space
+            , Str "start"
+            , Space
+            , Str "with"
+            , Space
+            , Str "a"
+            , Space
+            , Str "document"
+            , Space
+            , Str "title."
+            ]
+        , CodeBlock ( "" , [] , [] ) "= Document Title"
+        , Para
+            [ Str "Keep"
+            , Space
+            , Str "in"
+            , Space
+            , Str "mind"
+            , Space
+            , Str "that"
+            , Space
+            , Str "the"
+            , Space
+            , Str "header"
+            , Space
+            , Str "is"
+            , Space
+            , Str "optional."
+            ]
+        ]
+      , [ Para
+            [ Str "Optional"
+            , Space
+            , Str "author"
+            , Space
+            , Str "and"
+            , Space
+            , Str "revision"
+            , Space
+            , Str "information"
+            , Space
+            , Str "lines"
+            , Space
+            , Str "immediately"
+            , Space
+            , Str "follow"
+            , Space
+            , Str "the"
+            , Space
+            , Str "document"
+            , SoftBreak
+            , Str "title."
+            ]
+        , CodeBlock
+            ( "" , [] , [] )
+            "= Document Title\nDoc Writer <doc.writer@asciidoc.org>\nv1.0, 2022-01-01"
+        ]
+      , [ Para [ Str "Second" , Space , Str "item" ] ]
+      ]
+  , Para
+      [ Str "Empty"
+      , Space
+      , Str "principle"
+      , Space
+      , Str "element:"
+      ]
+  , OrderedList
+      ( 1 , DefaultStyle , DefaultDelim )
+      [ [ Para [] , CodeBlock ( "" , [] , [] ) "test" ] ]
+  , Header 2 ( "_table" , [] , [] ) [ Str "Table" ]
+  , Header
+      3
+      ( "_simple_with_column_specs" , [] , [] )
+      [ Str "Simple"
+      , Space
+      , Str "with"
+      , Space
+      , Str "column"
+      , Space
+      , Str "specs"
+      ]
+  , Table
+      ( "" , [] , [] )
+      (Caption Nothing [])
+      [ ( AlignDefault , ColWidth 0.375 )
+      , ( AlignDefault , ColWidth 0.25 )
+      , ( AlignDefault , ColWidth 0.375 )
+      ]
+      (TableHead
+         ( "" , [] , [] )
+         [ Row
+             ( "" , [] , [] )
+             [ Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Para
+                     [ Str "This"
+                     , Space
+                     , Str "content"
+                     , Space
+                     , Str "is"
+                     , Space
+                     , Str "placed"
+                     , Space
+                     , Str "in"
+                     , Space
+                     , Str "the"
+                     , Space
+                     , Str "first"
+                     , Space
+                     , Str "cell"
+                     , Space
+                     , Str "of"
+                     , Space
+                     , Str "column"
+                     , Space
+                     , Str "1"
+                     ]
+                 ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Para
+                     [ Str "This"
+                     , Space
+                     , Str "line"
+                     , Space
+                     , Str "starts"
+                     , Space
+                     , Str "with"
+                     , Space
+                     , Str "a"
+                     , Space
+                     , Str "vertical"
+                     , Space
+                     , Str "bar"
+                     , Space
+                     , Str "so"
+                     , Space
+                     , Str "this"
+                     , Space
+                     , Str "content"
+                     , Space
+                     , Str "is"
+                     , Space
+                     , Str "placed"
+                     , Space
+                     , Str "in"
+                     , Space
+                     , Str "a"
+                     , Space
+                     , Str "new"
+                     , Space
+                     , Str "cell"
+                     , Space
+                     , Str "in"
+                     , SoftBreak
+                     , Str "column"
+                     , Space
+                     , Str "2"
+                     ]
+                 ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Para
+                     [ Str "When"
+                     , Space
+                     , Str "the"
+                     , Space
+                     , Str "processor"
+                     , Space
+                     , Str "encounters"
+                     , Space
+                     , Str "a"
+                     , Space
+                     , Str "whitespace"
+                     , Space
+                     , Str "followed"
+                     , Space
+                     , Str "by"
+                     , Space
+                     , Str "a"
+                     , Space
+                     , Str "vertical"
+                     , Space
+                     , Str "bar"
+                     , Space
+                     , Str "it"
+                     , SoftBreak
+                     , Str "ends"
+                     , Space
+                     , Str "the"
+                     , Space
+                     , Str "previous"
+                     , Space
+                     , Str "cell"
+                     , Space
+                     , Str "and"
+                     , Space
+                     , Str "starts"
+                     , Space
+                     , Str "a"
+                     , Space
+                     , Str "new"
+                     , Space
+                     , Str "cell"
+                     ]
+                 ]
+             ]
+         ])
+      [ TableBody ( "" , [] , [] ) (RowHeadColumns 0) [] [] ]
+      (TableFoot ( "" , [] , [] ) [])
+  , Header
+      3
+      ( "_repeated_column_in_specs" , [] , [] )
+      [ Str "Repeated"
+      , Space
+      , Str "column"
+      , Space
+      , Str "in"
+      , Space
+      , Str "specs"
+      ]
+  , Table
+      ( "" , [] , [] )
+      (Caption Nothing [])
+      [ ( AlignDefault , ColWidthDefault )
+      , ( AlignDefault , ColWidthDefault )
+      ]
+      (TableHead
+         ( "" , [] , [] )
+         [ Row
+             ( "" , [] , [] )
+             [ Cell
+                 ( "" , [] , [] )
+                 AlignRight
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Para
+                     [ Strong
+                         [ Str "This"
+                         , Space
+                         , Str "cell\8217s"
+                         , Space
+                         , Str "specifier"
+                         , Space
+                         , Str "indicates"
+                         , Space
+                         , Str "that"
+                         , Space
+                         , Str "this"
+                         , Space
+                         , Str "cell\8217s"
+                         , Space
+                         , Str "content"
+                         , Space
+                         , Str "is"
+                         , Space
+                         , Str "right-aligned"
+                         , Space
+                         , Str "and"
+                         , Space
+                         , Str "bold."
+                         ]
+                     ]
+                 ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Para
+                     [ Str "The"
+                     , Space
+                     , Str "cell"
+                     , Space
+                     , Str "specifier"
+                     , Space
+                     , Str "on"
+                     , Space
+                     , Str "this"
+                     , Space
+                     , Str "cell"
+                     , Space
+                     , Str "hasn\8217t"
+                     , Space
+                     , Str "been"
+                     , Space
+                     , Str "set"
+                     , Space
+                     , Str "explicitly,"
+                     , Space
+                     , Str "so"
+                     , Space
+                     , Str "the"
+                     , Space
+                     , Str "default"
+                     , SoftBreak
+                     , Str "properties"
+                     , Space
+                     , Str "are"
+                     , Space
+                     , Str "applied."
+                     ]
+                 ]
+             ]
+         ])
+      [ TableBody ( "" , [] , [] ) (RowHeadColumns 0) [] [] ]
+      (TableFoot ( "" , [] , [] ) [])
+  , Header
+      3
+      ( "_simple_without_column_specs" , [] , [] )
+      [ Str "Simple"
+      , Space
+      , Str "without"
+      , Space
+      , Str "column"
+      , Space
+      , Str "specs"
+      ]
+  , Table
+      ( "" , [] , [] )
+      (Caption Nothing [])
+      [ ( AlignDefault , ColWidthDefault )
+      , ( AlignDefault , ColWidthDefault )
+      ]
+      (TableHead
+         ( "" , [] , [] )
+         [ Row
+             ( "" , [] , [] )
+             [ Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Para
+                     [ Str "Column"
+                     , Space
+                     , Str "1,"
+                     , Space
+                     , Str "header"
+                     , Space
+                     , Str "row"
+                     ]
+                 ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Para
+                     [ Str "Column"
+                     , Space
+                     , Str "2,"
+                     , Space
+                     , Str "header"
+                     , Space
+                     , Str "row"
+                     ]
+                 ]
+             ]
+         ])
+      [ TableBody
+          ( "" , [] , [] )
+          (RowHeadColumns 0)
+          []
+          [ Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para
+                      [ Str "Cell"
+                      , Space
+                      , Str "in"
+                      , Space
+                      , Str "column"
+                      , Space
+                      , Str "1,"
+                      , Space
+                      , Str "row"
+                      , Space
+                      , Str "2"
+                      ]
+                  ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para
+                      [ Str "Cell"
+                      , Space
+                      , Str "in"
+                      , Space
+                      , Str "column"
+                      , Space
+                      , Str "2,"
+                      , Space
+                      , Str "row"
+                      , Space
+                      , Str "2"
+                      ]
+                  ]
+              ]
+          ]
+      ]
+      (TableFoot
+         ( "" , [] , [] )
+         [ Row
+             ( "" , [] , [] )
+             [ Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Para
+                     [ Str "Cell"
+                     , Space
+                     , Str "in"
+                     , Space
+                     , Str "column"
+                     , Space
+                     , Str "1,"
+                     , Space
+                     , Str "row"
+                     , Space
+                     , Str "3"
+                     ]
+                 ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Para
+                     [ Str "Cell"
+                     , Space
+                     , Str "in"
+                     , Space
+                     , Str "column"
+                     , Space
+                     , Str "2,"
+                     , Space
+                     , Str "row"
+                     , Space
+                     , Str "3"
+                     ]
+                 ]
+             ]
+         ])
+  , Header
+      3
+      ( "_with_caption" , [] , [] )
+      [ Str "With" , Space , Str "caption" ]
+  , Table
+      ( "" , [] , [] )
+      (Caption
+         Nothing
+         [ Plain
+             [ Str "My" , Space , Str "cool" , Space , Str "table." ]
+         ])
+      [ ( AlignDefault , ColWidthDefault )
+      , ( AlignDefault , ColWidthDefault )
+      ]
+      (TableHead
+         ( "" , [] , [] )
+         [ Row
+             ( "" , [] , [] )
+             [ Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Para
+                     [ Str "Column"
+                     , Space
+                     , Str "1,"
+                     , Space
+                     , Str "header"
+                     , Space
+                     , Str "row"
+                     ]
+                 ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Para
+                     [ Str "Column"
+                     , Space
+                     , Str "2,"
+                     , Space
+                     , Str "header"
+                     , Space
+                     , Str "row"
+                     ]
+                 ]
+             ]
+         ])
+      [ TableBody
+          ( "" , [] , [] )
+          (RowHeadColumns 0)
+          []
+          [ Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para
+                      [ Str "Cell"
+                      , Space
+                      , Str "in"
+                      , Space
+                      , Str "column"
+                      , Space
+                      , Str "1,"
+                      , Space
+                      , Str "row"
+                      , Space
+                      , Str "2"
+                      ]
+                  ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para
+                      [ Str "Cell"
+                      , Space
+                      , Str "in"
+                      , Space
+                      , Str "column"
+                      , Space
+                      , Str "2,"
+                      , Space
+                      , Str "row"
+                      , Space
+                      , Str "2"
+                      ]
+                  ]
+              ]
+          ]
+      ]
+      (TableFoot
+         ( "" , [] , [] )
+         [ Row
+             ( "" , [] , [] )
+             [ Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Para
+                     [ Str "Cell"
+                     , Space
+                     , Str "in"
+                     , Space
+                     , Str "column"
+                     , Space
+                     , Str "1,"
+                     , Space
+                     , Str "row"
+                     , Space
+                     , Str "3"
+                     ]
+                 ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Para
+                     [ Str "Cell"
+                     , Space
+                     , Str "in"
+                     , Space
+                     , Str "column"
+                     , Space
+                     , Str "2,"
+                     , Space
+                     , Str "row"
+                     , Space
+                     , Str "3"
+                     ]
+                 ]
+             ]
+         ])
+  , Header
+      3
+      ( "_no_header" , [] , [] )
+      [ Str "No" , Space , Str "header" ]
+  , Para
+      [ Str "By"
+      , Space
+      , Str "default"
+      , Space
+      , Str "the"
+      , Space
+      , Str "first"
+      , Space
+      , Str "line"
+      , Space
+      , Str "should"
+      , Space
+      , Str "turn"
+      , Space
+      , Str "into"
+      , Space
+      , Str "the"
+      , Space
+      , Str "header,"
+      , Space
+      , Str "but"
+      , Space
+      , Str "this"
+      , SoftBreak
+      , Str "can"
+      , Space
+      , Str "be"
+      , Space
+      , Str "disabled:"
+      ]
+  , Table
+      ( "" , [] , [] )
+      (Caption Nothing [])
+      [ ( AlignDefault , ColWidthDefault )
+      , ( AlignDefault , ColWidthDefault )
+      ]
+      (TableHead ( "" , [] , [] ) [])
+      [ TableBody
+          ( "" , [] , [] )
+          (RowHeadColumns 0)
+          []
+          [ Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para
+                      [ Str "Cell"
+                      , Space
+                      , Str "in"
+                      , Space
+                      , Str "column"
+                      , Space
+                      , Str "1,"
+                      , Space
+                      , Str "row"
+                      , Space
+                      , Str "1"
+                      ]
+                  ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para
+                      [ Str "Cell"
+                      , Space
+                      , Str "in"
+                      , Space
+                      , Str "column"
+                      , Space
+                      , Str "2,"
+                      , Space
+                      , Str "row"
+                      , Space
+                      , Str "1"
+                      ]
+                  ]
+              ]
+          ]
+      ]
+      (TableFoot
+         ( "" , [] , [] )
+         [ Row
+             ( "" , [] , [] )
+             [ Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Para
+                     [ Str "Cell"
+                     , Space
+                     , Str "in"
+                     , Space
+                     , Str "column"
+                     , Space
+                     , Str "1,"
+                     , Space
+                     , Str "row"
+                     , Space
+                     , Str "2"
+                     ]
+                 ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Para
+                     [ Str "Cell"
+                     , Space
+                     , Str "in"
+                     , Space
+                     , Str "column"
+                     , Space
+                     , Str "2,"
+                     , Space
+                     , Str "row"
+                     , Space
+                     , Str "2"
+                     ]
+                 ]
+             ]
+         ])
+  , Para
+      [ Str "And"
+      , Space
+      , Str "also"
+      , Space
+      , Str "explicitly"
+      , Space
+      , Str "enabled:"
+      ]
+  , Table
+      ( "" , [] , [] )
+      (Caption Nothing [])
+      [ ( AlignDefault , ColWidthDefault )
+      , ( AlignDefault , ColWidthDefault )
+      ]
+      (TableHead
+         ( "" , [] , [] )
+         [ Row
+             ( "" , [] , [] )
+             [ Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Para [ Str "Cell" , Space , Str "A1" ] ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Para [ Str "Cell" , Space , Str "B1" ] ]
+             ]
+         ])
+      [ TableBody
+          ( "" , [] , [] )
+          (RowHeadColumns 0)
+          []
+          [ Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para [ Str "Cell" , Space , Str "A2" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para [ Str "Cell" , Space , Str "B2" ] ]
+              ]
+          ]
+      ]
+      (TableFoot
+         ( "" , [] , [] )
+         [ Row
+             ( "" , [] , [] )
+             [ Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Para [ Str "Cell" , Space , Str "A3" ] ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Para [ Str "Cell" , Space , Str "B3" ] ]
+             ]
+         ])
+  , Header 3 ( "_footer" , [] , [] ) [ Str "Footer" ]
+  , Table
+      ( "" , [] , [] )
+      (Caption Nothing [])
+      [ ( AlignDefault , ColWidth 0.4 )
+      , ( AlignDefault , ColWidth 0.4 )
+      , ( AlignDefault , ColWidth 0.2 )
+      ]
+      (TableHead
+         ( "" , [] , [] )
+         [ Row
+             ( "" , [] , [] )
+             [ Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Para
+                     [ Str "Column"
+                     , Space
+                     , Str "1,"
+                     , Space
+                     , Str "header"
+                     , Space
+                     , Str "row"
+                     ]
+                 ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Para
+                     [ Str "Column"
+                     , Space
+                     , Str "2,"
+                     , Space
+                     , Str "header"
+                     , Space
+                     , Str "row"
+                     ]
+                 ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Para
+                     [ Str "Column"
+                     , Space
+                     , Str "3,"
+                     , Space
+                     , Str "header"
+                     , Space
+                     , Str "row"
+                     ]
+                 ]
+             ]
+         ])
+      [ TableBody
+          ( "" , [] , [] )
+          (RowHeadColumns 0)
+          []
+          [ Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para
+                      [ Str "Cell"
+                      , Space
+                      , Str "in"
+                      , Space
+                      , Str "column"
+                      , Space
+                      , Str "1,"
+                      , Space
+                      , Str "row"
+                      , Space
+                      , Str "2"
+                      ]
+                  ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para
+                      [ Str "Cell"
+                      , Space
+                      , Str "in"
+                      , Space
+                      , Str "column"
+                      , Space
+                      , Str "2,"
+                      , Space
+                      , Str "row"
+                      , Space
+                      , Str "2"
+                      ]
+                  ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para
+                      [ Str "Cell"
+                      , Space
+                      , Str "in"
+                      , Space
+                      , Str "column"
+                      , Space
+                      , Str "3,"
+                      , Space
+                      , Str "row"
+                      , Space
+                      , Str "2"
+                      ]
+                  ]
+              ]
+          ]
+      ]
+      (TableFoot
+         ( "" , [] , [] )
+         [ Row
+             ( "" , [] , [] )
+             [ Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Para
+                     [ Str "Column"
+                     , Space
+                     , Str "1,"
+                     , Space
+                     , Str "footer"
+                     , Space
+                     , Str "row"
+                     ]
+                 ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Para
+                     [ Str "Column"
+                     , Space
+                     , Str "2,"
+                     , Space
+                     , Str "footer"
+                     , Space
+                     , Str "row"
+                     ]
+                 ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Para
+                     [ Str "Column"
+                     , Space
+                     , Str "3,"
+                     , Space
+                     , Str "footer"
+                     , Space
+                     , Str "row"
+                     ]
+                 ]
+             ]
+         ])
+  , Para [ Str "or" ]
+  , Table
+      ( "" , [] , [] )
+      (Caption Nothing [])
+      [ ( AlignDefault , ColWidthDefault )
+      , ( AlignDefault , ColWidthDefault )
+      ]
+      (TableHead
+         ( "" , [] , [] )
+         [ Row
+             ( "" , [] , [] )
+             [ Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Para
+                     [ Str "Column"
+                     , Space
+                     , Str "1,"
+                     , Space
+                     , Str "header"
+                     , Space
+                     , Str "row"
+                     ]
+                 ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Para
+                     [ Str "Column"
+                     , Space
+                     , Str "2,"
+                     , Space
+                     , Str "header"
+                     , Space
+                     , Str "row"
+                     ]
+                 ]
+             ]
+         ])
+      [ TableBody
+          ( "" , [] , [] )
+          (RowHeadColumns 0)
+          []
+          [ Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para
+                      [ Str "Cell"
+                      , Space
+                      , Str "in"
+                      , Space
+                      , Str "column"
+                      , Space
+                      , Str "1,"
+                      , Space
+                      , Str "row"
+                      , Space
+                      , Str "2"
+                      ]
+                  ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para
+                      [ Str "Cell"
+                      , Space
+                      , Str "in"
+                      , Space
+                      , Str "column"
+                      , Space
+                      , Str "2,"
+                      , Space
+                      , Str "row"
+                      , Space
+                      , Str "2"
+                      ]
+                  ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para
+                      [ Str "Cell"
+                      , Space
+                      , Str "in"
+                      , Space
+                      , Str "column"
+                      , Space
+                      , Str "1,"
+                      , Space
+                      , Str "row"
+                      , Space
+                      , Str "3"
+                      ]
+                  ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para
+                      [ Str "Cell"
+                      , Space
+                      , Str "in"
+                      , Space
+                      , Str "column"
+                      , Space
+                      , Str "2,"
+                      , Space
+                      , Str "row"
+                      , Space
+                      , Str "3"
+                      ]
+                  ]
+              ]
+          ]
+      ]
+      (TableFoot
+         ( "" , [] , [] )
+         [ Row
+             ( "" , [] , [] )
+             [ Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Para
+                     [ Str "Column"
+                     , Space
+                     , Str "1,"
+                     , Space
+                     , Str "footer"
+                     , Space
+                     , Str "row"
+                     ]
+                 ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Para
+                     [ Str "Column"
+                     , Space
+                     , Str "2,"
+                     , Space
+                     , Str "footer"
+                     , Space
+                     , Str "row"
+                     ]
+                 ]
+             ]
+         ])
+  , Header 3 ( "_alignment" , [] , [] ) [ Str "Alignment" ]
+  , Table
+      ( "" , [] , [] )
+      (Caption Nothing [])
+      [ ( AlignDefault , ColWidthDefault )
+      , ( AlignDefault , ColWidthDefault )
+      ]
+      (TableHead
+         ( "" , [] , [] )
+         [ Row
+             ( "" , [] , [] )
+             [ Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Para [ Str "Column" , Space , Str "Name" ] ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Para [ Str "Column" , Space , Str "Name" ] ]
+             ]
+         ])
+      [ TableBody
+          ( "" , [] , [] )
+          (RowHeadColumns 0)
+          []
+          [ Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignCenter
+                  (RowSpan 1)
+                  (ColSpan 2)
+                  [ Para
+                      [ Str "This"
+                      , Space
+                      , Str "cell"
+                      , Space
+                      , Str "spans"
+                      , Space
+                      , Str "two"
+                      , Space
+                      , Str "columns,"
+                      , Space
+                      , Str "and"
+                      , Space
+                      , Str "its"
+                      , Space
+                      , Str "content"
+                      , Space
+                      , Str "is"
+                      , Space
+                      , Str "horizontally"
+                      , Space
+                      , Str "centered"
+                      , Space
+                      , Str "because"
+                      , Space
+                      , Str "the"
+                      , SoftBreak
+                      , Str "cell"
+                      , Space
+                      , Str "specifier"
+                      , Space
+                      , Str "includes"
+                      , Space
+                      , Str "the"
+                      , Space
+                      , Code ( "" , [] , [] ) "^"
+                      , Space
+                      , Str "operator."
+                      ]
+                  ]
+              ]
+          ]
+      ]
+      (TableFoot
+         ( "" , [] , [] )
+         [ Row
+             ( "" , [] , [] )
+             [ Cell
+                 ( "" , [] , [] )
+                 AlignCenter
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Para
+                     [ Str "This"
+                     , Space
+                     , Str "content"
+                     , Space
+                     , Str "is"
+                     , Space
+                     , Str "duplicated"
+                     , Space
+                     , Str "in"
+                     , Space
+                     , Str "two"
+                     , Space
+                     , Str "adjacent"
+                     , Space
+                     , Str "columns."
+                     , SoftBreak
+                     , Str "Its"
+                     , Space
+                     , Str "content"
+                     , Space
+                     , Str "is"
+                     , Space
+                     , Str "horizontally"
+                     , Space
+                     , Str "centered"
+                     , Space
+                     , Str "because"
+                     , Space
+                     , Str "the"
+                     , Space
+                     , Str "cell"
+                     , Space
+                     , Str "specifier"
+                     , SoftBreak
+                     , Str "includes"
+                     , Space
+                     , Str "the"
+                     , Space
+                     , Code ( "" , [] , [] ) "^"
+                     , Space
+                     , Str "operator."
+                     ]
+                 ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignCenter
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Para
+                     [ Str "This"
+                     , Space
+                     , Str "content"
+                     , Space
+                     , Str "is"
+                     , Space
+                     , Str "duplicated"
+                     , Space
+                     , Str "in"
+                     , Space
+                     , Str "two"
+                     , Space
+                     , Str "adjacent"
+                     , Space
+                     , Str "columns."
+                     , SoftBreak
+                     , Str "Its"
+                     , Space
+                     , Str "content"
+                     , Space
+                     , Str "is"
+                     , Space
+                     , Str "horizontally"
+                     , Space
+                     , Str "centered"
+                     , Space
+                     , Str "because"
+                     , Space
+                     , Str "the"
+                     , Space
+                     , Str "cell"
+                     , Space
+                     , Str "specifier"
+                     , SoftBreak
+                     , Str "includes"
+                     , Space
+                     , Str "the"
+                     , Space
+                     , Code ( "" , [] , [] ) "^"
+                     , Space
+                     , Str "operator."
+                     ]
+                 ]
+             ]
+         ])
+  , Header
+      3
+      ( "_multiple_paragraphs_in_cells" , [] , [] )
+      [ Str "Multiple"
+      , Space
+      , Str "paragraphs"
+      , Space
+      , Str "in"
+      , Space
+      , Str "cells"
+      ]
+  , Table
+      ( "" , [] , [] )
+      (Caption Nothing [])
+      [ ( AlignDefault , ColWidthDefault ) ]
+      (TableHead
+         ( "" , [] , [] )
+         [ Row
+             ( "" , [] , [] )
+             [ Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Para
+                     [ Str "Single"
+                     , Space
+                     , Str "paragraph"
+                     , Space
+                     , Str "on"
+                     , Space
+                     , Str "row"
+                     , Space
+                     , Str "1"
+                     ]
+                 ]
+             ]
+         ])
+      [ TableBody ( "" , [] , [] ) (RowHeadColumns 0) [] [] ]
+      (TableFoot
+         ( "" , [] , [] )
+         [ Row
+             ( "" , [] , [] )
+             [ Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Para
+                     [ Str "First"
+                     , Space
+                     , Str "paragraph"
+                     , Space
+                     , Str "on"
+                     , Space
+                     , Str "row"
+                     , Space
+                     , Str "2"
+                     ]
+                 , Para
+                     [ Str "Second"
+                     , Space
+                     , Str "paragraph"
+                     , Space
+                     , Str "on"
+                     , Space
+                     , Str "row"
+                     , Space
+                     , Str "2"
+                     ]
+                 ]
+             ]
+         ])
+  , Header
+      3
+      ( "_complex_table" , [] , [] )
+      [ Str "Complex" , Space , Str "table" ]
+  , Table
+      ( "" , [] , [] )
+      (Caption Nothing [])
+      [ ( AlignDefault , ColWidthDefault )
+      , ( AlignDefault , ColWidthDefault )
+      ]
+      (TableHead
+         ( "" , [] , [] )
+         [ Row
+             ( "" , [] , [] )
+             [ Cell
+                 ( "" , [] , [] )
+                 AlignRight
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Para
+                     [ Code ( "" , [] , [] ) "This"
+                     , Space
+                     , Code ( "" , [] , [] ) "content"
+                     , Space
+                     , Code ( "" , [] , [] ) "is"
+                     , Space
+                     , Code ( "" , [] , [] ) "duplicated"
+                     , Space
+                     , Code ( "" , [] , [] ) "across"
+                     , Space
+                     , Code ( "" , [] , [] ) "two"
+                     , Space
+                     , Code ( "" , [] , [] ) "columns."
+                     ]
+                 , Para
+                     [ Code ( "" , [] , [] ) "It"
+                     , Space
+                     , Code ( "" , [] , [] ) "is"
+                     , Space
+                     , Code ( "" , [] , [] ) "aligned"
+                     , Space
+                     , Code ( "" , [] , [] ) "right"
+                     , Space
+                     , Code ( "" , [] , [] ) "horizontally."
+                     ]
+                 , Para
+                     [ Code ( "" , [] , [] ) "And"
+                     , Space
+                     , Code ( "" , [] , [] ) "it"
+                     , Space
+                     , Code ( "" , [] , [] ) "is"
+                     , Space
+                     , Code ( "" , [] , [] ) "monospaced."
+                     ]
+                 ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignRight
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Para
+                     [ Code ( "" , [] , [] ) "This"
+                     , Space
+                     , Code ( "" , [] , [] ) "content"
+                     , Space
+                     , Code ( "" , [] , [] ) "is"
+                     , Space
+                     , Code ( "" , [] , [] ) "duplicated"
+                     , Space
+                     , Code ( "" , [] , [] ) "across"
+                     , Space
+                     , Code ( "" , [] , [] ) "two"
+                     , Space
+                     , Code ( "" , [] , [] ) "columns."
+                     ]
+                 , Para
+                     [ Code ( "" , [] , [] ) "It"
+                     , Space
+                     , Code ( "" , [] , [] ) "is"
+                     , Space
+                     , Code ( "" , [] , [] ) "aligned"
+                     , Space
+                     , Code ( "" , [] , [] ) "right"
+                     , Space
+                     , Code ( "" , [] , [] ) "horizontally."
+                     ]
+                 , Para
+                     [ Code ( "" , [] , [] ) "And"
+                     , Space
+                     , Code ( "" , [] , [] ) "it"
+                     , Space
+                     , Code ( "" , [] , [] ) "is"
+                     , Space
+                     , Code ( "" , [] , [] ) "monospaced."
+                     ]
+                 ]
+             ]
+         ])
+      [ TableBody
+          ( "" , [] , [] )
+          (RowHeadColumns 0)
+          []
+          [ Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignCenter
+                  (RowSpan 2)
+                  (ColSpan 1)
+                  [ Para
+                      [ Strong
+                          [ Str "This"
+                          , Space
+                          , Str "cell"
+                          , Space
+                          , Str "spans"
+                          , Space
+                          , Str "3"
+                          , Space
+                          , Str "rows."
+                          , Space
+                          , Str "The"
+                          , Space
+                          , Str "content"
+                          , Space
+                          , Str "is"
+                          , Space
+                          , Str "centered"
+                          , Space
+                          , Str "horizontally,"
+                          , Space
+                          , Str "aligned"
+                          , Space
+                          , Str "to"
+                          , Space
+                          , Str "the"
+                          , Space
+                          , Str "bottom"
+                          , Space
+                          , Str "of"
+                          , Space
+                          , Str "the"
+                          , Space
+                          , Str "cell,"
+                          , Space
+                          , Str "and"
+                          , Space
+                          , Str "strong."
+                          ]
+                      ]
+                  ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para
+                      [ Emph
+                          [ Str "This"
+                          , Space
+                          , Str "content"
+                          , Space
+                          , Str "is"
+                          , Space
+                          , Str "emphasized."
+                          ]
+                      ]
+                  ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ CodeBlock
+                      ( "" , [] , [] )
+                      "This content is aligned to the top of the cell and literal.\n\n"
+                  ]
+              ]
+          ]
+      ]
+      (TableFoot
+         ( "" , [] , [] )
+         [ Row
+             ( "" , [] , [] )
+             [ Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ CodeBlock
+                     ( "" , [] , [] ) "puts \"This is a source block!\""
+                 ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 []
+             ]
+         ])
+  , Header
+      3
+      ( "_column_styles" , [] , [] )
+      [ Str "Column" , Space , Str "styles" ]
+  , Table
+      ( "" , [] , [] )
+      (Caption Nothing [])
+      [ ( AlignDefault , ColWidthDefault )
+      , ( AlignDefault , ColWidthDefault )
+      ]
+      (TableHead
+         ( "" , [] , [] )
+         [ Row
+             ( "" , [] , [] )
+             [ Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Para [ Code ( "" , [] , [] ) "monospace" ] ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Para [ Code ( "" , [] , [] ) "mono" ] ]
+             ]
+         ])
+      [ TableBody ( "" , [] , [] ) (RowHeadColumns 0) [] [] ]
+      (TableFoot
+         ( "" , [] , [] )
+         [ Row
+             ( "" , [] , [] )
+             [ Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Para [ Str "default" ] ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Para [ Code ( "" , [] , [] ) "mono" ] ]
+             ]
+         ])
+  , Header
+      3
+      ( "_block_elements_in_cells" , [] , [] )
+      [ Str "Block"
+      , Space
+      , Str "elements"
+      , Space
+      , Str "in"
+      , Space
+      , Str "cells"
+      ]
+  , Table
+      ( "" , [] , [] )
+      (Caption Nothing [])
+      [ ( AlignDefault , ColWidthDefault )
+      , ( AlignDefault , ColWidthDefault )
+      ]
+      (TableHead
+         ( "" , [] , [] )
+         [ Row
+             ( "" , [] , [] )
+             [ Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Para [ Str "Normal" , Space , Str "Style" ] ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Para [ Str "AsciiDoc" , Space , Str "Style" ] ]
+             ]
+         ])
+      [ TableBody
+          ( "" , [] , [] )
+          (RowHeadColumns 0)
+          []
+          [ Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para
+                      [ Str "This"
+                      , Space
+                      , Str "cell"
+                      , Space
+                      , Str "isn\8217t"
+                      , Space
+                      , Str "prefixed"
+                      , Space
+                      , Str "with"
+                      , Space
+                      , Str "an"
+                      , Space
+                      , Code ( "" , [] , [] ) "a"
+                      , Str ","
+                      , Space
+                      , Str "so"
+                      , Space
+                      , Str "the"
+                      , Space
+                      , Str "processor"
+                      , Space
+                      , Str "doesn\8217t"
+                      , Space
+                      , Str "interpret"
+                      , Space
+                      , Str "the"
+                      , SoftBreak
+                      , Str "following"
+                      , Space
+                      , Str "lines"
+                      , Space
+                      , Str "as"
+                      , Space
+                      , Str "an"
+                      , Space
+                      , Str "AsciiDoc"
+                      , Space
+                      , Str "list."
+                      ]
+                  , Para
+                      [ Str "*"
+                      , Space
+                      , Str "List"
+                      , Space
+                      , Str "item"
+                      , Space
+                      , Str "1"
+                      , SoftBreak
+                      , Str "*"
+                      , Space
+                      , Str "List"
+                      , Space
+                      , Str "item"
+                      , Space
+                      , Str "2"
+                      , SoftBreak
+                      , Str "*"
+                      , Space
+                      , Str "List"
+                      , Space
+                      , Str "item"
+                      , Space
+                      , Str "3"
+                      ]
+                  ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para
+                      [ Str "This"
+                      , Space
+                      , Str "cell"
+                      , Space
+                      , Str "is"
+                      , Space
+                      , Str "prefixed"
+                      , Space
+                      , Str "with"
+                      , Space
+                      , Str "an"
+                      , Space
+                      , Code ( "" , [] , [] ) "a"
+                      , Str ","
+                      , Space
+                      , Str "so"
+                      , Space
+                      , Str "the"
+                      , Space
+                      , Str "processor"
+                      , Space
+                      , Str "interprets"
+                      , Space
+                      , Str "the"
+                      , Space
+                      , Str "following"
+                      , Space
+                      , Str "lines"
+                      , SoftBreak
+                      , Str "as"
+                      , Space
+                      , Str "an"
+                      , Space
+                      , Str "AsciiDoc"
+                      , Space
+                      , Str "list."
+                      ]
+                  , BulletList
+                      [ [ Para
+                            [ Str "List"
+                            , Space
+                            , Str "item"
+                            , Space
+                            , Str "1"
+                            ]
+                        ]
+                      , [ Para
+                            [ Str "List"
+                            , Space
+                            , Str "item"
+                            , Space
+                            , Str "2"
+                            ]
+                        ]
+                      , [ Para
+                            [ Str "List"
+                            , Space
+                            , Str "item"
+                            , Space
+                            , Str "3"
+                            ]
+                        ]
+                      ]
+                  ]
+              ]
+          ]
+      ]
+      (TableFoot
+         ( "" , [] , [] )
+         [ Row
+             ( "" , [] , [] )
+             [ Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Para
+                     [ Str "This"
+                     , Space
+                     , Str "cell"
+                     , Space
+                     , Str "isn\8217t"
+                     , Space
+                     , Str "prefixed"
+                     , Space
+                     , Str "with"
+                     , Space
+                     , Str "an"
+                     , Space
+                     , Code ( "" , [] , [] ) "a"
+                     , Str ","
+                     , Space
+                     , Str "so"
+                     , Space
+                     , Str "the"
+                     , Space
+                     , Str "processor"
+                     , Space
+                     , Str "doesn\8217t"
+                     , Space
+                     , Str "interpret"
+                     , Space
+                     , Str "the"
+                     , Space
+                     , Str "listing"
+                     , SoftBreak
+                     , Str "block"
+                     , Space
+                     , Str "delimiters"
+                     , Space
+                     , Str "or"
+                     , Space
+                     , Str "the"
+                     , Space
+                     , Code ( "" , [] , [] ) "source"
+                     , Space
+                     , Str "style."
+                     ]
+                 , Para
+                     [ Str "----"
+                     , SoftBreak
+                     , Str "import"
+                     , Space
+                     , Str "os"
+                     , SoftBreak
+                     , Str "print"
+                     , Space
+                     , Str "(\"%s\""
+                     , Space
+                     , Str "%(os.uname()))"
+                     , SoftBreak
+                     , Str "----"
+                     ]
+                 ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Para
+                     [ Str "This"
+                     , Space
+                     , Str "cell"
+                     , Space
+                     , Str "is"
+                     , Space
+                     , Str "prefixed"
+                     , Space
+                     , Str "with"
+                     , Space
+                     , Str "an"
+                     , Space
+                     , Code ( "" , [] , [] ) "a"
+                     , Str ","
+                     , Space
+                     , Str "so"
+                     , Space
+                     , Str "the"
+                     , Space
+                     , Str "listing"
+                     , Space
+                     , Str "block"
+                     , Space
+                     , Str "is"
+                     , Space
+                     , Str "processed"
+                     , Space
+                     , Str "and"
+                     , Space
+                     , Str "rendered"
+                     , SoftBreak
+                     , Str "according"
+                     , Space
+                     , Str "to"
+                     , Space
+                     , Str "the"
+                     , Space
+                     , Code ( "" , [] , [] ) "source"
+                     , Space
+                     , Str "style"
+                     , Space
+                     , Str "rules."
+                     ]
+                 , CodeBlock
+                     ( "" , [ "python" ] , [] )
+                     "import os\nprint \"%s\" %(os.uname())"
+                 ]
+             ]
+         ])
+  , Header
+      3
+      ( "_col_and_rowspan" , [] , [] )
+      [ Str "Col" , Space , Str "and" , Space , Str "rowspan" ]
+  , Table
+      ( "" , [] , [] )
+      (Caption Nothing [])
+      [ ( AlignDefault , ColWidthDefault )
+      , ( AlignDefault , ColWidthDefault )
+      , ( AlignDefault , ColWidthDefault )
+      ]
+      (TableHead
+         ( "" , [] , [] )
+         [ Row
+             ( "" , [] , [] )
+             [ Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Para
+                     [ Str "Column"
+                     , Space
+                     , Str "1,"
+                     , Space
+                     , Str "header"
+                     , Space
+                     , Str "row"
+                     ]
+                 ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Para
+                     [ Str "Column"
+                     , Space
+                     , Str "2,"
+                     , Space
+                     , Str "header"
+                     , Space
+                     , Str "row"
+                     ]
+                 ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Para
+                     [ Str "Column"
+                     , Space
+                     , Str "3,"
+                     , Space
+                     , Str "header"
+                     , Space
+                     , Str "row"
+                     ]
+                 ]
+             ]
+         ])
+      [ TableBody
+          ( "" , [] , [] )
+          (RowHeadColumns 0)
+          []
+          [ Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 2)
+                  (ColSpan 2)
+                  [ Para
+                      [ Str "This"
+                      , Space
+                      , Str "cell"
+                      , Space
+                      , Str "spans"
+                      , Space
+                      , Str "2"
+                      , Space
+                      , Str "cols"
+                      , Space
+                      , Str "and"
+                      , Space
+                      , Str "2"
+                      , Space
+                      , Str "rows"
+                      ]
+                  ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para
+                      [ Str "Cell"
+                      , Space
+                      , Str "in"
+                      , Space
+                      , Str "column"
+                      , Space
+                      , Str "3,"
+                      , Space
+                      , Str "row"
+                      , Space
+                      , Str "2"
+                      ]
+                  ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para
+                      [ Str "Cell"
+                      , Space
+                      , Str "in"
+                      , Space
+                      , Str "column"
+                      , Space
+                      , Str "3,"
+                      , Space
+                      , Str "row"
+                      , Space
+                      , Str "3"
+                      ]
+                  ]
+              ]
+          ]
+      ]
+      (TableFoot
+         ( "" , [] , [] )
+         [ Row
+             ( "" , [] , [] )
+             [ Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 3)
+                 [ Para
+                     [ Str "Cell"
+                     , Space
+                     , Str "in"
+                     , Space
+                     , Str "column"
+                     , Space
+                     , Str "1-3,"
+                     , Space
+                     , Str "row"
+                     , Space
+                     , Str "4"
+                     ]
+                 ]
+             ]
+         ])
+  , Header
+      3
+      ( "_csv_table" , [] , [] )
+      [ Str "CSV" , Space , Str "table" ]
+  , Table
+      ( "" , [] , [] )
+      (Caption Nothing [])
+      [ ( AlignDefault , ColWidthDefault )
+      , ( AlignDefault , ColWidthDefault )
+      , ( AlignDefault , ColWidthDefault )
+      ]
+      (TableHead
+         ( "" , [] , [] )
+         [ Row
+             ( "" , [] , [] )
+             [ Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Para [ Str "Artist" ] ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Para [ Str "Track" ] ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Para [ Str "Genre" ] ]
+             ]
+         ])
+      [ TableBody
+          ( "" , [] , [] )
+          (RowHeadColumns 0)
+          []
+          [ Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para [ Str "Baauer" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para [ Str "Harlem" , Space , Str "Shake" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para [ Str "Hip" , Space , Str "Hop" ] ]
+              ]
+          ]
+      ]
+      (TableFoot
+         ( "" , [] , [] )
+         [ Row
+             ( "" , [] , [] )
+             [ Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Para [ Str "The" , Space , Str "Lumineers" ] ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Para [ Str "Ho" , Space , Str "Hey" ] ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Para [ Str "Folk" , Space , Str "Rock" ] ]
+             ]
+         ])
+  , Para [ Str "or" ]
+  , Table
+      ( "" , [] , [] )
+      (Caption Nothing [])
+      [ ( AlignDefault , ColWidthDefault )
+      , ( AlignDefault , ColWidthDefault )
+      , ( AlignDefault , ColWidthDefault )
+      ]
+      (TableHead
+         ( "" , [] , [] )
+         [ Row
+             ( "" , [] , [] )
+             [ Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Para [ Str "Artist" ] ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Para [ Str "Track" ] ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Para [ Str "Genre" ] ]
+             ]
+         ])
+      [ TableBody ( "" , [] , [] ) (RowHeadColumns 0) [] [] ]
+      (TableFoot
+         ( "" , [] , [] )
+         [ Row
+             ( "" , [] , [] )
+             [ Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Para [ Str "Baauer" ] ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Para [ Str "Harlem" , Space , Str "Shake" ] ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Para [ Str "Hip" , Space , Str "Hop" ] ]
+             ]
+         ])
+  , Header
+      3
+      ( "_dsv_table" , [] , [] )
+      [ Str "DSV" , Space , Str "table" ]
+  , Table
+      ( "" , [] , [] )
+      (Caption Nothing [])
+      [ ( AlignDefault , ColWidthDefault )
+      , ( AlignDefault , ColWidthDefault )
+      , ( AlignDefault , ColWidthDefault )
+      ]
+      (TableHead
+         ( "" , [] , [] )
+         [ Row
+             ( "" , [] , [] )
+             [ Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Para [ Str "a" ] ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Para [ Str "b" ] ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Para [ Str "c" ] ]
+             ]
+         ])
+      [ TableBody ( "" , [] , [] ) (RowHeadColumns 0) [] [] ]
+      (TableFoot
+         ( "" , [] , [] )
+         [ Row
+             ( "" , [] , [] )
+             [ Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Para [ Str "d" ] ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Para [ Str "e" ] ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Para [ Str "f" ] ]
+             ]
+         ])
+  , Para [ Str "or" ]
+  , Table
+      ( "" , [] , [] )
+      (Caption Nothing [])
+      [ ( AlignDefault , ColWidthDefault )
+      , ( AlignDefault , ColWidthDefault )
+      , ( AlignDefault , ColWidthDefault )
+      ]
+      (TableHead
+         ( "" , [] , [] )
+         [ Row
+             ( "" , [] , [] )
+             [ Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Para [ Str "Artist" ] ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Para [ Str "Track" ] ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Para [ Str "Genre" ] ]
+             ]
+         ])
+      [ TableBody ( "" , [] , [] ) (RowHeadColumns 0) [] [] ]
+      (TableFoot
+         ( "" , [] , [] )
+         [ Row
+             ( "" , [] , [] )
+             [ Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Para [ Str "Robyn" ] ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Para [ Str "Indestructible" ] ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Para [ Str "Dance" ] ]
+             ]
+         ])
+  , Header
+      2
+      ( "_definition_list" , [] , [] )
+      [ Str "Definition" , Space , Str "list" ]
+  , DefinitionList
+      [ ( [ Str "CPU" ]
+        , [ [ Para
+                [ Str "The"
+                , Space
+                , Str "brain"
+                , Space
+                , Str "of"
+                , Space
+                , Str "the"
+                , Space
+                , Str "computer."
+                ]
+            ]
+          ]
+        )
+      , ( [ Str "Hard" , Space , Str "drive" ]
+        , [ [ Para
+                [ Str "Permanent"
+                , Space
+                , Str "storage"
+                , Space
+                , Str "for"
+                , Space
+                , Str "operating"
+                , Space
+                , Str "system"
+                , Space
+                , Str "and/or"
+                , Space
+                , Str "user"
+                , Space
+                , Str "files."
+                ]
+            ]
+          ]
+        )
+      ]
+  , Para [ Str "Mixed" ]
+  , DefinitionList
+      [ ( [ Str "Dairy" ]
+        , [ [ BulletList
+                [ [ Para [ Str "Milk" ] ]
+                , [ Para [ Str "Eggs" ]
+                  , DefinitionList [ ( [ Str "Bakery" ] , [ [] ] ) ]
+                  ]
+                , [ Para [ Str "Bread" ]
+                  , DefinitionList [ ( [ Str "Produce" ] , [ [] ] ) ]
+                  ]
+                , [ Para [ Str "Bananas" ] ]
+                ]
+            ]
+          ]
+        )
+      ]
+  , Para [ Str "With" , Space , Str "spaces" ]
+  , DefinitionList [ ( [ Str "Dairy" ] , [ [] ] ) ]
+  , BulletList
+      [ [ Para [ Str "Milk" ] ] , [ Para [ Str "Eggs" ] ] ]
+  , DefinitionList [ ( [ Str "Bakery" ] , [ [] ] ) ]
+  , BulletList [ [ Para [ Str "Bread" ] ] ]
+  , DefinitionList [ ( [ Str "Produce" ] , [ [] ] ) ]
+  , BulletList [ [ Para [ Str "Bananas" ] ] ]
+  , Para [ Str "Nested" ]
+  , DefinitionList
+      [ ( [ Str "Operating" , Space , Str "Systems" ]
+        , [ [ DefinitionList
+                [ ( [ Str "Linux" ]
+                  , [ [ OrderedList
+                          ( 1 , DefaultStyle , DefaultDelim )
+                          [ [ Para [ Str "Fedora" ]
+                            , BulletList [ [ Para [ Str "Desktop" ] ] ]
+                            ]
+                          , [ Para [ Str "Ubuntu" ]
+                            , BulletList
+                                [ [ Para [ Str "Desktop" ] ]
+                                , [ Para [ Str "Server" ] ]
+                                ]
+                            ]
+                          ]
+                      ]
+                    ]
+                  )
+                , ( [ Str "BSD" ]
+                  , [ [ OrderedList
+                          ( 1 , DefaultStyle , DefaultDelim )
+                          [ [ Para [ Str "FreeBSD" ] ]
+                          , [ Para [ Str "NetBSD" ]
+                            , DefinitionList
+                                [ ( [ Str "Cloud"
+                                    , Space
+                                    , Str "Providers"
+                                    ]
+                                  , [ [ DefinitionList
+                                          [ ( [ Str "PaaS" ] , [ [] ] )
+                                          ]
+                                      ]
+                                    ]
+                                  )
+                                ]
+                            ]
+                          , [ Para [ Str "OpenShift" ] ]
+                          , [ Para [ Str "CloudBees" ] ]
+                          ]
+                      ]
+                    ]
+                  )
+                , ( [ Str "IaaS" ]
+                  , [ [ OrderedList
+                          ( 1 , DefaultStyle , DefaultDelim )
+                          [ [ Para [ Str "Amazon" , Space , Str "EC2" ]
+                            ]
+                          ]
+                      ]
+                    ]
+                  )
+                ]
+            , Para
+                [ Str "This"
+                , Space
+                , Str "just"
+                , Space
+                , Str "affects"
+                , Space
+                , Str "the"
+                , Space
+                , Str "output:"
+                ]
+            ]
+          ]
+        )
+      ]
+  , Div
+      ( ""
+      , []
+      , [ ( "wrapper" , "1" )
+        , ( "itemwidth" , "75" )
+        , ( "labelwidth" , "25" )
+        ]
+      )
+      [ DefinitionList
+          [ ( [ Str "CPU" ]
+            , [ [ Para
+                    [ Str "The"
+                    , Space
+                    , Str "brain"
+                    , Space
+                    , Str "of"
+                    , Space
+                    , Str "the"
+                    , Space
+                    , Str "computer."
+                    ]
+                ]
+              ]
+            )
+          , ( [ Str "RAM" ]
+            , [ [ Para
+                    [ Str "Temporarily"
+                    , Space
+                    , Str "stores"
+                    , Space
+                    , Str "information"
+                    , Space
+                    , Str "the"
+                    , Space
+                    , Str "CPU"
+                    , Space
+                    , Str "uses"
+                    , Space
+                    , Str "during"
+                    , Space
+                    , Str "operation."
+                    ]
+                ]
+              ]
+            )
+          ]
+      ]
+  , Para [ Str "Q&A" , Space , Str "list" ]
+  , DefinitionList
+      [ ( [ Str "What"
+          , Space
+          , Str "is"
+          , Space
+          , Str "the"
+          , Space
+          , Str "answer?"
+          ]
+        , [ [ Para
+                [ Str "This"
+                , Space
+                , Str "is"
+                , Space
+                , Str "the"
+                , Space
+                , Str "answer."
+                ]
+            ]
+          ]
+        )
+      , ( [ Str "Are"
+          , Space
+          , Str "cameras"
+          , Space
+          , Str "allowed?"
+          ]
+        , [ [] ]
+        )
+      , ( [ Str "Are"
+          , Space
+          , Str "backpacks"
+          , Space
+          , Str "allowed?"
+          ]
+        , [ [ Para [ Str "No." ] ] ]
+        )
+      ]
+  , Para
+      [ Str "Ordered"
+      , Space
+      , Str "description"
+      , Space
+      , Str "list"
+      , Space
+      , Str "(with"
+      , Space
+      , Str "numbers)"
+      ]
+  , OrderedList
+      ( 1 , DefaultStyle , DefaultDelim )
+      [ [ DefinitionList
+            [ ( [ Str "&" ] , [ [ Para [ Str "ampersand" ] ] ] ) ]
+        ]
+      , [ DefinitionList
+            [ ( [ Str ">" ]
+              , [ [ Para [ Str "greater" , Space , Str "than" ] ] ]
+              )
+            ]
+        ]
+      ]
+  , Header
+      2
+      ( "_block_macros" , [] , [] )
+      [ Str "Block" , Space , Str "macros" ]
+  , Figure
+      ( "" , [] , [] )
+      (Caption Nothing [])
+      [ Plain
+          [ Image
+              ( ""
+              , []
+              , [ ( "width" , "300px" ) , ( "height" , "200px" ) ]
+              )
+              [ Str "Sunset" ]
+              ( "sunset.jpg" , "" )
+          ]
+      ]
+  , Plain
+      [ Image
+          ( "" , [] , [] )
+          [ Str "mymovie.mp4" ]
+          ( "mymovie.mp4" , "" )
+      ]
+  , Plain
+      [ Image
+          ( "" , [] , [] ) [ Str "mysong.mp3" ] ( "mysong.mp3" , "" )
+      ]
+  , Div ( "toc" , [] , [] ) []
+  , Div
+      ( ""
+      , [ "included" ]
+      , [ ( "path" , "asciidoc-reader-include.adoc" ) ]
+      )
+      [ Para
+          [ Str "This"
+          , Space
+          , Str "is"
+          , Space
+          , Str "a"
+          , Space
+          , Str "test!"
+          ]
+      , OrderedList
+          ( 1 , DefaultStyle , DefaultDelim )
+          [ [ Para [ Str "one" ]
+            , OrderedList
+                ( 1 , DefaultStyle , DefaultDelim )
+                [ [ Para [ Str "two" ] ] ]
+            ]
+          ]
+      ]
+  ]
diff --git a/test/command/01.csv b/test/command/01.csv
new file mode 100644
--- /dev/null
+++ b/test/command/01.csv
@@ -0,0 +1,4 @@
+"Column1";"Column2"
+"Data1";"- data1
+
+- data2"
diff --git a/test/command/10002.md b/test/command/10002.md
new file mode 100644
--- /dev/null
+++ b/test/command/10002.md
@@ -0,0 +1,203 @@
+````
+% pandoc -f native -t opendocument
+[ Table
+    ( "" , [] , [] )
+    (Caption Nothing [])
+    [ ( AlignDefault , ColWidthDefault )
+    , ( AlignDefault , ColWidthDefault )
+    , ( AlignDefault , ColWidthDefault )
+    ]
+    (TableHead
+       ( "" , [] , [] )
+       [ Row
+           ( "" , [] , [] )
+           [ Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 3)
+               [ Plain
+                   [ Str "First"
+                   , Space
+                   , Str "Header"
+                   , Space
+                   , Str "Row"
+                   ]
+               ]
+           ]
+       , Row
+           ( "" , [] , [] )
+           [ Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "Second" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "Header" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "Row" ] ]
+           ]
+       ])
+    [ TableBody
+        ( "" , [] , [] )
+        (RowHeadColumns 0)
+        [ Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "Header - Table" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "Header - Body" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "Header - Row" ] ]
+            ]
+        ]
+        [ Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "Table" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "Body" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "Row" ] ]
+            ]
+        ]
+    ]
+    (TableFoot
+        ( "" , [] , [] )
+        [ Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 3)
+                [ Plain
+                    [ Str "First"
+                    , Space
+                    , Str "Footer"
+                    , Space
+                    , Str "Row"
+                    ]
+                ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "Second" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "Footer" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "Row" ] ]
+            ]
+        ])
+]
+^D
+<table:table table:name="Table1" table:style-name="Table1">
+  <table:table-column table:style-name="Table1.A" />
+  <table:table-column table:style-name="Table1.B" />
+  <table:table-column table:style-name="Table1.C" />
+  <table:table-header-rows>
+    <table:table-row>
+      <table:table-cell table:style-name="TableHeaderRowCell" office:value-type="string" table:number-columns-spanned="3">
+        <text:p text:style-name="Table_20_Heading">First Header
+        Row</text:p>
+      </table:table-cell>
+    </table:table-row>
+    <table:table-row>
+      <table:table-cell table:style-name="TableHeaderRowCell" office:value-type="string">
+        <text:p text:style-name="Table_20_Heading">Second</text:p>
+      </table:table-cell>
+      <table:table-cell table:style-name="TableHeaderRowCell" office:value-type="string">
+        <text:p text:style-name="Table_20_Heading">Header</text:p>
+      </table:table-cell>
+      <table:table-cell table:style-name="TableHeaderRowCell" office:value-type="string">
+        <text:p text:style-name="Table_20_Heading">Row</text:p>
+      </table:table-cell>
+    </table:table-row>
+  </table:table-header-rows>
+  <table:table-row>
+    <table:table-cell table:style-name="TableRowCell" office:value-type="string">
+      <text:p text:style-name="Table_20_Heading">Header - Table</text:p>
+    </table:table-cell>
+    <table:table-cell table:style-name="TableRowCell" office:value-type="string">
+      <text:p text:style-name="Table_20_Heading">Header - Body</text:p>
+    </table:table-cell>
+    <table:table-cell table:style-name="TableRowCell" office:value-type="string">
+      <text:p text:style-name="Table_20_Heading">Header - Row</text:p>
+    </table:table-cell>
+  </table:table-row>
+  <table:table-row>
+    <table:table-cell table:style-name="TableRowCell" office:value-type="string">
+      <text:p text:style-name="Table_20_Contents">Table</text:p>
+    </table:table-cell>
+    <table:table-cell table:style-name="TableRowCell" office:value-type="string">
+      <text:p text:style-name="Table_20_Contents">Body</text:p>
+    </table:table-cell>
+    <table:table-cell table:style-name="TableRowCell" office:value-type="string">
+      <text:p text:style-name="Table_20_Contents">Row</text:p>
+    </table:table-cell>
+  </table:table-row>
+  <table:table-row>
+    <table:table-cell table:style-name="TableRowCell" office:value-type="string" table:number-columns-spanned="3">
+      <text:p text:style-name="Table_20_Contents">First Footer
+      Row</text:p>
+    </table:table-cell>
+  </table:table-row>
+  <table:table-row>
+    <table:table-cell table:style-name="TableRowCell" office:value-type="string">
+      <text:p text:style-name="Table_20_Contents">Second</text:p>
+    </table:table-cell>
+    <table:table-cell table:style-name="TableRowCell" office:value-type="string">
+      <text:p text:style-name="Table_20_Contents">Footer</text:p>
+    </table:table-cell>
+    <table:table-cell table:style-name="TableRowCell" office:value-type="string">
+      <text:p text:style-name="Table_20_Contents">Row</text:p>
+    </table:table-cell>
+  </table:table-row>
+</table:table>
+````
diff --git a/test/command/10057.md b/test/command/10057.md
new file mode 100644
--- /dev/null
+++ b/test/command/10057.md
@@ -0,0 +1,6 @@
+```
+% pandoc --natbib -t latex
+We all love the famous proof by @BenjaminHornigold [p. 42].
+^D
+We all love the famous proof by \citet[p.~42]{BenjaminHornigold}.
+```
diff --git a/test/command/10062.md b/test/command/10062.md
new file mode 100644
--- /dev/null
+++ b/test/command/10062.md
@@ -0,0 +1,10 @@
+```
+% pandoc -t asciidoc
+### section
+
+##### five
+^D
+==== section
+
+====== five
+```
diff --git a/test/command/10071.md b/test/command/10071.md
new file mode 100644
--- /dev/null
+++ b/test/command/10071.md
@@ -0,0 +1,15 @@
+Leading tabs must be preserved in org mode *src* blocks with the `-i`
+flag when pandoc is called with `-p`/`--preserve-tabs`.
+
+```
+% pandoc -f org -t native --preserve-tabs
+#+begin_src makefile -i
+%.o: %.cpp
+	$(CXX)	-o	$@	$<
+#+end_src
+^D
+[ CodeBlock
+    ( "" , [ "makefile" ] , [] )
+    "%.o: %.cpp\n\t$(CXX)\t-o\t$@\t$<\n"
+]
+```
diff --git a/test/command/10093.md b/test/command/10093.md
new file mode 100644
--- /dev/null
+++ b/test/command/10093.md
@@ -0,0 +1,53 @@
+```
+% pandoc -f rst
+========== ====
+Function   1   
+========== ====
+a          yes 
+b              
+========== ====
+^D
+<table>
+<thead>
+<tr>
+<th>Function</th>
+<th>1</th>
+</tr>
+</thead>
+<tbody>
+<tr>
+<td>a</td>
+<td>yes</td>
+</tr>
+<tr>
+<td>b</td>
+<td></td>
+</tr>
+</tbody>
+</table>
+```
+
+```
+% pandoc -f rst
+========== ====
+Function   1   
+========== ====
+a          yes 
+           & no
+========== ====
+^D
+<table>
+<thead>
+<tr>
+<th>Function</th>
+<th>1</th>
+</tr>
+</thead>
+<tbody>
+<tr>
+<td>a</td>
+<td>yes &amp; no</td>
+</tr>
+</tbody>
+</table>
+```
diff --git a/test/command/10094.md b/test/command/10094.md
new file mode 100644
--- /dev/null
+++ b/test/command/10094.md
@@ -0,0 +1,47 @@
+```
+% pandoc -f rst -t markdown_strict
+.. table:: Test Table
+
+   ================================== ====
+   Functions for tests                1   
+   ================================== ====
+   a                                  yes 
+   b                                      
+   c                                      
+   d                                  yes
+   e                                      
+   ================================== ====
+^D
+<table>
+<caption>Test Table</caption>
+<thead>
+<tr>
+<th>Functions for tests</th>
+<th>1</th>
+</tr>
+</thead>
+<tbody>
+<tr>
+<td>a</td>
+<td>yes</td>
+</tr>
+<tr>
+<td>b</td>
+<td></td>
+</tr>
+<tr>
+<td>c</td>
+<td></td>
+</tr>
+<tr>
+<td>d</td>
+<td>yes</td>
+</tr>
+<tr>
+<td>e</td>
+<td></td>
+</tr>
+</tbody>
+</table>
+
+```
diff --git a/test/command/10105.md b/test/command/10105.md
new file mode 100644
--- /dev/null
+++ b/test/command/10105.md
@@ -0,0 +1,8 @@
+```
+% pandoc -t asciidoc --wrap=preserve
+[link](https://example.com)
+[link](ftps://example.com)
+^D
+https://example.com[link]
+link:ftps://example.com[link]
+```
diff --git a/test/command/10127.md b/test/command/10127.md
new file mode 100644
--- /dev/null
+++ b/test/command/10127.md
@@ -0,0 +1,713 @@
+RST Reader
+
+```
+% pandoc -f rst -t native
+=====  =====  ======
+   Inputs     Output
+------------  ------
+  A      B    A or B
+=====  =====  ======
+False  False  False
+True   False  True
+False  True   True
+True   True   True
+=====  =====  ======
+
+Table with trailing whitespaces to ensure they don't interfere with col span parsing.
+
+===============  ============  =====================  
+Full column header
+---------------------------------------------------- 
+Header One       Header Two    Header 3
+===============  ============  =====================   
+Row              With col span 2 on the right
+---------------  -----------------------------------   
+Full column row
+----------------------------------------------------
+Row with         Col spans     For visual separation
+---------------  ------------  ---------------------  
+Row with col span 2            On the left
+-----------------------------  ---------------------
+Final row
+===============  ============  =====================
+^D
+[ Table
+    ( "" , [] , [] )
+    (Caption Nothing [])
+    [ ( AlignDefault , ColWidthDefault )
+    , ( AlignDefault , ColWidthDefault )
+    , ( AlignDefault , ColWidthDefault )
+    ]
+    (TableHead
+       ( "" , [] , [] )
+       [ Row
+           ( "" , [] , [] )
+           [ Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 2)
+               [ Plain [ Str "Inputs" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "Output" ] ]
+           ]
+       , Row
+           ( "" , [] , [] )
+           [ Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "A" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "B" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "A" , Space , Str "or" , Space , Str "B" ]
+               ]
+           ]
+       ])
+    [ TableBody
+        ( "" , [] , [] )
+        (RowHeadColumns 0)
+        []
+        [ Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "False" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "False" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "False" ] ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "True" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "False" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "True" ] ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "False" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "True" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "True" ] ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "True" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "True" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "True" ] ]
+            ]
+        ]
+    ]
+    (TableFoot ( "" , [] , [] ) [])
+, Para
+    [ Str "Table"
+    , Space
+    , Str "with"
+    , Space
+    , Str "trailing"
+    , Space
+    , Str "whitespaces"
+    , Space
+    , Str "to"
+    , Space
+    , Str "ensure"
+    , Space
+    , Str "they"
+    , Space
+    , Str "don't"
+    , Space
+    , Str "interfere"
+    , Space
+    , Str "with"
+    , Space
+    , Str "col"
+    , Space
+    , Str "span"
+    , Space
+    , Str "parsing."
+    ]
+, Table
+    ( "" , [] , [] )
+    (Caption Nothing [])
+    [ ( AlignDefault , ColWidthDefault )
+    , ( AlignDefault , ColWidthDefault )
+    , ( AlignDefault , ColWidthDefault )
+    ]
+    (TableHead
+       ( "" , [] , [] )
+       [ Row
+           ( "" , [] , [] )
+           [ Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 3)
+               [ Plain
+                   [ Str "Full"
+                   , Space
+                   , Str "column"
+                   , Space
+                   , Str "header"
+                   ]
+               ]
+           ]
+       , Row
+           ( "" , [] , [] )
+           [ Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "Header" , Space , Str "One" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "Header" , Space , Str "Two" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "Header" , Space , Str "3" ] ]
+           ]
+       ])
+    [ TableBody
+        ( "" , [] , [] )
+        (RowHeadColumns 0)
+        []
+        [ Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "Row" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 2)
+                [ Plain
+                    [ Str "With"
+                    , Space
+                    , Str "col"
+                    , Space
+                    , Str "span"
+                    , Space
+                    , Str "2"
+                    , Space
+                    , Str "on"
+                    , Space
+                    , Str "the"
+                    , Space
+                    , Str "right"
+                    ]
+                ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 3)
+                [ Plain
+                    [ Str "Full"
+                    , Space
+                    , Str "column"
+                    , Space
+                    , Str "row"
+                    ]
+                ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "Row" , Space , Str "with" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "Col" , Space , Str "spans" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain
+                    [ Str "For"
+                    , Space
+                    , Str "visual"
+                    , Space
+                    , Str "separation"
+                    ]
+                ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 2)
+                [ Plain
+                    [ Str "Row"
+                    , Space
+                    , Str "with"
+                    , Space
+                    , Str "col"
+                    , Space
+                    , Str "span"
+                    , Space
+                    , Str "2"
+                    ]
+                ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain
+                    [ Str "On"
+                    , Space
+                    , Str "the"
+                    , Space
+                    , Str "left"
+                    ]
+                ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "Final" , Space , Str "row" ] ]
+            , Cell
+                ( "" , [] , [] ) AlignDefault (RowSpan 1) (ColSpan 1) []
+            , Cell
+                ( "" , [] , [] ) AlignDefault (RowSpan 1) (ColSpan 1) []
+            ]
+        ]
+    ]
+    (TableFoot ( "" , [] , [] ) [])
+]
+```
+
+RST Writer
+```
+% pandoc -f native -t rst
+[ Table
+    ( "" , [] , [] )
+    (Caption Nothing [])
+    [ ( AlignDefault , ColWidthDefault )
+    , ( AlignDefault , ColWidthDefault )
+    , ( AlignDefault , ColWidthDefault )
+    ]
+    (TableHead
+       ( "" , [] , [] )
+       [ Row
+           ( "" , [] , [] )
+           [ Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 2)
+               [ Plain [ Str "Inputs" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "Output" ] ]
+           ]
+       , Row
+           ( "" , [] , [] )
+           [ Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "A" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "B" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "A" , Space , Str "or" , Space , Str "B" ]
+               ]
+           ]
+       ])
+    [ TableBody
+        ( "" , [] , [] )
+        (RowHeadColumns 0)
+        []
+        [ Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "False" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "False" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "False" ] ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "True" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "False" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "True" ] ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "False" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "True" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "True" ] ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "True" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "True" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "True" ] ]
+            ]
+        ]
+    ]
+    (TableFoot ( "" , [] , [] ) [])
+, Table
+    ( "" , [] , [] )
+    (Caption Nothing [])
+    [ ( AlignDefault , ColWidthDefault )
+    , ( AlignDefault , ColWidthDefault )
+    , ( AlignDefault , ColWidthDefault )
+    ]
+    (TableHead
+       ( "" , [] , [] )
+       [ Row
+           ( "" , [] , [] )
+           [ Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 3)
+               [ Plain
+                   [ Str "Full"
+                   , Space
+                   , Str "column"
+                   , Space
+                   , Str "header"
+                   ]
+               ]
+           ]
+       , Row
+           ( "" , [] , [] )
+           [ Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "Header" , Space , Str "One" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "Header" , Space , Str "Two" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "Header" , Space , Str "3" ] ]
+           ]
+       ])
+    [ TableBody
+        ( "" , [] , [] )
+        (RowHeadColumns 0)
+        []
+        [ Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "Row" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 2)
+                [ Plain
+                    [ Str "With"
+                    , Space
+                    , Str "col"
+                    , Space
+                    , Str "span"
+                    , Space
+                    , Str "2"
+                    , Space
+                    , Str "on"
+                    , Space
+                    , Str "the"
+                    , Space
+                    , Str "right"
+                    ]
+                ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 3)
+                [ Plain
+                    [ Str "Full"
+                    , Space
+                    , Str "column"
+                    , Space
+                    , Str "row"
+                    ]
+                ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 2)
+                [ Plain
+                    [ Str "Row"
+                    , Space
+                    , Str "with"
+                    , Space
+                    , Str "col"
+                    , Space
+                    , Str "span"
+                    , Space
+                    , Str "2"
+                    ]
+                ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain
+                    [ Str "On"
+                    , Space
+                    , Str "the"
+                    , Space
+                    , Str "left"
+                    ]
+                ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "Final" , Space , Str "row" ] ]
+            , Cell
+                ( "" , [] , [] ) AlignDefault (RowSpan 1) (ColSpan 1) []
+            , Cell
+                ( "" , [] , [] ) AlignDefault (RowSpan 1) (ColSpan 1) []
+            ]
+        ]
+    ]
+    (TableFoot
+      ( "" , [] , [] ) 
+      [ Row
+          ( "" , [] , [] )
+          [ Cell
+              ( "" , [] , [] )
+              AlignDefault
+              (RowSpan 1)
+              (ColSpan 1)
+              [ Plain [ Str "Footer" , Space , Str "Row" ] ]
+          , Cell
+              ( "" , [] , [] )
+              AlignDefault
+              (RowSpan 1)
+              (ColSpan 1)
+              [ Plain [ Str "at" , Space , Str "the" ] ]
+          , Cell
+              ( "" , [] , [] )
+              AlignDefault
+              (RowSpan 1)
+              (ColSpan 1)
+              [ Plain [ Str "bottom" ] ]
+          ]
+      ])
+]
+^D
+====== ===== ======
+Inputs       Output
+------------ ------
+A      B     A or B
+====== ===== ======
+False  False False
+True   False True
+False  True  True
+True   True  True
+====== ===== ======
+
+=================== ============================ ===========
+Full column header                               
+------------------------------------------------------------
+Header One          Header Two                   Header 3
+=================== ============================ ===========
+Row                 With col span 2 on the right 
+------------------- ----------------------------------------
+Full column row                                  
+------------------------------------------------------------
+Row with col span 2                              On the left
+------------------------------------------------ -----------
+Final row                                        
+Footer Row          at the                       bottom
+=================== ============================ ===========
+```
diff --git a/test/command/10145.md b/test/command/10145.md
new file mode 100644
--- /dev/null
+++ b/test/command/10145.md
@@ -0,0 +1,24 @@
+```
+% pandoc -f rtf -t native
+{\rtf1\ansi\deff0{\fonttbl{\f0 \fswiss Helvetica;}{\f1 \fmodern Courier;}}
+{\colortbl;\red255\green0\blue0;\red0\green0\blue255;}
+\widowctrl\hyphauto
+
+{\pard \ql \f0 \sa0 \li0 \fi0 {\shp{\*\shpinst\shpwr2\shpwrk3\shpbypara\shpbyignore\shptop1320\shpbottom7745\shpbxcolumn\shpbxignore\shpleft0\shpright9638{\sp{\sn shapeType}{\sv 75}}{\sp{\sn wzDescription}{\sv }}{\sp{\sn wzName}{\sv }}{\sp{\sn pib}{\sv {\pict\jpegblip\picw20\pich22\picwgoal400\pichgoal440 ffd8ffe000104a46494600010101004800480000fffe0050546869732061727420697320696e20746865207075626c696320646f6d61696e2e204b6576696e204875676865732c206b6576696e68406569742e636f6d2c2053657074656d6265722031393935ffdb00430001010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101ffdb00430101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101ffc00011080016001403012200021101031101ffc4001a000100020301000000000000000000000000080905060a07ffc400231000010501000300010500000000000000060304050708020001090a11153976b7ffc400160101010100000000000000000000000000060800ffc400261101000102050109000000000000000000010200030405061121b33134365154717475b4ffda000c03010002110311003f00a90cf388f366a62aa720ed6ae07f96901f3831d973452b8cf36fe3570fc908e46d466433e5dd954f2e96992d9e498c7753faa44916e016ca91cc7d88b38fe60a5b97737defcbcc539c98d336a57f4fc2ca9a486bf07ab575ad9a3af4df221d8215e36df86c4504ff0024574551b3d687ee0575757b3ad64e311ee62bd94158d37e24198c43973099f1fc0c41614d950246513a081abf76cfe7061f6863281e6352fd1670949c148dd6dfb0d25f5b3689b1d5c965b0eacbf4e0932ad28e22ab9ae945633f4744bd3c8cee0a7fdf085b9000f449c5f7afa30b83e0b6fd7b0c8429c9467ff9715347c891e25fa24a205861aa715e6a09bd0488237dc2723414d9891381524e8ca7c0894664f835653631ab55ee7e3de433e4ff001b30949124e4c10c8b6ad0a479b3f9c937b2cf5bc0095ad600a0a41a0e9faee174a1c605e161c6c7a313539650b0113190f1a8368e60d5b24f30ff008ea7f0bf867fa6595feeb6978f1fe0f9c26177f4d63a51a9235184750e7d18811339cd000000c75f000e00380380ae390c350def826ed42ad051fa6f501c50f9b699c3b69cbeb76476d202bf3ac985b6e0e968be66572893e6a744540bd9722e5c87956848629bc2559306bd113e8653d3b6aff651dfad7a3ac8b02958cba02a93ccf525757039bae6cff090e1d90688e8aa233ee86a4c4a3e0586d6b2340522e47dcb7d0046d8a5acb05a123ee25d2b230b2ada6e2e2f9ede3c05202520ec2487b0d56562529d8b3393bca76adca4ec1bca508abb001babc007915d84fe3dd14e207e3c62f8379da2a3b861fb6629d28dba53b6ea388ebfed866bf6dfb553455e91ed547ae92e9445253a4fdf3efb4f8ebdfbe7d3c78f1ee0bb9e13e358e942a4ed49e22cff00eeb35fdd7ebfffd9}}}}}\par}
+{\pard \ql \f0 \sa0 \li0 \fi0 moon\par}
+}
+^D
+[ Para
+    [ Image
+        ( ""
+        , []
+        , [ ( "width" , "0.2777777777777778in" )
+          , ( "height" , "0.3055555555555556in" )
+          ]
+        )
+        [ Str "image" ]
+        ( "9ea9761885249909bcd8a610706eef51b54dc351.jpg" , "" )
+    ]
+, Para [ Str "moon" ]
+]
+```
diff --git a/test/command/10148.md b/test/command/10148.md
new file mode 100644
--- /dev/null
+++ b/test/command/10148.md
@@ -0,0 +1,18 @@
+```
+% pandoc -t typst
+See [@MyPaper].
+
+See [@MyPaper, Equation 1] for details.
+
+See [@MyPaper, Equation 1].
+
+See [@MyPaper, Equation 1; @Other, Figure 1].
+^D
+See @MyPaper.
+
+See @MyPaper[Equation 1] for details.
+
+See @MyPaper[Equation 1].
+
+See @MyPaper[Equation 1]@Other[Figure 1].
+```
diff --git a/test/command/10149.md b/test/command/10149.md
new file mode 100644
--- /dev/null
+++ b/test/command/10149.md
@@ -0,0 +1,296 @@
+Row spans
+```
+% pandoc -f html --columns 24 -t ansi
+<table>
+  <thead>
+    <tr>
+      <td rowspan="3">1</td>
+      <td>2</td>
+      <td>3</td>
+      <td>4</td>
+      <td rowspan="4">5</td>
+      <td>6</td>
+    </tr>
+    <tr>
+      <td>2</td>
+      <td colspan="2" rowspan="2">3</td>
+      <td>6</td>
+    </tr>
+    <tr>
+      <td rowspan="2">2</td>
+      <td>6</td>
+    </tr>
+    <tr>
+      <td>1</td>
+      <td>3</td>
+      <td>4</td>
+      <td>6</td>
+    </tr>
+  </thead>
+  <tbody>
+    <tr>
+      <td colspan="2">a</td>
+      <td rowspan="2">c</td>
+      <td>d</td>
+      <td>e</td>
+      <td>f</td>
+    </tr>
+    <tr>
+      <td>a</td>
+      <td>b</td>
+      <td colspan="3" rowspan="2">d</td>
+    </tr>
+    <tr>
+      <td>a</td>
+      <td>b</td>
+      <td>c</td>
+    </tr>
+  </tbody>
+  <tfoot>
+    <tr>
+      <td colspan="2" rowspan="4">A</td>
+      <td>C</td>
+      <td>D</td>
+      <td colspan="2" rowspan="3">E</td>
+    </tr>
+    <tr>
+      <td>C</td>
+      <td>D</td>
+    </tr>
+    <tr>
+      <td>C</td>
+      <td>D</td>
+    </tr>
+    <tr>
+      <td>C</td>
+      <td>D</td>
+      <td>E</td>
+      <td>F</td>
+    </tr>
+  </tfoot>
+</table>
+^D
+1   2   3   4   5   6
+    2   3           6
+    2               6
+1       3   4       6
+─── ─── ─── ─── ─── ───
+a       c   d   e   f
+a   b       d
+a   b   c
+─── ─── ─── ─── ─── ───
+A       C   D   E
+        C   D
+        C   D
+        C   D   E   F[0m]8;;\
+```
+
+Empty rows
+```
+% pandoc -f native --columns 12 -t ansi
+[ Table
+    ( "" , [] , [] )
+    (Caption Nothing [])
+    [ ( AlignDefault , ColWidthDefault )
+    , ( AlignDefault , ColWidthDefault )
+    , ( AlignDefault , ColWidthDefault )
+    ]
+    (TableHead
+       ( "" , [] , [] )
+       [ Row
+           ( "" , [] , [] )
+           [ Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 3)
+               (ColSpan 2)
+               [ Plain [ Str "1" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "3" ] ]
+           ]
+       , Row
+           ( "" , [] , [] )
+           [ Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "3" ] ]
+           ]
+       , Row ( "" , [] , [] ) []
+       , Row
+           ( "" , [] , [] )
+           [ Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "1" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "2" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "3" ] ]
+           ]
+       ])
+    [ TableBody
+        ( "" , [] , [] )
+        (RowHeadColumns 0)
+        []
+        [ Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "1" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "2" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 2)
+                (ColSpan 1)
+                [ Plain [ Str "3" ] ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "1" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 4)
+                (ColSpan 1)
+                [ Plain [ Str "2" ] ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "1" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "3" ] ]
+            ]
+        , Row ( "" , [] , [] ) []
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "1" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "3" ] ]
+            ]
+        ]
+    ]
+    (TableFoot
+       ( "" , [] , [] )
+       [ Row
+           ( "" , [] , [] )
+           [ Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "1" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "2" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 2)
+               (ColSpan 1)
+               [ Plain [ Str "3" ] ]
+           ]
+       , Row ( "" , [] , [] ) []
+       , Row
+           ( "" , [] , [] )
+           [ Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "1" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "2" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 3)
+               (ColSpan 1)
+               [ Plain [ Str "3" ] ]
+           ]
+       , Row
+           ( "" , [] , [] )
+           [ Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "1" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "2" ] ]
+           ]
+       , Row ( "" , [] , [] ) []
+       ])
+]
+^D
+1       3
+        3
+1   2   3
+─── ─── ───
+1   2   3
+1   2
+1       3
+1       3
+─── ─── ───
+1   2   3
+1   2   3
+1   2[0m]8;;\
+```
diff --git a/test/command/10152.md b/test/command/10152.md
new file mode 100644
--- /dev/null
+++ b/test/command/10152.md
@@ -0,0 +1,446 @@
+# CRediT Roles
+
+This document contains tests and examples for enabling
+export of roles to JATS. It was added for
+[Issue #10152](https://github.com/jgm/pandoc/issues/10152)
+and corresponding [Pull Request #10153](https://github.com/jgm/pandoc/pull/10153).
+
+In the first example, we show a fully qualified CRediT role.
+An explicit name isn't given, so the CRediT name is used.
+
+```
+% pandoc -s -t jats
+---
+title: CRediT Test
+author:
+  - name: Max Mustermann
+    affiliation: [ 1 ]
+    roles:
+      - credit: software
+        credit-name: Software
+        degree: Lead
+affiliation:
+- id: 1
+  name: Silverlight University
+---
+^D
+<?xml version="1.0" encoding="utf-8" ?>
+<!DOCTYPE article PUBLIC "-//NLM//DTD JATS (Z39.96) Journal Archiving and Interchange DTD v1.2 20190208//EN"
+                  "JATS-archivearticle1.dtd">
+<article xmlns:mml="http://www.w3.org/1998/Math/MathML" xmlns:xlink="http://www.w3.org/1999/xlink" dtd-version="1.2" article-type="other">
+<front>
+<journal-meta>
+<journal-id></journal-id>
+<journal-title-group>
+</journal-title-group>
+<issn></issn>
+<publisher>
+<publisher-name></publisher-name>
+</publisher>
+</journal-meta>
+<article-meta>
+<title-group>
+<article-title>CRediT Test</article-title>
+</title-group>
+<contrib-group>
+<contrib contrib-type="author">
+<string-name>Max Mustermann</string-name>
+<role vocab="credit" degree-contribution="Lead"
+      vocab-identifier="https://credit.niso.org/"
+      vocab-term-identifier="https://credit.niso.org/contributor-roles/software/"
+      vocab-term="Software"
+>Software</role>
+<xref ref-type="aff" rid="aff-1"/>
+</contrib>
+<aff id="aff-1">
+<institution-wrap>
+<institution>Silverlight University</institution>
+</institution-wrap>
+</aff>
+</contrib-group>
+<permissions>
+</permissions>
+</article-meta>
+</front>
+<body>
+
+</body>
+<back>
+</back>
+</article>
+```
+
+In the second example, we show a fully qualified CRediT role.
+An explicit name is given in a different language.
+
+```
+% pandoc -s -t jats
+---
+title: CRediT Test
+author:
+  - name: Max Mustermann
+    affiliation: [ 1 ]
+    roles:
+      - credit: software
+        credit-name: Software
+        degree: Lead
+        name: Programas
+affiliation:
+- id: 1
+  name: Silverlight University
+---
+^D
+<?xml version="1.0" encoding="utf-8" ?>
+<!DOCTYPE article PUBLIC "-//NLM//DTD JATS (Z39.96) Journal Archiving and Interchange DTD v1.2 20190208//EN"
+                  "JATS-archivearticle1.dtd">
+<article xmlns:mml="http://www.w3.org/1998/Math/MathML" xmlns:xlink="http://www.w3.org/1999/xlink" dtd-version="1.2" article-type="other">
+<front>
+<journal-meta>
+<journal-id></journal-id>
+<journal-title-group>
+</journal-title-group>
+<issn></issn>
+<publisher>
+<publisher-name></publisher-name>
+</publisher>
+</journal-meta>
+<article-meta>
+<title-group>
+<article-title>CRediT Test</article-title>
+</title-group>
+<contrib-group>
+<contrib contrib-type="author">
+<string-name>Max Mustermann</string-name>
+<role vocab="credit" degree-contribution="Lead"
+      vocab-identifier="https://credit.niso.org/"
+      vocab-term-identifier="https://credit.niso.org/contributor-roles/software/"
+      vocab-term="Software"
+>Programas</role>
+<xref ref-type="aff" rid="aff-1"/>
+</contrib>
+<aff id="aff-1">
+<institution-wrap>
+<institution>Silverlight University</institution>
+</institution-wrap>
+</aff>
+</contrib-group>
+<permissions>
+</permissions>
+</article-meta>
+</front>
+<body>
+
+</body>
+<back>
+</back>
+</article>
+```
+
+In this example, we show a partially qualified CRediT role
+that does not have a `degree`:
+
+```
+% pandoc -s -t jats
+---
+title: CRediT Test
+author:
+  - name: Max Mustermann
+    affiliation: [ 1 ]
+    roles:
+      - credit: software
+        credit-name: Software
+affiliation:
+- id: 1
+  name: Silverlight University
+---
+^D
+<?xml version="1.0" encoding="utf-8" ?>
+<!DOCTYPE article PUBLIC "-//NLM//DTD JATS (Z39.96) Journal Archiving and Interchange DTD v1.2 20190208//EN"
+                  "JATS-archivearticle1.dtd">
+<article xmlns:mml="http://www.w3.org/1998/Math/MathML" xmlns:xlink="http://www.w3.org/1999/xlink" dtd-version="1.2" article-type="other">
+<front>
+<journal-meta>
+<journal-id></journal-id>
+<journal-title-group>
+</journal-title-group>
+<issn></issn>
+<publisher>
+<publisher-name></publisher-name>
+</publisher>
+</journal-meta>
+<article-meta>
+<title-group>
+<article-title>CRediT Test</article-title>
+</title-group>
+<contrib-group>
+<contrib contrib-type="author">
+<string-name>Max Mustermann</string-name>
+<role vocab="credit"
+      vocab-identifier="https://credit.niso.org/"
+      vocab-term-identifier="https://credit.niso.org/contributor-roles/software/"
+      vocab-term="Software"
+>Software</role>
+<xref ref-type="aff" rid="aff-1"/>
+</contrib>
+<aff id="aff-1">
+<institution-wrap>
+<institution>Silverlight University</institution>
+</institution-wrap>
+</aff>
+</contrib-group>
+<permissions>
+</permissions>
+</article-meta>
+</front>
+<body>
+
+</body>
+<back>
+</back>
+</article>
+```
+
+In this example, we show a more stripped-down data that requires automatic lookup of the
+`credit-name`.
+
+```
+% pandoc -s -t jats
+---
+title: CRediT Test
+author:
+  - name: Max Mustermann
+    affiliation: [ 1 ]
+    roles:
+      - credit: software
+affiliation:
+- id: 1
+  name: Silverlight University
+---
+^D
+<?xml version="1.0" encoding="utf-8" ?>
+<!DOCTYPE article PUBLIC "-//NLM//DTD JATS (Z39.96) Journal Archiving and Interchange DTD v1.2 20190208//EN"
+                  "JATS-archivearticle1.dtd">
+<article xmlns:mml="http://www.w3.org/1998/Math/MathML" xmlns:xlink="http://www.w3.org/1999/xlink" dtd-version="1.2" article-type="other">
+<front>
+<journal-meta>
+<journal-id></journal-id>
+<journal-title-group>
+</journal-title-group>
+<issn></issn>
+<publisher>
+<publisher-name></publisher-name>
+</publisher>
+</journal-meta>
+<article-meta>
+<title-group>
+<article-title>CRediT Test</article-title>
+</title-group>
+<contrib-group>
+<contrib contrib-type="author">
+<string-name>Max Mustermann</string-name>
+<role vocab="credit"
+      vocab-identifier="https://credit.niso.org/"
+      vocab-term-identifier="https://credit.niso.org/contributor-roles/software/"
+      vocab-term="Software"
+>Software</role>
+<xref ref-type="aff" rid="aff-1"/>
+</contrib>
+<aff id="aff-1">
+<institution-wrap>
+<institution>Silverlight University</institution>
+</institution-wrap>
+</aff>
+</contrib-group>
+<permissions>
+</permissions>
+</article-meta>
+</front>
+<body>
+
+</body>
+<back>
+</back>
+</article>
+```
+
+In this example, we test the correct XML encoding of
+the CRediT role [Writing – review & editing](https://credit.niso.org/contributor-roles/writing-review-editing/),
+which annoyingly contains an ampersand in its label.
+
+```
+% pandoc -s -t jats
+---
+title: CRediT Test
+author:
+  - name: Max Mustermann
+    affiliation: [ 1 ]
+    roles:
+      - credit: writing-review-editing
+        credit-name: Writing – review & editing
+        degree: Lead
+affiliation:
+- id: 1
+  name: Silverlight University
+---
+^D
+<?xml version="1.0" encoding="utf-8" ?>
+<!DOCTYPE article PUBLIC "-//NLM//DTD JATS (Z39.96) Journal Archiving and Interchange DTD v1.2 20190208//EN"
+                  "JATS-archivearticle1.dtd">
+<article xmlns:mml="http://www.w3.org/1998/Math/MathML" xmlns:xlink="http://www.w3.org/1999/xlink" dtd-version="1.2" article-type="other">
+<front>
+<journal-meta>
+<journal-id></journal-id>
+<journal-title-group>
+</journal-title-group>
+<issn></issn>
+<publisher>
+<publisher-name></publisher-name>
+</publisher>
+</journal-meta>
+<article-meta>
+<title-group>
+<article-title>CRediT Test</article-title>
+</title-group>
+<contrib-group>
+<contrib contrib-type="author">
+<string-name>Max Mustermann</string-name>
+<role vocab="credit" degree-contribution="Lead"
+      vocab-identifier="https://credit.niso.org/"
+      vocab-term-identifier="https://credit.niso.org/contributor-roles/writing-review-editing/"
+      vocab-term="Writing – review &amp; editing"
+>Writing – review &amp; editing</role>
+<xref ref-type="aff" rid="aff-1"/>
+</contrib>
+<aff id="aff-1">
+<institution-wrap>
+<institution>Silverlight University</institution>
+</institution-wrap>
+</aff>
+</contrib-group>
+<permissions>
+</permissions>
+</article-meta>
+</front>
+<body>
+
+</body>
+<back>
+</back>
+</article>
+```
+
+In this example, we show a role that isn't qualified with CRediT.
+
+```
+% pandoc -s -t jats
+---
+title: CRediT Test
+author:
+  - name: Max Mustermann
+    affiliation: [ 1 ]
+    roles:
+      - name: Dolphin Catcher
+affiliation:
+- id: 1
+  name: Silverlight University
+---
+^D
+<?xml version="1.0" encoding="utf-8" ?>
+<!DOCTYPE article PUBLIC "-//NLM//DTD JATS (Z39.96) Journal Archiving and Interchange DTD v1.2 20190208//EN"
+                  "JATS-archivearticle1.dtd">
+<article xmlns:mml="http://www.w3.org/1998/Math/MathML" xmlns:xlink="http://www.w3.org/1999/xlink" dtd-version="1.2" article-type="other">
+<front>
+<journal-meta>
+<journal-id></journal-id>
+<journal-title-group>
+</journal-title-group>
+<issn></issn>
+<publisher>
+<publisher-name></publisher-name>
+</publisher>
+</journal-meta>
+<article-meta>
+<title-group>
+<article-title>CRediT Test</article-title>
+</title-group>
+<contrib-group>
+<contrib contrib-type="author">
+<string-name>Max Mustermann</string-name>
+<role>Dolphin Catcher</role>
+<xref ref-type="aff" rid="aff-1"/>
+</contrib>
+<aff id="aff-1">
+<institution-wrap>
+<institution>Silverlight University</institution>
+</institution-wrap>
+</aff>
+</contrib-group>
+<permissions>
+</permissions>
+</article-meta>
+</front>
+<body>
+
+</body>
+<back>
+</back>
+</article>
+```
+
+In this example, we show a role that neither has a CRediT identifer,
+nor a name, so it's ignored.
+
+```
+% pandoc -s -t jats
+---
+title: CRediT Test
+author:
+  - name: Max Mustermann
+    affiliation: [ 1 ]
+    roles:
+      - irrelevant-key: Dolphin Catcher
+affiliation:
+- id: 1
+  name: Silverlight University
+---
+^D
+<?xml version="1.0" encoding="utf-8" ?>
+<!DOCTYPE article PUBLIC "-//NLM//DTD JATS (Z39.96) Journal Archiving and Interchange DTD v1.2 20190208//EN"
+                  "JATS-archivearticle1.dtd">
+<article xmlns:mml="http://www.w3.org/1998/Math/MathML" xmlns:xlink="http://www.w3.org/1999/xlink" dtd-version="1.2" article-type="other">
+<front>
+<journal-meta>
+<journal-id></journal-id>
+<journal-title-group>
+</journal-title-group>
+<issn></issn>
+<publisher>
+<publisher-name></publisher-name>
+</publisher>
+</journal-meta>
+<article-meta>
+<title-group>
+<article-title>CRediT Test</article-title>
+</title-group>
+<contrib-group>
+<contrib contrib-type="author">
+<string-name>Max Mustermann</string-name>
+<xref ref-type="aff" rid="aff-1"/>
+</contrib>
+<aff id="aff-1">
+<institution-wrap>
+<institution>Silverlight University</institution>
+</institution-wrap>
+</aff>
+</contrib-group>
+<permissions>
+</permissions>
+</article-meta>
+</front>
+<body>
+
+</body>
+<back>
+</back>
+</article>
+```
diff --git a/test/command/10160.md b/test/command/10160.md
new file mode 100644
--- /dev/null
+++ b/test/command/10160.md
@@ -0,0 +1,15 @@
+```
+% pandoc -f latex -t native
+\begin{equation}
+  [0,1)
+\end{equation}
+
+\begin{table}[h]
+\end{table}
+^D
+[ Para
+    [ Math
+        DisplayMath "\\begin{equation}\n  [0,1)\n\\end{equation}"
+    ]
+]
+```
diff --git a/test/command/10185.md b/test/command/10185.md
new file mode 100644
--- /dev/null
+++ b/test/command/10185.md
@@ -0,0 +1,46 @@
+```
+% pandoc -t latex --citeproc
+Lorem ipsum
+
+# References
+
+::: {#refs}
+:::
+^D
+Lorem ipsum
+
+\section{References}\label{references}
+
+\protect\phantomsection\label{refs}
+```
+
+```
+% pandoc -t latex --citeproc
+---
+references:
+- id: foo
+  type: book
+  title: The Title
+  author: John Doe
+...
+
+Lorem ipsum [@foo].
+
+# References
+
+::: {#refs}
+:::
+^D
+Lorem ipsum (John Doe, n.d.).
+
+\section{References}\label{references}
+
+\protect\phantomsection\label{refs}
+\begin{CSLReferences}{1}{1}
+\bibitem[\citeproctext]{ref-foo}
+John Doe. n.d. \emph{The Title}.
+
+\end{CSLReferences}
+
+```
+
diff --git a/test/command/10236.md b/test/command/10236.md
new file mode 100644
--- /dev/null
+++ b/test/command/10236.md
@@ -0,0 +1,80 @@
+```
+% pandoc -t rst
+- > test
+  >
+  > para 2
+^D
+- ..
+
+     test
+
+     para 2
+```
+
+```
+% pandoc -t rst
+1. > test
+   >
+   > para 2
+^D
+1. ..
+
+      test
+
+      para 2
+```
+
+```
+% pandoc -t rst
+::: caution
+> test
+:::
+^D
+.. caution::
+
+   ..
+
+      test
+```
+
+```
+% pandoc -f native -t rst --list-tables
+[ Table
+    ( "" , [] , [] )
+    (Caption Nothing [])
+    [ ( AlignDefault , ColWidth 0.26 ) ]
+    (TableHead ( "" , [] , [] ) [])
+    [ TableBody
+        ( "" , [] , [] )
+        (RowHeadColumns 0)
+        []
+        [ Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ BlockQuote
+                  [ Para [ Emph [ Str "Level" , Space , Str "0:" ] ]
+                  , Para
+                      [ Emph [ Str "Incomplete" , Space , Str "process" ]
+                      ]
+                  ]
+                ]
+            ]
+        ]
+    ]
+    (TableFoot ( "" , [] , [] ) [])
+]
+^D
+.. list-table::
+   :widths: 19
+
+   * - ..
+
+          *Level 0:*
+
+          *Incomplete process*
+```
+
diff --git a/test/command/10271.md b/test/command/10271.md
new file mode 100644
--- /dev/null
+++ b/test/command/10271.md
@@ -0,0 +1,29 @@
+```
+% pandoc -f markdown+smart -t typst+smart
+"don't do it---"
+^D
+"don't do it---"
+
+```
+```
+% pandoc -f markdown+smart -t typst-smart
+"don't do it---"
+^D
+“don’t do it—”
+
+```
+```
+% pandoc -f markdown-smart -t typst+smart
+"don't do it---"
+^D
+\"don\'t do it-\-\-\"
+
+```
+```
+% pandoc -f markdown-smart -t typst-smart
+"don't do it---"
+^D
+"don't do it---"
+
+```
+
diff --git a/test/command/10279.md b/test/command/10279.md
new file mode 100644
--- /dev/null
+++ b/test/command/10279.md
@@ -0,0 +1,9 @@
+```
+% pandoc -f rst
+See `the full compatibility guidelines <https://
+example.com>`_ for more information.
+^D
+<p>See <a href="https://example.com">the full compatibility
+guidelines</a> for more information.</p>
+
+```
diff --git a/test/command/10281.md b/test/command/10281.md
new file mode 100644
--- /dev/null
+++ b/test/command/10281.md
@@ -0,0 +1,68 @@
+```
+% pandoc -f rst -t native
+`Want Speed? Pass by Value`_
+
+.. note::
+  For more information about the pass-by-value idiom, read: `Want Speed? Pass by Value`_.
+
+  .. _Want Speed? Pass by Value: https://web.archive.org/web/20140205194657/http://cpp-next.com/archive/2009/08/want-speed-pass-by-value/
+^D
+[ Para
+    [ Link
+        ( "" , [] , [] )
+        [ Str "Want"
+        , Space
+        , Str "Speed?"
+        , Space
+        , Str "Pass"
+        , Space
+        , Str "by"
+        , Space
+        , Str "Value"
+        ]
+        ( "https://web.archive.org/web/20140205194657/http://cpp-next.com/archive/2009/08/want-speed-pass-by-value/"
+        , ""
+        )
+    ]
+, Div
+    ( "" , [ "note" ] , [] )
+    [ Div ( "" , [ "title" ] , [] ) [ Para [ Str "Note" ] ]
+    , Para
+        [ Str "For"
+        , Space
+        , Str "more"
+        , Space
+        , Str "information"
+        , Space
+        , Str "about"
+        , Space
+        , Str "the"
+        , Space
+        , Str "pass-by-value"
+        , Space
+        , Str "idiom,"
+        , Space
+        , Str "read:"
+        , Space
+        , Link
+            ( "" , [] , [] )
+            [ Str "Want"
+            , Space
+            , Str "Speed?"
+            , Space
+            , Str "Pass"
+            , Space
+            , Str "by"
+            , Space
+            , Str "Value"
+            ]
+            ( "https://web.archive.org/web/20140205194657/http://cpp-next.com/archive/2009/08/want-speed-pass-by-value/"
+            , ""
+            )
+        , Str "."
+        ]
+    ]
+]
+
+```
+
diff --git a/test/command/10318.md b/test/command/10318.md
new file mode 100644
--- /dev/null
+++ b/test/command/10318.md
@@ -0,0 +1,84 @@
+```
+% pandoc -f rst -t html5
+-a         Output all.
+-c arg     Output just arg.
+--long     Output all day long.
+/V         A VMS/DOS-style option.
+
+-p         This option has two paragraphs in the description.
+           This is the first.
+
+           This is the second.
+           Blank lines may be omitted between options
+           (as above) or left in (as here and below).
+
+--very-long-option  A VMS-style option.  Note the adjustment
+                    for the required two spaces.
+
+--an-even-longer-option
+           The description can also start on the next line.
+
+-2, --two  This option has two variants.
+
+-f FILE, --file=FILE  These two options are synonyms; both have
+                      arguments.
+
+-f <[path]file>  Option argument placeholders must start with
+                 a letter or be wrapped in angle brackets.
+
+-d <src dest>    Angle brackets are also required if an option
+                 expects more than one argument.
+^D
+<dl>
+<dt><code>-a</code></dt>
+<dd>
+<p>Output all.</p>
+</dd>
+<dt><code>-c arg</code></dt>
+<dd>
+<p>Output just arg.</p>
+</dd>
+<dt><code>--long</code></dt>
+<dd>
+<p>Output all day long.</p>
+</dd>
+<dt><code>/V</code></dt>
+<dd>
+<p>A VMS/DOS-style option.</p>
+</dd>
+<dt><code>-p</code></dt>
+<dd>
+<p>This option has two paragraphs in the description. This is the
+first.</p>
+<p>This is the second. Blank lines may be omitted between options (as
+above) or left in (as here and below).</p>
+</dd>
+<dt><code>--very-long-option</code></dt>
+<dd>
+<p>A VMS-style option. Note the adjustment for the required two
+spaces.</p>
+</dd>
+<dt><code>--an-even-longer-option</code></dt>
+<dd>
+<p>The description can also start on the next line.</p>
+</dd>
+<dt><code>-2, --two</code></dt>
+<dd>
+<p>This option has two variants.</p>
+</dd>
+<dt><code>-f FILE, --file=FILE</code></dt>
+<dd>
+<p>These two options are synonyms; both have arguments.</p>
+</dd>
+<dt><code>-f &lt;[path]file&gt;</code></dt>
+<dd>
+<p>Option argument placeholders must start with a letter or be wrapped
+in angle brackets.</p>
+</dd>
+<dt><code>-d &lt;src dest&gt;</code></dt>
+<dd>
+<p>Angle brackets are also required if an option expects more than one
+argument.</p>
+</dd>
+</dl>
+```
diff --git a/test/command/10328.md b/test/command/10328.md
new file mode 100644
--- /dev/null
+++ b/test/command/10328.md
@@ -0,0 +1,37 @@
+Unwrap divs if they only have the `nonincremental` or `incremental` classes.
+
+```
+% pandoc --incremental --from=markdown --to=revealjs
+## First slide
+
+::: nonincremental
+
+1.  Note 1
+2.  Note 2
+3.  Note 3
+
+:::
+
+## Second Slide
+
+1.  Note 1
+2.  Note 2
+3.  Note 3
+^D
+<section id="first-slide" class="slide level2">
+<h2>First slide</h2>
+<ol type="1">
+<li>Note 1</li>
+<li>Note 2</li>
+<li>Note 3</li>
+</ol>
+</section>
+<section id="second-slide" class="slide level2">
+<h2>Second Slide</h2>
+<ol type="1">
+<li class="fragment">Note 1</li>
+<li class="fragment">Note 2</li>
+<li class="fragment">Note 3</li>
+</ol>
+</section>
+```
diff --git a/test/command/10338-rst-multiple-header-rows.md b/test/command/10338-rst-multiple-header-rows.md
new file mode 100644
--- /dev/null
+++ b/test/command/10338-rst-multiple-header-rows.md
@@ -0,0 +1,155 @@
+```
+% pandoc -f rst -t native
+Multiple Headers
+================
+
+========== =========
+Header A1  Header A2
+Header B1  Header B2
+========== =========
+body a1    body a1
+body b1    body b2
+========== =========
+
+Headless
+========
+
+========== =========
+body a1    body a1
+body b1    body b2
+========== =========
+
+End Section
+===========
+^D
+[ Header
+    1
+    ( "multiple-headers" , [] , [] )
+    [ Str "Multiple" , Space , Str "Headers" ]
+, Table
+    ( "" , [] , [] )
+    (Caption Nothing [])
+    [ ( AlignDefault , ColWidthDefault )
+    , ( AlignDefault , ColWidthDefault )
+    ]
+    (TableHead
+       ( "" , [] , [] )
+       [ Row
+           ( "" , [] , [] )
+           [ Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "Header" , Space , Str "A1" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "Header" , Space , Str "A2" ] ]
+           ]
+       , Row
+           ( "" , [] , [] )
+           [ Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "Header" , Space , Str "B1" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "Header" , Space , Str "B2" ] ]
+           ]
+       ])
+    [ TableBody
+        ( "" , [] , [] )
+        (RowHeadColumns 0)
+        []
+        [ Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "body" , Space , Str "a1" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "body" , Space , Str "a1" ] ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "body" , Space , Str "b1" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "body" , Space , Str "b2" ] ]
+            ]
+        ]
+    ]
+    (TableFoot ( "" , [] , [] ) [])
+, Header 1 ( "headless" , [] , [] ) [ Str "Headless" ]
+, Table
+    ( "" , [] , [] )
+    (Caption Nothing [])
+    [ ( AlignDefault , ColWidthDefault )
+    , ( AlignDefault , ColWidthDefault )
+    ]
+    (TableHead ( "" , [] , [] ) [])
+    [ TableBody
+        ( "" , [] , [] )
+        (RowHeadColumns 0)
+        []
+        [ Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "body" , Space , Str "a1" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "body" , Space , Str "a1" ] ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "body" , Space , Str "b1" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "body" , Space , Str "b2" ] ]
+            ]
+        ]
+    ]
+    (TableFoot ( "" , [] , [] ) [])
+, Header
+    1
+    ( "end-section" , [] , [] )
+    [ Str "End" , Space , Str "Section" ]
+]
+```
diff --git a/test/command/10385.md b/test/command/10385.md
new file mode 100644
--- /dev/null
+++ b/test/command/10385.md
@@ -0,0 +1,22 @@
+````
+% pandoc -t asciidoc
+C+ C++ C+++ `++`
+
+`` ` `` \`hi\`
+
+`hi\there`` ok`
+
+```
+++`
+```
+^D
+C{plus} C{plus}{plus} C{plus}{plus}{plus} `{plus}{plus}`
+
+`++`++` ++`++hi++`++
+
+`hi++\++there++``++ ok`
+
+....
+++`
+....
+````
diff --git a/test/command/10390.md b/test/command/10390.md
new file mode 100644
--- /dev/null
+++ b/test/command/10390.md
@@ -0,0 +1,23 @@
+```
+% pandoc -f mediawiki
+ {| class="wikitable"
+ |+ Overview of basic table markup
+ ! Key
+ |-
+ | Value
+ |}
+^D
+<table>
+<caption>Overview of basic table markup</caption>
+<thead>
+<tr>
+<th><p>Key</p></th>
+</tr>
+</thead>
+<tbody>
+<tr>
+<td><p>Value</p></td>
+</tr>
+</tbody>
+</table>
+```
diff --git a/test/command/10414.md b/test/command/10414.md
new file mode 100644
--- /dev/null
+++ b/test/command/10414.md
@@ -0,0 +1,6 @@
+```
+% pandoc -f textile -t html
+from 30.-100. text, inside - after dash
+^D
+<p>from 30.–100. text, inside - after dash</p>
+```
diff --git a/test/command/10459.md b/test/command/10459.md
new file mode 100644
--- /dev/null
+++ b/test/command/10459.md
@@ -0,0 +1,11 @@
+```
+% pandoc -s --shift-heading-level-by=-1 -f djot -t native
+# hi
+^D
+Pandoc
+  Meta
+    { unMeta =
+        fromList [ ( "title" , MetaInlines [ Str "hi" ] ) ]
+    }
+  [ Div ( "hi" , [ "section" ] , [] ) [] ]
+```
diff --git a/test/command/10484.md b/test/command/10484.md
new file mode 100644
--- /dev/null
+++ b/test/command/10484.md
@@ -0,0 +1,22 @@
+```
+% pandoc -frst -tmarkdown_strict
+- One issue fixed: `issue 123`_.
+
+- One change merged: `Big change <pull 234_>`_.
+
+- Improved the `home page <https://example.com/homepage>`_.
+
+- One more `small change`__.
+
+.. _issue 123: https://github.com/joe/project/issues/123
+.. _pull 234: https://github.com/joe/project/pull/234
+__ https://github.com/joe/project/issues/999
+
+^D
+- One issue fixed: [issue
+  123](https://github.com/joe/project/issues/123).
+- One change merged: [Big
+  change](https://github.com/joe/project/pull/234).
+- Improved the [home page](https://example.com/homepage).
+- One more [small change](https://github.com/joe/project/issues/999).
+```
diff --git a/test/command/10490.md b/test/command/10490.md
new file mode 100644
--- /dev/null
+++ b/test/command/10490.md
@@ -0,0 +1,50 @@
+```
+% pandoc -f mediawiki -t html
+{|class="wikitable" style="text-align: center;"
+|-
+!rowspan=3 style=""|Witness program version
+!colspan=4 style=""|Hash size
+|-
+!Mainnet
+!Testnet
+!Mainnet
+!Testnet
+|-
+|0||p2||QW||7Xh||T7n
+|-
+|1||p4||QY||7Xq||T7w
+|}
+^D
+<table>
+<thead>
+<tr>
+<th style=""><p>Witness program version</p></th>
+<th colspan="4" style=""><p>Hash size</p></th>
+</tr>
+</thead>
+<tbody>
+<tr>
+<td><p>Mainnet</p></td>
+<td><p>Testnet</p></td>
+<td><p>Mainnet</p></td>
+<td><p>Testnet</p></td>
+<td></td>
+</tr>
+<tr>
+<td><p>0</p></td>
+<td><p>p2</p></td>
+<td><p>QW</p></td>
+<td><p>7Xh</p></td>
+<td><p>T7n</p></td>
+</tr>
+<tr>
+<td><p>1</p></td>
+<td><p>p4</p></td>
+<td><p>QY</p></td>
+<td><p>7Xq</p></td>
+<td><p>T7w</p></td>
+</tr>
+</tbody>
+</table>
+
+```
diff --git a/test/command/10491.md b/test/command/10491.md
new file mode 100644
--- /dev/null
+++ b/test/command/10491.md
@@ -0,0 +1,35 @@
+```
+% pandoc -f mediawiki -t gfm
+{| class="wikitable"
+|-
+!
+!0
+!1
+!2
+!3
+!4
+!5
+!6
+!7
+|-
+!+0
+|q||p||z||r||y||9||x||8
+|-
+!+8
+|g||f||2||t||v||d||w||0
+|-
+!+16
+|s||3||j||n||5||4||k||h
+|-
+!+24
+|c||e||6||m||u||a||7||l
+|}
+^D
+|     | 0   | 1   | 2   | 3   | 4   | 5   | 6   | 7   |
+|-----|-----|-----|-----|-----|-----|-----|-----|-----|
+| +0  | q   | p   | z   | r   | y   | 9   | x   | 8   |
+| +8  | g   | f   | 2   | t   | v   | d   | w   | 0   |
+| +16 | s   | 3   | j   | n   | 5   | 4   | k   | h   |
+| +24 | c   | e   | 6   | m   | u   | a   | 7   | l   |
+
+```
diff --git a/test/command/10497.md b/test/command/10497.md
new file mode 100644
--- /dev/null
+++ b/test/command/10497.md
@@ -0,0 +1,13 @@
+```
+% pandoc -f rst
+a.__b__
+
+a__b__
+
+__foo__
+^D
+<p>a.__b__</p>
+<p>a__b__</p>
+<p>__foo__</p>
+```
+
diff --git a/test/command/10537.md b/test/command/10537.md
new file mode 100644
--- /dev/null
+++ b/test/command/10537.md
@@ -0,0 +1,24 @@
+```
+% pandoc -f pod -t html
+=encoding utf8
+
+=head1 NAME
+
+Test document
+^D
+<h1>NAME</h1>
+<p>Test document</p>
+```
+
+```
+% pandoc -f pod -t html
+=encoding utf8
+
+
+=head1 NAME
+
+Test document
+^D
+<h1>NAME</h1>
+<p>Test document</p>
+```
diff --git a/test/command/10594.md b/test/command/10594.md
new file mode 100644
--- /dev/null
+++ b/test/command/10594.md
@@ -0,0 +1,28 @@
+```
+% pandoc -f docbook -t native
+<orderedlist numeration="loweralpha">
+<title>header inside listing</title>   // not rendered in any output format!
+<listitem>
+<simpara>first step</simpara>
+</listitem>
+</orderedlist>
+^D
+[ Div
+    ( "" , [] , [] )
+    [ Div
+        ( "" , [ "title" ] , [] )
+        [ Plain
+            [ Str "header"
+            , Space
+            , Str "inside"
+            , Space
+            , Str "listing"
+            ]
+        ]
+    , OrderedList
+        ( 1 , LowerAlpha , DefaultDelim )
+        [ [ Para [ Str "first" , Space , Str "step" ] ] ]
+    ]
+]
+
+```
diff --git a/test/command/10621.md b/test/command/10621.md
new file mode 100644
--- /dev/null
+++ b/test/command/10621.md
@@ -0,0 +1,7 @@
+```
+% pandoc -f markdown -t html
+[test](url
+"title")
+^D
+<p><a href="url" title="title">test</a></p>
+```
diff --git a/test/command/10631.md b/test/command/10631.md
new file mode 100644
--- /dev/null
+++ b/test/command/10631.md
@@ -0,0 +1,8 @@
+GFM has funny treatment of escaped braces, requiring `\\{` instead of `\{`.
+
+```
+% pandoc -f gfm -t markdown
+$\\{x,y\\}$
+^D
+$\{x,y\}$
+```
diff --git a/test/command/10635.md b/test/command/10635.md
new file mode 100644
--- /dev/null
+++ b/test/command/10635.md
@@ -0,0 +1,24 @@
+# Support for KOMA's `\minisec` command
+
+```
+% pandoc -f latex -t native
+\minisec{Montage}
+Zunächst suche man das Mauseloch.
+^D
+[ Header
+    6
+    ( "montage" , [ "unnumbered" , "unlisted" ] , [] )
+    [ Str "Montage" ]
+, Para
+    [ Str "Zun\228chst"
+    , Space
+    , Str "suche"
+    , Space
+    , Str "man"
+    , Space
+    , Str "das"
+    , Space
+    , Str "Mauseloch."
+    ]
+]
+```
diff --git a/test/command/10643.md b/test/command/10643.md
new file mode 100644
--- /dev/null
+++ b/test/command/10643.md
@@ -0,0 +1,11 @@
+```
+% pandoc -f html -t native
+<p>A<style></style>B</p>
+^D
+[ Para
+    [ Str "A"
+    , RawInline (Format "html") "<style></style>"
+    , Str "B"
+    ]
+]
+```
diff --git a/test/command/10650.md b/test/command/10650.md
new file mode 100644
--- /dev/null
+++ b/test/command/10650.md
@@ -0,0 +1,9 @@
+```
+% pandoc -t typst --wrap=preserve
+1\. I don't want this to be an enumerated list.
+2\. No, I don't: only a number before a paragraph.
+^D
+\1. I don't want this to be an enumerated list.
+\2. No, I don't: only a number before a paragraph.
+```
+
diff --git a/test/command/10659.md b/test/command/10659.md
new file mode 100644
--- /dev/null
+++ b/test/command/10659.md
@@ -0,0 +1,45 @@
+```
+% pandoc -f latex -t native
+\includegraphics[
+width=5cm,
+]{abc.jpg}
+^D
+[ Para
+    [ Image
+        ( "" , [] , [ ( "width" , "5cm" ) ] )
+        [ Str "image" ]
+        ( "abc.jpg" , "" )
+    ]
+]
+```
+
+```
+% pandoc -f latex -t native
+\includegraphics[%
+width=5cm,%
+]{abc.jpg}
+^D
+[ Para
+    [ Image
+        ( "" , [] , [ ( "width" , "5cm" ) ] )
+        [ Str "image" ]
+        ( "abc.jpg" , "" )
+    ]
+]
+```
+
+```
+% pandoc -f latex -t native
+\includegraphics[width=5cm]{%
+abc.jpg%
+}
+^D
+[ Para
+    [ Image
+        ( "" , [] , [ ( "width" , "5cm" ) ] )
+        [ Str "image" ]
+        ( "abc.jpg" , "" )
+    ]
+]
+```
+
diff --git a/test/command/10672.md b/test/command/10672.md
new file mode 100644
--- /dev/null
+++ b/test/command/10672.md
@@ -0,0 +1,26 @@
+```
+% pandoc
+| This | Is |
+|:-----|:---|
+| With \
+| Cells
+^D
+<table>
+<thead>
+<tr>
+<th style="text-align: left;">This</th>
+<th style="text-align: left;">Is</th>
+</tr>
+</thead>
+<tbody>
+<tr>
+<td style="text-align: left;">With \</td>
+<td style="text-align: left;"></td>
+</tr>
+<tr>
+<td style="text-align: left;">Cells</td>
+<td style="text-align: left;"></td>
+</tr>
+</tbody>
+</table>
+```
diff --git a/test/command/10708.md b/test/command/10708.md
new file mode 100644
--- /dev/null
+++ b/test/command/10708.md
@@ -0,0 +1,24 @@
+```
+% pandoc -f html -t mediawiki
+<dl>
+<dt>Case 1: Both subsets are non-empty</dt>
+<dd>
+In this case, …
+</dd>
+</dl>
+^D
+; Case 1<nowiki>:</nowiki> Both subsets are non-empty
+: In this case, …
+```
+
+```
+% pandoc -f mediawiki -t html
+; term : definition
+^D
+<dl>
+<dt>term</dt>
+<dd>
+definition
+</dd>
+</dl>
+```
diff --git a/test/command/10730.md b/test/command/10730.md
new file mode 100644
--- /dev/null
+++ b/test/command/10730.md
@@ -0,0 +1,7 @@
+```
+% pandoc -f org -t native
+=hi
+there=
+^D
+[ Para [ Code ( "" , [ "verbatim" ] , [] ) "hi there" ] ]
+```
diff --git a/test/command/10747.md b/test/command/10747.md
new file mode 100644
--- /dev/null
+++ b/test/command/10747.md
@@ -0,0 +1,6 @@
+```
+% pandoc -t typst
+[Mark]{.mark}
+^D
+#highlight[Mark]
+```
diff --git a/test/command/10755.md b/test/command/10755.md
new file mode 100644
--- /dev/null
+++ b/test/command/10755.md
@@ -0,0 +1,71 @@
+```
+% pandoc -f native -t markdown
+[ Figure
+    ( "" , [] , [] )
+    (Caption
+       Nothing [ Para [ Str "An" , Space , Str "image." ] ])
+    [ Plain
+        [ Image
+            ( ""
+            , []
+            , []
+            )
+            [ Str "An" , Space , Str "image." ]
+            ( "media/rId20.jpg" , "" )
+        ]
+    ]
+]
+^D
+![An image.](media/rId20.jpg)
+```
+
+```
+% pandoc -f native -t markdown -t markdown-implicit_figures
+[ Figure
+    ( "" , [] , [] )
+    (Caption
+       Nothing [ Para [ Str "An" , Space , Str "image." ] ])
+    [ Plain
+        [ Image
+            ( ""
+            , []
+            , []
+            )
+            [ Str "An" , Space , Str "image." ]
+            ( "media/rId20.jpg" , "" )
+        ]
+    ]
+]
+^D
+<figure>
+<img src="media/rId20.jpg" alt="An image." />
+<figcaption aria-hidden="true"><p>An image.</p></figcaption>
+</figure>
+```
+
+```
+% pandoc -f native -t markdown -t markdown-implicit_figures-raw_html
+[ Figure
+    ( "" , [] , [] )
+    (Caption
+       Nothing [ Para [ Str "An" , Space , Str "image." ] ])
+    [ Plain
+        [ Image
+            ( ""
+            , []
+            , []
+            )
+            [ Str "An" , Space , Str "image." ]
+            ( "media/rId20.jpg" , "" )
+        ]
+    ]
+]
+^D
+:::: figure
+![An image.](media/rId20.jpg)
+
+::: caption
+An image.
+:::
+::::
+```
diff --git a/test/command/10758.md b/test/command/10758.md
new file mode 100644
--- /dev/null
+++ b/test/command/10758.md
@@ -0,0 +1,21 @@
+```
+% pandoc -f native -t markdown
+[ Figure
+    ( "" , [] , [] )
+    (Caption
+       Nothing
+       [ Para [ Str "Foo" , Space , Emph [ Str "emphasis" ] ] ])
+    [ Plain
+        [ Image
+            ( ""
+            , []
+            , []
+            )
+            [ Str "Foo" , Space , Str "emphasis" ]
+            ( "media/rId20.jpg" , "" )
+        ]
+    ]
+]
+^D
+![Foo *emphasis*](media/rId20.jpg)
+```
diff --git a/test/command/10781.md b/test/command/10781.md
new file mode 100644
--- /dev/null
+++ b/test/command/10781.md
@@ -0,0 +1,8 @@
+```
+% pandoc -f latex -t markdown --wrap=preserve
+This is \texttt{--flag} with dashes.
+This is the same --flag without a code.
+^D
+This is `--flag` with dashes.
+This is the same --flag without a code.
+```
diff --git a/test/command/10791.md b/test/command/10791.md
new file mode 100644
--- /dev/null
+++ b/test/command/10791.md
@@ -0,0 +1,15 @@
+```
+% pandoc -t opendocument
+Aboard **the luxury cruise ship Heart of the Ocean[^1] in the Atlantic Ocean**...
+
+[^1]: **Heart of the Ocean** (海洋之心) – The Heart of the Ocean
+^D
+<text:p text:style-name="Text_20_body">Aboard
+<text:span text:style-name="Strong_20_Emphasis">the luxury cruise ship
+Heart of the
+Ocean</text:span><text:note text:id="ftn0" text:note-class="footnote"><text:note-citation>1</text:note-citation><text:note-body><text:p text:style-name="Footnote"><text:span text:style-name="Strong_20_Emphasis">Heart
+of the Ocean</text:span> (海洋之心) – The Heart of the
+Ocean</text:p></text:note-body></text:note><text:span text:style-name="Strong_20_Emphasis">
+in the Atlantic Ocean</text:span>…</text:p>
+
+```
diff --git a/test/command/10805.md b/test/command/10805.md
new file mode 100644
--- /dev/null
+++ b/test/command/10805.md
@@ -0,0 +1,19 @@
+```
+% pandoc -t typst -f latex
+\begin{equation}
+  \label{eq:U}
+  U = A
+\end{equation}
+^D
+$ U = A $<eq:U>
+```
+
+```
+% pandoc -t typst -f latex
+\begin{equation}
+  \label{eq:U 2}
+  U = A
+\end{equation}
+^D
+$ U = A $#label("eq:U 2")
+```
diff --git a/test/command/10812.md b/test/command/10812.md
new file mode 100644
--- /dev/null
+++ b/test/command/10812.md
@@ -0,0 +1,41 @@
+Check that the `four_space_rule` extension works for plain writer.
+
+```
+% pandoc -f markdown -t plain+four_space_rule
+This is the title
+
+Here we fix:
+
+- a
+- b
+- c
+^D
+This is the title
+
+Here we fix:
+
+-   a
+-   b
+-   c
+```
+
+Check that the `four_space_rule` extension is off by default.
+
+```
+% pandoc -f markdown -t plain
+This is the title
+
+Here we fix:
+
+- a
+- b
+- c
+^D
+This is the title
+
+Here we fix:
+
+- a
+- b
+- c
+```
diff --git a/test/command/10816.md b/test/command/10816.md
new file mode 100644
--- /dev/null
+++ b/test/command/10816.md
@@ -0,0 +1,7 @@
+```
+% pandoc -f markdown -t typst
+# Test①
+^D
+= Test①
+#label("test①")
+```
diff --git a/test/command/10825.md b/test/command/10825.md
new file mode 100644
--- /dev/null
+++ b/test/command/10825.md
@@ -0,0 +1,39 @@
+```
+% pandoc -f docbook -t html
+<?xml version="1.0" encoding="utf-8"?>
+<book xmlns="http://docbook.org/ns/docbook" version="5.0">
+  <info><title>Literallayout test</title></info>
+  <chapter>
+    <info><title>Literallayout without class</title></info>
+    <literallayout>First line.
+Second line.
+  Third line, indented two spaces.</literallayout>
+  </chapter>
+  <chapter>
+    <info><title>Literallayout with normal class</title></info>
+    <literallayout class="normal">First line.
+Second line.
+  Third line, indented two spaces.</literallayout>
+  </chapter>
+  <chapter>
+    <info><title>Literallayout with monospaced</title></info>
+    <literallayout class="monospaced">First line.
+Second line.
+  Third line, indented two spaces.</literallayout>
+  </chapter>
+</book>
+^D
+<h1>Literallayout without class</h1>
+<div class="line-block">First line.<br />
+Second line.<br />
+  Third line, indented two spaces.</div>
+<h1>Literallayout with normal class</h1>
+<div class="line-block">First line.<br />
+Second line.<br />
+  Third line, indented two spaces.</div>
+<h1>Literallayout with monospaced</h1>
+<pre><code>First line.
+Second line.
+  Third line, indented two spaces.</code></pre>
+
+```
diff --git a/test/command/10836.md b/test/command/10836.md
new file mode 100644
--- /dev/null
+++ b/test/command/10836.md
@@ -0,0 +1,12 @@
+```
+% pandoc -f org -t latex
+Some equation here
+\begin{equation}
+x = y
+\end{equation}
+where $x$ is something important.
+^D
+Some equation here \begin{equation}
+x = y
+\end{equation} where \(x\) is something important.
+```
diff --git a/test/command/10848.md b/test/command/10848.md
new file mode 100644
--- /dev/null
+++ b/test/command/10848.md
@@ -0,0 +1,82 @@
+```
+% pandoc -f html -t markdown
+<table>
+<tr>
+<td colspan="3">A</td>
+<td rowspan="1" colspan="2">F</td>
+</tr>
+<tr>
+<td>C</td>
+<td colspan="2">B</td>
+<td colspan="2">H</td>
+</tr>
+<tr>
+<td colspan="2">D</td>
+<td colspan="2">E</td>
+<td>G</td>
+</tr>
+</table>
+^D
++---+---+---+---+---+
+| A         | F     |
++---+-------+-------+
+| C | B     | H     |
++---+---+---+---+---+
+| D     | E     | G |
++-------+-------+---+
+```
+
+```
+% pandoc -f html -t markdown
+<table>
+<tr>
+<td colspan="2">A</td>
+<td colspan="2">J</td>
+<td rowspan="3">F</td>
+</tr>
+<tr>
+<td rowspan="3">C</td>
+<td>B</td>
+<td rowspan="2" colspan="2">H</td>
+</tr>
+<tr>
+<td>D</td>
+</tr>
+<tr>
+<td colspan="4">K</td>
+</tr>
+</table>
+^D
++---+---+-------+---+
+| A     | J     | F |
++---+---+-------+   |
+| C | B | H     |   |
+|   +---+       |   |
+|   | D |       |   |
+|   +---+-------+---+
+|   | K             |
++---+---------------+
+```
+
+```
+% pandoc -f html -t markdown-simple_tables-multiline_tables-pipe_tables
+<table>
+  <tbody>
+    <tr>
+      <td>a</td>
+      <td></td>
+    </tr>
+    <tr>
+      <td></td>
+      <td></td>
+    </tr>
+  </tbody>
+</table>
+^D
++---+---+
+| a |   |
++---+---+
+|   |   |
++---+---+
+```
+
diff --git a/test/command/10855.md b/test/command/10855.md
new file mode 100644
--- /dev/null
+++ b/test/command/10855.md
@@ -0,0 +1,71 @@
+```
+% pandoc -t markdown
++----------+----+
+| h1       | h2 |
++:===:+===:+:===+
+| A        | B  |
++-----+----+----+
+| C   | D  | E  |
++-----+----+----+
+^D
++-------------+----+
+| h1          | h2 |
++:====:+=====:+:===+
+| A           | B  |
++------+------+----+
+| C    | D    | E  |
++------+------+----+
+
+```
+
+```
+% pandoc -t markdown
++-----+----+----+
+| h1  | h2 | h3 |
++:===:+===:+:===+
+| A        | B  |
++-----+----+----+
+| C   | D  | E  |
++-----+----+----+
+^D
++------+------+----+
+| h1   | h2   | h3 |
++:====:+=====:+:===+
+| A           | B  |
++------+------+----+
+| C    | D    | E  |
++------+------+----+
+
+```
+
+```
+% pandoc -t markdown
++:------:+:-----------:+
+| hello  | ![a](b.png) |
++--------+-------------+
+| hello  | ![c](b.png) |
++--------+-------------+
+^D
++:------:+:-----------:+
+| hello  | ![a](b.png) |
++--------+-------------+
+| hello  | ![c](b.png) |
++--------+-------------+
+
+```
+
+```
+% pandoc -t markdown
++:------:+:-----------:+
+| hello  | ![a](b.png) |
++--------+-------------+
+| hello  | ![c](b.png) |
++--------+-------------+
+^D
++:------:+:-----------:+
+| hello  | ![a](b.png) |
++--------+-------------+
+| hello  | ![c](b.png) |
++--------+-------------+
+
+```
diff --git a/test/command/10862.md b/test/command/10862.md
new file mode 100644
--- /dev/null
+++ b/test/command/10862.md
@@ -0,0 +1,6 @@
+```
+% pandoc --embed-resources
+<script></script>
+^D
+<script></script>
+```
diff --git a/test/command/10867.md b/test/command/10867.md
new file mode 100644
--- /dev/null
+++ b/test/command/10867.md
@@ -0,0 +1,26 @@
+```
+% pandoc -f native -t markdown-raw_html
+[ Figure
+    ( "fig:foo" , [] , [ ( "label" , "1.1" ) ] )
+    (Caption
+       Nothing
+       [ Plain
+           [ Str "Figure" , Space , Str "1.1:" , Space , Str "Figure" ]
+       ])
+    [ Plain
+        [ Image
+            ( "" , [] , [] )
+            [ Str "Figure" , Space , Str "1.1:" , Space , Str "Figure" ]
+            ( "./image.png" , "" )
+        ]
+    ]
+]
+^D
+:::: {#fig:foo .figure label="1.1"}
+![Figure 1.1: Figure](./image.png)
+
+::: caption
+Figure 1.1: Figure
+:::
+::::
+```
diff --git a/test/command/10884.md b/test/command/10884.md
new file mode 100644
--- /dev/null
+++ b/test/command/10884.md
@@ -0,0 +1,17 @@
+```
+% pandoc -f markdown -t markdown
+  header1   header2
+  --------- ---------
+  r1c1      r1c2
+  r2c1      r2c2
+
+  : mycaption {#myid .myclass key="value"}
+^D
+  header1   header2
+  --------- ---------
+  r1c1      r1c2
+  r2c1      r2c2
+
+  : mycaption {#myid .myclass key="value"}
+
+```
diff --git a/test/command/10889.md b/test/command/10889.md
new file mode 100644
--- /dev/null
+++ b/test/command/10889.md
@@ -0,0 +1,16 @@
+```
+% pandoc
+apple
+
+: pomaceous
+
+  fruit
+^D
+<dl>
+<dt>apple</dt>
+<dd>
+<p>pomaceous</p>
+<p>fruit</p>
+</dd>
+</dl>
+```
diff --git a/test/command/10890.md b/test/command/10890.md
new file mode 100644
--- /dev/null
+++ b/test/command/10890.md
@@ -0,0 +1,15 @@
+```
+% pandoc --tab-stop=2 --from=native --to=markdown
+[ DefinitionList
+    [ ( [ Str "apple" ]
+      , [ [ Para [ Str "pomaceous" ] , Para [ Str "fruit" ] ] ]
+      )
+    ]
+]
+^D
+apple
+
+: pomaceous
+
+  fruit
+```
diff --git a/test/command/10912.md b/test/command/10912.md
new file mode 100644
--- /dev/null
+++ b/test/command/10912.md
@@ -0,0 +1,16 @@
+```
+% pandoc -f docbook -t native
+<orderedlist numeration="arabic" startingnumber="4">
+<listitem>
+<simpara>Para1</simpara>
+</listitem>
+<listitem>
+<simpara>Para2</simpara>
+</listitem>
+</orderedlist>
+^D
+[ OrderedList
+    ( 4 , Decimal , DefaultDelim )
+    [ [ Para [ Str "Para1" ] ] , [ Para [ Str "Para2" ] ] ]
+]
+```
diff --git a/test/command/10915.md b/test/command/10915.md
new file mode 100644
--- /dev/null
+++ b/test/command/10915.md
@@ -0,0 +1,8 @@
+```
+% pandoc -f latex
+\newcommand{\a}{\ifmmode x \else y \fi}
+$\a$ and \a
+^D
+<p><span class="math inline"><em>x</em></span> and y</p>
+```
+
diff --git a/test/command/10919.md b/test/command/10919.md
new file mode 100644
--- /dev/null
+++ b/test/command/10919.md
@@ -0,0 +1,21 @@
+# Org output with smart quotes turned on
+
+```
+% pandoc -t org+smart_quotes -s
+"It's nice" she said.
+^D
+#+options: ':t
+
+"It's nice" she said.
+```
+
+Same test, but with special strings turned off.
+```
+% pandoc -t org+smart_quotes-special_strings -s
+"It's nice" she said.
+^D
+#+options: ':t
+#+options: -:nil
+
+"It’s nice" she said.
+```
diff --git a/test/command/10926.md b/test/command/10926.md
new file mode 100644
--- /dev/null
+++ b/test/command/10926.md
@@ -0,0 +1,19 @@
+````
+% pandoc -f html -t gfm
+<div class="sourceCode" id="cb1"><pre
+class="sourceCode ruby"><code class="sourceCode ruby"><span id="cb1-1"><a href="#cb1-1" aria-hidden="true" tabindex="-1"></a><span class="fu">test</span></span></code></pre></div>
+^D
+``` ruby
+test
+```
+````
+
+````
+% pandoc -f html -t gfm
+<pre
+class="border language-ruby"><code class="sourceCode ruby"><span id="cb1-1"><a href="#cb1-1" aria-hidden="true" tabindex="-1"></a><span class="fu">test</span></span></code></pre>
+^D
+``` ruby
+test
+```
+````
diff --git a/test/command/10942.md b/test/command/10942.md
new file mode 100644
--- /dev/null
+++ b/test/command/10942.md
@@ -0,0 +1,97 @@
+Ungrouped field instruction:
+```
+% pandoc -f rtf -t native
+{\rtf1\ansi\deff0
+{\fonttbl{\f0\froman Times New Roman;}}
+{\colortbl;\red0\green0\blue0;}
+\deftab720
+
+\trowd\trleft0\cellx2000\cellx4000
+\pard\intbl
+{{\field{\*\fldinst HYPERLINK "https://example.com" }{\fldrslt {\hich\af0\loch\hich\af0\loch\cf0\f0\cf0\f0\loch
+{\*\bkmkstart _dx_frag_StartFragment}{\*\bkmkend _dx_frag_StartFragment}Problem Text}}}}\cell
+\pard\intbl Normal Text\cell
+\row
+
+\trowd\trleft0\cellx2000\cellx4000
+\pard\intbl Simple Text\cell
+\pard\intbl More Text\cell
+\row
+}
+^D
+[ Table
+    ( "" , [] , [] )
+    (Caption Nothing [])
+    [ ( AlignDefault , ColWidthDefault )
+    , ( AlignDefault , ColWidthDefault )
+    ]
+    (TableHead ( "" , [] , [] ) [])
+    [ TableBody
+        ( "" , [] , [] )
+        (RowHeadColumns 0)
+        []
+        [ Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Para
+                    [ Link
+                        ( "" , [] , [] )
+                        [ Str "Problem" , Space , Str "Text" ]
+                        ( "https://example.com" , "" )
+                    ]
+                ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Para [ Str "Normal" , Space , Str "Text" ] ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Para [ Str "Simple" , Space , Str "Text" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Para [ Str "More" , Space , Str "Text" ] ]
+            ]
+        ]
+    ]
+    (TableFoot ( "" , [] , [] ) [])
+]
+```
+
+Additionally, ungrouped field result:
+```
+% pandoc -f rtf -t native
+{\rtf1\ansi\ansicpg1252\cocoartf2867
+\cocoatextscaling0\cocoaplatform1{\fonttbl\f0\fnil\fcharset0 HelveticaNeue;}
+{\colortbl;\red255\green255\blue255;\red0\green0\blue0;}
+{\*\expandedcolortbl;;\cssrgb\c0\c0\c0;}
+\paperw11905\paperh16837\margl1133\margr1133\margb1133\margt1133
+\deftab720
+\pard\pardeftab720\partightenfactor0
+{\field{\*\fldinst{HYPERLINK "https://example.com"}}{\fldrslt 
+\f0\fs22 \cf2 \up0 \nosupersub \ul \ulc2 link}}}
+^D
+[ Para
+    [ Underline
+        [ Link
+            ( "" , [] , [] )
+            [ Str "link" ]
+            ( "https://example.com" , "" )
+        ]
+    ]
+]
+```
diff --git a/test/command/10965.md b/test/command/10965.md
new file mode 100644
--- /dev/null
+++ b/test/command/10965.md
@@ -0,0 +1,50 @@
+```
+% pandoc -f markdown -t typst
+::: {lang="en"}
+This text should be in English.
+:::
+^D
+#block[
+#set text(lang: "en");
+This text should be in English.
+
+]
+```
+
+```
+% pandoc -f markdown -t typst
+::: {lang="fr"}
+Ce texte devrait être en français.
+:::
+^D
+#block[
+#set text(lang: "fr");
+Ce texte devrait être en français.
+
+]
+```
+
+```
+% pandoc -f markdown -t typst
+::: {lang="de-DE"}
+Dieser Text sollte auf Deutsch sein.
+:::
+^D
+#block[
+#set text(lang: "de");
+Dieser Text sollte auf Deutsch sein.
+
+]
+```
+
+```
+% pandoc -f markdown -t typst
+::: {lang=""}
+This should not have lang set.
+:::
+^D
+#block[
+This should not have lang set.
+
+]
+```
diff --git a/test/command/10983.md b/test/command/10983.md
new file mode 100644
--- /dev/null
+++ b/test/command/10983.md
@@ -0,0 +1,22 @@
+```
+% pandoc --citeproc --csl command/chicago-fullnote-bibliography.csl -t plain
+---
+references:
+- id: test4
+  type: blog-post
+  title: "Username as author"
+  author:
+  - brtw
+  container-title: "Reddit"
+  issued:
+    year: 2004
+suppress-bibliography: true
+...
+
+[@test4]
+^D
+[1]
+
+[1] brtw, “Username as Author,” Reddit, 2004.
+
+```
diff --git a/test/command/10984.md b/test/command/10984.md
new file mode 100644
--- /dev/null
+++ b/test/command/10984.md
@@ -0,0 +1,16 @@
+ ```
+ % pandoc -f html -t djot
+<h1 id="foo" class="a b">Hi</hi>
+^D
+{#foo .a .b}
+# Hi
+```
+
+In this one the id is suppressed by the djot writer because
+the same one would be automatically generated by the djot reader:
+```
+% pandoc -f html -t djot
+<h2 id="Introduction">Introduction</h2>
+^D
+## Introduction
+```
diff --git a/test/command/11006.md b/test/command/11006.md
new file mode 100644
--- /dev/null
+++ b/test/command/11006.md
@@ -0,0 +1,56 @@
+```
+% pandoc -f html -t asciidoc
+<ul>
+  <li>
+    <p>Paragraph one</p>
+    <p>Paragraph two to force a list continuation</p>
+    <ul>
+      <li>First nested</li>
+      <li>Second nested</li>
+    </ul>
+  </li>
+</ul>
+
+<p>How about ordered lists?</p>
+
+<ol>
+  <li>
+    <p>Paragraph one</p>
+    <p>Paragraph two to force a list continuation</p>
+    <ol><li>Nested item</li></ol>
+  </li>
+</ol>
+
+<p>With non-default attributes:</p>
+
+<ol>
+  <li>
+    <p>Paragraph one</p>
+    <p>Paragraph two to force a list continuation</p>
+    <ol start=5><li>Nested item</li></ol>
+  </li>
+</ol>
+^D
+* Paragraph one
++
+Paragraph two to force a list continuation
+
+** First nested
+** Second nested
+
+How about ordered lists?
+
+. Paragraph one
++
+Paragraph two to force a list continuation
+
+.. Nested item
+
+With non-default attributes:
+
+. Paragraph one
++
+Paragraph two to force a list continuation
+[start=5]
+.. Nested item
+```
diff --git a/test/command/11013.md b/test/command/11013.md
new file mode 100644
--- /dev/null
+++ b/test/command/11013.md
@@ -0,0 +1,23 @@
+```
+% pandoc --csl command/chicago-fullnote-bibliography.csl -C --wrap=none -t plain
+---
+references:
+- id: test10
+  type: blog-post
+  title: "Test 10: Lowercase username in brackets, Works!"
+  author:
+  - literal: "[deleted]"
+  container-title: "Reddit"
+  issued:
+    year: 2009
+...
+
+blah [@test10].
+^D
+blah.[1]
+
+[deleted]. “Test 10: Lowercase Username in Brackets, Works!” Reddit, 2009.
+
+[1] [deleted], “Test 10: Lowercase Username in Brackets, Works!” Reddit, 2009.
+
+```
diff --git a/test/command/11014.md b/test/command/11014.md
new file mode 100644
--- /dev/null
+++ b/test/command/11014.md
@@ -0,0 +1,9 @@
+```
+% pandoc -f djot -t html
+{.foo}
+- bar
+^D
+<ul class="foo">
+<li>bar</li>
+</ul>
+```
diff --git a/test/command/11017.md b/test/command/11017.md
new file mode 100644
--- /dev/null
+++ b/test/command/11017.md
@@ -0,0 +1,9 @@
+```
+% pandoc -t markdown -f typst
+#show heading: smallcaps
+
+= Introduction
+^D
+# [Introduction]{.smallcaps}
+
+```
diff --git a/test/command/11046.md b/test/command/11046.md
new file mode 100644
--- /dev/null
+++ b/test/command/11046.md
@@ -0,0 +1,19 @@
+```
+% pandoc --citeproc -t plain+smart --csl command/chicago-note-bibliography.csl
+---
+references:
+- id: doe
+  title: Title
+  type: book
+  date: 2006
+  author: John Doe
+...
+
+blah blah [@doe]---blah blah.
+^D
+blah blah[1]---blah blah.
+
+John Doe. Title, n.d.
+
+[1] John Doe, Title.
+```
diff --git a/test/command/11047.md b/test/command/11047.md
new file mode 100644
--- /dev/null
+++ b/test/command/11047.md
@@ -0,0 +1,7 @@
+```
+% pandoc -t typst --wrap=auto
+Full-time study: 2001-2003; Thesis submission: Nov 2005; Award: Jul 2006.
+^D
+Full-time study: 2001-2003; Thesis submission: Nov 2005; Award: Jul
+\2006.
+```
diff --git a/test/command/11048.md b/test/command/11048.md
new file mode 100644
--- /dev/null
+++ b/test/command/11048.md
@@ -0,0 +1,48 @@
+```
+% pandoc -f biblatex -t markdown -s
+@article{khatri2021spooky,
+    title = {Spooky action at a global distance: analysis of space-based
+             entanglement distribution for the quantum internet},
+    author = {Khatri, Sumeet and Brady, Anthony J and Desporte, Ren{\'e}e A and
+              Bart, Manon P and Dowling, Jonathan P},
+    journal = {{npj} Quantum Information},
+    volume = {7},
+    number = {1},
+    pages = {4},
+    doi = {10.1038/s41534-020-00327-5},
+    url = {https://doi.org/10.1038/s41534-020-00327-5},
+    year = {2021},
+    publisher = {Nature Publishing Group UK London},
+}
+^D
+---
+nocite: "[@*]"
+references:
+- author:
+  - family: Khatri
+    given: Sumeet
+  - family: Brady
+    given: Anthony J
+  - family: Desporte
+    given: Renée A
+  - family: Bart
+    given: Manon P
+  - family: Dowling
+    given: Jonathan P
+  container-title: "[npj]{.nocase} Quantum Information"
+  doi: 10.1038/s41534-020-00327-5
+  id: khatri2021spooky
+  issue: 1
+  issued: 2021
+  page: 4
+  publisher: Nature Publishing Group UK London
+  title: "Spooky action at a global distance: Analysis of space-based
+    entanglement distribution for the quantum internet"
+  title-short: Spooky action at a global distance
+  type: article-journal
+  url: "https://doi.org/10.1038/s41534-020-00327-5"
+  volume: 7
+---
+
+
+```
diff --git a/test/command/11090.md b/test/command/11090.md
new file mode 100644
--- /dev/null
+++ b/test/command/11090.md
@@ -0,0 +1,49 @@
+```
+% pandoc -f typst -t native
+#include "command/11090/ch1.typ"
+
+== Chapter Two
+
+#figure(
+  image("command/11090/media/image1.png"),
+  caption: [This is an image.] 
+)
+^D
+[ Header
+    2 ( "" , [] , [] ) [ Str "Chapter" , Space , Str "One" ]
+, Figure
+    ( "" , [] , [] )
+    (Caption
+       Nothing [ Para [ Str "An" , Space , Str "image." ] ])
+    [ Para
+        [ Image
+            ( "" , [] , [] )
+            []
+            ( "command/11090/media/image1.png" , "" )
+        ]
+    ]
+, Header
+    2 ( "" , [] , [] ) [ Str "Chapter" , Space , Str "Two" ]
+, Figure
+    ( "" , [] , [] )
+    (Caption
+       Nothing
+       [ Para
+           [ Str "This"
+           , Space
+           , Str "is"
+           , Space
+           , Str "an"
+           , Space
+           , Str "image."
+           ]
+       ])
+    [ Para
+        [ Image
+            ( "" , [] , [] )
+            []
+            ( "command/11090/media/image1.png" , "" )
+        ]
+    ]
+]
+```
diff --git a/test/command/11090/ch1.typ b/test/command/11090/ch1.typ
new file mode 100644
--- /dev/null
+++ b/test/command/11090/ch1.typ
@@ -0,0 +1,6 @@
+== Chapter One
+
+#figure(
+  image("media/image1.png"),
+  caption: [An image.]
+)
diff --git a/test/command/11101.md b/test/command/11101.md
new file mode 100644
--- /dev/null
+++ b/test/command/11101.md
@@ -0,0 +1,15 @@
+```
+% pandoc -f typst -t native
+First paragraph.
+
+#pagebreak()
+
+Second paragraph.
+^D
+[ Para [ Str "First" , Space , Str "paragraph." ]
+, Div
+    ( "" , [ "page-break" ] , [ ( "wrapper" , "1" ) ] )
+    [ HorizontalRule ]
+, Para [ Str "Second" , Space , Str "paragraph." ]
+]
+```
diff --git a/test/command/11113.docx b/test/command/11113.docx
new file mode 100644
Binary files /dev/null and b/test/command/11113.docx differ
diff --git a/test/command/11113.md b/test/command/11113.md
new file mode 100644
--- /dev/null
+++ b/test/command/11113.md
@@ -0,0 +1,7 @@
+```
+% pandoc command/11113.docx -t plain
+^D
+Colored:❤️😏📖👌😒🤍
+
+BW: 😊︎
+```
diff --git a/test/command/11124.md b/test/command/11124.md
new file mode 100644
--- /dev/null
+++ b/test/command/11124.md
@@ -0,0 +1,10 @@
+The heading is "unlinked" before adding it to the TOC.
+
+```
+% pandoc --to=latex
+<http://example.com/> {-}
+=========================
+^D
+\section*{\texorpdfstring{\url{http://example.com/}}{http://example.com/}}\label{httpexample.com}
+\addcontentsline{toc}{section}{{http://example.com/}}
+```
diff --git a/test/command/11128.md b/test/command/11128.md
new file mode 100644
--- /dev/null
+++ b/test/command/11128.md
@@ -0,0 +1,23 @@
+```
+% pandoc -f html -t markdown_strict+pipe_tables-raw_html
+<table>
+<tr>
+<th class="" colspan="2" rowspan="1"><b>Subject</b></th>
+<th class=""><b>Grade</b></th>
+</tr>
+<tr>
+<td class="" colspan="1" rowspan="2">Physics</td>
+<td class="">Practical</td>
+<td class="">A</td>
+</tr>
+<tr>
+<td class="">Theory</td>
+<td class="">B+</td>
+</tr>
+</table>
+^D
+| **Subject** |           | **Grade** |
+|-------------|-----------|-----------|
+| Physics     | Practical | A         |
+|             | Theory    | B+        |
+```
diff --git a/test/command/11140.md b/test/command/11140.md
new file mode 100644
--- /dev/null
+++ b/test/command/11140.md
@@ -0,0 +1,71 @@
+```
+% pandoc -f rst -t native
+.. figure:: image.png
+   :alt: my alt
+
+   Caption
+^D
+[ Figure
+    ( "" , [] , [] )
+    (Caption Nothing [ Plain [ Str "Caption" ] ])
+    [ Plain
+        [ Image
+            ( "" , [] , [] )
+            [ Str "my" , Space , Str "alt" ]
+            ( "image.png" , "" )
+        ]
+    ]
+]
+```
+
+```
+% pandoc -f rst -t native
+.. figure:: image.png
+
+   Caption
+^D
+[ Figure
+    ( "" , [] , [] )
+    (Caption Nothing [ Plain [ Str "Caption" ] ])
+    [ Plain
+        [ Image
+            ( "" , [] , [] ) [ Str "Caption" ] ( "image.png" , "" )
+        ]
+    ]
+]
+```
+
+```
+% pandoc -f native -t markdown
+[ Figure
+    ( "" , [] , [] )
+    (Caption
+       Nothing [ Plain [ Str "Caption" ] ])
+    [ Plain
+        [ Image ( "" , [] , [] ) [ Str "my", Space, Str "alt" ] ( "image.png" , "" )
+        ]
+    ]
+]
+^D
+![Caption](image.png){alt="my alt"}
+```
+
+Ignore `\pandocbounded`:
+```
+% pandoc -f latex -t native
+\begin{figure}
+\centering
+\pandocbounded{\includegraphics[keepaspectratio,alt={Caption}]{image.png}}
+\caption{Caption}
+\end{figure}
+^D
+[ Figure
+    ( "" , [] , [] )
+    (Caption Nothing [ Plain [ Str "Caption" ] ])
+    [ Para
+        [ Image
+            ( "" , [] , [] ) [ Str "Caption" ] ( "image.png" , "" )
+        ]
+    ]
+]
+```
diff --git a/test/command/11150.md b/test/command/11150.md
new file mode 100644
--- /dev/null
+++ b/test/command/11150.md
@@ -0,0 +1,29 @@
+```
+% pandoc -f rst
+===  =====
+int  float
+===  =====
+10   9.90
+-10  9.90
+===  =====
+^D
+<table>
+<thead>
+<tr>
+<th>int</th>
+<th>float</th>
+</tr>
+</thead>
+<tbody>
+<tr>
+<td>10</td>
+<td>9.90</td>
+</tr>
+<tr>
+<td>-10</td>
+<td>9.90</td>
+</tr>
+</tbody>
+</table>
+
+```
diff --git a/test/command/11162.md b/test/command/11162.md
new file mode 100644
--- /dev/null
+++ b/test/command/11162.md
@@ -0,0 +1,19 @@
+```
+% pandoc -f native -t rst
+[ BulletList
+    [ [ Plain [ Str "list" ]
+      , CodeBlock ( "" , [ "ruby" ] , [] ) "code = 7 # comment"
+      ]
+    , [ Plain [ Str "second" , Space , Str "item" ] ]
+    ]
+]
+^D
+- list
+
+  .. code:: ruby
+
+     code = 7 # comment
+
+- second item
+
+```
diff --git a/test/command/11188.md b/test/command/11188.md
new file mode 100644
--- /dev/null
+++ b/test/command/11188.md
@@ -0,0 +1,80 @@
+Parsing PARAMETERS of Org-mode blocks
+
+```
+% pandoc -f org --to=native
+#+attr_html: :width 10px
+#+BEGIN_myex :this that
+huhu
+#+END_myex
+^D
+[ Div
+    ( ""
+    , [ "myex" ]
+    , [ ( "width" , "10px" ) , ( "this" , "that" ) ]
+    )
+    [ Para [ Str "huhu" ] ]
+]
+```
+
+Python-style parameters are accepted, too.
+
+```
+% pandoc -f org --to=native
+#+BEGIN_myblock width=10px
+[[image.svg][logo]]
+#+END_myblock
+^D
+[ Div
+    ( "" , [ "myblock" ] , [ ( "width" , "10px" ) ] )
+    [ Para
+        [ Span
+            ( ""
+            , [ "spurious-link" ]
+            , [ ( "target" , "image.svg" ) ]
+            )
+            [ Emph [ Str "logo" ] ]
+        ]
+    ]
+]
+```
+
+The fallback is to put the remainder of the line into a `parameters`
+attribute.
+
+```
+% pandoc -f org --to=native
+#+BEGIN_myblock these are parameters in an unsupported format
+/OK/
+#+END_myblock
+^D
+[ Div
+    ( ""
+    , [ "myblock" ]
+    , [ ( "parameters"
+        , "these are parameters in an unsupported format"
+        )
+      ]
+    )
+    [ Para [ Emph [ Str "OK" ] ] ]
+]
+```
+
+Also works on dynamic blocks.
+
+```
+% pandoc -f org --to=markdown
+#+BEGIN: clocktable :scope subtree :maxlevel 3
+#+CAPTION: Clock summary at [2025-10-18 Sat 17:23]
+| Headline     | Time   |
+|--------------+--------|
+| *Total time* | *0:00* |
+#+END:
+^D
+::: {.clocktable scope="subtree" maxlevel="3"}
+  Headline         Time
+  ---------------- ----------
+  **Total time**   **0:00**
+
+  : Clock summary at \[2025-10-18 Sat 17:23\]
+:::
+```
diff --git a/test/command/11210.md b/test/command/11210.md
new file mode 100644
--- /dev/null
+++ b/test/command/11210.md
@@ -0,0 +1,13 @@
+```
+% pandoc -t typst -f man
+.PP
+.IR login (1)
+.PP
+and a regular (paren) that should not be escaped.
+^D
+#emph[login]\(1)
+
+and a regular (paren) that should not be escaped.
+
+```
+
diff --git a/test/command/11211.md b/test/command/11211.md
new file mode 100644
--- /dev/null
+++ b/test/command/11211.md
@@ -0,0 +1,16 @@
+```
+% pandoc -f rtf -t native
+{\field{\*\fldinst{\rtlch\ab0\ai0\af2\alang1025\afs22\ltrch\b0\i0\fs22\lang1033\langnp1033\langfe1033\langfenp1033
+\loch\af2\dbch\af2\hich\f2\insrsid10976062\strike0\ulnone\cf1 HYPERLINK "https://example.com"}{\*\datafield 08d0c9ea79f9bace118c8200aa004ba90b0200000003000000e0c9ea79f9bace118c8200aa004ba90b28000000680074007400700073003a002f002f006500780061006d0070006c0065002e0063006f006d000000}}
+{\fldrslt{\rtlch\ab0\ai0\af2\alang1025\afs22\ltrch\b0\i0\fs22\lang1033\langnp1033\langfe1033\langfenp1033\loch\af2\dbch\af2\hich\f2\strike0\ul\cf2 link}}}
+^D
+[ Para
+    [ Underline
+        [ Link
+            ( "" , [] , [] )
+            [ Str "link" ]
+            ( "https://example.com" , "" )
+        ]
+    ]
+]
+```
diff --git a/test/command/11253.md b/test/command/11253.md
new file mode 100644
--- /dev/null
+++ b/test/command/11253.md
@@ -0,0 +1,27 @@
+```
+% pandoc -f markdown -t native
+\ifstrequal{hello}{hello}{TRUE}{FALSE}
+\ifstrequal{hello}{world}{TRUE}{FALSE}
+^D
+[ Para
+    [ RawInline (Format "tex") "TRUE"
+    , SoftBreak
+    , RawInline (Format "tex") "FALSE"
+    ]
+]
+```
+
+```
+% pandoc -f markdown-latex_macros -t native
+\ifstrequal{hello}{hello}{TRUE}{FALSE}
+\ifstrequal{hello}{world}{TRUE}{FALSE}
+^D
+[ Para
+    [ RawInline
+        (Format "tex") "\\ifstrequal{hello}{hello}{TRUE}{FALSE}"
+    , SoftBreak
+    , RawInline
+        (Format "tex") "\\ifstrequal{hello}{world}{TRUE}{FALSE}"
+    ]
+]
+```
diff --git a/test/command/1126.md b/test/command/1126.md
new file mode 100644
--- /dev/null
+++ b/test/command/1126.md
@@ -0,0 +1,28 @@
+```
+% pandoc -f html -t latex
+\begin{eqnarray}
+A&=&B,\\
+C&=&D
+\end{eqnarray}
+^D
+\textbackslash begin\{eqnarray\} A\&=\&B,\textbackslash\textbackslash{}
+C\&=\&D \textbackslash end\{eqnarray\}
+```
+
+```
+% pandoc -f html+raw_tex -t latex
+<p>See \eqref{myeq}.</p>
+\begin{eqnarray}
+A&=&B,\\
+C&amp;=&amp;D
+\\label{myeq}
+\end{eqnarray}
+^D
+See \eqref{myeq}.
+
+\begin{eqnarray}
+A&=&B,\\
+C&=&D
+\\label{myeq}
+\end{eqnarray}
+```
diff --git a/test/command/11266.md b/test/command/11266.md
new file mode 100644
--- /dev/null
+++ b/test/command/11266.md
@@ -0,0 +1,19 @@
+```
+% pandoc -t latex
+$$
+\begin{eqnarray}
+S &\rightarrow& a A                      \nonumber \\
+A &\rightarrow& d B \ | \ b A \ | \ c A  \nonumber \\
+B &\rightarrow& a c \ | \ b C \ | \ c A  \nonumber \\
+C &\rightarrow& \epsilon                 \nonumber
+\end{eqnarray}
+$$
+^D
+
+\begin{eqnarray}
+S &\rightarrow& a A                      \nonumber \\
+A &\rightarrow& d B \ | \ b A \ | \ c A  \nonumber \\
+B &\rightarrow& a c \ | \ b C \ | \ c A  \nonumber \\
+C &\rightarrow& \epsilon                 \nonumber
+\end{eqnarray}
+```
diff --git a/test/command/11270.md b/test/command/11270.md
new file mode 100644
--- /dev/null
+++ b/test/command/11270.md
@@ -0,0 +1,25 @@
+```
+% pandoc -f markdown -t native -s
+---
+header-includes: |
+    \makeatletter
+    \beamer@ignorenonframefalse
+    \makeatother
+...
+
+^D
+Pandoc
+  Meta
+    { unMeta =
+        fromList
+          [ ( "header-includes"
+            , MetaBlocks
+                [ RawBlock
+                    (Format "tex")
+                    "\\makeatletter\n\\beamer@ignorenonframefalse\n\\makeatother"
+                ]
+            )
+          ]
+    }
+  []
+```
diff --git a/test/command/11299.md b/test/command/11299.md
new file mode 100644
--- /dev/null
+++ b/test/command/11299.md
@@ -0,0 +1,28 @@
+```
+% pandoc -f mediawiki -t native
+<foo>
+
+<samp>x</samp>
+
+<kbd>x</kbd>
+
+<var>x</var>
+
+<mark>This is ''highlighted''</mark>
+^D
+[ Para [ Str "<foo>" ]
+, Para [ Code ( "" , [ "sample" ] , [] ) "x" ]
+, Para [ Span ( "" , [ "kbd" ] , [] ) [ Str "x" ] ]
+, Para [ Code ( "" , [ "variable" ] , [] ) "x" ]
+, Para
+    [ Span
+        ( "" , [ "mark" ] , [] )
+        [ Str "This"
+        , Space
+        , Str "is"
+        , Space
+        , Emph [ Str "highlighted" ]
+        ]
+    ]
+]
+```
diff --git a/test/command/11300.md b/test/command/11300.md
new file mode 100644
--- /dev/null
+++ b/test/command/11300.md
@@ -0,0 +1,67 @@
+```
+% pandoc -f docbook -t native -s
+<?xml version="1.0"?>
+<book xmlns="http://docbook.org/ns/docbook" version="5.0" dir="ltr">
+  <info>
+    <title>Book title</title>
+    <subtitle>Book subtitle</subtitle>
+  </info>
+  <chapter>
+    <info>
+      <title>Chapter title</title>
+    </info>
+    <para>My sentence</para>
+  </chapter>
+</book>
+^D
+Pandoc
+  Meta
+    { unMeta =
+        fromList
+          [ ( "subtitle"
+            , MetaInlines [ Str "Book" , Space , Str "subtitle" ]
+            )
+          , ( "title"
+            , MetaInlines [ Str "Book" , Space , Str "title" ]
+            )
+          ]
+    }
+  [ Header
+      1 ( "" , [] , [] ) [ Str "Chapter" , Space , Str "title" ]
+  , Para [ Str "My" , Space , Str "sentence" ]
+  ]
+```
+
+```
+% pandoc -f docbook -t native -s
+<?xml version="1.0"?>
+<book xmlns="http://docbook.org/ns/docbook" version="5.0" dir="ltr">
+  <chapter>
+    <info>
+      <title>Chapter title</title>
+    </info>
+    <para>My sentence</para>
+  </chapter>
+  <info>
+    <title>Book title</title>
+    <subtitle>Book subtitle</subtitle>
+  </info>
+</book>
+^D
+Pandoc
+  Meta
+    { unMeta =
+        fromList
+          [ ( "subtitle"
+            , MetaInlines [ Str "Book" , Space , Str "subtitle" ]
+            )
+          , ( "title"
+            , MetaInlines [ Str "Book" , Space , Str "title" ]
+            )
+          ]
+    }
+  [ Header
+      1 ( "" , [] , [] ) [ Str "Chapter" , Space , Str "title" ]
+  , Para [ Str "My" , Space , Str "sentence" ]
+  ]
+```
diff --git a/test/command/11309.md b/test/command/11309.md
new file mode 100644
--- /dev/null
+++ b/test/command/11309.md
@@ -0,0 +1,6 @@
+```
+% pandoc -f rst -t native
+Cho\ **co**\ late
+^D
+[ Para [ Str "Cho" , Strong [ Str "co" ] , Str "late" ] ]
+```
diff --git a/test/command/11312.md b/test/command/11312.md
new file mode 100644
--- /dev/null
+++ b/test/command/11312.md
@@ -0,0 +1,21 @@
+```
+% pandoc -f mediawiki -t texinfo
+foofoo
+
+ bar
+ baz
+
+foofoo
+^D
+@node Top
+@top Top
+
+foofoo
+
+@example
+bar
+baz
+@end example
+
+foofoo
+```
diff --git a/test/command/11323.md b/test/command/11323.md
new file mode 100644
--- /dev/null
+++ b/test/command/11323.md
@@ -0,0 +1,12 @@
+```
+% pandoc -f rst
+foo-
+   bar
+^D
+<dl>
+<dt>foo-</dt>
+<dd>
+<p>bar</p>
+</dd>
+</dl>
+```
diff --git a/test/command/11341.md b/test/command/11341.md
new file mode 100644
--- /dev/null
+++ b/test/command/11341.md
@@ -0,0 +1,9 @@
+```
+% pandoc -t commonmark -f html
+<h1>The Hobbit<br>or<br>There and Back Again</h1>
+^D
+The Hobbit\
+or\
+There and Back Again
+====================
+```
diff --git a/test/command/11342.md b/test/command/11342.md
new file mode 100644
--- /dev/null
+++ b/test/command/11342.md
@@ -0,0 +1,33 @@
+Subfigures should be converted to *fig-group* elements.
+
+```
+% pandoc -f latex -t jats
+\begin{figure}[H]
+  \begin{subfigure}
+    \centering
+    \includegraphics[height=1.5in]{assets/A.png}
+    \caption{Graph for function *A*.}
+    \label{fig:A}
+  \end{subfigure}
+  \begin{subfigure}
+    \centering
+    \includegraphics[height=1.5in]{assets/B.png}
+    \caption{Graph for function *B*.}
+    \label{fig:B}
+  \end{subfigure}
+  \label{fig:graphs}
+  \caption{Function graphs.}
+\end{figure}
+^D
+<fig-group id="figU003Agraphs">
+  <caption><p>Function graphs.</p></caption>
+  <fig id="figU003AA">
+    <caption><p>Graph for function *A*.</p></caption>
+    <graphic mimetype="image" mime-subtype="png" xlink:href="assets/A.png" />
+  </fig>
+  <fig id="figU003AB">
+    <caption><p>Graph for function *B*.</p></caption>
+    <graphic mimetype="image" mime-subtype="png" xlink:href="assets/B.png" />
+  </fig>
+</fig-group>
+```
diff --git a/test/command/11348.md b/test/command/11348.md
new file mode 100644
--- /dev/null
+++ b/test/command/11348.md
@@ -0,0 +1,61 @@
+```
+% pandoc -f markdown -t native
+$ invalid opening inline math$
+
+$
+invalid opening inline math$
+
+$invalid closing inline math $
+
+$invalid closing inline math
+$
+
+$valid inline math$
+^D
+[ Para
+    [ Str "$"
+    , Space
+    , Str "invalid"
+    , Space
+    , Str "opening"
+    , Space
+    , Str "inline"
+    , Space
+    , Str "math$"
+    ]
+, Para
+    [ Str "$"
+    , SoftBreak
+    , Str "invalid"
+    , Space
+    , Str "opening"
+    , Space
+    , Str "inline"
+    , Space
+    , Str "math$"
+    ]
+, Para
+    [ Str "$invalid"
+    , Space
+    , Str "closing"
+    , Space
+    , Str "inline"
+    , Space
+    , Str "math"
+    , Space
+    , Str "$"
+    ]
+, Para
+    [ Str "$invalid"
+    , Space
+    , Str "closing"
+    , Space
+    , Str "inline"
+    , Space
+    , Str "math"
+    , SoftBreak
+    , Str "$"
+    ]
+, Para [ Math InlineMath "valid inline math" ]
+]
+```
diff --git a/test/command/11362.md b/test/command/11362.md
new file mode 100644
--- /dev/null
+++ b/test/command/11362.md
@@ -0,0 +1,17 @@
+```
+% pandoc -f markdown -t asciidoc
+This is a _test_[^1].
+
+And yet another **one**[^1].
+
+We can also try to write #hashtags [this]{.test}.
+
+[^1]: Test footnote.
+^D
+This is a __test__footnote:[Test footnote.].
+
+And yet another **one**footnote:[Test footnote.].
+
+We can also try to write ++#++hashtags [.test]#this#.
+
+```
diff --git a/test/command/11364.md b/test/command/11364.md
new file mode 100644
--- /dev/null
+++ b/test/command/11364.md
@@ -0,0 +1,75 @@
+```
+% pandoc -f rtf -t native
+{\rtf1\ansi\deff3\adeflang1025
+{\fonttbl{\f0\froman\fprq2\fcharset0 Times New Roman;}{\f1\froman\fprq2\fcharset2 Symbol;}{\f2\fswiss\fprq2\fcharset0 Arial;}{\f3\froman\fprq2\fcharset0 Liberation Serif{\*\falt Times New Roman};}{\f4\fnil\fprq0\fcharset2 OpenSymbol{\*\falt Arial Unicode MS};}{\f5\fswiss\fprq2\fcharset0 Liberation Sans{\*\falt Arial};}{\f6\fnil\fprq2\fcharset0 Noto Sans CJK SC;}{\f7\fnil\fprq2\fcharset0 Matangi Light;}{\f8\fnil\fprq0\fcharset128 Matangi Light;}{\f9\fnil\fprq0\fcharset128 OpenSymbol{\*\falt Arial Unicode MS};}}
+{\colortbl;\red0\green0\blue0;\red0\green0\blue255;\red0\green255\blue255;\red0\green255\blue0;\red255\green0\blue255;\red255\green0\blue0;\red255\green255\blue0;\red255\green255\blue255;\red0\green0\blue128;\red0\green128\blue128;\red0\green128\blue0;\red128\green0\blue128;\red128\green0\blue0;\red128\green128\blue0;\red128\green128\blue128;\red192\green192\blue192;}
+{\stylesheet{\s0\snext0\widctlpar\hyphpar0\ltrpar\kerning1\cf0\rtlch\af7\afs24\alang1081\ltrch\hich\af3\afs24\alang1033\dbch\af10\langfe2052\loch\f3\fs24\lang1033 Normal;}
+{\*\cs15\snext15\rtlch\af4\ltrch\hich\af4\dbch\af4\loch\f4 Bullets;}
+{\s16\sbasedon0\snext17\sb240\sa120\keepn\rtlch\af7\afs28\ltrch\hich\af5\afs28\dbch\af6\loch\f5\fs28 Heading;}
+{\s17\sbasedon0\snext17\sl276\slmult1\sb0\sa140 Body Text;}
+{\s18\sbasedon17\snext18\rtlch\af8\ltrch List;}
+{\s19\sbasedon0\snext19\sb120\sa120\noline\rtlch\af8\afs24\ai\ltrch\fs24\i caption;}
+{\s20\sbasedon0\snext20\noline\rtlch\af8\ltrch Index;}
+{\s21\sbasedon0\snext21\nowidctlpar\noline Table Contents;}
+}{\*\listtable{\list\listtemplateid1
+{\listlevel\levelnfc23\leveljc0\levelstartat1\levelfollow0{\leveltext \'01\u8226 ?;}{\levelnumbers;}\f9\rtlch\af4\ltrch\fi-360\li720}
+{\listlevel\levelnfc23\leveljc0\levelstartat1\levelfollow0{\leveltext \'01\u9702 ?;}{\levelnumbers;}\f9\rtlch\af4\ltrch\fi-360\li1080}
+{\listlevel\levelnfc23\leveljc0\levelstartat1\levelfollow0{\leveltext \'01\u9642 ?;}{\levelnumbers;}\f9\rtlch\af4\ltrch\fi-360\li1440}
+{\listlevel\levelnfc23\leveljc0\levelstartat1\levelfollow0{\leveltext \'01\u8226 ?;}{\levelnumbers;}\f9\rtlch\af4\ltrch\fi-360\li1800}
+{\listlevel\levelnfc23\leveljc0\levelstartat1\levelfollow0{\leveltext \'01\u9702 ?;}{\levelnumbers;}\f9\rtlch\af4\ltrch\fi-360\li2160}
+{\listlevel\levelnfc23\leveljc0\levelstartat1\levelfollow0{\leveltext \'01\u9642 ?;}{\levelnumbers;}\f9\rtlch\af4\ltrch\fi-360\li2520}
+{\listlevel\levelnfc23\leveljc0\levelstartat1\levelfollow0{\leveltext \'01\u8226 ?;}{\levelnumbers;}\f9\rtlch\af4\ltrch\fi-360\li2880}
+{\listlevel\levelnfc23\leveljc0\levelstartat1\levelfollow0{\leveltext \'01\u9702 ?;}{\levelnumbers;}\f9\rtlch\af4\ltrch\fi-360\li3240}
+{\listlevel\levelnfc23\leveljc0\levelstartat1\levelfollow0{\leveltext \'01\u9642 ?;}{\levelnumbers;}\f9\rtlch\af4\ltrch\fi-360\li3600}\listid1}
+{\list\listtemplateid2
+{\listlevel\levelnfc255\leveljc0\levelstartat1\levelfollow2{\leveltext \'00;}{\levelnumbers;}\fi0\li0}
+{\listlevel\levelnfc255\leveljc0\levelstartat1\levelfollow2{\leveltext \'00;}{\levelnumbers;}\fi0\li0}
+{\listlevel\levelnfc255\leveljc0\levelstartat1\levelfollow2{\leveltext \'00;}{\levelnumbers;}\fi0\li0}
+{\listlevel\levelnfc255\leveljc0\levelstartat1\levelfollow2{\leveltext \'00;}{\levelnumbers;}\fi0\li0}
+{\listlevel\levelnfc255\leveljc0\levelstartat1\levelfollow2{\leveltext \'00;}{\levelnumbers;}\fi0\li0}
+{\listlevel\levelnfc255\leveljc0\levelstartat1\levelfollow2{\leveltext \'00;}{\levelnumbers;}\fi0\li0}
+{\listlevel\levelnfc255\leveljc0\levelstartat1\levelfollow2{\leveltext \'00;}{\levelnumbers;}\fi0\li0}
+{\listlevel\levelnfc255\leveljc0\levelstartat1\levelfollow2{\leveltext \'00;}{\levelnumbers;}\fi0\li0}
+{\listlevel\levelnfc255\leveljc0\levelstartat1\levelfollow2{\leveltext \'00;}{\levelnumbers;}\fi0\li0}\listid2}
+}{\listoverridetable{\listoverride\listid1\listoverridecount0\ls1}{\listoverride\listid2\listoverridecount0\ls2}}{\*\generator LibreOffice/25.8.4.2$Linux_X86_64 LibreOffice_project/580$Build-2}{\info{\creatim\yr2025\mo12\dy28\hr10\min51}{\revtim\yr2025\mo12\dy28\hr10\min53}{\printim\yr0\mo0\dy0\hr0\min0}}{\*\userprops}\deftab709
+\hyphauto1\viewscale140\formshade\nobrkwrptbl\paperh15840\paperw12240\margl1134\margr1134\margt1134\margb1134\sectd\sbknone\sftnnar\saftnnrlc\sectunlocked1\pgwsxn12240\pghsxn15840\marglsxn1134\margrsxn1134\margtsxn1134\margbsxn1134\ftnbj\ftnstart1\ftnrstcont\ftnnar\fet\aftnrstcont\aftnstart1\aftnnrlc
+{\*\ftnsep\chftnsep}\pgndec\pard\plain \s0\widctlpar\hyphpar0\ltrpar\kerning1\cf0\rtlch\af7\afs24\alang1081\ltrch\hich\af3\afs24\alang1033\dbch\af10\langfe2052\loch\f3\fs24\lang1033{\listtext\pard\plain \rtlch\af4\ltrch\hich\af4\dbch\af4\loch\f4 \u8226\'95\tab}\ilvl0\ls1 \fi-360\li720\lin720\ql\ltrpar{
+List item}
+\par \trowd\trql\ltrrow\trpaddft3\trpaddt0\trpaddfl3\trpaddl0\trpaddfb3\trpaddb0\trpaddfr3\trpaddr0\clbrdrt\brdrs\brdrw10\brdrcf1\clpadfl3\clpadl55\clbrdrl\brdrs\brdrw10\brdrcf1\clpadft3\clpadt55\clbrdrb\brdrs\brdrw10\brdrcf1\clpadfb3\clpadb55\clpadfr3\clpadr55\cellx4986\clbrdrt\brdrs\brdrw10\brdrcf1\clpadfl3\clpadl55\clbrdrl\brdrs\brdrw10\brdrcf1\clpadft3\clpadt55\clbrdrb\brdrs\brdrw10\brdrcf1\clpadfb3\clpadb55\clbrdrr\brdrs\brdrw10\brdrcf1\clpadfr3\clpadr55\cellx9972\pard\plain \s21\nowidctlpar\noline\intbl\ql\ltrpar{
+A}\cell\pard\plain \s21\nowidctlpar\noline\intbl\ql\ltrpar{
+B}\cell\row\pard \pard\plain \s0\widctlpar\hyphpar0\ltrpar\kerning1\cf0\rtlch\af7\afs24\alang1081\ltrch\hich\af3\afs24\alang1033\dbch\af10\langfe2052\loch\f3\fs24\lang1033\ql\ltrpar
+\par }
+^D
+[ BulletList
+    [ [ Para [ Str "List" , Space , Str "item" ] ] ]
+, Table
+    ( "" , [] , [] )
+    (Caption Nothing [])
+    [ ( AlignDefault , ColWidthDefault )
+    , ( AlignDefault , ColWidthDefault )
+    ]
+    (TableHead ( "" , [] , [] ) [])
+    [ TableBody
+        ( "" , [] , [] )
+        (RowHeadColumns 0)
+        []
+        [ Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Para [ Str "A" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Para [ Str "B" ] ]
+            ]
+        ]
+    ]
+    (TableFoot ( "" , [] , [] ) [])
+]
+```
diff --git a/test/command/11374.md b/test/command/11374.md
new file mode 100644
--- /dev/null
+++ b/test/command/11374.md
@@ -0,0 +1,6 @@
+```
+% pandoc -f native -t asciidoc
+[ Para [ SmallCaps [ Str "foo" ] ] ]
+^D
+[smallcaps]#foo#
+```
diff --git a/test/command/11384.md b/test/command/11384.md
new file mode 100644
--- /dev/null
+++ b/test/command/11384.md
@@ -0,0 +1,17 @@
+```
+% pandoc -t markdown -f native
+[ Para [ Math DisplayMath "\ne = mc^2\n" ] ]
+^D
+$$
+e = mc^2
+$$
+```
+
+But we need to collapse spaces around inline math:
+
+```
+% pandoc -t markdown -f native
+[ Para [ Math InlineMath "\ne=mc\n" ]]
+^D
+$e=mc$
+```
diff --git a/test/command/11409.md b/test/command/11409.md
new file mode 100644
--- /dev/null
+++ b/test/command/11409.md
@@ -0,0 +1,11 @@
+```
+% pandoc -t native
+text^[sup]{.class}^
+^D
+[ Para
+    [ Str "text"
+    , Superscript
+        [ Span ( "" , [ "class" ] , [] ) [ Str "sup" ] ]
+    ]
+]
+```
diff --git a/test/command/11420.md b/test/command/11420.md
new file mode 100644
--- /dev/null
+++ b/test/command/11420.md
@@ -0,0 +1,15 @@
+````
+% pandoc -t revealjs --syntax-highlighting=idiomatic
+# Slide
+
+```python
+def hello():
+    print("Hello")
+```
+^D
+<section id="slide" class="slide level1">
+<h1>Slide</h1>
+<pre><code class="language-python">def hello():
+    print(&quot;Hello&quot;)</code></pre>
+</section>
+````
diff --git a/test/command/11422.md b/test/command/11422.md
new file mode 100644
--- /dev/null
+++ b/test/command/11422.md
@@ -0,0 +1,12 @@
+```
+% pandoc -f docbook -t markdown
+<example>
+    <para>
+      Example without a title.
+    </para>
+</example>
+^D
+::: example
+Example without a title.
+:::
+```
diff --git a/test/command/11450.md b/test/command/11450.md
new file mode 100644
--- /dev/null
+++ b/test/command/11450.md
@@ -0,0 +1,62 @@
+Test for \footnotemark and \footnotetext (issue #11450)
+
+```
+% pandoc -f latex -t native
+Text\footnotemark{}.
+\footnotetext{The footnote content.}
+^D
+[ Para
+    [ Str "Text"
+    , Note
+        [ Para
+            [ Str "The"
+            , Space
+            , Str "footnote"
+            , Space
+            , Str "content."
+            ]
+        ]
+    , Str "."
+    ]
+]
+```
+
+With explicit footnote numbers:
+
+```
+% pandoc -f latex -t native
+First\footnotemark[1] and second\footnotemark[2].
+\footnotetext[1]{First note.}
+\footnotetext[2]{Second note.}
+^D
+[ Para
+    [ Str "First"
+    , Note [ Para [ Str "First" , Space , Str "note." ] ]
+    , Space
+    , Str "and"
+    , Space
+    , Str "second"
+    , Note [ Para [ Str "Second" , Space , Str "note." ] ]
+    , Str "."
+    ]
+]
+```
+
+Mixed with regular footnotes:
+
+```
+% pandoc -f latex -t native
+Text\footnotemark[1] and more\footnote{Regular footnote.}
+\footnotetext[1]{Marked footnote.}
+^D
+[ Para
+    [ Str "Text"
+    , Note [ Para [ Str "Marked" , Space , Str "footnote." ] ]
+    , Space
+    , Str "and"
+    , Space
+    , Str "more"
+    , Note [ Para [ Str "Regular" , Space , Str "footnote." ] ]
+    ]
+]
+```
diff --git a/test/command/11455.md b/test/command/11455.md
new file mode 100644
--- /dev/null
+++ b/test/command/11455.md
@@ -0,0 +1,26 @@
+```
+% pandoc -f textile -t html
+| foo | bar |
+| table
+* item 1
+* item 2
+* item 3 | xxx |
+^D
+<table>
+<tbody>
+<tr>
+<td>foo</td>
+<td>bar</td>
+</tr>
+<tr>
+<td><p>table</p>
+<ul>
+<li>item 1</li>
+<li>item 2</li>
+<li>item 3</li>
+</ul></td>
+<td>xxx</td>
+</tr>
+</tbody>
+</table>
+```
diff --git a/test/command/11463.md b/test/command/11463.md
new file mode 100644
--- /dev/null
+++ b/test/command/11463.md
@@ -0,0 +1,13 @@
+```
+% pandoc -t typst
+'hi' and \'
+^D
+'hi' and \'
+```
+
+```
+% pandoc -f markdown -t typst | pandoc -f typst -t markdown
+"hi" \" 'hi' and \'
+^D
+"hi" \" 'hi' and \'
+```
diff --git a/test/command/11479.md b/test/command/11479.md
new file mode 100644
--- /dev/null
+++ b/test/command/11479.md
@@ -0,0 +1,31 @@
+```
+% pandoc -f docbook -t gfm
+<important>
+<itemizedlist>
+<listitem>
+<simpara>Test.</simpara>
+</listitem>
+<listitem>
+<simpara>Test 2.</simpara>
+</listitem>
+</itemizedlist>
+</important>
+^D
+> [!IMPORTANT]
+> - Test.
+>
+> - Test 2.
+```
+
+```
+% pandoc -f gfm -t gfm
+> [!IMPORTANT]
+> - Test.
+>
+> - Test 2.
+^D
+> [!IMPORTANT]
+> - Test.
+>
+> - Test 2.
+```
diff --git a/test/command/11486.md b/test/command/11486.md
new file mode 100644
--- /dev/null
+++ b/test/command/11486.md
@@ -0,0 +1,82 @@
+```
+% pandoc -t revealjs --template=command/11486/scroll.revealjs
+---
+view: scroll
+---
+^D
+        scrollActivationWidth: 0,
+        scrollSnap: 'mandatory',
+        scrollProgress: 'auto',
+```
+
+```
+% pandoc -t revealjs --template=command/11486/scroll.revealjs
+---
+view: scroll
+scrollSnap: false
+---
+^D
+        scrollActivationWidth: 0,
+        scrollSnap: false,
+        scrollProgress: 'auto',
+```
+
+```
+% pandoc -t revealjs --template=command/11486/scroll.revealjs
+---
+view: scroll
+scrollSnap: proximity
+---
+^D
+        scrollActivationWidth: 0,
+        scrollSnap: 'proximity',
+        scrollProgress: 'auto',
+```
+
+```
+% pandoc -t revealjs --template=command/11486/scroll.revealjs
+---
+view: scroll
+scrollActivationWidth: 500
+---
+^D
+        scrollActivationWidth: 500,
+        scrollSnap: 'mandatory',
+        scrollProgress: 'auto',
+```
+
+```
+% pandoc -t revealjs --template=command/11486/scroll.revealjs
+---
+view: scroll
+scrollProgress: true
+---
+^D
+        scrollActivationWidth: 0,
+        scrollSnap: 'mandatory',
+        scrollProgress: true,
+```
+
+```
+% pandoc -t revealjs --template=command/11486/scroll.revealjs
+---
+view: scroll
+scrollProgress: false
+---
+^D
+        scrollActivationWidth: 0,
+        scrollSnap: 'mandatory',
+        scrollProgress: false,
+```
+
+```
+% pandoc -t revealjs --template=command/11486/scroll.revealjs
+---
+view: scroll
+scrollProgress: auto
+---
+^D
+        scrollActivationWidth: 0,
+        scrollSnap: 'mandatory',
+        scrollProgress: 'auto',
+```
diff --git a/test/command/11486/scroll.revealjs b/test/command/11486/scroll.revealjs
new file mode 100644
--- /dev/null
+++ b/test/command/11486/scroll.revealjs
@@ -0,0 +1,15 @@
+$if(view)$
+        scrollActivationWidth: $scrollActivationWidth$,
+$if(scrollSnap)$
+        scrollSnap: '$scrollSnap/nowrap$',
+$else$
+        scrollSnap: false,
+$endif$
+$if(scrollProgressAuto)$
+        scrollProgress: 'auto',
+$elseif(scrollProgress)$
+        scrollProgress: $scrollProgress$,
+$else$
+        scrollProgress: false,
+$endif$
+$endif$
diff --git a/test/command/11490.md b/test/command/11490.md
new file mode 100644
--- /dev/null
+++ b/test/command/11490.md
@@ -0,0 +1,13 @@
+```
+% pandoc -t markdown
+&lt;&amp;lt;
+^D
+\<\&lt;
+```
+
+```
+% pandoc -t markdown
+&amp;#xa0;
+^D
+\&#xa0;
+```
diff --git a/test/command/11494.md b/test/command/11494.md
new file mode 100644
--- /dev/null
+++ b/test/command/11494.md
@@ -0,0 +1,73 @@
+External images should not use [[File:...]] syntax.
+
+Inline external image:
+```
+% pandoc -f native -t mediawiki
+[Para [Image ("",[],[]) [] ("https://example.org/image.png", "")]]
+^D
+<nowiki></nowiki>https://example.org/image.png<nowiki></nowiki>
+```
+
+Inline local image (should still use [[File:]]):
+```
+% pandoc -f native -t mediawiki
+[Para [Image ("",[],[]) [] ("local.png", "")]]
+^D
+[[File:local.png]]
+```
+
+Figure with external image (from markdown):
+```
+% pandoc -f markdown -t mediawiki
+![](https://example.org/figure.png)
+^D
+<nowiki></nowiki>https://example.org/figure.png<nowiki></nowiki>
+```
+
+Local image (from markdown, no caption):
+```
+% pandoc -f markdown -t mediawiki
+![](local.png)
+^D
+[[File:local.png]]
+```
+
+Figure with caption and external image:
+```
+% pandoc -f markdown -t mediawiki
+![Caption](https://example.org/figure.png)
+^D
+<div class="figure">
+<nowiki></nowiki>https://example.org/figure.png<nowiki></nowiki>
+</div>
+```
+
+Figure with caption and local image:
+```
+% pandoc -f markdown -t mediawiki
+![Caption](local.png)
+^D
+<div class="figure">
+[[File:local.png|Caption]]
+</div>
+```
+
+SimpleFigure with external image (native format with fig: title):
+```
+% pandoc -f native -t mediawiki
+[Figure ("",[],[]) (Caption Nothing []) [Para [Image ("",[],[]) [Str "caption"] ("https://example.org/figure.png", "fig:")]]]
+^D
+<div class="figure">
+<nowiki></nowiki>https://example.org/figure.png<nowiki></nowiki>
+</div>
+```
+
+SimpleFigure with local image (native format with fig: title):
+```
+% pandoc -f native -t mediawiki
+[Figure ("",[],[]) (Caption Nothing []) [Para [Image ("",[],[]) [Str "caption"] ("local.png", "fig:")]]]
+^D
+<div class="figure">
+[[File:local.png|thumb|none|alt=caption|caption]]
+</div>
+```
diff --git a/test/command/11498.md b/test/command/11498.md
new file mode 100644
--- /dev/null
+++ b/test/command/11498.md
@@ -0,0 +1,121 @@
+```
+% pandoc -f markdown -t icml
+![](command/11498.png){object-style="myStyle"}
+^D
+<ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/Paragraph">
+  <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
+    <Rectangle Self="uec" StrokeWeight="0" ItemTransform="1 0 0 1 32 -32" AppliedObjectStyle="ObjectStyle/myStyle">
+      <Properties>
+        <PathGeometry>
+          <GeometryPathType PathOpen="false">
+            <PathPointArray>
+              <PathPointType Anchor="-32 -32" LeftDirection="-32 -32" RightDirection="-32 -32" />
+              <PathPointType Anchor="-32 32" LeftDirection="-32 32" RightDirection="-32 32" />
+              <PathPointType Anchor="32 32" LeftDirection="32 32" RightDirection="32 32" />
+              <PathPointType Anchor="32 -32" LeftDirection="32 -32" RightDirection="32 -32" />
+            </PathPointArray>
+          </GeometryPathType>
+        </PathGeometry>
+      </Properties>
+      <Image Self="ue6" ItemTransform="1 0 0 1 -32 -32">
+        <Properties>
+          <Profile type="string">
+            $ID/Embedded
+          </Profile>
+          <GraphicBounds Left="0" Top="0" Right="64" Bottom="64" />
+        </Properties>
+        <Link Self="ueb" LinkResourceURI="file:command/11498.png" />
+      </Image>
+    </Rectangle>
+  </CharacterStyleRange>
+</ParagraphStyleRange>
+```
+```
+% pandoc -s -f markdown -t icml
+![](command/11498.png){object-style="myStyle"}
+^D
+<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
+<?aid style="50" type="snippet" readerVersion="6.0" featureSet="513" product="8.0(370)" ?>
+<?aid SnippetType="InCopyInterchange"?>
+<Document DOMVersion="8.0" Self="pandoc_doc">
+    <RootCharacterStyleGroup Self="pandoc_character_styles">
+      <CharacterStyle Self="$ID/NormalCharacterStyle" Name="Default" />
+      <CharacterStyle Self="CharacterStyle/" Name="">
+        <Properties>
+          <BasedOn type="object">$ID/NormalCharacterStyle</BasedOn>
+        </Properties>
+      </CharacterStyle>
+    </RootCharacterStyleGroup>
+    <RootParagraphStyleGroup Self="pandoc_paragraph_styles">
+      <ParagraphStyle Self="$ID/NormalParagraphStyle" Name="$ID/NormalParagraphStyle"
+          SpaceBefore="6" SpaceAfter="6"> <!-- paragraph spacing -->
+        <Properties>
+          <TabList type="list">
+            <ListItem type="record">
+              <Alignment type="enumeration">LeftAlign</Alignment>
+              <AlignmentCharacter type="string">.</AlignmentCharacter>
+              <Leader type="string"></Leader>
+              <Position type="unit">10</Position> <!-- first tab stop -->
+            </ListItem>
+          </TabList>
+        </Properties>
+      </ParagraphStyle>
+      <ParagraphStyle Self="ParagraphStyle/Paragraph" Name="Paragraph" LeftIndent="0">
+        <Properties>
+          <BasedOn type="object">$ID/NormalParagraphStyle</BasedOn>
+        </Properties>
+      </ParagraphStyle>
+    </RootParagraphStyleGroup>
+    <RootTableStyleGroup Self="pandoc_table_styles">
+      <TableStyle Self="TableStyle/Table" Name="Table" />
+    </RootTableStyleGroup>
+    <RootCellStyleGroup Self="pandoc_cell_styles">
+      <CellStyle Self="CellStyle/Cell" AppliedParagraphStyle="ParagraphStyle/$ID/[No paragraph style]" Name="Cell" />
+    </RootCellStyleGroup>
+    <RootObjectStyleGroup Self="pandoc_object_styles">
+      <ObjectStyle Self="ObjectStyle/myStyle" Name="myStyle">
+        <Properties>
+          <BasedOn type="string">$ID/None</BasedOn>
+        </Properties>
+      </ObjectStyle>
+    </RootObjectStyleGroup>
+  <Story Self="pandoc_story"
+      TrackChanges="false"
+      StoryTitle=""
+      AppliedTOCStyle="n"
+      AppliedNamedGrid="n" >
+    <StoryPreference OpticalMarginAlignment="true" OpticalMarginSize="12" />
+
+<!-- body needs to be non-indented, otherwise code blocks are indented too far -->
+<ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/Paragraph">
+  <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
+    <Rectangle Self="uec" StrokeWeight="0" ItemTransform="1 0 0 1 32 -32" AppliedObjectStyle="ObjectStyle/myStyle">
+      <Properties>
+        <PathGeometry>
+          <GeometryPathType PathOpen="false">
+            <PathPointArray>
+              <PathPointType Anchor="-32 -32" LeftDirection="-32 -32" RightDirection="-32 -32" />
+              <PathPointType Anchor="-32 32" LeftDirection="-32 32" RightDirection="-32 32" />
+              <PathPointType Anchor="32 32" LeftDirection="32 32" RightDirection="32 32" />
+              <PathPointType Anchor="32 -32" LeftDirection="32 -32" RightDirection="32 -32" />
+            </PathPointArray>
+          </GeometryPathType>
+        </PathGeometry>
+      </Properties>
+      <Image Self="ue6" ItemTransform="1 0 0 1 -32 -32">
+        <Properties>
+          <Profile type="string">
+            $ID/Embedded
+          </Profile>
+          <GraphicBounds Left="0" Top="0" Right="64" Bottom="64" />
+        </Properties>
+        <Link Self="ueb" LinkResourceURI="file:command/11498.png" />
+      </Image>
+    </Rectangle>
+  </CharacterStyleRange>
+</ParagraphStyleRange>
+
+  </Story>
+  
+</Document>
+```
diff --git a/test/command/11498.png b/test/command/11498.png
new file mode 100644
Binary files /dev/null and b/test/command/11498.png differ
diff --git a/test/command/11511.md b/test/command/11511.md
new file mode 100644
--- /dev/null
+++ b/test/command/11511.md
@@ -0,0 +1,6 @@
+```
+% pandoc -f html -t typst
+<p><a href="http://torch.utils.data" rel="noopener noreferrer nofollow" target="_blank">torch.utils.data</a>.Dataset</p>
+^D
+#link("http://torch.utils.data")[torch.utils.data]\.Dataset
+```
diff --git a/test/command/11534.md b/test/command/11534.md
new file mode 100644
--- /dev/null
+++ b/test/command/11534.md
@@ -0,0 +1,42 @@
+```
+% pandoc -f markdown+lists_without_preceding_blankline+alerts -t native
+:::: caution
+::: title
+Caution
+:::
+
+Foo bar, wuppie fluppie!
+::::
+^D
+[ Div
+    ( "" , [ "caution" ] , [] )
+    [ Div ( "" , [ "title" ] , [] ) [ Para [ Str "Caution" ] ]
+    , Para
+        [ Str "Foo"
+        , Space
+        , Str "bar,"
+        , Space
+        , Str "wuppie"
+        , Space
+        , Str "fluppie!"
+        ]
+    ]
+]
+```
+
+```
+% pandoc -f markdown+lists_without_preceding_blankline -t native
+hello
+- a
+- b
+c
+^D
+[ Para [ Str "hello" ]
+, BulletList
+    [ [ Plain [ Str "a" ] ]
+    , [ Plain [ Str "b" , SoftBreak , Str "c" ] ]
+    ]
+]
+
+```
+
diff --git a/test/command/11542.md b/test/command/11542.md
new file mode 100644
--- /dev/null
+++ b/test/command/11542.md
@@ -0,0 +1,47 @@
+```
+% pandoc -f native -t markdown
+[ DefinitionList
+    [ ( [ Str "Input" ]
+      , [ [ CodeBlock ( "" , [] , [] ) "Term\n\n  : Def" ] ]
+      )
+    ]
+]
+^D
+Input
+
+:     Term
+
+        : Def
+```
+
+```
+% pandoc -f markdown -t native
+Input
+
+:     Term
+
+        : Def
+^D
+[ DefinitionList
+    [ ( [ Str "Input" ]
+      , [ [ CodeBlock ( "" , [] , [] ) "Term\n\n  : Def" ] ]
+      )
+    ]
+]
+```
+
+```
+% pandoc -f native -t markdown+four_space_rule
+[ DefinitionList
+    [ ( [ Str "Input" ]
+      , [ [ CodeBlock ( "" , [] , [] ) "Term\n\n  : Def" ] ]
+      )
+    ]
+]
+^D
+Input
+
+:       Term
+
+          : Def
+```
diff --git a/test/command/11562.md b/test/command/11562.md
new file mode 100644
--- /dev/null
+++ b/test/command/11562.md
@@ -0,0 +1,10 @@
+```
+% pandoc -t mediawiki
+[example](https://example.com/#/#room)
+
+[example](https://example.com/##)
+^D
+[https://example.com/#/#room example]
+
+[https://example.com/## example]
+```
diff --git a/test/command/11571.md b/test/command/11571.md
new file mode 100644
--- /dev/null
+++ b/test/command/11571.md
@@ -0,0 +1,18 @@
+```
+% pandoc -t markdown
+:::
+A
+:::
+^D
+\::: A \:::
+```
+
+```
+% pandoc -t commonmark+fenced_divs
+:::
+A
+:::
+^D
+\::: A \:::
+```
+
diff --git a/test/command/11583.md b/test/command/11583.md
new file mode 100644
--- /dev/null
+++ b/test/command/11583.md
@@ -0,0 +1,16 @@
+```
+% pandoc -t typst
+::: {lang=en}
+1. item
+2. item
+3. item
+:::
+^D
+#block[
+#set text(lang: "en");
++ item
++ item
++ item
+
+]
+```
diff --git a/test/command/11588.md b/test/command/11588.md
new file mode 100644
--- /dev/null
+++ b/test/command/11588.md
@@ -0,0 +1,10 @@
+```
+% pandoc --typst-input foo=FOO --typst-input bar="bar bim" -f typst -t plain
+#sys.inputs.at("foo");
+
+#sys.inputs.at("bar");
+^D
+FOO
+
+bar bim
+```
diff --git a/test/command/11589.md b/test/command/11589.md
new file mode 100644
--- /dev/null
+++ b/test/command/11589.md
@@ -0,0 +1,20 @@
+```
+% pandoc -f markdown -t native
+t^[a]{.cb}\ b^
+t^[a]{fg=yellow bg=blue}\ b^
+^D
+[ Para
+    [ Str "t"
+    , Superscript
+        [ Span ( "" , [ "cb" ] , [] ) [ Str "a" ] , Str "\160b" ]
+    , SoftBreak
+    , Str "t"
+    , Superscript
+        [ Span
+            ( "" , [] , [ ( "fg" , "yellow" ) , ( "bg" , "blue" ) ] )
+            [ Str "a" ]
+        , Str "\160b"
+        ]
+    ]
+]
+```
diff --git a/test/command/11598.md b/test/command/11598.md
new file mode 100644
--- /dev/null
+++ b/test/command/11598.md
@@ -0,0 +1,16 @@
+```
+% pandoc -f typst --wrap=none
+#rotate(90deg, figure(
+  [body text here inside rotate],
+  caption: "Figure 1: How a caption gets lost when rotating",
+  supplement: none,
+))
+^D
+<div class="rotate" data-angle="90.0">
+<figure>
+<p>body text here inside rotate</p>
+<figcaption><p>Figure 1: How a caption gets lost when rotating</p></figcaption>
+</figure>
+</div>
+
+```
diff --git a/test/command/11604.md b/test/command/11604.md
new file mode 100644
--- /dev/null
+++ b/test/command/11604.md
@@ -0,0 +1,22 @@
+```
+% pandoc -f latex -t typst
+\begin{table}
+  \caption{Caption}\label{tab}
+  \begin{tabular}{cc}
+    a & b \\ c & d
+  \end{tabular}
+\end{table}
+^D
+#figure(
+  align(center)[#table(
+    columns: 2,
+    align: (center,center,),
+    [a], [b],
+    [c], [d],
+  )]
+  , caption: [Caption]
+  , kind: table
+  )
+<tab>
+
+```
diff --git a/test/command/11608.md b/test/command/11608.md
new file mode 100644
--- /dev/null
+++ b/test/command/11608.md
@@ -0,0 +1,54 @@
+```
+% pandoc -f latex -t plain
+\documentclass[english]{article}
+\usepackage[T1]{fontenc}
+\usepackage[utf8]{inputenc}
+\usepackage{amsthm}
+\theoremstyle{plain}
+\newtheorem{thm}{\protect\theoremname}
+\newtheorem{prop}[thm]{\protect\propositionname}
+\usepackage{babel}
+\providecommand{\propositionname}{Proposition}
+\providecommand{\theoremname}{Theorem}
+
+\begin{document}
+\begin{thm}
+first theorem
+\end{thm}
+\begin{prop}
+first proposition
+\end{prop}
+
+\end{document}
+<div class="thm">
+<p><strong>Theorem 1</strong>. <em>first theorem</em></p>
+</div>
+<div class="prop">
+<p><strong>Proposition 2</strong>. <em>first proposition</em></p>
+</div>
+jgm@Johns-MacBook-Air:~/src/pandoc % `make binpath` -f latex -t plain
+\documentclass[english]{article}
+\usepackage[T1]{fontenc}
+\usepackage[utf8]{inputenc}
+\usepackage{amsthm}
+\theoremstyle{plain}
+\newtheorem{thm}{\protect\theoremname}
+\newtheorem{prop}[thm]{\protect\propositionname}
+\usepackage{babel}
+\providecommand{\propositionname}{Proposition}
+\providecommand{\theoremname}{Theorem}
+
+\begin{document}
+\begin{thm}
+first theorem
+\end{thm}
+\begin{prop}
+first proposition
+\end{prop}
+
+\end{document}
+^D
+Theorem 1. first theorem
+
+Proposition 2. first proposition
+```
diff --git a/test/command/11635.md b/test/command/11635.md
new file mode 100644
--- /dev/null
+++ b/test/command/11635.md
@@ -0,0 +1,28 @@
+```
+% pandoc -f man -t html
+.TH "TEST" "1" "2026-05-08"  "test v1.0.0" "test manual"
+.SH HEADING
+.TS
+tab(;);
+l l.
+this is a table element \
+written in two lines;abcdefg
+another \
+one;123456
+.TE
+^D
+<h1 id="heading">HEADING</h1>
+<table>
+<tbody>
+<tr>
+<td style="text-align: left;">this is a table element written in two
+lines</td>
+<td style="text-align: left;">abcdefg</td>
+</tr>
+<tr>
+<td style="text-align: left;">another one</td>
+<td style="text-align: left;">123456</td>
+</tr>
+</tbody>
+</table>
+```
diff --git a/test/command/1166.md b/test/command/1166.md
--- a/test/command/1166.md
+++ b/test/command/1166.md
@@ -17,28 +17,28 @@
 ^D
 <table>
 <thead>
-<tr class="header">
+<tr>
 <th>col 1</th>
 <th>col 2</th>
 </tr>
 </thead>
 <tbody>
-<tr class="odd">
+<tr>
 <td>1</td>
 <td>Second column of row 1.</td>
 </tr>
-<tr class="even">
-<td><p>2</p></td>
-<td><p>Second column of row 2. Second line of paragraph.</p></td>
+<tr>
+<td>2</td>
+<td>Second column of row 2. Second line of paragraph.</td>
 </tr>
-<tr class="odd">
-<td><p>3</p></td>
+<tr>
+<td>3</td>
 <td><ul>
 <li>Second column of row 3.</li>
 <li>Second item in bullet list (row 3, column 2).</li>
 </ul></td>
 </tr>
-<tr class="even">
+<tr>
 <td></td>
 <td>Row 4; column 1 will be empty.</td>
 </tr>
diff --git a/test/command/11664.md b/test/command/11664.md
new file mode 100644
--- /dev/null
+++ b/test/command/11664.md
@@ -0,0 +1,35 @@
+```
+% pandoc -t markdown -f html
+<table>
+        <colgroup>
+                <col width="1%"/>
+                <col />
+        </colgroup>
+        <tbody>
+                <tr>
+                        <td>
+                                <p>A</p><p>B</p>
+                        </td>
+                        <td>
+                                Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do
+                                eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut
+                                enim ad minim veniam, quis nostrud exercitation ullamco laboris
+                                nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
+                                in reprehenderit in voluptate velit esse cillum dolore eu fugiat
+                                nulla pariatur. Excepteur sint occaecat cupidatat non proident,
+                                sunt in culpa qui officia deserunt mollit anim id est laborum.
+                        </td>
+                </tr>
+        </tbody>
+</table>
+^D
++---+------------------------------------------------------------------+
+| A | Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do  |
+|   | eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut   |
+| B | enim ad minim veniam, quis nostrud exercitation ullamco laboris  |
+|   | nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor   |
+|   | in reprehenderit in voluptate velit esse cillum dolore eu fugiat |
+|   | nulla pariatur. Excepteur sint occaecat cupidatat non proident,  |
+|   | sunt in culpa qui officia deserunt mollit anim id est laborum.   |
++---+------------------------------------------------------------------+
+```
diff --git a/test/command/11668.md b/test/command/11668.md
new file mode 100644
--- /dev/null
+++ b/test/command/11668.md
@@ -0,0 +1,42 @@
+```
+% pandoc -f man -t html
+TH "TEST" "1" "2026-05-25" "test v1.0.0" "test manual"
+.SH HEADING
+.TP 4
+This is the unindented tag.
+This text, along with the table, should be indented.
+.TS
+tab(;);
+l l.
+aaa;bbb
+ccc;ddd
+.TE
+This should still be indented, until some other macro is called to change it.
+.PP
+Like this.
+^D
+<p>TH "TEST" "1" "2026-05-25" "test v1.0.0" "test manual"</p>
+<h1 id="heading">HEADING</h1>
+<dl>
+<dt>This is the unindented tag.</dt>
+<dd>
+<p>This text, along with the table, should be indented.</p>
+<table>
+<tbody>
+<tr>
+<td style="text-align: left;">aaa</td>
+<td style="text-align: left;">bbb</td>
+</tr>
+<tr>
+<td style="text-align: left;">ccc</td>
+<td style="text-align: left;">ddd</td>
+</tr>
+</tbody>
+</table>
+<p>This should still be indented, until some other macro is called to
+change it.</p>
+</dd>
+</dl>
+<p>Like this.</p>
+
+```
diff --git a/test/command/11682.md b/test/command/11682.md
new file mode 100644
--- /dev/null
+++ b/test/command/11682.md
@@ -0,0 +1,81 @@
+Cell paragraphs that use `\plain` after `\intbl`, together with a single
+`\trowd` and `\row` row terminators, should produce a flat table rather
+than deeply nested tables.
+
+```
+% pandoc -f rtf -t native
+{\rtf1\ansi\deff0
+{\fonttbl{\f0 Times;}{\f1 Times;}{\f2 Times;}}
+\trowd\trgaph60\trleft0
+\clvertalt\cellx3245
+\clvertalt\cellx6490
+\clvertalt\cellx9735
+\pard\intbl\s0\ql\plain\f0\fs20\plain\f2\fs22 A\plain\f1\fs22\cell
+\pard\intbl\s0\ql\plain\f0\fs20\plain\f2\fs22 B\plain\f1\fs22\cell
+\pard\intbl\s0\ql\plain\f0\fs20\plain\f2\fs22 C\plain\f1\fs22\cell
+\intbl\row
+\pard\intbl\s0\ql\plain\f0\fs20\plain\f2\fs22 1\plain\f1\fs22\cell
+\pard\intbl\s0\ql\plain\f0\fs20\plain\f2\fs22 2\plain\f1\fs22\cell
+\pard\intbl\s0\ql\plain\f0\fs20\plain\f2\fs22 3\plain\f1\fs22\cell
+\intbl\row
+}
+^D
+[ Table
+    ( "" , [] , [] )
+    (Caption Nothing [])
+    [ ( AlignDefault , ColWidthDefault )
+    , ( AlignDefault , ColWidthDefault )
+    , ( AlignDefault , ColWidthDefault )
+    ]
+    (TableHead ( "" , [] , [] ) [])
+    [ TableBody
+        ( "" , [] , [] )
+        (RowHeadColumns 0)
+        []
+        [ Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Para [ Str "A" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Para [ Str "B" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Para [ Str "C" ] ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Para [ Str "1" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Para [ Str "2" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Para [ Str "3" ] ]
+            ]
+        ]
+    ]
+    (TableFoot ( "" , [] , [] ) [])
+]
+```
diff --git a/test/command/1279.md b/test/command/1279.md
--- a/test/command/1279.md
+++ b/test/command/1279.md
@@ -1,5 +1,5 @@
 ```
-pandoc -s -t markdown
+% pandoc -s -t markdown
 ---
 author: 'John Doe[^1]'
 date: 2014
@@ -9,7 +9,7 @@
 [^1]: Dept. of This and That
 ^D
 ---
-author: 'John Doe[^1]'
+author: John Doe[^1]
 date: 2014
 title: My Article
 ---
diff --git a/test/command/1390.md b/test/command/1390.md
--- a/test/command/1390.md
+++ b/test/command/1390.md
@@ -3,7 +3,13 @@
 \newcommand\foo{+}
 Testing: $\mu\foo\eta$.
 ^D
-[Para [Str "Testing:",Space,Math InlineMath "\\mu+\\eta",Str "."]]
+[ Para
+    [ Str "Testing:"
+    , Space
+    , Math InlineMath "\\mu+\\eta"
+    , Str "."
+    ]
+]
 ```
 
 <!-- It would be nice to handle this case, but I don't
diff --git a/test/command/1592.md b/test/command/1592.md
--- a/test/command/1592.md
+++ b/test/command/1592.md
@@ -2,35 +2,35 @@
 % pandoc -t native
 [hi]{.smallcaps}
 ^D
-[Para [SmallCaps [Str "hi"]]]
+[ Para [ SmallCaps [ Str "hi" ] ] ]
 ```
 
 ```
 % pandoc -t native
 [hi]{style="font-variant: small-caps;"}
 ^D
-[Para [SmallCaps [Str "hi"]]]
+[ Para [ SmallCaps [ Str "hi" ] ] ]
 ```
 
 ```
 % pandoc -t native
 <span class="smallcaps">hi</span>
 ^D
-[Para [SmallCaps [Str "hi"]]]
+[ Para [ SmallCaps [ Str "hi" ] ] ]
 ```
 
 ```
 % pandoc -f html -t native
 <p><span class="smallcaps">hi</span></p>
 ^D
-[Para [SmallCaps [Str "hi"]]]
+[ Para [ SmallCaps [ Str "hi" ] ] ]
 ```
 
 ```
 % pandoc -f html -t native
 <p><span style="font-variant:small-caps">hi</span></p>
 ^D
-[Para [SmallCaps [Str "hi"]]]
+[ Para [ SmallCaps [ Str "hi" ] ] ]
 ```
 
 ```
@@ -41,9 +41,58 @@
 ```
 
 ```
-pandoc -f native -t markdown
+% pandoc -f native -t markdown
 [Para [SmallCaps [Str "hi"]]]
 ^D
 [hi]{.smallcaps}
 ```
 
+```
+% pandoc -f html -t native
+<bdo dir="ltr">foo</bdo>
+^D
+[ Plain
+    [ Span ( "" , [] , [ ( "dir" , "ltr" ) ] ) [ Str "foo" ] ]
+]
+```
+
+```
+% pandoc -f html -t native
+<bdo dir="rtl">foo<bdo dir="ltr">bar</bdo>baz</bdo>
+^D
+[ Plain
+    [ Span
+        ( "" , [] , [ ( "dir" , "rtl" ) ] )
+        [ Str "foo"
+        , Span ( "" , [] , [ ( "dir" , "ltr" ) ] ) [ Str "bar" ]
+        , Str "baz"
+        ]
+    ]
+]
+```
+
+```
+% pandoc -f html -t native
+<p><bdo dir="rtl">This text will go right
+to left.</bdo></p>
+^D
+[ Para
+    [ Span
+        ( "" , [] , [ ( "dir" , "rtl" ) ] )
+        [ Str "This"
+        , Space
+        , Str "text"
+        , Space
+        , Str "will"
+        , Space
+        , Str "go"
+        , Space
+        , Str "right"
+        , SoftBreak
+        , Str "to"
+        , Space
+        , Str "left."
+        ]
+    ]
+]
+```
diff --git a/test/command/1608.md b/test/command/1608.md
new file mode 100644
--- /dev/null
+++ b/test/command/1608.md
@@ -0,0 +1,205 @@
+```
+% pandoc -f latex -t native
+\newtheorem{theorem}{Theorem}
+\newtheorem{corollary}[theorem]{Corollary}
+\newtheorem{lemma}[theorem]{Lemma}
+\theoremstyle{definition}
+\newtheorem{definition}[theorem]{Definition}
+\theoremstyle{remark}
+\newtheorem{remark}{Remark}
+
+\begin{definition}[right-angled triangles] \label{def:tri}
+A \emph{right-angled triangle} is a triangle whose sides of length~\(a\), \(b\) and~\(c\), in some permutation of order, satisfies \(a^2+b^2=c^2\).
+\end{definition}
+
+\begin{lemma}
+The triangle with sides of length~\(3\), \(4\) and~\(5\) is right-angled.
+\end{lemma}
+
+\begin{proof}
+This lemma follows from \cref{def:tri} since \(3^2+4^2=9+16=25=5^2\).
+\end{proof}
+
+\begin{theorem}[Pythagorean triplets] \label{thm:py}
+Triangles with sides of length \(a=p^2-q^2\), \(b=2pq\) and \(c=p^2+q^2\) are right-angled triangles.
+\end{theorem}
+
+\begin{remark}
+These are all pretty interesting facts.
+\end{remark}
+^D
+[ Div
+    ( "def:tri" , [ "definition" ] , [] )
+    [ Para
+        [ Strong [ Str "Definition" , Space , Str "1" ]
+        , Space
+        , Str "(right-angled"
+        , Space
+        , Str "triangles)."
+        , Space
+        , Space
+        , Str "A"
+        , Space
+        , Emph [ Str "right-angled" , Space , Str "triangle" ]
+        , Space
+        , Str "is"
+        , Space
+        , Str "a"
+        , Space
+        , Str "triangle"
+        , Space
+        , Str "whose"
+        , Space
+        , Str "sides"
+        , Space
+        , Str "of"
+        , Space
+        , Str "length\160"
+        , Math InlineMath "a"
+        , Str ","
+        , Space
+        , Math InlineMath "b"
+        , Space
+        , Str "and\160"
+        , Math InlineMath "c"
+        , Str ","
+        , Space
+        , Str "in"
+        , Space
+        , Str "some"
+        , Space
+        , Str "permutation"
+        , Space
+        , Str "of"
+        , Space
+        , Str "order,"
+        , Space
+        , Str "satisfies"
+        , Space
+        , Math InlineMath "a^2+b^2=c^2"
+        , Str "."
+        ]
+    ]
+, Div
+    ( "" , [ "lemma" ] , [] )
+    [ Para
+        [ Strong [ Str "Lemma" , Space , Str "2" ]
+        , Str "."
+        , Space
+        , Space
+        , Emph
+            [ Str "The"
+            , Space
+            , Str "triangle"
+            , Space
+            , Str "with"
+            , Space
+            , Str "sides"
+            , Space
+            , Str "of"
+            , Space
+            , Str "length\160"
+            , Math InlineMath "3"
+            , Str ","
+            , Space
+            , Math InlineMath "4"
+            , Space
+            , Str "and\160"
+            , Math InlineMath "5"
+            , Space
+            , Str "is"
+            , Space
+            , Str "right-angled."
+            ]
+        ]
+    ]
+, Div
+    ( "" , [ "proof" ] , [] )
+    [ Para
+        [ Emph [ Str "Proof." ]
+        , Space
+        , Str "This"
+        , Space
+        , Str "lemma"
+        , Space
+        , Str "follows"
+        , Space
+        , Str "from"
+        , Space
+        , Link
+            ( ""
+            , []
+            , [ ( "reference-type" , "ref+label" )
+              , ( "reference" , "def:tri" )
+              ]
+            )
+            [ Str "1" ]
+            ( "#def:tri" , "" )
+        , Space
+        , Str "since"
+        , Space
+        , Math InlineMath "3^2+4^2=9+16=25=5^2"
+        , Str "."
+        , Str "\160\9723"
+        ]
+    ]
+, Div
+    ( "thm:py" , [ "theorem" ] , [] )
+    [ Para
+        [ Strong [ Str "Theorem" , Space , Str "3" ]
+        , Space
+        , Str "(Pythagorean"
+        , Space
+        , Str "triplets)."
+        , Space
+        , Space
+        , Emph
+            [ Str "Triangles"
+            , Space
+            , Str "with"
+            , Space
+            , Str "sides"
+            , Space
+            , Str "of"
+            , Space
+            , Str "length"
+            , Space
+            , Math InlineMath "a=p^2-q^2"
+            , Str ","
+            , Space
+            , Math InlineMath "b=2pq"
+            , Space
+            , Str "and"
+            , Space
+            , Math InlineMath "c=p^2+q^2"
+            , Space
+            , Str "are"
+            , Space
+            , Str "right-angled"
+            , Space
+            , Str "triangles."
+            ]
+        ]
+    ]
+, Div
+    ( "" , [ "remark" ] , [] )
+    [ Para
+        [ Emph [ Str "Remark" , Space , Str "1" ]
+        , Str "."
+        , Space
+        , Space
+        , Str "These"
+        , Space
+        , Str "are"
+        , Space
+        , Str "all"
+        , Space
+        , Str "pretty"
+        , Space
+        , Str "interesting"
+        , Space
+        , Str "facts."
+        ]
+    ]
+]
+```
diff --git a/test/command/1629.md b/test/command/1629.md
--- a/test/command/1629.md
+++ b/test/command/1629.md
@@ -1,5 +1,5 @@
 ```
-% pandoc -t latex --listings
+% pandoc -t latex --syntax-highlighting=idiomatic
 bla bla `a % b`
 
 *bla bla `a % b`*
diff --git a/test/command/168.md b/test/command/168.md
--- a/test/command/168.md
+++ b/test/command/168.md
@@ -11,13 +11,25 @@
 :::
 :::::::::::::::::::::::::::::::
 ^D
-[Div ("",["warning"],[])
- [Para [Str "This",Space,Str "is",Space,Str "the",Space,Str "warning!"]
- ,OrderedList (1,Decimal,Period)
-  [[Plain [Str "list"]]
-  ,[Plain [Str "another"]]]
- ,Div ("myid",["class"],[("key","val")])
-  [Para [Str "nested",Space,Str "div"]]]]
+[ Div
+    ( "" , [ "warning" ] , [] )
+    [ Para
+        [ Str "This"
+        , Space
+        , Str "is"
+        , Space
+        , Str "the"
+        , Space
+        , Str "warning!"
+        ]
+    , OrderedList
+        ( 1 , Decimal , Period )
+        [ [ Plain [ Str "list" ] ] , [ Plain [ Str "another" ] ] ]
+    , Div
+        ( "myid" , [ "class" ] , [ ( "key" , "val" ) ] )
+        [ Para [ Str "nested" , Space , Str "div" ] ]
+    ]
+]
 ```
 
 ```
@@ -26,7 +38,14 @@
 :::
 bar
 ^D
-[Para [Str "foo",SoftBreak,Str ":::",SoftBreak,Str "bar"]]
+[ Para
+    [ Str "foo"
+    , SoftBreak
+    , Str ":::"
+    , SoftBreak
+    , Str "bar"
+    ]
+]
 ```
 
 ```
@@ -37,7 +56,18 @@
 And another.
 :::::
 ^D
-[Div ("",["Warning"],[])
- [Para [Str "Here",Space,Str "is",Space,Str "a",Space,Str "paragraph."]
- ,Para [Str "And",Space,Str "another."]]]
+[ Div
+    ( "" , [ "Warning" ] , [] )
+    [ Para
+        [ Str "Here"
+        , Space
+        , Str "is"
+        , Space
+        , Str "a"
+        , Space
+        , Str "paragraph."
+        ]
+    , Para [ Str "And" , Space , Str "another." ]
+    ]
+]
 ```
diff --git a/test/command/1710.md b/test/command/1710.md
--- a/test/command/1710.md
+++ b/test/command/1710.md
@@ -54,12 +54,10 @@
 </div>
 </div>
 ^D
-\begin{frame}{%
-\protect\hypertarget{slide-one}{%
-Slide one}}
-
+\begin{frame}{Slide one}
+\protect\phantomsection\label{slide-one}
 \begin{columns}[T]
-\begin{column}{0.40\textwidth}
+\begin{column}{0.4\linewidth}
 \begin{itemize}
 \tightlist
 \item
@@ -69,7 +67,7 @@
 \end{itemize}
 \end{column}
 
-\begin{column}{0.40\textwidth}
+\begin{column}{0.4\linewidth}
 \begin{itemize}
 \tightlist
 \item
@@ -79,11 +77,9 @@
 \end{itemize}
 \end{column}
 
-\begin{column}{0.10\textwidth}
+\begin{column}{0.1\linewidth}
 ok
 \end{column}
 \end{columns}
-
 \end{frame}
 ```
-
diff --git a/test/command/1718.md b/test/command/1718.md
--- a/test/command/1718.md
+++ b/test/command/1718.md
@@ -6,6 +6,14 @@
 
 [^2]: the second, unused, note.
 ^D
-[WARNING] Note with key '2' defined at line 5 column 1 but not used.
-[Para [Str "Note",Note [Para [Str "the",Space,Str "first",Space,Str "note."]],Str "."]]
+2> [WARNING] Note with key '2' defined at line 5 column 1 but not used.
+[ Para
+    [ Str "Note"
+    , Note
+        [ Para
+            [ Str "the" , Space , Str "first" , Space , Str "note." ]
+        ]
+    , Str "."
+    ]
+]
 ```
diff --git a/test/command/1762.md b/test/command/1762.md
new file mode 100644
--- /dev/null
+++ b/test/command/1762.md
@@ -0,0 +1,15 @@
+```
+% pandoc -t latex
+# One {.unlisted}
+
+# Two {.unnumbered}
+
+# Three {.unlisted .unnumbered}
+^D
+\section{One}\label{one}
+
+\section*{Two}\label{two}
+\addcontentsline{toc}{section}{Two}
+
+\section*{Three}\label{three}
+```
diff --git a/test/command/1773.md b/test/command/1773.md
--- a/test/command/1773.md
+++ b/test/command/1773.md
@@ -2,5 +2,7 @@
 % pandoc -f latex+raw_tex -t native
 \noindent hi
 ^D
-[Para [RawInline (Format "latex") "\\noindent ",Str "hi"]]
+[ Para
+    [ RawInline (Format "latex") "\\noindent " , Str "hi" ]
+]
 ```
diff --git a/test/command/1881.md b/test/command/1881.md
--- a/test/command/1881.md
+++ b/test/command/1881.md
@@ -3,7 +3,7 @@
 <table>
 <caption>Demonstration of simple table syntax.</caption>
 <thead>
-<tr class="header">
+<tr>
 <th align="right">Right</th>
 <th align="left">Left</th>
 <th align="center">Center</th>
@@ -11,7 +11,7 @@
 </tr>
 </thead>
 <tbody>
-<tr class="odd">
+<tr>
 <td align="right">12</td>
 <td align="left">12</td>
 <td align="center">12</td>
@@ -20,21 +20,98 @@
 </tbody>
 </table>
 ^D
-[Table [Str "Demonstration",Space,Str "of",Space,Str "simple",Space,Str "table",Space,Str "syntax."] [AlignRight,AlignLeft,AlignCenter,AlignDefault] [0.0,0.0,0.0,0.0]
- [[Plain [Str "Right"]]
- ,[Plain [Str "Left"]]
- ,[Plain [Str "Center"]]
- ,[Plain [Str "Default"]]]
- [[[Plain [Str "12"]]
-  ,[Plain [Str "12"]]
-  ,[Plain [Str "12"]]
-  ,[Plain [Str "12"]]]]]
+[ Table
+    ( "" , [] , [] )
+    (Caption
+       Nothing
+       [ Plain
+           [ Str "Demonstration"
+           , Space
+           , Str "of"
+           , Space
+           , Str "simple"
+           , Space
+           , Str "table"
+           , Space
+           , Str "syntax."
+           ]
+       ])
+    [ ( AlignRight , ColWidthDefault )
+    , ( AlignLeft , ColWidthDefault )
+    , ( AlignCenter , ColWidthDefault )
+    , ( AlignDefault , ColWidthDefault )
+    ]
+    (TableHead
+       ( "" , [] , [] )
+       [ Row
+           ( "" , [] , [] )
+           [ Cell
+               ( "" , [] , [] )
+               AlignRight
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "Right" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignLeft
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "Left" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignCenter
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "Center" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "Default" ] ]
+           ]
+       ])
+    [ TableBody
+        ( "" , [] , [] )
+        (RowHeadColumns 0)
+        []
+        [ Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignRight
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "12" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignLeft
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "12" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignCenter
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "12" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "12" ] ]
+            ]
+        ]
+    ]
+    (TableFoot ( "" , [] , [] ) [])
+]
 ```
 
 ```
 % pandoc -f html -t native
 <table>
-<tr class="odd">
+<tr>
 <td style="text-align: right;">12</td>
 <td style="text-align:left;">12</td>
 <td style="text-align:  center">12</td>
@@ -42,14 +119,49 @@
 </tr>
 </table>
 ^D
-[Table [] [AlignRight,AlignLeft,AlignCenter,AlignRight] [0.0,0.0,0.0,0.0]
- [[]
- ,[]
- ,[]
- ,[]]
- [[[Plain [Str "12"]]
-  ,[Plain [Str "12"]]
-  ,[Plain [Str "12"]]
-  ,[Plain [Str "12"]]]]]
+[ Table
+    ( "" , [] , [] )
+    (Caption Nothing [])
+    [ ( AlignRight , ColWidthDefault )
+    , ( AlignLeft , ColWidthDefault )
+    , ( AlignCenter , ColWidthDefault )
+    , ( AlignRight , ColWidthDefault )
+    ]
+    (TableHead ( "" , [] , [] ) [])
+    [ TableBody
+        ( "" , [] , [] )
+        (RowHeadColumns 0)
+        []
+        [ Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignRight
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "12" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignLeft
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "12" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignCenter
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "12" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignRight
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "12" ] ]
+            ]
+        ]
+    ]
+    (TableFoot ( "" , [] , [] ) [])
+]
 ```
 
diff --git a/test/command/2103.md b/test/command/2103.md
new file mode 100644
--- /dev/null
+++ b/test/command/2103.md
@@ -0,0 +1,8 @@
+```
+% pandoc -t latex
+| A happy pandoc user said "fix this bug please
+| or I'll go crazy!"
+^D
+A happy pandoc user said ``fix this bug please\\
+or I'll go crazy!''
+```
diff --git a/test/command/2118.md b/test/command/2118.md
--- a/test/command/2118.md
+++ b/test/command/2118.md
@@ -7,5 +7,16 @@
   \label{fig:setminus}
 \end{figure}
 ^D
-[Para [Image ("",[],[("width","80%")]) [Str "Set",Space,Str "subtraction",Span ("",[],[("label","fig:setminus")]) []] ("setminus.png","fig:")]]
+[ Figure
+    ( "fig:setminus" , [] , [ ( "latex-placement" , "ht" ) ] )
+    (Caption
+       Nothing [ Plain [ Str "Set" , Space , Str "subtraction" ] ])
+    [ Plain
+        [ Image
+            ( "" , [] , [ ( "width" , "80%" ) ] )
+            []
+            ( "setminus.png" , "" )
+        ]
+    ]
+]
 ```
diff --git a/test/command/2337.md b/test/command/2337.md
new file mode 100644
--- /dev/null
+++ b/test/command/2337.md
@@ -0,0 +1,6 @@
+```
+% pandoc -t asciidoc -f html
+<a href="http://example.com">][</a>
+^D
+http://example.com[++][++]
+```
diff --git a/test/command/2378.md b/test/command/2378.md
--- a/test/command/2378.md
+++ b/test/command/2378.md
@@ -13,15 +13,16 @@
 ^D
 \begin{longtable}[]{@{}ll@{}}
 \caption{a table}\tabularnewline
-\toprule
-x & y\footnote{a footnote}\tabularnewline
-\midrule
+\toprule\noalign{}
+x & y\footnote{a footnote} \\
+\midrule\noalign{}
 \endfirsthead
-\toprule
-x & y{}\tabularnewline
-\midrule
+\toprule\noalign{}
+x & y{} \\
+\midrule\noalign{}
 \endhead
-1 & 2\tabularnewline
-\bottomrule
+\bottomrule\noalign{}
+\endlastfoot
+1 & 2 \\
 \end{longtable}
 ```
diff --git a/test/command/2434.md b/test/command/2434.md
--- a/test/command/2434.md
+++ b/test/command/2434.md
@@ -6,23 +6,23 @@
     2. beta
     * gamma
 ^D
-<text:list text:style-name="L1">
+<text:list text:style-name="Numbering_20_1">
   <text:list-item>
-    <text:p text:style-name="P1">a</text:p>
+    <text:p text:style-name="List_20_Number_20_Tight">a</text:p>
   </text:list-item>
   <text:list-item>
-    <text:p text:style-name="P1">b</text:p>
-    <text:list>
+    <text:p text:style-name="List_20_Number_20_Tight">b</text:p>
+    <text:list text:style-name="Numbering_20_1">
       <text:list-item>
-        <text:p text:style-name="P1">alpha</text:p>
+        <text:p text:style-name="List_20_Number_20_Tight">alpha</text:p>
       </text:list-item>
       <text:list-item>
-        <text:p text:style-name="P1">beta</text:p>
+        <text:p text:style-name="List_20_Number_20_Tight">beta</text:p>
       </text:list-item>
     </text:list>
-    <text:list text:style-name="L2">
+    <text:list text:style-name="List_20_1">
       <text:list-item>
-        <text:p text:style-name="P2">gamma</text:p>
+        <text:p text:style-name="List_20_Bullet_20_Tight">gamma</text:p>
       </text:list-item>
     </text:list>
   </text:list-item>
@@ -40,20 +40,23 @@
 
     more text -- this line is missing in the odt output
 ^D
-<text:list text:style-name="L1">
+<text:list text:style-name="Pandoc_5f_Numbering_5f_1">
   <text:list-item>
-    <text:p text:style-name="P1">text</text:p>
-    <text:p text:style-name="P1">some text</text:p>
-    <text:list>
+    <text:p text:style-name="List_20_Number">text</text:p>
+    <text:p text:style-name="List_20_Number">some text</text:p>
+    <text:list text:style-name="Pandoc_5f_Numbering_5f_2">
       <text:list-item>
-        <text:p text:style-name="P1">sub item 1</text:p>
+        <text:p text:style-name="List_20_Number_20_Tight">sub item
+        1</text:p>
       </text:list-item>
       <text:list-item>
-        <text:p text:style-name="P1">sub item 2</text:p>
+        <text:p text:style-name="List_20_Number_20_Tight">sub item
+        2</text:p>
       </text:list-item>
     </text:list>
-    <text:p text:style-name="P1">more text – this line is missing in the
-    odt output</text:p>
+    <text:p text:style-name="List_20_Number">more text – this line is
+    missing in the odt output</text:p>
   </text:list-item>
 </text:list>
 ```
+
diff --git a/test/command/2465.md b/test/command/2465.md
new file mode 100644
--- /dev/null
+++ b/test/command/2465.md
@@ -0,0 +1,59 @@
+```
+% pandoc -f textile -t native
+This list starts:
+
+# one
+# two
+
+This list should continue at 3:
+
+#3 three
+# four
+
+This list should restart at 1:
+
+# one again
+# two again
+^D
+[ Para
+    [ Str "This" , Space , Str "list" , Space , Str "starts:" ]
+, OrderedList
+    ( 1 , DefaultStyle , DefaultDelim )
+    [ [ Plain [ Str "one" ] ] , [ Plain [ Str "two" ] ] ]
+, Para
+    [ Str "This"
+    , Space
+    , Str "list"
+    , Space
+    , Str "should"
+    , Space
+    , Str "continue"
+    , Space
+    , Str "at"
+    , Space
+    , Str "3:"
+    ]
+, OrderedList
+    ( 3 , DefaultStyle , DefaultDelim )
+    [ [ Plain [ Str "three" ] ] , [ Plain [ Str "four" ] ] ]
+, Para
+    [ Str "This"
+    , Space
+    , Str "list"
+    , Space
+    , Str "should"
+    , Space
+    , Str "restart"
+    , Space
+    , Str "at"
+    , Space
+    , Str "1:"
+    ]
+, OrderedList
+    ( 1 , DefaultStyle , DefaultDelim )
+    [ [ Plain [ Str "one" , Space , Str "again" ] ]
+    , [ Plain [ Str "two" , Space , Str "again" ] ]
+    ]
+]
+```
+
diff --git a/test/command/2549.md b/test/command/2549.md
--- a/test/command/2549.md
+++ b/test/command/2549.md
@@ -4,7 +4,9 @@
 \section{A section}\label{foo}
 }
 ^D
-[Header 1 ("foo",[],[]) [Str "A",Space,Str "section"]]
+[ Header
+    1 ( "foo" , [] , [] ) [ Str "A" , Space , Str "section" ]
+]
 ```
 
 ```
@@ -13,15 +15,24 @@
 \section{A section}\label{foo}
 }
 ^D
-[Div ("bar",[],[])
- [Header 1 ("foo",[],[]) [Str "A",Space,Str "section"]]]
+[ Div
+    ( "bar" , [] , [] )
+    [ Header
+        1 ( "foo" , [] , [] ) [ Str "A" , Space , Str "section" ]
+    ]
+]
 ```
 
 ```
 % pandoc -f latex -t native
 Bar \hypertarget{foo}{Foo}
 ^D
-[Para [Str "Bar",Space,Span ("foo",[],[]) [Str "Foo"]]]
+[ Para
+    [ Str "Bar"
+    , Space
+    , Span ( "foo" , [] , [] ) [ Str "Foo" ]
+    ]
+]
 ```
 
 ```
@@ -32,7 +43,8 @@
 \end{verbatim}
 }
 ^D
-[Div ("foo",[],[])
- [CodeBlock ("",[],[]) "bar"]]
+[ Div
+    ( "foo" , [] , [] ) [ CodeBlock ( "" , [] , [] ) "bar" ]
+]
 ```
 
diff --git a/test/command/256.md b/test/command/256.md
--- a/test/command/256.md
+++ b/test/command/256.md
@@ -2,11 +2,41 @@
 % pandoc --abbreviations=command/abbrevs -t native
 Foo. bar baz h.k. and e.g. and Mr. Brown.
 ^D
-[Para [Str "Foo.\160bar",Space,Str "baz",Space,Str "h.k.\160and",Space,Str "e.g.",Space,Str "and",Space,Str "Mr.",Space,Str "Brown."]]
+[ Para
+    [ Str "Foo.\160bar"
+    , Space
+    , Str "baz"
+    , Space
+    , Str "h.k.\160and"
+    , Space
+    , Str "e.g."
+    , Space
+    , Str "and"
+    , Space
+    , Str "Mr."
+    , Space
+    , Str "Brown."
+    ]
+]
 ```
 ```
 % pandoc -t native
 Foo. bar baz h.k. and e.g. and Mr. Brown.
 ^D
-[Para [Str "Foo.",Space,Str "bar",Space,Str "baz",Space,Str "h.k.",Space,Str "and",Space,Str "e.g.\160and",Space,Str "Mr.\160Brown."]]
+[ Para
+    [ Str "Foo."
+    , Space
+    , Str "bar"
+    , Space
+    , Str "baz"
+    , Space
+    , Str "h.k."
+    , Space
+    , Str "and"
+    , Space
+    , Str "e.g.\160and"
+    , Space
+    , Str "Mr.\160Brown."
+    ]
+]
 ```
diff --git a/test/command/2606.md b/test/command/2606.md
--- a/test/command/2606.md
+++ b/test/command/2606.md
@@ -6,7 +6,7 @@
 ^D
 <table>
 <tbody>
-<tr class="odd">
+<tr>
 <td><p>* hello</p></td>
 </tr>
 </tbody>
@@ -22,7 +22,7 @@
 ^D
 <table>
 <tbody>
-<tr class="odd">
+<tr>
 <td><ul>
 <li>hello</li>
 </ul></td>
@@ -40,7 +40,7 @@
 ^D
 <table>
 <tbody>
-<tr class="odd">
+<tr>
 <td><p><code>* hello</code></p></td>
 </tr>
 </tbody>
diff --git a/test/command/262.md b/test/command/262.md
--- a/test/command/262.md
+++ b/test/command/262.md
@@ -5,7 +5,8 @@
 .. _hello:
 .. _goodbye: example.com
 ^D
-<p><a href="example.com">hello</a> and <a href="example.com">goodbye</a></p>
+<p><a href="example.com">hello</a> and <a
+href="example.com">goodbye</a></p>
 ```
 
 ```
diff --git a/test/command/2649.md b/test/command/2649.md
--- a/test/command/2649.md
+++ b/test/command/2649.md
@@ -7,7 +7,7 @@
 ^D
 <table>
 <tbody>
-<tr class="odd">
+<tr>
 </tr>
 </tbody>
 </table>
@@ -17,7 +17,7 @@
 % pandoc -f mediawiki -t html5
 {| border="4" cellspacing="2" cellpadding="0" WIDTH="100%"
 |-----
-| peildatum Simbase || november 2005 || '''uitslagen Flohrgambiet''' ||
+| peildatum Simbase || november 2005 || colspan=2 | '''uitslagen Flohrgambiet'''
 |-----
 | totaal aantal partijen Simbase || 7.316.773
 | wit wint || 53%
@@ -31,25 +31,24 @@
 ^D
 <table>
 <tbody>
-<tr class="odd">
+<tr>
 <td><p>peildatum Simbase</p></td>
 <td><p>november 2005</p></td>
-<td><p><strong>uitslagen Flohrgambiet</strong></p></td>
-<td></td>
+<td colspan="2"><p><strong>uitslagen Flohrgambiet</strong></p></td>
 </tr>
-<tr class="even">
+<tr>
 <td><p>totaal aantal partijen Simbase</p></td>
 <td><p>7.316.773</p></td>
 <td><p>wit wint</p></td>
 <td><p>53%</p></td>
 </tr>
-<tr class="odd">
+<tr>
 <td><p>percentage (en partijen) Flohrgambiet</p></td>
 <td><p>0.023 % (1.699)</p></td>
 <td><p>zwart wint</p></td>
 <td><p>27%</p></td>
 </tr>
-<tr class="even">
+<tr>
 <td><p>percentage Flohrgambiet in aug 2003</p></td>
 <td><p>0.035 %</p></td>
 <td><p>remise</p></td>
@@ -67,7 +66,8 @@
 ! Aantal
 |-
 | 1
-|align=left| {{FR-VLAG}} [[Sébastien Loeb]] | 78
+|align=left| {{FR-VLAG}} [[Sébastien Loeb]]
+| 78
 |-
 | 2
 |align=left| {{FR-VLAG}} '''[[Sébastien Ogier]]'''
@@ -79,26 +79,31 @@
 |}
 ^D
 <table>
-<tbody>
-<tr class="odd">
-<td></td>
-<td><p>Plaats</p></td>
-<td><p>Rijder</p></td>
-<td><p>Aantal</p></td>
+<thead>
+<tr>
+<th><p>Plaats</p></th>
+<th><p>Rijder</p></th>
+<th><p>Aantal</p></th>
 </tr>
-<tr class="even">
+</thead>
+<tbody>
+<tr>
 <td><p>1</p></td>
-<td><p><a href="Sébastien_Loeb" title="wikilink">Sébastien Loeb</a></p></td>
+<td style="text-align: left;"><p><a href="Sébastien_Loeb"
+class="wikilink" title="Sébastien Loeb">Sébastien Loeb</a></p></td>
 <td><p>78</p></td>
 </tr>
-<tr class="odd">
+<tr>
 <td><p>2</p></td>
-<td><p><strong><a href="Sébastien_Ogier" title="wikilink">Sébastien Ogier</a></strong></p></td>
+<td style="text-align: left;"><p><strong><a href="Sébastien_Ogier"
+class="wikilink" title="Sébastien Ogier">Sébastien
+Ogier</a></strong></p></td>
 <td><p>38</p></td>
 </tr>
-<tr class="even">
+<tr>
 <td><p>10</p></td>
-<td><p><a href="Hannu_Mikkola" title="wikilink">Hannu Mikkola</a></p></td>
+<td style="text-align: left;"><p><a href="Hannu_Mikkola"
+class="wikilink" title="Hannu Mikkola">Hannu Mikkola</a></p></td>
 <td><p>18</p></td>
 </tr>
 </tbody>
diff --git a/test/command/2662.md b/test/command/2662.md
--- a/test/command/2662.md
+++ b/test/command/2662.md
@@ -7,5 +7,5 @@
    :scale: 300 %
    :alt: alternate text
 ^D
-<p><img src="http://url.to.image/foo.png" alt="alternate text" class="align-left" width="600" height="300" /></p>
+<p><img src="http://url.to.image/foo.png" class="align-left" width="600" height="300" alt="alternate text" /></p>
 ```
diff --git a/test/command/2834.md b/test/command/2834.md
--- a/test/command/2834.md
+++ b/test/command/2834.md
@@ -19,11 +19,11 @@
   </tr>
 </table>
 ^D
-+-----------------------------------------------------------------------+
-| +------------------------------------------------------------------+  |
-| |   -----------                                                    |  |
-| |   some text                                                      |  |
-| |   -----------                                                    |  |
-| +------------------------------------------------------------------+  |
-+-----------------------------------------------------------------------+
++---------------------------------------------------------------------------+
+| +-----------------------------------------------------------------------+ |
+| |   -----------                                                         | |
+| |   some text                                                           | |
+| |   -----------                                                         | |
+| +-----------------------------------------------------------------------+ |
++---------------------------------------------------------------------------+
 ```
diff --git a/test/command/2874.md b/test/command/2874.md
--- a/test/command/2874.md
+++ b/test/command/2874.md
@@ -3,12 +3,12 @@
 <a></a>
 <br/>
 ^D
-{}~\\
+{}\strut \\
 ```
 
 ```
 % pandoc -f html -t latex
 <a name="foo"></a><br/>
 ^D
-\protect\hypertarget{foo}{}{}~\\
+\protect\phantomsection\label{foo}{}\strut \\
 ```
diff --git a/test/command/3113.md b/test/command/3113.md
--- a/test/command/3113.md
+++ b/test/command/3113.md
@@ -8,6 +8,11 @@
 E&=&F
 \end{eqnarray}
 ^D
-[Para [Math DisplayMath "\\begin{aligned}\nA&=&B,\\\\\nC&=&D,\\\\\n%\\end{eqnarray}\n%\\begin{eqnarray}\nE&=&F\\end{aligned}"]]
+[ Para
+    [ Math
+        DisplayMath
+        "\\begin{eqnarray}\nA&=&B,\\\\\nC&=&D,\\\\\n%\\end{eqnarray}\n%\\begin{eqnarray}\nE&=&F\n\\end{eqnarray}"
+    ]
+]
 ```
 
diff --git a/test/command/3123.md b/test/command/3123.md
new file mode 100644
--- /dev/null
+++ b/test/command/3123.md
@@ -0,0 +1,17 @@
+```
+% pandoc -f markdown -t native
+<?php echo "1" ; ?>
+^D
+[ RawBlock (Format "html") "<?php echo \"1\" ; ?>" ]
+```
+
+```
+% pandoc -f markdown -t native
+a<?php echo "1" ; ?>
+^D
+[ Para
+    [ Str "a"
+    , RawInline (Format "html") "<?php echo \"1\" ; ?>"
+    ]
+]
+```
diff --git a/test/command/3236.md b/test/command/3236.md
--- a/test/command/3236.md
+++ b/test/command/3236.md
@@ -1,9 +1,21 @@
 ```
-pandoc -f latex -t native
+% pandoc -f latex -t native
 \newcommand{\mycolor}{red}
 
 \includegraphics[width=17cm]{\mycolor /header}
 Magnificent \mycolor{} header.
 ^D
-[Para [Image ("",[],[("width","17cm")]) [Str "image"] ("red/header",""),SoftBreak,Str "Magnificent",Space,Str "red",Space,Str "header."]]
+[ Para
+    [ Image
+        ( "" , [] , [ ( "width" , "17cm" ) ] )
+        [ Str "image" ]
+        ( "red/header" , "" )
+    , SoftBreak
+    , Str "Magnificent"
+    , Space
+    , Str "red"
+    , Space
+    , Str "header."
+    ]
+]
 ```
diff --git a/test/command/3257.md b/test/command/3257.md
--- a/test/command/3257.md
+++ b/test/command/3257.md
@@ -2,12 +2,12 @@
 % pandoc -t native
 (i<j)
 ^D
-[Para [Str "(i<j)"]]
+[ Para [ Str "(i<j)" ] ]
 ```
 
 ```
 % pandoc -t native
 i<j-1, j>k
 ^D
-[Para [Str "i<j-1,",Space,Str "j>k"]]
+[ Para [ Str "i<j-1," , Space , Str "j>k" ] ]
 ```
diff --git a/test/command/3314.md b/test/command/3314.md
--- a/test/command/3314.md
+++ b/test/command/3314.md
@@ -18,12 +18,12 @@
 <col style="width: 15%" />
 </colgroup>
 <tbody>
-<tr class="odd">
+<tr>
 <td>First</td>
 <td>12.0</td>
 <td>Example row spanning lines</td>
 </tr>
-<tr class="even">
+<tr>
 <td>Second</td>
 <td>5.0</td>
 <td>Another</td>
diff --git a/test/command/3324.md b/test/command/3324.md
new file mode 100644
--- /dev/null
+++ b/test/command/3324.md
@@ -0,0 +1,18 @@
+```
+% pandoc -t latex
+Signatures
+
+\
+\
+___________________________\
+Peter Foobar\
+*The Foo Company*
+^D
+Signatures
+
+\hfill\break
+\hfill\break
+\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\\
+Peter Foobar\\
+\emph{The Foo Company}
+```
diff --git a/test/command/3348.md b/test/command/3348.md
--- a/test/command/3348.md
+++ b/test/command/3348.md
@@ -7,11 +7,64 @@
         line of text
   ----- ------------------------------------------------
 ^D
-[Table [] [AlignRight,AlignLeft] [8.333333333333333e-2,0.6666666666666666]
- [[]
- ,[]]
- [[[Plain [Str "foo"]]
-  ,[Plain [Str "bar"]]]
- ,[[Plain [Str "foo"]]
-  ,[Plain [Str "this",Space,Str "is",Space,Str "a",Space,Str "long",SoftBreak,Str "line",Space,Str "of",Space,Str "text"]]]]]
+[ Table
+    ( "" , [] , [] )
+    (Caption Nothing [])
+    [ ( AlignRight , ColWidth 8.333333333333333e-2 )
+    , ( AlignLeft , ColWidth 0.6805555555555556 )
+    ]
+    (TableHead ( "" , [] , [] ) [])
+    [ TableBody
+        ( "" , [] , [] )
+        (RowHeadColumns 0)
+        []
+        [ Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "foo" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "bar" ] ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "foo" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain
+                    [ Str "this"
+                    , Space
+                    , Str "is"
+                    , Space
+                    , Str "a"
+                    , Space
+                    , Str "long"
+                    , SoftBreak
+                    , Str "line"
+                    , Space
+                    , Str "of"
+                    , Space
+                    , Str "text"
+                    ]
+                ]
+            ]
+        ]
+    ]
+    (TableFoot ( "" , [] , [] ) [])
+]
 ```
diff --git a/test/command/3401.md b/test/command/3401.md
--- a/test/command/3401.md
+++ b/test/command/3401.md
@@ -5,7 +5,7 @@
 #+MACRO: HELLO /Hello, $1/
 {{{HELLO(World)}}}
 ^D
-[Para [Emph [Str "Hello,",Space,Str "World"]]]
+[ Para [ Emph [ Str "Hello," , Space , Str "World" ] ] ]
 ```
 
 Inverted argument order
@@ -15,5 +15,5 @@
 #+MACRO: A $2,$1
 {{{A(1,2)}}}
 ^D
-[Para [Str "2,1"]]
+[ Para [ Str "2,1" ] ]
 ```
diff --git a/test/command/3407.md b/test/command/3407.md
--- a/test/command/3407.md
+++ b/test/command/3407.md
@@ -1,6 +1,6 @@
 ```
 % pandoc -f native -t rst
-[Para [Span ("",[],[("role","foo")]) [Str "text"]]]
+[Para [Code ("",["interpreted-text"],[("role","foo")]) "text"]]
 ^D
 :foo:`text`
 ```
@@ -9,5 +9,10 @@
 % pandoc -f rst -t native
 :foo:`text`
 ^D
-[Para [Span ("",[],[("role","foo")]) [Str "text"]]]
+[ Para
+    [ Code
+        ( "" , [ "interpreted-text" ] , [ ( "role" , "foo" ) ] )
+        "text"
+    ]
+]
 ```
diff --git a/test/command/3422.md b/test/command/3422.md
--- a/test/command/3422.md
+++ b/test/command/3422.md
@@ -1,7 +1,7 @@
 See #3422
 
 ```
-% pandoc -t latex --listings
+% pandoc -t latex --syntax-highlighting=idiomatic
 `int main(int argc, const char *argv[]);`{.c}
 ^D
 \passthrough{\lstinline[language=C]!int main(int argc, const char *argv[]);!}
diff --git a/test/command/3432.md b/test/command/3432.md
--- a/test/command/3432.md
+++ b/test/command/3432.md
@@ -28,24 +28,24 @@
 <col style="width: 54%" />
 </colgroup>
 <thead>
-<tr class="header">
+<tr>
 <th>Treat</th>
 <th>Quantity</th>
 <th>Description</th>
 </tr>
 </thead>
 <tbody>
-<tr class="odd">
+<tr>
 <td>Albatross</td>
 <td>2.99</td>
 <td>On a stick!</td>
 </tr>
-<tr class="even">
+<tr>
 <td>Crunchy Frog</td>
 <td>1.49</td>
 <td>If we took the bones out, it wouldn't be crunchy, now would it?</td>
 </tr>
-<tr class="odd">
+<tr>
 <td>Gannet Ripple</td>
 <td>1.99</td>
 <td>On a stick!</td>
@@ -79,24 +79,24 @@
 <table>
 <caption>Frozen Delights!</caption>
 <thead>
-<tr class="header">
+<tr>
 <th>Treat</th>
 <th>Quantity</th>
 <th>Description</th>
 </tr>
 </thead>
 <tbody>
-<tr class="odd">
+<tr>
 <td>Albatross</td>
 <td>2.99</td>
 <td>On a stick!</td>
 </tr>
-<tr class="even">
+<tr>
 <td>Crunchy Frog</td>
 <td>1.49</td>
 <td>If we took the bones out, it wouldn't be crunchy, now would it?</td>
 </tr>
-<tr class="odd">
+<tr>
 <td>Gannet Ripple</td>
 <td>1.99</td>
 <td>On a stick!</td>
@@ -130,24 +130,24 @@
 <table>
 <caption>Frozen Delights!</caption>
 <thead>
-<tr class="header">
+<tr>
 <th>Treat</th>
 <th>Quantity</th>
 <th>Description</th>
 </tr>
 </thead>
 <tbody>
-<tr class="odd">
+<tr>
 <td>Albatross</td>
 <td>2.99</td>
 <td>On a stick!</td>
 </tr>
-<tr class="even">
+<tr>
 <td>Crunchy Frog</td>
 <td>1.49</td>
 <td>If we took the bones out, it wouldn't be crunchy, now would it?</td>
 </tr>
-<tr class="odd">
+<tr>
 <td>Gannet Ripple</td>
 <td>1.99</td>
 <td>On a stick!</td>
@@ -176,17 +176,17 @@
 <table>
 <caption>Frozen Delights!</caption>
 <tbody>
-<tr class="odd">
+<tr>
 <td>Albatross</td>
 <td>2.99</td>
 <td>On a stick!</td>
 </tr>
-<tr class="even">
+<tr>
 <td>Crunchy Frog</td>
 <td>1.49</td>
 <td>If we took the bones out, it wouldn't be crunchy, now would it?</td>
 </tr>
-<tr class="odd">
+<tr>
 <td>Gannet Ripple</td>
 <td>1.99</td>
 <td>On a stick!</td>
@@ -195,7 +195,7 @@
 </table>
 ```
 
-List-table with empty cells. You need a space after '-', otherwise the row will disapear. Parser for Bulletlists causes this ristriction. 
+List-table with empty cells. You need a space after '-', otherwise the row will disappear. Parser for Bulletlists causes this restriction. 
 
 ```
 % pandoc -f rst
@@ -219,24 +219,24 @@
 <table>
 <caption>Frozen Delights!</caption>
 <thead>
-<tr class="header">
+<tr>
 <th>Treat</th>
 <th>Quantity</th>
 <th>Description</th>
 </tr>
 </thead>
 <tbody>
-<tr class="odd">
+<tr>
 <td>Albatross</td>
 <td>2.99</td>
 <td></td>
 </tr>
-<tr class="even">
+<tr>
 <td>Crunchy Frog</td>
 <td></td>
 <td>If we took the bones out, it wouldn't be crunchy, now would it?</td>
 </tr>
-<tr class="odd">
+<tr>
 <td>Gannet Ripple</td>
 <td>1.99</td>
 <td>On a stick!</td>
@@ -266,7 +266,7 @@
 <table>
 <caption>Frozen Delights!</caption>
 <tbody>
-<tr class="odd">
+<tr>
 <td>Albatross</td>
 <td>2.99</td>
 <td><ul>
@@ -274,12 +274,12 @@
 <li>In a cup!</li>
 </ul></td>
 </tr>
-<tr class="even">
+<tr>
 <td>Crunchy Frog</td>
 <td>1.49</td>
 <td>If we took the bones out, it wouldn't be crunchy, now would it?</td>
 </tr>
-<tr class="odd">
+<tr>
 <td>Gannet Ripple</td>
 <td>1.99</td>
 <td>On a stick!</td>
diff --git a/test/command/3450.md b/test/command/3450.md
--- a/test/command/3450.md
+++ b/test/command/3450.md
@@ -2,11 +2,11 @@
 % pandoc -fmarkdown-implicit_figures
 ![image](lalune.jpg){height=2em}
 ^D
-<p><img src="lalune.jpg" alt="image" style="height:2em" /></p>
+<p><img src="lalune.jpg" style="height:2em" alt="image" /></p>
 ```
 ```
 % pandoc -fmarkdown-implicit_figures -t latex
 ![image](lalune.jpg){height=2em}
 ^D
-\includegraphics[width=\textwidth,height=2em]{lalune.jpg}
+\includegraphics[width=\linewidth,height=2em,keepaspectratio,alt={image}]{lalune.jpg}
 ```
diff --git a/test/command/3475.md b/test/command/3475.md
--- a/test/command/3475.md
+++ b/test/command/3475.md
@@ -1,7 +1,7 @@
 RST implicit internal links to headers:
 
 ```
-pandoc -f rst
+% pandoc -f rst
 Years
 -----
 
@@ -12,7 +12,7 @@
 ```
 
 ```
-pandoc -f rst
+% pandoc -f rst
 Years_
 
 Years
@@ -23,7 +23,7 @@
 ```
 
 ```
-pandoc -f rst
+% pandoc -f rst
 Years and years
 ---------------
 
@@ -34,7 +34,7 @@
 ```
 
 ```
-pandoc -f rst
+% pandoc -f rst
 Years and *years*
 -----------------
 
diff --git a/test/command/3487.md b/test/command/3487.md
--- a/test/command/3487.md
+++ b/test/command/3487.md
@@ -7,5 +7,5 @@
 ^D
 Some text
 
--   element
+- element
 ```
diff --git a/test/command/3494.md b/test/command/3494.md
--- a/test/command/3494.md
+++ b/test/command/3494.md
@@ -14,22 +14,22 @@
 ^D
 <table>
 <tbody>
-<tr class="odd">
+<tr>
 <td style="text-align: right;"><span><strong>ﺍ</strong></span></td>
 <td style="text-align: left;"></td>
 <td style="text-align: left;"></td>
 </tr>
-<tr class="even">
+<tr>
 <td style="text-align: right;"><strong>ﺄﺤﺴﻨﺘـ(ﻭﺍ) IV</strong></td>
 <td style="text-align: left;"><em><span>ʾaḥsant(ū)</span></em></td>
 <td style="text-align: left;">thank you</td>
 </tr>
-<tr class="odd">
-<td style="text-align: right;"><p><em>blah</em></p></td>
+<tr>
+<td style="text-align: right;"><em>blah</em></td>
 <td style="text-align: left;"><em>blah</em></td>
 <td style="text-align: left;"><em>blah</em></td>
 </tr>
-<tr class="even">
+<tr>
 <td style="text-align: right;">blah</td>
 <td style="text-align: left;">blah</td>
 <td style="text-align: left;">blah</td>
diff --git a/test/command/3499.md b/test/command/3499.md
--- a/test/command/3499.md
+++ b/test/command/3499.md
@@ -9,7 +9,7 @@
 <li>|something|</li>
 <li><table>
 <tbody>
-<tr class="odd">
+<tr>
 <td>else</td>
 </tr>
 </tbody>
diff --git a/test/command/3510.md b/test/command/3510.md
--- a/test/command/3510.md
+++ b/test/command/3510.md
@@ -10,11 +10,13 @@
 
 More text
 ^D
-[Para [Str "Text"]
-,Header 1 ("subsection",[],[]) [Str "Subsection"]
-,Para [Str "Included",Space,Str "text"]
-,Plain [Str "Lorem",Space,Str "ipsum."]
-,CodeBlock ("",["haskell"],[]) "putStrLn outString\n"
-,RawBlock (Format "latex") "\\emph{Hello}"
-,Para [Str "More",Space,Str "text"]]
+[ Para [ Str "Text" ]
+, Header 1 ( "subsection" , [] , [] ) [ Str "Subsection" ]
+, Para [ Str "Included" , Space , Str "text" ]
+, Plain [ Str "Lorem" , Space , Str "ipsum." ]
+, CodeBlock
+    ( "" , [ "haskell" ] , [] ) "putStrLn outString\n"
+, RawBlock (Format "latex") "\\emph{Hello}"
+, Para [ Str "More" , Space , Str "text" ]
+]
 ```
diff --git a/test/command/3511.md b/test/command/3511.md
--- a/test/command/3511.md
+++ b/test/command/3511.md
@@ -10,16 +10,20 @@
 
     not continuation
 ^D
-[BulletList
- [[Plain [Str "a"]
-  ,BulletList
-   [[Plain [Str "b"]
-    ,BulletList
-     [[Plain [Str "c"]]]]]]
- ,[CodeBlock ("",[],[]) "code"]]
-,OrderedList (1000,Decimal,Period)
- [[Plain [Str "one"]]]
-,CodeBlock ("",[],[]) "not continuation"]
+[ BulletList
+    [ [ Plain [ Str "a" ]
+      , BulletList
+          [ [ Plain [ Str "b" ]
+            , BulletList [ [ Plain [ Str "c" ] ] ]
+            ]
+          ]
+      ]
+    , [ CodeBlock ( "" , [] , [] ) "code" ]
+    ]
+, OrderedList
+    ( 1000 , Decimal , Period ) [ [ Plain [ Str "one" ] ] ]
+, CodeBlock ( "" , [] , [] ) "not continuation"
+]
 ```
 
 ```
@@ -34,13 +38,15 @@
 
     continuation
 ^D
-[BulletList
- [[Plain [Str "a"]]
- ,[Plain [Str "b"]
-  ,BulletList
-   [[Plain [Str "c"]]]]
- ,[CodeBlock ("",[],[]) "not code"]]
-,OrderedList (1000,Decimal,Period)
- [[Para [Str "one"]
-  ,Para [Str "continuation"]]]]
+[ BulletList
+    [ [ Plain [ Str "a" ] ]
+    , [ Plain [ Str "b" ]
+      , BulletList [ [ Plain [ Str "c" ] ] ]
+      ]
+    , [ CodeBlock ( "" , [] , [] ) "not code" ]
+    ]
+, OrderedList
+    ( 1000 , Decimal , Period )
+    [ [ Para [ Str "one" ] , Para [ Str "continuation" ] ] ]
+]
 ```
diff --git a/test/command/3516.md b/test/command/3516.md
--- a/test/command/3516.md
+++ b/test/command/3516.md
@@ -24,26 +24,75 @@
 |   |   |
 +---+---+
 ^D
-[Table [] [AlignDefault,AlignDefault] [5.555555555555555e-2,5.555555555555555e-2]
- [[]
- ,[]]
- [[[Plain [Str "1"]]
-  ,[Plain [Str "2"]]]
- ,[[]
-  ,[]]]]
+[ Table
+    ( "" , [] , [] )
+    (Caption Nothing [])
+    [ ( AlignDefault , ColWidth 5.555555555555555e-2 )
+    , ( AlignDefault , ColWidth 5.555555555555555e-2 )
+    ]
+    (TableHead ( "" , [] , [] ) [])
+    [ TableBody
+        ( "" , [] , [] )
+        (RowHeadColumns 0)
+        []
+        [ Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "1" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "2" ] ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] ) AlignDefault (RowSpan 1) (ColSpan 1) []
+            , Cell
+                ( "" , [] , [] ) AlignDefault (RowSpan 1) (ColSpan 1) []
+            ]
+        ]
+    ]
+    (TableFoot ( "" , [] , [] ) [])
+]
 ```
 
 ```
 % pandoc -f native -t rst
-[Table [] [AlignDefault,AlignDefault] [5.555555555555555e-2,5.555555555555555e-2]
- [[]
- ,[]]
- [[[Para [Str "1"]]
-  ,[Para [Str "2"]]]
- ,[[]
-  ,[]]]]
+[Table ("",[],[]) (Caption Nothing
+ [])
+ [(AlignDefault,ColWidth 5.555555555555555e-2)
+ ,(AlignDefault,ColWidth 5.555555555555555e-2)]
+ (TableHead ("",[],[])
+ [Row ("",[],[])
+  [Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+   []
+  ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+   []]])
+ [(TableBody ("",[],[]) (RowHeadColumns 0)
+  []
+  [Row ("",[],[])
+   [Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Para [Str "1"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Para [Str "2"]]]
+  ,Row ("",[],[])
+   [Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    []
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    []]])]
+ (TableFoot ("",[],[])
+ [])]
 ^D
 +---+---+
+|   |   |
++===+===+
 | 1 | 2 |
 +---+---+
 |   |   |
diff --git a/test/command/3518.md b/test/command/3518.md
--- a/test/command/3518.md
+++ b/test/command/3518.md
@@ -1,5 +1,5 @@
 ```
-pandoc -f latex -t plain
+% pandoc -f latex -t plain
 $\alpha^2 \cdot \alpha^{2+3} \equiv \alpha^7$
 ^D
 α² ⋅ α² ⁺ ³ ≡ α⁷
diff --git a/test/command/3523.md b/test/command/3523.md
new file mode 100644
--- /dev/null
+++ b/test/command/3523.md
@@ -0,0 +1,35 @@
+```
+% pandoc -f latex -t html 
+\documentclass{article}
+\usepackage{epigraph}
+\begin{document}
+
+\epigraph{
+    Das Recht hat kein Dasein f{\"u}r sich, sein Wesen vielmehr ist das Leben des Menschen selbst, von einer besonderen Seite angesehen. 
+    
+    Das Recht hat kein Dasein f{\"u}r sich, sein Wesen vielmehr ist das Leben des Menschen selbst, von einer besonderen Seite angesehen.
+    
+    \begin{itemize}
+        \item hey
+        \item hey
+        \item hey
+    \end{itemize}
+    
+    }{ Friedrich Carl von Savigny }
+\end{document}
+^D
+<div class="epigraph">
+<p>Das Recht hat kein Dasein f<span>ü</span>r sich, sein Wesen vielmehr
+ist das Leben des Menschen selbst, von einer besonderen Seite
+angesehen.</p>
+<p>Das Recht hat kein Dasein f<span>ü</span>r sich, sein Wesen vielmehr
+ist das Leben des Menschen selbst, von einer besonderen Seite
+angesehen.</p>
+<ul>
+<li><p>hey</p></li>
+<li><p>hey</p></li>
+<li><p>hey</p></li>
+</ul>
+<p>Friedrich Carl von Savigny</p>
+</div>
+```
diff --git a/test/command/3530.md b/test/command/3530.md
--- a/test/command/3530.md
+++ b/test/command/3530.md
@@ -3,10 +3,55 @@
 \subfile{command/sub-file-chapter-1}
 \subfile{command/sub-file-chapter-2}
 ^D
-[Header 1 ("chapter-1",[],[]) [Str "Chapter",Space,Str "1"]
-,Para [Str "This",Space,Str "is",Space,Str "Chapter",Space,Str "1,",Space,Str "provided",Space,Str "in",Space,Str "a",Space,Str "sub",Space,Str "file."]
-,Header 1 ("chapter-2",[],[]) [Str "Chapter",Space,Str "2"]
-,Para [Str "This",Space,Str "is",Space,Str "Chapter",Space,Str "2,",Space,Str "provided",Space,Str "in",Space,Str "a",Space,Str "second",Space,Str "sub",Space,Str "file."]]
+[ Header
+    1
+    ( "chapter-1" , [] , [] )
+    [ Str "Chapter" , Space , Str "1" ]
+, Para
+    [ Str "This"
+    , Space
+    , Str "is"
+    , Space
+    , Str "Chapter"
+    , Space
+    , Str "1,"
+    , Space
+    , Str "provided"
+    , Space
+    , Str "in"
+    , Space
+    , Str "a"
+    , Space
+    , Str "sub"
+    , Space
+    , Str "file."
+    ]
+, Header
+    1
+    ( "chapter-2" , [] , [] )
+    [ Str "Chapter" , Space , Str "2" ]
+, Para
+    [ Str "This"
+    , Space
+    , Str "is"
+    , Space
+    , Str "Chapter"
+    , Space
+    , Str "2,"
+    , Space
+    , Str "provided"
+    , Space
+    , Str "in"
+    , Space
+    , Str "a"
+    , Space
+    , Str "second"
+    , Space
+    , Str "sub"
+    , Space
+    , Str "file."
+    ]
+]
 ```
 
 ```
@@ -14,9 +59,9 @@
 \subfile{command/sub-file-chapter-1}
 \subfile{command/sub-file-chapter-2}
 ^D
-[Header 1 ("chapter-1",[],[]) [Str "Chapter",Space,Str "1"]
-,Para [Str "This",Space,Str "is",Space,Str "Chapter",Space,Str "1,",Space,Str "provided",Space,Str "in",Space,Str "a",Space,Str "sub",Space,Str "file."]
-,Header 1 ("chapter-2",[],[]) [Str "Chapter",Space,Str "2"]
-,Para [Str "This",Space,Str "is",Space,Str "Chapter",Space,Str "2,",Space,Str "provided",Space,Str "in",Space,Str "a",Space,Str "second",Space,Str "sub",Space,Str "file."]]
-
+[ RawBlock
+    (Format "latex") "\\subfile{command/sub-file-chapter-1}"
+, RawBlock
+    (Format "latex") "\\subfile{command/sub-file-chapter-2}"
+]
 ```
diff --git a/test/command/3531.md b/test/command/3531.md
--- a/test/command/3531.md
+++ b/test/command/3531.md
@@ -17,5 +17,4 @@
 A paragraph can span multiple lines
 without being broken into pieces.
 
-
 ```
diff --git a/test/command/3533-rst-csv-tables.md b/test/command/3533-rst-csv-tables.md
--- a/test/command/3533-rst-csv-tables.md
+++ b/test/command/3533-rst-csv-tables.md
@@ -5,16 +5,121 @@
    :header: Flavor,Price,Slogan
    :file: command/3533-rst-csv-tables.csv
 ^D
-[Table [Str "Test"] [AlignDefault,AlignDefault,AlignDefault] [0.4,0.2,0.4]
- [[Plain [Str "Flavor"]]
- ,[Plain [Str "Price"]]
- ,[Plain [Str "Slogan"]]]
- [[[Plain [Str "Albatross"]]
-  ,[Plain [Str "2.99"]]
-  ,[Plain [Str "On",Space,Str "a",Space,Str "stick!"]]]
- ,[[Plain [Str "Crunchy",Space,Str "Frog"]]
-  ,[Plain [Str "1.49"]]
-  ,[Plain [Str "If",Space,Str "we",Space,Str "took",Space,Str "the",Space,Str "bones",Space,Str "out,",Space,Str "it",Space,Str "wouldn't",Space,Str "be",SoftBreak,Str "crunchy,",Space,Str "now",Space,Str "would",Space,Str "it?"]]]]]
+[ Table
+    ( "" , [] , [] )
+    (Caption Nothing [ Plain [ Str "Test" ] ])
+    [ ( AlignDefault , ColWidth 0.4 )
+    , ( AlignDefault , ColWidth 0.2 )
+    , ( AlignDefault , ColWidth 0.4 )
+    ]
+    (TableHead
+       ( "" , [] , [] )
+       [ Row
+           ( "" , [] , [] )
+           [ Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "Flavor" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "Price" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "Slogan" ] ]
+           ]
+       ])
+    [ TableBody
+        ( "" , [] , [] )
+        (RowHeadColumns 0)
+        []
+        [ Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "Albatross" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "2.99" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain
+                    [ Str "On"
+                    , Space
+                    , Str "a"
+                    , Space
+                    , Str "stick!"
+                    ]
+                ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "Crunchy" , Space , Str "Frog" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "1.49" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain
+                    [ Str "If"
+                    , Space
+                    , Str "we"
+                    , Space
+                    , Str "took"
+                    , Space
+                    , Str "the"
+                    , Space
+                    , Str "bones"
+                    , Space
+                    , Str "out,"
+                    , Space
+                    , Str "it"
+                    , Space
+                    , Str "wouldn't"
+                    , Space
+                    , Str "be"
+                    , SoftBreak
+                    , Str "crunchy,"
+                    , Space
+                    , Str "now"
+                    , Space
+                    , Str "would"
+                    , Space
+                    , Str "it?"
+                    ]
+                ]
+            ]
+        ]
+    ]
+    (TableFoot ( "" , [] , [] ) [])
+]
 ```
 
 ```
@@ -28,16 +133,83 @@
    'cat''s' 3 4
    'dog''s' 2 3
 ^D
-[Table [Str "Test"] [AlignDefault,AlignDefault,AlignDefault] [0.0,0.0,0.0]
- [[]
- ,[Plain [Str "a"]]
- ,[Plain [Str "b"]]]
- [[[Plain [Str "cat's"]]
-  ,[Plain [Str "3"]]
-  ,[Plain [Str "4"]]]
- ,[[Plain [Str "dog's"]]
-  ,[Plain [Str "2"]]
-  ,[Plain [Str "3"]]]]]
+[ Table
+    ( "" , [] , [] )
+    (Caption Nothing [ Plain [ Str "Test" ] ])
+    [ ( AlignDefault , ColWidthDefault )
+    , ( AlignDefault , ColWidthDefault )
+    , ( AlignDefault , ColWidthDefault )
+    ]
+    (TableHead
+       ( "" , [] , [] )
+       [ Row
+           ( "" , [] , [] )
+           [ Cell
+               ( "" , [] , [] ) AlignDefault (RowSpan 1) (ColSpan 1) []
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "a" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "b" ] ]
+           ]
+       ])
+    [ TableBody
+        ( "" , [] , [] )
+        (RowHeadColumns 0)
+        []
+        [ Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "cat's" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "3" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "4" ] ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "dog's" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "2" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "3" ] ]
+            ]
+        ]
+    ]
+    (TableFoot ( "" , [] , [] ) [])
+]
 ```
 
 ```
@@ -47,10 +219,35 @@
 
    "1","\""
 ^D
-[Table [Str "Test"] [AlignDefault,AlignDefault] [0.0,0.0]
- [[]
- ,[]]
- [[[Plain [Str "1"]]
-  ,[Plain [Str "\""]]]]]
+[ Table
+    ( "" , [] , [] )
+    (Caption Nothing [ Plain [ Str "Test" ] ])
+    [ ( AlignDefault , ColWidthDefault )
+    , ( AlignDefault , ColWidthDefault )
+    ]
+    (TableHead ( "" , [] , [] ) [])
+    [ TableBody
+        ( "" , [] , [] )
+        (RowHeadColumns 0)
+        []
+        [ Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "1" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "\"" ] ]
+            ]
+        ]
+    ]
+    (TableFoot ( "" , [] , [] ) [])
+]
 ```
 
diff --git a/test/command/3534.md b/test/command/3534.md
--- a/test/command/3534.md
+++ b/test/command/3534.md
@@ -2,7 +2,8 @@
 % pandoc -f latex -t html
 I want to explain the interface of \lstinline[language=Java]{public class MyClass}.
 ^D
-<p>I want to explain the interface of <code class="sourceCode java"><span class="kw">public</span> <span class="kw">class</span> MyClass</code>.</p>
+<p>I want to explain the interface of <code
+class="sourceCode java"><span class="kw">public</span> <span class="kw">class</span> MyClass</code>.</p>
 
 ```
 
@@ -10,7 +11,8 @@
 % pandoc -f latex -t html
 I want to explain the interface of \lstinline{public class MyClass}.
 ^D
-<p>I want to explain the interface of <code>public class MyClass</code>.</p>
+<p>I want to explain the interface of
+<code>public class MyClass</code>.</p>
 
 ```
 
@@ -18,6 +20,66 @@
 % pandoc -f latex -t native
 I want to explain the interface of \lstinline[language=Java]{public class MyClass}.
 ^D
-[Para [Str "I",Space,Str "want",Space,Str "to",Space,Str "explain",Space,Str "the",Space,Str "interface",Space,Str "of",Space,Code ("",["java"],[]) "public class MyClass",Str "."]]
+[ Para
+    [ Str "I"
+    , Space
+    , Str "want"
+    , Space
+    , Str "to"
+    , Space
+    , Str "explain"
+    , Space
+    , Str "the"
+    , Space
+    , Str "interface"
+    , Space
+    , Str "of"
+    , Space
+    , Code ( "" , [ "java" ] , [] ) "public class MyClass"
+    , Str "."
+    ]
+]
 ```
 
+```
+% pandoc -f latex -t html
+I want to explain the interface of \mintinline{java}{public class MyClass}.
+^D
+<p>I want to explain the interface of <code
+class="sourceCode java"><span class="kw">public</span> <span class="kw">class</span> MyClass</code>.</p>
+
+```
+
+```
+% pandoc -f latex -t html
+I want to explain the interface of \mintinline{java}|public class MyClass|.
+^D
+<p>I want to explain the interface of <code
+class="sourceCode java"><span class="kw">public</span> <span class="kw">class</span> MyClass</code>.</p>
+
+```
+
+```
+% pandoc -f latex -t native
+I want to explain the interface of \mintinline[linenos]{java}{public class MyClass}.
+^D
+[ Para
+    [ Str "I"
+    , Space
+    , Str "want"
+    , Space
+    , Str "to"
+    , Space
+    , Str "explain"
+    , Space
+    , Str "the"
+    , Space
+    , Str "interface"
+    , Space
+    , Str "of"
+    , Space
+    , Code ( "" , [ "java" ] , [] ) "public class MyClass"
+    , Str "."
+    ]
+]
+```
diff --git a/test/command/3537.md b/test/command/3537.md
--- a/test/command/3537.md
+++ b/test/command/3537.md
@@ -7,14 +7,20 @@
 foo bar
 ```
 ^D
-[RawBlock (Format "ms") ".MACRO\nfoo bar"]
+[ RawBlock (Format "ms") ".MACRO\nfoo bar" ]
 ````
 
 ````
 % pandoc -t native
 Hi `there`{=ms}.
 ^D
-[Para [Str "Hi",Space,RawInline (Format "ms") "there",Str "."]]
+[ Para
+    [ Str "Hi"
+    , Space
+    , RawInline (Format "ms") "there"
+    , Str "."
+    ]
+]
 ````
 
 ````
@@ -24,5 +30,5 @@
 foo bar
 ~~~
 ^D
-[RawBlock (Format "ms") ".MACRO\nfoo bar"]
+[ RawBlock (Format "ms") ".MACRO\nfoo bar" ]
 ````
diff --git a/test/command/3539.md b/test/command/3539.md
--- a/test/command/3539.md
+++ b/test/command/3539.md
@@ -4,35 +4,205 @@
 % pandoc -f latex -t native
 Many programming languages provide \glspl{API}. Each \gls{API} should provide a documentation.
 ^D
-[Para [Str "Many",Space,Str "programming",Space,Str "languages",Space,Str "provide",Space,Span ("",[],[("acronym-label","API"),("acronym-form","plural+short")]) [Str "APIs"],Str ".",Space,Str "Each",Space,Span ("",[],[("acronym-label","API"),("acronym-form","singular+short")]) [Str "API"],Space,Str "should",Space,Str "provide",Space,Str "a",Space,Str "documentation."]]
+[ Para
+    [ Str "Many"
+    , Space
+    , Str "programming"
+    , Space
+    , Str "languages"
+    , Space
+    , Str "provide"
+    , Space
+    , Span
+        ( ""
+        , []
+        , [ ( "acronym-label" , "API" )
+          , ( "acronym-form" , "plural+short" )
+          ]
+        )
+        [ Str "APIs" ]
+    , Str "."
+    , Space
+    , Str "Each"
+    , Space
+    , Span
+        ( ""
+        , []
+        , [ ( "acronym-label" , "API" )
+          , ( "acronym-form" , "singular+short" )
+          ]
+        )
+        [ Str "API" ]
+    , Space
+    , Str "should"
+    , Space
+    , Str "provide"
+    , Space
+    , Str "a"
+    , Space
+    , Str "documentation."
+    ]
+]
 ```
 
 ```
 % pandoc -f latex -t native
 \Glsdesc{API} XYZ ist not as performant as \glsdesc{API} ZXY.
 ^D
-[Para [Span ("",[],[("acronym-label","API"),("acronym-form","singular+long")]) [Str "API"],Space,Str "XYZ",Space,Str "ist",Space,Str "not",Space,Str "as",Space,Str "performant",Space,Str "as",Space,Span ("",[],[("acronym-label","API"),("acronym-form","singular+long")]) [Str "API"],Space,Str "ZXY."]]
+[ Para
+    [ Span
+        ( ""
+        , []
+        , [ ( "acronym-label" , "API" )
+          , ( "acronym-form" , "singular+long" )
+          ]
+        )
+        [ Str "API" ]
+    , Space
+    , Str "XYZ"
+    , Space
+    , Str "ist"
+    , Space
+    , Str "not"
+    , Space
+    , Str "as"
+    , Space
+    , Str "performant"
+    , Space
+    , Str "as"
+    , Space
+    , Span
+        ( ""
+        , []
+        , [ ( "acronym-label" , "API" )
+          , ( "acronym-form" , "singular+long" )
+          ]
+        )
+        [ Str "API" ]
+    , Space
+    , Str "ZXY."
+    ]
+]
 ```
 
 ```
 % pandoc -f latex -t native
 \Acrlong{API} XYZ ist not as performant as \acrlong{API} ZXY.
 ^D
-[Para [Span ("",[],[("acronym-label","API"),("acronym-form","singular+long")]) [Str "API"],Space,Str "XYZ",Space,Str "ist",Space,Str "not",Space,Str "as",Space,Str "performant",Space,Str "as",Space,Span ("",[],[("acronym-label","API"),("acronym-form","singular+long")]) [Str "API"],Space,Str "ZXY."]]
+[ Para
+    [ Span
+        ( ""
+        , []
+        , [ ( "acronym-label" , "API" )
+          , ( "acronym-form" , "singular+long" )
+          ]
+        )
+        [ Str "API" ]
+    , Space
+    , Str "XYZ"
+    , Space
+    , Str "ist"
+    , Space
+    , Str "not"
+    , Space
+    , Str "as"
+    , Space
+    , Str "performant"
+    , Space
+    , Str "as"
+    , Space
+    , Span
+        ( ""
+        , []
+        , [ ( "acronym-label" , "API" )
+          , ( "acronym-form" , "singular+long" )
+          ]
+        )
+        [ Str "API" ]
+    , Space
+    , Str "ZXY."
+    ]
+]
 ```
 
 ```
 % pandoc -f latex -t native
 \Acrfull{API} XYZ ist not as performant as \acrfull{API} ZXY.
 ^D
-[Para [Span ("",[],[("acronym-label","API"),("acronym-form","singular+full")]) [Str "API"],Space,Str "XYZ",Space,Str "ist",Space,Str "not",Space,Str "as",Space,Str "performant",Space,Str "as",Space,Span ("",[],[("acronym-label","API"),("acronym-form","singular+full")]) [Str "API"],Space,Str "ZXY."]]
+[ Para
+    [ Span
+        ( ""
+        , []
+        , [ ( "acronym-label" , "API" )
+          , ( "acronym-form" , "singular+full" )
+          ]
+        )
+        [ Str "API" ]
+    , Space
+    , Str "XYZ"
+    , Space
+    , Str "ist"
+    , Space
+    , Str "not"
+    , Space
+    , Str "as"
+    , Space
+    , Str "performant"
+    , Space
+    , Str "as"
+    , Space
+    , Span
+        ( ""
+        , []
+        , [ ( "acronym-label" , "API" )
+          , ( "acronym-form" , "singular+full" )
+          ]
+        )
+        [ Str "API" ]
+    , Space
+    , Str "ZXY."
+    ]
+]
 ```
 
 ```
 % pandoc -f latex -t native
 \Acrshort{API} XYZ ist not as performant as \acrshort{API} ZXY.
 ^D
-[Para [Span ("",[],[("acronym-label","API"),("acronym-form","singular+abbrv")]) [Str "API"],Space,Str "XYZ",Space,Str "ist",Space,Str "not",Space,Str "as",Space,Str "performant",Space,Str "as",Space,Span ("",[],[("acronym-label","API"),("acronym-form","singular+abbrv")]) [Str "API"],Space,Str "ZXY."]]
+[ Para
+    [ Span
+        ( ""
+        , []
+        , [ ( "acronym-label" , "API" )
+          , ( "acronym-form" , "singular+abbrv" )
+          ]
+        )
+        [ Str "API" ]
+    , Space
+    , Str "XYZ"
+    , Space
+    , Str "ist"
+    , Space
+    , Str "not"
+    , Space
+    , Str "as"
+    , Space
+    , Str "performant"
+    , Space
+    , Str "as"
+    , Space
+    , Span
+        ( ""
+        , []
+        , [ ( "acronym-label" , "API" )
+          , ( "acronym-form" , "singular+abbrv" )
+          ]
+        )
+        [ Str "API" ]
+    , Space
+    , Str "ZXY."
+    ]
+]
 ```
 
 # Commands of [acronym package](ftp://ftp.mpi-sb.mpg.de/pub/tex/mirror/ftp.dante.de/pub/tex/macros/latex/contrib/acronym/acronym.pdf)
@@ -41,5 +211,43 @@
 % pandoc -f latex -t native
 Many programming languages provide \acp{API}. Each \ac{API} should provide a documentation.
 ^D
-[Para [Str "Many",Space,Str "programming",Space,Str "languages",Space,Str "provide",Space,Span ("",[],[("acronym-label","API"),("acronym-form","plural+short")]) [Str "APIs"],Str ".",Space,Str "Each",Space,Span ("",[],[("acronym-label","API"),("acronym-form","singular+short")]) [Str "API"],Space,Str "should",Space,Str "provide",Space,Str "a",Space,Str "documentation."]]
+[ Para
+    [ Str "Many"
+    , Space
+    , Str "programming"
+    , Space
+    , Str "languages"
+    , Space
+    , Str "provide"
+    , Space
+    , Span
+        ( ""
+        , []
+        , [ ( "acronym-label" , "API" )
+          , ( "acronym-form" , "plural+short" )
+          ]
+        )
+        [ Str "APIs" ]
+    , Str "."
+    , Space
+    , Str "Each"
+    , Space
+    , Span
+        ( ""
+        , []
+        , [ ( "acronym-label" , "API" )
+          , ( "acronym-form" , "singular+short" )
+          ]
+        )
+        [ Str "API" ]
+    , Space
+    , Str "should"
+    , Space
+    , Str "provide"
+    , Space
+    , Str "a"
+    , Space
+    , Str "documentation."
+    ]
+]
 ```
diff --git a/test/command/3558.md b/test/command/3558.md
--- a/test/command/3558.md
+++ b/test/command/3558.md
@@ -6,7 +6,8 @@
 
 \endmulti
 ^D
-[RawBlock (Format "latex") "\\multi"
-,Para [Str "hello"]
-,RawBlock (Format "latex") "\\endmulti"]
+[ RawBlock (Format "tex") "\\multi"
+, Para [ Str "hello" ]
+, RawBlock (Format "tex") "\\endmulti"
+]
 ```
diff --git a/test/command/3568.md b/test/command/3568.md
--- a/test/command/3568.md
+++ b/test/command/3568.md
@@ -7,9 +7,10 @@
 normal `code` normal.
 ^D
 .PP
-normal \f[I]italic \f[BI]bold in the middle\f[I] only italic\f[] normal.
+normal \f[I]italic \f[BI]bold in the middle\f[I] only italic\f[R]
+normal.
 .PP
-normal \f[B]bold \f[BC]code\f[B] more bold\f[] normal.
+normal \f[B]bold \f[CB]code\f[B] more bold\f[R] normal.
 .PP
-normal \f[C]code\f[] normal.
+normal \f[CR]code\f[R] normal.
 ```
diff --git a/test/command/3577.md b/test/command/3577.md
--- a/test/command/3577.md
+++ b/test/command/3577.md
@@ -15,14 +15,17 @@
     \caption{Subfigure with Subfloat}
 \end{figure}
 ^D
-
+<figure data-latex-placement="ht">
 <figure>
-<img src="img1.jpg" alt="Caption 1" /><figcaption>Caption 1</figcaption>
+<img src="img1.jpg" />
+<figcaption>Caption 1</figcaption>
 </figure>
-
 <figure>
-<img src="img2.jpg" alt="Caption 2" /><figcaption>Caption 2</figcaption>
+<img src="img2.jpg" />
+<figcaption>Caption 2</figcaption>
 </figure>
+<figcaption>Subfigure with Subfloat</figcaption>
+</figure>
 ```
 ```
 % pandoc -f latex -t html5
@@ -31,7 +34,8 @@
     \caption{Caption 3}
 \end{figure}
 ^D
-<figure>
-<img src="img1.jpg" alt="Caption 3" /><figcaption>Caption 3</figcaption>
+<figure data-latex-placement="ht">
+<img src="img1.jpg" />
+<figcaption>Caption 3</figcaption>
 </figure>
 ```
diff --git a/test/command/3585.md b/test/command/3585.md
--- a/test/command/3585.md
+++ b/test/command/3585.md
@@ -4,13 +4,32 @@
 
 Same but bzip2 it and nice it <tt>zfs send tank/storage/data/svn@daily-2014-03-20_00.00.00--2w | nice -15 bzip2 | ssh user@hyper.somewhere.org "> /storage/c-3po/tank-storage-data-svn.dmp.bz2"</tt>
 ^D
-[Para [Quoted DoubleQuote [Str "Hello"]]
-,Para [Str "Same",Space,Str "but",Space,Str "bzip2",Space,Str "it",Space,Str "and",Space,Str "nice",Space,Str "it",Space,Code ("",[],[]) "zfs send tank/storage/data/svn@daily-2014-03-20_00.00.00--2w | nice -15 bzip2 | ssh user@hyper.somewhere.org \"> /storage/c-3po/tank-storage-data-svn.dmp.bz2\""]]
+[ Para [ Quoted DoubleQuote [ Str "Hello" ] ]
+, Para
+    [ Str "Same"
+    , Space
+    , Str "but"
+    , Space
+    , Str "bzip2"
+    , Space
+    , Str "it"
+    , Space
+    , Str "and"
+    , Space
+    , Str "nice"
+    , Space
+    , Str "it"
+    , Space
+    , Code
+        ( "" , [] , [] )
+        "zfs send tank/storage/data/svn@daily-2014-03-20_00.00.00--2w | nice -15 bzip2 | ssh user@hyper.somewhere.org \"> /storage/c-3po/tank-storage-data-svn.dmp.bz2\""
+    ]
+]
 ```
 
 ```
 % pandoc -f mediawiki -t native
 "Hello"
 ^D
-[Para [Str "\"Hello\""]]
+[ Para [ Str "\"Hello\"" ] ]
 ```
diff --git a/test/command/3587.md b/test/command/3587.md
--- a/test/command/3587.md
+++ b/test/command/3587.md
@@ -2,20 +2,204 @@
 % pandoc -f latex -t native
 \SI[round-precision=2]{1}{m} is equal to \SI{1000}{mm}
 ^D
-[Para [Str "1\160m",Space,Str "is",Space,Str "equal",Space,Str "to",Space,Str "1000\160mm"]]
+[ Para
+    [ Str "1\160m"
+    , Space
+    , Str "is"
+    , Space
+    , Str "equal"
+    , Space
+    , Str "to"
+    , Space
+    , Str "1000\160mm"
+    ]
+]
 ```
 
 ```
 % pandoc -f latex -t native
 \SI[round-precision=2]{1}[\$]{} is equal to \SI{0.938094}{\euro}
 ^D
-[Para [Str "$\160\&1",Space,Str "is",Space,Str "equal",Space,Str "to",Space,Str "0.938094\160\8364"]]
+[ Para
+    [ Str "$\160\&1"
+    , Space
+    , Str "is"
+    , Space
+    , Str "equal"
+    , Space
+    , Str "to"
+    , Space
+    , Str "0.938094\160\8364"
+    ]
+]
 ```
 
 
 ```
 % pandoc -f latex -t native
-\SI[round-precision=2]{\{\}}[\{\}]{\{\}}
+\SI{30}{\milli\meter}
 ^D
-[Para [Str "{}\160{}\160{}"]]
+[ Para [ Str "30\160mm" ] ]
 ```
+
+```
+% pandoc -f latex -t native
+\SI{6}{\gram}
+^D
+[ Para [ Str "6\160g" ] ]
+```
+
+```
+% pandoc -f latex -t native
+\SI{25}{\square\meter}
+^D
+[ Para [ Str "25\160m" , Superscript [ Str "2" ] ] ]
+```
+
+```
+% pandoc -f latex -t native
+\SI{18.2}{\degreeCelsius}
+^D
+[ Para [ Str "18.2\160\176C" ] ]
+```
+
+```
+% pandoc -f latex -t native
+\SI{18.2}{\celsius}
+^D
+[ Para [ Str "18.2\160\176C" ] ]
+```
+
+# SIrange tests
+
+## Integer range with simple common units
+
+```
+% pandoc -f latex -t native
+\SIrange{10}{20}{\gram}
+^D
+[ Para [ Str "10\160g\8211\&20\160g" ] ]
+```
+```
+% pandoc -f latex -t native
+\SIrange{35}{9}{\milli\meter}
+^D
+[ Para [ Str "35\160mm\8211\&9\160mm" ] ]
+```
+```
+% pandoc -f latex -t native
+\SIrange{4}{97367265}{\celsius}
+^D
+[ Para [ Str "4\160\176C\8211\&97367265\160\176C" ] ]
+```
+
+## Decimal range with simple units
+
+```
+% pandoc -f latex -t native
+\SIrange{4.5}{97367265.5}{\celsius}
+^D
+[ Para [ Str "4.5\160\176C\8211\&97367265.5\160\176C" ] ]
+```
+
+## Squared, cubed etc. units
+
+```
+% pandoc -f latex -t native
+\SIrange{10}{20}{\square\meter}
+^D
+[ Para
+    [ Str "10\160m"
+    , Superscript [ Str "2" ]
+    , Str "\8211\&20\160m"
+    , Superscript [ Str "2" ]
+    ]
+]
+```
+
+```
+% pandoc -f latex -t native
+\SIrange{10}{20}{\cubic\meter}
+^D
+[ Para
+    [ Str "10\160m"
+    , Superscript [ Str "3" ]
+    , Str "\8211\&20\160m"
+    , Superscript [ Str "3" ]
+    ]
+]
+```
+
+```
+% pandoc -f latex -t native
+\SIrange{10}{20}{\raisetothe{4}\meter}
+^D
+[ Para
+    [ Str "10\160m"
+    , Superscript [ Str "4" ]
+    , Str "\8211\&20\160m"
+    , Superscript [ Str "4" ]
+    ]
+]
+```
+
+
+```
+% pandoc -f latex -t native
+\SIrange{10}{20}{\meter\squared}
+^D
+[ Para
+    [ Str "10\160m"
+    , Superscript [ Str "2" ]
+    , Str "\8211\&20\160m"
+    , Superscript [ Str "2" ]
+    ]
+]
+```
+
+```
+% pandoc -f latex -t native
+\SIrange{10}{20}{\meter\cubed}
+^D
+[ Para
+    [ Str "10\160m"
+    , Superscript [ Str "3" ]
+    , Str "\8211\&20\160m"
+    , Superscript [ Str "3" ]
+    ]
+]
+```
+
+```
+% pandoc -f latex -t native
+\SIrange{10}{20}{\meter\tothe{4}}
+^D
+[ Para
+    [ Str "10\160m"
+    , Superscript [ Str "4" ]
+    , Str "\8211\&20\160m"
+    , Superscript [ Str "4" ]
+    ]
+]
+```
+
+
+
+## Ignore round precision
+
+`round-precision` option appears to be ignored by `\SI` as of 7c6dbd37e, so
+`\SIrange` will ignore it as well.
+
+```
+% pandoc -f latex -t native
+\SIrange[round-precision=2]{10}{20}{\gram}
+^D
+[ Para [ Str "10\160g\8211\&20\160g" ] ]
+```
+```
+% pandoc -f latex -t native
+\SIrange[round-precision=2]{10.0}{20.25}{\gram}
+^D
+[ Para [ Str "10.0\160g\8211\&20.25\160g" ] ]
+```
+
diff --git a/test/command/3596.md b/test/command/3596.md
--- a/test/command/3596.md
+++ b/test/command/3596.md
@@ -6,9 +6,9 @@
 <li>baz</li>
 </ul>
 ^D
--   foo
--   bar
--   baz
+- foo
+- bar
+- baz
 ```
 
 ```
@@ -19,10 +19,10 @@
 <li>baz</li>
 </ul>
 ^D
--   foo
--   bar
-    -   subbar
--   baz
+- foo
+- bar
+  - subbar
+- baz
 ```
 
 
@@ -34,9 +34,9 @@
 <li>baz</li>
 </ul>
 ^D
--   foo
--   [bar]{#id}
--   baz
+- foo
+- [bar]{#id}
+- baz
 ```
 
 
@@ -48,12 +48,12 @@
 <li><p>baz</p></li>
 </ul>
 ^D
--   foo
+- foo
 
--   ::: {#id}
-    bar
-    :::
+- ::: {#id}
+  bar
+  :::
 
--   baz
+- baz
 
 ```
diff --git a/test/command/3667.md b/test/command/3667.md
--- a/test/command/3667.md
+++ b/test/command/3667.md
@@ -4,7 +4,7 @@
 ^D
 <table>
 <tbody>
-<tr class="odd">
+<tr>
 <td><a href="http://example.com/">link text</a></td>
 </tr>
 </tbody>
diff --git a/test/command/3674.md b/test/command/3674.md
--- a/test/command/3674.md
+++ b/test/command/3674.md
@@ -2,7 +2,7 @@
 `--reference-location=section`.
 
 ```
-% pandoc --reference-links -t markdown --reference-location=section --atx-headers
+% pandoc --reference-links -t markdown --reference-location=section
 # a
 
 ![](a)
diff --git a/test/command/3675.md b/test/command/3675.md
--- a/test/command/3675.md
+++ b/test/command/3675.md
@@ -7,9 +7,9 @@
 ^D
 .. code:: python
 
-    print("hello")
+   print("hello")
 
 ..
 
-    block quote
+   block quote
 ````
diff --git a/test/command/3681.md b/test/command/3681.md
--- a/test/command/3681.md
+++ b/test/command/3681.md
@@ -4,7 +4,34 @@
 
 Software developers create \cicd pipelines to… Following issue can be resolved by \cicd:
 ^D
-[Para [Str "Software",Space,Str "developers",Space,Str "create",Space,Str "CI/CD",Space,Str "pipelines",Space,Str "to\8230",Space,Str "Following",Space,Str "issue",Space,Str "can",Space,Str "be",Space,Str "resolved",Space,Str "by",Space,Str "CI/CD:"]]
+[ Para
+    [ Str "Software"
+    , Space
+    , Str "developers"
+    , Space
+    , Str "create"
+    , Space
+    , Str "CI/CD"
+    , Space
+    , Str "pipelines"
+    , Space
+    , Str "to\8230"
+    , Space
+    , Str "Following"
+    , Space
+    , Str "issue"
+    , Space
+    , Str "can"
+    , Space
+    , Str "be"
+    , Space
+    , Str "resolved"
+    , Space
+    , Str "by"
+    , Space
+    , Str "CI/CD:"
+    ]
+]
 ```
 
 ```
@@ -13,7 +40,22 @@
 
 \cicd\footnote{\url{https://en.wikipedia.org/wiki/CI/CD}} is awesome.
 ^D
-[Para [Str "CI/CD",Note [Para [Link ("",[],[]) [Str "https://en.wikipedia.org/wiki/CI/CD"] ("https://en.wikipedia.org/wiki/CI/CD","")]],Space,Str "is",Space,Str "awesome."]]
+[ Para
+    [ Str "CI/CD"
+    , Note
+        [ Para
+            [ Link
+                ( "" , [ "uri" ] , [] )
+                [ Str "https://en.wikipedia.org/wiki/CI/CD" ]
+                ( "https://en.wikipedia.org/wiki/CI/CD" , "" )
+            ]
+        ]
+    , Space
+    , Str "is"
+    , Space
+    , Str "awesome."
+    ]
+]
 ```
 
 ```
@@ -23,5 +65,5 @@
 
 \cicd\pipeline.
 ^D
-[Para [Str "CI/CD",Space,Str "pipeline."]]
+[ Para [ Str "CI/CD" , Space , Str "pipeline." ] ]
 ```
diff --git a/test/command/3701.md b/test/command/3701.md
--- a/test/command/3701.md
+++ b/test/command/3701.md
@@ -55,6 +55,7 @@
 ^D
 <p><a href="u">a</a></p>
 <p><a href="u">a</a></p>
-<p><a href="u2">a</a> <a href="u">A</a> <a href="u" class="foo">a</a></p>
+<p><a href="u2">a</a> <a href="u">A</a> <a href="u"
+class="foo">a</a></p>
 <p><a href="u3">a</a></p>
 ```
diff --git a/test/command/3706.md b/test/command/3706.md
--- a/test/command/3706.md
+++ b/test/command/3706.md
@@ -1,13 +1,13 @@
 Results marker can be hidden in block attributes (#3706)
 
 ```
-pandoc -f org -t native
-#+BEGIN_SRC R :exports results :colnames yes
+% pandoc -f org -t native
+#+begin_src r :exports results :colnames yes
    data.frame(Id = 1:3, Desc = rep("La",3))
-#+END_SRC
+#+end_src
 
-#+CAPTION: Lalelu.
-#+LABEL: tab
+#+caption: Lalelu.
+#+label: tab
 #+RESULTS:
 | Id | Desc |
 |----+------|
@@ -15,25 +15,93 @@
 |  2 | La   |
 |  3 | La   |
 ^D
-[Table [Str "Lalelu."] [AlignDefault,AlignDefault] [0.0,0.0]
- [[Plain [Str "Id"]]
- ,[Plain [Str "Desc"]]]
- [[[Plain [Str "1"]]
-  ,[Plain [Str "La"]]]
- ,[[Plain [Str "2"]]
-  ,[Plain [Str "La"]]]
- ,[[Plain [Str "3"]]
-  ,[Plain [Str "La"]]]]]
+[ Table
+    ( "tab" , [] , [] )
+    (Caption Nothing [ Plain [ Str "Lalelu." ] ])
+    [ ( AlignDefault , ColWidthDefault )
+    , ( AlignDefault , ColWidthDefault )
+    ]
+    (TableHead
+       ( "" , [] , [] )
+       [ Row
+           ( "" , [] , [] )
+           [ Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "Id" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "Desc" ] ]
+           ]
+       ])
+    [ TableBody
+        ( "" , [] , [] )
+        (RowHeadColumns 0)
+        []
+        [ Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "1" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "La" ] ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "2" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "La" ] ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "3" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "La" ] ]
+            ]
+        ]
+    ]
+    (TableFoot ( "" , [] , [] ) [])
+]
 ```
 
 ```
-pandoc -f org -t native
-#+BEGIN_SRC R :exports none :colnames yes
+% pandoc -f org -t native
+#+begin_src R :exports none :colnames yes
    data.frame(Id = 1:2, Desc = rep("La",2))
-#+END_SRC
+#+end_src
 
-#+CAPTION: Lalelu.
-#+LABEL: tab
+#+caption: Lalelu.
+#+label: tab
 #+RESULTS:
 | Id | Desc |
 |----+------|
diff --git a/test/command/3708.md b/test/command/3708.md
--- a/test/command/3708.md
+++ b/test/command/3708.md
@@ -5,11 +5,49 @@
     C & D
 \end{tabular}
 ^D
-[Table [] [AlignCenter,AlignCenter] [0.0,0.0]
- [[]
- ,[]]
- [[[Plain [Str "A"]]
-  ,[Plain [Str "B&1"]]]
- ,[[Plain [Str "C"]]
-  ,[Plain [Str "D"]]]]]
+[ Table
+    ( "" , [] , [] )
+    (Caption Nothing [])
+    [ ( AlignCenter , ColWidthDefault )
+    , ( AlignCenter , ColWidthDefault )
+    ]
+    (TableHead ( "" , [] , [] ) [])
+    [ TableBody
+        ( "" , [] , [] )
+        (RowHeadColumns 0)
+        []
+        [ Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "A" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "B&1" ] ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "C" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "D" ] ]
+            ]
+        ]
+    ]
+    (TableFoot ( "" , [] , [] ) [])
+]
 ```
diff --git a/test/command/3716.md b/test/command/3716.md
--- a/test/command/3716.md
+++ b/test/command/3716.md
@@ -2,5 +2,5 @@
 % pandoc
 <http://example.com>{.foo}
 ^D
-<p><a href="http://example.com" class="uri foo">http://example.com</a></p>
+<p><a href="http://example.com" class="foo">http://example.com</a></p>
 ```
diff --git a/test/command/3733.md b/test/command/3733.md
--- a/test/command/3733.md
+++ b/test/command/3733.md
@@ -6,8 +6,8 @@
 some: code
 ```
 ^D
-[BulletList
- [[Plain [Str "Item1"]]
- ,[Plain [Str "Item2"]]]
-,CodeBlock ("",["yaml"],[]) "some: code"]
+[ BulletList
+    [ [ Plain [ Str "Item1" ] ] , [ Plain [ Str "Item2" ] ] ]
+, CodeBlock ( "" , [ "yaml" ] , [] ) "some: code"
+]
 ````
diff --git a/test/command/3734.md b/test/command/3734.md
--- a/test/command/3734.md
+++ b/test/command/3734.md
@@ -4,27 +4,9 @@
 |--------------|-------|--------------------------------------------------------------------------|
 | aaaaaaaaaaaa |       | cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc |
 ^D
-<table>
-<colgroup>
-<col style="width: 14%" />
-<col style="width: 7%" />
-<col style="width: 77%" />
-</colgroup>
-<thead>
-<tr class="header">
-<th>aaaaaaaaaaaa</th>
-<th>bbbbb</th>
-<th>ccccccccccc</th>
-</tr>
-</thead>
-<tbody>
-<tr class="odd">
-<td>aaaaaaaaaaaa</td>
-<td></td>
-<td>cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc</td>
-</tr>
-</tbody>
-</table>
+| aaaaaaaaaaaa | bbbbb | ccccccccccc |
+|------------|-------|------------------------------------------------------|
+| aaaaaaaaaaaa |  | cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc |
 ```
 
 ```
@@ -33,9 +15,9 @@
 |--------------|-------|--------------------------------------------------------------------------|
 | aaaaaaaaaaaa |       | cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc |
 ^D
-| aaaaaaaaaaaa | bbbbb | ccccccccccc                                                              |
-|--------------|-------|--------------------------------------------------------------------------|
-| aaaaaaaaaaaa |       | cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc |
+| aaaaaaaaaaaa | bbbbb | ccccccccccc |
+|------------|-------|------------------------------------------------------|
+| aaaaaaaaaaaa |  | cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc |
 ```
 
 ```
@@ -44,7 +26,7 @@
 |--------------|-------|--------------------------------------------------------------------------|
 | aaaaaaaaaaaa |       | cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc |
 ^D
-| aaaaaaaaaaaa | bbbbb | ccccccccccc                                                              |
-| ------------ | ----- | ------------------------------------------------------------------------ |
-| aaaaaaaaaaaa |       | cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc |
+| aaaaaaaaaaaa | bbbbb | ccccccccccc |
+|----|----|----|
+| aaaaaaaaaaaa |  | cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc |
 ```
diff --git a/test/command/3736.md b/test/command/3736.md
--- a/test/command/3736.md
+++ b/test/command/3736.md
@@ -3,8 +3,7 @@
 <h2>hi
 there</h2>
 ^D
-hi there
---------
+## hi there
 ```
 
 ```
@@ -12,14 +11,12 @@
 <h2>hi <em>there
 again</em></h2>
 ^D
-hi *there again*
-----------------
+## hi *there again*
 ```
 
 ```
 % pandoc --wrap=preserve -f html -t markdown
 <h2>hi<br>there</h2>
 ^D
-hi there
---------
+## hi there
 ```
diff --git a/test/command/3752.md b/test/command/3752.md
new file mode 100644
--- /dev/null
+++ b/test/command/3752.md
@@ -0,0 +1,66 @@
+```
+% pandoc command/chap1/text.md command/chap2/text.md -f markdown+rebase_relative_paths --verbose -t docx -o - | pandoc -f docx -t plain
+^D
+2> [INFO] Loaded command/chap1/spider.png from command/chap1/spider.png
+2> [INFO] Loaded command/chap2/spider.png from command/chap2/spider.png
+2> [INFO] Loaded command/chap1/../../lalune.jpg from command/chap1/../../lalune.jpg
+Chapter one
+
+A spider: [spider]
+
+Another spider: [another spider]
+
+The moon: [moon]
+
+Link to spider picture.
+
+URL left alone: manual.
+
+Absolute path left alone: absolute.
+
+Link to fragment: chapter two.
+
+Empty path: empty.
+
+Chapter two
+
+A spider: [spider]
+```
+
+```
+% pandoc command/chap1/text.md command/chap2/text.md -f markdown+rebase_relative_paths -t html
+^D
+<h1 id="chapter-one">Chapter one</h1>
+<p>A spider: <img src="command/chap1/spider.png" alt="spider" /></p>
+<p>Another spider: <img src="command/chap2/spider.png"
+alt="another spider" /></p>
+<p>The moon: <img src="command/chap1/../../lalune.jpg" alt="moon" /></p>
+<p>Link to <a href="command/chap1/spider.png">spider picture</a>.</p>
+<p>URL left alone: <a
+href="https://pandoc.org/MANUAL.html">manual</a>.</p>
+<p>Absolute path left alone: <a
+href="/foo/bar/baz.png">absolute</a>.</p>
+<p>Link to fragment: <a href="#chapter-two">chapter two</a>.</p>
+<p>Empty path: <a href="">empty</a>.</p>
+<h1 id="chapter-two">Chapter two</h1>
+<p>A spider: <img src="command/chap2/spider.png" alt="spider" /></p>
+```
+
+```
+% pandoc command/chap1/text.md command/chap2/text.md -f commonmark+rebase_relative_paths -t html
+^D
+<h1>Chapter one</h1>
+<p>A spider: <img src="command/chap1/spider.png" alt="spider" /></p>
+<p>Another spider: <img src="command/chap2/spider.png"
+alt="another spider" /></p>
+<p>The moon: <img src="command/chap1/../../lalune.jpg" alt="moon" /></p>
+<p>Link to <a href="command/chap1/spider.png">spider picture</a>.</p>
+<p>URL left alone: <a
+href="https://pandoc.org/MANUAL.html">manual</a>.</p>
+<p>Absolute path left alone: <a
+href="/foo/bar/baz.png">absolute</a>.</p>
+<p>Link to fragment: <a href="#chapter-two">chapter two</a>.</p>
+<p>Empty path: <a href="">empty</a>.</p>
+<h1>Chapter two</h1>
+<p>A spider: <img src="command/chap2/spider.png" alt="spider" /></p>
+```
diff --git a/test/command/3755.md b/test/command/3755.md
--- a/test/command/3755.md
+++ b/test/command/3755.md
@@ -5,19 +5,45 @@
 date: '22. Juni 2017'
 ---
 ^D
-Pandoc (Meta {unMeta = fromList [("date",MetaInlines [Str "22.",Space,Str "Juni",Space,Str "2017"]),("title",MetaInlines [Str "Titel"])]})
-[]
+Pandoc
+  Meta
+    { unMeta =
+        fromList
+          [ ( "date"
+            , MetaInlines
+                [ Str "22." , Space , Str "Juni" , Space , Str "2017" ]
+            )
+          , ( "title" , MetaInlines [ Str "Titel" ] )
+          ]
+    }
+  []
 ```
 
 ```
 % pandoc -t native -s
 ---
-title: '<div>foo</div>'
+title: "<div>foo</div>\n"
 date: |
   22. Juni 2017
 ---
 ^D
-Pandoc (Meta {unMeta = fromList [("date",MetaBlocks [OrderedList (22,Decimal,Period) [[Plain [Str "Juni",Space,Str "2017"]]]]),("title",MetaBlocks [Div ("",[],[]) [Plain [Str "foo"]]])]})
-[]
+Pandoc
+  Meta
+    { unMeta =
+        fromList
+          [ ( "date"
+            , MetaBlocks
+                [ OrderedList
+                    ( 22 , Decimal , Period )
+                    [ [ Plain [ Str "Juni" , Space , Str "2017" ] ] ]
+                ]
+            )
+          , ( "title"
+            , MetaBlocks
+                [ Div ( "" , [] , [] ) [ Plain [ Str "foo" ] ] ]
+            )
+          ]
+    }
+  []
 ```
 
diff --git a/test/command/3779.md b/test/command/3779.md
--- a/test/command/3779.md
+++ b/test/command/3779.md
@@ -20,9 +20,38 @@
     Pandoc is 300\% awesome.
 }
 ^D
-[BulletList
- [[Para [Str "Pandoc",Space,Str "is",Space,Str "100%",Space,Str "awesome."]]]
-,BulletList
- [[Para [Str "Pandoc",Space,Str "is",Space,Str "200%",Space,Str "awesome."]]]
-,Para [Str "Pandoc",Space,Str "is",Space,Str "300%",Space,Str "awesome."]]
+[ BulletList
+    [ [ Para
+          [ Str "Pandoc"
+          , Space
+          , Str "is"
+          , Space
+          , Str "100%"
+          , Space
+          , Str "awesome."
+          ]
+      ]
+    ]
+, BulletList
+    [ [ Para
+          [ Str "Pandoc"
+          , Space
+          , Str "is"
+          , Space
+          , Str "200%"
+          , Space
+          , Str "awesome."
+          ]
+      ]
+    ]
+, Para
+    [ Str "Pandoc"
+    , Space
+    , Str "is"
+    , Space
+    , Str "300%"
+    , Space
+    , Str "awesome."
+    ]
+]
 ```
diff --git a/test/command/3792.md b/test/command/3792.md
--- a/test/command/3792.md
+++ b/test/command/3792.md
@@ -6,7 +6,7 @@
 ok
 ^D
 ---
-title: '\<this\> \*that\*'
+title: \<this\> \*that\*
 ---
 
 ok
diff --git a/test/command/3794.md b/test/command/3794.md
--- a/test/command/3794.md
+++ b/test/command/3794.md
@@ -2,6 +2,5 @@
 % pandoc -f html -t native
 <div><p>hello</div>
 ^D
-[Div ("",[],[])
- [Para [Str "hello"]]]
+[ Div ( "" , [] , [] ) [ Para [ Str "hello" ] ] ]
 ```
diff --git a/test/command/3804.md b/test/command/3804.md
--- a/test/command/3804.md
+++ b/test/command/3804.md
@@ -2,5 +2,8 @@
 % pandoc -t native
 \titleformat{\chapter}[display]{\normalfont\large\bfseries}{第\thechapter{}章}{20pt}{\Huge}
 ^D
-[RawBlock (Format "latex") "\\titleformat{\\chapter}[display]{\\normalfont\\large\\bfseries}{\31532\\thechapter{}\31456}{20pt}{\\Huge}"]
+[ RawBlock
+    (Format "tex")
+    "\\titleformat{\\chapter}[display]{\\normalfont\\large\\bfseries}{\31532\\thechapter{}\31456}{20pt}{\\Huge}"
+]
 ```
diff --git a/test/command/3824.md b/test/command/3824.md
--- a/test/command/3824.md
+++ b/test/command/3824.md
@@ -8,7 +8,7 @@
   * hi<code>
  there
 </code>
-  * ok
 
+  * ok
 
 ```
diff --git a/test/command/3840.md b/test/command/3840.md
--- a/test/command/3840.md
+++ b/test/command/3840.md
@@ -2,7 +2,8 @@
 % pandoc
 [@Alhazen1572-qk, V.9]: "competentius est"
 ^D
-<p><span class="citation" data-cites="Alhazen1572-qk">[@Alhazen1572-qk, V.9]</span>: “competentius est”</p>
+<p><span class="citation" data-cites="Alhazen1572-qk">[@Alhazen1572-qk,
+V.9]</span>: “competentius est”</p>
 ```
 
 ```
diff --git a/test/command/3853.md b/test/command/3853.md
--- a/test/command/3853.md
+++ b/test/command/3853.md
@@ -20,7 +20,9 @@
 
 hello \iftoggle{ebook}{ebook}{noebook}
 ^D
-[Para [Str "ebook",SoftBreak,Str "more"]
-,Para [Str "not",Space,Str "ebook",SoftBreak,Str "more"]
-,Para [Str "hello",Space,Str "noebook"]]
+[ Para [ Str "ebook" , SoftBreak , Str "more" ]
+, Para
+    [ Str "not" , Space , Str "ebook" , SoftBreak , Str "more" ]
+, Para [ Str "hello" , Space , Str "noebook" ]
+]
 ```
diff --git a/test/command/3880.md b/test/command/3880.md
--- a/test/command/3880.md
+++ b/test/command/3880.md
@@ -1,6 +1,6 @@
 ```
-pandoc -f rst -t native
+% pandoc -f rst -t native
 .. include:: command/3880.txt
 ^D
-[Para [Str "hi"]]
+[ Para [ Str "hi" ] ]
 ```
diff --git a/test/command/3916.md b/test/command/3916.md
--- a/test/command/3916.md
+++ b/test/command/3916.md
@@ -4,8 +4,12 @@
 <pre>blabla</pre>
 # more
 ^D
-[OrderedList (1,DefaultStyle,DefaultDelim)
- [[Plain [Str "text",Space,Str "text"]
-  ,CodeBlock ("",[],[]) "blabla"]
- ,[Plain [Str "more"]]]]
+[ OrderedList
+    ( 1 , DefaultStyle , DefaultDelim )
+    [ [ Plain [ Str "text" , Space , Str "text" ]
+      , CodeBlock ( "" , [] , [] ) "blabla"
+      ]
+    , [ Plain [ Str "more" ] ]
+    ]
+]
 ```
diff --git a/test/command/3947.md b/test/command/3947.md
--- a/test/command/3947.md
+++ b/test/command/3947.md
@@ -6,6 +6,8 @@
 
 	Another Code block
 ^D
-[RawBlock (Format "latex") "\\newpage"
-,CodeBlock ("",[],[]) "Code block\n\nAnother Code block"]
+[ RawBlock (Format "tex") "\\newpage"
+, CodeBlock
+    ( "" , [] , [] ) "Code block\n\nAnother Code block"
+]
 ```
diff --git a/test/command/3958.md b/test/command/3958.md
--- a/test/command/3958.md
+++ b/test/command/3958.md
@@ -2,19 +2,19 @@
 % pandoc -f latex -t native
 \texttt{"hi"}
 ^D
-[Para [Code ("",[],[]) "\"hi\""]]
+[ Para [ Code ( "" , [] , [] ) "\"hi\"" ] ]
 ```
 
 ```
 % pandoc -f latex -t native
 \texttt{``hi''}
 ^D
-[Para [Code ("",[],[]) "\8220hi\8221"]]
+[ Para [ Code ( "" , [] , [] ) "\8216\8216hi\8217\8217" ] ]
 ```
 
 ```
 % pandoc -f latex -t native
 \texttt{`hi'}
 ^D
-[Para [Code ("",[],[]) "\8216hi\8217"]]
+[ Para [ Code ( "" , [] , [] ) "\8216hi\8217" ] ]
 ```
diff --git a/test/command/3968.md b/test/command/3968.md
--- a/test/command/3968.md
+++ b/test/command/3968.md
@@ -4,6 +4,11 @@
 
 ## Section
 ^D
-\chapter[chapter]{Chapter}
-\section[section]{Section}
+\startchapter[title={Chapter},reference={chapter}]
+
+\startsection[title={Section},reference={section}]
+
+\stopsection
+
+\stopchapter
 ```
diff --git a/test/command/3971.md b/test/command/3971.md
--- a/test/command/3971.md
+++ b/test/command/3971.md
@@ -5,5 +5,5 @@
 \code{f}
 \end{document}
 ^D
-[Para [Code ("",[],[]) "f"]]
+[ Para [ Code ( "" , [] , [] ) "f" ] ]
 ```
diff --git a/test/command/3983.md b/test/command/3983.md
--- a/test/command/3983.md
+++ b/test/command/3983.md
@@ -1,29 +1,31 @@
 ```
-pandoc -f latex -t native
+% pandoc -f latex+raw_tex -t native
 \def\filename@area{foo:bar:baz}
 \makeatletter
 \graphicspath\expandafter{\expandafter{\filename@area}}%
 \makeatother
 ^D
-[RawBlock (Format "latex") "\\makeatletter"
-,RawBlock (Format "latex") "\\makeatother"]
+[ RawBlock (Format "latex") "\\makeatletter"
+, RawBlock (Format "latex") "\\makeatother"
+]
 ```
 
 ```
-pandoc -f latex -t native
+% pandoc -f latex+raw_tex -t native
 \makeatletter
   \newcommand\urlfootnote@[1]{\footnote{\url@{#1}}}
   \DeclareRobustCommand{\urlfootnote}{\hyper@normalise\urlfootnote@}
 \makeatother
 ^D
-[RawBlock (Format "latex") "\\makeatletter"
-,RawBlock (Format "latex") "\\makeatother"]
+[ RawBlock (Format "latex") "\\makeatletter"
+, RawBlock (Format "latex") "\\makeatother"
+]
 ```
 
 ```
-pandoc -f latex -t native
+% pandoc -f latex+raw_tex -t native
 \def\foo{bar}
 \expandafter\bam\foo
 ^D
-[RawBlock (Format "latex") "\\bambar"]
+[ RawBlock (Format "latex") "\\bambar" ]
 ```
diff --git a/test/command/3989.md b/test/command/3989.md
--- a/test/command/3989.md
+++ b/test/command/3989.md
@@ -1,7 +1,22 @@
 ```
-pandoc -f markdown -t native
+% pandoc -f markdown -t native
 <span title="1st line of text <br> 2nd line of text">foo</span>
  <span title="1st line of text <br> 2nd line of text">foo</span>
 ^D
-[Para [Span ("",[],[("title","1st line of text <br> 2nd line of text")]) [Str "foo"],SoftBreak,Span ("",[],[("title","1st line of text <br> 2nd line of text")]) [Str "foo"]]]
+[ Para
+    [ Span
+        ( ""
+        , []
+        , [ ( "title" , "1st line of text <br> 2nd line of text" ) ]
+        )
+        [ Str "foo" ]
+    , SoftBreak
+    , Span
+        ( ""
+        , []
+        , [ ( "title" , "1st line of text <br> 2nd line of text" ) ]
+        )
+        [ Str "foo" ]
+    ]
+]
 ```
diff --git a/test/command/4007.md b/test/command/4007.md
--- a/test/command/4007.md
+++ b/test/command/4007.md
@@ -1,23 +1,23 @@
 ```
-pandoc -f latex -t native
+% pandoc -f latex -t native
 \newcommand\arrow\to
 $a\arrow b$
 ^D
-[Para [Math InlineMath "a\\to b"]]
+[ Para [ Math InlineMath "a\\to b" ] ]
 ```
 
 ```
-pandoc -f latex -t native
+% pandoc -f latex -t native
 \newcommand\pfeil[1]{\to #1}
 $a\pfeil b$
 ^D
-[Para [Math InlineMath "a\\to b"]]
+[ Para [ Math InlineMath "a\\to b" ] ]
 ```
 
 ```
-pandoc -f latex -t native
+% pandoc -f latex -t native
 \newcommand\fleche{\to}
 $a\fleche b$
 ^D
-[Para [Math InlineMath "a\\to b"]]
+[ Para [ Math InlineMath "a\\to b" ] ]
 ```
diff --git a/test/command/4012.md b/test/command/4012.md
--- a/test/command/4012.md
+++ b/test/command/4012.md
@@ -1,8 +1,9 @@
 ```
-pandoc -f markdown-implicit_figures
+% pandoc -f markdown-implicit_figures
 ![image]
 
 [image]: http://example.com/image.jpg {height=35mm}
 ^D
-<p><img src="http://example.com/image.jpg" alt="image" style="height:35mm" /></p>
+<p><img src="http://example.com/image.jpg" style="height:35mm"
+alt="image" /></p>
 ```
diff --git a/test/command/4016.md b/test/command/4016.md
--- a/test/command/4016.md
+++ b/test/command/4016.md
@@ -1,5 +1,5 @@
 ```
-pandoc -t beamer
+% pandoc -t beamer
 # Level 2 blocks
 
 <div class="columns">
@@ -13,35 +13,30 @@
 </div>
 </div>
 ^D
-\begin{frame}{%
-\protect\hypertarget{level-2-blocks}{%
-Level 2 blocks}}
-
+\begin{frame}{Level 2 blocks}
+\protect\phantomsection\label{level-2-blocks}
 \begin{columns}[T]
-\begin{column}{0.40\textwidth}
+\begin{column}{0.4\linewidth}
 \begin{block}{Block one}
-
+\protect\phantomsection\label{block-one}
 \begin{itemize}
 \tightlist
 \item
   Item
 \end{itemize}
-
 \end{block}
 \end{column}
 
-\begin{column}{0.60\textwidth}
+\begin{column}{0.6\linewidth}
 \begin{block}{Block two}
-
+\protect\phantomsection\label{block-two}
 \begin{itemize}
 \tightlist
 \item
   Item
 \end{itemize}
-
 \end{block}
 \end{column}
 \end{columns}
-
 \end{frame}
 ```
diff --git a/test/command/4019.md b/test/command/4019.md
--- a/test/command/4019.md
+++ b/test/command/4019.md
@@ -1,5 +1,5 @@
 ```
-pandoc --wrap=preserve
+% pandoc --wrap=preserve
 This <!-- x > 0 --> works!
 This <!-- x > 0 --> fails?
 ^D
diff --git a/test/command/4054.md b/test/command/4054.md
--- a/test/command/4054.md
+++ b/test/command/4054.md
@@ -2,13 +2,20 @@
 % pandoc -t native -s -M title=New
 % Old
 ^D
-Pandoc (Meta {unMeta = fromList [("title",MetaString "New")]})
-[]
+Pandoc
+  Meta
+    { unMeta = fromList [ ( "title" , MetaString "New" ) ] }
+  []
 ```
 
 ```
 % pandoc -t native -s -M foo=1 -M foo=2
 ^D
-Pandoc (Meta {unMeta = fromList [("foo",MetaList [MetaString "1",MetaString "2"])]})
-[]
+Pandoc
+  Meta
+    { unMeta =
+        fromList
+          [ ( "foo" , MetaList [ MetaString "1" , MetaString "2" ] ) ]
+    }
+  []
 ```
diff --git a/test/command/4056.md b/test/command/4056.md
--- a/test/command/4056.md
+++ b/test/command/4056.md
@@ -5,7 +5,10 @@
 \end{shaded}
 }
 ^D
-[RawBlock (Format "latex") "\\parbox[t]{0.4\\textwidth}{\n\\begin{shaded}\n\\end{shaded}\n}"]
+[ RawBlock
+    (Format "tex")
+    "\\parbox[t]{0.4\\textwidth}{\n\\begin{shaded}\n\\end{shaded}\n}"
+]
 ```
 
 ```
@@ -14,11 +17,41 @@
 Blah & Foo & Bar \\
 \end{tabular}
 ^D
-[Table [] [AlignLeft,AlignRight,AlignRight] [0.0,0.0,0.0]
- [[]
- ,[]
- ,[]]
- [[[Plain [Str "Blah"]]
-  ,[Plain [Str "Foo"]]
-  ,[Plain [Str "Bar"]]]]]
+[ Table
+    ( "" , [] , [] )
+    (Caption Nothing [])
+    [ ( AlignLeft , ColWidthDefault )
+    , ( AlignRight , ColWidthDefault )
+    , ( AlignRight , ColWidthDefault )
+    ]
+    (TableHead ( "" , [] , [] ) [])
+    [ TableBody
+        ( "" , [] , [] )
+        (RowHeadColumns 0)
+        []
+        [ Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "Blah" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "Foo" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "Bar" ] ]
+            ]
+        ]
+    ]
+    (TableFoot ( "" , [] , [] ) [])
+]
 ```
diff --git a/test/command/4063.md b/test/command/4063.md
new file mode 100644
--- /dev/null
+++ b/test/command/4063.md
@@ -0,0 +1,44 @@
+```
+% pandoc -f html -t native
+<table>
+<colgroup>
+  <col width="30%" />
+  <col width="*" />
+</colgroup>
+<tr>
+  <td>1</td>
+  <td>2</td>
+</tr>
+</table>
+^D
+[ Table
+    ( "" , [] , [] )
+    (Caption Nothing [])
+    [ ( AlignDefault , ColWidth 0.3 )
+    , ( AlignDefault , ColWidth 0.7 )
+    ]
+    (TableHead ( "" , [] , [] ) [])
+    [ TableBody
+        ( "" , [] , [] )
+        (RowHeadColumns 0)
+        []
+        [ Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "1" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "2" ] ]
+            ]
+        ]
+    ]
+    (TableFoot ( "" , [] , [] ) [])
+]
+```
diff --git a/test/command/4068.md b/test/command/4068.md
--- a/test/command/4068.md
+++ b/test/command/4068.md
@@ -1,9 +1,33 @@
 ```
-pandoc -f mediawiki -t native
+% pandoc -f mediawiki -t native
 [https://domain.com/script.php?a=1&b=2&c=&d=4 open productname bugs]
 
 [http://domain.com?a=. open productname bugs]
 ^D
-[Para [Link ("",[],[]) [Str "open",Space,Str "productname",Space,Str "bugs"] ("https://domain.com/script.php?a=1&b=2&c=&d=4","")]
-,Para [Str "[",Link ("",[],[]) [Str "http://domain.com?a="] ("http://domain.com?a=",""),Str ".",Space,Str "open",Space,Str "productname",Space,Str "bugs]"]]
+[ Para
+    [ Link
+        ( "" , [] , [] )
+        [ Str "open"
+        , Space
+        , Str "productname"
+        , Space
+        , Str "bugs"
+        ]
+        ( "https://domain.com/script.php?a=1&b=2&c=&d=4" , "" )
+    ]
+, Para
+    [ Str "["
+    , Link
+        ( "" , [] , [] )
+        [ Str "http://domain.com?a=" ]
+        ( "http://domain.com?a=" , "" )
+    , Str "."
+    , Space
+    , Str "open"
+    , Space
+    , Str "productname"
+    , Space
+    , Str "bugs]"
+    ]
+]
 ```
diff --git a/test/command/4102.md b/test/command/4102.md
new file mode 100644
--- /dev/null
+++ b/test/command/4102.md
@@ -0,0 +1,11 @@
+SmallCaps spans can have additional attributes.
+```
+% pandoc -t latex -f markdown
+[Populus]{.smallcaps lang=la}
+
+[Romanus]{.smallcaps}
+^D
+\foreignlanguage{latin}{\textsc{Populus}}
+
+\textsc{Romanus}
+```
diff --git a/test/command/4119.md b/test/command/4119.md
--- a/test/command/4119.md
+++ b/test/command/4119.md
@@ -1,5 +1,5 @@
 ```
-pandoc -t native
+% pandoc -t native
 | col1 | col2 |
 | ---- | ---- |
 | 1    | 2    |
@@ -8,11 +8,56 @@
 not a caption!
 ::::::::::::::::
 ^D
-[Table [] [AlignDefault,AlignDefault] [0.0,0.0]
- [[Plain [Str "col1"]]
- ,[Plain [Str "col2"]]]
- [[[Plain [Str "1"]]
-  ,[Plain [Str "2"]]]]
-,Div ("",["notes"],[])
- [Para [Str "not",Space,Str "a",Space,Str "caption!"]]]
+[ Table
+    ( "" , [] , [] )
+    (Caption Nothing [])
+    [ ( AlignDefault , ColWidthDefault )
+    , ( AlignDefault , ColWidthDefault )
+    ]
+    (TableHead
+       ( "" , [] , [] )
+       [ Row
+           ( "" , [] , [] )
+           [ Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "col1" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "col2" ] ]
+           ]
+       ])
+    [ TableBody
+        ( "" , [] , [] )
+        (RowHeadColumns 0)
+        []
+        [ Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "1" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "2" ] ]
+            ]
+        ]
+    ]
+    (TableFoot ( "" , [] , [] ) [])
+, Div
+    ( "" , [ "notes" ] , [] )
+    [ Para
+        [ Str "not" , Space , Str "a" , Space , Str "caption!" ]
+    ]
+]
 ```
diff --git a/test/command/4134.md b/test/command/4134.md
--- a/test/command/4134.md
+++ b/test/command/4134.md
@@ -3,7 +3,7 @@
 Hello.\
 world.
 ^D
-[Para [Str "Hello.\160world."]]
+[ Para [ Str "Hello.\160world." ] ]
 ```
 
 ```
@@ -11,7 +11,7 @@
 Hello.\  
  world.
 ^D
-[Para [Str "Hello.\160world."]]
+[ Para [ Str "Hello.\160world." ] ]
 ```
 
 ```
@@ -20,6 +20,5 @@
 
 World.
 ^D
-[Para [Str "Hello.\160"]
-,Para [Str "World."]]
+[ Para [ Str "Hello.\160" ] , Para [ Str "World." ] ]
 ```
diff --git a/test/command/4159.md b/test/command/4159.md
--- a/test/command/4159.md
+++ b/test/command/4159.md
@@ -3,5 +3,7 @@
 \newcommand{\gen}{a\ Gen\ b}
 abc
 ^D
-[Para [Str "abc"]]
+[ RawBlock (Format "tex") "\\newcommand{\\gen}{a\\ Gen\\ b}"
+, Para [ Str "abc" ]
+]
 ```
diff --git a/test/command/4162.md b/test/command/4162.md
--- a/test/command/4162.md
+++ b/test/command/4162.md
@@ -3,8 +3,5 @@
 <div class="line-block">hi<br /><br>
  there</div>
 ^D
-[LineBlock
- [[Str "hi"]
- ,[]
- ,[Str "\160there"]]]
+[ LineBlock [ [ Str "hi" ] , [] , [ Str "\160there" ] ] ]
 ```
diff --git a/test/command/4164.md b/test/command/4164.md
--- a/test/command/4164.md
+++ b/test/command/4164.md
@@ -2,19 +2,15 @@
 % pandoc -f opml -t markdown
 <?xml version="1.0"?> <opml version="1.0"> <head> <title> test </title> </head> <body> <outline text="test"> <outline text="try" _note="Here is inline html:&#xA;&#xA;&lt;div&gt; &#xA;&lt;balise&gt;&#xA;bla bla&#xA;&lt;/div&gt;"/> </outline> </body> </opml>
 ^D
-test
-====
+# test
 
-try
----
+## try
 
 Here is inline html:
 
-<div>
-
-<balise> bla bla
-
-</div>
+::: {}
+`<balise>`{=html} bla bla
+:::
 
 ```
 
@@ -22,11 +18,9 @@
 % pandoc -f opml-raw_html-native_divs -t markdown
 <?xml version="1.0"?> <opml version="1.0"> <head> <title> test </title> </head> <body> <outline text="test"> <outline text="try" _note="Here is inline html:&#xA;&#xA;&lt;div&gt; &#xA;&lt;balise&gt;&#xA;bla bla&#xA;&lt;/div&gt;"/> </outline> </body> </opml>
 ^D
-test
-====
+# test
 
-try
----
+## try
 
 Here is inline html:
 
diff --git a/test/command/4183.md b/test/command/4183.md
--- a/test/command/4183.md
+++ b/test/command/4183.md
@@ -4,7 +4,13 @@
   <img src="foo" alt="bar">
 </figure>
 ^D
-[Para [Image ("",[],[]) [] ("foo","fig:")]]
+[ Figure
+    ( "" , [] , [] )
+    (Caption Nothing [])
+    [ Plain
+        [ Image ( "" , [] , [] ) [ Str "bar" ] ( "foo" , "" ) ]
+    ]
+]
 ```
 
 ```
@@ -18,7 +24,14 @@
   </figcaption>
 </figure>
 ^D
-[Para [Image ("",[],[]) [Str "baz"] ("foo","fig:")]]
+[ Figure
+    ( "" , [] , [] )
+    (Caption
+       Nothing [ Div ( "" , [] , [] ) [ Plain [ Str "baz" ] ] ])
+    [ Plain
+        [ Image ( "" , [] , [] ) [ Str "bar" ] ( "foo" , "" ) ]
+    ]
+]
 ```
 
 ```
@@ -28,5 +41,9 @@
   <figcaption><p><em>baz</em></p></figcaption>
 </figure>
 ^D
-[Para [Image ("",[],[]) [Emph [Str "baz"]] ("foo","fig:")]]
+[ Figure
+    ( "" , [] , [] )
+    (Caption Nothing [ Para [ Emph [ Str "baz" ] ] ])
+    [ Plain [ Image ( "" , [] , [] ) [] ( "foo" , "" ) ] ]
+]
 ```
diff --git a/test/command/4186.md b/test/command/4186.md
new file mode 100644
--- /dev/null
+++ b/test/command/4186.md
@@ -0,0 +1,64 @@
+```
+% pandoc -f org -t native
+#+begin_example -i
+    This should retain the four leading spaces
+#+end_example
+^D
+[ CodeBlock
+    ( "" , [] , [] )
+    "    This should retain the four leading spaces\n"
+]
+```
+
+```
+% pandoc -f org -t html
+- depth 1
+  #+name: bob
+  #+begin_example -i
+    Vertical alignment is four spaces beyond the appearance of the word "depth".
+  #+end_example
+       - depth 2
+         #+begin_example
+                          Vertically aligned with the second appearance of the word "depth".
+         #+end_example
+              #+begin_example -i
+    Vertical alignment is four spaces beyond the second
+    appearance of the word "depth".
+    The "begin" portion is a component of
+    this deeper list element, so that guarantees
+    that the entire block must be a component of the
+    inner list element.
+    #+end_example
+         Still inside the inner list element
+   #+name: carrie
+                         #+begin_example
+                           This belongs to the outer list element, and is aligned accordingly, since the NAME attribute is not indented deeply enough. It is not enough for the BEGIN alone to be aligned deeply if the block is meant to have a NAME.
+                           #+end_example
+                 Still in the shallower list element since the preceding example
+                 block forced the deeper list element to terminate.
+Outside all lists.
+^D
+<ul>
+<li><p>depth 1</p>
+<pre id="bob"><code>    Vertical alignment is four spaces beyond the appearance of the word &quot;depth&quot;.
+</code></pre>
+<ul>
+<li><p>depth 2</p>
+<pre><code>Vertically aligned with the second appearance of the word &quot;depth&quot;.
+</code></pre>
+<pre><code>    Vertical alignment is four spaces beyond the second
+    appearance of the word &quot;depth&quot;.
+    The &quot;begin&quot; portion is a component of
+    this deeper list element, so that guarantees
+    that the entire block must be a component of the
+    inner list element.
+</code></pre>
+<p>Still inside the inner list element</p></li>
+</ul>
+<pre id="carrie"><code>This belongs to the outer list element, and is aligned accordingly, since the NAME attribute is not indented deeply enough. It is not enough for the BEGIN alone to be aligned deeply if the block is meant to have a NAME.
+</code></pre>
+<p>Still in the shallower list element since the preceding example block
+forced the deeper list element to terminate.</p></li>
+</ul>
+<p>Outside all lists.</p>
+```
diff --git a/test/command/4193.md b/test/command/4193.md
--- a/test/command/4193.md
+++ b/test/command/4193.md
@@ -4,7 +4,7 @@
  a
 - b
 ^D
-[BulletList
- [[Plain [Str "a"]]
- ,[Plain [Str "b"]]]]
+[ BulletList
+    [ [ Plain [ Str "a" ] ] , [ Plain [ Str "b" ] ] ]
+]
 ```
diff --git a/test/command/4199.md b/test/command/4199.md
--- a/test/command/4199.md
+++ b/test/command/4199.md
@@ -2,5 +2,8 @@
 % pandoc -f latex -t native
 \foreignlanguage{ngerman}{foo}
 ^D
-[Para [Span ("",[],[("lang","de-DE")]) [Str "foo"]]]
+[ Para
+    [ Span ( "" , [] , [ ( "lang" , "de-DE" ) ] ) [ Str "foo" ]
+    ]
+]
 ```
diff --git a/test/command/4235.md b/test/command/4235.md
new file mode 100644
--- /dev/null
+++ b/test/command/4235.md
@@ -0,0 +1,15 @@
+```
+% pandoc --id-prefix=foo
+This.^[Has a footnote.]
+^D
+<p>This.<a href="#foofn1" class="footnote-ref" id="foofnref1"
+role="doc-noteref"><sup>1</sup></a></p>
+<section id="foofootnotes" class="footnotes footnotes-end-of-document"
+role="doc-endnotes">
+<hr />
+<ol>
+<li id="foofn1"><p>Has a footnote.<a href="#foofnref1"
+class="footnote-back" role="doc-backlink">↩︎</a></p></li>
+</ol>
+</section>
+```
diff --git a/test/command/4240.md b/test/command/4240.md
new file mode 100644
--- /dev/null
+++ b/test/command/4240.md
@@ -0,0 +1,44 @@
+```
+% pandoc -f rst -s -t native
+=====
+Title
+=====
+
+--------
+Subtitle
+--------
+
+header1
+=======
+
+header2
+-------
+
+.. _id:
+
+header3
+~~~~~~~
+
+.. _id2:
+.. _id3:
+
+header4
+~~~~~~~
+^D
+Pandoc
+  Meta
+    { unMeta =
+        fromList
+          [ ( "subtitle" , MetaInlines [ Str "Subtitle" ] )
+          , ( "title" , MetaInlines [ Str "Title" ] )
+          ]
+    }
+  [ Header 1 ( "header1" , [] , [] ) [ Str "header1" ]
+  , Header 2 ( "header2" , [] , [] ) [ Str "header2" ]
+  , Header 3 ( "id" , [] , [] ) [ Str "header3" ]
+  , Header
+      3
+      ( "id3" , [] , [] )
+      [ Str "header4" , Span ( "id2" , [] , [] ) [] ]
+  ]
+```
diff --git a/test/command/4253.md b/test/command/4253.md
new file mode 100644
--- /dev/null
+++ b/test/command/4253.md
@@ -0,0 +1,8 @@
+```
+% pandoc -f latex -t native
+\newcommand{\noop}[1]{#1}
+\noop{\newcommand{\foo}[1]{#1}}
+\foo{hi}
+^D
+[ Para [ Str "hi" ] ]
+```
diff --git a/test/command/4254.md b/test/command/4254.md
new file mode 100644
--- /dev/null
+++ b/test/command/4254.md
@@ -0,0 +1,12 @@
+```
+% pandoc -f rst -t latex
+.. math::
+
+   x &= y\\
+   y &= z
+^D
+\[\begin{aligned}
+x &= y\\
+y &= z
+\end{aligned}\]
+```
diff --git a/test/command/4280.md b/test/command/4280.md
new file mode 100644
--- /dev/null
+++ b/test/command/4280.md
@@ -0,0 +1,7 @@
+```
+% pandoc -f rst -t native
+Driver 
+------
+^D
+[ Header 1 ( "driver" , [] , [] ) [ Str "Driver" ] ]
+```
diff --git a/test/command/4281.md b/test/command/4281.md
new file mode 100644
--- /dev/null
+++ b/test/command/4281.md
@@ -0,0 +1,21 @@
+```
+% pandoc -t native
+:::: {.a}
+- ::: {.b}
+  text
+  :::
+  ::: {.c}
+  text
+  :::
+::::
+^D
+[ Div
+    ( "" , [ "a" ] , [] )
+    [ BulletList
+        [ [ Div ( "" , [ "b" ] , [] ) [ Para [ Str "text" ] ]
+          , Div ( "" , [ "c" ] , [] ) [ Para [ Str "text" ] ]
+          ]
+        ]
+    ]
+]
+```
diff --git a/test/command/4284.md b/test/command/4284.md
new file mode 100644
--- /dev/null
+++ b/test/command/4284.md
@@ -0,0 +1,120 @@
+```
+% pandoc -f org -t native
+#+EXCLUDE_TAGS:apple       cat   bye     dog %     
+
+* This should not appear                                              :apple:
+* NOEXPORT should appear if not specified in EXCLUDE_TAGS          :noexport:
+* This should not appear                                      :cat:hi:laptop:
+** Children of headers with excluded tags should not appear       :xylophone:
+* This should not appear                                                  :%:
+^D
+[ Header
+    1
+    ( "noexport-should-appear-if-not-specified-in-excludetags"
+    , []
+    , []
+    )
+    [ Str "NOEXPORT"
+    , Space
+    , Str "should"
+    , Space
+    , Str "appear"
+    , Space
+    , Str "if"
+    , Space
+    , Str "not"
+    , Space
+    , Str "specified"
+    , Space
+    , Str "in"
+    , Space
+    , Str "EXCLUDE"
+    , Subscript [ Str "TAGS" ]
+    , Space
+    , Span
+        ( "" , [ "tag" ] , [ ( "tag-name" , "noexport" ) ] )
+        [ SmallCaps [ Str "noexport" ] ]
+    ]
+]
+```
+
+```
+% pandoc -f org -t native
+#+EXCLUDE_TAGS:elephant
+* This should not appear                                           :elephant:
+* This should appear                                                   :fawn:
+^D
+[ Header
+    1
+    ( "this-should-appear" , [] , [] )
+    [ Str "This"
+    , Space
+    , Str "should"
+    , Space
+    , Str "appear"
+    , Space
+    , Span
+        ( "" , [ "tag" ] , [ ( "tag-name" , "fawn" ) ] )
+        [ SmallCaps [ Str "fawn" ] ]
+    ]
+]
+```
+
+```
+% pandoc -f org -t native
+#+EXCLUDE_TAGS: giraffe
+#+EXCLUDE_TAGS: hippo
+* This should not appear                                            :giraffe:
+* This should not appear                                              :hippo:
+* This should appear                                               :noexport:
+^D
+[ Header
+    1
+    ( "this-should-appear" , [] , [] )
+    [ Str "This"
+    , Space
+    , Str "should"
+    , Space
+    , Str "appear"
+    , Space
+    , Span
+        ( "" , [ "tag" ] , [ ( "tag-name" , "noexport" ) ] )
+        [ SmallCaps [ Str "noexport" ] ]
+    ]
+]
+```
+
+```
+% pandoc -f org -t native
+#+EXCLUDE_TAGS:
+* NOEXPORT should appear if not specified in EXCLUDE_TAGS          :noexport:
+^D
+[ Header
+    1
+    ( "noexport-should-appear-if-not-specified-in-excludetags"
+    , []
+    , []
+    )
+    [ Str "NOEXPORT"
+    , Space
+    , Str "should"
+    , Space
+    , Str "appear"
+    , Space
+    , Str "if"
+    , Space
+    , Str "not"
+    , Space
+    , Str "specified"
+    , Space
+    , Str "in"
+    , Space
+    , Str "EXCLUDE"
+    , Subscript [ Str "TAGS" ]
+    , Space
+    , Span
+        ( "" , [ "tag" ] , [ ( "tag-name" , "noexport" ) ] )
+        [ SmallCaps [ Str "noexport" ] ]
+    ]
+]
+```
diff --git a/test/command/4306.md b/test/command/4306.md
new file mode 100644
--- /dev/null
+++ b/test/command/4306.md
@@ -0,0 +1,22 @@
+```
+% pandoc -f latex -t native
+\documentclass{article}
+\usepackage{hyperref}
+\begin{document}
+The file id is \nolinkurl{ESP_123_5235}.
+\end{document}
+^D
+[ Para
+    [ Str "The"
+    , Space
+    , Str "file"
+    , Space
+    , Str "id"
+    , Space
+    , Str "is"
+    , Space
+    , Code ( "" , [] , [] ) "ESP_123_5235"
+    , Str "."
+    ]
+]
+```
diff --git a/test/command/4320.md b/test/command/4320.md
new file mode 100644
--- /dev/null
+++ b/test/command/4320.md
@@ -0,0 +1,29 @@
+```
+% pandoc -f native -t rst --wrap=none
+[Table ("",[],[]) (Caption Nothing
+ [])
+ [(AlignDefault,ColWidth 0.3)
+ ,(AlignDefault,ColWidth 0.3)]
+ (TableHead ("",[],[])
+ [Row ("",[],[])
+  [Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+   [Plain [Str "one"]]
+  ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+   [Plain [Str "two"]]]])
+ [(TableBody ("",[],[]) (RowHeadColumns 0)
+  []
+  [Row ("",[],[])
+   [Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "ports"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [BlockQuote
+     [Para [Strong [Str "thisIsGoingToBeTooLongAnyway"]]]]]])]
+ (TableFoot ("",[],[])
+ [])]
+^D
++--------------------+-------------------------------------+
+| one                | two                                 |
++====================+=====================================+
+| ports              |    **thisIsGoingToBeTooLongAnyway** |
++--------------------+-------------------------------------+
+```
diff --git a/test/command/4374.md b/test/command/4374.md
new file mode 100644
--- /dev/null
+++ b/test/command/4374.md
@@ -0,0 +1,20 @@
+```
+% pandoc -f latex -t native
+\cite{a%
+}
+^D
+[ Para
+    [ Cite
+        [ Citation
+            { citationId = "a"
+            , citationPrefix = []
+            , citationSuffix = []
+            , citationMode = NormalCitation
+            , citationNoteNum = 0
+            , citationHash = 0
+            }
+        ]
+        [ RawInline (Format "latex") "\\cite{a%\n}" ]
+    ]
+]
+```
diff --git a/test/command/4382.md b/test/command/4382.md
new file mode 100644
--- /dev/null
+++ b/test/command/4382.md
@@ -0,0 +1,8 @@
+```
+% pandoc -f rst -t native
+-
+
+=====
+^D
+[ BulletList [ [] ] , HorizontalRule ]
+```
diff --git a/test/command/4420.md b/test/command/4420.md
new file mode 100644
--- /dev/null
+++ b/test/command/4420.md
@@ -0,0 +1,9 @@
+```
+% pandoc -f native -t rst
+[Para [Image ("",["align-right"],[("width","100px")]) [Str "image"] ("foo.png","fig:test")]]
+^D
+|image|
+
+.. |image| image:: foo.png
+   :width: 100px
+```
diff --git a/test/command/4424.md b/test/command/4424.md
new file mode 100644
--- /dev/null
+++ b/test/command/4424.md
@@ -0,0 +1,10 @@
+```
+% pandoc -f latex -t native
+\documentclass{article}
+\usepackage[sortlocale=en_GB]{biblatex}
+\begin{document}
+Test
+\end{document}
+^D
+[ Para [ Str "Test" ] ]
+```
diff --git a/test/command/4442.md b/test/command/4442.md
new file mode 100644
--- /dev/null
+++ b/test/command/4442.md
@@ -0,0 +1,9 @@
+```
+% pandoc -f markdown -t latex
+\newcommand{\myFruit}{Mango\xspace}
+\myFruit is the king of fruits.
+^D
+\newcommand{\myFruit}{Mango\xspace}
+
+Mango is the king of fruits.
+```
diff --git a/test/command/4454.md b/test/command/4454.md
new file mode 100644
--- /dev/null
+++ b/test/command/4454.md
@@ -0,0 +1,9 @@
+```
+% pandoc -f rst -t native
+• a
+• b
+^D
+[ BulletList
+    [ [ Plain [ Str "a" ] ] , [ Plain [ Str "b" ] ] ]
+]
+```
diff --git a/test/command/4465.md b/test/command/4465.md
new file mode 100644
--- /dev/null
+++ b/test/command/4465.md
@@ -0,0 +1,15 @@
+```
+% pandoc -f html -t markdown
+<ol>
+  <li>An ordered list can contain block-level elements ind html, it means that divs are also allowed.</li>
+  <li>Let's see the problem! <div class="example">This is an example.</div></li>
+</ol>
+^D
+1.  An ordered list can contain block-level elements ind html, it means
+    that divs are also allowed.
+2.  Let\'s see the problem!
+
+    ::: example
+    This is an example.
+    :::
+```
diff --git a/test/command/4470.md b/test/command/4470.md
new file mode 100644
--- /dev/null
+++ b/test/command/4470.md
@@ -0,0 +1,27 @@
+```
+% pandoc -r latex -w plain
+\newcommand{\foo}{123}\renewcommand\foo{456}\foo
+^D
+456
+```
+
+```
+% pandoc -r latex -w plain
+\newcommand\foo{123}\renewcommand\foo{456}\foo
+^D
+456
+```
+
+```
+% pandoc -r latex -w plain
+\newcommand{\foo}{123}\renewcommand{\foo}{456}\foo
+^D
+456
+```
+
+```
+% pandoc -r latex -w plain
+\newcommand\foo{123}\renewcommand{\foo}{456}\foo
+^D
+456
+```
diff --git a/test/command/4499.md b/test/command/4499.md
new file mode 100644
--- /dev/null
+++ b/test/command/4499.md
@@ -0,0 +1,87 @@
+```
+% pandoc -f latex -t html
+\mbox{abc def} ghi
+^D
+<p>abc def ghi</p>
+```
+
+```
+% pandoc -f latex+raw_tex -t native
+\mbox{abc def}
+^D
+[ Para [ RawInline (Format "latex") "\\mbox{abc def}" ] ]
+```
+
+```
+% pandoc -f latex -t html
+abc \mbox{\textit{def ghi} jkl} mno
+^D
+<p>abc <em>def ghi</em> jkl mno</p>
+```
+
+```
+% pandoc -f latex -t html
+abc \mbox{def \\ ghi} jkl
+^D
+<p>abc defghi jkl</p>
+```
+
+```
+% pandoc -f latex -t html
+abc \mbox{def
+ghi}
+^D
+<p>abc def ghi</p>
+```
+
+```
+% pandoc -f latex -t html
+abc \mbox{def \textit{ghi \\ jkl}
+mno} pqr
+^D
+<p>abc def <em>ghijkl</em> mno pqr</p>
+```
+
+```
+% pandoc -f latex -t html
+\hbox{abc def} ghi
+^D
+<p>abc def ghi</p>
+```
+
+```
+% pandoc -f latex+raw_tex -t native
+\hbox{abc def}
+^D
+[ Para [ RawInline (Format "latex") "\\hbox{abc def}" ] ]
+```
+
+```
+% pandoc -f latex -t html
+abc \hbox{\textit{def ghi} jkl} mno
+^D
+<p>abc <em>def ghi</em> jkl mno</p>
+```
+
+```
+% pandoc -f latex -t html
+abc \hbox{def \\ ghi} jkl
+^D
+<p>abc defghi jkl</p>
+```
+
+```
+% pandoc -f latex -t html
+abc \hbox{def
+ghi}
+^D
+<p>abc def ghi</p>
+```
+
+```
+% pandoc -f latex -t html
+abc \hbox{def \textit{ghi \\ jkl}
+mno} pqr
+^D
+<p>abc def <em>ghijkl</em> mno pqr</p>
+```
diff --git a/test/command/4513.md b/test/command/4513.md
new file mode 100644
--- /dev/null
+++ b/test/command/4513.md
@@ -0,0 +1,32 @@
+```
+% pandoc -f textile -t native
+|_. heading 1 |_. heading 2|
+^D
+[ Table
+    ( "" , [] , [] )
+    (Caption Nothing [])
+    [ ( AlignDefault , ColWidthDefault )
+    , ( AlignDefault , ColWidthDefault )
+    ]
+    (TableHead
+       ( "" , [] , [] )
+       [ Row
+           ( "" , [] , [] )
+           [ Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "heading" , Space , Str "1" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "heading" , Space , Str "2" ] ]
+           ]
+       ])
+    [ TableBody ( "" , [] , [] ) (RowHeadColumns 0) [] [] ]
+    (TableFoot ( "" , [] , [] ) [])
+]
+```
diff --git a/test/command/4527.md b/test/command/4527.md
new file mode 100644
--- /dev/null
+++ b/test/command/4527.md
@@ -0,0 +1,23 @@
+This command comes through as regular text:
+```
+% pandoc -f latex+raw_tex -t native
+\maketitle
+^D
+[ RawBlock (Format "latex") "\\maketitle" ]
+```
+
+
+```
+% pandoc -f latex -t native
+\maketitle
+^D
+[]
+```
+
+```
+% pandoc -f latex -t rst
+\maketitle
+Hello.
+^D
+Hello.
+```
diff --git a/test/command/4528.md b/test/command/4528.md
new file mode 100644
--- /dev/null
+++ b/test/command/4528.md
@@ -0,0 +1,156 @@
+# Rendering small caps, superscripts and subscripts with and without `raw_html`
+
+## Small caps
+
+```
+% pandoc --wrap=none -f latex -t commonmark-raw_html
+This has \textsc{small caps} in it.
+^D
+This has SMALL CAPS in it.
+```
+
+```
+% pandoc --wrap=none -f latex -t commonmark+raw_html
+This has \textsc{small caps} in it.
+^D
+This has <span class="smallcaps">small caps</span> in it.
+```
+
+```
+% pandoc --wrap=none -f latex -t markdown_strict+raw_html
+This has \textsc{small caps} in it.
+^D
+This has <span class="smallcaps">small caps</span> in it.
+```
+
+## Strikeout
+
+```
+% pandoc --wrap=none -f html -t commonmark-raw_html-strikeout
+This has <s>strikeout</s> in it.
+^D
+This has strikeout in it.
+```
+
+```
+% pandoc --wrap=none -f html -t commonmark+raw_html-strikeout
+This has <s>strikeout</s> in it.
+^D
+This has <s>strikeout</s> in it.
+```
+
+```
+% pandoc --wrap=none -f html -t commonmark-raw_html+strikeout
+This has <s>strikeout</s> in it.
+^D
+This has ~~strikeout~~ in it.
+```
+
+```
+% pandoc --wrap=none -f html -t commonmark+raw_html+strikeout
+This has <s>strikeout</s> in it.
+^D
+This has ~~strikeout~~ in it.
+```
+
+```
+% pandoc --wrap=none -f html -t markdown_strict-raw_html-strikeout
+This has <s>strikeout</s> in it.
+^D
+This has strikeout in it.
+```
+
+```
+% pandoc --wrap=none -f html -t markdown_strict+raw_html-strikeout
+This has <s>strikeout</s> in it.
+^D
+This has <s>strikeout</s> in it.
+```
+
+```
+% pandoc --wrap=none -f html -t markdown_strict-raw_html+strikeout
+This has <s>strikeout</s> in it.
+^D
+This has ~~strikeout~~ in it.
+```
+
+```
+% pandoc --wrap=none -f html -t markdown_strict+raw_html+strikeout
+This has <s>strikeout</s> in it.
+^D
+This has ~~strikeout~~ in it.
+```
+
+## Superscript
+
+```
+% pandoc --wrap=none -f html -t commonmark-raw_html
+This has <sup>superscript</sup> in it and <sup>2 3</sup> again. With emphasis: <sup><em>2</em> 3</sup>. With letters: <sup>foo</sup>. With a span: <sup><span class=foo>2</span></sup>.
+^D
+This has ^(superscript) in it and ² ³ again. With emphasis: ^(*2* 3). With letters: ^(foo). With a span: ².
+```
+
+```
+% pandoc --wrap=none -f html -t commonmark+raw_html
+This has <sup>superscript</sup> in it and <sup>2</sup> again.
+^D
+This has <sup>superscript</sup> in it and <sup>2</sup> again.
+```
+
+```
+% pandoc --wrap=none -f html -t markdown_strict-raw_html-superscript
+This has <sup>superscript</sup> in it and <sup>2</sup> again.
+^D
+This has ^(superscript) in it and ² again.
+```
+
+```
+% pandoc --wrap=none -f html -t markdown_strict+raw_html-superscript
+This has <sup>superscript</sup> in it and <sup>2</sup> again.
+^D
+This has <sup>superscript</sup> in it and <sup>2</sup> again.
+```
+
+```
+% pandoc --wrap=none -f html -t markdown_strict+raw_html+superscript
+This has <sup>superscript</sup> in it and <sup>2</sup> again.
+^D
+This has ^superscript^ in it and ^2^ again.
+```
+
+## Subscript
+
+```
+% pandoc --wrap=none -f html -t commonmark-raw_html
+This has <sub>subscript</sub> in it and <sub>2 3</sub> again. With emphasis: <sub><em>2</em> 3</sub>. With letters: <sub>foo</sub>. With a span: <sub><span class=foo>2</span></sub>.
+^D
+This has _(subscript) in it and ₂ ₃ again. With emphasis: _(*2* 3). With letters: _(foo). With a span: ₂.
+```
+
+```
+% pandoc --wrap=none -f html -t commonmark+raw_html
+This has <sub>subscript</sub> in it and <sub>2</sub> again.
+^D
+This has <sub>subscript</sub> in it and <sub>2</sub> again.
+```
+
+```
+% pandoc --wrap=none -f html -t markdown_strict-raw_html-subscript
+This has <sub>subscript</sub> in it and <sub>2</sub> again.
+^D
+This has _(subscript) in it and ₂ again.
+```
+
+```
+% pandoc --wrap=none -f html -t markdown_strict+raw_html-subscript
+This has <sub>subscript</sub> in it and <sub>2</sub> again.
+^D
+This has <sub>subscript</sub> in it and <sub>2</sub> again.
+```
+
+```
+% pandoc --wrap=none -f html -t markdown_strict+raw_html+subscript
+This has <sub>subscript</sub> in it and <sub>2</sub> again.
+^D
+This has ~subscript~ in it and ~2~ again.
+```
diff --git a/test/command/4529.md b/test/command/4529.md
new file mode 100644
--- /dev/null
+++ b/test/command/4529.md
@@ -0,0 +1,36 @@
+```
+% pandoc -f latex -t plain+gutenberg
+\chapter{First chapter}\label{sec:chp1}
+The next chapter is Chapter~\ref{sec:chp2}.
+\section{First section}\label{sec:chp1sec1}
+The next section is Section~\ref{sec:chp2sec1}.
+
+\chapter{Second chapter}\label{sec:chp2}
+The previous chapter is Chapter~\ref{sec:chp1}.
+\section{First section}\label{sec:chp2sec1}
+The previous section is Section~\ref{sec:chp1sec1}.
+^D
+
+
+FIRST CHAPTER
+
+
+The next chapter is Chapter 2.
+
+
+First section
+
+The next section is Section 2.1.
+
+
+
+SECOND CHAPTER
+
+
+The previous chapter is Chapter 1.
+
+
+First section
+
+The previous section is Section 1.1.
+```
diff --git a/test/command/4545.md b/test/command/4545.md
new file mode 100644
--- /dev/null
+++ b/test/command/4545.md
@@ -0,0 +1,20 @@
+```
+% pandoc -t asciidoc
+Test 1
+
+[my text]
+
+Test 2
+^D
+Test 1
+
+++[++my text++]++
+
+Test 2
+```
+```
+% pandoc -t asciidoc
+4\. foo
+^D
+{empty}4. foo
+```
diff --git a/test/command/4550.md b/test/command/4550.md
new file mode 100644
--- /dev/null
+++ b/test/command/4550.md
@@ -0,0 +1,7 @@
+```
+% pandoc -f markdown-smart -t ms
+A ‘simple’ example
+^D
+.LP
+A \(oqsimple\(cq example
+```
diff --git a/test/command/4553.md b/test/command/4553.md
new file mode 100644
--- /dev/null
+++ b/test/command/4553.md
@@ -0,0 +1,21 @@
+```
+% pandoc -f latex -t native
+foo \include{command/bar}
+^D
+[ Para [ Str "foo" ]
+, Para [ Emph [ Str "hi" , Space , Str "there" ] ]
+]
+```
+
+```
+% pandoc -f latex -t native
+foo \input{command/bar}
+^D
+[ Para
+    [ Str "foo"
+    , Space
+    , Emph [ Str "hi" , Space , Str "there" ]
+    ]
+]
+```
+
diff --git a/test/command/4564.md b/test/command/4564.md
new file mode 100644
--- /dev/null
+++ b/test/command/4564.md
@@ -0,0 +1,58 @@
+```
+% pandoc -f native -t rst --list-tables
+[Table ("",[],[]) (Caption Nothing
+ [Plain [Str "Here",Space,Str "is",Space,Str "a",Space,Str "caption."]])
+ [(AlignDefault,ColWidth 0.1527777777777778)
+ ,(AlignDefault,ColWidth 0.1388888888888889)
+ ,(AlignDefault,ColWidth 0.16666666666666666)
+ ,(AlignDefault,ColWidth 0.375)]
+ (TableHead ("",[],[])
+ [Row ("",[],[])
+  [Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+   [Plain [Str "Centered",SoftBreak,Str "Header"]]
+  ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+   [Plain [Str "Left",SoftBreak,Str "Aligned"]]
+  ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+   [Plain [Str "Right",SoftBreak,Str "Aligned"]]
+  ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+   [Plain [Str "Default",Space,Str "aligned"]]]])
+ [(TableBody ("",[],[]) (RowHeadColumns 0)
+  []
+  [Row ("",[],[])
+   [Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "First"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain []]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "12.0"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "Example",Space,Str "of",Space,Str "a",Space,Str "row",Space,Str "that",SoftBreak,Str "spans",Space,Str "multiple",Space,Str "lines."]]]
+  ,Row ("",[],[])
+   [Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "Second"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "row"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "5.0"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "Here\8217s",Space,Str "another",Space,Str "one.",Space,Str "Note",SoftBreak,Str "the",Space,Str "blank",Space,Str "line",Space,Str "between",SoftBreak,Str "rows."]]]])]
+ (TableFoot ("",[],[])
+ [])]
+^D
+.. list-table:: Here is a caption.
+   :widths: 11 10 12 27
+   :header-rows: 1
+
+   * - Centered Header
+     - Left Aligned
+     - Right Aligned
+     - Default aligned
+   * - First
+     - 
+     - 12.0
+     - Example of a row that spans multiple lines.
+   * - Second
+     - row
+     - 5.0
+     - Here’s another one. Note the blank line between rows.
+```
diff --git a/test/command/4576.md b/test/command/4576.md
new file mode 100644
--- /dev/null
+++ b/test/command/4576.md
@@ -0,0 +1,6 @@
+```
+% pandoc -f latex -t native
+$\rho_\text{D$_2$O}=866$
+^D
+[ Para [ Math InlineMath "\\rho_\\text{D$_2$O}=866" ] ]
+```
diff --git a/test/command/4578.md b/test/command/4578.md
new file mode 100644
--- /dev/null
+++ b/test/command/4578.md
@@ -0,0 +1,14 @@
+```
+% pandoc -t markdown
+  ------ ------- --------------- ---------------------
+  One    row                12.0 Example of a row that
+                                 spans multiple lines.
+
+  ------ ------- --------------- ---------------------
+^D
+  ------ ------- --------------- ---------------------
+  One    row                12.0 Example of a row that
+                                 spans multiple lines.
+
+  ------ ------- --------------- ---------------------
+```
diff --git a/test/command/4579.md b/test/command/4579.md
new file mode 100644
--- /dev/null
+++ b/test/command/4579.md
@@ -0,0 +1,58 @@
+```
+% pandoc -f rst -t native
+.. list-table::
+  :header-rows: 1
+
+  * - Foo
+    - Bar
+  * - spam
+    - ham
+^D
+[ Table
+    ( "" , [] , [] )
+    (Caption Nothing [])
+    [ ( AlignDefault , ColWidthDefault )
+    , ( AlignDefault , ColWidthDefault )
+    ]
+    (TableHead
+       ( "" , [] , [] )
+       [ Row
+           ( "" , [] , [] )
+           [ Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "Foo" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "Bar" ] ]
+           ]
+       ])
+    [ TableBody
+        ( "" , [] , [] )
+        (RowHeadColumns 0)
+        []
+        [ Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "spam" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "ham" ] ]
+            ]
+        ]
+    ]
+    (TableFoot ( "" , [] , [] ) [])
+]
+```
diff --git a/test/command/4589.md b/test/command/4589.md
new file mode 100644
--- /dev/null
+++ b/test/command/4589.md
@@ -0,0 +1,14 @@
+```
+% pandoc -f markdown -t latex
+\newcommand{\one}[1]{#1}
+\newcommand{\two}[1]{#1}
+
+Formatting *is* working **here**. But sticking \one{two }\two{commands}
+together *breaks* formatting.
+^D
+\newcommand{\one}[1]{#1}
+\newcommand{\two}[1]{#1}
+
+Formatting \emph{is} working \textbf{here}. But sticking two commands
+together \emph{breaks} formatting.
+```
diff --git a/test/command/4594.md b/test/command/4594.md
new file mode 100644
--- /dev/null
+++ b/test/command/4594.md
@@ -0,0 +1,24 @@
+```
+% pandoc -f markdown -t latex
+Some **bold** text here.
+
+\begin{figure}[htbp]
+\centering
+\def\svgwidth{\columnwidth}
+\import{img/}{vectors.pdf_tex}
+\caption{Some caption.}
+\end{figure}
+
+Some *italic* text here.
+^D
+Some \textbf{bold} text here.
+
+\begin{figure}[htbp]
+\centering
+\def\svgwidth{\columnwidth}
+\import{img/}{vectors.pdf_tex}
+\caption{Some caption.}
+\end{figure}
+
+Some \emph{italic} text here.
+```
diff --git a/test/command/4598.md b/test/command/4598.md
new file mode 100644
--- /dev/null
+++ b/test/command/4598.md
@@ -0,0 +1,10 @@
+```
+% pandoc -f rst
+`x`__
+
+__ `xy`_
+
+.. _`xy`: http://xy.org
+^D
+<p><a href="http://xy.org">x</a></p>
+```
diff --git a/test/command/4624.md b/test/command/4624.md
new file mode 100644
--- /dev/null
+++ b/test/command/4624.md
@@ -0,0 +1,33 @@
+```
+% pandoc -f latex -t native
+\begin{Verbatim}[key1=value1]
+code1
+
+\end{Verbatim}
+
+
+\begin{lstlisting}[key2=value2]
+code2
+  
+\end{lstlisting}
+
+\begin{verbatim}
+code3
+\end{verbatim}
+
+\begin{verbatim}
+code4
+    \end{verbatim}
+
+\begin{verbatim}
+code5\end{verbatim}
+^D
+[ CodeBlock
+    ( "" , [] , [ ( "key1" , "value1" ) ] ) "code1\n"
+, CodeBlock
+    ( "" , [] , [ ( "key2" , "value2" ) ] ) "code2\n  "
+, CodeBlock ( "" , [] , [] ) "code3"
+, CodeBlock ( "" , [] , [] ) "code4"
+, CodeBlock ( "" , [] , [] ) "code5"
+]
+```
diff --git a/test/command/4635.md b/test/command/4635.md
new file mode 100644
--- /dev/null
+++ b/test/command/4635.md
@@ -0,0 +1,35 @@
+```
+% pandoc -f markdown -t native
+(cf.
+foo)
+^D
+[ Para [ Str "(cf." , SoftBreak , Str "foo)" ] ]
+```
+
+```
+% pandoc -f markdown -t native
+a (cf.
+foo)
+^D
+[ Para
+    [ Str "a" , Space , Str "(cf." , SoftBreak , Str "foo)" ]
+]
+```
+
+```
+% pandoc -f markdown -t native
+cf.
+foo
+^D
+[ Para [ Str "cf." , SoftBreak , Str "foo" ] ]
+```
+
+```
+% pandoc -f markdown -t native
+a cf.
+foo
+^D
+[ Para
+    [ Str "a" , Space , Str "cf." , SoftBreak , Str "foo" ]
+]
+```
diff --git a/test/command/4637.md b/test/command/4637.md
new file mode 100644
--- /dev/null
+++ b/test/command/4637.md
@@ -0,0 +1,6 @@
+```
+% pandoc -t latex
+more \indextext{dogs}' than \indextext{cats}'
+^D
+more \indextext{dogs}' than \indextext{cats}'
+```
diff --git a/test/command/4639.md b/test/command/4639.md
new file mode 100644
--- /dev/null
+++ b/test/command/4639.md
@@ -0,0 +1,10 @@
+```
+% pandoc -t html --mathjax
+\begin{equation}
+  E=mc^2
+\end{equation}
+^D
+<p><span class="math display">\[\begin{equation}
+  E=mc^2
+\end{equation}\]</span></p>
+```
diff --git a/test/command/4653.md b/test/command/4653.md
new file mode 100644
--- /dev/null
+++ b/test/command/4653.md
@@ -0,0 +1,8 @@
+```
+% pandoc -t latex
+\let\tex\TeX
+\renewcommand{\TeX}{\tex\xspace}
+^D
+\let\tex\TeX
+\renewcommand{\TeX}{\tex\xspace}
+```
diff --git a/test/command/4667.md b/test/command/4667.md
new file mode 100644
--- /dev/null
+++ b/test/command/4667.md
@@ -0,0 +1,20 @@
+```
+% pandoc -t latex
+---
+header-includes:
+- \newcommand{\blandscape}{\begin{landscape}}
+- \newcommand{\elandscape}{\end{landscape}}
+...
+
+\blandscape
+
+testing
+
+\elandscape
+^D
+\begin{landscape}
+
+testing
+
+\end{landscape}
+```
diff --git a/test/command/4669.md b/test/command/4669.md
new file mode 100644
--- /dev/null
+++ b/test/command/4669.md
@@ -0,0 +1,33 @@
+```
+% pandoc -f latex -t native
+{\tt <-}
+
+\begin{verbatim}
+  while (n > 0) {
+\end{verbatim}
+^D
+[ Para
+    [ Span ( "" , [] , [] ) [ Code ( "" , [] , [] ) "<-" ] ]
+, CodeBlock ( "" , [] , [] ) "  while (n > 0) {"
+]
+```
+
+```
+% pandoc -f latex -t native
+\begin{itemize}
+\item<1> one
+\item<2-3,5> two
+\item<2| @alert> three
+\item<handout> four
+\item<beamer:2> five
+\end{itemize}
+^D
+[ BulletList
+    [ [ Para [ Str "one" ] ]
+    , [ Para [ Str "two" ] ]
+    , [ Para [ Str "three" ] ]
+    , [ Para [ Str "four" ] ]
+    , [ Para [ Str "five" ] ]
+    ]
+]
+```
diff --git a/test/command/4677.md b/test/command/4677.md
new file mode 100644
--- /dev/null
+++ b/test/command/4677.md
@@ -0,0 +1,9 @@
+```
+% pandoc --to "markdown-bracketed_spans-fenced_divs-link_attributes-simple_tables-multiline_tables-grid_tables-pipe_tables-fenced_code_attributes-markdown_in_html_blocks-table_captions-smart"
+![Caption](img.png){#img:1}
+^D
+<figure id="img:1">
+<img src="img.png" alt="Caption" />
+<figcaption aria-hidden="true">Caption</figcaption>
+</figure>
+```
diff --git a/test/command/4690.md b/test/command/4690.md
new file mode 100644
--- /dev/null
+++ b/test/command/4690.md
@@ -0,0 +1,26 @@
+```
+% pandoc -t beamer
+# title
+
+:::: {.columns}
+::: {.column width="8%"}
+content
+:::
+::: {.column width="84%"}
+content2
+:::
+::::
+^D
+\begin{frame}{title}
+\protect\phantomsection\label{title}
+\begin{columns}[T]
+\begin{column}{0.08\linewidth}
+content
+\end{column}
+
+\begin{column}{0.84\linewidth}
+content2
+\end{column}
+\end{columns}
+\end{frame}
+```
diff --git a/test/command/4715.md b/test/command/4715.md
new file mode 100644
--- /dev/null
+++ b/test/command/4715.md
@@ -0,0 +1,31 @@
+```
+% pandoc -f rst -t native
+.. toctree::
+   :name: tree1
+   :class: foo bar
+   :caption: Indice dei contenuti
+   :numbered:
+   :maxdepth: 3
+
+   premessa.rst
+   acquisizione-software.rst
+   riuso-software.rst
+^D
+[ Div
+    ( "tree1"
+    , [ "toctree" , "foo" , "bar" ]
+    , [ ( "caption" , "Indice dei contenuti" )
+      , ( "numbered" , "" )
+      , ( "maxdepth" , "3" )
+      ]
+    )
+    [ Para
+        [ Str "premessa.rst"
+        , SoftBreak
+        , Str "acquisizione-software.rst"
+        , SoftBreak
+        , Str "riuso-software.rst"
+        ]
+    ]
+]
+ ```
diff --git a/test/command/4722.md b/test/command/4722.md
new file mode 100644
--- /dev/null
+++ b/test/command/4722.md
@@ -0,0 +1,46 @@
+```
+% pandoc -f tikiwiki -t native
+*Level 1
+*Level 1
+**Level 2
+***Level 3
+*Level 1
+^D
+[ BulletList
+    [ [ Plain [ Str "Level" , Space , Str "1" ] ]
+    , [ Plain [ Str "Level" , Space , Str "1" ]
+      , BulletList
+          [ [ Plain [ Str "Level" , Space , Str "2" ]
+            , BulletList [ [ Plain [ Str "Level" , Space , Str "3" ] ] ]
+            ]
+          ]
+      ]
+    , [ Plain [ Str "Level" , Space , Str "1" ] ]
+    ]
+]
+```
+```
+% pandoc -f tikiwiki -t native
+#Level 1
+#Level 1
+##Level 2
+###Level 3
+#Level 1
+^D
+[ OrderedList
+    ( 1 , DefaultStyle , DefaultDelim )
+    [ [ Plain [ Str "Level" , Space , Str "1" ] ]
+    , [ Plain [ Str "Level" , Space , Str "1" ]
+      , OrderedList
+          ( 1 , DefaultStyle , DefaultDelim )
+          [ [ Plain [ Str "Level" , Space , Str "2" ]
+            , OrderedList
+                ( 1 , DefaultStyle , DefaultDelim )
+                [ [ Plain [ Str "Level" , Space , Str "3" ] ] ]
+            ]
+          ]
+      ]
+    , [ Plain [ Str "Level" , Space , Str "1" ] ]
+    ]
+]
+```
diff --git a/test/command/4742.md b/test/command/4742.md
new file mode 100644
--- /dev/null
+++ b/test/command/4742.md
@@ -0,0 +1,62 @@
+Check that the commonmark reader handles the `ascii_identifiers`
+extension properly.
+
+```
+% pandoc -f commonmark+gfm_auto_identifiers+ascii_identifiers -t native
+# non ascii ⚠️ räksmörgås
+^D
+[ Header
+    1
+    ( "non-ascii-warning-raksmorgas" , [] , [] )
+    [ Str "non"
+    , Space
+    , Str "ascii"
+    , Space
+    , Str "\9888\65039"
+    , Space
+    , Str "r\228ksm\246rg\229s"
+    ]
+]
+```
+
+Note that the emoji here is actually a composite character,
+formed from \9888 and \65039. The latter is a combining mark,
+so it survives...
+
+```
+% pandoc -f commonmark+gfm_auto_identifiers-ascii_identifiers -t native
+# non ascii ⚠️ räksmörgås
+^D
+[ Header
+    1
+    ( "non-ascii-warning-r\228ksm\246rg\229s" , [] , [] )
+    [ Str "non"
+    , Space
+    , Str "ascii"
+    , Space
+    , Str "\9888\65039"
+    , Space
+    , Str "r\228ksm\246rg\229s"
+    ]
+]
+```
+
+`gfm` should have `ascii_identifiers` disabled by default.
+
+```
+% pandoc -f gfm -t native
+# non ascii ⚠️ räksmörgås
+^D
+[ Header
+    1
+    ( "non-ascii-warning-r\228ksm\246rg\229s" , [] , [] )
+    [ Str "non"
+    , Space
+    , Str "ascii"
+    , Space
+    , Str "\9888\65039"
+    , Space
+    , Str "r\228ksm\246rg\229s"
+    ]
+]
+```
diff --git a/test/command/4743.md b/test/command/4743.md
new file mode 100644
--- /dev/null
+++ b/test/command/4743.md
@@ -0,0 +1,47 @@
+Test that emojis are wrapped in Span
+
+```
+% pandoc -f commonmark+emoji -t native
+My:thumbsup:emoji:heart:
+^D
+[ Para
+    [ Str "My"
+    , Span
+        ( "" , [ "emoji" ] , [ ( "data-emoji" , "thumbsup" ) ] )
+        [ Str "\128077" ]
+    , Str "emoji"
+    , Span
+        ( "" , [ "emoji" ] , [ ( "data-emoji" , "heart" ) ] )
+        [ Str "\10084\65039" ]
+    ]
+]
+```
+
+```
+% pandoc -f markdown+emoji -t native
+My:thumbsup:emoji:heart:
+^D
+[ Para
+    [ Str "My"
+    , Span
+        ( "" , [ "emoji" ] , [ ( "data-emoji" , "thumbsup" ) ] )
+        [ Str "\128077" ]
+    , Str "emoji"
+    , Span
+        ( "" , [ "emoji" ] , [ ( "data-emoji" , "heart" ) ] )
+        [ Str "\10084\65039" ]
+    ]
+]
+```
+
+```
+% pandoc -f commonmark+emoji -t html
+:zero: header
+=============
+My:thumbsup:emoji:heart:x :hearts: xyz
+^D
+<h1><span class="emoji" data-emoji="zero">0️⃣</span> header</h1>
+<p>My<span class="emoji" data-emoji="thumbsup">👍</span>emoji<span
+class="emoji" data-emoji="heart">❤️</span>x <span class="emoji"
+data-emoji="hearts">♥️</span> xyz</p>
+```
diff --git a/test/command/4746.md b/test/command/4746.md
new file mode 100644
--- /dev/null
+++ b/test/command/4746.md
@@ -0,0 +1,56 @@
+```
+% pandoc -f latex -t native
+\begin{tabular}{c c}
+  \begin{tabular}{c} a \\ \end{tabular}
+  &
+  \\
+\end{tabular}
+^D
+[ Table
+    ( "" , [] , [] )
+    (Caption Nothing [])
+    [ ( AlignCenter , ColWidthDefault )
+    , ( AlignCenter , ColWidthDefault )
+    ]
+    (TableHead ( "" , [] , [] ) [])
+    [ TableBody
+        ( "" , [] , [] )
+        (RowHeadColumns 0)
+        []
+        [ Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Table
+                    ( "" , [] , [] )
+                    (Caption Nothing [])
+                    [ ( AlignCenter , ColWidthDefault ) ]
+                    (TableHead ( "" , [] , [] ) [])
+                    [ TableBody
+                        ( "" , [] , [] )
+                        (RowHeadColumns 0)
+                        []
+                        [ Row
+                            ( "" , [] , [] )
+                            [ Cell
+                                ( "" , [] , [] )
+                                AlignDefault
+                                (RowSpan 1)
+                                (ColSpan 1)
+                                [ Plain [ Str "a" ] ]
+                            ]
+                        ]
+                    ]
+                    (TableFoot ( "" , [] , [] ) [])
+                ]
+            , Cell
+                ( "" , [] , [] ) AlignDefault (RowSpan 1) (ColSpan 1) []
+            ]
+        ]
+    ]
+    (TableFoot ( "" , [] , [] ) [])
+]
+```
diff --git a/test/command/4748.md b/test/command/4748.md
new file mode 100644
--- /dev/null
+++ b/test/command/4748.md
@@ -0,0 +1,16 @@
+```
+% pandoc -f org -t rst
+Before example block.
+#+begin_example
+This is in an example block.
+#+end_example
+After example block.
+^D
+Before example block.
+
+::
+
+   This is in an example block.
+
+After example block.
+```
diff --git a/test/command/4768.md b/test/command/4768.md
new file mode 100644
--- /dev/null
+++ b/test/command/4768.md
@@ -0,0 +1,7 @@
+```
+% pandoc -f latex -t plain
+\def\foo#1!#2!#3{#1 or #2 and #3}
+\foo aa!bbb bbb!{ccc}
+^D
+aa or bbb bbb and ccc
+```
diff --git a/test/command/4781.md b/test/command/4781.md
new file mode 100644
--- /dev/null
+++ b/test/command/4781.md
@@ -0,0 +1,40 @@
+```
+% pandoc -t native
+Markdown parsed *here*
+
+\include{command/bar}
+
+*But not here*
+^D
+[ Para
+    [ Str "Markdown"
+    , Space
+    , Str "parsed"
+    , Space
+    , Emph [ Str "here" ]
+    ]
+, RawBlock (Format "tex") "\\include{command/bar}"
+, Para
+    [ Emph
+        [ Str "But" , Space , Str "not" , Space , Str "here" ]
+    ]
+]
+```
+
+```
+% pandoc -t native
+*here* \input{command/bar}
+
+*But not here*
+^D
+[ Para
+    [ Emph [ Str "here" ]
+    , Space
+    , RawInline (Format "tex") "\\input{command/bar}"
+    ]
+, Para
+    [ Emph
+        [ Str "But" , Space , Str "not" , Space , Str "here" ]
+    ]
+]
+```
diff --git a/test/command/4794.md b/test/command/4794.md
new file mode 100644
--- /dev/null
+++ b/test/command/4794.md
@@ -0,0 +1,18 @@
+```
+% pandoc -f markdown -t mediawiki
+| Column1 | Column2 | Column3 |
+| ------- | ------- | ------- |
+| text    |         | text    |
+^D
+{| class="wikitable"
+|-
+! Column1
+! Column2
+! Column3
+|-
+| text
+|
+| text
+|}
+
+```
diff --git a/test/command/4805-beamer-columns-alignment.md b/test/command/4805-beamer-columns-alignment.md
new file mode 100644
--- /dev/null
+++ b/test/command/4805-beamer-columns-alignment.md
@@ -0,0 +1,40 @@
+```
+% pandoc -t beamer
+:::: { .columns }                                
+::: { .column align=center }
+:::
+::: { .column align=bottom }
+:::
+::::
+
+:::: { .columns align=bottom .onlytextwidth }
+::: { .column align=top }
+:::
+::: { .column align=top-baseline }
+:::
+::::
+
+:::: { .columns totalwidth=7em } 
+::::
+^D
+\begin{frame}
+\begin{columns}[T]
+\begin{column}[c]{0.48\linewidth}
+\end{column}
+
+\begin{column}[b]{0.48\linewidth}
+\end{column}
+\end{columns}
+
+\begin{columns}[b,onlytextwidth]
+\begin{column}[T]{0.48\linewidth}
+\end{column}
+
+\begin{column}[t]{0.48\linewidth}
+\end{column}
+\end{columns}
+
+\begin{columns}[T,totalwidth=7em]
+\end{columns}
+\end{frame}
+```
diff --git a/test/command/4811.md b/test/command/4811.md
new file mode 100644
--- /dev/null
+++ b/test/command/4811.md
@@ -0,0 +1,60 @@
+No blank lines in inline interpreted roles:
+
+```
+% pandoc -f rst -t native
+`no
+
+blank`:myrole:
+^D
+[ Para [ Str "`no" ] , Para [ Str "blank`:myrole:" ] ]
+```
+
+Backslash escape behaves properly in interpreted roles:
+
+```
+% pandoc -f rst -t native
+`hi\ there`:sup:
+
+`hi\ there`:code:
+^D
+[ Para [ Superscript [ Str "hithere" ] ]
+, Para [ Code ( "" , [] , [] ) "hi\\ there" ]
+]
+```
+
+Backtick followed by alphanumeric doesn't end the span:
+```
+% pandoc -f rst -t native
+`hi`there`:myrole:
+^D
+[ Para
+    [ Code
+        ( "" , [ "interpreted-text" ] , [ ( "role" , "myrole" ) ] )
+        "hi`there"
+    ]
+]
+```
+
+Newline is okay, as long as not blank:
+```
+% pandoc -f rst -t native
+`hi
+there`:myrole:
+^D
+[ Para
+    [ Code
+        ( "" , [ "interpreted-text" ] , [ ( "role" , "myrole" ) ] )
+        "hi\nthere"
+    ]
+]
+```
+
+Use span for title-reference:
+```
+% pandoc -f rst -t native
+`default`
+^D
+[ Para
+    [ Span ( "" , [ "title-ref" ] , [] ) [ Str "default" ] ]
+]
+```
diff --git a/test/command/4817.md b/test/command/4817.md
new file mode 100644
--- /dev/null
+++ b/test/command/4817.md
@@ -0,0 +1,21 @@
+```
+% pandoc -t native -s
+---
+foo:
+- bar: bam
+...
+^D
+Pandoc
+  Meta
+    { unMeta =
+        fromList
+          [ ( "foo"
+            , MetaList
+                [ MetaMap
+                    (fromList [ ( "bar" , MetaInlines [ Str "bam" ] ) ])
+                ]
+            )
+          ]
+    }
+  []
+```
diff --git a/test/command/4819.md b/test/command/4819.md
new file mode 100644
--- /dev/null
+++ b/test/command/4819.md
@@ -0,0 +1,55 @@
+```
+% pandoc -f markdown -t native -s
+---
+foo: 42
+...
+^D
+Pandoc
+  Meta
+    { unMeta = fromList [ ( "foo" , MetaInlines [ Str "42" ] ) ]
+    }
+  []
+```
+
+```
+% pandoc -f markdown -t native -s
+---
+foo: true
+...
+^D
+Pandoc
+  Meta { unMeta = fromList [ ( "foo" , MetaBool True ) ] } []
+```
+
+```
+% pandoc -f markdown -t native -s
+---
+foo: True
+...
+^D
+Pandoc
+  Meta { unMeta = fromList [ ( "foo" , MetaBool True ) ] } []
+```
+
+```
+% pandoc -f markdown -t native -s
+---
+foo: FALSE
+...
+^D
+Pandoc
+  Meta { unMeta = fromList [ ( "foo" , MetaBool False ) ] }
+  []
+```
+
+```
+% pandoc -f markdown -t native -s
+---
+foo: no
+...
+^D
+Pandoc
+  Meta { unMeta = fromList [ ( "foo" , MetaBool False ) ] }
+  []
+```
+
diff --git a/test/command/4832.md b/test/command/4832.md
new file mode 100644
--- /dev/null
+++ b/test/command/4832.md
@@ -0,0 +1,39 @@
+```
+% pandoc -f latex -t native
+\url{http://example.com/foo%20bar.htm}
+^D
+[ Para
+    [ Link
+        ( "" , [ "uri" ] , [] )
+        [ Str "http://example.com/foo%20bar.htm" ]
+        ( "http://example.com/foo%20bar.htm" , "" )
+    ]
+]
+```
+
+```
+% pandoc -f latex -t native
+\url{http://example.com/foo{bar}.htm}
+^D
+[ Para
+    [ Link
+        ( "" , [ "uri" ] , [] )
+        [ Str "http://example.com/foo{bar}.htm" ]
+        ( "http://example.com/foo{bar}.htm" , "" )
+    ]
+]
+```
+
+```
+% pandoc -f latex -t native
+\href{http://example.com/foo%20bar}{Foobar}
+^D
+[ Para
+    [ Link
+        ( "" , [] , [] )
+        [ Str "Foobar" ]
+        ( "http://example.com/foo%20bar" , "" )
+    ]
+]
+```
+
diff --git a/test/command/4833.md b/test/command/4833.md
new file mode 100644
--- /dev/null
+++ b/test/command/4833.md
@@ -0,0 +1,20 @@
+```
+% pandoc -f native -t rst
+[Div ("",["warning"],[])
+ [Div ("",["title"],[])
+  [Para [Str "Warning"]]
+ ,Para [Str "Hi"]]]
+^D
+.. warning::
+
+   Hi
+```
+```
+% pandoc -f native -t rst
+[Div ("",["unknown"],[])
+ [Para [Str "Hi"]]]
+^D
+.. container:: unknown
+
+   Hi
+```
diff --git a/test/command/4842.md b/test/command/4842.md
new file mode 100644
--- /dev/null
+++ b/test/command/4842.md
@@ -0,0 +1,6 @@
+```
+% pandoc -f latex -t native
+\l
+^D
+[ Para [ Str "\322" ] ]
+```
diff --git a/test/command/4845.md b/test/command/4845.md
new file mode 100644
--- /dev/null
+++ b/test/command/4845.md
@@ -0,0 +1,21 @@
+```
+% pandoc -f html -t native
+x<a href="/foo"> leading trailing space </a>x
+^D
+[ Plain
+    [ Str "x"
+    , Space
+    , Link
+        ( "" , [] , [] )
+        [ Str "leading"
+        , Space
+        , Str "trailing"
+        , Space
+        , Str "space"
+        ]
+        ( "/foo" , "" )
+    , Space
+    , Str "x"
+    ]
+]
+```
diff --git a/test/command/4848.md b/test/command/4848.md
new file mode 100644
--- /dev/null
+++ b/test/command/4848.md
@@ -0,0 +1,92 @@
+```
+% pandoc -f latex -t native
+\enquote*{hi}
+^D
+[ Para [ Quoted SingleQuote [ Str "hi" ] ] ]
+```
+
+```
+% pandoc -f latex -t native
+\foreignquote{italian}{hi}
+^D
+[ Para
+    [ Quoted
+        DoubleQuote
+        [ Span ( "" , [] , [ ( "lang" , "it" ) ] ) [ Str "hi" ] ]
+    ]
+]
+```
+
+```
+% pandoc -f latex -t native
+\hyphenquote*{italian}{hi}
+^D
+[ Para
+    [ Quoted
+        SingleQuote
+        [ Span ( "" , [] , [ ( "lang" , "it" ) ] ) [ Str "hi" ] ]
+    ]
+]
+```
+
+```
+% pandoc -f latex -t native
+Lorem ipsum
+\blockquote{dolor sit amet}
+consectetuer.
+^D
+[ Para [ Str "Lorem" , Space , Str "ipsum" ]
+, BlockQuote
+    [ Para
+        [ Str "dolor" , Space , Str "sit" , Space , Str "amet" ]
+    ]
+, Para [ Str "consectetuer." ]
+]
+```
+
+```
+% pandoc -f latex -t native
+Lorem ipsum
+\blockcquote[198]{Knu86}{dolor sit amet}
+consectetuer.
+^D
+[ Para [ Str "Lorem" , Space , Str "ipsum" ]
+, BlockQuote
+    [ Para
+        [ Str "dolor" , Space , Str "sit" , Space , Str "amet" ]
+    , Para
+        [ Cite
+            [ Citation
+                { citationId = "Knu86"
+                , citationPrefix = []
+                , citationSuffix = [ Str "198" ]
+                , citationMode = NormalCitation
+                , citationNoteNum = 0
+                , citationHash = 0
+                }
+            ]
+            []
+        ]
+    ]
+, Para [ Str "consectetuer." ]
+]
+```
+
+```
+% pandoc -f latex -t native
+Lorem ipsum
+\foreignblockquote{italian}{dolor sit amet}
+consectetuer.
+^D
+[ Para [ Str "Lorem" , Space , Str "ipsum" ]
+, BlockQuote
+    [ Div
+        ( "" , [] , [ ( "lang" , "it" ) ] )
+        [ Para
+            [ Str "dolor" , Space , Str "sit" , Space , Str "amet" ]
+        ]
+    ]
+, Para [ Str "consectetuer." ]
+]
+```
+
diff --git a/test/command/4860.md b/test/command/4860.md
new file mode 100644
--- /dev/null
+++ b/test/command/4860.md
@@ -0,0 +1,20 @@
+```
+% pandoc -f rst -t native
+This is broken_.
+
+.. ***** REFERENCES FOLLOW *****
+.. _broken: http://google.com
+^D
+[ Para
+    [ Str "This"
+    , Space
+    , Str "is"
+    , Space
+    , Link
+        ( "" , [] , [] )
+        [ Str "broken" ]
+        ( "http://google.com" , "" )
+    , Str "."
+    ]
+]
+```
diff --git a/test/command/4877.md b/test/command/4877.md
new file mode 100644
--- /dev/null
+++ b/test/command/4877.md
@@ -0,0 +1,15 @@
+```
+% pandoc -f html -t native
+My <script type="math/tex">\mathcal{D}</script>
+^D
+[ Plain
+    [ Str "My" , Space , Math InlineMath "\\mathcal{D}" ]
+]
+```
+
+```
+% pandoc -f html -t native
+<script type="math/tex; mode=display">\mathcal{D}</script>
+^D
+[ Plain [ Math DisplayMath "\\mathcal{D}" ] ]
+```
diff --git a/test/command/4880.md b/test/command/4880.md
new file mode 100644
--- /dev/null
+++ b/test/command/4880.md
@@ -0,0 +1,7 @@
+```
+% pandoc -t latex
+$x=y%comment$
+^D
+\(x=y%comment
+\)
+```
diff --git a/test/command/4885.md b/test/command/4885.md
new file mode 100644
--- /dev/null
+++ b/test/command/4885.md
@@ -0,0 +1,8 @@
+```
+% pandoc -f org -t markdown
+This won't show the command.
+src_maxima[:exports none :results raw]{tex('integrate(sin((e^x)/pi),x,0,inf));} $$\int_{0}^{\infty }{\sin \left({{e^{x}}\over{\pi}}\right)\;dx}$$
+^D
+This won\'t show the command.
+$$\int_{0}^{\infty }{\sin \left({{e^{x}}\over{\pi}}\right)\;dx}$$
+```
diff --git a/test/command/4908.md b/test/command/4908.md
new file mode 100644
--- /dev/null
+++ b/test/command/4908.md
@@ -0,0 +1,16 @@
+```
+% pandoc -f markdown_mmd+fancy_lists+example_lists -t native -t plain
+(@) Example one
+(@) Example two
+
+some text
+
+(@) Example three
+^D
+(1) Example one
+(2) Example two
+
+some text
+
+(3) Example three
+```
diff --git a/test/command/4913.md b/test/command/4913.md
new file mode 100644
--- /dev/null
+++ b/test/command/4913.md
@@ -0,0 +1,34 @@
+```
+% pandoc -f markdown -t html
+[https://pandoc.org](https://pandoc.org)
+^D
+<p><a href="https://pandoc.org">https://pandoc.org</a></p>
+```
+
+```
+% pandoc -f markdown -t markdown
+[https://pandoc.org](https://pandoc.org)
+^D
+<https://pandoc.org>
+```
+
+```
+% pandoc -f markdown -t html
+<https://pandoc.org>
+^D
+<p><a href="https://pandoc.org" class="uri">https://pandoc.org</a></p>
+```
+
+```
+% pandoc -f markdown -t html
+<https://pandoc.org>{.foo}
+^D
+<p><a href="https://pandoc.org" class="foo">https://pandoc.org</a></p>
+```
+
+```
+% pandoc -f markdown -t html
+<me@example.com>
+^D
+<p><a href="mailto:me@example.com" class="email">me@example.com</a></p>
+```
diff --git a/test/command/4919.md b/test/command/4919.md
new file mode 100644
--- /dev/null
+++ b/test/command/4919.md
@@ -0,0 +1,17 @@
+```
+% pandoc -f rst -t native
+.. _`tgtmath`:
+
+  .. math::
+     :name:
+
+     V = \frac{K}{r^2}
+^D
+[ Div
+    ( "tgtmath" , [] , [] )
+    [ BlockQuote
+        [ Para [ Math DisplayMath "V = \\frac{K}{r^2}" ] ]
+    ]
+]
+```
+
diff --git a/test/command/4928.md b/test/command/4928.md
new file mode 100644
--- /dev/null
+++ b/test/command/4928.md
@@ -0,0 +1,221 @@
+```
+% pandoc -f latex -t native
+\cites(Multiprenote)(multipostnote)[23][42]{Knu86}[65]{Nie72}
+^D
+[ Para
+    [ Cite
+        [ Citation
+            { citationId = "Knu86"
+            , citationPrefix = [ Str "Multiprenote" , Space , Str "23" ]
+            , citationSuffix = [ Str "42" ]
+            , citationMode = NormalCitation
+            , citationNoteNum = 0
+            , citationHash = 0
+            }
+        , Citation
+            { citationId = "Nie72"
+            , citationPrefix = []
+            , citationSuffix =
+                [ Str "65" , Str "," , Space , Str "multipostnote" ]
+            , citationMode = NormalCitation
+            , citationNoteNum = 0
+            , citationHash = 0
+            }
+        ]
+        [ RawInline
+            (Format "latex")
+            "\\cites(Multiprenote)(multipostnote)[23][42]{Knu86}[65]{Nie72}"
+        ]
+    ]
+]
+```
+
+```
+% pandoc -f latex -t native
+\cites(Multiprenote)()[23][42]{Knu86}[65]{Nie72}
+^D
+[ Para
+    [ Cite
+        [ Citation
+            { citationId = "Knu86"
+            , citationPrefix = [ Str "Multiprenote" , Space , Str "23" ]
+            , citationSuffix = [ Str "42" ]
+            , citationMode = NormalCitation
+            , citationNoteNum = 0
+            , citationHash = 0
+            }
+        , Citation
+            { citationId = "Nie72"
+            , citationPrefix = []
+            , citationSuffix = [ Str "65" ]
+            , citationMode = NormalCitation
+            , citationNoteNum = 0
+            , citationHash = 0
+            }
+        ]
+        [ RawInline
+            (Format "latex")
+            "\\cites(Multiprenote)()[23][42]{Knu86}[65]{Nie72}"
+        ]
+    ]
+]
+```
+
+```
+% pandoc -f latex -t native
+\cites()(multipostnote)[23][42]{Knu86}[65]{Nie72}
+^D
+[ Para
+    [ Cite
+        [ Citation
+            { citationId = "Knu86"
+            , citationPrefix = [ Str "23" ]
+            , citationSuffix = [ Str "42" ]
+            , citationMode = NormalCitation
+            , citationNoteNum = 0
+            , citationHash = 0
+            }
+        , Citation
+            { citationId = "Nie72"
+            , citationPrefix = []
+            , citationSuffix =
+                [ Str "65" , Str "," , Space , Str "multipostnote" ]
+            , citationMode = NormalCitation
+            , citationNoteNum = 0
+            , citationHash = 0
+            }
+        ]
+        [ RawInline
+            (Format "latex")
+            "\\cites()(multipostnote)[23][42]{Knu86}[65]{Nie72}"
+        ]
+    ]
+]
+```
+
+```
+% pandoc -f latex -t native
+\cites()()[23][42]{Knu86}[65]{Nie72}
+^D
+[ Para
+    [ Cite
+        [ Citation
+            { citationId = "Knu86"
+            , citationPrefix = [ Str "23" ]
+            , citationSuffix = [ Str "42" ]
+            , citationMode = NormalCitation
+            , citationNoteNum = 0
+            , citationHash = 0
+            }
+        , Citation
+            { citationId = "Nie72"
+            , citationPrefix = []
+            , citationSuffix = [ Str "65" ]
+            , citationMode = NormalCitation
+            , citationNoteNum = 0
+            , citationHash = 0
+            }
+        ]
+        [ RawInline
+            (Format "latex") "\\cites()()[23][42]{Knu86}[65]{Nie72}"
+        ]
+    ]
+]
+```
+
+```
+% pandoc -f latex -t native
+\cites(multipostnote)[23][42]{Knu86}[65]{Nie72}
+^D
+[ Para
+    [ Cite
+        [ Citation
+            { citationId = "Knu86"
+            , citationPrefix = [ Str "23" ]
+            , citationSuffix = [ Str "42" ]
+            , citationMode = NormalCitation
+            , citationNoteNum = 0
+            , citationHash = 0
+            }
+        , Citation
+            { citationId = "Nie72"
+            , citationPrefix = []
+            , citationSuffix =
+                [ Str "65" , Str "," , Space , Str "multipostnote" ]
+            , citationMode = NormalCitation
+            , citationNoteNum = 0
+            , citationHash = 0
+            }
+        ]
+        [ RawInline
+            (Format "latex")
+            "\\cites(multipostnote)[23][42]{Knu86}[65]{Nie72}"
+        ]
+    ]
+]
+```
+
+```
+% pandoc -f latex -t native
+\cites(Multiprenote)(multipostnote){Knu86}
+^D
+[ Para
+    [ Cite
+        [ Citation
+            { citationId = "Knu86"
+            , citationPrefix = [ Str "Multiprenote" ]
+            , citationSuffix = [ Str "," , Space , Str "multipostnote" ]
+            , citationMode = NormalCitation
+            , citationNoteNum = 0
+            , citationHash = 0
+            }
+        ]
+        [ RawInline
+            (Format "latex")
+            "\\cites(Multiprenote)(multipostnote){Knu86}"
+        ]
+    ]
+]
+```
+
+```
+% pandoc -f latex -t native
+\footcites(Multiprenote)(multipostnote)[23][42]{Knu86}[65]{Nie72}
+^D
+[ Para
+    [ Note
+        [ Para
+            [ Cite
+                [ Citation
+                    { citationId = "Knu86"
+                    , citationPrefix =
+                        [ Str "Multiprenote" , Space , Str "23" ]
+                    , citationSuffix = [ Str "42" ]
+                    , citationMode = NormalCitation
+                    , citationNoteNum = 0
+                    , citationHash = 0
+                    }
+                , Citation
+                    { citationId = "Nie72"
+                    , citationPrefix = []
+                    , citationSuffix =
+                        [ Str "65"
+                        , Str ","
+                        , Space
+                        , Str "multipostnote"
+                        ]
+                    , citationMode = NormalCitation
+                    , citationNoteNum = 0
+                    , citationHash = 0
+                    }
+                ]
+                [ RawInline
+                    (Format "latex")
+                    "\\footcites(Multiprenote)(multipostnote)[23][42]{Knu86}[65]{Nie72}"
+                ]
+            , Str "."
+            ]
+        ]
+    ]
+]
+```
diff --git a/test/command/4933.md b/test/command/4933.md
new file mode 100644
--- /dev/null
+++ b/test/command/4933.md
@@ -0,0 +1,10 @@
+```
+% pandoc -f latex -t native
+\includegraphics{lalune}
+^D
+[ Para
+    [ Image
+        ( "" , [] , [] ) [ Str "image" ] ( "lalune.jpg" , "" )
+    ]
+]
+```
diff --git a/test/command/4960.md b/test/command/4960.md
new file mode 100644
--- /dev/null
+++ b/test/command/4960.md
@@ -0,0 +1,22 @@
+```
+% pandoc -t latex --biblatex
+[@a1;@a2;@a3]
+^D
+\autocite{a1,a2,a3}
+```
+
+```
+% pandoc -t latex --biblatex
+@a1 [@a2;@a3]
+^D
+\textcite{a1,a2,a3}
+```
+
+```
+% pandoc -t latex --biblatex
+[@a1, blah; @a2; see @a3]
+^D
+\autocites[blah]{a1}{a2}[see][]{a3}
+```
+
+
diff --git a/test/command/5010.md b/test/command/5010.md
new file mode 100644
--- /dev/null
+++ b/test/command/5010.md
@@ -0,0 +1,21 @@
+```
+% pandoc -f latex -t latex
+\(\left\{ \begin{matrix}
+y\,\,\,\, \geqq \,\,\, f\,(\, x\,)\,\, \\
+y\,\,\, \leqq \,\,\, g\,(\, x\,)\, \\
+\end{matrix} \right.\ \)
+^D
+\(\left\{ \begin{matrix}
+y\,\,\,\, \geqq \,\,\, f\,(\, x\,)\,\, \\
+y\,\,\, \leqq \,\,\, g\,(\, x\,)\, \\
+\end{matrix} \right.\ \)
+```
+
+```
+% pandoc -f markdown -t latex
+$x\ $
+^D
+\(x\ \)
+```
+
+
diff --git a/test/command/5014.md b/test/command/5014.md
new file mode 100644
--- /dev/null
+++ b/test/command/5014.md
@@ -0,0 +1,49 @@
+```
+% pandoc -f html -t native
+<table>
+  <thead>
+    <tr>
+        <td>Name</td>
+    </tr>
+  </thead>
+  <tbody>
+    <tr>
+        <td>Accounts</td>
+    </tr>
+    </tbody>
+</table>
+^D
+[ Table
+    ( "" , [] , [] )
+    (Caption Nothing [])
+    [ ( AlignDefault , ColWidthDefault ) ]
+    (TableHead
+       ( "" , [] , [] )
+       [ Row
+           ( "" , [] , [] )
+           [ Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "Name" ] ]
+           ]
+       ])
+    [ TableBody
+        ( "" , [] , [] )
+        (RowHeadColumns 0)
+        []
+        [ Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "Accounts" ] ]
+            ]
+        ]
+    ]
+    (TableFoot ( "" , [] , [] ) [])
+]
+```
diff --git a/test/command/5039.md b/test/command/5039.md
new file mode 100644
--- /dev/null
+++ b/test/command/5039.md
@@ -0,0 +1,27 @@
+```
+% pandoc -f man -t plain
+.ds foo bar
+.ds bar baz
+\*[\*[foo]]
+^D
+baz
+```
+
+```
+% pandoc -f man -t plain
+.ds foo [bar]
+.ds bar baz
+\*\*[foo]
+^D
+baz
+```
+
+```
+% pandoc -f man -t html
+.ds B-Font B
+.ds I-Font I
+.ds R-Font R
+\f\*[B-Font]certtool\fP
+^D
+<p><strong>certtool</strong></p>
+```
diff --git a/test/command/5050.md b/test/command/5050.md
new file mode 100644
--- /dev/null
+++ b/test/command/5050.md
@@ -0,0 +1,7 @@
+```
+% pandoc -t rst
+<unknown>
+x
+^D
+x
+```
diff --git a/test/command/5053.md b/test/command/5053.md
new file mode 100644
--- /dev/null
+++ b/test/command/5053.md
@@ -0,0 +1,14 @@
+```
+% pandoc
+—_legibility_—
+^D
+<p>—<em>legibility</em>—</p>
+```
+
+```
+% pandoc
+_filename_|_filetype_
+^D
+<p><em>filename</em>|<em>filetype</em></p>
+```
+
diff --git a/test/command/5071.md b/test/command/5071.md
new file mode 100644
--- /dev/null
+++ b/test/command/5071.md
@@ -0,0 +1,68 @@
+```
+% pandoc -f markdown -t html --number-sections
+## First section
+
+### Subhead
+
+##### Subhead with gap
+
+## Second section
+^D
+<h2 data-number="1" id="first-section"><span
+class="header-section-number">1</span> First section</h2>
+<h3 data-number="1.1" id="subhead"><span
+class="header-section-number">1.1</span> Subhead</h3>
+<h5 data-number="1.1.0.1" id="subhead-with-gap"><span
+class="header-section-number">1.1.0.1</span> Subhead with gap</h5>
+<h2 data-number="2" id="second-section"><span
+class="header-section-number">2</span> Second section</h2>
+
+```
+
+```
+% pandoc -f markdown -t html --number-sections
+## First section
+
+### Subhead
+
+# Higher-level section
+
+## Sub
+^D
+<h2 data-number="0.1" id="first-section"><span
+class="header-section-number">0.1</span> First section</h2>
+<h3 data-number="0.1.1" id="subhead"><span
+class="header-section-number">0.1.1</span> Subhead</h3>
+<h1 data-number="1" id="higher-level-section"><span
+class="header-section-number">1</span> Higher-level section</h1>
+<h2 data-number="1.1" id="sub"><span
+class="header-section-number">1.1</span> Sub</h2>
+```
+
+For backwards compatibility, we want it to work the old way,
+giving numbers like 0.1, when `--number-offset` is used:
+```
+% pandoc -f markdown -t html --number-sections --number-offset=2,2,2
+## First section
+
+### Subhead
+^D
+<h2 data-number="2.3" id="first-section"><span
+class="header-section-number">2.3</span> First section</h2>
+<h3 data-number="2.3.1" id="subhead"><span
+class="header-section-number">2.3.1</span> Subhead</h3>
+
+```
+
+```
+% pandoc -f markdown -t html --number-sections --number-offset=0,2,2
+## First section
+
+### Subhead
+^D
+<h2 data-number="0.3" id="first-section"><span
+class="header-section-number">0.3</span> First section</h2>
+<h3 data-number="0.3.1" id="subhead"><span
+class="header-section-number">0.3.1</span> Subhead</h3>
+
+```
diff --git a/test/command/5072.md b/test/command/5072.md
new file mode 100644
--- /dev/null
+++ b/test/command/5072.md
@@ -0,0 +1,14 @@
+```
+% pandoc -t latex -i
+1. one
+2. two
+^D
+\begin{enumerate}
+\def\labelenumi{\arabic{enumi}.}
+\tightlist
+\item
+  one
+\item
+  two
+\end{enumerate}
+```
diff --git a/test/command/5079.md b/test/command/5079.md
new file mode 100644
--- /dev/null
+++ b/test/command/5079.md
@@ -0,0 +1,35 @@
+```
+% pandoc -f html -t native
+<table>
+<tfoot>
+</tfoot>
+<tbody>
+<tr>
+<td>Cell</td>
+</tr>
+</tbody>
+</table>
+^D
+[ Table
+    ( "" , [] , [] )
+    (Caption Nothing [])
+    [ ( AlignDefault , ColWidthDefault ) ]
+    (TableHead ( "" , [] , [] ) [])
+    [ TableBody
+        ( "" , [] , [] )
+        (RowHeadColumns 0)
+        []
+        [ Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "Cell" ] ]
+            ]
+        ]
+    ]
+    (TableFoot ( "" , [] , [] ) [])
+]
+```
diff --git a/test/command/5080.md b/test/command/5080.md
new file mode 100644
--- /dev/null
+++ b/test/command/5080.md
@@ -0,0 +1,13 @@
+```
+% pandoc -t asciidoc
+[foo *bar*]{.small .red key=val}
+^D
+[.small .red]#foo _bar_#
+```
+
+```
+% pandoc -f html -t asciidoc
+<small>SMALL</small>
+^D
+[.small]#SMALL#
+```
diff --git a/test/command/5081.md b/test/command/5081.md
new file mode 100644
--- /dev/null
+++ b/test/command/5081.md
@@ -0,0 +1,8 @@
+```
+% pandoc -f rst
+Go to `g`_ `g <www.example.com>`_.
+^D
+<p>Go to <a href="www.example.com">g</a> <a
+href="www.example.com">g</a>.</p>
+
+```
diff --git a/test/command/5099.md b/test/command/5099.md
new file mode 100644
--- /dev/null
+++ b/test/command/5099.md
@@ -0,0 +1,29 @@
+```
+% pandoc -t native
+(@citation
+^D
+[ Para
+    [ Str "("
+    , Cite
+        [ Citation
+            { citationId = "citation"
+            , citationPrefix = []
+            , citationSuffix = []
+            , citationMode = AuthorInText
+            , citationNoteNum = 1
+            , citationHash = 0
+            }
+        ]
+        [ Str "@citation" ]
+    ]
+]
+```
+
+```
+% pandoc -t native
+('asd')
+^D
+[ Para
+    [ Str "(" , Quoted SingleQuote [ Str "asd" ] , Str ")" ]
+]
+```
diff --git a/test/command/5107.md b/test/command/5107.md
new file mode 100644
--- /dev/null
+++ b/test/command/5107.md
@@ -0,0 +1,23 @@
+```
+% pandoc -f muse -t dokuwiki
+ - foo
+   1. bar
+   - baz
+^D
+  * foo
+    - bar
+    * baz
+
+```
+```
+% pandoc -f muse -t dokuwiki
+ - foo
+   1. bar
+   2. baz
+^D
+  * foo
+    - bar
+    - baz
+
+```
+
diff --git a/test/command/5116.md b/test/command/5116.md
new file mode 100644
--- /dev/null
+++ b/test/command/5116.md
@@ -0,0 +1,107 @@
+```
+% pandoc -t latex
+![This is a figure.](img.jpg)
+
+  Right     Left     Center     Default
+-------     ------ ----------   -------
+     12     12        12            12
+    123     123       123          123
+      1     1          1             1
+
+  :  Demonstration of simple table syntax.
+^D
+\begin{figure}
+\centering
+\pandocbounded{\includegraphics[keepaspectratio,alt={This is a figure.}]{img.jpg}}
+\caption{This is a figure.}
+\end{figure}
+
+\begin{longtable}[]{@{}rlcl@{}}
+\caption{Demonstration of simple table syntax.}\tabularnewline
+\toprule\noalign{}
+Right & Left & Center & Default \\
+\midrule\noalign{}
+\endfirsthead
+\toprule\noalign{}
+Right & Left & Center & Default \\
+\midrule\noalign{}
+\endhead
+\bottomrule\noalign{}
+\endlastfoot
+12 & 12 & 12 & 12 \\
+123 & 123 & 123 & 123 \\
+1 & 1 & 1 & 1 \\
+\end{longtable}
+
+```
+
+```
+% pandoc -t latex --figure-caption-position=above --table-caption-position=above
+![This is a figure.](img.jpg)
+
+  Right     Left     Center     Default
+-------     ------ ----------   -------
+     12     12        12            12
+    123     123       123          123
+      1     1          1             1
+
+  :  Demonstration of simple table syntax.
+^D
+\begin{figure}
+\centering
+\caption{This is a figure.}
+\pandocbounded{\includegraphics[keepaspectratio,alt={This is a figure.}]{img.jpg}}
+\end{figure}
+
+\begin{longtable}[]{@{}rlcl@{}}
+\caption{Demonstration of simple table syntax.}\tabularnewline
+\toprule\noalign{}
+Right & Left & Center & Default \\
+\midrule\noalign{}
+\endfirsthead
+\toprule\noalign{}
+Right & Left & Center & Default \\
+\midrule\noalign{}
+\endhead
+\bottomrule\noalign{}
+\endlastfoot
+12 & 12 & 12 & 12 \\
+123 & 123 & 123 & 123 \\
+1 & 1 & 1 & 1 \\
+\end{longtable}
+
+```
+
+```
+% pandoc -t latex --figure-caption-position=below --table-caption-position=below
+![This is a figure.](img.jpg)
+
+  Right     Left     Center     Default
+-------     ------ ----------   -------
+     12     12        12            12
+    123     123       123          123
+      1     1          1             1
+
+  :  Demonstration of simple table syntax.
+^D
+\begin{figure}
+\centering
+\pandocbounded{\includegraphics[keepaspectratio,alt={This is a figure.}]{img.jpg}}
+\caption{This is a figure.}
+\end{figure}
+
+\begin{longtable}[]{@{}rlcl@{}}
+\toprule\noalign{}
+Right & Left & Center & Default \\
+\midrule\noalign{}
+\endhead
+\bottomrule\noalign{}
+\tabularnewline
+\caption{Demonstration of simple table syntax.}
+\endlastfoot
+12 & 12 & 12 & 12 \\
+123 & 123 & 123 & 123 \\
+1 & 1 & 1 & 1 \\
+\end{longtable}
+
+```
diff --git a/test/command/5119.md b/test/command/5119.md
new file mode 100644
--- /dev/null
+++ b/test/command/5119.md
@@ -0,0 +1,9 @@
+```
+% pandoc -t docbook
+h&#x4;i
+^D
+<para>
+  hi
+</para>
+```
+
diff --git a/test/command/512.md b/test/command/512.md
--- a/test/command/512.md
+++ b/test/command/512.md
@@ -8,7 +8,8 @@
 __ link1_
 __ link2_
 ^D
-<p><a href="http://www.example.com/">click here</a> or <a href="http://johnmacfarlane.net/pandoc/">click here</a></p>
+<p><a href="http://www.example.com/">click here</a> or <a
+href="http://johnmacfarlane.net/pandoc/">click here</a></p>
 ```
 
 Multiple indirection:
@@ -36,7 +37,7 @@
 
 __ link1_
 ^D
-[WARNING] Circular reference 'link1' at line 1 column 15
+2> [WARNING] Circular reference 'link1' at line 8 column 1
 <p><a href="">click here</a></p>
 ```
 
diff --git a/test/command/5121.md b/test/command/5121.md
new file mode 100644
--- /dev/null
+++ b/test/command/5121.md
@@ -0,0 +1,13 @@
+```
+% pandoc -f markdown -t markdown_strict
+![My caption](./my-figure.jpg){width=500px}
+
+## Header 2
+^D
+<figure>
+<img src="./my-figure.jpg" width="500" alt="My caption" />
+<figcaption aria-hidden="true">My caption</figcaption>
+</figure>
+
+## Header 2
+```
diff --git a/test/command/5128.md b/test/command/5128.md
new file mode 100644
--- /dev/null
+++ b/test/command/5128.md
@@ -0,0 +1,26 @@
+```
+% pandoc -f org -t rst --columns=78
+| Option | Meaning                                                                                                                                                                                                    |
+|--------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
+| =<=    | Left alignment, additional characters are added to the right (default for string).                                                                                                                         |
+| =>=     | Right alignment, additional characters are added to the left.                                                                                                                                              |
+| =^=     | Centered , the same amount of characters is added to the left and the right.                                                                                                                               |
+| ===      | Padding. If a numeric value is printed with a sign, then additional characters are added after the sign. Otherwise it behaves like "=>=". This option is only available for numbers (default for numbers). |
+^D
++--------+-------------------------------------------------------------------+
+| Option | Meaning                                                           |
++========+===================================================================+
+| ``<``  | Left alignment, additional characters are added to the right      |
+|        | (default for string).                                             |
++--------+-------------------------------------------------------------------+
+| ``>``  | Right alignment, additional characters are added to the left.     |
++--------+-------------------------------------------------------------------+
+| ``^``  | Centered , the same amount of characters is added to the left and |
+|        | the right.                                                        |
++--------+-------------------------------------------------------------------+
+| ``=``  | Padding. If a numeric value is printed with a sign, then          |
+|        | additional characters are added after the sign. Otherwise it      |
+|        | behaves like "``>``". This option is only available for numbers   |
+|        | (default for numbers).                                            |
++--------+-------------------------------------------------------------------+
+```
diff --git a/test/command/5177.md b/test/command/5177.md
new file mode 100644
--- /dev/null
+++ b/test/command/5177.md
@@ -0,0 +1,12 @@
+This should not give a "Prelude.read: no parse" error:
+
+```
+% pandoc -M foo=1e -s -t markdown
+hi
+^D
+---
+foo: 1e
+---
+
+hi
+```
diff --git a/test/command/5178.md b/test/command/5178.md
new file mode 100644
--- /dev/null
+++ b/test/command/5178.md
@@ -0,0 +1,52 @@
+```
+% pandoc -f rst -t org
+.. code:: haskell
+   :number-lines: 42
+
+   main = putStrLn "Hello World!"
+   unsafePerformIO main
+^D
+#+begin_src haskell -n 42
+main = putStrLn "Hello World!"
+unsafePerformIO main
+#+end_src
+```
+
+```
+% pandoc -f org -t native
+#+begin_src lisp -n 20
+  (+ 1 1)
+#+end_src
+
+#+begin_src lisp +n 10
+  (+ 2 2)
+#+end_src
+^D
+[ CodeBlock
+    ( ""
+    , [ "commonlisp" , "numberLines" ]
+    , [ ( "org-language" , "lisp" ) , ( "startFrom" , "20" ) ]
+    )
+    "(+ 1 1)\n"
+, CodeBlock
+    ( ""
+    , [ "commonlisp" , "numberLines" , "continuedSourceBlock" ]
+    , [ ( "org-language" , "lisp" ) , ( "startFrom" , "10" ) ]
+    )
+    "(+ 2 2)\n"
+]
+```
+
+```
+% pandoc -f native -t org
+[CodeBlock ("",["commonlisp","numberLines"],[("org-language","lisp"),("startFrom","20")]) "(+ 1 1)\n"
+,CodeBlock ("",["commonlisp","numberLines","continuedSourceBlock"],[("org-language","lisp"),("startFrom","10")]) "(+ 2 2)\n"]
+^D
+#+begin_src lisp -n 20
+(+ 1 1)
+#+end_src
+
+#+begin_src lisp +n 10
+(+ 2 2)
+#+end_src
+```
diff --git a/test/command/5182.md b/test/command/5182.md
new file mode 100644
--- /dev/null
+++ b/test/command/5182.md
@@ -0,0 +1,9 @@
+```
+% pandoc -f rst -t native
+.. include:: command/5182.txt
+^D
+[ CodeBlock
+    ( "" , [ "python" , "numberLines" ] , [] )
+    "def func(x):\n  return y"
+]
+```
diff --git a/test/command/5182.txt b/test/command/5182.txt
new file mode 100644
--- /dev/null
+++ b/test/command/5182.txt
@@ -0,0 +1,5 @@
+.. code::python
+   :number-lines:
+
+  def func(x):
+    return y
diff --git a/test/command/5195.md b/test/command/5195.md
new file mode 100644
--- /dev/null
+++ b/test/command/5195.md
@@ -0,0 +1,7 @@
+```
+% pandoc -f markdown_strict -t gfm+hard_line_breaks
+Hello
+there
+^D
+Hello there
+```
diff --git a/test/command/5233.md b/test/command/5233.md
new file mode 100644
--- /dev/null
+++ b/test/command/5233.md
@@ -0,0 +1,9 @@
+```
+% pandoc -f latex -t plain
+foo
+\endinput
+bar
+^D
+foo
+```
+
diff --git a/test/command/5241.md b/test/command/5241.md
new file mode 100644
--- /dev/null
+++ b/test/command/5241.md
@@ -0,0 +1,12 @@
+```
+% pandoc -f markdown -t html5
+<textarea>
+ one
+  *two*
+</textarea>
+^D
+<textarea>
+ one
+  *two*
+</textarea>
+```
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,41 @@
+```
+% 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,41 @@
+```
+% pandoc -f jats -t native
+<fig id="fig-1">
+  <caption>
+    <p>bar</p>
+  </caption>
+  <graphic xlink:href="foo.png">
+    <alt-text>baz</alt-text>
+  </graphic>
+</fig>
+^D
+[ Figure
+    ( "fig-1" , [] , [] )
+    (Caption Nothing [ Plain [ Str "bar" ] ])
+    [ Para
+        [ Image ( "" , [] , [] ) [ Str "baz" ] ( "foo.png" , "" ) ]
+    ]
+]
+```
+
+```
+% pandoc -f jats -t native
+<fig id="fig-1">
+  <caption>
+    <title>foo</title>
+    <p>bar</p>
+  </caption>
+    <graphic xlink:href="foo.png">
+      <alt-text>baz</alt-text>
+    </graphic>
+</fig>
+^D
+[ Figure
+    ( "fig-1" , [] , [] )
+    (Caption
+       Nothing [ Plain [ Str "foo" , LineBreak , Str "bar" ] ])
+    [ Para
+        [ Image ( "" , [] , [] ) [ Str "baz" ] ( "foo.png" , "" ) ]
+    ]
+]
+```
diff --git a/test/command/5340.md b/test/command/5340.md
new file mode 100644
--- /dev/null
+++ b/test/command/5340.md
@@ -0,0 +1,14 @@
+```
+% pandoc -f html -t latex --wrap=preserve
+<a href="https://example.com/foo-bar">https://example.com/foo-bar</a>
+<a href="https://example.com/foo--bar">https://example.com/foo--bar</a>
+<a href="https://example.com/foo%2Dbar">https://example.com/foo-bar</a>
+<a href="https://example.com/foo%2D%2Dbar">https://example.com/foo--bar</a>
+<a href="https://example.com/foo%2D%2Dbar">https://example.com/foo%2D%2Dbar</a>
+^D
+\url{https://example.com/foo-bar}
+\url{https://example.com/foo--bar}
+\url{https://example.com/foo\%2Dbar}
+\url{https://example.com/foo\%2D\%2Dbar}
+\url{https://example.com/foo\%2D\%2Dbar}
+```
diff --git a/test/command/5360.md b/test/command/5360.md
new file mode 100644
--- /dev/null
+++ b/test/command/5360.md
@@ -0,0 +1,22 @@
+```
+% pandoc -t native
+::: {.foo}
+<table>
+ <tr>
+  <td>hi</td>
+ </tr>
+</table>
+:::
+^D
+[ Div
+    ( "" , [ "foo" ] , [] )
+    [ RawBlock (Format "html") "<table>"
+    , RawBlock (Format "html") "<tr>"
+    , RawBlock (Format "html") "<td>"
+    , Plain [ Str "hi" ]
+    , RawBlock (Format "html") "</td>"
+    , RawBlock (Format "html") "</tr>"
+    , RawBlock (Format "html") "</table>"
+    ]
+]
+```
diff --git a/test/command/5367.md b/test/command/5367.md
new file mode 100644
--- /dev/null
+++ b/test/command/5367.md
@@ -0,0 +1,44 @@
+```
+% pandoc -t latex
+hello[^1]
+
+: Sample table.[^2]
+
+-----------
+ Fruit[^3]
+-----------
+ Bans[^4]
+-----------
+
+dolly[^5]
+
+[^1]: doc footnote
+[^2]: caption footnote
+[^3]: header footnote
+[^4]: table cell footnote
+[^5]: doc footnote
+^D
+hello\footnote{doc footnote}
+
+\begin{longtable}[]{@{}
+  >{\centering\arraybackslash}p{(\linewidth - 0\tabcolsep) * \real{0.1667}}@{}}
+\caption[Sample table.]{Sample table.\footnote{caption footnote}}\tabularnewline
+\toprule\noalign{}
+\begin{minipage}[b]{\linewidth}\centering
+Fruit\footnote{header footnote}
+\end{minipage} \\
+\midrule\noalign{}
+\endfirsthead
+\toprule\noalign{}
+\begin{minipage}[b]{\linewidth}\centering
+Fruit{}
+\end{minipage} \\
+\midrule\noalign{}
+\endhead
+\bottomrule\noalign{}
+\endlastfoot
+Bans\footnote{table cell footnote} \\
+\end{longtable}
+
+dolly\footnote{doc footnote}
+```
diff --git a/test/command/5368.md b/test/command/5368.md
new file mode 100644
--- /dev/null
+++ b/test/command/5368.md
@@ -0,0 +1,49 @@
+```
+% pandoc -t native
+1. foo
+
+    ![bar](bar.png)
+2. foo2
+
+    ![bar2](bar2.png)
+3. foo3
+
+    ![foo3](foo3.png)
+
+Quux.
+^D
+[ OrderedList
+    ( 1 , Decimal , Period )
+    [ [ Para [ Str "foo" ]
+      , Figure
+          ( "" , [] , [] )
+          (Caption Nothing [ Plain [ Str "bar" ] ])
+          [ Plain
+              [ Image ( "" , [] , [] ) [ Str "bar" ] ( "bar.png" , "" )
+              ]
+          ]
+      ]
+    , [ Para [ Str "foo2" ]
+      , Figure
+          ( "" , [] , [] )
+          (Caption Nothing [ Plain [ Str "bar2" ] ])
+          [ Plain
+              [ Image
+                  ( "" , [] , [] ) [ Str "bar2" ] ( "bar2.png" , "" )
+              ]
+          ]
+      ]
+    , [ Para [ Str "foo3" ]
+      , Figure
+          ( "" , [] , [] )
+          (Caption Nothing [ Plain [ Str "foo3" ] ])
+          [ Plain
+              [ Image
+                  ( "" , [] , [] ) [ Str "foo3" ] ( "foo3.png" , "" )
+              ]
+          ]
+      ]
+    ]
+, Para [ Str "Quux." ]
+]
+```
diff --git a/test/command/5369.md b/test/command/5369.md
new file mode 100644
--- /dev/null
+++ b/test/command/5369.md
@@ -0,0 +1,7 @@
+```
+% pandoc -f native -t markdown
+[Div ("",[],[("tags","[\"o\\ne\",\"two\"]")]) [] ]
+^D
+::: {tags="[\"o\\ne\",\"two\"]"}
+:::
+```
diff --git a/test/command/5407.md b/test/command/5407.md
new file mode 100644
--- /dev/null
+++ b/test/command/5407.md
@@ -0,0 +1,14 @@
+```
+% pandoc -t latex --wrap=preserve
+hi there?“
+hi there!“
+hi there?‘
+hi there!‘
+hi there!
+^D
+hi there?{\kern0pt}``
+hi there!{\kern0pt}``
+hi there?{\kern0pt}`
+hi there!{\kern0pt}`
+hi there!
+```
diff --git a/test/command/5410.md b/test/command/5410.md
new file mode 100644
--- /dev/null
+++ b/test/command/5410.md
@@ -0,0 +1,7 @@
+```
+% pandoc -f man -t native
+.ie n \{\
+'br\}
+^D
+[ Para [ LineBreak ] ]
+```
diff --git a/test/command/5416.md b/test/command/5416.md
new file mode 100644
--- /dev/null
+++ b/test/command/5416.md
@@ -0,0 +1,13 @@
+```
+% pandoc -f dokuwiki -t native
+{
+^D
+[ Para [ Str "{" ] ]
+```
+
+```
+% pandoc -f dokuwiki -t native
+{{
+^D
+[ Para [ Str "{{" ] ]
+```
diff --git a/test/command/5420.md b/test/command/5420.md
new file mode 100644
--- /dev/null
+++ b/test/command/5420.md
@@ -0,0 +1,6 @@
+```
+% pandoc --syntax-highlighting=idiomatic -t latex
+`int a = 1;`{.cpp style=cpp}
+^D
+\passthrough{\lstinline[language={C++}, style=cpp]!int a = 1;!}
+```
diff --git a/test/command/5439.md b/test/command/5439.md
new file mode 100644
--- /dev/null
+++ b/test/command/5439.md
@@ -0,0 +1,6 @@
+```
+% pandoc -t latex
+namespace\fshyp{}container
+^D
+namespace\fshyp{}container
+```
diff --git a/test/command/5446.md b/test/command/5446.md
new file mode 100644
--- /dev/null
+++ b/test/command/5446.md
@@ -0,0 +1,6 @@
+```
+% pandoc -f latex -t rst
+{\em test test \/}
+^D
+*test test*
+```
diff --git a/test/command/5474-figures.md b/test/command/5474-figures.md
new file mode 100644
--- /dev/null
+++ b/test/command/5474-figures.md
@@ -0,0 +1,15 @@
+```
+% pandoc -t opendocument+native_numbering
+
+![First image](lalune.jpg)
+
+![Second image](lalune.jpg)
+
+^D
+<text:p text:style-name="FigureWithCaption"><draw:frame draw:name="img1"><draw:image xlink:href="lalune.jpg" xlink:type="simple" xlink:show="embed" xlink:actuate="onLoad" /></draw:frame></text:p>
+<text:p text:style-name="FigureCaption">Figure <text:sequence text:ref-name="refIllustration0" text:name="Illustration" text:formula="ooow:Illustration+1" style:num-format="1">1</text:sequence>: First
+image</text:p>
+<text:p text:style-name="FigureWithCaption"><draw:frame draw:name="img2"><draw:image xlink:href="lalune.jpg" xlink:type="simple" xlink:show="embed" xlink:actuate="onLoad" /></draw:frame></text:p>
+<text:p text:style-name="FigureCaption">Figure <text:sequence text:ref-name="refIllustration1" text:name="Illustration" text:formula="ooow:Illustration+1" style:num-format="1">2</text:sequence>: Second
+image</text:p>
+```
diff --git a/test/command/5474-tables.md b/test/command/5474-tables.md
new file mode 100644
--- /dev/null
+++ b/test/command/5474-tables.md
@@ -0,0 +1,63 @@
+```
+% pandoc -t opendocument+native_numbering
+  Right     Left  
+-------     ------
+     12     11
+
+: First table
+
+  Right     Left  
+-------     ------
+     13     14    
+
+: Second Table
+^D
+<text:p text:style-name="TableCaption">Table <text:sequence text:ref-name="refTable0" text:name="Table" text:formula="ooow:Table+1" style:num-format="1">1</text:sequence>: First
+table</text:p>
+<table:table table:name="Table1" table:style-name="Table1">
+  <table:table-column table:style-name="Table1.A" />
+  <table:table-column table:style-name="Table1.B" />
+  <table:table-header-rows>
+    <table:table-row>
+      <table:table-cell table:style-name="TableHeaderRowCell" office:value-type="string">
+        <text:p text:style-name="P1">Right</text:p>
+      </table:table-cell>
+      <table:table-cell table:style-name="TableHeaderRowCell" office:value-type="string">
+        <text:p text:style-name="Table_20_Heading">Left</text:p>
+      </table:table-cell>
+    </table:table-row>
+  </table:table-header-rows>
+  <table:table-row>
+    <table:table-cell table:style-name="TableRowCell" office:value-type="string">
+      <text:p text:style-name="P2">12</text:p>
+    </table:table-cell>
+    <table:table-cell table:style-name="TableRowCell" office:value-type="string">
+      <text:p text:style-name="Table_20_Contents">11</text:p>
+    </table:table-cell>
+  </table:table-row>
+</table:table>
+<text:p text:style-name="TableCaption">Table <text:sequence text:ref-name="refTable1" text:name="Table" text:formula="ooow:Table+1" style:num-format="1">2</text:sequence>: Second
+Table</text:p>
+<table:table table:name="Table2" table:style-name="Table2">
+  <table:table-column table:style-name="Table2.A" />
+  <table:table-column table:style-name="Table2.B" />
+  <table:table-header-rows>
+    <table:table-row>
+      <table:table-cell table:style-name="TableHeaderRowCell" office:value-type="string">
+        <text:p text:style-name="P3">Right</text:p>
+      </table:table-cell>
+      <table:table-cell table:style-name="TableHeaderRowCell" office:value-type="string">
+        <text:p text:style-name="Table_20_Heading">Left</text:p>
+      </table:table-cell>
+    </table:table-row>
+  </table:table-header-rows>
+  <table:table-row>
+    <table:table-cell table:style-name="TableRowCell" office:value-type="string">
+      <text:p text:style-name="P4">13</text:p>
+    </table:table-cell>
+    <table:table-cell table:style-name="TableRowCell" office:value-type="string">
+      <text:p text:style-name="Table_20_Contents">14</text:p>
+    </table:table-cell>
+  </table:table-row>
+</table:table>
+```
diff --git a/test/command/5476.md b/test/command/5476.md
new file mode 100644
--- /dev/null
+++ b/test/command/5476.md
@@ -0,0 +1,12 @@
+```
+% pandoc -t latex
+![moon^[the moon]](test/lalune.jpg)
+^D
+\begin{figure}
+\centering
+\pandocbounded{\includegraphics[keepaspectratio,alt={moon}]{test/lalune.jpg}}
+\caption[moon]{moon\footnotemark{}}
+\end{figure}
+\footnotetext{the moon}
+```
+
diff --git a/test/command/5495.md b/test/command/5495.md
new file mode 100644
--- /dev/null
+++ b/test/command/5495.md
@@ -0,0 +1,18 @@
+```
+% pandoc -t markdown --reference-links
+All because of [1](#one) link...
+
+[This](#foo) will break Pandoc.
+
+[This](#bar) will make you laugh.
+^D
+All because of [1] link...
+
+[This] will break Pandoc.
+
+[This][2] will make you laugh.
+
+  [1]: #one
+  [This]: #foo
+  [2]: #bar
+```
diff --git a/test/command/5519.md b/test/command/5519.md
new file mode 100644
--- /dev/null
+++ b/test/command/5519.md
@@ -0,0 +1,14 @@
+~~~
+% pandoc -t markdown
+``````{.attr}
+ ```
+ code
+ ```
+``````
+^D
+```` attr
+ ```
+ code
+ ```
+````
+~~~
diff --git a/test/command/5529.md b/test/command/5529.md
new file mode 100644
--- /dev/null
+++ b/test/command/5529.md
@@ -0,0 +1,10 @@
+```
+% pandoc -t latex
+~~`hello world`~~
+
+~~_`hello world`_~~
+^D
+\st{\mbox{\texttt{hello\ world}}}
+
+\st{\emph{\mbox{\texttt{hello\ world}}}}
+```
diff --git a/test/command/5540.md b/test/command/5540.md
new file mode 100644
--- /dev/null
+++ b/test/command/5540.md
@@ -0,0 +1,14 @@
+```
+% pandoc -f latex -t native
+\begin{lstlisting}[language=myfunnylanguage]
+Stay pure!
+\end{lstlisting}
+^D
+[ CodeBlock
+    ( ""
+    , [ "myfunnylanguage" ]
+    , [ ( "language" , "myfunnylanguage" ) ]
+    )
+    "Stay pure!"
+]
+```
diff --git a/test/command/5541-localLink.md b/test/command/5541-localLink.md
new file mode 100644
--- /dev/null
+++ b/test/command/5541-localLink.md
@@ -0,0 +1,149 @@
+```
+% pandoc -f markdown -t icml -s
+
+# Header 1
+
+this is some text
+
+## Header 2
+
+some more text that [links to](#header-1) the first header. And this links to [some text](#spanner) in 2.1.
+
+## Header 2.1
+
+if you can read this text, [and it's linked]{#spanner} - all good!
+
+^D
+<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
+<?aid style="50" type="snippet" readerVersion="6.0" featureSet="513" product="8.0(370)" ?>
+<?aid SnippetType="InCopyInterchange"?>
+<Document DOMVersion="8.0" Self="pandoc_doc">
+    <RootCharacterStyleGroup Self="pandoc_character_styles">
+      <CharacterStyle Self="$ID/NormalCharacterStyle" Name="Default" />
+      <CharacterStyle Self="CharacterStyle/Link" Name="Link">
+        <Properties>
+          <BasedOn type="object">$ID/NormalCharacterStyle</BasedOn>
+        </Properties>
+      </CharacterStyle>
+    </RootCharacterStyleGroup>
+    <RootParagraphStyleGroup Self="pandoc_paragraph_styles">
+      <ParagraphStyle Self="$ID/NormalParagraphStyle" Name="$ID/NormalParagraphStyle"
+          SpaceBefore="6" SpaceAfter="6"> <!-- paragraph spacing -->
+        <Properties>
+          <TabList type="list">
+            <ListItem type="record">
+              <Alignment type="enumeration">LeftAlign</Alignment>
+              <AlignmentCharacter type="string">.</AlignmentCharacter>
+              <Leader type="string"></Leader>
+              <Position type="unit">10</Position> <!-- first tab stop -->
+            </ListItem>
+          </TabList>
+        </Properties>
+      </ParagraphStyle>
+      <ParagraphStyle Self="ParagraphStyle/Header1" Name="Header1" LeftIndent="0" PointSize="36">
+        <Properties>
+          <BasedOn type="object">$ID/NormalParagraphStyle</BasedOn>
+        </Properties>
+      </ParagraphStyle>
+      <ParagraphStyle Self="ParagraphStyle/Header2" Name="Header2" LeftIndent="0" PointSize="30">
+        <Properties>
+          <BasedOn type="object">$ID/NormalParagraphStyle</BasedOn>
+        </Properties>
+      </ParagraphStyle>
+      <ParagraphStyle Self="ParagraphStyle/Paragraph" Name="Paragraph" LeftIndent="0">
+        <Properties>
+          <BasedOn type="object">$ID/NormalParagraphStyle</BasedOn>
+        </Properties>
+      </ParagraphStyle>
+    </RootParagraphStyleGroup>
+    <RootTableStyleGroup Self="pandoc_table_styles">
+      <TableStyle Self="TableStyle/Table" Name="Table" />
+    </RootTableStyleGroup>
+    <RootCellStyleGroup Self="pandoc_cell_styles">
+      <CellStyle Self="CellStyle/Cell" AppliedParagraphStyle="ParagraphStyle/$ID/[No paragraph style]" Name="Cell" />
+    </RootCellStyleGroup>
+  <Story Self="pandoc_story"
+      TrackChanges="false"
+      StoryTitle=""
+      AppliedTOCStyle="n"
+      AppliedNamedGrid="n" >
+    <StoryPreference OpticalMarginAlignment="true" OpticalMarginSize="12" />
+
+<!-- body needs to be non-indented, otherwise code blocks are indented too far -->
+<ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/Header1">
+  <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
+    <HyperlinkTextDestination Self="HyperlinkTextDestination/#header-1" Name="Destination" DestinationUniqueKey="1" />
+    <Content>Header 1</Content>
+  </CharacterStyleRange>
+</ParagraphStyleRange>
+<Br />
+<ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/Paragraph">
+  <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
+    <Content>this is some text</Content>
+  </CharacterStyleRange>
+</ParagraphStyleRange>
+<Br />
+<ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/Header2">
+  <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
+    <HyperlinkTextDestination Self="HyperlinkTextDestination/#header-2" Name="Destination" DestinationUniqueKey="1" />
+    <Content>Header 2</Content>
+  </CharacterStyleRange>
+</ParagraphStyleRange>
+<Br />
+<ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/Paragraph">
+  <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
+    <Content>some more text that </Content>
+  </CharacterStyleRange>
+  <HyperlinkTextSource Self="htss-1" Name="" Hidden="false">
+    <CharacterStyleRange AppliedCharacterStyle="CharacterStyle/Link">
+      <Content>links to</Content>
+    </CharacterStyleRange>
+  </HyperlinkTextSource>
+  <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
+    <Content> the first header. And this links to </Content>
+  </CharacterStyleRange>
+  <HyperlinkTextSource Self="htss-2" Name="" Hidden="false">
+    <CharacterStyleRange AppliedCharacterStyle="CharacterStyle/Link">
+      <Content>some text</Content>
+    </CharacterStyleRange>
+  </HyperlinkTextSource>
+  <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
+    <Content> in 2.1.</Content>
+  </CharacterStyleRange>
+</ParagraphStyleRange>
+<Br />
+<ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/Header2">
+  <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
+    <HyperlinkTextDestination Self="HyperlinkTextDestination/#header-2.1" Name="Destination" DestinationUniqueKey="1" />
+    <Content>Header 2.1</Content>
+  </CharacterStyleRange>
+</ParagraphStyleRange>
+<Br />
+<ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/Paragraph">
+  <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
+    <Content>if you can read this text, </Content>
+  </CharacterStyleRange>
+  <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
+    <HyperlinkTextDestination Self="HyperlinkTextDestination/#spanner" Name="Destination" DestinationUniqueKey="1" />
+    <Content>and it’s linked</Content>
+  </CharacterStyleRange>
+  <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
+    <Content> - all good!</Content>
+  </CharacterStyleRange>
+</ParagraphStyleRange>
+
+  </Story>
+  <Hyperlink Self="uf-2" Name="#spanner" Source="htss-2" Visible="false" DestinationUniqueKey="1">
+    <Properties>
+      <BorderColor type="enumeration">Black</BorderColor>
+      <Destination type="object">HyperlinkTextDestination/#spanner</Destination>
+    </Properties>
+  </Hyperlink>
+  <Hyperlink Self="uf-1" Name="#header-1" Source="htss-1" Visible="false" DestinationUniqueKey="1">
+    <Properties>
+      <BorderColor type="enumeration">Black</BorderColor>
+      <Destination type="object">HyperlinkTextDestination/#header-1</Destination>
+    </Properties>
+  </Hyperlink>
+</Document>
+```
diff --git a/test/command/5541-nesting.md b/test/command/5541-nesting.md
new file mode 100644
--- /dev/null
+++ b/test/command/5541-nesting.md
@@ -0,0 +1,98 @@
+```
+% pandoc -f html -t icml -s
+
+<div id="blockId">
+  <div id="blockId2">
+    <span id="inlineId">
+      <img id="inlineId2" src="lalune.jpg" />
+    </span>
+  </div>
+</div>
+
+^D
+<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
+<?aid style="50" type="snippet" readerVersion="6.0" featureSet="513" product="8.0(370)" ?>
+<?aid SnippetType="InCopyInterchange"?>
+<Document DOMVersion="8.0" Self="pandoc_doc">
+    <RootCharacterStyleGroup Self="pandoc_character_styles">
+      <CharacterStyle Self="$ID/NormalCharacterStyle" Name="Default" />
+      <CharacterStyle Self="CharacterStyle/" Name="">
+        <Properties>
+          <BasedOn type="object">$ID/NormalCharacterStyle</BasedOn>
+        </Properties>
+      </CharacterStyle>
+    </RootCharacterStyleGroup>
+    <RootParagraphStyleGroup Self="pandoc_paragraph_styles">
+      <ParagraphStyle Self="$ID/NormalParagraphStyle" Name="$ID/NormalParagraphStyle"
+          SpaceBefore="6" SpaceAfter="6"> <!-- paragraph spacing -->
+        <Properties>
+          <TabList type="list">
+            <ListItem type="record">
+              <Alignment type="enumeration">LeftAlign</Alignment>
+              <AlignmentCharacter type="string">.</AlignmentCharacter>
+              <Leader type="string"></Leader>
+              <Position type="unit">10</Position> <!-- first tab stop -->
+            </ListItem>
+          </TabList>
+        </Properties>
+      </ParagraphStyle>
+      <ParagraphStyle Self="ParagraphStyle/" Name="" LeftIndent="0">
+        <Properties>
+          <BasedOn type="object">$ID/NormalParagraphStyle</BasedOn>
+        </Properties>
+      </ParagraphStyle>
+    </RootParagraphStyleGroup>
+    <RootTableStyleGroup Self="pandoc_table_styles">
+      <TableStyle Self="TableStyle/Table" Name="Table" />
+    </RootTableStyleGroup>
+    <RootCellStyleGroup Self="pandoc_cell_styles">
+      <CellStyle Self="CellStyle/Cell" AppliedParagraphStyle="ParagraphStyle/$ID/[No paragraph style]" Name="Cell" />
+    </RootCellStyleGroup>
+  <Story Self="pandoc_story"
+      TrackChanges="false"
+      StoryTitle=""
+      AppliedTOCStyle="n"
+      AppliedNamedGrid="n" >
+    <StoryPreference OpticalMarginAlignment="true" OpticalMarginSize="12" />
+
+<!-- body needs to be non-indented, otherwise code blocks are indented too far -->
+<ParagraphStyleRange AppliedParagraphStyle="">
+  <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
+    <HyperlinkTextDestination Self="HyperlinkTextDestination/#inlineId" Name="Destination" DestinationUniqueKey="1" />
+    <Content> </Content>
+  </CharacterStyleRange>
+  <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
+    <Rectangle Self="uec" StrokeWeight="0" ItemTransform="1 0 0 1 75 -75">
+      <Properties>
+        <PathGeometry>
+          <GeometryPathType PathOpen="false">
+            <PathPointArray>
+              <PathPointType Anchor="-75 -75" LeftDirection="-75 -75" RightDirection="-75 -75" />
+              <PathPointType Anchor="-75 75" LeftDirection="-75 75" RightDirection="-75 75" />
+              <PathPointType Anchor="75 75" LeftDirection="75 75" RightDirection="75 75" />
+              <PathPointType Anchor="75 -75" LeftDirection="75 -75" RightDirection="75 -75" />
+            </PathPointArray>
+          </GeometryPathType>
+        </PathGeometry>
+      </Properties>
+      <Image Self="ue6" ItemTransform="1 0 0 1 -75 -75">
+        <Properties>
+          <Profile type="string">
+            $ID/Embedded
+          </Profile>
+          <GraphicBounds Left="0" Top="0" Right="150" Bottom="150" />
+        </Properties>
+        <Link Self="ueb" LinkResourceURI="file:lalune.jpg" />
+      </Image>
+    </Rectangle>
+  </CharacterStyleRange>
+  <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
+    <HyperlinkTextDestination Self="HyperlinkTextDestination/#inlineId" Name="Destination" DestinationUniqueKey="1" />
+    <Content> </Content>
+  </CharacterStyleRange>
+</ParagraphStyleRange>
+
+  </Story>
+  
+</Document>
+```
diff --git a/test/command/5541-urlLink.md b/test/command/5541-urlLink.md
new file mode 100644
--- /dev/null
+++ b/test/command/5541-urlLink.md
@@ -0,0 +1,112 @@
+```
+% pandoc -f markdown -t icml -s
+
+# Header 1
+
+this is some text
+
+## Header 2
+
+some more text that [links to](https://www.pandoc.org) Pandoc.
+
+^D
+<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
+<?aid style="50" type="snippet" readerVersion="6.0" featureSet="513" product="8.0(370)" ?>
+<?aid SnippetType="InCopyInterchange"?>
+<Document DOMVersion="8.0" Self="pandoc_doc">
+    <RootCharacterStyleGroup Self="pandoc_character_styles">
+      <CharacterStyle Self="$ID/NormalCharacterStyle" Name="Default" />
+      <CharacterStyle Self="CharacterStyle/Link" Name="Link">
+        <Properties>
+          <BasedOn type="object">$ID/NormalCharacterStyle</BasedOn>
+        </Properties>
+      </CharacterStyle>
+    </RootCharacterStyleGroup>
+    <RootParagraphStyleGroup Self="pandoc_paragraph_styles">
+      <ParagraphStyle Self="$ID/NormalParagraphStyle" Name="$ID/NormalParagraphStyle"
+          SpaceBefore="6" SpaceAfter="6"> <!-- paragraph spacing -->
+        <Properties>
+          <TabList type="list">
+            <ListItem type="record">
+              <Alignment type="enumeration">LeftAlign</Alignment>
+              <AlignmentCharacter type="string">.</AlignmentCharacter>
+              <Leader type="string"></Leader>
+              <Position type="unit">10</Position> <!-- first tab stop -->
+            </ListItem>
+          </TabList>
+        </Properties>
+      </ParagraphStyle>
+      <ParagraphStyle Self="ParagraphStyle/Header1" Name="Header1" LeftIndent="0" PointSize="36">
+        <Properties>
+          <BasedOn type="object">$ID/NormalParagraphStyle</BasedOn>
+        </Properties>
+      </ParagraphStyle>
+      <ParagraphStyle Self="ParagraphStyle/Header2" Name="Header2" LeftIndent="0" PointSize="30">
+        <Properties>
+          <BasedOn type="object">$ID/NormalParagraphStyle</BasedOn>
+        </Properties>
+      </ParagraphStyle>
+      <ParagraphStyle Self="ParagraphStyle/Paragraph" Name="Paragraph" LeftIndent="0">
+        <Properties>
+          <BasedOn type="object">$ID/NormalParagraphStyle</BasedOn>
+        </Properties>
+      </ParagraphStyle>
+    </RootParagraphStyleGroup>
+    <RootTableStyleGroup Self="pandoc_table_styles">
+      <TableStyle Self="TableStyle/Table" Name="Table" />
+    </RootTableStyleGroup>
+    <RootCellStyleGroup Self="pandoc_cell_styles">
+      <CellStyle Self="CellStyle/Cell" AppliedParagraphStyle="ParagraphStyle/$ID/[No paragraph style]" Name="Cell" />
+    </RootCellStyleGroup>
+  <Story Self="pandoc_story"
+      TrackChanges="false"
+      StoryTitle=""
+      AppliedTOCStyle="n"
+      AppliedNamedGrid="n" >
+    <StoryPreference OpticalMarginAlignment="true" OpticalMarginSize="12" />
+
+<!-- body needs to be non-indented, otherwise code blocks are indented too far -->
+<ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/Header1">
+  <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
+    <HyperlinkTextDestination Self="HyperlinkTextDestination/#header-1" Name="Destination" DestinationUniqueKey="1" />
+    <Content>Header 1</Content>
+  </CharacterStyleRange>
+</ParagraphStyleRange>
+<Br />
+<ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/Paragraph">
+  <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
+    <Content>this is some text</Content>
+  </CharacterStyleRange>
+</ParagraphStyleRange>
+<Br />
+<ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/Header2">
+  <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
+    <HyperlinkTextDestination Self="HyperlinkTextDestination/#header-2" Name="Destination" DestinationUniqueKey="1" />
+    <Content>Header 2</Content>
+  </CharacterStyleRange>
+</ParagraphStyleRange>
+<Br />
+<ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/Paragraph">
+  <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
+    <Content>some more text that </Content>
+  </CharacterStyleRange>
+  <HyperlinkTextSource Self="htss-1" Name="" Hidden="false">
+    <CharacterStyleRange AppliedCharacterStyle="CharacterStyle/Link">
+      <Content>links to</Content>
+    </CharacterStyleRange>
+  </HyperlinkTextSource>
+  <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
+    <Content> Pandoc.</Content>
+  </CharacterStyleRange>
+</ParagraphStyleRange>
+
+  </Story>
+  <HyperlinkURLDestination Self="HyperlinkURLDestination/https%3a//www.pandoc.org" Name="link" DestinationURL="https://www.pandoc.org" DestinationUniqueKey="1" />
+  <Hyperlink Self="uf-1" Name="https://www.pandoc.org" Source="htss-1" Visible="false" DestinationUniqueKey="1">
+    <Properties>
+      <BorderColor type="enumeration">Black</BorderColor>
+      <Destination type="object">HyperlinkURLDestination/https%3a//www.pandoc.org</Destination>
+    </Properties>
+  </Hyperlink>
+</Document>
+```
diff --git a/test/command/5543.md b/test/command/5543.md
new file mode 100644
--- /dev/null
+++ b/test/command/5543.md
@@ -0,0 +1,8 @@
+```
+% pandoc -t markdown
+1\. item
+:   description
+^D
+1\. item
+: description
+```
diff --git a/test/command/5549.md b/test/command/5549.md
new file mode 100644
--- /dev/null
+++ b/test/command/5549.md
@@ -0,0 +1,8 @@
+```
+% pandoc -t native
+##
+
+[]
+^D
+[ Header 2 ( "section" , [] , [] ) [] , Para [ Str "[]" ] ]
+```
diff --git a/test/command/5565.md b/test/command/5565.md
new file mode 100644
--- /dev/null
+++ b/test/command/5565.md
@@ -0,0 +1,6 @@
+```
+% pandoc -t asciidoc
+***hi***
+^D
+*_hi_*
+```
diff --git a/test/command/5566.md b/test/command/5566.md
new file mode 100644
--- /dev/null
+++ b/test/command/5566.md
@@ -0,0 +1,6 @@
+```
+% pandoc -t asciidoc -f html
+fo<span class="c">o</span> f<span class="c">o</span>o <span class="c">f</span>oo <span class="c">foo</span>
+^D
+fo[.c]##o## f[.c]##o##o [.c]##f##oo [.c]#foo#
+```
diff --git a/test/command/5574.md b/test/command/5574.md
new file mode 100644
--- /dev/null
+++ b/test/command/5574.md
@@ -0,0 +1,7 @@
+No highlighting inside heading:
+```
+% pandoc -t latex
+# `foo`{.cpp}
+^D
+\section{\texorpdfstring{\texttt{foo}}{foo}}\label{foo}
+```
diff --git a/test/command/5619.md b/test/command/5619.md
new file mode 100644
--- /dev/null
+++ b/test/command/5619.md
@@ -0,0 +1,66 @@
+```
+% pandoc -f rst -t native
+.. figure:: img1.jpg
+  :width: 1in
+  :name: test
+
+  The caption. Here's what piggybacking on caption would look like {#fig:1}
+^D
+[ Figure
+    ( "" , [] , [] )
+    (Caption
+       Nothing
+       [ Plain
+           [ Str "The"
+           , Space
+           , Str "caption."
+           , Space
+           , Str "Here's"
+           , Space
+           , Str "what"
+           , Space
+           , Str "piggybacking"
+           , Space
+           , Str "on"
+           , Space
+           , Str "caption"
+           , Space
+           , Str "would"
+           , Space
+           , Str "look"
+           , Space
+           , Str "like"
+           , Space
+           , Str "{#fig:1}"
+           ]
+       ])
+    [ Plain
+        [ Image
+            ( "test" , [] , [ ( "width" , "1in" ) ] )
+            [ Str "The"
+            , Space
+            , Str "caption."
+            , Space
+            , Str "Here's"
+            , Space
+            , Str "what"
+            , Space
+            , Str "piggybacking"
+            , Space
+            , Str "on"
+            , Space
+            , Str "caption"
+            , Space
+            , Str "would"
+            , Space
+            , Str "look"
+            , Space
+            , Str "like"
+            , Space
+            , Str "{#fig:1}"
+            ]
+            ( "img1.jpg" , "" )
+        ]
+    ]
+]
+```
diff --git a/test/command/5620.md b/test/command/5620.md
new file mode 100644
--- /dev/null
+++ b/test/command/5620.md
@@ -0,0 +1,9 @@
+```
+% pandoc -t man
+`-o`, `--output=`*OUTFILE*
+:   Write output to *OUTFILE* instead of `stdout`(3)
+^D
+.TP
+\f[CR]\-o\f[R], \f[CR]\-\-output=\f[R]\f[I]OUTFILE\f[R]
+Write output to \f[I]OUTFILE\f[R] instead of \f[CR]stdout\f[R](3)
+```
diff --git a/test/command/5627.md b/test/command/5627.md
new file mode 100644
--- /dev/null
+++ b/test/command/5627.md
@@ -0,0 +1,87 @@
+```
+% pandoc -t html
+## Example
+
+1. One
+2. Two `-->something<!--`
+3. Three
+
+~~~html
+--><!--<script>alert('Escaped!')</script>
+~~~
+
+~~~html
+Something
+~~~
+^D
+<h2 id="example">Example</h2>
+<ol type="1">
+<li>One</li>
+<li>Two <code>--&gt;something&lt;!--</code></li>
+<li>Three</li>
+</ol>
+<div class="sourceCode" id="cb1"><pre
+class="sourceCode html"><code class="sourceCode html"><span id="cb1-1"><a href="#cb1-1" aria-hidden="true" tabindex="-1"></a>--&gt;<span class="co">&lt;!--&lt;script&gt;alert(&#39;Escaped!&#39;)&lt;/script&gt;</span></span></code></pre></div>
+<div class="sourceCode" id="cb2"><pre
+class="sourceCode html"><code class="sourceCode html"><span id="cb2-1"><a href="#cb2-1" aria-hidden="true" tabindex="-1"></a>Something</span></code></pre></div>
+```
+
+```
+% pandoc -t html
+## Example 2
+
+- `-->something<!--`
+- `-->something<!--`
+- bye `-->something else<!--`
+
+~~~html
+--><!--<script>alert('Escaped!')</script>
+~~~
+
+~~~html
+Something
+~~~
+^D
+<h2 id="example-2">Example 2</h2>
+<ul>
+<li><code>--&gt;something&lt;!--</code></li>
+<li><code>--&gt;something&lt;!--</code></li>
+<li>bye <code>--&gt;something else&lt;!--</code></li>
+</ul>
+<div class="sourceCode" id="cb1"><pre
+class="sourceCode html"><code class="sourceCode html"><span id="cb1-1"><a href="#cb1-1" aria-hidden="true" tabindex="-1"></a>--&gt;<span class="co">&lt;!--&lt;script&gt;alert(&#39;Escaped!&#39;)&lt;/script&gt;</span></span></code></pre></div>
+<div class="sourceCode" id="cb2"><pre
+class="sourceCode html"><code class="sourceCode html"><span id="cb2-1"><a href="#cb2-1" aria-hidden="true" tabindex="-1"></a>Something</span></code></pre></div>
+```
+
+```
+% pandoc -t html
+## Example 3
+
+1. `-->one<!--`
+5. bye `-->two <!--`
+3. ` three, not in block
+1. four, not in block  `
+2. five
+5. six
+6. seven `
+-  separate unordered list `
+42. forty-two, separate ordered list
+^D
+<h2 id="example-3">Example 3</h2>
+<ol type="1">
+<li><code>--&gt;one&lt;!--</code></li>
+<li>bye <code>--&gt;two &lt;!--</code></li>
+<li>` three, not in block</li>
+<li>four, not in block `</li>
+<li>five</li>
+<li>six</li>
+<li>seven `</li>
+</ol>
+<ul>
+<li>separate unordered list `</li>
+</ul>
+<ol start="42" type="1">
+<li>forty-two, separate ordered list</li>
+</ol>
+```
diff --git a/test/command/5635.md b/test/command/5635.md
new file mode 100644
--- /dev/null
+++ b/test/command/5635.md
@@ -0,0 +1,23 @@
+```
+% pandoc -f latex -t plain
+\providecommand{\test}{foo}
+\providecommand{\test}{bar}
+
+The value is: \test
+^D
+The value is: foo
+```
+
+```
+% pandoc -f latex -t plain
+\provideenvironment{test}{startfoo}{stopfoo}
+\provideenvironment{test}{startbar}{stopbar}
+
+\begin{test}
+Hi
+\end{test}
+^D
+startfoo Hi stopfoo
+```
+
+
diff --git a/test/command/5642.md b/test/command/5642.md
new file mode 100644
--- /dev/null
+++ b/test/command/5642.md
@@ -0,0 +1,9 @@
+```
+% pandoc -t html5 -f markdown
+![test](foo){aria-describedby="barbaz"}
+^D
+<figure>
+<img src="foo" aria-describedby="barbaz" alt="test" />
+<figcaption aria-hidden="true">test</figcaption>
+</figure>
+```
diff --git a/test/command/5650.md b/test/command/5650.md
new file mode 100644
--- /dev/null
+++ b/test/command/5650.md
@@ -0,0 +1,24 @@
+````
+% pandoc --id-prefix foo
+```haskell
+a
+b
+```
+^D
+<div class="sourceCode" id="foocb1"><pre
+class="sourceCode haskell"><code class="sourceCode haskell"><span id="foocb1-1"><a href="#foocb1-1" aria-hidden="true" tabindex="-1"></a>a</span>
+<span id="foocb1-2"><a href="#foocb1-2" aria-hidden="true" tabindex="-1"></a>b</span></code></pre></div>
+````
+
+````
+% pandoc --id-prefix foo
+``` {.haskell #bar}
+a
+b
+```
+^D
+<div class="sourceCode" id="foobar"><pre
+class="sourceCode haskell"><code class="sourceCode haskell"><span id="foobar-1"><a href="#foobar-1" aria-hidden="true" tabindex="-1"></a>a</span>
+<span id="foobar-2"><a href="#foobar-2" aria-hidden="true" tabindex="-1"></a>b</span></code></pre></div>
+````
+
diff --git a/test/command/5654.md b/test/command/5654.md
new file mode 100644
--- /dev/null
+++ b/test/command/5654.md
@@ -0,0 +1,6 @@
+```
+% pandoc -f latex -t markdown
+This is {\tt monospaced too} done.
+^D
+This is `monospaced too` done.
+```
diff --git a/test/command/5655.md b/test/command/5655.md
new file mode 100644
--- /dev/null
+++ b/test/command/5655.md
@@ -0,0 +1,20 @@
+````
+% pandoc --webtex
+$T_n={n+1 \choose 2}$
+^D
+<p><img style="vertical-align:middle"
+src="https://latex.codecogs.com/png.latex?%5Ctextstyle%20T_n%3D%7Bn%2B1%20%5Cchoose%202%7D"
+alt="T_n={n+1 \choose 2}" title="T_n={n+1 \choose 2}"
+class="math inline" /></p>
+````
+
+````
+% pandoc --webtex
+$$T_n={n+1 \choose 2}$$
+^D
+<p><img style="vertical-align:middle"
+src="https://latex.codecogs.com/png.latex?%5Cdisplaystyle%20T_n%3D%7Bn%2B1%20%5Cchoose%202%7D"
+alt="T_n={n+1 \choose 2}" title="T_n={n+1 \choose 2}"
+class="math display" /></p>
+````
+
diff --git a/test/command/5682.md b/test/command/5682.md
new file mode 100644
--- /dev/null
+++ b/test/command/5682.md
@@ -0,0 +1,8 @@
+```
+% pandoc -t native -f latex
+\newcommand{\ittakestwo}[2][defaultone]{#2}
+\ittakestwo[to]{tango}
+^D
+[ Para [ Str "tango" ] ]
+```
+
diff --git a/test/command/5684.md b/test/command/5684.md
new file mode 100644
--- /dev/null
+++ b/test/command/5684.md
@@ -0,0 +1,6 @@
+```
+% pandoc -f native -t latex
+[Str "\8222\8218Der",Space,Str "Erz\228hler.",Space,Str "Betrachtungen",Space,Str "zum",Space,Str "Werk",Space,Str "Nikolai",Space,Str "Lesskows\8216\8220."]
+^D
+„‚Der Erzähler. Betrachtungen zum Werk Nikolai Lesskows`\,``.
+```
diff --git a/test/command/5686.md b/test/command/5686.md
new file mode 100644
--- /dev/null
+++ b/test/command/5686.md
@@ -0,0 +1,31 @@
+```
+% pandoc -t native
+FOO\t0BAR
+
+This part does not make it to the html output.
+^D
+[ Para
+    [ Str "FOO" , RawInline (Format "tex") "\\t0" , Str "BAR" ]
+, Para
+    [ Str "This"
+    , Space
+    , Str "part"
+    , Space
+    , Str "does"
+    , Space
+    , Str "not"
+    , Space
+    , Str "make"
+    , Space
+    , Str "it"
+    , Space
+    , Str "to"
+    , Space
+    , Str "the"
+    , Space
+    , Str "html"
+    , Space
+    , Str "output."
+    ]
+]
+```
diff --git a/test/command/5690.md b/test/command/5690.md
new file mode 100644
--- /dev/null
+++ b/test/command/5690.md
@@ -0,0 +1,16 @@
+```
+% pandoc -f docbook -t asciidoc
+<warning>
+<title>My warning!</title>
+<para>A warning.</para>
+<para>Another paragraph.</para>
+</warning>
+^D
+[WARNING]
+.My warning!
+====
+A warning.
+
+Another paragraph.
+====
+```
diff --git a/test/command/5700-metadata-file-1.yml b/test/command/5700-metadata-file-1.yml
new file mode 100644
--- /dev/null
+++ b/test/command/5700-metadata-file-1.yml
@@ -0,0 +1,1 @@
+title: This title should be overridden by 5700-metadta-file-2.yml
diff --git a/test/command/5700-metadata-file-2.yml b/test/command/5700-metadata-file-2.yml
new file mode 100644
--- /dev/null
+++ b/test/command/5700-metadata-file-2.yml
@@ -0,0 +1,2 @@
+title: Multiple metadata files test
+desc: Both of these files should be loaded.
diff --git a/test/command/5700.md b/test/command/5700.md
new file mode 100644
--- /dev/null
+++ b/test/command/5700.md
@@ -0,0 +1,39 @@
+```
+% pandoc -t native -s --metadata-file command/5700-metadata-file-1.yml --metadata-file command/5700-metadata-file-2.yml
+^D
+Pandoc
+  Meta
+    { unMeta =
+        fromList
+          [ ( "desc"
+            , MetaInlines
+                [ Str "Both"
+                , Space
+                , Str "of"
+                , Space
+                , Str "these"
+                , Space
+                , Str "files"
+                , Space
+                , Str "should"
+                , Space
+                , Str "be"
+                , Space
+                , Str "loaded."
+                ]
+            )
+          , ( "title"
+            , MetaInlines
+                [ Str "Multiple"
+                , Space
+                , Str "metadata"
+                , Space
+                , Str "files"
+                , Space
+                , Str "test"
+                ]
+            )
+          ]
+    }
+  []
+```
diff --git a/test/command/5705.md b/test/command/5705.md
new file mode 100644
--- /dev/null
+++ b/test/command/5705.md
@@ -0,0 +1,11 @@
+```
+% pandoc -f native -t markdown
+[OrderedList (8,UpperRoman,Period)
+ [[Plain [Str "Blah"]
+  ,BulletList
+   [[Plain [Str "Blah"]]]]]]
+^D
+VIII. Blah
+      - Blah
+```
+
diff --git a/test/command/5708.md b/test/command/5708.md
new file mode 100644
--- /dev/null
+++ b/test/command/5708.md
@@ -0,0 +1,37 @@
+```
+% pandoc -f rst -t native
++--------+----------------+
+| 123456 | :math:`a + b`  |
++--------+----------------+
+^D
+[ Table
+    ( "" , [] , [] )
+    (Caption Nothing [])
+    [ ( AlignDefault , ColWidth 0.125 )
+    , ( AlignDefault , ColWidth 0.2361111111111111 )
+    ]
+    (TableHead ( "" , [] , [] ) [])
+    [ TableBody
+        ( "" , [] , [] )
+        (RowHeadColumns 0)
+        []
+        [ Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "123456" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Math InlineMath "a + b" ] ]
+            ]
+        ]
+    ]
+    (TableFoot ( "" , [] , [] ) [])
+]
+```
diff --git a/test/command/5711.md b/test/command/5711.md
new file mode 100644
--- /dev/null
+++ b/test/command/5711.md
@@ -0,0 +1,32 @@
+```
+% pandoc -t native -f latex
+\documentclass{article}
+\begin{document}
+\begin{tabular}{c}
+\parbox{2cm}{d\\e}
+\end{tabular}
+\end{document}
+^D
+[ Table
+    ( "" , [] , [] )
+    (Caption Nothing [])
+    [ ( AlignCenter , ColWidthDefault ) ]
+    (TableHead ( "" , [] , [] ) [])
+    [ TableBody
+        ( "" , [] , [] )
+        (RowHeadColumns 0)
+        []
+        [ Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "d" , LineBreak , Str "e" ] ]
+            ]
+        ]
+    ]
+    (TableFoot ( "" , [] , [] ) [])
+]
+```
diff --git a/test/command/5714.md b/test/command/5714.md
new file mode 100644
--- /dev/null
+++ b/test/command/5714.md
@@ -0,0 +1,16 @@
+```
+% pandoc -t native
+# hi _a
+b_
+
+# hi _c
+c
+^D
+[ Header
+    1 ( "hi-_a" , [] , [] ) [ Str "hi" , Space , Str "_a" ]
+, Para [ Str "b_" ]
+, Header
+    1 ( "hi-_c" , [] , [] ) [ Str "hi" , Space , Str "_c" ]
+, Para [ Str "c" ]
+]
+```
diff --git a/test/command/5740.md b/test/command/5740.md
new file mode 100644
--- /dev/null
+++ b/test/command/5740.md
@@ -0,0 +1,9 @@
+```
+% pandoc -t latex
+\newcommand\parenthesize[1][x]{(#1)}
+$\parenthesize$, $\parenthesize[y]$, $\parenthesize[\textsc{head}]$
+^D
+\newcommand\parenthesize[1][x]{(#1)}
+
+\((x)\), \((y)\), \((\textsc{head})\)
+```
diff --git a/test/command/5753.md b/test/command/5753.md
new file mode 100644
--- /dev/null
+++ b/test/command/5753.md
@@ -0,0 +1,19 @@
+```
+% pandoc -f rst -t native
+.. math::
+
+    q_3
+   + 4
+
+  - 5 +
+    q_5
+
+end
+^D
+[ Para
+    [ Math DisplayMath "q_3\n+ 4"
+    , Math DisplayMath "- 5 +\nq_5"
+    ]
+, Para [ Str "end" ]
+]
+```
diff --git a/test/command/5793.md b/test/command/5793.md
new file mode 100644
--- /dev/null
+++ b/test/command/5793.md
@@ -0,0 +1,13 @@
+```
+% pandoc -f html -t djot
+You can use <abbr title="Cascading Style Sheets">CSS</abbr>
+^D
+You can use [CSS]{.abbr title="Cascading Style Sheets"}
+```
+
+```
+% pandoc -f djot -t html
+You can use [CSS]{.abbr title="Cascading Style Sheets"}
+^D
+<p>You can use <abbr title="Cascading Style Sheets">CSS</abbr></p>
+```
diff --git a/test/command/5795.md b/test/command/5795.md
new file mode 100644
--- /dev/null
+++ b/test/command/5795.md
@@ -0,0 +1,25 @@
+```
+% pandoc -f html -t html
+<dfn id="foo" title="bax"><span>foo</span></dfn>
+^D
+<dfn id="foo" title="bax"><span>foo</span></dfn>
+```
+
+```
+% pandoc -f html -t native
+<dfn id="foo" title="bax"><span>foo</span></dfn>
+^D
+[ Plain
+    [ Span
+        ( "foo" , [ "dfn" ] , [ ( "title" , "bax" ) ] )
+        [ Span ( "" , [] , [] ) [ Str "foo" ] ]
+    ]
+]
+```
+
+```
+% pandoc -f native -t html
+[Plain [Span ("foo",["dfn"],[("title","bax")]) [Span ("",[],[]) [Str "foo"]]]]
+^D
+<dfn id="foo" title="bax"><span>foo</span></dfn>
+```
diff --git a/test/command/5797.md b/test/command/5797.md
new file mode 100644
--- /dev/null
+++ b/test/command/5797.md
@@ -0,0 +1,20 @@
+```
+% pandoc -f html -t html
+<mark>Ctrl-C</mark>
+^D
+<mark>Ctrl-C</mark>
+```
+
+```
+% pandoc -f html -t native
+<mark>Ctrl-C</mark>
+^D
+[ Plain [ Span ( "" , [ "mark" ] , [] ) [ Str "Ctrl-C" ] ] ]
+```
+
+```
+% pandoc -f native -t html
+[Plain [Span ("",["mark"],[]) [Str "Ctrl-C"]]]
+^D
+<mark>Ctrl-C</mark>
+```
diff --git a/test/command/5805.md b/test/command/5805.md
new file mode 100644
--- /dev/null
+++ b/test/command/5805.md
@@ -0,0 +1,20 @@
+```
+% pandoc -f html -t html
+<kbd>Ctrl-C</kbd>
+^D
+<kbd>Ctrl-C</kbd>
+```
+
+```
+% pandoc -f html -t native
+<kbd>Ctrl-C</kbd>
+^D
+[ Plain [ Span ( "" , [ "kbd" ] , [] ) [ Str "Ctrl-C" ] ] ]
+```
+
+```
+% pandoc -f native -t html
+[Plain [Span ("",["kbd"],[]) [Str "Ctrl-C"]]]
+^D
+<kbd>Ctrl-C</kbd>
+```
diff --git a/test/command/5813.md b/test/command/5813.md
new file mode 100644
--- /dev/null
+++ b/test/command/5813.md
@@ -0,0 +1,7 @@
+```
+% pandoc -f gfm
+### Jekyll Plugins & Gems :gem:
+^D
+<h3 id="jekyll-plugins--gems-gem">Jekyll Plugins &amp; Gems <span
+class="emoji" data-emoji="gem">💎</span></h3>
+```
diff --git a/test/command/5819.md b/test/command/5819.md
new file mode 100644
--- /dev/null
+++ b/test/command/5819.md
@@ -0,0 +1,18 @@
+```
+% pandoc -t revealjs --slide-level=2
+# Heading
+
+one
+
+. . .
+
+two
+^D
+<section id="heading" class="title-slide slide level1">
+<h1>Heading</h1>
+<p>one</p>
+<div class="fragment">
+<p>two</p>
+</div>
+</section>
+```
diff --git a/test/command/5836.md b/test/command/5836.md
new file mode 100644
--- /dev/null
+++ b/test/command/5836.md
@@ -0,0 +1,27 @@
+```
+% pandoc -f markdown -t latex
+\newcommand{\vara}{\alpha}
+\newcommand{\varb}{b}
+$\vara \varb$
+^D
+\newcommand{\vara}{\alpha}
+\newcommand{\varb}{b}
+
+\(\alpha b\)
+```
+```
+% pandoc -f latex -t latex
+\newcommand{\vara}{\alpha}
+\newcommand{\varb}{b}
+$\vara \varb$
+^D
+\(\alpha b\)
+```
+```
+% pandoc -f latex -t latex
+\newcommand{\vara}{\alpha}
+\newcommand{\varb}{b}
+\[\vara \varb\]
+^D
+\[\alpha b\]
+```
diff --git a/test/command/5845.md b/test/command/5845.md
new file mode 100644
--- /dev/null
+++ b/test/command/5845.md
@@ -0,0 +1,25 @@
+```
+% pandoc -t native
+\parbox{1em}{#1}
+^D
+[ Para [ Str "\\parbox{1em}{#1}" ] ]
+```
+
+```
+% pandoc -t native
+\newcommand{\highlight}[1]{\colorbox{yellow}{\parbox{\dimexpr\linewidth-2\fboxsep}{#1}}
+
+Hello World
+^D
+[ Para
+    [ Str "\\newcommand{"
+    , RawInline (Format "tex") "\\highlight"
+    , Str "}[1]{\\colorbox{yellow}{\\parbox{"
+    , RawInline (Format "tex") "\\dimexpr"
+    , RawInline (Format "tex") "\\linewidth-2"
+    , RawInline (Format "tex") "\\fboxsep"
+    , Str "}{#1}}"
+    ]
+, Para [ Str "Hello" , Space , Str "World" ]
+]
+```
diff --git a/test/command/5846.md b/test/command/5846.md
new file mode 100644
--- /dev/null
+++ b/test/command/5846.md
@@ -0,0 +1,170 @@
+```
+% pandoc --section-divs
+::: {.mydiv}
+# header 1a
+
+one
+
+# header 1b
+
+two
+:::
+^D
+<div class="mydiv">
+<section id="header-1a" class="level1">
+<h1>header 1a</h1>
+<p>one</p>
+</section>
+<section id="header-1b" class="level1">
+<h1>header 1b</h1>
+<p>two</p>
+</section>
+</div>
+```
+
+```
+% pandoc --section-divs
+::: mydiv
+# head 1
+## head 1.1
+# head 2
+:::
+
+## head 2.1
+^D
+<div class="mydiv">
+<section id="head-1" class="level1">
+<h1>head 1</h1>
+<section id="head-1.1" class="level2">
+<h2>head 1.1</h2>
+</section>
+</section>
+<section id="head-2" class="level1">
+<h1>head 2</h1>
+</section>
+</div>
+<section id="head-2.1" class="level2">
+<h2>head 2.1</h2>
+</section>
+```
+
+```
+% pandoc --section-divs
+# One
+## One A
+::: fence
+## One B
+# Two
+:::
+^D
+<section id="one" class="level1">
+<h1>One</h1>
+<section id="one-a" class="level2">
+<h2>One A</h2>
+</section>
+<div class="fence">
+<section id="one-b" class="level2">
+<h2>One B</h2>
+</section>
+<section id="two" class="level1">
+<h1>Two</h1>
+</section>
+</div>
+</section>
+```
+
+```
+% pandoc --section-divs
+# Beginning
+
+::: exterior
+
+At first...
+
+:::
+
+In the beginning...
+
+::: interior
+
+# Middle
+
+So it continued...
+
+:::
+
+# Ending
+
+::: exterior
+
+And finally...
+
+:::
+^D
+<section id="beginning" class="level1">
+<h1>Beginning</h1>
+<div class="exterior">
+<p>At first…</p>
+</div>
+<p>In the beginning…</p>
+</section>
+<section id="middle" class="level1 interior">
+<h1>Middle</h1>
+<p>So it continued…</p>
+</section>
+<section id="ending" class="level1">
+<h1>Ending</h1>
+<div class="exterior">
+<p>And finally…</p>
+</div>
+</section>
+```
+
+```
+% pandoc --section-divs
+::: part
+# One
+# Two
+:::
+::: part
+# Three
+# Four
+# Five
+:::
+::: part
+# Six
+# Seven
+# Eight
+:::
+^D
+<div class="part">
+<section id="one" class="level1">
+<h1>One</h1>
+</section>
+<section id="two" class="level1">
+<h1>Two</h1>
+</section>
+</div>
+<div class="part">
+<section id="three" class="level1">
+<h1>Three</h1>
+</section>
+<section id="four" class="level1">
+<h1>Four</h1>
+</section>
+<section id="five" class="level1">
+<h1>Five</h1>
+</section>
+</div>
+<div class="part">
+<section id="six" class="level1">
+<h1>Six</h1>
+</section>
+<section id="seven" class="level1">
+<h1>Seven</h1>
+</section>
+<section id="eight" class="level1">
+<h1>Eight</h1>
+</section>
+</div>
+```
diff --git a/test/command/5849-prefix.md b/test/command/5849-prefix.md
new file mode 100644
--- /dev/null
+++ b/test/command/5849-prefix.md
@@ -0,0 +1,31 @@
+```
+% pandoc -t latex --biblatex
+[e.g. @a1;@a2;@a3; but also @b1;@b2;@b3]
+^D
+\autocites[e.g.][]{a1,a2,a3}[but also][]{b1,b2,b3}
+```
+```
+% pandoc -t latex --biblatex
+[e.g. @a1; e.g. @a2;@a3; but also @b1;@b2;but also @b3]
+^D
+\autocites[e.g.][]{a1}[e.g.][]{a2,a3}[but also][]{b1,b2}[but also][]{b3}
+```
+```
+% pandoc -t latex --biblatex
+[e.g. @a1, ch.3 and elsewhere;@a2;@a3; but also @a4;@a5]
+^D
+\autocites[e.g.][ch.3 and elsewhere]{a1}{a2,a3}[but also][]{a4,a5}
+```
+```
+% pandoc -t latex --biblatex
+[e.g. @a1;@a2, ch.3 and elsewhere;@a3; but also @a4;@a5]
+^D
+\autocites[e.g.][]{a1}[ch.3 and elsewhere]{a2}{a3}[but also][]{a4,a5}
+```
+```
+% pandoc -t latex --biblatex
+[e.g. @a1, blah;@a2, ch.3 and elsewhere;@a3; but also @b4;@b5]
+^D
+\autocites[e.g.][blah]{a1}[ch.3 and elsewhere]{a2}{a3}[but
+also][]{b4,b5}
+```
diff --git a/test/command/5857.md b/test/command/5857.md
new file mode 100644
--- /dev/null
+++ b/test/command/5857.md
@@ -0,0 +1,11 @@
+```
+% pandoc -f native -t markdown
+[BulletList
+ [[Plain [Str "a"]]
+ ,[]
+ ,[Plain [Str "b"]]]]
+^D
+- a
+- 
+- b
+```
diff --git a/test/command/5876.md b/test/command/5876.md
new file mode 100644
--- /dev/null
+++ b/test/command/5876.md
@@ -0,0 +1,60 @@
+```
+% pandoc -s -t native --data-dir=command/5876 --metadata-file=5876.yaml
+Hello
+^D
+Pandoc
+  Meta
+    { unMeta =
+        fromList
+          [ ( "desc"
+            , MetaInlines
+                [ Str "Found"
+                , Space
+                , Str "in"
+                , Space
+                , Str "metadata"
+                , Space
+                , Str "directory."
+                ]
+            )
+          ]
+    }
+  [ Para [ Str "Hello" ] ]
+```
+```
+% pandoc -s -t native --data-dir=command/5876 --metadata-file=command/5876.yaml
+Hello
+^D
+Pandoc
+  Meta
+    { unMeta =
+        fromList
+          [ ( "desc"
+            , MetaInlines
+                [ Str "Found"
+                , Space
+                , Str "in"
+                , Space
+                , Str "working"
+                , Space
+                , Str "directory."
+                ]
+            )
+          ]
+    }
+  [ Para [ Str "Hello" ] ]
+```
+```
+% pandoc -s -t native --data-dir=command/5876 --metadata-file=does-not-exist.yaml
+Hello
+^D
+2> Could not find metadata file 'does-not-exist.yaml'
+=> 98
+```
+```
+% pandoc -s -t native --metadata-file=does-not-exist.yaml
+Hello
+^D
+2> Could not find metadata file 'does-not-exist.yaml'
+=> 98
+```
diff --git a/test/command/5876.yaml b/test/command/5876.yaml
new file mode 100644
--- /dev/null
+++ b/test/command/5876.yaml
@@ -0,0 +1,3 @@
+---
+desc: Found in working directory.
+---
diff --git a/test/command/5876/metadata/5876.yaml b/test/command/5876/metadata/5876.yaml
new file mode 100644
--- /dev/null
+++ b/test/command/5876/metadata/5876.yaml
@@ -0,0 +1,3 @@
+---
+desc: Found in metadata directory.
+---
diff --git a/test/command/5876/metadata/command/5876.yaml b/test/command/5876/metadata/command/5876.yaml
new file mode 100644
--- /dev/null
+++ b/test/command/5876/metadata/command/5876.yaml
@@ -0,0 +1,3 @@
+---
+desc: Should not be loaded.
+---
diff --git a/test/command/5878.md b/test/command/5878.md
new file mode 100644
--- /dev/null
+++ b/test/command/5878.md
@@ -0,0 +1,15 @@
+```
+% pandoc -t native
+Zozime^[],
+Synésius^[]
+^D
+[ Para
+    [ Str "Zozime"
+    , Note [ Para [] ]
+    , Str ","
+    , SoftBreak
+    , Str "Syn\233sius"
+    , Note [ Para [] ]
+    ]
+]
+```
diff --git a/test/command/5881.md b/test/command/5881.md
new file mode 100644
--- /dev/null
+++ b/test/command/5881.md
@@ -0,0 +1,14 @@
+```
+% pandoc -t markdown -s -H command/D.txt -d command/defaults1.yaml -d command/defaults2.yaml
+Ok
+^D
+here's d
+
+this is a
+
+here is b
+
+and this is c
+
+Ok
+```
diff --git a/test/command/5885.md b/test/command/5885.md
new file mode 100644
--- /dev/null
+++ b/test/command/5885.md
@@ -0,0 +1,20 @@
+```
+% pandoc -f docbook -t latex
+<equation>
+  <mathphrase>
+    J(x, y) = \left\{ \begin{array}{ll}
+    0 &amp; \text{if $I(x, y) &lt; t$} \\
+    1 &amp; \text{if $I(x, y) \ge t$}
+    \end{array}
+    \right.
+  </mathphrase>
+</equation>
+^D
+\[
+    J(x, y) = \left\{ \begin{array}{ll}
+    0 & \text{if $I(x, y) < t$} \\
+    1 & \text{if $I(x, y) \ge t$}
+    \end{array}
+    \right.
+  \]
+```
diff --git a/test/command/5898.md b/test/command/5898.md
new file mode 100644
--- /dev/null
+++ b/test/command/5898.md
@@ -0,0 +1,36 @@
+```
+% pandoc -f html -t rst
+<html>
+  <body>
+    <ul>
+      <li>A list of stuff with a table inside
+	<table>
+	  <thead>
+	    <tr>
+	      <th>First</th><th>Second</th><th>Third</th>
+	    </tr>
+	  </thead>
+	  <tbody>
+	    <tr>
+	      <td>First</td>
+	      <td>Second</td>
+	      <td>Third</td>
+	    </tr>
+	  </tbody>
+	</table>
+      </li>
+      <li>Another list item</li>
+    </ul>
+  </body>
+</html>
+^D
+- A list of stuff with a table inside
+
+  ===== ====== =====
+  First Second Third
+  ===== ====== =====
+  First Second Third
+  ===== ====== =====
+
+- Another list item
+```
diff --git a/test/command/5899.md b/test/command/5899.md
new file mode 100644
--- /dev/null
+++ b/test/command/5899.md
@@ -0,0 +1,51 @@
+```
+% pandoc -f html -t rst
+<html>
+  <body>
+    <ul>
+      <li>A list of stuff with a table inside
+        <table>
+          <thead>
+            <tr>
+              <th>First</th><th>Second</th><th>Third</th>
+            </tr>
+          </thead>
+          <tbody>
+            <tr>
+              <td>First</td>
+              <td>
+                The big long table cell.
+                The big long table cell.
+                The big long table cell.
+                The big long table cell.
+                The big long table cell.
+                The big long table cell.
+                The big long table cell.
+                The big long table cell.
+                The big long table cell.
+                The big long table cell.
+              </td>
+              <td>Third</td>
+            </tr>
+          </tbody>
+        </table>
+      </li>
+      <li>Another list item</li>
+    </ul>
+  </body>
+</html>
+^D
+- A list of stuff with a table inside
+
+  +-------+------------------------------------------------------+-------+
+  | First | Second                                               | Third |
+  +=======+======================================================+=======+
+  | First | The big long table cell. The big long table cell.    | Third |
+  |       | The big long table cell. The big long table cell.    |       |
+  |       | The big long table cell. The big long table cell.    |       |
+  |       | The big long table cell. The big long table cell.    |       |
+  |       | The big long table cell. The big long table cell.    |       |
+  +-------+------------------------------------------------------+-------+
+
+- Another list item
+ ```
diff --git a/test/command/5904.md b/test/command/5904.md
new file mode 100644
--- /dev/null
+++ b/test/command/5904.md
@@ -0,0 +1,10 @@
+```
+%  pandoc -s -t markdown -H command/B.txt --variable header-includes:foo
+Hi
+^D
+foo
+
+here is b
+
+Hi
+```
diff --git a/test/command/5918.md b/test/command/5918.md
new file mode 100644
--- /dev/null
+++ b/test/command/5918.md
@@ -0,0 +1,6 @@
+```
+% pandoc -t markdown -f latex
+1. \textsc{excessive}
+^D
+1\. [excessive]{.smallcaps}
+```
diff --git a/test/command/5936.md b/test/command/5936.md
new file mode 100644
--- /dev/null
+++ b/test/command/5936.md
@@ -0,0 +1,40 @@
+```
+% pandoc -f gfm -t rst
+| Name |
+| ---- |
+| Foo  |
+| Bar  |
+| Baz  |
+| Quux |
+^D
++------+
+| Name |
++======+
+| Foo  |
++------+
+| Bar  |
++------+
+| Baz  |
++------+
+| Quux |
++------+
+```
+
+```
+% pandoc -f gfm -t rst
+| Name | Number |
+| ---- | ------ |
+| Foo  | 3 |
+| Bar  | 4 |
+| Baz  | 2 |
+| Quux | 1 |
+^D
+==== ======
+Name Number
+==== ======
+Foo  3
+Bar  4
+Baz  2
+Quux 1
+==== ======
+```
diff --git a/test/command/5967.md b/test/command/5967.md
new file mode 100644
--- /dev/null
+++ b/test/command/5967.md
@@ -0,0 +1,15 @@
+```
+% pandoc --toc --toc-depth=3 -s -t plain
+# One
+## Two
+#### Four
+^D
+- One
+  - Two
+
+One
+
+Two
+
+Four
+```
diff --git a/test/command/5986.md b/test/command/5986.md
new file mode 100644
--- /dev/null
+++ b/test/command/5986.md
@@ -0,0 +1,18 @@
+```
+% pandoc -t epub --number-sections --toc --metadata title=Foo -o - | pandoc -f epub -t html
+# Hi
+^D
+<p><span id="title_page.xhtml"></span></p>
+<p><span id="nav.xhtml"></span></p>
+<nav epub:type="landmarks" id="landmarks" hidden="hidden">
+<ol>
+<li><a href="text/title_page.xhtml" class="titlepage">Title
+Page</a></li>
+<li><a href="#nav.xhtml_toc" class="toc">Table of Contents</a></li>
+</ol>
+</nav>
+<p><span id="ch001.xhtml"></span></p>
+<section id="ch001.xhtml_hi" class="level1" data-number="1">
+<h1 data-number="1"><span class="header-section-number">1</span> Hi</h1>
+</section>
+```
diff --git a/test/command/6009.md b/test/command/6009.md
new file mode 100644
--- /dev/null
+++ b/test/command/6009.md
@@ -0,0 +1,19 @@
+```
+% pandoc -t native
+  <tr>
+   <td>
+   </td>
+  </tr>
+
+x
+
+    y
+^D
+[ RawBlock (Format "html") "<tr>"
+, RawBlock (Format "html") "<td>"
+, RawBlock (Format "html") "</td>"
+, RawBlock (Format "html") "</tr>"
+, Para [ Str "x" ]
+, CodeBlock ( "" , [] , [] ) "y"
+]
+```
diff --git a/test/command/6021.md b/test/command/6021.md
new file mode 100644
--- /dev/null
+++ b/test/command/6021.md
@@ -0,0 +1,54 @@
+```
+% pandoc -t native
+Oxide      石英
+-------  ------
+SiO2        100
+^D
+[ Table
+    ( "" , [] , [] )
+    (Caption Nothing [])
+    [ ( AlignLeft , ColWidthDefault )
+    , ( AlignRight , ColWidthDefault )
+    ]
+    (TableHead
+       ( "" , [] , [] )
+       [ Row
+           ( "" , [] , [] )
+           [ Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "Oxide" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "\30707\33521" ] ]
+           ]
+       ])
+    [ TableBody
+        ( "" , [] , [] )
+        (RowHeadColumns 0)
+        []
+        [ Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "SiO2" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "100" ] ]
+            ]
+        ]
+    ]
+    (TableFoot ( "" , [] , [] ) [])
+]
+```
diff --git a/test/command/6026.md b/test/command/6026.md
new file mode 100644
--- /dev/null
+++ b/test/command/6026.md
@@ -0,0 +1,45 @@
+```
+% pandoc -t native
+@{https://openreview.net/forum?id=HkwoSDPgg}
+
+@https://openreview.net/forum?id=HkwoSDPgg
+^D
+[ Para
+    [ Cite
+        [ Citation
+            { citationId = "https://openreview.net/forum?id=HkwoSDPgg"
+            , citationPrefix = []
+            , citationSuffix = []
+            , citationMode = AuthorInText
+            , citationNoteNum = 1
+            , citationHash = 0
+            }
+        ]
+        [ Str "@https://openreview.net/forum?id=HkwoSDPgg" ]
+    ]
+, Para
+    [ Cite
+        [ Citation
+            { citationId = "https://openreview.net/forum?id"
+            , citationPrefix = []
+            , citationSuffix = []
+            , citationMode = AuthorInText
+            , citationNoteNum = 2
+            , citationHash = 0
+            }
+        ]
+        [ Str "@https://openreview.net/forum?id" ]
+    , Str "=HkwoSDPgg"
+    ]
+]
+```
+```
+% pandoc -t markdown
+@{https://openreview.net/forum?id=HkwoSDPgg}
+
+@https://openreview.net/forum?id=HkwoSDPgg
+^D
+@{https://openreview.net/forum?id=HkwoSDPgg}
+
+@https://openreview.net/forum?id=HkwoSDPgg
+```
diff --git a/test/command/6030.md b/test/command/6030.md
new file mode 100644
--- /dev/null
+++ b/test/command/6030.md
@@ -0,0 +1,94 @@
+```
+% pandoc -t revealjs --slide-level=3
+# One
+
+One
+
+## Two
+
+Two
+
+### Three
+
+Three
+
+#### Four
+
+Four
+
+# New sec
+
+New sec
+
+## New sub
+
+New sub
+^D
+<section>
+<section id="one" class="title-slide slide level1">
+<h1>One</h1>
+<p>One</p>
+</section>
+<section id="two" class="title-slide slide level2">
+<h2>Two</h2>
+<p>Two</p>
+</section>
+<section id="three" class="slide level3">
+<h3>Three</h3>
+<p>Three</p>
+<h4 id="four">Four</h4>
+<p>Four</p>
+</section>
+</section>
+<section>
+<section id="new-sec" class="title-slide slide level1">
+<h1>New sec</h1>
+<p>New sec</p>
+</section>
+<section id="new-sub" class="title-slide slide level2">
+<h2>New sub</h2>
+<p>New sub</p>
+</section>
+</section>
+```
+
+```
+% pandoc -t beamer --slide-level=3
+# One
+
+One
+
+## Two
+
+Two
+
+### Three
+
+Three
+
+#### Four
+
+Four
+^D
+\section{One}\label{one}
+
+\begin{frame}{One}
+One
+\end{frame}
+
+\subsection{Two}\label{two}
+
+\begin{frame}{Two}
+Two
+\end{frame}
+
+\begin{frame}{Three}
+\protect\phantomsection\label{three}
+Three
+
+\begin{block}{Four}
+\protect\phantomsection\label{four}
+Four
+\end{block}
+\end{frame}
+```
diff --git a/test/command/6033.md b/test/command/6033.md
new file mode 100644
--- /dev/null
+++ b/test/command/6033.md
@@ -0,0 +1,86 @@
+```
+% pandoc -t beamer --slide-level=4
+# One
+
+## One-A
+
+:::: columns
+
+::: column
+
+- One column.
+
+:::
+
+::: column
+
+- Another column.
+
+:::
+
+::::
+
+- Some more text.
+
+## One-B
+
+- Text.
+
+# Two
+
+## Two-A
+
+- More text.
+^D
+\section{One}\label{one}
+
+\subsection{One-A}\label{one-a}
+
+\begin{frame}{One-A}
+\begin{columns}[T]
+\begin{column}{0.48\linewidth}
+\begin{itemize}
+\tightlist
+\item
+  One column.
+\end{itemize}
+\end{column}
+
+\begin{column}{0.48\linewidth}
+\begin{itemize}
+\tightlist
+\item
+  Another column.
+\end{itemize}
+\end{column}
+\end{columns}
+
+\begin{itemize}
+\tightlist
+\item
+  Some more text.
+\end{itemize}
+\end{frame}
+
+\subsection{One-B}\label{one-b}
+
+\begin{frame}{One-B}
+\begin{itemize}
+\tightlist
+\item
+  Text.
+\end{itemize}
+\end{frame}
+
+\section{Two}\label{two}
+
+\subsection{Two-A}\label{two-a}
+
+\begin{frame}{Two-A}
+\begin{itemize}
+\tightlist
+\item
+  More text.
+\end{itemize}
+\end{frame}
+```
diff --git a/test/command/6034.md b/test/command/6034.md
new file mode 100644
--- /dev/null
+++ b/test/command/6034.md
@@ -0,0 +1,19 @@
+```
+% pandoc -f latex+raw_tex -t native
+\begin{figure*}
+  \centering
+  \begin{overpic}{test_pic}
+    \put (70,80) {Caption}
+  \end{overpic}
+\end{figure*}
+^D
+[ Figure
+    ( "" , [] , [] )
+    (Caption Nothing [])
+    [ RawBlock (Format "latex") "\\centering"
+    , RawBlock
+        (Format "latex")
+        "\\begin{overpic}{test_pic}\n    \\put (70,80) {Caption}\n  \\end{overpic}"
+    ]
+]
+```
diff --git a/test/command/6043.md b/test/command/6043.md
new file mode 100644
--- /dev/null
+++ b/test/command/6043.md
@@ -0,0 +1,8 @@
+```
+% pandoc -t beamer
+\textbf<1>{Bold Text On Slide1}
+^D
+\begin{frame}
+\textbf<1>{Bold Text On Slide1}
+\end{frame}
+```
diff --git a/test/command/6062.md b/test/command/6062.md
new file mode 100644
--- /dev/null
+++ b/test/command/6062.md
@@ -0,0 +1,6 @@
+```
+% pandoc -f native -t html
+[Header 1 ("section",["foo","unnumbered"],[("key","val")]) [Str "1"]]
+^D
+<h1 class="foo unnumbered" data-key="val" id="section">1</h1>
+```
diff --git a/test/command/6107.md b/test/command/6107.md
new file mode 100644
--- /dev/null
+++ b/test/command/6107.md
@@ -0,0 +1,26 @@
+```
+% pandoc -t beamer
+---
+title: A silly slide
+subtitle: Look for the sequel!
+---
+
+# A circus!
+
+## Another silly title
+
+Not much to do about nothing.
+
+## Epilogue {.standout}
+^D
+\section{A circus!}\label{a-circus}
+
+\begin{frame}{Another silly title}
+\protect\phantomsection\label{another-silly-title}
+Not much to do about nothing.
+\end{frame}
+
+\begin{frame}[standout]{Epilogue}
+\protect\phantomsection\label{epilogue}
+\end{frame}
+```
diff --git a/test/command/6114.md b/test/command/6114.md
new file mode 100644
--- /dev/null
+++ b/test/command/6114.md
@@ -0,0 +1,13 @@
+```
+% pandoc -f latex -t native
+\includegraphics[width=.85\textwidth]%
+ {pic_M87star.pdf}
+^D
+[ Para
+    [ Image
+        ( "" , [] , [ ( "width" , ".85\\textwidth" ) ] )
+        [ Str "image" ]
+        ( "pic_M87star.pdf" , "" )
+    ]
+]
+```
diff --git a/test/command/6119.md b/test/command/6119.md
new file mode 100644
--- /dev/null
+++ b/test/command/6119.md
@@ -0,0 +1,10 @@
+```
+% pandoc -t mediawiki
+[[link](url)]
+
+[![image](url)]
+^D
+[<nowiki/>[[url|link]]]
+
+[<nowiki/>[[File:url|image]]]
+```
diff --git a/test/command/6133.md b/test/command/6133.md
new file mode 100644
--- /dev/null
+++ b/test/command/6133.md
@@ -0,0 +1,12 @@
+```
+% pandoc -f markdown_mmd -t markdown_mmd -s
+author: Author
+title: Title
+
+Some text
+^D
+author: Author
+title: Title
+
+Some text
+```
diff --git a/test/command/6137.md b/test/command/6137.md
new file mode 100644
--- /dev/null
+++ b/test/command/6137.md
@@ -0,0 +1,162 @@
+```
+% pandoc -f latex -t native
+This reference to Table \ref{tbl:label} doesn't work.
+\begin{table}
+        \caption{This caption has no number.}\label{tbl:label}
+        \begin{tabular}{ l c r }
+          -------- & -------- & -------- \\
+          -------- & -------- & -------- \\
+        \end{tabular}
+\end{table}
+
+This reference to Figure \ref{fig:label} works fine.
+\begin{figure}
+        \includegraphics[width=\textwidth]{example.png}
+        \caption{A numbered caption, if I use pandoc-crossref.}\label{fig:label}
+\end{figure}
+^D
+[ Para
+    [ Str "This"
+    , Space
+    , Str "reference"
+    , Space
+    , Str "to"
+    , Space
+    , Str "Table"
+    , Space
+    , Link
+        ( ""
+        , []
+        , [ ( "reference-type" , "ref" )
+          , ( "reference" , "tbl:label" )
+          ]
+        )
+        [ Str "1" ]
+        ( "#tbl:label" , "" )
+    , Space
+    , Str "doesn\8217t"
+    , Space
+    , Str "work."
+    ]
+, Table
+    ( "tbl:label" , [] , [] )
+    (Caption
+       Nothing
+       [ Plain
+           [ Str "This"
+           , Space
+           , Str "caption"
+           , Space
+           , Str "has"
+           , Space
+           , Str "no"
+           , Space
+           , Str "number."
+           ]
+       ])
+    [ ( AlignLeft , ColWidthDefault )
+    , ( AlignCenter , ColWidthDefault )
+    , ( AlignRight , ColWidthDefault )
+    ]
+    (TableHead ( "" , [] , [] ) [])
+    [ TableBody
+        ( "" , [] , [] )
+        (RowHeadColumns 0)
+        []
+        [ Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "\8212\8212\8211" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "\8212\8212\8211" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "\8212\8212\8211" ] ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "\8212\8212\8211" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "\8212\8212\8211" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "\8212\8212\8211" ] ]
+            ]
+        ]
+    ]
+    (TableFoot ( "" , [] , [] ) [])
+, Para
+    [ Str "This"
+    , Space
+    , Str "reference"
+    , Space
+    , Str "to"
+    , Space
+    , Str "Figure"
+    , Space
+    , Link
+        ( ""
+        , []
+        , [ ( "reference-type" , "ref" )
+          , ( "reference" , "fig:label" )
+          ]
+        )
+        [ Str "1" ]
+        ( "#fig:label" , "" )
+    , Space
+    , Str "works"
+    , Space
+    , Str "fine."
+    ]
+, Figure
+    ( "fig:label" , [] , [] )
+    (Caption
+       Nothing
+       [ Plain
+           [ Str "A"
+           , Space
+           , Str "numbered"
+           , Space
+           , Str "caption,"
+           , Space
+           , Str "if"
+           , Space
+           , Str "I"
+           , Space
+           , Str "use"
+           , Space
+           , Str "pandoc-crossref."
+           ]
+       ])
+    [ Plain
+        [ Image
+            ( "" , [] , [ ( "width" , "\\textwidth" ) ] )
+            []
+            ( "example.png" , "" )
+        ]
+    ]
+]
+```
diff --git a/test/command/6194.md b/test/command/6194.md
new file mode 100644
--- /dev/null
+++ b/test/command/6194.md
@@ -0,0 +1,14 @@
+```
+% pandoc -f markdown -t rst
+image1: ![foo](x.png)
+
+image2: ![foo](y.png)
+^D
+image1: |foo|
+
+image2: |image1|
+
+.. |foo| image:: x.png
+.. |image1| image:: y.png
+```
+
diff --git a/test/command/6265.md b/test/command/6265.md
new file mode 100644
--- /dev/null
+++ b/test/command/6265.md
@@ -0,0 +1,6 @@
+```
+% pandoc -f markdown -t latex -M csquotes=true
+"test"
+^D
+\enquote{test}
+```
diff --git a/test/command/6285.md b/test/command/6285.md
new file mode 100644
--- /dev/null
+++ b/test/command/6285.md
@@ -0,0 +1,6 @@
+```
+% pandoc -t docx -f native -o - | pandoc -f docx -t native
+[ HorizontalRule ]
+^D
+[ HorizontalRule ]
+```
diff --git a/test/command/6288.md b/test/command/6288.md
new file mode 100644
--- /dev/null
+++ b/test/command/6288.md
@@ -0,0 +1,8 @@
+```
+% pandoc -f jats -t native
+<sec>
+<label>I</label><title>Introduction</title>
+</sec>
+^D
+[ Header 1 ( "" , [] , [] ) [ Str "Introduction" ] ]
+```
diff --git a/test/command/6296.md b/test/command/6296.md
new file mode 100644
--- /dev/null
+++ b/test/command/6296.md
@@ -0,0 +1,14 @@
+```
+% pandoc -f native -t markdown
+[Str "_hi_there"]
+^D
+\_hi_there
+```
+
+```
+% pandoc -f native -t markdown-intraword_underscores
+[Str "_hi_there"]
+^D
+\_hi\_there
+```
+
diff --git a/test/command/6308.md b/test/command/6308.md
new file mode 100644
--- /dev/null
+++ b/test/command/6308.md
@@ -0,0 +1,18 @@
+```
+% pandoc -f org -t asciidoc
+* Header
+#+begin_tip
+I'm a tip
+#+end_tip
+
+** Subheader
+^D
+== Header
+
+[TIP]
+====
+I'm a tip
+====
+
+=== Subheader
+```
diff --git a/test/command/6324.md b/test/command/6324.md
new file mode 100644
--- /dev/null
+++ b/test/command/6324.md
@@ -0,0 +1,26 @@
+```
+% pandoc -f latex -t native -s
+\documentclass{article}
+
+\begin{document}
+    \title{Document title}
+    \author{
+
+Me
+
+}
+\maketitle
+\end{document}
+^D
+Pandoc
+  Meta
+    { unMeta =
+        fromList
+          [ ( "author" , MetaList [ MetaInlines [ Str "Me" ] ] )
+          , ( "title"
+            , MetaInlines [ Str "Document" , Space , Str "title" ]
+            )
+          ]
+    }
+  []
+```
diff --git a/test/command/6348.md b/test/command/6348.md
new file mode 100644
--- /dev/null
+++ b/test/command/6348.md
@@ -0,0 +1,42 @@
+```
+% pandoc -f jats -t native
+<?xml version="1.0" encoding="utf-8"?>
+<!DOCTYPE article PUBLIC "-//NLM//DTD JATS (Z39.96) Journal Publishing DTD v1.0 20120330//EN" "http://jats.nlm.nih.gov/publishing/1.0/JATS-journalpublishing1.dtd">
+<article xmlns:mml="http://www.w3.org/1998/Math/MathML" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" dtd-version="1.0" article-type="research-article">
+  <front>
+    <journal-meta>
+      <journal-title-group>
+        <journal-title>Opinion Research</journal-title>
+      </journal-title-group>
+    </journal-meta>
+    <article-meta>
+      <title-group>
+        <article-title>Example article</article-title>
+      </title-group>
+    </article-meta>
+  </front>
+  <body>
+    <sec sec-type="results">
+      <title>Results</title>
+      <p>A University <xref ref-type="fn" rid="N0001">1</xref></p>
+    </sec>
+  </body>
+  <back>
+    <fn-group>
+      <fn id="N0001">
+        <p>footnote</p>
+      </fn>
+    </fn-group>
+  </back>
+</article>
+^D
+[ Header 1 ( "" , [] , [] ) [ Str "Results" ]
+, Para
+    [ Str "A"
+    , Space
+    , Str "University"
+    , Space
+    , Note [ Para [ Str "footnote" ] ]
+    ]
+]
+```
diff --git a/test/command/6350.md b/test/command/6350.md
new file mode 100644
--- /dev/null
+++ b/test/command/6350.md
@@ -0,0 +1,29 @@
+```
+% pandoc -f commonmark+implicit_figures -t native
+![caption](image.jpg){#ident width="100%"}
+^D
+[ Para
+    [ Image
+        ( "" , [] , [] ) [ Str "caption" ] ( "image.jpg" , "" )
+    , Str "{#ident"
+    , Space
+    , Str "width=\"100%\"}"
+    ]
+]
+
+```
+
+```
+% pandoc -f commonmark -t native
+![caption](image.jpg){#ident width="100%"}
+^D
+[ Para
+    [ Image
+        ( "" , [] , [] ) [ Str "caption" ] ( "image.jpg" , "" )
+    , Str "{#ident"
+    , Space
+    , Str "width=\"100%\"}"
+    ]
+]
+
+```
diff --git a/test/command/6360.md b/test/command/6360.md
new file mode 100644
--- /dev/null
+++ b/test/command/6360.md
@@ -0,0 +1,6 @@
+```
+% pandoc -f native -t latex --wrap=none
+[Link ("test2",[],[]) [Str "link",Space,Str "to",Space,Str "text",Space,Str "test1"] ("#test1","")]
+^D
+\protect\phantomsection\label{test2}\hyperref[test1]{link to text test1}
+```
diff --git a/test/command/6367.md b/test/command/6367.md
new file mode 100644
--- /dev/null
+++ b/test/command/6367.md
@@ -0,0 +1,75 @@
+```
+% pandoc -f ipynb -t org
+{
+ "cells": [
+  {
+   "cell_type": "markdown",
+   "metadata": {},
+   "source": [
+    "A Markdown cell"
+   ]
+  },
+  {
+   "cell_type": "code",
+   "execution_count": 1,
+   "metadata": {},
+   "outputs": [
+    {
+     "data": {
+      "text/plain": [
+       "2"
+      ]
+     },
+     "execution_count": 1,
+     "metadata": {},
+     "output_type": "execute_result"
+    }
+   ],
+   "source": [
+    "# A code cell\n",
+    "1 + 1"
+   ]
+  },
+  {
+   "cell_type": "markdown",
+   "metadata": {},
+   "source": [
+    "Another Markdown cell"
+   ]
+  }
+ ],
+ "metadata": {
+  "kernelspec": {
+   "display_name": "Python 3",
+   "language": "python",
+   "name": "python3"
+  },
+  "language_info": {
+   "codemirror_mode": {
+    "name": "ipython",
+    "version": 3
+   },
+   "file_extension": ".py",
+   "mimetype": "text/x-python",
+   "name": "python",
+   "nbconvert_exporter": "python",
+   "pygments_lexer": "ipython3",
+   "version": "3.8.2"
+  }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 4
+}
+^D
+A Markdown cell
+
+#+begin_src jupyter-python
+# A code cell
+1 + 1
+#+end_src
+
+#+RESULTS:
+: 2
+
+Another Markdown cell
+```
diff --git a/test/command/6384.md b/test/command/6384.md
new file mode 100644
--- /dev/null
+++ b/test/command/6384.md
@@ -0,0 +1,12 @@
+```
+% pandoc --wrap=preserve --file-scope command/file1.txt command/file2.txt
+^D
+<h1 id="command__file1.txt__zed">Zed</h1>
+<p><a href="bar">foo</a>
+and <a href="#command__file1.txt__zed">Zed</a>
+and <a href="#command__file2.txt__zed">other Zed</a>
+and <a href="#command__file2.txt">other file</a>
+and <a href="c.md#zed">foreign Zed</a></p>
+<h2 id="command__file2.txt__zed">Zed</h2>
+<p><a href="baz">foo</a></p>
+```
diff --git a/test/command/6385.md b/test/command/6385.md
new file mode 100644
--- /dev/null
+++ b/test/command/6385.md
@@ -0,0 +1,18 @@
+```
+% pandoc -f markdown -t html
+<details>
+<summary>Show me:</summary>
+details para 1
+
+details para 2
+
+</details>
+^D
+<details>
+<summary>
+Show me:
+</summary>
+<p>details para 1</p>
+<p>details para 2</p>
+</details>
+```
diff --git a/test/command/6388.md b/test/command/6388.md
new file mode 100644
--- /dev/null
+++ b/test/command/6388.md
@@ -0,0 +1,16 @@
+```
+% pandoc -t markdown -s
+---
+nvalue: false
+value: true
+---
+
+text
+^D
+---
+nvalue: false
+value: true
+---
+
+text
+```
diff --git a/test/command/6424.md b/test/command/6424.md
new file mode 100644
--- /dev/null
+++ b/test/command/6424.md
@@ -0,0 +1,6 @@
+```
+% pandoc -t asciidoc
+test^[this is a note\]. and more]
+^D
+testfootnote:[this is a note++]++. and more]
+```
diff --git a/test/command/6441.md b/test/command/6441.md
new file mode 100644
--- /dev/null
+++ b/test/command/6441.md
@@ -0,0 +1,22 @@
+```
+% pandoc -f org -t html
+#+ATTR_HTML: :class table-dark
+| h1 | h2 |
+|----|----|
+| c1 | c2 |
+^D
+<table class="table-dark">
+<thead>
+<tr>
+<th>h1</th>
+<th>h2</th>
+</tr>
+</thead>
+<tbody>
+<tr>
+<td>c1</td>
+<td>c2</td>
+</tr>
+</tbody>
+</table>
+```
diff --git a/test/command/6466-beg.hs b/test/command/6466-beg.hs
new file mode 100644
--- /dev/null
+++ b/test/command/6466-beg.hs
@@ -0,0 +1,8 @@
+want :: Int
+want = 42
+
+-- DO NOT WANT this; right bound is exclusive
+
+-- DO NOT WANT the below
+doNotWant :: Int
+doNotWant = 999
diff --git a/test/command/6466-end.hs b/test/command/6466-end.hs
new file mode 100644
--- /dev/null
+++ b/test/command/6466-end.hs
@@ -0,0 +1,4 @@
+-- DO NOT WANT
+
+want :: Int
+want = 42
diff --git a/test/command/6466-mid.hs b/test/command/6466-mid.hs
new file mode 100644
--- /dev/null
+++ b/test/command/6466-mid.hs
@@ -0,0 +1,10 @@
+-- DO NOT WANT
+
+want :: Int
+want = 42
+
+-- AVOID EXCLUSIVE RIGHT BOUND
+
+-- DO NOT WANT
+doNotWant :: Int
+doNotWant = 999
diff --git a/test/command/6466-whole.hs b/test/command/6466-whole.hs
new file mode 100644
--- /dev/null
+++ b/test/command/6466-whole.hs
@@ -0,0 +1,2 @@
+want :: Int
+want = 42
diff --git a/test/command/6466.md b/test/command/6466.md
new file mode 100644
--- /dev/null
+++ b/test/command/6466.md
@@ -0,0 +1,23 @@
+```
+% pandoc -f org -t native
+Stuff
+
+#+INCLUDE: "command/6466-beg.hs" src haskell :lines "-4"
+#+INCLUDE: "command/6466-mid.hs" src haskell :lines "3-6"
+#+INCLUDE: "command/6466-end.hs" src haskell :lines "3-"
+#+INCLUDE: "command/6466-whole.hs" src haskell :lines "-"
+
+More stuff
+^D
+[ Para [ Str "Stuff" ]
+, CodeBlock
+    ( "" , [ "haskell" ] , [] ) "want :: Int\nwant = 42\n\n"
+, CodeBlock
+    ( "" , [ "haskell" ] , [] ) "want :: Int\nwant = 42\n\n"
+, CodeBlock
+    ( "" , [ "haskell" ] , [] ) "want :: Int\nwant = 42\n"
+, CodeBlock
+    ( "" , [ "haskell" ] , [] ) "want :: Int\nwant = 42\n"
+, Para [ Str "More" , Space , Str "stuff" ]
+]
+```
diff --git a/test/command/6481.md b/test/command/6481.md
new file mode 100644
--- /dev/null
+++ b/test/command/6481.md
@@ -0,0 +1,38 @@
+```
+% pandoc -t html5
+::: {.div-class}
++-------+-----+-----+-------------------------------------------------+
+| Col 1 | Col | Col | Col 4                                           |
+|       | 2   | 3   |                                                 |
++:=====:+:===:+:===:+:================================================+
+| High  | Med | Med | Some description of something.                  |
++-------+-----+-----+-------------------------------------------------+
+:::
+^D
+<div class="div-class">
+<table style="width:97%;">
+<colgroup>
+<col style="width: 11%" />
+<col style="width: 8%" />
+<col style="width: 8%" />
+<col style="width: 69%" />
+</colgroup>
+<thead>
+<tr>
+<th style="text-align: center;">Col 1</th>
+<th style="text-align: center;">Col 2</th>
+<th style="text-align: center;">Col 3</th>
+<th style="text-align: left;">Col 4</th>
+</tr>
+</thead>
+<tbody>
+<tr>
+<td style="text-align: center;">High</td>
+<td style="text-align: center;">Med</td>
+<td style="text-align: center;">Med</td>
+<td style="text-align: left;">Some description of something.</td>
+</tr>
+</tbody>
+</table>
+</div>
+```
diff --git a/test/command/6541.md b/test/command/6541.md
new file mode 100644
--- /dev/null
+++ b/test/command/6541.md
@@ -0,0 +1,27 @@
+```
+% pandoc -f docbook -t markdown -s
+<?xml version="1.0"?>
+<!DOCTYPE book PUBLIC "-//OASIS//DTD DocBook XML V4.2//EN"
+  "http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd">
+<book>
+
+<bookinfo>
+<title>Title</title>
+<author>
+<firstname>Firstname</firstname><surname>Lastname</surname>
+</author>
+<releaseinfo>1.17</releaseinfo>
+</bookinfo>
+
+<para>Text.</para>
+
+</book>
+^D
+---
+author: Firstname Lastname
+releaseinfo: 1.17
+title: Title
+---
+
+Text.
+```
diff --git a/test/command/6549.md b/test/command/6549.md
new file mode 100644
--- /dev/null
+++ b/test/command/6549.md
@@ -0,0 +1,26 @@
+```
+% pandoc -f rst
+.. csv-table:: Test table
+   :file: command/01.csv
+   :delim: ;
+   :header-rows: 1
+^D
+<table>
+<caption>Test table</caption>
+<thead>
+<tr>
+<th>Column1</th>
+<th>Column2</th>
+</tr>
+</thead>
+<tbody>
+<tr>
+<td>Data1</td>
+<td><ul>
+<li>data1</li>
+<li>data2</li>
+</ul></td>
+</tr>
+</tbody>
+</table>
+```
diff --git a/test/command/6588.md b/test/command/6588.md
new file mode 100644
--- /dev/null
+++ b/test/command/6588.md
@@ -0,0 +1,10 @@
+```
+% pandoc -f rst
+I recommend you try |Python|_.
+
+.. |Python| replace:: Python, *the* best language around
+.. _Python: http://www.python.org/
+^D
+<p>I recommend you try <a href="http://www.python.org/"><span>Python,
+<em>the</em> best language around</span></a>.</p>
+```
diff --git a/test/command/6620.md b/test/command/6620.md
new file mode 100644
--- /dev/null
+++ b/test/command/6620.md
@@ -0,0 +1,18 @@
+```
+% pandoc -f latex
+\SI{23(2)}{\m}
+
+\SI{125(12)}{\m}
+
+\SI{0.135(21)}{\m}
+
+\SI{12.3(60)}{\m}
+
+\SI{10.0 \pm 3.3}{\ms}
+^D
+<p>23 ± 2 m</p>
+<p>125 ± 12 m</p>
+<p>0.135 ± 0.021 m</p>
+<p>12.3 ± 6 m</p>
+<p>10.0 ± 3.3 ms</p>
+```
diff --git a/test/command/6658.md b/test/command/6658.md
new file mode 100644
--- /dev/null
+++ b/test/command/6658.md
@@ -0,0 +1,75 @@
+```
+% pandoc -f latex -t html
+\num{12345,67890}
+
+\num{1+-2i}
+
+\num{.3e45}
+
+\num{1.654 x 2.34 x 3.430}
+
+\si{kg.m.s^{-1}}
+
+\si{\kilogram\metre\per\second}
+
+\si[per-mode=symbol]{\kilogram\metre\per\second}
+
+\si[per-mode=symbol]{\kilogram\metre\per\ampere\per\second}
+
+\numlist{10;20;30}
+
+\SIlist{0.13;0.67;0.80}{\milli\metre}
+
+\numrange{10}{20}
+
+\SIrange{0.13}{0.67}{\milli\metre}
+
+\ang{10}
+
+\ang{1;2;3}
+
+\ang{;;1}
+
+\ang{+10;;}
+
+\ang{-0;1;}
+
+\si{kg.m/s^2}
+
+\si{g_{polymer}~mol_{cat}.s^{-1}}
+
+\si{\kilo\gram\metre\per\square\second}
+
+\si{\gram\per\cubic\centi\metre}
+
+\si{\square\volt\cubic\lumen\per\farad}
+
+\si{\metre\squared\per\gray\cubic\lux}
+
+\si{\henry\second}
+^D
+<p>12345.67890</p>
+<p>1 ± 2i</p>
+<p>0.3 × 10<sup>45</sup></p>
+<p>1.654 × 2.34 × 3.430</p>
+<p>kg m s<sup>−1</sup></p>
+<p>kg m s<sup>−1</sup></p>
+<p>kg m/s</p>
+<p>kg m/A/s</p>
+<p>10, 20, &amp; 30</p>
+<p>0.13 mm, 0.67 mm, &amp; 0.80 mm</p>
+<p>10–20</p>
+<p>0.13 mm–0.67 mm</p>
+<p>10°</p>
+<p>1°2′3″</p>
+<p>1″</p>
+<p>10°</p>
+<p>-0°1′</p>
+<p>kg m/s<sup>2</sup></p>
+<p>g<sub>polymer</sub> mol<sub>cat</sub> s<sup>−1</sup></p>
+<p>kg m s<sup>−2</sup></p>
+<p>g cm<sup>−3</sup></p>
+<p>V<sup>2</sup> lm<sup>3</sup> F<sup>−1</sup></p>
+<p>m<sup>2</sup> Gy<sup>−1</sup> lx<sup>3</sup></p>
+<p>H s</p>
+```
diff --git a/test/command/6675.md b/test/command/6675.md
new file mode 100644
--- /dev/null
+++ b/test/command/6675.md
@@ -0,0 +1,134 @@
+```
+% pandoc -f markdown -t icml -s
+
+# Header 1
+
+this is some text
+
+## Header 2
+
+some more text that [links to](https://www.pandoc.org) Pandoc.
+
+and some text that [links to](#header-1) the first header
+
+^D
+<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
+<?aid style="50" type="snippet" readerVersion="6.0" featureSet="513" product="8.0(370)" ?>
+<?aid SnippetType="InCopyInterchange"?>
+<Document DOMVersion="8.0" Self="pandoc_doc">
+    <RootCharacterStyleGroup Self="pandoc_character_styles">
+      <CharacterStyle Self="$ID/NormalCharacterStyle" Name="Default" />
+      <CharacterStyle Self="CharacterStyle/Link" Name="Link">
+        <Properties>
+          <BasedOn type="object">$ID/NormalCharacterStyle</BasedOn>
+        </Properties>
+      </CharacterStyle>
+    </RootCharacterStyleGroup>
+    <RootParagraphStyleGroup Self="pandoc_paragraph_styles">
+      <ParagraphStyle Self="$ID/NormalParagraphStyle" Name="$ID/NormalParagraphStyle"
+          SpaceBefore="6" SpaceAfter="6"> <!-- paragraph spacing -->
+        <Properties>
+          <TabList type="list">
+            <ListItem type="record">
+              <Alignment type="enumeration">LeftAlign</Alignment>
+              <AlignmentCharacter type="string">.</AlignmentCharacter>
+              <Leader type="string"></Leader>
+              <Position type="unit">10</Position> <!-- first tab stop -->
+            </ListItem>
+          </TabList>
+        </Properties>
+      </ParagraphStyle>
+      <ParagraphStyle Self="ParagraphStyle/Header1" Name="Header1" LeftIndent="0" PointSize="36">
+        <Properties>
+          <BasedOn type="object">$ID/NormalParagraphStyle</BasedOn>
+        </Properties>
+      </ParagraphStyle>
+      <ParagraphStyle Self="ParagraphStyle/Header2" Name="Header2" LeftIndent="0" PointSize="30">
+        <Properties>
+          <BasedOn type="object">$ID/NormalParagraphStyle</BasedOn>
+        </Properties>
+      </ParagraphStyle>
+      <ParagraphStyle Self="ParagraphStyle/Paragraph" Name="Paragraph" LeftIndent="0">
+        <Properties>
+          <BasedOn type="object">$ID/NormalParagraphStyle</BasedOn>
+        </Properties>
+      </ParagraphStyle>
+    </RootParagraphStyleGroup>
+    <RootTableStyleGroup Self="pandoc_table_styles">
+      <TableStyle Self="TableStyle/Table" Name="Table" />
+    </RootTableStyleGroup>
+    <RootCellStyleGroup Self="pandoc_cell_styles">
+      <CellStyle Self="CellStyle/Cell" AppliedParagraphStyle="ParagraphStyle/$ID/[No paragraph style]" Name="Cell" />
+    </RootCellStyleGroup>
+  <Story Self="pandoc_story"
+      TrackChanges="false"
+      StoryTitle=""
+      AppliedTOCStyle="n"
+      AppliedNamedGrid="n" >
+    <StoryPreference OpticalMarginAlignment="true" OpticalMarginSize="12" />
+
+<!-- body needs to be non-indented, otherwise code blocks are indented too far -->
+<ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/Header1">
+  <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
+    <HyperlinkTextDestination Self="HyperlinkTextDestination/#header-1" Name="Destination" DestinationUniqueKey="1" />
+    <Content>Header 1</Content>
+  </CharacterStyleRange>
+</ParagraphStyleRange>
+<Br />
+<ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/Paragraph">
+  <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
+    <Content>this is some text</Content>
+  </CharacterStyleRange>
+</ParagraphStyleRange>
+<Br />
+<ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/Header2">
+  <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
+    <HyperlinkTextDestination Self="HyperlinkTextDestination/#header-2" Name="Destination" DestinationUniqueKey="1" />
+    <Content>Header 2</Content>
+  </CharacterStyleRange>
+</ParagraphStyleRange>
+<Br />
+<ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/Paragraph">
+  <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
+    <Content>some more text that </Content>
+  </CharacterStyleRange>
+  <HyperlinkTextSource Self="htss-1" Name="" Hidden="false">
+    <CharacterStyleRange AppliedCharacterStyle="CharacterStyle/Link">
+      <Content>links to</Content>
+    </CharacterStyleRange>
+  </HyperlinkTextSource>
+  <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
+    <Content> Pandoc.</Content>
+  </CharacterStyleRange>
+</ParagraphStyleRange>
+<Br />
+<ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/Paragraph">
+  <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
+    <Content>and some text that </Content>
+  </CharacterStyleRange>
+  <HyperlinkTextSource Self="htss-2" Name="" Hidden="false">
+    <CharacterStyleRange AppliedCharacterStyle="CharacterStyle/Link">
+      <Content>links to</Content>
+    </CharacterStyleRange>
+  </HyperlinkTextSource>
+  <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
+    <Content> the first header</Content>
+  </CharacterStyleRange>
+</ParagraphStyleRange>
+
+  </Story>
+  <Hyperlink Self="uf-2" Name="#header-1" Source="htss-2" Visible="false" DestinationUniqueKey="1">
+    <Properties>
+      <BorderColor type="enumeration">Black</BorderColor>
+      <Destination type="object">HyperlinkTextDestination/#header-1</Destination>
+    </Properties>
+  </Hyperlink>
+  <HyperlinkURLDestination Self="HyperlinkURLDestination/https%3a//www.pandoc.org" Name="link" DestinationURL="https://www.pandoc.org" DestinationUniqueKey="1" />
+  <Hyperlink Self="uf-1" Name="https://www.pandoc.org" Source="htss-1" Visible="false" DestinationUniqueKey="1">
+    <Properties>
+      <BorderColor type="enumeration">Black</BorderColor>
+      <Destination type="object">HyperlinkURLDestination/https%3a//www.pandoc.org</Destination>
+    </Properties>
+  </Hyperlink>
+</Document>
+```
diff --git a/test/command/6699.md b/test/command/6699.md
new file mode 100644
--- /dev/null
+++ b/test/command/6699.md
@@ -0,0 +1,15 @@
+```
+% pandoc -f rst -t native
+.. class:: allowframebreaks
+
+title
+-----
+
+text
+^D
+[ Header
+    1 ( "title" , [ "allowframebreaks" ] , [] ) [ Str "title" ]
+, Para [ Str "text" ]
+]
+```
+
diff --git a/test/command/6709.md b/test/command/6709.md
new file mode 100644
--- /dev/null
+++ b/test/command/6709.md
@@ -0,0 +1,13 @@
+Tabs must be expanded even if --file-scope is used
+````
+% pandoc -t native --file-scope --tab-stop=2
+```
+if true; then
+	echo "yup"
+fi
+```
+^D
+[ CodeBlock
+    ( "" , [] , [] ) "if true; then\n  echo \"yup\"\nfi"
+]
+````
diff --git a/test/command/6719.md b/test/command/6719.md
new file mode 100644
--- /dev/null
+++ b/test/command/6719.md
@@ -0,0 +1,18 @@
+```
+% pandoc -f docbook -t native
+<para>
+<emphasis>emphasized </emphasis>text
+</para>
+^D
+[ Para [ Emph [ Str "emphasized" , Space ] , Str "text" ] ]
+```
+
+```
+% pandoc -f jats -t native
+<p>
+<italic> hi  </italic>there
+</p>
+^D
+[ Para [ Emph [ Space , Str "hi" , Space ] , Str "there" ] ]
+```
+
diff --git a/test/command/6723.md b/test/command/6723.md
new file mode 100644
--- /dev/null
+++ b/test/command/6723.md
@@ -0,0 +1,32 @@
+```
+% pandoc --citeproc -t markdown-citations
+---
+csl: command/chicago-fullnote-bibliography.csl
+references:
+- id: doe
+  type: article
+  author:
+  - family: Doe
+    given: John
+  DOI: 10.1109/5.771073
+  issued:
+    - year: 2020
+  title: An article
+...
+Blah [@doe].
+
+# References {-}
+
+^D
+Blah.[^1]
+
+# References {#references .unnumbered}
+
+:::: {#refs .references .csl-bib-body .hanging-indent entry-spacing="0"}
+::: {#ref-doe .csl-entry}
+Doe, John. "An Article," 2020. <https://doi.org/10.1109/5.771073>.
+:::
+::::
+
+[^1]: John Doe, "An Article," 2020, <https://doi.org/10.1109/5.771073>.
+```
diff --git a/test/command/6739.md b/test/command/6739.md
new file mode 100644
--- /dev/null
+++ b/test/command/6739.md
@@ -0,0 +1,22 @@
+```
+% pandoc -f gfm
+* `--argument` This item does not have a pipe character
+* `--argA | --argB` This item has a pipe character
+^D
+<ul>
+<li><code>--argument</code> This item does not have a pipe
+character</li>
+<li><code>--argA | --argB</code> This item has a pipe character</li>
+</ul>
+```
+
+```
+% pandoc --mathjax -f gfm+tex_math_dollars
+* $|x|$
+* $|y|$
+^D
+<ul>
+<li><span class="math inline">\(|x|\)</span></li>
+<li><span class="math inline">\(|y|\)</span></li>
+</ul>
+```
diff --git a/test/command/6740.md b/test/command/6740.md
new file mode 100644
--- /dev/null
+++ b/test/command/6740.md
@@ -0,0 +1,7 @@
+```
+% pandoc -t gfm
+<https://www.google.com>
+^D
+<https://www.google.com>
+```
+
diff --git a/test/command/6741.md b/test/command/6741.md
new file mode 100644
--- /dev/null
+++ b/test/command/6741.md
@@ -0,0 +1,145 @@
+```
+% pandoc --citeproc --csl command/ieee.csl -t plain
+---
+title: 'A Simple Citations Test'
+author: 'Joanna Doe'
+references:
+- author:
+  - family: Mathôt
+    given: S
+  container-title: Annual review of vision science
+  DOI: 10.1146/annurev-vision-030320-062352
+  id: mathot2020
+  issued: 2020
+  title: "Tuning the senses: How the pupil shapes vision at the earliest
+    stage."
+  title-short: Tuning the senses
+  type: article-journal
+- author:
+  - family: Zokaei
+    given: Nahid
+  - family: Board
+    given: Alexander G.
+  - family: Manohar
+    given: Sanjay G.
+  - family: Nobre
+    given: Anna C.
+  container-title: Proceedings of the National Academy of Sciences of
+    the United States of America
+  DOI: 10.1073/pnas.1909959116
+  id: zokaei2019
+  issued: 2019
+  page: 201909959
+  title: Modulation of the pupillary response by the content of visual
+    working memory
+  type: article-journal
+- author:
+  - family: Suzuki
+    given: Y.
+  - family: Minami
+    given: T.
+  - family: Laeng
+    given: B.
+  - family: Nakauchi
+    given: S.
+  container-title: Acta Psychologica
+  DOI: 10.1016/j.actpsy.2019.102882
+  id: suzuki2019
+  issued: 2019
+  page: 102882
+  title: "Colorful glares: Effects of colors on brightness illusions
+    measured with pupillometry."
+  title-short: Colorful glares
+  type: article-journal
+  volume: 198
+- author:
+  - family: Brainard
+    given: David H.
+  - family: Hurlbert
+    given: Anya
+  container-title: Current Biology
+  DOI: 10.1016/j.cub.2015.05.020
+  id: brainard2015a
+  issue: 13
+  issued: 2015
+  page: R551-R554
+  title: "Colour vision: Understanding \\#TheDress"
+  title-short: Colour vision
+  type: article-journal
+  volume: 25
+- author:
+  - family: Cavanagh
+    given: Patrick
+  container-title: Limits of vision
+  editor:
+  - family: Crody-Dillon
+    given: John R.
+  id: cavanagh1991
+  issued: 1991
+  page: 234-250
+  publisher: CRC Press
+  title: Vision at equiluminance
+  type: chapter
+- author:
+  - family: Brainard
+    given: David H.
+  container-title: Annual Review of Vision Science
+  DOI: 10.1146/annurev-vision-082114-035341
+  id: brainard2015
+  issued: 2015
+  page: 519-546
+  title: Color and the cone mosaic
+  type: article-journal
+  volume: 1
+...
+
+# First Heading #
+Here is some **text**. And a reference [@brainard2015;@brainard2015a].
+
+# Second Heading #
+Here is some *text*[@cavanagh1991]. And a reference [@cavanagh1991;@brainard2015].
+
+# Third Heading #
+Here is some [text]{.underline}. And a reference [@mathot2020;@zokaei2019;@suzuki2019].
+
+::: {#refs}
+## Bibliography ##
+:::
+^D
+First Heading
+
+Here is some text. And a reference [1], [2].
+
+Second Heading
+
+Here is some text[3]. And a reference [1], [3].
+
+Third Heading
+
+Here is some text. And a reference [4]–[6].
+
+Bibliography
+
+[1] D. H. Brainard, “Color and the cone mosaic,” Annual Review of Vision
+Science, vol. 1, pp. 519–546, 2015.
+
+[2] D. H. Brainard and A. Hurlbert, “Colour vision: Understanding
+#TheDress,” Current Biology, vol. 25, no. 13, pp. R551–R554, 2015.
+
+[3] P. Cavanagh, “Vision at equiluminance,” in Limits of vision, J. R.
+Crody-Dillon, Ed. CRC Press, 1991, pp. 234–250.
+
+[4] S. Mathôt, “Tuning the senses: How the pupil shapes vision at the
+earliest stage.” Annual review of vision science, 2020.
+
+[5] N. Zokaei, A. G. Board, S. G. Manohar, and A. C. Nobre, “Modulation
+of the pupillary response by the content of visual working memory,”
+Proceedings of the National Academy of Sciences of the United States of
+America, p. 201909959, 2019.
+
+[6] Y. Suzuki, T. Minami, B. Laeng, and S. Nakauchi, “Colorful glares:
+Effects of colors on brightness illusions measured with pupillometry.”
+Acta Psychologica, vol. 198, p. 102882, 2019.
+
+```
+
diff --git a/test/command/6752.md b/test/command/6752.md
new file mode 100644
--- /dev/null
+++ b/test/command/6752.md
@@ -0,0 +1,36 @@
+```
+% pandoc -f biblatex -t csljson
+@xdata{XDPubAlfredAKnopf,
+    publisher   = {Alfred A.~Knopf},
+    address     = {New York, NY}
+}
+@book{Klinkenborg2012,
+    author      = {Verlyn Klinkenborg},
+    title       = {Several short sentences about writing},
+    date        = {2012},
+    xdata       = {XDPubAlfredAKnopf},
+}
+^D
+[
+  {
+    "author": [
+      {
+        "family": "Klinkenborg",
+        "given": "Verlyn"
+      }
+    ],
+    "id": "Klinkenborg2012",
+    "issued": {
+      "date-parts": [
+        [
+          2012
+        ]
+      ]
+    },
+    "publisher": "Alfred A. Knopf",
+    "publisher-place": "New York, NY",
+    "title": "Several short sentences about writing",
+    "type": "book"
+  }
+]
+```
diff --git a/test/command/6755.md b/test/command/6755.md
new file mode 100644
--- /dev/null
+++ b/test/command/6755.md
@@ -0,0 +1,11 @@
+```
+%pandoc -f native -t opendocument
+[Div ("divId",[],[])
+ [Para [Str "Here",Space,Str "is",Space,Str "a",Space,Str "div."]],
+Para [Span ("spanId",[],[]) [Str "And",Space,Str "here",Space,Str "is",Space,Str "a",Space,Str "span."]]]
+^D
+<text:section text:name="divId"><text:p text:style-name="Text_20_body">Here
+is a div.</text:p></text:section>
+<text:p text:style-name="Text_20_body"><text:bookmark-start text:name="spanId" />And
+here is a span.<text:bookmark-end text:name="spanId" /></text:p>
+```
diff --git a/test/command/6765.md b/test/command/6765.md
new file mode 100644
--- /dev/null
+++ b/test/command/6765.md
@@ -0,0 +1,31 @@
+```
+% pandoc --citeproc -t plain
+@book_chapter_1 [55] says blah.
+
+---
+csl: command/chicago-fullnote-bibliography.csl
+references:
+- id: book_chapter_1
+  author:
+    - family: Author
+      given: Ann
+  container-title: A book
+  editor:
+    - family: Editor
+      given: Edward
+  issued: 2014
+  page: 48-67
+  publisher: A publisher
+  publisher-place: A place
+  title: A book chapter
+  type: chapter
+...
+^D
+Ann Author[1] says blah.
+
+Author, Ann. “A Book Chapter.” In A Book, edited by Edward Editor,
+48–67. A place: A publisher, 2014.
+
+[1] “A Book Chapter,” in A Book, ed. Edward Editor (A place: A
+publisher, 2014), 55.
+```
diff --git a/test/command/6768.md b/test/command/6768.md
new file mode 100644
--- /dev/null
+++ b/test/command/6768.md
@@ -0,0 +1,21 @@
+```
+% pandoc -tcommonmark
+::: custom_div
+This is a div
+:::
+^D
+<div class="custom_div">
+
+This is a div
+
+</div>
+```
+
+```
+% pandoc -tcommonmark-raw_html
+::: custom_div
+This is a div
+:::
+^D
+This is a div
+```
diff --git a/test/command/6774.md b/test/command/6774.md
new file mode 100644
--- /dev/null
+++ b/test/command/6774.md
@@ -0,0 +1,63 @@
+```
+% pandoc -f native -t opendocument --quiet
+[Header 1 ("chapter1",[],[]) [Str "The",Space,Str "Chapter"]
+,Para [Str "Chapter",Space,Str "1",Space,Str "references",Space,Link ("",[],[]) [Str "The",Space,Str "Chapter"] ("#chapter1","")]]
+^D
+<text:h text:style-name="Heading_20_1" text:outline-level="1"><text:bookmark-start text:name="chapter1" />The
+Chapter<text:bookmark-end text:name="chapter1" /></text:h>
+<text:p text:style-name="First_20_paragraph">Chapter 1 references
+<text:a xlink:type="simple" xlink:href="#chapter1" office:name=""><text:span text:style-name="Definition">The
+Chapter</text:span></text:a></text:p>
+```
+```
+% pandoc -f native -t opendocument+xrefs_name --quiet
+[Header 1 ("chapter1",[],[]) [Str "The",Space,Str "Chapter"]
+,Para [Str "Chapter",Space,Str "1",Space,Str "references",Space,Link ("",[],[]) [Str "The",Space,Str "Chapter"] ("#chapter1","")]
+,Figure ("lalune",[],[]) (Caption Nothing [Para [Str "Voyage dans la Lune"]]) [Plain [Image ("",[],[]) [Str "lalune"] ("lalune.jpg","")]]
+,Para [Str "Image",Space,Str "1",Space,Str "references",Space,Link ("",[],[]) [Str "La",Space,Str "Lune"] ("#lalune","")]]
+^D
+<text:h text:style-name="Heading_20_1" text:outline-level="1"><text:bookmark-start text:name="chapter1" />The
+Chapter<text:bookmark-end text:name="chapter1" /></text:h>
+<text:p text:style-name="First_20_paragraph">Chapter 1 references
+<text:bookmark-ref text:reference-format="text" text:ref-name="chapter1">The
+Chapter</text:bookmark-ref></text:p>
+<text:p text:style-name="FigureWithCaption"><draw:frame draw:name="img1"><draw:image xlink:href="lalune.jpg" xlink:type="simple" xlink:show="embed" xlink:actuate="onLoad" /></draw:frame></text:p>
+<text:p text:style-name="FigureCaption">Voyage dans la Lune</text:p>
+<text:p text:style-name="Text_20_body">Image 1 references
+<text:sequence-ref text:reference-format="caption" text:ref-name="lalune">La
+Lune</text:sequence-ref></text:p>
+```
+```
+% pandoc -f native -t opendocument+xrefs_number --quiet
+[Header 1 ("chapter1",[],[]) [Str "The",Space,Str "Chapter"]
+,Para [Str "Chapter",Space,Str "1",Space,Str "references",Space,Link ("",[],[]) [Str "The",Space,Str "Chapter"] ("#chapter1","")]
+,Figure ("lalune",[],[]) (Caption Nothing [Para [Str "lalune"]]) [Plain [Image ("",[],[]) [Str "lalune"] ("lalune.jpg","Voyage dans la Lune")]]
+,Para [Str "Image",Space,Str "1",Space,Str "references",Space,Link ("",[],[]) [Str "La",Space,Str "Lune"] ("#lalune","")]]
+^D
+<text:h text:style-name="Heading_20_1" text:outline-level="1"><text:bookmark-start text:name="chapter1" />The
+Chapter<text:bookmark-end text:name="chapter1" /></text:h>
+<text:p text:style-name="First_20_paragraph">Chapter 1 references
+<text:bookmark-ref text:reference-format="number" text:ref-name="chapter1"></text:bookmark-ref></text:p>
+<text:p text:style-name="FigureWithCaption"><draw:frame draw:name="img1"><draw:image xlink:href="lalune.jpg" xlink:type="simple" xlink:show="embed" xlink:actuate="onLoad" /></draw:frame></text:p>
+<text:p text:style-name="FigureCaption">lalune</text:p>
+<text:p text:style-name="Text_20_body">Image 1 references
+<text:sequence-ref text:reference-format="value" text:ref-name="lalune"></text:sequence-ref></text:p>
+```
+```
+% pandoc -f native -t opendocument+xrefs_number+xrefs_name --quiet
+[Header 1 ("chapter1",[],[]) [Str "The",Space,Str "Chapter"]
+,Para [Str "Chapter",Space,Str "1",Space,Str "references",Space,Link ("",[],[]) [Str "The",Space,Str "Chapter"] ("#chapter1","")]
+,Figure ("lalune",[],[]) (Caption Nothing [Para [Str "Voyage dans la Lune"]]) [Plain [Image ("",[],[]) [Str "lalune"] ("lalune.jpg","")]]
+,Para [Str "Image",Space,Str "1",Space,Str "references",Space,Link ("",[],[]) [Str "La",Space,Str "Lune"] ("#lalune","")]]
+^D
+<text:h text:style-name="Heading_20_1" text:outline-level="1"><text:bookmark-start text:name="chapter1" />The
+Chapter<text:bookmark-end text:name="chapter1" /></text:h>
+<text:p text:style-name="First_20_paragraph">Chapter 1 references
+<text:bookmark-ref text:reference-format="number" text:ref-name="chapter1"></text:bookmark-ref><text:s /><text:bookmark-ref text:reference-format="text" text:ref-name="chapter1">The
+Chapter</text:bookmark-ref></text:p>
+<text:p text:style-name="FigureWithCaption"><draw:frame draw:name="img1"><draw:image xlink:href="lalune.jpg" xlink:type="simple" xlink:show="embed" xlink:actuate="onLoad" /></draw:frame></text:p>
+<text:p text:style-name="FigureCaption">Voyage dans la Lune</text:p>
+<text:p text:style-name="Text_20_body">Image 1 references
+<text:sequence-ref text:reference-format="value" text:ref-name="lalune"></text:sequence-ref><text:s /><text:sequence-ref text:reference-format="caption" text:ref-name="lalune">La
+Lune</text:sequence-ref></text:p>
+```
diff --git a/test/command/6783.md b/test/command/6783.md
new file mode 100644
--- /dev/null
+++ b/test/command/6783.md
@@ -0,0 +1,26 @@
+```
+% pandoc -f markdown -t plain -s --citeproc
+---
+references:
+- author:
+  - family: Jupyter
+    given: Project
+  container-title: Proceedings of the 17th Python in Science Conference
+  id: 'ref-1'
+  issued: 2018
+  title: 'Binder 2.0 - Reproducible, interactive, sharable environments for science at scale'
+  type: 'paper-conference'
+  volume:
+...
+
+This is a test[@ref-1].
+^D
+
+
+This is a test(Jupyter 2018).
+
+Jupyter, Project. 2018. “Binder 2.0 - Reproducible, Interactive,
+Sharable Environments for Science at Scale.” Proceedings of the 17th
+Python in Science Conference.
+```
+
diff --git a/test/command/6791.md b/test/command/6791.md
new file mode 100644
--- /dev/null
+++ b/test/command/6791.md
@@ -0,0 +1,47 @@
+```
+% pandoc -f docbook -t native --quiet
+<informaltable frame="all" rowsep="1" colsep="1">
+<?dbfo table-width="50%"?>
+<tgroup cols="2">
+<colspec colname="col_1" colwidth="6.25*"/>
+<colspec colname="col_2" colwidth="6.25*"/>
+<tbody>
+<row>
+<entry align="center" valign="top"><simpara>2</simpara></entry>
+<entry align="center" valign="top"><simpara>1</simpara></entry>
+</row>
+</tbody>
+</tgroup>
+</informaltable>
+^D
+[ Table
+    ( "" , [] , [] )
+    (Caption Nothing [])
+    [ ( AlignDefault , ColWidth 0.25 )
+    , ( AlignDefault , ColWidth 0.25 )
+    ]
+    (TableHead ( "" , [] , [] ) [])
+    [ TableBody
+        ( "" , [] , [] )
+        (RowHeadColumns 0)
+        []
+        [ Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignCenter
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Para [ Str "2" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignCenter
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Para [ Str "1" ] ]
+            ]
+        ]
+    ]
+    (TableFoot ( "" , [] , [] ) [])
+]
+```
diff --git a/test/command/6792.md b/test/command/6792.md
new file mode 100644
--- /dev/null
+++ b/test/command/6792.md
@@ -0,0 +1,66 @@
+```
+% pandoc -f native -t opendocument -s --quiet
+[Table ("",[],[]) (Caption Nothing
+ [])
+ [(AlignDefault,ColWidth 0.25)
+ ,(AlignDefault,ColWidth 0.25)]
+ (TableHead ("",[],[])
+ [])
+ [(TableBody ("",[],[]) (RowHeadColumns 0)
+  []
+  [Row ("",[],[])
+   [Cell ("",[],[]) AlignCenter (RowSpan 1) (ColSpan 1)
+    [Para [Str "2"]]
+   ,Cell ("",[],[]) AlignCenter (RowSpan 1) (ColSpan 1)
+    [Para [Str "1"]]]])]
+ (TableFoot ("",[],[])
+ [])]
+^D
+<?xml version="1.0" encoding="utf-8" ?>
+<office:document-content xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" xmlns:style="urn:oasis:names:tc:opendocument:xmlns:style:1.0" xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0" xmlns:table="urn:oasis:names:tc:opendocument:xmlns:table:1.0" xmlns:draw="urn:oasis:names:tc:opendocument:xmlns:drawing:1.0" xmlns:fo="urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:meta="urn:oasis:names:tc:opendocument:xmlns:meta:1.0" xmlns:number="urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0" xmlns:svg="urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0" xmlns:chart="urn:oasis:names:tc:opendocument:xmlns:chart:1.0" xmlns:dr3d="urn:oasis:names:tc:opendocument:xmlns:dr3d:1.0" xmlns:math="http://www.w3.org/1998/Math/MathML" xmlns:form="urn:oasis:names:tc:opendocument:xmlns:form:1.0" xmlns:script="urn:oasis:names:tc:opendocument:xmlns:script:1.0" xmlns:ooo="http://openoffice.org/2004/office" xmlns:ooow="http://openoffice.org/2004/writer" xmlns:oooc="http://openoffice.org/2004/calc" xmlns:dom="http://www.w3.org/2001/xml-events" xmlns:xforms="http://www.w3.org/2002/xforms" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" office:version="1.3">
+  <office:font-face-decls>
+    <style:font-face style:name="Courier New" style:font-family-generic="modern" style:font-pitch="fixed" svg:font-family="'Courier New'" />
+  </office:font-face-decls>
+  <office:automatic-styles>
+    <style:style style:name="fr2" style:family="graphic" style:parent-style-name="Formula"><style:graphic-properties style:vertical-pos="middle" style:vertical-rel="text" style:horizontal-pos="center" style:horizontal-rel="paragraph-content" style:wrap="none" /></style:style>
+    <style:style style:name="fr1" style:family="graphic" style:parent-style-name="Formula"><style:graphic-properties style:vertical-pos="middle" style:vertical-rel="text" /></style:style>
+    <style:style style:name="P1" style:family="paragraph" style:parent-style-name="Table_20_Contents">
+      <style:paragraph-properties fo:text-align="center" style:justify-single-word="false" />
+    </style:style>
+    <style:style style:name="P2" style:family="paragraph" style:parent-style-name="Table_20_Contents">
+      <style:paragraph-properties fo:text-align="center" style:justify-single-word="false" />
+    </style:style>
+    <style:style style:name="TableHeaderRowCell" style:family="table-cell">
+      <style:table-cell-properties fo:border="none" />
+    </style:style>
+    <style:style style:name="TableRowCell" style:family="table-cell">
+      <style:table-cell-properties fo:border="none" />
+    </style:style>
+    <style:style style:name="Table1" style:family="table">
+      <style:table-properties table:align="center" style:rel-width="50%" />
+    </style:style>
+    <style:style style:name="Table1.A" style:family="table-column">
+      <style:table-column-properties style:rel-column-width="16383*" />
+    </style:style>
+    <style:style style:name="Table1.B" style:family="table-column">
+      <style:table-column-properties style:rel-column-width="16383*" />
+    </style:style>
+  </office:automatic-styles>
+<office:body>
+<office:text>
+<table:table table:name="Table1" table:style-name="Table1">
+  <table:table-column table:style-name="Table1.A" />
+  <table:table-column table:style-name="Table1.B" />
+  <table:table-row>
+    <table:table-cell table:style-name="TableRowCell" office:value-type="string">
+      <text:p text:style-name="P1">2</text:p>
+    </table:table-cell>
+    <table:table-cell table:style-name="TableRowCell" office:value-type="string">
+      <text:p text:style-name="P2">1</text:p>
+    </table:table-cell>
+  </table:table-row>
+</table:table>
+</office:text>
+</office:body>
+</office:document-content>
+```
diff --git a/test/command/6796.md b/test/command/6796.md
new file mode 100644
--- /dev/null
+++ b/test/command/6796.md
@@ -0,0 +1,16 @@
+```
+% pandoc -f latex -t markdown
+\newcommand{\cL}{\mathcal{L}}
+\newcommand{\til}[1]{\tilde{#1}}
+
+$$\til\cL$$
+
+\newcommand{\mc}[1]{\mathcal{#1}}
+\newcommand{\dL}{\mc{L}}
+
+$$\til\dL$$
+^D
+$$\tilde{\mathcal{L}}$$
+
+$$\tilde{\mathcal{L}}$$
+```
diff --git a/test/command/6802.md b/test/command/6802.md
new file mode 100644
--- /dev/null
+++ b/test/command/6802.md
@@ -0,0 +1,8 @@
+```
+% pandoc -f latex -t native
+\blockquote[test][]{quote}
+^D
+[ BlockQuote [ Para [ Str "quote" ] , Para [ Str "test" ] ]
+]
+
+```
diff --git a/test/command/6821.md b/test/command/6821.md
new file mode 100644
--- /dev/null
+++ b/test/command/6821.md
@@ -0,0 +1,80 @@
+```
+% pandoc -f native -t latex
+[ Para [ Code ( "" , [ "python" ] , [] ) "x = 5" ]
+, Figure
+    ( "" , [] , [] )
+    (Caption
+       Nothing
+       [ Plain
+           [ Str "This"
+           , Space
+           , Str "is"
+           , Space
+           , Str "a"
+           , Space
+           , Str "test"
+           , Space
+           , Code ( "" , [ "python" ] , [] ) "x = 5"
+           ]
+       ])
+    [ Plain
+        [ Image
+            ( "" , [] , [] )
+            [ Str "This"
+            , Space
+            , Str "is"
+            , Space
+            , Str "a"
+            , Space
+            , Str "test"
+            , Space
+            , Code ( "" , [ "python" ] , [] ) "x = 5"
+            ]
+            ( "test.png" , "" )
+        ]
+    ]
+, Table
+    ( "" , [] , [] )
+    (Caption
+       Nothing
+       [ Plain [ Code ( "" , [ "cpp" ] , [] ) "caption" ] ])
+    [ ( AlignDefault , ColWidthDefault ) ]
+    (TableHead ( "" , [] , [] ) [])
+    [ TableBody ( "" , [] , [] ) (RowHeadColumns 0) [] [] ]
+    (TableFoot
+       ( "" , [] , [] )
+       [ Row
+           ( "" , [] , [] )
+           [ Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "A" ] ]
+           ]
+       ])
+, Para [ Code ( "" , [ "cpp" ] , [] ) "caption" ]
+]
+^D
+\VERB|\NormalTok{x }\OperatorTok{=} \DecValTok{5}|
+
+\begin{figure}
+\centering
+\pandocbounded{\includegraphics[keepaspectratio,alt={This is a test x = 5}]{test.png}}
+\caption{This is a test
+\protect\VERB|\NormalTok{x }\OperatorTok{=} \DecValTok{5}|}
+\end{figure}
+
+\begin{longtable}[]{@{}l@{}}
+\caption{\protect\VERB|\NormalTok{caption}|}\tabularnewline
+\toprule\noalign{}
+\endfirsthead
+\endhead
+\midrule\noalign{}
+A \\
+\bottomrule\noalign{}
+\endlastfoot
+\end{longtable}
+
+\VERB|\NormalTok{caption}|
+```
diff --git a/test/command/6836.md b/test/command/6836.md
new file mode 100644
--- /dev/null
+++ b/test/command/6836.md
@@ -0,0 +1,41 @@
+```
+% pandoc -t native
+[@buchanan]
+
+(@foo)
+
+See @foo.
+
+[@buchanan]
+^D
+[ Para
+    [ Cite
+        [ Citation
+            { citationId = "buchanan"
+            , citationPrefix = []
+            , citationSuffix = []
+            , citationMode = NormalCitation
+            , citationNoteNum = 1
+            , citationHash = 0
+            }
+        ]
+        [ Str "[@buchanan]" ]
+    ]
+, OrderedList ( 1 , Example , TwoParens ) [ [] ]
+, Para [ Str "See" , Space , Str "1." ]
+, Para
+    [ Cite
+        [ Citation
+            { citationId = "buchanan"
+            , citationPrefix = []
+            , citationSuffix = []
+            , citationMode = NormalCitation
+            , citationNoteNum = 2
+            , citationHash = 0
+            }
+        ]
+        [ Str "[@buchanan]" ]
+    ]
+]
+```
+
diff --git a/test/command/6837.md b/test/command/6837.md
new file mode 100644
--- /dev/null
+++ b/test/command/6837.md
@@ -0,0 +1,29 @@
+```
+% pandoc -t markdown --markdown-headings=setext
+## Hi
+
+### Ok
+^D
+Hi
+--
+
+### Ok
+```
+
+```
+% pandoc -t markdown+lhs
+# Hi
+^D
+2> [WARNING] Rendering heading 'Hi' as a paragraph.
+2>   ATX headings cannot be used in literate Haskell, because '#' is not
+2>   allowed in column 1. Consider using --markdown-headings=setext.
+Hi
+```
+
+```
+% pandoc -t markdown --markdown-headings=atx
+Hi
+--
+^D
+## Hi
+```
diff --git a/test/command/6844.md b/test/command/6844.md
new file mode 100644
--- /dev/null
+++ b/test/command/6844.md
@@ -0,0 +1,27 @@
+Negative numbers with siunitx
+
+```
+% pandoc -f latex -t native
+\SI{123}{\celsius}
+
+^D
+[ Para [ Str "123\160\176C" ] ]
+```
+
+```
+% pandoc -f latex -t native
+\SI{-123}{\celsius}
+
+^D
+[ Para [ Str "\8722\&123\160\176C" ] ]
+```
+
+```
+% pandoc -f latex -t native
+\SI{+123}{\celsius}
+
+^D
+[ Para [ Str "123\160\176C" ] ]
+```
+
+
diff --git a/test/command/6855.md b/test/command/6855.md
new file mode 100644
--- /dev/null
+++ b/test/command/6855.md
@@ -0,0 +1,12 @@
+```
+% pandoc -t markdown
+(@a) one
+(@b) two
+
+See (@a--@b)
+^D
+(1) one
+(2) two
+
+See (1--2)
+```
diff --git a/test/command/6858.md b/test/command/6858.md
new file mode 100644
--- /dev/null
+++ b/test/command/6858.md
@@ -0,0 +1,52 @@
+```
+% pandoc -t markdown -f man
+.TH FvwmAnimate 1 "Date" Fvwm "Fvwm Modules"
+.UC
+.SH NAME
+\fBFvwmAnimate\fP \- the fvwm animate module
+.SH SYNOPSIS
+Module FvwmAnimate [ModuleAlias]
+
+.IP "*FvwmAnimate: Color \fBcolor\fP"
+
+Tells \fBFvwmAnimate\fP what color to draw with.
+The color is "XOR'ed" (exclusive ORed) onto the background.
+
+.IP "*FvwmAnimate: Pixmap \fBpixmap\fP"
+
+Tells \fBFvwmAnimate\fP to use \fBpixmap\fP to draw with. This can be useful
+if \fB*FvwmAnimate: Color\fP gives poor results.
+^D
+# NAME
+
+**FvwmAnimate** - the fvwm animate module
+
+# SYNOPSIS
+
+Module FvwmAnimate \[ModuleAlias\]
+
+\*FvwmAnimate: Color color
+
+: Tells **FvwmAnimate** what color to draw with. The color is
+  \"XOR\'ed\" (exclusive ORed) onto the background.
+
+\*FvwmAnimate: Pixmap pixmap
+
+: Tells **FvwmAnimate** to use **pixmap** to draw with. This can be
+  useful if **\*FvwmAnimate: Color** gives poor results.
+```
+
+```
+% pandoc -t markdown -f man
+.IP "\[bu]"
+
+hi
+
+.IP "\[bu]"
+
+there
+^D
+- hi
+
+- there
+```
diff --git a/test/command/6869.md b/test/command/6869.md
new file mode 100644
--- /dev/null
+++ b/test/command/6869.md
@@ -0,0 +1,19 @@
+```
+% pandoc -f latex -t native
+\cite[„Aber“]{key}
+^D
+[ Para
+    [ Cite
+        [ Citation
+            { citationId = "key"
+            , citationPrefix = []
+            , citationSuffix = [ Str "\8222Aber\8220" ]
+            , citationMode = NormalCitation
+            , citationNoteNum = 0
+            , citationHash = 0
+            }
+        ]
+        [ RawInline (Format "latex") "\\cite[\8222Aber\8220]{key}" ]
+    ]
+]
+```
diff --git a/test/command/6873.md b/test/command/6873.md
new file mode 100644
--- /dev/null
+++ b/test/command/6873.md
@@ -0,0 +1,35 @@
+```
+% pandoc -f latex -t native --citeproc
+\cite[„Etwas […{]} auslassen“]{key}
+^D
+2> [WARNING] Citeproc: citation key not found
+[ Para
+    [ Cite
+        [ Citation
+            { citationId = "key"
+            , citationPrefix = []
+            , citationSuffix =
+                [ Str "\8222Etwas"
+                , Space
+                , Str "[\8230"
+                , Span ( "" , [] , [] ) [ Str "]" ]
+                , Space
+                , Str "auslassen\8220"
+                ]
+            , citationMode = NormalCitation
+            , citationNoteNum = 0
+            , citationHash = 0
+            }
+        ]
+        [ Str "("
+        , Strong [ Str "key?" ]
+        , Str "\8222Etwas"
+        , Space
+        , Str "[\8230"
+        , Span ( "" , [] , [] ) [ Str "]" ]
+        , Space
+        , Str "auslassen\8220)"
+        ]
+    ]
+]
+```
diff --git a/test/command/6890.md b/test/command/6890.md
new file mode 100644
--- /dev/null
+++ b/test/command/6890.md
@@ -0,0 +1,134 @@
+```
+% pandoc -t native --citeproc
+---
+references:
+- author:
+  - family: Früchtel
+    given: Frank
+  - family: Budde
+    given: Wolfgang
+  - family: Cyprian
+    given: Gudrun
+  edition: 3
+  id: fruchtel-sozialer-2013a
+  issued: 2013
+  language: de-DE
+  publisher: Springer VS
+  publisher-place: Wiesbaden, Germany
+  title: "Sozialer Raum und Soziale Arbeit Fieldbook: Methoden und
+    Techniken"
+  title-short: Sozialer Raum und Soziale Arbeit Fieldbook
+  type: book
+---
+
+@fruchtel-sozialer-2013a
+
+Some text.[^1]
+
+[^1]: @fruchtel-sozialer-2013a
+^D
+[ Para
+    [ Cite
+        [ Citation
+            { citationId = "fruchtel-sozialer-2013a"
+            , citationPrefix = []
+            , citationSuffix = []
+            , citationMode = AuthorInText
+            , citationNoteNum = 1
+            , citationHash = 0
+            }
+        ]
+        [ Str "Fr\252chtel"
+        , Space
+        , Str "et"
+        , Space
+        , Str "al."
+        , Space
+        , Str "(2013)"
+        ]
+    ]
+, Para
+    [ Str "Some"
+    , Space
+    , Str "text."
+    , Note
+        [ Para
+            [ Cite
+                [ Citation
+                    { citationId = "fruchtel-sozialer-2013a"
+                    , citationPrefix = []
+                    , citationSuffix = []
+                    , citationMode = AuthorInText
+                    , citationNoteNum = 2
+                    , citationHash = 0
+                    }
+                ]
+                [ Str "Fr\252chtel"
+                , Space
+                , Str "et"
+                , Space
+                , Str "al."
+                , Space
+                , Str "(2013)"
+                ]
+            ]
+        ]
+    ]
+, Div
+    ( "refs"
+    , [ "references" , "csl-bib-body" , "hanging-indent" ]
+    , []
+    )
+    [ Div
+        ( "ref-fruchtel-sozialer-2013a" , [ "csl-entry" ] , [] )
+        [ Para
+            [ Str "Fr\252chtel,"
+            , Space
+            , Str "Frank,"
+            , Space
+            , Str "Wolfgang"
+            , Space
+            , Str "Budde,"
+            , Space
+            , Str "and"
+            , Space
+            , Str "Gudrun"
+            , Space
+            , Str "Cyprian."
+            , Space
+            , Str "2013."
+            , Space
+            , Emph
+                [ Str "Sozialer"
+                , Space
+                , Str "Raum"
+                , Space
+                , Str "und"
+                , Space
+                , Str "Soziale"
+                , Space
+                , Str "Arbeit"
+                , Space
+                , Str "Fieldbook:"
+                , Space
+                , Str "Methoden"
+                , Space
+                , Str "und"
+                , Space
+                , Str "Techniken"
+                ]
+            , Str "."
+            , Space
+            , Str "3rd"
+            , Space
+            , Str "ed."
+            , Space
+            , Str "Springer"
+            , Space
+            , Str "VS."
+            ]
+        ]
+    ]
+]
+```
+
diff --git a/test/command/6925.md b/test/command/6925.md
new file mode 100644
--- /dev/null
+++ b/test/command/6925.md
@@ -0,0 +1,34 @@
+```
+% pandoc -f latex -t markdown
+\documentclass{amsart}
+\newtheorem{thm}{Theorem}[section]
+\theoremstyle{definition}
+\newtheorem{thm2}[section]{Theorem}
+\begin{document}
+\begin{thm}
+a
+\begin{figure}
+\includegraphics[]{1.png}
+\end{figure}
+\end{thm}
+
+\begin{thm2}
+a
+\begin{figure}
+\includegraphics[]{1.png}
+\end{figure}
+\end{thm2}
+\end{document}
+^D
+::: thm
+**Theorem 1**. *a*
+
+![](1.png)
+:::
+
+::: thm2
+**Theorem 1**. a
+
+![](1.png)
+:::
+```
diff --git a/test/command/6948.md b/test/command/6948.md
new file mode 100644
--- /dev/null
+++ b/test/command/6948.md
@@ -0,0 +1,31 @@
+Treat an image alone in its paragraph (but not a figure)
+as an independent image:
+```
+% pandoc -f native -t rst
+[Para [Image ("",["align-center"],[]) [Str "https://pandoc.org/diagram.jpg"] ("https://pandoc.org/diagram.jpg","")]]
+^D
+|https://pandoc.org/diagram.jpg|
+
+.. |https://pandoc.org/diagram.jpg| image:: https://pandoc.org/diagram.jpg
+```
+
+Here we just omit the center attribute as it's not valid:
+```
+% pandoc -f native -t rst
+[Para [Str "hi",Space,Image ("",["align-center"],[]) [Str "https://pandoc.org/diagram.jpg"] ("https://pandoc.org/diagram.jpg","")]]
+^D
+hi |https://pandoc.org/diagram.jpg|
+
+.. |https://pandoc.org/diagram.jpg| image:: https://pandoc.org/diagram.jpg
+```
+
+But we can use top, middle, or bottom alignment:
+```
+% pandoc -f native -t rst
+[Para [Str "hi",Space,Image ("",["align-top"],[]) [Str "https://pandoc.org/diagram.jpg"] ("https://pandoc.org/diagram.jpg","")]]
+^D
+hi |https://pandoc.org/diagram.jpg|
+
+.. |https://pandoc.org/diagram.jpg| image:: https://pandoc.org/diagram.jpg
+   :align: top
+```
diff --git a/test/command/6951.md b/test/command/6951.md
new file mode 100644
--- /dev/null
+++ b/test/command/6951.md
@@ -0,0 +1,18 @@
+```
+% pandoc --citeproc -t plain --bibliography command/biblio.bib
+---
+references:
+- id: foo
+  title: Crazy
+  type: book
+...
+
+[@foo; @item1]
+
+^D
+(Crazy, n.d.; Doe 2005)
+
+Crazy. n.d.
+
+Doe, John. 2005. First Book. Cambridge University Press.
+```
diff --git a/test/command/6958.md b/test/command/6958.md
new file mode 100644
--- /dev/null
+++ b/test/command/6958.md
@@ -0,0 +1,10 @@
+Add thin space between single and double quotes.
+```
+% pandoc -t latex+smart
+---
+lang: en-GB
+---
+'["On the Outside"]{}: Constructing Cycling Citizenship.'
+^D
+`\,{``On the Outside''}: Constructing Cycling Citizenship.'
+```
diff --git a/test/command/6959.md b/test/command/6959.md
new file mode 100644
--- /dev/null
+++ b/test/command/6959.md
@@ -0,0 +1,12 @@
+```
+% pandoc -t docx -o - | pandoc -f docx -t markdown --track-changes=all
+[This is the comment]{.comment-start id="1" author="Mike"
+date="2020-12-17T16:53:00Z"} [Here is my reply]{.comment-start id="2"
+author="Mike" date="2020-12-17T17:39:00Z"} This is the content being
+commented on [[]{.comment-end id="2"}]{.comment-end id="1"}
+^D
+[This is the comment]{.comment-start id="1" author="Mike"
+date="2020-12-17T16:53:00Z"} [Here is my reply]{.comment-start id="2"
+author="Mike" date="2020-12-17T17:39:00Z"} This is the content being
+commented on [[]{.comment-end id="2"}]{.comment-end id="1"}
+```
diff --git a/test/command/6970.md b/test/command/6970.md
new file mode 100644
--- /dev/null
+++ b/test/command/6970.md
@@ -0,0 +1,12 @@
+```
+% pandoc -f html -t native
+<a name="foo" class="bar baz" href='https://example.com' target='_blank'>https://example.com<a>
+^D
+[ Plain
+    [ Link
+        ( "foo" , [ "bar" , "baz" ] , [ ( "target" , "_blank" ) ] )
+        [ Str "https://example.com" ]
+        ( "https://example.com" , "" )
+    ]
+]
+```
diff --git a/test/command/6992.md b/test/command/6992.md
new file mode 100644
--- /dev/null
+++ b/test/command/6992.md
@@ -0,0 +1,76 @@
+```
+% pandoc -f mediawiki -t native
+{| class="wikitable"
+!colspan=4 | template request
+|-
+| mode || No || String || MUST be "template" or omitted
+|}
+^D
+[ Table
+    ( "" , [] , [] )
+    (Caption Nothing [])
+    [ ( AlignDefault , ColWidthDefault )
+    , ( AlignDefault , ColWidthDefault )
+    , ( AlignDefault , ColWidthDefault )
+    , ( AlignDefault , ColWidthDefault )
+    ]
+    (TableHead
+       ( "" , [] , [] )
+       [ Row
+           ( "" , [] , [] )
+           [ Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 4)
+               [ Para [ Str "template" , Space , Str "request" ] ]
+           ]
+       ])
+    [ TableBody
+        ( "" , [] , [] )
+        (RowHeadColumns 0)
+        []
+        [ Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Para [ Str "mode" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Para [ Str "No" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Para [ Str "String" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Para
+                    [ Str "MUST"
+                    , Space
+                    , Str "be"
+                    , Space
+                    , Str "\"template\""
+                    , Space
+                    , Str "or"
+                    , Space
+                    , Str "omitted"
+                    ]
+                ]
+            ]
+        ]
+    ]
+    (TableFoot ( "" , [] , [] ) [])
+]
+
+```
diff --git a/test/command/6993.md b/test/command/6993.md
new file mode 100644
--- /dev/null
+++ b/test/command/6993.md
@@ -0,0 +1,33 @@
+```
+% pandoc -f mediawiki -t native
+'''Should be bold '''
+^D
+[ Para
+    [ Strong
+        [ Str "Should" , Space , Str "be" , Space , Str "bold" ]
+    ]
+]
+```
+
+```
+% pandoc -f mediawiki -t native
+''' Should be bold'''
+^D
+[ Para
+    [ Strong
+        [ Str "Should" , Space , Str "be" , Space , Str "bold" ]
+    ]
+]
+```
+
+```
+% pandoc -f mediawiki -t native
+'' Should be emph ''
+^D
+[ Para
+    [ Emph
+        [ Str "Should" , Space , Str "be" , Space , Str "emph" ]
+    ]
+]
+```
+
diff --git a/test/command/7003.md b/test/command/7003.md
new file mode 100644
--- /dev/null
+++ b/test/command/7003.md
@@ -0,0 +1,58 @@
+```
+% pandoc -f latex -t native
+\documentclass{article}
+\usepackage{listings}
+
+\lstset{basicstyle=\ttfamily}
+
+\begin{filecontents*}[overwrite]{example.tex}
+\documentclass{article}
+\begin{document}
+\section{Bar}
+This a Bar section
+\end{document}
+\end{filecontents*}
+
+\begin{document}
+
+\section{With lstlisting environment}
+
+\begin{lstlisting}
+\documentclass{article}
+\begin{document}
+\section{Foo}
+This a Foo section
+\end{document}
+\end{lstlisting}
+
+\section{With lstinputlisting command}
+
+\lstinputlisting{example.tex}
+\end{document}
+^D
+[ Header
+    1
+    ( "with-lstlisting-environment" , [] , [] )
+    [ Str "With"
+    , Space
+    , Str "lstlisting"
+    , Space
+    , Str "environment"
+    ]
+, CodeBlock
+    ( "" , [] , [] )
+    "\\documentclass{article}\n\\begin{document}\n\\section{Foo}\nThis a Foo section\n\\end{document}"
+, Header
+    1
+    ( "with-lstinputlisting-command" , [] , [] )
+    [ Str "With"
+    , Space
+    , Str "lstinputlisting"
+    , Space
+    , Str "command"
+    ]
+, CodeBlock
+    ( "" , [ "latex" ] , [] )
+    "\\documentclass{article}\n\\begin{document}\n\\section{Bar}\nThis a Bar section\n\\end{document}"
+]
+```
diff --git a/test/command/7006.md b/test/command/7006.md
new file mode 100644
--- /dev/null
+++ b/test/command/7006.md
@@ -0,0 +1,23 @@
+```
+% pandoc -t html
+Test.[^fn]
+
+[^fn]: Foo:
+
+    ![Caption.](/image.jpg)
+^D
+<p>Test.<a href="#fn1" class="footnote-ref" id="fnref1"
+role="doc-noteref"><sup>1</sup></a></p>
+<section id="footnotes" class="footnotes footnotes-end-of-document"
+role="doc-endnotes">
+<hr />
+<ol>
+<li id="fn1"><p>Foo:</p>
+<figure>
+<img src="/image.jpg" alt="Caption." />
+<figcaption aria-hidden="true">Caption.</figcaption>
+</figure>
+<a href="#fnref1" class="footnote-back" role="doc-backlink">↩︎</a></li>
+</ol>
+</section>
+```
diff --git a/test/command/7009.md b/test/command/7009.md
new file mode 100644
--- /dev/null
+++ b/test/command/7009.md
@@ -0,0 +1,8 @@
+```
+% pandoc -t gfm
+3. a
+4. b
+^D
+3.  a
+4.  b
+```
diff --git a/test/command/7016.md b/test/command/7016.md
new file mode 100644
--- /dev/null
+++ b/test/command/7016.md
@@ -0,0 +1,51 @@
+```
+% pandoc --citeproc --to=jats_archiving --standalone
+---
+csl: command/apa.csl
+references:
+- id: doe
+  type: article
+  author:
+  - family: Doe
+    given: Jane
+  container-title: Proceedings of the Academy of Test Inputs
+  doi: 10.x/nope
+  issued: 2021
+  title: Another article
+...
+Blah [@doe].
+^D
+<?xml version="1.0" encoding="utf-8" ?>
+<!DOCTYPE article PUBLIC "-//NLM//DTD JATS (Z39.96) Journal Archiving and Interchange DTD v1.2 20190208//EN"
+                  "JATS-archivearticle1.dtd">
+<article xmlns:mml="http://www.w3.org/1998/Math/MathML" xmlns:xlink="http://www.w3.org/1999/xlink" dtd-version="1.2" article-type="other">
+<front>
+<journal-meta>
+<journal-id></journal-id>
+<journal-title-group>
+</journal-title-group>
+<issn></issn>
+<publisher>
+<publisher-name></publisher-name>
+</publisher>
+</journal-meta>
+<article-meta>
+<permissions>
+</permissions>
+</article-meta>
+</front>
+<body>
+<p>Blah (Doe, 2021).</p>
+</body>
+<back>
+<ref-list>
+  <title></title>
+  <ref id="ref-doe">
+    <mixed-citation>Doe, J. (2021). Another article. <italic>Proceedings
+    of the Academy of Test Inputs</italic>.
+    doi:<ext-link ext-link-type="uri" xlink:href="https://doi.org/10.x/nope">10.x/nope</ext-link></mixed-citation>
+  </ref>
+</ref-list>
+</back>
+</article>
+```
diff --git a/test/command/7041.md b/test/command/7041.md
new file mode 100644
--- /dev/null
+++ b/test/command/7041.md
@@ -0,0 +1,23 @@
+```
+% pandoc -f html -t jats
+<table>
+  <tr><td><blockquote>Fly, you fools!</blockquote></td></tr>
+</table>
+^D
+<table-wrap>
+  <table>
+    <colgroup>
+      <col width="100%" />
+    </colgroup>
+    <tbody>
+      <tr>
+        <td><p specific-use="wrapper">
+          <disp-quote>
+            <p>Fly, you fools!</p>
+          </disp-quote>
+        </p></td>
+      </tr>
+    </tbody>
+  </table>
+</table-wrap>
+```
diff --git a/test/command/7042.md b/test/command/7042.md
new file mode 100644
--- /dev/null
+++ b/test/command/7042.md
@@ -0,0 +1,149 @@
+```
+% pandoc -f markdown -t jats_publishing+element_citations --citeproc -s
+---
+nocite: "[@*]"
+references:
+- author:
+  - family: Jane
+    given: Doe
+  container-title: Public Library of Tests
+  id: year-month
+  issued: 1999-08
+  title: Year and month
+  type: article-journal
+- accessed: 1999-01-22
+  author:
+  - family: Negidius
+    given: Numerius
+  - literal: others
+  container-title: Public Library of Tests
+  id: access-date
+  issued: 1911-10-03
+  title: Entry with access date and et al.
+  type: article-journal
+- author:
+  - family: Beethoven
+    given: Ludwig
+    dropping-particle: van
+  - family: Bray
+    given: Jan
+    non-dropping-particle: de
+  container-title: Public Library of Tests
+  id: name-particles
+  issued: 1820
+  title: Name particles, dropping and non-dropping
+  type: article-journal
+- author:
+  - 宮水 三葉
+  - 立花 瀧
+  title: Big Book of Tests
+  id: book-with-japanese-authors
+  issued: 2016
+  type: book
+- author:
+  - family: Watson
+    given: J. D.
+  - family: Crick
+    given: F. H. C.
+  container-title: Nature
+  doi: '10.1038/171737a0'
+  id: full-journal-article-entry
+  issue: 4356
+  issued: '1953-04-01'
+  page: 737-738
+  pmid: 13054692
+  title: 'Molecular Structure of Nucleic Acids: A Structure for Deoxyribose Nucleic Acid'
+  type: article-journal
+  volume: 171
+...
+^D
+<?xml version="1.0" encoding="utf-8" ?>
+<!DOCTYPE article PUBLIC "-//NLM//DTD JATS (Z39.96) Journal Publishing DTD v1.2 20190208//EN"
+                  "JATS-publishing1.dtd">
+<article xmlns:mml="http://www.w3.org/1998/Math/MathML" xmlns:xlink="http://www.w3.org/1999/xlink" dtd-version="1.2" article-type="other">
+<front>
+<journal-meta>
+<journal-id></journal-id>
+<journal-title-group>
+</journal-title-group>
+<issn></issn>
+<publisher>
+<publisher-name></publisher-name>
+</publisher>
+</journal-meta>
+<article-meta>
+<permissions>
+</permissions>
+</article-meta>
+</front>
+<body>
+
+</body>
+<back>
+<ref-list>
+  <title></title>
+  <ref id="ref-year-month">
+    <element-citation publication-type="article-journal">
+      <person-group person-group-type="author">
+        <name><surname>Jane</surname><given-names>Doe</given-names></name>
+      </person-group>
+      <article-title>Year and month</article-title>
+      <source>Public Library of Tests</source>
+      <year iso-8601-date="1999-08">1999</year><month>08</month>
+    </element-citation>
+  </ref>
+  <ref id="ref-access-date">
+    <element-citation publication-type="article-journal">
+      <person-group person-group-type="author">
+        <name><surname>Negidius</surname><given-names>Numerius</given-names></name>
+        <etal/>
+      </person-group>
+      <article-title>Entry with access date and et al.</article-title>
+      <source>Public Library of Tests</source>
+      <year iso-8601-date="1911-10-03">1911</year><month>10</month><day>03</day>
+      <date-in-citation content-type="access-date"><year iso-8601-date="1999-01-22">1999</year><month>01</month><day>22</day></date-in-citation>
+    </element-citation>
+  </ref>
+  <ref id="ref-name-particles">
+    <element-citation publication-type="article-journal">
+      <person-group person-group-type="author">
+        <name><surname>Beethoven</surname><given-names>Ludwig van</given-names></name>
+        <name><surname>de Bray</surname><given-names>Jan</given-names></name>
+      </person-group>
+      <article-title>Name particles, dropping and non-dropping</article-title>
+      <source>Public Library of Tests</source>
+      <year iso-8601-date="1820">1820</year>
+    </element-citation>
+  </ref>
+  <ref id="ref-book-with-japanese-authors">
+    <element-citation publication-type="book">
+      <person-group person-group-type="author">
+        <string-name>宮水 三葉</string-name>
+        <string-name>立花 瀧</string-name>
+      </person-group>
+      <source>Big Book of Tests</source>
+      <year iso-8601-date="2016">2016</year>
+    </element-citation>
+  </ref>
+  <ref id="ref-full-journal-article-entry">
+    <element-citation publication-type="article-journal">
+      <person-group person-group-type="author">
+        <name><surname>Watson</surname><given-names>J. D.</given-names></name>
+        <name><surname>Crick</surname><given-names>F. H. C.</given-names></name>
+      </person-group>
+      <article-title>Molecular Structure of Nucleic Acids: A Structure for Deoxyribose Nucleic Acid</article-title>
+      <source>Nature</source>
+      <year iso-8601-date="1953-04-01">1953</year><month>04</month><day>01</day>
+      <volume>171</volume>
+      <issue>4356</issue>
+      <pub-id pub-id-type="doi">10.1038/171737a0</pub-id>
+      <pub-id pub-id-type="pmid">13054692</pub-id>
+      <fpage>737</fpage>
+      <lpage>738</lpage>
+    </element-citation>
+  </ref>
+</ref-list>
+</back>
+</article>
+
+```
diff --git a/test/command/7058.md b/test/command/7058.md
new file mode 100644
--- /dev/null
+++ b/test/command/7058.md
@@ -0,0 +1,6 @@
+```
+% pandoc -f latex -t markdown
+5\(-\)8 \(x\)
+^D
+5$-$`<!-- -->`{=html}8 $x$
+```
diff --git a/test/command/7064.md b/test/command/7064.md
new file mode 100644
--- /dev/null
+++ b/test/command/7064.md
@@ -0,0 +1,32 @@
+```
+% pandoc -f rst -t html
+.. csv-table:: Changes
+    :header: "Version", "Date", "Description"
+    :widths: 15, 15, 70
+    :delim: $
+
+    0.1.0 $ 18/02/2013 $ Initial Release
+^D
+<table>
+<caption>Changes</caption>
+<colgroup>
+<col style="width: 15%" />
+<col style="width: 15%" />
+<col style="width: 70%" />
+</colgroup>
+<thead>
+<tr>
+<th>Version</th>
+<th>Date</th>
+<th>Description</th>
+</tr>
+</thead>
+<tbody>
+<tr>
+<td>0.1.0</td>
+<td>18/02/2013</td>
+<td>Initial Release</td>
+</tr>
+</tbody>
+</table>
+```
diff --git a/test/command/7067.md b/test/command/7067.md
new file mode 100644
--- /dev/null
+++ b/test/command/7067.md
@@ -0,0 +1,90 @@
+```
+% pandoc -t biblatex
+---
+references:
+- id: garaud
+  author:
+    - family: Garaud
+      given: Marcel
+  container-title: Bulletin de la Societé des antiquaires de l’Ouest
+  collection-title: 4
+  issued:
+    - year: 1967
+  language: fr-FR
+  page: 11-27
+  title: Recherches sur les défrichements dans la Gâtine poitevine aux XI^e^ et XII^e^ siècles
+  type: article-journal
+  volume: 9
+...
+^D
+@article{garaud,
+  author = {Garaud, Marcel},
+  title = {Recherches sur les défrichements dans la Gâtine poitevine aux
+    XI\textsuperscript{e} et XII\textsuperscript{e} siècles},
+  journal = {Bulletin de la Societé des antiquaires de l’Ouest},
+  series = {4},
+  volume = {9},
+  pages = {11-27},
+  date = {1967},
+  langid = {fr-FR}
+}
+```
+
+```
+% pandoc -t bibtex
+---
+references:
+- id: garaud
+  author:
+    - family: Garaud
+      given: Marcel
+  container-title: Bulletin de la Société des antiquaires de l’Ouest
+  collection-title: 4
+  issued:
+    - year: 1967
+  language: fr-FR
+  page: 11-27
+  title: Recherches sur les défrichements dans la Gâtine poitevine aux XI^e^ et XII^e^ siècles
+  type: article-journal
+  volume: 9
+...
+^D
+@article{garaud,
+  author = {Garaud, Marcel},
+  title = {{Recherches sur les défrichements dans la Gâtine poitevine
+    aux XI\textsuperscript{e} et XII\textsuperscript{e} siècles}},
+  journal = {Bulletin de la Société des antiquaires de l’Ouest},
+  series = {4},
+  volume = {9},
+  pages = {11-27},
+  year = {1967}
+}
+```
+
+This tests the titlecasing of a word with an accented second letter:
+```
+% pandoc -t bibtex
+---
+references:
+- id: garaud
+  author:
+    - family: Garaud
+      given: Marcel
+  container-title: English Journal
+  issued:
+    - year: 1967
+  language: en-US
+  title: Research on the défrichements in the Gâtine poitevine
+  type: article-journal
+  volume: 9
+...
+^D
+@article{garaud,
+  author = {Garaud, Marcel},
+  title = {Research on the Défrichements in the {Gâtine} Poitevine},
+  journal = {English Journal},
+  volume = {9},
+  year = {1967}
+}
+```
+
diff --git a/test/command/7080.md b/test/command/7080.md
new file mode 100644
--- /dev/null
+++ b/test/command/7080.md
@@ -0,0 +1,17 @@
+```
+% pandoc -f markdown_mmd -t native
+![][image]
+
+[image]: image.png width=100px height=150px
+^D
+[ Para
+    [ Image
+        ( ""
+        , []
+        , [ ( "width" , "100px" ) , ( "height" , "150px" ) ]
+        )
+        []
+        ( "image.png" , "" )
+    ]
+]
+```
diff --git a/test/command/7092.md b/test/command/7092.md
new file mode 100644
--- /dev/null
+++ b/test/command/7092.md
@@ -0,0 +1,10 @@
+```
+% pandoc -flatex+raw_tex -t native
+\newcommand{\em}[1]{\emph{#1}}
+
+\em{\parseMe{foo}}
+^D
+[ Para
+    [ Emph [ RawInline (Format "latex") "\\parseMe{foo}" ] ]
+]
+```
diff --git a/test/command/7099.md b/test/command/7099.md
new file mode 100644
--- /dev/null
+++ b/test/command/7099.md
@@ -0,0 +1,18 @@
+```
+% pandoc -f html -t native --verbose
+<iframe src=""></iframe>
+^D
+2> [INFO] Skipped '<iframe src></iframe>' at input line 1 column 16
+[]
+```
+
+```
+% pandoc -f html -t native --verbose
+<iframe src="h:invalid@url"></iframe>
+^D
+2> [INFO] Fetching h:invalid@url...
+2> [WARNING] Could not fetch resource h:invalid@url: Could not fetch h:invalid@url
+2>   InvalidUrlException "h:invalid@url" "Invalid scheme"
+2> [INFO] Skipped '<iframe src="h:invalid@url"></iframe>' at input line 1 column 29
+[]
+```
diff --git a/test/command/7112.md b/test/command/7112.md
new file mode 100644
--- /dev/null
+++ b/test/command/7112.md
@@ -0,0 +1,15 @@
+```
+% pandoc -f rst
+.. csv-table::
+
+   setting, ``echo PATH="path"``
+^D
+<table>
+<tbody>
+<tr>
+<td>setting</td>
+<td><code>echo PATH="path"</code></td>
+</tr>
+</tbody>
+</table>
+```
diff --git a/test/command/7129.md b/test/command/7129.md
new file mode 100644
--- /dev/null
+++ b/test/command/7129.md
@@ -0,0 +1,55 @@
+```
+% pandoc -f latex -t native
+\begin{tabular}{ll} \hline
+  FOO & BAR         \\ \hline
+  foo & \verb|b&r|  \\ \hline
+\end{tabular}
+^D
+[ Table
+    ( "" , [] , [] )
+    (Caption Nothing [])
+    [ ( AlignLeft , ColWidthDefault )
+    , ( AlignLeft , ColWidthDefault )
+    ]
+    (TableHead
+       ( "" , [] , [] )
+       [ Row
+           ( "" , [] , [] )
+           [ Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "FOO" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "BAR" ] ]
+           ]
+       ])
+    [ TableBody
+        ( "" , [] , [] )
+        (RowHeadColumns 0)
+        []
+        [ Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "foo" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Code ( "" , [] , [] ) "b&r" ] ]
+            ]
+        ]
+    ]
+    (TableFoot ( "" , [] , [] ) [])
+]
+```
diff --git a/test/command/7132.md b/test/command/7132.md
new file mode 100644
--- /dev/null
+++ b/test/command/7132.md
@@ -0,0 +1,10 @@
+```
+% pandoc -f markdown -t org --columns=72
+- This line has exactly the wrong number of characters before the number 5.
+- Long line ending with a number (this time it is in parentheses and a 23)
+^D
+- This line has exactly the wrong number of characters before the
+  number 5.
+- Long line ending with a number (this time it is in parentheses and
+  a 23)
+```
diff --git a/test/command/7134.md b/test/command/7134.md
new file mode 100644
--- /dev/null
+++ b/test/command/7134.md
@@ -0,0 +1,51 @@
+```
+% pandoc -f rst -t native
+This is a paragraph.
+
+    This is a block quote.
+
+..
+
+    This should be a second block quote.
+^D
+[ Para
+    [ Str "This"
+    , Space
+    , Str "is"
+    , Space
+    , Str "a"
+    , Space
+    , Str "paragraph."
+    ]
+, BlockQuote
+    [ Para
+        [ Str "This"
+        , Space
+        , Str "is"
+        , Space
+        , Str "a"
+        , Space
+        , Str "block"
+        , Space
+        , Str "quote."
+        ]
+    ]
+, BlockQuote
+    [ Para
+        [ Str "This"
+        , Space
+        , Str "should"
+        , Space
+        , Str "be"
+        , Space
+        , Str "a"
+        , Space
+        , Str "second"
+        , Space
+        , Str "block"
+        , Space
+        , Str "quote."
+        ]
+    ]
+]
+```
diff --git a/test/command/7145.md b/test/command/7145.md
new file mode 100644
--- /dev/null
+++ b/test/command/7145.md
@@ -0,0 +1,72 @@
+```
+% pandoc -f mediawiki -t native
+Maecenas at sapien tempor, pretium turpis ut, imperdiet augue.<ref>This is a multiline
+
+reference
+<i>with</i>
+empty
+
+linebreaks</ref>  Nulla ut massa eget ex venenatis lobortis id in eros.
+^D
+[ Para
+    [ Str "Maecenas"
+    , Space
+    , Str "at"
+    , Space
+    , Str "sapien"
+    , Space
+    , Str "tempor,"
+    , Space
+    , Str "pretium"
+    , Space
+    , Str "turpis"
+    , Space
+    , Str "ut,"
+    , Space
+    , Str "imperdiet"
+    , Space
+    , Str "augue."
+    , Note
+        [ Para
+            [ Str "This"
+            , Space
+            , Str "is"
+            , Space
+            , Str "a"
+            , Space
+            , Str "multiline"
+            ]
+        , Para
+            [ Str "reference"
+            , SoftBreak
+            , RawInline (Format "html") "<i>"
+            , Str "with"
+            , RawInline (Format "html") "</i>"
+            , SoftBreak
+            , Str "empty"
+            ]
+        , Para [ Str "linebreaks" ]
+        ]
+    , Space
+    , Str "Nulla"
+    , Space
+    , Str "ut"
+    , Space
+    , Str "massa"
+    , Space
+    , Str "eget"
+    , Space
+    , Str "ex"
+    , Space
+    , Str "venenatis"
+    , Space
+    , Str "lobortis"
+    , Space
+    , Str "id"
+    , Space
+    , Str "in"
+    , Space
+    , Str "eros."
+    ]
+]
+```
diff --git a/test/command/7155.md b/test/command/7155.md
new file mode 100644
--- /dev/null
+++ b/test/command/7155.md
@@ -0,0 +1,33 @@
+```
+% pandoc -f markdown+tex_math_single_backslash -t native
+\(x\) \[x\]
+\\(x\\) \\[x\\]
+^D
+[ Para
+    [ Math InlineMath "x"
+    , Space
+    , Math DisplayMath "x"
+    , SoftBreak
+    , Str "\\(x\\)"
+    , Space
+    , Str "\\[x\\]"
+    ]
+]
+```
+
+```
+% pandoc -f markdown+tex_math_double_backslash -t native
+\(x\) \[x\]
+\\(x\\) \\[x\\]
+^D
+[ Para
+    [ Str "(x)"
+    , Space
+    , Str "[x]"
+    , SoftBreak
+    , Math InlineMath "x"
+    , Space
+    , Math DisplayMath "x"
+    ]
+]
+```
diff --git a/test/command/7172.md b/test/command/7172.md
new file mode 100644
--- /dev/null
+++ b/test/command/7172.md
@@ -0,0 +1,17 @@
+```
+% pandoc -t markdown
+- one
+  - two
+^D
+- one
+  - two
+```
+
+```
+% pandoc -t markdown+four_space_rule
+- one
+  - two
+^D
+-   one
+    -   two
+```
diff --git a/test/command/7173.md b/test/command/7173.md
new file mode 100644
--- /dev/null
+++ b/test/command/7173.md
@@ -0,0 +1,137 @@
+```
+% pandoc -f docbook -t latex
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE article PUBLIC "-//W3C//DTD MathML 2.0//EN" "http://www.w3.org/Math/DTD/mathml2/mathml2.dtd">
+<?xml-model href="http://www.oxygenxml.com/docbook/xml/5.0/rng/dbmathml.rng" schematypens="http://relaxng.org/ns/structure/1.0"?>
+<?xml-model href="http://docbook.org/xml/5.0/rng/docbook.rng" type="application/xml" schematypens="http://purl.oclc.org/dsdl/schematron"?>
+<article xmlns="http://docbook.org/ns/docbook"
+    xmlns:xlink="http://www.w3.org/1999/xlink"
+    version="5.1">
+    <title>Untitled Document</title>
+    <para>Word</para>
+    <informalequation>
+        <alt role='tex'>1+2</alt>
+        <m:math xmlns:m="http://www.w3.org/1998/Math/MathML">
+            <m:mrow>
+                <m:mrow><m:mn>1</m:mn><m:mo>+</m:mo><m:mn>2</m:mn>
+                </m:mrow>
+            </m:mrow>
+        </m:math>
+    </informalequation>
+</article>
+^D
+Word
+
+\[1 + 2\]
+```
+
+```
+% pandoc -f docbook -t latex
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE article PUBLIC "-//W3C//DTD MathML 2.0//EN" "http://www.w3.org/Math/DTD/mathml2/mathml2.dtd">
+<?xml-model href="http://www.oxygenxml.com/docbook/xml/5.0/rng/dbmathml.rng" schematypens="http://relaxng.org/ns/structure/1.0"?>
+<?xml-model href="http://docbook.org/xml/5.0/rng/docbook.rng" type="application/xml" schematypens="http://purl.oclc.org/dsdl/schematron"?>
+<article xmlns="http://docbook.org/ns/docbook"
+    xmlns:xlink="http://www.w3.org/1999/xlink"
+    version="5.1">
+    <title>Untitled Document</title>
+    <para>Word</para>
+    <informalequation>
+        <alt role='tex'>1+2</alt>
+        <mml:math xmlns:mml="http://www.w3.org/1998/Math/MathML">
+            <mml:mrow>
+                <mml:mrow><mml:mn>1</mml:mn><mml:mo>+</mml:mo><mml:mn>2</mml:mn>
+                </mml:mrow>
+            </mml:mrow>
+        </mml:math>
+    </informalequation>
+</article>
+^D
+Word
+
+\[1 + 2\]
+```
+
+```
+% pandoc -f docbook -t latex
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE article PUBLIC "-//W3C//DTD MathML 2.0//EN" "http://www.w3.org/Math/DTD/mathml2/mathml2.dtd">
+<?xml-model href="http://www.oxygenxml.com/docbook/xml/5.0/rng/dbmathml.rng" schematypens="http://relaxng.org/ns/structure/1.0"?>
+<?xml-model href="http://docbook.org/xml/5.0/rng/docbook.rng" type="application/xml" schematypens="http://purl.oclc.org/dsdl/schematron"?>
+<article xmlns="http://docbook.org/ns/docbook"
+    xmlns:xlink="http://www.w3.org/1999/xlink"
+    version="5.1">
+    <title>Untitled Document</title>
+    <para>Word</para>
+    <informalequation>
+        <alt role='tex'>1+2</alt>
+        <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <mrow>
+                <mrow><mn>1</mn><mo>+</mo><mn>2</mn>
+                </mrow>
+            </mrow>
+        </math>
+    </informalequation>
+</article>
+^D
+Word
+
+\[1 + 2\]
+```
+
+```
+% pandoc -f docbook -t latex
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE article PUBLIC "-//W3C//DTD MathML 2.0//EN" "http://www.w3.org/Math/DTD/mathml2/mathml2.dtd">
+<?xml-model href="http://www.oxygenxml.com/docbook/xml/5.0/rng/dbmathml.rng" schematypens="http://relaxng.org/ns/structure/1.0"?>
+<?xml-model href="http://docbook.org/xml/5.0/rng/docbook.rng" type="application/xml" schematypens="http://purl.oclc.org/dsdl/schematron"?>
+<article xmlns="http://docbook.org/ns/docbook"
+    xmlns:xlink="http://www.w3.org/1999/xlink"
+    xmlns:m="http://www.w3.org/1998/Math/MathML"
+    version="5.1">
+    <title>Untitled Document</title>
+    <para>Word</para>
+    <informalequation>
+        <alt role='tex'>1+2</alt>
+        <m:math>
+            <m:mrow>
+                <m:mrow><m:mn>1</m:mn><m:mo>+</m:mo><m:mn>2</m:mn>
+                </m:mrow>
+            </m:mrow>
+        </m:math>
+    </informalequation>
+</article>
+^D
+Word
+
+\[1 + 2\]
+```
+
+```
+% pandoc -f docbook -t latex
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE article PUBLIC "-//W3C//DTD MathML 2.0//EN" "http://www.w3.org/Math/DTD/mathml2/mathml2.dtd">
+<?xml-model href="http://www.oxygenxml.com/docbook/xml/5.0/rng/dbmathml.rng" schematypens="http://relaxng.org/ns/structure/1.0"?>
+<?xml-model href="http://docbook.org/xml/5.0/rng/docbook.rng" type="application/xml" schematypens="http://purl.oclc.org/dsdl/schematron"?>
+<article xmlns="http://docbook.org/ns/docbook"
+    xmlns:xlink="http://www.w3.org/1999/xlink"
+    xmlns:mml="http://www.w3.org/1998/Math/MathML"
+    version="5.1">
+    <title>Untitled Document</title>
+    <para>Word</para>
+    <informalequation>
+        <alt role='tex'>1+2</alt>
+        <mml:math>
+            <mml:mrow>
+                <mml:mrow><mml:mn>1</mml:mn><mml:mo>+</mml:mo><mml:mn>2</mml:mn>
+                </mml:mrow>
+            </mml:mrow>
+        </mml:math>
+    </informalequation>
+</article>
+^D
+Word
+
+\[1 + 2\]
+```
+
diff --git a/test/command/7181.md b/test/command/7181.md
new file mode 100644
--- /dev/null
+++ b/test/command/7181.md
@@ -0,0 +1,11 @@
+```
+% pandoc -t latex
+![Global frog population.](slides.pdf){page=13,trim=1cm,clip,width=4cm}
+^D
+\begin{figure}
+\centering
+\pandocbounded{\includegraphics[keepaspectratio,page=13,trim=1cm,clip,width=4cm,alt={Global frog population.}]{slides.pdf}}
+\caption{Global frog population.}
+\end{figure}
+
+```
diff --git a/test/command/7201.md b/test/command/7201.md
new file mode 100644
--- /dev/null
+++ b/test/command/7201.md
@@ -0,0 +1,47 @@
+```
+% pandoc -t revealjs --slide-level=1
+# Overview
+
+:::::::::::::: {.columns}
+::: {.column width="40%"}
+
+Left column
+
+:::
+::: {.column width="60%"}
+
+* First list
+    * subitem
+
+. . .
+
+* Second list
+    * subitem
+:::
+::::::::::::::
+^D
+<section id="overview" class="slide level1">
+<h1>Overview</h1>
+<div class="columns">
+<div class="column" style="width:40%;">
+<p>Left column</p>
+</div><div class="column" style="width:60%;">
+<ul>
+<li>First list
+<ul>
+<li>subitem</li>
+</ul></li>
+</ul>
+<div class="fragment">
+<ul>
+<li>Second list
+<ul>
+<li>subitem</li>
+</ul></li>
+</ul>
+</div>
+</div>
+</div>
+</section>
+
+```
diff --git a/test/command/7208.md b/test/command/7208.md
new file mode 100644
--- /dev/null
+++ b/test/command/7208.md
@@ -0,0 +1,6 @@
+```
+% pandoc -t gfm
+\<hi\>
+^D
+\<hi\>
+```
diff --git a/test/command/7214.md b/test/command/7214.md
new file mode 100644
--- /dev/null
+++ b/test/command/7214.md
@@ -0,0 +1,28 @@
+```
+% pandoc
++------------+----------+------------------+
+|日本語      | の文字列 | words in english |
++------------+----------+------------------+
+|abc defghij | def      | xyz              |
++------------+----------+------------------+
+^D
+<table style="width:60%;">
+<colgroup>
+<col style="width: 18%" />
+<col style="width: 15%" />
+<col style="width: 26%" />
+</colgroup>
+<tbody>
+<tr>
+<td>日本語</td>
+<td>の文字列</td>
+<td>words in english</td>
+</tr>
+<tr>
+<td>abc defghij</td>
+<td>def</td>
+<td>xyz</td>
+</tr>
+</tbody>
+</table>
+```
diff --git a/test/command/7216.md b/test/command/7216.md
new file mode 100644
--- /dev/null
+++ b/test/command/7216.md
@@ -0,0 +1,19 @@
+```
+% pandoc -t latex
+"This is some text in quotes. Another paragraph by the same speaker follows. The first paragraph should have no close quote.
+
+"The second paragraph should have open and close quotes."
+
+| "Open quote on this line,
+| Close quote on the next line."
+| "Quotes on the same line."
+^D
+``This is some text in quotes. Another paragraph by the same speaker
+follows. The first paragraph should have no close quote.
+
+``The second paragraph should have open and close quotes.''
+
+``Open quote on this line,\\
+Close quote on the next line.''\\
+``Quotes on the same line.''
+```
diff --git a/test/command/7219.md b/test/command/7219.md
new file mode 100644
--- /dev/null
+++ b/test/command/7219.md
@@ -0,0 +1,25 @@
+```
+% pandoc --citeproc -t plain
+---
+references:
+- author:
+  - family: Reese
+    given: Trevor R.
+  collection-title: 3rd series
+  container-title: William and Mary Quarterly
+  id: reese
+  issued: 1958
+  language: en-US
+  page: 168-190
+  title: Georgia in Anglo-Spanish diplomacy, 1736-1739
+  type: article-journal
+  volume: 15
+...
+and also in -@reese
+^D
+and also in (1958)
+
+Reese, Trevor R. 1958. “Georgia in Anglo-Spanish Diplomacy, 1736-1739.”
+William and Mary Quarterly, 3rd series, vol. 15: 168–90.
+
+```
diff --git a/test/command/7266.md b/test/command/7266.md
new file mode 100644
--- /dev/null
+++ b/test/command/7266.md
@@ -0,0 +1,10 @@
+```
+% pandoc -f biblatex -t biblatex -s
+@article{id,
+  annote = "annotation"
+}
+^D
+@article{id,
+  annote = {annotation}
+}
+```
diff --git a/test/command/7272.md b/test/command/7272.md
new file mode 100644
--- /dev/null
+++ b/test/command/7272.md
@@ -0,0 +1,30 @@
+```
+% pandoc -t latex -f html
+<table>
+  <tbody>
+    <tr>
+      <td>
+        <span>
+          text
+          <br />
+          text2
+        </span>
+      </td>
+    </tr>
+  </tbody>
+</table>
+^D
+{\def\LTcaptype{none} % do not increment counter
+\begin{longtable}[]{@{}
+  >{\raggedright\arraybackslash}p{(\linewidth - 0\tabcolsep) * \real{1.0000}}@{}}
+\toprule\noalign{}
+\endhead
+\bottomrule\noalign{}
+\endlastfoot
+\begin{minipage}[t]{\linewidth}\raggedright
+{ text\\
+text2 }\strut
+\end{minipage} \\
+\end{longtable}
+}
+```
diff --git a/test/command/7278.md b/test/command/7278.md
new file mode 100644
--- /dev/null
+++ b/test/command/7278.md
@@ -0,0 +1,38 @@
+```
+% pandoc -t beamer
+# Slide
+
+Some blocks:
+
+## example block title {.example}
+
+text in block
+
+## alert block title {.alert}
+
+text in block
+
+## block title
+
+text in block
+^D
+\begin{frame}{Slide}
+\protect\phantomsection\label{slide}
+Some blocks:
+
+\begin{exampleblock}{example block title}
+\protect\phantomsection\label{example-block-title}
+text in block
+\end{exampleblock}
+
+\begin{alertblock}{alert block title}
+\protect\phantomsection\label{alert-block-title}
+text in block
+\end{alertblock}
+
+\begin{block}{block title}
+\protect\phantomsection\label{block-title}
+text in block
+\end{block}
+\end{frame}
+```
diff --git a/test/command/7282.md b/test/command/7282.md
new file mode 100644
--- /dev/null
+++ b/test/command/7282.md
@@ -0,0 +1,7 @@
+Don't crash on unmatched closing tag.
+```
+% pandoc -f html -t native
+</script>
+^D
+[]
+```
diff --git a/test/command/7288.md b/test/command/7288.md
new file mode 100644
--- /dev/null
+++ b/test/command/7288.md
@@ -0,0 +1,40 @@
+```
+% pandoc -f rst -t ms
+.. list-table::
+   :widths: 50 50
+   :header-rows: 1
+
+   * - Left
+     - Right
+   * - Long text that should be easy to break up into multiple lines
+     - Another long text that should be easy to break up into multiple lines
+
+       Bar
+^D
+.PP
+.na
+.nr LLold \n[LL]
+.TS
+delim(@@) tab(	);
+lw(35.0n) lw(35.0n).
+T{
+Left
+T}	T{
+Right
+T}
+_
+T{
+.nr LL 35.0n
+.LP
+Long text that should be easy to break up into multiple lines
+T}	T{
+.nr LL 35.0n
+.PP
+Another long text that should be easy to break up into multiple lines
+.PP
+Bar
+T}
+.TE
+.nr LL \n[LLold]
+.ad
+```
diff --git a/test/command/7299.md b/test/command/7299.md
new file mode 100644
--- /dev/null
+++ b/test/command/7299.md
@@ -0,0 +1,23 @@
+```
+% pandoc -f latex -t plain
+$1-{\ensuremath{r}\xspace}$
+^D
+1 − r
+```
+
+```
+% pandoc -f latex -t plain
+\newcommand{\foo}{Foo\xspace}
+
+$\text{\foo bar}$
+^D
+Foo bar
+```
+
+```
+% pandoc -f latex -t plain
+a\xspace b
+^D
+a b
+```
+
diff --git a/test/command/7321.md b/test/command/7321.md
new file mode 100644
--- /dev/null
+++ b/test/command/7321.md
@@ -0,0 +1,24 @@
+```
+% pandoc -t plain --citeproc --wrap=none
+---
+references:
+- id: fenner2012a
+  title: One-click science marketing
+  author:
+  - family: Fenner
+    given: Martin
+  container-title: Nature Materials
+  volume: 11
+  issue: 4
+  publisher: Nature Publishing Group
+  type: article-journal
+  issued:
+    year: 2012
+---
+
+[@fenner2012a, $a^2+b^2=c^2$]
+^D
+(Fenner 2012, a² + b² = c²)
+
+Fenner, Martin. 2012. “One-Click Science Marketing.” Nature Materials 11 (4).
+```
diff --git a/test/command/7323.md b/test/command/7323.md
new file mode 100644
--- /dev/null
+++ b/test/command/7323.md
@@ -0,0 +1,29 @@
+```
+% pandoc --citeproc -t plain
+---
+references:
+- id: smith
+  author: John Smith
+  issued: 2019
+  title: Insects
+  type: book
+...
+
+@smith [chap. 6]
+
+@smith [chapter 6]
+
+@smith [Chap. 6]
+
+@smith [Chapter 6]
+^D
+John Smith (2019, chap. 6)
+
+John Smith (2019, chap. 6)
+
+John Smith (2019, chap. 6)
+
+John Smith (2019, chap. 6)
+
+John Smith. 2019. Insects.
+```
diff --git a/test/command/7324.md b/test/command/7324.md
new file mode 100644
--- /dev/null
+++ b/test/command/7324.md
@@ -0,0 +1,25 @@
+```
+% pandoc --citeproc -t plain
+---
+references:
+- id: smith
+  author: John Smith
+  issued: 2019
+  title: Insects
+  type: book
+...
+
+@smith [, among others]
+
+@smith [ among others]
+
+@smith [among others]
+^D
+John Smith (2019, among others)
+
+John Smith (2019 among others)
+
+John Smith (2019, among others)
+
+John Smith. 2019. Insects.
+```
diff --git a/test/command/7326.md b/test/command/7326.md
new file mode 100644
--- /dev/null
+++ b/test/command/7326.md
@@ -0,0 +1,1227 @@
+Table with row and column spans
+```
+% pandoc -f html -t asciidoc
+<table>
+  <colgroup>
+    <col style="width: 17%" />
+    <col style="width: 16%" />
+    <col style="width: 15%" />
+    <col style="width: 52%" />
+  </colgroup>
+  <thead>
+    <tr>
+      <th>Header 1</th>
+      <th>Header 2</th>
+      <th>Header 3</th>
+      <th>Header 4</th>
+    </tr>
+  </thead>
+  <tbody>
+    <tr>
+      <td>body row 1</td>
+      <td>column 2</td>
+      <td>column 3</td>
+      <td>column 4</td>
+    </tr>
+    <tr>
+      <td>body row 2</td>
+      <td colspan="2">Cells may span columns.</td>
+      <td>fff</td>
+    </tr>
+    <tr>
+      <td>body row 3</td>
+      <td rowspan="2">Cells may span rows.</td>
+      <td rowspan="2">
+        <ul>
+          <li>Cells</li>
+          <li>can</li>
+          <li>contain</li>
+          <li>blocks.</li>
+        </ul>
+      </td>
+      <td rowspan="2">
+        <ul>
+          <li>This is a very long line of text</li>
+          <li><a href="http://www.python.org/">Python</a></li>
+          <li>b</li>
+          <li>c</li>
+        </ul>
+      </td>
+    </tr>
+    <tr>
+      <td>body row 4</td>
+    </tr>
+  </tbody>
+</table>
+^D
+[width="100%",cols="17%,16%,15%,52%",options="header",]
+|===
+|Header 1 |Header 2 |Header 3 |Header 4
+|body row 1 |column 2 |column 3 |column 4
+|body row 2 2+|Cells may span columns. |fff
+|body row 3 .2+|Cells may span rows. .2+a|
+* Cells
+* can
+* contain
+* blocks.
+
+.2+a|
+* This is a very long line of text
+* http://www.python.org/[Python]
+* b
+* c
+
+|body row 4
+|===
+```
+
+Header and footer.
+AsciiDoc only supports 1 header and 1 footer row.
+So for multiple header and/or footer rows all the extra rows become part of the table body.
+```
+% pandoc -f html -t asciidoc
+<table>
+  <thead>
+    <tr>
+      <th colspan="2">Inputs</th>
+      <th>Output</th>
+    </tr>
+    <tr>
+      <th>A</th>
+      <th>B</th>
+      <th>A or B</th>
+    </tr>
+  </thead>
+  <tbody>
+    <tr>
+      <td>False</td>
+      <td>False</td>
+      <td>False</td>
+    </tr>
+    <tr>
+      <td>True</td>
+      <td>False</td>
+      <td>True</td>
+    </tr>
+    <tr>
+      <td>False</td>
+      <td>True</td>
+      <td>True</td>
+    </tr>
+    <tr>
+      <td>True</td>
+      <td>True</td>
+      <td>True</td>
+    </tr>
+  </tbody>
+  <tfoot>
+    <tr>
+      <td>A</td>
+      <td>B</td>
+      <td>A or B</td>
+    </tr>
+    <tr>
+      <td colspan="2">Inputs</td>
+      <td>Output</td>
+    </tr>
+  </tfoot>
+</table>
+<table>
+  <thead>
+    <tr>
+      <th colspan="2">Header</th>
+    </tr>
+  </thead>
+  <tbody>
+    <tr>
+      <td>Body 1-1</td>
+      <td>Body 2-1</td>
+    </tr>
+  </tbody>
+  <tfoot>
+    <tr>
+      <td colspan="2">Footer</td>
+    </tr>
+  </tfoot>
+</table>
+^D
+[cols=",,",options="header,footer",]
+|===
+2+|Inputs |Output
+|A |B |A or B
+|False |False |False
+|True |False |True
+|False |True |True
+|True |True |True
+|A |B |A or B
+2+|Inputs |Output
+|===
+
+[cols=",",options="header,footer",]
+|===
+2+|Header
+|Body 1-1 |Body 2-1
+2+|Footer
+|===
+```
+
+Table without header but with footer rows
+```
+% pandoc -f html -t asciidoc
+<table>
+  <colgroup>
+    <col style="width: 37%" />
+    <col style="width: 37%" />
+    <col style="width: 26%" />
+  </colgroup>
+  <tbody>
+    <tr>
+      <td>False</td>
+      <td>False</td>
+      <td>False</td>
+    </tr>
+    <tr>
+      <td>True</td>
+      <td>False</td>
+      <td>True</td>
+    </tr>
+    <tr>
+      <td>False</td>
+      <td>True</td>
+      <td>True</td>
+    </tr>
+    <tr>
+      <td>True</td>
+      <td>True</td>
+      <td>True</td>
+    </tr>
+  </tbody>
+  <tfoot>
+    <tr>
+      <td>A</td>
+      <td>B</td>
+      <td>A or B</td>
+    </tr>
+    <tr>
+      <td colspan="2">Inputs</td>
+      <td>Output</td>
+    </tr>
+  </tfoot>
+</table>
+^D
+[width="100%",cols="37%,37%,26%",options="footer",]
+|===
+|False |False |False
+|True |False |True
+|False |True |True
+|True |True |True
+|A |B |A or B
+2+|Inputs |Output
+|===
+```
+
+Adjust row span for multiple header rows
+```
+% pandoc -f html -t asciidoc
+<table style="width: 63%">
+  <colgroup>
+    <col style="width: 30%" />
+    <col style="width: 11%" />
+    <col style="width: 11%" />
+    <col style="width: 11%" />
+  </colgroup>
+  <thead>
+    <tr>
+      <th rowspan="2">Location</th>
+      <th colspan="3">Temperature 1961-1990 in degree Celsius</th>
+    </tr>
+    <tr>
+      <th>min</th>
+      <th>mean</th>
+      <th>max</th>
+    </tr>
+  </thead>
+  <tbody>
+    <tr>
+      <td>Antarctica</td>
+      <td>-89.2</td>
+      <td>N/A</td>
+      <td>19.8</td>
+    </tr>
+    <tr>
+      <td>Earth</td>
+      <td>-89.2</td>
+      <td>14</td>
+      <td>56.7</td>
+    </tr>
+  </tbody>
+</table>
+<table style="width: 63%">
+  <colgroup>
+    <col style="width: 11%" />
+    <col style="width: 11%" />
+    <col style="width: 11%" />
+    <col style="width: 30%" />
+  </colgroup>
+  <thead>
+    <tr>
+      <th colspan="3">Temperature 1961-1990 in degree Celsius</th>
+      <th rowspan="2">Location</th>
+    </tr>
+    <tr>
+      <th>min</th>
+      <th>mean</th>
+      <th>max</th>
+    </tr>
+  </thead>
+  <tbody>
+    <tr>
+      <td>-89.2</td>
+      <td>N/A</td>
+      <td>19.8</td>
+      <td>Antarctica</td>
+    </tr>
+    <tr>
+      <td>-89.2</td>
+      <td>14</td>
+      <td>56.7</td>
+      <td>Earth</td>
+    </tr>
+  </tbody>
+</table>
+<table style="width: 65%">
+  <colgroup>
+    <col style="width: 11%" />
+    <col style="width: 11%" />
+    <col style="width: 11%" />
+    <col style="width: 18%" />
+    <col style="width: 14%" />
+  </colgroup>
+  <thead>
+    <tr>
+      <th colspan="3">Temperature 1961-1990 in degree Celsius</th>
+      <th rowspan="2">Location</th>
+      <th>Extra</th>
+    </tr>
+    <tr>
+      <th>min</th>
+      <th>mean</th>
+      <th>max</th>
+      <th>Extra 2</th>
+    </tr>
+  </thead>
+  <tbody>
+    <tr>
+      <td>-89.2</td>
+      <td>N/A</td>
+      <td>19.8</td>
+      <td>Antarctica</td>
+      <td>Extra 3</td>
+    </tr>
+    <tr>
+      <td>-89.2</td>
+      <td>14</td>
+      <td>56.7</td>
+      <td>Earth</td>
+      <td>Extra 4</td>
+    </tr>
+  </tbody>
+</table>
+<table>
+  <thead>
+    <tr>
+      <th>Header 1-1</th>
+      <th colspan="2" rowspan="2">Header 1-2</th>
+    </tr>
+    <tr>
+      <th>Header 2-1</th>
+    </tr>
+    <tr>
+      <th>Header 3-1</th>
+      <th>Header 3-2</th>
+      <th>Header 3-3</th>
+    </tr>
+  </thead>
+  <tbody>
+    <tr>
+      <td rowspan="2">Body 1-1</td>
+      <td colspan="2">Body 1-2</td>
+    </tr>
+    <tr>
+      <td>Body 2-1</td>
+      <td>Body 2-2</td>
+    </tr>
+  </tbody>
+</table>
+<table>
+  <thead>
+    <tr>
+      <th rowspan="2">Header 1-1</th>
+      <th>Header 1-2</th>
+      <th rowspan="2">Header 1-3</th>
+    </tr>
+    <tr>
+      <th>Header 2-1</th>
+    </tr>
+    <tr>
+      <th>Header 3-1</th>
+      <th>Header 3-2</th>
+      <th>Header 3-3</th>
+    </tr>
+  </thead>
+  <tbody></tbody>
+</table>
+^D
+[width="63%",cols="49%,17%,17%,17%",options="header",]
+|===
+|Location 3+|Temperature 1961-1990 in degree Celsius
+| |min |mean |max
+|Antarctica |-89.2 |N/A |19.8
+|Earth |-89.2 |14 |56.7
+|===
+
+[width="63%",cols="19%,17%,17%,47%",options="header",]
+|===
+3+|Temperature 1961-1990 in degree Celsius |Location
+|min |mean |max |
+|-89.2 |N/A |19.8 |Antarctica
+|-89.2 |14 |56.7 |Earth
+|===
+
+[width="65%",cols="20%,16%,16%,27%,21%",options="header",]
+|===
+3+|Temperature 1961-1990 in degree Celsius |Location |Extra
+|min |mean |max | |Extra 2
+|-89.2 |N/A |19.8 |Antarctica |Extra 3
+|-89.2 |14 |56.7 |Earth |Extra 4
+|===
+
+[cols=",,",options="header",]
+|===
+|Header 1-1 2+|Header 1-2
+|Header 2-1 2+|
+|Header 3-1 |Header 3-2 |Header 3-3
+.2+|Body 1-1 2+|Body 1-2
+|Body 2-1 |Body 2-2
+|===
+
+[cols=",,",options="header",]
+|===
+|Header 1-1 |Header 1-2 |Header 1-3
+| |Header 2-1 |
+|Header 3-1 |Header 3-2 |Header 3-3
+|===
+```
+
+Adjust row span in multiple footer rows.
+```
+% pandoc -f html -t asciidoc
+<table>
+  <colgroup>
+    <col style="width: 40%" />
+    <col style="width: 40%" />
+    <col style="width: 20%" />
+  </colgroup>
+  <tbody>
+    <tr>
+      <td>Body 1-1</td>
+      <td>Body 1-2</td>
+      <td>Body 1-3</td>
+    </tr>
+  </tbody>
+  <tfoot>
+    <tr>
+      <td colspan="2">Footer 1-1/2</td>
+      <td>Footer 1-3</td>
+    </tr>
+    <tr>
+      <td>Footer 2-1</td>
+      <td rowspan="3">Span 3</td>
+      <td>Footer 2-3</td>
+    </tr>
+    <tr>
+      <td rowspan="2">Span 2</td>
+      <td>Footer 3-3</td>
+    </tr>
+    <tr>
+      <td>Footer 4-3</td>
+    </tr>
+  </tfoot>
+</table>
+<table>
+  <tbody>
+    <tr>
+      <td>Body 1-1</td>
+      <td>Body 1-2</td>
+      <td>Body 1-3</td>
+      <td>Body 1-4</td>
+      <td>Body 1-5</td>
+    </tr>
+    <tr>
+      <td>Body 2-1</td>
+      <td>Body 2-2</td>
+      <td>Body 2-3</td>
+      <td>Body 2-4</td>
+      <td>Body 2-5</td>
+    </tr>
+  </tbody>
+  <tfoot>
+    <tr>
+      <td colspan="3">Footer 1-1/2/3</td>
+      <td>Footer 1-4</td>
+      <td>Footer 1-5</td>
+    </tr>
+    <tr>
+      <td>Footer 2-1</td>
+      <td rowspan="3">Span 3</td>
+      <td>Footer 2-3</td>
+      <td colspan="2">Footer 2-4/5</td>
+    </tr>
+    <tr>
+      <td rowspan="2">Span 2</td>
+      <td colspan="2">Footer 3-3/4</td>
+      <td rowspan="2">Span 2</td>
+    </tr>
+    <tr>
+      <td rowspan="3">Span 3</td>
+      <td>Footer 4-4</td>
+    </tr>
+    <tr>
+      <td>Footer 5-1</td>
+      <td>Footer 5-2</td>
+      <td>Footer 5-4</td>
+      <td rowspan="2">Span 2</td>
+    </tr>
+    <tr>
+      <td colspan="2">Footer 6-1/2</td>
+      <td>Footer 6-4</td>
+    </tr>
+  </tfoot>
+</table>
+<table>
+  <tbody>
+    <tr>
+      <td>Body 1</td>
+      <td>Body 2</td>
+      <td>Body 3</td>
+      <td>Body 4</td>
+    </tr>
+  </tbody>
+  <tfoot>
+    <tr>
+      <td>Footer 1-1</td>
+      <td colspan="2" rowspan="3">Span 3</td>
+      <td rowspan="2">Span 2</td>
+    </tr>
+    <tr>
+      <td>Footer 2-1</td>
+    </tr>
+    <tr>
+      <td>Footer 3-1</td>
+      <td>Footer 3-4</td>
+    </tr>
+  </tfoot>
+</table>
+<table>
+  <tbody>
+    <tr>
+      <td>Body 1-1</td>
+      <td>Body 1-2</td>
+      <td>Body 1-3</td>
+      <td>Body 1-4</td>
+    </tr>
+  </tbody>
+  <tfoot>
+    <tr>
+      <td colspan="2">Footer 1-1/2</td>
+      <td rowspan="6">Span 6</td>
+      <td>Footer 1-4</td>
+    </tr>
+    <tr>
+      <td rowspan="3">Span 3</td>
+      <td>Footer 2-2</td>
+      <td>Footer 2-4</td>
+    </tr>
+    <tr>
+      <td>Footer 3-2</td>
+      <td>Footer 3-4</td>
+    </tr>
+    <tr>
+      <td>Footer 4-2</td>
+      <td>Footer 4-4</td>
+    </tr>
+    <tr>
+      <td>Footer 5-1</td>
+      <td>Footer 5-2</td>
+      <td rowspan="2">Span 2</td>
+    </tr>
+    <tr>
+      <td colspan="2">Footer 6-1/2</td>
+    </tr>
+  </tfoot>
+</table>
+^D
+[width="100%",cols="40%,40%,20%",options="footer",]
+|===
+|Body 1-1 |Body 1-2 |Body 1-3
+2+|Footer 1-1/2 |Footer 1-3
+|Footer 2-1 .2+|Span 3 |Footer 2-3
+|Span 2 |Footer 3-3
+| | |Footer 4-3
+|===
+
+[cols=",,,,",options="footer",]
+|===
+|Body 1-1 |Body 1-2 |Body 1-3 |Body 1-4 |Body 1-5
+|Body 2-1 |Body 2-2 |Body 2-3 |Body 2-4 |Body 2-5
+3+|Footer 1-1/2/3 |Footer 1-4 |Footer 1-5
+|Footer 2-1 .3+|Span 3 |Footer 2-3 2+|Footer 2-4/5
+.2+|Span 2 2+|Footer 3-3/4 .2+|Span 2
+.2+|Span 3 |Footer 4-4
+|Footer 5-1 |Footer 5-2 |Footer 5-4 |Span 2
+2+|Footer 6-1/2 | |Footer 6-4 |
+|===
+
+[cols=",,,",options="footer",]
+|===
+|Body 1 |Body 2 |Body 3 |Body 4
+|Footer 1-1 2.2+|Span 3 .2+|Span 2
+|Footer 2-1
+|Footer 3-1 2+| |Footer 3-4
+|===
+
+[cols=",,,",options="footer",]
+|===
+|Body 1-1 |Body 1-2 |Body 1-3 |Body 1-4
+2+|Footer 1-1/2 .5+|Span 6 |Footer 1-4
+.3+|Span 3 |Footer 2-2 |Footer 2-4
+|Footer 3-2 |Footer 3-4
+|Footer 4-2 |Footer 4-4
+|Footer 5-1 |Footer 5-2 |Span 2
+2+|Footer 6-1/2 | |
+|===
+```
+
+Individual cell alignments
+```
+% pandoc -f native -t asciidoc
+[ Table
+    ( "" , [] , [] )
+    (Caption Nothing [])
+    [ ( AlignDefault , ColWidthDefault )
+    , ( AlignDefault , ColWidthDefault )
+    , ( AlignDefault , ColWidthDefault )
+    ]
+    (TableHead
+       ( "" , [] , [] )
+       [ Row
+           ( "" , [] , [] )
+           [ Cell
+               ( "" , [] , [] )
+               AlignLeft
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "Left" , Space , Str "Header" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignCenter
+               (RowSpan 2)
+               (ColSpan 2)
+               [ Plain [ Str "Center" , Space , Str "Headers" ] ]
+           ]
+       , Row
+           ( "" , [] , [] )
+           [ Cell
+               ( "" , [] , [] )
+               AlignRight
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "Right" , Space , Str "Header" ] ]
+           ]
+       , Row
+           ( "" , [] , [] )
+           [ Cell
+               ( "" , [] , [] )
+               AlignCenter
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "Center" , Space , Str "Header" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignRight
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "Right" , Space , Str "Header" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignLeft
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "Left" , Space , Str "Header" ] ]
+           ]
+       ])
+    [ TableBody
+        ( "" , [] , [] )
+        (RowHeadColumns 0)
+        []
+        [ Row
+           ( "" , [] , [] )
+           [ Cell
+               ( "" , [] , [] )
+               AlignRight
+               (RowSpan 2)
+               (ColSpan 1)
+               [ Plain [ Str "Right" , Space , Str "Body" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignLeft
+               (RowSpan 1)
+               (ColSpan 2)
+               [ Plain [ Str "Left" , Space , Str "Body" ] ]
+           ]
+        , Row
+           ( "" , [] , [] )
+           [ Cell
+               ( "" , [] , [] )
+               AlignCenter
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "Center" , Space , Str "Body" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignRight
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "Right" , Space , Str "Body" ] ]
+           ]
+        ]
+    ]
+    (TableFoot
+        ( "" , [] , [] )
+        [ Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignCenter
+                (RowSpan 1)
+                (ColSpan 3)
+                [ Plain [ Str "Center" , Space , Str "Footer" ] ]
+            ]
+        , Row
+             ( "" , [] , [] )
+             [ Cell
+                 ( "" , [] , [] )
+                 AlignLeft
+                 (RowSpan 1)
+                 (ColSpan 2)
+                 [ Plain [ Str "Left" , Space , Str "Footer" ] ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignCenter
+                 (RowSpan 3)
+                 (ColSpan 1)
+                 [ Plain [ Str "Center" , Space , Str "Footer" ] ]
+             ]
+         , Row
+             ( "" , [] , [] )
+             [ Cell
+                 ( "" , [] , [] )
+                 AlignRight
+                 (RowSpan 1)
+                 (ColSpan 2)
+                 [ Plain [ Str "Right" , Space , Str "Footer" ] ]
+             ]
+         , Row
+             ( "" , [] , [] )
+             [ Cell
+                 ( "" , [] , [] )
+                 AlignCenter
+                 (RowSpan 1)
+                 (ColSpan 2)
+                 [ Plain [ Str "Center" , Space , Str "Footer" ] ]
+             ]
+        ])
+]
+^D
+[cols=",,",options="header,footer",]
+|===
+<|Left Header 2+^|Center Headers
+>|Right Header 2+|
+^|Center Header >|Right Header <|Left Header
+.2+>|Right Body 2+<|Left Body
+^|Center Body >|Right Body
+3+^|Center Footer
+2+<|Left Footer .2+^|Center Footer
+2+>|Right Footer
+2+^|Center Footer |
+|===
+```
+
+Adjust row span for empty rows and handle empty rows in general
+```
+% pandoc -f native -t asciidoc
+[ Table
+    ( "" , [] , [] )
+    (Caption Nothing [])
+    [ ( AlignDefault , ColWidthDefault )
+    , ( AlignDefault , ColWidthDefault )
+    , ( AlignDefault , ColWidthDefault )
+    ]
+    (TableHead
+       ( "" , [] , [] )
+       [ Row
+           ( "" , [] , [] )
+           [ Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 2)
+               (ColSpan 1)
+               [ Plain [ Str "Header" , Space , Str "1-1" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 3)
+               (ColSpan 1)
+               [ Plain [ Str "Span" , Space , Str "3" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 2)
+               (ColSpan 1)
+               [ Plain [ Str "Header" , Space , Str "1-3" ] ]
+           ]
+       , Row ( "" , [] , [] ) []
+       , Row
+           ( "" , [] , [] )
+           [ Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "Header" , Space , Str "2-1" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "Header" , Space , Str "2-3" ] ]
+           ]
+       ])
+    [ TableBody
+        ( "" , [] , [] )
+        (RowHeadColumns 0)
+        []
+        [ Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 3)
+                (ColSpan 2)
+                [ Plain [ Str "Body" , Space , Str "1-1/2" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 5)
+                (ColSpan 1)
+                [ Plain [ Str "Span" , Space , Str "5" ] ]
+            ]
+        , Row ( "" , [] , [] ) []
+        , Row ( "" , [] , [] ) []
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "Body" , Space , Str "2-1" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "Body" , Space , Str "2-2" ] ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "Body" , Space , Str "3-1" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "Body" , Space , Str "3-2" ] ]
+            ]
+        , Row ( "" , [] , [] ) []
+        ]
+    ]
+    (TableFoot
+       ( "" , [] , [] )
+       [ Row
+           ( "" , [] , [] )
+           [ Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 5)
+               (ColSpan 1)
+               [ Plain
+                   [ Str "Span" , Space , Str "5" ]
+               ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 2)
+               [ Plain [ Str "Footer" , Space , Str "1-2" ] ]
+           ]
+       , Row
+           ( "" , [] , [] )
+           [ Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 2)
+               (ColSpan 2)
+               [ Plain
+                   [ Str "Span" , Space , Str "2" ]
+               ]
+           ]
+       , Row ( "" , [] , [] ) []
+       , Row
+           ( "" , [] , [] )
+           [ Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 2)
+               [ Plain [ Str "Footer" , Space , Str "3-2/3" ] ]
+           ]
+       , Row
+           ( "" , [] , [] )
+           [ Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 2)
+               [ Plain [ Str "Footer" , Space , Str "4-2/3" ] ]
+           ]
+       ])
+, Table
+    ( "" , [] , [] )
+    (Caption Nothing [])
+    [ ( AlignDefault , ColWidthDefault )
+    , ( AlignDefault , ColWidthDefault )
+    , ( AlignDefault , ColWidthDefault )
+    ]
+    (TableHead ( "" , [] , [] ) [])
+    [ TableBody
+        ( "" , [] , [] )
+        (RowHeadColumns 0)
+        []
+        [ Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "Body" , Space , Str "1-1" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "Body" , Space , Str "1-2" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 3)
+                (ColSpan 1)
+                [ Plain [ Str "Span" , Space , Str "4" ] ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 5)
+                (ColSpan 1)
+                [ Plain [ Str "Span" , Space , Str "5" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "Body" , Space , Str "2-2" ] ]
+            ]
+        , Row
+            ( "" , [] , [] ) []
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "Body" , Space , Str "3-2" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "Body" , Space , Str "3-3" ] ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "Body" , Space , Str "4-2" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "Body" , Space , Str "4-3" ] ]
+            ]
+        , Row
+            ( "" , [] , [] ) []
+        , Row
+            ( "" , [] , [] ) []
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "Body" , Space , Str "6-1" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "Body" , Space , Str "6-2" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "Span" , Space , Str "6-3" ] ]
+            ]
+        ]
+    ]
+    (TableFoot
+       ( "" , [] , [] )
+       [ Row
+           ( "" , [] , [] )
+           [ Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "Footer" , Space , Str "1-1" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 8)
+               (ColSpan 1)
+               [ Plain [ Str "Span" , Space , Str "8" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "Footer" , Space , Str "1-3" ] ]
+           ]
+       , Row
+           ( "" , [] , [] )
+           [ Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 3)
+               (ColSpan 1)
+               [ Plain [ Str "Span" , Space , Str "3" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "Footer" , Space , Str "2-3" ] ]
+           ]
+       , Row
+           ( "" , [] , [] )
+           [ Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 2)
+               (ColSpan 1)
+               [ Plain [ Str "Span" , Space , Str "2" ] ]
+           ]
+       , Row ( "" , [] , [] ) []
+       , Row
+           ( "" , [] , [] )
+           [ Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "Footer" , Space , Str "4-1" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "Footer" , Space , Str "4-3" ] ]
+           ]
+       , Row
+           ( "" , [] , [] )
+           [ Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "Footer" , Space , Str "5-1" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 3)
+               (ColSpan 1)
+               [ Plain [ Str "Span" , Space , Str "3" ] ]
+           ]
+       , Row
+           ( "" , [] , [] )
+           [ Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 2)
+               (ColSpan 1)
+               [ Plain [ Str "Span" , Space , Str "2" ] ]
+           ]
+       , Row ( "" , [] , [] ) []
+       ])
+, Table
+    ( "" , [] , [] )
+    (Caption Nothing [])
+    [ ( AlignDefault , ColWidthDefault )
+    , ( AlignDefault , ColWidthDefault )
+    , ( AlignDefault , ColWidthDefault )
+    ]
+    (TableHead ( "" , [] , [] ) [])
+    [ TableBody
+        ( "" , [] , [] )
+        (RowHeadColumns 0)
+        []
+        [ Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [ "rowspan-cell" ] , [] )
+                AlignDefault
+                (RowSpan 6)
+                (ColSpan 1)
+                [ Plain [ Str "Span" , Space , Str "6" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "Body" , Space , Str "1-2" ] ]
+            , Cell
+                ( "" , [ "rowspan-cell" ] , [] )
+                AlignDefault
+                (RowSpan 2)
+                (ColSpan 1)
+                [ Plain [ Str "Span" , Space , Str "2" ] ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [ "rowspan-cell" ] , [] )
+                AlignDefault
+                (RowSpan 3)
+                (ColSpan 1)
+                [ Plain [ Str "Span" , Space , Str "3" ] ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [ "rowspan-cell" ] , [] )
+                AlignDefault
+                (RowSpan 4)
+                (ColSpan 1)
+                [ Plain [ Str "Span" , Space , Str "4" ] ]
+            ]
+        , Row ( "" , [] , [] ) []
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "Body" , Space , Str "3-2" ] ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "Body" , Space , Str "4-2" ] ]
+            ]
+        , Row ( "" , [] , [] ) []
+        , Row ( "" , [] , [] ) []
+        ]
+    ]
+    (TableFoot ( "" , [] , [] ) [])
+]
+^D
+[cols=",,",options="header,footer",]
+|===
+|Header 1-1 |Span 3 |Header 1-3
+|Header 2-1 | |Header 2-3
+2+|Body 1-1/2 .3+|Span 5
+|Body 2-1 |Body 2-2
+|Body 3-1 |Body 3-2
+| | |
+.3+|Span 5 2+|Footer 1-2
+2+|Span 2
+2+|Footer 3-2/3
+| 2+|Footer 4-2/3
+|===
+
+[cols=",,",options="footer",]
+|===
+|Body 1-1 |Body 1-2 .2+|Span 4
+.3+|Span 5 |Body 2-2
+|Body 3-2 |Body 3-3
+|Body 4-2 |Body 4-3
+| | |
+|Body 6-1 |Body 6-2 |Span 6-3
+|Footer 1-1 .5+|Span 8 |Footer 1-3
+.2+|Span 3 |Footer 2-3
+|Span 2
+|Footer 4-1 |Footer 4-3
+|Footer 5-1 |Span 3
+|Span 2 | |
+|===
+
+[cols=",,",]
+|===
+.5+|Span 6 |Body 1-2 .2+|Span 2
+.2+|Span 3
+.3+|Span 4
+|Body 3-2
+|Body 4-2
+| | |
+| | |
+|===
+```
diff --git a/test/command/7329.md b/test/command/7329.md
new file mode 100644
--- /dev/null
+++ b/test/command/7329.md
@@ -0,0 +1,72 @@
+```
+% pandoc -f markdown -t org
+- @item1
+- @item1 [p. 12]
+- @item1 [p.12; see also @item2]
+- [@item1]
+- [-@item1]
+- [see @item1 p. 12]
+- [see @item1, p. 12]
+- [see @item1, p. 12 and *passim*]
+- [@item1;@item2]
+- [see @item1; @item2]
+^D
+- [cite/t:@item1]
+- [cite/t:@item1 p. 12]
+- [cite/t:@item1 p.12; see also @item2]
+- [cite:@item1]
+- [cite/na:@item1]
+- [cite:see @item1 p. 12]
+- [cite:see @item1 p. 12]
+- [cite:see @item1 p. 12 and /passim/]
+- [cite:@item1; @item2]
+- [cite:see @item1; @item2]
+```
+
+```
+% pandoc -f markdown -t org -C --bibliography command/biblio.bib
+- [@item1]
+^D
+- (Doe 2005)
+
+<<refs>>
+
+<<ref-item1>>
+Doe, John. 2005. /First Book/. Cambridge University Press.
+```
+
+
+```
+% pandoc -f markdown -t org-citations -C --bibliography command/biblio.bib
+[@item1]
+^D
+(Doe 2005)
+
+<<refs>>
+
+<<ref-item1>>
+Doe, John. 2005. /First Book/. Cambridge University Press.
+```
+
+```
+% pandoc -f org -t markdown
+- [cite/t:@item1]
+- [cite/t:@item1 p. 12]
+- [cite/t:@item1 p.12; see also @item2]
+- [cite:@item1]
+- [cite/na:@item1]
+- [cite:see @item1 p. 12]
+- [cite:see @item1 p. 12 and /passim/]
+- [cite:@item1; @item2]
+- [cite:see @item1; @item2]
+^D
+- @item1
+- @item1 [p. 12]
+- @item1 [p.12; see also @item2]
+- [@item1]
+- [-@item1]
+- [see @item1 p. 12]
+- [see @item1 p. 12 and *passim*]
+- [@item1; @item2]
+- [see @item1; @item2]
+```
diff --git a/test/command/7339.md b/test/command/7339.md
new file mode 100644
--- /dev/null
+++ b/test/command/7339.md
@@ -0,0 +1,15 @@
+```
+% pandoc -f gfm -s -t native
+---
+title: Test
+---
+
+Hi
+^D
+Pandoc
+  Meta
+    { unMeta =
+        fromList [ ( "title" , MetaInlines [ Str "Test" ] ) ]
+    }
+  [ Para [ Str "Hi" ] ]
+```
diff --git a/test/command/7340.md b/test/command/7340.md
new file mode 100644
--- /dev/null
+++ b/test/command/7340.md
@@ -0,0 +1,6 @@
+```
+% pandoc -f latex -t native
+\(*\)
+^D
+[ Para [ Math InlineMath "*" ] ]
+```
diff --git a/test/command/7376.md b/test/command/7376.md
new file mode 100644
--- /dev/null
+++ b/test/command/7376.md
@@ -0,0 +1,16 @@
+```
+% pandoc --citeproc -t plain
+---
+references:
+- id: item1
+  type: book
+  author:
+    - family: Doe
+      given: Jane
+  issued: 2020
+  title: The title
+...
+^D
+
+
+```
diff --git a/test/command/7394.md b/test/command/7394.md
new file mode 100644
--- /dev/null
+++ b/test/command/7394.md
@@ -0,0 +1,85 @@
+```
+% pandoc -f markdown -t plain --citeproc
+---
+csl: command/chicago-fullnote-bibliography.csl
+references:
+- author:
+  - family: Wandt
+    given: Manfred
+  edition: 6
+  id: wandt2014ges-sv
+  issued: 2014
+  publisher: Franz Vahlen
+  publisher-place: München
+  title: Gesetzliche schuldverhältnisse
+  title-short: Gesetzl SV
+  type: book
+- author:
+  - family: Smith
+    given: Zenda
+  edition: 6
+  id: smith2015
+  issued: 2015
+  publisher: Macmillan
+  publisher-place: New York
+  title: A verb and a noun
+  type: book
+---
+
+Hi^[@wandt2014ges-sv.].
+
+Hi^[[@wandt2014ges-sv].].
+
+Hi^[[See also @wandt2014ges-sv].].
+
+Hi^[See also @wandt2014ges-sv.].
+
+Hi^[@wandt2014ges-sv [@smith2015].].
+
+Hi^[[@wandt2014ges-sv; @smith2015].].
+
+Hi [@wandt2014ges-sv].
+
+Hi [see also @wandt2014ges-sv].
+
+^D
+Hi[1].
+
+Hi[2].
+
+Hi[3].
+
+Hi[4].
+
+Hi[5].
+
+Hi[6].
+
+Hi.[7]
+
+Hi.[8]
+
+Smith, Zenda. A Verb and a Noun. 6th ed. New York: Macmillan, 2015.
+
+Wandt, Manfred. Gesetzliche Schuldverhältnisse. 6th ed. München: Franz
+Vahlen, 2014.
+
+[1] Manfred Wandt, Gesetzliche Schuldverhältnisse, 6th ed. (München:
+Franz Vahlen, 2014).
+
+[2] Wandt.
+
+[3] See also Wandt.
+
+[4] See also Wandt.
+
+[5] Wandt, Zenda Smith, A Verb and a Noun, 6th ed. (New York: Macmillan,
+2015).
+
+[6] Wandt, Gesetzl SV; Smith, A Verb and a Noun.
+
+[7] Wandt, Gesetzl SV.
+
+[8] See also Wandt.
+```
+
diff --git a/test/command/7397.md b/test/command/7397.md
new file mode 100644
--- /dev/null
+++ b/test/command/7397.md
@@ -0,0 +1,14 @@
+````
+% pandoc -t markdown
+~~~~ { .haskell startFrom="100"}
+qsort []     = []
+qsort (x:xs) = qsort (filter (< x) xs) ++ [x] ++
+               qsort (filter (>= x) xs)
+~~~~
+^D
+``` {.haskell startFrom="100"}
+qsort []     = []
+qsort (x:xs) = qsort (filter (< x) xs) ++ [x] ++
+               qsort (filter (>= x) xs)
+```
+````
diff --git a/test/command/7400.md b/test/command/7400.md
new file mode 100644
--- /dev/null
+++ b/test/command/7400.md
@@ -0,0 +1,8 @@
+```
+% pandoc -t native -s
+---
+# Comment only
+...
+^D
+Pandoc Meta { unMeta = fromList [] } []
+```
diff --git a/test/command/7416.md b/test/command/7416.md
new file mode 100644
--- /dev/null
+++ b/test/command/7416.md
@@ -0,0 +1,21 @@
+```
+% pandoc -f markdown -t html
+![caption](../media/rId25.jpg "title"){alt="alt"}
+
+^D
+<figure>
+<img src="../media/rId25.jpg" title="title" alt="alt" />
+<figcaption>caption</figcaption>
+</figure>
+```
+
+```
+% pandoc -f markdown -t html
+![caption](../media/rId25.jpg "title")
+
+^D
+<figure>
+<img src="../media/rId25.jpg" title="title" alt="caption" />
+<figcaption aria-hidden="true">caption</figcaption>
+</figure>
+```
diff --git a/test/command/7434.md b/test/command/7434.md
new file mode 100644
--- /dev/null
+++ b/test/command/7434.md
@@ -0,0 +1,23 @@
+```
+% pandoc -f markdown -t native
+\begin{proof}
+\newcommand{\x}{\left.\right.}
+\x
+\end{proof}
+
+1234567890abcdefghi
+
+[\*\a](x)
+^D
+[ RawBlock
+    (Format "tex")
+    "\\begin{proof}\n\\newcommand{\\x}{\\left.\\right.}\n\\left.\\right.\n\\end{proof}"
+, Para [ Str "1234567890abcdefghi" ]
+, Para
+    [ Link
+        ( "" , [] , [] )
+        [ Str "*" , RawInline (Format "tex") "\\a" ]
+        ( "x" , "" )
+    ]
+]
+```
diff --git a/test/command/7436.md b/test/command/7436.md
new file mode 100644
--- /dev/null
+++ b/test/command/7436.md
@@ -0,0 +1,31 @@
+```
+% pandoc -f rst -t native
+.. include:: command/three.txt
+   :code:
+
+.. include:: command/three.txt
+   :literal:
+
+.. include:: command/three.txt
+^D
+[ CodeBlock
+    ( "" , [ "" ] , [ ( "code" , "" ) ] )
+    "1st line.\n2nd line.\n3rd line.\n"
+, CodeBlock
+    ( "" , [ "" ] , [ ( "literal" , "" ) ] )
+    "1st line.\n2nd line.\n3rd line.\n"
+, Para
+    [ Str "1st"
+    , Space
+    , Str "line."
+    , SoftBreak
+    , Str "2nd"
+    , Space
+    , Str "line."
+    , SoftBreak
+    , Str "3rd"
+    , Space
+    , Str "line."
+    ]
+]
+```
diff --git a/test/command/7473.md b/test/command/7473.md
new file mode 100644
--- /dev/null
+++ b/test/command/7473.md
@@ -0,0 +1,39 @@
+```
+% pandoc -f rst -t native
+.. figure:: example.png
+   :figclass: foo bar
+   :align: right
+   :width: 1in
+
+   This is a caption.
+^D
+[ Figure
+    ( "" , [ "foo" , "bar" , "align-right" ] , [] )
+    (Caption
+       Nothing
+       [ Plain
+           [ Str "This"
+           , Space
+           , Str "is"
+           , Space
+           , Str "a"
+           , Space
+           , Str "caption."
+           ]
+       ])
+    [ Plain
+        [ Image
+            ( "" , [] , [ ( "width" , "1in" ) ] )
+            [ Str "This"
+            , Space
+            , Str "is"
+            , Space
+            , Str "a"
+            , Space
+            , Str "caption."
+            ]
+            ( "example.png" , "" )
+        ]
+    ]
+]
+```
diff --git a/test/command/7482.md b/test/command/7482.md
new file mode 100644
--- /dev/null
+++ b/test/command/7482.md
@@ -0,0 +1,47 @@
+```
+% pandoc -f html -t org
+<table border=0 cellpadding=0 cellspacing=0 width=206 style='border-collapse:
+ collapse;width:154pt'>
+<!--StartFragment-->
+ <col width=99 style='mso-width-source:userset;mso-width-alt:3157;width:74pt'>
+ <col width=107 style='mso-width-source:userset;mso-width-alt:3413;width:80pt'>
+ <tr height=23 style='height:17.0pt'>
+  <td height=23 align=left width=99 style='height:17.0pt;width:74pt'>Last N
+  credits</td>
+  <td align=left width=107 style='width:80pt'>Average grade</td>
+ </tr>
+ <tr height=21 style='height:16.0pt'>
+  <td height=21 align=right style='height:16.0pt'>140</td>
+  <td align=right>17.06571429</td>
+ </tr>
+ <tr height=21 style='height:16.0pt'>
+  <td height=21 class=xl63 align=right style='height:16.0pt'>84</td>
+  <td class=xl63 align=right>17.95595238</td>
+ </tr>
+ <tr height=21 style='height:16.0pt'>
+  <td height=21 class=xl63 align=right style='height:16.0pt'>64</td>
+  <td class=xl63 align=right>18.9734375</td>
+ </tr>
+ <tr height=21 style='height:16.0pt'>
+  <td height=21 align=right style='height:16.0pt'>36</td>
+  <td align=right>19.12777778</td>
+ </tr>
+ <tr height=27 style='mso-height-source:userset;height:20.0pt'>
+  <td height=27 align=right style='height:20.0pt'>29</td>
+  <td align=right>19.18275862</td>
+ </tr>
+ <tr height=21 style='height:16.0pt'>
+  <td height=21 align=right style='height:16.0pt'>19</td>
+  <td align=right>19.00526316</td>
+ </tr>
+<!--EndFragment-->
+</table>
+^D
+| Last N credits | Average grade |
+| 140            | 17.06571429   |
+| 84             | 17.95595238   |
+| 64             | 18.9734375    |
+| 36             | 19.12777778   |
+| 29             | 19.18275862   |
+| 19             | 19.00526316   |
+```
diff --git a/test/command/7494.md b/test/command/7494.md
new file mode 100644
--- /dev/null
+++ b/test/command/7494.md
@@ -0,0 +1,62 @@
+```
+% pandoc -f latex -t plain
+\def\foo{BAR}
+{\foo
+\def\foo{BAZ}
+\foo
+}
+\foo
+^D
+BAR BAZ BAR
+```
+
+```
+% pandoc -f latex -t plain
+\def\foo{BAR}
+{\foo
+\gdef\foo{BAZ}
+\foo
+}
+\foo
+^D
+BAR BAZ BAZ
+```
+
+```
+% pandoc -f latex -t plain
+\def\foo{BAR}
+{\foo
+\global\def\foo{BAZ}
+\foo
+}
+\foo
+^D
+BAR BAZ BAZ
+```
+
+```
+% pandoc -f latex -t plain
+\newcommand{\aaa}{BBB}
+{
+\renewcommand{\aaa}{AAA}
+\aaa
+}
+\aaa
+^D
+AAA BBB
+```
+
+```
+% pandoc -f latex -t markdown
+\newcommand{\aaa}{BBB}
+\begin{quote}
+\renewcommand{\aaa}{AAA}
+\aaa
+\end{quote}
+\aaa
+^D
+> AAA
+
+BBB
+```
+
diff --git a/test/command/7497.md b/test/command/7497.md
new file mode 100644
--- /dev/null
+++ b/test/command/7497.md
@@ -0,0 +1,37 @@
+````
+% pandoc -f markdown-raw_tex -t latex
+```
+\end{verbatim}
+\LaTeX
+\begin{verbatim}
+```
+^D
+\begin{Shaded}
+\begin{Highlighting}[]
+\NormalTok{\textbackslash{}end\{verbatim\}}
+\NormalTok{\textbackslash{}LaTeX}
+\NormalTok{\textbackslash{}begin\{verbatim\}}
+\end{Highlighting}
+\end{Shaded}
+````
+
+````
+% pandoc -f markdown-raw_tex -t latex
+hi[^1]
+
+[^1]:
+    ```
+    \end{Verbatim}
+    \LaTeX
+    \begin{Verbatim}
+    ```
+^D
+hi\footnote{\begin{Shaded}
+\begin{Highlighting}[]
+\NormalTok{\textbackslash{}end\{Verbatim\}}
+\NormalTok{\textbackslash{}LaTeX}
+\NormalTok{\textbackslash{}begin\{Verbatim\}}
+\end{Highlighting}
+\end{Shaded}
+}
+````
diff --git a/test/command/7512.md b/test/command/7512.md
new file mode 100644
--- /dev/null
+++ b/test/command/7512.md
@@ -0,0 +1,70 @@
+```
+% pandoc -t native -f latex
+\begin{equation*}
+[d,\delta]=0.
+\end{equation*}
+^D
+[ Para
+    [ Math
+        DisplayMath
+        "\\begin{equation*}\n[d,\\delta]=0.\n\\end{equation*}"
+    ]
+]
+```
+
+```
+% pandoc -t native -f latex
+\begin{table}[htb]
+  \begin{tabular}{|c|c|}
+       $W$      & rel. err. \\[0mm]
+       [$\mu$m] & [\%]\\
+  \end{tabular}
+\end{table}
+^D
+[ Table
+    ( "" , [] , [] )
+    (Caption Nothing [])
+    [ ( AlignCenter , ColWidthDefault )
+    , ( AlignCenter , ColWidthDefault )
+    ]
+    (TableHead ( "" , [] , [] ) [])
+    [ TableBody
+        ( "" , [] , [] )
+        (RowHeadColumns 0)
+        []
+        [ Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Math InlineMath "W" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "rel." , Space , Str "err." ] ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "[" , Math InlineMath "\\mu" , Str "m]" ]
+                ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "[%]" ] ]
+            ]
+        ]
+    ]
+    (TableFoot ( "" , [] , [] ) [])
+]
+```
diff --git a/test/command/7520.md b/test/command/7520.md
new file mode 100644
--- /dev/null
+++ b/test/command/7520.md
@@ -0,0 +1,22 @@
+```
+% pandoc -f org -t native -s
+:PROPERTIES:
+:ID:       d5b18943-98a3-4b2a-a545-41d17bf50f3e
+:END:
+#+title: Common Ground
+^D
+Pandoc
+  Meta
+    { unMeta =
+        fromList
+          [ ( "id"
+            , MetaString "d5b18943-98a3-4b2a-a545-41d17bf50f3e"
+            )
+          , ( "title"
+            , MetaInlines [ Str "Common" , Space , Str "Ground" ]
+            )
+          ]
+    }
+  []
+
+```
diff --git a/test/command/7521.md b/test/command/7521.md
new file mode 100644
--- /dev/null
+++ b/test/command/7521.md
@@ -0,0 +1,11 @@
+```
+% pandoc --strip-comments
+- one
+  <!-- with comm -->
+- two
+^D
+<ul>
+<li>one</li>
+<li>two</li>
+</ul>
+```
diff --git a/test/command/7525.md b/test/command/7525.md
new file mode 100644
--- /dev/null
+++ b/test/command/7525.md
@@ -0,0 +1,33 @@
+```
+% pandoc -f latex -t native
+\texttt{Normal code. \emph{Emph and code.} \textsc{\textbf{Bold small caps.}} \sout{Strikeout. \underline{Strikeout and underline.}}}
+^D
+[ Para
+    [ Code ( "" , [] , [] ) "Normal code. "
+    , Emph [ Code ( "" , [] , [] ) "Emph and code." ]
+    , Code ( "" , [] , [] ) " "
+    , SmallCaps
+        [ Strong [ Code ( "" , [] , [] ) "Bold small caps." ] ]
+    , Code ( "" , [] , [] ) " "
+    , Strikeout
+        [ Code ( "" , [] , [] ) "Strikeout. "
+        , Underline
+            [ Code ( "" , [] , [] ) "Strikeout and underline." ]
+        ]
+    ]
+]
+```
+
+```
+% pandoc -f html -t native
+<code><b>hi</b></code>
+^D
+[ Plain [ Strong [ Code ( "" , [] , [] ) "hi" ] ] ]
+```
+
+```
+% pandoc -f mediawiki -t native
+<code>''hey''</code>
+^D
+[ Para [ Emph [ Code ( "" , [] , [] ) "hey" ] ] ]
+```
diff --git a/test/command/7529.md b/test/command/7529.md
new file mode 100644
--- /dev/null
+++ b/test/command/7529.md
@@ -0,0 +1,7 @@
+```
+% pandoc -f html -t asciidoc
+<a href="https://example.com/show.cgi?id=hi--there--everyone">https://example.com/show.cgi?id=hi--there--everyone</a>
+^D
+link:++https://example.com/show.cgi?id=hi--there--everyone++[]
+```
+
diff --git a/test/command/7546.md b/test/command/7546.md
new file mode 100644
--- /dev/null
+++ b/test/command/7546.md
@@ -0,0 +1,6 @@
+```
+% pandoc -t html -f native
+Span ("", [], [("","")]) []
+^D
+<span></span>
+```
diff --git a/test/command/7557.md b/test/command/7557.md
new file mode 100644
--- /dev/null
+++ b/test/command/7557.md
@@ -0,0 +1,20 @@
+```
+% pandoc -f org -t native
+- 11. and 12. 09. meeting
+^D
+[ BulletList
+    [ [ Plain
+          [ Str "11."
+          , Space
+          , Str "and"
+          , Space
+          , Str "12."
+          , Space
+          , Str "09."
+          , Space
+          , Str "meeting"
+          ]
+      ]
+    ]
+]
+```
diff --git a/test/command/7568.md b/test/command/7568.md
new file mode 100644
--- /dev/null
+++ b/test/command/7568.md
@@ -0,0 +1,16 @@
+```
+% pandoc -f rst
+While `Labyrinth Lord: Revised Edition`_ (LLRE; PDF and POD) has been
+criticized for not being a completely faithful retro-clone of the
+Moldvay/Cook/Marsh Basic/Expert D&D rules (B/X), I think it still
+holds a useful spot.
+
+.. _Labyrinth Lord\: Revised Edition: https://www.drivethrurpg.com/product/64332/Labyrinth-Lord-Revised-Edition
+^D
+<p>While <a
+href="https://www.drivethrurpg.com/product/64332/Labyrinth-Lord-Revised-Edition">Labyrinth
+Lord: Revised Edition</a> (LLRE; PDF and POD) has been criticized for
+not being a completely faithful retro-clone of the Moldvay/Cook/Marsh
+Basic/Expert D&amp;D rules (B/X), I think it still holds a useful
+spot.</p>
+```
diff --git a/test/command/7573.md b/test/command/7573.md
new file mode 100644
--- /dev/null
+++ b/test/command/7573.md
@@ -0,0 +1,11 @@
+```
+% pandoc --preserve-tabs
+<ol>
+	<li>one
+</ol>
+^D
+<ol>
+<li>
+one
+</ol>
+```
diff --git a/test/command/7582.md b/test/command/7582.md
new file mode 100644
--- /dev/null
+++ b/test/command/7582.md
@@ -0,0 +1,28 @@
+```
+% pandoc -t revealjs
+# Slide
+
+::: columns
+:::: column
+Left column
+::::
+
+. . .
+
+:::: column
+Right column
+::::
+:::
+^D
+<section id="slide" class="slide level1">
+<h1>Slide</h1>
+<div class="columns">
+<div class="column">
+<p>Left column</p>
+</div><div class="fragment"><div class="column">
+<p>Right column</p>
+</div></div>
+</div>
+</section>
+
+```
diff --git a/test/command/7589.md b/test/command/7589.md
new file mode 100644
--- /dev/null
+++ b/test/command/7589.md
@@ -0,0 +1,72 @@
+```
+% pandoc -f html -t native
+<table>
+ <thead>
+  <tr>
+   <th>experience</th>
+   <th>expertise</th>
+   <th>paradigms</th>
+   <th>haskell</th>
+   <th>name</th>
+   <th>image</th>
+  </tr>
+ </thead>
+ <tbody></tbody>
+</table>
+^D
+[ Table
+    ( "" , [] , [] )
+    (Caption Nothing [])
+    [ ( AlignDefault , ColWidthDefault )
+    , ( AlignDefault , ColWidthDefault )
+    , ( AlignDefault , ColWidthDefault )
+    , ( AlignDefault , ColWidthDefault )
+    , ( AlignDefault , ColWidthDefault )
+    , ( AlignDefault , ColWidthDefault )
+    ]
+    (TableHead
+       ( "" , [] , [] )
+       [ Row
+           ( "" , [] , [] )
+           [ Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "experience" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "expertise" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "paradigms" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "haskell" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "name" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "image" ] ]
+           ]
+       ])
+    [ TableBody ( "" , [] , [] ) (RowHeadColumns 0) [] [] ]
+    (TableFoot ( "" , [] , [] ) [])
+]
+```
diff --git a/test/command/7615.md b/test/command/7615.md
new file mode 100644
--- /dev/null
+++ b/test/command/7615.md
@@ -0,0 +1,6 @@
+```
+% pandoc -f latex -t native
+\texttt{\^}
+^D
+[ Para [ Code ( "" , [] , [] ) "^" ] ]
+```
diff --git a/test/command/7623.md b/test/command/7623.md
new file mode 100644
--- /dev/null
+++ b/test/command/7623.md
@@ -0,0 +1,12 @@
+```
+% pandoc -t native
+[link $(0,1]$](url)
+^D
+[ Para
+    [ Link
+        ( "" , [] , [] )
+        [ Str "link" , Space , Math InlineMath "(0,1]" ]
+        ( "url" , "" )
+    ]
+]
+```
diff --git a/test/command/7632.md b/test/command/7632.md
new file mode 100644
--- /dev/null
+++ b/test/command/7632.md
@@ -0,0 +1,66 @@
+```
+% pandoc -t native
+(@a) First case
+
+[link to (@a)](url)
+^D
+[ OrderedList
+    ( 1 , Example , TwoParens )
+    [ [ Plain [ Str "First" , Space , Str "case" ] ] ]
+, Para
+    [ Link
+        ( "" , [] , [] )
+        [ Str "link" , Space , Str "to" , Space , Str "(1)" ]
+        ( "url" , "" )
+    ]
+]
+```
+
+```
+% pandoc -t native
+[@a]{.class}
+^D
+[ Para
+    [ Span
+        ( "" , [ "class" ] , [] )
+        [ Cite
+            [ Citation
+                { citationId = "a"
+                , citationPrefix = []
+                , citationSuffix = []
+                , citationMode = AuthorInText
+                , citationNoteNum = 1
+                , citationHash = 0
+                }
+            ]
+            [ Str "@a" ]
+        ]
+    ]
+]
+
+```
+
+```
+% pandoc -t native
+[@a](url)
+^D
+[ Para
+    [ Link
+        ( "" , [] , [] )
+        [ Cite
+            [ Citation
+                { citationId = "a"
+                , citationPrefix = []
+                , citationSuffix = []
+                , citationMode = AuthorInText
+                , citationNoteNum = 1
+                , citationHash = 0
+                }
+            ]
+            [ Str "@a" ]
+        ]
+        ( "url" , "" )
+    ]
+]
+
+```
diff --git a/test/command/7668.md b/test/command/7668.md
new file mode 100644
--- /dev/null
+++ b/test/command/7668.md
@@ -0,0 +1,36 @@
+```
+% pandoc -f bibtex -t csljson
+%@Book{JW82,
+ author   = {Richard A. Johnson and Dean W. Wichern},
+ title    = {Applied Multivariate Statistical Analysis},
+ publisher= {Prentice-Hall},
+ year     = {1983}
+}
+@Book{JW83,
+  author = {Richard %A.
+    B. Johnson},
+%  title = {Multivariate Analysis},
+  year = "%
+  1983"
+}
+^D
+[
+  {
+    "author": [
+      {
+        "family": "Johnson",
+        "given": "Richard B."
+      }
+    ],
+    "id": "JW83",
+    "issued": {
+      "date-parts": [
+        [
+          1983
+        ]
+      ]
+    },
+    "type": "book"
+  }
+]
+```
diff --git a/test/command/7678.md b/test/command/7678.md
new file mode 100644
--- /dev/null
+++ b/test/command/7678.md
@@ -0,0 +1,62 @@
+```
+% pandoc -f bibtex -t csljson
+@misc{doe,
+  author = "Jane Doe",
+  title = "Work",
+  year = "2021",
+  url = "%20and%20"
+}
+^D
+[
+  {
+    "URL": "%20and%20",
+    "author": [
+      {
+        "family": "Doe",
+        "given": "Jane"
+      }
+    ],
+    "id": "doe",
+    "issued": {
+      "date-parts": [
+        [
+          2021
+        ]
+      ]
+    },
+    "title": "Work",
+    "type": ""
+  }
+]
+```
+```
+% pandoc -f bibtex -t csljson
+@misc{doe,
+  author = "Jane Doe",
+  title = "Work",
+  year = "2021",
+  doi = "%20and%20"
+}
+^D
+[
+  {
+    "DOI": "%20and%20",
+    "author": [
+      {
+        "family": "Doe",
+        "given": "Jane"
+      }
+    ],
+    "id": "doe",
+    "issued": {
+      "date-parts": [
+        [
+          2021
+        ]
+      ]
+    },
+    "title": "Work",
+    "type": ""
+  }
+]
+```
diff --git a/test/command/7691.docx b/test/command/7691.docx
new file mode 100644
Binary files /dev/null and b/test/command/7691.docx differ
diff --git a/test/command/7691.md b/test/command/7691.md
new file mode 100644
--- /dev/null
+++ b/test/command/7691.md
@@ -0,0 +1,5 @@
+```
+% pandoc command/7691.docx
+^D
+<p>Some text</p>
+```
diff --git a/test/command/7692.md b/test/command/7692.md
new file mode 100644
--- /dev/null
+++ b/test/command/7692.md
@@ -0,0 +1,13 @@
+```
+% pandoc -t markdown
+[https://example.com](https://example.com){.clz}
+^D
+[https://example.com](https://example.com){.clz}
+```
+
+```
+% pandoc -f markdown -t html | pandoc -f html -t markdown
+<http://example.com>
+^D
+<http://example.com>
+```
diff --git a/test/command/7697.md b/test/command/7697.md
new file mode 100644
--- /dev/null
+++ b/test/command/7697.md
@@ -0,0 +1,27 @@
+```
+% pandoc -f rst -t mediawiki
+.. _refsubpage1:
+
+heading
+-------
+
+ref to top of this section: `refsubpage1`_.
+^D
+<span id="refsubpage1"></span>
+= heading =
+
+ref to top of this section: [[#refsubpage1|refsubpage1]].
+```
+```
+% pandoc -f markdown -t mediawiki
+# Heading {#foo}
+^D
+<span id="foo"></span>
+= Heading =
+```
+```
+% pandoc -f markdown -t mediawiki
+# My Heading {#My_Heading}
+^D
+= My Heading =
+```
diff --git a/test/command/7713.md b/test/command/7713.md
new file mode 100644
--- /dev/null
+++ b/test/command/7713.md
@@ -0,0 +1,29 @@
+```
+% pandoc
+| aaaaaaaaaaaa | bbbbb | ccccccccccc                                                       |
+| ---          | ---   | ---                                                               |
+|              |       | cccccccccc cccccccccc cccccccccc cccccccccc cccccccccc cccccccccc |
+^D
+<table>
+<colgroup>
+<col style="width: 33%" />
+<col style="width: 33%" />
+<col style="width: 33%" />
+</colgroup>
+<thead>
+<tr>
+<th>aaaaaaaaaaaa</th>
+<th>bbbbb</th>
+<th>ccccccccccc</th>
+</tr>
+</thead>
+<tbody>
+<tr>
+<td></td>
+<td></td>
+<td>cccccccccc cccccccccc cccccccccc cccccccccc cccccccccc
+cccccccccc</td>
+</tr>
+</tbody>
+</table>
+```
diff --git a/test/command/7723.md b/test/command/7723.md
new file mode 100644
--- /dev/null
+++ b/test/command/7723.md
@@ -0,0 +1,8 @@
+```
+% pandoc -t native
+Bug![^1]
+
+[^1]: Note.
+^D
+[ Para [ Str "Bug!" , Note [ Para [ Str "Note." ] ] ] ]
+```
diff --git a/test/command/7726.md b/test/command/7726.md
new file mode 100644
--- /dev/null
+++ b/test/command/7726.md
@@ -0,0 +1,22 @@
+```
+% pandoc -t markdown
+\# Hi
+
+\## Hi
+
+\### Hi
+
+\#### hi
+
+and #hi
+^D
+\# Hi
+
+\## Hi
+
+\### Hi
+
+\#### hi
+
+and #hi
+```
diff --git a/test/command/7738.md b/test/command/7738.md
new file mode 100644
--- /dev/null
+++ b/test/command/7738.md
@@ -0,0 +1,6 @@
+```
+% pandoc
+![_](url.png) image
+^D
+<p><img src="url.png" alt="_" /> image</p>
+```
diff --git a/test/command/7743.md b/test/command/7743.md
new file mode 100644
--- /dev/null
+++ b/test/command/7743.md
@@ -0,0 +1,56 @@
+```
+% pandoc -f markdown+mark -t html
+==Hi==
+^D
+<p><mark>Hi</mark></p>
+```
+
+```
+% pandoc -f markdown+mark -t latex
+==Hi==
+^D
+\hl{Hi}
+```
+
+```
+% pandoc -f markdown+mark -t rst
+==Hi==
+^D
+:mark:`Hi`
+```
+
+```
+% pandoc -f html -t markdown+mark
+<mark>Hi</mark>
+^D
+==Hi==
+```
+
+```
+% pandoc -f html -t markdown
+<mark>Hi</mark>
+^D
+[Hi]{.mark}
+```
+
+```
+% pandoc -f rst -t markdown+mark
+:mark:`Hi`
+^D
+==Hi==
+```
+
+```
+% pandoc -f markdown+mark -t docx -o - | pandoc -f docx -t markdown+mark
+==Hi==
+^D
+==Hi==
+```
+
+```
+% pandoc -f latex -t markdown+mark
+\hl{Hi}
+^D
+==Hi==
+```
+
diff --git a/test/command/7761.md b/test/command/7761.md
new file mode 100644
--- /dev/null
+++ b/test/command/7761.md
@@ -0,0 +1,35 @@
+```
+% pandoc --citeproc --csl command/chicago-fullnote-bibliography.csl -t plain
+---
+references:
+- id: noauthor
+  issued: 2020
+  publisher: Oxford University Press
+  publisher-place: Oxford
+  title: Title
+  type: book
+- id: author
+  author:
+  - family: Jones
+    given: Jim
+  issued: 2021
+  title: Title
+  type: book
+  url: "https://duckduckgo.com/cite2021"
+---
+
+Text.[^n]
+
+[^n]: See @author. Another example of a sea level mapping tool with
+similar limitations is @noauthor.
+^D
+Text.[1]
+
+Jones, Jim. Title, 2021. https://duckduckgo.com/cite2021.
+
+Title. Oxford: Oxford University Press, 2020.
+
+[1] See Jim Jones, Title, 2021, https://duckduckgo.com/cite2021. Another
+example of a sea level mapping tool with similar limitations is Title
+(Oxford: Oxford University Press, 2020).
+```
diff --git a/test/command/7778.md b/test/command/7778.md
new file mode 100644
--- /dev/null
+++ b/test/command/7778.md
@@ -0,0 +1,59 @@
+Here the thing to remember is that block level structure indications
+take precedence over inline level structure indications:
+
+```
+% pandoc
+Term
+: Def
+<!--
+: comment def
+-->
+^D
+<dl>
+<dt>Term</dt>
+<dd>
+Def &lt;!–
+</dd>
+<dd>
+comment def –&gt;
+</dd>
+</dl>
+```
+
+```
+% pandoc
+Term
+: Def
+test <!--
+: comment def
+and -->
+^D
+<dl>
+<dt>Term</dt>
+<dd>
+Def test &lt;!–
+</dd>
+<dd>
+comment def and –&gt;
+</dd>
+</dl>
+```
+
+```
+% pandoc
+Term
+: Def
+`code
+: comment def
+more code`
+^D
+<dl>
+<dt>Term</dt>
+<dd>
+Def `code
+</dd>
+<dd>
+comment def more code`
+</dd>
+</dl>
+```
diff --git a/test/command/7803.md b/test/command/7803.md
new file mode 100644
--- /dev/null
+++ b/test/command/7803.md
@@ -0,0 +1,26 @@
+```
+% pandoc -f html -t asciidoc
+<ul>
+<li><a href=x.htm><i>Xx</i></a><i>,</i>
+<li><a href=x.htm><i>Xx</i></a><i>,,</i>
+<li><a href=x.htm><i>Xx</i></a><i>1</i>
+<li><a href=x.htm><i>Xx</i></a>1<i>1</i>
+<li><a href=x.htm><i>Xx</i></a><i>bcd</i>
+<li><a href=x.htm><i>Xx</i></a>a<i>bcd</i>
+<li><a href=x.htm><i>Xx</i></a>a<i>bcd</i>e
+<li><a href=x.htm><i>Xx</i></a> <i>,</i>
+<li><a href=x.htm><i>Xx</i></a>,<i>,</i>
+<li><a href=x.htm>Xx</a><i>,</i>
+</ul>
+^D
+* link:x.htm[_Xx_]_,_
+* link:x.htm[_Xx_]_,,_
+* link:x.htm[_Xx_]_1_
+* link:x.htm[_Xx_]1__1__
+* link:x.htm[_Xx_]_bcd_
+* link:x.htm[_Xx_]a__bcd__
+* link:x.htm[_Xx_]a__bcd__e
+* link:x.htm[_Xx_] _,_
+* link:x.htm[_Xx_],_,_
+* link:x.htm[Xx]_,_
+```
diff --git a/test/command/7808.md b/test/command/7808.md
new file mode 100644
--- /dev/null
+++ b/test/command/7808.md
@@ -0,0 +1,8 @@
+Wiki links should have no display text, if their display text matches
+their target.
+```
+% pandoc -f mediawiki -t mediawiki
+[[Help]] [[Butter|Butter]] [[Bubbles|Everyone loves bubbles]]
+^D
+[[Help]] [[Butter]] [[Bubbles|Everyone loves bubbles]]
+```
diff --git a/test/command/7810.md b/test/command/7810.md
new file mode 100644
--- /dev/null
+++ b/test/command/7810.md
@@ -0,0 +1,43 @@
+```
+% pandoc -f org -t org
+- 
+  #+begin_example
+  aa
+  #+end_example
+- test
+^D
+- 
+  #+begin_example
+  aa
+  #+end_example
+
+- test
+```
+
+```
+% pandoc -f org -t org
+- a
+- 
+- a
+- a
+^D
+- a
+- 
+- a
+- a
+```
+
+```
+% pandoc -f org -t org
+- a
+  - b
+  - b
+- a
+- a
+^D
+- a
+  - b
+  - b
+- a
+- a
+```
diff --git a/test/command/7813-meta.yaml b/test/command/7813-meta.yaml
new file mode 100644
--- /dev/null
+++ b/test/command/7813-meta.yaml
@@ -0,0 +1,6 @@
+---
+abstract: |
+    a footnote[^1] in abstract.
+
+    [^1]: content
+...
diff --git a/test/command/7813.md b/test/command/7813.md
new file mode 100644
--- /dev/null
+++ b/test/command/7813.md
@@ -0,0 +1,26 @@
+```
+% pandoc --metadata-file command/7813-meta.yaml -t native -s
+Hi
+^D
+Pandoc
+  Meta
+    { unMeta =
+        fromList
+          [ ( "abstract"
+            , MetaBlocks
+                [ Para
+                    [ Str "a"
+                    , Space
+                    , Str "footnote"
+                    , Note [ Para [ Str "content" ] ]
+                    , Space
+                    , Str "in"
+                    , Space
+                    , Str "abstract."
+                    ]
+                ]
+            )
+          ]
+    }
+  [ Para [ Str "Hi" ] ]
+```
diff --git a/test/command/7826.md b/test/command/7826.md
new file mode 100644
--- /dev/null
+++ b/test/command/7826.md
@@ -0,0 +1,78 @@
+```
+% pandoc -t plain --citeproc
+---
+bibliography: command/biblio.bib
+suppress-bibliography: true
+csl: command/american-medical-association.csl
+notes-after-punctuation: true
+---
+
+In numerous recent works [@item1; @item2], statistician
+Foo and Bar have criticized XXX.
+^D
+In numerous recent works,^(1,2) statistician Foo and Bar have criticized
+XXX.
+```
+```
+% pandoc -t plain --citeproc
+---
+bibliography: command/biblio.bib
+suppress-bibliography: true
+csl: command/american-medical-association.csl
+---
+
+In numerous recent works [@item1; @item2], statistician
+Foo and Bar have criticized XXX.
+^D
+In numerous recent works^(1,2), statistician Foo and Bar have criticized
+XXX.
+```
+```
+% pandoc -t plain --citeproc
+---
+bibliography: command/biblio.bib
+suppress-bibliography: true
+csl: command/chicago-fullnote-bibliography.csl
+notes-after-punctuation: false
+---
+
+In numerous recent works [@item1; @item2], statistician
+Foo and Bar have criticized XXX.
+^D
+In numerous recent works[1], statistician Foo and Bar have criticized
+XXX.
+
+[1] John Doe, First Book (Cambridge: Cambridge University Press, 2005);
+John Doe, “Article,” Journal of Generic Studies 6 (2006): 33–34.
+```
+```
+% pandoc -t plain --citeproc
+---
+bibliography: command/biblio.bib
+suppress-bibliography: true
+csl: command/chicago-fullnote-bibliography.csl
+---
+
+In numerous recent works [@item1; @item2], statistician
+Foo and Bar have criticized XXX.
+^D
+In numerous recent works,[1] statistician Foo and Bar have criticized
+XXX.
+
+[1] John Doe, First Book (Cambridge: Cambridge University Press, 2005);
+John Doe, “Article,” Journal of Generic Studies 6 (2006): 33–34.
+```
+```
+% pandoc -t plain --citeproc
+---
+bibliography: command/biblio.bib
+suppress-bibliography: true
+notes-after-punctuation: true
+---
+
+In numerous recent works [@item1; @item2], statistician
+Foo and Bar have criticized XXX.
+^D
+In numerous recent works (Doe 2005, 2006), statistician Foo and Bar have
+criticized XXX.
+```
diff --git a/test/command/7847.md b/test/command/7847.md
new file mode 100644
--- /dev/null
+++ b/test/command/7847.md
@@ -0,0 +1,85 @@
+```
+% pandoc -f html -t markdown_strict+pipe_tables
+<table>
+<colgroup>
+<col style="width: 20%" />
+<col style="width: 60%" />
+<col style="width: 20%" />
+</colgroup>
+<thead>
+<tr>
+<th>aaa</th>
+<th>bbb</th>
+<th>ccc</th>
+</tr>
+</thead>
+<tbody>
+<tr>
+<td>Consequat nisi sit amet nibh. Nunc mi tortor, tristique
+sit amet, rhoncus porta, malesuada elementum, nisi.</td>
+<td></td>
+<td>ccc</td>
+</tr>
+</tbody>
+</table>
+^D
+| aaa | bbb | ccc |
+|---------------|------------------------------------------|---------------|
+| Consequat nisi sit amet nibh. Nunc mi tortor, tristique sit amet, rhoncus porta, malesuada elementum, nisi. |  | ccc |
+
+```
+
+```
+% pandoc -f html -t markdown_strict+pipe_tables
+<table>
+<tr>
+<th>aaa</th>
+<th>bbb</th>
+<th>ccc</th>
+</tr>
+<tr>
+<td>Consequat nisi sit amet nibh. Nunc mi tortor, tristique
+sit amet, rhoncus porta, malesuada elementum, nisi.</td>
+<td></td>
+<td>ccc</td>
+</tr>
+</table>
+^D
+| aaa | bbb | ccc |
+|----|----|----|
+| Consequat nisi sit amet nibh. Nunc mi tortor, tristique sit amet, rhoncus porta, malesuada elementum, nisi. |  | ccc |
+
+```
+
+```
+% pandoc -f html -t commonmark+pipe_tables
+<table>
+<colgroup>
+<col style="width: 20%" />
+<col style="width: 60%" />
+<col style="width: 20%" />
+</colgroup>
+<thead>
+<tr>
+<th>aaa</th>
+<th>bbb</th>
+<th>ccc</th>
+</tr>
+</thead>
+<tbody>
+<tr>
+<td>Consequat nisi sit amet nibh. Nunc mi tortor, tristique
+sit amet, rhoncus porta, malesuada elementum, nisi.</td>
+<td>bbb</td>
+<td>ccc</td>
+</tr>
+</tbody>
+</table>
+^D
+| aaa | bbb | ccc |
+|----|----|----|
+| Consequat nisi sit amet nibh. Nunc mi tortor, tristique sit amet, rhoncus porta, malesuada elementum, nisi. | bbb | ccc |
+
+```
+
+
diff --git a/test/command/7857.md b/test/command/7857.md
new file mode 100644
--- /dev/null
+++ b/test/command/7857.md
@@ -0,0 +1,21 @@
+```
+% pandoc --slide-level=2 -t beamer
+# section
+
+::: notes
+my note
+:::
+
+## slide
+
+ok
+^D
+\section{section}\label{section}
+
+\note{my note}
+
+\begin{frame}{slide}
+\protect\phantomsection\label{slide}
+ok
+\end{frame}
+```
diff --git a/test/command/7858.md b/test/command/7858.md
new file mode 100644
--- /dev/null
+++ b/test/command/7858.md
@@ -0,0 +1,6 @@
+```
+% pandoc -t html --columns=50 --wrap=auto
+`neuth asontue stheuosnt aeosunth asnoetuh asneotuh snatehou snatoehu sntahe ousntahoe unstaheou sntaheou aoeu sthoeu sntaoeusnth ansoetuhs atoeuh saonteu`
+^D
+<p><code>neuth asontue stheuosnt aeosunth asnoetuh asneotuh snatehou snatoehu sntahe ousntahoe unstaheou sntaheou aoeu sthoeu sntaoeusnth ansoetuhs atoeuh saonteu</code></p>
+```
diff --git a/test/command/7861.md b/test/command/7861.md
new file mode 100644
--- /dev/null
+++ b/test/command/7861.md
@@ -0,0 +1,7 @@
+```
+% pandoc -s -t native --data-dir=command/7861 --metadata-file=../../7861.yaml
+Hello
+^D
+2> Could not find metadata file '../../7861.yaml'
+=> 98
+```
diff --git a/test/command/7861.yaml b/test/command/7861.yaml
new file mode 100644
--- /dev/null
+++ b/test/command/7861.yaml
diff --git a/test/command/7861/metadata/placeholder b/test/command/7861/metadata/placeholder
new file mode 100644
--- /dev/null
+++ b/test/command/7861/metadata/placeholder
diff --git a/test/command/7863.md b/test/command/7863.md
new file mode 100644
--- /dev/null
+++ b/test/command/7863.md
@@ -0,0 +1,27 @@
+```
+% pandoc -f commonmark+yaml_metadata_block+sourcepos -t native
+---
+key:
+  |
+  value
+...
+
+
+Text
+^D
+[ Div
+    ( ""
+    , []
+    , [ ( "wrapper" , "1" ) , ( "data-pos" , "8:1-9:1" ) ]
+    )
+    [ Para
+        [ Span
+            ( ""
+            , []
+            , [ ( "wrapper" , "1" ) , ( "data-pos" , "8:1-8:5" ) ]
+            )
+            [ Str "Text" ]
+        ]
+    ]
+]
+```
diff --git a/test/command/7871.md b/test/command/7871.md
new file mode 100644
--- /dev/null
+++ b/test/command/7871.md
@@ -0,0 +1,14 @@
+```
+% pandoc -f html -t html
+<table>
+<tr><td style="padding-right:4px;text-align:right">a</td></tr>
+</table>
+^D
+<table>
+<tbody>
+<tr>
+<td style="text-align: right; padding-right: 4px;">a</td>
+</tr>
+</tbody>
+</table>
+```
diff --git a/test/command/7884.md b/test/command/7884.md
new file mode 100644
--- /dev/null
+++ b/test/command/7884.md
@@ -0,0 +1,72 @@
+```
+% pandoc -f html+epub_html_exts -t native
+<body epub:type="bodymatter">
+<section id="chapter-1" class="level1" data-number="1">
+<h1 data-number="1">Chapter 1</h1>
+<p>Here is a footnote.<a href="#fn1" class="footnote-ref" id="fnref1" epub:type="noteref">1</a></p>
+<p>Here is a second footnote.<a href="#fn2" class="footnote-ref" id="fnref2" epub:type="noteref">2</a></p>
+</section>
+<section class="footnotes footnotes-end-of-document" epub:type="footnotes">
+<hr />
+<ol>
+<li id="fn1" epub:type="footnote"><p>This is a test<a href="#fnref1" class="footnote-back" role="doc-backlink">↩︎</a></p></li>
+<li id="fn2" epub:type="footnote"><p>This is another test<a href="#fnref2" class="footnote-back" role="doc-backlink">↩︎</a></p></li>
+</ol>
+</section>
+</body>
+^D
+[ Div
+    ( "chapter-1"
+    , [ "section" , "level1" ]
+    , [ ( "number" , "1" ) ]
+    )
+    [ Header
+        1
+        ( "" , [] , [ ( "number" , "1" ) ] )
+        [ Str "Chapter" , Space , Str "1" ]
+    , Para
+        [ Str "Here"
+        , Space
+        , Str "is"
+        , Space
+        , Str "a"
+        , Space
+        , Str "footnote."
+        , Note
+            [ Para
+                [ Str "This"
+                , Space
+                , Str "is"
+                , Space
+                , Str "a"
+                , Space
+                , Str "test"
+                ]
+            ]
+        ]
+    , Para
+        [ Str "Here"
+        , Space
+        , Str "is"
+        , Space
+        , Str "a"
+        , Space
+        , Str "second"
+        , Space
+        , Str "footnote."
+        , Note
+            [ Para
+                [ Str "This"
+                , Space
+                , Str "is"
+                , Space
+                , Str "another"
+                , Space
+                , Str "test"
+                ]
+            ]
+        ]
+    ]
+]
+
+```
diff --git a/test/command/7894.md b/test/command/7894.md
new file mode 100644
--- /dev/null
+++ b/test/command/7894.md
@@ -0,0 +1,109 @@
+```
+% pandoc -f ris -t csljson
+TY  - BOOK
+ID  - Chang_Keisler_Model_Theory
+AU  - Chang, C. C.
+AU  - Keisler, H. Jerome
+PY  - 1990
+ET  - 3
+TI  - Model Theory
+PU  - North-Holland Press
+PP  - Amsterdam
+KW  - model theory
+KW  - logic
+ER  -
+TY  - JOUR
+AU  - Shannon, Claude E.
+PY  - 1948
+DA  - July
+TI  - A Mathematical Theory of Communication
+T2  - Bell System Technical Journal
+SP  - 379
+EP  - 423
+VL  - 27
+ER  -
+TY  - JOUR
+T1  - On computable numbers, with an application to the Entscheidungsproblem
+A1  - Turing, Alan Mathison
+JO  - Proc. of London Mathematical Society
+VL  - 47
+IS  - 1
+KW  - decidability
+KW  - computability
+SP  - 230
+EP  - 265
+Y1  - 1937
+ER  -
+^D
+[
+  {
+    "author": [
+      {
+        "family": "Chang",
+        "given": "C. C."
+      },
+      {
+        "family": "Keisler",
+        "given": "H. Jerome"
+      }
+    ],
+    "edition": "3",
+    "id": "Chang_Keisler_Model_Theory",
+    "issued": {
+      "date-parts": [
+        [
+          1990
+        ]
+      ]
+    },
+    "keyword": "logic, model theory",
+    "publisher-place": "Amsterdam",
+    "title": "Model Theory",
+    "type": "book"
+  },
+  {
+    "author": [
+      {
+        "family": "Shannon",
+        "given": "Claude E."
+      }
+    ],
+    "container-title": "Bell System Technical Journal",
+    "id": "Shannon_1948",
+    "issued": {
+      "date-parts": [
+        [
+          1948
+        ]
+      ]
+    },
+    "page": "379-423",
+    "title": "A Mathematical Theory of Communication",
+    "type": "article-journal",
+    "volume": "27"
+  },
+  {
+    "author": [
+      {
+        "family": "Turing",
+        "given": "Alan Mathison"
+      }
+    ],
+    "container-title": "Proc. of London Mathematical Society",
+    "id": "Turing_1937",
+    "issue": "1",
+    "issued": {
+      "date-parts": [
+        [
+          1937
+        ]
+      ]
+    },
+    "keyword": "computability, decidability",
+    "page": "230-265",
+    "title": "On computable numbers, with an application to the Entscheidungsproblem",
+    "type": "article-journal",
+    "volume": "47"
+  }
+]
+```
diff --git a/test/command/7919.md b/test/command/7919.md
new file mode 100644
--- /dev/null
+++ b/test/command/7919.md
@@ -0,0 +1,118 @@
+```
+% pandoc -f markdown
+single column table | 
+------------------- | 
+item 1              |
+item 2              |
+^D
+<table>
+<thead>
+<tr>
+<th>single column table</th>
+</tr>
+</thead>
+<tbody>
+<tr>
+<td>item 1</td>
+</tr>
+<tr>
+<td>item 2</td>
+</tr>
+</tbody>
+</table>
+```
+
+```
+% pandoc -f markdown
+| single column table
+| -------------------
+| item 1
+| item 2
+^D
+<table>
+<thead>
+<tr>
+<th>single column table</th>
+</tr>
+</thead>
+<tbody>
+<tr>
+<td>item 1</td>
+</tr>
+<tr>
+<td>item 2</td>
+</tr>
+</tbody>
+</table>
+```
+
+```
+% pandoc -f markdown
+single column table
+-------------------
+item 1
+item 2
+^D
+<h2 id="single-column-table">single column table</h2>
+<p>item 1 item 2</p>
+```
+
+```
+% pandoc -f gfm
+single column table | 
+------------------- | 
+item 1              |
+item 2              |
+^D
+<table>
+<thead>
+<tr>
+<th>single column table</th>
+</tr>
+</thead>
+<tbody>
+<tr>
+<td>item 1</td>
+</tr>
+<tr>
+<td>item 2</td>
+</tr>
+</tbody>
+</table>
+```
+
+```
+% pandoc -f gfm
+| single column table
+| -------------------
+| item 1
+| item 2
+^D
+<table>
+<thead>
+<tr>
+<th>single column table</th>
+</tr>
+</thead>
+<tbody>
+<tr>
+<td>item 1</td>
+</tr>
+<tr>
+<td>item 2</td>
+</tr>
+</tbody>
+</table>
+```
+
+```
+% pandoc -f gfm
+single column table
+-------------------
+item 1
+item 2
+^D
+<h2 id="single-column-table">single column table</h2>
+<p>item 1 item 2</p>
+```
+
diff --git a/test/command/7920.md b/test/command/7920.md
new file mode 100644
--- /dev/null
+++ b/test/command/7920.md
@@ -0,0 +1,20 @@
+```
+% pandoc -t native
+[hi]{#123}
+^D
+[ Para [ Span ( "123" , [] , [] ) [ Str "hi" ] ] ]
+```
+
+```
+% pandoc -t markdown
+[hi]{#123}
+^D
+[hi]{#123}
+```
+
+```
+% pandoc -t markdown
+# Hi {#123}
+^D
+# Hi {#123}
+```
diff --git a/test/command/7930.md b/test/command/7930.md
new file mode 100644
--- /dev/null
+++ b/test/command/7930.md
@@ -0,0 +1,98 @@
+```
+% pandoc -f latex -t native
+We discuss foobar in notes \ref{note:X} and \ref{note:Y}.
+
+Foo.\footnote{\label{note:X}A note. See also note~\ref{note:Y}.}
+
+Bar.\footnote{\label{note:Y}Another note. See also
+note~\ref{note:X}}
+^D
+[ Para
+    [ Str "We"
+    , Space
+    , Str "discuss"
+    , Space
+    , Str "foobar"
+    , Space
+    , Str "in"
+    , Space
+    , Str "notes"
+    , Space
+    , Link
+        ( ""
+        , []
+        , [ ( "reference-type" , "ref" )
+          , ( "reference" , "note:X" )
+          ]
+        )
+        [ Str "1" ]
+        ( "#note:X" , "" )
+    , Space
+    , Str "and"
+    , Space
+    , Link
+        ( ""
+        , []
+        , [ ( "reference-type" , "ref" )
+          , ( "reference" , "note:Y" )
+          ]
+        )
+        [ Str "2" ]
+        ( "#note:Y" , "" )
+    , Str "."
+    ]
+, Para
+    [ Str "Foo."
+    , Note
+        [ Para
+            [ Span ( "note:X" , [] , [ ( "label" , "note:X" ) ] ) []
+            , Str "A"
+            , Space
+            , Str "note."
+            , Space
+            , Str "See"
+            , Space
+            , Str "also"
+            , Space
+            , Str "note\160"
+            , Link
+                ( ""
+                , []
+                , [ ( "reference-type" , "ref" )
+                  , ( "reference" , "note:Y" )
+                  ]
+                )
+                [ Str "2" ]
+                ( "#note:Y" , "" )
+            , Str "."
+            ]
+        ]
+    ]
+, Para
+    [ Str "Bar."
+    , Note
+        [ Para
+            [ Span ( "note:Y" , [] , [ ( "label" , "note:Y" ) ] ) []
+            , Str "Another"
+            , Space
+            , Str "note."
+            , Space
+            , Str "See"
+            , Space
+            , Str "also"
+            , SoftBreak
+            , Str "note\160"
+            , Link
+                ( ""
+                , []
+                , [ ( "reference-type" , "ref" )
+                  , ( "reference" , "note:X" )
+                  ]
+                )
+                [ Str "1" ]
+                ( "#note:X" , "" )
+            ]
+        ]
+    ]
+]
+```
diff --git a/test/command/7939.md b/test/command/7939.md
new file mode 100644
--- /dev/null
+++ b/test/command/7939.md
@@ -0,0 +1,9 @@
+```
+% pandoc -f latex -t native
+\def\|{\verb|}
+\vbox{
+\hbox{\|\begin{minipage}[t]%|}
+}
+^D
+[ Para [ Code ( "" , [] , [] ) "\\begin{minipage}[t]%" ] ]
+```
diff --git a/test/command/7941.md b/test/command/7941.md
new file mode 100644
--- /dev/null
+++ b/test/command/7941.md
@@ -0,0 +1,6 @@
+```
+% pandoc -f commonmark_x -t commonmark_x
+# Class setup
+^D
+# Class setup
+```
diff --git a/test/command/7953.md b/test/command/7953.md
new file mode 100644
--- /dev/null
+++ b/test/command/7953.md
@@ -0,0 +1,11 @@
+```
+% pandoc -f latex -t native
+{foo\bgroup bar\egroup }
+^D
+[ Para
+    [ Span
+        ( "" , [] , [] )
+        [ Str "foo" , Span ( "" , [] , [] ) [ Str "bar" ] ]
+    ]
+]
+```
diff --git a/test/command/7965.md b/test/command/7965.md
new file mode 100644
--- /dev/null
+++ b/test/command/7965.md
@@ -0,0 +1,54 @@
+```
+% pandoc -f markdown -t gfm
+Watson and Crick (1953)
+
+<div id="refs" class="references csl-bib-body hanging-indent">
+
+<div id="ref-WatsonCrick1953" class="csl-entry">
+
+Watson, J. D., and F. H. C. Crick. 1953. “Molecular Structure of Nucleic
+Acids: A Structure for Deoxyribose Nucleic Acid.” *Nature* 171 (4356):
+737–38. <https://doi.org/10.1038/171737a0>.
+
+</div>
+
+</div>
+^D
+Watson and Crick (1953)
+
+<div id="refs" class="references csl-bib-body hanging-indent">
+
+<div id="ref-WatsonCrick1953" class="csl-entry">
+
+Watson, J. D., and F. H. C. Crick. 1953. “Molecular Structure of Nucleic
+Acids: A Structure for Deoxyribose Nucleic Acid.” *Nature* 171 (4356):
+737–38. <https://doi.org/10.1038/171737a0>.
+
+</div>
+
+</div>
+```
+
+```
+% pandoc -f markdown -t gfm-raw_html
+Watson and Crick (1953)
+
+<div id="refs" class="references csl-bib-body hanging-indent">
+
+<div id="ref-WatsonCrick1953" class="csl-entry">
+
+Watson, J. D., and F. H. C. Crick. 1953. “Molecular Structure of Nucleic
+Acids: A Structure for Deoxyribose Nucleic Acid.” *Nature* 171 (4356):
+737–38. <https://doi.org/10.1038/171737a0>.
+
+</div>
+
+</div>
+^D
+Watson and Crick (1953)
+
+Watson, J. D., and F. H. C. Crick. 1953. “Molecular Structure of Nucleic
+Acids: A Structure for Deoxyribose Nucleic Acid.” *Nature* 171 (4356):
+737–38. <https://doi.org/10.1038/171737a0>.
+```
+
diff --git a/test/command/8003.md b/test/command/8003.md
new file mode 100644
--- /dev/null
+++ b/test/command/8003.md
@@ -0,0 +1,6 @@
+```
+% pandoc -f markdown+ascii_identifiers
+# Işık
+^D
+<h1 id="isik">Işık</h1>
+```
diff --git a/test/command/8011.md b/test/command/8011.md
new file mode 100644
--- /dev/null
+++ b/test/command/8011.md
@@ -0,0 +1,15 @@
+```
+% pandoc -f docbook -t gfm
+<itemizedlist mark="none">
+<listitem>
+<simpara>&#10063; a</simpara>
+</listitem>
+<listitem>
+<simpara>&#10003; b</simpara>
+</listitem>
+</itemizedlist>
+^D
+- [ ] a
+
+- [x] b
+```
diff --git a/test/command/8024.md b/test/command/8024.md
new file mode 100644
--- /dev/null
+++ b/test/command/8024.md
@@ -0,0 +1,10 @@
+```
+% pandoc -d command/8024a.yaml -t markdown
+Hello, if this works the text should be wrapped.
+^D
+Hello, if this
+works the text
+should be
+wrapped.
+
+```
diff --git a/test/command/8024a.yaml b/test/command/8024a.yaml
new file mode 100644
--- /dev/null
+++ b/test/command/8024a.yaml
@@ -0,0 +1,2 @@
+defaults: ${.}/8024b.yaml
+
diff --git a/test/command/8024b.yaml b/test/command/8024b.yaml
new file mode 100644
--- /dev/null
+++ b/test/command/8024b.yaml
@@ -0,0 +1,3 @@
+wrap: auto
+columns: 15
+
diff --git a/test/command/8028.md b/test/command/8028.md
new file mode 100644
--- /dev/null
+++ b/test/command/8028.md
@@ -0,0 +1,10 @@
+```
+% pandoc
+foo^[a note
+
+with multiple paragraphs]
+^D
+<p>foo^[a note</p>
+<p>with multiple paragraphs]</p>
+
+```
diff --git a/test/command/8047.md b/test/command/8047.md
new file mode 100644
--- /dev/null
+++ b/test/command/8047.md
@@ -0,0 +1,6 @@
+```
+% pandoc --wrap=none
+![](file.jpg){height=10em width=10em style='border: 1px solid black'}
+^D
+<p><img src="file.jpg" style="border: 1px solid black;width:10em;height:10em" /></p>
+```
diff --git a/test/command/8070.md b/test/command/8070.md
new file mode 100644
--- /dev/null
+++ b/test/command/8070.md
@@ -0,0 +1,13 @@
+```
+% pandoc -f html -t asciidoc
+<p><a href="https://docs.oracle.com/database/121/BRADV/rcmxplat.htm#BRADV724">12.1
+manual&#44; Database Backup and Recovery User&#8217;s Guide:
+<span class="enumeration_chapter">Chapter 28</span> Transporting Data Across Platforms&#44;
+Steps to Transport a Database to a Different Platform Using Backup Sets</a></p>
+^D
+https://docs.oracle.com/database/121/BRADV/rcmxplat.htm#BRADV724[12.1
+manual&#44; Database Backup and Recovery User’s Guide:
+[.enumeration_chapter]#Chapter 28# Transporting Data Across
+Platforms&#44; Steps to Transport a Database to a Different Platform
+Using Backup Sets]
+```
diff --git a/test/command/8079.md b/test/command/8079.md
new file mode 100644
--- /dev/null
+++ b/test/command/8079.md
@@ -0,0 +1,19 @@
+```
+% pandoc -f html -t icml
+<table custom-style="Foo">
+<tr><td>one</td></tr>
+</table>
+^D
+<Table AppliedTableStyle="TableStyle/Foo" HeaderRowCount="0" BodyRowCount="1" ColumnCount="1">
+  <Column Name="0" />
+  <Cell Name="0:0" AppliedCellStyle="CellStyle/Cell">
+    <ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/TablePar">
+      <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
+        <Content>one</Content>
+      </CharacterStyleRange>
+    </ParagraphStyleRange>
+  </Cell>
+</Table>
+<ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/TableCaption">
+</ParagraphStyleRange>
+```
diff --git a/test/command/8088.md b/test/command/8088.md
new file mode 100644
--- /dev/null
+++ b/test/command/8088.md
@@ -0,0 +1,6 @@
+```
+% pandoc -t latex --biblatex
+[@first, 1; @second; @third, 3]
+^D
+\autocites[1]{first}{second}[3]{third}
+```
diff --git a/test/command/8097.md b/test/command/8097.md
new file mode 100644
--- /dev/null
+++ b/test/command/8097.md
@@ -0,0 +1,9 @@
+```
+% pandoc --number-sec --number-offset=2 --wrap=none
+# One
+
+# two
+^D
+<h1 data-number="3" id="one"><span class="header-section-number">3</span> One</h1>
+<h1 data-number="4" id="two"><span class="header-section-number">4</span> two</h1>
+```
diff --git a/test/command/8098.md b/test/command/8098.md
new file mode 100644
--- /dev/null
+++ b/test/command/8098.md
@@ -0,0 +1,36 @@
+```
+% pandoc -t revealjs --slide-level=2
+# Title 1
+
+## Slide 1
+
+Text.
+
+::: fragment
+### Sub Slide header
+
+Text.
+:::
+
+## Slide 2
+
+Text.
+^D
+<section>
+<section id="title-1" class="title-slide slide level1">
+<h1>Title 1</h1>
+
+</section>
+<section id="slide-1" class="slide level2">
+<h2>Slide 1</h2>
+<p>Text.</p>
+<div class="fragment">
+<h3 id="sub-slide-header">Sub Slide header</h3>
+<p>Text.</p>
+</div>
+</section>
+<section id="slide-2" class="slide level2">
+<h2>Slide 2</h2>
+<p>Text.</p>
+</section></section>
+```
diff --git a/test/command/8110.md b/test/command/8110.md
new file mode 100644
--- /dev/null
+++ b/test/command/8110.md
@@ -0,0 +1,41 @@
+```
+% pandoc -f mediawiki
+{| class="wikitable"
+! Header text 
+! Header text 
+! Header text
+
+|-
+| Example 
+| Example 
+| Example
+
+|- <!-- This is a comment --> 
+| Example 
+| Example 
+| Example
+|}
+^D
+<table>
+<thead>
+<tr>
+<th><p>Header text</p></th>
+<th><p>Header text</p></th>
+<th><p>Header text</p></th>
+</tr>
+</thead>
+<tbody>
+<tr>
+<td><p>Example</p></td>
+<td><p>Example</p></td>
+<td><p>Example</p></td>
+</tr>
+<tr>
+<td><p>Example</p></td>
+<td><p>Example</p></td>
+<td><p>Example</p></td>
+</tr>
+</tbody>
+</table>
+
+```
diff --git a/test/command/8131.md b/test/command/8131.md
new file mode 100644
--- /dev/null
+++ b/test/command/8131.md
@@ -0,0 +1,41 @@
+# TOC in gfm contains no HTML by default
+```
+% pandoc --to=gfm --toc --standalone
+# Head
+
+Content
+^D
+- [Head](#head)
+
+# Head
+
+Content
+```
+
+# Same in Markdown if link_attributes extension is disabled
+```
+% pandoc --to=markdown-link_attributes --toc --standalone
+# Head
+
+Content
+^D
+- [Head](#head)
+
+# Head
+
+Content
+```
+
+# IDs are added to TOC with the "attributes" CommonMark extension
+```
+% pandoc --to=commonmark+gfm_auto_identifiers+attributes --toc -s
+# Nam a sapien
+
+Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
+^D
+- [Nam a sapien](#nam-a-sapien){#toc-nam-a-sapien}
+
+# Nam a sapien
+
+Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
+```
diff --git a/test/command/8150.md b/test/command/8150.md
new file mode 100644
--- /dev/null
+++ b/test/command/8150.md
@@ -0,0 +1,55 @@
+Nested bullet lists
+```
+% pandoc -f html -t markdown
+<ul>
+	<li>L1</li>
+	<li>L2</li>
+	<ul>
+		<li>L3.1</li>
+		<li>L3.2</li>
+	</ul>
+  <li>L4</li>
+</ul>
+^D
+- L1
+- L2
+  - L3.1
+  - L3.2
+- L4
+```
+
+Nested ordered lists
+```
+% pandoc -f html -t markdown
+<ol>
+	<li>L1</li>
+	<li>L2</li>
+	<ol>
+		<li>L3.1</li>
+		<li>L3.2</li>
+	</ol>
+</ol>
+^D
+1.  L1
+2.  L2
+    1.  L3.1
+    2.  L3.2
+```
+
+Ordered list nested below an unordered list
+```
+% pandoc -f html -t markdown
+<ul>
+	<li>L1</li>
+	<li>L2</li>
+	<ol>
+		<li>L3.1</li>
+		<li>L3.2</li>
+	</ol>
+</ul>
+^D
+- L1
+- L2
+  1.  L3.1
+  2.  L3.2
+```
diff --git a/test/command/8170.md b/test/command/8170.md
new file mode 100644
--- /dev/null
+++ b/test/command/8170.md
@@ -0,0 +1,15 @@
+```
+% pandoc -f rtf -t html
+{\rtf1\ansi\ansicpg1252\cocoartf2638
+\cocoascreenfonts1\cocoatextscaling0\cocoaplatform0{\fonttbl\f0\froman\fcharset0 Times-Roman;}
+{\colortbl;\red255\green255\blue255;}
+{\*\expandedcolortbl;;}
+\margl1440\margr1440\vieww16800\viewh17280\viewkind0
+\pard\tx1080\tx1440\tx2160\tx2880\tx3600\tx4320\tx5040\tx5760\tx6480\tx7200\tx7920\tx8640\li180\fi440\sa120\pardirnatural\partightenfactor0
+
+\f0\fs34 \cf0 In 5
+\fs20 \super th
+\fs34 \nosupersub  grade I found a bug.}
+^D
+<p>In 5<sup>th</sup> grade I found a bug.</p>
+```
diff --git a/test/command/8174.md b/test/command/8174.md
new file mode 100644
--- /dev/null
+++ b/test/command/8174.md
@@ -0,0 +1,44 @@
+````
+% pandoc -t native
+```yaml {#id}
+some: code
+```
+^D
+[ CodeBlock ( "id" , [ "yaml" ] , [] ) "some: code" ]
+````
+
+````
+% pandoc -t native
+```yaml {.class #id}
+some: code
+```
+^D
+[ CodeBlock
+    ( "id" , [ "yaml" , "class" ] , [] ) "some: code"
+]
+````
+
+<!-- Inline code sections at the start of the line should not be mistaken for code blocks -->
+````
+% pandoc -t native
+```ab```
+^D
+[ Para [ Code ( "" , [] , [] ) "ab" ] ]
+````
+
+````
+% pandoc -t native
+```ab```{.class}
+^D
+[ Para [ Code ( "" , [ "class" ] , [] ) "ab" ] ]
+````
+
+<!-- Illegal language identifiers should be treated as inline code for now -->
+````
+% pandoc -t native
+``` foo}{.bar}
+test
+```
+^D
+[ Para [ Code ( "" , [] , [] ) "foo}{.bar} test" ] ]
+````
diff --git a/test/command/8178.md b/test/command/8178.md
new file mode 100644
--- /dev/null
+++ b/test/command/8178.md
@@ -0,0 +1,25 @@
+```
+% pandoc -f dokuwiki -t native
+<latex>$\sum_{\substack{(i,j) \in I^2 \i \neq j}}$</latex>
+^D
+[ Para
+    [ RawInline
+        (Format "latex")
+        "$\\sum_{\\substack{(i,j) \\in I^2 \\i \\neq j}}$"
+    ]
+]
+```
+
+```
+% pandoc -f dokuwiki+tex_math_dollars -t native
+$mc^2$
+^D
+[ Para [ Math InlineMath "mc^2" ] ]
+```
+
+```
+% pandoc -f dokuwiki -t native
+$mc^2$
+^D
+[ Para [ Str "$mc^2$" ] ]
+```
diff --git a/test/command/8179.md b/test/command/8179.md
new file mode 100644
--- /dev/null
+++ b/test/command/8179.md
@@ -0,0 +1,6 @@
+```
+% pandoc -f latex -t native
+\passthrough{\lstinline!\\textbf\{\}!}
+^D
+[ Para [ Code ( "" , [] , [] ) "\\textbf{}" ] ]
+```
diff --git a/test/command/8182.md b/test/command/8182.md
new file mode 100644
--- /dev/null
+++ b/test/command/8182.md
@@ -0,0 +1,6 @@
+```
+% pandoc -f dokuwiki -t rst
+This //text and [[https://pandoc.org/|link]] are in italic//.
+^D
+This *text and* `link <https://pandoc.org/>`__ *are in italic*.
+```
diff --git a/test/command/8201.md b/test/command/8201.md
new file mode 100644
--- /dev/null
+++ b/test/command/8201.md
@@ -0,0 +1,6 @@
+```
+% pandoc -f org -t html
+[[file:d:/Home/Documents/test.png][Link Test]]
+^D
+<p><a href="file:///d:/Home/Documents/test.png">Link Test</a></p>
+```
diff --git a/test/command/8204.md b/test/command/8204.md
new file mode 100644
--- /dev/null
+++ b/test/command/8204.md
@@ -0,0 +1,51 @@
+Include abstract in Org output.
+```
+% pandoc --to=org --standalone
+---
+abstract: |
+  This is an *abstract*.
+
+  It has multiple paragraphs.
+---
+^D
+#+begin_abstract
+This is an /abstract/.
+
+It has multiple paragraphs.
+
+#+end_abstract
+```
+
+Parse abstract environment as *abstract* metadata field.
+```
+% pandoc --from=org --to=markdown --standalone
+#+begin_abstract
+
+This is an /abstract/.
+
+It has multiple paragraphs.
+#+end_abstract
+
+Main text
+^D
+---
+abstract: |
+  This is an *abstract*.
+
+  It has multiple paragraphs.
+---
+
+Main text
+```
+
+Uppercase ABSTRACT environment is not moved to metadata.
+```
+% pandoc --from=org --to=markdown --standalone
+#+BEGIN_ABSTRACT
+Some text.
+#+END_ABSTRACT
+^D
+::: ABSTRACT
+Some text.
+:::
+```
diff --git a/test/command/8216.md b/test/command/8216.md
new file mode 100644
--- /dev/null
+++ b/test/command/8216.md
@@ -0,0 +1,51 @@
+Misaligned separators in grid table
+```
+% pandoc -f markdown -t html
+: Grid Table
+
++-----------------+:-:+
+|Some text        |[text]{.class1 .class2 .class3}|
++-----------------+---+
+|Some text        |[text]{.class1 .class2 .class3}|
++-----------------+---+
+|Some text        |[text]{.class1 .class2 .class3}|
++-----------------+---+
+^D
+<table style="width:69%;">
+<caption>Grid Table</caption>
+<colgroup>
+<col style="width: 25%" />
+<col style="width: 44%" />
+</colgroup>
+<tbody>
+<tr>
+<td>Some text</td>
+<td><span class="class1 class2 class3">text</span></td>
+</tr>
+<tr>
+<td>Some text</td>
+<td><span class="class1 class2 class3">text</span></td>
+</tr>
+<tr>
+<td>Some text</td>
+<td><span class="class1 class2 class3">text</span></td>
+</tr>
+</tbody>
+</table>
+```
+
+Missing cell
+
+```
+% pandoc -f markdown -t gfm
++------+
+| text |
++------+---+
+| text | 1 |
++------+---+
+^D
+|      |     |
+|------|-----|
+| text |     |
+| text | 1   |
+```
diff --git a/test/command/8219.md b/test/command/8219.md
new file mode 100644
--- /dev/null
+++ b/test/command/8219.md
@@ -0,0 +1,16 @@
+```
+% pandoc -f html -t latex
+<table id="test">
+  <tr><td>one</td><td>two</td></tr>
+</table>
+^D
+\begin{longtable}[]{@{}ll@{}}
+\caption{}\label{test}\tabularnewline
+\toprule\noalign{}
+\endfirsthead
+\endhead
+\bottomrule\noalign{}
+\endlastfoot
+one & two \\
+\end{longtable}
+```
diff --git a/test/command/8236.md b/test/command/8236.md
new file mode 100644
--- /dev/null
+++ b/test/command/8236.md
@@ -0,0 +1,15 @@
+```
+% pandoc -f org -t native
+  #+begin_src jupyter-python :session py :display plain
+  import pandas as pd
+  df = pd.read_csv('weight.csv', parse_dates=['Date'], index_col=0)
+  #+end_src
+^D
+[ CodeBlock
+    ( ""
+    , [ "python" , "code" ]
+    , [ ( "session" , "py" ) , ( "display" , "plain" ) ]
+    )
+    "import pandas as pd\ndf = pd.read_csv('weight.csv', parse_dates=['Date'], index_col=0)\n"
+]
+```
diff --git a/test/command/8243.md b/test/command/8243.md
new file mode 100644
--- /dev/null
+++ b/test/command/8243.md
@@ -0,0 +1,23 @@
+```
+% pandoc -f latex
+\newenvironment{topics}{
+\newcommand{\topic}[2]{ \item{##1 / ##2} }
+Topics:
+\begin{itemize}
+}
+{
+\end{itemize}
+}
+
+\begin{topics}
+\topic{Foo}{Bar}
+\topic{Baz}{Bim}
+\end{topics}
+^D
+<p>Topics:</p>
+<ul>
+<li><p><span>Foo / Bar</span></p></li>
+<li><p><span>Baz / Bim</span></p></li>
+</ul>
+```
+
diff --git a/test/command/8251.md b/test/command/8251.md
new file mode 100644
--- /dev/null
+++ b/test/command/8251.md
@@ -0,0 +1,13 @@
+```
+% pandoc -f native -t html
+Link ("",["", "", ""],[]) [Str "foo"] ("https://example.com","")
+^D
+<a href="https://example.com">foo</a>
+```
+
+```
+% pandoc -f native -t markdown
+Link ("",["", "", ""],[]) [Str "foo"] ("https://example.com","")
+^D
+[foo](https://example.com){}
+```
diff --git a/test/command/8254.md b/test/command/8254.md
new file mode 100644
--- /dev/null
+++ b/test/command/8254.md
@@ -0,0 +1,20 @@
+```
+% pandoc -t native
+Wow![@legras_michel_2010]
+^D
+[ Para
+    [ Str "Wow!"
+    , Cite
+        [ Citation
+            { citationId = "legras_michel_2010"
+            , citationPrefix = []
+            , citationSuffix = []
+            , citationMode = NormalCitation
+            , citationNoteNum = 2
+            , citationHash = 0
+            }
+        ]
+        [ Str "[@legras_michel_2010]" ]
+    ]
+]
+```
diff --git a/test/command/8256.md b/test/command/8256.md
new file mode 100644
--- /dev/null
+++ b/test/command/8256.md
@@ -0,0 +1,33 @@
+```
+% pandoc -t opendocument -s
+
+---
+title: |
+  This *is* \
+  a test
+author: Someone
+---
+
+Testing.
+^D
+<?xml version="1.0" encoding="utf-8" ?>
+<office:document-content xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" xmlns:style="urn:oasis:names:tc:opendocument:xmlns:style:1.0" xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0" xmlns:table="urn:oasis:names:tc:opendocument:xmlns:table:1.0" xmlns:draw="urn:oasis:names:tc:opendocument:xmlns:drawing:1.0" xmlns:fo="urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:meta="urn:oasis:names:tc:opendocument:xmlns:meta:1.0" xmlns:number="urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0" xmlns:svg="urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0" xmlns:chart="urn:oasis:names:tc:opendocument:xmlns:chart:1.0" xmlns:dr3d="urn:oasis:names:tc:opendocument:xmlns:dr3d:1.0" xmlns:math="http://www.w3.org/1998/Math/MathML" xmlns:form="urn:oasis:names:tc:opendocument:xmlns:form:1.0" xmlns:script="urn:oasis:names:tc:opendocument:xmlns:script:1.0" xmlns:ooo="http://openoffice.org/2004/office" xmlns:ooow="http://openoffice.org/2004/writer" xmlns:oooc="http://openoffice.org/2004/calc" xmlns:dom="http://www.w3.org/2001/xml-events" xmlns:xforms="http://www.w3.org/2002/xforms" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" office:version="1.3">
+  <office:font-face-decls>
+    <style:font-face style:name="Courier New" style:font-family-generic="modern" style:font-pitch="fixed" svg:font-family="'Courier New'" />
+  </office:font-face-decls>
+  <office:automatic-styles>
+    <style:style style:name="fr2" style:family="graphic" style:parent-style-name="Formula"><style:graphic-properties style:vertical-pos="middle" style:vertical-rel="text" style:horizontal-pos="center" style:horizontal-rel="paragraph-content" style:wrap="none" /></style:style>
+    <style:style style:name="fr1" style:family="graphic" style:parent-style-name="Formula"><style:graphic-properties style:vertical-pos="middle" style:vertical-rel="text" /></style:style>
+  </office:automatic-styles>
+<office:body>
+<office:text>
+<text:p text:style-name="Title">This
+<text:span text:style-name="Emphasis">is</text:span><text:line-break />a
+test</text:p>
+<text:p text:style-name="Author">Someone</text:p>
+<text:p text:style-name="Text_20_body">Testing.</text:p>
+</office:text>
+</office:body>
+</office:document-content>
+```
+
diff --git a/test/command/8257.md b/test/command/8257.md
new file mode 100644
--- /dev/null
+++ b/test/command/8257.md
@@ -0,0 +1,41 @@
+```
+% pandoc -f markdown -t html5
++------+-------+
+| Item | Price |
++======+=======+
+| Eggs | 5£    |
++------+-------+
+| Spam | 3£    |
++======+=======+
+| Sum  | 8£    |
++======+=======+
+^D
+<table style="width:21%;">
+<colgroup>
+<col style="width: 9%" />
+<col style="width: 11%" />
+</colgroup>
+<thead>
+<tr>
+<th>Item</th>
+<th>Price</th>
+</tr>
+</thead>
+<tbody>
+<tr>
+<td>Eggs</td>
+<td>5£</td>
+</tr>
+<tr>
+<td>Spam</td>
+<td>3£</td>
+</tr>
+</tbody><tfoot>
+<tr>
+<td>Sum</td>
+<td>8£</td>
+</tr>
+</tfoot>
+
+</table>
+```
diff --git a/test/command/8281.md b/test/command/8281.md
new file mode 100644
--- /dev/null
+++ b/test/command/8281.md
@@ -0,0 +1,15 @@
+```
+% pandoc -t html
+# Title
+
+test
+
+. . .
+
+test
+^D
+<h1 id="title">Title</h1>
+<p>test</p>
+<p>. . .</p>
+<p>test</p>
+```
diff --git a/test/command/8302.md b/test/command/8302.md
new file mode 100644
--- /dev/null
+++ b/test/command/8302.md
@@ -0,0 +1,6 @@
+```
+% pandoc -f org -t markdown
+some text cite:&long-2004-tecton-evolut
+^D
+some text @long-2004-tecton-evolut
+```
diff --git a/test/command/8307.md b/test/command/8307.md
new file mode 100644
--- /dev/null
+++ b/test/command/8307.md
@@ -0,0 +1,49 @@
+```
+% pandoc -t commonmark -f html
+<table>
+<tbody>
+<tr>
+<td title="this
+  
+
+breaks">hello</td>
+</tr>
+</tbody>
+</table>
+^D
+<table>
+<tbody>
+<tr>
+<td title="this
+  &#10;
+breaks">hello</td>
+</tr>
+</tbody>
+</table>
+```
+
+````
+% pandoc -t commonmark -f markdown
+``` {=html}
+<table>
+<tbody>
+<tr>
+<td title="this
+  
+
+breaks">hello</td>
+</tr>
+</tbody>
+</table>
+```
+^D
+<table>
+<tbody>
+<tr>
+<td title="this
+  &#10;
+breaks">hello</td>
+</tr>
+</tbody>
+</table>
+````
diff --git a/test/command/8344.md b/test/command/8344.md
new file mode 100644
--- /dev/null
+++ b/test/command/8344.md
@@ -0,0 +1,90 @@
+```
+% pandoc -t jats -s
+---
+title: |-
+  My\
+  document
+...
+
+# Section\
+with line break
+
+Paragraph\
+with line break
+
+--------
+A    B
+---  ---
+1\   3
+2    4
+
+*1\  5\
+2*   6
+
+     7
+--------
+
+^D
+<?xml version="1.0" encoding="utf-8" ?>
+<!DOCTYPE article PUBLIC "-//NLM//DTD JATS (Z39.96) Journal Archiving and Interchange DTD v1.2 20190208//EN"
+                  "JATS-archivearticle1.dtd">
+<article xmlns:mml="http://www.w3.org/1998/Math/MathML" xmlns:xlink="http://www.w3.org/1999/xlink" dtd-version="1.2" article-type="other">
+<front>
+<journal-meta>
+<journal-id></journal-id>
+<journal-title-group>
+</journal-title-group>
+<issn></issn>
+<publisher>
+<publisher-name></publisher-name>
+</publisher>
+</journal-meta>
+<article-meta>
+<title-group>
+<article-title>My<break/>document</article-title>
+</title-group>
+<permissions>
+</permissions>
+</article-meta>
+</front>
+<body>
+<sec id="section">
+  <title>Section<break/></title>
+  <p>with line break</p>
+  <p>Paragraph
+  with line break</p>
+  <table-wrap>
+    <table>
+      <colgroup>
+        <col width="7%" />
+        <col width="7%" />
+      </colgroup>
+      <thead>
+        <tr>
+          <th align="left">A</th>
+          <th align="left">B</th>
+        </tr>
+      </thead>
+      <tbody>
+        <tr>
+          <td align="left">1<break/>2</td>
+          <td align="left">3 4</td>
+        </tr>
+        <tr>
+          <td align="left"><italic>1
+          2</italic></td>
+          <td align="left">5<break/>6</td>
+        </tr>
+        <tr>
+          <td align="left"></td>
+          <td align="left">7</td>
+        </tr>
+      </tbody>
+    </table>
+  </table-wrap>
+</sec>
+</body>
+<back>
+</back>
+</article>
+```
diff --git a/test/command/8354.md b/test/command/8354.md
new file mode 100644
--- /dev/null
+++ b/test/command/8354.md
@@ -0,0 +1,38 @@
+```
+% pandoc -f markdown -t html --citeproc
+---
+title: test
+nocite: '[@*]'
+references:
+- author:
+  - family: Fekete
+    given: Jean-Daniel
+  - family: Freire
+    given: Juliana
+  DOI: 10.1109/MCG.2020.3006412
+  id: feketeExploringReproducibilityVisualization2020
+  ISSN: 1558-1756
+  issue: 5
+  issued: 2020-09
+  page: 108-119
+  source: IEEE Xplore
+  title: Exploring Reproducibility in Visualization
+  container-title: IEEE Computer Graphics and Applications
+  type: article-journal
+  volume: 40
+---
+
+## References
+^D
+<h2 class="unnumbered" id="references">References</h2>
+<div id="refs" class="references csl-bib-body hanging-indent"
+role="list">
+<div id="ref-feketeExploringReproducibilityVisualization2020"
+class="csl-entry" role="listitem">
+Fekete, Jean-Daniel, and Juliana Freire. 2020. <span>“Exploring
+Reproducibility in Visualization.”</span> <em>IEEE Computer Graphics and
+Applications</em> 40 (5): 108–19. <a
+href="https://doi.org/10.1109/MCG.2020.3006412">https://doi.org/10.1109/MCG.2020.3006412</a>.
+</div>
+</div>
+```
diff --git a/test/command/8364.md b/test/command/8364.md
new file mode 100644
--- /dev/null
+++ b/test/command/8364.md
@@ -0,0 +1,54 @@
+```
+% pandoc --citeproc -t jats -s
+---
+reference-section-title: Bibliography
+csl: command/apa.csl
+references:
+- author:
+  - family: Doe
+    given: John
+  id: test
+  issued:
+    date-parts:
+    - - 2006
+  title: Test
+  type: 'article-journal'
+  volume: 81
+---
+
+@test
+^D
+<?xml version="1.0" encoding="utf-8" ?>
+<!DOCTYPE article PUBLIC "-//NLM//DTD JATS (Z39.96) Journal Archiving and Interchange DTD v1.2 20190208//EN"
+                  "JATS-archivearticle1.dtd">
+<article xmlns:mml="http://www.w3.org/1998/Math/MathML" xmlns:xlink="http://www.w3.org/1999/xlink" dtd-version="1.2" article-type="other">
+<front>
+<journal-meta>
+<journal-id></journal-id>
+<journal-title-group>
+</journal-title-group>
+<issn></issn>
+<publisher>
+<publisher-name></publisher-name>
+</publisher>
+</journal-meta>
+<article-meta>
+<permissions>
+</permissions>
+</article-meta>
+</front>
+<body>
+<p>Doe (2006)</p>
+</body>
+<back>
+<ref-list>
+  <title>Bibliography</title>
+  <ref id="ref-test">
+    <mixed-citation>Doe, J. (2006). Test,
+    <italic>81</italic>.</mixed-citation>
+  </ref>
+</ref-list>
+</back>
+</article>
+
+```
diff --git a/test/command/8365.md b/test/command/8365.md
new file mode 100644
--- /dev/null
+++ b/test/command/8365.md
@@ -0,0 +1,50 @@
+```
+% pandoc -f jats -t native -s
+<?xml version="1.0" encoding="utf-8" ?>
+<!DOCTYPE article PUBLIC "-//NLM//DTD JATS (Z39.96) Journal Archiving and Interchange DTD v1.2 20190208//EN"
+                  "JATS-archivearticle1.dtd">
+<article xmlns:mml="http://www.w3.org/1998/Math/MathML" xmlns:xlink="http://www.w3.org/1999/xlink" dtd-version="1.2" article-type="other">
+<front>
+<journal-meta>
+<journal-id></journal-id>
+<journal-title-group>
+</journal-title-group>
+<issn></issn>
+<publisher>
+<publisher-name></publisher-name>
+</publisher>
+</journal-meta>
+<article-meta>
+<permissions>
+</permissions>
+</article-meta>
+</front>
+<body>
+<p>Doe (2006)</p>
+</body>
+<back>
+<ref-list>
+  <title>Bibliography</title>
+  <ref id="ref-test">
+    <mixed-citation>Doe, J. (2006). Test,
+    <italic>81</italic>.</mixed-citation>
+  </ref>
+</ref-list>
+</back>
+</article>
+^D
+Pandoc
+  Meta
+    { unMeta =
+        fromList
+          [ ( "references"
+            , MetaList
+                [ MetaMap (fromList [ ( "id" , MetaString "test" ) ]) ]
+            )
+          ]
+    }
+  [ Para [ Str "Doe" , Space , Str "(2006)" ]
+  , Header 1 ( "" , [] , [] ) [ Str "Bibliography" ]
+  , Div ( "refs" , [] , [] ) []
+  ]
+```
diff --git a/test/command/8380.md b/test/command/8380.md
new file mode 100644
--- /dev/null
+++ b/test/command/8380.md
@@ -0,0 +1,31 @@
+```
+% pandoc -f man -t rst
+LC_*
+^D
+LC\_\*
+```
+
+These examples of things that don't require escaping are taken
+from the RST documentation:
+
+```
+% pandoc -f native -t rst
+[Para [Str "2*x a**b O(N**2) e**(x*y) f(x)*f(y) a|b"]
+,Para [Str "a**b O(N**2) e**(x*y) f(x)*f(y)"]
+]
+^D
+2*x a**b O(N**2) e**(x*y) f(x)*f(y) a|b
+
+a**b O(N**2) e**(x*y) f(x)*f(y)
+```
+
+These examples of things that do require escaping are taken
+from the RST documentation:
+
+```
+% pandoc -f native -t rst
+Str "*4, class_, *args, **kwargs, `TeX-quoted', *ML, *.txt"
+^D
+\*4, class\_, \*args, \**kwargs, \`TeX-quoted', \*ML, \*.txt
+```
+
diff --git a/test/command/8402.md b/test/command/8402.md
new file mode 100644
--- /dev/null
+++ b/test/command/8402.md
@@ -0,0 +1,52 @@
+```
+% pandoc --toc -s -t markdown
+::: {.cell .markdown id="6u8qXoeFGdqt"}
+# Summary
+> Expand to see summary
+
+## Overview and Explanation
+:::
+
+# Details
+
+## inner 1
+text
+
+## inner 2
+
+### inner inner 1
+
+## inner 3
+text
+^D
+- [Summary](#summary){#toc-summary}
+  - [Overview and
+    Explanation](#overview-and-explanation){#toc-overview-and-explanation}
+- [Details](#details){#toc-details}
+  - [inner 1](#inner-1){#toc-inner-1}
+  - [inner 2](#inner-2){#toc-inner-2}
+    - [inner inner 1](#inner-inner-1){#toc-inner-inner-1}
+  - [inner 3](#inner-3){#toc-inner-3}
+
+::: {#6u8qXoeFGdqt .cell .markdown}
+# Summary
+
+> Expand to see summary
+
+## Overview and Explanation
+:::
+
+# Details
+
+## inner 1
+
+text
+
+## inner 2
+
+### inner inner 1
+
+## inner 3
+
+text
+```
diff --git a/test/command/8437.md b/test/command/8437.md
new file mode 100644
--- /dev/null
+++ b/test/command/8437.md
@@ -0,0 +1,44 @@
+```
+% pandoc -f markdown -t asciidoc
+[![alt](https://img.shields.io/badge/License-Apache%202.0-blue.svg "title")](http://www.apache.org/licenses/LICENSE-2.0)
+^D
+http://www.apache.org/licenses/LICENSE-2.0[image:https://img.shields.io/badge/License-Apache%202.0-blue.svg[alt,title="title"]]
+```
+
+```
+% pandoc -f markdown -t docbook
+[![alt](https://img.shields.io/badge/License-Apache%202.0-blue.svg "title")](http://www.apache.org/licenses/LICENSE-2.0)
+^D
+<para>
+  <link xlink:href="http://www.apache.org/licenses/LICENSE-2.0"><inlinemediaobject>
+    <imageobject>
+      <objectinfo>
+        <title>title</title>
+      </objectinfo>
+      <imagedata fileref="https://img.shields.io/badge/License-Apache%202.0-blue.svg" />
+    </imageobject>
+    <textobject>
+      <phrase>alt</phrase>
+    </textobject>
+  </inlinemediaobject></link>
+</para>
+```
+
+```
+% pandoc -f docbook -t markdown
+<para>
+  <link xlink:href="http://www.apache.org/licenses/LICENSE-2.0"><inlinemediaobject>
+    <imageobject>
+      <objectinfo>
+        <title>title</title>
+      </objectinfo>
+      <imagedata fileref="https://img.shields.io/badge/License-Apache%202.0-blue.svg" />
+    </imageobject>
+    <textobject>
+      <phrase>alt</phrase>
+    </textobject>
+  </inlinemediaobject></link>
+</para>
+^D
+[![alt](https://img.shields.io/badge/License-Apache%202.0-blue.svg "title")](http://www.apache.org/licenses/LICENSE-2.0)
+```
diff --git a/test/command/8486.md b/test/command/8486.md
new file mode 100644
--- /dev/null
+++ b/test/command/8486.md
@@ -0,0 +1,55 @@
+# Unnumbered and unlisted headings in ConTeXt
+
+```
+% pandoc --to=context
+# Preface {.unlisted -}
+
+Nullam rutrum.
+
+# Introduction
+
+Nullam eu ante vel est convallis dignissim.
+
+# Methods
+
+Sed diam. Nulla posuere. Praesent fermentum tempor tellus. Nam
+vestibulum accumsan nisl. Nam vestibulum accumsan nisl.
+
+# References {-}
+^D
+\startsubject[title={Preface},reference={preface},number=no,incrementnumber=no]
+
+Nullam rutrum.
+
+\stopsubject
+
+\startsectionlevel[title={Introduction},reference={introduction}]
+
+Nullam eu ante vel est convallis dignissim.
+
+\stopsectionlevel
+
+\startsectionlevel[title={Methods},reference={methods}]
+
+Sed diam. Nulla posuere. Praesent fermentum tempor tellus. Nam
+vestibulum accumsan nisl. Nam vestibulum accumsan nisl.
+
+\stopsectionlevel
+
+\startsectionlevel[title={References},reference={references},number=no,incrementnumber=no]
+
+\stopsectionlevel
+```
+
+## Semantic Headings with `--top-level-division`
+```
+% pandoc --to=context --top-level-division=chapter
+# Bibliography {-}
+None
+^D
+\startchapter[title={Bibliography},reference={bibliography},number=no,incrementnumber=no]
+
+None
+
+\stopchapter
+```
diff --git a/test/command/8487.md b/test/command/8487.md
new file mode 100644
--- /dev/null
+++ b/test/command/8487.md
@@ -0,0 +1,14 @@
+```
+% pandoc -f textile -t native
+p>.
+
+p=. Links:
+^D
+[ Div
+    ( "" , [] , [ ( "style" , "text-align:right;" ) ] )
+    [ Para [] ]
+, Div
+    ( "" , [] , [ ( "style" , "text-align:center;" ) ] )
+    [ Para [ Str "Links:" ] ]
+]
+```
diff --git a/test/command/8504.md b/test/command/8504.md
new file mode 100644
--- /dev/null
+++ b/test/command/8504.md
@@ -0,0 +1,90 @@
+```
+% pandoc -f markdown -s -t biblatex
+---
+references:
+- id: Larsson_2016
+  author:
+    - family: Larsson
+      given: Johan
+  citation-key: Larsson_2016
+  issued:
+    - year: 2016
+  medium: Windows
+  title: 'qualpalr: Automatic Generation of Qualitative Color Palettes'
+  type: software
+  URL: https://cran.r-project.org/package=qualpalr
+  version: 0.3.1
+...
+^D
+@software{Larsson_2016,
+  author = {Larsson, Johan},
+  title = {Qualpalr: {Automatic} {Generation} of {Qualitative} {Color}
+    {Palettes}},
+  version = {0.3.1},
+  date = {2016},
+  url = {https://cran.r-project.org/package=qualpalr}
+}
+```
+
+```
+% pandoc -f markdown -s -t bibtex
+---
+references:
+- id: Larsson_2016
+  author:
+    - family: Larsson
+      given: Johan
+  citation-key: Larsson_2016
+  issued:
+    - year: 2016
+  medium: Windows
+  title: 'qualpalr: Automatic Generation of Qualitative Color Palettes'
+  type: software
+  URL: https://cran.r-project.org/package=qualpalr
+  version: 0.3.1
+...
+^D
+@misc{Larsson_2016,
+  author = {Larsson, Johan},
+  title = {Qualpalr: {Automatic} {Generation} of {Qualitative} {Color}
+    {Palettes}},
+  year = {2016},
+  url = {https://cran.r-project.org/package=qualpalr}
+}
+```
+
+```
+% pandoc -f biblatex -s -t csljson
+@software{Larsson_2016,
+  author = {Larsson, Johan},
+  title = {Qualpalr: {Automatic} {Generation} of {Qualitative} {Color}
+    {Palettes}},
+  version = {0.3.1},
+  date = {2016},
+  url = {https://cran.r-project.org/package=qualpalr}
+}
+^D
+[
+  {
+    "URL": "https://cran.r-project.org/package=qualpalr",
+    "author": [
+      {
+        "family": "Larsson",
+        "given": "Johan"
+      }
+    ],
+    "id": "Larsson_2016",
+    "issued": {
+      "date-parts": [
+        [
+          2016
+        ]
+      ]
+    },
+    "title": "Qualpalr: Automatic Generation of Qualitative Color Palettes",
+    "title-short": "Qualpalr",
+    "type": "software",
+    "version": "0.3.1"
+  }
+]
+```
diff --git a/test/command/8508.md b/test/command/8508.md
new file mode 100644
--- /dev/null
+++ b/test/command/8508.md
@@ -0,0 +1,20 @@
+```
+% pandoc -t man
+SEE ALSO
+========
+
+* [Milk](https://en.wikipedia.org/wiki/Milk)
+* [EBNF](https://en.wikipedia.org/wiki/Extended_Backus–Naur_form)
+^D
+.SH SEE ALSO
+.IP \(bu 2
+\c
+.UR https://en.wikipedia.org/wiki/Milk
+Milk
+.UE \c
+.IP \(bu 2
+\c
+.UR https://en.wikipedia.org/wiki/Extended_Backus–Naur_form
+EBNF
+.UE \c
+```
diff --git a/test/command/8511.md b/test/command/8511.md
new file mode 100644
--- /dev/null
+++ b/test/command/8511.md
@@ -0,0 +1,16 @@
+# Conversion of icon-like sequences followed by alphanum char
+## to Jira
+```
+% pandoc -t jira
+:P :P_ :PA :Pa :P2
+^D
+\:P \:P\_ :PA :Pa :P2
+```
+
+## from jira
+```
+% pandoc -f jira -t markdown
+\:PA
+^D
+\\:PA
+```
diff --git a/test/command/8513.md b/test/command/8513.md
new file mode 100644
--- /dev/null
+++ b/test/command/8513.md
@@ -0,0 +1,27 @@
+# Round-tripping tags in org
+```
+% pandoc --from org --to org --columns=72
+* Header with tag   :tag:
+^D
+* Header with tag                                                  :tag:
+:PROPERTIES:
+:CUSTOM_ID: header-with-tag
+:END:
+```
+
+Multiple tags
+```
+% pandoc --from org-auto_identifiers --to org --columns=78
+* Header with two tags                                           :first:second:
+^D
+* Header with two tags                                          :first:second:
+```
+
+Check that long headings work with tags
+
+```
+% pandoc --from org-auto_identifiers --to org --columns=40
+* Header with tag and more words which are not that interesting   :tag:
+^D
+* Header with tag and more words which are not that interesting :tag:
+```
diff --git a/test/command/853.md b/test/command/853.md
--- a/test/command/853.md
+++ b/test/command/853.md
@@ -7,11 +7,14 @@
 .. [CIT2002] This is the citation.  It's just like a footnote,
    except the label is textual.
 ^D
-<p>Here is a citation reference: <a href="#CIT2002" class="citation">[CIT2002]</a>.</p>
+<p>Here is a citation reference: <a href="#CIT2002"
+class="citation">[CIT2002]</a>.</p>
 <div id="citations">
 <dl>
 <dt><span id="CIT2002" class="citation-label">CIT2002</span></dt>
-<dd><p>This is the citation. It's just like a footnote, except the label is textual.</p>
+<dd>
+<p>This is the citation. It's just like a footnote, except the label is
+textual.</p>
 </dd>
 </dl>
 </div>
diff --git a/test/command/8534.md b/test/command/8534.md
new file mode 100644
--- /dev/null
+++ b/test/command/8534.md
@@ -0,0 +1,11 @@
+```
+% pandoc -f html -t texinfo
+<html>
+foo <code>bar <var>baz</var> bar</code> foo
+</html>
+^D
+@node Top
+@top Top
+
+foo @code{bar }@code{@var{baz}}@code{ bar} foo
+```
diff --git a/test/command/8573.md b/test/command/8573.md
new file mode 100644
--- /dev/null
+++ b/test/command/8573.md
@@ -0,0 +1,7 @@
+```
+% pandoc -f latex -t plain
+\newenvironment{myenv}[1]{Open#1}{Close}
+\begin{myenv}{x}Hello\end{myenv}
+^D
+OpenxHelloClose
+```
diff --git a/test/command/8611.md b/test/command/8611.md
new file mode 100644
--- /dev/null
+++ b/test/command/8611.md
@@ -0,0 +1,34 @@
+```
+% pandoc -f markdown -s -t bibtex
+---
+nocite: "[@*]"
+references:
+- id: mcdowell:why
+  title: |
+    Why is Sellars's Essay Called "Empiricism and the Philosophy of Mind"?
+  author:
+  - family: McDowell
+    given: John
+  journal: Proceedings of the Aristotelian Society
+  type: chapter
+  container-title: 'Empiricism, Perceptual Knowledge, Normativity, and Realism: Essays on Wilfrid Sellars'
+  editor:
+    - family: deVries
+      given: Willem A.
+  issued: 2009
+  publisher: Oxford University Press
+  publisher-place: Oxford
+...
+^D
+@incollection{mcdowell:why,
+  author = {McDowell, John},
+  editor = {deVries, Willem A.},
+  publisher = {Oxford University Press},
+  title = {Why Is {Sellars’s} {Essay} {Called} “{Empiricism} and the
+    {Philosophy} of {Mind}”?},
+  booktitle = {Empiricism, Perceptual Knowledge, Normativity, and
+    Realism: Essays on Wilfrid Sellars},
+  year = {2009},
+  address = {Oxford}
+}
+```
diff --git a/test/command/8638.md b/test/command/8638.md
new file mode 100644
--- /dev/null
+++ b/test/command/8638.md
@@ -0,0 +1,22 @@
+# Beamer tables must not use longtable footer
+```
+% pandoc -t beamer
+| fruit   | price |
+|---------|------:|
+| apple   | 2.05  |
+| oranges | 4.25  |
+^D
+\begin{frame}
+{\def\LTcaptype{none} % do not increment counter
+\begin{longtable}[]{@{}lr@{}}
+\toprule\noalign{}
+fruit & price \\
+\midrule\noalign{}
+\endhead
+apple & 2.05 \\
+oranges & 4.25 \\
+\bottomrule\noalign{}
+\end{longtable}
+}
+\end{frame}
+```
diff --git a/test/command/8652.md b/test/command/8652.md
new file mode 100644
--- /dev/null
+++ b/test/command/8652.md
@@ -0,0 +1,28 @@
+```
+% pandoc -t native
+My text^[My note]isnot^[Text]
+^D
+[ Para
+    [ Str "My"
+    , Space
+    , Str "text"
+    , Note [ Para [ Str "My" , Space , Str "note" ] ]
+    , Str "isnot"
+    , Note [ Para [ Str "Text" ] ]
+    ]
+]
+
+```
+
+```
+% pandoc -t native
+^[note1]test^[note2]
+^D
+[ Para
+    [ Note [ Para [ Str "note1" ] ]
+    , Str "test"
+    , Note [ Para [ Str "note2" ] ]
+    ]
+]
+
+```
diff --git a/test/command/8653.md b/test/command/8653.md
new file mode 100644
--- /dev/null
+++ b/test/command/8653.md
@@ -0,0 +1,23 @@
+```
+% pandoc -f rst -t native
+.. role:: py:class(emphasis)
+
+:py:class:`foo`
+^D
+[ Para [ Emph [ Str "foo" ] ] ]
+```
+
+```
+% pandoc -f rst -t native
+:py:class:`foo`
+^D
+[ Para
+    [ Code
+        ( ""
+        , [ "interpreted-text" ]
+        , [ ( "role" , "py:class" ) ]
+        )
+        "foo"
+    ]
+]
+```
diff --git a/test/command/8659.md b/test/command/8659.md
new file mode 100644
--- /dev/null
+++ b/test/command/8659.md
@@ -0,0 +1,54 @@
+# A single pipe is parsed as an empty table
+```
+% pandoc -f org -t html
+|
+^D
+<table>
+<tbody>
+<tr>
+</tr>
+</tbody>
+</table>
+```
+# Accepts an empty org table within a grid table cell
+
+The misaligned pipe in the first row is treated as an empty table.
+
+```
+% pandoc -f org -t html
++-----+-----+-----+-----------+
+|     |     |     |         |
++:====+=====+====:+==========:+
+| a   |  b  | c   | d         |
++-----+-----+-----+-----------+
+^D
+<table style="width:42%;">
+<colgroup>
+<col style="width: 8%" />
+<col style="width: 8%" />
+<col style="width: 8%" />
+<col style="width: 16%" />
+</colgroup>
+<thead>
+<tr>
+<th style="text-align: left;"></th>
+<th></th>
+<th style="text-align: right;"></th>
+<th style="text-align: right;"><table>
+<tbody>
+<tr>
+</tr>
+</tbody>
+</table></th>
+</tr>
+</thead>
+<tbody>
+<tr>
+<td style="text-align: left;">a</td>
+<td>b</td>
+<td style="text-align: right;">c</td>
+<td style="text-align: right;">d</td>
+</tr>
+</tbody>
+</table>
+```
diff --git a/test/command/8661.md b/test/command/8661.md
new file mode 100644
--- /dev/null
+++ b/test/command/8661.md
@@ -0,0 +1,9 @@
+```
+% pandoc -f tsv -t gfm
+a	b	c
+		6
+^D
+| a   | b   | c   |
+|-----|-----|-----|
+|     |     | 6   |
+```
diff --git a/test/command/8665.md b/test/command/8665.md
new file mode 100644
--- /dev/null
+++ b/test/command/8665.md
@@ -0,0 +1,29 @@
+```
+% pandoc -f docbook -t asciidoc
+<informaltable frame="all" rowsep="1" colsep="1">
+    <tgroup cols="1">
+        <thead>
+            <row>
+                <entry align="left" valign="top">h1</entry>
+                <entry align="left" valign="top">h2</entry>
+            </row>
+        </thead>
+        <tbody>
+            <row>
+                <entry align="left" valign="top">
+                    <simpara>!@#$%^&amp;*(){}|~?+-',."&lt;&gt;[]\`</simpara>
+                </entry>
+                <entry align="left" valign="top">
+                    <simpara>col 2</simpara>
+                </entry>
+            </row>
+        </tbody>
+    </tgroup>
+</informaltable>
+^D
+[cols=",",options="header",]
+|===
+<|h1 <|h2
+<|!@++#++$%^&++*++()++{++}{vbar}~?{plus}-',."++<>[]\`++ <|col 2
+|===
+```
diff --git a/test/command/8666.md b/test/command/8666.md
new file mode 100644
--- /dev/null
+++ b/test/command/8666.md
@@ -0,0 +1,40 @@
+```
+% pandoc -f docbook -t native
+<formalpara xml:id="my_code_id">
+<title>Code title</title>
+<para>
+<programlisting language="bash" linenumbering="unnumbered">echo "hello world!"</programlisting>
+</para>
+</formalpara>
+<example xml:id="my_example_id">
+<title>Example title</title>
+<simpara>example content</simpara>
+</example>
+<sidebar xml:id="my_sidebar_id">
+<title>Sidebar title</title>
+<simpara>sidebar content</simpara>
+</sidebar>
+^D
+[ Div
+    ( "my_code_id" , [ "formalpara" ] , [] )
+    [ Div
+        ( "" , [ "title" ] , [] )
+        [ Plain [ Str "Code" , Space , Str "title" ] ]
+    , CodeBlock ( "" , [ "bash" ] , [] ) "echo \"hello world!\""
+    ]
+, Div
+    ( "my_example_id" , [ "example" ] , [] )
+    [ Div
+        ( "" , [ "title" ] , [] )
+        [ Plain [ Str "Example" , Space , Str "title" ] ]
+    , Para [ Str "example" , Space , Str "content" ]
+    ]
+, Div
+    ( "my_sidebar_id" , [ "sidebar" ] , [] )
+    [ Div
+        ( "" , [ "title" ] , [] )
+        [ Plain [ Str "Sidebar" , Space , Str "title" ] ]
+    , Para [ Str "sidebar" , Space , Str "content" ]
+    ]
+]
+```
diff --git a/test/command/8681.md b/test/command/8681.md
new file mode 100644
--- /dev/null
+++ b/test/command/8681.md
@@ -0,0 +1,14 @@
+# Include Jira panel title in resulting div
+```
+% pandoc -f jira -t html
+{panel:title=This is the title|titleBGColor=#cccccc|bgColor=#eeeeee}
+Panel content
+{panel}
+^D
+<div class="panel" data-titleBGColor="#cccccc" data-bgColor="#eeeeee">
+<div class="panelheader">
+<strong>This is the title</strong>
+</div>
+<p>Panel content</p>
+</div>
+```
diff --git a/test/command/8689.md b/test/command/8689.md
new file mode 100644
--- /dev/null
+++ b/test/command/8689.md
@@ -0,0 +1,12 @@
+# Org figures should be rendered implicit figures
+
+```
+% pandoc -f org -t markdown+implicit_figures
+#+label: fig:bsdd-graphql-voyager-orig-detail
+#+caption: Original bSDD GraphQL Schema: Detail of Classification and ClassificationProperty
+[[./Classification-ClassificationProperty.png]]
+^D
+![Original bSDD GraphQL Schema: Detail of Classification and
+ClassificationProperty](./Classification-ClassificationProperty.png){#fig:bsdd-graphql-voyager-orig-detail}
+
+```
diff --git a/test/command/8711.md b/test/command/8711.md
new file mode 100644
--- /dev/null
+++ b/test/command/8711.md
@@ -0,0 +1,118 @@
+```
+% pandoc -f html-native_spans -t native
+<table>
+<tr>
+<td>
+  <p><span class="foo">a</span> <span class="bar">b</span></p>
+</td>
+</tr>
+</table>
+^D
+[ Table
+    ( "" , [] , [] )
+    (Caption Nothing [])
+    [ ( AlignDefault , ColWidthDefault ) ]
+    (TableHead ( "" , [] , [] ) [])
+    [ TableBody
+        ( "" , [] , [] )
+        (RowHeadColumns 0)
+        []
+        [ Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Para [ Str "a" , Space , Str "b" ] ]
+            ]
+        ]
+    ]
+    (TableFoot ( "" , [] , [] ) [])
+]
+
+```
+
+```
+% pandoc -f html-native_spans+raw_html -t native
+<table>
+<tr>
+<td>
+  <p><span class="foo">a</span> <span class="bar">b</span></p>
+</td>
+</tr>
+</table>
+^D
+[ Table
+    ( "" , [] , [] )
+    (Caption Nothing [])
+    [ ( AlignDefault , ColWidthDefault ) ]
+    (TableHead ( "" , [] , [] ) [])
+    [ TableBody
+        ( "" , [] , [] )
+        (RowHeadColumns 0)
+        []
+        [ Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Para
+                    [ RawInline (Format "html") "<span class=\"foo\">"
+                    , Str "a"
+                    , RawInline (Format "html") "</span>"
+                    , Space
+                    , RawInline (Format "html") "<span class=\"bar\">"
+                    , Str "b"
+                    , RawInline (Format "html") "</span>"
+                    ]
+                ]
+            ]
+        ]
+    ]
+    (TableFoot ( "" , [] , [] ) [])
+]
+
+```
+
+```
+% pandoc -f html -t native
+<table>
+<tr>
+<td>
+  <p><span class="foo">a</span> <span class="bar">b</span></p>
+</td>
+</tr>
+</table>
+^D
+[ Table
+    ( "" , [] , [] )
+    (Caption Nothing [])
+    [ ( AlignDefault , ColWidthDefault ) ]
+    (TableHead ( "" , [] , [] ) [])
+    [ TableBody
+        ( "" , [] , [] )
+        (RowHeadColumns 0)
+        []
+        [ Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Para
+                    [ Span ( "" , [ "foo" ] , [] ) [ Str "a" ]
+                    , Space
+                    , Span ( "" , [ "bar" ] , [] ) [ Str "b" ]
+                    ]
+                ]
+            ]
+        ]
+    ]
+    (TableFoot ( "" , [] , [] ) [])
+]
+
+```
diff --git a/test/command/8738.md b/test/command/8738.md
new file mode 100644
--- /dev/null
+++ b/test/command/8738.md
@@ -0,0 +1,6 @@
+```
+% pandoc -f native -t mediawiki
+[Link ("",[],[]) [Link ("",[],[]) [Str "test"] ("https://bar.example.com",""),Str "Test"] ("https://foo.example.com","")]
+^D
+[https://foo.example.com <span>test</span>Test]
+```
diff --git a/test/command/8745.md b/test/command/8745.md
new file mode 100644
--- /dev/null
+++ b/test/command/8745.md
@@ -0,0 +1,52 @@
+# Alt text on images
+
+```
+% pandoc -f latex -t native
+\documentclass[12pt]{article}
+\usepackage{graphicx}
+\begin{document}
+Sample text
+\begin{figure}[ht]
+    \includegraphics[alt={Upside down painting},width=0.5\textwidth]{New_York_City_I.jpg}
+    \caption{New York City by Piet Mondrian (Wikipedia)}
+    \label{fig:Mondrian}
+\end{figure}
+\includegraphics[alt={Face of a mandrill}]{mandrill.jpg}
+\end{document}
+^D
+[ Para [ Str "Sample" , Space , Str "text" ]
+, Figure
+    ( "fig:Mondrian" , [] , [ ( "latex-placement" , "ht" ) ] )
+    (Caption
+       Nothing
+       [ Plain
+           [ Str "New"
+           , Space
+           , Str "York"
+           , Space
+           , Str "City"
+           , Space
+           , Str "by"
+           , Space
+           , Str "Piet"
+           , Space
+           , Str "Mondrian"
+           , Space
+           , Str "(Wikipedia)"
+           ]
+       ])
+    [ Para
+        [ Image
+            ( "" , [] , [ ( "width" , "50%" ) ] )
+            [ Str "Upside down painting" ]
+            ( "New_York_City_I.jpg" , "" )
+        ]
+    ]
+, Para
+    [ Image
+        ( "" , [] , [] )
+        [ Str "Face of a mandrill" ]
+        ( "mandrill.jpg" , "" )
+    ]
+]
+```
diff --git a/test/command/8764.md b/test/command/8764.md
new file mode 100644
--- /dev/null
+++ b/test/command/8764.md
@@ -0,0 +1,50 @@
+```
+% pandoc -f html -t opendocument
+<table>
+  <tbody>
+    <tr>
+      <th>Header</th>
+      <td>Normal cell (column 2)</td>
+      <td>Normal cell (column 3)</td>
+    </tr>
+    <tr>
+      <td>Normal cell (column 1)</td>
+      <td>Normal cell (column 2)</td>
+      <td>Normal cell (column 3)</td>
+    </tr>
+  </tbody>
+</table>
+^D
+<table:table table:name="Table1" table:style-name="Table1">
+  <table:table-column table:style-name="Table1.A" />
+  <table:table-column table:style-name="Table1.B" />
+  <table:table-column table:style-name="Table1.C" />
+  <table:table-row>
+    <table:table-cell table:style-name="TableRowCell" office:value-type="string">
+      <text:p text:style-name="Table_20_Contents">Header</text:p>
+    </table:table-cell>
+    <table:table-cell table:style-name="TableRowCell" office:value-type="string">
+      <text:p text:style-name="Table_20_Contents">Normal cell (column
+      2)</text:p>
+    </table:table-cell>
+    <table:table-cell table:style-name="TableRowCell" office:value-type="string">
+      <text:p text:style-name="Table_20_Contents">Normal cell (column
+      3)</text:p>
+    </table:table-cell>
+  </table:table-row>
+  <table:table-row>
+    <table:table-cell table:style-name="TableRowCell" office:value-type="string">
+      <text:p text:style-name="Table_20_Contents">Normal cell (column
+      1)</text:p>
+    </table:table-cell>
+    <table:table-cell table:style-name="TableRowCell" office:value-type="string">
+      <text:p text:style-name="Table_20_Contents">Normal cell (column
+      2)</text:p>
+    </table:table-cell>
+    <table:table-cell table:style-name="TableRowCell" office:value-type="string">
+      <text:p text:style-name="Table_20_Contents">Normal cell (column
+      3)</text:p>
+    </table:table-cell>
+  </table:table-row>
+</table:table>
+```
diff --git a/test/command/8770-block.md b/test/command/8770-block.md
new file mode 100644
--- /dev/null
+++ b/test/command/8770-block.md
@@ -0,0 +1,75 @@
+```
+% pandoc -t html5 --reference-location=block
+# Section 1
+
+hello[^1]
+
+: Sample table.[^2]
+
+-----------
+ Fruit[^3]
+-----------
+ Bans[^4]
+-----------
+
+# Section 2
+
+dolly[^5]
+
+[^1]: doc footnote
+[^2]: caption footnote
+[^3]: header footnote
+[^4]: table cell footnote
+[^5]: doc footnote
+^D
+<h1 id="section-1">Section 1</h1>
+<p>hello<a href="#fn1" class="footnote-ref" id="fnref1"
+role="doc-noteref"><sup>1</sup></a></p>
+<aside id="footnotes" class="footnotes footnotes-end-of-block"
+role="doc-footnote">
+<ol>
+<li id="fn1"><p>doc footnote<a href="#fnref1" class="footnote-back"
+role="doc-backlink">↩︎</a></p></li>
+</ol>
+</aside>
+<table style="width:17%;">
+<caption>Sample table.<a href="#fn2" class="footnote-ref" id="fnref2"
+role="doc-noteref"><sup>2</sup></a></caption>
+<colgroup>
+<col style="width: 16%" />
+</colgroup>
+<thead>
+<tr>
+<th style="text-align: center;">Fruit<a href="#fn3" class="footnote-ref"
+id="fnref3" role="doc-noteref"><sup>3</sup></a></th>
+</tr>
+</thead>
+<tbody>
+<tr>
+<td style="text-align: center;">Bans<a href="#fn4" class="footnote-ref"
+id="fnref4" role="doc-noteref"><sup>4</sup></a></td>
+</tr>
+</tbody>
+</table>
+<aside id="footnotes-2" class="footnotes footnotes-end-of-block"
+role="doc-footnote">
+<ol start="2">
+<li id="fn2"><p>caption footnote<a href="#fnref2" class="footnote-back"
+role="doc-backlink">↩︎</a></p></li>
+<li id="fn3"><p>header footnote<a href="#fnref3" class="footnote-back"
+role="doc-backlink">↩︎</a></p></li>
+<li id="fn4"><p>table cell footnote<a href="#fnref4"
+class="footnote-back" role="doc-backlink">↩︎</a></p></li>
+</ol>
+</aside>
+<h1 id="section-2">Section 2</h1>
+<p>dolly<a href="#fn5" class="footnote-ref" id="fnref5"
+role="doc-noteref"><sup>5</sup></a></p>
+<aside id="footnotes-3" class="footnotes footnotes-end-of-block"
+role="doc-footnote">
+<ol start="5">
+<li id="fn5"><p>doc footnote<a href="#fnref5" class="footnote-back"
+role="doc-backlink">↩︎</a></p></li>
+</ol>
+</aside>
+```
diff --git a/test/command/8770-document.md b/test/command/8770-document.md
new file mode 100644
--- /dev/null
+++ b/test/command/8770-document.md
@@ -0,0 +1,66 @@
+```
+% pandoc -t html5 --reference-location=document
+# Section 1
+
+hello[^1]
+
+: Sample table.[^2]
+
+-----------
+ Fruit[^3]
+-----------
+ Bans[^4]
+-----------
+
+# Section 2
+
+dolly[^5]
+
+[^1]: doc footnote
+[^2]: caption footnote
+[^3]: header footnote
+[^4]: table cell footnote
+[^5]: doc footnote
+^D
+<h1 id="section-1">Section 1</h1>
+<p>hello<a href="#fn1" class="footnote-ref" id="fnref1"
+role="doc-noteref"><sup>1</sup></a></p>
+<table style="width:17%;">
+<caption>Sample table.<a href="#fn2" class="footnote-ref" id="fnref2"
+role="doc-noteref"><sup>2</sup></a></caption>
+<colgroup>
+<col style="width: 16%" />
+</colgroup>
+<thead>
+<tr>
+<th style="text-align: center;">Fruit<a href="#fn3" class="footnote-ref"
+id="fnref3" role="doc-noteref"><sup>3</sup></a></th>
+</tr>
+</thead>
+<tbody>
+<tr>
+<td style="text-align: center;">Bans<a href="#fn4" class="footnote-ref"
+id="fnref4" role="doc-noteref"><sup>4</sup></a></td>
+</tr>
+</tbody>
+</table>
+<h1 id="section-2">Section 2</h1>
+<p>dolly<a href="#fn5" class="footnote-ref" id="fnref5"
+role="doc-noteref"><sup>5</sup></a></p>
+<section id="footnotes" class="footnotes footnotes-end-of-document"
+role="doc-endnotes">
+<hr />
+<ol>
+<li id="fn1"><p>doc footnote<a href="#fnref1" class="footnote-back"
+role="doc-backlink">↩︎</a></p></li>
+<li id="fn2"><p>caption footnote<a href="#fnref2" class="footnote-back"
+role="doc-backlink">↩︎</a></p></li>
+<li id="fn3"><p>header footnote<a href="#fnref3" class="footnote-back"
+role="doc-backlink">↩︎</a></p></li>
+<li id="fn4"><p>table cell footnote<a href="#fnref4"
+class="footnote-back" role="doc-backlink">↩︎</a></p></li>
+<li id="fn5"><p>doc footnote<a href="#fnref5" class="footnote-back"
+role="doc-backlink">↩︎</a></p></li>
+</ol>
+</section>
+```
diff --git a/test/command/8770-section.md b/test/command/8770-section.md
new file mode 100644
--- /dev/null
+++ b/test/command/8770-section.md
@@ -0,0 +1,72 @@
+```
+% pandoc -t html5 --reference-location=section
+# Section 1
+
+hello[^1]
+
+: Sample table.[^2]
+
+-----------
+ Fruit[^3]
+-----------
+ Bans[^4]
+-----------
+
+# Section 2
+
+dolly[^5]
+
+[^1]: doc footnote
+[^2]: caption footnote
+[^3]: header footnote
+[^4]: table cell footnote
+[^5]: doc footnote
+^D
+<h1 id="section-1">Section 1</h1>
+<p>hello<a href="#fn1" class="footnote-ref" id="fnref1"
+role="doc-noteref"><sup>1</sup></a></p>
+<table style="width:17%;">
+<caption>Sample table.<a href="#fn2" class="footnote-ref" id="fnref2"
+role="doc-noteref"><sup>2</sup></a></caption>
+<colgroup>
+<col style="width: 16%" />
+</colgroup>
+<thead>
+<tr>
+<th style="text-align: center;">Fruit<a href="#fn3" class="footnote-ref"
+id="fnref3" role="doc-noteref"><sup>3</sup></a></th>
+</tr>
+</thead>
+<tbody>
+<tr>
+<td style="text-align: center;">Bans<a href="#fn4" class="footnote-ref"
+id="fnref4" role="doc-noteref"><sup>4</sup></a></td>
+</tr>
+</tbody>
+</table>
+<aside id="footnotes" class="footnotes footnotes-end-of-section"
+role="doc-footnote">
+<hr />
+<ol>
+<li id="fn1"><p>doc footnote<a href="#fnref1" class="footnote-back"
+role="doc-backlink">↩︎</a></p></li>
+<li id="fn2"><p>caption footnote<a href="#fnref2" class="footnote-back"
+role="doc-backlink">↩︎</a></p></li>
+<li id="fn3"><p>header footnote<a href="#fnref3" class="footnote-back"
+role="doc-backlink">↩︎</a></p></li>
+<li id="fn4"><p>table cell footnote<a href="#fnref4"
+class="footnote-back" role="doc-backlink">↩︎</a></p></li>
+</ol>
+</aside>
+<h1 id="section-2">Section 2</h1>
+<p>dolly<a href="#fn5" class="footnote-ref" id="fnref5"
+role="doc-noteref"><sup>5</sup></a></p>
+<aside id="footnotes-2" class="footnotes footnotes-end-of-section"
+role="doc-footnote">
+<hr />
+<ol start="5">
+<li id="fn5"><p>doc footnote<a href="#fnref5" class="footnote-back"
+role="doc-backlink">↩︎</a></p></li>
+</ol>
+</aside>
+```
diff --git a/test/command/8777.md b/test/command/8777.md
new file mode 100644
--- /dev/null
+++ b/test/command/8777.md
@@ -0,0 +1,8 @@
+# Backslash escapes in markdown_strict
+
+```
+% pandoc --from=markdown_strict -t html
+These are not escaped: \~ \"
+^D
+<p>These are not escaped: \~ \"</p>
+```
diff --git a/test/command/8783.md b/test/command/8783.md
new file mode 100644
--- /dev/null
+++ b/test/command/8783.md
@@ -0,0 +1,33 @@
+```
+% pandoc -f rtf -t native
+{\rtf1\ansi\ansicpg1252\cocoartf2867
+\cocoatextscaling0\cocoaplatform1{\fonttbl\f0\fnil\fcharset0 HelveticaNeue;}
+{\colortbl;\red255\green255\blue255;\red0\green0\blue0;}
+{\*\expandedcolortbl;;\cssrgb\c0\c0\c0;}
+{\*\listtable{\list\listtemplateid1\listhybrid{\listlevel\levelnfc0\levelnfcn0\leveljc0\leveljcn0\levelfollow0\levelstartat1\levelspace360\levelindent0{\*\levelmarker \{decimal\}.}{\leveltext\leveltemplateid1\'02\'00.;}{\levelnumbers\'01;}\fi-360\li720\lin720 }{\listname ;}\listid1}
+{\list\listtemplateid2\listhybrid{\listlevel\levelnfc23\levelnfcn23\leveljc0\leveljcn0\levelfollow0\levelstartat1\levelspace360\levelindent0{\*\levelmarker \{disc\}}{\leveltext\leveltemplateid101\'01\uc0\u8226 ;}{\levelnumbers;}\fi-360\li720\lin720 }{\listname ;}\listid2}}
+{\*\listoverridetable{\listoverride\listid1\listoverridecount0\ls1}{\listoverride\listid2\listoverridecount0\ls2}}
+\paperw11905\paperh16837\margl1133\margr1133\margb1133\margt1133
+\deftab720
+\pard\pardeftab720\partightenfactor0
+
+\f0\fs22 \cf2 \up0 \nosupersub \ulnone First paragraph\
+\pard\tx20\tx360\pardeftab720\li360\fi-360\partightenfactor0
+\ls1\ilvl0\cf2 \up0 \nosupersub \ulnone {\listtext	1.	}\cf2 \up0 \nosupersub \ulnone Numbered item\
+\pard\pardeftab720\partightenfactor0
+\cf2 Second paragraph\
+\pard\tx20\tx180\pardeftab720\li180\fi-180\partightenfactor0
+\ls2\ilvl0\cf2 \up0 \nosupersub \ulnone {\listtext	\uc0\u8226 	}\cf2 \up0 \nosupersub \ulnone Bullet item\
+\pard\pardeftab720\partightenfactor0
+\cf2 New paragraph}
+^D
+[ Para [ Str "First" , Space , Str "paragraph" ]
+, OrderedList
+    ( 1 , Decimal , Period )
+    [ [ Para [ Str "Numbered" , Space , Str "item" ] ] ]
+, Para [ Str "Second" , Space , Str "paragraph" ]
+, BulletList
+    [ [ Para [ Str "Bullet" , Space , Str "item" ] ] ]
+, Para [ Str "New" , Space , Str "paragraph" ]
+]
+```
diff --git a/test/command/8789.md b/test/command/8789.md
new file mode 100644
--- /dev/null
+++ b/test/command/8789.md
@@ -0,0 +1,42 @@
+# `\multicolumn` with column-type `p`
+
+```
+% pandoc --from=latex --to=html
+\begin{tabular}{rrll}
+	\toprule
+	\textbf{First} & \textbf{Second} & \textbf{Third} & \textbf{Fourth} \\ \toprule
+	160 & 1 & test & test \\\midrule
+	160 & 2 & \multicolumn{2}{p{12cm}}{\textit{This is a test:}
+			\begin{equation*}
+				a^2+b^2 = c^2
+		\end{equation*}
+	}\\
+\bottomrule
+\end{tabular}
+^D
+<table>
+<thead>
+<tr>
+<th style="text-align: right;"><strong>First</strong></th>
+<th style="text-align: right;"><strong>Second</strong></th>
+<th style="text-align: left;"><strong>Third</strong></th>
+<th style="text-align: left;"><strong>Fourth</strong></th>
+</tr>
+</thead>
+<tbody>
+<tr>
+<td style="text-align: right;">160</td>
+<td style="text-align: right;">1</td>
+<td style="text-align: left;">test</td>
+<td style="text-align: left;">test</td>
+</tr>
+<tr>
+<td style="text-align: right;">160</td>
+<td style="text-align: right;">2</td>
+<td colspan="2" style="text-align: left;"><em>This is a test:</em> <span
+class="math display"><em>a</em><sup>2</sup> + <em>b</em><sup>2</sup> = <em>c</em><sup>2</sup></span></td>
+</tr>
+</tbody>
+</table>
+
+```
diff --git a/test/command/8852.md b/test/command/8852.md
new file mode 100644
--- /dev/null
+++ b/test/command/8852.md
@@ -0,0 +1,43 @@
+Github Formatted Markdown Identifiers
+```
+% pandoc -f man+gfm_auto_identifiers -t html
+.TH "TEST" "1" "2026-05-08"  "test v1.0.0" "test manual"
+.SH 1st HEADING
+.SH C++ & Rust
+.SH HEADING
+.SH HEADING
+^D
+<h1 id="1st-heading">1st HEADING</h1>
+<h1 id="c--rust">C++ &amp; Rust</h1>
+<h1 id="heading">HEADING</h1>
+<h1 id="heading-1">HEADING</h1>
+```
+
+Ascii Identifiers test
+```
+% pandoc -f man+ascii_identifiers -t html
+.TH "TEST" "1" "2026-05-08"  "test v1.0.0" "test manual"
+.SH Über den Flüssen
+^D
+<h1 id="uber-den-flussen">Über den Flüssen</h1>
+```
+
+Headers without Auto Identifiers test
+```
+% pandoc -f man-auto_identifiers -t native
+.TH "TEST" "1" "2026-05-08"  "test v1.0.0" "test manual"
+.SS Level 2
+.SS different styles:
+.SS Ordered
+.SS Ordered
+^D
+[ Header
+    2 ( "" , [] , [] ) [ Str "Level" , Space , Str "2" ]
+, Header
+    2
+    ( "" , [] , [] )
+    [ Str "different" , Space , Str "styles:" ]
+, Header 2 ( "" , [] , [] ) [ Str "Ordered" ]
+, Header 2 ( "" , [] , [] ) [ Str "Ordered" ]
+]
+```
diff --git a/test/command/8853.md b/test/command/8853.md
new file mode 100644
--- /dev/null
+++ b/test/command/8853.md
@@ -0,0 +1,6 @@
+```
+% pandoc -f markdown+wikilinks_title_after_pipe --wrap=none
+[[hi]] and ![[hi]]
+^D
+<p><a href="hi" class="wikilink">hi</a> and <img src="hi" class="wikilink" alt="hi" /></p>
+```
diff --git a/test/command/8863.md b/test/command/8863.md
new file mode 100644
--- /dev/null
+++ b/test/command/8863.md
@@ -0,0 +1,11 @@
+```
+% pandoc -f dokuwiki -t native
+  * item 1
+   * item 1.1
+^D
+[ BulletList
+    [ [ Plain [ Str "item" , Space , Str "1" ] ]
+    , [ Plain [ Str "item" , Space , Str "1.1" ] ]
+    ]
+]
+```
diff --git a/test/command/8867.md b/test/command/8867.md
new file mode 100644
--- /dev/null
+++ b/test/command/8867.md
@@ -0,0 +1,49 @@
+```
+% pandoc -f jats -t native -s
+<article-meta>
+      <title-group>
+        <article-title></article-title>
+      </title-group>
+      <permissions>
+        <copyright-statement>© 2023, Ellerman et al</copyright-statement>
+        <copyright-year>2023</copyright-year>
+        <copyright-holder>Ellerman et al</copyright-holder>
+        <license license-type="open-access">
+          <ali:license_ref xmlns:ali="http://www.niso.org/schemas/ali/1.0/">https://creativecommons.org/licenses/by/4.0/</ali:license_ref>
+          <license-p>This document is distributed under a Creative Commons Attribution 4.0 International license.</license-p>
+        </license>
+      </permissions>
+</article-meta>
+^D
+Pandoc
+  Meta
+    { unMeta =
+        fromList
+          [ ( "copyright"
+            , MetaMap
+                (fromList
+                   [ ( "holder" , MetaString "Ellerman et al" )
+                   , ( "statement"
+                     , MetaString "\169 2023, Ellerman et al"
+                     )
+                   , ( "year" , MetaString "2023" )
+                   ])
+            )
+          , ( "license"
+            , MetaMap
+                (fromList
+                   [ ( "link"
+                     , MetaString
+                         "https://creativecommons.org/licenses/by/4.0/"
+                     )
+                   , ( "text"
+                     , MetaString
+                         "This document is distributed under a Creative Commons Attribution 4.0 International license."
+                     )
+                   , ( "type" , MetaString "open-access" )
+                   ])
+            )
+          ]
+    }
+  []
+```
diff --git a/test/command/8869.md b/test/command/8869.md
new file mode 100644
--- /dev/null
+++ b/test/command/8869.md
@@ -0,0 +1,20 @@
+Org arguments can either be single words, or quoted.
+
+```
+% pandoc -f org -t native
+#+begin_src jupyter-julia :exports both
+1 + 2
+#+end_src
+
+#+begin_src jupyter-julia :exports "both"
+1 + 2
+#+end_src
+^D
+[ CodeBlock
+    ( "" , [ "julia" , "code" ] , [ ( "exports" , "both" ) ] )
+    "1 + 2\n"
+, CodeBlock
+    ( "" , [ "julia" , "code" ] , [ ( "exports" , "both" ) ] )
+    "1 + 2\n"
+]
+```
diff --git a/test/command/8872.md b/test/command/8872.md
new file mode 100644
--- /dev/null
+++ b/test/command/8872.md
@@ -0,0 +1,45 @@
+
+```
+% pandoc -f latex -t native
+\documentclass{amsart}
+\newtheorem{theorem}{Theorem}
+\begin{document}
+\begin{theorem}\label{thm}
+\begin{enumerate}
+\item \label{item1}text1
+\item \label{item2}text2
+\item text3
+\end{enumerate}
+\end{theorem}
+\end{document}
+^D
+[ Div
+    ( "thm" , [ "theorem" ] , [] )
+    [ Para
+        [ Strong [ Str "Theorem" , Space , Str "1" ]
+        , Str "."
+        , Space
+        , Space
+        , Emph []
+        ]
+    , OrderedList
+        ( 1 , DefaultStyle , DefaultDelim )
+        [ [ Para
+              [ Emph
+                  [ Span ( "item1" , [] , [ ( "label" , "item1" ) ] ) []
+                  , Str "text1"
+                  ]
+              ]
+          ]
+        , [ Para
+              [ Emph
+                  [ Span ( "item2" , [] , [ ( "label" , "item2" ) ] ) []
+                  , Str "text2"
+                  ]
+              ]
+          ]
+        , [ Para [ Emph [ Str "text3" ] ] ]
+        ]
+    ]
+]
+```
diff --git a/test/command/8880.md b/test/command/8880.md
new file mode 100644
--- /dev/null
+++ b/test/command/8880.md
@@ -0,0 +1,42 @@
+Raw EPUB attributes are rendered in EPUB output.
+
+```
+% pandoc -f native -t epub --metadata title=Raw -o - | pandoc -f epub -t html
+[ RawBlock (Format "epub") "<p>ok</p>" ]
+^D
+<p><span id="title_page.xhtml"></span></p>
+<p><span id="ch001.xhtml"></span></p>
+<section id="ch001.xhtml_raw" class="unnumbered level1">
+<h1 class="unnumbered">Raw</h1>
+<p>ok</p>
+</section>
+```
+
+Raw EPUB2 attributes are omitted from EPUB3 output.
+
+```
+% pandoc -f markdown -t epub3 --metadata title=Raw -o - | pandoc -f epub -t html
+~~~ {=epub2}
+<p>ok</p>
+~~~
+^D
+<p><span id="title_page.xhtml"></span></p>
+<p><span id="ch001.xhtml"></span></p>
+<section id="ch001.xhtml_raw" class="unnumbered level1">
+<h1 class="unnumbered">Raw</h1>
+</section>
+```
+
+```
+% pandoc -f markdown -t epub3 --metadata title=Raw -o - | pandoc -f epub -t html
+~~~ {=epub3}
+<p>ok</p>
+~~~
+^D
+<p><span id="title_page.xhtml"></span></p>
+<p><span id="ch001.xhtml"></span></p>
+<section id="ch001.xhtml_raw" class="unnumbered level1">
+<h1 class="unnumbered">Raw</h1>
+<p>ok</p>
+</section>
+```
diff --git a/test/command/8948.md b/test/command/8948.md
new file mode 100644
--- /dev/null
+++ b/test/command/8948.md
@@ -0,0 +1,31 @@
+```
+% pandoc --embed-resources
+![minimal](command/minimal.svg){.inline-svg}
+![minimal](command/minimal.svg){.inline-svg}
+^D
+<p><svg role="img" aria-label="minimal" alt="minimal" viewBox="-.333 -.333 480 150" style="background-color:#ffffff00" xml:space="preserve" width="480" height="150"><use href="#svg_7868854ffb8f30209cd0" width="100%" height="100%" /></svg>
+<svg id="svg_7868854ffb8f30209cd0" role="img" aria-label="minimal" alt="minimal" viewBox="-.333 -.333 480 150" style="background-color:#ffffff00" xml:space="preserve" width="480" height="150">
+    <path d="M 0 35.5 L 6.5 22.5 L 16 37 L 23 24 L 34.8 43.7 L 42.5 30 L 50.3 47 L 59.7 27.7 L 69 47 L 85 17.7 L 98.3 39 L 113 9.7 L 127.7 42.3 L 136.3 23.7 L 147 44.3 L 158.3 20.3 L 170.3 40.3 L 177.7 25.7 L 189.7 43 L 199.7 21 L 207.7 35 L 219 11 L 233 37 L 240.3 23.7 L 251 43 L 263 18.3 L 272.7 33.3 L 283 10 L 295 32.3 L 301.3 23 L 311.7 37 L 323.7 7.7 L 339.3 39 L 346.3 25.7 L 356.3 42.3 L 369.7 15 L 376.3 25.7 L 384 9 L 393 28.3 L 400.3 19 L 411.7 38.3 L 421 21 L 434.3 43 L 445 25 L 453 36.3 L 464.3 18.3 L 476.2 40.3 L 480 33.5 L 480 215 L 0 215 L 0 35.5 Z" fill="#175720" />
+</svg></p>
+```
+
+```
+% pandoc --embed-resources
+![minimal](command/minimal.svg){.inline-svg}
+![minimal](command/minimal.svg){#foo .inline-svg}
+^D
+<p><svg role="img" aria-label="minimal" alt="minimal" viewBox="-.333 -.333 480 150" style="background-color:#ffffff00" xml:space="preserve" width="480" height="150"><use href="#foo" width="100%" height="100%" /></svg>
+<svg id="foo" role="img" aria-label="minimal" alt="minimal" viewBox="-.333 -.333 480 150" style="background-color:#ffffff00" xml:space="preserve" width="480" height="150">
+    <path d="M 0 35.5 L 6.5 22.5 L 16 37 L 23 24 L 34.8 43.7 L 42.5 30 L 50.3 47 L 59.7 27.7 L 69 47 L 85 17.7 L 98.3 39 L 113 9.7 L 127.7 42.3 L 136.3 23.7 L 147 44.3 L 158.3 20.3 L 170.3 40.3 L 177.7 25.7 L 189.7 43 L 199.7 21 L 207.7 35 L 219 11 L 233 37 L 240.3 23.7 L 251 43 L 263 18.3 L 272.7 33.3 L 283 10 L 295 32.3 L 301.3 23 L 311.7 37 L 323.7 7.7 L 339.3 39 L 346.3 25.7 L 356.3 42.3 L 369.7 15 L 376.3 25.7 L 384 9 L 393 28.3 L 400.3 19 L 411.7 38.3 L 421 21 L 434.3 43 L 445 25 L 453 36.3 L 464.3 18.3 L 476.2 40.3 L 480 33.5 L 480 215 L 0 215 L 0 35.5 Z" fill="#175720" />
+</svg></p>
+```
+
+```
+% pandoc --embed-resources
+![minimal](command/minimal.svg)
+^D
+<figure>
+<img role="img" aria-label="minimal" src="data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBzdGFuZGFsb25lPSJubyI/PgoKPHN2ZyB2aWV3Qm94PSItLjMzMyAtLjMzMyA0ODAgMTUwIiBzdHlsZT0iYmFja2dyb3VuZC1jb2xvcjojZmZmZmZmMDAiIHZlcnNpb249IjEuMSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgeG1sOnNwYWNlPSJwcmVzZXJ2ZSI+CiAgICA8cGF0aCBkPSJNIDAgMzUuNSBMIDYuNSAyMi41IEwgMTYgMzcgTCAyMyAyNCBMIDM0LjggNDMuNyBMIDQyLjUgMzAgTCA1MC4zIDQ3IEwgNTkuNyAyNy43IEwgNjkgNDcgTCA4NSAxNy43IEwgOTguMyAzOSBMIDExMyA5LjcgTCAxMjcuNyA0Mi4zIEwgMTM2LjMgMjMuNyBMIDE0NyA0NC4zIEwgMTU4LjMgMjAuMyBMIDE3MC4zIDQwLjMgTCAxNzcuNyAyNS43IEwgMTg5LjcgNDMgTCAxOTkuNyAyMSBMIDIwNy43IDM1IEwgMjE5IDExIEwgMjMzIDM3IEwgMjQwLjMgMjMuNyBMIDI1MSA0MyBMIDI2MyAxOC4zIEwgMjcyLjcgMzMuMyBMIDI4MyAxMCBMIDI5NSAzMi4zIEwgMzAxLjMgMjMgTCAzMTEuNyAzNyBMIDMyMy43IDcuNyBMIDMzOS4zIDM5IEwgMzQ2LjMgMjUuNyBMIDM1Ni4zIDQyLjMgTCAzNjkuNyAxNSBMIDM3Ni4zIDI1LjcgTCAzODQgOSBMIDM5MyAyOC4zIEwgNDAwLjMgMTkgTCA0MTEuNyAzOC4zIEwgNDIxIDIxIEwgNDM0LjMgNDMgTCA0NDUgMjUgTCA0NTMgMzYuMyBMIDQ2NC4zIDE4LjMgTCA0NzYuMiA0MC4zIEwgNDgwIDMzLjUgTCA0ODAgMjE1IEwgMCAyMTUgTCAwIDM1LjUgWiIgZmlsbD0iIzE3NTcyMCIvPgo8L3N2Zz4K" alt="minimal" />
+<figcaption aria-hidden="true">minimal</figcaption>
+</figure>
+```
diff --git a/test/command/8956.md b/test/command/8956.md
new file mode 100644
--- /dev/null
+++ b/test/command/8956.md
@@ -0,0 +1,48 @@
+```
+% pandoc -iNtslidy
+# One
+
+- one
+- two
+^D
+<div id="one" class="slide section level1" number="1">
+<h1><span class="header-section-number">1</span> One</h1>
+<ul class="incremental">
+<li>one</li>
+<li>two</li>
+</ul>
+</div>
+```
+
+````
+% pandoc -pstnative
+```
+	after tab
+```
+^D
+Pandoc
+  Meta { unMeta = fromList [] }
+  [ CodeBlock ( "" , [] , [] ) "\tafter tab" ]
+````
+
+```
+% pandoc -sfalse
+hi
+^D
+<p>hi</p>
+```
+
+```
+% pandoc --standalone=false
+hi
+^D
+<p>hi</p>
+```
+
+```
+% pandoc --standalone=FALSE
+hi
+^D
+<p>hi</p>
+```
+
diff --git a/test/command/8957.md b/test/command/8957.md
new file mode 100644
--- /dev/null
+++ b/test/command/8957.md
@@ -0,0 +1,7 @@
+```
+% pandoc -f latex -t html --wrap=none
+![Sample figure caption.](fig.jpg){width="342pt" height="9pc"}
+^D
+<p>![Sample figure caption.](fig.jpg)<span>width="342pt" height="9pc"</span></p>
+
+```
diff --git a/test/command/8966.md b/test/command/8966.md
new file mode 100644
--- /dev/null
+++ b/test/command/8966.md
@@ -0,0 +1,9 @@
+```
+% pandoc -t typst
+**Samsonov T.E.** Shape-Adaptive Geometric Simplification of Heterogeneous Line Datasets / T. E. Samsonov, O. P. Yakimova // International Journal of Geographical Information Science. — 2017. — Vol. 31. — № 8. — pp. 1485-1520.
+^D
+#strong[Samsonov T.E.] Shape-Adaptive Geometric Simplification of
+Heterogeneous Line Datasets / T. E. Samsonov, O. P. Yakimova /\/
+International Journal of Geographical Information Science. --- 2017. ---
+Vol. 31. --- № 8. --- pp.~1485-1520.
+```
diff --git a/test/command/8981.md b/test/command/8981.md
new file mode 100644
--- /dev/null
+++ b/test/command/8981.md
@@ -0,0 +1,6 @@
+```
+% pandoc --wrap=none
+consectetur [^\[link\]^](#ref "Title")
+^D
+<p>consectetur <a href="#ref" title="Title"><sup>[link]</sup></a></p>
+```
diff --git a/test/command/8984.md b/test/command/8984.md
new file mode 100644
--- /dev/null
+++ b/test/command/8984.md
@@ -0,0 +1,122 @@
+```
+% pandoc -f html -t native
+<table>
+  <tr>
+    <th colspan="2">a</th>
+    <td>b</td>
+  </tr>
+  <tr>
+    <th>c</th>
+    <th>d</th>
+    <td>e</td>
+  </tr>
+</table>
+^D
+[ Table
+    ( "" , [] , [] )
+    (Caption Nothing [])
+    [ ( AlignDefault , ColWidthDefault )
+    , ( AlignDefault , ColWidthDefault )
+    , ( AlignDefault , ColWidthDefault )
+    ]
+    (TableHead ( "" , [] , [] ) [])
+    [ TableBody
+        ( "" , [] , [] )
+        (RowHeadColumns 2)
+        []
+        [ Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 2)
+                [ Plain [ Str "a" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "b" ] ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "c" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "d" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "e" ] ]
+            ]
+        ]
+    ]
+    (TableFoot ( "" , [] , [] ) [])
+]
+
+```
+
+```
+% pandoc -f html -t native
+<table>
+<tr>
+<th rowspan="2">Heading</th>
+<td>content</td>
+</tr>
+<tr>
+<td>content2</td>
+</tr>
+</table>
+^D
+[ Table
+    ( "" , [] , [] )
+    (Caption Nothing [])
+    [ ( AlignDefault , ColWidthDefault )
+    , ( AlignDefault , ColWidthDefault )
+    ]
+    (TableHead ( "" , [] , [] ) [])
+    [ TableBody
+        ( "" , [] , [] )
+        (RowHeadColumns 1)
+        []
+        [ Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 2)
+                (ColSpan 1)
+                [ Plain [ Str "Heading" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "content" ] ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "content2" ] ]
+            ]
+        ]
+    ]
+    (TableFoot ( "" , [] , [] ) [])
+]
+
+```
diff --git a/test/command/8992.md b/test/command/8992.md
new file mode 100644
--- /dev/null
+++ b/test/command/8992.md
@@ -0,0 +1,6 @@
+```
+% pandoc -t latex
+[A theorem](https://en.wikipedia.org/wiki/Rice's_theorem).
+^D
+\href{https://en.wikipedia.org/wiki/Rice's_theorem}{A theorem}.
+```
diff --git a/test/command/8997.md b/test/command/8997.md
new file mode 100644
--- /dev/null
+++ b/test/command/8997.md
@@ -0,0 +1,77 @@
+```
+% pandoc -f org -t native
+* has space after second colon
+: aaa
+: 
+: bbb
+
+
+* has no space after second colon
+: aaa
+:
+: bbb
+^D
+[ Header
+    1
+    ( "has-space-after-second-colon" , [] , [] )
+    [ Str "has"
+    , Space
+    , Str "space"
+    , Space
+    , Str "after"
+    , Space
+    , Str "second"
+    , Space
+    , Str "colon"
+    ]
+, CodeBlock ( "" , [] , [] ) "aaa\n\nbbb\n"
+, Header
+    1
+    ( "has-no-space-after-second-colon" , [] , [] )
+    [ Str "has"
+    , Space
+    , Str "no"
+    , Space
+    , Str "space"
+    , Space
+    , Str "after"
+    , Space
+    , Str "second"
+    , Space
+    , Str "colon"
+    ]
+, CodeBlock ( "" , [] , [] ) "aaa\n\nbbb\n"
+]
+```
+
+```
+% pandoc -f org -t native
+* only the colon
+:
+
+* only the colon and a space
+: 
+^D
+[ Header
+    1
+    ( "only-the-colon" , [] , [] )
+    [ Str "only" , Space , Str "the" , Space , Str "colon" ]
+, CodeBlock ( "" , [] , [] ) "\n"
+, Header
+    1
+    ( "only-the-colon-and-a-space" , [] , [] )
+    [ Str "only"
+    , Space
+    , Str "the"
+    , Space
+    , Str "colon"
+    , Space
+    , Str "and"
+    , Space
+    , Str "a"
+    , Space
+    , Str "space"
+    ]
+, CodeBlock ( "" , [] , [] ) "\n"
+]
+```
diff --git a/test/command/9000.md b/test/command/9000.md
new file mode 100644
--- /dev/null
+++ b/test/command/9000.md
@@ -0,0 +1,14 @@
+```
+% pandoc -t org --wrap=auto --columns=20
+[This is a link with a long description that should not
+wrap](http://example.com) and
+some regular text after it so we can see how wrapping works.
+^D
+[[http://example.com][This is a link with a long description that should not wrap]]
+and some regular
+text after it so we
+can see how wrapping
+works.
+
+```
+
diff --git a/test/command/9002.docx b/test/command/9002.docx
new file mode 100644
Binary files /dev/null and b/test/command/9002.docx differ
diff --git a/test/command/9002.md b/test/command/9002.md
new file mode 100644
--- /dev/null
+++ b/test/command/9002.md
@@ -0,0 +1,20 @@
+```
+% pandoc command/9002.docx -t html
+^D
+<table style="width:40%;">
+<caption><p>This is my table!</p></caption>
+<colgroup>
+<col style="width: 20%" />
+<col style="width: 20%" />
+</colgroup>
+<thead>
+<tr>
+<th>a</th>
+<th>b</th>
+</tr>
+</thead>
+<tbody>
+</tbody>
+</table>
+<p>See <a href="#_Ref143272803">Table 1 This is my table!</a></p>
+```
diff --git a/test/command/9017.md b/test/command/9017.md
new file mode 100644
--- /dev/null
+++ b/test/command/9017.md
@@ -0,0 +1,54 @@
+```
+% pandoc -t jats --citeproc -s
+---
+references:
+- author: DeGroot
+  id: degroot_probability
+  title: Probability
+  issued: 2002
+title: Doc example with single reference
+---
+
+# I like
+
+[@degroot_probability].
+^D
+<?xml version="1.0" encoding="utf-8" ?>
+<!DOCTYPE article PUBLIC "-//NLM//DTD JATS (Z39.96) Journal Archiving and Interchange DTD v1.2 20190208//EN"
+                  "JATS-archivearticle1.dtd">
+<article xmlns:mml="http://www.w3.org/1998/Math/MathML" xmlns:xlink="http://www.w3.org/1999/xlink" dtd-version="1.2" article-type="other">
+<front>
+<journal-meta>
+<journal-id></journal-id>
+<journal-title-group>
+</journal-title-group>
+<issn></issn>
+<publisher>
+<publisher-name></publisher-name>
+</publisher>
+</journal-meta>
+<article-meta>
+<title-group>
+<article-title>Doc example with single reference</article-title>
+</title-group>
+<permissions>
+</permissions>
+</article-meta>
+</front>
+<body>
+<sec id="i-like">
+  <title>I like</title>
+  <p>(DeGroot 2002).</p>
+</sec>
+</body>
+<back>
+<ref-list>
+  <title></title>
+  <ref id="ref-degroot_probability">
+    <mixed-citation>DeGroot. 2002.
+    <italic>Probability</italic>.</mixed-citation>
+  </ref>
+</ref-list>
+</back>
+</article>
+```
diff --git a/test/command/9021.md b/test/command/9021.md
new file mode 100644
--- /dev/null
+++ b/test/command/9021.md
@@ -0,0 +1,61 @@
+```
+% pandoc -t jats+element_citations --citeproc -s
+---
+references:
+- author: DeGroot
+  id: degroot_probability
+  title: Probability
+  issued: 2002
+title: Doc example with single reference
+reference-section-title: Ref Title
+---
+
+# I like
+
+[@degroot_probability].
+^D
+<?xml version="1.0" encoding="utf-8" ?>
+<!DOCTYPE article PUBLIC "-//NLM//DTD JATS (Z39.96) Journal Archiving and Interchange DTD v1.2 20190208//EN"
+                  "JATS-archivearticle1.dtd">
+<article xmlns:mml="http://www.w3.org/1998/Math/MathML" xmlns:xlink="http://www.w3.org/1999/xlink" dtd-version="1.2" article-type="other">
+<front>
+<journal-meta>
+<journal-id></journal-id>
+<journal-title-group>
+</journal-title-group>
+<issn></issn>
+<publisher>
+<publisher-name></publisher-name>
+</publisher>
+</journal-meta>
+<article-meta>
+<title-group>
+<article-title>Doc example with single reference</article-title>
+</title-group>
+<permissions>
+</permissions>
+</article-meta>
+</front>
+<body>
+<sec id="i-like">
+  <title>I like</title>
+  <p>(DeGroot 2002).</p>
+</sec>
+</body>
+<back>
+<ref-list>
+  <title>Ref Title</title>
+  <ref id="ref-degroot_probability">
+    <element-citation>
+      <person-group person-group-type="author">
+        <string-name>DeGroot</string-name>
+      </person-group>
+      <article-title>Probability</article-title>
+      <year iso-8601-date="2002">2002</year>
+    </element-citation>
+  </ref>
+</ref-list>
+</back>
+</article>
+
+```
diff --git a/test/command/9038.md b/test/command/9038.md
new file mode 100644
--- /dev/null
+++ b/test/command/9038.md
@@ -0,0 +1,6 @@
+```
+% pandoc -t native
+![foo]
+^D
+[ Para [ Str "![foo]" ] ]
+```
diff --git a/test/command/9042.md b/test/command/9042.md
new file mode 100644
--- /dev/null
+++ b/test/command/9042.md
@@ -0,0 +1,30 @@
+```
+% pandoc -f org
+#+TITLE: Testing
+
+* Testing
+
+p. lower case
+
+P. Upper Case
+^D
+<h1 id="testing-1">Testing</h1>
+<p>p. lower case</p>
+<p>P. Upper Case</p>
+```
+```
+% pandoc -f org+fancy_lists
+#+TITLE: Testing
+
+* Testing
+
+p. lower case
+
+P. Upper Case
+^D
+<h1 id="testing-1">Testing</h1>
+<ol type="a">
+<li><p>lower case</p></li>
+<li><p>Upper Case</p></li>
+</ol>
+```
diff --git a/test/command/9043.md b/test/command/9043.md
new file mode 100644
--- /dev/null
+++ b/test/command/9043.md
@@ -0,0 +1,13 @@
+```
+% pandoc -t latex
+[**TreeTagger**](https://www.cis.uni-muenchen.de/~schmid/tools/TreeTagger/)
+^D
+\href{https://www.cis.uni-muenchen.de/~schmid/tools/TreeTagger/}{\textbf{TreeTagger}}
+```
+
+```
+% pandoc -t latex
+[**TreeTagger**](https://www.cis.uni-muenchen.de/%E7schmid/tools/TreeTagger/)
+^D
+\href{https://www.cis.uni-muenchen.de/\%E7schmid/tools/TreeTagger/}{\textbf{TreeTagger}}
+```
diff --git a/test/command/9045.md b/test/command/9045.md
new file mode 100644
--- /dev/null
+++ b/test/command/9045.md
@@ -0,0 +1,10 @@
+```
+% pandoc -t latex
+![hi](there.jpg){#foo}
+^D
+\begin{figure}
+\centering
+\pandocbounded{\includegraphics[keepaspectratio,alt={hi}]{there.jpg}}
+\caption{hi}\label{foo}
+\end{figure}
+```
diff --git a/test/command/9047.md b/test/command/9047.md
new file mode 100644
--- /dev/null
+++ b/test/command/9047.md
@@ -0,0 +1,47 @@
+tests meant to test the fixes of bug [#9047](https://github.com/jgm/pandoc/issues/9047)
+
+```
+% pandoc -f html -t html
+<ul class="task-list">
+<li><label><input type="checkbox" />foo</label></li>
+<li><label><input type="checkbox" checked="" />bar</label></li>
+<li><label><input type="button" checked="" />foobar</label></li>
+<li><input id="hello" type="checkbox" checked/><label for="hello">hello</label></li>
+</ul>
+^D
+<ul>
+<li><label><input type="checkbox" />foo</label></li>
+<li><label><input type="checkbox" checked="" />bar</label></li>
+<li>foobar</li>
+<li><label><input type="checkbox" checked="" />hello</label></li>
+</ul>
+```
+
+w/ rawHTML extension a checkbox by itself is kept
+```
+% pandoc -f html+raw_html -t html+raw_html
+<input type="checkbox" checked="" />
+^D
+<input type="checkbox" checked>
+</input>
+```
+
+w/ rawHTML extension, a checkbox in an `li` is handled properly
+```
+% pandoc -f html+raw_html -t html+raw_html
+<ul>
+<li><input type="checkbox" checked/>foo</li>
+</ul>
+^D
+<ul class="task-list">
+<li><label><input type="checkbox" checked="" />foo</label></li>
+</ul>
+```
+
+w/o rawHTML extension, a checkbox outside of an `li` is properly ignored
+```
+% pandoc -f html -t html
+<p><input type="checkbox" checked/>foo</p>
+^D
+foo
+```
diff --git a/test/command/9088.md b/test/command/9088.md
new file mode 100644
--- /dev/null
+++ b/test/command/9088.md
@@ -0,0 +1,10 @@
+```
+% pandoc -t latex
+|    0 - A
+|    1 - B
+|    2 - C
+^D
+~~~0 - A\\
+\strut ~~~1 - B\\
+\strut ~~~2 - C
+```
diff --git a/test/command/9090.md b/test/command/9090.md
new file mode 100644
--- /dev/null
+++ b/test/command/9090.md
@@ -0,0 +1,15 @@
+```
+% pandoc -f html -t gfm
+<table>
+  <tr>
+    <th>invalid head cell</td>
+  </tr>
+  <tr>
+    <td>body cell</td>
+  </tr>
+</table>
+^D
+| invalid head cell |
+|-------------------|
+| body cell         |
+```
diff --git a/test/command/9121.md b/test/command/9121.md
new file mode 100644
--- /dev/null
+++ b/test/command/9121.md
@@ -0,0 +1,17 @@
+````
+% pandoc -t gfm
+a $$x=y$$ b
+^D
+a
+``` math
+x=y
+```
+b
+````
+
+````
+% pandoc -t gfm
+a $x=y$ b
+^D
+a $`x=y`$ b
+````
diff --git a/test/command/9136.md b/test/command/9136.md
new file mode 100644
--- /dev/null
+++ b/test/command/9136.md
@@ -0,0 +1,89 @@
+Verify that the OpenDocument writer uses predefined list, paragraph, and
+text styles instead of generating per-instance automatic styles.
+
+```
+% pandoc -t opendocument
+- one
+- two
+
+1. ordered one
+2. ordered two
+
+Some *italic*, **bold**, ~~strike~~, and `code`.
+
+> A block quote.
+
+Final paragraph.
+^D
+<text:list text:style-name="List_20_1">
+  <text:list-item>
+    <text:p text:style-name="List_20_Bullet_20_Tight">one</text:p>
+  </text:list-item>
+  <text:list-item>
+    <text:p text:style-name="List_20_Bullet_20_Tight">two</text:p>
+  </text:list-item>
+</text:list>
+<text:list text:style-name="Numbering_20_1">
+  <text:list-item>
+    <text:p text:style-name="List_20_Number_20_Tight">ordered
+    one</text:p>
+  </text:list-item>
+  <text:list-item>
+    <text:p text:style-name="List_20_Number_20_Tight">ordered
+    two</text:p>
+  </text:list-item>
+</text:list>
+<text:p text:style-name="First_20_paragraph">Some
+<text:span text:style-name="Emphasis">italic</text:span>,
+<text:span text:style-name="Strong_20_Emphasis">bold</text:span>,
+<text:span text:style-name="Strikeout">strike</text:span>, and
+<text:span text:style-name="Source_20_Text">code</text:span>.</text:p>
+<text:p text:style-name="Quotations">A block quote.</text:p>
+<text:p text:style-name="First_20_paragraph">Final paragraph.</text:p>
+```
+
+A non-default ordered list (start value other than 1, or non-decimal
+format) generates a single named override style, not one per instance.
+
+```
+% pandoc -t opendocument
+A) upper-alpha one
+B) upper-alpha two
+
+5. start at five
+6. and continue
+^D
+<text:list text:style-name="Pandoc_5f_Numbering_5f_1">
+  <text:list-item>
+    <text:p text:style-name="List_20_Number_20_Tight">upper-alpha
+    one</text:p>
+  </text:list-item>
+  <text:list-item>
+    <text:p text:style-name="List_20_Number_20_Tight">upper-alpha
+    two</text:p>
+  </text:list-item>
+</text:list>
+<text:list text:style-name="Numbering_20_1" text:start-value="5">
+  <text:list-item>
+    <text:p text:style-name="List_20_Number_20_Tight">start at
+    five</text:p>
+  </text:list-item>
+  <text:list-item>
+    <text:p text:style-name="List_20_Number_20_Tight">and
+    continue</text:p>
+  </text:list-item>
+</text:list>
+```
+
+A nested block quote uses the predefined `Quotations` style for the
+outer paragraph, and inherits indent from it for the inner paragraph.
+
+```
+% pandoc -t opendocument
+> First.
+>
+> > Nested.
+^D
+<text:p text:style-name="Quotations">First.</text:p>
+<text:p text:style-name="P1">Nested.</text:p>
+```
diff --git a/test/command/9150.md b/test/command/9150.md
new file mode 100644
--- /dev/null
+++ b/test/command/9150.md
@@ -0,0 +1,51 @@
+```
+% pandoc -f latex -t native
+\hfill  {\Large \textbf{Theoretische Grundlagen der Informatik}}
+^D
+[ Para
+    [ Span
+        ( "" , [] , [] )
+        [ Strong
+            [ Str "Theoretische"
+            , Space
+            , Str "Grundlagen"
+            , Space
+            , Str "der"
+            , Space
+            , Str "Informatik"
+            ]
+        ]
+    ]
+]
+```
+
+```
+% pandoc -f latex+raw_tex -t native
+\hfill  {\Large \textbf{Theoretische Grundlagen der Informatik}}
+^D
+[ Para
+    [ RawInline (Format "latex") "\\hfill  "
+    , Span
+        ( "" , [] , [] )
+        [ RawInline (Format "latex") "\\Large "
+        , Strong
+            [ Str "Theoretische"
+            , Space
+            , Str "Grundlagen"
+            , Space
+            , Str "der"
+            , Space
+            , Str "Informatik"
+            ]
+        ]
+    ]
+]
+```
+
+```
+% pandoc -f latex+raw_tex -t native
+\hskip 2pt plus 1pt minus 1pt
+^D
+[ RawBlock (Format "latex") "\\hskip 2pt plus 1pt minus 1pt"
+]
+```
diff --git a/test/command/9159.md b/test/command/9159.md
new file mode 100644
--- /dev/null
+++ b/test/command/9159.md
@@ -0,0 +1,15 @@
+```
+% pandoc -t org -f markdown
+\* See Blah
+
+\# not comment
+
+\| not table \|
+^D
+​* See Blah
+
+​# not comment
+
+​| not table |
+
+```
diff --git a/test/command/9171.md b/test/command/9171.md
new file mode 100644
--- /dev/null
+++ b/test/command/9171.md
@@ -0,0 +1,65 @@
+```
+% pandoc -f markdown -t native
+[link][link contents]{target="_blank"}
+[link2](https://example.com){target="_blank"}
+
+[link contents]: https://example.com
+^D
+[ Para
+    [ Link
+        ( "" , [] , [ ( "target" , "_blank" ) ] )
+        [ Str "link" ]
+        ( "https://example.com" , "" )
+    , SoftBreak
+    , Link
+        ( "" , [] , [ ( "target" , "_blank" ) ] )
+        [ Str "link2" ]
+        ( "https://example.com" , "" )
+    ]
+]
+
+```
+
+```
+% pandoc -f markdown -t native
+[link][link contents]{#id1 target="_blank"}
+[link2](https://example.com){target="_blank"}
+
+[link contents]: https://example.com {#id2 target="_nonblank"}
+^D
+[ Para
+    [ Link
+        ( "id1" , [] , [ ( "target" , "_blank" ) ] )
+        [ Str "link" ]
+        ( "https://example.com" , "" )
+    , SoftBreak
+    , Link
+        ( "" , [] , [ ( "target" , "_blank" ) ] )
+        [ Str "link2" ]
+        ( "https://example.com" , "" )
+    ]
+]
+
+```
+
+```
+% pandoc -f markdown -t native
+[link][link contents]{target="_blank"}
+[link2](https://example.com){target="_blank"}
+
+[link contents]: https://example.com {.foo}
+^D
+[ Para
+    [ Link
+        ( "" , [ "foo" ] , [ ( "target" , "_blank" ) ] )
+        [ Str "link" ]
+        ( "https://example.com" , "" )
+    , SoftBreak
+    , Link
+        ( "" , [] , [ ( "target" , "_blank" ) ] )
+        [ Str "link2" ]
+        ( "https://example.com" , "" )
+    ]
+]
+
+```
diff --git a/test/command/9193.md b/test/command/9193.md
new file mode 100644
--- /dev/null
+++ b/test/command/9193.md
@@ -0,0 +1,7 @@
+```
+% pandoc -t native
+$a+%
+b$
+^D
+[ Para [ Math InlineMath "a+%\nb" ] ]
+```
diff --git a/test/command/9196.md b/test/command/9196.md
new file mode 100644
--- /dev/null
+++ b/test/command/9196.md
@@ -0,0 +1,6 @@
+```
+% pandoc -f rst --wrap=none
+Define  _`my target`, then reference `my target`_.
+^D
+<p>Define <span id="my-target">my target</span>, then reference <a href="#my-target">my target</a>.</p>
+```
diff --git a/test/command/9201.md b/test/command/9201.md
new file mode 100644
--- /dev/null
+++ b/test/command/9201.md
@@ -0,0 +1,18 @@
+```
+% pandoc -f man -t markdown
+.TH "EXAMPLE" "1"
+.SH "OPTIONS"
+.TP 8n
+\fB\-\-help\fR
+This is line one.
+.sp
+This is line two.
+^D
+# OPTIONS
+
+**\--help**
+
+: This is line one.
+
+  This is line two.
+```
diff --git a/test/command/9202.md b/test/command/9202.md
new file mode 100644
--- /dev/null
+++ b/test/command/9202.md
@@ -0,0 +1,62 @@
+```
+% pandoc -f latex -t native
+\begin{otherlanguage}{french}
+Bonjour.
+\end{otherlanguage}
+^D
+[ Div
+    ( "" , [] , [ ( "lang" , "fr" ) ] )
+    [ Para [ Str "Bonjour." ] ]
+]
+```
+
+```
+% pandoc -f latex -t native
+\begin{otherlanguage*}{french}
+Bonjour.
+\end{otherlanguage*}
+^D
+[ Div
+    ( "" , [ "otherlanguage*" ] , [] )
+    [ Para
+        [ Span ( "" , [] , [] ) [ Str "french" ]
+        , SoftBreak
+        , Str "Bonjour."
+        ]
+    ]
+]
+```
+
+```
+% pandoc -f latex -t native
+\textfrench{Bonjour}
+^D
+[ Para
+    [ Span ( "" , [] , [ ( "lang" , "fr" ) ] ) [ Str "Bonjour" ]
+    ]
+]
+```
+
+```
+% pandoc -f latex -t native
+\foreignlanguage{swissgerman}{Guten tag}
+^D
+[ Para
+    [ Span
+        ( "" , [] , [ ( "lang" , "de-CH-1901" ) ] )
+        [ Str "Guten" , Space , Str "tag" ]
+    ]
+]
+```
+
+```
+% pandoc -f latex -t native
+\begin{french}
+Bonjour.
+\end{french}
+^D
+[ Div
+    ( "" , [] , [ ( "lang" , "fr" ) ] )
+    [ Para [ Str "Bonjour." ] ]
+]
+```
diff --git a/test/command/9209.md b/test/command/9209.md
new file mode 100644
--- /dev/null
+++ b/test/command/9209.md
@@ -0,0 +1,6 @@
+```
+% pandoc -t latex
+## [Section]{#Section3}
+^D
+\subsection{\texorpdfstring{\protect\hypertarget{Section3}{}{Section}}{Section}}\label{section}
+```
diff --git a/test/command/9218.md b/test/command/9218.md
new file mode 100644
--- /dev/null
+++ b/test/command/9218.md
@@ -0,0 +1,22 @@
+# Escape special lines in Org-mode code blocks
+
+````
+% pandoc -f markdown -t org
+``` org
+** Click Application
+*** Imports
+
+#+begin_src py
+from addict import Dict
+#+end_src
+```
+^D
+#+begin_src org
+,** Click Application
+,*** Imports
+
+,#+begin_src py
+from addict import Dict
+,#+end_src
+#+end_src
+````
diff --git a/test/command/9236.md b/test/command/9236.md
new file mode 100644
--- /dev/null
+++ b/test/command/9236.md
@@ -0,0 +1,34 @@
+```
+% pandoc -t typst
+![minimal](command/minimal.svg){width=3in}
+
+![minimal](command/minimal.svg){width=3in height=2in}
+
+![minimal](command/minimal.svg)
+
+And inline: ![minimal](command/minimal.svg){height=2in} and
+![minimal](command/minimal.svg).
+^D
+#figure(image("command/minimal.svg", width: 3in, alt: "minimal"),
+  caption: [
+    minimal
+  ]
+)
+
+#figure(image("command/minimal.svg", height: 2in, width: 3in, alt: "minimal"),
+  caption: [
+    minimal
+  ]
+)
+
+#figure(image("command/minimal.svg", alt: "minimal"),
+  caption: [
+    minimal
+  ]
+)
+
+And inline:
+#box(image("command/minimal.svg", height: 2in, alt: "minimal")) and
+#box(image("command/minimal.svg", alt: "minimal")).
+
+```
diff --git a/test/command/9275.md b/test/command/9275.md
new file mode 100644
--- /dev/null
+++ b/test/command/9275.md
@@ -0,0 +1,18 @@
+```
+% pandoc -t latex --biblatex
+[@scott2000, p. 33]
+[@scott2000, pp. 33-34 and elsewhere; @scott2001, ch. 4]
+^D
+\autocite[33]{scott2000} \autocites[33-34 and
+elsewhere]{scott2000}[ch.~4]{scott2001}
+
+```
+
+```
+% pandoc -t latex --biblatex -Mlang=de
+[@scott2000, p. 33]
+[@scott2000, S. 33]
+^D
+\autocite[p.~33]{scott2000} \autocite[33]{scott2000}
+
+```
diff --git a/test/command/9279.md b/test/command/9279.md
new file mode 100644
--- /dev/null
+++ b/test/command/9279.md
@@ -0,0 +1,131 @@
+```
+% pandoc -f org -t native
+#+LABEL: tbl:Cosasexample
+#+CAPTION: Cosas
++-------+-------+
+| cosas | cosas |
+| cosas | cosas |
++=======+=======+
+| cosas | cosas |
+| cosas | cosas |
++-------+-------+
+^D
+[ Table
+    ( "tbl:Cosasexample" , [] , [] )
+    (Caption Nothing [ Plain [ Str "Cosas" ] ])
+    [ ( AlignDefault , ColWidth 0.1111111111111111 )
+    , ( AlignDefault , ColWidth 0.1111111111111111 )
+    ]
+    (TableHead
+       ( "" , [] , [] )
+       [ Row
+           ( "" , [] , [] )
+           [ Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "cosas" , SoftBreak , Str "cosas" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "cosas" , SoftBreak , Str "cosas" ] ]
+           ]
+       ])
+    [ TableBody
+        ( "" , [] , [] )
+        (RowHeadColumns 0)
+        []
+        [ Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "cosas" , SoftBreak , Str "cosas" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "cosas" , SoftBreak , Str "cosas" ] ]
+            ]
+        ]
+    ]
+    (TableFoot ( "" , [] , [] ) [])
+]
+```
+
+```
+% pandoc -f org -t markdown
+#+LABEL: tbl:Cosasexample
+#+CAPTION: Cosas
++-------+-------+
+| cosas | cosas |
+| cosas | cosas |
++=======+=======+
+| cosas | cosas |
+| cosas | cosas |
++-------+-------+
+^D
+  ---------------
+  cosas   cosas
+  cosas   cosas
+  ------- -------
+  cosas   cosas
+  cosas   cosas
+
+  ---------------
+
+  : Cosas {#tbl:Cosasexample}
+
+```
+
+```
+% pandoc -f org -t markdown
+#+LABEL: tbl:Cosasexample
++-------+-------+
+| cosas | cosas |
+| cosas | cosas |
++=======+=======+
+| cosas | cosas |
+| cosas | cosas |
++-------+-------+
+^D
+  ---------------
+  cosas   cosas
+  cosas   cosas
+  ------- -------
+  cosas   cosas
+  cosas   cosas
+
+  ---------------
+
+```
+
+```
+% pandoc -f org -t markdown
+#+CAPTION: Cosas
++-------+-------+
+| cosas | cosas |
+| cosas | cosas |
++=======+=======+
+| cosas | cosas |
+| cosas | cosas |
++-------+-------+
+^D
+  ---------------
+  cosas   cosas
+  cosas   cosas
+  ------- -------
+  cosas   cosas
+  cosas   cosas
+
+  ---------------
+
+  : Cosas
+
+```
diff --git a/test/command/9293.md b/test/command/9293.md
new file mode 100644
--- /dev/null
+++ b/test/command/9293.md
@@ -0,0 +1,29 @@
+```
+% pandoc -f mediawiki -t native
+* Linearity in the first argument:
+*:<math>\begin{align}
+\langle a \mathbf u, \mathbf v\rangle &= a \langle \mathbf u, \mathbf v\rangle. \\
+\langle \mathbf u + \mathbf v, \mathbf w\rangle &= \langle \mathbf u, \mathbf w\rangle+ \langle \mathbf v, \mathbf w\rangle.
+\end{align}</math>
+^D
+[ BulletList
+    [ [ Plain
+          [ Str "Linearity"
+          , Space
+          , Str "in"
+          , Space
+          , Str "the"
+          , Space
+          , Str "first"
+          , Space
+          , Str "argument:"
+          ]
+      , Para
+          [ Math
+              DisplayMath
+              "\\begin{align}\n\\langle a \\mathbf u, \\mathbf v\\rangle &= a \\langle \\mathbf u, \\mathbf v\\rangle. \\\\\n\\langle \\mathbf u + \\mathbf v, \\mathbf w\\rangle &= \\langle \\mathbf u, \\mathbf w\\rangle+ \\langle \\mathbf v, \\mathbf w\\rangle.\n\\end{align}"
+          ]
+      ]
+    ]
+]
+```
diff --git a/test/command/934.md b/test/command/934.md
--- a/test/command/934.md
+++ b/test/command/934.md
@@ -7,6 +7,38 @@
 }
 \ddb{This should be italic and in quotes}{And this is the attribution}
 ^D
-[Para [Emph [Quoted DoubleQuote [Str "This",Space,Str "should",Space,Str "be",Space,Str "italic",Space,Str "and",Space,Str "in",Space,Str "quotes"]]]
-,Para [Strong [Str "And",Space,Str "this",Space,Str "is",Space,Str "the",Space,Str "attribution"]]]
+[ Para
+    [ Emph
+        [ Quoted
+            DoubleQuote
+            [ Str "This"
+            , Space
+            , Str "should"
+            , Space
+            , Str "be"
+            , Space
+            , Str "italic"
+            , Space
+            , Str "and"
+            , Space
+            , Str "in"
+            , Space
+            , Str "quotes"
+            ]
+        ]
+    ]
+, Para
+    [ Strong
+        [ Str "And"
+        , Space
+        , Str "this"
+        , Space
+        , Str "is"
+        , Space
+        , Str "the"
+        , Space
+        , Str "attribution"
+        ]
+    ]
+]
 ```
diff --git a/test/command/9346.md b/test/command/9346.md
new file mode 100644
--- /dev/null
+++ b/test/command/9346.md
@@ -0,0 +1,8 @@
+```
+% pandoc -f markdown -t markdown_strict+pipe_tables
+|V1 |V2 |V3 |V4 |V5 |V6 |V7 |V8 |V9 |V10 |V11 |V12 |V13 |V14 |V15 |V16 |V17 |V18 |V19 |V20 |V21 |V22 |V23 |V24 |V25 |V26 |V27 |V28 |V29 |V30 |V31 |V32 |V33 |V34 |V35 |V36 |V37 |V38 |V39 |V40 |V41 |V42 |V43 |V44 |V45 |V46 |V47 |V48 |V49 |V50 |V51 |V52 |V53 |V54 |V55 |V56 |V57 |V58 |V59 |V60 |V61 |V62 |V63 |V64 |V65 |V66 |V67 |V68 |V69 |V70 |V71 |V72 |
+|:--|:--|:--|:--|:--|:--|:--|:--|:--|:---|:---|:---|:---|:---|:---|:---|:---|:---|:---|:---|:---|:---|:---|:---|:---|:---|:---|:---|:---|:---|:---|:---|:---|:---|:---|:---|:---|:---|:---|:---|:---|:---|:---|:---|:---|:---|:---|:---|:---|:---|:---|:---|:---|:---|:---|:---|:---|:---|:---|:---|:---|:---|:---|:---|:---|:---|:---|:---|:---|:---|:---|:---|
+^D
+| V1 | V2 | V3 | V4 | V5 | V6 | V7 | V8 | V9 | V10 | V11 | V12 | V13 | V14 | V15 | V16 | V17 | V18 | V19 | V20 | V21 | V22 | V23 | V24 | V25 | V26 | V27 | V28 | V29 | V30 | V31 | V32 | V33 | V34 | V35 | V36 | V37 | V38 | V39 | V40 | V41 | V42 | V43 | V44 | V45 | V46 | V47 | V48 | V49 | V50 | V51 | V52 | V53 | V54 | V55 | V56 | V57 | V58 | V59 | V60 | V61 | V62 | V63 | V64 | V65 | V66 | V67 | V68 | V69 | V70 | V71 | V72 |
+|:-|:-|:-|:-|:-|:-|:-|:-|:-|:-|:-|:-|:-|:-|:-|:-|:-|:-|:-|:-|:-|:-|:-|:-|:-|:-|:-|:-|:-|:-|:-|:-|:-|:-|:-|:-|:-|:-|:-|:-|:-|:-|:-|:-|:-|:-|:-|:-|:-|:-|:-|:-|:-|:-|:-|:-|:-|:-|:-|:-|:-|:-|:-|:-|:-|:-|:-|:-|:-|:-|:-|:-|
+```
diff --git a/test/command/9350.md b/test/command/9350.md
new file mode 100644
--- /dev/null
+++ b/test/command/9350.md
@@ -0,0 +1,14 @@
+```
+% pandoc -f html -t latex
+<table><tbody><tr></tr></tbody></table>
+^D
+{\def\LTcaptype{none} % do not increment counter
+\begin{longtable}[]{@{}l@{}}
+\toprule\noalign{}
+\endhead
+\bottomrule\noalign{}
+\endlastfoot
+ \\
+\end{longtable}
+}
+```
diff --git a/test/command/9358.docx b/test/command/9358.docx
new file mode 100644
Binary files /dev/null and b/test/command/9358.docx differ
diff --git a/test/command/9358.md b/test/command/9358.md
new file mode 100644
--- /dev/null
+++ b/test/command/9358.md
@@ -0,0 +1,45 @@
+Caption belongs to the second table:
+```
+% pandoc -f docx -t html command/9358.docx
+^D
+<p>Lorem gipsum</p>
+<table>
+<colgroup>
+<col style="width: 50%" />
+<col style="width: 50%" />
+</colgroup>
+<thead>
+<tr>
+<th>A</th>
+<th>B</th>
+</tr>
+</thead>
+<tbody>
+<tr>
+<td>C</td>
+<td>D</td>
+</tr>
+</tbody>
+</table>
+<p>Lorem ipsum</p>
+<table>
+<caption><p>Table 1 Numbers from 1 to 4</p></caption>
+<colgroup>
+<col style="width: 50%" />
+<col style="width: 50%" />
+</colgroup>
+<thead>
+<tr>
+<th>1</th>
+<th>2</th>
+</tr>
+</thead>
+<tbody>
+<tr>
+<td>3</td>
+<td>4</td>
+</tr>
+</tbody>
+</table>
+<p>Lorem yipsum</p>
+```
diff --git a/test/command/9366.md b/test/command/9366.md
new file mode 100644
--- /dev/null
+++ b/test/command/9366.md
@@ -0,0 +1,34 @@
+```
+% pandoc -f native -t latex
+[ Para
+    [ Strikeout
+        [ Link
+            ( "" , [] , [] )
+            [ Str "Example" ]
+            ( "https://example.com" , "" )
+        ]
+    ]
+, Para
+    [ Strikeout
+        [ Link
+            ( "" , [] , [] )
+            [ Str "https://example.com" ]
+            ( "https://example.com" , "" )
+        ]
+    ]
+, Para
+    [ Strikeout
+        [ Link
+            ( "" , [] , [] )
+            [ Str "info@example.com" ]
+            ( "mailto:info@example.com" , "" )
+        ]
+    ]
+]
+^D
+\st{\mbox{\href{https://example.com}{Example}}}
+
+\st{\mbox{\url{https://example.com}}}
+
+\st{\mbox{\href{mailto:info@example.com}{\nolinkurl{info@example.com}}}}
+```
diff --git a/test/command/9371.md b/test/command/9371.md
new file mode 100644
--- /dev/null
+++ b/test/command/9371.md
@@ -0,0 +1,30 @@
+```
+% pandoc -t latex
+"'In this case (A),
+
+I get a kern to separate the quotes,' he said."
+
+"'Also in this case (B), I get a kern,' he added."
+
+"'But in this case (C), there is no kern,'
+
+he continued."
+
+"He concluded,
+
+'Nor in this case (D) is there a kern.'"
+^D
+``\,'In this case (A),
+
+I get a kern to separate the quotes,' he said.''
+
+``\,`Also in this case (B), I get a kern,' he added.''
+
+``\,`But in this case (C), there is no kern,'
+
+he continued.''
+
+``He concluded,
+
+`Nor in this case (D) is there a kern.'\,''
+```
diff --git a/test/command/9386.md b/test/command/9386.md
new file mode 100644
--- /dev/null
+++ b/test/command/9386.md
@@ -0,0 +1,17 @@
+```
+% pandoc -t typst --wrap=preserve
+A string of text that is long enough that after 73 chars that includes a
+/ slash creates a newline
+^D
+A string of text that is long enough that after 73 chars that includes a
+\/ slash creates a newline
+```
+
+```
+% pandoc -t typst --wrap=preserve
+A string of text that is long enough that after 73 chars that includes
+a / slash creates a newline
+^D
+A string of text that is long enough that after 73 chars that includes
+a / slash creates a newline
+```
diff --git a/test/command/9387.md b/test/command/9387.md
new file mode 100644
--- /dev/null
+++ b/test/command/9387.md
@@ -0,0 +1,23 @@
+```
+% pandoc -f html -t typst
+<div id="my label">
+<p>test</p>
+</div>
+<p>See <a href="#my label">my label</a>.</p>
+^D
+#block[
+test
+
+] #label("my label")
+See #link(label("my label"))[my label].
+
+```
+
+```
+% pandoc -f latex -t typst
+\cite{10.1117/12.695309}
+\cite{foo}
+^D
+#cite(label("10.1117/12.695309")) @foo
+
+```
diff --git a/test/command/9388.md b/test/command/9388.md
new file mode 100644
--- /dev/null
+++ b/test/command/9388.md
@@ -0,0 +1,21 @@
+```
+% pandoc -f latex -t native
+\begin{figure}
+\centering
+\includegraphics[width=0.5\linewidth,height=0.5\textheight]{figures/placeholder}
+\caption{Example figure}
+\end{figure}
+^D
+[ Figure
+    ( "" , [] , [] )
+    (Caption
+       Nothing [ Plain [ Str "Example" , Space , Str "figure" ] ])
+    [ Plain
+        [ Image
+            ( "" , [] , [ ( "width" , "50%" ) , ( "height" , "50%" ) ] )
+            []
+            ( "figures/placeholder" , "" )
+        ]
+    ]
+]
+```
diff --git a/test/command/9391.docx b/test/command/9391.docx
new file mode 100644
Binary files /dev/null and b/test/command/9391.docx differ
diff --git a/test/command/9391.md b/test/command/9391.md
new file mode 100644
--- /dev/null
+++ b/test/command/9391.md
@@ -0,0 +1,9 @@
+```
+% pandoc command/9391.docx -t html
+^D
+<p>Lorem ipsum.</p>
+<figure>
+<img src="media/image1.png" style="width:1.09702in;height:1.09702in" />
+<figcaption><p>Blue square.</p></figcaption>
+</figure>
+```
diff --git a/test/command/9420.md b/test/command/9420.md
new file mode 100644
--- /dev/null
+++ b/test/command/9420.md
@@ -0,0 +1,13 @@
+```
+% pandoc --embed-resources
+![](command/9420.svg){.inline-svg}
+^D
+<p><svg id="svg_e1815ef374a63cf552e4" role="img" width="504pt" height="360pt" viewBox="0 0 504 360">
+<defs>
+<clipPath id="svg_e1815ef374a63cf552e4_clip1-c3ce354c">
+  <path />
+</clipPath>
+</defs>
+<g clip-path="url(#svg_e1815ef374a63cf552e4_clip1-c3ce354c)" clip-rule="nonzero"></g>
+</svg></p>
+```
diff --git a/test/command/9420.svg b/test/command/9420.svg
new file mode 100644
--- /dev/null
+++ b/test/command/9420.svg
@@ -0,0 +1,9 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="504pt" height="360pt" viewBox="0 0 504 360" version="1.1">
+<defs>
+<clipPath id="clip1-c3ce354c">
+  <path/>
+</clipPath>
+</defs>
+<g clip-path="url(#clip1-c3ce354c)" clip-rule="nonzero"></g>
+</svg>
diff --git a/test/command/9445.md b/test/command/9445.md
new file mode 100644
--- /dev/null
+++ b/test/command/9445.md
@@ -0,0 +1,6 @@
+```
+% pandoc -f man -t markdown
+\fB--c \fI<file>
+^D
+**\--c** *\<file\>*
+```
diff --git a/test/command/9452.md b/test/command/9452.md
new file mode 100644
--- /dev/null
+++ b/test/command/9452.md
@@ -0,0 +1,19 @@
+```
+% pandoc -t typst
+@something2024 says blah.
+
+Here is a sentence [@something2024].
+
+With supplement [@something2024, p. 3].
+
+And just the year [-@something2024].
+^D
+#cite(<something2024>, form: "prose") says blah.
+
+Here is a sentence @something2024.
+
+With supplement @something2024[p.~3].
+
+And just the year (#cite(<something2024>, form: "year")).
+
+```
diff --git a/test/command/9467.md b/test/command/9467.md
new file mode 100644
--- /dev/null
+++ b/test/command/9467.md
@@ -0,0 +1,7 @@
+```
+% pandoc --embed-resources
+![](command/9467.svg)
+^D
+<p><img role="img" src="data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTkiIHN0YW5kYWxvbmU9Im5vIj8+CjwhLS0gQ3JlYXRlZCB3aXRoIElua3NjYXBlIChodHRwOi8vd3d3Lmlua3NjYXBlLm9yZy8pIC0tPgoKPHN2ZwogICB2ZXJzaW9uPSIxLjEiIGlkPSJzdmcyIiB3aWR0aD0iMTkxLjU2MjY3IiBoZWlnaHQ9IjE1MS43MTIwMSIgdmlld0JveD0iMCAwIDE5MS41NjI2NyAxNTEuNzEyMDEiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6c3ZnPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CiAgPGRlZnMgaWQ9ImRlZnM2Ij4KICAgIDxjbGlwUGF0aCBjbGlwUGF0aFVuaXRzPSJ1c2VyU3BhY2VPblVzZSIgaWQ9ImNsaXBQYXRoMjQiPgogICAgICA8cGF0aCBkPSJNIDU2LjY5MzYyLDAgMTEzLjM4NzI0LDExMy4zODcyNCAxNzAuMDgwODYsMCBaIiBpZD0icGF0aDIyIiAvPgogICAgPC9jbGlwUGF0aD4KICAgIDxjbGlwUGF0aCBjbGlwUGF0aFVuaXRzPSJ1c2VyU3BhY2VPblVzZSIgaWQ9ImNsaXBQYXRoMzgiPgogICAgICA8cGF0aCBkPSJNIDAsMCBIIDEwMCBWIDEwMCBIIDAgWiIgaWQ9InBhdGgzNiIgLz4KICAgIDwvY2xpcFBhdGg+CiAgICA8cmFkaWFsR3JhZGllbnQgZng9IjUwLjAwMDY0MSIgZnk9IjUwLjAwMDY0MSIgY3g9IjUwLjAwMDY0MSIgY3k9IjUwLjAwMDY0MSIgcj0iNTAuMDAwNjQxIiBncmFkaWVudFVuaXRzPSJ1c2VyU3BhY2VPblVzZSIgaWQ9InJhZGlhbEdyYWRpZW50NDYiPgogICAgICA8c3RvcCBzdHlsZT0ic3RvcC1vcGFjaXR5OjE7c3RvcC1jb2xvcjojZmZmZmZmIiBvZmZzZXQ9IjAiIGlkPSJzdG9wNDAiIC8+CiAgICAgIDxzdG9wIHN0eWxlPSJzdG9wLW9wYWNpdHk6MTtzdG9wLWNvbG9yOiM5OTk5ZmYiIG9mZnNldD0iMjUuMDAwMzIiIGlkPSJzdG9wNDIiIC8+CiAgICAgIDxzdG9wIHN0eWxlPSJzdG9wLW9wYWNpdHk6MTtzdG9wLWNvbG9yOiM5OTk5ZmYiIG9mZnNldD0iNTAuMDAwNjQiIGlkPSJzdG9wNDQiIC8+CiAgICA8L3JhZGlhbEdyYWRpZW50PgogIDwvZGVmcz4KICA8ZyBpZD0iZzgiIHRyYW5zZm9ybT0ibWF0cml4KDEuMzMzMzMzMywwLDAsLTEuMzMzMzMzMywwLDE1MS43MTIpIj4KICAgIDxnIGlkPSJnMTAiIHRyYW5zZm9ybT0idHJhbnNsYXRlKC0yNi42MDYsMC4xOTkpIj4KICAgICAgPGcgaWQ9ImcxMiI+CiAgICAgICAgPGcgaWQ9ImcxNCI+CiAgICAgICAgICA8ZyBpZD0iZzE2Ij4KICAgICAgICAgICAgPGcgaWQ9ImcxOCI+CiAgICAgICAgICAgICAgPGcgaWQ9ImcyMCIgY2xpcC1wYXRoPSJ1cmwoI2NsaXBQYXRoMjQpIj4KICAgICAgICAgICAgICAgIDxnIGlkPSJnMjYiIHRyYW5zZm9ybT0ibWF0cml4KDIuMjY4MDIsMCwwLDIuMjY4MDIsMTEzLjM4NzI0LDU2LjY5MzYyKSI+CiAgICAgICAgICAgICAgICAgIDxnIGlkPSJnMjgiPgogICAgICAgICAgICAgICAgICAgIDxnIGlkPSJnMzAiIHRyYW5zZm9ybT0idHJhbnNsYXRlKC01MCwtNTApIj4KICAgICAgICAgICAgICAgICAgICAgIDxnIGlkPSJnMzIiPgogICAgICAgICAgICAgICAgICAgICAgICA8ZyBpZD0iZzM0IiBjbGlwLXBhdGg9InVybCgjY2xpcFBhdGgzOCkiPgogICAgICAgICAgICAgICAgICAgICAgICAgIDxwYXRoIGQ9Ik0gMCwwIEggMTAwIFYgMTAwIEggMCBaIiBzdHlsZT0iZmlsbDp1cmwoI3JhZGlhbEdyYWRpZW50NDYpO3N0cm9rZTpub25lIiBpZD0icGF0aDQ4IiAvPgogICAgICAgICAgICAgICAgICAgICAgICA8L2c+CiAgICAgICAgICAgICAgICAgICAgICA8L2c+CiAgICAgICAgICAgICAgICAgICAgPC9nPgogICAgICAgICAgICAgICAgICA8L2c+CiAgICAgICAgICAgICAgICA8L2c+CiAgICAgICAgICAgICAgPC9nPgogICAgICAgICAgICA8L2c+CiAgICAgICAgICAgIDxwYXRoIGQ9Ik0gNTYuNjkzNjIsMCAxMTMuMzg3MjQsMTEzLjM4NzI0IDE3MC4wODA4NiwwIFoiIHN0eWxlPSJmaWxsOm5vbmU7c3Ryb2tlOiM5OTk5ZmY7c3Ryb2tlLXdpZHRoOjAuMzk4NTtzdHJva2UtbGluZWNhcDpidXR0O3N0cm9rZS1saW5lam9pbjptaXRlcjtzdHJva2UtbWl0ZXJsaW1pdDoxMDtzdHJva2UtZGFzaGFycmF5Om5vbmU7c3Ryb2tlLW9wYWNpdHk6MSIgaWQ9InBhdGg1MCIgLz4KICAgICAgICAgICAgPGcgaWQ9Imc1MiI+CiAgICAgICAgICAgICAgPGcgaWQ9Imc1NCIgdHJhbnNmb3JtPSJ0cmFuc2xhdGUoNjMuMzM3LDUuNDU3KSI+CiAgICAgICAgICAgICAgICA8ZyBpZD0iZzU2Ij4KICAgICAgICAgICAgICAgICAgPGcgaWQ9Imc1OCIgdHJhbnNmb3JtPSJ0cmFuc2xhdGUoLTM2LjczMSwtNS42NTYpIj4KICAgICAgICAgICAgICAgICAgICA8dGV4dCB4bWw6c3BhY2U9InByZXNlcnZlIiB0cmFuc2Zvcm09Im1hdHJpeCgxLDAsMCwtMSwzNi43MzEsNS42NTYpIiBzdHlsZT0iZm9udC12YXJpYW50Om5vcm1hbDtmb250LXdlaWdodDpub3JtYWw7Zm9udC1zaXplOjkuOTYyNnB4O2ZvbnQtZmFtaWx5OkNNU1MxMDstaW5rc2NhcGUtZm9udC1zcGVjaWZpY2F0aW9uOkNNU1MxMDt3cml0aW5nLW1vZGU6bHItdGI7ZmlsbDojOTk5OWZmO2ZpbGwtb3BhY2l0eToxO2ZpbGwtcnVsZTpub256ZXJvO3N0cm9rZTpub25lIiBpZD0idGV4dDYyIj48dHNwYW4geD0iMCA0Ljk4MTI5OTkgOC4zODU1MiAxMy4xNzM1NDYgMTguMzIxMjIyIDIwLjcwMTI4NiAyNS4xMjg2NjYgMzAuMjc2MzQgMzcuMTkxMzgzIDQxLjAxMDA0OCA0Ni4xNTc3MjIgNTAuOTQ1NzQ3IDU2LjA5MzQyMiA2MC41MjA4MDIgNjguOTk1OTg3IDcyLjU5MzQ4MyA3NS45OTc3MDQgNzguMzc3NzY5IDgzLjE2NTc5NCA4OC4zMDM1MDUgOTMuMjg0ODA1IDk1LjY2NDg3MSIgeT0iMCIgaWQ9InRzcGFuNjAiPmdyYWRpZW50c2hhZGVkdHJpYW5nbGU8L3RzcGFuPjwvdGV4dD4KICAgICAgICAgICAgICAgICAgICA8ZyBpZD0iZzY0IiB0cmFuc2Zvcm09InRyYW5zbGF0ZSgzNi43MzEsNS42NTYpIiAvPgogICAgICAgICAgICAgICAgICA8L2c+CiAgICAgICAgICAgICAgICA8L2c+CiAgICAgICAgICAgICAgICA8ZyBpZD0iZzY2IiB0cmFuc2Zvcm09InRyYW5zbGF0ZSgtNjMuMzM3LC01LjQ1NykiIC8+CiAgICAgICAgICAgICAgPC9nPgogICAgICAgICAgICA8L2c+CiAgICAgICAgICA8L2c+CiAgICAgICAgPC9nPgogICAgICA8L2c+CiAgICA8L2c+CiAgPC9nPgo8L3N2Zz4K" /></p>
+
+```
diff --git a/test/command/9467.svg b/test/command/9467.svg
new file mode 100644
--- /dev/null
+++ b/test/command/9467.svg
@@ -0,0 +1,56 @@
+<?xml version="1.0" encoding="UTF-9" standalone="no"?>
+<!-- Created with Inkscape (http://www.inkscape.org/) -->
+
+<svg
+   version="1.1" id="svg2" width="191.56267" height="151.71201" viewBox="0 0 191.56267 151.71201" xmlns="http://www.w3.org/2000/svg" xmlns:svg="http://www.w3.org/2000/svg">
+  <defs id="defs6">
+    <clipPath clipPathUnits="userSpaceOnUse" id="clipPath24">
+      <path d="M 56.69362,0 113.38724,113.38724 170.08086,0 Z" id="path22" />
+    </clipPath>
+    <clipPath clipPathUnits="userSpaceOnUse" id="clipPath38">
+      <path d="M 0,0 H 100 V 100 H 0 Z" id="path36" />
+    </clipPath>
+    <radialGradient fx="50.000641" fy="50.000641" cx="50.000641" cy="50.000641" r="50.000641" gradientUnits="userSpaceOnUse" id="radialGradient46">
+      <stop style="stop-opacity:1;stop-color:#ffffff" offset="0" id="stop40" />
+      <stop style="stop-opacity:1;stop-color:#9999ff" offset="25.00032" id="stop42" />
+      <stop style="stop-opacity:1;stop-color:#9999ff" offset="50.00064" id="stop44" />
+    </radialGradient>
+  </defs>
+  <g id="g8" transform="matrix(1.3333333,0,0,-1.3333333,0,151.712)">
+    <g id="g10" transform="translate(-26.606,0.199)">
+      <g id="g12">
+        <g id="g14">
+          <g id="g16">
+            <g id="g18">
+              <g id="g20" clip-path="url(#clipPath24)">
+                <g id="g26" transform="matrix(2.26802,0,0,2.26802,113.38724,56.69362)">
+                  <g id="g28">
+                    <g id="g30" transform="translate(-50,-50)">
+                      <g id="g32">
+                        <g id="g34" clip-path="url(#clipPath38)">
+                          <path d="M 0,0 H 100 V 100 H 0 Z" style="fill:url(#radialGradient46);stroke:none" id="path48" />
+                        </g>
+                      </g>
+                    </g>
+                  </g>
+                </g>
+              </g>
+            </g>
+            <path d="M 56.69362,0 113.38724,113.38724 170.08086,0 Z" style="fill:none;stroke:#9999ff;stroke-width:0.3985;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:10;stroke-dasharray:none;stroke-opacity:1" id="path50" />
+            <g id="g52">
+              <g id="g54" transform="translate(63.337,5.457)">
+                <g id="g56">
+                  <g id="g58" transform="translate(-36.731,-5.656)">
+                    <text xml:space="preserve" transform="matrix(1,0,0,-1,36.731,5.656)" style="font-variant:normal;font-weight:normal;font-size:9.9626px;font-family:CMSS10;-inkscape-font-specification:CMSS10;writing-mode:lr-tb;fill:#9999ff;fill-opacity:1;fill-rule:nonzero;stroke:none" id="text62"><tspan x="0 4.9812999 8.38552 13.173546 18.321222 20.701286 25.128666 30.27634 37.191383 41.010048 46.157722 50.945747 56.093422 60.520802 68.995987 72.593483 75.997704 78.377769 83.165794 88.303505 93.284805 95.664871" y="0" id="tspan60">gradientshadedtriangle</tspan></text>
+                    <g id="g64" transform="translate(36.731,5.656)" />
+                  </g>
+                </g>
+                <g id="g66" transform="translate(-63.337,-5.457)" />
+              </g>
+            </g>
+          </g>
+        </g>
+      </g>
+    </g>
+  </g>
+</svg>
diff --git a/test/command/9472.md b/test/command/9472.md
new file mode 100644
--- /dev/null
+++ b/test/command/9472.md
@@ -0,0 +1,85 @@
+```
+% pandoc -t latex -s
+---
+lang: de-DE
+---
+
+More text in English. ['Zitat auf Deutsch.']{lang=de}
+
+[Bonjour]{lang=fr} [café]{lang="fr-FR"}
+^D
+% Options for packages loaded elsewhere
+\PassOptionsToPackage{unicode}{hyperref}
+\PassOptionsToPackage{hyphens}{url}
+\documentclass[
+  french,
+  ngerman,
+]{article}
+\usepackage{xcolor}
+\usepackage{amsmath,amssymb}
+\setcounter{secnumdepth}{-\maxdimen} % remove section numbering
+\usepackage{iftex}
+\ifPDFTeX
+  \usepackage[T1]{fontenc}
+  \usepackage[utf8]{inputenc}
+  \usepackage{textcomp} % provide euro and other symbols
+\else % if luatex or xetex
+  \usepackage{unicode-math} % this also loads fontspec
+  \defaultfontfeatures{Scale=MatchLowercase}
+  \defaultfontfeatures[\rmfamily]{Ligatures=TeX,Scale=1}
+\fi
+\usepackage{lmodern}
+\ifPDFTeX\else
+  % xetex/luatex font selection
+\fi
+% Use upquote if available, for straight quotes in verbatim environments
+\IfFileExists{upquote.sty}{\usepackage{upquote}}{}
+\IfFileExists{microtype.sty}{% use microtype if available
+  \usepackage[]{microtype}
+  \UseMicrotypeSet[protrusion]{basicmath} % disable protrusion for tt fonts
+}{}
+\makeatletter
+\@ifundefined{KOMAClassName}{% if non-KOMA class
+  \IfFileExists{parskip.sty}{%
+    \usepackage{parskip}
+  }{% else
+    \setlength{\parindent}{0pt}
+    \setlength{\parskip}{6pt plus 2pt minus 1pt}}
+}{% if KOMA class
+  \KOMAoptions{parskip=half}}
+\makeatother
+\ifLuaTeX
+\usepackage[bidi=basic,shorthands=off]{babel}
+\else
+\usepackage[bidi=default,shorthands=off]{babel}
+\fi
+\ifLuaTeX
+  \usepackage{selnolig} % disable illegal ligatures
+\fi
+\setlength{\emergencystretch}{3em} % prevent overfull lines
+\providecommand{\tightlist}{%
+  \setlength{\itemsep}{0pt}\setlength{\parskip}{0pt}}
+\usepackage{bookmark}
+\IfFileExists{xurl.sty}{\usepackage{xurl}}{} % add URL line breaks if available
+\urlstyle{same}
+% fallback for those not using the hyperref driver hyperxmp:
+\makeatletter
+\@ifundefined{xmpquote}{\newcommand{\xmpquote}[1]{#1}}{}
+\makeatother
+\hypersetup{
+  pdflang={de-DE},
+  hidelinks,
+  pdfcreator={LaTeX via pandoc}}
+
+\author{}
+\date{}
+
+\begin{document}
+
+More text in English. \foreignlanguage{ngerman}{`Zitat auf Deutsch.'}
+
+\foreignlanguage{french}{Bonjour} \foreignlanguage{french}{café}
+
+\end{document}
+
+```
diff --git a/test/command/9475.md b/test/command/9475.md
new file mode 100644
--- /dev/null
+++ b/test/command/9475.md
@@ -0,0 +1,102 @@
+```
+% pandoc -f org -t native
+#+begin_note
+Useful note.
+#+end_note
+
+#+begin_warning
+Be careful!
+#+end_warning
+
+#+begin_tip
+Try this...
+#+end_tip
+
+#+begin_caution
+Caution
+#+end_caution
+
+#+name: foo
+#+begin_important
+Important
+#+end_important
+^D
+[ Div
+    ( "" , [ "note" ] , [] )
+    [ Div ( "" , [ "title" ] , [] ) [ Para [ Str "Note" ] ]
+    , Para [ Str "Useful" , Space , Str "note." ]
+    ]
+, Div
+    ( "" , [ "warning" ] , [] )
+    [ Div ( "" , [ "title" ] , [] ) [ Para [ Str "Warning" ] ]
+    , Para [ Str "Be" , Space , Str "careful!" ]
+    ]
+, Div
+    ( "" , [ "tip" ] , [] )
+    [ Div ( "" , [ "title" ] , [] ) [ Para [ Str "Tip" ] ]
+    , Para [ Str "Try" , Space , Str "this\8230" ]
+    ]
+, Div
+    ( "" , [ "caution" ] , [] )
+    [ Div ( "" , [ "title" ] , [] ) [ Para [ Str "Caution" ] ]
+    , Para [ Str "Caution" ]
+    ]
+, Div
+    ( "foo" , [ "important" ] , [] )
+    [ Div ( "" , [ "title" ] , [] ) [ Para [ Str "Important" ] ]
+    , Para [ Str "Important" ]
+    ]
+]
+
+```
+
+```
+% pandoc -f native -t org
+[ Div
+    ( "" , [ "note" ] , [] )
+    [ Div ( "" , [ "title" ] , [] ) [ Para [ Str "Note" ] ]
+    , Para [ Str "Useful" , Space , Str "note." ]
+    ]
+, Div
+    ( "" , [ "warning" ] , [] )
+    [ Div ( "" , [ "title" ] , [] ) [ Para [ Str "Warning" ] ]
+    , Para [ Str "Be" , Space , Str "careful!" ]
+    ]
+, Div
+    ( "" , [ "tip" ] , [] )
+    [ Div ( "" , [ "title" ] , [] ) [ Para [ Str "Tip" ] ]
+    , Para [ Str "Try" , Space , Str "this\8230" ]
+    ]
+, Div
+    ( "" , [ "caution" ] , [] )
+    [ Div ( "" , [ "title" ] , [] ) [ Para [ Str "Caution" ] ]
+    , Para [ Str "Caution" ]
+    ]
+, Div
+    ( "foo" , [ "important" ] , [] )
+    [ Div ( "" , [ "title" ] , [] ) [ Para [ Str "Important" ] ]
+    , Para [ Str "Important" ]
+    ]
+]
+^D
+#+begin_note
+Useful note.
+#+end_note
+
+#+begin_warning
+Be careful!
+#+end_warning
+
+#+begin_tip
+Try this...
+#+end_tip
+
+#+begin_caution
+Caution
+#+end_caution
+
+#+name: foo
+#+begin_important
+Important
+#+end_important
+```
diff --git a/test/command/9478.md b/test/command/9478.md
new file mode 100644
--- /dev/null
+++ b/test/command/9478.md
@@ -0,0 +1,9 @@
+```
+% pandoc -t typst --wrap=preserve
+**- a -
+- b**
+^D
+#strong[\- a -
+\- b]
+```
+
diff --git a/test/command/9481.md b/test/command/9481.md
new file mode 100644
--- /dev/null
+++ b/test/command/9481.md
@@ -0,0 +1,7 @@
+```
+% pandoc -f markdown+wikilinks_title_after_pipe
+[a](https://example.com)
+^D
+<p><a href="https://example.com">a</a></p>
+
+```
diff --git a/test/command/9516.md b/test/command/9516.md
new file mode 100644
--- /dev/null
+++ b/test/command/9516.md
@@ -0,0 +1,17 @@
+```
+% pandoc --number-sections
+# One {-}
+
+# Two
+
+# Three {-}
+
+# Four
+^D
+<h1 class="unnumbered" id="one">One</h1>
+<h1 data-number="1" id="two"><span
+class="header-section-number">1</span> Two</h1>
+<h1 class="unnumbered" id="three">Three</h1>
+<h1 data-number="2" id="four"><span
+class="header-section-number">2</span> Four</h1>
+```
diff --git a/test/command/9517.md b/test/command/9517.md
new file mode 100644
--- /dev/null
+++ b/test/command/9517.md
@@ -0,0 +1,34 @@
+```
+% pandoc -f latex+raw_tex -t native
+\begin{tabular}{l}
+\begin{theorem}
+Cats
+\end{theorem}
+\end{tabular}
+^D
+[ Table
+    ( "" , [] , [] )
+    (Caption Nothing [])
+    [ ( AlignLeft , ColWidthDefault ) ]
+    (TableHead ( "" , [] , [] ) [])
+    [ TableBody
+        ( "" , [] , [] )
+        (RowHeadColumns 0)
+        []
+        [ Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ RawBlock
+                    (Format "latex")
+                    "\\begin{theorem}\nCats\n\\end{theorem}"
+                ]
+            ]
+        ]
+    ]
+    (TableFoot ( "" , [] , [] ) [])
+]
+```
diff --git a/test/command/9555.md b/test/command/9555.md
new file mode 100644
--- /dev/null
+++ b/test/command/9555.md
@@ -0,0 +1,13 @@
+```
+% pandoc -t native -f latex
+a\@ b\@c
+
+\makeatletter
+a\@ b\@c
+\makeatother
+a\@ b\@c
+^D
+[ Para [ Str "a" , Space , Str "bc" ]
+, Para [ Str "ab" , SoftBreak , Str "a" , Space , Str "bc" ]
+]
+```
diff --git a/test/command/9569.md b/test/command/9569.md
new file mode 100644
--- /dev/null
+++ b/test/command/9569.md
@@ -0,0 +1,19 @@
+```
+% pandoc -f docbook -t gfm
+<note>
+  <para>Some content</para>
+</note>
+<para>Spacer.</para>
+<note>
+  <title>A note with a title. Works, but the title is discarded.</title>
+  <para>Some content</para>
+</note>
+^D
+> [!NOTE]
+> Some content
+
+Spacer.
+
+> [!NOTE]
+> Some content
+```
diff --git a/test/command/9576.md b/test/command/9576.md
new file mode 100644
--- /dev/null
+++ b/test/command/9576.md
@@ -0,0 +1,23 @@
+```
+% pandoc -t native
+::: {#something}
+Text with a footnote.[^3]
+
+[^3]: A footnote.
+:::
+^D
+[ Div
+    ( "something" , [] , [] )
+    [ Para
+        [ Str "Text"
+        , Space
+        , Str "with"
+        , Space
+        , Str "a"
+        , Space
+        , Str "footnote."
+        , Note [ Para [ Str "A" , Space , Str "footnote." ] ]
+        ]
+    ]
+]
+```
diff --git a/test/command/9579.md b/test/command/9579.md
new file mode 100644
--- /dev/null
+++ b/test/command/9579.md
@@ -0,0 +1,46 @@
+```
+% pandoc -t native
+\begin{tabular}{p{2in}}
+\end{tabular}
+
+# Test
+
+\begin{tabular}{p{2\linewidth}}
+\end{tabular}
+^D
+[ RawBlock
+    (Format "tex") "\\begin{tabular}{p{2in}}\n\\end{tabular}"
+, Header 1 ( "test" , [] , [] ) [ Str "Test" ]
+, RawBlock
+    (Format "tex")
+    "\\begin{tabular}{p{2\\linewidth}}\n\\end{tabular}"
+]
+```
+
+```
+% pandoc -f latex -t native
+\begin{tabular}{p{2in}}
+\end{tabular}
+
+Test
+
+\begin{tabular}{p{2\linewidth}}
+\end{tabular}
+^D
+[ Table
+    ( "" , [] , [] )
+    (Caption Nothing [])
+    [ ( AlignLeft , ColWidthDefault ) ]
+    (TableHead ( "" , [] , [] ) [])
+    [ TableBody ( "" , [] , [] ) (RowHeadColumns 0) [] [] ]
+    (TableFoot ( "" , [] , [] ) [])
+, Para [ Str "Test" ]
+, Table
+    ( "" , [] , [] )
+    (Caption Nothing [])
+    [ ( AlignLeft , ColWidth 2.0 ) ]
+    (TableHead ( "" , [] , [] ) [])
+    [ TableBody ( "" , [] , [] ) (RowHeadColumns 0) [] [] ]
+    (TableFoot ( "" , [] , [] ) [])
+]
+```
diff --git a/test/command/9585.md b/test/command/9585.md
new file mode 100644
--- /dev/null
+++ b/test/command/9585.md
@@ -0,0 +1,11 @@
+```
+% pandoc -f native -t typst
+[ Header 2 ( "" , [] , [] ) [ Str "One" ]
+, Header 2 ( "" , [ "unnumbered", "unlisted" ] , [] ) [ Str "Two" ]
+, Header 2 ( "" , [] , [] ) [ Str "Three" ]
+]
+^D
+== One
+#heading(level: 2, outlined: false, numbering: none)[Two]
+== Three
+```
diff --git a/test/command/9586.md b/test/command/9586.md
new file mode 100644
--- /dev/null
+++ b/test/command/9586.md
@@ -0,0 +1,7 @@
+```
+% pandoc -t typst
+**1. April 2024**
+^D
+#strong[\1. April 2024]
+
+```
diff --git a/test/command/9597.md b/test/command/9597.md
new file mode 100644
--- /dev/null
+++ b/test/command/9597.md
@@ -0,0 +1,6 @@
+```
+% pandoc -t latex
+~~$T$~~
+^D
+\st{$T$}
+```
diff --git a/test/command/9603.docx b/test/command/9603.docx
new file mode 100644
Binary files /dev/null and b/test/command/9603.docx differ
diff --git a/test/command/9603.md b/test/command/9603.md
new file mode 100644
--- /dev/null
+++ b/test/command/9603.md
@@ -0,0 +1,23 @@
+```
+% pandoc command/9603.docx -t html -f docx+styles
+^D
+<p>A table with a contemporary style:</p>
+<table data-custom-style="TableContemporary">
+<colgroup>
+<col style="width: 50%" />
+<col style="width: 50%" />
+</colgroup>
+<thead>
+<tr>
+<th>Test</th>
+<th>Column</th>
+</tr>
+</thead>
+<tbody>
+<tr>
+<td>1</td>
+<td>2</td>
+</tr>
+</tbody>
+</table>
+```
diff --git a/test/command/9616.md b/test/command/9616.md
new file mode 100644
--- /dev/null
+++ b/test/command/9616.md
@@ -0,0 +1,16 @@
+```
+% pandoc -f bibtex -t csljson -s
+@MISC {3252037,
+    TITLE = {Isomorphism between projective varieties $\mathbf{P}^{1}$ and a conic in $\mathbf{P}^{2}$},
+    URL = {https://math.stackexchange.com/q/3252037}
+}
+^D
+[
+  {
+    "URL": "https://math.stackexchange.com/q/3252037",
+    "id": "3252037",
+    "title": "Isomorphism between projective varieties $\\mathbf{P}^{1}$ and a conic in $\\mathbf{P}^{2}$",
+    "type": ""
+  }
+]
+```
diff --git a/test/command/9630.md b/test/command/9630.md
new file mode 100644
--- /dev/null
+++ b/test/command/9630.md
@@ -0,0 +1,12 @@
+```
+% pandoc -f dokuwiki
+  * [[https://example.com|https://example.com]]
+  * [[https://example.com/start#monitoring|https://example.com/start#monitoring]]
+^D
+<ul>
+<li><a href="https://example.com">https://example.com</a></li>
+<li><a
+href="https://example.com/start#monitoring">https://example.com/start#monitoring</a></li>
+</ul>
+
+```
diff --git a/test/command/9632.md b/test/command/9632.md
new file mode 100644
--- /dev/null
+++ b/test/command/9632.md
@@ -0,0 +1,7 @@
+```
+% pandoc -f dokuwiki
+[[.:supprimer-profil-windows|]]
+^D
+<p><a href="supprimer-profil-windows">supprimer-profil-windows</a></p>
+
+```
diff --git a/test/command/9635.md b/test/command/9635.md
new file mode 100644
--- /dev/null
+++ b/test/command/9635.md
@@ -0,0 +1,16 @@
+```
+% pandoc
+> ::: {.fence}
+> that is
+> not closed
+
+okay
+^D
+2> [WARNING] Div at _chunk line 1 column 1 unclosed at _chunk line 5 column 1, closing implicitly.
+<blockquote>
+<div class="fence">
+<p>that is not closed</p>
+</div>
+</blockquote>
+<p>okay</p>
+```
diff --git a/test/command/9639.md b/test/command/9639.md
new file mode 100644
--- /dev/null
+++ b/test/command/9639.md
@@ -0,0 +1,11 @@
+```
+% pandoc -f org -t native
+#+title: repro
+
+* heading-name
+:PROPERTIES:
+:ID:       123abc
+:END:
+^D
+[ Header 1 ( "123abc" , [] , [] ) [ Str "heading-name" ] ]
+```
diff --git a/test/command/9644.md b/test/command/9644.md
new file mode 100644
--- /dev/null
+++ b/test/command/9644.md
@@ -0,0 +1,7 @@
+```
+% pandoc -t latex
+[$T$]{.underline}
+[$T$]{.mark}
+^D
+\ul{$T$} \hl{$T$}
+```
diff --git a/test/command/9652.md b/test/command/9652.md
new file mode 100644
--- /dev/null
+++ b/test/command/9652.md
@@ -0,0 +1,9 @@
+````
+% pandoc -f markdown -t html --embed-resources
+```{=html}
+<img class="something inline-svg" src="command/9652.svg" />
+```
+^D
+<svg id="svg_b627f92299158b36552b" role="img" width="504.00pt" height="360.00pt" viewBox="0 0 504.00 360.00" class="something inline-svg please-do-not-delete-me">
+</svg>
+````
diff --git a/test/command/9652.svg b/test/command/9652.svg
new file mode 100644
--- /dev/null
+++ b/test/command/9652.svg
@@ -0,0 +1,3 @@
+<?xml version='1.0' encoding='UTF-8' ?>
+<svg xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' class='please-do-not-delete-me' width='504.00pt' height='360.00pt' viewBox='0 0 504.00 360.00'>
+</svg>
diff --git a/test/command/9657.md b/test/command/9657.md
new file mode 100644
--- /dev/null
+++ b/test/command/9657.md
@@ -0,0 +1,7 @@
+```
+% pandoc -t opendocument
+[Text here]{custom-style="Strikethrough"}
+^D
+<text:p text:style-name="Text_20_body"><text:span text:style-name="Strikethrough">Text
+here</text:span></text:p>
+```
diff --git a/test/command/9676.md b/test/command/9676.md
new file mode 100644
--- /dev/null
+++ b/test/command/9676.md
@@ -0,0 +1,9 @@
+```
+% pandoc -f latex
+\def\foo{BAR}
+\foo
+\ifstrequal{BAR}{BAR}{\def\foo{BAZ}}{}
+\foo
+^D
+<p>BAR BAZ</p>
+```
diff --git a/test/command/9700.md b/test/command/9700.md
new file mode 100644
--- /dev/null
+++ b/test/command/9700.md
@@ -0,0 +1,14 @@
+```
+% pandoc -t mediawiki
+This is a normal sentence with a manual text footnote\*
+
+\* The footnote explains why it couldn't just be inside parentheses
+
+\#foobar \#foobar
+^D
+This is a normal sentence with a manual text footnote*
+
+<nowiki></nowiki>* The footnote explains why it couldn’t just be inside parentheses
+
+<nowiki></nowiki>#foobar #foobar
+```
diff --git a/test/command/9716.md b/test/command/9716.md
new file mode 100644
--- /dev/null
+++ b/test/command/9716.md
@@ -0,0 +1,13 @@
+```
+% pandoc -f markdown+alerts -t native
+> [!TIP]
+> A suggestion.
+^D
+[ Div
+    ( "" , [ "tip" ] , [] )
+    [ Div ( "" , [ "title" ] , [] ) [ Para [ Str "Tip" ] ]
+    , Para [ Str "A" , Space , Str "suggestion." ]
+    ]
+]
+
+```
diff --git a/test/command/9777-b.md b/test/command/9777-b.md
new file mode 100644
--- /dev/null
+++ b/test/command/9777-b.md
@@ -0,0 +1,62 @@
+```
+% pandoc -f native -t typst
+[ Table
+    ( "" , [] , [ ( "typst:figure:kind" , "figure" ) ] )
+    (Caption Nothing [])
+    [ ( AlignDefault , ColWidthDefault )
+    , ( AlignDefault , ColWidthDefault )
+    ]
+    (TableHead
+       ( "" , [] , [] )
+       [ Row
+           ( "" , [] , [] )
+           [ Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "f" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "b" ] ]
+           ]
+       ])
+    [ TableBody
+        ( "" , [] , [] )
+        (RowHeadColumns 0)
+        []
+        [ Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "1" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "2" ] ]
+            ]
+        ]
+    ]
+    (TableFoot ( "" , [] , [] ) [])
+]
+^D
+#figure(
+  align(center)[#table(
+    columns: 2,
+    align: (auto,auto,),
+    table.header([f], [b],),
+    table.hline(),
+    [1], [2],
+  )]
+  , kind: figure
+  )
+```
+
diff --git a/test/command/9777.md b/test/command/9777.md
new file mode 100644
--- /dev/null
+++ b/test/command/9777.md
@@ -0,0 +1,58 @@
+```
+% pandoc -f native -t typst
+[ Table
+    ( "" , [ "typst:no-figure" ] , [] )
+    (Caption Nothing [])
+    [ ( AlignDefault , ColWidthDefault )
+    , ( AlignDefault , ColWidthDefault )
+    ]
+    (TableHead
+       ( "" , [] , [] )
+       [ Row
+           ( "" , [] , [] )
+           [ Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "f" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "b" ] ]
+           ]
+       ])
+    [ TableBody
+        ( "" , [] , [] )
+        (RowHeadColumns 0)
+        []
+        [ Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "1" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "2" ] ]
+            ]
+        ]
+    ]
+    (TableFoot ( "" , [] , [] ) [])
+]
+^D
+#table(
+  columns: 2,
+  align: (auto,auto,),
+  table.header([f], [b],),
+  table.hline(),
+  [1], [2],
+)
+```
diff --git a/test/command/9792.md b/test/command/9792.md
new file mode 100644
--- /dev/null
+++ b/test/command/9792.md
@@ -0,0 +1,21 @@
+```
+% pandoc -t gfm
+- list item
+  <details>
+
+  - subitem
+  </details>
+
+  item _continue_ **with** formatting
+- next list item
+^D
+- list item
+  <details>
+
+  - subitem
+
+  </details>
+
+  item *continue* **with** formatting
+- next list item
+```
diff --git a/test/command/9797.md b/test/command/9797.md
new file mode 100644
--- /dev/null
+++ b/test/command/9797.md
@@ -0,0 +1,39 @@
+```
+% pandoc -t native -f csv
+"one_line_break:
+four_line_breaks:
+
+
+
+last_line"
+^D
+[ Table
+    ( "" , [] , [] )
+    (Caption Nothing [])
+    [ ( AlignDefault , ColWidthDefault ) ]
+    (TableHead
+       ( "" , [] , [] )
+       [ Row
+           ( "" , [] , [] )
+           [ Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain
+                   [ Str "one_line_break:"
+                   , LineBreak
+                   , Str "four_line_breaks:"
+                   , LineBreak
+                   , LineBreak
+                   , LineBreak
+                   , LineBreak
+                   , Str "last_line"
+                   ]
+               ]
+           ]
+       ])
+    [ TableBody ( "" , [] , [] ) (RowHeadColumns 0) [] [] ]
+    (TableFoot ( "" , [] , [] ) [])
+]
+```
diff --git a/test/command/9805.md b/test/command/9805.md
new file mode 100644
--- /dev/null
+++ b/test/command/9805.md
@@ -0,0 +1,10 @@
+```
+% pandoc -f rst -t native
+word.*word
+------------
+* abc
+^D
+[ Header 1 ( "word.word" , [] , [] ) [ Str "word.*word" ]
+, BulletList [ [ Plain [ Str "abc" ] ] ]
+]
+```
diff --git a/test/command/9807.md b/test/command/9807.md
new file mode 100644
--- /dev/null
+++ b/test/command/9807.md
@@ -0,0 +1,13 @@
+```
+% pandoc -f typst -t native
+#let foo = [
+  bar baz
+]
+*#foo*
+^D
+[ Para
+    [ Strong
+        [ SoftBreak , Str "bar" , Space , Str "baz" , SoftBreak ]
+    ]
+]
+```
diff --git a/test/command/9809.md b/test/command/9809.md
new file mode 100644
--- /dev/null
+++ b/test/command/9809.md
@@ -0,0 +1,14 @@
+```
+% pandoc -f html -t native
+<ul>
+  <li>Bullet point.</li>
+  <p>Nested line.</p>
+</ul>
+^D
+[ BulletList
+    [ [ Para [ Str "Bullet" , Space , Str "point." ]
+      , Para [ Str "Nested" , Space , Str "line." ]
+      ]
+    ]
+]
+```
diff --git a/test/command/982.md b/test/command/982.md
--- a/test/command/982.md
+++ b/test/command/982.md
@@ -7,5 +7,9 @@
 y=x^2
 \EEQ
 ^D
-[Para [Math DisplayMath "y=x^2"]]
+[ Para
+    [ Math
+        DisplayMath "\\begin{equation}\ny=x^2\n\\end{equation}"
+    ]
+]
 ```
diff --git a/test/command/9865.md b/test/command/9865.md
new file mode 100644
--- /dev/null
+++ b/test/command/9865.md
@@ -0,0 +1,53 @@
+````
+% pandoc
+- example 1
+- ```
+  one
+  two
+  ```
+- list item three
+^D
+<ul>
+<li>example 1</li>
+<li><pre><code>one
+two</code></pre></li>
+<li>list item three</li>
+</ul>
+````
+
+````
+% pandoc
+- example 3
+- ```
+one
+two
+```
+- list item three
+^D
+<ul>
+<li>example 3</li>
+<li><pre><code>one
+two</code></pre></li>
+<li>list item three</li>
+</ul>
+````
+
+Here is a case that we used to handle differently, but
+#9865 aligns pandoc's markdown parser with commonmark in letting
+block level structure take precedence over inline level structure.
+
+````
+% pandoc
+- a <!--
+
+- b
+
+-->
+- c
+^D
+<ul>
+<li><p>a &lt;!–</p></li>
+<li><p>b</p></li>
+</ul>
+<p>–&gt; - c</p>
+````
diff --git a/test/command/987.md b/test/command/987.md
--- a/test/command/987.md
+++ b/test/command/987.md
@@ -1,5 +1,5 @@
 ```
-pandoc -f latex -t markdown
+% pandoc -f latex -t markdown
 \documentclass{article}
 \newenvironment{flubble}{FOO}{BAR}
 \begin{document}
diff --git a/test/command/9878.md b/test/command/9878.md
new file mode 100644
--- /dev/null
+++ b/test/command/9878.md
@@ -0,0 +1,12 @@
+```
+% pandoc -f textile -t native
+15% 50%
+^D
+[ Para [ Str "15%" , Space , Str "50%" ] ]
+```
+```
+% pandoc -f textile -t native
+15%. 70%
+^D
+[ Para [ Str "15%." , Space , Str "70%" ] ]
+```
diff --git a/test/command/9902.md b/test/command/9902.md
new file mode 100644
--- /dev/null
+++ b/test/command/9902.md
@@ -0,0 +1,6 @@
+```
+% pandoc -t native -f latex+raw_tex
+\kern.1pt
+^D
+[ RawBlock (Format "latex") "\\kern.1pt" ]
+```
diff --git a/test/command/9904.md b/test/command/9904.md
new file mode 100644
--- /dev/null
+++ b/test/command/9904.md
@@ -0,0 +1,180 @@
+```
+% pandoc -f rst -t native --citeproc --bibliography command/biblio.bib
+The axioms were introduced by :cite:t:`{see}item1`.
+The axioms were introduced by :cite:t:`item1{p. 1166}`.
+The axioms were introduced by :cite:t:`{see}item1{p. 1166}`.
+Axioms were introduced :cite:`{see}item1`.
+Axioms were introduced :cite:p:`item1{p. 1166}`.
+Axioms were introduced :cite:p:`{see}item1{p. 1166}`.
+
+.. bibliography::
+^D
+[ Para
+    [ Str "The"
+    , Space
+    , Str "axioms"
+    , Space
+    , Str "were"
+    , Space
+    , Str "introduced"
+    , Space
+    , Str "by"
+    , Space
+    , Cite
+        [ Citation
+            { citationId = "item1"
+            , citationPrefix = [ Str "see" ]
+            , citationSuffix = []
+            , citationMode = AuthorInText
+            , citationNoteNum = 0
+            , citationHash = 0
+            }
+        ]
+        [ Str "(see" , Space , Str "Doe;" , Space , Str "2005)" ]
+    , Str "."
+    , SoftBreak
+    , Str "The"
+    , Space
+    , Str "axioms"
+    , Space
+    , Str "were"
+    , Space
+    , Str "introduced"
+    , Space
+    , Str "by"
+    , Space
+    , Cite
+        [ Citation
+            { citationId = "item1"
+            , citationPrefix = []
+            , citationSuffix = [ Str "p." , Space , Str "1166" ]
+            , citationMode = AuthorInText
+            , citationNoteNum = 0
+            , citationHash = 0
+            }
+        ]
+        [ Str "Doe" , Space , Str "(2005," , Space , Str "1166)" ]
+    , Str "."
+    , SoftBreak
+    , Str "The"
+    , Space
+    , Str "axioms"
+    , Space
+    , Str "were"
+    , Space
+    , Str "introduced"
+    , Space
+    , Str "by"
+    , Space
+    , Cite
+        [ Citation
+            { citationId = "item1"
+            , citationPrefix = [ Str "see" ]
+            , citationSuffix = [ Str "p." , Space , Str "1166" ]
+            , citationMode = AuthorInText
+            , citationNoteNum = 0
+            , citationHash = 0
+            }
+        ]
+        [ Str "(see"
+        , Space
+        , Str "Doe;"
+        , Space
+        , Str "2005,"
+        , Space
+        , Str "1166)"
+        ]
+    , Str "."
+    , SoftBreak
+    , Str "Axioms"
+    , Space
+    , Str "were"
+    , Space
+    , Str "introduced"
+    , Space
+    , Cite
+        [ Citation
+            { citationId = "item1"
+            , citationPrefix = [ Str "see" ]
+            , citationSuffix = []
+            , citationMode = NormalCitation
+            , citationNoteNum = 0
+            , citationHash = 0
+            }
+        ]
+        [ Str "(see" , Space , Str "Doe" , Space , Str "2005)" ]
+    , Str "."
+    , SoftBreak
+    , Str "Axioms"
+    , Space
+    , Str "were"
+    , Space
+    , Str "introduced"
+    , Space
+    , Cite
+        [ Citation
+            { citationId = "item1"
+            , citationPrefix = []
+            , citationSuffix = [ Str "p." , Space , Str "1166" ]
+            , citationMode = NormalCitation
+            , citationNoteNum = 0
+            , citationHash = 0
+            }
+        ]
+        [ Str "(Doe" , Space , Str "2005," , Space , Str "1166)" ]
+    , Str "."
+    , SoftBreak
+    , Str "Axioms"
+    , Space
+    , Str "were"
+    , Space
+    , Str "introduced"
+    , Space
+    , Cite
+        [ Citation
+            { citationId = "item1"
+            , citationPrefix = [ Str "see" ]
+            , citationSuffix = [ Str "p." , Space , Str "1166" ]
+            , citationMode = NormalCitation
+            , citationNoteNum = 0
+            , citationHash = 0
+            }
+        ]
+        [ Str "(see"
+        , Space
+        , Str "Doe"
+        , Space
+        , Str "2005,"
+        , Space
+        , Str "1166)"
+        ]
+    , Str "."
+    ]
+, Div
+    ( "refs"
+    , [ "references" , "csl-bib-body" , "hanging-indent" ]
+    , []
+    )
+    [ Div
+        ( "ref-item1" , [ "csl-entry" ] , [] )
+        [ Para
+            [ Str "Doe,"
+            , Space
+            , Str "John."
+            , Space
+            , Str "2005."
+            , Space
+            , Emph [ Str "First" , Space , Str "Book" ]
+            , Str "."
+            , Space
+            , Str "Cambridge"
+            , Space
+            , Str "University"
+            , Space
+            , Str "Press."
+            ]
+        ]
+    ]
+]
+
+```
diff --git a/test/command/9905.md b/test/command/9905.md
new file mode 100644
--- /dev/null
+++ b/test/command/9905.md
@@ -0,0 +1,20 @@
+```
+% pandoc -t html5
+# Section Ψ {#Ψ}
+
+look at [Section Ψ](#Ψ).
+^D
+<h1 id="Ψ">Section Ψ</h1>
+<p>look at <a href="#Ψ">Section Ψ</a>.</p>
+
+```
+```
+% pandoc -t html4
+# Section Ψ {#Ψ}
+
+look at [Section Ψ](#Ψ).
+^D
+<h1 id="Ψ">Section Ψ</h1>
+<p>look at <a href="#%CE%A8">Section Ψ</a>.</p>
+
+```
diff --git a/test/command/9908.md b/test/command/9908.md
new file mode 100644
--- /dev/null
+++ b/test/command/9908.md
@@ -0,0 +1,10 @@
+```
+% pandoc -f native -t markdown
+[ BulletList
+    [ [ BlockQuote [ Para [ Str "a" ] , Para [ Str "b" ] ] ] ]
+]
+^D
+- > a
+  >
+  > b
+```
diff --git a/test/command/9943.md b/test/command/9943.md
new file mode 100644
--- /dev/null
+++ b/test/command/9943.md
@@ -0,0 +1,24 @@
+```
+% pandoc -t man -s -Vpandoc-version=X.Y
+---
+title: HELLO
+section: 1
+---
+^D
+.\" Automatically generated by Pandoc X.Y
+.\"
+.TH "HELLO" "1" "" ""
+```
+
+```
+% pandoc -t man -s -Vpandoc-version=X.Y
+---
+title: HELLO
+section: 1
+header: Head
+---
+^D
+.\" Automatically generated by Pandoc X.Y
+.\"
+.TH "HELLO" "1" "" "" "Head"
+```
diff --git a/test/command/9945.md b/test/command/9945.md
new file mode 100644
--- /dev/null
+++ b/test/command/9945.md
@@ -0,0 +1,28 @@
+```
+% pandoc -t typst --dpi 300
+![](image.jpg){width=300 height=300}
+^D
+#box(image("image.jpg", height: 1in, width: 1in))
+```
+
+```
+% pandoc -t typst --dpi 600
+![](image.jpg){width=300px height=300px}
+^D
+#box(image("image.jpg", height: 0.5in, width: 0.5in))
+```
+
+```
+% pandoc -t typst --dpi 600
+![](image.jpg){width=1in height=3cm}
+^D
+#box(image("image.jpg", height: 3cm, width: 1in))
+```
+
+
+```
+% pandoc -t typst --dpi 600
+![](image.jpg){.foo .bar baz=3}
+^D
+#box(image("image.jpg"))
+```
diff --git a/test/command/9953.md b/test/command/9953.md
new file mode 100644
--- /dev/null
+++ b/test/command/9953.md
@@ -0,0 +1,29 @@
+```
+% pandoc -f markdown -t native -s
+---
+header-includes: |
+    \makeatletter
+    \let\old@verbatim@font=\verbatim@font
+    \def\verbatim@font{%
+    \fontsize{10}{12}%
+    \old@verbatim@font
+    }
+    \makeatother
+...
+^D
+Pandoc
+  Meta
+    { unMeta =
+        fromList
+          [ ( "header-includes"
+            , MetaBlocks
+                [ RawBlock
+                    (Format "tex")
+                    "\\makeatletter\n\\let\\old@verbatim@font=\\verbatim@font\n\\def\\verbatim@font{%\n\\fontsize{10}{12}%\n\\old@verbatim@font\n}\n\\makeatother"
+                ]
+            )
+          ]
+    }
+  []
+
+```
diff --git a/test/command/9987.md b/test/command/9987.md
new file mode 100644
--- /dev/null
+++ b/test/command/9987.md
@@ -0,0 +1,10 @@
+```
+% pandoc -f bibtex -t bibtex
+@misc{agency,
+  author = {{European Environment Agency}},
+}
+^D
+@misc{agency,
+  author = {{European Environment Agency}}
+}
+```
diff --git a/test/command/A.txt b/test/command/A.txt
new file mode 100644
--- /dev/null
+++ b/test/command/A.txt
@@ -0,0 +1,1 @@
+this is a
diff --git a/test/command/B.txt b/test/command/B.txt
new file mode 100644
--- /dev/null
+++ b/test/command/B.txt
@@ -0,0 +1,1 @@
+here is b
diff --git a/test/command/C.txt b/test/command/C.txt
new file mode 100644
--- /dev/null
+++ b/test/command/C.txt
@@ -0,0 +1,1 @@
+and this is c
diff --git a/test/command/D.txt b/test/command/D.txt
new file mode 100644
--- /dev/null
+++ b/test/command/D.txt
@@ -0,0 +1,1 @@
+here's d
diff --git a/test/command/adjacent_latex_blocks.md b/test/command/adjacent_latex_blocks.md
new file mode 100644
--- /dev/null
+++ b/test/command/adjacent_latex_blocks.md
@@ -0,0 +1,10 @@
+```
+% pandoc -f markdown -t native
+\listoffigures
+
+\listoftables
+^D
+[ RawBlock (Format "tex") "\\listoffigures"
+, RawBlock (Format "tex") "\\listoftables"
+]
+```
diff --git a/test/command/advanced-optical-materials.csl b/test/command/advanced-optical-materials.csl
new file mode 100644
--- /dev/null
+++ b/test/command/advanced-optical-materials.csl
@@ -0,0 +1,155 @@
+<?xml version="1.0" encoding="utf-8"?>
+<style xmlns="http://purl.org/net/xbiblio/csl" class="in-text" version="1.0" demote-non-dropping-particle="sort-only" default-locale="en-US">
+  <info>
+    <title>Advanced Optical Materials</title>
+    <id>http://www.zotero.org/styles/advanced-optical-materials</id>
+    <link href="http://www.zotero.org/styles/advanced-optical-materials" rel="self"/>
+    <link href="http://www.zotero.org/styles/small" rel="template"/>
+    <link href="http://onlinelibrary.wiley.com/journal/10.1002/(ISSN)2195-1071/homepage/2298_forauthors.html" rel="documentation"/>
+    <author>
+      <name>Martin F. Schumann</name>
+      <email>mfs@mfs.name</email>
+    </author>
+    <category citation-format="numeric"/>
+    <category field="engineering"/>
+    <eissn>2195-1071</eissn>
+    <summary>A style for Wiley's Advanced Optical Materials</summary>
+    <updated>2017-02-16T15:37:41+00:00</updated>
+    <rights license="http://creativecommons.org/licenses/by-sa/3.0/">This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 License</rights>
+  </info>
+  <macro name="author">
+    <names variable="author">
+      <name initialize-with=". " delimiter=", " delimiter-precedes-last="always"/>
+      <label form="short" prefix=", " text-case="capitalize-first" suffix=" "/>
+      <substitute>
+        <names variable="editor"/>
+        <names variable="translator"/>
+      </substitute>
+    </names>
+  </macro>
+  <macro name="editor">
+    <names variable="editor">
+      <label form="short" text-case="capitalize-first" suffix=".: " strip-periods="true"/>
+      <name initialize-with="." delimiter=", " delimiter-precedes-last="always"/>
+    </names>
+  </macro>
+  <macro name="year-date">
+    <group font-weight="bold">
+      <choose>
+        <if variable="issued">
+          <date variable="issued">
+            <date-part name="year"/>
+          </date>
+        </if>
+        <else>
+          <text term="no date" form="short"/>
+        </else>
+      </choose>
+    </group>
+  </macro>
+  <macro name="access-date">
+    <group delimiter=", ">
+      <date variable="accessed">
+        <date-part name="month" prefix="accessed: " suffix=", " form="short"/>
+        <date-part name="year"/>
+      </date>
+    </group>
+  </macro>
+  <macro name="access">
+    <choose>
+      <if variable="page" match="none">
+        <choose>
+          <if variable="DOI">
+            <text variable="DOI" prefix="DOI: "/>
+          </if>
+        </choose>
+        <choose>
+          <if type="webpage">
+            <text variable="URL"/>
+          </if>
+        </choose>
+      </if>
+    </choose>
+  </macro>
+  <macro name="publisher">
+    <group delimiter=", ">
+      <text variable="publisher" text-case="capitalize-all"/>
+      <text variable="publisher-place" text-case="title"/>
+    </group>
+  </macro>
+  <macro name="pages">
+    <label variable="page" form="short" suffix=" "/>
+    <text variable="page"/>
+  </macro>
+  <citation collapse="citation-number">
+    <sort>
+      <key variable="citation-number"/>
+    </sort>
+    <layout prefix="[" suffix="]" delimiter="," vertical-align="sup">
+      <text variable="citation-number"/>
+    </layout>
+  </citation>
+  <bibliography entry-spacing="0" second-field-align="flush" line-spacing="2">
+    <layout suffix=".">
+      <text variable="citation-number" prefix="[" suffix="]"/>
+      <text macro="author" suffix=", "/>
+      <choose>
+        <if type="bill book graphic legal_case legislation motion_picture report song" match="any">
+          <group delimiter=", ">
+            <text variable="title" text-case="title" font-style="italic"/>
+            <text macro="publisher"/>
+            <text macro="year-date"/>
+          </group>
+        </if>
+        <else-if type="chapter paper-conference" match="any">
+          <group delimiter=", ">
+            <group delimiter=" ">
+              <text term="in"/>
+              <text variable="container-title" form="short" text-case="title" font-style="italic"/>
+              <text macro="editor" prefix="(" suffix=")"/>
+            </group>
+            <text macro="publisher"/>
+            <text macro="year-date"/>
+            <group delimiter=" ">
+              <text macro="pages"/>
+            </group>
+          </group>
+        </else-if>
+        <else-if type="patent">
+          <group delimiter=", ">
+            <text variable="number" font-style="italic"/>
+            <text macro="year-date"/>
+          </group>
+        </else-if>
+        <else-if type="thesis">
+          <group delimiter=", ">
+            <text variable="title" text-case="title"/>
+            <text variable="genre"/>
+            <text variable="publisher"/>
+            <text macro="year-date"/>
+          </group>
+        </else-if>
+        <else-if type="webpage">
+          <group delimiter=", ">
+            <text variable="title"/>
+            <text macro="access"/>
+            <text macro="access-date"/>
+          </group>
+        </else-if>
+        <else>
+          <group delimiter=" ">
+            <text variable="container-title" form="short" font-style="italic"/>
+            <group delimiter=", ">
+              <text macro="year-date"/>
+              <group>
+                <text variable="volume" font-style="italic"/>
+              </group>
+              <text variable="page-first"/>
+            </group>
+          </group>
+          <text macro="access" prefix=", "/>
+        </else>
+      </choose>
+    </layout>
+  </bibliography>
+</style>
diff --git a/test/command/alerts.md b/test/command/alerts.md
new file mode 100644
--- /dev/null
+++ b/test/command/alerts.md
@@ -0,0 +1,55 @@
+```
+% pandoc -f rst -t gfm
+.. note::
+   This is my note.
+^D
+> [!NOTE]
+> This is my note.
+```
+
+```
+% pandoc -f gfm -t rst
+> [!WARNING]
+> Be careful!
+^D
+.. warning::
+
+   Be careful!
+```
+
+```
+% pandoc -f gfm -t asciidoc
+> [!TIP]
+> A tip.
+^D
+[TIP]
+====
+A tip.
+====
+```
+
+```
+% pandoc -f gfm -t docbook
+> [!TIP]
+> A tip.
+^D
+<tip>
+  <title>Tip</title>
+  <para>
+    A tip.
+  </para>
+</tip>
+```
+
+```
+% pandoc -f docbook -t gfm
+<tip>
+  <title>Tip</title>
+  <para>
+    A tip.
+  </para>
+</tip>
+^D
+> [!TIP]
+> A tip.
+```
diff --git a/test/command/american-medical-association.csl b/test/command/american-medical-association.csl
new file mode 100644
--- /dev/null
+++ b/test/command/american-medical-association.csl
@@ -0,0 +1,279 @@
+<?xml version="1.0" encoding="utf-8"?>
+<style xmlns="http://purl.org/net/xbiblio/csl" class="in-text" version="1.0" demote-non-dropping-particle="sort-only" page-range-format="expanded" default-locale="en-US">
+  <info>
+    <title>American Medical Association 11th edition</title>
+    <title-short>AMA (11th ed.)</title-short>
+    <id>http://www.zotero.org/styles/american-medical-association</id>
+    <link href="http://www.zotero.org/styles/american-medical-association" rel="self"/>
+    <link href="http://www.zotero.org/styles/american-medical-association-10th-edition" rel="template"/>
+    <link href="https://westlibrary.txwes.edu/sites/default/files/pdf/AMACitationStyle.pdf" rel="documentation"/>
+    <link href="https://www.amamanualofstyle.com/fileasset/AMAMOS/aaaAMWA%20presentation%20Nov%202019%20FULL.pdf" rel="documentation"/>
+    <author>
+      <name>Julian Onions</name>
+      <email>julian.onions@gmail.com</email>
+    </author>
+    <contributor>
+      <name>Christian Pietsch</name>
+      <uri>http://purl.org/net/pietsch</uri>
+    </contributor>
+    <contributor>
+      <name>Daniel W Chan</name>
+      <email>danwchan@protonmail.com</email>
+    </contributor>
+    <contributor>
+      <name>Patrick O'Brien</name>
+      <email>obrienpat86@gmail.com</email>
+    </contributor>
+    <category citation-format="numeric"/>
+    <category field="medicine"/>
+    <summary>The American Medical Association style as used in JAMA. Version 11 as per November-2019.</summary>
+    <updated>2020-04-23T13:38:04+00:00</updated>
+    <rights license="http://creativecommons.org/licenses/by-sa/3.0/">This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 License</rights>
+  </info>
+  <locale xml:lang="en">
+    <terms>
+      <term name="page-range-delimiter">-</term>
+    </terms>
+  </locale>
+  <macro name="editor">
+    <names variable="editor">
+      <name name-as-sort-order="all" sort-separator=" " initialize-with="" delimiter=", " delimiter-precedes-last="always"/>
+      <label form="short" prefix=", "/>
+    </names>
+  </macro>
+  <macro name="author">
+    <group suffix=".">
+      <names variable="author">
+        <name name-as-sort-order="all" sort-separator=" " initialize-with="" delimiter=", " delimiter-precedes-last="always"/>
+        <label form="short" prefix=", "/>
+        <substitute>
+          <names variable="editor"/>
+          <text macro="title"/>
+        </substitute>
+      </names>
+    </group>
+  </macro>
+  <macro name="access">
+    <choose>
+      <if type="article-newspaper" match="none">
+        <choose>
+          <if variable="DOI">
+            <text value="doi:"/>
+            <text variable="DOI"/>
+          </if>
+          <else-if variable="URL">
+            <group delimiter=". ">
+              <choose>
+                <if type="webpage post post-weblog" match="any">
+                  <date variable="issued" prefix="Published " form="text"/>
+                </if>
+              </choose>
+              <group>
+                <text term="accessed" text-case="capitalize-first" suffix=" "/>
+                <date variable="accessed">
+                  <date-part name="month" suffix=" "/>
+                  <date-part name="day" suffix=", "/>
+                  <date-part name="year"/>
+                </date>
+              </group>
+              <text variable="URL"/>
+            </group>
+          </else-if>
+        </choose>
+      </if>
+    </choose>
+  </macro>
+  <macro name="title">
+    <choose>
+      <if type="bill book graphic legal_case legislation motion_picture report song" match="any">
+        <text variable="title" font-style="italic" text-case="title"/>
+      </if>
+      <else>
+        <text variable="title"/>
+      </else>
+    </choose>
+  </macro>
+  <macro name="publisher">
+    <text variable="publisher"/>
+  </macro>
+  <macro name="edition">
+    <choose>
+      <if is-numeric="edition">
+        <group delimiter=" ">
+          <number variable="edition" form="ordinal"/>
+          <text term="edition" form="short"/>
+        </group>
+      </if>
+      <else>
+        <text variable="edition" suffix="."/>
+      </else>
+    </choose>
+  </macro>
+  <citation collapse="citation-number">
+    <sort>
+      <key variable="citation-number"/>
+    </sort>
+    <layout delimiter="," vertical-align="sup">
+      <text variable="citation-number"/>
+      <group prefix="(" suffix=")">
+        <label variable="locator" form="short" strip-periods="true"/>
+        <text variable="locator"/>
+      </group>
+    </layout>
+  </citation>
+  <bibliography hanging-indent="false" et-al-min="7" et-al-use-first="3" second-field-align="flush">
+    <layout>
+      <text variable="citation-number" suffix=". "/>
+      <text macro="author"/>
+      <text macro="title" prefix=" " suffix="."/>
+      <choose>
+        <if type="bill book graphic legislation motion_picture report song" match="any">
+          <group suffix="." prefix=" " delimiter=" ">
+            <group delimiter=" ">
+              <text term="volume" form="short" text-case="capitalize-first" strip-periods="true"/>
+              <text variable="volume" suffix="."/>
+            </group>
+            <text macro="edition"/>
+            <text macro="editor" prefix="(" suffix=")"/>
+          </group>
+          <text macro="publisher" prefix=" "/>
+          <group suffix="." prefix="; ">
+            <date variable="issued">
+              <date-part name="year"/>
+            </date>
+            <text variable="page" prefix=":"/>
+          </group>
+        </if>
+        <else-if type="chapter paper-conference entry-dictionary entry-encyclopedia" match="any">
+          <group prefix=" " delimiter=" ">
+            <text term="in" text-case="capitalize-first" suffix=":"/>
+            <text macro="editor"/>
+            <text variable="container-title" font-style="italic" suffix="." text-case="title"/>
+            <group delimiter=" ">
+              <text term="volume" form="short" text-case="capitalize-first" strip-periods="true"/>
+              <text variable="volume" suffix="."/>
+            </group>
+            <text macro="edition"/>
+            <text variable="collection-title" suffix="."/>
+            <group suffix=".">
+              <text macro="publisher"/>
+              <group suffix="." prefix="; ">
+                <date variable="issued">
+                  <date-part name="year"/>
+                </date>
+                <text variable="page" prefix=":"/>
+              </group>
+            </group>
+          </group>
+        </else-if>
+        <else-if type="article-newspaper">
+          <text variable="container-title" font-style="italic" prefix=" " suffix=". "/>
+          <choose>
+            <if variable="URL">
+              <group delimiter=". " suffix=".">
+                <text variable="URL"/>
+                <group prefix="Published ">
+                  <date variable="issued">
+                    <date-part name="month" suffix=" "/>
+                    <date-part name="day" suffix=", "/>
+                    <date-part name="year"/>
+                  </date>
+                </group>
+                <group>
+                  <text term="accessed" text-case="capitalize-first" suffix=" "/>
+                  <date variable="accessed">
+                    <date-part name="month" suffix=" "/>
+                    <date-part name="day" suffix=", "/>
+                    <date-part name="year"/>
+                  </date>
+                </group>
+              </group>
+            </if>
+            <else>
+              <group delimiter=":" suffix=".">
+                <group>
+                  <date variable="issued">
+                    <date-part name="month" suffix=" "/>
+                    <date-part name="day" suffix=", "/>
+                    <date-part name="year"/>
+                  </date>
+                </group>
+                <text variable="page"/>
+              </group>
+            </else>
+          </choose>
+        </else-if>
+        <else-if type="legal_case">
+          <group suffix="," prefix=" " delimiter=" ">
+            <text macro="editor" prefix="(" suffix=")"/>
+          </group>
+          <group prefix=" " delimiter=" ">
+            <text variable="container-title"/>
+            <text variable="volume"/>
+          </group>
+          <text variable="page" prefix=", " suffix=" "/>
+          <group prefix="(" suffix=")." delimiter=" ">
+            <text variable="authority"/>
+            <date variable="issued">
+              <date-part name="year"/>
+            </date>
+          </group>
+        </else-if>
+        <else-if type="webpage post post-weblog" match="any">
+          <text variable="container-title" prefix=" " suffix="."/>
+        </else-if>
+        <else-if type="speech">
+          <group prefix=" " suffix=":">
+            <choose>
+              <if variable="genre">
+                <text variable="genre" suffix=" "/>
+                <text term="presented at"/>
+              </if>
+              <else>
+                <text term="presented at" text-case="capitalize-first"/>
+              </else>
+            </choose>
+          </group>
+          <group delimiter="; " prefix=" " suffix=".">
+            <text variable="event"/>
+            <group>
+              <date delimiter=" " variable="issued">
+                <date-part name="month"/>
+                <date-part name="day" suffix=","/>
+                <date-part name="year"/>
+              </date>
+            </group>
+            <text variable="event-place"/>
+          </group>
+        </else-if>
+        <else>
+          <text macro="editor" prefix=" " suffix="."/>
+          <group prefix=" " suffix=".">
+            <text variable="container-title" font-style="italic" form="short" strip-periods="true" suffix="."/>
+            <group delimiter=";" prefix=" ">
+              <choose>
+                <if variable="issue volume" match="any">
+                  <date variable="issued">
+                    <date-part name="year"/>
+                  </date>
+                </if>
+                <else>
+                  <group delimiter=" ">
+                    <text value="Published online"/>
+                    <date form="text" date-parts="year-month-day" variable="issued"/>
+                  </group>
+                </else>
+              </choose>
+              <group>
+                <text variable="volume"/>
+                <text variable="issue" prefix="(" suffix=")"/>
+              </group>
+            </group>
+            <text variable="page" prefix=":"/>
+          </group>
+        </else>
+      </choose>
+      <text prefix=" " macro="access"/>
+    </layout>
+  </bibliography>
+</style>
diff --git a/test/command/annales.csl b/test/command/annales.csl
new file mode 100644
--- /dev/null
+++ b/test/command/annales.csl
@@ -0,0 +1,334 @@
+<?xml version="1.0" encoding="utf-8"?>
+<style xmlns="http://purl.org/net/xbiblio/csl" class="note" default-locale="fr-FR" version="1.0" page-range-format="expanded" demote-non-dropping-particle="sort-only">
+  <info>
+    <title>Annales. Histoire, Sciences sociales (French)</title>
+    <id>http://www.zotero.org/styles/annales</id>
+    <link href="http://www.zotero.org/styles/annales" rel="self"/>
+    <link href="http://annales.ehess.fr/?lang=en/" rel="documentation"/>
+    <author>
+      <name>Franziska Heimburger</name>
+      <email>zotero@franziska.fr</email>
+    </author>
+    <category citation-format="note"/>
+    <category field="social_science"/>
+    <issn>0395-2649</issn>
+    <updated>2013-08-29T04:18:55+00:00</updated>
+    <rights license="http://creativecommons.org/licenses/by-sa/3.0/">This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 License</rights>
+  </info>
+  <locale xml:lang="fr">
+    <terms>
+      <term name="ordinal-01">ère</term>
+      <term name="ordinal-02">e</term>
+      <term name="ordinal-03">e</term>
+      <term name="ordinal-04">e</term>
+      <term name="cited">op.&#160;cit.</term>
+      <term name="page" form="short">
+        <single>p.</single>
+        <multiple>p.</multiple>
+      </term>
+      <term name="editor" form="short">
+        <single>dir.</single>
+        <multiple>dir.</multiple>
+      </term>
+    </terms>
+  </locale>
+  <macro name="author">
+    <names variable="author">
+      <name form="long" and="text" delimiter-precedes-last="never">
+        <name-part name="family" font-variant="small-caps"/>
+      </name>
+      <label form="short" prefix="&#160;(" suffix=")"/>
+      <substitute>
+        <names variable="editor"/>
+        <names variable="translator"/>
+        <text macro="title"/>
+      </substitute>
+    </names>
+  </macro>
+  <macro name="author-short">
+    <names variable="author">
+      <name form="long" and="text" initialize-with=". " delimiter-precedes-last="never">
+        <name-part name="family" font-variant="small-caps"/>
+      </name>
+      <label form="short" prefix="&#160;(" suffix=")"/>
+      <substitute>
+        <names variable="editor"/>
+        <names variable="translator"/>
+        <text macro="title"/>
+      </substitute>
+    </names>
+  </macro>
+  <macro name="editor">
+    <names variable="editor">
+      <name form="long" and="text" delimiter-precedes-last="never" sort-separator=" " font-style="normal">
+      </name>
+      <label form="short" prefix="&#160;(" suffix=".)"/>
+    </names>
+  </macro>
+  <macro name="translator">
+    <names variable="translator">
+      <name form="long" and="text" delimiter-precedes-last="never" sort-separator=" " font-style="normal" prefix=" trad. fr. ">
+        <name-part name="family" font-variant="small-caps"/>
+      </name>
+    </names>
+  </macro>
+  <macro name="title">
+    <choose>
+      <if type="bill book graphic legal_case motion_picture report song" match="any">
+        <text variable="title" text-case="capitalize-first" font-style="italic"/>
+      </if>
+      <else-if type="article-journal article-newspaper article-magazine" match="any">
+        <group delimiter=", ">
+          <text variable="title" text-case="capitalize-first" quotes="true" font-style="normal"/>
+          <text variable="container-title" font-style="italic"/>
+        </group>
+      </else-if>
+      <else-if type="thesis" match="any">
+        <group>
+          <text variable="title" text-case="capitalize-first" quotes="true" font-style="normal"/>
+          <text variable="genre" suffix=", " prefix=" "/>
+          <text variable="publisher"/>
+        </group>
+      </else-if>
+      <else-if type="manuscript" match="any">
+        <group delimiter=",">
+          <text variable="title" text-case="capitalize-first" quotes="true" font-style="normal"/>
+          <text variable="genre" prefix=" "/>
+        </group>
+      </else-if>
+      <else-if type="chapter entry-dictionary entry-encyclopedia" match="any">
+        <group>
+          <text variable="title" text-case="capitalize-first" quotes="true" suffix=","/>
+          <text value="in" font-style="italic" suffix=" " prefix=" "/>
+          <text macro="editor" suffix=", "/>
+          <text variable="container-title" text-case="capitalize-first" font-style="italic"/>
+        </group>
+      </else-if>
+      <else-if type="webpage" match="any">
+        <group>
+          <text variable="title" text-case="capitalize-first" font-style="italic" suffix=", "/>
+          <text variable="URL" text-decoration="underline"/>
+        </group>
+      </else-if>
+      <else>
+        <text variable="title" quotes="true"/>
+      </else>
+    </choose>
+  </macro>
+  <macro name="pub-place">
+    <choose>
+      <if type="bill book chapter entry-dictionary entry-encyclopedia thesis graphic legal_case manuscript motion_picture paper-conference report song" match="any">
+        <text variable="publisher-place"/>
+      </if>
+    </choose>
+  </macro>
+  <macro name="publisher">
+    <choose>
+      <if type="bill book chapter entry-dictionary entry-encyclopedia graphic legal_case motion_picture paper-conference report song" match="any">
+        <text variable="publisher"/>
+      </if>
+    </choose>
+  </macro>
+  <macro name="yearpage">
+    <choose>
+      <if type="bill book graphic legal_case motion_picture paper-conference manuscript report song thesis" match="any">
+        <group delimiter=", " font-style="normal">
+          <date variable="issued">
+            <date-part name="year"/>
+          </date>
+          <group delimiter=" ">
+            <text term="volume" form="short"/>
+            <text variable="volume"/>
+          </group>
+          <group delimiter="&#8239;">
+            <label variable="locator" form="short"/>
+            <text variable="locator"/>
+          </group>
+        </group>
+      </if>
+      <else-if type="chapter entry-dictionary entry-encyclopedia" match="any">
+        <group delimiter=" " font-style="normal">
+          <date variable="issued">
+            <date-part name="year" suffix=", "/>
+          </date>
+          <group>
+            <text term="volume" form="short" suffix="."/>
+            <text variable="number-of-volumes" prefix=". " suffix="/"/>
+            <text variable="volume" suffix=","/>
+          </group>
+          <label variable="page" form="short"/>
+          <group delimiter=", ">
+            <text variable="page"/>
+            <group delimiter="&#8239;">
+              <label variable="locator" form="short"/>
+              <text variable="locator"/>
+            </group>
+          </group>
+        </group>
+      </else-if>
+      <else-if type="article-journal" match="any">
+        <group delimiter=" " font-style="normal">
+          <label variable="page" form="short"/>
+          <group delimiter=", ">
+            <text variable="page"/>
+            <group delimiter="&#8239;">
+              <label variable="locator" form="short"/>
+              <text variable="locator"/>
+            </group>
+          </group>
+        </group>
+      </else-if>
+      <else-if type="article-newspaper article-magazine" match="any">
+        <group delimiter=" " font-style="normal">
+          <date variable="issued" form="numeric">
+            <date-part name="day"/>
+            <date-part name="month"/>
+            <date-part name="year"/>
+          </date>
+          <group delimiter=" " font-style="normal">
+            <choose>
+              <if variable="locator" match="any">
+                <group delimiter="&#8239;">
+                  <label variable="locator" form="short"/>
+                  <text variable="locator"/>
+                </group>
+              </if>
+              <else-if variable="locator" match="none">
+                <label variable="page" form="short"/>
+              </else-if>
+            </choose>
+          </group>
+        </group>
+      </else-if>
+      <else-if type="webpage" match="any">
+        <group delimiter=" " font-style="normal">
+          <text value="consulté le" suffix=" " prefix=" "/>
+          <date variable="accessed" form="text">
+            <date-part name="day"/>
+            <date-part name="month"/>
+            <date-part name="year"/>
+          </date>
+        </group>
+      </else-if>
+    </choose>
+  </macro>
+  <macro name="edition">
+    <choose>
+      <if type="bill book graphic legal_case motion_picture report song chapter paper-conference" match="any">
+        <choose>
+          <if is-numeric="edition">
+            <group delimiter=" ">
+              <number variable="edition" form="ordinal"/>
+              <text term="edition" form="short"/>
+            </group>
+          </if>
+          <else>
+            <text variable="edition" text-case="capitalize-first" suffix="."/>
+          </else>
+        </choose>
+      </if>
+      <else-if type="article-journal article-magazine" match="any">
+        <group font-style="normal">
+          <choose>
+            <if variable="issued">
+              <date variable="issued">
+                <date-part name="year"/>
+              </date>
+              <text macro="volume" prefix=", "/>
+            </if>
+            <else>
+              <text macro="volume" text-case="capitalize-first"/>
+            </else>
+          </choose>
+        </group>
+      </else-if>
+    </choose>
+    <text macro="issue" prefix=", "/>
+  </macro>
+  <macro name="volume">
+    <choose>
+      <if is-numeric="volume">
+        <text term="volume" form="short" suffix=".&#160;"/>
+        <text variable="volume"/>
+      </if>
+      <else>
+        <text variable="volume"/>
+      </else>
+    </choose>
+  </macro>
+  <macro name="issue">
+    <choose>
+      <if is-numeric="issue">
+        <text term="issue" form="short" suffix="&#160;"/>
+        <text variable="issue"/>
+      </if>
+      <else>
+        <text variable="issue"/>
+      </else>
+    </choose>
+  </macro>
+  <citation>
+    <layout suffix="." delimiter="&#160;; ">
+      <choose>
+        <if position="ibid-with-locator">
+          <group delimiter=", ">
+            <text term="ibid" text-case="capitalize-first" font-style="italic" suffix="."/>
+            <group delimiter="&#8239;">
+              <label variable="locator" form="short"/>
+              <text variable="locator"/>
+            </group>
+          </group>
+        </if>
+        <else-if position="ibid">
+          <text term="ibid" text-case="capitalize-first" font-style="italic"/>
+        </else-if>
+        <else-if position="subsequent">
+          <group delimiter=", ">
+            <text macro="author-short"/>
+            <choose>
+              <if type="bill book graphic legal_case motion_picture report song thesis" match="any">
+                <text variable="title" form="short" font-style="italic"/>
+              </if>
+              <else>
+                <text variable="title" text-case="capitalize-first" form="short" quotes="true" font-style="normal"/>
+              </else>
+            </choose>
+            <text term="cited" font-style="italic" suffix="."/>
+            <group delimiter="&#8239;">
+              <label variable="locator" form="short"/>
+              <text variable="locator"/>
+            </group>
+          </group>
+        </else-if>
+        <else>
+          <group delimiter=", ">
+            <text macro="author"/>
+            <text macro="title"/>
+            <text macro="translator"/>
+            <text macro="edition"/>
+            <text macro="pub-place"/>
+            <text macro="publisher"/>
+            <text macro="yearpage"/>
+          </group>
+        </else>
+      </choose>
+    </layout>
+  </citation>
+  <bibliography>
+    <sort>
+      <key macro="author" names-min="3" names-use-first="3"/>
+      <key variable="issued" sort="descending"/>
+    </sort>
+    <layout suffix=".">
+      <group delimiter=", ">
+        <text macro="author"/>
+        <text macro="title"/>
+        <text macro="translator"/>
+        <text macro="edition"/>
+        <text macro="pub-place"/>
+        <text macro="publisher"/>
+        <text macro="yearpage"/>
+      </group>
+    </layout>
+  </bibliography>
+</style>
diff --git a/test/command/apa.csl b/test/command/apa.csl
new file mode 100644
--- /dev/null
+++ b/test/command/apa.csl
@@ -0,0 +1,474 @@
+<?xml version="1.0" encoding="utf-8"?>
+<style xmlns="http://purl.org/net/xbiblio/csl" class="in-text" version="1.0" demote-non-dropping-particle="never">
+  <!-- This style was edited with the Visual CSL Editor (http://steveridout.com/csl/visualEditor/) -->
+  <info>
+    <title>American Psychological Association 6th edition</title>
+    <title-short>APA</title-short>
+    <id>http://www.zotero.org/styles/apa</id>
+    <link href="http://www.zotero.org/styles/apa" rel="self"/>
+    <link href="http://owl.english.purdue.edu/owl/resource/560/01/" rel="documentation"/>
+    <author>
+      <name>Simon Kornblith</name>
+      <email>simon@simonster.com</email>
+    </author>
+    <contributor>
+      <name>Bruce D'Arcus</name>
+    </contributor>
+    <contributor>
+      <name>Curtis M. Humphrey</name>
+    </contributor>
+    <contributor>
+      <name>Richard Karnesky</name>
+      <email>karnesky+zotero@gmail.com</email>
+      <uri>http://arc.nucapt.northwestern.edu/Richard_Karnesky</uri>
+    </contributor>
+    <contributor>
+      <name>Sebastian Karcher</name>
+    </contributor>
+    <category citation-format="author-date"/>
+    <category field="psychology"/>
+    <category field="generic-base"/>
+    <updated>2014-04-12T01:20:52+00:00</updated>
+    <rights license="http://creativecommons.org/licenses/by-sa/3.0/">This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 License</rights>
+  </info>
+  <locale xml:lang="en">
+    <terms>
+      <term name="editortranslator" form="short">
+        <single>ed. &amp; trans.</single>
+        <multiple>eds. &amp; trans.</multiple>
+      </term>
+      <term name="translator" form="short">
+        <single>trans.</single>
+        <multiple>trans.</multiple>
+      </term>
+    </terms>
+  </locale>
+  <macro name="container-contributors">
+    <choose>
+      <if type="chapter paper-conference" match="any">
+        <names variable="editor translator container-author" delimiter=", " suffix=", ">
+          <name and="symbol" initialize-with=". " delimiter=", "/>
+          <label form="short" prefix=" (" text-case="title" suffix=")"/>
+        </names>
+      </if>
+    </choose>
+  </macro>
+  <macro name="secondary-contributors">
+    <choose>
+      <if type="article-journal chapter paper-conference" match="none">
+        <names variable="translator editor container-author" delimiter=", " prefix=" (" suffix=")">
+          <name and="symbol" initialize-with=". " delimiter=", "/>
+          <label form="short" prefix=", " text-case="title"/>
+        </names>
+      </if>
+    </choose>
+  </macro>
+  <macro name="author">
+    <names variable="author">
+      <name name-as-sort-order="all" and="symbol" sort-separator=", " initialize-with=". " delimiter=", " delimiter-precedes-last="always"/>
+      <label form="short" prefix=" (" suffix=")" text-case="capitalize-first"/>
+      <substitute>
+        <names variable="editor"/>
+        <names variable="translator"/>
+        <choose>
+          <if type="report">
+            <text variable="publisher"/>
+            <text macro="title"/>
+          </if>
+          <else>
+            <text macro="title"/>
+          </else>
+        </choose>
+      </substitute>
+    </names>
+  </macro>
+  <macro name="author-short">
+    <names variable="author">
+      <name form="short" and="symbol" delimiter=", " initialize-with=". "/>
+      <substitute>
+        <names variable="editor"/>
+        <names variable="translator"/>
+        <choose>
+          <if type="report">
+            <text variable="publisher"/>
+            <text variable="title" form="short" font-style="italic"/>
+          </if>
+          <else-if type="legal_case">
+            <text variable="title" font-style="italic"/>
+          </else-if>
+          <else-if type="bill book graphic legislation motion_picture song" match="any">
+            <text variable="title" form="short" font-style="italic"/>
+          </else-if>
+          <else>
+            <text variable="title" form="short" quotes="true"/>
+          </else>
+        </choose>
+      </substitute>
+    </names>
+  </macro>
+  <macro name="access">
+    <choose>
+      <if type="thesis">
+        <choose>
+          <if variable="archive" match="any">
+            <group>
+              <text term="retrieved" text-case="capitalize-first" suffix=" "/>
+              <text term="from" suffix=" "/>
+              <text variable="archive" suffix="."/>
+              <text variable="archive_location" prefix=" (" suffix=")"/>
+            </group>
+          </if>
+          <else>
+            <group>
+              <text term="retrieved" text-case="capitalize-first" suffix=" "/>
+              <text term="from" suffix=" "/>
+              <text variable="URL"/>
+            </group>
+          </else>
+        </choose>
+      </if>
+      <else>
+        <choose>
+          <if variable="DOI">
+            <text variable="DOI" prefix="doi:"/>
+          </if>
+          <else>
+            <choose>
+              <if type="webpage">
+                <group delimiter=" ">
+                  <text term="retrieved" text-case="capitalize-first" suffix=" "/>
+                  <group>
+                    <date variable="accessed" form="text" suffix=", "/>
+                  </group>
+                  <text term="from"/>
+                  <text variable="URL"/>
+                </group>
+              </if>
+              <else>
+                <group>
+                  <text term="retrieved" text-case="capitalize-first" suffix=" "/>
+                  <text term="from" suffix=" "/>
+                  <text variable="URL"/>
+                </group>
+              </else>
+            </choose>
+          </else>
+        </choose>
+      </else>
+    </choose>
+  </macro>
+  <macro name="title">
+    <choose>
+      <if type="report thesis" match="any">
+        <text variable="title" font-style="italic"/>
+        <group prefix=" (" suffix=")" delimiter=" ">
+          <text variable="genre"/>
+          <text variable="number" prefix="No. "/>
+        </group>
+      </if>
+      <else-if type="book graphic  motion_picture report song manuscript speech" match="any">
+        <!---This is a hack until we have a computer program type -->
+        <choose>
+          <if variable="version">
+            <group delimiter=" ">
+              <text variable="title"/>
+              <group delimiter=" " prefix="(" suffix=")">
+                <text term="version" text-case="capitalize-first"/>
+                <text variable="version"/>
+              </group>
+            </group>
+          </if>
+          <else>
+            <text variable="title" font-style="italic"/>
+          </else>
+        </choose>
+      </else-if>
+      <else>
+        <text variable="title"/>
+      </else>
+    </choose>
+  </macro>
+  <macro name="publisher">
+    <choose>
+      <if type="report" match="any">
+        <group delimiter=": ">
+          <text variable="publisher-place"/>
+          <text variable="publisher"/>
+        </group>
+      </if>
+      <else-if type="thesis" match="any">
+        <group delimiter=", ">
+          <text variable="publisher"/>
+          <text variable="publisher-place"/>
+        </group>
+      </else-if>
+      <else>
+        <group delimiter=", ">
+          <choose>
+            <if variable="event" match="none">
+              <text variable="genre"/>
+            </if>
+          </choose>
+          <choose>
+            <if type="article-journal article-magazine" match="none">
+              <group delimiter=": ">
+                <text variable="publisher-place"/>
+                <text variable="publisher"/>
+              </group>
+            </if>
+          </choose>
+        </group>
+      </else>
+    </choose>
+  </macro>
+  <macro name="event">
+    <choose>
+      <if variable="container-title" match="none">
+        <choose>
+          <if variable="event">
+            <choose>
+              <if variable="genre" match="none">
+                <text term="presented at" text-case="capitalize-first" suffix=" "/>
+                <text variable="event"/>
+              </if>
+              <else>
+                <group delimiter=" ">
+                  <text variable="genre" text-case="capitalize-first"/>
+                  <text term="presented at"/>
+                  <text variable="event"/>
+                </group>
+              </else>
+            </choose>
+          </if>
+        </choose>
+      </if>
+    </choose>
+  </macro>
+  <macro name="issued">
+    <choose>
+      <if type="bill legal_case legislation" match="none">
+        <choose>
+          <if variable="issued">
+            <group prefix=" (" suffix=")">
+              <date variable="issued">
+                <date-part name="year"/>
+              </date>
+              <text variable="year-suffix"/>
+              <choose>
+                <if type="article-journal bill book chapter graphic legal_case legislation motion_picture paper-conference report song" match="none">
+                  <date variable="issued">
+                    <date-part prefix=", " name="month"/>
+                    <date-part prefix=" " name="day"/>
+                  </date>
+                </if>
+              </choose>
+            </group>
+          </if>
+          <else>
+            <group prefix=" (" suffix=")">
+              <text term="no date" form="short"/>
+              <text variable="year-suffix" prefix="-"/>
+            </group>
+          </else>
+        </choose>
+      </if>
+    </choose>
+  </macro>
+  <macro name="issued-sort">
+    <choose>
+      <if type="article-journal bill book chapter graphic legal_case legislation motion_picture paper-conference report song" match="none">
+        <date variable="issued">
+          <date-part name="year"/>
+          <date-part name="month"/>
+          <date-part name="day"/>
+        </date>
+      </if>
+      <else>
+        <date variable="issued">
+          <date-part name="year"/>
+        </date>
+      </else>
+    </choose>
+  </macro>
+  <macro name="issued-year">
+    <choose>
+      <if variable="issued">
+        <date variable="issued">
+          <date-part name="year"/>
+        </date>
+        <text variable="year-suffix"/>
+      </if>
+      <else>
+        <text term="no date" form="short"/>
+        <text variable="year-suffix" prefix="-"/>
+      </else>
+    </choose>
+  </macro>
+  <macro name="edition">
+    <choose>
+      <if is-numeric="edition">
+        <group delimiter=" ">
+          <number variable="edition" form="ordinal"/>
+          <text term="edition" form="short"/>
+        </group>
+      </if>
+      <else>
+        <text variable="edition" suffix="."/>
+      </else>
+    </choose>
+  </macro>
+  <macro name="locators">
+    <choose>
+      <if type="article-journal article-magazine" match="any">
+        <group prefix=", " delimiter=", ">
+          <group>
+            <text variable="volume" font-style="italic"/>
+            <text variable="issue" prefix="(" suffix=")"/>
+          </group>
+          <text variable="page"/>
+        </group>
+      </if>
+      <else-if type="article-newspaper">
+        <group delimiter=" " prefix=", ">
+          <label variable="page" form="short"/>
+          <text variable="page"/>
+        </group>
+      </else-if>
+      <else-if type="book graphic motion_picture report song chapter paper-conference" match="any">
+        <group prefix=" (" suffix=")" delimiter=", ">
+          <text macro="edition"/>
+          <group>
+            <text term="volume" form="short" plural="true" text-case="capitalize-first" suffix=" "/>
+            <number variable="number-of-volumes" form="numeric" prefix="1-"/>
+          </group>
+          <group>
+            <text term="volume" form="short" text-case="capitalize-first" suffix=" "/>
+            <number variable="volume" form="numeric"/>
+          </group>
+          <group>
+            <label variable="page" form="short" suffix=" "/>
+            <text variable="page"/>
+          </group>
+        </group>
+      </else-if>
+      <else-if type="legal_case">
+        <group prefix=" (" suffix=")" delimiter=" ">
+          <text variable="authority"/>
+          <date variable="issued" form="text"/>
+        </group>
+      </else-if>
+      <else-if type="bill legislation" match="any">
+        <date variable="issued" prefix=" (" suffix=")">
+          <date-part name="year"/>
+        </date>
+      </else-if>
+    </choose>
+  </macro>
+  <macro name="citation-locator">
+    <group>
+      <choose>
+        <if locator="chapter">
+          <label variable="locator" form="long" text-case="capitalize-first"/>
+        </if>
+        <else>
+          <label variable="locator" form="short"/>
+        </else>
+      </choose>
+      <text variable="locator" prefix=" "/>
+    </group>
+  </macro>
+  <macro name="container">
+    <group>
+      <choose>
+        <if type="chapter paper-conference entry-encyclopedia" match="any">
+          <text term="in" text-case="capitalize-first" suffix=" "/>
+        </if>
+      </choose>
+      <text macro="container-contributors"/>
+      <text macro="secondary-contributors"/>
+      <text macro="container-title"/>
+    </group>
+  </macro>
+  <macro name="container-title">
+    <choose>
+      <if type="article article-journal article-magazine article-newspaper" match="any">
+        <text variable="container-title" font-style="italic" text-case="title"/>
+      </if>
+      <else-if type="bill legal_case legislation" match="none">
+        <text variable="container-title" font-style="italic"/>
+      </else-if>
+    </choose>
+  </macro>
+  <macro name="legal-cites">
+    <choose>
+      <if type="bill legal_case legislation" match="any">
+        <group delimiter=" " prefix=", ">
+          <choose>
+            <if variable="container-title">
+              <text variable="volume"/>
+              <text variable="container-title"/>
+              <group delimiter=" ">
+                <!--change to label variable="section" as that becomes available -->
+                <text term="section" form="symbol"/>
+                <text variable="section"/>
+              </group>
+              <text variable="page"/>
+            </if>
+            <else>
+              <choose>
+                <if type="legal_case">
+                  <text variable="number" prefix="No. "/>
+                </if>
+                <else>
+                  <text variable="number" prefix="Pub. L. No. "/>
+                  <group delimiter=" ">
+                    <!--change to label variable="section" as that becomes available -->
+                    <text term="section" form="symbol"/>
+                    <text variable="section"/>
+                  </group>
+                </else>
+              </choose>
+            </else>
+          </choose>
+        </group>
+      </if>
+    </choose>
+  </macro>
+  <citation et-al-min="6" et-al-use-first="1" et-al-subsequent-min="3" et-al-subsequent-use-first="1" disambiguate-add-year-suffix="true" disambiguate-add-names="true" disambiguate-add-givenname="true" collapse="year" givenname-disambiguation-rule="primary-name">
+    <sort>
+      <key macro="author"/>
+      <key macro="issued-sort"/>
+    </sort>
+    <layout prefix="(" suffix=")" delimiter="; ">
+      <group delimiter=", ">
+        <text macro="author-short"/>
+        <text macro="issued-year"/>
+        <text macro="citation-locator"/>
+      </group>
+    </layout>
+  </citation>
+  <bibliography hanging-indent="true" et-al-min="8" et-al-use-first="6" et-al-use-last="true" entry-spacing="0" line-spacing="2">
+    <sort>
+      <key macro="author"/>
+      <key macro="issued-sort" sort="ascending"/>
+      <key macro="title"/>
+    </sort>
+    <layout>
+      <group suffix=".">
+        <group delimiter=". ">
+          <text macro="author"/>
+          <text macro="issued"/>
+          <text macro="title" prefix=" "/>
+          <text macro="container"/>
+        </group>
+        <text macro="legal-cites"/>
+        <text macro="locators"/>
+        <group delimiter=", " prefix=". ">
+          <text macro="event"/>
+          <text macro="publisher"/>
+        </group>
+      </group>
+      <text macro="access" prefix=" "/>
+    </layout>
+  </bibliography>
+</style>
diff --git a/test/command/archeologie-medievale.csl b/test/command/archeologie-medievale.csl
new file mode 100644
--- /dev/null
+++ b/test/command/archeologie-medievale.csl
@@ -0,0 +1,291 @@
+<?xml version="1.0" encoding="utf-8"?>
+<style xmlns="http://purl.org/net/xbiblio/csl" version="1.0" class="note" demote-non-dropping-particle="display-and-sort" default-locale="fr-FR" page-range-format="expanded">
+  <info>
+    <title>Archéologie médiévale (French)</title>
+    <id>http://www.zotero.org/styles/archeologie-medievale</id>
+    <link href="http://www.zotero.org/styles/archeologie-medievale" rel="self"/>
+    <link href="http://www.unicaen.fr/crahm/archeomed/spip.php?article80" rel="documentation"/>
+    <author>
+      <name>Nicolas Monteix</name>
+      <email>nicolas.monteix@univ-rouen.fr</email>
+    </author>
+    <category citation-format="note"/>
+    <category field="history"/>
+    <category field="anthropology"/>
+    <issn>0153-9337</issn>
+    <summary>Style auteur-date en note pour Archéologie médiévale. NB: les sources éditées doivent être considérées comme des livres ayant un auteur (médiéval) et un éditeur (contemporain). Pour les sources éditées ne disposant pas d'auteur (médiéval), il est nécessaire de transformer le (dir.) en (éd.). Pour les archives (type=manuscrit), le "lieu" correspond au dépôt d'archives, l' "archive" au fonds, la "loc. dans l'archive" à la cote.</summary>
+    <updated>2014-08-17T23:30:36+00:00</updated>
+    <rights license="http://creativecommons.org/licenses/by-sa/3.0/">This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 License</rights>
+  </info>
+  <locale xml:lang="fr">
+    <terms>
+      <term name="editor" form="short">dir.</term>
+      <term name="in">dans</term>
+      <term name="anonymous">anonyme</term>
+      <term name="anonymous" form="short">anon.</term>
+      <term name="accessed">consulté le</term>
+      <term name="no date">sans date</term>
+      <term name="no date" form="short">s.&#160;d.</term>
+    </terms>
+  </locale>
+  <macro name="author">
+    <names variable="author" delimiter=" ">
+      <name name-as-sort-order="all" font-variant="small-caps" sort-separator=" " initialize-with="." delimiter-precedes-last="never" and="text" delimiter=", "/>
+      <substitute>
+        <text macro="editor"/>
+      </substitute>
+    </names>
+  </macro>
+  <macro name="editor">
+    <names variable="editor">
+      <name name-as-sort-order="all" font-variant="small-caps" sort-separator=" " initialize-with="." delimiter-precedes-last="never" and="text" delimiter=", "/>
+      <label form="short" font-variant="normal" text-case="lowercase" prefix=" (" suffix=")"/>
+    </names>
+  </macro>
+  <macro name="pages">
+    <group>
+      <text variable="page" prefix="p.&#160;"/>
+    </group>
+  </macro>
+  <macro name="author-short">
+    <names variable="author">
+      <name form="short" delimiter-precedes-last="never" and="text" delimiter=", "/>
+      <et-al font-variant="normal" font-style="italic"/>
+      <substitute>
+        <text macro="editor-short"/>
+      </substitute>
+    </names>
+  </macro>
+  <macro name="editor-short">
+    <names variable="editor">
+      <name form="short" delimiter-precedes-last="never" and="text" delimiter=", "/>
+      <et-al font-variant="normal" font-style="italic"/>
+    </names>
+  </macro>
+  <macro name="URLaccess">
+    <group prefix="(" suffix=")">
+      <text variable="URL"/>
+      <text macro="access"/>
+    </group>
+  </macro>
+  <macro name="access">
+    <group prefix=" [" suffix="]">
+      <text term="accessed" suffix=" "/>
+      <date variable="accessed">
+        <date-part name="day" suffix=" "/>
+        <date-part name="month" suffix=" "/>
+        <date-part name="year"/>
+      </date>
+    </group>
+  </macro>
+  <macro name="editor-text">
+    <group>
+      <names variable="editor" suffix=" (éd.), ">
+        <name name-as-sort-order="all" font-variant="small-caps" sort-separator=" " initialize-with="." delimiter-precedes-last="never" and="text" delimiter=", "/>
+      </names>
+      <text macro="publisher" suffix=", "/>
+      <text macro="year-date"/>
+    </group>
+  </macro>
+  <macro name="editor-text-short">
+    <group>
+      <names variable="editor" suffix=" (éd.), ">
+        <name name-as-sort-order="all" form="short" font-variant="small-caps" delimiter-precedes-last="never" and="text" delimiter=", "/>
+      </names>
+      <text macro="year-date"/>
+    </group>
+  </macro>
+  <macro name="title">
+    <choose>
+      <if type="book" match="any">
+        <text variable="title" font-style="italic"/>
+      </if>
+      <else-if type="webpage" match="any">
+        <text variable="title"/>
+      </else-if>
+      <else-if variable="container-title" match="none">
+        <text variable="title" font-style="italic"/>
+      </else-if>
+      <else>
+        <text variable="title"/>
+      </else>
+    </choose>
+  </macro>
+  <macro name="publisher">
+    <group delimiter=", ">
+      <text variable="publisher-place"/>
+      <text variable="publisher"/>
+    </group>
+  </macro>
+  <macro name="year-date">
+    <choose>
+      <if variable="issued">
+        <date variable="issued">
+          <date-part name="year"/>
+        </date>
+      </if>
+      <else>
+        <text term="no date" form="short"/>
+      </else>
+    </choose>
+    <choose>
+      <if is-numeric="edition">
+        <group vertical-align="sup">
+          <number variable="edition"/>
+        </group>
+      </if>
+      <else>
+        <text variable="edition"/>
+      </else>
+    </choose>
+  </macro>
+  <macro name="type-sorting">
+    <choose>
+      <if type="book" variable="editor author" match="all">
+        <text value="1"/>
+      </if>
+      <else-if type="manuscript">
+        <text value="2"/>
+      </else-if>
+      <else>
+        <text value="3"/>
+      </else>
+    </choose>
+  </macro>
+  <macro name="locator">
+    <choose>
+      <if locator="paragraph">
+        <text variable="locator" prefix=", § "/>
+      </if>
+      <else-if locator="folio">
+        <text variable="locator" prefix=",&#160;fol.&#160;"/>
+      </else-if>
+      <else>
+        <group prefix=",&#160;">
+          <label variable="locator" form="short" suffix=".&#160;"/>
+          <text variable="locator"/>
+        </group>
+      </else>
+    </choose>
+  </macro>
+  <citation et-al-min="4" et-al-use-first="3" delimiter-precedes-et-al="never" disambiguate-add-year-suffix="true">
+    <sort>
+      <key variable="issued"/>
+    </sort>
+    <layout delimiter="&#160;; ">
+      <choose>
+        <if position="ibid-with-locator">
+          <group>
+            <text term="ibid" text-case="capitalize-first" font-style="italic"/>
+            <text macro="locator"/>
+          </group>
+        </if>
+        <else-if position="ibid">
+          <text term="ibid" text-case="capitalize-first" font-style="italic"/>
+        </else-if>
+        <else-if type="book" variable="editor author" match="all">
+          <group suffix=".">
+            <text macro="author-short" font-variant="small-caps" suffix=", "/>
+            <text macro="title" suffix=", "/>
+            <text macro="editor-text-short"/>
+            <text macro="locator"/>
+          </group>
+        </else-if>
+        <else-if type="manuscript">
+          <group delimiter=", ">
+            <text variable="publisher-place"/>
+            <text variable="archive_location"/>
+            <text macro="locator"/>
+          </group>
+        </else-if>
+        <else>
+          <text macro="author-short" suffix="&#160;" font-variant="small-caps"/>
+          <text macro="year-date"/>
+          <text macro="locator"/>
+        </else>
+      </choose>
+    </layout>
+  </citation>
+  <bibliography subsequent-author-substitute="">
+    <sort>
+      <key macro="type-sorting"/>
+      <key macro="author"/>
+      <key variable="issued"/>
+      <key variable="title"/>
+    </sort>
+    <layout suffix=".">
+      <choose>
+        <if type="book" variable="editor author" match="all">
+          <group suffix=".">
+            <text macro="author" suffix=", "/>
+            <text macro="title" suffix=", "/>
+            <text macro="editor-text"/>
+          </group>
+        </if>
+        <else-if type="manuscript">
+          <group delimiter=", ">
+            <text variable="archive_location"/>
+            <text variable="archive"/>
+            <text variable="title" font-style="italic"/>
+          </group>
+          <group prefix=" (" suffix=")">
+            <date variable="issued">
+              <date-part name="year"/>
+            </date>
+          </group>
+        </else-if>
+        <else>
+          <group display="block">
+            <text macro="author" suffix="&#9;"/>
+          </group>
+          <group display="left-margin">
+            <text macro="year-date" suffix=", "/>
+            <choose>
+              <if type="thesis">
+                <group delimiter=", " suffix=".">
+                  <text macro="title" font-style="italic"/>
+                  <text variable="genre"/>
+                  <text variable="publisher"/>
+                  <text variable="publisher-place"/>
+                </group>
+              </if>
+              <else-if type="webpage">
+                <group delimiter=" ">
+                  <text macro="title" font-style="italic"/>
+                  <text macro="URLaccess"/>
+                </group>
+              </else-if>
+              <else-if type="article-journal article-magazine article-newspaper broadcast personal_communication thesis entry-dictionary entry-encyclopedia" match="any">
+                <group delimiter=", " suffix=".">
+                  <text macro="title" quotes="true"/>
+                  <text variable="container-title" font-style="italic"/>
+                  <text variable="volume"/>
+                  <text variable="issue"/>
+                  <text macro="pages"/>
+                </group>
+              </else-if>
+              <else-if type="book graphic" match="any">
+                <group suffix=".">
+                  <text macro="title" suffix=", "/>
+                  <text macro="publisher"/>
+                </group>
+              </else-if>
+              <else-if type="chapter paper-conference" match="any">
+                <text macro="title" quotes="true" suffix=", "/>
+                <group delimiter=", ">
+                  <group delimiter=" ">
+                    <text term="in"/>
+                    <text macro="editor"/>
+                  </group>
+                  <text variable="container-title" font-style="italic"/>
+                  <text macro="publisher"/>
+                  <text macro="pages"/>
+                </group>
+              </else-if>
+            </choose>
+          </group>
+        </else>
+      </choose>
+    </layout>
+  </bibliography>
+</style>
diff --git a/test/command/ascii.md b/test/command/ascii.md
new file mode 100644
--- /dev/null
+++ b/test/command/ascii.md
@@ -0,0 +1,89 @@
+```
+% pandoc -t html --ascii
+äéıå
+^D
+<p>&#xE4;&#xE9;&#x131;&#xE5;</p>
+```
+
+```
+% pandoc -t latex --ascii
+äéıå
+^D
+\"{a}\'{e}\i\r{a}
+```
+
+```
+% pandoc -t man --ascii
+äéıå
+^D
+.PP
+\(:a\('e\(.i\(oa
+```
+
+```
+% pandoc -t ms --ascii
+äéıå
+^D
+.LP
+\(:a\('e\(.i\(oa
+```
+
+```
+% pandoc -t docbook --ascii
+äéıå
+^D
+<para>
+  &#xE4;&#xE9;&#x131;&#xE5;
+</para>
+```
+
+```
+% pandoc -t jats --ascii
+äéıå
+^D
+<p>&#xE4;&#xE9;&#x131;&#xE5;</p>
+```
+
+```
+% pandoc -t markdown-smart --ascii
+"äéıå"
+^D
+&ldquo;&auml;&eacute;&imath;&aring;&rdquo;
+```
+
+# CommonMark tests
+
+```
+% pandoc -f commonmark -t commonmark --ascii
+hello … ok? … bye
+^D
+hello &mldr; ok? &mldr; bye
+```
+
+```
+% pandoc -f commonmark+smart -t commonmark-smart --ascii --wrap=none
+"hi"...dog's breath---cat 5--6
+^D
+&ldquo;hi&rdquo;&mldr;dog&rsquo;s breath&mdash;cat 5&ndash;6
+```
+
+```
+% pandoc -f commonmark+smart -t commonmark+smart --ascii
+"hi"...dog's breath---cat 5--6
+^D
+"hi"...dog's breath---cat 5--6
+```
+
+```
+% pandoc -f commonmark -t commonmark --ascii
+foo &#1234; bar
+^D
+foo &#1234; bar
+```
+
+```
+% pandoc -f commonmark -t commonmark --ascii
+\[foo\](bar)
+^D
+\[foo\](bar)
+```
diff --git a/test/command/author-in-text-move-note.md b/test/command/author-in-text-move-note.md
new file mode 100644
--- /dev/null
+++ b/test/command/author-in-text-move-note.md
@@ -0,0 +1,19 @@
+```
+% pandoc --citeproc --csl command/chicago-fullnote-bibliography.csl -t plain
+---
+references:
+- id: foo
+  type: book
+  author: John Doe
+  title: A Book
+...
+
+See @foo [p. 21], as well.
+^D
+See John Doe,[1] as well.
+
+John Doe. A Book, n.d.
+
+[1] A Book, n.d., 21.
+```
+
diff --git a/test/command/averroes.bib b/test/command/averroes.bib
new file mode 100644
--- /dev/null
+++ b/test/command/averroes.bib
@@ -0,0 +1,95 @@
+@string{anch-ie = {Angew.~Chem. Int.~Ed.}}
+@string{cup     = {Cambridge University Press}}
+@string{dtv     = {Deutscher Taschenbuch-Verlag}}
+@string{hup     = {Harvard University Press}}
+@string{jams    = {J.~Amer. Math. Soc.}}
+@string{jchph   = {J.~Chem. Phys.}}
+@string{jomch   = {J.~Organomet. Chem.}}
+@string{pup     = {Princeton University Press}}
+
+@book{averroes/bland,
+  author       = {Averroes},
+  title        = {The Epistle on the Possibility of Conjunction with the Active
+                  Intellect by {Ibn Rushd} with the Commentary of {Moses Narboni}},
+  date         = 1982,
+  editor       = {Bland, Kalman P.},
+  translator   = {Bland, Kalman P.},
+  series       = {Moreshet: Studies in {Jewish} History, Literature and Thought},
+  number       = 7,
+  publisher    = {Jewish Theological Seminary of America},
+  location     = {New York},
+  keywords     = {primary},
+  langid       = {english},
+  langidopts   = {variant=american},
+  indextitle   = {Epistle on the Possibility of Conjunction, The},
+  shorttitle   = {Possibility of Conjunction},
+  annotation   = {A \texttt{book} entry with a \texttt{series} and a
+                  \texttt{number}. Note the concatenation of the \texttt{editor}
+                  and \texttt{translator} fields as well as the
+                  \texttt{indextitle} field},
+}
+
+@book{averroes/hannes,
+  author       = {Averroes},
+  title        = {Des Averro{\"e}s Abhandlung: \mkbibquote{{\"U}ber die
+                  M{\"o}glichkeit der Conjunktion} oder \mkbibquote{{\"U}ber den
+                  materiellen Intellekt}},
+  date         = 1892,
+  editor       = {Hannes, Ludwig},
+  translator   = {Hannes, Ludwig},
+  annotator    = {Hannes, Ludwig},
+  publisher    = {C.~A. Kaemmerer},
+  location     = {Halle an der Saale},
+  keywords     = {primary},
+  langid       = {german},
+  sorttitle    = {Uber die Moglichkeit der Conjunktion},
+  indexsorttitle= {Uber die Moglichkeit der Conjunktion},
+  indextitle   = {{\"U}ber die M{\"o}glichkeit der Conjunktion},
+  shorttitle   = {{\"U}ber die M{\"o}glichkeit der Conjunktion},
+  annotation   = {An annotated edition. Note the concatenation of the
+                  \texttt{editor}, \texttt{translator}, and \texttt{annotator}
+                  fields. Also note the \texttt{shorttitle},
+                  \texttt{indextitle}, \texttt{sorttitle}, and
+                  \texttt{indexsorttitle} fields},
+}
+
+@book{averroes/hercz,
+  author       = {Averroes},
+  title        = {Drei Abhandlungen {\"u}ber die Conjunction des separaten
+                  Intellects mit dem Menschen},
+  date         = 1869,
+  editor       = {Hercz, J.},
+  translator   = {Hercz, J.},
+  publisher    = {S.~Hermann},
+  location     = {Berlin},
+  keywords     = {primary},
+  langid       = {german},
+  indexsorttitle= {Drei Abhandlungen uber die Conjunction},
+  indextitle   = {Drei Abhandlungen {\"u}ber die Conjunction},
+  subtitle     = {Von Averroes (Vater und Sohn), aus dem Arabischen
+                  {\"u}bersetzt von Samuel Ibn Tibbon},
+  shorttitle   = {Drei Abhandlungen},
+  annotation   = {A \texttt{book} entry. Note the concatenation of the
+                  \texttt{editor} and \texttt{translator} fields as well as the
+                  \texttt{indextitle} and \texttt{indexsorttitle} fields},
+}
+
+@book{cicero,
+  author       = {Cicero, Marcus Tullius},
+  title        = {De natura deorum. {\"U}ber das Wesen der G{\"o}tter},
+  date         = 1995,
+  editor       = {Blank-Sangmeister, Ursula},
+  translator   = {Blank-Sangmeister, Ursula},
+  afterword    = {Thraede, Klaus},
+  language     = {langlatin and langgerman},
+  publisher    = {Reclam},
+  location     = {Stuttgart},
+  langid       = {german},
+  indextitle   = {De natura deorum},
+  shorttitle   = {De natura deorum},
+  annotation   = {A bilingual edition of Cicero's \emph{De natura deorum}, with
+                  a German translation. Note the format of the \texttt{language}
+                  field in the database file, the concatenation of the
+                  \texttt{editor} and \texttt{translator} fields, and the
+                  \texttt{afterword} field},
+}
diff --git a/test/command/bar-endinput.tex b/test/command/bar-endinput.tex
new file mode 100644
--- /dev/null
+++ b/test/command/bar-endinput.tex
@@ -0,0 +1,3 @@
+\emph{hi there}
+\endinput
+\emph{invisible}
diff --git a/test/command/bar.tex b/test/command/bar.tex
new file mode 100644
--- /dev/null
+++ b/test/command/bar.tex
@@ -0,0 +1,1 @@
+\emph{hi there}
diff --git a/test/command/biblatex-266.md b/test/command/biblatex-266.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-266.md
@@ -0,0 +1,34 @@
+```
+% pandoc -f biblatex -t markdown -s
+@book{goethe2005,
+  langid = {german},
+  location = {{Frankfurt am Main}},
+  title = {Not A Real Book},
+  date = {2005},
+  author = {family=Goethe, given=Johann Wolfgang, prefix=von, useprefix=false and given=Antonie, prefix=van, family=Leeuwenhoek, useprefix=true}, editor = {Schöne, Albrecht}
+}
+
+^D
+---
+nocite: "[@*]"
+references:
+- author:
+  - dropping-particle: von
+    family: Goethe
+    given: Johann Wolfgang
+  - family: Leeuwenhoek
+    given: Antonie
+    non-dropping-particle: van
+  editor:
+  - family: Schöne
+    given: Albrecht
+  id: goethe2005
+  issued: 2005
+  language: de-DE
+  publisher-place: Frankfurt am Main
+  title: Not A Real Book
+  type: book
+---
+
+
+```
diff --git a/test/command/biblatex-aksin.md b/test/command/biblatex-aksin.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-aksin.md
@@ -0,0 +1,78 @@
+```
+% pandoc -f biblatex -t markdown -s
+@comment{
+
+Adapted from biblatex-example.bib
+
+
+Formatted with pandoc and chicago-author-date.csl, 2013-10-23:
+
+(Aksin et al. 2006)
+
+Aksin, Özge, Hayati Türkmen, Levent Artok, Bekir Çetinkaya, Chaoying Ni,
+Orhan Büyükgüngör, and Erhan Özkal. 2006. “Effect of Immobilization on
+Catalytic Characteristics of Saturated Pd-N-heterocyclic Carbenes in
+Mizoroki-Heck Reactions.” *J. Organomet. Chem.* 691 (13): 3027–3036.
+
+
+Formatted with pandoc and apa.csl, 2013-10-23:
+
+(Aksin et al., 2006)
+
+Aksin, Ö., Türkmen, H., Artok, L., Çetinkaya, B., Ni, C., Büyükgüngör,
+O., & Özkal, E. (2006). Effect of immobilization on catalytic
+characteristics of saturated Pd-N-heterocyclic carbenes in Mizoroki-Heck
+reactions. *J. Organomet. Chem.*, *691*(13), 3027–3036.
+
+
+}
+
+@string{ jomch   = {J.~Organomet. Chem.} }
+
+@Article{aksin,
+  author       = {Aks{\i}n, {\"O}zge and T{\"u}rkmen, Hayati and Artok, Levent
+                  and {\c{C}}etinkaya, Bekir and Ni, Chaoying and
+                  B{\"u}y{\"u}kg{\"u}ng{\"o}r, Orhan and {\"O}zkal, Erhan},
+  title        = {Effect of immobilization on catalytic characteristics of
+                  saturated {Pd-N}-heterocyclic carbenes in {Mizoroki-Heck}
+                  reactions},
+  journaltitle = jomch,
+  date         = 2006,
+  volume       = 691,
+  number       = 13,
+  pages        = {3027-3036},
+  indextitle   = {Effect of immobilization on catalytic characteristics},
+}
+
+^D
+---
+nocite: "[@*]"
+references:
+- author:
+  - family: Aksın
+    given: Özge
+  - family: Türkmen
+    given: Hayati
+  - family: Artok
+    given: Levent
+  - family: Çetinkaya
+    given: Bekir
+  - family: Ni
+    given: Chaoying
+  - family: Büyükgüngör
+    given: Orhan
+  - family: Özkal
+    given: Erhan
+  container-title: J. Organomet. Chem.
+  id: aksin
+  issue: 13
+  issued: 2006
+  page: 3027-3036
+  title: Effect of immobilization on catalytic characteristics of
+    saturated Pd-N-heterocyclic carbenes in Mizoroki-Heck reactions
+  type: article-journal
+  volume: 691
+---
+
+
+```
diff --git a/test/command/biblatex-almendro.md b/test/command/biblatex-almendro.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-almendro.md
@@ -0,0 +1,71 @@
+```
+% pandoc -f biblatex -t markdown -s
+@comment{
+
+Adapted from biblatex-example.bib
+
+
+Formatted with pandoc and chicago-author-date.csl, 2013-10-23:
+
+(Almendro et al. 1998)
+
+Almendro, José L., Jacinto Martín, Alberto Sánchez, and Fernando Nozal.
+1998. “Elektromagnetisches Signalhorn.”
+
+
+Formatted with pandoc and apa.csl, 2013-10-23:
+
+(Almendro, Martín, Sánchez, & Nozal, 1998)
+
+Almendro, J. L., Martín, J., Sánchez, A., & Nozal, F. (1998).
+Elektromagnetisches Signalhorn.
+
+
+NOTES:
+
+- CSL styles’ handling of patent items needs to be improved
+
+}
+
+@Patent{almendro,
+  author       = {Almendro, Jos{\'e} L. and Mart{\'i}n, Jacinto and S{\'a}nchez,
+                  Alberto and Nozal, Fernando},
+  title        = {Elektromagnetisches Signalhorn},
+  number       = {EU-29702195U},
+  date         = 1998,
+  location     = {countryfr and countryuk and countryde},
+  hyphenation  = {german},
+  annotation   = {This is a patent entry with a location
+                  field. The number is given in the number field. Note
+                  the format of the location field in the database
+                  file. Compare laufenberg, sorace, and
+                  kowalik},
+}
+
+^D
+---
+nocite: "[@*]"
+references:
+- annote: This is a patent entry with a location field. The number is
+    given in the number field. Note the format of the location field in
+    the database file. Compare laufenberg, sorace, and kowalik
+  author:
+  - family: Almendro
+    given: José L.
+  - family: Martín
+    given: Jacinto
+  - family: Sánchez
+    given: Alberto
+  - family: Nozal
+    given: Fernando
+  id: almendro
+  issued: 1998
+  jurisdiction: France; United Kingdom; Germany
+  language: de-DE
+  number: EU-29702195U
+  title: Elektromagnetisches Signalhorn
+  type: patent
+---
+
+
+```
diff --git a/test/command/biblatex-angenendt.md b/test/command/biblatex-angenendt.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-angenendt.md
@@ -0,0 +1,66 @@
+```
+% pandoc -f biblatex -t markdown -s
+@comment{
+
+Adapted from biblatex-example.bib
+
+
+Formatted with pandoc and chicago-author-date.csl, 2013-10-23:
+
+(Angenendt 2002)
+
+Angenendt, Arnold. 2002. “In Honore Salvatoris – Vom Sinn und Unsinn der
+Patrozinienkunde.” *Revue d’Histoire Ecclésiastique* 97: 431–456,
+791–823.
+
+
+Formatted with pandoc and apa.csl, 2013-10-23:
+
+(Angenendt, 2002)
+
+Angenendt, A. (2002). In Honore Salvatoris – Vom Sinn und Unsinn der
+Patrozinienkunde. *Revue d’Histoire Ecclésiastique*, *97*, 431–456,
+791–823.
+
+
+}
+
+@Article{angenendt,
+  author       = {Angenendt, Arnold},
+  title        = {In Honore Salvatoris~-- Vom Sinn und Unsinn der
+                  Patrozinienkunde},
+  journaltitle = {Revue d'Histoire Eccl{\'e}siastique},
+  date         = 2002,
+  volume       = 97,
+  pages        = {431--456, 791--823},
+  hyphenation  = {german},
+  indextitle   = {In Honore Salvatoris},
+  shorttitle   = {In Honore Salvatoris},
+  annotation   = {A German article in a French journal. Apart from that, a
+                  typical article entry. Note the indextitle
+                  field},
+}
+
+^D
+---
+nocite: "[@*]"
+references:
+- annote: A German article in a French journal. Apart from that, a
+    typical article entry. Note the indextitle field
+  author:
+  - family: Angenendt
+    given: Arnold
+  container-title: Revue d'Histoire Eccl[é]{.nocase}siastique
+  id: angenendt
+  issued: 2002
+  language: de-DE
+  page: 431-456, 791-823
+  title: In Honore Salvatoris -- Vom Sinn und Unsinn der
+    Patrozinienkunde
+  title-short: In Honore Salvatoris
+  type: article-journal
+  volume: 97
+---
+
+
+```
diff --git a/test/command/biblatex-aristotle-anima.md b/test/command/biblatex-aristotle-anima.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-aristotle-anima.md
@@ -0,0 +1,62 @@
+```
+% pandoc -f biblatex -t markdown -s
+@comment{
+
+Adapted from biblatex-example.bib
+
+
+Formatted with pandoc and chicago-author-date.csl, 2013-10-23:
+
+(Aristotle 1907)
+
+Aristotle. 1907. *De Anima*. Edited by Robert Drew Hicks. Cambridge:
+Cambridge University Press.
+
+
+Formatted with pandoc and apa.csl, 2013-10-23:
+
+(Aristotle, 1907)
+
+Aristotle. (1907). *De anima*. (R. D. Hicks, Ed.). Cambridge: Cambridge
+University Press.
+
+
+}
+
+@string{ cup     = {Cambridge University Press} }
+
+@Book{aristotle:anima,
+  author       = {Aristotle},
+  title        = {De Anima},
+  date         = 1907,
+  editor       = {Hicks, Robert Drew},
+  publisher    = cup,
+  location     = {Cambridge},
+  keywords     = {primary},
+  hyphenation  = {british},
+  annotation   = {A book entry with an author and an
+                  editor},
+}
+
+^D
+---
+nocite: "[@*]"
+references:
+- annote: A book entry with an author and an editor
+  author:
+  - family: Aristotle
+  editor:
+  - family: Hicks
+    given: Robert Drew
+  id: "aristotle:anima"
+  issued: 1907
+  keyword: primary
+  language: en-GB
+  publisher: Cambridge University Press
+  publisher-place: Cambridge
+  title: De anima
+  type: book
+---
+
+
+```
diff --git a/test/command/biblatex-aristotle-physics.md b/test/command/biblatex-aristotle-physics.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-aristotle-physics.md
@@ -0,0 +1,63 @@
+```
+% pandoc -f biblatex -t markdown -s
+@comment{
+
+Adapted from biblatex-example.bib
+
+
+Formatted with pandoc and chicago-author-date.csl, 2013-10-23:
+
+(Aristotle 1929)
+
+Aristotle. 1929. *Physics*. Translated by P. H. Wicksteed and F. M.
+Cornford. New York: G. P. Putnam.
+
+
+Formatted with pandoc and apa.csl, 2013-10-23:
+
+(Aristotle, 1929)
+
+Aristotle. (1929). *Physics*. (P. H. Wicksteed & F. M. Cornford,
+Trans.). New York: G. P. Putnam.
+
+
+}
+
+@Book{aristotle:physics,
+  author       = {Aristotle},
+  title        = {Physics},
+  date         = 1929,
+  translator   = {Wicksteed, P. H. and Cornford, F. M.},
+  publisher    = {G. P. Putnam},
+  location     = {New York},
+  keywords     = {primary},
+  hyphenation  = {american},
+  shorttitle   = {Physics},
+  annotation   = {A book entry with a translator field},
+}
+
+^D
+---
+nocite: "[@*]"
+references:
+- annote: A book entry with a translator field
+  author:
+  - family: Aristotle
+  id: "aristotle:physics"
+  issued: 1929
+  keyword: primary
+  language: en-US
+  publisher: G. P. Putnam
+  publisher-place: New York
+  title: Physics
+  title-short: Physics
+  translator:
+  - family: Wicksteed
+    given: P. H.
+  - family: Cornford
+    given: F. M.
+  type: book
+---
+
+
+```
diff --git a/test/command/biblatex-aristotle-poetics.md b/test/command/biblatex-aristotle-poetics.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-aristotle-poetics.md
@@ -0,0 +1,65 @@
+```
+% pandoc -f biblatex -t markdown -s
+@comment{
+
+Adapted from biblatex-example.bib
+
+
+Formatted with pandoc and chicago-author-date.csl, 2013-10-23:
+
+(Aristotle 1968)
+
+Aristotle. 1968. *Poetics*. Edited by D. W. Lucas. Clarendon Aristotle.
+Oxford: Clarendon Press.
+
+
+Formatted with pandoc and apa.csl, 2013-10-23:
+
+(Aristotle, 1968)
+
+Aristotle. (1968). *Poetics*. (D. W. Lucas, Ed.). Oxford: Clarendon
+Press.
+
+
+}
+
+@Book{aristotle:poetics,
+  author       = {Aristotle},
+  title        = {Poetics},
+  date         = 1968,
+  editor       = {Lucas, D. W.},
+  series       = {Clarendon {Aristotle}},
+  publisher    = {Clarendon Press},
+  location     = {Oxford},
+  keywords     = {primary},
+  hyphenation  = {british},
+  shorttitle   = {Poetics},
+  annotation   = {A book entry with an author and an
+                  editor as well as a series field},
+}
+
+^D
+---
+nocite: "[@*]"
+references:
+- annote: A book entry with an author and an editor as well as a series
+    field
+  author:
+  - family: Aristotle
+  collection-title: Clarendon Aristotle
+  editor:
+  - family: Lucas
+    given: D. W.
+  id: "aristotle:poetics"
+  issued: 1968
+  keyword: primary
+  language: en-GB
+  publisher: Clarendon Press
+  publisher-place: Oxford
+  title: Poetics
+  title-short: Poetics
+  type: book
+---
+
+
+```
diff --git a/test/command/biblatex-aristotle-rhetoric.md b/test/command/biblatex-aristotle-rhetoric.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-aristotle-rhetoric.md
@@ -0,0 +1,80 @@
+```
+% pandoc -f biblatex -t markdown -s
+@comment{
+
+Adapted from biblatex-example.bib
+
+
+Formatted with pandoc and chicago-author-date.csl, 2013-10-23:
+
+(Aristotle 1877)
+
+Aristotle. 1877. *The Rhetoric of Aristotle with a Commentary by the
+Late Edward Meredith Cope*. Edited by Edward Meredith Cope. 3. Cambridge
+University Press.
+
+
+Formatted with pandoc and apa.csl, 2013-10-23:
+
+(Aristotle, 1877)
+
+Aristotle. (1877). *The rhetoric of Aristotle with a commentary by the
+late Edward Meredith Cope*. (E. M. Cope, Ed.) (1-3). Cambridge
+University Press.
+
+
+NOTES:
+
+- biblio2yaml
+	- commentator has no counterpart in CSL
+
+}
+
+@string{ cup     = {Cambridge University Press} }
+
+@Book{aristotle:rhetoric,
+  author       = {Aristotle},
+  title        = {The Rhetoric of {Aristotle} with a commentary by the late {Edward
+                  Meredith Cope}},
+  date         = 1877,
+  editor       = {Cope, Edward Meredith},
+  commentator  = {Cope, Edward Meredith},
+  volumes      = 3,
+  publisher    = cup,
+  keywords     = {primary},
+  hyphenation  = {british},
+  sorttitle    = {Rhetoric of Aristotle},
+  indextitle   = {Rhetoric of {Aristotle}, The},
+  shorttitle   = {Rhetoric},
+  annotation   = {A commented edition. Note the concatenation of the
+                  editor and commentator fields as well as the
+                  volumes, sorttitle, and indextitle
+                  fields},
+}
+
+^D
+---
+nocite: "[@*]"
+references:
+- annote: A commented edition. Note the concatenation of the editor and
+    commentator fields as well as the volumes, sorttitle, and indextitle
+    fields
+  author:
+  - family: Aristotle
+  editor:
+  - family: Cope
+    given: Edward Meredith
+  id: "aristotle:rhetoric"
+  issued: 1877
+  keyword: primary
+  language: en-GB
+  number-of-volumes: 3
+  publisher: Cambridge University Press
+  title: The rhetoric of Aristotle with a commentary by the late Edward
+    Meredith Cope
+  title-short: Rhetoric
+  type: book
+---
+
+
+```
diff --git a/test/command/biblatex-article.md b/test/command/biblatex-article.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-article.md
@@ -0,0 +1,128 @@
+```
+% pandoc -f biblatex -t markdown -s
+@comment{
+    - contains:
+        - an article entry with just the required fields
+        - an article entry with required and all optional fields
+    - notes:
+        - year, month to be ignored if date is present
+        - journal to be ignored if journaltitle is present
+        - editortype, editoratype, editorbtype, editorctype, pubstate,
+series contain keys which, unless corresponding CSL terms exist, require
+locale-specific expansion
+    - limitations:
+        - annotator, commentator, eid, eprint, eprintclass, eprinttype,
+issuetitle, issuesubtitle, language, origlanguage have no matching
+counterparts in CSL
+        - for editor, editora, editorb, editorc (plus editortype,
+editoratype, editorbtype, editorctype) only a subset, editor and director,
+has matching counterparts in CSL
+    - kludges:
+        - note + addendum -> CSL note
+        - number + issue -> CSL issue
+        - handling of titleaddon
+        - handling of (journal) series
+            - done properly, this should be mapped to some CSL variable
+(version? edition? collection-number?), CSL styles would have to be adapted
+            - slightly better kludge would map integer to ordinal + "ser."
+("3" -> "3rd ser."); localization keys "newseries" -> "new ser.",
+"oldseries" -> "old ser."; and print all other values as is -- but still
+wouldn't fit all styles or locales.
+    }
+
+@article{article-req,
+    Author = {Author, Ann},
+    Date = {2013-07-29},
+    Hyphenation = {english},
+    Journaltitle = {The Journaltitle},
+    Title = {An Article Entry with Just the Required Fields}}
+
+@article{article-opt,
+    Addendum = {The Addendum},
+    Annotator = {Annotator, A.},
+    Author = {Author, Jr., Ann A.},
+    Commentator = {Commentator, C.},
+    Date = {2008-12-31},
+    Doi = {10.1086/520976},
+    Editor = {Editor, Edward},
+    Editora = {Editor, A.},
+    Editorb = {Editor, B.},
+    Editorc = {Editor, C.},
+    Eid = {eid},
+    Eprint = {eprint},
+    Eprintclass = {eprintclass},
+    Eprinttype = {eprinttype},
+    Hyphenation = {english},
+    Issn = {issn},
+    Issue = {issue},
+    Issuesubtitle = {The Issuesubtitle},
+    Issuetitle = {The Issuetitle},
+    Journalsubtitle = {The Journalsubtitle},
+    Journaltitle = {The Journaltitle},
+    Journal = {The Journal},
+    Language = {language},
+    Month = {08},
+    Year = {2007},
+    Note = {The Note},
+    Number = {number},
+    Origlanguage = {origlanguage},
+    Pages = {pages},
+    Pubstate = {inpress},
+    Series = {newseries},
+    Subtitle = {The Subtitle},
+    Title = {An Article Entry with the Required and All Optional Fields},
+    Titleaddon = {The Titleaddon},
+    Translator = {Translator, Ted},
+    Url = {http://foo.bar.baz/},
+    Urldate = {2013-07-29},
+    Version = {version},
+    Volume = {volume},
+}
+
+^D
+---
+nocite: "[@*]"
+references:
+- author:
+  - family: Author
+    given: Ann
+  container-title: The Journaltitle
+  id: article-req
+  issued: 2013-07-29
+  language: en-US
+  title: An article entry with just the required fields
+  type: article-journal
+- accessed: 2013-07-29
+  author:
+  - family: Author
+    given: Ann A.
+    suffix: Jr.
+  collection-title: New series
+  container-title: "The Journaltitle: The Journalsubtitle"
+  doi: 10.1086/520976
+  editor:
+  - family: Editor
+    given: Edward
+  id: article-opt
+  issn: issn
+  issue: number, issue
+  issued: 2008-12-31
+  language: en-US
+  note: The Note. The Addendum
+  page: pages
+  status: in press
+  title: "An article entry with the required and all optional fields:
+    The subtitle. The titleaddon"
+  title-short: An article entry with the required and all optional
+    fields
+  translator:
+  - family: Translator
+    given: Ted
+  type: article-journal
+  url: "http://foo.bar.baz/"
+  version: version
+  volume: volume
+---
+
+
+```
diff --git a/test/command/biblatex-augustine.md b/test/command/biblatex-augustine.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-augustine.md
@@ -0,0 +1,56 @@
+```
+% pandoc -f biblatex -t markdown -s
+@comment{
+
+Adapted from biblatex-example.bib
+
+
+Formatted with pandoc and chicago-author-date.csl, 2013-10-23:
+
+(Augustine 1995)
+
+Augustine, Robert L. 1995. *Heterogeneous Catalysis for the Synthetic
+Chemist*. New York: Marcel Dekker.
+
+
+Formatted with pandoc and apa.csl, 2013-10-23:
+
+(Augustine, 1995)
+
+Augustine, R. L. (1995). *Heterogeneous catalysis for the synthetic
+chemist*. New York: Marcel Dekker.
+
+
+}
+
+@Book{augustine,
+  author       = {Augustine, Robert L.},
+  title        = {Heterogeneous catalysis for the synthetic chemist},
+  date         = 1995,
+  publisher    = {Marcel Dekker},
+  location     = {New York},
+  hyphenation  = {american},
+  shorttitle   = {Heterogeneous catalysis},
+  annotation   = {A plain book entry},
+}
+
+^D
+---
+nocite: "[@*]"
+references:
+- annote: A plain book entry
+  author:
+  - family: Augustine
+    given: Robert L.
+  id: augustine
+  issued: 1995
+  language: en-US
+  publisher: Marcel Dekker
+  publisher-place: New York
+  title: Heterogeneous catalysis for the synthetic chemist
+  title-short: Heterogeneous catalysis
+  type: book
+---
+
+
+```
diff --git a/test/command/biblatex-averroes-bland.md b/test/command/biblatex-averroes-bland.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-averroes-bland.md
@@ -0,0 +1,85 @@
+```
+% pandoc -f biblatex -t markdown -s
+@comment{
+
+Adapted from biblatex-example.bib
+
+Formatted with pandoc and chicago-author-date.csl, 2013-10-23:
+
+(Averroes 1982)
+
+Averroes. 1982. *The Epistle on the Possibility of Conjunction with the
+Active Intellect by Ibn Rushd with the Commentary of Moses Narboni*.
+Kalman P. Bland. Moreshet: Studies in Jewish History, Literature and
+Thought 7. New York: Jewish Theological Seminary of America.
+
+
+Formatted with pandoc and apa.csl, 2013-10-23:
+
+(Averroes, 1982)
+
+Averroes. (1982). *The epistle on the possibility of conjunction with
+the active intellect by Ibn Rushd with the commentary of Moses Narboni*.
+(K. P. Bland). New York: Jewish Theological Seminary of America.
+
+
+NOTES:
+
+- citeproc
+	- term "edited and translated by" missing
+
+}
+
+@Book{averroes-bland,
+  author       = {Averroes},
+  title        = {The Epistle on the Possibility of Conjunction with the Active
+                  Intellect by {Ibn Rushd} with the Commentary of {Moses Narboni}},
+  date         = 1982,
+  editor       = {Bland, Kalman P.},
+  translator   = {Bland, Kalman P.},
+  series       = {Moreshet: {Studies} in {Jewish} History, Literature and Thought},
+  number       = 7,
+  publisher    = {Jewish Theological Seminary of America},
+  location     = {New York},
+  keywords     = {primary},
+  hyphenation  = {american},
+  indextitle   = {Epistle on the Possibility of Conjunction, The},
+  shorttitle   = {Possibility of Conjunction},
+  annotation   = {A book entry with a series and a
+                  number. Note the concatenation of the editor
+                  and translator fields as well as the
+                  indextitle field},
+}
+
+^D
+---
+nocite: "[@*]"
+references:
+- annote: A book entry with a series and a number. Note the
+    concatenation of the editor and translator fields as well as the
+    indextitle field
+  author:
+  - family: Averroes
+  collection-number: 7
+  collection-title: "Moreshet: Studies in Jewish history, literature and
+    thought"
+  editor:
+  - family: Bland
+    given: Kalman P.
+  id: averroes-bland
+  issued: 1982
+  keyword: primary
+  language: en-US
+  publisher: Jewish Theological Seminary of America
+  publisher-place: New York
+  title: The epistle on the possibility of conjunction with the active
+    intellect by Ibn Rushd with the commentary of Moses Narboni
+  title-short: Possibility of conjunction
+  translator:
+  - family: Bland
+    given: Kalman P.
+  type: book
+---
+
+
+```
diff --git a/test/command/biblatex-averroes-hannes.md b/test/command/biblatex-averroes-hannes.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-averroes-hannes.md
@@ -0,0 +1,84 @@
+```
+% pandoc -f biblatex -t markdown -s
+@comment{
+
+Adapted from biblatex-example.bib
+
+Formatted with pandoc and chicago-author-date.csl, 2013-10-23:
+
+(Averroes 1892)
+
+Averroes. 1892. *Des Averroës Abhandlung: “Über die Möglichkeit der
+Conjunktion” oder “Über den materiellen Intellekt”*. Ludwig Hannes.
+Halle an der Saale: C. A. Kaemmerer.
+
+
+Formatted with pandoc and apa.csl, 2013-10-23:
+
+(Averroes, 1892)
+
+Averroes. (1892). *Des Averroës Abhandlung: “Über die Möglichkeit der
+Conjunktion” oder “Über den materiellen Intellekt”*. (L. Hannes). Halle
+an der Saale: C. A. Kaemmerer.
+
+
+NOTES:
+
+- citeproc
+	- term "edited and translated by" missing
+
+}
+
+@Book{averroes-hannes,
+  author       = {Averroes},
+  title        = {Des Averro{\"e}s Abhandlung: \mkbibquote{{\"U}ber die
+                  M{\"o}glichkeit der Conjunktion} oder \mkbibquote{{\"U}ber den
+                  materiellen Intellekt}},
+  date         = 1892,
+  editor       = {Hannes, Ludwig},
+  translator   = {Hannes, Ludwig},
+  annotator    = {Hannes, Ludwig},
+  publisher    = {C.~A. Kaemmerer},
+  location     = {Halle an der Saale},
+  keywords     = {primary},
+  hyphenation  = {german},
+  sorttitle    = {Uber die Moglichkeit der Conjunktion},
+  indexsorttitle= {Uber die Moglichkeit der Conjunktion},
+  indextitle   = {{\"U}ber die M{\"o}glichkeit der Conjunktion},
+  shorttitle   = {{\"U}ber die M{\"o}glichkeit der Conjunktion},
+  annotation   = {An annotated edition. Note the concatenation of the
+                  editor, translator, and annotator
+                  fields. Also note the shorttitle,
+                  indextitle, sorttitle, and
+                  indexsorttitle fields},
+}
+
+^D
+---
+nocite: "[@*]"
+references:
+- annote: An annotated edition. Note the concatenation of the editor,
+    translator, and annotator fields. Also note the shorttitle,
+    indextitle, sorttitle, and indexsorttitle fields
+  author:
+  - family: Averroes
+  editor:
+  - family: Hannes
+    given: Ludwig
+  id: averroes-hannes
+  issued: 1892
+  keyword: primary
+  language: de-DE
+  publisher: C. A. Kaemmerer
+  publisher-place: Halle an der Saale
+  title: "Des Averroës Abhandlung: \"Über die Möglichkeit der
+    Conjunktion\" oder \"Über den materiellen Intellekt\""
+  title-short: Über die Möglichkeit der Conjunktion
+  translator:
+  - family: Hannes
+    given: Ludwig
+  type: book
+---
+
+
+```
diff --git a/test/command/biblatex-averroes-hercz.md b/test/command/biblatex-averroes-hercz.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-averroes-hercz.md
@@ -0,0 +1,85 @@
+```
+% pandoc -f biblatex -t markdown -s
+@comment{
+
+Adapted from biblatex-example.bib
+
+
+Formatted with pandoc and chicago-author-date.csl, 2013-10-23:
+
+(Averroes 1869)
+
+Averroes. 1869. *Drei Abhandlungen über die Conjunction des separaten
+Intellects mit dem Menschen: Von Averroes (Vater und Sohn), aus dem
+Arabischen übersetzt von Samuel Ibn Tibbon*. J. Hercz. Berlin:
+S. Hermann.
+
+
+Formatted with pandoc and apa.csl, 2013-10-23:
+
+(Averroes, 1869)
+
+Averroes. (1869). *Drei Abhandlungen über die Conjunction des separaten
+Intellects mit dem Menschen: Von Averroes (Vater und Sohn), aus dem
+Arabischen übersetzt von Samuel Ibn Tibbon*. (J. Hercz). Berlin:
+S. Hermann.
+
+
+NOTES:
+
+- citeproc
+	- term "edited and translated by" missing
+
+}
+
+@Book{averroes-hercz,
+  author       = {Averroes},
+  title        = {Drei Abhandlungen {\"u}ber die Conjunction des separaten
+                  Intellects mit dem Menschen},
+  date         = 1869,
+  editor       = {Hercz, J.},
+  translator   = {Hercz, J.},
+  publisher    = {S.~Hermann},
+  location     = {Berlin},
+  keywords     = {primary},
+  hyphenation  = {german},
+  indexsorttitle= {Drei Abhandlungen uber die Conjunction},
+  indextitle   = {Drei Abhandlungen {\"u}ber die Conjunction},
+  subtitle     = {Von Averroes (Vater und Sohn), aus dem Arabischen
+                  {\"u}bersetzt von Samuel Ibn Tibbon},
+  shorttitle   = {Drei Abhandlungen},
+  annotation   = {A book entry. Note the concatenation of the
+                  editor and translator fields as well as the
+                  indextitle and indexsorttitle fields},
+}
+
+^D
+---
+nocite: "[@*]"
+references:
+- annote: A book entry. Note the concatenation of the editor and
+    translator fields as well as the indextitle and indexsorttitle
+    fields
+  author:
+  - family: Averroes
+  editor:
+  - family: Hercz
+    given: J.
+  id: averroes-hercz
+  issued: 1869
+  keyword: primary
+  language: de-DE
+  publisher: S. Hermann
+  publisher-place: Berlin
+  title: "Drei Abhandlungen über die Conjunction des separaten
+    Intellects mit dem Menschen: Von Averroes (Vater und Sohn), aus dem
+    Arabischen übersetzt von Samuel Ibn Tibbon"
+  title-short: Drei Abhandlungen
+  translator:
+  - family: Hercz
+    given: J.
+  type: book
+---
+
+
+```
diff --git a/test/command/biblatex-baez-article.md b/test/command/biblatex-baez-article.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-baez-article.md
@@ -0,0 +1,76 @@
+```
+% pandoc -f biblatex -t markdown -s
+@comment{
+
+Adapted from biblatex-example.bib
+
+Formatted with pandoc and chicago-author-date.csl, 2013-10-23:
+
+(Baez and Lauda 2004)
+
+Baez, John C., and Aaron D. Lauda. 2004. “Higher-dimensional Algebra V:
+2-groups” (version 3). *Theory and Applications of Categories* 12:
+423–491.
+
+
+Formatted with pandoc and apa.csl, 2013-10-23:
+
+(Baez & Lauda, 2004)
+
+Baez, J. C., & Lauda, A. D. (2004). Higher-dimensional algebra V:
+2-groups. *Theory and Applications of Categories*, *12*, 423–491.
+
+
+NOTES:
+
+- biblio2yaml
+	- eprint: see baez-online
+
+}
+
+@Article{baez-article,
+  author       = {Baez, John C. and Lauda, Aaron D.},
+  title        = {Higher-Dimensional Algebra {V}: 2-Groups},
+  journaltitle = {Theory and Applications of Categories},
+  date         = 2004,
+  volume       = 12,
+  pages        = {423-491},
+  version      = 3,
+  eprint       = {math/0307200v3},
+  eprinttype   = {arxiv},
+  hyphenation  = {american},
+  annotation   = {An article with eprint and
+                  eprinttype fields. Note that the arXiv reference is
+                  transformed into a clickable link if hyperref support
+                  has been enabled.  Compare baez\slash online, which
+                  is the same item given as an online entry},
+}
+
+^D
+---
+nocite: "[@*]"
+references:
+- annote: An article with eprint and eprinttype fields. Note that the
+    arXiv reference is transformed into a clickable link if hyperref
+    support has been enabled. Compare baez/online, which is the same
+    item given as an online entry
+  author:
+  - family: Baez
+    given: John C.
+  - family: Lauda
+    given: Aaron D.
+  container-title: Theory and Applications of Categories
+  id: baez-article
+  issued: 2004
+  language: en-US
+  page: 423-491
+  title: "Higher-dimensional algebra V: 2-groups"
+  title-short: Higher-dimensional algebra V
+  type: article-journal
+  url: "https://arxiv.org/abs/math/0307200v3"
+  version: 3
+  volume: 12
+---
+
+
+```
diff --git a/test/command/biblatex-baez-online.md b/test/command/biblatex-baez-online.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-baez-online.md
@@ -0,0 +1,69 @@
+```
+% pandoc -f biblatex -t markdown -s
+@comment{
+
+Adapted from biblatex-example.bib
+
+Formatted with pandoc and chicago-author-date.csl, 2013-10-23:
+
+(Baez and Lauda 2004)
+
+Baez, John C., and Aaron D. Lauda. 2004. “Higher-dimensional Algebra V:
+2-groups” (version 3). October 27.
+
+
+Formatted with pandoc and apa.csl, 2013-10-23:
+
+(Baez & Lauda, 2004)
+
+Baez, J. C., & Lauda, A. D. (2004, October 27). Higher-dimensional
+algebra V: 2-groups.
+
+
+NOTES:
+
+- biblio2yaml:
+	- eprinttype = {arxiv}, eprint = {math/0307200v3}, 
+	  should be converted to a url: http://arxiv.org/abs/math/0307200v3
+	  (prefix http://arxiv.org/abs/ seems to work for all arxiv material)
+
+}
+
+@Online{baez-online,
+  author       = {Baez, John C. and Lauda, Aaron D.},
+  title        = {Higher-Dimensional Algebra {V}: 2-Groups},
+  date         = {2004-10-27},
+  version      = 3,
+  hyphenation  = {american},
+  eprinttype   = {arxiv},
+  eprint       = {math/0307200v3},
+  annotation   = {An online reference from arXiv. Note the
+                  eprint and eprinttype fields. Compare
+                  baez\slash article which is the same item given as an
+                  article entry with eprint information},
+}
+
+^D
+---
+nocite: "[@*]"
+references:
+- annote: An online reference from arXiv. Note the eprint and eprinttype
+    fields. Compare baez/article which is the same item given as an
+    article entry with eprint information
+  author:
+  - family: Baez
+    given: John C.
+  - family: Lauda
+    given: Aaron D.
+  id: baez-online
+  issued: 2004-10-27
+  language: en-US
+  title: "Higher-dimensional algebra V: 2-groups"
+  title-short: Higher-dimensional algebra V
+  type: webpage
+  url: "https://arxiv.org/abs/math/0307200v3"
+  version: 3
+---
+
+
+```
diff --git a/test/command/biblatex-basic.md b/test/command/biblatex-basic.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-basic.md
@@ -0,0 +1,71 @@
+```
+% pandoc -f biblatex -t markdown -s
+@Book{item1,
+author="John Doe",
+title="First Book",
+year="2005",
+address="Cambridge",
+publisher="Cambridge University Press"
+}
+
+@Article{item2,
+author="John Doe",
+title="Article",
+year="2006",
+journal="Journal of Generic Studies",
+volume="6",
+pages="33-34"
+}
+
+@InCollection{пункт3,
+author="John Doe and Jenny Roe",
+title="Why Water Is Wet",
+booktitle="Third Book",
+editor="Sam Smith",
+publisher="Oxford University Press",
+address="Oxford",
+year="2007"
+}
+
+^D
+---
+nocite: "[@*]"
+references:
+- author:
+  - family: Doe
+    given: John
+  id: item1
+  issued: 2005
+  publisher: Cambridge University Press
+  publisher-place: Cambridge
+  title: First book
+  type: book
+- author:
+  - family: Doe
+    given: John
+  container-title: Journal of Generic Studies
+  id: item2
+  issued: 2006
+  page: 33-34
+  title: Article
+  type: article-journal
+  volume: 6
+- author:
+  - family: Doe
+    given: John
+  - family: Roe
+    given: Jenny
+  container-title: Third book
+  editor:
+  - family: Smith
+    given: Sam
+  id: пункт3
+  issued: 2007
+  publisher: Oxford University Press
+  publisher-place: Oxford
+  title: Why water is wet
+  type: chapter
+---
+
+
+```
diff --git a/test/command/biblatex-bertram.md b/test/command/biblatex-bertram.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-bertram.md
@@ -0,0 +1,66 @@
+```
+% pandoc -f biblatex -t markdown -s
+@comment{
+
+Adapted from biblatex-example.bib
+
+
+Formatted with pandoc and chicago-author-date.csl, 2013-10-23:
+
+(Bertram and Wentworth 1996)
+
+Bertram, Aaron, and Richard Wentworth. 1996. “Gromov Invariants for
+Holomorphic Maps on Riemann Surfaces.” *J. Amer. Math. Soc.* 9 (2):
+529–571.
+
+
+Formatted with pandoc and apa.csl, 2013-10-23:
+
+(Bertram & Wentworth, 1996)
+
+Bertram, A., & Wentworth, R. (1996). Gromov invariants for holomorphic
+maps on Riemann surfaces. *J. Amer. Math. Soc.*, *9*(2), 529–571.
+
+
+}
+
+@string{ jams    = {J.~Amer. Math. Soc.} }
+
+@Article{bertram,
+  author       = {Bertram, Aaron and Wentworth, Richard},
+  title        = {Gromov invariants for holomorphic maps on {Riemann} surfaces},
+  journaltitle = jams,
+  date         = 1996,
+  volume       = 9,
+  number       = 2,
+  pages        = {529-571},
+  hyphenation  = {american},
+  shorttitle   = {Gromov invariants},
+  annotation   = {An article entry with a volume and a
+                  number field},
+}
+
+^D
+---
+nocite: "[@*]"
+references:
+- annote: An article entry with a volume and a number field
+  author:
+  - family: Bertram
+    given: Aaron
+  - family: Wentworth
+    given: Richard
+  container-title: J. Amer. Math. Soc.
+  id: bertram
+  issue: 2
+  issued: 1996
+  language: en-US
+  page: 529-571
+  title: Gromov invariants for holomorphic maps on Riemann surfaces
+  title-short: Gromov invariants
+  type: article-journal
+  volume: 9
+---
+
+
+```
diff --git a/test/command/biblatex-bibstring-resolution.md b/test/command/biblatex-bibstring-resolution.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-bibstring-resolution.md
@@ -0,0 +1,20 @@
+```
+% pandoc -f biblatex -t markdown -s
+@book{item1,
+	Title = {The Title: \bibstring{newseries}},
+        Hyphenation = {english}
+}
+
+^D
+---
+nocite: "[@*]"
+references:
+- id: item1
+  language: en-US
+  title: "The title: New series"
+  title-short: The title
+  type: book
+---
+
+
+```
diff --git a/test/command/biblatex-book-averroes.md b/test/command/biblatex-book-averroes.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-book-averroes.md
@@ -0,0 +1,129 @@
+```
+% pandoc -f biblatex -t markdown -s
+@comment{
+adapted from
+http://mirrors.ctan.org/macros/latex/contrib/biblatex/doc/examples/biblatex-examples.bib}
+
+@book{averroes/bland,
+	Annotation = {A book entry with a series and a number. Note the concatenation of the editor and translator fields as well as the indextitle field},
+	Author = {Averroes},
+	Date = 1982,
+	Editor = {Bland, Kalman P.},
+	Hyphenation = {american},
+	Indextitle = {Epistle on the Possibility of Conjunction, The},
+	Keywords = {primary},
+	Location = {New York},
+	Number = 7,
+	Publisher = {Jewish Theological Seminary of America},
+	Series = {{Moreshet: Studies in Jewish History, Literature and Thought}},
+	Shorttitle = {Possibility of Conjunction},
+	Title = {The Epistle on the Possibility of Conjunction with the Active Intellect by {Ibn Rushd} with the Commentary of {Moses Narboni}},
+	Translator = {Bland, Kalman P.}}
+
+@book{averroes/hannes,
+	Annotation = {An annotated edition. Note the concatenation of the editor, translator, and annotator fields. Also note the shorttitle, indextitle, sorttitle, and indexsorttitle fields},
+	Annotator = {Hannes, Ludwig},
+	Author = {Averroes},
+	Date = 1892,
+	Editor = {Hannes, Ludwig},
+	Hyphenation = {german},
+	Indexsorttitle = {Uber die Moglichkeit der Conjunktion},
+	Indextitle = {Über die Möglichkeit der Conjunktion},
+	Keywords = {primary},
+	Location = {Halle an der Saale},
+	Publisher = {C.~A. Kaemmerer},
+	Shorttitle = {Über die Möglichkeit der Conjunktion},
+	Sorttitle = {Uber die Moglichkeit der Conjunktion},
+	Title = {Des Averroës Abhandlung: \mkbibquote{Über die Möglichkeit der Conjunktion} oder \mkbibquote{Über den materiellen Intellekt}},
+	Translator = {Hannes, Ludwig}}
+
+@book{averroes/hercz,
+	Annotation = {A book entry. Note the concatenation of the editor and translator fields as well as the indextitle and indexsorttitle fields},
+	Author = {Averroes},
+	Date = 1869,
+	Editor = {Hercz, J.},
+	Hyphenation = {german},
+	Indexsorttitle = {Drei Abhandlungen uber die Conjunction},
+	Indextitle = {Drei Abhandlungen über die Conjunction},
+	Keywords = {primary},
+	Location = {Berlin},
+	Publisher = {S.~Hermann},
+	Shorttitle = {Drei Abhandlungen},
+	Subtitle = {Von Averroes (Vater und Sohn), aus dem Arabischen übersetzt von Samuel Ibn Tibbon},
+	Title = {Drei Abhandlungen über die Conjunction des separaten Intellects mit dem Menschen},
+	Translator = {Hercz, J.}}
+^D
+---
+nocite: "[@*]"
+references:
+- annote: A book entry with a series and a number. Note the
+    concatenation of the editor and translator fields as well as the
+    indextitle field
+  author:
+  - family: Averroes
+  collection-number: 7
+  collection-title: "[Moreshet: Studies in Jewish History, Literature
+    and Thought]{.nocase}"
+  editor:
+  - family: Bland
+    given: Kalman P.
+  id: averroes/bland
+  issued: 1982
+  keyword: primary
+  language: en-US
+  publisher: Jewish Theological Seminary of America
+  publisher-place: New York
+  title: The epistle on the possibility of conjunction with the active
+    intellect by Ibn Rushd with the commentary of Moses Narboni
+  title-short: Possibility of conjunction
+  translator:
+  - family: Bland
+    given: Kalman P.
+  type: book
+- annote: An annotated edition. Note the concatenation of the editor,
+    translator, and annotator fields. Also note the shorttitle,
+    indextitle, sorttitle, and indexsorttitle fields
+  author:
+  - family: Averroes
+  editor:
+  - family: Hannes
+    given: Ludwig
+  id: averroes/hannes
+  issued: 1892
+  keyword: primary
+  language: de-DE
+  publisher: C. A. Kaemmerer
+  publisher-place: Halle an der Saale
+  title: "Des Averroës Abhandlung: \"Über die Möglichkeit der
+    Conjunktion\" oder \"Über den materiellen Intellekt\""
+  title-short: Über die Möglichkeit der Conjunktion
+  translator:
+  - family: Hannes
+    given: Ludwig
+  type: book
+- annote: A book entry. Note the concatenation of the editor and
+    translator fields as well as the indextitle and indexsorttitle
+    fields
+  author:
+  - family: Averroes
+  editor:
+  - family: Hercz
+    given: J.
+  id: averroes/hercz
+  issued: 1869
+  keyword: primary
+  language: de-DE
+  publisher: S. Hermann
+  publisher-place: Berlin
+  title: "Drei Abhandlungen über die Conjunction des separaten
+    Intellects mit dem Menschen: Von Averroes (Vater und Sohn), aus dem
+    Arabischen übersetzt von Samuel Ibn Tibbon"
+  title-short: Drei Abhandlungen
+  translator:
+  - family: Hercz
+    given: J.
+  type: book
+---
+
+
+```
diff --git a/test/command/biblatex-book-coleridge.md b/test/command/biblatex-book-coleridge.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-book-coleridge.md
@@ -0,0 +1,59 @@
+```
+% pandoc -f biblatex -t markdown -s
+@comment{adapted from http://mirrors.ctan.org/macros/latex/contrib/biblatex/doc/examples/biblatex-examples.bib
+
+TODO (as a stopgap):
+Combine biblatex “volume = 7” and “part = 2” to CSL “volume: 7.2”
+
+}
+
+@book{coleridge,
+	Annotation = {One (partial) volume of a multivolume book. This is a book entry with a volume and a part field which explicitly refers to the second (physical) part of the seventh (logical) volume. Also note the series and number fields},
+	Author = {Coleridge, Samuel Taylor},
+	Date = 1983,
+	Editor = {Coburn, Kathleen and Engell, James and Bate, W. Jackson},
+	Hyphenation = {british},
+	Indextitle = {Biographia literaria},
+	Location = {London},
+	Maintitle = {The collected works of {Samuel Taylor Coleridge}},
+	Number = 75,
+	Part = 2,
+	Publisher = {Routledge {and} Kegan Paul},
+	Series = {Bollingen Series},
+	Shorttitle = {Biographia literaria},
+	Title = {Biographia literaria, or {Biographical} sketches of my literary life and opinions},
+	Volume = 7}
+^D
+---
+nocite: "[@*]"
+references:
+- annote: One (partial) volume of a multivolume book. This is a book
+    entry with a volume and a part field which explicitly refers to the
+    second (physical) part of the seventh (logical) volume. Also note
+    the series and number fields
+  author:
+  - family: Coleridge
+    given: Samuel Taylor
+  collection-number: 75
+  collection-title: Bollingen series
+  editor:
+  - family: Coburn
+    given: Kathleen
+  - family: Engell
+    given: James
+  - family: Bate
+    given: W. Jackson
+  id: coleridge
+  issued: 1983
+  language: en-GB
+  publisher: Routledge and Kegan Paul
+  publisher-place: London
+  title: The collected works of Samuel Taylor Coleridge
+  type: book
+  volume: 7.2
+  volume-title: Biographia literaria, or Biographical sketches of my
+    literary life and opinions
+---
+
+
+```
diff --git a/test/command/biblatex-book-title-maintitle-series.md b/test/command/biblatex-book-title-maintitle-series.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-book-title-maintitle-series.md
@@ -0,0 +1,39 @@
+```
+% pandoc -f biblatex -t markdown -s
+@book{item1,
+	Author = {Author, Al},
+	Date = {2013},
+	Hyphenation = {french},
+	Location = {Location},
+	Mainsubtitle = {Mainsubtitle},
+	Maintitle = {Maintitle},
+	Maintitleaddon = {Maintitleaddon},
+	Number = {3},
+	Publisher = {Publisher},
+	Series = {Series},
+	Subtitle = {Subtitle},
+	Title = {Title of the Book},
+	Titleaddon = {Titleaddon},
+}
+
+^D
+---
+nocite: "[@*]"
+references:
+- author:
+  - family: Author
+    given: Al
+  collection-number: 3
+  collection-title: Series
+  id: item1
+  issued: 2013
+  language: fr-FR
+  publisher: Publisher
+  publisher-place: Location
+  title: "Maintitle: Mainsubtitle. Maintitleaddon"
+  type: book
+  volume-title: "Title of the Book: Subtitle. Titleaddon"
+---
+
+
+```
diff --git a/test/command/biblatex-book-vazques-de-parga.md b/test/command/biblatex-book-vazques-de-parga.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-book-vazques-de-parga.md
@@ -0,0 +1,48 @@
+```
+% pandoc -f biblatex -t markdown -s
+@comment{excerpted from http://mirrors.ctan.org/macros/latex/contrib/biblatex/doc/examples/biblatex-examples.bib
+
+Note handling of Author = {Vázques{ de }Parga, Luis}
+
+}
+
+@book{vazques-de-parga,
+	Annotation = {A multivolume book cited as a whole. This is a book entry with volumes, note, sorttitle, and indextitle fields},
+	Author = {Vázques{ de }Parga, Luis and Lacarra, José María and Uría Ríu, Juan},
+	Date = 1993,
+	Hyphenation = {spanish},
+	Indextitle = {Peregrinaciones a Santiago de Compostela, Las},
+	Location = {Pamplona},
+	Note = {Ed. facs. de la realizada en 1948--49},
+	Publisher = {Iberdrola},
+	Shorttitle = {Peregrinaciones},
+	Sorttitle = {Peregrinaciones a Santiago de Compostela},
+	Title = {Las Peregrinaciones a Santiago de Compostela},
+	Volumes = 3}
+^D
+---
+nocite: "[@*]"
+references:
+- annote: A multivolume book cited as a whole. This is a book entry with
+    volumes, note, sorttitle, and indextitle fields
+  author:
+  - family: Vázques de Parga
+    given: Luis
+  - family: Lacarra
+    given: José María
+  - family: Uría Ríu
+    given: Juan
+  id: vazques-de-parga
+  issued: 1993
+  language: es-ES
+  note: Ed. facs. de la realizada en 1948--49
+  number-of-volumes: 3
+  publisher: Iberdrola
+  publisher-place: Pamplona
+  title: Las Peregrinaciones a Santiago de Compostela
+  title-short: Peregrinaciones
+  type: book
+---
+
+
+```
diff --git a/test/command/biblatex-brandt.md b/test/command/biblatex-brandt.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-brandt.md
@@ -0,0 +1,88 @@
+```
+% pandoc -f biblatex -t markdown -s
+@comment{
+
+Adapted from biblatex-example.bib
+
+
+Formatted with pandoc and chicago-author-date.csl, 2013-10-23:
+
+(Brandt and Hoffmann 1987)
+
+Brandt, Ahasver von, and Erich Hoffmann. 1987. “Die nordischen Länder
+von der Mitte des 11. Jahrhunderts bis 1448.” In *Europa im Hoch- und
+Spätmittelalter*, edited by Ferdinand Seibt, 884–917. Handbuch der
+europäischen Geschichte 2. Stuttgart: Klett-Cotta.
+
+
+Formatted with pandoc and apa.csl, 2013-10-23:
+
+(Brandt & Hoffmann, 1987)
+
+Brandt, A. von, & Hoffmann, E. (1987). Die nordischen Länder von der
+Mitte des 11. Jahrhunderts bis 1448. In F. Seibt (ed.), *Europa im Hoch-
+und Spätmittelalter* (pp. 884–917). Stuttgart: Klett-Cotta.
+
+
+}
+
+@InCollection{brandt,
+  author       = {von Brandt, Ahasver and Erich Hoffmann},
+  editor       = {Ferdinand Seibt},
+  title        = {Die nordischen L{\"a}nder von der Mitte des 11.~Jahrhunderts
+                  bis 1448},
+  date         = 1987,
+  booktitle    = {Europa im Hoch- und Sp{\"a}tmittelalter},
+  series       = {Handbuch der europ{\"a}ischen Geschichte},
+  number       = 2,
+  publisher    = {Klett-Cotta},
+  location     = {Stuttgart},
+  pages        = {884-917},
+  options      = {useprefix=false},
+  hyphenation  = {german},
+  indexsorttitle= {Nordischen Lander von der Mitte des 11. Jahrhunderts bis
+                  1448},
+  indextitle   = {Nordischen L{\"a}nder von der Mitte des 11.~Jahrhunderts bis
+                  1448, Die},
+  shorttitle   = {Die nordischen L{\"a}nder},
+  annotation   = {An incollection entry with a series and a
+                  number. Note the format of the printed name and
+                  compare the useprefix option in the options
+                  field as well as vangennep. Also note the
+                  indextitle, and indexsorttitle fields},
+}
+
+^D
+---
+nocite: "[@*]"
+references:
+- annote: An incollection entry with a series and a number. Note the
+    format of the printed name and compare the useprefix option in the
+    options field as well as vangennep. Also note the indextitle, and
+    indexsorttitle fields
+  author:
+  - dropping-particle: von
+    family: Brandt
+    given: Ahasver
+  - family: Hoffmann
+    given: Erich
+  collection-number: 2
+  collection-title: Handbuch der europäischen Geschichte
+  container-title: Europa im Hoch- und Spätmittelalter
+  editor:
+  - family: Seibt
+    given: Ferdinand
+  id: brandt
+  issued: 1987
+  language: de-DE
+  page: 884-917
+  publisher: Klett-Cotta
+  publisher-place: Stuttgart
+  title: Die nordischen Länder von der Mitte des 11. Jahrhunderts bis
+    1448
+  title-short: Die nordischen Länder
+  type: chapter
+---
+
+
+```
diff --git a/test/command/biblatex-britannica.md b/test/command/biblatex-britannica.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-britannica.md
@@ -0,0 +1,85 @@
+```
+% pandoc -f biblatex -t markdown -s
+@comment{
+
+Adapted from biblatex-example.bib
+
+Formatted with pandoc and chicago-author-date.csl, 2013-10-23:
+
+(Preece 2003)
+
+Preece, Warren E., ed. 2003. *The New EncyclopæDia Britannica*. 15th ed.
+32. Chicago, Ill.: Encyclopædia Britannica.
+
+
+Formatted with pandoc and apa.csl, 2013-10-23:
+
+(Preece, 2003)
+
+Preece, W. E. (Ed.). (2003). *The new encyclopædia Britannica* (15th
+ed., 1-32). Chicago, Ill.: Encyclopædia Britannica.
+
+
+NOTES:
+
+- biblio2yaml
+	- spurious <span> in Encyclopædia
+	- options = {useeditor=false} has no equivalent in CSL, so citing and alphabetizing by title even though there is an editor does not seem to be possible
+
+- citeproc
+	- incorrect camel case: "EncyclopæDia"
+	- term "vols." missing
+
+}
+
+@Collection{britannica,
+  editor       = {Preece, Warren E.},
+  title        = {The New Encyclop{\ae}dia {Britannica}},
+  date         = 2003,
+  edition      = 15,
+  volumes      = 32,
+  publisher    = {Encyclop{\ae}dia Britannica},
+  location     = {Chicago, Ill.},
+  options      = {useeditor=false},
+  label        = {EB},
+  hyphenation  = {british},
+  sorttitle    = {Encyclop{\ae}dia Britannica},
+  indextitle   = {Encyclop{\ae}dia Britannica, The New},
+  shorttitle   = {Encyclop{\ae}dia {Britannica}},
+  annotation   = {This is a collection entry for an encyclopedia. Note
+                  the useeditor option in the options field as
+                  well as the sorttitle field. We want this entry to be
+                  cited and alphabetized by title even though there is an
+                  editor. In addition to that, we want the title to be
+                  alphabetized under \enquote*{E} rather than \enquote*{T}. Also
+                  note the label field which is provided for
+                  author-year citation styles},
+}
+
+^D
+---
+nocite: "[@*]"
+references:
+- annote: This is a collection entry for an encyclopedia. Note the
+    useeditor option in the options field as well as the sorttitle
+    field. We want this entry to be cited and alphabetized by title even
+    though there is an editor. In addition to that, we want the title to
+    be alphabetized under 'E' rather than 'T'. Also note the label field
+    which is provided for author-year citation styles
+  edition: 15
+  editor:
+  - family: Preece
+    given: Warren E.
+  id: britannica
+  issued: 2003
+  language: en-GB
+  number-of-volumes: 32
+  publisher: Encyclopædia Britannica
+  publisher-place: Chicago, Ill.
+  title: The new encyclopædia Britannica
+  title-short: Encyclopædia Britannica
+  type: book
+---
+
+
+```
diff --git a/test/command/biblatex-chiu.md b/test/command/biblatex-chiu.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-chiu.md
@@ -0,0 +1,77 @@
+```
+% pandoc -f biblatex -t markdown -s
+@comment{
+
+Adapted from biblatex-example.bib
+
+
+Formatted with pandoc and chicago-author-date.csl, 2013-10-23:
+
+(Chiu and Chow 1978)
+
+Chiu, Willy W., and We Min Chow. 1978. “A Hybrid Hierarchical Model of a
+Multiple Virtual Storage (MVS) Operating System.” Research report
+RC-6947. IBM.
+
+
+Formatted with pandoc and apa.csl, 2013-10-23:
+
+(Chiu & Chow, 1978)
+
+Chiu, W. W., & Chow, W. M. (1978). *A hybrid hierarchical model of a
+multiple virtual storage (MVS) operating system* (research report No.
+RC-6947). IBM.
+
+
+NOTES:
+
+- biblio2yaml
+	- "MVS", when not wrapped in {}, gives "mVS", which is probably never intended, or useful (latex converts the whole word to lowercase if unprotected ("MVS" -> "mvs"))
+
+}
+
+@Report{chiu,
+  author       = {Chiu, Willy W. and Chow, We Min},
+  title        = {A Hybrid Hierarchical Model of a Multiple Virtual Storage
+                  ({MVS}) Operating System},
+  type         = {resreport},
+  institution  = {IBM},
+  date         = 1978,
+  number       = {RC-6947},
+  hyphenation  = {american},
+  sorttitle    = {Hybrid Hierarchical Model of a Multiple Virtual Storage (MVS)
+                  Operating System},
+  indextitle   = {Hybrid Hierarchical Model, A},
+  annotation   = {This is a report entry for a research report. Note
+                  the format of the type field in the database file
+                  which uses a localization key. The number of the report is
+                  given in the number field. Also note the
+                  sorttitle and indextitle fields},
+}
+
+^D
+---
+nocite: "[@*]"
+references:
+- annote: This is a report entry for a research report. Note the format
+    of the type field in the database file which uses a localization
+    key. The number of the report is given in the number field. Also
+    note the sorttitle and indextitle fields
+  author:
+  - family: Chiu
+    given: Willy W.
+  - family: Chow
+    given: We Min
+  genre: research report
+  id: chiu
+  issued: 1978
+  language: en-US
+  number: RC-6947
+  publisher: IBM
+  title: A hybrid hierarchical model of a multiple virtual storage (MVS)
+    operating system
+  type: report
+---
+
+
+```
diff --git a/test/command/biblatex-cicero.md b/test/command/biblatex-cicero.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-cicero.md
@@ -0,0 +1,82 @@
+```
+% pandoc -f biblatex -t markdown -s
+@comment{
+
+Adapted from biblatex-example.bib
+
+
+Formatted with pandoc and chicago-author-date.csl, 2013-10-23:
+
+(Cicero 1995)
+
+Cicero, Marcus Tullius. 1995. *De natura deorum. Über das Wesen der
+Götter*. Ursula Blank-Sangmeister. Stuttgart: Reclam.
+
+
+Formatted with pandoc and apa.csl, 2013-10-23:
+
+(Cicero, 1995)
+
+Cicero, M. T. (1995). *De natura deorum. Über das Wesen der Götter*. (U.
+Blank-Sangmeister). Stuttgart: Reclam.
+
+
+NOTES:
+
+- biblio2yaml
+	- afterword, language: no CSL variables available
+
+- citeproc:
+	- term such as "edited and translated by" should appear
+
+}
+
+@Book{cicero,
+  author       = {Cicero, Marcus Tullius},
+  title        = {De natura deorum. {\"U}ber das Wesen der G{\"o}tter},
+  date         = 1995,
+  editor       = {Blank-Sangmeister, Ursula},
+  translator   = {Blank-Sangmeister, Ursula},
+  afterword    = {Thraede, Klaus},
+  language     = {langlatin and langgerman},
+  publisher    = {Reclam},
+  location     = {Stuttgart},
+  hyphenation  = {german},
+  indextitle   = {De natura deorum},
+  shorttitle   = {De natura deorum},
+  annotation   = {A bilingual edition of Cicero's \emph{De natura deorum}, with
+                  a German translation. Note the format of the language
+                  field in the database file, the concatenation of the
+                  editor and translator fields, and the
+                  afterword field},
+}
+
+^D
+---
+nocite: "[@*]"
+references:
+- annote: A bilingual edition of Cicero's *De natura deorum*, with a
+    German translation. Note the format of the language field in the
+    database file, the concatenation of the editor and translator
+    fields, and the afterword field
+  author:
+  - family: Cicero
+    given: Marcus Tullius
+  editor:
+  - family: Blank-Sangmeister
+    given: Ursula
+  id: cicero
+  issued: 1995
+  language: de-DE
+  publisher: Reclam
+  publisher-place: Stuttgart
+  title: De natura deorum. Über das Wesen der Götter
+  title-short: De natura deorum
+  translator:
+  - family: Blank-Sangmeister
+    given: Ursula
+  type: book
+---
+
+
+```
diff --git a/test/command/biblatex-cms.md b/test/command/biblatex-cms.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-cms.md
@@ -0,0 +1,81 @@
+```
+% pandoc -f biblatex -t markdown -s
+@comment{
+
+Adapted from biblatex-example.bib
+
+Formatted with pandoc and chicago-author-date.csl, 2013-10-23:
+
+(*The Chicago Manual of Style: The Essential Guide for Writers, Editors,
+and Publishers* 2003)
+
+*The Chicago Manual of Style: The Essential Guide for Writers, Editors,
+and Publishers*. 2003. 15th ed. Chicago, Ill.: University of Chicago
+Press.
+
+
+Formatted with pandoc and apa.csl, 2013-10-23:
+
+(*Chicago manual of style*, 2003)
+
+*The Chicago manual of style: The essential guide for writers, editors,
+and publishers*. (2003) (15th ed.). Chicago, Ill.: University of Chicago
+Press.
+
+
+NOTES:
+
+- chicago-author-date.csl should have as in-text citation: 
+  (*Chicago Manual of Style* 2003)
+  Same behaviour in Zotero; most probably a style file issue.
+
+}
+
+@Manual{cms,
+  title        = {The {Chicago} Manual of Style},
+  date         = 2003,
+  subtitle     = {The Essential Guide for Writers, Editors, and Publishers},
+  edition      = 15,
+  publisher    = {University of Chicago Press},
+  location     = {Chicago, Ill.},
+  isbn         = {0-226-10403-6},
+  label        = {CMS},
+  hyphenation  = {american},
+  sorttitle    = {Chicago Manual of Style},
+  indextitle   = {Chicago Manual of Style, The},
+  shorttitle   = {Chicago Manual of Style},
+  annotation   = {This is a manual entry without an author or
+                  editor. Note the label field in the database
+                  file which is provided for author-year citation styles. Also
+                  note the sorttitle and indextitle fields. By
+                  default, all entries without an author or
+                  editor are alphabetized by title but we want
+                  this entry to be alphabetized under \enquote*{C} rather than
+                  \enquote*{T}. There's also an isbn field},
+}
+
+^D
+---
+nocite: "[@*]"
+references:
+- annote: This is a manual entry without an author or editor. Note the
+    label field in the database file which is provided for author-year
+    citation styles. Also note the sorttitle and indextitle fields. By
+    default, all entries without an author or editor are alphabetized by
+    title but we want this entry to be alphabetized under 'C' rather
+    than 'T'. There's also an isbn field
+  edition: 15
+  id: cms
+  isbn: 0-226-10403-6
+  issued: 2003
+  language: en-US
+  publisher: University of Chicago Press
+  publisher-place: Chicago, Ill.
+  title: "The Chicago manual of style: The essential guide for writers,
+    editors, and publishers"
+  title-short: Chicago manual of style
+  type: book
+---
+
+
+```
diff --git a/test/command/biblatex-coleridge.md b/test/command/biblatex-coleridge.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-coleridge.md
@@ -0,0 +1,86 @@
+```
+% pandoc -f biblatex -t markdown -s
+@comment{
+
+Adapted from biblatex-example.bib
+
+
+Formatted with pandoc and chicago-author-date.csl, 2015-03-08:
+
+(Coleridge 1983)
+
+Coleridge, Samuel Taylor. 1983. *The Collected Works of Samuel Taylor
+Coleridge*. Edited by Kathleen Coburn, James Engell, and W. Jackson
+Bate. Vol. 7.2. Bollingen Series 75. London: Routledge and Kegan Paul.
+
+Formatted with pandoc and apa.csl, 2015-03-08:
+
+(Coleridge, 1983)
+
+Coleridge, S. T. (1983). *The collected works of Samuel Taylor
+Coleridge*. (K. Coburn, J. Engell, & W. J. Bate, Eds.) (Vol. 7.2).
+London: Routledge and Kegan Paul.
+
+NOTES:
+
+- volume-title currently not implemented by chicago-author-date.csl and apa.csl.
+
+}
+
+@Book{coleridge,
+  author       = {Coleridge, Samuel Taylor},
+  title        = {Biographia literaria, or {Biographical} sketches of my literary
+                  life and opinions},
+  date         = 1983,
+  editor       = {Coburn, Kathleen and Engell, James and Bate, W. Jackson},
+  maintitle    = {The collected works of {Samuel Taylor Coleridge}},
+  volume       = 7,
+  part         = 2,
+  series       = {Bollingen Series},
+  number       = 75,
+  publisher    = {Routledge {and} Kegan Paul},
+  location     = {London},
+  hyphenation  = {british},
+  indextitle   = {Biographia literaria},
+  shorttitle   = {Biographia literaria},
+  annotation   = {One (partial) volume of a multivolume book. This is a
+                  book entry with a volume and a part
+                  field which explicitly refers to the second (physical) part of
+                  the seventh (logical) volume. Also note the series
+                  and number fields},
+}
+
+^D
+---
+nocite: "[@*]"
+references:
+- annote: One (partial) volume of a multivolume book. This is a book
+    entry with a volume and a part field which explicitly refers to the
+    second (physical) part of the seventh (logical) volume. Also note
+    the series and number fields
+  author:
+  - family: Coleridge
+    given: Samuel Taylor
+  collection-number: 75
+  collection-title: Bollingen series
+  editor:
+  - family: Coburn
+    given: Kathleen
+  - family: Engell
+    given: James
+  - family: Bate
+    given: W. Jackson
+  id: coleridge
+  issued: 1983
+  language: en-GB
+  publisher: Routledge and Kegan Paul
+  publisher-place: London
+  title: The collected works of Samuel Taylor Coleridge
+  type: book
+  volume: 7.2
+  volume-title: Biographia literaria, or Biographical sketches of my
+    literary life and opinions
+---
+
+
+```
diff --git a/test/command/biblatex-companion.md b/test/command/biblatex-companion.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-companion.md
@@ -0,0 +1,70 @@
+```
+% pandoc -f biblatex -t markdown -s
+@comment{
+
+Adapted from biblatex-example.bib
+
+
+Formatted with pandoc and chicago-author-date.csl, 2013-10-23:
+
+(Goossens, Mittelbach, and Samarin 1994)
+
+Goossens, Michel, Frank Mittelbach, and Alexander Samarin. 1994. *The
+LaTeX Companion*. 1st ed. Reading, Mass.: Addison-Wesley.
+
+
+Formatted with pandoc and apa.csl, 2013-10-23:
+
+(Goossens, Mittelbach, & Samarin, 1994)
+
+Goossens, M., Mittelbach, F., & Samarin, A. (1994). *The LaTeX
+companion* (1st ed.). Reading, Mass.: Addison-Wesley.
+
+
+}
+
+@Book{companion,
+  author       = {Goossens, Michel and Mittelbach, Frank and Samarin, Alexander},
+  title        = {The {LaTeX} Companion},
+  date         = 1994,
+  edition      = 1,
+  publisher    = {Addison-Wesley},
+  location     = {Reading, Mass.},
+  pagetotal    = 528,
+  hyphenation  = {american},
+  sorttitle    = {LaTeX Companion},
+  indextitle   = {LaTeX Companion, The},
+  shorttitle   = {LaTeX Companion},
+  annotation   = {A book with three authors. Note the formatting of the author
+                  list. By default, only the first name is reversed in the
+                  bibliography},
+}
+
+^D
+---
+nocite: "[@*]"
+references:
+- annote: A book with three authors. Note the formatting of the author
+    list. By default, only the first name is reversed in the
+    bibliography
+  author:
+  - family: Goossens
+    given: Michel
+  - family: Mittelbach
+    given: Frank
+  - family: Samarin
+    given: Alexander
+  edition: 1
+  id: companion
+  issued: 1994
+  language: en-US
+  number-of-pages: 528
+  publisher: Addison-Wesley
+  publisher-place: Reading, Mass.
+  title: The LaTeX companion
+  title-short: LaTeX companion
+  type: book
+---
+
+
+```
diff --git a/test/command/biblatex-cotton.md b/test/command/biblatex-cotton.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-cotton.md
@@ -0,0 +1,69 @@
+```
+% pandoc -f biblatex -t markdown -s
+@comment{
+
+Adapted from biblatex-example.bib
+
+
+Formatted with pandoc and chicago-author-date.csl, 2013-10-23:
+
+(Cotton et al. 1999)
+
+Cotton, Frank Albert, Geoffrey Wilkinson, Carlos A. Murillio, and
+Manfred Bochmann. 1999. *Advanced Inorganic Chemistry*. 6th ed.
+Chichester: Wiley.
+
+
+Formatted with pandoc and apa.csl, 2013-10-23:
+
+(Cotton, Wilkinson, Murillio, & Bochmann, 1999)
+
+Cotton, F. A., Wilkinson, G., Murillio, C. A., & Bochmann, M. (1999).
+*Advanced inorganic chemistry* (6th ed.). Chichester: Wiley.
+
+
+}
+
+@Book{cotton,
+  author       = {Cotton, Frank Albert and Wilkinson, Geoffrey and Murillio,
+                  Carlos A. and Bochmann, Manfred},
+  title        = {Advanced inorganic chemistry},
+  date         = 1999,
+  edition      = 6,
+  publisher    = {Wiley},
+  location     = {Chichester},
+  hyphenation  = {british},
+  annotation   = {A book entry with \arabic{author} authors and an
+                  edition field. By default, long author and
+                  editor lists are automatically truncated. This is
+                  configurable},
+}
+
+^D
+---
+nocite: "[@*]"
+references:
+- annote: A book entry with `\arabic{author}`{=latex} authors and an
+    edition field. By default, long author and editor lists are
+    automatically truncated. This is configurable
+  author:
+  - family: Cotton
+    given: Frank Albert
+  - family: Wilkinson
+    given: Geoffrey
+  - family: Murillio
+    given: Carlos A.
+  - family: Bochmann
+    given: Manfred
+  edition: 6
+  id: cotton
+  issued: 1999
+  language: en-GB
+  publisher: Wiley
+  publisher-place: Chichester
+  title: Advanced inorganic chemistry
+  type: book
+---
+
+
+```
diff --git a/test/command/biblatex-crossref-inbook-mvbook.md b/test/command/biblatex-crossref-inbook-mvbook.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-crossref-inbook-mvbook.md
@@ -0,0 +1,58 @@
+```
+% pandoc -f biblatex -t markdown -s
+@comment{
+
+crossref, directly from inbook to mvbook
+
+}
+
+@inbook{inbook-1,
+    Crossref = {mvbook-1},
+    Title = {Macbeth [title field of inbook-1]},
+    Date = {1975},
+    Volume = {3},
+    Chapter = {7},
+    Pages = {100-200},
+}
+
+@mvbook{mvbook-1,
+    Author = {Shakespeare},
+    Date = {1970/1980},
+    Title = {Collected Works [title field of mvbook-1]},
+    Location = {Location},
+    Publisher = {Publisher},
+    Volumes = {4},
+}
+
+^D
+---
+nocite: "[@*]"
+references:
+- author:
+  - family: Shakespeare
+  chapter-number: 7
+  container-author:
+  - family: Shakespeare
+  container-title: Collected works \[title field of mvbook-1\]
+  id: inbook-1
+  issued: 1975
+  number-of-volumes: 4
+  page: 100-200
+  publisher: Publisher
+  publisher-place: Location
+  title: Macbeth \[title field of inbook-1\]
+  type: chapter
+  volume: 3
+- author:
+  - family: Shakespeare
+  id: mvbook-1
+  issued: 1970/1980
+  number-of-volumes: 4
+  publisher: Publisher
+  publisher-place: Location
+  title: Collected works \[title field of mvbook-1\]
+  type: book
+---
+
+
+```
diff --git a/test/command/biblatex-crossref-nested.md b/test/command/biblatex-crossref-nested.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-crossref-nested.md
@@ -0,0 +1,100 @@
+```
+% pandoc -f biblatex -t markdown -s
+@comment{
+
+Nested cross-references (see biber manual v 1.7)
+
+}
+
+@bookinbook{bookinbook-1,
+    Crossref = {book-1},
+    Title = {Macbeth [title field of bookinbook-1]},
+    Chapter = {7},
+    Pages = {100-200},
+}
+
+@inbook{inbook-1,
+    Crossref = {book-1},
+    Title = {Macbeth [title field of inbook-1]},
+    Chapter = {7},
+    Pages = {100-200},
+}
+
+@book{book-1,
+    Crossref = {mvbook-1},
+    Date = {1975},
+    Title = {Tragedies [title field of book-1]},
+    Volume = {3}
+}
+
+@mvbook{mvbook-1,
+    Author = {Shakespeare},
+    Date = {1970/1980},
+    Title = {Collected Works [title field of mvbook-1]},
+    Location = {Location},
+    Publisher = {Publisher},
+    Volumes = {4}
+}
+
+^D
+---
+nocite: "[@*]"
+references:
+- author:
+  - family: Shakespeare
+  chapter-number: 7
+  container-author:
+  - family: Shakespeare
+  container-title: Collected works \[title field of mvbook-1\]
+  id: bookinbook-1
+  issued: 1975
+  number-of-volumes: 4
+  page: 100-200
+  publisher: Publisher
+  publisher-place: Location
+  title: Macbeth \[title field of bookinbook-1\]
+  type: book
+  volume: 3
+  volume-title: Tragedies \[title field of book-1\]
+- author:
+  - family: Shakespeare
+  chapter-number: 7
+  container-author:
+  - family: Shakespeare
+  container-title: Collected works \[title field of mvbook-1\]
+  id: inbook-1
+  issued: 1975
+  number-of-volumes: 4
+  page: 100-200
+  publisher: Publisher
+  publisher-place: Location
+  title: Macbeth \[title field of inbook-1\]
+  type: chapter
+  volume: 3
+  volume-title: Tragedies \[title field of book-1\]
+- author:
+  - family: Shakespeare
+  container-author:
+  - family: Shakespeare
+  id: book-1
+  issued: 1975
+  number-of-volumes: 4
+  publisher: Publisher
+  publisher-place: Location
+  title: Collected works \[title field of mvbook-1\]
+  type: book
+  volume: 3
+  volume-title: Tragedies \[title field of book-1\]
+- author:
+  - family: Shakespeare
+  id: mvbook-1
+  issued: 1970/1980
+  number-of-volumes: 4
+  publisher: Publisher
+  publisher-place: Location
+  title: Collected works \[title field of mvbook-1\]
+  type: book
+---
+
+
+```
diff --git a/test/command/biblatex-ctan.md b/test/command/biblatex-ctan.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-ctan.md
@@ -0,0 +1,73 @@
+```
+% pandoc -f biblatex -t markdown -s
+@comment{
+
+Adapted from biblatex-example.bib
+
+
+Formatted with pandoc and chicago-author-date.csl, 2013-10-23:
+
+(“CTAN: The Comprehensive TeX Archive Network” 2006)
+
+“CTAN: The Comprehensive TeX Archive Network.” 2006.
+<http://www.ctan.org>.
+
+
+Formatted with pandoc and apa.csl, 2013-10-23:
+
+(“CTAN: The Comprehensive TeX Archive Network,” 2006)
+
+CTAN: The Comprehensive TeX Archive Network. (2006). Retrieved October
+01, 2006, from <http://www.ctan.org>
+
+
+NOTES:
+
+- biblio2yaml
+	- if there is no shorttitle, but title and subtitle, the title alone should also be mapped to title-short
+
+- citeproc
+	- citeproc should use title-short (if available) instead of title for in-text citations when there is no author
+
+}
+
+@Online{ctan,
+  title        = {{CTAN}},
+  date         = 2006,
+  url          = {http://www.ctan.org},
+  subtitle     = {{The Comprehensive TeX Archive Network}},
+  urldate      = {2006-10-01},
+  label        = {CTAN},
+  hyphenation  = {american},
+  annotation   = {This is an online entry. The \textsc{url}, which is
+                  given in the url field, is transformed into a
+                  clickable link if hyperref support has been
+                  enabled. Note the format of the urldate field
+                  (yyyy-mm-dd) in the database file. Also note the
+                  label field which may be used as a fallback by
+                  citation styles which need an author and\slash or a
+                  year},
+}
+
+^D
+---
+nocite: "[@*]"
+references:
+- accessed: 2006-10-01
+  annote: This is an online entry. The [url]{.smallcaps}, which is given
+    in the url field, is transformed into a clickable link if hyperref
+    support has been enabled. Note the format of the urldate field
+    (yyyy-mm-dd) in the database file. Also note the label field which
+    may be used as a fallback by citation styles which need an author
+    and/or a year
+  id: ctan
+  issued: 2006
+  language: en-US
+  title: "CTAN: The Comprehensive TeX Archive Network"
+  title-short: CTAN
+  type: webpage
+  url: "http://www.ctan.org"
+---
+
+
+```
diff --git a/test/command/biblatex-dates.md b/test/command/biblatex-dates.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-dates.md
@@ -0,0 +1,162 @@
+```
+% pandoc -f biblatex -t markdown -s
+@comment{
+    - Dates
+    - Not included in tests:
+        - malformed dates and date ranges
+        - literal dates ("13th century"; not supported by biblatex)
+        - seasons (would have to come from parsing the issue field)
+        - uncertain dates (use "doubtfuldate" from biblatex-apa?)
+        - dates with single-digit day or month (not supported by biblatex)
+        - negative dates (not supported by biblatex)
+    - Note: biblatex supports years < 1000 but only if padded with leading zeros
+    - TODO:
+        - either biblio2yaml or, probably better, citeproc should strip leading zeros
+         from days and months (CSL can add leading zeros to its output, but not remove
+         them when they are in its input data)
+}
+
+@article{year-month-old,
+    Author = {Author, Al},
+    Journal = {Journal},
+    Month = aug,
+    Title = {Year and Month, bibtex style, supported by biblatex for backwards compatibility},
+    Year = {1999}}
+
+@article{year-month-new,
+    Author = {Author, Al},
+    Journal = {Journal},
+    Month = {08},
+    Title = {Year and Month, biblatex style; note that biblatex does not have a ``day'' field},
+    Year = {1999}}
+
+@article{dates,
+    Author = {Author, Al},
+    Date = {2012-12-13},
+    Eventdate = {2011-10-03},
+    Journal = {Journal},
+    Month = may,
+    Origdate = {1888-10-01},
+    Title = {Dates, default biblatex style; year, month to be ignored if date exists},
+    Urldate = {1999-05-23},
+    Year = {9999}}
+
+@article{date-ranges-different-years,
+    Author = {Author, Al},
+    Date = {1999-10-14/2010-01-23},
+    Eventdate = {1999-12/2000-01},
+    Journal = {Journal},
+    Origdate = {1888-01-02/1913-12-13},
+    Title = {Date ranges; different years},
+    Urldate = {2012-10-12/2013-01-31}}
+
+@article{date-ranges-same-year,
+    Author = {Author, Al},
+    Date = {1999-10-14/1999-10-15},
+    Eventdate = {1999-10/1999-11},
+    Journal = {Journal},
+    Origdate = {1888-01-02/1888-12-13},
+    Title = {Date ranges; same year},
+    Urldate = {2012-10-31/2012-11-01}}
+
+@article{date-ranges-open,
+    Author = {Author, Al},
+    Date = {1999-10-14/},
+    Eventdate = {1999-10/},
+    Journal = {Journal},
+    Origdate = {1888-01-02/},
+    Title = {Date ranges, open-ended},
+    Urldate = {2012-10-31/}}
+
+@article{dates-very-old,
+    Author = {Author, Al},
+    Date = {0712-12-13},
+    Eventdate = {0311-10-03},
+    Journal = {Journal},
+    Month = may,
+    Origdate = {0088-10-01},
+    Title = {Dates, year less than 1000},
+    Urldate = {0999-12-14}}
+
+^D
+---
+nocite: "[@*]"
+references:
+- author:
+  - family: Author
+    given: Al
+  container-title: Journal
+  id: year-month-old
+  issued: 1999-08
+  title: Year and month, bibtex style, supported by biblatex for
+    backwards compatibility
+  type: article-journal
+- author:
+  - family: Author
+    given: Al
+  container-title: Journal
+  id: year-month-new
+  issued: 1999-08
+  title: Year and month, biblatex style; note that biblatex does not
+    have a "day" field
+  type: article-journal
+- accessed: 1999-05-23
+  author:
+  - family: Author
+    given: Al
+  container-title: Journal
+  event-date: 2011-10-03
+  id: dates
+  issued: 2012-12-13
+  original-date: 1888-10-01
+  title: Dates, default biblatex style; year, month to be ignored if
+    date exists
+  type: article-journal
+- accessed: 2012-10-12/2013-01-31
+  author:
+  - family: Author
+    given: Al
+  container-title: Journal
+  event-date: 1999-12/2000-01
+  id: date-ranges-different-years
+  issued: 1999-10-14/2010-01-23
+  original-date: 1888-01-02/1913-12-13
+  title: Date ranges; different years
+  type: article-journal
+- accessed: 2012-10-31/2012-11-01
+  author:
+  - family: Author
+    given: Al
+  container-title: Journal
+  event-date: 1999-10/1999-11
+  id: date-ranges-same-year
+  issued: 1999-10-14/1999-10-15
+  original-date: 1888-01-02/1888-12-13
+  title: Date ranges; same year
+  type: article-journal
+- accessed: 2012-10-31/
+  author:
+  - family: Author
+    given: Al
+  container-title: Journal
+  event-date: 1999-10/
+  id: date-ranges-open
+  issued: 1999-10-14/
+  original-date: 1888-01-02/
+  title: Date ranges, open-ended
+  type: article-journal
+- accessed: 0999-12-14
+  author:
+  - family: Author
+    given: Al
+  container-title: Journal
+  event-date: 0311-10-03
+  id: dates-very-old
+  issued: 0712-12-13
+  original-date: 0088-10-01
+  title: Dates, year less than 1000
+  type: article-journal
+---
+
+
+```
diff --git a/test/command/biblatex-doody.md b/test/command/biblatex-doody.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-doody.md
@@ -0,0 +1,101 @@
+```
+% pandoc -f biblatex -t markdown -s
+@comment{
+
+Adapted from biblatex-example.bib
+
+Formatted with pandoc and chicago-author-date.csl, 2013-10-23:
+
+(Doody 1974) (Matuz 1990)
+
+Doody, Terrence. 1974. “Hemingway’s Style and Jake’s Narration.” *The
+Journal of Narrative Technique* 4 (3): 212–225.
+
+Matuz, Roger, ed. 1990. *Contemporary Literary Criticism*. Vol. 61.
+Detroit: Gale.
+
+
+Formatted with pandoc and apa.csl, 2013-10-23:
+
+(Doody, 1974) (Matuz, 1990)
+
+Doody, T. (1974). Hemingway’s style and Jake’s narration. *The Journal
+of Narrative Technique*, *4*(3), 212–225.
+
+Matuz, R. (Ed.). (1990). *Contemporary literary criticism* (Vol. 61, pp.
+204–208). Detroit: Gale.
+
+
+NOTES
+
+- biblio2yaml
+	- contains fields “related” and “relatedstring”. In principle, these could be appended to CSL "note", if citeproc can handle citations in the bibliography ...
+
+}
+
+@Article{doody,
+  author       = {Doody, Terrence},
+  title        = {Hemingway's Style and {Jake}'s Narration},
+  year         = 1974,
+  volume       = 4,
+  number       = 3,
+  pages        = {212-225},
+  hyphenation  = {american},
+  related      = {matuz:doody},
+  relatedstring= {\autocap{e}xcerpt in},
+  journal      = {The Journal of Narrative Technique},
+  annotation   = {An article entry cited as an excerpt from a
+                  collection entry. Note the format of the
+                  related and relatedstring fields},
+}
+
+@Collection{matuz:doody,
+  editor       = {Matuz, Roger},
+  title        = {Contemporary Literary Criticism},
+  year         = 1990,
+  volume       = 61,
+  publisher    = {Gale},
+  location     = {Detroit},
+  pages        = {204-208},
+  hyphenation  = {american},
+  annotation   = {A collection entry providing the excerpt information
+                  for the doody entry. Note the format of the
+                  pages field},
+}
+
+^D
+---
+nocite: "[@*]"
+references:
+- annote: An article entry cited as an excerpt from a collection entry.
+    Note the format of the related and relatedstring fields
+  author:
+  - family: Doody
+    given: Terrence
+  container-title: The Journal of Narrative Technique
+  id: doody
+  issue: 3
+  issued: 1974
+  language: en-US
+  page: 212-225
+  title: Hemingway's style and Jake's narration
+  type: article-journal
+  volume: 4
+- annote: A collection entry providing the excerpt information for the
+    doody entry. Note the format of the pages field
+  editor:
+  - family: Matuz
+    given: Roger
+  id: "matuz:doody"
+  issued: 1990
+  language: en-US
+  page: 204-208
+  publisher: Gale
+  publisher-place: Detroit
+  title: Contemporary literary criticism
+  type: book
+  volume: 61
+---
+
+
+```
diff --git a/test/command/biblatex-edtf-date.md b/test/command/biblatex-edtf-date.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-edtf-date.md
@@ -0,0 +1,72 @@
+```
+% pandoc -f biblatex -t markdown -s
+Note that current CSL doesn't give us a way
+to distinguish between /open and /unknown,
+so item3-3 and item3-4 get parsed similarly.
+That should change in CSL 1.1, and then this
+test should be revised.
+
+@article{item3-3, date={1998/unknown}}
+@article{item3-4, date={1999/open}}
+@article{item3-10, date={2004-04-05T14:34:00}}
+@article{item5-1, date={0000}}
+@article{item5-2, date={-0876}}
+@article{item5-3, date={-0877/-0866}}
+@article{item5-5, date={-0343-02}}
+@article{item5-8, date={1723~}}
+@article{item5-9, date={1723?}}
+@article{item5-10, date={1723?~}}
+@article{item5-11, date={2004-22}}
+@article{item5-12, date={2004-24}}
+@article{item5-13, date={20uu}}
+@article{item5-14, date={y-123456789}}
+
+^D
+---
+nocite: "[@*]"
+references:
+- id: item3-3
+  issued: 1998/
+  type: article-journal
+- id: item3-4
+  issued: 1999/
+  type: article-journal
+- id: item3-10
+  issued: 2004-04-05
+  type: article-journal
+- id: item5-1
+  type: article-journal
+- id: item5-2
+  issued: "-0876"
+  type: article-journal
+- id: item5-3
+  issued: "-0877/-0866"
+  type: article-journal
+- id: item5-5
+  issued: "-0343-02"
+  type: article-journal
+- id: item5-8
+  issued: 1723\~
+  type: article-journal
+- id: item5-9
+  issued: 1723
+  type: article-journal
+- id: item5-10
+  issued: 1723\~
+  type: article-journal
+- id: item5-11
+  issued: 2004-22
+  type: article-journal
+- id: item5-12
+  issued: 2004-24
+  type: article-journal
+- id: item5-13
+  issued: 2000/2099
+  type: article-journal
+- id: item5-14
+  issued: y-123456789
+  type: article-journal
+---
+
+
+```
diff --git a/test/command/biblatex-escapedquotes.md b/test/command/biblatex-escapedquotes.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-escapedquotes.md
@@ -0,0 +1,51 @@
+```
+% pandoc -f biblatex -t markdown -s
+@comment{From jgm/pandoc#1568.  Double quotes escaped using {"}.}
+
+@ARTICLE{Koff2009-gn,
+  title       = "Pan-Canadian evaluation of irreversible compression ratios
+                 ({"}lossy{"} compression) for development of national
+                 guidelines",
+  author      = "Koff, David and Bak, Peter and Brownrigg, Paul and
+                 Hosseinzadeh, Danoush and Khademi, April and Kiss, Alex and
+                 Lepanto, Luigi and Michalak, Tracy and Shulman, Harry and
+                 Volkening, Andrew",
+  affiliation = "Sunnybrook Health Sciences Centre, 2075 Bayview Ave., Toronto,
+                 ON, M4N 3M5, Canada. dkoffmcmaster.ca",
+  journal     = "Journal of digital imaging",
+}
+
+^D
+---
+nocite: "[@*]"
+references:
+- author:
+  - family: Koff
+    given: David
+  - family: Bak
+    given: Peter
+  - family: Brownrigg
+    given: Paul
+  - family: Hosseinzadeh
+    given: Danoush
+  - family: Khademi
+    given: April
+  - family: Kiss
+    given: Alex
+  - family: Lepanto
+    given: Luigi
+  - family: Michalak
+    given: Tracy
+  - family: Shulman
+    given: Harry
+  - family: Volkening
+    given: Andrew
+  container-title: Journal of digital imaging
+  id: Koff2009-gn
+  title: Pan-canadian evaluation of irreversible compression ratios
+    (\"lossy\" compression) for development of national guidelines
+  type: article-journal
+---
+
+
+```
diff --git a/test/command/biblatex-formatting.md b/test/command/biblatex-formatting.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-formatting.md
@@ -0,0 +1,23 @@
+```
+% pandoc -f biblatex -t markdown -s
+@article{item1,
+    Title = {The Title:
+     \textit{italics},
+     \textbf{bold},
+     \textsubscript{subscript},
+     \textsuperscript{superscript},
+     \textsc{small-caps}}
+}
+^D
+---
+nocite: "[@*]"
+references:
+- id: item1
+  title: "The title: *Italics*, **bold**, ~subscript~, ^superscript^,
+    [small-caps]{.smallcaps}"
+  title-short: The title
+  type: article-journal
+---
+
+
+```
diff --git a/test/command/biblatex-gaonkar-in.md b/test/command/biblatex-gaonkar-in.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-gaonkar-in.md
@@ -0,0 +1,62 @@
+```
+% pandoc -f biblatex -t markdown -s
+@comment{
+
+Adapted from biblatex-example.bib
+
+
+Formatted with pandoc and chicago-author-date.csl, 2013-10-23:
+
+(Gaonkar 2001)
+
+Gaonkar, Dilip Parameshwar. 2001. “On Alternative Modernities.” In
+*Alternative Modernities*, edited by Dilip Parameshwar Gaonkar, 1–23.
+Durham; London: Duke University Press.
+
+
+Formatted with pandoc and apa.csl, 2013-10-23:
+
+(Gaonkar, 2001)
+
+Gaonkar, D. P. (2001). On alternative modernities. In D. P. Gaonkar
+(Ed.), *Alternative modernities* (pp. 1–23). Durham; London: Duke
+University Press.
+
+
+}
+
+@InCollection{gaonkar:in,
+  author       = {Gaonkar, Dilip Parameshwar},
+  editor       = {Gaonkar, Dilip Parameshwar},
+  title        = {On Alternative Modernities},
+  date         = 2001,
+  booktitle    = {Alternative Modernities},
+  publisher    = {Duke University Press},
+  location     = {Durham and London},
+  isbn         = {0-822-32714-7},
+  pages        = {1-23},
+}
+
+^D
+---
+nocite: "[@*]"
+references:
+- author:
+  - family: Gaonkar
+    given: Dilip Parameshwar
+  container-title: Alternative modernities
+  editor:
+  - family: Gaonkar
+    given: Dilip Parameshwar
+  id: "gaonkar:in"
+  isbn: 0-822-32714-7
+  issued: 2001
+  page: 1-23
+  publisher: Duke University Press
+  publisher-place: Durham; London
+  title: On alternative modernities
+  type: chapter
+---
+
+
+```
diff --git a/test/command/biblatex-gaonkar.md b/test/command/biblatex-gaonkar.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-gaonkar.md
@@ -0,0 +1,59 @@
+```
+% pandoc -f biblatex -t markdown -s
+@comment{
+
+Adapted from biblatex-example.bib
+
+
+Formatted with pandoc and chicago-author-date.csl, 2013-10-23:
+
+(Gaonkar 2001)
+
+Gaonkar, Dilip Parameshwar, ed. 2001. *Alternative Modernities*. Durham;
+London: Duke University Press.
+
+
+Formatted with pandoc and apa.csl, 2013-10-23:
+
+(Gaonkar, 2001)
+
+Gaonkar, D. P. (Ed.). (2001). *Alternative modernities*. Durham; London:
+Duke University Press.
+
+
+}
+
+@Collection{gaonkar,
+  editor       = {Gaonkar, Dilip Parameshwar},
+  title        = {Alternative Modernities},
+  date         = 2001,
+  publisher    = {Duke University Press},
+  location     = {Durham and London},
+  isbn         = {0-822-32714-7},
+  hyphenation  = {american},
+  annotation   = {This is a collection entry. Note the format of the
+                  location field in the database file as well as the
+                  isbn field},
+}
+
+^D
+---
+nocite: "[@*]"
+references:
+- annote: This is a collection entry. Note the format of the location
+    field in the database file as well as the isbn field
+  editor:
+  - family: Gaonkar
+    given: Dilip Parameshwar
+  id: gaonkar
+  isbn: 0-822-32714-7
+  issued: 2001
+  language: en-US
+  publisher: Duke University Press
+  publisher-place: Durham; London
+  title: Alternative modernities
+  type: book
+---
+
+
+```
diff --git a/test/command/biblatex-geer.md b/test/command/biblatex-geer.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-geer.md
@@ -0,0 +1,70 @@
+```
+% pandoc -f biblatex -t markdown -s
+@comment{
+
+Adapted from biblatex-example.bib
+
+Formatted with pandoc and chicago-author-date.csl, 2013-10-23:
+
+(Geer 1985)
+
+Geer, Ingrid de. 1985. “Earl, Saint, Bishop, Skald – and Music: The
+Orkney Earldom of the Twelfth Century. A Musicological Study.” PhD
+thesis, Uppsala: Uppsala Universitet.
+
+
+Formatted with pandoc and apa.csl, 2013-10-23:
+
+(Geer, 1985)
+
+Geer, I. de. (1985). *Earl, saint, bishop, skald – and music: The Orkney
+earldom of the twelfth century. A musicological study* (PhD thesis).
+Uppsala Universitet, Uppsala.
+
+
+}
+
+@Thesis{geer,
+  author       = {de Geer, Ingrid},
+  title        = {Earl, Saint, Bishop, Skald~-- and Music},
+  type         = {phdthesis},
+  institution  = {Uppsala Universitet},
+  date         = 1985,
+  subtitle     = {The {Orkney} Earldom of the Twelfth Century. {A} Musicological
+                  Study},
+  location     = {Uppsala},
+  options      = {useprefix=false},
+  hyphenation  = {british},
+  annotation   = {This is a typical thesis entry for a PhD thesis. Note
+                  the type field in the database file which uses a
+                  localization key. Also note the format of the printed name and
+                  compare the useprefix option in the options
+                  field as well as vangennep},
+}
+
+^D
+---
+nocite: "[@*]"
+references:
+- annote: This is a typical thesis entry for a PhD thesis. Note the type
+    field in the database file which uses a localization key. Also note
+    the format of the printed name and compare the useprefix option in
+    the options field as well as vangennep
+  author:
+  - dropping-particle: de
+    family: Geer
+    given: Ingrid
+  genre: PhD thesis
+  id: geer
+  issued: 1985
+  language: en-GB
+  publisher: Uppsala Universitet
+  publisher-place: Uppsala
+  title: "Earl, saint, bishop, skald -- and music: The Orkney earldom of
+    the twelfth century. A musicological study"
+  title-short: Earl, saint, bishop, skald -- and music
+  type: thesis
+---
+
+
+```
diff --git a/test/command/biblatex-gerhardt.md b/test/command/biblatex-gerhardt.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-gerhardt.md
@@ -0,0 +1,64 @@
+```
+% pandoc -f biblatex -t markdown -s
+@comment{
+
+Adapted from biblatex-example.bib
+
+Formatted with pandoc and chicago-author-date.csl, 2013-10-23:
+
+(Gerhardt 2000)
+
+Gerhardt, Michael J. 2000. *The Federal Appointments Process: A
+Constitutional and Historical Analysis*. Durham; London: Duke University
+Press.
+
+
+Formatted with pandoc and apa.csl, 2013-10-23:
+
+(Gerhardt, 2000)
+
+Gerhardt, M. J. (2000). *The federal appointments process: A
+constitutional and historical analysis*. Durham; London: Duke University
+Press.
+
+
+}
+
+@Book{gerhardt,
+  author       = {Gerhardt, Michael J.},
+  title        = {The Federal Appointments Process},
+  date         = 2000,
+  publisher    = {Duke University Press},
+  location     = {Durham and London},
+  hyphenation  = {american},
+  sorttitle    = {Federal Appointments Process},
+  indextitle   = {Federal Appointments Process, The},
+  subtitle     = {A Constitutional and Historical Analysis},
+  shorttitle   = {Federal Appointments Process},
+  annotation   = {This is a book entry. Note the format of the
+                  location field as well as the sorttitle and
+                  indextitle fields},
+}
+
+^D
+---
+nocite: "[@*]"
+references:
+- annote: This is a book entry. Note the format of the location field as
+    well as the sorttitle and indextitle fields
+  author:
+  - family: Gerhardt
+    given: Michael J.
+  id: gerhardt
+  issued: 2000
+  language: en-US
+  publisher: Duke University Press
+  publisher-place: Durham; London
+  title: "The federal appointments process: A constitutional and
+    historical analysis"
+  title-short: Federal appointments process
+  type: book
+---
+
+
+```
diff --git a/test/command/biblatex-gillies.md b/test/command/biblatex-gillies.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-gillies.md
@@ -0,0 +1,69 @@
+```
+% pandoc -f biblatex -t markdown -s
+@comment{
+
+Adapted from biblatex-example.bib
+
+
+Formatted with pandoc and chicago-author-date.csl, 2013-10-23:
+
+(Gillies 1933)
+
+Gillies, Alexander. 1933. “Herder and the Preparation of Goethe’s Idea
+of World Literature.” *Publications of the English Goethe Society, New
+Series* 9: 46–67.
+
+
+Formatted with pandoc and apa.csl, 2013-10-23:
+
+(Gillies, 1933)
+
+Gillies, A. (1933). Herder and the preparation of Goethe’s idea of world
+literature. *Publications of the English Goethe Society, new series*,
+*9*, 46–67.
+
+
+NOTES:
+
+- biblio2yaml
+	- "new series" is not pretty, but it’s the best we can do at the moment, given the limitations of CSL.
+
+}
+
+@Article{gillies,
+  author       = {Gillies, Alexander},
+  title        = {Herder and the Preparation of {Goethe}'s Idea of World
+                  Literature},
+  journaltitle = {Publications of the English Goethe Society},
+  date         = 1933,
+  series       = {newseries},
+  volume       = 9,
+  pages        = {46-67},
+  hyphenation  = {british},
+  annotation   = {An article entry with a series and a
+                  volume field. Note that format of the series
+                  field in the database file},
+}
+
+^D
+---
+nocite: "[@*]"
+references:
+- annote: An article entry with a series and a volume field. Note that
+    format of the series field in the database file
+  author:
+  - family: Gillies
+    given: Alexander
+  collection-title: New series
+  container-title: Publications of the English Goethe Society
+  id: gillies
+  issued: 1933
+  language: en-GB
+  page: 46-67
+  title: Herder and the preparation of Goethe's idea of world literature
+  type: article-journal
+  volume: 9
+---
+
+
+```
diff --git a/test/command/biblatex-glashow.md b/test/command/biblatex-glashow.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-glashow.md
@@ -0,0 +1,51 @@
+```
+% pandoc -f biblatex -t markdown -s
+@comment{
+
+Adapted from biblatex-example.bib
+
+Formatted with pandoc and chicago-author-date.csl, 2013-10-23:
+
+(Glashow 1961)
+
+Glashow, Sheldon. 1961. “Partial Symmetries of Weak Interactions.”
+*Nucl. Phys.* 22: 579–588.
+
+
+Formatted with pandoc and apa.csl, 2013-10-23:
+
+(Glashow, 1961)
+
+Glashow, S. (1961). Partial symmetries of weak interactions.
+*Nucl. Phys.*, *22*, 579–588.
+
+
+}
+
+@Article{glashow,
+  author       = {Glashow, Sheldon},
+  title        = {Partial Symmetries of Weak Interactions},
+  journaltitle = {Nucl.~Phys.},
+  date         = 1961,
+  volume       = 22,
+  pages        = {579-588},
+}
+
+^D
+---
+nocite: "[@*]"
+references:
+- author:
+  - family: Glashow
+    given: Sheldon
+  container-title: Nucl. Phys.
+  id: glashow
+  issued: 1961
+  page: 579-588
+  title: Partial symmetries of weak interactions
+  type: article-journal
+  volume: 22
+---
+
+
+```
diff --git a/test/command/biblatex-gonzalez.md b/test/command/biblatex-gonzalez.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-gonzalez.md
@@ -0,0 +1,62 @@
+```
+% pandoc -f biblatex -t markdown -s
+@comment{
+
+Adapted from biblatex-example.bib
+
+Formatted with pandoc and chicago-author-date.csl, 2013-10-23:
+
+(Gonzalez 2001)
+
+Gonzalez, Ray. 2001. *The Ghost of John Wayne and Other Stories*.
+Tucson: The University of Arizona Press.
+
+
+Formatted with pandoc and apa.csl, 2013-10-23:
+
+(Gonzalez, 2001)
+
+Gonzalez, R. (2001). *The ghost of John Wayne and other stories*.
+Tucson: The University of Arizona Press.
+
+}
+
+@Book{gonzalez,
+  author       = {Gonzalez, Ray},
+  title        = {The Ghost of {John Wayne} and Other Stories},
+  date         = 2001,
+  publisher    = {The University of Arizona Press},
+  location     = {Tucson},
+  isbn         = {0-816-52066-6},
+  hyphenation  = {american},
+  sorttitle    = {Ghost of John Wayne and Other Stories},
+  indextitle   = {Ghost of {John Wayne} and Other Stories, The},
+  shorttitle   = {Ghost of {John Wayne}},
+  annotation   = {A collection of short stories. This is a book entry.
+                  Note the sorttitle and indextitle fields in
+                  the database file. There's also an isbn field},
+}
+
+^D
+---
+nocite: "[@*]"
+references:
+- annote: A collection of short stories. This is a book entry. Note the
+    sorttitle and indextitle fields in the database file. There's also
+    an isbn field
+  author:
+  - family: Gonzalez
+    given: Ray
+  id: gonzalez
+  isbn: 0-816-52066-6
+  issued: 2001
+  language: en-US
+  publisher: The University of Arizona Press
+  publisher-place: Tucson
+  title: The ghost of John Wayne and other stories
+  title-short: Ghost of John Wayne
+  type: book
+---
+
+
+```
diff --git a/test/command/biblatex-hammond.md b/test/command/biblatex-hammond.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-hammond.md
@@ -0,0 +1,63 @@
+```
+% pandoc -f biblatex -t markdown -s
+@comment{
+
+Adapted from biblatex-example.bib
+
+Formatted with pandoc and chicago-author-date.csl, 2013-10-23:
+
+(Hammond 1997)
+
+Hammond, Christopher. 1997. *The Basics of Crystallography and
+Diffraction*. Oxford: International Union of Crystallography; Oxford
+University Press.
+
+
+Formatted with pandoc and apa.csl, 2013-10-23:
+
+(Hammond, 1997)
+
+Hammond, C. (1997). *The basics of crystallography and diffraction*.
+Oxford: International Union of Crystallography; Oxford University Press.
+
+
+}
+
+@Book{hammond,
+  author       = {Hammond, Christopher},
+  title        = {The basics of crystallography and diffraction},
+  date         = 1997,
+  publisher    = {International Union of Crystallography and Oxford University
+                  Press},
+  location     = {Oxford},
+  hyphenation  = {british},
+  sorttitle    = {Basics of crystallography and diffraction},
+  indextitle   = {Basics of crystallography and diffraction, The},
+  shorttitle   = {Crystallography and diffraction},
+  annotation   = {A book entry. Note the sorttitle and
+                  indextitle fields as well as the format of the
+                  publisher field},
+}
+
+^D
+---
+nocite: "[@*]"
+references:
+- annote: A book entry. Note the sorttitle and indextitle fields as well
+    as the format of the publisher field
+  author:
+  - family: Hammond
+    given: Christopher
+  id: hammond
+  issued: 1997
+  language: en-GB
+  publisher: International Union of Crystallography; Oxford University
+    Press
+  publisher-place: Oxford
+  title: The basics of crystallography and diffraction
+  title-short: Crystallography and diffraction
+  type: book
+---
+
+
+```
diff --git a/test/command/biblatex-herrmann.md b/test/command/biblatex-herrmann.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-herrmann.md
@@ -0,0 +1,70 @@
+```
+% pandoc -f biblatex -t markdown -s
+@comment{
+
+Adapted from biblatex-example.bib
+
+Formatted with pandoc and chicago-author-date.csl, 2013-10-23:
+
+(Herrmann et al. 2006)
+
+Herrmann, Wolfgang A., Karl Öfele, Sabine K. Schneider, Eberhardt
+Herdtweck, and Stephan D. Hoffmann. 2006. “A Carbocyclic Carbene as an
+Efficient Catalyst Ligand for C–C Coupling Reactions.” *Angew. Chem.
+Int. Ed.* 45 (23): 3859–3862.
+
+
+Formatted with pandoc and apa.csl, 2013-10-23:
+
+(Herrmann, Öfele, Schneider, Herdtweck, & Hoffmann, 2006)
+
+Herrmann, W. A., Öfele, K., Schneider, S. K., Herdtweck, E., & Hoffmann,
+S. D. (2006). A carbocyclic carbene as an efficient catalyst ligand for
+C–C coupling reactions. *Angew. Chem. Int. Ed.*, *45*(23), 3859–3862.
+
+
+}
+
+@string{ anch-ie = {Angew.~Chem. Int.~Ed.} }
+
+@Article{herrmann,
+  author       = {Herrmann, Wolfgang A. and {\"O}fele, Karl and Schneider,
+                  Sabine K.  and Herdtweck, Eberhardt and Hoffmann, Stephan D.},
+  title        = {A carbocyclic carbene as an efficient catalyst ligand for {C--C}
+                  coupling reactions},
+  journaltitle = anch-ie,
+  date         = 2006,
+  volume       = 45,
+  number       = 23,
+  pages        = {3859-3862},
+  indextitle   = {Carbocyclic carbene as an efficient catalyst, A},
+}
+
+^D
+---
+nocite: "[@*]"
+references:
+- author:
+  - family: Herrmann
+    given: Wolfgang A.
+  - family: Öfele
+    given: Karl
+  - family: Schneider
+    given: Sabine K.
+  - family: Herdtweck
+    given: Eberhardt
+  - family: Hoffmann
+    given: Stephan D.
+  container-title: Angew. Chem. Int. Ed.
+  id: herrmann
+  issue: 23
+  issued: 2006
+  page: 3859-3862
+  title: A carbocyclic carbene as an efficient catalyst ligand for C--C
+    coupling reactions
+  type: article-journal
+  volume: 45
+---
+
+
+```
diff --git a/test/command/biblatex-hyman.md b/test/command/biblatex-hyman.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-hyman.md
@@ -0,0 +1,79 @@
+```
+% pandoc -f biblatex -t markdown -s
+@comment{
+
+Adapted from biblatex-example.bib
+
+
+Formatted with pandoc and chicago-author-date.csl, 2013-10-23:
+
+(Hyman 1981)
+
+Hyman, Arthur. 1981. “Aristotle’s Theory of the Intellect and Its
+Interpretation by Averroes.” In *Studies in Aristotle*, edited by
+Dominic J. O’Meara, 161–191. Studies in Philosophy and the History of
+Philosophy 9. Washington, D.C.: The Catholic University of America
+Press.
+
+
+Formatted with pandoc and apa.csl, 2013-10-23:
+
+(Hyman, 1981)
+
+Hyman, A. (1981). Aristotle’s theory of the intellect and its
+interpretation by Averroes. In D. J. O’Meara (Ed.), *Studies in
+Aristotle* (pp. 161–191). Washington, D.C.: The Catholic University of
+America Press.
+
+
+}
+
+@InCollection{hyman,
+  author       = {Arthur Hyman},
+  editor       = {O'Meara, Dominic J.},
+  title        = {Aristotle's Theory of the Intellect and its Interpretation by
+                  {Averroes}},
+  date         = 1981,
+  booktitle    = {Studies in {Aristotle}},
+  series       = {Studies in Philosophy and the History of Philosophy},
+  number       = 9,
+  publisher    = {The Catholic University of America Press},
+  location     = {Washington, D.C.},
+  pages        = {161-191},
+  keywords     = {secondary},
+  hyphenation  = {american},
+  indextitle   = {Aristotle's Theory of the Intellect},
+  shorttitle   = {Aristotle's Theory of the Intellect},
+  annotation   = {An incollection entry with a series and
+                  number field},
+}
+
+^D
+---
+nocite: "[@*]"
+references:
+- annote: An incollection entry with a series and number field
+  author:
+  - family: Hyman
+    given: Arthur
+  collection-number: 9
+  collection-title: Studies in philosophy and the history of philosophy
+  container-title: Studies in Aristotle
+  editor:
+  - family: O'Meara
+    given: Dominic J.
+  id: hyman
+  issued: 1981
+  keyword: secondary
+  language: en-US
+  page: 161-191
+  publisher: The Catholic University of America Press
+  publisher-place: Washington, D.C.
+  title: Aristotle's theory of the intellect and its interpretation by
+    Averroes
+  title-short: Aristotle's theory of the intellect
+  type: chapter
+---
+
+
+```
diff --git a/test/command/biblatex-iliad.md b/test/command/biblatex-iliad.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-iliad.md
@@ -0,0 +1,68 @@
+```
+% pandoc -f biblatex -t markdown -s
+@comment{
+
+Adapted from biblatex-example.bib
+
+Formatted with pandoc and chicago-author-date.csl, 2013-10-23:
+
+(Homer 2004)
+
+Homer. 2004. *Die Ilias*. Translated by Wolfgang Schadewaldt. 3rd ed.
+Düsseldorf; Zürich: Artemis & Winkler.
+
+
+Formatted with pandoc and apa.csl, 2013-10-23:
+
+(Homer, 2004)
+
+Homer. (2004). *Die Ilias*. (W. Schadewaldt, trans.) (3rd ed.).
+Düsseldorf; Zürich: Artemis & Winkler.
+
+}
+
+@Book{iliad,
+  author       = {Homer},
+  title        = {Die Ilias},
+  date         = 2004,
+  translator   = {Schadewaldt, Wolfgang},
+  introduction = {Latacz, Joachim},
+  edition      = 3,
+  publisher    = {Artemis \& Winkler},
+  location     = {D{\"u}sseldorf and Z{\"u}rich},
+  hyphenation  = {german},
+  sorttitle    = {Ilias},
+  indextitle   = {Ilias, Die},
+  shorttitle   = {Ilias},
+  annotation   = {A German translation of the \emph{Iliad}. Note the
+                  translator and introduction fields and the
+                  format of the location field in the database
+                  file. Also note the sorttitle and indextitle
+                  fields},
+}
+
+^D
+---
+nocite: "[@*]"
+references:
+- annote: A German translation of the *Iliad*. Note the translator and
+    introduction fields and the format of the location field in the
+    database file. Also note the sorttitle and indextitle fields
+  author:
+  - family: Homer
+  edition: 3
+  id: iliad
+  issued: 2004
+  language: de-DE
+  publisher: Artemis & Winkler
+  publisher-place: Düsseldorf; Zürich
+  title: Die Ilias
+  title-short: Ilias
+  translator:
+  - family: Schadewaldt
+    given: Wolfgang
+  type: book
+---
+
+
+```
diff --git a/test/command/biblatex-inbook-title-booktitle-maintitle-series-2.md b/test/command/biblatex-inbook-title-booktitle-maintitle-series-2.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-inbook-title-booktitle-maintitle-series-2.md
@@ -0,0 +1,48 @@
+```
+% pandoc -f biblatex -t markdown -s
+@inbook{item1,
+	Author = {Author, Al},
+	Bookauthor = {Bookauthor, Bob},
+	Booksubtitle = {Booksubtitle},
+	Booktitle = {Booktitle},
+	Booktitleaddon = {Booktitleaddon},
+	Date = {2011},
+	Hyphenation = {french},
+	Location = {Location},
+	Mainsubtitle = {Mainsubtitle},
+	Maintitle = {Maintitle},
+	Maintitleaddon = {Maintitleaddon},
+	Number = {3},
+	Publisher = {Publisher},
+	Series = {Series},
+	Subtitle = {Subtitle},
+	Title = {Title of the ``inbook'' Entry},
+	Titleaddon = {Titleaddon},
+	Volume = {4}}
+
+^D
+---
+nocite: "[@*]"
+references:
+- author:
+  - family: Author
+    given: Al
+  collection-number: 3
+  collection-title: Series
+  container-author:
+  - family: Bookauthor
+    given: Bob
+  container-title: "Maintitle: Mainsubtitle. Maintitleaddon"
+  id: item1
+  issued: 2011
+  language: fr-FR
+  publisher: Publisher
+  publisher-place: Location
+  title: "Title of the \"inbook\" Entry: Subtitle. Titleaddon"
+  type: chapter
+  volume: 4
+  volume-title: "Booktitle: Booksubtitle. Booktitleaddon"
+---
+
+
+```
diff --git a/test/command/biblatex-inbook-title-booktitle-maintitle-series.md b/test/command/biblatex-inbook-title-booktitle-maintitle-series.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-inbook-title-booktitle-maintitle-series.md
@@ -0,0 +1,44 @@
+```
+% pandoc -f biblatex -t markdown -s
+@inbook{item1,
+	Author = {Author, Al},
+	Booksubtitle = {Booksubtitle},
+	Booktitle = {Booktitle},
+	Booktitleaddon = {Booktitleaddon},
+	Date = {2011},
+	Hyphenation = {french},
+	Location = {Location},
+	Mainsubtitle = {Mainsubtitle},
+	Maintitle = {Maintitle},
+	Maintitleaddon = {Maintitleaddon},
+	Number = {3},
+	Publisher = {Publisher},
+	Series = {Series},
+	Subtitle = {Subtitle},
+	Title = {Title of the ``inbook'' Entry},
+	Titleaddon = {Titleaddon},
+	Volume = {4}}
+
+^D
+---
+nocite: "[@*]"
+references:
+- author:
+  - family: Author
+    given: Al
+  collection-number: 3
+  collection-title: Series
+  container-title: "Maintitle: Mainsubtitle. Maintitleaddon"
+  id: item1
+  issued: 2011
+  language: fr-FR
+  publisher: Publisher
+  publisher-place: Location
+  title: "Title of the \"inbook\" Entry: Subtitle. Titleaddon"
+  type: chapter
+  volume: 4
+  volume-title: "Booktitle: Booksubtitle. Booktitleaddon"
+---
+
+
+```
diff --git a/test/command/biblatex-inbook.md b/test/command/biblatex-inbook.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-inbook.md
@@ -0,0 +1,147 @@
+```
+% pandoc -f biblatex -t markdown -s
+@comment{
+adapted from http://mirrors.ctan.org/macros/latex/contrib/biblatex/doc/examples/biblatex-examples.bib
+
+TODO / citeproc: in biblatex "inbook" entries, citeproc should suppress bookauthor = CSL container-author if identical with author. -- See annotation in kant:kpv.
+}
+
+@string{dtv = {Deutscher Taschenbuch-Verlag}}
+
+@inbook{kant:kpv,
+	Annotation = {An edition of Kant's \emph{Collected Works}, volume five. This is an inbook entry which explicitly refers to the \emph{Critique of Practical Reason} only, not to the entire fifth volume. Note the author and bookauthor fields in the database file. By default, the bookauthor is omitted if the values of the author and bookauthor fields are identical},
+	Author = {Kant, Immanuel},
+	Bookauthor = {Kant, Immanuel},
+	Booktitle = {Kritik der praktischen Vernunft. Kritik der Urtheilskraft},
+	Date = 1968,
+	Hyphenation = {german},
+	Location = {Berlin},
+	Maintitle = {Kants Werke. Akademie Textausgabe},
+	Pages = {1-163},
+	Publisher = {Walter de Gruyter},
+	Shorthand = {KpV},
+	Shorttitle = {Kritik der praktischen Vernunft},
+	Title = {Kritik der praktischen Vernunft},
+	Volume = 5}
+
+@inbook{kant:ku,
+	Annotation = {An edition of Kant's \emph{Collected Works}, volume five. This is an inbook entry which explicitly refers to the \emph{Critique of Judgment} only, not to the entire fifth volume},
+	Author = {Kant, Immanuel},
+	Bookauthor = {Kant, Immanuel},
+	Booktitle = {Kritik der praktischen Vernunft. Kritik der Urtheilskraft},
+	Date = 1968,
+	Hyphenation = {german},
+	Location = {Berlin},
+	Maintitle = {Kants Werke. Akademie Textausgabe},
+	Pages = {165-485},
+	Publisher = {Walter de Gruyter},
+	Shorthand = {KU},
+	Title = {Kritik der Urtheilskraft},
+	Volume = 5}
+
+@inbook{nietzsche:historie,
+	Annotation = {A single essay from the critical edition of Nietzsche's works. This inbook entry explicitly refers to an essay found in the first volume. Note the title, booktitle, and maintitle fields. Also note the sorttitle and sortyear fields. We want this entry to be listed after the entry referring to the entire first volume},
+	Author = {Nietzsche, Friedrich},
+	Bookauthor = {Nietzsche, Friedrich},
+	Booktitle = {Die Geburt der Tragödie. Unzeitgemäße Betrachtungen I--IV. Nachgelassene Schriften 1870--1973},
+	Date = 1988,
+	Editor = {Colli, Giorgio and Montinari, Mazzino},
+	Hyphenation = {german},
+	Indexsorttitle = {Vom Nutzen und Nachtheil der Historie fur das Leben},
+	Indextitle = {Vom Nutzen und Nachtheil der Historie für das Leben},
+	Location = {München and Berlin and New York},
+	Mainsubtitle = {Kritische Studienausgabe},
+	Maintitle = {Sämtliche Werke},
+	Pages = {243-334},
+	Publisher = dtv # { and Walter de Gruyter},
+	Shorttitle = {Vom Nutzen und Nachtheil der Historie},
+	Sorttitle = {Werke-01-243},
+	Sortyear = {1988-2},
+	Subtitle = {Vom Nutzen und Nachtheil der Historie für das Leben},
+	Title = {Unzeitgemässe Betrachtungen. Zweites Stück},
+	Volume = 1}
+
+^D
+---
+nocite: "[@*]"
+references:
+- annote: An edition of Kant's *Collected Works*, volume five. This is
+    an inbook entry which explicitly refers to the *Critique of
+    Practical Reason* only, not to the entire fifth volume. Note the
+    author and bookauthor fields in the database file. By default, the
+    bookauthor is omitted if the values of the author and bookauthor
+    fields are identical
+  author:
+  - family: Kant
+    given: Immanuel
+  container-author:
+  - family: Kant
+    given: Immanuel
+  container-title: Kants Werke. Akademie Textausgabe
+  id: "kant:kpv"
+  issued: 1968
+  language: de-DE
+  page: 1-163
+  publisher: Walter de Gruyter
+  publisher-place: Berlin
+  title: Kritik der praktischen Vernunft
+  title-short: Kritik der praktischen Vernunft
+  type: chapter
+  volume: 5
+  volume-title: Kritik der praktischen Vernunft. Kritik der
+    Urtheilskraft
+- annote: An edition of Kant's *Collected Works*, volume five. This is
+    an inbook entry which explicitly refers to the *Critique of
+    Judgment* only, not to the entire fifth volume
+  author:
+  - family: Kant
+    given: Immanuel
+  container-author:
+  - family: Kant
+    given: Immanuel
+  container-title: Kants Werke. Akademie Textausgabe
+  id: "kant:ku"
+  issued: 1968
+  language: de-DE
+  page: 165-485
+  publisher: Walter de Gruyter
+  publisher-place: Berlin
+  title: Kritik der Urtheilskraft
+  type: chapter
+  volume: 5
+  volume-title: Kritik der praktischen Vernunft. Kritik der
+    Urtheilskraft
+- annote: A single essay from the critical edition of Nietzsche's works.
+    This inbook entry explicitly refers to an essay found in the first
+    volume. Note the title, booktitle, and maintitle fields. Also note
+    the sorttitle and sortyear fields. We want this entry to be listed
+    after the entry referring to the entire first volume
+  author:
+  - family: Nietzsche
+    given: Friedrich
+  container-author:
+  - family: Nietzsche
+    given: Friedrich
+  container-title: "Sämtliche Werke: Kritische Studienausgabe"
+  editor:
+  - family: Colli
+    given: Giorgio
+  - family: Montinari
+    given: Mazzino
+  id: "nietzsche:historie"
+  issued: 1988
+  language: de-DE
+  page: 243-334
+  publisher: Deutscher Taschenbuch-Verlag; Walter de Gruyter
+  publisher-place: München; Berlin; New York
+  title: "Unzeitgemässe Betrachtungen. Zweites Stück: Vom Nutzen und
+    Nachtheil der Historie für das Leben"
+  title-short: Vom Nutzen und Nachtheil der Historie
+  type: chapter
+  volume: 1
+  volume-title: Die Geburt der Tragödie. Unzeitgemäße Betrachtungen
+    I--IV. Nachgelassene Schriften 1870--1973
+---
+
+
+```
diff --git a/test/command/biblatex-incollection-2.md b/test/command/biblatex-incollection-2.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-incollection-2.md
@@ -0,0 +1,98 @@
+```
+% pandoc -f biblatex -t markdown -s
+
+@comment{adapted from http://mirrors.ctan.org/macros/latex/contrib/biblatex/doc/examples/biblatex-examples.bib}
+
+
+@string{hup = {Harvard University Press}}
+
+
+@incollection{westfahl:space,
+	Annotation = {A cross-referenced article from a collection. This is an incollection entry with a crossref field. Note the subtitle and indextitle fields},
+	Author = {Westfahl, Gary},
+	Crossref = {westfahl:frontier},
+	Hyphenation = {american},
+	Indextitle = {True Frontier, The},
+	Pages = {55-65},
+	Subtitle = {Confronting and Avoiding the Realities of Space in {American} Science Fiction Films},
+	Title = {The True Frontier}}
+
+@incollection{gaonkar:in,
+	Author = {Gaonkar, Dilip Parameshwar},
+	Booktitle = {Alternative Modernities},
+	Date = 2001,
+	Editor = {Gaonkar, Dilip Parameshwar},
+	Isbn = {0-822-32714-7},
+	Location = {Durham and London},
+	Pages = {1-23},
+	Publisher = {Duke University Press},
+	Title = {On Alternative Modernities}}
+
+@collection{westfahl:frontier,
+	Annotation = {This is a collection entry. Note the format of the location field as well as the subtitle and booksubtitle fields},
+	Booksubtitle = {The Frontier Theme in Science Fiction},
+	Booktitle = {Space and Beyond},
+	Date = 2000,
+	Editor = {Westfahl, Gary},
+	Hyphenation = {american},
+	Location = {Westport, Conn. and London},
+	Publisher = {Greenwood},
+	Subtitle = {The Frontier Theme in Science Fiction},
+	Title = {Space and Beyond}}
+^D
+---
+nocite: "[@*]"
+references:
+- annote: A cross-referenced article from a collection. This is an
+    incollection entry with a crossref field. Note the subtitle and
+    indextitle fields
+  author:
+  - family: Westfahl
+    given: Gary
+  container-title: "Space and beyond: The frontier theme in science
+    fiction"
+  editor:
+  - family: Westfahl
+    given: Gary
+  id: "westfahl:space"
+  issued: 2000
+  language: en-US
+  page: 55-65
+  publisher: Greenwood
+  publisher-place: Westport, Conn.; London
+  title: "The true frontier: Confronting and avoiding the realities of
+    space in American science fiction films"
+  title-short: The true frontier
+  type: chapter
+- author:
+  - family: Gaonkar
+    given: Dilip Parameshwar
+  container-title: Alternative modernities
+  editor:
+  - family: Gaonkar
+    given: Dilip Parameshwar
+  id: "gaonkar:in"
+  isbn: 0-822-32714-7
+  issued: 2001
+  page: 1-23
+  publisher: Duke University Press
+  publisher-place: Durham; London
+  title: On alternative modernities
+  type: chapter
+- annote: This is a collection entry. Note the format of the location
+    field as well as the subtitle and booksubtitle fields
+  editor:
+  - family: Westfahl
+    given: Gary
+  id: "westfahl:frontier"
+  issued: 2000
+  language: en-US
+  publisher: Greenwood
+  publisher-place: Westport, Conn.; London
+  title: "Space and beyond: The frontier theme in science fiction"
+  title-short: Space and beyond
+  type: book
+---
+
+
+```
diff --git a/test/command/biblatex-incollection.md b/test/command/biblatex-incollection.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-incollection.md
@@ -0,0 +1,130 @@
+```
+% pandoc -f biblatex -t markdown -s
+@comment{adapted from http://mirrors.ctan.org/macros/latex/contrib/biblatex/doc/examples/biblatex-examples.bib}
+
+@string{hup = {Harvard University Press}}
+
+@incollection{brandt,
+	Annotation = {An incollection entry with a series and a number. Note the format of the printed name and compare the useprefix option in the options field as well as vangennep. Also note the indextitle, and indexsorttitle fields},
+	Author = {von Brandt, Ahasver and Hoffmann, Erich},
+	Booktitle = {Europa im Hoch- und Spätmittelalter},
+	Date = 1987,
+	Editor = {Seibt, Ferdinand},
+	Hyphenation = {german},
+	Indexsorttitle = {Nordischen Lander von der Mitte des 11. Jahrhunderts bis 1448},
+	Indextitle = {Nordischen Länder von der Mitte des 11.~Jahrhunderts bis 1448, Die},
+	Location = {Stuttgart},
+	Number = 2,
+	Options = {useprefix=false},
+	Pages = {884-917},
+	Publisher = {Klett-Cotta},
+	Series = {Handbuch der europäischen Geschichte},
+	Shorttitle = {Die nordischen Länder},
+	Title = {Die nordischen Länder von der Mitte des 11.~Jahrhunderts bis 1448}}
+
+@incollection{hyman,
+	Annotation = {An incollection entry with a series and number field},
+	Author = {Hyman, Arthur},
+	Booktitle = {Studies in {Aristotle}},
+	Date = 1981,
+	Editor = {O'Meara, Dominic J.},
+	Hyphenation = {american},
+	Indextitle = {Aristotle's Theory of the Intellect},
+	Keywords = {secondary},
+	Location = {Washington, D.C.},
+	Number = 9,
+	Pages = {161-191},
+	Publisher = {The Catholic University of America Press},
+	Series = {Studies in Philosophy and the History of Philosophy},
+	Shorttitle = {Aristotle's Theory of the Intellect},
+	Title = {Aristotle's Theory of the Intellect and its Interpretation by {Averroes}}}
+
+@incollection{pines,
+	Annotation = {A typical incollection entry. Note the indextitle field},
+	Author = {Pines, Shlomo},
+	Booktitle = {Studies in Medieval {Jewish} History and Literature},
+	Date = 1979,
+	Editor = {Twersky, Isadore},
+	Hyphenation = {american},
+	Indextitle = {Limitations of Human Knowledge According to Al-Farabi, ibn Bajja, and Maimonides, The},
+	Keywords = {secondary},
+	Location = {Cambridge, Mass.},
+	Pages = {82-109},
+	Publisher = hup,
+	Shorttitle = {Limitations of Human Knowledge},
+	Title = {The Limitations of Human Knowledge According to {Al-Farabi}, {ibn Bajja}, and {Maimonides}}}
+
+^D
+---
+nocite: "[@*]"
+references:
+- annote: An incollection entry with a series and a number. Note the
+    format of the printed name and compare the useprefix option in the
+    options field as well as vangennep. Also note the indextitle, and
+    indexsorttitle fields
+  author:
+  - dropping-particle: von
+    family: Brandt
+    given: Ahasver
+  - family: Hoffmann
+    given: Erich
+  collection-number: 2
+  collection-title: Handbuch der europäischen Geschichte
+  container-title: Europa im Hoch- und Spätmittelalter
+  editor:
+  - family: Seibt
+    given: Ferdinand
+  id: brandt
+  issued: 1987
+  language: de-DE
+  page: 884-917
+  publisher: Klett-Cotta
+  publisher-place: Stuttgart
+  title: Die nordischen Länder von der Mitte des 11. Jahrhunderts bis
+    1448
+  title-short: Die nordischen Länder
+  type: chapter
+- annote: An incollection entry with a series and number field
+  author:
+  - family: Hyman
+    given: Arthur
+  collection-number: 9
+  collection-title: Studies in philosophy and the history of philosophy
+  container-title: Studies in Aristotle
+  editor:
+  - family: O'Meara
+    given: Dominic J.
+  id: hyman
+  issued: 1981
+  keyword: secondary
+  language: en-US
+  page: 161-191
+  publisher: The Catholic University of America Press
+  publisher-place: Washington, D.C.
+  title: Aristotle's theory of the intellect and its interpretation by
+    Averroes
+  title-short: Aristotle's theory of the intellect
+  type: chapter
+- annote: A typical incollection entry. Note the indextitle field
+  author:
+  - family: Pines
+    given: Shlomo
+  container-title: Studies in medieval Jewish history and literature
+  editor:
+  - family: Twersky
+    given: Isadore
+  id: pines
+  issued: 1979
+  keyword: secondary
+  language: en-US
+  page: 82-109
+  publisher: Harvard University Press
+  publisher-place: Cambridge, Mass.
+  title: The limitations of human knowledge according to Al-Farabi, [ibn
+    Bajja]{.nocase}, and Maimonides
+  title-short: Limitations of human knowledge
+  type: chapter
+---
+
+
+```
diff --git a/test/command/biblatex-inproceedings.md b/test/command/biblatex-inproceedings.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-inproceedings.md
@@ -0,0 +1,88 @@
+```
+% pandoc -f biblatex -t markdown -s
+@comment{adapted from http://mirrors.ctan.org/macros/latex/contrib/biblatex/doc/examples/biblatex-examples.bib}
+
+@string{cup = {Cambridge University Press}}
+
+@inproceedings{moraux,
+	Annotation = {This is a typical inproceedings entry. Note the booksubtitle, shorttitle, indextitle, and indexsorttitle fields. Also note the eventdate field.},
+	Author = {Moraux, Paul},
+	Booktitle = {Aristotle on Mind and the Senses},
+	Booktitleaddon = {Proceedings of the Seventh Symposium Aristotelicum},
+	Date = 1979,
+	Editor = {Lloyd, G. E. R. and Owen, G. E. L.},
+	Eventdate = 1975,
+	Hyphenation = {french},
+	Indexsorttitle = {De Anima dans la tradition grecque},
+	Indextitle = {\emph{De Anima} dans la tradition grècque, Le},
+	Keywords = {secondary},
+	Location = {Cambridge},
+	Pages = {281-324},
+	Publisher = cup,
+	Shorttitle = {\emph{De Anima} dans la tradition grècque},
+	Subtitle = {Quelques aspects de l'interpretation du traité, de Theophraste à Themistius},
+	Title = {Le \emph{De Anima} dans la tradition grècque}}
+
+@inproceedings{salam,
+	Author = {Salam, Abdus},
+	Booksubtitle = {Relativistic groups and analyticity},
+	Booktitle = {Elementary particle theory},
+	Booktitleaddon = {Proceedings of the Eighth {Nobel} Symposium},
+	Date = 1968,
+	Editor = {Svartholm, Nils},
+	Eventdate = {1968-05-19/1968-05-25},
+	Location = {Stockholm},
+	Pages = {367-377},
+	Publisher = {Almquist \& Wiksell},
+	Title = {Weak and Electromagnetic Interactions},
+	Venue = {Aspenäsgarden, Lerum}}
+^D
+---
+nocite: "[@*]"
+references:
+- annote: This is a typical inproceedings entry. Note the booksubtitle,
+    shorttitle, indextitle, and indexsorttitle fields. Also note the
+    eventdate field.
+  author:
+  - family: Moraux
+    given: Paul
+  container-title: Aristotle on Mind and the Senses. Proceedings of the
+    Seventh Symposium Aristotelicum
+  editor:
+  - family: Lloyd
+    given: G. E. R.
+  - family: Owen
+    given: G. E. L.
+  event-date: 1975
+  id: moraux
+  issued: 1979
+  keyword: secondary
+  language: fr-FR
+  page: 281-324
+  publisher: Cambridge University Press
+  publisher-place: Cambridge
+  title: "Le *De Anima* dans la tradition grècque: Quelques aspects de
+    l'interpretation du traité, de Theophraste à Themistius"
+  title-short: "*De Anima* dans la tradition grècque"
+  type: paper-conference
+- author:
+  - family: Salam
+    given: Abdus
+  container-title: "Elementary particle theory: Relativistic groups and
+    analyticity. Proceedings of the eighth Nobel symposium"
+  editor:
+  - family: Svartholm
+    given: Nils
+  event-date: 1968-05-19/1968-05-25
+  event-place: Aspenäsgarden, Lerum
+  id: salam
+  issued: 1968
+  page: 367-377
+  publisher: Almquist & Wiksell
+  publisher-place: Stockholm
+  title: Weak and electromagnetic interactions
+  type: paper-conference
+---
+
+
+```
diff --git a/test/command/biblatex-issue288.md b/test/command/biblatex-issue288.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-issue288.md
@@ -0,0 +1,35 @@
+```
+% pandoc -f biblatex -t markdown -s
+@thesis{Leavitt_2016,
+location = {{Los Angeles, CA}},
+title = {Upvoting the News: {{Breaking}} News Aggregation, Crowd Collaboration,
+and Algorithm-Driven Attention on Reddit.Com},
+timestamp = {2017-04-06T14:13:22Z},
+langid = {english},
+institution = {{University of Southern California}},
+type = {Dissertation},
+author = {Leavitt, Alex},
+date = {2016-08},
+}
+
+^D
+---
+nocite: "[@*]"
+references:
+- author:
+  - family: Leavitt
+    given: Alex
+  genre: Dissertation
+  id: Leavitt_2016
+  issued: 2016-08
+  language: en-US
+  publisher: University of Southern California
+  publisher-place: Los Angeles, CA
+  title: "Upvoting the news: Breaking news aggregation, crowd
+    collaboration, and algorithm-driven attention on reddit.com"
+  title-short: Upvoting the news
+  type: thesis
+---
+
+
+```
diff --git a/test/command/biblatex-itzhaki.md b/test/command/biblatex-itzhaki.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-itzhaki.md
@@ -0,0 +1,82 @@
+```
+% pandoc -f biblatex -t markdown -s
+@comment{
+
+Adapted from biblatex-example.bib
+
+Formatted with pandoc and chicago-author-date.csl, 2013-10-23:
+
+(Itzhaki 1996)
+
+Itzhaki, Nissan. 1996. “Some Remarks on ’t Hooft’s S-matrix for Black
+Holes” (version 1). March 11.
+
+
+Formatted with pandoc and apa.csl, 2013-10-23:
+
+(Itzhaki, 1996)
+
+Itzhaki, N. (1996, March 11). Some remarks on ’t Hooft’s S-matrix for
+black holes.
+
+
+NOTES:
+
+- biblio2yaml:
+	- eprinttype = {arxiv}, eprint = {hep-th/9603067}, 
+	  should be converted to a url: http://arxiv.org/abs/hep-th/9603067
+	  (prefix http://arxiv.org/abs/ seems to work for all arxiv material)
+
+- citeproc:
+	- obtaining correct case of "'t Hooft's" in title is possible but awkward:
+	  '{t Hooft's} works; {'t Hooft}'s or '{t Hooft}'s do not
+
+}
+
+@Online{itzhaki,
+  author       = {Itzhaki, Nissan},
+  title        = {Some remarks on '{t Hooft's} {S}-matrix for black holes},
+  date         = {1996-03-11},
+  version      = 1,
+  hyphenation  = {american},
+  eprinttype   = {arxiv},
+  eprint       = {hep-th/9603067},
+  annotation   = {An online reference from arXiv. Note the
+                  eprint and eprinttype fields. Also note that
+                  the arXiv reference is transformed into a clickable link if
+                  hyperref support has been enabled},
+  abstract     = {We discuss the limitations of 't Hooft's proposal for the
+                  black hole S-matrix. We find that the validity of the S-matrix
+                  implies violation of the semi-classical approximation at
+                  scales large compared to the Planck scale. We also show that
+                  the effect of the centrifugal barrier on the S-matrix is
+                  crucial even for large transverse distances.},
+}
+
+^D
+---
+nocite: "[@*]"
+references:
+- abstract: We discuss the limitations of 't Hooft's proposal for the
+    black hole S-matrix. We find that the validity of the S-matrix
+    implies violation of the semi-classical approximation at scales
+    large compared to the Planck scale. We also show that the effect of
+    the centrifugal barrier on the S-matrix is crucial even for large
+    transverse distances.
+  annote: An online reference from arXiv. Note the eprint and eprinttype
+    fields. Also note that the arXiv reference is transformed into a
+    clickable link if hyperref support has been enabled
+  author:
+  - family: Itzhaki
+    given: Nissan
+  id: itzhaki
+  issued: 1996-03-11
+  language: en-US
+  title: Some remarks on '[t Hooft's]{.nocase} S-matrix for black holes
+  type: webpage
+  url: "https://arxiv.org/abs/hep-th/9603067"
+  version: 1
+---
+
+
+```
diff --git a/test/command/biblatex-jaffe.md b/test/command/biblatex-jaffe.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-jaffe.md
@@ -0,0 +1,82 @@
+```
+% pandoc -f biblatex -t markdown -s
+@comment{
+
+Adapted from biblatex-example.bib
+
+Formatted with pandoc and chicago-author-date.csl, 2013-10-23:
+
+(Jaffé 1885–1888)
+
+Jaffé, Philipp, ed. 1885–1888. *Regesta Pontificum Romanorum ab condita
+ecclesia ad annum post Christum natum \<span
+Style="font-variant:small-caps;"\>mcxcviii\</span\>*. 2nd ed. 2.
+Leipzig.
+
+
+Formatted with pandoc and apa.csl, 2013-10-23:
+
+(Jaffé, 1885–1888)
+
+Jaffé, P. (Ed.). (1885–1888). *Regesta Pontificum Romanorum ab condita
+ecclesia ad annum post Christum natum \<span
+style="font-variant:small-caps;"\>mcxcviii\</span\>* (2nd ed., 1-2).
+Leipzig.
+
+
+NOTES:
+
+- biblatex conversion:
+	- hyphenation = {latin}
+- citeproc:
+	- "vols." is missing
+		- works in Zotero
+		- This does not show up in the tests from the citeproc test suite that currently fail.
+	- "\<span ...\> needs to be fixed.
+		- maybe add markdown syntax ^^small caps^^ ?
+		- in pandoc "plain" output, small caps could be converted to uppercase chars: "MCXCVIII" would definitely look better here.
+
+}
+
+@Collection{jaffe,
+  editor       = {Jaff{\'e}, Philipp},
+  title        = {Regesta Pontificum Romanorum ab condita ecclesia ad annum post
+                  Christum natum \textsc{mcxcviii}},
+  date         = {1885/1888},
+  editora      = {Loewenfeld, Samuel and Kaltenbrunner, Ferdinand and Ewald,
+                  Paul},
+  edition      = 2,
+  volumes      = 2,
+  location     = {Leipzig},
+  editoratype  = {redactor},
+  indextitle   = {Regesta Pontificum Romanorum},
+  shorttitle   = {Regesta Pontificum Romanorum},
+  annotation   = {A collection entry with edition and
+                  volumes fields. Note the editora and
+                  editoratype fields},
+  hyphenation  = {latin},
+}
+
+^D
+---
+nocite: "[@*]"
+references:
+- annote: A collection entry with edition and volumes fields. Note the
+    editora and editoratype fields
+  edition: 2
+  editor:
+  - family: Jaffé
+    given: Philipp
+  id: jaffe
+  issued: 1885/1888
+  language: la
+  number-of-volumes: 2
+  publisher-place: Leipzig
+  title: Regesta Pontificum Romanorum ab condita ecclesia ad annum post
+    Christum natum [mcxcviii]{.smallcaps}
+  title-short: Regesta Pontificum Romanorum
+  type: book
+---
+
+
+```
diff --git a/test/command/biblatex-jcg.md b/test/command/biblatex-jcg.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-jcg.md
@@ -0,0 +1,54 @@
+```
+% pandoc -f biblatex -t markdown -s
+@comment{
+
+Adapted from biblatex-example.bib
+
+Formatted with pandoc and chicago-author-date.csl, 2013-10-23:
+
+(“Semantic 3D Media and Content” 2011)
+
+“Semantic 3D Media and Content.” 2011. *Computers and Graphics* 35 (4).
+
+
+Formatted with pandoc and apa.csl, 2013-10-23:
+
+(“Semantic 3D media and content,” 2011)
+
+Semantic 3D media and content. (2011). *Computers and Graphics*,
+*35*(4).
+
+
+NOTES:
+	- output looks OK even if indistinguishable from article without page numbers
+
+}
+
+@Periodical{jcg,
+  title        = {Computers and Graphics},
+  year         = 2011,
+  issuetitle   = {Semantic {3D} Media and Content},
+  volume       = 35,
+  number       = 4,
+  issn         = {0097-8493},
+  annotation   = {This is a periodical entry with an issn
+                  field.},
+}
+
+^D
+---
+nocite: "[@*]"
+references:
+- annote: This is a periodical entry with an issn field.
+  container-title: Computers and Graphics
+  id: jcg
+  issn: 0097-8493
+  issue: 4
+  issued: 2011
+  title: Semantic 3D media and content
+  type: article-journal
+  volume: 35
+---
+
+
+```
diff --git a/test/command/biblatex-kant-kpv.md b/test/command/biblatex-kant-kpv.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-kant-kpv.md
@@ -0,0 +1,90 @@
+```
+% pandoc -f biblatex -t markdown -s
+@comment{
+
+Adapted from biblatex-example.bib
+
+
+Formatted with pandoc and chicago-author-date.csl, 2013-10-23:
+
+(Kant 1968)
+
+Kant, Immanuel. 1968. “Kritik der praktischen Vernunft.” In *Kants
+Werke. Akademie Textausgabe*, by Immanuel Kant, 5:1–163. Berlin: Walter
+de Gruyter.
+
+
+Formatted with pandoc and apa.csl, 2013-10-23:
+
+(Kant, 1968)
+
+Kant, I. (1968). Kritik der praktischen Vernunft. In *Kants Werke.
+Akademie Textausgabe* (Vol. 5, pp. 1–163). Berlin: Walter de Gruyter.
+
+
+NOTES:
+
+- citeproc
+	- support for the not yet official "volume-title" is missing
+
+- csl style file
+	- if author and container-author are identical, container-author should be suppressed (apparently csl style file issue; zotero shows same behaviour)
+
+}
+
+@InBook{kant:kpv,
+  title        = {Kritik der praktischen Vernunft},
+  date         = 1968,
+  author       = {Kant, Immanuel},
+  booktitle    = {Kritik der praktischen Vernunft. Kritik der Urtheilskraft},
+  bookauthor   = {Kant, Immanuel},
+  maintitle    = {Kants Werke. Akademie Textausgabe},
+  volume       = 5,
+  publisher    = {Walter de Gruyter},
+  location     = {Berlin},
+  pages        = {1-163},
+  shorthand    = {KpV},
+  hyphenation  = {german},
+  shorttitle   = {Kritik der praktischen Vernunft},
+  annotation   = {An edition of Kant's \emph{Collected Works}, volume five. This
+                  is an inbook entry which explicitly refers to the
+                  \emph{Critique of Practical Reason} only, not to the entire
+                  fifth volume. Note the author and bookauthor
+                  fields in the database file. By default, the
+                  bookauthor is omitted if the values of the
+                  author and bookauthor fields are identical},
+}
+
+^D
+---
+nocite: "[@*]"
+references:
+- annote: An edition of Kant's *Collected Works*, volume five. This is
+    an inbook entry which explicitly refers to the *Critique of
+    Practical Reason* only, not to the entire fifth volume. Note the
+    author and bookauthor fields in the database file. By default, the
+    bookauthor is omitted if the values of the author and bookauthor
+    fields are identical
+  author:
+  - family: Kant
+    given: Immanuel
+  container-author:
+  - family: Kant
+    given: Immanuel
+  container-title: Kants Werke. Akademie Textausgabe
+  id: "kant:kpv"
+  issued: 1968
+  language: de-DE
+  page: 1-163
+  publisher: Walter de Gruyter
+  publisher-place: Berlin
+  title: Kritik der praktischen Vernunft
+  title-short: Kritik der praktischen Vernunft
+  type: chapter
+  volume: 5
+  volume-title: Kritik der praktischen Vernunft. Kritik der
+    Urtheilskraft
+---
+
+
+```
diff --git a/test/command/biblatex-kant-ku.md b/test/command/biblatex-kant-ku.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-kant-ku.md
@@ -0,0 +1,82 @@
+```
+% pandoc -f biblatex -t markdown -s
+@comment{
+
+Adapted from biblatex-example.bib
+
+
+Formatted with pandoc and chicago-author-date.csl, 2013-10-23:
+
+(Kant 1968)
+
+Kant, Immanuel. 1968. “Kritik der Urtheilskraft.” In *Kants Werke.
+Akademie Textausgabe*, by Immanuel Kant, 5:165–485. Berlin: Walter de
+Gruyter.
+
+
+Formatted with pandoc and apa.csl, 2013-10-23:
+
+(Kant, 1968)
+
+Kant, I. (1968). Kritik der Urtheilskraft. In *Kants Werke. Akademie
+Textausgabe* (Vol. 5, pp. 165–485). Berlin: Walter de Gruyter.
+
+
+NOTES:
+
+- citeproc
+	- support for the not yet official "volume-title" is missing
+	
+- CSL style file
+	- if author and container-author are identical, container-author should be suppressed (apparently csl style file issue; zotero shows same behaviour)
+
+}
+
+@InBook{kant:ku,
+  title        = {Kritik der Urtheilskraft},
+  date         = 1968,
+  author       = {Kant, Immanuel},
+  booktitle    = {Kritik der praktischen Vernunft. Kritik der Urtheilskraft},
+  bookauthor   = {Kant, Immanuel},
+  maintitle    = {Kants Werke. Akademie Textausgabe},
+  volume       = 5,
+  publisher    = {Walter de Gruyter},
+  location     = {Berlin},
+  pages        = {165-485},
+  shorthand    = {KU},
+  hyphenation  = {german},
+  annotation   = {An edition of Kant's \emph{Collected Works}, volume five. This
+                  is an inbook entry which explicitly refers to the
+                  \emph{Critique of Judgment} only, not to the entire fifth
+                  volume},
+}
+
+^D
+---
+nocite: "[@*]"
+references:
+- annote: An edition of Kant's *Collected Works*, volume five. This is
+    an inbook entry which explicitly refers to the *Critique of
+    Judgment* only, not to the entire fifth volume
+  author:
+  - family: Kant
+    given: Immanuel
+  container-author:
+  - family: Kant
+    given: Immanuel
+  container-title: Kants Werke. Akademie Textausgabe
+  id: "kant:ku"
+  issued: 1968
+  language: de-DE
+  page: 165-485
+  publisher: Walter de Gruyter
+  publisher-place: Berlin
+  title: Kritik der Urtheilskraft
+  type: chapter
+  volume: 5
+  volume-title: Kritik der praktischen Vernunft. Kritik der
+    Urtheilskraft
+---
+
+
+```
diff --git a/test/command/biblatex-kastenholz.md b/test/command/biblatex-kastenholz.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-kastenholz.md
@@ -0,0 +1,126 @@
+```
+% pandoc -f biblatex -t markdown -s
+@comment{
+
+Adapted from biblatex-example.bib
+
+
+Formatted with pandoc and chicago-author-date.csl, 2013-10-23:
+
+(Kastenholz and Hünenberger 2006)
+
+Kastenholz, M. A., and Philippe H. Hünenberger. 2006. “Computation of
+Methodologyindependent Ionic Solvation Free Energies from Molecular
+Simulations: I. the Electrostatic Potential in Molecular Liquids.”
+*J. Chem. Phys.* 124.
+doi:[10.1063/1.2172593](https://doi.org/10.1063/1.2172593 "10.1063/1.2172593").
+
+
+Formatted with pandoc and apa.csl, 2013-10-23:
+
+(Kastenholz & Hünenberger, 2006)
+
+Kastenholz, M. A., & Hünenberger, P. H. (2006). Computation of
+methodologyindependent ionic solvation free energies from molecular
+simulations: I. the electrostatic potential in molecular liquids.
+*J. Chem. Phys.*, *124*.
+doi:[10.1063/1.2172593](https://doi.org/10.1063/1.2172593 "10.1063/1.2172593")
+
+
+NOTES:
+
+- biblio2xaml
+	- fix conversion of "\hyphen”
+	- the string "doi:" should not appear as part of the content of the "doi" field 
+
+}
+
+@string{ jchph   = {J.~Chem. Phys.} }
+
+@Article{kastenholz,
+  author       = {Kastenholz, M. A. and H{\"u}nenberger, Philippe H.},
+  title        = {Computation of methodology\hyphen independent ionic solvation
+                  free energies from molecular simulations},
+  journaltitle = jchph,
+  date         = 2006,
+  subtitle     = {I. {The} electrostatic potential in molecular liquids},
+  volume       = 124,
+  eid          = 124106,
+  doi          = {10.1063/1.2172593},
+  hyphenation  = {american},
+  indextitle   = {Computation of ionic solvation free energies},
+  annotation   = {An article entry with an eid and a
+                  doi field. Note that the \textsc{doi} is transformed
+                  into a clickable link if hyperref support has been
+                  enabled},
+  abstract     = {The computation of ionic solvation free energies from
+                  atomistic simulations is a surprisingly difficult problem that
+                  has found no satisfactory solution for more than 15 years. The
+                  reason is that the charging free energies evaluated from such
+                  simulations are affected by very large errors. One of these is
+                  related to the choice of a specific convention for summing up
+                  the contributions of solvent charges to the electrostatic
+                  potential in the ionic cavity, namely, on the basis of point
+                  charges within entire solvent molecules (M scheme) or on the
+                  basis of individual point charges (P scheme). The use of an
+                  inappropriate convention may lead to a charge-independent
+                  offset in the calculated potential, which depends on the
+                  details of the summation scheme, on the quadrupole-moment
+                  trace of the solvent molecule, and on the approximate form
+                  used to represent electrostatic interactions in the
+                  system. However, whether the M or P scheme (if any) represents
+                  the appropriate convention is still a matter of on-going
+                  debate. The goal of the present article is to settle this
+                  long-standing controversy by carefully analyzing (both
+                  analytically and numerically) the properties of the
+                  electrostatic potential in molecular liquids (and inside
+                  cavities within them).},
+}
+
+^D
+---
+nocite: "[@*]"
+references:
+- abstract: The computation of ionic solvation free energies from
+    atomistic simulations is a surprisingly difficult problem that has
+    found no satisfactory solution for more than 15 years. The reason is
+    that the charging free energies evaluated from such simulations are
+    affected by very large errors. One of these is related to the choice
+    of a specific convention for summing up the contributions of solvent
+    charges to the electrostatic potential in the ionic cavity, namely,
+    on the basis of point charges within entire solvent molecules (M
+    scheme) or on the basis of individual point charges (P scheme). The
+    use of an inappropriate convention may lead to a charge-independent
+    offset in the calculated potential, which depends on the details of
+    the summation scheme, on the quadrupole-moment trace of the solvent
+    molecule, and on the approximate form used to represent
+    electrostatic interactions in the system. However, whether the M or
+    P scheme (if any) represents the appropriate convention is still a
+    matter of on-going debate. The goal of the present article is to
+    settle this long-standing controversy by carefully analyzing (both
+    analytically and numerically) the properties of the electrostatic
+    potential in molecular liquids (and inside cavities within them).
+  annote: An article entry with an eid and a doi field. Note that the
+    [doi]{.smallcaps} is transformed into a clickable link if hyperref
+    support has been enabled
+  author:
+  - family: Kastenholz
+    given: M. A.
+  - family: Hünenberger
+    given: Philippe H.
+  container-title: J. Chem. Phys.
+  doi: 10.1063/1.2172593
+  id: kastenholz
+  issued: 2006
+  language: en-US
+  title: "Computation of methodology-independent ionic solvation free
+    energies from molecular simulations: I. The electrostatic potential
+    in molecular liquids"
+  title-short: Computation of methodology-independent ionic solvation
+    free energies from molecular simulations
+  type: article-journal
+  volume: 124
+---
+
+
+```
diff --git a/test/command/biblatex-knuth-ct-a.md b/test/command/biblatex-knuth-ct-a.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-knuth-ct-a.md
@@ -0,0 +1,78 @@
+```
+% pandoc -f biblatex -t markdown -s
+@comment{
+
+Adapted from biblatex-example.bib
+
+
+Formatted with pandoc and chicago-author-date.csl, 2013-10-23:
+
+(Knuth 1984)
+
+Knuth, Donald E. 1984. *Computers & Typesetting*. Vol. A. Reading,
+Mass.: Addison-Wesley.
+
+
+Formatted with pandoc and apa.csl, 2013-10-23:
+
+(Knuth, 1984)
+
+Knuth, D. E. (1984). *Computers & typesetting* (Vol. A). Reading, Mass.:
+Addison-Wesley.
+
+
+NOTES:
+
+- volume-title currently not implemented by chicago-author-date.csl and apa.csl.
+
+}
+
+@Book{knuth:ct:a,
+  author       = {Knuth, Donald E.},
+  title        = {The {\TeX} book},
+  date         = 1984,
+  maintitle    = {Computers \& Typesetting},
+  volume       = {A},
+  publisher    = {Addison-Wesley},
+  location     = {Reading, Mass.},
+  hyphenation  = {american},
+  sortyear     = {1984-1},
+  sorttitle    = {Computers & Typesetting A},
+  indexsorttitle= {The TeXbook},
+  indextitle   = {\protect\TeX book, The},
+  shorttitle   = {\TeX book},
+  annotation   = {The first volume of a five-volume book. Note the
+                  sorttitle and sortyear fields. We want this
+                  volume to be listed after the entry referring to the entire
+                  five-volume set. Also note the indextitle and
+                  indexsorttitle fields. Indexing packages that don't
+                  generate robust index entries require some control sequences
+                  to be protected from expansion},
+}
+
+^D
+---
+nocite: "[@*]"
+references:
+- annote: The first volume of a five-volume book. Note the sorttitle and
+    sortyear fields. We want this volume to be listed after the entry
+    referring to the entire five-volume set. Also note the indextitle
+    and indexsorttitle fields. Indexing packages that don't generate
+    robust index entries require some control sequences to be protected
+    from expansion
+  author:
+  - family: Knuth
+    given: Donald E.
+  id: "knuth:ct:a"
+  issued: 1984
+  language: en-US
+  publisher: Addison-Wesley
+  publisher-place: Reading, Mass.
+  title: Computers & typesetting
+  type: book
+  volume: A
+  volume-title: The TeX book
+---
+
+
+```
diff --git a/test/command/biblatex-knuth-ct-b.md b/test/command/biblatex-knuth-ct-b.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-knuth-ct-b.md
@@ -0,0 +1,70 @@
+```
+% pandoc -f biblatex -t markdown -s
+@comment{
+
+Adapted from biblatex-example.bib
+
+
+Formatted with pandoc and chicago-author-date.csl, 2015-03-08:
+
+(Knuth 1986)
+
+Knuth, Donald E. 1986. *Computers & Typesetting*. Vol. B. Reading,
+Mass.: Addison-Wesley.
+
+
+Formatted with pandoc and apa.csl, 2015-03-08:
+
+(Knuth, 1986)
+
+Knuth, D. E. (1986). *Computers & typesetting* (Vol. B). Reading, Mass.:
+Addison-Wesley.
+
+
+NOTES:
+
+- volume-title currently not implemented by chicago-author-date.csl and apa.csl.
+
+}
+
+@Book{knuth:ct:b,
+  author       = {Knuth, Donald E.},
+  title        = {\TeX: {T}he Program},
+  date         = 1986,
+  maintitle    = {Computers \& Typesetting},
+  volume       = {B},
+  publisher    = {Addison-Wesley},
+  location     = {Reading, Mass.},
+  hyphenation  = {american},
+  sortyear     = {1986-1},
+  sorttitle    = {Computers & Typesetting B},
+  indexsorttitle= {TeX: The Program},
+  shorttitle   = {\TeX},
+  annotation   = {The second volume of a five-volume book. Note the
+                  sorttitle and sortyear fields. Also note the
+                  indexsorttitle field},
+}
+
+^D
+---
+nocite: "[@*]"
+references:
+- annote: The second volume of a five-volume book. Note the sorttitle
+    and sortyear fields. Also note the indexsorttitle field
+  author:
+  - family: Knuth
+    given: Donald E.
+  id: "knuth:ct:b"
+  issued: 1986
+  language: en-US
+  publisher: Addison-Wesley
+  publisher-place: Reading, Mass.
+  title: Computers & typesetting
+  title-short: TeX
+  type: book
+  volume: B
+  volume-title: "TeX: The program"
+---
+
+
+```
diff --git a/test/command/biblatex-knuth-ct-c.md b/test/command/biblatex-knuth-ct-c.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-knuth-ct-c.md
@@ -0,0 +1,69 @@
+```
+% pandoc -f biblatex -t markdown -s
+@comment{
+
+Adapted from biblatex-example.bib
+
+
+Formatted with pandoc and chicago-author-date.csl, 2015-03-08:
+
+(Knuth 1986)
+
+Knuth, Donald E. 1986. *Computers & Typesetting*. Vol. C. Reading,
+Mass.: Addison-Wesley.
+
+
+Formatted with pandoc and apa.csl, 2015-03-08:
+
+(Knuth, 1986)
+
+Knuth, D. E. (1986). *Computers & typesetting* (Vol. C). Reading, Mass.:
+Addison-Wesley.
+
+
+NOTES:
+
+- volume-title currently not implemented by chicago-author-date.csl and apa.csl.
+
+}
+
+@Book{knuth:ct:c,
+  author       = {Knuth, Donald E.},
+  title        = {The {METAFONTbook}},
+  date         = 1986,
+  maintitle    = {Computers \& Typesetting},
+  volume       = {C},
+  publisher    = {Addison-Wesley},
+  location     = {Reading, Mass.},
+  hyphenation  = {american},
+  sortyear     = {1986-2},
+  sorttitle    = {Computers & Typesetting C},
+  indextitle   = {METAFONTbook, The},
+  shorttitle   = {{METAFONTbook}},
+  annotation   = {The third volume of a five-volume book. Note the
+                  sorttitle and sortyear fields as well as the
+                  indextitle field},
+}
+
+^D
+---
+nocite: "[@*]"
+references:
+- annote: The third volume of a five-volume book. Note the sorttitle and
+    sortyear fields as well as the indextitle field
+  author:
+  - family: Knuth
+    given: Donald E.
+  id: "knuth:ct:c"
+  issued: 1986
+  language: en-US
+  publisher: Addison-Wesley
+  publisher-place: Reading, Mass.
+  title: Computers & typesetting
+  type: book
+  volume: C
+  volume-title: The METAFONTbook
+---
+
+
+```
diff --git a/test/command/biblatex-knuth-ct-d.md b/test/command/biblatex-knuth-ct-d.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-knuth-ct-d.md
@@ -0,0 +1,71 @@
+```
+% pandoc -f biblatex -t markdown -s
+@comment{
+
+Adapted from biblatex-example.bib
+
+
+Formatted with pandoc and chicago-author-date.csl, 2015-03-08:
+
+(Knuth 1986)
+
+Knuth, Donald E. 1986. *Computers & Typesetting*. Vol. D. Reading,
+Mass.: Addison-Wesley.
+
+
+Formatted with pandoc and apa.csl, 2015-03-08:
+
+(Knuth, 1986)
+
+Knuth, D. E. (1986). *Computers & typesetting* (Vol. D). Reading, Mass.:
+Addison-Wesley.
+
+
+NOTES:
+
+- biblio2yaml
+	- Should letters following a colon, such as the "T" in "{{METAFONT}: {T}he Program}" be protected by default? -- I'm not sure ...
+
+- volume-title currently not implemented by chicago-author-date.csl and apa.csl.
+
+}
+
+@Book{knuth:ct:d,
+  author       = {Knuth, Donald E.},
+  title        = {{METAFONT}: {T}he Program},
+  date         = 1986,
+  maintitle    = {Computers \& Typesetting},
+  volume       = {D},
+  publisher    = {Addison-Wesley},
+  location     = {Reading, Mass.},
+  hyphenation  = {american},
+  sortyear     = {1986-3},
+  sorttitle    = {Computers & Typesetting D},
+  shorttitle   = {{METAFONT}},
+  annotation   = {The fourth volume of a five-volume book. Note the
+                  sorttitle and sortyear fields},
+}
+
+^D
+---
+nocite: "[@*]"
+references:
+- annote: The fourth volume of a five-volume book. Note the sorttitle
+    and sortyear fields
+  author:
+  - family: Knuth
+    given: Donald E.
+  id: "knuth:ct:d"
+  issued: 1986
+  language: en-US
+  publisher: Addison-Wesley
+  publisher-place: Reading, Mass.
+  title: Computers & typesetting
+  title-short: METAFONT
+  type: book
+  volume: D
+  volume-title: "METAFONT: The program"
+---
+
+
+```
diff --git a/test/command/biblatex-knuth-ct-e.md b/test/command/biblatex-knuth-ct-e.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-knuth-ct-e.md
@@ -0,0 +1,66 @@
+```
+% pandoc -f biblatex -t markdown -s
+@comment{
+
+Adapted from biblatex-example.bib
+
+
+Formatted with pandoc and chicago-author-date.csl, 2015-03-08:
+
+(Knuth 1986)
+
+Knuth, Donald E. 1986. *Computers & Typesetting*. Vol. E. Reading,
+Mass.: Addison-Wesley.
+
+
+Formatted with pandoc and apa.csl, 2015-03-08:
+
+(Knuth, 1986)
+
+Knuth, D. E. (1986). *Computers & typesetting* (Vol. E). Reading, Mass.:
+Addison-Wesley.
+
+
+NOTES:
+
+- volume-title currently not implemented by chicago-author-date.csl and apa.csl.
+
+}
+
+@Book{knuth:ct:e,
+  author       = {Knuth, Donald E.},
+  title        = {Computer Modern Typefaces},
+  date         = 1986,
+  maintitle    = {Computers \& Typesetting},
+  volume       = {E},
+  publisher    = {Addison-Wesley},
+  location     = {Reading, Mass.},
+  hyphenation  = {american},
+  sortyear     = {1986-4},
+  sorttitle    = {Computers & Typesetting E},
+  annotation   = {The fifth volume of a five-volume book. Note the
+                  sorttitle and sortyear fields},
+}
+
+^D
+---
+nocite: "[@*]"
+references:
+- annote: The fifth volume of a five-volume book. Note the sorttitle and
+    sortyear fields
+  author:
+  - family: Knuth
+    given: Donald E.
+  id: "knuth:ct:e"
+  issued: 1986
+  language: en-US
+  publisher: Addison-Wesley
+  publisher-place: Reading, Mass.
+  title: Computers & typesetting
+  type: book
+  volume: E
+  volume-title: Computer modern typefaces
+---
+
+
+```
diff --git a/test/command/biblatex-knuth-ct-related.md b/test/command/biblatex-knuth-ct-related.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-knuth-ct-related.md
@@ -0,0 +1,72 @@
+```
+% pandoc -f biblatex -t markdown -s
+@comment{
+
+Adapted from biblatex-example.bib
+
+
+Formatted with pandoc and chicago-author-date.csl, 2013-10-23:
+
+(Knuth 1984–1986)
+
+Knuth, Donald E. 1984–1986. *Computers & Typesetting*. 5. Reading,
+Mass.: Addison-Wesley.
+
+
+Formatted with pandoc and apa.csl, 2013-10-23:
+
+(Knuth, 1984–1986)
+
+Knuth, D. E. (1984–1986). *Computers & typesetting* (1-5). Reading,
+Mass.: Addison-Wesley.
+
+
+NOTES:
+
+- biblio2yaml
+	- related = {...}, relatedtype  = {multivolume}, -- no counterpart in CSL 
+
+- citeproc
+	- term "vols." missing
+
+}
+
+@Book{knuth:ct:related,
+  author       = {Knuth, Donald E.},
+  title        = {Computers \& Typesetting},
+  date         = {1984/1986},
+  volumes      = 5,
+  publisher    = {Addison-Wesley},
+  location     = {Reading, Mass.},
+  hyphenation  = {american},
+  sortyear     = {1984-0},
+  sorttitle    = {Computers & Typesetting},
+  indexsorttitle= {Computers & Typesetting},
+  related      = {knuth:ct:a,knuth:ct:b,knuth:ct:c,knuth:ct:d,knuth:ct:e},
+  relatedtype  = {multivolume},
+  annotation   = {A five-volume book cited as a whole and related to its
+                  individual volumes. Note the related and
+                  relatedtype fields},
+}
+
+^D
+---
+nocite: "[@*]"
+references:
+- annote: A five-volume book cited as a whole and related to its
+    individual volumes. Note the related and relatedtype fields
+  author:
+  - family: Knuth
+    given: Donald E.
+  id: "knuth:ct:related"
+  issued: 1984/1986
+  language: en-US
+  number-of-volumes: 5
+  publisher: Addison-Wesley
+  publisher-place: Reading, Mass.
+  title: Computers & typesetting
+  type: book
+---
+
+
+```
diff --git a/test/command/biblatex-knuth-ct.md b/test/command/biblatex-knuth-ct.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-knuth-ct.md
@@ -0,0 +1,66 @@
+```
+% pandoc -f biblatex -t markdown -s
+@comment{
+
+Adapted from biblatex-example.bib
+
+
+Formatted with pandoc and chicago-author-date.csl, 2013-10-23:
+
+(Knuth 1984–1986)
+
+Knuth, Donald E. 1984–1986. *Computers & Typesetting*. 5. Reading,
+Mass.: Addison-Wesley.
+
+
+Formatted with pandoc and apa.csl, 2013-10-23:
+
+(Knuth, 1984–1986)
+
+Knuth, D. E. (1984–1986). *Computers & typesetting* (1-5). Reading,
+Mass.: Addison-Wesley.
+
+
+NOTES:
+
+- citeproc
+	- term "vols." is missing
+
+}
+
+@Book{knuth:ct,
+  author       = {Knuth, Donald E.},
+  title        = {Computers \& Typesetting},
+  date         = {1984/1986},
+  volumes      = 5,
+  publisher    = {Addison-Wesley},
+  location     = {Reading, Mass.},
+  hyphenation  = {american},
+  sortyear     = {1984-0},
+  sorttitle    = {Computers & Typesetting},
+  indexsorttitle= {Computers & Typesetting},
+  annotation   = {A five-volume book cited as a whole. This is a book
+                  entry, note the volumes field},
+}
+
+^D
+---
+nocite: "[@*]"
+references:
+- annote: A five-volume book cited as a whole. This is a book entry,
+    note the volumes field
+  author:
+  - family: Knuth
+    given: Donald E.
+  id: "knuth:ct"
+  issued: 1984/1986
+  language: en-US
+  number-of-volumes: 5
+  publisher: Addison-Wesley
+  publisher-place: Reading, Mass.
+  title: Computers & typesetting
+  type: book
+---
+
+
+```
diff --git a/test/command/biblatex-kowalik.md b/test/command/biblatex-kowalik.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-kowalik.md
@@ -0,0 +1,68 @@
+```
+% pandoc -f biblatex -t markdown -s
+@comment{
+
+Adapted from biblatex-example.bib
+
+
+Formatted with pandoc and chicago-author-date.csl, 2013-10-23:
+
+(Kowalik and Isard 1995)
+
+Kowalik, F., and M. Isard. 1995. “Estimateur d’un défaut de
+fonctionnement d’un modulateur en quadrature et étage de modulation
+l’utilisant.” French patent request.
+
+
+Formatted with pandoc and apa.csl, 2013-10-23:
+
+(Kowalik & Isard, 1995)
+
+Kowalik, F., & Isard, M. (1995, January 11). Estimateur d’un défaut de
+fonctionnement d’un modulateur en quadrature et étage de modulation
+l’utilisant. French patent request.
+
+
+}
+
+@Patent{kowalik,
+  author       = {Kowalik, F. and Isard, M.},
+  title        = {Estimateur d'un d{\'e}faut de fonctionnement d'un modulateur
+                  en quadrature et {\'e}tage de modulation l'utilisant},
+  number       = 9500261,
+  date         = {1995-01-11},
+  type         = {patreqfr},
+  hyphenation  = {french},
+  indextitle   = {Estimateur d'un d{\'e}faut de fonctionnement},
+  annotation   = {This is a patent entry for a French patent request
+                  with a full date. The number is given in the number
+                  field. Note the format of the type and date
+                  fields in the database file. Compare almendro,
+                  laufenberg, and sorace},
+}
+
+^D
+---
+nocite: "[@*]"
+references:
+- annote: This is a patent entry for a French patent request with a full
+    date. The number is given in the number field. Note the format of
+    the type and date fields in the database file. Compare almendro,
+    laufenberg, and sorace
+  author:
+  - family: Kowalik
+    given: F.
+  - family: Isard
+    given: M.
+  genre: French patent request
+  id: kowalik
+  issued: 1995-01-11
+  language: fr-FR
+  number: 9500261
+  title: Estimateur d'un défaut de fonctionnement d'un modulateur en
+    quadrature et étage de modulation l'utilisant
+  type: patent
+---
+
+
+```
diff --git a/test/command/biblatex-kullback-related.md b/test/command/biblatex-kullback-related.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-kullback-related.md
@@ -0,0 +1,62 @@
+```
+% pandoc -f biblatex -t markdown -s
+@comment{
+
+Adapted from biblatex-example.bib
+
+
+Formatted with pandoc and chicago-author-date.csl, 2013-10-23:
+
+(Kullback 1997)
+
+Kullback, Solomon. 1997. *Information Theory and Statistics*. New York:
+Dover Publications.
+
+
+Formatted with pandoc and apa.csl, 2013-10-23:
+
+(Kullback, 1997)
+
+Kullback, S. (1997). *Information theory and statistics*. New York:
+Dover Publications.
+
+
+NOTES:
+
+- related = {kullback}, relatedtype = {origpubin}, -- not possible in CSL
+
+}
+
+@Book{kullback:related,
+  author       = {Kullback, Solomon},
+  title        = {Information Theory and Statistics},
+  year         = 1997,
+  publisher    = {Dover Publications},
+  location     = {New York},
+  hyphenation  = {american},
+  related      = {kullback},
+  relatedtype  = {origpubin},
+  annotation   = {A reprint of the kullback entry. Note the format of
+                  the related and relatedtype fields},
+}
+
+^D
+---
+nocite: "[@*]"
+references:
+- annote: A reprint of the kullback entry. Note the format of the
+    related and relatedtype fields
+  author:
+  - family: Kullback
+    given: Solomon
+  id: "kullback:related"
+  issued: 1997
+  language: en-US
+  publisher: Dover Publications
+  publisher-place: New York
+  title: Information theory and statistics
+  type: book
+---
+
+
+```
diff --git a/test/command/biblatex-kullback-reprint.md b/test/command/biblatex-kullback-reprint.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-kullback-reprint.md
@@ -0,0 +1,71 @@
+```
+% pandoc -f biblatex -t markdown -s
+@comment{
+
+Adapted from biblatex-example.bib
+
+
+Formatted with pandoc and chicago-author-date.csl, 2013-10-23:
+
+(Kullback 1997)
+
+Kullback, Solomon. 1997. *Information Theory and Statistics*. New York:
+Dover Publications.
+
+
+Formatted with pandoc and apa.csl, 2013-10-23:
+
+(Kullback, 1997)
+
+Kullback, S. (1997). *Information theory and statistics*. New York:
+Dover Publications.
+
+
+NOTES:
+
+Formatted with chicago-author-date-TEST-20131018.csl 
+
+(Kullback [1959] 1997)
+
+Kullback, Solomon. (1959) 1997. *Information Theory and Statistics*. New
+York: Dover Publications.
+
+}
+
+@Book{kullback:reprint,
+  author       = {Kullback, Solomon},
+  title        = {Information Theory and Statistics},
+  year         = 1997,
+  publisher    = {Dover Publications},
+  location     = {New York},
+  origyear     = 1959,
+  origpublisher= {John Wiley \& Sons},
+  hyphenation  = {american},
+  annotation   = {A reprint of the kullback entry. Note the format of
+                  origyear and origpublisher. These fields are
+                  not used by the standard bibliography styles},
+}
+
+^D
+---
+nocite: "[@*]"
+references:
+- annote: A reprint of the kullback entry. Note the format of origyear
+    and origpublisher. These fields are not used by the standard
+    bibliography styles
+  author:
+  - family: Kullback
+    given: Solomon
+  id: "kullback:reprint"
+  issued: 1997
+  language: en-US
+  original-date: 1959
+  original-publisher: John Wiley & Sons
+  publisher: Dover Publications
+  publisher-place: New York
+  title: Information theory and statistics
+  type: book
+---
+
+
+```
diff --git a/test/command/biblatex-kullback.md b/test/command/biblatex-kullback.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-kullback.md
@@ -0,0 +1,52 @@
+```
+% pandoc -f biblatex -t markdown -s
+@comment{
+
+Adapted from biblatex-example.bib
+
+
+Formatted with pandoc and chicago-author-date.csl, 2013-10-23:
+
+(Kullback 1959)
+
+Kullback, Solomon. 1959. *Information Theory and Statistics*. New York:
+John Wiley & Sons.
+
+
+Formatted with pandoc and apa.csl, 2013-10-23:
+
+(Kullback, 1959)
+
+Kullback, S. (1959). *Information theory and statistics*. New York: John
+Wiley & Sons.
+
+
+}
+
+@Book{kullback,
+  author       = {Kullback, Solomon},
+  title        = {Information Theory and Statistics},
+  year         = 1959,
+  publisher    = {John Wiley \& Sons},
+  location     = {New York},
+  hyphenation  = {american},
+}
+
+^D
+---
+nocite: "[@*]"
+references:
+- author:
+  - family: Kullback
+    given: Solomon
+  id: kullback
+  issued: 1959
+  language: en-US
+  publisher: John Wiley & Sons
+  publisher-place: New York
+  title: Information theory and statistics
+  type: book
+---
+
+
+```
diff --git a/test/command/biblatex-laufenberg.md b/test/command/biblatex-laufenberg.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-laufenberg.md
@@ -0,0 +1,109 @@
+```
+% pandoc -f biblatex -t markdown -s
+@comment{
+
+Adapted from biblatex-example.bib
+
+
+Formatted with pandoc and chicago-author-date.csl, 2013-10-23:
+
+(Laufenberg et al. 2006)
+
+Laufenberg, Xaver, Dominique Eynius, Helmut Suelzle, Stephan Usbeck,
+Matthias Spaeth, Miriam Neuser-Hoffmann, Christian Myrzik, et al. 2006.
+“Elektrische Einrichtung und Betriebsverfahren.” European patent.
+
+
+Formatted with pandoc and apa.csl, 2013-10-23:
+
+(Laufenberg et al., 2006)
+
+Laufenberg, X., Eynius, D., Suelzle, H., Usbeck, S., Spaeth, M.,
+Neuser-Hoffmann, M., … Ebner, N. (2006, September 13). Elektrische
+Einrichtung und Betriebsverfahren. European patent.
+
+
+NOTES:
+
+- biblio2yaml
+	- Is there any equivalent of "holder" in CSL?
+
+}
+
+@Patent{laufenberg,
+  author       = {Laufenberg, Xaver and Eynius, Dominique and Suelzle, Helmut
+                  and Usbeck, Stephan and Spaeth, Matthias and Neuser-Hoffmann,
+                  Miriam and Myrzik, Christian and Schmid, Manfred and Nietfeld,
+                  Franz and Thiel, Alexander and Braun, Harald and Ebner,
+                  Norbert},
+  title        = {Elektrische Einrichtung und Betriebsverfahren},
+  number       = 1700367,
+  date         = {2006-09-13},
+  holder       = {{Robert Bosch GmbH} and {Daimler Chrysler AG} and {Bayerische
+                  Motoren Werke AG}},
+  type         = {patenteu},
+  hyphenation  = {german},
+  annotation   = {This is a patent entry with a holder field.
+                  Note the format of the type and location
+                  fields in the database file. Compare almendro,
+                  sorace, and kowalik},
+  abstract     = {The invention relates to an electric device comprising a
+                  generator, in particular for use in the vehicle electric
+                  system of a motor vehicle and a controller for controlling the
+                  generator voltage. The device is equipped with a control zone,
+                  in which the voltage is controlled and zones, in which the
+                  torque is controlled. The invention also relates to methods
+                  for operating a device of this type.},
+  file         = {http://v3.espacenet.com/textdoc?IDX=EP1700367},
+}
+
+^D
+---
+nocite: "[@*]"
+references:
+- abstract: The invention relates to an electric device comprising a
+    generator, in particular for use in the vehicle electric system of a
+    motor vehicle and a controller for controlling the generator
+    voltage. The device is equipped with a control zone, in which the
+    voltage is controlled and zones, in which the torque is controlled.
+    The invention also relates to methods for operating a device of this
+    type.
+  annote: This is a patent entry with a holder field. Note the format of
+    the type and location fields in the database file. Compare almendro,
+    sorace, and kowalik
+  author:
+  - family: Laufenberg
+    given: Xaver
+  - family: Eynius
+    given: Dominique
+  - family: Suelzle
+    given: Helmut
+  - family: Usbeck
+    given: Stephan
+  - family: Spaeth
+    given: Matthias
+  - family: Neuser-Hoffmann
+    given: Miriam
+  - family: Myrzik
+    given: Christian
+  - family: Schmid
+    given: Manfred
+  - family: Nietfeld
+    given: Franz
+  - family: Thiel
+    given: Alexander
+  - family: Braun
+    given: Harald
+  - family: Ebner
+    given: Norbert
+  genre: European patent
+  id: laufenberg
+  issued: 2006-09-13
+  language: de-DE
+  number: 1700367
+  title: Elektrische Einrichtung und Betriebsverfahren
+  type: patent
+---
+
+
+```
diff --git a/test/command/biblatex-loh.md b/test/command/biblatex-loh.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-loh.md
@@ -0,0 +1,65 @@
+```
+% pandoc -f biblatex -t markdown -s
+@comment{
+
+Adapted from biblatex-example.bib
+
+
+Formatted with pandoc and chicago-author-date.csl, 2013-10-23:
+
+(Loh 1992)
+
+Loh, Nin C. 1992. “High-resolution Micromachined Interferometric
+Accelerometer.” Master’s thesis, Cambridge, Mass.: Massachusetts
+Institute of Technology.
+
+
+Formatted with pandoc and apa.csl, 2013-10-23:
+
+(Loh, 1992)
+
+Loh, N. C. (1992). *High-resolution micromachined interferometric
+accelerometer* (Master’s thesis). Massachusetts Institute of Technology,
+Cambridge, Mass.
+
+
+NOTES:
+
+- biblio2yaml
+	- At some point, actual localization of "localization keys" will have to be implemented
+
+}
+
+@Thesis{loh,
+  author       = {Loh, Nin C.},
+  title        = {High-Resolution Micromachined Interferometric Accelerometer},
+  type         = {mathesis},
+  institution  = {Massachusetts Institute of Technology},
+  date         = 1992,
+  location     = {Cambridge, Mass.},
+  hyphenation  = {american},
+  annotation   = {This is a typical thesis entry for an MA thesis. Note
+                  the type field in the database file which uses a
+                  localization key},
+}
+^D
+---
+nocite: "[@*]"
+references:
+- annote: This is a typical thesis entry for an MA thesis. Note the type
+    field in the database file which uses a localization key
+  author:
+  - family: Loh
+    given: Nin C.
+  genre: Master's thesis
+  id: loh
+  issued: 1992
+  language: en-US
+  publisher: Massachusetts Institute of Technology
+  publisher-place: Cambridge, Mass.
+  title: High-resolution micromachined interferometric accelerometer
+  type: thesis
+---
+
+
+```
diff --git a/test/command/biblatex-malinowski.md b/test/command/biblatex-malinowski.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-malinowski.md
@@ -0,0 +1,67 @@
+```
+% pandoc -f biblatex -t markdown -s
+@comment{
+
+Adapted from biblatex-example.bib
+
+
+Formatted with pandoc and chicago-author-date.csl, 2013-10-23:
+
+(Malinowski 1972)
+
+Malinowski, Bronisław. 1972. *Argonauts of the Western Pacific: An
+Account of Native Enterprise and Adventure in the Archipelagoes of
+Melanesian New Guinea*. 8th ed. London: Routledge and Kegan Paul.
+
+
+Formatted with pandoc and apa.csl, 2013-10-23:
+
+(Malinowski, 1972)
+
+Malinowski, B. (1972). *Argonauts of the Western Pacific: An account of
+native enterprise and adventure in the Archipelagoes of Melanesian New
+Guinea* (8th ed.). London: Routledge and Kegan Paul.
+
+
+}
+
+@Book{malinowski,
+  author       = {Malinowski, Bronis{\l}aw},
+  title        = {Argonauts of the {Western Pacific}},
+  date         = 1972,
+  edition      = 8,
+  publisher    = {Routledge {and} Kegan Paul},
+  location     = {London},
+  hyphenation  = {british},
+  subtitle     = {An account of native enterprise and adventure in the
+                  {Archipelagoes of Melanesian New Guinea}},
+  shorttitle   = {Argonauts},
+  annotation   = {This is a book entry. Note the format of the
+                  publisher and edition fields as well as the
+                  subtitle field},
+}
+
+^D
+---
+nocite: "[@*]"
+references:
+- annote: This is a book entry. Note the format of the publisher and
+    edition fields as well as the subtitle field
+  author:
+  - family: Malinowski
+    given: Bronisław
+  edition: 8
+  id: malinowski
+  issued: 1972
+  language: en-GB
+  publisher: Routledge and Kegan Paul
+  publisher-place: London
+  title: "Argonauts of the Western Pacific: An account of native
+    enterprise and adventure in the [Archipelagoes of Melanesian New
+    Guinea]{.nocase}"
+  title-short: Argonauts
+  type: book
+---
+
+
+```
diff --git a/test/command/biblatex-manual.md b/test/command/biblatex-manual.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-manual.md
@@ -0,0 +1,51 @@
+```
+% pandoc -f biblatex -t markdown -s
+@comment{adapted from http://mirrors.ctan.org/macros/latex/contrib/biblatex/doc/examples/biblatex-examples.bib}
+
+@Manual{cms,
+  title        = {The {Chicago} Manual of Style},
+  date         = 2003,
+  subtitle     = {The Essential Guide for Writers, Editors, and Publishers},
+  edition      = 15,
+  publisher    = {University of Chicago Press},
+  location     = {Chicago, Ill.},
+  isbn         = {0-226-10403-6},
+  label        = {CMS},
+  hyphenation  = {american},
+  sorttitle    = {Chicago Manual of Style},
+  indextitle   = {Chicago Manual of Style, The},
+  shorttitle   = {Chicago Manual of Style},
+  annotation   = {This is a manual entry without an author or
+                  editor. Note the label field in the database
+                  file which is provided for author-year citation styles. Also
+                  note the sorttitle and indextitle fields. By
+                  default, all entries without an author or
+                  editor are alphabetized by title but we want
+                  this entry to be alphabetized under \enquote*{C} rather than
+                  \enquote*{T}. There's also an isbn field},
+}
+^D
+---
+nocite: "[@*]"
+references:
+- annote: This is a manual entry without an author or editor. Note the
+    label field in the database file which is provided for author-year
+    citation styles. Also note the sorttitle and indextitle fields. By
+    default, all entries without an author or editor are alphabetized by
+    title but we want this entry to be alphabetized under 'C' rather
+    than 'T'. There's also an isbn field
+  edition: 15
+  id: cms
+  isbn: 0-226-10403-6
+  issued: 2003
+  language: en-US
+  publisher: University of Chicago Press
+  publisher-place: Chicago, Ill.
+  title: "The Chicago manual of style: The essential guide for writers,
+    editors, and publishers"
+  title-short: Chicago manual of style
+  type: book
+---
+
+
+```
diff --git a/test/command/biblatex-markey.md b/test/command/biblatex-markey.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-markey.md
@@ -0,0 +1,65 @@
+```
+% pandoc -f biblatex -t markdown -s
+@comment{
+
+Adapted from biblatex-example.bib
+
+
+Formatted with pandoc and chicago-author-date.csl, 2013-10-23:
+
+(Markey 2005)
+
+Markey, Nicolas. 2005. “Tame the BeaST: The B to X of BibTeX” (version
+1.3). October 16.
+<http://tug.ctan.org/tex-archive/info/bibtex/tamethebeast/ttb_en.pdf>.
+
+
+Formatted with pandoc and apa.csl, 2013-10-23:
+
+(Markey, 2005)
+
+Markey, N. (2005, October 16). Tame the BeaST: The B to X of BibTeX.
+Retrieved October 01, 2006, from
+<http://tug.ctan.org/tex-archive/info/bibtex/tamethebeast/ttb_en.pdf>
+
+
+}
+
+@Online{markey,
+  author       = {Markey, Nicolas},
+  title        = {Tame the {BeaST}},
+  date         = {2005-10-16},
+  url          =
+                  {http://tug.ctan.org/tex-archive/info/bibtex/tamethebeast/ttb_en.pdf},
+  subtitle     = {The {B} to {X} of {BibTeX}},
+  version      = {1.3},
+  urldate      = {2006-10-01},
+  hyphenation  = {american},
+  sorttitle    = {Tame the Beast},
+  annotation   = {An online entry for a tutorial. Note the format of
+                  the date field (yyyy-mm-dd) in the database
+                  file.},
+}
+
+^D
+---
+nocite: "[@*]"
+references:
+- accessed: 2006-10-01
+  annote: An online entry for a tutorial. Note the format of the date
+    field (yyyy-mm-dd) in the database file.
+  author:
+  - family: Markey
+    given: Nicolas
+  id: markey
+  issued: 2005-10-16
+  language: en-US
+  title: "Tame the BeaST: The B to X of BibTeX"
+  title-short: Tame the BeaST
+  type: webpage
+  url: "http://tug.ctan.org/tex-archive/info/bibtex/tamethebeast/ttb_en.pdf"
+  version: 1.3
+---
+
+
+```
diff --git a/test/command/biblatex-maron.md b/test/command/biblatex-maron.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-maron.md
@@ -0,0 +1,70 @@
+```
+% pandoc -f biblatex -t markdown -s
+@comment{
+
+Adapted from biblatex-example.bib
+
+
+Formatted with pandoc and chicago-author-date.csl, 2013-10-23:
+
+(Maron 2000)
+
+Maron, Monika. 2000. *Animal Triste*. Translated by Brigitte Goldstein.
+Lincoln: University of Nebraska Press.
+
+
+Formatted with pandoc and apa.csl, 2013-10-23:
+
+(Maron, 2000)
+
+Maron, M. (2000). *Animal triste*. (B. Goldstein, Trans.). Lincoln:
+University of Nebraska Press.
+
+
+NOTES:
+
+-   origlanguage concatenated with translator, e.g. “translated from the German by …” not possible in CSL
+
+}
+
+@Book{maron,
+  author       = {Maron, Monika},
+  title        = {Animal Triste},
+  date         = 2000,
+  translator   = {Brigitte Goldstein},
+  origlanguage = {german},
+  publisher    = {University of Nebraska Press},
+  location     = {Lincoln},
+  hyphenation  = {american},
+  shorttitle   = {Animal Triste},
+  annotation   = {An English translation of a German novel with a French title.
+                  In other words: a book entry with a
+                  translator field.  Note the origlanguage
+                  field which is concatenated with the translator},
+}
+
+^D
+---
+nocite: "[@*]"
+references:
+- annote: "An English translation of a German novel with a French title.
+    In other words: a book entry with a translator field. Note the
+    origlanguage field which is concatenated with the translator"
+  author:
+  - family: Maron
+    given: Monika
+  id: maron
+  issued: 2000
+  language: en-US
+  publisher: University of Nebraska Press
+  publisher-place: Lincoln
+  title: Animal triste
+  title-short: Animal triste
+  translator:
+  - family: Goldstein
+    given: Brigitte
+  type: book
+---
+
+
+```
diff --git a/test/command/biblatex-massa.md b/test/command/biblatex-massa.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-massa.md
@@ -0,0 +1,56 @@
+```
+% pandoc -f biblatex -t markdown -s
+@comment{
+
+Adapted from biblatex-example.bib
+
+
+Formatted with pandoc and chicago-author-date.csl, 2013-10-23:
+
+(Massa 2004)
+
+Massa, Werner. 2004. *Crystal Structure Determination*. 2nd ed. Berlin:
+Spinger.
+
+
+Formatted with pandoc and apa.csl, 2013-10-23:
+
+(Massa, 2004)
+
+Massa, W. (2004). *Crystal structure determination* (2nd ed.). Berlin:
+Spinger.
+
+
+}
+
+@Book{massa,
+  author       = {Werner Massa},
+  title        = {Crystal structure determination},
+  date         = 2004,
+  edition      = 2,
+  publisher    = {Spinger},
+  location     = {Berlin},
+  hyphenation  = {british},
+  annotation   = {A book entry with an edition field},
+}
+
+^D
+---
+nocite: "[@*]"
+references:
+- annote: A book entry with an edition field
+  author:
+  - family: Massa
+    given: Werner
+  edition: 2
+  id: massa
+  issued: 2004
+  language: en-GB
+  publisher: Spinger
+  publisher-place: Berlin
+  title: Crystal structure determination
+  type: book
+---
+
+
+```
diff --git a/test/command/biblatex-moore-related.md b/test/command/biblatex-moore-related.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-moore-related.md
@@ -0,0 +1,66 @@
+```
+% pandoc -f biblatex -t markdown -s
+@comment{
+
+Adapted from biblatex-example.bib
+
+
+Formatted with pandoc and chicago-author-date.csl, 2013-10-23:
+
+(Moore 1998)
+
+Moore, Gordon E. 1998. “Cramming More Components onto Integrated
+Circuits.” *Proceedings of the IEEE* 86 (1): 82–85.
+
+
+Formatted with pandoc and apa.csl, 2013-10-23:
+
+(Moore, 1998)
+
+Moore, G. E. (1998). Cramming more components onto integrated circuits.
+*Proceedings of the IEEE*, *86*(1), 82–85.
+
+
+NOTES:
+
+- "related = {moore}, relatedtype = {reprintfrom}," – no equivalent implemented in CSL
+
+}
+
+@Article{moore:related,
+  author       = {Moore, Gordon E.},
+  title        = {Cramming more components onto integrated circuits},
+  journaltitle = {Proceedings of the {IEEE}},
+  year         = 1998,
+  volume       = 86,
+  number       = 1,
+  pages        = {82-85},
+  hyphenation  = {american},
+  related      = {moore},
+  relatedtype  = {reprintfrom},
+  annotation   = {A reprint of Moore's law. Note the related and
+                  relatedtype fields},
+}
+
+^D
+---
+nocite: "[@*]"
+references:
+- annote: A reprint of Moore's law. Note the related and relatedtype
+    fields
+  author:
+  - family: Moore
+    given: Gordon E.
+  container-title: Proceedings of the IEEE
+  id: "moore:related"
+  issue: 1
+  issued: 1998
+  language: en-US
+  page: 82-85
+  title: Cramming more components onto integrated circuits
+  type: article-journal
+  volume: 86
+---
+
+
+```
diff --git a/test/command/biblatex-moore.md b/test/command/biblatex-moore.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-moore.md
@@ -0,0 +1,56 @@
+```
+% pandoc -f biblatex -t markdown -s
+@comment{
+
+Adapted from biblatex-example.bib
+
+
+Formatted with pandoc and chicago-author-date.csl, 2013-10-23:
+
+(Moore 1965)
+
+Moore, Gordon E. 1965. “Cramming More Components onto Integrated
+Circuits.” *Electronics* 38 (8): 114–117.
+
+
+Formatted with pandoc and apa.csl, 2013-10-23:
+
+(Moore, 1965)
+
+Moore, G. E. (1965). Cramming more components onto integrated circuits.
+*Electronics*, *38*(8), 114–117.
+
+
+}
+
+@Article{moore,
+  author       = {Moore, Gordon E.},
+  title        = {Cramming more components onto integrated circuits},
+  journaltitle = {Electronics},
+  year         = 1965,
+  volume       = 38,
+  number       = 8,
+  pages        = {114-117},
+  hyphenation  = {american},
+}
+
+^D
+---
+nocite: "[@*]"
+references:
+- author:
+  - family: Moore
+    given: Gordon E.
+  container-title: Electronics
+  id: moore
+  issue: 8
+  issued: 1965
+  language: en-US
+  page: 114-117
+  title: Cramming more components onto integrated circuits
+  type: article-journal
+  volume: 38
+---
+
+
+```
diff --git a/test/command/biblatex-moraux.md b/test/command/biblatex-moraux.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-moraux.md
@@ -0,0 +1,94 @@
+```
+% pandoc -f biblatex -t markdown -s
+@comment{
+
+Adapted from biblatex-example.bib
+
+
+Formatted with pandoc and chicago-author-date.csl, 2013-10-23:
+
+(Moraux 1979)
+
+Moraux, Paul. 1979. “Le *De Anima* dans la tradition grècque: Quelques
+aspects de l’interpretation du traité, de Theophraste à Themistius.” In
+*Aristotle on Mind and the Senses. Proceedings of the Seventh Symposium
+Aristotelicum*, edited by G. E. R. Lloyd and G. E. L. Owen, 281–324.
+Cambridge: Cambridge University Press.
+
+
+Formatted with pandoc and apa.csl, 2013-10-23:
+
+(Moraux, 1979)
+
+Moraux, P. (1979). Le *De Anima* dans la tradition grècque: Quelques
+aspects de l’interpretation du traité, de Theophraste à Themistius. In
+G. E. R. Lloyd & G. E. L. Owen (eds.), *Aristotle on Mind and the
+Senses. Proceedings of the Seventh Symposium Aristotelicum* (pp.
+281–324). Cambridge: Cambridge University Press.
+
+
+NOTES:
+
+- Since case (conversion) can only be specified per entry, not per field, for apa.csl the case of container-title would have to be adjusted manually.
+
+}
+
+@string{ cup     = {Cambridge University Press} }
+
+@InProceedings{moraux,
+  author       = {Moraux, Paul},
+  editor       = {Lloyd, G. E. R. and Owen, G. E. L.},
+  title        = {Le \emph{De Anima} dans la tradition gr{\`e}cque},
+  date         = 1979,
+  booktitle    = {Aristotle on Mind and the Senses},
+  subtitle     = {Quelques aspects de l'interpretation du trait{\'e}, de
+                  Theophraste {\`a} Themistius},
+  booktitleaddon= {Proceedings of the Seventh Symposium Aristotelicum},
+  eventdate    = 1975,
+  publisher    = cup,
+  location     = {Cambridge},
+  pages        = {281-324},
+  keywords     = {secondary},
+  hyphenation  = {french},
+  indexsorttitle= {De Anima dans la tradition grecque},
+  indextitle   = {\emph{De Anima} dans la tradition gr{\`e}cque, Le},
+  shorttitle   = {\emph{De Anima} dans la tradition gr{\`e}cque},
+  annotation   = {This is a typical inproceedings entry. Note the
+                  booksubtitle, shorttitle,
+                  indextitle, and indexsorttitle fields. Also
+                  note the eventdate field.},
+}
+
+^D
+---
+nocite: "[@*]"
+references:
+- annote: This is a typical inproceedings entry. Note the booksubtitle,
+    shorttitle, indextitle, and indexsorttitle fields. Also note the
+    eventdate field.
+  author:
+  - family: Moraux
+    given: Paul
+  container-title: Aristotle on Mind and the Senses. Proceedings of the
+    Seventh Symposium Aristotelicum
+  editor:
+  - family: Lloyd
+    given: G. E. R.
+  - family: Owen
+    given: G. E. L.
+  event-date: 1975
+  id: moraux
+  issued: 1979
+  keyword: secondary
+  language: fr-FR
+  page: 281-324
+  publisher: Cambridge University Press
+  publisher-place: Cambridge
+  title: "Le *De Anima* dans la tradition grècque: Quelques aspects de
+    l'interpretation du traité, de Theophraste à Themistius"
+  title-short: "*De Anima* dans la tradition grècque"
+  type: paper-conference
+---
+
+
+```
diff --git a/test/command/biblatex-murray.md b/test/command/biblatex-murray.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-murray.md
@@ -0,0 +1,105 @@
+```
+% pandoc -f biblatex -t markdown -s
+@comment{
+
+Adapted from biblatex-example.bib
+
+
+Formatted with pandoc and chicago-author-date.csl, 2013-10-23:
+
+(Hostetler et al. 1998)
+
+Hostetler, Michael J., Julia E. Wingate, Chuan-Jian Zhong, Jay E.
+Harris, Richard W. Vachet, Michael R. Clark, J. David Londono, et al.
+1998. “Alkanethiolate Gold Cluster Molecules with Core Diameters from
+1.5 to 5.2 nm: Core and Monolayer Properties as a Function of Core
+Size.” *Langmuir* 14 (1): 17–30.
+
+
+Formatted with pandoc and apa.csl, 2013-10-23:
+
+(Hostetler et al., 1998)
+
+Hostetler, M. J., Wingate, J. E., Zhong, C.-J., Harris, J. E., Vachet,
+R. W., Clark, M. R., … Murray, R. W. (1998). Alkanethiolate gold cluster
+molecules with core diameters from 1.5 to 5.2 nm: Core and monolayer
+properties as a function of core size. *Langmuir*, *14*(1), 17–30.
+
+
+}
+
+@Article{murray,
+  author       = {Hostetler, Michael J. and Wingate, Julia E. and Zhong,
+                  Chuan-Jian and Harris, Jay E. and Vachet, Richard W. and
+                  Clark, Michael R.  and Londono, J. David and Green, Stephen
+                  J. and Stokes, Jennifer J.  and Wignall, George D. and Glish,
+                  Gary L. and Porter, Marc D.  and Evans, Neal D. and Murray,
+                  Royce W.},
+  title        = {Alkanethiolate gold cluster molecules with core diameters from
+                  1.5 to 5.2~{nm}},
+  journaltitle = {Langmuir},
+  date         = 1998,
+  subtitle     = {Core and monolayer properties as a function of core size},
+  volume       = 14,
+  number       = 1,
+  pages        = {17-30},
+  hyphenation  = {american},
+  indextitle   = {Alkanethiolate gold cluster molecules},
+  shorttitle   = {Alkanethiolate gold cluster molecules},
+  annotation   = {An article entry with \arabic{author} authors. By
+                  default, long author and editor lists are automatically
+                  truncated. This is configurable},
+}
+
+^D
+---
+nocite: "[@*]"
+references:
+- annote: An article entry with `\arabic{author}`{=latex} authors. By
+    default, long author and editor lists are automatically truncated.
+    This is configurable
+  author:
+  - family: Hostetler
+    given: Michael J.
+  - family: Wingate
+    given: Julia E.
+  - family: Zhong
+    given: Chuan-Jian
+  - family: Harris
+    given: Jay E.
+  - family: Vachet
+    given: Richard W.
+  - family: Clark
+    given: Michael R.
+  - family: Londono
+    given: J. David
+  - family: Green
+    given: Stephen J.
+  - family: Stokes
+    given: Jennifer J.
+  - family: Wignall
+    given: George D.
+  - family: Glish
+    given: Gary L.
+  - family: Porter
+    given: Marc D.
+  - family: Evans
+    given: Neal D.
+  - family: Murray
+    given: Royce W.
+  container-title: Langmuir
+  id: murray
+  issue: 1
+  issued: 1998
+  language: en-US
+  page: 17-30
+  title: "Alkanethiolate gold cluster molecules with core diameters from
+    1.5 to 5.2 [nm]{.nocase}: Core and monolayer properties as a
+    function of core size"
+  title-short: Alkanethiolate gold cluster molecules
+  type: article-journal
+  volume: 14
+---
+
+
+```
diff --git a/test/command/biblatex-nietzsche-historie.md b/test/command/biblatex-nietzsche-historie.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-nietzsche-historie.md
@@ -0,0 +1,100 @@
+```
+% pandoc -f biblatex -t markdown -s
+@comment{
+
+Adapted from biblatex-example.bib
+
+Formatted with pandoc and chicago-author-date.csl, 2013-10-23:
+
+(Nietzsche 1988)
+
+Nietzsche, Friedrich. 1988. “Unzeitgemässe Betrachtungen. Zweites Stück:
+Vom Nutzen und Nachtheil der Historie für das Leben.” In *Sämtliche
+Werke: Kritische Studienausgabe*, by Friedrich Nietzsche, edited by
+Giorgio Colli and Mazzino Montinari, 1:243–334. München; Berlin; New
+York: Deutscher Taschenbuch-Verlag; Walter de Gruyter.
+
+
+Formatted with pandoc and apa.csl, 2013-10-23:
+
+(Nietzsche, 1988)
+
+Nietzsche, F. (1988). Unzeitgemässe Betrachtungen. Zweites Stück: Vom
+Nutzen und Nachtheil der Historie für das Leben. In G. Colli & M.
+Montinari (eds.), *Sämtliche Werke: Kritische Studienausgabe* (Vol. 1,
+pp. 243–334). München; Berlin; New York: Deutscher Taschenbuch-Verlag;
+Walter de Gruyter.
+
+
+}
+
+@string{ dtv     = {Deutscher Taschenbuch-Verlag} }
+
+@InBook{nietzsche:historie,
+  title        = {Unzeitgem{\"a}sse Betrachtungen. Zweites St{\"u}ck},
+  date         = 1988,
+  author       = {Nietzsche, Friedrich},
+  booktitle    = {Die Geburt der Trag{\"o}die. Unzeitgem{\"a}{\ss}e
+                  Betrachtungen I--IV. Nachgelassene Schriften 1870--1973},
+  bookauthor   = {Nietzsche, Friedrich},
+  editor       = {Colli, Giorgio and Montinari, Mazzino},
+  subtitle     = {Vom Nutzen und Nachtheil der Historie f{\"u}r das Leben},
+  maintitle    = {S{\"a}mtliche Werke},
+  mainsubtitle = {Kritische Studienausgabe},
+  volume       = 1,
+  publisher    = dtv # { and Walter de Gruyter},
+  location     = {M{\"u}nchen and Berlin and New York},
+  pages        = {243-334},
+  hyphenation  = {german},
+  sortyear     = {1988-2},
+  sorttitle    = {Werke-01-243},
+  indexsorttitle= {Vom Nutzen und Nachtheil der Historie fur das Leben},
+  indextitle   = {Vom Nutzen und Nachtheil der Historie f{\"u}r das Leben},
+  shorttitle   = {Vom Nutzen und Nachtheil der Historie},
+  annotation   = {A single essay from the critical edition of Nietzsche's works.
+                  This inbook entry explicitly refers to an essay found
+                  in the first volume. Note the title,
+                  booktitle, and maintitle fields. Also note
+                  the sorttitle and sortyear fields. We want
+                  this entry to be listed after the entry referring to the
+                  entire first volume},
+}
+
+^D
+---
+nocite: "[@*]"
+references:
+- annote: A single essay from the critical edition of Nietzsche's works.
+    This inbook entry explicitly refers to an essay found in the first
+    volume. Note the title, booktitle, and maintitle fields. Also note
+    the sorttitle and sortyear fields. We want this entry to be listed
+    after the entry referring to the entire first volume
+  author:
+  - family: Nietzsche
+    given: Friedrich
+  container-author:
+  - family: Nietzsche
+    given: Friedrich
+  container-title: "Sämtliche Werke: Kritische Studienausgabe"
+  editor:
+  - family: Colli
+    given: Giorgio
+  - family: Montinari
+    given: Mazzino
+  id: "nietzsche:historie"
+  issued: 1988
+  language: de-DE
+  page: 243-334
+  publisher: Deutscher Taschenbuch-Verlag; Walter de Gruyter
+  publisher-place: München; Berlin; New York
+  title: "Unzeitgemässe Betrachtungen. Zweites Stück: Vom Nutzen und
+    Nachtheil der Historie für das Leben"
+  title-short: Vom Nutzen und Nachtheil der Historie
+  type: chapter
+  volume: 1
+  volume-title: Die Geburt der Tragödie. Unzeitgemäße Betrachtungen
+    I--IV. Nachgelassene Schriften 1870--1973
+---
+
+
+```
diff --git a/test/command/biblatex-nietzsche-ksa.md b/test/command/biblatex-nietzsche-ksa.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-nietzsche-ksa.md
@@ -0,0 +1,89 @@
+```
+% pandoc -f biblatex -t markdown -s
+@comment{
+
+Adapted from biblatex-example.bib
+
+Formatted with pandoc and chicago-author-date.csl, 2013-10-23:
+
+(Nietzsche 1988)
+
+Nietzsche, Friedrich. 1988. *Sämtliche Werke: Kritische Studienausgabe*.
+Edited by Giorgio Colli and Mazzino Montinari. 2nd ed. 15. München;
+Berlin; New York: Deutscher Taschenbuch-Verlag; Walter de Gruyter.
+
+
+Formatted with pandoc and apa.csl, 2013-10-23:
+
+(Nietzsche, 1988)
+
+Nietzsche, F. (1988). *Sämtliche Werke: Kritische Studienausgabe*. (G.
+Colli & M. Montinari, eds.) (2nd ed., 1-15). München; Berlin; New York:
+Deutscher Taschenbuch-Verlag; Walter de Gruyter.
+
+
+NOTES:
+
+- biblio2yaml
+	- term "vols." missing
+
+}
+
+@string{ dtv     = {Deutscher Taschenbuch-Verlag} }
+
+@Book{nietzsche:ksa,
+  author       = {Nietzsche, Friedrich},
+  title        = {S{\"a}mtliche Werke},
+  date         = 1988,
+  editor       = {Colli, Giorgio and Montinari, Mazzino},
+  edition      = 2,
+  volumes      = 15,
+  publisher    = dtv # { and Walter de Gruyter},
+  location     = {M{\"u}nchen and Berlin and New York},
+  hyphenation  = {german},
+  sortyear     = {1988-0},
+  sorttitle    = {Werke-00-000},
+  indexsorttitle= {Samtliche Werke},
+  subtitle     = {Kritische Studienausgabe},
+  annotation   = {The critical edition of Nietzsche's works. This is a
+                  book entry referring to a 15-volume work as a
+                  whole. Note the volumes field and the format of the
+                  publisher and location fields in the
+                  database file. Also note the sorttitle and
+                  sortyear fields which are used to fine-tune the
+                  sorting order of the bibliography. We want this item listed
+                  first in the bibliography},
+}
+
+^D
+---
+nocite: "[@*]"
+references:
+- annote: The critical edition of Nietzsche's works. This is a book
+    entry referring to a 15-volume work as a whole. Note the volumes
+    field and the format of the publisher and location fields in the
+    database file. Also note the sorttitle and sortyear fields which are
+    used to fine-tune the sorting order of the bibliography. We want
+    this item listed first in the bibliography
+  author:
+  - family: Nietzsche
+    given: Friedrich
+  edition: 2
+  editor:
+  - family: Colli
+    given: Giorgio
+  - family: Montinari
+    given: Mazzino
+  id: "nietzsche:ksa"
+  issued: 1988
+  language: de-DE
+  number-of-volumes: 15
+  publisher: Deutscher Taschenbuch-Verlag; Walter de Gruyter
+  publisher-place: München; Berlin; New York
+  title: "Sämtliche Werke: Kritische Studienausgabe"
+  title-short: Sämtliche Werke
+  type: book
+---
+
+
+```
diff --git a/test/command/biblatex-nietzsche-ksa1.md b/test/command/biblatex-nietzsche-ksa1.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-nietzsche-ksa1.md
@@ -0,0 +1,95 @@
+```
+% pandoc -f biblatex -t markdown -s
+@comment{
+
+Adapted from biblatex-example.bib
+
+
+Formatted with pandoc and chicago-author-date.csl, 2015-03-08:
+
+(Nietzsche 1988)
+
+Nietzsche, Friedrich. 1988. *Sämtliche Werke: Kritische Studienausgabe*.
+Edited by Giorgio Colli and Mazzino Montinari. 2nd ed. Vol. 1. München;
+Berlin; New York: Deutscher Taschenbuch-Verlag; Walter de Gruyter.
+
+
+Formatted with pandoc and apa.csl, 2015-03-08:
+
+(Nietzsche, 1988)
+
+Nietzsche, F. (1988). *Sämtliche Werke: Kritische Studienausgabe*. (G.
+Colli & M. Montinari, eds., F. Nietzsche) (2nd ed., Vol. 1). München;
+Berlin; New York: Deutscher Taschenbuch-Verlag; Walter de Gruyter.
+
+
+NOTES:
+
+- volume-title currently not implemented by chicago-author-date.csl and apa.csl.
+
+}
+
+@string{ dtv     = {Deutscher Taschenbuch-Verlag} }
+
+@Book{nietzsche:ksa1,
+  author       = {Nietzsche, Friedrich},
+  title        = {Die Geburt der Trag{\"o}die. Unzeitgem{\"a}{\ss}e
+                  Betrachtungen I--IV. Nachgelassene Schriften 1870--1973},
+  date         = 1988,
+  editor       = {Colli, Giorgio and Montinari, Mazzino},
+  maintitle    = {S{\"a}mtliche Werke},
+  mainsubtitle = {Kritische Studienausgabe},
+  volume       = 1,
+  edition      = 2,
+  publisher    = dtv # { and Walter de Gruyter},
+  location     = {M{\"u}nchen and Berlin and New York},
+  hyphenation  = {german},
+  sortyear     = {1988-1},
+  sorttitle    = {Werke-01-000},
+  indexsorttitle= {Samtliche Werke I},
+  bookauthor   = {Nietzsche, Friedrich},
+  indextitle   = {S{\"a}mtliche Werke I},
+  shorttitle   = {S{\"a}mtliche Werke I},
+  annotation   = {A single volume from the critical edition of Nietzsche's
+                  works. This book entry explicitly refers to the first
+                  volume only. Note the title and maintitle
+                  fields. Also note the sorttitle and sortyear
+                  fields. We want this entry to be listed after the entry
+                  referring to the entire edition},
+}
+
+^D
+---
+nocite: "[@*]"
+references:
+- annote: A single volume from the critical edition of Nietzsche's
+    works. This book entry explicitly refers to the first volume only.
+    Note the title and maintitle fields. Also note the sorttitle and
+    sortyear fields. We want this entry to be listed after the entry
+    referring to the entire edition
+  author:
+  - family: Nietzsche
+    given: Friedrich
+  container-author:
+  - family: Nietzsche
+    given: Friedrich
+  edition: 2
+  editor:
+  - family: Colli
+    given: Giorgio
+  - family: Montinari
+    given: Mazzino
+  id: "nietzsche:ksa1"
+  issued: 1988
+  language: de-DE
+  publisher: Deutscher Taschenbuch-Verlag; Walter de Gruyter
+  publisher-place: München; Berlin; New York
+  title: "Sämtliche Werke: Kritische Studienausgabe"
+  type: book
+  volume: 1
+  volume-title: Die Geburt der Tragödie. Unzeitgemäße Betrachtungen
+    I--IV. Nachgelassene Schriften 1870--1973
+---
+
+
+```
diff --git a/test/command/biblatex-online.md b/test/command/biblatex-online.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-online.md
@@ -0,0 +1,64 @@
+```
+% pandoc -f biblatex -t markdown -s
+@comment{adapted from http://mirrors.ctan.org/macros/latex/contrib/biblatex/doc/examples/biblatex-examples.bib}
+
+@online{markey,
+	Annotation = {An online entry for a tutorial. Note the format of the date field (yyyy-mm-dd) in the database file.},
+	Author = {Markey, Nicolas},
+	Date = {2005-10-16},
+	Hyphenation = {american},
+	Sorttitle = {Tame the Beast},
+	Subtitle = {The {B} to {X} of {BibTeX}},
+	Title = {Tame the {BeaST}},
+	Url = {http://tug.ctan.org/tex-archive/info/bibtex/tamethebeast/ttb_en.pdf},
+	Urldate = {2006-10-01},
+	Version = {1.3},
+}
+
+@online{CTAN,
+	Annotation = {This is an online entry. The \textsc{url}, which is given in the url field, is transformed into a clickable link if hyperref support has been enabled. Note the format of the urldate field (yyyy-mm-dd) in the database file. Also note the label field which may be used as a fallback by citation styles which need an author and\slash or a year},
+	Date = 2006,
+	Hyphenation = {american},
+	Label = {CTAN},
+	Subtitle = {The {Comprehensive TeX Archive Network}},
+	Title = {{CTAN}},
+	Url = {http://www.ctan.org},
+	Urldate = {2006-10-01},
+}
+
+^D
+---
+nocite: "[@*]"
+references:
+- accessed: 2006-10-01
+  annote: An online entry for a tutorial. Note the format of the date
+    field (yyyy-mm-dd) in the database file.
+  author:
+  - family: Markey
+    given: Nicolas
+  id: markey
+  issued: 2005-10-16
+  language: en-US
+  title: "Tame the BeaST: The B to X of BibTeX"
+  title-short: Tame the BeaST
+  type: webpage
+  url: "http://tug.ctan.org/tex-archive/info/bibtex/tamethebeast/ttb_en.pdf"
+  version: 1.3
+- accessed: 2006-10-01
+  annote: This is an online entry. The [url]{.smallcaps}, which is given
+    in the url field, is transformed into a clickable link if hyperref
+    support has been enabled. Note the format of the urldate field
+    (yyyy-mm-dd) in the database file. Also note the label field which
+    may be used as a fallback by citation styles which need an author
+    and/or a year
+  id: CTAN
+  issued: 2006
+  language: en-US
+  title: "CTAN: The Comprehensive TeX Archive Network"
+  title-short: CTAN
+  type: webpage
+  url: "http://www.ctan.org"
+---
+
+
+```
diff --git a/test/command/biblatex-options-url-false-doi-false.md b/test/command/biblatex-options-url-false-doi-false.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-options-url-false-doi-false.md
@@ -0,0 +1,57 @@
+```
+% pandoc -f biblatex -t markdown -s
+@comment{
+
+Entry contains url and doi fields; these should be discarded since the
+options field specifies url=false, doi=false.
+
+Exception: As in standard biblatex, in online entries url should never be
+discarded, even if options contains url=false.
+
+}
+
+@article{item1,
+    Author = {Author, Andy},
+    Date = {2012},
+    Doi = {1234/5678.90},
+    Journal = {Journal},
+    Options = {url=false, doi=false},
+    Title = {Title, Any Entry Type Except online},
+    Url = {http://foo.bar}
+}
+
+@online{item2,
+    Author = {Author, Andy},
+    Date = {2012},
+    Doi = {1234/5678.90},
+    Journal = {Journal},
+    Options = {url=false, doi=false},
+    Title = {Title, Entry Type online},
+    Url = {http://foo.bar}
+}
+
+^D
+---
+nocite: "[@*]"
+references:
+- author:
+  - family: Author
+    given: Andy
+  container-title: Journal
+  id: item1
+  issued: 2012
+  title: Title, any entry type except online
+  type: article-journal
+- author:
+  - family: Author
+    given: Andy
+  container-title: Journal
+  id: item2
+  issued: 2012
+  title: Title, entry type online
+  type: webpage
+  url: "http://foo.bar"
+---
+
+
+```
diff --git a/test/command/biblatex-padhye.md b/test/command/biblatex-padhye.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-padhye.md
@@ -0,0 +1,117 @@
+```
+% pandoc -f biblatex -t markdown -s
+@comment{
+
+Adapted from biblatex-example.bib
+
+
+Formatted with pandoc and chicago-author-date.csl, 2013-10-23:
+
+(Padhye, Firoiu, and Towsley 1999)
+
+Padhye, Jitendra, Victor Firoiu, and Don Towsley. 1999. “A Stochastic
+Model of TCP Reno Congestion Avoidance and Control.” Technical report
+99-02. Amherst, Mass.: University of Massachusetts.
+
+
+Formatted with pandoc and apa.csl, 2013-10-23:
+
+(Padhye, Firoiu, & Towsley, 1999)
+
+Padhye, J., Firoiu, V., & Towsley, D. (1999). *A stochastic model of TCP
+Reno congestion avoidance and control* (technical report No. 99-02).
+Amherst, Mass.: University of Massachusetts.
+
+}
+
+@Report{padhye,
+  author       = {Padhye, Jitendra and Firoiu, Victor and Towsley, Don},
+  title        = {A Stochastic Model of {TCP Reno} Congestion Avoidance and
+                  Control},
+  type         = {techreport},
+  institution  = {University of Massachusetts},
+  date         = 1999,
+  number       = {99-02},
+  location     = {Amherst, Mass.},
+  hyphenation  = {american},
+  sorttitle    = {A Stochastic Model of TCP Reno Congestion Avoidance and
+                  Control},
+  indextitle   = {Stochastic Model of {TCP Reno} Congestion Avoidance and Control,
+                  A},
+  annotation   = {This is a report entry for a technical report. Note
+                  the format of the type field in the database file
+                  which uses a localization key. The number of the report is
+                  given in the number field. Also note the
+                  sorttitle and indextitle fields},
+  abstract     = {The steady state performance of a bulk transfer TCP flow
+                  (i.e., a flow with a large amount of data to send, such as FTP
+                  transfers) may be characterized by three quantities. The first
+                  is the send rate, which is the amount of data sent by the
+                  sender in unit time. The second is the throughput, which is
+                  the amount of data received by the receiver in unit time. Note
+                  that the throughput will always be less than or equal to the
+                  send rate due to losses. Finally, the number of non-duplicate
+                  packets received by the receiver in unit time gives us the
+                  goodput of the connection. The goodput is always less than or
+                  equal to the throughput, since the receiver may receive two
+                  copies of the same packet due to retransmissions by the
+                  sender. In a previous paper, we presented a simple model for
+                  predicting the steady state send rate of a bulk transfer TCP
+                  flow as a function of loss rate and round trip time. In this
+                  paper, we extend that work in two ways. First, we analyze the
+                  performance of bulk transfer TCP flows using more precise,
+                  stochastic analysis. Second, we build upon the previous
+                  analysis to provide both an approximate formula as well as a
+                  more accurate stochastic model for the steady state throughput
+                  of a bulk transfer TCP flow.},
+  file         = {ftp://gaia.cs.umass.edu/pub/Padhey99-markov.ps},
+}
+
+^D
+---
+nocite: "[@*]"
+references:
+- abstract: The steady state performance of a bulk transfer TCP flow
+    (i.e., a flow with a large amount of data to send, such as FTP
+    transfers) may be characterized by three quantities. The first is
+    the send rate, which is the amount of data sent by the sender in
+    unit time. The second is the throughput, which is the amount of data
+    received by the receiver in unit time. Note that the throughput will
+    always be less than or equal to the send rate due to losses.
+    Finally, the number of non-duplicate packets received by the
+    receiver in unit time gives us the goodput of the connection. The
+    goodput is always less than or equal to the throughput, since the
+    receiver may receive two copies of the same packet due to
+    retransmissions by the sender. In a previous paper, we presented a
+    simple model for predicting the steady state send rate of a bulk
+    transfer TCP flow as a function of loss rate and round trip time. In
+    this paper, we extend that work in two ways. First, we analyze the
+    performance of bulk transfer TCP flows using more precise,
+    stochastic analysis. Second, we build upon the previous analysis to
+    provide both an approximate formula as well as a more accurate
+    stochastic model for the steady state throughput of a bulk transfer
+    TCP flow.
+  annote: This is a report entry for a technical report. Note the format
+    of the type field in the database file which uses a localization
+    key. The number of the report is given in the number field. Also
+    note the sorttitle and indextitle fields
+  author:
+  - family: Padhye
+    given: Jitendra
+  - family: Firoiu
+    given: Victor
+  - family: Towsley
+    given: Don
+  genre: technical report
+  id: padhye
+  issued: 1999
+  language: en-US
+  number: 99-02
+  publisher: University of Massachusetts
+  publisher-place: Amherst, Mass.
+  title: A stochastic model of TCP Reno congestion avoidance and control
+  type: report
+---
+
+
+```
diff --git a/test/command/biblatex-patent.md b/test/command/biblatex-patent.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-patent.md
@@ -0,0 +1,158 @@
+```
+% pandoc -f biblatex -t markdown -s
+@comment{adapted from http://mirrors.ctan.org/macros/latex/contrib/biblatex/doc/examples/biblatex-examples.bib
+
+TODO: Is there a CSL counterpart for the biblatex field "holder"?}
+
+
+@patent{almendro,
+	Annotation = {This is a patent entry with a location field. The number is given in the number field. Note the format of the location field in the database file. Compare laufenberg, sorace, and kowalik},
+	Author = {Almendro, José L. and Martín, Jacinto and Sánchez, Alberto and Nozal, Fernando},
+	Date = 1998,
+	Hyphenation = {german},
+	Location = {countryfr and countryuk and countryde},
+	Number = {EU-29702195U},
+	Title = {Elektromagnetisches Signalhorn}}
+
+@patent{kowalik,
+	Annotation = {This is a patent entry for a French patent request with a full date. The number is given in the number field. Note the format of the type and date fields in the database file. Compare almendro, laufenberg, and sorace},
+	Author = {Kowalik, F. and Isard, M.},
+	Date = {1995-01-11},
+	Hyphenation = {french},
+	Indextitle = {Estimateur d'un défaut de fonctionnement},
+	Number = 9500261,
+	Title = {Estimateur d'un défaut de fonctionnement d'un modulateur en quadrature et étage de modulation l'utilisant},
+	Type = {patreqfr}}
+
+@patent{laufenberg,
+	Annotation = {This is a patent entry with a holder field. Note the format of the type and location fields in the database file. Compare almendro, sorace, and kowalik},
+	Author = {Laufenberg, Xaver and Eynius, Dominique and Suelzle, Helmut and Usbeck, Stephan and Spaeth, Matthias and Neuser-Hoffmann, Miriam and Myrzik, Christian and Schmid, Manfred and Nietfeld, Franz and Thiel, Alexander and Braun, Harald and Ebner, Norbert},
+	Date = {2006-09-13},
+	File = {http://v3.espacenet.com/textdoc?IDX=EP1700367},
+	Holder = {{Robert Bosch GmbH} and {Daimler Chrysler AG} and {Bayerische Motoren Werke AG}},
+	Hyphenation = {german},
+	Number = 1700367,
+	Title = {Elektrische Einrichtung und Betriebsverfahren},
+	Type = {patenteu},
+	Abstract = {The invention relates to an electric device comprising a
+                  generator, in particular for use in the vehicle electric
+                  system of a motor vehicle and a controller for controlling the
+                  generator voltage. The device is equipped with a control zone,
+                  in which the voltage is controlled and zones, in which the
+                  torque is controlled. The invention also relates to methods
+                  for operating a device of this type.}}
+
+@patent{sorace,
+	Annotation = {This is a patent entry with a holder field. Note the format of the type and date fields in the database file. Compare almendro, laufenberg, and kowalik},
+	Author = {Sorace, Ronald E. and Reinhardt, Victor S. and Vaughn, Steven A.},
+	Date = {1997-09-16},
+	Date-Modified = {2013-10-16 13:44:15 +0000},
+	Holder = {{Hughes Aircraft Company}},
+	Hyphenation = {american},
+	Number = 5668842,
+	Title = {High-Speed Digital-to-{RF} Converter},
+	Type = {patentus}}
+
+^D
+---
+nocite: "[@*]"
+references:
+- annote: This is a patent entry with a location field. The number is
+    given in the number field. Note the format of the location field in
+    the database file. Compare laufenberg, sorace, and kowalik
+  author:
+  - family: Almendro
+    given: José L.
+  - family: Martín
+    given: Jacinto
+  - family: Sánchez
+    given: Alberto
+  - family: Nozal
+    given: Fernando
+  id: almendro
+  issued: 1998
+  jurisdiction: France; United Kingdom; Germany
+  language: de-DE
+  number: EU-29702195U
+  title: Elektromagnetisches Signalhorn
+  type: patent
+- annote: This is a patent entry for a French patent request with a full
+    date. The number is given in the number field. Note the format of
+    the type and date fields in the database file. Compare almendro,
+    laufenberg, and sorace
+  author:
+  - family: Kowalik
+    given: F.
+  - family: Isard
+    given: M.
+  genre: French patent request
+  id: kowalik
+  issued: 1995-01-11
+  language: fr-FR
+  number: 9500261
+  title: Estimateur d'un défaut de fonctionnement d'un modulateur en
+    quadrature et étage de modulation l'utilisant
+  type: patent
+- abstract: The invention relates to an electric device comprising a
+    generator, in particular for use in the vehicle electric system of a
+    motor vehicle and a controller for controlling the generator
+    voltage. The device is equipped with a control zone, in which the
+    voltage is controlled and zones, in which the torque is controlled.
+    The invention also relates to methods for operating a device of this
+    type.
+  annote: This is a patent entry with a holder field. Note the format of
+    the type and location fields in the database file. Compare almendro,
+    sorace, and kowalik
+  author:
+  - family: Laufenberg
+    given: Xaver
+  - family: Eynius
+    given: Dominique
+  - family: Suelzle
+    given: Helmut
+  - family: Usbeck
+    given: Stephan
+  - family: Spaeth
+    given: Matthias
+  - family: Neuser-Hoffmann
+    given: Miriam
+  - family: Myrzik
+    given: Christian
+  - family: Schmid
+    given: Manfred
+  - family: Nietfeld
+    given: Franz
+  - family: Thiel
+    given: Alexander
+  - family: Braun
+    given: Harald
+  - family: Ebner
+    given: Norbert
+  genre: European patent
+  id: laufenberg
+  issued: 2006-09-13
+  language: de-DE
+  number: 1700367
+  title: Elektrische Einrichtung und Betriebsverfahren
+  type: patent
+- annote: This is a patent entry with a holder field. Note the format of
+    the type and date fields in the database file. Compare almendro,
+    laufenberg, and kowalik
+  author:
+  - family: Sorace
+    given: Ronald E.
+  - family: Reinhardt
+    given: Victor S.
+  - family: Vaughn
+    given: Steven A.
+  genre: U.S. patent
+  id: sorace
+  issued: 1997-09-16
+  language: en-US
+  number: 5668842
+  title: High-speed digital-to-RF converter
+  type: patent
+---
+
+
+```
diff --git a/test/command/biblatex-periodical.md b/test/command/biblatex-periodical.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-periodical.md
@@ -0,0 +1,31 @@
+```
+% pandoc -f biblatex -t markdown -s
+@comment{excerpt from
+http://mirrors.ctan.org/macros/latex/contrib/biblatex/doc/examples/biblatex-examples.bib}
+
+@periodical{jcg,
+	Annotation = {This is a periodical entry with an issn field.},
+	Issn = {0097-8493},
+	Issuetitle = {Semantic {3D} Media and Content},
+	Number = 4,
+	Title = {Computers and Graphics},
+	Volume = 35,
+	Year = 2011}
+
+^D
+---
+nocite: "[@*]"
+references:
+- annote: This is a periodical entry with an issn field.
+  container-title: Computers and Graphics
+  id: jcg
+  issn: 0097-8493
+  issue: 4
+  issued: 2011
+  title: Semantic 3D media and content
+  type: article-journal
+  volume: 35
+---
+
+
+```
diff --git a/test/command/biblatex-piccato.md b/test/command/biblatex-piccato.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-piccato.md
@@ -0,0 +1,59 @@
+```
+% pandoc -f biblatex -t markdown -s
+@comment{
+
+Adapted from biblatex-example.bib
+
+
+Formatted with pandoc and chicago-author-date.csl, 2013-10-23:
+
+(Piccato 2001)
+
+Piccato, Pablo. 2001. *City of Suspects: Crime in Mexico City,
+1900–1931*. Durham; London: Duke University Press.
+
+
+Formatted with pandoc and apa.csl, 2013-10-23:
+
+(Piccato, 2001)
+
+Piccato, P. (2001). *City of suspects: Crime in Mexico City, 1900–1931*.
+Durham; London: Duke University Press.
+
+
+}
+
+@Book{piccato,
+  author       = {Piccato, Pablo},
+  title        = {City of Suspects},
+  date         = 2001,
+  publisher    = {Duke University Press},
+  location     = {Durham and London},
+  hyphenation  = {american},
+  subtitle     = {Crime in {Mexico City}, 1900--1931},
+  shorttitle   = {City of Suspects},
+  annotation   = {This is a book entry. Note the format of the
+                  location field in the database file},
+}
+
+^D
+---
+nocite: "[@*]"
+references:
+- annote: This is a book entry. Note the format of the location field in
+    the database file
+  author:
+  - family: Piccato
+    given: Pablo
+  id: piccato
+  issued: 2001
+  language: en-US
+  publisher: Duke University Press
+  publisher-place: Durham; London
+  title: "City of suspects: Crime in Mexico City, 1900--1931"
+  title-short: City of suspects
+  type: book
+---
+
+
+```
diff --git a/test/command/biblatex-pines.md b/test/command/biblatex-pines.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-pines.md
@@ -0,0 +1,77 @@
+```
+% pandoc -f biblatex -t markdown -s
+@comment{
+
+Adapted from biblatex-example.bib
+
+
+Formatted with pandoc and chicago-author-date.csl, 2013-10-23:
+
+(Pines 1979)
+
+Pines, Shlomo. 1979. “The Limitations of Human Knowledge According to
+Al-Farabi, ibn Bajja, and Maimonides.” In *Studies in Medieval Jewish
+History and Literature*, edited by Isadore Twersky, 82–109. Cambridge,
+Mass.: Harvard University Press.
+
+
+Formatted with pandoc and apa.csl, 2013-10-23:
+
+(Pines, 1979)
+
+Pines, S. (1979). The limitations of human knowledge according to
+Al-Farabi, ibn Bajja, and Maimonides. In I. Twersky (Ed.), *Studies in
+medieval Jewish history and literature* (pp. 82–109). Cambridge, Mass.:
+Harvard University Press.
+
+
+}
+
+@string{ hup     = {Harvard University Press} }
+
+@InCollection{pines,
+  author       = {Pines, Shlomo},
+  editor       = {Twersky, Isadore},
+  title        = {The Limitations of Human Knowledge According to {Al-Farabi}, {ibn
+                  Bajja}, and {Maimonides}},
+  date         = 1979,
+  booktitle    = {Studies in Medieval {Jewish} History and Literature},
+  publisher    = hup,
+  location     = {Cambridge, Mass.},
+  pages        = {82-109},
+  keywords     = {secondary},
+  hyphenation  = {american},
+  indextitle   = {Limitations of Human Knowledge According to {Al-Farabi}, {ibn
+                  Bajja}, and {Maimonides}, The},
+  shorttitle   = {Limitations of Human Knowledge},
+  annotation   = {A typical incollection entry. Note the
+                  indextitle field},
+}
+
+^D
+---
+nocite: "[@*]"
+references:
+- annote: A typical incollection entry. Note the indextitle field
+  author:
+  - family: Pines
+    given: Shlomo
+  container-title: Studies in medieval Jewish history and literature
+  editor:
+  - family: Twersky
+    given: Isadore
+  id: pines
+  issued: 1979
+  keyword: secondary
+  language: en-US
+  page: 82-109
+  publisher: Harvard University Press
+  publisher-place: Cambridge, Mass.
+  title: The limitations of human knowledge according to Al-Farabi, [ibn
+    Bajja]{.nocase}, and Maimonides
+  title-short: Limitations of human knowledge
+  type: chapter
+---
+
+
+```
diff --git a/test/command/biblatex-quotes.md b/test/command/biblatex-quotes.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-quotes.md
@@ -0,0 +1,44 @@
+```
+% pandoc -f biblatex -t markdown -s
+@comment{excerpt from http://mirrors.ctan.org/macros/latex/contrib/biblatex/doc/examples/biblatex-examples.bib
+
+\mkbibquote{} should be replaced by a matching set of quotation marks that can be used by citeproc for quote substitution and flipflopping. English smart double quotation marks seem best, as they cannot be confused with apostrophes.
+
+\enquote{}, \enquote*{} should be replaced by a matching set of quotation marks, too: “foo”, ‘bar’.
+}
+
+@string{pup = {Princeton University Press}}
+
+@book{nussbaum,
+	Annotation = {A book entry. Note the sorttitle and indexsorttitle fields and the markup of the quotes in the database file},
+	Author = {Nussbaum, Martha},
+	Date = 1978,
+	Hyphenation = {american},
+	Indexsorttitle = {Aristotle's De Motu Animalium},
+	Keywords = {secondary},
+	Location = {Princeton},
+	Publisher = pup,
+	Sorttitle = {Aristotle's De Motu Animalium},
+	Title = {Aristotle's \mkbibquote{De Motu Animalium}}}
+
+^D
+---
+nocite: "[@*]"
+references:
+- annote: A book entry. Note the sorttitle and indexsorttitle fields and
+    the markup of the quotes in the database file
+  author:
+  - family: Nussbaum
+    given: Martha
+  id: nussbaum
+  issued: 1978
+  keyword: secondary
+  language: en-US
+  publisher: Princeton University Press
+  publisher-place: Princeton
+  title: Aristotle's "De Motu Animalium"
+  type: book
+---
+
+
+```
diff --git a/test/command/biblatex-reese.md b/test/command/biblatex-reese.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-reese.md
@@ -0,0 +1,71 @@
+```
+% pandoc -f biblatex -t markdown -s
+@comment{
+
+Adapted from biblatex-example.bib
+
+
+Formatted with pandoc and chicago-author-date.csl, 2013-10-23:
+
+(Reese 1958)
+
+Reese, Trevor R. 1958. “Georgia in Anglo-Spanish Diplomacy, 1736-1739.”
+*William and Mary Quarterly, 3* 15: 168–190.
+
+
+Formatted with pandoc and apa.csl, 2013-10-23:
+
+(Reese, 1958)
+
+Reese, T. R. (1958). Georgia in Anglo-Spanish diplomacy, 1736-1739.
+*William and Mary Quarterly, 3*, *15*, 168–190.
+
+
+NOTES:
+
+- biblio2yaml
+	- series field: still not entirely satisfactory.
+	  Could we map this to some existing CSL variable, and have the CSL styles handle this? "edition", maybe ??
+
+}
+
+@Article{reese,
+  author       = {Reese, Trevor R.},
+  title        = {Georgia in {Anglo-Spanish} Diplomacy, 1736-1739},
+  journaltitle = {William and Mary Quarterly},
+  date         = 1958,
+  series       = 3,
+  volume       = 15,
+  pages        = {168-190},
+  hyphenation  = {american},
+  annotation   = {An article entry with a series and a
+                  volume field. Note the format of the series. If the
+                  value of the series field is an integer, this number
+                  is printed as an ordinal and the string \enquote*{series} is
+                  appended automatically},
+}
+
+^D
+---
+nocite: "[@*]"
+references:
+- annote: An article entry with a series and a volume field. Note the
+    format of the series. If the value of the series field is an
+    integer, this number is printed as an ordinal and the string
+    'series' is appended automatically
+  author:
+  - family: Reese
+    given: Trevor R.
+  collection-title: 3rd series
+  container-title: William and Mary Quarterly
+  id: reese
+  issued: 1958
+  language: en-US
+  page: 168-190
+  title: Georgia in Anglo-Spanish diplomacy, 1736-1739
+  type: article-journal
+  volume: 15
+---
+
+
+```
diff --git a/test/command/biblatex-report.md b/test/command/biblatex-report.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-report.md
@@ -0,0 +1,119 @@
+```
+% pandoc -f biblatex -t markdown -s
+@comment{excerpt from http://mirrors.ctan.org/macros/latex/contrib/biblatex/doc/examples/biblatex-examples.bib
+
+TODO: Where to map "file" field?
+}
+
+@report{chiu,
+	Annotation = {This is a report entry for a research report. Note the format of the type field in the database file which uses a localization key. The number of the report is given in the number field. Also note the sorttitle and indextitle fields},
+	Author = {Chiu, Willy W. and Chow, We Min},
+	Date = 1978,
+	Hyphenation = {american},
+	Indextitle = {Hybrid Hierarchical Model, A},
+	Institution = {IBM},
+	Number = {RC-6947},
+	Sorttitle = {Hybrid Hierarchical Model of a Multiple Virtual Storage (MVS) Operating System},
+	Title = {A Hybrid Hierarchical Model of a {Multiple Virtual Storage} ({MVS}) Operating System},
+	Type = {resreport}}
+
+@report{padhye,
+	Annotation = {This is a report entry for a technical report. Note the format of the type field in the database file which uses a localization key. The number of the report is given in the number field. Also note the sorttitle and indextitle fields},
+	Author = {Padhye, Jitendra and Firoiu, Victor and Towsley, Don},
+	Date = 1999,
+	File = {ftp://gaia.cs.umass.edu/pub/Padhey99-markov.ps},
+	Hyphenation = {american},
+	Indextitle = {Stochastic Model of TCP Reno Congestion Avoidance and Control, A},
+	Institution = {University of Massachusetts},
+	Location = {Amherst, Mass.},
+	Number = {99-02},
+	Sorttitle = {A Stochastic Model of TCP Reno Congestion Avoidance and Control},
+	Title = {A Stochastic Model of {TCP Reno} Congestion Avoidance and Control},
+	Type = {techreport},
+	Abstract = {The steady state performance of a bulk transfer TCP flow
+                  (i.e., a flow with a large amount of data to send, such as FTP
+                  transfers) may be characterized by three quantities. The first
+                  is the send rate, which is the amount of data sent by the
+                  sender in unit time. The second is the throughput, which is
+                  the amount of data received by the receiver in unit time. Note
+                  that the throughput will always be less than or equal to the
+                  send rate due to losses. Finally, the number of non-duplicate
+                  packets received by the receiver in unit time gives us the
+                  goodput of the connection. The goodput is always less than or
+                  equal to the throughput, since the receiver may receive two
+                  copies of the same packet due to retransmissions by the
+                  sender. In a previous paper, we presented a simple model for
+                  predicting the steady state send rate of a bulk transfer TCP
+                  flow as a function of loss rate and round trip time. In this
+                  paper, we extend that work in two ways. First, we analyze the
+                  performance of bulk transfer TCP flows using more precise,
+                  stochastic analysis. Second, we build upon the previous
+                  analysis to provide both an approximate formula as well as a
+                  more accurate stochastic model for the steady state throughput
+                  of a bulk transfer TCP flow.}}
+^D
+---
+nocite: "[@*]"
+references:
+- annote: This is a report entry for a research report. Note the format
+    of the type field in the database file which uses a localization
+    key. The number of the report is given in the number field. Also
+    note the sorttitle and indextitle fields
+  author:
+  - family: Chiu
+    given: Willy W.
+  - family: Chow
+    given: We Min
+  genre: research report
+  id: chiu
+  issued: 1978
+  language: en-US
+  number: RC-6947
+  publisher: IBM
+  title: A hybrid hierarchical model of a Multiple Virtual Storage (MVS)
+    operating system
+  type: report
+- abstract: The steady state performance of a bulk transfer TCP flow
+    (i.e., a flow with a large amount of data to send, such as FTP
+    transfers) may be characterized by three quantities. The first is
+    the send rate, which is the amount of data sent by the sender in
+    unit time. The second is the throughput, which is the amount of data
+    received by the receiver in unit time. Note that the throughput will
+    always be less than or equal to the send rate due to losses.
+    Finally, the number of non-duplicate packets received by the
+    receiver in unit time gives us the goodput of the connection. The
+    goodput is always less than or equal to the throughput, since the
+    receiver may receive two copies of the same packet due to
+    retransmissions by the sender. In a previous paper, we presented a
+    simple model for predicting the steady state send rate of a bulk
+    transfer TCP flow as a function of loss rate and round trip time. In
+    this paper, we extend that work in two ways. First, we analyze the
+    performance of bulk transfer TCP flows using more precise,
+    stochastic analysis. Second, we build upon the previous analysis to
+    provide both an approximate formula as well as a more accurate
+    stochastic model for the steady state throughput of a bulk transfer
+    TCP flow.
+  annote: This is a report entry for a technical report. Note the format
+    of the type field in the database file which uses a localization
+    key. The number of the report is given in the number field. Also
+    note the sorttitle and indextitle fields
+  author:
+  - family: Padhye
+    given: Jitendra
+  - family: Firoiu
+    given: Victor
+  - family: Towsley
+    given: Don
+  genre: technical report
+  id: padhye
+  issued: 1999
+  language: en-US
+  number: 99-02
+  publisher: University of Massachusetts
+  publisher-place: Amherst, Mass.
+  title: A stochastic model of TCP Reno congestion avoidance and control
+  type: report
+---
+
+
+```
diff --git a/test/command/biblatex-salam.md b/test/command/biblatex-salam.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-salam.md
@@ -0,0 +1,69 @@
+```
+% pandoc -f biblatex -t markdown -s
+@comment{
+
+Adapted from biblatex-example.bib
+
+
+Formatted with pandoc and chicago-author-date.csl, 2013-10-23:
+
+(Salam 1968)
+
+Salam, Abdus. 1968. “Weak and Electromagnetic Interactions.” In
+*Elementary Particle Theory: Relativistic Groups and Analyticity.
+Proceedings of the Eighth Nobel Symposium*, edited by Nils Svartholm,
+367–377. Stockholm: Almquist & Wiksell.
+
+
+Formatted with pandoc and apa.csl, 2013-10-23:
+
+(Salam, 1968)
+
+Salam, A. (1968). Weak and electromagnetic interactions. In N. Svartholm
+(Ed.), *Elementary particle theory: Relativistic groups and analyticity.
+Proceedings of the eighth Nobel symposium* (pp. 367–377). Stockholm:
+Almquist & Wiksell.
+
+
+}
+
+@InProceedings{salam,
+  author       = {Salam, Abdus},
+  editor       = {Svartholm, Nils},
+  title        = {Weak and Electromagnetic Interactions},
+  date         = 1968,
+  booktitle    = {Elementary particle theory},
+  booksubtitle = {Relativistic groups and analyticity},
+  booktitleaddon= {Proceedings of the Eighth {Nobel} Symposium},
+  eventdate    = {1968-05-19/1968-05-25},
+  venue        = {Aspen{\"a}sgarden, Lerum},
+  publisher    = {Almquist \& Wiksell},
+  location     = {Stockholm},
+  pages        = {367-377},
+}
+
+^D
+---
+nocite: "[@*]"
+references:
+- author:
+  - family: Salam
+    given: Abdus
+  container-title: "Elementary particle theory: Relativistic groups and
+    analyticity. Proceedings of the eighth Nobel symposium"
+  editor:
+  - family: Svartholm
+    given: Nils
+  event-date: 1968-05-19/1968-05-25
+  event-place: Aspenäsgarden, Lerum
+  id: salam
+  issued: 1968
+  page: 367-377
+  publisher: Almquist & Wiksell
+  publisher-place: Stockholm
+  title: Weak and electromagnetic interactions
+  type: paper-conference
+---
+
+
+```
diff --git a/test/command/biblatex-sarfraz.md b/test/command/biblatex-sarfraz.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-sarfraz.md
@@ -0,0 +1,65 @@
+```
+% pandoc -f biblatex -t markdown -s
+@comment{
+
+Adapted from biblatex-example.bib
+
+
+Formatted with pandoc and chicago-author-date.csl, 2013-10-23:
+
+(Sarfraz and Razzak 2002)
+
+Sarfraz, M., and M. F. A. Razzak. 2002. “Technical Section: An Algorithm
+for Automatic Capturing of the Font Outlines.” *Computers and Graphics*
+26 (5): 795–804.
+
+
+Formatted with pandoc and apa.csl, 2013-10-23:
+
+(Sarfraz & Razzak, 2002)
+
+Sarfraz, M., & Razzak, M. F. A. (2002). Technical section: An algorithm
+for automatic capturing of the font outlines. *Computers and Graphics*,
+*26*(5), 795–804.
+
+
+}
+
+@Article{sarfraz,
+  author       = {M. Sarfraz and M. F. A. Razzak},
+  title        = {Technical section: {An} algorithm for automatic capturing of
+                  the font outlines},
+  year         = 2002,
+  volume       = 26,
+  number       = 5,
+  pages        = {795-804},
+  issn         = {0097-8493},
+  journal      = {Computers and Graphics},
+  annotation   = {An article entry with an issn field},
+}
+
+^D
+---
+nocite: "[@*]"
+references:
+- annote: An article entry with an issn field
+  author:
+  - family: Sarfraz
+    given: M.
+  - family: Razzak
+    given: M. F. A.
+  container-title: Computers and Graphics
+  id: sarfraz
+  issn: 0097-8493
+  issue: 5
+  issued: 2002
+  page: 795-804
+  title: "Technical section: An algorithm for automatic capturing of the
+    font outlines"
+  title-short: Technical section
+  type: article-journal
+  volume: 26
+---
+
+
+```
diff --git a/test/command/biblatex-shore.md b/test/command/biblatex-shore.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-shore.md
@@ -0,0 +1,66 @@
+```
+% pandoc -f biblatex -t markdown -s
+@comment{
+
+Adapted from biblatex-example.bib
+
+
+Formatted with pandoc and chicago-author-date.csl, 2013-10-23:
+
+(Shore 1991)
+
+Shore, Bradd. 1991. “Twice-born, Once Conceived: Meaning Construction
+and Cultural Cognition.” *American Anthropologist, New Series* 93 (1)
+(March): 9–27.
+
+
+Formatted with pandoc and apa.csl, 2013-10-23:
+
+(Shore, 1991)
+
+Shore, B. (1991). Twice-born, once conceived: Meaning construction and
+cultural cognition. *American Anthropologist, new series*, *93*(1),
+9–27.
+
+
+}
+
+@Article{shore,
+  author       = {Shore, Bradd},
+  title        = {Twice-Born, Once Conceived},
+  journaltitle = {American Anthropologist},
+  date         = {1991-03},
+  subtitle     = {Meaning Construction and Cultural Cognition},
+  series       = {newseries},
+  volume       = 93,
+  number       = 1,
+  pages        = {9-27},
+  annotation   = {An article entry with series,
+                  volume, and number fields. Note the format
+                  of the series which is a localization key},
+}
+
+^D
+---
+nocite: "[@*]"
+references:
+- annote: An article entry with series, volume, and number fields. Note
+    the format of the series which is a localization key
+  author:
+  - family: Shore
+    given: Bradd
+  collection-title: New series
+  container-title: American Anthropologist
+  id: shore
+  issue: 1
+  issued: 1991-03
+  page: 9-27
+  title: "Twice-born, once conceived: Meaning construction and cultural
+    cognition"
+  title-short: Twice-born, once conceived
+  type: article-journal
+  volume: 93
+---
+
+
+```
diff --git a/test/command/biblatex-sigfridsson.md b/test/command/biblatex-sigfridsson.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-sigfridsson.md
@@ -0,0 +1,106 @@
+```
+% pandoc -f biblatex -t markdown -s
+@comment{
+
+Adapted from biblatex-example.bib
+
+Formatted with pandoc and chicago-author-date.csl, 2013-10-23:
+
+(Sigfridsson and Ryde 1998)
+
+Sigfridsson, Emma, and Ulf Ryde. 1998. “Comparison of Methods for
+Deriving Atomic Charges from the Electrostatic Potential and Moments.”
+*Journal of Computational Chemistry* 19 (4): 377–395.
+doi:[10.1002/(SICI)1096-987X(199803)19:4\<377::AID-JCC1\>3.0.CO;2-P](https://doi.org/10.1002/(SICI)1096-987X(199803)19:4<377::AID-JCC1>3.0.CO;2-P "10.1002/(SICI)1096-987X(199803)19:4<377::AID-JCC1>3.0.CO;2-P").
+
+
+Formatted with pandoc and apa.csl, 2013-10-23:
+
+(Sigfridsson & Ryde, 1998)
+
+Sigfridsson, E., & Ryde, U. (1998). Comparison of methods for deriving
+atomic charges from the electrostatic potential and moments. *Journal of
+Computational Chemistry*, *19*(4), 377–395.
+doi:[10.1002/(SICI)1096-987X(199803)19:4\<377::AID-JCC1\>3.0.CO;2-P](https://doi.org/10.1002/(SICI)1096-987X(199803)19:4<377::AID-JCC1>3.0.CO;2-P "10.1002/(SICI)1096-987X(199803)19:4<377::AID-JCC1>3.0.CO;2-P")
+
+
+NOTES:
+
+- biblio2xaml
+	- the string "doi:" should not appear as part of the content of the "doi" field 
+
+}
+
+@Article{sigfridsson,
+  author       = {Sigfridsson, Emma and Ryde, Ulf},
+  title        = {Comparison of methods for deriving atomic charges from the
+                  electrostatic potential and moments},
+  journaltitle = {Journal of Computational Chemistry},
+  date         = 1998,
+  volume       = 19,
+  number       = 4,
+  pages        = {377-395},
+  doi          = {10.1002/(SICI)1096-987X(199803)19:4<377::AID-JCC1>3.0.CO;2-P},
+  hyphenation  = {american},
+  indextitle   = {Methods for deriving atomic charges},
+  annotation   = {An article entry with volume,
+                  number, and doi fields. Note that the
+                  \textsc{doi} is transformed into a clickable link if
+                  hyperref support has been enabled},
+  abstract     = {Four methods for deriving partial atomic charges from the
+                  quantum chemical electrostatic potential (CHELP, CHELPG,
+                  Merz-Kollman, and RESP) have been compared and critically
+                  evaluated. It is shown that charges strongly depend on how and
+                  where the potential points are selected. Two alternative
+                  methods are suggested to avoid the arbitrariness in the
+                  point-selection schemes and van der Waals exclusion radii:
+                  CHELP-BOW, which also estimates the charges from the
+                  electrostatic potential, but with potential points that are
+                  Boltzmann-weighted after their occurrence in actual
+                  simulations using the energy function of the program in which
+                  the charges will be used, and CHELMO, which estimates the
+                  charges directly from the electrostatic multipole
+                  moments. Different criteria for the quality of the charges are
+                  discussed.},
+}
+
+^D
+---
+nocite: "[@*]"
+references:
+- abstract: "Four methods for deriving partial atomic charges from the
+    quantum chemical electrostatic potential (CHELP, CHELPG,
+    Merz-Kollman, and RESP) have been compared and critically evaluated.
+    It is shown that charges strongly depend on how and where the
+    potential points are selected. Two alternative methods are suggested
+    to avoid the arbitrariness in the point-selection schemes and van
+    der Waals exclusion radii: CHELP-BOW, which also estimates the
+    charges from the electrostatic potential, but with potential points
+    that are Boltzmann-weighted after their occurrence in actual
+    simulations using the energy function of the program in which the
+    charges will be used, and CHELMO, which estimates the charges
+    directly from the electrostatic multipole moments. Different
+    criteria for the quality of the charges are discussed."
+  annote: An article entry with volume, number, and doi fields. Note
+    that the [doi]{.smallcaps} is transformed into a clickable link if
+    hyperref support has been enabled
+  author:
+  - family: Sigfridsson
+    given: Emma
+  - family: Ryde
+    given: Ulf
+  container-title: Journal of Computational Chemistry
+  doi: "10.1002/(SICI)1096-987X(199803)19:4\\<377::AID-JCC1\\>3.0.CO;2-P"
+  id: sigfridsson
+  issue: 4
+  issued: 1998
+  language: en-US
+  page: 377-395
+  title: Comparison of methods for deriving atomic charges from the
+    electrostatic potential and moments
+  type: article-journal
+  volume: 19
+---
+
+
+```
diff --git a/test/command/biblatex-sorace.md b/test/command/biblatex-sorace.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-sorace.md
@@ -0,0 +1,65 @@
+```
+% pandoc -f biblatex -t markdown -s
+@comment{
+
+Adapted from biblatex-example.bib
+
+
+Formatted with pandoc and chicago-author-date.csl, 2013-10-23:
+
+(Sorace, Reinhardt, and Vaughn 1997)
+
+Sorace, Ronald E., Victor S. Reinhardt, and Steven A. Vaughn. 1997.
+“High-speed Digital-to-RF Converter.” U.S. patent.
+
+
+Formatted with pandoc and apa.csl, 2013-10-23:
+
+(Sorace, Reinhardt, & Vaughn, 1997)
+
+Sorace, R. E., Reinhardt, V. S., & Vaughn, S. A. (1997, September 16).
+High-speed digital-to-RF converter. U.S. patent.
+
+
+}
+
+@Patent{sorace,
+  author       = {Sorace, Ronald E. and Reinhardt, Victor S. and Vaughn, Steven
+                  A.},
+  title        = {High-Speed Digital-to-{RF} Converter},
+  number       = 5668842,
+  date         = {1997-09-16},
+  holder       = {{Hughes Aircraft Company}},
+  type         = {patentus},
+  hyphenation  = {american},
+  annotation   = {This is a patent entry with a holder field.
+                  Note the format of the type and date fields
+                  in the database file. Compare almendro,
+                  laufenberg, and kowalik},
+}
+
+^D
+---
+nocite: "[@*]"
+references:
+- annote: This is a patent entry with a holder field. Note the format of
+    the type and date fields in the database file. Compare almendro,
+    laufenberg, and kowalik
+  author:
+  - family: Sorace
+    given: Ronald E.
+  - family: Reinhardt
+    given: Victor S.
+  - family: Vaughn
+    given: Steven A.
+  genre: U.S. patent
+  id: sorace
+  issued: 1997-09-16
+  language: en-US
+  number: 5668842
+  title: High-speed digital-to-RF converter
+  type: patent
+---
+
+
+```
diff --git a/test/command/biblatex-spiegelberg.md b/test/command/biblatex-spiegelberg.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-spiegelberg.md
@@ -0,0 +1,74 @@
+```
+% pandoc -f biblatex -t markdown -s
+@comment{
+
+Adapted from biblatex-example.bib
+
+
+Formatted with pandoc and chicago-author-date.csl, 2013-10-23:
+
+(Spiegelberg 1969)
+
+Spiegelberg, Herbert. 1969. ““Intention” und “Intentionalität” in der
+Scholastik, bei Brentano und Husserl.” *Studia Philosophica* 29:
+189–216.
+
+
+Formatted with pandoc and apa.csl, 2013-10-23:
+
+(Spiegelberg, 1969)
+
+Spiegelberg, H. (1969). “Intention” und “Intentionalität” in der
+Scholastik, bei Brentano und Husserl. *Studia Philosophica*, *29*,
+189–216.
+
+
+NOTES:
+
+- citeproc
+	- flipflopping of quotes incorrect
+
+}
+
+@Article{spiegelberg,
+  author       = {Spiegelberg, Herbert},
+  title        = {\mkbibquote{Intention} und \mkbibquote{Intentionalit{\"a}t} in
+                  der Scholastik, bei Brentano und Husserl},
+  journaltitle = {Studia Philosophica},
+  date         = 1969,
+  volume       = 29,
+  pages        = {189-216},
+  hyphenation  = {german},
+  sorttitle    = {Intention und Intentionalitat in der Scholastik, bei Brentano
+                  und Husserl},
+  indexsorttitle= {Intention und Intentionalitat in der Scholastik, bei Brentano
+                  und Husserl},
+  shorttitle   = {Intention und Intentionalit{\"a}t},
+  annotation   = {An article entry. Note the sorttitle and
+                  indexsorttitle fields and the markup of the quotes in
+                  the database file},
+}
+
+^D
+---
+nocite: "[@*]"
+references:
+- annote: An article entry. Note the sorttitle and indexsorttitle fields
+    and the markup of the quotes in the database file
+  author:
+  - family: Spiegelberg
+    given: Herbert
+  container-title: Studia Philosophica
+  id: spiegelberg
+  issued: 1969
+  language: de-DE
+  page: 189-216
+  title: "\"Intention\" und \"Intentionalität\" in der Scholastik, bei
+    Brentano und Husserl"
+  title-short: Intention und Intentionalität
+  type: article-journal
+  volume: 29
+---
+
+
+```
diff --git a/test/command/biblatex-springer.md b/test/command/biblatex-springer.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-springer.md
@@ -0,0 +1,58 @@
+```
+% pandoc -f biblatex -t markdown -s
+@comment{
+
+Adapted from biblatex-example.bib
+
+
+Formatted with pandoc and chicago-author-date.csl, 2013-10-23:
+
+(Springer 1950)
+
+Springer, Otto. 1950. “Mediaeval Pilgrim Routes from Scandinavia to
+Rome.” *Mediaeval Studies* 12: 92–122.
+
+
+Formatted with pandoc and apa.csl, 2013-10-23:
+
+(Springer, 1950)
+
+Springer, O. (1950). Mediaeval pilgrim routes from Scandinavia to Rome.
+*Mediaeval Studies*, *12*, 92–122.
+
+
+}
+
+@Article{springer,
+  author       = {Springer, Otto},
+  title        = {Mediaeval Pilgrim Routes from {Scandinavia} to {Rome}},
+  journaltitle = {Mediaeval Studies},
+  date         = 1950,
+  volume       = 12,
+  pages        = {92-122},
+  hyphenation  = {british},
+  shorttitle   = {Mediaeval Pilgrim Routes},
+  annotation   = {A plain article entry},
+}
+
+^D
+---
+nocite: "[@*]"
+references:
+- annote: A plain article entry
+  author:
+  - family: Springer
+    given: Otto
+  container-title: Mediaeval Studies
+  id: springer
+  issued: 1950
+  language: en-GB
+  page: 92-122
+  title: Mediaeval pilgrim routes from Scandinavia to Rome
+  title-short: Mediaeval pilgrim routes
+  type: article-journal
+  volume: 12
+---
+
+
+```
diff --git a/test/command/biblatex-strings.md b/test/command/biblatex-strings.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-strings.md
@@ -0,0 +1,46 @@
+```
+% pandoc -f biblatex -t markdown -s
+@comment{excerpt from http://mirrors.ctan.org/macros/latex/contrib/biblatex/doc/examples/biblatex-examples.bib}
+
+@string{anch-ie = {Angew.~Chem. Int.~Ed.}}
+
+@article{herrmann,
+	Author = {Herrmann, Wolfgang A. and Öfele, Karl and Schneider, Sabine K. and Herdtweck, Eberhardt and Hoffmann, Stephan D.},
+	Date = 2006,
+	Hyphenation = {english},
+	Indextitle = {Carbocyclic carbene as an efficient catalyst, A},
+	Journaltitle = anch-ie,
+	Number = 23,
+	Pages = {3859-3862},
+	Title = {A Carbocyclic Carbene as an Efficient Catalyst Ligand for {C--C} Coupling Reactions},
+	Volume = 45}
+
+^D
+---
+nocite: "[@*]"
+references:
+- author:
+  - family: Herrmann
+    given: Wolfgang A.
+  - family: Öfele
+    given: Karl
+  - family: Schneider
+    given: Sabine K.
+  - family: Herdtweck
+    given: Eberhardt
+  - family: Hoffmann
+    given: Stephan D.
+  container-title: Angew. Chem. Int. Ed.
+  id: herrmann
+  issue: 23
+  issued: 2006
+  language: en-US
+  page: 3859-3862
+  title: A carbocyclic carbene as an efficient catalyst ligand for C--C
+    coupling reactions
+  type: article-journal
+  volume: 45
+---
+
+
+```
diff --git a/test/command/biblatex-test-case-conversion.md b/test/command/biblatex-test-case-conversion.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-test-case-conversion.md
@@ -0,0 +1,73 @@
+```
+% pandoc -f biblatex -t markdown -s
+@comment{
+    - bibtex and biblatex
+        - expect titles in title case
+        - styles use titles as is, or convert them to sentence case
+        - strings wrapped {} are not converted
+    - all CSL styles at <http://github.com/citation-style-language/styles>
+      and <https://www.zotero.org/styles/>
+        - expect titles in sentence case
+        - styles use titles as is, or convert them to title case
+        - except for (hardcoded) list of stop words, see
+          <http://citationstyles.org/downloads/specification.html#title-case-conversion>
+        - citeproc-js (MLZ only?) also recognizes a markup syntax for
+          suppressing title-case changes on a range of text (see
+          <https://forums.zotero.org/discussion/21991/excessive-capitalization-of-citation-titles/#Item_22>):
+            - `<span class="nocase"/>lowercase</span>`
+    - Proposal:
+        - When converting to yaml, convert English titles to sentence case,
+            - for all strings wrapped in {} where {} is not part of a latex
+              command, ...
+            - ... when starting with an uppercase letter: suppress
+conversion, remove the {}
+            - ... when starting with a lowercase letter ("nm", "iPod"):
+              suppress conversion, replace the {} with
+              <span class="nocase"/></span>
+            - Note: Camel case ("iPod") needs to be protected in
+              bibtex/biblatex anyway; the only "extension" (wrt bibtex/biblatex
+              specs) we'd be introducing is wrapping lowercase-only strings in
+              {}, something that is never necessary on the latex side but
+              won't break anything there either.
+        - citeproc-hs/pandoc-citeproc should be modified to honour this new
+          syntax and suppress conversion to title case for strings wrapped
+          in `<span class="nocase"/></span>`.
+        - Expected output, using one of the title-case CSL styles, here
+          chicago-author-date.csl:
+
+            Author, Ann. 2013. “A Title, in English, with a Proper Name and
+an
+            ACRONYM and a camelCase Word and Some Units, 400 nm, 3 cm, and
+a Quote,
+            *Alea iacta est*.” *Journal*.
+    }
+
+@article{item1,
+    Author = {Author, Ann},
+    Date = {2013},
+    Hyphenation = {english},
+    Journaltitle = {Journal},
+    Title = {A Title, in {English}, with a {Proper Name} and an {ACRONYM}
+and a {camelCase} Word and Some Units, 400~{nm}, 3~{cm}, and a Quote,
+\textit{{Alea} {iacta est}}}
+}
+
+^D
+---
+nocite: "[@*]"
+references:
+- author:
+  - family: Author
+    given: Ann
+  container-title: Journal
+  id: item1
+  issued: 2013
+  language: en-US
+  title: A title, in English, with a Proper Name and an ACRONYM and a
+    [camelCase]{.nocase} word and some units, 400 [nm]{.nocase},
+    3 [cm]{.nocase}, and a quote, *Alea [iacta est]{.nocase}*
+  type: article-journal
+---
+
+
+```
diff --git a/test/command/biblatex-textnormal.md b/test/command/biblatex-textnormal.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-textnormal.md
@@ -0,0 +1,17 @@
+```
+% pandoc -f biblatex -t markdown -s
+@book{item1,
+	Title = {The Title \textnormal{of this book}},
+}
+
+^D
+---
+nocite: "[@*]"
+references:
+- id: item1
+  title: The title [of this book]{.nodecor}
+  type: book
+---
+
+
+```
diff --git a/test/command/biblatex-thesis.md b/test/command/biblatex-thesis.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-thesis.md
@@ -0,0 +1,68 @@
+```
+% pandoc -f biblatex -t markdown -s
+@comment{excerpted from http://mirrors.ctan.org/macros/latex/contrib/biblatex/doc/examples/biblatex-examples.bib
+
+TODO: Uppercase letters following hyphens need to be converted to lowercase, too (e.g., "r" in "High-Resolution". -- Same for citeproc when doing title-case conversion!)
+}
+
+@thesis{geer,
+	Annotation = {This is a typical thesis entry for a PhD thesis. Note the type field in the database file which uses a localization key. Also note the format of the printed name and compare the useprefix option in the options field as well as vangennep},
+	Author = {de Geer, Ingrid},
+	Date = 1985,
+	Hyphenation = {british},
+	Institution = {Uppsala Universitet},
+	Location = {Uppsala},
+	Options = {useprefix=false},
+	Subtitle = {The {Orkney} Earldom of the Twelfth Century. {A} Musicological Study},
+	Title = {Earl, Saint, Bishop, Skald~-- and Music},
+	Type = {phdthesis}}
+
+@thesis{loh,
+	Annotation = {This is a typical thesis entry for an MA thesis. Note the type field in the database file which uses a localization key},
+	Author = {Loh, Nin C.},
+	Date = 1992,
+	Hyphenation = {american},
+	Institution = {Massachusetts Institute of Technology},
+	Location = {Cambridge, Mass.},
+	Title = {High-Resolution Micromachined Interferometric Accelerometer},
+	Type = {mathesis}}
+
+^D
+---
+nocite: "[@*]"
+references:
+- annote: This is a typical thesis entry for a PhD thesis. Note the type
+    field in the database file which uses a localization key. Also note
+    the format of the printed name and compare the useprefix option in
+    the options field as well as vangennep
+  author:
+  - dropping-particle: de
+    family: Geer
+    given: Ingrid
+  genre: PhD thesis
+  id: geer
+  issued: 1985
+  language: en-GB
+  publisher: Uppsala Universitet
+  publisher-place: Uppsala
+  title: "Earl, saint, bishop, skald -- and music: The Orkney earldom of
+    the twelfth century. A musicological study"
+  title-short: Earl, saint, bishop, skald -- and music
+  type: thesis
+- annote: This is a typical thesis entry for an MA thesis. Note the type
+    field in the database file which uses a localization key
+  author:
+  - family: Loh
+    given: Nin C.
+  genre: Master's thesis
+  id: loh
+  issued: 1992
+  language: en-US
+  publisher: Massachusetts Institute of Technology
+  publisher-place: Cambridge, Mass.
+  title: High-resolution micromachined interferometric accelerometer
+  type: thesis
+---
+
+
+```
diff --git a/test/command/biblatex-title-and-shorttitle.md b/test/command/biblatex-title-and-shorttitle.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-title-and-shorttitle.md
@@ -0,0 +1,76 @@
+```
+% pandoc -f biblatex -t markdown -s
+@comment{
+
+TODO:
+Slight inconsistency:
+When a biblatex “title” field contains a colon, the part before the colon is mapped to CSL “title-short”.
+When there’s a biblatex “title” and a “subtitle” field, CSL “title-short” is not set, though it would make at least as much sense to map “title” (without “subtitle”) to CSL “title-short” in this case.
+
+CSL “container-title-short” could also be set
+- from biblatex “shortjournal”
+- for inbook, incollection etc. from the “shorttitle” field of the cross-referenced book, collection etc. entry (see item5, item6)
+... but it might not really be worth it, “container-title-short” not being used once in my sample of 70+ CSL styles.
+
+}
+
+@book{item4,
+	Shorttitle = {The Shorttitle},
+	Subtitle = {And a Subtitle, in Two Separate Fields; plus a Separate “Shorttitle” Field},
+	Title = {The Title: With a Colon in the “Title” Field}}
+
+@book{item3,
+	Subtitle = {And a Subtitle, in two separate fields},
+	Title = {The Title: With a Colon in the “title” field}}
+
+@book{item2,
+	Subtitle = {The Subtitle, In Two Separate fields},
+	Title = {The Title}}
+
+@book{item1,
+	Title = {The Title: And the Subtitle, all in the “title” Field}}
+
+@inbook{item5,
+	Title = {The inbook Title: And the Subtitle, all in the “title” Field},
+	Crossref = {item6}}
+
+@book{item6,
+	Title = {The Title: And the Subtitle, all in the “title” Field},
+	Shorttitle = {The Shorttitle},
+}
+^D
+---
+nocite: "[@*]"
+references:
+- id: item4
+  title: "The title: With a colon in the \"title\" field: And a subtitle,
+    in two separate fields; plus a separate \"shorttitle\" field"
+  title-short: The shorttitle
+  type: book
+- id: item3
+  title: "The title: With a colon in the \"title\" field: And a subtitle,
+    in two separate fields"
+  title-short: The title
+  type: book
+- id: item2
+  title: "The title: The subtitle, in two separate fields"
+  title-short: The title
+  type: book
+- id: item1
+  title: "The title: And the subtitle, all in the \"title\" field"
+  title-short: The title
+  type: book
+- container-title: "The title: And the subtitle, all in the \"title\"
+    field"
+  id: item5
+  title: "The inbook title: And the subtitle, all in the \"title\" field"
+  title-short: The inbook title
+  type: chapter
+- id: item6
+  title: "The title: And the subtitle, all in the \"title\" field"
+  title-short: The shorttitle
+  type: book
+---
+
+
+```
diff --git a/test/command/biblatex-vangennep-related.md b/test/command/biblatex-vangennep-related.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-vangennep-related.md
@@ -0,0 +1,69 @@
+```
+% pandoc -f biblatex -t markdown -s
+@comment{
+
+Adapted from biblatex-example.bib
+
+
+Formatted with pandoc and chicago-author-date.csl, 2013-10-23:
+
+(van Gennep 1909)
+
+van Gennep, Arnold. 1909. *Les rites de passage*. Paris: Nourry.
+
+
+Formatted with pandoc and apa.csl, 2013-10-23:
+
+(van Gennep, 1909)
+
+van Gennep, A. (1909). *Les rites de passage*. Paris: Nourry.
+
+NOTES:
+
+- biblio2yaml
+	- "related = {vizedom:related}, relatedtype = {bytranslator}": no equivalent implemented in CSL
+	- "options = {useprefix}," is shorthand for "options = {useprefix=true},"
+
+
+}
+
+@Book{vangennep:related,
+  author       = {van Gennep, Arnold},
+  title        = {Les rites de passage},
+  date         = 1909,
+  publisher    = {Nourry},
+  location     = {Paris},
+  options      = {useprefix},
+  hyphenation  = {french},
+  related      = {vizedom:related},
+  relatedtype  = {bytranslator},
+  sorttitle    = {Rites de passage},
+  indextitle   = {Rites de passage, Les},
+  shorttitle   = {Rites de passage},
+  annotation   = {A variant of the vangennep entry related to its
+                  translation. Note the format of the related and
+                  relatedtype fields},
+}
+
+^D
+---
+nocite: "[@*]"
+references:
+- annote: A variant of the vangennep entry related to its translation.
+    Note the format of the related and relatedtype fields
+  author:
+  - family: Gennep
+    given: Arnold
+    non-dropping-particle: van
+  id: "vangennep:related"
+  issued: 1909
+  language: fr-FR
+  publisher: Nourry
+  publisher-place: Paris
+  title: Les rites de passage
+  title-short: Rites de passage
+  type: book
+---
+
+
+```
diff --git a/test/command/biblatex-vangennep-trans.md b/test/command/biblatex-vangennep-trans.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-vangennep-trans.md
@@ -0,0 +1,69 @@
+```
+% pandoc -f biblatex -t markdown -s
+@comment{
+
+Adapted from biblatex-example.bib
+
+
+Formatted with pandoc and chicago-author-date.csl, 2013-10-23:
+
+(van Gennep 1960)
+
+van Gennep, Arnold. 1960. *The Rites of Passage*. Translated by Monika
+B. Vizedom and Gabrielle L. Caffee. University of Chicago Press.
+
+
+Formatted with pandoc and apa.csl, 2013-10-23:
+
+(van Gennep, 1960)
+
+van Gennep, A. (1960). *The rites of passage*. (M. B. Vizedom & G. L.
+Caffee, Trans.). University of Chicago Press.
+
+
+}
+
+@Book{vangennep:trans,
+  author       = {van Gennep, Arnold},
+  title        = {The Rites of Passage},
+  year         = 1960,
+  translator   = {Vizedom, Monika B. and Caffee, Gabrielle L.},
+  language     = {english},
+  origlanguage = {french},
+  publisher    = {University of Chicago Press},
+  options      = {useprefix},
+  indextitle   = {Rites of Passage, The},
+  sorttitle    = {Rites of Passage},
+  shorttitle   = {Rites of Passage},
+  hyphenation  = {american},
+  annotation   = {A translation of the vangennep entry. Note the
+                  translator and origlanguage fields. Compare
+                  with the vangennep:related entry.},
+}
+
+^D
+---
+nocite: "[@*]"
+references:
+- annote: "A translation of the vangennep entry. Note the translator and
+    origlanguage fields. Compare with the vangennep:related entry."
+  author:
+  - family: Gennep
+    given: Arnold
+    non-dropping-particle: van
+  id: "vangennep:trans"
+  issued: 1960
+  language: en-US
+  publisher: University of Chicago Press
+  title: The rites of passage
+  title-short: Rites of passage
+  translator:
+  - family: Vizedom
+    given: Monika B.
+  - family: Caffee
+    given: Gabrielle L.
+  type: book
+---
+
+
+```
diff --git a/test/command/biblatex-vangennep.md b/test/command/biblatex-vangennep.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-vangennep.md
@@ -0,0 +1,61 @@
+```
+% pandoc -f biblatex -t markdown -s
+@comment{
+
+Adapted from biblatex-example.bib
+
+
+Formatted with pandoc and chicago-author-date.csl, 2013-10-23:
+
+(van Gennep 1909)
+
+van Gennep, Arnold. 1909. *Les rites de passage*. Paris: Nourry.
+
+
+Formatted with pandoc and apa.csl, 2013-10-23:
+
+(van Gennep, 1909)
+
+van Gennep, A. (1909). *Les rites de passage*. Paris: Nourry.
+
+
+}
+
+@Book{vangennep,
+  author       = {van Gennep, Arnold},
+  title        = {Les rites de passage},
+  date         = 1909,
+  publisher    = {Nourry},
+  location     = {Paris},
+  options      = {useprefix},
+  hyphenation  = {french},
+  sorttitle    = {Rites de passage},
+  indextitle   = {Rites de passage, Les},
+  shorttitle   = {Rites de passage},
+  annotation   = {A book entry. Note the format of the printed name and
+                  compare the useprefix option in the options
+                  field as well as brandt and geer},
+}
+
+^D
+---
+nocite: "[@*]"
+references:
+- annote: A book entry. Note the format of the printed name and compare
+    the useprefix option in the options field as well as brandt and geer
+  author:
+  - family: Gennep
+    given: Arnold
+    non-dropping-particle: van
+  id: vangennep
+  issued: 1909
+  language: fr-FR
+  publisher: Nourry
+  publisher-place: Paris
+  title: Les rites de passage
+  title-short: Rites de passage
+  type: book
+---
+
+
+```
diff --git a/test/command/biblatex-vazques-de-parga-mvbook.md b/test/command/biblatex-vazques-de-parga-mvbook.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-vazques-de-parga-mvbook.md
@@ -0,0 +1,75 @@
+```
+% pandoc -f biblatex -t markdown -s
+@comment{
+
+Adapted from biblatex-example.bib
+
+
+Formatted with pandoc and chicago-author-date.csl, 2013-10-23:
+
+(Vázques de Parga, Lacarra, and Uría Ríu 1993)
+
+Vázques de Parga, Luis, José María Lacarra, and Juan Uría Ríu. 1993.
+*Las Peregrinaciones a Santiago de Compostela*. 3. Pamplona: Iberdrola.
+
+
+Formatted with pandoc and apa.csl, 2013-10-23:
+
+(Vázques de Parga, Lacarra, & Uría Ríu, 1993)
+
+Vázques de Parga, L., Lacarra, J. M., & Uría Ríu, J. (1993). *Las
+Peregrinaciones a Santiago de Compostela* (1-3). Pamplona: Iberdrola.
+
+
+NOTES:
+
+- citeproc
+	- term "vols." missing
+
+}
+
+@mvbook{vazques-de-parga,
+  author       = {V{\'a}zques{ de }Parga, Luis and Lacarra, Jos{\'e} Mar{\'i}a
+                  and Ur{\'i}a R{\'i}u, Juan},
+  title        = {Las Peregrinaciones a Santiago de Compostela},
+  date         = 1993,
+  volumes      = 3,
+  note         = {Ed. facs. de la realizada en 1948--49},
+  publisher    = {Iberdrola},
+  location     = {Pamplona},
+  hyphenation  = {spanish},
+  sorttitle    = {Peregrinaciones a Santiago de Compostela},
+  indextitle   = {Peregrinaciones a Santiago de Compostela, Las},
+  shorttitle   = {Peregrinaciones},
+  annotation   = {A multivolume book cited as a whole. This is a book
+                  entry with volumes, note,
+                  sorttitle, and indextitle fields},
+}
+
+^D
+---
+nocite: "[@*]"
+references:
+- annote: A multivolume book cited as a whole. This is a book entry with
+    volumes, note, sorttitle, and indextitle fields
+  author:
+  - family: Vázques de Parga
+    given: Luis
+  - family: Lacarra
+    given: José María
+  - family: Uría Ríu
+    given: Juan
+  id: vazques-de-parga
+  issued: 1993
+  language: es-ES
+  note: Ed. facs. de la realizada en 1948--49
+  number-of-volumes: 3
+  publisher: Iberdrola
+  publisher-place: Pamplona
+  title: Las Peregrinaciones a Santiago de Compostela
+  title-short: Peregrinaciones
+  type: book
+---
+
+
+```
diff --git a/test/command/biblatex-vazques-de-parga.md b/test/command/biblatex-vazques-de-parga.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-vazques-de-parga.md
@@ -0,0 +1,74 @@
+```
+% pandoc -f biblatex -t markdown -s
+@comment{
+
+Adapted from biblatex-example.bib
+
+Formatted with pandoc and chicago-author-date.csl, 2013-10-23:
+
+(Vázques de Parga, Lacarra, and Uría Ríu 1993)
+
+Vázques de Parga, Luis, José María Lacarra, and Juan Uría Ríu. 1993.
+*Las Peregrinaciones a Santiago de Compostela*. 3. Pamplona: Iberdrola.
+
+
+Formatted with pandoc and apa.csl, 2013-10-23:
+
+(Vázques de Parga, Lacarra, & Uría Ríu, 1993)
+
+Vázques de Parga, L., Lacarra, J. M., & Uría Ríu, J. (1993). *Las
+Peregrinaciones a Santiago de Compostela* (1-3). Pamplona: Iberdrola.
+
+
+NOTES:
+
+- citeproc
+	- term "vols." missing
+
+}
+
+@Book{vazques-de-parga,
+  author       = {V{\'a}zques{ de }Parga, Luis and Lacarra, Jos{\'e} Mar{\'i}a
+                  and Ur{\'i}a R{\'i}u, Juan},
+  title        = {Las Peregrinaciones a Santiago de Compostela},
+  date         = 1993,
+  volumes      = 3,
+  note         = {Ed. facs. de la realizada en 1948--49},
+  publisher    = {Iberdrola},
+  location     = {Pamplona},
+  hyphenation  = {spanish},
+  sorttitle    = {Peregrinaciones a Santiago de Compostela},
+  indextitle   = {Peregrinaciones a Santiago de Compostela, Las},
+  shorttitle   = {Peregrinaciones},
+  annotation   = {A multivolume book cited as a whole. This is a book
+                  entry with volumes, note,
+                  sorttitle, and indextitle fields},
+}
+
+^D
+---
+nocite: "[@*]"
+references:
+- annote: A multivolume book cited as a whole. This is a book entry with
+    volumes, note, sorttitle, and indextitle fields
+  author:
+  - family: Vázques de Parga
+    given: Luis
+  - family: Lacarra
+    given: José María
+  - family: Uría Ríu
+    given: Juan
+  id: vazques-de-parga
+  issued: 1993
+  language: es-ES
+  note: Ed. facs. de la realizada en 1948--49
+  number-of-volumes: 3
+  publisher: Iberdrola
+  publisher-place: Pamplona
+  title: Las Peregrinaciones a Santiago de Compostela
+  title-short: Peregrinaciones
+  type: book
+---
+
+
+```
diff --git a/test/command/biblatex-video.md b/test/command/biblatex-video.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-video.md
@@ -0,0 +1,19 @@
+```
+% pandoc -f biblatex -t markdown -s
+@video{x1,title={blah}}
+@movie{x2,title={blah}}
+
+^D
+---
+nocite: "[@*]"
+references:
+- id: x1
+  title: Blah
+  type: motion_picture
+- id: x2
+  title: Blah
+  type: motion_picture
+---
+
+
+```
diff --git a/test/command/biblatex-vizedom-related.md b/test/command/biblatex-vizedom-related.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-vizedom-related.md
@@ -0,0 +1,68 @@
+```
+% pandoc -f biblatex -t markdown -s
+@comment{
+
+Adapted from biblatex-example.bib
+
+Formatted with pandoc and chicago-author-date.csl, 2013-10-23:
+
+(Vizedom and Caffee 1960)
+
+Vizedom, Monika B., and Gabrielle L. Caffee, trans. 1960. *The Rites of
+Passage*. University of Chicago Press.
+
+
+Formatted with pandoc and apa.csl, 2013-10-23:
+
+(Vizedom & Caffee, 1960)
+
+Vizedom, M. B., & Caffee, G. L. (Trans.). (1960). *The rites of
+passage*. University of Chicago Press.
+
+
+NOTES:
+
+- biblio2yaml
+	- "related = {vangennep}, relatedtype = {translationof}": no equivalent implemented in CSL
+
+}
+
+@Book{vizedom:related,
+  title        = {The Rites of Passage},
+  year         = 1960,
+  translator   = {Vizedom, Monika B. and Caffee, Gabrielle L.},
+  language     = {english},
+  publisher    = {University of Chicago Press},
+  hyphenation  = {american},
+  options      = {usetranslator},
+  related      = {vangennep},
+  relatedtype  = {translationof},
+  indextitle   = {Rites of Passage, The},
+  sorttitle    = {Rites of Passage},
+  shorttitle   = {Rites of Passage},
+  annotation   = {A translated work from vangennep. Note the format of
+                  the related and relatedtype fields},
+}
+
+^D
+---
+nocite: "[@*]"
+references:
+- annote: A translated work from vangennep. Note the format of the
+    related and relatedtype fields
+  id: "vizedom:related"
+  issued: 1960
+  language: en-US
+  publisher: University of Chicago Press
+  title: The rites of passage
+  title-short: Rites of passage
+  translator:
+  - family: Vizedom
+    given: Monika B.
+  - family: Caffee
+    given: Gabrielle L.
+  type: book
+---
+
+
+```
diff --git a/test/command/biblatex-wassenberg.md b/test/command/biblatex-wassenberg.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-wassenberg.md
@@ -0,0 +1,83 @@
+```
+% pandoc -f biblatex -t markdown -s
+@comment{
+
+Adapted from biblatex-example.bib
+
+Formatted with pandoc and chicago-author-date.csl, 2013-10-23:
+
+(Wassenberg and Sanders 2010)
+
+Wassenberg, Jan, and Peter Sanders. 2010. “Faster Radix Sort via Virtual
+Memory and Write-combining” (version 1). August 17.
+
+
+Formatted with pandoc and apa.csl, 2013-10-23:
+
+(Wassenberg & Sanders, 2010)
+
+Wassenberg, J., & Sanders, P. (2010, August 17). Faster radix sort via
+virtual memory and write-combining.
+
+
+NOTES:
+
+- biblio2yaml
+	- "eprinttype = {arxiv}, eprintclass = {cs.DS}, eprint = {1008.2849v1}" should be used to reconstruct a Url: http://arxiv.org/abs/1008.2849v1 ("cs.DS" does not seem to be essential)
+
+}
+
+@Online{wassenberg,
+  author       = {Wassenberg, Jan and Sanders, Peter},
+  title        = {Faster Radix Sort via Virtual Memory and Write-Combining},
+  date         = {2010-08-17},
+  version      = 1,
+  hyphenation  = {american},
+  eprinttype   = {arxiv},
+  eprintclass  = {cs.DS},
+  eprint       = {1008.2849v1},
+  annotation   = {A recent online reference from arXiv using the new
+                  (April 2007 onward) identifier format. Note the
+                  eprint, eprinttype, and eprintclass
+                  fields. Also note that the arXiv reference is transformed into
+                  a clickable link if hyperref support has been
+                  enabled},
+  abstract     = {Sorting algorithms are the deciding factor for the performance
+                  of common operations such as removal of duplicates or database
+                  sort-merge joins. This work focuses on 32-bit integer keys,
+                  optionally paired with a 32-bit value. We present a fast radix
+                  sorting algorithm that builds upon a microarchitecture-aware
+                  variant of counting sort},
+}
+
+^D
+---
+nocite: "[@*]"
+references:
+- abstract: Sorting algorithms are the deciding factor for the
+    performance of common operations such as removal of duplicates or
+    database sort-merge joins. This work focuses on 32-bit integer keys,
+    optionally paired with a 32-bit value. We present a fast radix
+    sorting algorithm that builds upon a microarchitecture-aware variant
+    of counting sort
+  annote: A recent online reference from arXiv using the new (April 2007
+    onward) identifier format. Note the eprint, eprinttype, and
+    eprintclass fields. Also note that the arXiv reference is
+    transformed into a clickable link if hyperref support has been
+    enabled
+  author:
+  - family: Wassenberg
+    given: Jan
+  - family: Sanders
+    given: Peter
+  id: wassenberg
+  issued: 2010-08-17
+  language: en-US
+  title: Faster radix sort via virtual memory and write-combining
+  type: webpage
+  url: "https://arxiv.org/abs/1008.2849v1"
+  version: 1
+---
+
+
+```
diff --git a/test/command/biblatex-weinberg.md b/test/command/biblatex-weinberg.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-weinberg.md
@@ -0,0 +1,52 @@
+```
+% pandoc -f biblatex -t markdown -s
+@comment{
+
+Adapted from biblatex-example.bib
+
+
+Formatted with pandoc and chicago-author-date.csl, 2013-10-23:
+
+(Weinberg 1967)
+
+Weinberg, Steven. 1967. “A Model of Leptons.” *Phys. Rev. Lett.* 19:
+1264–1266.
+
+
+Formatted with pandoc and apa.csl, 2013-10-23:
+
+(Weinberg, 1967)
+
+Weinberg, S. (1967). A model of leptons. *Phys. Rev. Lett.*, *19*,
+1264–1266.
+
+
+}
+
+@Article{weinberg,
+  author       = {Weinberg, Steven},
+  title        = {A Model of Leptons},
+  journaltitle = {Phys.~Rev.~Lett.},
+  date         = 1967,
+  volume       = 19,
+  pages        = {1264-1266},
+}
+
+^D
+---
+nocite: "[@*]"
+references:
+- author:
+  - family: Weinberg
+    given: Steven
+  container-title: Phys. Rev. Lett.
+  id: weinberg
+  issued: 1967
+  page: 1264-1266
+  title: A model of leptons
+  type: article-journal
+  volume: 19
+---
+
+
+```
diff --git a/test/command/biblatex-westfahl-frontier.md b/test/command/biblatex-westfahl-frontier.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-westfahl-frontier.md
@@ -0,0 +1,60 @@
+```
+% pandoc -f biblatex -t markdown -s
+@comment{
+
+Adapted from biblatex-example.bib
+
+Formatted with pandoc and chicago-author-date.csl, 2013-10-23:
+
+(Westfahl 2000)
+
+Westfahl, Gary, ed. 2000. *Space and Beyond: The Frontier Theme in
+Science Fiction*. Westport, Conn.; London: Greenwood.
+
+
+Formatted with pandoc and apa.csl, 2013-10-23:
+
+(Westfahl, 2000)
+
+Westfahl, G. (Ed.). (2000). *Space and beyond: The frontier theme in
+science fiction*. Westport, Conn.; London: Greenwood.
+
+
+}
+
+@Collection{westfahl:frontier,
+  editor       = {Westfahl, Gary},
+  title        = {Space and Beyond},
+  date         = 2000,
+  subtitle     = {The Frontier Theme in Science Fiction},
+  publisher    = {Greenwood},
+  location     = {Westport, Conn. and London},
+  hyphenation  = {american},
+  booktitle    = {Space and Beyond},
+  booksubtitle = {The Frontier Theme in Science Fiction},
+  annotation   = {This is a collection entry. Note the format of the
+                  location field as well as the subtitle and
+                  booksubtitle fields},
+}
+
+^D
+---
+nocite: "[@*]"
+references:
+- annote: This is a collection entry. Note the format of the location
+    field as well as the subtitle and booksubtitle fields
+  editor:
+  - family: Westfahl
+    given: Gary
+  id: "westfahl:frontier"
+  issued: 2000
+  language: en-US
+  publisher: Greenwood
+  publisher-place: Westport, Conn.; London
+  title: "Space and beyond: The frontier theme in science fiction"
+  title-short: Space and beyond
+  type: book
+---
+
+
+```
diff --git a/test/command/biblatex-westfahl-space.md b/test/command/biblatex-westfahl-space.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-westfahl-space.md
@@ -0,0 +1,106 @@
+```
+% pandoc -f biblatex -t markdown -s
+@comment{
+
+Adapted from biblatex-example.bib
+
+
+Formatted with pandoc and chicago-author-date.csl, 2013-10-23:
+
+(Westfahl 2000a) (Westfahl 2000b)
+
+Westfahl, Gary. 2000a. “The True Frontier: Confronting and Avoiding the
+Realities of Space in American Science Fiction Films.” In *Space and
+Beyond: The Frontier Theme in Science Fiction*, edited by Gary Westfahl,
+55–65. Westport, Conn.; London: Greenwood.
+
+———, ed. 2000b. *Space and Beyond: The Frontier Theme in Science
+Fiction*. Westport, Conn.; London: Greenwood.
+
+
+Formatted with pandoc and apa.csl, 2013-10-23:
+
+(Westfahl, 2000) (Westfahl, 2000)
+
+Westfahl, G. (2000). The true frontier: Confronting and avoiding the
+realities of space in American science fiction films. In G. Westfahl
+(Ed.), *Space and beyond: The frontier theme in science fiction* (pp.
+55–65). Westport, Conn.; London: Greenwood.
+
+Westfahl, G. (Ed.). (2000). *Space and beyond: The frontier theme in
+science fiction*. Westport, Conn.; London: Greenwood.
+
+
+}
+
+@InCollection{westfahl:space,
+  author       = {Westfahl, Gary},
+  title        = {The True Frontier},
+  subtitle     = {Confronting and Avoiding the Realities of Space in {American}
+                  Science Fiction Films},
+  pages        = {55-65},
+  crossref     = {westfahl:frontier},
+  hyphenation  = {american},
+  indextitle   = {True Frontier, The},
+  annotation   = {A cross-referenced article from a collection. This is
+                  an incollection entry with a crossref
+                  field. Note the subtitle and indextitle
+                  fields},
+}
+
+@Collection{westfahl:frontier,
+  editor       = {Westfahl, Gary},
+  title        = {Space and Beyond},
+  date         = 2000,
+  subtitle     = {The Frontier Theme in Science Fiction},
+  publisher    = {Greenwood},
+  location     = {Westport, Conn. and London},
+  hyphenation  = {american},
+  booktitle    = {Space and Beyond},
+  booksubtitle = {The Frontier Theme in Science Fiction},
+  annotation   = {This is a collection entry. Note the format of the
+                  location field as well as the subtitle and
+                  booksubtitle fields},
+}
+^D
+---
+nocite: "[@*]"
+references:
+- annote: A cross-referenced article from a collection. This is an
+    incollection entry with a crossref field. Note the subtitle and
+    indextitle fields
+  author:
+  - family: Westfahl
+    given: Gary
+  container-title: "Space and beyond: The frontier theme in science
+    fiction"
+  editor:
+  - family: Westfahl
+    given: Gary
+  id: "westfahl:space"
+  issued: 2000
+  language: en-US
+  page: 55-65
+  publisher: Greenwood
+  publisher-place: Westport, Conn.; London
+  title: "The true frontier: Confronting and avoiding the realities of
+    space in American science fiction films"
+  title-short: The true frontier
+  type: chapter
+- annote: This is a collection entry. Note the format of the location
+    field as well as the subtitle and booksubtitle fields
+  editor:
+  - family: Westfahl
+    given: Gary
+  id: "westfahl:frontier"
+  issued: 2000
+  language: en-US
+  publisher: Greenwood
+  publisher-place: Westport, Conn.; London
+  title: "Space and beyond: The frontier theme in science fiction"
+  title-short: Space and beyond
+  type: book
+---
+
+
+```
diff --git a/test/command/biblatex-wilde.md b/test/command/biblatex-wilde.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-wilde.md
@@ -0,0 +1,65 @@
+```
+% pandoc -f biblatex -t markdown -s
+@comment{
+
+Adapted from biblatex-example.bib
+
+
+Formatted with pandoc and chicago-author-date.csl, 2013-10-23:
+
+(Wilde 1899)
+
+Wilde, Oscar. 1899. *The Importance of Being Earnest: A Trivial Comedy
+for Serious People*. English and American Drama of the Nineteenth
+Century. Leonard Smithers and Company.
+
+
+Formatted with pandoc and apa.csl, 2013-10-23:
+
+(Wilde, 1899)
+
+Wilde, O. (1899). *The importance of being earnest: A trivial comedy for
+serious people*. Leonard Smithers and Company.
+
+
+NOTES:
+
+- biblio2yaml
+	- From "eprint = {4HIWAAAAYAAJ}, eprinttype = {googlebooks}", a url could be reconstructed, shortest form: http://books.google.com?id=4HIWAAAAYAAJ
+
+}
+
+@Book{wilde,
+  author       = {Wilde, Oscar},
+  title        = {The Importance of Being Earnest: {A} Trivial Comedy for Serious
+                  People},
+  year         = 1899,
+  series       = {English and American drama of the Nineteenth Century},
+  publisher    = {Leonard Smithers {and} Company},
+  eprint       = {4HIWAAAAYAAJ},
+  eprinttype   = {googlebooks},
+  annotation   = {A book with eprint and eprinttype
+                  fields.},
+}
+
+^D
+---
+nocite: "[@*]"
+references:
+- annote: A book with eprint and eprinttype fields.
+  author:
+  - family: Wilde
+    given: Oscar
+  collection-title: English and american drama of the nineteenth century
+  id: wilde
+  issued: 1899
+  publisher: Leonard Smithers and Company
+  title: "The importance of being earnest: A trivial comedy for serious
+    people"
+  title-short: The importance of being earnest
+  type: book
+  url: "https://books.google.com?id=4HIWAAAAYAAJ"
+---
+
+
+```
diff --git a/test/command/biblatex-worman.md b/test/command/biblatex-worman.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-worman.md
@@ -0,0 +1,60 @@
+```
+% pandoc -f biblatex -t markdown -s
+@comment{
+
+Adapted from biblatex-example.bib
+
+
+Formatted with pandoc and chicago-author-date.csl, 2013-10-23:
+
+(Worman 2002)
+
+Worman, Nancy. 2002. *The Cast of Character: Style in Greek Literature*.
+Austin: University of Texas Press.
+
+
+Formatted with pandoc and apa.csl, 2013-10-23:
+
+(Worman, 2002)
+
+Worman, N. (2002). *The cast of character: Style in Greek literature*.
+Austin: University of Texas Press.
+
+
+}
+
+@Book{worman,
+  author       = {Worman, Nancy},
+  title        = {The Cast of Character},
+  date         = 2002,
+  publisher    = {University of Texas Press},
+  location     = {Austin},
+  hyphenation  = {american},
+  sorttitle    = {Cast of Character},
+  indextitle   = {Cast of Character, The},
+  subtitle     = {Style in {Greek} Literature},
+  shorttitle   = {Cast of Character},
+  annotation   = {A book entry. Note the sorttitle and
+                  indextitle fields},
+}
+
+^D
+---
+nocite: "[@*]"
+references:
+- annote: A book entry. Note the sorttitle and indextitle fields
+  author:
+  - family: Worman
+    given: Nancy
+  id: worman
+  issued: 2002
+  language: en-US
+  publisher: University of Texas Press
+  publisher-place: Austin
+  title: "The cast of character: Style in Greek literature"
+  title-short: Cast of character
+  type: book
+---
+
+
+```
diff --git a/test/command/biblatex-yoon.md b/test/command/biblatex-yoon.md
new file mode 100644
--- /dev/null
+++ b/test/command/biblatex-yoon.md
@@ -0,0 +1,67 @@
+```
+% pandoc -f biblatex -t markdown -s
+@comment{
+
+Adapted from biblatex-example.bib
+
+
+Formatted with pandoc and chicago-author-date.csl, 2013-10-23:
+
+(Yoon et al. 2006)
+
+Yoon, Myeong S., Dowook Ryu, Jeongryul Kim, and Kyo Han Ahn. 2006.
+“Palladium Pincer Complexes with Reduced Bond Angle Strain: Efficient
+Catalysts for the Heck Reaction.” *Organometallics* 25 (10): 2409–2411.
+
+
+Formatted with pandoc and apa.csl, 2013-10-23:
+
+(Yoon, Ryu, Kim, & Ahn, 2006)
+
+Yoon, M. S., Ryu, D., Kim, J., & Ahn, K. H. (2006). Palladium pincer
+complexes with reduced bond angle strain: Efficient catalysts for the
+Heck reaction. *Organometallics*, *25*(10), 2409–2411.
+
+
+}
+
+@Article{yoon,
+  author       = {Yoon, Myeong S. and Ryu, Dowook and Kim, Jeongryul and Ahn,
+                  Kyo Han},
+  title        = {Palladium pincer complexes with reduced bond angle strain:
+                  efficient catalysts for the {Heck} reaction},
+  journaltitle = {Organometallics},
+  date         = 2006,
+  volume       = 25,
+  number       = 10,
+  pages        = {2409-2411},
+  indextitle   = {Palladium pincer complexes},
+}
+
+^D
+---
+nocite: "[@*]"
+references:
+- author:
+  - family: Yoon
+    given: Myeong S.
+  - family: Ryu
+    given: Dowook
+  - family: Kim
+    given: Jeongryul
+  - family: Ahn
+    given: Kyo Han
+  container-title: Organometallics
+  id: yoon
+  issue: 10
+  issued: 2006
+  page: 2409-2411
+  title: "Palladium pincer complexes with reduced bond angle strain:
+    Efficient catalysts for the Heck reaction"
+  title-short: Palladium pincer complexes with reduced bond angle strain
+  type: article-journal
+  volume: 25
+---
+
+
+```
diff --git a/test/command/biblio.bib b/test/command/biblio.bib
new file mode 100644
--- /dev/null
+++ b/test/command/biblio.bib
@@ -0,0 +1,26 @@
+@Book{item1,
+author="John Doe",
+title="First Book",
+year="2005",
+address="Cambridge",
+publisher="Cambridge University Press"
+}
+
+@Article{item2,
+author="John Doe",
+title="Article",
+year="2006",
+journal="Journal of Generic Studies",
+volume="6",
+pages="33-34"
+}
+
+@InCollection{пункт3,
+author="John Doe and Jenny Roe",
+title="Why Water Is Wet",
+booktitle="Third Book",
+editor="Sam Smith",
+publisher="Oxford University Press",
+address="Oxford",
+year="2007"
+}
diff --git a/test/command/bibtex-basic.md b/test/command/bibtex-basic.md
new file mode 100644
--- /dev/null
+++ b/test/command/bibtex-basic.md
@@ -0,0 +1,71 @@
+```
+% pandoc -f biblatex -t markdown -s
+@Book{item1,
+author="John Doe",
+title="First Book",
+year="2005",
+address="Cambridge",
+publisher="Cambridge University Press"
+}
+
+@Article{item2,
+author="John Doe",
+title="Article",
+year="2006",
+journal="Journal of Generic Studies",
+volume="6",
+pages="33-34"
+}
+
+@InCollection{пункт3,
+author="John Doe and Jenny Roe",
+title="Why Water Is Wet",
+booktitle="Third Book",
+editor="Sam Smith",
+publisher="Oxford University Press",
+address="Oxford",
+year="2007"
+}
+
+^D
+---
+nocite: "[@*]"
+references:
+- author:
+  - family: Doe
+    given: John
+  id: item1
+  issued: 2005
+  publisher: Cambridge University Press
+  publisher-place: Cambridge
+  title: First book
+  type: book
+- author:
+  - family: Doe
+    given: John
+  container-title: Journal of Generic Studies
+  id: item2
+  issued: 2006
+  page: 33-34
+  title: Article
+  type: article-journal
+  volume: 6
+- author:
+  - family: Doe
+    given: John
+  - family: Roe
+    given: Jenny
+  container-title: Third book
+  editor:
+  - family: Smith
+    given: Sam
+  id: пункт3
+  issued: 2007
+  publisher: Oxford University Press
+  publisher-place: Oxford
+  title: Why water is wet
+  type: chapter
+---
+
+
+```
diff --git a/test/command/bioethics.csl b/test/command/bioethics.csl
new file mode 100644
--- /dev/null
+++ b/test/command/bioethics.csl
@@ -0,0 +1,226 @@
+<?xml version="1.0" encoding="utf-8"?>
+<style xmlns="http://purl.org/net/xbiblio/csl" class="note" version="1.0" page-range-format="minimal-two" demote-non-dropping-particle="never" default-locale="en-GB">
+  <info>
+    <title>Bioethics</title>
+    <id>http://www.zotero.org/styles/bioethics</id>
+    <link href="http://www.zotero.org/styles/bioethics" rel="self"/>
+    <link href="http://www.zotero.org/styles/journal-of-roman-archaeology-b" rel="template"/>
+    <link href="http://onlinelibrary.wiley.com/journal/10.1111/(ISSN)1467-8519/homepage/ForAuthors.html" rel="documentation"/>
+    <author>
+      <name>Patrick O'Brien</name>
+    </author>
+    <category citation-format="note"/>
+    <category field="anthropology"/>
+    <issn>0269-9702</issn>
+    <eissn>1467-8519</eissn>
+    <updated>2017-07-12T11:26:44+00:00</updated>
+    <rights license="http://creativecommons.org/licenses/by-sa/3.0/">This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 License</rights>
+  </info>
+  <macro name="editor">
+    <names variable="editor">
+      <name sort-separator=", " initialize-with="." delimiter=", "/>
+      <label form="short" prefix=", "/>
+      <substitute>
+        <text macro="container-author"/>
+      </substitute>
+    </names>
+  </macro>
+  <macro name="container-author">
+    <names variable="container-author" delimiter=", ">
+      <name sort-separator=", " initialize-with="." delimiter=", "/>
+    </names>
+  </macro>
+  <macro name="author">
+    <names variable="author">
+      <name initialize-with="."/>
+      <substitute>
+        <text macro="editor"/>
+        <text variable="title"/>
+      </substitute>
+    </names>
+  </macro>
+  <macro name="editor-short">
+    <names variable="editor">
+      <name form="short" sort-separator=", " delimiter=", "/>
+    </names>
+  </macro>
+  <macro name="container-author-short">
+    <names variable="container-author" delimiter=", ">
+      <name form="short" sort-separator=", " delimiter=", "/>
+      <et-al font-style="italic"/>
+    </names>
+  </macro>
+  <macro name="author-short">
+    <names variable="author">
+      <name form="short" sort-separator=", " delimiter=", "/>
+      <et-al font-style="italic"/>
+      <substitute>
+        <text macro="editor-short"/>
+        <text macro="container-author-short"/>
+        <text variable="title-short" font-style="italic"/>
+      </substitute>
+    </names>
+  </macro>
+  <macro name="collection">
+    <group delimiter=" " suffix=", ">
+      <text variable="collection-title"/>
+      <text variable="collection-number"/>
+    </group>
+  </macro>
+  <macro name="encyclopedia">
+    <group delimiter=" ">
+      <choose>
+        <if variable="title-short" match="any">
+          <text variable="title" form="short" font-style="italic"/>
+        </if>
+        <else>
+          <text variable="container-title" font-style="italic"/>
+        </else>
+      </choose>
+      <text variable="volume"/>
+      <date variable="issued" prefix="(" suffix=")">
+        <date-part name="year"/>
+      </date>
+      <text variable="page" suffix=","/>
+      <text variable="title" prefix="s.v. " quotes="true"/>
+      <text macro="author" prefix="(" suffix=")"/>
+    </group>
+  </macro>
+  <macro name="title">
+    <choose>
+      <if type="book thesis" match="any">
+        <text variable="title" font-style="italic"/>
+      </if>
+      <else-if type="webpage post-weblog" match="any">
+        <date form="text" variable="issued" suffix=". "/>
+        <text variable="title" font-style="italic" suffix=". "/>
+        <text variable="container-title" font-style="italic"/>
+      </else-if>
+      <else-if type="article-journal article-magazine article-newspaper" match="any">
+        <group delimiter=". ">
+          <text variable="title" quotes="false"/>
+          <group delimiter=" ">
+            <text variable="container-title" form="short" strip-periods="true" font-style="italic"/>
+            <group delimiter="; ">
+              <text macro="year-date"/>
+              <group delimiter=": ">
+                <group>
+                  <text variable="volume"/>
+                  <text variable="issue" prefix="(" suffix=")"/>
+                </group>
+                <text variable="page"/>
+              </group>
+            </group>
+          </group>
+        </group>
+      </else-if>
+      <else-if type="chapter paper-conference" match="any">
+        <group delimiter=". " suffix=". ">
+          <text macro="year-date"/>
+          <text variable="title" quotes="false"/>
+        </group>
+        <group delimiter=". ">
+          <group delimiter=" ">
+            <text term="in" text-case="capitalize-first"/>
+            <text macro="editor"/>
+          </group>
+          <text variable="container-title"/>
+        </group>
+      </else-if>
+      <else>
+        <text variable="title" font-style="italic" font-weight="bold"/>
+      </else>
+    </choose>
+  </macro>
+  <macro name="publisher">
+    <choose>
+      <if variable="collection-title" match="any">
+        <text macro="collection"/>
+      </if>
+      <else-if type="thesis">
+        <text variable="genre" suffix=","/>
+        <text variable="publisher"/>
+      </else-if>
+      <else>
+        <group delimiter=": ">
+          <text variable="publisher-place"/>
+          <text variable="publisher"/>
+        </group>
+      </else>
+    </choose>
+  </macro>
+  <macro name="year-date">
+    <choose>
+      <if variable="issued">
+        <date variable="issued">
+          <date-part name="year"/>
+        </date>
+      </if>
+      <else>
+        <text term="no date" form="short"/>
+      </else>
+    </choose>
+  </macro>
+  <macro name="locator">
+    <choose>
+      <if locator="page">
+        <text variable="locator" prefix=": "/>
+      </if>
+      <else-if locator="paragraph">
+        <text variable="locator" prefix="§"/>
+      </else-if>
+      <else-if type="webpage post-weblog" match="any">
+        <group delimiter=" " prefix=". ">
+          <group delimiter=": ">
+            <text term="available at" text-case="capitalize-first"/>
+            <text variable="URL"/>
+          </group>
+          <group delimiter=" " prefix="[" suffix="]">
+            <text term="accessed" text-case="capitalize-first"/>
+            <date form="text" variable="accessed"/>
+          </group>
+        </group>
+      </else-if>
+      <else>
+        <text variable="page" prefix=": "/>
+      </else>
+    </choose>
+  </macro>
+  <citation and="symbol" delimiter-precedes-et-al="always" delimiter-precedes-last="always" et-al-min="3" et-al-use-first="1">
+    <layout delimiter="; " suffix=".">
+      <choose>
+        <if type="entry-dictionary entry-encyclopedia" match="any">
+          <text macro="encyclopedia"/>
+        </if>
+        <else-if position="ibid-with-locator">
+          <group delimiter=" ">
+            <text term="ibid" suffix="."/>
+            <text macro="locator"/>
+          </group>
+        </else-if>
+        <else-if position="ibid">
+          <text term="ibid" suffix="."/>
+        </else-if>
+        <else-if position="subsequent">
+          <group delimiter=" ">
+            <text macro="author-short"/>
+            <group prefix="(" suffix=")" delimiter=" ">
+              <text term="cited"/>
+              <group delimiter="&#160;">
+                <text term="note" form="short"/>
+                <text variable="first-reference-note-number"/>
+              </group>
+            </group>
+            <text macro="locator"/>
+          </group>
+        </else-if>
+        <else>
+          <text macro="author" suffix=". "/>
+          <text macro="title"/>
+          <text macro="publisher" prefix=". "/>
+          <text macro="locator"/>
+        </else>
+      </choose>
+    </layout>
+  </citation>
+</style>
diff --git a/test/command/bits-book-meta.md b/test/command/bits-book-meta.md
new file mode 100644
--- /dev/null
+++ b/test/command/bits-book-meta.md
@@ -0,0 +1,104 @@
+```
+% pandoc -f jats -t native -s
+<book>
+    <book-meta>
+		<book-id book-id-type="publisher">handbook-648</book-id>
+  		<book-title-group>
+   			<book-title>The NCBI Handbook</book-title>
+  		</book-title-group>
+  		<contrib-group>
+   			<contrib contrib-type="author">
+    			<name><surname>McEntyre</surname>
+     			<given-names>Jo</given-names></name>
+    			<xref ref-type="aff" rid="bid.m.1"/>
+   			</contrib>
+   			<contrib contrib-type="editor">
+    			<name><surname>Ostell</surname>
+     			<given-names>Jim</given-names></name>
+    			<xref ref-type="aff" rid="bid.m.1"/>
+   			</contrib>
+  		</contrib-group>
+  		<aff id="bid.m.1">
+   			<institution>National Center for Biotechnology Information (NCBI), National Library of Medicine, National Institutes of Health</institution>, <addr-line>Bethesda, MD 20892-6510</addr-line>
+  		</aff>
+  		<pub-date iso-8601-date="2002-11">
+   			<month>11</month>
+   			<year>2002</year>
+  		</pub-date>
+  		<publisher>
+   			<publisher-name>National Center for Biotechnology Information (NCBI), National Library of Medicine, National Institutes of Health</publisher-name>
+   			<publisher-loc>Bethesda, MD</publisher-loc>
+  		</publisher>
+  		<edition>1</edition>
+  		<counts>
+   			<book-fig-count count="98"/>
+   			<book-table-count count="40"/>
+   			<book-equation-count count="0"/>
+   			<book-ref-count count="115"/>
+   			<book-page-count count="532"/>
+   			<book-word-count count="149852"/>
+  		</counts>
+ 	</book-meta>
+</book>
+^D
+Pandoc
+  Meta
+    { unMeta =
+        fromList
+          [ ( "author"
+            , MetaList
+                [ MetaInlines [ Str "Jo" , Space , Str "McEntyre" ] ]
+            )
+          , ( "date" , MetaInlines [ Str "2002-11" ] )
+          , ( "institute"
+            , MetaList
+                [ MetaInlines
+                    [ Str "National"
+                    , Space
+                    , Str "Center"
+                    , Space
+                    , Str "for"
+                    , Space
+                    , Str "Biotechnology"
+                    , Space
+                    , Str "Information"
+                    , Space
+                    , Str "(NCBI),"
+                    , Space
+                    , Str "National"
+                    , Space
+                    , Str "Library"
+                    , Space
+                    , Str "of"
+                    , Space
+                    , Str "Medicine,"
+                    , Space
+                    , Str "National"
+                    , Space
+                    , Str "Institutes"
+                    , Space
+                    , Str "of"
+                    , Space
+                    , Str "Health,"
+                    , Space
+                    , Str "Bethesda,"
+                    , Space
+                    , Str "MD"
+                    , Space
+                    , Str "20892-6510"
+                    ]
+                ]
+            )
+          , ( "title"
+            , MetaInlines
+                [ Str "The"
+                , Space
+                , Str "NCBI"
+                , Space
+                , Str "Handbook"
+                ]
+            )
+          ]
+    }
+  []
+```
diff --git a/test/command/bits-book-part-wrapper-meta.md b/test/command/bits-book-part-wrapper-meta.md
new file mode 100644
--- /dev/null
+++ b/test/command/bits-book-part-wrapper-meta.md
@@ -0,0 +1,95 @@
+```
+% pandoc -f jats -t native -s
+<book-part-wrapper 
+  dtd-version="2.1"
+  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+  xmlns:xi="http://www.w3.org/2001/XInclude"
+  xmlns:mml="http://www.w3.org/1998/Math/MathML"
+  xmlns:xlink="http://www.w3.org/1999/xlink">
+
+ <collection-meta>
+  <title-group>
+   <title>Balisage Series on Markup Technologies</title>
+  </title-group>
+ 
+  <abstract>
+   <p>The <italic>Balisage Series on Markup Technologies</italic> 
+    is an occasional series...</p>
+  </abstract>
+ </collection-meta>
+
+ <book-meta>
+  <book-title-group>
+   <book-title>Proceedings of Balisage: The Markup Conference 
+    2013</book-title>
+  </book-title-group>
+ 
+  <abstract>
+   <p>Balisage is a peer-reviewed conference...</p></abstract>
+ 
+ </book-meta>
+</book-part-wrapper>
+^D
+Pandoc
+  Meta
+    { unMeta =
+        fromList
+          [ ( "abstract"
+            , MetaBlocks
+                [ Para
+                    [ Str "Balisage"
+                    , Space
+                    , Str "is"
+                    , Space
+                    , Str "a"
+                    , Space
+                    , Str "peer-reviewed"
+                    , Space
+                    , Str "conference..."
+                    ]
+                ]
+            )
+          , ( "title"
+            , MetaInlines
+                [ Str "Proceedings"
+                , Space
+                , Str "of"
+                , Space
+                , Str "Balisage:"
+                , Space
+                , Str "The"
+                , Space
+                , Str "Markup"
+                , Space
+                , Str "Conference"
+                , SoftBreak
+                , Str "2013"
+                ]
+            )
+          ]
+    }
+  [ Para
+      [ Str "The"
+      , Space
+      , Emph
+          [ Str "Balisage"
+          , Space
+          , Str "Series"
+          , Space
+          , Str "on"
+          , Space
+          , Str "Markup"
+          , Space
+          , Str "Technologies"
+          ]
+      , SoftBreak
+      , Str "is"
+      , Space
+      , Str "an"
+      , Space
+      , Str "occasional"
+      , Space
+      , Str "series..."
+      ]
+  ]
+```
diff --git a/test/command/bits-book-part-wrapper.md b/test/command/bits-book-part-wrapper.md
new file mode 100644
--- /dev/null
+++ b/test/command/bits-book-part-wrapper.md
@@ -0,0 +1,149 @@
+```
+% pandoc -f jats -t native
+<book-part-wrapper 
+  dtd-version="2.1"
+  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+  xmlns:xi="http://www.w3.org/2001/XInclude"
+  xmlns:mml="http://www.w3.org/1998/Math/MathML"
+  xmlns:xlink="http://www.w3.org/1999/xlink">
+
+ <collection-meta>
+  <title-group>
+   <title>Balisage Series on Markup Technologies</title>
+  </title-group>
+ 
+  <abstract>
+   <p>The <italic>Balisage Series on Markup Technologies</italic> 
+    is an occasional series...</p>
+  </abstract>
+ </collection-meta>
+
+ <book-meta>
+  <book-title-group>
+   <book-title>Proceedings of Balisage: The Markup Conference 
+    2013</book-title>
+  </book-title-group>
+ 
+  <abstract>
+   <p>Balisage is a peer-reviewed conference...</p></abstract>
+ 
+ </book-meta>
+
+ <book-part id="bid.1" book-part-type="part">
+   			<book-part-meta>
+    			<title-group>
+     				<label>Part 1</label>
+     				<title>The Databases</title>
+    			</title-group>
+   			</book-part-meta>
+   			<body>
+    			<sec id="bid.3">
+     				<title>History</title>
+     				<p>Initially, GenBank was built and maintained at Los Alamos 
+      				National Laboratory.</p>
+    			</sec>
+   			</body>
+   			<back>
+                <title>Back matter of book part</title>
+  				<ref-list>
+   					<title>References</title>
+   					<ref id="bid.41">
+    					<label>1</label>
+    					<element-citation>
+     						<person-group>
+      							<string-name>
+									<surname>Olson</surname>
+       								<given-names>M</given-names>
+								</string-name>
+      							<string-name>
+									<surname>Hood</surname>
+       								<given-names>L</given-names>
+								</string-name>
+      							<string-name>
+									<surname>Cantor</surname>
+       								<given-names>C</given-names>
+								</string-name>
+      							<string-name>
+									<surname>Botstein</surname>
+       								<given-names>D</given-names>
+								</string-name>
+     						</person-group>
+     						<article-title>A common language for physical mapping of the human genome</article-title>
+     						<source>Science</source>
+     						<year iso-8601-date="1989">1989</year>
+     						<volume>245</volume>
+     						<issue>4925</issue>
+     						<fpage>1434</fpage>
+     						<lpage>1435</lpage>
+     						<pub-id pub-id-type="pmid">2781285</pub-id>
+    					</element-citation>
+   					</ref>
+  				</ref-list>
+ 			</back>
+  	</book-part>
+</book-part-wrapper>
+^D
+[ Para
+    [ Str "The"
+    , Space
+    , Emph
+        [ Str "Balisage"
+        , Space
+        , Str "Series"
+        , Space
+        , Str "on"
+        , Space
+        , Str "Markup"
+        , Space
+        , Str "Technologies"
+        ]
+    , SoftBreak
+    , Str "is"
+    , Space
+    , Str "an"
+    , Space
+    , Str "occasional"
+    , Space
+    , Str "series..."
+    ]
+, Header 2 ( "bid.3" , [] , [] ) [ Str "History" ]
+, Para
+    [ Str "Initially,"
+    , Space
+    , Str "GenBank"
+    , Space
+    , Str "was"
+    , Space
+    , Str "built"
+    , Space
+    , Str "and"
+    , Space
+    , Str "maintained"
+    , Space
+    , Str "at"
+    , Space
+    , Str "Los"
+    , Space
+    , Str "Alamos"
+    , SoftBreak
+    , Str "National"
+    , Space
+    , Str "Laboratory."
+    ]
+, Header
+    2
+    ( "" , [] , [] )
+    [ Str "Back"
+    , Space
+    , Str "matter"
+    , Space
+    , Str "of"
+    , Space
+    , Str "book"
+    , Space
+    , Str "part"
+    ]
+, Header 1 ( "" , [] , [] ) [ Str "References" ]
+, Div ( "refs" , [] , [] ) []
+]
+```
diff --git a/test/command/bits-book.md b/test/command/bits-book.md
new file mode 100644
--- /dev/null
+++ b/test/command/bits-book.md
@@ -0,0 +1,186 @@
+```
+% pandoc -f jats -t native
+<book dtd-version="2.1" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:mml="http://www.w3.org/1998/Math/MathML">
+ 	<front-matter>
+  		<front-matter-part>
+   			<book-part-meta>
+    			<title-group>
+     				<title>About this book</title>
+    			</title-group>
+   			</book-part-meta>
+   			<named-book-part-body>
+    			<sec sec-type="miscinfo">
+     				<title>The NCBI Handbook</title>
+     				<p>Bioinformatics consists of a computational approach
+      				to biomedical information management and analysis.</p>
+    			</sec>
+   			</named-book-part-body>
+  		</front-matter-part>
+ 	</front-matter>
+ 	<book-body>
+  		<book-part id="bid.1" book-part-type="part">
+   			<book-part-meta>
+    			<title-group>
+     				<label>Part 1</label>
+     				<title>The Databases</title>
+    			</title-group>
+   			</book-part-meta>
+   			<body>
+    			<sec id="bid.3">
+     				<title>History</title>
+     				<p>Initially, GenBank was built and maintained at Los Alamos 
+      				National Laboratory.</p>
+    			</sec>
+   			</body>
+   			<back>
+                <title>Back matter of book part</title>
+  				<ref-list>
+   					<title>References</title>
+   					<ref id="bid.41">
+    					<label>1</label>
+    					<element-citation>
+     						<person-group>
+      							<string-name>
+									<surname>Olson</surname>
+       								<given-names>M</given-names>
+								</string-name>
+      							<string-name>
+									<surname>Hood</surname>
+       								<given-names>L</given-names>
+								</string-name>
+      							<string-name>
+									<surname>Cantor</surname>
+       								<given-names>C</given-names>
+								</string-name>
+      							<string-name>
+									<surname>Botstein</surname>
+       								<given-names>D</given-names>
+								</string-name>
+     						</person-group>
+     						<article-title>A common language for physical mapping of the human genome</article-title>
+     						<source>Science</source>
+     						<year iso-8601-date="1989">1989</year>
+     						<volume>245</volume>
+     						<issue>4925</issue>
+     						<fpage>1434</fpage>
+     						<lpage>1435</lpage>
+     						<pub-id pub-id-type="pmid">2781285</pub-id>
+    					</element-citation>
+   					</ref>
+  				</ref-list>
+ 			</back>
+  		</book-part>
+ 	</book-body>
+ 	<book-back>
+  		<ack id="bid.394">
+   		<title>Acknowledgments</title>
+   		<p>We gratefully acknowledge the work of Vladimir Soussov,
+    	as well as the entire NCBI Entrez team...</p>
+  		</ack>
+ 	</book-back>
+</book>
+^D
+[ Header
+    2
+    ( "" , [] , [] )
+    [ Str "The" , Space , Str "NCBI" , Space , Str "Handbook" ]
+, Para
+    [ Str "Bioinformatics"
+    , Space
+    , Str "consists"
+    , Space
+    , Str "of"
+    , Space
+    , Str "a"
+    , Space
+    , Str "computational"
+    , Space
+    , Str "approach"
+    , SoftBreak
+    , Str "to"
+    , Space
+    , Str "biomedical"
+    , Space
+    , Str "information"
+    , Space
+    , Str "management"
+    , Space
+    , Str "and"
+    , Space
+    , Str "analysis."
+    ]
+, Header 2 ( "bid.3" , [] , [] ) [ Str "History" ]
+, Para
+    [ Str "Initially,"
+    , Space
+    , Str "GenBank"
+    , Space
+    , Str "was"
+    , Space
+    , Str "built"
+    , Space
+    , Str "and"
+    , Space
+    , Str "maintained"
+    , Space
+    , Str "at"
+    , Space
+    , Str "Los"
+    , Space
+    , Str "Alamos"
+    , SoftBreak
+    , Str "National"
+    , Space
+    , Str "Laboratory."
+    ]
+, Header
+    2
+    ( "" , [] , [] )
+    [ Str "Back"
+    , Space
+    , Str "matter"
+    , Space
+    , Str "of"
+    , Space
+    , Str "book"
+    , Space
+    , Str "part"
+    ]
+, Header 1 ( "" , [] , [] ) [ Str "References" ]
+, Div ( "refs" , [] , [] ) []
+, Header 2 ( "bid.394" , [] , [] ) [ Str "Acknowledgments" ]
+, Para
+    [ Str "We"
+    , Space
+    , Str "gratefully"
+    , Space
+    , Str "acknowledge"
+    , Space
+    , Str "the"
+    , Space
+    , Str "work"
+    , Space
+    , Str "of"
+    , Space
+    , Str "Vladimir"
+    , Space
+    , Str "Soussov,"
+    , SoftBreak
+    , Str "as"
+    , Space
+    , Str "well"
+    , Space
+    , Str "as"
+    , Space
+    , Str "the"
+    , Space
+    , Str "entire"
+    , Space
+    , Str "NCBI"
+    , Space
+    , Str "Entrez"
+    , Space
+    , Str "team..."
+    ]
+]
+```
diff --git a/test/command/bits-index-elements.md b/test/command/bits-index-elements.md
new file mode 100644
--- /dev/null
+++ b/test/command/bits-index-elements.md
@@ -0,0 +1,83 @@
+```
+% pandoc -f jats -t native
+<index-group>
+	<index-title-group>
+		<title>Index group</title>
+	</index-title-group>
+	<p>Content of index group</p>
+	<index>
+		<index-title-group>
+			<title>Index</title>
+		</index-title-group>
+		<p>Content of index</p>
+  		<index-div>
+   			<index-title-group>
+    			<title>N</title>
+   			</index-title-group>
+   			<p>Content of index div</p>
+   			<index-entry>
+    			<term>Navy</term>
+    			<x>.</x>
+    			<see-entry>Armed forces</see-entry>
+    			<x>.</x>
+   			</index-entry>
+   			<index-entry>
+    			<term>Necessary and proper clause, congressional power</term>
+   			</index-entry>
+   			<index-entry>
+    			<term>Newsgathering as commerce</term>
+   			</index-entry>
+  		</index-div>
+	</index>
+</index-group>
+^D
+[ Header
+    1 ( "" , [] , [] ) [ Str "Index" , Space , Str "group" ]
+, Para
+    [ Str "Content"
+    , Space
+    , Str "of"
+    , Space
+    , Str "index"
+    , Space
+    , Str "group"
+    ]
+, Header 2 ( "" , [] , [] ) [ Str "Index" ]
+, Para
+    [ Str "Content" , Space , Str "of" , Space , Str "index" ]
+, Header 3 ( "" , [] , [] ) [ Str "N" ]
+, Para
+    [ Str "Content"
+    , Space
+    , Str "of"
+    , Space
+    , Str "index"
+    , Space
+    , Str "div"
+    ]
+, Plain [ Str "Navy" ]
+, Plain [ Str "." ]
+, Plain [ Str "Armed" , Space , Str "forces" ]
+, Plain [ Str "." ]
+, Plain
+    [ Str "Necessary"
+    , Space
+    , Str "and"
+    , Space
+    , Str "proper"
+    , Space
+    , Str "clause,"
+    , Space
+    , Str "congressional"
+    , Space
+    , Str "power"
+    ]
+, Plain
+    [ Str "Newsgathering"
+    , Space
+    , Str "as"
+    , Space
+    , Str "commerce"
+    ]
+]
+```
diff --git a/test/command/bits-legend.md b/test/command/bits-legend.md
new file mode 100644
--- /dev/null
+++ b/test/command/bits-legend.md
@@ -0,0 +1,45 @@
+```
+% pandoc -f jats -t native
+<fig id="fig_A.1" orientation="portrait">
+ <label>Figure A.1</label>
+ <caption>
+  <title>Field of Application</title>
+ </caption>
+ <legend>
+  <title>Key</title>
+  <def-list>
+   <def-item>
+    <term>I</term>
+    <def><p>input</p></def>
+   </def-item>
+   <def-item>
+    <term>O</term>
+    <def><p>output</p></def>
+   </def-item>
+   ...
+  </def-list>
+ </legend>
+ <graphic xlink:href="1234"/>
+</fig>
+^D
+[ Figure
+    ( "fig_A.1" , [] , [] )
+    (Caption
+       Nothing
+       [ Plain
+           [ Str "Field"
+           , Space
+           , Str "of"
+           , Space
+           , Str "Application"
+           ]
+       ])
+    [ Header 1 ( "" , [] , [] ) [ Str "Key" ]
+    , DefinitionList
+        [ ( [ Str "I" ] , [ [ Para [ Str "input" ] ] ] )
+        , ( [ Str "O" ] , [ [ Para [ Str "output" ] ] ] )
+        ]
+    , Para [ Image ( "" , [] , [] ) [] ( "1234" , "" ) ]
+    ]
+]
+```
diff --git a/test/command/bits-named-boook-parts.md b/test/command/bits-named-boook-parts.md
new file mode 100644
--- /dev/null
+++ b/test/command/bits-named-boook-parts.md
@@ -0,0 +1,68 @@
+```
+% pandoc -f jats -t native
+<dedication>
+	<named-book-part-body>
+		<p>This is the dedication text.</p>
+	</named-book-part-body>
+</dedication>
+^D
+[ Header 1 ( "" , [] , [] ) [ Str "Dedication" ]
+, Para
+    [ Str "This"
+    , Space
+    , Str "is"
+    , Space
+    , Str "the"
+    , Space
+    , Str "dedication"
+    , Space
+    , Str "text."
+    ]
+]
+```
+
+```
+% pandoc -f jats -t native
+<foreword>
+	<named-book-part-body>
+		<p>This is the foreword text.</p>
+	</named-book-part-body>
+</foreword>
+^D
+[ Header 1 ( "" , [] , [] ) [ Str "Foreword" ]
+, Para
+    [ Str "This"
+    , Space
+    , Str "is"
+    , Space
+    , Str "the"
+    , Space
+    , Str "foreword"
+    , Space
+    , Str "text."
+    ]
+]
+```
+
+```
+% pandoc -f jats -t native
+<preface>
+	<named-book-part-body>
+		<p>This is the preface text.</p>
+	</named-book-part-body>
+</preface>
+^D
+[ Header 1 ( "" , [] , [] ) [ Str "Preface" ]
+, Para
+    [ Str "This"
+    , Space
+    , Str "is"
+    , Space
+    , Str "the"
+    , Space
+    , Str "preface"
+    , Space
+    , Str "text."
+    ]
+]
+```
diff --git a/test/command/bits-title-display-as.md b/test/command/bits-title-display-as.md
new file mode 100644
--- /dev/null
+++ b/test/command/bits-title-display-as.md
@@ -0,0 +1,175 @@
+```
+% pandoc -f jats -t native
+<sec>
+	<title>THE EUROPEAN UNION  EXPLAINED</title>
+</sec>
+^D
+[ Header
+    1
+    ( "" , [] , [] )
+    [ Str "THE"
+    , Space
+    , Str "EUROPEAN"
+    , Space
+    , Str "UNION"
+    , Space
+    , Str "EXPLAINED"
+    ]
+]
+```
+
+```
+% pandoc -f jats -t native
+<sec>
+	<title display-as="3">THE EUROPEAN UNION  EXPLAINED</title>
+</sec>
+^D
+[ Header
+    3
+    ( "" , [] , [] )
+    [ Str "THE"
+    , Space
+    , Str "EUROPEAN"
+    , Space
+    , Str "UNION"
+    , Space
+    , Str "EXPLAINED"
+    ]
+]
+```
+
+```
+% pandoc -f jats -t native
+<body>
+	<sec>
+		<title>The European Parliament</title>
+		<p>Members of the European Parliament (MEPs) are directly elected by EU citizens.</p>
+		<sec>
+		    <title display-as="3">Composition of the European Parliament</title>
+			<p>The seats in the European Parliament are allocated among the Member States.</p>
+		</sec>
+        <sec>
+            <title>Composition of the European Parliament - II </title>
+            <p>Most MEPs are associated with a national political party in their home country.</p>
+		</sec>
+    </sec>
+</body>
+^D
+[ Header
+    1
+    ( "" , [] , [] )
+    [ Str "The"
+    , Space
+    , Str "European"
+    , Space
+    , Str "Parliament"
+    ]
+, Para
+    [ Str "Members"
+    , Space
+    , Str "of"
+    , Space
+    , Str "the"
+    , Space
+    , Str "European"
+    , Space
+    , Str "Parliament"
+    , Space
+    , Str "(MEPs)"
+    , Space
+    , Str "are"
+    , Space
+    , Str "directly"
+    , Space
+    , Str "elected"
+    , Space
+    , Str "by"
+    , Space
+    , Str "EU"
+    , Space
+    , Str "citizens."
+    ]
+, Header
+    3
+    ( "" , [] , [] )
+    [ Str "Composition"
+    , Space
+    , Str "of"
+    , Space
+    , Str "the"
+    , Space
+    , Str "European"
+    , Space
+    , Str "Parliament"
+    ]
+, Para
+    [ Str "The"
+    , Space
+    , Str "seats"
+    , Space
+    , Str "in"
+    , Space
+    , Str "the"
+    , Space
+    , Str "European"
+    , Space
+    , Str "Parliament"
+    , Space
+    , Str "are"
+    , Space
+    , Str "allocated"
+    , Space
+    , Str "among"
+    , Space
+    , Str "the"
+    , Space
+    , Str "Member"
+    , Space
+    , Str "States."
+    ]
+, Header
+    2
+    ( "" , [] , [] )
+    [ Str "Composition"
+    , Space
+    , Str "of"
+    , Space
+    , Str "the"
+    , Space
+    , Str "European"
+    , Space
+    , Str "Parliament"
+    , Space
+    , Str "-"
+    , Space
+    , Str "II"
+    ]
+, Para
+    [ Str "Most"
+    , Space
+    , Str "MEPs"
+    , Space
+    , Str "are"
+    , Space
+    , Str "associated"
+    , Space
+    , Str "with"
+    , Space
+    , Str "a"
+    , Space
+    , Str "national"
+    , Space
+    , Str "political"
+    , Space
+    , Str "party"
+    , Space
+    , Str "in"
+    , Space
+    , Str "their"
+    , Space
+    , Str "home"
+    , Space
+    , Str "country."
+    ]
+]
+```
diff --git a/test/command/bits-title-supress.md b/test/command/bits-title-supress.md
new file mode 100644
--- /dev/null
+++ b/test/command/bits-title-supress.md
@@ -0,0 +1,122 @@
+```
+% pandoc -f jats -t native
+<sec>
+	<title>The European Parliament</title>
+	<p>Members of the European Parliament (MEPs) are directly elected by EU citizens.</p>
+</sec>
+^D
+[ Header
+    1
+    ( "" , [] , [] )
+    [ Str "The"
+    , Space
+    , Str "European"
+    , Space
+    , Str "Parliament"
+    ]
+, Para
+    [ Str "Members"
+    , Space
+    , Str "of"
+    , Space
+    , Str "the"
+    , Space
+    , Str "European"
+    , Space
+    , Str "Parliament"
+    , Space
+    , Str "(MEPs)"
+    , Space
+    , Str "are"
+    , Space
+    , Str "directly"
+    , Space
+    , Str "elected"
+    , Space
+    , Str "by"
+    , Space
+    , Str "EU"
+    , Space
+    , Str "citizens."
+    ]
+]
+```
+
+```
+% pandoc -f jats -t native
+<sec>
+	<title suppress="no">The European Parliament</title>
+	<p>Members of the European Parliament (MEPs) are directly elected by EU citizens.</p>
+</sec>
+^D
+[ Header
+    1
+    ( "" , [] , [] )
+    [ Str "The"
+    , Space
+    , Str "European"
+    , Space
+    , Str "Parliament"
+    ]
+, Para
+    [ Str "Members"
+    , Space
+    , Str "of"
+    , Space
+    , Str "the"
+    , Space
+    , Str "European"
+    , Space
+    , Str "Parliament"
+    , Space
+    , Str "(MEPs)"
+    , Space
+    , Str "are"
+    , Space
+    , Str "directly"
+    , Space
+    , Str "elected"
+    , Space
+    , Str "by"
+    , Space
+    , Str "EU"
+    , Space
+    , Str "citizens."
+    ]
+]
+```
+
+```
+% pandoc -f jats -t native
+<sec>
+	<title suppress="yes">The European Parliament</title>
+	<p>Members of the European Parliament (MEPs) are directly elected by EU citizens.</p>
+</sec>
+^D
+[ Para
+    [ Str "Members"
+    , Space
+    , Str "of"
+    , Space
+    , Str "the"
+    , Space
+    , Str "European"
+    , Space
+    , Str "Parliament"
+    , Space
+    , Str "(MEPs)"
+    , Space
+    , Str "are"
+    , Space
+    , Str "directly"
+    , Space
+    , Str "elected"
+    , Space
+    , Str "by"
+    , Space
+    , Str "EU"
+    , Space
+    , Str "citizens."
+    ]
+]
+```
diff --git a/test/command/bits-toc-elements.md b/test/command/bits-toc-elements.md
new file mode 100644
--- /dev/null
+++ b/test/command/bits-toc-elements.md
@@ -0,0 +1,69 @@
+```
+% pandoc -f jats -t native
+<toc-group>
+	<toc-title-group>
+		<title>TOC group</title>
+	</toc-title-group>
+	<p>Content of toc group</p>
+	<toc>
+		<toc-title-group>
+			<title>TOC</title>
+		</toc-title-group>
+		<p>Content of TOC</p>
+  		<toc-div content-type="sections">
+   			<toc-title-group>
+                <title>Mental Health Services</title>
+            </toc-title-group>
+            <toc-entry>
+                <label>Section 1</label>
+                <title>Introduction</title>
+                <nav-pointer rid="tc3"/>
+            </toc-entry>
+            <toc-entry>
+                <label>Section 2</label>
+                <title>Mental Health of the Population</title>
+                <nav-pointer rid="tc4"/>
+            </toc-entry>
+  		</toc-div>
+	</toc>
+</toc-group>
+^D
+[ Header
+    1 ( "" , [] , [] ) [ Str "TOC" , Space , Str "group" ]
+, Para
+    [ Str "Content"
+    , Space
+    , Str "of"
+    , Space
+    , Str "toc"
+    , Space
+    , Str "group"
+    ]
+, Header 2 ( "" , [] , [] ) [ Str "TOC" ]
+, Para
+    [ Str "Content" , Space , Str "of" , Space , Str "TOC" ]
+, Header
+    3
+    ( "" , [] , [] )
+    [ Str "Mental"
+    , Space
+    , Str "Health"
+    , Space
+    , Str "Services"
+    ]
+, Header 4 ( "" , [] , [] ) [ Str "Introduction" ]
+, Header
+    4
+    ( "" , [] , [] )
+    [ Str "Mental"
+    , Space
+    , Str "Health"
+    , Space
+    , Str "of"
+    , Space
+    , Str "the"
+    , Space
+    , Str "Population"
+    ]
+]
+```
diff --git a/test/command/chap1/spider.png b/test/command/chap1/spider.png
new file mode 100644
Binary files /dev/null and b/test/command/chap1/spider.png differ
diff --git a/test/command/chap1/text.md b/test/command/chap1/text.md
new file mode 100644
--- /dev/null
+++ b/test/command/chap1/text.md
@@ -0,0 +1,17 @@
+# Chapter one
+
+A spider: ![spider](spider.png)
+
+Another spider: ![another spider][refspider]
+
+The moon: ![moon](../../lalune.jpg)
+
+Link to [spider picture](spider.png).
+
+URL left alone: [manual](https://pandoc.org/MANUAL.html).
+
+Absolute path left alone: [absolute](/foo/bar/baz.png).
+
+Link to fragment: [chapter two](#chapter-two).
+
+Empty path: [empty]().
diff --git a/test/command/chap2/spider.png b/test/command/chap2/spider.png
new file mode 100644
Binary files /dev/null and b/test/command/chap2/spider.png differ
diff --git a/test/command/chap2/text.md b/test/command/chap2/text.md
new file mode 100644
--- /dev/null
+++ b/test/command/chap2/text.md
@@ -0,0 +1,5 @@
+# Chapter two
+
+A spider: ![spider](spider.png)
+
+[refspider]: spider.png
diff --git a/test/command/chicago-annotated-bibliography.csl b/test/command/chicago-annotated-bibliography.csl
new file mode 100644
--- /dev/null
+++ b/test/command/chicago-annotated-bibliography.csl
@@ -0,0 +1,1207 @@
+<?xml version="1.0" encoding="utf-8"?>
+<style xmlns="http://purl.org/net/xbiblio/csl" class="note" version="1.0" demote-non-dropping-particle="never" page-range-format="chicago">
+  <info>
+    <title>Chicago Manual of Style 16th edition (note, annotated bibliography)</title>
+    <id>http://www.zotero.org/styles/chicago-annotated-bibliography</id>
+    <link href="http://www.zotero.org/styles/chicago-annotated-bibliography" rel="self"/>
+    <link href="http://www.chicagomanualofstyle.org/tools_citationguide.html" rel="documentation"/>
+    <author>
+      <name>Julian Onions</name>
+      <email>julian.onions@gmail.com</email>
+    </author>
+    <contributor>
+      <name>Simon Kornblith</name>
+      <email>simon@simonster.com</email>
+    </contributor>
+    <contributor>
+      <name>Elena Razlogova</name>
+      <email>elena.razlogova@gmail.com</email>
+    </contributor>
+    <contributor>
+      <name>Frank Bennett</name>
+      <email>biercenator@gmail.com</email>
+    </contributor>
+    <contributor>
+      <name>Andrew Dunning</name>
+      <email>andrew.dunning@utoronto.ca</email>
+    </contributor>
+    <category citation-format="note"/>
+    <category field="generic-base"/>
+    <summary>Chicago format with short notes and annotated bibliography</summary>
+    <updated>2012-10-25T21:15:26+00:00</updated>
+    <rights license="http://creativecommons.org/licenses/by-sa/3.0/">This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 License</rights>
+  </info>
+  <locale xml:lang="en">
+    <terms>
+      <term name="editor" form="verb-short">ed.</term>
+      <term name="translator" form="verb-short">trans.</term>
+      <term name="editortranslator" form="verb-short">
+        <single>ed. and trans.</single>
+        <multiple>ed. and trans.</multiple>
+      </term>
+      <term name="editortranslator" form="verb">
+        <single>Edited and translated by</single>
+        <multiple>Edited and translated by</multiple>
+      </term>
+      <term name="translator" form="short">trans.</term>
+    </terms>
+  </locale>
+  <macro name="editor-translator">
+    <group delimiter=", ">
+      <group delimiter=" ">
+        <choose>
+          <if variable="container-author reviewed-author" match="any">
+            <group>
+              <names variable="container-author reviewed-author">
+                <label form="verb-short" text-case="lowercase" suffix=" "/>
+                <name and="text" delimiter=", "/>
+              </names>
+            </group>
+          </if>
+        </choose>
+      </group>
+      <names variable="editor translator" delimiter=", ">
+        <label form="verb-short" text-case="lowercase" suffix=" "/>
+        <name and="text" delimiter=", "/>
+      </names>
+    </group>
+  </macro>
+  <macro name="secondary-contributors-note">
+    <choose>
+      <if type="chapter paper-conference" match="none">
+        <text macro="editor-translator"/>
+      </if>
+    </choose>
+  </macro>
+  <macro name="container-contributors-note">
+    <choose>
+      <if type="chapter paper-conference" match="any">
+        <text macro="editor-translator"/>
+      </if>
+    </choose>
+  </macro>
+  <macro name="secondary-contributors">
+    <choose>
+      <if type="chapter paper-conference" match="none">
+        <names variable="editor translator" delimiter=". ">
+          <label form="verb" text-case="capitalize-first" suffix=" "/>
+          <name and="text" delimiter=", "/>
+        </names>
+      </if>
+    </choose>
+  </macro>
+  <macro name="container-contributors">
+    <choose>
+      <if type="chapter paper-conference" match="any">
+        <group delimiter=", ">
+          <choose>
+            <if variable="author">
+              <choose>
+                <if variable="container-author" match="any">
+                  <names variable="container-author">
+                    <label form="verb-short" text-case="lowercase" suffix=" "/>
+                    <name and="text" delimiter=", "/>
+                  </names>
+                </if>
+              </choose>
+              <!--This includes page numbers after the container author, e.g. for Introductions -->
+              <choose>
+                <if variable="container-author author" match="all">
+                  <group delimiter=". ">
+                    <text variable="page"/>
+                    <names variable="editor translator" delimiter=", ">
+                      <label form="verb" suffix=" "/>
+                      <name and="text" delimiter=", "/>
+                    </names>
+                  </group>
+                </if>
+                <else>
+                  <names variable="editor translator" delimiter=", ">
+                    <label form="verb" text-case="lowercase" suffix=" "/>
+                    <name and="text" delimiter=", "/>
+                  </names>
+                </else>
+              </choose>
+            </if>
+          </choose>
+        </group>
+      </if>
+    </choose>
+  </macro>
+  <macro name="recipient-note">
+    <names variable="recipient" delimiter=", ">
+      <label form="verb" text-case="lowercase" suffix=" "/>
+      <name and="text" delimiter=", "/>
+    </names>
+  </macro>
+  <macro name="contributors-note">
+    <group delimiter=" ">
+      <names variable="author">
+        <name and="text" sort-separator=", " delimiter=", "/>
+        <label form="short" prefix=", "/>
+        <substitute>
+          <names variable="editor"/>
+          <names variable="translator"/>
+        </substitute>
+      </names>
+      <text macro="recipient-note"/>
+    </group>
+  </macro>
+  <macro name="editor">
+    <names variable="editor">
+      <name name-as-sort-order="first" and="text" sort-separator=", " delimiter=", " delimiter-precedes-last="always"/>
+      <label form="short" prefix=", "/>
+    </names>
+  </macro>
+  <macro name="translator">
+    <names variable="translator">
+      <name name-as-sort-order="first" and="text" sort-separator=", " delimiter=", " delimiter-precedes-last="always"/>
+      <label form="verb-short" prefix=", "/>
+    </names>
+  </macro>
+  <macro name="recipient">
+    <group delimiter=" ">
+      <choose>
+        <if type="personal_communication">
+          <choose>
+            <if variable="genre">
+              <text variable="genre" text-case="capitalize-first"/>
+            </if>
+            <else>
+              <text term="letter" text-case="capitalize-first"/>
+            </else>
+          </choose>
+        </if>
+      </choose>
+      <text macro="recipient-note"/>
+    </group>
+  </macro>
+  <macro name="contributors">
+    <group delimiter=". ">
+      <names variable="author">
+        <name name-as-sort-order="first" and="text" sort-separator=", " delimiter=", " delimiter-precedes-last="always"/>
+        <substitute>
+          <text macro="editor"/>
+          <text macro="translator"/>
+        </substitute>
+      </names>
+      <text macro="recipient"/>
+    </group>
+  </macro>
+  <macro name="recipient-short">
+    <names variable="recipient">
+      <label form="verb" text-case="lowercase" suffix=" "/>
+      <name form="short" and="text" delimiter=", "/>
+    </names>
+  </macro>
+  <macro name="contributors-short">
+    <group delimiter=" ">
+      <names variable="author">
+        <name form="short" and="text" delimiter=", "/>
+        <substitute>
+          <names variable="editor"/>
+          <names variable="translator"/>
+        </substitute>
+      </names>
+      <text macro="recipient-short"/>
+    </group>
+  </macro>
+  <macro name="contributors-sort">
+    <names variable="author">
+      <name name-as-sort-order="all" and="text" sort-separator=", " delimiter=", " delimiter-precedes-last="always"/>
+      <substitute>
+        <names variable="editor"/>
+        <names variable="translator"/>
+        <text macro="title"/>
+      </substitute>
+    </names>
+  </macro>
+  <macro name="interviewer-note">
+    <names variable="interviewer" delimiter=", ">
+      <label form="verb" text-case="lowercase" suffix=" "/>
+      <name and="text" delimiter=", "/>
+    </names>
+  </macro>
+  <macro name="interviewer">
+    <names variable="interviewer" delimiter=", ">
+      <label form="verb" text-case="capitalize-first" suffix=" "/>
+      <name and="text" delimiter=", "/>
+    </names>
+  </macro>
+  <macro name="title-note">
+    <choose>
+      <if variable="title" match="none">
+        <text variable="genre"/>
+      </if>
+      <else-if type="bill book graphic  legislation motion_picture report song" match="any">
+        <text variable="title" text-case="title" font-style="italic"/>
+        <group delimiter=" " prefix=", ">
+          <text term="version"/>
+          <text variable="version"/>
+        </group>
+      </else-if>
+      <else-if type="legal_case interview" match="any">
+        <text variable="title"/>
+      </else-if>
+      <else-if variable="reviewed-author">
+        <text variable="title" font-style="italic" prefix="review of "/>
+      </else-if>
+      <else>
+        <text variable="title" text-case="title" quotes="true"/>
+      </else>
+    </choose>
+  </macro>
+  <macro name="title">
+    <choose>
+      <if variable="title" match="none">
+        <choose>
+          <if type="personal_communication" match="none">
+            <text variable="genre" text-case="capitalize-first"/>
+          </if>
+        </choose>
+      </if>
+      <else-if type="bill book graphic legislation motion_picture report song" match="any">
+        <text variable="title" text-case="title" font-style="italic"/>
+        <group prefix=" (" suffix=")" delimiter=" ">
+          <text term="version"/>
+          <text variable="version"/>
+        </group>
+      </else-if>
+      <else-if variable="reviewed-author">
+        <group delimiter=", ">
+          <text variable="title" font-style="italic" prefix="Review of "/>
+          <names variable="reviewed-author">
+            <label form="verb-short" text-case="lowercase" suffix=" "/>
+            <name and="text" delimiter=", "/>
+          </names>
+        </group>
+      </else-if>
+      <else-if type="legal_case interview" match="any">
+        <text variable="title"/>
+      </else-if>
+      <else>
+        <text variable="title" text-case="title" quotes="true"/>
+      </else>
+    </choose>
+  </macro>
+  <macro name="title-short">
+    <choose>
+      <if variable="title" match="none">
+        <choose>
+          <if type="interview">
+            <text term="interview"/>
+          </if>
+          <else-if type="manuscript speech" match="any">
+            <text variable="genre" form="short"/>
+          </else-if>
+          <else-if type="personal_communication">
+            <text macro="issued"/>
+          </else-if>
+        </choose>
+      </if>
+      <else-if type="bill book graphic legislation motion_picture report song" match="any">
+        <text variable="title" text-case="title" form="short" font-style="italic"/>
+      </else-if>
+      <else-if type="legal_case interview" match="any">
+        <text variable="title"/>
+      </else-if>
+      <else>
+        <text variable="title" text-case="title" form="short" quotes="true"/>
+      </else>
+    </choose>
+  </macro>
+  <macro name="date-disambiguate">
+    <choose>
+      <if disambiguate="true">
+        <text macro="issued"/>
+      </if>
+    </choose>
+  </macro>
+  <macro name="description-note">
+    <group delimiter=", ">
+      <text macro="interviewer-note"/>
+      <text variable="medium"/>
+      <choose>
+        <if variable="title" match="none"/>
+        <else-if type="manuscript thesis speech" match="any"/>
+        <else>
+          <text variable="genre"/>
+        </else>
+      </choose>
+    </group>
+  </macro>
+  <macro name="description">
+    <group delimiter=", ">
+      <group delimiter=". ">
+        <text macro="interviewer"/>
+        <text variable="medium" text-case="capitalize-first"/>
+      </group>
+      <choose>
+        <if variable="title" match="none"/>
+        <else-if type="thesis speech" match="any"/>
+        <else>
+          <text variable="genre" text-case="capitalize-first"/>
+        </else>
+      </choose>
+    </group>
+  </macro>
+  <macro name="container-title-note">
+    <group delimiter=" ">
+      <choose>
+        <if type="chapter paper-conference" match="any">
+          <text term="in"/>
+        </if>
+      </choose>
+      <choose>
+        <if type="legal_case" match="none">
+          <text variable="container-title" text-case="title" font-style="italic"/>
+        </if>
+      </choose>
+    </group>
+  </macro>
+  <macro name="container-title">
+    <group delimiter=" ">
+      <choose>
+        <if type="chapter paper-conference" match="any">
+          <text term="in" text-case="capitalize-first"/>
+        </if>
+      </choose>
+      <choose>
+        <if type="legal_case" match="none">
+          <text variable="container-title" text-case="title" font-style="italic"/>
+        </if>
+      </choose>
+    </group>
+  </macro>
+  <macro name="collection-title">
+    <choose>
+      <if match="none" type="article-journal">
+        <choose>
+          <if match="none" is-numeric="collection-number">
+            <group delimiter=", ">
+              <text variable="collection-title" text-case="title"/>
+              <text variable="collection-number"/>
+            </group>
+          </if>
+          <else>
+            <group delimiter=" ">
+              <text variable="collection-title" text-case="title"/>
+              <text variable="collection-number"/>
+            </group>
+          </else>
+        </choose>
+      </if>
+    </choose>
+  </macro>
+  <macro name="collection-title-journal">
+    <choose>
+      <if type="article-journal">
+        <group delimiter=" ">
+          <text variable="collection-title"/>
+          <text variable="collection-number"/>
+        </group>
+      </if>
+    </choose>
+  </macro>
+  <macro name="edition-note">
+    <choose>
+      <if type="bill book chapter graphic legal_case legislation motion_picture paper-conference report song" match="any">
+        <choose>
+          <if is-numeric="edition">
+            <group delimiter=" ">
+              <number variable="edition" form="ordinal"/>
+              <text term="edition" form="short"/>
+            </group>
+          </if>
+          <else>
+            <text variable="edition"/>
+          </else>
+        </choose>
+      </if>
+    </choose>
+  </macro>
+  <macro name="edition">
+    <choose>
+      <if type="bill book chapter graphic legal_case legislation motion_picture paper-conference report song" match="any">
+        <choose>
+          <if is-numeric="edition">
+            <group delimiter=" ">
+              <number variable="edition" form="ordinal"/>
+              <text term="edition" form="short"/>
+            </group>
+          </if>
+          <else>
+            <text variable="edition" text-case="capitalize-first" suffix="."/>
+          </else>
+        </choose>
+      </if>
+    </choose>
+  </macro>
+  <macro name="locators-note-join-with-space">
+    <choose>
+      <if type="article-journal" variable="volume" match="all">
+        <choose>
+          <if match="none" variable="collection-title">
+            <text macro="locators-note"/>
+          </if>
+        </choose>
+      </if>
+    </choose>
+  </macro>
+  <macro name="locators-note-join-with-comma">
+    <choose>
+      <if type="article-journal" match="none">
+        <text macro="locators-note"/>
+      </if>
+      <else-if type="article-journal">
+        <choose>
+          <if variable="volume" match="none">
+            <text macro="locators-note"/>
+          </if>
+          <else-if match="any" variable="collection-title">
+            <text macro="locators-note"/>
+          </else-if>
+        </choose>
+      </else-if>
+    </choose>
+  </macro>
+  <macro name="locators-note">
+    <choose>
+      <if type="article-journal">
+        <group delimiter=", ">
+          <text macro="collection-title-journal"/>
+          <number variable="volume"/>
+          <group delimiter=" ">
+            <text term="issue" form="short"/>
+            <number variable="issue"/>
+          </group>
+        </group>
+      </if>
+      <else-if type="legal_case">
+        <group delimiter=", ">
+          <group delimiter=" ">
+            <number variable="volume"/>
+            <text variable="container-title"/>
+            <text variable="page"/>
+          </group>
+          <text variable="locator"/>
+        </group>
+      </else-if>
+      <else-if type="bill book chapter graphic legal_case legislation motion_picture paper-conference report song" match="any">
+        <group delimiter=", ">
+          <text macro="edition-note"/>
+          <group delimiter=" ">
+            <text term="volume" form="short"/>
+            <number variable="volume" form="numeric"/>
+          </group>
+          <choose>
+            <if variable="locator" match="none">
+              <group delimiter=" ">
+                <number variable="number-of-volumes" form="numeric"/>
+                <text term="volume" form="short" plural="true"/>
+              </group>
+            </if>
+          </choose>
+        </group>
+      </else-if>
+    </choose>
+  </macro>
+  <macro name="locators-join-with-space">
+    <choose>
+      <if type="article-journal" variable="volume" match="all">
+        <choose>
+          <if match="none" variable="collection-title">
+            <text macro="locators"/>
+          </if>
+        </choose>
+      </if>
+    </choose>
+  </macro>
+  <macro name="locators-join-with-comma">
+    <choose>
+      <if type="legal_case chapter paper-conference" match="any">
+        <text macro="locators"/>
+      </if>
+      <else-if type="article-journal">
+        <choose>
+          <if variable="volume" match="none">
+            <text macro="locators"/>
+          </if>
+          <else-if match="any" variable="collection-title">
+            <text macro="locators"/>
+          </else-if>
+        </choose>
+      </else-if>
+    </choose>
+  </macro>
+  <macro name="locators-join-with-period">
+    <choose>
+      <if type="legal_case article-journal chapter paper-conference" match="none">
+        <text macro="locators"/>
+      </if>
+    </choose>
+  </macro>
+  <macro name="locators">
+    <choose>
+      <if type="article-journal">
+        <group delimiter=", ">
+          <text macro="collection-title-journal"/>
+          <number variable="volume"/>
+          <group delimiter=" ">
+            <text term="issue" form="short"/>
+            <number variable="issue"/>
+          </group>
+        </group>
+      </if>
+      <else-if type="legal_case">
+        <group delimiter=" ">
+          <number variable="volume"/>
+          <text variable="container-title"/>
+          <text variable="page"/>
+        </group>
+      </else-if>
+      <else-if type="bill book graphic legal_case legislation motion_picture report song" match="any">
+        <group delimiter=". ">
+          <text macro="edition"/>
+          <group delimiter=" ">
+            <text term="volume" form="short" text-case="capitalize-first"/>
+            <number variable="volume" form="numeric"/>
+          </group>
+          <group delimiter=" ">
+            <number variable="number-of-volumes" form="numeric"/>
+            <text term="volume" form="short" plural="true"/>
+          </group>
+        </group>
+      </else-if>
+      <else-if type="chapter paper-conference" match="any">
+        <group delimiter=". ">
+          <text macro="edition"/>
+          <choose>
+            <if variable="page" match="none">
+              <group delimiter=" ">
+                <text term="volume" form="short" text-case="capitalize-first"/>
+                <number variable="volume" form="numeric"/>
+              </group>
+            </if>
+          </choose>
+        </group>
+      </else-if>
+    </choose>
+  </macro>
+  <macro name="locators-newspaper">
+    <choose>
+      <if type="article-newspaper">
+        <group delimiter=", ">
+          <group delimiter=" ">
+            <number variable="edition"/>
+            <text term="edition"/>
+          </group>
+          <group delimiter=" ">
+            <text term="section" form="short"/>
+            <text variable="section"/>
+          </group>
+        </group>
+      </if>
+    </choose>
+  </macro>
+  <macro name="event-note">
+    <text variable="event"/>
+  </macro>
+  <macro name="event">
+    <choose>
+      <if variable="title">
+        <group delimiter=" ">
+          <text term="presented at"/>
+          <text variable="event"/>
+        </group>
+      </if>
+      <else>
+        <group delimiter=" ">
+          <text term="presented at" text-case="capitalize-first"/>
+          <text variable="event"/>
+        </group>
+      </else>
+    </choose>
+  </macro>
+  <macro name="originally-published">
+    <group delimiter=", ">
+      <group delimiter=": ">
+        <text variable="original-publisher-place"/>
+        <text variable="original-publisher"/>
+      </group>
+      <date variable="original-date" form="text" date-parts="year"/>
+    </group>
+  </macro>
+  <macro name="reprint-note">
+    <!--needs localization-->
+    <choose>
+      <if variable="original-date issued" match="all">
+        <choose>
+          <!--for whatever reason in notes, when we have both original and new publishers, reprint doesn't appear-->
+          <if variable="original-publisher original-publisher-place" match="none">
+            <text value="repr."/>
+          </if>
+        </choose>
+      </if>
+    </choose>
+  </macro>
+  <macro name="reprint">
+    <!--needs localization-->
+    <choose>
+      <if variable="original-date issued" match="all">
+        <text value="reprint" text-case="capitalize-first"/>
+      </if>
+    </choose>
+  </macro>
+  <macro name="publisher">
+    <choose>
+      <if type="thesis">
+        <text variable="publisher"/>
+      </if>
+      <else-if type="speech">
+        <text variable="event-place"/>
+      </else-if>
+      <else>
+        <group delimiter=": ">
+          <text variable="publisher-place"/>
+          <text variable="publisher"/>
+        </group>
+      </else>
+    </choose>
+  </macro>
+  <macro name="issued">
+    <choose>
+      <if variable="issued">
+        <choose>
+          <if type="graphic report" match="any">
+            <date variable="issued" form="text"/>
+          </if>
+          <else-if type="legal_case">
+            <group delimiter=" ">
+              <text variable="authority"/>
+              <date variable="issued">
+                <date-part name="year"/>
+              </date>
+            </group>
+          </else-if>
+          <else-if type="bill book chapter graphic legal_case legislation motion_picture paper-conference report song thesis" match="any">
+            <date variable="issued">
+              <date-part name="year"/>
+            </date>
+          </else-if>
+          <else>
+            <date variable="issued" form="text"/>
+          </else>
+        </choose>
+      </if>
+      <else-if variable="status">
+        <text variable="status"/>
+      </else-if>
+      <else-if variable="accessed URL" match="all"/>
+      <else>
+        <text term="no date" form="short"/>
+      </else>
+    </choose>
+  </macro>
+  <macro name="point-locators-subsequent">
+    <choose>
+      <if type="legal_case"/>
+      <else-if variable="locator">
+        <choose>
+          <if locator="page" match="none">
+            <group delimiter=" ">
+              <choose>
+                <if type="bill book graphic legislation motion_picture report song" match="any">
+                  <choose>
+                    <if variable="volume">
+                      <group delimiter=", ">
+                        <group delimiter=" ">
+                          <text term="volume" form="short"/>
+                          <number variable="volume" form="numeric"/>
+                        </group>
+                        <label variable="locator" form="short"/>
+                      </group>
+                    </if>
+                    <else>
+                      <label variable="locator" form="short"/>
+                    </else>
+                  </choose>
+                </if>
+                <else>
+                  <label variable="locator" form="short"/>
+                </else>
+              </choose>
+              <text variable="locator"/>
+            </group>
+          </if>
+          <else-if type="bill book graphic legislation motion_picture report song" match="any">
+            <group delimiter=":">
+              <number variable="volume" form="numeric"/>
+              <text variable="locator"/>
+            </group>
+          </else-if>
+          <else>
+            <text variable="locator"/>
+          </else>
+        </choose>
+      </else-if>
+    </choose>
+  </macro>
+  <macro name="point-locators-join-with-colon">
+    <choose>
+      <if type="article-journal">
+        <choose>
+          <if variable="locator page" match="any">
+            <choose>
+              <if variable="volume issue" match="any">
+                <text macro="point-locators"/>
+              </if>
+            </choose>
+          </if>
+        </choose>
+      </if>
+    </choose>
+  </macro>
+  <macro name="point-locators-join-with-comma">
+    <choose>
+      <if type="article-journal" match="none">
+        <text macro="point-locators"/>
+      </if>
+      <else-if variable="volume issue" match="none">
+        <text macro="point-locators"/>
+      </else-if>
+    </choose>
+  </macro>
+  <macro name="point-locators">
+    <choose>
+      <if variable="locator" match="none">
+        <choose>
+          <if type="article-journal chapter paper-conference" match="any">
+            <text variable="page"/>
+          </if>
+        </choose>
+      </if>
+      <else-if type="article-journal">
+        <group delimiter=" ">
+          <choose>
+            <if locator="page" match="none">
+              <label variable="locator" form="short" suffix=" "/>
+            </if>
+          </choose>
+          <text variable="locator"/>
+        </group>
+      </else-if>
+      <else-if type="legal_case"/>
+      <else>
+        <group delimiter=" ">
+          <choose>
+            <if locator="page" match="none">
+              <label variable="locator" form="short"/>
+            </if>
+          </choose>
+          <text variable="locator"/>
+        </group>
+      </else>
+    </choose>
+  </macro>
+  <macro name="locators-chapter">
+    <choose>
+      <if type="chapter paper-conference" match="any">
+        <choose>
+          <if variable="author container-author" match="all"/>
+          <else>
+            <choose>
+              <if variable="page">
+                <number variable="volume" suffix=":"/>
+                <text variable="page"/>
+              </if>
+            </choose>
+          </else>
+        </choose>
+      </if>
+    </choose>
+  </macro>
+  <macro name="locators-journal-join-with-colon">
+    <choose>
+      <if type="article-journal">
+        <choose>
+          <if variable="volume issue" match="any">
+            <text variable="page"/>
+          </if>
+        </choose>
+      </if>
+    </choose>
+  </macro>
+  <macro name="locators-journal-join-with-comma">
+    <choose>
+      <if type="article-journal">
+        <choose>
+          <if variable="volume issue" match="none">
+            <text variable="page"/>
+          </if>
+        </choose>
+      </if>
+    </choose>
+  </macro>
+  <macro name="archive-note">
+    <choose>
+      <if type="thesis">
+        <group delimiter=" ">
+          <text variable="archive"/>
+          <text variable="archive_location" prefix="(" suffix=")"/>
+        </group>
+      </if>
+      <else>
+        <group delimiter=", ">
+          <text variable="archive_location"/>
+          <text variable="archive"/>
+          <text variable="archive-place"/>
+        </group>
+      </else>
+    </choose>
+  </macro>
+  <macro name="archive">
+    <choose>
+      <if type="thesis">
+        <group delimiter=" ">
+          <text variable="archive"/>
+          <text variable="archive_location" prefix="(" suffix=")"/>
+        </group>
+      </if>
+      <else>
+        <group delimiter=". ">
+          <text variable="archive_location" text-case="capitalize-first"/>
+          <text variable="archive"/>
+          <text variable="archive-place"/>
+        </group>
+      </else>
+    </choose>
+  </macro>
+  <macro name="issue-note-join-with-space">
+    <choose>
+      <if type="article-journal legal_case manuscript thesis" variable="publisher-place publisher" match="any">
+        <!--Chicago doesn't use publisher/place for Newspapers and we want the date delimited by a comma-->
+        <choose>
+          <if type="article-newspaper" match="none">
+            <choose>
+              <if type="article-journal" match="none">
+                <text macro="issue-note"/>
+              </if>
+              <else-if variable="issue volume" match="any">
+                <text macro="issue-note"/>
+              </else-if>
+            </choose>
+          </if>
+        </choose>
+      </if>
+    </choose>
+  </macro>
+  <macro name="issue-note-join-with-comma">
+    <choose>
+      <if type="article-journal legal_case manuscript thesis" variable="publisher-place publisher" match="none">
+        <text macro="issue-note"/>
+      </if>
+      <else-if type="article-newspaper">
+        <text macro="issue-note"/>
+      </else-if>
+      <else-if type="article-journal">
+        <choose>
+          <if variable="volume issue" match="none">
+            <text macro="issue-note"/>
+          </if>
+        </choose>
+      </else-if>
+    </choose>
+  </macro>
+  <macro name="issue-note">
+    <choose>
+      <if type="legal_case" match="any">
+        <text macro="issued" prefix="(" suffix=")"/>
+      </if>
+      <else-if type="article-journal">
+        <choose>
+          <if variable="volume issue" match="any">
+            <text macro="issued" prefix="(" suffix=")"/>
+          </if>
+          <else>
+            <text macro="issued"/>
+          </else>
+        </choose>
+      </else-if>
+      <else-if type="article-newspaper">
+        <text macro="issued"/>
+      </else-if>
+      <else-if variable="publisher-place event-place publisher genre" match="any">
+        <group prefix="(" suffix=")" delimiter=", ">
+          <choose>
+            <if variable="title" match="none"/>
+            <else-if type="manuscript thesis speech" match="any">
+              <text variable="genre"/>
+            </else-if>
+          </choose>
+          <text macro="event-note"/>
+          <group delimiter="; ">
+            <text macro="originally-published"/>
+            <group delimiter=", ">
+              <text macro="reprint-note"/>
+              <text macro="publisher"/>
+            </group>
+          </group>
+          <text macro="issued"/>
+        </group>
+      </else-if>
+      <else>
+        <text macro="issued"/>
+      </else>
+    </choose>
+  </macro>
+  <macro name="issue-join-with-space">
+    <choose>
+      <if type="article-journal legal_case" match="any">
+        <choose>
+          <if variable="issue volume" match="any">
+            <text macro="issue"/>
+          </if>
+        </choose>
+      </if>
+    </choose>
+  </macro>
+  <macro name="issue-join-with-period">
+    <choose>
+      <if type="article-journal legal_case" match="none">
+        <choose>
+          <if type="speech" variable="publisher publisher-place" match="any">
+            <text macro="issue"/>
+          </if>
+        </choose>
+      </if>
+    </choose>
+  </macro>
+  <macro name="issue-join-with-comma">
+    <choose>
+      <if type="article-journal legal_case" match="none">
+        <choose>
+          <if type="speech" variable="publisher publisher-place" match="none">
+            <text macro="issue"/>
+          </if>
+        </choose>
+      </if>
+      <else-if variable="volume issue" match="none">
+        <text macro="issue"/>
+      </else-if>
+    </choose>
+  </macro>
+  <macro name="issue">
+    <choose>
+      <if type="legal_case" match="any">
+        <text macro="issued" prefix="(" suffix=")"/>
+      </if>
+      <else-if type="article-journal">
+        <choose>
+          <if variable="issue volume" match="any">
+            <text macro="issued" prefix="(" suffix=")"/>
+          </if>
+          <else>
+            <text macro="issued"/>
+          </else>
+        </choose>
+      </else-if>
+      <else-if type="speech">
+        <group delimiter=", ">
+          <group delimiter=" ">
+            <choose>
+              <if variable="title" match="none"/>
+              <else>
+                <text variable="genre" text-case="capitalize-first"/>
+              </else>
+            </choose>
+            <text macro="event"/>
+          </group>
+          <text variable="event-place"/>
+          <text macro="issued"/>
+        </group>
+      </else-if>
+      <!--Chicago doesn't use publisher/place for Newspapers -->
+      <else-if type="article-newspaper">
+        <text macro="issued"/>
+      </else-if>
+      <else-if variable="publisher-place publisher" match="any">
+        <group delimiter=", ">
+          <choose>
+            <if type="thesis">
+              <text variable="genre" text-case="capitalize-first"/>
+            </if>
+          </choose>
+          <group delimiter=". ">
+            <text macro="originally-published"/>
+            <group delimiter=", ">
+              <text macro="reprint"/>
+              <text macro="publisher"/>
+            </group>
+          </group>
+          <text macro="issued"/>
+        </group>
+      </else-if>
+      <else>
+        <text macro="issued"/>
+      </else>
+    </choose>
+  </macro>
+  <macro name="access-note">
+    <group delimiter=", ">
+      <choose>
+        <if type="graphic report" match="any">
+          <text macro="archive-note"/>
+        </if>
+        <else-if type="article-journal bill book chapter legal_case legislation motion_picture paper-conference" match="none">
+          <text macro="archive-note"/>
+        </else-if>
+      </choose>
+      <choose>
+        <if variable="issued" match="none">
+          <group delimiter=" ">
+            <text term="accessed"/>
+            <date variable="accessed" form="text"/>
+          </group>
+        </if>
+      </choose>
+      <choose>
+        <if type="legal_case" match="none">
+          <choose>
+            <if variable="DOI">
+              <text variable="DOI" prefix="doi:"/>
+            </if>
+            <else>
+              <text variable="URL"/>
+            </else>
+          </choose>
+        </if>
+      </choose>
+    </group>
+  </macro>
+  <macro name="access">
+    <group delimiter=". ">
+      <choose>
+        <if type="graphic report" match="any">
+          <text macro="archive"/>
+        </if>
+        <else-if type="article-journal bill book chapter legal_case legislation motion_picture paper-conference" match="none">
+          <text macro="archive"/>
+        </else-if>
+      </choose>
+      <choose>
+        <if variable="issued" match="none">
+          <group delimiter=" ">
+            <text term="accessed" text-case="capitalize-first"/>
+            <date variable="accessed" form="text"/>
+          </group>
+        </if>
+      </choose>
+      <choose>
+        <if type="legal_case" match="none">
+          <choose>
+            <if variable="DOI">
+              <text variable="DOI" prefix="doi:"/>
+            </if>
+            <else>
+              <text variable="URL"/>
+            </else>
+          </choose>
+        </if>
+      </choose>
+    </group>
+  </macro>
+  <macro name="case-locator-subsequent">
+    <choose>
+      <if type="legal_case">
+        <text macro="locators-note"/>
+      </if>
+    </choose>
+  </macro>
+  <macro name="case-issue-subsequent">
+    <choose>
+      <if type="legal_case">
+        <text macro="issue"/>
+      </if>
+    </choose>
+  </macro>
+  <citation et-al-min="4" et-al-use-first="1" disambiguate-add-names="true">
+    <layout suffix="." delimiter="; ">
+      <choose>
+        <if position="ibid-with-locator">
+          <group delimiter=", ">
+            <text term="ibid"/>
+            <text macro="point-locators-subsequent"/>
+          </group>
+        </if>
+        <else-if position="ibid">
+          <text term="ibid"/>
+        </else-if>
+        <else>
+          <group delimiter=", ">
+            <text macro="contributors-short"/>
+            <group delimiter=" ">
+              <group delimiter=", ">
+                <text macro="title-short"/>
+                <!--if title & author are the same: -->
+                <text macro="date-disambiguate"/>
+                <text macro="case-locator-subsequent"/>
+              </group>
+              <text macro="case-issue-subsequent"/>
+            </group>
+            <text macro="point-locators-subsequent"/>
+          </group>
+        </else>
+      </choose>
+    </layout>
+  </citation>
+  <bibliography hanging-indent="true" et-al-min="11" et-al-use-first="7" subsequent-author-substitute="&#8212;&#8212;&#8212;" entry-spacing="0">
+    <sort>
+      <key macro="contributors-sort"/>
+      <key variable="title"/>
+      <key variable="genre"/>
+      <key variable="issued"/>
+    </sort>
+    <layout suffix=".">
+      <group delimiter=". ">
+        <group delimiter=": ">
+          <group delimiter=", ">
+            <group delimiter=" ">
+              <group delimiter=". ">
+                <group delimiter=" ">
+                  <group delimiter=", ">
+                    <group delimiter=". ">
+                      <group delimiter=". ">
+                        <text macro="contributors"/>
+                        <text macro="title"/>
+                      </group>
+                      <text macro="description"/>
+                      <text macro="secondary-contributors"/>
+                      <group delimiter=", ">
+                        <text macro="container-title"/>
+                        <text macro="container-contributors"/>
+                      </group>
+                      <text macro="locators-join-with-period"/>
+                    </group>
+                    <text macro="locators-join-with-comma"/>
+                    <text macro="locators-chapter"/>
+                  </group>
+                  <text macro="locators-join-with-space"/>
+                </group>
+                <text macro="collection-title"/>
+                <text macro="issue-join-with-period"/>
+              </group>
+              <text macro="issue-join-with-space"/>
+            </group>
+            <text macro="issue-join-with-comma"/>
+            <text macro="locators-journal-join-with-comma"/>
+            <text macro="locators-newspaper"/>
+          </group>
+          <text macro="locators-journal-join-with-colon"/>
+        </group>
+        <text macro="access"/>
+      </group>
+      <text variable="note" display="block"/>
+    </layout>
+  </bibliography>
+</style>
diff --git a/test/command/chicago-author-date-with-original-date-and-status.csl b/test/command/chicago-author-date-with-original-date-and-status.csl
new file mode 100644
--- /dev/null
+++ b/test/command/chicago-author-date-with-original-date-and-status.csl
@@ -0,0 +1,575 @@
+<?xml version="1.0" encoding="utf-8"?>
+<style xmlns="http://purl.org/net/xbiblio/csl" class="in-text" version="1.0" demote-non-dropping-particle="never" page-range-format="chicago">
+  <info>
+    <title>Chicago Manual of Style 16th edition (author-date)</title>
+    <id>http://www.zotero.org/styles/chicago-author-date</id>
+    <link href="http://www.zotero.org/styles/chicago-author-date" rel="self"/>
+    <link href="http://www.chicagomanualofstyle.org/tools_citationguide.html" rel="documentation"/>
+    <author>
+      <name>Julian Onions</name>
+      <email>julian.onions@gmail.com</email>
+    </author>
+    <contributor>
+      <name>Sebastian Karcher</name>
+    </contributor>
+    <contributor>
+      <name>Richard Karnesky</name>
+      <email>karnesky+zotero@gmail.com</email>
+      <uri>http://arc.nucapt.northwestern.edu/Richard_Karnesky</uri>
+    </contributor>
+    <contributor>
+      <name>Andrew Dunning</name>
+      <email>andrew.dunning@utoronto.ca</email>
+    </contributor>
+    <category citation-format="author-date"/>
+    <category field="generic-base"/>
+    <summary>The author-date variant of the Chicago style</summary>
+    <updated>2014-05-23T03:53:32+00:00</updated>
+    <rights license="http://creativecommons.org/licenses/by-sa/3.0/">This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 License</rights>
+  </info>
+  <locale xml:lang="en">
+    <terms>
+      <term name="editor" form="verb-short">ed.</term>
+      <term name="container-author" form="verb">by</term>
+      <term name="translator" form="verb-short">trans.</term>
+      <term name="editortranslator" form="verb">
+        <single>edited and translated by</single>
+        <multiple>edited and translated by</multiple>
+      </term>
+      <term name="translator" form="short">trans.</term>
+    </terms>
+  </locale>
+  <macro name="secondary-contributors">
+    <choose>
+      <if type="chapter paper-conference" match="none">
+        <names variable="editor translator" delimiter=". ">
+          <label form="verb" text-case="capitalize-first" suffix=" "/>
+          <name and="text" delimiter=", "/>
+        </names>
+      </if>
+    </choose>
+  </macro>
+  <macro name="container-contributors">
+    <choose>
+      <if type="chapter paper-conference" match="any">
+        <group prefix=", " delimiter=", ">
+          <names variable="container-author" delimiter=", ">
+            <label form="verb" suffix=" "/>
+            <name and="text" delimiter=", "/>
+          </names>
+          <names variable="editor translator" delimiter=", ">
+            <label form="verb" suffix=" "/>
+            <name and="text" delimiter=", "/>
+          </names>
+        </group>
+      </if>
+    </choose>
+  </macro>
+  <macro name="editor">
+    <names variable="editor">
+      <name name-as-sort-order="first" and="text" sort-separator=", " delimiter=", " delimiter-precedes-last="always"/>
+      <label form="short" prefix=", "/>
+    </names>
+  </macro>
+  <macro name="translator">
+    <names variable="translator">
+      <name name-as-sort-order="first" and="text" sort-separator=", " delimiter=", " delimiter-precedes-last="always"/>
+      <label form="short" prefix=", "/>
+    </names>
+  </macro>
+  <macro name="recipient">
+    <choose>
+      <if type="personal_communication">
+        <choose>
+          <if variable="genre">
+            <text variable="genre" text-case="capitalize-first"/>
+          </if>
+          <else>
+            <text term="letter" text-case="capitalize-first"/>
+          </else>
+        </choose>
+      </if>
+    </choose>
+    <names variable="recipient" delimiter=", ">
+      <label form="verb" prefix=" " text-case="lowercase" suffix=" "/>
+      <name and="text" delimiter=", "/>
+    </names>
+  </macro>
+  <macro name="contributors">
+    <group delimiter=". ">
+      <names variable="author">
+        <name and="text" name-as-sort-order="first" sort-separator=", " delimiter=", " delimiter-precedes-last="always"/>
+        <label form="short" prefix=", "/>
+        <substitute>
+          <names variable="editor"/>
+          <names variable="translator"/>
+          <text macro="title"/>
+        </substitute>
+      </names>
+      <text macro="recipient"/>
+    </group>
+  </macro>
+  <macro name="contributors-short">
+    <names variable="author">
+      <name form="short" and="text" delimiter=", " initialize-with=". "/>
+      <substitute>
+        <names variable="editor"/>
+        <names variable="translator"/>
+        <text macro="title"/>
+      </substitute>
+    </names>
+  </macro>
+  <macro name="interviewer">
+    <names variable="interviewer" delimiter=", ">
+      <label form="verb" prefix=" " text-case="capitalize-first" suffix=" "/>
+      <name and="text" delimiter=", "/>
+    </names>
+  </macro>
+  <macro name="archive">
+    <group delimiter=". ">
+      <text variable="archive_location" text-case="capitalize-first"/>
+      <text variable="archive"/>
+      <text variable="archive-place"/>
+    </group>
+  </macro>
+  <macro name="access">
+    <group delimiter=". ">
+      <choose>
+        <if type="graphic report" match="any">
+          <text macro="archive"/>
+        </if>
+        <else-if type="article-journal bill book chapter legal_case legislation motion_picture paper-conference" match="none">
+          <text macro="archive"/>
+        </else-if>
+      </choose>
+      <choose>
+        <if variable="issued" match="none">
+          <group delimiter=" ">
+            <text term="accessed" text-case="capitalize-first"/>
+            <date variable="accessed" delimiter=" ">
+              <date-part name="month"/>
+              <date-part name="day"/>
+            </date>
+          </group>
+        </if>
+      </choose>
+      <choose>
+        <if type="legal_case" match="none">
+          <choose>
+            <if variable="DOI">
+              <text variable="DOI" prefix="doi:"/>
+            </if>
+            <else>
+              <text variable="URL"/>
+            </else>
+          </choose>
+        </if>
+      </choose>
+    </group>
+  </macro>
+  <macro name="title">
+    <choose>
+      <if variable="title" match="none">
+        <choose>
+          <if type="personal_communication" match="none">
+            <text variable="genre" text-case="capitalize-first"/>
+          </if>
+        </choose>
+      </if>
+      <else-if type="bill book graphic legislation motion_picture report song" match="any">
+        <text variable="title" text-case="title" font-style="italic"/>
+        <group prefix=" (" suffix=")" delimiter=" ">
+          <text term="version"/>
+          <text variable="version"/>
+        </group>
+      </else-if>
+      <else-if variable="reviewed-author">
+        <group delimiter=", ">
+          <text variable="title" font-style="italic" prefix="Review of "/>
+          <names variable="reviewed-author">
+            <label form="verb-short" text-case="lowercase" suffix=" "/>
+            <name and="text" delimiter=", "/>
+          </names>
+        </group>
+      </else-if>
+      <else-if type="legal_case interview" match="any">
+        <text variable="title"/>
+      </else-if>
+      <else>
+        <text variable="title" text-case="title" quotes="true"/>
+      </else>
+    </choose>
+  </macro>
+  <macro name="edition">
+    <choose>
+      <if type="bill book graphic legal_case legislation motion_picture report song" match="any">
+        <choose>
+          <if is-numeric="edition">
+            <group delimiter=" " prefix=". ">
+              <number variable="edition" form="ordinal"/>
+              <text term="edition" form="short" strip-periods="true"/>
+            </group>
+          </if>
+          <else>
+            <text variable="edition" prefix=". "/>
+          </else>
+        </choose>
+      </if>
+      <else-if type="chapter  paper-conference" match="any">
+        <choose>
+          <if is-numeric="edition">
+            <group delimiter=" " prefix=", ">
+              <number variable="edition" form="ordinal"/>
+              <text term="edition" form="short"/>
+            </group>
+          </if>
+          <else>
+            <text variable="edition" prefix=", "/>
+          </else>
+        </choose>
+      </else-if>
+    </choose>
+  </macro>
+  <macro name="locators">
+    <choose>
+      <if type="article-journal">
+        <choose>
+          <if variable="volume">
+            <text variable="volume" prefix=" "/>
+            <group prefix=" (" suffix=")">
+              <choose>
+                <if variable="issue">
+                  <text variable="issue"/>
+                </if>
+                <else>
+                  <date variable="issued">
+                    <date-part name="month"/>
+                  </date>
+                </else>
+              </choose>
+            </group>
+          </if>
+          <else-if variable="issue">
+            <group delimiter=" " prefix=", ">
+              <text term="issue" form="short"/>
+              <text variable="issue"/>
+              <date variable="issued" prefix="(" suffix=")">
+                <date-part name="month"/>
+              </date>
+            </group>
+          </else-if>
+          <else>
+            <date variable="issued" prefix=", ">
+              <date-part name="month"/>
+            </date>
+          </else>
+        </choose>
+      </if>
+      <else-if type="legal_case">
+        <text variable="volume" prefix=", "/>
+        <text variable="container-title" prefix=" "/>
+        <text variable="page" prefix=" "/>
+      </else-if>
+      <else-if type="bill book graphic legal_case legislation motion_picture report song" match="any">
+        <group prefix=". " delimiter=". ">
+          <group>
+            <text term="volume" form="short" text-case="capitalize-first" suffix=" "/>
+            <number variable="volume" form="numeric"/>
+          </group>
+          <group>
+            <number variable="number-of-volumes" form="numeric"/>
+            <text term="volume" form="short" prefix=" " plural="true"/>
+          </group>
+        </group>
+      </else-if>
+      <else-if type="chapter paper-conference" match="any">
+        <choose>
+          <if variable="page" match="none">
+            <group prefix=". ">
+              <text term="volume" form="short" text-case="capitalize-first" suffix=" "/>
+              <number variable="volume" form="numeric"/>
+            </group>
+          </if>
+        </choose>
+      </else-if>
+    </choose>
+  </macro>
+  <macro name="locators-chapter">
+    <choose>
+      <if type="chapter paper-conference" match="any">
+        <choose>
+          <if variable="page">
+            <group prefix=", ">
+              <text variable="volume" suffix=":"/>
+              <text variable="page"/>
+            </group>
+          </if>
+        </choose>
+      </if>
+    </choose>
+  </macro>
+  <macro name="locators-article">
+    <choose>
+      <if type="article-newspaper">
+        <group prefix=", " delimiter=", ">
+          <group>
+            <text variable="edition" suffix=" "/>
+            <text term="edition" prefix=" "/>
+          </group>
+          <group>
+            <text term="section" form="short" suffix=" "/>
+            <text variable="section"/>
+          </group>
+        </group>
+      </if>
+      <else-if type="article-journal">
+        <choose>
+          <if variable="volume issue" match="any">
+            <text variable="page" prefix=": "/>
+          </if>
+          <else>
+            <text variable="page" prefix=", "/>
+          </else>
+        </choose>
+      </else-if>
+    </choose>
+  </macro>
+  <macro name="point-locators">
+    <choose>
+      <if variable="locator">
+        <choose>
+          <if locator="page" match="none">
+            <choose>
+              <if type="bill book graphic legal_case legislation motion_picture report song" match="any">
+                <choose>
+                  <if variable="volume">
+                    <group>
+                      <text term="volume" form="short" suffix=" "/>
+                      <number variable="volume" form="numeric"/>
+                      <label variable="locator" form="short" prefix=", " suffix=" "/>
+                    </group>
+                  </if>
+                  <else>
+                    <label variable="locator" form="short" suffix=" "/>
+                  </else>
+                </choose>
+              </if>
+              <else>
+                <label variable="locator" form="short" suffix=" "/>
+              </else>
+            </choose>
+          </if>
+          <else-if type="bill book graphic legal_case legislation motion_picture report song" match="any">
+            <number variable="volume" form="numeric" suffix=":"/>
+          </else-if>
+        </choose>
+        <text variable="locator"/>
+      </if>
+    </choose>
+  </macro>
+  <macro name="container-prefix">
+    <text term="in" text-case="capitalize-first"/>
+  </macro>
+  <macro name="container-title">
+    <choose>
+      <if type="chapter paper-conference" match="any">
+        <text macro="container-prefix" suffix=" "/>
+      </if>
+    </choose>
+    <choose>
+      <if type="legal_case" match="none">
+        <text variable="container-title" text-case="title" font-style="italic"/>
+      </if>
+    </choose>
+  </macro>
+  <macro name="publisher">
+    <group delimiter=": ">
+      <text variable="publisher-place"/>
+      <text variable="publisher"/>
+    </group>
+  </macro>
+  <macro name="date-citation">
+    <choose>
+      <if variable="original-date">
+        <date variable="original-date" prefix="["  suffix="]">
+        <date-part name="year"/>
+      </date>
+      </if>
+    </choose>
+  <choose>
+    <if variable="issued">
+      <date variable="issued" prefix=" ">
+        <date-part name="year"/>
+      </date>
+    </if>
+    <else-if variable="status">
+      <text variable="status" prefix=", "/>
+    </else-if>
+    <else-if variable="accessed">
+      <date variable="accessed" prefix=" ">
+        <date-part name="year"/>
+      </date>
+    </else-if>
+    </choose>
+  </macro>
+  <macro name="date-bibliography">
+      <choose>
+        <if variable="original-date">
+          <date variable="original-date" prefix=" ("  suffix=") ">
+          <date-part name="year"/>
+        </date>
+        </if>
+      </choose>
+    <choose>
+      <if variable="issued">
+        <date variable="issued">
+          <date-part name="year"/>
+        </date>
+      </if>
+      <else-if variable="status">
+        <text variable="status" text-case="capitalize-first"/>
+      </else-if>
+      <else-if variable="accessed">
+        <date variable="accessed">
+          <date-part name="year"/>
+        </date>
+      </else-if>
+    </choose>
+  </macro>
+  <macro name="day-month">
+    <date variable="issued">
+      <date-part name="month"/>
+      <date-part name="day" prefix=" "/>
+    </date>
+  </macro>
+  <macro name="collection-title">
+    <choose>
+      <if match="none" type="article-journal">
+        <choose>
+          <if match="none" is-numeric="collection-number">
+            <group delimiter=", ">
+              <text variable="collection-title" text-case="title"/>
+              <text variable="collection-number"/>
+            </group>
+          </if>
+          <else>
+            <group delimiter=" ">
+              <text variable="collection-title" text-case="title"/>
+              <text variable="collection-number"/>
+            </group>
+          </else>
+        </choose>
+      </if>
+    </choose>
+  </macro>
+  <macro name="collection-title-journal">
+    <choose>
+      <if type="article-journal">
+        <group delimiter=" ">
+          <text variable="collection-title"/>
+          <text variable="collection-number"/>
+        </group>
+      </if>
+    </choose>
+  </macro>
+  <macro name="event">
+    <group>
+      <text term="presented at" suffix=" "/>
+      <text variable="event"/>
+    </group>
+  </macro>
+  <macro name="description">
+    <choose>
+      <if type="interview">
+        <group delimiter=". ">
+          <text macro="interviewer"/>
+          <text variable="medium" text-case="capitalize-first"/>
+        </group>
+      </if>
+      <else>
+        <text variable="medium" text-case="capitalize-first" prefix=". "/>
+      </else>
+    </choose>
+    <choose>
+      <if variable="title" match="none"/>
+      <else-if type="thesis personal_communication speech" match="any"/>
+      <else>
+        <group delimiter=" " prefix=". ">
+          <text variable="genre" text-case="capitalize-first"/>
+          <choose>
+            <if type="report">
+              <text variable="number"/>
+            </if>
+          </choose>
+        </group>
+      </else>
+    </choose>
+  </macro>
+  <macro name="issue">
+    <choose>
+      <if type="legal_case">
+        <text variable="authority" prefix=". "/>
+      </if>
+      <else-if type="speech">
+        <group prefix=". " delimiter=", ">
+          <group delimiter=" ">
+            <text variable="genre" text-case="capitalize-first"/>
+            <text macro="event"/>
+          </group>
+          <text variable="event-place"/>
+          <text macro="day-month"/>
+        </group>
+      </else-if>
+      <else-if type="article-newspaper article-magazine personal_communication" match="any">
+        <text macro="day-month" prefix=", "/>
+      </else-if>
+      <else>
+        <group prefix=". " delimiter=", ">
+          <choose>
+            <if type="thesis">
+              <text variable="genre" text-case="capitalize-first"/>
+            </if>
+          </choose>
+          <text macro="publisher"/>
+        </group>
+      </else>
+    </choose>
+  </macro>
+  <citation et-al-min="4" et-al-use-first="1" disambiguate-add-year-suffix="true" disambiguate-add-names="true" disambiguate-add-givenname="true" givenname-disambiguation-rule="primary-name">
+    <layout prefix="(" suffix=")" delimiter="; ">
+      <group delimiter=", ">
+        <group delimiter=" ">
+          <text macro="contributors-short"/>
+          <text macro="date-citation"/>
+        </group>
+        <text macro="point-locators"/>
+      </group>
+    </layout>
+  </citation>
+  <bibliography hanging-indent="true" et-al-min="11" et-al-use-first="7" subsequent-author-substitute="&#8212;&#8212;&#8212;" entry-spacing="0">
+    <sort>
+      <key macro="contributors"/>
+      <key variable="original-date"/>
+      <key variable="issued"/>
+    </sort>
+    <layout suffix=".">
+      <group delimiter=". ">
+        <text macro="contributors"/>
+        <text macro="date-bibliography" text-case="capitalize-first"/> 
+        <text macro="title"/>
+      </group>
+      <text macro="description"/>
+      <text macro="secondary-contributors" prefix=". "/>
+      <text macro="container-title" prefix=". "/>
+      <text macro="container-contributors"/>
+      <text macro="edition"/>
+      <text macro="locators-chapter"/>
+      <text macro="collection-title-journal" prefix=", " suffix=", "/>
+      <text macro="locators"/>
+      <text macro="collection-title" prefix=". "/>
+      <text macro="issue"/>
+      <text macro="locators-article"/>
+      <text macro="access" prefix=". "/>
+    </layout>
+  </bibliography>
+</style>
diff --git a/test/command/chicago-fullnote-bibliography.csl b/test/command/chicago-fullnote-bibliography.csl
new file mode 100644
--- /dev/null
+++ b/test/command/chicago-fullnote-bibliography.csl
@@ -0,0 +1,1430 @@
+<?xml version="1.0" encoding="utf-8"?>
+<style xmlns="http://purl.org/net/xbiblio/csl" class="note" version="1.0" demote-non-dropping-particle="display-and-sort" page-range-format="chicago">
+  <info>
+    <title>Chicago Manual of Style 17th edition (full note)</title>
+    <id>http://www.zotero.org/styles/chicago-fullnote-bibliography</id>
+    <link href="http://www.zotero.org/styles/chicago-fullnote-bibliography" rel="self"/>
+    <link href="http://www.chicagomanualofstyle.org/tools_citationguide.html" rel="documentation"/>
+    <author>
+      <name>Julian Onions</name>
+      <email>julian.onions@gmail.com</email>
+    </author>
+    <contributor>
+      <name>Simon Kornblith</name>
+      <email>simon@simonster.com</email>
+    </contributor>
+    <contributor>
+      <name>Elena Razlogova</name>
+      <email>elena.razlogova@gmail.com</email>
+    </contributor>
+    <contributor>
+      <name>Frank Bennett</name>
+      <email>biercenator@gmail.com</email>
+    </contributor>
+    <contributor>
+      <name>Andrew Dunning</name>
+      <email>andrew.dunning@utoronto.ca</email>
+    </contributor>
+    <contributor>
+      <name>Sebastian Karcher</name>
+    </contributor>
+    <category citation-format="note"/>
+    <category field="generic-base"/>
+    <summary>Chicago format with full notes and bibliography</summary>
+    <updated>2017-10-12T12:00:00+00:00</updated>
+    <rights license="http://creativecommons.org/licenses/by-sa/3.0/">This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 License</rights>
+  </info>
+  <locale xml:lang="en">
+    <terms>
+      <term name="editor" form="verb-short">ed.</term>
+      <term name="translator" form="verb-short">trans.</term>
+      <term name="translator" form="short">trans.</term>
+      <term name="editortranslator" form="verb-short">ed. and trans.</term>
+      <term name="editortranslator" form="verb">Edited and translated by</term>
+      <term name="translator" form="short">trans.</term>
+    </terms>
+  </locale>
+  <macro name="editor-translator">
+    <group delimiter=", ">
+      <group delimiter=" ">
+        <choose>
+          <if variable="container-author reviewed-author" match="any">
+            <group>
+              <names variable="container-author reviewed-author">
+                <label form="verb-short" text-case="lowercase" suffix=" "/>
+                <name and="text" delimiter=", "/>
+              </names>
+            </group>
+          </if>
+        </choose>
+      </group>
+      <names variable="editor translator" delimiter=", ">
+        <label form="verb-short" text-case="lowercase" suffix=" "/>
+        <name and="text" delimiter=", "/>
+      </names>
+    </group>
+  </macro>
+  <macro name="secondary-contributors-note">
+    <choose>
+      <if type="chapter entry-dictionary entry-encyclopedia paper-conference" match="none">
+        <text macro="editor-translator"/>
+      </if>
+    </choose>
+  </macro>
+  <macro name="container-contributors-note">
+    <choose>
+      <if type="chapter entry-dictionary entry-encyclopedia paper-conference" match="any">
+        <text macro="editor-translator"/>
+      </if>
+    </choose>
+  </macro>
+  <macro name="secondary-contributors">
+    <choose>
+      <if type="chapter entry-dictionary entry-encyclopedia paper-conference" match="none">
+        <names variable="editor translator" delimiter=". ">
+          <label form="verb" text-case="capitalize-first" suffix=" "/>
+          <name and="text" delimiter=", "/>
+        </names>
+      </if>
+    </choose>
+  </macro>
+  <macro name="container-contributors">
+    <choose>
+      <if type="chapter entry-dictionary entry-encyclopedia paper-conference" match="any">
+        <group delimiter=", ">
+          <choose>
+            <if variable="author">
+              <choose>
+                <if variable="container-author" match="any">
+                  <names variable="container-author">
+                    <label form="verb-short" text-case="lowercase" suffix=" "/>
+                    <name and="text" delimiter=", "/>
+                  </names>
+                </if>
+              </choose>
+              <!--This includes page numbers after the container author, e.g. for Introductions -->
+              <choose>
+                <if variable="container-author author" match="all">
+                  <group delimiter=". ">
+                    <text variable="page"/>
+                    <names variable="editor translator" delimiter=", ">
+                      <label form="verb" suffix=" "/>
+                      <name and="text" delimiter=", "/>
+                    </names>
+                  </group>
+                </if>
+                <else>
+                  <names variable="editor translator" delimiter=", ">
+                    <label form="verb" text-case="lowercase" suffix=" "/>
+                    <name and="text" delimiter=", "/>
+                  </names>
+                </else>
+              </choose>
+            </if>
+          </choose>
+        </group>
+      </if>
+    </choose>
+  </macro>
+  <macro name="recipient-note">
+    <names variable="recipient" delimiter=", ">
+      <label form="verb" text-case="lowercase" suffix=" "/>
+      <name and="text" delimiter=", "/>
+    </names>
+  </macro>
+  <macro name="contributors-note">
+    <group delimiter=" ">
+      <names variable="author">
+        <name and="text" sort-separator=", " delimiter=", "/>
+        <label form="short" prefix=", "/>
+        <substitute>
+          <names variable="editor"/>
+          <names variable="translator"/>
+        </substitute>
+      </names>
+      <text macro="recipient-note"/>
+    </group>
+  </macro>
+  <macro name="editor">
+    <names variable="editor">
+      <name name-as-sort-order="first" and="text" sort-separator=", " delimiter=", " delimiter-precedes-last="always"/>
+      <label form="short" prefix=", "/>
+    </names>
+  </macro>
+  <macro name="translator">
+    <names variable="translator">
+      <name name-as-sort-order="first" and="text" sort-separator=", " delimiter=", " delimiter-precedes-last="always"/>
+      <label form="verb-short" prefix=", "/>
+    </names>
+  </macro>
+  <macro name="recipient">
+    <group delimiter=" ">
+      <choose>
+        <if type="personal_communication">
+          <choose>
+            <if variable="genre">
+              <text variable="genre" text-case="capitalize-first"/>
+            </if>
+            <else>
+              <text term="letter" text-case="capitalize-first"/>
+            </else>
+          </choose>
+        </if>
+      </choose>
+      <text macro="recipient-note"/>
+    </group>
+  </macro>
+  <macro name="contributors">
+    <group delimiter=". ">
+      <names variable="author">
+        <name name-as-sort-order="first" and="text" sort-separator=", " delimiter=", " delimiter-precedes-last="always"/>
+        <substitute>
+          <text macro="editor"/>
+          <text macro="translator"/>
+        </substitute>
+      </names>
+      <text macro="recipient"/>
+    </group>
+  </macro>
+  <macro name="recipient-short">
+    <names variable="recipient">
+      <label form="verb" text-case="lowercase" suffix=" "/>
+      <name form="short" and="text" delimiter=", "/>
+    </names>
+  </macro>
+  <macro name="contributors-short">
+    <group delimiter=" ">
+      <names variable="author">
+        <name form="short" and="text" delimiter=", "/>
+        <substitute>
+          <names variable="editor"/>
+          <names variable="translator"/>
+        </substitute>
+      </names>
+      <text macro="recipient-short"/>
+    </group>
+  </macro>
+  <macro name="contributors-sort">
+    <names variable="author">
+      <name name-as-sort-order="all" and="text" sort-separator=", " delimiter=", " delimiter-precedes-last="always"/>
+      <substitute>
+        <names variable="editor"/>
+        <names variable="translator"/>
+        <text macro="title"/>
+      </substitute>
+    </names>
+  </macro>
+  <macro name="interviewer-note">
+    <names variable="interviewer" delimiter=", ">
+      <label form="verb" text-case="lowercase" suffix=" "/>
+      <name and="text" delimiter=", "/>
+    </names>
+  </macro>
+  <macro name="interviewer">
+    <names variable="interviewer" delimiter=", ">
+      <label form="verb" text-case="capitalize-first" suffix=" "/>
+      <name and="text" delimiter=", "/>
+    </names>
+  </macro>
+  <macro name="title-note">
+    <choose>
+      <if variable="title" match="none">
+        <text variable="genre"/>
+      </if>
+      <else-if type="book graphic map motion_picture song" match="any">
+        <text variable="title" text-case="title" font-style="italic"/>
+        <group delimiter=" " prefix=", ">
+          <text term="version"/>
+          <text variable="version"/>
+        </group>
+      </else-if>
+      <else-if type="legal_case interview patent" match="any">
+        <text variable="title"/>
+      </else-if>
+      <else-if variable="reviewed-author">
+        <text variable="title" font-style="italic" prefix="review of "/>
+      </else-if>
+      <else>
+        <text variable="title" text-case="title" quotes="true"/>
+      </else>
+    </choose>
+  </macro>
+  <macro name="title">
+    <choose>
+      <if variable="title" match="none">
+        <choose>
+          <if type="personal_communication" match="none">
+            <text variable="genre" text-case="capitalize-first"/>
+          </if>
+        </choose>
+      </if>
+      <else-if type="book graphic motion_picture song" match="any">
+        <text variable="title" text-case="title" font-style="italic"/>
+        <group prefix=" (" suffix=")" delimiter=" ">
+          <text term="version"/>
+          <text variable="version"/>
+        </group>
+      </else-if>
+      <else-if variable="reviewed-author">
+        <group delimiter=", ">
+          <text variable="title" font-style="italic" prefix="Review of "/>
+          <names variable="reviewed-author">
+            <label form="verb-short" text-case="lowercase" suffix=" "/>
+            <name and="text" delimiter=", "/>
+          </names>
+        </group>
+      </else-if>
+      <else-if type="bill legislation legal_case interview patent" match="any">
+        <text variable="title"/>
+      </else-if>
+      <else>
+        <text variable="title" text-case="title" quotes="true"/>
+      </else>
+    </choose>
+  </macro>
+  <macro name="title-short">
+    <choose>
+      <if variable="title" match="none">
+        <choose>
+          <if type="interview">
+            <text term="interview"/>
+          </if>
+          <else-if type="manuscript speech" match="any">
+            <text variable="genre" form="short"/>
+          </else-if>
+          <else-if type="personal_communication">
+            <text macro="issued"/>
+          </else-if>
+        </choose>
+      </if>
+      <else-if type="book graphic motion_picture song" match="any">
+        <text variable="title" text-case="title" form="short" font-style="italic"/>
+      </else-if>
+      <else-if type="legal_case" variable="title-short" match="all">
+        <text variable="title" font-style="italic" form="short"/>
+      </else-if>
+      <else-if type="patent interview" match="any">
+        <text variable="title" form="short"/>
+      </else-if>
+      <else-if type="legal_case bill legislation" match="any">
+        <text variable="title"/>
+      </else-if>
+      <else>
+        <text variable="title" text-case="title" form="short" quotes="true"/>
+      </else>
+    </choose>
+  </macro>
+  <macro name="date-disambiguate">
+    <choose>
+      <if disambiguate="true">
+        <text macro="issued"/>
+      </if>
+    </choose>
+  </macro>
+  <macro name="description-note">
+    <group delimiter=", ">
+      <text macro="interviewer-note"/>
+      <text variable="medium"/>
+      <choose>
+        <if variable="title" match="none"/>
+        <else-if type="manuscript thesis speech" match="any"/>
+        <else-if type="patent">
+          <group delimiter=" ">
+            <text variable="authority"/>
+            <text variable="number"/>
+          </group>
+        </else-if>
+        <else>
+          <text variable="genre"/>
+        </else>
+      </choose>
+      <choose>
+        <if type="map">
+          <text variable="scale"/>
+        </if>
+        <else-if type="graphic">
+          <text variable="dimensions"/>
+        </else-if>
+      </choose>
+    </group>
+  </macro>
+  <macro name="description">
+    <group delimiter=", ">
+      <group delimiter=". ">
+        <text macro="interviewer"/>
+        <text variable="medium" text-case="capitalize-first"/>
+      </group>
+      <choose>
+        <if variable="title" match="none"/>
+        <else-if type="thesis speech" match="any"/>
+        <else-if type="patent">
+          <group delimiter=" ">
+            <text variable="authority"/>
+            <text variable="number"/>
+          </group>
+        </else-if>
+        <else>
+          <text variable="genre" text-case="capitalize-first"/>
+        </else>
+      </choose>
+      <choose>
+        <if type="map">
+          <text variable="scale"/>
+        </if>
+        <else-if type="graphic">
+          <text variable="dimensions"/>
+        </else-if>
+      </choose>
+    </group>
+  </macro>
+  <macro name="container-title-note">
+    <group delimiter=" ">
+      <choose>
+        <if type="chapter entry-dictionary entry-encyclopedia paper-conference" match="any">
+          <text term="in"/>
+        </if>
+      </choose>
+      <choose>
+        <if type="webpage">
+          <text variable="container-title"/>
+        </if>
+        <else-if type="post-weblog">
+          <text variable="container-title" text-case="title" font-style="italic" suffix=" (blog)"/>
+        </else-if>
+        <else-if type="bill legislation legal_case" match="none">
+          <text variable="container-title" text-case="title" font-style="italic"/>
+        </else-if>
+      </choose>
+    </group>
+  </macro>
+  <macro name="container-title">
+    <group delimiter=" ">
+      <choose>
+        <if type="chapter entry-dictionary entry-encyclopedia paper-conference" match="any">
+          <text term="in" text-case="capitalize-first"/>
+        </if>
+      </choose>
+      <choose>
+        <if type="webpage">
+          <text variable="container-title"/>
+        </if>
+        <else-if type="post-weblog">
+          <text variable="container-title" text-case="title" font-style="italic" suffix=" (blog)"/>
+        </else-if>
+        <else-if type="bill legislation legal_case" match="none">
+          <text variable="container-title" text-case="title" font-style="italic"/>
+        </else-if>
+      </choose>
+    </group>
+  </macro>
+  <macro name="collection-title">
+    <choose>
+      <if match="none" type="article-journal">
+        <choose>
+          <if match="none" is-numeric="collection-number">
+            <group delimiter=", ">
+              <text variable="collection-title" text-case="title"/>
+              <text variable="collection-number"/>
+            </group>
+          </if>
+          <else>
+            <group delimiter=" ">
+              <text variable="collection-title" text-case="title"/>
+              <text variable="collection-number"/>
+            </group>
+          </else>
+        </choose>
+      </if>
+    </choose>
+  </macro>
+  <macro name="collection-title-journal">
+    <choose>
+      <if type="article-journal">
+        <group delimiter=" ">
+          <text variable="collection-title"/>
+          <text variable="collection-number"/>
+        </group>
+      </if>
+    </choose>
+  </macro>
+  <macro name="edition-note">
+    <choose>
+      <if type="book chapter graphic motion_picture paper-conference report song" match="any">
+        <choose>
+          <if is-numeric="edition">
+            <group delimiter=" ">
+              <number variable="edition" form="ordinal"/>
+              <text term="edition" form="short"/>
+            </group>
+          </if>
+          <else>
+            <text variable="edition"/>
+          </else>
+        </choose>
+      </if>
+    </choose>
+  </macro>
+  <macro name="edition">
+    <choose>
+      <if type="book chapter graphic motion_picture paper-conference report song" match="any">
+        <choose>
+          <if is-numeric="edition">
+            <group delimiter=" ">
+              <number variable="edition" form="ordinal"/>
+              <text term="edition" form="short"/>
+            </group>
+          </if>
+          <else>
+            <text variable="edition" text-case="capitalize-first" suffix="."/>
+          </else>
+        </choose>
+      </if>
+    </choose>
+  </macro>
+  <macro name="locators-note-join-with-space">
+    <choose>
+      <if type="article-journal" variable="volume" match="all">
+        <choose>
+          <if match="none" variable="collection-title">
+            <text macro="locators-note"/>
+          </if>
+        </choose>
+      </if>
+    </choose>
+  </macro>
+  <macro name="locators-note-join-with-comma">
+    <choose>
+      <if type="article-journal" match="none">
+        <text macro="locators-note"/>
+      </if>
+      <else-if type="article-journal">
+        <choose>
+          <if variable="volume" match="none">
+            <text macro="locators-note"/>
+          </if>
+          <else-if match="any" variable="collection-title">
+            <text macro="locators-note"/>
+          </else-if>
+        </choose>
+      </else-if>
+    </choose>
+  </macro>
+  <macro name="locators-note">
+    <choose>
+      <if type="article-journal">
+        <group delimiter=", ">
+          <text macro="collection-title-journal"/>
+          <number variable="volume"/>
+          <group delimiter=" ">
+            <text term="issue" form="short"/>
+            <number variable="issue"/>
+          </group>
+        </group>
+      </if>
+      <else-if type="bill legislation legal_case" match="any">
+        <text macro="legal-cites"/>
+      </else-if>
+      <else-if type="book chapter graphic motion_picture paper-conference report song" match="any">
+        <group delimiter=", ">
+          <text macro="edition-note"/>
+          <group delimiter=" ">
+            <text term="volume" form="short"/>
+            <number variable="volume" form="numeric"/>
+          </group>
+          <choose>
+            <if variable="locator" match="none">
+              <group delimiter=" ">
+                <number variable="number-of-volumes" form="numeric"/>
+                <text term="volume" form="short" plural="true"/>
+              </group>
+            </if>
+          </choose>
+        </group>
+      </else-if>
+    </choose>
+  </macro>
+  <macro name="legal-cites">
+    <choose>
+      <if type="legal_case" match="any">
+        <group delimiter=" ">
+          <choose>
+            <if variable="container-title">
+              <text variable="volume"/>
+              <text variable="container-title"/>
+              <group delimiter=" ">
+                <!--change to label variable="section" as that becomes available -->
+                <text term="section" form="symbol"/>
+                <text variable="section"/>
+              </group>
+              <text variable="page"/>
+            </if>
+            <else>
+              <text variable="number" prefix="No. "/>
+            </else>
+          </choose>
+        </group>
+      </if>
+      <else-if type="bill legislation" match="any">
+        <group delimiter=", ">
+          <choose>
+            <if variable="number">
+              <!--There's a public law number-->
+              <text variable="number" prefix="Pub. L. No. "/>
+              <group delimiter=" ">
+                <!--change to label variable="section" as that becomes available -->
+                <text term="section" form="symbol"/>
+                <text variable="section"/>
+              </group>
+              <group delimiter=" ">
+                <text variable="volume"/>
+                <text variable="container-title"/>
+                <text variable="page-first"/>
+              </group>
+            </if>
+            <else>
+              <group delimiter=" ">
+                <text variable="volume"/>
+                <text variable="container-title"/>
+                <!--change to label variable="section" as that becomes available -->
+                <text term="section" form="symbol"/>
+                <text variable="section"/>
+              </group>
+            </else>
+          </choose>
+        </group>
+      </else-if>
+    </choose>
+  </macro>
+  <macro name="locators-join-with-space">
+    <choose>
+      <if type="article-journal" variable="volume" match="all">
+        <choose>
+          <if match="none" variable="collection-title">
+            <text macro="locators"/>
+          </if>
+        </choose>
+      </if>
+    </choose>
+  </macro>
+  <macro name="locators-join-with-comma">
+    <choose>
+      <if type="bill chapter legislation legal_case paper-conference" match="any">
+        <text macro="locators"/>
+      </if>
+      <else-if type="article-journal">
+        <choose>
+          <if variable="volume" match="none">
+            <text macro="locators"/>
+          </if>
+          <else-if match="any" variable="collection-title">
+            <text macro="locators"/>
+          </else-if>
+        </choose>
+      </else-if>
+    </choose>
+  </macro>
+  <macro name="locators-join-with-period">
+    <choose>
+      <if type="bill legislation legal_case article-journal chapter paper-conference" match="none">
+        <text macro="locators"/>
+      </if>
+    </choose>
+  </macro>
+  <macro name="locators">
+    <choose>
+      <if type="article-journal">
+        <group delimiter=", ">
+          <text macro="collection-title-journal"/>
+          <number variable="volume"/>
+          <group delimiter=" ">
+            <text term="issue" form="short"/>
+            <number variable="issue"/>
+          </group>
+        </group>
+      </if>
+      <else-if type="bill legislation legal_case" match="any">
+        <text macro="legal-cites"/>
+      </else-if>
+      <else-if type="book graphic motion_picture report song" match="any">
+        <group delimiter=". ">
+          <text macro="edition"/>
+          <group delimiter=" ">
+            <text term="volume" form="short" text-case="capitalize-first"/>
+            <number variable="volume" form="numeric"/>
+          </group>
+          <group delimiter=" ">
+            <number variable="number-of-volumes" form="numeric"/>
+            <text term="volume" form="short" plural="true"/>
+          </group>
+        </group>
+      </else-if>
+      <else-if type="chapter entry-dictionary entry-encyclopedia paper-conference" match="any">
+        <group delimiter=". ">
+          <text macro="edition"/>
+          <choose>
+            <if variable="page" match="none">
+              <group delimiter=" ">
+                <text term="volume" form="short" text-case="capitalize-first"/>
+                <number variable="volume" form="numeric"/>
+              </group>
+            </if>
+          </choose>
+        </group>
+      </else-if>
+    </choose>
+  </macro>
+  <macro name="locators-newspaper">
+    <choose>
+      <if type="article-newspaper">
+        <group delimiter=", ">
+          <group delimiter=" ">
+            <number variable="edition"/>
+            <text term="edition"/>
+          </group>
+          <group delimiter=" ">
+            <text term="section" form="short"/>
+            <text variable="section"/>
+          </group>
+        </group>
+      </if>
+    </choose>
+  </macro>
+  <macro name="event-note">
+    <text variable="event"/>
+  </macro>
+  <macro name="event">
+    <choose>
+      <if variable="title">
+        <group delimiter=" ">
+          <text term="presented at"/>
+          <text variable="event"/>
+        </group>
+      </if>
+      <else>
+        <group delimiter=" ">
+          <text term="presented at" text-case="capitalize-first"/>
+          <text variable="event"/>
+        </group>
+      </else>
+    </choose>
+  </macro>
+  <macro name="originally-published">
+    <group delimiter=", ">
+      <group delimiter=": ">
+        <text variable="original-publisher-place"/>
+        <text variable="original-publisher"/>
+      </group>
+      <date variable="original-date" form="text" date-parts="year"/>
+    </group>
+  </macro>
+  <macro name="reprint-note">
+    <!--needs localization-->
+    <choose>
+      <if variable="original-date issued" match="all">
+        <choose>
+          <!--for whatever reason in notes, when we have both original and new publishers, reprint doesn't appear-->
+          <if variable="original-publisher original-publisher-place" match="none">
+            <text value="repr."/>
+          </if>
+        </choose>
+      </if>
+    </choose>
+  </macro>
+  <macro name="reprint">
+    <!--needs localization-->
+    <choose>
+      <if variable="original-date issued" match="all">
+        <text value="reprint" text-case="capitalize-first"/>
+      </if>
+    </choose>
+  </macro>
+  <macro name="publisher">
+    <choose>
+      <if type="thesis">
+        <text variable="publisher"/>
+      </if>
+      <else-if type="speech">
+        <text variable="event-place"/>
+      </else-if>
+      <else>
+        <group delimiter=": ">
+          <text variable="publisher-place"/>
+          <text variable="publisher"/>
+        </group>
+      </else>
+    </choose>
+  </macro>
+  <macro name="issued">
+    <choose>
+      <if variable="issued">
+        <choose>
+          <if type="legal_case">
+            <group delimiter=" ">
+              <text variable="authority"/>
+              <choose>
+                <if variable="container-title" match="any">
+                  <!--Only print year for cases published in reporters-->
+                  <date variable="issued" form="numeric" date-parts="year"/>
+                </if>
+                <else>
+                  <date variable="issued" form="text"/>
+                </else>
+              </choose>
+            </group>
+          </if>
+          <else-if type="book bill chapter  legislation motion_picture paper-conference song thesis" match="any">
+            <choose>
+              <if is-uncertain-date="issued">
+                <date variable="issued" form="numeric" date-parts="year" prefix="[" suffix="?]"/>
+              </if>
+              <else>
+                <date variable="issued" form="numeric" date-parts="year"/>
+              </else>
+            </choose>
+          </else-if>
+          <else-if type="patent">
+            <group delimiter=", ">
+              <group delimiter=" ">
+                <!--Needs Localization-->
+                <text value="filed"/>
+                <date variable="submitted" form="text"/>
+              </group>
+              <group delimiter=" ">
+                <choose>
+                  <if variable="issued submitted" match="all">
+                    <text term="and"/>
+                  </if>
+                </choose>
+                <!--Needs Localization-->
+                <text value="issued"/>
+                <date variable="issued" form="text"/>
+              </group>
+            </group>
+          </else-if>
+          <else>
+            <choose>
+              <if is-uncertain-date="issued">
+                <date variable="issued" form="text" prefix="[" suffix="?]"/>
+              </if>
+              <else>
+                <date variable="issued" form="text"/>
+              </else>
+            </choose>
+          </else>
+        </choose>
+      </if>
+      <else-if variable="status">
+        <text variable="status"/>
+      </else-if>
+      <else-if variable="accessed URL" match="all"/>
+      <else>
+        <text term="no date" form="short"/>
+      </else>
+    </choose>
+  </macro>
+  <macro name="point-locators-subsequent">
+    <choose>
+      <if type="legal_case" variable="locator" match="all">
+        <choose>
+          <if locator="page">
+            <group delimiter=":">
+              <number variable="volume"/>
+              <text variable="locator"/>
+            </group>
+          </if>
+          <else>
+            <group delimiter=" ">
+              <label variable="locator" form="short"/>
+              <text variable="locator"/>
+            </group>
+          </else>
+        </choose>
+      </if>
+      <else-if variable="locator">
+        <choose>
+          <if locator="page" match="none">
+            <group delimiter=" ">
+              <choose>
+                <if type="book graphic motion_picture report song" match="any">
+                  <choose>
+                    <if variable="volume">
+                      <group delimiter=", ">
+                        <group delimiter=" ">
+                          <text term="volume" form="short"/>
+                          <number variable="volume" form="numeric"/>
+                        </group>
+                        <label variable="locator" form="short"/>
+                      </group>
+                    </if>
+                    <else>
+                      <label variable="locator" form="short"/>
+                    </else>
+                  </choose>
+                </if>
+                <else>
+                  <label variable="locator" form="short"/>
+                </else>
+              </choose>
+              <text variable="locator"/>
+            </group>
+          </if>
+          <else-if type="book graphic motion_picture report song" match="any">
+            <group delimiter=":">
+              <number variable="volume" form="numeric"/>
+              <text variable="locator"/>
+            </group>
+          </else-if>
+          <else>
+            <text variable="locator"/>
+          </else>
+        </choose>
+      </else-if>
+    </choose>
+  </macro>
+  <macro name="point-locators-join-with-colon">
+    <choose>
+      <if type="article-journal">
+        <choose>
+          <if variable="locator page" match="any">
+            <choose>
+              <if variable="volume issue" match="any">
+                <text macro="point-locators"/>
+              </if>
+            </choose>
+          </if>
+        </choose>
+      </if>
+    </choose>
+  </macro>
+  <macro name="point-locators-join-with-comma">
+    <choose>
+      <if type="article-journal" match="none">
+        <text macro="point-locators"/>
+      </if>
+      <else-if variable="volume issue" match="none">
+        <text macro="point-locators"/>
+      </else-if>
+    </choose>
+  </macro>
+  <macro name="point-locators">
+    <choose>
+      <if variable="locator" match="none">
+        <choose>
+          <if type="article-journal chapter paper-conference" match="any">
+            <text variable="page"/>
+          </if>
+        </choose>
+      </if>
+      <else-if type="article-journal">
+        <group delimiter=" ">
+          <choose>
+            <if locator="page" match="none">
+              <label variable="locator" form="short" suffix=" "/>
+            </if>
+          </choose>
+          <text variable="locator"/>
+        </group>
+      </else-if>
+      <else-if type="legal_case"/>
+      <else>
+        <group delimiter=" ">
+          <choose>
+            <if locator="page" match="none">
+              <label variable="locator" form="short"/>
+            </if>
+          </choose>
+          <text variable="locator"/>
+        </group>
+      </else>
+    </choose>
+  </macro>
+  <macro name="locators-chapter">
+    <choose>
+      <if type="chapter entry-dictionary entry-encyclopedia paper-conference" match="any">
+        <choose>
+          <if variable="author container-author" match="all"/>
+          <else>
+            <choose>
+              <if variable="page">
+                <number variable="volume" suffix=":"/>
+                <text variable="page"/>
+              </if>
+            </choose>
+          </else>
+        </choose>
+      </if>
+    </choose>
+  </macro>
+  <macro name="locators-journal-join-with-colon">
+    <choose>
+      <if type="article-journal">
+        <choose>
+          <if variable="volume issue" match="any">
+            <text variable="page"/>
+          </if>
+        </choose>
+      </if>
+    </choose>
+  </macro>
+  <macro name="locators-journal-join-with-comma">
+    <choose>
+      <if type="article-journal">
+        <choose>
+          <if variable="volume issue" match="none">
+            <text variable="page"/>
+          </if>
+        </choose>
+      </if>
+    </choose>
+  </macro>
+  <macro name="archive-note">
+    <choose>
+      <if type="thesis">
+        <group delimiter=" ">
+          <text variable="archive"/>
+          <text variable="archive_location" prefix="(" suffix=")"/>
+        </group>
+      </if>
+      <else>
+        <group delimiter=", ">
+          <text variable="archive_location"/>
+          <text variable="archive"/>
+          <text variable="archive-place"/>
+        </group>
+      </else>
+    </choose>
+  </macro>
+  <macro name="archive">
+    <choose>
+      <if type="thesis">
+        <group delimiter=" ">
+          <text variable="archive"/>
+          <text variable="archive_location" prefix="(" suffix=")"/>
+        </group>
+      </if>
+      <else>
+        <group delimiter=". ">
+          <text variable="archive_location" text-case="capitalize-first"/>
+          <text variable="archive"/>
+          <text variable="archive-place"/>
+        </group>
+      </else>
+    </choose>
+  </macro>
+  <macro name="issue-note-join-with-space">
+    <choose>
+      <if type="article-journal bill legislation legal_case manuscript thesis" variable="publisher-place publisher" match="any">
+        <!--Chicago doesn't use publisher/place for Newspapers and we want the date delimited by a comma-->
+        <choose>
+          <if type="article-newspaper" match="none">
+            <choose>
+              <if type="article-journal" match="none">
+                <text macro="issue-note"/>
+              </if>
+              <else-if variable="issue volume" match="any">
+                <text macro="issue-note"/>
+              </else-if>
+            </choose>
+          </if>
+        </choose>
+      </if>
+    </choose>
+  </macro>
+  <macro name="issue-note-join-with-comma">
+    <choose>
+      <if type="article-journal bill legislation legal_case manuscript thesis" variable="publisher-place publisher" match="none">
+        <text macro="issue-note"/>
+      </if>
+      <else-if type="article-newspaper">
+        <text macro="issue-note"/>
+      </else-if>
+      <else-if type="article-journal">
+        <choose>
+          <if variable="volume issue" match="none">
+            <text macro="issue-note"/>
+          </if>
+        </choose>
+      </else-if>
+    </choose>
+  </macro>
+  <macro name="issue-map-graphic">
+    <!--See CMoS 17th ed. 14.235 and 14.237-->
+    <choose>
+      <if type="graphic map" match="any">
+        <choose>
+          <if variable="publisher publisher-place" match="none">
+            <text macro="issued"/>
+          </if>
+        </choose>
+      </if>
+    </choose>
+  </macro>
+  <macro name="issue-note">
+    <choose>
+      <if type="bill legislation legal_case" match="any">
+        <text macro="issued" prefix="(" suffix=")"/>
+      </if>
+      <else-if type="article-journal">
+        <choose>
+          <if variable="volume issue" match="any">
+            <text macro="issued" prefix="(" suffix=")"/>
+          </if>
+          <else>
+            <text macro="issued"/>
+          </else>
+        </choose>
+      </else-if>
+      <else-if type="article-newspaper">
+        <text macro="issued"/>
+      </else-if>
+      <else-if type="manuscript thesis speech" match="any">
+        <group delimiter=", " prefix="(" suffix=")">
+          <choose>
+            <if variable="title" match="any">
+              <text variable="genre"/>
+            </if>
+          </choose>
+          <text variable="publisher"/>
+          <text macro="issued"/>
+        </group>
+      </else-if>
+      <else-if variable="publisher-place event-place publisher" match="any">
+        <group prefix="(" suffix=")" delimiter=", ">
+          <text macro="event-note"/>
+          <group delimiter="; ">
+            <text macro="originally-published"/>
+            <group delimiter=", ">
+              <text macro="reprint-note"/>
+              <text macro="publisher"/>
+            </group>
+          </group>
+          <text macro="issued"/>
+        </group>
+      </else-if>
+      <else>
+        <text macro="issued"/>
+      </else>
+    </choose>
+  </macro>
+  <macro name="issue-join-with-space">
+    <choose>
+      <if type="article-journal" match="any">
+        <choose>
+          <if variable="issue volume" match="any">
+            <text macro="issue"/>
+          </if>
+        </choose>
+      </if>
+      <else-if type="bill legislation legal_case" match="any">
+        <text macro="issue"/>
+      </else-if>
+    </choose>
+  </macro>
+  <macro name="issue-join-with-period">
+    <choose>
+      <if type="article-journal bill legislation legal_case" match="none">
+        <choose>
+          <if type="speech" variable="publisher publisher-place" match="any">
+            <text macro="issue"/>
+          </if>
+        </choose>
+      </if>
+    </choose>
+  </macro>
+  <macro name="issue-join-with-comma">
+    <choose>
+      <if type="bill legislation legal_case" match="none">
+        <choose>
+          <if type="article-journal" match="none">
+            <choose>
+              <if type="speech" variable="publisher publisher-place" match="none">
+                <text macro="issue"/>
+              </if>
+            </choose>
+          </if>
+          <else-if variable="volume issue" match="none">
+            <text macro="issue"/>
+          </else-if>
+        </choose>
+      </if>
+    </choose>
+  </macro>
+  <macro name="issue">
+    <choose>
+      <if type="bill legislation legal_case" match="any">
+        <text macro="issued" prefix="(" suffix=")"/>
+      </if>
+      <else-if type="article-journal">
+        <choose>
+          <if variable="issue volume" match="any">
+            <text macro="issued" prefix="(" suffix=")"/>
+          </if>
+          <else>
+            <text macro="issued"/>
+          </else>
+        </choose>
+      </else-if>
+      <else-if type="speech">
+        <group delimiter=", ">
+          <group delimiter=" ">
+            <choose>
+              <if variable="title" match="none"/>
+              <else>
+                <text variable="genre" text-case="capitalize-first"/>
+              </else>
+            </choose>
+            <text macro="event"/>
+          </group>
+          <text variable="event-place"/>
+          <text macro="issued"/>
+        </group>
+      </else-if>
+      <!--Chicago doesn't use publisher/place for Newspapers -->
+      <else-if type="article-newspaper">
+        <text macro="issued"/>
+      </else-if>
+      <else-if variable="publisher-place publisher" match="any">
+        <group delimiter=", ">
+          <choose>
+            <if type="thesis">
+              <text variable="genre" text-case="capitalize-first"/>
+            </if>
+          </choose>
+          <group delimiter=". ">
+            <text macro="originally-published"/>
+            <group delimiter=", ">
+              <text macro="reprint"/>
+              <text macro="publisher"/>
+            </group>
+          </group>
+          <text macro="issued"/>
+        </group>
+      </else-if>
+      <!--location for data for maps and artwork is different-->
+      <else-if type="graphic map" match="none">
+        <text macro="issued"/>
+      </else-if>
+    </choose>
+  </macro>
+  <macro name="access-note">
+    <group delimiter=", ">
+      <choose>
+        <if type="graphic report" match="any">
+          <text macro="archive-note"/>
+        </if>
+        <else-if type="article-journal bill book chapter legal_case legislation motion_picture paper-conference" match="none">
+          <text macro="archive-note"/>
+        </else-if>
+      </choose>
+      <choose>
+        <if variable="issued" match="none">
+          <group delimiter=" ">
+            <text term="accessed"/>
+            <date variable="accessed" form="text"/>
+          </group>
+        </if>
+      </choose>
+      <choose>
+        <if type="legal_case" match="none">
+          <choose>
+            <if variable="DOI">
+              <text variable="DOI" prefix="https://doi.org/"/>
+            </if>
+            <else>
+              <text variable="URL"/>
+            </else>
+          </choose>
+        </if>
+      </choose>
+    </group>
+  </macro>
+  <macro name="access">
+    <group delimiter=". ">
+      <choose>
+        <if type="graphic report" match="any">
+          <text macro="archive"/>
+        </if>
+        <else-if type="article-journal bill book chapter legal_case legislation motion_picture paper-conference" match="none">
+          <text macro="archive"/>
+        </else-if>
+      </choose>
+      <choose>
+        <if variable="issued" match="none">
+          <group delimiter=" ">
+            <text term="accessed" text-case="capitalize-first"/>
+            <date variable="accessed" form="text"/>
+          </group>
+        </if>
+      </choose>
+      <choose>
+        <if type="legal_case" match="none">
+          <choose>
+            <if variable="DOI">
+              <text variable="DOI" prefix="https://doi.org/"/>
+            </if>
+            <else>
+              <text variable="URL"/>
+            </else>
+          </choose>
+        </if>
+      </choose>
+    </group>
+  </macro>
+  <macro name="case-locator-subsequent">
+    <choose>
+      <if type="legal_case">
+        <group delimiter=" ">
+          <text variable="volume"/>
+          <text variable="container-title"/>
+        </group>
+      </if>
+    </choose>
+  </macro>
+  <macro name="case-pinpoint-subsequent">
+    <choose>
+      <if type="legal_case">
+        <group delimiter=" ">
+          <choose>
+            <if locator="page">
+              <text term="at"/>
+              <text variable="locator"/>
+            </if>
+            <else>
+              <label variable="locator"/>
+              <text variable="locator"/>
+            </else>
+          </choose>
+        </group>
+      </if>
+    </choose>
+  </macro>
+  <citation et-al-min="4" et-al-use-first="1" disambiguate-add-names="true">
+    <layout suffix="." delimiter="; ">
+      <choose>
+        <if position="ibid ibid-with-locator" match="any">
+          <group delimiter=", ">
+            <text macro="contributors-short"/>
+            <group delimiter=" ">
+              <group delimiter=", ">
+                <choose>
+                  <if variable="author editor translator" match="none">
+                    <text macro="title-short"/>
+                  </if>
+                </choose>
+                <text macro="case-locator-subsequent"/>
+              </group>
+              <text macro="case-pinpoint-subsequent"/>
+            </group>
+            <choose>
+              <if match="none" type="legal_case">
+                <text macro="point-locators-subsequent"/>
+              </if>
+            </choose>
+          </group>
+        </if>
+        <else-if position="subsequent">
+          <group delimiter=", ">
+            <text macro="contributors-short"/>
+            <group delimiter=" ">
+              <group delimiter=", ">
+                <text macro="title-short"/>
+                <!--if title & author are the same: -->
+                <text macro="date-disambiguate"/>
+                <text macro="case-locator-subsequent"/>
+              </group>
+              <text macro="case-pinpoint-subsequent"/>
+            </group>
+            <choose>
+              <if match="none" type="legal_case">
+                <text macro="point-locators-subsequent"/>
+              </if>
+            </choose>
+          </group>
+        </else-if>
+        <else>
+          <group delimiter=", ">
+            <group delimiter=": ">
+              <group delimiter=", ">
+                <group delimiter=" ">
+                  <group delimiter=", ">
+                    <group delimiter=" ">
+                      <group delimiter=", ">
+                        <group delimiter=", ">
+                          <text macro="contributors-note"/>
+                          <text macro="title-note"/>
+                          <text macro="issue-map-graphic"/>
+                        </group>
+                        <text macro="description-note"/>
+                        <text macro="secondary-contributors-note"/>
+                        <text macro="container-title-note"/>
+                        <text macro="container-contributors-note"/>
+                      </group>
+                      <text macro="locators-note-join-with-space"/>
+                    </group>
+                    <text macro="locators-note-join-with-comma"/>
+                    <text macro="collection-title"/>
+                    <text macro="issue-note-join-with-comma"/>
+                  </group>
+                  <text macro="issue-note-join-with-space"/>
+                </group>
+                <text macro="locators-newspaper"/>
+                <text macro="point-locators-join-with-comma"/>
+              </group>
+              <text macro="point-locators-join-with-colon"/>
+            </group>
+            <text macro="access-note"/>
+          </group>
+        </else>
+      </choose>
+    </layout>
+  </citation>
+  <bibliography hanging-indent="true" et-al-min="11" et-al-use-first="7" subsequent-author-substitute="&#8212;&#8212;&#8212;" entry-spacing="0">
+    <sort>
+      <key macro="contributors-sort"/>
+      <key variable="title"/>
+      <key variable="genre"/>
+      <key variable="issued"/>
+    </sort>
+    <layout suffix=".">
+      <group delimiter=". ">
+        <group delimiter=": ">
+          <group delimiter=", ">
+            <group delimiter=" ">
+              <group delimiter=". ">
+                <group delimiter=" ">
+                  <group delimiter=", ">
+                    <group delimiter=". ">
+                      <group delimiter=". ">
+                        <text macro="contributors"/>
+                        <text macro="title"/>
+                        <text macro="issue-map-graphic"/>
+                      </group>
+                      <text macro="description"/>
+                      <text macro="secondary-contributors"/>
+                      <group delimiter=", ">
+                        <text macro="container-title"/>
+                        <text macro="container-contributors"/>
+                      </group>
+                      <text macro="locators-join-with-period"/>
+                    </group>
+                    <text macro="locators-join-with-comma"/>
+                    <text macro="locators-chapter"/>
+                  </group>
+                  <text macro="locators-join-with-space"/>
+                </group>
+                <text macro="collection-title"/>
+                <text macro="issue-join-with-period"/>
+              </group>
+              <text macro="issue-join-with-space"/>
+            </group>
+            <text macro="issue-join-with-comma"/>
+            <text macro="locators-journal-join-with-comma"/>
+            <text macro="locators-newspaper"/>
+          </group>
+          <text macro="locators-journal-join-with-colon"/>
+        </group>
+        <text macro="access"/>
+      </group>
+    </layout>
+  </bibliography>
+</style>
diff --git a/test/command/chicago-note-bibliography.csl b/test/command/chicago-note-bibliography.csl
new file mode 100644
--- /dev/null
+++ b/test/command/chicago-note-bibliography.csl
@@ -0,0 +1,1005 @@
+<?xml version="1.0" encoding="utf-8"?>
+<style xmlns="http://purl.org/net/xbiblio/csl" class="note" version="1.0" demote-non-dropping-particle="sort-only">
+  <info>
+    <title>Chicago Manual of Style (note)</title>
+    <id>http://www.zotero.org/styles/chicago-note-bibliography</id>
+    <link href="http://www.zotero.org/styles/chicago-note-bibliography" rel="self"/>
+    <link href="http://www.chicagomanualofstyle.org/tools_citationguide.html" rel="documentation"/>
+    <author>
+      <name>Julian Onions</name>
+      <email>julian.onions@gmail.com</email>
+    </author>
+    <contributor>
+      <name>Simon Kornblith</name>
+      <email>simon@simonster.com</email>
+    </contributor>
+    <contributor>
+      <name>Elena Razlogova</name>
+      <email>elena.razlogova@gmail.com</email>
+    </contributor>
+    <contributor>
+      <name>Frank Bennett</name>
+      <email>biercenator@gmail.com</email>
+    </contributor>
+    <category citation-format="note"/>
+    <category field="generic-base"/>
+    <summary>Chicago format with short notes and bibliography</summary>
+    <updated>2012-10-25T21:15:26+00:00</updated>
+    <rights license="http://creativecommons.org/licenses/by-sa/3.0/">This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 License</rights>
+  </info>
+  <locale xml:lang="en">
+    <terms>
+      <term name="editortranslator" form="verb-short">
+        <single>trans. and ed.</single>
+        <multiple>trans. and ed.</multiple>
+      </term>
+      <term name="editortranslator" form="verb">
+        <single> Translated and edited by</single>
+        <multiple> Translated and edited by</multiple>
+      </term>
+      <term name="editor" form="verb-short">ed.</term>
+      <term name="translator" form="verb-short">trans.</term>
+    </terms>
+  </locale>
+  <macro name="editor-translator">
+    <group delimiter=", ">
+      <choose>
+        <if variable="author">
+          <group delimiter=" ">
+            <choose>
+              <if variable="container-author">
+                <group>
+                  <names variable="container-author">
+                    <label form="verb-short" text-case="lowercase" suffix=" "/>
+                    <name and="text" delimiter=", "/>
+                  </names>
+                </group>
+              </if>
+            </choose>
+          </group>
+          <names variable="editor translator" delimiter=", ">
+            <label form="verb-short" text-case="lowercase" suffix=" "/>
+            <name and="text" delimiter=", "/>
+          </names>
+        </if>
+      </choose>
+    </group>
+  </macro>
+  <macro name="secondary-contributors-note">
+    <choose>
+      <if type="chapter paper-conference" match="none">
+        <text macro="editor-translator"/>
+      </if>
+    </choose>
+  </macro>
+  <macro name="container-contributors-note">
+    <choose>
+      <if type="chapter paper-conference" match="any">
+        <text macro="editor-translator"/>
+      </if>
+    </choose>
+  </macro>
+  <macro name="secondary-contributors">
+    <choose>
+      <if type="chapter paper-conference" match="none">
+        <group delimiter=". ">
+          <choose>
+            <if variable="author">
+              <names variable="editor translator" delimiter=". ">
+                <label form="verb" text-case="capitalize-first" suffix=" "/>
+                <name and="text" delimiter=", "/>
+              </names>
+            </if>
+          </choose>
+        </group>
+      </if>
+    </choose>
+  </macro>
+  <macro name="container-contributors">
+    <choose>
+      <if type="chapter paper-conference" match="any">
+        <group delimiter=", ">
+          <choose>
+            <if variable="author">
+              <choose>
+                <if variable="container-author">
+                  <names variable="container-author">
+                    <label form="verb-short" text-case="lowercase" suffix=" "/>
+                    <name and="text" delimiter=", "/>
+                  </names>
+                </if>
+              </choose>
+              <!--This includes page numbers after the container author, e.g. for Introductions -->
+              <choose>
+                <if variable="container-author author" match="all">
+                  <group delimiter=". ">
+                    <text variable="page"/>
+                    <names variable="editor translator" delimiter=", ">
+                      <label form="verb" suffix=" "/>
+                      <name and="text" delimiter=", "/>
+                    </names>
+                  </group>
+                </if>
+                <else>
+                  <names variable="editor translator" delimiter=", ">
+                    <label form="verb" text-case="lowercase" suffix=" "/>
+                    <name and="text" delimiter=", "/>
+                  </names>
+                </else>
+              </choose>
+            </if>
+          </choose>
+        </group>
+      </if>
+    </choose>
+  </macro>
+  <macro name="recipient-note">
+    <names variable="recipient" delimiter=", ">
+      <label form="verb" text-case="lowercase" suffix=" "/>
+      <name and="text" delimiter=", "/>
+    </names>
+  </macro>
+  <macro name="contributors-note">
+    <group delimiter=" ">
+      <names variable="author">
+        <name and="text" sort-separator=", " delimiter=", "/>
+        <label form="short" prefix=", "/>
+        <substitute>
+          <names variable="editor"/>
+          <names variable="translator"/>
+        </substitute>
+      </names>
+      <text macro="recipient-note"/>
+    </group>
+  </macro>
+  <macro name="editor">
+    <names variable="editor">
+      <name name-as-sort-order="first" and="text" sort-separator=", " delimiter=", " delimiter-precedes-last="always"/>
+      <label form="short" prefix=", "/>
+    </names>
+  </macro>
+  <macro name="translator">
+    <names variable="translator">
+      <name name-as-sort-order="first" and="text" sort-separator=", " delimiter=", " delimiter-precedes-last="always"/>
+      <label form="verb-short" prefix=", "/>
+    </names>
+  </macro>
+  <macro name="recipient">
+    <group delimiter=" ">
+      <choose>
+        <if type="personal_communication">
+          <choose>
+            <if variable="genre">
+              <text variable="genre" text-case="capitalize-first"/>
+            </if>
+            <else>
+              <text term="letter" text-case="capitalize-first"/>
+            </else>
+          </choose>
+        </if>
+      </choose>
+      <text macro="recipient-note"/>
+    </group>
+  </macro>
+  <macro name="contributors">
+    <group delimiter=". ">
+      <names variable="author">
+        <name name-as-sort-order="first" and="text" sort-separator=", " delimiter=", " delimiter-precedes-last="always"/>
+        <substitute>
+          <text macro="editor"/>
+          <text macro="translator"/>
+        </substitute>
+      </names>
+      <text macro="recipient"/>
+    </group>
+  </macro>
+  <macro name="recipient-short">
+    <names variable="recipient">
+      <label form="verb" text-case="lowercase" suffix=" "/>
+      <name form="short" and="text" delimiter=", "/>
+    </names>
+  </macro>
+  <macro name="contributors-short">
+    <group delimiter=" ">
+      <names variable="author">
+        <name form="short" and="text" delimiter=", "/>
+        <substitute>
+          <names variable="editor"/>
+          <names variable="translator"/>
+        </substitute>
+      </names>
+      <text macro="recipient-short"/>
+    </group>
+  </macro>
+  <macro name="contributors-sort">
+    <names variable="author">
+      <name name-as-sort-order="all" and="text" sort-separator=", " delimiter=", " delimiter-precedes-last="always"/>
+      <substitute>
+        <names variable="editor"/>
+        <names variable="translator"/>
+      </substitute>
+    </names>
+  </macro>
+  <macro name="interviewer-note">
+    <names variable="interviewer" delimiter=", ">
+      <label form="verb" text-case="lowercase" suffix=" "/>
+      <name and="text" delimiter=", "/>
+    </names>
+  </macro>
+  <macro name="interviewer">
+    <names variable="interviewer" delimiter=", ">
+      <label form="verb" text-case="capitalize-first" suffix=" "/>
+      <name and="text" delimiter=", "/>
+    </names>
+  </macro>
+  <macro name="title-note">
+    <choose>
+      <if variable="title" match="none">
+        <text variable="genre"/>
+      </if>
+      <else-if type="bill book graphic  legislation motion_picture report song" match="any">
+        <text variable="title" text-case="title" font-style="italic"/>
+        <text variable="version" prefix=" , version " suffix=""/>
+        <!--This isn't localized because we don't have a version term. While not ideal, it should work for many languages and is better than not including a term.-->
+      </else-if>
+      <else-if type="legal_case">
+        <text variable="title"/>
+      </else-if>
+      <else>
+        <text variable="title" text-case="title" quotes="true"/>
+      </else>
+    </choose>
+  </macro>
+  <macro name="title">
+    <choose>
+      <if variable="title" match="none">
+        <choose>
+          <if type="personal_communication" match="none">
+            <text variable="genre" text-case="capitalize-first"/>
+          </if>
+        </choose>
+      </if>
+      <else-if type="bill book graphic legislation motion_picture report song" match="any">
+        <text variable="title" text-case="title" font-style="italic"/>
+        <text variable="version" prefix=" (version " suffix=")"/>
+      </else-if>
+      <else-if type="legal_case">
+        <text variable="title"/>
+      </else-if>
+      <else>
+        <text variable="title" text-case="title" quotes="true"/>
+      </else>
+    </choose>
+  </macro>
+  <macro name="title-short">
+    <choose>
+      <if variable="title" match="none">
+        <choose>
+          <if type="interview">
+            <text term="interview" text-case="lowercase"/>
+          </if>
+          <else-if type="manuscript speech" match="any">
+            <text variable="genre" form="short"/>
+          </else-if>
+          <else-if type="personal_communication">
+            <text macro="issued"/>
+          </else-if>
+        </choose>
+      </if>
+      <else-if type="bill book graphic legislation motion_picture report song" match="any">
+        <text variable="title" text-case="title" form="short" font-style="italic"/>
+      </else-if>
+      <else-if type="legal_case">
+        <text variable="title"/>
+      </else-if>
+      <else>
+        <text variable="title" text-case="title" form="short" quotes="true"/>
+      </else>
+    </choose>
+  </macro>
+  <macro name="description-note">
+    <group delimiter=", ">
+      <text macro="interviewer-note"/>
+      <text variable="medium"/>
+      <choose>
+        <if variable="title" match="none"/>
+        <else-if type="thesis speech" match="any"/>
+        <else>
+          <text variable="genre"/>
+        </else>
+      </choose>
+    </group>
+  </macro>
+  <macro name="description">
+    <group delimiter=", ">
+      <group delimiter=". ">
+        <text macro="interviewer"/>
+        <text variable="medium" text-case="capitalize-first"/>
+      </group>
+      <choose>
+        <if variable="title" match="none"/>
+        <else-if type="thesis speech" match="any"/>
+        <else>
+          <text variable="genre" text-case="capitalize-first"/>
+        </else>
+      </choose>
+    </group>
+  </macro>
+  <macro name="container-title-note">
+    <group delimiter=" ">
+      <choose>
+        <if type="chapter paper-conference" match="any">
+          <text term="in" text-case="lowercase"/>
+        </if>
+      </choose>
+      <choose>
+        <if type="legal_case" match="none">
+          <text variable="container-title" text-case="title" font-style="italic"/>
+        </if>
+      </choose>
+    </group>
+  </macro>
+  <macro name="container-title">
+    <group delimiter=" ">
+      <choose>
+        <if type="chapter paper-conference" match="any">
+          <text term="in" text-case="capitalize-first"/>
+        </if>
+      </choose>
+      <choose>
+        <if type="legal_case" match="none">
+          <text variable="container-title" text-case="title" font-style="italic"/>
+        </if>
+      </choose>
+    </group>
+  </macro>
+  <macro name="collection-title">
+    <group delimiter=" ">
+      <text variable="collection-title" text-case="title"/>
+      <text variable="collection-number"/>
+    </group>
+  </macro>
+  <macro name="edition-note">
+    <choose>
+      <if type="bill book chapter graphic legal_case legislation motion_picture paper-conference report song" match="any">
+        <choose>
+          <if is-numeric="edition">
+            <group delimiter=" ">
+              <number variable="edition" form="ordinal"/>
+              <text term="edition" form="short"/>
+            </group>
+          </if>
+          <else>
+            <number variable="edition" suffix="."/>
+          </else>
+        </choose>
+      </if>
+    </choose>
+  </macro>
+  <macro name="edition">
+    <choose>
+      <if type="bill book chapter graphic legal_case legislation motion_picture paper-conference report song" match="any">
+        <choose>
+          <if is-numeric="edition">
+            <group delimiter=" ">
+              <number variable="edition" form="ordinal"/>
+              <text term="edition" form="short"/>
+            </group>
+          </if>
+          <else>
+            <number variable="edition" text-case="capitalize-first" suffix="."/>
+          </else>
+        </choose>
+      </if>
+    </choose>
+  </macro>
+  <macro name="locators-note-join-with-space">
+    <choose>
+      <if type="article-journal">
+        <text macro="locators-note"/>
+      </if>
+    </choose>
+  </macro>
+  <macro name="locators-note-join-with-comma">
+    <choose>
+      <if type="article-journal" match="none">
+        <text macro="locators-note"/>
+      </if>
+    </choose>
+  </macro>
+  <macro name="locators-note">
+    <choose>
+      <if type="article-journal">
+        <group delimiter=", ">
+          <number variable="volume"/>
+          <group delimiter=" ">
+            <text term="issue" form="short"/>
+            <number variable="issue"/>
+          </group>
+        </group>
+      </if>
+      <else-if type="legal_case">
+        <group delimiter=", ">
+          <group delimiter=" ">
+            <number variable="volume"/>
+            <text variable="container-title"/>
+            <text variable="page"/>
+          </group>
+          <text variable="locator"/>
+        </group>
+      </else-if>
+      <else-if type="bill book chapter graphic legal_case legislation motion_picture paper-conference report song" match="any">
+        <group delimiter=", ">
+          <group delimiter=" ">
+            <text term="volume" form="short"/>
+            <number variable="volume" form="numeric"/>
+          </group>
+          <choose>
+            <if variable="locator" match="none">
+              <group delimiter=" ">
+                <number variable="number-of-volumes" form="numeric"/>
+                <text term="volume" form="short" plural="true"/>
+              </group>
+            </if>
+          </choose>
+          <text macro="edition-note"/>
+        </group>
+      </else-if>
+    </choose>
+  </macro>
+  <macro name="locators-join-with-space">
+    <choose>
+      <if type="article-journal">
+        <text macro="locators"/>
+      </if>
+    </choose>
+  </macro>
+  <macro name="locators-join-with-comma">
+    <choose>
+      <if type="legal_case">
+        <text macro="locators"/>
+      </if>
+    </choose>
+  </macro>
+  <macro name="locators-join-with-period">
+    <choose>
+      <if type="legal_case article-journal" match="none">
+        <text macro="locators"/>
+      </if>
+    </choose>
+  </macro>
+  <macro name="locators">
+    <choose>
+      <if type="article-journal">
+        <group delimiter=", ">
+          <number variable="volume"/>
+          <group delimiter=" ">
+            <text term="issue" form="short"/>
+            <number variable="issue"/>
+          </group>
+        </group>
+      </if>
+      <else-if type="legal_case">
+        <group delimiter=" ">
+          <number variable="volume"/>
+          <text variable="container-title"/>
+          <text variable="page"/>
+        </group>
+      </else-if>
+      <else-if type="bill book graphic legal_case legislation motion_picture report song" match="any">
+        <group delimiter=". ">
+          <group delimiter=" ">
+            <text term="volume" form="short" text-case="capitalize-first"/>
+            <number variable="volume" form="numeric"/>
+          </group>
+          <group delimiter=" ">
+            <number variable="number-of-volumes" form="numeric"/>
+            <text term="volume" form="short" plural="true"/>
+          </group>
+          <text macro="edition"/>
+        </group>
+      </else-if>
+      <else-if type="chapter paper-conference" match="any">
+        <group delimiter=". ">
+          <choose>
+            <if variable="page" match="none">
+              <group delimiter=" ">
+                <text term="volume" form="short" text-case="capitalize-first"/>
+                <number variable="volume" form="numeric"/>
+              </group>
+            </if>
+          </choose>
+          <text macro="edition"/>
+        </group>
+      </else-if>
+    </choose>
+  </macro>
+  <macro name="locators-newspaper">
+    <choose>
+      <if type="article-newspaper">
+        <group delimiter=", ">
+          <group delimiter=" ">
+            <number variable="edition"/>
+            <text term="edition"/>
+          </group>
+          <group delimiter=" ">
+            <text term="section" form="short"/>
+            <text variable="section"/>
+          </group>
+        </group>
+      </if>
+    </choose>
+  </macro>
+  <macro name="event">
+    <group delimiter=" ">
+      <text term="presented at"/>
+      <text variable="event"/>
+    </group>
+  </macro>
+  <macro name="publisher">
+    <choose>
+      <if type="thesis">
+        <text variable="publisher"/>
+      </if>
+      <else>
+        <group delimiter=": ">
+          <text variable="publisher-place"/>
+          <text variable="publisher"/>
+        </group>
+      </else>
+    </choose>
+  </macro>
+  <macro name="issued">
+    <choose>
+      <if variable="issued">
+        <choose>
+          <if type="graphic report" match="any">
+            <date variable="issued">
+              <date-part name="month" suffix=" "/>
+              <date-part name="day" suffix=", "/>
+              <date-part name="year"/>
+            </date>
+          </if>
+          <else-if type="legal_case">
+            <group delimiter=" ">
+              <text variable="authority"/>
+              <date variable="issued">
+                <date-part name="year"/>
+              </date>
+            </group>
+          </else-if>
+          <else-if type="bill book chapter graphic legal_case legislation motion_picture paper-conference report song thesis" match="any">
+            <date variable="issued">
+              <date-part name="year"/>
+            </date>
+          </else-if>
+          <else>
+            <date variable="issued">
+              <date-part name="month" suffix=" "/>
+              <date-part name="day" suffix=", "/>
+              <date-part name="year"/>
+            </date>
+          </else>
+        </choose>
+      </if>
+      <else-if variable="accessed URL" match="all">
+      </else-if>
+      <else>
+        <text term="no date" form="short"/>
+      </else>
+    </choose>
+  </macro>
+  <macro name="point-locators-subsequent">
+    <choose>
+      <if variable="locator">
+        <choose>
+          <if locator="page" match="none">
+            <group delimiter=" ">
+              <choose>
+                <if type="bill book graphic legal_case legislation motion_picture report song" match="any">
+                  <choose>
+                    <if variable="volume">
+                      <group delimiter=", ">
+                        <group delimiter=" ">
+                          <text term="volume" form="short" text-case="lowercase"/>
+                          <number variable="volume" form="numeric"/>
+                        </group>
+                        <label variable="locator" form="short"/>
+                      </group>
+                    </if>
+                    <else>
+                      <label variable="locator" form="short"/>
+                    </else>
+                  </choose>
+                </if>
+                <else>
+                  <label variable="locator" form="short"/>
+                </else>
+              </choose>
+              <text variable="locator"/>
+            </group>
+          </if>
+          <else-if type="bill book graphic legal_case legislation motion_picture report song" match="any">
+            <group delimiter=":">
+              <number variable="volume" form="numeric"/>
+              <text variable="locator"/>
+            </group>
+          </else-if>
+          <else>
+            <text variable="locator"/>
+          </else>
+        </choose>
+      </if>
+    </choose>
+  </macro>
+  <macro name="point-locators-join-with-colon">
+    <choose>
+      <if type="article-journal">
+        <choose>
+          <if variable="locator page" match="any">
+            <text macro="point-locators"/>
+          </if>
+        </choose>
+      </if>
+    </choose>
+  </macro>
+  <macro name="point-locators-join-with-comma">
+    <choose>
+      <if type="article-journal" match="none">
+        <text macro="point-locators"/>
+      </if>
+    </choose>
+  </macro>
+  <macro name="point-locators">
+    <choose>
+      <if variable="locator" match="none">
+        <choose>
+          <if type="article-journal chapter paper-conference" match="any">
+            <text variable="page"/>
+          </if>
+        </choose>
+      </if>
+      <else-if type="article-journal">
+        <group delimiter=" ">
+          <choose>
+            <if locator="page" match="none">
+              <label variable="locator" form="short" suffix=" "/>
+            </if>
+          </choose>
+          <text variable="locator"/>
+        </group>
+      </else-if>
+      <else-if type="legal_case"/>
+      <else>
+        <group delimiter=" ">
+          <choose>
+            <if locator="page" match="none">
+              <label variable="locator" form="short"/>
+            </if>
+          </choose>
+          <text variable="locator"/>
+        </group>
+      </else>
+    </choose>
+  </macro>
+  <macro name="locators-chapter">
+    <choose>
+      <if type="chapter paper-conference" match="any">
+        <choose>
+          <if variable="page">
+            <number variable="volume" suffix=":"/>
+            <text variable="page"/>
+          </if>
+        </choose>
+      </if>
+    </choose>
+  </macro>
+  <macro name="locators-journal">
+    <choose>
+      <if type="article-journal">
+        <text variable="page"/>
+      </if>
+    </choose>
+  </macro>
+  <macro name="archive-note">
+    <choose>
+      <if type="thesis">
+        <group delimiter=" ">
+          <text variable="archive"/>
+          <text variable="archive_location" prefix="(" suffix=")"/>
+        </group>
+      </if>
+      <else>
+        <group delimiter=", ">
+          <text variable="archive_location"/>
+          <text variable="archive"/>
+          <text variable="archive-place"/>
+        </group>
+      </else>
+    </choose>
+  </macro>
+  <macro name="archive">
+    <choose>
+      <if type="thesis">
+        <group delimiter=" ">
+          <text variable="archive"/>
+          <text variable="archive_location" prefix="(" suffix=")"/>
+        </group>
+      </if>
+      <else>
+        <group delimiter=". ">
+          <text variable="archive_location" text-case="capitalize-first"/>
+          <text variable="archive"/>
+          <text variable="archive-place"/>
+        </group>
+      </else>
+    </choose>
+  </macro>
+  <macro name="issue-note-join-with-space">
+    <choose>
+      <if type="article-journal legal_case" variable="publisher-place publisher" match="any">
+        <text macro="issue-note"/>
+      </if>
+    </choose>
+  </macro>
+  <macro name="issue-note-join-with-comma">
+    <choose>
+      <if type="article-journal legal_case" variable="publisher-place publisher" match="none">
+        <text macro="issue-note"/>
+      </if>
+    </choose>
+  </macro>
+  <macro name="issue-note">
+    <choose>
+      <if type="article-journal legal_case" match="any">
+        <text macro="issued" prefix="(" suffix=")"/>
+      </if>
+      <else-if variable="publisher-place publisher" match="any">
+        <group prefix="(" suffix=")" delimiter=", ">
+          <group delimiter=" ">
+            <choose>
+              <if variable="title" match="none"/>
+              <else-if type="thesis speech" match="any">
+                <text variable="genre"/>
+              </else-if>
+            </choose>
+            <text macro="event"/>
+          </group>
+          <text macro="publisher"/>
+          <text macro="issued"/>
+        </group>
+      </else-if>
+      <else>
+        <text macro="issued"/>
+      </else>
+    </choose>
+  </macro>
+  <macro name="issue-join-with-space">
+    <choose>
+      <if type="article-journal legal_case">
+        <text macro="issue"/>
+      </if>
+    </choose>
+  </macro>
+  <macro name="issue-join-with-period">
+    <choose>
+      <if type="article-journal legal_case" match="none">
+        <choose>
+          <if type="speech" variable="publisher publisher-place" match="any">
+            <text macro="issue"/>
+          </if>
+        </choose>
+      </if>
+    </choose>
+  </macro>
+  <macro name="issue-join-with-comma">
+    <choose>
+      <if type="article-journal legal_case" match="none">
+        <choose>
+          <if type="speech" variable="publisher publisher-place" match="none">
+            <text macro="issue"/>
+          </if>
+        </choose>
+      </if>
+    </choose>
+  </macro>
+  <macro name="issue">
+    <choose>
+      <if type="article-journal legal_case" match="any">
+        <text macro="issued" prefix=" (" suffix=")"/>
+      </if>
+      <else-if type="speech">
+        <group delimiter=", ">
+          <group delimiter=" ">
+            <choose>
+              <if variable="title" match="none"/>
+              <else>
+                <text variable="genre" text-case="capitalize-first"/>
+              </else>
+            </choose>
+            <text macro="event"/>
+          </group>
+          <text variable="event-place"/>
+          <text macro="issued"/>
+        </group>
+      </else-if>
+      <else-if variable="publisher-place publisher" match="any">
+        <group delimiter=", ">
+          <choose>
+            <if type="thesis">
+              <text variable="genre" text-case="capitalize-first"/>
+            </if>
+          </choose>
+          <text macro="publisher"/>
+          <text macro="issued"/>
+        </group>
+      </else-if>
+      <else>
+        <text macro="issued"/>
+      </else>
+    </choose>
+  </macro>
+  <macro name="access-note">
+    <group delimiter=", ">
+      <choose>
+        <if type="graphic report" match="any">
+          <text macro="archive-note"/>
+        </if>
+        <else-if type="article-journal article-magazine article-newspaper bill book chapter graphic legal_case legislation motion_picture paper-conference report song" match="none">
+          <text macro="archive-note"/>
+        </else-if>
+      </choose>
+      <choose>
+        <if variable="issued" match="none">
+          <group delimiter=" ">
+            <text term="accessed"/>
+            <date variable="accessed">
+              <date-part name="month" suffix=" "/>
+              <date-part name="day" suffix=", "/>
+              <date-part name="year"/>
+            </date>
+          </group>
+        </if>
+      </choose>
+      <choose>
+        <if type="legal_case" match="none">
+          <choose>
+            <if variable="DOI">
+              <text variable="DOI" prefix="doi:"/>
+            </if>
+            <else>
+              <text variable="URL"/>
+            </else>
+          </choose>
+        </if>
+      </choose>
+    </group>
+  </macro>
+  <macro name="access">
+    <group delimiter=". ">
+      <choose>
+        <if type="graphic report" match="any">
+          <text macro="archive"/>
+        </if>
+        <else-if type="article-journal article-magazine article-newspaper bill book chapter graphic legal_case legislation motion_picture paper-conference report song" match="none">
+          <text macro="archive"/>
+        </else-if>
+      </choose>
+      <choose>
+        <if variable="issued" match="none">
+          <group delimiter=" ">
+            <text term="accessed" text-case="capitalize-first"/>
+            <date variable="accessed">
+              <date-part name="month" suffix=" "/>
+              <date-part name="day" suffix=", "/>
+              <date-part name="year"/>
+            </date>
+          </group>
+        </if>
+      </choose>
+      <choose>
+        <if type="legal_case" match="none">
+          <choose>
+            <if variable="DOI">
+              <text variable="DOI" prefix="doi:"/>
+            </if>
+            <else>
+              <text variable="URL"/>
+            </else>
+          </choose>
+        </if>
+      </choose>
+    </group>
+  </macro>
+  <macro name="case-locator-subsequent">
+    <choose>
+      <if type="legal_case">
+        <text macro="locators-note"/>
+      </if>
+    </choose>
+  </macro>
+  <macro name="case-issue-subsequent">
+    <choose>
+      <if type="legal_case">
+        <text macro="issue"/>
+      </if>
+    </choose>
+  </macro>
+  <citation et-al-min="4" et-al-use-first="1" disambiguate-add-names="true">
+    <layout suffix="." delimiter="; ">
+      <choose>
+        <if position="ibid-with-locator">
+          <group delimiter=", ">
+            <text term="ibid"/>
+            <text macro="point-locators-subsequent"/>
+          </group>
+        </if>
+        <else-if position="ibid">
+          <text term="ibid"/>
+        </else-if>
+        <else>
+          <group delimiter=", ">
+            <text macro="contributors-short"/>
+            <group delimiter=" ">
+              <group delimiter=", ">
+                <text macro="title-short"/>
+                <text macro="case-locator-subsequent"/>
+              </group>
+              <text macro="case-issue-subsequent"/>
+            </group>
+            <text macro="point-locators-subsequent"/>
+          </group>
+        </else>
+      </choose>
+    </layout>
+  </citation>
+  <bibliography hanging-indent="true" et-al-min="11" et-al-use-first="7" subsequent-author-substitute="&#8212;&#8212;&#8212;" entry-spacing="0">
+    <sort>
+      <key macro="contributors-sort"/>
+      <key variable="title"/>
+      <key variable="genre"/>
+      <key variable="issued"/>
+    </sort>
+    <layout suffix=".">
+      <group delimiter=". ">
+        <group delimiter=": ">
+          <group delimiter=", ">
+            <group delimiter=" ">
+              <group delimiter=". ">
+                <group delimiter=" ">
+                  <group delimiter=", ">
+                    <group delimiter=". ">
+                      <group delimiter=" ">
+                        <group delimiter=". ">
+                          <text macro="contributors"/>
+                          <text macro="title"/>
+                        </group>
+                        <text macro="description"/>
+                      </group>
+                      <text macro="secondary-contributors"/>
+                      <group delimiter=", ">
+                        <text macro="container-title"/>
+                        <text macro="container-contributors"/>
+                        <text macro="locators-chapter"/>
+                      </group>
+                      <text macro="locators-join-with-period"/>
+                    </group>
+                    <text macro="locators-join-with-comma"/>
+                  </group>
+                  <text macro="locators-join-with-space"/>
+                </group>
+                <text macro="collection-title"/>
+                <text macro="issue-join-with-period"/>
+              </group>
+              <text macro="issue-join-with-space"/>
+            </group>
+            <text macro="issue-join-with-comma"/>
+            <text macro="locators-newspaper"/>
+          </group>
+          <text macro="locators-journal"/>
+        </group>
+        <text macro="access"/>
+      </group>
+    </layout>
+  </bibliography>
+</style>
diff --git a/test/command/chinese-gb7714-2005-numeric.csl b/test/command/chinese-gb7714-2005-numeric.csl
new file mode 100644
--- /dev/null
+++ b/test/command/chinese-gb7714-2005-numeric.csl
@@ -0,0 +1,213 @@
+<?xml version="1.0" encoding="utf-8"?>
+<style xmlns="http://purl.org/net/xbiblio/csl" class="in-text" version="1.0" demote-non-dropping-particle="sort-only" default-locale="zh-CN">
+  <info>
+    <title>Chinese Std GB/T 7714-2005 (numeric, Chinese)</title>
+    <id>http://www.zotero.org/styles/chinese-gb7714-2005-numeric</id>
+    <link href="http://www.zotero.org/styles/chinese-gb7714-2005-numeric" rel="self"/>
+    <link href="http://gradschool.ustc.edu.cn/ylb/material/xw/wdxz/19.pdf" rel="documentation"/>
+    <author>
+      <name>heromyth</name>
+      <email>zxpmyth@yahoo.com.cn</email>
+    </author>
+    <category citation-format="numeric"/>
+    <category field="engineering"/>
+    <category field="generic-base"/>
+    <category field="science"/>
+    <summary>This style just partly implemented what the Chinese GB/T 7714-2005 requires.</summary>
+    <updated>2012-10-11T09:38:41+00:00</updated>
+    <rights license="http://creativecommons.org/licenses/by-sa/3.0/">This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 License</rights>
+  </info>
+  <macro name="author">
+    <names variable="author">
+      <name initialize-with=" " name-as-sort-order="all" sort-separator=" " delimiter=", " delimiter-precedes-last="always">
+        <name-part name="family" text-case="uppercase"/>
+      </name>
+    </names>
+  </macro>
+  <macro name="recipient">
+    <names variable="recipient">
+      <name name-as-sort-order="all" sort-separator=" " delimiter=", " delimiter-precedes-last="always"/>
+      <label form="short" prefix=", " text-case="lowercase"/>
+    </names>
+  </macro>
+  <macro name="interviewer">
+    <names variable="interviewer">
+      <name name-as-sort-order="all" sort-separator=" " delimiter=", " delimiter-precedes-last="always"/>
+      <label form="short" prefix=", " text-case="lowercase"/>
+    </names>
+  </macro>
+  <macro name="composer">
+    <names variable="composer">
+      <name name-as-sort-order="all" sort-separator=" " delimiter=", " delimiter-precedes-last="always"/>
+      <label form="short" prefix=", " text-case="lowercase"/>
+    </names>
+  </macro>
+  <macro name="original-author">
+    <names variable="original-author">
+      <name name-as-sort-order="all" sort-separator=" " delimiter=", " delimiter-precedes-last="always"/>
+      <label form="short" prefix=", " text-case="lowercase"/>
+    </names>
+  </macro>
+  <macro name="title">
+    <text variable="title"/>
+  </macro>
+  <macro name="titleField">
+    <choose>
+      <if type="report">
+        <text macro="title" suffix="[R]. "/>
+      </if>
+      <else-if type="thesis">
+        <text macro="title" suffix="[D]. "/>
+      </else-if>
+      <else-if type="bill legislation" match="any">
+        <text variable="number" suffix=", "/>
+        <text macro="title" suffix="[S]"/>
+      </else-if>
+      <else-if type="bill book graphic legal_case legislation motion_picture report song" match="any">
+        <text macro="title" suffix="[M]. "/>
+      </else-if>
+      <else-if type="paper-conference">
+        <text macro="title" suffix="[C]//"/>
+      </else-if>
+      <else-if type="chapter paper-conference" match="any">
+        <text macro="title" suffix="[G]//"/>
+      </else-if>
+      <else-if type="webpage">
+        <text macro="title" suffix="[EB/OL]. "/>
+      </else-if>
+      <else-if type="patent">
+        <text macro="title"/>
+        <text variable="number" prefix=": 中国, " suffix="[P].  "/>
+      </else-if>
+      <else>
+        <text macro="title" suffix="[J]. "/>
+      </else>
+    </choose>
+  </macro>
+  <macro name="secondaryAuthor">
+    <names variable="editor">
+      <name initialize-with=" " name-as-sort-order="all" sort-separator=" " delimiter=", " delimiter-precedes-last="always">
+        <name-part name="family" text-case="uppercase"/>
+      </name>
+    </names>
+    <names variable="translator">
+      <name name-as-sort-order="all" sort-separator=" " delimiter=", " delimiter-precedes-last="always" suffix=", 译"/>
+    </names>
+  </macro>
+  <macro name="publisher">
+    <choose>
+      <if type="chapter paper-conference" match="any">
+        <text variable="container-title" suffix=". "/>
+      </if>
+      <else-if type="report">
+        <text variable="collection-title" suffix=", "/>
+        <text variable="number" suffix=", "/>
+      </else-if>
+      <else-if type="bill legislation" match="any">
+        <text variable="container-title" prefix=". "/>
+      </else-if>
+      <else>
+        <text variable="container-title" suffix=", "/>
+      </else>
+    </choose>
+    <!--
+
+<text variable="event" suffix="event "/>
+<text variable="event-place" suffix="event-place "/>
+<text variable="original-title" suffix="original-title"/>
+
+ -->
+    <text variable="publisher-place" suffix=": "/>
+    <group delimiter=", ">
+      <text variable="publisher"/>
+      <choose>
+        <if type="webpage" variable="container-title" match="all">
+          <date variable="issued" suffix=". ">
+            <date-part name="year"/>
+            <date-part name="month" form="numeric-leading-zeros" prefix="-"/>
+            <date-part name="day" form="numeric-leading-zeros" prefix="-"/>
+          </date>
+        </if>
+        <else-if type="webpage"/>
+        <else-if type="patent">
+          <date variable="issued">
+            <date-part name="year"/>
+            <date-part name="month" form="numeric-leading-zeros" prefix="-"/>
+            <date-part name="day" form="numeric-leading-zeros" prefix="-"/>
+          </date>
+        </else-if>
+        <else-if variable="publisher">
+          <date variable="issued">
+            <date-part name="year"/>
+          </date>
+        </else-if>
+        <else-if type="bill legislation" match="any"/>
+        <else>
+          <date variable="issued">
+            <date-part name="year"/>
+          </date>
+        </else>
+      </choose>
+    </group>
+    <text variable="volume" prefix=", "/>
+    <text variable="issue" prefix="(" suffix=")"/>
+  </macro>
+  <macro name="pageField">
+    <text variable="page"/>
+  </macro>
+  <macro name="referenceDate">
+    <choose>
+      <if type="webpage">
+        <date variable="issued" prefix="(" suffix=")">
+          <date-part name="year"/>
+          <date-part name="month" form="numeric-leading-zeros" prefix="-"/>
+          <date-part name="day" form="numeric-leading-zeros" prefix="-"/>
+        </date>
+        <date variable="accessed" prefix="[" suffix="]">
+          <date-part name="year"/>
+          <date-part name="month" form="numeric-leading-zeros" prefix="-"/>
+          <date-part name="day" form="numeric-leading-zeros" prefix="-"/>
+        </date>
+      </if>
+    </choose>
+  </macro>
+  <macro name="access">
+    <choose>
+      <if variable="DOI">
+        <text variable="DOI" prefix="doi:"/>
+      </if>
+      <else-if variable="URL">
+        <text variable="URL"/>
+      </else-if>
+    </choose>
+  </macro>
+  <citation collapse="citation-number">
+    <sort>
+      <key variable="citation-number" sort="ascending"/>
+    </sort>
+    <layout vertical-align="sup" prefix="[" suffix="]" delimiter=",">
+      <text variable="citation-number"/>
+    </layout>
+  </citation>
+  <bibliography et-al-min="4" et-al-use-first="3" second-field-align="flush" entry-spacing="0">
+    <layout suffix=".">
+      <text variable="citation-number" prefix="[" suffix="]"/>
+      <text macro="author" suffix=". "/>
+      <text macro="titleField"/>
+      <text macro="secondaryAuthor" suffix=". "/>
+      <text variable="edition" prefix="第" suffix="版. "/>
+      <text macro="publisher"/>
+      <text macro="pageField" prefix=": "/>
+      <text macro="referenceDate"/>
+      <choose>
+        <if type="webpage" match="any">
+          <text macro="access" prefix=". "/>
+        </if>
+      </choose>
+      <text macro="recipient"/>
+      <text macro="interviewer"/>
+      <text macro="composer"/>
+      <text macro="original-author"/>
+    </layout>
+  </bibliography>
+</style>
diff --git a/test/command/cite-in-inline-note.md b/test/command/cite-in-inline-note.md
new file mode 100644
--- /dev/null
+++ b/test/command/cite-in-inline-note.md
@@ -0,0 +1,26 @@
+```
+% pandoc -t native
+foo^[bar [@doe]]
+^D
+[ Para
+    [ Str "foo"
+    , Note
+        [ Para
+            [ Str "bar"
+            , Space
+            , Cite
+                [ Citation
+                    { citationId = "doe"
+                    , citationPrefix = []
+                    , citationSuffix = []
+                    , citationMode = NormalCitation
+                    , citationNoteNum = 1
+                    , citationHash = 0
+                    }
+                ]
+                [ Str "[@doe]" ]
+            ]
+        ]
+    ]
+]
+```
diff --git a/test/command/citeproc-17.md b/test/command/citeproc-17.md
new file mode 100644
--- /dev/null
+++ b/test/command/citeproc-17.md
@@ -0,0 +1,17 @@
+```
+% pandoc -t csljson
+---
+references:
+- id: foo
+  type: book
+  title: "Hi & Low"
+...
+^D
+[
+  {
+    "id": "foo",
+    "title": "Hi & Low",
+    "type": "book"
+  }
+]
+```
diff --git a/test/command/citeproc-20.md b/test/command/citeproc-20.md
new file mode 100644
--- /dev/null
+++ b/test/command/citeproc-20.md
@@ -0,0 +1,25 @@
+```
+% pandoc --citeproc -t plain
+Lorem ipsum dolor sit amet^[Consectetur adipisicing elit: «sed do eiusmod tempor incididunt» [@doe_1989, 15].].
+
+---
+csl: command/chicago-fullnote-bibliography.csl
+suppress-bibliography: true
+references:
+- id: doe_1989
+  author:
+    - family: Doe
+      given: John
+  issued:
+    - year: 1989
+  publisher: ABC
+  publisher-place: New York
+  title: Tempor
+  type: book
+...
+^D
+Lorem ipsum dolor sit amet[1].
+
+[1] Consectetur adipisicing elit: «sed do eiusmod tempor incididunt»
+(John Doe, Tempor (New York: ABC, 1989), 15).
+```
diff --git a/test/command/citeproc-7a.md b/test/command/citeproc-7a.md
new file mode 100644
--- /dev/null
+++ b/test/command/citeproc-7a.md
@@ -0,0 +1,42 @@
+```
+% pandoc --citeproc -t markdown-citations
+---
+csl: command/chicago-fullnote-bibliography.csl
+references:
+  - id: test
+    title: Test
+    author:
+      family: Doe
+      given: John
+---
+
+Test [@test, 12].
+
+Test [@test, 12].
+
+Test.^[asdfasdf]
+
+Test [@test, 12].
+^D
+Test.[^1]
+
+Test.[^2]
+
+Test.[^3]
+
+Test.[^4]
+
+:::: {#refs .references .csl-bib-body .hanging-indent entry-spacing="0"}
+::: {#ref-test .csl-entry}
+Doe, John. "Test," n.d.
+:::
+::::
+
+[^1]: John Doe, "Test," n.d., 12.
+
+[^2]: Doe, 12.
+
+[^3]: asdfasdf
+
+[^4]: Doe, "Test," 12.
+```
diff --git a/test/command/citeproc-7b.md b/test/command/citeproc-7b.md
new file mode 100644
--- /dev/null
+++ b/test/command/citeproc-7b.md
@@ -0,0 +1,36 @@
+```
+% pandoc --citeproc -t markdown-citations
+---
+csl: command/bioethics.csl
+references:
+  - id: test
+    title: Test
+    author:
+      family: Doe
+      given: John
+---
+
+Irrelevant.^[note]
+
+Test [@test, 12].
+
+Test.^[asdfasdf]
+
+Test [@test, 12].
+^D
+Irrelevant.[^1]
+
+Test.[^2]
+
+Test.[^3]
+
+Test.[^4]
+
+[^1]: note
+
+[^2]: J. Doe. ***Test***: 12.
+
+[^3]: asdfasdf
+
+[^4]: Doe (cited n. 2) : 12.
+```
diff --git a/test/command/citeproc-87.md b/test/command/citeproc-87.md
new file mode 100644
--- /dev/null
+++ b/test/command/citeproc-87.md
@@ -0,0 +1,59 @@
+```
+% pandoc --citeproc -Mlang=it-IT -t markdown-citations
+Foo [@a 50: «Disse: "bar"»]. «Disse: "baz"»
+
+---
+suppress-bibliography: true
+references:
+- id: a
+  author:
+    - literal: Aristotele
+  title: Metafisica
+  type: book
+...
+^D
+Foo (Aristotele, s.d., 50: «Disse: "bar"»). «Disse: "baz"»
+```
+
+The Quoted is passed to citeproc as a Span ("",["csl-quoted"],[])
+so that flipflopping and localization occur.
+```
+% pandoc -C -t plain -Mlang=en --csl command/le-tapuscrit-note.csl
+---
+references:
+- id: a
+  author:
+    - literal: Aristotele
+  title: Metafisica et "Physica"
+  type: article-journal
+...
+
+Foo [@a 50].
+^D
+Foo.[1]
+
+ARISTOTELE, “Metafisica et ‘Physica’.”
+
+[1] Aristotele, “Metafisica et ‘Physica’,” p. 50.
+```
+
+```
+% pandoc -C -t plain -Mlang=it --csl command/le-tapuscrit-note.csl
+---
+references:
+- id: a
+  author:
+    - literal: Aristotele
+  title: Metafisica et "Physica"
+  type: article-journal
+...
+
+Foo [@a 50].
+^D
+Foo.[1]
+
+ARISTOTELE, «Metafisica et “Physica”».
+
+[1] Aristotele, «Metafisica et “Physica”», p. 50.
+```
+
diff --git a/test/command/citeproc-author-in-text-suffix.md b/test/command/citeproc-author-in-text-suffix.md
new file mode 100644
--- /dev/null
+++ b/test/command/citeproc-author-in-text-suffix.md
@@ -0,0 +1,34 @@
+```
+% pandoc -t native
+@a [p. 33; @b]
+^D
+[ Para
+    [ Cite
+        [ Citation
+            { citationId = "a"
+            , citationPrefix = []
+            , citationSuffix = [ Str "p.\160\&33" ]
+            , citationMode = AuthorInText
+            , citationNoteNum = 1
+            , citationHash = 0
+            }
+        , Citation
+            { citationId = "b"
+            , citationPrefix = []
+            , citationSuffix = []
+            , citationMode = NormalCitation
+            , citationNoteNum = 1
+            , citationHash = 0
+            }
+        ]
+        [ Str "@a"
+        , Space
+        , Str "[p."
+        , Space
+        , Str "33;"
+        , Space
+        , Str "@b]"
+        ]
+    ]
+]
+```
diff --git a/test/command/csv.md b/test/command/csv.md
new file mode 100644
--- /dev/null
+++ b/test/command/csv.md
@@ -0,0 +1,102 @@
+```
+% pandoc -f csv -t native
+Fruit,Price,Quantity
+Apple,25 cents,33
+"""Navel"" Orange","35 cents",22
+,,45
+^D
+[ Table
+    ( "" , [] , [] )
+    (Caption Nothing [])
+    [ ( AlignDefault , ColWidthDefault )
+    , ( AlignDefault , ColWidthDefault )
+    , ( AlignDefault , ColWidthDefault )
+    ]
+    (TableHead
+       ( "" , [] , [] )
+       [ Row
+           ( "" , [] , [] )
+           [ Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "Fruit" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "Price" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "Quantity" ] ]
+           ]
+       ])
+    [ TableBody
+        ( "" , [] , [] )
+        (RowHeadColumns 0)
+        []
+        [ Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "Apple" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "25" , Space , Str "cents" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "33" ] ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "\"Navel\"" , Space , Str "Orange" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "35" , Space , Str "cents" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "22" ] ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] ) AlignDefault (RowSpan 1) (ColSpan 1) []
+            , Cell
+                ( "" , [] , [] ) AlignDefault (RowSpan 1) (ColSpan 1) []
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "45" ] ]
+            ]
+        ]
+    ]
+    (TableFoot ( "" , [] , [] ) [])
+]
+```
diff --git a/test/command/defaults-inheritance-1.md b/test/command/defaults-inheritance-1.md
new file mode 100644
--- /dev/null
+++ b/test/command/defaults-inheritance-1.md
@@ -0,0 +1,6 @@
+```
+% pandoc -d command/defaults3
+# Header
+^D
+# Header
+```
diff --git a/test/command/defaults-inheritance-2.md b/test/command/defaults-inheritance-2.md
new file mode 100644
--- /dev/null
+++ b/test/command/defaults-inheritance-2.md
@@ -0,0 +1,6 @@
+```
+% pandoc -d command/defaults6 2>&1
+^D
+Error: Circular defaults file reference in 'command/defaults7.yaml'
+=> 63
+```
diff --git a/test/command/defaults-inheritance-3.md b/test/command/defaults-inheritance-3.md
new file mode 100644
--- /dev/null
+++ b/test/command/defaults-inheritance-3.md
@@ -0,0 +1,6 @@
+```
+% pandoc -d command/defaults8
+<h1>Header</h1>
+^D
+# Header
+```
diff --git a/test/command/defaults1.yaml b/test/command/defaults1.yaml
new file mode 100644
--- /dev/null
+++ b/test/command/defaults1.yaml
@@ -0,0 +1,1 @@
+include-in-header: command/A.txt
diff --git a/test/command/defaults2.yaml b/test/command/defaults2.yaml
new file mode 100644
--- /dev/null
+++ b/test/command/defaults2.yaml
@@ -0,0 +1,4 @@
+include-in-header:
+- command/B.txt
+- command/C.txt
+
diff --git a/test/command/defaults3.yaml b/test/command/defaults3.yaml
new file mode 100644
--- /dev/null
+++ b/test/command/defaults3.yaml
@@ -0,0 +1,4 @@
+defaults:
+  - command/defaults4
+  - command/defaults5
+to: markdown
diff --git a/test/command/defaults4.yaml b/test/command/defaults4.yaml
new file mode 100644
--- /dev/null
+++ b/test/command/defaults4.yaml
@@ -0,0 +1,3 @@
+from: html
+defaults:
+  - command/defaults5
diff --git a/test/command/defaults5.yaml b/test/command/defaults5.yaml
new file mode 100644
--- /dev/null
+++ b/test/command/defaults5.yaml
@@ -0,0 +1,2 @@
+from: markdown
+to: html
diff --git a/test/command/defaults6.yaml b/test/command/defaults6.yaml
new file mode 100644
--- /dev/null
+++ b/test/command/defaults6.yaml
@@ -0,0 +1,2 @@
+defaults:
+  - command/defaults7
diff --git a/test/command/defaults7.yaml b/test/command/defaults7.yaml
new file mode 100644
--- /dev/null
+++ b/test/command/defaults7.yaml
@@ -0,0 +1,2 @@
+defaults:
+  - command/defaults6
diff --git a/test/command/defaults8.yaml b/test/command/defaults8.yaml
new file mode 100644
--- /dev/null
+++ b/test/command/defaults8.yaml
@@ -0,0 +1,2 @@
+from: html
+defaults: command/defaults9
diff --git a/test/command/defaults9.yaml b/test/command/defaults9.yaml
new file mode 100644
--- /dev/null
+++ b/test/command/defaults9.yaml
@@ -0,0 +1,1 @@
+to: markdown
diff --git a/test/command/din-1505-2.csl b/test/command/din-1505-2.csl
new file mode 100644
--- /dev/null
+++ b/test/command/din-1505-2.csl
@@ -0,0 +1,406 @@
+<?xml version="1.0" encoding="utf-8"?>
+<style xmlns="http://purl.org/net/xbiblio/csl" class="in-text" version="1.0" demote-non-dropping-particle="sort-only" default-locale="de-DE">
+  <info>
+    <title>DIN 1505-2 (author-date, German)</title>
+    <id>http://www.zotero.org/styles/din-1505-2</id>
+    <link href="http://www.zotero.org/styles/din-1505-2" rel="self"/>
+    <link href="http://www.bui.haw-hamburg.de/fileadmin/redaktion/diplom/Lorenzen__litverz.pdf" rel="documentation"/>
+    <link href="http://bibliothek.fh-potsdam.de/fileadmin/fhp_bib/dokumente/Schulungen/wissenschaftliches_Arbeiten/Zitieren_Lorenzen.pdf" rel="documentation"/>
+    <link href="http://www.uni-muenster.de/imperia/md/content/fachbereich_physik/didaktik_physik/materialien/materialschlichting/zitierregeln.pdf" rel="documentation"/>
+    <link href="http://forums.zotero.org/discussion/1857" rel="documentation"/>
+    <author>
+      <name>Sven Rothe</name>
+      <email>mmoole@googlemail.com</email>
+    </author>
+    <contributor>
+      <name>Julian Onions</name>
+      <email>julian.onions@gmail.com</email>
+    </contributor>
+    <category citation-format="author-date"/>
+    <category field="generic-base"/>
+    <summary>Style following DIN 1505-2, for other media types on additional standards 
+      Hinweise zur Benutzung: 
+      * Zitieren von Gesetzen: 
+        - hier müssen manuell §, Abs und S. zur Seitenangabe beim Zitieren eingetragen werden 
+        - im Kurzbeleg wird der Kurztitel verwendet, dafür keine Autoren eintragen! 
+        - als Jahresangabe wird 'Datum des Inkrafttretens' herangezogen, Verwenden nur bei Verweis auf nicht z.Z. gültige Gesetze, z.B. (idF. v. 12.12.1972) 
+       * Zitieren von Normen und Standards - nicht vollständig nach DIN 1505
+        - Nutzen Sie den Typ 'Bericht' - als Abhilfe, da es keinen Typ 'Standard' gibt.
+        - als Autor die Kurzbezeichnung inkl. Nummer und Jahr eingeben (z.B. VDI 2222-1997), Vorname leer, Jahr leer
+        - als Titel den ausführlichen Titel bei Bedarf (z.B. VDI Richtlinie 2222 Blatt 1 - Konstruktionsmethodik - Methodisches Entwickeln von Lösungsprinzipien)</summary>
+    <!--    This is just a beginning to try to have a DIN 1505 citation style,
+            Feel free to send me any comments, suggestions etc...
+            todo:
+            * basic media types (book, journal article, etc..)
+            * more media types (according DINxxx) audio video etc...
+            * fine tuning
+            * correcting errors
+            known bugs, help appreciated
+            * Abbreviations (Mitarb.) & (Hrsg. der Reihe) are missing (contributor, seriesEditor labels)
+            * "contributor" is not valid as a name variable , nevertheless it works but doesn't validate!
+            * author etc. first names should not be abbreviated
+            * reviewed author seems to be not available as variable (newspaper article)
+            * thesis type does notoffer a PLACE or FACULTY as variable!
+            how to show the place if it is not included in the University title!?!?
+            * thesis type: publisher (university), genre (type) dont seem to get through!?
+    -->
+    <!-- useful things:
+      non breaking space: &#160;
+      narrow no break space: uni202F / &#8239; - but this is not supported widely!
+      em dash: &#8212;
+      space:  &#032;
+      tab: &#009;
+
+    -->
+    <updated>2012-09-27T22:06:38+00:00</updated>
+    <rights license="http://creativecommons.org/licenses/by-sa/3.0/">This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 License</rights>
+  </info>
+  <locale xml:lang="de">
+    <terms>
+      <term name="anonymous" form="short">o.&#160;A.</term>
+      <term name="no date" form="short">o.&#160;J.</term>
+      <term name="collection-editor" form="short">Hrsg.</term>
+      <term name="retrieved">abgerufen am</term>
+      <term name="composer" form="short">Komp.</term>
+      <term name="composer" form="long">Komponist</term>
+    </terms>
+  </locale>
+  <macro name="author">
+    <names variable="author" delimiter=" ; ">
+      <name name-as-sort-order="all" sort-separator=", " delimiter=" ; " delimiter-precedes-last="always" font-variant="small-caps"/>
+      <label form="short" prefix=" (" suffix=")"/>
+    </names>
+  </macro>
+  <macro name="author-container">
+    <names variable="container-author" delimiter=" ; ">
+      <name name-as-sort-order="all" sort-separator=", " initialize-with=". " delimiter=" ; " delimiter-precedes-last="always" font-variant="small-caps"/>
+      <label form="short" prefix=" (" suffix=")"/>
+    </names>
+  </macro>
+  <macro name="editor">
+    <names variable="editor" delimiter=" ; ">
+      <name name-as-sort-order="all" sort-separator=", " initialize-with=". " delimiter=" ; " delimiter-precedes-last="always" font-variant="small-caps"/>
+      <label form="short" prefix=" (" suffix=")"/>
+      <!-- needed: Label should appear as suffix to EVERY name...!-->
+    </names>
+  </macro>
+  <macro name="editor-collection">
+    <names variable="collection-editor" delimiter=" ; ">
+      <name name-as-sort-order="all" sort-separator=", " initialize-with=". " delimiter=" ; " delimiter-precedes-last="always" font-variant="small-caps"/>
+      <label form="short" prefix=" (" suffix=")"/>
+      <!-- needed: Label should appear as suffix to EVERY name...!-->
+    </names>
+  </macro>
+  <macro name="composer">
+    <names variable="composer" delimiter=" ; ">
+      <name name-as-sort-order="all" sort-separator=", " delimiter=" ; " delimiter-precedes-last="always" font-variant="small-caps"/>
+      <label form="long" prefix=" (" suffix=")"/>
+      <!-- needed: Label should appear as suffix to EVERY name...!-->
+    </names>
+  </macro>
+  <!--  <macro name="contributor">
+    <names variable=" " delimiter=" ; ">
+    <name name-as-sort-order="all" sort-separator=", " initialize-with=". " delimiter=" ; "
+    delimiter-precedes-last="always" font-variant="small-caps"/>
+    <label form="short" prefix=" (" suffix=")"/>
+    </names>
+    </macro>-->
+  <macro name="translator">
+    <names variable="translator" delimiter=" ; ">
+      <name name-as-sort-order="all" sort-separator=", " initialize-with=". " delimiter=" ; " delimiter-precedes-last="always" font-variant="small-caps"/>
+      <label form="short" prefix=" (" suffix=")"/>
+      <!-- needed: Label should appear as suffix to EVERY name...!-->
+    </names>
+  </macro>
+  <macro name="recipient">
+    <names variable="recipient" delimiter=" ; ">
+      <name name-as-sort-order="all" sort-separator=", " initialize-with=". " delimiter=" ; " delimiter-precedes-last="always" font-variant="small-caps"/>
+      <!--<label form="long" prefix=" (" suffix=")"/>-->
+      <!-- needed: Label should appear as suffix to EVERY name...!-->
+    </names>
+  </macro>
+  <macro name="author-short">
+    <names variable="author">
+      <name form="short" and="symbol" delimiter=", " initialize-with=". " delimiter-precedes-last="never" font-variant="small-caps"/>
+      <et-al font-variant="normal"/>
+      <substitute>
+        <names variable="editor" font-variant="small-caps"/>
+        <names variable="translator" font-variant="small-caps"/>
+        <choose>
+          <if type="bill book graphic legal_case  motion_picture report song" match="any">
+            <text variable="title" form="short" font-style="italic"/>
+          </if>
+          <else-if type="bill legal_case legislation" match="any">
+            <text variable="title" form="short" font-style="normal"/>
+          </else-if>
+          <else>
+            <text variable="title" form="short" quotes="true"/>
+          </else>
+        </choose>
+      </substitute>
+    </names>
+  </macro>
+  <macro name="access">
+    <group>
+      <text term="retrieved" suffix=" "/>
+      <date variable="accessed">
+        <date-part name="year" form="long" suffix="-"/>
+        <date-part name="month" form="numeric-leading-zeros" suffix="-"/>
+        <date-part name="day" form="numeric-leading-zeros"/>
+      </date>
+      <!--<date variable="accessed" form="numeric" date-parts="year-month-day"/> // dd.mm.yyy -->
+    </group>
+  </macro>
+  <macro name="title">
+    <choose>
+      <if type="bill legislation" match="any">
+        <group delimiter=" &#8212; ">
+          <text variable="title-short" font-style="normal"/>
+          <text variable="title"/>
+        </group>
+      </if>
+      <else-if type="book graphic legal_case motion_picture report song" match="any">
+        <text variable="title" font-style="italic"/>
+      </else-if>
+      <else>
+        <text variable="title"/>
+      </else>
+    </choose>
+  </macro>
+  <macro name="genre">
+    <choose>
+      <if type="report thesis manuscript map" match="any">
+        <group>
+          <text variable="genre"/>
+          <!--<text term="number" form="short" suffix=" "/>-->
+          <text variable="number" prefix=" Nr. "/>
+        </group>
+      </if>
+    </choose>
+  </macro>
+  <macro name="volumes">
+    <group delimiter=" ">
+      <text term="volume" form="short" plural="false"/>
+      <number variable="volume" form="numeric"/>
+      <number variable="number-of-volumes" form="numeric" prefix="v. "/>
+    </group>
+  </macro>
+  <macro name="edition">
+    <group>
+      <number variable="edition" form="numeric" suffix=". "/>
+      <text term="edition" form="short" plural="false"/>
+    </group>
+  </macro>
+  <macro name="pages">
+    <choose>
+      <if type="chapter paper-conference article-journal" match="any">
+        <label variable="page" form="short" suffix="&#160;"/>
+        <text variable="page"/>
+      </if>
+    </choose>
+  </macro>
+  <macro name="dimensions">
+    <group>
+      <text variable="dimensions"/>
+    </group>
+  </macro>
+  <macro name="medium">
+    <group>
+      <text variable="medium"/>
+    </group>
+  </macro>
+  <macro name="scale">
+    <group>
+      <text term="scale"/>
+      <text prefix=" " variable="scale"/>
+    </group>
+  </macro>
+  <macro name="recipient-show">
+    <choose>
+      <if type="personal_communication">
+        <choose>
+          <if variable="genre">
+            <text variable="genre" text-case="capitalize-first"/>
+          </if>
+          <else>
+            <text term="letter" text-case="capitalize-first"/>
+          </else>
+        </choose>
+      </if>
+    </choose>
+    <text macro="recipient" prefix=", "/>
+  </macro>
+  <macro name="cite-year">
+    <group>
+      <choose>
+        <if type="bill legislation" match="any">
+          <date variable="issued" prefix=" (" suffix=")">
+            <date-part name="year" prefix="idF. v. "/>
+          </date>
+        </if>
+        <else>
+          <date variable="issued" prefix=", ">
+            <date-part name="year"/>
+          </date>
+          <text variable="year-suffix"/>
+        </else>
+      </choose>
+    </group>
+  </macro>
+  <macro name="bibliography-year">
+    <date variable="issued" form="numeric" date-parts="year"/>
+    <text variable="year-suffix"/>
+  </macro>
+  <macro name="locator">
+    <group>
+      <choose>
+        <if type="bill legislation" match="any">
+          <text variable="locator" prefix=" "/>
+        </if>
+        <else>
+          <label variable="locator" form="short" prefix=", "/>
+          <text variable="locator" prefix=" "/>
+        </else>
+      </choose>
+    </group>
+  </macro>
+  <citation et-al-min="3" et-al-use-first="1" disambiguate-add-year-suffix="true" disambiguate-add-names="false" disambiguate-add-givenname="false" collapse="year">
+    <sort>
+      <key macro="author"/>
+      <key variable="issued"/>
+    </sort>
+    <layout prefix="(" suffix=")" delimiter="; ">
+      <group>
+        <text macro="author-short"/>
+        <text macro="cite-year"/>
+        <text macro="locator"/>
+      </group>
+    </layout>
+  </citation>
+  <bibliography hanging-indent="true" et-al-min="9" et-al-use-first="8">
+    <sort>
+      <key macro="author"/>
+      <key variable="issued"/>
+      <key variable="title"/>
+    </sort>
+    <layout>
+      <group delimiter=" ; " suffix=":">
+        <text macro="author"/>
+        <choose>
+          <if type="bill book graphic legal_case legislation manuscript map motion_picture report song thesis webpage" match="any">
+            <!-- except type="chapter article " etc.... -->
+            <text macro="editor"/>
+            <text macro="editor-collection"/>
+            <text macro="composer"/>
+          </if>
+        </choose>
+        <!-- <text macro="contributor"/> -->
+        <text macro="translator"/>
+      </group>
+      <choose>
+        <!-- Tabelle 1 aus litverz.ps -->
+        <if type="bill book broadcast graphic legal_case legislation manuscript map motion_picture report song" match="any">
+          <text prefix=" " macro="title"/>
+          <text prefix=", " variable="collection-title" font-style="italic"/>
+          <!--Reihe-->
+          <text prefix=" (" macro="genre" suffix=")"/>
+          <text prefix=". " macro="volumes"/>
+          <text prefix=". " macro="edition"/>
+          <text prefix=". " macro="medium"/>
+          <text prefix=". " macro="dimensions"/>
+          <text prefix=". " variable="publisher-place"/>
+          <text prefix="&#160;: " variable="publisher"/>
+          <text macro="bibliography-year" prefix=", "/>
+          <!-- " (1. Gesamttitel mit Zählung)"
+            " (2. Gesamttitel mit Zählung)" -->
+          <text prefix=" &#8211;&#160;" macro="scale"/>
+          <text prefix=". &#8212;&#160;" variable="note"/>
+          <text prefix=" &#8212;&#160;ISBN&#160;" variable="ISBN"/>
+        </if>
+        <!-- Tabelle 3 aus litverz.ps -->
+        <else-if type="chapter paper-conference" match="any">
+          <text prefix=" " macro="title" suffix="."/>
+          <text prefix=". " term="in" text-case="capitalize-all" suffix=": "/>
+          <!-- verfahre nach Tabelle 1... -->
+          <group delimiter=" ; " suffix=": ">
+            <text macro="author-container"/>
+            <text macro="editor"/>
+            <text macro="editor-collection"/>
+          </group>
+          <text variable="container-title" font-style="italic"/>
+          <text prefix=", " variable="collection-title" font-style="italic"/>
+          <!-- Reihe -->
+          <text prefix=". " macro="volumes"/>
+          <!-- <text prefix=" : " variable="title of volumes"/> what is this? -->
+          <text prefix=". " macro="edition"/>
+          <text prefix=". " variable="publisher-place"/>
+          <text prefix="&#160;: " variable="publisher"/>
+          <text macro="bibliography-year" prefix=", "/>
+          <!-- " (1. Gesamttitel mit Zählung)"
+            " (2. Gesamttitel mit Zählung)" -->
+          <text prefix=". &#8212;&#160;" variable="note"/>
+          <text prefix=" &#8212;&#160;ISBN&#160;" variable="ISBN"/>
+          <text prefix=", " macro="pages"/>
+        </else-if>
+        <!-- Tabelle 5 aus litverz.ps - Hochschulschriften
+          (Diplomarbeiten, Dissertationen, Master-A., unverö. Studienarbeiten -->
+        <else-if type="thesis" match="any">
+          <text prefix=" " macro="title" font-style="italic"/>
+          <text prefix=". " macro="edition"/>
+          <text prefix=". " variable="publisher-place"/>
+          <text prefix=", " variable="publisher" form="long"/>
+          <!-- <text prefix=", " variable="faculty"/> -->
+          <text prefix=", " macro="genre"/>
+          <text macro="bibliography-year" prefix=", "/>
+          <text prefix=". &#8212;&#160;" variable="note"/>
+        </else-if>
+        <else-if type="webpage post post-weblog" match="any">
+          <text prefix=" " macro="title" suffix=". " font-style="italic"/>
+          <text prefix="URL " variable="URL"/>
+          <text prefix=". - " macro="access"/>
+          <text prefix=". &#8212;&#160;" variable="container-title"/>
+          <text prefix=". &#8212;&#160;" variable="note"/>
+        </else-if>
+        <!-- Tabelle 2 aus litverz.ps UND -->
+        <!-- Tabelle 4 aus litverz.ps - Schriften von Tagungen, Konferenzen, Symposien, ...-->
+        <else-if type="article article-journal article-magazine article-newspaper" match="any">
+          <text prefix=" " variable="title"/>
+          <!-- " : Zusatz zum Sachtitel"
+            ". Angabe des Teils"
+            " (Gesamttitelangabe)" -->
+          <group>
+            <text prefix=". " term="in" text-case="capitalize-first" suffix=": "/>
+            <text macro="editor" suffix=" "/>
+            <text variable="container-title" font-style="italic"/>
+            <text prefix=", " variable="collection-title" font-style="italic" suffix="."/>
+            <!--", unterreihe der zeitschrift/zeitung" -->
+          </group>
+          <text prefix=" " macro="volumes"/>
+          <text prefix=". " variable="publisher-place"/>
+          <text prefix=", " variable="publisher" form="long"/>
+          <text macro="bibliography-year" prefix=" (" suffix=")"/>
+          <text prefix=", Nr.&#160;" variable="issue"/>
+          <text prefix=", " macro="pages"/>
+          <text prefix=". &#8212;&#160;" variable="note"/>
+          <text prefix=" &#8212;&#160;ISBN&#160;" variable="ISBN"/>
+        </else-if>
+        <!-- keiner der oben genannten fälle -->
+        <else>
+          <group suffix=".">
+            <text prefix=" " macro="title"/>
+            <text prefix=", " macro="editor"/>
+            <text prefix=". " macro="recipient-show"/>
+          </group>
+          <group prefix=" " suffix=".">
+            <text variable="container-title" font-style="italic"/>
+            <group prefix=", ">
+              <text variable="volume" font-style="italic"/>
+              <text variable="issue" prefix="(" suffix=")"/>
+            </group>
+            <text prefix=", " macro="pages"/>
+          </group>
+        </else>
+      </choose>
+    </layout>
+  </bibliography>
+</style>
diff --git a/test/command/docbook-bibliography.md b/test/command/docbook-bibliography.md
new file mode 100644
--- /dev/null
+++ b/test/command/docbook-bibliography.md
@@ -0,0 +1,45 @@
+```
+% pandoc -f docbook -t native --quiet
+<bibliodiv>
+<title>Document References</title>
+<bibliomixed>
+<bibliomisc><anchor xml:id="refTheFirst" xreflabel="[1]"/>[1] First reference</bibliomisc>
+</bibliomixed>
+<bibliomixed>
+<bibliomisc><anchor xml:id="refTheSecond" xreflabel="[2]"/>[2] Second reference</bibliomisc>
+</bibliomixed>
+<bibliomixed>
+<bibliomisc><anchor xml:id="refTheThird" xreflabel="[3]"/>[3] Third reference</bibliomisc>
+</bibliomixed>
+</bibliodiv>
+^D
+[ Header
+    1
+    ( "" , [] , [] )
+    [ Str "Document" , Space , Str "References" ]
+, Para
+    [ Span ( "refTheFirst" , [] , [] ) []
+    , Str "[1]"
+    , Space
+    , Str "First"
+    , Space
+    , Str "reference"
+    ]
+, Para
+    [ Span ( "refTheSecond" , [] , [] ) []
+    , Str "[2]"
+    , Space
+    , Str "Second"
+    , Space
+    , Str "reference"
+    ]
+, Para
+    [ Span ( "refTheThird" , [] , [] ) []
+    , Str "[3]"
+    , Space
+    , Str "Third"
+    , Space
+    , Str "reference"
+    ]
+]
+```
diff --git a/test/command/dokuwiki-quote.md b/test/command/dokuwiki-quote.md
new file mode 100644
--- /dev/null
+++ b/test/command/dokuwiki-quote.md
@@ -0,0 +1,16 @@
+```
+% pandoc -f dokuwiki -t native
+> <code>some
+code
+</code>
+>> ok
+> then
+> more
+^D
+[ BlockQuote
+    [ CodeBlock ( "" , [] , [] ) "some\ncode\n"
+    , BlockQuote [ Plain [ Str "ok" ] ]
+    , Plain [ Str "then" , LineBreak , Str "more" ]
+    ]
+]
+```
diff --git a/test/command/dots.md b/test/command/dots.md
--- a/test/command/dots.md
+++ b/test/command/dots.md
@@ -6,7 +6,8 @@
 
 \vdots
 ^D
-[Para [Str "\8230"]
-,Para [Str "\8230"]
-,Para [Str "\8942"]]
+[ Para [ Str "\8230" ]
+, Para [ Str "\8230" ]
+, Para [ Str "\8942" ]
+]
 ```
diff --git a/test/command/duplicate_attributes.md b/test/command/duplicate_attributes.md
new file mode 100644
--- /dev/null
+++ b/test/command/duplicate_attributes.md
@@ -0,0 +1,7 @@
+```
+% pandoc
+[span]{.foobar style="color:blue" class="zip" style="color:red"}
+^D
+2> [WARNING] Ignoring duplicate attribute style="color:red".
+<p><span class="foobar zip" style="color:blue">span</span></p>
+```
diff --git a/test/command/emoji.md b/test/command/emoji.md
new file mode 100644
--- /dev/null
+++ b/test/command/emoji.md
@@ -0,0 +1,27 @@
+```
+% pandoc -t markdown+emoji -f markdown+emoji
+:smile:
+^D
+:smile:
+```
+
+```
+% pandoc -t markdown-emoji -f markdown+emoji
+:smile:
+^D
+😄
+```
+
+```
+% pandoc -t gfm -f markdown+emoji
+:smile:
+^D
+:smile:
+```
+
+```
+% pandoc -t gfm-emoji -f markdown+emoji
+:smile:
+^D
+😄
+```
diff --git a/test/command/empty_paragraphs.md b/test/command/empty_paragraphs.md
--- a/test/command/empty_paragraphs.md
+++ b/test/command/empty_paragraphs.md
@@ -2,34 +2,32 @@
 % pandoc -f native -t docx -o - | pandoc -f docx -t native
 [Para [Str "hi"], Para [], Para [], Para [Str "lo"]]
 ^D
-[Para [Str "hi"]
-,Para [Str "lo"]]
+[ Para [ Str "hi" ] , Para [ Str "lo" ] ]
 ```
 
 ```
 % pandoc -f native -t docx+empty_paragraphs -o - | pandoc -f docx -t native
 [Para [Str "hi"], Para [], Para [], Para [Str "lo"]]
 ^D
-[Para [Str "hi"]
-,Para [Str "lo"]]
+[ Para [ Str "hi" ] , Para [ Str "lo" ] ]
 ```
 
 ```
 % pandoc -f native -t docx -o - | pandoc -f docx+empty_paragraphs -t native
 [Para [Str "hi"], Para [], Para [], Para [Str "lo"]]
 ^D
-[Para [Str "hi"]
-,Para [Str "lo"]]
+[ Para [ Str "hi" ] , Para [ Str "lo" ] ]
 ```
 
 ```
 % pandoc -f native -t docx+empty_paragraphs -o - | pandoc -f docx+empty_paragraphs -t native
 [Para [Str "hi"], Para [], Para [], Para [Str "lo"]]
 ^D
-[Para [Str "hi"]
-,Para []
-,Para []
-,Para [Str "lo"]]
+[ Para [ Str "hi" ]
+, Para []
+, Para []
+, Para [ Str "lo" ]
+]
 ```
 
 ```
@@ -37,8 +35,6 @@
 [Para [Str "hi"], Para [], Para [], Para [Str "lo"]]
 ^D
 <p>hi</p>
-
-
 <p>lo</p>
 ```
 
@@ -59,10 +55,11 @@
 <p></p>
 <p>lo</p>
 ^D
-[Para [Str "hi"]
-,Para []
-,Para []
-,Para [Str "lo"]]
+[ Para [ Str "hi" ]
+, Para []
+, Para []
+, Para [ Str "lo" ]
+]
 ```
 
 ```
@@ -72,8 +69,7 @@
 <p></p>
 <p>lo</p>
 ^D
-[Para [Str "hi"]
-,Para [Str "lo"]]
+[ Para [ Str "hi" ] , Para [ Str "lo" ] ]
 ```
 
 ```
diff --git a/test/command/figures-context.md b/test/command/figures-context.md
new file mode 100644
--- /dev/null
+++ b/test/command/figures-context.md
@@ -0,0 +1,48 @@
+# Figure with one image, caption and label
+
+```
+% pandoc -t context -f html
+<figure>
+  <img src="mandrill.jpg" />
+  <figcaption><q>The Mandrill</q>, a photo used in
+    image processing tests.</figcaption>
+</figure>
+^D
+\startplacefigure[title={\quotation{The Mandrill}, a photo used in image
+processing tests.}]
+{\externalfigure[mandrill.jpg]}
+\stopplacefigure
+```
+
+# Nested figures
+
+```
+% pandoc -t context -f html
+<figure id="test-images">
+  <figure id="mandrill">
+    <img src="../testing/mandrill.jpg">
+    <figcaption><q>The Mandrill</q> is a commonly used test image.</figcaption>
+  </figure>
+  <figure id="peppers">
+    <img src="../testing/peppers.webp" >
+    <figcaption>Another test image. This one is called <q>peppers</q>.</figcaption>
+  </figure>
+  <figcaption>Signal processing test images.</figcaption>
+</figure>
+^D
+\startplacefigure[reference=test-images,title={Signal processing test
+images.}]
+\startfloatcombination
+\startplacefigure[reference=mandrill,title={\quotation{The Mandrill} is
+a commonly used test image.}]
+{\externalfigure[../testing/mandrill.jpg]}
+\stopplacefigure
+
+\startplacefigure[reference=peppers,title={Another test image. This one
+is called \quotation{peppers}.}]
+{\externalfigure[../testing/peppers.webp]}
+\stopplacefigure
+
+\stopfloatcombination
+\stopplacefigure
+```
diff --git a/test/command/figures-fb2.md b/test/command/figures-fb2.md
new file mode 100644
--- /dev/null
+++ b/test/command/figures-fb2.md
@@ -0,0 +1,8 @@
+```
+% pandoc -f native -t fb2
+[Figure ("fig-id",[],[]) (Caption Nothing []) [Para [Str "content"]]]
+
+^D
+<?xml version="1.0" encoding="UTF-8"?>
+<FictionBook xmlns="http://www.gribuser.ru/xml/fictionbook/2.0" xmlns:l="http://www.w3.org/1999/xlink"><description><title-info><genre>unrecognised</genre></title-info><document-info><program-used>pandoc</program-used></document-info></description><body><title><p /></title><section><p>content</p></section></body></FictionBook>
+```
diff --git a/test/command/figures-haddock.md b/test/command/figures-haddock.md
new file mode 100644
--- /dev/null
+++ b/test/command/figures-haddock.md
@@ -0,0 +1,7 @@
+```
+% pandoc -f native -t haddock
+[Figure ("fig-id",[],[]) (Caption Nothing []) [Para [Str "content"]]]
+
+^D
+content
+```
diff --git a/test/command/figures-html.md b/test/command/figures-html.md
new file mode 100644
--- /dev/null
+++ b/test/command/figures-html.md
@@ -0,0 +1,92 @@
+# Writer
+
+HTML5 figure with caption and content.
+
+```
+% pandoc -f native -t html5
+[Figure ("fig-id",[],[]) (Caption Nothing [Plain [Str "caption"]]) [Para [Str "content"]]]
+
+^D
+<figure id="fig-id">
+<p>content</p>
+<figcaption>caption</figcaption>
+</figure>
+```
+
+HTML5 figure with NO caption and content.
+
+```
+% pandoc -f native -t html5
+[Figure ("fig-id",[],[]) (Caption Nothing []) [Para [Str "content"]]]
+
+^D
+<figure id="fig-id">
+<p>content</p>
+</figure>
+```
+
+HTML4 figure with caption and content.
+
+```
+% pandoc -f native -t html4
+[Figure ("fig-id",[],[]) (Caption Nothing [Plain [Str "caption"]]) [Para [Str "content"]]]
+
+^D
+<div class="float" id="fig-id">
+<p>content</p>
+<div class="figcaption">caption</div>
+</div>
+```
+
+HTML4 figure with NO caption and content.
+
+```
+% pandoc -f native -t html4
+[Figure ("fig-id",[],[]) (Caption Nothing []) [Para [Str "content"]]]
+
+^D
+<div class="float" id="fig-id">
+<p>content</p>
+</div>
+```
+
+# Reader
+
+Figure with caption and multiple elements.
+
+```
+% pandoc -f html -t native
+<figure class="important">
+  <img src="../media/rId25.jpg" />
+  <ul> <li> ITEM </li> </ul>
+  <figcaption> CAP2 </figcaption>
+</figure>
+^D
+[ Figure
+    ( "" , [ "important" ] , [] )
+    (Caption Nothing [ Plain [ Str "CAP2" ] ])
+    [ Plain
+        [ Image ( "" , [] , [] ) [] ( "../media/rId25.jpg" , "" ) ]
+    , BulletList [ [ Plain [ Str "ITEM" ] ] ]
+    ]
+]
+```
+
+Figure without caption.
+
+```
+% pandoc -f html -t native
+<figure class="important">
+  <img src="../media/rId25.jpg" />
+  <ul> <li> ITEM </li> </ul>
+</figure>
+^D
+[ Figure
+    ( "" , [ "important" ] , [] )
+    (Caption Nothing [])
+    [ Plain
+        [ Image ( "" , [] , [] ) [] ( "../media/rId25.jpg" , "" ) ]
+    , BulletList [ [ Plain [ Str "ITEM" ] ] ]
+    ]
+]
+```
diff --git a/test/command/figures-jats.md b/test/command/figures-jats.md
new file mode 100644
--- /dev/null
+++ b/test/command/figures-jats.md
@@ -0,0 +1,31 @@
+Figure float with caption at the figure level.
+
+```
+% pandoc -f native -t jats
+[Figure ("fig-id",[],[]) (Caption Nothing [Para [Str "Caption"]]) [Para [Str "Text"],
+Para [Image ("fig-id-2",[],[]) [] ("foo.png", "fig:")]]]
+
+^D
+<fig id="fig-id">
+  <caption><p>Caption</p></caption>
+  <p>Text</p>
+  <graphic id="fig-id-2" mimetype="image" mime-subtype="png" xlink:href="foo.png" xlink:title="fig:" />
+</fig>
+```
+
+Figure float with caption and alt text.
+
+```
+% pandoc -f native -t jats
+[Figure ("fig-id",[],[]) (Caption Nothing [Para [Str "Caption"]]) [Para [Str "Text"],
+Para [Image ("fig-id-2",[],[]) [Str "alt"] ("foo.png", "fig:")]]]
+
+^D
+<fig id="fig-id">
+  <caption><p>Caption</p></caption>
+  <p>Text</p>
+  <graphic id="fig-id-2" mimetype="image" mime-subtype="png" xlink:href="foo.png" xlink:title="fig:">
+    <alt-text>alt</alt-text>
+  </graphic>
+</fig>
+```
diff --git a/test/command/figures-jira.md b/test/command/figures-jira.md
new file mode 100644
--- /dev/null
+++ b/test/command/figures-jira.md
@@ -0,0 +1,9 @@
+A figure with title
+```
+% pandoc -f native -t jira
+[Figure ("fig-id",[],[("title","This is the title")]) (Caption Nothing []) []]
+^D
+{panel:title=This is the title}
+{anchor:fig-id}
+{panel}
+```
diff --git a/test/command/figures-latex.md b/test/command/figures-latex.md
new file mode 100644
--- /dev/null
+++ b/test/command/figures-latex.md
@@ -0,0 +1,83 @@
+# Figure with one image, caption and label
+
+```
+% pandoc -f latex -t native
+\begin{document}
+  \begin{figure}
+    \includegraphics{../../media/rId25.jpg}
+    \caption{CAP}
+    \label{LAB}
+  \end{figure}
+\end{document}
+^D
+[ Figure
+    ( "LAB" , [] , [] )
+    (Caption Nothing [ Plain [ Str "CAP" ] ])
+    [ Plain
+        [ Image ( "" , [] , [] ) [] ( "../../media/rId25.jpg" , "" )
+        ]
+    ]
+]
+```
+
+# Nested figures
+
+```
+% pandoc -f latex -t native
+\begin{figure}
+  \begin{subfigure}[b]{0.5\textwidth}
+    \begin{subfigure}[b]{0.5\textwidth}
+      \centering
+      \includegraphics{test/media/rId25.jpg}
+      \caption{CAP1.1}
+    \end{subfigure}
+    \begin{subfigure}[b]{0.5\textwidth}
+      \centering
+      \includegraphics{test/media/rId25.jpg}
+      \caption{CAP1.2}
+    \end{subfigure}
+    \caption{CAP1}
+    \label{fig:inner1}
+  \end{subfigure}
+  \begin{subfigure}[b]{0.5\textwidth}
+    \includegraphics{test/media/rId25.jpg}
+    \caption{CAP2}
+    \label{fig:inner2}
+  \end{subfigure}
+  \caption{CAP}
+  \label{fig:outer}
+\end{figure}
+^D
+[ Figure
+    ( "fig:outer" , [] , [] )
+    (Caption Nothing [ Plain [ Str "CAP" ] ])
+    [ Figure
+        ( "fig:inner1" , [] , [] )
+        (Caption Nothing [ Plain [ Str "CAP1" ] ])
+        [ Figure
+            ( "" , [] , [] )
+            (Caption Nothing [ Plain [ Str "CAP1.1" ] ])
+            [ Plain
+                [ Image
+                    ( "" , [] , [] ) [] ( "test/media/rId25.jpg" , "" )
+                ]
+            ]
+        , Figure
+            ( "" , [] , [] )
+            (Caption Nothing [ Plain [ Str "CAP1.2" ] ])
+            [ Plain
+                [ Image
+                    ( "" , [] , [] ) [] ( "test/media/rId25.jpg" , "" )
+                ]
+            ]
+        ]
+    , Figure
+        ( "fig:inner2" , [] , [] )
+        (Caption Nothing [ Plain [ Str "CAP2" ] ])
+        [ Plain
+            [ Image ( "" , [] , [] ) [] ( "test/media/rId25.jpg" , "" )
+            ]
+        ]
+    ]
+]
+```
diff --git a/test/command/figures-markdown.md b/test/command/figures-markdown.md
new file mode 100644
--- /dev/null
+++ b/test/command/figures-markdown.md
@@ -0,0 +1,12 @@
+Figure float with caption at the figure level.
+
+```
+% pandoc -f native -t markdown
+[Figure ("fig-id",[],[]) (Caption Nothing [Para [Str "Caption"]]) [Para [Image ("",[],[]) [] ("foo.png", "fig:")]]]
+
+^D
+<figure id="fig-id">
+<p><img src="foo.png" title="fig:" /></p>
+<figcaption><p>Caption</p></figcaption>
+</figure>
+```
diff --git a/test/command/figures-mediawiki.md b/test/command/figures-mediawiki.md
new file mode 100644
--- /dev/null
+++ b/test/command/figures-mediawiki.md
@@ -0,0 +1,11 @@
+Figure float with caption at the figure level.
+
+```
+% pandoc -f native -t mediawiki
+[Figure ("fig-id",[],[]) (Caption Nothing [Para [Str "Caption"]]) [Para [Image ("",[],[]) [] ("foo.png", "fig:")]]]
+
+^D
+<div id="fig-id" class="figure">
+[[File:foo.png|thumb|none]]
+</div>
+```
diff --git a/test/command/figures-org.md b/test/command/figures-org.md
new file mode 100644
--- /dev/null
+++ b/test/command/figures-org.md
@@ -0,0 +1,16 @@
+```
+% pandoc -f native -t org
+[Figure ("fig-id",[],[]) (Caption Nothing []) [Para [Str "content"]]]
+
+^D
+<<fig-id>>
+content
+```
+
+```
+% pandoc -f native -t org
+[Figure ("",[],[]) (Caption Nothing []) [Para [Str "content"]]]
+
+^D
+content
+```
diff --git a/test/command/figures-rst.md b/test/command/figures-rst.md
new file mode 100644
--- /dev/null
+++ b/test/command/figures-rst.md
@@ -0,0 +1,13 @@
+Figure float with caption at the figure level.
+
+```
+% pandoc -f native -t rst
+[Figure ("fig-id",[],[]) (Caption Nothing [Para [Str "Caption"]]) [Para [Image ("",[],[]) [] ("foo.png", "fig:")]]]
+
+^D
+.. figure:: foo.png
+   name: fig-id
+   :alt: fig:
+
+   Caption
+```
diff --git a/test/command/figures-texinfo.md b/test/command/figures-texinfo.md
new file mode 100644
--- /dev/null
+++ b/test/command/figures-texinfo.md
@@ -0,0 +1,115 @@
+Figure float with caption at the figure level.
+
+```
+% pandoc -f native -t texinfo
+[Figure ("fig-id",[],[]) (Caption Nothing [Para [Str "Caption"]]) [Para [Image ("",[],[]) [] ("foo.png", "fig:")]]]
+
+^D
+@node Top
+@top Top
+
+@float Figure
+@image{foo,,,,png}
+@caption{Caption}
+@end float
+```
+
+Float that has no caption and doesn't contain a `SimpleFigure`
+
+```
+% pandoc -f native -t texinfo
+[Figure ("fig-id",[],[]) (Caption Nothing []) [Para [Image ("",[],[]) [] ("foo.png", "")]]]
+
+^D
+@node Top
+@top Top
+
+@float
+@image{foo,,,,png}
+@end float
+```
+
+Table float with caption at the figure level.
+
+```
+% pandoc -f native -t texinfo
+[Figure ("fig-id",[],[]) (Caption Nothing [Para [Str "Caption"]])
+[Table ("",[],[]) (Caption Nothing
+ [])
+ [(AlignDefault,ColWidthDefault)
+ ,(AlignDefault,ColWidthDefault)
+ ,(AlignDefault,ColWidthDefault)]
+ (TableHead ("",[],[])
+ [Row ("",[],[])
+  [Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+   [Plain [Str "Fruit"]]
+  ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+   [Plain [Str "Price"]]
+  ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+   [Plain [Str "Quantity"]]]])
+ [(TableBody ("",[],[]) (RowHeadColumns 0)
+  []
+  [Row ("",[],[])
+   [Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "Apple"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "25",Space,Str "cents"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "33"]]]
+  ,Row ("",[],[])
+   [Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "\"Navel\"",Space,Str "Orange"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "35",Space,Str "cents"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "22"]]]
+  ,Row ("",[],[])
+   [Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    []
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    []
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "45"]]]])]
+ (TableFoot ("",[],[])
+ [])]]
+
+^D
+@node Top
+@top Top
+
+@float Table
+@multitable {"Navel" Orange} {35 cents} {Quantity} 
+@headitem 
+Fruit
+ @tab Price
+ @tab Quantity
+@item 
+Apple
+ @tab 25 cents
+ @tab 33
+@item 
+"Navel" Orange
+ @tab 35 cents
+ @tab 22
+@item 
+45
+@end multitable
+@caption{Caption}
+@end float
+```
+
+Float the isn't a table nor a figure.
+
+```
+% pandoc -f native -t texinfo
+[Figure ("fig-id",[],[]) (Caption Nothing [Para[ Str "Caption"]]) [Para [Str "Content"]]]
+
+^D
+@node Top
+@top Top
+
+@float
+Content
+@caption{Caption}
+@end float
+```
diff --git a/test/command/figures-textile.md b/test/command/figures-textile.md
new file mode 100644
--- /dev/null
+++ b/test/command/figures-textile.md
@@ -0,0 +1,31 @@
+```
+% pandoc -f native -t textile
+[Figure ("fig-id",[],[]) (Caption Nothing [Para [Str "Caption"]]) [Para [Image ("",[],[]) [] ("foo.png", "")]]]
+
+^D
+<figure id="fig-id">
+
+<figcaption>
+
+Caption
+
+</figcaption>
+
+!foo.png!
+
+
+</figure>
+```
+
+```
+% pandoc -f native -t textile
+[Figure ("fig-id",[],[]) (Caption Nothing []) [Para [Image ("",[],[]) [] ("foo.png", "")]]]
+
+^D
+<figure id="fig-id">
+
+!foo.png!
+
+
+</figure>
+```
diff --git a/test/command/figures-xwiki.md b/test/command/figures-xwiki.md
new file mode 100644
--- /dev/null
+++ b/test/command/figures-xwiki.md
@@ -0,0 +1,10 @@
+```
+% pandoc -f native -t xwiki
+[Figure ("fig-id",[],[]) (Caption Nothing []) [Para [Str "content"]]]
+
+^D
+(((
+{{id name="fig-id" /}}content
+
+)))
+```
diff --git a/test/command/figures-zimwiki.md b/test/command/figures-zimwiki.md
new file mode 100644
--- /dev/null
+++ b/test/command/figures-zimwiki.md
@@ -0,0 +1,9 @@
+```
+% pandoc -f native -t zimwiki
+[Figure ("fig-id",[],[]) (Caption Nothing []) [Para [Str "content"]]]
+
+^D
+content
+
+
+```
diff --git a/test/command/file1.txt b/test/command/file1.txt
new file mode 100644
--- /dev/null
+++ b/test/command/file1.txt
@@ -0,0 +1,9 @@
+# Zed
+
+[foo]: bar
+
+[foo]
+and [Zed](#zed)
+and [other Zed](command/file2.txt#zed)
+and [other file](command/file2.txt)
+and [foreign Zed](c.md#zed)
diff --git a/test/command/file2.txt b/test/command/file2.txt
new file mode 100644
--- /dev/null
+++ b/test/command/file2.txt
@@ -0,0 +1,5 @@
+## Zed
+
+[foo]: baz
+
+[foo]
diff --git a/test/command/gfm.md b/test/command/gfm.md
--- a/test/command/gfm.md
+++ b/test/command/gfm.md
@@ -7,20 +7,76 @@
 | apple | 0.13  |
 | orange|1.12|
 ^D
-[Table [] [AlignDefault,AlignRight] [0.0,0.0]
- [[Plain [Str "Fruit"]]
- ,[Plain [Str "Price"]]]
- [[[Plain [Str "apple"]]
-  ,[Plain [Str "0.13"]]]
- ,[[Plain [Str "orange"]]
-  ,[Plain [Str "1.12"]]]]]
+[ Table
+    ( "" , [] , [] )
+    (Caption Nothing [])
+    [ ( AlignDefault , ColWidthDefault )
+    , ( AlignRight , ColWidthDefault )
+    ]
+    (TableHead
+       ( "" , [] , [] )
+       [ Row
+           ( "" , [] , [] )
+           [ Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "Fruit" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "Price" ] ]
+           ]
+       ])
+    [ TableBody
+        ( "" , [] , [] )
+        (RowHeadColumns 0)
+        []
+        [ Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "apple" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "0.13" ] ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "orange" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "1.12" ] ]
+            ]
+        ]
+    ]
+    (TableFoot ( "" , [] , [] ) [])
+]
 ```
 
 ```
 % pandoc -f gfm -t native
 ~~stricken out~~
 ^D
-[Para [Strikeout [Str "stricken",Space,Str "out"]]]
+[ Para [ Strikeout [ Str "stricken" , Space , Str "out" ] ]
+]
 ```
 
 ```
@@ -29,44 +85,73 @@
 ## Header
 # -foo-bar_baz
 ^D
-[Header 1 ("header",[],[]) [Str "Header"]
-,Header 2 ("header-1",[],[]) [Str "Header"]
-,Header 1 ("-foo-bar_baz",[],[]) [Str "-foo-bar_baz"]]
+[ Header 1 ( "header" , [] , [] ) [ Str "Header" ]
+, Header 2 ( "header-1" , [] , [] ) [ Str "Header" ]
+, Header
+    1 ( "-foo-bar_baz" , [] , [] ) [ Str "-foo-bar_baz" ]
+]
 ```
 
 ```
 % pandoc -f gfm -t native
 My:thumbsup:emoji:heart:
 ^D
-[Para [Str "My\128077emoji\10084\65039"]]
+[ Para
+    [ Str "My"
+    , Span
+        ( "" , [ "emoji" ] , [ ( "data-emoji" , "thumbsup" ) ] )
+        [ Str "\128077" ]
+    , Str "emoji"
+    , Span
+        ( "" , [ "emoji" ] , [ ( "data-emoji" , "heart" ) ] )
+        [ Str "\10084\65039" ]
+    ]
+]
 ```
 
 ```
 % pandoc -f gfm -t native
 "hi"
 ^D
-[Para [Str "\"hi\""]]
+[ Para [ Str "\"hi\"" ] ]
 ```
 
 ```
 % pandoc -f gfm+smart -t native
 "hi"
 ^D
-[Para [Str "\8220hi\8221"]]
+[ Para [ Quoted DoubleQuote [ Str "hi" ] ] ]
 ```
 
 ```
 % pandoc -t gfm -f native
-[Table [Str "The",Space,Str "caption."] [AlignDefault,AlignRight] [0.0,0.0]
- [[Plain [Str "Fruit"]]
- ,[Plain [Str "Price"]]]
- [[[Plain [Str "apple"]]
-  ,[Plain [Str "0.13"]]]
- ,[[Plain [Str "orange"]]
-  ,[Plain [Str "1.12"]]]]]
+[Table ("",[],[]) (Caption Nothing
+ [Plain [Str "The",Space,Str "caption."]])
+ [(AlignDefault,ColWidthDefault)
+ ,(AlignRight,ColWidthDefault)]
+ (TableHead ("",[],[])
+ [Row ("",[],[])
+  [Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+   [Plain [Str "Fruit"]]
+  ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+   [Plain [Str "Price"]]]])
+ [(TableBody ("",[],[]) (RowHeadColumns 0)
+  []
+  [Row ("",[],[])
+   [Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "apple"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "0.13"]]]
+  ,Row ("",[],[])
+   [Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "orange"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "1.12"]]]])]
+ (TableFoot ("",[],[])
+ [])]
 ^D
 | Fruit  | Price |
-| ------ | ----: |
+|--------|------:|
 | apple  |  0.13 |
 | orange |  1.12 |
 
@@ -99,5 +184,39 @@
 hi
 hi
 ^D
-[Para [Str "hi",LineBreak,Str "hi"]]
+[ Para [ Str "hi" , LineBreak , Str "hi" ] ]
+```
+
+```
+% pandoc -f gfm -t native
+- [ ] foo
+- [x] bar
+^D
+[ BulletList
+    [ [ Plain [ Str "\9744" , Space , Str "foo" ] ]
+    , [ Plain [ Str "\9746" , Space , Str "bar" ] ]
+    ]
+]
+```
+
+```
+% pandoc -f gfm-task_lists -t native
+- [ ] foo
+- [x] bar
+^D
+[ BulletList
+    [ [ Plain [ Str "[" , Space , Str "]" , Space , Str "foo" ]
+      ]
+    , [ Plain [ Str "[x]" , Space , Str "bar" ] ]
+    ]
+]
+```
+
+```
+% pandoc -f gfm -t gfm
+- [ ] foo
+- [x] bar
+^D
+- [ ] foo
+- [x] bar
 ```
diff --git a/test/command/grid-table-indented.md b/test/command/grid-table-indented.md
new file mode 100644
--- /dev/null
+++ b/test/command/grid-table-indented.md
@@ -0,0 +1,65 @@
+Like other block-level constructs, grid tables may be indented by up to
+three spaces and are still recognized as tables.
+
+```
+% pandoc -f markdown -t html
+   +---+---+
+   | a | b |
+   +===+===+
+   | 1 | 2 |
+   +---+---+
+^D
+<table style="width:11%;">
+<colgroup>
+<col style="width: 5%" />
+<col style="width: 5%" />
+</colgroup>
+<thead>
+<tr>
+<th>a</th>
+<th>b</th>
+</tr>
+</thead>
+<tbody>
+<tr>
+<td>1</td>
+<td>2</td>
+</tr>
+</tbody>
+</table>
+```
+
+A headerless indented grid table is recognized too.
+
+```
+% pandoc -f markdown -t html
+  +------+------+
+  | foo  | bar  |
+  +------+------+
+^D
+<table style="width:19%;">
+<colgroup>
+<col style="width: 9%" />
+<col style="width: 9%" />
+</colgroup>
+<tbody>
+<tr>
+<td>foo</td>
+<td>bar</td>
+</tr>
+</tbody>
+</table>
+```
+
+A grid table indented four spaces is a code block, not a table.
+
+```
+% pandoc -f markdown -t html
+    +---+---+
+    | a | b |
+    +---+---+
+^D
+<pre><code>+---+---+
+| a | b |
++---+---+</code></pre>
+```
diff --git a/test/command/harvard-university-of-kent.csl b/test/command/harvard-university-of-kent.csl
new file mode 100644
--- /dev/null
+++ b/test/command/harvard-university-of-kent.csl
@@ -0,0 +1,253 @@
+<?xml version="1.0" encoding="utf-8"?>
+<style xmlns="http://purl.org/net/xbiblio/csl" class="in-text" version="1.0" demote-non-dropping-particle="sort-only" default-locale="en-GB">
+  <info>
+    <title>University of Kent - Harvard</title>
+    <id>http://www.zotero.org/styles/harvard-university-of-kent</id>
+    <link href="http://www.zotero.org/styles/harvard-university-of-kent" rel="self"/>
+    <link href="http://www.zotero.org/styles/harvard-cardiff-university-biosi" rel="template"/>
+    <link href="http://www.kent.ac.uk/ai/Harvard-Style-Guide-July-2014.pdf" rel="documentation"/>
+    <author>
+      <name>Sebastian Karcher</name>
+    </author>
+    <category citation-format="author-date"/>
+    <category field="generic-base"/>
+    <summary>The Harvard author-date style - adapted for the University of Kent</summary>
+    <updated>2012-09-27T22:06:38+00:00</updated>
+    <rights license="http://creativecommons.org/licenses/by-sa/3.0/">This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 License</rights>
+  </info>
+  <macro name="editor">
+    <names variable="editor" delimiter=", ">
+      <name name-as-sort-order="all" and="text" sort-separator=", " initialize-with=". " delimiter=", " delimiter-precedes-last="never"/>
+      <label form="short" prefix=" "/>
+    </names>
+  </macro>
+  <macro name="author">
+    <names variable="author">
+      <name name-as-sort-order="all" and="text" sort-separator=", " initialize-with="." delimiter-precedes-last="never" delimiter=", "/>
+      <label form="short" prefix=" "/>
+      <et-al font-style="italic"/>
+      <substitute>
+        <names variable="editor"/>
+        <text macro="title-substitute"/>
+      </substitute>
+    </names>
+  </macro>
+  <macro name="author-short">
+    <names variable="author">
+      <name form="short" and="text" delimiter=", " delimiter-precedes-last="never" initialize-with=". "/>
+      <et-al font-style="italic"/>
+      <substitute>
+        <names variable="editor"/>
+        <text macro="title-substitute"/>
+      </substitute>
+    </names>
+  </macro>
+  <macro name="access">
+    <choose>
+      <if variable="URL">
+        <group delimiter=" ">
+          <group delimiter=": ">
+            <text term="available at" text-case="capitalize-first"/>
+            <text variable="URL"/>
+          </group>
+          <group prefix="[" suffix="]" delimiter=": ">
+            <text term="accessed" text-case="capitalize-first"/>
+            <date variable="accessed">
+              <date-part name="day" suffix=" "/>
+              <date-part name="month" suffix=" "/>
+              <date-part name="year"/>
+            </date>
+          </group>
+        </group>
+      </if>
+    </choose>
+  </macro>
+  <macro name="title">
+    <choose>
+      <if type="bill book graphic legal_case legislation motion_picture report song thesis webpage" match="any">
+        <text variable="title" font-style="italic" text-case="title"/>
+      </if>
+      <else>
+        <text variable="title"/>
+      </else>
+    </choose>
+  </macro>
+  <macro name="title-substitute">
+    <choose>
+      <if type="bill book graphic legal_case legislation motion_picture report song thesis webpage" match="any">
+        <text variable="title" font-style="italic" text-case="title"/>
+      </if>
+      <else-if type="broadcast">
+        <choose>
+          <if variable="container-title">
+            <text variable="title"/>
+          </if>
+          <else>
+            <text variable="title" font-style="italic"/>
+          </else>
+        </choose>
+      </else-if>
+      <else>
+        <text variable="title"/>
+      </else>
+    </choose>
+  </macro>
+  <macro name="publisher">
+    <choose>
+      <if type="thesis">
+        <text variable="publisher"/>
+      </if>
+      <else-if type="graphic">
+        <text variable="archive"/>
+      </else-if>
+      <else>
+        <group delimiter=": ">
+          <text variable="publisher-place"/>
+          <text variable="publisher"/>
+        </group>
+      </else>
+    </choose>
+  </macro>
+  <macro name="year-date">
+    <choose>
+      <if variable="issued">
+        <date variable="issued">
+          <date-part name="year"/>
+        </date>
+      </if>
+      <else>
+        <text term="no date" form="short"/>
+      </else>
+    </choose>
+  </macro>
+  <macro name="edition">
+    <choose>
+      <if is-numeric="edition">
+        <group delimiter=" ">
+          <number variable="edition" form="ordinal"/>
+          <text term="edition" form="short"/>
+        </group>
+      </if>
+      <else>
+        <text variable="edition" suffix="."/>
+      </else>
+    </choose>
+  </macro>
+  <macro name="online">
+    <choose>
+      <if variable="medium">
+        <text variable="medium" prefix="[" suffix="]"/>
+      </if>
+      <else-if variable="URL">
+        <text term="online" text-case="capitalize-first" prefix="[" suffix="]"/>
+      </else-if>
+    </choose>
+  </macro>
+  <macro name="broadcast-info">
+    <choose>
+      <if type="broadcast">
+        <group delimiter=". ">
+          <text variable="container-title" font-style="italic"/>
+          <text variable="number"/>
+        </group>
+      </if>
+    </choose>
+  </macro>
+  <macro name="pages">
+    <group>
+      <label variable="page" form="short" suffix=" "/>
+      <text variable="page"/>
+    </group>
+  </macro>
+  <citation et-al-min="4" et-al-use-first="1" disambiguate-add-year-suffix="true" disambiguate-add-names="true" disambiguate-add-givenname="true">
+    <layout prefix="(" suffix=")" delimiter="; ">
+      <group delimiter=", ">
+        <group delimiter=" ">
+          <text macro="author-short"/>
+          <text macro="year-date"/>
+        </group>
+        <group>
+          <label variable="locator" form="short"/>
+          <text variable="locator"/>
+        </group>
+      </group>
+    </layout>
+  </citation>
+  <bibliography et-al-min="4" et-al-use-first="1" hanging-indent="true">
+    <sort>
+      <key macro="author"/>
+      <key variable="title"/>
+    </sort>
+    <layout suffix=".">
+      <text macro="author"/>
+      <date variable="issued" prefix=" (" suffix=").">
+        <date-part name="year"/>
+      </date>
+      <choose>
+        <if type="book broadcast graphic legal_case motion_picture report song" match="any">
+          <group prefix=" " delimiter=". " suffix=".">
+            <text macro="title"/>
+            <text macro="broadcast-info"/>
+            <text macro="online"/>
+            <group delimiter=" ">
+              <text term="volume" form="short" text-case="capitalize-first"/>
+              <text variable="volume"/>
+            </group>
+            <text macro="edition"/>
+            <text macro="editor"/>
+            <text variable="collection-title"/>
+            <text variable="collection-number" prefix="Number "/>
+            <text macro="publisher"/>
+            <text variable="dimensions"/>
+          </group>
+        </if>
+        <else-if type="chapter paper-conference" match="any">
+          <text macro="title" prefix=" " suffix="."/>
+          <group prefix=" " delimiter=" ">
+            <text term="in" text-case="capitalize-first" suffix=":"/>
+            <text macro="editor"/>
+            <text variable="container-title" font-style="italic" suffix="." text-case="title"/>
+            <text macro="edition"/>
+            <group suffix="." delimiter=", ">
+              <text macro="publisher"/>
+              <text macro="pages"/>
+            </group>
+          </group>
+        </else-if>
+        <else-if type="thesis">
+          <group prefix=" " delimiter=". " suffix=".">
+            <text macro="title"/>
+            <group delimiter=", ">
+              <text variable="genre"/>
+              <text macro="publisher"/>
+            </group>
+          </group>
+        </else-if>
+        <else-if type="webpage">
+          <group prefix=" " suffix=".">
+            <group delimiter=" " suffix=".">
+              <text macro="title"/>
+              <text macro="online"/>
+            </group>
+            <text macro="edition"/>
+          </group>
+        </else-if>
+        <else>
+          <group suffix=".">
+            <text macro="title" prefix=" "/>
+            <text macro="editor" prefix=" "/>
+          </group>
+          <group prefix=" " suffix=".">
+            <group delimiter=" ">
+              <text variable="container-title" font-style="italic"/>
+              <text macro="online"/>
+            </group>
+            <text variable="volume" font-weight="bold" prefix=" "/>
+            <text variable="page" prefix=":"/>
+          </group>
+        </else>
+      </choose>
+      <text prefix=". " macro="access" suffix="."/>
+    </layout>
+  </bibliography>
+</style>
diff --git a/test/command/hspace.md b/test/command/hspace.md
--- a/test/command/hspace.md
+++ b/test/command/hspace.md
@@ -8,7 +8,10 @@
 \caption{lalune \hspace{2em} \vspace{1em} bloo}
 \end{figure}
 ^D
-[RawBlock (Format "latex") "\\begin{figure}\n\\includegraphics{lalune.jpg}\n\\caption{lalune \\hspace{2em} \\vspace{1em} bloo}\n\\end{figure}"]
+[ RawBlock
+    (Format "tex")
+    "\\begin{figure}\n\\includegraphics{lalune.jpg}\n\\caption{lalune \\hspace{2em} \\vspace{1em} bloo}\n\\end{figure}"
+]
 ```
 
 Here block:
@@ -32,14 +35,22 @@
 F & F &\\
 \end{tabular}
 ^D
-[RawBlock (Format "latex") "\\begin{tabular}[t]{cc|c}\n\\(P\\) & \\(Q\\) & \\(P\\wedge Q\\)\\\\\n\\hline\nT & T &\\\\\nT & F &\\\\\nF & T &\\\\\nF & F &\\\\\n\\end{tabular}\n\\hspace{1em}\n\\begin{tabular}[t]{cc|c}\n\\(P\\) & \\(Q\\) & \\(P\\vee Q\\)\\\\\n\\hline\nT & T &\\\\\nT & F &\\\\\nF & T &\\\\\nF & F &\\\\\n\\end{tabular}"]
+[ RawBlock
+    (Format "tex")
+    "\\begin{tabular}[t]{cc|c}\n\\(P\\) & \\(Q\\) & \\(P\\wedge Q\\)\\\\\n\\hline\nT & T &\\\\\nT & F &\\\\\nF & T &\\\\\nF & F &\\\\\n\\end{tabular}\n\\hspace{1em}\n\\begin{tabular}[t]{cc|c}\n\\(P\\) & \\(Q\\) & \\(P\\vee Q\\)\\\\\n\\hline\nT & T &\\\\\nT & F &\\\\\nF & T &\\\\\nF & F &\\\\\n\\end{tabular}"
+]
 ```
 
 ```
 % pandoc -f markdown+raw_tex -t native
 hi\hspace{1em}there
 ^D
-[Para [Str "hi",RawInline (Format "tex") "\\hspace{1em}",Str "there"]]
+[ Para
+    [ Str "hi"
+    , RawInline (Format "tex") "\\hspace{1em}"
+    , Str "there"
+    ]
+]
 ```
 
 ```
@@ -50,7 +61,8 @@
 
 there
 ^D
-[Para [Str "hi"]
-,RawBlock (Format "latex") "\\hspace{1em}"
-,Para [Str "there"]]
+[ Para [ Str "hi" ]
+, RawBlock (Format "tex") "\\hspace{1em}"
+, Para [ Str "there" ]
+]
 ```
diff --git a/test/command/html-read-figure.md b/test/command/html-read-figure.md
--- a/test/command/html-read-figure.md
+++ b/test/command/html-read-figure.md
@@ -5,7 +5,13 @@
   <figcaption>bar</figcaption>
 </figure>
 ^D
-[Para [Image ("",[],[]) [Str "bar"] ("foo.png","fig:voyage")]]
+[ Figure
+    ( "" , [] , [] )
+    (Caption Nothing [ Plain [ Str "bar" ] ])
+    [ Plain
+        [ Image ( "" , [] , [] ) [] ( "foo.png" , "voyage" ) ]
+    ]
+]
 ```
 
 ```
@@ -15,7 +21,13 @@
   <img src="foo.png" title="voyage">
 </figure>
 ^D
-[Para [Image ("",[],[]) [Str "bar"] ("foo.png","fig:voyage")]]
+[ Figure
+    ( "" , [] , [] )
+    (Caption Nothing [ Plain [ Str "bar" ] ])
+    [ Plain
+        [ Image ( "" , [] , [] ) [] ( "foo.png" , "voyage" ) ]
+    ]
+]
 ```
 
 ```
@@ -24,7 +36,13 @@
   <img src="foo.png" title="voyage">
 </figure>
 ^D
-[Para [Image ("",[],[]) [] ("foo.png","fig:voyage")]]
+[ Figure
+    ( "" , [] , [] )
+    (Caption Nothing [])
+    [ Plain
+        [ Image ( "" , [] , [] ) [] ( "foo.png" , "voyage" ) ]
+    ]
+]
 ```
 
 ```
@@ -34,12 +52,30 @@
   <figcaption>bar</figcaption>
 </figure>
 ^D
-[Para [Image ("",[],[]) [Str "bar"] ("foo.png","fig:voyage")]]
+[ Figure
+    ( "" , [] , [] )
+    (Caption Nothing [ Plain [ Str "bar" ] ])
+    [ Para
+        [ Image ( "" , [] , [] ) [] ( "foo.png" , "voyage" ) ]
+    ]
+]
 ```
 
 ```
 % pandoc -f html -t native
 <figure><img src="foo.png" title="voyage" alt="this is ignored"><figcaption>bar <strong>baz</strong></figcaption></figure>
 ^D
-[Para [Image ("",[],[]) [Str "bar",Space,Strong [Str "baz"]] ("foo.png","fig:voyage")]]
+[ Figure
+    ( "" , [] , [] )
+    (Caption
+       Nothing
+       [ Plain [ Str "bar" , Space , Strong [ Str "baz" ] ] ])
+    [ Plain
+        [ Image
+            ( "" , [] , [] )
+            [ Str "this" , Space , Str "is" , Space , Str "ignored" ]
+            ( "foo.png" , "voyage" )
+        ]
+    ]
+]
 ```
diff --git a/test/command/html-trim-definition-list-terms.md b/test/command/html-trim-definition-list-terms.md
new file mode 100644
--- /dev/null
+++ b/test/command/html-trim-definition-list-terms.md
@@ -0,0 +1,25 @@
+```
+% pandoc -f html -t native
+<dl>
+    <dt>
+    foo
+    bar
+    </dt>
+    <dt>
+    baz
+    </dt>
+    <dd>test</dd>
+</dl>
+^D
+[ DefinitionList
+    [ ( [ Str "foo"
+        , SoftBreak
+        , Str "bar"
+        , LineBreak
+        , Str "baz"
+        ]
+      , [ [ Plain [ Str "test" ] ] ]
+      )
+    ]
+]
+```
diff --git a/test/command/html-writer-a-in-a.md b/test/command/html-writer-a-in-a.md
new file mode 100644
--- /dev/null
+++ b/test/command/html-writer-a-in-a.md
@@ -0,0 +1,7 @@
+a is not allowed inside a in HTML, so we remove links in link text:
+```
+% pandoc -f native -t html
+[ Link ("",[],[]) [Link ("",[],[]) [Str "Lo"] ("url2","") ] ("url","") ]
+^D
+<a href="url"><span>Lo</span></a>
+```
diff --git a/test/command/hyphenat.md b/test/command/hyphenat.md
--- a/test/command/hyphenat.md
+++ b/test/command/hyphenat.md
@@ -2,48 +2,60 @@
 % pandoc -f latex -t native
 electromagnetic\hyp{}endioscopy
 ^D
-[Para [Str "electromagnetic-endioscopy"]]
+[ Para [ Str "electromagnetic-endioscopy" ] ]
 ```
 
 ```
 % pandoc -f latex -t native
 C\colonhyp\bshyp{}Windows\bshyp
 ^D
-[Para [Str "C:\173\\\173Windows\\\173"]]
+[ Para [ Str "C:\173\\\173Windows\\\173" ] ]
 ```
 
 ```
 % pandoc -f latex -t native
 \fshyp{}usr\fshyp{}share\fshyp
 ^D
-[Para [Str "/\173usr/\173share/\173"]]
+[ Para [ Str "/\173usr/\173share/\173" ] ]
 ```
 
 ```
 % pandoc -f latex -t native
 \fshyp{}home\fshyp{}schrieveslaach\fshyp\dothyp{}m2
 ^D
-[Para [Str "/\173home/\173schrieveslaach/\173.\173m2"]]
+[ Para [ Str "/\173home/\173schrieveslaach/\173.\173m2" ] ]
 ```
 
 ```
 % pandoc -f latex -t native
 \nohyphens{Pneumonoultramicroscopicsilicovolcanoconiosis}
 ^D
-[Para [Str "Pneumonoultramicroscopicsilicovolcanoconiosis"]]
+[ Para
+    [ Str "Pneumonoultramicroscopicsilicovolcanoconiosis" ]
+]
 ```
 
 ```
 % pandoc -f latex -t native
 \textnhtt{Pneumonoultramicroscopicsilicovolcanoconiosis}
 ^D
-[Para [Code ("",[],[]) "Pneumonoultramicroscopicsilicovolcanoconiosis"]]
+[ Para
+    [ Code
+        ( "" , [] , [] )
+        "Pneumonoultramicroscopicsilicovolcanoconiosis"
+    ]
+]
 ```
 
 ```
 % pandoc -f latex -t native
 \nhttfamily{Pneumonoultramicroscopicsilicovolcanoconiosis}
 ^D
-[Para [Code ("",[],[]) "Pneumonoultramicroscopicsilicovolcanoconiosis"]]
+[ Para
+    [ Code
+        ( "" , [] , [] )
+        "Pneumonoultramicroscopicsilicovolcanoconiosis"
+    ]
+]
 ```
 
diff --git a/test/command/ieee.csl b/test/command/ieee.csl
new file mode 100644
--- /dev/null
+++ b/test/command/ieee.csl
@@ -0,0 +1,339 @@
+<?xml version="1.0" encoding="utf-8"?>
+<style xmlns="http://purl.org/net/xbiblio/csl" class="in-text" version="1.0" demote-non-dropping-particle="sort-only">
+  <info>
+    <title>IEEE</title>
+    <id>http://www.zotero.org/styles/ieee</id>
+    <link href="http://www.zotero.org/styles/ieee" rel="self"/>
+    <link href="http://www.ieee.org/documents/style_manual.pdf" rel="documentation"/>
+    <link href="http://www.ieee.org/documents/auinfo07.pdf" rel="documentation"/>
+    <author>
+      <name>Michael Berkowitz</name>
+      <email>mberkowi@gmu.edu</email>
+    </author>
+    <contributor>
+      <name>Julian Onions</name>
+      <email>julian.onions@gmail.com</email>
+    </contributor>
+    <contributor>
+      <name>Rintze Zelle</name>
+      <uri>http://twitter.com/rintzezelle</uri>
+    </contributor>
+    <contributor>
+      <name>Stephen Frank</name>
+      <uri>http://www.zotero.org/sfrank</uri>
+    </contributor>
+    <contributor>
+      <name>Sebastian Karcher</name>
+    </contributor>
+    <category citation-format="numeric"/>
+    <category field="engineering"/>
+    <category field="generic-base"/>
+    <updated>2013-12-17T18:04:02+00:00</updated>
+    <rights license="http://creativecommons.org/licenses/by-sa/3.0/">This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 License</rights>
+  </info>
+  <locale xml:lang="en">
+    <terms>
+      <term name="chapter" form="short">ch.</term>
+      <term name="presented at">presented at the</term>
+      <term name="available at">available</term>
+    </terms>
+  </locale>
+  <!-- Macros -->
+  <macro name="edition">
+    <choose>
+      <if type="bill book chapter graphic legal_case legislation motion_picture paper-conference report song" match="any">
+        <choose>
+          <if is-numeric="edition">
+            <group delimiter=" ">
+              <number variable="edition" form="ordinal"/>
+              <text term="edition" form="short"/>
+            </group>
+          </if>
+          <else>
+            <text variable="edition" text-case="capitalize-first" suffix="."/>
+          </else>
+        </choose>
+      </if>
+    </choose>
+  </macro>
+  <macro name="issued">
+    <choose>
+      <if type="article-journal report" match="any">
+        <date variable="issued">
+          <date-part name="month" form="short" suffix=" "/>
+          <date-part name="year" form="long"/>
+        </date>
+      </if>
+      <else-if type=" bill book chapter graphic legal_case legislation motion_picture paper-conference song thesis" match="any">
+        <date variable="issued">
+          <date-part name="year" form="long"/>
+        </date>
+      </else-if>
+      <else>
+        <date variable="issued">
+          <date-part name="day" form="numeric-leading-zeros" suffix="-"/>
+          <date-part name="month" form="short" suffix="-" strip-periods="true"/>
+          <date-part name="year" form="long"/>
+        </date>
+      </else>
+    </choose>
+  </macro>
+  <macro name="author">
+    <names variable="author">
+      <name initialize-with=". " delimiter=", " and="text"/>
+      <label form="short" prefix=", " text-case="capitalize-first"/>
+      <substitute>
+        <names variable="editor"/>
+        <names variable="translator"/>
+      </substitute>
+    </names>
+  </macro>
+  <macro name="editor">
+    <names variable="editor">
+      <name initialize-with=". " delimiter=", " and="text"/>
+      <label form="short" prefix=", " text-case="capitalize-first"/>
+    </names>
+  </macro>
+  <macro name="locators">
+    <group delimiter=", ">
+      <text macro="edition"/>
+      <group delimiter=" ">
+        <text term="volume" form="short"/>
+        <number variable="volume" form="numeric"/>
+      </group>
+      <group delimiter=" ">
+        <number variable="number-of-volumes" form="numeric"/>
+        <text term="volume" form="short" plural="true"/>
+      </group>
+      <group delimiter=" ">
+        <text term="issue" form="short"/>
+        <number variable="issue" form="numeric"/>
+      </group>
+    </group>
+  </macro>
+  <macro name="title">
+    <choose>
+      <if type="bill book graphic legal_case legislation motion_picture song" match="any">
+        <text variable="title" font-style="italic"/>
+      </if>
+      <else>
+        <text variable="title" quotes="true"/>
+      </else>
+    </choose>
+  </macro>
+  <macro name="publisher">
+    <choose>
+      <if type=" bill book chapter graphic legal_case legislation motion_picture paper-conference song" match="any">
+        <group delimiter=": ">
+          <text variable="publisher-place"/>
+          <text variable="publisher"/>
+        </group>
+      </if>
+      <else>
+        <group delimiter=", ">
+          <text variable="publisher"/>
+          <text variable="publisher-place"/>
+        </group>
+      </else>
+    </choose>
+  </macro>
+  <macro name="event">
+    <choose>
+      <if type="paper-conference speech" match="any">
+        <choose>
+          <!-- Published Conference Paper -->
+          <if variable="container-title">
+            <group delimiter=", ">
+              <group delimiter=" ">
+                <text term="in"/>
+                <text variable="container-title" font-style="italic"/>
+              </group>
+              <text variable="event-place"/>
+            </group>
+          </if>
+          <!-- Unpublished Conference Paper -->
+          <else>
+            <group delimiter=", ">
+              <group delimiter=" ">
+                <text term="presented at"/>
+                <text variable="event"/>
+              </group>
+              <text variable="event-place"/>
+            </group>
+          </else>
+        </choose>
+      </if>
+    </choose>
+  </macro>
+  <macro name="access">
+    <choose>
+      <if type="webpage">
+        <choose>
+          <if variable="URL">
+            <group delimiter=". ">
+              <text term="online" prefix="[" suffix="]" text-case="capitalize-first"/>
+              <group delimiter=": ">
+                <text term="available at" text-case="capitalize-first"/>
+                <text variable="URL"/>
+              </group>
+              <group prefix="[" suffix="]" delimiter=": ">
+                <text term="accessed" text-case="capitalize-first"/>
+                <date variable="accessed">
+                  <date-part name="day" form="numeric-leading-zeros" suffix="-"/>
+                  <date-part name="month" form="short" suffix="-" strip-periods="true"/>
+                  <date-part name="year" form="long"/>
+                </date>
+              </group>
+            </group>
+          </if>
+        </choose>
+      </if>
+    </choose>
+  </macro>
+  <macro name="page">
+    <group>
+      <label variable="page" form="short" suffix=" "/>
+      <text variable="page"/>
+    </group>
+  </macro>
+  <macro name="citation-locator">
+    <group delimiter=" ">
+      <choose>
+        <if locator="page">
+          <label variable="locator" form="short"/>
+        </if>
+        <else>
+          <label variable="locator" form="short" text-case="capitalize-first"/>
+        </else>
+      </choose>
+      <text variable="locator"/>
+    </group>
+  </macro>
+  <!-- Citation -->
+  <citation collapse="citation-number">
+    <sort>
+      <key variable="citation-number"/>
+    </sort>
+    <layout delimiter=", ">
+      <group prefix="[" suffix="]" delimiter=", ">
+        <text variable="citation-number"/>
+        <text macro="citation-locator"/>
+      </group>
+    </layout>
+  </citation>
+  <!-- Bibliography -->
+  <bibliography entry-spacing="0" second-field-align="flush">
+    <layout suffix=".">
+      <!-- Citation Number -->
+      <text variable="citation-number" prefix="[" suffix="]"/>
+      <!-- Author(s) -->
+      <text macro="author" suffix=", "/>
+      <!-- Rest of Citation -->
+      <choose>
+        <!-- Specific Formats -->
+        <if type="article-journal">
+          <group delimiter=", ">
+            <text macro="title"/>
+            <text variable="container-title" font-style="italic" form="short"/>
+            <text macro="locators"/>
+            <text macro="page"/>
+            <text macro="issued"/>
+          </group>
+        </if>
+        <else-if type="paper-conference speech" match="any">
+          <group delimiter=", ">
+            <text macro="title"/>
+            <text macro="event"/>
+            <text macro="issued"/>
+            <text macro="locators"/>
+            <text macro="page"/>
+          </group>
+        </else-if>
+        <else-if type="report">
+          <group delimiter=", ">
+            <text macro="title"/>
+            <text macro="publisher"/>
+            <group delimiter=" ">
+              <text variable="genre"/>
+              <text variable="number"/>
+            </group>
+            <text macro="issued"/>
+          </group>
+        </else-if>
+        <else-if type="thesis">
+          <group delimiter=", ">
+            <text macro="title"/>
+            <text variable="genre"/>
+            <text macro="publisher"/>
+            <text macro="issued"/>
+          </group>
+        </else-if>
+        <else-if type="webpage post-weblog" match="any">
+          <group delimiter=", " suffix=". ">
+            <text macro="title"/>
+            <text variable="container-title" font-style="italic"/>
+            <text macro="issued"/>
+          </group>
+          <text macro="access"/>
+        </else-if>
+        <else-if type="patent">
+          <group delimiter=", ">
+            <text macro="title"/>
+            <text variable="number"/>
+            <text macro="issued"/>
+          </group>
+        </else-if>
+        <!-- Generic/Fallback Formats -->
+        <else-if type="bill book graphic legal_case legislation motion_picture report song" match="any">
+          <group delimiter=", " suffix=". ">
+            <text macro="title"/>
+            <text macro="locators"/>
+          </group>
+          <group delimiter=", ">
+            <text macro="publisher"/>
+            <text macro="issued"/>
+            <text macro="page"/>
+          </group>
+        </else-if>
+        <else-if type="article-magazine article-newspaper broadcast interview manuscript map patent personal_communication song speech thesis webpage" match="any">
+          <group delimiter=", ">
+            <text macro="title"/>
+            <text variable="container-title" font-style="italic"/>
+            <text macro="locators"/>
+            <text macro="publisher"/>
+            <text macro="page"/>
+            <text macro="issued"/>
+          </group>
+        </else-if>
+        <else-if type="chapter paper-conference" match="any">
+          <group delimiter=", " suffix=", ">
+            <text macro="title"/>
+            <group delimiter=" ">
+              <text term="in"/>
+              <text variable="container-title" font-style="italic"/>
+            </group>
+            <text macro="locators"/>
+          </group>
+          <text macro="editor" suffix=" "/>
+          <group delimiter=", ">
+            <text macro="publisher"/>
+            <text macro="issued"/>
+            <text macro="page"/>
+          </group>
+        </else-if>
+        <else>
+          <group delimiter=", " suffix=". ">
+            <text macro="title"/>
+            <text variable="container-title" font-style="italic"/>
+            <text macro="locators"/>
+          </group>
+          <group delimiter=", ">
+            <text macro="publisher"/>
+            <text macro="page"/>
+            <text macro="issued"/>
+          </group>
+        </else>
+      </choose>
+    </layout>
+  </bibliography>
+</style>
diff --git a/test/command/ifstrequal.md b/test/command/ifstrequal.md
--- a/test/command/ifstrequal.md
+++ b/test/command/ifstrequal.md
@@ -5,6 +5,12 @@
 \h{a}
 \h{b}
 ^D
-[Para [Emph [Str "no"]]
-,Para [Str "\225",SoftBreak,Str "b"]]
+[ Para
+    [ Emph [ Str "no" ]
+    , SoftBreak
+    , Str "\225"
+    , SoftBreak
+    , Str "b"
+    ]
+]
 ```
diff --git a/test/command/indented-fences.md b/test/command/indented-fences.md
--- a/test/command/indented-fences.md
+++ b/test/command/indented-fences.md
@@ -5,7 +5,7 @@
 in y
    ```
 ^D
-[CodeBlock ("",["haskell"],[]) "let x = y\nin y"]
+[ CodeBlock ( "" , [ "haskell" ] , [] ) "let x = y\nin y" ]
 `````
 `````
 % pandoc -t native
@@ -16,5 +16,7 @@
  y
 ~~~
 ^D
-[CodeBlock ("",["haskell"],[]) " let x = y\nin y +\ny +\ny"]
+[ CodeBlock
+    ( "" , [ "haskell" ] , [] ) " let x = y\nin y +\ny +\ny"
+]
 `````
diff --git a/test/command/input-with-endinput.md b/test/command/input-with-endinput.md
new file mode 100644
--- /dev/null
+++ b/test/command/input-with-endinput.md
@@ -0,0 +1,15 @@
+```
+% pandoc --from=latex -t native
+\begin{document}
+Visible
+
+\include{command/bar-endinput}
+
+Visible
+\end{document}
+^D
+[ Para [ Str "Visible" ]
+, Para [ Emph [ Str "hi" , Space , Str "there" ] ]
+, Para [ Str "Visible" ]
+]
+```
diff --git a/test/command/issue160.csl b/test/command/issue160.csl
new file mode 100644
--- /dev/null
+++ b/test/command/issue160.csl
@@ -0,0 +1,28 @@
+<?xml version="1.0" encoding="utf-8"?>
+<style xmlns="http://purl.org/net/xbiblio/csl" class="in-text" version="1.0" default-locale="en-US">
+  <info>
+    <title>Issue 160 Test Style</title>
+    <id>issue-160-test</id>
+    <category citation-format="label"/>
+    <updated>2017-02-04T19:31:46+0000</updated>
+  </info>
+  <citation>
+    <layout prefix="[" suffix="]" delimiter=",">
+      <text variable="citation-label"/>
+    </layout>
+  </citation>
+  <bibliography>
+    <layout>
+      <text variable="citation-label" prefix="[" suffix="] "/>
+      <group delimiter=". " suffix=".">
+        <names variable="author">
+          <name delimiter=", " delimiter-precedes-last="always"/>
+        </names>
+        <text variable="title"/>
+        <date variable="issued">
+          <date-part name="year"/>
+        </date>
+      </group>
+    </layout>
+  </bibliography>
+</style>
diff --git a/test/command/issue437.csl b/test/command/issue437.csl
new file mode 100644
--- /dev/null
+++ b/test/command/issue437.csl
@@ -0,0 +1,26 @@
+<?xml version="1.0" encoding="utf-8"?>
+<style xmlns="http://purl.org/net/xbiblio/csl" class="note" default-locale="en-US" version="1.0">
+  <info>
+    <title>Minimal style to reproduce bug</title>
+    <id>http://www.example.org/styles/minimal-test-style</id>
+    <author>
+      <name>Nicolas Chachereau</name>
+      <email>nicolas@nchachereau.ch</email>
+    </author>
+    <updated>2020-01-27T14:27:45+01:00</updated>
+  </info>
+  <citation>
+    <layout>
+      <group delimiter=", ">
+        <names variable="author"/>
+        <text variable="title"/>
+        <text variable="publisher-place"/>
+        <date variable="issued" form="numeric" date-parts="year"/>
+        <group delimiter="&#160;">
+          <number variable="number-of-pages"/>
+          <label variable="number-of-pages"/>
+        </group>
+      </group>
+    </layout>
+  </citation>
+</style>
diff --git a/test/command/issue58.csl b/test/command/issue58.csl
new file mode 100644
--- /dev/null
+++ b/test/command/issue58.csl
@@ -0,0 +1,553 @@
+<?xml version="1.0" encoding="utf-8"?>
+<style xmlns="http://purl.org/net/xbiblio/csl" class="in-text" version="1.0" demote-non-dropping-particle="never" page-range-format="chicago">
+  <info>
+    <title>Chicago Manual of Style 16th edition (author-date) modif 2014-06-30</title>
+    <id></id>
+    <link href="" rel="self"/>
+    <link href="http://www.chicagomanualofstyle.org/tools_citationguide.html" rel="documentation"/>
+    <author>
+      <name>Julian Onions</name>
+      <email>julian.onions@gmail.com</email>
+    </author>
+    <contributor>
+      <name>Sebastian Karcher</name>
+    </contributor>
+    <contributor>
+      <name>Richard Karnesky</name>
+      <email>karnesky+zotero@gmail.com</email>
+      <uri>http://arc.nucapt.northwestern.edu/Richard_Karnesky</uri>
+    </contributor>
+    <contributor>
+      <name>Andrew Dunning</name>
+      <email>andrew.dunning@utoronto.ca</email>
+    </contributor>
+    <category citation-format="author-date"/>
+    <category field="generic-base"/>
+    <summary>The author-date variant of the Chicago style</summary>
+    <updated>2014-05-23T03:53:32+00:00</updated>
+    <rights license="http://creativecommons.org/licenses/by-sa/3.0/">This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 License</rights>
+  </info>
+  <locale xml:lang="en">
+    <terms>
+      <term name="editor" form="verb-short">ed.</term>
+      <term name="container-author" form="verb">by</term>
+      <term name="translator" form="verb-short">trans.</term>
+      <term name="editortranslator" form="verb">
+        <single>edited and translated by</single>
+        <multiple>edited and translated by</multiple>
+      </term>
+      <term name="translator" form="short">trans.</term>
+    </terms>
+  </locale>
+  <macro name="secondary-contributors">
+    <choose>
+      <if type="chapter paper-conference" match="none">
+        <names variable="editor translator" delimiter=". ">
+          <label form="verb" text-case="capitalize-first" suffix=" "/>
+          <name and="text" delimiter=", "/>
+        </names>
+      </if>
+    </choose>
+  </macro>
+  <macro name="container-contributors">
+    <choose>
+      <if type="chapter paper-conference" match="any">
+        <group prefix=", " delimiter=", ">
+          <names variable="container-author" delimiter=", ">
+            <label form="verb" suffix=" "/>
+            <name and="text" delimiter=", "/>
+          </names>
+          <names variable="editor translator" delimiter=", ">
+            <label form="verb" suffix=" "/>
+            <name and="text" delimiter=", "/>
+          </names>
+        </group>
+      </if>
+    </choose>
+  </macro>
+  <macro name="editor">
+    <names variable="editor">
+      <name name-as-sort-order="first" and="text" sort-separator=", " delimiter=", " delimiter-precedes-last="always"/>
+      <label form="short" prefix=", "/>
+    </names>
+  </macro>
+  <macro name="translator">
+    <names variable="translator">
+      <name name-as-sort-order="first" and="text" sort-separator=", " delimiter=", " delimiter-precedes-last="always"/>
+      <label form="short" prefix=", "/>
+    </names>
+  </macro>
+  <macro name="recipient">
+    <choose>
+      <if type="personal_communication">
+        <choose>
+          <if variable="genre">
+            <text variable="genre" text-case="capitalize-first"/>
+          </if>
+          <else>
+            <text term="letter" text-case="capitalize-first"/>
+          </else>
+        </choose>
+      </if>
+    </choose>
+    <names variable="recipient" delimiter=", ">
+      <label form="verb" prefix=" " text-case="lowercase" suffix=" "/>
+      <name and="text" delimiter=", "/>
+    </names>
+  </macro>
+  <macro name="noauthor-container-title">
+    <choose>
+      <if variable="container-title">
+        <choose>
+          <if type="article-journal article-magazine article-newspaper" match="any">
+            <text macro="container-title"/>
+          </if>
+        </choose>
+      </if>
+    </choose>
+  </macro>
+  <macro name="contributors">
+    <group delimiter=". ">
+      <names variable="author">
+        <name and="text" name-as-sort-order="first" sort-separator=", " delimiter=", " delimiter-precedes-last="always"/>
+        <label form="short" prefix=", "/>
+        <substitute>
+          <names variable="editor"/>
+          <names variable="translator"/>
+          <text macro="noauthor-container-title"/>
+          <text macro="title"/>
+        </substitute>
+      </names>
+      <text macro="recipient"/>
+    </group>
+  </macro>
+  <macro name="contributors-short">
+    <names variable="author">
+      <name form="short" and="text" delimiter=", " initialize-with=". "/>
+      <substitute>
+        <names variable="editor"/>
+        <names variable="translator"/>
+        <text macro="noauthor-container-title"/>
+        <text macro="title"/>
+      </substitute>
+    </names>
+  </macro>
+  <macro name="interviewer">
+    <names variable="interviewer" delimiter=", ">
+      <label form="verb" prefix=" " text-case="capitalize-first" suffix=" "/>
+      <name and="text" delimiter=", "/>
+    </names>
+  </macro>
+  <macro name="archive">
+    <group delimiter=". ">
+      <text variable="archive_location" text-case="capitalize-first"/>
+      <text variable="archive"/>
+      <text variable="archive-place"/>
+    </group>
+  </macro>
+  <macro name="access">
+    <group delimiter=". ">
+      <choose>
+        <if type="graphic report" match="any">
+          <text macro="archive"/>
+        </if>
+        <else-if type="article-journal bill book chapter legal_case legislation motion_picture paper-conference" match="none">
+          <text macro="archive"/>
+        </else-if>
+      </choose>
+      <choose>
+        <if variable="issued" match="none">
+          <group delimiter=" ">
+            <text term="accessed" text-case="capitalize-first"/>
+            <date variable="accessed" delimiter=" ">
+              <date-part name="month"/>
+              <date-part name="day"/>
+            </date>
+          </group>
+        </if>
+      </choose>
+      <choose>
+        <if type="legal_case" match="none">
+          <choose>
+            <if variable="DOI">
+              <text variable="DOI" prefix="doi:"/>
+            </if>
+            <else>
+              <text variable="URL"/>
+            </else>
+          </choose>
+        </if>
+      </choose>
+    </group>
+  </macro>
+  <macro name="title">
+    <choose>
+      <if variable="title" match="none">
+        <choose>
+          <if type="personal_communication" match="none">
+            <text variable="genre" text-case="capitalize-first"/>
+          </if>
+        </choose>
+      </if>
+      <else-if type="bill book graphic legislation motion_picture report song" match="any">
+        <text variable="title" text-case="title" font-style="italic"/>
+        <group prefix=" (" suffix=")" delimiter=" ">
+          <text term="version"/>
+          <text variable="version"/>
+        </group>
+      </else-if>
+      <else-if variable="reviewed-author">
+        <group delimiter=", ">
+          <text variable="title" font-style="italic" prefix="Review of "/>
+          <names variable="reviewed-author">
+            <label form="verb-short" text-case="lowercase" suffix=" "/>
+            <name and="text" delimiter=", "/>
+          </names>
+        </group>
+      </else-if>
+      <else-if type="legal_case interview" match="any">
+        <text variable="title"/>
+      </else-if>
+      <else>
+        <text variable="title" text-case="title" quotes="true"/>
+      </else>
+    </choose>
+  </macro>
+  <macro name="edition">
+    <choose>
+      <if type="bill book graphic legal_case legislation motion_picture report song" match="any">
+        <choose>
+          <if is-numeric="edition">
+            <group delimiter=" " prefix=". ">
+              <number variable="edition" form="ordinal"/>
+              <text term="edition" form="short" strip-periods="true"/>
+            </group>
+          </if>
+          <else>
+            <text variable="edition" prefix=". "/>
+          </else>
+        </choose>
+      </if>
+      <else-if type="chapter  paper-conference" match="any">
+        <choose>
+          <if is-numeric="edition">
+            <group delimiter=" " prefix=", ">
+              <number variable="edition" form="ordinal"/>
+              <text term="edition" form="short"/>
+            </group>
+          </if>
+          <else>
+            <text variable="edition" prefix=", "/>
+          </else>
+        </choose>
+      </else-if>
+    </choose>
+  </macro>
+  <macro name="locators">
+    <choose>
+      <if type="article-journal">
+        <choose>
+          <if variable="volume">
+            <text variable="volume" prefix=" "/>
+            <group prefix=" (" suffix=")">
+              <choose>
+                <if variable="issue">
+                  <text variable="issue"/>
+                </if>
+                <else>
+                  <date variable="issued">
+                    <date-part name="month"/>
+                  </date>
+                </else>
+              </choose>
+            </group>
+          </if>
+          <else-if variable="issue">
+            <group delimiter=" " prefix=", ">
+              <text term="issue" form="short"/>
+              <text variable="issue"/>
+              <date variable="issued" prefix="(" suffix=")">
+                <date-part name="month"/>
+              </date>
+            </group>
+          </else-if>
+          <else>
+            <date variable="issued" prefix=", ">
+              <date-part name="month"/>
+            </date>
+          </else>
+        </choose>
+      </if>
+      <else-if type="legal_case">
+        <text variable="volume" prefix=", "/>
+        <text variable="container-title" prefix=" "/>
+        <text variable="page" prefix=" "/>
+      </else-if>
+      <else-if type="bill book graphic legal_case legislation motion_picture report song" match="any">
+        <group prefix=". " delimiter=". ">
+          <group>
+            <text term="volume" form="short" text-case="capitalize-first" suffix=" "/>
+            <number variable="volume" form="numeric"/>
+          </group>
+          <group>
+            <number variable="number-of-volumes" form="numeric"/>
+            <text term="volume" form="short" prefix=" " plural="true"/>
+          </group>
+        </group>
+      </else-if>
+      <else-if type="chapter paper-conference" match="any">
+        <choose>
+          <if variable="page" match="none">
+            <group prefix=". ">
+              <text term="volume" form="short" text-case="capitalize-first" suffix=" "/>
+              <number variable="volume" form="numeric"/>
+            </group>
+          </if>
+        </choose>
+      </else-if>
+    </choose>
+  </macro>
+  <macro name="locators-chapter">
+    <choose>
+      <if type="chapter paper-conference" match="any">
+        <choose>
+          <if variable="page">
+            <group prefix=", ">
+              <text variable="volume" suffix=":"/>
+              <text variable="page"/>
+            </group>
+          </if>
+        </choose>
+      </if>
+    </choose>
+  </macro>
+  <macro name="locators-article">
+    <choose>
+      <if type="article-newspaper">
+        <group prefix=", " delimiter=", ">
+          <group>
+            <text variable="edition" suffix=" "/>
+            <text term="edition" prefix=" "/>
+          </group>
+          <group>
+            <text term="section" form="short" suffix=" "/>
+            <text variable="section"/>
+          </group>
+        </group>
+      </if>
+      <else-if type="article-journal">
+        <choose>
+          <if variable="volume issue" match="any">
+            <text variable="page" prefix=": "/>
+          </if>
+          <else>
+            <text variable="page" prefix=", "/>
+          </else>
+        </choose>
+      </else-if>
+    </choose>
+  </macro>
+  <macro name="point-locators">
+    <choose>
+      <if variable="locator">
+        <choose>
+          <if locator="page" match="none">
+            <choose>
+              <if type="bill book graphic legal_case legislation motion_picture report song" match="any">
+                <choose>
+                  <if variable="volume">
+                    <group>
+                      <text term="volume" form="short" suffix=" "/>
+                      <number variable="volume" form="numeric"/>
+                      <label variable="locator" form="short" prefix=", " suffix=" "/>
+                    </group>
+                  </if>
+                  <else>
+                    <label variable="locator" form="short" suffix=" "/>
+                  </else>
+                </choose>
+              </if>
+              <else>
+                <label variable="locator" form="short" suffix=" "/>
+              </else>
+            </choose>
+          </if>
+          <else-if type="bill book graphic legal_case legislation motion_picture report song" match="any">
+            <number variable="volume" form="numeric" suffix=":"/>
+          </else-if>
+        </choose>
+        <text variable="locator"/>
+      </if>
+    </choose>
+  </macro>
+  <macro name="container-prefix">
+    <text term="in" text-case="capitalize-first"/>
+  </macro>
+  <macro name="container-title">
+    <choose>
+      <if type="chapter paper-conference" match="any">
+        <text macro="container-prefix" suffix=" "/>
+      </if>
+    </choose>
+    <choose>
+      <if type="legal_case" match="none">
+        <text variable="container-title" text-case="title" font-style="italic"/>
+      </if>
+    </choose>
+  </macro>
+  <macro name="publisher">
+    <group delimiter=": ">
+      <text variable="publisher-place"/>
+      <text variable="publisher"/>
+    </group>
+  </macro>
+  <macro name="date">
+    <choose>
+      <if variable="issued">
+        <date variable="issued">
+          <date-part name="year"/>
+        </date>
+      </if>
+      <else-if variable="accessed">
+        <date variable="accessed">
+          <date-part name="year"/>
+        </date>
+      </else-if>
+    </choose>
+  </macro>
+  <macro name="day-month">
+    <date variable="issued">
+      <date-part name="month"/>
+      <date-part name="day" prefix=" "/>
+    </date>
+  </macro>
+  <macro name="collection-title">
+    <choose>
+      <if match="none" type="article-journal">
+        <choose>
+          <if match="none" is-numeric="collection-number">
+            <group delimiter=", ">
+              <text variable="collection-title" text-case="title"/>
+              <text variable="collection-number"/>
+            </group>
+          </if>
+          <else>
+            <group delimiter=" ">
+              <text variable="collection-title" text-case="title"/>
+              <text variable="collection-number"/>
+            </group>
+          </else>
+        </choose>
+      </if>
+    </choose>
+  </macro>
+  <macro name="collection-title-journal">
+    <choose>
+      <if type="article-journal">
+        <group delimiter=" ">
+          <text variable="collection-title"/>
+          <text variable="collection-number"/>
+        </group>
+      </if>
+    </choose>
+  </macro>
+  <macro name="event">
+    <group>
+      <text term="presented at" suffix=" "/>
+      <text variable="event"/>
+    </group>
+  </macro>
+  <macro name="description">
+    <choose>
+      <if type="interview">
+        <group delimiter=". ">
+          <text macro="interviewer"/>
+          <text variable="medium" text-case="capitalize-first"/>
+        </group>
+      </if>
+      <else>
+        <text variable="medium" text-case="capitalize-first" prefix=". "/>
+      </else>
+    </choose>
+    <choose>
+      <if variable="title" match="none"/>
+      <else-if type="thesis personal_communication speech" match="any"/>
+      <else>
+        <group delimiter=" " prefix=". ">
+          <text variable="genre" text-case="capitalize-first"/>
+          <choose>
+            <if type="report">
+              <text variable="number"/>
+            </if>
+          </choose>
+        </group>
+      </else>
+    </choose>
+  </macro>
+  <macro name="issue">
+    <choose>
+      <if type="legal_case">
+        <text variable="authority" prefix=". "/>
+      </if>
+      <else-if type="speech">
+        <group prefix=". " delimiter=", ">
+          <group delimiter=" ">
+            <text variable="genre" text-case="capitalize-first"/>
+            <text macro="event"/>
+          </group>
+          <text variable="event-place"/>
+          <text macro="day-month"/>
+        </group>
+      </else-if>
+      <else-if type="article-newspaper article-magazine personal_communication" match="any">
+        <text macro="day-month" prefix=", "/>
+      </else-if>
+      <else>
+        <group prefix=". " delimiter=", ">
+          <choose>
+            <if type="thesis">
+              <text variable="genre" text-case="capitalize-first"/>
+            </if>
+          </choose>
+          <text macro="publisher"/>
+        </group>
+      </else>
+    </choose>
+  </macro>
+  <citation et-al-min="4" et-al-use-first="1" disambiguate-add-year-suffix="true" disambiguate-add-names="true" disambiguate-add-givenname="true" givenname-disambiguation-rule="primary-name">
+    <layout prefix="(" suffix=")" delimiter="; ">
+      <group delimiter=", ">
+        <group delimiter=" ">
+          <text macro="contributors-short"/>
+          <text macro="date"/>
+        </group>
+        <text macro="point-locators"/>
+      </group>
+    </layout>
+  </citation>
+  <bibliography hanging-indent="true" et-al-min="11" et-al-use-first="7" subsequent-author-substitute="&#8212;&#8212;&#8212;" entry-spacing="0">
+    <sort>
+      <key macro="contributors"/>
+      <key variable="issued"/>
+    </sort>
+    <layout suffix=".">
+      <group delimiter=". ">
+        <text macro="contributors"/>
+        <text macro="date"/>
+        <text macro="title"/>
+      </group>
+      <text macro="description"/>
+      <text macro="secondary-contributors" prefix=". "/>
+      <text macro="container-title" prefix=". "/>
+      <text macro="container-contributors"/>
+      <text macro="edition"/>
+      <text macro="locators-chapter"/>
+      <text macro="collection-title-journal" prefix=", " suffix=", "/>
+      <text macro="locators"/>
+      <text macro="collection-title" prefix=". "/>
+      <text macro="issue"/>
+      <text macro="locators-article"/>
+      <text macro="access" prefix=". "/>
+    </layout>
+  </bibliography>
+</style>
diff --git a/test/command/jabberwocky.md b/test/command/jabberwocky.md
new file mode 100644
--- /dev/null
+++ b/test/command/jabberwocky.md
@@ -0,0 +1,22 @@
+```
+% pandoc -t plain -f markdown
+| 'Twas brillig, and the slithy toves
+|       Did gyre and gimble in the wabe:
+| All mimsy were the borogoves,
+|       And the mome raths outgrabe.
+|
+| "Beware the Jabberwock, my son!
+|       The jaws that bite, the claws that catch!
+| Beware the Jubjub bird, and shun
+|       The frumious Bandersnatch!"
+^D
+’Twas brillig, and the slithy toves
+      Did gyre and gimble in the wabe:
+All mimsy were the borogoves,
+      And the mome raths outgrabe.
+
+“Beware the Jabberwock, my son!
+      The jaws that bite, the claws that catch!
+Beware the Jubjub bird, and shun
+      The frumious Bandersnatch!”
+```
diff --git a/test/command/jats-figure-alt-text.md b/test/command/jats-figure-alt-text.md
new file mode 100644
--- /dev/null
+++ b/test/command/jats-figure-alt-text.md
@@ -0,0 +1,22 @@
+```
+% pandoc -f jats -t native
+<fig id="fig-1">
+  <caption>
+    <p>bar</p>
+  </caption>
+  <alt-text>alternative-decription</alt-text>
+  <graphic xlink:href="foo.png">
+    <alt-text>baz</alt-text> 
+  </graphic>
+</fig>
+
+^D
+[ Figure
+    ( "fig-1" , [] , [] )
+    (Caption Nothing [ Plain [ Str "bar" ] ])
+    [ Plain [ Str "alternative-decription" ]
+    , Para
+        [ Image ( "" , [] , [] ) [ Str "baz" ] ( "foo.png" , "" ) ]
+    ]
+]
+```
diff --git a/test/command/latex-center.md b/test/command/latex-center.md
new file mode 100644
--- /dev/null
+++ b/test/command/latex-center.md
@@ -0,0 +1,12 @@
+# `\begin{center}`
+
+```
+% pandoc -f latex -t native
+\begin{center}
+Hello
+\end{center}
+
+^D
+[ Div ( "" , [ "center" ] , [] ) [ Para [ Str "Hello" ] ] ]
+```
+
diff --git a/test/command/latex-color.md b/test/command/latex-color.md
--- a/test/command/latex-color.md
+++ b/test/command/latex-color.md
@@ -4,21 +4,40 @@
 % pandoc -f latex -t native
 Hello \textcolor{red}{World}
 ^D
-[Para [Str "Hello",Space,Span ("",[],[("style","color: red")]) [Str "World"]]]
+[ Para
+    [ Str "Hello"
+    , Space
+    , Span
+        ( "" , [] , [ ( "style" , "color: red" ) ] ) [ Str "World" ]
+    ]
+]
 ```
 
 ```
 % pandoc -f latex -t native
 \textcolor{red}{Hello} World
 ^D
-[Para [Span ("",[],[("style","color: red")]) [Str "Hello"],Space,Str "World"]]
+[ Para
+    [ Span
+        ( "" , [] , [ ( "style" , "color: red" ) ] ) [ Str "Hello" ]
+    , Space
+    , Str "World"
+    ]
+]
 ```
 
 ```
 % pandoc -f latex -t native
 Hello \textcolor{blue}{\textbf{World}}
 ^D
-[Para [Str "Hello",Space,Span ("",[],[("style","color: blue")]) [Strong [Str "World"]]]]
+[ Para
+    [ Str "Hello"
+    , Space
+    , Span
+        ( "" , [] , [ ( "style" , "color: blue" ) ] )
+        [ Strong [ Str "World" ] ]
+    ]
+]
 ```
 
 
@@ -26,7 +45,15 @@
 % pandoc -f latex -t native
 Hello \textcolor{blue}{\textbf{World}}.
 ^D
-[Para [Str "Hello",Space,Span ("",[],[("style","color: blue")]) [Strong [Str "World"]],Str "."]]
+[ Para
+    [ Str "Hello"
+    , Space
+    , Span
+        ( "" , [] , [ ( "style" , "color: blue" ) ] )
+        [ Strong [ Str "World" ] ]
+    , Str "."
+    ]
+]
 ```
 
 ```
@@ -38,10 +65,14 @@
 \end{itemize}
 }
 ^D
-[Div ("",[],[("style","color: orange")])
- [BulletList
-  [[Para [Str "Item",Space,Str "1"]]
-  ,[Para [Str "Item",Space,Str "2"]]]]]
+[ Div
+    ( "" , [] , [ ( "style" , "color: orange" ) ] )
+    [ BulletList
+        [ [ Para [ Str "Item" , Space , Str "1" ] ]
+        , [ Para [ Str "Item" , Space , Str "2" ] ]
+        ]
+    ]
+]
 ```
 
 ```
@@ -53,11 +84,16 @@
 \end{itemize}
 } some more text
 ^D
-[Div ("",[],[("style","color: blue")])
- [BulletList
-  [[Para [Str "Item",Space,Str "1"]]
-  ,[Para [Str "Item",Space,Str "2"]]]]
-,Para [Str "some",Space,Str "more",Space,Str "text"]]
+[ Div
+    ( "" , [] , [ ( "style" , "color: blue" ) ] )
+    [ BulletList
+        [ [ Para [ Str "Item" , Space , Str "1" ] ]
+        , [ Para [ Str "Item" , Space , Str "2" ] ]
+        ]
+    ]
+, Para
+    [ Str "some" , Space , Str "more" , Space , Str "text" ]
+]
 ```
 
 # `\colorbox{}{}`
@@ -67,28 +103,57 @@
 % pandoc -f latex -t native
 Hello \colorbox{red}{World}
 ^D
-[Para [Str "Hello",Space,Span ("",[],[("style","background-color: red")]) [Str "World"]]]
+[ Para
+    [ Str "Hello"
+    , Space
+    , Span
+        ( "" , [] , [ ( "style" , "background-color: red" ) ] )
+        [ Str "World" ]
+    ]
+]
 ```
 
 ```
 % pandoc -f latex -t native
 \colorbox{red}{Hello} World
 ^D
-[Para [Span ("",[],[("style","background-color: red")]) [Str "Hello"],Space,Str "World"]]
+[ Para
+    [ Span
+        ( "" , [] , [ ( "style" , "background-color: red" ) ] )
+        [ Str "Hello" ]
+    , Space
+    , Str "World"
+    ]
+]
 ```
 
 ```
 % pandoc -f latex -t native
 Hello \colorbox{blue}{\textbf{World}}
 ^D
-[Para [Str "Hello",Space,Span ("",[],[("style","background-color: blue")]) [Strong [Str "World"]]]]
+[ Para
+    [ Str "Hello"
+    , Space
+    , Span
+        ( "" , [] , [ ( "style" , "background-color: blue" ) ] )
+        [ Strong [ Str "World" ] ]
+    ]
+]
 ```
 
 ```
 % pandoc -f latex -t native
 Hello \colorbox{blue}{\textbf{World}}.
 ^D
-[Para [Str "Hello",Space,Span ("",[],[("style","background-color: blue")]) [Strong [Str "World"]],Str "."]]
+[ Para
+    [ Str "Hello"
+    , Space
+    , Span
+        ( "" , [] , [ ( "style" , "background-color: blue" ) ] )
+        [ Strong [ Str "World" ] ]
+    , Str "."
+    ]
+]
 ```
 
 ```
@@ -102,10 +167,17 @@
 \end{minipage}
 }
 ^D
-[Div ("",[],[("style","background-color: orange")])
- [BulletList
-  [[Para [Str "Item",Space,Str "1"]]
-  ,[Para [Str "Item",Space,Str "2"]]]]]
+[ Div
+    ( "" , [] , [ ( "style" , "background-color: orange" ) ] )
+    [ Div
+        ( "" , [ "minipage" ] , [] )
+        [ BulletList
+            [ [ Para [ Str "Item" , Space , Str "1" ] ]
+            , [ Para [ Str "Item" , Space , Str "2" ] ]
+            ]
+        ]
+    ]
+]
 ```
 
 ```
@@ -119,9 +191,17 @@
 \end{minipage}
 } some more text
 ^D
-[Div ("",[],[("style","background-color: blue")])
- [BulletList
-  [[Para [Str "Item",Space,Str "1"]]
-  ,[Para [Str "Item",Space,Str "2"]]]]
-,Para [Str "some",Space,Str "more",Space,Str "text"]]
+[ Div
+    ( "" , [] , [ ( "style" , "background-color: blue" ) ] )
+    [ Div
+        ( "" , [ "minipage" ] , [] )
+        [ BulletList
+            [ [ Para [ Str "Item" , Space , Str "1" ] ]
+            , [ Para [ Str "Item" , Space , Str "2" ] ]
+            ]
+        ]
+    ]
+, Para
+    [ Str "some" , Space , Str "more" , Space , Str "text" ]
+]
 ```
diff --git a/test/command/latex-command-comment.md b/test/command/latex-command-comment.md
--- a/test/command/latex-command-comment.md
+++ b/test/command/latex-command-comment.md
@@ -1,7 +1,7 @@
 ```
-pandoc -f latex -t native
+% pandoc -f latex -t native
 \emph%
 {hi}
 ^D
-[Para [Emph [Str "hi"]]]
+[ Para [ Emph [ Str "hi" ] ] ]
 ```
diff --git a/test/command/latex-fontawesome.md b/test/command/latex-fontawesome.md
--- a/test/command/latex-fontawesome.md
+++ b/test/command/latex-fontawesome.md
@@ -2,12 +2,12 @@
 % pandoc -f latex -t native
 Check: \faCheck
 ^D
-[Para [Str "Check:",Space,Str "\10003"]]
+[ Para [ Str "Check:" , Space , Str "\10003" ] ]
 ```
 
 ```
 % pandoc -f latex -t native
 Close: \faClose
 ^D
-[Para [Str "Close:",Space,Str "\10007"]]
+[ Para [ Str "Close:" , Space , Str "\10007" ] ]
 ```
diff --git a/test/command/latex-math-trailing-space.md b/test/command/latex-math-trailing-space.md
new file mode 100644
--- /dev/null
+++ b/test/command/latex-math-trailing-space.md
@@ -0,0 +1,38 @@
+Test that trailing spaces before \end{equation} don't create spurious paragraph breaks:
+
+```
+% pandoc -f latex -t latex
+\begin{equation}
+  a
+ \end{equation}
+^D
+\begin{equation}
+  a
+\end{equation}
+```
+
+Same for align environment:
+
+```
+% pandoc -f latex -t latex
+\begin{align}
+  x &= y \\
+ \end{align}
+^D
+\begin{align}
+  x &= y \\
+\end{align}
+```
+
+Test with multiple trailing spaces:
+
+```
+% pandoc -f latex -t latex
+\begin{equation}
+  a + b
+   \end{equation}
+^D
+\begin{equation}
+  a + b
+\end{equation}
+```
diff --git a/test/command/latex-tabular-column-specs.md b/test/command/latex-tabular-column-specs.md
--- a/test/command/latex-tabular-column-specs.md
+++ b/test/command/latex-tabular-column-specs.md
@@ -11,14 +11,85 @@
 \bottomrule
 \end{tabular}
 ^D
-[Table [] [AlignLeft,AlignLeft,AlignLeft] [0.0,0.0,0.0]
- [[Plain [Math InlineMath ""]]
- ,[Plain [Math InlineMath "f1"]]
- ,[Plain [Math InlineMath "f2"]]]
- [[[Plain [Math InlineMath "e"]]
-  ,[Plain [Math InlineMath "0.5"]]
-  ,[Plain [Math InlineMath "4"]]]
- ,[[Plain [Math InlineMath "f"]]
-  ,[Plain [Math InlineMath "0.5"]]
-  ,[Plain [Math InlineMath "5,5"]]]]]
+[ Table
+    ( "" , [] , [] )
+    (Caption Nothing [])
+    [ ( AlignLeft , ColWidthDefault )
+    , ( AlignLeft , ColWidthDefault )
+    , ( AlignLeft , ColWidthDefault )
+    ]
+    (TableHead
+       ( "" , [] , [] )
+       [ Row
+           ( "" , [] , [] )
+           [ Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Math InlineMath "" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Math InlineMath "f1" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Math InlineMath "f2" ] ]
+           ]
+       ])
+    [ TableBody
+        ( "" , [] , [] )
+        (RowHeadColumns 0)
+        []
+        [ Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Math InlineMath "e" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Math InlineMath "0.5" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Math InlineMath "4" ] ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Math InlineMath "f" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Math InlineMath "0.5" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Math InlineMath "5,5" ] ]
+            ]
+        ]
+    ]
+    (TableFoot ( "" , [] , [] ) [])
+]
 ```
diff --git a/test/command/le-tapuscrit-note.csl b/test/command/le-tapuscrit-note.csl
new file mode 100644
--- /dev/null
+++ b/test/command/le-tapuscrit-note.csl
@@ -0,0 +1,496 @@
+<?xml version="1.0" encoding="utf-8"?>
+<style xmlns="http://purl.org/net/xbiblio/csl" class="note" default-locale="fr-FR" version="1.0" page-range-format="expanded">
+  <info>
+    <title>Le tapuscrit (École des hautes études en sciences sociales) (note, French)</title>
+    <title-short>Tapuscrit-EHESS</title-short>
+    <id>http://www.zotero.org/styles/le-tapuscrit-note</id>
+    <link href="http://www.zotero.org/styles/le-tapuscrit-note" rel="self"/>
+    <link href="http://www.editions.ehess.fr/ouvrages/ouvrage/le-tapuscrit/" rel="documentation"/>
+    <author>
+      <name>Franziska Heimburger</name>
+      <email>zotero@franziska.fr</email>
+    </author>
+    <category citation-format="note"/>
+    <category field="social_science"/>
+    <category field="generic-base"/>
+    <updated>2018-07-12T11:20:37+00:00</updated>
+    <rights license="http://creativecommons.org/licenses/by-sa/3.0/">This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 License</rights>
+  </info>
+  <locale xml:lang="fr">
+    <terms>
+      <term name="ordinal-01">ère</term>
+      <term name="ordinal-02">e</term>
+      <term name="ordinal-03">e</term>
+      <term name="ordinal-04">e</term>
+      <term name="cited">op.&#160;cit.</term>
+      <term name="page" form="short">p.</term>
+      <term name="editor" form="short">
+        <single>ed.</single>
+        <multiple>eds.</multiple>
+      </term>
+      <term name="in">dans</term>
+    </terms>
+  </locale>
+  <macro name="author">
+    <choose>
+      <if variable="author">
+        <names variable="author">
+          <name form="long" and="text" delimiter-precedes-last="never" sort-separator=" "/>
+        </names>
+      </if>
+      <else-if variable="editor">
+        <names variable="editor">
+          <name form="long" and="text" delimiter-precedes-last="never" sort-separator=" "/>
+          <label form="short" prefix="&#160;(" suffix=".)"/>
+        </names>
+      </else-if>
+    </choose>
+  </macro>
+  <macro name="author-bib">
+    <choose>
+      <if variable="author">
+        <names variable="author">
+          <name name-as-sort-order="all" form="long" and="text" delimiter-precedes-last="never" sort-separator=" ">
+            <name-part name="family" font-variant="small-caps"/>
+          </name>
+        </names>
+      </if>
+      <else-if variable="editor">
+        <names variable="editor">
+          <name name-as-sort-order="all" form="long" and="text" delimiter-precedes-last="never" sort-separator=" ">
+            <name-part name="family" font-variant="small-caps"/>
+          </name>
+          <label form="short" prefix="&#160;(" suffix=".)"/>
+        </names>
+      </else-if>
+    </choose>
+  </macro>
+  <macro name="author-ibid">
+    <choose>
+      <if variable="author">
+        <names variable="author">
+          <name and="text" initialize="true" initialize-with="." delimiter-precedes-last="never" sort-separator=" " font-style="normal"/>
+        </names>
+      </if>
+      <else-if variable="editor">
+        <names variable="editor">
+          <name form="long" and="text" delimiter-precedes-last="never" sort-separator=" "/>
+          <label form="short" prefix="&#160;(" suffix=".)"/>
+        </names>
+      </else-if>
+    </choose>
+  </macro>
+  <macro name="editor">
+    <names variable="editor">
+      <name form="long" and="text" delimiter-precedes-last="never" sort-separator=" "/>
+      <label form="short" prefix="&#160;(" suffix=".)"/>
+    </names>
+  </macro>
+  <macro name="translator">
+    <names variable="translator">
+      <name form="long" and="text" delimiter-precedes-last="never" sort-separator=" " prefix=" traduit par "/>
+    </names>
+  </macro>
+  <macro name="title">
+    <choose>
+      <if type="bill book graphic legal_case motion_picture report song" match="any">
+        <text variable="title" text-case="capitalize-first" font-style="italic"/>
+      </if>
+      <else-if type="article-journal article-newspaper article-magazine" match="any">
+        <group delimiter=", ">
+          <text variable="title" text-case="capitalize-first" quotes="true"/>
+          <text variable="container-title" font-style="italic"/>
+        </group>
+      </else-if>
+      <else-if type="thesis" match="any">
+        <group delimiter="">
+          <text variable="title" text-case="capitalize-first" font-style="italic" suffix=","/>
+          <text variable="genre" suffix=", " prefix=" "/>
+          <text variable="publisher"/>
+        </group>
+      </else-if>
+      <else-if type="manuscript" match="any">
+        <group delimiter=",">
+          <text variable="title" text-case="capitalize-first" font-style="italic"/>
+          <text variable="genre" prefix=" [" suffix="]"/>
+        </group>
+      </else-if>
+      <else-if type="chapter entry-dictionary entry-encyclopedia" match="any">
+        <group delimiter="">
+          <text variable="title" text-case="capitalize-first" quotes="true"/>
+          <text value="dans" suffix=" " prefix=" "/>
+          <text macro="editor" suffix=", "/>
+          <text variable="container-title" text-case="capitalize-first" font-style="italic"/>
+        </group>
+      </else-if>
+      <else-if type="webpage post-weblog" match="any">
+        <group delimiter="">
+          <text variable="title" text-case="capitalize-first" font-style="italic" suffix=", "/>
+          <text variable="URL"/>
+          <group prefix=" , ">
+            <date variable="issued">
+              <date-part name="day" suffix=" "/>
+              <date-part name="month" suffix=" "/>
+              <date-part name="year"/>
+            </date>
+          </group>
+        </group>
+      </else-if>
+      <else>
+        <text variable="title" quotes="true"/>
+      </else>
+    </choose>
+  </macro>
+  <macro name="pub-place">
+    <choose>
+      <if type="bill book chapter entry-dictionary entry-encyclopedia thesis graphic legal_case manuscript motion_picture paper-conference report song" match="any">
+        <choose>
+          <if variable="publisher-place" match="any">
+            <text variable="publisher-place"/>
+          </if>
+          <else>
+            <text value="s.l."/>
+          </else>
+        </choose>
+      </if>
+    </choose>
+  </macro>
+  <macro name="publisher">
+    <choose>
+      <if type="bill book chapter entry-dictionary entry-encyclopedia graphic legal_case motion_picture paper-conference report song" match="any">
+        <text variable="publisher"/>
+      </if>
+    </choose>
+  </macro>
+  <macro name="yearpage">
+    <choose>
+      <if type="bill book graphic legal_case motion_picture paper-conference manuscript report song thesis" match="any">
+        <group delimiter=", ">
+          <date variable="issued">
+            <date-part name="year"/>
+          </date>
+          <group>
+            <text term="volume" form="short" suffix="."/>
+            <text variable="number-of-volumes" prefix=". " suffix="/"/>
+            <text variable="volume"/>
+          </group>
+          <choose>
+            <if variable="locator" match="any">
+              <group delimiter="&#8239;">
+                <label variable="locator" form="short"/>
+                <text variable="locator"/>
+              </group>
+            </if>
+            <else-if variable="locator" match="none">
+              <text variable="number-of-pages" suffix="&#160;p"/>
+            </else-if>
+          </choose>
+        </group>
+      </if>
+      <else-if type="chapter entry-dictionary entry-encyclopedia" match="any">
+        <group delimiter=" ">
+          <date variable="issued">
+            <date-part name="year" suffix=", "/>
+          </date>
+          <group>
+            <text term="volume" form="short" suffix="."/>
+            <text variable="number-of-volumes" prefix=". " suffix="/"/>
+            <text variable="volume" suffix=","/>
+          </group>
+          <choose>
+            <if variable="locator" match="any">
+              <group delimiter="&#8239;">
+                <label variable="locator" form="short"/>
+                <text variable="locator"/>
+              </group>
+            </if>
+            <else-if variable="locator" match="none">
+              <label variable="page" form="short"/>
+              <text variable="page"/>
+            </else-if>
+          </choose>
+        </group>
+      </else-if>
+      <else-if type="article-journal" match="any">
+        <group delimiter=" " font-style="normal">
+          <choose>
+            <if variable="locator" match="any">
+              <group delimiter="&#8239;">
+                <label variable="locator" form="short"/>
+                <text variable="locator"/>
+              </group>
+            </if>
+            <else-if variable="locator" match="none">
+              <label variable="page" form="short"/>
+              <text variable="page"/>
+            </else-if>
+          </choose>
+        </group>
+      </else-if>
+      <else-if type="article-newspaper article-magazine" match="any">
+        <date variable="issued">
+          <date-part name="day" suffix=" "/>
+          <date-part name="month" form="short" suffix=" "/>
+          <date-part name="year"/>
+        </date>
+        <group delimiter=" " font-style="normal">
+          <label variable="page" form="short"/>
+          <text variable="page"/>
+        </group>
+        <group delimiter=" " font-style="normal">
+          <choose>
+            <if variable="locator" match="any">
+              <group delimiter="&#8239;">
+                <label variable="locator" form="short"/>
+                <text variable="locator"/>
+              </group>
+            </if>
+            <else-if variable="locator" match="none">
+              <label variable="page" form="short"/>
+            </else-if>
+          </choose>
+        </group>
+      </else-if>
+      <else-if type="webpage post-weblog" match="any">
+        <group delimiter=" " prefix="(" suffix=")">
+          <text value="consulté le" suffix=" " prefix=" "/>
+          <date variable="accessed" form="text">
+            <date-part name="day"/>
+            <date-part name="month"/>
+            <date-part name="year"/>
+          </date>
+        </group>
+      </else-if>
+    </choose>
+  </macro>
+  <macro name="yearpage-bib">
+    <choose>
+      <if type="bill book graphic legal_case motion_picture paper-conference report song thesis" match="any">
+        <group delimiter=", ">
+          <group delimiter=", ">
+            <date variable="issued">
+              <date-part name="year"/>
+            </date>
+            <group>
+              <text term="volume" form="short" suffix="."/>
+              <text variable="number-of-volumes" prefix=". " suffix="/"/>
+              <text variable="volume"/>
+            </group>
+            <text variable="number-of-pages" suffix="&#160;p"/>
+          </group>
+          <group>
+            <label variable="locator" form="short"/>
+            <text variable="locator"/>
+          </group>
+        </group>
+      </if>
+      <else-if type="chapter entry-dictionary entry-encyclopedia" match="any">
+        <group delimiter=", ">
+          <date variable="issued">
+            <date-part name="year"/>
+          </date>
+          <group>
+            <text term="volume" form="short" suffix="."/>
+            <text variable="number-of-volumes" prefix=". " suffix="/"/>
+            <text variable="volume"/>
+          </group>
+          <group>
+            <label variable="page" form="short"/>
+            <text variable="page" prefix="&#160;"/>
+          </group>
+        </group>
+      </else-if>
+      <else-if type="article-journal chapter" match="any">
+        <group delimiter=" ">
+          <label variable="page" form="short"/>
+          <text variable="page"/>
+        </group>
+      </else-if>
+      <else-if type="article-newspaper article-magazine" match="any">
+        <group delimiter=" ">
+          <date variable="issued">
+            <date-part name="day" suffix=" "/>
+            <date-part name="month" form="short" suffix=" "/>
+            <date-part name="year"/>
+          </date>
+          <label variable="page" form="short"/>
+          <text variable="page"/>
+        </group>
+      </else-if>
+      <else-if type="manuscript">
+        <group delimiter="" font-style="normal">
+          <choose>
+            <if variable="issued">
+              <date variable="issued">
+                <date-part name="day" suffix=" "/>
+                <date-part name="month" suffix=" "/>
+                <date-part name="year"/>
+              </date>
+            </if>
+            <else>
+              <text value="s. d."/>
+            </else>
+          </choose>
+        </group>
+      </else-if>
+      <else-if type="webpage post-weblog" match="any">
+        <group delimiter=" ">
+          <text value="consulté le" suffix=" " prefix=" "/>
+          <date variable="accessed" form="text">
+            <date-part name="day"/>
+            <date-part name="month"/>
+            <date-part name="year"/>
+          </date>
+        </group>
+      </else-if>
+    </choose>
+  </macro>
+  <macro name="edition">
+    <choose>
+      <if type="bill book graphic legal_case motion_picture report song chapter paper-conference" match="any">
+        <choose>
+          <if is-numeric="edition">
+            <group delimiter=" ">
+              <number variable="edition" form="ordinal"/>
+              <text term="edition" form="short"/>
+            </group>
+          </if>
+          <else>
+            <text variable="edition" text-case="capitalize-first" suffix="."/>
+          </else>
+        </choose>
+      </if>
+      <else-if type="article-journal article-magazine" match="any">
+        <group delimiter="">
+          <choose>
+            <if variable="issued">
+              <date variable="issued">
+                <date-part name="day" suffix=" "/>
+                <date-part name="month" suffix=" "/>
+                <date-part name="year"/>
+              </date>
+              <text macro="volume" prefix=", "/>
+            </if>
+            <else>
+              <text macro="volume" text-case="capitalize-first"/>
+            </else>
+          </choose>
+        </group>
+      </else-if>
+    </choose>
+    <text macro="issue" prefix=", "/>
+  </macro>
+  <macro name="volume">
+    <choose>
+      <if is-numeric="volume">
+        <text term="volume" form="short" suffix=".&#160;"/>
+        <text variable="volume"/>
+      </if>
+      <else>
+        <text variable="volume"/>
+      </else>
+    </choose>
+  </macro>
+  <macro name="issue">
+    <choose>
+      <if is-numeric="issue">
+        <text term="issue" form="short" suffix="&#160;"/>
+        <text variable="issue"/>
+      </if>
+      <else>
+        <text variable="issue"/>
+      </else>
+    </choose>
+  </macro>
+  <macro name="collection">
+    <text variable="collection-title" quotes="true" prefix=" (coll.&#160;" suffix=")"/>
+  </macro>
+  <citation et-al-min="4" et-al-use-first="1">
+    <layout suffix="." delimiter="&#160;; ">
+      <choose>
+        <if position="ibid-with-locator">
+          <group delimiter=", ">
+            <text term="ibid" text-case="capitalize-first" font-style="italic" suffix="."/>
+            <text variable="locator" prefix="p.&#160;"/>
+          </group>
+        </if>
+        <else-if position="ibid">
+          <text term="ibid" text-case="capitalize-first" font-style="italic"/>
+        </else-if>
+        <else-if position="subsequent">
+          <group delimiter=", ">
+            <text macro="author-ibid"/>
+            <choose>
+              <if type="bill book graphic legal_case motion_picture report song thesis manuscript" match="any">
+                <text variable="title" form="short" font-style="italic"/>
+                <text term="cited" font-style="italic" suffix="."/>
+              </if>
+              <else>
+                <text variable="title" text-case="capitalize-first" form="short" quotes="true"/>
+                <text value="art cit"/>
+              </else>
+            </choose>
+            <text variable="locator" prefix="p.&#160;"/>
+          </group>
+        </else-if>
+        <else>
+          <choose>
+            <if type="manuscript">
+              <group delimiter=", ">
+                <text variable="archive"/>
+                <text variable="archive_location"/>
+                <text variable="call-number"/>
+                <text macro="title"/>
+                <text macro="yearpage-bib"/>
+              </group>
+            </if>
+            <else-if type="bill chapter article-journal article-newspaper interview book graphic legal_case motion_picture paper-conference report song thesis webpage post-weblog article-magazine" match="any">
+              <group delimiter=", ">
+                <text macro="author"/>
+                <text macro="title"/>
+                <text macro="translator"/>
+                <text macro="edition"/>
+                <text macro="pub-place"/>
+                <text macro="publisher"/>
+                <text macro="yearpage"/>
+              </group>
+            </else-if>
+          </choose>
+        </else>
+      </choose>
+    </layout>
+  </citation>
+  <bibliography>
+    <sort>
+      <key macro="author" names-min="3" names-use-first="3"/>
+      <key variable="issued" sort="descending"/>
+    </sort>
+    <layout suffix=".">
+      <choose>
+        <if type="manuscript">
+          <group delimiter=", ">
+            <text variable="archive"/>
+            <text variable="archive_location"/>
+            <text variable="call-number"/>
+            <text macro="title"/>
+            <text macro="yearpage-bib"/>
+          </group>
+        </if>
+        <else-if type="bill chapter article-journal article-newspaper interview book graphic legal_case motion_picture paper-conference report song thesis webpage post-weblog article-magazine" match="any">
+          <group delimiter=", ">
+            <text macro="author-bib"/>
+            <text macro="title"/>
+            <text macro="translator"/>
+            <text macro="edition"/>
+            <text macro="pub-place"/>
+            <group delimiter=" ">
+              <text macro="publisher"/>
+              <text macro="collection"/>
+            </group>
+            <text macro="yearpage-bib"/>
+          </group>
+        </else-if>
+      </choose>
+    </layout>
+  </bibliography>
+</style>
diff --git a/test/command/lettrine.md b/test/command/lettrine.md
--- a/test/command/lettrine.md
+++ b/test/command/lettrine.md
@@ -4,6 +4,17 @@
 
 \lettrine[lhang=0.17]{A}{category} is
 ^D
-[Para [Span ("",["lettrine"],[]) [Str "A"],Span ("",[],[]) [Str "category"],Space,Str "is"]
-,Para [Span ("",["lettrine"],[]) [Str "A"],Span ("",[],[]) [Str "category"],Space,Str "is"]]
+[ Para
+    [ Span ( "" , [ "lettrine" ] , [] ) [ Str "A" ]
+    , SmallCaps [ Str "category" ]
+    , Space
+    , Str "is"
+    ]
+, Para
+    [ Span ( "" , [ "lettrine" ] , [] ) [ Str "A" ]
+    , SmallCaps [ Str "category" ]
+    , Space
+    , Str "is"
+    ]
+]
 ```
diff --git a/test/command/lists-inside-definition.md b/test/command/lists-inside-definition.md
new file mode 100644
--- /dev/null
+++ b/test/command/lists-inside-definition.md
@@ -0,0 +1,70 @@
+This inserts an empty `\item[]` when a list occurs at the
+beginning of a definition list definition; otherwise the list
+may start on the line with the label, which looks terrible.
+See https://tex.stackexchange.com/questions/192480/force-itemize-inside-description-onto-a-new-line
+
+```
+% pandoc -t latex
+Definition
+:   1. list
+    2. list
+^D
+\begin{description}
+\tightlist
+\item[Definition]
+\hfill
+\begin{enumerate}
+\def\labelenumi{\arabic{enumi}.}
+\tightlist
+\item
+  list
+\item
+  list
+\end{enumerate}
+\end{description}
+```
+
+```
+% pandoc -t latex
+Definition
+:   Foo
+
+    1. list
+    2. list
+^D
+\begin{description}
+\tightlist
+\item[Definition]
+Foo
+
+\begin{enumerate}
+\def\labelenumi{\arabic{enumi}.}
+\tightlist
+\item
+  list
+\item
+  list
+\end{enumerate}
+\end{description}
+```
+
+```
+% pandoc -t latex
+Definition
+:   - list
+    - list
+^D
+\begin{description}
+\tightlist
+\item[Definition]
+\hfill
+\begin{itemize}
+\tightlist
+\item
+  list
+\item
+  list
+\end{itemize}
+\end{description}
+```
+
diff --git a/test/command/locators.csl b/test/command/locators.csl
new file mode 100644
--- /dev/null
+++ b/test/command/locators.csl
@@ -0,0 +1,68 @@
+<?xml version="1.0" encoding="utf-8"?>
+<style xmlns="http://purl.org/net/xbiblio/csl" class="note" version="1.0" demote-non-dropping-particle="sort-only" default-locale="en-GB">
+  <info>
+    <title>A CSL to test locator parsing in pandoc-citeproc</title>
+    <title-short>test-locators</title-short>
+    <id>https://example.com/test-locators</id>
+    <link href="https://forums.zotero.org/discussion/4841/new-australian-legal-citation-style/?Focus=20831#Comment_20831" rel="documentation"/>
+    <category citation-format="note"/>
+  </info>
+
+  <locale>
+    <terms>
+      <term name="section" form="short">
+        <single>s</single>
+        <multiple>ss</multiple>
+      </term>
+    </terms>
+  </locale>
+
+  <macro name="locator">
+    <choose>
+      <if locator="section">
+        <!-- s or ss -->
+        <group delimiter=" " prefix=" ">
+          <label variable="locator" form="short" />
+          <text variable="locator" prefix="{" suffix="}" />
+        </group>
+      </if>
+      <else>
+        <text variable="locator" prefix=" {" suffix="}" />
+      </else>
+    </choose>
+  </macro>
+
+  <macro name="title">
+      <text variable="title" suffix=" "/>
+  </macro>
+
+  <citation>
+    <layout prefix="" suffix="." delimiter="; ">
+      <choose>
+        <if position="ibid-with-locator">
+          <text value="ibid-with-locator"/>
+          <text macro="locator"/>
+        </if>
+        <else-if position="ibid">
+          <text value="ibid"/>
+        </else-if>
+        <else-if position="subsequent">
+          <text value="subsequent"/>
+          <text macro="locator"/>
+        </else-if>
+        <else>
+          <text macro="title" />
+          <text macro="locator" />
+        </else>
+      </choose>
+    </layout>
+  </citation>
+  <bibliography>
+    <sort>
+      <key variable="issued"/>
+    </sort>
+    <layout>
+      <text variable="title" />
+    </layout>
+  </bibliography>
+</style>
diff --git a/test/command/lstlisting.md b/test/command/lstlisting.md
--- a/test/command/lstlisting.md
+++ b/test/command/lstlisting.md
@@ -8,7 +8,16 @@
 }
 \end{lstlisting}
 ^D
-[CodeBlock ("lst:Hello-World",["java"],[("language","Java"),("caption","Java Example"),("label","lst:Hello-World")]) "public class World {\n    public static void main(String[] args) {\n        System.out.println(\"Hello World\");\n    }\n}"]
+[ CodeBlock
+    ( "lst:Hello-World"
+    , [ "java" ]
+    , [ ( "language" , "Java" )
+      , ( "caption" , "Java Example" )
+      , ( "label" , "lst:Hello-World" )
+      ]
+    )
+    "public class World {\n    public static void main(String[] args) {\n        System.out.println(\"Hello World\");\n    }\n}"
+]
 ```
 
 ```
@@ -21,5 +30,15 @@
 }
 \end{lstlisting}
 ^D
-[CodeBlock ("lst:Hello-World",["java"],[("language","Java"),("escapechar","|"),("caption","Java Example"),("label","lst:Hello-World")]) "public class World {\n    public static void main(String[] args) {\n        System.out.println(\"Hello World\");\n    }\n}"]
+[ CodeBlock
+    ( "lst:Hello-World"
+    , [ "java" ]
+    , [ ( "language" , "Java" )
+      , ( "escapechar" , "|" )
+      , ( "caption" , "Java Example" )
+      , ( "label" , "lst:Hello-World" )
+      ]
+    )
+    "public class World {\n    public static void main(String[] args) {\n        System.out.println(\"Hello World\");\n    }\n}"
+]
 ```
diff --git a/test/command/macro-defs-in-preamble.md b/test/command/macro-defs-in-preamble.md
new file mode 100644
--- /dev/null
+++ b/test/command/macro-defs-in-preamble.md
@@ -0,0 +1,18 @@
+```
+% pandoc -s -f latex-latex_macros -t native
+\documentclass[11pt]{article}
+
+\newcommand{\vara}{\alpha}
+\newcommand{\varb}{b}
+
+\begin{document}
+$\vara \varb$
+\end{document}
+^D
+Pandoc
+  Meta { unMeta = fromList [] }
+  [ RawBlock (Format "latex") "\\newcommand{\\vara}{\\alpha}"
+  , RawBlock (Format "latex") "\\newcommand{\\varb}{b}"
+  , Para [ Math InlineMath "\\vara \\varb" ]
+  ]
+```
diff --git a/test/command/macros.md b/test/command/macros.md
--- a/test/command/macros.md
+++ b/test/command/macros.md
@@ -1,17 +1,20 @@
 ```
-% pandoc -f markdown+latex_macros -t markdown
+% pandoc -f markdown+latex_macros -t markdown+raw_tex-raw_attribute
 \newcommand{\my}{\phi}
 $\my+\my$
 ^D
+\newcommand{\my}{\phi}
+
 $\phi+\phi$
 ```
 
 ```
-% pandoc -f markdown-latex_macros -t markdown
+% pandoc -f markdown-latex_macros -t markdown+raw_tex-raw_attribute
 \newcommand{\my}{\phi}
 $\my+\my$
 ^D
 \newcommand{\my}{\phi}
+
 $\my+\my$
 ```
 
@@ -22,19 +25,19 @@
 ```
 % pandoc -f latex -t latex
 \let\a\b
-\newcommand{\b}{\emph{ouk}}
-\a
+\def\b{\emph{ouk}}
+\a a
 ^D
-\b
+a̱
 ```
 
 ```
 % pandoc -f latex -t latex
 \newcommand{\a}{\b}
 \newcommand{\b}{\emph{ouk}}
-\a
+\a a
 ^D
-\emph{ouk}
+\emph{ouk}a
 ```
 
 ```
@@ -58,8 +61,9 @@
 ^D
 \(5-67\)
 
-\[\begin{aligned}
-x &= y\\\end{aligned}\]
+\begin{align}
+x &= y\\
+\end{align}
 
 \emph{hi}
 
@@ -67,34 +71,92 @@
 ```
 
 ```
-% pandoc -f markdown+latex_macros -t markdown
+% pandoc -f markdown+latex_macros -t markdown+raw_tex-raw_attribute
 \newcommand{\my}{\phi}
 \begin{equation}
 \my+\my
 \end{equation}
 ^D
+\newcommand{\my}{\phi}
+
 \begin{equation}
 \phi+\phi
 \end{equation}
 ```
 
 ```
-% pandoc -f markdown-latex_macros -t markdown
+% pandoc -f markdown-latex_macros -t markdown+raw_tex-raw_attribute
 \newcommand{\my}{\phi}
 \begin{equation}
 \my+\my
 \end{equation}
 ^D
 \newcommand{\my}{\phi}
+
 \begin{equation}
 \my+\my
 \end{equation}
 ```
 
 ```
-% pandoc -f markdown+latex_macros -t markdown
+% pandoc -f markdown+latex_macros -t markdown+raw_tex-raw_attribute
 \newcommand{\my}{\emph{a}}
 \my
 ^D
+\newcommand{\my}{\emph{a}}
 \emph{a}
 ```
+
+<https://tex.stackexchange.com/questions/258/what-is-the-difference-between-let-and-def>
+
+```
+% pandoc -f latex -t plain
+\def\bar{hello}
+\let\fooi\bar
+\def\fooii{\bar}
+\fooi +\fooii
+
+\def\bar{goodbye}
+\fooi +\fooii
+^D
+hello+hello
+
+hello+goodbye
+```
+
+```
+% pandoc -f latex -t plain
+\def\txt{a}
+\def\foo{\txt}
+\let\bar\foo
+\bar % -> a
+\def\txt{b}
+\bar % -> b
+\def\foo{OH}
+\bar % -> b
+^D
+a b b
+```
+
+```
+% pandoc -f latex -t plain
+\def\aaa{aaa}
+\def\bbb{x\aaa}
+\edef\ccc{y\aaa}
+\def\aaa{AAA}
+\bbb \ccc
+^D
+xAAAyaaa
+```
+
+```
+% pandoc -f latex -t plain
+\gdef\aaa{aaa}
+\gdef\bbb{x\aaa}
+\xdef\ccc{y\aaa}
+\gdef\aaa{AAA}
+\bbb \ccc
+^D
+xAAAyaaa
+```
+
diff --git a/test/command/make-section-column-divs.md b/test/command/make-section-column-divs.md
new file mode 100644
--- /dev/null
+++ b/test/command/make-section-column-divs.md
@@ -0,0 +1,28 @@
+For reference see
+https://groups.google.com/d/msgid/pandoc-discuss/cef24253-7731-417c-a1ee-48153c4344bf%40googlegroups.com
+
+```
+% pandoc
+::: columns
+::: column
+# A
+
+a
+:::
+::: column
+# B
+
+b
+:::
+:::
+^D
+<div class="columns">
+<div class="column">
+<h1 id="a">A</h1>
+<p>a</p>
+</div><div class="column">
+<h1 id="b">B</h1>
+<p>b</p>
+</div>
+</div>
+```
diff --git a/test/command/man-defines.md b/test/command/man-defines.md
new file mode 100644
--- /dev/null
+++ b/test/command/man-defines.md
@@ -0,0 +1,15 @@
+```
+% pandoc -f man -t plain
+.de test
+ok
+..
+.test
+.br
+\A'test'
+.br
+\A'xyz'
+^D
+ok
+1
+0
+```
diff --git a/test/command/md-abbrevs.md b/test/command/md-abbrevs.md
--- a/test/command/md-abbrevs.md
+++ b/test/command/md-abbrevs.md
@@ -6,18 +6,7 @@
 % pandoc -t native
 Mr. Bob
 ^D
-[Para [Str "Mr.\160Bob"]]
-```
-
-Here pandoc readjusts the softbreak so that the nonbreaking
-space can be inserted:
-
-```
-% pandoc -t native
-Hi Mr.
-Bob
-^D
-[Para [Str "Hi",SoftBreak,Str "Mr.\160Bob"]]
+[ Para [ Str "Mr.\160Bob" ] ]
 ```
 
 If you don't want this to happen you can escape the period:
@@ -26,6 +15,7 @@
 % pandoc -t native
 Hi Mr\. Bob
 ^D
-[Para [Str "Hi",Space,Str "Mr.",Space,Str "Bob"]]
+[ Para [ Str "Hi" , Space , Str "Mr." , Space , Str "Bob" ]
+]
 ```
 
diff --git a/test/command/mdoc-An.md b/test/command/mdoc-An.md
new file mode 100644
--- /dev/null
+++ b/test/command/mdoc-An.md
@@ -0,0 +1,17 @@
+```
+% pandoc -f mdoc -t plain
+.Sh DESCRIPTION
+.An Emily Brontë ,
+.An Anne Brontë
+.Pp
+.An -split
+.An Charlotte Brontë
+.An Bramwell Brontë
+^D
+DESCRIPTION
+
+Emily Brontë, Anne Brontë
+
+Charlotte Brontë
+Bramwell Brontë
+```
diff --git a/test/command/mdoc-Bd-unfilled.md b/test/command/mdoc-Bd-unfilled.md
new file mode 100644
--- /dev/null
+++ b/test/command/mdoc-Bd-unfilled.md
@@ -0,0 +1,24 @@
+```
+% pandoc -f mdoc -t plain
+.Bd -unfilled
+’Twas brillig, and the slithy toves
+      Did gyre and gimble in the wabe:
+All mimsy were the borogoves,
+      And the mome raths outgrabe.
+
+“Beware the Jabberwock, my son!
+      The jaws that bite, the claws that catch!
+Beware the Jubjub bird, and shun
+      The frumious Bandersnatch!”
+.Ed
+^D
+’Twas brillig, and the slithy toves
+      Did gyre and gimble in the wabe:
+All mimsy were the borogoves,
+      And the mome raths outgrabe.
+
+“Beware the Jabberwock, my son!
+      The jaws that bite, the claws that catch!
+Beware the Jubjub bird, and shun
+      The frumious Bandersnatch!”
+```
diff --git a/test/command/mdoc-Bl-column.md b/test/command/mdoc-Bl-column.md
new file mode 100644
--- /dev/null
+++ b/test/command/mdoc-Bl-column.md
@@ -0,0 +1,22 @@
+```
+% pandoc -f mdoc -t djot
+.Bl -column a b
+.It a Ta
+.Sy b
+b
+.Ta c
+.Pp
+.It c Ta d Ta \&
+.It Em e
+.Ta f
+.Ta g
+.It h Ta Ta j
+.It Pq a Ta b Ta c
+.El
+^D
+| a   | *b* b | c |
+| c   | d     |   |
+| _e_ | f     | g |
+| h   |       | j |
+| (a) | b     | c |
+```
diff --git a/test/command/mdoc-Bl-tag.md b/test/command/mdoc-Bl-tag.md
new file mode 100644
--- /dev/null
+++ b/test/command/mdoc-Bl-tag.md
@@ -0,0 +1,36 @@
+```
+% pandoc -f mdoc -t native
+.Bl -tag
+.It one
+one
+.It Xo
+two
+.Xc
+two
+.It Em three Xo
+three
+.Xc
+three
+.It Po one two
+.Bq three
+.Pc
+four
+.El
+^D
+[ DefinitionList
+    [ ( [ Str "one" ] , [ [ Para [ Str "one" ] ] ] )
+    , ( [ Str "two" ] , [ [ Para [ Str "two" ] ] ] )
+    , ( [ Emph [ Str "three" ] , Space , Str "three" ]
+      , [ [ Para [ Str "three" ] ] ]
+      )
+    , ( [ Str "(one"
+        , Space
+        , Str "two"
+        , Space
+        , Str "[three])"
+        ]
+      , [ [ Para [ Str "four" ] ] ]
+      )
+    ]
+]
+```
diff --git a/test/command/mediawiki_behavior_switches.md b/test/command/mediawiki_behavior_switches.md
new file mode 100644
--- /dev/null
+++ b/test/command/mediawiki_behavior_switches.md
@@ -0,0 +1,16 @@
+```
+% pandoc -f mediawiki -t native
+____INDEX____
+__NOINDEX__
+__noindex__
+__FOOBAR__
+^D
+[ Para
+    [ Str "____"
+    , SoftBreak
+    , Str "__noindex__"
+    , SoftBreak
+    , Str "__FOOBAR__"
+    ]
+]
+```
diff --git a/test/command/minimal.svg b/test/command/minimal.svg
new file mode 100644
--- /dev/null
+++ b/test/command/minimal.svg
@@ -0,0 +1,5 @@
+<?xml version="1.0" standalone="no"?>
+
+<svg viewBox="-.333 -.333 480 150" style="background-color:#ffffff00" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xml:space="preserve">
+    <path d="M 0 35.5 L 6.5 22.5 L 16 37 L 23 24 L 34.8 43.7 L 42.5 30 L 50.3 47 L 59.7 27.7 L 69 47 L 85 17.7 L 98.3 39 L 113 9.7 L 127.7 42.3 L 136.3 23.7 L 147 44.3 L 158.3 20.3 L 170.3 40.3 L 177.7 25.7 L 189.7 43 L 199.7 21 L 207.7 35 L 219 11 L 233 37 L 240.3 23.7 L 251 43 L 263 18.3 L 272.7 33.3 L 283 10 L 295 32.3 L 301.3 23 L 311.7 37 L 323.7 7.7 L 339.3 39 L 346.3 25.7 L 356.3 42.3 L 369.7 15 L 376.3 25.7 L 384 9 L 393 28.3 L 400.3 19 L 411.7 38.3 L 421 21 L 434.3 43 L 445 25 L 453 36.3 L 464.3 18.3 L 476.2 40.3 L 480 33.5 L 480 215 L 0 215 L 0 35.5 Z" fill="#175720"/>
+</svg>
diff --git a/test/command/mmd-metadata.md b/test/command/mmd-metadata.md
new file mode 100644
--- /dev/null
+++ b/test/command/mmd-metadata.md
@@ -0,0 +1,20 @@
+```
+% pandoc -f markdown_mmd -t markdown -s
+Title: Blah blah blah
+Author: Doo de Doo
+Base Header Level: 1
+Bibliography: Pubs.bib
+Lang: en-GB
+
+body
+^D
+---
+author: Doo de Doo
+baseheaderlevel: 1
+bibliography: Pubs.bib
+lang: en-GB
+title: Blah blah blah
+---
+
+body
+```
diff --git a/test/command/modern-humanities-research-association.csl b/test/command/modern-humanities-research-association.csl
new file mode 100644
--- /dev/null
+++ b/test/command/modern-humanities-research-association.csl
@@ -0,0 +1,445 @@
+<?xml version="1.0" encoding="utf-8"?>
+<style xmlns="http://purl.org/net/xbiblio/csl" class="note" version="1.0" demote-non-dropping-particle="sort-only" default-locale="en-GB">
+  <info>
+    <title>Modern Humanities Research Association (note with bibliography)</title>
+    <id>http://www.zotero.org/styles/modern-humanities-research-association</id>
+    <link href="http://www.zotero.org/styles/modern-humanities-research-association" rel="self"/>
+    <link href="http://www.mhra.org.uk/Publications/Books/StyleGuide/download.shtml" rel="documentation"/>
+    <author>
+      <name>Rintze Zelle</name>
+      <uri>http://twitter.com/rintzezelle</uri>
+    </author>
+    <contributor>
+      <name>Sebastian Karcher</name>
+    </contributor>
+    <category citation-format="note"/>
+    <category field="generic-base"/>
+    <summary>MHRA format with full notes and bibliography</summary>
+    <updated>2013-04-16T04:40:01+00:00</updated>
+    <rights license="http://creativecommons.org/licenses/by-sa/3.0/">This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 License</rights>
+  </info>
+  <locale xml:lang="en">
+    <terms>
+      <term name="et-al">and others</term>
+      <term name="editor" form="verb-short">ed. by</term>
+      <term name="edition" form="short">edn</term>
+      <term name="translator" form="verb-short">trans. by</term>
+    </terms>
+  </locale>
+  <macro name="author">
+    <group delimiter=". ">
+      <names variable="author">
+        <name name-as-sort-order="first" and="text" sort-separator=", " delimiter=", " delimiter-precedes-last="always"/>
+        <label form="short" prefix=", " suffix="."/>
+        <substitute>
+          <names variable="editor"/>
+          <names variable="translator"/>
+          <text macro="title-note"/>
+        </substitute>
+      </names>
+      <text macro="recipient"/>
+    </group>
+  </macro>
+  <macro name="recipient">
+    <group delimiter=" ">
+      <choose>
+        <if type="personal_communication">
+          <choose>
+            <if variable="genre">
+              <text variable="genre" text-case="capitalize-first"/>
+            </if>
+            <else>
+              <text term="letter" text-case="capitalize-first"/>
+            </else>
+          </choose>
+        </if>
+      </choose>
+      <text macro="recipient-note"/>
+    </group>
+  </macro>
+  <macro name="contributors-note">
+    <names variable="author">
+      <name and="text" sort-separator=", " delimiter=", " delimiter-precedes-last="never"/>
+      <label form="short" prefix=", "/>
+      <substitute>
+        <names variable="editor"/>
+        <names variable="translator"/>
+        <text macro="title-note"/>
+      </substitute>
+    </names>
+    <text macro="recipient-note"/>
+  </macro>
+  <macro name="title-note">
+    <choose>
+      <if type="bill book graphic legal_case legislation motion_picture report song" match="any">
+        <text variable="title" font-style="italic" text-case="title"/>
+      </if>
+      <else>
+        <text variable="title" quotes="true" text-case="title"/>
+      </else>
+    </choose>
+  </macro>
+  <macro name="disambiguate">
+    <choose>
+      <if disambiguate="true">
+        <choose>
+          <if variable="title" match="none">
+            <text macro="issued"/>
+          </if>
+          <else-if type="bill book graphic legal_case legislation motion_picture report song" match="any">
+            <text variable="title" font-style="italic" text-case="title" form="short"/>
+          </else-if>
+          <else>
+            <text variable="title" quotes="true" text-case="title" form="short"/>
+          </else>
+        </choose>
+      </if>
+    </choose>
+  </macro>
+  <macro name="title-sort-substitute">
+    <choose>
+      <if type="bill book graphic legal_case legislation motion_picture report song" match="any">
+        <text variable="title" font-style="italic" text-case="title" form="short"/>
+      </if>
+      <else>
+        <text variable="title" quotes="true" text-case="title" form="short"/>
+      </else>
+    </choose>
+  </macro>
+  <macro name="editor-translator">
+    <group delimiter=", ">
+      <choose>
+        <if variable="author">
+          <group delimiter=" ">
+            <choose>
+              <if variable="container-author">
+                <group>
+                  <names variable="container-author">
+                    <label form="verb-short" text-case="lowercase" suffix=" "/>
+                    <name and="text" delimiter=", "/>
+                  </names>
+                </group>
+              </if>
+            </choose>
+          </group>
+          <names variable="editor translator" delimiter=", ">
+            <label form="verb-short" text-case="lowercase" suffix=" "/>
+            <name and="text" delimiter=", "/>
+          </names>
+        </if>
+      </choose>
+    </group>
+  </macro>
+  <macro name="collection-title">
+    <text variable="collection-title" text-case="title"/>
+    <text variable="collection-number" prefix=", "/>
+  </macro>
+  <macro name="locators-note">
+    <choose>
+      <if type="article-journal">
+        <text variable="volume"/>
+      </if>
+      <else-if type="bill book chapter graphic legal_case legislation motion_picture paper-conference report song" match="any">
+        <group delimiter=", ">
+          <text macro="edition-note"/>
+          <group>
+            <number variable="number-of-volumes" form="numeric"/>
+            <text term="volume" form="short" prefix=" " plural="true"/>
+          </group>
+        </group>
+      </else-if>
+    </choose>
+  </macro>
+  <macro name="volume">
+    <choose>
+      <if type="article-journal">
+        <text variable="volume"/>
+      </if>
+      <else-if type="bill book chapter graphic legal_case legislation motion_picture paper-conference report song" match="any">
+        <group delimiter=", ">
+          <text macro="edition-note"/>
+          <group>
+            <number variable="number-of-volumes" form="numeric"/>
+            <text term="volume" form="short" prefix=" " plural="true"/>
+          </group>
+        </group>
+      </else-if>
+    </choose>
+  </macro>
+  <macro name="issue-note">
+    <choose>
+      <if type="article-journal">
+        <choose>
+          <if variable="volume">
+            <text macro="issued" prefix=" (" suffix=")"/>
+          </if>
+          <else>
+            <text macro="issued" prefix=", "/>
+          </else>
+        </choose>
+      </if>
+      <else-if variable="publisher-place publisher" match="any">
+        <group prefix=" (" suffix=")" delimiter=", ">
+          <group delimiter=" ">
+            <choose>
+              <if variable="title" match="none"/>
+              <else-if type="thesis speech" match="any">
+                <text variable="genre" prefix="unpublished "/>
+              </else-if>
+            </choose>
+            <text macro="event"/>
+          </group>
+          <text macro="publisher"/>
+          <text macro="issued"/>
+        </group>
+      </else-if>
+      <else>
+        <text macro="issued" prefix=", "/>
+      </else>
+    </choose>
+  </macro>
+  <macro name="locators-specific-note">
+    <choose>
+      <if type="bill book chapter graphic legal_case legislation motion_picture paper-conference report song" match="any">
+        <choose>
+          <if is-numeric="volume">
+            <number variable="volume" form="roman" font-variant="small-caps"/>
+          </if>
+        </choose>
+      </if>
+    </choose>
+  </macro>
+  <macro name="container-title-note">
+    <choose>
+      <if type="chapter paper-conference" match="any">
+        <text term="in" text-case="lowercase" suffix=" "/>
+      </if>
+    </choose>
+    <text variable="container-title" font-style="italic"/>
+  </macro>
+  <macro name="edition-note">
+    <choose>
+      <if type="bill book chapter graphic legal_case legislation motion_picture paper-conference report song" match="any">
+        <choose>
+          <if is-numeric="edition">
+            <group delimiter=" ">
+              <number variable="edition" form="ordinal"/>
+              <text term="edition" form="short"/>
+            </group>
+          </if>
+          <else>
+            <text variable="edition"/>
+          </else>
+        </choose>
+      </if>
+    </choose>
+  </macro>
+  <macro name="editor-note">
+    <names variable="editor">
+      <name and="text" sort-separator=", " delimiter=", "/>
+      <label form="short" prefix=", " suffix="."/>
+    </names>
+  </macro>
+  <macro name="translator-note">
+    <names variable="translator">
+      <name and="text" sort-separator=", " delimiter=", "/>
+      <label form="verb-short" prefix=", " suffix="."/>
+    </names>
+  </macro>
+  <macro name="recipient-note">
+    <names variable="recipient" delimiter=", ">
+      <label form="verb" prefix=" " text-case="lowercase" suffix=" "/>
+      <name and="text" delimiter=", "/>
+    </names>
+  </macro>
+  <macro name="recipient-short">
+    <names variable="recipient">
+      <label form="verb" prefix=" " text-case="lowercase" suffix=" "/>
+      <name form="short" and="text" delimiter=", "/>
+    </names>
+  </macro>
+  <macro name="contributors-short">
+    <names variable="author">
+      <name form="short" and="text" sort-separator=", " delimiter=", " delimiter-precedes-last="never"/>
+      <substitute>
+        <names variable="editor"/>
+        <names variable="translator"/>
+        <text macro="title-sort-substitute"/>
+      </substitute>
+    </names>
+    <text macro="recipient-short"/>
+  </macro>
+  <macro name="interviewer-note">
+    <names variable="interviewer" delimiter=", ">
+      <label form="verb" prefix=" " text-case="lowercase" suffix=" "/>
+      <name and="text" delimiter=", "/>
+    </names>
+  </macro>
+  <macro name="locators-newspaper">
+    <choose>
+      <if type="article-newspaper">
+        <group delimiter=", ">
+          <group>
+            <text variable="edition" suffix=" "/>
+            <text term="edition" prefix=" "/>
+          </group>
+          <group>
+            <text term="section" suffix=" "/>
+            <text variable="section"/>
+          </group>
+        </group>
+      </if>
+    </choose>
+  </macro>
+  <macro name="event">
+    <group>
+      <text term="presented at" suffix=" "/>
+      <text variable="event"/>
+    </group>
+  </macro>
+  <macro name="publisher">
+    <group delimiter=": ">
+      <text variable="publisher-place"/>
+      <text variable="publisher"/>
+    </group>
+  </macro>
+  <macro name="issued">
+    <choose>
+      <if type="graphic report article-newspaper article-magazine personal_communication" match="any">
+        <date variable="issued">
+          <date-part name="day" suffix=" "/>
+          <date-part name="month" suffix=" "/>
+          <date-part name="year"/>
+        </date>
+      </if>
+      <else>
+        <date variable="issued">
+          <date-part name="year"/>
+        </date>
+      </else>
+    </choose>
+  </macro>
+  <macro name="pages">
+    <choose>
+      <if type="article-journal">
+        <text variable="page" prefix=", "/>
+      </if>
+      <else>
+        <choose>
+          <if variable="volume">
+            <text variable="page" prefix=", "/>
+          </if>
+          <else>
+            <label variable="page" form="short" prefix=", " suffix=" "/>
+            <text variable="page"/>
+          </else>
+        </choose>
+      </else>
+    </choose>
+  </macro>
+  <macro name="point-locators">
+    <text macro="pages"/>
+    <choose>
+      <if variable="page">
+        <group prefix=" (" suffix=")">
+          <label variable="locator" form="short" suffix=" "/>
+          <text variable="locator"/>
+        </group>
+      </if>
+      <else>
+        <label variable="locator" form="short" prefix=", " suffix=" "/>
+        <text variable="locator"/>
+      </else>
+    </choose>
+  </macro>
+  <macro name="point-locators-subsequent">
+    <label variable="locator" form="short" prefix=", " suffix=" "/>
+    <text variable="locator"/>
+  </macro>
+  <macro name="archive-note">
+    <group delimiter=", ">
+      <text variable="archive_location"/>
+      <text variable="archive"/>
+      <text variable="archive-place"/>
+    </group>
+  </macro>
+  <macro name="access-note">
+    <group delimiter=", ">
+      <choose>
+        <if type="article-journal bill chapter legal_case legislation paper-conference" match="none">
+          <text macro="archive-note" prefix=", "/>
+        </if>
+      </choose>
+    </group>
+    <choose>
+      <if variable="DOI">
+        <text variable="DOI" prefix=" &lt;doi:" suffix="&gt;"/>
+      </if>
+      <else>
+        <choose>
+          <if variable="URL">
+            <text variable="URL" prefix=" &lt;" suffix="&gt;"/>
+            <group prefix=" [" suffix="]">
+              <text term="accessed" text-case="lowercase"/>
+              <date variable="accessed">
+                <date-part name="day" prefix=" "/>
+                <date-part name="month" prefix=" "/>
+                <date-part name="year" prefix=" "/>
+              </date>
+            </group>
+          </if>
+        </choose>
+      </else>
+    </choose>
+  </macro>
+  <citation et-al-min="4" et-al-use-first="1" disambiguate-add-names="true" disambiguate-add-givenname="true">
+    <layout prefix="" suffix="." delimiter="; ">
+      <choose>
+        <if position="subsequent">
+          <group delimiter=", ">
+            <text macro="contributors-short"/>
+            <text macro="disambiguate"/>
+            <text macro="locators-specific-note"/>
+          </group>
+          <text macro="point-locators-subsequent"/>
+        </if>
+        <else>
+          <group delimiter=", ">
+            <text macro="contributors-note"/>
+            <text macro="title-note"/>
+            <text macro="container-title-note"/>
+            <text macro="editor-translator"/>
+            <text macro="collection-title"/>
+            <text macro="locators-note"/>
+          </group>
+          <text macro="issue-note"/>
+          <text macro="locators-specific-note" prefix=", "/>
+          <text macro="locators-newspaper" prefix=", "/>
+          <text macro="point-locators"/>
+          <text macro="access-note"/>
+        </else>
+      </choose>
+    </layout>
+  </citation>
+  <bibliography hanging-indent="true" et-al-min="7" et-al-use-first="6" subsequent-author-substitute="---">
+    <sort>
+      <key macro="author"/>
+      <key variable="title"/>
+    </sort>
+    <layout>
+      <group delimiter=", ">
+        <text macro="author"/>
+        <text macro="title-note"/>
+        <text macro="container-title-note"/>
+        <text macro="editor-translator"/>
+        <text macro="collection-title"/>
+        <text macro="volume"/>
+      </group>
+      <text macro="issue-note"/>
+      <text macro="locators-specific-note" prefix=", "/>
+      <text macro="locators-newspaper" prefix=", "/>
+      <text macro="pages"/>
+      <text macro="access-note"/>
+    </layout>
+  </bibliography>
+</style>
diff --git a/test/command/multiple-metadata-blocks.md b/test/command/multiple-metadata-blocks.md
--- a/test/command/multiple-metadata-blocks.md
+++ b/test/command/multiple-metadata-blocks.md
@@ -10,6 +10,10 @@
 foo: bim
 ...
 ^D
-Pandoc (Meta {unMeta = fromList [("foo",MetaInlines [Str "bar"])]})
-[]
+Pandoc
+  Meta
+    { unMeta =
+        fromList [ ( "foo" , MetaInlines [ Str "bim" ] ) ]
+    }
+  []
 ```
diff --git a/test/command/nested-spanlike.md b/test/command/nested-spanlike.md
new file mode 100644
--- /dev/null
+++ b/test/command/nested-spanlike.md
@@ -0,0 +1,6 @@
+```
+% pandoc -f markdown -t html
+[test]{.foo .underline #bar .smallcaps .kbd}
+^D
+<p><kbd id="bar"><u><span class="smallcaps">test</span></u></kbd></p>
+```
diff --git a/test/command/nested-table-to-asciidoc-6942.md b/test/command/nested-table-to-asciidoc-6942.md
new file mode 100644
--- /dev/null
+++ b/test/command/nested-table-to-asciidoc-6942.md
@@ -0,0 +1,82 @@
+A table within a table should be converted into a table within table
+
+```
+% pandoc -f html -t asciidoc
+<!doctype html>
+<html>
+<head>
+<meta charset="utf-8">
+<title> NestedTables </title>
+</head>
+<body>
+<table>
+ <tr>
+  <td >
+   <table>  <tr> <td> a1 </td> <td> a2 </td> </tr>  </table>
+  </td>
+  <td>b</td>
+ </tr>
+ <tr>
+   <td>c</td> <td>d </td>
+ </tr>
+</table>
+</body>
+</html>
+^D
+[width="100%",cols="50%,50%",]
+|===
+a|
+[cols=",",]
+!===
+!a1 !a2
+!===
+
+|b
+|c |d
+|===
+```
+
+A table within a table within a table cannot be converted because asciidoc only
+supports two levels of tables.
+The table on level 3 is thus converted to level 2 and a warning is produced
+```
+% pandoc -f html -t asciidoc --verbose
+<!doctype html>
+<html>
+<head>
+<meta charset="utf-8">
+<title> NestedTables </title>
+</head>
+<body>
+<table>
+ <tr>
+  <td>
+    <table>  <tr>
+	<td> a1 </td>
+	<td>
+	  <table>  <tr> <td> 1 </td> <td> 2 </td> </tr>  </table>
+	</td>
+    </tr>  </table>
+  </td>
+  <td>b</td>
+ </tr>
+ <tr>
+   <td>c</td> <td>d </td>
+ </tr>
+</table>
+</body>
+</html>
+^D
+2> [INFO] Not rendering Table ("",[],[]) (Caption Nothing []) [(AlignDefault,ColWidth 0.5),(AlignDefault,ColWidth 0.5)] (TableHead ("",[],[]) []) [TableBody ("",[],[]) (RowHeadColumns 0) [] [Row ("",[],[]) [Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1) [Plain [Str "a1"]],Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1) [Table ("",[],[]) (Caption Nothing []) [(AlignDefault,ColWidthDefault),(AlignDefault,ColWidthDefault)] (TableHead ("",[],[]) []) [TableBody ("",[],[]) (RowHeadColumns 0) [] [Row ("",[],[]) [Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1) [Plain [Str "1"]],Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1) [Plain [Str "2"]]]]] (TableFoot ("",[],[]) [])]]]] (TableFoot ("",[],[]) [])
+[width="100%",cols="50%,50%",]
+|===
+a|
+[width="100%",cols="50%,50%",]
+!===
+!a1 !
+!===
+
+|b
+|c |d
+|===
+```
diff --git a/test/command/newif.md b/test/command/newif.md
new file mode 100644
--- /dev/null
+++ b/test/command/newif.md
@@ -0,0 +1,55 @@
+```
+% pandoc -f latex -t plain
+\iftrue
+should print
+\iftrue
+should print
+\else
+should not print A
+\fi
+\else
+should not print B
+\fi
+
+\iffalse
+should not print C
+\else
+\iftrue
+should print
+\else
+should not print D
+\fi
+\fi
+
+\newif\ifepub
+
+\ifepub
+should not print E
+\fi
+
+\epubtrue
+
+\ifepub
+should print
+\else
+should not print F
+\fi
+
+\epubfalse
+
+\ifepub
+should not print G
+\else
+should print
+\fi
+^D
+should print
+
+should print
+
+should print
+
+should print
+
+should print
+```
diff --git a/test/command/oscola.csl b/test/command/oscola.csl
new file mode 100644
--- /dev/null
+++ b/test/command/oscola.csl
@@ -0,0 +1,680 @@
+<?xml version="1.0" encoding="utf-8"?>
+<style xmlns="http://purl.org/net/xbiblio/csl" class="note" version="1.0" demote-non-dropping-particle="never" default-locale="en-GB">
+  <info>
+    <title>OSCOLA (Oxford University Standard for Citation of Legal Authorities)</title>
+    <title-short>OSCOLA</title-short>
+    <id>http://www.zotero.org/styles/oscola</id>
+    <link href="http://www.zotero.org/styles/oscola" rel="self"/>
+    <link href="http://www.zotero.org/styles/australian-guide-to-legal-citation" rel="template"/>
+    <link href="http://www.law.ox.ac.uk/publications/oscola.php" rel="documentation"/>
+    <author>
+      <name>Sebastian Karcher</name>
+    </author>
+    <category citation-format="note"/>
+    <category field="law"/>
+    <summary>The OSCOLA Standards. For a Zotero Group showing data-entry in Zotero see: https://www.zotero.org/groups/oscola_samples/items/order/itemType</summary>
+    <updated>2013-11-15T01:14:57+00:00</updated>
+    <rights license="http://creativecommons.org/licenses/by-sa/3.0/">This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 License</rights>
+  </info>
+  <locale>
+    <terms>
+      <term name="chapter" form="short">
+        <single>ch.</single>
+        <multiple>chs.</multiple>
+      </term>
+      <term name="section" form="short">
+        <single>s</single>
+        <multiple>ss</multiple>
+      </term>
+      <term name="paragraph" form="short">
+        <single>para</single>
+        <multiple>paras</multiple>
+      </term>
+      <term name="translator" form="short">
+        <single>tr.</single>
+        <multiple>trs.</multiple>
+      </term>
+      <term name="edition" form="short">edn.</term>
+      <term name="et-al">and others</term>
+    </terms>
+  </locale>
+  <!--Authors and Persons-->
+  <macro name="author-note">
+    <!--for bills & hearing this should start with jurisdiction once available-->
+    <choose>
+      <if type="interview">
+        <group delimiter=", ">
+          <names variable="interviewer">
+            <name delimiter-precedes-last="never" and="text" delimiter=", " initialize="false" initialize-with=""/>
+          </names>
+          <names variable="author" prefix="Interview with ">
+            <name delimiter-precedes-last="never" and="text" delimiter=", " initialize="false" initialize-with=""/>
+          </names>
+        </group>
+      </if>
+      <else-if type="personal_communication">
+        <group delimiter=" ">
+          <group delimiter=" from ">
+            <text variable="genre"/>
+            <names variable="author">
+              <name delimiter-precedes-last="never" and="text" delimiter=", " initialize="false" initialize-with=""/>
+            </names>
+          </group>
+          <names variable="recipient" prefix="to ">
+            <name delimiter-precedes-last="never" and="text" delimiter=", " initialize="false" initialize-with=""/>
+          </names>
+        </group>
+      </else-if>
+      <else-if type="broadcast">
+        <text variable="publisher"/>
+      </else-if>
+      <else-if type="legal_case legislation" match="any"/>
+      <else>
+        <names variable="author">
+          <name delimiter-precedes-last="never" and="text" delimiter=", " initialize="false" initialize-with=""/>
+          <label form="short" prefix=" (" suffix=")" strip-periods="true"/>
+          <substitute>
+            <names variable="editor"/>
+            <names variable="translator"/>
+            <text macro="title"/>
+          </substitute>
+        </names>
+      </else>
+    </choose>
+  </macro>
+  <macro name="author-short">
+    <choose>
+      <if type="interview">
+        <group delimiter=", ">
+          <names variable="interviewer">
+            <name delimiter-precedes-last="never" and="text" form="short" delimiter=", " initialize="false" initialize-with=""/>
+          </names>
+          <names variable="author" prefix="Interview with ">
+            <name delimiter-precedes-last="never" and="text" form="short" delimiter=", " initialize="false" initialize-with=""/>
+          </names>
+        </group>
+      </if>
+      <else-if type="personal_communication">
+        <group delimiter=" ">
+          <group delimiter=" from ">
+            <text variable="genre"/>
+            <names variable="author">
+              <name delimiter-precedes-last="never" and="text" delimiter=", " form="short" initialize="false" initialize-with=""/>
+            </names>
+          </group>
+          <names variable="recipient" prefix="to ">
+            <name delimiter-precedes-last="never" and="text" delimiter=", " initialize="false" form="short" initialize-with=""/>
+          </names>
+        </group>
+      </else-if>
+      <else-if type="broadcast">
+        <text variable="publisher"/>
+      </else-if>
+      <else>
+        <names variable="author">
+          <name delimiter-precedes-last="never" and="text" delimiter=", " initialize="false" initialize-with="" form="short"/>
+          <substitute>
+            <names variable="editor"/>
+            <names variable="translator"/>
+            <text macro="title"/>
+          </substitute>
+        </names>
+      </else>
+    </choose>
+  </macro>
+  <macro name="author">
+    <!--for bills & hearing this should start with jurisdiction once available-->
+    <choose>
+      <if type="interview">
+        <group delimiter=", ">
+          <names variable="interviewer">
+            <name delimiter-precedes-last="never" and="text" delimiter=", " initialize-with="" name-as-sort-order="all" sort-separator=" "/>
+          </names>
+          <names variable="author" prefix="Interview with ">
+            <name delimiter-precedes-last="never" and="text" delimiter=", " initialize="false" initialize-with=""/>
+          </names>
+        </group>
+      </if>
+      <else-if type="personal_communication">
+        <group delimiter=" ">
+          <group delimiter=", ">
+            <names variable="author">
+              <name delimiter-precedes-last="never" and="text" delimiter=", " initialize-with="" name-as-sort-order="all" sort-separator=" "/>
+            </names>
+            <text variable="genre"/>
+          </group>
+          <names variable="recipient" prefix="to ">
+            <name delimiter-precedes-last="never" and="text" delimiter=", " initialize="false" initialize-with=""/>
+          </names>
+        </group>
+      </else-if>
+      <else-if type="broadcast">
+        <text variable="publisher"/>
+      </else-if>
+      <else-if type="legal_case legislation" match="any"/>
+      <else>
+        <names variable="author">
+          <name delimiter-precedes-last="never" and="text" delimiter=", " name-as-sort-order="all" initialize-with="" sort-separator=" "/>
+          <label form="short" prefix=" (" suffix=")" strip-periods="true"/>
+          <substitute>
+            <names variable="editor"/>
+            <names variable="translator"/>
+            <text macro="title"/>
+          </substitute>
+        </names>
+      </else>
+    </choose>
+  </macro>
+  <macro name="editor">
+    <choose>
+      <if type="chapter paper-conference entry-encyclopedia" match="none">
+        <names variable="editor translator container-author" delimiter=", ">
+          <name delimiter-precedes-last="never" and="text" delimiter=", " initialize="false" initialize-with=""/>
+          <label form="short" prefix=" " strip-periods="true"/>
+        </names>
+      </if>
+    </choose>
+  </macro>
+  <macro name="editor-chapter">
+    <group>
+      <text term="in" suffix=" "/>
+      <names variable="editor translator container-author" delimiter=", ">
+        <name delimiter-precedes-last="never" and="text" delimiter=", " initialize="false" initialize-with=""/>
+        <label form="short" prefix=" (" suffix=")" strip-periods="true"/>
+      </names>
+    </group>
+  </macro>
+  <!-- Titles -->
+  <macro name="title">
+    <choose>
+      <if type="book motion_picture treaty" match="any">
+        <text variable="title" font-style="italic" text-case="title"/>
+      </if>
+      <else-if type="bill legislation" match="any">
+        <text variable="title"/>
+      </else-if>
+      <else-if type="legal_case">
+        <text variable="title" font-style="italic" strip-periods="true"/>
+      </else-if>
+      <else>
+        <text variable="title" quotes="true" text-case="title"/>
+      </else>
+    </choose>
+  </macro>
+  <macro name="title-short">
+    <choose>
+      <if type="book motion_picture treaty" match="any">
+        <text variable="title" font-style="italic" text-case="title" form="short"/>
+      </if>
+      <else-if type="bill legislation" match="any">
+        <text variable="title" form="short"/>
+      </else-if>
+      <else-if type="legal_case">
+        <choose>
+          <if variable="title-short">
+            <text variable="title-short" font-style="italic"/>
+          </if>
+          <else>
+            <text variable="title" font-style="italic"/>
+          </else>
+        </choose>
+      </else-if>
+      <else>
+        <text variable="title" quotes="true" text-case="title" form="short"/>
+      </else>
+    </choose>
+  </macro>
+  <!--Dates-->
+  <macro name="issued-year">
+    <date variable="issued" form="text" date-parts="year"/>
+  </macro>
+  <macro name="issued-full">
+    <date variable="issued" form="text"/>
+  </macro>
+  <macro name="date-parenthesis">
+    <choose>
+      <if type="legal_case article-journal article-magazine" match="any">
+        <choose>
+          <if variable="number authority" match="all">
+            <text macro="issued-year" prefix="[" suffix="]"/>
+          </if>
+          <else-if variable="volume">
+            <text macro="issued-year" prefix="(" suffix=")"/>
+          </else-if>
+          <else-if variable="container-title volume number" match="any">
+            <!--no year in square brackets for unreported case w/o medium neutral citation-->
+            <text macro="issued-year" prefix="[" suffix="]"/>
+          </else-if>
+        </choose>
+      </if>
+      <else-if type="legislation bill" match="any">
+        <text macro="issued-year"/>
+      </else-if>
+    </choose>
+  </macro>
+  <!--publication info -->
+  <macro name="publisher">
+    <choose>
+      <if type="book chapter broadcast personal_communication manuscript paper-conference article-newspaper report legislation motion_picture speech interview thesis entry-encyclopedia webpage post-weblog" match="any">
+        <group delimiter=" ">
+          <group prefix="(" suffix=")" delimiter=", ">
+            <choose>
+              <if type="article-newspaper">
+                <text variable="publisher-place" strip-periods="true"/>
+                <date variable="issued" form="text"/>
+              </if>
+              <else-if type="broadcast personal_communication treaty" match="any">
+                <date variable="issued" form="text"/>
+              </else-if>
+              <else-if type="legislation bill" match="any">
+                <!--this should be jurisdiction we use code instead-->
+                <text variable="container-title" strip-periods="true"/>
+              </else-if>
+              <else>
+                <!--this won't work in Zotero yet, but does no harm -->
+                <names variable="director">
+                  <label form="verb" text-case="capitalize-first" suffix=" "/>
+                  <name delimiter-precedes-last="never" and="text" delimiter=", " initialize="false" initialize-with=""/>
+                </names>
+                <text macro="editor"/>
+                <choose>
+                  <!--if none of these, this we don't want edition either. Might be Loose-Leaf-->
+                  <if variable="publisher issued genre container-title" match="any">
+                    <text macro="edition"/>
+                  </if>
+                </choose>
+                <choose>
+                  <if type="speech">
+                    <text variable="event"/>
+                    <text variable="event-place"/>
+                    <text macro="issued-full"/>
+                  </if>
+                  <else-if type="thesis" match="any">
+                    <text variable="genre" strip-periods="true"/>
+                    <group delimiter=" ">
+                      <text variable="publisher" strip-periods="true"/>
+                      <text macro="issued-year"/>
+                    </group>
+                  </else-if>
+                  <else-if type="webpage post-weblog" match="any">
+                    <text variable="container-title" font-style="italic"/>
+                    <text macro="issued-full"/>
+                  </else-if>
+                  <else-if type="interview" match="any">
+                    <text macro="issued-full"/>
+                  </else-if>
+                  <else>
+                    <group delimiter=" ">
+                      <text variable="publisher" strip-periods="true"/>
+                      <text macro="issued-year"/>
+                    </group>
+                  </else>
+                </choose>
+              </else>
+            </choose>
+          </group>
+          <choose>
+            <if type="report interview manuscript" match="any">
+              <group delimiter=" ">
+                <text variable="genre" strip-periods="true"/>
+                <text variable="number"/>
+              </group>
+            </if>
+          </choose>
+        </group>
+      </if>
+    </choose>
+  </macro>
+  <macro name="looseleaf-note">
+    <choose>
+      <if type="book">
+        <choose>
+          <if variable="publisher issued" match="none">
+            <choose>
+              <if variable="locator">
+                <group delimiter=" ">
+                  <label variable="locator" form="short" strip-periods="true"/>
+                  <text variable="locator"/>
+                  <text variable="edition" prefix="(" suffix=")"/>
+                </group>
+              </if>
+            </choose>
+          </if>
+        </choose>
+      </if>
+    </choose>
+  </macro>
+  <macro name="volume-book">
+    <choose>
+      <if type="book chapter report" match="any">
+        <group delimiter=" ">
+          <label variable="volume" form="short" strip-periods="true"/>
+          <text variable="volume"/>
+        </group>
+      </if>
+    </choose>
+  </macro>
+  <macro name="edition">
+    <choose>
+      <if is-numeric="edition">
+        <group delimiter=" ">
+          <number variable="edition" form="ordinal"/>
+          <label variable="edition" form="short" strip-periods="true"/>
+        </group>
+      </if>
+      <else>
+        <text variable="edition" strip-periods="true"/>
+      </else>
+    </choose>
+  </macro>
+  <macro name="book-container">
+    <choose>
+      <if type="chapter paper-conference entry-encyclopedia" match="any">
+        <group>
+          <text macro="editor-chapter" prefix=" "/>
+          <text variable="container-title" font-style="italic" prefix=", "/>
+        </group>
+      </if>
+    </choose>
+  </macro>
+  <macro name="broadcast-container">
+    <choose>
+      <if type="broadcast" match="any">
+        <text variable="container-title" font-style="italic"/>
+      </if>
+    </choose>
+  </macro>
+  <macro name="bill-number">
+    <choose>
+      <if type="bill">
+        <text variable="number" prefix="[" suffix="]"/>
+      </if>
+    </choose>
+  </macro>
+  <macro name="article-case-info">
+    <choose>
+      <if type="article-journal article-magazine article-newspaper legal_case" match="any">
+        <group delimiter=", ">
+          <!--Assume that only cases with a Medium Neutral Citation have a docket number -->
+          <choose>
+            <if variable="authority number" match="all">
+              <group delimiter=" ">
+                <text variable="authority" form="short" strip-periods="true"/>
+                <text variable="number"/>
+              </group>
+            </if>
+          </choose>
+          <group delimiter=" ">
+            <text variable="volume"/>
+            <choose>
+              <if type="legal_case">
+                <choose>
+                  <if variable="container-title">
+                    <text variable="container-title" form="short" strip-periods="true"/>
+                  </if>
+                </choose>
+              </if>
+              <else-if type="article-magazine article-newspaper" match="any">
+                <text variable="container-title" font-style="italic"/>
+              </else-if>
+              <else>
+                <text variable="container-title"/>
+              </else>
+            </choose>
+          </group>
+        </group>
+      </if>
+    </choose>
+  </macro>
+  <macro name="page-first">
+    <choose>
+      <if type="chapter report paper-conference" match="none">
+        <text variable="page-first"/>
+      </if>
+    </choose>
+  </macro>
+  <macro name="court">
+    <choose>
+      <if type="legal_case">
+        <choose>
+          <if variable="number" match="none">
+            <text variable="authority" prefix="(" suffix=")" strip-periods="true"/>
+          </if>
+        </choose>
+      </if>
+    </choose>
+  </macro>
+  <macro name="locator-basic">
+    <group delimiter=" ">
+      <choose>
+        <if locator="page" match="none">
+          <label variable="locator" form="short" strip-periods="true"/>
+        </if>
+      </choose>
+      <text variable="locator"/>
+    </group>
+  </macro>
+  <macro name="locator-space">
+    <choose>
+      <if type="legal_case">
+        <choose>
+          <if locator="paragraph">
+            <text variable="locator" prefix="[" suffix="]"/>
+          </if>
+          <else-if variable="number container-title volume page" match="all"/>
+          <else-if variable="authority">
+            <text variable="locator"/>
+          </else-if>
+        </choose>
+      </if>
+      <else-if type="legislation book article-journal article-magazine" match="none">
+        <text macro="locator-basic"/>
+      </else-if>
+      <else-if type="book">
+        <choose>
+          <if variable="issued publisher" match="any">
+            <text macro="locator-basic"/>
+          </if>
+        </choose>
+      </else-if>
+    </choose>
+  </macro>
+  <macro name="locator-comma">
+    <choose>
+      <if type="legal_case">
+        <choose>
+          <if locator="paragraph" match="none">
+            <choose>
+              <if variable="authority" match="none">
+                <text variable="locator"/>
+              </if>
+              <else-if variable="number container-title volume page" match="all">
+                <text variable="locator"/>
+              </else-if>
+            </choose>
+          </if>
+        </choose>
+      </if>
+      <else-if type="legislation article-journal article-magazine" match="any">
+        <text macro="locator-basic"/>
+      </else-if>
+    </choose>
+  </macro>
+  <!--Others -->
+  <macro name="treaty-catchall">
+    <choose>
+      <if type="treaty">
+        <text variable="genre"/>
+      </if>
+    </choose>
+  </macro>
+  <macro name="URL">
+    <choose>
+      <if type="legal_case legislation bill" match="none">
+        <choose>
+          <if variable="URL">
+            <group delimiter=" ">
+              <text variable="URL" prefix="&lt;" suffix="&gt;"/>
+              <group delimiter=" ">
+                <text term="accessed"/>
+                <date variable="accessed" form="text"/>
+              </group>
+            </group>
+          </if>
+        </choose>
+      </if>
+    </choose>
+  </macro>
+  <macro name="author-count">
+    <names variable="author">
+      <name form="count"/>
+      <substitute>
+        <names variable="editor"/>
+      </substitute>
+    </names>
+  </macro>
+  <macro name="sort-type">
+    <!--This should just sort secondary sources first. I'm leaving the rest from AGLC for simplicity-->
+    <choose>
+      <if type="book chapter paper-conference article-magazine article-newspaper article-journal manuscript report speech entry-encyclopedia" match="any">
+        <text value="1"/>
+      </if>
+      <else-if type="legal_case">
+        <text value="2"/>
+        <text variable="title"/>
+      </else-if>
+      <else-if type="bill legislation" match="any">
+        <text value="3"/>
+        <choose>
+          <if type="legislation">
+            <text variable="title"/>
+          </if>
+        </choose>
+      </else-if>
+      <else-if type="treaty">
+        <text value="4"/>
+      </else-if>
+      <else>
+        <text value="1"/>
+      </else>
+    </choose>
+  </macro>
+  <citation et-al-min="4" et-al-use-first="1">
+    <layout suffix="." delimiter="; ">
+      <choose>
+        <if position="ibid-with-locator">
+          <group delimiter=" ">
+            <text term="ibid" strip-periods="true" text-case="lowercase"/>
+            <text variable="locator"/>
+          </group>
+        </if>
+        <else-if position="ibid">
+          <text term="ibid" strip-periods="true" text-case="lowercase"/>
+        </else-if>
+        <else-if position="subsequent">
+          <choose>
+            <if type="legal_case bill legislation treaty" match="any">
+              <!--don't use short form and above note for legal citations -->
+              <group delimiter=" ">
+                <text macro="author-note"/>
+                <text macro="title-short"/>
+                <text macro="looseleaf-note"/>
+                <text variable="first-reference-note-number" prefix="(n " suffix=")"/>
+                <text macro="locator-space"/>
+              </group>
+            </if>
+            <else>
+              <group delimiter=" ">
+                <group delimiter=", ">
+                  <text macro="author-short"/>
+                  <choose>
+                    <if disambiguate="true">
+                      <text macro="title-short"/>
+                    </if>
+                  </choose>
+                </group>
+                <text variable="first-reference-note-number" prefix="(n " suffix=")"/>
+                <text macro="locator-basic"/>
+              </group>
+            </else>
+          </choose>
+        </else-if>
+        <else>
+          <!--general whole citation -->
+          <group delimiter=" ">
+            <group delimiter=", ">
+              <group delimiter=" ">
+                <group delimiter=", ">
+                  <text macro="author-note"/>
+                  <group>
+                    <text macro="title"/>
+                    <text macro="book-container"/>
+                  </group>
+                  <text macro="broadcast-container"/>
+                  <text macro="volume-book"/>
+                  <text macro="looseleaf-note"/>
+                </group>
+                <group delimiter=" ">
+                  <text macro="date-parenthesis"/>
+                  <text macro="bill-number"/>
+                  <text macro="article-case-info"/>
+                  <text macro="publisher"/>
+                </group>
+              </group>
+              <text macro="treaty-catchall"/>
+            </group>
+            <group delimiter=", ">
+              <group delimiter=" ">
+                <text macro="page-first"/>
+                <text macro="court"/>
+                <text macro="locator-space"/>
+              </group>
+              <text macro="locator-comma"/>
+            </group>
+            <text macro="URL"/>
+          </group>
+        </else>
+      </choose>
+    </layout>
+  </citation>
+  <bibliography et-al-min="4" et-al-use-first="1" subsequent-author-substitute="&#8212;&#8212;">
+    <sort>
+      <key macro="sort-type"/>
+      <key macro="author" names-min="1" names-use-first="1"/>
+      <key macro="author-count" names-min="2" names-use-first="2"/>
+      <key macro="author"/>
+      <key variable="issued"/>
+      <key variable="title"/>
+    </sort>
+    <layout>
+      <group delimiter=" ">
+        <group delimiter=", ">
+          <group delimiter=" ">
+            <group delimiter=", ">
+              <text macro="author"/>
+              <group>
+                <text macro="title"/>
+                <text macro="book-container"/>
+              </group>
+              <text macro="broadcast-container"/>
+              <text macro="volume-book"/>
+              <text macro="looseleaf-note"/>
+            </group>
+            <group delimiter=" ">
+              <text macro="date-parenthesis"/>
+              <text macro="bill-number"/>
+              <text macro="article-case-info"/>
+              <text macro="publisher"/>
+            </group>
+          </group>
+          <text macro="treaty-catchall"/>
+        </group>
+        <group delimiter=" ">
+          <text macro="page-first"/>
+          <text macro="court"/>
+        </group>
+        <text macro="URL"/>
+      </group>
+    </layout>
+  </bibliography>
+</style>
diff --git a/test/command/pandoc-citeproc-118.md b/test/command/pandoc-citeproc-118.md
new file mode 100644
--- /dev/null
+++ b/test/command/pandoc-citeproc-118.md
@@ -0,0 +1,27 @@
+```
+% pandoc --citeproc -t markdown-citations
+---
+references:
+- director:
+    family: Hitchcock
+    given: Alfred
+  id: nbn
+  issued:
+    year: 1959
+  language: 'en-US'
+  publisher: 'Metro-Goldwyn-Mayer'
+  publisher-place: USA
+  title: North by Northwest
+  type: motion_picture
+---
+
+[@nbn] is a spy thriller film.
+^D
+(Hitchcock 1959) is a spy thriller film.
+
+:::: {#refs .references .csl-bib-body .hanging-indent}
+::: {#ref-nbn .csl-entry}
+Hitchcock, Alfred, dir. 1959. *North by Northwest*. Metro-Goldwyn-Mayer.
+:::
+::::
+```
diff --git a/test/command/pandoc-citeproc-119.md b/test/command/pandoc-citeproc-119.md
new file mode 100644
--- /dev/null
+++ b/test/command/pandoc-citeproc-119.md
@@ -0,0 +1,38 @@
+```
+% pandoc --citeproc -t markdown-citations
+---
+bibliography: 'command/averroes.bib'
+csl: command/apa.csl
+---
+
+@averroes/bland; @averroes/hannes; @averroes/hercz
+
+References {#references .unnumbered}
+==========
+^D
+Averroes (1982); Averroes (1892); Averroes (1869)
+
+# References {#references .unnumbered}
+
+:::::: {#refs .references .csl-bib-body .hanging-indent entry-spacing="0" line-spacing="2"}
+::: {#ref-averroes/hercz .csl-entry}
+Averroes. (1869). *Drei Abhandlungen über die Conjunction des separaten
+Intellects mit dem Menschen: Von Averroes (Vater und Sohn), aus dem
+Arabischen übersetzt von Samuel Ibn Tibbon*. (J. Hercz, Ed. & Trans.).
+Berlin: S. Hermann.
+:::
+
+::: {#ref-averroes/hannes .csl-entry}
+Averroes. (1892). *Des Averroës Abhandlung: "Über die Möglichkeit der
+Conjunktion" oder "Über den materiellen Intellekt"*. (L. Hannes, Ed. &
+Trans.). Halle an der Saale: C. A. Kaemmerer.
+:::
+
+::: {#ref-averroes/bland .csl-entry}
+Averroes. (1982). *The epistle on the possibility of conjunction with
+the active intellect by Ibn Rushd with the commentary of Moses Narboni*.
+(K. P. Bland, Ed. & Trans.). New York: Jewish Theological Seminary of
+America.
+:::
+::::::
+```
diff --git a/test/command/pandoc-citeproc-13.md b/test/command/pandoc-citeproc-13.md
new file mode 100644
--- /dev/null
+++ b/test/command/pandoc-citeproc-13.md
@@ -0,0 +1,29 @@
+```
+% pandoc --citeproc -t markdown-citations
+---
+csl: 'command/chicago-note-bibliography.csl'
+references:
+- author:
+    family: Author
+    given:
+    - Ann
+  container-title: Journal
+  id: item1
+  issued:
+  - year: 2011
+  title: Title
+  type: 'article-newspaper'
+---
+
+Foo [@item1].
+^D
+Foo.[^1]
+
+:::: {#refs .references .csl-bib-body .hanging-indent entry-spacing="0"}
+::: {#ref-item1 .csl-entry}
+Author, Ann. "Title." *Journal*, 2011.
+:::
+::::
+
+[^1]: Author, "Title."
+```
diff --git a/test/command/pandoc-citeproc-136.md b/test/command/pandoc-citeproc-136.md
new file mode 100644
--- /dev/null
+++ b/test/command/pandoc-citeproc-136.md
@@ -0,0 +1,23 @@
+```
+% pandoc --citeproc -t markdown-citations
+---
+references:
+- id: stanze
+  type: book
+  issued:
+  - year: 1547
+  title: Stanze in lode della donna brutta
+  publisher-place: Florence
+  language: it-IT
+...
+
+@stanze is an anoynymous work.
+^D
+*Stanze in lode della donna brutta* (1547) is an anoynymous work.
+
+:::: {#refs .references .csl-bib-body .hanging-indent}
+::: {#ref-stanze .csl-entry}
+*Stanze in lode della donna brutta*. 1547. Florence.
+:::
+::::
+```
diff --git a/test/command/pandoc-citeproc-14.md b/test/command/pandoc-citeproc-14.md
new file mode 100644
--- /dev/null
+++ b/test/command/pandoc-citeproc-14.md
@@ -0,0 +1,77 @@
+```
+% pandoc --citeproc -t markdown-citations
+---
+references:
+- author:
+    family: Pelikan
+    given: Jaroslav
+  container-title: 'The Christian tradition: A history of the
+    development of doctrine'
+  id: CTv1c2
+  issued:
+  - year: 1971
+  language: 'en-US'
+  page: '34-56'
+  publisher: University of Chicago Press
+  publisher-place: Chicago
+  title: Chapter two
+  type: chapter
+  volume: 1
+  volume-title: 'The emergence of the Catholic tradition (100--600)'
+- author:
+    family: Pelikan
+    given: Jaroslav
+  container-title: 'The Christian tradition: A history of the
+    development of doctrine'
+  id: CTv1
+  issued:
+  - year: 1971
+  language: 'en-US'
+  publisher: University of Chicago Press
+  publisher-place: Chicago
+  title: 'The emergence of the Catholic tradition (100--600)'
+  type: book
+  volume: 1
+- author:
+    family: Pelikan
+    given: Jaroslav
+  id: CT
+  issued:
+  - year: 1971
+  language: 'en-US'
+  publisher: University of Chicago Press
+  publisher-place: Chicago
+  title: 'The Christian tradition: A history of the development of
+    doctrine'
+  type: book
+---
+
+Foo [@CT, 1:12]. Bar [@CTv1, 12]. Baz [@CTv1c2, 12].
+
+References {#references .unnumbered}
+==========
+^D
+Foo (Pelikan 1971b, 1:12). Bar (Pelikan 1971c, 12). Baz (Pelikan 1971a,
+12).
+
+# References {#references .unnumbered}
+
+:::::: {#refs .references .csl-bib-body .hanging-indent}
+::: {#ref-CTv1c2 .csl-entry}
+Pelikan, Jaroslav. 1971a. "Chapter Two." In *The Emergence of the
+Catholic Tradition (100--600)*, vol. 1 of *The Christian Tradition: A
+History of the Development of Doctrine*. University of Chicago Press.
+:::
+
+::: {#ref-CT .csl-entry}
+Pelikan, Jaroslav. 1971b. *The Christian Tradition: A History of the
+Development of Doctrine*. University of Chicago Press.
+:::
+
+::: {#ref-CTv1 .csl-entry}
+Pelikan, Jaroslav. 1971c. *The Emergence of the Catholic Tradition
+(100--600)*. In *The Christian Tradition: A History of the Development
+of Doctrine*, vol. 1. University of Chicago Press.
+:::
+::::::
+```
diff --git a/test/command/pandoc-citeproc-152.md b/test/command/pandoc-citeproc-152.md
new file mode 100644
--- /dev/null
+++ b/test/command/pandoc-citeproc-152.md
@@ -0,0 +1,63 @@
+```
+% pandoc --citeproc -t markdown-citations
+---
+csl: command/apa.csl
+references:
+- URL: 'http://geekfeminism.wikia.com/wiki/Geek_Feminism'
+  accessed:
+    day: 10
+    month: 4
+    year: 2013
+  container-title: Geek Feminism
+  custom2: ok.mm
+  id: Feminism2013gf
+  issued:
+    day: 10
+    month: 4
+    year: 2013
+  keyword: gender
+  title: Geek Feminism
+  type: webpage
+- URL: 'http://geekfeminism.wikia.com/wiki/Category:Communities'
+  accessed:
+    day: 19
+    month: 10
+    year: 2011
+  container-title: Geek Feminism
+  custom2: gender.mm
+  id: Feminism2011ces
+  issued:
+    day: 14
+    month: 8
+    year: 2011
+  keyword: gender
+  title: Communities
+  type: 'entry-encyclopedia'
+---
+
+Test
+====
+
+I have two citations [@Feminism2013gf; @Feminism2011ces].
+
+References
+==========
+^D
+# Test
+
+I have two citations ("Communities," 2011; "Geek Feminism," 2013).
+
+# References {#references .unnumbered}
+
+::::: {#refs .references .csl-bib-body .hanging-indent entry-spacing="0" line-spacing="2"}
+::: {#ref-Feminism2011ces .csl-entry}
+Communities. (2011, August 14). In *Geek Feminism*. Retrieved from
+<http://geekfeminism.wikia.com/wiki/Category:Communities>
+:::
+
+::: {#ref-Feminism2013gf .csl-entry}
+Geek Feminism. (2013, April 10). *Geek Feminism*. Retrieved April 10,
+2013, from <http://geekfeminism.wikia.com/wiki/Geek_Feminism>
+:::
+:::::
+```
diff --git a/test/command/pandoc-citeproc-160.md b/test/command/pandoc-citeproc-160.md
new file mode 100644
--- /dev/null
+++ b/test/command/pandoc-citeproc-160.md
@@ -0,0 +1,44 @@
+```
+% pandoc --citeproc -t markdown-citations
+---
+csl: command/issue160.csl
+references:
+- author:
+  - family: Doe
+    given: Jane
+  citation-label: Jane11
+  id: item1
+  issued:
+    year: 2011
+  title: A book
+  type: book
+---
+
+No citation-label
+-----------------
+
+Foo [@item1].
+
+Expected
+--------
+
+> Foo \[Jane11\].
+>
+> \[Jane11\] Jane Doe. A book. 2011.
+^D
+## No citation-label
+
+Foo \[Jane11\].
+
+## Expected
+
+> Foo \[Jane11\].
+>
+> \[Jane11\] Jane Doe. A book. 2011.
+
+:::: {#refs .references .csl-bib-body}
+::: {#ref-item1 .csl-entry}
+\[Jane11\] Jane Doe. A book. 2011.
+:::
+::::
+```
diff --git a/test/command/pandoc-citeproc-175.md b/test/command/pandoc-citeproc-175.md
new file mode 100644
--- /dev/null
+++ b/test/command/pandoc-citeproc-175.md
@@ -0,0 +1,43 @@
+```
+% pandoc --citeproc -t markdown-citations
+---
+references:
+- author:
+  - family: Doe
+    given: Jane
+  container-title: A magazine
+  id: item1
+  issued:
+  - month: 1
+    year: 2011
+  - month: 2
+    year: 2011
+  page: '33-44'
+  title: A title
+  type: 'article-magazine'
+---
+
+Missing en-dash between months
+------------------------------
+
+Foo [@item1].
+
+Expected
+--------
+
+> Doe, Jane. 2011. "A Title." *A Magazine*, January--February.
+^D
+## Missing en-dash between months
+
+Foo (Doe 2011).
+
+## Expected
+
+> Doe, Jane. 2011. "A Title." *A Magazine*, January--February.
+
+:::: {#refs .references .csl-bib-body .hanging-indent}
+::: {#ref-item1 .csl-entry}
+Doe, Jane. 2011. "A Title." *A Magazine*, January--February, 33--44.
+:::
+::::
+```
diff --git a/test/command/pandoc-citeproc-197.md b/test/command/pandoc-citeproc-197.md
new file mode 100644
--- /dev/null
+++ b/test/command/pandoc-citeproc-197.md
@@ -0,0 +1,31 @@
+```
+% pandoc --citeproc -t markdown-citations
+---
+csl: 'command/chicago-fullnote-bibliography.csl'
+nocite: '@test'
+references:
+- editor:
+  - family: Abelard
+    given: Peter
+  id: test
+  issued:
+    date-parts:
+    - - 1989
+  publisher: Clarendon Press
+  publisher-place: Oxford
+  title: Test
+  type: book
+---
+
+This is a test [@test].
+^D
+This is a test.[^1]
+
+:::: {#refs .references .csl-bib-body .hanging-indent entry-spacing="0"}
+::: {#ref-test .csl-entry}
+Abelard, Peter, ed. *Test*. Oxford: Clarendon Press, 1989.
+:::
+::::
+
+[^1]: Peter Abelard, ed., *Test* (Oxford: Clarendon Press, 1989).
+```
diff --git a/test/command/pandoc-citeproc-213.md b/test/command/pandoc-citeproc-213.md
new file mode 100644
--- /dev/null
+++ b/test/command/pandoc-citeproc-213.md
@@ -0,0 +1,33 @@
+```
+% pandoc --citeproc -t markdown-citations
+---
+csl: 'command/harvard-university-of-kent.csl'
+references:
+- author:
+  - family: Doe
+    given: Ann
+  collection-title: The collection title
+  dimensions: 789 pp.
+  id: doe1
+  issued:
+  - year: 1999
+  publisher: The publisher
+  title: Title
+  type: book
+---
+
+Foo [@doe1].
+
+References {#references .unnumbered}
+==========
+^D
+Foo (Doe 1999).
+
+# References {#references .unnumbered}
+
+:::: {#refs .references .csl-bib-body .hanging-indent}
+::: {#ref-doe1 .csl-entry}
+Doe, A. (1999). *Title*. The collection title. The publisher. 789 pp.
+:::
+::::
+```
diff --git a/test/command/pandoc-citeproc-25.md b/test/command/pandoc-citeproc-25.md
new file mode 100644
--- /dev/null
+++ b/test/command/pandoc-citeproc-25.md
@@ -0,0 +1,30 @@
+```
+% pandoc --citeproc -t markdown-citations
+---
+references:
+- author:
+  - family: Author
+    given: Al
+  id: item1
+  issued:
+    date-parts:
+    - - 1998
+  title: 'foo bar baz: bazbaz foo'
+  type: 'article-journal'
+---
+
+Foo [@item1].
+
+References {#references .unnumbered}
+==========
+^D
+Foo (Author 1998).
+
+# References {#references .unnumbered}
+
+:::: {#refs .references .csl-bib-body .hanging-indent}
+::: {#ref-item1 .csl-entry}
+Author, Al. 1998. *Foo Bar Baz: Bazbaz Foo*.
+:::
+::::
+```
diff --git a/test/command/pandoc-citeproc-250.md b/test/command/pandoc-citeproc-250.md
new file mode 100644
--- /dev/null
+++ b/test/command/pandoc-citeproc-250.md
@@ -0,0 +1,21 @@
+```
+% pandoc --citeproc -t markdown-citations
+---
+link-citations: true
+references:
+- author:
+    family: Doe
+  id: doe
+  title: Title
+---
+
+[@doe]
+^D
+([Doe, n.d.](#ref-doe))
+
+:::: {#refs .references .csl-bib-body .hanging-indent}
+::: {#ref-doe .csl-entry}
+Doe. n.d. *Title*.
+:::
+::::
+```
diff --git a/test/command/pandoc-citeproc-27.md b/test/command/pandoc-citeproc-27.md
new file mode 100644
--- /dev/null
+++ b/test/command/pandoc-citeproc-27.md
@@ -0,0 +1,38 @@
+```
+% pandoc --citeproc -t markdown-citations
+---
+csl: command/science.csl
+references:
+- author:
+  - family: AuthorOne
+    given: Joe
+  - family: AuthorTwo
+    given: Jill
+  container-title: Some Journal
+  id: AuthorOne2014
+  issue: X
+  issued:
+    date-parts:
+    - - 2014
+  page: 'XXXX-YYYY'
+  title: Sample Title
+  type: 'article-journal'
+  volume: XX
+---
+
+Minimal example
+===============
+
+Here is some text that needs a citation [@AuthorOne2014].
+^D
+# Minimal example
+
+Here is some text that needs a citation (*1*).
+
+:::: {#refs .references .csl-bib-body}
+::: {#ref-AuthorOne2014 .csl-entry}
+[1. ]{.csl-left-margin}[J. AuthorOne, J. AuthorTwo, *Some Journal*, in
+press.]{.csl-right-inline}
+:::
+::::
+```
diff --git a/test/command/pandoc-citeproc-292.md b/test/command/pandoc-citeproc-292.md
new file mode 100644
--- /dev/null
+++ b/test/command/pandoc-citeproc-292.md
@@ -0,0 +1,43 @@
+```
+% pandoc --citeproc -t markdown-citations
+---
+csl: 'command/sage-harvard.csl'
+references:
+- author:
+    family: Doe
+  id: doe
+  issued:
+    year: 2007
+  type: article
+- author:
+    family: Zoe
+  id: zoe
+  issued:
+  - year: 2009
+  type: article
+- author:
+    family: Roe
+  id: roe
+  issued:
+  - year: 2007
+  type: article
+---
+
+[@zoe; @roe; see for comparison @doe, p. 3]
+^D
+(Roe, 2007; Zoe, 2009; see for comparison Doe, 2007: 3)
+
+:::::: {#refs .references .csl-bib-body .hanging-indent}
+::: {#ref-doe .csl-entry}
+Doe (2007).
+:::
+
+::: {#ref-roe .csl-entry}
+Roe (2007).
+:::
+
+::: {#ref-zoe .csl-entry}
+Zoe (2009).
+:::
+::::::
+```
diff --git a/test/command/pandoc-citeproc-301.md b/test/command/pandoc-citeproc-301.md
new file mode 100644
--- /dev/null
+++ b/test/command/pandoc-citeproc-301.md
@@ -0,0 +1,25 @@
+```
+% pandoc --citeproc -t markdown-citations
+---
+references:
+- id: test
+  title: Essays presented to N.R. Ker (On Art)
+- id: test2
+  title: '*Test:* An experiment: An abridgement'
+---
+
+@test; @test2
+^D
+*Essays Presented to N.R. Ker (On Art)* (n.d.); **Test:* An Experiment:
+An Abridgement* (n.d.)
+
+::::: {#refs .references .csl-bib-body .hanging-indent}
+::: {#ref-test .csl-entry}
+*Essays Presented to N.R. Ker (On Art)*. n.d.
+:::
+
+::: {#ref-test2 .csl-entry}
+**Test:* An Experiment: An Abridgement*. n.d.
+:::
+:::::
+```
diff --git a/test/command/pandoc-citeproc-307.md b/test/command/pandoc-citeproc-307.md
new file mode 100644
--- /dev/null
+++ b/test/command/pandoc-citeproc-307.md
@@ -0,0 +1,31 @@
+```
+% pandoc --citeproc -t markdown-citations
+---
+lang: 'fr-FR'
+references:
+- author:
+  - family: Bazin
+    given: André
+  container-title: Cahiers du cinéma
+  id: bazin_cybernetique_1954
+  issue: 36
+  issued:
+    date-parts:
+    - - 1954
+      - 6
+  page: '22-27'
+  title: 'La Cybernétique d''André Cayatte'
+  type: 'article-journal'
+---
+
+Bonjour[@bazin_cybernetique_1954] !
+^D
+Bonjour(Bazin 1954) !
+
+:::: {#refs .references .csl-bib-body .hanging-indent}
+::: {#ref-bazin_cybernetique_1954 .csl-entry}
+Bazin, André. 1954. « La Cybernétique d'André Cayatte ». *Cahiers du
+cinéma*, nᵒ 36 (juin): 22‑27.
+:::
+::::
+```
diff --git a/test/command/pandoc-citeproc-31.md b/test/command/pandoc-citeproc-31.md
new file mode 100644
--- /dev/null
+++ b/test/command/pandoc-citeproc-31.md
@@ -0,0 +1,49 @@
+```
+% pandoc --citeproc -t markdown-citations
+---
+csl: command/oscola.csl
+references:
+- DOI: 10.1086/504343
+  author:
+  - family: Olson
+    given: Hope A.
+  container-title: Library Quarterly
+  id: item1
+  issue: 1
+  issued:
+    date-parts:
+    - - 2006
+  page: '19-35'
+  title: 'Codes, costs, and critiques: The organization of information
+    in *Library Quarterly*, 1931--2004'
+  title-short: 'Codes, costs, and critiques'
+  type: 'article-magazine'
+  volume: 76
+- id: item2
+  title: Second title
+---
+
+Foo [@item1]. Bar [@item2]. Baz [@item1].
+^D
+Foo.[^1] Bar.[^2] Baz.[^3]
+
+::::: {#refs .references .csl-bib-body}
+::: {#ref-item1 .csl-entry}
+Olson HA, '[Codes, Costs, and Critiques: The Organization of Information
+in *Library Quarterly*, 1931--2004](https://doi.org/10.1086/504343)'
+(2006) 76 *Library Quarterly* 19
+:::
+
+::: {#ref-item2 .csl-entry}
+'Second Title'
+:::
+:::::
+
+[^1]: Hope A Olson, 'Codes, Costs, and Critiques: The Organization of
+    Information in *Library Quarterly*, 1931--2004' (2006) 76 *Library
+    Quarterly* 19.
+
+[^2]: 'Second Title'.
+
+[^3]: Olson (n 1).
+```
diff --git a/test/command/pandoc-citeproc-312.md b/test/command/pandoc-citeproc-312.md
new file mode 100644
--- /dev/null
+++ b/test/command/pandoc-citeproc-312.md
@@ -0,0 +1,171 @@
+```
+% pandoc --citeproc -t markdown-citations
+---
+csl: command/apa.csl
+nocite: '@*'
+references:
+- author:
+  - literal: NN
+  id: 'Y'
+  issued:
+  - year: 1950
+  title: 'Date: Year'
+  title-short: Date
+  type: webpage
+- author:
+  - literal: NN
+  id: Y/Y
+  issued:
+  - year: 1951
+  - year: 1952
+  title: 'Date range: Year'
+  title-short: Date range
+  type: webpage
+- author:
+  - literal: NN
+  id: YM
+  issued:
+  - month: 1
+    year: 1953
+  title: 'Date: Year+month'
+  title-short: Date
+  type: webpage
+- author:
+  - literal: NN
+  id: YM/YM
+  issued:
+  - month: 1
+    year: 1954
+  - month: 2
+    year: 1955
+  title: 'Date range: Year+month'
+  title-short: Date range
+  type: webpage
+- author:
+  - literal: NN
+  id: YM/YM_same
+  issued:
+  - month: 1
+    year: 1956
+  - month: 2
+    year: 1956
+  title: 'Date range: Year+month, same year'
+  title-short: Date range
+  type: webpage
+- author:
+  - literal: NN
+  id: YMD
+  issued:
+  - day: 15
+    month: 1
+    year: 1958
+  title: 'Date: Year+month+day'
+  title-short: Date
+  type: webpage
+- author:
+  - literal: NN
+  id: YMD/YMD
+  issued:
+  - day: 15
+    month: 1
+    year: 1959
+  - day: 16
+    month: 2
+    year: 1960
+  title: 'Date range: Year+month+day'
+  title-short: Date range
+  type: webpage
+- author:
+  - literal: NN
+  id: YMD/YMD_same
+  issued:
+  - day: 15
+    month: 1
+    year: 1961
+  - day: 16
+    month: 1
+    year: 1962
+  title: 'Date range: Year+month+day, same month'
+  title-short: Date range
+  type: webpage
+- author:
+  - literal: NN
+  id: YS
+  issued:
+  - season: 3
+    year: 1963
+  title: 'Date: Year+season'
+  title-short: Date
+  type: webpage
+- author:
+  - literal: NN
+  id: YS/YS
+  issued:
+  - season: 1
+    year: 1964
+  - season: 4
+    year: 1965
+  title: 'Date range: Year+season'
+  title-short: Date range
+  type: webpage
+- author:
+  - literal: NN
+  id: YS/YS_same
+  issued:
+  - season: 2
+    year: 1966
+  - season: 4
+    year: 1966
+  title: 'Date range: Year+season, same year'
+  title-short: Date range
+  type: webpage
+---
+
+^D
+:::::::::::::: {#refs .references .csl-bib-body .hanging-indent entry-spacing="0" line-spacing="2"}
+::: {#ref-Y .csl-entry}
+NN. (1950). Date: Year.
+:::
+
+::: {#ref-Y/Y .csl-entry}
+NN. (1951--1952). Date range: Year.
+:::
+
+::: {#ref-YM .csl-entry}
+NN. (1953, January). Date: Year+month.
+:::
+
+::: {#ref-YM/YM .csl-entry}
+NN. (1954--1955, January--February). Date range: Year+month.
+:::
+
+::: {#ref-YM/YM_same .csl-entry}
+NN. (1956, January--February). Date range: Year+month, same year.
+:::
+
+::: {#ref-YMD .csl-entry}
+NN. (1958, January 15). Date: Year+month+day.
+:::
+
+::: {#ref-YMD/YMD .csl-entry}
+NN. (1959--1960, January 15--February 16). Date range: Year+month+day.
+:::
+
+::: {#ref-YMD/YMD_same .csl-entry}
+NN. (1961--1962, January 15--16). Date range: Year+month+day, same
+month.
+:::
+
+::: {#ref-YS .csl-entry}
+NN. (1963, Autumn). Date: Year+season.
+:::
+
+::: {#ref-YS/YS .csl-entry}
+NN. (1964--1965, Spring--Winter). Date range: Year+season.
+:::
+
+::: {#ref-YS/YS_same .csl-entry}
+NN. (1966, Summer--Winter). Date range: Year+season, same year.
+:::
+::::::::::::::
+```
diff --git a/test/command/pandoc-citeproc-320.md b/test/command/pandoc-citeproc-320.md
new file mode 100644
--- /dev/null
+++ b/test/command/pandoc-citeproc-320.md
@@ -0,0 +1,254 @@
+```
+% pandoc --citeproc -t markdown-citations
+---
+csl: command/apa.csl
+references:
+- author:
+  - family: Benjamin
+    given: A. S.
+  id: itemA1
+- author:
+  - family: Yaakov
+    given: D.
+    non-dropping-particle: ben
+  id: itemA2
+- author:
+  - family: Brown
+    given: J. R.
+  id: itemA3
+- author:
+  - family: Browning
+    given: A. R.
+  id: itemA4
+- author:
+  - family: Girard
+    given: 'J.-B.'
+  id: itemA5
+- author:
+  - family: 'Girard-Perregaux'
+    given: A. S.
+  id: itemA6
+- author:
+  - family: Ibn Abdulaziz
+    given: T.
+  id: itemA7
+- author:
+  - family: Ibn Nidal
+    given: A. K. M.
+  id: itemA8
+- author:
+  - family: López
+    given: M. E.
+  id: itemA9
+- author:
+  - family: López de Molina
+    given: G.
+  id: itemA10
+- author:
+  - family: Singh
+    given: Y.
+  id: itemA11
+- author:
+  - family: Singh Siddhu
+    given: N.
+  id: itemA12
+- author:
+  - family: Villafuerte
+    given: S. A.
+  id: itemA13
+- author:
+  - family: 'Villa-Lobos'
+    given: J.
+  id: itemA14
+- author:
+  - family: Macalister
+    given: Donald
+  id: itemB1
+- author:
+  - family: MacAlister
+    given: Paul
+  id: itemB2
+- author:
+  - family: Macauley
+    given: Catharine
+  id: itemB3
+- author:
+  - family: Macmillan
+    given: Harold
+  id: itemB4
+- author:
+  - family: Madison
+    given: James
+  id: itemB5
+- author:
+  - family: McAllister
+    given: Ward
+  id: itemB6
+- author:
+  - family: McAuley
+    given: Catherine
+  id: itemB7
+- author:
+  - family: McMillan
+    given: Edwin M.
+  id: itemB8
+- author:
+  - family: 'Sainte-Beuve'
+    given: 'Charles-Augustin'
+  id: itemC1
+- author:
+  - family: 'Saint-Gaudens'
+    given: Augustus
+  id: itemC2
+- author:
+  - family: 'Saint-Saëns'
+    given: Camille
+  id: itemC3
+- author:
+  - dropping-particle: de
+    family: San Martin
+    given: José
+  id: itemC4
+- author:
+  - family: St. Denis
+    given: Ruth
+  id: itemC5
+- author:
+  - family: St. Laurent
+    given: Louis Stephen
+  id: itemC6
+---
+
+Foo
+[@itemA1; @itemA2; @itemA3; @itemA4; @itemA5; @itemA6; @itemA7; @itemA8; @itemA9; @itemA10; @itemA11; @itemA12; @itemA13; @itemA14].
+
+Foo
+[@itemB1; @itemB2; @itemB3; @itemB4; @itemB5; @itemB6; @itemB7; @itemB8].
+
+Foo [@itemC1; @itemC2; @itemC3; @itemC4; @itemC5; @itemC6].
+^D
+Foo (ben Yaakov, n.d.; Benjamin, n.d.; Brown, n.d.; Browning, n.d.;
+Girard, n.d.; Girard-Perregaux, n.d.; Ibn Abdulaziz, n.d.; Ibn Nidal,
+n.d.; López de Molina, n.d.; López, n.d.; Singh Siddhu, n.d.; Singh,
+n.d.; Villafuerte, n.d.; Villa-Lobos, n.d.).
+
+Foo (Macalister, n.d.; MacAlister, n.d.; Macauley, n.d.; Macmillan,
+n.d.; Madison, n.d.; McAllister, n.d.; McAuley, n.d.; McMillan, n.d.).
+
+Foo (Sainte-Beuve, n.d.; Saint-Gaudens, n.d.; Saint-Saëns, n.d.; San
+Martin, n.d.; St. Denis, n.d.; St. Laurent, n.d.).
+
+::::::::::::::::::::::::::::::: {#refs .references .csl-bib-body .hanging-indent entry-spacing="0" line-spacing="2"}
+::: {#ref-itemA2 .csl-entry}
+ben Yaakov, D. (n.d.).
+:::
+
+::: {#ref-itemA1 .csl-entry}
+Benjamin, A. S. (n.d.).
+:::
+
+::: {#ref-itemA3 .csl-entry}
+Brown, J. R. (n.d.).
+:::
+
+::: {#ref-itemA4 .csl-entry}
+Browning, A. R. (n.d.).
+:::
+
+::: {#ref-itemA5 .csl-entry}
+Girard, J.-B. (n.d.).
+:::
+
+::: {#ref-itemA6 .csl-entry}
+Girard-Perregaux, A. S. (n.d.).
+:::
+
+::: {#ref-itemA7 .csl-entry}
+Ibn Abdulaziz, T. (n.d.).
+:::
+
+::: {#ref-itemA8 .csl-entry}
+Ibn Nidal, A. K. M. (n.d.).
+:::
+
+::: {#ref-itemA10 .csl-entry}
+López de Molina, G. (n.d.).
+:::
+
+::: {#ref-itemA9 .csl-entry}
+López, M. E. (n.d.).
+:::
+
+::: {#ref-itemB1 .csl-entry}
+Macalister, D. (n.d.).
+:::
+
+::: {#ref-itemB2 .csl-entry}
+MacAlister, P. (n.d.).
+:::
+
+::: {#ref-itemB3 .csl-entry}
+Macauley, C. (n.d.).
+:::
+
+::: {#ref-itemB4 .csl-entry}
+Macmillan, H. (n.d.).
+:::
+
+::: {#ref-itemB5 .csl-entry}
+Madison, J. (n.d.).
+:::
+
+::: {#ref-itemB6 .csl-entry}
+McAllister, W. (n.d.).
+:::
+
+::: {#ref-itemB7 .csl-entry}
+McAuley, C. (n.d.).
+:::
+
+::: {#ref-itemB8 .csl-entry}
+McMillan, E. M. (n.d.).
+:::
+
+::: {#ref-itemC1 .csl-entry}
+Sainte-Beuve, C.-A. (n.d.).
+:::
+
+::: {#ref-itemC2 .csl-entry}
+Saint-Gaudens, A. (n.d.).
+:::
+
+::: {#ref-itemC3 .csl-entry}
+Saint-Saëns, C. (n.d.).
+:::
+
+::: {#ref-itemC4 .csl-entry}
+San Martin, J. de. (n.d.).
+:::
+
+::: {#ref-itemA12 .csl-entry}
+Singh Siddhu, N. (n.d.).
+:::
+
+::: {#ref-itemA11 .csl-entry}
+Singh, Y. (n.d.).
+:::
+
+::: {#ref-itemC5 .csl-entry}
+St. Denis, R. (n.d.).
+:::
+
+::: {#ref-itemC6 .csl-entry}
+St. Laurent, L. S. (n.d.).
+:::
+
+::: {#ref-itemA13 .csl-entry}
+Villafuerte, S. A. (n.d.).
+:::
+
+::: {#ref-itemA14 .csl-entry}
+Villa-Lobos, J. (n.d.).
+:::
+:::::::::::::::::::::::::::::::
+```
diff --git a/test/command/pandoc-citeproc-320a.md b/test/command/pandoc-citeproc-320a.md
new file mode 100644
--- /dev/null
+++ b/test/command/pandoc-citeproc-320a.md
@@ -0,0 +1,80 @@
+```
+% pandoc --citeproc -t plain
+---
+references:
+- author:
+  - family: ʾUdhrī
+    given: Jamīl
+    non-dropping-particle: 'al-'
+  issued: 2000
+  title: hamza
+  id: item1
+- author:
+  - family: ʿUdhrī
+    given: Jamīl
+    non-dropping-particle: 'al-'
+  issued: 2000
+  title: ayn
+  id: item2
+- author:
+  - family: "'Udhrī"
+    given: Jamīl
+    non-dropping-particle: 'al-'
+  issued: 2000
+  title: straight apostrophe
+  id: item3
+- author:
+  - family: '‘Udhrī'
+    given: Jamīl
+    non-dropping-particle: 'al-'
+  issued: 2000
+  title: inverted curly apostrophe = opening single curly quote (for ayn)
+  id: item4
+- author:
+  - family: '’Udhrī'
+    given: Jamīl
+    non-dropping-particle: 'al-'
+  issued: 2000
+  title: curly apostrophe = closing single curly quote (for hamza)
+  id: item5
+- author:
+  - family: Uch
+    given: Ann
+  id: item6
+  issued: 2000
+- author:
+  - family: Uebel
+    given: Joe
+  id: item7
+  issued: 2000
+- author:
+  - family: Zzz
+    given: Zoe
+  id: item8
+  issued: 2000
+---
+
+Foo [@item1; @item2; @item3; @item4; @item5; @item6; @item7; @item8].
+^D
+Foo (al-ʾUdhrī 2000; al-ʿUdhrī 2000; al-’Udhrī 2000b, 2000a; al-‘Udhrī
+2000; Uch 2000; Uebel 2000; Zzz 2000).
+
+Uch, Ann. 2000.
+
+‘Udhrī, Jamīl al-. 2000. Inverted Curly Apostrophe = Opening Single
+Curly Quote (for Ayn).
+
+ʿUdhrī, Jamīl al-. 2000. Ayn.
+
+’Udhrī, Jamīl al-. 2000a. Curly Apostrophe = Closing Single Curly Quote
+(for Hamza).
+
+ʾUdhrī, Jamīl al-. 2000. Hamza.
+
+’Udhrī, Jamīl al-. 2000b. Straight Apostrophe.
+
+Uebel, Joe. 2000.
+
+Zzz, Zoe. 2000.
+
+```
diff --git a/test/command/pandoc-citeproc-322.md b/test/command/pandoc-citeproc-322.md
new file mode 100644
--- /dev/null
+++ b/test/command/pandoc-citeproc-322.md
@@ -0,0 +1,35 @@
+```
+% pandoc --citeproc -t markdown-citations
+---
+csl: command/annales.csl
+references:
+- author:
+  - family: Timmory
+    given: François
+  container-title: 'L''Écran français'
+  id: timmory\_\_justice_1950
+  issue: 272
+  issued:
+  - day: 25
+    month: 9
+    year: 1950
+  language: 'fr-FR'
+  page: 12
+  title: '*Justice est faite* : soyons justes'
+  type: 'article-journal'
+---
+
+Foo [@timmory__justice_1950].
+^D
+Foo.[^1]
+
+:::: {#refs .references .csl-bib-body}
+::: {#ref-timmory__justice_1950 .csl-entry}
+François [Timmory]{.smallcaps}, « *Justice est faite* : soyons justes »,
+*L'Écran français*, 1950, nᵒ 272, p. 12.
+:::
+::::
+
+[^1]: François [Timmory]{.smallcaps}, « *Justice est faite* : soyons
+    justes », *L'Écran français*, 1950, nᵒ 272, p. 12.
+```
diff --git a/test/command/pandoc-citeproc-325.md b/test/command/pandoc-citeproc-325.md
new file mode 100644
--- /dev/null
+++ b/test/command/pandoc-citeproc-325.md
@@ -0,0 +1,30 @@
+```
+% pandoc --citeproc -t markdown-citations
+---
+references:
+- author:
+  - family: Smith
+    given: John
+  id: item1
+  type: book
+- author:
+  - family: Smith
+    given: John
+  id: item2
+  type: book
+---
+
+[@item1; @item2]
+^D
+(Smith, n.d.-a, n.d.-b)
+
+::::: {#refs .references .csl-bib-body .hanging-indent}
+::: {#ref-item1 .csl-entry}
+Smith, John. n.d.-a.
+:::
+
+::: {#ref-item2 .csl-entry}
+Smith, John. n.d.-b.
+:::
+:::::
+```
diff --git a/test/command/pandoc-citeproc-327.md b/test/command/pandoc-citeproc-327.md
new file mode 100644
--- /dev/null
+++ b/test/command/pandoc-citeproc-327.md
@@ -0,0 +1,51 @@
+```
+% pandoc --citeproc -t markdown-citations
+---
+csl: 'command/chinese-gb7714-2005-numeric.csl'
+references:
+- ISSN: '1003-1111'
+  URL: 'http://kns.cnki.net/kns/detail/detail.aspx?QueryID=4&CurRec=4&recid=&FileName=CHAN201706006&DbName=CJFDLAST2018&DbCode=CJFQ&yx=Y&pr=&URLID=21.1110.S.20171129.1725.006'
+  abstract: '为了解辽东湾海域底栖动物次级生产力水平和时空分布特点,根据2007年的4月和10月辽东湾海域大型底栖动物调查数据,运用Brey经验公式计算大型底栖动物次级生产力和P/B值,并结合海洋生物指数方法对辽东湾海域进行生境适宜性评价。分析结果表明,该海域大型底栖动物年平均次级生产力为5.59g/(m\~2·年),年平均P/B值为3.16,辽东湾大型底栖动物次级生产力空间分布呈现出自沿岸向中部递增的趋势,P/B值空间分布与底栖动物次级生产力相反,呈现出自沿岸向中部递减的趋势,群落组成中以个体小、生活史短、代谢快的底栖动物为主。'
+  accessed:
+  - day: 27
+    month: 3
+    year: 2018
+  author:
+  - family: 李
+    given: 轶平
+  - family: 于
+    given: 旭光
+  - family: 孙
+    given: 明
+  - family: 郭
+    given: 栋
+  - family: 段
+    given: 妍
+  - family: 董
+    given: 婧
+  container-title: 水产科学
+  id: LiLiaoDongWanHaiYuDiQiDongWuCiJiShengChanLiYanJiuJiShengJingGuaYiXingPingJie2017
+  issue: 06
+  issued:
+  - year: 2017
+  keyword: '次级生产力,大型底栖动物,海洋生物指数方法,AMBI,macrozoobenthos,P/B
+    value,P/B值,secondary productivity'
+  language: 中文;
+  page: '728-734'
+  title: 辽东湾海域底栖动物次级生产力研究及生境适宜性评价
+  type: 'article-journal'
+---
+
+I referenced something here
+[@LiLiaoDongWanHaiYuDiQiDongWuCiJiShengChanLiYanJiuJiShengJingGuaYiXingPingJie2017]
+^D
+I referenced something here^\[1\]^
+
+:::: {#refs .references .csl-bib-body entry-spacing="0"}
+::: {#ref-LiLiaoDongWanHaiYuDiQiDongWuCiJiShengChanLiYanJiuJiShengJingGuaYiXingPingJie2017 .csl-entry}
+[\[1\] ]{.csl-left-margin}[李轶平, 于旭光, 孙明, 等.
+[辽东湾海域底栖动物次级生产力研究及生境适宜性评价](http://kns.cnki.net/kns/detail/detail.aspx?QueryID=4&CurRec=4&recid=&FileName=CHAN201706006&DbName=CJFDLAST2018&DbCode=CJFQ&yx=Y&pr=&URLID=21.1110.S.20171129.1725.006)\[J\].
+水产科学, 2017(6): 728～734.]{.csl-right-inline}
+:::
+::::
+```
diff --git a/test/command/pandoc-citeproc-338.md b/test/command/pandoc-citeproc-338.md
new file mode 100644
--- /dev/null
+++ b/test/command/pandoc-citeproc-338.md
@@ -0,0 +1,34 @@
+```
+% pandoc --citeproc -t markdown-citations
+---
+csl: 'command/din-1505-2.csl'
+lang: de
+nocite: '@*'
+pagetitle: Citation
+references:
+- ISBN: '978-3-642-32078-1'
+  author:
+  - family: Wolfinger
+    given: Christine
+  edition: '11., vollst. überarb. Aufl.'
+  id: 'item-1'
+  issued:
+  - year: 2013
+  keyword: UNIX; LINUX
+  number-of-pages: 'XVIII, 529 S. : Ill., graph. Darst.'
+  publisher: Springer Vieweg
+  publisher-place: 'Berlin \[u.a.\]'
+  title: 'Keine Angst vor Linux, Unix: ein Lehrbuch für Linux- und
+    Unix-Anwender'
+  type: book
+---
+
+^D
+:::: {#refs .references .csl-bib-body .hanging-indent}
+::: {#ref-item-1 .csl-entry}
+[Wolfinger, Christine]{.smallcaps}: *Keine Angst vor Linux, Unix: ein
+Lehrbuch für Linux- und Unix-Anwender*. 11., vollst. überarb. Aufl.
+Aufl. Berlin \[u.a.\] : Springer Vieweg, 2013 --- ISBN 978-3-642-32078-1
+:::
+::::
+```
diff --git a/test/command/pandoc-citeproc-351.md b/test/command/pandoc-citeproc-351.md
new file mode 100644
--- /dev/null
+++ b/test/command/pandoc-citeproc-351.md
@@ -0,0 +1,27 @@
+```
+% pandoc --citeproc -t markdown-citations
+---
+csl: 'command/zeitschrift-fur-kunstgeschichte.csl'
+references:
+- editor:
+  - family: Nietzsche
+    given: Friedrich
+  id: Nie72
+  issued:
+  - year: 1872
+  title: Die geburt
+  type: book
+---
+
+@Nie72
+^D
+Friedrich Nietzsche (ed.)[^1]
+
+:::: {#refs .references .csl-bib-body .hanging-indent entry-spacing="0"}
+::: {#ref-Nie72 .csl-entry}
+Nietzsche, Friedrich (ed.), *Die geburt*, 1872.
+:::
+::::
+
+[^1]: *Die geburt*, 1872.
+```
diff --git a/test/command/pandoc-citeproc-356.md b/test/command/pandoc-citeproc-356.md
new file mode 100644
--- /dev/null
+++ b/test/command/pandoc-citeproc-356.md
@@ -0,0 +1,20 @@
+```
+% pandoc --citeproc -t markdown-citations
+---
+references:
+- author:
+  - family: Alice
+  id: foo
+  issued:
+  - year: 2042
+  other-ids:
+  - bar
+  - doz
+  type: book
+---
+
+[@bar]
+^D
+2> [WARNING] Citeproc: citation bar not found
+(**bar?**)
+```
diff --git a/test/command/pandoc-citeproc-360.md b/test/command/pandoc-citeproc-360.md
new file mode 100644
--- /dev/null
+++ b/test/command/pandoc-citeproc-360.md
@@ -0,0 +1,35 @@
+```
+% pandoc --citeproc -t markdown-citations
+---
+csl: 'command/chicago-fullnote-bibliography.csl'
+references:
+- author:
+  - family: 'L''Estrange'
+    given: Michael
+  - family: Merchant
+    given: Stephen
+  id: lestrange2017
+  issued:
+  - day: 18
+    month: 7
+    year: 2017
+  language: 'en-US'
+  title: 2017 Independent Intelligence Review
+  title-short: Independent Intelligence Review
+  type: report
+---
+
+[@lestrange2017]
+^D
+[^1]
+
+:::: {#refs .references .csl-bib-body .hanging-indent entry-spacing="0"}
+::: {#ref-lestrange2017 .csl-entry}
+L'Estrange, Michael, and Stephen Merchant. "2017 Independent
+Intelligence Review," July 18, 2017.
+:::
+::::
+
+[^1]: Michael L'Estrange and Stephen Merchant, "2017 Independent
+    Intelligence Review," July 18, 2017.
+```
diff --git a/test/command/pandoc-citeproc-361.md b/test/command/pandoc-citeproc-361.md
new file mode 100644
--- /dev/null
+++ b/test/command/pandoc-citeproc-361.md
@@ -0,0 +1,80 @@
+```
+% pandoc --citeproc -t markdown-citations
+---
+csl: command/locators.csl
+references:
+- id: citekey
+  title: Title
+  type: 'article-journal'
+- id: other
+  title: Other
+  type: 'article-journal'
+suppress-bibliography: true
+---
+
+Content[@citekey]
+
+Content[@citekey, 1]
+
+Content[@citekey, 2]
+
+Content[@citekey, 2]
+
+Content[@citekey 2]
+
+Content[@citekey, p. 2]
+
+Content[@citekey p. 2]
+
+Content[@citekey]
+
+Content[@other]
+
+Content[@citekey, 3]
+
+Content[@citekey, 3]
+^D
+Content[^1]
+
+Content[^2]
+
+Content[^3]
+
+Content[^4]
+
+Content[^5]
+
+Content[^6]
+
+Content[^7]
+
+Content[^8]
+
+Content[^9]
+
+Content[^10]
+
+Content[^11]
+
+[^1]: Title.
+
+[^2]: Ibid-with-locator {1}.
+
+[^3]: Ibid-with-locator {2}.
+
+[^4]: Ibid.
+
+[^5]: Ibid.
+
+[^6]: Ibid.
+
+[^7]: Ibid.
+
+[^8]: Subsequent.
+
+[^9]: Other.
+
+[^10]: Subsequent {3}.
+
+[^11]: Ibid.
+```
diff --git a/test/command/pandoc-citeproc-365.md b/test/command/pandoc-citeproc-365.md
new file mode 100644
--- /dev/null
+++ b/test/command/pandoc-citeproc-365.md
@@ -0,0 +1,39 @@
+```
+% pandoc --citeproc -t markdown-citations
+---
+csl: 'command/le-tapuscrit-note.csl'
+references:
+- ISBN: '978-2-912573-52-0'
+  author:
+  - family: Le Gras
+    given: Gwénaëlle
+  call-number: 'Tolbiac - Rez de Jardin - Littérature et art - Magasin -
+    2010-82178'
+  collection-title: 'Jeux d''acteurs'
+  id: legras_michel_2010
+  issued:
+  - year: 2010
+  language: fre
+  number-of-pages: 128
+  publisher: Scope
+  publisher-place: Paris
+  source: 'BnF Catalogue général (http://catalogue.bnf.fr)'
+  title: 'Michel Simon : l''art de la disgrâce'
+  title-short: Michel Simon
+  type: book
+---
+
+Foo [@legras_michel_2010].
+^D
+Foo.[^1]
+
+:::: {#refs .references .csl-bib-body}
+::: {#ref-legras_michel_2010 .csl-entry}
+[Le Gras]{.smallcaps} Gwénaëlle, *Michel Simon : l'art de la disgrâce*,
+Paris, Scope (coll. « Jeux d'acteurs »), 2010, 128 p.
+:::
+::::
+
+[^1]: Gwénaëlle Le Gras, *Michel Simon : l'art de la disgrâce*, Paris,
+    Scope, 2010, 128 p.
+```
diff --git a/test/command/pandoc-citeproc-371.md b/test/command/pandoc-citeproc-371.md
new file mode 100644
--- /dev/null
+++ b/test/command/pandoc-citeproc-371.md
@@ -0,0 +1,40 @@
+```
+% pandoc --citeproc -t markdown-citations
+---
+references:
+- author:
+  - family: Doe
+    given: Jane
+  id: item1
+  status: in press
+  title: Title one
+  type: book
+- author:
+  - family: Doe
+    given: Jane
+  id: item2
+  issued:
+  - year: 2018
+  title: Title two
+  type: book
+---
+
+Foo [@item2; @item1].
+
+References {#references .unnumbered}
+==========
+^D
+Foo (Doe 2018, in press).
+
+# References {#references .unnumbered}
+
+::::: {#refs .references .csl-bib-body .hanging-indent}
+::: {#ref-item2 .csl-entry}
+Doe, Jane. 2018. *Title Two*.
+:::
+
+::: {#ref-item1 .csl-entry}
+Doe, Jane. In press. *Title One*.
+:::
+:::::
+```
diff --git a/test/command/pandoc-citeproc-38.md b/test/command/pandoc-citeproc-38.md
new file mode 100644
--- /dev/null
+++ b/test/command/pandoc-citeproc-38.md
@@ -0,0 +1,29 @@
+```
+% pandoc --citeproc -t markdown-citations
+---
+references:
+- author:
+  - family: Doe
+    given: Ann
+  - family: Doe
+    given: Ben
+  - family: Roe
+    given: Ron
+  id: a
+  issued:
+    date-parts:
+    - - 2007
+  title: Title
+  type: 'article-journal'
+---
+
+@a
+^D
+Doe et al. (2007)
+
+:::: {#refs .references .csl-bib-body .hanging-indent}
+::: {#ref-a .csl-entry}
+Doe, Ann, Ben Doe, and Ron Roe. 2007. *Title*.
+:::
+::::
+```
diff --git a/test/command/pandoc-citeproc-386.md b/test/command/pandoc-citeproc-386.md
new file mode 100644
--- /dev/null
+++ b/test/command/pandoc-citeproc-386.md
@@ -0,0 +1,36 @@
+```
+% pandoc --citeproc -t markdown-citations
+---
+csl: 'command/advanced-optical-materials.csl'
+references:
+- DOI: 10.1038/lsa.2012.20
+  ISSN: '2047-7538'
+  author:
+  - family: Ding
+    given: K.
+  - family: Ning
+    given: C. Z.
+  container-title: Light Sci. Appl.
+  id: ding_metallic_2012
+  issue: 7
+  issued:
+  - month: 7
+    year: 2012
+  page: 'e20-e20'
+  title: 'Metallic subwavelength-cavity semiconductor nanolasers'
+  type: 'article-journal'
+  volume: 1
+---
+
+@ding_metallic_2012
+^D
+^\[1\]^
+
+:::: {#refs .references .csl-bib-body entry-spacing="0" line-spacing="2"}
+::: {#ref-ding_metallic_2012 .csl-entry}
+[\[1\] ]{.csl-left-margin}[[K. Ding, C. Z. Ning, *Light Sci. Appl.*
+**2012**, *1*,
+e20](https://doi.org/10.1038/lsa.2012.20).]{.csl-right-inline}
+:::
+::::
+```
diff --git a/test/command/pandoc-citeproc-392.md b/test/command/pandoc-citeproc-392.md
new file mode 100644
--- /dev/null
+++ b/test/command/pandoc-citeproc-392.md
@@ -0,0 +1,29 @@
+```
+% pandoc --citeproc -t markdown-citations
+---
+csl: command/vancouver.csl
+references:
+- author:
+  - family: James
+    given: M.R.C.E.L.
+  id: james
+- author:
+  - family: MacFarlane
+    given: J. G.
+  id: macfarlane
+---
+
+@james; @macfarlane
+^D
+(1); (2)
+
+::::: {#refs .references .csl-bib-body}
+::: {#ref-james .csl-entry}
+[1. ]{.csl-left-margin}[James MRCEL. ]{.csl-right-inline}
+:::
+
+::: {#ref-macfarlane .csl-entry}
+[2. ]{.csl-left-margin}[MacFarlane JG. ]{.csl-right-inline}
+:::
+:::::
+```
diff --git a/test/command/pandoc-citeproc-399.md b/test/command/pandoc-citeproc-399.md
new file mode 100644
--- /dev/null
+++ b/test/command/pandoc-citeproc-399.md
@@ -0,0 +1,45 @@
+```
+% pandoc --citeproc -t markdown-citations
+---
+csl: command/style399.csl
+references:
+- author:
+  - family: One
+  id: one
+- author:
+  - family: Two
+  id: two
+- author:
+  - family: Three
+  id: three
+- author:
+  - family: Four
+  id: four
+- author:
+  - family: Five
+  id: five
+- author:
+  - family: Six
+  id: six
+- author:
+  - family: Seven
+  id: seven
+- author:
+  - family: Eight
+  id: eight
+- author:
+  - family: Nine
+  id: nine
+- author:
+  - family: Ten
+  id: ten
+- author:
+  - family: Eleven
+  id: eleven
+---
+
+Inline citation
+[@one; @two; @three; @four; @five; @six; @seven; @eight; @nine; @ten; @eleven].
+^D
+Inline citation \[1,2,3,4,5,6,7,8,9,10,11\].
+```
diff --git a/test/command/pandoc-citeproc-401.md b/test/command/pandoc-citeproc-401.md
new file mode 100644
--- /dev/null
+++ b/test/command/pandoc-citeproc-401.md
@@ -0,0 +1,59 @@
+```
+% pandoc --citeproc -t markdown-citations
+---
+references:
+- id: haslanger2012SocialConstructionDebunking
+  type: chapter
+  author:
+  - family: Haslanger
+    given: Sally
+  issued:
+  - year: 2012
+  original-date:
+  - year: 2003
+  title: 'Social Construction: The ‘Debunking’ Project'
+  title-short: Social Construction
+  container-title: 'Resisting Reality: Social Construction and Social Critique'
+  publisher: Oxford University Press
+  publisher-place: Oxford
+  event-place: Oxford
+  page: 113–138
+  ISBN: 978-0-19-989262-4
+
+- id: haslanger2012FeminismMetaphysicsNegotiating
+  type: chapter
+  author:
+  - family: Haslanger
+    given: Sally
+  issued:
+  - year: 2012
+  original-date:
+  - year: 2000
+  title: 'Feminism in Metaphysics: Negotiating the Natural'
+  container-title: 'Resisting Reality: Social Construction and Social Critique'
+  publisher: Oxford University Press
+  publisher-place: Oxford
+  event-place: Oxford
+  page: 139–157
+  ISBN: 978-0-19-989262-4
+  language: en
+...
+
+Haslanger [-@haslanger2012SocialConstructionDebunking; @haslanger2012FeminismMetaphysicsNegotiating] says...
+^D
+Haslanger (\[2003\] 2012, \[2000\] 2012) says...
+
+::::: {#refs .references .csl-bib-body .hanging-indent}
+::: {#ref-haslanger2012FeminismMetaphysicsNegotiating .csl-entry}
+Haslanger, Sally. (2000) 2012. "Feminism in Metaphysics: Negotiating the
+Natural." In *Resisting Reality: Social Construction and Social
+Critique*. Oxford University Press.
+:::
+
+::: {#ref-haslanger2012SocialConstructionDebunking .csl-entry}
+Haslanger, Sally. (2003) 2012. "Social Construction: The 'Debunking'
+Project." In *Resisting Reality: Social Construction and Social
+Critique*. Oxford University Press.
+:::
+:::::
+```
diff --git a/test/command/pandoc-citeproc-408.md b/test/command/pandoc-citeproc-408.md
new file mode 100644
--- /dev/null
+++ b/test/command/pandoc-citeproc-408.md
@@ -0,0 +1,39 @@
+```
+% pandoc --citeproc -t markdown-citations
+---
+references:
+- id: smith1
+  type: article-journal
+  author:
+  - family: Smith
+    given: Mary
+  issued:
+  - year: 2019
+  title: Foo
+
+- id: smithsmith
+  type: article-journal
+  author:
+  - family: Smith
+    given: Mary
+  - family: Smith
+    given: John
+  issued:
+  - year: 2019
+  title: Foo bar
+...
+
+[@smithsmith; @smith1]
+^D
+(Smith and Smith 2019; Smith 2019)
+
+::::: {#refs .references .csl-bib-body .hanging-indent}
+::: {#ref-smith1 .csl-entry}
+Smith, Mary. 2019. *Foo*.
+:::
+
+::: {#ref-smithsmith .csl-entry}
+Smith, Mary, and John Smith. 2019. *Foo Bar*.
+:::
+:::::
+```
diff --git a/test/command/pandoc-citeproc-416.md b/test/command/pandoc-citeproc-416.md
new file mode 100644
--- /dev/null
+++ b/test/command/pandoc-citeproc-416.md
@@ -0,0 +1,60 @@
+```
+% pandoc --citeproc -t markdown-citations
+Blah blah [@item1; @item2; @item3].
+
+# References {-}
+
+---
+title: The Title
+references:
+- id: item1
+  type: article-newspaper
+  author:
+  - family: Doe
+    given: J.
+  issued:
+  - year: 2010
+    month: 12
+    day: 13
+  title: The title
+- id: item2
+  type: article-newspaper
+  author:
+  - family: Doe
+    given: J.
+  issued:
+  - year: 2007
+    month: 12
+    day: 12
+  - year: 2007
+    month: 12
+    day: 13
+  title: The title
+- id: item3
+  type: article-newspaper
+  author:
+  - family: Doe
+    given: J.
+  issued:
+  - year: 2008
+  title: The title
+...
+^D
+Blah blah (Doe 2010, 2007, 2008).
+
+# References {#references .unnumbered}
+
+:::::: {#refs .references .csl-bib-body .hanging-indent}
+::: {#ref-item2 .csl-entry}
+Doe, J. 2007. *The Title*. December 12--13.
+:::
+
+::: {#ref-item3 .csl-entry}
+Doe, J. 2008. *The Title*.
+:::
+
+::: {#ref-item1 .csl-entry}
+Doe, J. 2010. *The Title*. December 13.
+:::
+::::::
+```
diff --git a/test/command/pandoc-citeproc-437.md b/test/command/pandoc-citeproc-437.md
new file mode 100644
--- /dev/null
+++ b/test/command/pandoc-citeproc-437.md
@@ -0,0 +1,23 @@
+```
+% pandoc --citeproc -t markdown-citations
+---
+csl: command/issue437.csl
+references:
+- author:
+  - family: Smith
+    given: John
+  id: hirt2009
+  issued:
+  - year: 2009
+  publisher: Publishing House
+  publisher-place: Lausanne
+  title: Some Book
+  type: book
+---
+
+> Here is a quote. [@hirt2009]
+^D
+> Here is a quote.[^1]
+
+[^1]: John Smith, Some Book, Lausanne, 2009
+```
diff --git a/test/command/pandoc-citeproc-47.md b/test/command/pandoc-citeproc-47.md
new file mode 100644
--- /dev/null
+++ b/test/command/pandoc-citeproc-47.md
@@ -0,0 +1,112 @@
+```
+% pandoc --citeproc -t markdown-citations
+---
+references:
+- author:
+  - family: Doe
+    given: A.
+  id: doe
+  issued:
+    date-parts:
+    - - 2000
+  title: Title
+  type: book
+- author:
+  - family: Doe
+    given: A.
+  - family: Poe
+    given: A.
+  id: doepoe
+  issued:
+    date-parts:
+    - - 2000
+  title: Title
+  type: book
+- editor:
+  - family: Doe
+    given: A.
+  id: 'doe-ed'
+  issued:
+    date-parts:
+    - - 2000
+  title: Title
+  type: book
+- author:
+  - family: Doe
+    given: A.
+  - family: Loe
+    given: A.
+  - family: Toe
+    given: A.
+  id: doeloetoe
+  issued:
+    date-parts:
+    - - 2000
+  title: Title
+  type: book
+---
+
+Foo [@doe]. Bar [@doepoe]. Foo [@doe-ed]. Bar [@doeloetoe].
+
+Expected output:
+
+> Doe, A. 2000a. Title.
+>
+> ---------, ed. 2000b. Title.
+>
+> Doe, A., A. Loe, and A. Toe. 2000. Title.
+>
+> Doe, A., and A. Poe. 2000. Title.
+
+(See CMoS, 16e, 15.16, "Single author versus several authors---reference
+list order": "Successive entries by two or more authors in which only
+the first author's name is the same are alphabetized according to the
+coauthors' last names (regardless of how many coauthors there are)." and
+15.18, "The 3-em dash with edited, translated, or compiled works": "The
+chronological order is maintained, regardless of the added abbreviation.
+\[ed., trans., comp., or whatever\]"
+
+References {#references .unnumbered}
+==========
+^D
+Foo (Doe 2000a). Bar (Doe and Poe 2000). Foo (Doe 2000b). Bar (Doe et
+al. 2000).
+
+Expected output:
+
+> Doe, A. 2000a. Title.
+>
+> ---------, ed. 2000b. Title.
+>
+> Doe, A., A. Loe, and A. Toe. 2000. Title.
+>
+> Doe, A., and A. Poe. 2000. Title.
+
+(See CMoS, 16e, 15.16, "Single author versus several authors---reference
+list order": "Successive entries by two or more authors in which only
+the first author's name is the same are alphabetized according to the
+coauthors' last names (regardless of how many coauthors there are)." and
+15.18, "The 3-em dash with edited, translated, or compiled works": "The
+chronological order is maintained, regardless of the added abbreviation.
+\[ed., trans., comp., or whatever\]"
+
+# References {#references .unnumbered}
+
+::::::: {#refs .references .csl-bib-body .hanging-indent}
+::: {#ref-doe .csl-entry}
+Doe, A. 2000a. *Title*.
+:::
+
+::: {#ref-doe-ed .csl-entry}
+Doe, A., ed. 2000b. *Title*.
+:::
+
+::: {#ref-doeloetoe .csl-entry}
+Doe, A., A. Loe, and A. Toe. 2000. *Title*.
+:::
+
+::: {#ref-doepoe .csl-entry}
+Doe, A., and A. Poe. 2000. *Title*.
+:::
+:::::::
+```
diff --git a/test/command/pandoc-citeproc-51.md b/test/command/pandoc-citeproc-51.md
new file mode 100644
--- /dev/null
+++ b/test/command/pandoc-citeproc-51.md
@@ -0,0 +1,45 @@
+```
+% pandoc --citeproc -t markdown-citations
+---
+references:
+- author:
+  - family: Doe
+    given: John
+  container-title: Journal of Something
+  id: item1
+  issued:
+    date-parts:
+    - - 1987
+    - - 1988
+  page: '12-34'
+  title: The title
+  type: 'article-journal'
+  volume: 3
+- author:
+  - family: Roe
+    given: Ron
+  container-title: Journal of Something
+  id: item2
+  issued:
+    date-parts:
+    - - 1987
+  page: '12-34'
+  title: The title
+  type: 'article-journal'
+  volume: 4
+---
+
+@item1; @item2
+^D
+Doe (1987--1988); Roe (1987)
+
+::::: {#refs .references .csl-bib-body .hanging-indent}
+::: {#ref-item1 .csl-entry}
+Doe, John. 1987--1988. "The Title." *Journal of Something* 3: 12--34.
+:::
+
+::: {#ref-item2 .csl-entry}
+Roe, Ron. 1987. "The Title." *Journal of Something* 4: 12--34.
+:::
+:::::
+```
diff --git a/test/command/pandoc-citeproc-53.md b/test/command/pandoc-citeproc-53.md
new file mode 100644
--- /dev/null
+++ b/test/command/pandoc-citeproc-53.md
@@ -0,0 +1,56 @@
+```
+% pandoc --citeproc -t markdown-citations
+---
+csl: command/archeologie-medievale.csl
+references:
+- title: Work A
+  id: a
+  issued:
+    date-parts:
+    - - 2000
+  author:
+  - given: John
+    family: Doe
+  type: book
+- title: Work B
+  id: b
+  issued:
+    date-parts:
+    - - 1990
+  author:
+  - given: Jane
+    family: Roe
+  type: book
+---
+@a @a @b @b @a @a @b @b
+^D
+Doe[^1] Doe[^2] Roe[^3] Roe[^4] Doe[^5] Doe[^6] Roe[^7] Roe[^8]
+
+::::: {#refs .references .csl-bib-body}
+::: {#ref-a .csl-entry}
+[[Doe J.]{.smallcaps} ]{.csl-block}
+[2000, *Work A*,.]{.csl-left-margin}
+:::
+
+::: {#ref-b .csl-entry}
+[[Roe J.]{.smallcaps} ]{.csl-block}
+[1990, *Work B*,.]{.csl-left-margin}
+:::
+:::::
+
+[^1]: 2000
+
+[^2]: *Ibid.*
+
+[^3]: 1990
+
+[^4]: *Ibid.*
+
+[^5]: 2000
+
+[^6]: *Ibid.*
+
+[^7]: 1990
+
+[^8]: *Ibid.*
+```
diff --git a/test/command/pandoc-citeproc-57.md b/test/command/pandoc-citeproc-57.md
new file mode 100644
--- /dev/null
+++ b/test/command/pandoc-citeproc-57.md
@@ -0,0 +1,37 @@
+```
+% pandoc --citeproc -t markdown-citations
+---
+csl: 'command/chicago-author-date-with-original-date-and-status.csl'
+references:
+- author:
+  - family: Faraday
+    given: Carry
+  container-title: Seven Trips beyond the Asteroid Belt
+  editor:
+  - family: Oring
+    given: James
+  id: 'Faraday-forthcoming'
+  publisher: Launch Press
+  publisher-place: 'Cape Canaveral, FL'
+  status: forthcoming
+  title: Protean photography
+  type: chapter
+---
+
+[@Faraday-forthcoming]
+
+References
+==========
+^D
+(Faraday, forthcoming)
+
+# References {#references .unnumbered}
+
+:::: {#refs .references .csl-bib-body .hanging-indent entry-spacing="0"}
+::: {#ref-Faraday-forthcoming .csl-entry}
+Faraday, Carry. Forthcoming. "Protean Photography." In *Seven Trips
+Beyond the Asteroid Belt*, edited by James Oring. Cape Canaveral, FL:
+Launch Press.
+:::
+::::
+```
diff --git a/test/command/pandoc-citeproc-58.md b/test/command/pandoc-citeproc-58.md
new file mode 100644
--- /dev/null
+++ b/test/command/pandoc-citeproc-58.md
@@ -0,0 +1,32 @@
+```
+% pandoc --citeproc -t markdown-citations
+---
+csl: command/issue58.csl
+references:
+- id: stanze
+  issued:
+    date-parts:
+    - - 1547
+  language: 'it-IT'
+  publisher-place: Florence
+  title: Stanze in lode della donna brutta
+  type: book
+---
+
+In this item, the title replaces the (unknown) author (see 14.79)
+[@stanze, p. 12].
+
+References
+==========
+^D
+In this item, the title replaces the (unknown) author (see 14.79)
+(*Stanze in lode della donna brutta* 1547, 12).
+
+# References {#references .unnumbered}
+
+:::: {#refs .references .csl-bib-body .hanging-indent entry-spacing="0"}
+::: {#ref-stanze .csl-entry}
+*Stanze in lode della donna brutta*. 1547. Florence.
+:::
+::::
+```
diff --git a/test/command/pandoc-citeproc-61.md b/test/command/pandoc-citeproc-61.md
new file mode 100644
--- /dev/null
+++ b/test/command/pandoc-citeproc-61.md
@@ -0,0 +1,77 @@
+```
+% pandoc --citeproc -t markdown-citations
+---
+csl: 'command/modern-humanities-research-association.csl'
+references:
+- author:
+  - family: Doe
+    given: John
+  id: doe
+  issued:
+    date-parts:
+    - - 1985
+  publisher: Publisher
+  title: Title
+  type: book
+- author:
+  - family: Roe
+    given: Rob
+  id: roe
+  issued:
+    date-parts:
+    - - 1985
+  publisher: Publisher
+  title: Title
+  type: book
+---
+
+Text
+====
+
+Foo [@doe, VIII, 89]
+
+Foo [@roe, III, 89]
+
+Foo [@doe, LVIII, 89]
+
+Foo [@roe, MVIII, 89]
+
+Foo [@doe, CL, 89]
+
+References
+==========
+^D
+# Text
+
+Foo[^1]
+
+Foo[^2]
+
+Foo[^3]
+
+Foo[^4]
+
+Foo[^5]
+
+# References {#references .unnumbered}
+
+::::: {#refs .references .csl-bib-body .hanging-indent}
+::: {#ref-doe .csl-entry}
+Doe, John, *Title* (Publisher, 1985)
+:::
+
+::: {#ref-roe .csl-entry}
+Roe, Rob, *Title* (Publisher, 1985)
+:::
+:::::
+
+[^1]: John Doe, *Title* (Publisher, 1985), VIII, 89.
+
+[^2]: Rob Roe, *Title* (Publisher, 1985), III, 89.
+
+[^3]: Doe, LVIII, 89.
+
+[^4]: Roe, MVIII, 89.
+
+[^5]: Doe, CL, 89.
+```
diff --git a/test/command/pandoc-citeproc-64.md b/test/command/pandoc-citeproc-64.md
new file mode 100644
--- /dev/null
+++ b/test/command/pandoc-citeproc-64.md
@@ -0,0 +1,24 @@
+```
+% pandoc --citeproc -t markdown-citations --csl command/chicago-fullnote-bibliography.csl
+---
+bibliography:
+- command/biblio.bib
+nocite: '[@*]'
+---
+
+^D
+:::::: {#refs .references .csl-bib-body .hanging-indent entry-spacing="0"}
+::: {#ref-item2 .csl-entry}
+Doe, John. "Article." *Journal of Generic Studies* 6 (2006): 33--34.
+:::
+
+::: {#ref-item1 .csl-entry}
+---------. *First Book*. Cambridge: Cambridge University Press, 2005.
+:::
+
+::: {#ref-пункт3 .csl-entry}
+Doe, John, and Jenny Roe. "Why Water Is Wet." In *Third Book*, edited by
+Sam Smith. Oxford: Oxford University Press, 2007.
+:::
+::::::
+```
diff --git a/test/command/pandoc-citeproc-65.md b/test/command/pandoc-citeproc-65.md
new file mode 100644
--- /dev/null
+++ b/test/command/pandoc-citeproc-65.md
@@ -0,0 +1,37 @@
+```
+% pandoc --citeproc -t markdown-citations
+---
+references:
+- ISBN: 3406493556
+  author:
+  - family: Stotz
+    given: Peter
+  call-number: 'PA25 PA2616 .H24 Abt. 2, T. 5, Bd. 2, etc'
+  collection-number: 2.5
+  collection-title: Handbuch der Altertumswissenschaft
+  event-place: Munich
+  first-reference-note-number: 1
+  id: 'stotz:1996handbuch'
+  issued:
+    literal: 1996_2004
+  language: de
+  number-of-volumes: 5
+  publisher: Beck
+  publisher-place: Munich
+  source: Library of Congress ISBN
+  title: Handbuch zur lateinischen Sprache des Mittelalters
+  title-short: Handbuch
+  type: book
+---
+
+[@stotz:1996handbuch]
+^D
+(Stotz 1996--2004)
+
+:::: {#refs .references .csl-bib-body .hanging-indent}
+::: {#ref-stotz:1996handbuch .csl-entry}
+Stotz, Peter. 1996--2004. *Handbuch zur lateinischen Sprache des
+Mittelalters*. 5 vols. Handbuch der Altertumswissenschaft, 2.5. Beck.
+:::
+::::
+```
diff --git a/test/command/pandoc-citeproc-68.md b/test/command/pandoc-citeproc-68.md
new file mode 100644
--- /dev/null
+++ b/test/command/pandoc-citeproc-68.md
@@ -0,0 +1,56 @@
+```
+% pandoc --citeproc -t markdown-citations
+---
+csl: 'command/chicago-fullnote-bibliography.csl'
+references:
+- ISBN: 0888441088
+  author:
+  - family: Goering
+    given: Joseph
+  call-number: BV4009 .W55 1992
+  collection-number: 108
+  collection-title: Studies and Texts
+  event-place: Toronto
+  first-reference-note-number: 1
+  id: 'goering:1992william'
+  issued:
+    date-parts:
+    - - 1992
+  publisher: Pontifical Institute of Mediaeval Studies
+  publisher-place: Toronto
+  source: toroprod.library.utoronto.ca Library Catalog
+  title: 'William de Montibus (c. 1140--1213): The Schools and the
+    Literature of Pastoral Care'
+  title-short: William de Montibus
+  type: book
+---
+
+\... a prose commentary [the text of fol. 9r is printed in
+@goering:1992william, pp. 501--3]. \... a collection of verses with a
+formal prose commentary [excerpts from this text were previously printed
+in @goering:1992william, p. 508--14; it was also briefly described in
+@goering:1992william, pp. 141--42] \... and finally a note starting with
+a citation [@goering:1992william, pp. 141-42].
+^D
+\... a prose commentary.[^1] \... a collection of verses with a formal
+prose commentary[^2] \... and finally a note starting with a
+citation.[^3]
+
+:::: {#refs .references .csl-bib-body .hanging-indent entry-spacing="0"}
+::: {#ref-goering:1992william .csl-entry}
+Goering, Joseph. *William de Montibus (c. 1140--1213): The Schools and
+the Literature of Pastoral Care*. Studies and Texts 108. Toronto:
+Pontifical Institute of Mediaeval Studies, 1992.
+:::
+::::
+
+[^1]: The text of fol. 9r is printed in Joseph Goering, *William de
+    Montibus (c. 1140--1213): The Schools and the Literature of Pastoral
+    Care*, Studies and Texts 108 (Toronto: Pontifical Institute of
+    Mediaeval Studies, 1992), 501--3.
+
+[^2]: Excerpts from this text were previously printed in Goering,
+    508--14; it was also briefly described in Goering, 141--42.
+
+[^3]: Goering, *William de Montibus*, 141--42.
+```
diff --git a/test/command/pandoc-citeproc-7.md b/test/command/pandoc-citeproc-7.md
new file mode 100644
--- /dev/null
+++ b/test/command/pandoc-citeproc-7.md
@@ -0,0 +1,31 @@
+```
+% pandoc --citeproc -t markdown-citations
+---
+references:
+- author:
+    family: Author
+    given:
+    - Ann
+  container-title: Journal
+  id: item1
+  issued:
+  - day: 24
+    month: 9
+    year: 2011
+  - day: 26
+    month: 9
+    year: 2011
+  title: Title
+  type: 'article-magazine'
+---
+
+@item1
+^D
+Author (2011)
+
+:::: {#refs .references .csl-bib-body .hanging-indent}
+::: {#ref-item1 .csl-entry}
+Author, Ann. 2011. "Title." *Journal*, September 24--26.
+:::
+::::
+```
diff --git a/test/command/pandoc-citeproc-70.md b/test/command/pandoc-citeproc-70.md
new file mode 100644
--- /dev/null
+++ b/test/command/pandoc-citeproc-70.md
@@ -0,0 +1,73 @@
+```
+% pandoc --citeproc -t markdown-citations
+---
+references:
+- ISBN: 9782503531465
+  author:
+  - family: 'Dinkova-Bruun'
+    given: Greti
+  call-number: CB351 .F564 2009
+  collection-number: 50
+  collection-title: Textes et études du moyen âge
+  container-title: 'Florilegium mediaevale: Études offertes à Jacqueline
+    Hamesse à l''occasion de son éméritat'
+  editor:
+  - family: Meirinhos
+    given: José Francisco
+  - family: Weijers
+    given: Olga
+  event-place: 'Louvain-la-Neuve'
+  first-reference-note-number: 1
+  id: 'bruun:2009samuel'
+  issued:
+    date-parts:
+    - - 2009
+  language: fr
+  page: '155--174'
+  publisher: 'Fédération Internationale des Instituts d''Études
+    Médiévales'
+  publisher-place: 'Louvain-la-Neuve'
+  source: Library of Congress ISBN
+  title: 'Samuel Presbyter and the Glosses to His Versification of Psalm
+    1: An Anti-Church Invective?'
+  title-short: Samuel Presbyter
+  type: chapter
+- ISSN: '0362-1529'
+  author:
+  - family: Thorndike
+    given: Lynn
+  container-title: Traditio
+  first-reference-note-number: 1
+  id: 'thorndike:1955unde'
+  issued:
+    date-parts:
+    - - 1955
+  language: la
+  note: 'ArticleType: research-article / Full publication date: 1955 /
+    Copyright © 1955 Fordham University'
+  page: '163--193'
+  source: JSTOR
+  title: Unde versus
+  type: 'article-journal'
+  volume: 11
+---
+
+[@thorndike:1955unde; @bruun:2009samuel]
+^D
+(Thorndike 1955; Dinkova-Bruun 2009)
+
+::::: {#refs .references .csl-bib-body .hanging-indent}
+::: {#ref-bruun:2009samuel .csl-entry}
+Dinkova-Bruun, Greti. 2009. "Samuel Presbyter and the Glosses to His
+Versification of Psalm 1: An Anti-Church Invective?" In *Florilegium
+mediaevale: Études offertes à Jacqueline Hamesse à l'occasion de son
+éméritat*, edited by José Francisco Meirinhos and Olga Weijers. Textes
+et études du moyen âge 50. Fédération Internationale des Instituts
+d'Études Médiévales.
+:::
+
+::: {#ref-thorndike:1955unde .csl-entry}
+Thorndike, Lynn. 1955. "Unde versus." *Traditio* 11: 163--93.
+:::
+:::::
+```
diff --git a/test/command/pandoc-citeproc-75.md b/test/command/pandoc-citeproc-75.md
new file mode 100644
--- /dev/null
+++ b/test/command/pandoc-citeproc-75.md
@@ -0,0 +1,67 @@
+```
+% pandoc --citeproc -t markdown-citations
+---
+csl: command/apa.csl
+references:
+- author:
+  - family: Doe
+    given: John
+  id: test
+  issued:
+    date-parts:
+    - - 2006
+  title: Test
+  type: 'article-journal'
+  volume: 81
+---
+
+[@test, p. 6]
+
+[@test, chap. 6]
+
+[@test, n. 6]
+
+[@test, pp. 34-36, 38-39]
+
+[@test, sec. 3]
+
+[@test, p.3]
+
+[@test, 33-35, 38-39]
+
+[@test, 14]
+
+[@test bk. VI]
+
+[@test, no. 6]
+
+[@test, nos. 6 and 7]
+^D
+(Doe, 2006, p. 6)
+
+(Doe, 2006, Chapter 6)
+
+(Doe, 2006, n. 6)
+
+(Doe, 2006, pp. 34--36, 38--39)
+
+(Doe, 2006, sec. 3)
+
+(Doe, 2006, p. 3)
+
+(Doe, 2006, pp. 33--35, 38--39)
+
+(Doe, 2006, p. 14)
+
+(Doe, 2006, bk. VI)
+
+(Doe, 2006, no. 6)
+
+(Doe, 2006, no. 6 and 7)
+
+:::: {#refs .references .csl-bib-body .hanging-indent entry-spacing="0" line-spacing="2"}
+::: {#ref-test .csl-entry}
+Doe, J. (2006). Test, *81*.
+:::
+::::
+```
diff --git a/test/command/pandoc-citeproc-76.md b/test/command/pandoc-citeproc-76.md
new file mode 100644
--- /dev/null
+++ b/test/command/pandoc-citeproc-76.md
@@ -0,0 +1,64 @@
+```
+% pandoc --citeproc -t markdown-citations
+---
+references:
+- author:
+  - family: Author
+    given: Al
+  id: item1
+  issued:
+    date-parts:
+    - - 1998
+  title: 'foo bar baz: bazbaz bar foo'
+  type: 'article-journal'
+- author:
+  - family: Author
+    given: Al
+  id: item2
+  issued:
+    date-parts:
+    - - 1998
+  title: 'foo bar baz: the bazbaz bar foo'
+  type: 'article-journal'
+- author:
+  - family: Author
+    given: Al
+  id: item3
+  issued:
+    date-parts:
+    - - 1998
+  title: 'foo bar baz: a bazbaz bar foo'
+  type: 'article-journal'
+- author:
+  - family: Author
+    given: Al
+  id: item4
+  issued:
+    date-parts:
+    - - 1998
+  title: 'foo bar baz: an abazbaz bar foo'
+  type: 'article-journal'
+---
+
+@item1, @item2, @item3, @item4
+^D
+Author (1998c), Author (1998d), Author (1998a), Author (1998b)
+
+::::::: {#refs .references .csl-bib-body .hanging-indent}
+::: {#ref-item3 .csl-entry}
+Author, Al. 1998a. *Foo Bar Baz: A Bazbaz Bar Foo*.
+:::
+
+::: {#ref-item4 .csl-entry}
+Author, Al. 1998b. *Foo Bar Baz: An Abazbaz Bar Foo*.
+:::
+
+::: {#ref-item1 .csl-entry}
+Author, Al. 1998c. *Foo Bar Baz: Bazbaz Bar Foo*.
+:::
+
+::: {#ref-item2 .csl-entry}
+Author, Al. 1998d. *Foo Bar Baz: The Bazbaz Bar Foo*.
+:::
+:::::::
+```
diff --git a/test/command/pandoc-citeproc-77.md b/test/command/pandoc-citeproc-77.md
new file mode 100644
--- /dev/null
+++ b/test/command/pandoc-citeproc-77.md
@@ -0,0 +1,67 @@
+```
+% pandoc --citeproc -t markdown-citations
+---
+csl: 'command/chicago-fullnote-bibliography.csl'
+references:
+- author:
+  - family: Doe
+    given: 'John, III'
+    parse-names: true
+  id: item1
+  type: book
+- author:
+  - family: van Gogh
+    given: Vincent
+    parse-names: true
+  id: item2
+  type: book
+- author:
+  - family: Humboldt
+    given: Alexander von
+    parse-names: true
+  id: item3
+  type: book
+- author:
+  - family: Bennett
+    given: 'Frank G.,! Jr.'
+    parse-names: true
+  id: item4
+  type: book
+- author:
+  - family: Dumboldt
+    given: 'Ezekiel, III'
+    parse-names: true
+  id: item5
+  type: book
+---
+
+[@item1; @item2; @item3; @item4; @item5]
+^D
+[^1]
+
+:::::::: {#refs .references .csl-bib-body .hanging-indent entry-spacing="0"}
+::: {#ref-item4 .csl-entry}
+Bennett, Frank G., Jr., n.d.
+:::
+
+::: {#ref-item1 .csl-entry}
+Doe, John, III, n.d.
+:::
+
+::: {#ref-item5 .csl-entry}
+Dumboldt, Ezekiel, III, n.d.
+:::
+
+::: {#ref-item2 .csl-entry}
+Gogh, Vincent van, n.d.
+:::
+
+::: {#ref-item3 .csl-entry}
+Humboldt, Alexander von, n.d.
+:::
+::::::::
+
+[^1]: John Doe III, n.d.; Vincent van Gogh, n.d.; Alexander von
+    Humboldt, n.d.; Frank G. Bennett, Jr., n.d.; Ezekiel Dumboldt III,
+    n.d.
+```
diff --git a/test/command/pandoc-citeproc-82.md b/test/command/pandoc-citeproc-82.md
new file mode 100644
--- /dev/null
+++ b/test/command/pandoc-citeproc-82.md
@@ -0,0 +1,39 @@
+```
+% pandoc --citeproc -t markdown-citations
+---
+csl: 'command/chicago-annotated-bibliography.csl'
+references:
+- URL: 'https://www.worldcat.org/'
+  accessed:
+    date-parts:
+    - - 2014
+      - 9
+      - 19
+  author:
+  - literal: OCLC
+  first-reference-note-number: 1
+  id: OCLC_i1099
+  title: WorldCat
+  type: webpage
+---
+
+Title
+=====
+
+Some text.[^1]
+
+[^1]: Comment regarding text, supported by citation [@OCLC_i1099].
+^D
+# Title
+
+Some text.[^1]
+
+:::: {#refs .references .csl-bib-body .hanging-indent entry-spacing="0"}
+::: {#ref-OCLC_i1099 .csl-entry}
+OCLC. "WorldCat." Accessed September 19, 2014.
+<https://www.worldcat.org/>.
+:::
+::::
+
+[^1]: Comment regarding text, supported by citation (OCLC, "WorldCat").
+```
diff --git a/test/command/pandoc-citeproc-87.md b/test/command/pandoc-citeproc-87.md
new file mode 100644
--- /dev/null
+++ b/test/command/pandoc-citeproc-87.md
@@ -0,0 +1,156 @@
+```
+% pandoc --citeproc -t markdown-citations
+---
+references:
+- URL: 'http://www.example.com'
+  author:
+  - family: Doe
+    given: John
+  container-title: The Web Site
+  id: item1
+  issued:
+    date-parts:
+    - - 2006
+      - 10
+      - 26
+  title: Title
+  type: webpage
+- URL: 'http://www.example.com'
+  author:
+  - family: Doe
+    given: John
+  container-title: The Web Site
+  id: item2
+  issued:
+    date-parts:
+    - - 2006
+      - 10
+      - 26
+    - - 2006
+      - 11
+      - 27
+  title: Title
+  type: webpage
+- URL: 'http://www.example.com'
+  author:
+  - family: Doe
+    given: John
+  container-title: The Web Site
+  id: item2a
+  issued:
+    date-parts:
+    - - 2006
+      - 10
+    - - 2006
+      - 11
+  title: Title
+  type: webpage
+- URL: 'http://www.example.com'
+  author:
+  - family: Doe
+    given: John
+  container-title: The Web Site
+  id: item2b
+  issued:
+    date-parts:
+    - - 2006
+      - 12
+      - 31
+    - - 2007
+      - 1
+      - 1
+  title: Title
+  type: webpage
+- URL: 'http://www.example.com'
+  author:
+  - family: Doe
+    given: John
+  container-title: The Newspaper
+  id: item3
+  issued:
+    date-parts:
+    - - 2006
+      - 10
+      - 26
+    - - 2006
+      - 11
+      - 27
+  title: Title
+  type: 'article-newspaper'
+- URL: 'http://www.example.com'
+  author:
+  - family: Doe
+    given: John
+  container-title: The Newspaper
+  id: item3b
+  issued:
+    date-parts:
+    - - 2006
+      - 10
+    - - 2006
+      - 11
+  title: Title
+  type: 'article-newspaper'
+---
+
+@item1 -- webpage, date
+
+@item2 -- webpage, date range
+
+@item2a -- webpage, date range YM
+
+@item2b -- webpage, date range across years
+
+@item3 -- article-newspaper
+
+@item3b -- article-newspaper YM
+
+References
+==========
+^D
+Doe (2006a) -- webpage, date
+
+Doe (2006c) -- webpage, date range
+
+Doe (2006b) -- webpage, date range YM
+
+Doe (2006--2007) -- webpage, date range across years
+
+Doe (2006e) -- article-newspaper
+
+Doe (2006d) -- article-newspaper YM
+
+# References {#references .unnumbered}
+
+::::::::: {#refs .references .csl-bib-body .hanging-indent}
+::: {#ref-item1 .csl-entry}
+Doe, John. 2006a. "Title." The Web Site, October 26.
+<http://www.example.com>.
+:::
+
+::: {#ref-item2a .csl-entry}
+Doe, John. 2006b. "Title." The Web Site, October--November.
+<http://www.example.com>.
+:::
+
+::: {#ref-item2 .csl-entry}
+Doe, John. 2006c. "Title." The Web Site, October 26--November 27.
+<http://www.example.com>.
+:::
+
+::: {#ref-item3b .csl-entry}
+Doe, John. 2006d. "Title." *The Newspaper*, October--November.
+<http://www.example.com>.
+:::
+
+::: {#ref-item3 .csl-entry}
+Doe, John. 2006e. "Title." *The Newspaper*, October 26--November 27.
+<http://www.example.com>.
+:::
+
+::: {#ref-item2b .csl-entry}
+Doe, John. 2006--2007. "Title." The Web Site, December 31--January 1.
+<http://www.example.com>.
+:::
+:::::::::
+```
diff --git a/test/command/pandoc-citeproc-chicago-author-date.md b/test/command/pandoc-citeproc-chicago-author-date.md
new file mode 100644
--- /dev/null
+++ b/test/command/pandoc-citeproc-chicago-author-date.md
@@ -0,0 +1,109 @@
+```
+% pandoc --citeproc -t markdown-citations
+---
+bibliography: command/biblio.bib
+link-citations: true
+---
+
+Pandoc with citeproc-hs
+=======================
+
+[@nonexistent]
+
+@nonexistent
+
+@item1 says blah.
+
+@item1 [p. 30] says blah.
+
+@item1 [p. 30, with suffix] says blah.
+
+@item1 [-@item2 p. 30; see also @пункт3] says blah.
+
+In a note.[^1]
+
+A citation group [see @item1 chap. 3; also @пункт3 p. 34-35].
+
+Another one [see @item1 p. 34-35].
+
+And another one in a note.[^2]
+
+Citation with a suffix and locator [@item1 pp. 33, 35-37, and nowhere
+else].
+
+Citation with suffix only [@item1 and nowhere else].
+
+Now some modifiers.[^3]
+
+With some markup [*see* @item1 p. **32**].
+
+References {#references .unnumbered}
+==========
+
+[^1]: @пункт3 [p. 12] and a citation without locators [@пункт3].
+
+[^2]: Some citations [see @item1 chap. 3; @пункт3; @item2].
+
+[^3]: Like a citation without author: [-@item1], and now Doe with a
+    locator [-@item2 p. 44].
+^D
+2> [WARNING] Citeproc: citation nonexistent not found
+# Pandoc with citeproc-hs
+
+([**nonexistent?**](#ref-nonexistent))
+
+([**nonexistent?**](#ref-nonexistent))
+
+Doe ([2005](#ref-item1)) says blah.
+
+Doe ([2005, 30](#ref-item1)) says blah.
+
+Doe ([2005, 30](#ref-item1), with suffix) says blah.
+
+Doe ([2005](#ref-item1); [2006, 30](#ref-item2); see also [Doe and Roe
+2007](#ref-пункт3)) says blah.
+
+In a note.[^1]
+
+A citation group (see [Doe 2005, chap. 3](#ref-item1); also [Doe and Roe
+2007, 34--35](#ref-пункт3)).
+
+Another one (see [Doe 2005, 34--35](#ref-item1)).
+
+And another one in a note.[^2]
+
+Citation with a suffix and locator ([Doe 2005, 33, 35--37](#ref-item1),
+and nowhere else).
+
+Citation with suffix only ([Doe 2005](#ref-item1) and nowhere else).
+
+Now some modifiers.[^3]
+
+With some markup (*see* [Doe 2005, 32](#ref-item1)).
+
+# References {#references .unnumbered}
+
+:::::: {#refs .references .csl-bib-body .hanging-indent}
+::: {#ref-item1 .csl-entry}
+Doe, John. 2005. *First Book*. Cambridge University Press.
+:::
+
+::: {#ref-item2 .csl-entry}
+Doe, John. 2006. "Article." *Journal of Generic Studies* 6: 33--34.
+:::
+
+::: {#ref-пункт3 .csl-entry}
+Doe, John, and Jenny Roe. 2007. "Why Water Is Wet." In *Third Book*,
+edited by Sam Smith. Oxford University Press.
+:::
+::::::
+
+[^1]: Doe and Roe ([2007, 12](#ref-пункт3)) and a citation without
+    locators ([Doe and Roe 2007](#ref-пункт3)).
+
+[^2]: Some citations (see [Doe 2005, chap. 3](#ref-item1);
+    [2006](#ref-item2); [Doe and Roe 2007](#ref-пункт3)).
+
+[^3]: Like a citation without author: ([2005](#ref-item1)), and now Doe
+    with a locator ([2006, 44](#ref-item2)).
+```
diff --git a/test/command/pandoc-citeproc-chicago-fullnote-bibliography.md b/test/command/pandoc-citeproc-chicago-fullnote-bibliography.md
new file mode 100644
--- /dev/null
+++ b/test/command/pandoc-citeproc-chicago-fullnote-bibliography.md
@@ -0,0 +1,134 @@
+```
+% pandoc --citeproc -t markdown-citations
+---
+bibliography: command/biblio.bib
+csl: 'command/chicago-fullnote-bibliography.csl'
+link-citations: true
+---
+
+Pandoc with citeproc-hs
+=======================
+
+[@nonexistent]
+
+@nonexistent
+
+@item1 says blah.
+
+@item1 [p. 30] says blah.
+
+@item1 [p. 30, with suffix] says blah.
+
+@item1 [-@item2 p. 30; see also @пункт3] says blah.
+
+In a note.[^1]
+
+A citation group [see @item1 chap. 3; also @пункт3 p. 34-35].
+
+Another one [see @item1 p. 34-35].
+
+And another one in a note.[^2]
+
+Citation with a suffix and locator [@item1 pp. 33, 35-37, and nowhere
+else].
+
+Citation with suffix only [@item1 and nowhere else].
+
+Now some modifiers.[^3]
+
+With some markup [*see* @item1 p. **32**].
+
+References {#references .unnumbered}
+==========
+
+[^1]: @пункт3 [p. 12] and a citation without locators [@пункт3].
+
+[^2]: Some citations [see @item1 chap. 3; @пункт3; @item2].
+
+[^3]: Like a citation without author: [-@item1], and again
+    [-@item1], and now Doe with a locator [-@item2 p. 44].
+^D
+2> [WARNING] Citeproc: citation nonexistent not found
+# Pandoc with citeproc-hs
+
+[^1]
+
+[^2]
+
+John Doe[^3] says blah.
+
+Doe[^4] says blah.
+
+Doe[^5] says blah.
+
+Doe[^6] says blah.
+
+In a note.[^7]
+
+A citation group.[^8]
+
+Another one.[^9]
+
+And another one in a note.[^10]
+
+Citation with a suffix and locator.[^11]
+
+Citation with suffix only.[^12]
+
+Now some modifiers.[^13]
+
+With some markup.[^14]
+
+# References {#references .unnumbered}
+
+:::::: {#refs .references .csl-bib-body .hanging-indent entry-spacing="0"}
+::: {#ref-item2 .csl-entry}
+Doe, John. "Article." *Journal of Generic Studies* 6 (2006): 33--34.
+:::
+
+::: {#ref-item1 .csl-entry}
+---------. *First Book*. Cambridge: Cambridge University Press, 2005.
+:::
+
+::: {#ref-пункт3 .csl-entry}
+Doe, John, and Jenny Roe. "Why Water Is Wet." In *Third Book*, edited by
+Sam Smith. Oxford: Oxford University Press, 2007.
+:::
+::::::
+
+[^1]: [**Nonexistent?**](#ref-nonexistent)
+
+[^2]: [**Nonexistent?**](#ref-nonexistent)
+
+[^3]: [*First Book* (Cambridge: Cambridge University Press,
+    2005)](#ref-item1).
+
+[^4]: [30](#ref-item1).
+
+[^5]: [30](#ref-item1), with suffix.
+
+[^6]: [*First Book*](#ref-item1); ["Article," *Journal of Generic
+    Studies* 6 (2006): 30](#ref-item2); see also [John Doe and Jenny
+    Roe, "Why Water Is Wet," in *Third Book*, ed. Sam Smith (Oxford:
+    Oxford University Press, 2007)](#ref-пункт3).
+
+[^7]: Doe and Roe, ["Why Water Is Wet," 12](#ref-пункт3) and a citation
+    without locators ([Doe and Roe, "Why Water Is Wet"](#ref-пункт3)).
+
+[^8]: See [Doe, *First Book*, chap. 3](#ref-item1); also [Doe and Roe,
+    "Why Water Is Wet," 34--35](#ref-пункт3).
+
+[^9]: See [Doe, *First Book*, 34--35](#ref-item1).
+
+[^10]: Some citations (see [Doe, chap. 3](#ref-item1); [Doe and Roe,
+    "Why Water Is Wet"](#ref-пункт3); [Doe, "Article"](#ref-item2)).
+
+[^11]: [Doe, *First Book*, 33, 35--37](#ref-item1), and nowhere else.
+
+[^12]: [Doe, *First Book*](#ref-item1) and nowhere else.
+
+[^13]: Like a citation without author: (), and again (), and now Doe
+    with a locator (["Article," 44](#ref-item2)).
+
+[^14]: *See* [Doe, *First Book*, 32](#ref-item1).
+```
diff --git a/test/command/pandoc-citeproc-ieee.md b/test/command/pandoc-citeproc-ieee.md
new file mode 100644
--- /dev/null
+++ b/test/command/pandoc-citeproc-ieee.md
@@ -0,0 +1,113 @@
+```
+% pandoc --citeproc -t markdown-citations
+---
+bibliography: command/biblio.bib
+csl: command/ieee.csl
+link-citations: true
+---
+
+Pandoc with citeproc-hs
+=======================
+
+[@nonexistent]
+
+@nonexistent
+
+@item1 says blah.
+
+@item1 [p. 30] says blah.
+
+@item1 [p. 30, with suffix] says blah.
+
+@item1 [-@item2 p. 30; see also @пункт3] says blah.
+
+In a note.[^1]
+
+A citation group [see @item1 chap. 3; also @пункт3 p. 34-35].
+
+Another one [see @item1 p. 34-35].
+
+And another one in a note.[^2]
+
+Citation with a suffix and locator [@item1 pp. 33, 35-37, and nowhere
+else].
+
+Citation with suffix only [@item1 and nowhere else].
+
+Now some modifiers.[^3]
+
+With some markup [*see* @item1 p. **32**].
+
+References {#references .unnumbered}
+==========
+
+[^1]: @пункт3 [p. 12] and a citation without locators [@пункт3].
+
+[^2]: Some citations [see @item1 chap. 3; @пункт3; @item2].
+
+[^3]: Like a citation without author: [-@item1], and now Doe with a
+    locator [-@item2 p. 44].
+^D
+2> [WARNING] Citeproc: citation nonexistent not found
+# Pandoc with citeproc-hs
+
+[**nonexistent?**](#ref-nonexistent)
+
+[**nonexistent?**](#ref-nonexistent)
+
+[\[1\]](#ref-item1) says blah.
+
+[\[1, p. 30\]](#ref-item1) says blah.
+
+[\[1, p. 30\]](#ref-item1), with suffix says blah.
+
+[\[1\]](#ref-item1), [\[2, p. 30\]](#ref-item2), see also
+[\[3\]](#ref-пункт3) says blah.
+
+In a note.[^1]
+
+A citation group see [\[1, Ch. 3\]](#ref-item1), also [\[3, pp.
+34--35\]](#ref-пункт3).
+
+Another one see [\[1, pp. 34--35\]](#ref-item1).
+
+And another one in a note.[^2]
+
+Citation with a suffix and locator [\[1, pp. 33, 35--37\]](#ref-item1),
+and nowhere else.
+
+Citation with suffix only [\[1\]](#ref-item1) and nowhere else.
+
+Now some modifiers.[^3]
+
+With some markup *see* [\[1, p. 32\]](#ref-item1).
+
+# References {#references .unnumbered}
+
+:::::: {#refs .references .csl-bib-body entry-spacing="0"}
+::: {#ref-item1 .csl-entry}
+[\[1\] ]{.csl-left-margin}[J. Doe, *First book*. Cambridge: Cambridge
+University Press, 2005.]{.csl-right-inline}
+:::
+
+::: {#ref-item2 .csl-entry}
+[\[2\] ]{.csl-left-margin}[J. Doe, "Article," *Journal of Generic
+Studies*, vol. 6, pp. 33--34, 2006.]{.csl-right-inline}
+:::
+
+::: {#ref-пункт3 .csl-entry}
+[\[3\] ]{.csl-left-margin}[J. Doe and J. Roe, "Why water is wet," in
+*Third book*, S. Smith, Ed. Oxford: Oxford University Press,
+2007.]{.csl-right-inline}
+:::
+::::::
+
+[^1]: [\[3, p. 12\]](#ref-пункт3) and a citation without locators
+    [\[3\]](#ref-пункт3).
+
+[^2]: Some citations see [\[1, Ch. 3\]](#ref-item1),
+    [\[2\]](#ref-item2), [\[3\]](#ref-пункт3).
+
+[^3]: Like a citation without author: [\[1\]](#ref-item1), and now Doe
+    with a locator [\[2, p. 44\]](#ref-item2).
+```
diff --git a/test/command/pandoc-citeproc-locators-delimited.md b/test/command/pandoc-citeproc-locators-delimited.md
new file mode 100644
--- /dev/null
+++ b/test/command/pandoc-citeproc-locators-delimited.md
@@ -0,0 +1,127 @@
+```
+% pandoc --citeproc -t markdown-citations
+---
+csl: command/locators.csl
+references:
+- id: citekey
+  title: Title
+  type: 'article-journal'
+suppress-bibliography: true
+---
+
+See <https://github.com/jgm/pandoc-citeproc/pull/362>.
+
+Standard page range[@citekey {35-89, 102}]
+
+Alphanumeric[@citekey {abcdefg1234}]
+
+Kitchen sink[@citekey, {123(4)a-8(\[a\]12.398{8})}]
+
+Empty braces inside[@citekey, {{}}]
+
+Label specified[@citekey {p. a}]
+
+Should it work outside? No. [@citekey, p. {(a)}]
+
+Empty locator [@citekey, {}]
+
+Empty locator to force suffix[@citekey {} 123-35 numbers are suffix]
+
+Suffix generally [@citekey {123-35} numbers not, but text is suffix]
+
+With preceding comma[@citekey, {p. VI}]
+
+No commas before label[@citekey, {, p. (p. is not recognised)}]
+
+Trim white space[@citekey, { p. 9 }]
+
+Without delimiters[@citekey, suffix]
+
+With rendering label[@citekey {ss IV div 4 s 128L(7)(a)(i)-(iv), 129(5),
+130(b)}]
+
+The text is apparently NOT verbatim; it is lightly processed as page
+numbers. [@citekey {no comma, no label, no nothing}]
+
+AGLC-style page \[para\] [@citekey {584 \[78\]}]
+
+Unbalanced curly { breaks the parse[@citekey {p. suffix{suffix}suffix]
+
+Unbalanced curly } ends early[@citekey {green}suffix}suffix]
+^D
+See <https://github.com/jgm/pandoc-citeproc/pull/362>.
+
+Standard page range[^1]
+
+Alphanumeric[^2]
+
+Kitchen sink[^3]
+
+Empty braces inside[^4]
+
+Label specified[^5]
+
+Should it work outside? No.[^6]
+
+Empty locator[^7]
+
+Empty locator to force suffix[^8]
+
+Suffix generally[^9]
+
+With preceding comma[^10]
+
+No commas before label[^11]
+
+Trim white space[^12]
+
+Without delimiters[^13]
+
+With rendering label[^14]
+
+The text is apparently NOT verbatim; it is lightly processed as page
+numbers.[^15]
+
+AGLC-style page \[para\][^16]
+
+Unbalanced curly { breaks the parse[^17]
+
+Unbalanced curly } ends early[^18]
+
+[^1]: Title {35--89, 102}.
+
+[^2]: Ibid-with-locator {abcdefg1234}.
+
+[^3]: Ibid-with-locator {123(4)a--8(\[a\]12.398{8})}.
+
+[^4]: Ibid-with-locator {{}}.
+
+[^5]: Ibid-with-locator {a}.
+
+[^6]: Subsequent, p. {(a)}.
+
+[^7]: Ibid.
+
+[^8]: Ibid 123-35 numbers are suffix.
+
+[^9]: Ibid-with-locator {123--35} numbers not, but text is suffix.
+
+[^10]: Ibid-with-locator {VI}.
+
+[^11]: Ibid-with-locator {, p. (p. is not recognised)}.
+
+[^12]: Ibid-with-locator {9}.
+
+[^13]: Subsequent, suffix.
+
+[^14]: Ibid-with-locator ss {IV div 4 s 128L(7)(a)(i)--(iv), 129(5),
+    130(b)}.
+
+[^15]: Ibid-with-locator {no comma, no label, no nothing}.
+
+[^16]: Ibid-with-locator {584 \[78\]}.
+
+[^17]: Subsequent {p. suffix{suffix}suffix.
+
+[^18]: Ibid-with-locator {green}suffix}suffix.
+```
diff --git a/test/command/pandoc-citeproc-locators-integrated.md b/test/command/pandoc-citeproc-locators-integrated.md
new file mode 100644
--- /dev/null
+++ b/test/command/pandoc-citeproc-locators-integrated.md
@@ -0,0 +1,159 @@
+```
+% pandoc --citeproc -t markdown-citations
+---
+csl: command/locators.csl
+references:
+- id: citekey
+  title: Title
+  type: 'article-journal'
+suppress-bibliography: true
+---
+
+See <https://github.com/jgm/pandoc-citeproc/pull/362>.
+
+[@citekey, 89, and suffix]
+
+[@citekey, 89, perfect Ibid with suffix]
+
+[@citekey, 123-79, and suffix]
+
+[@citekey, xi, will be entirely suffix]
+
+[@citekey, p. xi, gives you a (page) locator xi]
+
+[@citekey, pp. VII, 89, gives you a (pages) locator VII, 89]
+
+[@citekey, p. VI, VII, VIII-IX, explicit romans]
+
+[@citekey \[89\]]
+
+[@citekey, p. \[89\]]
+
+[@citekey and nothing else]
+
+[@citekey, 123(4)\[5\]6, and suffix]
+
+[@citekey, 3(a), 4.4.8, \[7.6\], 7A(2)(a)(i)-(iv)]
+
+[@citekey, 4B.2a.i(3.4), and suffix]
+
+[@citekey, IV.2A, and suffix]
+
+[@citekey, \[28\], and suffix]
+
+[@citekey, \[39-52\], and suffix]
+
+[@citekey, \[39\]-\[52\], and suffix]
+
+[@citekey, s 123(4)(a)(iv), and suffix]
+
+[@citekey, ss 123(4)-(6), and suffix]
+
+[@citekey, \[13\], and suffix]
+
+[@citekey, p.3, and suffix]
+
+[@citekey, (13 entirely suffix]
+
+[@citekey, p.a entirely suffix]
+
+[@citekey, s (a) entirely suffix]
+^D
+See <https://github.com/jgm/pandoc-citeproc/pull/362>.
+
+[^1]
+
+[^2]
+
+[^3]
+
+[^4]
+
+[^5]
+
+[^6]
+
+[^7]
+
+[^8]
+
+[^9]
+
+[^10]
+
+[^11]
+
+[^12]
+
+[^13]
+
+[^14]
+
+[^15]
+
+[^16]
+
+[^17]
+
+[^18]
+
+[^19]
+
+[^20]
+
+[^21]
+
+[^22]
+
+[^23]
+
+[^24]
+
+[^1]: Title {89}, and suffix.
+
+[^2]: Ibid, perfect Ibid with suffix.
+
+[^3]: Ibid-with-locator {123--79}, and suffix.
+
+[^4]: Subsequent, xi, will be entirely suffix.
+
+[^5]: Ibid-with-locator {xi}, gives you a (page) locator xi.
+
+[^6]: Ibid-with-locator {VII, 89}, gives you a (pages) locator VII, 89.
+
+[^7]: Ibid-with-locator {VI, VII, VIII--IX}, explicit romans.
+
+[^8]: Ibid-with-locator {\[89\]}.
+
+[^9]: Ibid.
+
+[^10]: Subsequent and nothing else.
+
+[^11]: Ibid-with-locator {123(4)\[5\]6}, and suffix.
+
+[^12]: Ibid-with-locator {3(a), 4.4.8, \[7.6\], 7A(2)(a)(i)--(iv)}.
+
+[^13]: Ibid-with-locator {4B.2a.i(3.4)}, and suffix.
+
+[^14]: Ibid-with-locator {IV.2A}, and suffix.
+
+[^15]: Ibid-with-locator {\[28\]}, and suffix.
+
+[^16]: Ibid-with-locator {\[39--52\]}, and suffix.
+
+[^17]: Ibid-with-locator {\[39\]--\[52\]}, and suffix.
+
+[^18]: Ibid-with-locator s {123(4)(a)(iv)}, and suffix.
+
+[^19]: Ibid-with-locator ss {123(4)--(6)}, and suffix.
+
+[^20]: Ibid-with-locator {\[13\]}, and suffix.
+
+[^21]: Ibid-with-locator {3}, and suffix.
+
+[^22]: Subsequent, (13 entirely suffix.
+
+[^23]: Ibid, p.a entirely suffix.
+
+[^24]: Ibid, s (a) entirely suffix.
+```
diff --git a/test/command/pandoc-citeproc-move-period-inside-quote.md b/test/command/pandoc-citeproc-move-period-inside-quote.md
new file mode 100644
--- /dev/null
+++ b/test/command/pandoc-citeproc-move-period-inside-quote.md
@@ -0,0 +1,52 @@
+```
+% pandoc --citeproc -t markdown-citations
+---
+csl: 'command/chicago-fullnote-bibliography.csl'
+references:
+- DOI: 10.1038/171737a0
+  URL: 'http://www.nature.com/nature/journal/v171/n4356/abs/171737a0.html'
+  accessed:
+    day: 17
+    month: 6
+    year: 2008
+  author:
+  - family: Watson
+    given: J. D.
+  - family: Crick
+    given: F. H. C.
+  container-title: Nature
+  custom4: custom4
+  id: WatsonCrick1953
+  issue: 4356
+  issued:
+    date-parts:
+    - - 1953
+      - 4
+      - 25
+  language: 'en-US'
+  note: this is a note
+  original-date:
+    year: 1951
+  page: '737-738'
+  title: 'Molecular structure of nucleic acids: a structure for
+    deoxyribose nucleic acid'
+  title-short: Molecular structure of nucleic acids
+  type: 'article-journal'
+  volume: 171
+suppress-bibliography: true
+---
+
+Here is a "test citation" [@WatsonCrick1953].
+
+Here is a test citation [@WatsonCrick1953].
+^D
+Here is a "test citation."[^1]
+
+Here is a test citation.[^2]
+
+[^1]: J. D. Watson and F. H. C. Crick, "Molecular Structure of Nucleic
+    Acids: A Structure for Deoxyribose Nucleic Acid," *Nature* 171, no.
+    4356 (April 25, 1953): 737--38, <https://doi.org/10.1038/171737a0>.
+
+[^2]: Watson and Crick.
+```
diff --git a/test/command/pandoc-citeproc-no-author.md b/test/command/pandoc-citeproc-no-author.md
new file mode 100644
--- /dev/null
+++ b/test/command/pandoc-citeproc-no-author.md
@@ -0,0 +1,73 @@
+```
+% pandoc --citeproc -t markdown-citations
+---
+references:
+- container-title: Magazine
+  id: item1
+  issued:
+    year: 2012
+  title: Title A
+  type: 'article-magazine'
+- container-title: Magazine
+  id: item2
+  issued:
+    year: 2012
+  title: Title B
+  type: 'article-magazine'
+- container-title: Magazine
+  id: item3
+  issued:
+    year: 2012
+  title: Title C
+  type: 'article-magazine'
+- container-title: Magazine
+  id: item4
+  issued:
+    year: 2012
+  title: Title D
+  type: 'article-magazine'
+- container-title: Newspaper
+  id: item5
+  issued:
+    year: 2012
+  title: Title E
+  type: 'article-magazine'
+- container-title: Newspaper
+  id: item6
+  issued:
+    year: 2012
+  title: Title F
+  type: 'article-magazine'
+---
+
+@item1 [p. 3], @item2, @item3, @item4, @item5, @item6
+^D
+*Magazine* (2012a, 3), *Magazine* (2012b), *Magazine* (2012c),
+*Magazine* (2012d), *Newspaper* (2012a), *Newspaper* (2012b)
+
+::::::::: {#refs .references .csl-bib-body .hanging-indent}
+::: {#ref-item1 .csl-entry}
+*Magazine*. 2012a. "Title A."
+:::
+
+::: {#ref-item2 .csl-entry}
+*Magazine*. 2012b. "Title B."
+:::
+
+::: {#ref-item3 .csl-entry}
+*Magazine*. 2012c. "Title C."
+:::
+
+::: {#ref-item4 .csl-entry}
+*Magazine*. 2012d. "Title D."
+:::
+
+::: {#ref-item5 .csl-entry}
+*Newspaper*. 2012a. "Title E."
+:::
+
+::: {#ref-item6 .csl-entry}
+*Newspaper*. 2012b. "Title F."
+:::
+:::::::::
+```
diff --git a/test/command/pandoc-citeproc-number-of-volumes.md b/test/command/pandoc-citeproc-number-of-volumes.md
new file mode 100644
--- /dev/null
+++ b/test/command/pandoc-citeproc-number-of-volumes.md
@@ -0,0 +1,29 @@
+```
+% pandoc --citeproc -t markdown-citations
+---
+references:
+- author:
+    family: Author
+    given:
+    - Al
+  id: item1
+  issued:
+    year: 2013
+  language: 'en-US'
+  number-of-volumes: 2
+  publisher: Publisher
+  publisher-place: Location
+  title: Title
+  type: book
+---
+
+@item1
+^D
+Author (2013)
+
+:::: {#refs .references .csl-bib-body .hanging-indent}
+::: {#ref-item1 .csl-entry}
+Author, Al. 2013. *Title*. 2 vols. Publisher.
+:::
+::::
+```
diff --git a/test/command/pandoc-citeproc-page-range.md b/test/command/pandoc-citeproc-page-range.md
new file mode 100644
--- /dev/null
+++ b/test/command/pandoc-citeproc-page-range.md
@@ -0,0 +1,32 @@
+```
+% pandoc --citeproc -t markdown-citations
+---
+csl: 'command/chicago-fullnote-bibliography.csl'
+references:
+- URL: 'https://johnmacfarlane.net/vagueness.pdf'
+  id: test1
+- URL: 'https://pandoc.org'
+  id: test2
+- URL: 'https://johnmacfarlane.net'
+  id: test3
+suppress-bibliography: true
+---
+
+Test 1 [@test1, pp. 93--101].
+
+Test 2 [@test2, pp. 93--101].
+
+Test 3 [@test3, pp. 93-101].
+^D
+Test 1.[^1]
+
+Test 2.[^2]
+
+Test 3.[^3]
+
+[^1]: N.d., 93--101, <https://johnmacfarlane.net/vagueness.pdf>.
+
+[^2]: N.d., 93--101, <https://pandoc.org>.
+
+[^3]: N.d., 93--101, <https://johnmacfarlane.net>.
+```
diff --git a/test/command/parse-raw.md b/test/command/parse-raw.md
--- a/test/command/parse-raw.md
+++ b/test/command/parse-raw.md
@@ -2,7 +2,7 @@
 % pandoc -f latex+raw_tex -t markdown
 \emph{Hi \foo{there}}
 ^D
-*Hi \foo{there}*
+*Hi `\foo{there}`{=latex}*
 ```
 
 ```
@@ -16,7 +16,7 @@
 % pandoc -f html+raw_html -t markdown
 <em>Hi <blink>there</blink></em>
 ^D
-*Hi <blink>there</blink>*
+*Hi `<blink>`{=html}there`</blink>`{=html}*
 ```
 
 ```
diff --git a/test/command/pdfstandard.md b/test/command/pdfstandard.md
new file mode 100644
--- /dev/null
+++ b/test/command/pdfstandard.md
@@ -0,0 +1,616 @@
+PDF standard support: basic PDF/A-2b test (infers version 1.7)
+```
+% pandoc -t latex -s
+---
+pdfstandard: a-2b
+lang: en-US
+---
+
+Test document.
+^D
+\DocumentMetadata{
+  pdfversion=1.7,
+  pdfstandard={a-2b},
+  lang=en-US,
+  xmp=true}
+% Options for packages loaded elsewhere
+\PassOptionsToPackage{unicode}{hyperref}
+\PassOptionsToPackage{hyphens}{url}
+\documentclass[
+  american,
+]{article}
+\usepackage{xcolor}
+\usepackage{amsmath,amssymb}
+\setcounter{secnumdepth}{-\maxdimen} % remove section numbering
+\usepackage{iftex}
+\ifPDFTeX
+  \usepackage[T1]{fontenc}
+  \usepackage[utf8]{inputenc}
+  \usepackage{textcomp} % provide euro and other symbols
+\else % if luatex or xetex
+  \usepackage{unicode-math} % this also loads fontspec
+  \defaultfontfeatures{Scale=MatchLowercase}
+  \defaultfontfeatures[\rmfamily]{Ligatures=TeX,Scale=1}
+\fi
+\usepackage{lmodern}
+\ifPDFTeX\else
+  % xetex/luatex font selection
+\fi
+% Use upquote if available, for straight quotes in verbatim environments
+\IfFileExists{upquote.sty}{\usepackage{upquote}}{}
+\IfFileExists{microtype.sty}{% use microtype if available
+  \usepackage[]{microtype}
+  \UseMicrotypeSet[protrusion]{basicmath} % disable protrusion for tt fonts
+}{}
+\makeatletter
+\@ifundefined{KOMAClassName}{% if non-KOMA class
+  \IfFileExists{parskip.sty}{%
+    \usepackage{parskip}
+  }{% else
+    \setlength{\parindent}{0pt}
+    \setlength{\parskip}{6pt plus 2pt minus 1pt}}
+}{% if KOMA class
+  \KOMAoptions{parskip=half}}
+\makeatother
+\ifLuaTeX
+\usepackage[bidi=basic,shorthands=off]{babel}
+\else
+\usepackage[bidi=default,shorthands=off]{babel}
+\fi
+\ifLuaTeX
+  \usepackage{selnolig} % disable illegal ligatures
+\fi
+\setlength{\emergencystretch}{3em} % prevent overfull lines
+\providecommand{\tightlist}{%
+  \setlength{\itemsep}{0pt}\setlength{\parskip}{0pt}}
+\usepackage{bookmark}
+\IfFileExists{xurl.sty}{\usepackage{xurl}}{} % add URL line breaks if available
+\urlstyle{same}
+% fallback for those not using the hyperref driver hyperxmp:
+\makeatletter
+\@ifundefined{xmpquote}{\newcommand{\xmpquote}[1]{#1}}{}
+\makeatother
+\hypersetup{
+  pdflang={en-US},
+  hidelinks,
+  pdfcreator={LaTeX via pandoc}}
+
+\author{}
+\date{}
+
+\begin{document}
+
+Test document.
+
+\end{document}
+```
+
+PDF standard support: PDF/UA-1 with tagging
+```
+% pandoc -t latex -s
+---
+pdfstandard: ua-1
+lang: en-US
+---
+
+Accessible document.
+^D
+\DocumentMetadata{
+  pdfstandard={ua-1},
+  tagging=on,
+  lang=en-US,
+  xmp=true}
+% Options for packages loaded elsewhere
+\PassOptionsToPackage{unicode}{hyperref}
+\PassOptionsToPackage{hyphens}{url}
+\documentclass[
+  american,
+]{article}
+\usepackage{xcolor}
+\usepackage{amsmath,amssymb}
+\setcounter{secnumdepth}{-\maxdimen} % remove section numbering
+\usepackage{iftex}
+\ifPDFTeX
+  \usepackage[T1]{fontenc}
+  \usepackage[utf8]{inputenc}
+  \usepackage{textcomp} % provide euro and other symbols
+\else % if luatex or xetex
+  \usepackage{unicode-math} % this also loads fontspec
+  \defaultfontfeatures{Scale=MatchLowercase}
+  \defaultfontfeatures[\rmfamily]{Ligatures=TeX,Scale=1}
+\fi
+\usepackage{lmodern}
+\ifPDFTeX\else
+  % xetex/luatex font selection
+\fi
+% Use upquote if available, for straight quotes in verbatim environments
+\IfFileExists{upquote.sty}{\usepackage{upquote}}{}
+\IfFileExists{microtype.sty}{% use microtype if available
+  \usepackage[]{microtype}
+  \UseMicrotypeSet[protrusion]{basicmath} % disable protrusion for tt fonts
+}{}
+\makeatletter
+\@ifundefined{KOMAClassName}{% if non-KOMA class
+  \IfFileExists{parskip.sty}{%
+    \usepackage{parskip}
+  }{% else
+    \setlength{\parindent}{0pt}
+    \setlength{\parskip}{6pt plus 2pt minus 1pt}}
+}{% if KOMA class
+  \KOMAoptions{parskip=half}}
+\makeatother
+\ifLuaTeX
+\usepackage[bidi=basic,shorthands=off]{babel}
+\else
+\usepackage[bidi=default,shorthands=off]{babel}
+\fi
+\ifLuaTeX
+  \usepackage{selnolig} % disable illegal ligatures
+\fi
+\setlength{\emergencystretch}{3em} % prevent overfull lines
+\providecommand{\tightlist}{%
+  \setlength{\itemsep}{0pt}\setlength{\parskip}{0pt}}
+\usepackage{bookmark}
+\IfFileExists{xurl.sty}{\usepackage{xurl}}{} % add URL line breaks if available
+\urlstyle{same}
+% fallback for those not using the hyperref driver hyperxmp:
+\makeatletter
+\@ifundefined{xmpquote}{\newcommand{\xmpquote}[1]{#1}}{}
+\makeatother
+\hypersetup{
+  pdflang={en-US},
+  hidelinks,
+  pdfcreator={LaTeX via pandoc}}
+
+\author{}
+\date{}
+
+\begin{document}
+
+Accessible document.
+
+\end{document}
+```
+
+PDF standard support: multiple standards with version
+```
+% pandoc -t latex -s
+---
+pdfstandard:
+  - a-2b
+  - ua-1
+  - "1.7"
+lang: de-DE
+---
+
+Multi-standard document.
+^D
+\DocumentMetadata{
+  pdfversion=1.7,
+  pdfstandard={a-2b,ua-1},
+  tagging=on,
+  lang=de-DE,
+  xmp=true}
+% Options for packages loaded elsewhere
+\PassOptionsToPackage{unicode}{hyperref}
+\PassOptionsToPackage{hyphens}{url}
+\documentclass[
+  ngerman,
+]{article}
+\usepackage{xcolor}
+\usepackage{amsmath,amssymb}
+\setcounter{secnumdepth}{-\maxdimen} % remove section numbering
+\usepackage{iftex}
+\ifPDFTeX
+  \usepackage[T1]{fontenc}
+  \usepackage[utf8]{inputenc}
+  \usepackage{textcomp} % provide euro and other symbols
+\else % if luatex or xetex
+  \usepackage{unicode-math} % this also loads fontspec
+  \defaultfontfeatures{Scale=MatchLowercase}
+  \defaultfontfeatures[\rmfamily]{Ligatures=TeX,Scale=1}
+\fi
+\usepackage{lmodern}
+\ifPDFTeX\else
+  % xetex/luatex font selection
+\fi
+% Use upquote if available, for straight quotes in verbatim environments
+\IfFileExists{upquote.sty}{\usepackage{upquote}}{}
+\IfFileExists{microtype.sty}{% use microtype if available
+  \usepackage[]{microtype}
+  \UseMicrotypeSet[protrusion]{basicmath} % disable protrusion for tt fonts
+}{}
+\makeatletter
+\@ifundefined{KOMAClassName}{% if non-KOMA class
+  \IfFileExists{parskip.sty}{%
+    \usepackage{parskip}
+  }{% else
+    \setlength{\parindent}{0pt}
+    \setlength{\parskip}{6pt plus 2pt minus 1pt}}
+}{% if KOMA class
+  \KOMAoptions{parskip=half}}
+\makeatother
+\ifLuaTeX
+\usepackage[bidi=basic,shorthands=off]{babel}
+\else
+\usepackage[bidi=default,shorthands=off]{babel}
+\fi
+\ifLuaTeX
+  \usepackage{selnolig} % disable illegal ligatures
+\fi
+\setlength{\emergencystretch}{3em} % prevent overfull lines
+\providecommand{\tightlist}{%
+  \setlength{\itemsep}{0pt}\setlength{\parskip}{0pt}}
+\usepackage{bookmark}
+\IfFileExists{xurl.sty}{\usepackage{xurl}}{} % add URL line breaks if available
+\urlstyle{same}
+% fallback for those not using the hyperref driver hyperxmp:
+\makeatletter
+\@ifundefined{xmpquote}{\newcommand{\xmpquote}[1]{#1}}{}
+\makeatother
+\hypersetup{
+  pdflang={de-DE},
+  hidelinks,
+  pdfcreator={LaTeX via pandoc}}
+
+\author{}
+\date{}
+
+\begin{document}
+
+Multi-standard document.
+
+\end{document}
+```
+
+PDF standard support: PDF/A-1b infers version 1.4
+```
+% pandoc -t latex -s
+---
+pdfstandard: a-1b
+lang: en-US
+---
+
+PDF/A-1 document.
+^D
+\DocumentMetadata{
+  pdfversion=1.4,
+  pdfstandard={a-1b},
+  lang=en-US,
+  xmp=true}
+% Options for packages loaded elsewhere
+\PassOptionsToPackage{unicode}{hyperref}
+\PassOptionsToPackage{hyphens}{url}
+\documentclass[
+  american,
+]{article}
+\usepackage{xcolor}
+\usepackage{amsmath,amssymb}
+\setcounter{secnumdepth}{-\maxdimen} % remove section numbering
+\usepackage{iftex}
+\ifPDFTeX
+  \usepackage[T1]{fontenc}
+  \usepackage[utf8]{inputenc}
+  \usepackage{textcomp} % provide euro and other symbols
+\else % if luatex or xetex
+  \usepackage{unicode-math} % this also loads fontspec
+  \defaultfontfeatures{Scale=MatchLowercase}
+  \defaultfontfeatures[\rmfamily]{Ligatures=TeX,Scale=1}
+\fi
+\usepackage{lmodern}
+\ifPDFTeX\else
+  % xetex/luatex font selection
+\fi
+% Use upquote if available, for straight quotes in verbatim environments
+\IfFileExists{upquote.sty}{\usepackage{upquote}}{}
+\IfFileExists{microtype.sty}{% use microtype if available
+  \usepackage[]{microtype}
+  \UseMicrotypeSet[protrusion]{basicmath} % disable protrusion for tt fonts
+}{}
+\makeatletter
+\@ifundefined{KOMAClassName}{% if non-KOMA class
+  \IfFileExists{parskip.sty}{%
+    \usepackage{parskip}
+  }{% else
+    \setlength{\parindent}{0pt}
+    \setlength{\parskip}{6pt plus 2pt minus 1pt}}
+}{% if KOMA class
+  \KOMAoptions{parskip=half}}
+\makeatother
+\ifLuaTeX
+\usepackage[bidi=basic,shorthands=off]{babel}
+\else
+\usepackage[bidi=default,shorthands=off]{babel}
+\fi
+\ifLuaTeX
+  \usepackage{selnolig} % disable illegal ligatures
+\fi
+\setlength{\emergencystretch}{3em} % prevent overfull lines
+\providecommand{\tightlist}{%
+  \setlength{\itemsep}{0pt}\setlength{\parskip}{0pt}}
+\usepackage{bookmark}
+\IfFileExists{xurl.sty}{\usepackage{xurl}}{} % add URL line breaks if available
+\urlstyle{same}
+% fallback for those not using the hyperref driver hyperxmp:
+\makeatletter
+\@ifundefined{xmpquote}{\newcommand{\xmpquote}[1]{#1}}{}
+\makeatother
+\hypersetup{
+  pdflang={en-US},
+  hidelinks,
+  pdfcreator={LaTeX via pandoc}}
+
+\author{}
+\date{}
+
+\begin{document}
+
+PDF/A-1 document.
+
+\end{document}
+```
+
+PDF standard support: PDF/A-4 with no version inference (uses default 2.0)
+```
+% pandoc -t latex -s
+---
+pdfstandard: a-4
+lang: en-US
+---
+
+PDF/A-4 document.
+^D
+\DocumentMetadata{
+  pdfstandard={a-4},
+  lang=en-US,
+  xmp=true}
+% Options for packages loaded elsewhere
+\PassOptionsToPackage{unicode}{hyperref}
+\PassOptionsToPackage{hyphens}{url}
+\documentclass[
+  american,
+]{article}
+\usepackage{xcolor}
+\usepackage{amsmath,amssymb}
+\setcounter{secnumdepth}{-\maxdimen} % remove section numbering
+\usepackage{iftex}
+\ifPDFTeX
+  \usepackage[T1]{fontenc}
+  \usepackage[utf8]{inputenc}
+  \usepackage{textcomp} % provide euro and other symbols
+\else % if luatex or xetex
+  \usepackage{unicode-math} % this also loads fontspec
+  \defaultfontfeatures{Scale=MatchLowercase}
+  \defaultfontfeatures[\rmfamily]{Ligatures=TeX,Scale=1}
+\fi
+\usepackage{lmodern}
+\ifPDFTeX\else
+  % xetex/luatex font selection
+\fi
+% Use upquote if available, for straight quotes in verbatim environments
+\IfFileExists{upquote.sty}{\usepackage{upquote}}{}
+\IfFileExists{microtype.sty}{% use microtype if available
+  \usepackage[]{microtype}
+  \UseMicrotypeSet[protrusion]{basicmath} % disable protrusion for tt fonts
+}{}
+\makeatletter
+\@ifundefined{KOMAClassName}{% if non-KOMA class
+  \IfFileExists{parskip.sty}{%
+    \usepackage{parskip}
+  }{% else
+    \setlength{\parindent}{0pt}
+    \setlength{\parskip}{6pt plus 2pt minus 1pt}}
+}{% if KOMA class
+  \KOMAoptions{parskip=half}}
+\makeatother
+\ifLuaTeX
+\usepackage[bidi=basic,shorthands=off]{babel}
+\else
+\usepackage[bidi=default,shorthands=off]{babel}
+\fi
+\ifLuaTeX
+  \usepackage{selnolig} % disable illegal ligatures
+\fi
+\setlength{\emergencystretch}{3em} % prevent overfull lines
+\providecommand{\tightlist}{%
+  \setlength{\itemsep}{0pt}\setlength{\parskip}{0pt}}
+\usepackage{bookmark}
+\IfFileExists{xurl.sty}{\usepackage{xurl}}{} % add URL line breaks if available
+\urlstyle{same}
+% fallback for those not using the hyperref driver hyperxmp:
+\makeatletter
+\@ifundefined{xmpquote}{\newcommand{\xmpquote}[1]{#1}}{}
+\makeatother
+\hypersetup{
+  pdflang={en-US},
+  hidelinks,
+  pdfcreator={LaTeX via pandoc}}
+
+\author{}
+\date{}
+
+\begin{document}
+
+PDF/A-4 document.
+
+\end{document}
+```
+
+PDF standard support: numeric YAML version (2 becomes 2.0)
+```
+% pandoc -t latex -s
+---
+pdfstandard:
+  - ua-1
+  - 2
+lang: en-US
+---
+
+PDF 2.0 document.
+^D
+\DocumentMetadata{
+  pdfversion=2.0,
+  pdfstandard={ua-1},
+  tagging=on,
+  lang=en-US,
+  xmp=true}
+% Options for packages loaded elsewhere
+\PassOptionsToPackage{unicode}{hyperref}
+\PassOptionsToPackage{hyphens}{url}
+\documentclass[
+  american,
+]{article}
+\usepackage{xcolor}
+\usepackage{amsmath,amssymb}
+\setcounter{secnumdepth}{-\maxdimen} % remove section numbering
+\usepackage{iftex}
+\ifPDFTeX
+  \usepackage[T1]{fontenc}
+  \usepackage[utf8]{inputenc}
+  \usepackage{textcomp} % provide euro and other symbols
+\else % if luatex or xetex
+  \usepackage{unicode-math} % this also loads fontspec
+  \defaultfontfeatures{Scale=MatchLowercase}
+  \defaultfontfeatures[\rmfamily]{Ligatures=TeX,Scale=1}
+\fi
+\usepackage{lmodern}
+\ifPDFTeX\else
+  % xetex/luatex font selection
+\fi
+% Use upquote if available, for straight quotes in verbatim environments
+\IfFileExists{upquote.sty}{\usepackage{upquote}}{}
+\IfFileExists{microtype.sty}{% use microtype if available
+  \usepackage[]{microtype}
+  \UseMicrotypeSet[protrusion]{basicmath} % disable protrusion for tt fonts
+}{}
+\makeatletter
+\@ifundefined{KOMAClassName}{% if non-KOMA class
+  \IfFileExists{parskip.sty}{%
+    \usepackage{parskip}
+  }{% else
+    \setlength{\parindent}{0pt}
+    \setlength{\parskip}{6pt plus 2pt minus 1pt}}
+}{% if KOMA class
+  \KOMAoptions{parskip=half}}
+\makeatother
+\ifLuaTeX
+\usepackage[bidi=basic,shorthands=off]{babel}
+\else
+\usepackage[bidi=default,shorthands=off]{babel}
+\fi
+\ifLuaTeX
+  \usepackage{selnolig} % disable illegal ligatures
+\fi
+\setlength{\emergencystretch}{3em} % prevent overfull lines
+\providecommand{\tightlist}{%
+  \setlength{\itemsep}{0pt}\setlength{\parskip}{0pt}}
+\usepackage{bookmark}
+\IfFileExists{xurl.sty}{\usepackage{xurl}}{} % add URL line breaks if available
+\urlstyle{same}
+% fallback for those not using the hyperref driver hyperxmp:
+\makeatletter
+\@ifundefined{xmpquote}{\newcommand{\xmpquote}[1]{#1}}{}
+\makeatother
+\hypersetup{
+  pdflang={en-US},
+  hidelinks,
+  pdfcreator={LaTeX via pandoc}}
+
+\author{}
+\date{}
+
+\begin{document}
+
+PDF 2.0 document.
+
+\end{document}
+```
+
+PDF standard support: explicit version overrides inferred version
+```
+% pandoc -t latex -s
+---
+pdfstandard:
+  - a-2b
+  - "1.5"
+lang: en-US
+---
+
+Explicit version document.
+^D
+\DocumentMetadata{
+  pdfversion=1.5,
+  pdfstandard={a-2b},
+  lang=en-US,
+  xmp=true}
+% Options for packages loaded elsewhere
+\PassOptionsToPackage{unicode}{hyperref}
+\PassOptionsToPackage{hyphens}{url}
+\documentclass[
+  american,
+]{article}
+\usepackage{xcolor}
+\usepackage{amsmath,amssymb}
+\setcounter{secnumdepth}{-\maxdimen} % remove section numbering
+\usepackage{iftex}
+\ifPDFTeX
+  \usepackage[T1]{fontenc}
+  \usepackage[utf8]{inputenc}
+  \usepackage{textcomp} % provide euro and other symbols
+\else % if luatex or xetex
+  \usepackage{unicode-math} % this also loads fontspec
+  \defaultfontfeatures{Scale=MatchLowercase}
+  \defaultfontfeatures[\rmfamily]{Ligatures=TeX,Scale=1}
+\fi
+\usepackage{lmodern}
+\ifPDFTeX\else
+  % xetex/luatex font selection
+\fi
+% Use upquote if available, for straight quotes in verbatim environments
+\IfFileExists{upquote.sty}{\usepackage{upquote}}{}
+\IfFileExists{microtype.sty}{% use microtype if available
+  \usepackage[]{microtype}
+  \UseMicrotypeSet[protrusion]{basicmath} % disable protrusion for tt fonts
+}{}
+\makeatletter
+\@ifundefined{KOMAClassName}{% if non-KOMA class
+  \IfFileExists{parskip.sty}{%
+    \usepackage{parskip}
+  }{% else
+    \setlength{\parindent}{0pt}
+    \setlength{\parskip}{6pt plus 2pt minus 1pt}}
+}{% if KOMA class
+  \KOMAoptions{parskip=half}}
+\makeatother
+\ifLuaTeX
+\usepackage[bidi=basic,shorthands=off]{babel}
+\else
+\usepackage[bidi=default,shorthands=off]{babel}
+\fi
+\ifLuaTeX
+  \usepackage{selnolig} % disable illegal ligatures
+\fi
+\setlength{\emergencystretch}{3em} % prevent overfull lines
+\providecommand{\tightlist}{%
+  \setlength{\itemsep}{0pt}\setlength{\parskip}{0pt}}
+\usepackage{bookmark}
+\IfFileExists{xurl.sty}{\usepackage{xurl}}{} % add URL line breaks if available
+\urlstyle{same}
+% fallback for those not using the hyperref driver hyperxmp:
+\makeatletter
+\@ifundefined{xmpquote}{\newcommand{\xmpquote}[1]{#1}}{}
+\makeatother
+\hypersetup{
+  pdflang={en-US},
+  hidelinks,
+  pdfcreator={LaTeX via pandoc}}
+
+\author{}
+\date{}
+
+\begin{document}
+
+Explicit version document.
+
+\end{document}
+```
diff --git a/test/command/refs.md b/test/command/refs.md
--- a/test/command/refs.md
+++ b/test/command/refs.md
@@ -2,25 +2,82 @@
 % pandoc -f latex -t native
 Figure \ref{fig:1}
 ^D
-[Para [Str "Figure",Space,Link ("",[],[("reference-type","ref"),("reference","fig:1")]) [Str "[fig:1]"] ("#fig:1","")]]
+[ Para
+    [ Str "Figure"
+    , Space
+    , Link
+        ( ""
+        , []
+        , [ ( "reference-type" , "ref" )
+          , ( "reference" , "fig:1" )
+          ]
+        )
+        [ Str "[fig:1]" ]
+        ( "#fig:1" , "" )
+    ]
+]
 ```
 
 ```
 % pandoc -f latex -t native
 Figure \cref{fig:1}
 ^D
-[Para [Str "Figure",Space,Link ("",[],[("reference-type","ref"),("reference","fig:1")]) [Str "[fig:1]"] ("#fig:1","")]]
+[ Para
+    [ Str "Figure"
+    , Space
+    , Link
+        ( ""
+        , []
+        , [ ( "reference-type" , "ref+label" )
+          , ( "reference" , "fig:1" )
+          ]
+        )
+        [ Str "[fig:1]" ]
+        ( "#fig:1" , "" )
+    ]
+]
 ```
 
 ```
 % pandoc -f latex -t native
 Figure \vref{fig:1}
 ^D
-[Para [Str "Figure",Space,Link ("",[],[("reference-type","ref+page"),("reference","fig:1")]) [Str "[fig:1]"] ("#fig:1","")]]
+[ Para
+    [ Str "Figure"
+    , Space
+    , Link
+        ( ""
+        , []
+        , [ ( "reference-type" , "ref" )
+          , ( "reference" , "fig:1" )
+          ]
+        )
+        [ Str "[fig:1]" ]
+        ( "#fig:1" , "" )
+    ]
+]
 ```
 
 ```
 % pandoc -f latex -t native
+\autoref{fig:flowchart}
+^D
+[ Para
+    [ Link
+        ( ""
+        , []
+        , [ ( "reference-type" , "ref+label" )
+          , ( "reference" , "fig:flowchart" )
+          ]
+        )
+        [ Str "[fig:flowchart]" ]
+        ( "#fig:flowchart" , "" )
+    ]
+]
+```
+
+```
+% pandoc -f latex -t native
 Accuracy~\eqref{eq:Accuracy} is the proportion, measuring true results among all results.
 
 \begin{equation}
@@ -28,8 +85,42 @@
   Accuracy = \frac{t_p + t_n}{t_p + f_p + f_n + t_n}
 \end{equation}
 ^D
-[Para [Str "Accuracy\160",Link ("",[],[("reference-type","eqref"),("reference","eq:Accuracy")]) [Str "[eq:Accuracy]"] ("#eq:Accuracy",""),Space,Str "is",Space,Str "the",Space,Str "proportion,",Space,Str "measuring",Space,Str "true",Space,Str "results",Space,Str "among",Space,Str "all",Space,Str "results."]
-,Para [Math DisplayMath "\\label{eq:Accuracy}\n  Accuracy = \\frac{t_p + t_n}{t_p + f_p + f_n + t_n}"]]
+[ Para
+    [ Str "Accuracy\160"
+    , Link
+        ( ""
+        , []
+        , [ ( "reference-type" , "eqref" )
+          , ( "reference" , "eq:Accuracy" )
+          ]
+        )
+        [ Str "[eq:Accuracy]" ]
+        ( "#eq:Accuracy" , "" )
+    , Space
+    , Str "is"
+    , Space
+    , Str "the"
+    , Space
+    , Str "proportion,"
+    , Space
+    , Str "measuring"
+    , Space
+    , Str "true"
+    , Space
+    , Str "results"
+    , Space
+    , Str "among"
+    , Space
+    , Str "all"
+    , Space
+    , Str "results."
+    ]
+, Para
+    [ Math
+        DisplayMath
+        "\\begin{equation}\n  \\label{eq:Accuracy}\n  Accuracy = \\frac{t_p + t_n}{t_p + f_p + f_n + t_n}\n\\end{equation}"
+    ]
+]
 ```
 
 ```
@@ -42,13 +133,177 @@
 
 Figure \ref{fig:Logo} illustrated the SVG logo
 ^D
-[Para [Image ("",[],[]) [Str "Logo",Span ("",[],[("label","fig:Logo")]) []] ("command/SVG_logo.svg","fig:")]
-,Para [Str "Figure",Space,Link ("",[],[("reference-type","ref"),("reference","fig:Logo")]) [Str "[fig:Logo]"] ("#fig:Logo",""),Space,Str "illustrated",Space,Str "the",Space,Str "SVG",Space,Str "logo"]]
+[ Figure
+    ( "fig:Logo" , [] , [] )
+    (Caption Nothing [ Plain [ Str "Logo" ] ])
+    [ Plain
+        [ Image ( "" , [] , [] ) [] ( "command/SVG_logo.svg" , "" )
+        ]
+    ]
+, Para
+    [ Str "Figure"
+    , Space
+    , Link
+        ( ""
+        , []
+        , [ ( "reference-type" , "ref" )
+          , ( "reference" , "fig:Logo" )
+          ]
+        )
+        [ Str "1" ]
+        ( "#fig:Logo" , "" )
+    , Space
+    , Str "illustrated"
+    , Space
+    , Str "the"
+    , Space
+    , Str "SVG"
+    , Space
+    , Str "logo"
+    ]
+]
 ```
 
 ```
 % pandoc -f latex -t native
+\chapter{One}
+\begin{figure}
+  \includegraphics{command/SVG_logo.svg}
+  \caption{Logo}
+  \label{fig:Logo}
+\end{figure}
+
+\begin{figure}
+  \includegraphics{command/SVG_logo2.svg}
+  \caption{Logo2}
+  \label{fig:Logo2}
+\end{figure}
+
+\chapter{Two}
+
+\section{Subone}
+
+\begin{figure}
+  \includegraphics{command/SVG_logo3.svg}
+  \caption{Logo3}
+  \label{fig:Logo3}
+\end{figure}
+
+Figure \ref{fig:Logo} illustrated the SVG logo
+
+Figure \ref{fig:Logo2} illustrated the SVG logo
+
+Figure \ref{fig:Logo3} illustrated the SVG logo
+^D
+[ Header 1 ( "one" , [] , [] ) [ Str "One" ]
+, Figure
+    ( "fig:Logo" , [] , [] )
+    (Caption Nothing [ Plain [ Str "Logo" ] ])
+    [ Plain
+        [ Image ( "" , [] , [] ) [] ( "command/SVG_logo.svg" , "" )
+        ]
+    ]
+, Figure
+    ( "fig:Logo2" , [] , [] )
+    (Caption Nothing [ Plain [ Str "Logo2" ] ])
+    [ Plain
+        [ Image ( "" , [] , [] ) [] ( "command/SVG_logo2.svg" , "" )
+        ]
+    ]
+, Header 1 ( "two" , [] , [] ) [ Str "Two" ]
+, Header 2 ( "subone" , [] , [] ) [ Str "Subone" ]
+, Figure
+    ( "fig:Logo3" , [] , [] )
+    (Caption Nothing [ Plain [ Str "Logo3" ] ])
+    [ Plain
+        [ Image ( "" , [] , [] ) [] ( "command/SVG_logo3.svg" , "" )
+        ]
+    ]
+, Para
+    [ Str "Figure"
+    , Space
+    , Link
+        ( ""
+        , []
+        , [ ( "reference-type" , "ref" )
+          , ( "reference" , "fig:Logo" )
+          ]
+        )
+        [ Str "1.1" ]
+        ( "#fig:Logo" , "" )
+    , Space
+    , Str "illustrated"
+    , Space
+    , Str "the"
+    , Space
+    , Str "SVG"
+    , Space
+    , Str "logo"
+    ]
+, Para
+    [ Str "Figure"
+    , Space
+    , Link
+        ( ""
+        , []
+        , [ ( "reference-type" , "ref" )
+          , ( "reference" , "fig:Logo2" )
+          ]
+        )
+        [ Str "1.2" ]
+        ( "#fig:Logo2" , "" )
+    , Space
+    , Str "illustrated"
+    , Space
+    , Str "the"
+    , Space
+    , Str "SVG"
+    , Space
+    , Str "logo"
+    ]
+, Para
+    [ Str "Figure"
+    , Space
+    , Link
+        ( ""
+        , []
+        , [ ( "reference-type" , "ref" )
+          , ( "reference" , "fig:Logo3" )
+          ]
+        )
+        [ Str "2.1" ]
+        ( "#fig:Logo3" , "" )
+    , Space
+    , Str "illustrated"
+    , Space
+    , Str "the"
+    , Space
+    , Str "SVG"
+    , Space
+    , Str "logo"
+    ]
+]
+```
+
+
+```
+% pandoc -f latex -t native
 \label{section} Section \ref{section}
 ^D
-[Para [Span ("section",[],[("label","section")]) [Str "[section]"],Space,Str "Section",Space,Link ("",[],[("reference-type","ref"),("reference","section")]) [Str "[section]"] ("#section","")]]
+[ Para
+    [ Span ( "section" , [] , [ ( "label" , "section" ) ] ) []
+    , Space
+    , Str "Section"
+    , Space
+    , Link
+        ( ""
+        , []
+        , [ ( "reference-type" , "ref" )
+          , ( "reference" , "section" )
+          ]
+        )
+        [ Str "[section]" ]
+        ( "#section" , "" )
+    ]
+]
 ```
diff --git a/test/command/reset-citation-positions.md b/test/command/reset-citation-positions.md
new file mode 100644
--- /dev/null
+++ b/test/command/reset-citation-positions.md
@@ -0,0 +1,41 @@
+```
+% pandoc --citeproc -t plain --csl command/chicago-fullnote-bibliography.csl
+---
+suppress-bibliography: true
+references:
+- id: foo
+  name: John doe
+  title: A Book
+  type: book
+  publisher: Oxford University Press
+  issued: 2010
+...
+
+# Chapter one
+
+Blah [@foo, p. 7].
+
+Blah [@foo, p. 8].
+
+# Chapter two {.reset-citation-positions}
+
+Blah [@foo, p. 57].
+^D
+Chapter one
+
+Blah.[1]
+
+Blah.[2]
+
+Chapter two
+
+Blah.[3]
+
+[1] A Book (Oxford University Press, 2010), 7.
+
+[2] A Book, 8.
+
+[3] A Book (Oxford University Press, 2010), 57.
+
+```
+
diff --git a/test/command/rst-writer-gridtable-if-rowspans.md b/test/command/rst-writer-gridtable-if-rowspans.md
new file mode 100644
--- /dev/null
+++ b/test/command/rst-writer-gridtable-if-rowspans.md
@@ -0,0 +1,246 @@
+```
+% pandoc -f native -t rst
+[ Table
+    ( "" , [] , [] )
+    (Caption Nothing [])
+    [ ( AlignDefault , ColWidthDefault )
+    , ( AlignDefault , ColWidthDefault )
+    , ( AlignDefault , ColWidthDefault )
+    ]
+    (TableHead ( "" , [] , [] ) [])
+    [ TableBody
+        ( "" , [] , [] )
+        (RowHeadColumns 0)
+        []
+        [ Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "1" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 2)
+                (ColSpan 1)
+                [ Plain [ Str "2" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "3" ] ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "1" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "3" ] ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "1" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "2" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "3" ] ]
+            ]
+        ]
+    ]
+    (TableFoot ( "" , [] , [] ) [])
+, Table
+    ( "" , [] , [] )
+    (Caption Nothing [])
+    [ ( AlignDefault , ColWidthDefault )
+    , ( AlignDefault , ColWidthDefault )
+    , ( AlignDefault , ColWidthDefault )
+    ]
+    (TableHead
+       ( "" , [] , [] )
+       [ Row
+           ( "" , [] , [] )
+           [ Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "1" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 2)
+               (ColSpan 1)
+               [ Plain [ Str "2" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "3" ] ]
+           ]
+       , Row
+           ( "" , [] , [] )
+           [ Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "1" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "3" ] ]
+           ]
+       ])
+    [ TableBody
+        ( "" , [] , [] )
+        (RowHeadColumns 0)
+        []
+        [ Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "1" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "2" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "3" ] ]
+            ]
+        ]
+    ]
+    (TableFoot ( "" , [] , [] ) [])
+, Table
+    ( "" , [] , [] )
+    (Caption Nothing [])
+    [ ( AlignDefault , ColWidthDefault )
+    , ( AlignDefault , ColWidthDefault )
+    , ( AlignDefault , ColWidthDefault )
+    ]
+    (TableHead ( "" , [] , [] ) [])
+    [ TableBody
+        ( "" , [] , [] )
+        (RowHeadColumns 0)
+        [] []
+    ]
+    (TableFoot ( "" , [] , [] )
+        [ Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "1" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 2)
+                (ColSpan 1)
+                [ Plain [ Str "2" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "3" ] ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "1" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "3" ] ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "1" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "2" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "3" ] ]
+            ]
+    ])
+]
+^D
++---+---+---+
+| 1 | 2 | 3 |
++---+   +---+
+| 1 |   | 3 |
++---+---+---+
+| 1 | 2 | 3 |
++---+---+---+
+
++---+---+---+
+| 1 | 2 | 3 |
++---+   +---+
+| 1 |   | 3 |
++===+===+===+
+| 1 | 2 | 3 |
++---+---+---+
+
++===+===+===+
+| 1 | 2 | 3 |
++---+   +---+
+| 1 |   | 3 |
++---+---+---+
+| 1 | 2 | 3 |
++===+===+===+
+```
diff --git a/test/command/rst_block_subst.md b/test/command/rst_block_subst.md
new file mode 100644
--- /dev/null
+++ b/test/command/rst_block_subst.md
@@ -0,0 +1,18 @@
+```
+% pandoc -f rst -t native
+|figure05|
+
+.. |figure05| figure:: img/dummy.png
+
+   capt
+^D
+[ Figure
+    ( "" , [] , [] )
+    (Caption Nothing [ Plain [ Str "capt" ] ])
+    [ Plain
+        [ Image
+            ( "" , [] , [] ) [ Str "capt" ] ( "img/dummy.png" , "" )
+        ]
+    ]
+]
+```
diff --git a/test/command/sage-harvard.csl b/test/command/sage-harvard.csl
new file mode 100644
--- /dev/null
+++ b/test/command/sage-harvard.csl
@@ -0,0 +1,202 @@
+<?xml version="1.0" encoding="utf-8"?>
+<style xmlns="http://purl.org/net/xbiblio/csl" class="in-text" version="1.0" demote-non-dropping-particle="never" default-locale="en-GB">
+  <info>
+    <title>SAGE - Harvard</title>
+    <id>http://www.zotero.org/styles/sage-harvard</id>
+    <link href="http://www.zotero.org/styles/sage-harvard" rel="self"/>
+    <link href="http://www.zotero.org/styles/the-open-university-harvard" rel="template"/>
+    <link href="http://www.uk.sagepub.com/repository/binaries/pdf/SAGE_Harvard_reference_style.pdf" rel="documentation"/>
+    <author>
+      <name>Joseph Reagle</name>
+    </author>
+    <category citation-format="author-date"/>
+    <category field="generic-base"/>
+    <summary>The SAGE Harvard author-date style</summary>
+    <updated>2012-09-27T22:06:38+00:00</updated>
+    <rights license="http://creativecommons.org/licenses/by-sa/3.0/">This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 License</rights>
+  </info>
+  <locale xml:lang="en-GB">
+    <terms>
+      <term name="editor" form="short">
+        <single>ed.</single>
+        <multiple>eds</multiple>
+      </term>
+    </terms>
+  </locale>
+  <macro name="editor">
+    <names variable="editor" delimiter=", ">
+      <name and="text" initialize-with="" delimiter=", " sort-separator=" " name-as-sort-order="all"/>
+      <label form="short" prefix=" (" suffix=")"/>
+    </names>
+  </macro>
+  <macro name="author">
+    <names variable="author">
+      <name initialize-with="" name-as-sort-order="all" and="text" sort-separator=" " delimiter=", " delimiter-precedes-last="never" form="long"/>
+      <label form="short" prefix=" (" suffix=")"/>
+      <substitute>
+        <names variable="editor"/>
+        <names variable="translator"/>
+        <text variable="container-title" font-style="italic"/>
+        <text macro="title"/>
+      </substitute>
+    </names>
+  </macro>
+  <macro name="author-count">
+    <names variable="author">
+      <name form="count"/>
+      <substitute>
+        <names variable="editor"/>
+      </substitute>
+    </names>
+  </macro>
+  <macro name="author-short">
+    <names variable="author">
+      <name form="short" and="text" delimiter=", " delimiter-precedes-last="never" initialize-with=""/>
+      <substitute>
+        <names variable="editor"/>
+        <names variable="translator"/>
+        <text variable="container-title" font-style="italic"/>
+        <text macro="title"/>
+      </substitute>
+    </names>
+  </macro>
+  <macro name="access">
+    <choose>
+      <if variable="URL">
+        <text value="Available from: "/>
+        <text variable="URL"/>
+        <group prefix=" (" delimiter=" " suffix=")">
+          <text term="accessed"/>
+          <date variable="accessed">
+            <date-part name="day" suffix=" "/>
+            <date-part name="month" suffix=" "/>
+            <date-part name="year"/>
+          </date>
+        </group>
+      </if>
+    </choose>
+  </macro>
+  <macro name="title">
+    <choose>
+      <if type="bill book graphic legal_case motion_picture report song" match="any">
+        <text variable="title" font-style="italic"/>
+      </if>
+      <else>
+        <text variable="title"/>
+      </else>
+    </choose>
+  </macro>
+  <macro name="publisher">
+    <group delimiter=": ">
+      <text variable="publisher-place"/>
+      <text variable="publisher"/>
+    </group>
+  </macro>
+  <macro name="year-date">
+    <choose>
+      <if variable="issued">
+        <date variable="issued">
+          <date-part name="year"/>
+        </date>
+      </if>
+      <else>
+        <text term="no date" form="short"/>
+      </else>
+    </choose>
+  </macro>
+  <macro name="locator">
+    <choose>
+      <if type="article-journal">
+        <text variable="volume"/>
+        <text variable="issue" prefix="(" suffix=")"/>
+      </if>
+    </choose>
+  </macro>
+  <macro name="published-date">
+    <choose>
+      <if type="article-newspaper">
+        <date variable="issued">
+          <date-part name="day" form="ordinal" suffix=" "/>
+          <date-part name="month" form="long"/>
+        </date>
+      </if>
+    </choose>
+  </macro>
+  <macro name="pages">
+    <choose>
+      <if type="chapter paper-conference" match="any">
+        <group delimiter=" " prefix=", ">
+          <label variable="page" form="short" suffix=" "/>
+          <text variable="page"/>
+        </group>
+      </if>
+      <else-if type="article-journal">
+        <text variable="page" prefix=": "/>
+      </else-if>
+    </choose>
+  </macro>
+  <macro name="edition">
+    <choose>
+      <if is-numeric="edition">
+        <group delimiter=" ">
+          <number variable="edition" form="ordinal"/>
+          <text term="edition" form="short"/>
+        </group>
+      </if>
+      <else>
+        <text variable="edition" suffix="."/>
+      </else>
+    </choose>
+  </macro>
+  <macro name="container-prefix">
+    <choose>
+      <if type="chapter paper-conference" match="any">
+        <text term="in" text-case="capitalize-first" suffix=": "/>
+      </if>
+    </choose>
+  </macro>
+  <citation et-al-min="3" et-al-use-first="1" disambiguate-add-year-suffix="true" disambiguate-add-names="true" disambiguate-add-givenname="true" collapse="year">
+    <sort>
+      <key macro="author-short"/>
+      <key macro="year-date"/>
+    </sort>
+    <layout prefix="(" suffix=")" delimiter="; ">
+      <group delimiter=": ">
+        <group delimiter=", ">
+          <text macro="author-short"/>
+          <text macro="year-date"/>
+        </group>
+        <text variable="locator"/>
+      </group>
+    </layout>
+  </citation>
+  <bibliography hanging-indent="true" et-al-min="4" et-al-use-first="3">
+    <sort>
+      <key macro="author" names-min="1" names-use-first="1"/>
+      <key macro="author-count" names-min="3" names-use-first="3"/>
+      <key macro="author" names-min="3" names-use-first="1"/>
+      <key macro="year-date"/>
+      <key variable="title"/>
+    </sort>
+    <layout suffix=".">
+      <group delimiter=" ">
+        <text macro="author"/>
+        <text macro="year-date" prefix="(" suffix=")"/>
+        <text macro="title" suffix="."/>
+        <text macro="edition"/>
+        <text macro="container-prefix"/>
+        <group delimiter=", ">
+          <text macro="editor"/>
+          <text variable="container-title" font-style="italic"/>
+          <text variable="collection-title"/>
+          <text variable="genre"/>
+          <text macro="publisher"/>
+          <text macro="published-date"/>
+        </group>
+        <text macro="locator"/>
+      </group>
+      <text macro="pages"/>
+      <text macro="access" prefix=". "/>
+    </layout>
+  </bibliography>
+</style>
diff --git a/test/command/science.csl b/test/command/science.csl
new file mode 100644
--- /dev/null
+++ b/test/command/science.csl
@@ -0,0 +1,245 @@
+<?xml version="1.0" encoding="utf-8"?>
+<style xmlns="http://purl.org/net/xbiblio/csl" class="in-text" version="1.0" demote-non-dropping-particle="sort-only" default-locale="en-US">
+  <info>
+    <title>Science</title>
+    <id>http://www.zotero.org/styles/science</id>
+    <link href="http://www.zotero.org/styles/science" rel="self"/>
+    <link href="http://www.sciencemag.org/about/authors/prep/res/refs.dtl" rel="documentation"/>
+    <author>
+      <name>Julian Onions</name>
+      <email>julian.onions@gmail.com</email>
+    </author>
+    <contributor>
+      <name>Sebastian Karcher</name>
+    </contributor>
+    <contributor>
+      <name>Greg Barendt</name>
+    </contributor>
+    <category citation-format="numeric"/>
+    <category field="science"/>
+    <issn>0036-8075</issn>
+    <eissn>1095-9203</eissn>
+    <summary>The Science journal style.</summary>
+    <updated>2014-06-18T08:06:38+00:00</updated>
+    <rights license="http://creativecommons.org/licenses/by-sa/3.0/">This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 License</rights>
+  </info>
+  <macro name="editor">
+    <names variable="editor" delimiter=", ">
+      <name initialize-with=". " delimiter=", " delimiter-precedes-last="always"/>
+      <label form="short" prefix=", " text-case="capitalize-first"/>
+    </names>
+  </macro>
+  <macro name="author">
+    <names variable="author">
+      <name sort-separator=", " initialize-with=". " delimiter=", " delimiter-precedes-last="always"/>
+      <label form="short" prefix=", " text-case="capitalize-first"/>
+      <et-al font-style="italic"/>
+      <substitute>
+        <names variable="editor"/>
+      </substitute>
+    </names>
+  </macro>
+  <macro name="access">
+    <choose>
+      <if variable="page" match="none">
+        <text macro="access-value"/>
+      </if>
+      <else-if is-numeric="page" match="none">
+        <text macro="access-value"/>
+      </else-if>
+    </choose>
+  </macro>
+  <macro name="access-value">
+    <choose>
+      <if variable="DOI">
+        <text variable="DOI" prefix=", doi:"/>
+      </if>
+      <else>
+        <group prefix=" (" suffix=")">
+          <text value="available at "/>
+          <text variable="URL"/>
+        </group>
+      </else>
+    </choose>
+  </macro>
+  <macro name="title">
+    <choose>
+      <if type="bill book graphic legal_case legislation motion_picture report song" match="any">
+        <text variable="title" font-style="italic"/>
+      </if>
+      <else>
+        <text variable="title"/>
+      </else>
+    </choose>
+  </macro>
+  <macro name="article-details">
+    <group delimiter=", ">
+      <group delimiter=". ">
+        <text macro="title"/>
+        <text form="short" variable="container-title" font-style="italic"/>
+        <text variable="volume" font-weight="bold"/>
+      </group>
+      <text variable="page"/>
+    </group>
+    <text macro="issued" prefix=" (" suffix=")"/>
+    <text macro="access"/>
+  </macro>
+  <macro name="publisher">
+    <group delimiter=", ">
+      <text variable="publisher"/>
+      <text variable="publisher-place"/>
+    </group>
+  </macro>
+  <macro name="volume">
+    <text variable="volume" prefix="vol. "/>
+  </macro>
+  <macro name="pages">
+    <label variable="page" form="short" suffix=" "/>
+    <text variable="page" form="short"/>
+  </macro>
+  <macro name="issued">
+    <date variable="issued" delimiter=" ">
+      <date-part name="year"/>
+    </date>
+  </macro>
+  <macro name="edition">
+    <choose>
+      <if is-numeric="edition">
+        <group delimiter=" ">
+          <text term="edition" form="short"/>
+          <number variable="edition" form="numeric"/>
+        </group>
+      </if>
+      <else>
+        <text variable="edition" suffix="."/>
+      </else>
+    </choose>
+  </macro>
+  <citation collapse="citation-number">
+    <sort>
+      <key variable="citation-number"/>
+    </sort>
+    <layout prefix="(" suffix=")" delimiter=", ">
+      <text variable="citation-number" font-style="italic"/>
+    </layout>
+  </citation>
+  <bibliography et-al-min="6" et-al-use-first="1" second-field-align="flush">
+    <layout suffix=".">
+      <text variable="citation-number" suffix=". "/>
+      <group delimiter=", ">
+        <text macro="author"/>
+        <choose>
+          <if type="thesis">
+            <group delimiter=" ">
+              <group delimiter=", ">
+                <group>
+                  <!-- Always print, even if no university given -->
+                  <text value="thesis"/>
+                </group>
+                <text macro="publisher"/>
+              </group>
+              <text macro="issued" prefix="(" suffix=")"/>
+            </group>
+          </if>
+          <else-if type="bill book graphic legal_case legislation motion_picture song chapter paper-conference" match="any">
+            <group delimiter=" ">
+              <choose>
+                <if type="chapter paper-conference" match="any">
+                  <group delimiter=", ">
+                    <group delimiter=" ">
+                      <text term="in"/>
+                      <text variable="container-title" font-style="italic"/>
+                    </group>
+                    <text macro="editor"/>
+                  </group>
+                </if>
+                <else>
+                  <text macro="title"/>
+                </else>
+              </choose>
+              <group prefix="(" suffix=")" delimiter="; ">
+                <group delimiter=", ">
+                  <text macro="publisher"/>
+                  <text macro="edition"/>
+                  <text macro="issued"/>
+                </group>
+                <text variable="URL"/>
+              </group>
+            </group>
+            <group delimiter=" of ">
+              <group>
+                <label variable="volume" form="short" suffix=" "/>
+                <number variable="volume"/>
+              </group>
+              <text variable="collection-title" font-style="italic"/>
+            </group>
+            <choose>
+              <if type="chapter paper-conference" match="any">
+                <text macro="pages"/>
+              </if>
+            </choose>
+          </else-if>
+          <else-if type="article-journal">
+            <choose>
+              <if variable="page">
+                <choose>
+                  <if is-numeric="page" match="none">
+                    <group>
+                      <group delimiter=", ">
+                        <text variable="container-title" form="short" font-style="italic"/>
+                        <group>
+                          <text term="in press"/>
+                        </group>
+                      </group>
+                      <text macro="access"/>
+                    </group>
+                  </if>
+                  <else>
+                    <text macro="article-details"/>
+                  </else>
+                </choose>
+              </if>
+              <else>
+                <text macro="article-details"/>
+              </else>
+            </choose>
+          </else-if>
+          <else-if type="report">
+            <group>
+              <group delimiter=", ">
+                <text variable="title" quotes="true"/>
+                <text variable="collection-title" font-style="italic"/>
+              </group>
+              <group prefix=" (" suffix=")" delimiter=", ">
+                <group delimiter=" ">
+                  <text variable="genre" form="short"/>
+                  <number variable="number"/>
+                </group>
+                <text variable="publisher"/>
+                <text variable="publisher-place"/>
+                <text macro="issued"/>
+              </group>
+            </group>
+            <text macro="pages"/>
+            <text macro="access"/>
+          </else-if>
+          <else>
+            <group>
+              <group delimiter=", ">
+                <text macro="editor"/>
+                <group delimiter=". ">
+                  <text macro="title"/>
+                  <text form="short" variable="container-title" font-style="italic"/>
+                  <text variable="volume" font-weight="bold"/>
+                </group>
+              </group>
+              <text macro="issued" prefix=" (" suffix=")"/>
+            </group>
+            <text macro="pages"/>
+            <text macro="access"/>
+          </else>
+        </choose>
+      </group>
+    </layout>
+  </bibliography>
+</style>
diff --git a/test/command/section-divs.md b/test/command/section-divs.md
new file mode 100644
--- /dev/null
+++ b/test/command/section-divs.md
@@ -0,0 +1,25 @@
+```
+% pandoc  --section-divs
+::: {#hi .section .level1}
+# Hi
+
+::: {#there .section .level2}
+## there
+:::
+:::
+
+::: {#ok .section .level1}
+Ok
+==
+:::
+^D
+<section id="hi" class="level1">
+<h1>Hi</h1>
+<section id="there" class="level2">
+<h2>there</h2>
+</section>
+</section>
+<section id="ok" class="level1">
+<h1>Ok</h1>
+</section>
+```
diff --git a/test/command/setext-fenced-div.md b/test/command/setext-fenced-div.md
new file mode 100644
--- /dev/null
+++ b/test/command/setext-fenced-div.md
@@ -0,0 +1,8 @@
+```
+% pandoc -t native
+::: {.cell}
+---
+:::
+^D
+[ Div ( "" , [ "cell" ] , [] ) [ HorizontalRule ] ]
+```
diff --git a/test/command/shift-heading-level-by.md b/test/command/shift-heading-level-by.md
new file mode 100644
--- /dev/null
+++ b/test/command/shift-heading-level-by.md
@@ -0,0 +1,59 @@
+```
+% pandoc --shift-heading-level-by 1 -t native -s
+---
+title: My title
+...
+
+# First heading
+
+## Second
+^D
+Pandoc
+  Meta
+    { unMeta =
+        fromList
+          [ ( "title"
+            , MetaInlines [ Str "My" , Space , Str "title" ]
+            )
+          ]
+    }
+  [ Header
+      2
+      ( "first-heading" , [] , [] )
+      [ Str "First" , Space , Str "heading" ]
+  , Header 3 ( "second" , [] , [] ) [ Str "Second" ]
+  ]
+```
+
+```
+% pandoc --shift-heading-level-by -1 -t native -s
+---
+title: Old title
+...
+
+# First heading
+
+## Second
+
+# Another top-level heading
+^D
+Pandoc
+  Meta
+    { unMeta =
+        fromList
+          [ ( "title"
+            , MetaInlines [ Str "First" , Space , Str "heading" ]
+            )
+          ]
+    }
+  [ Header 1 ( "second" , [] , [] ) [ Str "Second" ]
+  , Para
+      [ Str "Another"
+      , Space
+      , Str "top-level"
+      , Space
+      , Str "heading"
+      ]
+  ]
+```
+
diff --git a/test/command/short-caption.md b/test/command/short-caption.md
new file mode 100644
--- /dev/null
+++ b/test/command/short-caption.md
@@ -0,0 +1,42 @@
+```
+% pandoc -f latex -t native
+\begin{table}
+\caption[short caption]{long caption}
+\begin{tabular}{ll}
+hi & hi \\
+\end{tabular}
+\end{table}
+^D
+[ Table
+    ( "" , [] , [] )
+    (Caption
+       (Just [ Str "short" , Space , Str "caption" ])
+       [ Plain [ Str "long" , Space , Str "caption" ] ])
+    [ ( AlignLeft , ColWidthDefault )
+    , ( AlignLeft , ColWidthDefault )
+    ]
+    (TableHead ( "" , [] , [] ) [])
+    [ TableBody
+        ( "" , [] , [] )
+        (RowHeadColumns 0)
+        []
+        [ Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "hi" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "hi" ] ]
+            ]
+        ]
+    ]
+    (TableFoot ( "" , [] , [] ) [])
+]
+```
diff --git a/test/command/sloppypar.md b/test/command/sloppypar.md
new file mode 100644
--- /dev/null
+++ b/test/command/sloppypar.md
@@ -0,0 +1,229 @@
+```
+% pandoc -f latex+raw_tex -t native
+\begin{sloppypar}
+Sequi id qui facere et incidunt ut. Et fuga ut voluptate enim qui. Odit unde magni ipsam dicta modi. Modi soluta velit est aut aut possimus.
+
+Qui et temporibus explicabo. Esse ab ut quidem. Vel qui perspiciatis quae odio consectetur alias non sed. Quo consectetur libero omnis quos eius ad vel.
+\end{sloppypar}
+^D
+[ Para
+    [ Str "Sequi"
+    , Space
+    , Str "id"
+    , Space
+    , Str "qui"
+    , Space
+    , Str "facere"
+    , Space
+    , Str "et"
+    , Space
+    , Str "incidunt"
+    , Space
+    , Str "ut."
+    , Space
+    , Str "Et"
+    , Space
+    , Str "fuga"
+    , Space
+    , Str "ut"
+    , Space
+    , Str "voluptate"
+    , Space
+    , Str "enim"
+    , Space
+    , Str "qui."
+    , Space
+    , Str "Odit"
+    , Space
+    , Str "unde"
+    , Space
+    , Str "magni"
+    , Space
+    , Str "ipsam"
+    , Space
+    , Str "dicta"
+    , Space
+    , Str "modi."
+    , Space
+    , Str "Modi"
+    , Space
+    , Str "soluta"
+    , Space
+    , Str "velit"
+    , Space
+    , Str "est"
+    , Space
+    , Str "aut"
+    , Space
+    , Str "aut"
+    , Space
+    , Str "possimus."
+    ]
+, Para
+    [ Str "Qui"
+    , Space
+    , Str "et"
+    , Space
+    , Str "temporibus"
+    , Space
+    , Str "explicabo."
+    , Space
+    , Str "Esse"
+    , Space
+    , Str "ab"
+    , Space
+    , Str "ut"
+    , Space
+    , Str "quidem."
+    , Space
+    , Str "Vel"
+    , Space
+    , Str "qui"
+    , Space
+    , Str "perspiciatis"
+    , Space
+    , Str "quae"
+    , Space
+    , Str "odio"
+    , Space
+    , Str "consectetur"
+    , Space
+    , Str "alias"
+    , Space
+    , Str "non"
+    , Space
+    , Str "sed."
+    , Space
+    , Str "Quo"
+    , Space
+    , Str "consectetur"
+    , Space
+    , Str "libero"
+    , Space
+    , Str "omnis"
+    , Space
+    , Str "quos"
+    , Space
+    , Str "eius"
+    , Space
+    , Str "ad"
+    , Space
+    , Str "vel."
+    ]
+]
+```
+
+```
+% pandoc -f latex -t native
+\begin{sloppypar}
+Sequi id qui facere et incidunt ut. Et fuga ut voluptate enim qui. Odit unde magni ipsam dicta modi. Modi soluta velit est aut aut possimus.
+
+Qui et temporibus explicabo. Esse ab ut quidem. Vel qui perspiciatis quae odio consectetur alias non sed. Quo consectetur libero omnis quos eius ad vel.
+\end{sloppypar}
+^D
+[ Para
+    [ Str "Sequi"
+    , Space
+    , Str "id"
+    , Space
+    , Str "qui"
+    , Space
+    , Str "facere"
+    , Space
+    , Str "et"
+    , Space
+    , Str "incidunt"
+    , Space
+    , Str "ut."
+    , Space
+    , Str "Et"
+    , Space
+    , Str "fuga"
+    , Space
+    , Str "ut"
+    , Space
+    , Str "voluptate"
+    , Space
+    , Str "enim"
+    , Space
+    , Str "qui."
+    , Space
+    , Str "Odit"
+    , Space
+    , Str "unde"
+    , Space
+    , Str "magni"
+    , Space
+    , Str "ipsam"
+    , Space
+    , Str "dicta"
+    , Space
+    , Str "modi."
+    , Space
+    , Str "Modi"
+    , Space
+    , Str "soluta"
+    , Space
+    , Str "velit"
+    , Space
+    , Str "est"
+    , Space
+    , Str "aut"
+    , Space
+    , Str "aut"
+    , Space
+    , Str "possimus."
+    ]
+, Para
+    [ Str "Qui"
+    , Space
+    , Str "et"
+    , Space
+    , Str "temporibus"
+    , Space
+    , Str "explicabo."
+    , Space
+    , Str "Esse"
+    , Space
+    , Str "ab"
+    , Space
+    , Str "ut"
+    , Space
+    , Str "quidem."
+    , Space
+    , Str "Vel"
+    , Space
+    , Str "qui"
+    , Space
+    , Str "perspiciatis"
+    , Space
+    , Str "quae"
+    , Space
+    , Str "odio"
+    , Space
+    , Str "consectetur"
+    , Space
+    , Str "alias"
+    , Space
+    , Str "non"
+    , Space
+    , Str "sed."
+    , Space
+    , Str "Quo"
+    , Space
+    , Str "consectetur"
+    , Space
+    , Str "libero"
+    , Space
+    , Str "omnis"
+    , Space
+    , Str "quos"
+    , Space
+    , Str "eius"
+    , Space
+    , Str "ad"
+    , Space
+    , Str "vel."
+    ]
+]
+```
diff --git a/test/command/style399.csl b/test/command/style399.csl
new file mode 100644
--- /dev/null
+++ b/test/command/style399.csl
@@ -0,0 +1,12 @@
+<?xml version="1.0" encoding="utf-8"?>
+<style xmlns="http://purl.org/net/xbiblio/csl" class="in-text" version="1.0" demote-non-dropping-particle="never" default-locale="en-US">
+  <citation>
+    <sort>
+      <key variable="citation-number"/>
+    </sort>
+    <layout prefix="[" suffix="]" delimiter=",">
+      <text variable="citation-number"/>
+    </layout>
+  </citation>
+</style>
+
diff --git a/test/command/svg.md b/test/command/svg.md
--- a/test/command/svg.md
+++ b/test/command/svg.md
@@ -2,7 +2,7 @@
 % pandoc -f latex -t icml
 \includegraphics{command/corrupt.svg}
 ^D
-[WARNING] Could not determine image size for 'command/corrupt.svg': could not determine image type
+2> [WARNING] Could not determine image size for command/corrupt.svg: could not determine image type
 <ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/Paragraph">
   <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
     <Rectangle Self="uec" StrokeWeight="0" ItemTransform="1 0 0 1 150 -100">
@@ -23,6 +23,7 @@
           <Profile type="string">
             $ID/Embedded
           </Profile>
+          <GraphicBounds Left="0" Top="0" Right="300" Bottom="200" />
         </Properties>
         <Link Self="ueb" LinkResourceURI="file:command/corrupt.svg" />
       </Image>
@@ -35,27 +36,27 @@
 % pandoc -f latex -t icml
 \includegraphics{command/SVG_logo.svg}
 ^D
-[WARNING] Could not determine image size for 'command/SVG_logo.svg': could not determine SVG size
 <ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/Paragraph">
   <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
-    <Rectangle Self="uec" StrokeWeight="0" ItemTransform="1 0 0 1 150 -100">
+    <Rectangle Self="uec" StrokeWeight="0" ItemTransform="1 0 0 1 37.5 -37.5">
       <Properties>
         <PathGeometry>
           <GeometryPathType PathOpen="false">
             <PathPointArray>
-              <PathPointType Anchor="-150 -100" LeftDirection="-150 -100" RightDirection="-150 -100" />
-              <PathPointType Anchor="-150 100" LeftDirection="-150 100" RightDirection="-150 100" />
-              <PathPointType Anchor="150 100" LeftDirection="150 100" RightDirection="150 100" />
-              <PathPointType Anchor="150 -100" LeftDirection="150 -100" RightDirection="150 -100" />
+              <PathPointType Anchor="-37.5 -37.5" LeftDirection="-37.5 -37.5" RightDirection="-37.5 -37.5" />
+              <PathPointType Anchor="-37.5 37.5" LeftDirection="-37.5 37.5" RightDirection="-37.5 37.5" />
+              <PathPointType Anchor="37.5 37.5" LeftDirection="37.5 37.5" RightDirection="37.5 37.5" />
+              <PathPointType Anchor="37.5 -37.5" LeftDirection="37.5 -37.5" RightDirection="37.5 -37.5" />
             </PathPointArray>
           </GeometryPathType>
         </PathGeometry>
       </Properties>
-      <Image Self="ue6" ItemTransform="1 0 0 1 -150 -100">
+      <Image Self="ue6" ItemTransform="1 0 0 1 -37.5 -37.5">
         <Properties>
           <Profile type="string">
             $ID/Embedded
           </Profile>
+          <GraphicBounds Left="0" Top="0" Right="75" Bottom="75" />
         </Properties>
         <Link Self="ueb" LinkResourceURI="file:command/SVG_logo.svg" />
       </Image>
@@ -68,27 +69,27 @@
 % pandoc -f latex -t icml
 \includegraphics{command/SVG_logo-without-xml-declaration.svg}
 ^D
-[WARNING] Could not determine image size for 'command/SVG_logo-without-xml-declaration.svg': could not determine SVG size
 <ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/Paragraph">
   <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
-    <Rectangle Self="uec" StrokeWeight="0" ItemTransform="1 0 0 1 150 -100">
+    <Rectangle Self="uec" StrokeWeight="0" ItemTransform="1 0 0 1 37.5 -37.5">
       <Properties>
         <PathGeometry>
           <GeometryPathType PathOpen="false">
             <PathPointArray>
-              <PathPointType Anchor="-150 -100" LeftDirection="-150 -100" RightDirection="-150 -100" />
-              <PathPointType Anchor="-150 100" LeftDirection="-150 100" RightDirection="-150 100" />
-              <PathPointType Anchor="150 100" LeftDirection="150 100" RightDirection="150 100" />
-              <PathPointType Anchor="150 -100" LeftDirection="150 -100" RightDirection="150 -100" />
+              <PathPointType Anchor="-37.5 -37.5" LeftDirection="-37.5 -37.5" RightDirection="-37.5 -37.5" />
+              <PathPointType Anchor="-37.5 37.5" LeftDirection="-37.5 37.5" RightDirection="-37.5 37.5" />
+              <PathPointType Anchor="37.5 37.5" LeftDirection="37.5 37.5" RightDirection="37.5 37.5" />
+              <PathPointType Anchor="37.5 -37.5" LeftDirection="37.5 -37.5" RightDirection="37.5 -37.5" />
             </PathPointArray>
           </GeometryPathType>
         </PathGeometry>
       </Properties>
-      <Image Self="ue6" ItemTransform="1 0 0 1 -150 -100">
+      <Image Self="ue6" ItemTransform="1 0 0 1 -37.5 -37.5">
         <Properties>
           <Profile type="string">
             $ID/Embedded
           </Profile>
+          <GraphicBounds Left="0" Top="0" Right="75" Bottom="75" />
         </Properties>
         <Link Self="ueb" LinkResourceURI="file:command/SVG_logo-without-xml-declaration.svg" />
       </Image>
@@ -122,6 +123,7 @@
           <Profile type="string">
             $ID/Embedded
           </Profile>
+          <GraphicBounds Left="0" Top="0" Right="109.5" Bottom="130.5" />
         </Properties>
         <Link Self="ueb" LinkResourceURI="file:command/inkscape-cube.svg" />
       </Image>
diff --git a/test/command/table-with-cell-align.md b/test/command/table-with-cell-align.md
new file mode 100644
--- /dev/null
+++ b/test/command/table-with-cell-align.md
@@ -0,0 +1,105 @@
+```
+% pandoc -f docbook -t native --quiet
+<informaltable frame="all" rowsep="1" colsep="1">
+<tgroup cols="16">
+<tbody>
+<row>
+<entry align="center" valign="top"><simpara>1</simpara></entry>
+<entry align="left" valign="top"><simpara>2</simpara></entry>
+<entry align="right" valign="top"><simpara>3</simpara></entry>
+<entry align="justify" valign="top"><simpara>4</simpara></entry>
+</row>
+</tbody>
+</tgroup>
+</informaltable>
+^D
+[ Table
+    ( "" , [] , [] )
+    (Caption Nothing [])
+    [ ( AlignDefault , ColWidthDefault )
+    , ( AlignDefault , ColWidthDefault )
+    , ( AlignDefault , ColWidthDefault )
+    , ( AlignDefault , ColWidthDefault )
+    ]
+    (TableHead ( "" , [] , [] ) [])
+    [ TableBody
+        ( "" , [] , [] )
+        (RowHeadColumns 0)
+        []
+        [ Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignCenter
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Para [ Str "1" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignLeft
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Para [ Str "2" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignRight
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Para [ Str "3" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Para [ Str "4" ] ]
+            ]
+        ]
+    ]
+    (TableFoot ( "" , [] , [] ) [])
+]
+```
+```
+% pandoc -f native -t opendocument --quiet
+[Table ("",[],[]) (Caption Nothing
+ [])
+ [(AlignDefault,ColWidthDefault)
+ ,(AlignDefault,ColWidthDefault)
+ ,(AlignDefault,ColWidthDefault)
+ ,(AlignDefault,ColWidthDefault)]
+ (TableHead ("",[],[])
+ [])
+ [(TableBody ("",[],[]) (RowHeadColumns 0)
+  []
+  [Row ("",[],[])
+   [Cell ("",[],[]) AlignCenter (RowSpan 1) (ColSpan 1)
+    [Para [Str "1"]]
+   ,Cell ("",[],[]) AlignLeft (RowSpan 1) (ColSpan 1)
+    [Para [Str "2"]]
+   ,Cell ("",[],[]) AlignRight (RowSpan 1) (ColSpan 1)
+    [Para [Str "3"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Para [Str "4"]]]])]
+ (TableFoot ("",[],[])
+ [])]
+^D
+<table:table table:name="Table1" table:style-name="Table1">
+  <table:table-column table:style-name="Table1.A" />
+  <table:table-column table:style-name="Table1.B" />
+  <table:table-column table:style-name="Table1.C" />
+  <table:table-column table:style-name="Table1.D" />
+  <table:table-row>
+    <table:table-cell table:style-name="TableRowCell" office:value-type="string">
+      <text:p text:style-name="P1">1</text:p>
+    </table:table-cell>
+    <table:table-cell table:style-name="TableRowCell" office:value-type="string">
+      <text:p text:style-name="Table_20_Contents">2</text:p>
+    </table:table-cell>
+    <table:table-cell table:style-name="TableRowCell" office:value-type="string">
+      <text:p text:style-name="P2">3</text:p>
+    </table:table-cell>
+    <table:table-cell table:style-name="TableRowCell" office:value-type="string">
+      <text:p text:style-name="Table_20_Contents">4</text:p>
+    </table:table-cell>
+  </table:table-row>
+</table:table>
+```
diff --git a/test/command/table-with-column-span.md b/test/command/table-with-column-span.md
new file mode 100644
--- /dev/null
+++ b/test/command/table-with-column-span.md
@@ -0,0 +1,385 @@
+```
+% pandoc -f docbook -t native --quiet
+<informaltable frame="all" rowsep="1" colsep="1">
+<tgroup cols="16">
+<colspec colname="col_1" colwidth="6.25*"/>
+<colspec colname="col_2" colwidth="6.25*"/>
+<colspec colname="col_3" colwidth="6.25*"/>
+<colspec colname="col_4" colwidth="6.25*"/>
+<colspec colname="col_5" colwidth="6.25*"/>
+<colspec colname="col_6" colwidth="6.25*"/>
+<colspec colname="col_7" colwidth="6.25*"/>
+<colspec colname="col_8" colwidth="6.25*"/>
+<colspec colname="col_9" colwidth="6.25*"/>
+<colspec colname="col_10" colwidth="6.25*"/>
+<colspec colname="col_11" colwidth="6.25*"/>
+<colspec colname="col_12" colwidth="6.25*"/>
+<colspec colname="col_13" colwidth="6.25*"/>
+<colspec colname="col_14" colwidth="6.25*"/>
+<colspec colname="col_15" colwidth="6.25*"/>
+<colspec colname="col_16" colwidth="6.25*"/>
+<tbody>
+<row>
+<entry align="center" valign="top" namest="col_1" nameend="col_8"><simpara><emphasis role="strong">Octet no. 1</emphasis></simpara></entry>
+<entry align="center" valign="top" namest="col_2" nameend="col_9"><simpara><emphasis role="strong">Octet no. 2</emphasis></simpara></entry>
+</row>
+<row>
+<entry align="center" valign="top"><simpara>16</simpara></entry>
+<entry align="center" valign="top"><simpara>15</simpara></entry>
+<entry align="center" valign="top"><simpara>14</simpara></entry>
+<entry align="center" valign="top"><simpara>13</simpara></entry>
+<entry align="center" valign="top"><simpara>12</simpara></entry>
+<entry align="center" valign="top"><simpara>11</simpara></entry>
+<entry align="center" valign="top"><simpara>10</simpara></entry>
+<entry align="center" valign="top"><simpara>9</simpara></entry>
+<entry align="center" valign="top"><simpara>8</simpara></entry>
+<entry align="center" valign="top"><simpara>7</simpara></entry>
+<entry align="center" valign="top"><simpara>6</simpara></entry>
+<entry align="center" valign="top"><simpara>5</simpara></entry>
+<entry align="center" valign="top"><simpara>4</simpara></entry>
+<entry align="center" valign="top"><simpara>3</simpara></entry>
+<entry align="center" valign="top"><simpara>2</simpara></entry>
+<entry align="center" valign="top"><simpara>1</simpara></entry>
+</row>
+<row>
+<entry align="center" valign="top" namest="col_1" nameend="col_8"><simpara>Code A</simpara></entry>
+<entry align="center" valign="top" namest="col_2" nameend="col_9"><simpara>Code B</simpara></entry>
+</row>
+</tbody>
+</tgroup>
+</informaltable>
+^D
+[ Table
+    ( "" , [] , [] )
+    (Caption Nothing [])
+    [ ( AlignDefault , ColWidth 6.25e-2 )
+    , ( AlignDefault , ColWidth 6.25e-2 )
+    , ( AlignDefault , ColWidth 6.25e-2 )
+    , ( AlignDefault , ColWidth 6.25e-2 )
+    , ( AlignDefault , ColWidth 6.25e-2 )
+    , ( AlignDefault , ColWidth 6.25e-2 )
+    , ( AlignDefault , ColWidth 6.25e-2 )
+    , ( AlignDefault , ColWidth 6.25e-2 )
+    , ( AlignDefault , ColWidth 6.25e-2 )
+    , ( AlignDefault , ColWidth 6.25e-2 )
+    , ( AlignDefault , ColWidth 6.25e-2 )
+    , ( AlignDefault , ColWidth 6.25e-2 )
+    , ( AlignDefault , ColWidth 6.25e-2 )
+    , ( AlignDefault , ColWidth 6.25e-2 )
+    , ( AlignDefault , ColWidth 6.25e-2 )
+    , ( AlignDefault , ColWidth 6.25e-2 )
+    ]
+    (TableHead ( "" , [] , [] ) [])
+    [ TableBody
+        ( "" , [] , [] )
+        (RowHeadColumns 0)
+        []
+        [ Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignCenter
+                (RowSpan 1)
+                (ColSpan 8)
+                [ Para
+                    [ Strong
+                        [ Str "Octet"
+                        , Space
+                        , Str "no."
+                        , Space
+                        , Str "1"
+                        ]
+                    ]
+                ]
+            , Cell
+                ( "" , [] , [] )
+                AlignCenter
+                (RowSpan 1)
+                (ColSpan 8)
+                [ Para
+                    [ Strong
+                        [ Str "Octet"
+                        , Space
+                        , Str "no."
+                        , Space
+                        , Str "2"
+                        ]
+                    ]
+                ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignCenter
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Para [ Str "16" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignCenter
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Para [ Str "15" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignCenter
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Para [ Str "14" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignCenter
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Para [ Str "13" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignCenter
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Para [ Str "12" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignCenter
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Para [ Str "11" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignCenter
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Para [ Str "10" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignCenter
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Para [ Str "9" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignCenter
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Para [ Str "8" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignCenter
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Para [ Str "7" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignCenter
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Para [ Str "6" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignCenter
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Para [ Str "5" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignCenter
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Para [ Str "4" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignCenter
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Para [ Str "3" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignCenter
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Para [ Str "2" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignCenter
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Para [ Str "1" ] ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignCenter
+                (RowSpan 1)
+                (ColSpan 8)
+                [ Para [ Str "Code" , Space , Str "A" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignCenter
+                (RowSpan 1)
+                (ColSpan 8)
+                [ Para [ Str "Code" , Space , Str "B" ] ]
+            ]
+        ]
+    ]
+    (TableFoot ( "" , [] , [] ) [])
+]
+```
+```
+% pandoc -f native -t opendocument --quiet
+[Table ("",[],[]) (Caption Nothing
+ [])
+ [(AlignDefault,ColWidth 6.25e-2)
+ ,(AlignDefault,ColWidth 6.25e-2)
+ ,(AlignDefault,ColWidth 6.25e-2)
+ ,(AlignDefault,ColWidth 6.25e-2)
+ ,(AlignDefault,ColWidth 6.25e-2)
+ ,(AlignDefault,ColWidth 6.25e-2)
+ ,(AlignDefault,ColWidth 6.25e-2)
+ ,(AlignDefault,ColWidth 6.25e-2)
+ ,(AlignDefault,ColWidth 6.25e-2)
+ ,(AlignDefault,ColWidth 6.25e-2)
+ ,(AlignDefault,ColWidth 6.25e-2)
+ ,(AlignDefault,ColWidth 6.25e-2)
+ ,(AlignDefault,ColWidth 6.25e-2)
+ ,(AlignDefault,ColWidth 6.25e-2)
+ ,(AlignDefault,ColWidth 6.25e-2)
+ ,(AlignDefault,ColWidth 6.25e-2)]
+ (TableHead ("",[],[])
+ [])
+ [(TableBody ("",[],[]) (RowHeadColumns 0)
+  []
+  [Row ("",[],[])
+   [Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 8)
+    [Para [Strong [Str "Octet",Space,Str "no.",Space,Str "1"]]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 8)
+    [Para [Strong [Str "Octet",Space,Str "no.",Space,Str "2"]]]]
+  ,Row ("",[],[])
+   [Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Para [Str "16"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Para [Str "15"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Para [Str "14"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Para [Str "13"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Para [Str "12"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Para [Str "11"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Para [Str "10"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Para [Str "9"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Para [Str "8"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Para [Str "7"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Para [Str "6"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Para [Str "5"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Para [Str "4"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Para [Str "3"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Para [Str "2"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Para [Str "1"]]]
+  ,Row ("",[],[])
+   [Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 8)
+    [Para [Str "Code",Space,Str "A"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 8)
+    [Para [Str "Code",Space,Str "B"]]]])]
+ (TableFoot ("",[],[])
+ [])]
+^D
+<table:table table:name="Table1" table:style-name="Table1">
+  <table:table-column table:style-name="Table1.A" />
+  <table:table-column table:style-name="Table1.B" />
+  <table:table-column table:style-name="Table1.C" />
+  <table:table-column table:style-name="Table1.D" />
+  <table:table-column table:style-name="Table1.E" />
+  <table:table-column table:style-name="Table1.F" />
+  <table:table-column table:style-name="Table1.G" />
+  <table:table-column table:style-name="Table1.H" />
+  <table:table-column table:style-name="Table1.I" />
+  <table:table-column table:style-name="Table1.J" />
+  <table:table-column table:style-name="Table1.K" />
+  <table:table-column table:style-name="Table1.L" />
+  <table:table-column table:style-name="Table1.M" />
+  <table:table-column table:style-name="Table1.N" />
+  <table:table-column table:style-name="Table1.O" />
+  <table:table-column table:style-name="Table1.P" />
+  <table:table-row>
+    <table:table-cell table:style-name="TableRowCell" office:value-type="string" table:number-columns-spanned="8">
+      <text:p text:style-name="Table_20_Contents"><text:span text:style-name="Strong_20_Emphasis">Octet
+      no. 1</text:span></text:p>
+    </table:table-cell>
+    <table:table-cell table:style-name="TableRowCell" office:value-type="string" table:number-columns-spanned="8">
+      <text:p text:style-name="Table_20_Contents"><text:span text:style-name="Strong_20_Emphasis">Octet
+      no. 2</text:span></text:p>
+    </table:table-cell>
+  </table:table-row>
+  <table:table-row>
+    <table:table-cell table:style-name="TableRowCell" office:value-type="string">
+      <text:p text:style-name="Table_20_Contents">16</text:p>
+    </table:table-cell>
+    <table:table-cell table:style-name="TableRowCell" office:value-type="string">
+      <text:p text:style-name="Table_20_Contents">15</text:p>
+    </table:table-cell>
+    <table:table-cell table:style-name="TableRowCell" office:value-type="string">
+      <text:p text:style-name="Table_20_Contents">14</text:p>
+    </table:table-cell>
+    <table:table-cell table:style-name="TableRowCell" office:value-type="string">
+      <text:p text:style-name="Table_20_Contents">13</text:p>
+    </table:table-cell>
+    <table:table-cell table:style-name="TableRowCell" office:value-type="string">
+      <text:p text:style-name="Table_20_Contents">12</text:p>
+    </table:table-cell>
+    <table:table-cell table:style-name="TableRowCell" office:value-type="string">
+      <text:p text:style-name="Table_20_Contents">11</text:p>
+    </table:table-cell>
+    <table:table-cell table:style-name="TableRowCell" office:value-type="string">
+      <text:p text:style-name="Table_20_Contents">10</text:p>
+    </table:table-cell>
+    <table:table-cell table:style-name="TableRowCell" office:value-type="string">
+      <text:p text:style-name="Table_20_Contents">9</text:p>
+    </table:table-cell>
+    <table:table-cell table:style-name="TableRowCell" office:value-type="string">
+      <text:p text:style-name="Table_20_Contents">8</text:p>
+    </table:table-cell>
+    <table:table-cell table:style-name="TableRowCell" office:value-type="string">
+      <text:p text:style-name="Table_20_Contents">7</text:p>
+    </table:table-cell>
+    <table:table-cell table:style-name="TableRowCell" office:value-type="string">
+      <text:p text:style-name="Table_20_Contents">6</text:p>
+    </table:table-cell>
+    <table:table-cell table:style-name="TableRowCell" office:value-type="string">
+      <text:p text:style-name="Table_20_Contents">5</text:p>
+    </table:table-cell>
+    <table:table-cell table:style-name="TableRowCell" office:value-type="string">
+      <text:p text:style-name="Table_20_Contents">4</text:p>
+    </table:table-cell>
+    <table:table-cell table:style-name="TableRowCell" office:value-type="string">
+      <text:p text:style-name="Table_20_Contents">3</text:p>
+    </table:table-cell>
+    <table:table-cell table:style-name="TableRowCell" office:value-type="string">
+      <text:p text:style-name="Table_20_Contents">2</text:p>
+    </table:table-cell>
+    <table:table-cell table:style-name="TableRowCell" office:value-type="string">
+      <text:p text:style-name="Table_20_Contents">1</text:p>
+    </table:table-cell>
+  </table:table-row>
+  <table:table-row>
+    <table:table-cell table:style-name="TableRowCell" office:value-type="string" table:number-columns-spanned="8">
+      <text:p text:style-name="Table_20_Contents">Code A</text:p>
+    </table:table-cell>
+    <table:table-cell table:style-name="TableRowCell" office:value-type="string" table:number-columns-spanned="8">
+      <text:p text:style-name="Table_20_Contents">Code B</text:p>
+    </table:table-cell>
+  </table:table-row>
+</table:table>
+```
diff --git a/test/command/tabularx.md b/test/command/tabularx.md
--- a/test/command/tabularx.md
+++ b/test/command/tabularx.md
@@ -6,33 +6,143 @@
   & Column Heading 2
   & Column Heading 3 \\
 \hline
-  Cell 1.1 
+  Cell 1.1
   & Cell 1.2
   & Cell 1.3 \\
 \hline
-  Cell 2.1 
+  Cell 2.1
   & Cell 2.2
   & Cell 2.3 \\
 \hline
-  Cell 3.1 
+  Cell 3.1
   & Cell 3.2
   & Cell 3.3 \\
 \hline
 \end{tabularx}
 ^D
-[Table [] [AlignCenter,AlignCenter,AlignCenter] [0.0,0.0,0.0]
- [[Plain [Str "Column",Space,Str "Heading",Space,Str "1"]]
- ,[Plain [Str "Column",Space,Str "Heading",Space,Str "2"]]
- ,[Plain [Str "Column",Space,Str "Heading",Space,Str "3"]]]
- [[[Plain [Str "Cell",Space,Str "1.1"]]
-  ,[Plain [Str "Cell",Space,Str "1.2"]]
-  ,[Plain [Str "Cell",Space,Str "1.3"]]]
- ,[[Plain [Str "Cell",Space,Str "2.1"]]
-  ,[Plain [Str "Cell",Space,Str "2.2"]]
-  ,[Plain [Str "Cell",Space,Str "2.3"]]]
- ,[[Plain [Str "Cell",Space,Str "3.1"]]
-  ,[Plain [Str "Cell",Space,Str "3.2"]]
-  ,[Plain [Str "Cell",Space,Str "3.3"]]]]]
+[ Table
+    ( "" , [] , [] )
+    (Caption Nothing [])
+    [ ( AlignCenter , ColWidthDefault )
+    , ( AlignCenter , ColWidthDefault )
+    , ( AlignCenter , ColWidthDefault )
+    ]
+    (TableHead
+       ( "" , [] , [] )
+       [ Row
+           ( "" , [] , [] )
+           [ Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain
+                   [ Str "Column"
+                   , Space
+                   , Str "Heading"
+                   , Space
+                   , Str "1"
+                   ]
+               ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain
+                   [ Str "Column"
+                   , Space
+                   , Str "Heading"
+                   , Space
+                   , Str "2"
+                   ]
+               ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain
+                   [ Str "Column"
+                   , Space
+                   , Str "Heading"
+                   , Space
+                   , Str "3"
+                   ]
+               ]
+           ]
+       ])
+    [ TableBody
+        ( "" , [] , [] )
+        (RowHeadColumns 0)
+        []
+        [ Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "Cell" , Space , Str "1.1" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "Cell" , Space , Str "1.2" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "Cell" , Space , Str "1.3" ] ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "Cell" , Space , Str "2.1" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "Cell" , Space , Str "2.2" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "Cell" , Space , Str "2.3" ] ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "Cell" , Space , Str "3.1" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "Cell" , Space , Str "3.2" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "Cell" , Space , Str "3.3" ] ]
+            ]
+        ]
+    ]
+    (TableFoot ( "" , [] , [] ) [])
+]
 ```
 
 ```
@@ -43,33 +153,143 @@
   & Column Heading 2
   & Column Heading 3 \\
 \hline
-  Cell 1.1 
+  Cell 1.1
   & Cell 1.2
   & Cell 1.3 \\
 \hline
-  Cell 2.1 
+  Cell 2.1
   & Cell 2.2
   & Cell 2.3 \\
 \hline
-  Cell 3.1 
+  Cell 3.1
   & Cell 3.2
   & Cell 3.3 \\
 \hline
 \end{tabularx}
 ^D
-[Table [] [AlignLeft,AlignCenter,AlignLeft] [0.0,0.0,0.25]
- [[Plain [Str "Column",Space,Str "Heading",Space,Str "1"]]
- ,[Plain [Str "Column",Space,Str "Heading",Space,Str "2"]]
- ,[Plain [Str "Column",Space,Str "Heading",Space,Str "3"]]]
- [[[Plain [Str "Cell",Space,Str "1.1"]]
-  ,[Plain [Str "Cell",Space,Str "1.2"]]
-  ,[Plain [Str "Cell",Space,Str "1.3"]]]
- ,[[Plain [Str "Cell",Space,Str "2.1"]]
-  ,[Plain [Str "Cell",Space,Str "2.2"]]
-  ,[Plain [Str "Cell",Space,Str "2.3"]]]
- ,[[Plain [Str "Cell",Space,Str "3.1"]]
-  ,[Plain [Str "Cell",Space,Str "3.2"]]
-  ,[Plain [Str "Cell",Space,Str "3.3"]]]]]
+[ Table
+    ( "" , [] , [] )
+    (Caption Nothing [])
+    [ ( AlignLeft , ColWidthDefault )
+    , ( AlignCenter , ColWidthDefault )
+    , ( AlignLeft , ColWidth 0.25 )
+    ]
+    (TableHead
+       ( "" , [] , [] )
+       [ Row
+           ( "" , [] , [] )
+           [ Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain
+                   [ Str "Column"
+                   , Space
+                   , Str "Heading"
+                   , Space
+                   , Str "1"
+                   ]
+               ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain
+                   [ Str "Column"
+                   , Space
+                   , Str "Heading"
+                   , Space
+                   , Str "2"
+                   ]
+               ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain
+                   [ Str "Column"
+                   , Space
+                   , Str "Heading"
+                   , Space
+                   , Str "3"
+                   ]
+               ]
+           ]
+       ])
+    [ TableBody
+        ( "" , [] , [] )
+        (RowHeadColumns 0)
+        []
+        [ Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "Cell" , Space , Str "1.1" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "Cell" , Space , Str "1.2" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "Cell" , Space , Str "1.3" ] ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "Cell" , Space , Str "2.1" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "Cell" , Space , Str "2.2" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "Cell" , Space , Str "2.3" ] ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "Cell" , Space , Str "3.1" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "Cell" , Space , Str "3.2" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "Cell" , Space , Str "3.3" ] ]
+            ]
+        ]
+    ]
+    (TableFoot ( "" , [] , [] ) [])
+]
 ```
 
 ```
@@ -80,31 +300,141 @@
   & Column Heading 2
   & Column Heading 3 \\
 \hline
-  Cell 1.1 
+  Cell 1.1
   & Cell 1.2
   & Cell 1.3 \\
 \hline
-  Cell 2.1 
+  Cell 2.1
   & Cell 2.2
   & Cell 2.3 \\
 \hline
-  Cell 3.1 
+  Cell 3.1
   & Cell 3.2
   & Cell 3.3 \\
 \hline
 \end{tabularx}
 ^D
-[Table [] [AlignLeft,AlignCenter,AlignLeft] [0.25,0.0,0.25]
- [[Plain [Str "Column",Space,Str "Heading",Space,Str "1"]]
- ,[Plain [Str "Column",Space,Str "Heading",Space,Str "2"]]
- ,[Plain [Str "Column",Space,Str "Heading",Space,Str "3"]]]
- [[[Plain [Str "Cell",Space,Str "1.1"]]
-  ,[Plain [Str "Cell",Space,Str "1.2"]]
-  ,[Plain [Str "Cell",Space,Str "1.3"]]]
- ,[[Plain [Str "Cell",Space,Str "2.1"]]
-  ,[Plain [Str "Cell",Space,Str "2.2"]]
-  ,[Plain [Str "Cell",Space,Str "2.3"]]]
- ,[[Plain [Str "Cell",Space,Str "3.1"]]
-  ,[Plain [Str "Cell",Space,Str "3.2"]]
-  ,[Plain [Str "Cell",Space,Str "3.3"]]]]]
+[ Table
+    ( "" , [] , [] )
+    (Caption Nothing [])
+    [ ( AlignLeft , ColWidth 0.25 )
+    , ( AlignCenter , ColWidthDefault )
+    , ( AlignLeft , ColWidth 0.25 )
+    ]
+    (TableHead
+       ( "" , [] , [] )
+       [ Row
+           ( "" , [] , [] )
+           [ Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain
+                   [ Str "Column"
+                   , Space
+                   , Str "Heading"
+                   , Space
+                   , Str "1"
+                   ]
+               ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain
+                   [ Str "Column"
+                   , Space
+                   , Str "Heading"
+                   , Space
+                   , Str "2"
+                   ]
+               ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain
+                   [ Str "Column"
+                   , Space
+                   , Str "Heading"
+                   , Space
+                   , Str "3"
+                   ]
+               ]
+           ]
+       ])
+    [ TableBody
+        ( "" , [] , [] )
+        (RowHeadColumns 0)
+        []
+        [ Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "Cell" , Space , Str "1.1" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "Cell" , Space , Str "1.2" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "Cell" , Space , Str "1.3" ] ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "Cell" , Space , Str "2.1" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "Cell" , Space , Str "2.2" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "Cell" , Space , Str "2.3" ] ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "Cell" , Space , Str "3.1" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "Cell" , Space , Str "3.2" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "Cell" , Space , Str "3.3" ] ]
+            ]
+        ]
+    ]
+    (TableFoot ( "" , [] , [] ) [])
+]
 ```
diff --git a/test/command/tasklist.md b/test/command/tasklist.md
new file mode 100644
--- /dev/null
+++ b/test/command/tasklist.md
@@ -0,0 +1,105 @@
+tests adapted from <https://github.github.com/gfm/#task-list-items-extension->
+
+```
+% pandoc
+- [ ] foo
+- [x] bar
+^D
+<ul class="task-list">
+<li><label><input type="checkbox" />foo</label></li>
+<li><label><input type="checkbox" checked="" />bar</label></li>
+</ul>
+```
+
+
+```
+% pandoc
+- [x] foo
+  - [ ] bar
+  - [x] baz
+- [ ] bim
+^D
+<ul class="task-list">
+<li><label><input type="checkbox" checked="" />foo</label>
+<ul class="task-list">
+<li><label><input type="checkbox" />bar</label></li>
+<li><label><input type="checkbox" checked="" />baz</label></li>
+</ul></li>
+<li><label><input type="checkbox" />bim</label></li>
+</ul>
+```
+
+
+custom html task list test:
+
+```
+% pandoc
+- [ ]  unchecked
+- plain item
+-  [x] checked
+
+paragraph
+
+1. [ ] ordered unchecked
+2. [] plain item
+3. [x] ordered checked
+
+paragraph
+
+- [ ] list item with a
+
+    second paragraph
+
+- [x] checked
+^D
+<ul>
+<li><label><input type="checkbox" />unchecked</label></li>
+<li>plain item</li>
+<li><label><input type="checkbox" checked="" />checked</label></li>
+</ul>
+<p>paragraph</p>
+<ol type="1">
+<li><label><input type="checkbox" />ordered unchecked</label></li>
+<li>[] plain item</li>
+<li><label><input type="checkbox" checked="" />ordered
+checked</label></li>
+</ol>
+<p>paragraph</p>
+<ul class="task-list">
+<li><p><label><input type="checkbox" />list item with a</label></p>
+<p>second paragraph</p></li>
+<li><p><label><input type="checkbox"
+checked="" />checked</label></p></li>
+</ul>
+```
+
+latex task list test:
+
+```
+% pandoc -t latex
+- [ ] foo bar
+
+  baz
+
+- [x] ok
+^D
+\begin{itemize}
+\item[$\square$]
+  foo bar
+
+  baz
+\item[$\boxtimes$]
+  ok
+\end{itemize}
+```
+
+round trip:
+
+```
+% pandoc -f markdown -t markdown
+- [ ] foo
+- [x] bar
+^D
+- [ ] foo
+- [x] bar
+```
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><span> <em>hi</em> </span></p>
+```
diff --git a/test/command/three.txt b/test/command/three.txt
new file mode 100644
--- /dev/null
+++ b/test/command/three.txt
@@ -0,0 +1,3 @@
+1st line.
+2nd line.
+3rd line.
diff --git a/test/command/toc.md b/test/command/toc.md
new file mode 100644
--- /dev/null
+++ b/test/command/toc.md
@@ -0,0 +1,47 @@
+```
+% pandoc -s --toc -t markdown
+# A
+## b
+# B
+## b
+
+::: interior
+# C
+## cc
+# D
+:::
+
+::: blue
+# E
+## e
+:::
+^D
+- [A](#a){#toc-a}
+  - [b](#b){#toc-b}
+- [B](#b-1){#toc-b-1}
+  - [b](#b-2){#toc-b-2}
+- [E](#e){#toc-e}
+  - [e](#e-1){#toc-e-1}
+
+# A
+
+## b
+
+# B
+
+## b
+
+::: interior
+# C
+
+## cc
+
+# D
+:::
+
+::: blue
+# E
+
+## e
+:::
+```
diff --git a/test/command/translations.md b/test/command/translations.md
--- a/test/command/translations.md
+++ b/test/command/translations.md
@@ -2,14 +2,14 @@
 % pandoc -f latex -t native -M lang=en
 \figurename\ 2
 ^D
-[Para [Str "Figure\160\&2"]]
+[ Para [ Str "Figure\160\&2" ] ]
 ```
 
 ```
 % pandoc -f latex -t native -M lang=de-DE
 \figurename\ 2
 ^D
-[Para [Str "Abbildung\160\&2"]]
+[ Para [ Str "Abbildung\160\&2" ] ]
 ```
 
 ```
@@ -17,13 +17,13 @@
 \setmainlanguage{german}
 \figurename 2
 ^D
-[Para [Str "Abbildung2"]]
+[ Para [ Str "Abbildung2" ] ]
 ```
 
 ```
-% pandoc -f latex -t native -M lang=sr
+% pandoc -f latex -t native -M lang=sr-Latn
 \figurename~2
 \figurename.
 ^D
-[Para [Str "Slika\160\&2",SoftBreak,Str "Slika."]]
+[ Para [ Str "Slika\160\&2" , SoftBreak , Str "Slika." ] ]
 ```
diff --git a/test/command/typst-hs-80.md b/test/command/typst-hs-80.md
new file mode 100644
--- /dev/null
+++ b/test/command/typst-hs-80.md
@@ -0,0 +1,55 @@
+```
+% pandoc -f typst -t native -s
+#set document(
+  title: [My Title],
+)
+
+#title()
+^D
+Pandoc
+  Meta
+    { unMeta =
+        fromList
+          [ ( "title"
+            , MetaInlines [ Str "My" , Space , Str "Title" ]
+            )
+          ]
+    }
+  []
+```
+
+```
+% pandoc -f typst -t native -s
+#set document(
+  title: [ignored],
+)
+
+#title[My Title]
+^D
+Pandoc
+  Meta
+    { unMeta =
+        fromList
+          [ ( "title"
+            , MetaInlines [ Str "My" , Space , Str "Title" ]
+            )
+          ]
+    }
+  []
+```
+
+```
+% pandoc -f typst -t native -s
+#title[My Title]
+^D
+Pandoc
+  Meta
+    { unMeta =
+        fromList
+          [ ( "title"
+            , MetaInlines [ Str "My" , Space , Str "Title" ]
+            )
+          ]
+    }
+  []
+```
diff --git a/test/command/typst-image-alt.md b/test/command/typst-image-alt.md
new file mode 100644
--- /dev/null
+++ b/test/command/typst-image-alt.md
@@ -0,0 +1,78 @@
+```
+% pandoc -f markdown-implicit_figures -t typst
+![Alt text from inlines](image.png)
+^D
+#box(image("image.png", alt: "Alt text from inlines"))
+```
+
+```
+% pandoc -f markdown-implicit_figures -t typst
+![](image.png){alt="Explicit alt attribute"}
+^D
+#box(image("image.png", alt: "Explicit alt attribute"))
+```
+
+```
+% pandoc -f markdown-implicit_figures -t typst
+![Inlines ignored](image.png){alt="Explicit wins"}
+^D
+#box(image("image.png", alt: "Explicit wins"))
+```
+
+```
+% pandoc -f markdown-implicit_figures -t typst
+![](image.png)
+^D
+#box(image("image.png"))
+```
+
+```
+% pandoc -f markdown-implicit_figures -t typst
+![Inlines ignored for decorative](image.png){alt=""}
+^D
+#box(image("image.png"))
+```
+
+```
+% pandoc -t typst
+![Caption text](image.png){alt="Alt text describing the image"}
+
+^D
+#figure(image("image.png", alt: "Alt text describing the image"),
+  caption: [
+    Caption text
+  ]
+)
+```
+
+```
+% pandoc -t typst
+![Caption only](image.png)
+
+^D
+#figure(image("image.png", alt: "Caption only"),
+  caption: [
+    Caption only
+  ]
+)
+```
+
+```
+% pandoc -f markdown -t typst
+![Caption](test.png){alt="A \"quoted\" phrase and C:\\path\\file"}
+^D
+#figure(image("test.png", alt: "A \"quoted\" phrase and C:\\path\\file"),
+  caption: [
+    Caption
+  ]
+)
+
+```
+
+```
+% pandoc -f html -t typst
+<img src="data:image/png;base64,iVBORw0KGgo=" alt="A small red dot">
+^D
+#box(image(bytes((137,80,78,71,13,10,26,10)), alt: "A small red dot"))
+
+```
diff --git a/test/command/typst-images.md b/test/command/typst-images.md
new file mode 100644
--- /dev/null
+++ b/test/command/typst-images.md
@@ -0,0 +1,32 @@
+```
+% pandoc -t typst
+![dot](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+9AAAACXBIWXMAAC4jAAAuIwF4pT92AAAASUlEQVQYGa3OWwoAIAgEQNf739k0EjVCfxKCHtMqiEh0jcWjOKBAkQjPe7MFdun/IbRdDNb05nvolzWzEx0DdozK96W1PzjNHxcgphkBs9CoHwAAAABJRU5ErkJggg==){width=1in}
+^D
+#figure(image(bytes((137,80,78,71,13,10,26,10,0,0,0,13,73,72,68,82,0,0,0,10,0,0,0,10,8,6,0,0,0,141,50,207,189,0,0,0,9,112,72,89,115,0,0,46,35,0,0,46,35,1,120,165,63,118,0,0,0,73,73,68,65,84,24,25,173,206,91,10,0,32,8,4,64,215,251,223,217,52,18,53,66,127,18,130,30,211,42,136,72,116,141,197,163,56,160,64,145,8,207,123,179,5,118,233,255,33,180,93,12,214,244,230,123,232,151,53,179,19,29,3,118,140,202,247,165,181,63,56,205,31,23,32,166,25,1,179,208,168,31,0,0,0,0,73,69,78,68,174,66,96,130)), width: 1in, alt: "dot"),
+  caption: [
+    dot
+  ]
+)
+```
+
+```
+% pandoc -t typst
+![dot](dot.png){width="1in"}
+^D
+#figure(image("dot.png", width: 1in, alt: "dot"),
+  caption: [
+    dot
+  ]
+)
+```
+
+```
+% pandoc -t typst
+![chicken](data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%20100%20100%22%20aria-label%3D%22Chicken%22%3E%20%3Cpath%20d%3D%22M76.5%2033.3l-8.3-6.6%204-5c-1.3-2-1.3-4.7.1-6.6%203.4-3.8%208.7-2%2010.2%202.2%204.5.7%207.5%205.4%204.4%209.4a5.7%205.7%200%2001-6.4%201.6zM73%2026.2l3%202.4%203.8-4.7c1.3%201%203.5%202%204.5.7%202.1-2.9-1.5-5.4-4.7-3.5%201.2-4.6-2.7-6.2-4.5-3.9-.7%202.2.2%203%201.7%204.2z%22%2F%3E%20%3Cpath%20d%3D%22M54%2072.3a19.1%2019.1%200%2001-19.2-17.8%2021.4%2021.4%200%20014.7-15.2c3.5-4.3%208.4-7.1%2013.7-8l3.1-.1c8.2-.9%2012.9-5.5%2013-5.6l1-1%208.2%206.5-1%201.3c-3.3%204-2.8%2011.3-2.5%2014.2a21.5%2021.5%200%2001-4.4%2017.5%2021.2%2021.2%200%2001-16.5%208.2zM70.6%2029a27%2027%200%2001-14%205.5l-3%20.2a18%2018%200%2000-11.3%206.7%2018%2018%200%2000-4%2012.8%2016%2016%200%200015.9%2014.7c5.4%200%2010.4-2.5%2014-6.9A18%2018%200%200072%2049.4c0-.8-.2-1.6-.3-2.2-.5-4-.7-10.7%202.1-15.5z%22%2F%3E%20%3Cpath%20d%3D%22M46%2087C22.6%2087%20.5%2087%20.5%2066.8c0-19%2020.4-34.6%2045.5-34.6%201.2%200%202.5%200%203.7.2%2010.1.6%209.7-.1.5%203.2a18.3%2018.3%200%2000-12%2018.6%2016%2016%200%200015.9%2014.7c5.4%200%2010.4-2.5%2014-6.9A18%2018%200%200072%2049.4c-.6-4-.4-7.4-.2-11.3a35.8%2035.8%200%200119.5%2026A11.7%2011.7%200%200187.8%2087H46zm-2.8-51.3c-22%201-39.4%2014.6-39.4%2031%200%2015.8%2016%2016.9%2042.2%2016.9h41.8c4.6%200%208.4-3.8%208.4-8.4-.4-4.8-3.2-7.7-8.1-8.4-.3-10.4-7.4-18.4-13.3-22.7.1%202%20.5%204.3.7%206.1%200%205-1.6%2010-4.8%2014A21.2%2021.2%200%200154%2072.3a19.1%2019.1%200%2001-19.3-17.8%2021.4%2021.4%200%20018.4-18.8z%22%2F%3E%20%3C%2Fsvg%3E)
+^D
+#figure(image(bytes("<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 100 100\" aria-label=\"Chicken\"> <path d=\"M76.5 33.3l-8.3-6.6 4-5c-1.3-2-1.3-4.7.1-6.6 3.4-3.8 8.7-2 10.2 2.2 4.5.7 7.5 5.4 4.4 9.4a5.7 5.7 0 01-6.4 1.6zM73 26.2l3 2.4 3.8-4.7c1.3 1 3.5 2 4.5.7 2.1-2.9-1.5-5.4-4.7-3.5 1.2-4.6-2.7-6.2-4.5-3.9-.7 2.2.2 3 1.7 4.2z\"/> <path d=\"M54 72.3a19.1 19.1 0 01-19.2-17.8 21.4 21.4 0 014.7-15.2c3.5-4.3 8.4-7.1 13.7-8l3.1-.1c8.2-.9 12.9-5.5 13-5.6l1-1 8.2 6.5-1 1.3c-3.3 4-2.8 11.3-2.5 14.2a21.5 21.5 0 01-4.4 17.5 21.2 21.2 0 01-16.5 8.2zM70.6 29a27 27 0 01-14 5.5l-3 .2a18 18 0 00-11.3 6.7 18 18 0 00-4 12.8 16 16 0 0015.9 14.7c5.4 0 10.4-2.5 14-6.9A18 18 0 0072 49.4c0-.8-.2-1.6-.3-2.2-.5-4-.7-10.7 2.1-15.5z\"/> <path d=\"M46 87C22.6 87 .5 87 .5 66.8c0-19 20.4-34.6 45.5-34.6 1.2 0 2.5 0 3.7.2 10.1.6 9.7-.1.5 3.2a18.3 18.3 0 00-12 18.6 16 16 0 0015.9 14.7c5.4 0 10.4-2.5 14-6.9A18 18 0 0072 49.4c-.6-4-.4-7.4-.2-11.3a35.8 35.8 0 0119.5 26A11.7 11.7 0 0187.8 87H46zm-2.8-51.3c-22 1-39.4 14.6-39.4 31 0 15.8 16 16.9 42.2 16.9h41.8c4.6 0 8.4-3.8 8.4-8.4-.4-4.8-3.2-7.7-8.1-8.4-.3-10.4-7.4-18.4-13.3-22.7.1 2 .5 4.3.7 6.1 0 5-1.6 10-4.8 14A21.2 21.2 0 0154 72.3a19.1 19.1 0 01-19.3-17.8 21.4 21.4 0 018.4-18.8z\"/> </svg>"), alt: "chicken"),
+  caption: [
+    chicken
+  ]
+)
+```
diff --git a/test/command/typst-property-output.md b/test/command/typst-property-output.md
new file mode 100644
--- /dev/null
+++ b/test/command/typst-property-output.md
@@ -0,0 +1,235 @@
+```
+% pandoc -f html -t typst
+<span typst:text:fill="orange">foo</span>
+^D
+#text(fill: orange)[foo]
+```
+
+```
+% pandoc -f html -t typst
+<span>foo</span>
+^D
+foo
+```
+
+```
+% pandoc -f html -t typst
+<div typst:inset="10pt">foo</div>
+^D
+#block(inset: 10pt)[
+foo
+]
+```
+
+```
+% pandoc -f html -t typst
+<div typst:text:fill="purple">foo</div>
+^D
+#block[
+#set text(fill: purple);
+foo
+]
+```
+
+```
+% pandoc -f html -t typst
+<div>foo</div>
+^D
+#block[
+foo
+]
+```
+
+```
+% pandoc -f html -t typst
+<table typst:fill="blue">
+  <tr><td>A</td><td>B</td></tr>
+</table>
+^D
+#figure(
+  align(center)[#table(
+    columns: 2,
+    align: (auto,auto,),
+    fill: blue,
+    [A], [B],
+  )]
+  , kind: table
+  )
+```
+
+```
+% pandoc -f html -t typst
+<table typst:text:fill="orange">
+  <tr><td>A</td><td>B</td></tr>
+</table>
+^D
+#figure(
+  align(center)[#set text(fill: orange);#table(
+    columns: 2,
+    align: (auto,auto,),
+    [A], [B],
+  )]
+  , kind: table
+  )
+```
+
+```
+% pandoc -f html -t typst
+<table>
+  <tr><td>A</td><td typst:fill="green">B</td></tr>
+</table>
+^D
+#figure(
+  align(center)[#table(
+    columns: 2,
+    align: (auto,auto,),
+    [A], table.cell(fill: green)[B],
+  )]
+  , kind: table
+  )
+```
+
+```
+% pandoc -f html -t typst
+<table>
+  <tr><td>A</td><td typst:text:fill="fuchsia">B</td></tr>
+</table>
+^D
+#figure(
+  align(center)[#table(
+    columns: 2,
+    align: (auto,auto,),
+    [A], [#set text(fill: fuchsia);
+    B],
+  )]
+  , kind: table
+  )
+```
+
+```
+% pandoc -f html -t typst
+<table>
+  <tr><td>A</td><td typst:text:fill="maroon" align="center">B</td></tr>
+</table>
+^D
+#figure(
+  align(center)[#table(
+    columns: 2,
+    align: (auto,center,),
+    [A], table.cell(align: center)[#set text(fill: maroon);
+    B],
+  )]
+  , kind: table
+  )
+```
+
+```
+% pandoc -f html -t typst
+<table>
+  <tr><td>A</td><td typst:align="horizon" align="center">B</td></tr>
+</table>
+^D
+#figure(
+  align(center)[#table(
+    columns: 2,
+    align: (auto,center,),
+    [A], table.cell(align: horizon + center)[B],
+  )]
+  , kind: table
+  )
+```
+
+
+```
+% pandoc -f html -t typst
+<table>
+  <tr><td>A</td><td>B</td></tr>
+</table>
+^D
+#figure(
+  align(center)[#table(
+    columns: 2,
+    align: (auto,auto,),
+    [A], [B],
+  )]
+  , kind: table
+  )
+```
+
+```
+% pandoc -f html -t typst
+<p>Paragraph before.</p>
+
+<table class="typst:no-figure" typst:text:size="3em">
+  <tr>
+    <td>A</td>
+    <td>B</td>
+    <td>C</td>
+  </tr>
+</table>
+
+<p>Paragraph after.</p>
+^D
+Paragraph before.
+
+#{set text(size: 3em);table(
+  columns: 3,
+  align: (auto,auto,auto,),
+  [A], [B], [C],
+)}
+Paragraph after.
+```
+
+
+```
+% pandoc -f html -t typst
+<p>Paragraph before.</p>
+
+<table typst:text:size="3em">
+  <tr>
+    <td>A</td>
+    <td>B</td>
+    <td>C</td>
+  </tr>
+</table>
+
+<p>Paragraph after.</p>
+^D
+Paragraph before.
+
+#figure(
+  align(center)[#set text(size: 3em);#table(
+    columns: 3,
+    align: (auto,auto,auto,),
+    [A], [B], [C],
+  )]
+  , kind: table
+  )
+
+Paragraph after.
+```
+
+
+```
+% pandoc -f html -t typst
+<p>Paragraph before.</p>
+
+<table class="typst:no-figure">
+  <tr>
+    <td>A</td>
+    <td>B</td>
+    <td>C</td>
+  </tr>
+</table>
+
+<p>Paragraph after.</p>
+^D
+Paragraph before.
+
+#table(
+  columns: 3,
+  align: (auto,auto,auto,),
+  [A], [B], [C],
+)
+Paragraph after.
+```
diff --git a/test/command/unicode-collation.md b/test/command/unicode-collation.md
new file mode 100644
--- /dev/null
+++ b/test/command/unicode-collation.md
@@ -0,0 +1,130 @@
+```
+% pandoc --citeproc -t plain
+---
+lang: en-US
+csl: command/apa.csl
+references:
+- id: a1
+  type: book
+  author:
+  - family: Ubina
+    given: A. John
+  issued: 1985
+- id: a2
+  type: book
+  author:
+  - family: Über
+    given: Aglaia
+  issued: 1996
+- id: a3
+  type: book
+  author:
+  - family: Oñate
+    given: José
+  issued: 1985
+- id: a4
+  type: book
+  author:
+  - family: Onush
+    given: Frank
+  issued: 2002
+- id: a5
+  type: book
+  author:
+  - family: O'Neil
+    given: Timothy
+  issued: 2010
+---
+
+[@a1;@a2;@a3;@a4;@a5]
+^D
+(O’Neil, 2010; Oñate, 1985; Onush, 2002; Über, 1996; Ubina, 1985)
+
+O’Neil, T. (2010).
+
+Oñate, J. (1985).
+
+Onush, F. (2002).
+
+Über, A. (1996).
+
+Ubina, A. J. (1985).
+```
+
+```
+% pandoc --citeproc -t plain
+---
+lang: es
+csl: command/apa.csl
+references:
+- id: a1
+  type: book
+  author:
+  - family: Ubina
+    given: A. John
+  issued: 1985
+- id: a2
+  type: book
+  author:
+  - family: Über
+    given: Aglaia
+  issued: 1996
+- id: a3
+  type: book
+  author:
+  - family: Oñate
+    given: José
+  issued: 1985
+- id: a4
+  type: book
+  author:
+  - family: Onush
+    given: Frank
+  issued: 2002
+- id: a5
+  type: book
+  author:
+  - family: O'Neil
+    given: Timothy
+  issued: 2010
+---
+
+[@a1;@a2;@a3;@a4;@a5]
+^D
+(O’Neil, 2010; Onush, 2002; Oñate, 1985; Über, 1996; Ubina, 1985)
+
+O’Neil, T. (2010).
+
+Onush, F. (2002).
+
+Oñate, J. (1985).
+
+Über, A. (1996).
+
+Ubina, A. J. (1985).
+```
+
+```
+% pandoc -C -t plain
+---
+nocite: '@*'
+lang: fr-FR-u-kb-true
+references:
+- id: cote
+  author: cote
+- id: côte
+  author: côte
+- id: coté
+  author: coté
+- id: côté
+  author: côté
+...
+^D
+cote. s. d.
+
+côte. s. d.
+
+coté. s. d.
+
+côté. s. d.
+```
diff --git a/test/command/vancouver.csl b/test/command/vancouver.csl
new file mode 100644
--- /dev/null
+++ b/test/command/vancouver.csl
@@ -0,0 +1,351 @@
+<?xml version="1.0" encoding="utf-8"?>
+<style xmlns="http://purl.org/net/xbiblio/csl" class="in-text" version="1.0" demote-non-dropping-particle="sort-only" page-range-format="minimal">
+  <info>
+    <title>Vancouver</title>
+    <id>http://www.zotero.org/styles/vancouver</id>
+    <link href="http://www.zotero.org/styles/vancouver" rel="self"/>
+    <link href="http://www.nlm.nih.gov/bsd/uniform_requirements.html" rel="documentation"/>
+    <author>
+      <name>Michael Berkowitz</name>
+      <email>mberkowi@gmu.edu</email>
+    </author>
+    <contributor>
+      <name>Sean Takats</name>
+      <email>stakats@gmu.edu</email>
+    </contributor>
+    <contributor>
+      <name>Sebastian Karcher</name>
+    </contributor>
+    <category citation-format="numeric"/>
+    <category field="medicine"/>
+    <summary>Vancouver style as outlined by International Committee of Medical Journal Editors Uniform Requirements for Manuscripts Submitted to Biomedical Journals: Sample References</summary>
+    <updated>2014-09-06T16:03:01+00:00</updated>
+    <rights license="http://creativecommons.org/licenses/by-sa/3.0/">This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 License</rights>
+  </info>
+  <locale xml:lang="en">
+    <date form="text" delimiter=" ">
+      <date-part name="year"/>
+      <date-part name="month" form="short" strip-periods="true"/>
+      <date-part name="day"/>
+    </date>
+    <terms>
+      <term name="collection-editor" form="long">
+        <single>editor</single>
+        <multiple>editors</multiple>
+      </term>
+      <term name="presented at">presented at</term>
+      <term name="available at">available from</term>
+      <term name="section" form="short">sect.</term>
+    </terms>
+  </locale>
+  <locale xml:lang="fr">
+    <date form="text" delimiter=" ">
+      <date-part name="day"/>
+      <date-part name="month" form="short" strip-periods="true"/>
+      <date-part name="year"/>
+    </date>
+  </locale>
+  <macro name="author">
+    <names variable="author">
+      <name sort-separator=" " initialize-with="" name-as-sort-order="all" delimiter=", " delimiter-precedes-last="always"/>
+      <label form="long" prefix=", "/>
+      <substitute>
+        <names variable="editor"/>
+      </substitute>
+    </names>
+  </macro>
+  <macro name="editor">
+    <names variable="editor" suffix=".">
+      <name sort-separator=" " initialize-with="" name-as-sort-order="all" delimiter=", " delimiter-precedes-last="always"/>
+      <label form="long" prefix=", "/>
+    </names>
+  </macro>
+  <macro name="chapter-marker">
+    <choose>
+      <if type="chapter paper-conference entry-dictionary entry-encyclopedia" match="any">
+        <text term="in" text-case="capitalize-first"/>
+      </if>
+    </choose>
+  </macro>
+  <macro name="publisher">
+    <choose>
+      <!--discard publisher info for articles-->
+      <if type="article-journal article-magazine article-newspaper" match="none">
+        <group delimiter=": " suffix=";">
+          <choose>
+            <if type="thesis">
+              <text variable="publisher-place" prefix="[" suffix="]"/>
+            </if>
+            <else-if type="speech"/>
+            <else>
+              <text variable="publisher-place"/>
+            </else>
+          </choose>
+          <text variable="publisher"/>
+        </group>
+      </if>
+    </choose>
+  </macro>
+  <macro name="access">
+    <choose>
+      <if variable="URL">
+        <group delimiter=": ">
+          <text term="available at" text-case="capitalize-first"/>
+          <text variable="URL"/>
+        </group>
+      </if>
+    </choose>
+  </macro>
+  <macro name="accessed-date">
+    <choose>
+      <if variable="URL">
+        <group prefix="[" suffix="]" delimiter=" ">
+          <text term="cited" text-case="lowercase"/>
+          <date variable="accessed" form="text"/>
+        </group>
+      </if>
+    </choose>
+  </macro>
+  <macro name="container-title">
+    <choose>
+      <if type="article-journal article-magazine chapter paper-conference article-newspaper review review-book entry-dictionary entry-encyclopedia" match="any">
+        <group suffix="." delimiter=" ">
+          <choose>
+            <if type="article-journal review review-book" match="any">
+              <text variable="container-title" form="short" strip-periods="true"/>
+            </if>
+            <else>
+              <text variable="container-title" strip-periods="true"/>
+            </else>
+          </choose>
+          <choose>
+            <if variable="URL">
+              <text term="internet" prefix="[" suffix="]" text-case="capitalize-first"/>
+            </if>
+          </choose>
+        </group>
+        <text macro="edition" prefix=" "/>
+      </if>
+      <!--add event-name and event-place once they become available-->
+      <else-if type="bill legislation" match="any">
+        <group delimiter=", ">
+          <group delimiter=". ">
+            <text variable="container-title"/>
+            <group delimiter=" ">
+              <text term="section" form="short" text-case="capitalize-first"/>
+              <text variable="section"/>
+            </group>
+          </group>
+          <text variable="number"/>
+        </group>
+      </else-if>
+      <else-if type="speech">
+        <group delimiter=": " suffix=";">
+          <group delimiter=" ">
+            <text variable="genre" text-case="capitalize-first"/>
+            <text term="presented at"/>
+          </group>
+          <text variable="event"/>
+        </group>
+      </else-if>
+      <else>
+        <group delimiter=", " suffix=".">
+          <choose>
+            <if variable="collection-title" match="none">
+              <group delimiter=" ">
+                <label variable="volume" form="short" text-case="capitalize-first"/>
+                <text variable="volume"/>
+              </group>
+            </if>
+          </choose>
+          <text variable="container-title"/>
+        </group>
+      </else>
+    </choose>
+  </macro>
+  <macro name="title">
+    <text variable="title"/>
+    <choose>
+      <if type="article-journal article-magazine chapter paper-conference article-newspaper review review-book entry-dictionary entry-encyclopedia" match="none">
+        <choose>
+          <if variable="URL">
+            <text term="internet" prefix=" [" suffix="]" text-case="capitalize-first"/>
+          </if>
+        </choose>
+        <text macro="edition" prefix=". "/>
+      </if>
+    </choose>
+    <choose>
+      <if type="thesis">
+        <text variable="genre" prefix=" [" suffix="]"/>
+      </if>
+    </choose>
+  </macro>
+  <macro name="edition">
+    <choose>
+      <if is-numeric="edition">
+        <group delimiter=" ">
+          <number variable="edition" form="ordinal"/>
+          <text term="edition" form="short"/>
+        </group>
+      </if>
+      <else>
+        <text variable="edition" suffix="."/>
+      </else>
+    </choose>
+  </macro>
+  <macro name="date">
+    <choose>
+      <if type="article-journal article-magazine article-newspaper review review-book" match="any">
+        <group suffix=";" delimiter=" ">
+          <date variable="issued" form="text"/>
+          <text macro="accessed-date"/>
+        </group>
+      </if>
+      <else-if type="bill legislation" match="any">
+        <group delimiter=", ">
+          <date variable="issued" delimiter=" ">
+            <date-part name="month" form="short" strip-periods="true"/>
+            <date-part name="day"/>
+          </date>
+          <date variable="issued">
+            <date-part name="year"/>
+          </date>
+        </group>
+      </else-if>
+      <else-if type="report">
+        <date variable="issued" delimiter=" ">
+          <date-part name="year"/>
+          <date-part name="month" form="short" strip-periods="true"/>
+        </date>
+        <text macro="accessed-date" prefix=" "/>
+      </else-if>
+      <else-if type="patent">
+        <group suffix=".">
+          <group delimiter=", ">
+            <text variable="number"/>
+            <date variable="issued">
+              <date-part name="year"/>
+            </date>
+          </group>
+          <text macro="accessed-date" prefix=" "/>
+        </group>
+      </else-if>
+      <else-if type="speech">
+        <group delimiter="; ">
+          <group delimiter=" ">
+            <date variable="issued" delimiter=" ">
+              <date-part name="year"/>
+              <date-part name="month" form="short" strip-periods="true"/>
+              <date-part name="day"/>
+            </date>
+            <text macro="accessed-date"/>
+          </group>
+          <text variable="event-place"/>
+        </group>
+      </else-if>
+      <else>
+        <group suffix=".">
+          <date variable="issued">
+            <date-part name="year"/>
+          </date>
+          <text macro="accessed-date" prefix=" "/>
+        </group>
+      </else>
+    </choose>
+  </macro>
+  <macro name="pages">
+    <choose>
+      <if type="article-journal article-magazine article-newspaper review review-book" match="any">
+        <text variable="page" prefix=":"/>
+      </if>
+      <else-if type="book" match="any">
+        <text variable="number-of-pages" prefix=" "/>
+        <choose>
+          <if is-numeric="number-of-pages">
+            <label variable="number-of-pages" form="short" prefix=" " plural="never"/>
+          </if>
+        </choose>
+      </else-if>
+      <else>
+        <group prefix=" " delimiter=" ">
+          <label variable="page" form="short" plural="never"/>
+          <text variable="page"/>
+        </group>
+      </else>
+    </choose>
+  </macro>
+  <macro name="journal-location">
+    <choose>
+      <if type="article-journal article-magazine review review-book" match="any">
+        <text variable="volume"/>
+        <text variable="issue" prefix="(" suffix=")"/>
+      </if>
+    </choose>
+  </macro>
+  <macro name="collection-details">
+    <choose>
+      <if type="article-journal article-magazine article-newspaper review review-book" match="none">
+        <choose>
+          <if variable="collection-title">
+            <group delimiter=" " prefix="(" suffix=")">
+              <names variable="collection-editor" suffix=".">
+                <name sort-separator=" " initialize-with="" name-as-sort-order="all" delimiter=", " delimiter-precedes-last="always"/>
+                <label form="long" prefix=", "/>
+              </names>
+              <group delimiter="; ">
+                <text variable="collection-title"/>
+                <group delimiter=" ">
+                  <label variable="volume" form="short"/>
+                  <text variable="volume"/>
+                </group>
+              </group>
+            </group>
+          </if>
+        </choose>
+      </if>
+    </choose>
+  </macro>
+  <macro name="report-details">
+    <choose>
+      <if type="report">
+        <text variable="number" prefix="Report No.: "/>
+      </if>
+    </choose>
+  </macro>
+  <citation collapse="citation-number">
+    <sort>
+      <key variable="citation-number"/>
+    </sort>
+    <layout prefix="(" suffix=")" delimiter=",">
+      <text variable="citation-number"/>
+    </layout>
+  </citation>
+  <bibliography et-al-min="7" et-al-use-first="6" second-field-align="flush">
+    <layout>
+      <text variable="citation-number" suffix=". "/>
+      <group delimiter=". " suffix=". ">
+        <text macro="author"/>
+        <text macro="title"/>
+      </group>
+      <group delimiter=" " suffix=". ">
+        <group delimiter=": ">
+          <text macro="chapter-marker"/>
+          <group delimiter=" ">
+            <text macro="editor"/>
+            <text macro="container-title"/>
+          </group>
+        </group>
+        <text macro="publisher"/>
+        <group>
+          <text macro="date"/>
+          <text macro="journal-location"/>
+          <text macro="pages"/>
+        </group>
+      </group>
+      <text macro="collection-details" suffix=". "/>
+      <text macro="report-details" suffix=". "/>
+      <text macro="access"/>
+    </layout>
+  </bibliography>
+</style>
diff --git a/test/command/video-audio.md b/test/command/video-audio.md
new file mode 100644
--- /dev/null
+++ b/test/command/video-audio.md
@@ -0,0 +1,23 @@
+```
+% pandoc -f markdown-implicit_figures -t html
+![](./test.mp4)
+
+![Your browser does not support video.](foo/test.webm){width=300}
+
+![](test.mp3)
+
+![](./test.pdf)
+
+![](./test.jpg)
+^D
+<p><video src="./test.mp4" controls=""><a
+href="./test.mp4">Video</a></video></p>
+<p><video src="foo/test.webm" width="300" controls=""><a
+href="foo/test.webm">Your browser does not support
+video.</a></video></p>
+<p><audio src="test.mp3" controls=""><a
+href="test.mp3">Audio</a></audio></p>
+<p><embed src="./test.pdf" /></p>
+<p><img src="./test.jpg" /></p>
+```
+
diff --git a/test/command/wikilinks_title_after_pipe.md b/test/command/wikilinks_title_after_pipe.md
new file mode 100644
--- /dev/null
+++ b/test/command/wikilinks_title_after_pipe.md
@@ -0,0 +1,73 @@
+# CommonMark
+
+## Reader
+```
+% pandoc --from commonmark_x+wikilinks_title_after_pipe -t html --columns 90
+[[https://example.org]]
+
+[[https://example.org|title]]
+
+[[name of page]]
+
+[[name of page|title]]
+^D
+<p><a href="https://example.org" class="wikilink">https://example.org</a></p>
+<p><a href="https://example.org" class="wikilink">title</a></p>
+<p><a href="name of page" class="wikilink">name of page</a></p>
+<p><a href="name of page" class="wikilink">title</a></p>
+```
+
+## Writer
+
+```
+% pandoc -t commonmark_x+wikilinks_title_after_pipe -f html
+<p><a href="https://example.org" class="wikilink">https://example.org</a></p>
+<p><a href="https://example.org" class="wikilink">title</a></p>
+<p><a href="Home" class="wikilink">Home</a></p>
+<p><a href="Name of page" class="wikilink">Title</a></p>
+^D
+[[https://example.org]]
+
+[[https://example.org|title]]
+
+[[Home]]
+
+[[Name%20of%20page|Title]]
+```
+
+# Markdown
+## Reader
+
+```
+% pandoc --from markdown+wikilinks_title_after_pipe -t html --columns 90
+[[https://example.org]]
+
+[[https://example.org|title]]
+
+[[name of page]]
+
+[[name of page|title]]
+^D
+<p><a href="https://example.org" class="wikilink">https://example.org</a></p>
+<p><a href="https://example.org" class="wikilink">title</a></p>
+<p><a href="name of page" class="wikilink">name of page</a></p>
+<p><a href="name of page" class="wikilink">title</a></p>
+```
+
+## Writer
+
+```
+% pandoc -t markdown+wikilinks_title_after_pipe -f html
+<p><a href="https://example.org" class="wikilink">https://example.org</a></p>
+<p><a href="https://example.org" class="wikilink">title</a></p>
+<p><a href="Home" class="wikilink">Home</a></p>
+<p><a href="Name of page" class="wikilink">Title</a></p>
+^D
+[[https://example.org]]
+
+[[https://example.org|title]]
+
+[[Home]]
+
+[[Name%20of%20page|Title]]
+```
diff --git a/test/command/wikilinks_title_before_pipe.md b/test/command/wikilinks_title_before_pipe.md
new file mode 100644
--- /dev/null
+++ b/test/command/wikilinks_title_before_pipe.md
@@ -0,0 +1,84 @@
+# CommonMark
+
+## Reader
+
+```
+% pandoc -f commonmark+wikilinks_title_before_pipe -t html --columns 90
+[[https://example.org]]
+
+[[title|https://example.org]]
+
+[[Name of page]]
+
+[[Title|Name of page]]
+^D
+<p><a href="https://example.org" class="wikilink">https://example.org</a></p>
+<p><a href="https://example.org" class="wikilink">title</a></p>
+<p><a href="Name of page" class="wikilink">Name of page</a></p>
+<p><a href="Name of page" class="wikilink">Title</a></p>
+```
+
+## Writer
+
+```
+% pandoc -t commonmark_x+wikilinks_title_before_pipe -f html
+<p><a href="https://example.org" class="wikilink">https://example.org</a></p>
+<p><a href="https://example.org" class="wikilink">title</a></p>
+<p><a href="Home" class="wikilink">Home</a></p>
+<p><a href="Name of page" class="wikilink">Title</a></p>
+^D
+[[https://example.org]]
+
+[[title|https://example.org]]
+
+[[Home]]
+
+[[Title|Name%20of%20page]]
+```
+
+## Regular links should still work
+
+```
+% pandoc -f commonmark+wikilinks_title_before_pipe -t html
+[Title](Name%20of%20page)
+^D
+<p><a href="Name%20of%20page">Title</a></p>
+```
+
+# Markdown
+
+## Reader
+
+```
+% pandoc -f markdown+wikilinks_title_before_pipe -t html --columns 90
+[[https://example.org]]
+
+[[title|https://example.org]]
+
+[[Name of page]]
+
+[[Title|Name of page]]
+^D
+<p><a href="https://example.org" class="wikilink">https://example.org</a></p>
+<p><a href="https://example.org" class="wikilink">title</a></p>
+<p><a href="Name of page" class="wikilink">Name of page</a></p>
+<p><a href="Name of page" class="wikilink">Title</a></p>
+```
+
+## Writer
+
+```
+% pandoc -t markdown+wikilinks_title_before_pipe -f html
+<p><a href="https://example.org" class="wikilink">https://example.org</a></p>
+<p><a href="https://example.org" class="wikilink">title</a></p>
+<p><a href="Home" class="wikilink">Home</a></p>
+<p><a href="Name of page" class="wikilink">Title</a></p>
+^D
+[[https://example.org]]
+
+[[title|https://example.org]]
+
+[[Home]]
+
+[[Title|Name%20of%20page]]
+```
diff --git a/test/command/write18.md b/test/command/write18.md
--- a/test/command/write18.md
+++ b/test/command/write18.md
@@ -3,12 +3,12 @@
 % pandoc -t native
 \write18{git --version}
 ^D
-[RawBlock (Format "latex") "\\write18{git --version}"]
+[ RawBlock (Format "tex") "\\write18{git --version}" ]
 ```
 
 ```
 % pandoc -f latex+raw_tex -t native
 \write18{git --version}
 ^D
-[RawBlock (Format "latex") "\\write18{git --version}"]
+[ RawBlock (Format "latex") "\\write18{git --version}" ]
 ```
diff --git a/test/command/yaml-metadata-blocks.md b/test/command/yaml-metadata-blocks.md
new file mode 100644
--- /dev/null
+++ b/test/command/yaml-metadata-blocks.md
@@ -0,0 +1,121 @@
+```
+% pandoc -s -t native
+---
+foobar_: this should be ignored
+foo:
+  bar_: as should this
+---
+^D
+Pandoc
+  Meta
+    { unMeta = fromList [ ( "foo" , MetaMap (fromList []) ) ] }
+  []
+```
+```
+% pandoc -s -t native
+---
+# For precedence, see multiple-metadata-blocks.md and vars-and-metadata.md
+# For Bools, see also 4819.md
+# For Multiline strings, see yaml-with-chomp.md
+int: 7
+float: 1.5
+scientific: 3.7e-5
+bool: true
+more: False
+nothing: null
+empty: []
+nested:
+  int: 8
+  float: 2.5
+  bool: true
+  more: False
+  nothing: null
+  empty: []
+  scientific: 3.7e-5
+---
+^D
+Pandoc
+  Meta
+    { unMeta =
+        fromList
+          [ ( "bool" , MetaBool True )
+          , ( "empty" , MetaList [] )
+          , ( "float" , MetaInlines [ Str "1.5" ] )
+          , ( "int" , MetaInlines [ Str "7" ] )
+          , ( "more" , MetaBool False )
+          , ( "nested"
+            , MetaMap
+                (fromList
+                   [ ( "bool" , MetaBool True )
+                   , ( "empty" , MetaList [] )
+                   , ( "float" , MetaInlines [ Str "2.5" ] )
+                   , ( "int" , MetaInlines [ Str "8" ] )
+                   , ( "more" , MetaBool False )
+                   , ( "nothing" , MetaString "" )
+                   , ( "scientific" , MetaInlines [ Str "3.7e-5" ] )
+                   ])
+            )
+          , ( "nothing" , MetaString "" )
+          , ( "scientific" , MetaInlines [ Str "3.7e-5" ] )
+          ]
+    }
+  []
+```
+```
+% pandoc -s -t native
+---
+array:
+  - foo: bar
+  - bool: True
+---
+^D
+Pandoc
+  Meta
+    { unMeta =
+        fromList
+          [ ( "array"
+            , MetaList
+                [ MetaMap
+                    (fromList [ ( "foo" , MetaInlines [ Str "bar" ] ) ])
+                , MetaMap (fromList [ ( "bool" , MetaBool True ) ])
+                ]
+            )
+          ]
+    }
+  []
+```
+```
+% pandoc -s -t native --metadata-file command/yaml-metadata.yaml
+---
+title: document
+---
+^D
+Pandoc
+  Meta
+    { unMeta =
+        fromList
+          [ ( "other"
+            , MetaInlines
+                [ Emph [ Str "markdown" ] , Space , Str "value" ]
+            )
+          , ( "title" , MetaInlines [ Str "document" ] )
+          ]
+    }
+  []
+```
+```
+% pandoc -s -t native --metadata-file command/yaml-metadata.yaml -M title=cmdline
+^D
+Pandoc
+  Meta
+    { unMeta =
+        fromList
+          [ ( "other"
+            , MetaInlines
+                [ Emph [ Str "markdown" ] , Space , Str "value" ]
+            )
+          , ( "title" , MetaString "cmdline" )
+          ]
+    }
+  []
+```
diff --git a/test/command/yaml-metadata.yaml b/test/command/yaml-metadata.yaml
new file mode 100644
--- /dev/null
+++ b/test/command/yaml-metadata.yaml
@@ -0,0 +1,4 @@
+---
+title: file
+other: _markdown_ value
+---
diff --git a/test/command/yaml-with-chomp.md b/test/command/yaml-with-chomp.md
--- a/test/command/yaml-with-chomp.md
+++ b/test/command/yaml-with-chomp.md
@@ -7,6 +7,14 @@
     BLOCK
 ...
 ^D
-Pandoc (Meta {unMeta = fromList [("ml",MetaBlocks [Para [Str "TEST"],Plain [Str "BLOCK"]])]})
-[]
+Pandoc
+  Meta
+    { unMeta =
+        fromList
+          [ ( "ml"
+            , MetaInlines [ Str "TEST" , LineBreak , Str "BLOCK" ]
+            )
+          ]
+    }
+  []
 ```
diff --git a/test/command/zeitschrift-fur-kunstgeschichte.csl b/test/command/zeitschrift-fur-kunstgeschichte.csl
new file mode 100644
--- /dev/null
+++ b/test/command/zeitschrift-fur-kunstgeschichte.csl
@@ -0,0 +1,346 @@
+<?xml version="1.0" encoding="utf-8"?>
+<style xmlns="http://purl.org/net/xbiblio/csl" class="note" version="1.0" demote-non-dropping-particle="sort-only">
+  <info>
+    <title>Zeitschrift für Kunstgeschichte</title>
+    <title-short>ZfK</title-short>
+    <id>http://www.zotero.org/styles/zeitschrift-fur-kunstgeschichte</id>
+    <link href="http://www.zotero.org/styles/zeitschrift-fur-kunstgeschichte" rel="self"/>
+    <link href="http://www.zotero.org/styles/kritische-ausgabe" rel="template"/>
+    <link href="http://www.uni-bielefeld.de/geschichte/abteilung/arbeitsbereiche/bildwissenschaft/zfk/documents/Sylesheet-(ger)-Zeitschrift-fur-Kunstgeschichte.pdf" rel="documentation"/>
+    <link href="https://github.com/citation-style-language/styles/pull/1861" rel="documentation"/>
+    <author>
+      <name>Philipp Zumstein</name>
+      <uri>https://github.com/zuphilip/</uri>
+    </author>
+    <contributor>
+      <name>Anna Simon</name>
+      <email>simonanna@gmx.net</email>
+    </contributor>
+    <category citation-format="note"/>
+    <category field="humanities"/>
+    <category field="history"/>
+    <issn>0044-2992</issn>
+    <summary>From the editors: "Die Herausgeber werden im Falle von Editionen, Lexika und Ausstellungskatalogen dem Titel nachgestellt [use encyclopedia articles with or without container-title for that]. Bei gewöhnlichen Sammelbänden werden die Herausgeber dem Titel vorangestellt [use book for that]." Multilingual style; the information for exhibition catalogues should be entered in the field collection-title; locators may use the word "here" or "hier" in front of the page referring to which must be entered individually (the style outputs the locator as it is entered w/o any label or additional text).</summary>
+    <updated>2016-02-03T17:41:02+00:00</updated>
+    <rights license="http://creativecommons.org/licenses/by-sa/3.0/">This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 License</rights>
+  </info>
+  <locale xml:lang="de">
+    <terms>
+      <term name="note">wie Anm.</term>
+      <term name="et-al">et al.</term>
+      <term name="editor" form="short">Hg.</term>
+      <term name="editortranslator" form="verb-short">hg. und übers. von</term>
+      <term name="accessed">letzter Zugriff am</term>
+    </terms>
+  </locale>
+  <locale xml:lang="en">
+    <terms>
+      <term name="note">as note</term>
+      <term name="editortranslator" form="verb-short">ed. and trans. by</term>
+    </terms>
+  </locale>
+  <macro name="author-short">
+    <names variable="author">
+      <name form="short" delimiter="/" and="text" delimiter-precedes-et-al="never"/>
+      <substitute>
+        <choose>
+          <if type="entry-encyclopedia" match="none">
+            <names variable="editor"/>
+          </if>
+        </choose>
+        <text variable="title" form="short"/>
+      </substitute>
+    </names>
+  </macro>
+  <macro name="author">
+    <names variable="author" delimiter=", ">
+      <name and="text" delimiter-precedes-et-al="never" delimiter-precedes-last="never"/>
+      <label form="short" prefix=" (" suffix=")"/>
+      <substitute>
+        <choose>
+          <if type="entry-encyclopedia" match="none">
+            <names variable="editor"/>
+          </if>
+        </choose>
+        <text variable="title"/>
+      </substitute>
+    </names>
+  </macro>
+  <macro name="author-bibliography">
+    <names variable="author" delimiter=", ">
+      <name and="text" delimiter-precedes-et-al="never" delimiter-precedes-last="never" name-as-sort-order="first"/>
+      <label form="short" prefix=" (" suffix=")"/>
+      <substitute>
+        <choose>
+          <if type="entry-encyclopedia" match="none">
+            <names variable="editor"/>
+          </if>
+        </choose>
+        <text variable="title"/>
+      </substitute>
+    </names>
+  </macro>
+  <macro name="editor">
+    <names variable="editor translator" delimiter=", ">
+      <name and="text" delimiter-precedes-et-al="never" delimiter-precedes-last="never"/>
+      <label form="short" prefix=" (" suffix=")"/>
+    </names>
+  </macro>
+  <macro name="editor-encyclopedia">
+    <names variable="editor translator" delimiter=", ">
+      <label form="verb-short" suffix=" "/>
+      <name and="text" delimiter-precedes-et-al="never" delimiter-precedes-last="never"/>
+    </names>
+  </macro>
+  <macro name="volume">
+    <choose>
+      <if type="article-journal">
+        <text variable="volume" prefix=" "/>
+        <text variable="issue" prefix="/"/>
+      </if>
+      <else>
+        <choose>
+          <if variable="volume">
+            <group delimiter=" ">
+              <number variable="volume" form="long-ordinal" text-case="capitalize-first"/>
+              <text term="volume" form="short" text-case="capitalize-first"/>
+            </group>
+          </if>
+          <else>
+            <group>
+              <number variable="number-of-volumes" form="numeric"/>
+              <text term="volume" form="short" prefix=" " plural="true"/>
+            </group>
+          </else>
+        </choose>
+      </else>
+    </choose>
+  </macro>
+  <macro name="year-date">
+    <date variable="issued" date-parts="year" form="numeric"/>
+  </macro>
+  <macro name="collection-with-number">
+    <group delimiter=", " prefix="(" suffix=")">
+      <text variable="collection-title"/>
+      <text variable="collection-number"/>
+    </group>
+  </macro>
+  <macro name="translator">
+    <names variable="editor translator" delimiter=", ">
+      <label form="verb-short"/>
+      <name prefix=" " and="text" delimiter-precedes-et-al="never" delimiter-precedes-last="never"/>
+    </names>
+  </macro>
+  <citation et-al-min="3" et-al-use-first="1" disambiguate-add-names="true">
+    <layout delimiter="; " suffix=".">
+      <choose>
+        <if position="ibid-with-locator">
+          <group delimiter=", ">
+            <text term="ibid"/>
+            <text variable="locator" prefix=" "/>
+          </group>
+        </if>
+        <else-if position="ibid">
+          <text term="ibid"/>
+        </else-if>
+        <else-if position="subsequent">
+          <group delimiter=", ">
+            <group delimiter=" ">
+              <text macro="author-short"/>
+              <text macro="year-date"/>
+              <group delimiter=" " prefix="(" suffix=")">
+                <text term="note"/>
+                <text variable="first-reference-note-number"/>
+              </group>
+            </group>
+            <text variable="locator"/>
+          </group>
+        </else-if>
+        <else>
+          <group delimiter=", ">
+            <text macro="author"/>
+            <choose>
+              <if match="any" variable="container-title">
+                <text variable="title"/>
+                <group delimiter=" ">
+                  <text term="in" suffix=": "/>
+                  <choose>
+                    <if type="entry-encyclopedia" match="any">
+                      <group delimiter=", ">
+                        <group delimiter=" ">
+                          <text variable="container-title" font-style="italic"/>
+                          <text macro="collection-with-number"/>
+                          <text macro="volume"/>
+                        </group>
+                        <text macro="editor-encyclopedia"/>
+                      </group>
+                    </if>
+                    <else>
+                      <text macro="editor" suffix=","/>
+                      <text variable="container-title" font-style="italic"/>
+                      <text macro="collection-with-number"/>
+                      <text macro="volume"/>
+                    </else>
+                  </choose>
+                </group>
+              </if>
+              <else>
+                <choose>
+                  <if type="entry-encyclopedia" match="any">
+                    <group delimiter=" ">
+                      <text variable="title" font-style="italic"/>
+                      <text macro="collection-with-number"/>
+                    </group>
+                    <text macro="editor-encyclopedia"/>
+                  </if>
+                  <else-if match="any" variable="translator">
+                    <choose>
+                      <if match="none" variable="author">
+                        <names variable="editor">
+                          <name and="text" delimiter-precedes-et-al="never" delimiter-precedes-last="never"/>
+                          <label form="short" prefix=" (" suffix=")"/>
+                        </names>
+                      </if>
+                    </choose>
+                    <group delimiter=" ">
+                      <text variable="title" font-style="italic" suffix=","/>
+                      <text macro="collection-with-number"/>
+                    </group>
+                  </else-if>
+                  <else>
+                    <choose>
+                      <if match="none" variable="author">
+                        <names variable="editor">
+                          <name and="text" delimiter-precedes-et-al="never" delimiter-precedes-last="never"/>
+                          <label form="short" prefix=" (" suffix=")"/>
+                        </names>
+                      </if>
+                    </choose>
+                    <group delimiter=" ">
+                      <group delimiter=", ">
+                        <text variable="title" font-style="italic"/>
+                        <text macro="translator"/>
+                      </group>
+                      <text macro="collection-with-number"/>
+                    </group>
+                  </else>
+                </choose>
+              </else>
+            </choose>
+            <choose>
+              <if type="thesis">
+                <text variable="publisher" prefix="Diss., "/>
+              </if>
+            </choose>
+            <group delimiter=" ">
+              <text variable="publisher-place"/>
+              <group>
+                <text variable="edition" vertical-align="sup"/>
+                <text macro="year-date"/>
+              </group>
+            </group>
+            <text variable="page" prefix=" "/>
+            <text variable="locator" prefix=" "/>
+          </group>
+        </else>
+      </choose>
+      <choose>
+        <if variable="URL" match="any">
+          <group>
+            <text variable="URL" prefix=", "/>
+            <text term="accessed" prefix=" ("/>
+            <date variable="accessed" prefix=" " delimiter="." suffix=")">
+              <date-part name="day"/>
+              <date-part name="month" form="numeric"/>
+              <date-part name="year"/>
+            </date>
+          </group>
+        </if>
+      </choose>
+    </layout>
+  </citation>
+  <bibliography et-al-min="3" et-al-use-first="1" subsequent-author-substitute="&#8212;&#8212;&#8212;" entry-spacing="0" hanging-indent="true">
+    <sort>
+      <key macro="author-bibliography"/>
+      <key macro="year-date"/>
+      <key variable="title"/>
+    </sort>
+    <layout suffix=".">
+      <group delimiter=", ">
+        <text macro="author-bibliography"/>
+        <choose>
+          <if match="any" variable="container-title">
+            <text variable="title"/>
+            <group delimiter=" ">
+              <text term="in" suffix=": "/>
+              <choose>
+                <if type="entry-encyclopedia" match="any">
+                  <group delimiter=", ">
+                    <group delimiter=" ">
+                      <text variable="container-title" font-style="italic"/>
+                      <text macro="collection-with-number"/>
+                      <text macro="volume"/>
+                    </group>
+                    <text macro="editor-encyclopedia"/>
+                  </group>
+                </if>
+                <else>
+                  <text macro="editor" suffix=","/>
+                  <text variable="container-title" font-style="italic"/>
+                  <text macro="collection-with-number"/>
+                  <text macro="volume"/>
+                </else>
+              </choose>
+            </group>
+          </if>
+          <else>
+            <choose>
+              <if type="entry-encyclopedia" match="any">
+                <group delimiter=" ">
+                  <text variable="title" font-style="italic"/>
+                  <text macro="collection-with-number"/>
+                </group>
+                <text macro="editor-encyclopedia"/>
+              </if>
+              <else>
+                <group delimiter=" ">
+                  <group delimiter=", ">
+                    <text variable="title" font-style="italic"/>
+                    <text macro="editor"/>
+                  </group>
+                  <text macro="collection-with-number"/>
+                </group>
+              </else>
+            </choose>
+          </else>
+        </choose>
+        <choose>
+          <if type="thesis">
+            <text variable="publisher" prefix="Diss., "/>
+          </if>
+        </choose>
+        <group delimiter=" ">
+          <text variable="publisher-place"/>
+          <group>
+            <text variable="edition" vertical-align="sup"/>
+            <text macro="year-date"/>
+          </group>
+        </group>
+        <text variable="page" prefix=" "/>
+      </group>
+      <choose>
+        <if variable="URL" match="any">
+          <group>
+            <text variable="URL" prefix=", "/>
+            <text term="accessed" prefix=" ("/>
+            <date variable="accessed" prefix=" " delimiter="." suffix=")">
+              <date-part name="day"/>
+              <date-part name="month" form="numeric"/>
+              <date-part name="year"/>
+            </date>
+          </group>
+        </if>
+      </choose>
+    </layout>
+  </bibliography>
+</style>
diff --git a/test/creole-reader.native b/test/creole-reader.native
--- a/test/creole-reader.native
+++ b/test/creole-reader.native
@@ -1,95 +1,970 @@
-Pandoc (Meta {unMeta = fromList []})
-[Header 1 ("",[],[]) [Str "Top-level heading (1)"]
-,Header 2 ("",[],[]) [Str "This a test for creole 0.1 (2)"]
-,Header 3 ("",[],[]) [Str "This is a Subheading (3)"]
-,Header 4 ("",[],[]) [Str "Subsub (4)"]
-,Header 5 ("",[],[]) [Str "Subsubsub (5)"]
-,Para [Str "The",Space,Str "ending",Space,Str "equal",Space,Str "signs",Space,Str "should",Space,Str "not",Space,Str "be",Space,Str "displayed:"]
-,Header 1 ("",[],[]) [Str "Top-level heading (1)"]
-,Header 2 ("",[],[]) [Str "This a test for creole 0.1 (2)"]
-,Header 3 ("",[],[]) [Str "This is a Subheading (3)"]
-,Header 4 ("",[],[]) [Str "Subsub (4)"]
-,Header 5 ("",[],[]) [Str "Subsubsub (5)"]
-,Para [Str "You",Space,Str "can",Space,Str "make",Space,Str "things",Space,Strong [Str "bold"],Space,Str "or",Space,Emph [Str "italic"],Space,Str "or",Space,Strong [Emph [Str "both"]],Space,Str "or",Space,Emph [Strong [Str "both"]],Str "."]
-,Para [Str "Character",Space,Str "formatting",Space,Str "extends",Space,Str "across",Space,Str "line",Space,Str "breaks:",Space,Strong [Str "bold,",Space,Str "this",Space,Str "is",Space,Str "still",Space,Str "bold.",Space,Str "This",Space,Str "line",Space,Str "deliberately",Space,Str "does",Space,Str "not",Space,Str "end",Space,Str "in",Space,Str "star-star."]]
-,Para [Str "Not",Space,Str "bold.",Space,Str "Character",Space,Str "formatting",Space,Str "does",Space,Str "not",Space,Str "cross",Space,Str "paragraph",Space,Str "boundaries."]
-,Para [Str "You",Space,Str "can",Space,Str "use",Space,Link ("",[],[]) [Str "internal links"] ("internal links",""),Space,Str "or",Space,Link ("",[],[]) [Str "external links"] ("http://www.wikicreole.org",""),Str ",",Space,Str "give",Space,Str "the",Space,Str "link",Space,Str "a",Space,Link ("",[],[]) [Str "different"] ("internal links",""),Space,Str "name."]
-,Para [Str "Here's",Space,Str "another",Space,Str "sentence:",Space,Str "This",Space,Str "wisdom",Space,Str "is",Space,Str "taken",Space,Str "from",Space,Link ("",[],[]) [Str "Ward Cunningham's"] ("Ward Cunningham's",""),Space,Link ("",[],[]) [Str "Presentation at the Wikisym 06"] ("http://www.c2.com/doc/wikisym/WikiSym2006.pdf",""),Str "."]
-,Para [Str "Here's",Space,Str "a",Space,Str "external",Space,Str "link",Space,Str "without",Space,Str "a",Space,Str "description:",Space,Link ("",[],[]) [Str "http://www.wikicreole.org"] ("http://www.wikicreole.org","")]
-,Para [Str "Be",Space,Str "careful",Space,Str "that",Space,Str "italic",Space,Str "links",Space,Str "are",Space,Str "rendered",Space,Str "properly:",Space,Emph [Link ("",[],[]) [Str "My Book Title"] ("http://my.book.example/","")]]
-,Para [Str "Free",Space,Str "links",Space,Str "without",Space,Str "braces",Space,Str "should",Space,Str "be",Space,Str "rendered",Space,Str "as",Space,Str "well,",Space,Str "like",Space,Link ("",[],[]) [Str "http://www.wikicreole.org/"] ("http://www.wikicreole.org/",""),Space,Str "and",Space,Link ("",[],[]) [Str "http://www.wikicreole.org/users/~example"] ("http://www.wikicreole.org/users/~example",""),Str "."]
-,Para [Str "Creole1.0",Space,Str "specifies",Space,Str "that",Space,Link ("",[],[]) [Str "http://bar"] ("http://bar",""),Space,Str "and",Space,Link ("",[],[]) [Str "ftp://bar"] ("ftp://bar",""),Space,Str "should",Space,Str "not",Space,Str "render",Space,Str "italic,",Space,Str "something",Space,Str "like",Space,Str "foo:",Emph [Str "bar",Space,Str "should",Space,Str "render",Space,Str "as",Space,Str "italic."]]
-,Para [Str "You",Space,Str "can",Space,Str "use",Space,Str "this",Space,Str "to",Space,Str "draw",Space,Str "a",Space,Str "line",Space,Str "to",Space,Str "separate",Space,Str "the",Space,Str "page:"]
-,HorizontalRule
-,Para [Str "You",Space,Str "can",Space,Str "use",Space,Str "lists,",Space,Str "start",Space,Str "it",Space,Str "at",Space,Str "the",Space,Str "first",Space,Str "column",Space,Str "for",Space,Str "now,",Space,Str "please..."]
-,Para [Str "unnumbered",Space,Str "lists",Space,Str "are",Space,Str "like"]
-,BulletList
- [[Plain [Str "item",Space,Str "a"]]
- ,[Plain [Str "item",Space,Str "b"]]
- ,[Plain [Strong [Str "bold",Space,Str "item",Space,Str "c"]]]]
-,Para [Str "blank",Space,Str "space",Space,Str "is",Space,Str "also",Space,Str "permitted",Space,Str "before",Space,Str "lists",Space,Str "like:"]
-,BulletList
- [[Plain [Str "item",Space,Str "a"]]
- ,[Plain [Str "item",Space,Str "b"]]
- ,[Plain [Str "item",Space,Str "c"]
-  ,BulletList
-   [[Plain [Str "item",Space,Str "c.a"]]]]]
-,Para [Str "or",Space,Str "you",Space,Str "can",Space,Str "number",Space,Str "them"]
-,OrderedList (1,DefaultStyle,DefaultDelim)
- [[Plain [Link ("",[],[]) [Str "item 1"] ("item 1","")]]
- ,[Plain [Str "item",Space,Str "2"]]
- ,[Plain [Emph [Space,Str "italic",Space,Str "item",Space,Str "3",Space]]
-  ,OrderedList (1,DefaultStyle,DefaultDelim)
-   [[Plain [Str "item",Space,Str "3.1"]]
-   ,[Plain [Str "item",Space,Str "3.2"]]]]]
-,Para [Str "up",Space,Str "to",Space,Str "five",Space,Str "levels"]
-,BulletList
- [[Plain [Str "1"]
-  ,BulletList
-   [[Plain [Str "2"]
-    ,BulletList
-     [[Plain [Str "3"]
-      ,BulletList
-       [[Plain [Str "4"]
-        ,BulletList
-         [[Plain [Str "5"]]]]]]]]]]]
-,BulletList
- [[Plain [Str "You",Space,Str "can",Space,Str "have",Space,Str "multiline",Space,Str "list",Space,Str "items"]]
- ,[Plain [Str "this",Space,Str "is",Space,Str "a",Space,Str "second",Space,Str "multiline",Space,Str "list",Space,Str "item"]]]
-,Para [Str "You",Space,Str "can",Space,Str "use",Space,Str "nowiki",Space,Str "syntax",Space,Str "if",Space,Str "you",Space,Str "would",Space,Str "like",Space,Str "do",Space,Str "stuff",Space,Str "like",Space,Str "this:"]
-,CodeBlock ("",[],[]) "Guitar Chord C:\n\n||---|---|---|\n||-0-|---|---|\n||---|---|---|\n||---|-0-|---|\n||---|---|-0-|\n||---|---|---|"
-,Para [Str "You",Space,Str "can",Space,Str "also",Space,Str "use",Space,Str "it",Space,Str "inline",Space,Str "nowiki",Space,Code ("",[],[]) " in a sentence ",Space,Str "like",Space,Str "this."]
-,Header 1 ("",[],[]) [Str "Escapes"]
-,Para [Str "Normal",Space,Str "Link:",Space,Link ("",[],[]) [Str "http://wikicreole.org/"] ("http://wikicreole.org/",""),Space,Str "-",Space,Str "now",Space,Str "same",Space,Str "link,",Space,Str "but",Space,Str "escaped:",Space,Str "http://wikicreole.org/"]
-,Para [Str "Normal",Space,Str "asterisks:",Space,Str "**not",Space,Str "bold**"]
-,Para [Str "a",Space,Str "tilde",Space,Str "alone:",Space,Str "~"]
-,Para [Str "a",Space,Str "tilde",Space,Str "escapes",Space,Str "itself:",Space,Str "~xxx"]
-,Header 3 ("",[],[]) [Str "Creole 0.2"]
-,Para [Str "This",Space,Str "should",Space,Str "be",Space,Str "a",Space,Str "flower",Space,Str "with",Space,Str "the",Space,Str "ALT",Space,Str "text",Space,Str "\"this",Space,Str "is",Space,Str "a",Space,Str "flower\"",Space,Str "if",Space,Str "your",Space,Str "wiki",Space,Str "supports",Space,Str "ALT",Space,Str "text",Space,Str "on",Space,Str "images:"]
-,Para [Image ("",[],[]) [Str "here is a red flower"] ("Red-Flower.jpg","")]
-,Header 3 ("",[],[]) [Str "Creole 0.4"]
-,Para [Str "Tables",Space,Str "are",Space,Str "done",Space,Str "like",Space,Str "this:"]
-,Table [] [AlignDefault,AlignDefault] [0.0,0.0]
- [[Plain [Str "header",Space,Str "col1"]]
- ,[Plain [Str "header",Space,Str "col2"]]]
- [[[Plain [Str "col1"]]
-  ,[Plain [Str "col2"]]]
- ,[[Plain [Str "you"]]
-  ,[Plain [Str "can"]]]
- ,[[Plain [Str "also"]]
-  ,[Plain [Str "align",LineBreak,Str "it."]]]]
-,Para [Str "You",Space,Str "can",Space,Str "format",Space,Str "an",Space,Str "address",Space,Str "by",Space,Str "simply",Space,Str "forcing",Space,Str "linebreaks:"]
-,Para [Str "My",Space,Str "contact",Space,Str "dates:",LineBreak,Str "Pone:",Space,Str "xyz",LineBreak,Str "Fax:",Space,Str "+45",LineBreak,Str "Mobile:",Space,Str "abc"]
-,Header 3 ("",[],[]) [Str "Creole 0.5"]
-,Table [] [AlignDefault,AlignDefault] [0.0,0.0]
- [[Plain [Str "Header",Space,Str "title"]]
- ,[Plain [Str "Another",Space,Str "header",Space,Str "title"]]]
- [[[Plain [Code ("",[],[]) " //not italic text// "]]
-  ,[Plain [Code ("",[],[]) " **not bold text** "]]]
- ,[[Plain [Emph [Str "italic",Space,Str "text"]]]
-  ,[Plain [Strong [Space,Str "bold",Space,Str "text",Space]]]]]
-,Header 3 ("",[],[]) [Str "Creole 1.0"]
-,Para [Str "If",Space,Str "interwiki",Space,Str "links",Space,Str "are",Space,Str "setup",Space,Str "in",Space,Str "your",Space,Str "wiki,",Space,Str "this",Space,Str "links",Space,Str "to",Space,Str "the",Space,Str "WikiCreole",Space,Str "page",Space,Str "about",Space,Str "Creole",Space,Str "1.0",Space,Str "test",Space,Str "cases:",Space,Link ("",[],[]) [Str "WikiCreole:Creole1.0TestCases"] ("WikiCreole:Creole1.0TestCases",""),Str "."]
-,HorizontalRule
-,Para [Str "The",Space,Str "above",Space,Str "test",Space,Str "document",Space,Str "was",Space,Str "found",Space,Str "on",Space,Link ("",[],[]) [Str "http://www.wikicreole.org/wiki/Creole1.0TestCases"] ("http://www.wikicreole.org/wiki/Creole1.0TestCases",""),Space,Str "and",Space,Str "downloaded",Space,Str "from",Space,Link ("",[],[]) [Str "http://www.wikicreole.org/attach/Creole1.0TestCases/creole1.0test.txt"] ("http://www.wikicreole.org/attach/Creole1.0TestCases/creole1.0test.txt",""),Str "."]
-,Para [Str "The",Space,Str "Creole",Space,Str "Wiki",Space,Str "is",Space,Str "licensed:",Space,Str "Copyright",Space,Str "(C)",Space,Str "by",Space,Str "the",Space,Str "contributors.",Space,Str "Some",Space,Str "rights",Space,Str "reserved,",Space,Str "license",Space,Link ("",[],[]) [Str "https://creativecommons.org/licenses/by-sa/1.0/"] ("BY-SA",""),Str "."]]
+Pandoc
+  Meta { unMeta = fromList [] }
+  [ Header 1 ( "" , [] , [] ) [ Str "Top-level heading (1)" ]
+  , Header
+      2 ( "" , [] , [] ) [ Str "This a test for creole 0.1 (2)" ]
+  , Header
+      3 ( "" , [] , [] ) [ Str "This is a Subheading (3)" ]
+  , Header 4 ( "" , [] , [] ) [ Str "Subsub (4)" ]
+  , Header 5 ( "" , [] , [] ) [ Str "Subsubsub (5)" ]
+  , Para
+      [ Str "The"
+      , Space
+      , Str "ending"
+      , Space
+      , Str "equal"
+      , Space
+      , Str "signs"
+      , Space
+      , Str "should"
+      , Space
+      , Str "not"
+      , Space
+      , Str "be"
+      , Space
+      , Str "displayed:"
+      ]
+  , Header 1 ( "" , [] , [] ) [ Str "Top-level heading (1)" ]
+  , Header
+      2 ( "" , [] , [] ) [ Str "This a test for creole 0.1 (2)" ]
+  , Header
+      3 ( "" , [] , [] ) [ Str "This is a Subheading (3)" ]
+  , Header 4 ( "" , [] , [] ) [ Str "Subsub (4)" ]
+  , Header 5 ( "" , [] , [] ) [ Str "Subsubsub (5)" ]
+  , Para
+      [ Str "You"
+      , Space
+      , Str "can"
+      , Space
+      , Str "make"
+      , Space
+      , Str "things"
+      , Space
+      , Strong [ Str "bold" ]
+      , Space
+      , Str "or"
+      , Space
+      , Emph [ Str "italic" ]
+      , Space
+      , Str "or"
+      , Space
+      , Strong [ Emph [ Str "both" ] ]
+      , Space
+      , Str "or"
+      , Space
+      , Emph [ Strong [ Str "both" ] ]
+      , Str "."
+      ]
+  , Para
+      [ Str "Character"
+      , Space
+      , Str "formatting"
+      , Space
+      , Str "extends"
+      , Space
+      , Str "across"
+      , Space
+      , Str "line"
+      , Space
+      , Str "breaks:"
+      , Space
+      , Strong
+          [ Str "bold,"
+          , Space
+          , Str "this"
+          , Space
+          , Str "is"
+          , Space
+          , Str "still"
+          , Space
+          , Str "bold."
+          , Space
+          , Str "This"
+          , Space
+          , Str "line"
+          , Space
+          , Str "deliberately"
+          , Space
+          , Str "does"
+          , Space
+          , Str "not"
+          , Space
+          , Str "end"
+          , Space
+          , Str "in"
+          , Space
+          , Str "star-star."
+          ]
+      ]
+  , Para
+      [ Str "Not"
+      , Space
+      , Str "bold."
+      , Space
+      , Str "Character"
+      , Space
+      , Str "formatting"
+      , Space
+      , Str "does"
+      , Space
+      , Str "not"
+      , Space
+      , Str "cross"
+      , Space
+      , Str "paragraph"
+      , Space
+      , Str "boundaries."
+      ]
+  , Para
+      [ Str "You"
+      , Space
+      , Str "can"
+      , Space
+      , Str "use"
+      , Space
+      , Link
+          ( "" , [] , [] )
+          [ Str "internal links" ]
+          ( "internal links" , "" )
+      , Space
+      , Str "or"
+      , Space
+      , Link
+          ( "" , [] , [] )
+          [ Str "external links" ]
+          ( "http://www.wikicreole.org" , "" )
+      , Str ","
+      , Space
+      , Str "give"
+      , Space
+      , Str "the"
+      , Space
+      , Str "link"
+      , Space
+      , Str "a"
+      , Space
+      , Link
+          ( "" , [] , [] )
+          [ Str "different" ]
+          ( "internal links" , "" )
+      , Space
+      , Str "name."
+      ]
+  , Para
+      [ Str "Here's"
+      , Space
+      , Str "another"
+      , Space
+      , Str "sentence:"
+      , Space
+      , Str "This"
+      , Space
+      , Str "wisdom"
+      , Space
+      , Str "is"
+      , Space
+      , Str "taken"
+      , Space
+      , Str "from"
+      , Space
+      , Link
+          ( "" , [] , [] )
+          [ Str "Ward Cunningham's" ]
+          ( "Ward Cunningham's" , "" )
+      , Space
+      , Link
+          ( "" , [] , [] )
+          [ Str "Presentation at the Wikisym 06" ]
+          ( "http://www.c2.com/doc/wikisym/WikiSym2006.pdf" , "" )
+      , Str "."
+      ]
+  , Para
+      [ Str "Here's"
+      , Space
+      , Str "a"
+      , Space
+      , Str "external"
+      , Space
+      , Str "link"
+      , Space
+      , Str "without"
+      , Space
+      , Str "a"
+      , Space
+      , Str "description:"
+      , Space
+      , Link
+          ( "" , [] , [] )
+          [ Str "http://www.wikicreole.org" ]
+          ( "http://www.wikicreole.org" , "" )
+      ]
+  , Para
+      [ Str "Be"
+      , Space
+      , Str "careful"
+      , Space
+      , Str "that"
+      , Space
+      , Str "italic"
+      , Space
+      , Str "links"
+      , Space
+      , Str "are"
+      , Space
+      , Str "rendered"
+      , Space
+      , Str "properly:"
+      , Space
+      , Emph
+          [ Link
+              ( "" , [] , [] )
+              [ Str "My Book Title" ]
+              ( "http://my.book.example/" , "" )
+          ]
+      ]
+  , Para
+      [ Str "Free"
+      , Space
+      , Str "links"
+      , Space
+      , Str "without"
+      , Space
+      , Str "braces"
+      , Space
+      , Str "should"
+      , Space
+      , Str "be"
+      , Space
+      , Str "rendered"
+      , Space
+      , Str "as"
+      , Space
+      , Str "well,"
+      , Space
+      , Str "like"
+      , Space
+      , Link
+          ( "" , [] , [] )
+          [ Str "http://www.wikicreole.org/" ]
+          ( "http://www.wikicreole.org/" , "" )
+      , Space
+      , Str "and"
+      , Space
+      , Link
+          ( "" , [] , [] )
+          [ Str "http://www.wikicreole.org/users/~example" ]
+          ( "http://www.wikicreole.org/users/~example" , "" )
+      , Str "."
+      ]
+  , Para
+      [ Str "Creole1.0"
+      , Space
+      , Str "specifies"
+      , Space
+      , Str "that"
+      , Space
+      , Link
+          ( "" , [] , [] ) [ Str "http://bar" ] ( "http://bar" , "" )
+      , Space
+      , Str "and"
+      , Space
+      , Link
+          ( "" , [] , [] ) [ Str "ftp://bar" ] ( "ftp://bar" , "" )
+      , Space
+      , Str "should"
+      , Space
+      , Str "not"
+      , Space
+      , Str "render"
+      , Space
+      , Str "italic,"
+      , Space
+      , Str "something"
+      , Space
+      , Str "like"
+      , Space
+      , Str "foo:"
+      , Emph
+          [ Str "bar"
+          , Space
+          , Str "should"
+          , Space
+          , Str "render"
+          , Space
+          , Str "as"
+          , Space
+          , Str "italic."
+          ]
+      ]
+  , Para
+      [ Str "You"
+      , Space
+      , Str "can"
+      , Space
+      , Str "use"
+      , Space
+      , Str "this"
+      , Space
+      , Str "to"
+      , Space
+      , Str "draw"
+      , Space
+      , Str "a"
+      , Space
+      , Str "line"
+      , Space
+      , Str "to"
+      , Space
+      , Str "separate"
+      , Space
+      , Str "the"
+      , Space
+      , Str "page:"
+      ]
+  , HorizontalRule
+  , Para
+      [ Str "You"
+      , Space
+      , Str "can"
+      , Space
+      , Str "use"
+      , Space
+      , Str "lists,"
+      , Space
+      , Str "start"
+      , Space
+      , Str "it"
+      , Space
+      , Str "at"
+      , Space
+      , Str "the"
+      , Space
+      , Str "first"
+      , Space
+      , Str "column"
+      , Space
+      , Str "for"
+      , Space
+      , Str "now,"
+      , Space
+      , Str "please..."
+      ]
+  , Para
+      [ Str "unnumbered"
+      , Space
+      , Str "lists"
+      , Space
+      , Str "are"
+      , Space
+      , Str "like"
+      ]
+  , BulletList
+      [ [ Plain [ Str "item" , Space , Str "a" ] ]
+      , [ Plain [ Str "item" , Space , Str "b" ] ]
+      , [ Plain
+            [ Strong
+                [ Str "bold" , Space , Str "item" , Space , Str "c" ]
+            ]
+        ]
+      ]
+  , Para
+      [ Str "blank"
+      , Space
+      , Str "space"
+      , Space
+      , Str "is"
+      , Space
+      , Str "also"
+      , Space
+      , Str "permitted"
+      , Space
+      , Str "before"
+      , Space
+      , Str "lists"
+      , Space
+      , Str "like:"
+      ]
+  , BulletList
+      [ [ Plain [ Str "item" , Space , Str "a" ] ]
+      , [ Plain [ Str "item" , Space , Str "b" ] ]
+      , [ Plain [ Str "item" , Space , Str "c" ]
+        , BulletList
+            [ [ Plain [ Str "item" , Space , Str "c.a" ] ] ]
+        ]
+      ]
+  , Para
+      [ Str "or"
+      , Space
+      , Str "you"
+      , Space
+      , Str "can"
+      , Space
+      , Str "number"
+      , Space
+      , Str "them"
+      ]
+  , OrderedList
+      ( 1 , DefaultStyle , DefaultDelim )
+      [ [ Plain
+            [ Link ( "" , [] , [] ) [ Str "item 1" ] ( "item 1" , "" ) ]
+        ]
+      , [ Plain [ Str "item" , Space , Str "2" ] ]
+      , [ Plain
+            [ Emph
+                [ Space
+                , Str "italic"
+                , Space
+                , Str "item"
+                , Space
+                , Str "3"
+                , Space
+                ]
+            ]
+        , OrderedList
+            ( 1 , DefaultStyle , DefaultDelim )
+            [ [ Plain [ Str "item" , Space , Str "3.1" ] ]
+            , [ Plain [ Str "item" , Space , Str "3.2" ] ]
+            ]
+        ]
+      ]
+  , Para
+      [ Str "up"
+      , Space
+      , Str "to"
+      , Space
+      , Str "five"
+      , Space
+      , Str "levels"
+      ]
+  , BulletList
+      [ [ Plain [ Str "1" ]
+        , BulletList
+            [ [ Plain [ Str "2" ]
+              , BulletList
+                  [ [ Plain [ Str "3" ]
+                    , BulletList
+                        [ [ Plain [ Str "4" ]
+                          , BulletList [ [ Plain [ Str "5" ] ] ]
+                          ]
+                        ]
+                    ]
+                  ]
+              ]
+            ]
+        ]
+      ]
+  , BulletList
+      [ [ Plain
+            [ Str "You"
+            , Space
+            , Str "can"
+            , Space
+            , Str "have"
+            , Space
+            , Str "multiline"
+            , Space
+            , Str "list"
+            , Space
+            , Str "items"
+            ]
+        ]
+      , [ Plain
+            [ Str "this"
+            , Space
+            , Str "is"
+            , Space
+            , Str "a"
+            , Space
+            , Str "second"
+            , Space
+            , Str "multiline"
+            , Space
+            , Str "list"
+            , Space
+            , Str "item"
+            ]
+        ]
+      ]
+  , Para
+      [ Str "You"
+      , Space
+      , Str "can"
+      , Space
+      , Str "use"
+      , Space
+      , Str "nowiki"
+      , Space
+      , Str "syntax"
+      , Space
+      , Str "if"
+      , Space
+      , Str "you"
+      , Space
+      , Str "would"
+      , Space
+      , Str "like"
+      , Space
+      , Str "do"
+      , Space
+      , Str "stuff"
+      , Space
+      , Str "like"
+      , Space
+      , Str "this:"
+      ]
+  , CodeBlock
+      ( "" , [] , [] )
+      "Guitar Chord C:\n\n||---|---|---|\n||-0-|---|---|\n||---|---|---|\n||---|-0-|---|\n||---|---|-0-|\n||---|---|---|"
+  , Para
+      [ Str "You"
+      , Space
+      , Str "can"
+      , Space
+      , Str "also"
+      , Space
+      , Str "use"
+      , Space
+      , Str "it"
+      , Space
+      , Str "inline"
+      , Space
+      , Str "nowiki"
+      , Space
+      , Code ( "" , [] , [] ) " in a sentence "
+      , Space
+      , Str "like"
+      , Space
+      , Str "this."
+      ]
+  , Header 1 ( "" , [] , [] ) [ Str "Escapes" ]
+  , Para
+      [ Str "Normal"
+      , Space
+      , Str "Link:"
+      , Space
+      , Link
+          ( "" , [] , [] )
+          [ Str "http://wikicreole.org/" ]
+          ( "http://wikicreole.org/" , "" )
+      , Space
+      , Str "-"
+      , Space
+      , Str "now"
+      , Space
+      , Str "same"
+      , Space
+      , Str "link,"
+      , Space
+      , Str "but"
+      , Space
+      , Str "escaped:"
+      , Space
+      , Str "http://wikicreole.org/"
+      ]
+  , Para
+      [ Str "Normal"
+      , Space
+      , Str "asterisks:"
+      , Space
+      , Str "**not"
+      , Space
+      , Str "bold**"
+      ]
+  , Para
+      [ Str "a"
+      , Space
+      , Str "tilde"
+      , Space
+      , Str "alone:"
+      , Space
+      , Str "~"
+      ]
+  , Para
+      [ Str "a"
+      , Space
+      , Str "tilde"
+      , Space
+      , Str "escapes"
+      , Space
+      , Str "itself:"
+      , Space
+      , Str "~xxx"
+      ]
+  , Header 3 ( "" , [] , [] ) [ Str "Creole 0.2" ]
+  , Para
+      [ Str "This"
+      , Space
+      , Str "should"
+      , Space
+      , Str "be"
+      , Space
+      , Str "a"
+      , Space
+      , Str "flower"
+      , Space
+      , Str "with"
+      , Space
+      , Str "the"
+      , Space
+      , Str "ALT"
+      , Space
+      , Str "text"
+      , Space
+      , Str "\"this"
+      , Space
+      , Str "is"
+      , Space
+      , Str "a"
+      , Space
+      , Str "flower\""
+      , Space
+      , Str "if"
+      , Space
+      , Str "your"
+      , Space
+      , Str "wiki"
+      , Space
+      , Str "supports"
+      , Space
+      , Str "ALT"
+      , Space
+      , Str "text"
+      , Space
+      , Str "on"
+      , Space
+      , Str "images:"
+      ]
+  , Para
+      [ Image
+          ( "" , [] , [] )
+          [ Str "here is a red flower" ]
+          ( "Red-Flower.jpg" , "" )
+      ]
+  , Header 3 ( "" , [] , [] ) [ Str "Creole 0.4" ]
+  , Para
+      [ Str "Tables"
+      , Space
+      , Str "are"
+      , Space
+      , Str "done"
+      , Space
+      , Str "like"
+      , Space
+      , Str "this:"
+      ]
+  , Table
+      ( "" , [] , [] )
+      (Caption Nothing [])
+      [ ( AlignDefault , ColWidthDefault )
+      , ( AlignDefault , ColWidthDefault )
+      ]
+      (TableHead
+         ( "" , [] , [] )
+         [ Row
+             ( "" , [] , [] )
+             [ Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "header" , Space , Str "col1" ] ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "header" , Space , Str "col2" ] ]
+             ]
+         ])
+      [ TableBody
+          ( "" , [] , [] )
+          (RowHeadColumns 0)
+          []
+          [ Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "col1" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "col2" ] ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "you" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "can" ] ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "also" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "align" , LineBreak , Str "it." ] ]
+              ]
+          ]
+      ]
+      (TableFoot ( "" , [] , [] ) [])
+  , Para
+      [ Str "You"
+      , Space
+      , Str "can"
+      , Space
+      , Str "format"
+      , Space
+      , Str "an"
+      , Space
+      , Str "address"
+      , Space
+      , Str "by"
+      , Space
+      , Str "simply"
+      , Space
+      , Str "forcing"
+      , Space
+      , Str "linebreaks:"
+      ]
+  , Para
+      [ Str "My"
+      , Space
+      , Str "contact"
+      , Space
+      , Str "dates:"
+      , LineBreak
+      , Str "Pone:"
+      , Space
+      , Str "xyz"
+      , LineBreak
+      , Str "Fax:"
+      , Space
+      , Str "+45"
+      , LineBreak
+      , Str "Mobile:"
+      , Space
+      , Str "abc"
+      ]
+  , Header 3 ( "" , [] , [] ) [ Str "Creole 0.5" ]
+  , Table
+      ( "" , [] , [] )
+      (Caption Nothing [])
+      [ ( AlignDefault , ColWidthDefault )
+      , ( AlignDefault , ColWidthDefault )
+      ]
+      (TableHead
+         ( "" , [] , [] )
+         [ Row
+             ( "" , [] , [] )
+             [ Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "Header" , Space , Str "title" ] ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain
+                     [ Str "Another"
+                     , Space
+                     , Str "header"
+                     , Space
+                     , Str "title"
+                     ]
+                 ]
+             ]
+         ])
+      [ TableBody
+          ( "" , [] , [] )
+          (RowHeadColumns 0)
+          []
+          [ Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain
+                      [ Code ( "" , [] , [] ) " //not italic text// " ]
+                  ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain
+                      [ Code ( "" , [] , [] ) " **not bold text** " ]
+                  ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Emph [ Str "italic" , Space , Str "text" ] ]
+                  ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain
+                      [ Strong
+                          [ Space
+                          , Str "bold"
+                          , Space
+                          , Str "text"
+                          , Space
+                          ]
+                      ]
+                  ]
+              ]
+          ]
+      ]
+      (TableFoot ( "" , [] , [] ) [])
+  , Header 3 ( "" , [] , [] ) [ Str "Creole 1.0" ]
+  , Para
+      [ Str "If"
+      , Space
+      , Str "interwiki"
+      , Space
+      , Str "links"
+      , Space
+      , Str "are"
+      , Space
+      , Str "setup"
+      , Space
+      , Str "in"
+      , Space
+      , Str "your"
+      , Space
+      , Str "wiki,"
+      , Space
+      , Str "this"
+      , Space
+      , Str "links"
+      , Space
+      , Str "to"
+      , Space
+      , Str "the"
+      , Space
+      , Str "WikiCreole"
+      , Space
+      , Str "page"
+      , Space
+      , Str "about"
+      , Space
+      , Str "Creole"
+      , Space
+      , Str "1.0"
+      , Space
+      , Str "test"
+      , Space
+      , Str "cases:"
+      , Space
+      , Link
+          ( "" , [] , [] )
+          [ Str "WikiCreole:Creole1.0TestCases" ]
+          ( "WikiCreole:Creole1.0TestCases" , "" )
+      , Str "."
+      ]
+  , HorizontalRule
+  , Para
+      [ Str "The"
+      , Space
+      , Str "above"
+      , Space
+      , Str "test"
+      , Space
+      , Str "document"
+      , Space
+      , Str "was"
+      , Space
+      , Str "found"
+      , Space
+      , Str "on"
+      , Space
+      , Link
+          ( "" , [] , [] )
+          [ Str "http://www.wikicreole.org/wiki/Creole1.0TestCases" ]
+          ( "http://www.wikicreole.org/wiki/Creole1.0TestCases" , "" )
+      , Space
+      , Str "and"
+      , Space
+      , Str "downloaded"
+      , Space
+      , Str "from"
+      , Space
+      , Link
+          ( "" , [] , [] )
+          [ Str
+              "http://www.wikicreole.org/attach/Creole1.0TestCases/creole1.0test.txt"
+          ]
+          ( "http://www.wikicreole.org/attach/Creole1.0TestCases/creole1.0test.txt"
+          , ""
+          )
+      , Str "."
+      ]
+  , Para
+      [ Str "The"
+      , Space
+      , Str "Creole"
+      , Space
+      , Str "Wiki"
+      , Space
+      , Str "is"
+      , Space
+      , Str "licensed:"
+      , Space
+      , Str "Copyright"
+      , Space
+      , Str "(C)"
+      , Space
+      , Str "by"
+      , Space
+      , Str "the"
+      , Space
+      , Str "contributors."
+      , Space
+      , Str "Some"
+      , Space
+      , Str "rights"
+      , Space
+      , Str "reserved,"
+      , Space
+      , Str "license"
+      , Space
+      , Link
+          ( "" , [] , [] )
+          [ Str "https://creativecommons.org/licenses/by-sa/1.0/" ]
+          ( "BY-SA" , "" )
+      , Str "."
+      ]
+  ]
diff --git a/test/djot-reader.djot b/test/djot-reader.djot
new file mode 100644
--- /dev/null
+++ b/test/djot-reader.djot
@@ -0,0 +1,749 @@
+# Pandoc Test Suite
+
+John MacFarlane
+Anonymous
+
+July 17, 2006
+
+This is a set of tests for pandoc. Most of them are adapted from John Gruber's
+markdown test suite.
+
+* * * *
+
+{#headers}
+# Headers
+
+{#level-2-with-an-embedded-link}
+## Level 2 with an [embedded link](/url)
+
+{#level-3-with-emphasis}
+### Level 3 with _emphasis_
+
+{#level-4}
+#### Level 4
+
+{#level-5}
+##### Level 5
+
+{#level-1}
+# Level 1
+
+{#level-2-with-emphasis}
+## Level 2 with _emphasis_
+
+{#level-3}
+### Level 3
+
+with no blank line
+
+{#level-2}
+## Level 2
+
+with no blank line
+
+* * * *
+
+{#paragraphs}
+# Paragraphs
+
+Here's a regular paragraph.
+
+In Markdown 1.0.0 and earlier. Version 8. This line turns into a list item.
+Because a hard-wrapped line in the middle of a paragraph looked like a list
+item.
+
+Here's one with a bullet. \* criminey.
+
+There should be a hard line break\
+here.
+
+* * * *
+
+{#block-quotes}
+# Block Quotes
+
+E-mail style:
+
+> This is a block quote. It is pretty short.
+
+> Code in a block quote:
+>
+> ```
+> sub status {
+>     print "working";
+> }
+> ```
+>
+> A list:
+>
+> 1. item one
+> 2. item two
+>
+> Nested block quotes:
+>
+> > nested
+>
+> > nested
+
+This should not be a block quote: 2 \> 1.
+
+And a following paragraph.
+
+* * * *
+
+{#code-blocks}
+# Code Blocks
+
+Code:
+
+```
+---- (should be four hyphens)
+
+sub status {
+    print "working";
+}
+
+this code block is indented by one tab
+```
+
+And:
+
+```
+    this code block is indented by two tabs
+
+These should not be escaped:  \$ \\ \> \[ \{
+```
+
+* * * *
+
+{#lists}
+# Lists
+
+{#unordered}
+## Unordered
+
+Asterisks tight:
+
+- asterisk 1
+- asterisk 2
+- asterisk 3
+
+Asterisks loose:
+
+- asterisk 1
+
+- asterisk 2
+
+- asterisk 3
+
+Pluses tight:
+
+- Plus 1
+- Plus 2
+- Plus 3
+
+Pluses loose:
+
+- Plus 1
+
+- Plus 2
+
+- Plus 3
+
+Minuses tight:
+
+- Minus 1
+- Minus 2
+- Minus 3
+
+Minuses loose:
+
+- Minus 1
+
+- Minus 2
+
+- Minus 3
+
+{#ordered}
+## Ordered
+
+Tight:
+
+1. First
+2. Second
+3. Third
+
+and:
+
+1. One
+2. Two
+3. Three
+
+Loose using tabs:
+
+1. First
+
+2. Second
+
+3. Third
+
+and using spaces:
+
+1. One
+
+2. Two
+
+3. Three
+
+Multiple paragraphs:
+
+1. Item 1, graf one.
+
+   Item 1. graf two. The quick brown fox jumped over the lazy dog's back.
+
+2. Item 2.
+
+3. Item 3.
+
+{#nested}
+## Nested
+
+- Tab
+
+  - Tab
+
+    - Tab
+
+Here's another:
+
+1. First
+2. Second:
+
+   - Fee
+   - Fie
+   - Foe
+3. Third
+
+Same thing but with paragraphs:
+
+1. First
+
+2. Second:
+
+   - Fee
+   - Fie
+   - Foe
+
+3. Third
+
+{#tabs-and-spaces}
+## Tabs and spaces
+
+- this is a list item indented with tabs
+
+- this is a list item indented with spaces
+
+  - this is an example list item indented with tabs
+
+  - this is an example list item indented with spaces
+
+{#fancy-list-markers}
+## Fancy list markers
+
+(2) begins with 2
+
+(3) and now 3
+
+    with a continuation
+
+    iv. sublist with roman numerals, starting with 4
+    v. more items
+
+       (A) a subsublist
+       (B) a subsublist
+
+Nesting:
+
+A. Upper Alpha
+
+   I. Upper Roman.
+
+      (6) Decimal start with 6
+
+          c) Lower alpha with paren
+
+Autonumbering:
+
+1. Autonumber.
+2. More.
+
+   1. Nested.
+
+Should not be a list item:
+
+M.A. 2007
+
+B. Williams
+
+* * * *
+
+{#definition-lists}
+# Definition Lists
+
+Tight using spaces:
+
+: apple
+
+  red fruit
+: orange
+
+  orange fruit
+: banana
+
+  yellow fruit
+
+Tight using tabs:
+
+: apple
+
+  red fruit
+: orange
+
+  orange fruit
+: banana
+
+  yellow fruit
+
+Loose:
+
+: apple
+
+  red fruit
+
+: orange
+
+  orange fruit
+
+: banana
+
+  yellow fruit
+
+Multiple blocks with italics:
+
+: _apple_
+
+  red fruit
+
+  contains seeds, crisp, pleasant to taste
+
+: _orange_
+
+  orange fruit
+
+  ```
+  { orange code block }
+  ```
+
+  > orange block quote
+
+Multiple definitions, tight:
+
+: apple
+
+  red fruit
+
+  computer
+: orange
+
+  orange fruit
+
+  bank
+
+Multiple definitions, loose:
+
+: apple
+
+  red fruit
+
+  computer
+
+: orange
+
+  orange fruit
+
+  bank
+
+Blank line after term, indented marker, alternate markers:
+
+: apple
+
+  red fruit
+
+  computer
+
+: orange
+
+  orange fruit
+
+  1. sublist
+  2. sublist
+
+{#html-blocks}
+# HTML Blocks
+
+Simple block on one line:
+
+:::
+foo
+
+:::
+
+And nested without indentation:
+
+::::::
+::::
+:::
+foo
+
+:::
+
+::::
+
+:::
+bar
+
+:::
+
+::::::
+
+Interpreted markdown in a table:
+
+This is _emphasized_
+
+And this is *strong*
+
+Here's a simple block:
+
+:::
+foo
+
+:::
+
+This should be a code block, though:
+
+```
+<div>
+    foo
+</div>
+```
+
+As should this:
+
+```
+<div>foo</div>
+```
+
+Now, nested:
+
+:::::
+::::
+:::
+foo
+
+:::
+
+::::
+
+:::::
+
+This should just be an HTML comment:
+
+Multiline:
+
+Code block:
+
+```
+<!-- Comment -->
+```
+
+Just plain comment, with trailing spaces on the line:
+
+Code:
+
+```
+<hr />
+```
+
+Hr's:
+
+* * * *
+
+{#inline-markup}
+# Inline Markup
+
+This is _emphasized_, and so _is this_.
+
+This is *strong*, and so *is this*.
+
+An _[emphasized link](/url)_.
+
+*_This is strong and em._*
+
+So is *_this_* word.
+
+*_This is strong and em._*
+
+So is *_this_* word.
+
+This is code: `>`, `$`, `\`, `\$`, `<html>`.
+
+{-This is _strikeout_.-}
+
+Superscripts: a^bc^d a^_hello_^ a^hello there^.
+
+Subscripts: H~2~O, H~23~O, H~many of them~O.
+
+These should not be superscripts or subscripts, because of the unescaped spaces:
+a\^b c\^d, a\~b c\~d.
+
+* * * *
+
+{#smart-quotes-ellipses-dashes}
+# Smart quotes, ellipses, dashes
+
+"Hello," said the spider. "'Shelob' is my name."
+
+'A', 'B', and 'C' are letters.
+
+'Oak,' 'elm,' and 'beech' are names of trees. So is 'pine.'
+
+'He said, "I want to go."' Were you alive in the 70's?
+
+Here is some quoted '`code`' and a "[quoted
+link](http://example.com/?foo=1&bar=2)".
+
+Some dashes: one---two --- three---four --- five.
+
+Dashes between numbers: 5--7, 255--66, 1987--1999.
+
+Ellipses...and...and....
+
+* * * *
+
+{#latex}
+# LaTeX
+
+- 
+- $`2+2=4`
+- $`x \in y`
+- $`\alpha \wedge \omega`
+- $`223`
+- $`p`-Tree
+- Here's some display math:
+  $$`\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: $`\alpha + \omega \times x^2`.
+
+These shouldn't be math:
+
+- To get the famous equation, write `$e = mc^2$`.
+- $22,000 is a _lot_ of money. So is $34,000. (It worked if "lot" is
+  emphasized.)
+- Shoes ($20) and socks ($5).
+- Escaped `$`\: $73 _this should be emphasized_ 23$.
+
+Here's a LaTeX table:
+
+* * * *
+
+{#special-characters}
+# Special Characters
+
+Here is some unicode:
+
+- I hat: Î
+- o umlaut: ö
+- section: §
+- set membership: ∈
+- copyright: ©
+
+AT&T has an ampersand in their name.
+
+AT&T is another way to write it.
+
+This & that.
+
+4 \< 5.
+
+6 \> 5.
+
+Backslash: \\
+
+Backtick: \`
+
+Asterisk: \*
+
+Underscore: \_
+
+Left brace: \{
+
+Right brace: \}
+
+Left bracket: \[
+
+Right bracket: \]
+
+Left paren: (
+
+Right paren: )
+
+Greater-than: \>
+
+Hash: #
+
+Period: .
+
+Bang: \!
+
+Plus: +
+
+Minus: -
+
+* * * *
+
+{#links}
+# Links
+
+{#explicit}
+## Explicit
+
+Just a [URL](/url/).
+
+[URL and title](/url/){title="title"}.
+
+[URL and title](/url/){title="title preceded by two spaces"}.
+
+[URL and title](/url/){title="title preceded by a tab"}.
+
+[URL and title](/url/){title="title with \"quotes\" in it"}
+
+[URL and title](/url/){title="title with single quotes"}
+
+[with\_underscore](/url/with_underscore)
+
+[Email link](mailto:nobody@nowhere.net)
+
+[Empty]().
+
+{#reference}
+## Reference
+
+Foo [bar](/url/).
+
+With [embedded \[brackets\]](/url/).
+
+[b](/url/) by itself should be a link.
+
+Indented [once](/url).
+
+Indented [twice](/url).
+
+Indented [thrice](/url).
+
+This should \[not\]\[\] be a link.
+
+```
+[not]: /url
+```
+
+Foo [bar](/url/){title="Title with \"quotes\" inside"}.
+
+Foo [biz](/url/){title="Title with \"quote\" inside"}.
+
+{#with-ampersands}
+## With ampersands
+
+Here's a [link with an ampersand in the URL](http://example.com/?foo=1&bar=2).
+
+Here's a link with an amersand in the link text:
+[AT&T](http://att.com/){title="AT&T"}.
+
+Here's an [inline link](/script?foo=1&bar=2).
+
+Here's an [inline link in pointy braces](/script?foo=1&bar=2).
+
+{#autolinks}
+## Autolinks
+
+With an ampersand: <http://example.com/?foo=1&bar=2>
+
+- In a list?
+- <http://example.com/>
+- It should.
+
+An e-mail address: <nobody@nowhere.net>
+
+> Blockquoted: <http://example.com/>
+
+Auto-links should not occur here: `<http://example.com/>`
+
+```
+or here: <http://example.com/>
+```
+
+* * * *
+
+{#images}
+# Images
+
+From "Voyage dans la Lune" by Georges Melies (1902):
+
+::::
+![lalune](lalune.jpg){title="Voyage dans la Lune"}
+
+{.caption}
+:::
+lalune
+
+:::
+
+::::
+
+Here is a movie ![movie](movie.jpg) icon.
+
+* * * *
+
+{#footnotes}
+# Footnotes
+
+Here is a footnote reference,[^1] and another.[^2] This should _not_ be a
+footnote reference, because it contains a space.\[\^my note\] Here is an inline
+note.[^3]
+
+> Notes can go in quotes.[^4]
+
+1. And in list items.[^5]
+
+This paragraph should not be part of the note, as it is not indented.
+
+[^1]: Here is the footnote. It can go anywhere after the footnote reference. It
+    need not be placed at the end of the document.
+
+[^2]: Here's the long note. This one contains multiple blocks.
+
+    Subsequent blocks are indented to show that they belong to the footnote (as
+    with list items).
+
+    ```
+      { <code> }
+    ```
+
+    If you want, you can indent every line, but you can also be lazy and just
+    indent the first line of each block.
+
+[^3]: This is _easier_ to type. Inline notes may contain
+    [links](http://google.com) and `]` verbatim characters, as well as
+    \[bracketed text\].
+
+[^4]: In quote.
+
+[^5]: In list.
diff --git a/test/djot-reader.native b/test/djot-reader.native
new file mode 100644
--- /dev/null
+++ b/test/djot-reader.native
@@ -0,0 +1,2365 @@
+Pandoc
+  Meta { unMeta = fromList [] }
+  [ Div
+      ( "Pandoc-Test-Suite" , [ "section" ] , [] )
+      [ Header
+          1
+          ( "" , [] , [] )
+          [ Str "Pandoc" , Space , Str "Test" , Space , Str "Suite" ]
+      , Para
+          [ Str "John"
+          , Space
+          , Str "MacFarlane"
+          , SoftBreak
+          , Str "Anonymous"
+          ]
+      , Para
+          [ Str "July" , Space , Str "17," , Space , Str "2006" ]
+      , Para
+          [ Str "This"
+          , Space
+          , Str "is"
+          , Space
+          , Str "a"
+          , Space
+          , Str "set"
+          , Space
+          , Str "of"
+          , Space
+          , Str "tests"
+          , Space
+          , Str "for"
+          , Space
+          , Str "pandoc."
+          , Space
+          , Str "Most"
+          , Space
+          , Str "of"
+          , Space
+          , Str "them"
+          , Space
+          , Str "are"
+          , Space
+          , Str "adapted"
+          , Space
+          , Str "from"
+          , Space
+          , Str "John"
+          , Space
+          , Str "Gruber\8217s"
+          , SoftBreak
+          , Str "markdown"
+          , Space
+          , Str "test"
+          , Space
+          , Str "suite."
+          ]
+      , HorizontalRule
+      ]
+  , Div
+      ( "headers" , [ "section" ] , [] )
+      [ Header 1 ( "" , [] , [] ) [ Str "Headers" ]
+      , Div
+          ( "level-2-with-an-embedded-link" , [ "section" ] , [] )
+          [ Header
+              2
+              ( "" , [] , [] )
+              [ Str "Level"
+              , Space
+              , Str "2"
+              , Space
+              , Str "with"
+              , Space
+              , Str "an"
+              , Space
+              , Link
+                  ( "" , [] , [] )
+                  [ Str "embedded" , Space , Str "link" ]
+                  ( "/url" , "" )
+              ]
+          , Div
+              ( "level-3-with-emphasis" , [ "section" ] , [] )
+              [ Header
+                  3
+                  ( "" , [] , [] )
+                  [ Str "Level"
+                  , Space
+                  , Str "3"
+                  , Space
+                  , Str "with"
+                  , Space
+                  , Emph [ Str "emphasis" ]
+                  ]
+              , Div
+                  ( "level-4" , [ "section" ] , [] )
+                  [ Header
+                      4
+                      ( "" , [] , [] )
+                      [ Str "Level" , Space , Str "4" ]
+                  , Div
+                      ( "level-5" , [ "section" ] , [] )
+                      [ Header
+                          5
+                          ( "" , [] , [] )
+                          [ Str "Level" , Space , Str "5" ]
+                      ]
+                  ]
+              ]
+          ]
+      ]
+  , Div
+      ( "level-1" , [ "section" ] , [] )
+      [ Header
+          1 ( "" , [] , [] ) [ Str "Level" , Space , Str "1" ]
+      , Div
+          ( "level-2-with-emphasis" , [ "section" ] , [] )
+          [ Header
+              2
+              ( "" , [] , [] )
+              [ Str "Level"
+              , Space
+              , Str "2"
+              , Space
+              , Str "with"
+              , Space
+              , Emph [ Str "emphasis" ]
+              ]
+          , Div
+              ( "level-3" , [ "section" ] , [] )
+              [ Header
+                  3 ( "" , [] , [] ) [ Str "Level" , Space , Str "3" ]
+              , Para
+                  [ Str "with"
+                  , Space
+                  , Str "no"
+                  , Space
+                  , Str "blank"
+                  , Space
+                  , Str "line"
+                  ]
+              ]
+          ]
+      , Div
+          ( "level-2" , [ "section" ] , [] )
+          [ Header
+              2 ( "" , [] , [] ) [ Str "Level" , Space , Str "2" ]
+          , Para
+              [ Str "with"
+              , Space
+              , Str "no"
+              , Space
+              , Str "blank"
+              , Space
+              , Str "line"
+              ]
+          , HorizontalRule
+          ]
+      ]
+  , Div
+      ( "paragraphs" , [ "section" ] , [] )
+      [ Header 1 ( "" , [] , [] ) [ Str "Paragraphs" ]
+      , Para
+          [ Str "Here\8217s"
+          , Space
+          , Str "a"
+          , Space
+          , Str "regular"
+          , Space
+          , Str "paragraph."
+          ]
+      , Para
+          [ Str "In"
+          , Space
+          , Str "Markdown"
+          , Space
+          , Str "1.0.0"
+          , Space
+          , Str "and"
+          , Space
+          , Str "earlier."
+          , Space
+          , Str "Version"
+          , Space
+          , Str "8."
+          , Space
+          , Str "This"
+          , Space
+          , Str "line"
+          , Space
+          , Str "turns"
+          , Space
+          , Str "into"
+          , Space
+          , Str "a"
+          , Space
+          , Str "list"
+          , Space
+          , Str "item."
+          , SoftBreak
+          , Str "Because"
+          , Space
+          , Str "a"
+          , Space
+          , Str "hard-wrapped"
+          , Space
+          , Str "line"
+          , Space
+          , Str "in"
+          , Space
+          , Str "the"
+          , Space
+          , Str "middle"
+          , Space
+          , Str "of"
+          , Space
+          , Str "a"
+          , Space
+          , Str "paragraph"
+          , Space
+          , Str "looked"
+          , Space
+          , Str "like"
+          , Space
+          , Str "a"
+          , Space
+          , Str "list"
+          , SoftBreak
+          , Str "item."
+          ]
+      , Para
+          [ Str "Here\8217s"
+          , Space
+          , Str "one"
+          , Space
+          , Str "with"
+          , Space
+          , Str "a"
+          , Space
+          , Str "bullet."
+          , Space
+          , Str "*"
+          , Space
+          , Str "criminey."
+          ]
+      , Para
+          [ Str "There"
+          , Space
+          , Str "should"
+          , Space
+          , Str "be"
+          , Space
+          , Str "a"
+          , Space
+          , Str "hard"
+          , Space
+          , Str "line"
+          , Space
+          , Str "break"
+          , LineBreak
+          , Str "here."
+          ]
+      , HorizontalRule
+      ]
+  , Div
+      ( "block-quotes" , [ "section" ] , [] )
+      [ Header
+          1 ( "" , [] , [] ) [ Str "Block" , Space , Str "Quotes" ]
+      , Para [ Str "E-mail" , Space , Str "style:" ]
+      , BlockQuote
+          [ Para
+              [ Str "This"
+              , Space
+              , Str "is"
+              , Space
+              , Str "a"
+              , Space
+              , Str "block"
+              , Space
+              , Str "quote."
+              , Space
+              , Str "It"
+              , Space
+              , Str "is"
+              , Space
+              , Str "pretty"
+              , Space
+              , Str "short."
+              ]
+          ]
+      , BlockQuote
+          [ Para
+              [ Str "Code"
+              , Space
+              , Str "in"
+              , Space
+              , Str "a"
+              , Space
+              , Str "block"
+              , Space
+              , Str "quote:"
+              ]
+          , CodeBlock
+              ( "" , [ "" ] , [] )
+              "sub status {\n    print \"working\";\n}\n"
+          , Para [ Str "A" , Space , Str "list:" ]
+          , OrderedList
+              ( 1 , Decimal , Period )
+              [ [ Plain [ Str "item" , Space , Str "one" ] ]
+              , [ Plain [ Str "item" , Space , Str "two" ] ]
+              ]
+          , Para
+              [ Str "Nested"
+              , Space
+              , Str "block"
+              , Space
+              , Str "quotes:"
+              ]
+          , BlockQuote [ Para [ Str "nested" ] ]
+          , BlockQuote [ Para [ Str "nested" ] ]
+          ]
+      , Para
+          [ Str "This"
+          , Space
+          , Str "should"
+          , Space
+          , Str "not"
+          , Space
+          , Str "be"
+          , Space
+          , Str "a"
+          , Space
+          , Str "block"
+          , Space
+          , Str "quote:"
+          , Space
+          , Str "2"
+          , Space
+          , Str ">"
+          , Space
+          , Str "1."
+          ]
+      , Para
+          [ Str "And"
+          , Space
+          , Str "a"
+          , Space
+          , Str "following"
+          , Space
+          , Str "paragraph."
+          ]
+      , HorizontalRule
+      ]
+  , Div
+      ( "code-blocks" , [ "section" ] , [] )
+      [ Header
+          1 ( "" , [] , [] ) [ Str "Code" , Space , Str "Blocks" ]
+      , Para [ Str "Code:" ]
+      , CodeBlock
+          ( "" , [ "" ] , [] )
+          "---- (should be four hyphens)\n\nsub status {\n    print \"working\";\n}\n\nthis code block is indented by one tab\n"
+      , Para [ Str "And:" ]
+      , CodeBlock
+          ( "" , [ "" ] , [] )
+          "    this code block is indented by two tabs\n\nThese should not be escaped:  \\$ \\\\ \\> \\[ \\{\n"
+      , HorizontalRule
+      ]
+  , Div
+      ( "lists" , [ "section" ] , [] )
+      [ Header 1 ( "" , [] , [] ) [ Str "Lists" ]
+      , Div
+          ( "unordered" , [ "section" ] , [] )
+          [ Header 2 ( "" , [] , [] ) [ Str "Unordered" ]
+          , Para [ Str "Asterisks" , Space , Str "tight:" ]
+          , BulletList
+              [ [ Plain [ Str "asterisk" , Space , Str "1" ] ]
+              , [ Plain [ Str "asterisk" , Space , Str "2" ] ]
+              , [ Plain [ Str "asterisk" , Space , Str "3" ] ]
+              ]
+          , Para [ Str "Asterisks" , Space , Str "loose:" ]
+          , BulletList
+              [ [ Para [ Str "asterisk" , Space , Str "1" ] ]
+              , [ Para [ Str "asterisk" , Space , Str "2" ] ]
+              , [ Para [ Str "asterisk" , Space , Str "3" ] ]
+              ]
+          , Para [ Str "Pluses" , Space , Str "tight:" ]
+          , BulletList
+              [ [ Plain [ Str "Plus" , Space , Str "1" ] ]
+              , [ Plain [ Str "Plus" , Space , Str "2" ] ]
+              , [ Plain [ Str "Plus" , Space , Str "3" ] ]
+              ]
+          , Para [ Str "Pluses" , Space , Str "loose:" ]
+          , BulletList
+              [ [ Para [ Str "Plus" , Space , Str "1" ] ]
+              , [ Para [ Str "Plus" , Space , Str "2" ] ]
+              , [ Para [ Str "Plus" , Space , Str "3" ] ]
+              ]
+          , Para [ Str "Minuses" , Space , Str "tight:" ]
+          , BulletList
+              [ [ Plain [ Str "Minus" , Space , Str "1" ] ]
+              , [ Plain [ Str "Minus" , Space , Str "2" ] ]
+              , [ Plain [ Str "Minus" , Space , Str "3" ] ]
+              ]
+          , Para [ Str "Minuses" , Space , Str "loose:" ]
+          , BulletList
+              [ [ Para [ Str "Minus" , Space , Str "1" ] ]
+              , [ Para [ Str "Minus" , Space , Str "2" ] ]
+              , [ Para [ Str "Minus" , Space , Str "3" ] ]
+              ]
+          ]
+      , Div
+          ( "ordered" , [ "section" ] , [] )
+          [ Header 2 ( "" , [] , [] ) [ Str "Ordered" ]
+          , Para [ Str "Tight:" ]
+          , OrderedList
+              ( 1 , Decimal , Period )
+              [ [ Plain [ Str "First" ] ]
+              , [ Plain [ Str "Second" ] ]
+              , [ Plain [ Str "Third" ] ]
+              ]
+          , Para [ Str "and:" ]
+          , OrderedList
+              ( 1 , Decimal , Period )
+              [ [ Plain [ Str "One" ] ]
+              , [ Plain [ Str "Two" ] ]
+              , [ Plain [ Str "Three" ] ]
+              ]
+          , Para
+              [ Str "Loose"
+              , Space
+              , Str "using"
+              , Space
+              , Str "tabs:"
+              ]
+          , OrderedList
+              ( 1 , Decimal , Period )
+              [ [ Para [ Str "First" ] ]
+              , [ Para [ Str "Second" ] ]
+              , [ Para [ Str "Third" ] ]
+              ]
+          , Para
+              [ Str "and"
+              , Space
+              , Str "using"
+              , Space
+              , Str "spaces:"
+              ]
+          , OrderedList
+              ( 1 , Decimal , Period )
+              [ [ Para [ Str "One" ] ]
+              , [ Para [ Str "Two" ] ]
+              , [ Para [ Str "Three" ] ]
+              ]
+          , Para [ Str "Multiple" , Space , Str "paragraphs:" ]
+          , 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"
+                    , Space
+                    , Str "back."
+                    ]
+                ]
+              , [ Para [ Str "Item" , Space , Str "2." ] ]
+              , [ Para [ Str "Item" , Space , Str "3." ] ]
+              ]
+          ]
+      , Div
+          ( "nested" , [ "section" ] , [] )
+          [ Header 2 ( "" , [] , [] ) [ Str "Nested" ]
+          , BulletList
+              [ [ Plain [ Str "Tab" ]
+                , BulletList
+                    [ [ Plain [ Str "Tab" ]
+                      , BulletList [ [ Plain [ Str "Tab" ] ] ]
+                      ]
+                    ]
+                ]
+              ]
+          , Para [ Str "Here\8217s" , Space , Str "another:" ]
+          , OrderedList
+              ( 1 , Decimal , Period )
+              [ [ Plain [ Str "First" ] ]
+              , [ Plain [ Str "Second:" ]
+                , BulletList
+                    [ [ Plain [ Str "Fee" ] ]
+                    , [ Plain [ Str "Fie" ] ]
+                    , [ Plain [ Str "Foe" ] ]
+                    ]
+                ]
+              , [ Plain [ Str "Third" ] ]
+              ]
+          , Para
+              [ Str "Same"
+              , Space
+              , Str "thing"
+              , Space
+              , Str "but"
+              , Space
+              , Str "with"
+              , Space
+              , Str "paragraphs:"
+              ]
+          , OrderedList
+              ( 1 , Decimal , Period )
+              [ [ Para [ Str "First" ] ]
+              , [ Para [ Str "Second:" ]
+                , BulletList
+                    [ [ Plain [ Str "Fee" ] ]
+                    , [ Plain [ Str "Fie" ] ]
+                    , [ Plain [ Str "Foe" ] ]
+                    ]
+                ]
+              , [ Para [ Str "Third" ] ]
+              ]
+          ]
+      , Div
+          ( "tabs-and-spaces" , [ "section" ] , [] )
+          [ Header
+              2
+              ( "" , [] , [] )
+              [ Str "Tabs" , Space , Str "and" , Space , Str "spaces" ]
+          , BulletList
+              [ [ Para
+                    [ Str "this"
+                    , Space
+                    , Str "is"
+                    , Space
+                    , Str "a"
+                    , Space
+                    , Str "list"
+                    , Space
+                    , Str "item"
+                    , Space
+                    , Str "indented"
+                    , Space
+                    , Str "with"
+                    , Space
+                    , Str "tabs"
+                    ]
+                ]
+              , [ Para
+                    [ Str "this"
+                    , Space
+                    , Str "is"
+                    , Space
+                    , Str "a"
+                    , Space
+                    , Str "list"
+                    , Space
+                    , Str "item"
+                    , Space
+                    , Str "indented"
+                    , Space
+                    , Str "with"
+                    , Space
+                    , Str "spaces"
+                    ]
+                , BulletList
+                    [ [ Para
+                          [ Str "this"
+                          , Space
+                          , Str "is"
+                          , Space
+                          , Str "an"
+                          , Space
+                          , Str "example"
+                          , Space
+                          , Str "list"
+                          , Space
+                          , Str "item"
+                          , Space
+                          , Str "indented"
+                          , Space
+                          , Str "with"
+                          , Space
+                          , Str "tabs"
+                          ]
+                      ]
+                    , [ Para
+                          [ Str "this"
+                          , Space
+                          , Str "is"
+                          , Space
+                          , Str "an"
+                          , Space
+                          , Str "example"
+                          , Space
+                          , Str "list"
+                          , Space
+                          , Str "item"
+                          , Space
+                          , Str "indented"
+                          , Space
+                          , Str "with"
+                          , Space
+                          , Str "spaces"
+                          ]
+                      ]
+                    ]
+                ]
+              ]
+          ]
+      , Div
+          ( "fancy-list-markers" , [ "section" ] , [] )
+          [ Header
+              2
+              ( "" , [] , [] )
+              [ Str "Fancy"
+              , Space
+              , Str "list"
+              , Space
+              , Str "markers"
+              ]
+          , OrderedList
+              ( 2 , Decimal , TwoParens )
+              [ [ 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 )
+                    [ [ Plain
+                          [ Str "sublist"
+                          , Space
+                          , Str "with"
+                          , Space
+                          , Str "roman"
+                          , Space
+                          , Str "numerals,"
+                          , Space
+                          , Str "starting"
+                          , Space
+                          , Str "with"
+                          , Space
+                          , Str "4"
+                          ]
+                      ]
+                    , [ Plain [ Str "more" , Space , Str "items" ]
+                      , OrderedList
+                          ( 1 , UpperAlpha , TwoParens )
+                          [ [ Plain
+                                [ Str "a" , Space , Str "subsublist" ]
+                            ]
+                          , [ Plain
+                                [ Str "a" , Space , Str "subsublist" ]
+                            ]
+                          ]
+                      ]
+                    ]
+                ]
+              ]
+          , Para [ Str "Nesting:" ]
+          , OrderedList
+              ( 1 , UpperAlpha , Period )
+              [ [ Plain [ Str "Upper" , Space , Str "Alpha" ]
+                , OrderedList
+                    ( 1 , UpperRoman , Period )
+                    [ [ Plain [ Str "Upper" , Space , Str "Roman." ]
+                      , OrderedList
+                          ( 6 , Decimal , TwoParens )
+                          [ [ Plain
+                                [ Str "Decimal"
+                                , Space
+                                , Str "start"
+                                , Space
+                                , Str "with"
+                                , Space
+                                , Str "6"
+                                ]
+                            , OrderedList
+                                ( 3 , LowerAlpha , OneParen )
+                                [ [ Plain
+                                      [ Str "Lower"
+                                      , Space
+                                      , Str "alpha"
+                                      , Space
+                                      , Str "with"
+                                      , Space
+                                      , Str "paren"
+                                      ]
+                                  ]
+                                ]
+                            ]
+                          ]
+                      ]
+                    ]
+                ]
+              ]
+          , Para [ Str "Autonumbering:" ]
+          , OrderedList
+              ( 1 , Decimal , Period )
+              [ [ Plain [ Str "Autonumber." ] ]
+              , [ Plain [ Str "More." ]
+                , OrderedList
+                    ( 1 , Decimal , Period )
+                    [ [ Plain [ Str "Nested." ] ] ]
+                ]
+              ]
+          , Para
+              [ Str "Should"
+              , Space
+              , Str "not"
+              , Space
+              , Str "be"
+              , Space
+              , Str "a"
+              , Space
+              , Str "list"
+              , Space
+              , Str "item:"
+              ]
+          , Para [ Str "M.A.\160\&2007" ]
+          , OrderedList
+              ( 2 , UpperAlpha , Period )
+              [ [ Plain [ Str "Williams" ] ] ]
+          , HorizontalRule
+          ]
+      ]
+  , Div
+      ( "definition-lists" , [ "section" ] , [] )
+      [ Header
+          1
+          ( "" , [] , [] )
+          [ Str "Definition" , Space , Str "Lists" ]
+      , Para
+          [ Str "Tight"
+          , Space
+          , Str "using"
+          , Space
+          , Str "spaces:"
+          ]
+      , DefinitionList
+          [ ( [ Str "apple" ]
+            , [ [ Plain [ Str "red" , Space , Str "fruit" ] ] ]
+            )
+          , ( [ Str "orange" ]
+            , [ [ Plain [ Str "orange" , Space , Str "fruit" ] ] ]
+            )
+          , ( [ Str "banana" ]
+            , [ [ Plain [ Str "yellow" , Space , Str "fruit" ] ] ]
+            )
+          ]
+      , Para
+          [ Str "Tight" , Space , Str "using" , Space , Str "tabs:" ]
+      , DefinitionList
+          [ ( [ Str "apple" ]
+            , [ [ Plain [ Str "red" , Space , Str "fruit" ] ] ]
+            )
+          , ( [ Str "orange" ]
+            , [ [ Plain [ Str "orange" , Space , Str "fruit" ] ] ]
+            )
+          , ( [ Str "banana" ]
+            , [ [ Plain [ Str "yellow" , Space , Str "fruit" ] ] ]
+            )
+          ]
+      , Para [ Str "Loose:" ]
+      , DefinitionList
+          [ ( [ Str "apple" ]
+            , [ [ Para [ Str "red" , Space , Str "fruit" ] ] ]
+            )
+          , ( [ Str "orange" ]
+            , [ [ Para [ Str "orange" , Space , Str "fruit" ] ] ]
+            )
+          , ( [ Str "banana" ]
+            , [ [ Para [ Str "yellow" , Space , Str "fruit" ] ] ]
+            )
+          ]
+      , Para
+          [ Str "Multiple"
+          , Space
+          , Str "blocks"
+          , Space
+          , Str "with"
+          , Space
+          , Str "italics:"
+          ]
+      , DefinitionList
+          [ ( [ Emph [ Str "apple" ] ]
+            , [ [ Para [ Str "red" , Space , Str "fruit" ]
+                , Para
+                    [ Str "contains"
+                    , Space
+                    , Str "seeds,"
+                    , Space
+                    , Str "crisp,"
+                    , Space
+                    , Str "pleasant"
+                    , Space
+                    , Str "to"
+                    , Space
+                    , Str "taste"
+                    ]
+                ]
+              ]
+            )
+          , ( [ Emph [ Str "orange" ] ]
+            , [ [ Para [ Str "orange" , Space , Str "fruit" ]
+                , CodeBlock
+                    ( "" , [ "" ] , [] ) "{ orange code block }\n"
+                , BlockQuote
+                    [ Para
+                        [ Str "orange"
+                        , Space
+                        , Str "block"
+                        , Space
+                        , Str "quote"
+                        ]
+                    ]
+                ]
+              ]
+            )
+          ]
+      , Para
+          [ Str "Multiple"
+          , Space
+          , Str "definitions,"
+          , Space
+          , Str "tight:"
+          ]
+      , DefinitionList
+          [ ( [ Str "apple" ]
+            , [ [ Para [ Str "red" , Space , Str "fruit" ]
+                , Para [ Str "computer" ]
+                ]
+              ]
+            )
+          , ( [ Str "orange" ]
+            , [ [ Para [ Str "orange" , Space , Str "fruit" ]
+                , Para [ Str "bank" ]
+                ]
+              ]
+            )
+          ]
+      , Para
+          [ Str "Multiple"
+          , Space
+          , Str "definitions,"
+          , Space
+          , Str "loose:"
+          ]
+      , DefinitionList
+          [ ( [ Str "apple" ]
+            , [ [ Para [ Str "red" , Space , Str "fruit" ]
+                , Para [ Str "computer" ]
+                ]
+              ]
+            )
+          , ( [ Str "orange" ]
+            , [ [ Para [ Str "orange" , Space , Str "fruit" ]
+                , Para [ Str "bank" ]
+                ]
+              ]
+            )
+          ]
+      , Para
+          [ Str "Blank"
+          , Space
+          , Str "line"
+          , Space
+          , Str "after"
+          , Space
+          , Str "term,"
+          , Space
+          , Str "indented"
+          , Space
+          , Str "marker,"
+          , Space
+          , Str "alternate"
+          , Space
+          , Str "markers:"
+          ]
+      , DefinitionList
+          [ ( [ Str "apple" ]
+            , [ [ Para [ Str "red" , Space , Str "fruit" ]
+                , Para [ Str "computer" ]
+                ]
+              ]
+            )
+          , ( [ Str "orange" ]
+            , [ [ Para [ Str "orange" , Space , Str "fruit" ]
+                , OrderedList
+                    ( 1 , Decimal , Period )
+                    [ [ Plain [ Str "sublist" ] ]
+                    , [ Plain [ Str "sublist" ] ]
+                    ]
+                ]
+              ]
+            )
+          ]
+      ]
+  , Div
+      ( "html-blocks" , [ "section" ] , [] )
+      [ Header
+          1 ( "" , [] , [] ) [ Str "HTML" , Space , Str "Blocks" ]
+      , Para
+          [ Str "Simple"
+          , Space
+          , Str "block"
+          , Space
+          , Str "on"
+          , Space
+          , Str "one"
+          , Space
+          , Str "line:"
+          ]
+      , Div ( "" , [] , [] ) [ Para [ Str "foo" ] ]
+      , Para
+          [ Str "And"
+          , Space
+          , Str "nested"
+          , Space
+          , Str "without"
+          , Space
+          , Str "indentation:"
+          ]
+      , Div
+          ( "" , [] , [] )
+          [ Div
+              ( "" , [] , [] )
+              [ Div ( "" , [] , [] ) [ Para [ Str "foo" ] ] ]
+          , Div ( "" , [] , [] ) [ Para [ Str "bar" ] ]
+          ]
+      , Para
+          [ Str "Interpreted"
+          , Space
+          , Str "markdown"
+          , Space
+          , Str "in"
+          , Space
+          , Str "a"
+          , Space
+          , Str "table:"
+          ]
+      , Para
+          [ Str "This"
+          , Space
+          , Str "is"
+          , Space
+          , Emph [ Str "emphasized" ]
+          ]
+      , Para
+          [ Str "And"
+          , Space
+          , Str "this"
+          , Space
+          , Str "is"
+          , Space
+          , Strong [ Str "strong" ]
+          ]
+      , Para
+          [ Str "Here\8217s"
+          , Space
+          , Str "a"
+          , Space
+          , Str "simple"
+          , Space
+          , Str "block:"
+          ]
+      , Div ( "" , [] , [] ) [ Para [ Str "foo" ] ]
+      , Para
+          [ Str "This"
+          , Space
+          , Str "should"
+          , Space
+          , Str "be"
+          , Space
+          , Str "a"
+          , Space
+          , Str "code"
+          , Space
+          , Str "block,"
+          , Space
+          , Str "though:"
+          ]
+      , CodeBlock ( "" , [ "" ] , [] ) "<div>\n    foo\n</div>\n"
+      , Para
+          [ Str "As" , Space , Str "should" , Space , Str "this:" ]
+      , CodeBlock ( "" , [ "" ] , [] ) "<div>foo</div>\n"
+      , Para [ Str "Now," , Space , Str "nested:" ]
+      , Div
+          ( "" , [] , [] )
+          [ Div
+              ( "" , [] , [] )
+              [ Div ( "" , [] , [] ) [ Para [ Str "foo" ] ] ]
+          ]
+      , Para
+          [ Str "This"
+          , Space
+          , Str "should"
+          , Space
+          , Str "just"
+          , Space
+          , Str "be"
+          , Space
+          , Str "an"
+          , Space
+          , Str "HTML"
+          , Space
+          , Str "comment:"
+          ]
+      , Para [ Str "Multiline:" ]
+      , Para [ Str "Code" , Space , Str "block:" ]
+      , CodeBlock ( "" , [ "" ] , [] ) "<!-- Comment -->\n"
+      , Para
+          [ Str "Just"
+          , Space
+          , Str "plain"
+          , Space
+          , Str "comment,"
+          , Space
+          , Str "with"
+          , Space
+          , Str "trailing"
+          , Space
+          , Str "spaces"
+          , Space
+          , Str "on"
+          , Space
+          , Str "the"
+          , Space
+          , Str "line:"
+          ]
+      , Para [ Str "Code:" ]
+      , CodeBlock ( "" , [ "" ] , [] ) "<hr />\n"
+      , Para [ Str "Hr\8217s:" ]
+      , HorizontalRule
+      ]
+  , Div
+      ( "inline-markup" , [ "section" ] , [] )
+      [ Header
+          1 ( "" , [] , [] ) [ Str "Inline" , Space , Str "Markup" ]
+      , Para
+          [ Str "This"
+          , Space
+          , Str "is"
+          , Space
+          , Emph [ Str "emphasized" ]
+          , Str ","
+          , Space
+          , Str "and"
+          , Space
+          , Str "so"
+          , Space
+          , Emph [ Str "is" , Space , Str "this" ]
+          , Str "."
+          ]
+      , Para
+          [ Str "This"
+          , Space
+          , Str "is"
+          , Space
+          , Strong [ Str "strong" ]
+          , Str ","
+          , Space
+          , Str "and"
+          , Space
+          , Str "so"
+          , Space
+          , Strong [ Str "is" , Space , Str "this" ]
+          , Str "."
+          ]
+      , Para
+          [ Str "An"
+          , Space
+          , Emph
+              [ Link
+                  ( "" , [] , [] )
+                  [ Str "emphasized" , Space , Str "link" ]
+                  ( "/url" , "" )
+              ]
+          , Str "."
+          ]
+      , Para
+          [ Strong
+              [ Emph
+                  [ Str "This"
+                  , Space
+                  , Str "is"
+                  , Space
+                  , Str "strong"
+                  , Space
+                  , Str "and"
+                  , Space
+                  , Str "em."
+                  ]
+              ]
+          ]
+      , Para
+          [ Str "So"
+          , Space
+          , Str "is"
+          , Space
+          , Strong [ Emph [ Str "this" ] ]
+          , Space
+          , Str "word."
+          ]
+      , Para
+          [ Strong
+              [ Emph
+                  [ Str "This"
+                  , Space
+                  , Str "is"
+                  , Space
+                  , Str "strong"
+                  , Space
+                  , Str "and"
+                  , Space
+                  , Str "em."
+                  ]
+              ]
+          ]
+      , Para
+          [ Str "So"
+          , Space
+          , Str "is"
+          , Space
+          , Strong [ Emph [ Str "this" ] ]
+          , Space
+          , Str "word."
+          ]
+      , Para
+          [ Str "This"
+          , Space
+          , Str "is"
+          , Space
+          , Str "code:"
+          , Space
+          , Code ( "" , [] , [] ) ">"
+          , Str ","
+          , Space
+          , Code ( "" , [] , [] ) "$"
+          , Str ","
+          , Space
+          , Code ( "" , [] , [] ) "\\`, "
+          , Str "$"
+          , Code ( "" , [] , [] ) ", "
+          , Str "<html>"
+          , Code ( "" , [] , [] ) "."
+          ]
+      , Para
+          [ Span
+              ( "" , [ "deleted" ] , [] )
+              [ Str "This"
+              , Space
+              , Str "is"
+              , Space
+              , Emph [ Str "strikeout" ]
+              , Str "."
+              ]
+          ]
+      , Para
+          [ Str "Superscripts:"
+          , Space
+          , Str "a"
+          , Superscript [ Str "bc" ]
+          , Str "d"
+          , Space
+          , Str "a"
+          , Superscript [ Emph [ Str "hello" ] ]
+          , Space
+          , Str "a"
+          , Superscript [ Str "hello\160there" ]
+          , Str "."
+          ]
+      , Para
+          [ Str "Subscripts:"
+          , Space
+          , Str "H"
+          , Subscript [ Str "2" ]
+          , Str "O,"
+          , Space
+          , Str "H"
+          , Subscript [ Str "23" ]
+          , Str "O,"
+          , Space
+          , Str "H"
+          , Subscript [ Str "many\160of\160them" ]
+          , Str "O."
+          ]
+      , Para
+          [ Str "These"
+          , Space
+          , Str "should"
+          , Space
+          , Str "not"
+          , Space
+          , Str "be"
+          , Space
+          , Str "superscripts"
+          , Space
+          , Str "or"
+          , Space
+          , Str "subscripts,"
+          , Space
+          , Str "because"
+          , Space
+          , Str "of"
+          , Space
+          , Str "the"
+          , Space
+          , Str "unescaped"
+          , Space
+          , Str "spaces:"
+          , SoftBreak
+          , Str "a^b"
+          , Space
+          , Str "c^d,"
+          , Space
+          , Str "a~b"
+          , Space
+          , Str "c~d."
+          ]
+      , HorizontalRule
+      ]
+  , Div
+      ( "smart-quotes-ellipses-dashes" , [ "section" ] , [] )
+      [ Header
+          1
+          ( "" , [] , [] )
+          [ Str "Smart"
+          , Space
+          , Str "quotes,"
+          , Space
+          , Str "ellipses,"
+          , Space
+          , Str "dashes"
+          ]
+      , Para
+          [ Quoted DoubleQuote [ Str "Hello," ]
+          , Space
+          , Str "said"
+          , Space
+          , Str "the"
+          , Space
+          , Str "spider."
+          , Space
+          , Quoted
+              DoubleQuote
+              [ Quoted SingleQuote [ Str "Shelob" ]
+              , Space
+              , Str "is"
+              , Space
+              , Str "my"
+              , Space
+              , Str "name."
+              ]
+          ]
+      , Para
+          [ Quoted SingleQuote [ Str "A" ]
+          , Str ","
+          , Space
+          , Quoted SingleQuote [ Str "B" ]
+          , Str ","
+          , Space
+          , Str "and"
+          , Space
+          , Quoted SingleQuote [ Str "C" ]
+          , Space
+          , Str "are"
+          , Space
+          , Str "letters."
+          ]
+      , Para
+          [ Quoted SingleQuote [ Str "Oak," ]
+          , Space
+          , Quoted SingleQuote [ Str "elm," ]
+          , Space
+          , Str "and"
+          , Space
+          , Quoted SingleQuote [ Str "beech" ]
+          , Space
+          , Str "are"
+          , Space
+          , Str "names"
+          , Space
+          , Str "of"
+          , Space
+          , Str "trees."
+          , Space
+          , Str "So"
+          , Space
+          , Str "is"
+          , Space
+          , Quoted SingleQuote [ Str "pine." ]
+          ]
+      , Para
+          [ Quoted
+              SingleQuote
+              [ Str "He"
+              , Space
+              , Str "said,"
+              , Space
+              , Quoted
+                  DoubleQuote
+                  [ Str "I"
+                  , Space
+                  , Str "want"
+                  , Space
+                  , Str "to"
+                  , Space
+                  , Str "go."
+                  ]
+              ]
+          , Space
+          , Str "Were"
+          , Space
+          , Str "you"
+          , Space
+          , Str "alive"
+          , Space
+          , Str "in"
+          , Space
+          , Str "the"
+          , Space
+          , Str "70\8217s?"
+          ]
+      , Para
+          [ Str "Here"
+          , Space
+          , Str "is"
+          , Space
+          , Str "some"
+          , Space
+          , Str "quoted"
+          , Space
+          , Quoted SingleQuote [ Code ( "" , [] , [] ) "code" ]
+          , Space
+          , Str "and"
+          , Space
+          , Str "a"
+          , Space
+          , Quoted
+              DoubleQuote
+              [ Link
+                  ( "" , [] , [] )
+                  [ Str "quoted" , SoftBreak , Str "link" ]
+                  ( "http://example.com/?foo=1&bar=2" , "" )
+              ]
+          , Str "."
+          ]
+      , Para
+          [ Str "Some"
+          , Space
+          , Str "dashes:"
+          , Space
+          , Str "one\8212two"
+          , Space
+          , Str "\8212"
+          , Space
+          , Str "three\8212four"
+          , Space
+          , Str "\8212"
+          , Space
+          , Str "five."
+          ]
+      , Para
+          [ Str "Dashes"
+          , Space
+          , Str "between"
+          , Space
+          , Str "numbers:"
+          , Space
+          , Str "5\8211\&7,"
+          , Space
+          , Str "255\8211\&66,"
+          , Space
+          , Str "1987\8211\&1999."
+          ]
+      , Para [ Str "Ellipses\8230and\8230and\8230." ]
+      , HorizontalRule
+      ]
+  , Div
+      ( "latex" , [ "section" ] , [] )
+      [ Header 1 ( "" , [] , [] ) [ Str "LaTeX" ]
+      , BulletList
+          [ []
+          , [ Plain [ Math InlineMath "2+2=4" ] ]
+          , [ Plain [ Math InlineMath "x \\in y" ] ]
+          , [ Plain [ Math InlineMath "\\alpha \\wedge \\omega" ] ]
+          , [ Plain [ Math InlineMath "223" ] ]
+          , [ Plain [ Math InlineMath "p" , Str "-Tree" ] ]
+          , [ Plain
+                [ Str "Here\8217s"
+                , Space
+                , Str "some"
+                , Space
+                , Str "display"
+                , Space
+                , Str "math:"
+                , SoftBreak
+                , Math
+                    DisplayMath
+                    "\\frac{d}{dx}f(x)=\\lim_{h\\to 0}\\frac{f(x+h)-f(x)}{h}"
+                ]
+            ]
+          , [ Plain
+                [ Str "Here\8217s"
+                , Space
+                , Str "one"
+                , Space
+                , Str "that"
+                , Space
+                , Str "has"
+                , Space
+                , Str "a"
+                , Space
+                , Str "line"
+                , Space
+                , Str "break"
+                , Space
+                , Str "in"
+                , Space
+                , Str "it:"
+                , Space
+                , Math InlineMath "\\alpha + \\omega \\times x^2"
+                , Str "."
+                ]
+            ]
+          ]
+      , Para
+          [ Str "These"
+          , Space
+          , Str "shouldn\8217t"
+          , Space
+          , Str "be"
+          , Space
+          , Str "math:"
+          ]
+      , BulletList
+          [ [ Plain
+                [ Str "To"
+                , Space
+                , Str "get"
+                , Space
+                , Str "the"
+                , Space
+                , Str "famous"
+                , Space
+                , Str "equation,"
+                , Space
+                , Str "write"
+                , Space
+                , Code ( "" , [] , [] ) "$e = mc^2$"
+                , Str "."
+                ]
+            ]
+          , [ Plain
+                [ Str "$22,000"
+                , Space
+                , Str "is"
+                , Space
+                , Str "a"
+                , Space
+                , Emph [ Str "lot" ]
+                , Space
+                , Str "of"
+                , Space
+                , Str "money."
+                , Space
+                , Str "So"
+                , Space
+                , Str "is"
+                , Space
+                , Str "$34,000."
+                , Space
+                , Str "(It"
+                , Space
+                , Str "worked"
+                , Space
+                , Str "if"
+                , Space
+                , Quoted DoubleQuote [ Str "lot" ]
+                , Space
+                , Str "is"
+                , SoftBreak
+                , Str "emphasized.)"
+                ]
+            ]
+          , [ Plain
+                [ Str "Shoes"
+                , Space
+                , Str "($20)"
+                , Space
+                , Str "and"
+                , Space
+                , Str "socks"
+                , Space
+                , Str "($5)."
+                ]
+            ]
+          , [ Plain
+                [ Str "Escaped"
+                , Space
+                , Code ( "" , [] , [] ) "$"
+                , Str ":"
+                , Space
+                , Str "$73"
+                , Space
+                , Emph
+                    [ Str "this"
+                    , Space
+                    , Str "should"
+                    , Space
+                    , Str "be"
+                    , Space
+                    , Str "emphasized"
+                    ]
+                , Space
+                , Str "23$."
+                ]
+            ]
+          ]
+      , Para
+          [ Str "Here\8217s"
+          , Space
+          , Str "a"
+          , Space
+          , Str "LaTeX"
+          , Space
+          , Str "table:"
+          ]
+      , HorizontalRule
+      ]
+  , Div
+      ( "special-characters" , [ "section" ] , [] )
+      [ Header
+          1
+          ( "" , [] , [] )
+          [ Str "Special" , Space , Str "Characters" ]
+      , Para
+          [ Str "Here"
+          , Space
+          , Str "is"
+          , Space
+          , Str "some"
+          , Space
+          , Str "unicode:"
+          ]
+      , BulletList
+          [ [ Plain
+                [ Str "I" , Space , Str "hat:" , Space , Str "\206" ]
+            ]
+          , [ Plain
+                [ Str "o" , Space , Str "umlaut:" , Space , Str "\246" ]
+            ]
+          , [ Plain [ Str "section:" , Space , Str "\167" ] ]
+          , [ Plain
+                [ Str "set"
+                , Space
+                , Str "membership:"
+                , Space
+                , Str "\8712"
+                ]
+            ]
+          , [ Plain [ Str "copyright:" , Space , Str "\169" ] ]
+          ]
+      , Para
+          [ Str "AT&T"
+          , Space
+          , Str "has"
+          , Space
+          , Str "an"
+          , Space
+          , Str "ampersand"
+          , Space
+          , Str "in"
+          , Space
+          , Str "their"
+          , Space
+          , Str "name."
+          ]
+      , Para
+          [ Str "AT&T"
+          , Space
+          , Str "is"
+          , Space
+          , Str "another"
+          , Space
+          , Str "way"
+          , Space
+          , Str "to"
+          , Space
+          , Str "write"
+          , Space
+          , Str "it."
+          ]
+      , Para
+          [ Str "This" , Space , Str "&" , Space , Str "that." ]
+      , Para [ Str "4" , Space , Str "<" , Space , Str "5." ]
+      , Para [ Str "6" , Space , Str ">" , Space , Str "5." ]
+      , Para [ Str "Backslash:" , Space , Str "\\" ]
+      , Para [ Str "Backtick:" , Space , Str "`" ]
+      , Para [ Str "Asterisk:" , Space , Str "*" ]
+      , Para [ Str "Underscore:" , Space , Str "_" ]
+      , Para
+          [ Str "Left" , Space , Str "brace:" , Space , Str "{" ]
+      , Para
+          [ Str "Right" , Space , Str "brace:" , Space , Str "}" ]
+      , Para
+          [ Str "Left" , Space , Str "bracket:" , Space , Str "[" ]
+      , Para
+          [ Str "Right" , Space , Str "bracket:" , Space , Str "]" ]
+      , Para
+          [ Str "Left" , Space , Str "paren:" , Space , Str "(" ]
+      , Para
+          [ Str "Right" , Space , Str "paren:" , Space , Str ")" ]
+      , Para [ Str "Greater-than:" , Space , Str ">" ]
+      , Para [ Str "Hash:" , Space , Str "#" ]
+      , Para [ Str "Period:" , Space , Str "." ]
+      , Para [ Str "Bang:" , Space , Str "!" ]
+      , Para [ Str "Plus:" , Space , Str "+" ]
+      , Para [ Str "Minus:" , Space , Str "-" ]
+      , HorizontalRule
+      ]
+  , Div
+      ( "links" , [ "section" ] , [] )
+      [ Header 1 ( "" , [] , [] ) [ Str "Links" ]
+      , Div
+          ( "explicit" , [ "section" ] , [] )
+          [ Header 2 ( "" , [] , [] ) [ Str "Explicit" ]
+          , Para
+              [ Str "Just"
+              , Space
+              , Str "a"
+              , Space
+              , Link ( "" , [] , [] ) [ Str "URL" ] ( "/url/" , "" )
+              , Str "."
+              ]
+          , Para
+              [ Link
+                  ( "" , [] , [ ( "title" , "title" ) ] )
+                  [ Str "URL"
+                  , Space
+                  , Str "and"
+                  , Space
+                  , Str "title"
+                  ]
+                  ( "/url/" , "" )
+              , Str "."
+              ]
+          , Para
+              [ Link
+                  ( ""
+                  , []
+                  , [ ( "title" , "title preceded by two spaces" ) ]
+                  )
+                  [ Str "URL"
+                  , Space
+                  , Str "and"
+                  , Space
+                  , Str "title"
+                  ]
+                  ( "/url/" , "" )
+              , Str "."
+              ]
+          , Para
+              [ Link
+                  ( ""
+                  , []
+                  , [ ( "title" , "title preceded by a tab" ) ]
+                  )
+                  [ Str "URL"
+                  , Space
+                  , Str "and"
+                  , Space
+                  , Str "title"
+                  ]
+                  ( "/url/" , "" )
+              , Str "."
+              ]
+          , Para
+              [ Link
+                  ( ""
+                  , []
+                  , [ ( "title" , "title with \"quotes\" in it" ) ]
+                  )
+                  [ Str "URL"
+                  , Space
+                  , Str "and"
+                  , Space
+                  , Str "title"
+                  ]
+                  ( "/url/" , "" )
+              ]
+          , Para
+              [ Link
+                  ( ""
+                  , []
+                  , [ ( "title" , "title with single quotes" ) ]
+                  )
+                  [ Str "URL"
+                  , Space
+                  , Str "and"
+                  , Space
+                  , Str "title"
+                  ]
+                  ( "/url/" , "" )
+              ]
+          , Para
+              [ Link
+                  ( "" , [] , [] )
+                  [ Str "with_underscore" ]
+                  ( "/url/with_underscore" , "" )
+              ]
+          , Para
+              [ Link
+                  ( "" , [] , [] )
+                  [ Str "Email" , Space , Str "link" ]
+                  ( "mailto:nobody@nowhere.net" , "" )
+              ]
+          , Para
+              [ Link ( "" , [] , [] ) [ Str "Empty" ] ( "" , "" )
+              , Str "."
+              ]
+          ]
+      , Div
+          ( "reference" , [ "section" ] , [] )
+          [ Header 2 ( "" , [] , [] ) [ Str "Reference" ]
+          , Para
+              [ Str "Foo"
+              , Space
+              , Link ( "" , [] , [] ) [ Str "bar" ] ( "/url/" , "" )
+              , Str "."
+              ]
+          , Para
+              [ Str "With"
+              , Space
+              , Link
+                  ( "" , [] , [] )
+                  [ Str "embedded" , Space , Str "[brackets]" ]
+                  ( "/url/" , "" )
+              , Str "."
+              ]
+          , Para
+              [ Link ( "" , [] , [] ) [ Str "b" ] ( "/url/" , "" )
+              , Space
+              , Str "by"
+              , Space
+              , Str "itself"
+              , Space
+              , Str "should"
+              , Space
+              , Str "be"
+              , Space
+              , Str "a"
+              , Space
+              , Str "link."
+              ]
+          , Para
+              [ Str "Indented"
+              , Space
+              , Link ( "" , [] , [] ) [ Str "once" ] ( "/url" , "" )
+              , Str "."
+              ]
+          , Para
+              [ Str "Indented"
+              , Space
+              , Link ( "" , [] , [] ) [ Str "twice" ] ( "/url" , "" )
+              , Str "."
+              ]
+          , Para
+              [ Str "Indented"
+              , Space
+              , Link ( "" , [] , [] ) [ Str "thrice" ] ( "/url" , "" )
+              , Str "."
+              ]
+          , Para
+              [ Str "This"
+              , Space
+              , Str "should"
+              , Space
+              , Str "[not][]"
+              , Space
+              , Str "be"
+              , Space
+              , Str "a"
+              , Space
+              , Str "link."
+              ]
+          , CodeBlock ( "" , [ "" ] , [] ) "[not]: /url\n"
+          , Para
+              [ Str "Foo"
+              , Space
+              , Link
+                  ( ""
+                  , []
+                  , [ ( "title" , "Title with \"quotes\" inside" ) ]
+                  )
+                  [ Str "bar" ]
+                  ( "/url/" , "" )
+              , Str "."
+              ]
+          , Para
+              [ Str "Foo"
+              , Space
+              , Link
+                  ( ""
+                  , []
+                  , [ ( "title" , "Title with \"quote\" inside" ) ]
+                  )
+                  [ Str "biz" ]
+                  ( "/url/" , "" )
+              , Str "."
+              ]
+          ]
+      , Div
+          ( "with-ampersands" , [ "section" ] , [] )
+          [ Header
+              2
+              ( "" , [] , [] )
+              [ Str "With" , Space , Str "ampersands" ]
+          , Para
+              [ Str "Here\8217s"
+              , Space
+              , Str "a"
+              , Space
+              , Link
+                  ( "" , [] , [] )
+                  [ Str "link"
+                  , Space
+                  , Str "with"
+                  , Space
+                  , Str "an"
+                  , Space
+                  , Str "ampersand"
+                  , Space
+                  , Str "in"
+                  , Space
+                  , Str "the"
+                  , Space
+                  , Str "URL"
+                  ]
+                  ( "http://example.com/?foo=1&bar=2" , "" )
+              , Str "."
+              ]
+          , Para
+              [ Str "Here\8217s"
+              , Space
+              , Str "a"
+              , Space
+              , Str "link"
+              , Space
+              , Str "with"
+              , Space
+              , Str "an"
+              , Space
+              , Str "amersand"
+              , Space
+              , Str "in"
+              , Space
+              , Str "the"
+              , Space
+              , Str "link"
+              , Space
+              , Str "text:"
+              , SoftBreak
+              , Link
+                  ( "" , [] , [ ( "title" , "AT&T" ) ] )
+                  [ Str "AT&T" ]
+                  ( "http://att.com/" , "" )
+              , Str "."
+              ]
+          , Para
+              [ Str "Here\8217s"
+              , Space
+              , Str "an"
+              , Space
+              , Link
+                  ( "" , [] , [] )
+                  [ Str "inline" , Space , Str "link" ]
+                  ( "/script?foo=1&bar=2" , "" )
+              , Str "."
+              ]
+          , Para
+              [ Str "Here\8217s"
+              , Space
+              , Str "an"
+              , Space
+              , Link
+                  ( "" , [] , [] )
+                  [ Str "inline"
+                  , Space
+                  , Str "link"
+                  , Space
+                  , Str "in"
+                  , Space
+                  , Str "pointy"
+                  , Space
+                  , Str "braces"
+                  ]
+                  ( "/script?foo=1&bar=2" , "" )
+              , Str "."
+              ]
+          ]
+      , Div
+          ( "autolinks" , [ "section" ] , [] )
+          [ Header 2 ( "" , [] , [] ) [ Str "Autolinks" ]
+          , Para
+              [ Str "With"
+              , Space
+              , Str "an"
+              , Space
+              , Str "ampersand:"
+              , Space
+              , Link
+                  ( "" , [ "uri" ] , [] )
+                  [ Str "http://example.com/?foo=1&bar=2" ]
+                  ( "http://example.com/?foo=1&bar=2" , "" )
+              ]
+          , BulletList
+              [ [ Plain
+                    [ Str "In" , Space , Str "a" , Space , Str "list?" ]
+                ]
+              , [ Plain
+                    [ Link
+                        ( "" , [ "uri" ] , [] )
+                        [ Str "http://example.com/" ]
+                        ( "http://example.com/" , "" )
+                    ]
+                ]
+              , [ Plain [ Str "It" , Space , Str "should." ] ]
+              ]
+          , Para
+              [ Str "An"
+              , Space
+              , Str "e-mail"
+              , Space
+              , Str "address:"
+              , Space
+              , Link
+                  ( "" , [ "email" ] , [] )
+                  [ Str "nobody@nowhere.net" ]
+                  ( "mailto:nobody@nowhere.net" , "" )
+              ]
+          , BlockQuote
+              [ Para
+                  [ Str "Blockquoted:"
+                  , Space
+                  , Link
+                      ( "" , [ "uri" ] , [] )
+                      [ Str "http://example.com/" ]
+                      ( "http://example.com/" , "" )
+                  ]
+              ]
+          , Para
+              [ Str "Auto-links"
+              , Space
+              , Str "should"
+              , Space
+              , Str "not"
+              , Space
+              , Str "occur"
+              , Space
+              , Str "here:"
+              , Space
+              , Code ( "" , [] , [] ) "<http://example.com/>"
+              ]
+          , CodeBlock
+              ( "" , [ "" ] , [] ) "or here: <http://example.com/>\n"
+          , HorizontalRule
+          ]
+      ]
+  , Div
+      ( "images" , [ "section" ] , [] )
+      [ Header 1 ( "" , [] , [] ) [ Str "Images" ]
+      , Para
+          [ Str "From"
+          , Space
+          , Quoted
+              DoubleQuote
+              [ Str "Voyage"
+              , Space
+              , Str "dans"
+              , Space
+              , Str "la"
+              , Space
+              , Str "Lune"
+              ]
+          , Space
+          , Str "by"
+          , Space
+          , Str "Georges"
+          , Space
+          , Str "Melies"
+          , Space
+          , Str "(1902):"
+          ]
+      , Div
+          ( "" , [] , [] )
+          [ Para
+              [ Image
+                  ( "" , [] , [ ( "title" , "Voyage dans la Lune" ) ] )
+                  [ Str "lalune" ]
+                  ( "lalune.jpg" , "" )
+              ]
+          , Div ( "" , [ "caption" ] , [] ) [ Para [ Str "lalune" ] ]
+          ]
+      , Para
+          [ Str "Here"
+          , Space
+          , Str "is"
+          , Space
+          , Str "a"
+          , Space
+          , Str "movie"
+          , Space
+          , Image
+              ( "" , [] , [] ) [ Str "movie" ] ( "movie.jpg" , "" )
+          , Space
+          , Str "icon."
+          ]
+      , HorizontalRule
+      ]
+  , Div
+      ( "footnotes" , [ "section" ] , [] )
+      [ Header 1 ( "" , [] , [] ) [ Str "Footnotes" ]
+      , Para
+          [ Str "Here"
+          , Space
+          , Str "is"
+          , Space
+          , Str "a"
+          , Space
+          , Str "footnote"
+          , Space
+          , Str "reference,"
+          , Note
+              [ Para
+                  [ Str "Here"
+                  , Space
+                  , Str "is"
+                  , Space
+                  , Str "the"
+                  , Space
+                  , Str "footnote."
+                  , Space
+                  , Str "It"
+                  , Space
+                  , Str "can"
+                  , Space
+                  , Str "go"
+                  , Space
+                  , Str "anywhere"
+                  , Space
+                  , Str "after"
+                  , Space
+                  , Str "the"
+                  , Space
+                  , Str "footnote"
+                  , Space
+                  , Str "reference."
+                  , Space
+                  , Str "It"
+                  , SoftBreak
+                  , Str "need"
+                  , Space
+                  , Str "not"
+                  , Space
+                  , Str "be"
+                  , Space
+                  , Str "placed"
+                  , Space
+                  , Str "at"
+                  , Space
+                  , Str "the"
+                  , Space
+                  , Str "end"
+                  , Space
+                  , Str "of"
+                  , Space
+                  , Str "the"
+                  , Space
+                  , Str "document."
+                  ]
+              ]
+          , Space
+          , Str "and"
+          , Space
+          , Str "another."
+          , Note
+              [ Para
+                  [ Str "Here\8217s"
+                  , Space
+                  , Str "the"
+                  , Space
+                  , Str "long"
+                  , Space
+                  , Str "note."
+                  , Space
+                  , Str "This"
+                  , Space
+                  , Str "one"
+                  , Space
+                  , Str "contains"
+                  , Space
+                  , Str "multiple"
+                  , Space
+                  , Str "blocks."
+                  ]
+              , Para
+                  [ Str "Subsequent"
+                  , Space
+                  , Str "blocks"
+                  , Space
+                  , Str "are"
+                  , Space
+                  , Str "indented"
+                  , Space
+                  , Str "to"
+                  , Space
+                  , Str "show"
+                  , Space
+                  , Str "that"
+                  , Space
+                  , Str "they"
+                  , Space
+                  , Str "belong"
+                  , Space
+                  , Str "to"
+                  , Space
+                  , Str "the"
+                  , Space
+                  , Str "footnote"
+                  , Space
+                  , Str "(as"
+                  , SoftBreak
+                  , Str "with"
+                  , Space
+                  , Str "list"
+                  , Space
+                  , Str "items)."
+                  ]
+              , CodeBlock ( "" , [ "" ] , [] ) "{ <code> }\n"
+              , Para
+                  [ Str "If"
+                  , Space
+                  , Str "you"
+                  , Space
+                  , Str "want,"
+                  , Space
+                  , Str "you"
+                  , Space
+                  , Str "can"
+                  , Space
+                  , Str "indent"
+                  , Space
+                  , Str "every"
+                  , Space
+                  , Str "line,"
+                  , Space
+                  , Str "but"
+                  , Space
+                  , Str "you"
+                  , Space
+                  , Str "can"
+                  , Space
+                  , Str "also"
+                  , Space
+                  , Str "be"
+                  , Space
+                  , Str "lazy"
+                  , Space
+                  , Str "and"
+                  , Space
+                  , Str "just"
+                  , SoftBreak
+                  , Str "indent"
+                  , Space
+                  , Str "the"
+                  , Space
+                  , Str "first"
+                  , Space
+                  , Str "line"
+                  , Space
+                  , Str "of"
+                  , Space
+                  , Str "each"
+                  , Space
+                  , Str "block."
+                  ]
+              ]
+          , Space
+          , Str "This"
+          , Space
+          , Str "should"
+          , Space
+          , Emph [ Str "not" ]
+          , Space
+          , Str "be"
+          , Space
+          , Str "a"
+          , SoftBreak
+          , Str "footnote"
+          , Space
+          , Str "reference,"
+          , Space
+          , Str "because"
+          , Space
+          , Str "it"
+          , Space
+          , Str "contains"
+          , Space
+          , Str "a"
+          , Space
+          , Str "space.[^my"
+          , Space
+          , Str "note]"
+          , Space
+          , Str "Here"
+          , Space
+          , Str "is"
+          , Space
+          , Str "an"
+          , Space
+          , Str "inline"
+          , SoftBreak
+          , Str "note."
+          , Note
+              [ Para
+                  [ Str "This"
+                  , Space
+                  , Str "is"
+                  , Space
+                  , Emph [ Str "easier" ]
+                  , Space
+                  , Str "to"
+                  , Space
+                  , Str "type."
+                  , Space
+                  , Str "Inline"
+                  , Space
+                  , Str "notes"
+                  , Space
+                  , Str "may"
+                  , Space
+                  , Str "contain"
+                  , SoftBreak
+                  , Link
+                      ( "" , [] , [] )
+                      [ Str "links" ]
+                      ( "http://google.com" , "" )
+                  , Space
+                  , Str "and"
+                  , Space
+                  , Code ( "" , [] , [] ) "]"
+                  , Space
+                  , Str "verbatim"
+                  , Space
+                  , Str "characters,"
+                  , Space
+                  , Str "as"
+                  , Space
+                  , Str "well"
+                  , Space
+                  , Str "as"
+                  , SoftBreak
+                  , Str "[bracketed"
+                  , Space
+                  , Str "text]."
+                  ]
+              ]
+          ]
+      , BlockQuote
+          [ Para
+              [ Str "Notes"
+              , Space
+              , Str "can"
+              , Space
+              , Str "go"
+              , Space
+              , Str "in"
+              , Space
+              , Str "quotes."
+              , Note [ Para [ Str "In" , Space , Str "quote." ] ]
+              ]
+          ]
+      , OrderedList
+          ( 1 , Decimal , Period )
+          [ [ Plain
+                [ Str "And"
+                , Space
+                , Str "in"
+                , Space
+                , Str "list"
+                , Space
+                , Str "items."
+                , Note [ Para [ Str "In" , Space , Str "list." ] ]
+                ]
+            ]
+          ]
+      , Para
+          [ Str "This"
+          , Space
+          , Str "paragraph"
+          , Space
+          , Str "should"
+          , Space
+          , Str "not"
+          , Space
+          , Str "be"
+          , Space
+          , Str "part"
+          , Space
+          , Str "of"
+          , Space
+          , Str "the"
+          , Space
+          , Str "note,"
+          , Space
+          , Str "as"
+          , Space
+          , Str "it"
+          , Space
+          , Str "is"
+          , Space
+          , Str "not"
+          , Space
+          , Str "indented."
+          ]
+      ]
+  ]
diff --git a/test/docbook-chapter.docbook b/test/docbook-chapter.docbook
new file mode 100644
--- /dev/null
+++ b/test/docbook-chapter.docbook
@@ -0,0 +1,30 @@
+<!DOCTYPE chapter PUBLIC "-//OASIS//DTD DocBook XML V4.1.2//EN"
+          "http://www.oasis-open.org/docbook/xml/4.1.2/docbookx.dtd">
+<!-- This matches the example from
+https://tdg.docbook.org/tdg/4.5/section.html, sans sectioninfo and subtitle, as
+they're currently not supported -->
+<chapter><title>Test Chapter</title>
+<para>This chapter uses recursive sections.</para>
+<section>
+<title>Like a Sect1</title>
+<para>This section is like a Sect1.</para>
+<section><title>Like a Sect2</title>
+<para>This section is like a Sect2.</para>
+<section><title>Like a Sect3</title>
+<para>This section is like a Sect3.</para>
+<section><title>Like a Sect4</title>
+<para>This section is like a Sect4.</para>
+<section><title>Like a Sect5</title>
+<para>This section is like a Sect5.</para>
+<section><title>Would be like a Sect6</title>
+<para>This section would be like a Sect6, if there was one.</para>
+<section><title>Would be like a Sect7</title>
+<para>This section would be like a Sect7, if there was one.</para>
+</section>
+</section>
+</section>
+</section>
+</section>
+</section>
+</section>
+</chapter>
diff --git a/test/docbook-chapter.native b/test/docbook-chapter.native
new file mode 100644
--- /dev/null
+++ b/test/docbook-chapter.native
@@ -0,0 +1,173 @@
+Pandoc
+  Meta { unMeta = fromList [] }
+  [ Header
+      1 ( "" , [] , [] ) [ Str "Test" , Space , Str "Chapter" ]
+  , Para
+      [ Str "This"
+      , Space
+      , Str "chapter"
+      , Space
+      , Str "uses"
+      , Space
+      , Str "recursive"
+      , Space
+      , Str "sections."
+      ]
+  , Header
+      2
+      ( "" , [] , [] )
+      [ Str "Like" , Space , Str "a" , Space , Str "Sect1" ]
+  , Para
+      [ Str "This"
+      , Space
+      , Str "section"
+      , Space
+      , Str "is"
+      , Space
+      , Str "like"
+      , Space
+      , Str "a"
+      , Space
+      , Str "Sect1."
+      ]
+  , Header
+      3
+      ( "" , [] , [] )
+      [ Str "Like" , Space , Str "a" , Space , Str "Sect2" ]
+  , Para
+      [ Str "This"
+      , Space
+      , Str "section"
+      , Space
+      , Str "is"
+      , Space
+      , Str "like"
+      , Space
+      , Str "a"
+      , Space
+      , Str "Sect2."
+      ]
+  , Header
+      4
+      ( "" , [] , [] )
+      [ Str "Like" , Space , Str "a" , Space , Str "Sect3" ]
+  , Para
+      [ Str "This"
+      , Space
+      , Str "section"
+      , Space
+      , Str "is"
+      , Space
+      , Str "like"
+      , Space
+      , Str "a"
+      , Space
+      , Str "Sect3."
+      ]
+  , Header
+      5
+      ( "" , [] , [] )
+      [ Str "Like" , Space , Str "a" , Space , Str "Sect4" ]
+  , Para
+      [ Str "This"
+      , Space
+      , Str "section"
+      , Space
+      , Str "is"
+      , Space
+      , Str "like"
+      , Space
+      , Str "a"
+      , Space
+      , Str "Sect4."
+      ]
+  , Header
+      6
+      ( "" , [] , [] )
+      [ Str "Like" , Space , Str "a" , Space , Str "Sect5" ]
+  , Para
+      [ Str "This"
+      , Space
+      , Str "section"
+      , Space
+      , Str "is"
+      , Space
+      , Str "like"
+      , Space
+      , Str "a"
+      , Space
+      , Str "Sect5."
+      ]
+  , Header
+      7
+      ( "" , [] , [] )
+      [ Str "Would"
+      , Space
+      , Str "be"
+      , Space
+      , Str "like"
+      , Space
+      , Str "a"
+      , Space
+      , Str "Sect6"
+      ]
+  , Para
+      [ Str "This"
+      , Space
+      , Str "section"
+      , Space
+      , Str "would"
+      , Space
+      , Str "be"
+      , Space
+      , Str "like"
+      , Space
+      , Str "a"
+      , Space
+      , Str "Sect6,"
+      , Space
+      , Str "if"
+      , Space
+      , Str "there"
+      , Space
+      , Str "was"
+      , Space
+      , Str "one."
+      ]
+  , Header
+      8
+      ( "" , [] , [] )
+      [ Str "Would"
+      , Space
+      , Str "be"
+      , Space
+      , Str "like"
+      , Space
+      , Str "a"
+      , Space
+      , Str "Sect7"
+      ]
+  , Para
+      [ Str "This"
+      , Space
+      , Str "section"
+      , Space
+      , Str "would"
+      , Space
+      , Str "be"
+      , Space
+      , Str "like"
+      , Space
+      , Str "a"
+      , Space
+      , Str "Sect7,"
+      , Space
+      , Str "if"
+      , Space
+      , Str "there"
+      , Space
+      , Str "was"
+      , Space
+      , Str "one."
+      ]
+  ]
diff --git a/test/docbook-reader.docbook b/test/docbook-reader.docbook
--- a/test/docbook-reader.docbook
+++ b/test/docbook-reader.docbook
@@ -1,7 +1,14 @@
 <?xml version="1.0" encoding="utf-8" ?>
 <!DOCTYPE article PUBLIC "-//OASIS//DTD DocBook XML V4.4//EN"
-                  "http://www.oasis-open.org/docbook/xml/4.4/docbookx.dtd">
-<article>
+"http://www.oasis-open.org/docbook/xml/4.4/docbookx.dtd"
+[
+<!ENTITY GHC "GHC" >
+<!ENTITY let "LET" >
+<!ENTITY case "CASE" >
+]>
+<article xmlns="http://docbook.org/ns/docbook"
+         xmlns:xlink="http://www.w3.org/1999/xlink"
+         xmlns:mml="http://www.w3.org/1998/Math/MathML">
   <articleinfo>
     <title>Pandoc Test Suite</title>
     <authorgroup>
@@ -20,9 +27,9 @@
   This is a set of tests for pandoc. Most of them are adapted from John
   Gruber’s markdown test suite.
 </para>
-<sect1 id="headers">
+<sect1 id="headers" role="sect1role">
   <title>Headers</title>
-  <sect2 id="level-2-with-an-embedded-link">
+  <sect2 id="level-2-with-an-embedded-link" role="sect2role">
     <title>Level 2 with an <ulink url="/url">embedded link</ulink></title>
     <sect3 id="level-3-with-emphasis">
       <title>Level 3 with <emphasis>emphasis</emphasis></title>
@@ -47,6 +54,12 @@
       <para>
         with no blank line
       </para>
+      <simplesect>
+        <title>Level 4</title>
+        <para>
+        An unnumbered section.
+        </para>
+      </simplesect>
     </sect3>
   </sect2>
   <sect2 id="level-2">
@@ -61,6 +74,9 @@
   <para>
     Here’s a regular paragraph.
   </para>
+  <para role="pararole">
+    And here’s a regular paragraph with a role.
+  </para>
   <para>
     In Markdown 1.0.0 and earlier. Version 8. This line turns into a list
     item. Because a hard-wrapped line in the middle of a paragraph looked like
@@ -80,6 +96,11 @@
       This is a block quote. It is pretty short.
     </para>
   </blockquote>
+  <blockquote role="roleblockquote">
+    <para>
+      This is a block quote with a role.
+    </para>
+  </blockquote>
   <blockquote>
     <para>
       Code in a block quote:
@@ -89,6 +110,11 @@
     print &quot;working&quot;;
 }
 </programlisting>
+    <programlisting linenumbering="numbered">
+sub status {
+    print &quot;working with line numbers&quot;;
+}
+</programlisting>
     <screen>
 % <command>ls</command>
 </screen>
@@ -176,9 +202,9 @@
       </listitem>
     </itemizedlist>
     <para>
-      Pluses loose:
+      Asterisks tight:
     </para>
-    <itemizedlist>
+    <itemizedlist spacing="compact">
       <listitem>
         <para>
           Plus 1
@@ -195,30 +221,30 @@
         </para>
       </listitem>
     </itemizedlist>
-    <para>
-      Minuses loose:
-    </para>
-    <itemizedlist>
+  </sect2>
+  <sect2 id="ordered">
+    <title>Ordered</title>
+    <orderedlist numeration="arabic">
       <listitem>
         <para>
-          Minus 1
+          First
         </para>
       </listitem>
       <listitem>
         <para>
-          Minus 2
+          Second
         </para>
       </listitem>
       <listitem>
         <para>
-          Minus 3
+          Third
         </para>
       </listitem>
-    </itemizedlist>
-  </sect2>
-  <sect2 id="ordered">
-    <title>Ordered</title>
-    <orderedlist numeration="arabic">
+    </orderedlist>
+    <para>
+      with role:
+    </para>
+    <orderedlist role="listrole" numeration="arabic">
       <listitem>
         <para>
           First
@@ -236,9 +262,9 @@
       </listitem>
     </orderedlist>
     <para>
-      and using spaces:
+      and tight:
     </para>
-    <orderedlist numeration="arabic">
+    <orderedlist spacing="compact" numeration="arabic">
       <listitem>
         <para>
           One
@@ -407,8 +433,8 @@
   </sect2>
   <sect2 id="fancy-list-markers">
     <title>Fancy list markers</title>
-    <orderedlist numeration="arabic">
-      <listitem override="2">
+    <orderedlist numeration="arabic" startingnumber="2">
+      <listitem>
         <para>
           begins with 2
         </para>
@@ -420,8 +446,8 @@
         <para>
           with a continuation
         </para>
-        <orderedlist numeration="lowerroman">
-          <listitem override="4">
+        <orderedlist numeration="lowerroman" startingnumber="4">
+          <listitem>
             <para>
               sublist with roman numerals, starting with 4
             </para>
@@ -459,13 +485,13 @@
             <para>
               Upper Roman.
             </para>
-            <orderedlist numeration="arabic">
-              <listitem override="6">
+            <orderedlist numeration="arabic" startingnumber="6">
+              <listitem>
                 <para>
                   Decimal start with 6
                 </para>
-                <orderedlist numeration="loweralpha">
-                  <listitem override="3">
+                <orderedlist numeration="loweralpha" startingnumber="3">
+                  <listitem>
                     <para>
                       Lower alpha with paren
                     </para>
@@ -705,6 +731,12 @@
     So is <emphasis role="strong"><emphasis>this</emphasis></emphasis> word.
   </para>
   <para>
+    So is <emphasis role="emphasisrole"><emphasis>this</emphasis></emphasis> word with a role.
+  </para>
+  <para>
+    So is <phrase role="phraserole"><phrase>this</phrase></phrase> phrase with a role.
+  </para>
+  <para>
     This is code: <literal>&gt;</literal>, <literal>$</literal>,
     <literal>\</literal>, <literal>\$</literal>,
     <literal>&lt;html&gt;</literal>.
@@ -713,6 +745,9 @@
     More code: <classname>Class</classname> and <type>Type</type>
   </para>
   <para>
+    Referencing a man page: <citerefentry><refentrytitle>nix.conf</refentrytitle><manvolnum>5</manvolnum></citerefentry>
+  </para>
+  <para>
     <emphasis role="strikethrough">This is
     <emphasis>strikeout</emphasis>.</emphasis>
   </para>
@@ -1405,6 +1440,75 @@
     </tgroup>
   </table>
   <para>
+    Table with attributes
+  </para>
+  <table xml:id="mytableid1" class="mytableclass1 mytableclass2" tabstyle="mytabstyle1" role="tablerole1">
+    <title>
+      Attribute table caption
+    </title>
+    <tgroup>
+      <thead>
+	<th>
+	  <para>
+	    header cell 1
+	  </para>
+	</th>
+	<th>
+	  <para>
+	    header cell 2
+	  </para>
+	</th>
+      </thead>
+      <tbody>
+	<tr>
+	  <td>
+	    <para>
+	      body cell 1
+	    </para>
+	  </td>
+	  <td>
+	    <para>
+	      body cell 2
+	    </para>
+	  </td>
+	</tr>
+      </tbody>
+    </tgroup>
+  </table>
+  <para>
+    Table with attributes, without caption
+  </para>
+  <informaltable xml:id="mytableid2" class="mytableclass3 mytableclass4" tabstyle="mytabstyle2" role="tablerole2">
+    <tgroup>
+      <thead>
+	<th>
+	  <para>
+	    header cell 1
+	  </para>
+	</th>
+	<th>
+	  <para>
+	    header cell 2
+	  </para>
+	</th>
+      </thead>
+      <tbody>
+	<tr>
+	  <td>
+	    <para>
+	      body cell 1
+	    </para>
+	  </td>
+	  <td>
+	    <para>
+	      body cell 2
+	    </para>
+	  </td>
+	</tr>
+      </tbody>
+    </tgroup>
+  </informaltable>
+  <para>
     Multiline table without caption:
   </para>
   <informaltable>
@@ -1557,5 +1661,78 @@
       </tbody>
     </tgroup>
   </informaltable>
+  <para>
+    Multiline table with cells spanning multiple columns and rows without caption.
+  </para>
+  <informaltable>
+    <tgroup cols="3">
+      <colspec align="left" colname="c1" />
+      <colspec align="left" colname="c2" />
+      <colspec align="left" colname="c3" />
+      <colspec align="left" colname="c4" />
+      <thead>
+  <tr>
+    <th namest="c1" nameend="c3">Columns</th>
+  </tr>
+  <tr>
+    <th>A</th>
+    <th>B</th>
+    <th>C</th>
+  </tr>
+      </thead>
+      <tbody>
+	<tr>
+	  <td namest="c1" nameend="c2">A1 + B1</td>
+	  <td morerows="1">C1 + C2</td>
+	</tr>
+  <tr>
+	  <td namest="c1" nameend="c2" morerows="1">A2 + B2 + A3 + B3</td>
+	</tr>
+  <tr>
+	  <td>C3</td>
+	</tr>
+      </tbody>
+    </tgroup>
+  </informaltable>
+  <procedure><title>An Example Procedure</title>
+    <step>
+      <para>
+        A Step
+      </para>
+    </step>
+    <step>
+      <para>
+        Another Step
+      </para>
+      <substeps>
+        <step>
+          <para>
+            Substeps can be nested indefinitely deep.
+          </para>
+        </step>
+      </substeps>
+    </step>
+    <step>
+      <para>
+        A Final Step
+      </para>
+    </step>
+  </procedure>
+</sect1>
+<sect1 id="indexterms">
+  <title>Index terms</title>
+  <para>
+    In the simplest case, index terms<indexterm><primary>index term</primary></indexterm> consists of just a <code>&lt;primary&gt;</code> element, but <indexterm><primary>index term</primary><secondary>multi-level</secondary></indexterm> they can also consist of a <code>&lt;primary&gt;</code> <emph>and</emph> <code>&lt;secondary&gt;</code> element, and <indexterm><primary>index term</primary><secondary>multi-level</secondary><tertiary>3-level</tertiary></indexterm> can even include a <code>&lt;tertiary&gt;</code> term.
+  </para>
+  <para>
+    Index terms can also refer to other index terms: <indexterm><primary>index cross referencing</primary></indexterm><indexterm><primary>index term</primary><secondary>cross references</secondary><see>index cross referencing</see></indexterm>exclusively, using the <code>&lt;see&gt;</code> tag; or <indexterm><primary>index cross referencing</primary><seealso>cross referencing</seealso></indexterm> as a reference to related terms, using the <code>&lt;seealso&gt;</code> tag.
+  </para>
+  <para>
+    <indexterm><primary>food</primary><secondary>big <foreignphrase>baguette</foreignphrase> <strong>supreme</strong></secondary></indexterm>Nested content in index term elements is flattened.
+  </para>
+</sect1>
+<sect1 id="titleabbrev">
+  <title>Abbreviated title</title>
+  <titleabbrev>Abbr. title</titleabbrev>
 </sect1>
 </article>
diff --git a/test/docbook-reader.native b/test/docbook-reader.native
--- a/test/docbook-reader.native
+++ b/test/docbook-reader.native
@@ -1,397 +1,3494 @@
-Pandoc (Meta {unMeta = fromList [("author",MetaList [MetaInlines [Str "John",SoftBreak,Str "MacFarlane"],MetaInlines [Str "Anonymous"]]),("date",MetaInlines [Str "July",Space,Str "17,",Space,Str "2006"]),("title",MetaInlines [Str "Pandoc",Space,Str "Test",Space,Str "Suite"])]})
-[Para [Str "This",Space,Str "is",Space,Str "a",Space,Str "set",Space,Str "of",Space,Str "tests",Space,Str "for",Space,Str "pandoc.",Space,Str "Most",Space,Str "of",Space,Str "them",Space,Str "are",Space,Str "adapted",Space,Str "from",Space,Str "John",SoftBreak,Str "Gruber\8217s",Space,Str "markdown",Space,Str "test",Space,Str "suite."]
-,Header 1 ("headers",[],[]) [Str "Headers"]
-,Header 2 ("level-2-with-an-embedded-link",[],[]) [Str "Level",Space,Str "2",Space,Str "with",Space,Str "an",Space,Link ("",[],[]) [Str "embedded",Space,Str "link"] ("/url","")]
-,Header 3 ("level-3-with-emphasis",[],[]) [Str "Level",Space,Str "3",Space,Str "with",Space,Emph [Str "emphasis"]]
-,Header 4 ("level-4",[],[]) [Str "Level",Space,Str "4"]
-,Header 5 ("level-5",[],[]) [Str "Level",Space,Str "5"]
-,Para [Str "Hi."]
-,Header 1 ("level-1",[],[]) [Str "Level",Space,Str "1"]
-,Header 2 ("level-2-with-emphasis",[],[]) [Str "Level",Space,Str "2",Space,Str "with",Space,Emph [Str "emphasis"]]
-,Header 3 ("level-3",[],[]) [Str "Level",Space,Str "3"]
-,Para [Str "with",Space,Str "no",Space,Str "blank",Space,Str "line"]
-,Header 2 ("level-2",[],[]) [Str "Level",Space,Str "2"]
-,Para [Str "with",Space,Str "no",Space,Str "blank",Space,Str "line"]
-,Header 1 ("paragraphs",[],[]) [Str "Paragraphs"]
-,Para [Str "Here\8217s",Space,Str "a",Space,Str "regular",Space,Str "paragraph."]
-,Para [Str "In",Space,Str "Markdown",Space,Str "1.0.0",Space,Str "and",Space,Str "earlier.",Space,Str "Version",Space,Str "8.",Space,Str "This",Space,Str "line",Space,Str "turns",Space,Str "into",Space,Str "a",Space,Str "list",SoftBreak,Str "item.",Space,Str "Because",Space,Str "a",Space,Str "hard-wrapped",Space,Str "line",Space,Str "in",Space,Str "the",Space,Str "middle",Space,Str "of",Space,Str "a",Space,Str "paragraph",Space,Str "looked",Space,Str "like",SoftBreak,Str "a",Space,Str "list",Space,Str "item."]
-,Para [Str "Here\8217s",Space,Str "one",Space,Str "with",Space,Str "a",Space,Str "bullet.",Space,Str "*",Space,Str "criminey."]
-,Header 1 ("block-quotes",[],[]) [Str "Block",Space,Str "Quotes"]
-,Para [Str "E-mail",Space,Str "style:"]
-,BlockQuote
- [Para [Str "This",Space,Str "is",Space,Str "a",Space,Str "block",Space,Str "quote.",Space,Str "It",Space,Str "is",Space,Str "pretty",Space,Str "short."]]
-,BlockQuote
- [Para [Str "Code",Space,Str "in",Space,Str "a",Space,Str "block",Space,Str "quote:"]
- ,CodeBlock ("",[],[]) "sub status {\n    print \"working\";\n}"
- ,CodeBlock ("",[],[]) "% ls"
- ,Para [Str "A",Space,Str "list:"]
- ,OrderedList (1,Decimal,DefaultDelim)
-  [[Para [Str "item",Space,Str "one"]]
-  ,[Para [Str "item",Space,Str "two"]]]
- ,Para [Str "Nested",Space,Str "block",Space,Str "quotes:"]
- ,BlockQuote
-  [Para [Str "nested"]]
- ,BlockQuote
-  [Para [Str "nested"]]]
-,Para [Str "This",Space,Str "should",Space,Str "not",Space,Str "be",Space,Str "a",Space,Str "block",Space,Str "quote:",Space,Str "2",Space,Str ">",Space,Str "1."]
-,Para [Str "And",Space,Str "a",Space,Str "following",Space,Str "paragraph."]
-,Header 1 ("code-blocks",[],[]) [Str "Code",Space,Str "Blocks"]
-,Para [Str "Code:"]
-,CodeBlock ("",[],[]) "---- (should be four hyphens)\n\nsub status {\n    print \"working\";\n}\n\nthis code block is indented by one tab"
-,Para [Str "And:"]
-,CodeBlock ("",[],[]) "    this code block is indented by two tabs\n\nThese should not be escaped:  \\$ \\\\ \\> \\[ \\{"
-,Header 1 ("lists",[],[]) [Str "Lists"]
-,Header 2 ("unordered",[],[]) [Str "Unordered"]
-,Para [Str "Asterisks",Space,Str "loose:"]
-,BulletList
- [[Para [Str "asterisk",Space,Str "1"]]
- ,[Para [Str "asterisk",Space,Str "2"]]
- ,[Para [Str "asterisk",Space,Str "3"]]]
-,Para [Str "Pluses",Space,Str "loose:"]
-,BulletList
- [[Para [Str "Plus",Space,Str "1"]]
- ,[Para [Str "Plus",Space,Str "2"]]
- ,[Para [Str "Plus",Space,Str "3"]]]
-,Para [Str "Minuses",Space,Str "loose:"]
-,BulletList
- [[Para [Str "Minus",Space,Str "1"]]
- ,[Para [Str "Minus",Space,Str "2"]]
- ,[Para [Str "Minus",Space,Str "3"]]]
-,Header 2 ("ordered",[],[]) [Str "Ordered"]
-,OrderedList (1,Decimal,DefaultDelim)
- [[Para [Str "First"]]
- ,[Para [Str "Second"]]
- ,[Para [Str "Third"]]]
-,Para [Str "and",Space,Str "using",Space,Str "spaces:"]
-,OrderedList (1,Decimal,DefaultDelim)
- [[Para [Str "One"]]
- ,[Para [Str "Two"]]
- ,[Para [Str "Three"]]]
-,Para [Str "Multiple",Space,Str "paragraphs:"]
-,OrderedList (1,Decimal,DefaultDelim)
- [[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."]]
- ,[Para [Str "Item",Space,Str "2."]]
- ,[Para [Str "Item",Space,Str "3."]]]
-,Header 2 ("nested",[],[]) [Str "Nested"]
-,BulletList
- [[Para [Str "Tab"]
-  ,BulletList
-   [[Para [Str "Tab"]
-    ,BulletList
-     [[Para [Str "Tab"]]]]]]]
-,Para [Str "Here\8217s",Space,Str "another:"]
-,OrderedList (1,Decimal,DefaultDelim)
- [[Para [Str "First"]]
- ,[Para [Str "Second:"]
-  ,BulletList
-   [[Para [Str "Fee"]]
-   ,[Para [Str "Fie"]]
-   ,[Para [Str "Foe"]]]]
- ,[Para [Str "Third"]]]
-,Para [Str "Same",Space,Str "thing",Space,Str "but",Space,Str "with",Space,Str "paragraphs:"]
-,OrderedList (1,Decimal,DefaultDelim)
- [[Para [Str "First"]]
- ,[Para [Str "Second:"]
-  ,BulletList
-   [[Para [Str "Fee"]]
-   ,[Para [Str "Fie"]]
-   ,[Para [Str "Foe"]]]]
- ,[Para [Str "Third"]]]
-,Header 2 ("tabs-and-spaces",[],[]) [Str "Tabs",Space,Str "and",Space,Str "spaces"]
-,BulletList
- [[Para [Str "this",Space,Str "is",Space,Str "a",Space,Str "list",Space,Str "item",Space,Str "indented",Space,Str "with",Space,Str "tabs"]]
- ,[Para [Str "this",Space,Str "is",Space,Str "a",Space,Str "list",Space,Str "item",Space,Str "indented",Space,Str "with",Space,Str "spaces"]
-  ,BulletList
-   [[Para [Str "this",Space,Str "is",Space,Str "an",Space,Str "example",Space,Str "list",Space,Str "item",Space,Str "indented",Space,Str "with",Space,Str "tabs"]]
-   ,[Para [Str "this",Space,Str "is",Space,Str "an",Space,Str "example",Space,Str "list",Space,Str "item",Space,Str "indented",Space,Str "with",Space,Str "spaces"]]]]]
-,Header 2 ("fancy-list-markers",[],[]) [Str "Fancy",Space,Str "list",Space,Str "markers"]
-,OrderedList (2,Decimal,DefaultDelim)
- [[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,DefaultDelim)
-   [[Para [Str "sublist",Space,Str "with",Space,Str "roman",Space,Str "numerals,",Space,Str "starting",Space,Str "with",Space,Str "4"]]
-   ,[Para [Str "more",Space,Str "items"]
-    ,OrderedList (1,UpperAlpha,DefaultDelim)
-     [[Para [Str "a",Space,Str "subsublist"]]
-     ,[Para [Str "a",Space,Str "subsublist"]]]]]]]
-,Para [Str "Nesting:"]
-,OrderedList (1,UpperAlpha,DefaultDelim)
- [[Para [Str "Upper",Space,Str "Alpha"]
-  ,OrderedList (1,UpperRoman,DefaultDelim)
-   [[Para [Str "Upper",Space,Str "Roman."]
-    ,OrderedList (6,Decimal,DefaultDelim)
-     [[Para [Str "Decimal",Space,Str "start",Space,Str "with",Space,Str "6"]
-      ,OrderedList (3,LowerAlpha,DefaultDelim)
-       [[Para [Str "Lower",Space,Str "alpha",Space,Str "with",Space,Str "paren"]]]]]]]]]
-,Para [Str "Autonumbering:"]
-,OrderedList (1,Decimal,DefaultDelim)
- [[Para [Str "Autonumber."]]
- ,[Para [Str "More."]
-  ,OrderedList (1,Decimal,DefaultDelim)
-   [[Para [Str "Nested."]]]]]
-,Para [Str "Should",Space,Str "not",Space,Str "be",Space,Str "a",Space,Str "list",Space,Str "item:"]
-,Para [Str "M.A.\160\&2007"]
-,Para [Str "B.",Space,Str "Williams"]
-,Header 2 ("callout",[],[]) [Str "Callout"]
-,Para [Str "Simple."]
-,BulletList
- [[Para [Str "A",Space,Code ("",[],[]) "__letrec",Space,Str "is",Space,Str "equivalent",Space,Str "to",Space,Str "a",Space,Str "normal",SoftBreak,Str "Haskell",Space,Str "LET."]]
- ,[Para [Str "GHC",Space,Str "compiled",Space,Str "the",Space,Str "body",Space,Str "of",Space,Str "our",Space,Str "list",Space,Str "comprehension",Space,Str "into",SoftBreak,Str "a",Space,Str "loop",Space,Str "named",Space,Code ("",[],[]) "go_s1YC",Str "."]]
- ,[Para [Str "If",Space,Str "our",Space,Str "CASE",Space,Str "expression",Space,Str "matches",Space,Str "the",Space,Str "empty",Space,Str "list,",Space,Str "we",SoftBreak,Str "return",Space,Str "the",Space,Str "empty",Space,Str "list.",Space,Str "This",Space,Str "is",Space,Str "reassuringly",SoftBreak,Str "familiar."]]]
-,Header 1 ("definition-lists",[],[]) [Str "Definition",Space,Str "Lists"]
-,DefinitionList
- [([Str "apple"],
-   [[Para [Str "red",Space,Str "fruit"]]])
- ,([Str "orange"],
-   [[Para [Str "orange",Space,Str "fruit"]]])
- ,([Str "banana"],
-   [[Para [Str "yellow",Space,Str "fruit"]]])]
-,Para [Str "Multiple",Space,Str "blocks",Space,Str "with",Space,Str "italics:"]
-,DefinitionList
- [([Emph [Str "apple"]],
-   [[Para [Str "red",Space,Str "fruit"]
-    ,Para [Str "contains",Space,Str "seeds,",Space,Str "crisp,",Space,Str "pleasant",Space,Str "to",Space,Str "taste"]]])
- ,([Emph [Str "orange"]],
-   [[Para [Str "orange",Space,Str "fruit"]
-    ,CodeBlock ("",[],[]) "{ orange code block }"
-    ,BlockQuote
-     [Para [Str "orange",Space,Str "block",Space,Str "quote"]]]])]
-,Para [Str "Multiple",Space,Str "definitions,",Space,Str "loose:"]
-,DefinitionList
- [([Str "apple"],
-   [[Para [Str "red",Space,Str "fruit"]]
-   ,[Para [Str "computer"]]])
- ,([Str "orange"],
-   [[Para [Str "orange",Space,Str "fruit"]]
-   ,[Para [Str "bank"]]])]
-,Para [Str "Blank",Space,Str "line",Space,Str "after",Space,Str "term,",Space,Str "indented",Space,Str "marker,",Space,Str "alternate",Space,Str "markers:"]
-,DefinitionList
- [([Str "apple"],
-   [[Para [Str "red",Space,Str "fruit"]]
-   ,[Para [Str "computer"]]])
- ,([Str "orange"],
-   [[Para [Str "orange",Space,Str "fruit"]
-    ,OrderedList (1,Decimal,DefaultDelim)
-     [[Para [Str "sublist"]]
-     ,[Para [Str "sublist"]]]]])]
-,Header 1 ("inline-markup",[],[]) [Str "Inline",Space,Str "Markup"]
-,Para [Str "This",Space,Str "is",Space,Emph [Str "emphasized"],Str ",",Space,Str "and",Space,Str "so",Space,Emph [Str "is",SoftBreak,Str "this"],Str "."]
-,Para [Str "This",Space,Str "is",Space,Strong [Str "strong"],Str ",",Space,Str "and",Space,Str "so",SoftBreak,Strong [Str "is",Space,Str "this"],Str "."]
-,Para [Str "An",Space,Emph [Link ("",[],[]) [Str "emphasized",Space,Str "link"] ("/url","")],Str "."]
-,Para [Strong [Emph [Str "This",Space,Str "is",Space,Str "strong",Space,Str "and",SoftBreak,Str "em."]]]
-,Para [Str "So",Space,Str "is",Space,Strong [Emph [Str "this"]],Space,Str "word."]
-,Para [Strong [Emph [Str "This",Space,Str "is",Space,Str "strong",Space,Str "and",SoftBreak,Str "em."]]]
-,Para [Str "So",Space,Str "is",Space,Strong [Emph [Str "this"]],Space,Str "word."]
-,Para [Str "This",Space,Str "is",Space,Str "code:",Space,Code ("",[],[]) ">",Str ",",Space,Code ("",[],[]) "$",Str ",",SoftBreak,Code ("",[],[]) "\\",Str ",",Space,Code ("",[],[]) "\\$",Str ",",SoftBreak,Code ("",[],[]) "<html>",Str "."]
-,Para [Str "More",Space,Str "code:",Space,Code ("",[],[]) "Class",Space,Str "and",Space,Code ("",[],[]) "Type"]
-,Para [Strikeout [Str "This",Space,Str "is",SoftBreak,Emph [Str "strikeout"],Str "."]]
-,Para [Str "Superscripts:",Space,Str "a",Superscript [Str "bc"],Str "d",SoftBreak,Str "a",Superscript [Emph [Str "hello"]],SoftBreak,Str "a",Superscript [Str "hello\160there"],Str "."]
-,Para [Str "Subscripts:",Space,Str "H",Subscript [Str "2"],Str "O,",Space,Str "H",Subscript [Str "23"],Str "O,",SoftBreak,Str "H",Subscript [Str "many\160of\160them"],Str "O."]
-,Para [Str "These",Space,Str "should",Space,Str "not",Space,Str "be",Space,Str "superscripts",Space,Str "or",Space,Str "subscripts,",Space,Str "because",Space,Str "of",Space,Str "the",Space,Str "unescaped",SoftBreak,Str "spaces:",Space,Str "a^b",Space,Str "c^d,",Space,Str "a~b",Space,Str "c~d."]
-,Header 1 ("smart-quotes-ellipses-dashes",[],[]) [Str "Smart",Space,Str "quotes,",Space,Str "ellipses,",Space,Str "dashes"]
-,Para [Quoted DoubleQuote [Str "Hello,"],Space,Str "said",Space,Str "the",Space,Str "spider.",Space,Quoted DoubleQuote [Quoted SingleQuote [Str "Shelob"],Space,Str "is",Space,Str "my",SoftBreak,Str "name."]]
-,Para [Quoted DoubleQuote [Str "A"],Str ",",Space,Quoted DoubleQuote [Str "B"],Str ",",Space,Str "and",Space,Quoted DoubleQuote [Str "C"],Space,Str "are",Space,Str "letters."]
-,Para [Quoted DoubleQuote [Str "He",Space,Str "said,",Space,Quoted SingleQuote [Str "I",Space,Str "want",Space,Str "to",Space,Str "go."]],Space,Str "Were",Space,Str "you",Space,Str "alive",Space,Str "in",Space,Str "the",SoftBreak,Str "70\8217s?"]
-,Para [Str "Some",Space,Str "dashes:",Space,Str "one\8212two",Space,Str "\8212",Space,Str "three\8212four",Space,Str "\8212",Space,Str "five."]
-,Para [Str "Dashes",Space,Str "between",Space,Str "numbers:",Space,Str "5\8211\&7,",Space,Str "255\8211\&66,",Space,Str "1987\8211\&1999."]
-,Para [Str "Ellipses\8230and\8230and\8230."]
-,Header 1 ("math",[],[]) []
-,Para [Math DisplayMath "e = mc^{2}",Math DisplayMath "1",SoftBreak,Math InlineMath "e = mc^{2}",SoftBreak,Math DisplayMath "e = mc^{2}"]
-,Header 1 ("special-characters",[],[]) [Str "Special",Space,Str "Characters"]
-,Para [Str "Here",Space,Str "is",Space,Str "some",Space,Str "unicode:"]
-,BulletList
- [[Para [Str "I",Space,Str "hat:",Space,Str "\206"]]
- ,[Para [Str "o",Space,Str "umlaut:",Space,Str "\246"]]
- ,[Para [Str "section:",Space,Str "\167"]]
- ,[Para [Str "set",Space,Str "membership:",Space,Str "\8712"]]
- ,[Para [Str "copyright:",Space,Str "\169"]]]
-,Para [Str "AT&T",Space,Str "has",Space,Str "an",Space,Str "ampersand",Space,Str "in",Space,Str "their",Space,Str "name."]
-,Para [Str "AT&T",Space,Str "is",Space,Str "another",Space,Str "way",Space,Str "to",Space,Str "write",Space,Str "it."]
-,Para [Str "This",Space,Str "&",Space,Str "that."]
-,Para [Str "4",Space,Str "<",Space,Str "5."]
-,Para [Str "6",Space,Str ">",Space,Str "5."]
-,Para [Str "Backslash:",Space,Str "\\"]
-,Para [Str "Backtick:",Space,Str "`"]
-,Para [Str "Asterisk:",Space,Str "*"]
-,Para [Str "Underscore:",Space,Str "_"]
-,Para [Str "Left",Space,Str "brace:",Space,Str "{"]
-,Para [Str "Right",Space,Str "brace:",Space,Str "}"]
-,Para [Str "Left",Space,Str "bracket:",Space,Str "["]
-,Para [Str "Right",Space,Str "bracket:",Space,Str "]"]
-,Para [Str "Left",Space,Str "paren:",Space,Str "("]
-,Para [Str "Right",Space,Str "paren:",Space,Str ")"]
-,Para [Str "Greater-than:",Space,Str ">"]
-,Para [Str "Hash:",Space,Str "#"]
-,Para [Str "Period:",Space,Str "."]
-,Para [Str "Bang:",Space,Str "!"]
-,Para [Str "Plus:",Space,Str "+"]
-,Para [Str "Minus:",Space,Str "-"]
-,Header 1 ("links",[],[]) [Str "Links"]
-,Header 2 ("explicit",[],[]) [Str "Explicit"]
-,Para [Str "Just",Space,Str "a",Space,Link ("",[],[]) [Str "URL"] ("/url/",""),Str "."]
-,Para [Link ("",[],[]) [Str "URL",Space,Str "and",Space,Str "title"] ("/url/",""),Str "."]
-,Para [Link ("",[],[]) [Str "URL",Space,Str "and",Space,Str "title"] ("/url/",""),Str "."]
-,Para [Link ("",[],[]) [Str "URL",Space,Str "and",Space,Str "title"] ("/url/",""),Str "."]
-,Para [Link ("",[],[]) [Str "URL",Space,Str "and",Space,Str "title"] ("/url/","")]
-,Para [Link ("",[],[]) [Str "URL",Space,Str "and",Space,Str "title"] ("/url/","")]
-,Para [Link ("",[],[]) [Str "with_underscore"] ("/url/with_underscore","")]
-,Para [Link ("",[],[]) [Str "nobody@nowhere.net"] ("mailto:nobody@nowhere.net","")]
-,Para [Link ("",[],[]) [Str "Empty"] ("",""),Str "."]
-,Header 2 ("reference",[],[]) [Str "Reference"]
-,Para [Str "Foo",Space,Link ("",[],[]) [Str "bar"] ("/url/",""),Str "."]
-,Para [Str "Foo",Space,Link ("",[],[]) [Str "bar"] ("/url/",""),Str "."]
-,Para [Str "Foo",Space,Link ("",[],[]) [Str "bar"] ("/url/",""),Str "."]
-,Para [Str "With",Space,Link ("",[],[]) [Str "embedded",Space,Str "[brackets]"] ("/url/",""),Str "."]
-,Para [Link ("",[],[]) [Str "b"] ("/url/",""),Space,Str "by",Space,Str "itself",Space,Str "should",Space,Str "be",Space,Str "a",Space,Str "link."]
-,Para [Str "Indented",Space,Link ("",[],[]) [Str "once"] ("/url",""),Str "."]
-,Para [Str "Indented",Space,Link ("",[],[]) [Str "twice"] ("/url",""),Str "."]
-,Para [Str "Indented",Space,Link ("",[],[]) [Str "thrice"] ("/url",""),Str "."]
-,Para [Str "This",Space,Str "should",Space,Str "[not][]",Space,Str "be",Space,Str "a",Space,Str "link."]
-,CodeBlock ("",[],[]) "[not]: /url"
-,Para [Str "Foo",Space,Link ("",[],[]) [Str "bar"] ("/url/",""),Str "."]
-,Para [Str "Foo",Space,Link ("",[],[]) [Str "biz"] ("/url/",""),Str "."]
-,Header 2 ("with-ampersands",[],[]) [Str "With",Space,Str "ampersands"]
-,Para [Str "Here\8217s",Space,Str "a",Space,Link ("",[],[]) [Str "link",Space,Str "with",Space,Str "an",SoftBreak,Str "ampersand",Space,Str "in",Space,Str "the",Space,Str "URL"] ("http://example.com/?foo=1&bar=2",""),Str "."]
-,Para [Str "Here\8217s",Space,Str "a",Space,Str "link",Space,Str "with",Space,Str "an",Space,Str "amersand",Space,Str "in",Space,Str "the",Space,Str "link",Space,Str "text:",SoftBreak,Link ("",[],[]) [Str "AT&T"] ("http://att.com/",""),Str "."]
-,Para [Str "Here\8217s",Space,Str "an",Space,Link ("",[],[]) [Str "inline",Space,Str "link"] ("/script?foo=1&bar=2",""),Str "."]
-,Para [Str "Here\8217s",Space,Str "an",Space,Link ("",[],[]) [Str "inline",Space,Str "link",Space,Str "in",Space,Str "pointy",SoftBreak,Str "braces"] ("/script?foo=1&bar=2",""),Str "."]
-,Header 2 ("autolinks",[],[]) [Str "Autolinks"]
-,Para [Str "With",Space,Str "an",Space,Str "ampersand:",SoftBreak,Link ("",[],[]) [Str "http://example.com/?foo=1&bar=2"] ("http://example.com/?foo=1&bar=2","")]
-,BulletList
- [[Para [Str "In",Space,Str "a",Space,Str "list?"]]
- ,[Para [Link ("",[],[]) [Str "http://example.com/"] ("http://example.com/","")]]
- ,[Para [Str "It",Space,Str "should."]]]
-,Para [Str "An",Space,Str "e-mail",Space,Str "address:",Space,Link ("",[],[]) [Str "nobody@nowhere.net"] ("mailto:nobody@nowhere.net","")]
-,BlockQuote
- [Para [Str "Blockquoted:",SoftBreak,Link ("",[],[]) [Str "http://example.com/"] ("http://example.com/","")]]
-,Para [Str "Auto-links",Space,Str "should",Space,Str "not",Space,Str "occur",Space,Str "here:",SoftBreak,Code ("",[],[]) "<http://example.com/>"]
-,CodeBlock ("",[],[]) "or here: <http://example.com/>"
-,Header 1 ("images",[],[]) [Str "Images"]
-,Para [Str "From",Space,Quoted DoubleQuote [Str "Voyage",Space,Str "dans",Space,Str "la",Space,Str "Lune"],Space,Str "by",Space,Str "Georges",Space,Str "Melies",Space,Str "(1902):"]
-,Para [Image ("",[],[]) [Str "lalune",Space,Str "fig",Space,Str "caption"] ("lalune.jpg","fig:")]
-,Para [Str "Here",Space,Str "is",Space,Str "a",Space,Str "movie",Space,Image ("",[],[]) [] ("movie.jpg",""),Space,Str "icon.",SoftBreak,Str "And",Space,Str "here",Space,Str "a",Space,Str "second",Space,Str "movie",Space,Image ("",[],[]) [Str "alt",Space,Str "text"] ("movie.jpg",""),Space,Str "icon.",SoftBreak,Str "And",Space,Str "here",Space,Str "a",Space,Str "third",Space,Str "movie",Space,Image ("",[],[]) [Str "alt",Space,Str "text"] ("movie.jpg",""),Space,Str "icon."]
-,Para [Image ("",[],[]) [Str "lalune",Space,Str "no",Space,Str "figure",Space,Str "alt",Space,Str "text"] ("lalune.jpg","")]
-,Header 1 ("footnotes",[],[]) [Str "Footnotes"]
-,Para [Str "Here",Space,Str "is",Space,Str "a",Space,Str "footnote",Space,Str "reference,",Note [Para [Str "Here",Space,Str "is",Space,Str "the",Space,Str "footnote.",Space,Str "It",Space,Str "can",Space,Str "go",Space,Str "anywhere",Space,Str "after",Space,Str "the",Space,Str "footnote",Space,Str "reference.",SoftBreak,Str "It",Space,Str "need",Space,Str "not",Space,Str "be",Space,Str "placed",Space,Str "at",Space,Str "the",Space,Str "end",Space,Str "of",Space,Str "the",Space,Str "document."]],Space,Str "and",Space,Str "another.",Note [Para [Str "Here\8217s",Space,Str "the",Space,Str "long",Space,Str "note.",Space,Str "This",Space,Str "one",Space,Str "contains",Space,Str "multiple",Space,Str "blocks."],Para [Str "Subsequent",Space,Str "blocks",Space,Str "are",Space,Str "indented",Space,Str "to",Space,Str "show",Space,Str "that",Space,Str "they",Space,Str "belong",Space,Str "to",Space,Str "the",SoftBreak,Str "footnote",Space,Str "(as",Space,Str "with",Space,Str "list",Space,Str "items)."],CodeBlock ("",[],[]) "  { <code> }",Para [Str "If",Space,Str "you",Space,Str "want,",Space,Str "you",Space,Str "can",Space,Str "indent",Space,Str "every",Space,Str "line,",Space,Str "but",Space,Str "you",Space,Str "can",Space,Str "also",Space,Str "be",Space,Str "lazy",Space,Str "and",SoftBreak,Str "just",Space,Str "indent",Space,Str "the",Space,Str "first",Space,Str "line",Space,Str "of",Space,Str "each",Space,Str "block."]],Space,Str "This",Space,Str "should",Space,Emph [Str "not"],Space,Str "be",Space,Str "a",Space,Str "footnote",Space,Str "reference,",SoftBreak,Str "because",Space,Str "it",Space,Str "contains",Space,Str "a",Space,Str "space.[^my",Space,Str "note]",Space,Str "Here",Space,Str "is",Space,Str "an",Space,Str "inline",Space,Str "note.",Note [Para [Str "This",Space,Str "is",Space,Emph [Str "easier"],Space,Str "to",Space,Str "type.",Space,Str "Inline",Space,Str "notes",Space,Str "may",Space,Str "contain",SoftBreak,Link ("",[],[]) [Str "links"] ("http://google.com",""),Space,Str "and",Space,Code ("",[],[]) "]",SoftBreak,Str "verbatim",Space,Str "characters,",Space,Str "as",Space,Str "well",Space,Str "as",Space,Str "[bracketed",Space,Str "text]."]]]
-,BlockQuote
- [Para [Str "Notes",Space,Str "can",Space,Str "go",Space,Str "in",Space,Str "quotes.",Note [Para [Str "In",Space,Str "quote."]]]]
-,OrderedList (1,Decimal,DefaultDelim)
- [[Para [Str "And",Space,Str "in",Space,Str "list",Space,Str "items.",Note [Para [Str "In",Space,Str "list."]]]]]
-,Para [Str "This",Space,Str "paragraph",Space,Str "should",Space,Str "not",Space,Str "be",Space,Str "part",Space,Str "of",Space,Str "the",Space,Str "note,",Space,Str "as",Space,Str "it",Space,Str "is",Space,Str "not",Space,Str "indented."]
-,Header 1 ("tables",[],[]) [Str "Tables"]
-,Para [Str "Simple",Space,Str "table",Space,Str "with",Space,Str "caption:"]
-,Table [Str "Demonstration",Space,Str "of",Space,Str "simple",Space,Str "table",Space,Str "syntax."] [AlignRight,AlignLeft,AlignCenter,AlignLeft] [0.0,0.0,0.0,0.0]
- [[Plain [Str "Right"]]
- ,[Plain [Str "Left"]]
- ,[Plain [Str "Center"]]
- ,[Plain [Str "Default"]]]
- [[[Plain [Str "12"]]
-  ,[Plain [Str "12"]]
-  ,[Plain [Str "12"]]
-  ,[Plain [Str "12"]]]
- ,[[Plain [Str "123"]]
-  ,[Plain [Str "123"]]
-  ,[Plain [Str "123"]]
-  ,[Plain [Str "123"]]]
- ,[[Plain [Str "1"]]
-  ,[Plain [Str "1"]]
-  ,[Plain [Str "1"]]
-  ,[Plain [Str "1"]]]]
-,Para [Str "Simple",Space,Str "table",Space,Str "without",Space,Str "caption:"]
-,Table [] [AlignRight,AlignLeft,AlignCenter,AlignLeft] [0.0,0.0,0.0,0.0]
- [[Plain [Str "Right"]]
- ,[Plain [Str "Left"]]
- ,[Plain [Str "Center"]]
- ,[Plain [Str "Default"]]]
- [[[Plain [Str "12"]]
-  ,[Plain [Str "12"]]
-  ,[Plain [Str "12"]]
-  ,[Plain [Str "12"]]]
- ,[[Plain [Str "123"]]
-  ,[Plain [Str "123"]]
-  ,[Plain [Str "123"]]
-  ,[Plain [Str "123"]]]
- ,[[Plain [Str "1"]]
-  ,[Plain [Str "1"]]
-  ,[Plain [Str "1"]]
-  ,[Plain [Str "1"]]]]
-,Para [Str "Simple",Space,Str "table",Space,Str "indented",Space,Str "two",Space,Str "spaces:"]
-,Table [Str "Demonstration",Space,Str "of",Space,Str "simple",Space,Str "table",Space,Str "syntax."] [AlignRight,AlignLeft,AlignCenter,AlignLeft] [0.0,0.0,0.0,0.0]
- [[Plain [Str "Right"]]
- ,[Plain [Str "Left"]]
- ,[Plain [Str "Center"]]
- ,[Plain [Str "Default"]]]
- [[[Plain [Str "12"]]
-  ,[Plain [Str "12"]]
-  ,[Plain [Str "12"]]
-  ,[Plain [Str "12"]]]
- ,[[Plain [Str "123"]]
-  ,[Plain [Str "123"]]
-  ,[Plain [Str "123"]]
-  ,[Plain [Str "123"]]]
- ,[[Plain [Str "1"]]
-  ,[Plain [Str "1"]]
-  ,[Plain [Str "1"]]
-  ,[Plain [Str "1"]]]]
-,Para [Str "Multiline",Space,Str "table",Space,Str "with",Space,Str "caption:"]
-,Table [Str "Here's",Space,Str "the",Space,Str "caption.",Space,Str "It",Space,Str "may",Space,Str "span",Space,Str "multiple",Space,Str "lines."] [AlignCenter,AlignLeft,AlignRight,AlignLeft] [0.2,0.2,0.3,0.3]
- [[Plain [Str "Centered",Space,Str "Header"]]
- ,[Plain [Str "Left",Space,Str "Aligned"]]
- ,[Plain [Str "Right",Space,Str "Aligned"]]
- ,[Plain [Str "Default",Space,Str "aligned"]]]
- [[[Plain [Str "First"]]
-  ,[Plain [Str "row"]]
-  ,[Plain [Str "12.0"]]
-  ,[Plain [Str "Example",Space,Str "of",Space,Str "a",Space,Str "row",Space,Str "that",Space,Str "spans",Space,Str "multiple",Space,Str "lines."]]]
- ,[[Plain [Str "Second"]]
-  ,[Plain [Str "row"]]
-  ,[Plain [Str "5.0"]]
-  ,[Plain [Str "Here's",Space,Str "another",Space,Str "one.",Space,Str "Note",Space,Str "the",Space,Str "blank",Space,Str "line",Space,Str "between",Space,Str "rows."]]]]
-,Para [Str "Multiline",Space,Str "table",Space,Str "without",Space,Str "caption:"]
-,Table [] [AlignCenter,AlignLeft,AlignRight,AlignLeft] [0.1,0.2,0.3,0.4]
- [[Plain [Str "Centered",Space,Str "Header"]]
- ,[Plain [Str "Left",Space,Str "Aligned"]]
- ,[Plain [Str "Right",Space,Str "Aligned"]]
- ,[Plain [Str "Default",Space,Str "aligned"]]]
- [[[Plain [Str "First"]]
-  ,[Plain [Str "row"]]
-  ,[Plain [Str "12.0"]]
-  ,[Plain [Str "Example",Space,Str "of",Space,Str "a",Space,Str "row",Space,Str "that",Space,Str "spans",Space,Str "multiple",Space,Str "lines."]]]
- ,[[Plain [Str "Second"]]
-  ,[Plain [Str "row"]]
-  ,[Plain [Str "5.0"]]
-  ,[Plain [Str "Here's",Space,Str "another",Space,Str "one.",Space,Str "Note",Space,Str "the",Space,Str "blank",Space,Str "line",Space,Str "between",Space,Str "rows."]]]]
-,Para [Str "Table",Space,Str "without",Space,Str "column",Space,Str "headers:"]
-,Table [] [AlignRight,AlignLeft,AlignCenter,AlignRight] [0.0,0.0,0.0,0.0]
- [[]
- ,[]
- ,[]
- ,[]]
- [[[Plain [Str "12"]]
-  ,[Plain [Str "12"]]
-  ,[Plain [Str "12"]]
-  ,[Plain [Str "12"]]]
- ,[[Plain [Str "123"]]
-  ,[Plain [Str "123"]]
-  ,[Plain [Str "123"]]
-  ,[Plain [Str "123"]]]
- ,[[Plain [Str "1"]]
-  ,[Plain [Str "1"]]
-  ,[Plain [Str "1"]]
-  ,[Plain [Str "1"]]]]
-,Para [Str "Multiline",Space,Str "table",Space,Str "without",Space,Str "column",Space,Str "headers:"]
-,Table [] [AlignCenter,AlignLeft,AlignRight,AlignLeft] [0.25,0.25,0.25,0.25]
- [[]
- ,[]
- ,[]
- ,[]]
- [[[Plain [Str "First"]]
-  ,[Plain [Str "row"]]
-  ,[Plain [Str "12.0"]]
-  ,[Plain [Str "Example",Space,Str "of",Space,Str "a",Space,Str "row",Space,Str "that",Space,Str "spans",Space,Str "multiple",Space,Str "lines."]]]
- ,[[Plain [Str "Second"]]
-  ,[Plain [Str "row"]]
-  ,[Plain [Str "5.0"]]
-  ,[Plain [Str "Here's",Space,Str "another",Space,Str "one.",Space,Str "Note",Space,Str "the",Space,Str "blank",Space,Str "line",Space,Str "between",Space,Str "rows."]]]]]
+Pandoc
+  Meta
+    { unMeta =
+        fromList
+          [ ( "author"
+            , MetaList
+                [ MetaInlines [ Str "John" , Space , Str "MacFarlane" ]
+                , MetaInlines [ Str "Anonymous" ]
+                ]
+            )
+          , ( "date"
+            , MetaInlines
+                [ Str "July" , Space , Str "17," , Space , Str "2006" ]
+            )
+          , ( "title"
+            , MetaInlines
+                [ Str "Pandoc"
+                , Space
+                , Str "Test"
+                , Space
+                , Str "Suite"
+                ]
+            )
+          ]
+    }
+  [ Para
+      [ Str "This"
+      , Space
+      , Str "is"
+      , Space
+      , Str "a"
+      , Space
+      , Str "set"
+      , Space
+      , Str "of"
+      , Space
+      , Str "tests"
+      , Space
+      , Str "for"
+      , Space
+      , Str "pandoc."
+      , Space
+      , Str "Most"
+      , Space
+      , Str "of"
+      , Space
+      , Str "them"
+      , Space
+      , Str "are"
+      , Space
+      , Str "adapted"
+      , Space
+      , Str "from"
+      , Space
+      , Str "John"
+      , SoftBreak
+      , Str "Gruber\8217s"
+      , Space
+      , Str "markdown"
+      , Space
+      , Str "test"
+      , Space
+      , Str "suite."
+      ]
+  , Header
+      1
+      ( "headers" , [] , [ ( "role" , "sect1role" ) ] )
+      [ Str "Headers" ]
+  , Header
+      2
+      ( "level-2-with-an-embedded-link"
+      , []
+      , [ ( "role" , "sect2role" ) ]
+      )
+      [ Str "Level"
+      , Space
+      , Str "2"
+      , Space
+      , Str "with"
+      , Space
+      , Str "an"
+      , Space
+      , Link
+          ( "" , [] , [] )
+          [ Str "embedded" , Space , Str "link" ]
+          ( "/url" , "" )
+      ]
+  , Header
+      3
+      ( "level-3-with-emphasis" , [] , [] )
+      [ Str "Level"
+      , Space
+      , Str "3"
+      , Space
+      , Str "with"
+      , Space
+      , Emph [ Str "emphasis" ]
+      ]
+  , Header
+      4 ( "level-4" , [] , [] ) [ Str "Level" , Space , Str "4" ]
+  , Header
+      5 ( "level-5" , [] , [] ) [ Str "Level" , Space , Str "5" ]
+  , Para [ Str "Hi." ]
+  , Header
+      1 ( "level-1" , [] , [] ) [ Str "Level" , Space , Str "1" ]
+  , Header
+      2
+      ( "level-2-with-emphasis" , [] , [] )
+      [ Str "Level"
+      , Space
+      , Str "2"
+      , Space
+      , Str "with"
+      , Space
+      , Emph [ Str "emphasis" ]
+      ]
+  , Header
+      3 ( "level-3" , [] , [] ) [ Str "Level" , Space , Str "3" ]
+  , Para
+      [ Str "with"
+      , Space
+      , Str "no"
+      , Space
+      , Str "blank"
+      , Space
+      , Str "line"
+      ]
+  , Header
+      4
+      ( "" , [ "unnumbered" ] , [] )
+      [ Str "Level" , Space , Str "4" ]
+  , Para
+      [ Str "An"
+      , Space
+      , Str "unnumbered"
+      , Space
+      , Str "section."
+      ]
+  , Header
+      2 ( "level-2" , [] , [] ) [ Str "Level" , Space , Str "2" ]
+  , Para
+      [ Str "with"
+      , Space
+      , Str "no"
+      , Space
+      , Str "blank"
+      , Space
+      , Str "line"
+      ]
+  , Header 1 ( "paragraphs" , [] , [] ) [ Str "Paragraphs" ]
+  , Para
+      [ Str "Here\8217s"
+      , Space
+      , Str "a"
+      , Space
+      , Str "regular"
+      , Space
+      , Str "paragraph."
+      ]
+  , Div
+      ( ""
+      , []
+      , [ ( "wrapper" , "1" ) , ( "role" , "pararole" ) ]
+      )
+      [ Para
+          [ Str "And"
+          , Space
+          , Str "here\8217s"
+          , Space
+          , Str "a"
+          , Space
+          , Str "regular"
+          , Space
+          , Str "paragraph"
+          , Space
+          , Str "with"
+          , Space
+          , Str "a"
+          , Space
+          , Str "role."
+          ]
+      ]
+  , Para
+      [ Str "In"
+      , Space
+      , Str "Markdown"
+      , Space
+      , Str "1.0.0"
+      , Space
+      , Str "and"
+      , Space
+      , Str "earlier."
+      , Space
+      , Str "Version"
+      , Space
+      , Str "8."
+      , Space
+      , Str "This"
+      , Space
+      , Str "line"
+      , Space
+      , Str "turns"
+      , Space
+      , Str "into"
+      , Space
+      , Str "a"
+      , Space
+      , Str "list"
+      , SoftBreak
+      , Str "item."
+      , Space
+      , Str "Because"
+      , Space
+      , Str "a"
+      , Space
+      , Str "hard-wrapped"
+      , Space
+      , Str "line"
+      , Space
+      , Str "in"
+      , Space
+      , Str "the"
+      , Space
+      , Str "middle"
+      , Space
+      , Str "of"
+      , Space
+      , Str "a"
+      , Space
+      , Str "paragraph"
+      , Space
+      , Str "looked"
+      , Space
+      , Str "like"
+      , SoftBreak
+      , Str "a"
+      , Space
+      , Str "list"
+      , Space
+      , Str "item."
+      ]
+  , Para
+      [ Str "Here\8217s"
+      , Space
+      , Str "one"
+      , Space
+      , Str "with"
+      , Space
+      , Str "a"
+      , Space
+      , Str "bullet."
+      , Space
+      , Str "*"
+      , Space
+      , Str "criminey."
+      ]
+  , Header
+      1
+      ( "block-quotes" , [] , [] )
+      [ Str "Block" , Space , Str "Quotes" ]
+  , Para [ Str "E-mail" , Space , Str "style:" ]
+  , BlockQuote
+      [ Para
+          [ Str "This"
+          , Space
+          , Str "is"
+          , Space
+          , Str "a"
+          , Space
+          , Str "block"
+          , Space
+          , Str "quote."
+          , Space
+          , Str "It"
+          , Space
+          , Str "is"
+          , Space
+          , Str "pretty"
+          , Space
+          , Str "short."
+          ]
+      ]
+  , Div
+      ( ""
+      , []
+      , [ ( "wrapper" , "1" ) , ( "role" , "roleblockquote" ) ]
+      )
+      [ BlockQuote
+          [ Para
+              [ Str "This"
+              , Space
+              , Str "is"
+              , Space
+              , Str "a"
+              , Space
+              , Str "block"
+              , Space
+              , Str "quote"
+              , Space
+              , Str "with"
+              , Space
+              , Str "a"
+              , Space
+              , Str "role."
+              ]
+          ]
+      ]
+  , BlockQuote
+      [ Para
+          [ Str "Code"
+          , Space
+          , Str "in"
+          , Space
+          , Str "a"
+          , Space
+          , Str "block"
+          , Space
+          , Str "quote:"
+          ]
+      , CodeBlock
+          ( "" , [] , [] ) "sub status {\n    print \"working\";\n}"
+      , CodeBlock
+          ( "" , [ "numberLines" ] , [] )
+          "sub status {\n    print \"working with line numbers\";\n}"
+      , CodeBlock ( "" , [] , [] ) "% ls"
+      , Para [ Str "A" , Space , Str "list:" ]
+      , OrderedList
+          ( 1 , Decimal , DefaultDelim )
+          [ [ Para [ Str "item" , Space , Str "one" ] ]
+          , [ Para [ Str "item" , Space , Str "two" ] ]
+          ]
+      , Para
+          [ Str "Nested"
+          , Space
+          , Str "block"
+          , Space
+          , Str "quotes:"
+          ]
+      , BlockQuote [ Para [ Str "nested" ] ]
+      , BlockQuote [ Para [ Str "nested" ] ]
+      ]
+  , Para
+      [ Str "This"
+      , Space
+      , Str "should"
+      , Space
+      , Str "not"
+      , Space
+      , Str "be"
+      , Space
+      , Str "a"
+      , Space
+      , Str "block"
+      , Space
+      , Str "quote:"
+      , Space
+      , Str "2"
+      , Space
+      , Str ">"
+      , Space
+      , Str "1."
+      ]
+  , Para
+      [ Str "And"
+      , Space
+      , Str "a"
+      , Space
+      , Str "following"
+      , Space
+      , Str "paragraph."
+      ]
+  , Header
+      1
+      ( "code-blocks" , [] , [] )
+      [ Str "Code" , Space , Str "Blocks" ]
+  , Para [ Str "Code:" ]
+  , CodeBlock
+      ( "" , [] , [] )
+      "---- (should be four hyphens)\n\nsub status {\n    print \"working\";\n}\n\nthis code block is indented by one tab"
+  , Para [ Str "And:" ]
+  , CodeBlock
+      ( "" , [] , [] )
+      "    this code block is indented by two tabs\n\nThese should not be escaped:  \\$ \\\\ \\> \\[ \\{"
+  , Header 1 ( "lists" , [] , [] ) [ Str "Lists" ]
+  , Header 2 ( "unordered" , [] , [] ) [ Str "Unordered" ]
+  , Para [ Str "Asterisks" , Space , Str "loose:" ]
+  , BulletList
+      [ [ Para [ Str "asterisk" , Space , Str "1" ] ]
+      , [ Para [ Str "asterisk" , Space , Str "2" ] ]
+      , [ Para [ Str "asterisk" , Space , Str "3" ] ]
+      ]
+  , Para [ Str "Asterisks" , Space , Str "tight:" ]
+  , BulletList
+      [ [ Plain [ Str "Plus" , Space , Str "1" ] ]
+      , [ Plain [ Str "Plus" , Space , Str "2" ] ]
+      , [ Plain [ Str "Plus" , Space , Str "3" ] ]
+      ]
+  , Header 2 ( "ordered" , [] , [] ) [ Str "Ordered" ]
+  , OrderedList
+      ( 1 , Decimal , DefaultDelim )
+      [ [ Para [ Str "First" ] ]
+      , [ Para [ Str "Second" ] ]
+      , [ Para [ Str "Third" ] ]
+      ]
+  , Para [ Str "with" , Space , Str "role:" ]
+  , Div
+      ( ""
+      , []
+      , [ ( "wrapper" , "1" ) , ( "role" , "listrole" ) ]
+      )
+      [ OrderedList
+          ( 1 , Decimal , DefaultDelim )
+          [ [ Para [ Str "First" ] ]
+          , [ Para [ Str "Second" ] ]
+          , [ Para [ Str "Third" ] ]
+          ]
+      ]
+  , Para [ Str "and" , Space , Str "tight:" ]
+  , OrderedList
+      ( 1 , Decimal , DefaultDelim )
+      [ [ Plain [ Str "One" ] ]
+      , [ Plain [ Str "Two" ] ]
+      , [ Plain [ Str "Three" ] ]
+      ]
+  , Para [ Str "Multiple" , Space , Str "paragraphs:" ]
+  , OrderedList
+      ( 1 , Decimal , DefaultDelim )
+      [ [ 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."
+            ]
+        ]
+      , [ Para [ Str "Item" , Space , Str "2." ] ]
+      , [ Para [ Str "Item" , Space , Str "3." ] ]
+      ]
+  , Header 2 ( "nested" , [] , [] ) [ Str "Nested" ]
+  , BulletList
+      [ [ Para [ Str "Tab" ]
+        , BulletList
+            [ [ Para [ Str "Tab" ]
+              , BulletList [ [ Para [ Str "Tab" ] ] ]
+              ]
+            ]
+        ]
+      ]
+  , Para [ Str "Here\8217s" , Space , Str "another:" ]
+  , OrderedList
+      ( 1 , Decimal , DefaultDelim )
+      [ [ Para [ Str "First" ] ]
+      , [ Para [ Str "Second:" ]
+        , BulletList
+            [ [ Para [ Str "Fee" ] ]
+            , [ Para [ Str "Fie" ] ]
+            , [ Para [ Str "Foe" ] ]
+            ]
+        ]
+      , [ Para [ Str "Third" ] ]
+      ]
+  , Para
+      [ Str "Same"
+      , Space
+      , Str "thing"
+      , Space
+      , Str "but"
+      , Space
+      , Str "with"
+      , Space
+      , Str "paragraphs:"
+      ]
+  , OrderedList
+      ( 1 , Decimal , DefaultDelim )
+      [ [ Para [ Str "First" ] ]
+      , [ Para [ Str "Second:" ]
+        , BulletList
+            [ [ Para [ Str "Fee" ] ]
+            , [ Para [ Str "Fie" ] ]
+            , [ Para [ Str "Foe" ] ]
+            ]
+        ]
+      , [ Para [ Str "Third" ] ]
+      ]
+  , Header
+      2
+      ( "tabs-and-spaces" , [] , [] )
+      [ Str "Tabs" , Space , Str "and" , Space , Str "spaces" ]
+  , BulletList
+      [ [ Para
+            [ Str "this"
+            , Space
+            , Str "is"
+            , Space
+            , Str "a"
+            , Space
+            , Str "list"
+            , Space
+            , Str "item"
+            , Space
+            , Str "indented"
+            , Space
+            , Str "with"
+            , Space
+            , Str "tabs"
+            ]
+        ]
+      , [ Para
+            [ Str "this"
+            , Space
+            , Str "is"
+            , Space
+            , Str "a"
+            , Space
+            , Str "list"
+            , Space
+            , Str "item"
+            , Space
+            , Str "indented"
+            , Space
+            , Str "with"
+            , Space
+            , Str "spaces"
+            ]
+        , BulletList
+            [ [ Para
+                  [ Str "this"
+                  , Space
+                  , Str "is"
+                  , Space
+                  , Str "an"
+                  , Space
+                  , Str "example"
+                  , Space
+                  , Str "list"
+                  , Space
+                  , Str "item"
+                  , Space
+                  , Str "indented"
+                  , Space
+                  , Str "with"
+                  , Space
+                  , Str "tabs"
+                  ]
+              ]
+            , [ Para
+                  [ Str "this"
+                  , Space
+                  , Str "is"
+                  , Space
+                  , Str "an"
+                  , Space
+                  , Str "example"
+                  , Space
+                  , Str "list"
+                  , Space
+                  , Str "item"
+                  , Space
+                  , Str "indented"
+                  , Space
+                  , Str "with"
+                  , Space
+                  , Str "spaces"
+                  ]
+              ]
+            ]
+        ]
+      ]
+  , Header
+      2
+      ( "fancy-list-markers" , [] , [] )
+      [ Str "Fancy" , Space , Str "list" , Space , Str "markers" ]
+  , OrderedList
+      ( 2 , Decimal , DefaultDelim )
+      [ [ 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 , DefaultDelim )
+            [ [ Para
+                  [ Str "sublist"
+                  , Space
+                  , Str "with"
+                  , Space
+                  , Str "roman"
+                  , Space
+                  , Str "numerals,"
+                  , Space
+                  , Str "starting"
+                  , Space
+                  , Str "with"
+                  , Space
+                  , Str "4"
+                  ]
+              ]
+            , [ Para [ Str "more" , Space , Str "items" ]
+              , OrderedList
+                  ( 1 , UpperAlpha , DefaultDelim )
+                  [ [ Para [ Str "a" , Space , Str "subsublist" ] ]
+                  , [ Para [ Str "a" , Space , Str "subsublist" ] ]
+                  ]
+              ]
+            ]
+        ]
+      ]
+  , Para [ Str "Nesting:" ]
+  , OrderedList
+      ( 1 , UpperAlpha , DefaultDelim )
+      [ [ Para [ Str "Upper" , Space , Str "Alpha" ]
+        , OrderedList
+            ( 1 , UpperRoman , DefaultDelim )
+            [ [ Para [ Str "Upper" , Space , Str "Roman." ]
+              , OrderedList
+                  ( 6 , Decimal , DefaultDelim )
+                  [ [ Para
+                        [ Str "Decimal"
+                        , Space
+                        , Str "start"
+                        , Space
+                        , Str "with"
+                        , Space
+                        , Str "6"
+                        ]
+                    , OrderedList
+                        ( 3 , LowerAlpha , DefaultDelim )
+                        [ [ Para
+                              [ Str "Lower"
+                              , Space
+                              , Str "alpha"
+                              , Space
+                              , Str "with"
+                              , Space
+                              , Str "paren"
+                              ]
+                          ]
+                        ]
+                    ]
+                  ]
+              ]
+            ]
+        ]
+      ]
+  , Para [ Str "Autonumbering:" ]
+  , OrderedList
+      ( 1 , Decimal , DefaultDelim )
+      [ [ Para [ Str "Autonumber." ] ]
+      , [ Para [ Str "More." ]
+        , OrderedList
+            ( 1 , Decimal , DefaultDelim )
+            [ [ Para [ Str "Nested." ] ] ]
+        ]
+      ]
+  , Para
+      [ Str "Should"
+      , Space
+      , Str "not"
+      , Space
+      , Str "be"
+      , Space
+      , Str "a"
+      , Space
+      , Str "list"
+      , Space
+      , Str "item:"
+      ]
+  , Para [ Str "M.A.\160\&2007" ]
+  , Para [ Str "B." , Space , Str "Williams" ]
+  , Header 2 ( "callout" , [] , [] ) [ Str "Callout" ]
+  , Para [ Str "Simple." ]
+  , BulletList
+      [ [ Para
+            [ Str "A"
+            , Space
+            , Code ( "" , [] , [] ) "__letrec"
+            , Space
+            , Str "is"
+            , Space
+            , Str "equivalent"
+            , Space
+            , Str "to"
+            , Space
+            , Str "a"
+            , Space
+            , Str "normal"
+            , SoftBreak
+            , Str "Haskell"
+            , Space
+            , Str "LET."
+            ]
+        ]
+      , [ Para
+            [ Str "GHC"
+            , Space
+            , Str "compiled"
+            , Space
+            , Str "the"
+            , Space
+            , Str "body"
+            , Space
+            , Str "of"
+            , Space
+            , Str "our"
+            , Space
+            , Str "list"
+            , Space
+            , Str "comprehension"
+            , Space
+            , Str "into"
+            , SoftBreak
+            , Str "a"
+            , Space
+            , Str "loop"
+            , Space
+            , Str "named"
+            , Space
+            , Code ( "" , [] , [] ) "go_s1YC"
+            , Str "."
+            ]
+        ]
+      , [ Para
+            [ Str "If"
+            , Space
+            , Str "our"
+            , Space
+            , Str "CASE"
+            , Space
+            , Str "expression"
+            , Space
+            , Str "matches"
+            , Space
+            , Str "the"
+            , Space
+            , Str "empty"
+            , Space
+            , Str "list,"
+            , Space
+            , Str "we"
+            , SoftBreak
+            , Str "return"
+            , Space
+            , Str "the"
+            , Space
+            , Str "empty"
+            , Space
+            , Str "list."
+            , Space
+            , Str "This"
+            , Space
+            , Str "is"
+            , Space
+            , Str "reassuringly"
+            , SoftBreak
+            , Str "familiar."
+            ]
+        ]
+      ]
+  , Header
+      1
+      ( "definition-lists" , [] , [] )
+      [ Str "Definition" , Space , Str "Lists" ]
+  , DefinitionList
+      [ ( [ Str "apple" ]
+        , [ [ Para [ Str "red" , Space , Str "fruit" ] ] ]
+        )
+      , ( [ Str "orange" ]
+        , [ [ Para [ Str "orange" , Space , Str "fruit" ] ] ]
+        )
+      , ( [ Str "banana" ]
+        , [ [ Para [ Str "yellow" , Space , Str "fruit" ] ] ]
+        )
+      ]
+  , Para
+      [ Str "Multiple"
+      , Space
+      , Str "blocks"
+      , Space
+      , Str "with"
+      , Space
+      , Str "italics:"
+      ]
+  , DefinitionList
+      [ ( [ Emph [ Str "apple" ] ]
+        , [ [ Para [ Str "red" , Space , Str "fruit" ]
+            , Para
+                [ Str "contains"
+                , Space
+                , Str "seeds,"
+                , Space
+                , Str "crisp,"
+                , Space
+                , Str "pleasant"
+                , Space
+                , Str "to"
+                , Space
+                , Str "taste"
+                ]
+            ]
+          ]
+        )
+      , ( [ Emph [ Str "orange" ] ]
+        , [ [ Para [ Str "orange" , Space , Str "fruit" ]
+            , CodeBlock ( "" , [] , [] ) "{ orange code block }"
+            , BlockQuote
+                [ Para
+                    [ Str "orange"
+                    , Space
+                    , Str "block"
+                    , Space
+                    , Str "quote"
+                    ]
+                ]
+            ]
+          ]
+        )
+      ]
+  , Para
+      [ Str "Multiple"
+      , Space
+      , Str "definitions,"
+      , Space
+      , Str "loose:"
+      ]
+  , DefinitionList
+      [ ( [ Str "apple" ]
+        , [ [ Para [ Str "red" , Space , Str "fruit" ] ]
+          , [ Para [ Str "computer" ] ]
+          ]
+        )
+      , ( [ Str "orange" ]
+        , [ [ Para [ Str "orange" , Space , Str "fruit" ] ]
+          , [ Para [ Str "bank" ] ]
+          ]
+        )
+      ]
+  , Para
+      [ Str "Blank"
+      , Space
+      , Str "line"
+      , Space
+      , Str "after"
+      , Space
+      , Str "term,"
+      , Space
+      , Str "indented"
+      , Space
+      , Str "marker,"
+      , Space
+      , Str "alternate"
+      , Space
+      , Str "markers:"
+      ]
+  , DefinitionList
+      [ ( [ Str "apple" ]
+        , [ [ Para [ Str "red" , Space , Str "fruit" ] ]
+          , [ Para [ Str "computer" ] ]
+          ]
+        )
+      , ( [ Str "orange" ]
+        , [ [ Para [ Str "orange" , Space , Str "fruit" ]
+            , OrderedList
+                ( 1 , Decimal , DefaultDelim )
+                [ [ Para [ Str "sublist" ] ]
+                , [ Para [ Str "sublist" ] ]
+                ]
+            ]
+          ]
+        )
+      ]
+  , Header
+      1
+      ( "inline-markup" , [] , [] )
+      [ Str "Inline" , Space , Str "Markup" ]
+  , Para
+      [ Str "This"
+      , Space
+      , Str "is"
+      , Space
+      , Emph [ Str "emphasized" ]
+      , Str ","
+      , Space
+      , Str "and"
+      , Space
+      , Str "so"
+      , Space
+      , Emph [ Str "is" , SoftBreak , Str "this" ]
+      , Str "."
+      ]
+  , Para
+      [ Str "This"
+      , Space
+      , Str "is"
+      , Space
+      , Strong [ Str "strong" ]
+      , Str ","
+      , Space
+      , Str "and"
+      , Space
+      , Str "so"
+      , SoftBreak
+      , Strong [ Str "is" , Space , Str "this" ]
+      , Str "."
+      ]
+  , Para
+      [ Str "An"
+      , Space
+      , Emph
+          [ Link
+              ( "" , [] , [] )
+              [ Str "emphasized" , Space , Str "link" ]
+              ( "/url" , "" )
+          ]
+      , Str "."
+      ]
+  , Para
+      [ Strong
+          [ Emph
+              [ Str "This"
+              , Space
+              , Str "is"
+              , Space
+              , Str "strong"
+              , Space
+              , Str "and"
+              , SoftBreak
+              , Str "em."
+              ]
+          ]
+      ]
+  , Para
+      [ Str "So"
+      , Space
+      , Str "is"
+      , Space
+      , Strong [ Emph [ Str "this" ] ]
+      , Space
+      , Str "word."
+      ]
+  , Para
+      [ Strong
+          [ Emph
+              [ Str "This"
+              , Space
+              , Str "is"
+              , Space
+              , Str "strong"
+              , Space
+              , Str "and"
+              , SoftBreak
+              , Str "em."
+              ]
+          ]
+      ]
+  , Para
+      [ Str "So"
+      , Space
+      , Str "is"
+      , Space
+      , Strong [ Emph [ Str "this" ] ]
+      , Space
+      , Str "word."
+      ]
+  , Para
+      [ Str "So"
+      , Space
+      , Str "is"
+      , Space
+      , Emph [ Emph [ Str "this" ] ]
+      , Space
+      , Str "word"
+      , Space
+      , Str "with"
+      , Space
+      , Str "a"
+      , Space
+      , Str "role."
+      ]
+  , Para
+      [ Str "So"
+      , Space
+      , Str "is"
+      , Space
+      , Span
+          ( "" , [ "phraserole" ] , [ ( "role" , "phraserole" ) ] )
+          [ Str "this" ]
+      , Space
+      , Str "phrase"
+      , Space
+      , Str "with"
+      , Space
+      , Str "a"
+      , Space
+      , Str "role."
+      ]
+  , Para
+      [ Str "This"
+      , Space
+      , Str "is"
+      , Space
+      , Str "code:"
+      , Space
+      , Code ( "" , [] , [] ) ">"
+      , Str ","
+      , Space
+      , Code ( "" , [] , [] ) "$"
+      , Str ","
+      , SoftBreak
+      , Code ( "" , [] , [] ) "\\"
+      , Str ","
+      , Space
+      , Code ( "" , [] , [] ) "\\$"
+      , Str ","
+      , SoftBreak
+      , Code ( "" , [] , [] ) "<html>"
+      , Str "."
+      ]
+  , Para
+      [ Str "More"
+      , Space
+      , Str "code:"
+      , Space
+      , Code ( "" , [] , [] ) "Class"
+      , Space
+      , Str "and"
+      , Space
+      , Code ( "" , [] , [] ) "Type"
+      ]
+  , Para
+      [ Str "Referencing"
+      , Space
+      , Str "a"
+      , Space
+      , Str "man"
+      , Space
+      , Str "page:"
+      , Space
+      , Code ( "" , [ "citerefentry" ] , [] ) "nix.conf(5)"
+      ]
+  , Para
+      [ Strikeout
+          [ Str "This"
+          , Space
+          , Str "is"
+          , SoftBreak
+          , Emph [ Str "strikeout" ]
+          , Str "."
+          ]
+      ]
+  , Para
+      [ Str "Superscripts:"
+      , Space
+      , Str "a"
+      , Superscript [ Str "bc" ]
+      , Str "d"
+      , SoftBreak
+      , Str "a"
+      , Superscript [ Emph [ Str "hello" ] ]
+      , SoftBreak
+      , Str "a"
+      , Superscript [ Str "hello\160there" ]
+      , Str "."
+      ]
+  , Para
+      [ Str "Subscripts:"
+      , Space
+      , Str "H"
+      , Subscript [ Str "2" ]
+      , Str "O,"
+      , Space
+      , Str "H"
+      , Subscript [ Str "23" ]
+      , Str "O,"
+      , SoftBreak
+      , Str "H"
+      , Subscript [ Str "many\160of\160them" ]
+      , Str "O."
+      ]
+  , Para
+      [ Str "These"
+      , Space
+      , Str "should"
+      , Space
+      , Str "not"
+      , Space
+      , Str "be"
+      , Space
+      , Str "superscripts"
+      , Space
+      , Str "or"
+      , Space
+      , Str "subscripts,"
+      , Space
+      , Str "because"
+      , Space
+      , Str "of"
+      , Space
+      , Str "the"
+      , Space
+      , Str "unescaped"
+      , SoftBreak
+      , Str "spaces:"
+      , Space
+      , Str "a^b"
+      , Space
+      , Str "c^d,"
+      , Space
+      , Str "a~b"
+      , Space
+      , Str "c~d."
+      ]
+  , Header
+      1
+      ( "smart-quotes-ellipses-dashes" , [] , [] )
+      [ Str "Smart"
+      , Space
+      , Str "quotes,"
+      , Space
+      , Str "ellipses,"
+      , Space
+      , Str "dashes"
+      ]
+  , Para
+      [ Quoted DoubleQuote [ Str "Hello," ]
+      , Space
+      , Str "said"
+      , Space
+      , Str "the"
+      , Space
+      , Str "spider."
+      , Space
+      , Quoted
+          DoubleQuote
+          [ Quoted SingleQuote [ Str "Shelob" ]
+          , Space
+          , Str "is"
+          , Space
+          , Str "my"
+          , SoftBreak
+          , Str "name."
+          ]
+      ]
+  , Para
+      [ Quoted DoubleQuote [ Str "A" ]
+      , Str ","
+      , Space
+      , Quoted DoubleQuote [ Str "B" ]
+      , Str ","
+      , Space
+      , Str "and"
+      , Space
+      , Quoted DoubleQuote [ Str "C" ]
+      , Space
+      , Str "are"
+      , Space
+      , Str "letters."
+      ]
+  , Para
+      [ Quoted
+          DoubleQuote
+          [ Str "He"
+          , Space
+          , Str "said,"
+          , Space
+          , Quoted
+              SingleQuote
+              [ Str "I"
+              , Space
+              , Str "want"
+              , Space
+              , Str "to"
+              , Space
+              , Str "go."
+              ]
+          ]
+      , Space
+      , Str "Were"
+      , Space
+      , Str "you"
+      , Space
+      , Str "alive"
+      , Space
+      , Str "in"
+      , Space
+      , Str "the"
+      , SoftBreak
+      , Str "70\8217s?"
+      ]
+  , Para
+      [ Str "Some"
+      , Space
+      , Str "dashes:"
+      , Space
+      , Str "one\8212two"
+      , Space
+      , Str "\8212"
+      , Space
+      , Str "three\8212four"
+      , Space
+      , Str "\8212"
+      , Space
+      , Str "five."
+      ]
+  , Para
+      [ Str "Dashes"
+      , Space
+      , Str "between"
+      , Space
+      , Str "numbers:"
+      , Space
+      , Str "5\8211\&7,"
+      , Space
+      , Str "255\8211\&66,"
+      , Space
+      , Str "1987\8211\&1999."
+      ]
+  , Para [ Str "Ellipses\8230and\8230and\8230." ]
+  , Header 1 ( "math" , [] , [] ) []
+  , Para
+      [ Math DisplayMath "e = mc^{2}"
+      , Math DisplayMath "1"
+      , SoftBreak
+      , Math InlineMath "e = mc^{2}"
+      , SoftBreak
+      , Math DisplayMath "e = mc^{2}"
+      ]
+  , Header
+      1
+      ( "special-characters" , [] , [] )
+      [ Str "Special" , Space , Str "Characters" ]
+  , Para
+      [ Str "Here"
+      , Space
+      , Str "is"
+      , Space
+      , Str "some"
+      , Space
+      , Str "unicode:"
+      ]
+  , BulletList
+      [ [ Para
+            [ Str "I" , Space , Str "hat:" , Space , Str "\206" ]
+        ]
+      , [ Para
+            [ Str "o" , Space , Str "umlaut:" , Space , Str "\246" ]
+        ]
+      , [ Para [ Str "section:" , Space , Str "\167" ] ]
+      , [ Para
+            [ Str "set"
+            , Space
+            , Str "membership:"
+            , Space
+            , Str "\8712"
+            ]
+        ]
+      , [ Para [ Str "copyright:" , Space , Str "\169" ] ]
+      ]
+  , Para
+      [ Str "AT&T"
+      , Space
+      , Str "has"
+      , Space
+      , Str "an"
+      , Space
+      , Str "ampersand"
+      , Space
+      , Str "in"
+      , Space
+      , Str "their"
+      , Space
+      , Str "name."
+      ]
+  , Para
+      [ Str "AT&T"
+      , Space
+      , Str "is"
+      , Space
+      , Str "another"
+      , Space
+      , Str "way"
+      , Space
+      , Str "to"
+      , Space
+      , Str "write"
+      , Space
+      , Str "it."
+      ]
+  , Para
+      [ Str "This" , Space , Str "&" , Space , Str "that." ]
+  , Para [ Str "4" , Space , Str "<" , Space , Str "5." ]
+  , Para [ Str "6" , Space , Str ">" , Space , Str "5." ]
+  , Para [ Str "Backslash:" , Space , Str "\\" ]
+  , Para [ Str "Backtick:" , Space , Str "`" ]
+  , Para [ Str "Asterisk:" , Space , Str "*" ]
+  , Para [ Str "Underscore:" , Space , Str "_" ]
+  , Para
+      [ Str "Left" , Space , Str "brace:" , Space , Str "{" ]
+  , Para
+      [ Str "Right" , Space , Str "brace:" , Space , Str "}" ]
+  , Para
+      [ Str "Left" , Space , Str "bracket:" , Space , Str "[" ]
+  , Para
+      [ Str "Right" , Space , Str "bracket:" , Space , Str "]" ]
+  , Para
+      [ Str "Left" , Space , Str "paren:" , Space , Str "(" ]
+  , Para
+      [ Str "Right" , Space , Str "paren:" , Space , Str ")" ]
+  , Para [ Str "Greater-than:" , Space , Str ">" ]
+  , Para [ Str "Hash:" , Space , Str "#" ]
+  , Para [ Str "Period:" , Space , Str "." ]
+  , Para [ Str "Bang:" , Space , Str "!" ]
+  , Para [ Str "Plus:" , Space , Str "+" ]
+  , Para [ Str "Minus:" , Space , Str "-" ]
+  , Header 1 ( "links" , [] , [] ) [ Str "Links" ]
+  , Header 2 ( "explicit" , [] , [] ) [ Str "Explicit" ]
+  , Para
+      [ Str "Just"
+      , Space
+      , Str "a"
+      , Space
+      , Link ( "" , [] , [] ) [ Str "URL" ] ( "/url/" , "" )
+      , Str "."
+      ]
+  , Para
+      [ Link
+          ( "" , [] , [] )
+          [ Str "URL" , Space , Str "and" , Space , Str "title" ]
+          ( "/url/" , "" )
+      , Str "."
+      ]
+  , Para
+      [ Link
+          ( "" , [] , [] )
+          [ Str "URL" , Space , Str "and" , Space , Str "title" ]
+          ( "/url/" , "" )
+      , Str "."
+      ]
+  , Para
+      [ Link
+          ( "" , [] , [] )
+          [ Str "URL" , Space , Str "and" , Space , Str "title" ]
+          ( "/url/" , "" )
+      , Str "."
+      ]
+  , Para
+      [ Link
+          ( "" , [] , [] )
+          [ Str "URL" , Space , Str "and" , Space , Str "title" ]
+          ( "/url/" , "" )
+      ]
+  , Para
+      [ Link
+          ( "" , [] , [] )
+          [ Str "URL" , Space , Str "and" , Space , Str "title" ]
+          ( "/url/" , "" )
+      ]
+  , Para
+      [ Link
+          ( "" , [] , [] )
+          [ Str "with_underscore" ]
+          ( "/url/with_underscore" , "" )
+      ]
+  , Para
+      [ Link
+          ( "" , [] , [] )
+          [ Str "nobody@nowhere.net" ]
+          ( "mailto:nobody@nowhere.net" , "" )
+      ]
+  , Para
+      [ Link ( "" , [] , [] ) [ Str "Empty" ] ( "" , "" )
+      , Str "."
+      ]
+  , Header 2 ( "reference" , [] , [] ) [ Str "Reference" ]
+  , Para
+      [ Str "Foo"
+      , Space
+      , Link ( "" , [] , [] ) [ Str "bar" ] ( "/url/" , "" )
+      , Str "."
+      ]
+  , Para
+      [ Str "Foo"
+      , Space
+      , Link ( "" , [] , [] ) [ Str "bar" ] ( "/url/" , "" )
+      , Str "."
+      ]
+  , Para
+      [ Str "Foo"
+      , Space
+      , Link ( "" , [] , [] ) [ Str "bar" ] ( "/url/" , "" )
+      , Str "."
+      ]
+  , Para
+      [ Str "With"
+      , Space
+      , Link
+          ( "" , [] , [] )
+          [ Str "embedded" , Space , Str "[brackets]" ]
+          ( "/url/" , "" )
+      , Str "."
+      ]
+  , Para
+      [ Link ( "" , [] , [] ) [ Str "b" ] ( "/url/" , "" )
+      , Space
+      , Str "by"
+      , Space
+      , Str "itself"
+      , Space
+      , Str "should"
+      , Space
+      , Str "be"
+      , Space
+      , Str "a"
+      , Space
+      , Str "link."
+      ]
+  , Para
+      [ Str "Indented"
+      , Space
+      , Link ( "" , [] , [] ) [ Str "once" ] ( "/url" , "" )
+      , Str "."
+      ]
+  , Para
+      [ Str "Indented"
+      , Space
+      , Link ( "" , [] , [] ) [ Str "twice" ] ( "/url" , "" )
+      , Str "."
+      ]
+  , Para
+      [ Str "Indented"
+      , Space
+      , Link ( "" , [] , [] ) [ Str "thrice" ] ( "/url" , "" )
+      , Str "."
+      ]
+  , Para
+      [ Str "This"
+      , Space
+      , Str "should"
+      , Space
+      , Str "[not][]"
+      , Space
+      , Str "be"
+      , Space
+      , Str "a"
+      , Space
+      , Str "link."
+      ]
+  , CodeBlock ( "" , [] , [] ) "[not]: /url"
+  , Para
+      [ Str "Foo"
+      , Space
+      , Link ( "" , [] , [] ) [ Str "bar" ] ( "/url/" , "" )
+      , Str "."
+      ]
+  , Para
+      [ Str "Foo"
+      , Space
+      , Link ( "" , [] , [] ) [ Str "biz" ] ( "/url/" , "" )
+      , Str "."
+      ]
+  , Header
+      2
+      ( "with-ampersands" , [] , [] )
+      [ Str "With" , Space , Str "ampersands" ]
+  , Para
+      [ Str "Here\8217s"
+      , Space
+      , Str "a"
+      , Space
+      , Link
+          ( "" , [] , [] )
+          [ Str "link"
+          , Space
+          , Str "with"
+          , Space
+          , Str "an"
+          , SoftBreak
+          , Str "ampersand"
+          , Space
+          , Str "in"
+          , Space
+          , Str "the"
+          , Space
+          , Str "URL"
+          ]
+          ( "http://example.com/?foo=1&bar=2" , "" )
+      , Str "."
+      ]
+  , Para
+      [ Str "Here\8217s"
+      , Space
+      , Str "a"
+      , Space
+      , Str "link"
+      , Space
+      , Str "with"
+      , Space
+      , Str "an"
+      , Space
+      , Str "amersand"
+      , Space
+      , Str "in"
+      , Space
+      , Str "the"
+      , Space
+      , Str "link"
+      , Space
+      , Str "text:"
+      , SoftBreak
+      , Link
+          ( "" , [] , [] ) [ Str "AT&T" ] ( "http://att.com/" , "" )
+      , Str "."
+      ]
+  , Para
+      [ Str "Here\8217s"
+      , Space
+      , Str "an"
+      , Space
+      , Link
+          ( "" , [] , [] )
+          [ Str "inline" , Space , Str "link" ]
+          ( "/script?foo=1&bar=2" , "" )
+      , Str "."
+      ]
+  , Para
+      [ Str "Here\8217s"
+      , Space
+      , Str "an"
+      , Space
+      , Link
+          ( "" , [] , [] )
+          [ Str "inline"
+          , Space
+          , Str "link"
+          , Space
+          , Str "in"
+          , Space
+          , Str "pointy"
+          , SoftBreak
+          , Str "braces"
+          ]
+          ( "/script?foo=1&bar=2" , "" )
+      , Str "."
+      ]
+  , Header 2 ( "autolinks" , [] , [] ) [ Str "Autolinks" ]
+  , Para
+      [ Str "With"
+      , Space
+      , Str "an"
+      , Space
+      , Str "ampersand:"
+      , SoftBreak
+      , Link
+          ( "" , [] , [] )
+          [ Str "http://example.com/?foo=1&bar=2" ]
+          ( "http://example.com/?foo=1&bar=2" , "" )
+      ]
+  , BulletList
+      [ [ Para
+            [ Str "In" , Space , Str "a" , Space , Str "list?" ]
+        ]
+      , [ Para
+            [ Link
+                ( "" , [] , [] )
+                [ Str "http://example.com/" ]
+                ( "http://example.com/" , "" )
+            ]
+        ]
+      , [ Para [ Str "It" , Space , Str "should." ] ]
+      ]
+  , Para
+      [ Str "An"
+      , Space
+      , Str "e-mail"
+      , Space
+      , Str "address:"
+      , Space
+      , Link
+          ( "" , [] , [] )
+          [ Str "nobody@nowhere.net" ]
+          ( "mailto:nobody@nowhere.net" , "" )
+      ]
+  , BlockQuote
+      [ Para
+          [ Str "Blockquoted:"
+          , SoftBreak
+          , Link
+              ( "" , [] , [] )
+              [ Str "http://example.com/" ]
+              ( "http://example.com/" , "" )
+          ]
+      ]
+  , Para
+      [ Str "Auto-links"
+      , Space
+      , Str "should"
+      , Space
+      , Str "not"
+      , Space
+      , Str "occur"
+      , Space
+      , Str "here:"
+      , SoftBreak
+      , Code ( "" , [] , [] ) "<http://example.com/>"
+      ]
+  , CodeBlock
+      ( "" , [] , [] ) "or here: <http://example.com/>"
+  , Header 1 ( "images" , [] , [] ) [ Str "Images" ]
+  , Para
+      [ Str "From"
+      , Space
+      , Quoted
+          DoubleQuote
+          [ Str "Voyage"
+          , Space
+          , Str "dans"
+          , Space
+          , Str "la"
+          , Space
+          , Str "Lune"
+          ]
+      , Space
+      , Str "by"
+      , Space
+      , Str "Georges"
+      , Space
+      , Str "Melies"
+      , Space
+      , Str "(1902):"
+      ]
+  , Figure
+      ( "" , [] , [] )
+      (Caption
+         Nothing
+         [ Plain
+             [ Str "lalune"
+             , Space
+             , Str "fig"
+             , Space
+             , Str "caption"
+             ]
+         ])
+      [ Plain
+          [ Image
+              ( "" , [] , [] )
+              [ Str "lalune"
+              , Space
+              , Str "alt"
+              , Space
+              , Str "text"
+              , Space
+              , Str "shadowed"
+              , Space
+              , Str "by"
+              , Space
+              , Str "fig"
+              , Space
+              , Str "caption"
+              ]
+              ( "lalune.jpg" , "" )
+          ]
+      ]
+  , Para
+      [ Str "Here"
+      , Space
+      , Str "is"
+      , Space
+      , Str "a"
+      , Space
+      , Str "movie"
+      , Space
+      , Image ( "" , [] , [] ) [] ( "movie.jpg" , "" )
+      , Space
+      , Str "icon."
+      , SoftBreak
+      , Str "And"
+      , Space
+      , Str "here"
+      , Space
+      , Str "a"
+      , Space
+      , Str "second"
+      , Space
+      , Str "movie"
+      , Space
+      , Image
+          ( "" , [] , [] )
+          [ Str "alt" , Space , Str "text" ]
+          ( "movie.jpg" , "" )
+      , Space
+      , Str "icon."
+      , SoftBreak
+      , Str "And"
+      , Space
+      , Str "here"
+      , Space
+      , Str "a"
+      , Space
+      , Str "third"
+      , Space
+      , Str "movie"
+      , Space
+      , Image
+          ( "" , [] , [] )
+          [ Str "alt" , Space , Str "text" ]
+          ( "movie.jpg" , "" )
+      , Space
+      , Str "icon."
+      ]
+  , Para
+      [ Image
+          ( "" , [] , [] )
+          [ Str "lalune"
+          , Space
+          , Str "no"
+          , Space
+          , Str "figure"
+          , Space
+          , Str "alt"
+          , Space
+          , Str "text"
+          ]
+          ( "lalune.jpg" , "" )
+      ]
+  , Header 1 ( "footnotes" , [] , [] ) [ Str "Footnotes" ]
+  , Para
+      [ Str "Here"
+      , Space
+      , Str "is"
+      , Space
+      , Str "a"
+      , Space
+      , Str "footnote"
+      , Space
+      , Str "reference,"
+      , Note
+          [ Para
+              [ Str "Here"
+              , Space
+              , Str "is"
+              , Space
+              , Str "the"
+              , Space
+              , Str "footnote."
+              , Space
+              , Str "It"
+              , Space
+              , Str "can"
+              , Space
+              , Str "go"
+              , Space
+              , Str "anywhere"
+              , Space
+              , Str "after"
+              , Space
+              , Str "the"
+              , Space
+              , Str "footnote"
+              , Space
+              , Str "reference."
+              , SoftBreak
+              , Str "It"
+              , Space
+              , Str "need"
+              , Space
+              , Str "not"
+              , Space
+              , Str "be"
+              , Space
+              , Str "placed"
+              , Space
+              , Str "at"
+              , Space
+              , Str "the"
+              , Space
+              , Str "end"
+              , Space
+              , Str "of"
+              , Space
+              , Str "the"
+              , Space
+              , Str "document."
+              ]
+          ]
+      , Space
+      , Str "and"
+      , Space
+      , Str "another."
+      , Note
+          [ Para
+              [ Str "Here\8217s"
+              , Space
+              , Str "the"
+              , Space
+              , Str "long"
+              , Space
+              , Str "note."
+              , Space
+              , Str "This"
+              , Space
+              , Str "one"
+              , Space
+              , Str "contains"
+              , Space
+              , Str "multiple"
+              , Space
+              , Str "blocks."
+              ]
+          , Para
+              [ Str "Subsequent"
+              , Space
+              , Str "blocks"
+              , Space
+              , Str "are"
+              , Space
+              , Str "indented"
+              , Space
+              , Str "to"
+              , Space
+              , Str "show"
+              , Space
+              , Str "that"
+              , Space
+              , Str "they"
+              , Space
+              , Str "belong"
+              , Space
+              , Str "to"
+              , Space
+              , Str "the"
+              , SoftBreak
+              , Str "footnote"
+              , Space
+              , Str "(as"
+              , Space
+              , Str "with"
+              , Space
+              , Str "list"
+              , Space
+              , Str "items)."
+              ]
+          , CodeBlock ( "" , [] , [] ) "  { <code> }"
+          , Para
+              [ Str "If"
+              , Space
+              , Str "you"
+              , Space
+              , Str "want,"
+              , Space
+              , Str "you"
+              , Space
+              , Str "can"
+              , Space
+              , Str "indent"
+              , Space
+              , Str "every"
+              , Space
+              , Str "line,"
+              , Space
+              , Str "but"
+              , Space
+              , Str "you"
+              , Space
+              , Str "can"
+              , Space
+              , Str "also"
+              , Space
+              , Str "be"
+              , Space
+              , Str "lazy"
+              , Space
+              , Str "and"
+              , SoftBreak
+              , Str "just"
+              , Space
+              , Str "indent"
+              , Space
+              , Str "the"
+              , Space
+              , Str "first"
+              , Space
+              , Str "line"
+              , Space
+              , Str "of"
+              , Space
+              , Str "each"
+              , Space
+              , Str "block."
+              ]
+          ]
+      , Space
+      , Str "This"
+      , Space
+      , Str "should"
+      , Space
+      , Emph [ Str "not" ]
+      , Space
+      , Str "be"
+      , Space
+      , Str "a"
+      , Space
+      , Str "footnote"
+      , Space
+      , Str "reference,"
+      , SoftBreak
+      , Str "because"
+      , Space
+      , Str "it"
+      , Space
+      , Str "contains"
+      , Space
+      , Str "a"
+      , Space
+      , Str "space.[^my"
+      , Space
+      , Str "note]"
+      , Space
+      , Str "Here"
+      , Space
+      , Str "is"
+      , Space
+      , Str "an"
+      , Space
+      , Str "inline"
+      , Space
+      , Str "note."
+      , Note
+          [ Para
+              [ Str "This"
+              , Space
+              , Str "is"
+              , Space
+              , Emph [ Str "easier" ]
+              , Space
+              , Str "to"
+              , Space
+              , Str "type."
+              , Space
+              , Str "Inline"
+              , Space
+              , Str "notes"
+              , Space
+              , Str "may"
+              , Space
+              , Str "contain"
+              , SoftBreak
+              , Link
+                  ( "" , [] , [] )
+                  [ Str "links" ]
+                  ( "http://google.com" , "" )
+              , Space
+              , Str "and"
+              , Space
+              , Code ( "" , [] , [] ) "]"
+              , SoftBreak
+              , Str "verbatim"
+              , Space
+              , Str "characters,"
+              , Space
+              , Str "as"
+              , Space
+              , Str "well"
+              , Space
+              , Str "as"
+              , Space
+              , Str "[bracketed"
+              , Space
+              , Str "text]."
+              ]
+          ]
+      ]
+  , BlockQuote
+      [ Para
+          [ Str "Notes"
+          , Space
+          , Str "can"
+          , Space
+          , Str "go"
+          , Space
+          , Str "in"
+          , Space
+          , Str "quotes."
+          , Note [ Para [ Str "In" , Space , Str "quote." ] ]
+          ]
+      ]
+  , OrderedList
+      ( 1 , Decimal , DefaultDelim )
+      [ [ Para
+            [ Str "And"
+            , Space
+            , Str "in"
+            , Space
+            , Str "list"
+            , Space
+            , Str "items."
+            , Note [ Para [ Str "In" , Space , Str "list." ] ]
+            ]
+        ]
+      ]
+  , Para
+      [ Str "This"
+      , Space
+      , Str "paragraph"
+      , Space
+      , Str "should"
+      , Space
+      , Str "not"
+      , Space
+      , Str "be"
+      , Space
+      , Str "part"
+      , Space
+      , Str "of"
+      , Space
+      , Str "the"
+      , Space
+      , Str "note,"
+      , Space
+      , Str "as"
+      , Space
+      , Str "it"
+      , Space
+      , Str "is"
+      , Space
+      , Str "not"
+      , Space
+      , Str "indented."
+      ]
+  , Header 1 ( "tables" , [] , [] ) [ Str "Tables" ]
+  , Para
+      [ Str "Simple"
+      , Space
+      , Str "table"
+      , Space
+      , Str "with"
+      , Space
+      , Str "caption:"
+      ]
+  , Table
+      ( "" , [] , [] )
+      (Caption
+         Nothing
+         [ Plain
+             [ Str "Demonstration"
+             , Space
+             , Str "of"
+             , Space
+             , Str "simple"
+             , Space
+             , Str "table"
+             , Space
+             , Str "syntax."
+             ]
+         ])
+      [ ( AlignRight , ColWidthDefault )
+      , ( AlignLeft , ColWidthDefault )
+      , ( AlignCenter , ColWidthDefault )
+      , ( AlignLeft , ColWidthDefault )
+      ]
+      (TableHead
+         ( "" , [] , [] )
+         [ Row
+             ( "" , [] , [] )
+             [ Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "Right" ] ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "Left" ] ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "Center" ] ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "Default" ] ]
+             ]
+         ])
+      [ TableBody
+          ( "" , [] , [] )
+          (RowHeadColumns 0)
+          []
+          [ Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "12" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "12" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "12" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "12" ] ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "123" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "123" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "123" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "123" ] ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "1" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "1" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "1" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "1" ] ]
+              ]
+          ]
+      ]
+      (TableFoot ( "" , [] , [] ) [])
+  , Para
+      [ Str "Simple"
+      , Space
+      , Str "table"
+      , Space
+      , Str "without"
+      , Space
+      , Str "caption:"
+      ]
+  , Table
+      ( "" , [] , [] )
+      (Caption Nothing [])
+      [ ( AlignRight , ColWidthDefault )
+      , ( AlignLeft , ColWidthDefault )
+      , ( AlignCenter , ColWidthDefault )
+      , ( AlignLeft , ColWidthDefault )
+      ]
+      (TableHead
+         ( "" , [] , [] )
+         [ Row
+             ( "" , [] , [] )
+             [ Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "Right" ] ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "Left" ] ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "Center" ] ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "Default" ] ]
+             ]
+         ])
+      [ TableBody
+          ( "" , [] , [] )
+          (RowHeadColumns 0)
+          []
+          [ Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "12" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "12" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "12" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "12" ] ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "123" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "123" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "123" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "123" ] ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "1" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "1" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "1" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "1" ] ]
+              ]
+          ]
+      ]
+      (TableFoot ( "" , [] , [] ) [])
+  , Para
+      [ Str "Simple"
+      , Space
+      , Str "table"
+      , Space
+      , Str "indented"
+      , Space
+      , Str "two"
+      , Space
+      , Str "spaces:"
+      ]
+  , Table
+      ( "" , [] , [] )
+      (Caption
+         Nothing
+         [ Plain
+             [ Str "Demonstration"
+             , Space
+             , Str "of"
+             , Space
+             , Str "simple"
+             , Space
+             , Str "table"
+             , Space
+             , Str "syntax."
+             ]
+         ])
+      [ ( AlignRight , ColWidthDefault )
+      , ( AlignLeft , ColWidthDefault )
+      , ( AlignCenter , ColWidthDefault )
+      , ( AlignLeft , ColWidthDefault )
+      ]
+      (TableHead
+         ( "" , [] , [] )
+         [ Row
+             ( "" , [] , [] )
+             [ Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "Right" ] ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "Left" ] ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "Center" ] ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "Default" ] ]
+             ]
+         ])
+      [ TableBody
+          ( "" , [] , [] )
+          (RowHeadColumns 0)
+          []
+          [ Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "12" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "12" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "12" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "12" ] ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "123" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "123" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "123" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "123" ] ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "1" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "1" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "1" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "1" ] ]
+              ]
+          ]
+      ]
+      (TableFoot ( "" , [] , [] ) [])
+  , Para
+      [ Str "Multiline"
+      , Space
+      , Str "table"
+      , Space
+      , Str "with"
+      , Space
+      , Str "caption:"
+      ]
+  , Table
+      ( "" , [] , [] )
+      (Caption
+         Nothing
+         [ Plain
+             [ Str "Here's"
+             , Space
+             , Str "the"
+             , Space
+             , Str "caption."
+             , Space
+             , Str "It"
+             , Space
+             , Str "may"
+             , Space
+             , Str "span"
+             , Space
+             , Str "multiple"
+             , Space
+             , Str "lines."
+             ]
+         ])
+      [ ( AlignCenter , ColWidth 0.2 )
+      , ( AlignLeft , ColWidth 0.2 )
+      , ( AlignRight , ColWidth 0.3 )
+      , ( AlignLeft , ColWidth 0.3 )
+      ]
+      (TableHead
+         ( "" , [] , [] )
+         [ Row
+             ( "" , [] , [] )
+             [ Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "Centered" , Space , Str "Header" ] ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "Left" , Space , Str "Aligned" ] ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "Right" , Space , Str "Aligned" ] ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "Default" , Space , Str "aligned" ] ]
+             ]
+         ])
+      [ TableBody
+          ( "" , [] , [] )
+          (RowHeadColumns 0)
+          []
+          [ Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "First" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "row" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "12.0" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain
+                      [ Str "Example"
+                      , Space
+                      , Str "of"
+                      , Space
+                      , Str "a"
+                      , Space
+                      , Str "row"
+                      , Space
+                      , Str "that"
+                      , Space
+                      , Str "spans"
+                      , Space
+                      , Str "multiple"
+                      , Space
+                      , Str "lines."
+                      ]
+                  ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "Second" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "row" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "5.0" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain
+                      [ Str "Here's"
+                      , Space
+                      , Str "another"
+                      , Space
+                      , Str "one."
+                      , Space
+                      , Str "Note"
+                      , Space
+                      , Str "the"
+                      , Space
+                      , Str "blank"
+                      , Space
+                      , Str "line"
+                      , Space
+                      , Str "between"
+                      , Space
+                      , Str "rows."
+                      ]
+                  ]
+              ]
+          ]
+      ]
+      (TableFoot ( "" , [] , [] ) [])
+  , Para
+      [ Str "Table"
+      , Space
+      , Str "with"
+      , Space
+      , Str "attributes"
+      ]
+  , Table
+      ( "mytableid1"
+      , [ "mytableclass1" , "mytableclass2" ]
+      , [ ( "role" , "tablerole1" )
+        , ( "custom-style" , "mytabstyle1" )
+        ]
+      )
+      (Caption
+         Nothing
+         [ Plain
+             [ Str "Attribute"
+             , Space
+             , Str "table"
+             , Space
+             , Str "caption"
+             ]
+         ])
+      [ ( AlignDefault , ColWidthDefault )
+      , ( AlignDefault , ColWidthDefault )
+      ]
+      (TableHead ( "" , [] , [] ) [])
+      [ TableBody
+          ( "" , [] , [] )
+          (RowHeadColumns 0)
+          []
+          [ Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para
+                      [ Str "body"
+                      , Space
+                      , Str "cell"
+                      , Space
+                      , Str "1"
+                      ]
+                  ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para
+                      [ Str "body"
+                      , Space
+                      , Str "cell"
+                      , Space
+                      , Str "2"
+                      ]
+                  ]
+              ]
+          ]
+      ]
+      (TableFoot ( "" , [] , [] ) [])
+  , Para
+      [ Str "Table"
+      , Space
+      , Str "with"
+      , Space
+      , Str "attributes,"
+      , Space
+      , Str "without"
+      , Space
+      , Str "caption"
+      ]
+  , Table
+      ( "mytableid2"
+      , [ "mytableclass3" , "mytableclass4" ]
+      , [ ( "role" , "tablerole2" )
+        , ( "custom-style" , "mytabstyle2" )
+        ]
+      )
+      (Caption Nothing [])
+      [ ( AlignDefault , ColWidthDefault )
+      , ( AlignDefault , ColWidthDefault )
+      ]
+      (TableHead ( "" , [] , [] ) [])
+      [ TableBody
+          ( "" , [] , [] )
+          (RowHeadColumns 0)
+          []
+          [ Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para
+                      [ Str "body"
+                      , Space
+                      , Str "cell"
+                      , Space
+                      , Str "1"
+                      ]
+                  ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para
+                      [ Str "body"
+                      , Space
+                      , Str "cell"
+                      , Space
+                      , Str "2"
+                      ]
+                  ]
+              ]
+          ]
+      ]
+      (TableFoot ( "" , [] , [] ) [])
+  , Para
+      [ Str "Multiline"
+      , Space
+      , Str "table"
+      , Space
+      , Str "without"
+      , Space
+      , Str "caption:"
+      ]
+  , Table
+      ( "" , [] , [] )
+      (Caption Nothing [])
+      [ ( AlignCenter , ColWidth 0.1 )
+      , ( AlignLeft , ColWidth 0.2 )
+      , ( AlignRight , ColWidth 0.3 )
+      , ( AlignLeft , ColWidth 0.4 )
+      ]
+      (TableHead
+         ( "" , [] , [] )
+         [ Row
+             ( "" , [] , [] )
+             [ Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "Centered" , Space , Str "Header" ] ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "Left" , Space , Str "Aligned" ] ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "Right" , Space , Str "Aligned" ] ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "Default" , Space , Str "aligned" ] ]
+             ]
+         ])
+      [ TableBody
+          ( "" , [] , [] )
+          (RowHeadColumns 0)
+          []
+          [ Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "First" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "row" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "12.0" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain
+                      [ Str "Example"
+                      , Space
+                      , Str "of"
+                      , Space
+                      , Str "a"
+                      , Space
+                      , Str "row"
+                      , Space
+                      , Str "that"
+                      , Space
+                      , Str "spans"
+                      , Space
+                      , Str "multiple"
+                      , Space
+                      , Str "lines."
+                      ]
+                  ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "Second" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "row" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "5.0" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain
+                      [ Str "Here's"
+                      , Space
+                      , Str "another"
+                      , Space
+                      , Str "one."
+                      , Space
+                      , Str "Note"
+                      , Space
+                      , Str "the"
+                      , Space
+                      , Str "blank"
+                      , Space
+                      , Str "line"
+                      , Space
+                      , Str "between"
+                      , Space
+                      , Str "rows."
+                      ]
+                  ]
+              ]
+          ]
+      ]
+      (TableFoot ( "" , [] , [] ) [])
+  , Para
+      [ Str "Table"
+      , Space
+      , Str "without"
+      , Space
+      , Str "column"
+      , Space
+      , Str "headers:"
+      ]
+  , Table
+      ( "" , [] , [] )
+      (Caption Nothing [])
+      [ ( AlignRight , ColWidthDefault )
+      , ( AlignLeft , ColWidthDefault )
+      , ( AlignCenter , ColWidthDefault )
+      , ( AlignRight , ColWidthDefault )
+      ]
+      (TableHead ( "" , [] , [] ) [])
+      [ TableBody
+          ( "" , [] , [] )
+          (RowHeadColumns 0)
+          []
+          [ Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "12" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "12" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "12" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "12" ] ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "123" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "123" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "123" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "123" ] ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "1" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "1" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "1" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "1" ] ]
+              ]
+          ]
+      ]
+      (TableFoot ( "" , [] , [] ) [])
+  , Para
+      [ Str "Multiline"
+      , Space
+      , Str "table"
+      , Space
+      , Str "without"
+      , Space
+      , Str "column"
+      , Space
+      , Str "headers:"
+      ]
+  , Table
+      ( "" , [] , [] )
+      (Caption Nothing [])
+      [ ( AlignCenter , ColWidth 0.25 )
+      , ( AlignLeft , ColWidth 0.25 )
+      , ( AlignRight , ColWidth 0.25 )
+      , ( AlignLeft , ColWidth 0.25 )
+      ]
+      (TableHead ( "" , [] , [] ) [])
+      [ TableBody
+          ( "" , [] , [] )
+          (RowHeadColumns 0)
+          []
+          [ Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "First" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "row" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "12.0" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain
+                      [ Str "Example"
+                      , Space
+                      , Str "of"
+                      , Space
+                      , Str "a"
+                      , Space
+                      , Str "row"
+                      , Space
+                      , Str "that"
+                      , Space
+                      , Str "spans"
+                      , Space
+                      , Str "multiple"
+                      , Space
+                      , Str "lines."
+                      ]
+                  ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "Second" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "row" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "5.0" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain
+                      [ Str "Here's"
+                      , Space
+                      , Str "another"
+                      , Space
+                      , Str "one."
+                      , Space
+                      , Str "Note"
+                      , Space
+                      , Str "the"
+                      , Space
+                      , Str "blank"
+                      , Space
+                      , Str "line"
+                      , Space
+                      , Str "between"
+                      , Space
+                      , Str "rows."
+                      ]
+                  ]
+              ]
+          ]
+      ]
+      (TableFoot ( "" , [] , [] ) [])
+  , Para
+      [ Str "Multiline"
+      , Space
+      , Str "table"
+      , Space
+      , Str "with"
+      , Space
+      , Str "cells"
+      , Space
+      , Str "spanning"
+      , Space
+      , Str "multiple"
+      , Space
+      , Str "columns"
+      , Space
+      , Str "and"
+      , Space
+      , Str "rows"
+      , Space
+      , Str "without"
+      , Space
+      , Str "caption."
+      ]
+  , Table
+      ( "" , [] , [] )
+      (Caption Nothing [])
+      [ ( AlignLeft , ColWidthDefault )
+      , ( AlignLeft , ColWidthDefault )
+      , ( AlignLeft , ColWidthDefault )
+      ]
+      (TableHead
+         ( "" , [] , [] )
+         [ Row
+             ( "" , [] , [] )
+             [ Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 3)
+                 [ Plain [ Str "Columns" ] ]
+             ]
+         , Row
+             ( "" , [] , [] )
+             [ Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "A" ] ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "B" ] ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "C" ] ]
+             ]
+         ])
+      [ TableBody
+          ( "" , [] , [] )
+          (RowHeadColumns 0)
+          []
+          [ Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 2)
+                  [ Plain
+                      [ Str "A1" , Space , Str "+" , Space , Str "B1" ]
+                  ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 2)
+                  (ColSpan 1)
+                  [ Plain
+                      [ Str "C1" , Space , Str "+" , Space , Str "C2" ]
+                  ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 2)
+                  (ColSpan 2)
+                  [ Plain
+                      [ Str "A2"
+                      , Space
+                      , Str "+"
+                      , Space
+                      , Str "B2"
+                      , Space
+                      , Str "+"
+                      , Space
+                      , Str "A3"
+                      , Space
+                      , Str "+"
+                      , Space
+                      , Str "B3"
+                      ]
+                  ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "C3" ] ]
+              ]
+          ]
+      ]
+      (TableFoot ( "" , [] , [] ) [])
+  , OrderedList
+      ( 1 , DefaultStyle , DefaultDelim )
+      [ [ Para [ Str "A" , Space , Str "Step" ] ]
+      , [ Para [ Str "Another" , Space , Str "Step" ]
+        , OrderedList
+            ( 1 , DefaultStyle , DefaultDelim )
+            [ [ Para
+                  [ Str "Substeps"
+                  , Space
+                  , Str "can"
+                  , Space
+                  , Str "be"
+                  , Space
+                  , Str "nested"
+                  , Space
+                  , Str "indefinitely"
+                  , Space
+                  , Str "deep."
+                  ]
+              ]
+            ]
+        ]
+      , [ Para
+            [ Str "A" , Space , Str "Final" , Space , Str "Step" ]
+        ]
+      ]
+  , Header
+      1
+      ( "indexterms" , [] , [] )
+      [ Str "Index" , Space , Str "terms" ]
+  , Para
+      [ Str "In"
+      , Space
+      , Str "the"
+      , Space
+      , Str "simplest"
+      , Space
+      , Str "case,"
+      , Space
+      , Str "index"
+      , Space
+      , Str "terms"
+      , Span
+          ( "" , [ "indexterm" ] , [ ( "primary" , "index term" ) ] )
+          []
+      , Space
+      , Str "consists"
+      , Space
+      , Str "of"
+      , Space
+      , Str "just"
+      , Space
+      , Str "a"
+      , Space
+      , Code ( "" , [] , [] ) "<primary>"
+      , Space
+      , Str "element,"
+      , Space
+      , Str "but"
+      , Space
+      , Span
+          ( ""
+          , [ "indexterm" ]
+          , [ ( "primary" , "index term" )
+            , ( "secondary" , "multi-level" )
+            ]
+          )
+          []
+      , Space
+      , Str "they"
+      , Space
+      , Str "can"
+      , Space
+      , Str "also"
+      , Space
+      , Str "consist"
+      , Space
+      , Str "of"
+      , Space
+      , Str "a"
+      , Space
+      , Code ( "" , [] , [] ) "<primary>"
+      , Space
+      , Str "and"
+      , Space
+      , Code ( "" , [] , [] ) "<secondary>"
+      , Space
+      , Str "element,"
+      , Space
+      , Str "and"
+      , Space
+      , Span
+          ( ""
+          , [ "indexterm" ]
+          , [ ( "primary" , "index term" )
+            , ( "secondary" , "multi-level" )
+            , ( "tertiary" , "3-level" )
+            ]
+          )
+          []
+      , Space
+      , Str "can"
+      , Space
+      , Str "even"
+      , Space
+      , Str "include"
+      , Space
+      , Str "a"
+      , Space
+      , Code ( "" , [] , [] ) "<tertiary>"
+      , Space
+      , Str "term."
+      ]
+  , Para
+      [ Str "Index"
+      , Space
+      , Str "terms"
+      , Space
+      , Str "can"
+      , Space
+      , Str "also"
+      , Space
+      , Str "refer"
+      , Space
+      , Str "to"
+      , Space
+      , Str "other"
+      , Space
+      , Str "index"
+      , Space
+      , Str "terms:"
+      , Space
+      , Span
+          ( ""
+          , [ "indexterm" ]
+          , [ ( "primary" , "index cross referencing" ) ]
+          )
+          []
+      , Span
+          ( ""
+          , [ "indexterm" ]
+          , [ ( "primary" , "index term" )
+            , ( "secondary" , "cross references" )
+            , ( "see" , "index cross referencing" )
+            ]
+          )
+          []
+      , Str "exclusively,"
+      , Space
+      , Str "using"
+      , Space
+      , Str "the"
+      , Space
+      , Code ( "" , [] , [] ) "<see>"
+      , Space
+      , Str "tag;"
+      , Space
+      , Str "or"
+      , Space
+      , Span
+          ( ""
+          , [ "indexterm" ]
+          , [ ( "primary" , "index cross referencing" )
+            , ( "seealso" , "cross referencing" )
+            ]
+          )
+          []
+      , Space
+      , Str "as"
+      , Space
+      , Str "a"
+      , Space
+      , Str "reference"
+      , Space
+      , Str "to"
+      , Space
+      , Str "related"
+      , Space
+      , Str "terms,"
+      , Space
+      , Str "using"
+      , Space
+      , Str "the"
+      , Space
+      , Code ( "" , [] , [] ) "<seealso>"
+      , Space
+      , Str "tag."
+      ]
+  , Para
+      [ Span
+          ( ""
+          , [ "indexterm" ]
+          , [ ( "primary" , "food" )
+            , ( "secondary" , "big baguette supreme" )
+            ]
+          )
+          []
+      , Str "Nested"
+      , Space
+      , Str "content"
+      , Space
+      , Str "in"
+      , Space
+      , Str "index"
+      , Space
+      , Str "term"
+      , Space
+      , Str "elements"
+      , Space
+      , Str "is"
+      , Space
+      , Str "flattened."
+      ]
+  , Header
+      1
+      ( "titleabbrev"
+      , []
+      , [ ( "titleabbrev" , "Abbr. title" ) ]
+      )
+      [ Str "Abbreviated" , Space , Str "title" ]
+  ]
diff --git a/test/docbook-xref.docbook b/test/docbook-xref.docbook
--- a/test/docbook-xref.docbook
+++ b/test/docbook-xref.docbook
@@ -1,6 +1,6 @@
 <!DOCTYPE book PUBLIC "-//OASIS//DTD DocBook XML V4.1.2//EN"
           "http://www.oasis-open.org/docbook/xml/4.1.2/docbookx.dtd">
-<book><title>An Example Book</title>
+<book id='book01'><title>An Example Book</title>
 <chapter id="ch01"><title>XRef Samples</title>
 <para>
 This paragraph demonstrates several features of
@@ -24,6 +24,18 @@
 <listitem><para>A link to an
 <sgmltag>funcsynopsis</sgmltag> element: <xref linkend="func01"/>.
 </para></listitem>
+<listitem><para>A link to a
+<sgmltag>figure</sgmltag> element: <xref linkend="fig01"/>.
+</para></listitem>
+<listitem><para>A link to a
+<sgmltag>table</sgmltag> element: <xref linkend="table01"/>.
+</para></listitem>
+<listitem><para>A link to a
+<sgmltag>part</sgmltag> element: <xref linkend="part01"/>.
+</para></listitem>
+<listitem><para>A link to a
+<sgmltag>book</sgmltag> element: <xref linkend="book01"/>.
+</para></listitem>
 </itemizedlist>
 </chapter>
 
@@ -32,6 +44,9 @@
   <para>Some content here</para>
 </chapter>
 
+<part id="part01">
+  <title>Later Part</title>
+
 <chapter id="ch03" xreflabel="Chapter the Third">
   <title>The Third Chapter</title>
   <para>Some content here</para>
@@ -65,6 +80,35 @@
 </funcprototype>
 </funcsynopsis>
 
+<figure id="fig01"><title>The Pythagorean Theorem Illustrated</title>
+<mediaobject>
+  <imageobject>
+    <imagedata fileref="figures/pythag.png"/>
+  </imageobject>
+  <textobject><phrase>An illustration of the Pythagorean Theorem</phrase></textobject>
+</mediaobject>
+</figure>
+
+<table id="table01" frame="all" rowsep="1" colsep="1">
+  <title>Supported features by version</title>
+  <tgroup cols="2">
+    <colspec colname="col_1" colwidth="50*"/>
+    <colspec colname="col_2" colwidth="50*"/>
+    <thead>
+      <row>
+        <entry>Version</entry>
+        <entry>Feat</entry>
+      </row>
+    </thead>
+    <tbody>
+      <row>
+        <entry>Free</entry>
+        <entry>no</entry>
+      </row>
+    </tbody>
+  </tgroup>
+</table>
+
 </chapter>
+</part>
 </book>
-
diff --git a/test/docbook-xref.native b/test/docbook-xref.native
--- a/test/docbook-xref.native
+++ b/test/docbook-xref.native
@@ -1,29 +1,369 @@
-Pandoc (Meta {unMeta = fromList []})
-[Header 1 ("ch01",[],[]) [Str "XRef",Space,Str "Samples"]
-,Para [Str "This",Space,Str "paragraph",Space,Str "demonstrates",Space,Str "several",Space,Str "features",Space,Str "of",SoftBreak,Str "XRef."]
-,BulletList
- [[Para [Str "A",Space,Str "straight",Space,Str "link",Space,Str "generates",Space,Str "the",SoftBreak,Str "cross-reference",Space,Str "text:",Space,Link ("",[],[]) [Str "The",Space,Str "Second",Space,Str "Chapter"] ("#ch02",""),Str "."]]
- ,[Para [Str "A",Space,Str "link",Space,Str "to",Space,Str "an",Space,Str "element",Space,Str "with",Space,Str "an",SoftBreak,Str "XRefLabel:",SoftBreak,Link ("",[],[]) [Str "Chapter",Space,Str "the",Space,Str "Third"] ("#ch03",""),Str "."]]
- ,[Para [Str "A",Space,Str "link",Space,Str "with",Space,Str "an",SoftBreak,Str "EndTerm:",SoftBreak,Link ("",[],[]) [Str "Chapter",Space,Str "4"] ("#ch04",""),Str "."]]
- ,[Para [Str "A",Space,Str "link",Space,Str "to",Space,Str "an",SoftBreak,Str "cmdsynopsis",Space,Str "element:",Space,Link ("",[],[]) [Str "chgrp"] ("#cmd01",""),Str "."]]
- ,[Para [Str "A",Space,Str "link",Space,Str "to",Space,Str "an",SoftBreak,Str "funcsynopsis",Space,Str "element:",Space,Link ("",[],[]) [Str "max"] ("#func01",""),Str "."]]]
-,Header 1 ("ch02",[],[]) [Str "The",Space,Str "Second",Space,Str "Chapter"]
-,Para [Str "Some",Space,Str "content",Space,Str "here"]
-,Header 1 ("ch03",[],[]) [Str "The",Space,Str "Third",Space,Str "Chapter"]
-,Para [Str "Some",Space,Str "content",Space,Str "here"]
-,Header 1 ("ch04",[],[]) [Str "The",Space,Str "Fourth",Space,Str "Chapter"]
-,Para [Str "Some",Space,Str "content",Space,Str "here"]
-,Plain [Str "chgrp"]
-,Plain [Str "-R"]
-,Plain [Str "-H"]
-,Plain [Str "-L"]
-,Plain [Str "-P"]
-,Plain [Str "-f"]
-,Plain [Str "group"]
-,Plain [Str "file"]
-,Plain [Str "int"]
-,Plain [Str "max"]
-,Plain [Str "int"]
-,Plain [Str "int1"]
-,Plain [Str "int"]
-,Plain [Str "int2"]]
+Pandoc
+  Meta
+    { unMeta =
+        fromList
+          [ ( "title"
+            , MetaInlines
+                [ Str "An"
+                , Space
+                , Str "Example"
+                , Space
+                , Str "Book"
+                ]
+            )
+          ]
+    }
+  [ Header
+      2
+      ( "ch01" , [] , [] )
+      [ Str "XRef" , Space , Str "Samples" ]
+  , Para
+      [ Str "This"
+      , Space
+      , Str "paragraph"
+      , Space
+      , Str "demonstrates"
+      , Space
+      , Str "several"
+      , Space
+      , Str "features"
+      , Space
+      , Str "of"
+      , SoftBreak
+      , Str "XRef."
+      ]
+  , BulletList
+      [ [ Para
+            [ Str "A"
+            , Space
+            , Str "straight"
+            , Space
+            , Str "link"
+            , Space
+            , Str "generates"
+            , Space
+            , Str "the"
+            , SoftBreak
+            , Str "cross-reference"
+            , Space
+            , Str "text:"
+            , Space
+            , Link
+                ( "" , [] , [] )
+                [ Str "The"
+                , Space
+                , Str "Second"
+                , Space
+                , Str "Chapter"
+                ]
+                ( "#ch02" , "" )
+            , Str "."
+            ]
+        ]
+      , [ Para
+            [ Str "A"
+            , Space
+            , Str "link"
+            , Space
+            , Str "to"
+            , Space
+            , Str "an"
+            , Space
+            , Str "element"
+            , Space
+            , Str "with"
+            , Space
+            , Str "an"
+            , SoftBreak
+            , Str "XRefLabel:"
+            , SoftBreak
+            , Link
+                ( "" , [] , [] )
+                [ Str "Chapter"
+                , Space
+                , Str "the"
+                , Space
+                , Str "Third"
+                ]
+                ( "#ch03" , "" )
+            , Str "."
+            ]
+        ]
+      , [ Para
+            [ Str "A"
+            , Space
+            , Str "link"
+            , Space
+            , Str "with"
+            , Space
+            , Str "an"
+            , SoftBreak
+            , Str "EndTerm:"
+            , SoftBreak
+            , Link
+                ( "" , [] , [] )
+                [ Str "Chapter" , Space , Str "4" ]
+                ( "#ch04" , "" )
+            , Str "."
+            ]
+        ]
+      , [ Para
+            [ Str "A"
+            , Space
+            , Str "link"
+            , Space
+            , Str "to"
+            , Space
+            , Str "an"
+            , SoftBreak
+            , Str "cmdsynopsis"
+            , Space
+            , Str "element:"
+            , Space
+            , Link ( "" , [] , [] ) [ Str "chgrp" ] ( "#cmd01" , "" )
+            , Str "."
+            ]
+        ]
+      , [ Para
+            [ Str "A"
+            , Space
+            , Str "link"
+            , Space
+            , Str "to"
+            , Space
+            , Str "an"
+            , SoftBreak
+            , Str "funcsynopsis"
+            , Space
+            , Str "element:"
+            , Space
+            , Link ( "" , [] , [] ) [ Str "max" ] ( "#func01" , "" )
+            , Str "."
+            ]
+        ]
+      , [ Para
+            [ Str "A"
+            , Space
+            , Str "link"
+            , Space
+            , Str "to"
+            , Space
+            , Str "a"
+            , SoftBreak
+            , Str "figure"
+            , Space
+            , Str "element:"
+            , Space
+            , Link
+                ( "" , [] , [] )
+                [ Str "The"
+                , Space
+                , Str "Pythagorean"
+                , Space
+                , Str "Theorem"
+                , Space
+                , Str "Illustrated"
+                ]
+                ( "#fig01" , "" )
+            , Str "."
+            ]
+        ]
+      , [ Para
+            [ Str "A"
+            , Space
+            , Str "link"
+            , Space
+            , Str "to"
+            , Space
+            , Str "a"
+            , SoftBreak
+            , Str "table"
+            , Space
+            , Str "element:"
+            , Space
+            , Link
+                ( "" , [] , [] )
+                [ Str "Supported"
+                , Space
+                , Str "features"
+                , Space
+                , Str "by"
+                , Space
+                , Str "version"
+                ]
+                ( "#table01" , "" )
+            , Str "."
+            ]
+        ]
+      , [ Para
+            [ Str "A"
+            , Space
+            , Str "link"
+            , Space
+            , Str "to"
+            , Space
+            , Str "a"
+            , SoftBreak
+            , Str "part"
+            , Space
+            , Str "element:"
+            , Space
+            , Link
+                ( "" , [] , [] )
+                [ Str "Later" , Space , Str "Part" ]
+                ( "#part01" , "" )
+            , Str "."
+            ]
+        ]
+      , [ Para
+            [ Str "A"
+            , Space
+            , Str "link"
+            , Space
+            , Str "to"
+            , Space
+            , Str "a"
+            , SoftBreak
+            , Str "book"
+            , Space
+            , Str "element:"
+            , Space
+            , Link
+                ( "" , [] , [] )
+                [ Str "An"
+                , Space
+                , Str "Example"
+                , Space
+                , Str "Book"
+                ]
+                ( "#book01" , "" )
+            , Str "."
+            ]
+        ]
+      ]
+  , Header
+      2
+      ( "ch02" , [] , [] )
+      [ Str "The" , Space , Str "Second" , Space , Str "Chapter" ]
+  , Para
+      [ Str "Some" , Space , Str "content" , Space , Str "here" ]
+  , Header
+      1
+      ( "part01" , [] , [] )
+      [ Str "Later" , Space , Str "Part" ]
+  , Header
+      2
+      ( "ch03" , [] , [] )
+      [ Str "The" , Space , Str "Third" , Space , Str "Chapter" ]
+  , Para
+      [ Str "Some" , Space , Str "content" , Space , Str "here" ]
+  , Header
+      2
+      ( "ch04" , [] , [ ( "titleabbrev" , "Chapter 4" ) ] )
+      [ Str "The" , Space , Str "Fourth" , Space , Str "Chapter" ]
+  , Para
+      [ Str "Some" , Space , Str "content" , Space , Str "here" ]
+  , Plain [ Str "chgrp" ]
+  , Plain [ Str "-R" ]
+  , Plain [ Str "-H" ]
+  , Plain [ Str "-L" ]
+  , Plain [ Str "-P" ]
+  , Plain [ Str "-f" ]
+  , Plain [ Str "group" ]
+  , Plain [ Str "file" ]
+  , Plain [ Str "int" ]
+  , Plain [ Str "max" ]
+  , Plain [ Str "int" ]
+  , Plain [ Str "int1" ]
+  , Plain [ Str "int" ]
+  , Plain [ Str "int2" ]
+  , Figure
+      ( "fig01" , [] , [] )
+      (Caption
+         Nothing
+         [ Plain
+             [ Str "The"
+             , Space
+             , Str "Pythagorean"
+             , Space
+             , Str "Theorem"
+             , Space
+             , Str "Illustrated"
+             ]
+         ])
+      [ Plain
+          [ Image
+              ( "" , [] , [] )
+              [ Str "An"
+              , Space
+              , Str "illustration"
+              , Space
+              , Str "of"
+              , Space
+              , Str "the"
+              , Space
+              , Str "Pythagorean"
+              , Space
+              , Str "Theorem"
+              ]
+              ( "figures/pythag.png" , "" )
+          ]
+      ]
+  , Table
+      ( "table01" , [] , [] )
+      (Caption
+         Nothing
+         [ Plain
+             [ Str "Supported"
+             , Space
+             , Str "features"
+             , Space
+             , Str "by"
+             , Space
+             , Str "version"
+             ]
+         ])
+      [ ( AlignDefault , ColWidth 0.5 )
+      , ( AlignDefault , ColWidth 0.5 )
+      ]
+      (TableHead
+         ( "" , [] , [] )
+         [ Row
+             ( "" , [] , [] )
+             [ Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "Version" ] ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "Feat" ] ]
+             ]
+         ])
+      [ TableBody
+          ( "" , [] , [] )
+          (RowHeadColumns 0)
+          []
+          [ Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "Free" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "no" ] ]
+              ]
+          ]
+      ]
+      (TableFoot ( "" , [] , [] ) [])
+  ]
diff --git a/test/docx/0_level_headers.native b/test/docx/0_level_headers.native
--- a/test/docx/0_level_headers.native
+++ b/test/docx/0_level_headers.native
@@ -1,25 +1,146 @@
-[Table [] [AlignDefault] [0.0]
- [[]]
- [[[]]
- ,[[Plain [Str "User\8217s",Space,Str "Guide"]]]
- ,[[]]
- ,[[]]
- ,[[]]
- ,[[Plain [Str "11",Space,Str "August",Space,Str "2017"]]]
- ,[[]]
- ,[[]]
- ,[[]]
- ,[[]]]
-,Para [Str "CONTENTS"]
-,Para [Strong [Str "Section",Space,Str "Page"]]
-,Para [Str "FIGURES",Space,Str "iv"]
-,Para [Str "TABLES",Space,Str "v"]
-,Para [Str "SECTION",Space,Str "1",Space,Str "Introduction",Space,Str "2"]
-,Header 1 ("figures",["Heading0"],[]) [Str "FIGURES"]
-,Para [Strong [Str "Figure",Space,Str "Page"]]
-,Para [Strong [Str "No",Space,Str "table",Space,Str "of",Space,Str "figures",Space,Str "entries",Space,Str "found."]]
-,Header 1 ("tables",["Heading0"],[]) [Str "TABLES"]
-,Para [Strong [Str "Table",Space,Str "Page"]]
-,Para [Strong [Str "No",Space,Str "table",Space,Str "of",Space,Str "figures",Space,Str "entries",Space,Str "found."]]
-,Header 1 ("introduction",[],[]) [Str "Introduction"]
-,Para [Str "Nothing",Space,Str "to",Space,Str "introduce,",Space,Str "yet."]]
+[ Table
+    ( "" , [] , [] )
+    (Caption Nothing [])
+    [ ( AlignDefault , ColWidth 0.8615384615384616 ) ]
+    (TableHead ( "" , [] , [] ) [])
+    [ TableBody
+        ( "" , [] , [] )
+        (RowHeadColumns 0)
+        []
+        [ Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] ) AlignDefault (RowSpan 1) (ColSpan 1) []
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "User\8217s" , Space , Str "Guide" ] ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] ) AlignDefault (RowSpan 1) (ColSpan 1) []
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] ) AlignDefault (RowSpan 1) (ColSpan 1) []
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] ) AlignDefault (RowSpan 1) (ColSpan 1) []
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain
+                    [ Str "11"
+                    , Space
+                    , Str "August"
+                    , Space
+                    , Str "2017"
+                    ]
+                ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] ) AlignDefault (RowSpan 1) (ColSpan 1) []
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] ) AlignDefault (RowSpan 1) (ColSpan 1) []
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] ) AlignDefault (RowSpan 1) (ColSpan 1) []
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] ) AlignDefault (RowSpan 1) (ColSpan 1) []
+            ]
+        ]
+    ]
+    (TableFoot ( "" , [] , [] ) [])
+, Para [ Str "CONTENTS" ]
+, Para [ Strong [ Str "Section" , Space , Str "Page" ] ]
+, Para
+    [ Str "FIGURES"
+    , Space
+    , Link ( "" , [] , [] ) [ Str "iv" ] ( "#figures" , "" )
+    ]
+, Para
+    [ Str "TABLES"
+    , Space
+    , Link ( "" , [] , [] ) [ Str "v" ] ( "#tables" , "" )
+    ]
+, Para
+    [ Str "SECTION"
+    , Space
+    , Str "1"
+    , Space
+    , Str "Introduction"
+    , Space
+    , Link ( "" , [] , [] ) [ Str "2" ] ( "#introduction" , "" )
+    ]
+, Header
+    1 ( "figures" , [ "Heading-0" ] , [] ) [ Str "FIGURES" ]
+, Para [ Strong [ Str "Figure" , Space , Str "Page" ] ]
+, Para
+    [ Strong
+        [ Str "No"
+        , Space
+        , Str "table"
+        , Space
+        , Str "of"
+        , Space
+        , Str "figures"
+        , Space
+        , Str "entries"
+        , Space
+        , Str "found."
+        ]
+    ]
+, Header
+    1 ( "tables" , [ "Heading-0" ] , [] ) [ Str "TABLES" ]
+, Para [ Strong [ Str "Table" , Space , Str "Page" ] ]
+, Para
+    [ Strong
+        [ Str "No"
+        , Space
+        , Str "table"
+        , Space
+        , Str "of"
+        , Space
+        , Str "figures"
+        , Space
+        , Str "entries"
+        , Space
+        , Str "found."
+        ]
+    ]
+, Header
+    1 ( "introduction" , [] , [] ) [ Str "Introduction" ]
+, Para
+    [ Str "Nothing"
+    , Space
+    , Str "to"
+    , Space
+    , Str "introduce,"
+    , Space
+    , Str "yet."
+    ]
+]
diff --git a/test/docx/adjacent_codeblocks.docx b/test/docx/adjacent_codeblocks.docx
new file mode 100644
Binary files /dev/null and b/test/docx/adjacent_codeblocks.docx differ
diff --git a/test/docx/adjacent_codeblocks.native b/test/docx/adjacent_codeblocks.native
new file mode 100644
--- /dev/null
+++ b/test/docx/adjacent_codeblocks.native
@@ -0,0 +1,6 @@
+[Para [Str "Next,",Space,Str "open",Space,Str "the",Space,Str "terminal",Space,Str "window.",Space,Str "Using",Space,Str "the",Space,Str "terminal",Space,Str "window,",Space,Str "run",Space,Str "the",Space,Str "\"ifconfig",Space,Str "-a\"",Space,Str "command",Space,Str "to",Space,Str "list",Space,Str "all",Space,Str "the",Space,Str "interfaces",Space,Str "on",Space,Str "your",Space,Str "system,",Space,Str "as",Space,Str "shown",Space,Str "here."]
+,CodeBlock ("",[],[]) "# ifconfig -a\neth0      Link encap:Ethernet  HWaddr 00:0c:29:69:12:7c  \n          inet addr:172.16.0.108  Bcast:172.16.0.255  Mask:255.255.255.0\n          inet6 addr: fc00:660:0:1:20c:29ff:fe69:127c/64 Scope:Global\n          inet6 addr: fe80::20c:29ff:fe69:127c/64 Scope:Link\n          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1\n          RX packets:9859 errors:0 dropped:0 overruns:0 frame:0\n          TX packets:1399 errors:0 dropped:0 overruns:0 carrier:0\n          collisions:0 txqueuelen:1000 \n          RX bytes:1920894 (1.8 MiB)  TX bytes:233088 (227.6 KiB)\n          Interrupt:19 Base address:0x2000 \n\nlo        Link encap:Local Loopback  \n          inet addr:127.0.0.1  Mask:255.0.0.0\n          inet6 addr: ::1/128 Scope:Host\n          UP LOOPBACK RUNNING  MTU:65536  Metric:1\n          RX packets:372 errors:0 dropped:0 overruns:0 frame:0\n          TX packets:372 errors:0 dropped:0 overruns:0 carrier:0\n          collisions:0 txqueuelen:0 \n          RX bytes:22320 (21.7 KiB)  TX bytes:22320 (21.7 KiB)\n\nwlan0     Link encap:Ethernet  HWaddr 00:c0:ca:85:00:ba  \n          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1\n          RX packets:0 errors:0 dropped:0 overruns:0 frame:0\n          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0\n          collisions:0 txqueuelen:1000 \n          RX bytes:0 (0.0 B)  TX bytes:0 (0.0 B)"
+,Para [Str "The",Space,Str "ALFA",Space,Str "wireless",Space,Str "card",Space,Str "is",Space,Str "represented",Space,Str "by",Space,Str "the",Space,Str "\"wlan0\"",Space,Str "interface."]
+,Para [Str "In",Space,Str "addition",Space,Str "to",Space,Str "the",Space,Str "interfaces",Space,Str "shown",Space,Str "in",Space,Str "the",Space,Str "ifconfig",Space,Str "output,",Space,Str "there",Space,Str "is",Space,Str "another",Space,Str "interface",Space,Str "known",Space,Str "as",Space,Str "the",Space,Emph [Str "wireless",Space,Str "physical",Space,Str "interface"],Str ".",Space,Str "We",Space,Str "can",Space,Str "identify",Space,Str "this",Space,Str "interface",Space,Str "by",Space,Str "listing",Space,Str "the",Space,Str "contents",Space,Str "of",Space,Str "the",Space,Str "/sys/class/ieee80211",Space,Str "directory,",Space,Str "as",Space,Str "shown."]
+,CodeBlock ("",[],[]) "# ls /sys/class/ieee80211/\nphy0"
+,Para [Str "The",Space,Str "\"phy0\"",Space,Str "interface",Space,Str "is",Space,Str "the",Space,Str "parent",Space,Str "interface",Space,Str "used",Space,Str "to",Space,Str "create",Space,Str "child",Space,Str "interfaces.",Space,Str "Note",Space,Str "that",Space,Str "if",Space,Str "you",Space,Str "unplug",Space,Str "and",Space,Str "replug",Space,Str "the",Space,Str "USB",Space,Str "interface,",Space,Str "the",Space,Str "\"phy\"",Space,Str "interface",Space,Str "number",Space,Str "will",Space,Str "increment",Space,Str "by",Space,Str "one",Space,Str "until",Space,Str "you",Space,Str "reboot",Space,Str "your",Space,Str "system."]]
diff --git a/test/docx/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,3 @@
+Pandoc (Meta {unMeta = fromList []})
+[Header 1 ("test",[],[]) [Str "Test"]
+,Para [Str "This",Space,Str "is",Space,Emph [Str "italic"],Str ",",Space,Strong [Str "bold"],Str ",",Space,Underline [Str "underlined"],Str ",",Space,Emph [Underline [Str "italic",Space,Str "underlined"]],Str ",",Space,Strong [Underline [Str "bold",Space,Str "underlined"]],Str ",",Space,Emph [Strong [Underline [Str "bold",Space,Str "italic",Space,Str "underlined"]]],Str "."]]
diff --git a/test/docx/anchor_header_after_anchor.docx b/test/docx/anchor_header_after_anchor.docx
new file mode 100644
Binary files /dev/null and b/test/docx/anchor_header_after_anchor.docx differ
diff --git a/test/docx/anchor_header_after_anchor.native b/test/docx/anchor_header_after_anchor.native
new file mode 100644
--- /dev/null
+++ b/test/docx/anchor_header_after_anchor.native
@@ -0,0 +1,6 @@
+[Para [Link ("",[],[]) [Str "A",Space,Str "link",Space,Str "to",Space,Str "the",Space,Str "bookmark"] ("#referenced-title" , "")]
+,Para [Strong [Str "Accomplices:"]]
+,Para [Str "There",Space,Str "are",Space,Str "bookmarks",Space,Str "around",Space,Str "here."]
+,Para []
+,Header 1 ("referenced-title",[],[]) [Str "Referenced" ,Space ,Str "title"]
+,Para [Str "Content"]]
diff --git a/test/docx/block_quotes.docx b/test/docx/block_quotes.docx
Binary files a/test/docx/block_quotes.docx and b/test/docx/block_quotes.docx differ
diff --git a/test/docx/block_quotes.native b/test/docx/block_quotes.native
new file mode 100644
--- /dev/null
+++ b/test/docx/block_quotes.native
@@ -0,0 +1,11 @@
+[Header 2 ("some-block-quotes-in-different-ways",[],[]) [Str "Some",Space,Str "block",Space,Str "quotes,",Space,Str "in",Space,Str "different",Space,Str "ways"]
+,Para [Str "This",Space,Str "is",Space,Str "the",Space,Str "proper",Space,Str "way,",Space,Str "with",Space,Str "a",Space,Str "style"]
+,BlockQuote
+ [Para [Str "I",Space,Str "don\8217t",Space,Str "know",Space,Str "why",Space,Str "this",Space,Str "would",Space,Str "be",Space,Str "in",Space,Str "italics,",Space,Str "but",Space,Str "so",Space,Str "it",Space,Str "appears",Space,Str "to",Space,Str "be",Space,Str "on",Space,Str "my",Space,Str "screen."]]
+,Para [Str "And",Space,Str "this",Space,Str "is",Space,Str "also",Space,Str "a",Space,Str "proper",Space,Str "way,",Space,Str "with",Space,Str "a",Space,Str "different", Space, Str "style"]
+,BlockQuote
+ [Para [Str "This",Space,Str "is",Space,Str "called",Space,Str "the",Space,Str "Intense",Space,Str "Quote",Space,Str "style."]]
+,Para [Str "And",Space,Str "this",Space,Str "is",Space,Str "the",Space,Str "way",Space,Str "that",Space,Str "most",Space,Str "people",Space,Str "do",Space,Str "it:"]
+,BlockQuote
+ [Para [Str "I",Space,Str "just",Space,Str "indented",Space,Str "this,",Space,Str "so",Space,Str "it",Space,Str "looks",Space,Str "like",Space,Str "a",Space,Str "block",Space,Str "quote.",Space,Str "I",Space,Str "think",Space,Str "this",Space,Str "is",Space,Str "how",Space,Str "most",Space,Str "people",Space,Str "do",Space,Str "block",Space,Str "quotes",Space,Str "in",Space,Str "their",Space,Str "documents."]]
+,Para [Str "And",Space,Str "back",Space,Str "to",Space,Str "the",Space,Str "normal",Space,Str "style."]]
diff --git a/test/docx/block_quotes_parse_indent.native b/test/docx/block_quotes_parse_indent.native
deleted file mode 100644
--- a/test/docx/block_quotes_parse_indent.native
+++ /dev/null
@@ -1,8 +0,0 @@
-[Header 2 ("some-block-quotes-in-different-ways",[],[]) [Str "Some",Space,Str "block",Space,Str "quotes,",Space,Str "in",Space,Str "different",Space,Str "ways"]
-,Para [Str "This",Space,Str "is",Space,Str "the",Space,Str "proper",Space,Str "way,",Space,Str "with",Space,Str "a",Space,Str "style"]
-,BlockQuote
- [Para [Str "I",Space,Str "don\8217t",Space,Str "know",Space,Str "why",Space,Str "this",Space,Str "would",Space,Str "be",Space,Str "in",Space,Str "italics,",Space,Str "but",Space,Str "so",Space,Str "it",Space,Str "appears",Space,Str "to",Space,Str "be",Space,Str "on",Space,Str "my",Space,Str "screen."]]
-,Para [Str "And",Space,Str "this",Space,Str "is",Space,Str "the",Space,Str "way",Space,Str "that",Space,Str "most",Space,Str "people",Space,Str "do",Space,Str "it:"]
-,BlockQuote
- [Para [Str "I",Space,Str "just",Space,Str "indented",Space,Str "this,",Space,Str "so",Space,Str "it",Space,Str "looks",Space,Str "like",Space,Str "a",Space,Str "block",Space,Str "quote.",Space,Str "I",Space,Str "think",Space,Str "this",Space,Str "is",Space,Str "how",Space,Str "most",Space,Str "people",Space,Str "do",Space,Str "block",Space,Str "quotes",Space,Str "in",Space,Str "their",Space,Str "documents."]]
-,Para [Str "And",Space,Str "back",Space,Str "to",Space,Str "the",Space,Str "normal",Space,Str "style."]]
diff --git a/test/docx/char_styles.docx b/test/docx/char_styles.docx
Binary files a/test/docx/char_styles.docx and b/test/docx/char_styles.docx differ
diff --git a/test/docx/comments.native b/test/docx/comments.native
--- a/test/docx/comments.native
+++ b/test/docx/comments.native
@@ -1,4 +1,4 @@
 [Para [Str "I",Space,Str "want",Space,Span ("",["comment-start"],[("id","0"),("author","Jesse Rosenthal"),("date","2016-05-09T16:13:00Z")]) [Str "I",Space,Str "left",Space,Str "a",Space,Str "comment."],Str "some",Space,Str "text",Space,Str "to",Space,Str "have",Space,Str "a",Space,Str "comment",Space,Span ("",["comment-end"],[("id","0")]) [],Str "on",Space,Str "it."]
 ,Para [Str "This",Space,Str "is",Space,Span ("",["comment-start"],[("id","1"),("author","Jesse Rosenthal"),("date","2016-05-09T16:13:00Z")]) [Str "A",Space,Str "comment",Space,Str "across",Space,Str "paragraphs."],Str "a",Space,Str "new",Space,Str "paragraph."]
 ,Para [Str "And",Space,Str "so",Span ("",["comment-end"],[("id","1")]) [],Space,Str "is",Space,Str "this."]
-,Para [Str "One",Space,Span ("",["comment-start"],[("id","2"),("author","Jesse Rosenthal"),("date","2016-05-09T16:14:00Z")]) [Str "This",Space,Str "one",Space,Str "has",Space,Str "multiple",Space,Str "paragraphs.",Space,Str "\182",Space,Str "See?"],Str "more",Span ("",["comment-end"],[("id","2")]) [],Str ".",Space,Str "And",Space,Str "this",Space,Str "is",Space,Str "one",Space,Str "with",Space,Str "a",Space,Span ("",["comment-start"],[("id","3"),("author","Jesse Rosenthal"),("date","2016-06-22T14:35:00Z")]) [Str "Do",Space,Str "something."],Span ("",["comment-start"],[("id","4"),("author","Jesse Rosenthal"),("date","2016-06-22T14:36:00Z")]) [Str "Do",Space,Str "something",Space,Str "else."],Str "comment",Space,Str "in",Space,Str "a",Space,Str "comment",Span ("",["comment-end"],[("id","3")]) [Span ("",["comment-end"],[("id","4")]) []],Str "."]]
+,Para [Str "One",Space,Span ("",["comment-start"],[("id","2"),("author","Jesse Rosenthal"),("date","2016-05-09T16:14:00Z")]) [Str "This",Space,Str "one",Space,Str "has",Space,Str "multiple",Space,Str "paragraphs.",LineBreak, Str "See?"],Str "more",Span ("",["comment-end"],[("id","2")]) [],Str ".",Space,Str "And",Space,Str "this",Space,Str "is",Space,Str "one",Space,Str "with",Space,Str "a",Space,Span ("",["comment-start"],[("id","3"),("author","Jesse Rosenthal"),("date","2016-06-22T14:35:00Z")]) [Str "Do",Space,Str "something."],Span ("",["comment-start"],[("id","4"),("author","Jesse Rosenthal"),("date","2016-06-22T14:36:00Z")]) [Str "Do",Space,Str "something",Space,Str "else."],Str "comment",Space,Str "in",Space,Str "a",Space,Str "comment",Span ("",["comment-end"],[("id","3")]) [Span ("",["comment-end"],[("id","4")]) []],Str "."]]
diff --git a/test/docx/compact-style-removal.docx b/test/docx/compact-style-removal.docx
new file mode 100644
Binary files /dev/null and b/test/docx/compact-style-removal.docx differ
diff --git a/test/docx/compact-style-removal.native b/test/docx/compact-style-removal.native
new file mode 100644
--- /dev/null
+++ b/test/docx/compact-style-removal.native
@@ -0,0 +1,5 @@
+[OrderedList (1,Decimal,Period)
+ [[Plain [Str "One"]]
+ ,[Plain [Str "Two"]]
+ ,[Plain [Str "Three"]]
+ ,[Plain [Str "Four"]]]]
diff --git a/test/docx/cross_reference.docx b/test/docx/cross_reference.docx
new file mode 100644
Binary files /dev/null and b/test/docx/cross_reference.docx differ
diff --git a/test/docx/cross_reference.native b/test/docx/cross_reference.native
new file mode 100644
--- /dev/null
+++ b/test/docx/cross_reference.native
@@ -0,0 +1,7 @@
+[ Header 1 ( "title" , [] , [] ) [ Str "TITLE" ]
+, Para
+    [ Str "Cross-reference:"
+    , Space
+    , Link ( "" , [] , [] ) [ Str "TITLE" ] ( "#title" , "" )
+    ]
+]
diff --git a/test/docx/custom-style-no-styles.native b/test/docx/custom-style-no-styles.native
new file mode 100644
--- /dev/null
+++ b/test/docx/custom-style-no-styles.native
@@ -0,0 +1,4 @@
+[Para [Str "This",Space,Str "is",Space,Str "some",Space,Str "text."]
+,Para [Str "This",Space,Str "is",Space,Str "text",Space,Str "with",Space,Str "an",Space,Emph [Str "emphasized"],Space,Str "text",Space,Str "style.",Space,Str "And",Space,Str "this",Space,Str "is",Space,Str "text",Space,Str "with",Space,Str "a",Space,Strong [Str "strengthened"],Space,Str "text",Space,Str "style."]
+,BlockQuote
+ [Para [Str "Here",Space,Str "is",Space,Str "a",Space,Str "styled",Space,Str "paragraph",Space,Str "that",Space,Str "inherits",Space,Str "from",Space,Str "Block",Space,Str "Text."]]]
diff --git a/test/docx/custom-style-preserve.native b/test/docx/custom-style-preserve.native
new file mode 100644
--- /dev/null
+++ b/test/docx/custom-style-preserve.native
@@ -0,0 +1,15 @@
+[Para [Span ("",[],[("custom-style","MyStyle")]) [Str "This",Space,Str "span",Note [Para [Str "Neither",Space,Str "footnote",Space,Str "nor",Space,Str "footnote",Space,Str "reference",Space,Str "should",Space,Str "get",Space,Str "a",Space,Str "custom",Space,Str "style",Space,Str "from",Space,Str "its",Space,Str "span."]],Space,Str "should",Space,Str "have",Space,Str "a",Space,Str "custom",Space,Str "style",Space,Str "(",Link ("",[],[]) [Str "link"] ("http://example.com/",""),Str "),"],Space,Str "but",Space,Str "the",Space,Str "text",Space,Str "after",Space,Str "the",Space,Str "comma",Space,Str "shouldn\8217t,",Space,Str "nor",Space,Str "should",Space,Str "the",Space,Str "link."]
+,Div ("",[],[("custom-style","MyOtherStyle")])
+ [Para [Str "The",Space,Str "contents",Space,Str "of",Space,Str "this",Space,Str "div",Space,Str "should",Space,Str "have",Space,Str "a",Space,Str "custom",Space,Str "style,",Space,Str "but",Space,Link ("",[],[]) [Str "this",Space,Str "link",Space,Str "should",Space,Str "not"] ("http://example.com/",""),Str "."]
+ ,Header 2 ("this-header-should-not-have-the-divs-custom-style",[],[]) [Str "This",Space,Str "header",Space,Str "should",Space,Str "not",Space,Str "have",Space,Str "the",Space,Str "div\8217s",Space,Str "custom",Space,Str "style"]
+ ,BlockQuote
+  [Para [Str "This",Space,Str "blockquote",Space,Str "should",Space,Str "not."]]
+ ,CodeBlock ("",[],[]) "# This code block should not."
+ ,Para [Str "But",Space,Str "this",Space,Str "paragraph",Space,Str "should.",Note [Para [Str "Neither",Space,Str "footnote",Space,Str "nor",Space,Str "footnote",Space,Str "reference",Space,Str "should",Space,Str "get",Space,Str "a",Space,Str "custom",Space,Str "style",Space,Str "from",Space,Str "its",Space,Str "div."]]]]
+,Div ("",[],[("custom-style","MyOuterStyle")])
+ [Div ("",[],[("custom-style","MyInnerStyle")])
+  [Para [Str "This",Space,Str "should",Space,Str "have",Space,Str "MyInnerStyle."]
+  ,Header 3 ("this-heading-should-not",[],[]) [Str "This",Space,Str "heading",Space,Str "should",Space,Str "not"]]
+ ,Para [Str "This",Space,Str "should",Space,Str "have",Space,Str "MyOuterStyle,",Space,Str "but",Space,Str "the",Space,Str "following",Space,Str "elision",Space,Str "should",Space,Str "have",Space,Str "its",SoftBreak,Str "own",Space,Str "style.",Space,Span ("",[],[("custom-style","Elision")]) [Str "..."]]
+ ,BlockQuote
+  [Para [Str "This",Space,Str "blockquote",Space,Str "should",Space,Str "include",Space,Strong [Str "bold",Space,Str "text",Space,Str "with",Space,Str "an",Space,Str "elision:",SoftBreak,Span ("",[],[("custom-style","Elision")]) [Str "..."]]]]]]
diff --git a/test/docx/custom-style-reference.docx b/test/docx/custom-style-reference.docx
Binary files a/test/docx/custom-style-reference.docx and b/test/docx/custom-style-reference.docx differ
diff --git a/test/docx/custom-style-roundtrip-start.native b/test/docx/custom-style-roundtrip-start.native
deleted file mode 100644
--- a/test/docx/custom-style-roundtrip-start.native
+++ /dev/null
@@ -1,5 +0,0 @@
-[Para [Str "This",Space,Str "is",Space,Str "a",Space,Str "test",Space,Str "of",Space,Str "custom-styles."]
-,Para [Str "Here",Space,Str "is",Space,Str "something",Space,Span ("",[],[("custom-style","Emphatic")]) [Str "emphasized"],Str ".",Space,Str "And",SoftBreak,Str "here",Space,Str "is",Space,Str "something",Space,Span ("",[],[("custom-style","Strengthened")]) [Str "strong"],Str "."]
-,Div ("",[],[("custom-style","My Block Style")])
- [Para [Str "One",Space,Str "paragraph",Space,Str "of",Space,Str "text."]
- ,Para [Str "And",Space,Str "another",Space,Str "paragraph",Space,Str "of",Space,Span ("",[],[("custom-style","Emphatic")]) [Str "really",SoftBreak,Str "cool"],Space,Str "text."]]]
diff --git a/test/docx/custom-style-with-styles.native b/test/docx/custom-style-with-styles.native
new file mode 100644
--- /dev/null
+++ b/test/docx/custom-style-with-styles.native
@@ -0,0 +1,7 @@
+[Div ("",[],[("custom-style","First Paragraph")])
+ [Para [Str "This",Space,Str "is",Space,Str "some",Space,Str "text."]]
+,Div ("",[],[("custom-style","Body Text")])
+ [Para [Str "This",Space,Str "is",Space,Str "text",Space,Str "with",Space,Str "an",Space,Span ("",[],[("custom-style","Emphatic")]) [Str "emphasized"],Space,Str "text",Space,Str "style.",Space,Str "And",Space,Str "this",Space,Str "is",Space,Str "text",Space,Str "with",Space,Str "a",Space,Span ("",[],[("custom-style","Strengthened")]) [Str "strengthened"],Space,Str "text",Space,Str "style."]]
+,Div ("",[],[("custom-style","My Block Style")])
+ [BlockQuote
+  [Para [Str "Here",Space,Str "is",Space,Str "a",Space,Str "styled",Space,Str "paragraph",Space,Str "that",Space,Str "inherits",Space,Str "from",Space,Str "Block",Space,Str "Text."]]]]
diff --git a/test/docx/custom_style.native b/test/docx/custom_style.native
new file mode 100644
--- /dev/null
+++ b/test/docx/custom_style.native
@@ -0,0 +1,5 @@
+[Para [Str "This",Space,Str "is",Space,Str "a",Space,Str "test",Space,Str "of",Space,Str "custom-styles."]
+,Para [Str "Here",Space,Str "is",Space,Str "something",Space,Span ("",[],[("custom-style","Emphatic")]) [Str "emphasized"],Str ".",Space,Str "And",SoftBreak,Str "here",Space,Str "is",Space,Str "something",Space,Span ("",[],[("custom-style","Strengthened")]) [Str "strong"],Str "."]
+,Div ("",[],[("custom-style","My Block Style")])
+ [Para [Str "One",Space,Str "paragraph",Space,Str "of",Space,Str "text."]
+ ,Para [Str "And",Space,Str "another",Space,Str "paragraph",Space,Str "of",Space,Span ("",[],[("custom-style","Emphatic")]) [Str "really",SoftBreak,Str "cool"],Space,Str "text."]]]
diff --git a/test/docx/deep_normalize.docx b/test/docx/deep_normalize.docx
Binary files a/test/docx/deep_normalize.docx and b/test/docx/deep_normalize.docx differ
diff --git a/test/docx/deep_normalize.native b/test/docx/deep_normalize.native
--- a/test/docx/deep_normalize.native
+++ b/test/docx/deep_normalize.native
@@ -1,6 +1,6 @@
 [OrderedList (1,Decimal,OneParen)
  [[Para [Str "This",Space,Str "is",Space,Str "at",Space,Str "the",Space,Str "first",Space,Str "level"]
-  ,OrderedList (1,LowerAlpha,DefaultDelim)
+  ,OrderedList (1,LowerAlpha,OneParen)
    [[Para [Str "This",Space,Str "is",Space,Str "at",Space,Str "the",Space,Str "second",Space,Str "level"]
-    ,OrderedList (1,LowerRoman,DefaultDelim)
-     [[Para [Str "This",Space,Str "is",Space,Emph [Str "at",Space,Strong [Str "the",Space,Str "third",Space,Str "level"],Str ",",Space,Str "and",Space,Str "I",Space,Str "want",Space,Str "to"],Space,Str "test",Space,Str "normalization",Space,Str "here."]]]]]]]]
+    ,OrderedList (1,LowerRoman,OneParen)
+     [[Para [Str "This",Space,Str "is",Space,Emph [Str "at",Space,Strong [Str "the",Space,Span ("",["mark"],[]) [Str "th"],Str "i",Span ("",["mark"],[]) [Str "rd"],Space,Str "level"],Str ",",Space,Str "and",Space,Str "I",Space,Str "want",Space,Str "to"],Space,Str "test",Space,Str "normalization",Space,Str "here."]]]]]]]]
diff --git a/test/docx/definition_list.docx b/test/docx/definition_list.docx
Binary files a/test/docx/definition_list.docx and b/test/docx/definition_list.docx differ
diff --git a/test/docx/definition_list.native b/test/docx/definition_list.native
--- a/test/docx/definition_list.native
+++ b/test/docx/definition_list.native
@@ -1,7 +1,33 @@
-[DefinitionList
- [([Str "Term",Space,Str "1"],
-   [[Para [Str "Definition",Space,Str "1"]]])
- ,([Str "Term",Space,Str "2",Space,Str "with",Space,Emph [Str "inline",Space,Str "markup"]],
-   [[Para [Str "Definition",Space,Str "2"]
-    ,CodeBlock ("",[],[]) "{ some code, part of Definition 2 }"
-    ,Para [Str "Third",Space,Str "paragraph",Space,Str "of",Space,Str "definition",Space,Str "2."]]])]]
+[ DefinitionList
+    [ ( [ Str "Term" , Space , Str "1" ]
+      , [ [ Para [ Str "Definition" , Space , Str "1" ] ] ]
+      )
+    , ( [ Str "Term"
+        , Space
+        , Str "2"
+        , Space
+        , Str "with"
+        , Space
+        , Emph [ Str "inline" , Space , Str "markup" ]
+        ]
+      , [ [ Para [ Str "Definition" , Space , Str "2" ]
+          , Para
+              [ Code
+                  ( "" , [] , [] ) "{ some code, part of Definition 2 }"
+              ]
+          , Para
+              [ Str "Third"
+              , Space
+              , Str "paragraph"
+              , Space
+              , Str "of"
+              , Space
+              , Str "definition"
+              , Space
+              , Str "2."
+              ]
+          ]
+        ]
+      )
+    ]
+]
diff --git a/test/docx/diagram.docx b/test/docx/diagram.docx
new file mode 100644
Binary files /dev/null and b/test/docx/diagram.docx differ
diff --git a/test/docx/diagram.native b/test/docx/diagram.native
new file mode 100644
--- /dev/null
+++ b/test/docx/diagram.native
@@ -0,0 +1,2 @@
+[Header 1 ("diagram-after",[],[]) [Str "Diagram",Space,Str "after:"]
+,Para [Span ("",["diagram"],[]) [Str "[DIAGRAM]"]]]
diff --git a/test/docx/document-properties-short-desc.native b/test/docx/document-properties-short-desc.native
new file mode 100644
--- /dev/null
+++ b/test/docx/document-properties-short-desc.native
@@ -0,0 +1,2 @@
+Pandoc (Meta {unMeta = fromList [("author",MetaList [MetaInlines [Str "A.",Space,Str "M."]]),("description",MetaInlines [Str "Short",Space,RawInline (Format "html") "<i>",Str "description",RawInline (Format "html") "</i>",Space,Str "&."]),("keywords",MetaList [MetaInlines [Str "keyword",Space,Str "1"],MetaInlines [Str "keyword",Space,Str "2"]]),("subject",MetaInlines [Str "This",Space,Str "is",Space,Str "the",Space,Str "subject"]),("title",MetaInlines [Str "Testing",Space,Str "custom",Space,Str "properties"])]})
+[Para [Str "Testing",Space,Str "document",Space,Str "properties"]]
diff --git a/test/docx/document-properties.native b/test/docx/document-properties.native
new file mode 100644
--- /dev/null
+++ b/test/docx/document-properties.native
@@ -0,0 +1,2 @@
+Pandoc (Meta {unMeta = fromList [("Company",MetaInlines [Str "My",Space,Str "Company"]),("Second Custom Property",MetaInlines [Str "Second",Space,Str "custom",Space,Str "property",Space,Str "value"]),("abstract",MetaBlocks [Plain [Str "Quite",Space,Str "a",Space,Str "long",Space,Str "description",SoftBreak,Str "spanning",Space,Str "several",Space,Str "lines"]]),("author",MetaList [MetaInlines [Str "A.",Space,Str "M."]]),("category",MetaInlines [Str "My",Space,Str "Category"]),("custom1",MetaInlines [Str "First",Space,Str "custom",Space,Str "property",Space,Str "value"]),("custom3",MetaInlines [Str "Escaping",Space,Str "amp",Space,Str "&",Space,Str "."]),("custom4",MetaInlines [Str "Escaping",Space,Str "LT,GT",Space,Str "<",Space,Str "asdf",Space,Str ">",Space,Str "<"]),("custom5",MetaInlines [Str "Escaping",Space,Str "html",Space,RawInline (Format "html") "<i>",Str "asdf",RawInline (Format "html") "</i>"]),("custom6",MetaInlines [Str "Escaping",Space,Emph [Str "MD"],Space,Str "\225",Space,Str "a"]),("custom9",MetaInlines [Str "Extended",Space,Str "chars:",Space,Str "\8364",Space,Str "\225",Space,Str "\233",Space,Str "\237",Space,Str "\243",Space,Str "\250",Space,Str "$"]),("description",MetaBlocks [Para [Str "Long",Space,Str "description",Space,Str "spanning",SoftBreak,Str "several",Space,Str "lines."],Plain [Str "This",Space,Str "is",Space,Str "\225",Space,Str "second",Space,RawInline (Format "html") "<i>",Str "line",RawInline (Format "html") "</i>",Str "."]]),("keywords",MetaList [MetaInlines [Str "keyword",Space,Str "1"],MetaInlines [Str "keyword",Space,Str "2"]]),("lang",MetaInlines [Str "en-US"]),("nested-custom",MetaList [MetaMap (fromList [("custom 7",MetaInlines [Str "Nested",Space,Str "Custom",Space,Str "value",Space,Str "7"])]),MetaMap (fromList [("custom 8",MetaInlines [Str "Nested",Space,Str "Custom",Space,Str "value",Space,Str "8"])])]),("subject",MetaInlines [Str "This",Space,Str "is",Space,Str "the",Space,Str "subject"]),("subtitle",MetaInlines [Str "This",Space,Str "is",Space,Str "a",Space,Str "subtitle"]),("title",MetaInlines [Str "Testing",Space,Str "custom",Space,Str "properties"])]})
+[Para [Str "Testing",Space,Str "document",Space,Str "properties"]]
diff --git a/test/docx/drop_cap.docx b/test/docx/drop_cap.docx
Binary files a/test/docx/drop_cap.docx and b/test/docx/drop_cap.docx differ
diff --git a/test/docx/empty_field.docx b/test/docx/empty_field.docx
new file mode 100644
Binary files /dev/null and b/test/docx/empty_field.docx differ
diff --git a/test/docx/empty_field.native b/test/docx/empty_field.native
new file mode 100644
--- /dev/null
+++ b/test/docx/empty_field.native
@@ -0,0 +1,7 @@
+[Para
+    [Str "\24076\26395\28145\20837\20102\35299\30340\35835\32773\21487\20197\21435\30475David",Space,Str "French",Span ( "" , [ "indexref" ] , [ ( "entry" , "French" ) ] ) [],Space,Str "Belding\21644Kevin",Space,Str "J.",Space,Str "Mitchell\30340"
+    ,Link ("",[],[]) [Str "Foundations",Space,Str "of",Space,Str "Analysis,",Space,Str "2nd",Space,Str "Edition"] ("https://books.google.com/books?id=sp_Zcb9ot90C&lpg=PR4&hl=zh-CN&pg=PA19#v=onepage&q&f=true",""),Str ",\21487\20174\&19\39029\30475\36215\65292\25110D.C.",Space,Str "Goldrei\30340",Space
+    ,Link ("",[],[]) [Str "Classic",Space,Str "Set",Space,Str "Theory:",Space,Str "For",Space,Str "Guided",Space,Str "Independent",Space,Str "Study"] ("https://books.google.ae/books?id=dlc0DwAAQBAJ&lpg=PT29&hl=zh-CN&pg=PT26#v=onepage&q&f=true","")
+    ,Str "\65292\20174\31532\20108\31456\30475\36215\65292\38405\35835\26102\35201\27880\24847\26412\25991\19982\36825\20123\20070\25152\19981\21516\30340\26159\24182\27809\26377\25226\23454\25968\30475\20316\26159\26377\29702\25968\38598\30340\20998\21106\12290"]
+,Para [Str "Index:"]
+,Para [Str "French,",Space,Str "1"]]
diff --git a/test/docx/german-reference.docx b/test/docx/german-reference.docx
new file mode 100644
Binary files /dev/null and b/test/docx/german-reference.docx differ
diff --git a/test/docx/golden/block_quotes.docx b/test/docx/golden/block_quotes.docx
new file mode 100644
Binary files /dev/null and b/test/docx/golden/block_quotes.docx differ
diff --git a/test/docx/golden/codeblock.docx b/test/docx/golden/codeblock.docx
new file mode 100644
Binary files /dev/null and b/test/docx/golden/codeblock.docx differ
diff --git a/test/docx/golden/comments.docx b/test/docx/golden/comments.docx
new file mode 100644
Binary files /dev/null and b/test/docx/golden/comments.docx differ
diff --git a/test/docx/golden/custom_style_no_reference.docx b/test/docx/golden/custom_style_no_reference.docx
new file mode 100644
Binary files /dev/null and b/test/docx/golden/custom_style_no_reference.docx differ
diff --git a/test/docx/golden/custom_style_preserve.docx b/test/docx/golden/custom_style_preserve.docx
new file mode 100644
Binary files /dev/null and b/test/docx/golden/custom_style_preserve.docx differ
diff --git a/test/docx/golden/custom_style_reference.docx b/test/docx/golden/custom_style_reference.docx
new file mode 100644
Binary files /dev/null and b/test/docx/golden/custom_style_reference.docx differ
diff --git a/test/docx/golden/definition_list.docx b/test/docx/golden/definition_list.docx
new file mode 100644
Binary files /dev/null and b/test/docx/golden/definition_list.docx differ
diff --git a/test/docx/golden/document-properties-short-desc.docx b/test/docx/golden/document-properties-short-desc.docx
new file mode 100644
Binary files /dev/null and b/test/docx/golden/document-properties-short-desc.docx differ
diff --git a/test/docx/golden/document-properties.docx b/test/docx/golden/document-properties.docx
new file mode 100644
Binary files /dev/null and b/test/docx/golden/document-properties.docx differ
diff --git a/test/docx/golden/headers.docx b/test/docx/golden/headers.docx
new file mode 100644
Binary files /dev/null and b/test/docx/golden/headers.docx differ
diff --git a/test/docx/golden/image.docx b/test/docx/golden/image.docx
new file mode 100644
Binary files /dev/null and b/test/docx/golden/image.docx differ
diff --git a/test/docx/golden/inline_code.docx b/test/docx/golden/inline_code.docx
new file mode 100644
Binary files /dev/null and b/test/docx/golden/inline_code.docx differ
diff --git a/test/docx/golden/inline_formatting.docx b/test/docx/golden/inline_formatting.docx
new file mode 100644
Binary files /dev/null and b/test/docx/golden/inline_formatting.docx differ
diff --git a/test/docx/golden/inline_images.docx b/test/docx/golden/inline_images.docx
new file mode 100644
Binary files /dev/null and b/test/docx/golden/inline_images.docx differ
diff --git a/test/docx/golden/link_in_notes.docx b/test/docx/golden/link_in_notes.docx
new file mode 100644
Binary files /dev/null and b/test/docx/golden/link_in_notes.docx differ
diff --git a/test/docx/golden/links.docx b/test/docx/golden/links.docx
new file mode 100644
Binary files /dev/null and b/test/docx/golden/links.docx differ
diff --git a/test/docx/golden/lists.docx b/test/docx/golden/lists.docx
new file mode 100644
Binary files /dev/null and b/test/docx/golden/lists.docx differ
diff --git a/test/docx/golden/lists_9994.docx b/test/docx/golden/lists_9994.docx
new file mode 100644
Binary files /dev/null and b/test/docx/golden/lists_9994.docx differ
diff --git a/test/docx/golden/lists_continuing.docx b/test/docx/golden/lists_continuing.docx
new file mode 100644
Binary files /dev/null and b/test/docx/golden/lists_continuing.docx differ
diff --git a/test/docx/golden/lists_div_bullets.docx b/test/docx/golden/lists_div_bullets.docx
new file mode 100644
Binary files /dev/null and b/test/docx/golden/lists_div_bullets.docx differ
diff --git a/test/docx/golden/lists_multiple_initial.docx b/test/docx/golden/lists_multiple_initial.docx
new file mode 100644
Binary files /dev/null and b/test/docx/golden/lists_multiple_initial.docx differ
diff --git a/test/docx/golden/lists_restarting.docx b/test/docx/golden/lists_restarting.docx
new file mode 100644
Binary files /dev/null and b/test/docx/golden/lists_restarting.docx differ
diff --git a/test/docx/golden/nested_anchors_in_header.docx b/test/docx/golden/nested_anchors_in_header.docx
new file mode 100644
Binary files /dev/null and b/test/docx/golden/nested_anchors_in_header.docx differ
diff --git a/test/docx/golden/notes.docx b/test/docx/golden/notes.docx
new file mode 100644
Binary files /dev/null and b/test/docx/golden/notes.docx differ
diff --git a/test/docx/golden/raw-blocks.docx b/test/docx/golden/raw-blocks.docx
new file mode 100644
Binary files /dev/null and b/test/docx/golden/raw-blocks.docx differ
diff --git a/test/docx/golden/raw-bookmarks.docx b/test/docx/golden/raw-bookmarks.docx
new file mode 100644
Binary files /dev/null and b/test/docx/golden/raw-bookmarks.docx differ
diff --git a/test/docx/golden/table_one_row.docx b/test/docx/golden/table_one_row.docx
new file mode 100644
Binary files /dev/null and b/test/docx/golden/table_one_row.docx differ
diff --git a/test/docx/golden/table_with_list_cell.docx b/test/docx/golden/table_with_list_cell.docx
new file mode 100644
Binary files /dev/null and b/test/docx/golden/table_with_list_cell.docx differ
diff --git a/test/docx/golden/tables-default-widths.docx b/test/docx/golden/tables-default-widths.docx
new file mode 100644
Binary files /dev/null and b/test/docx/golden/tables-default-widths.docx differ
diff --git a/test/docx/golden/tables.docx b/test/docx/golden/tables.docx
new file mode 100644
Binary files /dev/null and b/test/docx/golden/tables.docx differ
diff --git a/test/docx/golden/tables_separated_with_rawblock.docx b/test/docx/golden/tables_separated_with_rawblock.docx
new file mode 100644
Binary files /dev/null and b/test/docx/golden/tables_separated_with_rawblock.docx differ
diff --git a/test/docx/golden/task_list.docx b/test/docx/golden/task_list.docx
new file mode 100644
Binary files /dev/null and b/test/docx/golden/task_list.docx differ
diff --git a/test/docx/golden/track_changes_deletion.docx b/test/docx/golden/track_changes_deletion.docx
new file mode 100644
Binary files /dev/null and b/test/docx/golden/track_changes_deletion.docx differ
diff --git a/test/docx/golden/track_changes_insertion.docx b/test/docx/golden/track_changes_insertion.docx
new file mode 100644
Binary files /dev/null and b/test/docx/golden/track_changes_insertion.docx differ
diff --git a/test/docx/golden/track_changes_move.docx b/test/docx/golden/track_changes_move.docx
new file mode 100644
Binary files /dev/null and b/test/docx/golden/track_changes_move.docx differ
diff --git a/test/docx/golden/track_changes_scrubbed_metadata.docx b/test/docx/golden/track_changes_scrubbed_metadata.docx
new file mode 100644
Binary files /dev/null and b/test/docx/golden/track_changes_scrubbed_metadata.docx differ
diff --git a/test/docx/golden/unicode.docx b/test/docx/golden/unicode.docx
new file mode 100644
Binary files /dev/null and b/test/docx/golden/unicode.docx differ
diff --git a/test/docx/golden/verbatim_subsuper.docx b/test/docx/golden/verbatim_subsuper.docx
new file mode 100644
Binary files /dev/null and b/test/docx/golden/verbatim_subsuper.docx differ
diff --git a/test/docx/hanging_indent.docx b/test/docx/hanging_indent.docx
Binary files a/test/docx/hanging_indent.docx and b/test/docx/hanging_indent.docx differ
diff --git a/test/docx/headers.docx b/test/docx/headers.docx
Binary files a/test/docx/headers.docx and b/test/docx/headers.docx differ
diff --git a/test/docx/image_vml.native b/test/docx/image_vml.native
--- a/test/docx/image_vml.native
+++ b/test/docx/image_vml.native
@@ -1,4 +1,3 @@
 [Header 1 ("vml-image",[],[]) [Strong [Str "VML",Space,Str "Image"]]
-,BlockQuote
- [Para [Str "It",Space,Str "should",Space,Str "follow",Space,Str "below:"]
- ,Para [Image ("",[],[]) [] ("media/image4.jpeg","")]]]
+,Para [Str "It",Space,Str "should",Space,Str "follow",Space,Str "below:"]
+,Para [Image ("",[],[]) [] ("media/image4.jpeg","")]]
diff --git a/test/docx/image_vml_as_object.docx b/test/docx/image_vml_as_object.docx
new file mode 100644
Binary files /dev/null and b/test/docx/image_vml_as_object.docx differ
diff --git a/test/docx/image_vml_as_object.native b/test/docx/image_vml_as_object.native
new file mode 100644
--- /dev/null
+++ b/test/docx/image_vml_as_object.native
@@ -0,0 +1,2 @@
+[Para [Str "Test",Space,Str "with",Space,Str "object",Space,Str "as",Space,Str "image:"]
+,Para [Image ("",[],[]) [] ("media/image1.emf","")]]
diff --git a/test/docx/image_with_textbox_caption.docx b/test/docx/image_with_textbox_caption.docx
new file mode 100644
Binary files /dev/null and b/test/docx/image_with_textbox_caption.docx differ
diff --git a/test/docx/image_with_textbox_caption.native b/test/docx/image_with_textbox_caption.native
new file mode 100644
--- /dev/null
+++ b/test/docx/image_with_textbox_caption.native
@@ -0,0 +1,44 @@
+[ Figure
+    ( "" , [] , [] )
+    (Caption
+       Nothing
+       [ Para
+           [ Str "1"
+           , Space
+           , Str "Daniel"
+           , Space
+           , Str "Schliebner:"
+           , Space
+           , Str "Cantor'sches"
+           , Space
+           , Str "Diagonalverfahren."
+           , Space
+           , Str "Von"
+           , Space
+           , Str "Mengen,"
+           , Space
+           , Str "Unendlichkeiten"
+           , Space
+           , Str "und"
+           , Space
+           , Str "Wahnsinn,"
+           , Space
+           , Str "Pdf:"
+           , Space
+           , Str
+               "https://www2.informatik.hu-berlin.de/~kossahl/Uni/Ma1/Cantor.pdf"
+           ]
+       ])
+    [ Plain
+        [ Image
+            ( ""
+            , []
+            , [ ( "width" , "2.3680555555555554in" )
+              , ( "height" , "0.9340277777777778in" )
+              ]
+            )
+            []
+            ( "media/image1.emf" , "" )
+        ]
+    ]
+]
diff --git a/test/docx/image_writer_test.native b/test/docx/image_writer_test.native
new file mode 100644
--- /dev/null
+++ b/test/docx/image_writer_test.native
@@ -0,0 +1,10 @@
+[Para [Str "No",Space,Str "width",Space,Str "given:"]
+,Para [Image ("fig:testimg",[],[]) [Str "testimg"] ("lalune.jpg","fig:")]
+,Para [Str "With",Space,Str "height",Space,Str "10cm:"]
+,Para [Image ("fig:2testimg",[],[("height","10cm")]) [Str "2testimg"] ("lalune.jpg","fig:")]
+,Para [Str "With",Space,Str "width",Space,Str "6cm:"]
+,Para [Image ("",[],[("width","6cm")]) [Str "3testimg"] ("lalune.jpg","fig:")]
+,Header 1 ("with-height-3in-and-width-6in",[],[]) [Str "With",Space,Str "height",Space,Str "3in",Space,Str "and",Space,Str "width",Space,Str "6in:"]
+,Para [Image ("",[],[("width","6in"),("height","3in")]) [Str "4testimg"] ("lalune.jpg","fig:")]
+,Para [RawInline (Format "openxml") "<w:fldSimple w:instr=\"REF ref_fig:testimg\" />"]
+,Para [RawInline (Format "openxml") "<w:fldSimple w:instr=\"REF ref_fig:2testimg\" />"]]
diff --git a/test/docx/inline_formatting.docx b/test/docx/inline_formatting.docx
Binary files a/test/docx/inline_formatting.docx and b/test/docx/inline_formatting.docx differ
diff --git a/test/docx/inline_formatting.native b/test/docx/inline_formatting.native
--- a/test/docx/inline_formatting.native
+++ b/test/docx/inline_formatting.native
@@ -1,5 +1,6 @@
+Pandoc (Meta {unMeta = fromList []})
 [Para [Str "Regular",Space,Str "text",Space,Emph [Str "italics"],Space,Strong [Str "bold",Space,Emph [Str "bold",Space,Str "italics"]],Str "."]
 ,Para [Str "This",Space,Str "is",Space,SmallCaps [Str "Small",Space,Str "Caps"],Str ",",Space,Str "and",Space,Str "this",Space,Str "is",Space,Strikeout [Str "strikethrough"],Str "."]
-,Para [Str "Some",Space,Str "people",Space,Str "use",Space,Span ("",["underline"],[]) [Str "single",Space,Str "underlines",Space,Str "for",Space,Emph [Str "emphasis"]],Str "."]
+,Para [Str "Some",Space,Str "people",Space,Str "use",Space,Underline [Str "single",Space,Str "underlines",Space,Str "for",Space,Emph [Str "emphasis"]],Str "."]
 ,Para [Str "Above",Space,Str "the",Space,Str "line",Space,Str "is",Space,Superscript [Str "superscript"],Space,Str "and",Space,Str "below",Space,Str "the",Space,Str "line",Space,Str "is",Space,Subscript [Str "subscript"],Str "."]
 ,Para [Str "A",Space,Str "line",LineBreak,Str "break."]]
diff --git a/test/docx/inline_images.docx b/test/docx/inline_images.docx
Binary files a/test/docx/inline_images.docx and b/test/docx/inline_images.docx differ
diff --git a/test/docx/inline_images_writer_test.native b/test/docx/inline_images_writer_test.native
new file mode 100644
--- /dev/null
+++ b/test/docx/inline_images_writer_test.native
@@ -0,0 +1,2 @@
+[Para [Str "This",Space,Str "picture",Space,Image ("",[],[("width","0.8888888888888888in"),("height","0.8888888888888888in")]) [Str "This",Space,Str "one",Space,Str "is",Space,Str "green",Space,Str "and",Space,Str "looks",Space,Str "like",Space,Str "Sideshow",Space,Str "Bob."] ("lalune.jpg","First identicon"),Space,Str "is",Space,Str "an",Space,Str "identicon."]
+,Para [Str "Here",Space,Str "is",Space,Link ("",[],[]) [Str "one",Space,Image ("",[],[("width","0.8888888888888888in"),("height","0.8888888888888888in")]) [Str "This",Space,Str "one",Space,Str "is",Space,Str "reddish,",Space,Str "and",Space,Str "looks",Space,Str "like",Space,Str "a",Space,Str "heart",Space,Str "that",Space,Str "has",Space,Str "leaked",Space,Str "out."] ("lalune.jpg","Second identicon"),Space,Str "that"] ("http://www.google.com",""),Space,Str "links."]]
diff --git a/test/docx/instrText_hyperlink.docx b/test/docx/instrText_hyperlink.docx
new file mode 100644
Binary files /dev/null and b/test/docx/instrText_hyperlink.docx differ
diff --git a/test/docx/instrText_hyperlink.native b/test/docx/instrText_hyperlink.native
new file mode 100644
--- /dev/null
+++ b/test/docx/instrText_hyperlink.native
@@ -0,0 +1,1 @@
+[Para [Str "\24076\26395\28145\20837\20102\35299\30340\35835\32773\21487\20197\21435\30475David",Space,Str "French",Space,Str "Belding\21644Kevin",Space,Str "J.",Space,Str "Mitchell\30340",Link ("",[],[]) [Str "Foundations",Space,Str "of",Space,Str "Analysis,",Space,Str "2nd",Space,Str "Edition"] ("https://books.google.com/books?id=sp_Zcb9ot90C&lpg=PR4&hl=zh-CN&pg=PA19#v=onepage&q&f=true",""),Str ",\21487\20174\&19\39029\30475\36215\65292\25110D.C.",Space,Str "Goldrei\30340",Space,Link ("",[],[]) [Str "Classic",Space,Str "Set",Space,Str "Theory:",Space,Str "For",Space,Str "Guided",Space,Str "Independent",Space,Str "Study"] ("https://books.google.ae/books?id=dlc0DwAAQBAJ&lpg=PT29&hl=zh-CN&pg=PT26#v=onepage&q&f=true",""),Str "\65292\20174\31532\20108\31456\30475\36215\65292\38405\35835\26102\35201\27880\24847\26412\25991\19982\36825\20123\20070\25152\19981\21516\30340\26159\24182\27809\26377\25226\23454\25968\30475\20316\26159\26377\29702\25968\38598\30340\20998\21106\12290"]]
diff --git a/test/docx/link_in_notes.docx b/test/docx/link_in_notes.docx
Binary files a/test/docx/link_in_notes.docx and b/test/docx/link_in_notes.docx differ
diff --git a/test/docx/links.docx b/test/docx/links.docx
Binary files a/test/docx/links.docx and b/test/docx/links.docx differ
diff --git a/test/docx/lists-compact.docx b/test/docx/lists-compact.docx
new file mode 100644
Binary files /dev/null and b/test/docx/lists-compact.docx differ
diff --git a/test/docx/lists-compact.native b/test/docx/lists-compact.native
new file mode 100644
--- /dev/null
+++ b/test/docx/lists-compact.native
@@ -0,0 +1,5 @@
+[OrderedList (1,Decimal,Period)
+ [[Plain [Str "One"]]
+ ,[Plain [Str "Two"]]
+ ,[Plain [Str "Three"]]
+ ,[Plain [Str "Four"]]]]
diff --git a/test/docx/lists.docx b/test/docx/lists.docx
Binary files a/test/docx/lists.docx and b/test/docx/lists.docx differ
diff --git a/test/docx/lists.native b/test/docx/lists.native
--- a/test/docx/lists.native
+++ b/test/docx/lists.native
@@ -2,7 +2,7 @@
 ,OrderedList (1,Decimal,Period)
  [[Para [Str "one"]]
  ,[Para [Str "two"]
-  ,OrderedList (1,LowerAlpha,DefaultDelim)
+  ,OrderedList (1,LowerAlpha,Period)
    [[Para [Str "a"]]
    ,[Para [Str "b"]]]]]
 ,BulletList
@@ -15,4 +15,4 @@
       ,Para [Str "Sub",Space,Str "paragraph"]]]]]]
  ,[Para [Str "Same",Space,Str "list"]]]
 ,BulletList
- [[Para [Str "Different",Space,Str "list",Space,Str "adjacent",Space,Str "to",Space,Str "the",Space,Str "one",Space,Str "above."]]]]
+ [[Plain [Str "Different",Space,Str "list",Space,Str "adjacent",Space,Str "to",Space,Str "the",Space,Str "one",Space,Str "above."]]]]
diff --git a/test/docx/lists_9994.native b/test/docx/lists_9994.native
new file mode 100644
--- /dev/null
+++ b/test/docx/lists_9994.native
@@ -0,0 +1,8 @@
+[ OrderedList
+    ( 1 , Decimal , Period )
+    [ [ Plain [ Str "one" ]
+      , BulletList [ [ Plain [ Str "bul" ] ] ]
+      ]
+    , [ Plain [ Str "two" ] ]
+    ]
+]
diff --git a/test/docx/lists_div_bullets.native b/test/docx/lists_div_bullets.native
new file mode 100644
--- /dev/null
+++ b/test/docx/lists_div_bullets.native
@@ -0,0 +1,5 @@
+[ BulletList
+  [ [ Div ( "", [], []) [ Para [ Str "one" ], Para [ Str "two" ] ] ]
+  , [ Div ( "refs", [], []) [ Header 1 ( "" , [] , [] ) [ Str "three" ], Para [ Str "four" ] ] ]
+  ]
+]
diff --git a/test/docx/lists_level_override.docx b/test/docx/lists_level_override.docx
new file mode 100644
Binary files /dev/null and b/test/docx/lists_level_override.docx differ
diff --git a/test/docx/lists_level_override.native b/test/docx/lists_level_override.native
new file mode 100644
--- /dev/null
+++ b/test/docx/lists_level_override.native
@@ -0,0 +1,266 @@
+Pandoc
+  Meta { unMeta = fromList [] }
+  [ Para
+      [ Str "For"
+      , Space
+      , Str "each"
+      , Space
+      , Str "initiative"
+      , Space
+      , Str "below"
+      , Space
+      , Str "is"
+      , Space
+      , Str "outlined"
+      , Space
+      , Str "the"
+      , Space
+      , Str "goals,"
+      , Space
+      , Str "an"
+      , Space
+      , Str "approximate"
+      , Space
+      , Str "roadmap"
+      , Space
+      , Str "which"
+      , Space
+      , Str "will"
+      , Space
+      , Str "likely"
+      , Space
+      , Str "change"
+      , Space
+      , Str "as"
+      , Space
+      , Str "we"
+      , Space
+      , Str "iterate,"
+      , Space
+      , Str "signals/metrics"
+      , Space
+      , Str "to"
+      , Space
+      , Str "measure"
+      , Space
+      , Str "success,"
+      , Space
+      , Str "and"
+      , Space
+      , Str "initial"
+      , Space
+      , Str "workitems"
+      , Space
+      , Str "with"
+      , Space
+      , Str "a"
+      , Space
+      , Str "rough"
+      , Space
+      , Strong [ Str "schedule" ]
+      , Space
+      , Str "and"
+      , Space
+      , Str "contacts"
+      , Space
+      , Str "where"
+      , Space
+      , Str "available:"
+      ]
+  , Para [ Str "\160" ]
+  , OrderedList
+      ( 1 , Decimal , Period )
+      [ [ Para
+            [ Str "State"
+            , Space
+            , Str "of"
+            , Space
+            , Str "Documentation"
+            ]
+        ]
+      ]
+  , BlockQuote
+      [ Para
+          [ Strong
+              [ Str "Goal:"
+              , Space
+              , Str "Baseline"
+              , Space
+              , Str "and"
+              , Space
+              , Str "ongoing"
+              , Space
+              , Str "metrics"
+              , Space
+              , Str "tracking"
+              , Space
+              , Str "doc"
+              , Space
+              , Str "usefulness"
+              , Space
+              , Str "and"
+              , Space
+              , Str "completeness."
+              ]
+          ]
+      , Para [ Str "\160" ]
+      ]
+  , OrderedList
+      ( 2 , Decimal , Period )
+      [ [ Para [ Str "Content" , Space , Str "Migration" ] ] ]
+  , BlockQuote
+      [ Para
+          [ Str "Goal:"
+          , Space
+          , Str "Content"
+          , Space
+          , Str "is"
+          , Space
+          , Str "accessible"
+          , Space
+          , Str "to"
+          , Space
+          , Str "new"
+          , Space
+          , Str "employees"
+          , Space
+          , Str "and"
+          , Space
+          , Str "is"
+          , Space
+          , Str "better"
+          , Space
+          , Str "organized/archived."
+          ]
+      , Para [ Str "\160" ]
+      ]
+  , OrderedList
+      ( 3 , Decimal , Period )
+      [ [ Para [ Str "Wiki" , Space , Str "(xl)" ] ] ]
+  , BlockQuote
+      [ Para
+          [ Strong
+              [ Str "Goal:"
+              , Space
+              , Str "Useful"
+              , Space
+              , Str "documentation"
+              , Space
+              , Str "that"
+              , Space
+              , Str "is"
+              , Space
+              , Str "archived,"
+              , Space
+              , Str "searchable"
+              , Space
+              , Str "and"
+              , Space
+              , Str "easy"
+              , Space
+              , Str "to"
+              , Space
+              , Str "create"
+              ]
+          ]
+      , Para [ Str "\160\160" ]
+      ]
+  , OrderedList
+      ( 4 , Decimal , Period )
+      [ [ Para
+            [ Str "XL"
+            , Space
+            , Str "Code"
+            , Space
+            , Str "Autoreview"
+            , Space
+            , Str "Bot"
+            , Space
+            , Str "(XLCRBot)."
+            ]
+        ]
+      ]
+  , BlockQuote
+      [ Para
+          [ Strong
+              [ Str "Goal:"
+              , Space
+              , Str "Feedback"
+              , Space
+              , Str "on"
+              , Space
+              , Str "basic"
+              , Space
+              , Str "violations"
+              , Space
+              , Str "in"
+              , Space
+              , Str "seconds"
+              , Space
+              , Str "or"
+              , Space
+              , Str "minutes"
+              , Space
+              , Str "at"
+              , Space
+              , Str "most"
+              , Space
+              , Str "in"
+              , Space
+              , Str "either"
+              , Space
+              , Str "VS"
+              , Space
+              , Str "or"
+              , Space
+              , Str "Codeflow."
+              ]
+          ]
+      ]
+  , OrderedList
+      ( 5 , Decimal , Period )
+      [ [ 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"
+              ]
+          ]
+      ]
+  , Para [ Strong [ Str "\160" ] , Str "\160" ]
+  , OrderedList
+      ( 6 , Decimal , Period )
+      [ [ Para [ Str "Education" , Space , Str "efforts" ] ] ]
+  , BlockQuote
+      [ Para
+          [ Strong
+              [ Str "Goal:"
+              , Space
+              , Str "Broad,"
+              , Space
+              , Str "discoverable"
+              , Space
+              , Str "channels"
+              , Space
+              , Str "for"
+              , Space
+              , Str "updates"
+              , Space
+              , Str "and"
+              , Space
+              , Str "news"
+              ]
+          ]
+      ]
+  , Para [ Strong [ Str "\160" ] ]
+  ]
diff --git a/test/docx/lists_multiple_initial.native b/test/docx/lists_multiple_initial.native
new file mode 100644
--- /dev/null
+++ b/test/docx/lists_multiple_initial.native
@@ -0,0 +1,8 @@
+[OrderedList (1,Decimal,Period)
+ [[OrderedList (1,LowerAlpha,TwoParens)
+   [[Para [Str "foo"]]
+   ,[Para [Str "bar"]]]]]
+,BulletList
+ [[BulletList
+   [[Para [Str "foo"]]
+   ,[Para [Str "bar"]]]]]]
diff --git a/test/docx/lists_sublist_reset.docx b/test/docx/lists_sublist_reset.docx
new file mode 100644
Binary files /dev/null and b/test/docx/lists_sublist_reset.docx differ
diff --git a/test/docx/lists_sublist_reset.native b/test/docx/lists_sublist_reset.native
new file mode 100644
--- /dev/null
+++ b/test/docx/lists_sublist_reset.native
@@ -0,0 +1,8 @@
+[OrderedList (1,Decimal,Period)
+ [[Para [Str "Head",Space,Str "1"]
+  ,OrderedList (1,Decimal,DefaultDelim)
+   [[Para [Str "Head",Space,Str "1.1"]]
+   ,[Para [Str "Head",Space,Str "1.2"]]]]
+ ,[Para [Str "Head",Space,Str "2"]
+  ,OrderedList (1,Decimal,DefaultDelim)
+   [[Para [Str "Head",Space,Str "2.1"]]]]]]
diff --git a/test/docx/mendeley_citations.docx b/test/docx/mendeley_citations.docx
new file mode 100644
Binary files /dev/null and b/test/docx/mendeley_citations.docx differ
diff --git a/test/docx/mendeley_citations_minus.native b/test/docx/mendeley_citations_minus.native
new file mode 100644
--- /dev/null
+++ b/test/docx/mendeley_citations_minus.native
@@ -0,0 +1,318 @@
+Pandoc
+  Meta { unMeta = fromList [] }
+  [ Para
+      [ Str "This"
+      , Space
+      , Str "is"
+      , Space
+      , Str "a"
+      , Space
+      , Str "Mendeley"
+      , Space
+      , Str "test"
+      , Space
+      , Str "(prefix"
+      , Space
+      , Str "Hadwen-Bennett"
+      , Space
+      , Str "et"
+      , Space
+      , Str "al.,"
+      , Space
+      , Str "2018,"
+      , Space
+      , Str "p."
+      , Space
+      , Str "123"
+      , Space
+      , Str "suffix)."
+      ]
+  , Para
+      [ Str "Another"
+      , Space
+      , Str "test"
+      , Space
+      , Str "(prefix"
+      , Space
+      , Str "Seo,"
+      , Space
+      , Str "2019,"
+      , Space
+      , Str "pp."
+      , Space
+      , Str "10\8211\&20"
+      , Space
+      , Str "suffix)."
+      ]
+  , Para
+      [ Str "The"
+      , Space
+      , Str "last"
+      , Space
+      , Str "test"
+      , Space
+      , Str "(Koh"
+      , Space
+      , Str "&"
+      , Space
+      , Str "Abbas,"
+      , Space
+      , Str "2015;"
+      , Space
+      , Str "Lee"
+      , Space
+      , Str "et"
+      , Space
+      , Str "al.,"
+      , Space
+      , Str "2011)."
+      ]
+  , Header 1 ( "references" , [] , [] ) [ Str "References" ]
+  , Para
+      [ Str "Hadwen-Bennett,"
+      , Space
+      , Str "A.,"
+      , Space
+      , Str "Sentance,"
+      , Space
+      , Str "S.,"
+      , Space
+      , Str "&"
+      , Space
+      , Str "Morrison,"
+      , Space
+      , Str "C."
+      , Space
+      , Str "(2018)."
+      , Space
+      , Str "Making"
+      , Space
+      , Str "Programming"
+      , Space
+      , Str "Accessible"
+      , Space
+      , Str "to"
+      , Space
+      , Str "Learners"
+      , Space
+      , Str "with"
+      , Space
+      , Str "Visual"
+      , Space
+      , Str "Impairments:"
+      , Space
+      , Str "A"
+      , Space
+      , Str "Literature"
+      , Space
+      , Str "Review."
+      , Space
+      , Emph
+          [ Str "International"
+          , Space
+          , Str "Journal"
+          , Space
+          , Str "of"
+          , Space
+          , Str "Computer"
+          , Space
+          , Str "Science"
+          , Space
+          , Str "Education"
+          , Space
+          , Str "in"
+          , Space
+          , Str "Schools"
+          ]
+      , Str ","
+      , Space
+      , Emph [ Str "2" ]
+      , Str "(2),"
+      , Space
+      , Str "3\8211\&13."
+      , Space
+      , Str
+          "https://www.microsoft.com/en-us/research/publication/making-programming-accessible-to-learners-with-visual-impairments-a-literature-review/"
+      ]
+  , Para
+      [ Str "Koh,"
+      , Space
+      , Str "K.,"
+      , Space
+      , Str "&"
+      , Space
+      , Str "Abbas,"
+      , Space
+      , Str "J."
+      , Space
+      , Str "(2015)."
+      , Space
+      , Str "Future"
+      , Space
+      , Str "of"
+      , Space
+      , Str "library"
+      , Space
+      , Str "and"
+      , Space
+      , Str "museum"
+      , Space
+      , Str "services"
+      , Space
+      , Str "supporting"
+      , Space
+      , Str "teen"
+      , Space
+      , Str "learning:"
+      , Space
+      , Str "Perceptions"
+      , Space
+      , Str "of"
+      , Space
+      , Str "professionals"
+      , Space
+      , Str "in"
+      , Space
+      , Str "learning"
+      , Space
+      , Str "labs"
+      , Space
+      , Str "and"
+      , Space
+      , Str "makerspaces."
+      , Space
+      , Emph
+          [ Str "Journal"
+          , Space
+          , Str "of"
+          , Space
+          , Str "Research"
+          , Space
+          , Str "on"
+          , Space
+          , Str "Libraries"
+          , Space
+          , Str "\\&"
+          , Space
+          , Str "Young"
+          , Space
+          , Str "Adults"
+          ]
+      , Str ","
+      , Space
+      , Emph [ Str "6" ]
+      , Str "(4)."
+      ]
+  , Para
+      [ Str "Lee,"
+      , Space
+      , Str "I.,"
+      , Space
+      , Str "Martin,"
+      , Space
+      , Str "F.,"
+      , Space
+      , Str "Denner,"
+      , Space
+      , Str "J.,"
+      , Space
+      , Str "Coulter,"
+      , Space
+      , Str "B.,"
+      , Space
+      , Str "Allan,"
+      , Space
+      , Str "W.,"
+      , Space
+      , Str "Erickson,"
+      , Space
+      , Str "J.,"
+      , Space
+      , Str "Malyn-Smith,"
+      , Space
+      , Str "J.,"
+      , Space
+      , Str "&"
+      , Space
+      , Str "Werner,"
+      , Space
+      , Str "L."
+      , Space
+      , Str "(2011)."
+      , Space
+      , Str "Computational"
+      , Space
+      , Str "Thinking"
+      , Space
+      , Str "for"
+      , Space
+      , Str "Youth"
+      , Space
+      , Str "in"
+      , Space
+      , Str "Practice."
+      , Space
+      , Emph [ Str "ACM" , Space , Str "Inroads" ]
+      , Str ","
+      , Space
+      , Emph [ Str "2" ]
+      , Str "(1),"
+      , Space
+      , Str "32\8211\&37."
+      , Space
+      , Str "https://doi.org/10.1145/1929887.1929902"
+      ]
+  , Para
+      [ Str "Seo,"
+      , Space
+      , Str "J."
+      , Space
+      , Str "(2019)."
+      , Space
+      , Str "Is"
+      , Space
+      , Str "the"
+      , Space
+      , Str "Maker"
+      , Space
+      , Str "Movement"
+      , Space
+      , Str "Inclusive"
+      , Space
+      , Str "of"
+      , Space
+      , Str "{ANYONE}?:"
+      , Space
+      , Str "Three"
+      , Space
+      , Str "Accessibility"
+      , Space
+      , Str "Considerations"
+      , Space
+      , Str "to"
+      , Space
+      , Str "Invite"
+      , Space
+      , Str "Blind"
+      , Space
+      , Str "Makers"
+      , Space
+      , Str "to"
+      , Space
+      , Str "the"
+      , Space
+      , Str "Making"
+      , Space
+      , Str "World."
+      , Space
+      , Emph [ Str "TechTrends" ]
+      , Str ","
+      , Space
+      , Emph [ Str "63" ]
+      , Str "(5),"
+      , Space
+      , Str "514\8211\&520."
+      , Space
+      , Str "https://doi.org/10.1007/s11528-019-00377-3"
+      ]
+  ]
diff --git a/test/docx/mendeley_citations_plus.native b/test/docx/mendeley_citations_plus.native
new file mode 100644
--- /dev/null
+++ b/test/docx/mendeley_citations_plus.native
@@ -0,0 +1,374 @@
+Pandoc
+  Meta
+    { unMeta =
+        fromList
+          [ ( "references"
+            , MetaList
+                [ MetaMap
+                    (fromList
+                       [ ( "DOI"
+                         , MetaString "10.1145/1929887.1929902"
+                         )
+                       , ( "ISSN" , MetaString "2153-2184" )
+                       , ( "author"
+                         , MetaList
+                             [ MetaMap
+                                 (fromList
+                                    [ ( "dropping-particle"
+                                      , MetaString ""
+                                      )
+                                    , ( "family" , MetaString "Lee" )
+                                    , ( "given" , MetaString "Irene" )
+                                    , ( "non-dropping-particle"
+                                      , MetaString ""
+                                      )
+                                    , ( "suffix" , MetaString "" )
+                                    ])
+                             , MetaMap
+                                 (fromList
+                                    [ ( "dropping-particle"
+                                      , MetaString ""
+                                      )
+                                    , ( "family" , MetaString "Martin" )
+                                    , ( "given" , MetaString "Fred" )
+                                    , ( "non-dropping-particle"
+                                      , MetaString ""
+                                      )
+                                    , ( "suffix" , MetaString "" )
+                                    ])
+                             , MetaMap
+                                 (fromList
+                                    [ ( "dropping-particle"
+                                      , MetaString ""
+                                      )
+                                    , ( "family" , MetaString "Denner" )
+                                    , ( "given" , MetaString "Jill" )
+                                    , ( "non-dropping-particle"
+                                      , MetaString ""
+                                      )
+                                    , ( "suffix" , MetaString "" )
+                                    ])
+                             , MetaMap
+                                 (fromList
+                                    [ ( "dropping-particle"
+                                      , MetaString ""
+                                      )
+                                    , ( "family"
+                                      , MetaString "Coulter"
+                                      )
+                                    , ( "given" , MetaString "Bob" )
+                                    , ( "non-dropping-particle"
+                                      , MetaString ""
+                                      )
+                                    , ( "suffix" , MetaString "" )
+                                    ])
+                             , MetaMap
+                                 (fromList
+                                    [ ( "dropping-particle"
+                                      , MetaString ""
+                                      )
+                                    , ( "family" , MetaString "Allan" )
+                                    , ( "given" , MetaString "Walter" )
+                                    , ( "non-dropping-particle"
+                                      , MetaString ""
+                                      )
+                                    , ( "suffix" , MetaString "" )
+                                    ])
+                             , MetaMap
+                                 (fromList
+                                    [ ( "dropping-particle"
+                                      , MetaString ""
+                                      )
+                                    , ( "family"
+                                      , MetaString "Erickson"
+                                      )
+                                    , ( "given" , MetaString "Jeri" )
+                                    , ( "non-dropping-particle"
+                                      , MetaString ""
+                                      )
+                                    , ( "suffix" , MetaString "" )
+                                    ])
+                             , MetaMap
+                                 (fromList
+                                    [ ( "dropping-particle"
+                                      , MetaString ""
+                                      )
+                                    , ( "family"
+                                      , MetaString "Malyn-Smith"
+                                      )
+                                    , ( "given" , MetaString "Joyce" )
+                                    , ( "non-dropping-particle"
+                                      , MetaString ""
+                                      )
+                                    , ( "suffix" , MetaString "" )
+                                    ])
+                             , MetaMap
+                                 (fromList
+                                    [ ( "dropping-particle"
+                                      , MetaString ""
+                                      )
+                                    , ( "family" , MetaString "Werner" )
+                                    , ( "given" , MetaString "Linda" )
+                                    , ( "non-dropping-particle"
+                                      , MetaString ""
+                                      )
+                                    , ( "suffix" , MetaString "" )
+                                    ])
+                             ]
+                         )
+                       , ( "container-title"
+                         , MetaInlines
+                             [ Str "ACM" , Space , Str "Inroads" ]
+                         )
+                       , ( "id" , MetaString "ITEM-1" )
+                       , ( "issue" , MetaInlines [ Str "1" ] )
+                       , ( "issued" , MetaString "2011-02" )
+                       , ( "page" , MetaInlines [ Str "32-37" ] )
+                       , ( "publisher" , MetaInlines [ Str "ACM" ] )
+                       , ( "publisher-place"
+                         , MetaInlines
+                             [ Str "New"
+                             , Space
+                             , Str "York,"
+                             , Space
+                             , Str "NY,"
+                             , Space
+                             , Str "USA"
+                             ]
+                         )
+                       , ( "title"
+                         , MetaInlines
+                             [ Str "Computational"
+                             , Space
+                             , Str "Thinking"
+                             , Space
+                             , Str "for"
+                             , Space
+                             , Str "Youth"
+                             , Space
+                             , Str "in"
+                             , Space
+                             , Str "Practice"
+                             ]
+                         )
+                       , ( "type" , MetaString "article-journal" )
+                       , ( "volume" , MetaInlines [ Str "2" ] )
+                       ])
+                , MetaMap
+                    (fromList
+                       [ ( "author"
+                         , MetaList
+                             [ MetaMap
+                                 (fromList
+                                    [ ( "dropping-particle"
+                                      , MetaString ""
+                                      )
+                                    , ( "family" , MetaString "Koh" )
+                                    , ( "given"
+                                      , MetaString "Kyungwon"
+                                      )
+                                    , ( "non-dropping-particle"
+                                      , MetaString ""
+                                      )
+                                    , ( "suffix" , MetaString "" )
+                                    ])
+                             , MetaMap
+                                 (fromList
+                                    [ ( "dropping-particle"
+                                      , MetaString ""
+                                      )
+                                    , ( "family" , MetaString "Abbas" )
+                                    , ( "given" , MetaString "June" )
+                                    , ( "non-dropping-particle"
+                                      , MetaString ""
+                                      )
+                                    , ( "suffix" , MetaString "" )
+                                    ])
+                             ]
+                         )
+                       , ( "container-title"
+                         , MetaInlines
+                             [ Str "Journal"
+                             , Space
+                             , Str "of"
+                             , Space
+                             , Str "Research"
+                             , Space
+                             , Str "on"
+                             , Space
+                             , Str "Libraries"
+                             , Space
+                             , Str "\\&"
+                             , Space
+                             , Str "Young"
+                             , Space
+                             , Str "Adults"
+                             ]
+                         )
+                       , ( "id" , MetaString "ITEM-2" )
+                       , ( "issue" , MetaInlines [ Str "4" ] )
+                       , ( "issued" , MetaString "2015" )
+                       , ( "title"
+                         , MetaInlines
+                             [ Str "Future"
+                             , Space
+                             , Str "of"
+                             , Space
+                             , Str "library"
+                             , Space
+                             , Str "and"
+                             , Space
+                             , Str "museum"
+                             , Space
+                             , Str "services"
+                             , Space
+                             , Str "supporting"
+                             , Space
+                             , Str "teen"
+                             , Space
+                             , Str "learning:"
+                             , Space
+                             , Str "Perceptions"
+                             , Space
+                             , Str "of"
+                             , Space
+                             , Str "professionals"
+                             , Space
+                             , Str "in"
+                             , Space
+                             , Str "learning"
+                             , Space
+                             , Str "labs"
+                             , Space
+                             , Str "and"
+                             , Space
+                             , Str "makerspaces"
+                             ]
+                         )
+                       , ( "type" , MetaString "article-journal" )
+                       , ( "volume" , MetaInlines [ Str "6" ] )
+                       ])
+                ]
+            )
+          ]
+    }
+  [ Para
+      [ Str "This"
+      , Space
+      , Str "is"
+      , Space
+      , Str "a"
+      , Space
+      , Str "Mendeley"
+      , Space
+      , Str "test"
+      , Space
+      , Cite
+          [ Citation
+              { citationId = "ITEM-1"
+              , citationPrefix = [ Str "prefix" ]
+              , citationSuffix =
+                  [ Str "," , Space , Str "123" , Space , Str "suffix" ]
+              , citationMode = NormalCitation
+              , citationNoteNum = 0
+              , citationHash = 0
+              }
+          ]
+          [ Str "(prefix"
+          , Space
+          , Str "Hadwen-Bennett"
+          , Space
+          , Str "et"
+          , Space
+          , Str "al.,"
+          , Space
+          , Str "2018,"
+          , Space
+          , Str "p."
+          , Space
+          , Str "123"
+          , Space
+          , Str "suffix)"
+          ]
+      , Str "."
+      ]
+  , Para
+      [ Str "Another"
+      , Space
+      , Str "test"
+      , Space
+      , Cite
+          [ Citation
+              { citationId = "ITEM-1"
+              , citationPrefix = [ Str "prefix" ]
+              , citationSuffix =
+                  [ Str ","
+                  , Space
+                  , Str "10-20"
+                  , Space
+                  , Str "suffix"
+                  ]
+              , citationMode = NormalCitation
+              , citationNoteNum = 0
+              , citationHash = 0
+              }
+          ]
+          [ Str "(prefix"
+          , Space
+          , Str "Seo,"
+          , Space
+          , Str "2019,"
+          , Space
+          , Str "pp."
+          , Space
+          , Str "10\8211\&20"
+          , Space
+          , Str "suffix)"
+          ]
+      , Str "."
+      ]
+  , Para
+      [ Str "The"
+      , Space
+      , Str "last"
+      , Space
+      , Str "test"
+      , Space
+      , Cite
+          [ Citation
+              { citationId = "ITEM-1"
+              , citationPrefix = []
+              , citationSuffix = []
+              , citationMode = NormalCitation
+              , citationNoteNum = 0
+              , citationHash = 0
+              }
+          , Citation
+              { citationId = "ITEM-2"
+              , citationPrefix = []
+              , citationSuffix = []
+              , citationMode = NormalCitation
+              , citationNoteNum = 0
+              , citationHash = 0
+              }
+          ]
+          [ Str "(Koh"
+          , Space
+          , Str "&"
+          , Space
+          , Str "Abbas,"
+          , Space
+          , Str "2015;"
+          , Space
+          , Str "Lee"
+          , Space
+          , Str "et"
+          , Space
+          , Str "al.,"
+          , Space
+          , Str "2011)"
+          ]
+      , Str "."
+      ]
+  , Header 1 ( "references" , [] , [] ) [ Str "References" ]
+  ]
diff --git a/test/docx/metadata.docx b/test/docx/metadata.docx
Binary files a/test/docx/metadata.docx and b/test/docx/metadata.docx differ
diff --git a/test/docx/metadata_after_normal.docx b/test/docx/metadata_after_normal.docx
Binary files a/test/docx/metadata_after_normal.docx and b/test/docx/metadata_after_normal.docx differ
diff --git a/test/docx/nested_anchors_in_header.native b/test/docx/nested_anchors_in_header.native
--- a/test/docx/nested_anchors_in_header.native
+++ b/test/docx/nested_anchors_in_header.native
@@ -1,4 +1,9 @@
-[Header 1 ("short-instructions",[],[]) [Str "Short",Space,Str "instructions"]
+[Header 1 ("\1086\1075\1083\1072\1074\1083\1077\1085\1080\1077",["TOC-Heading"],[]) [Str "\1054\1075\1083\1072\1074\1083\1077\1085\1080\1077"]
+,Para [Link ("",[],[]) [Str "Short",Space,Str "instructions",Space,Link ("",[],[]) [Str "1"] ("#short-instructions","")] ("#short-instructions","")]
+,Para [Link ("",[],[]) [Str "Some",Space,Str "instructions",Space,Link ("",[],[]) [Str "1"] ("#some-instructions","")] ("#some-instructions","")]
+,Para [Link ("",[],[]) [Str "Remote",Space,Str "folder",Space,Str "or",Space,Str "longlonglonglonglong",Space,Str "file",Space,Str "with",Space,Str "manymanymanymany",Space,Str "letters",Space,Str "inside",Space,Str "opening",Space,Link ("",[],[]) [Str "2"] ("#remote-folder-or-longlonglonglonglong-file-with-manymanymanymany-letters-inside-opening","")] ("#remote-folder-or-longlonglonglonglong-file-with-manymanymanymany-letters-inside-opening","")]
+,Para [Link ("",[],[]) [Str "Remote",Space,Str "folder",Space,Str "or",Space,Str "longlonglonglonglong",Space,Str "file",Space,Str "with",Space,Str "manymanymanymany",Space,Str "letters",Space,Str "inside",Space,Str "closing",Space,Link ("",[],[]) [Str "2"] ("#remote-folder-or-longlonglonglonglong-file-with-manymanymanymany-letters-inside-closing","")] ("#remote-folder-or-longlonglonglonglong-file-with-manymanymanymany-letters-inside-closing","")]
+,Header 1 ("short-instructions",[],[]) [Str "Short",Space,Str "instructions"]
 ,Para [Link ("",[],[]) [Str "Open",Space,Str "remote",Space,Str "folder"] ("#remote-folder-or-longlonglonglonglong-file-with-manymanymanymany-letters-inside-opening","")]
 ,Para [Str "Do",Space,Str "staff"]
 ,Para [Link ("",[],[]) [Str "Close",Space,Str "remote",Space,Str "folder"] ("#remote-folder-or-longlonglonglonglong-file-with-manymanymanymany-letters-inside-closing","")]
diff --git a/test/docx/nested_instrText.docx b/test/docx/nested_instrText.docx
new file mode 100644
Binary files /dev/null and b/test/docx/nested_instrText.docx differ
diff --git a/test/docx/nested_instrText.native b/test/docx/nested_instrText.native
new file mode 100644
--- /dev/null
+++ b/test/docx/nested_instrText.native
@@ -0,0 +1,5 @@
+[Para [Str "\24076\26395\28145\20837\20102\35299\30340\35835\32773\21487\20197\21435\30475David",Space,Str "French",Space,Str "Belding\21644Kevin",Space,Str "J.",Space,Str "Mitchell\30340"
+    ,Link ("",[],[]) [Str "Foundations",Space,Str "of",Space,Str "Analysis,",Space,Str "1/16/18",Space,Str "8:40:00",Space,Str "AM,",Space,Str "2nd",Space,Str "Edition"] ("https://books.google.com/books?id=sp_Zcb9ot90C&lpg=PR4&hl=zh-CN&pg=PA19#v=onepage&q&f=true","")
+    ,Str ",\21487\20174\&19\39029\30475\36215\65292\25110D.C.",Space,Str "Goldrei\30340",Space
+    ,Link ("",[],[]) [Str "Classic",Space,Str "Set",Space,Str "Theory:",Space,Str "For",Space,Str "Guided",Space,Str "Independent",Space,Str "Study"] ("https://books.google.ae/books?id=dlc0DwAAQBAJ&lpg=PT29&hl=zh-CN&pg=PT26#v=onepage&q&f=true","")
+    ,Str "\65292\20174\31532\20108\31456\30475\36215\65292\38405\35835\26102\35201\27880\24847\26412\25991\19982\36825\20123\20070\25152\19981\21516\30340\26159\24182\27809\26377\25226\23454\25968\30475\20316\26159\26377\29702\25968\38598\30340\20998\21106\12290"]]
diff --git a/test/docx/nested_sdt.docx b/test/docx/nested_sdt.docx
new file mode 100644
Binary files /dev/null and b/test/docx/nested_sdt.docx differ
diff --git a/test/docx/nested_sdt.native b/test/docx/nested_sdt.native
new file mode 100644
--- /dev/null
+++ b/test/docx/nested_sdt.native
@@ -0,0 +1,3 @@
+[Para [Str "Test",Space,Str "Paragraph1"]
+,Para [Str "Test",Space,Str "Paragraph2"]
+,Para [Str "Test",Space,Str "Paragraph3"]]
diff --git a/test/docx/nested_smart_tags.docx b/test/docx/nested_smart_tags.docx
new file mode 100644
Binary files /dev/null and b/test/docx/nested_smart_tags.docx differ
diff --git a/test/docx/nested_smart_tags.native b/test/docx/nested_smart_tags.native
new file mode 100644
--- /dev/null
+++ b/test/docx/nested_smart_tags.native
@@ -0,0 +1,7 @@
+[Header 2 ("and-it-came-to-pass-in-the-course-of-those-many-days",["Myheading2"],[]) [Str "159.",Space,Str "And",Space,Str "It",Space,Str "Came",Space,Str "to",Space,Str "Pass",Space,Str "in",Space,Str "the",Space,Str "Course",Space,Str "of",Space,Str "Those",Space,Str "Many",Space,Str "Days"]
+,Para [Str "I",Space,Str "heard"]
+,Para [Str "\8220And",Space,Str "it",Space,Str "came",Space,Str "to",Space,Str "pass",Space,Str "in",Space,Str "the",Space,Str "course",Space,Str "of",Space,Str "those",Space,Str "many",Space,Str "days",Space,Str "that",Space,Str "the",Space,Str "king",Space,Str "of",Space,Str "Egypt",Space,Str "died;",Space,Str "and",Space,Str "the",Space,Str "children",Space,Str "of",Space,Str "Israel",Space,Str "sighed",Space,Str "by",Space,Str "reason",Space,Str "of",Space,Str "the",Space,Str "bondage,",Space,Str "and",Space,Str "they",Space,Str "cried,",Space,Str "and",Space,Str "their",Space,Str "cry",Space,Str "came",Space,Str "up",Space,Str "unto",Space,Str "God",Space,Str "by",Space,Str "reason",Space,Str "of",Space,Str "the",Space,Str "bondage.",Space,Str "And",Space,Str "God",Space,Str "heard",Space,Str "their",Space,Str "groaning\8221",Space,Str "(Exodus",Space,Str "2:23-4).",Space,Str "This",Space,Str "means",Space,Str "that",Space,Str "they",Space,Str "suffered",Space,Str "so",Space,Str "much",Space,Str "that",Space,Str "they",Space,Str "could",Space,Str "not",Space,Str "bear",Space,Str "it",Space,Str "any",Space,Str "longer.",Space,Str "And",Space,Str "they",Space,Str "so",Space,Str "pleaded",Space,Str "with",Space,Str "prayer,",Space,Str "that",Space,Str "\8220their",Space,Str "cry",Space,Str "came",Space,Str "up",Space,Str "unto",Space,Str "God.\8221"]
+,Para [Str "But",Space,Str "we",Space,Str "can",Space,Str "see",Space,Str "that",Space,Str "they",Space,Str "were",Space,Str "saying,",Space,Str "\8220Would",Space,Str "that",Space,Str "we",Space,Str "had\8230",Space,Str "when",Space,Str "we",Space,Str "sat",Space,Str "by",Space,Str "the",Space,Str "flesh-pots,",Space,Str "when",Space,Str "we",Space,Str "did",Space,Str "eat",Space,Str "bread",Space,Str "to",Space,Str "the",Space,Str "full.\8221",Space,Str "And",Space,Str "they",Space,Str "also",Space,Str "said,",Space,Str "\8220We",Space,Str "remember",Space,Str "the",Space,Str "fish,",Space,Str "which",Space,Str "we",Space,Str "would",Space,Str "eat",Space,Str "in",Space,Str "Egypt",Space,Str "for",Space,Str "naught;",Space,Str "the",Space,Str "cucumbers,",Space,Str "and",Space,Str "the",Space,Str "melons,",Space,Str "and",Space,Str "the",Space,Str "leeks,",Space,Str "and",Space,Str "the",Space,Str "onions,",Space,Str "and",Space,Str "the",Space,Str "garlic.\8221"]
+,Para [Str "The",Space,Str "thing",Space,Str "is",Space,Str "that,",Space,Str "indeed,",Space,Str "they",Space,Str "were",Space,Str "very",Space,Str "fond",Space,Str "of",Space,Str "the",Space,Str "work",Space,Str "in",Space,Str "Egypt.",Space,Str "This",Space,Str "is",Space,Str "the",Space,Str "meaning",Space,Str "of",Space,Str "\8220But",Space,Str "mingled",Space,Str "themselves",Space,Str "with",Space,Str "the",Space,Str "nations,",Space,Str "and",Space,Str "learned",Space,Str "their",Space,Str "works.\8221",Space,Str "It",Space,Str "means",Space,Str "that",Space,Str "if",Space,Str "Israel",Space,Str "are",Space,Str "under",Space,Str "the",Space,Str "dominion",Space,Str "of",Space,Str "a",Space,Str "certain",Space,Str "nation,",Space,Str "that",Space,Str "nation",Space,Str "controls",Space,Str "them",Space,Str "and",Space,Str "they",Space,Str "cannot",Space,Str "retire",Space,Str "from",Space,Str "their",Space,Str "dominion.",Space,Str "Thus,",Space,Str "they",Space,Str "tasted",Space,Str "sufficient",Space,Str "flavor",Space,Str "in",Space,Str "that",Space,Str "work",Space,Str "and",Space,Str "could",Space,Str "not",Space,Str "be",Space,Str "redeemed."]
+,Para [Str "So",Space,Str "what",Space,Str "did",Space,Str "the",Space,Str "Creator",Space,Str "do?",Space,Str "\8220The",Space,Str "king",Space,Str "of",Space,Str "Egypt",Space,Str "died,\8221",Space,Str "meaning",Space,Str "they",Space,Str "had",Space,Str "lost",Space,Str "this",Space,Str "servitude.",Space,Str "Thus",Space,Str "they",Space,Str "could",Space,Str "no",Space,Str "longer",Space,Str "work;",Space,Str "they",Space,Str "understood",Space,Str "that",Space,Str "if",Space,Str "there",Space,Str "is",Space,Str "no",Space,Str "perfection",Space,Str "of",Space,Str "the",Space,Emph [Str "Mochin"],Str ",",Space,Str "the",Space,Str "servitude",Space,Str "is",Space,Str "also",Space,Str "incomplete.",Space,Str "Hence,",Space,Str "\8220and",Space,Str "the",Space,Str "children",Space,Str "of",Space,Str "Israel",Space,Str "sighed",Space,Str "by",Space,Str "reason",Space,Str "of",Space,Str "the",Space,Str "bondage.\8221",Space,Str "The",Space,Str "work",Space,Str "means",Space,Str "that",Space,Str "they",Space,Str "did",Space,Str "not",Space,Str "suffice",Space,Str "for",Space,Str "the",Space,Str "work,",Space,Str "that",Space,Str "they",Space,Str "had",Space,Str "no",Space,Str "liveliness",Space,Str "in",Space,Str "the",Space,Str "servitude."]
+,Para [Str "This",Space,Str "is",Space,Str "the",Space,Str "meaning",Space,Str "of",Space,Str "\8220the",Space,Str "king",Space,Str "of",Space,Str "Egypt",Space,Str "died,\8221",Space,Str "that",Space,Str "all",Space,Str "the",Space,Str "dominations",Space,Str "of",Space,Str "the",Space,Str "king",Space,Str "of",Space,Str "Egypt,",Space,Str "which",Space,Str "he",Space,Str "was",Space,Str "providing",Space,Str "for",Space,Str "and",Space,Str "nourishing,",Space,Str "had",Space,Str "died.",Space,Str "This",Space,Str "is",Space,Str "why",Space,Str "they",Space,Str "had",Space,Str "room",Space,Str "for",Space,Str "prayer.",Space,Str "And",Space,Str "they",Space,Str "were",Space,Str "immediately",Space,Str "salvaged.",Space,Str "And",Space,Str "afterwards,",Space,Str "when",Space,Str "they",Space,Str "walked",Space,Str "in",Space,Str "the",Space,Str "desert",Space,Str "and",Space,Str "came",Space,Str "to",Space,Str "a",Space,Str "state",Space,Str "of",Space,Emph [Str "Katnut"],Space,Str "(smallness),",Space,Str "they",Space,Str "craved",Space,Str "the",Space,Str "servitude",Space,Str "that",Space,Str "they",Space,Str "had",Space,Str "had",Space,Str "prior",Space,Str "to",Space,Str "the",Space,Str "death",Space,Str "of",Space,Str "the",Space,Str "king",Space,Str "of",Space,Str "Egypt."]]
diff --git a/test/docx/normalize.docx b/test/docx/normalize.docx
Binary files a/test/docx/normalize.docx and b/test/docx/normalize.docx differ
diff --git a/test/docx/notes.docx b/test/docx/notes.docx
Binary files a/test/docx/notes.docx and b/test/docx/notes.docx differ
diff --git a/test/docx/numbered_header.docx b/test/docx/numbered_header.docx
Binary files a/test/docx/numbered_header.docx and b/test/docx/numbered_header.docx differ
diff --git a/test/docx/overlapping_targets.docx b/test/docx/overlapping_targets.docx
new file mode 100644
Binary files /dev/null and b/test/docx/overlapping_targets.docx differ
diff --git a/test/docx/overlapping_targets.native b/test/docx/overlapping_targets.native
new file mode 100644
--- /dev/null
+++ b/test/docx/overlapping_targets.native
@@ -0,0 +1,3 @@
+[Para [Link ("",[],[]) [Str "One",Space,Str "link",Space,Str "to",Space,Str "one",Space,Str "target."] ("#Fizz","")]
+,Para [Span ("Fizz",["anchor"],[]) [],Str "This",Space,Str "is",Space,Str "a",Space,Str "target",Space,Str "with",Space,Str "two",Space,Str "names."]
+,Para [Link ("",[],[]) [Str "Another",Space,Str "link",Space,Str "to",Space,Str "the",Space,Str "same",Space,Str "target."] ("#Fizz","")]]
diff --git a/test/docx/pageref.docx b/test/docx/pageref.docx
new file mode 100644
Binary files /dev/null and b/test/docx/pageref.docx differ
diff --git a/test/docx/pageref.native b/test/docx/pageref.native
new file mode 100644
--- /dev/null
+++ b/test/docx/pageref.native
@@ -0,0 +1,4 @@
+[Para [Str "Title",Space,Link ("",[],[]) [Str "2"] ("#title","")]
+,Para [Str "Title2",Space,Link ("",[],[]) [Str "2"] ("#title2","")]
+,Header 1 ("title", [],[]) [Str "Title"]
+,Header 1 ("title2",[],[]) [Str "Title2"]]
diff --git a/test/docx/paragraph_insertion_deletion.docx b/test/docx/paragraph_insertion_deletion.docx
new file mode 100644
Binary files /dev/null and b/test/docx/paragraph_insertion_deletion.docx differ
diff --git a/test/docx/paragraph_insertion_deletion_accept.native b/test/docx/paragraph_insertion_deletion_accept.native
new file mode 100644
--- /dev/null
+++ b/test/docx/paragraph_insertion_deletion_accept.native
@@ -0,0 +1,2 @@
+[Para [Str "This",Space,Str "is",Space,Str "a"]
+,Para [Str "split",Space,Str "Paragraph."]]
diff --git a/test/docx/paragraph_insertion_deletion_all.native b/test/docx/paragraph_insertion_deletion_all.native
new file mode 100644
--- /dev/null
+++ b/test/docx/paragraph_insertion_deletion_all.native
@@ -0,0 +1,3 @@
+[Para [Str "This",Space,Str "is",Space,Str "a",Span ("",["paragraph-insertion"],[("author","Seeley, Jason"),("date","2017-09-17T16:39:00Z")]) []]
+,Para [Str "split",Span ("",["paragraph-deletion"],[("author","Seeley, Jason"),("date","2017-09-17T16:39:00Z")]) []]
+,Para [Str "Paragraph."]]
diff --git a/test/docx/paragraph_insertion_deletion_reject.native b/test/docx/paragraph_insertion_deletion_reject.native
new file mode 100644
--- /dev/null
+++ b/test/docx/paragraph_insertion_deletion_reject.native
@@ -0,0 +1,2 @@
+[Para [Str "This",Space,Str "is",Space,Str "a",Space,Str "split"]
+,Para [Str "Paragraph."]]
diff --git a/test/docx/raw-blocks.native b/test/docx/raw-blocks.native
new file mode 100644
--- /dev/null
+++ b/test/docx/raw-blocks.native
@@ -0,0 +1,6 @@
+[Para [Str "Cell",Space,Str "compartments"]
+,RawBlock (Format "openxml") "<w:tbl>\n<w:tblPr>\n<w:tblW w:w=\"2000\" w:type=\"pct\"/>\n<w:tblBorders>\n<w:top w:val=\"single\" w:sz=\"4\" w:color=\"198200\"/>\n<w:start w:val=\"single\" w:sz=\"4\" w:color=\"198200\"/>\n<w:bottom w:val=\"single\" w:sz=\"4\" w:color=\"198200\"/>\n<w:end w:val=\"single\" w:sz=\"4\" w:color=\"198200\"/>\n</w:tblBorders>\n</w:tblPr>\n<w:tblGrid>\n<w:gridCol w:w=\"1871\" />\n<w:gridCol w:w=\"1872\" />\n</w:tblGrid>\n<w:tr>\n<w:tc>"
+,Para [Str "Ribosome"]
+,RawBlock (Format "openxml") "</w:tc>\n<w:tc>"
+,Para [Str "Lysosome"]
+,RawBlock (Format "openxml") "</w:tc>\n</w:tr>\n</w:tbl>"]
diff --git a/test/docx/raw-bookmarks.native b/test/docx/raw-bookmarks.native
new file mode 100644
--- /dev/null
+++ b/test/docx/raw-bookmarks.native
@@ -0,0 +1,3 @@
+[Para [Str "Manual",Space,Str "endnotes."]
+,Para [Str "Nullam",Space,Str "eu",Space,Str "ante",Space,Str "vel",Space,Str "est",Space,Str "convallis",Space,Str "dignissim.",Space,Str "Nunc",Space,Str "porta",Space,Str "vulputate",Space,Str "tellus.",Space,Str "Nunc",Space,Str "rutrum",Space,Str "turpis",Space,Str "sed",Space,Str "pede.",Space,Str "Sed",Space,Str "bibendum.",RawInline (Format "openxml") "<w:bookmarkStart w:id=\"0\" w:name=\"Aliquam\"/>",Str "Aliquam",Space,Str "posuere."]
+,Para [Str "Nunc",Space,Str "aliquet,",Space,Str "augue",Space,Str "nec",Space,Str "adipiscing",Space,Str "interdum,",Space,Str "lacus",Space,Str "tellus",Space,Str "malesuada",Space,Str "massa,",Space,Str "quis",Space,Str "varius",Space,Str "mi",Space,Str "purus",Space,Str "non",Space,Str "odio.",RawInline (Format "openxml") "<w:bookmarkEnd w:id=\"0\"/>",Str "Pellentesque",Space,Str "condimentum,",Space,Str "magna",Space,Str "ut",Space,Str "suscipit",Space,Str "hendrerit,",Space,Str "ipsum",Space,Str "augue",Space,Str "ornare",Space,Str "nulla,",Space,Str "non",Space,Str "luctus",Space,Str "diam",Space,Str "neque",Space,Str "sit",Space,Str "amet",Space,Str "urna.",Space,Str "Curabitur",Space,Str "vulputate",Space,Str "vestibulum",Space,Str "lorem."]]
diff --git a/test/docx/relative_indentation_blockquotes.docx b/test/docx/relative_indentation_blockquotes.docx
new file mode 100644
Binary files /dev/null and b/test/docx/relative_indentation_blockquotes.docx differ
diff --git a/test/docx/relative_indentation_blockquotes.native b/test/docx/relative_indentation_blockquotes.native
new file mode 100644
--- /dev/null
+++ b/test/docx/relative_indentation_blockquotes.native
@@ -0,0 +1,6 @@
+[Header 1 ("indentation-blockquotes",[],[]) [Str "Indentation",Space,Str "blockquotes"]
+,Para [Str "Foobar"]
+,Para [Str "First",Space,Str "line",Space,Str "indented."]
+,Para [Str "Normal",Space,Str "list",Space,Str "paragraph"]
+,Para [Str "List",Space,Str "paragraph",Space,Str "with",Space,Str "less",Space,Str "indent"]
+,BlockQuote [Para [Str "List",Space,Str "paragraph",Space,Str "with",Space,Str "more",Space,Str "indent"]]]
diff --git a/test/docx/sdt_elements.native b/test/docx/sdt_elements.native
--- a/test/docx/sdt_elements.native
+++ b/test/docx/sdt_elements.native
@@ -1,10 +1,60 @@
-[Table [] [AlignDefault,AlignDefault,AlignDefault] [0.0,0.0,0.0]
- [[]
- ,[]
- ,[]]
- [[[Plain [Strong [Str "col1Header"]]]
-  ,[Plain [Strong [Str "col2Header"]]]
-  ,[Plain [Strong [Str "col3Header"]]]]
- ,[[Plain [Str "col1",Space,Str "content"]]
-  ,[Plain [Str "Body",Space,Str "copy"]]
-  ,[Plain [Str "col3",Space,Str "content"]]]]]
+[ Table
+    ( "" , [] , [] )
+    (Caption Nothing [])
+    [ ( AlignDefault , ColWidth 0.16167023554603854 )
+    , ( AlignDefault , ColWidth 0.16167023554603854 )
+    , ( AlignDefault , ColWidth 0.40920770877944324 )
+    ]
+    (TableHead
+       ( "" , [] , [] )
+       [ Row
+           ( "" , [] , [] )
+           [ Cell
+               ( "" , [] , [] )
+               AlignCenter
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Strong [ Str "col1Header" ] ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignCenter
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Strong [ Str "col2Header" ] ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignCenter
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Strong [ Str "col3Header" ] ] ]
+           ]
+       ])
+    [ TableBody
+        ( "" , [] , [] )
+        (RowHeadColumns 0)
+        []
+        [ Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "col1" , Space , Str "content" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "Body" , Space , Str "copy" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "col3" , Space , Str "content" ] ]
+            ]
+        ]
+    ]
+    (TableFoot ( "" , [] , [] ) [])
+]
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/table_captions_no_field.docx b/test/docx/table_captions_no_field.docx
new file mode 100644
Binary files /dev/null and b/test/docx/table_captions_no_field.docx differ
diff --git a/test/docx/table_captions_no_field.native b/test/docx/table_captions_no_field.native
new file mode 100644
--- /dev/null
+++ b/test/docx/table_captions_no_field.native
@@ -0,0 +1,81 @@
+[ Para
+    [ Str "See" , Space , Str "Table" , Space , Str "5.1." ]
+, Table
+    ( "" , [] , [] )
+    (Caption
+       Nothing [ Para [ Str "Table" , Space , Str "5.1" ] ])
+    [ ( AlignDefault , ColWidth 0.7605739372523824 )
+    , ( AlignDefault , ColWidth 0.11971303137380876 )
+    , ( AlignDefault , ColWidth 0.11971303137380876 )
+    ]
+    (TableHead
+       ( "" , [] , [] )
+       [ Row
+           ( "" , [] , [] )
+           [ Cell
+               ( "" , [] , [] ) AlignDefault (RowSpan 1) (ColSpan 1) []
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "Count" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "%" ] ]
+           ]
+       ])
+    [ TableBody
+        ( "" , [] , [] )
+        (RowHeadColumns 0)
+        []
+        [ Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "First" , Space , Str "option" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "242" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "45" ] ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "Second" , Space , Str "option" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "99" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "18" ] ]
+            ]
+        ]
+    ]
+    (TableFoot ( "" , [] , [] ) [])
+, Header 2 ( "section" , [] , [] ) []
+]
diff --git a/test/docx/table_captions_with_field.docx b/test/docx/table_captions_with_field.docx
new file mode 100644
Binary files /dev/null and b/test/docx/table_captions_with_field.docx differ
diff --git a/test/docx/table_captions_with_field.native b/test/docx/table_captions_with_field.native
new file mode 100644
--- /dev/null
+++ b/test/docx/table_captions_with_field.native
@@ -0,0 +1,145 @@
+[ Para
+    [ Str "See"
+    , Space
+    , Link
+        ( "" , [] , [] )
+        [ Str "Table" , Space , Str "1" ]
+        ( "#_Ref71265628" , "" )
+    , Str "."
+    ]
+, Table
+    ( "" , [] , [] )
+    (Caption
+       Nothing
+       [ Para
+           [ Span ( "_Ref71265628" , [ "anchor" ] , [] ) []
+           , Str "Table"
+           , Space
+           , Str "1"
+           ]
+       ])
+    [ ( AlignDefault , ColWidth 0.7605739372523824 )
+    , ( AlignDefault , ColWidth 0.11971303137380876 )
+    , ( AlignDefault , ColWidth 0.11971303137380876 )
+    ]
+    (TableHead
+       ( "" , [] , [] )
+       [ Row
+           ( "" , [] , [] )
+           [ Cell
+               ( "" , [] , [] ) AlignDefault (RowSpan 1) (ColSpan 1) []
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "Count" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "%" ] ]
+           ]
+       ])
+    [ TableBody
+        ( "" , [] , [] )
+        (RowHeadColumns 0)
+        []
+        [ Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "First" , Space , Str "option" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "242" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "45" ] ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "Second" , Space , Str "option" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "99" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "18" ] ]
+            ]
+        ]
+    ]
+    (TableFoot ( "" , [] , [] ) [])
+, Header 2 ( "section" , [] , [] ) []
+, Table
+    ( "" , [] , [] )
+    (Caption
+       Nothing
+       [ Para
+           [ Span ( "_Ref71265695" , [ "anchor" ] , [] ) []
+           , Str "Table"
+           , Space
+           , Str "2"
+           ]
+       ])
+    [ ( AlignDefault , ColWidth 0.33329636202307006 )
+    , ( AlignDefault , ColWidth 0.33329636202307006 )
+    , ( AlignDefault , ColWidth 0.33340727595385977 )
+    ]
+    (TableHead
+       ( "" , [] , [] )
+       [ Row
+           ( "" , [] , [] )
+           [ Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "One" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "Two" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "Three" ] ]
+           ]
+       ])
+    [ TableBody ( "" , [] , [] ) (RowHeadColumns 0) [] [] ]
+    (TableFoot ( "" , [] , [] ) [])
+, Para
+    [ Str "See"
+    , Space
+    , Link
+        ( "" , [] , [] )
+        [ Str "Table" , Space , Str "2" ]
+        ( "#_Ref71265695" , "" )
+    , Str "."
+    ]
+]
diff --git a/test/docx/table_gridbefore.docx b/test/docx/table_gridbefore.docx
new file mode 100644
Binary files /dev/null and b/test/docx/table_gridbefore.docx differ
diff --git a/test/docx/table_gridbefore.native b/test/docx/table_gridbefore.native
new file mode 100644
--- /dev/null
+++ b/test/docx/table_gridbefore.native
@@ -0,0 +1,823 @@
+[ Table
+    ( "" , [] , [] )
+    (Caption Nothing [])
+    [ ( AlignDefault , ColWidth 7.883369330453563e-3 )
+    , ( AlignDefault , ColWidth 3.0669546436285097e-2 )
+    , ( AlignDefault , ColWidth 3.0669546436285097e-2 )
+    , ( AlignDefault , ColWidth 3.0669546436285097e-2 )
+    , ( AlignDefault , ColWidth 3.0669546436285097e-2 )
+    , ( AlignDefault , ColWidth 3.0669546436285097e-2 )
+    , ( AlignDefault , ColWidth 3.0669546436285097e-2 )
+    , ( AlignDefault , ColWidth 3.0669546436285097e-2 )
+    , ( AlignDefault , ColWidth 3.0669546436285097e-2 )
+    , ( AlignDefault , ColWidth 3.0669546436285097e-2 )
+    , ( AlignDefault , ColWidth 0.42861771058315334 )
+    ]
+    (TableHead
+       ( "" , [] , [] )
+       [ Row
+           ( "" , [] , [] )
+           [ Cell
+               ( "" , [] , [] ) AlignDefault (RowSpan 1) (ColSpan 1) []
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 8)
+               [ Plain [ Str "Bits" ] ]
+           , Cell
+               ( "" , [] , [] ) AlignDefault (RowSpan 1) (ColSpan 1) []
+           , Cell
+               ( "" , [] , [] ) AlignDefault (RowSpan 1) (ColSpan 1) []
+           ]
+       ])
+    [ TableBody
+        ( "" , [] , [] )
+        (RowHeadColumns 0)
+        []
+        [ Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] ) AlignDefault (RowSpan 1) (ColSpan 1) []
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "8" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "7" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "6" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "5" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "4" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "3" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "2" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "1" ] ]
+            , Cell
+                ( "" , [] , [] ) AlignDefault (RowSpan 1) (ColSpan 1) []
+            , Cell
+                ( "" , [] , [] ) AlignDefault (RowSpan 1) (ColSpan 1) []
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] ) AlignDefault (RowSpan 1) (ColSpan 1) []
+            , Cell
+                ( "" , [] , [] ) AlignDefault (RowSpan 1) (ColSpan 1) []
+            , Cell
+                ( "" , [] , [] ) AlignDefault (RowSpan 1) (ColSpan 1) []
+            , Cell
+                ( "" , [] , [] ) AlignDefault (RowSpan 1) (ColSpan 1) []
+            , Cell
+                ( "" , [] , [] ) AlignDefault (RowSpan 1) (ColSpan 1) []
+            , Cell
+                ( "" , [] , [] ) AlignDefault (RowSpan 1) (ColSpan 1) []
+            , Cell
+                ( "" , [] , [] ) AlignDefault (RowSpan 1) (ColSpan 1) []
+            , Cell
+                ( "" , [] , [] ) AlignDefault (RowSpan 1) (ColSpan 1) []
+            , Cell
+                ( "" , [] , [] ) AlignDefault (RowSpan 1) (ColSpan 1) []
+            , Cell
+                ( "" , [] , [] ) AlignDefault (RowSpan 1) (ColSpan 1) []
+            , Cell
+                ( "" , [] , [] ) AlignDefault (RowSpan 1) (ColSpan 1) []
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] ) AlignDefault (RowSpan 1) (ColSpan 1) []
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "0" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "0" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "0" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "0" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "0" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "0" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "0" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "1" ] ]
+            , Cell
+                ( "" , [] , [] ) AlignDefault (RowSpan 1) (ColSpan 1) []
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "TEXT" ] ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] ) AlignDefault (RowSpan 1) (ColSpan 1) []
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "0" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "0" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "0" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "0" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "0" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "0" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "1" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "0" ] ]
+            , Cell
+                ( "" , [] , [] ) AlignDefault (RowSpan 1) (ColSpan 1) []
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "BINARY" ] ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] ) AlignDefault (RowSpan 1) (ColSpan 1) []
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "0" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "0" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "0" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "0" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "0" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "0" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "1" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "1" ] ]
+            , Cell
+                ( "" , [] , [] ) AlignDefault (RowSpan 1) (ColSpan 1) []
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "HYPERLINKS" ] ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] ) AlignDefault (RowSpan 1) (ColSpan 1) []
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "0" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "0" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "0" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "0" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "0" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "1" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "0" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "0" ] ]
+            , Cell
+                ( "" , [] , [] ) AlignDefault (RowSpan 1) (ColSpan 1) []
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "FILEURL" ] ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] ) AlignDefault (RowSpan 1) (ColSpan 1) []
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "0" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "0" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "0" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "0" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "0" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "1" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "0" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "1" ] ]
+            , Cell
+                ( "" , [] , [] ) AlignDefault (RowSpan 1) (ColSpan 1) []
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "LOCATION" ] ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] ) AlignDefault (RowSpan 1) (ColSpan 1) []
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "0" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "0" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "0" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "0" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "0" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "1" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "1" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "0" ] ]
+            , Cell
+                ( "" , [] , [] ) AlignDefault (RowSpan 1) (ColSpan 1) []
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "ENHANCED" , Space , Str "STATUS" ] ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] ) AlignDefault (RowSpan 1) (ColSpan 1) []
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "0" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "0" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "0" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "0" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "0" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "1" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "1" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "1" ] ]
+            , Cell
+                ( "" , [] , [] ) AlignDefault (RowSpan 1) (ColSpan 1) []
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain
+                    [ Str "Value"
+                    , Space
+                    , Str "allocated"
+                    , Space
+                    , Str "for"
+                    , Space
+                    , Str "use"
+                    , Space
+                    , Str "in"
+                    , Space
+                    , Str "interworking"
+                    , Space
+                    , Str "(NOTE)"
+                    ]
+                ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] ) AlignDefault (RowSpan 1) (ColSpan 1) []
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "0" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "0" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "0" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "0" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "1" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "0" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "0" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "0" ] ]
+            , Cell
+                ( "" , [] , [] ) AlignDefault (RowSpan 1) (ColSpan 1) []
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "LOCATION" , Space , Str "ALTITUDE" ] ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] ) AlignDefault (RowSpan 1) (ColSpan 1) []
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "0" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "0" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "0" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "0" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "1" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "0" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "0" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "1" ] ]
+            , Cell
+                ( "" , [] , [] ) AlignDefault (RowSpan 1) (ColSpan 1) []
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "LOCATION" , Space , Str "TIMESTAMP" ] ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 2)
+                [ Plain [ Str "0" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "0" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "0" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "0" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "1" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "0" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "1" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "0" ] ]
+            , Cell
+                ( "" , [] , [] ) AlignDefault (RowSpan 1) (ColSpan 1) []
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "CODED" , Space , Str "TEXT" ] ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] ) AlignDefault (RowSpan 1) (ColSpan 1) []
+            , Cell
+                ( "" , [] , [] ) AlignDefault (RowSpan 1) (ColSpan 1) []
+            , Cell
+                ( "" , [] , [] ) AlignDefault (RowSpan 1) (ColSpan 1) []
+            , Cell
+                ( "" , [] , [] ) AlignDefault (RowSpan 1) (ColSpan 1) []
+            , Cell
+                ( "" , [] , [] ) AlignDefault (RowSpan 1) (ColSpan 1) []
+            , Cell
+                ( "" , [] , [] ) AlignDefault (RowSpan 1) (ColSpan 1) []
+            , Cell
+                ( "" , [] , [] ) AlignDefault (RowSpan 1) (ColSpan 1) []
+            , Cell
+                ( "" , [] , [] ) AlignDefault (RowSpan 1) (ColSpan 1) []
+            , Cell
+                ( "" , [] , [] ) AlignDefault (RowSpan 1) (ColSpan 1) []
+            , Cell
+                ( "" , [] , [] ) AlignDefault (RowSpan 1) (ColSpan 1) []
+            , Cell
+                ( "" , [] , [] ) AlignDefault (RowSpan 1) (ColSpan 1) []
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] ) AlignDefault (RowSpan 1) (ColSpan 1) []
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 10)
+                [ Plain
+                    [ Str "All"
+                    , Space
+                    , Str "other"
+                    , Space
+                    , Str "values"
+                    , Space
+                    , Str "are"
+                    , Space
+                    , Str "reserved."
+                    ]
+                ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] ) AlignDefault (RowSpan 1) (ColSpan 1) []
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 10)
+                [ Plain
+                    [ Str "NOTE:"
+                    , Space
+                    , Str "Usage"
+                    , Space
+                    , Str "of"
+                    , Space
+                    , Str "this"
+                    , Space
+                    , Str "value"
+                    , Space
+                    , Str "is"
+                    , Space
+                    , Str "described"
+                    , Space
+                    , Str "in"
+                    , Space
+                    , Str "3GPP\160TS\160\&29.582\160[48]."
+                    ]
+                ]
+            ]
+        ]
+    ]
+    (TableFoot ( "" , [] , [] ) [])
+]
diff --git a/test/docx/table_header_rowspan.docx b/test/docx/table_header_rowspan.docx
new file mode 100644
Binary files /dev/null and b/test/docx/table_header_rowspan.docx differ
diff --git a/test/docx/table_header_rowspan.native b/test/docx/table_header_rowspan.native
new file mode 100644
--- /dev/null
+++ b/test/docx/table_header_rowspan.native
@@ -0,0 +1,542 @@
+[ Table
+    ( "" , [] , [] )
+    (Caption Nothing [])
+    [ ( AlignLeft , ColWidth 0.30701754385964913 )
+    , ( AlignDefault , ColWidth 0.13645224171539963 )
+    , ( AlignDefault , ColWidth 0.10009746588693959 )
+    , ( AlignDefault , ColWidth 9.707602339181289e-2 )
+    , ( AlignDefault , ColWidth 7.719298245614035e-2 )
+    , ( AlignDefault , ColWidth 7.085769980506823e-2 )
+    , ( AlignDefault , ColWidth 7.09551656920078e-2 )
+    , ( AlignDefault , ColWidth 0.14035087719298248 )
+    ]
+    (TableHead
+       ( "" , [] , [] )
+       [ Row
+           ( "" , [] , [] )
+           [ Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 2)
+               (ColSpan 1)
+               [ Plain [ Str "A" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 2)
+               (ColSpan 1)
+               [ Plain [ Strong [ Str "B" ] ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 2)
+               (ColSpan 1)
+               [ Plain [ Strong [ Str "C" ] ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 2)
+               (ColSpan 1)
+               [ Plain [ Strong [ Str "D" ] ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 3)
+               [ Plain [ Str "E" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 2)
+               (ColSpan 1)
+               [ Plain [ Str "F" ] ]
+           ]
+       , Row
+           ( "" , [] , [] )
+           [ Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Strong [ Str "G" ] ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Strong [ Str "H" ] ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Strong [ Str "I" ] ] ]
+           ]
+       ])
+    [ TableBody
+        ( "" , [] , [] )
+        (RowHeadColumns 0)
+        []
+        [ Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignLeft
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "1" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "2" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "3" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "4" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "5" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "6" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "7" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "8" ] ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignLeft
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "1" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "2" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "3" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "4" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "5" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "6" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "7" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "8" ] ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignLeft
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "1" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "2" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "3" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "4" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "5" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "6" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "7" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "8" ] ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignLeft
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "1" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "2" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "3" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "4" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "5" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "6" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "7" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "8" ] ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignLeft
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "1" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "2" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "3" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "4" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "5" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "6" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "7" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "8" ] ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignLeft
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "1" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "2" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "3" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "4" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "5" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "6" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "7" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "8" ] ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignLeft
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "1" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "2" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "3" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "4" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "5" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "6" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "7" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "8" ] ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignLeft
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "1" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "2" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "3" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "4" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "5" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "6" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "7" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "8" ] ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignLeft
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "1" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "2" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "3" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "4" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "5" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "6" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "7" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "8" ] ]
+            ]
+        ]
+    ]
+    (TableFoot ( "" , [] , [] ) [])
+]
diff --git a/test/docx/table_one_header_row.docx b/test/docx/table_one_header_row.docx
new file mode 100644
Binary files /dev/null and b/test/docx/table_one_header_row.docx differ
diff --git a/test/docx/table_one_header_row.native b/test/docx/table_one_header_row.native
new file mode 100644
--- /dev/null
+++ b/test/docx/table_one_header_row.native
@@ -0,0 +1,34 @@
+[ Table
+    ( "" , [] , [] )
+    (Caption Nothing [])
+    [ ( AlignDefault , ColWidth 0.3330243337195829 )
+    , ( AlignDefault , ColWidth 0.33325608342989577 )
+    , ( AlignDefault , ColWidth 0.33371958285052145 )
+    ]
+    (TableHead
+       ( "" , [] , [] )
+       [ Row
+           ( "" , [] , [] )
+           [ Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "One" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "Row" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "Table" ] ]
+           ]
+       ])
+    [ TableBody ( "" , [] , [] ) (RowHeadColumns 0) [] [] ]
+    (TableFoot ( "" , [] , [] ) [])
+]
diff --git a/test/docx/table_one_row.docx b/test/docx/table_one_row.docx
Binary files a/test/docx/table_one_row.docx and b/test/docx/table_one_row.docx differ
diff --git a/test/docx/table_one_row.native b/test/docx/table_one_row.native
--- a/test/docx/table_one_row.native
+++ b/test/docx/table_one_row.native
@@ -1,7 +1,37 @@
-[Table [] [AlignDefault,AlignDefault,AlignDefault] [0.0,0.0,0.0]
- [[]
- ,[]
- ,[]]
- [[[Plain [Str "One"]]
-  ,[Plain [Str "Row"]]
-  ,[Plain [Str "Table"]]]]]
+[ Table
+    ( "" , [] , [] )
+    (Caption Nothing [])
+    [ ( AlignDefault , ColWidth 0.33333333333333337 )
+    , ( AlignDefault , ColWidth 0.33333333333333337 )
+    , ( AlignDefault , ColWidth 0.33333333333333337 )
+    ]
+    (TableHead ( "" , [] , [] ) [])
+    [ TableBody
+        ( "" , [] , [] )
+        (RowHeadColumns 0)
+        []
+        [ Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "One" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "Row" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "Table" ] ]
+            ]
+        ]
+    ]
+    (TableFoot ( "" , [] , [] ) [])
+]
diff --git a/test/docx/table_variable_width.docx b/test/docx/table_variable_width.docx
new file mode 100644
Binary files /dev/null and b/test/docx/table_variable_width.docx differ
diff --git a/test/docx/table_variable_width.native b/test/docx/table_variable_width.native
new file mode 100644
--- /dev/null
+++ b/test/docx/table_variable_width.native
@@ -0,0 +1,78 @@
+[ Table
+    ( "" , [] , [] )
+    (Caption Nothing [])
+    [ ( AlignDefault , ColWidth 1.9673503557974047e-2 )
+    , ( AlignDefault , ColWidth 1.946421096693177e-2 )
+    , ( AlignDefault , ColWidth 0.21735035579740478 )
+    , ( AlignDefault , ColWidth 0.4660946002511511 )
+    , ( AlignDefault , ColWidth 1.0464629552113855e-4 )
+    , ( AlignDefault , ColWidth 0.25627877773126834 )
+    ]
+    (TableHead
+       ( "" , [] , [] )
+       [ Row
+           ( "" , [] , [] )
+           [ Cell
+               ( "" , [] , [] ) AlignDefault (RowSpan 1) (ColSpan 1) []
+           , Cell
+               ( "" , [] , [] ) AlignDefault (RowSpan 1) (ColSpan 1) []
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "h3" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 2)
+               [ Plain [ Str "h4" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "h5" ] ]
+           ]
+       ])
+    [ TableBody
+        ( "" , [] , [] )
+        (RowHeadColumns 0)
+        []
+        [ Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 3)
+                [ Plain [ Str "c11" ] ]
+            , Cell
+                ( "" , [] , [] ) AlignDefault (RowSpan 1) (ColSpan 1) []
+            , Cell
+                ( "" , [] , [] ) AlignDefault (RowSpan 1) (ColSpan 2) []
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] ) AlignDefault (RowSpan 1) (ColSpan 1) []
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 2)
+                [ Plain [ Str "c22" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "c23" ] ]
+            , Cell
+                ( "" , [] , [] ) AlignDefault (RowSpan 1) (ColSpan 2) []
+            ]
+        ]
+    ]
+    (TableFoot ( "" , [] , [] ) [])
+]
diff --git a/test/docx/table_with_list_cell.docx b/test/docx/table_with_list_cell.docx
Binary files a/test/docx/table_with_list_cell.docx and b/test/docx/table_with_list_cell.docx differ
diff --git a/test/docx/table_with_list_cell.native b/test/docx/table_with_list_cell.native
--- a/test/docx/table_with_list_cell.native
+++ b/test/docx/table_with_list_cell.native
@@ -1,11 +1,72 @@
-[Table [] [AlignDefault,AlignDefault] [0.0,0.0]
- [[Plain [Str "Cell",Space,Str "with",Space,Str "text"]]
- ,[Plain [Str "Cell",Space,Str "with",Space,Str "text"]]]
- [[[BulletList
-    [[Para [Str "Cell",Space,Str "with"]]
-    ,[Para [Str "A"]]
-    ,[Para [Str "Bullet",Space,Str "list"]]]]
-  ,[OrderedList (1,Decimal,Period)
-    [[Para [Str "Cell",Space,Str "with"]]
-    ,[Para [Str "A"]]
-    ,[Para [Str "Numbered",Space,Str "list."]]]]]]]
+[ Table
+    ( "" , [] , [] )
+    (Caption Nothing [])
+    [ ( AlignDefault , ColWidth 0.5 )
+    , ( AlignDefault , ColWidth 0.5 )
+    ]
+    (TableHead
+       ( "" , [] , [] )
+       [ Row
+           ( "" , [] , [] )
+           [ Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain
+                   [ Str "Cell"
+                   , Space
+                   , Str "with"
+                   , Space
+                   , Str "text"
+                   ]
+               ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain
+                   [ Str "Cell"
+                   , Space
+                   , Str "with"
+                   , Space
+                   , Str "text"
+                   ]
+               ]
+           ]
+       ])
+    [ TableBody
+        ( "" , [] , [] )
+        (RowHeadColumns 0)
+        []
+        [ Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ BulletList
+                    [ [ Para [ Str "Cell" , Space , Str "with" ] ]
+                    , [ Para [ Str "A" ] ]
+                    , [ Para [ Str "Bullet" , Space , Str "list" ] ]
+                    ]
+                ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ OrderedList
+                    ( 1 , Decimal , Period )
+                    [ [ Para [ Str "Cell" , Space , Str "with" ] ]
+                    , [ Para [ Str "A" ] ]
+                    , [ Para [ Str "Numbered" , Space , Str "list." ] ]
+                    ]
+                ]
+            ]
+        ]
+    ]
+    (TableFoot ( "" , [] , [] ) [])
+]
diff --git a/test/docx/tables-default-widths.native b/test/docx/tables-default-widths.native
new file mode 100644
--- /dev/null
+++ b/test/docx/tables-default-widths.native
@@ -0,0 +1,92 @@
+[Header 2 ("a-table-with-and-without-a-header-row",[],[]) [Str "A",Space,Str "table,",Space,Str "with",Space,Str "and",Space,Str "without",Space,Str "a",Space,Str "header",Space,Str "row"]
+,Table ("",[],[]) (Caption Nothing
+ [])
+ [(AlignDefault,ColWidthDefault)
+ ,(AlignDefault,ColWidthDefault)
+ ,(AlignDefault,ColWidthDefault)
+ ,(AlignDefault,ColWidthDefault)]
+ (TableHead ("",[],[])
+ [Row ("",[],[])
+  [Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+   [Plain [Str "Name"]]
+  ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+   [Plain [Str "Game"]]
+  ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+   [Plain [Str "Fame"]]
+  ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+   [Plain [Str "Blame"]]]])
+ [(TableBody ("",[],[]) (RowHeadColumns 0)
+  []
+  [Row ("",[],[])
+   [Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "Lebron",Space,Str "James"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "Basketball"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "Very",Space,Str "High"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "Leaving",Space,Str "Cleveland"]]]
+  ,Row ("",[],[])
+   [Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "Ryan",Space,Str "Braun"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "Baseball"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "Moderate"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "Steroids"]]]
+  ,Row ("",[],[])
+   [Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "Russell",Space,Str "Wilson"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "Football"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "High"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "Tacky",Space,Str "uniform"]]]])]
+ (TableFoot ("",[],[])
+ [])
+,Table ("",[],[]) (Caption Nothing
+ [])
+ [(AlignDefault,ColWidthDefault)
+ ,(AlignDefault,ColWidthDefault)]
+ (TableHead ("",[],[])
+ [])
+ [(TableBody ("",[],[]) (RowHeadColumns 0)
+  []
+  [Row ("",[],[])
+   [Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "Sinple"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "Table"]]]
+  ,Row ("",[],[])
+   [Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "Without"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "Header"]]]])]
+ (TableFoot ("",[],[])
+ [])
+,Table ("",[],[]) (Caption Nothing
+ [])
+ [(AlignDefault,ColWidthDefault)
+ ,(AlignDefault,ColWidthDefault)]
+ (TableHead ("",[],[])
+ [])
+ [(TableBody ("",[],[]) (RowHeadColumns 0)
+  []
+  [Row ("",[],[])
+   [Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Para [Str "Simple"]
+    ,Para [Str "Multiparagraph"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Para [Str "Table"]
+    ,Para [Str "Full"]]]
+  ,Row ("",[],[])
+   [Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Para [Str "Of"]
+    ,Para [Str "Paragraphs"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Para [Str "In",Space,Str "each"]
+    ,Para [Str "Cell."]]]])]
+ (TableFoot ("",[],[])
+ [])]
diff --git a/test/docx/tables.docx b/test/docx/tables.docx
Binary files a/test/docx/tables.docx and b/test/docx/tables.docx differ
diff --git a/test/docx/tables.native b/test/docx/tables.native
--- a/test/docx/tables.native
+++ b/test/docx/tables.native
@@ -1,36 +1,238 @@
-[Header 2 ("a-table-with-and-without-a-header-row",[],[]) [Str "A",Space,Str "table,",Space,Str "with",Space,Str "and",Space,Str "without",Space,Str "a",Space,Str "header",Space,Str "row"]
-,Table [] [AlignDefault,AlignDefault,AlignDefault,AlignDefault] [0.0,0.0,0.0,0.0]
- [[Plain [Str "Name"]]
- ,[Plain [Str "Game"]]
- ,[Plain [Str "Fame"]]
- ,[Plain [Str "Blame"]]]
- [[[Plain [Str "Lebron",Space,Str "James"]]
-  ,[Plain [Str "Basketball"]]
-  ,[Plain [Str "Very",Space,Str "High"]]
-  ,[Plain [Str "Leaving",Space,Str "Cleveland"]]]
- ,[[Plain [Str "Ryan",Space,Str "Braun"]]
-  ,[Plain [Str "Baseball"]]
-  ,[Plain [Str "Moderate"]]
-  ,[Plain [Str "Steroids"]]]
- ,[[Plain [Str "Russell",Space,Str "Wilson"]]
-  ,[Plain [Str "Football"]]
-  ,[Plain [Str "High"]]
-  ,[Plain [Str "Tacky",Space,Str "uniform"]]]]
-,Table [] [AlignDefault,AlignDefault] [0.0,0.0]
- [[]
- ,[]]
- [[[Plain [Str "Sinple"]]
-  ,[Plain [Str "Table"]]]
- ,[[Plain [Str "Without"]]
-  ,[Plain [Str "Header"]]]]
-,Table [] [AlignDefault,AlignDefault] [0.0,0.0]
- [[]
- ,[]]
- [[[Para [Str "Simple"]
-   ,Para [Str "Multiparagraph"]]
-  ,[Para [Str "Table"]
-   ,Para [Str "Full"]]]
- ,[[Para [Str "Of"]
-   ,Para [Str "Paragraphs"]]
-  ,[Para [Str "In",Space,Str "each"]
-   ,Para [Str "Cell."]]]]]
+[ Header
+    2
+    ( "a-table-with-and-without-a-header-row" , [] , [] )
+    [ Str "A"
+    , Space
+    , Str "table,"
+    , Space
+    , Str "with"
+    , Space
+    , Str "and"
+    , Space
+    , Str "without"
+    , Space
+    , Str "a"
+    , Space
+    , Str "header"
+    , Space
+    , Str "row"
+    ]
+, Table
+    ( "" , [] , [] )
+    (Caption Nothing [])
+    [ ( AlignDefault , ColWidth 0.25 )
+    , ( AlignDefault , ColWidth 0.25 )
+    , ( AlignDefault , ColWidth 0.25 )
+    , ( AlignDefault , ColWidth 0.25 )
+    ]
+    (TableHead
+       ( "" , [] , [] )
+       [ Row
+           ( "" , [] , [] )
+           [ Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "Name" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "Game" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "Fame" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "Blame" ] ]
+           ]
+       ])
+    [ TableBody
+        ( "" , [] , [] )
+        (RowHeadColumns 0)
+        []
+        [ Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "Lebron" , Space , Str "James" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "Basketball" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "Very" , Space , Str "High" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "Leaving" , Space , Str "Cleveland" ] ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "Ryan" , Space , Str "Braun" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "Baseball" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "Moderate" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "Steroids" ] ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "Russell" , Space , Str "Wilson" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "Football" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "High" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "Tacky" , Space , Str "uniform" ] ]
+            ]
+        ]
+    ]
+    (TableFoot ( "" , [] , [] ) [])
+, Table
+    ( "" , [] , [] )
+    (Caption Nothing [])
+    [ ( AlignDefault , ColWidth 0.5 )
+    , ( AlignDefault , ColWidth 0.5 )
+    ]
+    (TableHead ( "" , [] , [] ) [])
+    [ TableBody
+        ( "" , [] , [] )
+        (RowHeadColumns 0)
+        []
+        [ Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "Sinple" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "Table" ] ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "Without" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "Header" ] ]
+            ]
+        ]
+    ]
+    (TableFoot ( "" , [] , [] ) [])
+, Table
+    ( "" , [] , [] )
+    (Caption Nothing [])
+    [ ( AlignDefault , ColWidth 0.5 )
+    , ( AlignDefault , ColWidth 0.5 )
+    ]
+    (TableHead ( "" , [] , [] ) [])
+    [ TableBody
+        ( "" , [] , [] )
+        (RowHeadColumns 0)
+        []
+        [ Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Para [ Str "Simple" ]
+                , Para [ Str "Multiparagraph" ]
+                ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Para [ Str "Table" ] , Para [ Str "Full" ] ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Para [ Str "Of" ] , Para [ Str "Paragraphs" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Para [ Str "In" , Space , Str "each" ]
+                , Para [ Str "Cell." ]
+                ]
+            ]
+        ]
+    ]
+    (TableFoot ( "" , [] , [] ) [])
+]
diff --git a/test/docx/tables_separated_with_rawblock.native b/test/docx/tables_separated_with_rawblock.native
new file mode 100644
--- /dev/null
+++ b/test/docx/tables_separated_with_rawblock.native
@@ -0,0 +1,27 @@
+[Table ("", [], []) (Caption Nothing
+ [])
+ [(AlignDefault,ColWidthDefault)
+ ,(AlignDefault,ColWidthDefault)]
+ (TableHead ("",[],[]) [])
+ [TableBody ("",[],[]) (RowHeadColumns 0)
+  []
+  [Row ("",[],[])
+   [Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "a"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "b"]]]]]
+ (TableFoot ("",[],[]) [])
+,RawBlock (Format "latex") ""
+,Table ("",[],[]) (Caption Nothing
+ [])
+ [(AlignDefault,ColWidthDefault)
+ ,(AlignDefault,ColWidthDefault)]
+   (TableHead ("",[],[]) [])
+   [TableBody ("",[],[]) (RowHeadColumns 0)
+    []
+    [Row ("",[],[])
+     [Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+      [Plain [Str "c"]]
+     ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+      [Plain [Str "d"]]]]]
+ (TableFoot ("",[],[]) [])]
diff --git a/test/docx/task_list.docx b/test/docx/task_list.docx
new file mode 100644
Binary files /dev/null and b/test/docx/task_list.docx differ
diff --git a/test/docx/task_list.native b/test/docx/task_list.native
new file mode 100644
--- /dev/null
+++ b/test/docx/task_list.native
@@ -0,0 +1,40 @@
+[ BulletList
+    [ [ Para [ Str "\9744" , Space , Str "Unchecked" ] ]
+    , [ Para [ Str "\9746" , Space , Str "Checked" ]
+      , Para
+          [ Str "with"
+          , Space
+          , Str "continuation"
+          , Space
+          , Str "paragraph"
+          ]
+      ]
+    , [ Para [ Str "\9744" , Space , Str "Unchecked" ]
+      , BulletList
+          [ [ Plain
+                [ Str "\9746"
+                , Space
+                , Str "Checked"
+                , Space
+                , Str "sublist"
+                ]
+            , BulletList
+                [ [ Plain
+                      [ Str "\9744"
+                      , Space
+                      , Str "Unchecked"
+                      , Space
+                      , Str "subsublist"
+                      ]
+                  , OrderedList
+                      ( 1 , Decimal , Period )
+                      [ [ Plain [ Str "Numbered" , Space , Str "child" ]
+                        ]
+                      ]
+                  ]
+                ]
+            ]
+          ]
+      ]
+    ]
+]
diff --git a/test/docx/text_in_shape_format.docx b/test/docx/text_in_shape_format.docx
new file mode 100644
Binary files /dev/null and b/test/docx/text_in_shape_format.docx differ
diff --git a/test/docx/text_in_shape_format.native b/test/docx/text_in_shape_format.native
new file mode 100644
--- /dev/null
+++ b/test/docx/text_in_shape_format.native
@@ -0,0 +1,33 @@
+[ Para
+    [ Str "Last"
+    , Space
+    , Str "update:"
+    , Space
+    , Str "May"
+    , Space
+    , Str "1,"
+    , Space
+    , Str "2017"
+    ]
+, Para
+    [ Str "U"
+    , Str "sing"
+    , Space
+    , Str "Microsoft"
+    , Space
+    , Str "Word"
+    , Space
+    , Str "2007/2010"
+    , LineBreak
+    , Str "for"
+    , Space
+    , Str "Writing"
+    , Space
+    , Str "Technical"
+    , Space
+    , Str "Documents"
+    ]
+, Para [ Str "Valter" , Space , Str "Kiisk" ]
+, Para [ Str "Institute" , Space , Str "of" , Space , Str "Physics," , Space , Str "University" , Space , Str "of" , Space , Str "Tartu" ]
+, Para []
+]
diff --git a/test/docx/textbox_image.docx b/test/docx/textbox_image.docx
new file mode 100644
Binary files /dev/null and b/test/docx/textbox_image.docx differ
diff --git a/test/docx/textbox_image.native b/test/docx/textbox_image.native
new file mode 100644
--- /dev/null
+++ b/test/docx/textbox_image.native
@@ -0,0 +1,30 @@
+[ Para
+    [ Str "The"
+    , Space
+    , Str "image"
+    , Space
+    , Str "is"
+    , Space
+    , Str "below."
+    ]
+, Para
+    [ Image
+        ( ""
+        , []
+        , [ ( "width" , "4.543038057742782in" )
+          , ( "height" , "2.9166666666666665in" )
+          ]
+        )
+        []
+        ( "media/image1.png" , "" )
+    ]
+, Para
+    [ Str "The"
+    , Space
+    , Str "image"
+    , Space
+    , Str "is"
+    , Space
+    , Str "above."
+    ]
+]
diff --git a/test/docx/textbox_image_duplicate_encoding.docx b/test/docx/textbox_image_duplicate_encoding.docx
new file mode 100644
Binary files /dev/null and b/test/docx/textbox_image_duplicate_encoding.docx differ
diff --git a/test/docx/textbox_image_duplicate_encoding.native b/test/docx/textbox_image_duplicate_encoding.native
new file mode 100644
--- /dev/null
+++ b/test/docx/textbox_image_duplicate_encoding.native
@@ -0,0 +1,30 @@
+[ Para
+    [ Str "The"
+    , Space
+    , Str "image"
+    , Space
+    , Str "is"
+    , Space
+    , Str "below."
+    ]
+, Para
+    [ Image
+        ( ""
+        , []
+        , [ ( "width" , "4.543038057742782in" )
+          , ( "height" , "2.9166666666666665in" )
+          ]
+        )
+        []
+        ( "media/image1.png" , "" )
+    ]
+, Para
+    [ Str "The"
+    , Space
+    , Str "image"
+    , Space
+    , Str "is"
+    , Space
+    , Str "above."
+    ]
+]
diff --git a/test/docx/track_changes_scrubbed_metadata.docx b/test/docx/track_changes_scrubbed_metadata.docx
new file mode 100644
Binary files /dev/null and b/test/docx/track_changes_scrubbed_metadata.docx differ
diff --git a/test/docx/track_changes_scrubbed_metadata.native b/test/docx/track_changes_scrubbed_metadata.native
new file mode 100644
--- /dev/null
+++ b/test/docx/track_changes_scrubbed_metadata.native
@@ -0,0 +1,9 @@
+[Para [ Str "Here", Space, Str "is", Space, Str "a", Space
+      , Span ("",["deletion"],[("author","Author")]) [Str "dummy"]
+      , Span ("",["insertion"],[("author","Author")]) [Str "test"]
+      , Space
+      , Span ("",["comment-start"],[("id","3"),("author","Author")]) 
+        [Str "With",Space,Str "a",Space,Str "comment!"]
+      , Str "document",Span ("",["comment-end"],[("id","3")]) [],Str "."
+      ]
+]
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/docx/unused_anchors.docx b/test/docx/unused_anchors.docx
new file mode 100644
Binary files /dev/null and b/test/docx/unused_anchors.docx differ
diff --git a/test/docx/unused_anchors.native b/test/docx/unused_anchors.native
new file mode 100644
--- /dev/null
+++ b/test/docx/unused_anchors.native
@@ -0,0 +1,3 @@
+[Header 1 ("my-section",[],[]) [Str "My",Space,Str "Section"]
+,Para [Link ("",[],[]) [Str "Here",Space,Str "is",Space,Str "a",Space,Str "link."] ("#Foo","")]
+,Para [Span ("Foo",["anchor"],[]) [],Str "Here",Space,Str "is",Space,Str "the",Space,Str "target."]]
diff --git a/test/docx/zotero_citations.docx b/test/docx/zotero_citations.docx
new file mode 100644
Binary files /dev/null and b/test/docx/zotero_citations.docx differ
diff --git a/test/docx/zotero_citations_minus.native b/test/docx/zotero_citations_minus.native
new file mode 100644
--- /dev/null
+++ b/test/docx/zotero_citations_minus.native
@@ -0,0 +1,335 @@
+Pandoc
+  Meta { unMeta = fromList [] }
+  [ Para
+      [ Str "This"
+      , Space
+      , Str "is"
+      , Space
+      , Str "a"
+      , Space
+      , Str "citation"
+      , Space
+      , Str "(Smith"
+      , Space
+      , Str "et"
+      , Space
+      , Str "al.,"
+      , Space
+      , Str "2013)"
+      ]
+  , Para
+      [ Str "This"
+      , Space
+      , Str "is"
+      , Space
+      , Str "a"
+      , Space
+      , Str "citation"
+      , Space
+      , Str "with"
+      , Space
+      , Str "two"
+      , Space
+      , Str "sources"
+      , Space
+      , Str "(Boer"
+      , Space
+      , Str "et"
+      , Space
+      , Str "al.,"
+      , Space
+      , Str "2016;"
+      , Space
+      , Str "Smith"
+      , Space
+      , Str "et"
+      , Space
+      , Str "al.,"
+      , Space
+      , Str "2013)."
+      ]
+  , Para
+      [ Str "This"
+      , Space
+      , Str "is"
+      , Space
+      , Str "a"
+      , Space
+      , Str "citation"
+      , Space
+      , Str "with"
+      , Space
+      , Str "additional"
+      , Space
+      , Str "prefix,"
+      , Space
+      , Str "suffix"
+      , Space
+      , Str "and"
+      , Space
+      , Str "a"
+      , Space
+      , Str "page"
+      , Space
+      , Str "number"
+      , Space
+      , Str "(prefix"
+      , Space
+      , Str "Bellomo"
+      , Space
+      , Str "et"
+      , Space
+      , Str "al.,"
+      , Space
+      , Str "2016,"
+      , Space
+      , Str "p."
+      , Space
+      , Str "2"
+      , Space
+      , Str "suffix)."
+      ]
+  , Header
+      1
+      ( "reference-list" , [] , [] )
+      [ Str "Reference" , Space , Str "list" ]
+  , Para
+      [ Str "Bellomo,"
+      , Space
+      , Str "K.,"
+      , Space
+      , Str "Clement,"
+      , Space
+      , Str "A."
+      , Space
+      , Str "C.,"
+      , Space
+      , Str "Murphy,"
+      , Space
+      , Str "L."
+      , Space
+      , Str "N.,"
+      , Space
+      , Str "Polvani,"
+      , Space
+      , Str "L."
+      , Space
+      , Str "M.,"
+      , Space
+      , Str "&"
+      , Space
+      , Str "Cane,"
+      , Space
+      , Str "M."
+      , Space
+      , Str "A."
+      , Space
+      , Str "(2016)."
+      , Space
+      , Str "New"
+      , Space
+      , Str "observational"
+      , Space
+      , Str "evidence"
+      , Space
+      , Str "for"
+      , Space
+      , Str "a"
+      , Space
+      , Str "positive"
+      , Space
+      , Str "cloud"
+      , Space
+      , Str "feedback"
+      , Space
+      , Str "that"
+      , Space
+      , Str "amplifies"
+      , Space
+      , Str "the"
+      , Space
+      , Str "Atlantic"
+      , Space
+      , Str "Multidecadal"
+      , Space
+      , Str "Oscillation."
+      , Space
+      , Emph
+          [ Str "Geophys."
+          , Space
+          , Str "Res."
+          , Space
+          , Str "Lett."
+          ]
+      , Str ","
+      , Space
+      , Emph [ Str "43" ]
+      , Str "(18),"
+      , Space
+      , Str "9852\8211\&9859."
+      , Space
+      , Str "https://doi.org/10.1002/2016GL069961"
+      ]
+  , Para
+      [ Str "Boer,"
+      , Space
+      , Str "G."
+      , Space
+      , Str "J.,"
+      , Space
+      , Str "Smith,"
+      , Space
+      , Str "D."
+      , Space
+      , Str "M.,"
+      , Space
+      , Str "Cassou,"
+      , Space
+      , Str "C.,"
+      , Space
+      , Str "Doblas-Reyes,"
+      , Space
+      , Str "F.,"
+      , Space
+      , Str "Danabasoglu,"
+      , Space
+      , Str "G.,"
+      , Space
+      , Str "Kirtman,"
+      , Space
+      , Str "B.,"
+      , Space
+      , Str "Kushnir,"
+      , Space
+      , Str "Y.,"
+      , Space
+      , Str "Kimoto,"
+      , Space
+      , Str "M.,"
+      , Space
+      , Str "Meehl,"
+      , Space
+      , Str "G."
+      , Space
+      , Str "A.,"
+      , Space
+      , Str "Msadek,"
+      , Space
+      , Str "R.,"
+      , Space
+      , Str "M\252ller,"
+      , Space
+      , Str "W."
+      , Space
+      , Str "A.,"
+      , Space
+      , Str "Taylor,"
+      , Space
+      , Str "K."
+      , Space
+      , Str "E.,"
+      , Space
+      , Str "Zwiers,"
+      , Space
+      , Str "F.,"
+      , Space
+      , Str "Rixen,"
+      , Space
+      , Str "M.,"
+      , Space
+      , Str "Ruprich-Robert,"
+      , Space
+      , Str "Y.,"
+      , Space
+      , Str "&"
+      , Space
+      , Str "Eade,"
+      , Space
+      , Str "R."
+      , Space
+      , Str "(2016)."
+      , Space
+      , Str "The"
+      , Space
+      , Str "Decadal"
+      , Space
+      , Str "Climate"
+      , Space
+      , Str "Prediction"
+      , Space
+      , Str "Project"
+      , Space
+      , Str "(DCPP)."
+      , Space
+      , Emph
+          [ Str "Geoscientific"
+          , Space
+          , Str "Model"
+          , Space
+          , Str "Development"
+          ]
+      , Str ","
+      , Space
+      , Emph [ Str "9" ]
+      , Str ","
+      , Space
+      , Str "3751\8211\&3777."
+      , Space
+      , Str "https://doi.org/10.5194/gmd-9-3751-2016"
+      ]
+  , Para
+      [ Str "Smith,"
+      , Space
+      , Str "D."
+      , Space
+      , Str "M.,"
+      , Space
+      , Str "Eade,"
+      , Space
+      , Str "R.,"
+      , Space
+      , Str "&"
+      , Space
+      , Str "Pohlmann,"
+      , Space
+      , Str "H."
+      , Space
+      , Str "(2013)."
+      , Space
+      , Str "A"
+      , Space
+      , Str "comparison"
+      , Space
+      , Str "of"
+      , Space
+      , Str "full-field"
+      , Space
+      , Str "and"
+      , Space
+      , Str "anomaly"
+      , Space
+      , Str "initialization"
+      , Space
+      , Str "for"
+      , Space
+      , Str "seasonal"
+      , Space
+      , Str "to"
+      , Space
+      , Str "decadal"
+      , Space
+      , Str "climate"
+      , Space
+      , Str "prediction."
+      , Space
+      , Emph [ Str "Climate" , Space , Str "Dynamics" ]
+      , Str ","
+      , Space
+      , Emph [ Str "41" ]
+      , Str "(11\8211\&12),"
+      , Space
+      , Str "3325\8211\&3338."
+      , Space
+      , Str "https://doi.org/10.1007/s00382-013-1683-2"
+      ]
+  ]
diff --git a/test/docx/zotero_citations_plus.native b/test/docx/zotero_citations_plus.native
new file mode 100644
--- /dev/null
+++ b/test/docx/zotero_citations_plus.native
@@ -0,0 +1,440 @@
+Pandoc
+  Meta
+    { unMeta =
+        fromList
+          [ ( "references"
+            , MetaList
+                [ MetaMap
+                    (fromList
+                       [ ( "DOI" , MetaString "10.1002/2016GL069961" )
+                       , ( "author"
+                         , MetaList
+                             [ MetaMap
+                                 (fromList
+                                    [ ( "family"
+                                      , MetaString "Bellomo"
+                                      )
+                                    , ( "given" , MetaString "K." )
+                                    ])
+                             , MetaMap
+                                 (fromList
+                                    [ ( "family"
+                                      , MetaString "Clement"
+                                      )
+                                    , ( "given" , MetaString "A.C." )
+                                    ])
+                             , MetaMap
+                                 (fromList
+                                    [ ( "family" , MetaString "Murphy" )
+                                    , ( "given" , MetaString "L.N." )
+                                    ])
+                             , MetaMap
+                                 (fromList
+                                    [ ( "family"
+                                      , MetaString "Polvani"
+                                      )
+                                    , ( "given" , MetaString "L.M." )
+                                    ])
+                             , MetaMap
+                                 (fromList
+                                    [ ( "family" , MetaString "Cane" )
+                                    , ( "given" , MetaString "M.A." )
+                                    ])
+                             ]
+                         )
+                       , ( "container-title"
+                         , MetaInlines
+                             [ Str "Geophys."
+                             , Space
+                             , Str "Res."
+                             , Space
+                             , Str "Lett."
+                             ]
+                         )
+                       , ( "id" , MetaString "10" )
+                       , ( "issue" , MetaInlines [ Str "18" ] )
+                       , ( "issued" , MetaString "2016" )
+                       , ( "language" , MetaInlines [ Str "en" ] )
+                       , ( "page"
+                         , MetaInlines [ Str "9852\8211\&9859" ]
+                         )
+                       , ( "title"
+                         , MetaInlines
+                             [ Str "New"
+                             , Space
+                             , Str "observational"
+                             , Space
+                             , Str "evidence"
+                             , Space
+                             , Str "for"
+                             , Space
+                             , Str "a"
+                             , Space
+                             , Str "positive"
+                             , Space
+                             , Str "cloud"
+                             , Space
+                             , Str "feedback"
+                             , Space
+                             , Str "that"
+                             , Space
+                             , Str "amplifies"
+                             , Space
+                             , Str "the"
+                             , Space
+                             , Str "Atlantic"
+                             , Space
+                             , Str "Multidecadal"
+                             , Space
+                             , Str "Oscillation"
+                             ]
+                         )
+                       , ( "type" , MetaString "article-journal" )
+                       , ( "volume" , MetaInlines [ Str "43" ] )
+                       ])
+                , MetaMap
+                    (fromList
+                       [ ( "DOI"
+                         , MetaString "10.1007/s00382-013-1683-2"
+                         )
+                       , ( "ISSN" , MetaString "0930-7575, 1432-0894" )
+                       , ( "author"
+                         , MetaList
+                             [ MetaMap
+                                 (fromList
+                                    [ ( "family" , MetaString "Smith" )
+                                    , ( "given" , MetaString "Doug M." )
+                                    ])
+                             , MetaMap
+                                 (fromList
+                                    [ ( "family" , MetaString "Eade" )
+                                    , ( "given" , MetaString "Rosie" )
+                                    ])
+                             , MetaMap
+                                 (fromList
+                                    [ ( "family"
+                                      , MetaString "Pohlmann"
+                                      )
+                                    , ( "given" , MetaString "Holger" )
+                                    ])
+                             ]
+                         )
+                       , ( "container-title"
+                         , MetaInlines
+                             [ Str "Climate" , Space , Str "Dynamics" ]
+                         )
+                       , ( "id" , MetaString "109" )
+                       , ( "issue" , MetaInlines [ Str "11-12" ] )
+                       , ( "issued" , MetaString "2013-12" )
+                       , ( "language" , MetaInlines [ Str "en" ] )
+                       , ( "page"
+                         , MetaInlines [ Str "3325\8211\&3338" ]
+                         )
+                       , ( "title"
+                         , MetaInlines
+                             [ Str "A"
+                             , Space
+                             , Str "comparison"
+                             , Space
+                             , Str "of"
+                             , Space
+                             , Str "full-field"
+                             , Space
+                             , Str "and"
+                             , Space
+                             , Str "anomaly"
+                             , Space
+                             , Str "initialization"
+                             , Space
+                             , Str "for"
+                             , Space
+                             , Str "seasonal"
+                             , Space
+                             , Str "to"
+                             , Space
+                             , Str "decadal"
+                             , Space
+                             , Str "climate"
+                             , Space
+                             , Str "prediction"
+                             ]
+                         )
+                       , ( "type" , MetaString "article-journal" )
+                       , ( "volume" , MetaInlines [ Str "41" ] )
+                       ])
+                , MetaMap
+                    (fromList
+                       [ ( "DOI"
+                         , MetaString "10.5194/gmd-9-3751-2016"
+                         )
+                       , ( "author"
+                         , MetaList
+                             [ MetaMap
+                                 (fromList
+                                    [ ( "family" , MetaString "Boer" )
+                                    , ( "given" , MetaString "G.J." )
+                                    ])
+                             , MetaMap
+                                 (fromList
+                                    [ ( "family" , MetaString "Smith" )
+                                    , ( "given" , MetaString "D.M." )
+                                    ])
+                             , MetaMap
+                                 (fromList
+                                    [ ( "family" , MetaString "Cassou" )
+                                    , ( "given" , MetaString "C." )
+                                    ])
+                             , MetaMap
+                                 (fromList
+                                    [ ( "family"
+                                      , MetaString "Doblas-Reyes"
+                                      )
+                                    , ( "given" , MetaString "F." )
+                                    ])
+                             , MetaMap
+                                 (fromList
+                                    [ ( "family"
+                                      , MetaString "Danabasoglu"
+                                      )
+                                    , ( "given" , MetaString "G." )
+                                    ])
+                             , MetaMap
+                                 (fromList
+                                    [ ( "family"
+                                      , MetaString "Kirtman"
+                                      )
+                                    , ( "given" , MetaString "B." )
+                                    ])
+                             , MetaMap
+                                 (fromList
+                                    [ ( "family"
+                                      , MetaString "Kushnir"
+                                      )
+                                    , ( "given" , MetaString "Y." )
+                                    ])
+                             , MetaMap
+                                 (fromList
+                                    [ ( "family" , MetaString "Kimoto" )
+                                    , ( "given" , MetaString "M." )
+                                    ])
+                             , MetaMap
+                                 (fromList
+                                    [ ( "family" , MetaString "Meehl" )
+                                    , ( "given" , MetaString "G.A." )
+                                    ])
+                             , MetaMap
+                                 (fromList
+                                    [ ( "family" , MetaString "Msadek" )
+                                    , ( "given" , MetaString "R." )
+                                    ])
+                             , MetaMap
+                                 (fromList
+                                    [ ( "family"
+                                      , MetaString "M\252ller"
+                                      )
+                                    , ( "given" , MetaString "W.A." )
+                                    ])
+                             , MetaMap
+                                 (fromList
+                                    [ ( "family" , MetaString "Taylor" )
+                                    , ( "given" , MetaString "K.E." )
+                                    ])
+                             , MetaMap
+                                 (fromList
+                                    [ ( "family" , MetaString "Zwiers" )
+                                    , ( "given" , MetaString "F." )
+                                    ])
+                             , MetaMap
+                                 (fromList
+                                    [ ( "family" , MetaString "Rixen" )
+                                    , ( "given" , MetaString "M." )
+                                    ])
+                             , MetaMap
+                                 (fromList
+                                    [ ( "family"
+                                      , MetaString "Ruprich-Robert"
+                                      )
+                                    , ( "given" , MetaString "Y." )
+                                    ])
+                             , MetaMap
+                                 (fromList
+                                    [ ( "family" , MetaString "Eade" )
+                                    , ( "given" , MetaString "R." )
+                                    ])
+                             ]
+                         )
+                       , ( "container-title"
+                         , MetaInlines
+                             [ Str "Geoscientific"
+                             , Space
+                             , Str "Model"
+                             , Space
+                             , Str "Development"
+                             ]
+                         )
+                       , ( "id" , MetaString "6" )
+                       , ( "issued" , MetaString "2016" )
+                       , ( "language" , MetaInlines [ Str "en" ] )
+                       , ( "page"
+                         , MetaInlines [ Str "3751\8211\&3777" ]
+                         )
+                       , ( "title"
+                         , MetaInlines
+                             [ Str "The"
+                             , Space
+                             , Str "Decadal"
+                             , Space
+                             , Str "Climate"
+                             , Space
+                             , Str "Prediction"
+                             , Space
+                             , Str "Project"
+                             , Space
+                             , Str "(DCPP)"
+                             ]
+                         )
+                       , ( "type" , MetaString "article-journal" )
+                       , ( "volume" , MetaInlines [ Str "9" ] )
+                       ])
+                ]
+            )
+          ]
+    }
+  [ Para
+      [ Str "This"
+      , Space
+      , Str "is"
+      , Space
+      , Str "a"
+      , Space
+      , Str "citation"
+      , Space
+      , Cite
+          [ Citation
+              { citationId = "109"
+              , citationPrefix = []
+              , citationSuffix = []
+              , citationMode = NormalCitation
+              , citationNoteNum = 0
+              , citationHash = 0
+              }
+          ]
+          [ Str "(Smith"
+          , Space
+          , Str "et"
+          , Space
+          , Str "al.,"
+          , Space
+          , Str "2013)"
+          ]
+      ]
+  , Para
+      [ Str "This"
+      , Space
+      , Str "is"
+      , Space
+      , Str "a"
+      , Space
+      , Str "citation"
+      , Space
+      , Str "with"
+      , Space
+      , Str "two"
+      , Space
+      , Str "sources"
+      , Space
+      , Cite
+          [ Citation
+              { citationId = "6"
+              , citationPrefix = []
+              , citationSuffix = []
+              , citationMode = NormalCitation
+              , citationNoteNum = 0
+              , citationHash = 0
+              }
+          , Citation
+              { citationId = "109"
+              , citationPrefix = []
+              , citationSuffix = []
+              , citationMode = NormalCitation
+              , citationNoteNum = 0
+              , citationHash = 0
+              }
+          ]
+          [ Str "(Boer"
+          , Space
+          , Str "et"
+          , Space
+          , Str "al.,"
+          , Space
+          , Str "2016;"
+          , Space
+          , Str "Smith"
+          , Space
+          , Str "et"
+          , Space
+          , Str "al.,"
+          , Space
+          , Str "2013)"
+          ]
+      , Str "."
+      ]
+  , Para
+      [ Str "This"
+      , Space
+      , Str "is"
+      , Space
+      , Str "a"
+      , Space
+      , Str "citation"
+      , Space
+      , Str "with"
+      , Space
+      , Str "additional"
+      , Space
+      , Str "prefix,"
+      , Space
+      , Str "suffix"
+      , Space
+      , Str "and"
+      , Space
+      , Str "a"
+      , Space
+      , Str "page"
+      , Space
+      , Str "number"
+      , Space
+      , Cite
+          [ Citation
+              { citationId = "10"
+              , citationPrefix = [ Str "prefix" ]
+              , citationSuffix =
+                  [ Str "," , Space , Str "2" , Space , Str "suffix" ]
+              , citationMode = NormalCitation
+              , citationNoteNum = 0
+              , citationHash = 0
+              }
+          ]
+          [ Str "(prefix"
+          , Space
+          , Str "Bellomo"
+          , Space
+          , Str "et"
+          , Space
+          , Str "al.,"
+          , Space
+          , Str "2016,"
+          , Space
+          , Str "p."
+          , Space
+          , Str "2"
+          , Space
+          , Str "suffix)"
+          ]
+      , Str "."
+      ]
+  , Header
+      1
+      ( "reference-list" , [] , [] )
+      [ Str "Reference" , Space , Str "list" ]
+  ]
diff --git a/test/dokuwiki_external_images.dokuwiki b/test/dokuwiki_external_images.dokuwiki
--- a/test/dokuwiki_external_images.dokuwiki
+++ b/test/dokuwiki_external_images.dokuwiki
@@ -1,1 +1,1 @@
-{{https://cooluri.com/image.png|HTTPS image}} {{http://cooluri.com/image.png|HTTP image}} {{ftp://ftp.cooluri.com/image.png|FTP image}} {{file:///tmp/coolimage.png|Filesystem image}} {{:/image.jpg|Relative image 1}} {{:image.jpg|Relative image 2}}
+{{https://cooluri.com/image.png|HTTPS image}} {{http://cooluri.com/image.png|HTTP image}} {{ftp://ftp.cooluri.com/image.png|FTP image}} {{file:///tmp/coolimage.png|Filesystem image}} {{/image.jpg|Relative image 1}} {{image.jpg|Relative image 2}}
diff --git a/test/dokuwiki_multiblock_table.dokuwiki b/test/dokuwiki_multiblock_table.dokuwiki
--- a/test/dokuwiki_multiblock_table.dokuwiki
+++ b/test/dokuwiki_multiblock_table.dokuwiki
@@ -1,4 +1,5 @@
 Sample grid table.
-^Fruit  ^Price^Advantages                     ^
-|Bananas|$1.34|built-in wrapper\\ \\ potassium|
-|Oranges|$2.10|* cures scurvy\\ * tasty       |
+^Fruit  ^Price^Advantages                         ^
+|Bananas|$1.34|built-in wrapper\\ \\ potassium    |
+|Oranges|$2.10|* cures scurvy\\ * tasty           |
+|Apples |$1.10|Some text\\ \\ after two linebreaks|
diff --git a/test/dokuwiki_multiblock_table.native b/test/dokuwiki_multiblock_table.native
--- a/test/dokuwiki_multiblock_table.native
+++ b/test/dokuwiki_multiblock_table.native
@@ -1,13 +1,41 @@
-[Table [Str "Sample",Space,Str "grid",Space,Str "table."] [AlignDefault,AlignDefault,AlignDefault] [0.2222222222222222,0.2222222222222222,0.2916666666666667]
- [[Plain [Str "Fruit"]]
- ,[Plain [Str "Price"]]
- ,[Plain [Str "Advantages"]]]
- [[[Para [Str "Bananas"]]
-  ,[Para [Str "$1.34"]]
-  ,[Para [Str "built-in",Space,Str "wrapper"]
-   ,Para [Str "potassium"]]]
- ,[[Para [Str "Oranges"]]
-  ,[Para [Str "$2.10"]]
-  ,[BulletList
-    [[Plain [Str "cures",Space,Str "scurvy"]]
-    ,[Plain [Str "tasty"]]]]]]]
+[Table ("",[],[]) (Caption Nothing
+ [Para [Str "Sample",Space,Str "grid",Space,Str "table."]])
+ [(AlignDefault,ColWidth 0.2222222222222222)
+ ,(AlignDefault,ColWidth 0.2222222222222222)
+ ,(AlignDefault,ColWidth 0.2916666666666667)]
+ (TableHead ("",[],[])
+ [Row ("",[],[])
+  [Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+   [Plain [Str "Fruit"]]
+  ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+   [Plain [Str "Price"]]
+  ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+   [Plain [Str "Advantages"]]]])
+ [(TableBody ("",[],[]) (RowHeadColumns 0)
+  []
+  [Row ("",[],[])
+   [Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Para [Str "Bananas"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Para [Str "$1.34"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Para [Str "built-in",Space,Str "wrapper"]
+    ,Para [Str "potassium"]]]
+  ,Row ("",[],[])
+   [Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Para [Str "Oranges"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Para [Str "$2.10"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [BulletList
+     [[Plain [Str "cures",Space,Str "scurvy"]]
+     ,[Plain [Str "tasty"]]]]]
+  ,Row ("",[],[])
+   [Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Para [Str "Apples"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Para [Str "$1.10"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Para [Str "Some",Space,Str "text",LineBreak,LineBreak,Str "after",Space,Str "two",Space,Str "linebreaks"]]]])]
+ (TableFoot ("",[],[])
+ [])]
diff --git a/test/endnotexml-reader.native b/test/endnotexml-reader.native
new file mode 100644
--- /dev/null
+++ b/test/endnotexml-reader.native
@@ -0,0 +1,124 @@
+Pandoc
+  Meta
+    { unMeta =
+        fromList
+          [ ( "nocite"
+            , MetaInlines
+                [ Cite
+                    [ Citation
+                        { citationId = "*"
+                        , citationPrefix = []
+                        , citationSuffix = []
+                        , citationMode = NormalCitation
+                        , citationNoteNum = 0
+                        , citationHash = 0
+                        }
+                    ]
+                    [ Str "[@*]" ]
+                ]
+            )
+          , ( "references"
+            , MetaList
+                [ MetaMap
+                    (fromList
+                       [ ( "author"
+                         , MetaList
+                             [ MetaMap
+                                 (fromList
+                                    [ ( "family"
+                                      , MetaString "Chapman"
+                                      )
+                                    , ( "given" , MetaString "A. G." )
+                                    ])
+                             ]
+                         )
+                       , ( "container-title"
+                         , MetaInlines [ Str "Ecology" ]
+                         )
+                       , ( "id" , MetaString "13264" )
+                       , ( "isbn" , MetaInlines [ Str "0012-9658" ] )
+                       , ( "issued" , MetaString "1937" )
+                       , ( "number" , MetaInlines [ Str "1" ] )
+                       , ( "pages" , MetaInlines [ Str "93-105" ] )
+                       , ( "title"
+                         , MetaInlines
+                             [ Str "An"
+                             , SoftBreak
+                             , Str "ecological"
+                             , Space
+                             , Str "basis"
+                             , Space
+                             , Str "for"
+                             , Space
+                             , Str "reforestation"
+                             , Space
+                             , Str "of"
+                             , Space
+                             , Str "submariginal"
+                             , Space
+                             , Str "lands"
+                             , SoftBreak
+                             , Str "in"
+                             , Space
+                             , Str "the"
+                             , Space
+                             , Str "Central"
+                             , Space
+                             , Str "Hardwood"
+                             , Space
+                             , Str "Region"
+                             ]
+                         )
+                       , ( "type" , MetaString "article-journal" )
+                       , ( "volume" , MetaInlines [ Str "18" ] )
+                       ])
+                , MetaMap
+                    (fromList
+                       [ ( "author"
+                         , MetaList
+                             [ MetaMap
+                                 (fromList
+                                    [ ( "family"
+                                      , MetaString "Strohecker"
+                                      )
+                                    , ( "given" , MetaString "H. F." )
+                                    ])
+                             ]
+                         )
+                       , ( "container-title"
+                         , MetaInlines [ Str "Ecology" ]
+                         )
+                       , ( "id" , MetaString "13265" )
+                       , ( "isbn" , MetaInlines [ Str "0012-9658" ] )
+                       , ( "issued" , MetaString "1937" )
+                       , ( "number" , MetaInlines [ Str "1" ] )
+                       , ( "pages" , MetaInlines [ Str "162-168" ] )
+                       , ( "title"
+                         , MetaInlines
+                             [ Str "A"
+                             , Space
+                             , Str "survey"
+                             , SoftBreak
+                             , Str "of"
+                             , Space
+                             , Str "soil"
+                             , Space
+                             , Str "temperatures"
+                             , Space
+                             , Str "in"
+                             , Space
+                             , Str "the"
+                             , Space
+                             , Str "Chicago"
+                             , Space
+                             , Str "area"
+                             ]
+                         )
+                       , ( "type" , MetaString "article-journal" )
+                       , ( "volume" , MetaInlines [ Str "18" ] )
+                       ])
+                ]
+            )
+          ]
+    }
+  []
diff --git a/test/endnotexml-reader.xml b/test/endnotexml-reader.xml
new file mode 100644
--- /dev/null
+++ b/test/endnotexml-reader.xml
@@ -0,0 +1,216 @@
+<?xml version="1.0" encoding="utf-8"?>
+<xml>
+  <records>
+    <record>
+      <database name="EndNote Ecology.enl"
+      path="/Users/LowDecarie/Dropbox/Meta presentation of stats/Data/EndNote Ecology.enl">
+      EndNote Ecology.enl</database>
+      <source-app name="EndNote" version="15.0">
+      EndNote</source-app>
+      <rec-number>13264</rec-number>
+      <foreign-keys>
+        <key app="EN" db-id="0xxzez5ectezp7e9zrnxp0dq5zrafepwxfe2">
+        13264</key>
+      </foreign-keys>
+      <ref-type name="Journal Article">17</ref-type>
+      <contributors>
+        <authors>
+          <author>
+            <style face="normal" font="default" size="100%">
+            Chapman, A. G.</style>
+          </author>
+        </authors>
+      </contributors>
+      <auth-address>
+        <style face="normal" font="default" size="100%">Cent States
+        Forest Expt Stn, Columbus, OH USA</style>
+      </auth-address>
+      <titles>
+        <title>
+          <style face="normal" font="default" size="100%">An
+          ecological basis for reforestation of submariginal lands
+          in the Central Hardwood Region</style>
+        </title>
+        <secondary-title>
+          <style face="normal" font="default" size="100%">
+          Ecology</style>
+        </secondary-title>
+        <alt-title>
+          <style face="normal" font="default" size="100%">
+          Ecology</style>
+        </alt-title>
+      </titles>
+      <periodical>
+        <full-title>
+          <style face="normal" font="default" size="100%">
+          Ecology</style>
+        </full-title>
+        <abbr-1>
+          <style face="normal" font="default" size="100%">
+          Ecology</style>
+        </abbr-1>
+      </periodical>
+      <alt-periodical>
+        <full-title>
+          <style face="normal" font="default" size="100%">
+          Ecology</style>
+        </full-title>
+        <abbr-1>
+          <style face="normal" font="default" size="100%">
+          Ecology</style>
+        </abbr-1>
+      </alt-periodical>
+      <pages>
+        <style face="normal" font="default" size="100%">
+        93-105</style>
+      </pages>
+      <volume>
+        <style face="normal" font="default" size="100%">18</style>
+      </volume>
+      <number>
+        <style face="normal" font="default" size="100%">1</style>
+      </number>
+      <dates>
+        <year>
+          <style face="normal" font="default" size="100%">
+          1937</style>
+        </year>
+        <pub-dates>
+          <date>
+            <style face="normal" font="default" size="100%">
+            Jan</style>
+          </date>
+        </pub-dates>
+      </dates>
+      <isbn>
+        <style face="normal" font="default" size="100%">
+        0012-9658</style>
+      </isbn>
+      <accession-num>
+        <style face="normal" font="default" size="100%">
+        ISI:000200148800007</style>
+      </accession-num>
+      <notes>
+        <style face="normal" font="default" size="100%">V02fgTimes
+        Cited:5Cited References Count:2</style>
+      </notes>
+      <urls>
+        <related-urls>
+          <url>
+            <style face="normal" font="default" size="100%">&lt;Go
+            to ISI&gt;://000200148800007</style>
+          </url>
+        </related-urls>
+      </urls>
+      <language>
+        <style face="normal" font="default" size="100%">
+        English</style>
+      </language>
+    </record>
+    <record>
+      <database name="EndNote Ecology.enl"
+      path="/Users/LowDecarie/Dropbox/Meta presentation of stats/Data/EndNote Ecology.enl">
+      EndNote Ecology.enl</database>
+      <source-app name="EndNote" version="15.0">
+      EndNote</source-app>
+      <rec-number>13265</rec-number>
+      <foreign-keys>
+        <key app="EN" db-id="0xxzez5ectezp7e9zrnxp0dq5zrafepwxfe2">
+        13265</key>
+      </foreign-keys>
+      <ref-type name="Journal Article">17</ref-type>
+      <contributors>
+        <authors>
+          <author>
+            <style face="normal" font="default" size="100%">
+            Strohecker, H. F.</style>
+          </author>
+        </authors>
+      </contributors>
+      <auth-address>
+        <style face="normal" font="default" size="100%">Univ
+        Chicago, Chicago, IL USA</style>
+      </auth-address>
+      <titles>
+        <title>
+          <style face="normal" font="default" size="100%">A survey
+          of soil temperatures in the Chicago area</style>
+        </title>
+        <secondary-title>
+          <style face="normal" font="default" size="100%">
+          Ecology</style>
+        </secondary-title>
+        <alt-title>
+          <style face="normal" font="default" size="100%">
+          Ecology</style>
+        </alt-title>
+      </titles>
+      <periodical>
+        <full-title>
+          <style face="normal" font="default" size="100%">
+          Ecology</style>
+        </full-title>
+        <abbr-1>
+          <style face="normal" font="default" size="100%">
+          Ecology</style>
+        </abbr-1>
+      </periodical>
+      <alt-periodical>
+        <full-title>
+          <style face="normal" font="default" size="100%">
+          Ecology</style>
+        </full-title>
+        <abbr-1>
+          <style face="normal" font="default" size="100%">
+          Ecology</style>
+        </abbr-1>
+      </alt-periodical>
+      <pages>
+        <style face="normal" font="default" size="100%">
+        162-168</style>
+      </pages>
+      <volume>
+        <style face="normal" font="default" size="100%">18</style>
+      </volume>
+      <number>
+        <style face="normal" font="default" size="100%">1</style>
+      </number>
+      <dates>
+        <year>
+          <style face="normal" font="default" size="100%">
+          1937</style>
+        </year>
+        <pub-dates>
+          <date>
+            <style face="normal" font="default" size="100%">
+            Jan</style>
+          </date>
+        </pub-dates>
+      </dates>
+      <isbn>
+        <style face="normal" font="default" size="100%">
+        0012-9658</style>
+      </isbn>
+      <accession-num>
+        <style face="normal" font="default" size="100%">
+        ISI:000200148800014</style>
+      </accession-num>
+      <notes>
+        <style face="normal" font="default" size="100%">V02fgTimes
+        Cited:5Cited References Count:14</style>
+      </notes>
+      <urls>
+        <related-urls>
+          <url>
+            <style face="normal" font="default" size="100%">&lt;Go
+            to ISI&gt;://000200148800014</style>
+          </url>
+        </related-urls>
+      </urls>
+      <language>
+        <style face="normal" font="default" size="100%">
+        English</style>
+      </language>
+    </record>
+  </records>
+</xml>
diff --git a/test/epub/epub2_cover.epub b/test/epub/epub2_cover.epub
new file mode 100644
Binary files /dev/null and b/test/epub/epub2_cover.epub differ
diff --git a/test/epub/epub2_no_cover.epub b/test/epub/epub2_no_cover.epub
new file mode 100644
Binary files /dev/null and b/test/epub/epub2_no_cover.epub differ
diff --git a/test/epub/epub2_picture.epub b/test/epub/epub2_picture.epub
new file mode 100644
Binary files /dev/null and b/test/epub/epub2_picture.epub differ
diff --git a/test/epub/features.epub b/test/epub/features.epub
Binary files a/test/epub/features.epub and b/test/epub/features.epub differ
diff --git a/test/epub/features.native b/test/epub/features.native
--- a/test/epub/features.native
+++ b/test/epub/features.native
@@ -1,93 +1,1721 @@
-[Para [Span ("front.xhtml",[],[]) []]
-,Div ("",["section"],[])
- [Header 1 ("",[],[]) [Str "Reflowable",Space,Str "EPUB",Space,Str "3",Space,Str "Conformance",Space,Str "Test",Space,Str "Document:",Space,Str "0100"]
- ,Div ("",["section"],[])
-  [Header 2 ("",[],[]) [Str "Status",Space,Str "of",Space,Str "this",Space,Str "Document"]
-  ,Para [Str "This",Space,Str "publication",Space,Str "is",Space,Str "currently",Space,Str "considered",Space,Span ("",["status"],[]) [Str "[UNDER",Space,Str "DEVELOPMENT]"],Space,Str "by",Space,Str "the",Space,Str "IDPF."]
-  ,Para [Str "This",Space,Str "publication",Space,Str "is",Space,Str "part",Space,Str "of",Space,Str "version",Space,Span ("",["version"],[]) [Str "X.X"],Space,Str "of",Space,Str "the",Space,Str "EPUB",Space,Str "3.0",Space,Str "Compliance",Space,Str "Test",Space,Str "Suite",Space,Str "released",SoftBreak,Str "on",Space,RawInline (Format "html") "<time class=\"release\">",Str "TBD",RawInline (Format "html") "</time>",Str "."]
-  ,Para [Str "Before",Space,Str "using",Space,Str "this",Space,Str "publication",Space,Str "to",Space,Str "evaluate",Space,Str "reading",Space,Str "systems,",Space,Str "testers",Space,Str "are",Space,Str "strongly",Space,Str "encouraged",Space,Str "to",SoftBreak,Str "verify",Space,Str "that",Space,Str "they",Space,Str "have",Space,Str "the",Space,Str "latest",Space,Str "release",Space,Str "by",Space,Str "checking",Space,Str "the",Space,Str "current",Space,Str "release",Space,Str "version",Space,Str "and",Space,Str "date",Space,Str "of",SoftBreak,Str "the",Space,Str "test",Space,Str "suite",Space,Str "at",Space,Link ("",[],[]) [Str "TBD"] ("http://idpf.org/","")]
-  ,Para [Str "This",Space,Str "publication",Space,Str "is",Space,Str "one",Space,Str "of",Space,Str "several",Space,Str "that",Space,Str "currently",Space,Str "comprise",Space,Str "the",Space,Str "EPUB",Space,Str "3",Space,Str "conformance",Space,Str "test",Space,Str "suite",SoftBreak,Str "for",Space,Str "reflowable",Space,Str "content.",Space,Str "The",Space,Str "complete",Space,Str "test",Space,Str "suite",Space,Str "includes",Space,Str "all",Space,Str "of",Space,Str "the",Space,Str "following",Space,Str "publications:"]
-  ,OrderedList (1,DefaultStyle,DefaultDelim)
-   [[Plain [Str "."]]]]
- ,Div ("",["section"],[])
-  [Header 2 ("",[],[]) [Str "About",Space,Str "this",Space,Str "Document"]
-  ,Para [Str "This",Space,Str "document",Space,Str "focuses",Space,Str "on",Space,Str "human-evaluated",Space,Str "binary",Space,Str "(pass/fail)",Space,Str "tests",Space,Str "in",Space,Str "a",SoftBreak,Str "reflowable",Space,Str "context.",Space,Str "Tests",Space,Str "for",Space,Str "fixed-layout",Space,Str "content",Space,Str "and",Space,Str "other",Space,Str "individual",Space,Str "tests",Space,Str "that",SoftBreak,Str "require",Space,Str "a",Space,Str "dedicated",Space,Str "epub",Space,Str "file",Space,Str "are",Space,Str "available",Space,Str "in",Space,Str "additional",Space,Str "sibling",Space,Str "documents;",Space,Str "refer",Space,Str "to",SoftBreak,Str "the",Space,Link ("",[],[]) [Str "test",Space,Str "suite",SoftBreak,Str "wiki"] ("https://github.com/mgylling/epub-testsuite/wiki/Overview",""),Space,Str "(",Code ("",[],[]) "https://github.com/mgylling/epub-testsuite/wiki/Overview",Str ")",Space,Str "for",Space,Str "additional",SoftBreak,Str "information."]]
- ,Div ("",["section"],[])
-  [Header 2 ("",[],[]) [Str "Conventions"]
-  ,Para [Str "The",Space,Str "following",Space,Str "conventions",Space,Str "are",Space,Str "used",Space,Str "throughout",Space,Str "the",Space,Str "document:"]
-  ,DefinitionList
-   [([Str "1.",Space,Str "Locating",Space,Str "a",Space,Str "test"],
-     [[Div ("",["ctest"],[])
-       [Para [Str "Tests",Space,Str "for",Space,Emph [Str "required"],Space,Str "Reading",Space,Str "System",Space,Str "functionality",Space,Str "are",SoftBreak,Str "preceded",Space,Str "by",Space,Str "the",Space,Str "label:",Space,Span ("",["nature"],[("style","display: inline; font-size: 100%")]) [Str "[REQUIRED]"]]]
-      ,Div ("",["otest"],[])
-       [Para [Str "Tests",Space,Str "for",Space,Emph [Str "optional"],Space,Str "Reading",Space,Str "System",Space,Str "functionality",Space,Str "are",SoftBreak,Str "preceded",Space,Str "by",Space,Str "the",Space,Str "label:",Space,Span ("",["nature"],[("style","display: inline; font-size: 100%")]) [Str "[OPTIONAL]"]]]]])
-   ,([Str "2.",Space,Str "Performing",Space,Str "the",Space,Str "test"],
-     [[Plain [Str "Each",Space,Str "test",Space,Str "includes",Space,Str "a",Space,Str "description",Space,Str "of",Space,Str "its",Space,Str "purpose",Space,Str "followed",Space,Str "by",Space,Str "the",Space,Str "actual",Space,Strong [Str "test",Space,Str "statement,",SoftBreak,Str "which",Space,Str "can",Space,Str "always",Space,Str "be",Space,Str "evaluated",Space,Str "to",Space,Str "true",Space,Str "or",Space,Str "false"],Str ".",Space,Str "These",Space,Str "statements",Space,Str "typically",Space,Str "have",Space,Str "the",Space,Str "form:",SoftBreak,Str "\"If",Space,Str "[some",Space,Str "condition],",Space,Str "the",Space,Str "test",Space,Str "passes\"."]]])
-   ,([Str "3.",Space,Str "Scoring",Space,Str "in",Space,Str "the",Space,Str "results",Space,Str "form"],
-     [[Plain [Str "@@@TODO",Space,Str "provide",Space,Str "info",Space,Str "on",Space,Str "where",Space,Str "to",Space,Str "get",Space,Str "the",Space,Str "results",Space,Str "form"]]])]]]
-,Para [Span ("content-mathml-001.xhtml",[],[]) []]
-,Div ("",["section"],[])
- [Header 2 ("content-mathml-001.xhtml#mathml",[],[]) [Str "MathML"]
- ,Div ("content-mathml-001.xhtml#mathml-010",["section","ctest"],[])
-  [Header 2 ("",[],[]) [Span ("",["nature"],[]) [Str "[REQUIRED]"],SoftBreak,Span ("",["test-id"],[]) [Str "mathml-010"],Space,Str "Rendering"]
-  ,Para [Str "Tests",Space,Str "whether",Space,Str "MathML",Space,Str "equation",Space,Str "rendering",Space,Str "is",Space,Str "supported."]
-  ,Plain [Math DisplayMath "\\int_{- \\infty}^{\\infty}e^{- x^{2}}\\, dx = \\sqrt{\\pi}",SoftBreak,Math DisplayMath "\\sum\\limits_{n = 1}^{\\infty}\\frac{1}{n^{2}} = \\frac{\\pi^{2}}{6}",SoftBreak,Math DisplayMath "x = \\frac{- b \\pm \\sqrt{b^{2} - 4ac}}{2a}"]
-  ,Para [Str "If",Space,Str "the",Space,Str "preceding",Space,Str "equations",Space,Str "are",Space,Str "not",Space,Str "presented",Space,Str "as",Space,Str "linear",Space,Str "text",Space,Str "(e.g.,",Space,Str "x=-b\177b2-4ac2a),",SoftBreak,Str "the",Space,Str "test",Space,Str "passes."]]
- ,Div ("content-mathml-001.xhtml#mathml-020",["section","otest"],[])
-  [Header 2 ("",[],[]) [Span ("",["nature"],[]) [Str "[OPTIONAL]"],SoftBreak,Span ("",["test-id"],[]) [Str "mathml-020"],Space,Str "CSS",Space,Str "Styling",Space,Str "of",Space,Str "the",Space,Code ("",[],[]) "math",Space,Str "element"]
-  ,Para [Str "Tests",Space,Str "whether",Space,Str "basic",Space,Str "CSS",Space,Str "styling",Space,Str "of",Space,Str "MathML",Space,Str "is",Space,Str "supported",Space,Str "on",Space,Str "the",Space,Code ("",[],[]) "math",Space,Str "element."]
-  ,Plain [Math InlineMath "{2x}{+ y - z}"]
-  ,Para [Str "The",Space,Str "test",Space,Str "passes",Space,Str "if",Space,Str "the",Space,Str "equation",Space,Str "has",Space,Str "a",Space,Str "yellow",Space,Str "background",Space,Str "and",Space,Str "a",Space,Str "dashed",Space,Str "border."]
-  ,Para [Str "If",Space,Str "the",Space,Str "reading",Space,Str "system",Space,Str "does",Space,Str "not",Space,Str "have",Space,Str "a",Space,Str "viewport,",Space,Str "or",Space,Str "does",Space,Str "not",Space,Str "support",SoftBreak,Str "CSS",Space,Str "styles,",Space,Str "this",Space,Str "test",Space,Str "should",Space,Str "be",Space,Str "marked",Space,Code ("",[],[]) "Not Supported",Str "."]]
- ,Div ("content-mathml-001.xhtml#mathml-021",["section","otest"],[])
-  [Header 2 ("",[],[]) [Span ("",["nature"],[]) [Str "[OPTIONAL]"],SoftBreak,Span ("",["test-id"],[]) [Str "mathml-021"],Space,Str "CSS",Space,Str "Styling",Space,Str "of",Space,Str "the",Space,Code ("",[],[]) "mo",Space,Str "element"]
-  ,Para [Str "Tests",Space,Str "whether",Space,Str "basic",Space,Str "CSS",Space,Str "styling",Space,Str "of",Space,Str "MathML",Space,Str "is",Space,Str "supported",Space,Str "on",Space,Str "the",Space,Code ("",[],[]) "mo",Space,Str "element."]
-  ,Plain [Math InlineMath "{2x}{+ y - z}"]
-  ,Para [Str "The",Space,Str "test",Space,Str "passes",Space,Str "if",Space,Str "the",Space,Str "operators",Space,Str "are",Space,Str "enlarged",Space,Str "relative",Space,Str "to",Space,Str "the",Space,Str "other",Space,Str "symbols",Space,Str "and",Space,Str "numbers."]
-  ,Para [Str "If",Space,Str "the",Space,Str "reading",Space,Str "system",Space,Str "does",Space,Str "not",Space,Str "have",Space,Str "a",Space,Str "viewport,",Space,Str "or",Space,Str "does",Space,Str "not",Space,Str "support",SoftBreak,Str "CSS",Space,Str "styles,",Space,Str "this",Space,Str "test",Space,Str "should",Space,Str "be",Space,Str "marked",Space,Code ("",[],[]) "Not Supported",Str "."]]
- ,Div ("content-mathml-001.xhtml#mathml-022",["section","otest"],[])
-  [Header 2 ("",[],[]) [Span ("",["nature"],[]) [Str "[OPTIONAL]"],SoftBreak,Span ("",["test-id"],[]) [Str "mathml-022"],Space,Str "CSS",Space,Str "Styling",Space,Str "of",Space,Str "the",Space,Code ("",[],[]) "mi",Space,Str "element"]
-  ,Para [Str "Tests",Space,Str "whether",Space,Str "basic",Space,Str "CSS",Space,Str "styling",Space,Str "of",Space,Str "MathML",Space,Str "is",Space,Str "supported",Space,Str "on",Space,Str "the",Space,Code ("",[],[]) "mi",Space,Str "element."]
-  ,Plain [Math InlineMath "{2x}{+ y - z}"]
-  ,Para [Str "The",Space,Str "test",Space,Str "passes",Space,Str "if",Space,Str "the",Space,Str "identifiers",Space,Str "are",Space,Str "bolded",Space,Str "and",Space,Str "blue."]
-  ,Para [Str "If",Space,Str "the",Space,Str "reading",Space,Str "system",Space,Str "does",Space,Str "not",Space,Str "have",Space,Str "a",Space,Str "viewport,",Space,Str "or",Space,Str "does",Space,Str "not",Space,Str "support",SoftBreak,Str "CSS",Space,Str "styles,",Space,Str "this",Space,Str "test",Space,Str "should",Space,Str "be",Space,Str "marked",Space,Code ("",[],[]) "Not Supported",Str "."]]
- ,Div ("content-mathml-001.xhtml#mathml-023",["section","otest"],[])
-  [Header 2 ("",[],[]) [Span ("",["nature"],[]) [Str "[OPTIONAL]"],SoftBreak,Span ("",["test-id"],[]) [Str "mathml-023"],Space,Str "CSS",Space,Str "Styling",Space,Str "of",Space,Str "the",Space,Code ("",[],[]) "mn",Space,Str "element"]
-  ,Para [Str "Tests",Space,Str "whether",Space,Str "basic",Space,Str "CSS",Space,Str "styling",Space,Str "of",Space,Str "MathML",Space,Str "is",Space,Str "supported",Space,Str "on",Space,Str "the",Space,Code ("",[],[]) "mn",Space,Str "element."]
-  ,Plain [Math InlineMath "{2x}{+ y - z}"]
-  ,Para [Str "The",Space,Str "test",Space,Str "passes",Space,Str "if",Space,Str "the",Space,Str "number",Space,Str "2",Space,Str "is",Space,Str "italicized",Space,Str "and",Space,Str "blue."]
-  ,Para [Str "If",Space,Str "the",Space,Str "reading",Space,Str "system",Space,Str "does",Space,Str "not",Space,Str "have",Space,Str "a",Space,Str "viewport,",Space,Str "or",Space,Str "does",Space,Str "not",Space,Str "support",SoftBreak,Str "CSS",Space,Str "styles,",Space,Str "this",Space,Str "test",Space,Str "should",Space,Str "be",Space,Str "marked",Space,Code ("",[],[]) "Not Supported",Str "."]]
- ,Div ("content-mathml-001.xhtml#mathml-024",["section","ctest"],[])
-  [Header 2 ("",[],[]) [Span ("",["nature"],[]) [Str "[REQUIRED]"],SoftBreak,Span ("",["test-id"],[]) [Str "mathml-024"],Str "Horizontal",Space,Str "stretch,",Space,Code ("",[],[]) "mover",Str ",",Space,Code ("",[],[]) "munder",Str ",",Space,Str "and",Space,Code ("",[],[]) "mspace",Space,Str "elements"]
-  ,Para [Str "Tests",Space,Str "whether",Space,Str "horizontal",Space,Str "stretch,",Space,Code ("",[],[]) "mover",Str ",",Space,Code ("",[],[]) "munder",Str ",",Space,Code ("",[],[]) "mspace",Space,Str "elements",Space,Str "are",Space,Str "supported."]
-  ,Plain [Math DisplayMath "c = \\overset{\\text{complex\\ number}}{\\overbrace{\\underset{\\text{real}}{\\underbrace{\\mspace{20mu} a\\mspace{20mu}}} + \\underset{\\text{imaginary}}{\\underbrace{\\quad b{\\mathbb{i}}\\quad}}}}"]
-  ,Para [Str "The",Space,Str "test",Space,Str "passes",Space,Str "if",Space,Str "the",Space,Str "rendering",Space,Str "looks",Space,Str "like",Space,Str "."]]
- ,Div ("content-mathml-001.xhtml#mathml-025",["section","ctest"],[])
-  [Header 2 ("",[],[]) [Span ("",["nature"],[]) [Str "[REQUIRED]"],SoftBreak,Span ("",["test-id"],[]) [Str "mathml-025"],Str "Testing",Space,Code ("",[],[]) "mtable",Space,Str "with",Space,Code ("",[],[]) "colspan",Space,Str "and",Space,Code ("",[],[]) "rowspan",Space,Str "attributes,",Space,Str "Hebrew",Space,Str "and",Space,Str "Script",Space,Str "fonts"]
-  ,Para [Str "Tests",Space,Str "whether",Space,Code ("",[],[]) "mtable",Space,Str "with",Space,Code ("",[],[]) "colspan",Space,Str "and",Space,Code ("",[],[]) "mspace",Space,Str "attributes",Space,Str "(colum",Space,Str "and",Space,Str "row",Space,Str "spanning)",Space,Str "are",Space,Str "supported;",Space,Str "uses",Space,Str "Hebrew",Space,Str "and",Space,Str "Script",Space,Str "alphabets."]
-  ,Plain [Math DisplayMath "\\begin{matrix}\n & {\\operatorname{cov}\\left( \\mathcal{L} \\right)} & \\longrightarrow & {\\operatorname{non}\\left( \\mathcal{K} \\right)} & \\longrightarrow & {\\operatorname{cof}\\left( \\mathcal{K} \\right)} & \\longrightarrow & {\\operatorname{cof}\\left( \\mathcal{L} \\right)} & \\longrightarrow & 2^{\\aleph_{0}} \\\\\n & \\uparrow & & \\uparrow & & \\uparrow & & \\uparrow & & \\\\\n & {\\mathfrak{b}} & \\longrightarrow & {\\mathfrak{d}} & & & & & & \\\\\n & \\uparrow & & \\uparrow & & & & & & \\\\\n\\aleph_{1} & \\longrightarrow & {\\operatorname{add}\\left( \\mathcal{L} \\right)} & \\longrightarrow & {\\operatorname{add}\\left( \\mathcal{K} \\right)} & \\longrightarrow & {\\operatorname{cov}\\left( \\mathcal{K} \\right)} & \\longrightarrow & {\\operatorname{non}\\left( \\mathcal{L} \\right)} & \\\\\n\\end{matrix}"]
-  ,Para [Str "The",Space,Str "test",Space,Str "passes",Space,Str "if",Space,Str "the",Space,Str "rendering",Space,Str "looks",Space,Str "like",Space,Link ("",[],[]) [Str "Cicho\324's",Space,Str "Diagram"] ("http://en.wikipedia.org/wiki/Cicho%C5%84's_diagram",""),Str ":",Space,Str "."]]
- ,Div ("content-mathml-001.xhtml#mathml-026",["section","ctest"],[])
-  [Header 2 ("",[],[]) [Span ("",["nature"],[]) [Str "[REQUIRED]"],SoftBreak,Span ("",["test-id"],[]) [Str "mathml-026"],Str "BiDi,",Space,Str "RTL",Space,Str "and",Space,Str "Arabic",Space,Str "alphabets"]
-  ,Para [Str "Tests",Space,Str "whether",Space,Str "right-to-left",Space,Str "and",Space,Str "Arabic",Space,Str "alphabets",Space,Str "are",Space,Str "supported."]
-  ,Plain [Math DisplayMath "{d\\left( s \\right)} = \\left\\{ \\begin{matrix}\n{\\sum\\limits_{{\\lbrack?\\rbrack} = 1}^{S}s^{\\lbrack?\\rbrack}} & {\\text{\1573\1584\1575\1603\1575\1606}s > 0} \\\\\n{\\int_{1}^{S}{s^{\\lbrack?\\rbrack}s}} & {\\text{\1573\1584\1575\1603\1575\1606}s \\in m} \\\\\n{T\\pi} & {\\text{\1594\1610\1585\1584\1604\1603}\\left( \\text{\1605\1593}\\pi \\simeq 3,141 \\right)} \\\\\n\\end{matrix} \\right."]
-  ,Para [Str "The",Space,Str "test",Space,Str "passes",Space,Str "if",Space,Str "the",Space,Str "rendering",Space,Str "looks",Space,Str "like",Space,Str "the",Space,Str "following",Space,Str "image:"]]
- ,Div ("content-mathml-001.xhtml#mathml-027",["section","ctest"],[])
-  [Header 2 ("",[],[]) [Span ("",["nature"],[]) [Str "[REQUIRED]"],SoftBreak,Span ("",["test-id"],[]) [Str "mathml-027"],Str "Elementary",Space,Str "math:",Space,Str "long",Space,Str "division",Space,Str "notation"]
-  ,Para [Str "Tests",Space,Str "whether",Space,Code ("",[],[]) "mlongdiv",Space,Str "elements",Space,Str "(from",Space,Str "elementary",Space,Str "math)",Space,Str "are",Space,Str "supported."]
-  ,Plain [Span ("",["math"],[("xmlns","http://www.w3.org/1998/Math/MathML")]) [SoftBreak,Str "3",SoftBreak,Str "435.3",SoftBreak,Str "1306",SoftBreak,Str "12",SoftBreak,Str "10",SoftBreak,Str "9",SoftBreak,Str "16",SoftBreak,Str "15",SoftBreak,Str "1.0",SoftBreak,Str "9",SoftBreak,Str "1",SoftBreak]]
-  ,Para [Str "The",Space,Str "test",Space,Str "passes",Space,Str "if",Space,Str "the",Space,Str "rendering",Space,Str "looks",Space,Str "like",Space,Str "the",Space,Str "following",Space,Str "image:",Space,Str "."]]]
-,Para [Span ("content-switch-001.xhtml",[],[]) []]
-,Div ("content-switch-001.xhtml#epub-switch",["section"],[])
- [Header 3 ("",[],[]) [Code ("",[],[]) "epub:switch"]
- ,Div ("content-switch-001.xhtml#switch-010",["section","ctest"],[])
-  [Header 4 ("",[],[]) [Span ("",["nature"],[]) [Str "[REQUIRED]"],Space,Span ("",["test-id"],[]) [Str "switch-010"],Space,Str "Support"]
-  ,Para [Str "Tests",Space,Str "whether",Space,Str "the",Space,Code ("",[],[]) "epub:switch",Space,Str "element",Space,Str "is",Space,Str "supported."]
-  ,Para [Str "PASS"]
-  ,Para [Str "If",Space,Str "only",Space,Str "the",Space,Str "word",Space,Str "\"PASS\"",Space,Str "is",Space,Str "rendered",Space,Str "before",Space,Str "this",Space,Str "paragraph,",Space,Str "the",Space,Str "test",Space,Str "passes.",Space,Str "If",Space,Str "both",Space,Str "\"PASS\"",Space,Str "and",Space,Str "\"FAIL\"",Space,Str "are",Space,Str "rendered,",Space,Str "or",Space,Str "neither",SoftBreak,Str "\"PASS\"",Space,Str "nor",Space,Str "\"FAIL\"",Space,Str "is",Space,Str "rendered,",Space,Str "the",Space,Str "test",Space,Str "fails."]]
- ,Div ("content-switch-001.xhtml#switch-020",["section","otest"],[])
-  [Header 4 ("",[],[]) [Span ("",["nature"],[]) [Str "[OPTIONAL]"],SoftBreak,Span ("",["test-id"],[]) [Str "switch-020"],SoftBreak,Str "MathML",Space,Str "Embedding"]
-  ,Para [Str "Tests",Space,Str "whether",Space,Str "the",Space,Str "MathML",Space,Str "namespace",Space,Str "is",Space,Str "recognized",Space,Str "when",Space,Str "used",Space,Str "in",Space,Str "an",Space,Code ("",[],[]) "epub:case",Space,Str "element."]
-  ,Para [Math InlineMath "{2x}{+ y - z}"]
-  ,Para [Str "If",Space,Str "a",Space,Str "MathML",Space,Str "equation",Space,Str "is",Space,Str "rendered",Space,Str "before",Space,Str "this",Space,Str "paragraph,",Space,Str "the",Space,Str "test",Space,Str "passes."]
-  ,Para [Str "If",Space,Str "test",Space,Code ("",[],[]) "switch-010",Space,Str "did",Space,Str "not",Space,Str "pass,",Space,Str "this",Space,Str "test",Space,Str "should",Space,Str "be",Space,Str "marked",Space,Code ("",[],[]) "Not Supported",Str "."]]]]
+Pandoc
+  Meta
+    { unMeta =
+        fromList
+          [ ( "author"
+            , MetaList
+                [ MetaInlines [ Str "Ori Idan" ]
+                , MetaInlines [ Str "Matt Garrish" ]
+                , MetaInlines [ Str "Marisa DeMeglio" ]
+                , MetaInlines [ Str "Toshiaki Koike" ]
+                , MetaInlines [ Str "Vincent Gros" ]
+                , MetaInlines [ Str "Markus Gylling" ]
+                ]
+            )
+          , ( "description"
+            , MetaInlines
+                [ Str
+                    "Tests for Content Documents in a reflowable context [UNDER CONSTRUCTION]"
+                ]
+            )
+          , ( "identifier"
+            , MetaInlines
+                [ Str "com.github.epub-testsuite.epub30-test-0100" ]
+            )
+          , ( "language"
+            , MetaList
+                [ MetaInlines [ Str "jp" ] , MetaInlines [ Str "en" ] ]
+            )
+          , ( "title"
+            , MetaInlines
+                [ Str "EPUBTEST 0100 - Reflowable Content Tests" ]
+            )
+          ]
+    }
+  [ Para [ Span ( "front.xhtml" , [] , [] ) [] ]
+  , Div
+      ( "" , [ "section" ] , [] )
+      [ Header
+          1
+          ( "" , [] , [] )
+          [ Str "Reflowable"
+          , Space
+          , Str "EPUB"
+          , Space
+          , Str "3"
+          , Space
+          , Str "Conformance"
+          , Space
+          , Str "Test"
+          , Space
+          , Str "Document:"
+          , Space
+          , Str "0100"
+          ]
+      , Div
+          ( "" , [ "section" ] , [] )
+          [ Header
+              2
+              ( "" , [] , [] )
+              [ Str "Status"
+              , Space
+              , Str "of"
+              , Space
+              , Str "this"
+              , Space
+              , Str "Document"
+              ]
+          , Para
+              [ Str "This"
+              , Space
+              , Str "publication"
+              , Space
+              , Str "is"
+              , Space
+              , Str "currently"
+              , Space
+              , Str "considered"
+              , Space
+              , Span
+                  ( "" , [ "status" ] , [] )
+                  [ Str "[UNDER" , Space , Str "DEVELOPMENT]" ]
+              , Space
+              , Str "by"
+              , Space
+              , Str "the"
+              , Space
+              , Str "IDPF."
+              ]
+          , Para
+              [ Str "This"
+              , Space
+              , Str "publication"
+              , Space
+              , Str "is"
+              , Space
+              , Str "part"
+              , Space
+              , Str "of"
+              , Space
+              , Str "version"
+              , Space
+              , Span ( "" , [ "version" ] , [] ) [ Str "X.X" ]
+              , Space
+              , Str "of"
+              , Space
+              , Str "the"
+              , Space
+              , Str "EPUB"
+              , Space
+              , Str "3.0"
+              , Space
+              , Str "Compliance"
+              , Space
+              , Str "Test"
+              , Space
+              , Str "Suite"
+              , Space
+              , Str "released"
+              , SoftBreak
+              , Str "on"
+              , Space
+              , RawInline (Format "html") "<time class=\"release\">"
+              , Str "TBD"
+              , RawInline (Format "html") "</time>"
+              , Str "."
+              ]
+          , Para
+              [ Str "Before"
+              , Space
+              , Str "using"
+              , Space
+              , Str "this"
+              , Space
+              , Str "publication"
+              , Space
+              , Str "to"
+              , Space
+              , Str "evaluate"
+              , Space
+              , Str "reading"
+              , Space
+              , Str "systems,"
+              , Space
+              , Str "testers"
+              , Space
+              , Str "are"
+              , Space
+              , Str "strongly"
+              , Space
+              , Str "encouraged"
+              , Space
+              , Str "to"
+              , SoftBreak
+              , Str "verify"
+              , Space
+              , Str "that"
+              , Space
+              , Str "they"
+              , Space
+              , Str "have"
+              , Space
+              , Str "the"
+              , Space
+              , Str "latest"
+              , Space
+              , Str "release"
+              , Space
+              , Str "by"
+              , Space
+              , Str "checking"
+              , Space
+              , Str "the"
+              , Space
+              , Str "current"
+              , Space
+              , Str "release"
+              , Space
+              , Str "version"
+              , Space
+              , Str "and"
+              , Space
+              , Str "date"
+              , Space
+              , Str "of"
+              , SoftBreak
+              , Str "the"
+              , Space
+              , Str "test"
+              , Space
+              , Str "suite"
+              , Space
+              , Str "at"
+              , Space
+              , Link
+                  ( "" , [] , [] )
+                  [ Str "TBD" ]
+                  ( "http://idpf.org/" , "" )
+              ]
+          , Para
+              [ Str "This"
+              , Space
+              , Str "publication"
+              , Space
+              , Str "is"
+              , Space
+              , Str "one"
+              , Space
+              , Str "of"
+              , Space
+              , Str "several"
+              , Space
+              , Str "that"
+              , Space
+              , Str "currently"
+              , Space
+              , Str "comprise"
+              , Space
+              , Str "the"
+              , Space
+              , Str "EPUB"
+              , Space
+              , Str "3"
+              , Space
+              , Str "conformance"
+              , Space
+              , Str "test"
+              , Space
+              , Str "suite"
+              , SoftBreak
+              , Str "for"
+              , Space
+              , Str "reflowable"
+              , Space
+              , Str "content."
+              , Space
+              , Str "The"
+              , Space
+              , Str "complete"
+              , Space
+              , Str "test"
+              , Space
+              , Str "suite"
+              , Space
+              , Str "includes"
+              , Space
+              , Str "all"
+              , Space
+              , Str "of"
+              , Space
+              , Str "the"
+              , Space
+              , Str "following"
+              , Space
+              , Str "publications:"
+              ]
+          , OrderedList
+              ( 1 , DefaultStyle , DefaultDelim )
+              [ [ Plain [ Str "." ] ] ]
+          ]
+      , Div
+          ( "" , [ "section" ] , [] )
+          [ Header
+              2
+              ( "" , [] , [] )
+              [ Str "About"
+              , Space
+              , Str "this"
+              , Space
+              , Str "Document"
+              ]
+          , Para
+              [ Str "This"
+              , Space
+              , Str "document"
+              , Space
+              , Str "focuses"
+              , Space
+              , Str "on"
+              , Space
+              , Str "human-evaluated"
+              , Space
+              , Str "binary"
+              , Space
+              , Str "(pass/fail)"
+              , Space
+              , Str "tests"
+              , Space
+              , Str "in"
+              , Space
+              , Str "a"
+              , SoftBreak
+              , Str "reflowable"
+              , Space
+              , Str "context."
+              , Space
+              , Str "Tests"
+              , Space
+              , Str "for"
+              , Space
+              , Str "fixed-layout"
+              , Space
+              , Str "content"
+              , Space
+              , Str "and"
+              , Space
+              , Str "other"
+              , Space
+              , Str "individual"
+              , Space
+              , Str "tests"
+              , Space
+              , Str "that"
+              , SoftBreak
+              , Str "require"
+              , Space
+              , Str "a"
+              , Space
+              , Str "dedicated"
+              , Space
+              , Str "epub"
+              , Space
+              , Str "file"
+              , Space
+              , Str "are"
+              , Space
+              , Str "available"
+              , Space
+              , Str "in"
+              , Space
+              , Str "additional"
+              , Space
+              , Str "sibling"
+              , Space
+              , Str "documents;"
+              , Space
+              , Str "refer"
+              , Space
+              , Str "to"
+              , SoftBreak
+              , Str "the"
+              , Space
+              , Link
+                  ( "" , [] , [] )
+                  [ Str "test"
+                  , Space
+                  , Str "suite"
+                  , SoftBreak
+                  , Str "wiki"
+                  ]
+                  ( "https://github.com/mgylling/epub-testsuite/wiki/Overview"
+                  , ""
+                  )
+              , Space
+              , Str "("
+              , Code
+                  ( "" , [] , [] )
+                  "https://github.com/mgylling/epub-testsuite/wiki/Overview"
+              , Str ")"
+              , Space
+              , Str "for"
+              , Space
+              , Str "additional"
+              , SoftBreak
+              , Str "information."
+              ]
+          ]
+      , Div
+          ( "" , [ "section" ] , [] )
+          [ Header 2 ( "" , [] , [] ) [ Str "Conventions" ]
+          , Para
+              [ Str "The"
+              , Space
+              , Str "following"
+              , Space
+              , Str "conventions"
+              , Space
+              , Str "are"
+              , Space
+              , Str "used"
+              , Space
+              , Str "throughout"
+              , Space
+              , Str "the"
+              , Space
+              , Str "document:"
+              ]
+          , DefinitionList
+              [ ( [ Str "1."
+                  , Space
+                  , Str "Locating"
+                  , Space
+                  , Str "a"
+                  , Space
+                  , Str "test"
+                  ]
+                , [ [ Div
+                        ( "" , [ "ctest" ] , [] )
+                        [ Para
+                            [ Str "Tests"
+                            , Space
+                            , Str "for"
+                            , Space
+                            , Emph [ Str "required" ]
+                            , Space
+                            , Str "Reading"
+                            , Space
+                            , Str "System"
+                            , Space
+                            , Str "functionality"
+                            , Space
+                            , Str "are"
+                            , SoftBreak
+                            , Str "preceded"
+                            , Space
+                            , Str "by"
+                            , Space
+                            , Str "the"
+                            , Space
+                            , Str "label:"
+                            , Space
+                            , Span
+                                ( ""
+                                , [ "nature" ]
+                                , [ ( "style"
+                                    , "display: inline; font-size: 100%"
+                                    )
+                                  ]
+                                )
+                                [ Str "[REQUIRED]" ]
+                            ]
+                        ]
+                    , Div
+                        ( "" , [ "otest" ] , [] )
+                        [ Para
+                            [ Str "Tests"
+                            , Space
+                            , Str "for"
+                            , Space
+                            , Emph [ Str "optional" ]
+                            , Space
+                            , Str "Reading"
+                            , Space
+                            , Str "System"
+                            , Space
+                            , Str "functionality"
+                            , Space
+                            , Str "are"
+                            , SoftBreak
+                            , Str "preceded"
+                            , Space
+                            , Str "by"
+                            , Space
+                            , Str "the"
+                            , Space
+                            , Str "label:"
+                            , Space
+                            , Span
+                                ( ""
+                                , [ "nature" ]
+                                , [ ( "style"
+                                    , "display: inline; font-size: 100%"
+                                    )
+                                  ]
+                                )
+                                [ Str "[OPTIONAL]" ]
+                            ]
+                        ]
+                    ]
+                  ]
+                )
+              , ( [ Str "2."
+                  , Space
+                  , Str "Performing"
+                  , Space
+                  , Str "the"
+                  , Space
+                  , Str "test"
+                  ]
+                , [ [ Plain
+                        [ Str "Each"
+                        , Space
+                        , Str "test"
+                        , Space
+                        , Str "includes"
+                        , Space
+                        , Str "a"
+                        , Space
+                        , Str "description"
+                        , Space
+                        , Str "of"
+                        , Space
+                        , Str "its"
+                        , Space
+                        , Str "purpose"
+                        , Space
+                        , Str "followed"
+                        , Space
+                        , Str "by"
+                        , Space
+                        , Str "the"
+                        , Space
+                        , Str "actual"
+                        , Space
+                        , Strong
+                            [ Str "test"
+                            , Space
+                            , Str "statement,"
+                            , SoftBreak
+                            , Str "which"
+                            , Space
+                            , Str "can"
+                            , Space
+                            , Str "always"
+                            , Space
+                            , Str "be"
+                            , Space
+                            , Str "evaluated"
+                            , Space
+                            , Str "to"
+                            , Space
+                            , Str "true"
+                            , Space
+                            , Str "or"
+                            , Space
+                            , Str "false"
+                            ]
+                        , Str "."
+                        , Space
+                        , Str "These"
+                        , Space
+                        , Str "statements"
+                        , Space
+                        , Str "typically"
+                        , Space
+                        , Str "have"
+                        , Space
+                        , Str "the"
+                        , Space
+                        , Str "form:"
+                        , SoftBreak
+                        , Str "\"If"
+                        , Space
+                        , Str "[some"
+                        , Space
+                        , Str "condition],"
+                        , Space
+                        , Str "the"
+                        , Space
+                        , Str "test"
+                        , Space
+                        , Str "passes\"."
+                        ]
+                    ]
+                  ]
+                )
+              , ( [ Str "3."
+                  , Space
+                  , Str "Scoring"
+                  , Space
+                  , Str "in"
+                  , Space
+                  , Str "the"
+                  , Space
+                  , Str "results"
+                  , Space
+                  , Str "form"
+                  ]
+                , [ [ Plain
+                        [ Str "@@@TODO"
+                        , Space
+                        , Str "provide"
+                        , Space
+                        , Str "info"
+                        , Space
+                        , Str "on"
+                        , Space
+                        , Str "where"
+                        , Space
+                        , Str "to"
+                        , Space
+                        , Str "get"
+                        , Space
+                        , Str "the"
+                        , Space
+                        , Str "results"
+                        , Space
+                        , Str "form"
+                        ]
+                    ]
+                  ]
+                )
+              ]
+          ]
+      ]
+  , Para [ Span ( "content-mathml-001.xhtml" , [] , [] ) [] ]
+  , Div
+      ( "" , [ "section" ] , [] )
+      [ Header
+          2
+          ( "content-mathml-001.xhtml_mathml" , [] , [] )
+          [ Str "MathML" ]
+      , Div
+          ( "content-mathml-001.xhtml_mathml-010"
+          , [ "section" , "ctest" ]
+          , []
+          )
+          [ Header
+              2
+              ( "" , [] , [] )
+              [ Span ( "" , [ "nature" ] , [] ) [ Str "[REQUIRED]" ]
+              , SoftBreak
+              , Span ( "" , [ "test-id" ] , [] ) [ Str "mathml-010" ]
+              , Space
+              , Str "Rendering"
+              ]
+          , Para
+              [ Str "Tests"
+              , Space
+              , Str "whether"
+              , Space
+              , Str "MathML"
+              , Space
+              , Str "equation"
+              , Space
+              , Str "rendering"
+              , Space
+              , Str "is"
+              , Space
+              , Str "supported."
+              ]
+          , Plain
+              [ Math
+                  DisplayMath
+                  "\\int_{- \\infty}^{\\infty}e^{- x^{2}}\\, dx = \\sqrt{\\pi}"
+              , SoftBreak
+              , Math
+                  DisplayMath
+                  "\\sum\\limits_{n = 1}^{\\infty}\\frac{1}{n^{2}} = \\frac{\\pi^{2}}{6}"
+              , SoftBreak
+              , Math
+                  DisplayMath
+                  "x = \\frac{- b \\pm \\sqrt{b^{2} - 4ac}}{2a}"
+              ]
+          , Para
+              [ Str "If"
+              , Space
+              , Str "the"
+              , Space
+              , Str "preceding"
+              , Space
+              , Str "equations"
+              , Space
+              , Str "are"
+              , Space
+              , Str "not"
+              , Space
+              , Str "presented"
+              , Space
+              , Str "as"
+              , Space
+              , Str "linear"
+              , Space
+              , Str "text"
+              , Space
+              , Str "(e.g.,"
+              , Space
+              , Str "x=-b\177b2-4ac2a),"
+              , SoftBreak
+              , Str "the"
+              , Space
+              , Str "test"
+              , Space
+              , Str "passes."
+              ]
+          ]
+      , Div
+          ( "content-mathml-001.xhtml_mathml-020"
+          , [ "section" , "otest" ]
+          , []
+          )
+          [ Header
+              2
+              ( "" , [] , [] )
+              [ Span ( "" , [ "nature" ] , [] ) [ Str "[OPTIONAL]" ]
+              , SoftBreak
+              , Span ( "" , [ "test-id" ] , [] ) [ Str "mathml-020" ]
+              , Space
+              , Str "CSS"
+              , Space
+              , Str "Styling"
+              , Space
+              , Str "of"
+              , Space
+              , Str "the"
+              , Space
+              , Code ( "" , [] , [] ) "math"
+              , Space
+              , Str "element"
+              ]
+          , Para
+              [ Str "Tests"
+              , Space
+              , Str "whether"
+              , Space
+              , Str "basic"
+              , Space
+              , Str "CSS"
+              , Space
+              , Str "styling"
+              , Space
+              , Str "of"
+              , Space
+              , Str "MathML"
+              , Space
+              , Str "is"
+              , Space
+              , Str "supported"
+              , Space
+              , Str "on"
+              , Space
+              , Str "the"
+              , Space
+              , Code ( "" , [] , [] ) "math"
+              , Space
+              , Str "element."
+              ]
+          , Plain [ Math InlineMath "{2x}{+ y - z}" ]
+          , Para
+              [ Str "The"
+              , Space
+              , Str "test"
+              , Space
+              , Str "passes"
+              , Space
+              , Str "if"
+              , Space
+              , Str "the"
+              , Space
+              , Str "equation"
+              , Space
+              , Str "has"
+              , Space
+              , Str "a"
+              , Space
+              , Str "yellow"
+              , Space
+              , Str "background"
+              , Space
+              , Str "and"
+              , Space
+              , Str "a"
+              , Space
+              , Str "dashed"
+              , Space
+              , Str "border."
+              ]
+          , Para
+              [ Str "If"
+              , Space
+              , Str "the"
+              , Space
+              , Str "reading"
+              , Space
+              , Str "system"
+              , Space
+              , Str "does"
+              , Space
+              , Str "not"
+              , Space
+              , Str "have"
+              , Space
+              , Str "a"
+              , Space
+              , Str "viewport,"
+              , Space
+              , Str "or"
+              , Space
+              , Str "does"
+              , Space
+              , Str "not"
+              , Space
+              , Str "support"
+              , SoftBreak
+              , Str "CSS"
+              , Space
+              , Str "styles,"
+              , Space
+              , Str "this"
+              , Space
+              , Str "test"
+              , Space
+              , Str "should"
+              , Space
+              , Str "be"
+              , Space
+              , Str "marked"
+              , Space
+              , Code ( "" , [] , [] ) "Not Supported"
+              , Str "."
+              ]
+          ]
+      , Div
+          ( "content-mathml-001.xhtml_mathml-021"
+          , [ "section" , "otest" ]
+          , []
+          )
+          [ Header
+              2
+              ( "" , [] , [] )
+              [ Span ( "" , [ "nature" ] , [] ) [ Str "[OPTIONAL]" ]
+              , SoftBreak
+              , Span ( "" , [ "test-id" ] , [] ) [ Str "mathml-021" ]
+              , Space
+              , Str "CSS"
+              , Space
+              , Str "Styling"
+              , Space
+              , Str "of"
+              , Space
+              , Str "the"
+              , Space
+              , Code ( "" , [] , [] ) "mo"
+              , Space
+              , Str "element"
+              ]
+          , Para
+              [ Str "Tests"
+              , Space
+              , Str "whether"
+              , Space
+              , Str "basic"
+              , Space
+              , Str "CSS"
+              , Space
+              , Str "styling"
+              , Space
+              , Str "of"
+              , Space
+              , Str "MathML"
+              , Space
+              , Str "is"
+              , Space
+              , Str "supported"
+              , Space
+              , Str "on"
+              , Space
+              , Str "the"
+              , Space
+              , Code ( "" , [] , [] ) "mo"
+              , Space
+              , Str "element."
+              ]
+          , Plain [ Math InlineMath "{2x}{+ y - z}" ]
+          , Para
+              [ Str "The"
+              , Space
+              , Str "test"
+              , Space
+              , Str "passes"
+              , Space
+              , Str "if"
+              , Space
+              , Str "the"
+              , Space
+              , Str "operators"
+              , Space
+              , Str "are"
+              , Space
+              , Str "enlarged"
+              , Space
+              , Str "relative"
+              , Space
+              , Str "to"
+              , Space
+              , Str "the"
+              , Space
+              , Str "other"
+              , Space
+              , Str "symbols"
+              , Space
+              , Str "and"
+              , Space
+              , Str "numbers."
+              ]
+          , Para
+              [ Str "If"
+              , Space
+              , Str "the"
+              , Space
+              , Str "reading"
+              , Space
+              , Str "system"
+              , Space
+              , Str "does"
+              , Space
+              , Str "not"
+              , Space
+              , Str "have"
+              , Space
+              , Str "a"
+              , Space
+              , Str "viewport,"
+              , Space
+              , Str "or"
+              , Space
+              , Str "does"
+              , Space
+              , Str "not"
+              , Space
+              , Str "support"
+              , SoftBreak
+              , Str "CSS"
+              , Space
+              , Str "styles,"
+              , Space
+              , Str "this"
+              , Space
+              , Str "test"
+              , Space
+              , Str "should"
+              , Space
+              , Str "be"
+              , Space
+              , Str "marked"
+              , Space
+              , Code ( "" , [] , [] ) "Not Supported"
+              , Str "."
+              ]
+          ]
+      , Div
+          ( "content-mathml-001.xhtml_mathml-022"
+          , [ "section" , "otest" ]
+          , []
+          )
+          [ Header
+              2
+              ( "" , [] , [] )
+              [ Span ( "" , [ "nature" ] , [] ) [ Str "[OPTIONAL]" ]
+              , SoftBreak
+              , Span ( "" , [ "test-id" ] , [] ) [ Str "mathml-022" ]
+              , Space
+              , Str "CSS"
+              , Space
+              , Str "Styling"
+              , Space
+              , Str "of"
+              , Space
+              , Str "the"
+              , Space
+              , Code ( "" , [] , [] ) "mi"
+              , Space
+              , Str "element"
+              ]
+          , Para
+              [ Str "Tests"
+              , Space
+              , Str "whether"
+              , Space
+              , Str "basic"
+              , Space
+              , Str "CSS"
+              , Space
+              , Str "styling"
+              , Space
+              , Str "of"
+              , Space
+              , Str "MathML"
+              , Space
+              , Str "is"
+              , Space
+              , Str "supported"
+              , Space
+              , Str "on"
+              , Space
+              , Str "the"
+              , Space
+              , Code ( "" , [] , [] ) "mi"
+              , Space
+              , Str "element."
+              ]
+          , Plain [ Math InlineMath "{2x}{+ y - z}" ]
+          , Para
+              [ Str "The"
+              , Space
+              , Str "test"
+              , Space
+              , Str "passes"
+              , Space
+              , Str "if"
+              , Space
+              , Str "the"
+              , Space
+              , Str "identifiers"
+              , Space
+              , Str "are"
+              , Space
+              , Str "bolded"
+              , Space
+              , Str "and"
+              , Space
+              , Str "blue."
+              ]
+          , Para
+              [ Str "If"
+              , Space
+              , Str "the"
+              , Space
+              , Str "reading"
+              , Space
+              , Str "system"
+              , Space
+              , Str "does"
+              , Space
+              , Str "not"
+              , Space
+              , Str "have"
+              , Space
+              , Str "a"
+              , Space
+              , Str "viewport,"
+              , Space
+              , Str "or"
+              , Space
+              , Str "does"
+              , Space
+              , Str "not"
+              , Space
+              , Str "support"
+              , SoftBreak
+              , Str "CSS"
+              , Space
+              , Str "styles,"
+              , Space
+              , Str "this"
+              , Space
+              , Str "test"
+              , Space
+              , Str "should"
+              , Space
+              , Str "be"
+              , Space
+              , Str "marked"
+              , Space
+              , Code ( "" , [] , [] ) "Not Supported"
+              , Str "."
+              ]
+          ]
+      , Div
+          ( "content-mathml-001.xhtml_mathml-023"
+          , [ "section" , "otest" ]
+          , []
+          )
+          [ Header
+              2
+              ( "" , [] , [] )
+              [ Span ( "" , [ "nature" ] , [] ) [ Str "[OPTIONAL]" ]
+              , SoftBreak
+              , Span ( "" , [ "test-id" ] , [] ) [ Str "mathml-023" ]
+              , Space
+              , Str "CSS"
+              , Space
+              , Str "Styling"
+              , Space
+              , Str "of"
+              , Space
+              , Str "the"
+              , Space
+              , Code ( "" , [] , [] ) "mn"
+              , Space
+              , Str "element"
+              ]
+          , Para
+              [ Str "Tests"
+              , Space
+              , Str "whether"
+              , Space
+              , Str "basic"
+              , Space
+              , Str "CSS"
+              , Space
+              , Str "styling"
+              , Space
+              , Str "of"
+              , Space
+              , Str "MathML"
+              , Space
+              , Str "is"
+              , Space
+              , Str "supported"
+              , Space
+              , Str "on"
+              , Space
+              , Str "the"
+              , Space
+              , Code ( "" , [] , [] ) "mn"
+              , Space
+              , Str "element."
+              ]
+          , Plain [ Math InlineMath "{2x}{+ y - z}" ]
+          , Para
+              [ Str "The"
+              , Space
+              , Str "test"
+              , Space
+              , Str "passes"
+              , Space
+              , Str "if"
+              , Space
+              , Str "the"
+              , Space
+              , Str "number"
+              , Space
+              , Str "2"
+              , Space
+              , Str "is"
+              , Space
+              , Str "italicized"
+              , Space
+              , Str "and"
+              , Space
+              , Str "blue."
+              ]
+          , Para
+              [ Str "If"
+              , Space
+              , Str "the"
+              , Space
+              , Str "reading"
+              , Space
+              , Str "system"
+              , Space
+              , Str "does"
+              , Space
+              , Str "not"
+              , Space
+              , Str "have"
+              , Space
+              , Str "a"
+              , Space
+              , Str "viewport,"
+              , Space
+              , Str "or"
+              , Space
+              , Str "does"
+              , Space
+              , Str "not"
+              , Space
+              , Str "support"
+              , SoftBreak
+              , Str "CSS"
+              , Space
+              , Str "styles,"
+              , Space
+              , Str "this"
+              , Space
+              , Str "test"
+              , Space
+              , Str "should"
+              , Space
+              , Str "be"
+              , Space
+              , Str "marked"
+              , Space
+              , Code ( "" , [] , [] ) "Not Supported"
+              , Str "."
+              ]
+          ]
+      , Div
+          ( "content-mathml-001.xhtml_mathml-024"
+          , [ "section" , "ctest" ]
+          , []
+          )
+          [ Header
+              2
+              ( "" , [] , [] )
+              [ Span ( "" , [ "nature" ] , [] ) [ Str "[REQUIRED]" ]
+              , SoftBreak
+              , Span ( "" , [ "test-id" ] , [] ) [ Str "mathml-024" ]
+              , Str "Horizontal"
+              , Space
+              , Str "stretch,"
+              , Space
+              , Code ( "" , [] , [] ) "mover"
+              , Str ","
+              , Space
+              , Code ( "" , [] , [] ) "munder"
+              , Str ","
+              , Space
+              , Str "and"
+              , Space
+              , Code ( "" , [] , [] ) "mspace"
+              , Space
+              , Str "elements"
+              ]
+          , Para
+              [ Str "Tests"
+              , Space
+              , Str "whether"
+              , Space
+              , Str "horizontal"
+              , Space
+              , Str "stretch,"
+              , Space
+              , Code ( "" , [] , [] ) "mover"
+              , Str ","
+              , Space
+              , Code ( "" , [] , [] ) "munder"
+              , Str ","
+              , Space
+              , Code ( "" , [] , [] ) "mspace"
+              , Space
+              , Str "elements"
+              , Space
+              , Str "are"
+              , Space
+              , Str "supported."
+              ]
+          , Plain
+              [ Math
+                  DisplayMath
+                  "c = \\overset{\\text{complex number}}{\\overbrace{\\underset{\\text{real}}{\\underbrace{\\mspace{20mu} a\\mspace{20mu}}} + \\underset{\\text{imaginary}}{\\underbrace{\\quad b{\\mathbb{i}}\\quad}}}}"
+              ]
+          , Para
+              [ Str "The"
+              , Space
+              , Str "test"
+              , Space
+              , Str "passes"
+              , Space
+              , Str "if"
+              , Space
+              , Str "the"
+              , Space
+              , Str "rendering"
+              , Space
+              , Str "looks"
+              , Space
+              , Str "like"
+              , Space
+              , Str "."
+              ]
+          ]
+      , Div
+          ( "content-mathml-001.xhtml_mathml-025"
+          , [ "section" , "ctest" ]
+          , []
+          )
+          [ Header
+              2
+              ( "" , [] , [] )
+              [ Span ( "" , [ "nature" ] , [] ) [ Str "[REQUIRED]" ]
+              , SoftBreak
+              , Span ( "" , [ "test-id" ] , [] ) [ Str "mathml-025" ]
+              , Str "Testing"
+              , Space
+              , Code ( "" , [] , [] ) "mtable"
+              , Space
+              , Str "with"
+              , Space
+              , Code ( "" , [] , [] ) "colspan"
+              , Space
+              , Str "and"
+              , Space
+              , Code ( "" , [] , [] ) "rowspan"
+              , Space
+              , Str "attributes,"
+              , Space
+              , Str "Hebrew"
+              , Space
+              , Str "and"
+              , Space
+              , Str "Script"
+              , Space
+              , Str "fonts"
+              ]
+          , Para
+              [ Str "Tests"
+              , Space
+              , Str "whether"
+              , Space
+              , Code ( "" , [] , [] ) "mtable"
+              , Space
+              , Str "with"
+              , Space
+              , Code ( "" , [] , [] ) "colspan"
+              , Space
+              , Str "and"
+              , Space
+              , Code ( "" , [] , [] ) "mspace"
+              , Space
+              , Str "attributes"
+              , Space
+              , Str "(column"
+              , Space
+              , Str "and"
+              , Space
+              , Str "row"
+              , Space
+              , Str "spanning)"
+              , Space
+              , Str "are"
+              , Space
+              , Str "supported;"
+              , Space
+              , Str "uses"
+              , Space
+              , Str "Hebrew"
+              , Space
+              , Str "and"
+              , Space
+              , Str "Script"
+              , Space
+              , Str "alphabets."
+              ]
+          , Plain
+              [ Math
+                  DisplayMath
+                  "\\begin{matrix}\n & {\\operatorname{cov}(\\mathcal{L})} & \\longrightarrow & {\\operatorname{non}(\\mathcal{K})} & \\longrightarrow & {\\operatorname{cof}(\\mathcal{K})} & \\longrightarrow & {\\operatorname{cof}(\\mathcal{L})} & \\longrightarrow & 2^{\\aleph_{0}} \\\\\n & \\uparrow & & \\uparrow & & \\uparrow & & \\uparrow & & \\\\\n & {\\mathfrak{b}} & \\longrightarrow & {\\mathfrak{d}} & & & & & & \\\\\n & \\uparrow & & \\uparrow & & & & & & \\\\\n\\aleph_{1} & \\longrightarrow & {\\operatorname{add}(\\mathcal{L})} & \\longrightarrow & {\\operatorname{add}(\\mathcal{K})} & \\longrightarrow & {\\operatorname{cov}(\\mathcal{K})} & \\longrightarrow & {\\operatorname{non}(\\mathcal{L})} & \n\\end{matrix}"
+              ]
+          , Para
+              [ Str "The"
+              , Space
+              , Str "test"
+              , Space
+              , Str "passes"
+              , Space
+              , Str "if"
+              , Space
+              , Str "the"
+              , Space
+              , Str "rendering"
+              , Space
+              , Str "looks"
+              , Space
+              , Str "like"
+              , Space
+              , Link
+                  ( "" , [] , [] )
+                  [ Str "Cicho\324's" , Space , Str "Diagram" ]
+                  ( "http://en.wikipedia.org/wiki/Cicho%C5%84's_diagram"
+                  , ""
+                  )
+              , Str ":"
+              , Space
+              , Str "."
+              ]
+          ]
+      , Div
+          ( "content-mathml-001.xhtml_mathml-026"
+          , [ "section" , "ctest" ]
+          , []
+          )
+          [ Header
+              2
+              ( "" , [] , [] )
+              [ Span ( "" , [ "nature" ] , [] ) [ Str "[REQUIRED]" ]
+              , SoftBreak
+              , Span ( "" , [ "test-id" ] , [] ) [ Str "mathml-026" ]
+              , Str "BiDi,"
+              , Space
+              , Str "RTL"
+              , Space
+              , Str "and"
+              , Space
+              , Str "Arabic"
+              , Space
+              , Str "alphabets"
+              ]
+          , Para
+              [ Str "Tests"
+              , Space
+              , Str "whether"
+              , Space
+              , Str "right-to-left"
+              , Space
+              , Str "and"
+              , Space
+              , Str "Arabic"
+              , Space
+              , Str "alphabets"
+              , Space
+              , Str "are"
+              , Space
+              , Str "supported."
+              ]
+          , Plain
+              [ Math
+                  DisplayMath
+                  "{\1583(\1587)} = \\left\\{ \\begin{matrix}\n{\\sum\\limits_{\1646 = 1}^{\1589}\1587^{\1646}} & {\\text{\1573\1584\1575\1603\1575\1606}\1587 > 0} \\\\\n{\\int_{1}^{\1589}{\1587^{\1646}\1569\1587}} & {\\text{\1573\1584\1575\1603\1575\1606}\1587 \\in \1605} \\\\\n{{\1591\1575}\\pi} & {\\text{\1594\1610\1585\1584\1604\1603}\\left( \\text{\1605\1593}\\pi \\simeq 3,141 \\right)}\n\\end{matrix} \\right."
+              ]
+          , Para
+              [ Str "The"
+              , Space
+              , Str "test"
+              , Space
+              , Str "passes"
+              , Space
+              , Str "if"
+              , Space
+              , Str "the"
+              , Space
+              , Str "rendering"
+              , Space
+              , Str "looks"
+              , Space
+              , Str "like"
+              , Space
+              , Str "the"
+              , Space
+              , Str "following"
+              , Space
+              , Str "image:"
+              ]
+          ]
+      , Div
+          ( "content-mathml-001.xhtml_mathml-027"
+          , [ "section" , "ctest" ]
+          , []
+          )
+          [ Header
+              2
+              ( "" , [] , [] )
+              [ Span ( "" , [ "nature" ] , [] ) [ Str "[REQUIRED]" ]
+              , SoftBreak
+              , Span ( "" , [ "test-id" ] , [] ) [ Str "mathml-027" ]
+              , Str "Elementary"
+              , Space
+              , Str "math:"
+              , Space
+              , Str "long"
+              , Space
+              , Str "division"
+              , Space
+              , Str "notation"
+              ]
+          , Para
+              [ Str "Tests"
+              , Space
+              , Str "whether"
+              , Space
+              , Code ( "" , [] , [] ) "mlongdiv"
+              , Space
+              , Str "elements"
+              , Space
+              , Str "(from"
+              , Space
+              , Str "elementary"
+              , Space
+              , Str "math)"
+              , Space
+              , Str "are"
+              , Space
+              , Str "supported."
+              ]
+          , Plain
+              [ Span
+                  ( ""
+                  , [ "math" ]
+                  , [ ( "xmlns" , "http://www.w3.org/1998/Math/MathML" )
+                    ]
+                  )
+                  [ SoftBreak
+                  , Str "3"
+                  , SoftBreak
+                  , Str "435.3"
+                  , SoftBreak
+                  , Str "1306"
+                  , SoftBreak
+                  , Str "12"
+                  , SoftBreak
+                  , Str "10"
+                  , SoftBreak
+                  , Str "9"
+                  , SoftBreak
+                  , Str "16"
+                  , SoftBreak
+                  , Str "15"
+                  , SoftBreak
+                  , Str "1.0"
+                  , SoftBreak
+                  , Str "9"
+                  , SoftBreak
+                  , Str "1"
+                  , SoftBreak
+                  ]
+              ]
+          , Para
+              [ Str "The"
+              , Space
+              , Str "test"
+              , Space
+              , Str "passes"
+              , Space
+              , Str "if"
+              , Space
+              , Str "the"
+              , Space
+              , Str "rendering"
+              , Space
+              , Str "looks"
+              , Space
+              , Str "like"
+              , Space
+              , Str "the"
+              , Space
+              , Str "following"
+              , Space
+              , Str "image:"
+              , Space
+              , Str "."
+              ]
+          ]
+      ]
+  , Para [ Span ( "content-switch-001.xhtml" , [] , [] ) [] ]
+  , Div
+      ( "content-switch-001.xhtml_epub-switch"
+      , [ "section" ]
+      , []
+      )
+      [ Header
+          3 ( "" , [] , [] ) [ Code ( "" , [] , [] ) "epub:switch" ]
+      , Div
+          ( "content-switch-001.xhtml_switch-010"
+          , [ "section" , "ctest" ]
+          , []
+          )
+          [ Header
+              4
+              ( "" , [] , [] )
+              [ Span ( "" , [ "nature" ] , [] ) [ Str "[REQUIRED]" ]
+              , Space
+              , Span ( "" , [ "test-id" ] , [] ) [ Str "switch-010" ]
+              , Space
+              , Str "Support"
+              ]
+          , Para
+              [ Str "Tests"
+              , Space
+              , Str "whether"
+              , Space
+              , Str "the"
+              , Space
+              , Link
+                  ( "" , [] , [] )
+                  [ Code ( "" , [] , [] ) "epub:switch" ]
+                  ( "http://idpf.org/epub/30/spec/epub30-contentdocs.html#sec-xhtml-content-switch"
+                  , ""
+                  )
+              , Space
+              , Str "element"
+              , Space
+              , Str "is"
+              , Space
+              , Str "supported."
+              ]
+          , Para [ Str "PASS" ]
+          , Para
+              [ Str "If"
+              , Space
+              , Str "only"
+              , Space
+              , Str "the"
+              , Space
+              , Str "word"
+              , Space
+              , Str "\"PASS\""
+              , Space
+              , Str "is"
+              , Space
+              , Str "rendered"
+              , Space
+              , Str "before"
+              , Space
+              , Str "this"
+              , Space
+              , Str "paragraph,"
+              , Space
+              , Str "the"
+              , Space
+              , Str "test"
+              , Space
+              , Str "passes."
+              , Space
+              , Str "If"
+              , Space
+              , Str "both"
+              , Space
+              , Str "\"PASS\""
+              , Space
+              , Str "and"
+              , Space
+              , Str "\"FAIL\""
+              , Space
+              , Str "are"
+              , Space
+              , Str "rendered,"
+              , Space
+              , Str "or"
+              , Space
+              , Str "neither"
+              , SoftBreak
+              , Str "\"PASS\""
+              , Space
+              , Str "nor"
+              , Space
+              , Str "\"FAIL\""
+              , Space
+              , Str "is"
+              , Space
+              , Str "rendered,"
+              , Space
+              , Str "the"
+              , Space
+              , Str "test"
+              , Space
+              , Str "fails."
+              ]
+          ]
+      , Div
+          ( "content-switch-001.xhtml_switch-020"
+          , [ "section" , "otest" ]
+          , []
+          )
+          [ Header
+              4
+              ( "" , [] , [] )
+              [ Span ( "" , [ "nature" ] , [] ) [ Str "[OPTIONAL]" ]
+              , SoftBreak
+              , Span ( "" , [ "test-id" ] , [] ) [ Str "switch-020" ]
+              , SoftBreak
+              , Str "MathML"
+              , Space
+              , Str "Embedding"
+              ]
+          , Para
+              [ Str "Tests"
+              , Space
+              , Str "whether"
+              , Space
+              , Str "the"
+              , Space
+              , Str "MathML"
+              , Space
+              , Str "namespace"
+              , Space
+              , Str "is"
+              , Space
+              , Str "recognized"
+              , Space
+              , Str "when"
+              , Space
+              , Str "used"
+              , Space
+              , Str "in"
+              , Space
+              , Str "an"
+              , Space
+              , Link
+                  ( "" , [] , [] )
+                  [ Code ( "" , [] , [] ) "epub:case" ]
+                  ( "http://idpf.org/epub/30/spec/epub30-contentdocs.html#sec-xhtml-epub-case"
+                  , ""
+                  )
+              , Space
+              , Str "element."
+              ]
+          , Para [ Math InlineMath "{2x}{+ y - z}" ]
+          , Para
+              [ Str "If"
+              , Space
+              , Str "a"
+              , Space
+              , Str "MathML"
+              , Space
+              , Str "equation"
+              , Space
+              , Str "is"
+              , Space
+              , Str "rendered"
+              , Space
+              , Str "before"
+              , Space
+              , Str "this"
+              , Space
+              , Str "paragraph,"
+              , Space
+              , Str "the"
+              , Space
+              , Str "test"
+              , Space
+              , Str "passes."
+              ]
+          , Para
+              [ Str "If"
+              , Space
+              , Str "test"
+              , Space
+              , Code ( "" , [] , [] ) "switch-010"
+              , Space
+              , Str "did"
+              , Space
+              , Str "not"
+              , Space
+              , Str "pass,"
+              , Space
+              , Str "this"
+              , Space
+              , Str "test"
+              , Space
+              , Str "should"
+              , Space
+              , Str "be"
+              , Space
+              , Str "marked"
+              , Space
+              , Code ( "" , [] , [] ) "Not Supported"
+              , Str "."
+              ]
+          ]
+      ]
+  ]
diff --git a/test/epub/formatting.epub b/test/epub/formatting.epub
Binary files a/test/epub/formatting.epub and b/test/epub/formatting.epub differ
diff --git a/test/epub/formatting.native b/test/epub/formatting.native
--- a/test/epub/formatting.native
+++ b/test/epub/formatting.native
@@ -1,402 +1,6020 @@
-[Para [Span ("front.xhtml",[],[]) []]
-,Div ("",["section"],[])
- [Header 1 ("",[],[]) [Str "EPUB",Space,Str "3",Space,Str "Styling",Space,Str "Test",Space,Str "Document:",Space,Str "0101"]
- ,Div ("",["section"],[])
-  [Header 2 ("",[],[]) [Str "Status",Space,Str "of",Space,Str "this",Space,Str "Document"]
-  ,Para [Str "This",Space,Str "publication",Space,Str "is",Space,Str "currently",Space,Str "considered",Space,Span ("",["status"],[]) [Str "[UNDER",Space,Str "DEVELOPMENT]"],Space,Str "by",Space,Str "the",Space,Str "IDPF."]
-  ,Para [Str "This",Space,Str "publication",Space,Str "is",Space,Str "part",Space,Str "of",Space,Str "version",Space,Span ("",["version"],[]) [Str "X.X"],Space,Str "of",Space,Str "the",Space,Str "EPUB",Space,Str "3.0",Space,Str "Compliance",Space,Str "Test",Space,Str "Suite",Space,Str "released",SoftBreak,Str "on",Space,RawInline (Format "html") "<time class=\"release\">",Str "TBD",RawInline (Format "html") "</time>",Str "."]
-  ,Para [Str "Before",Space,Str "using",Space,Str "this",Space,Str "publication",Space,Str "to",Space,Str "evaluate",Space,Str "reading",Space,Str "systems,",Space,Str "testers",Space,Str "are",Space,Str "strongly",Space,Str "encouraged",Space,Str "to",SoftBreak,Str "verify",Space,Str "that",Space,Str "they",Space,Str "have",Space,Str "the",Space,Str "latest",Space,Str "release",Space,Str "by",Space,Str "checking",Space,Str "the",Space,Str "current",Space,Str "release",Space,Str "version",Space,Str "and",Space,Str "date",Space,Str "of",SoftBreak,Str "the",Space,Str "test",Space,Str "suite",Space,Str "at",Space,Link ("",[],[]) [Str "TBD"] ("http://idpf.org/","")]
-  ,Para [Str "This",Space,Str "publication",Space,Str "is",Space,Str "one",Space,Str "of",Space,Str "several",Space,Str "that",Space,Str "currently",Space,Str "comprise",Space,Str "the",Space,Str "EPUB",Space,Str "3",Space,Str "conformance",Space,Str "test",Space,Str "suite",SoftBreak,Str "for",Space,Str "reflowable",Space,Str "content.",Space,Str "The",Space,Str "complete",Space,Str "test",Space,Str "suite",Space,Str "includes",Space,Str "all",Space,Str "of",Space,Str "the",Space,Str "following",Space,Str "publications:"]
-  ,OrderedList (1,DefaultStyle,DefaultDelim)
-   [[Plain [Str "."]]]]
- ,Div ("",["section"],[])
-  [Header 2 ("",[],[]) [Str "About",Space,Str "this",Space,Str "Document"]
-  ,Para [Str "This",Space,Str "document",Space,Str "focuses",Space,Str "on",Space,Str "human-evaluated",Space,Str "binary",Space,Str "(pass/fail)",Space,Str "tests",Space,Str "in",Space,Str "a",SoftBreak,Str "reflowable",Space,Str "context.",Space,Str "Tests",Space,Str "for",Space,Str "fixed-layout",Space,Str "content",Space,Str "and",Space,Str "other",Space,Str "individual",Space,Str "tests",Space,Str "that",SoftBreak,Str "require",Space,Str "a",Space,Str "dedicated",Space,Str "epub",Space,Str "file",Space,Str "are",Space,Str "available",Space,Str "in",Space,Str "additional",Space,Str "sibling",Space,Str "documents;",Space,Str "refer",Space,Str "to",SoftBreak,Str "the",Space,Link ("",[],[]) [Str "test",Space,Str "suite",SoftBreak,Str "wiki"] ("https://github.com/mgylling/epub-testsuite/wiki/Overview",""),Space,Str "(",Code ("",[],[]) "https://github.com/mgylling/epub-testsuite/wiki/Overview",Str ")",Space,Str "for",Space,Str "additional",SoftBreak,Str "information."]]
- ,Div ("",["section"],[])
-  [Header 2 ("",[],[]) [Str "Conventions"]
-  ,Para [Str "The",Space,Str "following",Space,Str "conventions",Space,Str "are",Space,Str "used",Space,Str "throughout",Space,Str "the",Space,Str "document:"]
-  ,DefinitionList
-   [([Str "1.",Space,Str "Locating",Space,Str "a",Space,Str "test"],
-     [[Div ("",["ctest"],[])
-       [Para [Str "Tests",Space,Str "for",Space,Emph [Str "required"],Space,Str "Reading",Space,Str "System",Space,Str "functionality",Space,Str "are",SoftBreak,Str "preceded",Space,Str "by",Space,Str "the",Space,Str "label:",Space,Span ("",["nature"],[("style","display: inline; font-size: 100%")]) [Str "[REQUIRED]"]]]
-      ,Div ("",["otest"],[])
-       [Para [Str "Tests",Space,Str "for",Space,Emph [Str "optional"],Space,Str "Reading",Space,Str "System",Space,Str "functionality",Space,Str "are",SoftBreak,Str "preceded",Space,Str "by",Space,Str "the",Space,Str "label:",Space,Span ("",["nature"],[("style","display: inline; font-size: 100%")]) [Str "[OPTIONAL]"]]]]])
-   ,([Str "2.",Space,Str "Performing",Space,Str "the",Space,Str "test"],
-     [[Plain [Str "Each",Space,Str "test",Space,Str "includes",Space,Str "a",Space,Str "description",Space,Str "of",Space,Str "its",Space,Str "purpose",Space,Str "followed",Space,Str "by",Space,Str "the",Space,Str "actual",Space,Strong [Str "test",Space,Str "statement,",SoftBreak,Str "which",Space,Str "can",Space,Str "always",Space,Str "be",Space,Str "evaluated",Space,Str "to",Space,Str "true",Space,Str "or",Space,Str "false"],Str ".",Space,Str "These",Space,Str "statements",Space,Str "typically",Space,Str "have",Space,Str "the",Space,Str "form:",SoftBreak,Str "\"If",Space,Str "[some",Space,Str "condition],",Space,Str "the",Space,Str "test",Space,Str "passes\"."]]])
-   ,([Str "3.",Space,Str "Scoring",Space,Str "in",Space,Str "the",Space,Str "results",Space,Str "form"],
-     [[Plain [Str "@@@TODO",Space,Str "provide",Space,Str "info",Space,Str "on",Space,Str "where",Space,Str "to",Space,Str "get",Space,Str "the",Space,Str "results",Space,Str "form"]]])]]]
-,Para [Span ("styling-xhtml-001.xhtml",[],[]) []]
-,Div ("styling-xhtml-001.xhtml#epub-css",["section"],[])
- [Header 1 ("",[],[]) [Str "EPUB",Space,Str "Style",Space,Str "Sheets"]
- ,Para [Str "This",Space,Str "section",Space,Str "contains",Space,Str "tests",Space,Str "for",Space,Str "styling",Space,Str "and",Space,Str "layout."]]
-,Para [Span ("styling-xhtml-003.xhtml",[],[]) []]
-,Div ("styling-xhtml-003.xhtml#style-110",["section","ctest"],[])
- [Header 2 ("",[],[]) [Span ("",["nature"],[]) [Str "[REQUIRED]"],Space,Span ("",["test-id"],[]) [Str "style-110"],Space,Str "Multi-Column",Space,Str "Layouts"]
- ,Para [Str "Tests",Space,Str "whether",Space,Str "the",Space,Code ("",[],[]) "CSS Multi-Column Layout",Space,Str "properties",Space,Str "are",Space,Str "supported."]
- ,Div ("",["multicol"],[])
-  [Para [Str "Lorem",Space,Str "ipsum",Space,Str "dolor",Space,Str "sit",Space,Str "amet,",Space,Str "consectetur",Space,Str "adipisicing",Space,Str "elit,",Space,Str "sed",Space,Str "do",Space,Str "eiusmod",Space,Str "tempor",Space,Str "incididunt",Space,Str "ut",Space,Str "labore",Space,Str "et",Space,Str "dolore",Space,Str "magna",Space,Str "aliqua.",Space,Str "Ut",Space,Str "enim",Space,Str "ad",Space,Str "minim",Space,Str "veniam,",Space,Str "quis",Space,Str "nostrud",Space,Str "exercitation",Space,Str "ullamco",Space,Str "laboris",Space,Str "nisi",Space,Str "ut",Space,Str "aliquip",Space,Str "ex",Space,Str "ea",Space,Str "commodo",Space,Str "consequat.",Space,Str "Duis",Space,Str "aute",Space,Str "irure",Space,Str "dolor",Space,Str "in",Space,Str "reprehenderit",Space,Str "in",Space,Str "voluptate",Space,Str "velit",Space,Str "esse",Space,Str "cillum",Space,Str "dolore",Space,Str "eu",Space,Str "fugiat",Space,Str "nulla",Space,Str "pariatur.",Space,Str "Excepteur",Space,Str "sint",Space,Str "occaecat",Space,Str "cupidatat",Space,Str "non",Space,Str "proident,",Space,Str "sunt",Space,Str "in",Space,Str "culpa",Space,Str "qui",Space,Str "officia",Space,Str "deserunt",Space,Str "mollit",Space,Str "anim",Space,Str "id",Space,Str "est",Space,Str "laborum."]
-  ,Para [Str "Lorem",Space,Str "ipsum",Space,Str "dolor",Space,Str "sit",Space,Str "amet,",Space,Str "consectetur",Space,Str "adipisicing",Space,Str "elit,",Space,Str "sed",Space,Str "do",Space,Str "eiusmod",Space,Str "tempor",Space,Str "incididunt",Space,Str "ut",Space,Str "labore",Space,Str "et",Space,Str "dolore",Space,Str "magna",Space,Str "aliqua.",Space,Str "Ut",Space,Str "enim",Space,Str "ad",Space,Str "minim",Space,Str "veniam,",Space,Str "quis",Space,Str "nostrud",Space,Str "exercitation",Space,Str "ullamco",Space,Str "laboris",Space,Str "nisi",Space,Str "ut",Space,Str "aliquip",Space,Str "ex",Space,Str "ea",Space,Str "commodo",Space,Str "consequat.",Space,Str "Duis",Space,Str "aute",Space,Str "irure",Space,Str "dolor",Space,Str "in",Space,Str "reprehenderit",Space,Str "in",Space,Str "voluptate",Space,Str "velit",Space,Str "esse",Space,Str "cillum",Space,Str "dolore",Space,Str "eu",Space,Str "fugiat",Space,Str "nulla",Space,Str "pariatur.",Space,Str "Excepteur",Space,Str "sint",Space,Str "occaecat",Space,Str "cupidatat",Space,Str "non",Space,Str "proident,",Space,Str "sunt",Space,Str "in",Space,Str "culpa",Space,Str "qui",Space,Str "officia",Space,Str "deserunt",Space,Str "mollit",Space,Str "anim",Space,Str "id",Space,Str "est",Space,Str "laborum."]
-  ,Para [Str "Lorem",Space,Str "ipsum",Space,Str "dolor",Space,Str "sit",Space,Str "amet,",Space,Str "consectetur",Space,Str "adipisicing",Space,Str "elit,",Space,Str "sed",Space,Str "do",Space,Str "eiusmod",Space,Str "tempor",Space,Str "incididunt",Space,Str "ut",Space,Str "labore",Space,Str "et",Space,Str "dolore",Space,Str "magna",Space,Str "aliqua.",Space,Str "Ut",Space,Str "enim",Space,Str "ad",Space,Str "minim",Space,Str "veniam,",Space,Str "quis",Space,Str "nostrud",Space,Str "exercitation",Space,Str "ullamco",Space,Str "laboris",Space,Str "nisi",Space,Str "ut",Space,Str "aliquip",Space,Str "ex",Space,Str "ea",Space,Str "commodo",Space,Str "consequat.",Space,Str "Duis",Space,Str "aute",Space,Str "irure",Space,Str "dolor",Space,Str "in",Space,Str "reprehenderit",Space,Str "in",Space,Str "voluptate",Space,Str "velit",Space,Str "esse",Space,Str "cillum",Space,Str "dolore",Space,Str "eu",Space,Str "fugiat",Space,Str "nulla",Space,Str "pariatur.",Space,Str "Excepteur",Space,Str "sint",Space,Str "occaecat",Space,Str "cupidatat",Space,Str "non",Space,Str "proident,",Space,Str "sunt",Space,Str "in",Space,Str "culpa",Space,Str "qui",Space,Str "officia",Space,Str "deserunt",Space,Str "mollit",Space,Str "anim",Space,Str "id",Space,Str "est",Space,Str "laborum."]
-  ,Para [Str "Lorem",Space,Str "ipsum",Space,Str "dolor",Space,Str "sit",Space,Str "amet,",Space,Str "consectetur",Space,Str "adipisicing",Space,Str "elit,",Space,Str "sed",Space,Str "do",Space,Str "eiusmod",Space,Str "tempor",Space,Str "incididunt",Space,Str "ut",Space,Str "labore",Space,Str "et",Space,Str "dolore",Space,Str "magna",Space,Str "aliqua.",Space,Str "Ut",Space,Str "enim",Space,Str "ad",Space,Str "minim",Space,Str "veniam,",Space,Str "quis",Space,Str "nostrud",Space,Str "exercitation",Space,Str "ullamco",Space,Str "laboris",Space,Str "nisi",Space,Str "ut",Space,Str "aliquip",Space,Str "ex",Space,Str "ea",Space,Str "commodo",Space,Str "consequat.",Space,Str "Duis",Space,Str "aute",Space,Str "irure",Space,Str "dolor",Space,Str "in",Space,Str "reprehenderit",Space,Str "in",Space,Str "voluptate",Space,Str "velit",Space,Str "esse",Space,Str "cillum",Space,Str "dolore",Space,Str "eu",Space,Str "fugiat",Space,Str "nulla",Space,Str "pariatur.",Space,Str "Excepteur",Space,Str "sint",Space,Str "occaecat",Space,Str "cupidatat",Space,Str "non",Space,Str "proident,",Space,Str "sunt",Space,Str "in",Space,Str "culpa",Space,Str "qui",Space,Str "officia",Space,Str "deserunt",Space,Str "mollit",Space,Str "anim",Space,Str "id",Space,Str "est",Space,Str "laborum."]
-  ,Para [Str "Lorem",Space,Str "ipsum",Space,Str "dolor",Space,Str "sit",Space,Str "amet,",Space,Str "consectetur",Space,Str "adipisicing",Space,Str "elit,",Space,Str "sed",Space,Str "do",Space,Str "eiusmod",Space,Str "tempor",Space,Str "incididunt",Space,Str "ut",Space,Str "labore",Space,Str "et",Space,Str "dolore",Space,Str "magna",Space,Str "aliqua.",Space,Str "Ut",Space,Str "enim",Space,Str "ad",Space,Str "minim",Space,Str "veniam,",Space,Str "quis",Space,Str "nostrud",Space,Str "exercitation",Space,Str "ullamco",Space,Str "laboris",Space,Str "nisi",Space,Str "ut",Space,Str "aliquip",Space,Str "ex",Space,Str "ea",Space,Str "commodo",Space,Str "consequat.",Space,Str "Duis",Space,Str "aute",Space,Str "irure",Space,Str "dolor",Space,Str "in",Space,Str "reprehenderit",Space,Str "in",Space,Str "voluptate",Space,Str "velit",Space,Str "esse",Space,Str "cillum",Space,Str "dolore",Space,Str "eu",Space,Str "fugiat",Space,Str "nulla",Space,Str "pariatur.",Space,Str "Excepteur",Space,Str "sint",Space,Str "occaecat",Space,Str "cupidatat",Space,Str "non",Space,Str "proident,",Space,Str "sunt",Space,Str "in",Space,Str "culpa",Space,Str "qui",Space,Str "officia",Space,Str "deserunt",Space,Str "mollit",Space,Str "anim",Space,Str "id",Space,Str "est",Space,Str "laborum."]
-  ,Para [Str "Lorem",Space,Str "ipsum",Space,Str "dolor",Space,Str "sit",Space,Str "amet,",Space,Str "consectetur",Space,Str "adipisicing",Space,Str "elit,",Space,Str "sed",Space,Str "do",Space,Str "eiusmod",Space,Str "tempor",Space,Str "incididunt",Space,Str "ut",Space,Str "labore",Space,Str "et",Space,Str "dolore",Space,Str "magna",Space,Str "aliqua.",Space,Str "Ut",Space,Str "enim",Space,Str "ad",Space,Str "minim",Space,Str "veniam,",Space,Str "quis",Space,Str "nostrud",Space,Str "exercitation",Space,Str "ullamco",Space,Str "laboris",Space,Str "nisi",Space,Str "ut",Space,Str "aliquip",Space,Str "ex",Space,Str "ea",Space,Str "commodo",Space,Str "consequat.",Space,Str "Duis",Space,Str "aute",Space,Str "irure",Space,Str "dolor",Space,Str "in",Space,Str "reprehenderit",Space,Str "in",Space,Str "voluptate",Space,Str "velit",Space,Str "esse",Space,Str "cillum",Space,Str "dolore",Space,Str "eu",Space,Str "fugiat",Space,Str "nulla",Space,Str "pariatur.",Space,Str "Excepteur",Space,Str "sint",Space,Str "occaecat",Space,Str "cupidatat",Space,Str "non",Space,Str "proident,",Space,Str "sunt",Space,Str "in",Space,Str "culpa",Space,Str "qui",Space,Str "officia",Space,Str "deserunt",Space,Str "mollit",Space,Str "anim",Space,Str "id",Space,Str "est",Space,Str "laborum."]
-  ,Para [Str "Lorem",Space,Str "ipsum",Space,Str "dolor",Space,Str "sit",Space,Str "amet,",Space,Str "consectetur",Space,Str "adipisicing",Space,Str "elit,",Space,Str "sed",Space,Str "do",Space,Str "eiusmod",Space,Str "tempor",Space,Str "incididunt",Space,Str "ut",Space,Str "labore",Space,Str "et",Space,Str "dolore",Space,Str "magna",Space,Str "aliqua.",Space,Str "Ut",Space,Str "enim",Space,Str "ad",Space,Str "minim",Space,Str "veniam,",Space,Str "quis",Space,Str "nostrud",Space,Str "exercitation",Space,Str "ullamco",Space,Str "laboris",Space,Str "nisi",Space,Str "ut",Space,Str "aliquip",Space,Str "ex",Space,Str "ea",Space,Str "commodo",Space,Str "consequat.",Space,Str "Duis",Space,Str "aute",Space,Str "irure",Space,Str "dolor",Space,Str "in",Space,Str "reprehenderit",Space,Str "in",Space,Str "voluptate",Space,Str "velit",Space,Str "esse",Space,Str "cillum",Space,Str "dolore",Space,Str "eu",Space,Str "fugiat",Space,Str "nulla",Space,Str "pariatur.",Space,Str "Excepteur",Space,Str "sint",Space,Str "occaecat",Space,Str "cupidatat",Space,Str "non",Space,Str "proident,",Space,Str "sunt",Space,Str "in",Space,Str "culpa",Space,Str "qui",Space,Str "officia",Space,Str "deserunt",Space,Str "mollit",Space,Str "anim",Space,Str "id",Space,Str "est",Space,Str "laborum."]
-  ,Para [Str "Lorem",Space,Str "ipsum",Space,Str "dolor",Space,Str "sit",Space,Str "amet,",Space,Str "consectetur",Space,Str "adipisicing",Space,Str "elit,",Space,Str "sed",Space,Str "do",Space,Str "eiusmod",Space,Str "tempor",Space,Str "incididunt",Space,Str "ut",Space,Str "labore",Space,Str "et",Space,Str "dolore",Space,Str "magna",Space,Str "aliqua.",Space,Str "Ut",Space,Str "enim",Space,Str "ad",Space,Str "minim",Space,Str "veniam,",Space,Str "quis",Space,Str "nostrud",Space,Str "exercitation",Space,Str "ullamco",Space,Str "laboris",Space,Str "nisi",Space,Str "ut",Space,Str "aliquip",Space,Str "ex",Space,Str "ea",Space,Str "commodo",Space,Str "consequat.",Space,Str "Duis",Space,Str "aute",Space,Str "irure",Space,Str "dolor",Space,Str "in",Space,Str "reprehenderit",Space,Str "in",Space,Str "voluptate",Space,Str "velit",Space,Str "esse",Space,Str "cillum",Space,Str "dolore",Space,Str "eu",Space,Str "fugiat",Space,Str "nulla",Space,Str "pariatur.",Space,Str "Excepteur",Space,Str "sint",Space,Str "occaecat",Space,Str "cupidatat",Space,Str "non",Space,Str "proident,",Space,Str "sunt",Space,Str "in",Space,Str "culpa",Space,Str "qui",Space,Str "officia",Space,Str "deserunt",Space,Str "mollit",Space,Str "anim",Space,Str "id",Space,Str "est",Space,Str "laborum."]
-  ,Para [Str "Lorem",Space,Str "ipsum",Space,Str "dolor",Space,Str "sit",Space,Str "amet,",Space,Str "consectetur",Space,Str "adipisicing",Space,Str "elit,",Space,Str "sed",Space,Str "do",Space,Str "eiusmod",Space,Str "tempor",Space,Str "incididunt",Space,Str "ut",Space,Str "labore",Space,Str "et",Space,Str "dolore",Space,Str "magna",Space,Str "aliqua.",Space,Str "Ut",Space,Str "enim",Space,Str "ad",Space,Str "minim",Space,Str "veniam,",Space,Str "quis",Space,Str "nostrud",Space,Str "exercitation",Space,Str "ullamco",Space,Str "laboris",Space,Str "nisi",Space,Str "ut",Space,Str "aliquip",Space,Str "ex",Space,Str "ea",Space,Str "commodo",Space,Str "consequat.",Space,Str "Duis",Space,Str "aute",Space,Str "irure",Space,Str "dolor",Space,Str "in",Space,Str "reprehenderit",Space,Str "in",Space,Str "voluptate",Space,Str "velit",Space,Str "esse",Space,Str "cillum",Space,Str "dolore",Space,Str "eu",Space,Str "fugiat",Space,Str "nulla",Space,Str "pariatur.",Space,Str "Excepteur",Space,Str "sint",Space,Str "occaecat",Space,Str "cupidatat",Space,Str "non",Space,Str "proident,",Space,Str "sunt",Space,Str "in",Space,Str "culpa",Space,Str "qui",Space,Str "officia",Space,Str "deserunt",Space,Str "mollit",Space,Str "anim",Space,Str "id",Space,Str "est",Space,Str "laborum."]]
- ,Para [Str "If",Space,Str "the",Space,Str "preceding",Space,Str "text",Space,Str "is",Space,Str "rendered",Space,Str "in",Space,Str "three",Space,Str "columns,",Space,Str "the",Space,Str "test",Space,Str "passes."]]
-,Para [Span ("styling-xhtml-002.xhtml",[],[]) []]
-,Div ("styling-xhtml-002.xhtml#style-lists",["section"],[])
- [Header 2 ("",[],[]) [Str "Lists"]
- ,Div ("styling-xhtml-002.xhtml#style-list-style-type",["section"],[])
-  [Header 3 ("",[],[]) [Str "The",Space,Code ("",[],[]) "list-style-type",Space,Str "property"]
-  ,Div ("styling-xhtml-002.xhtml#style-009",["section","ctest"],[])
-   [Header 4 ("",[],[]) [Span ("",["nature"],[]) [Str "[REQUIRED]"],Space,Span ("",["test-id"],[]) [Str "style-009"],Space,Code ("",[],[]) "decimal"]
-   ,Para [Str "Tests",Space,Str "whether",Space,Str "the",Space,Code ("",[],[]) "list-style-type",Space,Str "property",Space,Str "set",Space,Str "to",Space,Code ("",[],[]) "decimal",Space,Str "is",Space,Str "supported",Space,Str "on",Space,Str "a",Space,Code ("",[],[]) "ol",Space,Str "element."]
-   ,OrderedList (1,DefaultStyle,DefaultDelim)
-    [[Plain [Str "Lorem"]]
-    ,[Plain [Str "Ipsum"]]
-    ,[Plain [Str "Dolor"]]
-    ,[Plain [Str "Sit"]]
-    ,[Plain [Str "Amet"]]]
-   ,Para [Str "If",Space,Str "the",Space,Str "preceding",Space,Str "list",Space,Str "has",Space,Str "decimal",Space,Str "markers",Space,Str "in",Space,Str "ascending",Space,Str "order,",Space,Str "the",Space,Str "test",Space,Str "passes."]]
-  ,Div ("styling-xhtml-002.xhtml#style-010",["section","ctest"],[])
-   [Header 4 ("",[],[]) [Span ("",["nature"],[]) [Str "[REQUIRED]"],Space,Span ("",["test-id"],[]) [Str "style-010"],Space,Code ("",[],[]) "circle"]
-   ,Para [Str "Tests",Space,Str "whether",Space,Str "the",Space,Code ("",[],[]) "list-style-type",Space,Str "property",Space,Str "set",Space,Str "to",Space,Code ("",[],[]) "circle",Space,Str "is",Space,Str "supported",Space,Str "on",Space,Str "a",Space,Code ("",[],[]) "ul",Space,Str "element."]
-   ,BulletList
-    [[Plain [Str "Lorem"]]
-    ,[Plain [Str "Ipsum"]]
-    ,[Plain [Str "Dolor"]]
-    ,[Plain [Str "Sit"]]
-    ,[Plain [Str "Amet"]]]
-   ,Para [Str "If",Space,Str "the",Space,Str "preceding",Space,Str "list",Space,Str "has",Space,Str "circle",Space,Str "markers,",Space,Str "the",Space,Str "test",Space,Str "passes."]]
-  ,Div ("styling-xhtml-002.xhtml#style-011",["section","ctest"],[])
-   [Header 4 ("",[],[]) [Span ("",["nature"],[]) [Str "[REQUIRED]"],Space,Span ("",["test-id"],[]) [Str "style-011"],Space,Code ("",[],[]) "square"]
-   ,Para [Str "Tests",Space,Str "whether",Space,Str "the",Space,Code ("",[],[]) "list-style-type",Space,Str "property",Space,Str "set",Space,Str "to",Space,Code ("",[],[]) "square",Space,Str "is",Space,Str "supported",Space,Str "on",Space,Str "a",Space,Code ("",[],[]) "ul",Space,Str "element."]
-   ,BulletList
-    [[Plain [Str "Lorem"]]
-    ,[Plain [Str "Ipsum"]]
-    ,[Plain [Str "Dolor"]]
-    ,[Plain [Str "Sit"]]
-    ,[Plain [Str "Amet"]]]
-   ,Para [Str "If",Space,Str "the",Space,Str "preceding",Space,Str "list",Space,Str "has",Space,Str "square",Space,Str "markers,",Space,Str "the",Space,Str "test",Space,Str "passes."]]
-  ,Div ("styling-xhtml-002.xhtml#style-012",["section","ctest"],[])
-   [Header 4 ("",[],[]) [Span ("",["nature"],[]) [Str "[REQUIRED]"],Space,Span ("",["test-id"],[]) [Str "style-012"],Space,Code ("",[],[]) "disc"]
-   ,Para [Str "Tests",Space,Str "whether",Space,Str "the",Space,Code ("",[],[]) "list-style-type",Space,Str "property",Space,Str "set",Space,Str "to",Space,Code ("",[],[]) "disc",Space,Str "is",Space,Str "supported",Space,Str "on",Space,Str "a",Space,Code ("",[],[]) "ul",Space,Str "element."]
-   ,BulletList
-    [[Plain [Str "Lorem"]]
-    ,[Plain [Str "Ipsum"]]
-    ,[Plain [Str "Dolor"]]
-    ,[Plain [Str "Sit"]]
-    ,[Plain [Str "Amet"]]]
-   ,Para [Str "If",Space,Str "the",Space,Str "preceding",Space,Str "list",Space,Str "has",Space,Str "disc",Space,Str "markers,",Space,Str "the",Space,Str "test",Space,Str "passes."]]
-  ,Div ("styling-xhtml-002.xhtml#style-013",["section","ctest"],[])
-   [Header 4 ("",[],[]) [Span ("",["nature"],[]) [Str "[REQUIRED]"],Space,Span ("",["test-id"],[]) [Str "style-013"],Space,Code ("",[],[]) "lower-latin"]
-   ,Para [Str "Tests",Space,Str "whether",Space,Str "the",Space,Code ("",[],[]) "list-style-type",Space,Str "property",Space,Str "set",Space,Str "to",Space,Code ("",[],[]) "lower-latin",Space,Str "is",Space,Str "supported",Space,Str "on",Space,Str "a",Space,Code ("",[],[]) "ol",Space,Str "element."]
-   ,OrderedList (1,DefaultStyle,DefaultDelim)
-    [[Plain [Str "Lorem"]]
-    ,[Plain [Str "Ipsum"]]
-    ,[Plain [Str "Dolor"]]
-    ,[Plain [Str "Sit"]]
-    ,[Plain [Str "Amet"]]]
-   ,Para [Str "If",Space,Str "the",Space,Str "preceding",Space,Str "list",Space,Str "has",Space,Str "lower-latin",Space,Str "markers",Space,Str "in",Space,Str "ascending",Space,Str "order,",Space,Str "the",Space,Str "test",Space,Str "passes."]]
-  ,Div ("styling-xhtml-002.xhtml#style-014",["section","ctest"],[])
-   [Header 4 ("",[],[]) [Span ("",["nature"],[]) [Str "[REQUIRED]"],Space,Span ("",["test-id"],[]) [Str "style-014"],Space,Code ("",[],[]) "lower-roman"]
-   ,Para [Str "Tests",Space,Str "whether",Space,Str "the",Space,Code ("",[],[]) "list-style-type",Space,Str "property",Space,Str "set",Space,Str "to",Space,Code ("",[],[]) "lower-roman",Space,Str "is",Space,Str "supported",Space,Str "on",Space,Str "a",Space,Code ("",[],[]) "ol",Space,Str "element."]
-   ,OrderedList (1,DefaultStyle,DefaultDelim)
-    [[Plain [Str "Lorem"]]
-    ,[Plain [Str "Ipsum"]]
-    ,[Plain [Str "Dolor"]]
-    ,[Plain [Str "Sit"]]
-    ,[Plain [Str "Amet"]]]
-   ,Para [Str "If",Space,Str "the",Space,Str "preceding",Space,Str "list",Space,Str "has",Space,Str "lower-roman",Space,Str "markers",Space,Str "in",Space,Str "ascending",Space,Str "order,",Space,Str "the",Space,Str "test",Space,Str "passes."]]
-  ,Div ("styling-xhtml-002.xhtml#style-015",["section","ctest"],[])
-   [Header 4 ("",[],[]) [Span ("",["nature"],[]) [Str "[REQUIRED]"],Space,Span ("",["test-id"],[]) [Str "style-015"],Space,Code ("",[],[]) "upper-alpha"]
-   ,Para [Str "Tests",Space,Str "whether",Space,Str "the",Space,Code ("",[],[]) "list-style-type",Space,Str "property",Space,Str "set",Space,Str "to",Space,Code ("",[],[]) "upper-alpha",Space,Str "is",Space,Str "supported",Space,Str "on",Space,Str "a",Space,Code ("",[],[]) "ol",Space,Str "element."]
-   ,OrderedList (1,DefaultStyle,DefaultDelim)
-    [[Plain [Str "Lorem"]]
-    ,[Plain [Str "Ipsum"]]
-    ,[Plain [Str "Dolor"]]
-    ,[Plain [Str "Sit"]]
-    ,[Plain [Str "Amet"]]]
-   ,Para [Str "If",Space,Str "the",Space,Str "preceding",Space,Str "list",Space,Str "has",Space,Str "upper-alpha",Space,Str "markers",Space,Str "in",Space,Str "ascending",Space,Str "order,",Space,Str "the",Space,Str "test",Space,Str "passes."]]
-  ,Div ("styling-xhtml-002.xhtml#style-016",["section","ctest"],[])
-   [Header 4 ("",[],[]) [Span ("",["nature"],[]) [Str "[REQUIRED]"],Space,Span ("",["test-id"],[]) [Str "style-016"],Space,Code ("",[],[]) "hiragana"]
-   ,Para [Str "Tests",Space,Str "whether",Space,Str "the",Space,Code ("",[],[]) "list-style-type",Space,Str "property",Space,Str "set",Space,Str "to",Space,Code ("",[],[]) "hiragana",Space,Str "is",Space,Str "supported",Space,Str "on",Space,Str "a",Space,Code ("",[],[]) "ol",Space,Str "element."]
-   ,OrderedList (1,DefaultStyle,DefaultDelim)
-    [[Plain [Str "Lorem"]]
-    ,[Plain [Str "Ipsum"]]
-    ,[Plain [Str "Dolor"]]
-    ,[Plain [Str "Sit"]]
-    ,[Plain [Str "Amet"]]]
-   ,Para [Str "If",Space,Str "the",Space,Str "preceding",Space,Str "list",Space,Str "has",Space,Str "hiragana",Space,Str "markers",Space,Str "in",Space,Str "ascending",Space,Str "order,",Space,Str "the",Space,Str "test",Space,Str "passes."]]
-  ,Div ("styling-xhtml-002.xhtml#style-017",["section","ctest"],[])
-   [Header 4 ("",[],[]) [Span ("",["nature"],[]) [Str "[REQUIRED]"],Space,Span ("",["test-id"],[]) [Str "style-017"],Space,Code ("",[],[]) "hiragana-iroha"]
-   ,Para [Str "Tests",Space,Str "whether",Space,Str "the",Space,Code ("",[],[]) "list-style-type",Space,Str "property",Space,Str "set",Space,Str "to",Space,Code ("",[],[]) "hiragana-iroha",Space,Str "is",Space,Str "supported",Space,Str "on",Space,Str "a",Space,Code ("",[],[]) "ol",Space,Str "element."]
-   ,OrderedList (1,DefaultStyle,DefaultDelim)
-    [[Plain [Str "Lorem"]]
-    ,[Plain [Str "Ipsum"]]
-    ,[Plain [Str "Dolor"]]
-    ,[Plain [Str "Sit"]]
-    ,[Plain [Str "Amet"]]]
-   ,Para [Str "If",Space,Str "the",Space,Str "preceding",Space,Str "list",Space,Str "has",Space,Str "hiragana-iroha",Space,Str "markers",Space,Str "in",Space,Str "ascending",Space,Str "order,",Space,Str "the",Space,Str "test",Space,Str "passes."]]
-  ,Div ("styling-xhtml-002.xhtml#style-018",["section","ctest"],[])
-   [Header 4 ("",[],[]) [Span ("",["nature"],[]) [Str "[REQUIRED]"],Space,Span ("",["test-id"],[]) [Str "style-018"],Space,Code ("",[],[]) "katakana"]
-   ,Para [Str "Tests",Space,Str "whether",Space,Str "the",Space,Code ("",[],[]) "list-style-type",Space,Str "property",Space,Str "set",Space,Str "to",Space,Code ("",[],[]) "katakana",Space,Str "is",Space,Str "supported",Space,Str "on",Space,Str "a",Space,Code ("",[],[]) "ol",Space,Str "element."]
-   ,OrderedList (1,DefaultStyle,DefaultDelim)
-    [[Plain [Str "Lorem"]]
-    ,[Plain [Str "Ipsum"]]
-    ,[Plain [Str "Dolor"]]
-    ,[Plain [Str "Sit"]]
-    ,[Plain [Str "Amet"]]]
-   ,Para [Str "If",Space,Str "the",Space,Str "preceding",Space,Str "list",Space,Str "has",Space,Str "katakana",Space,Str "markers",Space,Str "in",Space,Str "ascending",Space,Str "order,",Space,Str "the",Space,Str "test",Space,Str "passes."]]
-  ,Div ("styling-xhtml-002.xhtml#style-019",["section","ctest"],[])
-   [Header 4 ("",[],[]) [Span ("",["nature"],[]) [Str "[REQUIRED]"],Space,Span ("",["test-id"],[]) [Str "style-019"],Space,Code ("",[],[]) "katakana-iroha"]
-   ,Para [Str "Tests",Space,Str "whether",Space,Str "the",Space,Code ("",[],[]) "list-style-type",Space,Str "property",Space,Str "set",Space,Str "to",Space,Code ("",[],[]) "katakana-iroha",Space,Str "is",Space,Str "supported",Space,Str "on",Space,Str "a",Space,Code ("",[],[]) "ol",Space,Str "element."]
-   ,OrderedList (1,DefaultStyle,DefaultDelim)
-    [[Plain [Str "Lorem"]]
-    ,[Plain [Str "Ipsum"]]
-    ,[Plain [Str "Dolor"]]
-    ,[Plain [Str "Sit"]]
-    ,[Plain [Str "Amet"]]]
-   ,Para [Str "If",Space,Str "the",Space,Str "preceding",Space,Str "list",Space,Str "has",Space,Str "katakana-iroha",Space,Str "markers",Space,Str "in",Space,Str "ascending",Space,Str "order,",Space,Str "the",Space,Str "test",Space,Str "passes."]]
-  ,Div ("styling-xhtml-002.xhtml#style-020",["section","ctest"],[])
-   [Header 4 ("",[],[]) [Span ("",["nature"],[]) [Str "[REQUIRED]"],Space,Span ("",["test-id"],[]) [Str "style-020"],Space,Code ("",[],[]) "upper-roman"]
-   ,Para [Str "Tests",Space,Str "whether",Space,Str "the",Space,Code ("",[],[]) "list-style-type",Space,Str "property",Space,Str "set",Space,Str "to",Space,Code ("",[],[]) "upper-roman",Space,Str "is",Space,Str "supported",Space,Str "on",Space,Str "a",Space,Code ("",[],[]) "ol",Space,Str "element."]
-   ,OrderedList (1,DefaultStyle,DefaultDelim)
-    [[Plain [Str "Lorem"]]
-    ,[Plain [Str "Ipsum"]]
-    ,[Plain [Str "Dolor"]]
-    ,[Plain [Str "Sit"]]
-    ,[Plain [Str "Amet"]]]
-   ,Para [Str "If",Space,Str "the",Space,Str "preceding",Space,Str "list",Space,Str "has",Space,Str "upper-roman",Space,Str "markers",Space,Str "in",Space,Str "ascending",Space,Str "order,",Space,Str "the",Space,Str "test",Space,Str "passes."]]
-  ,Div ("styling-xhtml-002.xhtml#style-021",["section","ctest"],[])
-   [Header 4 ("",[],[]) [Span ("",["nature"],[]) [Str "[REQUIRED]"],Space,Span ("",["test-id"],[]) [Str "style-021"],Space,Code ("",[],[]) "upper-latin"]
-   ,Para [Str "Tests",Space,Str "whether",Space,Str "the",Space,Code ("",[],[]) "list-style-type",Space,Str "property",Space,Str "set",Space,Str "to",Space,Code ("",[],[]) "upper-latin",Space,Str "is",Space,Str "supported",Space,Str "on",Space,Str "a",Space,Code ("",[],[]) "ol",Space,Str "element."]
-   ,OrderedList (1,DefaultStyle,DefaultDelim)
-    [[Plain [Str "Lorem"]]
-    ,[Plain [Str "Ipsum"]]
-    ,[Plain [Str "Dolor"]]
-    ,[Plain [Str "Sit"]]
-    ,[Plain [Str "Amet"]]]
-   ,Para [Str "If",Space,Str "the",Space,Str "preceding",Space,Str "list",Space,Str "has",Space,Str "upper-latin",Space,Str "markers",Space,Str "in",Space,Str "ascending",Space,Str "order,",Space,Str "the",Space,Str "test",Space,Str "passes."]]
-  ,Div ("styling-xhtml-002.xhtml#style-022",["section","ctest"],[])
-   [Header 4 ("",[],[]) [Span ("",["nature"],[]) [Str "[REQUIRED]"],Space,Span ("",["test-id"],[]) [Str "style-022"],Space,Code ("",[],[]) "lower-alpha"]
-   ,Para [Str "Tests",Space,Str "whether",Space,Str "the",Space,Code ("",[],[]) "list-style-type",Space,Str "property",Space,Str "set",Space,Str "to",Space,Code ("",[],[]) "lower-alpha",Space,Str "is",Space,Str "supported",Space,Str "on",Space,Str "a",Space,Code ("",[],[]) "ol",Space,Str "element."]
-   ,OrderedList (1,DefaultStyle,DefaultDelim)
-    [[Plain [Str "Lorem"]]
-    ,[Plain [Str "Ipsum"]]
-    ,[Plain [Str "Dolor"]]
-    ,[Plain [Str "Sit"]]
-    ,[Plain [Str "Amet"]]]
-   ,Para [Str "If",Space,Str "the",Space,Str "preceding",Space,Str "list",Space,Str "has",Space,Str "lower-alpha",Space,Str "markers",Space,Str "in",Space,Str "ascending",Space,Str "order,",Space,Str "the",Space,Str "test",Space,Str "passes."]]
-  ,Div ("styling-xhtml-002.xhtml#style-023",["section","ctest"],[])
-   [Header 4 ("",[],[]) [Span ("",["nature"],[]) [Str "[REQUIRED]"],Space,Span ("",["test-id"],[]) [Str "style-023"],Space,Code ("",[],[]) "lower-greek"]
-   ,Para [Str "Tests",Space,Str "whether",Space,Str "the",Space,Code ("",[],[]) "list-style-type",Space,Str "property",Space,Str "set",Space,Str "to",Space,Code ("",[],[]) "lower-greek",Space,Str "is",Space,Str "supported",Space,Str "on",Space,Str "a",Space,Code ("",[],[]) "ol",Space,Str "element."]
-   ,OrderedList (1,DefaultStyle,DefaultDelim)
-    [[Plain [Str "Lorem"]]
-    ,[Plain [Str "Ipsum"]]
-    ,[Plain [Str "Dolor"]]
-    ,[Plain [Str "Sit"]]
-    ,[Plain [Str "Amet"]]]
-   ,Para [Str "If",Space,Str "the",Space,Str "preceding",Space,Str "list",Space,Str "has",Space,Str "lower-greek",Space,Str "markers",Space,Str "in",Space,Str "ascending",Space,Str "order,",Space,Str "the",Space,Str "test",Space,Str "passes."]]
-  ,Div ("styling-xhtml-002.xhtml#style-024",["section","ctest"],[])
-   [Header 4 ("",[],[]) [Span ("",["nature"],[]) [Str "[REQUIRED]"],Space,Span ("",["test-id"],[]) [Str "style-024"],Space,Code ("",[],[]) "armenian"]
-   ,Para [Str "Tests",Space,Str "whether",Space,Str "the",Space,Code ("",[],[]) "list-style-type",Space,Str "property",Space,Str "set",Space,Str "to",Space,Code ("",[],[]) "armenian",Space,Str "is",Space,Str "supported",Space,Str "on",Space,Str "a",Space,Code ("",[],[]) "ol",Space,Str "element."]
-   ,OrderedList (1,DefaultStyle,DefaultDelim)
-    [[Plain [Str "Lorem"]]
-    ,[Plain [Str "Ipsum"]]
-    ,[Plain [Str "Dolor"]]
-    ,[Plain [Str "Sit"]]
-    ,[Plain [Str "Amet"]]]
-   ,Para [Str "If",Space,Str "the",Space,Str "preceding",Space,Str "list",Space,Str "has",Space,Str "armenian",Space,Str "markers",Space,Str "in",Space,Str "ascending",Space,Str "order,",Space,Str "the",Space,Str "test",Space,Str "passes."]]
-  ,Div ("styling-xhtml-002.xhtml#style-025",["section","ctest"],[])
-   [Header 4 ("",[],[]) [Span ("",["nature"],[]) [Str "[REQUIRED]"],Space,Span ("",["test-id"],[]) [Str "style-025"],Space,Code ("",[],[]) "cjk-ideographic"]
-   ,Para [Str "Tests",Space,Str "whether",Space,Str "the",Space,Code ("",[],[]) "list-style-type",Space,Str "property",Space,Str "set",Space,Str "to",Space,Code ("",[],[]) "cjk-ideographic",Space,Str "is",Space,Str "supported",Space,Str "on",Space,Str "a",Space,Code ("",[],[]) "ol",Space,Str "element."]
-   ,OrderedList (1,DefaultStyle,DefaultDelim)
-    [[Plain [Str "Lorem"]]
-    ,[Plain [Str "Ipsum"]]
-    ,[Plain [Str "Dolor"]]
-    ,[Plain [Str "Sit"]]
-    ,[Plain [Str "Amet"]]]
-   ,Para [Str "If",Space,Str "the",Space,Str "preceding",Space,Str "list",Space,Str "has",Space,Str "cjk-ideographic",Space,Str "markers",Space,Str "in",Space,Str "ascending",Space,Str "order,",Space,Str "the",Space,Str "test",Space,Str "passes."]]
-  ,Div ("styling-xhtml-002.xhtml#style-026",["section","ctest"],[])
-   [Header 4 ("",[],[]) [Span ("",["nature"],[]) [Str "[REQUIRED]"],Space,Span ("",["test-id"],[]) [Str "style-026"],Space,Code ("",[],[]) "decimal-leading-zero"]
-   ,Para [Str "Tests",Space,Str "whether",Space,Str "the",Space,Code ("",[],[]) "list-style-type",Space,Str "property",Space,Str "set",Space,Str "to",Space,Code ("",[],[]) "decimal-leading-zero",Space,Str "is",Space,Str "supported",Space,Str "on",Space,Str "a",Space,Code ("",[],[]) "ol",Space,Str "element."]
-   ,OrderedList (1,DefaultStyle,DefaultDelim)
-    [[Plain [Str "Lorem"]]
-    ,[Plain [Str "Ipsum"]]
-    ,[Plain [Str "Dolor"]]
-    ,[Plain [Str "Sit"]]
-    ,[Plain [Str "Amet"]]]
-   ,Para [Str "If",Space,Str "the",Space,Str "preceding",Space,Str "list",Space,Str "has",Space,Str "decimal-leading-zero",Space,Str "markers",Space,Str "in",Space,Str "ascending",Space,Str "order,",Space,Str "the",Space,Str "test",Space,Str "passes."]]
-  ,Div ("styling-xhtml-002.xhtml#style-027",["section","ctest"],[])
-   [Header 4 ("",[],[]) [Span ("",["nature"],[]) [Str "[REQUIRED]"],Space,Span ("",["test-id"],[]) [Str "style-027"],Space,Code ("",[],[]) "georgian"]
-   ,Para [Str "Tests",Space,Str "whether",Space,Str "the",Space,Code ("",[],[]) "list-style-type",Space,Str "property",Space,Str "set",Space,Str "to",Space,Code ("",[],[]) "georgian",Space,Str "is",Space,Str "supported",Space,Str "on",Space,Str "a",Space,Code ("",[],[]) "ol",Space,Str "element."]
-   ,OrderedList (1,DefaultStyle,DefaultDelim)
-    [[Plain [Str "Lorem"]]
-    ,[Plain [Str "Ipsum"]]
-    ,[Plain [Str "Dolor"]]
-    ,[Plain [Str "Sit"]]
-    ,[Plain [Str "Amet"]]]
-   ,Para [Str "If",Space,Str "the",Space,Str "preceding",Space,Str "list",Space,Str "has",Space,Str "georgian",Space,Str "markers",Space,Str "in",Space,Str "ascending",Space,Str "order,",Space,Str "the",Space,Str "test",Space,Str "passes."]]
-  ,Div ("styling-xhtml-002.xhtml#style-028",["section","ctest"],[])
-   [Header 4 ("",[],[]) [Span ("",["nature"],[]) [Str "[REQUIRED]"],Space,Span ("",["test-id"],[]) [Str "style-028"],Space,Code ("",[],[]) "hebrew"]
-   ,Para [Str "Tests",Space,Str "whether",Space,Str "the",Space,Code ("",[],[]) "list-style-type",Space,Str "property",Space,Str "set",Space,Str "to",Space,Code ("",[],[]) "hebrew",Space,Str "is",Space,Str "supported",Space,Str "on",Space,Str "a",Space,Code ("",[],[]) "ol",Space,Str "element."]
-   ,OrderedList (1,DefaultStyle,DefaultDelim)
-    [[Plain [Str "Lorem"]]
-    ,[Plain [Str "Ipsum"]]
-    ,[Plain [Str "Dolor"]]
-    ,[Plain [Str "Sit"]]
-    ,[Plain [Str "Amet"]]]
-   ,Para [Str "If",Space,Str "the",Space,Str "preceding",Space,Str "list",Space,Str "has",Space,Str "hebrew",Space,Str "markers",Space,Str "in",Space,Str "ascending",Space,Str "order,",Space,Str "the",Space,Str "test",Space,Str "passes."]]
-  ,Div ("styling-xhtml-002.xhtml#style-029",["section","ctest"],[])
-   [Header 4 ("",[],[]) [Span ("",["nature"],[]) [Str "[REQUIRED]"],Space,Span ("",["test-id"],[]) [Str "style-029"],Space,Code ("",[],[]) "none"]
-   ,Para [Str "Tests",Space,Str "whether",Space,Str "the",Space,Code ("",[],[]) "list-style-type",Space,Str "property",Space,Str "set",Space,Str "to",Space,Code ("",[],[]) "none",Space,Str "is",Space,Str "supported",Space,Str "on",Space,Str "a",Space,Code ("",[],[]) "ol",Space,Str "element."]
-   ,OrderedList (1,DefaultStyle,DefaultDelim)
-    [[Plain [Str "Lorem"]]
-    ,[Plain [Str "Ipsum"]]
-    ,[Plain [Str "Dolor"]]
-    ,[Plain [Str "Sit"]]
-    ,[Plain [Str "Amet"]]]
-   ,Para [Str "If",Space,Str "the",Space,Str "preceding",Space,Str "list",Space,Str "has",Space,Str "no",Space,Str "markers,",Space,Str "the",Space,Str "test",Space,Str "passes."]]]
- ,Div ("styling-xhtml-002.xhtml#style-list-style",["section"],[])
-  [Header 3 ("",[],[]) [Str "The",Space,Code ("",[],[]) "list-style",Space,Str "property"]
-  ,Div ("styling-xhtml-002.xhtml#style-030",["section","ctest"],[])
-   [Header 4 ("",[],[]) [Span ("",["nature"],[]) [Str "[REQUIRED]"],Space,Span ("",["test-id"],[]) [Str "style-030"],Space,Str "images"]
-   ,Para [Str "Tests",Space,Str "whether",Space,Str "the",Space,Code ("",[],[]) "list-style",Space,Str "shorthand",Space,Str "property",Space,Str "is",Space,Str "supported",Space,Str "using",Space,Str "a",Space,Str "gif",Space,Str "on",Space,Str "a",Space,Code ("",[],[]) "ul",Space,Str "element."]
-   ,BulletList
-    [[Plain [Str "Lorem"]]
-    ,[Plain [Str "Ipsum"]]
-    ,[Plain [Str "Dolor"]]
-    ,[Plain [Str "Sit"]]
-    ,[Plain [Str "Amet"]]]
-   ,Para [Str "If",Space,Str "the",Space,Str "preceding",Space,Str "list",Space,Str "has",Space,Str "the",Space,Str "purple",Space,Str "and",Space,Str "aqua",Space,Str "square",Space,Str "bullet",Space,Str "the",Space,Str "test",Space,Str "passes."]]]
- ,Div ("styling-xhtml-002.xhtml#style-list-style-position",["section"],[])
-  [Header 3 ("",[],[]) [Str "The",Space,Code ("",[],[]) "list-style-position",Space,Str "property"]
-  ,Div ("styling-xhtml-002.xhtml#style-040",["section","ctest"],[])
-   [Header 4 ("",[],[]) [Span ("",["nature"],[]) [Str "[REQUIRED]"],Space,Span ("",["test-id"],[]) [Str "style-040"],Space,Str "The",Space,Code ("",[],[]) "list-style-position",Space,Str "property:",Space,Code ("",[],[]) "inside"]
-   ,Para [Str "Tests",Space,Str "whether",Space,Str "the",Space,Code ("",[],[]) "list-style-position",Space,Str "property",Space,Str "set",Space,Str "to",Space,Code ("",[],[]) "inside",Space,Str "is",Space,Str "supported",Space,Str "on",Space,Str "a",Space,Code ("",[],[]) "ul",Space,Str "element."]
-   ,BulletList
-    [[Plain [Str "Lorem",Space,Str "ipsum",Space,Str "dolor",Space,Str "sit",Space,Str "amet,",Space,Str "consectetur",Space,Str "adipisicing",Space,Str "elit,",Space,Str "sed",Space,Str "do",Space,Str "eiusmod",Space,Str "tempor",Space,Str "incididunt",Space,Str "ut",Space,Str "labore",Space,Str "et",Space,Str "dolore",Space,Str "magna",Space,Str "aliqua.",Space,Str "Ut",Space,Str "enim",Space,Str "ad",Space,Str "minim",Space,Str "veniam,",Space,Str "quis",Space,Str "nostrud",Space,Str "exercitation",Space,Str "ullamco",Space,Str "laboris",Space,Str "nisi",Space,Str "ut",Space,Str "aliquip",Space,Str "ex",Space,Str "ea",Space,Str "commodo",Space,Str "consequat."]]
-    ,[Plain [Str "Lorem",Space,Str "ipsum",Space,Str "dolor",Space,Str "sit",Space,Str "amet,",Space,Str "consectetur",Space,Str "adipisicing",Space,Str "elit,",Space,Str "sed",Space,Str "do",Space,Str "eiusmod",Space,Str "tempor",Space,Str "incididunt",Space,Str "ut",Space,Str "labore",Space,Str "et",Space,Str "dolore",Space,Str "magna",Space,Str "aliqua.",Space,Str "Ut",Space,Str "enim",Space,Str "ad",Space,Str "minim",Space,Str "veniam,",Space,Str "quis",Space,Str "nostrud",Space,Str "exercitation",Space,Str "ullamco",Space,Str "laboris",Space,Str "nisi",Space,Str "ut",Space,Str "aliquip",Space,Str "ex",Space,Str "ea",Space,Str "commodo",Space,Str "consequat."]]
-    ,[Plain [Str "Lorem",Space,Str "ipsum",Space,Str "dolor",Space,Str "sit",Space,Str "amet,",Space,Str "consectetur",Space,Str "adipisicing",Space,Str "elit,",Space,Str "sed",Space,Str "do",Space,Str "eiusmod",Space,Str "tempor",Space,Str "incididunt",Space,Str "ut",Space,Str "labore",Space,Str "et",Space,Str "dolore",Space,Str "magna",Space,Str "aliqua.",Space,Str "Ut",Space,Str "enim",Space,Str "ad",Space,Str "minim",Space,Str "veniam,",Space,Str "quis",Space,Str "nostrud",Space,Str "exercitation",Space,Str "ullamco",Space,Str "laboris",Space,Str "nisi",Space,Str "ut",Space,Str "aliquip",Space,Str "ex",Space,Str "ea",Space,Str "commodo",Space,Str "consequat."]]]
-   ,Para [Str "If",Space,Str "the",Space,Str "preceding",Space,Str "list",Space,Str "has",Space,Str "markers",Space,Str "inside",Space,Str "the",Space,Str "indentation,",Space,Str "the",Space,Str "test",Space,Str "passes."]]
-  ,Div ("styling-xhtml-002.xhtml#style-041",["section","ctest"],[])
-   [Header 4 ("",[],[]) [Span ("",["nature"],[]) [Str "[REQUIRED]"],Space,Span ("",["test-id"],[]) [Str "style-041"],Space,Str "The",Space,Code ("",[],[]) "list-style-position",Space,Str "property:",Space,Code ("",[],[]) "outside"]
-   ,Para [Str "Tests",Space,Str "whether",Space,Str "the",Space,Code ("",[],[]) "list-style-position",Space,Str "property",Space,Str "set",Space,Str "to",Space,Code ("",[],[]) "outside",Space,Str "is",Space,Str "supported",Space,Str "on",Space,Str "a",Space,Code ("",[],[]) "ul",Space,Str "element."]
-   ,BulletList
-    [[Plain [Str "Lorem",Space,Str "ipsum",Space,Str "dolor",Space,Str "sit",Space,Str "amet,",Space,Str "consectetur",Space,Str "adipisicing",Space,Str "elit,",Space,Str "sed",Space,Str "do",Space,Str "eiusmod",Space,Str "tempor",Space,Str "incididunt",Space,Str "ut",Space,Str "labore",Space,Str "et",Space,Str "dolore",Space,Str "magna",Space,Str "aliqua.",Space,Str "Ut",Space,Str "enim",Space,Str "ad",Space,Str "minim",Space,Str "veniam,",Space,Str "quis",Space,Str "nostrud",Space,Str "exercitation",Space,Str "ullamco",Space,Str "laboris",Space,Str "nisi",Space,Str "ut",Space,Str "aliquip",Space,Str "ex",Space,Str "ea",Space,Str "commodo",Space,Str "consequat."]]
-    ,[Plain [Str "Lorem",Space,Str "ipsum",Space,Str "dolor",Space,Str "sit",Space,Str "amet,",Space,Str "consectetur",Space,Str "adipisicing",Space,Str "elit,",Space,Str "sed",Space,Str "do",Space,Str "eiusmod",Space,Str "tempor",Space,Str "incididunt",Space,Str "ut",Space,Str "labore",Space,Str "et",Space,Str "dolore",Space,Str "magna",Space,Str "aliqua.",Space,Str "Ut",Space,Str "enim",Space,Str "ad",Space,Str "minim",Space,Str "veniam,",Space,Str "quis",Space,Str "nostrud",Space,Str "exercitation",Space,Str "ullamco",Space,Str "laboris",Space,Str "nisi",Space,Str "ut",Space,Str "aliquip",Space,Str "ex",Space,Str "ea",Space,Str "commodo",Space,Str "consequat."]]
-    ,[Plain [Str "Lorem",Space,Str "ipsum",Space,Str "dolor",Space,Str "sit",Space,Str "amet,",Space,Str "consectetur",Space,Str "adipisicing",Space,Str "elit,",Space,Str "sed",Space,Str "do",Space,Str "eiusmod",Space,Str "tempor",Space,Str "incididunt",Space,Str "ut",Space,Str "labore",Space,Str "et",Space,Str "dolore",Space,Str "magna",Space,Str "aliqua.",Space,Str "Ut",Space,Str "enim",Space,Str "ad",Space,Str "minim",Space,Str "veniam,",Space,Str "quis",Space,Str "nostrud",Space,Str "exercitation",Space,Str "ullamco",Space,Str "laboris",Space,Str "nisi",Space,Str "ut",Space,Str "aliquip",Space,Str "ex",Space,Str "ea",Space,Str "commodo",Space,Str "consequat."]]]
-   ,Para [Str "If",Space,Str "the",Space,Str "preceding",Space,Str "list",Space,Str "has",Space,Str "the",Space,Str "default",Space,Str "setting",Space,Str "(marker",Space,Str "outside",Space,Str "the",Space,Str "indentation),",Space,Str "the",Space,Str "test",Space,Str "passes."]]]
- ,Div ("styling-xhtml-002.xhtml#style-list-start",["section"],[])
-  [Header 3 ("",[],[]) [Str "The",Space,Str "HTML",Space,Code ("",[],[]) "start",Space,Str "attribute"]
-  ,Div ("styling-xhtml-002.xhtml#style-050",["section","ctest"],[])
-   [Header 4 ("",[],[]) [Span ("",["nature"],[]) [Str "[REQUIRED]"],Space,Span ("",["test-id"],[]) [Str "style-050"],Space,Str "Without",Space,Code ("",[],[]) "list-style-type",Space,Str "set"]
-   ,Para [Str "Tests",Space,Str "whether",Space,Str "the",Space,Code ("",[],[]) "start",Space,Str "attribute",Space,Str "is",Space,Str "supported",Space,Str "on",Space,Str "a",Space,Code ("",[],[]) "ol",Space,Str "element",Space,Str "with",Space,Str "no",Space,Code ("",[],[]) "list-style-type",Space,Str "property."]
-   ,OrderedList (25,DefaultStyle,DefaultDelim)
-    [[Plain [Str "Lorem"]]
-    ,[Plain [Str "Ipsum"]]
-    ,[Plain [Str "Dolor"]]
-    ,[Plain [Str "Sit"]]
-    ,[Plain [Str "Amet"]]]
-   ,Para [Str "If",Space,Str "the",Space,Str "preceding",Space,Str "list",Space,Str "starts",Space,Str "at",Space,Str "25,",Space,Str "the",Space,Str "test",Space,Str "passes."]]
-  ,Div ("styling-xhtml-002.xhtml#style-051",["section","ctest"],[])
-   [Header 4 ("",[],[]) [Span ("",["nature"],[]) [Str "[REQUIRED]"],Space,Span ("",["test-id"],[]) [Str "style-051"],Space,Str "With",Space,Code ("",[],[]) "list-style-type",Space,Str "set"]
-   ,Para [Str "Tests",Space,Str "whether",Space,Str "the",Space,Code ("",[],[]) "start",Space,Str "attribute",Space,Str "is",Space,Str "supported",Space,Str "on",Space,Str "a",Space,Code ("",[],[]) "ol",Space,Str "element",Space,Str "with",Space,Str "a",Space,Code ("",[],[]) "list-style-type",Space,Str "property."]
-   ,OrderedList (50,DefaultStyle,DefaultDelim)
-    [[Plain [Str "Lorem"]]
-    ,[Plain [Str "Ipsum"]]
-    ,[Plain [Str "Dolor"]]
-    ,[Plain [Str "Sit"]]
-    ,[Plain [Str "Amet"]]]
-   ,Para [Str "If",Space,Str "the",Space,Str "preceding",Space,Str "list",Space,Str "starts",Space,Str "at",Space,Str "'L'",Space,Str "(50),",Space,Str "the",Space,Str "test",Space,Str "passes."]]]]
-,Para [Span ("styling-xhtml-004.xhtml",[],[]) []]
-,Div ("styling-xhtml-004.xhtml#style-media-rules",["section"],[])
- [Header 2 ("",[],[]) [Code ("",[],[]) "@media",Space,Str "Rules"]
- ,Div ("styling-xhtml-004.xhtml#style-210",["section","ctest"],[])
-  [Header 3 ("",[],[]) [Span ("",["nature"],[]) [Str "[REQUIRED]"],Space,Span ("",["test-id"],[]) [Str "style-210"],Space,Code ("",[],[]) "all"]
-  ,Para [Str "Tests",Space,Str "whether",Space,Str "the",Space,Code ("",[],[]) "@media",Space,Str "rule",Space,Str "set",Space,Str "to",Space,Code ("",[],[]) "all",Space,Str "is",Space,Str "supported."]
-  ,Para [Str "FAIL"]
-  ,Para [Str "If",Space,Str "the",Space,Str "preceding",Space,Str "paragraph",Space,Str "reads",Space,Str "\"FAIL\",",Space,Str "the",Space,Str "test",Space,Str "fails."]]
- ,Div ("styling-xhtml-004.xhtml#style-211",["section","ctest"],[])
-  [Header 3 ("",[],[]) [Span ("",["nature"],[]) [Str "[REQUIRED]"],Space,Span ("",["test-id"],[]) [Str "style-211"],Space,Code ("",[],[]) "screen"]
-  ,Para [Str "Tests",Space,Str "whether",Space,Str "the",Space,Code ("",[],[]) "@media",Space,Str "rule",Space,Str "set",Space,Str "to",Space,Code ("",[],[]) "screen",Space,Str "is",Space,Str "supported."]
-  ,Para [Str "FAIL"]
-  ,Para [Str "If",Space,Str "the",Space,Str "preceding",Space,Str "paragraph",Space,Str "reads",Space,Str "\"FAIL\",",Space,Str "the",Space,Str "test",Space,Str "fails."]]
- ,Div ("styling-xhtml-004.xhtml#style-212",["section","ctest"],[])
-  [Header 3 ("",[],[]) [Span ("",["nature"],[]) [Str "[REQUIRED]"],Space,Span ("",["test-id"],[]) [Str "style-212"],Space,Code ("",[],[]) "handheld"]
-  ,Para [Str "Tests",Space,Str "whether",Space,Str "the",Space,Code ("",[],[]) "@media",Space,Str "rule",Space,Str "set",Space,Str "to",Space,Code ("",[],[]) "handheld",Space,Str "is",Space,Str "supported."]
-  ,Para [Str "FAIL"]
-  ,Para [Str "If",Space,Str "the",Space,Str "preceding",Space,Str "paragraph",Space,Str "reads",Space,Str "\"FAIL\",",Space,Str "the",Space,Str "test",Space,Str "fails."]]
- ,Div ("styling-xhtml-004.xhtml#style-213",["section","ctest"],[])
-  [Header 3 ("",[],[]) [Span ("",["nature"],[]) [Str "[REQUIRED]"],Space,Span ("",["test-id"],[]) [Str "style-213"],Space,Code ("",[],[]) "tv"]
-  ,Para [Str "Tests",Space,Str "whether",Space,Str "the",Space,Code ("",[],[]) "@media",Space,Str "rule",Space,Str "set",Space,Str "to",Space,Code ("",[],[]) "tv",Space,Str "is",Space,Str "supported."]
-  ,Para [Str "FAIL"]
-  ,Para [Str "If",Space,Str "the",Space,Str "preceding",Space,Str "paragraph",Space,Str "reads",Space,Str "\"FAIL\",",Space,Str "the",Space,Str "test",Space,Str "fails."]]
- ,Div ("styling-xhtml-004.xhtml#style-220",["section","ctest"],[])
-  [Header 3 ("",[],[]) [Span ("",["nature"],[]) [Str "[REQUIRED]"],Space,Span ("",["test-id"],[]) [Str "style-220"],Space,Code ("",[],[]) "orientation:landscape"]
-  ,Para [Str "Tests",Space,Str "whether",Space,Str "the",Space,Code ("",[],[]) "@media",Space,Str "rule",Space,Str "set",Space,Str "to",Space,Code ("",[],[]) "orientation:landscape",Space,Str "is",Space,Str "supported."]
-  ,Para [Str "FAIL"]
-  ,Para [Str "If",Space,Str "the",Space,Str "preceding",Space,Str "paragraph",Space,Str "reads",Space,Str "\"FAIL\"",Space,Str "when",Space,Str "the",Space,Str "device",Space,Str "is",Space,Str "held",Space,Str "in",Space,Str "landscape",Space,Str "mode,",Space,Str "and",Space,Str "the",Space,Str "device",Space,Str "supports",Space,Str "multiple",Space,Str "orientations,",Space,Str "the",Space,Str "test",Space,Str "fails."]]
- ,Div ("styling-xhtml-004.xhtml#style-221",["section","ctest"],[])
-  [Header 3 ("",[],[]) [Span ("",["nature"],[]) [Str "[REQUIRED]"],Space,Span ("",["test-id"],[]) [Str "style-221"],Space,Code ("",[],[]) "orientation:portrait"]
-  ,Para [Str "Tests",Space,Str "whether",Space,Str "the",Space,Code ("",[],[]) "@media",Space,Str "rule",Space,Str "set",Space,Str "to",Space,Code ("",[],[]) "orientation:portrait",Space,Str "is",Space,Str "supported."]
-  ,Para [Str "FAIL"]
-  ,Para [Str "If",Space,Str "the",Space,Str "preceding",Space,Str "paragraph",Space,Str "reads",Space,Str "\"FAIL\"",Space,Str "when",Space,Str "the",Space,Str "device",Space,Str "is",Space,Str "held",Space,Str "in",Space,Str "portrait",Space,Str "mode,",Space,Str "and",Space,Str "the",Space,Str "device",Space,Str "supports",Space,Str "multiple",Space,Str "orientations,",Space,Str "the",Space,Str "test",Space,Str "fails."]]
- ,Div ("styling-xhtml-004.xhtml#style-230",["section","ctest"],[])
-  [Header 3 ("",[],[]) [Span ("",["nature"],[]) [Str "[REQUIRED]"],Space,Span ("",["test-id"],[]) [Str "style-230"],Space,Code ("",[],[]) "min-width"]
-  ,Para [Str "Tests",Space,Str "whether",Space,Str "the",Space,Code ("",[],[]) "@media",Space,Str "rule",Space,Str "set",Space,Str "to",Space,Code ("",[],[]) "min-width:200px",Space,Str "is",Space,Str "supported."]
-  ,Para [Str "FAIL"]
-  ,Para [Str "If",Space,Str "the",Space,Str "preceding",Space,Str "paragraph",Space,Str "reads",Space,Str "\"FAIL\",",Space,Str "the",Space,Str "test",Space,Str "fails."]]
- ,Div ("styling-xhtml-004.xhtml#style-231",["section","ctest"],[])
-  [Header 3 ("",[],[]) [Span ("",["nature"],[]) [Str "[REQUIRED]"],Space,Span ("",["test-id"],[]) [Str "style-231"],Space,Code ("",[],[]) "max-width"]
-  ,Para [Str "Tests",Space,Str "whether",Space,Str "the",Space,Code ("",[],[]) "@media",Space,Str "rule",Space,Str "set",Space,Str "to",Space,Code ("",[],[]) "max-width:2000px",Space,Str "is",Space,Str "supported."]
-  ,Para [Str "FAIL"]
-  ,Para [Str "If",Space,Str "the",Space,Str "preceding",Space,Str "paragraph",Space,Str "reads",Space,Str "\"FAIL\",",Space,Str "the",Space,Str "test",Space,Str "fails."]]
- ,Div ("styling-xhtml-004.xhtml#style-240",["section","ctest"],[])
-  [Header 3 ("",[],[]) [Span ("",["nature"],[]) [Str "[REQUIRED]"],Space,Span ("",["test-id"],[]) [Str "style-240"],Space,Code ("",[],[]) "min-device-width"]
-  ,Para [Str "Tests",Space,Str "whether",Space,Str "the",Space,Code ("",[],[]) "@media",Space,Str "rule",Space,Str "set",Space,Str "to",Space,Code ("",[],[]) "min-device-width:200px",Space,Str "is",Space,Str "supported."]
-  ,Para [Str "FAIL"]
-  ,Para [Str "If",Space,Str "the",Space,Str "preceding",Space,Str "paragraph",Space,Str "reads",Space,Str "\"FAIL\",",Space,Str "the",Space,Str "test",Space,Str "fails."]]
- ,Div ("styling-xhtml-004.xhtml#style-241",["section","ctest"],[])
-  [Header 3 ("",[],[]) [Span ("",["nature"],[]) [Str "[REQUIRED]"],Space,Span ("",["test-id"],[]) [Str "style-241"],Space,Code ("",[],[]) "max-device-width"]
-  ,Para [Str "Tests",Space,Str "whether",Space,Str "the",Space,Code ("",[],[]) "@media",Space,Str "rule",Space,Str "set",Space,Str "to",Space,Code ("",[],[]) "max-device-width:2000px",Space,Str "is",Space,Str "supported."]
-  ,Para [Str "FAIL"]
-  ,Para [Str "If",Space,Str "the",Space,Str "preceding",Space,Str "paragraph",Space,Str "reads",Space,Str "\"FAIL\",",Space,Str "the",Space,Str "test",Space,Str "fails."]]]
-,Para [Span ("styling-xhtml-005.xhtml",[],[]) []]
-,Div ("styling-xhtml-005.xhtml#style-text-xform",["section"],[])
- [Header 2 ("",[],[]) [Str "The",Space,Code ("",[],[]) "text-transform",Space,Str "property"]
- ,Div ("styling-xhtml-005.xhtml#style-310",["section","ctest"],[])
-  [Header 2 ("",[],[]) [Span ("",["nature"],[]) [Str "[REQUIRED]"],Space,Span ("",["test-id"],[]) [Str "style-310"],Space,Code ("",[],[]) "uppercase"]
-  ,Para [Str "Tests",Space,Str "whether",Space,Str "the",Space,Code ("",[],[]) "text-transform",Space,Str "property",Space,Str "set",Space,Str "to",Space,Str "uppercase",Space,Str "is",Space,Str "supported."]
-  ,Para [Str "Lorem",Space,Str "ipsum",Space,Str "dolor",Space,Str "sit",Space,Str "amet,",Space,Str "consectetur",Space,Str "adipisicing",Space,Str "elit,",Space,Str "sed",Space,Str "do",Space,Str "eiusmod",Space,Str "tempor",Space,Str "incididunt",Space,Str "ut",Space,Str "labore",Space,Str "et",Space,Str "dolore",Space,Str "magna",Space,Str "aliqua.",Space,Str "Ut",Space,Str "enim",Space,Str "ad",Space,Str "minim",Space,Str "veniam,",Space,Str "quis",Space,Str "nostrud",Space,Str "exercitation",Space,Str "ullamco",Space,Str "laboris",Space,Str "nisi",Space,Str "ut",Space,Str "aliquip",Space,Str "ex",Space,Str "ea",Space,Str "commodo",Space,Str "consequat.",Space,Str "Duis",Space,Str "aute",Space,Str "irure",Space,Str "dolor",Space,Str "in",Space,Str "reprehenderit",Space,Str "in",Space,Str "voluptate",Space,Str "velit",Space,Str "esse",Space,Str "cillum",Space,Str "dolore",Space,Str "eu",Space,Str "fugiat",Space,Str "nulla",Space,Str "pariatur.",Space,Str "Excepteur",Space,Str "sint",Space,Str "occaecat",Space,Str "cupidatat",Space,Str "non",Space,Str "proident,",Space,Str "sunt",Space,Str "in",Space,Str "culpa",Space,Str "qui",Space,Str "officia",Space,Str "deserunt",Space,Str "mollit",Space,Str "anim",Space,Str "id",Space,Str "est",Space,Str "laborum."]
-  ,Para [Str "If",Space,Str "the",Space,Str "preceding",Space,Str "paragraph",Space,Str "is",Space,Str "in",Space,Str "upper",Space,Str "case,",Space,Str "the",Space,Str "test",Space,Str "passes."]]
- ,Div ("styling-xhtml-005.xhtml#style-311",["section","ctest"],[])
-  [Header 2 ("",[],[]) [Span ("",["nature"],[]) [Str "[REQUIRED]"],Space,Span ("",["test-id"],[]) [Str "style-311"],Space,Code ("",[],[]) "capitalize"]
-  ,Para [Str "Tests",Space,Str "whether",Space,Str "the",Space,Code ("",[],[]) "text-transform",Space,Str "property",Space,Str "set",Space,Str "to",Space,Str "capitalize",Space,Str "is",Space,Str "supported."]
-  ,Para [Str "Lorem",Space,Str "ipsum",Space,Str "dolor",Space,Str "sit",Space,Str "amet,",Space,Str "consectetur",Space,Str "adipisicing",Space,Str "elit,",Space,Str "sed",Space,Str "do",Space,Str "eiusmod",Space,Str "tempor",Space,Str "incididunt",Space,Str "ut",Space,Str "labore",Space,Str "et",Space,Str "dolore",Space,Str "magna",Space,Str "aliqua.",Space,Str "Ut",Space,Str "enim",Space,Str "ad",Space,Str "minim",Space,Str "veniam,",Space,Str "quis",Space,Str "nostrud",Space,Str "exercitation",Space,Str "ullamco",Space,Str "laboris",Space,Str "nisi",Space,Str "ut",Space,Str "aliquip",Space,Str "ex",Space,Str "ea",Space,Str "commodo",Space,Str "consequat.",Space,Str "Duis",Space,Str "aute",Space,Str "irure",Space,Str "dolor",Space,Str "in",Space,Str "reprehenderit",Space,Str "in",Space,Str "voluptate",Space,Str "velit",Space,Str "esse",Space,Str "cillum",Space,Str "dolore",Space,Str "eu",Space,Str "fugiat",Space,Str "nulla",Space,Str "pariatur.",Space,Str "Excepteur",Space,Str "sint",Space,Str "occaecat",Space,Str "cupidatat",Space,Str "non",Space,Str "proident,",Space,Str "sunt",Space,Str "in",Space,Str "culpa",Space,Str "qui",Space,Str "officia",Space,Str "deserunt",Space,Str "mollit",Space,Str "anim",Space,Str "id",Space,Str "est",Space,Str "laborum."]
-  ,Para [Str "If",Space,Str "each",Space,Str "first",Space,Str "letter",Space,Str "of",Space,Str "each",Space,Str "word",Space,Str "in",Space,Str "the",Space,Str "preceding",Space,Str "paragraph",Space,Str "is",Space,Str "in",Space,Str "upper",Space,Str "case,",Space,Str "the",Space,Str "test",Space,Str "passes."]]
- ,Div ("styling-xhtml-005.xhtml#style-312",["section","ctest"],[])
-  [Header 2 ("",[],[]) [Span ("",["nature"],[]) [Str "[REQUIRED]"],Space,Span ("",["test-id"],[]) [Str "style-312"],Space,Code ("",[],[]) "lowercase"]
-  ,Para [Str "Tests",Space,Str "whether",Space,Str "the",Space,Code ("",[],[]) "text-transform",Space,Str "property",Space,Str "set",Space,Str "to",Space,Str "lowercase",Space,Str "is",Space,Str "supported."]
-  ,Para [Str "Lorem",Space,Str "ipsum",Space,Str "dolor",Space,Str "sit",Space,Str "amet,",Space,Str "consectetur",Space,Str "adipisicing",Space,Str "elit,",Space,Str "sed",Space,Str "do",Space,Str "eiusmod",Space,Str "tempor",Space,Str "incididunt",Space,Str "ut",Space,Str "labore",Space,Str "et",Space,Str "dolore",Space,Str "magna",Space,Str "aliqua.",Space,Str "Ut",Space,Str "enim",Space,Str "ad",Space,Str "minim",Space,Str "veniam,",Space,Str "quis",Space,Str "nostrud",Space,Str "exercitation",Space,Str "ullamco",Space,Str "laboris",Space,Str "nisi",Space,Str "ut",Space,Str "aliquip",Space,Str "ex",Space,Str "ea",Space,Str "commodo",Space,Str "consequat.",Space,Str "Duis",Space,Str "aute",Space,Str "irure",Space,Str "dolor",Space,Str "in",Space,Str "reprehenderit",Space,Str "in",Space,Str "voluptate",Space,Str "velit",Space,Str "esse",Space,Str "cillum",Space,Str "dolore",Space,Str "eu",Space,Str "fugiat",Space,Str "nulla",Space,Str "pariatur.",Space,Str "Excepteur",Space,Str "sint",Space,Str "occaecat",Space,Str "cupidatat",Space,Str "non",Space,Str "proident,",Space,Str "sunt",Space,Str "in",Space,Str "culpa",Space,Str "qui",Space,Str "officia",Space,Str "deserunt",Space,Str "mollit",Space,Str "anim",Space,Str "id",Space,Str "est",Space,Str "laborum."]
-  ,Para [Str "If",Space,Str "the",Space,Str "preceding",Space,Str "paragraph",Space,Str "is",Space,Str "in",Space,Str "lower",Space,Str "case,",Space,Str "the",Space,Str "test",Space,Str "passes."]]]
-,Para [Span ("styling-xhtml-006.xhtml",[],[]) []]
-,Div ("styling-xhtml-006.xhtml#style-ruby",["section"],[])
- [Header 2 ("",[],[]) [Str "The",Space,Code ("",[],[]) "epub-ruby-position",Space,Str "property"]
- ,Div ("styling-xhtml-006.xhtml#style-410",["section","ctest"],[])
-  [Header 2 ("",[],[]) [Span ("",["nature"],[]) [Str "[REQUIRED]"],Space,Span ("",["test-id"],[]) [Str "style-410"],Space,Code ("",[],[]) "over"]
-  ,Para [Str "Tests",Space,Str "whether",Space,Str "the",Space,Code ("",[],[]) "-epub-ruby-position",Space,Str "property",Space,Str "set",Space,Str "to",Space,Str "over",Space,Str "is",Space,Str "supported."]
-  ,Plain [RawInline (Format "html") "<ruby class=\"ruby-over\">",Strong [Str "Lorem",Space,Str "Ipsum"],Space,RawInline (Format "html") "<rp>",Str "(",RawInline (Format "html") "</rp>",RawInline (Format "html") "<rt>",Str "Lorem",Space,Str "Ipsum",RawInline (Format "html") "</rt>",RawInline (Format "html") "<rp>",Str ")",RawInline (Format "html") "</rp>",RawInline (Format "html") "</ruby>"]
-  ,Para [Str "If",Space,Str "the",Space,Str "Ruby",Space,Str "text",Space,Str "is",Space,Str "positioned",Space,Str "on",Space,Str "the",Space,Link ("",[],[]) [Str "over"] ("http://www.w3.org/TR/css3-writing-modes/#over",""),Space,Str "side",Space,Str "of",Space,Str "the",Space,Str "ruby",Space,Str "base,",Space,Str "the",Space,Str "test",Space,Str "passes."]]
- ,Div ("styling-xhtml-006.xhtml#style-411",["section","ctest"],[])
-  [Header 2 ("",[],[]) [Span ("",["nature"],[]) [Str "[REQUIRED]"],Space,Span ("",["test-id"],[]) [Str "style-411"],Space,Code ("",[],[]) "under"]
-  ,Para [Str "Tests",Space,Str "whether",Space,Str "the",Space,Code ("",[],[]) "-epub-ruby-position",Space,Str "property",Space,Str "set",Space,Str "to",Space,Str "under",Space,Str "is",Space,Str "supported."]
-  ,Plain [RawInline (Format "html") "<ruby class=\"ruby-under\">",Strong [Str "Lorem",Space,Str "Ipsum"],Space,RawInline (Format "html") "<rp>",Str "(",RawInline (Format "html") "</rp>",RawInline (Format "html") "<rt>",Str "Lorem",Space,Str "Ipsum",RawInline (Format "html") "</rt>",RawInline (Format "html") "<rp>",Str ")",RawInline (Format "html") "</rp>",RawInline (Format "html") "</ruby>"]
-  ,Para [Str "If",Space,Str "the",Space,Str "Ruby",Space,Str "text",Space,Str "is",Space,Str "positioned",Space,Str "on",Space,Str "the",Space,Link ("",[],[]) [Str "under"] ("http://www.w3.org/TR/css3-writing-modes/#under",""),Space,Str "side",Space,Str "of",Space,Str "the",Space,Str "ruby",Space,Str "base,",Space,Str "the",Space,Str "test",Space,Str "passes."]]
- ,Div ("styling-xhtml-006.xhtml#style-412",["section","ctest"],[])
-  [Header 2 ("",[],[]) [Span ("",["nature"],[]) [Str "[REQUIRED]"],Space,Span ("",["test-id"],[]) [Str "style-412"],Space,Code ("",[],[]) "inter-character"]
-  ,Para [Str "Tests",Space,Str "whether",Space,Str "the",Space,Code ("",[],[]) "-epub-ruby-position",Space,Str "property",Space,Str "set",Space,Str "to",Space,Str "inter-caracter",Space,Str "is",Space,Str "supported."]
-  ,Plain [RawInline (Format "html") "<ruby class=\"ruby-inter-character\">",Strong [Str "Lorem",Space,Str "Ipsum"],Space,RawInline (Format "html") "<rp>",Str "(",RawInline (Format "html") "</rp>",RawInline (Format "html") "<rt>",Str "Lorem",Space,Str "Ipsum",RawInline (Format "html") "</rt>",RawInline (Format "html") "<rp>",Str ")",RawInline (Format "html") "</rp>",RawInline (Format "html") "</ruby>"]
-  ,Para [Str "If",Space,Str "the",Space,Str "Ruby",Space,Str "text",Space,Str "is",Space,Str "positioned",Space,Str "on",Space,Str "the",Space,Str "right",Space,Str "side",Space,Str "of",Space,Str "the",Space,Str "base",Space,Str "text,",Space,Str "the",Space,Str "test",Space,Str "passes."]]]]
+Pandoc
+  Meta
+    { unMeta =
+        fromList
+          [ ( "author"
+            , MetaList
+                [ MetaInlines [ Str "Ori Idan" ]
+                , MetaInlines [ Str "Matt Garrish" ]
+                , MetaInlines [ Str "Marisa DeMeglio" ]
+                , MetaInlines [ Str "Toshiaki Koike" ]
+                , MetaInlines [ Str "Vincent Gros" ]
+                , MetaInlines [ Str "Markus Gylling" ]
+                ]
+            )
+          , ( "description"
+            , MetaInlines
+                [ Str "Tests for Styling [UNDER CONSTRUCTION]" ]
+            )
+          , ( "identifier"
+            , MetaInlines
+                [ Str "com.github.epub-testsuite.epub30-test-0101" ]
+            )
+          , ( "language" , MetaInlines [ Str "en" ] )
+          , ( "title"
+            , MetaInlines [ Str "EPUBTEST 0101 - Styling Tests" ]
+            )
+          ]
+    }
+  [ Para [ Span ( "front.xhtml" , [] , [] ) [] ]
+  , Div
+      ( "" , [ "section" ] , [] )
+      [ Header
+          1
+          ( "" , [] , [] )
+          [ Str "EPUB"
+          , Space
+          , Str "3"
+          , Space
+          , Str "Styling"
+          , Space
+          , Str "Test"
+          , Space
+          , Str "Document:"
+          , Space
+          , Str "0101"
+          ]
+      , Div
+          ( "" , [ "section" ] , [] )
+          [ Header
+              2
+              ( "" , [] , [] )
+              [ Str "Status"
+              , Space
+              , Str "of"
+              , Space
+              , Str "this"
+              , Space
+              , Str "Document"
+              ]
+          , Para
+              [ Str "This"
+              , Space
+              , Str "publication"
+              , Space
+              , Str "is"
+              , Space
+              , Str "currently"
+              , Space
+              , Str "considered"
+              , Space
+              , Span
+                  ( "" , [ "status" ] , [] )
+                  [ Str "[UNDER" , Space , Str "DEVELOPMENT]" ]
+              , Space
+              , Str "by"
+              , Space
+              , Str "the"
+              , Space
+              , Str "IDPF."
+              ]
+          , Para
+              [ Str "This"
+              , Space
+              , Str "publication"
+              , Space
+              , Str "is"
+              , Space
+              , Str "part"
+              , Space
+              , Str "of"
+              , Space
+              , Str "version"
+              , Space
+              , Span ( "" , [ "version" ] , [] ) [ Str "X.X" ]
+              , Space
+              , Str "of"
+              , Space
+              , Str "the"
+              , Space
+              , Str "EPUB"
+              , Space
+              , Str "3.0"
+              , Space
+              , Str "Compliance"
+              , Space
+              , Str "Test"
+              , Space
+              , Str "Suite"
+              , Space
+              , Str "released"
+              , SoftBreak
+              , Str "on"
+              , Space
+              , RawInline (Format "html") "<time class=\"release\">"
+              , Str "TBD"
+              , RawInline (Format "html") "</time>"
+              , Str "."
+              ]
+          , Para
+              [ Str "Before"
+              , Space
+              , Str "using"
+              , Space
+              , Str "this"
+              , Space
+              , Str "publication"
+              , Space
+              , Str "to"
+              , Space
+              , Str "evaluate"
+              , Space
+              , Str "reading"
+              , Space
+              , Str "systems,"
+              , Space
+              , Str "testers"
+              , Space
+              , Str "are"
+              , Space
+              , Str "strongly"
+              , Space
+              , Str "encouraged"
+              , Space
+              , Str "to"
+              , SoftBreak
+              , Str "verify"
+              , Space
+              , Str "that"
+              , Space
+              , Str "they"
+              , Space
+              , Str "have"
+              , Space
+              , Str "the"
+              , Space
+              , Str "latest"
+              , Space
+              , Str "release"
+              , Space
+              , Str "by"
+              , Space
+              , Str "checking"
+              , Space
+              , Str "the"
+              , Space
+              , Str "current"
+              , Space
+              , Str "release"
+              , Space
+              , Str "version"
+              , Space
+              , Str "and"
+              , Space
+              , Str "date"
+              , Space
+              , Str "of"
+              , SoftBreak
+              , Str "the"
+              , Space
+              , Str "test"
+              , Space
+              , Str "suite"
+              , Space
+              , Str "at"
+              , Space
+              , Link
+                  ( "" , [] , [] )
+                  [ Str "TBD" ]
+                  ( "http://idpf.org/" , "" )
+              ]
+          , Para
+              [ Str "This"
+              , Space
+              , Str "publication"
+              , Space
+              , Str "is"
+              , Space
+              , Str "one"
+              , Space
+              , Str "of"
+              , Space
+              , Str "several"
+              , Space
+              , Str "that"
+              , Space
+              , Str "currently"
+              , Space
+              , Str "comprise"
+              , Space
+              , Str "the"
+              , Space
+              , Str "EPUB"
+              , Space
+              , Str "3"
+              , Space
+              , Str "conformance"
+              , Space
+              , Str "test"
+              , Space
+              , Str "suite"
+              , SoftBreak
+              , Str "for"
+              , Space
+              , Str "reflowable"
+              , Space
+              , Str "content."
+              , Space
+              , Str "The"
+              , Space
+              , Str "complete"
+              , Space
+              , Str "test"
+              , Space
+              , Str "suite"
+              , Space
+              , Str "includes"
+              , Space
+              , Str "all"
+              , Space
+              , Str "of"
+              , Space
+              , Str "the"
+              , Space
+              , Str "following"
+              , Space
+              , Str "publications:"
+              ]
+          , OrderedList
+              ( 1 , DefaultStyle , DefaultDelim )
+              [ [ Plain [ Str "." ] ] ]
+          ]
+      , Div
+          ( "" , [ "section" ] , [] )
+          [ Header
+              2
+              ( "" , [] , [] )
+              [ Str "About"
+              , Space
+              , Str "this"
+              , Space
+              , Str "Document"
+              ]
+          , Para
+              [ Str "This"
+              , Space
+              , Str "document"
+              , Space
+              , Str "focuses"
+              , Space
+              , Str "on"
+              , Space
+              , Str "human-evaluated"
+              , Space
+              , Str "binary"
+              , Space
+              , Str "(pass/fail)"
+              , Space
+              , Str "tests"
+              , Space
+              , Str "in"
+              , Space
+              , Str "a"
+              , SoftBreak
+              , Str "reflowable"
+              , Space
+              , Str "context."
+              , Space
+              , Str "Tests"
+              , Space
+              , Str "for"
+              , Space
+              , Str "fixed-layout"
+              , Space
+              , Str "content"
+              , Space
+              , Str "and"
+              , Space
+              , Str "other"
+              , Space
+              , Str "individual"
+              , Space
+              , Str "tests"
+              , Space
+              , Str "that"
+              , SoftBreak
+              , Str "require"
+              , Space
+              , Str "a"
+              , Space
+              , Str "dedicated"
+              , Space
+              , Str "epub"
+              , Space
+              , Str "file"
+              , Space
+              , Str "are"
+              , Space
+              , Str "available"
+              , Space
+              , Str "in"
+              , Space
+              , Str "additional"
+              , Space
+              , Str "sibling"
+              , Space
+              , Str "documents;"
+              , Space
+              , Str "refer"
+              , Space
+              , Str "to"
+              , SoftBreak
+              , Str "the"
+              , Space
+              , Link
+                  ( "" , [] , [] )
+                  [ Str "test"
+                  , Space
+                  , Str "suite"
+                  , SoftBreak
+                  , Str "wiki"
+                  ]
+                  ( "https://github.com/mgylling/epub-testsuite/wiki/Overview"
+                  , ""
+                  )
+              , Space
+              , Str "("
+              , Code
+                  ( "" , [] , [] )
+                  "https://github.com/mgylling/epub-testsuite/wiki/Overview"
+              , Str ")"
+              , Space
+              , Str "for"
+              , Space
+              , Str "additional"
+              , SoftBreak
+              , Str "information."
+              ]
+          ]
+      , Div
+          ( "" , [ "section" ] , [] )
+          [ Header 2 ( "" , [] , [] ) [ Str "Conventions" ]
+          , Para
+              [ Str "The"
+              , Space
+              , Str "following"
+              , Space
+              , Str "conventions"
+              , Space
+              , Str "are"
+              , Space
+              , Str "used"
+              , Space
+              , Str "throughout"
+              , Space
+              , Str "the"
+              , Space
+              , Str "document:"
+              ]
+          , DefinitionList
+              [ ( [ Str "1."
+                  , Space
+                  , Str "Locating"
+                  , Space
+                  , Str "a"
+                  , Space
+                  , Str "test"
+                  ]
+                , [ [ Div
+                        ( "" , [ "ctest" ] , [] )
+                        [ Para
+                            [ Str "Tests"
+                            , Space
+                            , Str "for"
+                            , Space
+                            , Emph [ Str "required" ]
+                            , Space
+                            , Str "Reading"
+                            , Space
+                            , Str "System"
+                            , Space
+                            , Str "functionality"
+                            , Space
+                            , Str "are"
+                            , SoftBreak
+                            , Str "preceded"
+                            , Space
+                            , Str "by"
+                            , Space
+                            , Str "the"
+                            , Space
+                            , Str "label:"
+                            , Space
+                            , Span
+                                ( ""
+                                , [ "nature" ]
+                                , [ ( "style"
+                                    , "display: inline; font-size: 100%"
+                                    )
+                                  ]
+                                )
+                                [ Str "[REQUIRED]" ]
+                            ]
+                        ]
+                    , Div
+                        ( "" , [ "otest" ] , [] )
+                        [ Para
+                            [ Str "Tests"
+                            , Space
+                            , Str "for"
+                            , Space
+                            , Emph [ Str "optional" ]
+                            , Space
+                            , Str "Reading"
+                            , Space
+                            , Str "System"
+                            , Space
+                            , Str "functionality"
+                            , Space
+                            , Str "are"
+                            , SoftBreak
+                            , Str "preceded"
+                            , Space
+                            , Str "by"
+                            , Space
+                            , Str "the"
+                            , Space
+                            , Str "label:"
+                            , Space
+                            , Span
+                                ( ""
+                                , [ "nature" ]
+                                , [ ( "style"
+                                    , "display: inline; font-size: 100%"
+                                    )
+                                  ]
+                                )
+                                [ Str "[OPTIONAL]" ]
+                            ]
+                        ]
+                    ]
+                  ]
+                )
+              , ( [ Str "2."
+                  , Space
+                  , Str "Performing"
+                  , Space
+                  , Str "the"
+                  , Space
+                  , Str "test"
+                  ]
+                , [ [ Plain
+                        [ Str "Each"
+                        , Space
+                        , Str "test"
+                        , Space
+                        , Str "includes"
+                        , Space
+                        , Str "a"
+                        , Space
+                        , Str "description"
+                        , Space
+                        , Str "of"
+                        , Space
+                        , Str "its"
+                        , Space
+                        , Str "purpose"
+                        , Space
+                        , Str "followed"
+                        , Space
+                        , Str "by"
+                        , Space
+                        , Str "the"
+                        , Space
+                        , Str "actual"
+                        , Space
+                        , Strong
+                            [ Str "test"
+                            , Space
+                            , Str "statement,"
+                            , SoftBreak
+                            , Str "which"
+                            , Space
+                            , Str "can"
+                            , Space
+                            , Str "always"
+                            , Space
+                            , Str "be"
+                            , Space
+                            , Str "evaluated"
+                            , Space
+                            , Str "to"
+                            , Space
+                            , Str "true"
+                            , Space
+                            , Str "or"
+                            , Space
+                            , Str "false"
+                            ]
+                        , Str "."
+                        , Space
+                        , Str "These"
+                        , Space
+                        , Str "statements"
+                        , Space
+                        , Str "typically"
+                        , Space
+                        , Str "have"
+                        , Space
+                        , Str "the"
+                        , Space
+                        , Str "form:"
+                        , SoftBreak
+                        , Str "\"If"
+                        , Space
+                        , Str "[some"
+                        , Space
+                        , Str "condition],"
+                        , Space
+                        , Str "the"
+                        , Space
+                        , Str "test"
+                        , Space
+                        , Str "passes\"."
+                        ]
+                    ]
+                  ]
+                )
+              , ( [ Str "3."
+                  , Space
+                  , Str "Scoring"
+                  , Space
+                  , Str "in"
+                  , Space
+                  , Str "the"
+                  , Space
+                  , Str "results"
+                  , Space
+                  , Str "form"
+                  ]
+                , [ [ Plain
+                        [ Str "@@@TODO"
+                        , Space
+                        , Str "provide"
+                        , Space
+                        , Str "info"
+                        , Space
+                        , Str "on"
+                        , Space
+                        , Str "where"
+                        , Space
+                        , Str "to"
+                        , Space
+                        , Str "get"
+                        , Space
+                        , Str "the"
+                        , Space
+                        , Str "results"
+                        , Space
+                        , Str "form"
+                        ]
+                    ]
+                  ]
+                )
+              ]
+          ]
+      ]
+  , Para [ Span ( "styling-xhtml-001.xhtml" , [] , [] ) [] ]
+  , Div
+      ( "styling-xhtml-001.xhtml_epub-css" , [ "section" ] , [] )
+      [ Header
+          1
+          ( "" , [] , [] )
+          [ Str "EPUB" , Space , Str "Style" , Space , Str "Sheets" ]
+      , Para
+          [ Str "This"
+          , Space
+          , Str "section"
+          , Space
+          , Str "contains"
+          , Space
+          , Str "tests"
+          , Space
+          , Str "for"
+          , Space
+          , Str "styling"
+          , Space
+          , Str "and"
+          , Space
+          , Str "layout."
+          ]
+      ]
+  , Para [ Span ( "styling-xhtml-003.xhtml" , [] , [] ) [] ]
+  , Div
+      ( "styling-xhtml-003.xhtml_style-110"
+      , [ "section" , "ctest" ]
+      , []
+      )
+      [ Header
+          2
+          ( "" , [] , [] )
+          [ Span ( "" , [ "nature" ] , [] ) [ Str "[REQUIRED]" ]
+          , Space
+          , Span ( "" , [ "test-id" ] , [] ) [ Str "style-110" ]
+          , Space
+          , Str "Multi-Column"
+          , Space
+          , Str "Layouts"
+          ]
+      , Para
+          [ Str "Tests"
+          , Space
+          , Str "whether"
+          , Space
+          , Str "the"
+          , Space
+          , Link
+              ( "" , [] , [] )
+              [ Code ( "" , [] , [] ) "CSS Multi-Column Layout" ]
+              ( "http://idpf.org/epub/30/spec/epub30-contentdocs.html#sec-css-multi-column"
+              , ""
+              )
+          , Space
+          , Str "properties"
+          , Space
+          , Str "are"
+          , Space
+          , Str "supported."
+          ]
+      , Div
+          ( "" , [ "multicol" ] , [] )
+          [ Para
+              [ Str "Lorem"
+              , Space
+              , Str "ipsum"
+              , Space
+              , Str "dolor"
+              , Space
+              , Str "sit"
+              , Space
+              , Str "amet,"
+              , Space
+              , Str "consectetur"
+              , Space
+              , Str "adipisicing"
+              , Space
+              , Str "elit,"
+              , Space
+              , Str "sed"
+              , Space
+              , Str "do"
+              , Space
+              , Str "eiusmod"
+              , Space
+              , Str "tempor"
+              , Space
+              , Str "incididunt"
+              , Space
+              , Str "ut"
+              , Space
+              , Str "labore"
+              , Space
+              , Str "et"
+              , Space
+              , Str "dolore"
+              , Space
+              , Str "magna"
+              , Space
+              , Str "aliqua."
+              , Space
+              , Str "Ut"
+              , Space
+              , Str "enim"
+              , Space
+              , Str "ad"
+              , Space
+              , Str "minim"
+              , Space
+              , Str "veniam,"
+              , Space
+              , Str "quis"
+              , Space
+              , Str "nostrud"
+              , Space
+              , Str "exercitation"
+              , Space
+              , Str "ullamco"
+              , Space
+              , Str "laboris"
+              , Space
+              , Str "nisi"
+              , Space
+              , Str "ut"
+              , Space
+              , Str "aliquip"
+              , Space
+              , Str "ex"
+              , Space
+              , Str "ea"
+              , Space
+              , Str "commodo"
+              , Space
+              , Str "consequat."
+              , Space
+              , Str "Duis"
+              , Space
+              , Str "aute"
+              , Space
+              , Str "irure"
+              , Space
+              , Str "dolor"
+              , Space
+              , Str "in"
+              , Space
+              , Str "reprehenderit"
+              , Space
+              , Str "in"
+              , Space
+              , Str "voluptate"
+              , Space
+              , Str "velit"
+              , Space
+              , Str "esse"
+              , Space
+              , Str "cillum"
+              , Space
+              , Str "dolore"
+              , Space
+              , Str "eu"
+              , Space
+              , Str "fugiat"
+              , Space
+              , Str "nulla"
+              , Space
+              , Str "pariatur."
+              , Space
+              , Str "Excepteur"
+              , Space
+              , Str "sint"
+              , Space
+              , Str "occaecat"
+              , Space
+              , Str "cupidatat"
+              , Space
+              , Str "non"
+              , Space
+              , Str "proident,"
+              , Space
+              , Str "sunt"
+              , Space
+              , Str "in"
+              , Space
+              , Str "culpa"
+              , Space
+              , Str "qui"
+              , Space
+              , Str "officia"
+              , Space
+              , Str "deserunt"
+              , Space
+              , Str "mollit"
+              , Space
+              , Str "anim"
+              , Space
+              , Str "id"
+              , Space
+              , Str "est"
+              , Space
+              , Str "laborum."
+              ]
+          , Para
+              [ Str "Lorem"
+              , Space
+              , Str "ipsum"
+              , Space
+              , Str "dolor"
+              , Space
+              , Str "sit"
+              , Space
+              , Str "amet,"
+              , Space
+              , Str "consectetur"
+              , Space
+              , Str "adipisicing"
+              , Space
+              , Str "elit,"
+              , Space
+              , Str "sed"
+              , Space
+              , Str "do"
+              , Space
+              , Str "eiusmod"
+              , Space
+              , Str "tempor"
+              , Space
+              , Str "incididunt"
+              , Space
+              , Str "ut"
+              , Space
+              , Str "labore"
+              , Space
+              , Str "et"
+              , Space
+              , Str "dolore"
+              , Space
+              , Str "magna"
+              , Space
+              , Str "aliqua."
+              , Space
+              , Str "Ut"
+              , Space
+              , Str "enim"
+              , Space
+              , Str "ad"
+              , Space
+              , Str "minim"
+              , Space
+              , Str "veniam,"
+              , Space
+              , Str "quis"
+              , Space
+              , Str "nostrud"
+              , Space
+              , Str "exercitation"
+              , Space
+              , Str "ullamco"
+              , Space
+              , Str "laboris"
+              , Space
+              , Str "nisi"
+              , Space
+              , Str "ut"
+              , Space
+              , Str "aliquip"
+              , Space
+              , Str "ex"
+              , Space
+              , Str "ea"
+              , Space
+              , Str "commodo"
+              , Space
+              , Str "consequat."
+              , Space
+              , Str "Duis"
+              , Space
+              , Str "aute"
+              , Space
+              , Str "irure"
+              , Space
+              , Str "dolor"
+              , Space
+              , Str "in"
+              , Space
+              , Str "reprehenderit"
+              , Space
+              , Str "in"
+              , Space
+              , Str "voluptate"
+              , Space
+              , Str "velit"
+              , Space
+              , Str "esse"
+              , Space
+              , Str "cillum"
+              , Space
+              , Str "dolore"
+              , Space
+              , Str "eu"
+              , Space
+              , Str "fugiat"
+              , Space
+              , Str "nulla"
+              , Space
+              , Str "pariatur."
+              , Space
+              , Str "Excepteur"
+              , Space
+              , Str "sint"
+              , Space
+              , Str "occaecat"
+              , Space
+              , Str "cupidatat"
+              , Space
+              , Str "non"
+              , Space
+              , Str "proident,"
+              , Space
+              , Str "sunt"
+              , Space
+              , Str "in"
+              , Space
+              , Str "culpa"
+              , Space
+              , Str "qui"
+              , Space
+              , Str "officia"
+              , Space
+              , Str "deserunt"
+              , Space
+              , Str "mollit"
+              , Space
+              , Str "anim"
+              , Space
+              , Str "id"
+              , Space
+              , Str "est"
+              , Space
+              , Str "laborum."
+              ]
+          , Para
+              [ Str "Lorem"
+              , Space
+              , Str "ipsum"
+              , Space
+              , Str "dolor"
+              , Space
+              , Str "sit"
+              , Space
+              , Str "amet,"
+              , Space
+              , Str "consectetur"
+              , Space
+              , Str "adipisicing"
+              , Space
+              , Str "elit,"
+              , Space
+              , Str "sed"
+              , Space
+              , Str "do"
+              , Space
+              , Str "eiusmod"
+              , Space
+              , Str "tempor"
+              , Space
+              , Str "incididunt"
+              , Space
+              , Str "ut"
+              , Space
+              , Str "labore"
+              , Space
+              , Str "et"
+              , Space
+              , Str "dolore"
+              , Space
+              , Str "magna"
+              , Space
+              , Str "aliqua."
+              , Space
+              , Str "Ut"
+              , Space
+              , Str "enim"
+              , Space
+              , Str "ad"
+              , Space
+              , Str "minim"
+              , Space
+              , Str "veniam,"
+              , Space
+              , Str "quis"
+              , Space
+              , Str "nostrud"
+              , Space
+              , Str "exercitation"
+              , Space
+              , Str "ullamco"
+              , Space
+              , Str "laboris"
+              , Space
+              , Str "nisi"
+              , Space
+              , Str "ut"
+              , Space
+              , Str "aliquip"
+              , Space
+              , Str "ex"
+              , Space
+              , Str "ea"
+              , Space
+              , Str "commodo"
+              , Space
+              , Str "consequat."
+              , Space
+              , Str "Duis"
+              , Space
+              , Str "aute"
+              , Space
+              , Str "irure"
+              , Space
+              , Str "dolor"
+              , Space
+              , Str "in"
+              , Space
+              , Str "reprehenderit"
+              , Space
+              , Str "in"
+              , Space
+              , Str "voluptate"
+              , Space
+              , Str "velit"
+              , Space
+              , Str "esse"
+              , Space
+              , Str "cillum"
+              , Space
+              , Str "dolore"
+              , Space
+              , Str "eu"
+              , Space
+              , Str "fugiat"
+              , Space
+              , Str "nulla"
+              , Space
+              , Str "pariatur."
+              , Space
+              , Str "Excepteur"
+              , Space
+              , Str "sint"
+              , Space
+              , Str "occaecat"
+              , Space
+              , Str "cupidatat"
+              , Space
+              , Str "non"
+              , Space
+              , Str "proident,"
+              , Space
+              , Str "sunt"
+              , Space
+              , Str "in"
+              , Space
+              , Str "culpa"
+              , Space
+              , Str "qui"
+              , Space
+              , Str "officia"
+              , Space
+              , Str "deserunt"
+              , Space
+              , Str "mollit"
+              , Space
+              , Str "anim"
+              , Space
+              , Str "id"
+              , Space
+              , Str "est"
+              , Space
+              , Str "laborum."
+              ]
+          , Para
+              [ Str "Lorem"
+              , Space
+              , Str "ipsum"
+              , Space
+              , Str "dolor"
+              , Space
+              , Str "sit"
+              , Space
+              , Str "amet,"
+              , Space
+              , Str "consectetur"
+              , Space
+              , Str "adipisicing"
+              , Space
+              , Str "elit,"
+              , Space
+              , Str "sed"
+              , Space
+              , Str "do"
+              , Space
+              , Str "eiusmod"
+              , Space
+              , Str "tempor"
+              , Space
+              , Str "incididunt"
+              , Space
+              , Str "ut"
+              , Space
+              , Str "labore"
+              , Space
+              , Str "et"
+              , Space
+              , Str "dolore"
+              , Space
+              , Str "magna"
+              , Space
+              , Str "aliqua."
+              , Space
+              , Str "Ut"
+              , Space
+              , Str "enim"
+              , Space
+              , Str "ad"
+              , Space
+              , Str "minim"
+              , Space
+              , Str "veniam,"
+              , Space
+              , Str "quis"
+              , Space
+              , Str "nostrud"
+              , Space
+              , Str "exercitation"
+              , Space
+              , Str "ullamco"
+              , Space
+              , Str "laboris"
+              , Space
+              , Str "nisi"
+              , Space
+              , Str "ut"
+              , Space
+              , Str "aliquip"
+              , Space
+              , Str "ex"
+              , Space
+              , Str "ea"
+              , Space
+              , Str "commodo"
+              , Space
+              , Str "consequat."
+              , Space
+              , Str "Duis"
+              , Space
+              , Str "aute"
+              , Space
+              , Str "irure"
+              , Space
+              , Str "dolor"
+              , Space
+              , Str "in"
+              , Space
+              , Str "reprehenderit"
+              , Space
+              , Str "in"
+              , Space
+              , Str "voluptate"
+              , Space
+              , Str "velit"
+              , Space
+              , Str "esse"
+              , Space
+              , Str "cillum"
+              , Space
+              , Str "dolore"
+              , Space
+              , Str "eu"
+              , Space
+              , Str "fugiat"
+              , Space
+              , Str "nulla"
+              , Space
+              , Str "pariatur."
+              , Space
+              , Str "Excepteur"
+              , Space
+              , Str "sint"
+              , Space
+              , Str "occaecat"
+              , Space
+              , Str "cupidatat"
+              , Space
+              , Str "non"
+              , Space
+              , Str "proident,"
+              , Space
+              , Str "sunt"
+              , Space
+              , Str "in"
+              , Space
+              , Str "culpa"
+              , Space
+              , Str "qui"
+              , Space
+              , Str "officia"
+              , Space
+              , Str "deserunt"
+              , Space
+              , Str "mollit"
+              , Space
+              , Str "anim"
+              , Space
+              , Str "id"
+              , Space
+              , Str "est"
+              , Space
+              , Str "laborum."
+              ]
+          , Para
+              [ Str "Lorem"
+              , Space
+              , Str "ipsum"
+              , Space
+              , Str "dolor"
+              , Space
+              , Str "sit"
+              , Space
+              , Str "amet,"
+              , Space
+              , Str "consectetur"
+              , Space
+              , Str "adipisicing"
+              , Space
+              , Str "elit,"
+              , Space
+              , Str "sed"
+              , Space
+              , Str "do"
+              , Space
+              , Str "eiusmod"
+              , Space
+              , Str "tempor"
+              , Space
+              , Str "incididunt"
+              , Space
+              , Str "ut"
+              , Space
+              , Str "labore"
+              , Space
+              , Str "et"
+              , Space
+              , Str "dolore"
+              , Space
+              , Str "magna"
+              , Space
+              , Str "aliqua."
+              , Space
+              , Str "Ut"
+              , Space
+              , Str "enim"
+              , Space
+              , Str "ad"
+              , Space
+              , Str "minim"
+              , Space
+              , Str "veniam,"
+              , Space
+              , Str "quis"
+              , Space
+              , Str "nostrud"
+              , Space
+              , Str "exercitation"
+              , Space
+              , Str "ullamco"
+              , Space
+              , Str "laboris"
+              , Space
+              , Str "nisi"
+              , Space
+              , Str "ut"
+              , Space
+              , Str "aliquip"
+              , Space
+              , Str "ex"
+              , Space
+              , Str "ea"
+              , Space
+              , Str "commodo"
+              , Space
+              , Str "consequat."
+              , Space
+              , Str "Duis"
+              , Space
+              , Str "aute"
+              , Space
+              , Str "irure"
+              , Space
+              , Str "dolor"
+              , Space
+              , Str "in"
+              , Space
+              , Str "reprehenderit"
+              , Space
+              , Str "in"
+              , Space
+              , Str "voluptate"
+              , Space
+              , Str "velit"
+              , Space
+              , Str "esse"
+              , Space
+              , Str "cillum"
+              , Space
+              , Str "dolore"
+              , Space
+              , Str "eu"
+              , Space
+              , Str "fugiat"
+              , Space
+              , Str "nulla"
+              , Space
+              , Str "pariatur."
+              , Space
+              , Str "Excepteur"
+              , Space
+              , Str "sint"
+              , Space
+              , Str "occaecat"
+              , Space
+              , Str "cupidatat"
+              , Space
+              , Str "non"
+              , Space
+              , Str "proident,"
+              , Space
+              , Str "sunt"
+              , Space
+              , Str "in"
+              , Space
+              , Str "culpa"
+              , Space
+              , Str "qui"
+              , Space
+              , Str "officia"
+              , Space
+              , Str "deserunt"
+              , Space
+              , Str "mollit"
+              , Space
+              , Str "anim"
+              , Space
+              , Str "id"
+              , Space
+              , Str "est"
+              , Space
+              , Str "laborum."
+              ]
+          , Para
+              [ Str "Lorem"
+              , Space
+              , Str "ipsum"
+              , Space
+              , Str "dolor"
+              , Space
+              , Str "sit"
+              , Space
+              , Str "amet,"
+              , Space
+              , Str "consectetur"
+              , Space
+              , Str "adipisicing"
+              , Space
+              , Str "elit,"
+              , Space
+              , Str "sed"
+              , Space
+              , Str "do"
+              , Space
+              , Str "eiusmod"
+              , Space
+              , Str "tempor"
+              , Space
+              , Str "incididunt"
+              , Space
+              , Str "ut"
+              , Space
+              , Str "labore"
+              , Space
+              , Str "et"
+              , Space
+              , Str "dolore"
+              , Space
+              , Str "magna"
+              , Space
+              , Str "aliqua."
+              , Space
+              , Str "Ut"
+              , Space
+              , Str "enim"
+              , Space
+              , Str "ad"
+              , Space
+              , Str "minim"
+              , Space
+              , Str "veniam,"
+              , Space
+              , Str "quis"
+              , Space
+              , Str "nostrud"
+              , Space
+              , Str "exercitation"
+              , Space
+              , Str "ullamco"
+              , Space
+              , Str "laboris"
+              , Space
+              , Str "nisi"
+              , Space
+              , Str "ut"
+              , Space
+              , Str "aliquip"
+              , Space
+              , Str "ex"
+              , Space
+              , Str "ea"
+              , Space
+              , Str "commodo"
+              , Space
+              , Str "consequat."
+              , Space
+              , Str "Duis"
+              , Space
+              , Str "aute"
+              , Space
+              , Str "irure"
+              , Space
+              , Str "dolor"
+              , Space
+              , Str "in"
+              , Space
+              , Str "reprehenderit"
+              , Space
+              , Str "in"
+              , Space
+              , Str "voluptate"
+              , Space
+              , Str "velit"
+              , Space
+              , Str "esse"
+              , Space
+              , Str "cillum"
+              , Space
+              , Str "dolore"
+              , Space
+              , Str "eu"
+              , Space
+              , Str "fugiat"
+              , Space
+              , Str "nulla"
+              , Space
+              , Str "pariatur."
+              , Space
+              , Str "Excepteur"
+              , Space
+              , Str "sint"
+              , Space
+              , Str "occaecat"
+              , Space
+              , Str "cupidatat"
+              , Space
+              , Str "non"
+              , Space
+              , Str "proident,"
+              , Space
+              , Str "sunt"
+              , Space
+              , Str "in"
+              , Space
+              , Str "culpa"
+              , Space
+              , Str "qui"
+              , Space
+              , Str "officia"
+              , Space
+              , Str "deserunt"
+              , Space
+              , Str "mollit"
+              , Space
+              , Str "anim"
+              , Space
+              , Str "id"
+              , Space
+              , Str "est"
+              , Space
+              , Str "laborum."
+              ]
+          , Para
+              [ Str "Lorem"
+              , Space
+              , Str "ipsum"
+              , Space
+              , Str "dolor"
+              , Space
+              , Str "sit"
+              , Space
+              , Str "amet,"
+              , Space
+              , Str "consectetur"
+              , Space
+              , Str "adipisicing"
+              , Space
+              , Str "elit,"
+              , Space
+              , Str "sed"
+              , Space
+              , Str "do"
+              , Space
+              , Str "eiusmod"
+              , Space
+              , Str "tempor"
+              , Space
+              , Str "incididunt"
+              , Space
+              , Str "ut"
+              , Space
+              , Str "labore"
+              , Space
+              , Str "et"
+              , Space
+              , Str "dolore"
+              , Space
+              , Str "magna"
+              , Space
+              , Str "aliqua."
+              , Space
+              , Str "Ut"
+              , Space
+              , Str "enim"
+              , Space
+              , Str "ad"
+              , Space
+              , Str "minim"
+              , Space
+              , Str "veniam,"
+              , Space
+              , Str "quis"
+              , Space
+              , Str "nostrud"
+              , Space
+              , Str "exercitation"
+              , Space
+              , Str "ullamco"
+              , Space
+              , Str "laboris"
+              , Space
+              , Str "nisi"
+              , Space
+              , Str "ut"
+              , Space
+              , Str "aliquip"
+              , Space
+              , Str "ex"
+              , Space
+              , Str "ea"
+              , Space
+              , Str "commodo"
+              , Space
+              , Str "consequat."
+              , Space
+              , Str "Duis"
+              , Space
+              , Str "aute"
+              , Space
+              , Str "irure"
+              , Space
+              , Str "dolor"
+              , Space
+              , Str "in"
+              , Space
+              , Str "reprehenderit"
+              , Space
+              , Str "in"
+              , Space
+              , Str "voluptate"
+              , Space
+              , Str "velit"
+              , Space
+              , Str "esse"
+              , Space
+              , Str "cillum"
+              , Space
+              , Str "dolore"
+              , Space
+              , Str "eu"
+              , Space
+              , Str "fugiat"
+              , Space
+              , Str "nulla"
+              , Space
+              , Str "pariatur."
+              , Space
+              , Str "Excepteur"
+              , Space
+              , Str "sint"
+              , Space
+              , Str "occaecat"
+              , Space
+              , Str "cupidatat"
+              , Space
+              , Str "non"
+              , Space
+              , Str "proident,"
+              , Space
+              , Str "sunt"
+              , Space
+              , Str "in"
+              , Space
+              , Str "culpa"
+              , Space
+              , Str "qui"
+              , Space
+              , Str "officia"
+              , Space
+              , Str "deserunt"
+              , Space
+              , Str "mollit"
+              , Space
+              , Str "anim"
+              , Space
+              , Str "id"
+              , Space
+              , Str "est"
+              , Space
+              , Str "laborum."
+              ]
+          , Para
+              [ Str "Lorem"
+              , Space
+              , Str "ipsum"
+              , Space
+              , Str "dolor"
+              , Space
+              , Str "sit"
+              , Space
+              , Str "amet,"
+              , Space
+              , Str "consectetur"
+              , Space
+              , Str "adipisicing"
+              , Space
+              , Str "elit,"
+              , Space
+              , Str "sed"
+              , Space
+              , Str "do"
+              , Space
+              , Str "eiusmod"
+              , Space
+              , Str "tempor"
+              , Space
+              , Str "incididunt"
+              , Space
+              , Str "ut"
+              , Space
+              , Str "labore"
+              , Space
+              , Str "et"
+              , Space
+              , Str "dolore"
+              , Space
+              , Str "magna"
+              , Space
+              , Str "aliqua."
+              , Space
+              , Str "Ut"
+              , Space
+              , Str "enim"
+              , Space
+              , Str "ad"
+              , Space
+              , Str "minim"
+              , Space
+              , Str "veniam,"
+              , Space
+              , Str "quis"
+              , Space
+              , Str "nostrud"
+              , Space
+              , Str "exercitation"
+              , Space
+              , Str "ullamco"
+              , Space
+              , Str "laboris"
+              , Space
+              , Str "nisi"
+              , Space
+              , Str "ut"
+              , Space
+              , Str "aliquip"
+              , Space
+              , Str "ex"
+              , Space
+              , Str "ea"
+              , Space
+              , Str "commodo"
+              , Space
+              , Str "consequat."
+              , Space
+              , Str "Duis"
+              , Space
+              , Str "aute"
+              , Space
+              , Str "irure"
+              , Space
+              , Str "dolor"
+              , Space
+              , Str "in"
+              , Space
+              , Str "reprehenderit"
+              , Space
+              , Str "in"
+              , Space
+              , Str "voluptate"
+              , Space
+              , Str "velit"
+              , Space
+              , Str "esse"
+              , Space
+              , Str "cillum"
+              , Space
+              , Str "dolore"
+              , Space
+              , Str "eu"
+              , Space
+              , Str "fugiat"
+              , Space
+              , Str "nulla"
+              , Space
+              , Str "pariatur."
+              , Space
+              , Str "Excepteur"
+              , Space
+              , Str "sint"
+              , Space
+              , Str "occaecat"
+              , Space
+              , Str "cupidatat"
+              , Space
+              , Str "non"
+              , Space
+              , Str "proident,"
+              , Space
+              , Str "sunt"
+              , Space
+              , Str "in"
+              , Space
+              , Str "culpa"
+              , Space
+              , Str "qui"
+              , Space
+              , Str "officia"
+              , Space
+              , Str "deserunt"
+              , Space
+              , Str "mollit"
+              , Space
+              , Str "anim"
+              , Space
+              , Str "id"
+              , Space
+              , Str "est"
+              , Space
+              , Str "laborum."
+              ]
+          , Para
+              [ Str "Lorem"
+              , Space
+              , Str "ipsum"
+              , Space
+              , Str "dolor"
+              , Space
+              , Str "sit"
+              , Space
+              , Str "amet,"
+              , Space
+              , Str "consectetur"
+              , Space
+              , Str "adipisicing"
+              , Space
+              , Str "elit,"
+              , Space
+              , Str "sed"
+              , Space
+              , Str "do"
+              , Space
+              , Str "eiusmod"
+              , Space
+              , Str "tempor"
+              , Space
+              , Str "incididunt"
+              , Space
+              , Str "ut"
+              , Space
+              , Str "labore"
+              , Space
+              , Str "et"
+              , Space
+              , Str "dolore"
+              , Space
+              , Str "magna"
+              , Space
+              , Str "aliqua."
+              , Space
+              , Str "Ut"
+              , Space
+              , Str "enim"
+              , Space
+              , Str "ad"
+              , Space
+              , Str "minim"
+              , Space
+              , Str "veniam,"
+              , Space
+              , Str "quis"
+              , Space
+              , Str "nostrud"
+              , Space
+              , Str "exercitation"
+              , Space
+              , Str "ullamco"
+              , Space
+              , Str "laboris"
+              , Space
+              , Str "nisi"
+              , Space
+              , Str "ut"
+              , Space
+              , Str "aliquip"
+              , Space
+              , Str "ex"
+              , Space
+              , Str "ea"
+              , Space
+              , Str "commodo"
+              , Space
+              , Str "consequat."
+              , Space
+              , Str "Duis"
+              , Space
+              , Str "aute"
+              , Space
+              , Str "irure"
+              , Space
+              , Str "dolor"
+              , Space
+              , Str "in"
+              , Space
+              , Str "reprehenderit"
+              , Space
+              , Str "in"
+              , Space
+              , Str "voluptate"
+              , Space
+              , Str "velit"
+              , Space
+              , Str "esse"
+              , Space
+              , Str "cillum"
+              , Space
+              , Str "dolore"
+              , Space
+              , Str "eu"
+              , Space
+              , Str "fugiat"
+              , Space
+              , Str "nulla"
+              , Space
+              , Str "pariatur."
+              , Space
+              , Str "Excepteur"
+              , Space
+              , Str "sint"
+              , Space
+              , Str "occaecat"
+              , Space
+              , Str "cupidatat"
+              , Space
+              , Str "non"
+              , Space
+              , Str "proident,"
+              , Space
+              , Str "sunt"
+              , Space
+              , Str "in"
+              , Space
+              , Str "culpa"
+              , Space
+              , Str "qui"
+              , Space
+              , Str "officia"
+              , Space
+              , Str "deserunt"
+              , Space
+              , Str "mollit"
+              , Space
+              , Str "anim"
+              , Space
+              , Str "id"
+              , Space
+              , Str "est"
+              , Space
+              , Str "laborum."
+              ]
+          ]
+      , Para
+          [ Str "If"
+          , Space
+          , Str "the"
+          , Space
+          , Str "preceding"
+          , Space
+          , Str "text"
+          , Space
+          , Str "is"
+          , Space
+          , Str "rendered"
+          , Space
+          , Str "in"
+          , Space
+          , Str "three"
+          , Space
+          , Str "columns,"
+          , Space
+          , Str "the"
+          , Space
+          , Str "test"
+          , Space
+          , Str "passes."
+          ]
+      ]
+  , Para [ Span ( "styling-xhtml-002.xhtml" , [] , [] ) [] ]
+  , Div
+      ( "styling-xhtml-002.xhtml_style-lists"
+      , [ "section" ]
+      , []
+      )
+      [ Header 2 ( "" , [] , [] ) [ Str "Lists" ]
+      , Div
+          ( "styling-xhtml-002.xhtml_style-list-style-type"
+          , [ "section" ]
+          , []
+          )
+          [ Header
+              3
+              ( "" , [] , [] )
+              [ Str "The"
+              , Space
+              , Code ( "" , [] , [] ) "list-style-type"
+              , Space
+              , Str "property"
+              ]
+          , Div
+              ( "styling-xhtml-002.xhtml_style-009"
+              , [ "section" , "ctest" ]
+              , []
+              )
+              [ Header
+                  4
+                  ( "" , [] , [] )
+                  [ Span ( "" , [ "nature" ] , [] ) [ Str "[REQUIRED]" ]
+                  , Space
+                  , Span ( "" , [ "test-id" ] , [] ) [ Str "style-009" ]
+                  , Space
+                  , Code ( "" , [] , [] ) "decimal"
+                  ]
+              , Para
+                  [ Str "Tests"
+                  , Space
+                  , Str "whether"
+                  , Space
+                  , Str "the"
+                  , Space
+                  , Code ( "" , [] , [] ) "list-style-type"
+                  , Space
+                  , Str "property"
+                  , Space
+                  , Str "set"
+                  , Space
+                  , Str "to"
+                  , Space
+                  , Code ( "" , [] , [] ) "decimal"
+                  , Space
+                  , Str "is"
+                  , Space
+                  , Str "supported"
+                  , Space
+                  , Str "on"
+                  , Space
+                  , Str "a"
+                  , Space
+                  , Code ( "" , [] , [] ) "ol"
+                  , Space
+                  , Str "element."
+                  ]
+              , OrderedList
+                  ( 1 , DefaultStyle , DefaultDelim )
+                  [ [ Plain [ Str "Lorem" ] ]
+                  , [ Plain [ Str "Ipsum" ] ]
+                  , [ Plain [ Str "Dolor" ] ]
+                  , [ Plain [ Str "Sit" ] ]
+                  , [ Plain [ Str "Amet" ] ]
+                  ]
+              , Para
+                  [ Str "If"
+                  , Space
+                  , Str "the"
+                  , Space
+                  , Str "preceding"
+                  , Space
+                  , Str "list"
+                  , Space
+                  , Str "has"
+                  , Space
+                  , Str "decimal"
+                  , Space
+                  , Str "markers"
+                  , Space
+                  , Str "in"
+                  , Space
+                  , Str "ascending"
+                  , Space
+                  , Str "order,"
+                  , Space
+                  , Str "the"
+                  , Space
+                  , Str "test"
+                  , Space
+                  , Str "passes."
+                  ]
+              ]
+          , Div
+              ( "styling-xhtml-002.xhtml_style-010"
+              , [ "section" , "ctest" ]
+              , []
+              )
+              [ Header
+                  4
+                  ( "" , [] , [] )
+                  [ Span ( "" , [ "nature" ] , [] ) [ Str "[REQUIRED]" ]
+                  , Space
+                  , Span ( "" , [ "test-id" ] , [] ) [ Str "style-010" ]
+                  , Space
+                  , Code ( "" , [] , [] ) "circle"
+                  ]
+              , Para
+                  [ Str "Tests"
+                  , Space
+                  , Str "whether"
+                  , Space
+                  , Str "the"
+                  , Space
+                  , Code ( "" , [] , [] ) "list-style-type"
+                  , Space
+                  , Str "property"
+                  , Space
+                  , Str "set"
+                  , Space
+                  , Str "to"
+                  , Space
+                  , Code ( "" , [] , [] ) "circle"
+                  , Space
+                  , Str "is"
+                  , Space
+                  , Str "supported"
+                  , Space
+                  , Str "on"
+                  , Space
+                  , Str "a"
+                  , Space
+                  , Code ( "" , [] , [] ) "ul"
+                  , Space
+                  , Str "element."
+                  ]
+              , BulletList
+                  [ [ Plain [ Str "Lorem" ] ]
+                  , [ Plain [ Str "Ipsum" ] ]
+                  , [ Plain [ Str "Dolor" ] ]
+                  , [ Plain [ Str "Sit" ] ]
+                  , [ Plain [ Str "Amet" ] ]
+                  ]
+              , Para
+                  [ Str "If"
+                  , Space
+                  , Str "the"
+                  , Space
+                  , Str "preceding"
+                  , Space
+                  , Str "list"
+                  , Space
+                  , Str "has"
+                  , Space
+                  , Str "circle"
+                  , Space
+                  , Str "markers,"
+                  , Space
+                  , Str "the"
+                  , Space
+                  , Str "test"
+                  , Space
+                  , Str "passes."
+                  ]
+              ]
+          , Div
+              ( "styling-xhtml-002.xhtml_style-011"
+              , [ "section" , "ctest" ]
+              , []
+              )
+              [ Header
+                  4
+                  ( "" , [] , [] )
+                  [ Span ( "" , [ "nature" ] , [] ) [ Str "[REQUIRED]" ]
+                  , Space
+                  , Span ( "" , [ "test-id" ] , [] ) [ Str "style-011" ]
+                  , Space
+                  , Code ( "" , [] , [] ) "square"
+                  ]
+              , Para
+                  [ Str "Tests"
+                  , Space
+                  , Str "whether"
+                  , Space
+                  , Str "the"
+                  , Space
+                  , Code ( "" , [] , [] ) "list-style-type"
+                  , Space
+                  , Str "property"
+                  , Space
+                  , Str "set"
+                  , Space
+                  , Str "to"
+                  , Space
+                  , Code ( "" , [] , [] ) "square"
+                  , Space
+                  , Str "is"
+                  , Space
+                  , Str "supported"
+                  , Space
+                  , Str "on"
+                  , Space
+                  , Str "a"
+                  , Space
+                  , Code ( "" , [] , [] ) "ul"
+                  , Space
+                  , Str "element."
+                  ]
+              , BulletList
+                  [ [ Plain [ Str "Lorem" ] ]
+                  , [ Plain [ Str "Ipsum" ] ]
+                  , [ Plain [ Str "Dolor" ] ]
+                  , [ Plain [ Str "Sit" ] ]
+                  , [ Plain [ Str "Amet" ] ]
+                  ]
+              , Para
+                  [ Str "If"
+                  , Space
+                  , Str "the"
+                  , Space
+                  , Str "preceding"
+                  , Space
+                  , Str "list"
+                  , Space
+                  , Str "has"
+                  , Space
+                  , Str "square"
+                  , Space
+                  , Str "markers,"
+                  , Space
+                  , Str "the"
+                  , Space
+                  , Str "test"
+                  , Space
+                  , Str "passes."
+                  ]
+              ]
+          , Div
+              ( "styling-xhtml-002.xhtml_style-012"
+              , [ "section" , "ctest" ]
+              , []
+              )
+              [ Header
+                  4
+                  ( "" , [] , [] )
+                  [ Span ( "" , [ "nature" ] , [] ) [ Str "[REQUIRED]" ]
+                  , Space
+                  , Span ( "" , [ "test-id" ] , [] ) [ Str "style-012" ]
+                  , Space
+                  , Code ( "" , [] , [] ) "disc"
+                  ]
+              , Para
+                  [ Str "Tests"
+                  , Space
+                  , Str "whether"
+                  , Space
+                  , Str "the"
+                  , Space
+                  , Code ( "" , [] , [] ) "list-style-type"
+                  , Space
+                  , Str "property"
+                  , Space
+                  , Str "set"
+                  , Space
+                  , Str "to"
+                  , Space
+                  , Code ( "" , [] , [] ) "disc"
+                  , Space
+                  , Str "is"
+                  , Space
+                  , Str "supported"
+                  , Space
+                  , Str "on"
+                  , Space
+                  , Str "a"
+                  , Space
+                  , Code ( "" , [] , [] ) "ul"
+                  , Space
+                  , Str "element."
+                  ]
+              , BulletList
+                  [ [ Plain [ Str "Lorem" ] ]
+                  , [ Plain [ Str "Ipsum" ] ]
+                  , [ Plain [ Str "Dolor" ] ]
+                  , [ Plain [ Str "Sit" ] ]
+                  , [ Plain [ Str "Amet" ] ]
+                  ]
+              , Para
+                  [ Str "If"
+                  , Space
+                  , Str "the"
+                  , Space
+                  , Str "preceding"
+                  , Space
+                  , Str "list"
+                  , Space
+                  , Str "has"
+                  , Space
+                  , Str "disc"
+                  , Space
+                  , Str "markers,"
+                  , Space
+                  , Str "the"
+                  , Space
+                  , Str "test"
+                  , Space
+                  , Str "passes."
+                  ]
+              ]
+          , Div
+              ( "styling-xhtml-002.xhtml_style-013"
+              , [ "section" , "ctest" ]
+              , []
+              )
+              [ Header
+                  4
+                  ( "" , [] , [] )
+                  [ Span ( "" , [ "nature" ] , [] ) [ Str "[REQUIRED]" ]
+                  , Space
+                  , Span ( "" , [ "test-id" ] , [] ) [ Str "style-013" ]
+                  , Space
+                  , Code ( "" , [] , [] ) "lower-latin"
+                  ]
+              , Para
+                  [ Str "Tests"
+                  , Space
+                  , Str "whether"
+                  , Space
+                  , Str "the"
+                  , Space
+                  , Code ( "" , [] , [] ) "list-style-type"
+                  , Space
+                  , Str "property"
+                  , Space
+                  , Str "set"
+                  , Space
+                  , Str "to"
+                  , Space
+                  , Code ( "" , [] , [] ) "lower-latin"
+                  , Space
+                  , Str "is"
+                  , Space
+                  , Str "supported"
+                  , Space
+                  , Str "on"
+                  , Space
+                  , Str "a"
+                  , Space
+                  , Code ( "" , [] , [] ) "ol"
+                  , Space
+                  , Str "element."
+                  ]
+              , OrderedList
+                  ( 1 , DefaultStyle , DefaultDelim )
+                  [ [ Plain [ Str "Lorem" ] ]
+                  , [ Plain [ Str "Ipsum" ] ]
+                  , [ Plain [ Str "Dolor" ] ]
+                  , [ Plain [ Str "Sit" ] ]
+                  , [ Plain [ Str "Amet" ] ]
+                  ]
+              , Para
+                  [ Str "If"
+                  , Space
+                  , Str "the"
+                  , Space
+                  , Str "preceding"
+                  , Space
+                  , Str "list"
+                  , Space
+                  , Str "has"
+                  , Space
+                  , Str "lower-latin"
+                  , Space
+                  , Str "markers"
+                  , Space
+                  , Str "in"
+                  , Space
+                  , Str "ascending"
+                  , Space
+                  , Str "order,"
+                  , Space
+                  , Str "the"
+                  , Space
+                  , Str "test"
+                  , Space
+                  , Str "passes."
+                  ]
+              ]
+          , Div
+              ( "styling-xhtml-002.xhtml_style-014"
+              , [ "section" , "ctest" ]
+              , []
+              )
+              [ Header
+                  4
+                  ( "" , [] , [] )
+                  [ Span ( "" , [ "nature" ] , [] ) [ Str "[REQUIRED]" ]
+                  , Space
+                  , Span ( "" , [ "test-id" ] , [] ) [ Str "style-014" ]
+                  , Space
+                  , Code ( "" , [] , [] ) "lower-roman"
+                  ]
+              , Para
+                  [ Str "Tests"
+                  , Space
+                  , Str "whether"
+                  , Space
+                  , Str "the"
+                  , Space
+                  , Code ( "" , [] , [] ) "list-style-type"
+                  , Space
+                  , Str "property"
+                  , Space
+                  , Str "set"
+                  , Space
+                  , Str "to"
+                  , Space
+                  , Code ( "" , [] , [] ) "lower-roman"
+                  , Space
+                  , Str "is"
+                  , Space
+                  , Str "supported"
+                  , Space
+                  , Str "on"
+                  , Space
+                  , Str "a"
+                  , Space
+                  , Code ( "" , [] , [] ) "ol"
+                  , Space
+                  , Str "element."
+                  ]
+              , OrderedList
+                  ( 1 , DefaultStyle , DefaultDelim )
+                  [ [ Plain [ Str "Lorem" ] ]
+                  , [ Plain [ Str "Ipsum" ] ]
+                  , [ Plain [ Str "Dolor" ] ]
+                  , [ Plain [ Str "Sit" ] ]
+                  , [ Plain [ Str "Amet" ] ]
+                  ]
+              , Para
+                  [ Str "If"
+                  , Space
+                  , Str "the"
+                  , Space
+                  , Str "preceding"
+                  , Space
+                  , Str "list"
+                  , Space
+                  , Str "has"
+                  , Space
+                  , Str "lower-roman"
+                  , Space
+                  , Str "markers"
+                  , Space
+                  , Str "in"
+                  , Space
+                  , Str "ascending"
+                  , Space
+                  , Str "order,"
+                  , Space
+                  , Str "the"
+                  , Space
+                  , Str "test"
+                  , Space
+                  , Str "passes."
+                  ]
+              ]
+          , Div
+              ( "styling-xhtml-002.xhtml_style-015"
+              , [ "section" , "ctest" ]
+              , []
+              )
+              [ Header
+                  4
+                  ( "" , [] , [] )
+                  [ Span ( "" , [ "nature" ] , [] ) [ Str "[REQUIRED]" ]
+                  , Space
+                  , Span ( "" , [ "test-id" ] , [] ) [ Str "style-015" ]
+                  , Space
+                  , Code ( "" , [] , [] ) "upper-alpha"
+                  ]
+              , Para
+                  [ Str "Tests"
+                  , Space
+                  , Str "whether"
+                  , Space
+                  , Str "the"
+                  , Space
+                  , Code ( "" , [] , [] ) "list-style-type"
+                  , Space
+                  , Str "property"
+                  , Space
+                  , Str "set"
+                  , Space
+                  , Str "to"
+                  , Space
+                  , Code ( "" , [] , [] ) "upper-alpha"
+                  , Space
+                  , Str "is"
+                  , Space
+                  , Str "supported"
+                  , Space
+                  , Str "on"
+                  , Space
+                  , Str "a"
+                  , Space
+                  , Code ( "" , [] , [] ) "ol"
+                  , Space
+                  , Str "element."
+                  ]
+              , OrderedList
+                  ( 1 , DefaultStyle , DefaultDelim )
+                  [ [ Plain [ Str "Lorem" ] ]
+                  , [ Plain [ Str "Ipsum" ] ]
+                  , [ Plain [ Str "Dolor" ] ]
+                  , [ Plain [ Str "Sit" ] ]
+                  , [ Plain [ Str "Amet" ] ]
+                  ]
+              , Para
+                  [ Str "If"
+                  , Space
+                  , Str "the"
+                  , Space
+                  , Str "preceding"
+                  , Space
+                  , Str "list"
+                  , Space
+                  , Str "has"
+                  , Space
+                  , Str "upper-alpha"
+                  , Space
+                  , Str "markers"
+                  , Space
+                  , Str "in"
+                  , Space
+                  , Str "ascending"
+                  , Space
+                  , Str "order,"
+                  , Space
+                  , Str "the"
+                  , Space
+                  , Str "test"
+                  , Space
+                  , Str "passes."
+                  ]
+              ]
+          , Div
+              ( "styling-xhtml-002.xhtml_style-016"
+              , [ "section" , "ctest" ]
+              , []
+              )
+              [ Header
+                  4
+                  ( "" , [] , [] )
+                  [ Span ( "" , [ "nature" ] , [] ) [ Str "[REQUIRED]" ]
+                  , Space
+                  , Span ( "" , [ "test-id" ] , [] ) [ Str "style-016" ]
+                  , Space
+                  , Code ( "" , [] , [] ) "hiragana"
+                  ]
+              , Para
+                  [ Str "Tests"
+                  , Space
+                  , Str "whether"
+                  , Space
+                  , Str "the"
+                  , Space
+                  , Code ( "" , [] , [] ) "list-style-type"
+                  , Space
+                  , Str "property"
+                  , Space
+                  , Str "set"
+                  , Space
+                  , Str "to"
+                  , Space
+                  , Code ( "" , [] , [] ) "hiragana"
+                  , Space
+                  , Str "is"
+                  , Space
+                  , Str "supported"
+                  , Space
+                  , Str "on"
+                  , Space
+                  , Str "a"
+                  , Space
+                  , Code ( "" , [] , [] ) "ol"
+                  , Space
+                  , Str "element."
+                  ]
+              , OrderedList
+                  ( 1 , DefaultStyle , DefaultDelim )
+                  [ [ Plain [ Str "Lorem" ] ]
+                  , [ Plain [ Str "Ipsum" ] ]
+                  , [ Plain [ Str "Dolor" ] ]
+                  , [ Plain [ Str "Sit" ] ]
+                  , [ Plain [ Str "Amet" ] ]
+                  ]
+              , Para
+                  [ Str "If"
+                  , Space
+                  , Str "the"
+                  , Space
+                  , Str "preceding"
+                  , Space
+                  , Str "list"
+                  , Space
+                  , Str "has"
+                  , Space
+                  , Str "hiragana"
+                  , Space
+                  , Str "markers"
+                  , Space
+                  , Str "in"
+                  , Space
+                  , Str "ascending"
+                  , Space
+                  , Str "order,"
+                  , Space
+                  , Str "the"
+                  , Space
+                  , Str "test"
+                  , Space
+                  , Str "passes."
+                  ]
+              ]
+          , Div
+              ( "styling-xhtml-002.xhtml_style-017"
+              , [ "section" , "ctest" ]
+              , []
+              )
+              [ Header
+                  4
+                  ( "" , [] , [] )
+                  [ Span ( "" , [ "nature" ] , [] ) [ Str "[REQUIRED]" ]
+                  , Space
+                  , Span ( "" , [ "test-id" ] , [] ) [ Str "style-017" ]
+                  , Space
+                  , Code ( "" , [] , [] ) "hiragana-iroha"
+                  ]
+              , Para
+                  [ Str "Tests"
+                  , Space
+                  , Str "whether"
+                  , Space
+                  , Str "the"
+                  , Space
+                  , Code ( "" , [] , [] ) "list-style-type"
+                  , Space
+                  , Str "property"
+                  , Space
+                  , Str "set"
+                  , Space
+                  , Str "to"
+                  , Space
+                  , Code ( "" , [] , [] ) "hiragana-iroha"
+                  , Space
+                  , Str "is"
+                  , Space
+                  , Str "supported"
+                  , Space
+                  , Str "on"
+                  , Space
+                  , Str "a"
+                  , Space
+                  , Code ( "" , [] , [] ) "ol"
+                  , Space
+                  , Str "element."
+                  ]
+              , OrderedList
+                  ( 1 , DefaultStyle , DefaultDelim )
+                  [ [ Plain [ Str "Lorem" ] ]
+                  , [ Plain [ Str "Ipsum" ] ]
+                  , [ Plain [ Str "Dolor" ] ]
+                  , [ Plain [ Str "Sit" ] ]
+                  , [ Plain [ Str "Amet" ] ]
+                  ]
+              , Para
+                  [ Str "If"
+                  , Space
+                  , Str "the"
+                  , Space
+                  , Str "preceding"
+                  , Space
+                  , Str "list"
+                  , Space
+                  , Str "has"
+                  , Space
+                  , Str "hiragana-iroha"
+                  , Space
+                  , Str "markers"
+                  , Space
+                  , Str "in"
+                  , Space
+                  , Str "ascending"
+                  , Space
+                  , Str "order,"
+                  , Space
+                  , Str "the"
+                  , Space
+                  , Str "test"
+                  , Space
+                  , Str "passes."
+                  ]
+              ]
+          , Div
+              ( "styling-xhtml-002.xhtml_style-018"
+              , [ "section" , "ctest" ]
+              , []
+              )
+              [ Header
+                  4
+                  ( "" , [] , [] )
+                  [ Span ( "" , [ "nature" ] , [] ) [ Str "[REQUIRED]" ]
+                  , Space
+                  , Span ( "" , [ "test-id" ] , [] ) [ Str "style-018" ]
+                  , Space
+                  , Code ( "" , [] , [] ) "katakana"
+                  ]
+              , Para
+                  [ Str "Tests"
+                  , Space
+                  , Str "whether"
+                  , Space
+                  , Str "the"
+                  , Space
+                  , Code ( "" , [] , [] ) "list-style-type"
+                  , Space
+                  , Str "property"
+                  , Space
+                  , Str "set"
+                  , Space
+                  , Str "to"
+                  , Space
+                  , Code ( "" , [] , [] ) "katakana"
+                  , Space
+                  , Str "is"
+                  , Space
+                  , Str "supported"
+                  , Space
+                  , Str "on"
+                  , Space
+                  , Str "a"
+                  , Space
+                  , Code ( "" , [] , [] ) "ol"
+                  , Space
+                  , Str "element."
+                  ]
+              , OrderedList
+                  ( 1 , DefaultStyle , DefaultDelim )
+                  [ [ Plain [ Str "Lorem" ] ]
+                  , [ Plain [ Str "Ipsum" ] ]
+                  , [ Plain [ Str "Dolor" ] ]
+                  , [ Plain [ Str "Sit" ] ]
+                  , [ Plain [ Str "Amet" ] ]
+                  ]
+              , Para
+                  [ Str "If"
+                  , Space
+                  , Str "the"
+                  , Space
+                  , Str "preceding"
+                  , Space
+                  , Str "list"
+                  , Space
+                  , Str "has"
+                  , Space
+                  , Str "katakana"
+                  , Space
+                  , Str "markers"
+                  , Space
+                  , Str "in"
+                  , Space
+                  , Str "ascending"
+                  , Space
+                  , Str "order,"
+                  , Space
+                  , Str "the"
+                  , Space
+                  , Str "test"
+                  , Space
+                  , Str "passes."
+                  ]
+              ]
+          , Div
+              ( "styling-xhtml-002.xhtml_style-019"
+              , [ "section" , "ctest" ]
+              , []
+              )
+              [ Header
+                  4
+                  ( "" , [] , [] )
+                  [ Span ( "" , [ "nature" ] , [] ) [ Str "[REQUIRED]" ]
+                  , Space
+                  , Span ( "" , [ "test-id" ] , [] ) [ Str "style-019" ]
+                  , Space
+                  , Code ( "" , [] , [] ) "katakana-iroha"
+                  ]
+              , Para
+                  [ Str "Tests"
+                  , Space
+                  , Str "whether"
+                  , Space
+                  , Str "the"
+                  , Space
+                  , Code ( "" , [] , [] ) "list-style-type"
+                  , Space
+                  , Str "property"
+                  , Space
+                  , Str "set"
+                  , Space
+                  , Str "to"
+                  , Space
+                  , Code ( "" , [] , [] ) "katakana-iroha"
+                  , Space
+                  , Str "is"
+                  , Space
+                  , Str "supported"
+                  , Space
+                  , Str "on"
+                  , Space
+                  , Str "a"
+                  , Space
+                  , Code ( "" , [] , [] ) "ol"
+                  , Space
+                  , Str "element."
+                  ]
+              , OrderedList
+                  ( 1 , DefaultStyle , DefaultDelim )
+                  [ [ Plain [ Str "Lorem" ] ]
+                  , [ Plain [ Str "Ipsum" ] ]
+                  , [ Plain [ Str "Dolor" ] ]
+                  , [ Plain [ Str "Sit" ] ]
+                  , [ Plain [ Str "Amet" ] ]
+                  ]
+              , Para
+                  [ Str "If"
+                  , Space
+                  , Str "the"
+                  , Space
+                  , Str "preceding"
+                  , Space
+                  , Str "list"
+                  , Space
+                  , Str "has"
+                  , Space
+                  , Str "katakana-iroha"
+                  , Space
+                  , Str "markers"
+                  , Space
+                  , Str "in"
+                  , Space
+                  , Str "ascending"
+                  , Space
+                  , Str "order,"
+                  , Space
+                  , Str "the"
+                  , Space
+                  , Str "test"
+                  , Space
+                  , Str "passes."
+                  ]
+              ]
+          , Div
+              ( "styling-xhtml-002.xhtml_style-020"
+              , [ "section" , "ctest" ]
+              , []
+              )
+              [ Header
+                  4
+                  ( "" , [] , [] )
+                  [ Span ( "" , [ "nature" ] , [] ) [ Str "[REQUIRED]" ]
+                  , Space
+                  , Span ( "" , [ "test-id" ] , [] ) [ Str "style-020" ]
+                  , Space
+                  , Code ( "" , [] , [] ) "upper-roman"
+                  ]
+              , Para
+                  [ Str "Tests"
+                  , Space
+                  , Str "whether"
+                  , Space
+                  , Str "the"
+                  , Space
+                  , Code ( "" , [] , [] ) "list-style-type"
+                  , Space
+                  , Str "property"
+                  , Space
+                  , Str "set"
+                  , Space
+                  , Str "to"
+                  , Space
+                  , Code ( "" , [] , [] ) "upper-roman"
+                  , Space
+                  , Str "is"
+                  , Space
+                  , Str "supported"
+                  , Space
+                  , Str "on"
+                  , Space
+                  , Str "a"
+                  , Space
+                  , Code ( "" , [] , [] ) "ol"
+                  , Space
+                  , Str "element."
+                  ]
+              , OrderedList
+                  ( 1 , DefaultStyle , DefaultDelim )
+                  [ [ Plain [ Str "Lorem" ] ]
+                  , [ Plain [ Str "Ipsum" ] ]
+                  , [ Plain [ Str "Dolor" ] ]
+                  , [ Plain [ Str "Sit" ] ]
+                  , [ Plain [ Str "Amet" ] ]
+                  ]
+              , Para
+                  [ Str "If"
+                  , Space
+                  , Str "the"
+                  , Space
+                  , Str "preceding"
+                  , Space
+                  , Str "list"
+                  , Space
+                  , Str "has"
+                  , Space
+                  , Str "upper-roman"
+                  , Space
+                  , Str "markers"
+                  , Space
+                  , Str "in"
+                  , Space
+                  , Str "ascending"
+                  , Space
+                  , Str "order,"
+                  , Space
+                  , Str "the"
+                  , Space
+                  , Str "test"
+                  , Space
+                  , Str "passes."
+                  ]
+              ]
+          , Div
+              ( "styling-xhtml-002.xhtml_style-021"
+              , [ "section" , "ctest" ]
+              , []
+              )
+              [ Header
+                  4
+                  ( "" , [] , [] )
+                  [ Span ( "" , [ "nature" ] , [] ) [ Str "[REQUIRED]" ]
+                  , Space
+                  , Span ( "" , [ "test-id" ] , [] ) [ Str "style-021" ]
+                  , Space
+                  , Code ( "" , [] , [] ) "upper-latin"
+                  ]
+              , Para
+                  [ Str "Tests"
+                  , Space
+                  , Str "whether"
+                  , Space
+                  , Str "the"
+                  , Space
+                  , Code ( "" , [] , [] ) "list-style-type"
+                  , Space
+                  , Str "property"
+                  , Space
+                  , Str "set"
+                  , Space
+                  , Str "to"
+                  , Space
+                  , Code ( "" , [] , [] ) "upper-latin"
+                  , Space
+                  , Str "is"
+                  , Space
+                  , Str "supported"
+                  , Space
+                  , Str "on"
+                  , Space
+                  , Str "a"
+                  , Space
+                  , Code ( "" , [] , [] ) "ol"
+                  , Space
+                  , Str "element."
+                  ]
+              , OrderedList
+                  ( 1 , DefaultStyle , DefaultDelim )
+                  [ [ Plain [ Str "Lorem" ] ]
+                  , [ Plain [ Str "Ipsum" ] ]
+                  , [ Plain [ Str "Dolor" ] ]
+                  , [ Plain [ Str "Sit" ] ]
+                  , [ Plain [ Str "Amet" ] ]
+                  ]
+              , Para
+                  [ Str "If"
+                  , Space
+                  , Str "the"
+                  , Space
+                  , Str "preceding"
+                  , Space
+                  , Str "list"
+                  , Space
+                  , Str "has"
+                  , Space
+                  , Str "upper-latin"
+                  , Space
+                  , Str "markers"
+                  , Space
+                  , Str "in"
+                  , Space
+                  , Str "ascending"
+                  , Space
+                  , Str "order,"
+                  , Space
+                  , Str "the"
+                  , Space
+                  , Str "test"
+                  , Space
+                  , Str "passes."
+                  ]
+              ]
+          , Div
+              ( "styling-xhtml-002.xhtml_style-022"
+              , [ "section" , "ctest" ]
+              , []
+              )
+              [ Header
+                  4
+                  ( "" , [] , [] )
+                  [ Span ( "" , [ "nature" ] , [] ) [ Str "[REQUIRED]" ]
+                  , Space
+                  , Span ( "" , [ "test-id" ] , [] ) [ Str "style-022" ]
+                  , Space
+                  , Code ( "" , [] , [] ) "lower-alpha"
+                  ]
+              , Para
+                  [ Str "Tests"
+                  , Space
+                  , Str "whether"
+                  , Space
+                  , Str "the"
+                  , Space
+                  , Code ( "" , [] , [] ) "list-style-type"
+                  , Space
+                  , Str "property"
+                  , Space
+                  , Str "set"
+                  , Space
+                  , Str "to"
+                  , Space
+                  , Code ( "" , [] , [] ) "lower-alpha"
+                  , Space
+                  , Str "is"
+                  , Space
+                  , Str "supported"
+                  , Space
+                  , Str "on"
+                  , Space
+                  , Str "a"
+                  , Space
+                  , Code ( "" , [] , [] ) "ol"
+                  , Space
+                  , Str "element."
+                  ]
+              , OrderedList
+                  ( 1 , DefaultStyle , DefaultDelim )
+                  [ [ Plain [ Str "Lorem" ] ]
+                  , [ Plain [ Str "Ipsum" ] ]
+                  , [ Plain [ Str "Dolor" ] ]
+                  , [ Plain [ Str "Sit" ] ]
+                  , [ Plain [ Str "Amet" ] ]
+                  ]
+              , Para
+                  [ Str "If"
+                  , Space
+                  , Str "the"
+                  , Space
+                  , Str "preceding"
+                  , Space
+                  , Str "list"
+                  , Space
+                  , Str "has"
+                  , Space
+                  , Str "lower-alpha"
+                  , Space
+                  , Str "markers"
+                  , Space
+                  , Str "in"
+                  , Space
+                  , Str "ascending"
+                  , Space
+                  , Str "order,"
+                  , Space
+                  , Str "the"
+                  , Space
+                  , Str "test"
+                  , Space
+                  , Str "passes."
+                  ]
+              ]
+          , Div
+              ( "styling-xhtml-002.xhtml_style-023"
+              , [ "section" , "ctest" ]
+              , []
+              )
+              [ Header
+                  4
+                  ( "" , [] , [] )
+                  [ Span ( "" , [ "nature" ] , [] ) [ Str "[REQUIRED]" ]
+                  , Space
+                  , Span ( "" , [ "test-id" ] , [] ) [ Str "style-023" ]
+                  , Space
+                  , Code ( "" , [] , [] ) "lower-greek"
+                  ]
+              , Para
+                  [ Str "Tests"
+                  , Space
+                  , Str "whether"
+                  , Space
+                  , Str "the"
+                  , Space
+                  , Code ( "" , [] , [] ) "list-style-type"
+                  , Space
+                  , Str "property"
+                  , Space
+                  , Str "set"
+                  , Space
+                  , Str "to"
+                  , Space
+                  , Code ( "" , [] , [] ) "lower-greek"
+                  , Space
+                  , Str "is"
+                  , Space
+                  , Str "supported"
+                  , Space
+                  , Str "on"
+                  , Space
+                  , Str "a"
+                  , Space
+                  , Code ( "" , [] , [] ) "ol"
+                  , Space
+                  , Str "element."
+                  ]
+              , OrderedList
+                  ( 1 , DefaultStyle , DefaultDelim )
+                  [ [ Plain [ Str "Lorem" ] ]
+                  , [ Plain [ Str "Ipsum" ] ]
+                  , [ Plain [ Str "Dolor" ] ]
+                  , [ Plain [ Str "Sit" ] ]
+                  , [ Plain [ Str "Amet" ] ]
+                  ]
+              , Para
+                  [ Str "If"
+                  , Space
+                  , Str "the"
+                  , Space
+                  , Str "preceding"
+                  , Space
+                  , Str "list"
+                  , Space
+                  , Str "has"
+                  , Space
+                  , Str "lower-greek"
+                  , Space
+                  , Str "markers"
+                  , Space
+                  , Str "in"
+                  , Space
+                  , Str "ascending"
+                  , Space
+                  , Str "order,"
+                  , Space
+                  , Str "the"
+                  , Space
+                  , Str "test"
+                  , Space
+                  , Str "passes."
+                  ]
+              ]
+          , Div
+              ( "styling-xhtml-002.xhtml_style-024"
+              , [ "section" , "ctest" ]
+              , []
+              )
+              [ Header
+                  4
+                  ( "" , [] , [] )
+                  [ Span ( "" , [ "nature" ] , [] ) [ Str "[REQUIRED]" ]
+                  , Space
+                  , Span ( "" , [ "test-id" ] , [] ) [ Str "style-024" ]
+                  , Space
+                  , Code ( "" , [] , [] ) "armenian"
+                  ]
+              , Para
+                  [ Str "Tests"
+                  , Space
+                  , Str "whether"
+                  , Space
+                  , Str "the"
+                  , Space
+                  , Code ( "" , [] , [] ) "list-style-type"
+                  , Space
+                  , Str "property"
+                  , Space
+                  , Str "set"
+                  , Space
+                  , Str "to"
+                  , Space
+                  , Code ( "" , [] , [] ) "armenian"
+                  , Space
+                  , Str "is"
+                  , Space
+                  , Str "supported"
+                  , Space
+                  , Str "on"
+                  , Space
+                  , Str "a"
+                  , Space
+                  , Code ( "" , [] , [] ) "ol"
+                  , Space
+                  , Str "element."
+                  ]
+              , OrderedList
+                  ( 1 , DefaultStyle , DefaultDelim )
+                  [ [ Plain [ Str "Lorem" ] ]
+                  , [ Plain [ Str "Ipsum" ] ]
+                  , [ Plain [ Str "Dolor" ] ]
+                  , [ Plain [ Str "Sit" ] ]
+                  , [ Plain [ Str "Amet" ] ]
+                  ]
+              , Para
+                  [ Str "If"
+                  , Space
+                  , Str "the"
+                  , Space
+                  , Str "preceding"
+                  , Space
+                  , Str "list"
+                  , Space
+                  , Str "has"
+                  , Space
+                  , Str "armenian"
+                  , Space
+                  , Str "markers"
+                  , Space
+                  , Str "in"
+                  , Space
+                  , Str "ascending"
+                  , Space
+                  , Str "order,"
+                  , Space
+                  , Str "the"
+                  , Space
+                  , Str "test"
+                  , Space
+                  , Str "passes."
+                  ]
+              ]
+          , Div
+              ( "styling-xhtml-002.xhtml_style-025"
+              , [ "section" , "ctest" ]
+              , []
+              )
+              [ Header
+                  4
+                  ( "" , [] , [] )
+                  [ Span ( "" , [ "nature" ] , [] ) [ Str "[REQUIRED]" ]
+                  , Space
+                  , Span ( "" , [ "test-id" ] , [] ) [ Str "style-025" ]
+                  , Space
+                  , Code ( "" , [] , [] ) "cjk-ideographic"
+                  ]
+              , Para
+                  [ Str "Tests"
+                  , Space
+                  , Str "whether"
+                  , Space
+                  , Str "the"
+                  , Space
+                  , Code ( "" , [] , [] ) "list-style-type"
+                  , Space
+                  , Str "property"
+                  , Space
+                  , Str "set"
+                  , Space
+                  , Str "to"
+                  , Space
+                  , Code ( "" , [] , [] ) "cjk-ideographic"
+                  , Space
+                  , Str "is"
+                  , Space
+                  , Str "supported"
+                  , Space
+                  , Str "on"
+                  , Space
+                  , Str "a"
+                  , Space
+                  , Code ( "" , [] , [] ) "ol"
+                  , Space
+                  , Str "element."
+                  ]
+              , OrderedList
+                  ( 1 , DefaultStyle , DefaultDelim )
+                  [ [ Plain [ Str "Lorem" ] ]
+                  , [ Plain [ Str "Ipsum" ] ]
+                  , [ Plain [ Str "Dolor" ] ]
+                  , [ Plain [ Str "Sit" ] ]
+                  , [ Plain [ Str "Amet" ] ]
+                  ]
+              , Para
+                  [ Str "If"
+                  , Space
+                  , Str "the"
+                  , Space
+                  , Str "preceding"
+                  , Space
+                  , Str "list"
+                  , Space
+                  , Str "has"
+                  , Space
+                  , Str "cjk-ideographic"
+                  , Space
+                  , Str "markers"
+                  , Space
+                  , Str "in"
+                  , Space
+                  , Str "ascending"
+                  , Space
+                  , Str "order,"
+                  , Space
+                  , Str "the"
+                  , Space
+                  , Str "test"
+                  , Space
+                  , Str "passes."
+                  ]
+              ]
+          , Div
+              ( "styling-xhtml-002.xhtml_style-026"
+              , [ "section" , "ctest" ]
+              , []
+              )
+              [ Header
+                  4
+                  ( "" , [] , [] )
+                  [ Span ( "" , [ "nature" ] , [] ) [ Str "[REQUIRED]" ]
+                  , Space
+                  , Span ( "" , [ "test-id" ] , [] ) [ Str "style-026" ]
+                  , Space
+                  , Code ( "" , [] , [] ) "decimal-leading-zero"
+                  ]
+              , Para
+                  [ Str "Tests"
+                  , Space
+                  , Str "whether"
+                  , Space
+                  , Str "the"
+                  , Space
+                  , Code ( "" , [] , [] ) "list-style-type"
+                  , Space
+                  , Str "property"
+                  , Space
+                  , Str "set"
+                  , Space
+                  , Str "to"
+                  , Space
+                  , Code ( "" , [] , [] ) "decimal-leading-zero"
+                  , Space
+                  , Str "is"
+                  , Space
+                  , Str "supported"
+                  , Space
+                  , Str "on"
+                  , Space
+                  , Str "a"
+                  , Space
+                  , Code ( "" , [] , [] ) "ol"
+                  , Space
+                  , Str "element."
+                  ]
+              , OrderedList
+                  ( 1 , DefaultStyle , DefaultDelim )
+                  [ [ Plain [ Str "Lorem" ] ]
+                  , [ Plain [ Str "Ipsum" ] ]
+                  , [ Plain [ Str "Dolor" ] ]
+                  , [ Plain [ Str "Sit" ] ]
+                  , [ Plain [ Str "Amet" ] ]
+                  ]
+              , Para
+                  [ Str "If"
+                  , Space
+                  , Str "the"
+                  , Space
+                  , Str "preceding"
+                  , Space
+                  , Str "list"
+                  , Space
+                  , Str "has"
+                  , Space
+                  , Str "decimal-leading-zero"
+                  , Space
+                  , Str "markers"
+                  , Space
+                  , Str "in"
+                  , Space
+                  , Str "ascending"
+                  , Space
+                  , Str "order,"
+                  , Space
+                  , Str "the"
+                  , Space
+                  , Str "test"
+                  , Space
+                  , Str "passes."
+                  ]
+              ]
+          , Div
+              ( "styling-xhtml-002.xhtml_style-027"
+              , [ "section" , "ctest" ]
+              , []
+              )
+              [ Header
+                  4
+                  ( "" , [] , [] )
+                  [ Span ( "" , [ "nature" ] , [] ) [ Str "[REQUIRED]" ]
+                  , Space
+                  , Span ( "" , [ "test-id" ] , [] ) [ Str "style-027" ]
+                  , Space
+                  , Code ( "" , [] , [] ) "georgian"
+                  ]
+              , Para
+                  [ Str "Tests"
+                  , Space
+                  , Str "whether"
+                  , Space
+                  , Str "the"
+                  , Space
+                  , Code ( "" , [] , [] ) "list-style-type"
+                  , Space
+                  , Str "property"
+                  , Space
+                  , Str "set"
+                  , Space
+                  , Str "to"
+                  , Space
+                  , Code ( "" , [] , [] ) "georgian"
+                  , Space
+                  , Str "is"
+                  , Space
+                  , Str "supported"
+                  , Space
+                  , Str "on"
+                  , Space
+                  , Str "a"
+                  , Space
+                  , Code ( "" , [] , [] ) "ol"
+                  , Space
+                  , Str "element."
+                  ]
+              , OrderedList
+                  ( 1 , DefaultStyle , DefaultDelim )
+                  [ [ Plain [ Str "Lorem" ] ]
+                  , [ Plain [ Str "Ipsum" ] ]
+                  , [ Plain [ Str "Dolor" ] ]
+                  , [ Plain [ Str "Sit" ] ]
+                  , [ Plain [ Str "Amet" ] ]
+                  ]
+              , Para
+                  [ Str "If"
+                  , Space
+                  , Str "the"
+                  , Space
+                  , Str "preceding"
+                  , Space
+                  , Str "list"
+                  , Space
+                  , Str "has"
+                  , Space
+                  , Str "georgian"
+                  , Space
+                  , Str "markers"
+                  , Space
+                  , Str "in"
+                  , Space
+                  , Str "ascending"
+                  , Space
+                  , Str "order,"
+                  , Space
+                  , Str "the"
+                  , Space
+                  , Str "test"
+                  , Space
+                  , Str "passes."
+                  ]
+              ]
+          , Div
+              ( "styling-xhtml-002.xhtml_style-028"
+              , [ "section" , "ctest" ]
+              , []
+              )
+              [ Header
+                  4
+                  ( "" , [] , [] )
+                  [ Span ( "" , [ "nature" ] , [] ) [ Str "[REQUIRED]" ]
+                  , Space
+                  , Span ( "" , [ "test-id" ] , [] ) [ Str "style-028" ]
+                  , Space
+                  , Code ( "" , [] , [] ) "hebrew"
+                  ]
+              , Para
+                  [ Str "Tests"
+                  , Space
+                  , Str "whether"
+                  , Space
+                  , Str "the"
+                  , Space
+                  , Code ( "" , [] , [] ) "list-style-type"
+                  , Space
+                  , Str "property"
+                  , Space
+                  , Str "set"
+                  , Space
+                  , Str "to"
+                  , Space
+                  , Code ( "" , [] , [] ) "hebrew"
+                  , Space
+                  , Str "is"
+                  , Space
+                  , Str "supported"
+                  , Space
+                  , Str "on"
+                  , Space
+                  , Str "a"
+                  , Space
+                  , Code ( "" , [] , [] ) "ol"
+                  , Space
+                  , Str "element."
+                  ]
+              , OrderedList
+                  ( 1 , DefaultStyle , DefaultDelim )
+                  [ [ Plain [ Str "Lorem" ] ]
+                  , [ Plain [ Str "Ipsum" ] ]
+                  , [ Plain [ Str "Dolor" ] ]
+                  , [ Plain [ Str "Sit" ] ]
+                  , [ Plain [ Str "Amet" ] ]
+                  ]
+              , Para
+                  [ Str "If"
+                  , Space
+                  , Str "the"
+                  , Space
+                  , Str "preceding"
+                  , Space
+                  , Str "list"
+                  , Space
+                  , Str "has"
+                  , Space
+                  , Str "hebrew"
+                  , Space
+                  , Str "markers"
+                  , Space
+                  , Str "in"
+                  , Space
+                  , Str "ascending"
+                  , Space
+                  , Str "order,"
+                  , Space
+                  , Str "the"
+                  , Space
+                  , Str "test"
+                  , Space
+                  , Str "passes."
+                  ]
+              ]
+          , Div
+              ( "styling-xhtml-002.xhtml_style-029"
+              , [ "section" , "ctest" ]
+              , []
+              )
+              [ Header
+                  4
+                  ( "" , [] , [] )
+                  [ Span ( "" , [ "nature" ] , [] ) [ Str "[REQUIRED]" ]
+                  , Space
+                  , Span ( "" , [ "test-id" ] , [] ) [ Str "style-029" ]
+                  , Space
+                  , Code ( "" , [] , [] ) "none"
+                  ]
+              , Para
+                  [ Str "Tests"
+                  , Space
+                  , Str "whether"
+                  , Space
+                  , Str "the"
+                  , Space
+                  , Code ( "" , [] , [] ) "list-style-type"
+                  , Space
+                  , Str "property"
+                  , Space
+                  , Str "set"
+                  , Space
+                  , Str "to"
+                  , Space
+                  , Code ( "" , [] , [] ) "none"
+                  , Space
+                  , Str "is"
+                  , Space
+                  , Str "supported"
+                  , Space
+                  , Str "on"
+                  , Space
+                  , Str "a"
+                  , Space
+                  , Code ( "" , [] , [] ) "ol"
+                  , Space
+                  , Str "element."
+                  ]
+              , OrderedList
+                  ( 1 , DefaultStyle , DefaultDelim )
+                  [ [ Plain [ Str "Lorem" ] ]
+                  , [ Plain [ Str "Ipsum" ] ]
+                  , [ Plain [ Str "Dolor" ] ]
+                  , [ Plain [ Str "Sit" ] ]
+                  , [ Plain [ Str "Amet" ] ]
+                  ]
+              , Para
+                  [ Str "If"
+                  , Space
+                  , Str "the"
+                  , Space
+                  , Str "preceding"
+                  , Space
+                  , Str "list"
+                  , Space
+                  , Str "has"
+                  , Space
+                  , Str "no"
+                  , Space
+                  , Str "markers,"
+                  , Space
+                  , Str "the"
+                  , Space
+                  , Str "test"
+                  , Space
+                  , Str "passes."
+                  ]
+              ]
+          ]
+      , Div
+          ( "styling-xhtml-002.xhtml_style-list-style"
+          , [ "section" ]
+          , []
+          )
+          [ Header
+              3
+              ( "" , [] , [] )
+              [ Str "The"
+              , Space
+              , Code ( "" , [] , [] ) "list-style"
+              , Space
+              , Str "property"
+              ]
+          , Div
+              ( "styling-xhtml-002.xhtml_style-030"
+              , [ "section" , "ctest" ]
+              , []
+              )
+              [ Header
+                  4
+                  ( "" , [] , [] )
+                  [ Span ( "" , [ "nature" ] , [] ) [ Str "[REQUIRED]" ]
+                  , Space
+                  , Span ( "" , [ "test-id" ] , [] ) [ Str "style-030" ]
+                  , Space
+                  , Str "images"
+                  ]
+              , Para
+                  [ Str "Tests"
+                  , Space
+                  , Str "whether"
+                  , Space
+                  , Str "the"
+                  , Space
+                  , Code ( "" , [] , [] ) "list-style"
+                  , Space
+                  , Str "shorthand"
+                  , Space
+                  , Str "property"
+                  , Space
+                  , Str "is"
+                  , Space
+                  , Str "supported"
+                  , Space
+                  , Str "using"
+                  , Space
+                  , Str "a"
+                  , Space
+                  , Str "gif"
+                  , Space
+                  , Str "on"
+                  , Space
+                  , Str "a"
+                  , Space
+                  , Code ( "" , [] , [] ) "ul"
+                  , Space
+                  , Str "element."
+                  ]
+              , BulletList
+                  [ [ Plain [ Str "Lorem" ] ]
+                  , [ Plain [ Str "Ipsum" ] ]
+                  , [ Plain [ Str "Dolor" ] ]
+                  , [ Plain [ Str "Sit" ] ]
+                  , [ Plain [ Str "Amet" ] ]
+                  ]
+              , Para
+                  [ Str "If"
+                  , Space
+                  , Str "the"
+                  , Space
+                  , Str "preceding"
+                  , Space
+                  , Str "list"
+                  , Space
+                  , Str "has"
+                  , Space
+                  , Str "the"
+                  , Space
+                  , Str "purple"
+                  , Space
+                  , Str "and"
+                  , Space
+                  , Str "aqua"
+                  , Space
+                  , Str "square"
+                  , Space
+                  , Str "bullet"
+                  , Space
+                  , Str "the"
+                  , Space
+                  , Str "test"
+                  , Space
+                  , Str "passes."
+                  ]
+              ]
+          ]
+      , Div
+          ( "styling-xhtml-002.xhtml_style-list-style-position"
+          , [ "section" ]
+          , []
+          )
+          [ Header
+              3
+              ( "" , [] , [] )
+              [ Str "The"
+              , Space
+              , Code ( "" , [] , [] ) "list-style-position"
+              , Space
+              , Str "property"
+              ]
+          , Div
+              ( "styling-xhtml-002.xhtml_style-040"
+              , [ "section" , "ctest" ]
+              , []
+              )
+              [ Header
+                  4
+                  ( "" , [] , [] )
+                  [ Span ( "" , [ "nature" ] , [] ) [ Str "[REQUIRED]" ]
+                  , Space
+                  , Span ( "" , [ "test-id" ] , [] ) [ Str "style-040" ]
+                  , Space
+                  , Str "The"
+                  , Space
+                  , Code ( "" , [] , [] ) "list-style-position"
+                  , Space
+                  , Str "property:"
+                  , Space
+                  , Code ( "" , [] , [] ) "inside"
+                  ]
+              , Para
+                  [ Str "Tests"
+                  , Space
+                  , Str "whether"
+                  , Space
+                  , Str "the"
+                  , Space
+                  , Code ( "" , [] , [] ) "list-style-position"
+                  , Space
+                  , Str "property"
+                  , Space
+                  , Str "set"
+                  , Space
+                  , Str "to"
+                  , Space
+                  , Code ( "" , [] , [] ) "inside"
+                  , Space
+                  , Str "is"
+                  , Space
+                  , Str "supported"
+                  , Space
+                  , Str "on"
+                  , Space
+                  , Str "a"
+                  , Space
+                  , Code ( "" , [] , [] ) "ul"
+                  , Space
+                  , Str "element."
+                  ]
+              , BulletList
+                  [ [ Plain
+                        [ Str "Lorem"
+                        , Space
+                        , Str "ipsum"
+                        , Space
+                        , Str "dolor"
+                        , Space
+                        , Str "sit"
+                        , Space
+                        , Str "amet,"
+                        , Space
+                        , Str "consectetur"
+                        , Space
+                        , Str "adipisicing"
+                        , Space
+                        , Str "elit,"
+                        , Space
+                        , Str "sed"
+                        , Space
+                        , Str "do"
+                        , Space
+                        , Str "eiusmod"
+                        , Space
+                        , Str "tempor"
+                        , Space
+                        , Str "incididunt"
+                        , Space
+                        , Str "ut"
+                        , Space
+                        , Str "labore"
+                        , Space
+                        , Str "et"
+                        , Space
+                        , Str "dolore"
+                        , Space
+                        , Str "magna"
+                        , Space
+                        , Str "aliqua."
+                        , Space
+                        , Str "Ut"
+                        , Space
+                        , Str "enim"
+                        , Space
+                        , Str "ad"
+                        , Space
+                        , Str "minim"
+                        , Space
+                        , Str "veniam,"
+                        , Space
+                        , Str "quis"
+                        , Space
+                        , Str "nostrud"
+                        , Space
+                        , Str "exercitation"
+                        , Space
+                        , Str "ullamco"
+                        , Space
+                        , Str "laboris"
+                        , Space
+                        , Str "nisi"
+                        , Space
+                        , Str "ut"
+                        , Space
+                        , Str "aliquip"
+                        , Space
+                        , Str "ex"
+                        , Space
+                        , Str "ea"
+                        , Space
+                        , Str "commodo"
+                        , Space
+                        , Str "consequat."
+                        ]
+                    ]
+                  , [ Plain
+                        [ Str "Lorem"
+                        , Space
+                        , Str "ipsum"
+                        , Space
+                        , Str "dolor"
+                        , Space
+                        , Str "sit"
+                        , Space
+                        , Str "amet,"
+                        , Space
+                        , Str "consectetur"
+                        , Space
+                        , Str "adipisicing"
+                        , Space
+                        , Str "elit,"
+                        , Space
+                        , Str "sed"
+                        , Space
+                        , Str "do"
+                        , Space
+                        , Str "eiusmod"
+                        , Space
+                        , Str "tempor"
+                        , Space
+                        , Str "incididunt"
+                        , Space
+                        , Str "ut"
+                        , Space
+                        , Str "labore"
+                        , Space
+                        , Str "et"
+                        , Space
+                        , Str "dolore"
+                        , Space
+                        , Str "magna"
+                        , Space
+                        , Str "aliqua."
+                        , Space
+                        , Str "Ut"
+                        , Space
+                        , Str "enim"
+                        , Space
+                        , Str "ad"
+                        , Space
+                        , Str "minim"
+                        , Space
+                        , Str "veniam,"
+                        , Space
+                        , Str "quis"
+                        , Space
+                        , Str "nostrud"
+                        , Space
+                        , Str "exercitation"
+                        , Space
+                        , Str "ullamco"
+                        , Space
+                        , Str "laboris"
+                        , Space
+                        , Str "nisi"
+                        , Space
+                        , Str "ut"
+                        , Space
+                        , Str "aliquip"
+                        , Space
+                        , Str "ex"
+                        , Space
+                        , Str "ea"
+                        , Space
+                        , Str "commodo"
+                        , Space
+                        , Str "consequat."
+                        ]
+                    ]
+                  , [ Plain
+                        [ Str "Lorem"
+                        , Space
+                        , Str "ipsum"
+                        , Space
+                        , Str "dolor"
+                        , Space
+                        , Str "sit"
+                        , Space
+                        , Str "amet,"
+                        , Space
+                        , Str "consectetur"
+                        , Space
+                        , Str "adipisicing"
+                        , Space
+                        , Str "elit,"
+                        , Space
+                        , Str "sed"
+                        , Space
+                        , Str "do"
+                        , Space
+                        , Str "eiusmod"
+                        , Space
+                        , Str "tempor"
+                        , Space
+                        , Str "incididunt"
+                        , Space
+                        , Str "ut"
+                        , Space
+                        , Str "labore"
+                        , Space
+                        , Str "et"
+                        , Space
+                        , Str "dolore"
+                        , Space
+                        , Str "magna"
+                        , Space
+                        , Str "aliqua."
+                        , Space
+                        , Str "Ut"
+                        , Space
+                        , Str "enim"
+                        , Space
+                        , Str "ad"
+                        , Space
+                        , Str "minim"
+                        , Space
+                        , Str "veniam,"
+                        , Space
+                        , Str "quis"
+                        , Space
+                        , Str "nostrud"
+                        , Space
+                        , Str "exercitation"
+                        , Space
+                        , Str "ullamco"
+                        , Space
+                        , Str "laboris"
+                        , Space
+                        , Str "nisi"
+                        , Space
+                        , Str "ut"
+                        , Space
+                        , Str "aliquip"
+                        , Space
+                        , Str "ex"
+                        , Space
+                        , Str "ea"
+                        , Space
+                        , Str "commodo"
+                        , Space
+                        , Str "consequat."
+                        ]
+                    ]
+                  ]
+              , Para
+                  [ Str "If"
+                  , Space
+                  , Str "the"
+                  , Space
+                  , Str "preceding"
+                  , Space
+                  , Str "list"
+                  , Space
+                  , Str "has"
+                  , Space
+                  , Str "markers"
+                  , Space
+                  , Str "inside"
+                  , Space
+                  , Str "the"
+                  , Space
+                  , Str "indentation,"
+                  , Space
+                  , Str "the"
+                  , Space
+                  , Str "test"
+                  , Space
+                  , Str "passes."
+                  ]
+              ]
+          , Div
+              ( "styling-xhtml-002.xhtml_style-041"
+              , [ "section" , "ctest" ]
+              , []
+              )
+              [ Header
+                  4
+                  ( "" , [] , [] )
+                  [ Span ( "" , [ "nature" ] , [] ) [ Str "[REQUIRED]" ]
+                  , Space
+                  , Span ( "" , [ "test-id" ] , [] ) [ Str "style-041" ]
+                  , Space
+                  , Str "The"
+                  , Space
+                  , Code ( "" , [] , [] ) "list-style-position"
+                  , Space
+                  , Str "property:"
+                  , Space
+                  , Code ( "" , [] , [] ) "outside"
+                  ]
+              , Para
+                  [ Str "Tests"
+                  , Space
+                  , Str "whether"
+                  , Space
+                  , Str "the"
+                  , Space
+                  , Code ( "" , [] , [] ) "list-style-position"
+                  , Space
+                  , Str "property"
+                  , Space
+                  , Str "set"
+                  , Space
+                  , Str "to"
+                  , Space
+                  , Code ( "" , [] , [] ) "outside"
+                  , Space
+                  , Str "is"
+                  , Space
+                  , Str "supported"
+                  , Space
+                  , Str "on"
+                  , Space
+                  , Str "a"
+                  , Space
+                  , Code ( "" , [] , [] ) "ul"
+                  , Space
+                  , Str "element."
+                  ]
+              , BulletList
+                  [ [ Plain
+                        [ Str "Lorem"
+                        , Space
+                        , Str "ipsum"
+                        , Space
+                        , Str "dolor"
+                        , Space
+                        , Str "sit"
+                        , Space
+                        , Str "amet,"
+                        , Space
+                        , Str "consectetur"
+                        , Space
+                        , Str "adipisicing"
+                        , Space
+                        , Str "elit,"
+                        , Space
+                        , Str "sed"
+                        , Space
+                        , Str "do"
+                        , Space
+                        , Str "eiusmod"
+                        , Space
+                        , Str "tempor"
+                        , Space
+                        , Str "incididunt"
+                        , Space
+                        , Str "ut"
+                        , Space
+                        , Str "labore"
+                        , Space
+                        , Str "et"
+                        , Space
+                        , Str "dolore"
+                        , Space
+                        , Str "magna"
+                        , Space
+                        , Str "aliqua."
+                        , Space
+                        , Str "Ut"
+                        , Space
+                        , Str "enim"
+                        , Space
+                        , Str "ad"
+                        , Space
+                        , Str "minim"
+                        , Space
+                        , Str "veniam,"
+                        , Space
+                        , Str "quis"
+                        , Space
+                        , Str "nostrud"
+                        , Space
+                        , Str "exercitation"
+                        , Space
+                        , Str "ullamco"
+                        , Space
+                        , Str "laboris"
+                        , Space
+                        , Str "nisi"
+                        , Space
+                        , Str "ut"
+                        , Space
+                        , Str "aliquip"
+                        , Space
+                        , Str "ex"
+                        , Space
+                        , Str "ea"
+                        , Space
+                        , Str "commodo"
+                        , Space
+                        , Str "consequat."
+                        ]
+                    ]
+                  , [ Plain
+                        [ Str "Lorem"
+                        , Space
+                        , Str "ipsum"
+                        , Space
+                        , Str "dolor"
+                        , Space
+                        , Str "sit"
+                        , Space
+                        , Str "amet,"
+                        , Space
+                        , Str "consectetur"
+                        , Space
+                        , Str "adipisicing"
+                        , Space
+                        , Str "elit,"
+                        , Space
+                        , Str "sed"
+                        , Space
+                        , Str "do"
+                        , Space
+                        , Str "eiusmod"
+                        , Space
+                        , Str "tempor"
+                        , Space
+                        , Str "incididunt"
+                        , Space
+                        , Str "ut"
+                        , Space
+                        , Str "labore"
+                        , Space
+                        , Str "et"
+                        , Space
+                        , Str "dolore"
+                        , Space
+                        , Str "magna"
+                        , Space
+                        , Str "aliqua."
+                        , Space
+                        , Str "Ut"
+                        , Space
+                        , Str "enim"
+                        , Space
+                        , Str "ad"
+                        , Space
+                        , Str "minim"
+                        , Space
+                        , Str "veniam,"
+                        , Space
+                        , Str "quis"
+                        , Space
+                        , Str "nostrud"
+                        , Space
+                        , Str "exercitation"
+                        , Space
+                        , Str "ullamco"
+                        , Space
+                        , Str "laboris"
+                        , Space
+                        , Str "nisi"
+                        , Space
+                        , Str "ut"
+                        , Space
+                        , Str "aliquip"
+                        , Space
+                        , Str "ex"
+                        , Space
+                        , Str "ea"
+                        , Space
+                        , Str "commodo"
+                        , Space
+                        , Str "consequat."
+                        ]
+                    ]
+                  , [ Plain
+                        [ Str "Lorem"
+                        , Space
+                        , Str "ipsum"
+                        , Space
+                        , Str "dolor"
+                        , Space
+                        , Str "sit"
+                        , Space
+                        , Str "amet,"
+                        , Space
+                        , Str "consectetur"
+                        , Space
+                        , Str "adipisicing"
+                        , Space
+                        , Str "elit,"
+                        , Space
+                        , Str "sed"
+                        , Space
+                        , Str "do"
+                        , Space
+                        , Str "eiusmod"
+                        , Space
+                        , Str "tempor"
+                        , Space
+                        , Str "incididunt"
+                        , Space
+                        , Str "ut"
+                        , Space
+                        , Str "labore"
+                        , Space
+                        , Str "et"
+                        , Space
+                        , Str "dolore"
+                        , Space
+                        , Str "magna"
+                        , Space
+                        , Str "aliqua."
+                        , Space
+                        , Str "Ut"
+                        , Space
+                        , Str "enim"
+                        , Space
+                        , Str "ad"
+                        , Space
+                        , Str "minim"
+                        , Space
+                        , Str "veniam,"
+                        , Space
+                        , Str "quis"
+                        , Space
+                        , Str "nostrud"
+                        , Space
+                        , Str "exercitation"
+                        , Space
+                        , Str "ullamco"
+                        , Space
+                        , Str "laboris"
+                        , Space
+                        , Str "nisi"
+                        , Space
+                        , Str "ut"
+                        , Space
+                        , Str "aliquip"
+                        , Space
+                        , Str "ex"
+                        , Space
+                        , Str "ea"
+                        , Space
+                        , Str "commodo"
+                        , Space
+                        , Str "consequat."
+                        ]
+                    ]
+                  ]
+              , Para
+                  [ Str "If"
+                  , Space
+                  , Str "the"
+                  , Space
+                  , Str "preceding"
+                  , Space
+                  , Str "list"
+                  , Space
+                  , Str "has"
+                  , Space
+                  , Str "the"
+                  , Space
+                  , Str "default"
+                  , Space
+                  , Str "setting"
+                  , Space
+                  , Str "(marker"
+                  , Space
+                  , Str "outside"
+                  , Space
+                  , Str "the"
+                  , Space
+                  , Str "indentation),"
+                  , Space
+                  , Str "the"
+                  , Space
+                  , Str "test"
+                  , Space
+                  , Str "passes."
+                  ]
+              ]
+          ]
+      , Div
+          ( "styling-xhtml-002.xhtml_style-list-start"
+          , [ "section" ]
+          , []
+          )
+          [ Header
+              3
+              ( "" , [] , [] )
+              [ Str "The"
+              , Space
+              , Str "HTML"
+              , Space
+              , Code ( "" , [] , [] ) "start"
+              , Space
+              , Str "attribute"
+              ]
+          , Div
+              ( "styling-xhtml-002.xhtml_style-050"
+              , [ "section" , "ctest" ]
+              , []
+              )
+              [ Header
+                  4
+                  ( "" , [] , [] )
+                  [ Span ( "" , [ "nature" ] , [] ) [ Str "[REQUIRED]" ]
+                  , Space
+                  , Span ( "" , [ "test-id" ] , [] ) [ Str "style-050" ]
+                  , Space
+                  , Str "Without"
+                  , Space
+                  , Code ( "" , [] , [] ) "list-style-type"
+                  , Space
+                  , Str "set"
+                  ]
+              , Para
+                  [ Str "Tests"
+                  , Space
+                  , Str "whether"
+                  , Space
+                  , Str "the"
+                  , Space
+                  , Code ( "" , [] , [] ) "start"
+                  , Space
+                  , Str "attribute"
+                  , Space
+                  , Str "is"
+                  , Space
+                  , Str "supported"
+                  , Space
+                  , Str "on"
+                  , Space
+                  , Str "a"
+                  , Space
+                  , Code ( "" , [] , [] ) "ol"
+                  , Space
+                  , Str "element"
+                  , Space
+                  , Str "with"
+                  , Space
+                  , Str "no"
+                  , Space
+                  , Code ( "" , [] , [] ) "list-style-type"
+                  , Space
+                  , Str "property."
+                  ]
+              , OrderedList
+                  ( 25 , DefaultStyle , DefaultDelim )
+                  [ [ Plain [ Str "Lorem" ] ]
+                  , [ Plain [ Str "Ipsum" ] ]
+                  , [ Plain [ Str "Dolor" ] ]
+                  , [ Plain [ Str "Sit" ] ]
+                  , [ Plain [ Str "Amet" ] ]
+                  ]
+              , Para
+                  [ Str "If"
+                  , Space
+                  , Str "the"
+                  , Space
+                  , Str "preceding"
+                  , Space
+                  , Str "list"
+                  , Space
+                  , Str "starts"
+                  , Space
+                  , Str "at"
+                  , Space
+                  , Str "25,"
+                  , Space
+                  , Str "the"
+                  , Space
+                  , Str "test"
+                  , Space
+                  , Str "passes."
+                  ]
+              ]
+          , Div
+              ( "styling-xhtml-002.xhtml_style-051"
+              , [ "section" , "ctest" ]
+              , []
+              )
+              [ Header
+                  4
+                  ( "" , [] , [] )
+                  [ Span ( "" , [ "nature" ] , [] ) [ Str "[REQUIRED]" ]
+                  , Space
+                  , Span ( "" , [ "test-id" ] , [] ) [ Str "style-051" ]
+                  , Space
+                  , Str "With"
+                  , Space
+                  , Code ( "" , [] , [] ) "list-style-type"
+                  , Space
+                  , Str "set"
+                  ]
+              , Para
+                  [ Str "Tests"
+                  , Space
+                  , Str "whether"
+                  , Space
+                  , Str "the"
+                  , Space
+                  , Code ( "" , [] , [] ) "start"
+                  , Space
+                  , Str "attribute"
+                  , Space
+                  , Str "is"
+                  , Space
+                  , Str "supported"
+                  , Space
+                  , Str "on"
+                  , Space
+                  , Str "a"
+                  , Space
+                  , Code ( "" , [] , [] ) "ol"
+                  , Space
+                  , Str "element"
+                  , Space
+                  , Str "with"
+                  , Space
+                  , Str "a"
+                  , Space
+                  , Code ( "" , [] , [] ) "list-style-type"
+                  , Space
+                  , Str "property."
+                  ]
+              , OrderedList
+                  ( 50 , DefaultStyle , DefaultDelim )
+                  [ [ Plain [ Str "Lorem" ] ]
+                  , [ Plain [ Str "Ipsum" ] ]
+                  , [ Plain [ Str "Dolor" ] ]
+                  , [ Plain [ Str "Sit" ] ]
+                  , [ Plain [ Str "Amet" ] ]
+                  ]
+              , Para
+                  [ Str "If"
+                  , Space
+                  , Str "the"
+                  , Space
+                  , Str "preceding"
+                  , Space
+                  , Str "list"
+                  , Space
+                  , Str "starts"
+                  , Space
+                  , Str "at"
+                  , Space
+                  , Str "'L'"
+                  , Space
+                  , Str "(50),"
+                  , Space
+                  , Str "the"
+                  , Space
+                  , Str "test"
+                  , Space
+                  , Str "passes."
+                  ]
+              ]
+          ]
+      ]
+  , Para [ Span ( "styling-xhtml-004.xhtml" , [] , [] ) [] ]
+  , Div
+      ( "styling-xhtml-004.xhtml_style-media-rules"
+      , [ "section" ]
+      , []
+      )
+      [ Header
+          2
+          ( "" , [] , [] )
+          [ Code ( "" , [] , [] ) "@media" , Space , Str "Rules" ]
+      , Div
+          ( "styling-xhtml-004.xhtml_style-210"
+          , [ "section" , "ctest" ]
+          , []
+          )
+          [ Header
+              3
+              ( "" , [] , [] )
+              [ Span ( "" , [ "nature" ] , [] ) [ Str "[REQUIRED]" ]
+              , Space
+              , Span ( "" , [ "test-id" ] , [] ) [ Str "style-210" ]
+              , Space
+              , Code ( "" , [] , [] ) "all"
+              ]
+          , Para
+              [ Str "Tests"
+              , Space
+              , Str "whether"
+              , Space
+              , Str "the"
+              , Space
+              , Code ( "" , [] , [] ) "@media"
+              , Space
+              , Str "rule"
+              , Space
+              , Str "set"
+              , Space
+              , Str "to"
+              , Space
+              , Code ( "" , [] , [] ) "all"
+              , Space
+              , Str "is"
+              , Space
+              , Str "supported."
+              ]
+          , Para [ Str "FAIL" ]
+          , Para
+              [ Str "If"
+              , Space
+              , Str "the"
+              , Space
+              , Str "preceding"
+              , Space
+              , Str "paragraph"
+              , Space
+              , Str "reads"
+              , Space
+              , Str "\"FAIL\","
+              , Space
+              , Str "the"
+              , Space
+              , Str "test"
+              , Space
+              , Str "fails."
+              ]
+          ]
+      , Div
+          ( "styling-xhtml-004.xhtml_style-211"
+          , [ "section" , "ctest" ]
+          , []
+          )
+          [ Header
+              3
+              ( "" , [] , [] )
+              [ Span ( "" , [ "nature" ] , [] ) [ Str "[REQUIRED]" ]
+              , Space
+              , Span ( "" , [ "test-id" ] , [] ) [ Str "style-211" ]
+              , Space
+              , Code ( "" , [] , [] ) "screen"
+              ]
+          , Para
+              [ Str "Tests"
+              , Space
+              , Str "whether"
+              , Space
+              , Str "the"
+              , Space
+              , Code ( "" , [] , [] ) "@media"
+              , Space
+              , Str "rule"
+              , Space
+              , Str "set"
+              , Space
+              , Str "to"
+              , Space
+              , Code ( "" , [] , [] ) "screen"
+              , Space
+              , Str "is"
+              , Space
+              , Str "supported."
+              ]
+          , Para [ Str "FAIL" ]
+          , Para
+              [ Str "If"
+              , Space
+              , Str "the"
+              , Space
+              , Str "preceding"
+              , Space
+              , Str "paragraph"
+              , Space
+              , Str "reads"
+              , Space
+              , Str "\"FAIL\","
+              , Space
+              , Str "the"
+              , Space
+              , Str "test"
+              , Space
+              , Str "fails."
+              ]
+          ]
+      , Div
+          ( "styling-xhtml-004.xhtml_style-212"
+          , [ "section" , "ctest" ]
+          , []
+          )
+          [ Header
+              3
+              ( "" , [] , [] )
+              [ Span ( "" , [ "nature" ] , [] ) [ Str "[REQUIRED]" ]
+              , Space
+              , Span ( "" , [ "test-id" ] , [] ) [ Str "style-212" ]
+              , Space
+              , Code ( "" , [] , [] ) "handheld"
+              ]
+          , Para
+              [ Str "Tests"
+              , Space
+              , Str "whether"
+              , Space
+              , Str "the"
+              , Space
+              , Code ( "" , [] , [] ) "@media"
+              , Space
+              , Str "rule"
+              , Space
+              , Str "set"
+              , Space
+              , Str "to"
+              , Space
+              , Code ( "" , [] , [] ) "handheld"
+              , Space
+              , Str "is"
+              , Space
+              , Str "supported."
+              ]
+          , Para [ Str "FAIL" ]
+          , Para
+              [ Str "If"
+              , Space
+              , Str "the"
+              , Space
+              , Str "preceding"
+              , Space
+              , Str "paragraph"
+              , Space
+              , Str "reads"
+              , Space
+              , Str "\"FAIL\","
+              , Space
+              , Str "the"
+              , Space
+              , Str "test"
+              , Space
+              , Str "fails."
+              ]
+          ]
+      , Div
+          ( "styling-xhtml-004.xhtml_style-213"
+          , [ "section" , "ctest" ]
+          , []
+          )
+          [ Header
+              3
+              ( "" , [] , [] )
+              [ Span ( "" , [ "nature" ] , [] ) [ Str "[REQUIRED]" ]
+              , Space
+              , Span ( "" , [ "test-id" ] , [] ) [ Str "style-213" ]
+              , Space
+              , Code ( "" , [] , [] ) "tv"
+              ]
+          , Para
+              [ Str "Tests"
+              , Space
+              , Str "whether"
+              , Space
+              , Str "the"
+              , Space
+              , Code ( "" , [] , [] ) "@media"
+              , Space
+              , Str "rule"
+              , Space
+              , Str "set"
+              , Space
+              , Str "to"
+              , Space
+              , Code ( "" , [] , [] ) "tv"
+              , Space
+              , Str "is"
+              , Space
+              , Str "supported."
+              ]
+          , Para [ Str "FAIL" ]
+          , Para
+              [ Str "If"
+              , Space
+              , Str "the"
+              , Space
+              , Str "preceding"
+              , Space
+              , Str "paragraph"
+              , Space
+              , Str "reads"
+              , Space
+              , Str "\"FAIL\","
+              , Space
+              , Str "the"
+              , Space
+              , Str "test"
+              , Space
+              , Str "fails."
+              ]
+          ]
+      , Div
+          ( "styling-xhtml-004.xhtml_style-220"
+          , [ "section" , "ctest" ]
+          , []
+          )
+          [ Header
+              3
+              ( "" , [] , [] )
+              [ Span ( "" , [ "nature" ] , [] ) [ Str "[REQUIRED]" ]
+              , Space
+              , Span ( "" , [ "test-id" ] , [] ) [ Str "style-220" ]
+              , Space
+              , Code ( "" , [] , [] ) "orientation:landscape"
+              ]
+          , Para
+              [ Str "Tests"
+              , Space
+              , Str "whether"
+              , Space
+              , Str "the"
+              , Space
+              , Code ( "" , [] , [] ) "@media"
+              , Space
+              , Str "rule"
+              , Space
+              , Str "set"
+              , Space
+              , Str "to"
+              , Space
+              , Code ( "" , [] , [] ) "orientation:landscape"
+              , Space
+              , Str "is"
+              , Space
+              , Str "supported."
+              ]
+          , Para [ Str "FAIL" ]
+          , Para
+              [ Str "If"
+              , Space
+              , Str "the"
+              , Space
+              , Str "preceding"
+              , Space
+              , Str "paragraph"
+              , Space
+              , Str "reads"
+              , Space
+              , Str "\"FAIL\""
+              , Space
+              , Str "when"
+              , Space
+              , Str "the"
+              , Space
+              , Str "device"
+              , Space
+              , Str "is"
+              , Space
+              , Str "held"
+              , Space
+              , Str "in"
+              , Space
+              , Str "landscape"
+              , Space
+              , Str "mode,"
+              , Space
+              , Str "and"
+              , Space
+              , Str "the"
+              , Space
+              , Str "device"
+              , Space
+              , Str "supports"
+              , Space
+              , Str "multiple"
+              , Space
+              , Str "orientations,"
+              , Space
+              , Str "the"
+              , Space
+              , Str "test"
+              , Space
+              , Str "fails."
+              ]
+          ]
+      , Div
+          ( "styling-xhtml-004.xhtml_style-221"
+          , [ "section" , "ctest" ]
+          , []
+          )
+          [ Header
+              3
+              ( "" , [] , [] )
+              [ Span ( "" , [ "nature" ] , [] ) [ Str "[REQUIRED]" ]
+              , Space
+              , Span ( "" , [ "test-id" ] , [] ) [ Str "style-221" ]
+              , Space
+              , Code ( "" , [] , [] ) "orientation:portrait"
+              ]
+          , Para
+              [ Str "Tests"
+              , Space
+              , Str "whether"
+              , Space
+              , Str "the"
+              , Space
+              , Code ( "" , [] , [] ) "@media"
+              , Space
+              , Str "rule"
+              , Space
+              , Str "set"
+              , Space
+              , Str "to"
+              , Space
+              , Code ( "" , [] , [] ) "orientation:portrait"
+              , Space
+              , Str "is"
+              , Space
+              , Str "supported."
+              ]
+          , Para [ Str "FAIL" ]
+          , Para
+              [ Str "If"
+              , Space
+              , Str "the"
+              , Space
+              , Str "preceding"
+              , Space
+              , Str "paragraph"
+              , Space
+              , Str "reads"
+              , Space
+              , Str "\"FAIL\""
+              , Space
+              , Str "when"
+              , Space
+              , Str "the"
+              , Space
+              , Str "device"
+              , Space
+              , Str "is"
+              , Space
+              , Str "held"
+              , Space
+              , Str "in"
+              , Space
+              , Str "portrait"
+              , Space
+              , Str "mode,"
+              , Space
+              , Str "and"
+              , Space
+              , Str "the"
+              , Space
+              , Str "device"
+              , Space
+              , Str "supports"
+              , Space
+              , Str "multiple"
+              , Space
+              , Str "orientations,"
+              , Space
+              , Str "the"
+              , Space
+              , Str "test"
+              , Space
+              , Str "fails."
+              ]
+          ]
+      , Div
+          ( "styling-xhtml-004.xhtml_style-230"
+          , [ "section" , "ctest" ]
+          , []
+          )
+          [ Header
+              3
+              ( "" , [] , [] )
+              [ Span ( "" , [ "nature" ] , [] ) [ Str "[REQUIRED]" ]
+              , Space
+              , Span ( "" , [ "test-id" ] , [] ) [ Str "style-230" ]
+              , Space
+              , Code ( "" , [] , [] ) "min-width"
+              ]
+          , Para
+              [ Str "Tests"
+              , Space
+              , Str "whether"
+              , Space
+              , Str "the"
+              , Space
+              , Code ( "" , [] , [] ) "@media"
+              , Space
+              , Str "rule"
+              , Space
+              , Str "set"
+              , Space
+              , Str "to"
+              , Space
+              , Code ( "" , [] , [] ) "min-width:200px"
+              , Space
+              , Str "is"
+              , Space
+              , Str "supported."
+              ]
+          , Para [ Str "FAIL" ]
+          , Para
+              [ Str "If"
+              , Space
+              , Str "the"
+              , Space
+              , Str "preceding"
+              , Space
+              , Str "paragraph"
+              , Space
+              , Str "reads"
+              , Space
+              , Str "\"FAIL\","
+              , Space
+              , Str "the"
+              , Space
+              , Str "test"
+              , Space
+              , Str "fails."
+              ]
+          ]
+      , Div
+          ( "styling-xhtml-004.xhtml_style-231"
+          , [ "section" , "ctest" ]
+          , []
+          )
+          [ Header
+              3
+              ( "" , [] , [] )
+              [ Span ( "" , [ "nature" ] , [] ) [ Str "[REQUIRED]" ]
+              , Space
+              , Span ( "" , [ "test-id" ] , [] ) [ Str "style-231" ]
+              , Space
+              , Code ( "" , [] , [] ) "max-width"
+              ]
+          , Para
+              [ Str "Tests"
+              , Space
+              , Str "whether"
+              , Space
+              , Str "the"
+              , Space
+              , Code ( "" , [] , [] ) "@media"
+              , Space
+              , Str "rule"
+              , Space
+              , Str "set"
+              , Space
+              , Str "to"
+              , Space
+              , Code ( "" , [] , [] ) "max-width:2000px"
+              , Space
+              , Str "is"
+              , Space
+              , Str "supported."
+              ]
+          , Para [ Str "FAIL" ]
+          , Para
+              [ Str "If"
+              , Space
+              , Str "the"
+              , Space
+              , Str "preceding"
+              , Space
+              , Str "paragraph"
+              , Space
+              , Str "reads"
+              , Space
+              , Str "\"FAIL\","
+              , Space
+              , Str "the"
+              , Space
+              , Str "test"
+              , Space
+              , Str "fails."
+              ]
+          ]
+      , Div
+          ( "styling-xhtml-004.xhtml_style-240"
+          , [ "section" , "ctest" ]
+          , []
+          )
+          [ Header
+              3
+              ( "" , [] , [] )
+              [ Span ( "" , [ "nature" ] , [] ) [ Str "[REQUIRED]" ]
+              , Space
+              , Span ( "" , [ "test-id" ] , [] ) [ Str "style-240" ]
+              , Space
+              , Code ( "" , [] , [] ) "min-device-width"
+              ]
+          , Para
+              [ Str "Tests"
+              , Space
+              , Str "whether"
+              , Space
+              , Str "the"
+              , Space
+              , Code ( "" , [] , [] ) "@media"
+              , Space
+              , Str "rule"
+              , Space
+              , Str "set"
+              , Space
+              , Str "to"
+              , Space
+              , Code ( "" , [] , [] ) "min-device-width:200px"
+              , Space
+              , Str "is"
+              , Space
+              , Str "supported."
+              ]
+          , Para [ Str "FAIL" ]
+          , Para
+              [ Str "If"
+              , Space
+              , Str "the"
+              , Space
+              , Str "preceding"
+              , Space
+              , Str "paragraph"
+              , Space
+              , Str "reads"
+              , Space
+              , Str "\"FAIL\","
+              , Space
+              , Str "the"
+              , Space
+              , Str "test"
+              , Space
+              , Str "fails."
+              ]
+          ]
+      , Div
+          ( "styling-xhtml-004.xhtml_style-241"
+          , [ "section" , "ctest" ]
+          , []
+          )
+          [ Header
+              3
+              ( "" , [] , [] )
+              [ Span ( "" , [ "nature" ] , [] ) [ Str "[REQUIRED]" ]
+              , Space
+              , Span ( "" , [ "test-id" ] , [] ) [ Str "style-241" ]
+              , Space
+              , Code ( "" , [] , [] ) "max-device-width"
+              ]
+          , Para
+              [ Str "Tests"
+              , Space
+              , Str "whether"
+              , Space
+              , Str "the"
+              , Space
+              , Code ( "" , [] , [] ) "@media"
+              , Space
+              , Str "rule"
+              , Space
+              , Str "set"
+              , Space
+              , Str "to"
+              , Space
+              , Code ( "" , [] , [] ) "max-device-width:2000px"
+              , Space
+              , Str "is"
+              , Space
+              , Str "supported."
+              ]
+          , Para [ Str "FAIL" ]
+          , Para
+              [ Str "If"
+              , Space
+              , Str "the"
+              , Space
+              , Str "preceding"
+              , Space
+              , Str "paragraph"
+              , Space
+              , Str "reads"
+              , Space
+              , Str "\"FAIL\","
+              , Space
+              , Str "the"
+              , Space
+              , Str "test"
+              , Space
+              , Str "fails."
+              ]
+          ]
+      ]
+  , Para [ Span ( "styling-xhtml-005.xhtml" , [] , [] ) [] ]
+  , Div
+      ( "styling-xhtml-005.xhtml_style-text-xform"
+      , [ "section" ]
+      , []
+      )
+      [ Header
+          2
+          ( "" , [] , [] )
+          [ Str "The"
+          , Space
+          , Code ( "" , [] , [] ) "text-transform"
+          , Space
+          , Str "property"
+          ]
+      , Div
+          ( "styling-xhtml-005.xhtml_style-310"
+          , [ "section" , "ctest" ]
+          , []
+          )
+          [ Header
+              2
+              ( "" , [] , [] )
+              [ Span ( "" , [ "nature" ] , [] ) [ Str "[REQUIRED]" ]
+              , Space
+              , Span ( "" , [ "test-id" ] , [] ) [ Str "style-310" ]
+              , Space
+              , Code ( "" , [] , [] ) "uppercase"
+              ]
+          , Para
+              [ Str "Tests"
+              , Space
+              , Str "whether"
+              , Space
+              , Str "the"
+              , Space
+              , Code ( "" , [] , [] ) "text-transform"
+              , Space
+              , Str "property"
+              , Space
+              , Str "set"
+              , Space
+              , Str "to"
+              , Space
+              , Str "uppercase"
+              , Space
+              , Str "is"
+              , Space
+              , Str "supported."
+              ]
+          , Para
+              [ Str "Lorem"
+              , Space
+              , Str "ipsum"
+              , Space
+              , Str "dolor"
+              , Space
+              , Str "sit"
+              , Space
+              , Str "amet,"
+              , Space
+              , Str "consectetur"
+              , Space
+              , Str "adipisicing"
+              , Space
+              , Str "elit,"
+              , Space
+              , Str "sed"
+              , Space
+              , Str "do"
+              , Space
+              , Str "eiusmod"
+              , Space
+              , Str "tempor"
+              , Space
+              , Str "incididunt"
+              , Space
+              , Str "ut"
+              , Space
+              , Str "labore"
+              , Space
+              , Str "et"
+              , Space
+              , Str "dolore"
+              , Space
+              , Str "magna"
+              , Space
+              , Str "aliqua."
+              , Space
+              , Str "Ut"
+              , Space
+              , Str "enim"
+              , Space
+              , Str "ad"
+              , Space
+              , Str "minim"
+              , Space
+              , Str "veniam,"
+              , Space
+              , Str "quis"
+              , Space
+              , Str "nostrud"
+              , Space
+              , Str "exercitation"
+              , Space
+              , Str "ullamco"
+              , Space
+              , Str "laboris"
+              , Space
+              , Str "nisi"
+              , Space
+              , Str "ut"
+              , Space
+              , Str "aliquip"
+              , Space
+              , Str "ex"
+              , Space
+              , Str "ea"
+              , Space
+              , Str "commodo"
+              , Space
+              , Str "consequat."
+              , Space
+              , Str "Duis"
+              , Space
+              , Str "aute"
+              , Space
+              , Str "irure"
+              , Space
+              , Str "dolor"
+              , Space
+              , Str "in"
+              , Space
+              , Str "reprehenderit"
+              , Space
+              , Str "in"
+              , Space
+              , Str "voluptate"
+              , Space
+              , Str "velit"
+              , Space
+              , Str "esse"
+              , Space
+              , Str "cillum"
+              , Space
+              , Str "dolore"
+              , Space
+              , Str "eu"
+              , Space
+              , Str "fugiat"
+              , Space
+              , Str "nulla"
+              , Space
+              , Str "pariatur."
+              , Space
+              , Str "Excepteur"
+              , Space
+              , Str "sint"
+              , Space
+              , Str "occaecat"
+              , Space
+              , Str "cupidatat"
+              , Space
+              , Str "non"
+              , Space
+              , Str "proident,"
+              , Space
+              , Str "sunt"
+              , Space
+              , Str "in"
+              , Space
+              , Str "culpa"
+              , Space
+              , Str "qui"
+              , Space
+              , Str "officia"
+              , Space
+              , Str "deserunt"
+              , Space
+              , Str "mollit"
+              , Space
+              , Str "anim"
+              , Space
+              , Str "id"
+              , Space
+              , Str "est"
+              , Space
+              , Str "laborum."
+              ]
+          , Para
+              [ Str "If"
+              , Space
+              , Str "the"
+              , Space
+              , Str "preceding"
+              , Space
+              , Str "paragraph"
+              , Space
+              , Str "is"
+              , Space
+              , Str "in"
+              , Space
+              , Str "upper"
+              , Space
+              , Str "case,"
+              , Space
+              , Str "the"
+              , Space
+              , Str "test"
+              , Space
+              , Str "passes."
+              ]
+          ]
+      , Div
+          ( "styling-xhtml-005.xhtml_style-311"
+          , [ "section" , "ctest" ]
+          , []
+          )
+          [ Header
+              2
+              ( "" , [] , [] )
+              [ Span ( "" , [ "nature" ] , [] ) [ Str "[REQUIRED]" ]
+              , Space
+              , Span ( "" , [ "test-id" ] , [] ) [ Str "style-311" ]
+              , Space
+              , Code ( "" , [] , [] ) "capitalize"
+              ]
+          , Para
+              [ Str "Tests"
+              , Space
+              , Str "whether"
+              , Space
+              , Str "the"
+              , Space
+              , Code ( "" , [] , [] ) "text-transform"
+              , Space
+              , Str "property"
+              , Space
+              , Str "set"
+              , Space
+              , Str "to"
+              , Space
+              , Str "capitalize"
+              , Space
+              , Str "is"
+              , Space
+              , Str "supported."
+              ]
+          , Para
+              [ Str "Lorem"
+              , Space
+              , Str "ipsum"
+              , Space
+              , Str "dolor"
+              , Space
+              , Str "sit"
+              , Space
+              , Str "amet,"
+              , Space
+              , Str "consectetur"
+              , Space
+              , Str "adipisicing"
+              , Space
+              , Str "elit,"
+              , Space
+              , Str "sed"
+              , Space
+              , Str "do"
+              , Space
+              , Str "eiusmod"
+              , Space
+              , Str "tempor"
+              , Space
+              , Str "incididunt"
+              , Space
+              , Str "ut"
+              , Space
+              , Str "labore"
+              , Space
+              , Str "et"
+              , Space
+              , Str "dolore"
+              , Space
+              , Str "magna"
+              , Space
+              , Str "aliqua."
+              , Space
+              , Str "Ut"
+              , Space
+              , Str "enim"
+              , Space
+              , Str "ad"
+              , Space
+              , Str "minim"
+              , Space
+              , Str "veniam,"
+              , Space
+              , Str "quis"
+              , Space
+              , Str "nostrud"
+              , Space
+              , Str "exercitation"
+              , Space
+              , Str "ullamco"
+              , Space
+              , Str "laboris"
+              , Space
+              , Str "nisi"
+              , Space
+              , Str "ut"
+              , Space
+              , Str "aliquip"
+              , Space
+              , Str "ex"
+              , Space
+              , Str "ea"
+              , Space
+              , Str "commodo"
+              , Space
+              , Str "consequat."
+              , Space
+              , Str "Duis"
+              , Space
+              , Str "aute"
+              , Space
+              , Str "irure"
+              , Space
+              , Str "dolor"
+              , Space
+              , Str "in"
+              , Space
+              , Str "reprehenderit"
+              , Space
+              , Str "in"
+              , Space
+              , Str "voluptate"
+              , Space
+              , Str "velit"
+              , Space
+              , Str "esse"
+              , Space
+              , Str "cillum"
+              , Space
+              , Str "dolore"
+              , Space
+              , Str "eu"
+              , Space
+              , Str "fugiat"
+              , Space
+              , Str "nulla"
+              , Space
+              , Str "pariatur."
+              , Space
+              , Str "Excepteur"
+              , Space
+              , Str "sint"
+              , Space
+              , Str "occaecat"
+              , Space
+              , Str "cupidatat"
+              , Space
+              , Str "non"
+              , Space
+              , Str "proident,"
+              , Space
+              , Str "sunt"
+              , Space
+              , Str "in"
+              , Space
+              , Str "culpa"
+              , Space
+              , Str "qui"
+              , Space
+              , Str "officia"
+              , Space
+              , Str "deserunt"
+              , Space
+              , Str "mollit"
+              , Space
+              , Str "anim"
+              , Space
+              , Str "id"
+              , Space
+              , Str "est"
+              , Space
+              , Str "laborum."
+              ]
+          , Para
+              [ Str "If"
+              , Space
+              , Str "each"
+              , Space
+              , Str "first"
+              , Space
+              , Str "letter"
+              , Space
+              , Str "of"
+              , Space
+              , Str "each"
+              , Space
+              , Str "word"
+              , Space
+              , Str "in"
+              , Space
+              , Str "the"
+              , Space
+              , Str "preceding"
+              , Space
+              , Str "paragraph"
+              , Space
+              , Str "is"
+              , Space
+              , Str "in"
+              , Space
+              , Str "upper"
+              , Space
+              , Str "case,"
+              , Space
+              , Str "the"
+              , Space
+              , Str "test"
+              , Space
+              , Str "passes."
+              ]
+          ]
+      , Div
+          ( "styling-xhtml-005.xhtml_style-312"
+          , [ "section" , "ctest" ]
+          , []
+          )
+          [ Header
+              2
+              ( "" , [] , [] )
+              [ Span ( "" , [ "nature" ] , [] ) [ Str "[REQUIRED]" ]
+              , Space
+              , Span ( "" , [ "test-id" ] , [] ) [ Str "style-312" ]
+              , Space
+              , Code ( "" , [] , [] ) "lowercase"
+              ]
+          , Para
+              [ Str "Tests"
+              , Space
+              , Str "whether"
+              , Space
+              , Str "the"
+              , Space
+              , Code ( "" , [] , [] ) "text-transform"
+              , Space
+              , Str "property"
+              , Space
+              , Str "set"
+              , Space
+              , Str "to"
+              , Space
+              , Str "lowercase"
+              , Space
+              , Str "is"
+              , Space
+              , Str "supported."
+              ]
+          , Para
+              [ Str "Lorem"
+              , Space
+              , Str "ipsum"
+              , Space
+              , Str "dolor"
+              , Space
+              , Str "sit"
+              , Space
+              , Str "amet,"
+              , Space
+              , Str "consectetur"
+              , Space
+              , Str "adipisicing"
+              , Space
+              , Str "elit,"
+              , Space
+              , Str "sed"
+              , Space
+              , Str "do"
+              , Space
+              , Str "eiusmod"
+              , Space
+              , Str "tempor"
+              , Space
+              , Str "incididunt"
+              , Space
+              , Str "ut"
+              , Space
+              , Str "labore"
+              , Space
+              , Str "et"
+              , Space
+              , Str "dolore"
+              , Space
+              , Str "magna"
+              , Space
+              , Str "aliqua."
+              , Space
+              , Str "Ut"
+              , Space
+              , Str "enim"
+              , Space
+              , Str "ad"
+              , Space
+              , Str "minim"
+              , Space
+              , Str "veniam,"
+              , Space
+              , Str "quis"
+              , Space
+              , Str "nostrud"
+              , Space
+              , Str "exercitation"
+              , Space
+              , Str "ullamco"
+              , Space
+              , Str "laboris"
+              , Space
+              , Str "nisi"
+              , Space
+              , Str "ut"
+              , Space
+              , Str "aliquip"
+              , Space
+              , Str "ex"
+              , Space
+              , Str "ea"
+              , Space
+              , Str "commodo"
+              , Space
+              , Str "consequat."
+              , Space
+              , Str "Duis"
+              , Space
+              , Str "aute"
+              , Space
+              , Str "irure"
+              , Space
+              , Str "dolor"
+              , Space
+              , Str "in"
+              , Space
+              , Str "reprehenderit"
+              , Space
+              , Str "in"
+              , Space
+              , Str "voluptate"
+              , Space
+              , Str "velit"
+              , Space
+              , Str "esse"
+              , Space
+              , Str "cillum"
+              , Space
+              , Str "dolore"
+              , Space
+              , Str "eu"
+              , Space
+              , Str "fugiat"
+              , Space
+              , Str "nulla"
+              , Space
+              , Str "pariatur."
+              , Space
+              , Str "Excepteur"
+              , Space
+              , Str "sint"
+              , Space
+              , Str "occaecat"
+              , Space
+              , Str "cupidatat"
+              , Space
+              , Str "non"
+              , Space
+              , Str "proident,"
+              , Space
+              , Str "sunt"
+              , Space
+              , Str "in"
+              , Space
+              , Str "culpa"
+              , Space
+              , Str "qui"
+              , Space
+              , Str "officia"
+              , Space
+              , Str "deserunt"
+              , Space
+              , Str "mollit"
+              , Space
+              , Str "anim"
+              , Space
+              , Str "id"
+              , Space
+              , Str "est"
+              , Space
+              , Str "laborum."
+              ]
+          , Para
+              [ Str "If"
+              , Space
+              , Str "the"
+              , Space
+              , Str "preceding"
+              , Space
+              , Str "paragraph"
+              , Space
+              , Str "is"
+              , Space
+              , Str "in"
+              , Space
+              , Str "lower"
+              , Space
+              , Str "case,"
+              , Space
+              , Str "the"
+              , Space
+              , Str "test"
+              , Space
+              , Str "passes."
+              ]
+          ]
+      ]
+  , Para [ Span ( "styling-xhtml-006.xhtml" , [] , [] ) [] ]
+  , Div
+      ( "styling-xhtml-006.xhtml_style-ruby"
+      , [ "section" ]
+      , []
+      )
+      [ Header
+          2
+          ( "" , [] , [] )
+          [ Str "The"
+          , Space
+          , Code ( "" , [] , [] ) "epub-ruby-position"
+          , Space
+          , Str "property"
+          ]
+      , Div
+          ( "styling-xhtml-006.xhtml_style-410"
+          , [ "section" , "ctest" ]
+          , []
+          )
+          [ Header
+              2
+              ( "" , [] , [] )
+              [ Span ( "" , [ "nature" ] , [] ) [ Str "[REQUIRED]" ]
+              , Space
+              , Span ( "" , [ "test-id" ] , [] ) [ Str "style-410" ]
+              , Space
+              , Code ( "" , [] , [] ) "over"
+              ]
+          , Para
+              [ Str "Tests"
+              , Space
+              , Str "whether"
+              , Space
+              , Str "the"
+              , Space
+              , Code ( "" , [] , [] ) "-epub-ruby-position"
+              , Space
+              , Str "property"
+              , Space
+              , Str "set"
+              , Space
+              , Str "to"
+              , Space
+              , Str "over"
+              , Space
+              , Str "is"
+              , Space
+              , Str "supported."
+              ]
+          , Plain
+              [ RawInline (Format "html") "<ruby class=\"ruby-over\">"
+              , Strong [ Str "Lorem" , Space , Str "Ipsum" ]
+              , Space
+              , RawInline (Format "html") "<rp>"
+              , Str "("
+              , RawInline (Format "html") "</rp>"
+              , RawInline (Format "html") "<rt>"
+              , Str "Lorem"
+              , Space
+              , Str "Ipsum"
+              , RawInline (Format "html") "</rt>"
+              , RawInline (Format "html") "<rp>"
+              , Str ")"
+              , RawInline (Format "html") "</rp>"
+              , RawInline (Format "html") "</ruby>"
+              ]
+          , Para
+              [ Str "If"
+              , Space
+              , Str "the"
+              , Space
+              , Str "Ruby"
+              , Space
+              , Str "text"
+              , Space
+              , Str "is"
+              , Space
+              , Str "positioned"
+              , Space
+              , Str "on"
+              , Space
+              , Str "the"
+              , Space
+              , Link
+                  ( "" , [] , [] )
+                  [ Str "over" ]
+                  ( "http://www.w3.org/TR/css3-writing-modes/#over"
+                  , ""
+                  )
+              , Space
+              , Str "side"
+              , Space
+              , Str "of"
+              , Space
+              , Str "the"
+              , Space
+              , Str "ruby"
+              , Space
+              , Str "base,"
+              , Space
+              , Str "the"
+              , Space
+              , Str "test"
+              , Space
+              , Str "passes."
+              ]
+          ]
+      , Div
+          ( "styling-xhtml-006.xhtml_style-411"
+          , [ "section" , "ctest" ]
+          , []
+          )
+          [ Header
+              2
+              ( "" , [] , [] )
+              [ Span ( "" , [ "nature" ] , [] ) [ Str "[REQUIRED]" ]
+              , Space
+              , Span ( "" , [ "test-id" ] , [] ) [ Str "style-411" ]
+              , Space
+              , Code ( "" , [] , [] ) "under"
+              ]
+          , Para
+              [ Str "Tests"
+              , Space
+              , Str "whether"
+              , Space
+              , Str "the"
+              , Space
+              , Code ( "" , [] , [] ) "-epub-ruby-position"
+              , Space
+              , Str "property"
+              , Space
+              , Str "set"
+              , Space
+              , Str "to"
+              , Space
+              , Str "under"
+              , Space
+              , Str "is"
+              , Space
+              , Str "supported."
+              ]
+          , Plain
+              [ RawInline (Format "html") "<ruby class=\"ruby-under\">"
+              , Strong [ Str "Lorem" , Space , Str "Ipsum" ]
+              , Space
+              , RawInline (Format "html") "<rp>"
+              , Str "("
+              , RawInline (Format "html") "</rp>"
+              , RawInline (Format "html") "<rt>"
+              , Str "Lorem"
+              , Space
+              , Str "Ipsum"
+              , RawInline (Format "html") "</rt>"
+              , RawInline (Format "html") "<rp>"
+              , Str ")"
+              , RawInline (Format "html") "</rp>"
+              , RawInline (Format "html") "</ruby>"
+              ]
+          , Para
+              [ Str "If"
+              , Space
+              , Str "the"
+              , Space
+              , Str "Ruby"
+              , Space
+              , Str "text"
+              , Space
+              , Str "is"
+              , Space
+              , Str "positioned"
+              , Space
+              , Str "on"
+              , Space
+              , Str "the"
+              , Space
+              , Link
+                  ( "" , [] , [] )
+                  [ Str "under" ]
+                  ( "http://www.w3.org/TR/css3-writing-modes/#under"
+                  , ""
+                  )
+              , Space
+              , Str "side"
+              , Space
+              , Str "of"
+              , Space
+              , Str "the"
+              , Space
+              , Str "ruby"
+              , Space
+              , Str "base,"
+              , Space
+              , Str "the"
+              , Space
+              , Str "test"
+              , Space
+              , Str "passes."
+              ]
+          ]
+      , Div
+          ( "styling-xhtml-006.xhtml_style-412"
+          , [ "section" , "ctest" ]
+          , []
+          )
+          [ Header
+              2
+              ( "" , [] , [] )
+              [ Span ( "" , [ "nature" ] , [] ) [ Str "[REQUIRED]" ]
+              , Space
+              , Span ( "" , [ "test-id" ] , [] ) [ Str "style-412" ]
+              , Space
+              , Code ( "" , [] , [] ) "inter-character"
+              ]
+          , Para
+              [ Str "Tests"
+              , Space
+              , Str "whether"
+              , Space
+              , Str "the"
+              , Space
+              , Code ( "" , [] , [] ) "-epub-ruby-position"
+              , Space
+              , Str "property"
+              , Space
+              , Str "set"
+              , Space
+              , Str "to"
+              , Space
+              , Str "inter-caracter"
+              , Space
+              , Str "is"
+              , Space
+              , Str "supported."
+              ]
+          , Plain
+              [ RawInline
+                  (Format "html")
+                  "<ruby class=\"ruby-inter-character\">"
+              , Strong [ Str "Lorem" , Space , Str "Ipsum" ]
+              , Space
+              , RawInline (Format "html") "<rp>"
+              , Str "("
+              , RawInline (Format "html") "</rp>"
+              , RawInline (Format "html") "<rt>"
+              , Str "Lorem"
+              , Space
+              , Str "Ipsum"
+              , RawInline (Format "html") "</rt>"
+              , RawInline (Format "html") "<rp>"
+              , Str ")"
+              , RawInline (Format "html") "</rp>"
+              , RawInline (Format "html") "</ruby>"
+              ]
+          , Para
+              [ Str "If"
+              , Space
+              , Str "the"
+              , Space
+              , Str "Ruby"
+              , Space
+              , Str "text"
+              , Space
+              , Str "is"
+              , Space
+              , Str "positioned"
+              , Space
+              , Str "on"
+              , Space
+              , Str "the"
+              , Space
+              , Str "right"
+              , Space
+              , Str "side"
+              , Space
+              , Str "of"
+              , Space
+              , Str "the"
+              , Space
+              , Str "base"
+              , Space
+              , Str "text,"
+              , Space
+              , Str "the"
+              , Space
+              , Str "test"
+              , Space
+              , Str "passes."
+              ]
+          ]
+      ]
+  ]
diff --git a/test/epub/img.epub b/test/epub/img.epub
Binary files a/test/epub/img.epub and b/test/epub/img.epub differ
diff --git a/test/epub/img_no_cover.epub b/test/epub/img_no_cover.epub
new file mode 100644
Binary files /dev/null and b/test/epub/img_no_cover.epub differ
diff --git a/test/epub/wasteland.epub b/test/epub/wasteland.epub
Binary files a/test/epub/wasteland.epub and b/test/epub/wasteland.epub differ
diff --git a/test/epub/wasteland.native b/test/epub/wasteland.native
--- a/test/epub/wasteland.native
+++ b/test/epub/wasteland.native
@@ -1,941 +1,4602 @@
-[Para [Image ("",[],[]) [] ("wasteland-cover.jpg","")]
-,Para [Span ("wasteland-content.xhtml",[],[]) []]
-,Div ("wasteland-content.xhtml#frontmatter",["section"],[("type","frontmatter")])
- []
-,Div ("wasteland-content.xhtml#bodymatter",["section"],[("type","bodymatter")])
- [Div ("wasteland-content.xhtml#ch1",["section"],[])
-  [Header 2 ("",[],[]) [Str "I.",Space,Str "THE",Space,Str "BURIAL",Space,Str "OF",Space,Str "THE",Space,Str "DEAD"]
-  ,Div ("",["linegroup"],[])
-   [Div ("",[],[])
-    [Plain [Str "April",Space,Str "is",Space,Str "the",Space,Str "cruellest",Space,Str "month,",Space,Str "breeding"]]
-   ,Div ("",[],[])
-    [Plain [Str "Lilacs",Space,Str "out",Space,Str "of",Space,Str "the",Space,Str "dead",Space,Str "land,",Space,Str "mixing"]]
-   ,Div ("",[],[])
-    [Plain [Str "Memory",Space,Str "and",Space,Str "desire,",Space,Str "stirring"]]
-   ,Div ("",[],[])
-    [Plain [Str "Dull",Space,Str "roots",Space,Str "with",Space,Str "spring",Space,Str "rain."]]
-   ,Div ("",[],[])
-    [Plain [Str "Winter",Space,Str "kept",Space,Str "us",Space,Str "warm,",Space,Str "covering"]]
-   ,Div ("",[],[])
-    [Plain [Str "Earth",Space,Str "in",Space,Str "forgetful",Space,Str "snow,",Space,Str "feeding"]]
-   ,Div ("",[],[])
-    [Plain [Str "A",Space,Str "little",Space,Str "life",Space,Str "with",Space,Str "dried",Space,Str "tubers."]]
-   ,Div ("",[],[])
-    [Plain [Str "Summer",Space,Str "surprised",Space,Str "us,",Space,Str "coming",Space,Str "over",Space,Str "the",Space,Str "Starnbergersee"]]
-   ,Div ("",[],[])
-    [Plain [Str "With",Space,Str "a",Space,Str "shower",Space,Str "of",Space,Str "rain;",Space,Str "we",Space,Str "stopped",Space,Str "in",Space,Str "the",Space,Str "colonnade,"]]
-   ,Div ("",[],[])
-    [Plain [Str "And",Space,Str "went",Space,Str "on",Space,Str "in",Space,Str "sunlight,",Space,Str "into",Space,Str "the",Space,Str "Hofgarten,",Span ("",["lnum"],[]) [Str "10"]]]
-   ,Div ("",[],[])
-    [Plain [Str "And",Space,Str "drank",Space,Str "coffee,",Space,Str "and",Space,Str "talked",Space,Str "for",Space,Str "an",Space,Str "hour."]]
-   ,Div ("",[],[("lang","de")])
-    [Plain [Str "Bin",Space,Str "gar",Space,Str "keine",Space,Str "Russin,",Space,Str "stamm'",Space,Str "aus",Space,Str "Litauen,",Space,Str "echt",SoftBreak,Str "deutsch."]]
-   ,Div ("",[],[])
-    [Plain [Str "And",Space,Str "when",Space,Str "we",Space,Str "were",Space,Str "children,",Space,Str "staying",Space,Str "at",Space,Str "the",Space,Str "archduke's,"]]
-   ,Div ("",[],[])
-    [Plain [Str "My",Space,Str "cousin's,",Space,Str "he",Space,Str "took",Space,Str "me",Space,Str "out",Space,Str "on",Space,Str "a",Space,Str "sled,"]]
-   ,Div ("",[],[])
-    [Plain [Str "And",Space,Str "I",Space,Str "was",Space,Str "frightened.",Space,Str "He",Space,Str "said,",Space,Str "Marie,"]]
-   ,Div ("",[],[])
-    [Plain [Str "Marie,",Space,Str "hold",Space,Str "on",Space,Str "tight.",Space,Str "And",Space,Str "down",Space,Str "we",Space,Str "went."]]
-   ,Div ("",[],[])
-    [Plain [Str "In",Space,Str "the",Space,Str "mountains,",Space,Str "there",Space,Str "you",Space,Str "feel",Space,Str "free."]]
-   ,Div ("",[],[])
-    [Plain [Str "I",Space,Str "read,",Space,Str "much",Space,Str "of",Space,Str "the",Space,Str "night,",Space,Str "and",Space,Str "go",Space,Str "south",Space,Str "in",Space,Str "the",Space,Str "winter."]]]
-  ,Div ("",["linegroup"],[])
-   [Div ("",[],[])
-    [Plain [Str "What",Space,Str "are",Space,Str "the",Space,Str "roots",Space,Str "that",Space,Str "clutch,",Space,Str "what",Space,Str "branches",Space,Str "grow"]]
-   ,Div ("wasteland-content.xhtml#ln20",[],[])
-    [Plain [Str "Out",Space,Str "of",Space,Str "this",Space,Str "stony",Space,Str "rubbish?",Space,Str "Son",Space,Str "of",Space,Str "man,",Note [Para [Link ("",[],[]) [Str "Line",Space,Str "20."] ("#wasteland-content.xhtml#ln20",""),Space,Str "Cf.",Space,Str "Ezekiel",Space,Str "2:1."]]]
-    ,Div ("",[],[])
-     [Plain [Str "You",Space,Str "cannot",Space,Str "say,",Space,Str "or",Space,Str "guess,",Space,Str "for",Space,Str "you",Space,Str "know",Space,Str "only"]]
-    ,Div ("",[],[])
-     [Plain [Str "A",Space,Str "heap",Space,Str "of",Space,Str "broken",Space,Str "images,",Space,Str "where",Space,Str "the",Space,Str "sun",Space,Str "beats,"]]
-    ,Div ("wasteland-content.xhtml#ln23",[],[])
-     [Plain [Str "And",Space,Str "the",Space,Str "dead",Space,Str "tree",Space,Str "gives",Space,Str "no",Space,Str "shelter,",Space,Str "the",Space,Str "cricket",Space,Str "no",Space,Str "relief,",Note [Para [Link ("",[],[]) [Str "23."] ("#wasteland-content.xhtml#ln23",""),Space,Str "Cf.",Space,Str "Ecclesiastes",Space,Str "12:5."]]]
-     ,Div ("",[],[])
-      [Plain [Str "And",Space,Str "the",Space,Str "dry",Space,Str "stone",Space,Str "no",Space,Str "sound",Space,Str "of",Space,Str "water.",Space,Str "Only"]]
-     ,Div ("",[],[])
-      [Plain [Str "There",Space,Str "is",Space,Str "shadow",Space,Str "under",Space,Str "this",Space,Str "red",Space,Str "rock,"]]
-     ,Div ("",[],[])
-      [Plain [Str "(Come",Space,Str "in",Space,Str "under",Space,Str "the",Space,Str "shadow",Space,Str "of",Space,Str "this",Space,Str "red",Space,Str "rock),"]]
-     ,Div ("",[],[])
-      [Plain [Str "And",Space,Str "I",Space,Str "will",Space,Str "show",Space,Str "you",Space,Str "something",Space,Str "different",Space,Str "from",Space,Str "either"]]
-     ,Div ("",[],[])
-      [Plain [Str "Your",Space,Str "shadow",Space,Str "at",Space,Str "morning",Space,Str "striding",Space,Str "behind",Space,Str "you"]]
-     ,Div ("",[],[])
-      [Plain [Str "Or",Space,Str "your",Space,Str "shadow",Space,Str "at",Space,Str "evening",Space,Str "rising",Space,Str "to",Space,Str "meet",Space,Str "you;"]]
-     ,Div ("",[],[])
-      [Plain [Str "I",Space,Str "will",Space,Str "show",Space,Str "you",Space,Str "fear",Space,Str "in",Space,Str "a",Space,Str "handful",Space,Str "of",Space,Str "dust.",Span ("",["lnum"],[]) [Str "30"]]]
-     ,BlockQuote
-      [Div ("",[],[])
-       [Div ("wasteland-content.xhtml#ln31",[],[])
-        [Plain [Str "Frisch",Space,Str "weht",Space,Str "der",Space,Str "Wind",Note [Para [Link ("",[],[]) [Str "31."] ("#wasteland-content.xhtml#ln31",""),Space,Str "V.",Space,Str "Tristan",Space,Str "und",Space,Str "Isolde,",Space,Str "i,",Space,Str "verses",Space,Str "5-8."]]]
-        ,Div ("",[],[])
-         [Plain [Str "Der",Space,Str "Heimat",Space,Str "zu"]]
-        ,Div ("",[],[])
-         [Plain [Str "Mein",Space,Str "Irisch",Space,Str "Kind,"]]
-        ,Div ("",[],[])
-         [Plain [Str "Wo",Space,Str "weilest",Space,Str "du?"]]]
-       ,RawBlock (Format "html") "</blockquote>"
-       ,Div ("",[],[])
-        [Plain [Str "\"You",Space,Str "gave",Space,Str "me",Space,Str "hyacinths",Space,Str "first",Space,Str "a",Space,Str "year",Space,Str "ago;"]]
-       ,Div ("",[],[])
-        [Plain [Str "\"They",Space,Str "called",Space,Str "me",Space,Str "the",Space,Str "hyacinth",Space,Str "girl.\""]]
-       ,Div ("",[],[])
-        [Plain [Str "\8213Yet",Space,Str "when",Space,Str "we",Space,Str "came",Space,Str "back,",Space,Str "late,",Space,Str "from",Space,Str "the",Space,Str "Hyacinth",SoftBreak,Str "garden,"]]
-       ,Div ("",[],[])
-        [Plain [Str "Your",Space,Str "arms",Space,Str "full,",Space,Str "and",Space,Str "your",Space,Str "hair",Space,Str "wet,",Space,Str "I",Space,Str "could",Space,Str "not"]]
-       ,Div ("",[],[])
-        [Plain [Str "Speak,",Space,Str "and",Space,Str "my",Space,Str "eyes",Space,Str "failed,",Space,Str "I",Space,Str "was",Space,Str "neither"]]
-       ,Div ("",[],[])
-        [Plain [Str "Living",Space,Str "nor",Space,Str "dead,",Space,Str "and",Space,Str "I",Space,Str "knew",Space,Str "nothing,",Span ("",["lnum"],[]) [Str "40"]]]
-       ,Div ("",[],[])
-        [Plain [Str "Looking",Space,Str "into",Space,Str "the",Space,Str "heart",Space,Str "of",Space,Str "light,",Space,Str "the",Space,Str "silence."]]
-       ,Div ("wasteland-content.xhtml#ln42",[],[("lang","de")])
-        [Plain [Emph [Str "Od'",Space,Str "und",Space,Str "leer",Space,Str "das",Space,Str "Meer"],Str ".",Note [Para [Link ("",[],[]) [Str "42."] ("#wasteland-content.xhtml#ln42",""),Space,Str "Id.",Space,Str "iii,",Space,Str "verse",Space,Str "24."]]]
-        ,Div ("",["linegroup"],[])
-         [Div ("",[],[])
-          [Plain [Str "Madame",Space,Str "Sosostris,",Space,Str "famous",Space,Str "clairvoyante,"]]
-         ,Div ("",[],[])
-          [Plain [Str "Had",Space,Str "a",Space,Str "bad",Space,Str "cold,",Space,Str "nevertheless"]]
-         ,Div ("",[],[])
-          [Plain [Str "Is",Space,Str "known",Space,Str "to",Space,Str "be",Space,Str "the",Space,Str "wisest",Space,Str "woman",Space,Str "in",Space,Str "Europe,"]]
-         ,Div ("wasteland-content.xhtml#ln46",[],[])
-          [Plain [Str "With",Space,Str "a",Space,Str "wicked",Space,Str "pack",Space,Str "of",Space,Str "cards.",Space,Str "Here,",Space,Str "said",Space,Str "she,",Note [Para [Link ("",[],[]) [Str "46."] ("#wasteland-content.xhtml#ln46",""),Space,Str "I",Space,Str "am",Space,Str "not",Space,Str "familiar",Space,Str "with",Space,Str "the",Space,Str "exact",Space,Str "constitution",Space,Str "of",Space,Str "the",Space,Str "Tarot",Space,Str "pack",Space,Str "of",SoftBreak,Str "cards,",Space,Str "from",Space,Str "which",Space,Str "I",Space,Str "have",Space,Str "obviously",Space,Str "departed",Space,Str "to",Space,Str "suit",Space,Str "my",Space,Str "own",Space,Str "convenience.",SoftBreak,Str "The",Space,Str "Hanged",Space,Str "Man,",Space,Str "a",Space,Str "member",Space,Str "of",Space,Str "the",Space,Str "traditional",Space,Str "pack,",Space,Str "fits",Space,Str "my",Space,Str "purpose",Space,Str "in",Space,Str "two",SoftBreak,Str "ways:",Space,Str "because",Space,Str "he",Space,Str "is",Space,Str "associated",Space,Str "in",Space,Str "my",Space,Str "mind",Space,Str "with",Space,Str "the",Space,Str "Hanged",Space,Str "God",Space,Str "of",Space,Str "Frazer,",SoftBreak,Str "and",Space,Str "because",Space,Str "I",Space,Str "associate",Space,Str "him",Space,Str "with",Space,Str "the",Space,Str "hooded",Space,Str "figure",Space,Str "in",Space,Str "the",Space,Str "passage",Space,Str "of",Space,Str "the",SoftBreak,Str "disciples",Space,Str "to",Space,Str "Emmaus",Space,Str "in",Space,Str "Part",Space,Str "V.",Space,Str "The",Space,Str "Phoenician",Space,Str "Sailor",Space,Str "and",Space,Str "the",Space,Str "Merchant",SoftBreak,Str "appear",Space,Str "later;",Space,Str "also",Space,Str "the",Space,Str "\"crowds",Space,Str "of",Space,Str "people,\"",Space,Str "and",Space,Str "Death",Space,Str "by",Space,Str "Water",Space,Str "is",SoftBreak,Str "executed",Space,Str "in",Space,Str "Part",Space,Str "IV.",Space,Str "The",Space,Str "Man",Space,Str "with",Space,Str "Three",Space,Str "Staves",Space,Str "(an",Space,Str "authentic",Space,Str "member",Space,Str "of",SoftBreak,Str "the",Space,Str "Tarot",Space,Str "pack)",Space,Str "I",Space,Str "associate,",Space,Str "quite",Space,Str "arbitrarily,",Space,Str "with",Space,Str "the",Space,Str "Fisher",Space,Str "King",SoftBreak,Str "himself."]]]
-          ,Div ("",[],[])
-           [Plain [Str "Is",Space,Str "your",Space,Str "card,",Space,Str "the",Space,Str "drowned",Space,Str "Phoenician",Space,Str "Sailor,"]]
-          ,Div ("",[],[])
-           [Plain [Str "(Those",Space,Str "are",Space,Str "pearls",Space,Str "that",Space,Str "were",Space,Str "his",Space,Str "eyes.",Space,Str "Look!)"]]
-          ,Div ("",[],[])
-           [Plain [Str "Here",Space,Str "is",Space,Str "Belladonna,",Space,Str "the",Space,Str "Lady",Space,Str "of",Space,Str "the",Space,Str "Rocks,"]]
-          ,Div ("",[],[])
-           [Plain [Str "The",Space,Str "lady",Space,Str "of",Space,Str "situations.",Span ("",["lnum"],[]) [Str "50"]]]
-          ,Div ("",[],[])
-           [Plain [Str "Here",Space,Str "is",Space,Str "the",Space,Str "man",Space,Str "with",Space,Str "three",Space,Str "staves,",Space,Str "and",Space,Str "here",Space,Str "the",Space,Str "Wheel,"]]
-          ,Div ("",[],[])
-           [Plain [Str "And",Space,Str "here",Space,Str "is",Space,Str "the",Space,Str "one-eyed",Space,Str "merchant,",Space,Str "and",Space,Str "this",Space,Str "card,"]]
-          ,Div ("",[],[])
-           [Plain [Str "Which",Space,Str "is",Space,Str "blank,",Space,Str "is",Space,Str "something",Space,Str "he",Space,Str "carries",Space,Str "on",Space,Str "his",Space,Str "back,"]]
-          ,Div ("",[],[])
-           [Plain [Str "Which",Space,Str "I",Space,Str "am",Space,Str "forbidden",Space,Str "to",Space,Str "see.",Space,Str "I",Space,Str "do",Space,Str "not",Space,Str "find"]]
-          ,Div ("",[],[])
-           [Plain [Str "The",Space,Str "Hanged",Space,Str "Man.",Space,Str "Fear",Space,Str "death",Space,Str "by",Space,Str "water."]]
-          ,Div ("",[],[])
-           [Plain [Str "I",Space,Str "see",Space,Str "crowds",Space,Str "of",Space,Str "people,",Space,Str "walking",Space,Str "round",Space,Str "in",Space,Str "a",Space,Str "ring."]]
-          ,Div ("",[],[])
-           [Plain [Str "Thank",Space,Str "you.",Space,Str "If",Space,Str "you",Space,Str "see",Space,Str "dear",Space,Str "Mrs.",Space,Str "Equitone,"]]
-          ,Div ("",[],[])
-           [Plain [Str "Tell",Space,Str "her",Space,Str "I",Space,Str "bring",Space,Str "the",Space,Str "horoscope",Space,Str "myself:"]]
-          ,Div ("",[],[])
-           [Plain [Str "One",Space,Str "must",Space,Str "be",Space,Str "so",Space,Str "careful",Space,Str "these",Space,Str "days."]]]
-         ,Div ("",["linegroup"],[])
-          [Div ("wasteland-content.xhtml#ln60",[],[])
-           [Plain [Str "Unreal",Space,Str "City,",Note [Para [Link ("",[],[]) [Str "60."] ("#wasteland-content.xhtml#ln60",""),Space,Str "Cf.",Space,Str "Baudelaire:"],BlockQuote [Para [Str "\"Fourmillante",Space,Str "cite;,",Space,Str "cite;",Space,Str "pleine",Space,Str "de",Space,Str "reves,",LineBreak,Str "Ou",Space,Str "le",Space,Str "spectre",Space,Str "en",SoftBreak,Str "plein",Space,Str "jour",Space,Str "raccroche",Space,Str "le",Space,Str "passant.\""]]]]
-           ,Div ("",[],[])
-            [Plain [Str "Under",Space,Str "the",Space,Str "brown",Space,Str "fog",Space,Str "of",Space,Str "a",Space,Str "winter",Space,Str "dawn,"]]
-           ,Div ("",[],[])
-            [Plain [Str "A",Space,Str "crowd",Space,Str "flowed",Space,Str "over",Space,Str "London",Space,Str "Bridge,",Space,Str "so",Space,Str "many,"]]
-           ,Div ("wasteland-content.xhtml#ln63",[],[])
-            [Plain [Str "I",Space,Str "had",Space,Str "not",Space,Str "thought",Space,Str "death",Space,Str "had",Space,Str "undone",Space,Str "so",Space,Str "many.",Note [Para [Link ("",[],[]) [Str "63."] ("#wasteland-content.xhtml#ln63",""),Space,Str "Cf.",Space,Str "Inferno,",Space,Str "iii.",Space,Str "55-7."],BlockQuote [Para [Str "\"si",Space,Str "lunga",Space,Str "tratta",LineBreak,Str "di",Space,Str "gente,",Space,Str "ch'io",Space,Str "non",Space,Str "avrei",Space,Str "mai",Space,Str "creduto",LineBreak,Str "che",SoftBreak,Str "morte",Space,Str "tanta",Space,Str "n'avesse",Space,Str "disfatta.\""]]]]
-            ,Div ("wasteland-content.xhtml#ln64",[],[])
-             [Plain [Str "Sighs,",Space,Str "short",Space,Str "and",Space,Str "infrequent,",Space,Str "were",Space,Str "exhaled,",Note [Para [Link ("",[],[]) [Str "64."] ("#wasteland-content.xhtml#ln64",""),Space,Str "Cf.",Space,Str "Inferno,",Space,Str "iv.",Space,Str "25-7:"],BlockQuote [Para [Str "\"Quivi,",Space,Str "secondo",Space,Str "che",Space,Str "per",Space,Str "ascoltahre,",LineBreak,Str "\"non",Space,Str "avea",Space,Str "pianto,",Space,Str "ma'",Space,Str "che",Space,Str "di",SoftBreak,Str "sospiri,",LineBreak,Str "\"che",Space,Str "l'aura",Space,Str "eterna",Space,Str "facevan",Space,Str "tremare.\""]]]]
-             ,Div ("",[],[])
-              [Plain [Str "And",Space,Str "each",Space,Str "man",Space,Str "fixed",Space,Str "his",Space,Str "eyes",Space,Str "before",Space,Str "his",Space,Str "feet."]]
-             ,Div ("",[],[])
-              [Plain [Str "Flowed",Space,Str "up",Space,Str "the",Space,Str "hill",Space,Str "and",Space,Str "down",Space,Str "King",Space,Str "William",Space,Str "Street,"]]
-             ,Div ("",[],[])
-              [Plain [Str "To",Space,Str "where",Space,Str "Saint",Space,Str "Mary",Space,Str "Woolnoth",Space,Str "kept",Space,Str "the",Space,Str "hours"]]
-             ,Div ("wasteland-content.xhtml#ln68",[],[])
-              [Plain [Str "With",Space,Str "a",Space,Str "dead",Space,Str "sound",Space,Str "on",Space,Str "the",Space,Str "final",Space,Str "stroke",Space,Str "of",Space,Str "nine.",Note [Para [Link ("",[],[]) [Str "68."] ("#wasteland-content.xhtml#ln68",""),Space,Str "A",Space,Str "phenomenon",Space,Str "which",Space,Str "I",Space,Str "have",Space,Str "often",Space,Str "noticed."]]]
-              ,Div ("",[],[])
-               [Plain [Str "There",Space,Str "I",Space,Str "saw",Space,Str "one",Space,Str "I",Space,Str "knew,",Space,Str "and",Space,Str "stopped",Space,Str "him,",Space,Str "crying",SoftBreak,Str "\"Stetson!"]]
-              ,Div ("",[],[])
-               [Plain [Str "\"You",Space,Str "who",Space,Str "were",Space,Str "with",Space,Str "me",Space,Str "in",Space,Str "the",Space,Str "ships",Space,Str "at",Space,Str "Mylae!",Span ("",["lnum"],[]) [Str "70"]]]
-              ,Div ("",[],[])
-               [Plain [Str "\"That",Space,Str "corpse",Space,Str "you",Space,Str "planted",Space,Str "last",Space,Str "year",Space,Str "in",Space,Str "your",Space,Str "garden,"]]
-              ,Div ("",[],[])
-               [Plain [Str "\"Has",Space,Str "it",Space,Str "begun",Space,Str "to",Space,Str "sprout?",Space,Str "Will",Space,Str "it",Space,Str "bloom",Space,Str "this",Space,Str "year?"]]
-              ,Div ("",[],[])
-               [Plain [Str "\"Or",Space,Str "has",Space,Str "the",Space,Str "sudden",Space,Str "frost",Space,Str "disturbed",Space,Str "its",Space,Str "bed?"]]]
-             ,Div ("",["linegroup"],[])
-              [Div ("wasteland-content.xhtml#ln74",[],[])
-               [Plain [Str "\"Oh",Space,Str "keep",Space,Str "the",Space,Str "Dog",Space,Str "far",Space,Str "hence,",Space,Str "that's",Space,Str "friend",Space,Str "to",Space,Str "men,",Note [Para [Link ("",[],[]) [Str "74."] ("#wasteland-content.xhtml#ln74",""),Space,Str "Cf.",Space,Str "the",Space,Str "Dirge",Space,Str "in",Space,Str "Webster's",Space,Str "White",Space,Str "Devil",Space,Str "."]]]
-               ,Div ("",[],[])
-                [Plain [Str "\"Or",Space,Str "with",Space,Str "his",Space,Str "nails",Space,Str "he'll",Space,Str "dig",Space,Str "it",Space,Str "up",Space,Str "again!"]]
-               ,Div ("wasteland-content.xhtml#ln76",[],[])
-                [Plain [Str "\"You!",Space,Span ("",[],[("lang","fr")]) [Str "hypocrite",Space,Str "lecteur!",Space,Str "-",Space,Str "mon",Space,Str "semblable,",Space,Str "-",SoftBreak,Str "mon",Space,Str "frere"],Space,Str "!\"",Note [Para [Link ("",[],[]) [Str "76."] ("#wasteland-content.xhtml#ln76",""),Space,Str "V.",Space,Str "Baudelaire,",Space,Str "Preface",Space,Str "to",Space,Str "Fleurs",Space,Str "du",Space,Str "Mal."]]]
-                ,Div ("wasteland-content.xhtml#ch2",["section"],[])
-                 [Header 2 ("",[],[]) [Str "II.",Space,Str "A",Space,Str "GAME",Space,Str "OF",Space,Str "CHESS"]
-                 ,Div ("",["linegroup"],[])
-                  [Div ("wasteland-content.xhtml#ln77",[],[])
-                   [Plain [Str "The",Space,Str "Chair",Space,Str "she",Space,Str "sat",Space,Str "in,",Space,Str "like",Space,Str "a",Space,Str "burnished",Space,Str "throne,",Note [Para [Link ("",[],[]) [Str "77."] ("#wasteland-content.xhtml#ln77",""),Space,Str "Cf.",Space,Str "Antony",Space,Str "and",Space,Str "Cleopatra,",Space,Str "II.",Space,Str "ii.,",Space,Str "l.",Space,Str "190."]]]
-                   ,Div ("",[],[])
-                    [Plain [Str "Glowed",Space,Str "on",Space,Str "the",Space,Str "marble,",Space,Str "where",Space,Str "the",Space,Str "glass"]]
-                   ,Div ("",[],[])
-                    [Plain [Str "Held",Space,Str "up",Space,Str "by",Space,Str "standards",Space,Str "wrought",Space,Str "with",Space,Str "fruited",Space,Str "vines"]]
-                   ,Div ("",[],[])
-                    [Plain [Str "From",Space,Str "which",Space,Str "a",Space,Str "golden",Space,Str "Cupidon",Space,Str "peeped",Space,Str "out",Span ("",["lnum"],[]) [Str "80"]]]
-                   ,Div ("",[],[])
-                    [Plain [Str "(Another",Space,Str "hid",Space,Str "his",Space,Str "eyes",Space,Str "behind",Space,Str "his",Space,Str "wing)"]]
-                   ,Div ("",[],[])
-                    [Plain [Str "Doubled",Space,Str "the",Space,Str "flames",Space,Str "of",Space,Str "sevenbranched",Space,Str "candelabra"]]
-                   ,Div ("",[],[])
-                    [Plain [Str "Reflecting",Space,Str "light",Space,Str "upon",Space,Str "the",Space,Str "table",Space,Str "as"]]
-                   ,Div ("",[],[])
-                    [Plain [Str "The",Space,Str "glitter",Space,Str "of",Space,Str "her",Space,Str "jewels",Space,Str "rose",Space,Str "to",Space,Str "meet",Space,Str "it,"]]
-                   ,Div ("",[],[])
-                    [Plain [Str "From",Space,Str "satin",Space,Str "cases",Space,Str "poured",Space,Str "in",Space,Str "rich",Space,Str "profusion;"]]
-                   ,Div ("",[],[])
-                    [Plain [Str "In",Space,Str "vials",Space,Str "of",Space,Str "ivory",Space,Str "and",Space,Str "coloured",Space,Str "glass"]]
-                   ,Div ("",[],[])
-                    [Plain [Str "Unstoppered,",Space,Str "lurked",Space,Str "her",Space,Str "strange",Space,Str "synthetic",Space,Str "perfumes,"]]
-                   ,Div ("",[],[])
-                    [Plain [Str "Unguent,",Space,Str "powdered,",Space,Str "or",Space,Str "liquid",Space,Str "-",Space,Str "troubled,",Space,Str "confused"]]
-                   ,Div ("",[],[])
-                    [Plain [Str "And",Space,Str "drowned",Space,Str "the",Space,Str "sense",Space,Str "in",Space,Str "odours;",Space,Str "stirred",Space,Str "by",Space,Str "the",Space,Str "air"]]
-                   ,Div ("",[],[])
-                    [Plain [Str "That",Space,Str "freshened",Space,Str "from",Space,Str "the",Space,Str "window,",Space,Str "these",Space,Str "ascended",Span ("",["lnum"],[]) [Str "90"]]]
-                   ,Div ("",[],[])
-                    [Plain [Str "In",Space,Str "fattening",Space,Str "the",Space,Str "prolonged",Space,Str "candle-flames,"]]
-                   ,Div ("wasteland-content.xhtml#ln92",[],[])
-                    [Plain [Str "Flung",Space,Str "their",Space,Str "smoke",Space,Str "into",Space,Str "the",Space,Str "laquearia,",Note [Para [Link ("",[],[]) [Str "92."] ("#wasteland-content.xhtml#ln92",""),Space,Str "Laquearia.",Space,Str "V.",Space,Str "Aeneid,",Space,Str "I.",Space,Str "726:"],BlockQuote [Para [Str "dependent",Space,Str "lychni",Space,Str "laquearibus",Space,Str "aureis",Space,Str "incensi,",Space,Str "et",Space,Str "noctem",SoftBreak,Str "flammis",LineBreak,Str "funalia",Space,Str "vincunt."]]]]
-                    ,Div ("",[],[])
-                     [Plain [Str "Stirring",Space,Str "the",Space,Str "pattern",Space,Str "on",Space,Str "the",Space,Str "coffered",Space,Str "ceiling."]]
-                    ,Div ("",[],[])
-                     [Plain [Str "Huge",Space,Str "sea-wood",Space,Str "fed",Space,Str "with",Space,Str "copper"]]
-                    ,Div ("",[],[])
-                     [Plain [Str "Burned",Space,Str "green",Space,Str "and",Space,Str "orange,",Space,Str "framed",Space,Str "by",Space,Str "the",Space,Str "coloured",Space,Str "stone,"]]
-                    ,Div ("",[],[])
-                     [Plain [Str "In",Space,Str "which",Space,Str "sad",Space,Str "light",Space,Str "a",Space,Str "carved",Space,Str "dolphin",Space,Str "swam."]]
-                    ,Div ("",[],[])
-                     [Plain [Str "Above",Space,Str "the",Space,Str "antique",Space,Str "mantel",Space,Str "was",Space,Str "displayed"]]
-                    ,Div ("wasteland-content.xhtml#ln98",[],[])
-                     [Plain [Str "As",Space,Str "though",Space,Str "a",Space,Str "window",Space,Str "gave",Space,Str "upon",Space,Str "the",Space,Str "sylvan",Space,Str "scene",Note [Para [Link ("",[],[]) [Str "98."] ("#wasteland-content.xhtml#ln98",""),Space,Str "Sylvan",Space,Str "scene.",Space,Str "V.",Space,Str "Milton,",Space,Str "Paradise",Space,Str "Lost,",Space,Str "iv.",Space,Str "140."]]]
-                     ,Div ("wasteland-content.xhtml#ln99",[],[])
-                      [Plain [Str "The",Space,Str "change",Space,Str "of",Space,Str "Philomel,",Space,Str "by",Space,Str "the",Space,Str "barbarous",Space,Str "king",Note [Para [Link ("",[],[]) [Str "99."] ("#wasteland-content.xhtml#ln99",""),Space,Str "V.",Space,Str "Ovid,",Space,Str "Metamorphoses,",Space,Str "vi,",Space,Str "Philomela."]]]
-                      ,Div ("wasteland-content.xhtml#ln100",[],[])
-                       [Plain [Str "So",Space,Str "rudely",Space,Str "forced;",Space,Str "yet",Space,Str "there",Space,Str "the",Space,Str "nightingale",Note [Para [Link ("",[],[]) [Str "100."] ("#wasteland-content.xhtml#ln100",""),Space,Str "Cf.",Space,Str "Part",Space,Str "III,",Space,Str "l.",Space,Str "204."]]]
-                       ,Div ("",[],[])
-                        [Plain [Str "Filled",Space,Str "all",Space,Str "the",Space,Str "desert",Space,Str "with",Space,Str "inviolable",Space,Str "voice"]]
-                       ,Div ("",[],[])
-                        [Plain [Str "And",Space,Str "still",Space,Str "she",Space,Str "cried,",Space,Str "and",Space,Str "still",Space,Str "the",Space,Str "world",Space,Str "pursues,"]]
-                       ,Div ("",[],[])
-                        [Plain [Str "\"Jug",Space,Str "Jug\"",Space,Str "to",Space,Str "dirty",Space,Str "ears."]]
-                       ,Div ("",[],[])
-                        [Plain [Str "And",Space,Str "other",Space,Str "withered",Space,Str "stumps",Space,Str "of",Space,Str "time"]]
-                       ,Div ("",[],[])
-                        [Plain [Str "Were",Space,Str "told",Space,Str "upon",Space,Str "the",Space,Str "walls;",Space,Str "staring",Space,Str "forms"]]
-                       ,Div ("",[],[])
-                        [Plain [Str "Leaned",Space,Str "out,",Space,Str "leaning,",Space,Str "hushing",Space,Str "the",Space,Str "room",Space,Str "enclosed."]]
-                       ,Div ("",[],[])
-                        [Plain [Str "Footsteps",Space,Str "shuffled",Space,Str "on",Space,Str "the",Space,Str "stair."]]
-                       ,Div ("",[],[])
-                        [Plain [Str "Under",Space,Str "the",Space,Str "firelight,",Space,Str "under",Space,Str "the",Space,Str "brush,",Space,Str "her",Space,Str "hair"]]
-                       ,Div ("",[],[])
-                        [Plain [Str "Spread",Space,Str "out",Space,Str "in",Space,Str "fiery",Space,Str "points"]]
-                       ,Div ("",[],[])
-                        [Plain [Str "Glowed",Space,Str "into",Space,Str "words,",Space,Str "then",Space,Str "would",Space,Str "be",Space,Str "savagely",Space,Str "still.",Span ("",["lnum"],[]) [Str "110"]]]]
-                      ,Div ("",["linegroup"],[])
-                       [Div ("",["linegroup"],[])
-                        [Div ("",[],[])
-                         [Plain [Str "\"My",Space,Str "nerves",Space,Str "are",Space,Str "bad",Space,Str "to-night.",Space,Str "Yes,",Space,Str "bad.",Space,Str "Stay",Space,Str "with",Space,Str "me."]]
-                        ,Div ("",[],[])
-                         [Plain [Str "\"Speak",Space,Str "to",Space,Str "me.",Space,Str "Why",Space,Str "do",Space,Str "you",Space,Str "never",Space,Str "speak.",Space,Str "Speak."]]
-                        ,Div ("",[],[])
-                         [Plain [Str "\"What",Space,Str "are",Space,Str "you",Space,Str "thinking",Space,Str "of?",Space,Str "What",Space,Str "thinking?",Space,Str "What?"]]
-                        ,Div ("",[],[])
-                         [Plain [Str "\"I",Space,Str "never",Space,Str "know",Space,Str "what",Space,Str "you",Space,Str "are",Space,Str "thinking.",Space,Str "Think.\""]]]
-                       ,Div ("",["linegroup"],[])
-                        [Div ("wasteland-content.xhtml#ln115",[],[])
-                         [Plain [Str "I",Space,Str "think",Space,Str "we",Space,Str "are",Space,Str "in",Space,Str "rats'",Space,Str "alley",Note [Para [Link ("",[],[]) [Str "115."] ("#wasteland-content.xhtml#ln115",""),Space,Str "Cf.",Space,Str "Part",Space,Str "III,",Space,Str "l.",Space,Str "195."]]]
-                         ,Div ("",[],[])
-                          [Plain [Str "Where",Space,Str "the",Space,Str "dead",Space,Str "men",Space,Str "lost",Space,Str "their",Space,Str "bones."]]]]
-                       ,Div ("",["linegroup"],[])
-                        [Div ("",[],[])
-                         [Plain [Str "\"What",Space,Str "is",Space,Str "that",Space,Str "noise?\""]]
-                        ,Div ("wasteland-content.xhtml#ln118",["indent"],[])
-                         [Plain [Str "The",Space,Str "wind",Space,Str "under",Space,Str "the",Space,Str "door.",Note [Para [Link ("",[],[]) [Str "118."] ("#wasteland-content.xhtml#ln118",""),Space,Str "Cf.",Space,Str "Webster:"],BlockQuote [Para [Str "\"Is",Space,Str "the",Space,Str "wind",Space,Str "in",Space,Str "that",Space,Str "door",Space,Str "still?\""]]]]
-                         ,Div ("",[],[])
-                          [Plain [Str "\"What",Space,Str "is",Space,Str "that",Space,Str "noise",Space,Str "now?",Space,Str "What",Space,Str "is",Space,Str "the",Space,Str "wind",Space,Str "doing?\""]]
-                         ,Div ("",["indent"],[])
-                          [Plain [Str "Nothing",Space,Str "again",Space,Str "nothing.",Span ("",["lnum"],[]) [Str "120"]]]]
-                        ,Div ("",["linegroup"],[])
-                         [Div ("",[],[])
-                          [Plain [Str "\"Do"]]
-                         ,Div ("",[],[])
-                          [Plain [Str "\"You",Space,Str "know",Space,Str "nothing?",Space,Str "Do",Space,Str "you",Space,Str "see",Space,Str "nothing?",Space,Str "Do",Space,Str "you",Space,Str "remember"]]
-                         ,Div ("",[],[])
-                          [Plain [Str "\"Nothing?\""]]]
-                        ,Div ("",["linegroup"],[])
-                         [Div ("",[],[])
-                          [Plain [Str "I",Space,Str "remember"]]
-                         ,Div ("",[],[])
-                          [Plain [Str "Those",Space,Str "are",Space,Str "pearls",Space,Str "that",Space,Str "were",Space,Str "his",Space,Str "eyes."]]
-                         ,Div ("wasteland-content.xhtml#ln126",[],[])
-                          [Plain [Str "\"Are",Space,Str "you",Space,Str "alive,",Space,Str "or",Space,Str "not?",Space,Str "Is",Space,Str "there",Space,Str "nothing",Space,Str "in",Space,Str "your",Space,Str "head?\"",Note [Para [Link ("",[],[]) [Str "126."] ("#wasteland-content.xhtml#ln126",""),Space,Str "Cf.",Space,Str "Part",Space,Str "I,",Space,Str "l.",Space,Str "37,",Space,Str "48."]]]
-                          ,Div ("",[],[])
-                           [Plain [Str "But"]]
-                          ,Div ("",[],[])
-                           [Plain [Str "O",Space,Str "O",Space,Str "O",Space,Str "O",Space,Str "that",Space,Str "Shakespeherian",Space,Str "Rag\8213"]]
-                          ,Div ("",[],[])
-                           [Plain [Str "It's",Space,Str "so",Space,Str "elegant"]]
-                          ,Div ("",[],[])
-                           [Plain [Str "So",Space,Str "intelligent",Span ("",["lnum"],[]) [Str "130"]]]
-                          ,Div ("",[],[])
-                           [Plain [Str "\"What",Space,Str "shall",Space,Str "I",Space,Str "do",Space,Str "now?",Space,Str "What",Space,Str "shall",Space,Str "I",Space,Str "do?\""]]
-                          ,Div ("",[],[])
-                           [Plain [Str "I",Space,Str "shall",Space,Str "rush",Space,Str "out",Space,Str "as",Space,Str "I",Space,Str "am,",Space,Str "and",Space,Str "walk",Space,Str "the",Space,Str "street"]]
-                          ,Div ("",[],[])
-                           [Plain [Str "\"With",Space,Str "my",Space,Str "hair",Space,Str "down,",Space,Str "so.",Space,Str "What",Space,Str "shall",Space,Str "we",Space,Str "do",Space,Str "to-morrow?"]]
-                          ,Div ("",[],[])
-                           [Plain [Str "\"What",Space,Str "shall",Space,Str "we",Space,Str "ever",Space,Str "do?\""]]
-                          ,Div ("",[],[])
-                           [Plain [Str "The",Space,Str "hot",Space,Str "water",Space,Str "at",Space,Str "ten."]]
-                          ,Div ("",[],[])
-                           [Plain [Str "And",Space,Str "if",Space,Str "it",Space,Str "rains,",Space,Str "a",Space,Str "closed",Space,Str "car",Space,Str "at",Space,Str "four."]]
-                          ,Div ("",[],[])
-                           [Plain [Str "And",Space,Str "we",Space,Str "shall",Space,Str "play",Space,Str "a",Space,Str "game",Space,Str "of",Space,Str "chess,"]]
-                          ,Div ("wasteland-content.xhtml#ln138",[],[])
-                           [Plain [Str "Pressing",Space,Str "lidless",Space,Str "eyes",Space,Str "and",Space,Str "waiting",Space,Str "for",Space,Str "a",Space,Str "knock",Space,Str "upon",Space,Str "the",Space,Str "door.",Note [Para [Link ("",[],[]) [Str "138."] ("#wasteland-content.xhtml#ln138",""),Space,Str "Cf.",Space,Str "the",Space,Str "game",Space,Str "of",Space,Str "chess",Space,Str "in",Space,Str "Middleton's",Space,Str "Women",Space,Str "beware",Space,Str "Women."]]]
-                           ,Div ("",["linegroup"],[])
-                            [Div ("",[],[])
-                             [Plain [Str "When",Space,Str "Lil's",Space,Str "husband",Space,Str "got",Space,Str "demobbed,",Space,Str "I",Space,Str "said",Space,Str "-"]]
-                            ,Div ("",[],[])
-                             [Plain [Str "I",Space,Str "didn't",Space,Str "mince",Space,Str "my",Space,Str "words,",Space,Str "I",Space,Str "said",Space,Str "to",Space,Str "her",Space,Str "myself,",Span ("",["lnum"],[]) [Str "140"]]]
-                            ,Div ("",[],[])
-                             [Plain [Str "HURRY",Space,Str "UP",Space,Str "PLEASE",Space,Str "ITS",Space,Str "TIME"]]
-                            ,Div ("",[],[])
-                             [Plain [Str "Now",Space,Str "Albert's",Space,Str "coming",Space,Str "back,",Space,Str "make",Space,Str "yourself",Space,Str "a",Space,Str "bit",Space,Str "smart."]]
-                            ,Div ("",[],[])
-                             [Plain [Str "He'll",Space,Str "want",Space,Str "to",Space,Str "know",Space,Str "what",Space,Str "you",Space,Str "done",Space,Str "with",Space,Str "that",Space,Str "money",Space,Str "he",Space,Str "gave",SoftBreak,Str "you"]]
-                            ,Div ("",[],[])
-                             [Plain [Str "To",Space,Str "get",Space,Str "yourself",Space,Str "some",Space,Str "teeth.",Space,Str "He",Space,Str "did,",Space,Str "I",Space,Str "was",Space,Str "there."]]
-                            ,Div ("",[],[])
-                             [Plain [Str "You",Space,Str "have",Space,Str "them",Space,Str "all",Space,Str "out,",Space,Str "Lil,",Space,Str "and",Space,Str "get",Space,Str "a",Space,Str "nice",Space,Str "set,"]]
-                            ,Div ("",[],[])
-                             [Plain [Str "He",Space,Str "said,",Space,Str "I",Space,Str "swear,",Space,Str "I",Space,Str "can't",Space,Str "bear",Space,Str "to",Space,Str "look",Space,Str "at",Space,Str "you."]]
-                            ,Div ("",[],[])
-                             [Plain [Str "And",Space,Str "no",Space,Str "more",Space,Str "can't",Space,Str "I,",Space,Str "I",Space,Str "said,",Space,Str "and",Space,Str "think",Space,Str "of",Space,Str "poor",Space,Str "Albert,"]]
-                            ,Div ("",[],[])
-                             [Plain [Str "He's",Space,Str "been",Space,Str "in",Space,Str "the",Space,Str "army",Space,Str "four",Space,Str "years,",Space,Str "he",Space,Str "wants",Space,Str "a",Space,Str "good",Space,Str "time,"]]
-                            ,Div ("",[],[])
-                             [Plain [Str "And",Space,Str "if",Space,Str "you",Space,Str "don't",Space,Str "give",Space,Str "it",Space,Str "him,",Space,Str "there's",Space,Str "others",Space,Str "will,",Space,Str "I",SoftBreak,Str "said."]]
-                            ,Div ("",[],[])
-                             [Plain [Str "Oh",Space,Str "is",Space,Str "there,",Space,Str "she",Space,Str "said.",Space,Str "Something",Space,Str "o'",Space,Str "that,",Space,Str "I",Space,Str "said.",Span ("",["lnum"],[]) [Str "150"]]]
-                            ,Div ("",[],[])
-                             [Plain [Str "Then",Space,Str "I'll",Space,Str "know",Space,Str "who",Space,Str "to",Space,Str "thank,",Space,Str "she",Space,Str "said,",Space,Str "and",Space,Str "give",Space,Str "me",Space,Str "a",Space,Str "straight",SoftBreak,Str "look."]]
-                            ,Div ("",[],[])
-                             [Plain [Str "HURRY",Space,Str "UP",Space,Str "PLEASE",Space,Str "ITS",Space,Str "TIME"]]
-                            ,Div ("",[],[])
-                             [Plain [Str "If",Space,Str "you",Space,Str "don't",Space,Str "like",Space,Str "it",Space,Str "you",Space,Str "can",Space,Str "get",Space,Str "on",Space,Str "with",Space,Str "it,",Space,Str "I",Space,Str "said."]]
-                            ,Div ("",[],[])
-                             [Plain [Str "Others",Space,Str "can",Space,Str "pick",Space,Str "and",Space,Str "choose",Space,Str "if",Space,Str "you",Space,Str "can't."]]
-                            ,Div ("",[],[])
-                             [Plain [Str "But",Space,Str "if",Space,Str "Albert",Space,Str "makes",Space,Str "off,",Space,Str "it",Space,Str "won't",Space,Str "be",Space,Str "for",Space,Str "lack",Space,Str "of",SoftBreak,Str "telling."]]
-                            ,Div ("",[],[])
-                             [Plain [Str "You",Space,Str "ought",Space,Str "to",Space,Str "be",Space,Str "ashamed,",Space,Str "I",Space,Str "said,",Space,Str "to",Space,Str "look",Space,Str "so",Space,Str "antique."]]
-                            ,Div ("",[],[])
-                             [Plain [Str "(And",Space,Str "her",Space,Str "only",Space,Str "thirty-one.)"]]
-                            ,Div ("",[],[])
-                             [Plain [Str "I",Space,Str "can't",Space,Str "help",Space,Str "it,",Space,Str "she",Space,Str "said,",Space,Str "pulling",Space,Str "a",Space,Str "long",Space,Str "face,"]]
-                            ,Div ("",[],[])
-                             [Plain [Str "It's",Space,Str "them",Space,Str "pills",Space,Str "I",Space,Str "took,",Space,Str "to",Space,Str "bring",Space,Str "it",Space,Str "off,",Space,Str "she",Space,Str "said."]]
-                            ,Div ("",[],[])
-                             [Plain [Str "(She's",Space,Str "had",Space,Str "five",Space,Str "already,",Space,Str "and",Space,Str "nearly",Space,Str "died",Space,Str "of",Space,Str "young",Space,Str "George.)",Span ("",["lnum"],[]) [Str "160"]]]
-                            ,Div ("",[],[])
-                             [Plain [Str "The",Space,Str "chemist",Space,Str "said",Space,Str "it",Space,Str "would",Space,Str "be",Space,Str "all",Space,Str "right,",Space,Str "but",Space,Str "I've",Space,Str "never",Space,Str "been",Space,Str "the",SoftBreak,Str "same."]]
-                            ,Div ("",[],[])
-                             [Plain [Str "You",Space,Emph [Str "are"],Space,Str "a",Space,Str "proper",Space,Str "fool,",Space,Str "I",Space,Str "said."]]
-                            ,Div ("",[],[])
-                             [Plain [Str "Well,",Space,Str "if",Space,Str "Albert",Space,Str "won't",Space,Str "leave",Space,Str "you",Space,Str "alone,",Space,Str "there",Space,Str "it",Space,Str "is,",Space,Str "I",SoftBreak,Str "said,"]]
-                            ,Div ("",[],[])
-                             [Plain [Str "What",Space,Str "you",Space,Str "get",Space,Str "married",Space,Str "for",Space,Str "if",Space,Str "you",Space,Str "don't",Space,Str "want",Space,Str "children?"]]
-                            ,Div ("",[],[])
-                             [Plain [Str "HURRY",Space,Str "UP",Space,Str "PLEASE",Space,Str "ITS",Space,Str "TIME"]]
-                            ,Div ("",[],[])
-                             [Plain [Str "Well,",Space,Str "that",Space,Str "Sunday",Space,Str "Albert",Space,Str "was",Space,Str "home,",Space,Str "they",Space,Str "had",Space,Str "a",Space,Str "hot",SoftBreak,Str "gammon,"]]
-                            ,Div ("",[],[])
-                             [Plain [Str "And",Space,Str "they",Space,Str "asked",Space,Str "me",Space,Str "in",Space,Str "to",Space,Str "dinner,",Space,Str "to",Space,Str "get",Space,Str "the",Space,Str "beauty",Space,Str "of",Space,Str "it",SoftBreak,Str "hot\8213"]]
-                            ,Div ("",[],[])
-                             [Plain [Str "HURRY",Space,Str "UP",Space,Str "PLEASE",Space,Str "ITS",Space,Str "TIME"]]
-                            ,Div ("",[],[])
-                             [Plain [Str "HURRY",Space,Str "UP",Space,Str "PLEASE",Space,Str "ITS",Space,Str "TIME"]]
-                            ,Div ("",[],[])
-                             [Plain [Str "Goonight",Space,Str "Bill.",Space,Str "Goonight",Space,Str "Lou.",Space,Str "Goonight",Space,Str "May.",Space,Str "Goonight.",Span ("",["lnum"],[]) [Str "170"]]]
-                            ,Div ("",[],[])
-                             [Plain [Str "Ta",Space,Str "ta.",Space,Str "Goonight.",Space,Str "Goonight."]]
-                            ,Div ("",[],[])
-                             [Plain [Str "Good",Space,Str "night,",Space,Str "ladies,",Space,Str "good",Space,Str "night,",Space,Str "sweet",Space,Str "ladies,",Space,Str "good",Space,Str "night,",Space,Str "good",SoftBreak,Str "night."]]]
-                           ,RawBlock (Format "html") "</section>"
-                           ,Div ("wasteland-content.xhtml#ch3",["section"],[])
-                            [Header 2 ("",[],[]) [Str "III.",Space,Str "THE",Space,Str "FIRE",Space,Str "SERMON"]
-                            ,Div ("",["linegroup"],[])
-                             [Div ("",[],[])
-                              [Plain [Str "The",Space,Str "river's",Space,Str "tent",Space,Str "is",Space,Str "broken:",Space,Str "the",Space,Str "last",Space,Str "fingers",Space,Str "of",Space,Str "leaf"]]
-                             ,Div ("",[],[])
-                              [Plain [Str "Clutch",Space,Str "and",Space,Str "sink",Space,Str "into",Space,Str "the",Space,Str "wet",Space,Str "bank.",Space,Str "The",Space,Str "wind"]]
-                             ,Div ("",[],[])
-                              [Plain [Str "Crosses",Space,Str "the",Space,Str "brown",Space,Str "land,",Space,Str "unheard.",Space,Str "The",Space,Str "nymphs",Space,Str "are",SoftBreak,Str "departed."]]
-                             ,Div ("wasteland-content.xhtml#ln176",[],[])
-                              [Plain [Str "Sweet",Space,Str "Thames,",Space,Str "run",Space,Str "softly,",Space,Str "till",Space,Str "I",Space,Str "end",Space,Str "my",Space,Str "song.",Note [Para [Link ("",[],[]) [Str "176."] ("#wasteland-content.xhtml#ln176",""),Space,Str "V.",Space,Str "Spenser,",Space,Str "Prothalamion."]]]
-                              ,Div ("",[],[])
-                               [Plain [Str "The",Space,Str "river",Space,Str "bears",Space,Str "no",Space,Str "empty",Space,Str "bottles,",Space,Str "sandwich",Space,Str "papers,"]]
-                              ,Div ("",[],[])
-                               [Plain [Str "Silk",Space,Str "handkerchiefs,",Space,Str "cardboard",Space,Str "boxes,",Space,Str "cigarette",Space,Str "ends"]]
-                              ,Div ("",[],[])
-                               [Plain [Str "Or",Space,Str "other",Space,Str "testimony",Space,Str "of",Space,Str "summer",Space,Str "nights.",Space,Str "The",Space,Str "nymphs",Space,Str "are",SoftBreak,Str "departed."]]
-                              ,Div ("",[],[])
-                               [Plain [Str "And",Space,Str "their",Space,Str "friends,",Space,Str "the",Space,Str "loitering",Space,Str "heirs",Space,Str "of",Space,Str "city",Space,Str "directors;",Span ("",["lnum"],[]) [Str "180"]]]
-                              ,Div ("",[],[])
-                               [Plain [Str "Departed,",Space,Str "have",Space,Str "left",Space,Str "no",Space,Str "addresses."]]
-                              ,Div ("",[],[])
-                               [Plain [Str "By",Space,Str "the",Space,Str "waters",Space,Str "of",Space,Str "Leman",Space,Str "I",Space,Str "sat",Space,Str "down",Space,Str "and",Space,Str "wept",Space,Str ".",Space,Str ".",Space,Str "."]]
-                              ,Div ("",[],[])
-                               [Plain [Str "Sweet",Space,Str "Thames,",Space,Str "run",Space,Str "softly",Space,Str "till",Space,Str "I",Space,Str "end",Space,Str "my",Space,Str "song,"]]
-                              ,Div ("",[],[])
-                               [Plain [Str "Sweet",Space,Str "Thames,",Space,Str "run",Space,Str "softly,",Space,Str "for",Space,Str "I",Space,Str "speak",Space,Str "not",Space,Str "loud",Space,Str "or",Space,Str "long."]]
-                              ,Div ("",[],[])
-                               [Plain [Str "But",Space,Str "at",Space,Str "my",Space,Str "back",Space,Str "in",Space,Str "a",Space,Str "cold",Space,Str "blast",Space,Str "I",Space,Str "hear"]]
-                              ,Div ("",[],[])
-                               [Plain [Str "The",Space,Str "rattle",Space,Str "of",Space,Str "the",Space,Str "bones,",Space,Str "and",Space,Str "chuckle",Space,Str "spread",Space,Str "from",Space,Str "ear",Space,Str "to",SoftBreak,Str "ear."]]]
-                             ,Div ("",["linegroup"],[])
-                              [Div ("",[],[])
-                               [Plain [Str "A",Space,Str "rat",Space,Str "crept",Space,Str "softly",Space,Str "through",Space,Str "the",Space,Str "vegetation"]]
-                              ,Div ("",[],[])
-                               [Plain [Str "Dragging",Space,Str "its",Space,Str "slimy",Space,Str "belly",Space,Str "on",Space,Str "the",Space,Str "bank"]]
-                              ,Div ("",[],[])
-                               [Plain [Str "While",Space,Str "I",Space,Str "was",Space,Str "fishing",Space,Str "in",Space,Str "the",Space,Str "dull",Space,Str "canal"]]
-                              ,Div ("",[],[])
-                               [Plain [Str "On",Space,Str "a",Space,Str "winter",Space,Str "evening",Space,Str "round",Space,Str "behind",Space,Str "the",Space,Str "gashouse",Span ("",["lnum"],[]) [Str "190"]]]
-                              ,Div ("",[],[])
-                               [Plain [Str "Musing",Space,Str "upon",Space,Str "the",Space,Str "king",Space,Str "my",Space,Str "brother's",Space,Str "wreck"]]
-                              ,Div ("wasteland-content.xhtml#ln192",[],[])
-                               [Plain [Str "And",Space,Str "on",Space,Str "the",Space,Str "king",Space,Str "my",Space,Str "father's",Space,Str "death",Space,Str "before",Space,Str "him.",Note [Para [Link ("",[],[]) [Str "192."] ("#wasteland-content.xhtml#ln192",""),Space,Str "Cf.",Space,Str "The",Space,Str "Tempest,",Space,Str "I.",Space,Str "ii."]]]
-                               ,Div ("",[],[])
-                                [Plain [Str "White",Space,Str "bodies",Space,Str "naked",Space,Str "on",Space,Str "the",Space,Str "low",Space,Str "damp",Space,Str "ground"]]
-                               ,Div ("",[],[])
-                                [Plain [Str "And",Space,Str "bones",Space,Str "cast",Space,Str "in",Space,Str "a",Space,Str "little",Space,Str "low",Space,Str "dry",Space,Str "garret,"]]
-                               ,Div ("",[],[])
-                                [Plain [Str "Rattled",Space,Str "by",Space,Str "the",Space,Str "rat's",Space,Str "foot",Space,Str "only,",Space,Str "year",Space,Str "to",Space,Str "year."]]
-                               ,Div ("wasteland-content.xhtml#ln196",[],[])
-                                [Plain [Str "But",Space,Str "at",Space,Str "my",Space,Str "back",Space,Str "from",Space,Str "time",Space,Str "to",Space,Str "time",Space,Str "I",Space,Str "hear",Note [Para [Link ("",[],[]) [Str "196."] ("#wasteland-content.xhtml#ln196",""),Space,Str "Cf.",Space,Str "Marvell,",Space,Str "To",Space,Str "His",Space,Str "Coy",Space,Str "Mistress."]]]
-                                ,Div ("wasteland-content.xhtml#ln197",[],[])
-                                 [Plain [Str "The",Space,Str "sound",Space,Str "of",Space,Str "horns",Space,Str "and",Space,Str "motors,",Space,Str "which",Space,Str "shall",Space,Str "bring",Note [Para [Link ("",[],[]) [Str "197."] ("#wasteland-content.xhtml#ln197",""),Space,Str "Cf.",Space,Str "Day,",Space,Str "Parliament",Space,Str "of",Space,Str "Bees:"],BlockQuote [Div ("",[],[]) [Div ("",[],[]) [Plain [Str "\"When",Space,Str "of",Space,Str "the",Space,Str "sudden,",Space,Str "listening,",Space,Str "you",Space,Str "shall",SoftBreak,Str "hear,"]],Div ("",[],[]) [Plain [Str "\"A",Space,Str "noise",Space,Str "of",Space,Str "horns",Space,Str "and",Space,Str "hunting,",Space,Str "which",Space,Str "shall",SoftBreak,Str "bring"]],Div ("",[],[]) [Plain [Str "\"Actaeon",Space,Str "to",Space,Str "Diana",Space,Str "in",Space,Str "the",Space,Str "spring,"]],Div ("",[],[]) [Plain [Str "\"Where",Space,Str "all",Space,Str "shall",Space,Str "see",Space,Str "her",Space,Str "naked",Space,Str "skin",Space,Str ".",Space,Str ".",Space,Str ".\""]]]]]]
-                                 ,Div ("",[],[])
-                                  [Plain [Str "Sweeney",Space,Str "to",Space,Str "Mrs.",Space,Str "Porter",Space,Str "in",Space,Str "the",Space,Str "spring."]]
-                                 ,Div ("wasteland-content.xhtml#ln199",[],[])
-                                  [Plain [Str "O",Space,Str "the",Space,Str "moon",Space,Str "shone",Space,Str "bright",Space,Str "on",Space,Str "Mrs.",Space,Str "Porter",Note [Para [Link ("",[],[]) [Str "199."] ("#wasteland-content.xhtml#ln199",""),Space,Str "I",Space,Str "do",Space,Str "not",Space,Str "know",Space,Str "the",Space,Str "origin",Space,Str "of",Space,Str "the",Space,Str "ballad",Space,Str "from",Space,Str "which",Space,Str "these",Space,Str "lines",Space,Str "are",SoftBreak,Str "taken:",Space,Str "it",Space,Str "was",Space,Str "reported",Space,Str "to",Space,Str "me",Space,Str "from",Space,Str "Sydney,",Space,Str "Australia."]]]
-                                  ,Div ("",[],[])
-                                   [Plain [Str "And",Space,Str "on",Space,Str "her",Space,Str "daughter",Span ("",["lnum"],[]) [Str "200"]]]
-                                  ,Div ("",[],[])
-                                   [Plain [Str "They",Space,Str "wash",Space,Str "their",Space,Str "feet",Space,Str "in",Space,Str "soda",Space,Str "water"]]
-                                  ,Div ("wasteland-content.xhtml#ln202",[],[("lang","fr")])
-                                   [Plain [Emph [Str "Et",Space,Str "O",Space,Str "ces",Space,Str "voix",Space,Str "d'enfants,",Space,Str "chantant",Space,Str "dans",Space,Str "la",Space,Str "coupole"],Str "!",Note [Para [Link ("",[],[]) [Str "202."] ("#wasteland-content.xhtml#ln202",""),Space,Str "V.",Space,Str "Verlaine,",Space,Str "Parsifal."]]]
-                                   ,Div ("",["linegroup"],[])
-                                    [Div ("",[],[])
-                                     [Plain [Str "Twit",Space,Str "twit",Space,Str "twit"]]
-                                    ,Div ("",[],[])
-                                     [Plain [Str "Jug",Space,Str "jug",Space,Str "jug",Space,Str "jug",Space,Str "jug",Space,Str "jug"]]
-                                    ,Div ("",[],[])
-                                     [Plain [Str "So",Space,Str "rudely",Space,Str "forc'd."]]
-                                    ,Div ("",[],[])
-                                     [Plain [Str "Tereu"]]]
-                                   ,Div ("",["linegroup"],[])
-                                    [Div ("",[],[])
-                                     [Plain [Str "Unreal",Space,Str "City"]]
-                                    ,Div ("",[],[])
-                                     [Plain [Str "Under",Space,Str "the",Space,Str "brown",Space,Str "fog",Space,Str "of",Space,Str "a",Space,Str "winter",Space,Str "noon"]]
-                                    ,Div ("",[],[])
-                                     [Plain [Str "Mr.",Space,Str "Eugenides,",Space,Str "the",Space,Str "Smyrna",Space,Str "merchant"]]
-                                    ,Div ("wasteland-content.xhtml#ln210",[],[])
-                                     [Plain [Str "Unshaven,",Space,Str "with",Space,Str "a",Space,Str "pocket",Space,Str "full",Space,Str "of",Space,Str "currants",Note [Para [Link ("",[],[]) [Str "210."] ("#wasteland-content.xhtml#ln210",""),Space,Str "The",Space,Str "currants",Space,Str "were",Space,Str "quoted",Space,Str "at",Space,Str "a",Space,Str "price",Space,Str "\"cost",Space,Str "insurance",Space,Str "and",Space,Str "freight",Space,Str "to",SoftBreak,Str "London\";",Space,Str "and",Space,Str "the",Space,Str "Bill",Space,Str "of",Space,Str "Lading",Space,Str "etc.",Space,Str "were",Space,Str "to",Space,Str "be",Space,Str "handed",Space,Str "to",Space,Str "the",Space,Str "buyer",Space,Str "upon",SoftBreak,Str "payment",Space,Str "of",Space,Str "the",Space,Str "sight",Space,Str "draft."]]]
-                                     ,Div ("",[],[])
-                                      [Plain [Str "C.i.f.",Space,Str "London:",Space,Str "documents",Space,Str "at",Space,Str "sight,"]]
-                                     ,Div ("",[],[])
-                                      [Plain [Str "Asked",Space,Str "me",Space,Str "in",Space,Str "demotic",Space,Str "French"]]
-                                     ,Div ("",[],[])
-                                      [Plain [Str "To",Space,Str "luncheon",Space,Str "at",Space,Str "the",Space,Str "Cannon",Space,Str "Street",Space,Str "Hotel"]]
-                                     ,Div ("",[],[])
-                                      [Plain [Str "Followed",Space,Str "by",Space,Str "a",Space,Str "weekend",Space,Str "at",Space,Str "the",Space,Str "Metropole."]]]
-                                    ,Div ("",["linegroup"],[])
-                                     [Div ("",[],[])
-                                      [Plain [Str "At",Space,Str "the",Space,Str "violet",Space,Str "hour,",Space,Str "when",Space,Str "the",Space,Str "eyes",Space,Str "and",Space,Str "back"]]
-                                     ,Div ("",[],[])
-                                      [Plain [Str "Turn",Space,Str "upward",Space,Str "from",Space,Str "the",Space,Str "desk,",Space,Str "when",Space,Str "the",Space,Str "human",Space,Str "engine",Space,Str "waits"]]
-                                     ,Div ("",[],[])
-                                      [Plain [Str "Like",Space,Str "a",Space,Str "taxi",Space,Str "throbbing",Space,Str "waiting,"]]
-                                     ,Div ("wasteland-content.xhtml#ln218",[],[])
-                                      [Plain [Str "I",Space,Str "Tiresias,",Space,Str "though",Space,Str "blind,",Space,Str "throbbing",Space,Str "between",Space,Str "two",Space,Str "lives,",Note [Para [Link ("",[],[]) [Str "218."] ("#wasteland-content.xhtml#ln218",""),Space,Str "Tiresias,",Space,Str "although",Space,Str "a",Space,Str "mere",Space,Str "spectator",Space,Str "and",Space,Str "not",Space,Str "indeed",Space,Str "a",Space,Str "\"character,\"",Space,Str "is",SoftBreak,Str "yet",Space,Str "the",Space,Str "most",Space,Str "important",Space,Str "personage",Space,Str "in",Space,Str "the",Space,Str "poem,",Space,Str "uniting",Space,Str "all",Space,Str "the",Space,Str "rest.",Space,Str "Just",SoftBreak,Str "as",Space,Str "the",Space,Str "one-eyed",Space,Str "merchant,",Space,Str "seller",Space,Str "of",Space,Str "currants,",Space,Str "melts",Space,Str "into",Space,Str "the",Space,Str "Phoenician",SoftBreak,Str "Sailor,",Space,Str "and",Space,Str "the",Space,Str "latter",Space,Str "is",Space,Str "not",Space,Str "wholly",Space,Str "distinct",Space,Str "from",Space,Str "Ferdinand",Space,Str "Prince",Space,Str "of",SoftBreak,Str "Naples,",Space,Str "so",Space,Str "all",Space,Str "the",Space,Str "women",Space,Str "are",Space,Str "one",Space,Str "woman,",Space,Str "and",Space,Str "the",Space,Str "two",Space,Str "sexes",Space,Str "meet",Space,Str "in",SoftBreak,Str "Tiresias.",Space,Str "What",Space,Str "Tiresias",Space,Str "sees,",Space,Str "in",Space,Str "fact,",Space,Str "is",Space,Str "the",Space,Str "substance",Space,Str "of",Space,Str "the",Space,Str "poem.",Space,Str "The",SoftBreak,Str "whole",Space,Str "passage",Space,Str "from",Space,Str "Ovid",Space,Str "is",Space,Str "of",Space,Str "great",Space,Str "anthropological",Space,Str "interest:"],BlockQuote [Para [Str "'.",Space,Str ".",Space,Str ".",Space,Str "Cum",Space,Str "Iunone",Space,Str "iocos",Space,Str "et",Space,Str "maior",Space,Str "vestra",Space,Str "profecto",Space,Str "est",LineBreak,Str "Quam,",Space,Str "quae",SoftBreak,Str "contingit",Space,Str "maribus,'",Space,Str "dixisse,",Space,Str "'voluptas.'",LineBreak,Str "Illa",Space,Str "negat;",Space,Str "placuit",SoftBreak,Str "quae",Space,Str "sit",Space,Str "sententia",Space,Str "docti",LineBreak,Str "Quaerere",Space,Str "Tiresiae:",Space,Str "venus",Space,Str "huic",Space,Str "erat",SoftBreak,Str "utraque",Space,Str "nota.",LineBreak,Str "Nam",Space,Str "duo",Space,Str "magnorum",Space,Str "viridi",Space,Str "coeuntia",Space,Str "silva",LineBreak,Str "Corpora",Space,Str "serpentum",Space,Str "baculi",Space,Str "violaverat",Space,Str "ictu",LineBreak,Str "Deque",Space,Str "viro",Space,Str "factus,",SoftBreak,Str "mirabile,",Space,Str "femina",Space,Str "septem",LineBreak,Str "Egerat",Space,Str "autumnos;",Space,Str "octavo",Space,Str "rursus",SoftBreak,Str "eosdem",LineBreak,Str "Vidit",Space,Str "et",Space,Str "'est",Space,Str "vestrae",Space,Str "si",Space,Str "tanta",Space,Str "potentia",Space,Str "plagae,'",LineBreak,Str "Dixit",Space,Str "'ut",Space,Str "auctoris",Space,Str "sortem",Space,Str "in",Space,Str "contraria",Space,Str "mutet,",LineBreak,Str "Nunc",Space,Str "quoque",Space,Str "vos",SoftBreak,Str "feriam!'",Space,Str "percussis",Space,Str "anguibus",Space,Str "isdem",LineBreak,Str "Forma",Space,Str "prior",Space,Str "rediit",SoftBreak,Str "genetivaque",Space,Str "venit",Space,Str "imago.",LineBreak,Str "Arbiter",Space,Str "hic",Space,Str "igitur",Space,Str "sumptus",Space,Str "de",Space,Str "lite",SoftBreak,Str "iocosa",LineBreak,Str "Dicta",Space,Str "Iovis",Space,Str "firmat;",Space,Str "gravius",Space,Str "Saturnia",Space,Str "iusto",LineBreak,Str "Nec",SoftBreak,Str "pro",Space,Str "materia",Space,Str "fertur",Space,Str "doluisse",Space,Str "suique",LineBreak,Str "Iudicis",Space,Str "aeterna",Space,Str "damnavit",SoftBreak,Str "lumina",Space,Str "nocte,",LineBreak,Str "At",Space,Str "pater",Space,Str "omnipotens",Space,Str "(neque",Space,Str "enim",Space,Str "licet",Space,Str "inrita",SoftBreak,Str "cuiquam",LineBreak,Str "Facta",Space,Str "dei",Space,Str "fecisse",Space,Str "deo)",Space,Str "pro",Space,Str "lumine",Space,Str "adempto",LineBreak,Str "Scire",SoftBreak,Str "futura",Space,Str "dedit",Space,Str "poenamque",Space,Str "levavit",Space,Str "honore.",LineBreak]]]]
-                                      ,Div ("",[],[])
-                                       [Plain [Str "Old",Space,Str "man",Space,Str "with",Space,Str "wrinkled",Space,Str "female",Space,Str "breasts,",Space,Str "can",Space,Str "see"]]
-                                      ,Div ("",[],[])
-                                       [Plain [Str "At",Space,Str "the",Space,Str "violet",Space,Str "hour,",Space,Str "the",Space,Str "evening",Space,Str "hour",Space,Str "that",Space,Str "strives",Span ("",["lnum"],[]) [Str "220"]]]
-                                      ,Div ("wasteland-content.xhtml#ln221",[],[])
-                                       [Plain [Str "Homeward,",Space,Str "and",Space,Str "brings",Space,Str "the",Space,Str "sailor",Space,Str "home",Space,Str "from",Space,Str "sea,",Note [Para [Link ("",[],[]) [Str "221."] ("#wasteland-content.xhtml#ln221",""),Space,Str "This",Space,Str "may",Space,Str "not",Space,Str "appear",Space,Str "as",Space,Str "exact",Space,Str "as",Space,Str "Sappho's",Space,Str "lines,",Space,Str "but",Space,Str "I",Space,Str "had",Space,Str "in",Space,Str "mind",SoftBreak,Str "the",Space,Str "\"longshore\"",Space,Str "or",Space,Str "\"dory\"",Space,Str "fisherman,",Space,Str "who",Space,Str "returns",Space,Str "at",Space,Str "nightfall."]]]
-                                       ,Div ("",[],[])
-                                        [Plain [Str "The",Space,Str "typist",Space,Str "home",Space,Str "at",Space,Str "teatime,",Space,Str "clears",Space,Str "her",Space,Str "breakfast,",Space,Str "lights"]]
-                                       ,Div ("",[],[])
-                                        [Plain [Str "Her",Space,Str "stove,",Space,Str "and",Space,Str "lays",Space,Str "out",Space,Str "food",Space,Str "in",Space,Str "tins."]]
-                                       ,Div ("",[],[])
-                                        [Plain [Str "Out",Space,Str "of",Space,Str "the",Space,Str "window",Space,Str "perilously",Space,Str "spread"]]
-                                       ,Div ("",[],[])
-                                        [Plain [Str "Her",Space,Str "drying",Space,Str "combinations",Space,Str "touched",Space,Str "by",Space,Str "the",Space,Str "sun's",Space,Str "last",Space,Str "rays,"]]
-                                       ,Div ("",[],[])
-                                        [Plain [Str "On",Space,Str "the",Space,Str "divan",Space,Str "are",Space,Str "piled",Space,Str "(at",Space,Str "night",Space,Str "her",Space,Str "bed)"]]
-                                       ,Div ("",[],[])
-                                        [Plain [Str "Stockings,",Space,Str "slippers,",Space,Str "camisoles,",Space,Str "and",Space,Str "stays."]]
-                                       ,Div ("",[],[])
-                                        [Plain [Str "I",Space,Str "Tiresias,",Space,Str "old",Space,Str "man",Space,Str "with",Space,Str "wrinkled",Space,Str "dugs"]]
-                                       ,Div ("",[],[])
-                                        [Plain [Str "Perceived",Space,Str "the",Space,Str "scene,",Space,Str "and",Space,Str "foretold",Space,Str "the",Space,Str "rest",Space,Str "-"]]
-                                       ,Div ("",[],[])
-                                        [Plain [Str "I",Space,Str "too",Space,Str "awaited",Space,Str "the",Space,Str "expected",Space,Str "guest.",Span ("",["lnum"],[]) [Str "230"]]]
-                                       ,Div ("",[],[])
-                                        [Plain [Str "He,",Space,Str "the",Space,Str "young",Space,Str "man",Space,Str "carbuncular,",Space,Str "arrives,"]]
-                                       ,Div ("",[],[])
-                                        [Plain [Str "A",Space,Str "small",Space,Str "house",Space,Str "agent's",Space,Str "clerk,",Space,Str "with",Space,Str "one",Space,Str "bold",Space,Str "stare,"]]
-                                       ,Div ("",[],[])
-                                        [Plain [Str "One",Space,Str "of",Space,Str "the",Space,Str "low",Space,Str "on",Space,Str "whom",Space,Str "assurance",Space,Str "sits"]]
-                                       ,Div ("",[],[])
-                                        [Plain [Str "As",Space,Str "a",Space,Str "silk",Space,Str "hat",Space,Str "on",Space,Str "a",Space,Str "Bradford",Space,Str "millionaire."]]
-                                       ,Div ("",[],[])
-                                        [Plain [Str "The",Space,Str "time",Space,Str "is",Space,Str "now",Space,Str "propitious,",Space,Str "as",Space,Str "he",Space,Str "guesses,"]]
-                                       ,Div ("",[],[])
-                                        [Plain [Str "The",Space,Str "meal",Space,Str "is",Space,Str "ended,",Space,Str "she",Space,Str "is",Space,Str "bored",Space,Str "and",Space,Str "tired,"]]
-                                       ,Div ("",[],[])
-                                        [Plain [Str "Endeavours",Space,Str "to",Space,Str "engage",Space,Str "her",Space,Str "in",Space,Str "caresses"]]
-                                       ,Div ("",[],[])
-                                        [Plain [Str "Which",Space,Str "still",Space,Str "are",Space,Str "unreproved,",Space,Str "if",Space,Str "undesired."]]
-                                       ,Div ("",[],[])
-                                        [Plain [Str "Flushed",Space,Str "and",Space,Str "decided,",Space,Str "he",Space,Str "assaults",Space,Str "at",Space,Str "once;"]]
-                                       ,Div ("",[],[])
-                                        [Plain [Str "Exploring",Space,Str "hands",Space,Str "encounter",Space,Str "no",Space,Str "defence;",Span ("",["lnum"],[]) [Str "240"]]]
-                                       ,Div ("",[],[])
-                                        [Plain [Str "His",Space,Str "vanity",Space,Str "requires",Space,Str "no",Space,Str "response,"]]
-                                       ,Div ("",[],[])
-                                        [Plain [Str "And",Space,Str "makes",Space,Str "a",Space,Str "welcome",Space,Str "of",Space,Str "indifference."]]
-                                       ,Div ("",[],[])
-                                        [Plain [Str "(And",Space,Str "I",Space,Str "Tiresias",Space,Str "have",Space,Str "foresuffered",Space,Str "all"]]
-                                       ,Div ("",[],[])
-                                        [Plain [Str "Enacted",Space,Str "on",Space,Str "this",Space,Str "same",Space,Str "divan",Space,Str "or",Space,Str "bed;"]]
-                                       ,Div ("",[],[])
-                                        [Plain [Str "I",Space,Str "who",Space,Str "have",Space,Str "sat",Space,Str "by",Space,Str "Thebes",Space,Str "below",Space,Str "the",Space,Str "wall"]]
-                                       ,Div ("",[],[])
-                                        [Plain [Str "And",Space,Str "walked",Space,Str "among",Space,Str "the",Space,Str "lowest",Space,Str "of",Space,Str "the",Space,Str "dead.)"]]
-                                       ,Div ("",[],[])
-                                        [Plain [Str "Bestows",Space,Str "one",Space,Str "final",Space,Str "patronising",Space,Str "kiss,"]]
-                                       ,Div ("",[],[])
-                                        [Plain [Str "And",Space,Str "gropes",Space,Str "his",Space,Str "way,",Space,Str "finding",Space,Str "the",Space,Str "stairs",Space,Str "unlit",Space,Str ".",Space,Str ".",Space,Str "."]]]
-                                      ,Div ("",["linegroup"],[])
-                                       [Div ("",[],[])
-                                        [Plain [Str "She",Space,Str "turns",Space,Str "and",Space,Str "looks",Space,Str "a",Space,Str "moment",Space,Str "in",Space,Str "the",Space,Str "glass,"]]
-                                       ,Div ("",[],[])
-                                        [Plain [Str "Hardly",Space,Str "aware",Space,Str "of",Space,Str "her",Space,Str "departed",Space,Str "lover;",Span ("",["lnum"],[]) [Str "250"]]]
-                                       ,Div ("",[],[])
-                                        [Plain [Str "Her",Space,Str "brain",Space,Str "allows",Space,Str "one",Space,Str "half-formed",Space,Str "thought",Space,Str "to",Space,Str "pass:"]]
-                                       ,Div ("",[],[])
-                                        [Plain [Str "\"Well",Space,Str "now",Space,Str "that's",Space,Str "done:",Space,Str "and",Space,Str "I'm",Space,Str "glad",Space,Str "it's",Space,Str "over.\""]]
-                                       ,Div ("wasteland-content.xhtml#ln253",[],[])
-                                        [Plain [Str "When",Space,Str "lovely",Space,Str "woman",Space,Str "stoops",Space,Str "to",Space,Str "folly",Space,Str "and",Note [Para [Link ("",[],[]) [Str "253."] ("#wasteland-content.xhtml#ln253",""),Space,Str "V.",Space,Str "Goldsmith,",Space,Str "the",Space,Str "song",Space,Str "in",Space,Str "The",Space,Str "Vicar",Space,Str "of",Space,Str "Wakefield."]]]
-                                        ,Div ("",[],[])
-                                         [Plain [Str "Paces",Space,Str "about",Space,Str "her",Space,Str "room",Space,Str "again,",Space,Str "alone,"]]
-                                        ,Div ("",[],[])
-                                         [Plain [Str "She",Space,Str "smoothes",Space,Str "her",Space,Str "hair",Space,Str "with",Space,Str "automatic",Space,Str "hand,"]]
-                                        ,Div ("",[],[])
-                                         [Plain [Str "And",Space,Str "puts",Space,Str "a",Space,Str "record",Space,Str "on",Space,Str "the",Space,Str "gramophone."]]]
-                                       ,Div ("",["linegroup"],[])
-                                        [Div ("wasteland-content.xhtml#ln257",[],[])
-                                         [Plain [Str "\"This",Space,Str "music",Space,Str "crept",Space,Str "by",Space,Str "me",Space,Str "upon",Space,Str "the",Space,Str "waters\"",Note [Para [Link ("",[],[]) [Str "257."] ("#wasteland-content.xhtml#ln257",""),Space,Str "V.",Space,Str "The",Space,Str "Tempest,",Space,Str "as",Space,Str "above."]]]
-                                         ,Div ("",[],[])
-                                          [Plain [Str "And",Space,Str "along",Space,Str "the",Space,Str "Strand,",Space,Str "up",Space,Str "Queen",Space,Str "Victoria",Space,Str "Street."]]
-                                         ,Div ("",[],[])
-                                          [Plain [Str "O",Space,Str "City",Space,Str "city,",Space,Str "I",Space,Str "can",Space,Str "sometimes",Space,Str "hear"]]
-                                         ,Div ("",[],[])
-                                          [Plain [Str "Beside",Space,Str "a",Space,Str "public",Space,Str "bar",Space,Str "in",Space,Str "Lower",Space,Str "Thames",Space,Str "Street,",Span ("",["lnum"],[]) [Str "260"]]]
-                                         ,Div ("",[],[])
-                                          [Plain [Str "The",Space,Str "pleasant",Space,Str "whining",Space,Str "of",Space,Str "a",Space,Str "mandoline"]]
-                                         ,Div ("",[],[])
-                                          [Plain [Str "And",Space,Str "a",Space,Str "clatter",Space,Str "and",Space,Str "a",Space,Str "chatter",Space,Str "from",Space,Str "within"]]
-                                         ,Div ("",[],[])
-                                          [Plain [Str "Where",Space,Str "fishmen",Space,Str "lounge",Space,Str "at",Space,Str "noon:",Space,Str "where",Space,Str "the",Space,Str "walls"]]
-                                         ,Div ("wasteland-content.xhtml#ln264",[],[])
-                                          [Plain [Str "Of",Space,Str "Magnus",Space,Str "Martyr",Space,Str "hold",Note [Para [Link ("",[],[]) [Str "264."] ("#wasteland-content.xhtml#ln264",""),Space,Str "The",Space,Str "interior",Space,Str "of",Space,Str "St.",Space,Str "Magnus",Space,Str "Martyr",Space,Str "is",Space,Str "to",Space,Str "my",Space,Str "mind",Space,Str "one",Space,Str "of",Space,Str "the",Space,Str "finest",SoftBreak,Str "among",Space,Str "Wren's",Space,Str "interiors.",Space,Str "See",Space,Str "The",Space,Str "Proposed",Space,Str "Demolition",Space,Str "of",Space,Str "Nineteen",Space,Str "City",SoftBreak,Str "Churches",Space,Str "(P.",Space,Str "S.",Space,Str "King",Space,Str "&",Space,Str "Son,",Space,Str "Ltd.)."]]]
-                                          ,Div ("",[],[])
-                                           [Plain [Str "Inexplicable",Space,Str "splendour",Space,Str "of",Space,Str "Ionian",Space,Str "white",Space,Str "and",Space,Str "gold."]]]
-                                         ,Div ("",["linegroup","indent"],[])
-                                          [Div ("wasteland-content.xhtml#ln266",[],[])
-                                           [Plain [Str "The",Space,Str "river",Space,Str "sweats",Note [Para [Link ("",[],[]) [Str "266."] ("#wasteland-content.xhtml#ln266",""),Space,Str "The",Space,Str "Song",Space,Str "of",Space,Str "the",Space,Str "(three)",Space,Str "Thames-daughters",Space,Str "begins",Space,Str "here.",Space,Str "From",Space,Str "line",Space,Str "292",SoftBreak,Str "to",Space,Str "306",Space,Str "inclusive",Space,Str "they",Space,Str "speak",Space,Str "in",Space,Str "turn.",Space,Str "V.",Space,Str "Gutterdsammerung,",Space,Str "III.",Space,Str "i:",Space,Str "the",SoftBreak,Str "Rhine-daughters."]]]
-                                           ,Div ("",[],[])
-                                            [Plain [Str "Oil",Space,Str "and",Space,Str "tar"]]
-                                           ,Div ("",[],[])
-                                            [Plain [Str "The",Space,Str "barges",Space,Str "drift"]]
-                                           ,Div ("",[],[])
-                                            [Plain [Str "With",Space,Str "the",Space,Str "turning",Space,Str "tide"]]
-                                           ,Div ("",[],[])
-                                            [Plain [Str "Red",Space,Str "sails",Span ("",["lnum"],[]) [Str "270"]]]
-                                           ,Div ("",[],[])
-                                            [Plain [Str "Wide"]]
-                                           ,Div ("",[],[])
-                                            [Plain [Str "To",Space,Str "leeward,",Space,Str "swing",Space,Str "on",Space,Str "the",Space,Str "heavy",Space,Str "spar."]]
-                                           ,Div ("",[],[])
-                                            [Plain [Str "The",Space,Str "barges",Space,Str "wash"]]
-                                           ,Div ("",[],[])
-                                            [Plain [Str "Drifting",Space,Str "logs"]]
-                                           ,Div ("",[],[])
-                                            [Plain [Str "Down",Space,Str "Greenwich",Space,Str "reach"]]
-                                           ,Div ("",[],[])
-                                            [Plain [Str "Past",Space,Str "the",Space,Str "Isle",Space,Str "of",Space,Str "Dogs."]]
-                                           ,Div ("",["indent"],[])
-                                            [Plain [Str "Weialala",Space,Str "leia"]]
-                                           ,Div ("",["indent"],[])
-                                            [Plain [Str "Wallala",Space,Str "leialala"]]]
-                                          ,Div ("",["linegroup","indent"],[])
-                                           [Div ("wasteland-content.xhtml#ln279",[],[])
-                                            [Plain [Str "Elizabeth",Space,Str "and",Space,Str "Leicester",Note [Para [Link ("",[],[]) [Str "279."] ("#wasteland-content.xhtml#ln279",""),Space,Str "V.",Space,Str "Froude,",Space,Str "Elizabeth,",Space,Str "Vol.",Space,Str "I,",Space,Str "ch.",Space,Str "iv,",Space,Str "letter",Space,Str "of",Space,Str "De",Space,Str "Quadra",Space,Str "to",Space,Str "Philip",SoftBreak,Str "of",Space,Str "Spain:"],BlockQuote [Div ("",[],[]) [Div ("",[],[]) [Plain [Str "\"In",Space,Str "the",Space,Str "afternoon",Space,Str "we",Space,Str "were",Space,Str "in",Space,Str "a",Space,Str "barge,",Space,Str "watching",Space,Str "the",SoftBreak,Str "games",Space,Str "on",Space,Str "the",Space,Str "river."]],Div ("",[],[]) [Plain [Str "(The",Space,Str "queen)",Space,Str "was",Space,Str "alone",Space,Str "with",Space,Str "Lord",Space,Str "Robert",Space,Str "and",Space,Str "myself",SoftBreak,Str "on",Space,Str "the",Space,Str "poop,"]],Div ("",[],[]) [Plain [Str "when",Space,Str "they",Space,Str "began",Space,Str "to",Space,Str "talk",Space,Str "nonsense,",Space,Str "and",Space,Str "went",Space,Str "so",Space,Str "far",SoftBreak,Str "that",Space,Str "Lord",Space,Str "Robert"]],Div ("",[],[]) [Plain [Str "at",Space,Str "last",Space,Str "said,",Space,Str "as",Space,Str "I",Space,Str "was",Space,Str "on",Space,Str "the",Space,Str "spot",Space,Str "there",Space,Str "was",Space,Str "no",SoftBreak,Str "reason",Space,Str "why",Space,Str "they"]],Div ("",[],[]) [Plain [Str "should",Space,Str "not",Space,Str "be",Space,Str "married",Space,Str "if",Space,Str "the",Space,Str "queen",Space,Str "pleased.\""]]]]]]
-                                            ,Div ("",[],[])
-                                             [Plain [Str "Beating",Space,Str "oars",Span ("",["lnum"],[]) [Str "280"]]]
-                                            ,Div ("",[],[])
-                                             [Plain [Str "The",Space,Str "stern",Space,Str "was",Space,Str "formed"]]
-                                            ,Div ("",[],[])
-                                             [Plain [Str "A",Space,Str "gilded",Space,Str "shell"]]
-                                            ,Div ("",[],[])
-                                             [Plain [Str "Red",Space,Str "and",Space,Str "gold"]]
-                                            ,Div ("",[],[])
-                                             [Plain [Str "The",Space,Str "brisk",Space,Str "swell"]]
-                                            ,Div ("",[],[])
-                                             [Plain [Str "Rippled",Space,Str "both",Space,Str "shores"]]
-                                            ,Div ("",[],[])
-                                             [Plain [Str "Southwest",Space,Str "wind"]]
-                                            ,Div ("",[],[])
-                                             [Plain [Str "Carried",Space,Str "down",Space,Str "stream"]]
-                                            ,Div ("",[],[])
-                                             [Plain [Str "The",Space,Str "peal",Space,Str "of",Space,Str "bells"]]
-                                            ,Div ("",[],[])
-                                             [Plain [Str "White",Space,Str "towers"]]
-                                            ,Div ("",["indent"],[])
-                                             [Plain [Str "Weialala",Space,Str "leia",Span ("",["lnum"],[]) [Str "290"]]]
-                                            ,Div ("",["indent"],[])
-                                             [Plain [Str "Wallala",Space,Str "leialala"]]]
-                                           ,Div ("",["linegroup"],[])
-                                            [Div ("",[],[])
-                                             [Plain [Str "\"Trams",Space,Str "and",Space,Str "dusty",Space,Str "trees."]]
-                                            ,Div ("wasteland-content.xhtml#ln293",[],[])
-                                             [Plain [Str "Highbury",Space,Str "bore",Space,Str "me.",Space,Str "Richmond",Space,Str "and",Space,Str "Kew",Note [Para [Link ("",[],[]) [Str "293."] ("#wasteland-content.xhtml#ln293",""),Space,Str "Cf.",Space,Str "Purgatorio,",Space,Str "v.",Space,Str "133:"],BlockQuote [Para [Str "\"Ricorditi",Space,Str "di",Space,Str "me,",Space,Str "che",Space,Str "son",Space,Str "la",Space,Str "Pia;",LineBreak,Str "Siena",Space,Str "mi",Space,Str "fe',",Space,Str "disfecemi",SoftBreak,Str "Maremma.\""]]]]
-                                             ,Div ("",[],[])
-                                              [Plain [Str "Undid",Space,Str "me.",Space,Str "By",Space,Str "Richmond",Space,Str "I",Space,Str "raised",Space,Str "my",Space,Str "knees"]]
-                                             ,Div ("",[],[])
-                                              [Plain [Str "Supine",Space,Str "on",Space,Str "the",Space,Str "floor",Space,Str "of",Space,Str "a",Space,Str "narrow",Space,Str "canoe.\""]]]
-                                            ,Div ("",["linegroup"],[])
-                                             [Div ("",[],[])
-                                              [Plain [Str "\"My",Space,Str "feet",Space,Str "are",Space,Str "at",Space,Str "Moorgate,",Space,Str "and",Space,Str "my",Space,Str "heart"]]
-                                             ,Div ("",[],[])
-                                              [Plain [Str "Under",Space,Str "my",Space,Str "feet.",Space,Str "After",Space,Str "the",Space,Str "event"]]
-                                             ,Div ("",[],[])
-                                              [Plain [Str "He",Space,Str "wept.",Space,Str "He",Space,Str "promised",Space,Str "'a",Space,Str "new",Space,Str "start'."]]
-                                             ,Div ("",[],[])
-                                              [Plain [Str "I",Space,Str "made",Space,Str "no",Space,Str "comment.",Space,Str "What",Space,Str "should",Space,Str "I",Space,Str "resent?\""]]
-                                             ,Div ("",[],[])
-                                              [Plain [Str "\"On",Space,Str "Margate",Space,Str "Sands.",Span ("",["lnum"],[]) [Str "300"]]]
-                                             ,Div ("",[],[])
-                                              [Plain [Str "I",Space,Str "can",Space,Str "connect"]]
-                                             ,Div ("",[],[])
-                                              [Plain [Str "Nothing",Space,Str "with",Space,Str "nothing."]]
-                                             ,Div ("",[],[])
-                                              [Plain [Str "The",Space,Str "broken",Space,Str "fingernails",Space,Str "of",Space,Str "dirty",Space,Str "hands."]]
-                                             ,Div ("",[],[])
-                                              [Plain [Str "My",Space,Str "people",Space,Str "humble",Space,Str "people",Space,Str "who",Space,Str "expect"]]
-                                             ,Div ("",[],[])
-                                              [Plain [Str "Nothing.\""]]
-                                             ,Div ("",["indent"],[])
-                                              [Plain [Str "la",Space,Str "la"]]]
-                                            ,Div ("",["linegroup"],[])
-                                             [Div ("wasteland-content.xhtml#ln307",[],[])
-                                              [Plain [Str "To",Space,Str "Carthage",Space,Str "then",Space,Str "I",Space,Str "came",Note [Para [Link ("",[],[]) [Str "307."] ("#wasteland-content.xhtml#ln307",""),Space,Str "V.",Space,Str "St.",Space,Str "Augustine's",Space,Str "Confessions:",Space,Str "\"to",Space,Str "Carthage",Space,Str "then",Space,Str "I",Space,Str "came,",Space,Str "where",Space,Str "a",SoftBreak,Str "cauldron",Space,Str "of",Space,Str "unholy",Space,Str "loves",Space,Str "sang",Space,Str "all",Space,Str "about",Space,Str "mine",Space,Str "ears.\""]]]
-                                              ,Div ("",["linegroup"],[])
-                                               [Div ("wasteland-content.xhtml#ln308",[],[])
-                                                [Plain [Str "Burning",Space,Str "burning",Space,Str "burning",Space,Str "burning",Note [Para [Link ("",[],[]) [Str "308."] ("#wasteland-content.xhtml#ln308",""),Space,Str "The",Space,Str "complete",Space,Str "text",Space,Str "of",Space,Str "the",Space,Str "Buddha's",Space,Str "Fire",Space,Str "Sermon",Space,Str "(which",Space,Str "corresponds",Space,Str "in",SoftBreak,Str "importance",Space,Str "to",Space,Str "the",Space,Str "Sermon",Space,Str "on",Space,Str "the",Space,Str "Mount)",Space,Str "from",Space,Str "which",Space,Str "these",Space,Str "words",Space,Str "are",Space,Str "taken,",SoftBreak,Str "will",Space,Str "be",Space,Str "found",Space,Str "translated",Space,Str "in",Space,Str "the",Space,Str "late",Space,Str "Henry",Space,Str "Clarke",Space,Str "Warren's",Space,Str "Buddhism",Space,Str "in",SoftBreak,Str "Translation",Space,Str "(Harvard",Space,Str "Oriental",Space,Str "Series).",Space,Str "Mr.",Space,Str "Warren",Space,Str "was",Space,Str "one",Space,Str "of",Space,Str "the",Space,Str "great",SoftBreak,Str "pioneers",Space,Str "of",Space,Str "Buddhist",Space,Str "studies",Space,Str "in",Space,Str "the",Space,Str "Occident."]]]
-                                                ,Div ("wasteland-content.xhtml#ln309",[],[])
-                                                 [Plain [Str "O",Space,Str "Lord",Space,Str "Thou",Space,Str "pluckest",Space,Str "me",Space,Str "out",Note [Para [Link ("",[],[]) [Str "309."] ("#wasteland-content.xhtml#ln309",""),Space,Str "From",Space,Str "St.",Space,Str "Augustine's",Space,Str "Confessions",Space,Str "again.",Space,Str "The",Space,Str "collocation",Space,Str "of",Space,Str "these",Space,Str "two",SoftBreak,Str "representatives",Space,Str "of",Space,Str "eastern",Space,Str "and",Space,Str "western",Space,Str "asceticism,",Space,Str "as",Space,Str "the",Space,Str "culmination",Space,Str "of",SoftBreak,Str "this",Space,Str "part",Space,Str "of",Space,Str "the",Space,Str "poem,",Space,Str "is",Space,Str "not",Space,Str "an",Space,Str "accident."]]]
-                                                 ,Div ("",[],[])
-                                                  [Plain [Str "O",Space,Str "Lord",Space,Str "Thou",Space,Str "pluckest",Span ("",["lnum"],[]) [Str "310"]]]]
-                                                ,Div ("",["linegroup"],[])
-                                                 [Div ("",[],[])
-                                                  [Plain [Str "burning"]]]
-                                                ,RawBlock (Format "html") "</section>"
-                                                ,Div ("wasteland-content.xhtml#ch4",["section"],[])
-                                                 [Header 2 ("",[],[]) [Str "IV.",Space,Str "DEATH",Space,Str "BY",Space,Str "WATER"]
-                                                 ,Div ("",["linegroup"],[])
-                                                  [Div ("",[],[])
-                                                   [Plain [Str "Phlebas",Space,Str "the",Space,Str "Phoenician,",Space,Str "a",Space,Str "fortnight",Space,Str "dead,"]]
-                                                  ,Div ("",[],[])
-                                                   [Plain [Str "Forgot",Space,Str "the",Space,Str "cry",Space,Str "of",Space,Str "gulls,",Space,Str "and",Space,Str "the",Space,Str "deep",Space,Str "sea",Space,Str "swell"]]
-                                                  ,Div ("",[],[])
-                                                   [Plain [Str "And",Space,Str "the",Space,Str "profit",Space,Str "and",Space,Str "loss."]]]
-                                                 ,Div ("",["linegroup"],[])
-                                                  [Div ("",["indent2"],[])
-                                                   [Plain [Str "A",Space,Str "current",Space,Str "under",Space,Str "sea"]]
-                                                  ,Div ("",[],[])
-                                                   [Plain [Str "Picked",Space,Str "his",Space,Str "bones",Space,Str "in",Space,Str "whispers.",Space,Str "As",Space,Str "he",Space,Str "rose",Space,Str "and",Space,Str "fell"]]
-                                                  ,Div ("",[],[])
-                                                   [Plain [Str "He",Space,Str "passed",Space,Str "the",Space,Str "stages",Space,Str "of",Space,Str "his",Space,Str "age",Space,Str "and",Space,Str "youth"]]
-                                                  ,Div ("",[],[])
-                                                   [Plain [Str "Entering",Space,Str "the",Space,Str "whirlpool."]]]
-                                                 ,Div ("",["linegroup"],[])
-                                                  [Div ("",["indent2"],[])
-                                                   [Plain [Str "Gentile",Space,Str "or",Space,Str "Jew"]]
-                                                  ,Div ("",[],[])
-                                                   [Plain [Str "O",Space,Str "you",Space,Str "who",Space,Str "turn",Space,Str "the",Space,Str "wheel",Space,Str "and",Space,Str "look",Space,Str "to",Space,Str "windward,",Span ("",["lnum"],[]) [Str "320"]]]
-                                                  ,Div ("",[],[])
-                                                   [Plain [Str "Consider",Space,Str "Phlebas,",Space,Str "who",Space,Str "was",Space,Str "once",Space,Str "handsome",Space,Str "and",Space,Str "tall",Space,Str "as",Space,Str "you."]]]]
-                                                ,Div ("wasteland-content.xhtml#ch5",["section"],[])
-                                                 [Header 2 ("",[],[]) [Str "V.",Space,Str "WHAT",Space,Str "THE",Space,Str "THUNDER",Space,Str "SAID"]
-                                                 ,Div ("",["linegroup"],[])
-                                                  [Div ("",[],[])
-                                                   [Plain [Str "After",Space,Str "the",Space,Str "torchlight",Space,Str "red",Space,Str "on",Space,Str "sweaty",Space,Str "faces"]]
-                                                  ,Div ("",[],[])
-                                                   [Plain [Str "After",Space,Str "the",Space,Str "frosty",Space,Str "silence",Space,Str "in",Space,Str "the",Space,Str "gardens"]]
-                                                  ,Div ("",[],[])
-                                                   [Plain [Str "After",Space,Str "the",Space,Str "agony",Space,Str "in",Space,Str "stony",Space,Str "places"]]
-                                                  ,Div ("",[],[])
-                                                   [Plain [Str "The",Space,Str "shouting",Space,Str "and",Space,Str "the",Space,Str "crying"]]
-                                                  ,Div ("",[],[])
-                                                   [Plain [Str "Prison",Space,Str "and",Space,Str "palace",Space,Str "and",Space,Str "reverberation"]]
-                                                  ,Div ("",[],[])
-                                                   [Plain [Str "Of",Space,Str "thunder",Space,Str "of",Space,Str "spring",Space,Str "over",Space,Str "distant",Space,Str "mountains"]]
-                                                  ,Div ("",[],[])
-                                                   [Plain [Str "He",Space,Str "who",Space,Str "was",Space,Str "living",Space,Str "is",Space,Str "now",Space,Str "dead"]]
-                                                  ,Div ("",[],[])
-                                                   [Plain [Str "We",Space,Str "who",Space,Str "were",Space,Str "living",Space,Str "are",Space,Str "now",Space,Str "dying"]]
-                                                  ,Div ("",[],[])
-                                                   [Plain [Str "With",Space,Str "a",Space,Str "little",Space,Str "patience",Span ("",["lnum"],[]) [Str "330"]]]]
-                                                 ,Div ("",["linegroup"],[])
-                                                  [Div ("",[],[])
-                                                   [Plain [Str "Here",Space,Str "is",Space,Str "no",Space,Str "water",Space,Str "but",Space,Str "only",Space,Str "rock"]]
-                                                  ,Div ("",[],[])
-                                                   [Plain [Str "Rock",Space,Str "and",Space,Str "no",Space,Str "water",Space,Str "and",Space,Str "the",Space,Str "sandy",Space,Str "road"]]
-                                                  ,Div ("",[],[])
-                                                   [Plain [Str "The",Space,Str "road",Space,Str "winding",Space,Str "above",Space,Str "among",Space,Str "the",Space,Str "mountains"]]
-                                                  ,Div ("",[],[])
-                                                   [Plain [Str "Which",Space,Str "are",Space,Str "mountains",Space,Str "of",Space,Str "rock",Space,Str "without",Space,Str "water"]]
-                                                  ,Div ("",[],[])
-                                                   [Plain [Str "If",Space,Str "there",Space,Str "were",Space,Str "water",Space,Str "we",Space,Str "should",Space,Str "stop",Space,Str "and",Space,Str "drink"]]
-                                                  ,Div ("",[],[])
-                                                   [Plain [Str "Amongst",Space,Str "the",Space,Str "rock",Space,Str "one",Space,Str "cannot",Space,Str "stop",Space,Str "or",Space,Str "think"]]
-                                                  ,Div ("",[],[])
-                                                   [Plain [Str "Sweat",Space,Str "is",Space,Str "dry",Space,Str "and",Space,Str "feet",Space,Str "are",Space,Str "in",Space,Str "the",Space,Str "sand"]]
-                                                  ,Div ("",[],[])
-                                                   [Plain [Str "If",Space,Str "there",Space,Str "were",Space,Str "only",Space,Str "water",Space,Str "amongst",Space,Str "the",Space,Str "rock"]]
-                                                  ,Div ("",[],[])
-                                                   [Plain [Str "Dead",Space,Str "mountain",Space,Str "mouth",Space,Str "of",Space,Str "carious",Space,Str "teeth",Space,Str "that",Space,Str "cannot",Space,Str "spit"]]
-                                                  ,Div ("",[],[])
-                                                   [Plain [Str "Here",Space,Str "one",Space,Str "can",Space,Str "neither",Space,Str "stand",Space,Str "nor",Space,Str "lie",Space,Str "nor",Space,Str "sit",Span ("",["lnum"],[]) [Str "340"]]]
-                                                  ,Div ("",[],[])
-                                                   [Plain [Str "There",Space,Str "is",Space,Str "not",Space,Str "even",Space,Str "silence",Space,Str "in",Space,Str "the",Space,Str "mountains"]]
-                                                  ,Div ("",[],[])
-                                                   [Plain [Str "But",Space,Str "dry",Space,Str "sterile",Space,Str "thunder",Space,Str "without",Space,Str "rain"]]
-                                                  ,Div ("",[],[])
-                                                   [Plain [Str "There",Space,Str "is",Space,Str "not",Space,Str "even",Space,Str "solitude",Space,Str "in",Space,Str "the",Space,Str "mountains"]]
-                                                  ,Div ("",[],[])
-                                                   [Plain [Str "But",Space,Str "red",Space,Str "sullen",Space,Str "faces",Space,Str "sneer",Space,Str "and",Space,Str "snarl"]]
-                                                  ,Div ("",[],[])
-                                                   [Plain [Str "From",Space,Str "doors",Space,Str "of",Space,Str "mudcracked",Space,Str "houses"]]
-                                                  ,Div ("",["linegroup"],[])
-                                                   [Div ("",["indent2"],[])
-                                                    [Plain [Str "If",Space,Str "there",Space,Str "were",Space,Str "water"]]
-                                                   ,Div ("",[],[])
-                                                    [Plain [Str "And",Space,Str "no",Space,Str "rock"]]
-                                                   ,Div ("",[],[])
-                                                    [Plain [Str "If",Space,Str "there",Space,Str "were",Space,Str "rock"]]
-                                                   ,Div ("",[],[])
-                                                    [Plain [Str "And",Space,Str "also",Space,Str "water"]]
-                                                   ,Div ("",[],[])
-                                                    [Plain [Str "And",Space,Str "water",Span ("",["lnum"],[]) [Str "350"]]]
-                                                   ,Div ("",[],[])
-                                                    [Plain [Str "A",Space,Str "spring"]]
-                                                   ,Div ("",[],[])
-                                                    [Plain [Str "A",Space,Str "pool",Space,Str "among",Space,Str "the",Space,Str "rock"]]
-                                                   ,Div ("",[],[])
-                                                    [Plain [Str "If",Space,Str "there",Space,Str "were",Space,Str "the",Space,Str "sound",Space,Str "of",Space,Str "water",Space,Str "only"]]
-                                                   ,Div ("",[],[])
-                                                    [Plain [Str "Not",Space,Str "the",Space,Str "cicada"]]
-                                                   ,Div ("",[],[])
-                                                    [Plain [Str "And",Space,Str "dry",Space,Str "grass",Space,Str "singing"]]
-                                                   ,Div ("",[],[])
-                                                    [Plain [Str "But",Space,Str "sound",Space,Str "of",Space,Str "water",Space,Str "over",Space,Str "a",Space,Str "rock"]]
-                                                   ,Div ("wasteland-content.xhtml#ln357",[],[])
-                                                    [Plain [Str "Where",Space,Str "the",Space,Str "hermit-thrush",Space,Str "sings",Space,Str "in",Space,Str "the",Space,Str "pine",Space,Str "trees",Note [Para [Link ("",[],[]) [Str "357."] ("#wasteland-content.xhtml#ln357",""),Space,Str "This",Space,Str "is",Space,Str "Turdus",Space,Str "aonalaschkae",Space,Str "pallasii,",Space,Str "the",Space,Str "hermit-thrush",Space,Str "which",Space,Str "I",Space,Str "have",SoftBreak,Str "heard",Space,Str "in",Space,Str "Quebec",Space,Str "County.",Space,Str "Chapman",Space,Str "says",Space,Str "(Handbook",Space,Str "of",Space,Str "Birds",Space,Str "of",Space,Str "Eastern",Space,Str "North",SoftBreak,Str "America)",Space,Str "\"it",Space,Str "is",Space,Str "most",Space,Str "at",Space,Str "home",Space,Str "in",Space,Str "secluded",Space,Str "woodland",Space,Str "and",Space,Str "thickety",Space,Str "retreats.",SoftBreak,Str ".",Space,Str ".",Space,Str ".",Space,Str "Its",Space,Str "notes",Space,Str "are",Space,Str "not",Space,Str "remarkable",Space,Str "for",Space,Str "variety",Space,Str "or",Space,Str "volume,",Space,Str "but",Space,Str "in",Space,Str "purity",SoftBreak,Str "and",Space,Str "sweetness",Space,Str "of",Space,Str "tone",Space,Str "and",Space,Str "exquisite",Space,Str "modulation",Space,Str "they",Space,Str "are",Space,Str "unequalled.\"",Space,Str "Its",SoftBreak,Str "\"water-dripping",Space,Str "song\"",Space,Str "is",Space,Str "justly",Space,Str "celebrated."]]]
-                                                    ,Div ("",[],[])
-                                                     [Plain [Str "Drip",Space,Str "drop",Space,Str "drip",Space,Str "drop",Space,Str "drop",Space,Str "drop",Space,Str "drop"]]
-                                                    ,Div ("",[],[])
-                                                     [Plain [Str "But",Space,Str "there",Space,Str "is",Space,Str "no",Space,Str "water"]]]]
-                                                  ,Div ("",["linegroup"],[])
-                                                   [Div ("wasteland-content.xhtml#ln360",[],[])
-                                                    [Plain [Str "Who",Space,Str "is",Space,Str "the",Space,Str "third",Space,Str "who",Space,Str "walks",Space,Str "always",Space,Str "beside",Space,Str "you?",Note [Para [Link ("",[],[]) [Str "360."] ("#wasteland-content.xhtml#ln360",""),Space,Str "The",Space,Str "following",Space,Str "lines",Space,Str "were",Space,Str "stimulated",Space,Str "by",Space,Str "the",Space,Str "account",Space,Str "of",Space,Str "one",Space,Str "of",Space,Str "the",SoftBreak,Str "Antarctic",Space,Str "expeditions",Space,Str "(I",Space,Str "forget",Space,Str "which,",Space,Str "but",Space,Str "I",Space,Str "think",Space,Str "one",Space,Str "of",Space,Str "Shackleton's):",SoftBreak,Str "it",Space,Str "was",Space,Str "related",Space,Str "that",Space,Str "the",Space,Str "party",Space,Str "of",Space,Str "explorers,",Space,Str "at",Space,Str "the",Space,Str "extremity",Space,Str "of",Space,Str "their",SoftBreak,Str "strength,",Space,Str "had",Space,Str "the",Space,Str "constant",Space,Str "delusion",Space,Str "that",Space,Str "there",Space,Str "was",Space,Str "one",Space,Str "more",Space,Str "member",Space,Str "than",SoftBreak,Str "could",Space,Str "actually",Space,Str "be",Space,Str "counted."]]]
-                                                    ,Div ("",[],[])
-                                                     [Plain [Str "When",Space,Str "I",Space,Str "count,",Space,Str "there",Space,Str "are",Space,Str "only",Space,Str "you",Space,Str "and",Space,Str "I",Space,Str "together"]]
-                                                    ,Div ("",[],[])
-                                                     [Plain [Str "But",Space,Str "when",Space,Str "I",Space,Str "look",Space,Str "ahead",Space,Str "up",Space,Str "the",Space,Str "white",Space,Str "road"]]
-                                                    ,Div ("",[],[])
-                                                     [Plain [Str "There",Space,Str "is",Space,Str "always",Space,Str "another",Space,Str "one",Space,Str "walking",Space,Str "beside",Space,Str "you"]]
-                                                    ,Div ("",[],[])
-                                                     [Plain [Str "Gliding",Space,Str "wrapt",Space,Str "in",Space,Str "a",Space,Str "brown",Space,Str "mantle,",Space,Str "hooded"]]
-                                                    ,Div ("",[],[])
-                                                     [Plain [Str "I",Space,Str "do",Space,Str "not",Space,Str "know",Space,Str "whether",Space,Str "a",Space,Str "man",Space,Str "or",Space,Str "a",Space,Str "woman"]]
-                                                    ,Div ("wasteland-content.xhtml#ln367",[],[])
-                                                     [Plain [Str "\8213But",Space,Str "who",Space,Str "is",Space,Str "that",Space,Str "on",Space,Str "the",Space,Str "other",Space,Str "side",Space,Str "of",Space,Str "you?",Note [Para [Link ("",[],[]) [Str "367-77."] ("#wasteland-content.xhtml#ln367",""),Space,Str "Cf.",Space,Str "Hermann",Space,Str "Hesse,",Space,Str "Blick",Space,Str "ins",Space,Str "Chaos:"],BlockQuote [Para [Str "\"Schon",Space,Str "ist",Space,Str "halb",Space,Str "Europa,",Space,Str "schon",Space,Str "ist",Space,Str "zumindest",Space,Str "der",Space,Str "halbe",Space,Str "Osten",Space,Str "Europas",SoftBreak,Str "auf",Space,Str "dem",LineBreak,Str "Wege",Space,Str "zum",Space,Str "Chaos,",Space,Str "fhrt",Space,Str "betrunken",Space,Str "im",Space,Str "heiligem",Space,Str "Wahn",Space,Str "am",SoftBreak,Str "Abgrund",Space,Str "entlang",LineBreak,Str "und",Space,Str "singt",Space,Str "dazu,",Space,Str "singt",Space,Str "betrunken",Space,Str "und",Space,Str "hymnisch",SoftBreak,Str "wie",Space,Str "Dmitri",Space,Str "Karamasoff",Space,Str "sang.",LineBreak,Str "Ueber",Space,Str "diese",Space,Str "Lieder",Space,Str "lacht",Space,Str "der",SoftBreak,Str "Bsrger",Space,Str "beleidigt,",Space,Str "der",Space,Str "Heilige",LineBreak,Str "und",Space,Str "Seher",Space,Str "hrt",Space,Str "sie",Space,Str "mit",SoftBreak,Str "Trvnen.\""]]]]
-                                                     ,Div ("",["linegroup"],[])
-                                                      [Div ("",[],[])
-                                                       [Plain [Str "What",Space,Str "is",Space,Str "that",Space,Str "sound",Space,Str "high",Space,Str "in",Space,Str "the",Space,Str "air"]]
-                                                      ,Div ("",[],[])
-                                                       [Plain [Str "Murmur",Space,Str "of",Space,Str "maternal",Space,Str "lamentation"]]
-                                                      ,Div ("",[],[])
-                                                       [Plain [Str "Who",Space,Str "are",Space,Str "those",Space,Str "hooded",Space,Str "hordes",Space,Str "swarming"]]
-                                                      ,Div ("",[],[])
-                                                       [Plain [Str "Over",Space,Str "endless",Space,Str "plains,",Space,Str "stumbling",Space,Str "in",Space,Str "cracked",Space,Str "earth",Span ("",["lnum"],[]) [Str "370"]]]
-                                                      ,Div ("",[],[])
-                                                       [Plain [Str "Ringed",Space,Str "by",Space,Str "the",Space,Str "flat",Space,Str "horizon",Space,Str "only"]]
-                                                      ,Div ("",[],[])
-                                                       [Plain [Str "What",Space,Str "is",Space,Str "the",Space,Str "city",Space,Str "over",Space,Str "the",Space,Str "mountains"]]
-                                                      ,Div ("",[],[])
-                                                       [Plain [Str "Cracks",Space,Str "and",Space,Str "reforms",Space,Str "and",Space,Str "bursts",Space,Str "in",Space,Str "the",Space,Str "violet",Space,Str "air"]]
-                                                      ,Div ("",[],[])
-                                                       [Plain [Str "Falling",Space,Str "towers"]]
-                                                      ,Div ("",[],[])
-                                                       [Plain [Str "Jerusalem",Space,Str "Athens",Space,Str "Alexandria"]]
-                                                      ,Div ("",[],[])
-                                                       [Plain [Str "Vienna",Space,Str "London"]]
-                                                      ,Div ("",[],[])
-                                                       [Plain [Str "Unreal"]]]
-                                                     ,Div ("",["linegroup"],[])
-                                                      [Div ("",[],[])
-                                                       [Plain [Str "A",Space,Str "woman",Space,Str "drew",Space,Str "her",Space,Str "long",Space,Str "black",Space,Str "hair",Space,Str "out",Space,Str "tight"]]
-                                                      ,Div ("",[],[])
-                                                       [Plain [Str "And",Space,Str "fiddled",Space,Str "whisper",Space,Str "music",Space,Str "on",Space,Str "those",Space,Str "strings"]]
-                                                      ,Div ("",[],[])
-                                                       [Plain [Str "And",Space,Str "bats",Space,Str "with",Space,Str "baby",Space,Str "faces",Space,Str "in",Space,Str "the",Space,Str "violet",Space,Str "light",Span ("",["lnum"],[]) [Str "380"]]]
-                                                      ,Div ("",[],[])
-                                                       [Plain [Str "Whistled,",Space,Str "and",Space,Str "beat",Space,Str "their",Space,Str "wings"]]
-                                                      ,Div ("",[],[])
-                                                       [Plain [Str "And",Space,Str "crawled",Space,Str "head",Space,Str "downward",Space,Str "down",Space,Str "a",Space,Str "blackened",Space,Str "wall"]]
-                                                      ,Div ("",[],[])
-                                                       [Plain [Str "And",Space,Str "upside",Space,Str "down",Space,Str "in",Space,Str "air",Space,Str "were",Space,Str "towers"]]
-                                                      ,Div ("",[],[])
-                                                       [Plain [Str "Tolling",Space,Str "reminiscent",Space,Str "bells,",Space,Str "that",Space,Str "kept",Space,Str "the",Space,Str "hours"]]
-                                                      ,Div ("",[],[])
-                                                       [Plain [Str "And",Space,Str "voices",Space,Str "singing",Space,Str "out",Space,Str "of",Space,Str "empty",Space,Str "cisterns",Space,Str "and",Space,Str "exhausted",SoftBreak,Str "wells."]]]
-                                                     ,Div ("",["linegroup"],[])
-                                                      [Div ("",[],[])
-                                                       [Plain [Str "In",Space,Str "this",Space,Str "decayed",Space,Str "hole",Space,Str "among",Space,Str "the",Space,Str "mountains"]]
-                                                      ,Div ("",[],[])
-                                                       [Plain [Str "In",Space,Str "the",Space,Str "faint",Space,Str "moonlight,",Space,Str "the",Space,Str "grass",Space,Str "is",Space,Str "singing"]]
-                                                      ,Div ("",[],[])
-                                                       [Plain [Str "Over",Space,Str "the",Space,Str "tumbled",Space,Str "graves,",Space,Str "about",Space,Str "the",Space,Str "chapel"]]
-                                                      ,Div ("",[],[])
-                                                       [Plain [Str "There",Space,Str "is",Space,Str "the",Space,Str "empty",Space,Str "chapel,",Space,Str "only",Space,Str "the",Space,Str "wind's",Space,Str "home."]]
-                                                      ,Div ("",[],[])
-                                                       [Plain [Str "It",Space,Str "has",Space,Str "no",Space,Str "windows,",Space,Str "and",Space,Str "the",Space,Str "door",Space,Str "swings,",Span ("",["lnum"],[]) [Str "390"]]]
-                                                      ,Div ("",[],[])
-                                                       [Plain [Str "Dry",Space,Str "bones",Space,Str "can",Space,Str "harm",Space,Str "no",Space,Str "one."]]
-                                                      ,Div ("",[],[])
-                                                       [Plain [Str "Only",Space,Str "a",Space,Str "cock",Space,Str "stood",Space,Str "on",Space,Str "the",Space,Str "rooftree"]]
-                                                      ,Div ("",[],[])
-                                                       [Plain [Str "Co",Space,Str "co",Space,Str "rico",Space,Str "co",Space,Str "co",Space,Str "rico"]]
-                                                      ,Div ("",[],[])
-                                                       [Plain [Str "In",Space,Str "a",Space,Str "flash",Space,Str "of",Space,Str "lightning.",Space,Str "Then",Space,Str "a",Space,Str "damp",Space,Str "gust"]]
-                                                      ,Div ("",[],[])
-                                                       [Plain [Str "Bringing",Space,Str "rain"]]]
-                                                     ,Div ("",["linegroup"],[])
-                                                      [Div ("",[],[])
-                                                       [Plain [Str "Ganga",Space,Str "was",Space,Str "sunken,",Space,Str "and",Space,Str "the",Space,Str "limp",Space,Str "leaves"]]
-                                                      ,Div ("",[],[])
-                                                       [Plain [Str "Waited",Space,Str "for",Space,Str "rain,",Space,Str "while",Space,Str "the",Space,Str "black",Space,Str "clouds"]]
-                                                      ,Div ("",[],[])
-                                                       [Plain [Str "Gathered",Space,Str "far",Space,Str "distant,",Space,Str "over",Space,Str "Himavant."]]
-                                                      ,Div ("",[],[])
-                                                       [Plain [Str "The",Space,Str "jungle",Space,Str "crouched,",Space,Str "humped",Space,Str "in",Space,Str "silence."]]
-                                                      ,Div ("",[],[])
-                                                       [Plain [Str "Then",Space,Str "spoke",Space,Str "the",Space,Str "thunder",Span ("",["lnum"],[]) [Str "400"]]]
-                                                      ,Div ("",[],[])
-                                                       [Plain [Str "DA"]]
-                                                      ,Div ("wasteland-content.xhtml#ln402",[],[])
-                                                       [Plain [Span ("",[],[("lang","sa")]) [Str "Datta"],Str ":",Space,Str "what",Space,Str "have",Space,Str "we",Space,Str "given?",Note [Para [Link ("",[],[]) [Str "402."] ("#wasteland-content.xhtml#ln402",""),Space,Quoted DoubleQuote [Str "\"Datta,",Space,Str "dayadhvam,",Space,Str "damyata\""],Space,Str "(Give,",Space,Str "sympathize,",SoftBreak,Str "control).",Space,Str "The",Space,Str "fable",Space,Str "of",Space,Str "the",Space,Str "meaning",Space,Str "of",Space,Str "the",Space,Str "Thunder",Space,Str "is",Space,Str "found",Space,Str "in",Space,Str "the",SoftBreak,Str "Brihadaranyaka-Upanishad,",Space,Str "5,",Space,Str "1.",Space,Str "A",Space,Str "translation",Space,Str "is",Space,Str "found",Space,Str "in",Space,Str "Deussen's",SoftBreak,Str "Sechzig",Space,Str "Upanishads",Space,Str "des",Space,Str "Veda,",Space,Str "p.",Space,Str "489."]]]
-                                                       ,Div ("",[],[])
-                                                        [Plain [Str "My",Space,Str "friend,",Space,Str "blood",Space,Str "shaking",Space,Str "my",Space,Str "heart"]]
-                                                       ,Div ("",[],[])
-                                                        [Plain [Str "The",Space,Str "awful",Space,Str "daring",Space,Str "of",Space,Str "a",Space,Str "moment's",Space,Str "surrender"]]
-                                                       ,Div ("",[],[])
-                                                        [Plain [Str "Which",Space,Str "an",Space,Str "age",Space,Str "of",Space,Str "prudence",Space,Str "can",Space,Str "never",Space,Str "retract"]]
-                                                       ,Div ("",[],[])
-                                                        [Plain [Str "By",Space,Str "this,",Space,Str "and",Space,Str "this",Space,Str "only,",Space,Str "we",Space,Str "have",Space,Str "existed"]]
-                                                       ,Div ("",[],[])
-                                                        [Plain [Str "Which",Space,Str "is",Space,Str "not",Space,Str "to",Space,Str "be",Space,Str "found",Space,Str "in",Space,Str "our",Space,Str "obituaries"]]
-                                                       ,Div ("wasteland-content.xhtml#ln408",[],[])
-                                                        [Plain [Str "Or",Space,Str "in",Space,Str "memories",Space,Str "draped",Space,Str "by",Space,Str "the",Space,Str "beneficent",Space,Str "spider",Note [Para [Link ("",[],[]) [Str "408."] ("#wasteland-content.xhtml#ln408",""),Space,Str "Cf.",Space,Str "Webster,",Space,Str "The",Space,Str "White",Space,Str "Devil,",Space,Str "v.",Space,Str "vi:"],BlockQuote [Para [Str "\".",Space,Str ".",Space,Str ".",Space,Str "they'll",Space,Str "remarry",LineBreak,Str "Ere",Space,Str "the",Space,Str "worm",Space,Str "pierce",Space,Str "your",Space,Str "winding-sheet,",SoftBreak,Str "ere",Space,Str "the",Space,Str "spider",LineBreak,Str "Make",Space,Str "a",Space,Str "thin",Space,Str "curtain",Space,Str "for",Space,Str "your",Space,Str "epitaphs.\""]]]]
-                                                        ,Div ("",[],[])
-                                                         [Plain [Str "Or",Space,Str "under",Space,Str "seals",Space,Str "broken",Space,Str "by",Space,Str "the",Space,Str "lean",Space,Str "solicitor"]]
-                                                        ,Div ("",[],[])
-                                                         [Plain [Str "In",Space,Str "our",Space,Str "empty",Space,Str "rooms",Span ("",["lnum"],[]) [Str "410"]]]
-                                                        ,Div ("",[],[])
-                                                         [Plain [Str "DA"]]
-                                                        ,Div ("wasteland-content.xhtml#ln412",[],[])
-                                                         [Plain [Span ("",[],[("lang","sa")]) [Str "Dayadhvam"],Str ":",Space,Str "I",Space,Str "have",Space,Str "heard",Space,Str "the",Space,Str "key",Note [Para [Link ("",[],[]) [Str "412."] ("#wasteland-content.xhtml#ln412",""),Space,Str "Cf.",Space,Str "Inferno,",Space,Str "xxxiii.",Space,Str "46:"],BlockQuote [Para [Str "\"ed",Space,Str "io",Space,Str "sentii",Space,Str "chiavar",Space,Str "l'uscio",Space,Str "di",Space,Str "sotto",LineBreak,Str "all'orribile",Space,Str "torre.\""]],Para [Str "Also",Space,Str "F.",Space,Str "H.",Space,Str "Bradley,",Space,Str "Appearance",Space,Str "and",Space,Str "Reality,",Space,Str "p.",Space,Str "346:"],BlockQuote [Para [Str "\"My",Space,Str "external",Space,Str "sensations",Space,Str "are",Space,Str "no",Space,Str "less",Space,Str "private",Space,Str "to",Space,Str "myself",Space,Str "than",Space,Str "are",Space,Str "my",SoftBreak,Str "thoughts",Space,Str "or",Space,Str "my",Space,Str "feelings.",Space,Str "In",Space,Str "either",Space,Str "case",Space,Str "my",Space,Str "experience",Space,Str "falls",Space,Str "within",SoftBreak,Str "my",Space,Str "own",Space,Str "circle,",Space,Str "a",Space,Str "circle",Space,Str "closed",Space,Str "on",Space,Str "the",Space,Str "outside;",Space,Str "and,",Space,Str "with",Space,Str "all",Space,Str "its",SoftBreak,Str "elements",Space,Str "alike,",Space,Str "every",Space,Str "sphere",Space,Str "is",Space,Str "opaque",Space,Str "to",Space,Str "the",Space,Str "others",Space,Str "which",Space,Str "surround",SoftBreak,Str "it.",Space,Str ".",Space,Str ".",Space,Str ".",Space,Str "In",Space,Str "brief,",Space,Str "regarded",Space,Str "as",Space,Str "an",Space,Str "existence",Space,Str "which",Space,Str "appears",Space,Str "in",Space,Str "a",SoftBreak,Str "soul,",Space,Str "the",Space,Str "whole",Space,Str "world",Space,Str "for",Space,Str "each",Space,Str "is",Space,Str "peculiar",Space,Str "and",Space,Str "private",Space,Str "to",Space,Str "that",SoftBreak,Str "soul.\""]]]]
-                                                         ,Div ("",[],[])
-                                                          [Plain [Str "Turn",Space,Str "in",Space,Str "the",Space,Str "door",Space,Str "once",Space,Str "and",Space,Str "turn",Space,Str "once",Space,Str "only"]]
-                                                         ,Div ("",[],[])
-                                                          [Plain [Str "We",Space,Str "think",Space,Str "of",Space,Str "the",Space,Str "key,",Space,Str "each",Space,Str "in",Space,Str "his",Space,Str "prison"]]
-                                                         ,Div ("",[],[])
-                                                          [Plain [Str "Thinking",Space,Str "of",Space,Str "the",Space,Str "key,",Space,Str "each",Space,Str "confirms",Space,Str "a",Space,Str "prison"]]
-                                                         ,Div ("",[],[])
-                                                          [Plain [Str "Only",Space,Str "at",Space,Str "nightfall,",Space,Str "aetherial",Space,Str "rumours"]]
-                                                         ,Div ("",[],[])
-                                                          [Plain [Str "Revive",Space,Str "for",Space,Str "a",Space,Str "moment",Space,Str "a",Space,Str "broken",Space,Str "Coriolanus"]]
-                                                         ,Div ("",[],[])
-                                                          [Plain [Str "DA"]]
-                                                         ,Div ("",[],[])
-                                                          [Plain [Span ("",[],[("lang","sa")]) [Str "Damyata"],Str ":",Space,Str "The",Space,Str "boat",Space,Str "responded"]]
-                                                         ,Div ("",[],[])
-                                                          [Plain [Str "Gaily,",Space,Str "to",Space,Str "the",Space,Str "hand",Space,Str "expert",Space,Str "with",Space,Str "sail",Space,Str "and",Space,Str "oar",Span ("",["lnum"],[]) [Str "420"]]]
-                                                         ,Div ("",[],[])
-                                                          [Plain [Str "The",Space,Str "sea",Space,Str "was",Space,Str "calm,",Space,Str "your",Space,Str "heart",Space,Str "would",Space,Str "have",Space,Str "responded"]]
-                                                         ,Div ("",[],[])
-                                                          [Plain [Str "Gaily,",Space,Str "when",Space,Str "invited,",Space,Str "beating",Space,Str "obedient"]]
-                                                         ,Div ("",[],[])
-                                                          [Plain [Str "To",Space,Str "controlling",Space,Str "hands"]]]
-                                                        ,Div ("",["linegroup"],[])
-                                                         [Div ("",["indent"],[])
-                                                          [Plain [Str "I",Space,Str "sat",Space,Str "upon",Space,Str "the",Space,Str "shore"]]
-                                                         ,Div ("wasteland-content.xhtml#ln425",[],[])
-                                                          [Plain [Str "Fishing,",Space,Str "with",Space,Str "the",Space,Str "arid",Space,Str "plain",Space,Str "behind",Space,Str "me",Note [Para [Link ("",[],[]) [Str "425."] ("#wasteland-content.xhtml#ln425",""),Space,Str "V.",Space,Str "Weston,",Space,Str "From",Space,Str "Ritual",Space,Str "to",Space,Str "Romance;",Space,Str "chapter",Space,Str "on",Space,Str "the",Space,Str "Fisher",Space,Str "King."]]]
-                                                          ,Div ("",[],[])
-                                                           [Plain [Str "Shall",Space,Str "I",Space,Str "at",Space,Str "least",Space,Str "set",Space,Str "my",Space,Str "lands",Space,Str "in",Space,Str "order?"]]
-                                                          ,Div ("",[],[])
-                                                           [Plain [Str "London",Space,Str "Bridge",Space,Str "is",Space,Str "falling",Space,Str "down",Space,Str "falling",Space,Str "down",Space,Str "falling",Space,Str "down"]]
-                                                          ,Div ("wasteland-content.xhtml#ln428",[],[("lang","it")])
-                                                           [Plain [Emph [Str "Poi",Space,Str "s'ascose",Space,Str "nel",Space,Str "foco",Space,Str "che",Space,Str "gli",Space,Str "affina"],SoftBreak,Note [Para [Link ("",[],[]) [Str "428."] ("#wasteland-content.xhtml#ln428",""),Space,Str "V.",Space,Str "Purgatorio,",Space,Str "xxvi.",Space,Str "148."],BlockQuote [Para [Str "\"'Ara",Space,Str "vos",Space,Str "prec",Space,Str "per",Space,Str "aquella",Space,Str "valor",LineBreak,Str "'que",Space,Str "vos",Space,Str "guida",Space,Str "al",Space,Str "som",Space,Str "de",SoftBreak,Str "l'escalina,",LineBreak,Str "'sovegna",Space,Str "vos",Space,Str "a",Space,Str "temps",Space,Str "de",Space,Str "ma",Space,Str "dolor.'",LineBreak,Str "Poi",SoftBreak,Str "s'ascose",Space,Str "nel",Space,Str "foco",Space,Str "che",Space,Str "gli",Space,Str "affina.\""]]]]
-                                                           ,Div ("wasteland-content.xhtml#ln429",[],[])
-                                                            [Plain [Span ("",[],[("lang","it")]) [SoftBreak,Emph [Str "Quando",Space,Str "fiam",Space,Str "ceu",Space,Str "chelidon"],SoftBreak],Space,Str "-",Space,Str "O",Space,Str "swallow",Space,Str "swallow",Note [Para [Link ("",[],[]) [Str "429."] ("#wasteland-content.xhtml#ln429",""),Space,Str "V.",Space,Str "Pervigilium",Space,Str "Veneris.",Space,Str "Cf.",Space,Str "Philomela",Space,Str "in",Space,Str "Parts",Space,Str "II",Space,Str "and",Space,Str "III."]]]
-                                                            ,Div ("wasteland-content.xhtml#ln430",[],[("lang","fr")])
-                                                             [Plain [Emph [Str "Le",Space,Str "Prince",Space,Str "d'Aquitaine",Space,Str "a",Space,Str "la",Space,Str "tour",Space,Str "abolie"],SoftBreak,Note [Para [Link ("",[],[]) [Str "430."] ("#wasteland-content.xhtml#ln430",""),Space,Str "V.",Space,Str "Gerard",Space,Str "de",Space,Str "Nerval,",Space,Str "Sonnet",Space,Str "El",Space,Str "Desdichado."]]]
-                                                             ,Div ("",[],[])
-                                                              [Plain [Str "These",Space,Str "fragments",Space,Str "I",Space,Str "have",Space,Str "shored",Space,Str "against",Space,Str "my",Space,Str "ruins"]]
-                                                             ,Div ("wasteland-content.xhtml#ln432",[],[])
-                                                              [Plain [Str "Why",Space,Str "then",Space,Str "Ile",Space,Str "fit",Space,Str "you.",Space,Str "Hieronymo's",Space,Str "mad",Space,Str "againe.",Note [Para [Link ("",[],[]) [Str "432."] ("#wasteland-content.xhtml#ln432",""),Space,Str "V.",Space,Str "Kyd's",Space,Str "Spanish",Space,Str "Tragedy."]]]
-                                                              ,Div ("",[],[("lang","sa")])
-                                                               [Plain [Str "Datta.",Space,Str "Dayadhvam.",Space,Str "Damyata."]]
-                                                              ,Div ("wasteland-content.xhtml#ln434",["linegroup","indent"],[])
-                                                               [Plain [Span ("",[],[("lang","sa")]) [Str "Shantih",Space,Str "shantih",Space,Str "shantih",Note [Para [Link ("",[],[]) [Str "434."] ("#wasteland-content.xhtml#ln434",""),Space,Str "Shantih.",Space,Str "Repeated",Space,Str "as",Space,Str "here,",Space,Str "a",Space,Str "formal",Space,Str "ending",Space,Str "to",Space,Str "an",Space,Str "Upanishad.",Space,Str "'The",SoftBreak,Str "Peace",Space,Str "which",Space,Str "passeth",Space,Str "understanding'",Space,Str "is",Space,Str "a",Space,Str "feeble",Space,Str "translation",Space,Str "of",Space,Str "the",SoftBreak,Str "content",Space,Str "of",Space,Str "this",Space,Str "word."]]]]
-                                                               ,Div ("wasteland-content.xhtml#backmatter",["section"],[("type","backmatter")])
-                                                                [Div ("wasteland-content.xhtml#rearnotes",["section"],[("type","rearnotes")])
-                                                                 [Header 2 ("",[],[]) [Str "NOTES",Space,Str "ON",Space,Str "\"THE",Space,Str "WASTE",Space,Str "LAND\""]
-                                                                 ,Para [Str "Not",Space,Str "only",Space,Str "the",Space,Str "title,",Space,Str "but",Space,Str "the",Space,Str "plan",Space,Str "and",Space,Str "a",Space,Str "good",Space,Str "deal",Space,Str "of",Space,Str "the",Space,Str "incidental",Space,Str "symbolism",Space,Str "of",SoftBreak,Str "the",Space,Str "poem",Space,Str "were",Space,Str "suggested",Space,Str "by",Space,Str "Miss",Space,Str "Jessie",Space,Str "L.",Space,Str "Weston's",Space,Str "book",Space,Str "on",Space,Str "the",Space,Str "Grail",Space,Str "legend:",SoftBreak,Str "From",Space,Str "Ritual",Space,Str "to",Space,Str "Romance"]
-                                                                 ,Para [Str "Indeed,",Space,Str "so",Space,Str "deeply",Space,Str "am",Space,Str "I",Space,Str "indebted,",Space,Str "Miss",Space,Str "Weston's",Space,Str "book",Space,Str "will",Space,Str "elucidate",Space,Str "the",SoftBreak,Str "difficulties",Space,Str "of",Space,Str "the",Space,Str "poem",Space,Str "much",Space,Str "better",Space,Str "than",Space,Str "my",Space,Str "notes",Space,Str "can",Space,Str "do;",Space,Str "and",Space,Str "I",Space,Str "recommend",Space,Str "it",SoftBreak,Str "(apart",Space,Str "from",Space,Str "the",Space,Str "great",Space,Str "interest",Space,Str "of",Space,Str "the",Space,Str "book",Space,Str "itself)",Space,Str "to",Space,Str "any",Space,Str "who",Space,Str "think",Space,Str "such",SoftBreak,Str "elucidation",Space,Str "of",Space,Str "the",Space,Str "poem",Space,Str "worth",Space,Str "the",Space,Str "trouble.",Space,Str "To",Space,Str "another",Space,Str "work",Space,Str "of",Space,Str "anthropology",Space,Str "I",Space,Str "am",SoftBreak,Str "indebted",Space,Str "in",Space,Str "general,",Space,Str "one",Space,Str "which",Space,Str "has",Space,Str "influenced",Space,Str "our",Space,Str "generation",Space,Str "profoundly;",Space,Str "I",Space,Str "mean",SoftBreak,Str "The",Space,Str "Golden",Space,Str "Bough;",Space,Str "I",Space,Str "have",Space,Str "used",Space,Str "especially",Space,Str "the",Space,Str "two",Space,Str "volumes",Space,Str "Adonis,",Space,Str "Attis,",Space,Str "Osiris.",SoftBreak,Str "Anyone",Space,Str "who",Space,Str "is",Space,Str "acquainted",Space,Str "with",Space,Str "these",Space,Str "works",Space,Str "will",Space,Str "immediately",Space,Str "recognise",Space,Str "in",Space,Str "the",Space,Str "poem",SoftBreak,Str "certain",Space,Str "references",Space,Str "to",Space,Str "vegetation",Space,Str "ceremonies."]
-                                                                 ,Div ("",["section"],[])
-                                                                  [Header 3 ("",[],[]) [Str "I.",Space,Str "THE",Space,Str "BURIAL",Space,Str "OF",Space,Str "THE",Space,Str "DEAD"]]
-                                                                 ,Div ("",["section"],[])
-                                                                  [Header 3 ("",[],[]) [Str "II.",Space,Str "A",Space,Str "GAME",Space,Str "OF",Space,Str "CHESS"]]
-                                                                 ,Div ("",["section"],[])
-                                                                  [Header 3 ("",[],[]) [Str "III.",Space,Str "THE",Space,Str "FIRE",Space,Str "SERMON"]]
-                                                                 ,Div ("",["section"],[])
-                                                                  [Header 3 ("",[],[]) [Str "V.",Space,Str "WHAT",Space,Str "THE",Space,Str "THUNDER",Space,Str "SAID"]
-                                                                  ,Para [Str "In",Space,Str "the",Space,Str "first",Space,Str "part",Space,Str "of",Space,Str "Part",Space,Str "V",Space,Str "three",Space,Str "themes",Space,Str "are",Space,Str "employed:",Space,Str "the",Space,Str "journey",Space,Str "to",Space,Str "Emmaus,",SoftBreak,Str "the",Space,Str "approach",Space,Str "to",Space,Str "the",Space,Str "Chapel",Space,Str "Perilous",Space,Str "(see",Space,Str "Miss",Space,Str "Weston's",Space,Str "book)",Space,Str "and",Space,Str "the",Space,Str "present",SoftBreak,Str "decay",Space,Str "of",Space,Str "eastern",Space,Str "Europe."]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]
+Pandoc
+  Meta
+    { unMeta =
+        fromList
+          [ ( "author" , MetaInlines [ Str "T.S. Eliot" ] )
+          , ( "date" , MetaInlines [ Str "2011-09-01" ] )
+          , ( "identifier"
+            , MetaInlines
+                [ Str "code.google.com.epub-samples.wasteland-basic" ]
+            )
+          , ( "language" , MetaInlines [ Str "en-US" ] )
+          , ( "rights"
+            , MetaInlines
+                [ Str
+                    "This work is shared with the public using the Attribution-ShareAlike 3.0 Unported (CC BY-SA 3.0) license."
+                ]
+            )
+          , ( "title" , MetaInlines [ Str "The Waste Land" ] )
+          ]
+    }
+  [ Para
+      [ Image ( "" , [] , [] ) [] ( "wasteland-cover.jpg" , "" ) ]
+  , Para [ Span ( "wasteland-content.xhtml" , [] , [] ) [] ]
+  , Div
+      ( "wasteland-content.xhtml_frontmatter"
+      , [ "section" , "frontmatter" ]
+      , []
+      )
+      []
+  , Div
+      ( "wasteland-content.xhtml_bodymatter"
+      , [ "section" , "bodymatter" ]
+      , []
+      )
+      [ Div
+          ( "wasteland-content.xhtml_ch1" , [ "section" ] , [] )
+          [ Header
+              2
+              ( "" , [] , [] )
+              [ Str "I."
+              , Space
+              , Str "THE"
+              , Space
+              , Str "BURIAL"
+              , Space
+              , Str "OF"
+              , Space
+              , Str "THE"
+              , Space
+              , Str "DEAD"
+              ]
+          , Div
+              ( "" , [ "linegroup" ] , [] )
+              [ Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "April"
+                      , Space
+                      , Str "is"
+                      , Space
+                      , Str "the"
+                      , Space
+                      , Str "cruellest"
+                      , Space
+                      , Str "month,"
+                      , Space
+                      , Str "breeding"
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "Lilacs"
+                      , Space
+                      , Str "out"
+                      , Space
+                      , Str "of"
+                      , Space
+                      , Str "the"
+                      , Space
+                      , Str "dead"
+                      , Space
+                      , Str "land,"
+                      , Space
+                      , Str "mixing"
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "Memory"
+                      , Space
+                      , Str "and"
+                      , Space
+                      , Str "desire,"
+                      , Space
+                      , Str "stirring"
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "Dull"
+                      , Space
+                      , Str "roots"
+                      , Space
+                      , Str "with"
+                      , Space
+                      , Str "spring"
+                      , Space
+                      , Str "rain."
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "Winter"
+                      , Space
+                      , Str "kept"
+                      , Space
+                      , Str "us"
+                      , Space
+                      , Str "warm,"
+                      , Space
+                      , Str "covering"
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "Earth"
+                      , Space
+                      , Str "in"
+                      , Space
+                      , Str "forgetful"
+                      , Space
+                      , Str "snow,"
+                      , Space
+                      , Str "feeding"
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "A"
+                      , Space
+                      , Str "little"
+                      , Space
+                      , Str "life"
+                      , Space
+                      , Str "with"
+                      , Space
+                      , Str "dried"
+                      , Space
+                      , Str "tubers."
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "Summer"
+                      , Space
+                      , Str "surprised"
+                      , Space
+                      , Str "us,"
+                      , Space
+                      , Str "coming"
+                      , Space
+                      , Str "over"
+                      , Space
+                      , Str "the"
+                      , Space
+                      , Str "Starnbergersee"
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "With"
+                      , Space
+                      , Str "a"
+                      , Space
+                      , Str "shower"
+                      , Space
+                      , Str "of"
+                      , Space
+                      , Str "rain;"
+                      , Space
+                      , Str "we"
+                      , Space
+                      , Str "stopped"
+                      , Space
+                      , Str "in"
+                      , Space
+                      , Str "the"
+                      , Space
+                      , Str "colonnade,"
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "And"
+                      , Space
+                      , Str "went"
+                      , Space
+                      , Str "on"
+                      , Space
+                      , Str "in"
+                      , Space
+                      , Str "sunlight,"
+                      , Space
+                      , Str "into"
+                      , Space
+                      , Str "the"
+                      , Space
+                      , Str "Hofgarten,"
+                      , Span ( "" , [ "lnum" ] , [] ) [ Str "10" ]
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "And"
+                      , Space
+                      , Str "drank"
+                      , Space
+                      , Str "coffee,"
+                      , Space
+                      , Str "and"
+                      , Space
+                      , Str "talked"
+                      , Space
+                      , Str "for"
+                      , Space
+                      , Str "an"
+                      , Space
+                      , Str "hour."
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [ ( "lang" , "de" ) ] )
+                  [ Plain
+                      [ Str "Bin"
+                      , Space
+                      , Str "gar"
+                      , Space
+                      , Str "keine"
+                      , Space
+                      , Str "Russin,"
+                      , Space
+                      , Str "stamm'"
+                      , Space
+                      , Str "aus"
+                      , Space
+                      , Str "Litauen,"
+                      , Space
+                      , Str "echt"
+                      , SoftBreak
+                      , Str "deutsch."
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "And"
+                      , Space
+                      , Str "when"
+                      , Space
+                      , Str "we"
+                      , Space
+                      , Str "were"
+                      , Space
+                      , Str "children,"
+                      , Space
+                      , Str "staying"
+                      , Space
+                      , Str "at"
+                      , Space
+                      , Str "the"
+                      , Space
+                      , Str "archduke's,"
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "My"
+                      , Space
+                      , Str "cousin's,"
+                      , Space
+                      , Str "he"
+                      , Space
+                      , Str "took"
+                      , Space
+                      , Str "me"
+                      , Space
+                      , Str "out"
+                      , Space
+                      , Str "on"
+                      , Space
+                      , Str "a"
+                      , Space
+                      , Str "sled,"
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "And"
+                      , Space
+                      , Str "I"
+                      , Space
+                      , Str "was"
+                      , Space
+                      , Str "frightened."
+                      , Space
+                      , Str "He"
+                      , Space
+                      , Str "said,"
+                      , Space
+                      , Str "Marie,"
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "Marie,"
+                      , Space
+                      , Str "hold"
+                      , Space
+                      , Str "on"
+                      , Space
+                      , Str "tight."
+                      , Space
+                      , Str "And"
+                      , Space
+                      , Str "down"
+                      , Space
+                      , Str "we"
+                      , Space
+                      , Str "went."
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "In"
+                      , Space
+                      , Str "the"
+                      , Space
+                      , Str "mountains,"
+                      , Space
+                      , Str "there"
+                      , Space
+                      , Str "you"
+                      , Space
+                      , Str "feel"
+                      , Space
+                      , Str "free."
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "I"
+                      , Space
+                      , Str "read,"
+                      , Space
+                      , Str "much"
+                      , Space
+                      , Str "of"
+                      , Space
+                      , Str "the"
+                      , Space
+                      , Str "night,"
+                      , Space
+                      , Str "and"
+                      , Space
+                      , Str "go"
+                      , Space
+                      , Str "south"
+                      , Space
+                      , Str "in"
+                      , Space
+                      , Str "the"
+                      , Space
+                      , Str "winter."
+                      ]
+                  ]
+              ]
+          , Div
+              ( "" , [ "linegroup" ] , [] )
+              [ Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "What"
+                      , Space
+                      , Str "are"
+                      , Space
+                      , Str "the"
+                      , Space
+                      , Str "roots"
+                      , Space
+                      , Str "that"
+                      , Space
+                      , Str "clutch,"
+                      , Space
+                      , Str "what"
+                      , Space
+                      , Str "branches"
+                      , Space
+                      , Str "grow"
+                      ]
+                  ]
+              , Div
+                  ( "wasteland-content.xhtml_ln20" , [] , [] )
+                  [ Plain
+                      [ Str "Out"
+                      , Space
+                      , Str "of"
+                      , Space
+                      , Str "this"
+                      , Space
+                      , Str "stony"
+                      , Space
+                      , Str "rubbish?"
+                      , Space
+                      , Str "Son"
+                      , Space
+                      , Str "of"
+                      , Space
+                      , Str "man,"
+                      , Note
+                          [ Para
+                              [ Link
+                                  ( "" , [] , [] )
+                                  [ Str "Line" , Space , Str "20." ]
+                                  ( "#wasteland-content.xhtml_ln20"
+                                  , ""
+                                  )
+                              , Space
+                              , Str "Cf."
+                              , Space
+                              , Str "Ezekiel"
+                              , Space
+                              , Str "2:1."
+                              ]
+                          ]
+                      , Span ( "" , [ "lnum" ] , [] ) [ Str "20" ]
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "You"
+                      , Space
+                      , Str "cannot"
+                      , Space
+                      , Str "say,"
+                      , Space
+                      , Str "or"
+                      , Space
+                      , Str "guess,"
+                      , Space
+                      , Str "for"
+                      , Space
+                      , Str "you"
+                      , Space
+                      , Str "know"
+                      , Space
+                      , Str "only"
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "A"
+                      , Space
+                      , Str "heap"
+                      , Space
+                      , Str "of"
+                      , Space
+                      , Str "broken"
+                      , Space
+                      , Str "images,"
+                      , Space
+                      , Str "where"
+                      , Space
+                      , Str "the"
+                      , Space
+                      , Str "sun"
+                      , Space
+                      , Str "beats,"
+                      ]
+                  ]
+              , Div
+                  ( "wasteland-content.xhtml_ln23" , [] , [] )
+                  [ Plain
+                      [ Str "And"
+                      , Space
+                      , Str "the"
+                      , Space
+                      , Str "dead"
+                      , Space
+                      , Str "tree"
+                      , Space
+                      , Str "gives"
+                      , Space
+                      , Str "no"
+                      , Space
+                      , Str "shelter,"
+                      , Space
+                      , Str "the"
+                      , Space
+                      , Str "cricket"
+                      , Space
+                      , Str "no"
+                      , Space
+                      , Str "relief,"
+                      , Note
+                          [ Para
+                              [ Link
+                                  ( "" , [] , [] )
+                                  [ Str "23." ]
+                                  ( "#wasteland-content.xhtml_ln23"
+                                  , ""
+                                  )
+                              , Space
+                              , Str "Cf."
+                              , Space
+                              , Str "Ecclesiastes"
+                              , Space
+                              , Str "12:5."
+                              ]
+                          ]
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "And"
+                      , Space
+                      , Str "the"
+                      , Space
+                      , Str "dry"
+                      , Space
+                      , Str "stone"
+                      , Space
+                      , Str "no"
+                      , Space
+                      , Str "sound"
+                      , Space
+                      , Str "of"
+                      , Space
+                      , Str "water."
+                      , Space
+                      , Str "Only"
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "There"
+                      , Space
+                      , Str "is"
+                      , Space
+                      , Str "shadow"
+                      , Space
+                      , Str "under"
+                      , Space
+                      , Str "this"
+                      , Space
+                      , Str "red"
+                      , Space
+                      , Str "rock,"
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "(Come"
+                      , Space
+                      , Str "in"
+                      , Space
+                      , Str "under"
+                      , Space
+                      , Str "the"
+                      , Space
+                      , Str "shadow"
+                      , Space
+                      , Str "of"
+                      , Space
+                      , Str "this"
+                      , Space
+                      , Str "red"
+                      , Space
+                      , Str "rock),"
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "And"
+                      , Space
+                      , Str "I"
+                      , Space
+                      , Str "will"
+                      , Space
+                      , Str "show"
+                      , Space
+                      , Str "you"
+                      , Space
+                      , Str "something"
+                      , Space
+                      , Str "different"
+                      , Space
+                      , Str "from"
+                      , Space
+                      , Str "either"
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "Your"
+                      , Space
+                      , Str "shadow"
+                      , Space
+                      , Str "at"
+                      , Space
+                      , Str "morning"
+                      , Space
+                      , Str "striding"
+                      , Space
+                      , Str "behind"
+                      , Space
+                      , Str "you"
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "Or"
+                      , Space
+                      , Str "your"
+                      , Space
+                      , Str "shadow"
+                      , Space
+                      , Str "at"
+                      , Space
+                      , Str "evening"
+                      , Space
+                      , Str "rising"
+                      , Space
+                      , Str "to"
+                      , Space
+                      , Str "meet"
+                      , Space
+                      , Str "you;"
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "I"
+                      , Space
+                      , Str "will"
+                      , Space
+                      , Str "show"
+                      , Space
+                      , Str "you"
+                      , Space
+                      , Str "fear"
+                      , Space
+                      , Str "in"
+                      , Space
+                      , Str "a"
+                      , Space
+                      , Str "handful"
+                      , Space
+                      , Str "of"
+                      , Space
+                      , Str "dust."
+                      , Span ( "" , [ "lnum" ] , [] ) [ Str "30" ]
+                      ]
+                  ]
+              , BlockQuote
+                  [ Div
+                      ( "" , [] , [] )
+                      [ Div
+                          ( "wasteland-content.xhtml_ln31" , [] , [] )
+                          [ Plain
+                              [ Str "Frisch"
+                              , Space
+                              , Str "weht"
+                              , Space
+                              , Str "der"
+                              , Space
+                              , Str "Wind"
+                              , Note
+                                  [ Para
+                                      [ Link
+                                          ( "" , [] , [] )
+                                          [ Str "31." ]
+                                          ( "#wasteland-content.xhtml_ln31"
+                                          , ""
+                                          )
+                                      , Space
+                                      , Str "V."
+                                      , Space
+                                      , Str "Tristan"
+                                      , Space
+                                      , Str "und"
+                                      , Space
+                                      , Str "Isolde,"
+                                      , Space
+                                      , Str "i,"
+                                      , Space
+                                      , Str "verses"
+                                      , Space
+                                      , Str "5-8."
+                                      ]
+                                  ]
+                              ]
+                          ]
+                      , Div
+                          ( "" , [] , [] )
+                          [ Plain
+                              [ Str "Der"
+                              , Space
+                              , Str "Heimat"
+                              , Space
+                              , Str "zu"
+                              ]
+                          ]
+                      , Div
+                          ( "" , [] , [] )
+                          [ Plain
+                              [ Str "Mein"
+                              , Space
+                              , Str "Irisch"
+                              , Space
+                              , Str "Kind,"
+                              ]
+                          ]
+                      , Div
+                          ( "" , [] , [] )
+                          [ Plain
+                              [ Str "Wo"
+                              , Space
+                              , Str "weilest"
+                              , Space
+                              , Str "du?"
+                              ]
+                          ]
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "\"You"
+                      , Space
+                      , Str "gave"
+                      , Space
+                      , Str "me"
+                      , Space
+                      , Str "hyacinths"
+                      , Space
+                      , Str "first"
+                      , Space
+                      , Str "a"
+                      , Space
+                      , Str "year"
+                      , Space
+                      , Str "ago;"
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "\"They"
+                      , Space
+                      , Str "called"
+                      , Space
+                      , Str "me"
+                      , Space
+                      , Str "the"
+                      , Space
+                      , Str "hyacinth"
+                      , Space
+                      , Str "girl.\""
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "\8213Yet"
+                      , Space
+                      , Str "when"
+                      , Space
+                      , Str "we"
+                      , Space
+                      , Str "came"
+                      , Space
+                      , Str "back,"
+                      , Space
+                      , Str "late,"
+                      , Space
+                      , Str "from"
+                      , Space
+                      , Str "the"
+                      , Space
+                      , Str "Hyacinth"
+                      , SoftBreak
+                      , Str "garden,"
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "Your"
+                      , Space
+                      , Str "arms"
+                      , Space
+                      , Str "full,"
+                      , Space
+                      , Str "and"
+                      , Space
+                      , Str "your"
+                      , Space
+                      , Str "hair"
+                      , Space
+                      , Str "wet,"
+                      , Space
+                      , Str "I"
+                      , Space
+                      , Str "could"
+                      , Space
+                      , Str "not"
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "Speak,"
+                      , Space
+                      , Str "and"
+                      , Space
+                      , Str "my"
+                      , Space
+                      , Str "eyes"
+                      , Space
+                      , Str "failed,"
+                      , Space
+                      , Str "I"
+                      , Space
+                      , Str "was"
+                      , Space
+                      , Str "neither"
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "Living"
+                      , Space
+                      , Str "nor"
+                      , Space
+                      , Str "dead,"
+                      , Space
+                      , Str "and"
+                      , Space
+                      , Str "I"
+                      , Space
+                      , Str "knew"
+                      , Space
+                      , Str "nothing,"
+                      , Span ( "" , [ "lnum" ] , [] ) [ Str "40" ]
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "Looking"
+                      , Space
+                      , Str "into"
+                      , Space
+                      , Str "the"
+                      , Space
+                      , Str "heart"
+                      , Space
+                      , Str "of"
+                      , Space
+                      , Str "light,"
+                      , Space
+                      , Str "the"
+                      , Space
+                      , Str "silence."
+                      ]
+                  ]
+              , Div
+                  ( "wasteland-content.xhtml_ln42"
+                  , []
+                  , [ ( "lang" , "de" ) ]
+                  )
+                  [ Plain
+                      [ Emph
+                          [ Str "Od'"
+                          , Space
+                          , Str "und"
+                          , Space
+                          , Str "leer"
+                          , Space
+                          , Str "das"
+                          , Space
+                          , Str "Meer"
+                          ]
+                      , Str "."
+                      , Note
+                          [ Para
+                              [ Link
+                                  ( "" , [] , [] )
+                                  [ Str "42." ]
+                                  ( "#wasteland-content.xhtml_ln42"
+                                  , ""
+                                  )
+                              , Space
+                              , Str "Id."
+                              , Space
+                              , Str "iii,"
+                              , Space
+                              , Str "verse"
+                              , Space
+                              , Str "24."
+                              ]
+                          ]
+                      ]
+                  ]
+              ]
+          , Div
+              ( "" , [ "linegroup" ] , [] )
+              [ Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "Madame"
+                      , Space
+                      , Str "Sosostris,"
+                      , Space
+                      , Str "famous"
+                      , Space
+                      , Str "clairvoyante,"
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "Had"
+                      , Space
+                      , Str "a"
+                      , Space
+                      , Str "bad"
+                      , Space
+                      , Str "cold,"
+                      , Space
+                      , Str "nevertheless"
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "Is"
+                      , Space
+                      , Str "known"
+                      , Space
+                      , Str "to"
+                      , Space
+                      , Str "be"
+                      , Space
+                      , Str "the"
+                      , Space
+                      , Str "wisest"
+                      , Space
+                      , Str "woman"
+                      , Space
+                      , Str "in"
+                      , Space
+                      , Str "Europe,"
+                      ]
+                  ]
+              , Div
+                  ( "wasteland-content.xhtml_ln46" , [] , [] )
+                  [ Plain
+                      [ Str "With"
+                      , Space
+                      , Str "a"
+                      , Space
+                      , Str "wicked"
+                      , Space
+                      , Str "pack"
+                      , Space
+                      , Str "of"
+                      , Space
+                      , Str "cards."
+                      , Space
+                      , Str "Here,"
+                      , Space
+                      , Str "said"
+                      , Space
+                      , Str "she,"
+                      , Note
+                          [ Para
+                              [ Link
+                                  ( "" , [] , [] )
+                                  [ Str "46." ]
+                                  ( "#wasteland-content.xhtml_ln46"
+                                  , ""
+                                  )
+                              , Space
+                              , Str "I"
+                              , Space
+                              , Str "am"
+                              , Space
+                              , Str "not"
+                              , Space
+                              , Str "familiar"
+                              , Space
+                              , Str "with"
+                              , Space
+                              , Str "the"
+                              , Space
+                              , Str "exact"
+                              , Space
+                              , Str "constitution"
+                              , Space
+                              , Str "of"
+                              , Space
+                              , Str "the"
+                              , Space
+                              , Str "Tarot"
+                              , Space
+                              , Str "pack"
+                              , Space
+                              , Str "of"
+                              , SoftBreak
+                              , Str "cards,"
+                              , Space
+                              , Str "from"
+                              , Space
+                              , Str "which"
+                              , Space
+                              , Str "I"
+                              , Space
+                              , Str "have"
+                              , Space
+                              , Str "obviously"
+                              , Space
+                              , Str "departed"
+                              , Space
+                              , Str "to"
+                              , Space
+                              , Str "suit"
+                              , Space
+                              , Str "my"
+                              , Space
+                              , Str "own"
+                              , Space
+                              , Str "convenience."
+                              , SoftBreak
+                              , Str "The"
+                              , Space
+                              , Str "Hanged"
+                              , Space
+                              , Str "Man,"
+                              , Space
+                              , Str "a"
+                              , Space
+                              , Str "member"
+                              , Space
+                              , Str "of"
+                              , Space
+                              , Str "the"
+                              , Space
+                              , Str "traditional"
+                              , Space
+                              , Str "pack,"
+                              , Space
+                              , Str "fits"
+                              , Space
+                              , Str "my"
+                              , Space
+                              , Str "purpose"
+                              , Space
+                              , Str "in"
+                              , Space
+                              , Str "two"
+                              , SoftBreak
+                              , Str "ways:"
+                              , Space
+                              , Str "because"
+                              , Space
+                              , Str "he"
+                              , Space
+                              , Str "is"
+                              , Space
+                              , Str "associated"
+                              , Space
+                              , Str "in"
+                              , Space
+                              , Str "my"
+                              , Space
+                              , Str "mind"
+                              , Space
+                              , Str "with"
+                              , Space
+                              , Str "the"
+                              , Space
+                              , Str "Hanged"
+                              , Space
+                              , Str "God"
+                              , Space
+                              , Str "of"
+                              , Space
+                              , Str "Frazer,"
+                              , SoftBreak
+                              , Str "and"
+                              , Space
+                              , Str "because"
+                              , Space
+                              , Str "I"
+                              , Space
+                              , Str "associate"
+                              , Space
+                              , Str "him"
+                              , Space
+                              , Str "with"
+                              , Space
+                              , Str "the"
+                              , Space
+                              , Str "hooded"
+                              , Space
+                              , Str "figure"
+                              , Space
+                              , Str "in"
+                              , Space
+                              , Str "the"
+                              , Space
+                              , Str "passage"
+                              , Space
+                              , Str "of"
+                              , Space
+                              , Str "the"
+                              , SoftBreak
+                              , Str "disciples"
+                              , Space
+                              , Str "to"
+                              , Space
+                              , Str "Emmaus"
+                              , Space
+                              , Str "in"
+                              , Space
+                              , Str "Part"
+                              , Space
+                              , Str "V."
+                              , Space
+                              , Str "The"
+                              , Space
+                              , Str "Phoenician"
+                              , Space
+                              , Str "Sailor"
+                              , Space
+                              , Str "and"
+                              , Space
+                              , Str "the"
+                              , Space
+                              , Str "Merchant"
+                              , SoftBreak
+                              , Str "appear"
+                              , Space
+                              , Str "later;"
+                              , Space
+                              , Str "also"
+                              , Space
+                              , Str "the"
+                              , Space
+                              , Str "\"crowds"
+                              , Space
+                              , Str "of"
+                              , Space
+                              , Str "people,\""
+                              , Space
+                              , Str "and"
+                              , Space
+                              , Str "Death"
+                              , Space
+                              , Str "by"
+                              , Space
+                              , Str "Water"
+                              , Space
+                              , Str "is"
+                              , SoftBreak
+                              , Str "executed"
+                              , Space
+                              , Str "in"
+                              , Space
+                              , Str "Part"
+                              , Space
+                              , Str "IV."
+                              , Space
+                              , Str "The"
+                              , Space
+                              , Str "Man"
+                              , Space
+                              , Str "with"
+                              , Space
+                              , Str "Three"
+                              , Space
+                              , Str "Staves"
+                              , Space
+                              , Str "(an"
+                              , Space
+                              , Str "authentic"
+                              , Space
+                              , Str "member"
+                              , Space
+                              , Str "of"
+                              , SoftBreak
+                              , Str "the"
+                              , Space
+                              , Str "Tarot"
+                              , Space
+                              , Str "pack)"
+                              , Space
+                              , Str "I"
+                              , Space
+                              , Str "associate,"
+                              , Space
+                              , Str "quite"
+                              , Space
+                              , Str "arbitrarily,"
+                              , Space
+                              , Str "with"
+                              , Space
+                              , Str "the"
+                              , Space
+                              , Str "Fisher"
+                              , Space
+                              , Str "King"
+                              , SoftBreak
+                              , Str "himself."
+                              ]
+                          ]
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "Is"
+                      , Space
+                      , Str "your"
+                      , Space
+                      , Str "card,"
+                      , Space
+                      , Str "the"
+                      , Space
+                      , Str "drowned"
+                      , Space
+                      , Str "Phoenician"
+                      , Space
+                      , Str "Sailor,"
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "(Those"
+                      , Space
+                      , Str "are"
+                      , Space
+                      , Str "pearls"
+                      , Space
+                      , Str "that"
+                      , Space
+                      , Str "were"
+                      , Space
+                      , Str "his"
+                      , Space
+                      , Str "eyes."
+                      , Space
+                      , Str "Look!)"
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "Here"
+                      , Space
+                      , Str "is"
+                      , Space
+                      , Str "Belladonna,"
+                      , Space
+                      , Str "the"
+                      , Space
+                      , Str "Lady"
+                      , Space
+                      , Str "of"
+                      , Space
+                      , Str "the"
+                      , Space
+                      , Str "Rocks,"
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "The"
+                      , Space
+                      , Str "lady"
+                      , Space
+                      , Str "of"
+                      , Space
+                      , Str "situations."
+                      , Span ( "" , [ "lnum" ] , [] ) [ Str "50" ]
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "Here"
+                      , Space
+                      , Str "is"
+                      , Space
+                      , Str "the"
+                      , Space
+                      , Str "man"
+                      , Space
+                      , Str "with"
+                      , Space
+                      , Str "three"
+                      , Space
+                      , Str "staves,"
+                      , Space
+                      , Str "and"
+                      , Space
+                      , Str "here"
+                      , Space
+                      , Str "the"
+                      , Space
+                      , Str "Wheel,"
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "And"
+                      , Space
+                      , Str "here"
+                      , Space
+                      , Str "is"
+                      , Space
+                      , Str "the"
+                      , Space
+                      , Str "one-eyed"
+                      , Space
+                      , Str "merchant,"
+                      , Space
+                      , Str "and"
+                      , Space
+                      , Str "this"
+                      , Space
+                      , Str "card,"
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "Which"
+                      , Space
+                      , Str "is"
+                      , Space
+                      , Str "blank,"
+                      , Space
+                      , Str "is"
+                      , Space
+                      , Str "something"
+                      , Space
+                      , Str "he"
+                      , Space
+                      , Str "carries"
+                      , Space
+                      , Str "on"
+                      , Space
+                      , Str "his"
+                      , Space
+                      , Str "back,"
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "Which"
+                      , Space
+                      , Str "I"
+                      , Space
+                      , Str "am"
+                      , Space
+                      , Str "forbidden"
+                      , Space
+                      , Str "to"
+                      , Space
+                      , Str "see."
+                      , Space
+                      , Str "I"
+                      , Space
+                      , Str "do"
+                      , Space
+                      , Str "not"
+                      , Space
+                      , Str "find"
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "The"
+                      , Space
+                      , Str "Hanged"
+                      , Space
+                      , Str "Man."
+                      , Space
+                      , Str "Fear"
+                      , Space
+                      , Str "death"
+                      , Space
+                      , Str "by"
+                      , Space
+                      , Str "water."
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "I"
+                      , Space
+                      , Str "see"
+                      , Space
+                      , Str "crowds"
+                      , Space
+                      , Str "of"
+                      , Space
+                      , Str "people,"
+                      , Space
+                      , Str "walking"
+                      , Space
+                      , Str "round"
+                      , Space
+                      , Str "in"
+                      , Space
+                      , Str "a"
+                      , Space
+                      , Str "ring."
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "Thank"
+                      , Space
+                      , Str "you."
+                      , Space
+                      , Str "If"
+                      , Space
+                      , Str "you"
+                      , Space
+                      , Str "see"
+                      , Space
+                      , Str "dear"
+                      , Space
+                      , Str "Mrs."
+                      , Space
+                      , Str "Equitone,"
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "Tell"
+                      , Space
+                      , Str "her"
+                      , Space
+                      , Str "I"
+                      , Space
+                      , Str "bring"
+                      , Space
+                      , Str "the"
+                      , Space
+                      , Str "horoscope"
+                      , Space
+                      , Str "myself:"
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "One"
+                      , Space
+                      , Str "must"
+                      , Space
+                      , Str "be"
+                      , Space
+                      , Str "so"
+                      , Space
+                      , Str "careful"
+                      , Space
+                      , Str "these"
+                      , Space
+                      , Str "days."
+                      ]
+                  ]
+              ]
+          , Div
+              ( "" , [ "linegroup" ] , [] )
+              [ Div
+                  ( "wasteland-content.xhtml_ln60" , [] , [] )
+                  [ Plain
+                      [ Str "Unreal"
+                      , Space
+                      , Str "City,"
+                      , Note
+                          [ Para
+                              [ Link
+                                  ( "" , [] , [] )
+                                  [ Str "60." ]
+                                  ( "#wasteland-content.xhtml_ln60"
+                                  , ""
+                                  )
+                              , Space
+                              , Str "Cf."
+                              , Space
+                              , Str "Baudelaire:"
+                              ]
+                          , BlockQuote
+                              [ Para
+                                  [ Str "\"Fourmillante"
+                                  , Space
+                                  , Str "cite;,"
+                                  , Space
+                                  , Str "cite;"
+                                  , Space
+                                  , Str "pleine"
+                                  , Space
+                                  , Str "de"
+                                  , Space
+                                  , Str "reves,"
+                                  , LineBreak
+                                  , Str "Ou"
+                                  , Space
+                                  , Str "le"
+                                  , Space
+                                  , Str "spectre"
+                                  , Space
+                                  , Str "en"
+                                  , SoftBreak
+                                  , Str "plein"
+                                  , Space
+                                  , Str "jour"
+                                  , Space
+                                  , Str "raccroche"
+                                  , Space
+                                  , Str "le"
+                                  , Space
+                                  , Str "passant.\""
+                                  ]
+                              ]
+                          ]
+                      , Span ( "" , [ "lnum" ] , [] ) [ Str "60" ]
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "Under"
+                      , Space
+                      , Str "the"
+                      , Space
+                      , Str "brown"
+                      , Space
+                      , Str "fog"
+                      , Space
+                      , Str "of"
+                      , Space
+                      , Str "a"
+                      , Space
+                      , Str "winter"
+                      , Space
+                      , Str "dawn,"
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "A"
+                      , Space
+                      , Str "crowd"
+                      , Space
+                      , Str "flowed"
+                      , Space
+                      , Str "over"
+                      , Space
+                      , Str "London"
+                      , Space
+                      , Str "Bridge,"
+                      , Space
+                      , Str "so"
+                      , Space
+                      , Str "many,"
+                      ]
+                  ]
+              , Div
+                  ( "wasteland-content.xhtml_ln63" , [] , [] )
+                  [ Plain
+                      [ Str "I"
+                      , Space
+                      , Str "had"
+                      , Space
+                      , Str "not"
+                      , Space
+                      , Str "thought"
+                      , Space
+                      , Str "death"
+                      , Space
+                      , Str "had"
+                      , Space
+                      , Str "undone"
+                      , Space
+                      , Str "so"
+                      , Space
+                      , Str "many."
+                      , Note
+                          [ Para
+                              [ Link
+                                  ( "" , [] , [] )
+                                  [ Str "63." ]
+                                  ( "#wasteland-content.xhtml_ln63"
+                                  , ""
+                                  )
+                              , Space
+                              , Str "Cf."
+                              , Space
+                              , Str "Inferno,"
+                              , Space
+                              , Str "iii."
+                              , Space
+                              , Str "55-7."
+                              ]
+                          , BlockQuote
+                              [ Para
+                                  [ Str "\"si"
+                                  , Space
+                                  , Str "lunga"
+                                  , Space
+                                  , Str "tratta"
+                                  , LineBreak
+                                  , Str "di"
+                                  , Space
+                                  , Str "gente,"
+                                  , Space
+                                  , Str "ch'io"
+                                  , Space
+                                  , Str "non"
+                                  , Space
+                                  , Str "avrei"
+                                  , Space
+                                  , Str "mai"
+                                  , Space
+                                  , Str "creduto"
+                                  , LineBreak
+                                  , Str "che"
+                                  , SoftBreak
+                                  , Str "morte"
+                                  , Space
+                                  , Str "tanta"
+                                  , Space
+                                  , Str "n'avesse"
+                                  , Space
+                                  , Str "disfatta.\""
+                                  ]
+                              ]
+                          ]
+                      ]
+                  ]
+              , Div
+                  ( "wasteland-content.xhtml_ln64" , [] , [] )
+                  [ Plain
+                      [ Str "Sighs,"
+                      , Space
+                      , Str "short"
+                      , Space
+                      , Str "and"
+                      , Space
+                      , Str "infrequent,"
+                      , Space
+                      , Str "were"
+                      , Space
+                      , Str "exhaled,"
+                      , Note
+                          [ Para
+                              [ Link
+                                  ( "" , [] , [] )
+                                  [ Str "64." ]
+                                  ( "#wasteland-content.xhtml_ln64"
+                                  , ""
+                                  )
+                              , Space
+                              , Str "Cf."
+                              , Space
+                              , Str "Inferno,"
+                              , Space
+                              , Str "iv."
+                              , Space
+                              , Str "25-7:"
+                              ]
+                          , BlockQuote
+                              [ Para
+                                  [ Str "\"Quivi,"
+                                  , Space
+                                  , Str "secondo"
+                                  , Space
+                                  , Str "che"
+                                  , Space
+                                  , Str "per"
+                                  , Space
+                                  , Str "ascoltahre,"
+                                  , LineBreak
+                                  , Str "\"non"
+                                  , Space
+                                  , Str "avea"
+                                  , Space
+                                  , Str "pianto,"
+                                  , Space
+                                  , Str "ma'"
+                                  , Space
+                                  , Str "che"
+                                  , Space
+                                  , Str "di"
+                                  , SoftBreak
+                                  , Str "sospiri,"
+                                  , LineBreak
+                                  , Str "\"che"
+                                  , Space
+                                  , Str "l'aura"
+                                  , Space
+                                  , Str "eterna"
+                                  , Space
+                                  , Str "facevan"
+                                  , Space
+                                  , Str "tremare.\""
+                                  ]
+                              ]
+                          ]
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "And"
+                      , Space
+                      , Str "each"
+                      , Space
+                      , Str "man"
+                      , Space
+                      , Str "fixed"
+                      , Space
+                      , Str "his"
+                      , Space
+                      , Str "eyes"
+                      , Space
+                      , Str "before"
+                      , Space
+                      , Str "his"
+                      , Space
+                      , Str "feet."
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "Flowed"
+                      , Space
+                      , Str "up"
+                      , Space
+                      , Str "the"
+                      , Space
+                      , Str "hill"
+                      , Space
+                      , Str "and"
+                      , Space
+                      , Str "down"
+                      , Space
+                      , Str "King"
+                      , Space
+                      , Str "William"
+                      , Space
+                      , Str "Street,"
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "To"
+                      , Space
+                      , Str "where"
+                      , Space
+                      , Str "Saint"
+                      , Space
+                      , Str "Mary"
+                      , Space
+                      , Str "Woolnoth"
+                      , Space
+                      , Str "kept"
+                      , Space
+                      , Str "the"
+                      , Space
+                      , Str "hours"
+                      ]
+                  ]
+              , Div
+                  ( "wasteland-content.xhtml_ln68" , [] , [] )
+                  [ Plain
+                      [ Str "With"
+                      , Space
+                      , Str "a"
+                      , Space
+                      , Str "dead"
+                      , Space
+                      , Str "sound"
+                      , Space
+                      , Str "on"
+                      , Space
+                      , Str "the"
+                      , Space
+                      , Str "final"
+                      , Space
+                      , Str "stroke"
+                      , Space
+                      , Str "of"
+                      , Space
+                      , Str "nine."
+                      , Note
+                          [ Para
+                              [ Link
+                                  ( "" , [] , [] )
+                                  [ Str "68." ]
+                                  ( "#wasteland-content.xhtml_ln68"
+                                  , ""
+                                  )
+                              , Space
+                              , Str "A"
+                              , Space
+                              , Str "phenomenon"
+                              , Space
+                              , Str "which"
+                              , Space
+                              , Str "I"
+                              , Space
+                              , Str "have"
+                              , Space
+                              , Str "often"
+                              , Space
+                              , Str "noticed."
+                              ]
+                          ]
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "There"
+                      , Space
+                      , Str "I"
+                      , Space
+                      , Str "saw"
+                      , Space
+                      , Str "one"
+                      , Space
+                      , Str "I"
+                      , Space
+                      , Str "knew,"
+                      , Space
+                      , Str "and"
+                      , Space
+                      , Str "stopped"
+                      , Space
+                      , Str "him,"
+                      , Space
+                      , Str "crying"
+                      , SoftBreak
+                      , Str "\"Stetson!"
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "\"You"
+                      , Space
+                      , Str "who"
+                      , Space
+                      , Str "were"
+                      , Space
+                      , Str "with"
+                      , Space
+                      , Str "me"
+                      , Space
+                      , Str "in"
+                      , Space
+                      , Str "the"
+                      , Space
+                      , Str "ships"
+                      , Space
+                      , Str "at"
+                      , Space
+                      , Str "Mylae!"
+                      , Span ( "" , [ "lnum" ] , [] ) [ Str "70" ]
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "\"That"
+                      , Space
+                      , Str "corpse"
+                      , Space
+                      , Str "you"
+                      , Space
+                      , Str "planted"
+                      , Space
+                      , Str "last"
+                      , Space
+                      , Str "year"
+                      , Space
+                      , Str "in"
+                      , Space
+                      , Str "your"
+                      , Space
+                      , Str "garden,"
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "\"Has"
+                      , Space
+                      , Str "it"
+                      , Space
+                      , Str "begun"
+                      , Space
+                      , Str "to"
+                      , Space
+                      , Str "sprout?"
+                      , Space
+                      , Str "Will"
+                      , Space
+                      , Str "it"
+                      , Space
+                      , Str "bloom"
+                      , Space
+                      , Str "this"
+                      , Space
+                      , Str "year?"
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "\"Or"
+                      , Space
+                      , Str "has"
+                      , Space
+                      , Str "the"
+                      , Space
+                      , Str "sudden"
+                      , Space
+                      , Str "frost"
+                      , Space
+                      , Str "disturbed"
+                      , Space
+                      , Str "its"
+                      , Space
+                      , Str "bed?"
+                      ]
+                  ]
+              ]
+          , Div
+              ( "" , [ "linegroup" ] , [] )
+              [ Div
+                  ( "wasteland-content.xhtml_ln74" , [] , [] )
+                  [ Plain
+                      [ Str "\"Oh"
+                      , Space
+                      , Str "keep"
+                      , Space
+                      , Str "the"
+                      , Space
+                      , Str "Dog"
+                      , Space
+                      , Str "far"
+                      , Space
+                      , Str "hence,"
+                      , Space
+                      , Str "that's"
+                      , Space
+                      , Str "friend"
+                      , Space
+                      , Str "to"
+                      , Space
+                      , Str "men,"
+                      , Note
+                          [ Para
+                              [ Link
+                                  ( "" , [] , [] )
+                                  [ Str "74." ]
+                                  ( "#wasteland-content.xhtml_ln74"
+                                  , ""
+                                  )
+                              , Space
+                              , Str "Cf."
+                              , Space
+                              , Str "the"
+                              , Space
+                              , Str "Dirge"
+                              , Space
+                              , Str "in"
+                              , Space
+                              , Str "Webster's"
+                              , Space
+                              , Str "White"
+                              , Space
+                              , Str "Devil"
+                              , Space
+                              , Str "."
+                              ]
+                          ]
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "\"Or"
+                      , Space
+                      , Str "with"
+                      , Space
+                      , Str "his"
+                      , Space
+                      , Str "nails"
+                      , Space
+                      , Str "he'll"
+                      , Space
+                      , Str "dig"
+                      , Space
+                      , Str "it"
+                      , Space
+                      , Str "up"
+                      , Space
+                      , Str "again!"
+                      ]
+                  ]
+              , Div
+                  ( "wasteland-content.xhtml_ln76" , [] , [] )
+                  [ Plain
+                      [ Str "\"You!"
+                      , Space
+                      , Span
+                          ( "" , [] , [ ( "lang" , "fr" ) ] )
+                          [ Str "hypocrite"
+                          , Space
+                          , Str "lecteur!"
+                          , Space
+                          , Str "-"
+                          , Space
+                          , Str "mon"
+                          , Space
+                          , Str "semblable,"
+                          , Space
+                          , Str "-"
+                          , SoftBreak
+                          , Str "mon"
+                          , Space
+                          , Str "frere"
+                          ]
+                      , Space
+                      , Str "!\""
+                      , Note
+                          [ Para
+                              [ Link
+                                  ( "" , [] , [] )
+                                  [ Str "76." ]
+                                  ( "#wasteland-content.xhtml_ln76"
+                                  , ""
+                                  )
+                              , Space
+                              , Str "V."
+                              , Space
+                              , Str "Baudelaire,"
+                              , Space
+                              , Str "Preface"
+                              , Space
+                              , Str "to"
+                              , Space
+                              , Str "Fleurs"
+                              , Space
+                              , Str "du"
+                              , Space
+                              , Str "Mal."
+                              ]
+                          ]
+                      ]
+                  ]
+              ]
+          ]
+      , Div
+          ( "wasteland-content.xhtml_ch2" , [ "section" ] , [] )
+          [ Header
+              2
+              ( "" , [] , [] )
+              [ Str "II."
+              , Space
+              , Str "A"
+              , Space
+              , Str "GAME"
+              , Space
+              , Str "OF"
+              , Space
+              , Str "CHESS"
+              ]
+          , Div
+              ( "" , [ "linegroup" ] , [] )
+              [ Div
+                  ( "wasteland-content.xhtml_ln77" , [] , [] )
+                  [ Plain
+                      [ Str "The"
+                      , Space
+                      , Str "Chair"
+                      , Space
+                      , Str "she"
+                      , Space
+                      , Str "sat"
+                      , Space
+                      , Str "in,"
+                      , Space
+                      , Str "like"
+                      , Space
+                      , Str "a"
+                      , Space
+                      , Str "burnished"
+                      , Space
+                      , Str "throne,"
+                      , Note
+                          [ Para
+                              [ Link
+                                  ( "" , [] , [] )
+                                  [ Str "77." ]
+                                  ( "#wasteland-content.xhtml_ln77"
+                                  , ""
+                                  )
+                              , Space
+                              , Str "Cf."
+                              , Space
+                              , Str "Antony"
+                              , Space
+                              , Str "and"
+                              , Space
+                              , Str "Cleopatra,"
+                              , Space
+                              , Str "II."
+                              , Space
+                              , Str "ii.,"
+                              , Space
+                              , Str "l."
+                              , Space
+                              , Str "190."
+                              ]
+                          ]
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "Glowed"
+                      , Space
+                      , Str "on"
+                      , Space
+                      , Str "the"
+                      , Space
+                      , Str "marble,"
+                      , Space
+                      , Str "where"
+                      , Space
+                      , Str "the"
+                      , Space
+                      , Str "glass"
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "Held"
+                      , Space
+                      , Str "up"
+                      , Space
+                      , Str "by"
+                      , Space
+                      , Str "standards"
+                      , Space
+                      , Str "wrought"
+                      , Space
+                      , Str "with"
+                      , Space
+                      , Str "fruited"
+                      , Space
+                      , Str "vines"
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "From"
+                      , Space
+                      , Str "which"
+                      , Space
+                      , Str "a"
+                      , Space
+                      , Str "golden"
+                      , Space
+                      , Str "Cupidon"
+                      , Space
+                      , Str "peeped"
+                      , Space
+                      , Str "out"
+                      , Span ( "" , [ "lnum" ] , [] ) [ Str "80" ]
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "(Another"
+                      , Space
+                      , Str "hid"
+                      , Space
+                      , Str "his"
+                      , Space
+                      , Str "eyes"
+                      , Space
+                      , Str "behind"
+                      , Space
+                      , Str "his"
+                      , Space
+                      , Str "wing)"
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "Doubled"
+                      , Space
+                      , Str "the"
+                      , Space
+                      , Str "flames"
+                      , Space
+                      , Str "of"
+                      , Space
+                      , Str "sevenbranched"
+                      , Space
+                      , Str "candelabra"
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "Reflecting"
+                      , Space
+                      , Str "light"
+                      , Space
+                      , Str "upon"
+                      , Space
+                      , Str "the"
+                      , Space
+                      , Str "table"
+                      , Space
+                      , Str "as"
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "The"
+                      , Space
+                      , Str "glitter"
+                      , Space
+                      , Str "of"
+                      , Space
+                      , Str "her"
+                      , Space
+                      , Str "jewels"
+                      , Space
+                      , Str "rose"
+                      , Space
+                      , Str "to"
+                      , Space
+                      , Str "meet"
+                      , Space
+                      , Str "it,"
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "From"
+                      , Space
+                      , Str "satin"
+                      , Space
+                      , Str "cases"
+                      , Space
+                      , Str "poured"
+                      , Space
+                      , Str "in"
+                      , Space
+                      , Str "rich"
+                      , Space
+                      , Str "profusion;"
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "In"
+                      , Space
+                      , Str "vials"
+                      , Space
+                      , Str "of"
+                      , Space
+                      , Str "ivory"
+                      , Space
+                      , Str "and"
+                      , Space
+                      , Str "coloured"
+                      , Space
+                      , Str "glass"
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "Unstoppered,"
+                      , Space
+                      , Str "lurked"
+                      , Space
+                      , Str "her"
+                      , Space
+                      , Str "strange"
+                      , Space
+                      , Str "synthetic"
+                      , Space
+                      , Str "perfumes,"
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "Unguent,"
+                      , Space
+                      , Str "powdered,"
+                      , Space
+                      , Str "or"
+                      , Space
+                      , Str "liquid"
+                      , Space
+                      , Str "-"
+                      , Space
+                      , Str "troubled,"
+                      , Space
+                      , Str "confused"
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "And"
+                      , Space
+                      , Str "drowned"
+                      , Space
+                      , Str "the"
+                      , Space
+                      , Str "sense"
+                      , Space
+                      , Str "in"
+                      , Space
+                      , Str "odours;"
+                      , Space
+                      , Str "stirred"
+                      , Space
+                      , Str "by"
+                      , Space
+                      , Str "the"
+                      , Space
+                      , Str "air"
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "That"
+                      , Space
+                      , Str "freshened"
+                      , Space
+                      , Str "from"
+                      , Space
+                      , Str "the"
+                      , Space
+                      , Str "window,"
+                      , Space
+                      , Str "these"
+                      , Space
+                      , Str "ascended"
+                      , Span ( "" , [ "lnum" ] , [] ) [ Str "90" ]
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "In"
+                      , Space
+                      , Str "fattening"
+                      , Space
+                      , Str "the"
+                      , Space
+                      , Str "prolonged"
+                      , Space
+                      , Str "candle-flames,"
+                      ]
+                  ]
+              , Div
+                  ( "wasteland-content.xhtml_ln92" , [] , [] )
+                  [ Plain
+                      [ Str "Flung"
+                      , Space
+                      , Str "their"
+                      , Space
+                      , Str "smoke"
+                      , Space
+                      , Str "into"
+                      , Space
+                      , Str "the"
+                      , Space
+                      , Str "laquearia,"
+                      , Note
+                          [ Para
+                              [ Link
+                                  ( "" , [] , [] )
+                                  [ Str "92." ]
+                                  ( "#wasteland-content.xhtml_ln92"
+                                  , ""
+                                  )
+                              , Space
+                              , Str "Laquearia."
+                              , Space
+                              , Str "V."
+                              , Space
+                              , Str "Aeneid,"
+                              , Space
+                              , Str "I."
+                              , Space
+                              , Str "726:"
+                              ]
+                          , BlockQuote
+                              [ Para
+                                  [ Str "dependent"
+                                  , Space
+                                  , Str "lychni"
+                                  , Space
+                                  , Str "laquearibus"
+                                  , Space
+                                  , Str "aureis"
+                                  , Space
+                                  , Str "incensi,"
+                                  , Space
+                                  , Str "et"
+                                  , Space
+                                  , Str "noctem"
+                                  , SoftBreak
+                                  , Str "flammis"
+                                  , LineBreak
+                                  , Str "funalia"
+                                  , Space
+                                  , Str "vincunt."
+                                  ]
+                              ]
+                          ]
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "Stirring"
+                      , Space
+                      , Str "the"
+                      , Space
+                      , Str "pattern"
+                      , Space
+                      , Str "on"
+                      , Space
+                      , Str "the"
+                      , Space
+                      , Str "coffered"
+                      , Space
+                      , Str "ceiling."
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "Huge"
+                      , Space
+                      , Str "sea-wood"
+                      , Space
+                      , Str "fed"
+                      , Space
+                      , Str "with"
+                      , Space
+                      , Str "copper"
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "Burned"
+                      , Space
+                      , Str "green"
+                      , Space
+                      , Str "and"
+                      , Space
+                      , Str "orange,"
+                      , Space
+                      , Str "framed"
+                      , Space
+                      , Str "by"
+                      , Space
+                      , Str "the"
+                      , Space
+                      , Str "coloured"
+                      , Space
+                      , Str "stone,"
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "In"
+                      , Space
+                      , Str "which"
+                      , Space
+                      , Str "sad"
+                      , Space
+                      , Str "light"
+                      , Space
+                      , Str "a"
+                      , Space
+                      , Str "carved"
+                      , Space
+                      , Str "dolphin"
+                      , Space
+                      , Str "swam."
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "Above"
+                      , Space
+                      , Str "the"
+                      , Space
+                      , Str "antique"
+                      , Space
+                      , Str "mantel"
+                      , Space
+                      , Str "was"
+                      , Space
+                      , Str "displayed"
+                      ]
+                  ]
+              , Div
+                  ( "wasteland-content.xhtml_ln98" , [] , [] )
+                  [ Plain
+                      [ Str "As"
+                      , Space
+                      , Str "though"
+                      , Space
+                      , Str "a"
+                      , Space
+                      , Str "window"
+                      , Space
+                      , Str "gave"
+                      , Space
+                      , Str "upon"
+                      , Space
+                      , Str "the"
+                      , Space
+                      , Str "sylvan"
+                      , Space
+                      , Str "scene"
+                      , Note
+                          [ Para
+                              [ Link
+                                  ( "" , [] , [] )
+                                  [ Str "98." ]
+                                  ( "#wasteland-content.xhtml_ln98"
+                                  , ""
+                                  )
+                              , Space
+                              , Str "Sylvan"
+                              , Space
+                              , Str "scene."
+                              , Space
+                              , Str "V."
+                              , Space
+                              , Str "Milton,"
+                              , Space
+                              , Str "Paradise"
+                              , Space
+                              , Str "Lost,"
+                              , Space
+                              , Str "iv."
+                              , Space
+                              , Str "140."
+                              ]
+                          ]
+                      ]
+                  ]
+              , Div
+                  ( "wasteland-content.xhtml_ln99" , [] , [] )
+                  [ Plain
+                      [ Str "The"
+                      , Space
+                      , Str "change"
+                      , Space
+                      , Str "of"
+                      , Space
+                      , Str "Philomel,"
+                      , Space
+                      , Str "by"
+                      , Space
+                      , Str "the"
+                      , Space
+                      , Str "barbarous"
+                      , Space
+                      , Str "king"
+                      , Note
+                          [ Para
+                              [ Link
+                                  ( "" , [] , [] )
+                                  [ Str "99." ]
+                                  ( "#wasteland-content.xhtml_ln99"
+                                  , ""
+                                  )
+                              , Space
+                              , Str "V."
+                              , Space
+                              , Str "Ovid,"
+                              , Space
+                              , Str "Metamorphoses,"
+                              , Space
+                              , Str "vi,"
+                              , Space
+                              , Str "Philomela."
+                              ]
+                          ]
+                      ]
+                  ]
+              , Div
+                  ( "wasteland-content.xhtml_ln100" , [] , [] )
+                  [ Plain
+                      [ Str "So"
+                      , Space
+                      , Str "rudely"
+                      , Space
+                      , Str "forced;"
+                      , Space
+                      , Str "yet"
+                      , Space
+                      , Str "there"
+                      , Space
+                      , Str "the"
+                      , Space
+                      , Str "nightingale"
+                      , Note
+                          [ Para
+                              [ Link
+                                  ( "" , [] , [] )
+                                  [ Str "100." ]
+                                  ( "#wasteland-content.xhtml_ln100"
+                                  , ""
+                                  )
+                              , Space
+                              , Str "Cf."
+                              , Space
+                              , Str "Part"
+                              , Space
+                              , Str "III,"
+                              , Space
+                              , Str "l."
+                              , Space
+                              , Str "204."
+                              ]
+                          ]
+                      , SoftBreak
+                      , Span ( "" , [ "lnum" ] , [] ) [ Str "100" ]
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "Filled"
+                      , Space
+                      , Str "all"
+                      , Space
+                      , Str "the"
+                      , Space
+                      , Str "desert"
+                      , Space
+                      , Str "with"
+                      , Space
+                      , Str "inviolable"
+                      , Space
+                      , Str "voice"
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "And"
+                      , Space
+                      , Str "still"
+                      , Space
+                      , Str "she"
+                      , Space
+                      , Str "cried,"
+                      , Space
+                      , Str "and"
+                      , Space
+                      , Str "still"
+                      , Space
+                      , Str "the"
+                      , Space
+                      , Str "world"
+                      , Space
+                      , Str "pursues,"
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "\"Jug"
+                      , Space
+                      , Str "Jug\""
+                      , Space
+                      , Str "to"
+                      , Space
+                      , Str "dirty"
+                      , Space
+                      , Str "ears."
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "And"
+                      , Space
+                      , Str "other"
+                      , Space
+                      , Str "withered"
+                      , Space
+                      , Str "stumps"
+                      , Space
+                      , Str "of"
+                      , Space
+                      , Str "time"
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "Were"
+                      , Space
+                      , Str "told"
+                      , Space
+                      , Str "upon"
+                      , Space
+                      , Str "the"
+                      , Space
+                      , Str "walls;"
+                      , Space
+                      , Str "staring"
+                      , Space
+                      , Str "forms"
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "Leaned"
+                      , Space
+                      , Str "out,"
+                      , Space
+                      , Str "leaning,"
+                      , Space
+                      , Str "hushing"
+                      , Space
+                      , Str "the"
+                      , Space
+                      , Str "room"
+                      , Space
+                      , Str "enclosed."
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "Footsteps"
+                      , Space
+                      , Str "shuffled"
+                      , Space
+                      , Str "on"
+                      , Space
+                      , Str "the"
+                      , Space
+                      , Str "stair."
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "Under"
+                      , Space
+                      , Str "the"
+                      , Space
+                      , Str "firelight,"
+                      , Space
+                      , Str "under"
+                      , Space
+                      , Str "the"
+                      , Space
+                      , Str "brush,"
+                      , Space
+                      , Str "her"
+                      , Space
+                      , Str "hair"
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "Spread"
+                      , Space
+                      , Str "out"
+                      , Space
+                      , Str "in"
+                      , Space
+                      , Str "fiery"
+                      , Space
+                      , Str "points"
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "Glowed"
+                      , Space
+                      , Str "into"
+                      , Space
+                      , Str "words,"
+                      , Space
+                      , Str "then"
+                      , Space
+                      , Str "would"
+                      , Space
+                      , Str "be"
+                      , Space
+                      , Str "savagely"
+                      , Space
+                      , Str "still."
+                      , Span ( "" , [ "lnum" ] , [] ) [ Str "110" ]
+                      ]
+                  ]
+              ]
+          , Div
+              ( "" , [ "linegroup" ] , [] )
+              [ Div
+                  ( "" , [ "linegroup" ] , [] )
+                  [ Div
+                      ( "" , [] , [] )
+                      [ Plain
+                          [ Str "\"My"
+                          , Space
+                          , Str "nerves"
+                          , Space
+                          , Str "are"
+                          , Space
+                          , Str "bad"
+                          , Space
+                          , Str "to-night."
+                          , Space
+                          , Str "Yes,"
+                          , Space
+                          , Str "bad."
+                          , Space
+                          , Str "Stay"
+                          , Space
+                          , Str "with"
+                          , Space
+                          , Str "me."
+                          ]
+                      ]
+                  , Div
+                      ( "" , [] , [] )
+                      [ Plain
+                          [ Str "\"Speak"
+                          , Space
+                          , Str "to"
+                          , Space
+                          , Str "me."
+                          , Space
+                          , Str "Why"
+                          , Space
+                          , Str "do"
+                          , Space
+                          , Str "you"
+                          , Space
+                          , Str "never"
+                          , Space
+                          , Str "speak."
+                          , Space
+                          , Str "Speak."
+                          ]
+                      ]
+                  , Div
+                      ( "" , [] , [] )
+                      [ Plain
+                          [ Str "\"What"
+                          , Space
+                          , Str "are"
+                          , Space
+                          , Str "you"
+                          , Space
+                          , Str "thinking"
+                          , Space
+                          , Str "of?"
+                          , Space
+                          , Str "What"
+                          , Space
+                          , Str "thinking?"
+                          , Space
+                          , Str "What?"
+                          ]
+                      ]
+                  , Div
+                      ( "" , [] , [] )
+                      [ Plain
+                          [ Str "\"I"
+                          , Space
+                          , Str "never"
+                          , Space
+                          , Str "know"
+                          , Space
+                          , Str "what"
+                          , Space
+                          , Str "you"
+                          , Space
+                          , Str "are"
+                          , Space
+                          , Str "thinking."
+                          , Space
+                          , Str "Think.\""
+                          ]
+                      ]
+                  ]
+              , Div
+                  ( "" , [ "linegroup" ] , [] )
+                  [ Div
+                      ( "wasteland-content.xhtml_ln115" , [] , [] )
+                      [ Plain
+                          [ Str "I"
+                          , Space
+                          , Str "think"
+                          , Space
+                          , Str "we"
+                          , Space
+                          , Str "are"
+                          , Space
+                          , Str "in"
+                          , Space
+                          , Str "rats'"
+                          , Space
+                          , Str "alley"
+                          , Note
+                              [ Para
+                                  [ Link
+                                      ( "" , [] , [] )
+                                      [ Str "115." ]
+                                      ( "#wasteland-content.xhtml_ln115"
+                                      , ""
+                                      )
+                                  , Space
+                                  , Str "Cf."
+                                  , Space
+                                  , Str "Part"
+                                  , Space
+                                  , Str "III,"
+                                  , Space
+                                  , Str "l."
+                                  , Space
+                                  , Str "195."
+                                  ]
+                              ]
+                          ]
+                      ]
+                  , Div
+                      ( "" , [] , [] )
+                      [ Plain
+                          [ Str "Where"
+                          , Space
+                          , Str "the"
+                          , Space
+                          , Str "dead"
+                          , Space
+                          , Str "men"
+                          , Space
+                          , Str "lost"
+                          , Space
+                          , Str "their"
+                          , Space
+                          , Str "bones."
+                          ]
+                      ]
+                  ]
+              ]
+          , Div
+              ( "" , [ "linegroup" ] , [] )
+              [ Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "\"What"
+                      , Space
+                      , Str "is"
+                      , Space
+                      , Str "that"
+                      , Space
+                      , Str "noise?\""
+                      ]
+                  ]
+              , Div
+                  ( "wasteland-content.xhtml_ln118"
+                  , [ "indent" ]
+                  , []
+                  )
+                  [ Plain
+                      [ Str "The"
+                      , Space
+                      , Str "wind"
+                      , Space
+                      , Str "under"
+                      , Space
+                      , Str "the"
+                      , Space
+                      , Str "door."
+                      , Note
+                          [ Para
+                              [ Link
+                                  ( "" , [] , [] )
+                                  [ Str "118." ]
+                                  ( "#wasteland-content.xhtml_ln118"
+                                  , ""
+                                  )
+                              , Space
+                              , Str "Cf."
+                              , Space
+                              , Str "Webster:"
+                              ]
+                          , BlockQuote
+                              [ Para
+                                  [ Str "\"Is"
+                                  , Space
+                                  , Str "the"
+                                  , Space
+                                  , Str "wind"
+                                  , Space
+                                  , Str "in"
+                                  , Space
+                                  , Str "that"
+                                  , Space
+                                  , Str "door"
+                                  , Space
+                                  , Str "still?\""
+                                  ]
+                              ]
+                          ]
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "\"What"
+                      , Space
+                      , Str "is"
+                      , Space
+                      , Str "that"
+                      , Space
+                      , Str "noise"
+                      , Space
+                      , Str "now?"
+                      , Space
+                      , Str "What"
+                      , Space
+                      , Str "is"
+                      , Space
+                      , Str "the"
+                      , Space
+                      , Str "wind"
+                      , Space
+                      , Str "doing?\""
+                      ]
+                  ]
+              , Div
+                  ( "" , [ "indent" ] , [] )
+                  [ Plain
+                      [ Str "Nothing"
+                      , Space
+                      , Str "again"
+                      , Space
+                      , Str "nothing."
+                      , Span ( "" , [ "lnum" ] , [] ) [ Str "120" ]
+                      ]
+                  ]
+              ]
+          , Div
+              ( "" , [ "linegroup" ] , [] )
+              [ Div ( "" , [] , [] ) [ Plain [ Str "\"Do" ] ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "\"You"
+                      , Space
+                      , Str "know"
+                      , Space
+                      , Str "nothing?"
+                      , Space
+                      , Str "Do"
+                      , Space
+                      , Str "you"
+                      , Space
+                      , Str "see"
+                      , Space
+                      , Str "nothing?"
+                      , Space
+                      , Str "Do"
+                      , Space
+                      , Str "you"
+                      , Space
+                      , Str "remember"
+                      ]
+                  ]
+              , Div ( "" , [] , [] ) [ Plain [ Str "\"Nothing?\"" ] ]
+              ]
+          , Div
+              ( "" , [ "linegroup" ] , [] )
+              [ Div
+                  ( "" , [] , [] )
+                  [ Plain [ Str "I" , Space , Str "remember" ] ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "Those"
+                      , Space
+                      , Str "are"
+                      , Space
+                      , Str "pearls"
+                      , Space
+                      , Str "that"
+                      , Space
+                      , Str "were"
+                      , Space
+                      , Str "his"
+                      , Space
+                      , Str "eyes."
+                      ]
+                  ]
+              , Div
+                  ( "wasteland-content.xhtml_ln126" , [] , [] )
+                  [ Plain
+                      [ Str "\"Are"
+                      , Space
+                      , Str "you"
+                      , Space
+                      , Str "alive,"
+                      , Space
+                      , Str "or"
+                      , Space
+                      , Str "not?"
+                      , Space
+                      , Str "Is"
+                      , Space
+                      , Str "there"
+                      , Space
+                      , Str "nothing"
+                      , Space
+                      , Str "in"
+                      , Space
+                      , Str "your"
+                      , Space
+                      , Str "head?\""
+                      , Note
+                          [ Para
+                              [ Link
+                                  ( "" , [] , [] )
+                                  [ Str "126." ]
+                                  ( "#wasteland-content.xhtml_ln126"
+                                  , ""
+                                  )
+                              , Space
+                              , Str "Cf."
+                              , Space
+                              , Str "Part"
+                              , Space
+                              , Str "I,"
+                              , Space
+                              , Str "l."
+                              , Space
+                              , Str "37,"
+                              , Space
+                              , Str "48."
+                              ]
+                          ]
+                      ]
+                  ]
+              , Div ( "" , [] , [] ) [ Plain [ Str "But" ] ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "O"
+                      , Space
+                      , Str "O"
+                      , Space
+                      , Str "O"
+                      , Space
+                      , Str "O"
+                      , Space
+                      , Str "that"
+                      , Space
+                      , Str "Shakespeherian"
+                      , Space
+                      , Str "Rag\8213"
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "It's"
+                      , Space
+                      , Str "so"
+                      , Space
+                      , Str "elegant"
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "So"
+                      , Space
+                      , Str "intelligent"
+                      , Span ( "" , [ "lnum" ] , [] ) [ Str "130" ]
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "\"What"
+                      , Space
+                      , Str "shall"
+                      , Space
+                      , Str "I"
+                      , Space
+                      , Str "do"
+                      , Space
+                      , Str "now?"
+                      , Space
+                      , Str "What"
+                      , Space
+                      , Str "shall"
+                      , Space
+                      , Str "I"
+                      , Space
+                      , Str "do?\""
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "I"
+                      , Space
+                      , Str "shall"
+                      , Space
+                      , Str "rush"
+                      , Space
+                      , Str "out"
+                      , Space
+                      , Str "as"
+                      , Space
+                      , Str "I"
+                      , Space
+                      , Str "am,"
+                      , Space
+                      , Str "and"
+                      , Space
+                      , Str "walk"
+                      , Space
+                      , Str "the"
+                      , Space
+                      , Str "street"
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "\"With"
+                      , Space
+                      , Str "my"
+                      , Space
+                      , Str "hair"
+                      , Space
+                      , Str "down,"
+                      , Space
+                      , Str "so."
+                      , Space
+                      , Str "What"
+                      , Space
+                      , Str "shall"
+                      , Space
+                      , Str "we"
+                      , Space
+                      , Str "do"
+                      , Space
+                      , Str "to-morrow?"
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "\"What"
+                      , Space
+                      , Str "shall"
+                      , Space
+                      , Str "we"
+                      , Space
+                      , Str "ever"
+                      , Space
+                      , Str "do?\""
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "The"
+                      , Space
+                      , Str "hot"
+                      , Space
+                      , Str "water"
+                      , Space
+                      , Str "at"
+                      , Space
+                      , Str "ten."
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "And"
+                      , Space
+                      , Str "if"
+                      , Space
+                      , Str "it"
+                      , Space
+                      , Str "rains,"
+                      , Space
+                      , Str "a"
+                      , Space
+                      , Str "closed"
+                      , Space
+                      , Str "car"
+                      , Space
+                      , Str "at"
+                      , Space
+                      , Str "four."
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "And"
+                      , Space
+                      , Str "we"
+                      , Space
+                      , Str "shall"
+                      , Space
+                      , Str "play"
+                      , Space
+                      , Str "a"
+                      , Space
+                      , Str "game"
+                      , Space
+                      , Str "of"
+                      , Space
+                      , Str "chess,"
+                      ]
+                  ]
+              , Div
+                  ( "wasteland-content.xhtml_ln138" , [] , [] )
+                  [ Plain
+                      [ Str "Pressing"
+                      , Space
+                      , Str "lidless"
+                      , Space
+                      , Str "eyes"
+                      , Space
+                      , Str "and"
+                      , Space
+                      , Str "waiting"
+                      , Space
+                      , Str "for"
+                      , Space
+                      , Str "a"
+                      , Space
+                      , Str "knock"
+                      , Space
+                      , Str "upon"
+                      , Space
+                      , Str "the"
+                      , Space
+                      , Str "door."
+                      , Note
+                          [ Para
+                              [ Link
+                                  ( "" , [] , [] )
+                                  [ Str "138." ]
+                                  ( "#wasteland-content.xhtml_ln138"
+                                  , ""
+                                  )
+                              , Space
+                              , Str "Cf."
+                              , Space
+                              , Str "the"
+                              , Space
+                              , Str "game"
+                              , Space
+                              , Str "of"
+                              , Space
+                              , Str "chess"
+                              , Space
+                              , Str "in"
+                              , Space
+                              , Str "Middleton's"
+                              , Space
+                              , Str "Women"
+                              , Space
+                              , Str "beware"
+                              , Space
+                              , Str "Women."
+                              ]
+                          ]
+                      ]
+                  ]
+              ]
+          , Div
+              ( "" , [ "linegroup" ] , [] )
+              [ Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "When"
+                      , Space
+                      , Str "Lil's"
+                      , Space
+                      , Str "husband"
+                      , Space
+                      , Str "got"
+                      , Space
+                      , Str "demobbed,"
+                      , Space
+                      , Str "I"
+                      , Space
+                      , Str "said"
+                      , Space
+                      , Str "-"
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "I"
+                      , Space
+                      , Str "didn't"
+                      , Space
+                      , Str "mince"
+                      , Space
+                      , Str "my"
+                      , Space
+                      , Str "words,"
+                      , Space
+                      , Str "I"
+                      , Space
+                      , Str "said"
+                      , Space
+                      , Str "to"
+                      , Space
+                      , Str "her"
+                      , Space
+                      , Str "myself,"
+                      , Span ( "" , [ "lnum" ] , [] ) [ Str "140" ]
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "HURRY"
+                      , Space
+                      , Str "UP"
+                      , Space
+                      , Str "PLEASE"
+                      , Space
+                      , Str "ITS"
+                      , Space
+                      , Str "TIME"
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "Now"
+                      , Space
+                      , Str "Albert's"
+                      , Space
+                      , Str "coming"
+                      , Space
+                      , Str "back,"
+                      , Space
+                      , Str "make"
+                      , Space
+                      , Str "yourself"
+                      , Space
+                      , Str "a"
+                      , Space
+                      , Str "bit"
+                      , Space
+                      , Str "smart."
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "He'll"
+                      , Space
+                      , Str "want"
+                      , Space
+                      , Str "to"
+                      , Space
+                      , Str "know"
+                      , Space
+                      , Str "what"
+                      , Space
+                      , Str "you"
+                      , Space
+                      , Str "done"
+                      , Space
+                      , Str "with"
+                      , Space
+                      , Str "that"
+                      , Space
+                      , Str "money"
+                      , Space
+                      , Str "he"
+                      , Space
+                      , Str "gave"
+                      , SoftBreak
+                      , Str "you"
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "To"
+                      , Space
+                      , Str "get"
+                      , Space
+                      , Str "yourself"
+                      , Space
+                      , Str "some"
+                      , Space
+                      , Str "teeth."
+                      , Space
+                      , Str "He"
+                      , Space
+                      , Str "did,"
+                      , Space
+                      , Str "I"
+                      , Space
+                      , Str "was"
+                      , Space
+                      , Str "there."
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "You"
+                      , Space
+                      , Str "have"
+                      , Space
+                      , Str "them"
+                      , Space
+                      , Str "all"
+                      , Space
+                      , Str "out,"
+                      , Space
+                      , Str "Lil,"
+                      , Space
+                      , Str "and"
+                      , Space
+                      , Str "get"
+                      , Space
+                      , Str "a"
+                      , Space
+                      , Str "nice"
+                      , Space
+                      , Str "set,"
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "He"
+                      , Space
+                      , Str "said,"
+                      , Space
+                      , Str "I"
+                      , Space
+                      , Str "swear,"
+                      , Space
+                      , Str "I"
+                      , Space
+                      , Str "can't"
+                      , Space
+                      , Str "bear"
+                      , Space
+                      , Str "to"
+                      , Space
+                      , Str "look"
+                      , Space
+                      , Str "at"
+                      , Space
+                      , Str "you."
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "And"
+                      , Space
+                      , Str "no"
+                      , Space
+                      , Str "more"
+                      , Space
+                      , Str "can't"
+                      , Space
+                      , Str "I,"
+                      , Space
+                      , Str "I"
+                      , Space
+                      , Str "said,"
+                      , Space
+                      , Str "and"
+                      , Space
+                      , Str "think"
+                      , Space
+                      , Str "of"
+                      , Space
+                      , Str "poor"
+                      , Space
+                      , Str "Albert,"
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "He's"
+                      , Space
+                      , Str "been"
+                      , Space
+                      , Str "in"
+                      , Space
+                      , Str "the"
+                      , Space
+                      , Str "army"
+                      , Space
+                      , Str "four"
+                      , Space
+                      , Str "years,"
+                      , Space
+                      , Str "he"
+                      , Space
+                      , Str "wants"
+                      , Space
+                      , Str "a"
+                      , Space
+                      , Str "good"
+                      , Space
+                      , Str "time,"
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "And"
+                      , Space
+                      , Str "if"
+                      , Space
+                      , Str "you"
+                      , Space
+                      , Str "don't"
+                      , Space
+                      , Str "give"
+                      , Space
+                      , Str "it"
+                      , Space
+                      , Str "him,"
+                      , Space
+                      , Str "there's"
+                      , Space
+                      , Str "others"
+                      , Space
+                      , Str "will,"
+                      , Space
+                      , Str "I"
+                      , SoftBreak
+                      , Str "said."
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "Oh"
+                      , Space
+                      , Str "is"
+                      , Space
+                      , Str "there,"
+                      , Space
+                      , Str "she"
+                      , Space
+                      , Str "said."
+                      , Space
+                      , Str "Something"
+                      , Space
+                      , Str "o'"
+                      , Space
+                      , Str "that,"
+                      , Space
+                      , Str "I"
+                      , Space
+                      , Str "said."
+                      , Span ( "" , [ "lnum" ] , [] ) [ Str "150" ]
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "Then"
+                      , Space
+                      , Str "I'll"
+                      , Space
+                      , Str "know"
+                      , Space
+                      , Str "who"
+                      , Space
+                      , Str "to"
+                      , Space
+                      , Str "thank,"
+                      , Space
+                      , Str "she"
+                      , Space
+                      , Str "said,"
+                      , Space
+                      , Str "and"
+                      , Space
+                      , Str "give"
+                      , Space
+                      , Str "me"
+                      , Space
+                      , Str "a"
+                      , Space
+                      , Str "straight"
+                      , SoftBreak
+                      , Str "look."
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "HURRY"
+                      , Space
+                      , Str "UP"
+                      , Space
+                      , Str "PLEASE"
+                      , Space
+                      , Str "ITS"
+                      , Space
+                      , Str "TIME"
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "If"
+                      , Space
+                      , Str "you"
+                      , Space
+                      , Str "don't"
+                      , Space
+                      , Str "like"
+                      , Space
+                      , Str "it"
+                      , Space
+                      , Str "you"
+                      , Space
+                      , Str "can"
+                      , Space
+                      , Str "get"
+                      , Space
+                      , Str "on"
+                      , Space
+                      , Str "with"
+                      , Space
+                      , Str "it,"
+                      , Space
+                      , Str "I"
+                      , Space
+                      , Str "said."
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "Others"
+                      , Space
+                      , Str "can"
+                      , Space
+                      , Str "pick"
+                      , Space
+                      , Str "and"
+                      , Space
+                      , Str "choose"
+                      , Space
+                      , Str "if"
+                      , Space
+                      , Str "you"
+                      , Space
+                      , Str "can't."
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "But"
+                      , Space
+                      , Str "if"
+                      , Space
+                      , Str "Albert"
+                      , Space
+                      , Str "makes"
+                      , Space
+                      , Str "off,"
+                      , Space
+                      , Str "it"
+                      , Space
+                      , Str "won't"
+                      , Space
+                      , Str "be"
+                      , Space
+                      , Str "for"
+                      , Space
+                      , Str "lack"
+                      , Space
+                      , Str "of"
+                      , SoftBreak
+                      , Str "telling."
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "You"
+                      , Space
+                      , Str "ought"
+                      , Space
+                      , Str "to"
+                      , Space
+                      , Str "be"
+                      , Space
+                      , Str "ashamed,"
+                      , Space
+                      , Str "I"
+                      , Space
+                      , Str "said,"
+                      , Space
+                      , Str "to"
+                      , Space
+                      , Str "look"
+                      , Space
+                      , Str "so"
+                      , Space
+                      , Str "antique."
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "(And"
+                      , Space
+                      , Str "her"
+                      , Space
+                      , Str "only"
+                      , Space
+                      , Str "thirty-one.)"
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "I"
+                      , Space
+                      , Str "can't"
+                      , Space
+                      , Str "help"
+                      , Space
+                      , Str "it,"
+                      , Space
+                      , Str "she"
+                      , Space
+                      , Str "said,"
+                      , Space
+                      , Str "pulling"
+                      , Space
+                      , Str "a"
+                      , Space
+                      , Str "long"
+                      , Space
+                      , Str "face,"
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "It's"
+                      , Space
+                      , Str "them"
+                      , Space
+                      , Str "pills"
+                      , Space
+                      , Str "I"
+                      , Space
+                      , Str "took,"
+                      , Space
+                      , Str "to"
+                      , Space
+                      , Str "bring"
+                      , Space
+                      , Str "it"
+                      , Space
+                      , Str "off,"
+                      , Space
+                      , Str "she"
+                      , Space
+                      , Str "said."
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "(She's"
+                      , Space
+                      , Str "had"
+                      , Space
+                      , Str "five"
+                      , Space
+                      , Str "already,"
+                      , Space
+                      , Str "and"
+                      , Space
+                      , Str "nearly"
+                      , Space
+                      , Str "died"
+                      , Space
+                      , Str "of"
+                      , Space
+                      , Str "young"
+                      , Space
+                      , Str "George.)"
+                      , Span ( "" , [ "lnum" ] , [] ) [ Str "160" ]
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "The"
+                      , Space
+                      , Str "chemist"
+                      , Space
+                      , Str "said"
+                      , Space
+                      , Str "it"
+                      , Space
+                      , Str "would"
+                      , Space
+                      , Str "be"
+                      , Space
+                      , Str "all"
+                      , Space
+                      , Str "right,"
+                      , Space
+                      , Str "but"
+                      , Space
+                      , Str "I've"
+                      , Space
+                      , Str "never"
+                      , Space
+                      , Str "been"
+                      , Space
+                      , Str "the"
+                      , SoftBreak
+                      , Str "same."
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "You"
+                      , Space
+                      , Emph [ Str "are" ]
+                      , Space
+                      , Str "a"
+                      , Space
+                      , Str "proper"
+                      , Space
+                      , Str "fool,"
+                      , Space
+                      , Str "I"
+                      , Space
+                      , Str "said."
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "Well,"
+                      , Space
+                      , Str "if"
+                      , Space
+                      , Str "Albert"
+                      , Space
+                      , Str "won't"
+                      , Space
+                      , Str "leave"
+                      , Space
+                      , Str "you"
+                      , Space
+                      , Str "alone,"
+                      , Space
+                      , Str "there"
+                      , Space
+                      , Str "it"
+                      , Space
+                      , Str "is,"
+                      , Space
+                      , Str "I"
+                      , SoftBreak
+                      , Str "said,"
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "What"
+                      , Space
+                      , Str "you"
+                      , Space
+                      , Str "get"
+                      , Space
+                      , Str "married"
+                      , Space
+                      , Str "for"
+                      , Space
+                      , Str "if"
+                      , Space
+                      , Str "you"
+                      , Space
+                      , Str "don't"
+                      , Space
+                      , Str "want"
+                      , Space
+                      , Str "children?"
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "HURRY"
+                      , Space
+                      , Str "UP"
+                      , Space
+                      , Str "PLEASE"
+                      , Space
+                      , Str "ITS"
+                      , Space
+                      , Str "TIME"
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "Well,"
+                      , Space
+                      , Str "that"
+                      , Space
+                      , Str "Sunday"
+                      , Space
+                      , Str "Albert"
+                      , Space
+                      , Str "was"
+                      , Space
+                      , Str "home,"
+                      , Space
+                      , Str "they"
+                      , Space
+                      , Str "had"
+                      , Space
+                      , Str "a"
+                      , Space
+                      , Str "hot"
+                      , SoftBreak
+                      , Str "gammon,"
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "And"
+                      , Space
+                      , Str "they"
+                      , Space
+                      , Str "asked"
+                      , Space
+                      , Str "me"
+                      , Space
+                      , Str "in"
+                      , Space
+                      , Str "to"
+                      , Space
+                      , Str "dinner,"
+                      , Space
+                      , Str "to"
+                      , Space
+                      , Str "get"
+                      , Space
+                      , Str "the"
+                      , Space
+                      , Str "beauty"
+                      , Space
+                      , Str "of"
+                      , Space
+                      , Str "it"
+                      , SoftBreak
+                      , Str "hot\8213"
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "HURRY"
+                      , Space
+                      , Str "UP"
+                      , Space
+                      , Str "PLEASE"
+                      , Space
+                      , Str "ITS"
+                      , Space
+                      , Str "TIME"
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "HURRY"
+                      , Space
+                      , Str "UP"
+                      , Space
+                      , Str "PLEASE"
+                      , Space
+                      , Str "ITS"
+                      , Space
+                      , Str "TIME"
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "Goonight"
+                      , Space
+                      , Str "Bill."
+                      , Space
+                      , Str "Goonight"
+                      , Space
+                      , Str "Lou."
+                      , Space
+                      , Str "Goonight"
+                      , Space
+                      , Str "May."
+                      , Space
+                      , Str "Goonight."
+                      , Span ( "" , [ "lnum" ] , [] ) [ Str "170" ]
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "Ta"
+                      , Space
+                      , Str "ta."
+                      , Space
+                      , Str "Goonight."
+                      , Space
+                      , Str "Goonight."
+                      ]
+                  ]
+              , Div
+                  ( "" , [] , [] )
+                  [ Plain
+                      [ Str "Good"
+                      , Space
+                      , Str "night,"
+                      , Space
+                      , Str "ladies,"
+                      , Space
+                      , Str "good"
+                      , Space
+                      , Str "night,"
+                      , Space
+                      , Str "sweet"
+                      , Space
+                      , Str "ladies,"
+                      , Space
+                      , Str "good"
+                      , Space
+                      , Str "night,"
+                      , Space
+                      , Str "good"
+                      , SoftBreak
+                      , Str "night."
+                      ]
+                  ]
+              ]
+          ]
+      ]
+  , Div
+      ( "wasteland-content.xhtml_backmatter"
+      , [ "section" , "backmatter" ]
+      , []
+      )
+      [ Div
+          ( "wasteland-content.xhtml_rearnotes"
+          , [ "rearnotes" ]
+          , []
+          )
+          [ Header
+              2
+              ( "" , [] , [] )
+              [ Str "NOTES"
+              , Space
+              , Str "ON"
+              , Space
+              , Str "\"THE"
+              , Space
+              , Str "WASTE"
+              , Space
+              , Str "LAND\""
+              ]
+          , Para
+              [ Str "Not"
+              , Space
+              , Str "only"
+              , Space
+              , Str "the"
+              , Space
+              , Str "title,"
+              , Space
+              , Str "but"
+              , Space
+              , Str "the"
+              , Space
+              , Str "plan"
+              , Space
+              , Str "and"
+              , Space
+              , Str "a"
+              , Space
+              , Str "good"
+              , Space
+              , Str "deal"
+              , Space
+              , Str "of"
+              , Space
+              , Str "the"
+              , Space
+              , Str "incidental"
+              , Space
+              , Str "symbolism"
+              , Space
+              , Str "of"
+              , SoftBreak
+              , Str "the"
+              , Space
+              , Str "poem"
+              , Space
+              , Str "were"
+              , Space
+              , Str "suggested"
+              , Space
+              , Str "by"
+              , Space
+              , Str "Miss"
+              , Space
+              , Str "Jessie"
+              , Space
+              , Str "L."
+              , Space
+              , Str "Weston's"
+              , Space
+              , Str "book"
+              , Space
+              , Str "on"
+              , Space
+              , Str "the"
+              , Space
+              , Str "Grail"
+              , Space
+              , Str "legend:"
+              , SoftBreak
+              , Str "From"
+              , Space
+              , Str "Ritual"
+              , Space
+              , Str "to"
+              , Space
+              , Str "Romance"
+              ]
+          , Para
+              [ Str "Indeed,"
+              , Space
+              , Str "so"
+              , Space
+              , Str "deeply"
+              , Space
+              , Str "am"
+              , Space
+              , Str "I"
+              , Space
+              , Str "indebted,"
+              , Space
+              , Str "Miss"
+              , Space
+              , Str "Weston's"
+              , Space
+              , Str "book"
+              , Space
+              , Str "will"
+              , Space
+              , Str "elucidate"
+              , Space
+              , Str "the"
+              , SoftBreak
+              , Str "difficulties"
+              , Space
+              , Str "of"
+              , Space
+              , Str "the"
+              , Space
+              , Str "poem"
+              , Space
+              , Str "much"
+              , Space
+              , Str "better"
+              , Space
+              , Str "than"
+              , Space
+              , Str "my"
+              , Space
+              , Str "notes"
+              , Space
+              , Str "can"
+              , Space
+              , Str "do;"
+              , Space
+              , Str "and"
+              , Space
+              , Str "I"
+              , Space
+              , Str "recommend"
+              , Space
+              , Str "it"
+              , SoftBreak
+              , Str "(apart"
+              , Space
+              , Str "from"
+              , Space
+              , Str "the"
+              , Space
+              , Str "great"
+              , Space
+              , Str "interest"
+              , Space
+              , Str "of"
+              , Space
+              , Str "the"
+              , Space
+              , Str "book"
+              , Space
+              , Str "itself)"
+              , Space
+              , Str "to"
+              , Space
+              , Str "any"
+              , Space
+              , Str "who"
+              , Space
+              , Str "think"
+              , Space
+              , Str "such"
+              , SoftBreak
+              , Str "elucidation"
+              , Space
+              , Str "of"
+              , Space
+              , Str "the"
+              , Space
+              , Str "poem"
+              , Space
+              , Str "worth"
+              , Space
+              , Str "the"
+              , Space
+              , Str "trouble."
+              , Space
+              , Str "To"
+              , Space
+              , Str "another"
+              , Space
+              , Str "work"
+              , Space
+              , Str "of"
+              , Space
+              , Str "anthropology"
+              , Space
+              , Str "I"
+              , Space
+              , Str "am"
+              , SoftBreak
+              , Str "indebted"
+              , Space
+              , Str "in"
+              , Space
+              , Str "general,"
+              , Space
+              , Str "one"
+              , Space
+              , Str "which"
+              , Space
+              , Str "has"
+              , Space
+              , Str "influenced"
+              , Space
+              , Str "our"
+              , Space
+              , Str "generation"
+              , Space
+              , Str "profoundly;"
+              , Space
+              , Str "I"
+              , Space
+              , Str "mean"
+              , SoftBreak
+              , Str "The"
+              , Space
+              , Str "Golden"
+              , Space
+              , Str "Bough;"
+              , Space
+              , Str "I"
+              , Space
+              , Str "have"
+              , Space
+              , Str "used"
+              , Space
+              , Str "especially"
+              , Space
+              , Str "the"
+              , Space
+              , Str "two"
+              , Space
+              , Str "volumes"
+              , Space
+              , Str "Adonis,"
+              , Space
+              , Str "Attis,"
+              , Space
+              , Str "Osiris."
+              , SoftBreak
+              , Str "Anyone"
+              , Space
+              , Str "who"
+              , Space
+              , Str "is"
+              , Space
+              , Str "acquainted"
+              , Space
+              , Str "with"
+              , Space
+              , Str "these"
+              , Space
+              , Str "works"
+              , Space
+              , Str "will"
+              , Space
+              , Str "immediately"
+              , Space
+              , Str "recognise"
+              , Space
+              , Str "in"
+              , Space
+              , Str "the"
+              , Space
+              , Str "poem"
+              , SoftBreak
+              , Str "certain"
+              , Space
+              , Str "references"
+              , Space
+              , Str "to"
+              , Space
+              , Str "vegetation"
+              , Space
+              , Str "ceremonies."
+              ]
+          , Div
+              ( "" , [ "section" ] , [] )
+              [ Header
+                  3
+                  ( "" , [] , [] )
+                  [ Str "I."
+                  , Space
+                  , Str "THE"
+                  , Space
+                  , Str "BURIAL"
+                  , Space
+                  , Str "OF"
+                  , Space
+                  , Str "THE"
+                  , Space
+                  , Str "DEAD"
+                  ]
+              ]
+          , Div
+              ( "" , [ "section" ] , [] )
+              [ Header
+                  3
+                  ( "" , [] , [] )
+                  [ Str "II."
+                  , Space
+                  , Str "A"
+                  , Space
+                  , Str "GAME"
+                  , Space
+                  , Str "OF"
+                  , Space
+                  , Str "CHESS"
+                  ]
+              ]
+          ]
+      ]
+  ]
diff --git a/test/fb2/basic.fb2 b/test/fb2/basic.fb2
--- a/test/fb2/basic.fb2
+++ b/test/fb2/basic.fb2
@@ -1,3 +1,73 @@
 <?xml version="1.0" encoding="UTF-8"?>
-<FictionBook xmlns="http://www.gribuser.ru/xml/fictionbook/2.0" xmlns:l="http://www.w3.org/1999/xlink"><description><title-info><genre>unrecognised</genre></title-info><document-info><program-used>pandoc</program-used></document-info></description><body><title><p /></title><section><title><p>Top-level title</p></title><section><title><p>Section</p></title><section><title><p>Subsection</p></title><p>This <emphasis>emphasized</emphasis> <strong>strong</strong> <code>verbatim</code> markdown. See this link<a l:href="#l1" type="note"><sup>[1]</sup></a>.</p><p>Ordered list:</p><p>1. one</p><p>2. two</p><p>3. three</p><cite><p>Blockquote is for citatons.</p></cite><empty-line /><p><code>Code</code></p><p><code>block</code></p><p><code>is</code></p><p><code>for</code></p><p><code>code.</code></p><empty-line /><p><strikethrough>Strikeout</strikethrough> is Pandoc’s extension. Superscript and subscripts too: H<sub>2</sub>O is a liquid<a l:href="#n2" type="note"><sup>[2]</sup></a>. 2<sup>10</sup> is 1024.</p><p>Math is another Pandoc extension: <code>E = m c^2</code>.</p></section></section></section></body><body name="notes"><section id="l1"><title><p>1</p></title><p><code>http://example.com/</code></p></section><section id="n2"><title><p>2</p></title><p>Sometimes.</p></section></body></FictionBook>
-
+<FictionBook xmlns="http://www.gribuser.ru/xml/fictionbook/2.0" xmlns:l="http://www.w3.org/1999/xlink">
+<description>
+<title-info>
+<genre>unrecognised</genre>
+</title-info>
+<document-info>
+<program-used>pandoc</program-used>
+</document-info>
+</description>
+<body>
+<title>
+<p />
+</title>
+<section id="top-level-title">
+<title>
+<p>Top-level title</p>
+</title>
+<section id="section">
+<title>
+<p>Section</p>
+</title>
+<section id="subsection">
+<title>
+<p>Subsection</p>
+</title>
+<p>This <emphasis>emphasized</emphasis> <strong>strong</strong> <code>verbatim</code> markdown.
+See this <a l:href="http://example.com/">link</a>.</p>
+<p>Ordered list:</p>
+<p>1. one</p>
+<p>2. two</p>
+<p>3. three</p>
+<cite>
+<p>Blockquote
+is
+for
+citatons.</p>
+</cite>
+<empty-line />
+<p>
+<code>Code</code>
+</p>
+<p>
+<code>block</code>
+</p>
+<p>
+<code>is</code>
+</p>
+<p>
+<code>for</code>
+</p>
+<p>
+<code>code.</code>
+</p>
+<empty-line />
+<p>
+<strikethrough>Strikeout</strikethrough> is Pandoc’s extension.
+Superscript and subscripts too: H<sub>2</sub>O is a liquid<a l:href="#n1" type="note">[1]</a>.
+2<sup>10</sup> is 1024.</p>
+<p>Math is another Pandoc extension: <code>E = m c^2</code>.</p>
+</section>
+</section>
+</section>
+</body>
+<body name="notes">
+<section id="n1">
+<title>
+<p>1</p>
+</title>
+<p>Sometimes.</p>
+</section>
+</body>
+</FictionBook>
diff --git a/test/fb2/images-embedded.fb2 b/test/fb2/images-embedded.fb2
--- a/test/fb2/images-embedded.fb2
+++ b/test/fb2/images-embedded.fb2
@@ -1,2 +1,2 @@
 <?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><image l:href="#image1" l:type="inlineImageType" alt="This image was embedded using data URI scheme" /><p>This image was embedded using data URI scheme</p></section></body><binary id="image1" content-type="image/png">iVBORw0KGgoAAAANSUhEUgAAADAAAAAgCAIAAADbtmxLAAABmGlDQ1BpY2MAAHjapdG/axMBGMbxTy4tldJSwSAiHW4ootKCqIOrVShIkRIrJNUluUvaQi4Nd1dEXAQHF4cOXVRcLOLirJv4BygIggqCi7sUBRcpcbiDgtBBfOGF5/315eV9qR7qRUk2EpL087S+MB82mivh2BeBcUcddrwVZYOLS0uLDrRfH1Xgw1wvSjL/ZpNxJ4uohFiKBmlOZYC7t/JBTmUXtWitFROMYDZtNFcIzqDWLvRl1FYL3UAtXa5fIughXC30A4TtQr9AGK2lCcFbzMRJPybYxWScxDFVGE16m1G5ZwUTnf71aziPaXUsYB4h2tjEOnrIMVfG/QJyAC/GtKvYKFlRqQe4jbTkrGKtZM+WvZvI0CnjbtnfKb1XMtBoroR//yzrnjtbbDRxhdFvw+HP04w9Zu/+cPj76XC4t0P1M2+29+c3trnwnerWfm7mCVP3ePl6P9d+xqstjn0dtNIWitMG3S4/njPZ5Mh7xm/8b734Z1m384nlOyy+4+EjTnSZunkyzsP1ft5J+63eKWT1hXn4AzDofghlJQBJAAAACXBIWXMAAAsSAAALEgHS3X78AAACInpUWHRSYXcgcHJvZmlsZSB0eXBlIGV4aWYAAHjahVRJtiQhCNx7ijpCMIhyHNPU9/oGffxeaNY3p/5VC5IAQkAhtL9/evh8Pp+PiwaNKZubAYDuugNcMH4ZIAN6A6ATo68kdAA8VQ1DkoEIq2EILiBiALIQDTISWvz3SSQNJHwnilWTGgC/ZMSa1Fc8TDznZH4rgWOtRrwQKGh8VyNZ8bAY9Ccj1EGXUI0JwNE3n3itxrzis7Sq1TgBiNMwesKo1TjfcdZqXBaiWRpLrcbbEjBLU63G9QGv1bit+CSKWi2W8+3QLDluF/wIBgBEaNQWNSjFzHj7/zgOP92EBap3v2BqlNi2pEbGVi0yBNwkcRPiTVxIJDVLRgJxEXGLRgAgLBASkiIIwlIEYgyBJCnC4lKExN6yGSW6SD961nvvQaxhBZq4rbptbX1HlJPSokN37t9m9957a5utDux7Xwk06WnWWOJ2yqgkPqW4e2urnmNPK0HMtq0Hkkc7ZbSXUleHiNMIoGy7r/ppEwAIV+Amv1rS/3ghgCz23ns+m/HrASdJMWT2chsBiS2z73fcLGd+3E8hZ05nQ81zzOW2n8Saj1VzwTMHZ+g6xcPg5ozLASM7Z/hl9kaPnPFQmrcyvm8lFKbrAQwAoegtYFy34rEXRSFP/qEo4tmQ0wywlwPyG5G/BJQXvF5wOR4k7m9HjlupR/y6Mp42RjhWxm+Oh99BvMrwD3UCiGvkpxuRAAAACXZwQWcAAAAwAAAAIACELJ4GAAALGklEQVRYw11YW48dV1b+1tq7qs6t+/TldPsSx3bbcRwncWY0A4LMCOYFXpgHJCR4QvwAnpAQj/wB/gR/ACR4QUKDECMUEjLOZew4zsRxuu122+52n9Pnfuqy9/p4qNNtD1tLpVKpap/vrMu31rdl/nAgIjSpF0kAJAEHGJwAAIQheqeARVqomCQZGUkjSYLmTAyAkCJiESRVNYQAaL3h8k3SzPj6MjEzsr7SqyoAcRABQItRVZ14kqifmNEkTZNiUZiZ934xm4WE3mva8GYGAA5UJ8YYIyCipiKk1ZuTBAhQBGZQFRKvTAgBaQBIeOekBqpa+0gBxFgAlmhqhixJzUKMRVEUx/3RWmel3z9xzrVX2+tuRb3WnrDKVFUEgKlCVWI055WMZ76AieipX0AYzYwQUZqZqJD0tKCqFJAxhKiqSZKooirj06fPMt/odlezhngFYar+0e7jxWLR6/Vc7ubzpNnM4BlDSDLvvQ8hnAYFIlCFRUDEjASgIGFGEcBIoSrMCFAVhgiKTxJPkgJVSeBBhKqaTCb5Ip4cD/efPP/g9q2soSvdTp7nAuv2Vk/2BoHFyWgRYxVjbDezRiMDMicNxqCqqhIZVZxZVK3zaRkgXYaMdeDMoMoapSpo8GSE1t6ihaCqPs3WV/VwPpxOp8fHRw++cUmq7XYzSbLV1W5vu3fw7Emn0xwcD+ZzF8vKQtlI09R7J6SXOldgEDEwAmdguMyYV/lEVWEkARExEkoVBxHWxeUSFefK6fTJ48dlme/sXN7a3vjVnf8NIQ6Hk1ajOZ+Nf/3ZZ9Uij0V+fedqM0v2nz5ut7LtCz1GC2WVJqmry1KgZKLqlbo0qLPanJrAVKgSRX/LPElxQF0smiDy6Ojo7pd3qXLjxo2r1y8fnwxORpN8Nt/u9fLF5OTFcRVKDWE0HJZF2O71IsOzZ0+e7D3tdDo7168miU9SJ6IhBIGD2KuKMpHaPwoFXkXq9Aak+/u//TsFRCEgEAljjFtbW+UiHPb765sbJ8M+Y9HtdAbDgWs0pSge7O1u9Tar+Xwwmy0m03I0XpgbjydZlk2n43armaVOJIqQDEIIIKBABK/iBYuAnT4HwJrx1CkhRosAIRBBo93ImunO25dv/eBmb231+rUrRTH/we1ba+udhw/uSoZGOzt38Vx/1D85folYLhazqpg3mj5ruNWVTqPhxcEsAOa8ihJiAhMEQVChCgXmhKcWT41O6IGq5kCjqPOTk9F4PF7rrlvKRtQHjx/d2Lk+mgy+evrwhzs3Xuzv0tmbb5z79LNPzm9utdorEoNkzPPx+x+812o10tR7DyCqUwCMQUUIUqm2JOolbb/GjmbwoDGS9GZBnYM4IS0E5+TChS1Nk7Z28uPhW29euvPRf2fN1pdffNE1vXnzxsGgf/B036duvbce5tXG2uZkfnL79q3t8+sA4Rws0CJIAOI8LADUusLqeC0rTl4RJgyg1Fe+fB7yUrxTQoRWVoExbWTjl6P5fD7dO6yIF4P+bDK/92T3hzffLWGffPq5c7K1uf7hj3+PrLqbqxffuDQc9VdWVtY31846l1CFqJlalk8gr/UxAIzLLrZkbVK5WHgHhFIYmS+K6ZhFkY/Hi/5gPOhLUzvnu73L59KVxjyffXH314vFIsbYaTXeuXFtcHx4sPd9S+3l84PMwTsyBrMgQhUIgrEUREWUU4O8uhcLdW45BsWpiVRgoSyYTxYn/ee7e9/f/2Z8eOwYm8pko4EktDvpzOZXL5z3Dd3b2/vi/r1G0795cat//GxrvWPTaW+lvdVdXUkTCaVagAUrF6wKVSAGxIAQJEZYiVjSSrBSq4SVWCFWKINYpQzK4FHmhqjOgbF/+Hx0dJyXtv/46ZuXtrrd1V6ruRhNJqPZlfbq5999/Dt/+LNf/tf/nEyH585t73338OrVS3E8Pnl+MJnOi7i4fG1no7cJ79Sh7vPISwCwZYCERN3TjQCFZFxGE3FJV97iXCGIKBZlcyV799zbIdhsNnvyaP/x3r6Z+Tx02i6Kv/7WO8bFX/3ZT37xyZ2yf9Ta2n73vZ1vf/Xlv338+R/97MOVjc63X99fbXduvfuONBJTAlDxiBGAWKQZSVn2BZ4lDYwAlDQzkF7LEmYQyUSTdkvTzNuiZLz25vlOt3N0cPTwxcH7W2/9+NbN0Uef3Pvs6w/+9KcraePb3+z+6NKF+cHLvvN/89d/2SQsTSdr3clwMh0M1nvr0ki4yI0iQgBSu8dYOwxm4BIEyTrTEY1mHrNpZD3KiMIhlLEokljKWueyytsX3ji/2rqzuzt4Obh95eLd3+ztf7Xv1e2sp8OXw73h8Od//FNNtIh5Rqx322tZWoWimo1c7hQi4mgBxtPpA3VBkXQ0M8BOh5VoS3D8j3+CACqsR4EYzUyIalqaCqCxyIsB/uFf//lPfv93R/2jf/z4m0Zmf/6j977af/wXH/7B6ubK+dVV2+g6D0Yzg4OoA0kRrYoiEXcarFfzq7IueJKsYZktAXl7MRURiARakiQ08xAACHCGybj/i3v3ZoNyDa3/vPPg59cuf/fi4GKjPRmH99cuHT5+Ouv3ipV5b2ve2lxRdfPJLMa4ttKxEEl68ZH52bh4xkDhbLI2OYNiBpL+cHfmnKvfq2nf+eWXi2L+6PgQh42nk+GVc1uf7h9+f1T8ZOftXz76flu7L07Gs7FttCYvknH74PiDt24kjWa/PyvLElupJ2OMZFXBROS3hnoz8sxBS9+YYemhrw9L55xCFCYSalgR7Ehy/+DFnChC0kq3m37j9nr2L7uPnrw8UBb//t2emGsnybW8OW9M3uhc+fbprNWW0Qwh6MwKAQGEEIhlpccYSVLl/wkPM4unqEj6+7MyUZeIpj6pRxOJjDGO5qNpbNLsWTiSyt/dex5mR1Ui+9Phxe72w+moI1mmViSbG7xQNNpHlrhKBnkkcbIwi5WZGegpgMYYq6oCoKoiamZAfB1TWCoq+o/2DxzEiU/TNHXeBCGEqqqKGKGIDPOFTedDY8x8M5HEIRlXi5D7TtrsVpv5cDbZyB69eL7a6IjIfD6NNBHJy1A3tcRJCOV4Nmq1OiqZUgFznonzZVWIECoqXjWpijJGevVipFkZqipYKt6JE1XXjj5tJHk+n41jptrtrifqptNpq9WaTMcqyXon9VlqxHgyi5GjWa6qeZ5DJcsyM6OomVm04WQwnY3XIGkCQGEhzktjORoN8yp3zqVpI0lSUNXB59OhiChE1RdaSK0XSTNqoSSbmQe8F8Bi4jRN00WRr3TY7jSzJAEAQZIkCBUQo1aqmtSTHmJkrGApQtu7lodKKXDQGCyaaJo4mgeAEEPM667sd59/dyoQpUYDUQBCpZiqqmrNIgCEIKlgWS1OTl4OYl9gRoo40VgrRhGpP0G9qMZgFieTKgaKOFXQgolaCE7MBOrgnEO0aKWfLI7rWRaAnC4ATv3ZpiLiVQFYoCmzLAuhHI5eMsInIBkNUXTZUAERAVlvFSrziZoZFxOaaK3HAJOw1K9ArQXKMl/MJ7Ld6Z0l/1m86qMCGEXEe7+EW0+g4iFljCHxLQGcWq0NUp/Ur52K+Vc3ohrrFrs8PzhlJgBiKt7MYoxVKIpiIRudtdc9QSxheTPnHIAYCaNzTlXNzKg+YWRQpgKQRjGIB8Pyb0BJnv1ikFoYOwBEBKAEqFQlaRalFtqkc440n3IZrNp7Z4LExMpgy4SAVBaFVp9zhBCIaBQnDqhPSQgKIAJPksal+AG8ogpRnQCIUVRFoSEE9QIaLNCpqiPFQUK0/wPxadi/ncvxsAAAACV0RVh0ZGF0ZTpjcmVhdGUAMjAxMS0wMi0yOFQwMjo1NTowMiswMTowMGbLlncAAAAldEVYdGRhdGU6bW9kaWZ5ADIwMTEtMDItMjhUMDI6NTU6MDIrMDE6MDAXli7LAAAAEXRFWHRqcGVnOmNvbG9yc3BhY2UAMix1VZ8AAAAgdEVYdGpwZWc6c2FtcGxpbmctZmFjdG9yADF4MSwxeDEsMXgx6ZX8cAAAAABJRU5ErkJggg==</binary></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><image l:href="#image1" l:type="imageType" alt="This image was embedded using data URI scheme" /><p>This image was embedded using data URI scheme</p></section></body><binary id="image1" content-type="image/png">iVBORw0KGgoAAAANSUhEUgAAADAAAAAgCAIAAADbtmxLAAABmGlDQ1BpY2MAAHjapdG/axMBGMbxTy4tldJSwSAiHW4ootKCqIOrVShIkRIrJNUluUvaQi4Nd1dEXAQHF4cOXVRcLOLirJv4BygIggqCi7sUBRcpcbiDgtBBfOGF5/315eV9qR7qRUk2EpL087S+MB82mivh2BeBcUcddrwVZYOLS0uLDrRfH1Xgw1wvSjL/ZpNxJ4uohFiKBmlOZYC7t/JBTmUXtWitFROMYDZtNFcIzqDWLvRl1FYL3UAtXa5fIughXC30A4TtQr9AGK2lCcFbzMRJPybYxWScxDFVGE16m1G5ZwUTnf71aziPaXUsYB4h2tjEOnrIMVfG/QJyAC/GtKvYKFlRqQe4jbTkrGKtZM+WvZvI0CnjbtnfKb1XMtBoroR//yzrnjtbbDRxhdFvw+HP04w9Zu/+cPj76XC4t0P1M2+29+c3trnwnerWfm7mCVP3ePl6P9d+xqstjn0dtNIWitMG3S4/njPZ5Mh7xm/8b734Z1m384nlOyy+4+EjTnSZunkyzsP1ft5J+63eKWT1hXn4AzDofghlJQBJAAAACXBIWXMAAAsSAAALEgHS3X78AAACInpUWHRSYXcgcHJvZmlsZSB0eXBlIGV4aWYAAHjahVRJtiQhCNx7ijpCMIhyHNPU9/oGffxeaNY3p/5VC5IAQkAhtL9/evh8Pp+PiwaNKZubAYDuugNcMH4ZIAN6A6ATo68kdAA8VQ1DkoEIq2EILiBiALIQDTISWvz3SSQNJHwnilWTGgC/ZMSa1Fc8TDznZH4rgWOtRrwQKGh8VyNZ8bAY9Ccj1EGXUI0JwNE3n3itxrzis7Sq1TgBiNMwesKo1TjfcdZqXBaiWRpLrcbbEjBLU63G9QGv1bit+CSKWi2W8+3QLDluF/wIBgBEaNQWNSjFzHj7/zgOP92EBap3v2BqlNi2pEbGVi0yBNwkcRPiTVxIJDVLRgJxEXGLRgAgLBASkiIIwlIEYgyBJCnC4lKExN6yGSW6SD961nvvQaxhBZq4rbptbX1HlJPSokN37t9m9957a5utDux7Xwk06WnWWOJ2yqgkPqW4e2urnmNPK0HMtq0Hkkc7ZbSXUleHiNMIoGy7r/ppEwAIV+Amv1rS/3ghgCz23ns+m/HrASdJMWT2chsBiS2z73fcLGd+3E8hZ05nQ81zzOW2n8Saj1VzwTMHZ+g6xcPg5ozLASM7Z/hl9kaPnPFQmrcyvm8lFKbrAQwAoegtYFy34rEXRSFP/qEo4tmQ0wywlwPyG5G/BJQXvF5wOR4k7m9HjlupR/y6Mp42RjhWxm+Oh99BvMrwD3UCiGvkpxuRAAAACXZwQWcAAAAwAAAAIACELJ4GAAALGklEQVRYw11YW48dV1b+1tq7qs6t+/TldPsSx3bbcRwncWY0A4LMCOYFXpgHJCR4QvwAnpAQj/wB/gR/ACR4QUKDECMUEjLOZew4zsRxuu122+52n9Pnfuqy9/p4qNNtD1tLpVKpap/vrMu31rdl/nAgIjSpF0kAJAEHGJwAAIQheqeARVqomCQZGUkjSYLmTAyAkCJiESRVNYQAaL3h8k3SzPj6MjEzsr7SqyoAcRABQItRVZ14kqifmNEkTZNiUZiZ934xm4WE3mva8GYGAA5UJ8YYIyCipiKk1ZuTBAhQBGZQFRKvTAgBaQBIeOekBqpa+0gBxFgAlmhqhixJzUKMRVEUx/3RWmel3z9xzrVX2+tuRb3WnrDKVFUEgKlCVWI055WMZ76AieipX0AYzYwQUZqZqJD0tKCqFJAxhKiqSZKooirj06fPMt/odlezhngFYar+0e7jxWLR6/Vc7ubzpNnM4BlDSDLvvQ8hnAYFIlCFRUDEjASgIGFGEcBIoSrMCFAVhgiKTxJPkgJVSeBBhKqaTCb5Ip4cD/efPP/g9q2soSvdTp7nAuv2Vk/2BoHFyWgRYxVjbDezRiMDMicNxqCqqhIZVZxZVK3zaRkgXYaMdeDMoMoapSpo8GSE1t6ihaCqPs3WV/VwPpxOp8fHRw++cUmq7XYzSbLV1W5vu3fw7Emn0xwcD+ZzF8vKQtlI09R7J6SXOldgEDEwAmdguMyYV/lEVWEkARExEkoVBxHWxeUSFefK6fTJ48dlme/sXN7a3vjVnf8NIQ6Hk1ajOZ+Nf/3ZZ9Uij0V+fedqM0v2nz5ut7LtCz1GC2WVJqmry1KgZKLqlbo0qLPanJrAVKgSRX/LPElxQF0smiDy6Ojo7pd3qXLjxo2r1y8fnwxORpN8Nt/u9fLF5OTFcRVKDWE0HJZF2O71IsOzZ0+e7D3tdDo7168miU9SJ6IhBIGD2KuKMpHaPwoFXkXq9Aak+/u//TsFRCEgEAljjFtbW+UiHPb765sbJ8M+Y9HtdAbDgWs0pSge7O1u9Tar+Xwwmy0m03I0XpgbjydZlk2n43armaVOJIqQDEIIIKBABK/iBYuAnT4HwJrx1CkhRosAIRBBo93ImunO25dv/eBmb231+rUrRTH/we1ba+udhw/uSoZGOzt38Vx/1D85folYLhazqpg3mj5ruNWVTqPhxcEsAOa8ihJiAhMEQVChCgXmhKcWT41O6IGq5kCjqPOTk9F4PF7rrlvKRtQHjx/d2Lk+mgy+evrwhzs3Xuzv0tmbb5z79LNPzm9utdorEoNkzPPx+x+812o10tR7DyCqUwCMQUUIUqm2JOolbb/GjmbwoDGS9GZBnYM4IS0E5+TChS1Nk7Z28uPhW29euvPRf2fN1pdffNE1vXnzxsGgf/B036duvbce5tXG2uZkfnL79q3t8+sA4Rws0CJIAOI8LADUusLqeC0rTl4RJgyg1Fe+fB7yUrxTQoRWVoExbWTjl6P5fD7dO6yIF4P+bDK/92T3hzffLWGffPq5c7K1uf7hj3+PrLqbqxffuDQc9VdWVtY31846l1CFqJlalk8gr/UxAIzLLrZkbVK5WHgHhFIYmS+K6ZhFkY/Hi/5gPOhLUzvnu73L59KVxjyffXH314vFIsbYaTXeuXFtcHx4sPd9S+3l84PMwTsyBrMgQhUIgrEUREWUU4O8uhcLdW45BsWpiVRgoSyYTxYn/ee7e9/f/2Z8eOwYm8pko4EktDvpzOZXL5z3Dd3b2/vi/r1G0795cat//GxrvWPTaW+lvdVdXUkTCaVagAUrF6wKVSAGxIAQJEZYiVjSSrBSq4SVWCFWKINYpQzK4FHmhqjOgbF/+Hx0dJyXtv/46ZuXtrrd1V6ruRhNJqPZlfbq5999/Dt/+LNf/tf/nEyH585t73338OrVS3E8Pnl+MJnOi7i4fG1no7cJ79Sh7vPISwCwZYCERN3TjQCFZFxGE3FJV97iXCGIKBZlcyV799zbIdhsNnvyaP/x3r6Z+Tx02i6Kv/7WO8bFX/3ZT37xyZ2yf9Ta2n73vZ1vf/Xlv338+R/97MOVjc63X99fbXduvfuONBJTAlDxiBGAWKQZSVn2BZ4lDYwAlDQzkF7LEmYQyUSTdkvTzNuiZLz25vlOt3N0cPTwxcH7W2/9+NbN0Uef3Pvs6w/+9KcraePb3+z+6NKF+cHLvvN/89d/2SQsTSdr3clwMh0M1nvr0ki4yI0iQgBSu8dYOwxm4BIEyTrTEY1mHrNpZD3KiMIhlLEokljKWueyytsX3ji/2rqzuzt4Obh95eLd3+ztf7Xv1e2sp8OXw73h8Od//FNNtIh5Rqx322tZWoWimo1c7hQi4mgBxtPpA3VBkXQ0M8BOh5VoS3D8j3+CACqsR4EYzUyIalqaCqCxyIsB/uFf//lPfv93R/2jf/z4m0Zmf/6j977af/wXH/7B6ubK+dVV2+g6D0Yzg4OoA0kRrYoiEXcarFfzq7IueJKsYZktAXl7MRURiARakiQ08xAACHCGybj/i3v3ZoNyDa3/vPPg59cuf/fi4GKjPRmH99cuHT5+Ouv3ipV5b2ve2lxRdfPJLMa4ttKxEEl68ZH52bh4xkDhbLI2OYNiBpL+cHfmnKvfq2nf+eWXi2L+6PgQh42nk+GVc1uf7h9+f1T8ZOftXz76flu7L07Gs7FttCYvknH74PiDt24kjWa/PyvLElupJ2OMZFXBROS3hnoz8sxBS9+YYemhrw9L55xCFCYSalgR7Ehy/+DFnChC0kq3m37j9nr2L7uPnrw8UBb//t2emGsnybW8OW9M3uhc+fbprNWW0Qwh6MwKAQGEEIhlpccYSVLl/wkPM4unqEj6+7MyUZeIpj6pRxOJjDGO5qNpbNLsWTiSyt/dex5mR1Ui+9Phxe72w+moI1mmViSbG7xQNNpHlrhKBnkkcbIwi5WZGegpgMYYq6oCoKoiamZAfB1TWCoq+o/2DxzEiU/TNHXeBCGEqqqKGKGIDPOFTedDY8x8M5HEIRlXi5D7TtrsVpv5cDbZyB69eL7a6IjIfD6NNBHJy1A3tcRJCOV4Nmq1OiqZUgFznonzZVWIECoqXjWpijJGevVipFkZqipYKt6JE1XXjj5tJHk+n41jptrtrifqptNpq9WaTMcqyXon9VlqxHgyi5GjWa6qeZ5DJcsyM6OomVm04WQwnY3XIGkCQGEhzktjORoN8yp3zqVpI0lSUNXB59OhiChE1RdaSK0XSTNqoSSbmQe8F8Bi4jRN00WRr3TY7jSzJAEAQZIkCBUQo1aqmtSTHmJkrGApQtu7lodKKXDQGCyaaJo4mgeAEEPM667sd59/dyoQpUYDUQBCpZiqqmrNIgCEIKlgWS1OTl4OYl9gRoo40VgrRhGpP0G9qMZgFieTKgaKOFXQgolaCE7MBOrgnEO0aKWfLI7rWRaAnC4ATv3ZpiLiVQFYoCmzLAuhHI5eMsInIBkNUXTZUAERAVlvFSrziZoZFxOaaK3HAJOw1K9ArQXKMl/MJ7Ld6Z0l/1m86qMCGEXEe7+EW0+g4iFljCHxLQGcWq0NUp/Ur52K+Vc3ohrrFrs8PzhlJgBiKt7MYoxVKIpiIRudtdc9QSxheTPnHIAYCaNzTlXNzKg+YWRQpgKQRjGIB8Pyb0BJnv1ikFoYOwBEBKAEqFQlaRalFtqkc440n3IZrNp7Z4LExMpgy4SAVBaFVp9zhBCIaBQnDqhPSQgKIAJPksal+AG8ogpRnQCIUVRFoSEE9QIaLNCpqiPFQUK0/wPxadi/ncvxsAAAACV0RVh0ZGF0ZTpjcmVhdGUAMjAxMS0wMi0yOFQwMjo1NTowMiswMTowMGbLlncAAAAldEVYdGRhdGU6bW9kaWZ5ADIwMTEtMDItMjhUMDI6NTU6MDIrMDE6MDAXli7LAAAAEXRFWHRqcGVnOmNvbG9yc3BhY2UAMix1VZ8AAAAgdEVYdGpwZWc6c2FtcGxpbmctZmFjdG9yADF4MSwxeDEsMXgx6ZX8cAAAAABJRU5ErkJggg==</binary></FictionBook>
diff --git a/test/fb2/images.fb2 b/test/fb2/images.fb2
--- a/test/fb2/images.fb2
+++ b/test/fb2/images.fb2
@@ -1,2 +1,2 @@
 <?xml version="1.0" encoding="UTF-8"?>
-<FictionBook xmlns="http://www.gribuser.ru/xml/fictionbook/2.0" xmlns:l="http://www.w3.org/1999/xlink"><description><title-info><genre>unrecognised</genre></title-info><document-info><program-used>pandoc</program-used></document-info></description><body><title><p /></title><section><p>This example test if Pandoc correctly embeds images into FictionBook.</p><p>Small inline image: <image l:href="#image1" l:type="inlineImageType" alt="alt text a small PNG image" />.</p><p>Paragraph image:</p><image l:href="#image2" l:type="imageType" alt="alt text of a big JPEG image" title="image title text" /><p>alt text of a big missing image</p><p>A missing image inline: alt text of missing image.</p></section></body><binary id="image2" content-type="image/jpeg">/9j/4AAQSkZJRgABAQEASABIAAD/4QOoRXhpZgAATU0AKgAAAAgAFgD+AAQAAAABAAAAAQEPAAIAAAAUAAABFgEQAAIAAAAUAAABKgESAAMAAAABAAEAAAExAAIAAAAdAAABPgEyAAIAAAAUAAABXEdGAAkAAAABAAAAAkdJAAkAAAABAAAAKIdpAAQAAAABAAACXMYSAAEAAAAEAQEAAMYTAAEAAAAEAQEAAMYUAAIAAAAMAAABcMYhAAoAAAAJAAABfMYiAAoAAAAJAAABxMYnAAUAAAADAAACDMYoAAUAAAADAAACJMYqAAoAAAABAAACPMYrAAUAAAABAAACRMYsAAUAAAABAAACTMYuAAUAAAABAAACVMZaAAMAAAABABEAAMZbAAMAAAABABUAAAAAAABQRU5UQVggICAgICAgICAgICAgAFBFTlRBWCBLMjBEICAgICAgICAAZGFya3RhYmxlIDAuNy4xKzkxM35nYTA5MzllYQAAMjAxMTowMjowNiAwNzoyOToxNgBQRU5UQVggSzIwRAAAAZM/AAEAAP//NuAAAQAA///jlgABAAD//2viAAEAAAABh0EAAQAAAABNLwABAAD//+62AAEAAAAAKd8AAQAAAAFHQAABAAAAASNbAAEAAP//py8AAQAA///Z7gABAAD//4X3AAEAAAABWGsAAQAAAAAZVgABAAD//9qsAAEAAAAAUBMAAQAAAACr2QABAAAAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAEAAAABdAAAAQAAAAEAAAABAAAAAWX//4AAAAEAAAAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAVgpoABQAAAAEAAANegp0ABQAAAAEAAANmiCIAAwAAAAEAAQAAiCcAAwAAAAEAyAAAkAMAAgAAABQAAANukAQAAgAAABQAAAOCkgQACgAAAAEAAAOWkgcAAwAAAAEABQAAkgkAAwAAAAEAEAAAkgoABQAAAAEAAAOeoAEAAwAAAAEAAQAAohcAAwAAAAEAAgAApAEAAwAAAAEAAAAApAIAAwAAAAEAAQAApAMAAwAAAAEAAAAApAUAAwAAAAEAhwAApAYAAwAAAAEAAAAApAgAAwAAAAEAAAAApAkAAwAAAAEAAAAApAoAAwAAAAEAAAAApAwAAwAAAAEAAwAAAAAAAAAAAAEAAAAyAAAAHAAAAAoyMDExOjAyOjA2IDA3OjI5OjE2ADIwMTE6MDI6MDYgMDc6Mjk6MTYAAAAACgAAAAoAAP/iAxhJQ0NfUFJPRklMRQABAQAAAwhsY21zBCAAAG1udHJSR0IgWFlaIAfbAAIACgAWABAAGmFjc3BBUFBMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD21gABAAAAANMtbGNtcwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADWRlc2MAAAEgAAAAUGNwcnQAAAFwAAAAgHd0cHQAAAHwAAAAFGNoYWQAAAIEAAAALHJYWVoAAAIwAAAAFGJYWVoAAAJEAAAAFGdYWVoAAAJYAAAAFHJUUkMAAAJsAAAAIGdUUkMAAAKMAAAAIGJUUkMAAAKsAAAAIGNocm0AAALMAAAAJGRtbmQAAALwAAAADWRtZGQAAAMAAAAABW1sdWMAAAAAAAAAAQAAAAxlblVTAAAANAAAABwAUgAAAEcAAABCAAAAIAAAAGIAAAB1AAAAaQAAAGwAAAB0AAAALQAAAGkAAABuAAAAAAAAbWx1YwAAAAAAAAABAAAADGVuVVMAAABkAAAAHABOAAAAbwAAACAAAABjAAAAbwAAAHAAAAB5AAAAcgAAAGkAAABnAAAAaAAAAHQAAAAsAAAAIAAAAHUAAABzAAAAZQAAACAAAABmAAAAcgAAAGUAAABlAAAAbAAAAHkAAAAAAABYWVogAAAAAAAA9tYAAQAAAADTLXNmMzIAAAAAAAEMSgAABeP///MqAAAHmwAA/Yf///ui///9owAAA9gAAMCUWFlaIAAAAAAAAG+UAAA47gAAA5BYWVogAAAAAAAAJJ0AAA+DAAC2vlhZWiAAAAAAAABipQAAt5AAABjecGFyYQAAAAAAAwAAAAJmZgAA8qcAAA1ZAAAT0AAACltwYXJhAAAAAAADAAAAAmZmAADypwAADVkAABPQAAAKW3BhcmEAAAAAAAMAAAACZmYAAPKnAAANWQAAE9AAAApbY2hybQAAAAAAAwAAAACj1wAAVHsAAEzNAACZmgAAJmYAAA9cKGR0IGludGVybmFsKQAAAHNSR0IAAAAA/9sAQwABAQEBAQEBAQEBAQEBAgIDAgICAgIEAwMCAwUEBQUFBAQEBQYHBgUFBwYEBAYJBgcICAgICAUGCQoJCAoHCAgI/9sAQwEBAQECAgIEAgIECAUEBQgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI/8AAEQgBqQKAAwERAAIRAQMRAf/EAB8AAAEDBQEBAQAAAAAAAAAAAAMCBAgAAQUGBwkKC//EAFQQAAIBAwMCAwUFBQUFAwoCCwECAwQFEQAGBxIhCBMxFCJBUWEJFTJxgSORobHBFjNCctEkNFJi8BeC4QoYJUNTc5KywvE1Y4Oi0iZUZDZEhIWj/8QAHQEAAgMBAQEBAQAAAAAAAAAAAQIAAwQFBgcICf/EAEQRAAEDAgQEAwYEBQMDBAICAwEAAhEDIQQSMUEFIlFhEzJxBhSBkaHwQrHB0RUjUuHxBzNiJHKSFkOCojRTCLLCY+L/2gAMAwEAAhEDEQA/APstdMAYBGvaZl9gY610gKfiDqFyh0Suj1wdAPQSeg9sDTZ0UoIfj6aGZSEroXGMaGYqEqukfIamdAqukfLRBUVwo+mdEuQlW6BnOo5ygVigP56mdLN1foHx0MyEKwQfHTBycOsq6BjGiHKFUEHx1JCiuFAOpITKgoHpjU9EJVdPp8DqI5tlXSPTGjKit0D11M0KFW6fn30WvKRW6e2caBPRMNFbpPf/AKzohyhCSVyfgdSUQFfpwfTRzKQk4+HbUzJFWP01MyaEkJnAwM+mmzoR1TWkqIK6miq6aRZYXGVKnI9cEfoQR+mmJIMFAshGIAYKSOsjOPpqZ+igburlcH4Z0MyMFJI/XULoUhJ6RnONNmQhJ6PXvpsxUI3SShH11A5CLKxUkYI9dHOpEJJXIGc6mfooAd0hkPwBOi1yI7pJUjOiHqEJJBz27H8tHOmISCudTOEggWSSnft2GjnvdEgJJHx7euiHlQJBUYxqB+6m6Gy4+ujKASCv5HRzJtEgp2ONQFTdIKnv6Y0wejZIIyMdz+ujnUkpDLj6agegEMqPkM6bNsiEMr8vT56mcI6pBHzGiCgUIocakqQhMv076aUShlT31JSpBUdxjRzbowhlPl30Q5SEIrnUzKQhMpGmDghCEyE9sZ0A9EJDJ8x30cwUIQmQ57DOmlQITIO/bRLiigMgPqMaIcpKEyYyQO2mD+qiAy/IHvoZkShsnzAB0S9QlBK/D4fXT5+qhQmXPcAk6AepKCykg4zps6KC6egPcabOiCEBk7kgfu0Q5QCUFkxnGjmTaXQGX176YPlKTKAynHV302aNUSEArkjI0c/RAgILDue2nDksILKB37Y0Q9RAZcjP9NMH9VCDupxOpx6d9eAlVNch9B0C5WJXR+ulLkFboP002ZQFX6D20ZRV+jUkKEXVdHbuDj4HQDglVdGPj/DTAhMVXRqSgrFPqSdSZQ0VBPTPb56kpQOqv0DH11ApZV0DRlNFlYL2ORg6gKkjQKug4+B0Q5AC11fo7/TUzFPKt0evw1MyVV0Zz8NEORMJJXGpnSgXsq6To50wVdJ7dtTN1RA6q/QD6HQLlIScH5aIcorFcn0OdTMirFc59dTMgEhSjNIo7lTg/uz/AF0S7opCUUB+g0M6isU+XY/P5aOZRcupLhXbe3rJZKqjxZ7jIGjnSRmRKhkJXpjOfLV/LdT8DIo+L62kB9PNNx+X39JTkDVbTeb1TWmv22s08YFfO9FCoIzNK0ZdFUk47+W2qaTM0joJ/dANMFbHgHOMMM41XKVJJBPTkhsZH+uhKm0rHWyup7rRR1lKwePrkib4YdHKOD+TKw07xBui5pBgp+U+RzpQdksJPSf10ZUhW6Tj07ageoQkkA6MqQklPlol6kJJT9dMHKQkFPiR30cyBCSUB1A5EJBQ/PUDhohCSyYwMaaUoCGy/Eagcp6pJQ/nqSpF0PpGScd9EuUIvKQU+XbRzqJBU5xjRlGEMoPXRzIhJKfLvqNd1UF0IoP104dCMhIKEenfULlPRDK/MaIcpKGyY76YOUPVCKg5OO+pmMolDKn5Z0c6CGV7k9tEvRhIZMemdEuUQiuSc6OYKEITJjPy1A5EITIPUZ0wUQyvx9DqSpCEyfLuNQlSEMrnPbTZlIQSnzGpmU7IJU/LA0xchCCU+f8A0dEnojCEVwe4GofVSEFo/wAydNmQQmTHwxqByl0Jkz6jRBTAoLp69m0Q5QDdBZNNnUBQHQ9+300Q9MU3ZMfTRzpQdkB1z9dNm3TdkEpg57jTZrIFAZPoTohykoLR5+GRo5lB3TdlOPidOHjVMSpyMpI+WvArIzVC6D393RJVoSuj66TMpF1RQd/XGnlTdUE+edAlFX6Ae+dCVFcqDn5nRDkFbox8dGbKQq6BjGTqBxQBKro+uoCoSrdA0cxShXKdu2pnKOVW6PTUDkQqCflps6gKsE+fbQzo6q4T6/lqZ9woq6O2pn6Iqug6Oe6EQklDnsO2iHoZVXSRo5kysB9dQlBWx2z8NFRVooBYqOp6LjV0FQ0ahkSWEE4LqfdYD8mA9O/vD6aaOWU4FpTC03ACSa01c0k9bEVxIwXMyuSUPu9s4BHb/hPz07x+IJ3M3TG+VM1oS4XgStLQy0pUDq6EppEVmErkZJU9gSB2wM9snQZDuXdOy5DYuFmXraW2wWiKuqYUlqGSBGDHpkkK57E+oJ+J+Y+egbkxsqWNcRJWU6ckgEHHY/TSSgub8pbFi33toW2OpqrXe4KmGqttfTTLFNR1KOGRg7AjpLBQykdLdge3cacJiPCeHG43HVWMeQC0biFzXf7XvkDjm37p2hLctq1sVPFcY6KpeOBKmohPmiikUk+S6zRFBICMEFT1K51rY8UKpY+99Rex37yNt+xVmGa19iJmdvv6LJcZ8sLu+3W26S0F8+974sN3jtMlKqTWOklCokdSFJEbAr1N1HJZmUZ6OxxWBNM5ZENsTNidbf29So9oIDtBFup6/WV1uO4yy193daKrlp6VVhJj6WLydRLBVByTjobvj17Z1gDYAM6qoiAAtK2NPRTbj33bqD2wCgucxnjkaRQklQfNXCt2YYVsMD26iOxBA0VQRSY47j8tfzTV3XibwPyXUSpHy1lzKpUUPy0cyiTj9+jmRCSVHyGiUFYp+eoCpKQUPxwdQFRJ6c/DtoyokFB21FFboPw1JQSSp9NQFGEgqP8A7abMpCQUPwxqZuqEIbL8x21A9QhIKA+miHqRukFSM47/ANNM1ykJBUfLUzbKRdIKYxjTZghlQ2TBOjmUi6GUHwOhmKKQyeue+ma5RBZMZxnTZ1CUMp6g5zoB0KNQmXuB8NHOoSkFPTt202dFDKEdu502YKAoTJ2+OpmCEoTKfiPrqZjsmlDKZOc40c5COyEyDtnB00qIRQj8tNnRkITKT89EOvChiEJlwcYGjmQiUArj8tEOlEJDJ8+x0Q5BAZPUdtEOUIlCKn4DUlQtQmXPfuTokqbILL8xoyohMvx9fz0Q5RBZc+moHIi2qAyaaUCgMnx0Q5QSm7pgk4I0QUyCyHOO+mzdUEJk9cgnRzKEoDJgaOdQlAZCfodNmuopwlcjXgyZKqQipGhmKZWAzqSmjol9OfhjQlKkY02ZMG9UoIe2fTUzFSBsrhPnjGpmKUBK6RnONQOIUVujsR2zo5lFcqNHNKit0frqB6BCt0fqdQORVdH11C4qQrdB750Q5RV0H89EuQVivSCWIAHx1JRV+j8s+miSoFY9hkkAfM6kqSr9I+ulzIqxU/EaYGVDCrpOceh0QUEnpGM41JQgKinzGiHKELXb9bq2qSmqbXBRyXKncSwGaZkUN8VOFYYYZGcZB6T8NW0agBh2iYGAZXGNw3OOOS/bwtFXJR1FuqzRwRVLiNaSpkRYvLqgpbEDtMnSxGFdeoHB6jupsjLTdfMPpO3ex30K1U3yMpGn1i6cx72NFvXbNkNnu021qiCaioJkzKsssULtOlTHgCORQFXBOGLEDI9IaOZj3mJ1O0AkRH3+qRzRlAJh33+X3KjZ4gt03ba+zK2k2zdrYL9bqykqKCGVZatrlRR1YaGKFcftJBGXSSE+8ysjq2UZ9bMIMz2l03+F4v8AA2vte2y00WG8aQfhpJ/P5RF7Sf2zycI9mbfve7glBuy4mgqqyjAZlpzWuojEJwDLEnWqdYA/AxYKSQMVXCxUyMFhafQSZ6TcrKGZiSNAPv4/ei6XeKlJorlQiGOenWJWqWyCYkPqekj3jgEjHy+eM42E66Kpg07rz2tXJNsjpeWJKRabc/8AZjeX37FUQ1cK1c1TJ5TGJ6dsI83tCVFN1t2LjqxGVXXoJJFM9RliDpJ0IuBBn0B1W+ngHhzmPNnXnYCBr/4/ULeuMb7e6PdXKJ21T7u3NSV1ZBd6ZKuuhFFY4A0sclHGoVWjZK6GbrXplkPnZLAdlSqA6kwOIEW3kzEfDLMaC3Uqirlzw6dJ0+Pz0N+ogRZSlqr1BsW07kku8ktatHTSXSaRCWnqM5JRUUdyOjy1C5yAg7sTrkn+ZlFMdgPvrqe/ZV02Go4Rafp/j9yuacXXeppauTcd2ucMdmu9BNXSLPD5UtBMJ0lCSscA4SqlDEBQGQ9sHJ6GNY0NyAXbAtpERb5DXqlq5nvaG3bfa/btsRH1Ui4JEqIoZoyDHIoZTnsQRn+uuS61lWm1BWQ3CnFTB1eX1uncEEFWKn1/I6JBGqL25TCeY0JSkpPSPlokqaqxQamZGEgrjRBUKTgfTRzKSklQfhqZ1FYoMamcqJHTg49dHMokFQfhqFAobLjOPTTZkYSOkE5xoyiklAdQlBDKnvoyokED5DOpKMIZQ/DRzIJBHqCM6kqQhFPljUBRKQR8CNEOUQyo74I0c51QIQyuSQRogqQhlMH6aYOCkIZX17aMhSEgoPh21A9DRBKDOSNGUUIqfQDOmzFSEMrn46IKiEY/U/HRkqBCKH4aIcmQnT9+mDkQN0JlwfTRDrKRuglDkYxqAo9UJkHxGdMXKR0QWX1GpmspBQWU57aaVNUJk+WNQPMKeqAyfD002ZEBCZcflo5lIQWX0xoyiEEr39B9dGUMqCy+hPfQlDKITd1HcemmzIwglPn6aYuQhCKgep1A5SCEFkHppwUE3Zcj0xqSiApvMvu9gO2vDF0KtDK4GSNLJUVsD5ahdOicq4BPp30M0JSrAH4Dtoh2ybQqgPlpp6pi3qlBfoTqSkVyp+WNQOUVdB+R0ZUsq6DkD01JQVug/LUJUKrpPfUJUCsFJzgaMqBWxlimfexn+mpKib1kpgpamZfxIvUfTsPif0GT+mi2JTNbKx1+uMVus9wrxiaOLCN0nv3YKcfM9/TTU2y4BNTZJgrH2Hc9Nd6FZZg1NXrMKWenZSrxTB/LZWU5x74JHfuuD3zqypRLT21+Gv5KPZ00WUu1fDQ0ZqJCxiEkYJAzn9oo6fzOcAfHSUwSYCDWXhZVvdYqxGc4/XSAykDSqx3x6aOYoQqx8PTTFyirpycYzqZ1AE0pqqmrYPaKeRHjDMjEH8LKcEH6gjUJITOaQYWsTSXdK2tthnpah3V5oYiSJCvu9LI3pgNnKt8/xemrhlIn7+/uFY0DVcf3fcutmtu87PdaSarMMNtudHCjGRj78lNM464THmE+7IHjbrHYntrpYbl5qZkCZH5EaGb7Qe6cU81m2MfnZcK3byfPsCx7yum59o0lx2YtqpqnbNTArUSU1XIiI8M87jyYahQtH5ahwknSVViwKjoUMO6qfDa+HEw7e06gakXdNrbqhxbSLOWB2Pr1I0A6ydk4se2rXsyyis3ed48gcibGKva77uKVRLd7KMyVEtOUCQwq9OrIyRop66SLAKorBKmLJ8gDWvmQNibCdze+sQdlZ4T3ENz6X0H5R8JPe5W3VVRx9zBtG3RrfZaVprbHRCoo4eiopqmQdMUkZfICdLyHHSylVb1C9Qppuq0HEtFwZ7WuZjeQOn1V1RodfUGYOtjaIPXvutbr9wXb/s8rtz33dF0uG4IaqWkSvoa+OGO4vIvWY5xh4IllwpTq64oxlWPmHoNjHtDw1rQAbwQbRvMzbeL9LXQOGz1MhcWgaxHa0ESfTc3NlFu07tXatTu3kHatTZ+RrRuFNyUCU0spjWonpqh6wVFNMxePzVgqrqwL9DSRQxAq3UOnUB/JFIkgDKZ7aQR/4Wvcm8q+thmnEh0X0jWTAP0gibbbQsxw5vqpoOYJNsVu37gzihhqau9U9bVSia2VlZFVx3OveT9lHNLIktOyqG6MydZULovZFJ0RAOkDVocIG52M7xaZSV3seQ4G5mO85RpFgNpvp3Ui/EFu+43W87Jsu1ZLc9qorlbKu41E8yJAtUKmE01PCzNiSVTmZh0tjMIOWZVOHh1GJe+0yB10MnsALfPoSGp0AGkPFyJ+E76anTsL2IBY8r7Nv9qvdNcKzclTt+03qjvNHWSxU8S+05tkk4eaUq8kbO1M8RVAxeN16elhkW8PxDC4M1iCBJ/rb84mfUXtrW+tDC9oFj+hFtgANzN7qR+3a/7i27Z6Vq56u/Xu4TyxR1EhE87lcyEqT7gTA7L7oUIAPf7YKwzvyRZov/frM77+iqIDnGpsI9OwHwH5ldXtlugtdvo7bTdXs8MYjjBAHSuPQAdgPprHVrFzi46rNG6JTzw1SSvCWIWR4m6lIwynB9froOJGu6nZHK5yOx/pqZt1Ekp+7UzqSmtPMk6yAFTJGxSQA56GHr/r+R0S6LokEFFGGUMO4PcH56OZQFDXpbrAOek4YfI+v9dSVCqKkdyO2pKiSR6/A6JKBQynbt66JUSMH641CiAk4+mNSVEkpn0wNEGFEMqfiNGUUgoDnI1MykpBQg/TRDkYCQV+Y1CUIQinc4zjRzWUKGyZHy0cyOiQU+I1MyBQiCfjjTBEBDZcZ+WpKgCGRn10cyCGUP66kpkMgjtpg5CJQiuPTAGmL1MqGVB/PQLlIQ2XB0wdKEILKPgBqB15TNQmUemMabMgZQymO/ro5ijMoJQflo5kfRCKfMYOoHIygsuM9johykILL8v5aObdSEBk7nt30Q9GEJlP1A0S5SUEqcn1OjmUhBKY9NMHIlBZQcjt9dEOUQGXGRj6aYOUQHX4YOmzIwgsv6n5akqQgFDpid1AJQmXP56kpYQGXTByBFlNorgEj014WVUrY+nbUlRWwPz1EwV8dhoI5VWOx+WiCpoqx3+OjKJCrH7tBAq5Uj10Q4pVbRlEhXxpSUIVYPy7aM2UAVsEfAjRDioAr4+OO2pmKMStD3FuZNvyUd2njeW2wzSUtwkUkLTRsR0PjHvHq8texyBJ6fEaaNMulo1Onf7/AEVzKc8vVB3pfWsFPdaqoigqKNKeJ5YXl8oxqsg8yR3/AMKKmS3ywMkDJEw7QSP8o02ZgA3Urkt4vlxodvbYssNdVVFHdq6BKOtKtIqRtIwRWlDd2KlR1EscqjEOHI1qaWlxcRED9On30tCvDRmcTt8/v6arS7hzWtrtQ82Kvtty9qhs/tlxpWhpai4xpJ0TSSKMxIpjKOHVe7wgEZGbvd8x7XOtwLTv8td0zcOGv5rzGgJmTp0+K71brm122JJHQ11NXXRIizMYyvXL1GSMeWxypbCFQT3BUg4YE43hoqdB9z/dZ3NLXSR9+q3SW4otJS1sgdkE0C9lwcucHsT8nHb1/XtqrKJgKtonRZyNw3utlZAASp9RkZ/odVk2VZCX0gZ1GmVJVdH0yP46mYKErC1tDUo809D1SRyBRNCHIJwwy0eewYr1Aj/F27gjvY143RzLEVtWbrT3SW1VdFFWRIDA8jFDE4JDlxjqQd+nBHqPyOmAiA5O0CRZc6qa6rroLrtuppqy239I4ZUQt1w+xMOhqiB0XuqGBmCoSyO0fUvvAHZoBVHlv89YPrMfOE3LMG/7rld43ls+S2yTbut9z2/ba6gSz3p7Ksaw0zVTPC6yRHJk6usZEkWAGGR8daOZ0tbczadbDY7R2KuGCgDSG3g6GN/v81onAd2p+RONt5eH3llLpFyds2WKyVP37WwS1V8sbZprdfFaJinl1sNO6yAEBaiOeMke6TdxB0OGIpRlfMxoHalt+mo7HsslFzqVUMIu3QwRIG+n3EqLOxPEHtHghdn7c3pHvHe1BYCLFUvR2qGlqEvUHXSxU9SSkSSrLFRe0QMpfsfKLNJJGJd+NpOrtdVbaepkQRJI7jQ6fS1uHcQfBdadwDNjEECYmbSZPxCJfOaGoeWNvcTUlVvO68X7rs9vulfa4Nr1FHV7et1RRzzJFUSwhZkM06xwiAqpZJJXLgBSYMKXBxe3maSASRBIgQAbGBLtTECyvZWy+G5pAzWGtr3cTcDTKJF3G2hXNeVuJppdvbM3fwvdaDbnEm2N22S8v7ZY5DHdY+v2B6ny2WExU8Iq2qCz9Sz9IfowQZN2HdU8QNqWeZAHQG43idAALieulGIfTZhyLOAu686RIG/rrYEbFdcuVJyXx346tubF4otu171Bf9n3lLrT3mjehpNm1MEtBIK6iRJ2kq45JGQimWOJUkqyfNUTHHOwz6dTDudUJa0RcEEm5EaWsYkm4BsYVWOrOa+lmOYOJsJuAJJJIixG0m46gqXF62BLZ7XaKabeIuFXQXZax7DaaaCnStmZaj2h1Y+ZM9bUJJIxmLorsQvSgbAye/Nc/MG2IiSTYWtsA0WnU7yVspscQZAF5k66gg/DYAQFovLd6o948s+G7j/j+ONKK4NedyVtdDL1iz263UtNSgRB5F6pZDdI6fsQE81m6upOlruHy0ValS4AA9S51tjblnS+XoVkxbCGMafOXCJ2gEkkSDoYF7FwJClbY9oXiK9JuC81CGrjQRQyTOEeOIsMgRQN5ahiqnpJIX0+Jxzq+IZlLGb/AB+p/bp0vZ4gIA+/1P73+Gs0/JFTcbu+yrZJPXXuCVJ7lUPC0K2undWYGTAIEzDBEBw3fLdIIyzcMI8Rw5fnJ6D9ToO5Vr6IaM3XQddvl+e3VdSgvtuo6RKamgnZlqWpKaJpMvO2V/xHOCfMyS2CCGz6ay5S4z9j7hUmiZknun9Deqa43CppaZo5adURo5EcN1nv1enwHugHPc9X/CdA0yGhxSVKRbqswroxlGQChIIJ9PrquUmVaFUMDfLzbqIU6xVE8HtEUfaSpdoY+tmYY8sCMKev1Y4HyzsYZYCdp+An63OnxV4BADj01+cR92Wbt10iq7nX22BE8uliVXKuW6XDEdI/7vQfXIzg+ms+Uluc/f2bKt9OI7pVonWsrb3NG9U0aziHpcYEZRQCACAQSc/PtjTPGVone6FTYLNFO2kDiq0kr8xoSokdGjmUhJKkfA6mZRIKgZ7dvXT50Ugp8tEOCiQVI9QdTMFEMoPhogoykFSProgqIZUd/gdEORCGUI+GpKISCMjUa5CUIqR9dGUbQhlfp30Q4qAIZTHx0Q9QBDK5z66IciG7oRU/HtpsykIZUEknOpKMQhspBx31AVA1CZfkNSUcqGR9dNmtCmVBYY+WoSpG6GVB+miHIZUEr69tTMUwCEUx6HI0cyhQyvf0GdNnCWLIRXGM41M26bVBZcZOpnRhAZckY7HTZ0sbFBdSR3GDqByIQipGcjtpgUQgMvf46bMogso7k6AcoEBl9cY0+bdSJQWX4HOjnTEFBZT8Rpg7oiGoDL9e2iHKITIP10ZQATdlz8dEEoAKbRGR3HbXiS5ZlbHy7HQzKKxQaBcd00K/QB2xqZkXKukfLUzISqK+mRjRBTG+iuB27aJco4KsagKRVjGO2mzBGFWBqIwkgp1eWGXrxnpz3x+X6ahQITGvrYbesNRO5SAE+YfXpTH4seuAcenz1BfRO1s2TajvFPVzpSANFVBZWkjfCtGEcLkr8Ac5H0GnLDlzbKOZBWBv37CH2qlZDaK7KV7N0yRqrKVDkNnKd+lgBjBByMEF6XfUaffVM0TYrVL/AEtXaLVNcCovdJSQElZqfzJ6VekxqsyDPmw48wMSCUBLEMF6lvY8OdAsT8j6dD+fZBkAAO0+/wA1yvbVtse5uNL1snoXyqOrFx2+JJ4jLa4+oPSEyA4IUlAjg4kgliKkZONVeo5lQP3Ig636/wBxsQVaGnODPrHbXe4Xlty9v6svexOfKvlPan3DBaYLnPyBarbUeY0lVJb0poUBRcunu0dUlRGI0OJ0LZyB1mA0g1zDmP4ZtN5J/MXvpC6VJ2Z5psJaOtzEfqQQYH+ZlcRcm3y57R4y5YutDRxbMvVpiqaimjqvZkqameOGQRwxTEtPJIVwqu6lRTOMymYOcuMosBNIG409L9LCJv6jSCs4OYQ0GTF97D7077iF0bZ/J1GlbT8eWu90t9jtm5Lrbon6et5umV6gUkvUQRNFHJTh+xAHqq4JGTww7+YbS0ftPpP31d9GA4u1t8JAPz6KRcl9rNr3yrqrya6otNVNFTUkzBCkQLkJ8Qe6iXLHH4B8++UUw5kN13+/lZY8oeIbst3h3B5tDeJzBIs9FUmnlUggN+FhgkY/C65+R1nLLC9iFU2nzAdVi7PvCh3FYpLnZ2jrnhpo6kssqkM+TiMkE4YlHBB9D+7TPGXXSVbUw7mvDXWlZHbm7dv7rtBu9ku1vu1u62iMsEgZeoZBU/EMCGBBwQQR8NCtTcww4Qs7mmbfd4/MQtW3HbbZaLw98pbcKW5VwSlerplaf2tOkALWU47zIAvSHzlQB7y6vpVi5uUmR00j0Ox+7p2Mkei4Bfd9vQ2qr2atNuKx72VPa7KlTFUSQR1SKpNLT3IReVOis0fqeuVH6ChcEa6LcMZ8QRl3OlupG29ttdE1NwAzPudIFz/cnquccYVnKXI+1d0U1PxzS7c36N8Vn3jDuOthqae1vHIEneiMEjSiMH9oiyIuY50yq9Z1oqtosLDn5cu2t5127a7dkzalnl4k6RfKdIuRe1xbX5jCcteEGwbw3XtblFd+bY29y7bYaaOzNHtinFsiaOSab2OsKt7RLQysZ/OQOGGIpk6JYELW4TjIptyNaS0m5LrmwFhESLR8rgrPim1ql2ACBbWdRN+h6RFttRxOm21tvnHcHic2Fs3jraWwt3GzWqHkXZ9/kiqLZQ7gner6h5M8Xl1NJWU0fmpcKaSPzeqN8LI0sa63VXU2U3VHktDuVwBBLQB0OrTaCDuOhVVGoKk5pzEOEEyRMAdCAfqIMKHe59lczch/9qXgt3DuCm4erdsR1++rbva5U1yq7puG3RV/TJFFc1mp2nBjeOhq5pImMMC0pPtBljliudUptDcVdzRAyiIm5FoMSRMA3cSBEGUwIrkGk3krOGuaYFhazZgcokCGgE6gCWe0PGNxdyZxPHZr1Rbl3JQ7hWbYG39pQXxZL9fq+eHoFFFRySh0kRQzLJOEjhihmkldAj9OB+Dq589MDP5piwDZOYmD2JidgASRO8eCKRLnZWtFzEiTaALF0mbC53gCU38EaUW8ardXiC5atEdz5Tvlisdu3Bda9yKGO6mKOorIY6mWQI8FEBaaRQCAs61En4pcjbxd3hsbh6AhuYkdSLwYvdxLo/4gD1zYSnVc4VKr5c1sQNW7BsjSWjM6NXOJJIgCVFPyVDvHj+6X20JX7O49ttwvdklsctMjXGoqY6uSkBlWL9rFG0iOscODPKCC3vME1x3MDHtDyHPcG72E3joTGv4R6XHYp0z4jiASQbu001jsP6vlG/HPD5bLHunxNcqcnU8l4g4/jqJNh7DFOj08FJRUEUdRc6ql60Mb081yiqlRYB0xvQHGBIoGvEVXtw0uu5/OZ6TDAbzMEmTqHeq5rg51UgAQzl/+brv+UNad5Bnopkb35G2QbhFZbXuvdt8rpKY+3z2uGuurUFIzMhYRUULxlywKqDk9XwADMuTB4N7muLmAD4CTrEuNvhtedAb6QLG+I4gdJgXHW8wNx8N4WvUsV/s63e0cb8ZT2uzXQ0K0Uty6LBThlZllNYJmkrZZHIDHEMhlzhiPe1a9oJDq1QS0nTm6QGhoyiL7gD5KmniGuaXQXESN5J65iNNIN+wlbDs6mhs24LhDyNuinuFfTdNRBDA7Q0Kz1UqoVcMS81SXBReo9PSx6EGTjLUqhzYoCdr6wATbYCNTra5W2u5xbLGhoOvW287D0iTrJXRV35Rxci23ZEENJTK9DLJK/WVIZWCxQxoqlGIJkyOoFcL294aytoOdSdVN4/vefQLI6m1oAOpvHYRJ+oWZvV0lstPU7hoaRq1W8hq6np1UyzJ09KyJ1EAkAj3cjq6QMg+opjNFOesdJSsZJgrCbCuSXesu9wmo6eineaXz0aJVkE0Ajp2DHLZChVwQcEEEEg6trvd4YBMgaehJKavRa02m/X0+nVa1t/edBbN38s0csVVUz22sgNdDTwyO01VNCjxRxgjLyyJ0MFUBeklh8cX+CX0KZbuSBpsbk9huT6JarASL7T6AfcdZXR9oVdxqbbTtdpbOJ5IlmRaWpEpfqJLuRj0LN2wT2x8dZMQGgkN27fJLVaZmCtqjkjlDNG4cBmQ4+BBwR+8aqzWuq3NI1SiM/lpcyVI6Ox+emm6iQV9cjtoZuiKQVGMaYFBIKEfXRJUSSPgRqZpRSCo79u+pmUQuk6JKCQUHp30S6bpo3Q2XGfQ6bMjrZIKA49dAvKB6ofQfmNMXKITISfpqZ4TbIZX5d9HN1Q3uhFP36OZNskFD27Z1A5CbobLn6aaU0IRX17dtSUUIofpoz0UQiM9tQlFBKkeuNPmsohMnyxqB4RKEyn8jqSghMhH5aOZRDZcn0xoByKCynuD6acFQILKR+WpKIEoTKfUDUUgoLLn17HRBUhBZcYzjTBxRI2QSh+WjmQyoLLnvjvpsyEILLnUDk2VN2UEY0ZUI6ITJ9e2mLkxagMmASNHMla1BZMA/PRzlNFkBk7Z087IQVNkgHXilmLQBdWC/+OllLCrpz6aMogbquntgdtQlPlVdI1JQaCrlRjGNGU0FVj1zjUQcFWB8hqSUpar4B+GgjlVsA/DOjKGVNqmiiqkCuOiUAhJF7NGT8VPqNEORIharU7WuSyCW2bgmjjWCaJaepgWROp1UdXWvSyjK5I7g5PbVwrNiCE4qR5hMrhFztG89vV26hdy3szUqPBVyHot0cTQvBUeS/UxjlVUilKSiNCzHpYdTa6DHMc1uX++oIkfSRJ6p6dcZxbS5/wA/f7N75yltbbezLbums3ElfsWpb9kKSmcyW+VJQHiYx5KCOTrUqyk+oIPSc1Noue8tA5/znT5+q0MozP4YGp0jr+6fSXy/8X0Ox9t7pp933zc9XQSrMttphVBauNVbDtnzAGYdAd8Drx2GdFzW1HuNOIB3MW+gVNJ3is8V0AW6kaXvF/kB+SitzdLY9tX3a3K1kvHK2w7TYR0Xy11tsr4WtEdROrTVCARkNHAsTgw9RpvLlaWNRLBH19ag4EGnWAcToQReB66m1/NaDYmDQZUgGjldMmOtgB3+HZQ58btbsrdGx+CN58V8k0O46HkOReOtxVlgro7n7fSXONqqnaWp6wKcsKapWOcCI5VohG5lHRbRrPAfSeCAzmAIiI1/uL7dEjA1tTx3gcxygjeTlAbG41n6wsL4ZubLPujjvhvZc9t22vD229tUUN6u89TJU08qimjFNUUSiMxytPU0pRY8qFklVQwLdAj8O4Pe4znJsI1+xv023W+mGEBjIOonNpHmk9t9x8CuqcUcX8h0+87iu293UW47/VbgqNy1VuuNBNDb7pb4IaaNYpKqmUTJUzCZoQsgnPVHGp8zyD5dj6tEU7yMttiZJOxtAibRqTabx1eoSXQMpiIsYtJk73iTtadlN/kXelv3pctv09Vc5tjPbquiuDWuZ1N0k6WjnhZYGlEStHJA7Bm8zKrKAD7ynlYcCkSTzajtuDeJuCNI9UKdB3h8rZJ3/wAXv8B6rrdRuSk27tO8SXcW2lrK+pEUyR1DyqHZgghSUDqkZCRnA62DCTv1YFRGd4bT0H3MbfkIhUUWOe6Tt+X38tNlr1notqcQtydbbDSwUVrvc1ZcYqR38uFKvq6Kgr1HJLFzKY1yR0v6FtPVc+qxnUfkdP0HxTNaaj2lxnSfkPl+SJwralgsG6bfHXUtRZIN31qUqRRMn3iQIyyswLO/VIZlaSUlmaMfDOji3XYYvl+Qk/AegtukxNQl5MQYE/Lrv8NBouybqqaajsFdFUQrZa1q0PFH0YadVbqAjKHDMVGOxJXucdtYKZ5hNwqqIzExey0OuprfU2eWh3HQy7u25WVkdT5NxmWaC4DKhRVoECFSqiTLqyv7ue6lRpY9zXSyzh029Py6j5J2tBtO236f2/VRituztp8O773Pv3a9oprJxvcbyYL7UR3Gq8rYt1CJHLKyda9VBWJDSIHZxDSSxI4CxzMV7bcQ+vS8N5l8SLDmGsbwQZNhJBjVc11Q0nAOJLT1O99TrYWjrvuugy7hsdLvW1bPqts8s8qUlIsUFumt8LV9RbqxX6SlQRIlPCIRhjOzuVDsshUqvXTSoPfTdUAawm8mwjtNzOwAgxbor8TiXMYHF09QBvI2AmbzBjqFyvl+n5ts6bR5S4/8N254OfdtU09HSU9s3Dbq2Hd1sqZDUVFkukfnRBaepljd4qhDKaGpEboWQzRy3YV9J2ak+oCx0dRBAgOaSNR0MZhI1uMXE8NTd/1LHHM3TlPa1ie23raZjxzhyXZ+XducNcn26muEG4LHy5ta01m19y3CG0bh2hd7rPDa6qz10BMdSGlpat26kbEhgSoiMsbCVNGHwhpVRRtzNdcXBaA52YaixA9NDBsrfeKVWgajZMQbAgiCBGsAnNppcaysb4KuCLzvfkfdXio21vW0+ZtWW6ca7Y3DeKGKprd6rRX2qqbze2uMQjkK1U2LfE8iOUgpJWCssirocQxbKWFbRqBw8RrXEbNblhggzrd50nl3Vb8O2pjXQwHISL/1k30JEMbyCI5s/wAc59l1PX8v+Ebg7c9Gaap4Rkve46230FXWS091vV4F+uHnTVaANEKcTSqEiV+7p1YIMYWvibxRqSP93K0aWaMoFjrJveNDrMrdSxtMvqimLFzszv8A5GwBGkASZ7C2uO3/ALkn8Rt73h4WfDJxDtHbG9bVdFq75vimuEVBYtvXCOsiWpWkvlJHJUS32CRiRFDE7xSzwyVBTDRyX4JjmtGLxbyaUWEHmEGwbblIkEyGxmAJMRMfXoUCcLTl1UiY/puDLySQDo7KZLrSA0yurcu7C3NZeILHxpU7l2txdtuxyWX7u2lsa2zU8dNZ/N9lMZuEjNWPCSmS8C05kDsJM9UinOMXTrVzUIL3uJuSImJAyi3oCSBAhXcIwtZjGlvKGgyZzEmxJzECDckuyz33XZeM9ybIqKUbM21tuksO1qSGnYNW3v2esvEcFHl44yJ2naSKZ1jbzHAjRgMjKjVGMqOzGtUcCb2ABA5ovaAIvOpIVmHwx8NtRgdM63gZpJI9ZsAB1suoVF/t1daKf2S9S1N/lqWmtkxuDFIqbrWUSuQZRFGo6lMhwf8AhBBOMbCA7bKNdP7T1gfFaCx4JLm26RvEfP7K45d930lNyDuWuuL2Ox0dNYw9PLX1lWsy+ZIzeZO3R0ws6QoIogS4LOvuhio0spsFLLcmQLAEWFwL3IOp0tutIYTAmRrrE9CBEQOvoReJw+4ee4NjTcWVk1ZZbTapnuVJX3Rp4nWz0lMjsJ5TkpAonpY4HPYCWRwWynSB4JJe13SfU6CDvIJI6gCJmVU7DNdzbSAJ3mJJBvp8RuF0K8cmXe08Y2Xkex2KrqNvW2SkutXTrMrSewM6SVc0iMSoYRdcqgufL6gEDN7ogofzcjzfT6QAPiQDa99AgaTZc2ZJ3/LvEf3W78R7mt163dvC42ncVovWwrncKutthoFjZUEjxzRyOwBKpPFP1o3ZWVB37jNWIpllABwIcAJn4/lY/ErJXBMQLix3kwP1t6hB4kpG37unkXlKwV9urdoXS9imsNwpoGVVttLTx0zzxGQkSyTTQ1AWdQU9n8vyyoduqyu51Gk2jVF4kg2PNcC2gAhxFpOosElZzmk0z+GBrN9Tm00JgC8EdTKkpcJ7Zt201t2NNGsEUXV/s9OC8mSAqKEGWJJUAfHI/PXLl7zk1J/P71VNNmYgEwFex0lTSUXl18dLDcpXeqqEhPuiRzlsdgSAe2SMnHfUquBMN0FkpANxosuV7fHOdVyhCQQRnUCJYkEdsAnUlQBIKnRBRAlJIxoygWJGD/y6IcUSxIYd/XtqSpCRj17Y0Q5GAkdA7aOZANKERg9/XTSiWpLLnvoypHRCIx8MaEqABDK50ZUhDYAHOPpqSp2KGVz6flohyiGVI9RokowhFPU6hcQohFQfkdEvUhDK4Pro50UIqCc6OboohMuPUaOZGEJl+WNNKkITJ37jvoZkcqCwxjGjKKEUwO3fUmVIshEHuNQFTKhMPX0I+Ojm6JgBsgMuO+dNmlEDZCYZ+R1MyKCy4Pr30cykITLj00Q5RAcfHRDroZbIDKCM9gdNKkIDDOjmuiQglT6986OZSOiEy4+o0WuUhBZc/TRDuihCbuowf4aYOlGNlNhx2JGNeNL1lypAU+uM6WVIV+kj1A1Ad1I2Vun886IKZXC5+OhmUV+j176OZCFXR2GNQOgIwr9AOiHKK/SMdux1MyBCoLjPYaJeoQq6R8MDUzKQrFdQOUhaxeK2OB6gSpR1EUcfUAT1PGfiWjJ99cEY6fe9dWMBMIhuwUGfEFwHUchw0t246E/EO5Fr4LjX3K3tU0tLXSQnKi4W9SILhRszftOoRzMidKyID37WDxjo8OpzbCYkeh1B6C4B2lX03CmCWvI+RH166WhRe3TyLf7ZuThrYvL0W9tn3+mvdPZaS5WZWuljaOsjlcwQXZulpo5Gpo2SkrpIamGRafpSoKoT0Tg3NYajAC2J/pMjtFtbkAtN7hSljGlxBEPM2P4tvl6AHrbWXtsitm57RuO9WO4UVPvCJ5Hugr6FTcqSoRmWMvQVUcciq4VsskjqcZQufTn1KjgGB9mnSNL6wRb6fJNRxDc5awZoMHWO8wfpA+S8cftK+PYE4Lr5uFntzXyrulHIsdG0Ap4a2lu0OYqatJp5KOaqmd3ZKlJ4gx81YonkabXZwGIe6sKdfXvOhB1F7BtpBHQkiypxGGeMO+pQHygQRBN9+YACxE+i5vyTylS7wvvHe6PD/cn495ur7621Ny7HqlJbb/s1Kktv3JWw4eOGmFNIzCWEup80ilZmeWbULHuBFW1icwGoJILQdSZt1Ng6AIUwlX3dpayXCA3KSNbHSLD8RJkTcSSuweF7lva2xN37dt1LuCbkHdl3uF1aukr6Tzrq11AlWpniFPI0KJJVR3OnDTHDKYTGWLl9ZqlRxYRT5QANIiNQCYB0h2nWbBdd2ElsVzN+pF4uI0hvTYiZkgKZXK95445l2VJbt17NodwXNbVFW1NZDWGgqqBykk6Tw1cJV44agCPDNlJYVce80RAy4YPpkwYHcSNreo16gxYApjhMxADiCDsfgeulwdtfRYLjy8bjsu1au48pbnu29OLLrXUtVQ3v2VaG6We9QSR+TTXCnTy41AmFOwqWaOnkJmSYQq6ebfTw8v8A5YAeLwdIvJB7XtcixEnTNXxYcQwaRGYaRa3WTsBrotw5a8TvG+xt7RXDkDdtmsm+YVvFiqqWpqY/ZKCslSjq6yVUcdJp4qaoSXz2BaWJI0VQ7FTRToZqRZTkg5esmCQBAvJcIAA1NzCtZh25WPIAaCTBIEiDF56NzG8NEkqS3FklwsPEHF8e05bbRtQxyStQXCFKGorrhLU+dLDV/iWCVmecMvdkdHDFfexVjY8Uh4iwFrgACLdY+R2lYqQDy9x5sxmfWYgdIiPnC23lberbl4B3veq/bUtfUQ2SqrbhRB0Z6ONIpJI3BYxukxUoAyggnqGQPe1kFI06ljBkR3001EKzBU2+8tYDvr/iV5sUPic5WrKDj6+7V463Zu993BrRS0FVOLVX1FTFRSz9FcZ4wiTqADDWROyM8HS6Fz1Hsv4fzZHENOs3IFwNjcHca31hamCn4Yc6SBE6Te/aALzIhSo4csvPG4+Pq+33TZm2Zt5V01RTbneS+tT025K6JxBUtWxhJmipQuMLDKfP62jLCMt5gc+i2CX2GlpgbEaAk3sbAQb2jmVK1Nzs72Fpi4gbyQAdJFiTePW43PwnzXfg+73vg/lva1q2VcbruS6ybAudLXNU2u8WUTSNS2WnmcBoKyihToWhYBWp0R4DIElWOriLHVqTarHZsoGbqCfxHrM3d1sYtPH94YyqWE22noP206nUk3idl8slsulK8tdJLAI181Z0bBhKjPWAexxj0PYj9+vPsqlplbwXaN3Xz0/bA7js/wD2KbO8aux9lXTaPNnEW4rLXVF8q7NXU1BeLb7esf3dNUQxN7VTLUGjrYEmChJaYKjZlZH9Ngm1KZ8B7uV8iJBIJGsTYwTp6xYKivgxTYapgkXIBs4NMkG29xoddRK9A/Dfuja1Pxl4c+IOJTLYNqVWzaJhWSU0scFXQiiWQ3G2VUuPb2kZPMMkY6VaZWZlLBSOIsL6tTEVoIBsN4mACASQIgX17rRw/IygMrs7tjMyTJJ0A1Mx8xC89/BTT758QHh33FwjxAm4uOPDDZ99b52/dd2QVYtcu+qT+01wkgo9vTReZJT0RWojNXcQEf8AYmmpss8k8fSrmm008RiBL8jIaRNw0DM8WsIOVn4iZdDRfLhnmjWq0KMy2o8lwjlkyQ2fM+5BOjPNd5bl9HN18V3PifaFvtezq/ab23a1PFdrBaLPQCzx2egjeJbhJSNSZMiiBQskcimKUd2CPhhz6XEW162arJLjDi689LbX06bWWmnQp0qctYGtAjW83IzF3zkXJ1ub6Z4hYrFyLcK3duw7xd9j7i295kt23LJRzVtNS2tUDR2+NIvN9okqKZvaEiwYo1linkUyNHG9eANSmwF+h0A1LjE9IDTAJ1kFrdCRtIBHhEgyI1AABMkneDeBYujUASod7B35x1t6+827p3lLtTiPk662OFNzCru9NuO6XO4xO9KKuipeg1Iar9+Voj5RMUcD9ETYXXSrU3PoeHSMtzaMBDRI3IJHLG+aCbk3TB3hVm13tOUAklxAGUXBA7g2yxOgG5P4Qtu1G8OOtiXfkXaG5anjyigq7LYtzw7ZM0lyti03sxkjhkCC2xTCIx9flyyMrqFMIc9N2LfklwPM4A5S4WuCJve98oI0uTCWnjX1GhlJwgHUE3sbgARYdTF5AMyu9888M8ZWXiTe1Bwpuzd3HXJq09y3TTWaC4T28V0DSeVWs0QVJY6d0XyutWAVpIgBg65Da9bEPBqiRYTrE6dp3j1lW4QGgQ0Rl9ekEi86ehj5LSuLeFeMeS7nxrw7aqPf+4qrbApIuUZL5dauv9prqZStRbqiLz1iid5QWeMAo/SE6ZAszjqPrClnxRDQy4ZAFzoDJF4/MTYZQc9WpVNDw3VZeY0gDKTJ0kjMIm83kmSImfunfdstW8uMeBaE0FDSbvavNVHSO9LJZbZSxOtS+IlK/tVkgpoo26felkZSViOOHhafiZ6tTmFMT1BJiBruZJPQdSjWcaTQ5o5iYGn/AJXGjbablo3WM3fS2WTkHdnF+3Ky27U4p3Ftm3VW6K6MOlTAkTtRR2ynlXAiiqKaB1abr6olpisQLTB4tFAudT8SsC5zXSBHmLhJJG8EC34s0GGgyho1Bly2MOEgwWxFx/y5jB2iTeFJ202aZts0+3LdST0NJSUS0EVBTRR0tJRwBE8uFVj7riPpRYwT0Ad+wA1y69Yl5q1DJJkkmSTNz3vqVXSYykAymAGjQdtPvcq9Pcqq943HBS1lJt2lRa23PVrGYpR0gST9XXlVVPMC9YUdPU3YMDpnt8PlcbnXsOmmptMdh1VmQf7cX0+Ow+f19Fse2T97Tz7kW61lVTVESxU0EqRr0RKzHzMBQwD9SsAT+FYz6sdV1oYMkX316aeo37yNklU7DQdN/v7stxZPXAyNZs3VVNG6RjHwxpi5MEgoMdvXRDlCEjpPy1MyhSCudTMoksowMA6IcEUMjGiCpCGUH5aIKiQUIP01JUQyuTnONTPCiQUPwB0S5RDKg+udAFEoRUjGmBhSEgjOoHKFIKfLTeIpBQyAfqNDPdGDCEykE49NHMplKGQD8NTOoAhFceuNTOoGoTKDkgHOnndTL0QSo+OpmRCGVx6DRzJssIRUHuRnRDkwCCRnTEqFCZMdx6aBcgQgsvb6/wA9MHIgITL6jsfz0Qd1AIQGU+vfTAqAITgDB1JRhBYA4zoyiEEj1BGpMqQgsvr8tHMjCAy4B+OpKAagOvxA0Q5SEIqDo5k2VBZPj2xo5kC1BZcZOP8Aw0wcplQGXt29NEO6KbKamvHuMLKq0ocoq1C9SFWiHhRVqB4UVaGdRVpwVFWhKirUzKKtSVFWiCokO4jCkgnLBe3zJ1J2QJVGKNpFlaNGlAwrEAlfyPw0wcQoQtfu1WKi2yVdFLXxzQv1fsITI5IfpZCi9yDgg9PfGSPQaZkzCbL1i/VcV3FP/wBre395bZuqbdrrLJ1UF6sF8UlaWMqFeKoiYASQzIGdWbox1o6PkYG6nNFzXXB2I/Q9t/iCEuIw9IgMiR8L/wB9v0XlXtvjHxkbe25fePuOZeLuWbBZTXUdop79v6en3Jsi50jH2SGkuUkDLNEpdEehrDjySE9pmRgdd91bDF2Yuyl0SMhyuBFzA0P/ACG+jQqMVXfTcHCk57BJzAtLoJmI3BHprzOOiglzty7vXxick8e8BHhOs2tzltRqKr33bLzQex3bb89Ky0MULXFFnSvo6u4V1NNHNRiRPJidutC2rKOEfSzOc/8AlmSI8pm8gWPK0OmYvAWscQwtRjWRD3G4JggC99ruytETMzFjBOdfCT4mLftraHiE4X3VDcqjjcXKoodqVkNZWbmntTS1DvHBcKanhSbyDWTXOCmqY6hfNVVSRBJKjXUhTc4UnkgmNLASADcmQYGUkR1INlzMdiadGH0myQTOYeYDSQJBG4B00tNo7+FHxC+GykrOULr7NZdnUm4NrNuSzwWaGaho7zNZHo6e3Na6qnVYVqn9orKmpqmPVHUFneKONWcvi/FIAfd03kTBMh0jZrRDQAJj8RJhdDh4woqB9MwHAjUaC8iJzOJkwDEGMpiVKrcW97vsbbHh72DSrXbS33um5JvLc9ngiluVPX0vs1NTUtdSVa5zRU4jp1COuOinMoLKdYK7peS64aCAdLkkmZuCZO4IBA1C7FAhkhsFzoGUmSA0WDYtE66ySdtfRfjzf+z7zcaXiC18a2zkK5V9jenrrNT08U1uIqJiTLJNUytLAiJ7Ikqz/jjCKFbK6xtzkl+fKARzdCL6AQbzEXlXYxoYwVHkk6gSZI0ibbT0AXiXyP4d6/hrlvjSLe+4rzetmw74tGy937otxmnqNrVEd3kiigq5YVE8lJUolOsMXmEQuz9b9cdIT2WVRUOcSRBcBpPLt3G56aC7lxMVTJpNcQROlwYlwImxtERa9geUBexewqDm/j/jre23t88mbV5Z2JS3oXuwVF33BNFdLBY5KCeWRHqDTSrUUiEo0Mucx5PUSUZlxvp4ckOYC10EaEgmQBvIMkj07a9BniisTlsYvyjQ7+UbaC51JWo3fkjmBt/1PDvK/GWxPELapbM9XVtad7U9LS29CsKVArY5DEprEXzlChQSssrKg8pi1dGm0A1cO4Ng6lp6kiLO1tcbAbFTFVIA/lOg6AZbiIvmLYF+t5Cwv/azzBsywbOod9cScxbmskPIqXy4181PDuEUlolmy8slbRM61EaQz1CRwezK6p5ZZj5bE6hhA6plpuEhpbYxeDs68kxJmBe2izVMYxlE1XNLZiAW6XH9PKAL3Bup07Q5b2i162zT8V70423nZ62znb1vpbBcZDJFVUrKKd6nK+7LmWSHyikZwVYgojFefXpOcHNqAhwOYyIiZmL9BM9upvBSBcHk8hncHuYi0aTcmSBrZdg5BsWx9y7Ordnb8hbem17nSSwV9I8vlzTVq/tVqKdh/czxzBminQjyZY0kVl6ATjw1Z1OpnpcsaHoNL9iNeo2ukrYXxmFrhv8AL7+awPhu5ZuW8Nqbs4d33uU7i5R2RWSbN3DcZpR59466ZKm2XSTsMtXUEsc7Mo6PPSqUfgwL8fSY2o3EUxDH3A2BBhzfQHTeCFzcEwsc6kTLm3H/AGnT4jQ6QVFLx/cIw+Oq9UHg3t0iW+ktG363kTddXTVU6R0lxSGrotsUjmJlBd7i01wKn/1dsGRhwdaeEvGHpux77wQ1o6kw53yYI9XD0TYxxytwgmKpvtyNjNeNC4tA2OVw1C8xKXdHiJ3tyZwP4dPB1XUmwts86cTVPJF4uMdIqtwJb5CtLuNLEq+4ZKupZjBDmNKa4POygrJ0R92pTp56pxd20iM1/ONWNM/Im5y+i5VPHeBToik0F7nEMm+R7QMznQLgTIboTEyCQvpg4W47444U4d4z4s4qtFNtjjHbtlorNZKON8rS0ccSrEGb/E7dmZj3Z3Zj3Y68dxLGVa+IdVrGXk3/AGHpoOwXRwWCGHpCi2THXUncnudSuTc77k2DtSXcO795bVtiR7foKSQXSWOANJHV1UcBjWQlSo8wwI6yOkfTIGY9IOrcFUquApMfZxiJtMGNbfQnpddbD4ZgLXjzGeuw7dp/svCXwUcM7F5Bo91Q7Wt19p5rvf8Aed43DcLtuq7S7Io61rzU0ltt9ktsNVTx1aR0dFMYwojgJUAyn3Ydesq1Qyk11QDytjlbncSAXE5py3IuRIk2JkrC7E1m16ngl0ZzYOOVgaYAJAm9yQwk2/DIK9fuMPClw5S7ZgsVLuup3RTxU8UNRS0CwWSzUtRT+ZEv/o+3CGJ5UZXV/OknkLd3Y9KjXGx/GHudnyW2LpcTppmsB/2tAGymGwz6Dsw5ZuQLGdZJMvMzqXdI3XNuTadfD/vKy3amtVgo+F75Xxw71oq69VkFLa6qupGpqeuFLMxh9neaJYKkB2DdcbDuJCUpvdVaRPMAcpyzMHMRPWJy2BntC6dB7dW3dNzaYFpBsZJIEnQSblcR3byfUcgbF3JZJN8bF4c4921E0e4XF5NsutQPYEqUttBR9EYp40V6EVD95c1FRBEsLx+cNTKDWPD6hLqjiYBBcJzAZnG9g6QALHLJdBgvTID/AAsM0hoAGYRYXuJkBxbzc1mgizjpJ7hHjmq2tsm3cTcL8kSXqqpqdK++XeKmpWsdtq5hK0j0xgjWWonaR3kRBM7BFHmzAuGejGV2PdnrNLWCwknMQALQeUCIkwBewOixYcsokvewF75JAtdxJlxuYmReXGL9VhbRyNsrjznfeVPJvDa8q2LastTva5VEEa+wiGYSpNPK4jhidYaqBHRyip5yAFih1INTCl34S4ZQNyQWwNSZPqSWm1wrMThHPxFNwiS0gA2MS10jo0QTPQiTdE2NbeZuYd67y5Hs15sHE3Ge6ZLXJZqbdO2JqrcFXb6OCRaerNI80UFvDvPUzxQsHlRRBJIOtmRLXsp4VgpVZL2lxIaRAJABBdBJMAB0WuWg2lZaeN8aH0mNcwDLJLocJJJAsSCTAJs6J8pCmpSbFu9dtqj28/INVT2JYzE7WGjjpJalcnqzUyPO46yW6mQhmJb3hnXJOMYKni5JNtTYRpYBsgbA27FPUc4g2hx3uSD1vafUFZE7borXWUlPeb/f7/ZZo0g9kuckUsCyRsDGelI0BJz09JDDKp2GO6nGFxLqbQ12siZvrqT6/NMZc2AAPS1vvvp1WzU1dFJfr3b/ACVjMENPI8nb3+sOST8e3SPnn9NZTAph07n6QkLIAWSpp46qmgqomV4pEDqQcgg/I6XeCg4ahGK+uQRqAypAQimATnUzXhFIxj1GNFRWKjHoNCUIQiuNFFIKg+ujNoUQyh+GNQOUCTg/I6gdCMbobKcADGoHQZUAQyCPUamZFDZfiPXRzHRQi0oZHroFxRaEMqMghRoh0JwIQiPpqAoyksAdHOlhCIwe41A47poQig747aIcpCGy/MDUzIkILL+o04KkIZXOT8dQuvCkIRB9fTRBQAQmX5eujmRQSoI9BoyohFfodHMohMvxAGmzGJUhBZc/Dvo5lEFh8MdtRrpRCCy/DGRo5kYMoLJ8tPmUyoTL279tDMoL6ILLjt3xogokpu6+ucY0c6aAgsB3xohyMJuy/HT5roG6GwyPTUJRhBIwdGVEBgPTGNMHXUm11NFlPc68e5c1rtlQXP1+egSiXJfSPlnUlJmSCuPlqApw5JwflqSmkK/T2yNBDMq6fnkaMqZlXTpsxUDlfoOM6EoZ1QUnBx20cxCheFp9/wB1UG2o6m43Od4qCmTrrgsbSNBGchJcL38vPYt3x9MHVrWF1hqVZTYXGBusJvbfG3dt0NNe6+80lFbaS7xUlXN5yhQe4ZSfmCV7evy9RkMBNhurcPhalR2UC5H7LT75zztC227bt2db1TU9VXtRzrJROJLevkPIJ54zgrACEDP6L1AHB1a2i6SD06jrGvXp1VzcA8kj00m8/DpdaraOYEvO8ptu2qKJLlO6NTOatIvbadI5nlKU75eWRDGqsF9FdT1eoBawFpJOn7genz7rQ/BgUxUOn0k6XtG53WT3tR3G411DLfr9x1Zb1LAtIkJtE1VVSxsTgGUVMeV6sgJ3VfMbJOTrZRqUgMsOcPUAfVp+dlyhQq5s9Gw3J39LiPrPZRv2lx/vHZ+5dybz2jdeKN2VNTLBLf6SSy1lDXikSl9mgQsKioWonhNF05SMOQuVDZCttdUovAYS5ovHlMmZtZpAvuY9Fuq1n54c2x0hx06uBFydrjovM37QjeHJ8u+Ni+JzgPZFxqPEDxwsd92xNsu8TbiO/rP1QxXCx1NI9JiAyU1YrxSftHVkiDqehfK6nDsE/wAN1CoDkdY8uWNbzN4jQd4Os4MbhWsb4zNR1LRmAuYAkgkT6kDsVLmxeKXYW7fD9tnxDcM8mbY55L0Md1qIZKCmorpdqNGKvFLUNPCaKro3d40jeIeSUMQAWQtrnPYRUNB7C0AxrYT6gzmiTe/wW7BUjVIqsIaxwMXMzcwABfuIvqbr50fGbd9q8LbguW++CdtbNsvBNxrqnf20p2qo7pcdlzVTzUm46EqoWeCip6ynFYRFLLTxzywwyfsappV6lCv4jhmcMwgOA30LXdL6CYJ1GkHDUo+A05mmNQTLQNnC0wIMnpcEAOtL7hng/jvm+r4suW89zpuinoNzX62b8C1E8u2am4pSVdVTJZvIqICKaRKljVx5dVzSxIqKVd2di2MYagE25ZiTBAMzMQdNM1ySdFUKVapUaxjsjuUHLIgETqIEnQC4ZaASpe8RcI0vHO16KtsW56Hc236TY0lPVbXsVA9pFFWTQxxz1gVJhFCivEHVqlvOkaKWUTxRyxnWbHYhpLnEXmQXCbagabzo2wBggmV6fA0qtHw6bYDQYMG5NgdbkgAa72BsQuX0HLvJHiC27DwONtbH3VS7jltMd6sFiremShWpoFc+XVSpT0lNX0lXZp6mJU6pTMsbrJIEfOg0nYdwxGYyJhzrD53JBBiwiNhZc3EVKdbPTczLJExd0SQSQNO+cg79Suh8A86eJvlifdlk3DYdp8T7jsUXk7ytFTUwxT2mptlXHJUzm3KqsPbjO9R7PJKIlSqdyWikHVmxVGi3nc6QTaLgyIAnTlG9zYWlX8Pc4htPw5IETIknWbXgjSB6kajsnhEsNl5ZTkqep5h3dZuNNqVdTaqX+xASzUFxu8LTdUFTcYkLVLwRTR+U9OYhMs7rKXeHoAr12sa2q5mZ7ojNMAWuGzoTa9hFheUmML21fAw5a0gmYAc68ESSIHUm52JEL0KuPDUPFZguGyL1aLfZaq8UldcLrcaOne5mRmkbNVWLEvtgZ5Io1WYq/VgGQgLjmOx3iwxwNrAA27QJt9RCTD1nVB/M5nQb6ToNNoHRQU8XGz7RYa3aXivvu0qiwbxod/WCXc9xs9M3UdqyTSUdRcLk9Liaeighq5pD5oLUhR5E8tWJbo4InMMLMgh2ptmiQADuSALa73sFe2nSBqUxBbGmpuAZibAEmdo1MKTNBytsLc9Fvy67I5ipNv11vhmo7jT1FVR3Skoh0pLSTzUvniNqYwVXmJLDJEJ4QjB3UkjmxDYqN5ZFxY9DeNexBg7BbG03Pe3LckSJkaidLG9jrJXmz4tfEhQcBcgbE8S1Je5KKi2ffIdt7kq025cUtm5rP7TC3TJV1XlU0jwlpKmiYMz9clTArdFQ/mdjC0i8ZCCGu7t5TcTAlwkkB1ha5uBGLEmnTa6oLVA2TqQR0kWkaiXWMCLqbvgH5Tg3RuzxW+IJ7jtG+7W31yfXWqy7ttU7T2+5WmyUkFto5ErcBWV6hLoUkICuS5UsCCcWOa/3ahRJ0bmjeXuMW18oB63E6rG6hTrYms5o8uVg9A0F3UWc4gwYkHWCoR+E3cg4m+3o8UXA24L/AEFZtNuLqy67BpxStFSWelud5hvVypaeXBBiNVNVzA91BZ4xjo6dWurvq8LfUfqCwH0aHNH0IHWLrBiqGTHU6TAeZpcBqczoDp/8ZAHVeqG2fE7S724/tq8HbEk5goUq6qjnvs08lk2rTvHPKrM10qYwKxF6R7lvjqWkAz1opDGgcOLYq4l4pggETdxsNGC/pmyt7ldbE1Gmu+nTJc8G4bci4Fz5W7zJJBtkKjxzrYNkQ8UeI3mPxj0d68SvH1tt1TUUlrWmlpbDM1ErdFJbLQhPRWNWddNBVVctRUO7wtEU9BrbWfTNOjgW5ajiIm7+YgCToARBIYBAnMSgMOKgyV35WBpztb5csEuLjq8gCSJDZEADRdZ8B3hf3RwD4aOFtjck3KrvHKd6rqzeG8Vq5faJKevuFbLcp6JZpQZZUh86KjaQnLeQH9XA0nFsXT8cso3ZTAaD1LRGa2knmA9Fy+EGo6g+pVblLySBuATyg6CQ3tqTEL0IrrPTWmO5VVrssU1LUvJVV9PToqGaTpyZVVfxSsQM47k+9kkYPA8YmMx0sPvot7ABZeZ32gPiH4g4Wt3GH/adunal8s1zq3++7FW+dVSVtigp5bhLOtLTxzTGNmpFpyzoqYnYF+2NdPhdBznuLBoDFh5tGiTAmXSL7fFdHDz4ZBORptJtAM5u5gA6epXjzyXyFbuN+EvDPPyxZ7ts3kq02yn33yfX7rSS0XK63KSop6+LatHc5l8qvq5faJK6WIeY7rkt1CUI3qq2GLsWRTu1kNaG80uFi4gSQ1hgToCbXlcfhWOp1sKarYirLpJiKZmCSQ0Fz8uWJktbEABeldbyvuBuOaLnze1pt3hP4yqpKhbnWw1jT3zfMlTORGtks8SiWKSaGHohllp2uLeaOinUKJdcqphmMeKTj4tQgQyOgnndeBeXAOygeZ7bhb8HjvEa4UWljWmS4iGt2kWEkm4LgATYNqGx2Xwq+GWh5Jtlg3hy1xDsvaVosTpX2Ljkmlq6OjrXIqhW32ZOsVtTH56eTTDrhpnBmeSqq+qoTRj+LnD/AO0+X6ZxMACxDBA1i77W5WBrPNzsTQOIgPltF0kg+d8/1m0A2cWyS43qaNYz16hn82CJ6ajjMh95WDKY/eOS3WPUEjOfU4+evHk3WnL1RKyant1DLLhKeGNGIKqAqdicnHYDOgXSoxhJgLA1tfS1llmZpxJVRMqlYuoFZwewA9cEgj6gnTEw626sZTIN1zWiuNdet01FfLLcbba54ZKZaR6V1kmSGQB0Eh93yuvzf2vu9ShVUn1GjKGN6mx/Yn4bddVqeAGANiRv3I/P5xcrtqZaNCyopwOynsB9PprMSueAksVDBGOG6S3c/DQTQrFcEjv+7RkpZSCM6AMJgkFO3YnOjKkJBGM6OYowkFR2wBqZkQ1D6SfQfD9+oSVISGGfTH66gemIlDKHUDkIQyue3pqZk0IZTHx02YoZSUIrnOpmRBSCp7n4amdQBDK50Q5OEMp+78tTMlAQyB37DUlEhCZcfXRBTEJBUH10ZUKCV+GM6JKOVDZc99TNspkKEy/PuNNmRIQ2X699EOJRyoDKO50S5DKEIgE57jUDkIuhMgAOiHI5UFlzj5amdRrUFlB0cyOVAZfUfu0xdKmVBKgHGdSUQEJx+7RDlIQWAwck40Q5SEAjvqZ0YQWXv9NNmUCAVxnt21M6iEVznv30wcogMudWFwRhAde3f+GpnMqBTPIzryhIXIBVYwMDtoTupKvqEoKtSVFWpKirRUVEZ1FFWooq1FEKWaOEBpGCgnGpKIC57cbnZ9xXi5bLuVJWRyyU8nRJ5TxjpBxlZlIPvAkjB/wtn5GxjoAd9/JaRScxoqtKiTvHZlfW025tvbVmtO4JrZdXr6vbVQ4C1srdDeY8jYg8uZMYil6AGCdMiAd99DENBDnmJETsNfjI7T3BXUFRwhxFjBne2wGvZecnIdw3PQXa/wDKCWfkOz8R0FZDdBtW6Weqq4KhWBL+TRwiaeh646h4ulRNBP2lEkTZLdSnQIAykZzaQQCY63AMRqII0IhM7iTXEUSCSBcwbXIkmLzeWkXJETZce8P1dYuMfFFyRyRuHZfJXFtXV5vW3rJWUjz5tNXSpTtSu4zTuXlENT5yuYGcuA6tISa69N5plpg9SCImQdR00uJ3hWCvTqAMa6RaAZGkjym4JOg6yB0XpON68q3Tm3b2xaC6bZNptG3I79uKZ6iUVdJa5x/skVQvS6TFpmlVZFdWMdJ1NhmGsxoUvDc+8gwO5+m1z6wgK1JjGtyznNriwGpE31EbyT2Ut+P7fBfbDSVO7rtUzXq5KzzmmuJkiozCqfgR4x5LGSUnBBbpEZJPYDNWcASGDTtBv8e3zlYMS5zakssBp3/cd1naug31DBe4du3y1brmhSmpaP7xLUFVTxt0lmjqY0ZfMUpE/U0WGZFDdIGdRjqZjMSAbncSNJEgxc7yO6yVC2RmZe8xpfsdfSQvAjxibf5t8AnI26PEFwb4cbPyj4U92XF63m/YlJafNS31wX9tuOzwvIq07SpIxqhG3s8z08UjOjmV19Bha5xDAzPD2jlMiSOh6xtN76G05cRSo0aorsZmaSZBEkTHMJECdxpFwoML4LuJfGVbPCpzptO6WCl29vCx7qlrKfbURtMzLT09tqYKB0pRIjVeZR7Y6BuhlljWNhB1S7BWhrvEBdGXW+riO1hEDQnUkSANjnsxRD6PIy9hAhpadROriJgyBpBkrzn5t8JXLvhE5q4t2NwzScw7+493ZvCams2y4aqejrpWgR2ktsNRVU0CymogWVAGQSjEXusSua2hlQh1QwRrMfOxdEHaYPzXOqtxOAAdROZrjYNOYgkX1DQZ62O69Y/Bb4v+VLxsqwb43rwvztvTwR2S011ugq7XZ6hXqam118scibuipUnZQ8lQka0jGWOSSmD1LLEVcGlhqhe4jKKh0ki0iBlkiTYmQBlnlBK0HidBzWtJc2XHnDTmLhd03JaA20zLoImJXrrcOYdjbn3HxRtzbnCV55L2HuPZNferbZ7ZZqK8UcVfTOlLAtBVUk0lFDEJLhUsZlmRKd+o9SAtjnMpYjnOcBwIBJdETM5s0HRuhBLhFittOrh2DKZbFwQCLDKQAADLrgQNBqVCPYFikj5R8XXJG2OPfJ3NZH2ttKGybqpaqOvsN3TatKa+tqIoVLTRoXVorgvmvUrEghleMBj0OIVMrGNpugPLjI0yl1gL2n+m0TLoWvhdcvrvfUvAE31MugOkGbQCbgCQAdFIDw4eK2Cw7q37w9W8PbzpaS7XOroKuhhjobhZLXdYrZbwsdXXGRhTvUxoalxNEmHDu/v9WufjPErhtUOgjQ3FszpgRfLpYkdNVaOGUc5DxEwTIMmw1iNZtMGLQF3e0ty3um8VUlw2zyBv3iukv9HW7et9Ikdvr6ieGHIuklRU1RFbbYJcCKCSJJZcR1HvqsUeoMlK8gVLiTsOkC4e4SNSGi1nSQ+Kc3yGAwCHQM03nKLAEaSethI1x28fF5xlt7ctqfm+t3XtpZ9w23aVvt+5Ns1NoFTU+3RNNOvWjRilaaeJGlaaQfsekg5IdKeDqwPCZIubEOjlIFx8SBAuR0shfRFMlr8siZkg3iBeCTFtALkqA/je8MtRxJxDcPFJ4X7htjcvGa3E3Xf+yLZaI7laY6Y1bvNW2aGIxRy0bvTJNV2iRjTyGJ5qdIZg6y9DCcWbXIoVXFpEQ4mLx+KZhwk5XASJgyNOT7g7DVy9lOWkGBcuAgSBu6dDpbSN5b3GLivmLhvk/b+4tkbQrPDvvrajmj3LTX6Or2vumskpnX2un6kf9vGqR1AecQlHiIRpTEGGF5ezmzXadIOYCbz0G03JnvftUTTq5GEklwkgwRBiADO/9ItEWGigD4K7nb/BjtDf3gE5e39ZZtv7BuVJv7al7v0sVopN1bLrkarp3xPIkSGCuSop5nVpFBnT1HTjfjqrXOZXYCDJb1IcLDSSbG0QTHdYvZ7C1KTamFzZoEiP6Sb30kHWbC211x7d+56TxefabeLzetPHyttzi+g4P29bI7HDZ5bVcuQLfJcW9jiYKfaqO3VLuJHj6EqaqFVgVF9oAeYCg6lhXNqAOeKgtIcAY1I0LmiYbMBxl1mmENWcfRbh35WimZdcSMxJyG1ibeJEZcxbs5e/3Btk46tPHvF3FVntO4ty7ModqUEdJX1ErwQQU8cYhSkqlHlxrI3SyhPwRtE4ypRBrjcQrVJq1DAdO+/cHW0TO891to03NZTDLA2gDQa6baxAE7HefN+n39yh4nrh9mlsK+S3+j2Fdt0UG7mtUrPF97rtyNK+43O5lnaSupZaye1UNN1ARNJ7RVHrzTMO9QoU8NVq1hGZjSf+0OGRgAtBMl53DQABJcsHEaoe19KiTzOyuN7w4ucAYiGNbBDfM90Ew2D9B1PvC3xVMtjr6inG46eCN5Ih6ydfmKpjHqwYxeg9Opc68bfLmHlH+Upw7iM40J+5+aiPdfF5Lve/b4438MW2rbzJyBbqgxVt8r6/2LZ+2pSD0w1l1RZDVVa9JZrfSJJMoPTK9P8AiHVo8KcaIr13eHTIsYlzv+xtpH/IwzudEmJ/lVBTIzPtLBZw08xginM2zS+IIpkEFeA32h20OZ9geHWz3XcPI/DNh3jNaawbgusm3a97lvjc94np6GkjZKyR4qeSWSAxqsPX7HSBuiIRque7hXsrYinRpZgJY1rbQIOYkxePxPNi42m4WjEUH0aFXEVAHPAcXEmwGUtDWiBaXZWNcTzHNrJU1Lfx9tvw1793ZYd+bu2t4pfF9utaSO5bTsNrqRuC83euCyVdJbPOqJILPYY4xSIaypijj6Ij50nWFTWili24lpo4NpZTYbkkBsAk5qhABkkkhgJP9Iddcyo6qyi3GcSa245QJe1sQwCmw+cgCCRFyC4tbcdeunhZuNdW2Pkjnm2Vke9FimWl2/aFaLbWwrVUq0MtksksPQXqXWGKGW6dpp1bDJTwdMesv8TYwkUDmG7neZxF/KZhgNwzsJLnLfgS+pyvgAeVo1bsHF1pfBNx5JIpxcmWlsuVDtrYdNu6y2mtt+2qid6fymrpYIRHJLKsDBWK+fPMFGBMgReuJRhQpPHrvJPhvPN1gHvH/EDci5v6LqUKYe/JOmka2sfgNAAfXqpXW6W81Nism5aGaqjiCq5pnj63npeggBu4w5OWDZxhh2A9MLyGvIcuYQ3yfXv+y1fcnI9hkv8At2lW6W+osElNFWVucMhhkmEUIZgcL+3Vsk9sRupGe+mw9N0kmxFh6wT+X5hX08MTTIA5r73ga/RNd/3OtsAod6q8dRtIXYLeEasSEQ04c9NQ7kH3FaPJAww6vUgFdJRLYibxI9Y0jqdtvzQogumnF9P33Hx7Cy5nxNyBSbuh2lUxXG9UlxltlLJWUlbEGW3VVbUSyrBIyAKkpSNm8tjkdS9h+HWutQDJsIsPWGyYnWJ1GiuxDTLiNDJ9QLT6fp2upAHf1htVNb4K+dKdvLnWRi46IvJdYypYnJY9QKr6sAcfDWBzCbi4t8Z6fqszMM57iAPvr/dIW/CoqJJpJAAVZI0Vj0O8rgRqTjBKp0scHJ6sgHGdPki2/wBk/fqpk2/zYfqV0JVcRqHcSPjuwGOo/PGqS/os4b1SSnYY/jo51AxJKkflqZ+qYN6JBGfTGjmQyoZXtkeupm6KZUjGoTGqgCQVH5aGZNCGRkeh0Q5SENlz6DUzIoZGDo5ggENlz6aOZFDKnt276k9FEgrnRlRCIx2OpKiGVBydEORQiPX1GjmRIQSpGNHOpEpBAIxoZk0dUJlIznTBwTyhOvx+OmBUF0Ij0BGoChCCVxjtnQzJkMjscabMogFQe2pmhRCYEds6gKkIDr+ZGoCogso7nvps2yMdUEj4Htoh6mVBK4PcEaJeoUNlyfX/AMNTMgE2ZPjnvpsyMIDLnJzoyiWoJBz3OmBKWENlPc47amZEoLj89EPUiEBlyNO110VMrXlJ6riqtTMoq0CVFWoCoq0cyirRzqKtDMoq0Q9RVpi6FFjbrbY7pSNTtUT0kgIeOaIgNC49GGexx8j2Px0ucbp2PymQoX8x8ZbvvDWK/bH39cNhV1srzWLWyMnsfkufNEbnpPTCzLHkyZUK7FR+LXRp4ikRD2z6Tt97brp0MS4jISbjaDOxsdx/lRZ3jScl2+dmt3O+3IjdbjU3WvnprdHDDUQzoUQQ1JdljghdpveTMiRnKu/QAIxtMmADAteddTYXk9NNrLuuqlzi1rAHACBqQB66zuTPoov8b8fx88Wem31uHkvek9n2b97UVsuO1t/1tfVzRKXgNaFZOilo36SiwlY5qrqhEq/s1RuzUqigPDawHNEgtjuATeXdrhtzrpie19QtHkdMgy2JvIbHmEyS6YtaASTyvjrw08/00dx2/Dy3yrxJxsm4XvUPIN3s9LXWxKaoZ2ntl0tNXDNT0rFoaeV4S5pBJTRSGZJD5I0UfDdztbmnYO5pGhBB5rSJAnYA6rnY93guays8Z4J05SJuADlI2tM6kGDBtvrZfjz8Gt92rum9bB2p4quCK6ul2vb71s66NDdobM9vimSrrIJI5JTCtTSSVS09LU1EeEnjhgQezhYwUK5JpOyu1LXDQzFjoTBgkgHc7rGzipY7JWYXaXb3uZaYygHpNjroFIjibxoW/eF6u/HXG/F3L9p5MpJTIl0o7zaLo9VTsoboloqmsp6iUBfPMjvEirGIZIyQ8esFTAmS15b6cwj45YHbWSYO66tWuKsv8zQNwCJ3jK5xnSR0kyu58f8AjkuWx9lRU3iV25eOGrzb5pkuFdvKgq7Vb9xqk7wq1Bcpo1plqmCjriaTo6ukQs6uGWmvwmpmmlzN2yw6JG4BJi+vzWem+lVguIDyNNI/8svwGvVTYsF8pNxU1+r7hb5aulaCqjmsW4YBTSGkZx58ohmUxVsTKY0LpmP3mVZH6yDl8NwjLra4uO0EafG/YKqpldlpdb29PgQvACLgyt+yS8T1n5WsdUm8vs9NyXi4WvatCblPSUXCG671UUazPUQ95GttX7AKRHiHTTPMgkHvl39KMacZh3MP+5bMIBJDZNh1kyZI6hcNmF92r5Yik6+1nRlEu/pvA13la94+7rvzdXhbbxUW7imv29VbG3zR8w1F6So+57nDcqSRKSrjmhYzzp00c3moJGgLGjOQQxzVg8rX+CXC4yRrY+gi51ubFd/ixApElp5YcBtyRpMEixvluRHVc/Xkk+AnfXJfNFJttr34SeQbhZN4W63W+8xqNl3KqanofvydHVfbKKujDTecqeZRzVUUzowmaVFdSFZjaYtUFtOt8oOxAgX2BAOxlKrUo1nVwZov1IveIzGDGVzrmDeNIUmfF1sPeNl8V3Hm6fCrynt/wpeKWagmmt71ElLUWLcgNuFU9Dd6aNWhrWlkbs4iNWzZYOIwCKaGKDsM73g52je9gCBynoL6nKN+isxOCzhjKTS2bA6B0k2Im1wLtudAvP3f29vFRHa99eMfifdm1ucueqSpsdZuizV0b2bcd2sQp/KktaWON2o7zZom8yahuEcYlEVRI8TSJJNBrfVbQpsZQJLWyYm8aGc0S1xGrSNgDFisWXFNq1K9OkCQIcGyAIJkQZk6uzBwMzrF54+CG6yeJDa1p3/tfcvKuxOB77uO6TzXe7WqC4XO910nn0dbb4vMVoaG1+UtNHNHLE0rzI5WOGN1aSkkUGBzmjMG6AxacwJNzOa4AIHUk2GltX3kF1B0HMDcQJADYaLTAkZjoRYauXsDab/Lxlbafb9lvu+eZ9u0lI9JQV9XQUntvtQgWpWoq69TGskcat5RKw9YwFIcjpPJxL2vJq5Qyds1oFjAuZJ6nW+8q/C4J5ptZUIzE3MHcwBAs22gECIUZvFtvDbNr4Q2fc7bdk3ZR7uudsFvpqKrM9uv1YGNT7QJoiJCnTQ18riIO0TwRe6oKsLcNSLcVliInUXaNNN4BGsAybqyg41aLgdWxPrIOWRYToDuJtaFA3nTw2Hb0VBwDuo2d7xdNy00dtvW38WOqu1kInr6iZ6aieDqqI4YrhElKxkGWSYNUBuhdTMW10FskAEkOvEWiTOstEiANIGq2YWmchqkEOmOUkNuY0kCGiS4kEm8wAsX4ZYN9+HrbfOOxOQLtt/k7w43C1U+5t0batLSuKawSJGKnclHFTsvQaOeWOmvtqhjTzQxrolLyyQzb30aWIaL/wAwGAT12aZvBv4bjYEBukEeXqVKuBr08zTlM6RvuBEAkai4vNpgx28SdVwduzmj7Mvd11ue09yWfaa8g7FoatLv7VUV1ZbbHDNSiKvmSfzZjV1tHLSlVmDOwYZMmVuw7HltU0pzVGhwAGknKbCOjg7QATMCU+JYx76FOsQclTmJgghzXPuDAIgMN5kwI0BX4TNj+Irjr7YxrVv3iyz8X8s714CpbzRWm3VUVPZZ6m3yQwe1+ZIsrtJBGJY+pVabzw7hgrK4pfVY3DVQ58tzC/QGZAAiAdNQMpvuDRisXSOPpOqyGuZlIN8zmmWgkGLSC7USIjLC9ceN6em5Km37cZbpyLY+DHt1yvN/3PUu4uG9LashlmS2QxuTQWjDApWnNVVpUS+zdCP7Q2HFPZh6ZzsBIiG9D1ed3dGCBAGe3KfSVsTWqVG06Lg05omwAOkMtDjrmceVhs0EgFvm5R+I3ZfH3jUruOdtcd8wcp7r2VxpsuybUtW2dv117FntU8dffamhUjpgociewwCOqmjEcNDGGLLH23ZK1WnUIAzFzsxJaAS1rWAkkx5s5kA3NhdcoVcJhsQykXkU8ssABJIe++gJILWtEyJEQRqpY2r/AM47xO+JnaVy542/suj4YlgjpKvjvau4amWz000TIy1G57lCkTXGeL2iQtQ0+KSQMGLTxxiR8VMUMK1zmODnC+Yt018jXa6QHOuNYaSAuo5tZ9EM56QOwLfEMkWLhPhzplHcFzrx6ZcLwW2xcb7G2VYv7GbYtkdmeWkoLba1tlq9jTLvFCIQRTI3UroYyOgOXGR2OXi+IFTEPc4uN9Tc9pH3pG65fD8I+lhWnwwH7gGYcT9e5Mkncr5s/GfdN3eNPxn1/HFTv+88OcI8QXRdpXHc9BEI7nu/c08NDILdRJNG8UFXSU9H1TVCK5p4mll/AzhOvw1pEYksM1CcoFpAcS50i+UGLWkgBV8XzVf+ga8BtMZ3nzAZ2wxoBsXHMYJkAEmV7X8C7C494TslVdeLKpbtyNuWme83LkDdVVU3O8bulpnhMtbdKt2kkmkMQcRqWAhRukJG2UGXHY11RpaeWmyBlaBAzdI3/q1JIiTBK3YDhgp5fFGZ7rEz0FgDAhg/CAA3cCLmUu6OWLNbeN75dq+8Rmj6WuFbU08LGAQvOZGFT1H9kHWKaIHJQZz290a4DcoguEAWv1g/vfddEYMmsGgenwAEj89p67qFj8l2bcI29w7Zdw7fvlDYqiz3mVKBBcLfLT+1wxwTm4F0hmSmT2hVJdj7RHEvSwAfXfoMzVRVMg3A2nlMwCJ5rRA0cTayjqWVriRzGZk8wAOhAmDPmmLDqV6Mxby3jLRbyuwti2ujiukcdM89WzFYmp4+lmVIwqF2cjpDEKcdJPVgccU2NDZMk6279Se2sXkrKMNTztZ22/ydOh6Sou8v36bZ28uVbjPVbRoNuGK2XS5Q1XnVlNV0ziog9kpKdEMkxaWT2l44lLhiMK3mYFuHcHU2ls2JiNZgGdfwgWJN+tlfhmDK3rBgm0QZudp8o/wtEtHJfI/KXH3GNDx6lRZoJ9u0k9LdLqYk/tAlbS1cjSPSlJegSrBI0bsPxv04AXzBfjMK1lR5qmALQDcAAWJkXuPTWdi+FewNFWzy4yYmLEC0gSBPabCJkCO3hY3RdLFxruPalo2HyDuy2Wfel3qaW5ewLWK70VTUNTVklZUzRF6pTDOAtO86SgzOGBDpHurSaVJ5cAMu5As4CYA2cIJJAgEaiSshcxuJqNfLnSWnLJ0IJBGgykhp3lsQLBKr+a7tyBy3dqm0bjlte17JPUWr2VrfU0s1IlwqBMKlDNGYjWO0zxRxzOo8pg4bD9S0soimAXbwJkRy3AsdIALjrsdweo2mS00hE6n4gCdJMCYAEE+gj1X2Bua03W6UT0cs+4w0JuFIKctOZ8MqPOAhIUKZCque8hkc56VXHNe05TFv0B9dzGmwF7lcrF0SAM9p+Gn5xv05QFvVt31VVe7UouimFqqonenAYNJ5cCkyTPgkKjFlRcE5ZT379s/hQx0m4/WAB66n0VFWlDQQD0+f7fqt3tt6WptFbWVR8poZp4GY9gegt0tkgDuAO47ZPrqh9ojdR9OHQO31WYo5fPpaZ3KGUxKzAEHuQPlqPIBsqiE4KDOe4/LS5kAhkEZ+miXIwkFc/loz0UjdDKkZ+OpMBHKhsuT39dDMpCQUPfRBUyoZXUJhCEMqRkj00cyMbofSMHAxoSgAhlCB+mmzJo2QyM49NQuKmUoRUD4jTZlIQ2XJPpo5rJoQSProh4Ri0JDL64A0cyh7oTLntjOiHKBBZSO/bGpKMILr8f6amYbooRUHGdGVAhFSO39NGVEMr1fEaAdCJEIDAHI0c26kITKB2ONHOpCAU79tHOmg7oTKSfQ6OaE1oQWX4HtpsyIQWX44GBoZlCgMvx0cykILJn6aMox0QGUZ79safMgBuEJl+YGoHqaoDJ+o0cykJuyEemma6CoBaFMY/nryxcuCq+eoXQoq1JJUVaUv6KKtNmUVaOZRVqZgoq0ZUVakqJjX1U1HD58MazsCAEDBWZj+EKT26icYBxn56k9EzWzY6KKG4N90thqLuzbNtbyUVWaWiqbfVqKoiXu49kCySlwRIvkBHLFCQFBB1qotc85A6ZvppGh2+c6arvtweZoJcYiTN2/A2HS9tQLqMPN/BOyt9G38h8m8fWjaFzgmiqqumrNxyWm3UcMEZElwdIJc1caJLKGaQUzlSe/uoD2MLiAx2WQ8kR5cxk6ASLEkWgu9CZCGHl4NOgSI0LTE7xbTobEa7cyipb/DZsbZfFnJ26+P/C3vzfXIzzC7bZ3DZautal3Nd5JGng9usdXXQSNCjTRw9Uqs1SJnnKq5wnXdi3tcKTHNZsQQ3MIEHmykdTE8oGX15NSo2pUnEOmk67occpFzFjM/1Frcs+Uwtd8OG6tkb6t9ypOGOVL1Z+QdrIslZtnija1PspqipjAnq6an+8Vlrq8GVpIJoSpx09XoBqnEV30+XEMJB0NQmCBYEBgaBa85tO6avg6VZgLIbeDl5yCZs7OXNABiOUGbQASmtRxDwt4p7PuS38Y+ILxU8MbNo6ikv7Xat3vXRyybjEsksc72oyezrSGalErGFaaWYUz+QESbzpK/eS1xdiKDHHQgDQdCdSYOhmxGbSFofgKjKLaVGoTUcSQQBBy//EAXF4AaDYSZhl4cfCtc9zbPufIPEu+r/wADeKnYG4btxxuraVbeG3Pte80L3COuoeuVzHchb2pp6GsoZ4p0aHrDBCyzBjisTRaRRcJa8Bwc3lcDBBlplszIcCOt9FzKLq7qxqEWaDyuG3TMBPcaxpGymzY+X+ZrXxZd+NfFp4eeW94UiXasstbu/im10m69v3dY52Q/7AwNziBwY5FnopUdw5DMpBOYcNDXCphqjSYBAccjr6bgDtD5iEK/EGmqW1qYaCLhwLgAROwvYyQWgDvqoveDnm3wl3jkfe/hI4/3fvPaK7Ur6DcW0bTT1+4tpVEdjkibzacW24NTSrNSzxShkiSSPyZ4kZiqDp1cXOIptbWrsEukGWtN9uYSCIIvOot3s4UKdXMzDPa5sSIIdv6G3Yn4KXvjl8O/JG7+L6zbXFu663e53Rcotv3vbO9o4rjabtaJ4JY7gKupCJVRR+yq6+YJHkVhF5eH6Nc7A4tjnZ4yFgkEE9bWMg8xEAR3srcI4DNSqgODtojpYRG0m9oHwXyv8l+I3kHw++BrxcfZ0+JzZF0bkGs2zchx7f6+4jz9x2OS+iiUp50onq7lRzJVxGPy5KiWGOMsiCMZ6zaM16eIY4ZCWzHWJ7xIg6wCTcqjFcQdSpVMPVzZ2teAdZblIEkwTE9JMCBde8925D4D5G4s8OnDlJabpy9s247bqtp2qltVmN5uFdt6SywQSwlaUmanB6kppZKiNfLmlGJFc9KcvPXdVqvZ5gZIkCIdYmY62jULucOw+GoYRjajgKbmtaC6YJDSNIMwBJ0jcLz58Hdelkr9qeGPxN2Tdk9w49v11vd8m3FfEq6xdqT2txZ6qSaNkkWCWmqLfbxEJGR6ujmTpy0iDqYkGPGpgXAEC/PmEgDrMns2+wScOqOc/wB3zONQGGk25IMGbmABBMC5ANzaX+9/C1a937w5C3b4Vt47S23yWFudpoaiqlq7rHXQ1kcU8Fpu5lZZqK2OZHi66Z4GoqgUs0bITMmswqBrTTxAIBubBvUF1/Md7zmEiDYrXi6jg6nWFy2I32mBl0FiYEkbRofG7weeIre3g48Re5eH9y7KbhviXebUe3rtZLnfoYLntrcD2KeWgvtNUxienklrIqdKCR+lBU1EVNM6QyVBOt+PpGraxcJywDBgglsWO8gbXGy83w6qaFdjSC1jozZjffnv1IILrSRO8L3/ANrcv+Jm08U0vIzcJ3nfO4WWO8VcFwulst1L7VUUsKR0tRRLVSmieQSrVZcqYnfocN5fWvJx2BaH+E17RAjUu6yQcsEDS3eNb+nwePZXbJpuAOggNJAvuQ6TpDtomDIELuXt0bI2zxtYL9zvx9uyi3nRU9ZaaO9LQ098j3JU3B4KetmN6tk58u5e0h5qUuKeWRykHTLTmQx9OnXeHuGHhzCAIbbKBJaC1wBIjWZGriQYnLmlrTiR4T5zHNABc1sHLGcCActogRF7rMbC5L8R/KW9uAd8Xq5JyLxlV7e/tEu2p7bBXXafbMNPTwVVRdK+J4Gp1qZpZAIjGrI9JUxqzr1MaRTZSFQi0a3IaHHygT5iBJ1MiDA0Re11UU/DIZfK10cx3JgAtBENAIEtJNyV1raW5uL/ABFcu7jqrlxPuCssu1LnLYV38m8K2wVVluUjyCShs8zCnq6qoKCMTU/mPB5UMJHUfcOOpUdRw2Z0BrtA5s5gBEkXAaP6rGSYHTTVpeLiG0WE5qYOYsjlcYkE2mRNoO2YlfPre9t7Y+z2+0q8Gtql5l3LuDwd0tdd907PkqZ1pKiywXCOenqaepmdFSTzJEpwJSSXp3hjZ06T0dbD1c/iOc3K8tAIvHURBncyOs67+Xr4I0MZQw1SoPCzkyQDDvKZMAdgYtoIXqj44juLlz7WL7Ma5znenEtq5D2pftpJuGuqIYamt2/UKGNNBHTPIYJzHPUIZ3UJ11ikdQiBWvhjGUWVQ+IbDiAZki8GYtIAImYB6q3ib3U34atSiZeNPKS0Am8y4zIiwtN5ClJ44vGDw1wVZ9yPx3c75v8AsdDTyPcajaNG1bZIOiGoFdapq2N2gi6reJZVp0LtEaNWVT5YzzMPTrkipVZYkQXQM1wQQDBMuIEjXMvT030KDW03nK9jTDQCSwQAJAEttOsEgabKG22vBdztZOL+IN73KzbD4/5Q5YudVvHd9YldNN7DV3VaipENyjpIgRQw00dLQ08PmdMPRI74JJXuYuM7qLTmbSEeWbiMxEkcxcZJiwygbTxeA13vonG0m5H1HHUkcujGgieVrI6EuPTSVV621beEaLgniGexQ3kV9PJY6ilNzqB93TQMqw18tbJMEhUSrVyjzEleHyicyrFG6cgVg57sQwhpF5iwt6GTEExEzaC6/q6ZLKfguzEExZ3MSZMC4MSQ0X2ANgQu8eILxJJ4XfCvuTmyuWj3DylatqQbYsbUVdldw7quM0UNEYlljVUpneoiqVhRBiGbLIfRaa1M4ysKFEFviuAEzIEcxNySR1JsQRYlczDsZgsMauLILaQLnC0QNGiIF3csnVaP4f8AjDbHh18PK8I3Pd8t5v3H9LW7hv25amVXe/b1r3qBX3y1VAlM8VRBV1DQiaMFY2icO3SWOuni8Uap8agIa4BjRN8g0JGkOiTJE7Bcbh3DWTkxnNVc7O8kEQ6xLSTYwCAAdnCI207ijm6p5E8RfIPAnItveE22726lWTbVNTtTXq/1Lf7PfIMRRx2+O4Ukc8zRuTG1RTzsWX3Q9TKLBTFU6gnUkZWi5aTvECIuAe9uox/gk0w2IF977GBOpJBn+kbLlPLOxN8c28+cgb52BR7Y/wDM3s9rgtVypr3cKqmTc0lc9QValmhE8T08c1Eq9c0CisWpRW66dxI1GGmk018ReoTygiSIEgmbiZECSRAJhwyjb4tQPZh6YOSDmuBJJyuiDHLcONhchpNyp0bbXbF/4Y473+914Vt/JFnv1uNztUl5o45LAWnpYqiywy0xWGgCBYad6fAVXgl7EMWFr6oFcsklpJBIl2YkO5iTd1zI2iB65MGwhmUUy1uWwjKAARFvQH4n0Uz6DkWo5J3XuHbuyLNSwbFjs7U91vBCR0y9HRHDTjzOr9shSTqEaSRJgAsesAc1zIpmriDF7Dcm5J9L7lvQaEpadEUxTygucSd5jWd9zpqdzFphJU7hvW6ObJajbFutO6eOqG8xDZ1tC+y113qYaWmlrr3bEOUe2L5qpGaljJM71jIxUw9XSw7XsZnPK53xhpMNzGwDnGIaBZoE3JhnVGvbzg5QLumxdeWi/NlEy4EDNAA5ebmvj45gtVitG+NiNy1xpt17NFb7luPdxs0FNBx/PNVey3GjIknD1spoq6V4rbAskySTGSR6fMeRw9rHFrzmyZojUvHYAHVzQ0uMNAESSCFhmqymTSZzZSQc3K0AAhziSA0QSWzzOMQMpkB4T2dwjuTaO2L1ufjTmbe1W1bJU7dsN027V0ltskDVlXS0MFsttNTw0VJD5PVM5WDzy0/Qsg6+o769fEOfmaLkDM6Q50wC6XEkwIhoGVu5AAtXw/BMp0YbVimHEgDlAAcTmixLnTJc5zz+Igk37TxrsbZe9PFBzFZ7iKev4X2dabJerosFoipae33Q22QS0VXUR4cMKZaJlDSPIAjeYw90NgxGPjBnEOu4ucGkmZ0mLX5pkARtc6anUjSc3D0Ya5wbLRrq7KSN7QRproApj8d7H2VbNu0N625AvH23KmhcpHbZXMtXNNFHO/tFUxWdshuzBwFCL0yBe2sGMxj3yysc2W0WAEGLD166k3BJThpY8lgkkySbk6gdRpYAA20Cdcd3u41m59ybkltQXYEFfDSWy4MscNNV08MMbSSR9zLKodjGHkUK8ilVPYFqsSC2mHZpe7MY1I1A7Cdt4uRCerldFFsyAJ9Tf8rkDT5rauGY3rNiWYVFZXxx1cgv9VTRJHIaypmVJDFFIAfMhEj5aZiAzDC+4CxtxzMj4F8oyjt3PS2g13NyAsuJqZnudaXEidYA17TFoEgC2ukirJZjbRPLUP51wlLM5yThOosAfgTljlvj8OwGuW+oDZun39/msznZvv7/ALLNlkUOzMoVfxE/4e2e+q5spGyt2K5XuCMjUKYAIZUj56IKGXok4/Q6kyE2VCK5+epMKBqQe/w0ZKkIZGTgAdtQORCGe/w0Q6FIQmHfPfRDtkUjRDt0IQ2Ge+P3amaCjEIRHr8DolyACEw+ef10cyMIZX5akqQhEEeoxpiZUQ2Uk5GpmKMITD5jTZlIQSD27EDUDlEJgB8BnULrqQhMB3B7jRzIjW6Cy4PyGpmUjqhMO+dEO6poQWBI7Y1M6OVBYYz2A/XRzogbIDDHfRzJpQmGiHIEILD1+ejKhCCy/PI0cyLR1TdhgkfDUlQ9kJl+OmLkcpQmGR8dHNshlTdgMHP6aMpiEBh69tTN0U2UwWXtn1GvMrzqtqKK/wDHUlRXwfU5zqSoqI9fTUCiTohRXxnQlRXx2yR21JUVuk/no5iosNdaAVcc4ajoZo3h8p2kZgenPdSFGSvx+h/fohx6q2m+CDuuXrsPYUF1S8Wmx2u7b3ESQG4wJ0V0ESkFUFUMOkQKZ6Gchsdw3prX73ULfDnk1jb/ACtD3PJzVLet/W28/cLH0/FtBVX+Lcu7Vk39fqapWWmkrYEljo6hVPSYCwHQIw7Krdh1O5Izgh24xzG5adu+nr8/yFtUcRXa9gpBoa36x+51PURss5vJrNTx7YtNaKm93Ce9UkbxQSEzec0juZHAK9SgeZ2b1AAAY9tVUiXElo0B+AiEMOHQ545QBI6bQP8AHdct5Z4m465WtVfszmTaPGe8Nm09KtXTVVXbR5tD0sCJRIPeglVo27xFSyuQO5I1qwfEKtJ80XGTaNj2jQ/EItwrX5ajQcwNr3nsdRrrNuq8Tubts83eH/kYb42BS8r7blqdySVy7KvLx35L05pYoKaNKyAm4LTYFbJmomqZKSKTqMMAjDJ16DWPAYYLiIlsgC8uN4aDGuWMxtJkz0atfK17qTs1MAS4gSQJAFpcRmIAJGXXYKOu1d4bh2Fz14dOZdz3vdvhx5M5C3WmwbnQ2a9W1LdvWx1NdUCyvJWyCao9toZzSCWCthpJlpa5ooeoKWO88O/kuYW5wwZpOblMc0gAQHCYMuBcJJ6c7G4xrqpd/ts8lgCXiwEGMpIOzQC0EyLL3hu/C3L11pLjLs/xAcsDbcVXJUfdtIbbC91uLVEkzFKmejmmo0MjxtLGC3qwVF6SNcZmOokjxaYmwEl0AAAXAc2e36qzIxjiJyl1yYBLdLNmREAgSLWIIlR65C+zfuXPuwKTbfL3iB5Su3KVovE9/wBqbpoL9TyTbYmSNoUeNZbaGlidCIJ6YsIZ40UFE6zjTR43RpctKkPDOo5xO+mcidwdvguVieGudiBiXVHAiI5acyb6hoMGbi4O8rnnEUvio4b5t2l4d/Gr4kL+t+3HLU2Ph3fFn2daZNr7u/YpPPbJ4DCJ7TeClMzrSSzNFNDGwp53YPGNL6eFdh3VaDMwmXAuOZvSbQWydQNYkC00Hi9dtRzHNaDbqAYGouepsZ3MnbyT+2W4Ds1Nsfa+y/Ehbtv2ao2jui7br2pumyW2e2We/bdujRLW22hri7+x3O31Ukty9gl83zo4A0bv1zFL8DVY/wDmUXEghrbwSHzAJA2ItmEDaBAVnFSMUwjENh4MzJnKAcxnqYm5mwK3/wCzU5PvG0+R/EHsrlba+2dteNDaVHNW7w6Y4Tddw1Fshp6a91MbHBmSso6fb9/j6epJJmrChcyvqvHn+QKTPJsPWS35OzMPQEAxCt4bXa6u11ZwJPLOgJ0DtrOaQRG9ypH+Lyg35tO78Ffal7dvFt3DxPb9mbatnK20rdZJqaq3DtZpluNPcS4eUmrtUzpWqixmXoWdeogCJq6FbK52EBIdmJbJEBwBbBiLG4nQfMjoV6QzNxVECAHZjcksJBMToBAMWJEx1Mt131y940t032TjHaHF0VJa7TT2S77nuF1pjc6Oq9nnmZKWpo3lannZKqhlHUVXHS3SB0suI0GUqIbVqWcfLcjYbgSBcSJ6A9epSfh8M3xWMJ1iCNDoYGmgs65m9tPE7x4+H7xKU9HwVbtubV5LvfM/E13mrdh74p9rWKrkavgip1pbfc445p3vFOKe3wpFUQjzMRIstK0gQN1ximh/ih8tdrzGbkzls2JJMg9bOiY5OJ4f4+FENIcCHDlJiAIDxO+pLR3Mb+xP2cniz2V4t/DRb+dq3dvIFpv1ZE+yd37Ou1ZDV021b9TSZSCokjhhkjRgJTCarHuPEjF/LI1zeJUjSJohgAs4ETMaWkn4xOkiJR4ZjjizTq/ikzYA9SAO0i4v6KV3NvE+3927WvFtS4bbist1WSS/RUbU60d0R6X/APD69S6rUU9WrOJD1nyi5kiaFnVtctmM3JktmNdZ1HTLrpewM3XaoYdrpbk80XieUE7R8G6HebLwp8HtRybxJzj/AOZvyNuu/bGt27qzcW2eN99X65Uho6+zPHbZai1080yxr96BpaiSmnIJlaeeo6JKhJEk9I9zTRL3gAiC4Cdi4CRsDEHSAMogGRyqtXwKzg+S0HksTNg43aeY7wScxu6GghS/2RzpwDbuP77tmapquWuSa/aUFhodlbaEm564V9BUVdopZEigMlvtsrw0sVSZq6WJYhGkzMuHZan4evWJrMEiZzeVoBhzgXnppDQTcgTad5xVGkWUapLQHGQYvlNiGed+ZxAEAAu1iCvM37aaxbq2hR+CTxP820G0uOeO/vG/bGqbZY6Q7kvlPbqugirBLcqqsKQVcszwyhhTQJGizOySSlwNJTZRcX0AS5xANuQSHWDdTF9XGSRBAuuRxHE3bXqDkpuAJcA7zNIPK2wjLoC4jYwoL8i+EnmUeM37OnjbnrlDcF98Mt6vVs2nsW2XLcMNbcuPLLWFqyktFdURxezpVdBiBaLzYh5XkqzLAo11sBiKbK732LmgudqAXNbNjYkDraTeIcvP8WoVwyjMsoEw3lGcAmJyiYJjlkuLRHQr2c+1U4Y3N4nty+APwe8fbsssG5uRd13S5UV/uUytTWzZttosT3CSiiWnp4qfy27RwxxmaSQiORUJ6svCajn4p+JqgtFNoc7UumQQJJcSSYABMDVw6dz2oxDcHws4agBLntZAgCcpzGwAJg8x1EwLkr1I5GoXk4/u122tcd2c4ckWqG47fqtsVF2pqWK+SVM9IsiVUtIoNA0iJFDHLKHpzBKsTAph15XjudDcgaCQZMmIJImbG93RDiROoXew9OajX5gWsFoEAmPwzNxeADymSTJkwC3tcNxcpWk8abn2DtPjvkWq3Maq21d7Srs9NtmneNaOP74iCyR19FItXHQU8rNJTSA1Kly3TILKbKrMribazY635ejiRJ0cABa0HXVqUagLKbiTERN7G4MXhsnMBOYmx0UIOR+Sd6+MHlOwbD5U3fScQcYcDCTcW+7ja7pTU9xbeFRVVVNS0Lmqp0gars6LW1K+UjNJGkbxmNpImW7Btp0ScRmzF0MYLiZaC51iXQ6zTpcwTqFz8dWOLqMwdBmVo56ggEAAwxkEZQfxcxMgTBtM56jk7wweGbwsch33fvJdXeL1JPcaXYsFfWQT3i99FNGklPRzGITzeVVTzRg07u7vFH70pYEjFNxNTw6FJhLnXIAIPmAEjpAtIAv8uhh6bGVDiqz4pMBBc4t1guIEE85tN5N7dYTtwJzbztUcseIK0eGrxI8e73obdaWsk1JcoNk26ittKtPM1Pc6isqDdJqh1MtOZ6OCJYleTyU8qZ3fcyjTw7C17mGXXBObcggNaCCP+48xAzREDg4nHe9VKVbD57thoAgkESCXvIAI2DfKCYLzdSs4x29zh4xuEd1cY8f7+4j4Rt+9baJ75a6a31V8ulu2zb6uK2QW64XCsaKGJporbNFEIaLzHUVEpfy4mD56jcM0CpXJfBBMQ0Fz5dbzOJiCbgNAAILoC1Oq1m1A2nTyDyNmXRk5XOgBrRckS4uBdGURLhgLb4dbDxP4dub9vbc585wntO3Jai07XorHu1NvWujrqWmNdHNW+zUdK81Q0UMx6peuWUQ5bv0pqr+JU6j2VqtIXN82YkNBggDOQNrCwnXdX0uE1Kdb3elWyCDIApkuLhaXBkzJEkmCOoKn/Z+DuFr5tyjq+Orlz3vrYVVaaSGZr9undVZTbkgqpYJ0SjgSeFZvM9qkTzCRC3XjD5JF+KpVQ5zKtNrSXQBlZIgEAuzTFoNxNthKycJ4i3K0OrlxILjDrCbk5miJtbKcwGuwXF/EDxHuXw/+HHnCe27j5hroNm7TqauitW2d3XS2JaWlijp6OnmnqKlsdFQqyRCnMeQ/SFIyFyMJxDg2mG87gyXARJIuANSJBvPeNT0sViKTKYrOeWkZiIILiGtMgS0wCLdo8ywu1/AvxrcuO+GOB7U1XuyS+3fbdZufdKXu4TXW63CnaOtuNUtdPUKS4e21MpMaqiSVqhUaR+odB+Jiq5+WKTM0NgAQBAka/iaL3ImIauEMPkwZFZ5OIe0ZnEgkkuDj+EiLOOUERlzOmAvRzhO7cO+HngOyw7O4+uFNcLdcpLTZNtJLIJai4fe0lupqeLzXIwZig9obqYoWkPUQRrjVG4itUZTJEuAkxYAtzSYFgBMgdIWvHUQc40ptJ13i+pkuc4xGxJEwNMVZuFuP+E9u22k33FS888r1t5l3FuOz2my1VYlQap+urlo7NAsigKWidWqV65hAMkMwRdVTHPqf/igimwZQ4wDbSXGA0kjRpESdbk82jUcGuq1iKfiGDBgbw0nzO5eUkSLCwEKH9tvtw3DuTet+414Y3vxJthLZU1tXuO93KHbdmtFupR7THIKVmklkZelewhKTdIeQKUj8tMTXysy1qjSbG/M8nQQB1zDU22Mkz6rC1A4s8PNUBOUZRLRNiJMGOU3G5jyhSm2PXbj3vZuP7Lt2O53LYltlW2PW2un9istrkjpvOqLhVyTmN53BlLLGC5aaQdYiHmJqzFFtOq6o+wIJBJEwOUNYBIvEA6AaFxAXOo4inSpltNwNW0i5MuvBOwi7ov2uCpQ7X3fEthW18a7c3fuSigXyIHxFFTALjOJpGVZ5CuSz9TL1SdyD1Y5GIZUfD6kNJvc/QDYCwFrxaU76VMPmq8TvFz8YFusaxsLLeLJByjuKgs9+vFqsGwbxLbYIqihqJjXS08pw0oYwMIsgl1XpdwDgkkDBVzKFN5aXFwna31In6LMa1MCGAm51t6WufvZdDks8tVL13CtFRRnJkpViCxyMQoHXkksB0j3T2z6/LWRtUAyBf8lU15gDfqswTkkn10gdCcCFbHcHRzKQhFcZ1JGpRSCMjGpmCiQV7ep1M1lEPH79TOohsvqe+gHbohDI9NNnUQyn79NmUQ8amZGEhlznHrqB0KIWmlHKhMv5nQkpghkA6bMoWoRXHp3GhmupCEUHw7aYvULUIj4aJemDUFlwe3fSh53UhDKD8tMXoZUEj6A6gejAQWUZxps0aqQglfXGiHKBqCyj5aIdvKMdEEj56IeoEAjH00Q5SEFgfX11MwhHKZhAYDHy0cxTNEoLDt6afOEYlBK+vbvoF3RABBYepxpg9GEFwMevfUlNkQHHyzpsyMKXp9B8deZLl5hJ1A5RVo5lEvOf8WhmUVZ+B/hoT0UVZGPX+GnzXUVAjGc4GoXhRKBGMA9wNKDeVFXYd8/TTFyiSzIq5cqq5xnUzbqLHxBVjEVHBT0SM7AlABhsnPugd27E5P8AHTZiTdEti5usZer/AGPbtm+8bjURw21JUgLM3cMX6cD4ls98epwdLmJsrqOHfUeWt11UVOQuR4ZZ6rdGwrTyZuBKC4U8Sy2qiMtFWdSRl5THjrqRH1Ih8vPUGlX8Sgrsw9FzxBAE9TBH6Cdp7db9+nhhRblxJGhkau7AQD6wNLHQEJruHeL02+rRe95bR37Z9k7dn++qu41lpdre8widI64eRK5jWAdbuJQxVWWVujC6uoUXgfyyJdbVvxF4ubAR3F7rFXqUm0jSzS50DlDiYJiJy6E66D81vPI3GVJvw099u0lXW3aJSlv6J4J1pWlKx5gYr0RmUdKN5fvtE0gL4bSYetByAwDrr6wesfLsphca1jYaIGuhm2/W14J3iB0ze+fDtsXl/jjdvFHLNLf937GvFL7DXUdXdpJRUdLB46mL4U0sUgSWExgGB0Rk6Si4dnE3sqNqU4aW6R+R6zvOt5XKqvDgYDZN/KLeh1+Myb7kqB/CHL/MHC3NFf4T/EnuncXIXNVvt9RWbE3KVMX/AGx7NjZDJcOgDyP7TW8MsdZEnQ0sQWZFKzZj6WPoUn0xXw7YpuN/+Do8pMzkdqPlqFm4a45fBrEAj0AOnQTA/p6mekT+3PuCAtYLFa2qrbXVMUj0opGWIzU7JiQqxP8AeN1iVSQT1LnByTrgB5cZIn70t8tl38JhiAahIIGsif2FtCtC594PsPiT4r3fxByLSbnpLbWUsMsM1tenWusNxhZZaK70M3WWgr6aeOOeGQYwVKnILa24DH1MNWFWnBI1E2IOrTbQixXNxOFo1WAmN4Jn9oj5rzX4i3PaPHHwpyp4b/HNxVtTfHO/HW76DjrlLbFyVFortPPIpS/UqxEJSR11JURVEEkTs0Enm9LADv167hg6zauFs14Jae0HlJOsGxEXtKsoD3nD1MO93KB01gDIYkm9ztExqF80XiV4i3J9nl4+vC9R1W7t13m9HdibVtW8JaiMyb/4wr5I7fHHU1TMipdrbE9Va5vM6P2TW+bJC511GVqWJpGWw0ySNmuHNG/KbEHsRquRVFfCYmlVJ52kNEiZabdpyaa3BF19ePHEnF27+MtlcbXuhsF6sN529JBbKOhuNbc7ZVozTwPRVxiIE1O8aJKjSNH5vXMyEnGfL1Xl7nVReIJJAEWBtNgeg2svYvoPoT4ZIaHFp0BO0jW+zoDo0O6hj9lfxtbePOd+ffD5ujalvse5ONNu2So2pW14hnuG6NnV7VbWWpnjj6mZ6GnUWmR+pi3scI91u+u/xnFPfh21wfMSDGxAGa/cwQO5XBZVGCc7h7LAmRBgEX9Lgk3I7r0b8Rm1rxd6/jjb42lS1+y6y/tVV1TFGeu3QtR1geZqZWWZ1WadOkp0P1yg5yhbXBwTywve7QNPck2I7XjvYHqu3gajCyQTnBA1gRb8Wk27jQr5dPtd6O6eGfkKXx4eCzeF+4m5dvFLSW3mKybf9sRaKqWSJ7fuWGBlWmBcpFFJTVSkxyTUztGGczH0WAf4tHwq2jTykxf+ps6yJ1b3GwC85xTBYjA1DimXBF+kGwOW8xBuRlPWZUvPCZ4uOf8AmDZFJtg8V8W8+cb0Vkt183/urivctvFz3RFXzM0UlLQ3JIIae6SPB0XGCKSQwp1wAI5gcZalFtNzqhqWBhocHNEgaSJLmiZBMSYuRmXawuLqVG0w1hzkSHDmaGiwJbIDTrDSTlidYUNfGR4iN1x2j7Q+g2n4WN926JNmWS/Gwck0FvNXYqoy1lFcb2tlqJJKie0tTV5xPSvPHDUxLK3k+YEXVgsE9jaWZ4a4uIlp1aQLAgZc0jQwSDAkocU4m2tTe5jDUaxocA5pEOabAgkOiBJIG0WFz6QeFSXYnBG1uDuL+Jdy7Z23w7aeIrtXVc93tVTS0S3CK80kcVwnwlOayrlhheSRZCzRqxeQs0hUaMeDUe7xA6S5gHYEGQJmANzpNhuVz/ZnBMbh6fgMAeQ+TLZdpqRsTO4Ji8ABRP8A/KMIp968HeGLa22K2DmDkm68szRUltt3VUUdXM9okVUjgWFVfzW8ohAxCYZR1kyPrh8JLXPLWyAGm5sdQTvtcz6aABbeP0agwIFRkS5gDbGfNvMxED1NzoF4seO6l5B4f8Pnhe2/tncm/t57PornapdsX3cVOKWu2bfrdTSmoslQzp5lRAhuNJNTtMweFY6qEh0VGHVwuID6/iNbDr7zLSQARtsQ7WbEbrkcbZXwmAZSe4uaMsGLhwH4rAgEeUW0M6BfUf8AZt77qvHX4iebPHFyHs+wxbU2HsKz8G7Otq2vEiXCKOCu3RWRxYKhRWNHRqYhgxQDo7EBs+JxXu+Cy03EurPLp3yAkN/8jc311WV2EGLxVGmWjw6IvN2+K8DMADaGANAPqdyvSTkO8cZWfhPdnKtlvVZs+groJDG9DBIiX6SWqhip6SrpwqPLUPJJFGie5J1tKgYKX1xhUfVqNp+Z5IAk7mZgyRGsm4sCdF7PBYU0MQKTWgNYDNgAABdwj9Ooi8Ly1+0x3DxPxh4eOV6HdW2bRuDeNgta37fN8iqVr7dx/PNUQz0e3VeSbzKhqysUD7qDqs586rqPLgZNdijXfmFSkZphwDLXqPFpFvwi5dcMbA5nmDzWYljmObUJaXNcdxlpgXqGIADuUDd55GwGlw8BvAjVeJfd995r2xRca7I21y1uW4Q7xqbjY9m0st6pqO5wmX2H76rpvYbFTLErLCnl1NdGaeRIaZ5EyevSw7TTaC8lrTB5oBIvctBe506taIgyXNC4uAxlY1atR1MCpVh4BaXOA0bDXEMaAAeao4CbkPmF7ieFLwib2rt1bhh57vtHsm4VRtd0jrNoh9z7s3ZXW+uSWGju29rskhDU1WqSywU1LTxuYwQY0hMQzu4pRZTy0OYbAfy2NkEF2VpzutMOc8/1XkFdPF8IxFd7H1mtBEy6oTVeAbwAQ2m3NblaywOUXJJ7r4ja+Dw1ffXHnHvNvJVb4l77dRZNrUF23xPc5q+nrvMZLjerbLGYloAsczSsfKjCwsY3EiqdchtX3nKynTApgcxDTyht4DpN4mNSSdIldKlhXtPvleo5ztWtlpaXeUZWgNIAOv8ASAb7KCvC3iT314b/ABGc02as4bo+RYrDebhuDcdfx5Q0Vn23tl6ehoLfTXWWuljkEdvih86mmIapmSriqZI4nkSfq6JqCvhmudU5LgOcTfO5xMACZdAyhoEtBuAQqajvArGiaZD3gDKAXEhjA6DmeP6iXkmOZsxBC3zw/wBbuTxE3Pdl54t3Bt/kvY92qjXyzwUPte3KSsSoWKR6OjaKOomTzKo+Zcrj/tFUQz+wNEsYJLadJmR0ggAc1nXG4uGAAcrG5iN3tcSRe3FOrnO5rQxxkBsObykyJBBqO6uHh0xIa3MAZ9guAeC3o9jcZ7efxC+Im8V+1oKeGppGqfcppqcS08MheWgEs4j65SgY9OMOqgop1zquNYx7iKQEjU5twJ/HYxrve5uq8YxzWBrg3KJ/puNSLbTFhFxG0KPm8tibe8QfiJbblHzLva+eG/jq/ne3KVXetyGps943FS08M1utFenQiSwUNPQi5TxFxHGZLehUM7DWvB8RZSw7eIhjWkAtpxMzJzvEk3GYMaYJzF0HkXOx+Gr5v4a8czgMwDWg5DZrCdR4jiXECCWtJdIqBcGuXiq5N5Y8TO9PEZwpszb29drbd2tcNuT3653Fts7atdTLUwvS1d5q6tZHFxaLpmNPFHPNR0slOk6o9VIsZw/D8mGNKo7L4hbBPMbE5gxrZzR+JwgF4yNJLObUx1DxKdKiwuLATlETBaNXQ0Ma6Tkb5iMz8uV7CGezdp8n+Lu+bn4U37z3zjZFpN02/ctM+2LNPZZ+l5UnirYLermroaMVMVTLHcLtUDqieN6WkRnDJsp0qNBpeKXlkQ4gwINnHyB2UwabA+oTZzhBWDiNepWa2o8huYjmaDEg3DJBe+C3ztDKRNyXiFK7kvw97R44gsPh72Fx5svlvmDclTUbg+76O7XS0+x00k/l1d7ubS1NVBHGhlcLLKJJJqkxrEjt1dHNwmLdWfIIbTpxmLmtgA6NEAGXaBrRMSSQBK6n8TNKkar3PzOkDKZL3ACNTMCxcXOytEA6taes2/wYcS3KW3U/Onh14KrWoV9tjtO2rbRz2v8AZnphevWojjrbgEUKAkrGE4J8klAwsqcfeweJh6hLhuREE65AJa31u4bELC6i7EgsdIa4xdziXADRztIOpaABoCSF2XjHYvDl+usO3rDw/sjbFnjSequVt+6YaVkYSD2elkpMDMSqzS4ZMEGPsARnnVcdiGjNUeS4WBmb7meo0sfit9ZmSjyOMOtFwIiCbxEkR6KS1t4823ZJrcbRRfdVvpB009DB7lNG2fxCIYAOMDt27A4yNc12LcZkyTus/juyZNvv6LdldX6ukg4YqfoR6jWfOqlcjPb4ahcEWobY79jqZlaEjRzbplY9hn92hmlRBP0Gjm6qKxGdDOjCCfj2AGhmCgakH0+emzdE+WEMj8/nqZghllDIzjRlEidElgMdvXUDuiOSyFqSFNkJx3GjJUDUgjII02ZMQgH1Px0JUASGHb6aIdsjCCT8TokwiAhsDk5B0S5SLwgt8fhohyMdUHUzXUDd0Nx/189TMiQZQiM/lppTCdUA+upmUyILDB+WpKLWwgsPjjOmJCJBQWH79EFDLKAwzkamaEYKCR3I0c0oEIDDHr30+ZGEJgew9dQvULUEjP56ObooAgMMg+mmzowm7AHPp+mmY68qBS415tzl5dVpc4UVaJd0UVaBcFFWpnUVabMoq0Q5RXBI9DoSohSytFGzInmSYJVAcFzjOBn49tQuUAWqw3T2qSpoqinlqI2VjChp2xUqW97qyOkFfTpz39dMCdlqfTyw7T46frdco3xdN3bTVLnxxQ017qTOJJKO61ISlLO4V5WmHVKr9PWixqD1uUXA7ur0wHnKTl7/AKR+ZkQJK30aLHtPijsIseu9o3Jg/W/BbfNz1yzvK/07fcfGOy6ftVVUjF7rR18kRIjoqeN6qmZ0VVZ5JMriQGPr8xvL1soUWsz1HS46AXBiJk8pA6RJ6xF9VTGU8Pkp0qZeYuSQAGz6STO3LFpXQ9u+Fi3NbqNNy8j89XHcShxVVdDuyttdNVsZxUM5pqSQRxkPjpTJ6AXCNhmza/ibAbUmR3EnSNbT99AuPicdUL8wcBroAdbfina1hfUgErZajw8bMqeg0HJnP0tajSwySx8i3Or8rqiYN1QzSywA+8v44yBkDGDgg8YY7lNOn/4gH5gg/X6qhr8QzmJjTVjYN7fhEj47LnFNx54gdp2nbNJs7mbb3Ju2dqVdLU01o3paloa28wU9O8SJJeqDAUjqVjJJQye/EQR/j1pZicK8lz2lhcDcHMBP/F1//tv8Ej21KTHMawOe4RqRGhPUXjaLeq7rsHnCxbtvw2HuGyX3jXk4Uz1QsV4CkXGBApkntlbGTT3GBepSzwMXjDKZY4sgaxYnAuptztIc3qOvQjUHsQO0rO2sN/yj5g3H1G0zZc/8WPhq2/4nONn2ncLtuDYG8rRXQ7j2ZvWyRxvd9jbgpj1U9zt/Vnqce9FJAfcnhd4nDK2Bbw3iTsO8nVrrObsQdv1B2N0a+FZVAMw4afsZtHr3BsSoMeHLxV71ve5dz+FTxIbc2xtHxebXudBU3SosMLwWvcNDPI7Uu4LWe8n3fXSIIzB+Omq5Z6UgHyi+vH4IQKtAl1MgkTrb8JH9Q+RAmYXU4VWhxZXJDgIg7jSQSdIm+0DVTe413/yTurdO8Lbc9qLsWnpbgop2nmWrp7lQtTKyVPnELK4MgnXp7eWVKEno78qrTDQ0k6z8IOkdYhdPEUsO1m7iBHS8zaLdtJOsBQE+0F8BvI3M01bzt4Z910Vm8VVuaioZ4pap7ZY+QrPTVcdZFZrw8PvJLDInVTXAlpKaQ9Oeh2C9jhXEqbA2nWuwXBN8puCQNMp0cN9dQuRiw9rDUwwyOIgiTLhve8HdsC2twSDCXxV8ObW+138BPLexuLOPNy8feMTiy7z1440v12c7g2JuVOky0FU0zOTDWUomSmeNhTTlKV1YMpCbWF+FxIbVIyPEZh5SNiIiSDEnUXHrlxlehicKX3DrG4vJvHoJmdxewUyvspuTNp8leDXw4brt9q6tqXexU+z9w2eqpup9v7qtEsVHUW2dZWJzI4nqowy9QZmycuDrJxui6lXeDrqPQjbsBb5LXw3GOxFENjK9kySbxfm9S7W87x01Xxu/9ofE8XD/ANol4W6Jd/7x4op7jaL/ALYNT7PW7u2L7aUutpkndStSY3ghraXzCksM0LdLTB2QXYWvTdmwVU2fBB2zZeUjpMxuCOiOM4VXJdUAlwvYzOki+lgZgagdTMo+PPExZvElbuFOS9m119O3tzUVq3/Ty0lMtwpYbe1HIKW11DDEaPI9Q7PIpGZY5lBI8snGaBoGowxLJbrEkxcTcgaCQLQbGQutg6IqYWnWpEBrwYkXieYyJANhYkwLbEroHJfhK4n5t46ve2/EH/au5WO4W28UF+slFcpVp77BcDGstRU02DmrVwTFIrDyyE7kL7udmNbTdNIAm0E7RNgZi+8jWYhU4itVq1HUaQHhusB1GWACYkADYa95hfIJ4TPDrz/4V7nzXt228ybvg2zxTve42Tl/bMtqaoi2/s+5Uapb9429opB7TSy+z0k1WI0Lxfdq1KeYsDK3q8TQo4ljHNkZxLbxJBnJ1B6SYMkbhcThtWvw3EuY2CxrhY6wQRm3GnmnQ21Unftpdl7g3TsbmO40XFl23zNt3iza24bjvGi3NSXFbDO811qZXS5NIKipp6qmm8+Smp0EU6FJCuFTHOwNSoC1ocGjxCADImAyLdW2Ac426r0HEzQr4F9QBznBhhwAECSCNoBykOABMCCJXoJ9lvy7fuWWl4e5SXdfC3KOzttbd2vU2Ovvy3WKssFXb6iWS+UdSpEU1NXV0rxxxdMgjeNQ7sysNTiGHp0mGqwSHSZjplDW3vYSSRFpjqufguJVKlI0qtJudsWMS4k3JF+UAATmvABiQE6+0i2zxbZuWvskqW3VVlj4/HiSpc2Wk90UapQziokQxMW6DJGvShwFIKplW6Rl4VVLq1R1W58J221o+99StnFKdYUW0mNObxKdyTqc0CNBA1jQa7Lj326Gx+FLV9lxyzuLcNitz3SDf1DadizxOsklNcIK5YlcTBQVL0Ud08yPCnp/GS2NU8PqvFank3aS6xAAuY+ENg6SbKe0JFfD1m1rZWhw6lxiIE9XRNzE6BSr+y9p9veCD7NLhbcm+aSi2HQycfW/dcU8UTSTX/cN1eWuISNQ01RUyJW0NKkKqzOUCxKzYGtHH3mpjPBYMxBDAB0AAPzdmJPTWAsPs5w5rsAw5rOLnvJNmtMASdgA0fEgGUw3zx3yb4nOUuPtk79tm5/C74aJZq3dP3Q13kpN3XmGgdPJrbh7OfLsq1NTcB000XVWBIpWkmpyoQCrUw1AOr1i172jyi7G5uWC78ZDQZg5Ba7l16eLxNdraGGa8BxH8yBzEQ4ta112gENhzgXOvDGEAnyK8ZXJ21PGDetueGTwz8kcIcT+CXgncsN93buXpiprNuXc887eVS0kc8nk1zUdNTVdS1TLKYGxNIxfoRJOhgMUTGMxZdneMrB+IDVxAAOUXAENnQBsm3N4ngX1K9TA4NoLhlNVzjmHLZjHExncXXc3MJjmcMrlrfhC35DwT4hN/cj+GHirxWcp8ZpseHf+7dzx2Kjpp7zU01VVg3o3a5TU89DR1tJV3aN6nyhKxSnEVPCIsrtdTr+BUpVWhgaQMpMC4jK4AOJu1pyyTMlzuuapXwJxLKdI+Ka03jPmIcIcyS1pgGNAwNs2QZM0fEL4kN9cTQcO7svm1K/bXNF5qVSw7XsW7bXWbcoJayAxG0UNj2xU1V5qHkp3dmramB1dsBhAkgQZMPghWLmUC2q6OYgFziRcnma2m1gIgCbWJLtuhi+JilRDsXTeykCC0ODmASYbmqyXOeZkZW5fNAEZlHbhrmDmLxcxV+zuFuUKXwIpbrzHJuzkHlt7Z951V0WnqKaeksNreATRT0TNVQ9U1YRSqxDhJKllXTW4e3whUr5zSIIDWZiXTEku8oa7QkDm8okNJOXE8frVqzvdGNfWESXgNDADOTKXFznN8waQLy9wALVIXw8fZ52TYG4uV7dfuQeMfEXxLsK1UkFXW3O+vd6mqtcME8scVDboZobfQxPU1k5aZWkqI5Z5URwzzSyYa3EQGZ6QLHuNgG3mzQC5wJMAABoyggXEQ1dHA4Oox9OnXcXNeIBcS0GSXPORoALtXZn5zJDrky3r5binhHb2y9/eJXe1zq+a5rov9gLZxdTSUW59/BqiQU9tFDTqxrayOSnWGpSqSRKc9fXJCQ4GY1H1K/u2Hb4j4uHaC3mLjAa3eZgnQGy34msyjRficwo0y4jNfQwAMkuLyR5QBm0NhJXZ6bbv2h3ivkp6XnvxHXf7NXZFwxRW7bXHdFBe9219XNiMx3u7zh4bZUukKCKCjDrl3AnJIQwYbh1FpbUnEO7HLTG5i0v3zGwgaQuDiMXxCsPF4fTbSYd3gOfFyDkuxgEg3zOkgzooK+Ezwq0W86jk3wy8dcicv+J/wabIuVw25VRbj31HYtl7juNTJ7XPFXpZKZa28SUwWJ6oBgk81SI550FMsL9lmMpik3GV6YY4xkzBzyGtNixriGgScrJgSHEBxPLhxGAxFOo/A06rnPsapaGMcS4HldVgvzwS4wXOghpyiSvdLZPggoLDQbCvfLvJ9v8A7JbOoo02vsvZ9ii2ps7b05dmNRFQxvJUVFV1SdCVM83mA++iJIxY8nF8bBqmrRa51U2zPOZxERADQGtEbAG1ictkMBgy1rsLTY1tJxktbJnS73OkuIiTowHmgmCM1y7y3Q8HXTYG99gbYo7XcNx1osc2yhRRW+8bpgDSSNcYJ6mRKeCOmlm656ypBVIZG8xg7RI2fDU313e7PIJiRflZa0kA2OkNEkwGgmQtmJp06TXVXy4g3cJdJsIixccozASBALrNBeOOcT8rbY2Xup95cz7T5PvHiKvUtXNeH29T124bbIWqEjpaWjutDijkoqeARwxrKsDoFqJZY0eWQ63YmhWFMYXDAFmkkBt9XOdn5hJ6TDQ1o0uuHcKtJ1WoQwG4G8CYAAkk7kScz3EhS0r93WWe3GlQ2Sm3TXLJIbbLd6WijMSrjpnlDipaPqPQGwO7/hIHVrlPpPp6XYN4kT2EZZPf6aLdgarq1zIIGhBzjXbbSZ+p0W77bmt1+ulvtdVtqK3Lb2d45mo0E01wbtJ5TAMsSJjo6kdg3SVbsnfI6sXAkEme826nrJm0bzuE9ejkGcG517CLDYkm2oHbUxuFPtKwU9yrBT3jdc08LB54YrnUmOnwmellMhVeoHOAFyfl30lTEZ2CWiBbQD8gJ+MqhlSo0TYZjN76+s26DQbBbtb2t9KkVvtMQanVj1GNupYsjqyzE5JPUPme+qHOJN0tTMeZ5uVl9KlakkH1BI0JhOQhnse+Doyik/rqTsohNg9++pJUSNRXABWx66EogILLj49tSVIScD499QlGENhoyhCEwzjUlQhDI9f66OZEBDYY7/TUz3shCDps6KE2AT8dQORAQz/HTZkQ1BbsfTB0S5ENKGRk/L9NQvTEHUIRyO2cHUDkQEFgc99TNuiAhsOx1JCMIJ7Hsfho5kR3QW9TjRzKQguPj2H9dQuKICC3x9dGeqkIBx8RnRLiUwCCfU+o009FHNQX9fTRDkcqA+fn2+WpmhENQm7j0ydHMECxAJzj5aYFTKgN2zntogpg1Ab1zo5lMqltrzjn9V5BVoByirTZlFWhKivoqKsHRlRW1JKivg6koStdvlTIf/Rhsd3uUU0ZYSwBehCCMhm6gUbByDj4H9WAJuVfQgODswEffxUc77uGTake4rpuTfNys+xbNEzZqamnp/Y5yjdfmzhGdowrqFVjn3izM3ugWMcCIY2T8T8gOvy2AXeo4MPLS0Aud2OloFyBNrnUzC0i3cs3+2WWvnuGw+XuSLiahXpLjabC8tBU00/ZSJpvJjmmEQImbqC5GV8tX6dbhgnmA0BgOuZwBkdpJA6WvvKyVatIXDwYEgN5nGDaMoIEnQbbzqtp2VT+Iiqhp4KCy7V41a9RVFdcrve2jrqygnMnWkNNaqRvZyIklaBWmqvSFSY3HbVrm4UOzVHl0QIbvG5c4WnWzTqufjcQxwb4YLg0xfltFpNyTuYy+sldCTw48f3OpiunIVTvHmC9K/mNPum8T1dOGznEVuQpQwpknCpAMDtk6B4w5oig1rPQCf8AyMuPzXPb4nLLoifLyi8axcm2pJQbr4W/DzXLWzQcL8ZWmrnYPPPbbFTUlRLgKpImgWOQN0ooDBgR0rg9tK3jeKPmqEjoTI+RkK+o8uEPJ/8AJwPa4Oy0K1+EuzbbqJ5+NOUvEBw9SyRPEaG1bzqaykjYyF/OSluQq4lcnGVwFIJOM50zuKhxmrTY4/8Abl+HIWotdkpNog5gNC4Bx+bpJj1XNOVfCFzRyHtU2CyeL7e9j3RSV9PcrPfrrs2w19TYK6LBjrKNqSChkhkADKUDFHSWSKQSRuyHTg+K4amTNKA6xh5uOnMHf21EFJiHVC5rjlLQDAhwEm14dcevyumM+8ftHuMjHDubhrw0+JS3RMzTXDYm7Z9sXmpGAQy2e7xvSF3I/ulrgoPYMB30vueCqE+FXLDsHt//AMmz88iTDYyGA16LgdOU5x63DSB6uJ9V5tfaLcqVO4dkW/xB03h18dHh28V/HNPVV1iutfxpNPa9yWeUqbnte4XSxNXxex1saFknZgKapSCoRkZGOu3wrh1do935atN39NRpII0cGktNtCALtkGVjq8Rwzj7xTqtZk/qD59CC3LOlp1iNFMfwk+LLZXil4G8NPi729vK3xrfunZ9+gpqlZ6vbV1qpsSWq5QRjyfaGkpaciRkUrLKXHVHLri4vAmlVfRg25oNtOhsQBJ9QOq7eA4g2rT8MMkC4ncD8RvaNCATqAIC9EK2zW/YlOKqjqJqnYK079dB1q0dPIzl/ONQxMjJIWKnLEBnU/hJA5VSqDLo5vp8tFoo16lZ4a6zydd/ltGw7RsoT+Kbwm7r5A3xsrxWeEbdO1eC/Grt23intVyqgXtO9rf2eTbe4o4e1RQMclZgDLSysksTAZU9bh/EmNacNiuakemrT/U2dPTQ7rl47BHI6q0EvFrzBbO4ud7biPVfK39mb48uYeH/ALQ3xccH8s8XS8J7I5k5TnoLlYrnXyx0XE+/qqqnloGmk6Op43YT05AEftHTTsGAXOvRY3h2ei1lR0ljZBF8zYvA7iCJ0Mz0XMw3Ew3FmsWkgnSxOnWwExciYmQCvqx2cm6nv21bRfBV3+1bWp3tN7o1Trllrq2dVp6qNQVp0RkhqvMilyscjOFx0515PEFrZe2wMQSbAASQSbzoBGy+iMqMNNzW5Q52Z1hGm0QSZJmdTqZXlf8AZl23bXgW8VXjV8FF22huHdGyblc6PmTYFwttB7VBJtmolakkphLkySiiqQIBGrOFJYhDIz47HFalTEYalWbrcETFyAdwLuAn03i54tCg5mLq0M8WkEk6HVupAAMmwEz8F7L3jdFFuOwUt/uNs3PYt0tX1kG0oI5aimaruCK6qKyKIPGICqMcuroiqznLlAeBSadIBtcxOVpOu1/Q7gBd51E06hpscC22a4uImGzf9Z7Ax4M/aG1/KHgs5Y4W+0qsE143pscU8vG3MNhubUtN9+WCpnd7dJWpSsTLSwVMj0sRdA4jSNSCpdm9HgqgqU3YbYAObbNBHqPMRzG5H0C4/FWmjWGMI5QS12UQA07gkC4JuY3J1K86fGHyzcvDj4IvEBxg/CO79s+FXne2X7dvA9TWmqWs2xQinp4aW010rSdLwGgiiqqSnV2EUM5hMf7II2yvSq1K9Go6M1NzfE0iXOkne82cYFx1uMGH4hTpYetLpa5jmtIn8LbC92tkkt6tME9foH5x4UPLHCPDHi98P279lbc5b4qtthrtnXCOpkS0X/b8NHA9dabpLTszzWeonCsswDCnaBZo48Rv14quLa2vUo12kh5dbe5IaQDo6Cd7g3OkLg2VWU6Qp5Q+LkWbOpaTYaDmtZwkmV57+NjxX7f5Ztf2YPL7W3cNt3PtvxUUVj5D2xV2yJ7psi/ezz07WasELRQTTIrqY5YyiVEbLOCFI0vDOHOOLfSY6Q6m4AzZ0xcEzbrrHrZauMcQDMEMQWZclSmcu4iTpc3JtMzIi10y/wDKRtoV/G/go8EXht9tiuF1vvJ0a3C6Oyj7xrY6GVZamoUY6mae4u7OOxGPQnU4NFbGOFMQzLA7CWgD5BcnjfE3VsDVrPu4uZba+YxtblECJELE+Fa7PtPwE8Z86+M3k2Dc8nB3KJ4dtFJcFagsWwFttwSkS6TKmWevmpo4ylwkDyLE6QxRgOxmuxuMayo11Ec1YZnO1MEGWtA2tcC7jcmAAOjwSm8iphcVyijsIAcWOaGucXawSIEtY0HNGYkqGn2mfi68YPip5x4x4E8E3HXIUHH3LFjKbbocGnvfI9jjlkIqVow6SWjb0q4KrM6STQ0nmTuiAx6fh/Bed1KrAc2HPmCGTeXkyC4TOW7WkgAFyT2j9r6uFwtN+Gu1xLQ8auIiQzRxnQ1IaXScuVtz7LfZb/ZCcB+FPZdt5B5c2FBv7kiZ6CttkG96WWW3bcuMMAp56iChmzTxV086yOkrRdS0/s6xMnv9Q4j7QPpktwhym8uF3QdBMyBF3QbuJmwC4dD2XpupilUcXg6smAXAnmLYExMNMWAJvmJXFuN1359oT4xPGNfKvdt84y+z8NQvFN2h21EtJeOTKawTVHtlPJdAvmUVkFReZYpjD0SSRCGMyIqyZz4au3C4SlXxAz1HnxGtPlEgNa527jy8rTbMSTNgfU4ylVrYp+HwJa1tBopufq7OeZzKYmGmDGYXsckEyO+7ms/GXDO891eFD7PHw58IcZ3G3Vltr9+bu2m9BZbpZdvVkbM9opbyivKl+qOkpHGBK1NSH2lkVjEdXYXiGJxjG18fUJw4JAaSYe4bBo1YNXm39EybZW+z+Ewbmtw9M+8OGpaXim3/APY7NOsRTBPM85rsac2xcS8w3jwk7G3jxPJtvZ3Llle5V26dg2PY96Wpq6+yXVah4rfbaSthgikgo6qkrYZqiWUeWgMrqPMDNix7HVQx7HkO8pkFtwQQ4kE5QQ4AADYNF4C7eCwFJ76nisMeaDDzMwd5c9xGb/lJLnWK574o+Z+D5bTsGk2R4eK28+NTccITj3jegL7b3Laq+SBWa57geDylgtFKRG8tRWiWnnw5VGHQxtw7MWazqAeOXzPdzMY217zzTZobzdbkgV4qrRo0BiQXFp8rWeao68saBsRdx8rBFzYHm/E/GP8A5ru+du+IjxX123ec/FJuuet3Du7flmee4Ns+SKsHtFDb7cYmjo7J0iRfOpl8yYQSvIvSC6rWxlNlI4bBAikImQAXzo5zpudS1tgLWkwnwHCa1R3vfEBNQCGiTkptyizW2giGh7rkkySuh+IDe188bW9dh3Lw9x8lWfwTyK1prtzbFgnbcHIsMUzms+7Hjlikt1jdi9K1ylbqlKyvEkcYSWYUcHkaa+LAe4gEMOUACOU1CesgimLxGbUNVmHx9YsdRpVMpDoNS5uSOWllkOe2IdUuGO5WEua5zZIbB8T/AIPvCrW2jgDeXLPG3HtlsWz7fV7bsLSLT1lJA84po7TT2imQS1FyEqhumOAzMhXqXMgd8jKeIx7n1KAdVqZgDALibSL6NaALiQAYEwLW43C0sBSZTDRSZDjchogXLnOcRIM6ySTJudZJScseKfm2njtnAHAO6eONvvHKkW9OaRLYo7d1Dp8yk2/SObpWyhW6gak0I6sYlXvq8cLp0v8A8uqGi3KyKjj8f9to2u5x6tIsvM1eMUW5hh2eK/aJbTO93Pbm/wDi1kEfiBiOt8U+DbYexN1zcu78vN1548Q1ZDFR3De+6II2lhoUdnW32qgT/ZbVQIzArT06gllV5ZJpB5mpieOnJ4GFb4dPWAeZxiJe6xcfk0CzWgLCxlZ7vFxTszoIAEhjQSCYEkmYGZzi57oGYmBErbzbEu9LHC8ksVRDKlRTSo5VqeVTkMjd+k92U/RmHfOuKysQZWtlCmNWgjpCxlXtyC7IBdi1WFbqjWoWKoCnHqQ8eD8fh8fnpm4hzfKSPif3VoA1yifSP7rV63iba1XBHHCLlaJUYyB7XVy24uxcs3WKVogwYsQw+Pzz307cWQQTeOoB2jeVpGKeCT1+P5z81m4duUNPSJbWtlRNSAg+W1dLJEx7d26m6mPbPvZz8SdDxjM2+X396KvMScxdf6rZYaanpQ6U0SQRluoqgwufmB6D9NVmpOqUknVG1MwTtKsxwPXGkLlZCGxPx0AeqiRpsyiQ3z7Z1MyIEoWoXK9VpcyiExzj5agKiRqSiAkMPXOBqB10wZ1Qz6nProl6IZ1QXxn66IcmypB757nUzoBgQWGD8NEPRyobDPyxqFwRDUHTEqAJDj5YzoZkYQiAcj4ambdQBBYeoxjUlGEM49MZ1J3UDUE9tMSiWobj1x66Ad1RAQHA9fjo5tk2VAYAjRzlEAhBOPz0cymVCYfTto5pRAQWX5YydN4iMIDAYPbRDlIQGAPbvjUzJoQT3+H6aIqdEcqAykfX46OcC6ICE/p3A0c90Q0Ju47ZHroh97oBllLPXnSV4tVqEqKtTMoq02cqK+pm6qK+ewGBqZiorHUzlRV1YBzjH8tNnUhaXurc1s23Z6y/XO+2qwWeNcy1dbULDDA34QWd/cAyV7EjvjHrpM82GpW3CYR1R+QNJOsDpquX7Nt9dvp6ur3rQ0UlDS1krVcq03k091qQemNFjbLNBCixsTJhjN0jpxCc9Btbw6Yc03OnYdbaE6CNpOpV2PcaZFKmYsLAzAjQyNSelsu5zLcKyzVW4LtY7TVPUNaKB3kqx5yziSRVHkqwcZHcM+fewVUYGcjLTeBJ32/VDxhSYXASX9RB7mx+G1l06GlpoBCIoY18tOhO3dV+X8BpfEK5ziSSSdU4/do5glIQpJUjGZHVB65J7aMotaTomNdW+zASAxqkcqrP1HHShHr9fn+h0peFZSp5vlZc+u/JWzNli93LeW9tu2a3UwLTPPOqpTp1Aq7kZx7r9/ng49NMwEkNaCSdLG/ot44fVqNBp0z9Ol9Y6I2zOQdtcgW19y7fnpaqlChYJutHWVeru0bgnKsrIfgcMMgahc5pLXWIUxnDX0SKbrz09LSs/crxPT1DmFXgtiL786YCTN1YCdf+EnAGcge98dQOkyVno4ZpHN5unT4fX4Lxj8cHgPvMHJdL4xfAVVWvifxcUl2t+4d0bJcy0+1ec0op1nipLvDEREld5kCrFXYBLMokzkOvpsDxxtRooY67RIa6JLZEepEHTUahc9vCcRSLqmEPK7USB6+h77XBMWXWPD59orwb4sOKE3PaIL1x5d6e5T7K3/sTdaIlfx5cwD1wVkful4fMQpHKB74jLKq4kUcrGYKrhqpDpMDMCJOYbRE6/T4hej4LQOKa4Dzj0BzaEGbSPkZ16Z3ijxe2zlPiazc02qmuCW2xVQtm445atZKqppRJ5UdV9104lqlZ5uiRYceeEdcqw6gM9XDFtXwhYnQXm9wATANj6SF1aeEyE06pkGYIAiRZxJmALHUCx00K8Sft8/AnuPmHa25vH/4adu7rG9oNvw2nlayU1J5cl5sNOyyU14ip1HmpWUD06GR298RxxuhzTuD6bgONzxhatngy0zod29L7bEkjcR43j/CHUWmrQIcCCDfW8zfUgwRFxGikH9i14oL79oJxjvLcHJ3Kl0oeYLfdKfb28LdROqU9/SW0p93XeQyhwatqm0TSiWPCxvLJGVfOdV8Yw7aDZyyDJB6QZI9IcZm+kRCPCPaGWM0zMEbzqAelo0A7zKw3i88Qx4b5k4H8aFVe6qa28Vblq9ub5SipnNTLx9uSc0UstSyMFkkoLhR09fmMBGEkTqFDHOfh7w5tTCOsXgf+bRmEb3Bi916fjmDNClTx0QGuGhnlgNdJuBe/YCNQvYTjK/0+9dvWbdtPf9w7Sg3VZqS6baSqpIxSUdsKRyQDBJzFN0U9TKMh0kmCq2IlXXHxDwx3huEO1Inf/wD5nKOtzEmVqY4PaKlICo1u9wTM36zBOW3lAmJKccwcKbW8UHE3KPhU5YprZDtXkbbVaBJOrIi1jYL+yCQdTey1SQ1cRz1e9KT2Rxq6hin03Csw+T8jpN9xb0hcviNKkKRLpdeCBf5x1BvqJAiLL5iOZOXKnnr7AeXwsckUi7q8VPF/JO3+HZrBJP8A7XHeqK9rQUJUsoWFqijnMSOSAVSXucHXqTTycVp1qZmnU5t7jKSRPwn4hefbgyeH4hlTz0wWzbUuaG23Gnz11X0Z+FznDYPib4F4isex7BufbIrrdcLRuGhktgVrAbXUewS22silHU08UqNFIoLEtHIcFJe/Ax7arKz6rzcXknc3BEWjcfCdF6ThDDRpeMIytgNGhzbg9CNOkm2gXzufboeH/cvAm2eLfFrwJSbP2rw1uDcW1blyHS7dASjr90UVVU1Npv6RKAkc7oa6jkljALdMStnII9F7PY59Su2nXuWG3oYDgeux+a8rx+hQbQdUws5XSHA7BpbBG+v0I7Jt/wCVZT7kk3l4Ct9bZ3ffpbHd6C83aisERDU9PdFmoXir6eMjqE0scsETKTg+QnYEuWw+z7hnqUxZ4IEztJt2giZ+qycfzNwDHAjIHxpcw0RJiSBJgaXMC6idwHxfs/kPfPir5b8cPLu0N6+HThGksHKu9duWOSuisu5d41FILa1op4fMNHWn2m3mGqr1BaqqoRCkkcZmJ6nvhw1FtbDNLqjjkpkgSQbh43DQJLBuOd0wAtzqdfG4s4LGPyMID60GMuVpJa8HV+hfchh5GtDpj6JPsivDJyHufanJP2gPixqYp/FFyzb46Onoa2l8io2ZtKFAKG0QKOn2ZZlWGplWIL1o0IJB8zq5fHcZTwlAYCkZg5qh/qfO53y97ZvQJsIHYvFsx1RkAANpNFg2n1A0l2smeu67z40vH1Q+GPgq01exLBLyN4jd/TVe1dh7GoZQ1dc7yY3ijqhC3SVpYD5NRPLJ0xxx4DHqK685g+HuxdQ0GEARLiTAa06knQbxeSdNCvX4tlPBj3vEzkYRlgSajpkMaNydLaCXaa+OG3rb4qPCP4VvDX4WNp+H7hqj8U427dNxJel3ybrU7bg9rimuG9LxTxUYjlpBXuvlUvmSxVDSU8SCoZZAPX4pjMZiHCnXiiwMB5SMoMNa1skHO4TeARzGzRJ4XD8Y/CYB1TFUnHEPc4RLYc4y505SeVgjOJnQSC4NHp3w74YuauMvDbS8V7T8QlhvG9NqU1Rcn3ZtrZ1EtgvN8nqJJ6qrmqK5aqouFfUSSOJpYCvW7eWGh7Qrhx2NwzqjXFjvDgNaC6DlAAAaxsQ3pJvOY5rldbhDarGl1drRWqkufOYkuOhcSeWw0iwFmiy8nfGJf93V/jD4H8NXgQ5IHil8dUC3On3lV36hg/s9xesns0pMtTRCGmiMFTRz1bU7xS4Mz+Z5srJFrXg6TcYx+JaPCoNiXm+hMRmBJJBgRv5BqRh4tx6vgSym9rXV3eWmJBIc0SXNDrN0IzGS0GYbGb0K8O/Bm9+DOTt47g3LXXHkTxL1e1mrOTeeN9X9au33CZMPBaKSipoy8VqQK7LS4p1RoEaTqclRixlag+h4VI+FhxGVoBLnH+p0lsn/AMgJIbOq08Po1GP94xTHVsQeWAGtaxtjlZcwJJNgHO1MSoneJTxB7w2/xDtvibkflri/ircO/wC81x+9aWmq4vunju2xzpXS0Kwu00s1wkna30UdND5kz3IHs8PmK2AwbHVms5nloBLQJL3Oy5KcTqbF0uAAa4mAV0ONcRc2k99EASS1ri4AU4JNWqSWxFMAnMc0EsaJJgzW4c8B+7/EzZrbvjnK2XrwscbxWWGzbV4mslyqrLWXCyoEWCffMlBJHLUTvHTQeVbaeZI6OBI4pJJXjIGriXE2UnRVIrViSXEw5jDeQyRD3SSXVDIzHkaAvLcNquDGsweenhWiGxyvqCIn/wD1MiwAAqOkue4l0D0J4F8KPCvhusdyuXhr4a2DxduWaVvvW5fcqdVylicKGluIBq6pWK9QlcuTk9MkbZGuXjuO4jENax74Z/S2wgz+AQN+07yFoo8GwbaznV25i6Lklz9BqXzpsJtuCphbYTc1ViK7XAwVUKsk6RhGClvVkHSOlMjCdRZgM9XcHXHygDKPv/Pb5rTiX0fMwTPr8u8bm0roCuvmGEHLKgLH+Az+46SQsEWlL0ZQBhVoSrQVWimCSw+Q1JUQj9ABoyokkgdzoJmoZb5ZHy1CVckaTMoq0Q5RIJGfTvohyYShk6AdZWgJJOPnoF6KCcjsdDOoramZWMViPoNMHqxBIwTqFyiGxzkaXOjCFoh4RylBb1+GdTME2WyQ3ppg5DKgkEE/PUDk+VCbPr8dGVMqHoZkS2UFs5zjTEqZQkEZ+GhmUyoB/LvolyICE5B9PXUDlIQn9NEOTEQUE6hcUCIQCAPjpsykIT4+nrqByJCCwyARol6bLKA3ocdtTMny9EFsfLUzKESUFvh66IcFIQG0SUYQWxjvol+yIagNjHcgaYFMGqV59O3p8NcEuXhQrA+mO5/npcyJalZGpmSqs/qdEP6owr6Yvugq0cyirUzhRBqGKwSsG6SBkdie/wBQO+pKZuq4pftoHct1p2rbfDNbFeF4pK+JKge09ZaMwo6AgRuqSnrLLmNcKcEh6FQtObQ9tfWdrSOvou4MSwUnUzzSDIFhG8wbzpaNbldLoYKKl6tvx0KR22ipl6CWXpfJI/D6huxYk+pfOTk6DqpcSSuUSSfEnmcfu/3os1BTUsCieKlp4ZvLCkqoHYf4c/L10DVOiqJJME/ZTtW61BOM/HHz0MyQhX0QUECpjgkhf2hVaJQWJP8Ah7HuD8O2dSbJmEyMuqx4slnkkpqmSgp6qaIfsZJx5rRev4S2cep7jv3OnZULQQ20qx9d5BE2PS35JleaaZJqGqpVfoDCKQIgbyxnKtgYbpVu+FPYnPbBOgXbk/VWYdwgtd/n9PuOih9yVzBw3xRv/ZnJG4dz8f7Lp70tSu4b9WV9NJQC3UBSJFdg2UqPPrYoY2HcebJ1h+kKNuHFR7CyCTsBOYk7AakQJMAxFomVtpUs2fDNccwEhtxrcuJMCAOpE7LXr541Zqm4XuxcceG/nfeFJRW2O5terjJbdrW2qppvNMc0IutRHVy07ezzEMtMSQvuqwIze3hhBy1ajGGYAJJM9IYHCb6E+sJGYRxYKtM+JJFmtzRpuSxsibw4jeVx/dHiT8VNRdb7tuz+HLherttLbmuQrpeVqt0pVIZYaZZYrP0STiWORlMOVCxkdRIxrNUw2GN/Ht/2G57S8WAOpiV1sDhXhzPEpOkmIlgtE5iJdExBBJImV4gcobU8c24uf5fGd4N7d4Sqznylt1xt+77Ftvc1wrn5rp4ZGaGknpqqlpaasrqaKFp6aePpcMkaZZ0VG9FhTRNFuHxT3ASMpLC0CdYJJyggxfrYRdYvaLB1cJV97wtMCBDx4jTYcoENAIPcHqCYkLsNu8anhF5O25wtzDxRT7mvPH0UdPY5tu3KoqZ7htC609umC2tLbRhq2a4wyNThmiiKLE000Mo/bgYK2CxfvFRj2c1zYSSJF7nKGgbkgEgA7Lt8H4thvcmONTLEAnS83mxlxM8t3GZykBeiWwfGJwVZd0cXXCs8SFiuG2txWa2bfbZO7rjJYr9Q3Ko6DDLJT10VIvS3VLTsio0YZoT1dBbNHEcDVY5znUyHC4MGIHV0m+hmR+S5OELK9JzW6ZnEuOV0k6BrRLo2gifQyF8Wn2iHDnI/gR8Su/uUPCPv3efH3At+u7TW+6bJuNwgoLHO0s00VpeuVY0nC+TNLD3KlFfpHSgLd/B4pmOoBuKGZ0aGLzHMGzO4k9YJ1hea9qOGYjhGLGJwbi1pvI/CehMQL3Am3lvBXudwHwLWeJ37MSPf3PUHI+6+Vtw7aPt1T91VIramiXptnsyMv+z1Sin9lnSeQYjn8qUe4jA8fE1BRxAbQaCAZBMG55pFyQLQdyJ3Ij2vDKtXFYFjaroJaQ4eXYi4gAkySBppbUqYP2UXKe2uVPA34RpLpVvunkDb1BfOLr5b6yJZrlQ1dppaloDRR46o43jgpnKSDsWGG6yQ04zTyV6j6dpAfbqSAfrOn5LB7PYl78M2gQAGnJe0xYz1t1vGoheuO3bpUXDZVJW3jbouFDJF94biq4Fkie3IaOKrEsJYl/2RlkVVhxJkEN0EsDzajMjy1lhp3deNtZ3vHqupLXkEul1so23EbaxvIvN4XyPfaZ8c8qeBTx18Och7tvFNN4eOct+bH5D3Tcau2vPM9/sV2innllooY1aln8qsV2pYA4dJHCgMOlfccKqNcA1vmpZmgD/k0tFybyZvYTGwXguOYpjKrn0z/JqQDOnK4ERvAaAJdJPMTdeunB3iMn4x+1l5T49mhXj3Z3Nu5KmqjsU7Cnj2lvSGgpJoapRE5RJ7pboZgWmCmaqopT0KrOG89mdiMFLrmkPNryyQWzoMrosJhsE7Aeix2CoYAsaCXNe0Ty+ZwEg3BJaQTpaRAlwlbb9pLt+38k/ZF/aD2Cx0ENNtPbFNcEtEbSN7LXU9vvkVaLhSB1VxJ/tVQM90cplWKkEph6j6WLoveYecvrcZQCO8fW90/FchZUZlklriTazizMb9BA7yIsvnt8UPMW1ftTOSPsS+DqjlLbl23fX7Rt+3+Qns8jo22LjUVVPDUpLJJ1eXUmmtzTFRnod+sf3gGvUYOkKWIxNV3k82kAw1ziNNJMWt8ivD4yvn4dhcM3WbCQTHK0E3JnWA6CY6QTIPxA8bcUeKL7WPgD7PzgStoePeJdpbXsm3tx7WasnpbVeZ7LWT18FsMMUZy9NHX1MhL9QkZ5yXLyZGHgmMruZUx+JBzZiQYnYNJiQALQAIgCAIXo+NYWhQq0eGYc/y8hLw2BInPBJBJLjzOnzSM1wF9Gfi+8S/CXhZj31a/EzyZVbcsNu2vNc4vLdI6S4qi+TbqWltiSZnmlM7wdEnmmX2Riwjiw2vKVH+Ly0my6bbuk63IgQOb/jIkmV6nhNLw6bccSKbJh2waJBcS7XUQA2NYaMwK+bbi+qi5m5K3L4jrpQUu/PE7yXbKvbvG/GsxkZNkbJolNG9duFaaR1t8EpiWoqkUCR+0EMUk0+I/SPoeHRNCkYjnq1BcA6tA/rIAho3dqWtaSsTMU6pihxCo0kSWUKZOVzh+N8HyZy67tGs1zEtafcrw6eFHii1WLjne/PXIlx8Q/JHKO2P7S3Xd92igtlJHQU9HRyRUfkHIjoKOJpBHSVMjU8UaSySIZWZytfiYwtR1HDtytonNzHMS4m7ibCToXAT5WtMLPh8PUxOHfXqukvmmQ1paC0l0Ma3zxP4RzPc5znX04rvzfHiC+1/3Zf+JfBnv68cCfZvWKplp9y8o22mSgvXKtXB0F7PtwMFMdDHlUaqwIy6kkuFSJqKOBp4el71xYZqjrspk3O2aodgbxN+gmS3FiOJupVBg+EkBzTFSq27ac6tpjRzzo534fKIEl3pt4bOA+AfALx7HsPw7cawbUoEtK3C7Whuh7vuKsNSitNcq+QM9VVIruVMgK9iEwrdIw8Q41iMdUyvMBsAASGt10He0kyT1WzhfsxQY0hty4kmobuMDUm1j0BETosD4uuYtmbO2nvmXeHKVt4qs9so7fPumuraiBKSw0gZnpRWRurdS1FRVIDAcOyRzdJLFQMOGqAvFs0G0TJIAs2NSACekwN5Xp8DhYZ4gAEgwT0NiSTECBEmJm2hUWvCP4Zrt47fEdx/9op4i+Oa7Z/Em0rKlr8Pey62l9jqoaBmJO6rpAWMkVZVMvmU8OeqGNYpGPWVJ9NXqu4bSqUHf/k1P9y8hg2pjbNFnn1HWPnHEMTR4jWZVoGaFInK4i9V277i1MQPDaRfzRovYmsvm2RcU2jQ3Wqrd2LE1RRUnt37cw9ClnUt3SPMiq0uQAT6lvd15NkvEaDc9Ok/oNTFgvVtpVGA1nCGntv6b6aQfgDKzw2XcIaoy0G41tJUo1PaXj8yiRh6sMgOc4D4B6QwHYZINrKrQeb7+/vRZffbXZmF5O+/31jdbPuHctktKQy36rpLKqKZZ3qqgRNHECFysgI6gWZV7epIGMkA0ufcN/usuDwz3Tkv0j9Z7f5TKn3Ba5Wd7ZUK1xlqEYRlSjSRAhet1PoG97BIB9B2Jxp4IMH/AArnYdxjMLR9dbenyW8U6yJBEsxBlC+92x30JiwXPcQTbRLWRH6yjq4UlWwc4I9R+egHWsmgjVXPcE9iNTMU4KET66bOiraBcokMB8idQuTtdshnHw0CVYFbSzZFJJ9MaAcNVEInPfRBTNF1bRVyQ3c4z31FEIjQzBRW9NLmVgNkhj3IzkaherEPUJuohtjB7HJ0perGoepnTwEJvXTZ1AkHRD+qKG2O50S5HL0QzjHxI1A7ZNklBbvk4xqZ4TBsaoTY9T2OjKOVCPx1A+QpllBf8R9NQORDUJsdhjUzEaqQgkdifj8NN4nRGEFgPiNQv2UhCK/L10c6YNQWGfXTBymVAYeoPbQzqBqCRjGmLlCE3bsSB20cymVBYDPY99TPKbKgt+eBo59kQEBh2OmzIlqAwH+moHiUSFKssceoA1wy5eFyq2e2NGUYulAj46EpS1V1/HudFTIlBh8hnUJQyK/UD8RooZSr5HrntoSlhClkdU6oo/OfP4eoKSPzOinDL3ssfBRzvVNVVU0jICTFCzBhGSMEk/PGQPkCfXOjMKx7xlytHxWs7jtsscyXS1SVEtfAwaSnapIjqIvjEUbK4OAy4H4lAyOo6mYeivoVTEO09Pr6/oSn1huhvFleoild5iz+U8g6fMB7qcf4eoMPdOCO+QNJsjiqYZV7W0WSsteJ7fTPNJG05jDzdJyFcjJAPxx3/IY0Q+yrxVEteQBbb0WaVg6q49CM6IKykLH3CshpaeeaYF6RARUYBJRCO7YHcjGew+H5aOdW0aZc4AanT1XN9tbvpqV7hTU73G97WikeKlrIYjL7OyBR7KcEvI+GUqQvpkEk4yjX8oI3+/l6/JdbG4AyA6Gvi4n6nYKPfJHLsu9dxXviDju33jce7BaKe4XWjq6OVLOKCeaWFaipmAD+UfLlxFG3mVJWMKBGJJR0MNROQ1nWaDraZgGADq4giAfLOZ2wXRw2GZhi19UiZIbB5rRN9BHU+W4HMQFgLNtDgfYm9dybor9u0G69908FvDX++UFK9ZaIZ3ZPYLcjoqW+nYx+bHDS+4xyzeYwyb8VxqsaeRpLWONwHamNXGSXGDHbQAaLnD2efWcyq9rZBcWgAwI3EXN9S7mJvKitdq3c1dzXu2npNtVEFBZrTaEpaIW2atmnkkmuMwanqaqRaajk8k07PSP15DFsRK5dctDD0zTBBy3N5a0WDSZNzqdQB0kkQvcTlZLSCXZjcnSzRZovcGDPpOqiFDtTeG5vEPuXb2x7/wAzHdlu+7qGlrbrSUstVstJemeCtgsy00MdTA8grWWoSJ4E6/2lQsasJd7qEtzOblBnc36jMXWtEjMD0aTAVT8QynT5qgJEyAIAmReLkzAFnGJ2zESg3l4bPFLS8KcWcIbtudg3LaEq5bJQRW2appaG30ywForxf6akQy1NQOjzWWCtVBMsUaA9Zdb8+GdULmkkRJJEwP6WSYPQFzJMyYAg+WpY4PNSqGc2xBylx2Mm7BrIbEC8kmB5C+LjwC86fZzXWyfaA+Ad+VrndbXao4OYaeW7PdI99Wz3PPmwnlyxMoCtJSoiLGoDo6+VID1cJiaeMb7rVADTOUCRe+skzqYN/wAl57E4M4WqMXRvVF3NIGlvKIiRAvLSRsZJXr7xdv7gfxc+Hzgzdtvp7furjPc1kpDSQbztS3CrnQExyxRyVPmxVTrIkmUhkPs8kbB4yWjUefxNTEYWqblhJ0YYH0Mi3WCRMRdezwGIw+Ma6GirF5IbEmPwwAOhgEHTNAKijyR9lb4VPFHs/lDbmzOFOFOIK2qo7nbKS7wsaMzVFN0w0N2pKKkWNKRzM4PmuVDxDyjBKjhl2UPaCqCH16hcbSInU6Ek9LxczuIhDifCMOWOomm7K6NJsYJMC4OWIECDzGRMnxh+zP8AG14z/DFzPR/Zv7z4ftXJO5Nnpf7JYLEl7O3tx0FShFU8Fpr58U9SCtOamnhmVPPjwiSYaNT3uL8IpVCcUKmUODZJEtI2JAuOh6HUC68NwfjVXCk8LxDczQdrk6iInKRBJFwR1Oh7z4T+bNrcD/agc27Q2KNkbas3JFuqd67foYbdJZ32tfIKB1qbXdrVWBam1SzlGlUMCYnKVMcjwO7PRjW1BgCMUbtsSTYgmxDgC1wGhynTlsdO2x9F/E/5QOWocwAM3Ah2ZoIJJBmHASZkQvae2+IWg2JPxTWWt913vi64WKwXTcF0t9lmG3LHt6KU1dZMszA5WF66NmdXkaRZZAO7e7xjScKlRzm5Q02JIzTGVsCxgkcoiB1tf0uJa19MOY7+Y/NDRBcTY3MxJbMk5doEgBRc/wDKWNu7e5E+zq21zDTtSz7q2Rva0X201DnraeKrSWmnOGwTG3XTSDGQ4iBXspOr/ZLHupY0MNpGnpBH5b9bryPtHwgHA1pAhon0hwbAjWzjpoV2XlTwu1viU8LHPm+uMbBsSx8u0lj2FzNs6RaUVr3XdlDbTd2NcOny5DULUNSEL1AR1DxsGQINdKljW4WvSaTLWue06RlJDbGBcRJPUTqq6mMfiaAaWkFwABuCDJyRcnKLAT3I7xj+078Qr8rfZB8peJLh5rhT8a8obc2hK9rmqJCbNQ3aamp6lJVVWLNBUWqogUOwRfNcZJ6BrGcIWY5lF+rXOnvALh01m5gm3qVtpcQZ/DKtVglxa6LRBMMPpDXCQIkidJXyt7i5F4+8Nm5/s7+RuLdl1Ut52/x5T7v3HX1VPPQNui91dZXvOySnDyQU69FEkqARt7LIE6gSx9NWZUquq0m2BAa3f8IuR1cST1iOy8TSqYXCMwleMzgXPdto6A0Hs1vwJPdellqsu6vs09ueEPxgb7rLJvjxepuOm5n3NaPu+R7s1gu8NXQXWmuNQrukRp0mtzr56QdD1RKPIOtY8VSu2pUqYKh5GAsJEQHQDM63II1MxMXk959EnCt4li2y+o4Pm4zNMAgDQhrSCNACS3ss340PGdtDxkeKzgjffPG16/l/wzcdWVt/7q2bS2+a21lVLXyJBQUKzGQNWVFWDbpgURIxFMIlidE6ZOfwug7DFzqLZrOhjZgjNc7TAadZvmBkCwG/2idQxjaWGzZcOwGo8gOs0Q0WMZgbwGnmFw85i5fR79mLxVf+MrHv3mXlDaO2tveIfe9FbbpU7fhtptS7ZtMqu9FYaag6Io0pLfG6wow8paiaWpncFpQVwcfxnhtGGLi5rTzONy4wMzi6SBOgb+FrQABzLdgMDTxIGJFMMDiYAjkaHGGAxmzE89RwkveZkgNXkDzkdw/ayeJG78HcP8u2TZX2dPE97qqy+bmu0c9uh3lU1M9Klx29RJE9OaqmgPWrqJlULJ19QzT9W7gmFp4WmziOOaS50BjTcmCSHGbDTWNoiS6M/tBjMTXru4Rw05XCTVewuhpDSCyQNTJzf90SQ2Hew9x5V2De7xw3sPwObeua0G25aGz7kjsFRHa7JBsqGeNqmOmrOhkjWJ4gkUsjxKJGmWNqiSQAZKPjV6z8RjxANzmBEughkgdSbNAJjRobJXZPD/4dhRhaBaQLMaOe5HMR+EkASSDc+Yg8pl/U2zctLyHuDmzcu4bLQLSWySmqKg1y00O3reKOatlSu8yMM/T+yZpnaFkC4VUUssnGNZlGm6nMiTPeIFo7k2vJ3NsuugXOZTpZRJiALiS4AR1mLWgC/Ur5zuI+auBPtGvE9vbxLeK7lnjG1+ESh3dVvtDjG2zT11133crYvRTXa60NLG9WLcnutDTSDDyZLKyrlvZYDh+IwFBlalTc/EkEg5Dlpgm5mMucydzlHqvOcQxruIF+ApuazC04a4l7QapB0kkSwamBzGNtPfW5eN+uuO4dsSeHbgLxT830dRDU0tyq6TjWstNNRKTEY6ySe8PRCVIsyL0ISGLrll6TrzA4LiC53iltMATLqjAddgC4knb9Vecdw6mxtPEPN3NADWvd1tIZlaNJMkjpoU22F4prJs6hqb/yB4d/FfsyiuEqx3K+XDaUN5mmrMlQ1T91VFXNCEJiWNDGEUOvSOk5JOEqOAbRc0ibNa8T/wDbLJO5v0toN3EX0/EAdIIn8Dw0N6CxGU3NzfWZupRbb8W2wb9dLpQxbS8RVbX05c+V/wBku5oCkK9PVK3nUKL3ZsdIJb3cBTov4RiWMzvaI/7mfLz6rzVXF4YlrKbxJE3m/wD9enWJQrBvTZ/iG2JtzxBUG4Y6biujqqu52eshtnlVdHFTNLDJNXmuj66RiY3LQGKN4QF8xiQQtGLp+6mKoIfF7wBIkC2vrMEmw3PT4fiJccPRhxdAvNzP4QImNLzJBiNFhNw8n3zjCh23f6O40+8RdKhXkjuNBJRivEhTpNLWxxJCqoCD1OpVlaR8knJqe0tZkaDPr6ySNf1FhC6tPh4xVQtJDWtta5HaJPyEbXAELql05Iv96t9us1i2vvW336veH9tDRJPDDCV6pMVSyeXGcBgshyw9RGT7ukpg5huAeoH9/hFxuNVlZw+lTcXVXNgA9ddrRf8ALv17Daqq3rSRwU09PhD0N0oY8ue591u+fX17nSuqSZK5tWm6czgfzt8Flj2J76UP6pEnTZlFWlDyorE+upmRAQSdDOr4SG9M6WVEIkk/HUlRW0wKtaIVaYuToTHOf56TNZRI0M2yiG/r89DNKsaCh6ElWKs40CSohMQfz1C8KxgQ2OB8NDNNlYgnTZlEn66OZWtCE3r651C5NlCQfr6amayIQiTk6mdQoLn4ZGjmTBsoROB641M0KZUJj3+P7tEO6KBpQn/MaGZMGoR+h02dQNQW+Pz0cyYNQHOiXQmhDY4x89TMoAgH0OdNmUhAPqdDOiQgPjJ9Roh40RDUB+3YYxolwF0csoTA4PpqB/RANTdvj8tMHolqC3x740Q/ujkUpiwxntrjucV4NXBB+OgVFWQPU40FFWRqKK+e/r30cx0UV8nGPho5t0IEyraJeirEgep1A9AlM6ytiolE0rERorSOACSEA7tgeuMjSvf1VtKkXmBvb4rVqivF1nakno7ZU0EtPBKpnJB6ZHKjp90huxHoQc9j89KKl4JWynRLAHtJkE6dQJ+9VrFVXS7Le6VS2O83SzrI9ZcYaalLozsD1VEABIxhQXh9e5Zct2e1gkwNvRCozxAH5gCbCSZA2Hz0PToFslqqLfRbbtz0U9HWrPSRyQVNNUmpSpgYK3mRyerphwQw7EFTnvoPeBOVLBqVS4kwDva/7rbLm0aUFWZJzSxhGJkDEGIAfiBHpj1z8Maj4IhZKXmBifvuuNLuHd9bV19jo0cXCnXoSqkgWSKWAoh89pRIgYBiyhQASQc9I6jqumSQSTb7++y9C7B4ZjWvdo7aTr0iDHc/KTChfy9uLlLw/i63Qco7c4/sd1qqiuulzqbK1XHaZehjFJSxTzNTxzSuqRLAC0R6mmIynQ+zDUqLhDQXEahsS7tMT3LstgI1MroPazFlpa2WAES5xAbprEEgaXLTJgQJjNeHLe3GWyds3TZlNUCTdF0utRSRtRVMl2uF4qjlSa6PPmpII4JVSRnEPk07eSyIoiW/EVn4gtEwIt+FoE31tc3OpJN5Ky8ZpVRVOKLZy3JjSBIAOh1s0CxNxcldjks1duGRtp7i2FdayqJklSVnMEr07MwETyMeh2iRR0shZhkEdwSec6qRyuIgd/n1/T8ldRr0wPe6T4BEGRp3iNz1/VcVh2/drTyHuXaqXGw7msVwpZbrSJW1uKuKYdMa00/7MrGEg6ZI526iFZl6UMaFrGFjWTTMOB0vpqSDPWAQLknW9u7708ta57CNBI0t0GrpJ7abyVt1k403DFebc10iqxR1sdVeapS3RWRVY8oKtPXiQvTxxSTSiNAERSB6AkNaa75Ja6WiwFo6SRFyRvc/Jcmq+hUpkG77Cbi1zAHeJIm9zdMLhy3vzjarppeS7bd5NlvU1Brb2kaQfdypGDHT1x7RLEzRgLPSlYyzJ5kcXX5pR7JBLNW7bb3Gsx3i3VRuGpPGoEi36mNet3SfyUoW3HtG5WGxUNWlnMFdRwvFDTTlzLC8ZBAp4SXKYZkPSCG6iAT30tOq596fN3F/r+645wlVr3OJO9nCPq606G9xvsvj+l2pxH4DPHjH4aV5U3Dx34IeQ9xDdXFl2qoqmGk4i3yJUV6SrgqvLWa2lWnhbzWCPE3vspjlkPsapOLp+9uZ/MaIfYczeo1AO4AmOhBAWXCnEcMIw5INJ5lsHNDtQ0kf1639QQZI9uuO+YuIt97deycMX3j+77021uGvTeKLevbqB6CJWqbjC1RDkS00/mxyRSOPLiT3yRJTNFrz2J8TDnPVBY0gEcsG1hGYyP8AkR6CZC9TQL65OZ4c7QtDrtc4wJABvFgLEkgaErx2+3P4PTedu4++0/8ADpVb223zps+42L7zrIqdkq7jYfZ2qrZfgEwYxTyQSxeZIqebD05yFTPo/Z3GOZmweIGs2JmDYFp7mdBMHoZXhuPcFOVtfCASwEktmPMQY6xrItBN9FAr7S3xbeHX7RfwieFHxK0m17bsPxGbZvX9nuXmtDLBVWqmmaNWejif/eaSZ6kVEAXPlDzYm/C51fw2jUw2KfhTemQS2dCdpO0RB06hZcU9uJ4b74XEOY9gkHmaMsHeTNsskz11Akt4PfENvStk48u/jJ5W5ouPhbs227lxXbuT9t08tPtDc1HSzQJS012Cwedb4V9ro42rJkeCQiHzJIT1A5sTwgAur0qeZ7znyuPMDLgSACJFiQAZEGxhej4H7QGlRp4Qua3w7BwDXMuBrMw/KI0AdoDe+2eKbem9eQfBb4z+BuQNn7l3bd9u7Olvm2t4XTf810ium3Irt5i1NHUIjQXFaf2KjomK9AVkHW3Ueps2FrAVaVeiWtY5wEBomTPXmGaSQZ2sIXRx2CbVo1sO7MXNa8gEwCACQYENzNBzEEEklepf2Q/i0s0vgs8NlBaotjm/T2i3UcdDPUJSCGupLbTU09VMIUbpXqpV65ZOkAyAvgyAsPaJr3Yx0G1zoTAJmBYCTNhOphcT2ewdPE8OD8QSMrQC6RzCXQBeYA6CwHQLxc8dF15G2/4V/tbPDHZqimuHh/445I25ebVPbqillht63+8RXmK3CSJX64oJa27e6rJ5ZaEd8so30Sa1TDYt1i6Wb6sY5pOg1GUT6xol4mwUqGLwgEHJnuCDlcadgCeoJ0kiDuvLzwt2DbvjB+0I8EfGFx3ZE+wdvbN2va45rftQ3JoUs1mNdNRi2O2KuU1q1MTFi0crMXKMhMR9DReaIrYgZiSXEQQDchrYJEAARBIkATrdeGxDjjX4bC0w3lY0XJDSbudmIIOpMxoLBfUz49NhcR7N8MXKm8rvxBvG42yC170s26Nzbg6Km67sulTY66F7ldrgcSVEazU9NTrF1JDHNTQ+XF0wwQjxLOK4nlptho5cjR5QM4IIBvLrnMZcQZJkkj61Q4FhXOe+o/OfMSLQA0zTAFgwAzlAAAMWEk/KD9mLszlO58jSb/puLLVyptS3VENbQwX2719vprjuek8gUTddBTz11caQ1McopYF6UkmpZJGREzr1vEsjKPmyEggGAYBs4wS1okcuZxAEuiSvmPsg3EVqxzNL6fKXXyyWiWMzEOJFs2RrXE5RaIXspxhvz7Rb7UblTlDhba3JS+D7w37bqpNp8mbh25eXulDUjyxF93UFdPNI1XXygVbdEDwUyRN5j9+78NnDeH4bDtxeM55uwAZcx2ho/CBEudm6AXhetxvtJxOvjnYPAU/CqgcxdzFjRqc0WdJ0ADyYzHMLT+vvgq4T8JHhp2Pt7gKu8QfMc22jT2+yX247jqJbJY6y5tLC9XR0JEtreVpKh3ZYqR3jCTqWHmAil/F61ev4mRtNrrTcPyjmjNIfFp2BJGq6/B/ZunQpeCXh7oc7LIIcdMzmwQIt5ibXHlXqDx+lZbod0XrePiR5NhorbXw0i0NdV2eoEMkKGZlqlNBE9Rk1UJVWRcFwgz5agcDE4+mxpqZLmSDL9LiRLj35iTMEzqV2m8MqBrcNQa2MsGGBuoERlIDbDQbHoV4veLbfG5PtFOc67wu8Ocz78vPgs27uWy3HxA77Fwihsk0EvskI27SvBTw+0z9Pmswz0xkBW7gdfovZ7B4eixvE8W0BgzeGDmJe65kAu0sBMbiNQvO+02MxNuEcPH/UuEVC2BkZJ5SbkOfcmHaA5oGYD3Q4/wCMePOINj1G2+JLNuvbdrtUYs+3NuWu9Tx2mhpj0JTNMlcTFHWeX0oVEjdXuKeti+ORjeJVcWQaxDnTcm3qGi4IjoAOkABa+F8Lp4RzWU2hjALw0F5A3zNAcRO776km6kyvGFPVXLbN93bbnul+UGngmnrWdqJC5JXyoylLKoCRnpCYHSD72MjI6p4ctYRBvMXkXsTJH0Cp/iAcHBhIDbxoCdL/AIrzuTfon+3KSwX0We7pSypJT07xMk7xxxzzzYY/s2bpPQDjPSfeJ75XSuaWG4ubTPz+e3aUa9SpldTmxMxBmBIva0669Oqbbtpdzbks287Rt7dtq2qLfVsXuSUsk8tEYitQWeOVjEyhGXqkZXAALBSVxqphaweJUHLra3Uai49BB7hIKjaZZUiXOGhIgzaLXmxgTqbyF5qLHxrzVW1Fj2hxnaGpL7BFT3qa7XCtro90p7RB51TVUMRb7yZ4o6QC7Vvks0MrBepUaHXXc+sXtLrZYIAAlovEO0YJk5Zc5xF7mR2MDhhhmB+aQAQTmgGWk2EXIGjWjKA4XAhT4puMwd6W611e7d0UFDSUcyUlusNQ1poKiHrjSNHpwXWocLE465MAguCoXpBynGNLCC0OcbydZMkkREaiZm+8yuIHvZFRgAbAEEZogbk6XNg0D1MLLceUW5uPtvSbQrLvFuhkq6qe1rMkVFVx0zVUrY6FHs5eAt0YQIpiEfu5JLZ31hUggxoOu3zvv3steMptq1fEIsdY00EDrGwvMyV1+y3utuEgkrIIKhkVCjCk8ueok79gjHqjPp+JRgA/pXLhYn77rmVaLAOWR1vYfGL/AAW6U9T1pBHUtTx1rIHeJH6un54PxAORn6aOcbGVicw6gWTvP79NugGykFwPTB0C4BMGIeT8z+/Qzp4SSR8xpc6KEWyPrqSmDZSdNmThgSGfB7YOoXXTpBYnHwOlL7Qok6XMmAlIY4HqRqAqwNhC/PQlMklh8xoyjCGzEnQThnVJPx0MysCGSfmf9dSVEFnPfuDpgU4akFjnRzFWAJBPz0uZFIYnB+GgHBOAhHvpsyYNQm1J2RyoZ/LOmDkYQSRn4aGa6MITj0xohykITenwOoHKBBPqfjqAwiAgse5Az8tEvRA2QXJHbUL1IjVAbONTOSmyILZB7A/lqZ+iaEBvU6OdEBAb19QdQO6JoQ29Ce/7tHOdVAEA5wcDRzI5U3P56YOuplUoCQNckvXgmthX0ofdQsCvk6Jch4at1fI9tHOp4av1HPr3xoh6GRY64XBbcaeomMaUrOsLuzhfLLEBT39Rk4/dpXOi6tpUS+WjXX5K9TcYYY6OWZikbzLGpx8SelR+pI0HVLAqUqBJcBqAmlfeIoGCI8TuJTFnPuo/lkgOR+Ek4Hz76Dqqto4RzhJG0/CVpG9KuC509DFT1O5KG4B+g+wMEmiDAhx7w+AXv8Pj8QdV1KgJuNO/+F0uG4dzM05S3uJFtOq5zaJrrcLs9HLUWCe/2xaeoRZw0E1db38yINE4HT1Ll1YqnT5igdgwwKQBEkwD+fTr0j5rbi6gYAGtJDpnoDYzHfWCZyrrNi3NRlaq2XZ5qS9RzSQtSTqOtiPeTHSSJGdSp90+uRgYOrDXDbE3P3C4tbBvdFRg5ev0nsB3XC44ZNm7s2VteBpoeO9110tbb1owqy0FfFDJVyUM3USVppwhZfLIVJI5kICzINaGHOwuJkjb4xPeJ37G910n1wHPJbzttJ0vaRpeJ2vaLhSSu8939nVaNV9r61dJUHUD8wV/M47Z7aofUMWXJw1OnPPpeyjF51iivN8pL3uGuguFbWw0poYIZKOgiIWVkp28klnD4aTuwJV+691RjQrtYc4aZG9j8Y0t3m/e49e/DVH0gGtBbGurjoCZMAdLAaWO4c7c2rxbbLL99Q2uy026b5TQ1Mtc1NFULWzqhJhVcOAIwjr5IOAkS5yyk6ur8Rh5p03GBPx9f1kam0LAG4qoGioORtst7C0GT1tB1kzoVFbeW2th8Ic2cYVFPs28763pSXS4VFVtva/VdrvU0NbbZKVSlKxQ+y0U8cbr55jWNatyhHknq6eCqPfSfTAEG0mzQQQTc2BI2mTHdZ+JYqrUpDEtqFrSAbgCYd/xlzpJAOUFoIE3K1Plbd3iE52tlTPtPifi7jm6/cdTdbVbLzVVVwrqejeRqf2q6PBLTW+keVoJRHTxtXTHy5gMdDHVtPCUKUvdVvYGGiNjALg5z+8MaB/VBE24Oq+lUaxzXGnOpMOzRoGtJLQA4S91RouDE2HKrn4SvHqtDS7ru32gqXHcMlLUywWu1caWgUcLMDGlCtTM0s01LMG6GMillKRN5YA8o5q9Th2bK2m/1NQ+ugbaNYB+JNxdgsbjnEk+GGg6ZCbDckuFwPxQBMxA12jw28K+Ofh+7b62RavGRR7+3ozw3SGy8l7JirnekkjYSVEVXS1VPNT0bVMdQypTtOqdS9f7Qui6HPwXhimKTmNJsQ4H4czbmIm7d4783iNWrUb49Z7XkSNC29rQwkdgXBxgBdqq/ED4huL6uaxeKjwo7i3Xsi4UE8O5tz8NxzbrsVGqGNOq42poYbpCXiaUEQx1OUHfqA6tDD8M8W+EqB8RZ3I7ewk5Xf8Al8lkxWNo02Mc8ZHfhzcw0kw6JidJYBrda9wr4g/C5xulJs7wjb8405e4rWSWah4/sF6obfubbkpyq0Fto6+WmlnphI0rikqDHNEzCOJpExFG3EHPLoxjTSeTq4FrSdzpAMbgZTqSIvVhaOJq0PFBzta2JBzkAQb5cwEgGTIOsgmE98W/FvDX2lvhvu/F62G/764nvdtlunt9utUaXO33dOuKI00kxSFJqaojqFqlZgFkjWFi4eZNJw7EVMNV8VroIiJMAjrOsEeUgGfMNBN5wLHUizFtABka6HYRBOboCQQJDgJEfPHw/wAk8kb85IrvsnvHrY7q/ik21HS0O2N+2OqjFfWWmniSSOpjuFM6VM6tbjMTDExepEahl8wS47GPw+T/AK6iQ7Dul2U3Gb0NvNEEwGkm8Qr+CY6mP+irAsrjyuEtLmySDtl7m/LMCV6Dbq4J8SHOMlLtLws7/t281t1ra01M+/qisnjpZlCJX0hqkjiklhIK08lBcEugD5A8ry2bXNpuw9SXVx4YN5F5N9nGQSd6ZYNzO/puIVX4Sl4oeKgJPKYgDQXaHSAATLhcQJk2+KDxCcPc5eD3kTmXw7bpr4dtXa5WelgulNa6sVNuu9ufyrjSCOYoqzxpIkBEigASQt0nGc+/D6WIy1GmQ0mDcXEtNtRqddrwvh/EsNisDUfRIjONLGWm4i3b1GnUL61vs+rDyluTwV23kzgep4+2Vx3UXWWzbBsu46Casp6GOc2633ieslkdneirLibqxo8BXMKABgwOvM8ZFN2LbTqEte6JywMsF/hxH48t57yYgz9N9mqlMYItpNzsbcl087srS/4AgibQNDpGO8U3gP5S8C20L7fvD/Z9ybi4Spdi3y1b14nudZ/aKLbj11skparcO0pmEXUE8+aaS2FYQU9pkjVCxRcn8WpYouY8inVJEOEgOgghr5mCYgOk7STvMFhn4djcThyalAzLYjLIN2tGw1c2wMiBaUx/8mx3nJ/5tqbQp9p128HhvF5r2kSCGf2WqppKONlhMk0ZZnpbxSn3AzHpz0nB1r9p8LUc/wAUOygDSdZJkCASPL6d9lw/ZLH024EUi0klxaSNAIDgXHpJJ+aid9vRy1eOGORefNq7U25cV4j8S20tpXAmtqEpqqhu21riIPbPZlBkME1MyU3lz+W5kQuVHlgGcDLnsYyqRnouLo1tUaRBOmYG9pgbyUfaGqzBte9vN4zHMkaBwc11juIN43gAxdedn2LmxN02z7VDwn2ba+9n2deq+wVt6hu8tvSRqKKq27UzuY4XLrIwSR1RmKgkBj0DIHpeIOacLXzgwBBA3Ac35TbrA6ryPB6XhYumXDNmExpqDAPabGLnQL6M/wDyhLxVW6zcKcdfZv2a02jfHPvKFysk8NbT1bxR2W2pckjglmiDMySVU6rGkeSnlCof3sL1eK9lsF7xixWLgGMNyY1INvgDJNosLTb3XGeI+BhajmyHVQWNb8sxJ1IHl0MuME8pCgduvwv0O9Nubd+xa+zVls++d+2Gd7r4iecfPNJbaWtcqlVbIp1VmkfzIkQU4aRf9mjiRQwqJF7xxTMY7+JYg5MKz/babl8aOy6E3me8zlDZ5VBtfhOFOBpicZWAzkD/AGmk3JdMgloAjlcGiXcx5fYHh37IHbHh4sXh7tce667bFrirGud4sGzYpJaakvUNM3k1iS1BeSrgIPVUwzoYpW6VSONSVbhY3jTKtUvILzFiQABMaAXEXDbk7k7D1HAajqVGph8O3w2tiTmcS4SfMbAF28QALX1U690WKK/8Y27i/cfOe3LhPS3G32qsFPa46SGulku1IqrDF5rS00qKhhCL1HpqCQv4SOFTxlE4kOgm9gTcwCTMATMfIar0FLC4iizx6VLJIJzDaGn1FyZkmJ7rxZ+2I8Ve+OMtr3TwreH/AHdbJOdN5U94t9dbVhpI6nYeyImcVNbXVclQIKGQAvHG8jRMIpWfqBUZ6HBMAzFVvExDppNgvMiHOJszS5vcCb2i6r4xxOphcG33OnOIqAZPMb5eapFpa0DzGxN/wmI/8N7npbR4TeBuI+MqDw38J+H/AG1uS3XWC3XmePe1w3BcKSpjebcd7p6WamtyU00sUUqtPJLGhhV1jYLD09+rin1cb7w9zjUAMZGkCk0gw0OeCc8EkxTzSdiXTxOGcCp4fhhw4phrHkB7qjodVIcCcradyyRE+KBl1MBe5dTxmd42zam8N0eMXnvcd4q6lblQRW17Ptmpm6jGklTTRU9oaVHkJpu0kq95UUsGwTxqFWi0uNPCzAvmdUdl1gEtLWjQzY6Hur6lPFhgois1rdJFOmWuBvll7nEgSYiTvoVrd43nx/ta47y49snil8fVl5SqKOG7VW1auuorlc6hJFlHtMElwoJaeGn8umUpIsyRL3wA7ENBiG1GBnurS0HUF4A3MkPmTOhBd0EAIUOF4htRuIfWYAM0clPQGLCJNyZLRH9RW+bRs/jUgqYY+N+Vaa/8TS1sFVUz7s2/a7xuOCCWV53loHoTSUglQCePyqlJSh8tgsgVkIpuwJIFSWOb+FrjcjYl4Jv1bbuNUeM0KtJpkhz3SMxDmNAgCAGm8SDMt3m5C3Ta204Nybtss9/5GquVaq4UdVd49i72emouurR1WomqYaKGnJqVilZHhroJ44S0OEVnZ9U0cTTpvc2mzKQBJBL4noXExJ3Bk3AMC44hh8R4MipytcAHNAbIEmLAZhGgbExLtl3298b8WQ0tBvDZNJd+Cr/a6WO1VMNopPu9fIidGWhlhjX2SboYKqKA6sHPlnLKwrrYmq+Q/nkzPXvOqwcO8Rj25oLTpJBAm03Mi2u430Ty47pvlgvFBVy7Z3BuSzNUGVtwxFYaeGnaMMsQDESecrJleseWWkwzZPTrIQQ2LCJEE3n8gNr+saldtlBlVuTMGuI8sTodT6g6C9raBdJsVp3JDtyjiNvtFpv9VJ94PNJIJpYnlPU0bjuCw6ihKkrgAqMjRqSIZNha338evoue+vRdXNRxLmi0aaCPhpp8ytunqYLjSWxKmhWG8sQCEhYuiq5VmRuxKZHx7dxkarc7MANlkbSdTe5wPL69pE94+K2Cliq6WV09jt/k9lEkR6C31ZSPy7Anv37acOKzOIcJkz3usnk/PUzJFWpmUVaGdRCLZ+egSrQ3qkH0ONHMnQix74OiSokaBciAq0A8JwxIZsfPShyshDJ7k5A0cyiGxI9DoZkQELRz9FdCrSl6KQzfD46mZEBBJ74Axog7qxrEIn886maE6TqZ1EksBj00MyYNQ2OT29NQOVoCESAMg51CUUInPc6JenDChsWGc40cyORD0uYqBs3QWJPY/u0cymW6Qcd/y1MxTwgE/PA1M5UAQWOST20cybKUFtTMgBugscDQzpsuyAx+efro50Q1AJPzzouenIQGAz2BxohyaEFgRj0zqZwoAhN6H01M4UhN37D89HPdEBSWMhPpnXGzrwQYrCRhnUzhHIEoSY+Y0M9kCxV5nYjBxo+Jsp4arzO3fOdEPU8NCmMjhRG6IQe/WnUCPljtpsxRDI1/ZaPfaPcdvtk9RapoL0sZVhbmcUwZQynEUvfBADEK3YnADKNVv9VvoVqZfzNid9diL6fE/mtNk31Z6+r29tyOpig3DUubhNRVigVao4OHjCZEhU+6HQsD5Z7nSPqGOy30MC4B73WAEdrbGTbuD1WNv9+tvsf9pjcrxFHTwpFU1NBRMXhj6yredAR+0AJwT8FycD1FbnONwCfzW7D4Ut/lQLkkSdbbHbsOvUKNFbzQu2dxVNnqbxWcj3+jlbcPlW+gRKt7Mzye10sNMxjZ1ijj8/3etlZYi34siyjUJFvKetrjqTb632FlrxnD2hviCGHSJtJgNMiTfQW1nss3zNyFZeMNi1ty5FoLrVWTpN8t16stonNRRTtKqnyBIuG6UnhVGHdghBByoKuL3RTYM06CwJ+u5Wjh9HxK3jUnQW8pBIIjS8T0JM/DdbxvvdwuGwdt1Oz7fdp99Um9doUVXaaima3XG3wPc4cxywShTGWg89j/AIHAfpZguddjAU3EuzDVrzfrlMXFtdF42tXw7qwZWePDvcGRJi9uhPr2ut0uO6Kr2fcctI9C0lTJRw09mlfEsMh6ulc+kUrOjgEsEHT3I7nXEZVLzlba/wAP10Xpm4ANDHOk5Q45hF/3Gndc15Y3su2rDRrPeNpcd1lVVLFVRVLNT+2TSTCBYjNEsy5PXESyOJCyIAR1BtW+KJ5iXR009dR9YHVbuE4Rr6hLml7YESRa07wOoAgjX0Ufa3jeonFdaNy7W3E3JMUtRVJctkVNckCrMA4p6mWmSGczOsskXROH75J7KzHoNqOqNGjmaAuA+IAJiBra30CY4igyr7xRhmaCQSJIbYOMyNvwjt6JqLjZb3X7T8O9PxpyHwBVLbzX2mSvL2x9xT9cSsKFiJXqqsdMvnRysGdAW62Vm1ZXoV35qlbK6DAgyBrBhsNaIAibf8SsGCxOHouD6NbMDdxiSNy0ufc3My0EydWkgqQ/De3LJxTaJKnd9tuddyHdZqKkv1ZfaoVdVcKuCGOlE9PVZxJThjLKkSojLFK5RB3XVOKxbJyMAa0SQBpe/rJgTJ+NlgxTcTXd4lOSB/SALSSAW6CJ66i8mCtR5w8WPBPDm4v+zXmDlTYdgrjLDc4rAlStRfI4vMBjL0FN5lRFASPxtECfdK9Q6iDgeGYrFAuw7HPAP4WuIB7kNIB7TPWFX49PDN94kN5YzOcGtPXKXluY9wSNplcT5N8Z/HG5LPuTdz7e5q3Lse2W6nkX2Xjje0NVHWq7Sq1LVQ2dRDJ0SJ5csbh+rALKGLa61L2b4iBmFOHG0EsuN5BqX/8AGyz4fjPCKZFJ9ZoubyLTa4vIgEm8HYGyd8B/aieC+42y67I3N4hNpcUrbq6OgskO/qefbNfWUjU6uep6+KnjqJ4pBURtJEWV1ETdTOz5biPB8e0eLUoPE6w0uAvsWzaIgGDraAuZTNKu8eE9tRxuSHt16QTN9bSBfQQpScucW+Fjxg7ajqbxx7wZ4j6iMOlur5KK33+Ond0DdDVCiXpiYLH1FWyMKVKuqMOfhvaDEYcmnQqFs6iY+lp9PgkPs9TltTFsygaFwLTr+GYINrER8l5/8beEzmHwyLb5PApzDtzbvHUUklW/DHI1ZPeNpW6oeodKmntN0iU3C19E6TsvV7VB1SFjFnqxufxHD4txq4oZXx52DURbMwnKbaFuUwLHr1H4WpQoZaEvaXGxgHY2cBmudQ6byIEiPKz7YXd0u86bjTxAXzindvgb+0k4opk3Bs+vu11pqvb/ACPZoZXert1lv9MRS18saStUxU0qwVJSSoiMOJca7nDmmmx1Gq4VsLUtmbJgnTM08zAdJuNDNlwajRVIrYaW4inLsrgGkRc6kh1gZAJO+USV7PeADn+0+Lfw+7Y584wtNptFLumuqrt9wwVkUtVa6mFKamqKaRUmXomFRTSTBpGRmjqIg3diR5Li+HNGp7s90lguexJImR0MWkTpovYYLH0q1D31xOV0TOgMXEwZv27mF89P28HC+wOQfCR4avGjtSrpareVvu0m27jK1O0NTU2S4zV0tJBUowDCSjkgjhHUOrE7A4wAPWezOKfTrOwtTcA9eYAZr95O+y4/t9gPEonFU22puidAQTlt2Jvtud5XjN4G/E74ovDFvHY2ydjXCq3Dx7vC77e3vSbHrHiel3m9ru4qkgoJpcihuLS0UyKEAadsQMrNNFn0+OoUXvzuMFs3/plsSRuACPTqACvBcFxuJptFBs5agMCSMwzQ4NM2LoIvYxoSWr9AW/cqcGeKLwq3nmjafIOz+auIN02KartlvukcMNPLV06mRrfVL0AwVCSoYpqdwJUYSLkAZPyvEUquGrCjdtSQNzE7/K4OhHwX1PgWKbXjwqZAaCSQTOUg9yY1E3jcTZfDv9nb4heevAX44OVttW+W+WzgjZF7v1RyXa7bQJcP7N2Oaogts95o6F3LzmlBtkpAMiiCEPIsiodfTcVw5mLw4NTzkAC8SfMBpAkg3I1MCCQvm9PF1cHjq2GpNmiHFxBtygcpnzRzDS+9tR2f/wApdpePm8S3hnvnG9XS7ooLvxLHe23KlaKs7rae41LxVz1PUfN6ovKIICqqMiKAqBV5vsrUztql7Q2HAQBEWuD/AHJMgyrvbkP8HDvqOLpL40gAZBAgAATJtrMyZUdeJfFRt7wPfag8B+I/dtsu3I2zNs8dbWjp6KyUaw1k9DU7Cpaakj8pnVfOXz4etiVzhn6c+4ejiaVarhK9Old7y8X0nPOomwj1HqubTr4ajisM6q6KYp07gEmMtzBiSTPTta6id7XzZ9pt4z9sPaKlrpz5ybuEUxpvfjt+3EErLFFTtkuKOjoofNZhhsRyEAue+3hWDpYamadQ5abBJMSSIlxjubAeg0Wf2h47U4hihiKU53GGtmzQDDAD/wDZxtzEnsvu6+zJ4V448GlJuLwwWriq3wpsJ7rS3XkyKeMjf10neiqfvCqojI1RSO1JPb4w0mY1dJIof2ah38Rx3i7sZS95YRksGtjmaBmBvYczpJiSbEgWC9pwzgNbCgUiXeJVOZxMQ6QIAMkvcOhAygnmJJiaHiG8TnEnh62DYOWec920XGlhcw1dpWvqnFxv1eqHyqC30IHn1r9Mr/s4VLM3rgAHXmqFDEVangYdhfU/paJPQk9AOpgDWV7GhQoDOH1A2m0kOcbNaCbydA50WFydACV86X2m3jO5+qPCBvPnXfVlo/CRNubcFtfYW1rhQwHke7mSoFZBO8nV5dgpI4qV53kCzV7yLErimiaNT6vh/B6bKowNWoKlW+YNP8to/FmcLvPNAa3K0SS5zjIHExHHW08H7/g2Obh2thr3WLnWADGGfMROapYAOysBGY8C8DGzvDdsnj63w8Ibd319on40a27Uu4+QL3Y6TqsdFU08kcxS6bruNO8cFFA8f7OCITS1TEzyBuunjg7nGsTW8ICgPd8MzR75YCbiWsEPe69gIDBacxcTxuBUsOHk44txOMrNjK0iq9swQwEnw2Njzue4FxGVrSxonr/F/KPiV4F5d33vG7+GPiax7On27NuLc1tkutcu3937cjrEp6GSiucVniVPYPvOdBLOZDVx1MS9DLCpHDr0RVw3PVc8MIaHFtw5w3BqGMwaIG1yYleywrXtxeSjTZSfUkkB7ZIGoBbTgkHzHSBAduvSHjfiPxubc8N++6fanI+0fDTso2Gd6GwRGfddxnhkQziRNxzywyB3Lx0sNNHDHFSqVCA4j6eZxKtgjaq4vJIFsrGW5YygPJJPM5xdJ0AF1roU3txLG02AkExOZ7wSSbgljWhoMNEG4u6Nc9wf4gr9tranEHG3Ifhq3fYtzNdn2vWTcZWoJQ7ungpJJJpqh6mWG50xbyIizSq2EZmErxkNrTXD69Vz2PD2gEgPIAaARsAWESdAY2InlVTKRwrDzZXOIBdd9zMBsg9DJcJzDlJBLl6QXrdfhyk3PZtqXLa1puG/L7OJqeils1UldPUwpI6R9Tqkrt0RyBCzdDBJDkDOuWcXiAA0TGo0jYHt0+ELFSwFR7nVc8eHDScwsNdLgDUkASCd1qVm2tQ0E9s5N2xZLrs7ccG7aozvcIvPqKOkcGGoo6moqOqSRJRAMRwO6RyGPyzhez0sa8U20qp5MugsNZGWNeuYgTe91uxWGa95aYccoi+pgXgeUNmwMWFwZhTxtlyo6ih/ZeYlB1NBEZuxnUZGTn1B7/x1jZVBEryWIwzg+Dd2pjZalvBbfbKegvNVeo7LZ3rKSOtMvTidPMBSMs3c9TdKdIyz9QUdyAS2pDgQJ/eDB+Go26rThy580gOa8frbS4m+2q1bbO5Lrua9y2VqKeiMUU80lXUNGzeV57JHIkcfUqyOFVgshUoAfdOcF2UgLza3z1ifqYn4LfjaTaTA7c6DTQX1uQJi2s6rr9LRUlEZXp0cSSEtK5YlpW/4mPxP/QwNLntC4r6jnAB2ydlxoByRW8z6aMpwxJLn541JTBiQZM/HtqTsmgIZc/pqByYBDLfMnUL4UDSklxjtnSeIrGsVi/yGNTOnASC5GMnGjnRAQy4+HfQzJgwpDP279hqZ4KcMhC8wfI6hqJknzPpoZ0waUgydj72iXI5Cklx8ydLnVsIbPjPfGj4myICCZPpoConDEksTnRD04aEgtj11C/dFIZsduxGiH9UwYUIsO/fJ0M5VgaEMv2x6HUzdUwEpGc6BqJwxCLk9uw1A7qmDOqGz49Tk6mdMKaAzg9+2NQv6KZAhM/y9NDOmy7oLPj66meyhYhFvXJ/fo59wiGIDMT66mdEM6oDOfqdTOiGIDuTnJyNMHJsiCznPz1PECPhoLP3750c6YMlBd89zoh10AwoDP6+mNDPe6bIVI0y5+OdcUuJXgsgVeZ8zoB5ULArmU/8AENTMUMiV5hPoRqZ1Mirze3qNMH9FPDVmnWMdTsqr8z2Gm8SynhnZa/dLwqwSLCldH7vciHvg5GVJ9SPX49vzGs760iy2UMJBl0fP8wFDrlnd227mlXZ7bZrVuffNtiivFvpXvFDE9G4Vo1qnWR1NGwL4EvVE7dR6WIzqUHgtLs8NNiYMDseW/pfqvUUsFUY3xCwmDpF3bw0zffqNlHLi7xX7p42sG0U5G2/VQbOvFVDPaN13uokgW+gxRmsmqXhgkhhfraWUNI6h0RmzHh0Gt2AqhuamZibCTl6Tfp211TY2lh6tZ1JxgtECMsaS0Dy3GmkEQRJTrl3ePEl9qeRqvkXbPG1Hte42yeAvernVGmvdHHEZRdqKejgmURRLOiM8bBkMZ6gAU1VhW1czcglx2Dc28XEAz0mR0XWZRc7DNptqEBu8tblJHlhzxrB6Eg67nR+HrbZNwbv2hwf4peE9uXfcrU9Va9v7nrL1PfLTe6ekpoJp4RO/QaS5TQ/t3pmWJngilfDh3VejTrPoZ6+EcMk3tBBJMAg6gWvcTA1uuBiMc52HZQeXMdAIaIvbKHSNhJAJueoDSut8ycQjjTjiv5Z4Ktkth5H2y8e6rVQUVTNDZ92PaWneO1VkZkdJYzC9akeQrxyy+aj+6YzVgeLHMG1YyvtMC2aASIA7azIt3WTiuA98cQ9xJaIMmXRqBeSJdEkdgQVm6Hnbijclp2/4jtpSX6u2tcrIldS0EUsgmpoqtIKoTS0wIjQDpXzADIGQlk/EQ2GpRqAuZk5pg26SLHf4fFd/BYJ9Skym90SAc23pOswbTBGmmnWaP+zHKVtmul7v/Hv9hJld6q2WuCmqvvcBQvTcnqF6Io+ojChI2Zo0LPhektSxrWwCSXxG4j4am3wAJsseJwVSk4sbTJEgy6Ykf0xqRFzLiNo1XH9oXy2+Ha67IsVXdb3a+BamhqbNaGqKSH2K2VWBNGaOkhiFVSUMywTxtPN1Dzhg+WHiZ+i+lUrSRzVAJIEkxO+1pFmxAiRrGbEuFRxLWbgkzodIJJ5nCc1yQQYBJBCVyFy5SeIRN58FeGio2nc9xU5pEreR6yN57Zx9XyeXNTNNCGSatvChIpUpU8tYwYHqJoRJGstmBolh8TFyxkkARD3RqGg6N2LzaZADiDGHF0alJgd53EE5JBbaYJIMBs3DRLyAYDWnMmM3hz5e5wtG/bT4u/EjfN3WK3tWwLtHjajqdpbeqYsyCM3KohmludW5Ur1xLVxQofMTocKGNrMXg6LQ6jS8R39VSHQezBDIHVwcd7aLPlxU0zTijniS0nORpZ7pLJF+QNMEAkm67ZwF4fNoeGOx3TYHFe1dq7IsVTWyXSporFQpb56kSxsIoZalG824So0ZzUVT9cinv3AUUY/ilfFECs8uyjQmwveAIDR2A/dMcJgyfeGMGZxALjcnLHM4ukzfbSbd5eVNwo6qjp2FdOaWbpgjAmIV+rHbIPyJHY/Md9YTUEjqubSwrmvNriSetputW5ApLVdqF6XcNPar7YnjZqmnucUdVT9LkAu8cwZSnpnA7Zz6ZGrKWMqUnipReWkbgkH6XVdLhWGxNJ1CvSD2mLEWMbftPooYckfZ/wDg35Fevv1T4cOCts31QTFdbHtiOzV8c7sMYq7e1PMHJ8spKj9SsfU9111G+02OIyvqucDs6HCOkODrLVw3hlDClootymb5XFp9ZG+szqOmq4DYfs59x8J2i3WnwleOzxa8A26lq5XoLRuprfvWwWyMVDytHBT19OJzEJKmdw3tSsS2SWx20v4rg6z/ABMRhgD/AFU3OYTaBYEtFhpkAjQBVChjWU3U21BUzXh7Q6S65zGW1Mx65ifhYxf8WE3IFk2HuzhX7STiTjfxb+F27NSVFw35xdDUpX7VKKyx1tdtjqasp2WTLJW0U9StMz94egdJbAilTqCtwusfEEjLUgEz+EP8jraghpjS62VqjsVSNLHYcsZFy2XDUcxF3NAI1uCdSIJXjB4O+e9n/ZX+MXeXhbs/M/H24fCXykKPcGwuV3uUdbabNBURFBU1U8aAVESNAtLMqrF1z0sDOYoy/R2OI0RxOgKxkFkh7ACDI2DTJBM8s6AzeIPK4Vi2cJxJw4YXMqQ6mXQL9zIF4EkEkWi5Xsp9qlatqVX2THPXh/2zYJbvDszaFvu61vtEDNJJba+kaSvlkXtLJLI1QSV96R5ZG7AONcHg3EXV+K06jPITA7AgtAgTsB2A+E+k4l7ONpcNrVKji5z2v6kyZqamOxJjaAJNvIrwVfZ38c/aEfY7WQWmeybI8UGx9/7rGx93JX+yvSyF6arWhuDBS/sksj5Rky8UoilT0ZW9rxjj/uuPaypem9okRJ3FhuY166GNV894LwB2OwcUpzMJykaTMzO0W6AASLrgfEniw8RG27ly/ads2C98b+POw+0JzNxpXBae2c126ji6JL7RUUhCQbvgj95mgUiujY1CpJ1SJrJxDhtNzKbHn+URyPky2dGHcsdpe7dJEX7PBOKV2Yh9TLNdtnssc4/EWkCAQACbw7eREOtseMDhzjj7bXg3xsUe8diWjw8cqW2CHfArKrzYrTS1lta13akvsUkS+RLFVUsck0ZQr0p1L1BgNNwzD1Rw6pg6s+LTkaHWczS3UukG0dYXP9qRRq8Qo4nDEeFWa2Lt1FoIkBpaYFyIIkkBQt+2k4Jt/AHN2xdq7J3Pdo+Grptq47g2BsetqGll45slXXzypRIT/c008jSVkNLktTxTrGxLAk9P2bxQrVHmo0eKHNFQjQuA01N2izjYE6dVyfbLBGhSoupuJpEOygxNozEEDyk2bf8ACYAFlH3xVX3au7/tE+YpdlS0HEOz6rdy2emnpKpKVbDTpSw0lRPBIHCK6rHVOoVgjMwUdmA1fw8tfhRUqTUBlxAvmGZzo63ED8+qxcQYaXEWUaJ8NzRTbJMBjsjROoAykmPSy93v/J7/AA+WDmPxk+Ifxy2zjg7f4l2eG21x/SyyrBFQ1FTEIgoPq9TBa4Yg7AdpK5nPc5HK9pMc7C8NDarhnqk5tdBzOjtmIaNLAjquvwPh9DE8Sc6gT4VIANt5jAa0kWEmC4jqR6H1IvfiT5T5p8WfiM4T8EV349rdj1cSvvnlK90puG39kVVTDRWuS1UFGgSK91kTWv3IjJ7LE89QJZCIsHyuD4bSfhWY3HFzGaNy2fUGYvls2aDJ5yNAMrZIX0bEcRr0sSMHhmirVaJOY8rCAY8Qg5s0GTTaQ8zDi3yiYW2eF/D/AOBmPkjxIb+ve/vEFzbQ2Ses3Pyzvmpp7hcqKnijXroxO6ilslIArstLSiJgo6GWVgoZMbx6s6j4GFZ4OHcYhsnMSdXOu6oZ9ROwWbBezIxlSnUxbw+q2S2eRrYBJNNghrR1MXmS83K8I/D14Tt2/bYeJu6+MHmTc3I1J4BNvbzvFm2hYRdJkvd5qH6JZpIJET/ZaZ5RCskikS9MENLGFaMuPSYZ9HguCaarA/EVGzB8oEmM17/isLOdmcTET5rj+MPH8TlwrhTw9CADaXENuQdDFoJ0ZeMxK989m8I8K8Y7IsvC3Dmz7zxl4YrBbKivgoKYPdqHcqLO7SGOqkdy1KsxYyIX86qaCNVXyghfy/EuI1a1Y16wBqnLlAgZehy//wBQBDZDjzQB7r2ZwLcFhm4fDuEgwZkOuNCYu50gEmS0Ejqtf2/Zrly7W8wrVw7blgr6kWLfdJWxSX7asFTF7PU0oq7VMzeZXUsDxKY4hHGnURO+QvVQ2qKcPa4iDZzRDnRIeWmLyZGY9OUHRdTitLDFtNop5xlgNcQCAYgGIhrtS27iDcAQRpUvG/FF1s1j4p3PWch8kcR01miuMVg3DKbHarHT0MwKmKy0iwEGZYXlhjkWoDrD1ZCyK2qa2PLaj64aA8df5jiSNJMtDr3jLEjoY24fAPcyGnLJykMGUQDoXQHFs2MmD6RPX+A4L9aOPOLt20OwFpL9bIhFBTUFNSW970zq6zSsDGhjjjWsOeoonTCesBlRRdjMVWdULHOkC13WEWJsSLkE7mTa6wV8Dgxn0h0SYJIGrGjfQNAi42sTPbd+W+yb+25Ytw2rz7zeYKqKo29XzuAJa1ZeiGojZSAj+8yLJGAWUOTkSrnnGm5ri13KXWPodZte14Olt5V1AhvmgsAkjpaTE/WbXjYrdto7FksewRsLc12XdD2q3xtQ13nMI5qcSEOIWLOQwjY9XUuWwGKn3jpnFlQmbAx922+wsGJxxFUYik3KXOMiJg6jNMTewv8AGLLctsXK27K4stuyK67x1tfQ0UdBH5XvtUxtIYUlAOetyBg49W9/sHyBWxHibXOwt3Pp+gWOpgn1MYawFjeTOwm++sX+HZK2fZYOQb/953inq02xtur8ihts1X7VTyXQAsZmOWV3pllRUZDhZmlYEmONhrwxFKmXjV0gG9m6GJ/qMjTyg7OK53GXZSKQ8xhxMAE6ZRESLjMQdRlncLtckNbRVNRLS1hrVCKRDM4VYckjqAUAO2BgFiDgYzqnxbarnsaxwEiNdN/2+HyWQjuKB/KkDRyAIArsvWxb5gE49NAVRMbpThz5hpf0sm8V3VoKgzRyRPG7oQ646gvYN+R+fpoPqQ2VZ7tzANvp9/BHtVRPNbaCWpjEFQ0KmROrPQxHpn6aszdElemA8hukp55gI9ToGok8MpBc4GPXUNRMGJBk9fe/dpS8pw1IMn6/nqAlMKaQZCPU6IdCfIEkyfXQDwiGBIMvz0fETQhmT66BqIhpSDLn56GdNkKR1n6aGcpw2EkufnjQzp8qQXGiaibIUkvj8tLnRDEIuPnnUL1YAkGQD8tEuTZCkM/rkgaOYp8iEZPU/wA9QP6JwENpO5741BUnRMGlIL47fHUzJwwJBc9u+NTOE8IbSAn10DUTBhQ2f5HGlNROGdUJnA9PXUD5ThvRCZ+/c/8AhoF9kwYhM+fTtqeIiGFBZ/kc6IqI5EIuCe/y0M6YsQGcH6aJqAlTL1QWk+GcDU8RNk2QGfGR3B1M+yIpoDMO4GiX9U2RBZxnTZ0MpQWbt30c6PhoDyfu1A+6ORSGM3yOuP4q8GKSrztAVFDRV/OGiagAQ8JX80euRjUFRDwlQmHc6gqXU8JNqp53iIpmpQ/xEykqw+XbQdUkcqenTbPNPw1UfuQJWlr7bYbaXp7vK5WI2+GXy6TAAPnuT0lCScAKCvckjBzjqjxLD5r2PCA5rHVnXbGjiL+lp+N+wWHoePto7StF5t19o9qxbeuUr1t7tVLH5zXqsZ8u1bIoZ5l90ghlY490MqL0HY7GloHNOXTYDuBoOuwm5krOHOxNbxcO0ioYGc6gaCJiIGl7a63UALzzVtzcfHNfwXwzS7evd3iMNFbrmJJKKWnqYYZDFLTrIqx0opYklDTVBipSsXQi1Rn8g9PC0nNeatc5Wm8HeTqTJmTERmcTEBvmGzG4EgtquBsSBEW3sA2TmvYCwnM5sKJvJ3hn2Dx1VUd5rOWfFlUc71sEpuF0485OktQo7a0kRraK2baoIZaGho6nyV6Y4I5gkiJJO6gFj06fFqeJ5BQY4DUuaS5xvlLqktzG97tAGgcYWCr7NYg0/EbVLGAQ1gbyCwAIa4uJiASS0k7RMrlm09k/bYXOg2LRcLzcV3qHbm4nvcR5bjttBe6I08MlIi3entkk3TUz09QyOw6nlDF/MwwIuPD+FsqPFSsWS24YS8Cb8pLBIBuIJHquBiOKV3YZvhUxVbIALmuplwEGDzm400EHUNK3/eA+202xR7Ysr7I8Nl3sl1VVr/8As+sFvu1NHNIHklf2O53Ckj6WwqZdUJVnOTJ05ys4bwhxzNxDjHUhh6ASKTr+k9NLrq0OL41x/m0MrgYJ53RfYio0kCNSR10Wh8R+KDmXwhwbJ4T8UfBW6N0bH2Vt5Ns0d2jtFTtO/VFPFEiiL7prZ5rTe0MUiqUt1f5k5EixwuVXq6PFeEioH16D8uYl1y1zZO+dk5b/AP7Gt7kLDw7ixcwNbDxIEgEGN4pua10gjVhqRHeF6teFbefDvOtNs7lPjuz8Scs2ESy1kO47EiIKQw08cKI9FUKslNXRgxeYr9MiN1kDIJPlq2KxVF5ZUeQRMg2MHadI9DBHZejxj6FbCk0y7I+AASTJzEkntawix80Lslx5etGxN1XLacFp3LW8h3u6TixTyUFTLHNK6RtmtmVXSKihEjeaD+zC9KjEjKNZMHNSwIyDUgiRfWJknp1PaYHEsJ4lJhJs0DlggGJs0wBmMSDII8xtqFKbam2FnltNTbNx0Rijpdx1YRZKy7VcwMr3YTg+Y83WApkBzGjqhwIQAcXxDxCYEAWA2AG1x13tJnqtHDeGPYwNeC1xJdYEAGzcsaRA0vMAhdN2Lv6jTbu0dmXCit+3Llc6cPR25KsPijRwaly7Ae0GNCXklXqD+bCwZjJk2ueXGXm3WCNrAD6D9IXNxfDXNqurNlxaTJ3J235bxY6Q6dF1qG41EiNfxA1wgpw8EaAHokjGRKQvchgwxg/8LYxkjVLK0c33CwPwrZ8CcpMHvO3rb8wuT7s38dqX24VNHcbNNBBc6OWqp7rV+yJRmWFoozGhXCCXocfIv0tgkkGt2INyDBHbWf7LtYThAq0mBzTzAiRewM/GDFrWm61l+TZ54bpueSmrtp7XNM9HDV3KAxU5SNmJkyiyFjKskZSHCt7p9CcEjMBmNidhc+lj8zp8luPCWtcMMYe9tyB3gbwIBFySddFy6r5b5LpNw12xtw3ri7ate1JHeLBLtygq7lWC1pUrHHFVwzuoSYmUKiIJgJCgOCQTrb4TgAC4nQ+VoDjtJJmPhaToFmPDGBprFhLASOYzmhsuIa1oOo66ddF1vZu+N7y8XVW8rHvHcW971bqycSUt7oYYXuUdNUBZonWOngaknkQMI1YdpHQnqQ6DatNpBqjKOxmJ0uSZBtptcLm8R4ex9bwaTG8wGkiCRMAEmY36QRqFy7nDmHg29WKXc9ZerFvex09It0lSx22S73GECISoYhBFMYZlBVzEelusIcqcMLMmIILWAkGw2aSbb2M6arocE4S5pFR7cjhaXWgAztDiJ0MG0+h+OjxK/ZE2Kr+z/wBkeLvw87Xv9FyC1srd+7gts9VLJ95bdqqiWeKNaZx0pXUVPJE7ohzPGJB0hox1fTcJ7UNbjPccTAiGz/zAEydIJsDFl84477H06uDdxDBg3JOXq0ucZ+UbCIINyuxeCLxHWK4+A7xKeGvdT3e5bA5F4j3hHxzf6yeasqbbuW32hZ7hs2pqsAMUSmiuNH2zLSz9J95TrFxPA+Fi24sQ003tzDQEF9n69y1w0Dhay3cB4r4uGpYQk1A8GJM5YY4OafTVpuS0ncKeH/kwW9aG+eDjxM7HlEEl3tvI1Nc6GRKcNJTtVWmF0YSKpYAvROPoM49dL7ftLDReNw4fI7/PquD/AKfYh7iWXytgnpDrdYMR8LLuH2wf2cd/8c1o27z94Yds3C3eOPaLF4rrZ7qaMV1PSmST7sat6wDcYGUimkQh0cGJjGrjp43sxxp1N3u+JjwHTqN7XA1LT+K0bySF6r2n9n6LcN7zRdlrMjLEAmSJJgW1JBPfUElfHp4kN27Q584uu/N+8pqHZHjTt+7TYuRLNJTCgl3VFLTPGl1ioQix089PNSGnqkwHMs3mOGLEj3+CovwtVuGu6nBLTcxBBgu7zybQIC+e8XrUMbhjigAyuyBUFgDsC1syTu87GdBCkh9qNu/afMW3fs4OUdr23bdvq79xQlHcUguHtVVV1dPdpaZprhVN+0edyCGMxaROhgztgdOH2ba5lbEUHnyubtDRIJgAWje3buT1fbqoytg8HiQScwIuZJyhgvc/DYGRAhefB37fuBOQ/EDZNi/2NWS5UF/2BNWUTfeMNHbqiqWKdrbVSDqJeGBoFqvxmGaQggyZ12qf83DskmDkdplJi4BGwJglvaNF5DHP90x1UhgzNzAAnNlJGWc34i0EgO632X1FfZOcP+JTxF+Brjng+O6bi8MHgdS71tdvi7W6oEG4eZbhV3ICeioZY+ma32qOD2aCSpJEkxQRRHpLMvmPaR+FpYsYjGHxKjQPDpGS1sAuz1BoSTOVl9czrL6H7DeOcK2jg6ZYSXF9aYOkNbSmYMWfUAkXDYN1662fZG0uNecL3wZwRf7dw7sX7lrNs3K1WGhdLXs2ww01LWJO0XtHlRGedLvTxxExFZJKicNJJGQPFHiTcVRficZzGQ4k5RmgkBg5b2gnUZRlGWZXv6fBhgmYanhqYgA5AQ4mXHmcfhBDjd7iM2YC/mp4hud+bvtWuU7j9m34Wqqh2d4Kdo1EU/M3IO04ZZqWeJJ3f2KnnmKo6eagjVCze0TxtNI0kVO7P6DgOCbQp/xniflEeGyzZMW9J2AAyNuG5i0DyvtXiaZxh4Rw1wOIeIqVHGS0WDgIF3R5zqZNNpaM5XsDeL9sXi/g7gzwmeDzYUm5NkLX0e0LlZ9t09XUNbdsOZI6+c18aAmriMhqJJoy9Q5lMgTJ615OevxDGuxOJMDXmAAMDlaGuI5dGgWBFidl2cFwejwTDRzACIMiQ4nzkyQJ/wCQIkERuui84bz2tw1ypt5d4cp8SbYt1ptCU1n++rrR217fUzsqU1JLJO3mikWSGCpmBPSQsLBSyHPBp4plRz2eITUedhMakut0BIA6k6L0XDMOypgjkw8URr0cGxYAak6Bw0gi8rz/APs77tNxDfOX+D9vc07E5q5zvW6pN1Xi8Hf1FdaLdNfPIDW3qiSnkLW6jYPSwLSy9U7zBjkxwNI3b4yaVanTdQAp0aYyiWuBAAsHF0BziZMNkNAzG5AOXAUTTL6mPDs1TmgRE6ZWtFw1oi7gBowEm655zh4iNh7L5W8RfCldV74pueRYaS3Q2pLZ98oxZ3Mt1pa2NfMr54mqKiFKVEgRZZIoWjcTOYq+HYCrUoMdSZNMv1BgW/Dc2c7L5nE2kiA2/oMRj2OxAbVqAEszAEZbGRmiILWy0mJNiJktmd/hZ5N2RNtK77X5Bt+1ePhYKC2Q3e0CpS5Ku4HkllqTU1sbolbPn2JPLCqPPldT1lT058bVbTfna7M7MQ0gQIAiWA31mHHRom2qy1MJXqUmmk13ML5jDg0iwIvkkcxHQgDopabtqK3kCmue37dPLLYkplepKTwIkdb1RACJZCfLnQPO+SEJwvc9gcPvByGo10XEdTe+2lo1udd4oZg6eHLWvbzmwEHywdY/+MAyI23XIORfFlw7xxx/uravL/LXHXGW8JaOms9ZS1letFUW6vq5WgSaQzENBDGqzTRYXqEUQYBUKkjD1KdWqGGS2QDABsLnQmTFjGhIBMwFXiOH1GPbiKDcwBJ80AgbAmLk6zEmYkgpvdfFJxhurb+4t38UU/HXK1o2tNSWna9WL7FUfeE1Q1PQR0qCEEo9SagK8g6jEOjzEUDA2kVqpMENNQmZEAfi1MCGxmN9vll/hzcKxlTE1C1xBLrTBBJ2nu1trk21ujw4+ImgqtjUkD72J3A1yraqpsrUcldXNcJH/wBpqmWlULJQCpkqZBLCZovLMb9QGcHGMqMYHvBiOUmQA3YkuiSW7GDJsE9Xh2HfVIawSYmCNZjKBcggw0yAYmSFLCk39fEt833hcIN3XnzRVS0dHbJIA3XjyVYPMfLQdSBRJ0s5BYDPujEHEjk9LxE/ewmBvuqG8LZnEjKNJm4AmdtYmSLbLeNt2FrA0N73BuO8723e0TSskqJGsLE9TrFEoATGeletmOP8TZJNzqtNtqY+Jufn8du1lz8RWfWHhNaGU5i2nb17/ojwXVK65V1NUzma0irE3m1LLD1xdCyABiBkBSFx3PvnJ0oc2QSdPz+4UqYc06QdEOiLSY2/OTPYQtw2vdXuVH51PF/6POZIpulVWbrJYdIBycBlBJ+OR30zZAg7WWDH4cMdBMn8tv8AELaDJ6+8Bo5gsQYEkuM9znUzoin2SDJ9NQVOicMKGZfUZ0A9N4aGZO5x66BedEwYkGTBPfGoDNinFNJMn1J1AU3hpBf1wNAPRDEkykE+g0A9OKaCZs57jOpKcU1bzR9O+hmTZEMy+vc99HMERTQzJgdwBoZxMhOKaSZMDGQNHP0TCmUNpB886AqFMGJBlAJyc6AeUwpoZl/PRzpxTSDIAD21C9MGJBl+udTPsmDAkGYehOpmThiEZvroFyfIUMyZ7476mYJgwJBf5kDU8TorA3ohNJ39fz0uadU2RDaX9RoByYMCC0nbvjGjmujlQGkHzwNHMmyWQWlz37Y0Q68KBqC0v10ZRyoLSD0ONRrk2VAMvc4IOjmKYsQmkAz37aIcgGJu0g7nvnRzFOGbBBaTP+mhmKgZZSAabA9dcV1ReFFO6T54+BONIaiPhJXnd/XUzhDw1fzvrj9NHxEPDV/M/wCYaYVFPDQaiRzE3lAPIMFRnGe/z0xfIsmpsAN1od1u9iskVYbneX23C2HlDwrDGwyF63+DDJAJDY9M/DWc4lrCDU0XVp4HEV48FuY7GZI7CdO1vRef/NF1uPJG7Ytm2DfNPtbiLbsdLe+RaxnWKkrKCSdvIt6U8BDs05Tz2j93zo1CHzBOqyb8M5sjFZdbMHmJd1giLSLXgkWtb0+Fo1aDfBfzVnTGzmiN3TI3AcPLBuIJGI2DwZFFvyPc+9jyBNva82efb+36/wBggi/s/YGqvagtRb5+ukSSV+gyRGLppxFSRiNelm1pxHEC0eC0SGmXHMZJ0gPEG0m8nMS4iQAsVdrXg12ZWgQA0TBMXMC5AIABsSBc3hSd2nxTZNoWawbgs01528plFT7PUTC8Xi8MqOsRWsqlaRZiGRxDEEiXGAigltZqmIe85AA3sOUfH0GrnEnqVkqVAXvp1D4rhPMZDWzBMNFgyREfLYLnvJln5UsMcvK9um48p6O32iahv9gqtx3O3SX2CN0NPI/sUEgirEUywrBiaL/aQiv0hRq+k2g4BheZm3IHAEyCLuEg25iBpMLmYWviRW8KnQDw4iHyBAiSbtIF5OocQLkOuOY76qPFVc+OKmjs/CmwOIN03mrprLaquTlBrrUWP2qaNWrEpIaBKeompF86UQRVKySPTKOtuonWinw/AB7c9fNFzlYbxchrnH8UQCWwJlbcNxerUeS1pcA0+ZoaZi2YZiQ2SJ80iRAla/vn7Pzj7f8Ax1Hxhy5unxP7s20zQztua58t7hlW51SMHjkuNBNM8UTNJHTkZhkhMgGVXAQ2U+NGnVFZtCkInSmARPQjm32cCsL8M1zXNbVcS4AZARBjoQA2xkxFhoCvMZ/BlyL9nDyFu7lfwheNam4Vp913arudTsHmi2W6TZ27axHCSRwR21Y6hagRyEJJR0paMFY2CD3ddapxzC8RLKGJw7g9os6mXPcB1LXAyOpc4CZg7rDhfZDF4cVK2ErteCRLSMjZdcQ4EBkxa/NEkELvvh38bFl4+Xa+xvGB4Q+VPDX4p973KuFBf5ngs2296VHUzRzWe+XJ41ik8tkjioplEpVB0R9JC6y8S4HVp0szXNfQZEmbt/72MDi0k6nTq5b6PtKcTinUc/hvkgNIL22As10gOEX1aSdGnVdL5n8Te8Np7vsWzuNuLqbcHiBuNYae0x7d3Xt+43PcVOZ4vb4LjRPUxKZRT9U71KMqgRdB8rsBiw/Dn4h13gMN5PiNaAAY5iyCJsNSSR5rruOrMo0i6oHPDNW5ROaw5Wh8i1yIsJcbQuhbh8etr2Jtq8UXOPDHN/h2G3Zo2sNVujZFRPRUUUUMYqbSbtb5aqlE/kPKI5/OjWVOhiUKd4eCYyqSKMVQ43yOa6T1y2dHq2y5WExWCLxWc7JIJcXywf8AcS5uWCRoCbyACpM/9pkdl4+2Vdtvb2oN/wBBfBItllooKSrprxHEGkV5a1Gy0EscaqXUNh5cEs2WPIqYmmWua2nzDzXNtiCI19YXcp8IrYqvnD8rQZ+DtABpIO8yQJjQLmF43w3KfhVt+9OHdmXvkeTcFLPQW377eS3w0lC9XLTGqrnh6qtI6WP3swRvU/sh0oXA0vu5Fbw3PDIuT5tpgNBvm0AsL3MLcKgpuf4kGIs0kEutbMQA0EiXE6C4Gy4NY/EpcqDaWwNv3G+1lH58NNZRFuKknqfui400Mq+2090kaliejnngqIY5pmRz0I/qpiW3FYdxe/LMC+05ToIuQYgkCdxvK7mHwVIDxKpGczmLTIJJBcDHmyi8wATrElRfqfFdyPuTlyLbG0Wh8T+8LJVTbju1faLRUfc20vLR2o7VWyB1ovNqaeRFNa9SAHSmPSr9PV0eH8KPuxxTSWUiIDqhAk6Ogz5QZsAXXIk3A4nFOI0aFT3MiKpjlpy52V1xygZszosOVtiSMsE9V422Hybzxtix8w7l5L4y8O20dxVNrqKDaO3qiq3VBC6TvD0XCaqq4Kaohk64USDyp4UdXETK5zq5uIwNBxbeu+4JaGsAO2XledBqQ0kaxdZTX4nVLhTZ4eWSHPJLjqXTlDAO7Wut/wAhZRG8TPiZ5Z+yp5e4+s/M/iN2t4i+PLjcqu/0eytu2WKxX631kj+b7dBaqZ1hqKOJ4j0UlQ/QPPaRZpGHlptwvD6XFnOGAY/xWtjM45xvq4jlcZ1AMARlb5jxanExw+gMRxEMbQqHLDeR0WByXJc0Xz+Vxdq4iGr0E8C+9LHv7wq8BWGkNZ4k9yNx9aq+Gu23K9JaqVpqZVqKNXUinYpNCsMnmF5FYt1iJSFODj7HHE1mUKQDA6JdqYvOlhvaARFyV0+BycNRxtWuKQdzZRcQZibyTBMA6GY6r5SftEfBtvn7OrmXe2yd1UO8KDwY8ryzXC3yfdHW237tDG00S04SQQCtopqh40lhlImoJpkIILxj6dwvGjGUG1Gia1MQbjmBMQdbOi8gQ8A2sV8W4o1mExL3sMYeqTpmlh2dFiCLkf1NkGbqev8A5LByjbrfyl4u+GLtcqS3zX/aVn3FSwyzkK8tDVSwTrHGSFZui4Re8e4ABGsP+oFEHCseb5XEfMW/K6r9gcS5tc02AkmDpsJ31ESPVfZFTXmTam6jbKa3W1LbcIWlpRFTsFopkUSVSPL/AMMgMc2Rks6zMfidfKRiHEFwv92gdB8gvq38PZVZcmRP/wApJg+uwmLQF8i32+/2fG1uU73vvxx+FraFbLdbNSdXK9PbaENb7qY5PJa508kWUarjGPaVGA8aiXJkjkDfQ/Y/2me5owmIFtGE/OOsf0nQG2hC8Z7X+wD2UBjGEeIZJbfMW9YIkEdNSNrSvkgvW5L1dbVt7btxulXV2q1w1EduhkbqSijmmM0ojHwDOxcgfEk/HX0JtBjXl7RDnRPeBA+QXyXE46o6k3DvMtbMW0zRP5BY++C2Rmaos3mtRm3U8kisrDy6j2dfOQdXdgJBJg+h7Y7Y0aRe6zheT8pt9PuSq69NgcDT0yidbGBIv3Hp0X6cPgu3BtnYnhF4P2dyekWzqu27W2ek8bQSxSQSLZqZTG0TBXBcUo7dIU5OMjqbXw/2lqzjapcJl7/z+O5vfppZfpfgWCq1MLh/dCDFJpibX0M+s95B3svm88YvI27eUd82fwReFmolu3iV5Ov0+891SUlzcW3jy1vJUyU6S1XWZImioKyaoqA3u0sdZNgNLLH0+k9neEU6g8XFWw1AQSRq6wdDRaAQ1gOr3NDRbNI9tvairQd7rggXYysYZBJIZNnE7ZiCQIgAl5EBk+0PhS8Nvgu+zH4b3bwzvzcPHzXOOxf2o3TuS9UiGDcVOlM+LuzTF/JpgjLTJCoCwydSg9UuRzPaD2pq4t4fSloFmgay46WElziBN77CAs/sZ7KOwlA+DMkgVCSWyRMyJyhrAXGby0S4nc1Bt7xE/arX+3c47U5c5G8EvgWs1oltu2Ku2UslFuvlOjeSnqKivlzJHJa7O60kSxNG6VVQisx6EcY0nAYfh9N44m3xcQ4z4ciKYAMB5vmfecl2ttNwuHX41Vc9tDg3+1MmpA5zMAUgW2aLgVNTJygNgnitV9kpb9lWjh/cFkt/F2/bzer99811ku/Ey3Suq3NE4NPWbleeonpI0pGZ1mkHSamIDu8uddF/H6kmjSe9oY0glrmtYDIl2QMbN7AAzl6CV1sNhsNXc+pi2MdcXqF7qjmyQGgucYMiSbgDW1kypvsxPCVxfbN38cc5WrlGxMaKqr6i6cfKljse64wF/bigiMy09dDJUxUyMxjlKSU5YSe904j7U4lzYpN8W4aA5xc4TAAtkBDiJNiBBjRdDC+ztKW1cI5lFzpkAZdZvzZiMjfxNImJkLkfF3EPIXhB5eu/H/iD33uHlaGngqb9tCk3JRTUdbWVNV0wLXVG5KaJlmqba9RPRy108LrTyVLVAKxTB6XVisTRr0ctAFoPKQLtaBckMmQHxYAy5oLQJJzY+G0q9GqOcPHmBMZ3c0NDjckCQ6JF3Mc4w0Acir/FTx1xNzly0bNtaw86bsuO3ZLhBeKXyLJTV9JFJKlYtdHIqw0UCTQTyT1EJlmquiVF9sDpIMQY+pQD2O8NrXNGZ1zoC3S7reRggAxOUB0+r94pU62WrzVHgkNaZggkOm8CN6jtL2kNa2QW1udvFd43bPV2HwR8nS3WgXyl3RuaPbkO29obYeSpkroloHYTXu9TvG0paeFKdZBIOmeF8eXG8Cw1BrKnEQ5gGgcc1R0DQUmgNYBP/uPN9Q4TPmsT7R1Klaq3h5p1HOFi2S0EhrTmrPOWRAAbTpmBJ5CAu8cSfYiWG1HeHJfJfL1y3Vylum6G9Xm61PF+0o1EToqpTxw19JXyU9MFMf8AsoZTkL1Et31rd7XMpU2YaixzWMn/AN5wJPU5AwOM+rRPKFwa3DHVcVUxFapTqPfAk0i7yjytD3HlEQH+c3JOqyfKn2K2xd70lt2c/OfNlj2jJdVr73b9vx2TbkVdUhg6FKWlt1PDK6sHkA8vOGX3lGerJhvaik2t4xoBxFhmc9x7m7nGw6wAtT+DPq0crMQaZMkljGgG8ictmgmATJMi0rdLnsTem5N40Ph38QvG+6uZxtBIIK/cLWq3QWC42ieSb7muUSTVkaGqKU08M0ccXRFJ7VC4khdfMxFgZ/1lJwGbq7mzbtAyuMXacx7Ecwt6nhHEqTqRw2WHiSIa4WESSQGwP+LSSRGgMqZu3NpcjcW2fZdPtra9Zunju3yimpKOS6R3K7WacKYxUO5eDzFEatEyyyOySdByynXLjxHudmGYz2AB1AkQD3AEgdSrX42lJa4kEjm5TLoMgfiJEEnr0NjEgbRyVY7ju217eusG5L21XQzVEAe2COO3wRmEES9A6YijMASWJLN27DIyOqcxJiBuSL326/Abd1S7h1RuGFWnyOJFrzJB69RsY+azOya23X7c+975czaUs9VXrabUi+WWuMcEMZqHfpJBX2gyRlQB70B6s9hq2li2Cm3nBzEutFgDA7ydb2uN1i4hQqtDaLWEFgub2LiSIm1mxB6G1l2mS8UNLQirRlNGqqQVXC4PZcfAA/DQq4poEk/Vcengnl/hxf8Ab9lq9m35b7xJXSUlRTV1JFOaWM08gkaomDEMEUfAY/F6Zz37HC0qxdfY6d/09Pmt+M4Q6jAMgxJkRA7n46enVbZSTVzRM9b5KSkkhEJIRcnAJ+JxjOO2dXZoXOexs8qcGU49QBo50BTSTLj1YaBfKbw+ySZsd8nOoHHRMKaH5w9DjUzFN4aQZj8B30PVMKaGZSSe41A6E/hoZk+uTqZ04YkGQfPJ0M6bwwkGUfTQzp/D7JBlP1OpmTCmhmX5ldAvTZEgy9vxE6hqJgwJBl+BP8dDOmFNIM3y/ho+In8NCMx+fbUzJvCSTL9RqZk3hIZl+pOoHpxTSDKM/A99AOTCmkGY/nqZkwpIbTHHcgHUD04pwhNMTnvqF6YU0Nph89DOm8NBacZPf+OoHp/BQ2m+uiH9URRQmmBPrnUL0fCQTNn01MyBplBacYI9TqZ90xp9UBpR3GQBo5+qYUrIbTD17amdN4abtN699MHqCmgPOg9XUfrqZ+iPhpu86EfiBOoH3T+Gu/GUfE/n31wTUXhQxI834+6dAPRyJQlHxI0c8IFqV5w+f8dAuQDFfzfq2iHqeGsDfK2qEBSgqoKWrj6Z19oysE6g90eQAlQfTIGR64Olc6TGi14Oi2Ze2QbW1HcDdR934N13ikp7CtnoaK01UwgmkuZnrTKznCLSwI0aEEv0t5jKegHCnsyrSJaZNjtEfEknS3QSvUYSnhwc4dJAkxDbDqYJNwDa06nY47Y/BO1tqz7WqNvWmsprLYKprxDE9b1pdbiF6RWGAFwmA1QIkR1RAVPSSEZdjsa5zi9oA2HWPWwkiJMT6SQsOMxeZhpVXXfYwDyj+mScxAtMzJld+vlrpty0C0S0FbTMJkmieQGLy3U5z27gEDpOPUE4+B1RrYrl4aqaLsznAgggxex+/gVerq7dZaRKyWmrLrfJFYxqpHnZCnKqx7RRgKcn0wCT1H1ZtS0D79fv0CDaFSs4izWD5X7fiJn19AuS712xue/bhs63bc9LUbSCwXO9WaC0pLDXNH2p1jq3JdQsyLM2UAcQoBgnT+KxgcWZidBeNbGQB0ka7rdgyC1oYwCCQCSZG5tIHQbxJ2QN9bSstbYbTet10O99xWzbMjVdNa6W6LQlmkp5IBIqiRGeXy5nCdUqYY5QK5BD4aodDEutzSehjQ9O/Q2UDyXkUIDnzcCZjadPp3JgBFotm8l122knsO8rhsuluVPPLV2rc1K16jt8UzDojCPOJ1mji911NQYzIz5VgANXVX0QSHiI3aQJPYQWxO4EwO5WDxaJeHluYiAAOWdJJIgdYhthFxqo77Y4WvO26mnuForW3xydVU8Vlp9zbvMlyrI7f0BZA0iFY6WAdMgSmpgquABP5kkjSaqr8VdWaKVIhjDchunYkky8xubN0aAF6WjgaVIOq4k5iy40bzG8NGUxqJcZLtc1gue+Inhe/wDiK4k35wHzhNRc37earpY7xZ7VQx01LURRtG7z1MzuZqeVIlVlCFJlZl6S+SzX8JxzsNXFeiSC2bk29MoF5NryOsKrivDMHXwwApANqWAMF2tspJgX5sw6W2C8vNtx+Jn7JLkIb23+m+vG39nvY7JDtyg3DHSRRby4h277TLLHJJSyL1V1KplCLLG/WIYx7sHuqfVPp0OJCMMfCrvMljictR0aMvDTuWxrqV4pzMVw9h94aKlOTDgJc2JnxCBLwAYnbo64Xr5sjxoeHjl+27H5G4L5LtPJfGG6bdV0DVu34GnqLVW0cC1MDT0o/b008fXKGWSMsGkjHcYB8bXp1qJfTqtLXNixtqY+XcGOi9Vw7hoxzG1WEOv5pkOB1E6GR+Gx6gLzuWzbP4lpt7734a5J2T4e+aqa71tk3PaKNOjaW+JoX8+kN2sjuFC1dME6a+ieCpWUn3px7h2O40cRlpYkGo0gQ4WqDrDrBwH9L5tEZdV2m+yFVpNTBktLTMOuwF2tr5COrRB/Fm8qhX4bvFjuHj7a/NPGnNfMmz6zdEc1buWw2DbFGs0tDQTTTzV0m17rHKKW5RRtUxErNHHWRSdYCgBS/W4nw6m5rXYNpeDDS4xBsAAQRmYTGglpGhO1Hs/jqrsY5vEYaWy9rRrYzNrVAASbERPOwSCN18P2wvGdzht+W77R2Dx1tE7gukH3be6/dtfb5ZrVmq9tt1nho4JI4rdPFR5Ssn63jnmqnpgB5bx3VMJgqT2ivUk6kZZM2ILzmbF/wNALmhuciTLYnirxndQaAxunMIEnRoIeXkAg5iQ1rnEAOyAL0p8OXA2wd101Hwxyxwztfjfj3jKKifb3HdlrJqjb01rq5ZZIrrWFo4xXPNVUc8ApKtAKWSCQusspWfWbiHFnMJxufO99vEdALYtlbchpgglwOhhuUTPGo0mMYcFhBkaSTlmcxixmxIaMx0JJEkxlAiLuLl+427de8vBD4ArTsrgO97YWReQd8QtSmi41tlXUPCY0jYmOS9zsJWpoeookc/UwMiQoHwdB2Jpt4jxJxdTJIaBM1SB5QYu3+pwE2yt3K6PFMmHqjA4IZqrgHQRLaYJnOW2N5BbTMAxnfFMQ7ddl+FXhjw3VnC1/2BxXyFvPdF+u1urr1y5uGuir9x1VP58dSlVcofMatnt7vArBHwUUBQgU9QbEcZxeIaaLMrKbQYpsBgSCDZoyh8GdfyScN4Zh2PrYmsXVKh5S83mIsHvcAGg2OQZRNrG8Ntsb25V+zK+0Rr+N15EtG0/B9zVuSs3VxvOjQUmzrHdatSKm3V6tGrUEMssdKB7O6MoWGbpk/aDXTcafEsCMS4F9akAHmTmibGJIJiZzDqARZeLxGHdw/HHDPhlGrdoygw8C7Z1AvLcphziQd49zPGn4XuOftQPC/vPgXd9BU7T3dSzvW2wvcVeo2juWKldaSWUQnpnhIqgQcmOeCfzB8AvE4RxipgcSKzIc0i++Zs7aRpY7EKviHDadXCPo1yYPaIOs3m4/ENvKdZXxQ/YO8m3Xw8/av8R7S3dAlmnvv37xveqaaTpEFTJE2EOT7zJVUESBfjkjGca+re1VLxeH1HMuBDgewvPyMr5ZwCi6hxDwatnAub8f7kR8V+ghyJs+i3PbbhZ7NbLlT3cmGporjSVslM9tfzOoS5jdQ6qwLeS3aQEqQUY4+H06kOhoEdwDE/fwX3vBPIAqVXwNxrmIFvj3H564u332wPty8be3XYbHS32pnFg3Lb5oBLQV0k8TIEZQcezTQ++mcfsGxglWUXVM7SHU56yPmT6j7gLP7u/EtuZAEtvcQY0O8m+vMb6r8uZfDpu7fHim3f4ceP7dTDdsN/3HarVQTuUEgt61s4gVioJdoqExoCB1OUHbPb78ziLPcxjKpgZQ4n1An6nZfCuJ8Aqfxarw+mIeHuaB6Ex9LBOfBDx/sLmLxfeFjjTkyvitXG+4N7WWhvTyBh10T1CNJF7vcGUDygfgZB8tX4zEuw7H1iJLGuIi9wDH1XF4ZgjXxFOgLFzgINtxb46L6f8A7YDxg37gvk9PDp4fZb3cubNwW+x2K2UUitVVlHTVBqnidDIuUqDLUCmEQcKfUqUAY/IfZXgw4gM1S1NhdmMwLBsgn/7F20bEr9Me1ntK7hNEPpx49YDK0D/k4ZgBYttlDdTIGkhSq+zo+zm3V4I/CtvDxJc38nbN2LzZeLZU7w3TeGRLhVm3hBLBbqy7VDkLAwHmzeSnvyThnmcIqjR7acfw9TLhcOSaLIgAZQXE/wBIEuiwaDEXhsmVwPYLhFajiTVxVLPiqhLXFxBIA1jRo05jP4QAQGrlXGfHlf8AahcxbK8ZfO+0ZuLPB1aoI5ds7Mpqp5IORqOOrkb7zvwn6YjbPbqWAQ0SxqZUjaUpgl2NJ38DpFgh+LdeY/25BDcupNWCSZs2QOgXWxFN/H6nhUHuGCYS0XvWPLmEDSkACLmXGZJEAfQFd57e+wpOMqy8buq66/Xql20qeaIAaercTSeVIiqej2WOrYg5Zelo8gJgeSwT/wCc1zm+SSZJM5Zde+ug7kyZldTG0cn89ha1obILQJBAyAAGRZxbEWiCBKkq9+pxVUjxNFQ0da7yRweV5TzuoJCENj1UKfdyT0YGq/EJufj6riNwBDMpuWwJmbdo6d+sqJvJW2J+QOXLDY7ReodqR2Cgj3g8/wB2pVMt4jkljt9PKjYJQh6yZ4kKsRBTnqXqzrdg6zWNdUO/KAO45j6hsAHQF+8Lo1iXUxTc3PJgySBlsZBFozAXM6EBfPx9ob9pHU+H3mzZ8u9uPavbnP2y6umism2o69Xte4bTW9aXcPdEjCy089PFRRJJMkbU09Of2TOjMe1wTgb6gqCm4OY6QXROXLOUZZmc0kxq3QgEK/jXHMHhaVN9UuzyCBBBfJAJaSYa0CTe2YtzTEDye4fo6fxF8xb25kruCtt8x3PkLddFuHa9hpqsWTijbl1Efe23WK40scNfJRrUrFIsAkId/MjWTrlx7muKuCZTpNqBj2gzVeP5hB1cxjS4gOPlLgLNjM0AE/OeF0KfES6vUpvr03wfApmWWBDRVqnKA8eYhriObyE8o9orB4COYjv66XHlrxK3Tj7fFbG9M1t4PvFbtrb+xUkeELRVUJIrqmORouhWlljp1jVniSRiq68NU43gmAUcPS8YHzPqiS4yTZohovqedxsLar6dw/g/E8SG4qvU8BrTyU6cQQABOdwcXQACAGsAMzlGvovsf7NPwyXeM0e9eRfFNvi7Wlwtxhv3M25+qkqWIlMhjirEEbEqWDDAKsfTtjM7jt8woUg28fymntqR+uq5+NwdZnN4tQl4m1Q3E9iNNBrHeV2Gn8I3hy40oJtx8ReIvxI+Hm2UMDvUXa3cr1tZbqSJcly8V8aupO5X3vdHbPf00tXj7A4NxOHpmRblLCZ0A8MsJ6jVYn8I4pUHhtc515ykCoSbXIcHEQPiOy5NzvxD4ytoWBufeIfGfsrk2/bTs10qvYOS+PLZS0m47I0Cz1VNNX2o0zMpEMM8TmEqsqRt7oZi17Mdw97HUHU3081rPzQ4GAcrmk9tZuey5lHCYynUa9wa64sC/rFodDT1i0CNF54bj8Q/jB4dsNm3lzDyd4muG7lFaprxcN2LtCe47RrzDCktHQChp46mljR4A9M9XUVEnn9ccv7FlMQ6ruC0A7JhqfiZdg7nJ0JMubABg5QwECZ6nqU+JU8Q01MYabPEPLyw1gJk83MS4gnR0SCGmYaOr7T8RvL+5Nt7X5G5k8P20d0bpu9tgrdt32l3HTrZLBLXwNUrB7APaaa33QnolMHnzCrdkjheRkECcWrhaNN1SlRrDlMPMEmxGjgBLQDl5Q2HSXADmXpcA+q5lNz2OAdlcwaFwAyEOl2YnrmJaGwWuJJCnbtLavDu1LDWzLtywbUs5t9JRyVu26BpLbcROAUkFc8SvT1oV1VwzRtIrK2JGIVMGIxT6k/iuBe0QdIBPLtqeg3nVh6VY5KdQgF2YwXde1pnWYN9YClHs3jfav8AZWCy122aG+7WjkMtuoo6GTCQoEeET+c7kFcABThiAOpQCRpa2KrTncZcJvAAnTYD9Y6yuK+lTo1yaByOMAkuJ6zF/jOnSdV2zb1PQLJTBKW1U9dHFHPNFTIFjpAVKoiKFAX1fPxPTn4jGfxcxkmT16n7/NYMUHAECcpkCd73J67fktzWpWTr6CCVYofoR66gqLB4UKjMfQHvomoUfDVjLkZ+H56gej4YSDKPnqBxTimkmUd+57/DQc/qmDCkGVcZznQzo5CkGUY/FqZwmyIZkyPU6XOnDUlpPl20fETZSkGX5nGoXphT6pBk/M6XPdHwwhmX17jQLlZkSGlORgnRNRMGIbSH4nGhnThgSS/zbt+elzkpgxCMoB+A1YXbKzIhmXsfjoZkRTSGl9e/79TxAE/h9kIzfXUL0/hobTZz31C9OKSGZvhqZ7JxSQmqPgWUaQ1N1YKSA9Snp1jUFTdMKSxDX2iF4Wxf7abgaU1gIpZfK8oOE/vuny+vqI9zq68ZOMDOrBmLS7YR8zP7fD5IwMwbuf0j9/u6eNUEk+6366QVQVYKPRCaZviuP10PEU8LqhNM+fVFH6nRFTqp4IQWlbJPUP0GjnT+EEBpTg5dif00M6PhWQDL82Ofz0zqiPglD60HwGNQVNkRSQmlUfAafxEDSQWqPkdTNdHwl3czj6k64JevEikrif17/wAdDNChoqvPGDg4/XUzlA0ksTj56heUPCV/O7+p0Qd0PBCAVjeYTyFpHX8HUBiP54/P4n6aYPhMGENyhYqqtslddIKyqrZpKGNSPZM/s5CR+Jx8SPlnGgQJzLTSrZKZY1ok77/Dp+aytFTUtvhkgpIliiaR5WHUT1OxyxJJJPr+QHYYAA02dZKuZ5DnmY/TRImm9ngWKEVaqi4URjqZh8gTnB/PQLkWUZMmPjZYwVNLaglXUUVdGsuYwI4Wm8hPU+aV6jk47t3HYDPbUBIsArKjTUBGYWv0n0002Hx3Wvy8hbDpZo513Lt6KerQQxLNWRwswiBbpWJyHPT5mSOntkHsMaFaq5ktcDbsr6HDK1Rghpy66Hfvpt1T+P7tqZ1rtwV9HNW0zskPnlYvZcYYv0E4Vj0qeo98AdxkjQp4hsHm1RxDSwZaTYaRJ3nbXcCY9Z9VzrmDljaGz6BYblu/YkdXNDK0VsrpJJZKxVADdEUAeRh+0XICnORjQBqPM0JJHQTfudvit/BOG+I6XtcG65hAAA7ugfVQkuvjg2BRCTaj8S86vy9PbVqW2ltLbsEl5vtN70KyQwzvHKsWAArGOMYGerCnXS4fwnFYk5AW2kEl0MB/5OEgH1Pz0XS4myjgwa76gNGeUvzGd+RsSZvr8rysMvKXi021Q7Yv3FXgRvtrpL3Vtb7g3IPIlpilo6JRiGolttJNM7OxjI8sVAZfMBIbuda28JoME1cUwEf0h75naS1rRHUSOi5mI4x74802MqGNCGsZl3JkucSLxAZNrwopbj8VHi7Pio2/4VdzX7cdNveS03K+vRcbce2LcNZQQU6RKgZ7hcp46FpVkqGV6lQWHkKhJZ1HV4ZwWiWVMUyXMaQJLywXJ1/ljS05Sd72VHFsbSpsosDAwPBPNnuGxux8m+xYAYNlDLkD7L3iK0xb25V8HniP8V3hm8TE13q5L/T7r2TeLLt/cKSTRvLQVVHaLfTJSQsI1DGj60cMT3XpK+nZxJ9doo8Swmels4ObUdN4Muc7NroRrrdfPKGFbhsSa3C8U1tU8xaCGtsIIghsSZ5pBF4K4R4L93eBvnTmTe3CHiW8OfFfhy8QtPHRUFq2zuKSrrrXu+9RTSxSz22pvLHyoOyuIZX65OqIRl1hKtm49R4lgKXvDXyx2jgxrcrY1dlFj6SNZgwF6HgHE8Bj64wuLZzAy4OqOfmg6Nuc46RBjSZLl6HXL7K3wc8l7V3HsG48TWbYW5aWdTV8oWGOO2XqxVsgDUM1rhihhkmWZJGC04hEeYyjM5CufP4H2xx7HhznhzDHIZdm66zHUkkayBFh67iXsXwoU/8ApqWSqcxaW8uUjUl0wMp/7iRrutHtHiv5x4J8RmzfDF4qduUu7+VKO1TybE3RtyantlNzcad/YrclDG6lLbdFkqpFnVv9mWOCokGQU6q6vBKNdjsdhKkUnESHTLC4y4vcAZYACQ4czuURKpwftBUwjWcKxdL+ZBhzcpa4AB0NYSDnJyjw5sTMgC00qbwu8Jct2bkrmHxH0G3+fudrjRrTVdtnvNf/AGRs6hnioaGgpaaZaarRJahnWskRp5pah6jog6xGldD2gNBraPDwAySC8ta55J8xkjlECA1phrQAXOMk6H8BxNeuHYpzqLHxDGOLYaOY5puTfmLhH4WgCAtl294ReI+DeT9g2PhaHZPDG0bDZLdXpt+kvcixzVslZUq1fNH1BhLIr1JMsnnEeZNIhgceY2XG+0JxYdUxDwXGWgjZuXyjoDaQA20B2YGE/BeEMwtEspsc5pLieUczgWmSSJfB1LiQbcpKkbZ977Z4R5C4q4H27YK627DuctRW2ujtNMGbaTQxNKLfVushOKlop5ackli0dRGoI6OnEKrsTTfiTzZNY0l1hECJFpA7E92r4XKYqO56gLQXXDiLuIkWABg7TF0DxFcBcBc47e3bt6+bG2lyNBuCjNFuXal0k9nF/plJdVhaYKtHcVZuuCrXywzgq74w8d+E4xVwlVpD8h1Dunqd2ncGfTZcmtw92LoOpVW52NJAAuJ3IAOxHWRqIXgNcuZPGH9kltfanL2yNxT+MDwM224rZZ2ulR7Nvjj+0I+Dt269ZaOZaeSYNTzEMKeTqAKQ1B6/WspYHizslJ3g13Sco/23O/qadgY5huNBIXn+I4LHcLa99eka2HaAcxPO0aS4WzAbHlJgBx6fPry74gePNq/an3jxZ8NXWC68ex8q2vku3SqOgJHNPS3GphZf8LI8tXCy/BkYfDX0TgmFqPwDcPWEOylh/wDs0H4iDPRfKeP43D/xc4miZYSx30aTpv16Gy/SfO+bNc3qUsxq6+hV6KngqIEYwVdNMTPT5ckf+pdST9G7ga/P9cPYcrhvF+o1+X5r9B8OwRcxtRzhLgXRuLQSBfV2nwWD5Crai0V9t5WoXlorVaf9m3HGk/lvLbHOXnCKPfkonYy4b3TG9WnfK600AKoyHfTrP99PWFkbR8KWRJdpOltLnTMBrroV+bj9pZZd2cC/aW+KtbBf7ltvd9r5Mr7/AGu6W2doJ6OSolWugmikXDI6ipQhhjBB19x9mQyvwmixwzAtykHtyn5wviHt0+pS4u/FUuUkteOt2gj5f5ULuKeRd08Vcrcf8ubNgt1bvnb19pL7a1r6JayCSvgnWSLzadu0y+YFPQfxHA+OvR1KLn0zSaSMwLba3Bba2sGxXjqGJisMQ8SQ4OMkiSDmuQQQDvEbwV7W+BG2T7ovG+vEdyk3IXKvP27bvX7c3Buuf2aT+xUNZA8UwiaqYZvVQzmi8soBSxErGyOyKfn3tPVfhMOMBgminSaBa4L4M5RF8lsznfjOttf0B7CcNbxLGfxjijzUruJgCMtKIymNnfhYweTopy7r3t4mftDt7WTwO7f39d9l+FvaO3LHduZ4bPXPXT25YuiF7fH5ojkM8hheZ6LLrCzSqzsy+VrzmCw2CwRdxjFDM7MRSboC7+oA2hswHQAToLhy9JxvFYjFPZwnhsML2A1qn4g06MLmmxeBcXcWQTaQvdLj9G2BsG77U2vtkbm43prfNFRrbaeejp6K2UpWakeOVjFTQHHkyeXAoQiUdweot4jGYt1Zxrk8xMkmCS4mLXLiZ6iPQQB9Ew/CqFBtLCgBgZAa0RFxBERpFgXGbEmV2Pi/kjc3L3LPEj7wsVNarNHQVW4KOnqZF86oleip6VJZ4FdmWR3qrn0I49xYWLf4c7cNSNJtR4cJ8pAvEuza+jQSe8C+nmuN4DDMoRSnODmnSIkEAkRAzAWMk6dV6F3Ojiu8T0clRGFfpBDqHGQ3ZhnBUg4PUD2I1R4gF5heMpO8PmjT1C+XP7Rz7VLfvhD/ALLbR8Odz2zvHxF8k3C6Xqirp6H7xlsNhdIrZZ2hooh0T1dX7GssMcgK/tPM8vDhT7L2c9nn453u5JbTaBmgiXPcc5bJ8uVpAcdQI3uLPa3jVPh1MeOwOeTlY3mgBslzjAzOBeS2GkBzpBMNIWS+zm+xF2/fqqbxLfaTNdef/ErdvKudXte/10lXb7EZBlI6+QZFZXoFHVF1NBB2jCEgtrscW9qqOCb7jwUBtNts4Fid8nYf16uN5heOwnAMXjnjinHSXVHzDXRYDQlugB/C2zQDoTde426+AuMuPtpJLtzj/Z9v2dQ0YpmoIKOkgis8KxvFFNGZv2TQwpLJE0bgkxSZ7tEmPB1MfWcXVHOJcbySZJ6SL3gAdLd19J4fX8R7cO0QLAACx+AiDaQRv2JWocd7E29ty1QbdsV13tQcd3Kkp6CkpYKVJLhbnSmZVhqrjURvU1FOIlUxvKxljkiK9bqVxXWxra5Ic3mkmxhuouAOvQTOsSukcPVogRlLm7uJMi+05Zk7AWI0uF1+m27uiy16V1kvdz3m9Ev3a/tH7NGhGJfPkCoUlm7IvbvkyHC5KnG5pnM0R96fp6AXKDcRRewMrgMkT8dOsgak6DRW504X4p8TGy7PsLlvZtq3ztiKriuVJC9wmj8ip6GjSYPEVYYE0n4wV74KE624LGVqFYVKMBze0xvvvb126lcakw0g8BxaHWNokDbv9mYRdo8LHYuwN0WDeO89y82V11N0e83K+RwrVVEVV1IsNNHGBFTRQwt5KQRKqnuwAZiNWY3GtLf+nZlgDeSXbuJNy4n5CB3WbCvfUqNbUOWCMsWDWj8JAiRaXE6mSbFYHh/etNFxNxvt7cG09ybWv8VmhtsCV9MjHzaOMUitNPG3SJHSJJOh+lsFx0noI1RxDGGrUdWMGbm4gZrkddbfUbLoUeEmlUIpHlBNpMkTIgRHy7aSYhLyf4GfDPs+1XXfHHXhynh2nfEP9prVsGaa0VUMMwkkqKu3R0rxxzqGZmeGVJVOFkgUSL0SdlnH8TWe1tRwcW3BeAdIgTq2exHQ2uKcLwdlIPpNqeEYIt1mxcDYkTIGoMzsuM8G3raux93b04+8Q+8+LN78fU81PTbVlVJdvQTWud5JaeeqpI5IoorgjSvR1VM8UJjaKlnEax1C9Ax9YUw2rTaS9xOaQHZSBcAwbEXBvaW5iQZ6+Ap4iu3KxzmZRykRLxMSZk/Iw7WJsvXXbls4lqKajotsbneqtVZF5EUNt3TPVU86FMD345nHvJ8274BySe/FLw55zNBI1tpf0C59Sti8oqPbpBksAP1E2XU4bLBSAR0NdcKSnHR+yUoVAX8IGVJA9Pj6DUNUEzvr/lc/xXOMuAP36rMQeXTxeVG0jLknLMWJJOSST9ToZgqSwkyUszjto5xNlPCSfPx8M6AqdEfDSDPnOp4lkwpJBm9e40mdN4KSZvqdHxAm8JJMwHqx0ufomFIoZnHwJ0RUTCkk+f276BeU3hIZqB8SMagf3TeEhtUqe/UuPz0M6dtEoZq1Pbq0MyYUUk1I9PeP6aId0TiihmpPybUFQphSQ/aCfp+uhnlP4SGZyD2KY/PUzphRQjUt/wASg/LUzq1tJDM5+LAfpqZynFJCM3fu7Y+p1M6cUkMyjuMn9+gXp8iG0qjtjvqB6cUkNpfoo0udOKaG0w9OrGoHhWCkhNOB26iRoF6YUkEzD4nTF6YU0Jp8D56GcommgNUep+GoXJvBQWn9e/8AHTNeVPBQGn+TfTUzJhRKA0/fsQP10c6fwkFp/TuRotqICkgNUYz3P+moHFHwuibtUYx30Q4yp4S7x7SME51wi8SvFiire0DHwxpc4lHwUoVIx+LTF6XwUsVPYdxo5+iU0bq4qR2PVjRD95Q8FK9oHzxps6Boq/tHzONN4hSmgiCowPXUzpfBSvPH/FoZ0PCSTUgdOWAJ7Dv6nR8RTwSmNZFbbmKmluFJR3FZqd4JknjWQSwsCGjbIOUIJBU9u+mFdws0ojDkAOFo/Nc1n4g4nLUC0XF/GCCFlZD9y0oki6E8tTG3lkjC+79B2GtZ4vidG1CPQx+SJwrHgiuC4RF7jrBBPxXIuUtjSVd72/tTZm4odl7lv5nNUbXaaWaems1NETUSwmVegTdUlJBFJIDGjzA+W5B0cM4OBfWlzRcjMQC4+UH13PmIaYI1XQwVQYZgGGY1uTK2TIIk6NDdALui40m0Bds2JxVx1xytfPtPatutVyrgGuNaxaesuDlutmqKmQtLMxc9RLscnB7YAErY57xlNmjQCwHoNB+dzNyVgqh9RwdUdmcNyBP0jaB2FlvUlBa5ZIppKGmaZGZ0crlo2ZSpZT/hJBIyMdidZW1IkDdTn6/Y0UebFtPZM/ib513RbI46TfNRtDaFFdamknC1EkCS3h6eKXufcwxYKcBux7410auIccE2kfLncR65WSqaYDKrDAMA63HmMx0uTou+R1EqSOlNW1ED+WY5+gsszuCpXoDdiMdY+XcYPY65cg3IutT6APmaCJt07zHwUCvGl4ZfDf4wdnwcc+IDiGXfNPaKeWG3VU1HJHU2uWdO0tLXRftICFTzDhgpYRh1Zex6/B+P47BO8TDExuCRlIHUGQegtI2Wyt7LYXGMPvWV2cyCPOI/pNiCTA6QOq8Ua+2+Ov7I6n3Hvaeq394tvABU0JWriu1xoU33x5RlU/bU9VIGjqpoUCxggyKqR5EdLkkesdQ4dxUto0AKOIP4ebI+9wIuJNyQJ7uXBrVuJcKOeu/3nDU97F7YFswN3MHQuAN9tWWxuTPDP9rDW8hNumW98uimpKam2xt9aiC23jY1lkSOR7rLUxoRT3GkrVSJpYinmpCz9LpUkScupUxXBSJGXNmLy6XMdAIDdOYOEntygwRb1GEPD+P4YMpwWtDSMpioHuIzOAzS0jytBJGuUHVaBwr4h95fZ1VuwfC7z1yZdN2eFiybniit3K2z4pqG0VdZVVLPUW7db1AdqIpFLJLDLA/lsZDLlwwC9LEYSjxMO4jw+nmMf7b7EAA8zA088mB1GkSSVwXtxfCgMFxR2TOSBVs83IGV8/7Zi5kw6B5QIXvZxD/YWlj3jyDXeHXdlq2fu02+ntcD0tM9e9t8mVoaqqhM5qEmq5qysl6GzKizU2fecqnk+IGowNwxgubMgEWNhlmA3lAEwYknWCV6Sn4mInE0cTYEiTOV0EmW8vlFgDaYJgQFg7htzZHH2xt38c7UG9LNvCslpL/typ3DDNLLS3eNpaiihjdVkWFYnp4VCsVXyXky6lnzVRrPDwQ0Bgs6IuCBmuNZHTsNl1cfSrYwtrVnBxOYW8ov0MazfcuGhWGufjQ4q3HZdo7P29su6795S3HaPvC328RyPbbfSTQTVNOaquC1CR07rSVqAKrSOaaT3OrGa8PhKwLgIDW+YnsRo2QSRIttIkhIMC11RrxVhtoA8zjBBiAMpMeYkDUCYhR1q/D9c62z1vJ1qiqt9V1wFe9+4taihr7JuaylpIaqCGKNWla5Q07TNAZpCxVnpwAs0Yj6WDxtNxFEy18Ah4JBadRvlAJiYJvBmxnR7R0i1zqoANKzXTu0gXMwXWAjKIO4sCPhP8X/AAjbPD14huWuItr3Oe9bLoK4Ntu4moSd66z1MCzUkruqqGbyplVvdVg6MGVGDKv3fg3EzisOzEugOMyBoHAwRfv69iRdfkf2v4EcBj6lCnOQwWzu1wkfT+6+/wD8FPKV95W8NXAe8LJJY7k104t2+yV1Jdgv3bXU8UULwIGIPnRrGgDHK+bUzKx6V6V/PvtHSYzGVwTBzmZBBjeOgOnoJBuv1V7LUmVOG4d8HKWg6A5pG5A0mZ3gARIlTD2Hz/tqXZt2a1Wi/wDJOyKK61Vgq6ymtwjKLA/kTRzQORJMOrzeqcArIeor1ggnnNq1GiCIMAwTeDpYTFogGCrOIezgr1M3iBrjNpJGYXMGIsREbfBfnffapb3rd++PTxL3Kqq4rg9svce2qWoWneB6mkoKWKkgeVW7mURQRoz9g5UsAAwGv0D7G83C6VQ2zS70zEkj9Rvdfmv/AFNHh8Yq4fU0w1vqcoJJi2pOluib/Zcbdod0eOngm31lPV1MMFdV3BZ4YaaR6Fqeklm9rC1YaD9iI2mBlHSpQMSCoOtvtXjPd+G1qxMAC8HLYkAgEdRbrdZP9N8C3EcZpUnND7kgOEiQDlkakB0H4L1j8UPizrNg8ec7ci2it39t/g7kXetfuDiuSlraNqu77iooKemraq7U7Jg0VasNNVCWBmhjemTpUSTqyfO8Dwh2LqUcPVg12NGYHMMjHuJGUz5hMGbmYENa6fvPGOM/wpmIxBbloPdDSAHCpUYLiDEU3ESDrDS4k5mg7f4SLDR+Byg2Fe+Um3bX7t5LgaXdxqWjqp79cZJfaovZYVKSx08Sw1PmMxcVEsQIwFCuvtJivfXOwmFgNpABo2AHKS6ZGpGWPKLmTpo9h+FnhmHGPxpLq1dxL3AXlwzBogSDlBzzHRvVe2m1tg2rb216S0cdjc9Rue13GS/XG3Um35ztzbtxw0kMcSM1MKg1IkQSrJ1mPMUixRIsUB8ZVr03DO/QAgOLmS7Y5fNAG8Ak3lxcSR7zC16/iGIa2oAQDnzQTJkwNLhoJaJ7ST2Tw5WG23zk/wARHPNFv+Lb0FfLt7a0VLULJPVT1VHQLUS1M0kpjJZnubQ9Cwr7kA6QofpD499NuEp0oh5c42iIkNFuYk8skkm5griPq1vevd3087GtiSeuZxAi0DNA9CSTErm/2nX2mNn8H1g2/wCHbhyz3bnLxt7tt8NJtLaFut5qPutZlMSVddHF+0JYh3iphh5SvUeiJWfW/gHs1W4rVcxpy0m+dxgADcCbTGpNmgybw0+M4x7Q0OGM98qtkuJyNBJc8g69mA2LhcnkZzSW8C+yz+xrt/BsNN4kvGTDbOT/ABg1simneqqku1DtCnWKFIBD1II3uCpH5TzqXSJVVICAC59V7Te2NPIcDws5aX4nAQXEmSATcMJMnQv1NrLyXs/7P13YhvFOLAuri4BPliwkDQgCwmG+pJP0FpT3iCPy4Ki2MCwBx1xjo9Oy+9ggemDgfL4a+dzrey9v/LcQXg/Q/t+/dVV26ruscMN1q4RTK0cjQ0+QkrL3w/VklCT6dvwr699QnrdRjm0zmpAz1P8Ab7utJqLE1p8i02hI6GbyEel8rKpCsRQCBMEHAKp0gYIDduyaUy67vj3XTpYhpaS7QSLgHXc/Mz1jutysdSkvmVEddXzxMSER5GMcf0UP72fXOf550Q8TA+/gufiqJENLQD6CfjFlsXndySSSe5+unzzqsXhLB1PXTTpX1NcKmGN1kWGZB0o2fdKY7lvQDOfpj10jqhaCQbrU2mHjI1sTuP17dY+q0TjygRNlWzb16tRr456SWW4NWRRlJTNK8ghcDImAWTp6u69Kr8TgaKtWYi0QPkBdPVwbqVRx8TMQ4xE9de3p67LK0+16HbUE39mWuMMeI0ipDUGWGnVBgCNGOVXHSpGTlQB8NZapn1WtmIdVIFeCOuh+Y339b7qMe5OH9tVV02LRb0tFsq7xcbe+2JJ6umgkpbrNSwippJpkwQ0wjhljR2HWrxnpHSFz0/eKrnPqsfDgJsSIvBjoDMm+iubiKVPNTZTLqZcCbTANjJPS0et91hrNYq/bG3aCuqN2QbR5GoEgspqaK0l1kq1l7J5LALUU7KGcwyhxGZA8brhW1S/FOe6IJaTvtOpm5HY/BdZ+CpPORjRldexAsBpaLxblgm4hSGpd3V1to1qNyNcrldqbERgZUhFW/oKimRQnmwsyt2I8xB2KkgZyVHxGXUm0/dlzaXDvEcabIbuSLwOhMmCLaGD1XUrfeFr6aOYPC7svViNsgfD1+Pof+u+iHLmV8Hkdl/NPhVM3f+R1MxSeAkGoft3XH56hfdOKISDUP69SAfroZ0fBCQag/wDGMamaU4pKxn/5z+7QzFEUeyGZj69bfv0A9MKSQZfTJbH56mZMKSGZl+mNTMm8NJ89Rnso0cybwkj2gdu/8NKSm8FDNSTnsdTMmFFJ9oYfIfrqZ03gyhmoJPqM6GdWCikmoPzOdTOiKKE1QPnnRzqxtFCM/wBe2hnVgopBqBnGfpoymFFDapGSMnQzEJhRKQaj0Oc6mZOKKE1Sc5ycaGYJm0UJqggHv20c3RWCigtU/MgHQLk4ooTVIHxxqBxVgooDVQ+B9NEm6fwUJqn66GZEUEBqrtgnUzKGim7VXb1JGmlN4CA1SM9iDoF26IoTdBapx3IOPqNFz4TCimcl0pFLKaqmDAZI8wZH5jOpn+SIoGYTF71RDsKgSHPois/8gdO0OlH3eNUF7oPRaetf8oyP540JITGgIXfzVZ/xa4Tnrxow/ZV7Vn4nSgqeAle1f8w0SUDQSvalye41M5Q8BX9pAzkjTNd0Smgle05xg9vz0Q5DwEtar5EZ02dKaCuKoEnBA1GvKU0ET2nAwD30S5A0ECoMNVC8EwZ4mGCAxU/oR3GlJnVMxjmnM3Va8bK8kBgrb1dakAk9aFY5CSQc9YGc9lwexzk/HQhp6/NbfeYMsYB8z9NPouQchXKSz277m21ufe68gzMUt9PDUCp6ZnjdlaoVgEWIrHIzO7IBhyCWCqzBgecsR1Mm31+kH0XV4Zhb+JUa00rTI1voN5np2BtJDbYe3r/xdfEvG8tz7i5Iue5IaKhqrtMIY1t9WnmeTRwQKqeVRN5hCAZPm5aUs83UN9Ws00wykIDdpubXceptpoBYWXGxeWs8y0MjMRrEE36839ROoAiAIUiaevSpgiqImPQ6hhn5ayhx3WR2HgkFYnce67dtWzXO+3Yymgo6aarm6VJykcbOwyB2JCkD6kaBcZtqVZRwD6pyU9fgombDXdVm2ns/mi02GgvvK1+pI6zdtFDUdKVUUpE1QJpeklJKNsRwoVJCoafChnkTpYnENl1DMMjLD4drTmNz3M6ATvfg6dV0XaBpMzOjWidome8u1IClHNu2y3uxUNdZq5btBXIslFJBE0mMgsJGUYKBekk9RXBBUkE65xfIIB+x9Flw+Ae2p/MGWNZt8Pj2B6xZaG68svS0NNBduPNn2MmVq4yJNca2YOxKiN3MdPGSpBPUsuD7oDAAm6iaLW/zHEnaIAn1Mn5AE6yrcQ1lSrNNpJkR0gdhDvQ5hGpkqLG+avbty33s3i2Obe1Xc91Q10FZuirJr79tyg9mmVzFKYCtpSZxJGJgEVfKeNV8wgJuw1V4a6o1sU2gSAYBM2DjOZ3UgGTPSSvQVuGNFEPrFpc10taG8pJvIFw4tERmGUzJJkZvPHxc/Y3eE/di2nkXwwb6vfg25icQ2eK7bQrjHT3CnkgWmippLdFLH5jMWh65YmR5Ecl+vqBHosD7emq33fiNMYimTMO1mZkEgiBsDYdQvDO9g6orHF8PecLWY2MzAQIEyXaCTpOsjchQ5sXi63D4X+LaTwb/AGtPhKsVD4XtzUFHaByVsWwF9vbjoREIad6+njVGhrQabzfOj6KpWj6hAekMey7gdfEVBxLg1cvc0k5CQHt6joWibjQ6ZjK8/W4uMK1/DvaCiA6MviAucwnq43cCdI0Bgw3Vdq8IPjWp/D1y3S/Z/wB051tXiS4Vulle/eHXkunuC1pu1CgaSLbV5lVSz1cDwmKMhRJGURXUCSJV5PHOGMxVA8RwzfDqNMVWG2U7uAP4T37wdV1PZfiDsPi6fD8aM1OoJpumS5otAdMFwHTzNgG+vrFujxAbP465QsN95Krbtsyz3iFbb5dxmejtVLcaSB6jy4mMaCaV0mnJYM0Z8hWByrAeN93q+ETTZnOpgZjGmgmACImJvG6+n0MMK7BRpujoSIJzHq7sJjWAbRdQss9Vsrjvna8W7YlHsravIN637T8iWKgpkRDSJe9rVcRo6kE9Uze12+SToVcx+cQip0t1d7HYmpWwzPEJMNcwkCRIe1xy22a65JvludI53C+FNp4lzQCWkguvBIaHNE3gNJBj/u3mV6EUu5ts2e9zbIuNPb9pJS0sFZC1loKmjlkDQhAz1ULYhaWQhSGyXB9erufP1K9SrNSpzHSTB9BpeNbWAXXfwseEDTM5pkEiPNJMW020vbRfI/8Ab8eDG38Lbi4M8Rm29xVV7t27oKmw32CSsimWmvMCe1PLTBI0KwymapZlbq6ZAScGQg/Yf9NuNU6wqYRgjLzDUkt8t53FvsL4F/rLwp5qMx5kXylobAEy5sETre1haQIKm39kt4kOU7n4AOL9l7S2ttHd1q2xuC/cc3KKp3YlurzT17rc4mgiZB5xiiWUR04fqlLHo6WAzxfbnCsbj3OqODW1A1wBaTOSx06m3QTdet/0kr0XcMpmmHOrUnRaLAuMG5ME5gZy/h3C9kuF9uVNLTeKPluzwbPpONN73C2X/bt8daYTXeBKQR1NHcT5UDxRQ1EbxRQTSPPGpAPQeoDwvFKmTDUaNYkFhdLekkEHUglwuYAH6/ScI8VceGsAeQAJBM6G9hMgWJuDf0XxH/a6bclsnjw5pqGg29TrdorZe1W1xutK6z0UeGTrd+o4jAZlYqzhyuB2H27/AE9rh3CqYaSYLhcAaG+m1zG8ar82/wCtlFzOOPc4Rnaw3JJ0i56223UTvDVvWxcd703JvPcZ82kptsXCmjiVlzMaryqOVEVuzSiCqqXQf8cafLI7/GqRfSFMCZe35A5vhMATsCV472Gx7cHjnYqo6A1j49SMvx1mN4C9YeKtx3zxeeJifmbmfizcVssN8ENg4Vor3Zki2jtLbcU7+Y8fnI0NXUw0kAipqYq6T1E7yydaQquvI18OeGYJ1IPmoTmrPDjnLiJAG7cxPmMZKYMDM5fWuDPfxzijaop/yGAswzHt/lwLFzzIaSAJc3V78rZDWyPRHaXh33JtnkzamxuSdtV6ccw2iqqNvXqSqS8bki2nGzPAtopKiniKSUM0alg0CCSGoowIWzJLryNTiLDTe6m4F5jM0WGf/m4OdGYWEvmQ6SIyr6pgeHOpnwKjZFLNke8yA3SGyAOU6wxwLS3zG69J+KNhcS8c1Vj4msVma+1MqVcMcd/sM0TXQGoinqaCKcqpmm9nw6zROxaMqJARkjy+PxlSpOJAhojQggROvQB1oNunf1eFY4Usr6kkzzSWuuIDok3Nz3iRFgoTcu/a07H8LPHXN22dk0sG8vFTV8objgsOxJIprjDavapI3oqmpkyYmjjSeJVip8NLLH5QOFLjv4D2UxPEa2HZSJFNzBmfEbmQJu5xgwSIAOY2gL5/7Qe1+B4TRr++AOrU3BrWA8zzlETl5msuMxJ6tZzSpF/ZUeDuu4Ou24fF54o6TcnNPjb33TPdbnc54Fq5doUlRgPRRo7L/tDBQsk0IZPLRYIcRoxfd7Te0dEUxwfhYAwzYBII5zr35Qb7FzjmdtHm+A+x+KrPdxvjLi3EumGlrgGACwbAIBi2W2UWEmZ97Nr7hoL3LPXUsdTa4lYE008RilLBVwzRMAVUdYAHfJ7+76HwpMGHa37/ABtb5L1eKwrm02g3kC/Y3j13MgRpdb/7T6Au2R9NEO6LliggzVyQxPK8pVVGWJIAA/PULgE7cKSQAFjLmlFUyW6orJnVaeV5FzKVQkxspDYOCMEnB+IGp4gaCSraNN4BFPePzV6VbfVyx3f2CFashjHK0YEnQwHfP1x+Z7aOchNVpvaPCzW6TZZP2hdEEhU+CmFTTUtYZTP5jFonhBD48sOvSxX5HHx/d8dAkXTtDmjl2v8AK4nqg2asT7so4QoSSGJYZEIAKMgC4P7tQ1STPVPXwsPPQ3+ayJqgc9xoZlWKC55yXBHedu01pFY9HXS3KjlpZE7lZIplmJwO/SEikLf8nV88aBJJBG37b/P5ro8Mp5apdtBn0NvmTEd1j4KykvkPmVVE9ku09M8E6kExibp7Dr+OQW6WBzgDB+GlDrET0Wo4V1My05g0yOsb+nfbYpxcts3HcNJt43yrohcqHrlimh6i8M7R9HmrIcN8wVXpyDnqyBiw2BAPb7+/gq6danTe51NuvWNJmI0+cotLPTW+mFsV7rDeWYCWCmygdjj9oGwQEx36wc/P3tKXAmI+/p8k5pOqHxCBl6m/w9e2nwW8rMsaqiDpQdgAfQaYuXM8Im6o1JxjP8dAulEUEg1P1GpmTigrGpxkgrjQlMKKGarPbqzqZuib3dJapz8e+hnsiKCQaoZ9Sf10AUwoJBqR8Pz1A5P4KQanvqZkfBSTUn56kphRQzUevfQzJ/BSDUj4tjQDk4oIRqB8xoymFApBqOxJI1A7omFBCNQDjv31JOysFBIapHzJ1JunFBCNT39RnQzJhRSGqs9sgaJcnFBDNST8SdDMnFFBerVO7uqD6nGh4gCsFCdEwe60a+tXTgf5xqEq1mGPRNnvFJ36ZGlP/wCXGzfyGjdEYc7oRufUMpT1jD6x4/njRMjVOKKbvcKk56KJz/nlVf5Z1LlHwghmrrSuTHSRH6yM38gNEnoVPCEaJu0tcxyaqmRfj0wk/wAS2jIGqbwx0QHM5/FXT4/5VQf01AUwZ0CbmNMgtUVsx+TTNj9wwNTNspkOqbvFRsQXgic/N/e/nnVjXRonDCRdUpgiJMMNPESO5RAuR+g0DUdFylFASkvVH/j7fHTSj4aatUYxg/w1A66bwt1281ykd5jn89edLtl5oYYzorCuXI/bAn/NoyicMeiX7aCP7xj+uokOGPRX9rP/ABvqZgh7v1CX7X/zuf11AUpwyuKv5s/79PKU4dEFYMdnY/roylOG7JYqxj8Tfq2oSp4CUKtfQsf/AIjokJDh+yX7Whz7zH9ToFyX3ZWauhUFpZPLjHdmZuyj4k6IKIwzjoLrlltu0CSRVcdivLV01TJWsi0kis9Q4KrJMzADCowRQThV+OQACS/QjT0gf5Oq7NXAgiC8QABqNBsI6m56n1ksrsb5u6seyNT09FY7dUUdZXxPK7y1MqOtRHTxsmB0hkikJznCpH/jYq1J+UF03uBa3c/Xfe+10OGpUodqXAwdI/DMEa6j5mNF0ex1UiUccNTcKa5SP1TRPFGUBjJyAASc4zjP8B6aDXAaLBi6MvJDYA19Vx3lXf8Atu6yWfi2G4U9Sb1WGC7VCTskNtt1M0U9b5s6gosjRmOJYiyljP3IA76sI/K7xSLNvfcmzYnWTvcW6q5vBsSaZq05Dh5epJsLXMakmNrdRsm1qK03O3UVfdduWGnvKUSnDIrFQzFy3Vj3mUeWGOD7yn5g6z1XwCAfsBbMU2rSflY85S4m3y+t/gmfG9fTS8f7QWktUVOaq3rV11uMarJFJIWkYnp6ek9XWSMY7nAHoZWJBLZmP2Ux2ELa9R1xDjBv1037LVrRT8h0BmkqK6grdqVKLL7XcaUIbCqjBPSG/bABgwlAjI6D1YA6tWCmwCSfWIM+nSd5n0Oi14yrSL4Df5gMQD5pvex+V59Suk01Lt3a1RFe3oY5LnLTikmqPID1NVCC7xRDpH4QQxVAOletsYLEmOxLv9vYXjv/AI1PYbQuW7C1MS4xr8gNJ76nrJK5nuvaW2bztXdtrulhiuVlraWrbFHHJFURJIvVinkRhIwBGUz0jq6Qv4VXVba7mu69iB+Ufn3XfoF4ewteWkQDf4X6HrEkD5pd3sWx7jtOzWzcNi2xvLalfSDbtbRXOm+8Ka6W3sYI54qkssj/ALQDLZYl8DOca0UsfUpPFSg4tfOotffTYf3XJrcHGLD6FcS2A6/WLmAN4k2Xyi/aY/YzbS2Pc77zV4BU35tu+01U90k42SnmMlMI/feexTDM8ToY/NEM/YqP2UgISI/XPZr/AFGbiSMPxFoBNs9oP/eNPiPiNSvjntN/o3iqFD33hDvJzZQTM2uw/wBWlp10jRb34VPtAb14wuK7lyZ4gfETxhwbv7iKSHcE73Jak0l3kWAwLcqi3w+WxjczVEJihZ2NTOWcY8qN/Pcb9mmcOxHhUmvqCvLRlALhN8oMwXWFyByjqSR7z2G9tf4tw54c1jKmHAL5dAIb+JxPkp7G5IMNFgAcTw79qHUbp+0R4P5c8SnFG59l7Fo9tV2zbJdJdvSwytea9UenmqIYlYiXpatjiwgmWOtJMSZkY9F/stXw/C6zKNTxHkiRmBhoPMAdP6cwFgWxJsF57Fe1OCxfF8PR8M0aRuHOBAe4+QkG+Wxyl3mDpyjb6Or/ALq2Jubbts5xoqWC1bPt9NUTQbkqBJ7JRTRh1hmYA9DxwMXzI6qFlZwW6YiG+aNpVGjKG8zhEADNfpuJ0HUc0XC+w0HQ52HfVBuJE6jUzsJ3ubACASSPLf7Tr7OnaviD8IG9eVeN6mYcvUNsTdVDPHd53g3YsKmZoTT+YYCGElYYWVFw8nw6iNer9lPaNmCxjadXKKZJGgzCbXIvaBMk2Xi/bn2fqcWwlWhSL3VQAQA45JbcDKZFxuIMxchfNX9jdzFszjLxwcT0/Idwttv2dfKyCkSqrXVaemuMciVFE7F+0YeaGOIvlTiQL1YYg/WvbXCVTgKj6I52T8jIPrE5o6j4j8//AOlfF8nERgqziGVoFj+KZba9zdt9A4r7AeTPE7tLjrnnb3DNniblzeXJW3L3WXKOgt6TUdFWUJppYbtNTd4xB5dTLDKw6mlMEAdwUB18PwOE95wtSq05RSLeYm8OkEAwJMjlFok9V+pcXTbhcXQZ5M+YNYJJOUSQSDI1AmIE6L42vtXrttit8ZO6rdtinucFNa7JaqCs9ttfsE0s/lNK0jR9TF1YTqVkP40MZxr7D/p8x7cBNS0vdAkGAIG2hkXHWZX5w/12x1OpxhgZctptDtdZcRqBNiNLRoSo1eEbh2484c2WXb1Jtpt32i2wNfa+2sshjukEEkSimlaN0aOOeWWGFnDAqJTjJIB9TxbiHu1A1ZDTYAmNToYOsXMdukr557G8CPE+JMwrWy27jciWtEm4Bj1iBqSF9fNn4qtvHtjq9ueIGybe2Jxfdlmq6KjsqzVvHO3KQRdRkpa0oZ7dXxRgIp8mKCDzFliaJ165fhL8a2q41sM81KgF3wBUd1BYPM02kyS4cpkco/Z9HCNohuFxFHwqbdKZeS1twAcxgCDmcJyjMBlBu5avx3yxw5eand9k3hZbBvm+bQuKyW/fN1o66KmulIlL0pcJaRabHkNR1BjmSZo4JnErxd5gsYdhcRTANNpYKgkMABIM6EF1pcBlIBcBAMRJ6mIea38p7gXUyJJJbILZBzAdzmg5XdSIXM/EV9ofxnwhRCy7ssdk5SraqneHbPFm3vPa3X+4sTHHV1MXlJJHbuuR4YHheT2h4HkWNmMXl7uEezuKxtb/AKUHOYBe4DlFrRJBeQJykAsBFxJK837T+1mB4Xhs2PcG3OVtN0vcb6OLZa0OsXEQSS2+XK7N/Zy/ZxXvbnJ7eNPxvwU0fiDutOm5tr2OOv8AYU2AgZUieoVkdDWeVJTJBCWPkoTkySiUx9n2o9qsPh8OeE8NII0c65zEzIaQbgmczhY6DlifC+yfsXjOKYv/ANQ8XZ/Me4ZGZZAAEAuFoLQIuCbZncxEerG+7ZVbDdOU+MuXa2zR2tZfOopEjuFtrbTgxNiCPoD9EnU8bkgdUjYx2182ZWY4+HUaZda0yDNozTrYaE/VfcqWFfWDadVvKL3tfzXIvpqB8VL/AI+uN/8AuSyVt9SM7kryK63oytCkCssKdMqYzEcf3mFILuVXBwAXsYyoWAyBqdd/sDruvO42m14cW+UWPUiCRrvvE23ld7o7tTT0oq1qo54Sx98Ht64wPy9NAPkSvOVMG5rssQVpdbvm20lY8NWxqFqKmS1wxCMlampUEtEp9CehGYkkKAGyex1WysToNf039Pu5XSZwhxaMtiAHegOn1sBrMLK2mOaGSChutXDcauINUBVz00zFz0jucswBx1H4KcAA41YxwmBt9/e6z12Zmmo0ZQbetvoO3feFtftQx650wMLCKKSapfn21JKIoKxqgO2RnTZkTQQfOAkaUN0lvxD/AIj8/wA9KSiKVoSjVAfHvozdHwCtA3HNdvvSybhoZFekoZ5qeSmZ8JMsqBDK2FJ9xgpGO+A3r1ajHxPf95/T8l0MNg6bmmk4cxgzHS8Ceo+7LYZKK010TyU48suOlZoXKsvfPYj0HocemlAHRVtfVaRm22Ky4qQqhQ3Ydu5zqGN1QKCY1sNNcEjSpVm6G6kZXKsh+hBz+nofiNGeqsp0y0y3dEp2FNBHAJp5Qv8Ajkfqdvjkn4nUtsi+kXGYRfa+w97I0UPdkg1XfsdLmTDDoftXUDhtSU/u/VJNYR6N20JR92QzWAZ75/XQJEJxh0NqzB9RnUB6Jhhkn2wkZBJGl0Kf3fZDNaPiyqNQvCcYZNmu1MvZ6qnU/LzBnUlOMI7ohNeaM+lTGx/5ct/LUMphg3dEBrzFnCpVSH4dMLH+mjBmyf3TqkfersPdpavuP8Shf5nUAhM3ChIa5VB7rSH/AL0qj+WdCCU4wo+whe31zHLRUcY/94zH+Q0wgJxhkM1VcxfNRSxjPbEZOP3toeqsbhh0Q/NqSPfrnJ/5Y1X+h0XFM3D9kJ2LDDVla2fgJOkfwA1BG6YYdBApgckSyf55Xb+Z0YEQE4oQUPFGDn2am/VAf56AcU3gndE9qjjGEVEH0GNQuJ1QGHHRCauJPd8/rqT0T+AgmtLfhJYakJhSEoEleqAl26QPn21M19Uww5Kx73yjOR7bSlvkJFJ/cNM0HUJvdzMQmz3umGelppz8kiZv5DUyklDwOqH97FwStLWf99Qv8zokEaotoCU2e41eT5dLGPq8wH8gdQjumNEaITVtay/ipI3+PZmA/lowA6yLaI3CCampyS9YD29FjAH7znRm0IeF0CC03UCWqak/k/T/ACA1Oybw+ibM9Pggr1jPfqct/M6YOuiGG8LtpuPb1OuC4LjDBpP3gCPUHQATe5lV7dH8VH07aJQ9zKWtbH2OBoQlOEKr22M+mP36MWhA4QpQrVGAC36MdGBCnuqIKxf/AGkn/wAWhKrOG7K/t2B2kkx+emlD3XeEoV5+Er/w0EDhB0VGvbA/asR9QNMO6AwY2CDUVuYzJI/mIgL9PT2Yj+f+uoAZsnZhLwBErA1W5KutK0tpgr3qDIUNQUKR065UM5LdmYBiQmDkr8B30W0ydbfeg/fRXt4c1gzPg9uvy09eidU9BRUdrktdH/ssTuZZHABeWQt1M7nGGZmyT6euBgYAd7gTf7+/8pMjvE8Q3P3YdOy0W7UzrUXCtu9/pYKVQS3kSMkjOF7dMC5BLZIxk5wvY+mg2i0nqT9/dl1cO4gNZTZ89Pmenw3Wp2rbcc+6RQ1lugraemthhq/bXSR6hzJDL/dheiMCRQBEpVB0kkHJzqmBIMXtHx339fSE9ap/LzzdxtFhEEdZNtSQSZ7Lqj1y23biLXeXDXPEkb9cglkMhURjv2y/cZI+OT6az1GA8o36LnU8MX1gWzAPpaZ+/ktWt9gsNLtGmW71NfVPTJJDUVktX+0g/aEP+0j6MBe4X4KM4+szNAhot8/ufqtbqlZ+IJZuZAj5W+yd05oYd1muMtXVUu4NoxyQ+y2+sRYpyqqQ8plxh1Oe0cgOR3LKcDVws3o6/wDj177aLHiqFKIpiHEXIk/L9SN+q5htfdkF22FdUpLbuex7vpUC3O23JY1rYZEwUR+mRyqtEI+h0JQKwYA47DHUgx2W0a2Nj3HaZnfULr4TD56rXEy3QbEa6gWDpkxutbr+Ttw3yY1dpt24aq34jgp7nb1hneoiELM0kkSv0xxpMAnmMQjFfdYHPSr8I4DO4gDoTEbCZETvAk9lqw+Ap0m+G4X+MT0B1mNRFpXDOP7xyBu3aW5bbyLdXskdr3BWQ1VxtVwWlD1TCGVZqeSSPEUZkRJFhZSVVnjZn6jq84ai3KWy61gZ76xeY1NhNxotlSm4P5Whr3Bo6iB0uLGYvJ6wq5n8QW1vDJx1uDdvIu19w0W1UanpYKuks8lXFVOyB5Kgy08krO8S9UjAEv0JIwVwrY0YbhmIxdVtLDw9xmwItG0QI01gDS4XKxeMwuGYcTiKmQMu4mdHOgfAk7X6DQL5Y/GBtit3RyFxb9or4TeI9n7Fv8v3rv297PpYUrXpYbNWUcrXu6WtoxT0wlW4UEj0i+Z1oUqCVZmx9r4Ji3tou4bjqvM2GhwkQXgtDWv1cRDgHAACC26/MHt77PMdXHG+BUyWOkua7VwbDnOcwGQNCWuOYy10CFybw/csbs8f/ij8MPAvKlPTQceS73rN2Xe22WBvOus0aVFdNE6x9LSO5E8UUhJlSKdwzuUU6vq8Lp8Jw1bGU5c5lMNaDsOVo7ASAXDSRYCVnpe1+I9qOIUOG1A2kx9Q1HEO3ALoJ1gSQwnreYBH2Y1+4Noy7IpaPZVyt+06C7U8tLTXG2TLFSU8fX01EciuPKUxqZyyPGGVozkD3mPwEh7nkVJOhOs/vew6X9F+uqPDhnz5ZyyMsTc6R1v36rkK7Nu0e7/7NcZ3il4Z5NqoRcBZqm0wCy3+lRe1a9KySwO6LFmUUrQspkVGLghx03ViQTXGYaZgeYdRIuZJtnB3iAFifg6FGmfCcRcSASROmUAkQI/pIO5IJAPxAePHw98ieGDxR782xvlNlU12uFU+7rTXbRWSntMlLVTPNG1vjYK8AifqTyz3iZAASOlj+hPZnidHF4NjqLi4N5Tm80gCc33foNF+G/8AUr2cxPDOKvFZgp5yXsDZiCTpN7EXuYO5XodsH7VG6pf+AfEXU7Q2pcuUthbXXbO70uV+prXHvapnqqyWqrGVllqa2SopYaUM/SVgqMdmLxDXk63smWsrYdrsrKhlkNc4tAaAIAhrYc4mSZcBaLkfSuF/6lNrU6WNrSatIEPOZjBzEaFxJILGGzGwHHm2B8Y+WOUd381cocg8vb9rprxvvdF4q75dJzheueaQuQoHYKMhFA7BVHy17rh/D6WDoMw1EQ1gAv23Pcm57r4d7RcbqcRxtTGvEOeZAGjWiwaOzWgAeklejf2aPh0oubX3Tehsaq3tNb75QS1QFa1KKOhhxI0EDxTiX2iqeYRkeU48mnn6OpmYLwfanHuotbli4OoDpJsLEEQ0AuNxJLQba/Wf9GPZ2ljPFr1Q6xaJDi0Na27jLXNJLpazSAC4gzC+iDeXhy25feN6+88L2CzeHa+2mxTnb1x23cQKXc8roYEtlXSe0NSV1O8RMbhYOstU4UqygD5IeJVXPa3GAVSSJBbDgdcwcG5mkWi4FidDK/UR9lqbWn3Fz6ZDbS4uZAnzNcYIO8kwIIOYQvN2yfaGL4W/Chujj3nmy7uvvi7iq622UlFV1irXR1cMSwQz11Ug64qCnYOUjjZ2qJaciUhuoD0GL9mHcQxoZgSPdyAc1yBOsA6vI00DAQRsV86p+39Pg3C/H4xPvg5chjM6LjSwZYAvdJMOaBJyrlHgb8KV62VyhwB4hOZ7lvW7cu1ss+7aSjiroo6o0CQxRU8lJJ0SvJWiWsikIC9KYjhTMjlk7ntFx2k2jWwODaMjRkJv5naiGwQ2AQSTLjP4RfgewX+neJxFehxvjTi7EVCXBrgIaxu5GhPNIaCAwXIzFe/1/wB1703tT8IXKxWe38xXa00tEbzXPUlJbZTxoxn+6an2dFkrGeNOikmbzkwWHQzKuvmVOnTaXy7w23iZudgbyBe5bbQdSPvVImjTzUm5g8zAgQ02Lujo7gTfYQezWjesm/6DavHu7Kg2G8tNJdrNa6ikhoa680SFXoHWPqfojSoemaSMhECRftP7whs4oGnUzM5iB1kB2hJIGoExrc8ugV9SmAHVKPKDrrIaPNa0zpNzfbbI7B8Qu06nd+4bDuRt0WrkSS6x2iC1qHcRh4ozM0UYXzFpTMJV82RQesYHSAo1VVwDiM1JuYEEz22nYWiADebztY/COfTD55REyBM7ettdhB9TKqg5Tg2nx/uW8VdPW1dutNSacu9UjtWVLTxoIoyC3SqNIIiWwQyN2PbNdGg52RrYlxgfPU/nbZef4hw0PxEnUibDQQfSSdel1heR5toWCggr99XSlu24zdIVpaKCVEjo6qWpQRiixiVIhIQHcHqcM7SDpARbaQ8QinQbM/UXJnYCJIG3c3U4fQqGavlbGpmbD8R0JPcRsLTPQdu71ghutXbrY123JMWTqlMHSIV8sgJ1tjI6o/XLMe+e4Oq2sJm0ev399YVeI4bnphzyG/Gd9fl6BdZp7x54diksSg9IDrhjj44+A+WdSJuuI7AwYR/vFT6M37tAaoDCFV94YP8A6w/poxuiMGkm5YGSHB/LQlH3NBa7Rr+J+n8yBqSnGBJWOku1F0ezCoZet+zJKoMZJz1Zz2AOlDQVd7k8HNGnb4LDbZ3pb73Zrdc6asq6qCeMvG8tOUZgGK91BODlSfXV9Sg5pLSOn1EoHAkyQ2Oyzxv1OBkGdu3wib/TVQJ2CP8AD3fZSPvxTkrT1bf9zH8zowUx4eeyT98ys5UUVSoxnqZkA/L1z/DTZSRKAwQmJVfelSR2plB+HVMP6A6UhOcE3r9EFrjXMcqtGg+rsf6agZ1T+5tCsa+rwczUqH6IT/XRI6IjCCdENqyqOB7bgf8ALEO/7ydKKcapxhB0QjUy/wCKtqXz/lH8hqZNwnGE7JDTKezVFWRnP96R/LGly7KwYbsgsaRjlkZz/wA0jH+Z00wj7sdFfzKT/wBhTn81Ggm93KUKyJPwrGv5KNG6gwnVWNx6e3X7ulI3Te6BINxXuSw1Mqf3SyGbgM9jkaIaiMMhvcAO7Ej66AAGqcYbomM18pKdWeespYUUZJeRRgfqdECdE/ux6JuNxULhvLq4pMdj0Et/LOmLD0TDDXQ5L9GM9CVs3+WFv5kY0PDJCgw1kA3uVi3TRVij4dZRc/8A6x0Sy0mERQuhPdq05CU0K9v8c/8AHAU6kTaUfACCLnXkHzJKCNvgFDt/MjULB1RbR6hN5KyrfPVchEP+SBf/AKs6gYAev36JvA2ASDUsAA9fWN+TKuf3AajgDeFBSMQmztRv3mM85x/jmcj92caZtjICBoE22QzPRD/1FKfllAf56YJvAJEJQrlT+7CoP+Vcfy0S611Bh0CW7RqCZJkUf8zAfz0hAhOMK5YxtyW9W6PvCkLfIOCf4aZrC7QKHDEaoL7hpv8AAaqY/JIHP9NEsJ2TNw6bff0jnK0Nfj5v0L/Ns6ZtL0SmheE3e83AswSjgVcDDSVI7n5YVT9NEsMTP5phh2oX3lcCCZJrdGPh0B2/mRolo7oih1CavV1bNhrpIo+IjhRf55OixoBmPr+0JzQsu2feWQcsB+uvPlhSe5KhcvT3tQtkKe5Ja3Ij/ED+ugWIe5pf3j/zD56bJZIcGVcXLJwG76bIh7kri4gDOdEMQOCSvvMkfi76GVQYJL+8j8G7aIYl9yV/vMdgWOpk3Q9ySvvMD499HJ1Se4lULn8m/jpQFPclb7yzjLk/rqwsATe5dlRuXf8AEf36OSEPcugWpX2vkSSeW4VEUtud4lhiRljdWGcszkEkZwcAHuB+Wo1p0F5WuhgwRDRBEydfpYfFY7aUs1Ndat7hH0XCShhYYUKsSGWVvLGfez7yser5jsMEavcLZRpP1/JDFYVroLRb+wutouVVSxPBdvZ6GS4QgpHLL6qhPvAEehIBA/d6E6TKYICqp4VxBpyYK5rPcLHW2y8TddFYq6W5xv5NSYyJPfRFkVC4XDpGSDnpOMkeumbSMgO+n+P8Le2k9jgAJEd+9p11/sm9NyrsBqS7Xam5Mgmgp/MEMUVzhSOpKnpzHGvdiXDIApOSOw76Z+HcAA5hE6Eh39gqX8LqF7G5R0Ngb9z2/sVC7xY8o1HENqsF947uu5tx87VhprLtvb9ZUQlN0QyzrJLTSrKimlgQdcy3CchaZkBHUGMEnX4XhRinmg5oawXc6/JG5gnUwMoEu0EGHDn46jUw1L3unzEnlZAGZ0RlBtqASTOVuruUEKCO64/tCbI90ptl8i8VWBIoKi42jiqs21V3SxvRZaZoae/s0ktTN1eafNZY4kZshApK66ww3CXx4niFxsagLRfT/b/CNLElx7FYMQ32gl1eh4IsD4bg7MdyHVRlBcRbkbkFpkQVjbB4895QWvaO2uLL5uPcPK1zrI7bV7YucEVvuttv8MUUNRHehIQkfXNIQlSsjo6qFVW6g4rqeyjnVXB/Kxt80ktymYLSNbXIgEbwLLfhvavCYjDNqtph1V0tLIAcHCMzXNJloGx8ptGaQugXPlXmfim51sm/9ibWm8UN0tnsFfVUUXt8PG+2JGdqutpYpU8iqqaqV5YY43cLVTLFCitDBMDZQwVIhzKDyaAILnaGo4eRgdMtEDMZHKJe6DlAy48vrig6tTHjOBy0wQRTFs9R+k5BAgG5ysYZLnKJ21OO/D7sPnXalLxDT3TdFVX7IWypYbnWrckK1dejrTmmrJlgpTGaZhJGMRujBY4nIAXqVuIYrE4d4rQw+JOYCCC1pMyGknUQfNqS6JKx4L2ewWB4hT8Aue3wnNyFxLcrntB5SWhu+YCGxADbALxdo7Pub7Nj7RvZ43/FFRttG/0d2qFtFeswFqraZiBHP5Z6gIKoq3uZ9xh0+mvo9Z7eJcLf4JDs7SLggFwPSZ1HVfk3EYZns37XMFYllJrw6RctY+eoiwJGkWt1X0b8p+PLwrVV22vcqXxVcfb/AOPqVKiC47es9K010uXmIG6l9ngWOujheAYp+mKR4ZXy7BFTXyrDezePeHVDhajah8pLXZR/5aEzqSQCBEL9cO9sOEUYLcbSc0+bnaXHawBJJiZDRJvqVg7J47/DbzVRG5XjnDbddYrZba3pq9w32Gir5JIekxyRySPTzUc4jlkKE9ZkMaLiTrYDHV9nsVhjkdTIcSLZXEb62dIJ6C0zIAXocB7W8JxdA18HimOptmYcGm0aAx8S7KNeyhP4xvCvyH4ouFdw8w3nclVed6WeCovdooqY0NRT2lZSJFttVVUjEVE9TTiHFUw/3lRB7qIXk9X7P8Zw+CxQoMcCHQ1xk3PVodcNaZEalvMdgPln+oHsTiuPcKNUyKlOXUmwJywLOLRBc8AG1muho3LvmTKvIzSsQuFwB6fpjX1u+hK/DFSmc19R9E6mUhPNBAlbAHwKL+Xz+mjlmwTGzZH33X0EfYb8pcpbBn5d2rtajv8AV7I3PW0tuq6qhiUPYa9FiX2vrYgN109XJF5eck4KjIzr5x/qHg2VRSc6MzJMExIvIAnqB8JX6i//AI5UnFuIa4SwloIyyARcOJiwgk66gWXpv9oJ9pBtDw40lksG7thT33f8bTVO2NoNOlMsVOIx5FfcJ6eoaWkeGZpBFH0A4jjdCSpMfh+AezeIxtQii8To53miTdoEcznDW+5Bib/avbv234d7O4cHEAuLrsaLF5bG5HKwRdxkk6A3jxA408KXjc8TW96vxkckbIulqorjLHcbVebnaArVJjVRFNarb1IHFLFCrwiVfKfy1IExBz9SxdfBcMoDh9J/P0DuaTrmdfKXEwSOYA2y2j87+z3s9xr2k4k7j+NpNbTEFuYHKADAyMkZgzzcxhxEuzSQZNbE8L97t25LtQc0x8k3Tfq3KmtL3Wl3/UWR2r6qsCLHVrGR5ccTU9LU4poVTy1jd2DGPXm6/FKDGAYZtMMgmCzNYNJJ6uMEjmcLmACJX2DAexmMdUc/iFWs+oRAe2pkF3ABsCGsBLQeVrrCTEKbVq8LmxKDbPF+7rJtvmqG0zxT0t/qKDlC+UsTTVExiW4SPLLEbclR3mld0kWWSVTmMgBuJisZneWOpUs1taTdInKQGkuy2aA0yLz1XqcDwDwx4jcRXIJMFtZ13XaXSXxmJGYlwaLAA9emHYt+8Kk1PScdco7k48o7HtKjqoto8htV7ip4K2orJZ5KK21qeVckfzVDZhqHj6o361dT5Yrr4mljXOD6YzOdGakAJDRAJYS5kCTqGkA2O6bhns5iMBSaMPiC+m0F3885ozETNQAPvERzawGhN+MpPGVYN57k5T3Kvhy3jftwV9orbpUUe+q+ywWOKIsU89HopepJWUzsIJW/aMcsfXTYnA4BtNtBlZwDc3mpl2YkaDK4TAsJAtotmFqcZFZz6+DY8OgDJUADWiZMPaTfWAXGbHtNu58rc9U9048tO9uJdsWbhT7xn3Jfa3bt+e91EccRaaFnp0p6epEHmPHLLKkcjYpVIyWdl5VHhVLmyVczw2A0tLdbG5JExMCd+gg9DF1agq5nUSxu7w5pFogQJJki5iGgmdRHZZ920dl3Ja46Lc1ppLHZrE96t8dDEJbOkEiv7HK9cF6RHFCJ38yRslj+zQgK2ueMOXNc9wOobMaG2YR8hlAm9yJXYbTY5rWCIdJN+Yj+5vaBAEkrt3HPKdg3XuG70m3uQLbue20rLUVlypkh8lpWUp5ET+qopBC56mK/H1Jy1KLmeYFo0ANie8QNe37LNicBNIS0ZjsCTA77T10XY73vCisFsS7V9ZXvTe0x0zLHlnLO4QBUAyx94HA74yfhqtjC4hrRJK57OH5nFsAWnsnFHuGK5zslElympFOGmkaSNVPSDjBwSe/y7fHSCnuQi/BZReJ+BWY66U4DIz/m7H+uiGz0VfgOVCSjGT7PCR9VBzonqh7s6NdUoVMCggQwD/ujS7ojCFYq+34Wqz3Cujid5I4/cVFyxYkKMAepyw7adrCeUIswfMAVxvgzkq1XjZW3rfPV3eCvYMKYXOMxS1aH3wY2PaTHVjt3wB210eJYVzahsO8QY9dfqlbh83NsfvoOnyXeDcc9ve+uTrlqz3NDNwUkj3dGEwwaH7cmPQZ9flokJvdCkmvODlnXt89DSyPuaCboBkmdf1xoZU/uaDJeokBzUwA/no5URg0IX2Nvwv1/5Qx/pqGm6JIRGEEwhG9r2xDWP/lQ99BzTsn90Td79Jk9FDXMfqFX+baYMMwVBhrKxvkrAYgVT8mlAx/A6UsgwSmbhbIbXWubsgt6fV5Gb+QGg1oG6nuvRWNwrSB/tFMh+OIif/q0cgkkIjDjogNV1TH3rjIn+SJB/E50DT6pvAjZDFQygh66um+pkA/+UDTuaDt+ajMPugvNTuB5j1Eo+TTuR/PQDJOibwTogobfGxeKkplf/i6cn+OnAMZdkPAvKJ7XChykUKj6IBpZPVN7vKFJdgv45gg/5mxotYNEwwxCYybhoo8+ZW0qn5GQZ/nqClZEYUhN/wC0dG393O0v+SNmz+4af3d3RA4cHVCa/wDr0U1xl+WISM/q2NDwSicOEH76qXyBQVAIP+KRF/qdOKEHVEUQgvdLgfwQ0idvV5if5LoCkOqLaIQWr7gSOuooo/8ALGzfzI1Axqgp7QgPVVbZ6rnKoP8AwRIP550fDHT6phT7IJmB/HXXBx8cy9P/AMoGmygnRQUt01kFE5Jmjac//mSM38CcaIEXChYUMTUMQISmplH0Qf6aaHHVHwdlZrmqD3GCfQaJpybqCimsl2ycF/3nU8GUfDTZrr8OrvphTsEfCTdrqe/v99E0VDT6Js929R1H9TphTsh4XVNZLqMfj0W04Oinhrpo3fRsO1/tp+HcKP8A6tcmpgzrB+/gu4cENgiLuiAkf+nbYfrlP/2tIME7oVHYQDUJ3HfhIB5d1pJM/wDCqn/6tKcNqEPcuyObnVt5ZS4qAGyf9nB6hj09e3w76ngbJDgh0RBc6j/+N/Tyh/rphh0PdB0SxcpSP9//AP8Amui7DJDhB0V/vGXP/wCIf/qLoNoQNEPdB0SvvGY9hcmA/wAi6goSUDhBrCuK+Y+lykH/AHE/00ww/ZA4QdEta6Ygf+kpiP8AKn+ml8ATolOFAMEKvbJvjcqj9Anb+Go2gOinuw6K4qpcf/iFWfy6f9NN4Qmygww6JPtT+nt9WP8AvD/TR8EawocMOiT5w6xIaqqeUDAYuMqPocas8K1kRhQtdtj3E11yvdymuiF3aGClV1JjhUqA5K+rN0FsZ9CMDOmdQaABunNARlAHy3SKu4Xu4mGKmqLpt2FSWleSRZJKlBnqSNAfdbABEh9Or8JPpYyg0Xdf0/U9O35JRhRsAfgrzUdLBQSf2fnpaWdwJTLKGmeft6tL1dRJGB1kkj4emhlLrO07KNw4mXifl92UW+XJ6+Xatbxwty2va7bWVMSJR3mlq7jLb2aXqLjEigp7jyhirJGOrqyuBrfg6DM2d8/CADbqZ9Os6BMcNALmAEnc2ntAEn5jTood8obz2r4YqtabZm1au+8s39KaHbe0rDVm73/d1vg6UEs1XL1yClRlDzTTyJTQrGqh1aNF12MJgq+OBptIyN5iYy02TuYsD0sXOJsDMjz/ABriGB4VTFWs0vqmWtbGaq8j8LAbkCxOjWC7iJvEDmXkHx5U1HeeS5trcD8BR09TSxy0NPVy11xElVVqkRDzGnhnqi5VS0chi6gxGAXz0MPwnhwilUquqG/4Q1tgSb8xAibloMfBcPH8X9oBRdVp4anRaDbNUNR8EgCzcjM1wA0PIk2USuNNibx2un/bJvjxV8x7Cuu67lBFe7hT01ne31nU0kFaJVn9ojlhj8yKIVCs0ILqrqnuDXWr1sIGe7UsMHBkkc7gRoRoGkEnbzbibryHDfZ/iTXu4jjOIOpvrOAfyU8s3bHMXjlmMwJbtaFidtbZ2NvifkGs394mfEvco9xV1vtkd7pr9FT2uGsMjRxNXiCFG8mkoJqF1jjURLK0iRFkfr1eA2kKYp4VkCSQQ4kCAXZZNy50iTJIALgIhUYTg9WsMRUfxGqQ+Gy11NrTBcGAkCzWtIcQIaC43JdKXzjQx+D7n7atr8EPMG/ecN9VNH94zWLcVrp90P7Srw+Utd7VTwzQmcTVcgZXyCFVRjVnC44hRca1IUWAxLXFgHmmLlrogAi0ySVwfazh2J9n8XTbgMQ7E4iownw3sFZxu3LJbD6YcZLXSYgAWJUJvtF18SvJF9sXPXiG4qvFgvFzZrZ9/wBmkp5dpSUgX/YqK2eSnXC0ax1Qb2mR5JGDYwIyo9B7O4Sjh2OoYeoHhsG8+JP4i4GIGkBoAAudZXyP/WNvEq7qWK4lhnUnXbLcppZTBaGvElzpJLs5mbNAAgewXgH8Tr+K7jnj/a3JN/sFyvO17XHbJaeRI0NrWBYqQ10sbqTVTyx1StHPhlgjNQh/aYc+J9oOH+513Ppk8/WdCZyg7C0O0JMRDbL9G/6Re1FHi3DaQsKtIQ8DXM0RnOnmBkAWu7NJUmJfDr4U92cqbkvlw4T473Rs2pv7o12jstLWT1FZRVDU4tVP58ZEdEjQwRPhiJpKeSJR0iUGmlx3H0sMzLUc0xMSR5hOc9SZJaNAIcZ5V6Ov/p7wXF13uqYanUvE5WmMsDII6AAOPctsSY55yv8AZ/eGm7b/ALzceM9t0PhVo7NDbZjdLLe1tU8ZmNUB0xRk0rs8fQ5iZHBwil8nBvw/tNiqlMe9EVc0iMszAadRzWmJBA1gHVU1v9L+F+JOCa7DVGgGabi0C5glplhFp5gTYaL5jvGP4c7n4T/EHunh57rVX+3wQ01wtdfU0/kzT0k6dSGRAAokQh0YqOnK5AGcD6RwrHjF0BWaMpuCNYI6dtPu6/EH+pXsVU4BxZ2CL/EaQHNdABId1gkSCCDFvTRRmPUjTdJLkYOSAScDvrqOEBeBaSTJupeeF3xf7p8LFq5JuG0YXfdlZDTy7bmnippaO016yxiarqElRmf/AGaMxqEZD1EEkr1K3A43wMY0MY4wPxQSDEGwi0l0XOw6wvqX+nP+pVTgDMRlbmc8AtBALc4OrrgwGzpMmPUenHgK8Nu0987gHi28T183RzJzZdatNw2iguEksVNRT+Yp+9rzXTx+VUuqmOVIIvMEQEbOje7GvJ45i3YKl/DsBT8NoBBdBET+GmBzEnQujUmDq5fXP9NP9P8A+MYge0XH6vjVCQ9lO3NHlLzZjWiAWskNDRJEEBe21Jc+Vtw7P2pW7q3Luy52OSmjpKKqsrR08FiDkpKCDl5WkjlCiaVH6lQGIR+71/OKmCotceW++bUgXAA2EiSAST+Kdv1dSzZi6YN/KLTMXJmSPRrQZI6rkVfPsvY1y8TvMKjYE23KK92qnoZb3e6mKo82Gw+dOBD5MheR18tWORnyQhQKrFtzxUdhqOHbZ7s9mtm2eBoRAB7bzOkecyZMdicTV5qYFO5cA2zJdJcCAMpHw2F5ecLbk8Wd5424/sVVsPa21bfTbchp60XiaZrhO8KeWI0gWF4KeBUqWRqdmmkwS7lOyCcV4ZhaVZ7/ABZM/h03vmmSbWLQAOpklD2exmLq4ZjThw1uURJImQCBlgwP+92Y/wBIGuW463BszZfJl3vfMVC+zNmVm1RdNoVtaamsT2qikkhqJpLhBL1ICt0iEazJEUiKRgEMuZXwbxhnMp8zgeYADRwsMhEzLb6yfQqNxjm41nicjXAxN7tMk5hLSIIA09NF2zdXIXD/ACxX0W1drb7sVwp7va6OxW280bChq6SqaRJSkhwMwosQiKuo6GlZcgudc+jhatNxfUYYaSSDcQBf5npYwNgu4KlJ1MFrxJGxkmfLb4z1vpK7BsrkyzUO7LtueLcK1dmprQ9eVjV0r5qaCJSiMO6pMemMEIqAtIgXuSdZ3YNzmZY5idNpNhfWDaJ6dAtdTD/yYtl066TNu1+ul+i43vPiLfW0aap3lsG+UV12nc5TuHcXHM9zWOz1FQ0css0lDGPKWIwhI1NPKzU87xBmSN3eU9R1ai8htR0PZYPgk+pmbm8EAOaCLkABcHC8LqMqePRaS12tO1wdgbkE/iaTkdLrAlbpxt4rtmb73dfqq0X7ZN7uQ8m2owo1hvQlAURQPSSgGlgBkkPtBLxMenDEsOrFV4XVbTHiZgCZubX3Lrg2iGgTray3Yethn8lGCRqATY6kEaz3JjvcKVG2bhfl3vcqm/PNf7c1O1TS3GNlaOil84xSxQNkFOgge+VBkLsOygIvNbh2hnJb8zvJ7dAD3NzK2YiiHMDY02jtv369Nl2Gx316ie7zKaypgEsUccjhFMgESkt2Pfu2M/HH5aqOHMA73WR2H0CzpvE3fFOcj5yqM/z0Pd7wUhw3RKN1mxlVjzj0L/8AhpThjKb3YQhG6VLdl9nBI7d2P9BpjQR93EKOnNXK+3E2jujb33jYKxG8qlrJKqoNPRwdUyBkknLdzgkEJ+H4kHXSwHDqhcHgHeLTNthv+Xqs7wxs5jYRN4iep27772XCfCzZNjVHh6rqyO3bbrqhKJpJHDrO3nGjDESksQJc5JHYd8gDOu57SVagxYbMbaAWtpb6rjez+CpvwzT5utybyZ3Py2U2tpV88m0trySVtYztbKXqbC5J8lc5OD315jGUAKzwNifzXawuHHhtMbLOisUElqqpf4d5D/TWfwTlsFoNGLpBrIgD77t3z3kY/wBdH3e9k3g3STV05zmONvj3Gf56ng7JfBVCuRPwRxqPkFxomkTui2gNghtdkjyGkRPj3IGoKQTeB2TeTcFMh/aVlMn+aUf66jcPN0TRsmj7noVIzWwN9Acn+GoMKTaCj4CF/aelbJR5n/ywuf6ab3R24QFIdUltxZ7rT1zn/wB3jP7yND3M6kImiOqbG/zN2FvlI/5pIx/U6cYSLylNJqQbzVNnppaaP6tP/wDsroHCjqj4Q0QHu1wJz5lBEPnl2/00fdhCJpiLBCNyrTnqucSA/wDDCD/EnTe6NjTREUx0TdrhUH1u9SP8saL/AE0vu46fVMGCNkL28jHVX1kn5ykfy05w41hAMQWraVv7yNZT8mmdv5nR93jZQtKBHV22nBWG20UYJLnpVO5JyT+edOaLkDTBmUU31Fx0KV/yqP6aX3YxdTwwEN9xL3y8mPqDoe6dERTugNuKIdjKgyfj204wpGihp7oDbijPfzox+uj7qgWBAfcUZ/8AWr+/RGFhHIm7X8fB/wD7aPuvVTIm7X/OSXz8+/ro+7KEBNmv47ftAdEYZAhNzfx2Jkxphh4mEC1Nn3APUyd/z0Thp2ULU1e/DsTJn9dDwCoWiE0a+gZw2R+enGGtZQthAa+jI97A04w5AlKRsm7X4A5Mgxpvdt1MqbvfBge+M6UYa6JaE0N9TOQ4/fqz3c6FAtkLJNvemKgfedM4H/5wOP463Hhw1XezlUd3W6Qe/UUEgB/xFT/PQGAKQvaTeEj+0tjbHULM2Pmkf+mi7BOndHO0pf8AaOwR9ybVGMZOHVcfuOqzw8kQR9EoqJwu57MoHTVUyEf8NSw/k2lHDSdW/RMKtoBRzuy1kYFzdfqtY4/k2mbw3t9FHvnU/VUu5qAM8i365AkYwLg5H6Ak6V3DpMFv0SiqNj9QnS7tgUe7uG4AfWpDfzU6UcMH9P5qeJOh/JHG8UA//qKq/Xyz/wDRo/wyNB+aBqDqjpvQkYF/lb84kP8A9OqzwzQwgHiNQjje0o9L2WH1pgf5DQPCR/SUC8RtKsd8VpHuXiNh8jQuf5HTHhTf6T9/BAPncffxVLvi4g5+8YX/AP8AXyj+TaLuFjQA/RWeIBYx9UVN83LPeankA/8A5OYf10P4S2P8Ite3b9f2ThN9XI4zFCf/ANBMND+EC9/y/dIagnT8/wBk0uu9rgKGWQTU1ulQho5/LdjG3z6SPe7Z7fEZ0v8ACdhv99VY1w1Ud7rzrJthaGpuO7bVEK6s9hMU9E00VYPeLRxwKY5Y5Mk+mQxPzKjVw4QDLcptfp85kR3QOIYCJIE6X/I9VG/dfNu6rpT7r3VS0e05+O7Fb5Wl3NJUNXxMoMcfsVqoenqqrl7wp1qHMgjaRUKSMTHrp0uCgNbJOZ9g2IJ6XNms3tci4gCRwMZxl4e4U2gU2DM55MtbGogCXPieWQAfMZOUx24u4y3twlx/S36fcN+2byzuymgqrhVXKrW8wSZqZHgomd+lhDSRyRxeQhWFgsz9JZjrpcQFGo8UWx4bTbLyyYEu3u4izjJiBMLh+znDK9CkcZWk4iqD5znLQSS2mDALQ0EZmtgF0kglco5X3/y/vLdm4958h7a3dvvbk1W1TLQ7epp6WzVaUkeWniqatTKpdGZAYwwIYN0tIUBelwRlFgFKzti8wb2gtbr8T2BiYzcT4viC4txDC5sAFtMZhLbky4W3sB3OgUc79U0fIXFEO5rZxRaOOtmXOre2VO8624/sJJJ66Gmf2eCnpmWaOFJIXVVCTVEsQfr9IpOrhsM6nVaKr5OuUA5iACb3BBMQAeVoNxNx4rH4ulj8Aa2Fw4bTkjOXNDAXODJAghwEglwALi2xEXd2Db+2tvbEvc/HHFfKnCdjsl6rLVdeUbNSVCwSWmDyo4oq2kpnmRauWnWVKqpqKZUpJXl6j5irEllSnWqRVxOWoCJDZGaTrDhlOQGIyudni1iXLnYTD4HCUnYfAtq4fK7Ka0O8MtbEF7CHs8RwnNnY3wrFxGVrTu9NyVxnYt8X/Z/h54g2rylaqSxXtIE2deJLk8000NPV/et03DUMInnp5qGhkeA+dOFdjgEmPWQYXFVqYqVn5Wy2MzcjGgGMrGQXXDiJENOknVd7+I8PweKFDhtI1qkOnw3eLUeS3NNSpIaILQeYuc0GQyBlMmeVtweITmKh3ZuTefBXg3uXHW5qCO3Xay3jkKrmo6yqRx/t8s0NvCUdWJJQhLFSSgUgsEfXOw+Bo4Z7cuJcKgOopGQOl3SR8D10XZ4q7ieNomk/h9N+HcIc12JaAT1EU3BpHWR8188yt4kvs5+eBfKfb8ew9w1VvuFDRfeVIlxgrrVNIYpAvmIvmSIYkPUVV1dFYqOrB91icNRx+H8MulpgnLaCL9TE+vod1+PKjuL+xvGPefCyu5g0OlzSwmDcZZIgTYXF2wYXsltHeXii492rsCPj2r8M/N/G25KWPddns1HRXGym5ROI1ljpZmeczyL5UayGVGcyyyM+GV8ePr8OwteqSXva9nKZDXAaxZsZR/TBsANl+r+EcY47h8LTrYVtCvSqgOADqjCZF4e8uDnbukN5idDIUlfDz41eNd4XTemy+Ttr2Tww843WpNVbNt73ppKSGspKdBDCKaoCR01c7ftixToyWHSrdA1h4lwLE4emx7iXU787biTr1ItAvO86rt+zH+oeAx+Idhq7Th8S6wpVbOIbYEEw11ybNPaNSvJr7cKJR4iuJJbhVxV+8/7BUyXaVaoSmRVq5xTkoIo/KHQG6UwcqAcnOvSeyJYKFRtMy3N9SBN99l+ev/5N0GsxuEc61Q03SNLB9rSd819/gvF2Firr5vcE9Pc9yD8tetncr8vsEC6mz4Btt8dX3xDW6u5ShtlVta0WO7XqOmqR2q62GHFMiKY5Q0gkdXVCjAlBkdtYeL4l9PCudSkOJaBGtzfQiLbyIX1P/RvguGxvtBSp45odTa17yDEEtFrGxvsQZ7r6sLhzpdLhdNr2C87Z3bx7TpAtDXirrS9dU0rKhjKOwIowfMCuVLOoWZEVQCdfL/4Y0BxJDpO2k9zPNpMXmxJ2X9AKWOBa2ixuUDQEAECNmgQ21rxGkEgFYrf3Ic20OPKKu2JZtv3qWpIoaOKS8VU0NV5IiT2h4REBFHT/ALILFCAWXpiAyUC2MwQfUu7LuTlAInvNy7vbU6Ao4vFOoUnOpszHQCZB+AFg3UxJO1yJ8sN0cwVm2OOv7ccmb2tNNadzcnR3m619VG1TW1VDTs9U1R7mGcssVL10sYw4kAHu+5ruUsIxlanTpAlzWWA/qNgLxoXGHHcTMiV8r4px3weHOxOOeBTqVhmJMfyxM2AMAsYJYCTlMAQV2m7eNrxFcqborYdncU7U2Hx9DSiWCp3rRXH2u+QSll6+mmD9KumMxtKCqu4ZicgU0vZJtFs16hDv6WBrg0i95IuD2IMCJ36TP9S8fjKxbwzDAUoBD6znsLwd2Na11txN4MmLRvtLu3xB765U4/5J3FvXwuXW4WOGWC0237su60u4qi4U2AJoonWSNY16eosrKFjyVPk9Omp8Jw9Gm9k1Mzty1pyhpkm5idYi/Q8y6FXE8VxL6NaKIYyTDXv5y9oa1ulu4IO3QxrG4l5U3LUDclx3Hw5xftGooR5Vxt+3Kuoe+VFRKyM9KlXOip58qtIahkhYRovUDFldL7vQZyPc9zpECWgwBIzEB3lESJNyd0MRR4lUIfRFKiy8uDXu5iYOQfy5k2DhAgbgkrNcSbT5p4u3rFQ3rmva99uVRFHfYqC72uuho90EVnmJTUMiSkOGnek6f2RKezqCFjJLWYjDYRzP5LHCOUHlJHKRLhaIEm53nUQtGBocXpPy4iuypm5iIc0RmktB57aNttIDbyuscm763jviCusXKNkHGtLuCjuVNPDct2tFbb1VMrxT0lFV02I4G6RK00c4heZ3yiyKr5wt4bTpjPTIfEGzZjcEg3jQNjMOsGF18VxKtWIwuIYaQeCDL8oJNsrXN1cQSTOUj8I1KDwlFwjwxR0fGXJ9mtNj5EesopXmuiveaapWGGJ4IaarCmLz1icxezsVZAnWUTPSbMa7EPIdQMsv5bXJgmDeJuSB2k6qjgmEweEaMNW5ahDQA83gDlAcLWAsJBm8DVTx3Hy5a5q2Tb9ovNffNv09rFRKlrWGLzvMYhKRZB7iFpA3mA/hVkX1bXEZgM3MW3mLm0i8neAPmewXrm1A2IOt7dNJHcwYupCbN5BgrqianW8NU1LxiaoSiYSQ00zEnyI26B1KihV6gACB2A9NZ6mAjaR8p7/H5pAZAtH6fHddCbc6E+9PfcgfFwgP8tUe4TeB8/7oEdPy/shjdcK5ANU5+T1q4/8An1b7mdwEoa2dUBt60sUlOJ2o4euQKvXXDu3yAz3P00p4eSLa+iaRIlRmve7qOx8JWmlvEdopa1ZoVljkRqqaNPaZH7whC5XC+uMDOddt2Fc/FHw502t+HrYBcSi6mzDB1aNbzf8AF8SVxfwt8pVNu4+29TU+0Rua3rQ2/Bp9vVAmpVamIJV2Xy5h7uMllLDvk+muv7RcJc6u50kGTqRtHe36Lg+yuPpHBsgA2GjXA3nqIPrupz2O+Wu60S3izNboIpiVZkoGp5AyEoVdCVKspUrgjtjXk62BeDldP0P1/VewoPYWyzT4jTtaFljW1IIZdwXWA57hCvSfphw3bVZwgP4VcAeqE9fcgzMm5bi/YDpeOPp+Pf3Qpz+vw1Bg2bt+pUv1+iT961oUrLVe0/8A+TKmf56PubfsIShfffbpqLbK2PitSJf/AJiDqHB7iPv4JgbRdCO4LdEQZLe8fb1alLD9SM6IwZ2SamCiJuy1jtHPQxN9VCfwIGocE6LyoQJR13QkgBiqY5B/yPn+WlGEnVNZIbcbH/1jZ+p1DgeyBgIJ3FnJ68/ronCCJUkbof8AaA9h5hzqe6SoT0Qmvzf+0/efXU907IaIJv3x8zt+eh7qpmCA19yDmTB/lpvdDuoTCE18HciXAxnTe7dAoEI3wH/1q/qdD3YhAuQDexnAmGdF2EtogUFr565lBH56ZuFRDigNfGz3mXH56Iw28IlNmvZ7gSjP56b3YdFJ2QmvZyR1/X10vu6Eymz3vPrIP36cYRKT0TWS7oc5MZOfiB30Bh+qndNmuqd/eXPr20xw6BMJs92X4SN+jHtpxhroTdN3uxyf275+jnU92HRTN0QGu0gbtUPj19dEYcAaIC6bvd5M/wC8MT+mp7ueihcZTWS8S98T9vqNMKAS55TV7zN3/bofl2/8dE4bdDMQm5vVQMgSRn886Y4UahRxQWvU/wA0P/eOp7sEA9N3vcxyepG+ProjDQlL00kvc/yT/wCP/wANOcI0FQPMWWMa/wBgIPVBTJn4mlYf/Tr0b8M83Kt94ZKWm49u4IE1FGPT0K/6aT3UnUINxLYkFGO49vH8dyo0+PasKf8A1DR91dsPp/ZK+sw6n6oi7ksWF8u/wrk9IK3I9z8u76q91FyR9E1PFg6O+qfpuCjGOm+yKfl7apx+/OlGGb0+/mrBXMaynS39APcvc5Pr/fxn+mmbhGnZAYiBcpwm4sHAvMh/78Z/ppfcp2SuxUbo39opTjovTBvTOEOoMEBqFPerWKpdxVQB/wDTqj84k/107sG3p9/JFuIcNXIy7oqV7G90Z/OMD/69UOwINo+/koMX1j6/uiru6UD3rvbD6f4D/wDt6Q8PnYoHFbmFcbxP+K52k/o3/wC1pv4feyIxfdKG81+NwtXrj1b/AF0f4a6xAMeib35up/NFXeKEdqq3sfp16n8NcNQmbjGnf6pX9sJP8MlC/wCfm9v/ANXQGAEXn5IOxkDlj5/2XON0b73jR3BXstw2xTU6DzohXwVRUkI3UFmjTIB6gMFT0+ucdtW/wtm8/IH6SqqmNqCzQ0nuSP8A/H7Kgzzvy83KlDe9imnsu2bvdZqa3VtxidhU0NLNIkR8iokjUN19QAkUqydPV0du23DcMyQ58lguQRAMCbi5iLkEfnK89xzjDatI0WENe6wM3E2tpcmwIMgx0hbttm5W/lKybJ3W16oducF7Fq1o9i0A6IYbuabFPFd5RIgVolj6RSwgAN1vMfeeHoUUC0uc69apM9Wg3LRH4j+LoOX+pZMHXZXps8HlwmHMA2h5bbMSYhjTdv8AW7n0DZ53unfez7zvTascl8tm6qyn8ub2NqyoqY6kCeObNRRMwhEcQJfpVcMAAcN2JGDdSbmHKesAdrONyT8IJst1bi9GtUFMOzdg7NuNWgWHXW11y/xE8wXje9fY9uXa53uzW01Hnw26zeZMKC2jpeZ40ijyMMYwJGljjhYkBi0eBZguGAOc7LmI1O07AyQL+hLul1zvab2gLWCkwlk2AEk5fxEBoJO0GwaYuCFDfdvJe5Id/wC16DcWzN6PviK5NaNr7TippIVelmpGp473VUJleCmr3DqIUc9CeUpcN1M430MCSHRlJI5nSDF5LMwG8HMRcTA0APzLiHtSaeIoiqx4LXZaVEBwz2IFYsOkEjICYJGZxl0t9GuP6m0Xzj2y7H5Tavu3E9LCLXZdg7Xq6lLB5JVmWlrbjCqy3ib9p76SvDGGWUtAc9Wsdag7xPeGNDqhM53DQ9WsNmARZxzGIhw0X0bheHbVwwwuJd4dGI8NjrunXxKrYc8unma3ICSZDtU5vY42tVdsjb0m3Nm2azQ7t8uajhpFoh5T2+anpQUESqsaSLGhHSyOUXq6iygo44h+Z7nEujUyYMgkz13FwRstRo4HDeHRo02sYHgQ2BbKREW9DqDodYWX5KoL5ZducfVtdtXb+9KG3L5kkMtc8tXI0il5C1YADV06MxkaGaPrQgAFhoUsKHud4TuwtYDSw1adrGCt3EMU6nSDnszdeaJnraHDe4kAdF5/+Ke1bk8U/AVPabxtW20XIe3aVGsa113MdRapaWWSKqooROiyVEdQrRrHGnUXlTr6kSIKejwygaFU5XSHawDewINpAjUyQA3Ykr5T/qLw93HuD+G+jlrU7slwBaQSHC4BcHCBIBzOywQAVDD7O/xBVvGvJVDw7u7cDbIstyrZY6evqZRTvb6kKfMoXLxlkWodAg7qI5TnDFzq/jGCa5pqET1HXvYwY7zbSF8p/wBEfbl2CxY4Tijla4kNLoGR27bgkZjoARDusr2Q8WNXYN4cPxbY3JZONeUuNaKT2Zqqshdp7aT0oFjaQN5HS7xddUhUlmI6Q7hjy+HMcyp4tJxaTtFj69R0ET3gL9Ke3GDw+LwRpYykyqwbuN2+nQ6cwIA6TAXzWeJTYFVx3ybLZKq83m8001rorhS/eNU1RUUkEkWUpmlZmLCMDpByMr0nAzr0OHNPKfDAFyLQBO5svxB/qNwivheIBlWo57SxpbmJcQ28Nk65e0CFHsoI2icks5wcEY7jV5cLgLwRp3B6qVPhZpHu125Wtn3XQ1YrNmVtG1dUKWSyrLLDH7YPh1p1YHV2JbuR6it9Nzg0gwMzZ6kdB6/kvo/+mhz4muzLJdSeAb8pMDMTI09b6L2N3DV7R4+29YrheH3OKGxrUvGZbiK5pXKiFa2elgnkCFmEY82JP2ZfpVlbXn/AJDhSa2T0+cTF+8kTrov1tVrUcLh6b8Y97W093k3gAZi0EwDaIByzsVpVy5z5btHG9fvveFLbt98ibqpaez2WGmlllk24J1WGPyqeNfLeUrKWDMwZ5PNADAljd/BGMcKTbCZcSNQLkSYgQI00Guy4lT26x9LAnHV2hz3gBjWnyudytloBzG4cbgzYDdcI4y2DtLxCb8vm+73deT7nxFt28UFg2jQtQRM8/skQZ5J290JCsqqTDGVMnTh2HRrpYbPSb4gaBVfLiZsBNvU9CbDUTK8Fw/hOH49i3nE1nOweGLGMbkgvc0S6f6WzrAzOgAkCy9Ebly5eIr3yFZZd+1FduapoqKgxHGkk8srO4jcSF5AWHWjSFX6lY9lAGuMzhjeUZYBOugt8Bp9YX3L/ANRc9Sn4gzBotuJJggSfj0tbUrVbjy9vKr5iptmvdoLxyTaLAn3vGLhLTRUKyyMk0sUTKscVO8EyFJZZYlSNyAAelTGYKjkdswkXIF9wCZ1nUAEk2g7Y6/tDXGOZhHHPWY2S1uoJtIbEkRoS4AXJPXrdl4r41hqtvVO973T8iVNzmlWkpLRUSQUlvkkhUQQpJMFjCiOJQsy98qEjjRXCvoIIJ8NvMBJLhBMGSbX1Okd3GwA6dDBsexpxLpYTYNMtAiAL20GshoJIaLlx2enuVwnuO3d6zUFtv7s72aGCSll6kaeMq0wSRMBhJTxSdbMDgM2Ex06qGDhpY2RNzpEC+oPQ9/UroVMXmcx9RoIbbUzJtoR1A6CLgLbdz32w1lFfONd0TUW4fuuCpSWdmC2+41FaskMccNPgIxRjJPLJ0uEeMBCxUgJh6Ba4VG2mANc0CCTOzYsNC6ekK7FYpjw7D1gHRcyBlm8AzMmbkXDYvdc73jxvxDsWDdb263XS7WurgpmnoquGaU7aEM6P960cUgkMEa+8r9KtiLpaNXYurXsc6Za2IuTa4/pMRr6iTawErk4vhWHosdmJc0xaS7K4fjbm0ib7AX7LN8abug21JVczLs27ck7Nq56hKWO3xmR62IOY1uFQsh8ozL0qi9R8zyEZ5OpwGWvEYN7milYPP9UDLP4et9TsCQ0ECybBcRptzYthLqZ/pl2a8ZomIGg0LruIlT04qFYKSpv+4Z4o7hPO8iW9Io1S1J0hFpndRh3QKx6QSqtI+CxPVrBWwjRAFzue/beNp3AXpqGILhmjK3Ybx36HePmbLsB3BRRnJe3A/wDc1n9y2CvOIgXSxueADMc1Pj/lx/TROCO6RuIHZXO7MD/egfj2J0owBnREYkFcp5Y3Sai1WuLzZnXzppWxE5yFgcAk4PuguCfpkeuAdWF4dBcY2/ULDj8YcoM73+RXJ/DTuCC2bG21E1uqpQ237M4FJTsVP7Nh1JjBCdx+RDfPJ6/H8DnrvJGjjrH1+S897GYwNwNEj/8AWzSfp812XZV4nsVpNorRuCgqzVVlT2jlMfQ9TI6+9765wynGc65mNwAc4OaAbDpsPgvQYHEloIeSCXON50m3X81t8m8CgBW/xRAevnonf9/SdYxw0QTlW4YyDMhOF3TcugNFPbqn5YLKD+7q0owDCYTOxJ21Vv7XXBcCajI+ZSZWH7m6TojhwhAYyEJt5yK2Hgr0/wCYRdQP/wAJOoeGwLIHFhI/trAP/wC7ER/5wy/zA0h4bGoU99b1V13dDOD5VZDOvb8MgYaY8P6hEYkG6bSXelfLvS07fXy1/njR9xtql8cJu93gJyrTRH4eXM6/wBxo+4bQicQJsk/fcwJKXCtB+RdWz+8anuAjREYm2qGL/XocrckkX4B4R/NSNQYEbC6VuJI1QW3NcgcBqGQY+JZf9dQcPFyo7FHZJ/tXXD+8pA3+SdT/ADA0v8OlT3sITbvkXBelrv8AuqG/kdH+HHdA4qEL+2MGf2jzxf54XX+mlPDnbBN742NUht5UfYGugX/M/T/PRHDzGigxjeqWN0QyANHUxSf5XB1Dgwm943VjuEkEhyTnQ9xQ94QG3AQenzPj6Z1BgZvCAxAmyA24R3w+R6+uiMJdAV0M30nt5jHt89T3IzdT3i0hN3vxz/e4P56YYNDx0B783/tGx+elGDnVDxt0Br9nv1nR9z6BQ10Br6Tj9of36Hul5hB1c7FBa+en7Qn9dM7Czsl8aUB74TgeawH56Iwo1hTxwm7349/fPf66Iwd1PHk6ptJfTj+9P79E4W8wp4ybvfWPbzSR+eiMJdKa8IDX1hgmQk/no+6DUhB9e90Fr8xBJk7Z+eg7CiLJTXEJs9+JXHmHHz04wkFKa8JrJfycftNEYPsgMSdJWO++4gpASId/+Ea9r/D2leTHG7XS1viYB6IQfh2HbS/w4KHjPdHF8iIIKQk4+Kg6T+Hbqz+MBKN2o5ABLSUcnSQw6oVbB+Y7evfRGBI3SHi7OyoXG2N+K32xvnmnQ/00XYJyb+KsmIHyRkuNtyuKG3DB7DyEGP4aBwPVOOLtmLIntdpbDNb7bn5+UoxpfcXBE8WYVcVNmOT7BSA/TIx+46jcG4CNkg4gz7lFWqtajCQBBjt0yuP/AKtL/DzN/wAlc3ig2/NOkuFKoDK04H0qJP8AXSOwG0I/xWLSnC3WJfSpr17entDH+ugeGpTxZvVHF19CK64D/wDT/wDhpf4de4/NM3iY6pa3lvQV9eP/ANKD/TR/h8nRXt4r3S1vc2MfeVd2+br/APs6n8PA0RbxWBYq0l7rVjdobnWvIBkJ+z9/6d17HQ9wHT80v8Td1/JR85Q5fkpbHFVW/cFwpOmojikaOkiq3ctL5bQNAyKoz73vlgVK+mNKOHjXKY7SNp1P1gFZMdxstpyH79Ad40F/jZebO8+cd7bgt6bb2fa7ze9+3utmsslZFKppnqK2P2VUleRGeoMcQl6WQFUbDKxKsutNPhkkBoho6/M2HXvEi3Qr5vxn21qeGWUgXVHnLaIlwygEmLjXlBg37KQvCXHu8du0tq2vf5C7rLJAK2hxC1FTxP0GKgYIGghHXEobpMnSY1PUACGdgAOYaamd/X84Bhd3gHjYek2hV1bYRENA2aLCNBJE2XSfEVvzadws1p40v22tvTu1YKShSriRoKApTtIjyNHiWNvcYoilJGkjXJAydVUsO9pzhxvM777CIJ+YAM7QupxziWGawUKjAS4wJteJBJBkaep0CjttXd+0ePrc+6KmW73qiio+tq+6N5knIG4JQFZA0cR8whUVI4/2Uaxq0gwhdjKlE+Vrco0aB+Eakm9idSXSdBqAFxcHxTD4UGrWeXmLucB/McbBrYmQNA1ogmTeS5adsPbFZd987X3A1RbJuZbjLJuq/wAd0pnhjuBERpKKFlbqJmT2mb9o2QuAo93pZbhhw1ppXDWCAfW509PX8lwuHOdVxNPGENFeqc7xcSGjKwCZ0zW2gaXBUx6PkGo2ftQ33bEcN8235+bnZTa5pXsN2HaYLGWPQGYl5ISViIZZ093zM5XYPO85RDvgJG2vbe/TWF7yjxltCkXsjJNxDuV29u51H/yFiVxrk6rr7/Twb2uVyprU10r7VSVNCY+uioVgqY5I1hWNn63QVVRK5BKe8TiMIp1bTwQa4NAnUyNTIjQgWsB19ZXO4nxB72Gu90DlGU6CHAgzJvckjTpZsrb9t80T8a26m29DfLTYeP1tVVc6KuNCJjTmWSQVMUzzy++Fl/CzAv0P/i1lxGEhxc6bRaw9NAdegW7h/HRRApvLcsF0nMbyZBJI07kW9FheHNwUe/xbNz0G87dbuQ62I3GjaCjg9jpYpv2EqsEEfTKwQZIyCGyO3WBbVYxrHNIMaEzBteL7T3HfZZOE4/3lwxAeC43aIEDUTbePXfLqV4yeL7hf2CjtXOll9hqbfeKiWK8rRU7xx0lxDt1hzlkLhupSUPSVEberMda2sgZRtpppt+/02X5z/wBTvZsBw4tSjnJzhs2cDvrBm3yJ1K2XjPxB7535xguxKnflyNfQW6pgrLQ6wedc4SyFJaMuQ0koWNupcZVjlQes5yMwlKc8XtF+nwMbb/QLr+z3t5jMZw/3Q1eZrXBwIGZwtBbJGY6yI16yuLeMvdVHu7fGyr1blqpqJ7BGYamrkjNTXKZpG86dEJ6HJZlIYkt0A+hGpQptbOnoNrafqvI/6q8RZisRh6zBILDc6m5uRcjprtayh6CS6qrA5B7/AAJOtO8FfKxUP4V2ngzkP/ss37QbruFyusW34nhp7tQ0FYaepudE8qmSKNh2JHQr9yACFOlc0O/DMaeq9X7HcZfw/Ge8OeWsEB4BALmkiQBoevwXpq3iSs3LAve2uN/D/wAq8j241UVTSU9soYraslL0jzZ5ZVBeeolmRIupmcBRJ0gvJkNTweLJDy1o/wC42HQAWA6ki5sJiZ+6VP8AUDAYzNQwVGrUba1NgBI1c5ziSTewBsJLomIye6K/nnm6+2Dj7eW8NjcK7Skp5ty19os1yF2vtr9hBgihkV1VIahpK2Xy6VekhgzdikeEpcOpAucXGplEQ0ECXWIkzNhd2kepVmP4txrib6ODeW4Wm7nMua+o0U7g5RDW8zhlbqTB/CF0Ox8e8bcTWXbOyNqcgcrLTWm2tcLhSx3qoovZJpG/3mpK+UKcHqcmPI7HIYDuBiadN7y59IDaTf4XNz6R0ibL0nA+HUOGYeng8NiqhgF5AIFz+Iw2Wi95JO65dUWp94XC31NJu3krfzzPUUlHWXm8VtJQz1Id1aKgcFJJFRzFKWGCY1dmkGMFzhGUgS6mGW3EmNZIJgQJsYEwIMrjvruxVQFmIfVJJAIcWsmYhrgOYzFwHGJOYALtXFvGnFdmo6PdNvudPfN13Ohlulcbo9LW+UnTAIE83pYFpJDLjo6ViDdwfLDM7qwAyU+UN6SJMmY00Aud9omF3fZzgOFpH3lxz1Hi5dDjAAibmxceUDQRMkSpDpzFYL7b7nV+z22hvVDbqukkWermihjgPvLPLUoEjjiBji/CWy3bp7HWR+GeGmbabb9IJJJ6D+y9tS47ReIbZzJETtGsgQ0dTNlm9vb8q/8AsmqKnelNv+e4pCzUVA1ulp6WaR3bpVvP8lApMsS+WGJZXQEYJj1bXweV4a0DNpJIn5SSTY7GO5EhcD7Qk4U1apd1gA3mYuQBEEXJEjpN4z793tuqSosX3nbNubJp6uopbVbGa9MKm4mnMiszvMwjigNR1NLKmVjUBR1llVozBtzCTJMuiDAFoJgSbC1pcT8R5niftBiA0ZW5RIaDmBc4yZABIaBNiZ5QDOsGa+2325WRWekrGt+4K2ot7C82221j1JLMehPvS4yEyTRZMWVIjjVAV8tgekMaLnCKYlo0JENB6hu51MkuJPTVetpVQ4h1eznAy0HM4joXWgdmhrb6wuqWLZiUcsF6t95Fup4qVLNW0FrjWvppohG0LSxLLGWd0DHLdPUyBlyQq4X3drpMZid/L362Hx1uuhS5IDOUNsW2I6drj00st52Zcqjadztu16qhn3HEKWSekv8AJNHHTVNEoVYkOT2njAEbDBJUB8nJArfhZBeLfnJ+GnyV2HxuSKbpPQjSP3Gn10XbKC7KKcS+ZA7yM0pKLhQW74Hxx6evc+vx1V7rBgbLYMY3VPPvrGPfB/I6HuiPvgVffR/9r2H/ADaT3S0wm97XJOT7400dNTIxkdaKrkVAC3msVCqnYjswVxj44I7eo00MJqT9/f30PMx+NmG7369rfH7vcaVwFdJKfbG04mXyf/3ZoBJEBgQuIoW6V+hVw+P+fP8AjAXo8YoTXeT/AFH9fv8AvK4PsZiyMDhwP/1t+Fh/n66REhPvk9/eYH89cj3NetGL6Kz3lmDB2DA/A99T3SNETi5TF6ykYZanpyT/AMgH8tM3DEKv3kbIAq4I/wC5aph/yTOB+7ONT3USj713SWuE2T0XCsTBz3Ctn94zqDCCNNVDizEyhm7169va4ZPl1REfyb+mlGDGiBxhhNHudQxPnUVrqB884P8A+sp/np/duhQOK6hN5LjGPfa1zI/wMMoB/gy6X3ORFo++yHvY80H7+KR99ooOZL1T4+DdTD/6tKMEdAEW4xvX5oL7gVGz99tEpP4ZYlx+/AOrPc5uAgcfB8339EpdwSsD5Vfb5j+Xr+eGOoMIJkqHGEiWxKoXyvGcxU0vwJSQj+a6HuYUdjzoUNr/AD5JankGP+F1P9Ro+4oP4gAEE7jJwGgq4/h3TP8AInUOBUGPCGdyRZ7zOp+qMP6aAwJ6JTjxOqE25aZ+xrImb5F/X9+m9zjZBuPaTqgNdaR+5FI7Zz+FT/HTe62sicW1N5aulkzmJCfgVyuP3aDMJCDsUN0M1yL2SerjHqMTv/U6UYMaAIOxo2P1QDc5QMLcK3t295w38xp/chEwoccRaUA3arBPTc5SPk0aH+QGicGI0Se/ERdI++q4E5rYXH1iI/k2lOBERCDceeqbyXy4jHRLQMfXuHH8s6gwLQLpXcQfMjT4oDX6vxl0pX+qzMP5rqHAwieIu1Q/7RVWCDT5/KZdN7jdAcRdJlCfck4z/s07Af8AC6H+uiMBJQPEkA7ncgg0teoH/KD/ACY6X3Eg9Uo4kO4QDuhcsCtag9O8Tf00W4Ao/wASGhP5oT7nhznrnUntgxt/pqNwNohE8UGkpu+5oB6zsB69w3+mp7keiA4ownVN23TSZJasjH5k6YYAqr+LM/qQG3VRH0r6b9ZB21HYI7phxQGwIQ23PSkDFbTZ/wDerqHBEKDiI6ps+46fA/2uA5//ADB/rqDCCZQPERunDXNlX8ZOvaOoAL5aOKEWVC5HB6WJ/LSDD3lMzihN90Zbkcdmzqe7WuoOKOKULk57dXfGcaU4YJXcSOoKKtzb16+31Op7uNITjijouiC6MAMMRpxhoKI4o4HVFF0xkdQxpBhQlHFDOqKtyOBl9RuHumHEzqlrc2wMsB6fH00fdhKtHEzqSiJdCf8AFn9dB2Gsk/ihN0Vbo3bDd/z0BhxMKfxM6IouhyD1HHr66X3UaQmbxU6Sri5kAYbA+uj7sFc3ihQqm+ikhaeTzWjBUMEUswBOMhR3P5DTe6TaLpv4tAJJXO9w78rqj/ZtryJcK2UMlM8TOhhlGQCXaNkAHS2QxwQD+lTsIcsmw7qqrxzZhk9lHG97gk33R1ke57nuCWhgrXpqeO2iVKS6zvGyyylowmKaQuY1XPXIoHorEvG4YOE5Z9fpINp3iIG86Dh1+MGqXNe8tAOxiTvcCYvEzJi0alhafb5N1bMp5aLbFp27ap0esp6aFlqaeRopY/28oKRMgZWVSB0qI2C+vVoNwjz5yT2i3qN766Xt6JW44h1NjGhrRE3va0Eael7XvNx3HeV5egsbjb8u4aikWp8hK41coqJ5yMtFEzlSYWwpaVCfwqq5P4a/cwTGUen5E9u25K7NbjBaCWuJvr0PT49bx1lRl3tU+VsOprb1tekoZKCplofbqiaSWeCaR2FRVdUbMMssjIoVmIVZGZupgQ7qRDbReNgbC4/c2GwC4tfiU081QGWk3J0cbT8jAN++gUf9rttq8bovqb6sdNfdsW+0z0lL5KO0NxmlhZo6l4yQRGAEcLgOOkdWSCBmZSIBqATHbSNZ1uPkDovP08VTq4g06w5GjqYcSLHYx3ubXMWXVKa87e3Pv7kyfjSCk3BR0W3bQkNYJeqlEymWpHm1QOfLPtDIWOXAjjKt27PTZnGoAm0j4WGvwFuq6/8AE2uxDvBOYhjd++YSZ0vE6iJCe7i3rdOP7hSci7ipLBdIVtMdpv1JDNUMlZam6lNSMoeuSJXAZ85ljadD/gAj8Kf/AG+aO3Tb06DYx1VtfjTqLxi6trQ4BxuD+LuQDc7gkDZdK4/3BBTbY5JsdNa6yvv8FD5tuulK5uENttpUvT06svSUWF4jG4C9R6VDAnGmfRLWkAW1O0nfWJ7bLTgOJthzDJMct5AadNJjS51Ij0XErxu1t7cdCj3K+2KGvgpqI0lLUUJeWrknlRwCyFSjd4yD74GHOcsNV1Q0OhxNzbTQev3t1WCrxhuIw/M1sASQQZJJ7fe/RRvflqn40vlwtsG27Z92UVW0EtfX1QUVk0SGWUTQsWd5gOpom95BLIUy5VU1krMeLkADYRfoI2vpOsSR1Xnh7RNw1QsiQNXE2JgkgjW1yANzB6INnvPJnMe0abi608a2u124Uc9lqKqGAXRhHJOWEj1kjLSUohUrGTEJpwvVhQT214fhtWpeYB3EAH43c4HoAAesLn1eP1sdQ9ybQsJBnnIkmDEtYwtBu5xJE+WQvM3kTY+6OEeTLxs3ckET3u01RVnQypDWoPRkb3X8pwSPgcFh2Odc6tSNN2UifX9rhfH8XgqnDsZ4dTzMOoJ+hsbzrY6rbfEBurjTdV72VV8X7bs+27YLDSG4xUPmqjV7r+2VkkJw6lekkdm7N8RqivWNSoSfTSPyXV9qMVgarqTsEzLygugkjMdjO43XAeo+dKhZsnPx7fTQIvovKNJuApW8QcVWS+8X/wBs4bpcbbyQL7LFaI5qL2ijqqWOJA/nIRhU6nlJm9E6D3yNbmYd2RoAIJvI2vb1HbfZet9nuDUq2Edic0VWuhoIkG15EdTroFJTafLSQ7d3vaN53S+bN55o5aahpbbDUm2QVVOsbHDv2WNOqRJOvqPSAH6MgEpVaP8AZqXM6n5ba72AnaV77g/tGG03mo8067AAGN5Q706TIvIG8brLcLWze+6pd6XTaNfumLc8opbQu4aK9BI6MQBmlmkkR+upZ5C4C+4j+SZC5GcXMw1N7MtgJJ1MwBYBu25km06KcDxGLq1qlamXeKQG5wRAMy4udebwCADmI1G1XvelPxRcLNBPet38sbvqqiSpShvK+ciO6kzztR5AkqI5TKy1Tydm6h+HJFIaxr/DoNhwETNwOx0aD2AJmZO9+O4z7qWuxFR1dznDlIsTuS3VxB05iBoANtI3LuLmnm7ct0rNy3w2K30hevM1Xb6iSsq0McUMSVcdLmPqMaeV1Fu6M2SwwdOzgzwc9SflMXnU5d76bWC5mL9pcdxCtlzCm1pmTIJtlHKwuvBI10Nyu47PG99lbg2tLuO5cScbbMqI6uy0u4rVs2SeaGSMdaxwwzO0UdRPl1VnQ4CYIGVGtApOPne5wOwygm9hIk9zHz1XfwWIxWEfTa9tKmxstD4e4NMTOUkCToJjTSCJ6pbOPuVK6Ghh3FcbNf7PDc801lvUdTabrMomBWa5TUcE6SOOrJiIXy+xGXUEXUsG1sE3PpmaPQgtk7T6xbXquqY+o0NqODmSYmab3aEF3K8RaQ20WkTAWSbiXnCdZN3WmSWw1EclStmG26yCpmoU8zCyzCthSWd+8jhY/KIypADE6V/DmlhY4666stuABO27idVsxJ4m93iN5Q0nJEVI7nNG+zWg7rcuIeKqKrad6DkybfW45aKehulbX2yKJ7H73lrTuzL5oSPyz0wBVUFmLDsTq2lhqYBaAWixN9fkB6STAFgtPBqbgfEqVRVqGRceX/jqYAN4yyTrKmXs610dtSr2tsq5UjezSn7zuVKC9PDMUwYIFT8Pu4BI7p6Z6iSGNBtQ5zOX6n57f40XsMJiRRmnTIzbxoPv+5upB0N1p7TBRW+neAOqRxRKmB7oHoo7YH4fQDHf5aV+Hl111W8QyiAgW6liPtld7ZVR1dRVyTuysGUYdsKqOGCgHqbsB7zsfjqNw7YAiLfenayUY45iZ/b5LZ4K/wBmhEKzzTdyS8jdTOfiSe2TpThRqFa3iJ3KKLseg/tPjoe6qfxLqUlrs4wesn4ZzoDCSdE54lO64byncJauouMa3ettxFmmjHllehCRI3mPlSen3FTsQSzxj4nV1LDgMdZcbieOJcA10GD6Xm5nb07dVgOFrhPb6TZNI95qrgx27DGVdkwf2UMgKhUU4XqZDnJ6xIPQDW7iOGaTUht579SNz8lxPZfiD2UcO0umWDp/SCNADa43vZSKN2YDtJjt8/XXLdgwvZ/xIm0qxuz9/wBp+udRuFBR/iTihtd3A7yEH89EYXYJhxEyk/e0np5nf4fTQOFBvCh4idUhrs4ziQfv0Dhh0RPEd0gXdh38zB+PfQODEwoeImdUg3aQ5/bEfrqHDDomPETrKQbu5zmUfv1X7oANEv8AEr6obXaTOBJgfPTDDdEW8QItKGbvJgjzTj89BuFEwj/ECBqm71yOepkhYfVRnTHDlB2NCZu9EWEns8AcdsgdJH6jGgaJSjFiZCQapQfdmqk+glb+p0PdrQQj72SLlBNXMScXCsT44JVh/EaY4cdFX74R+JJa4VoxivDf5oh/QjQGGCY4tw3CBJcrgPSaiYHt7ysM/wATpxhwk98deD+abm4VR/FT0LH5h8fzXR92uiMaRdN3r2XL/d6s34vckUHP7xpfdxoh71HlCQLm4JDU9xT6Bif5MdQ4bomGMPdCN37Z67gnwOUb/TTDD30S+/GNfv5Jq18jU+9cJkHx6k/1XUOG7JRj9sySL2hBxcaY/mV/8NJ7uAbqHGE7hJN2ZgcVlK3+n79TwGpTjnbFIa51PbplpmH6/wBNAUGlA415Nv1QWuVXg5WJh/mP+mnbhwN1BjnRogNc6gesUfp/x+v7xoeFNkhxbpgoLXSf/wBmfy6xo+7tJQGOPRNnu0w9aeb/AONf9dT3ZKMaYiEJrxKPWGo+X+H/AF0PdtkRjnRCbPeHxgx1A+Xu/wDjqw4foo7HnUIJvDEnCVWf8p0ooQl9+KE12z26an/4DjTGjCAxibNdo+/Ukx+ODGf9NMaBOiR2PEWCayXSBu3kuP8A9Ef9NFtB0qv30dFzGo5+tfl4pbfI7dTA9cmOw9P5/wANesHC3E3K+ID2yoxygn73WW25zRbrk6U9yhWimaXoDIcpgnsTn09dV1uHFtxcLTgvamlUhr7FZem5ftE94ktIjI6WKl+sY7MR/ID9+kfgHBuZaB7S0jU8MJ7T8ubenqkpF9rQkkB2AA7aR2Ae0ZjCdntFRcYaVstZvzb9BQC5S3FHpy3SvR7xZsZwANVU8M5xygLY/jFJjM7nWWUsm6rbuGB6m2VPnKpw6kYZfX1H6aapQdTs4K6jxJlUTTdMLPCobvk4+es4VxxSX7YEGWdUA/4iBpi3cItxe4S0rOoKysHQjsQex0XMEJ/eSiLVEYPY4+OgGDbVA4kwlrVHsD6amSSJSuxUlMbjfqS1RLPWS+XCSFJ+CnBIz8vQ6LKZNhqkfjQzmJWBfkjaiIsn33SHK9WFOSBnGPp3Px07cOehS/xijF3BaveOcdm2ieenluUiyxdLdSxl42B+BI7gd85+mn9yeRYLLW9psNTeWuddaFuTfFv389zig3PbV29b4vPmiDiQVEh/BAWHS2G7MQrA46VOc6zNwxJk6nT1++3fZM7jDKstY4ADX7ka/ksdsTcW3LBS19hv+47dUXAOtQtPRKVPW2SYw491WyWTqwCFBwR3JtGFiwBPr96ffZZsJxim0EPeB6f512CyVLzHZ7NuPcq0jUtTE8NM5Kjyox0I2IUU+nSrIuT8dPTwjySD3Qf7R0WPiR97LQrn4hrjRzVl2ktFpqKmoCxKwjEjIgYYiDMcdxklvTIB+GNX1eGOa2xK5H/rHMbgEba6W2XKK7ckG4Lfte+32xQUlDSwGoWi6zJUzyFCied5bAHpBkOAoB6x3wMazs4c+SX66dfz1+euyz4n2iY5jXxA1j9wDH3qtB2Xv0Wahu1tt9PTw2KoT2i6xLTR+XKYIunolIOGLBGkY+hDFD2LasPDwRm6X2/b021uuZhfac08zaYADtddBOt/sLm9de7dS7dF0j2luii31PT1dbNR20CkiCM/4zL1kRxRBoowuGUgOqD1xlq4Fxtllw3JG+/WSZ0glY6XHKTKWdktLpsJEjp/TDRFjIEwLmFz+67x8SF3srSWy5XnbWzrVT1FFX2xqjpqKunlRQ6kTRuHwv8AiESLgDGTk6xN4DWBL3mCNpI+Mgn5kyslX2pxrqQbRJDQIOhtpEEDboIWuy82eI+K1mTbc1hv9rpLdNaqW4mdFrpqdx0EOYWCTSK6ArJgAydRIJOqXcOrPbLXAt6HX00B7dYVbPbLHsEASWiJ0+dyDpPr8ltk/N28Ztujb1x4Vt1C1JRYlqqW9UrSxPg9PUZhiJiR3iXuV+HcHUrUsSJc/KPiQJ32ufQroU/asupiiaLpjsT2MTYdio4XC+8n75mo6ep2per9bo5Z6ilt1RdEbqkLe+ZJWcvKqqCFJwAwUgEADWWjwyu54LQ0m1psN7Dv/decxnH6tfzhzhJPc9idbdNtF6LcbeLduLrrK29+L+WtmWw2VaKhpYLTHW0FD0yF2liWlYmNWLAHtgBU7YGus6hiGGalMmdS0g/Sy9twz26oYcBjmuptAgAtIaD1BE+ijX4obvxZ4na3d/IG2+QbVU7zt1JB9309QwppZKeKESS000UgVzlnl8tgCVaNg2Q645OLbQdIcS11zeR+fXfpaFy/aKvR4nOJpvDi0CI+oPzseuuy8vEb3oio91znpx6fXXm2HoV85DxmiPglvG0c5kYMy5JAA+H+h1bbZM4EQNl6ycPbstWy+MNj2+l21V101Ba5S9RJH1/7RIoZmjJ7ADqkIU5X32yO+R7NuFd4eZggWH9/y7r6FwLjtHC0aVOJIn6g/uex62UWuQrrba69cqclRvV7T3dbNw0NVZYJZ/eiqgImfEIVkcsYzIxZu3u+ozrhVmZWkmzpje3xsPp/fjcUxjK9apigYcC0gGNbbGSZj0FutnHGZuvINqhs/n2fjG11NVU1103mbNPNVVdW8jSPBB5GB0Dp6VBwE97GO40+FwbqrGl0+GNIAJJ3ubiT+msKcP4m+oDSpFtN7yS6oS4C5mAG2MDQbSdlIDZuxOMdpbjt09kuF63Xf4I56u5X26256sPAYliCD9mxhIeVy3ZgoVT7xBA6dDDlkiiwhrRtqb7m2kagwuzhMHgqVZr31PFq7kgkAZdtQLnfRdurfEDbbJBd6mpkue7qi+llNqulc8U0S0waKN5mCgrGYlKux6wfMAUAkAZW1XH+VSHProTE+k9ogSfqvV/+p6bWGoSXB1okNJyjuBbWZMfQLk25LtT7ptm5KOW4bJ27XVVPGaKAJNUNBUJULkUFMI80bEAN1yjzJFRiCsbhTpbh3F282nkM/wDyMQBvDZ2zSVyMXxI4im4crQQYl4sf+DQZmLZnRvlAapvbE3fdN2bdtc+39p3fck9HL7VcrdQ9FHS01bFgu6R1CwrFC+A/QpLBXBznAOunQdOY2Ikcxj979gP7enwXHzVphlJpdpIbpI6TAg9yuwVI5Tv5jtl6v22NlbXDlHCRy18tYjjqVJKtHiEalR+AKqsB3dwcCMwbSIqOnsBb1M6/l2ldipxTFvhoDWN3kku9AW2Hwk9CFltz8HWKks8l5te49209wiSMvTW+rNNFeI426vZGjXC9DgEKuAFfpbH4s2VsPTMS2ek9UtSk4TUp1C07xGg29P19Sq2BVJQWihrqSu3IlfUxmYUa1KJ+0iZh7JM0fYOyZK+91K/uk6bwmyBA+ZI6W9PkrsNjoacpImbb/rHQb7LtFBe9u0VTWVftM1FWAiPyXcvUk5/9YvvEN3AwDgDvkZ0GshuUD5D7C6beIicxPz/bX70W6Ulayx9ZFRCrEuIpMZjyckds98k9snHfUNG8FM3iBi6eG4YIOT6agoSE38QSDcDkHrIH0Pro+CieIQhm4H/i7fDUNHsj/EL6riG/blJUxb7hSJZS9tmhib49UNKXkU9x2VZRIMf4wvy0woHIZ9f0n6R8SuRjeJEl8XtH0Jj5GfUBA48qpqWk4+glh8qSG3wxySH1Pm0fVGvqfxKnmH5P1fPWrFU5qPnv+f6WCx8ExsUaAOzW/Vtvnr6rt/3mpGfMTpI/4uxGsJpbBej9/wC6aS7hoYGdJq2CJgPQuP8Ar46Pgzog7iQBuUI7hovLaUV1OYwAxPmDAHz/AC1HUdjqiOIjUFJ/tFQftP8AbqbA9T1jAOcfz0PCsieJAGJQH3NbF6gblRgjJI81e2NHwVDxRseZNZt4WSmVnqLtRRoACSZBgZ9D/HSGltCV/F2gyXQmMm/NtooZ79bhHjqDGUYOPXRbQPRA8aYBOb6p4u5rbKEeO40sis3QpEgPUe/b10vgQm/iYMQ7VE++qYAn2qEDOfxjtoiiCiOJDQlIkvVNDH50tXBDFnHUzgDP5nQFFEcUjmmyut0EgLRyiVfQFTkaYURsmHET1TSrvSUkZllc9OcDv8T6anhHZK/iYF5XAtw8oVX3q1RT1s1vSOGopZIWJAWXAdD8O/usM/XWylw9pF9/3XmMX7TnOHMdAEgjvEhPaflK5U9ehrbnQTUppomdUXPS5YjC49cjBz8jonh7SCAN1aPaaoHDM4RC6VNvi108UTy1sAmZVJj6sEA47/pkayHDXhdr+N04mdVrT8v7aSrgo5ap0ZoWlkfHuw49VJ+eiMG4zb+6y/8AqqlIaXX/AChbjDuShqnRKe4QTswDAKwPYjI9PppHYaNl0W8XaRYysAOQLMbgtunrYqepaXyUVnGXbOPT/r4aZuFMyFV/6hptdDnQdFnGvUJcxCphM3r09Y6vUj0/MEarFEarR/EyTEq5uTY7SY+OdHwBqmPFSEj71cntKcfHB1DhwVX/ABK1ygtciQep8nHpoeDeFDxQnVNJK9G7OkTD45UHR8CN0juJSYKaST0zEj2el7/ERj/TUNLdB2PAMhBMtPjKwqv1BI/lpfAaLqN4jukGoQdw8oH0kbt/HUNERop/FDGv5oRrPlNVZ+Ylb/XRGHAMEIfxHom7VMmTisrx3+MucfvGicO2LhQcQPUoBq5h3FbUn5ZKn/6dL7uCi3iTtQgvWzf/AMZL+qp/ppjhglPFHdUI19R1d6w/X9mugcKIQ/ijiY2QWr6n0FSDn5xj/XRGFtBSt4i7qgtcKn/+IjJ/93/46PgBH+JO0TZ7hV9z59Pj6xH/AF0PAASnijtioNMZcZPUfmde8yBfm3MYVo55Y/dSZlHoe+keRqrGPcd7J1HUVEbCWOV1lBzkMfXOi6PgiKrgZGqBJXVzlWapmJA6RkntpQGmwsgcQ6JlZOi3Fc6WJYfMMyAhiGyert6HQ8IAyr6eOeBB0W/bT5Xr9rT1TQ0ccyTx9DqWxj5fuyf36oxOF8SJsutw7jhw5JiZW103O17V45KmN2YAj3W+BPoc+usjuGN0XQHtVUm4TK5813+6JUeZDFGWhMS9BIwfg35/z07eGtBiUtT2nqOm0arDU/Mu+KWoimjub5VQvQfwAAg/hPzxpv4XTcLLKz2nxLSCNvvRbfP4iN0yRPEKG2xsc++gII/LWdvCBrMrdV9r6pEZQsdaued324yrI8NerennDPSf9NXVOFUzBbZUUvays0w4T6rR7/yFujcksstbWEK+CyxgqGwcjI+mtFHBsZEjRczFccr1iZstRSrqwzsZZASMHJ/XWksaCAsIxLuqa1AkqW6plWR/X3j8fz1YWtulNVxdJTWhjqopBJMaaMocxJApUJ2xn5k4x9NUmkDc3QZVIEaIyVAoK2aukkMRkVvMmlk7D0wMk5HofT56SGMM9Uxquzcyw1qqqh66eeYy+bVGedCzE9UYdOlsH07MBj6aFGne4iVScQSeYrYsF16Wwx/5gDg/rrVoIUa4ututc3FT3CWigp6SB5uhlCuGUMvwz3+Azk9jnHw9dZcRSLhliyUvIXBd6xVskw2vRo4UxwtXzRPII6CFWABZwQzghsYyMtJnA6dcPHNJfkAsIkn9N/2WWs4gBgJk9P1P309dhlutHYaGutEKJFDUy9VXMPeqKyXv09WT/d98BB2A7dskl3VBT/ltsPu5V9GpA1kmxP6enb9bpCbhmvcVRTXKuiYqUiqIEZlkuC4HREfXOVClguB2OSS2dClVa8w4zB06+vb19FacSctjH5x27n5rWtwWyxSU1wqaZqfb0sUrFKenLPLUyZA6VAJC9OY17HOABgHGqcWxjhpBOgG/qdPvVZ/KIHL99NQterrFfa2nt+057dQz22CYSyrUyqscRZep4ox/xEHDSMMksqggd9VDDvLgzYfcdhtG+psISPJNiLm/9z1Mb7WG8rpVBU0VVeuigFLBcGSJvYZCYmiQB0zGy9j7pQjBC9sZAHbpMqMLy13mOxV0gRk0/L+3ZJvN3mjNtNFNVxVKhpKRJPM60bPYh1H4T6Hqz6dJx3Iz1SXEBg/t+ytOJDQAXR8Vpl52Zt7fRvEu6be1fX3NW96emU3CilT3euEtjHYowAYL0DOD31W/CiowtqCZ2P7/AK/BY61NjnF7xc9Bf4D46fFecc1NLbqyrpKhXWWCWSKQMuMMpxnv6enpr5nVaWvLdIXPFSOWdJSZ1LZy7r2/Fk9u2e+i61wo4yLn6qa9i3parDs6335nlt1iSZY5KVagtLC5jziOEkZUluk+uOn1AJx7KnxKlSpioY9Br/hdKg8tp3JgfJR+3XX7k5Hrb7drdS10e3PvVqhmIykMs7JEgZvR5SFUYGcDq+HrwTSq4pwqEQ0mB6k7fdlixuIzuIYe59NL/oFKyDbdfsKOn29PUz27ZEjxxVFMK0wgVETdQMobqEqMVbCnAWRhk4YDXq62Hp0ag8SIG3T5D87LTQFSnTyUyY3/ADvJt6D8k/G+9ywXbcFp2ndhFcbw3QtO8KRQLbxGcyPjpKBssQgwJuods5OsL3io4sa6JuTOg/eNvnC6DOK1qJ/lamwHXr6Dr12W48eJRbZEVxtt8gnvM1MDU3eF5PbJ1LARoQCyxxqFChMAKPj666uGwNMsAbcW9SepI+/RNgca+i81HXfpPYaAAiw+7ldo3JzFuGSlpKNbxU1tVJUwvXQyTGZphC5dJi46ffBXHUCPgrHV1bCMaQ0besfW3911q3tFVLSZlxttP0vK0Wm5Y3jTbmuUK7uqvuqolSpnrZ2LNPUEBf71cnLARZbI6gOk9idVMw9MugWaPz/ssY9oMVTqSXai86/ZC7ztvnHdFEHuF1r7XcKqfqHSUHTED1K0QUH0YufdA7g474GurSwFIAAG66tL2rxElziIP5D9F1nbHOE1vmke6WnzJQhFGVld1pO3cqjlhkkjJ+Hw7aZ/CoktNyulhva5wJFQW9Tr6Ll24OY7rbpbhR0xlt9JWVDXFViQBYpeotM0bBcr1MUlKZIJMnbuMUO4cWOEXCw1fad5aQLEmV2ja/iEWGkskVwpay4UqJGJkaRQwwAFBAHfAAYE9/nqw8Oc4lwXQw3tY1oa11wNSt6uHiRo4Y7g9DSSVMjMBTIw6fLGPVj8T39PpqtvC322W2p7X0wDF+i1+DxNXGKEmos9NJL5gJIcgBcDIx+YP79XHhRmAbLJS9s7QW3QoPEtWQNO9Rblqesr0L1ACMZJPw7n0Gldwo7FOPbSDca6LZZ/E3ZBDH5FnrmqD+PqYYX/AK7apHDasnRbHe2VHUTK43uznmO52veIp7b7PVVUc6EknKHyyqBe/YEFwxHqO3w0/uDssFcqt7TsIcQIJ/b9d+3otdtvNd2t1HttLeQtVTLHH1MMlgIwpDHP+HAC/Qn561VcEHOM7z+v5rnYf2mfSpsa3VsfQC3w2Wwnmevehlh8+pWZkVe7ZAYY7/z0zeHtWk+07yyJuVpd/wCSrzcKueSnq6mGJ5BKPe7hgAP3dvTV1PCNaLhczFcequMtcRMLVTu29u2XudYyZHu+acdI9Bq7wWdFz3cVrnR5hZIbyuzRLEaqoWLJb8Z75Of6DR93ZOiuHFaxtmP+UKbdNbKVY1dR5gyGPUfj/wBHRbh2bBI/ilU3zXWMrr/XVaqr1UzdIA7sfTQbTaDoq6uPqOEFxWMe71RVVklkKDsAG0wYNlUcU/LMp7Hue4ReQUralPLcSIA5wrD46qNJusJm8SqD8R6rLtvy8CGSNLhWq7hRkOc4GlOEZotTeOVgIc4yUzj3teCGp6mvqauDocKskhIBPfq/PsDonC0wJ0KRnGqxGVzpF/qteq+Z967cFWsF2moaSRHQHzeoPn/EFH4T2/XGuZiqLM3NH6rQz2kxVPRyxNH4kt8Mr2y63aW6UkSNGGOD1A594/UBu2sVOiwOPVWu9sMSR4bjIH3P32WSm3lW3Zae4VVSPMZFJHmBmIHYZI9T8P4a71JjANpXKq8TqVYcTH9lsNs3BJA0UjsylAWTLZHUSCMj6YH7tO6nstdDGwRJ9P0+Sztdu2suVsnq5a0e1NUBcM2WCH3j+g7fu+mszcO1rgFuqcWdUYXk7wtVrb1MsaO0x885J6Se6HOQT8j8vrq2nSB2/wArn1Mc4DW/6bratvcpV9qjcSSTed0jodW9FC9IX6fn+ekxGBzaLo8P9o3UxzH7H3qtVr92Sm6xXKCSdpU95W6sHrznORq2lh4BbCwYjis1Q8FNZ987iqZkme51Ucih1Lo5UnqYscn49ydIMHTAgBLV49iS4OzQeo7rpO2Oar1b7FdLVcaiWtYxkU8jH34yc+h+X01mxPDmkgtXb4Z7VvYxzaxnolWblG4wSRVMlTUtEgR3jDEKxCgNn5ZPx1KuEaLAXS4T2jeLk7fpdbXtjlm6XXdtZLXTiloJmwIh38lekYA/I4/edUOwIZTuZK6GE9pqlTEmbNP0TPc/OtRSXFKWmqo4qVHDllOepOoAH54x1A+uNZ6eGbqdSmxftU5rw1mn6WWHh8QEiXdleoZqEtGHUEM4OO4A+v0/8NVtpNIlQ+1MO7LpFw5z2/RTqPOSeCbHs656WORnJz6fEfnjVLWSYGq6dX2ipsvMgrnd150uy1FUaSSBYB/d9OGGCvwP0bW6ngQW3P3K5GJ9rnhxy6fNLtfiDqJKcLXQQvVo2SV7CQfX5aepw+8BJhvbC380XH1WcoOe6Scyirt7hVZj7j+i57fwOqHYJ7QtTPbFjjzA/NNDz/DJVSRrb4ooApZWeTHw+OmPDzqT9E3/AKvYTlA+q2yg5b2/XWwV88slJJjBRvi4HdVP7tVVsIWmy20PaOi5mfNC1qTnjbqYIhqW7EdPxz+fy0wwTyVnd7XYeRc3WtXDn0TJMLZTezyeXkeb397PfuP104wDtSVhq+2Ivk1/Va8OdruGklZkZfdAjwMA47nOPmPTVz+HjZZme2L4n77rLWDnsz1awX6Onp6foJ81FOeofTSVMAADF1bhvbLM7LVsFqMMZMUg6zgJ6/Dq12XXErxrRKwEryoTkEDJGqS6DKAtor0VTKBLkkj09NEWPdPnJF9EWSqZVHTgHS5jCrMxKEalyqqTg/HGnJMwowwLIfU5ck9QbA0GtUeDMrKUxeX3cHOMn6auYQgDeE/WOQA9m6fU6BbIVjWjcKjE4A7Y0ewUDTureXIAMgg5+GnbM2SjSClKkuS2Ce+NJAKEEiSiBZcjA+GnywnuDISuiQ9gp+J9NEtMpr67q/RIf8Lfu0blTMd1cJJ3PRgY0gTB5TeaijqjF50byBG6gOogEjv3Hx7/AD0xaNQkcJEFAqYZfb6GZeoyZZCMeqYy3x+YXv8A66Q07iErmE3BWJvlwqLakERWNgxyreYVkLKchQMHuRkZ9M+vrqis4thQOO61K/7wv9PTRR2+1wxVwkLtJNKMdAOCEjXu7+8vYduxJ+WubiMRVAAEW+vpt8UrXzcj52XLbWntNlu9Zd5dwVVTcYOuOplJVamXLFxGe/8AwIekYAy2Ow1jpx4ZL266LO0kuc4n6QsXXrStSe/NVzFyB1tJ1MSRgYPwPf4HSuazLAGqQSRdMlhoIaVqWkSsjmwFIgchzj0LN+IDPxzpfDaRDR8EGOgzP3+i6LtyxrfUqrhc6eJEpvLEKl+oQhkKlyenAYD3sjH4h6Y10MLREF7/APH3+6vDQ8+n5/fxW07G+6aKOVjM1bJ7RIIOleoShjgSAYHcqoOfiCT89acAQ0Q3WFbADuY7/VW3TTx3Guoq2Ww09FTxO/VcHnMDoWwqujIDIpDEDPYHuCCNGux9Q84EfGfkP3QqEA2Bn5D5/wBlowg3HaEu8MFPDUxwzs5radGl6zkF2kjXuFPUwwA6Ag9l1zzTqNkA2B2F/wDPog5zhdwvv97BYe7z1KV9uvdjqqWsqlygVATTISOyMoPQykFvVgy5b9ctZxzCpTN/v77JXOcAMwv0HRQO5XnaXf256sW5bU8tQJWgUhlRyilsEdiM9wR2OdeC4iT45J1nZc3FuyvkCB9/fqtDWVXAhPmRp09+/df1/U6wvMaFVA2hb7QUg3zu6gt0c89HRyRwmp7gNlUQSCIemS3UR8gSddDDUW160mw1Ue6SGabf4XV67blBabPsWgo7zuKmp57jLPPEJy4hSKMSM4i9AynOGyPQnHx11auHpU3Ma3W512Hxi/otQY4MAB1P3tJj1hbTdXu9LTUkldeKe53auDMtLV0iTOIM9TO8nctjCKQvd5GEY+OttemWuytccx2t8Nr3sNJNzYIl78niG42nXvvAgXJvAsLlbhtTZFZZIVr9w2WhvNNWIkjzRhjUQOF6h1YI6jnIcA+7jpXOMHfhsA6kJdBB7fv+e/0TNE87xrv9f2tt3XVtp05padpbbSUd3tsaGCeoM5pz1ozEKYFICtkkFsDJwDrqUAWXbEd9Sr2U4MCelrBbm8NHcbnWSCKaScUphkcv5k02TlmYMOhUAAUYz3z6+utzcriXEffqrBGYHf727fFaq9utdlStvaWanksdV1RCKD9onQV6FyPicgeox7xznHauo0UxnA1VZpti/lC2uzCC2TPVNTRzwufMjnjPWrvhRlc9ycd8gYHfuda6FQtMi8/r+icMynmGi6VLTiogCNhZPxK2TlG+Yxrc5oPmVmcn4rCXSKaBlq45Xmakj80LI3ukZwR0gY7r1An5aqewahBxdE7BKt9PWWypqYJqmpqaDI9mxH1CJAMBCw7nHzI7jHftoUmFouSR+SAJBgrNRVBnUsiTLH3wXBUk/QHvq1riRMJ56JWTk57D5Y08DRBsKicg/P4fTUeYSHWUL4DJLZI9NSSDZM5t7rVbgcW6tqx3JglwB8UIOSfrn+Gs73Qy6ryzJHdETqEVLOgTGIQ+PgvYKR/X6flq4mCkYw5RHZZoAjIYknv6/D89RwiE9zrqkgZyRnv8NRx6qA6JHST6Z04MGTogJBkK56h+Z0Q4Qqieqsw7dOB9e+laZunIhIIOQRnSuEWTB15STCzD1AH102hQifRNzGVZhj0+uki0lUOtZJYZbPqT8dEmBKZhKwd6eSKkkmhfD9OMAnJHzGPiO/prJiYySE7uX4KPlzrJ37SVSVtMGCkkkFcnsO57/mPidcCo+9zKyOeSJTOjeWmlgWKGR55IlX3CMhiSc4Pb0/noMkPhok2VbXTE63W+22W4Fo56iJqZGdQgcnqfse4GPTPy/frpUARDnalMXE6aff3uuo2+rNQiM1RG8re90g/hHp+uulSeDotJe7RZA9Y/C3odWC9lYHE6bJLF3x1OT2x305aAla6UAqw6hk6BIKl4ukOrepPf1H00CQEeYpBDjtkH9ex0N5QI3QSzp1EnAx8/XRgBVtkGFQnlCYWQ4I740jssyVA4gqo62elczrK0ZAwWzoVMsXVjKjmmy55uOtt8nmzPWypUsOtShJP/AHf+vmNcjFVKYkDVK4ucZJ++y5ib7NFXw1LOA0ZRutsDrAJGO35/r21zRWi/3os76hhZNdyVE1VFNKQkeC6s6jGSe7Nn6/lnV1F+UybD8kxxBddZ5d4VEZiFUyr6qG6uoYHrjHYD/XWgYyDc6qwVXEXFk9odyEUpqk8hHZuoL5uG6c+g7flqxuLIAEiUtOruFsEG4IJOnolJYjv0nOD/AK62Cu0+VDNe6LLdYYjG5k6g56Rj4nVjnicvVHMfMU7ivzTQx0yyHyUbrCn0BI7/AK+mlY4OdJTuxJyho0TYVUZdlyAA2Cv1+Wm8TdVuPMqWQ47Me/y1adJKVpIEJBLY7ep+Pz0ROqbZNz1An0OhE6KuoTEFSkSkmhomSNfMYjLgKSD9Mn46BbOi9JTaW6haTXwyxTANnJY9sevqNVmQLrORuU+tFI1RJKwAZx7qjHocD4f9euo3oNU7AbwntVQeYyRrGI5cElcAdOO+dNMGCo6naALLFNTHrnToGAe59MfPU3sqsuyUacdYLIWc+v1GpJTBkD1W32SytMpldOhf8I+J+urmOVjMPN1sa2OMEHo/XRD9Vc2hbqEo2RM56f3nR3smdRvEKvuVcN+zHp8dQuEwFPBaLBXFlQEHyxgabMEooC1koWNScdGPjnQNS6IobEJvWWr2enllRAGAOMn00HxEoOoxosDC6GSR3AK9IYA/H8v36TxBNkKbTvYLYqe2JPGHCrn44+B1aH20TignQsqgfgU9u3bULwSoaN7oYsECuZRDEJSMdQXvj/oDTBwSHDg3IumlVYZ3IMUNsdCpVlmQ5J/MfDGe2NCehS+ANwCuM8m7VqqG2tVUEyRQpEyOBEvQkJH4VOQwPb1JJPpkDtrkcTw5NMuBNlW6mWw77/yuLWmjrLjsfZtLVUT9Bp1w4kLdK98Nj0De9nHbA9flrl0qRNMDaFjL+QSNVgrjaaqkZUf9tDHhS47+YDg9QGMKO+Poe3y1Z7sWkhZ3TmundltFVXeXDB1r1noZhkszfIH1J741fQoOIyhVsBNwpD7K2xHT22qWuSRlkkDTRdukQIQpLZGce5jA9Rn1wddOmMrdL6rqYehEytts/sAoa2qiSlSUu4iETJ2RZGZQhOM+6w7dvT00aWIA5SbraKMEmNFhNw2sXB6dKSTcVjmkm/bVTUb+VKO5AYDI6QcMCCO4HqM6pq84BAIHUKurTvDTJP3C0Lce37fS0VFVV++Ku2VM7FxOsCoXwM91IxglE+I+IyO+sGIYxoAeXT99lPCdNnCfvvuuTbj2+s9TLUU1wo4LoJQ7exNI4qywDpJNCepiOonLABssQp+XJfTDyYNx0+/z+QVVRhZzCwPyP7eo+ZUKuY+g7ohljohb5moqcyjqyJJUDI7AHuoPQPdYBlxgjtk+R4sSKpJEH7+RXIxZjKP2XH0yS5GC5U9QI9B8v5a5eljcLIDNzqupcd1FwpIt511uq1paiKgjcP1KGXEykBervgkAHAOQT+eutw3yvkxp9/qmpm5LRMD8vvutu3bcKS37ksSVErVphkmLJAQvmnqChR6jBKgZ9CD8vS3EYhoqgi8D7/daahIIDrX/ACif2W77f6iLjuy8xVFZdpULUMEBY+0FB2EBf1hiXsrZwD1vknpOulhmloLyJcb9NdT2HTtYaqM53Eu0HS+mw6xqep1sFJDY8N2vFvo/vi6LIVgeeWKNVMU8UoJZEGQCUOcv1AHv0jvjXosNSJZLnT+X+PqVsw+beP7X+M9dguuHbVBcqGmqY5qOsmSLMdXT5TyAV74KgdR7EfzA+PefSY8Qb/eytZQG2v3r1WLpdkpQzWyK1XW70UaKG8mVvOjIDD3ZFb1PvDPf4DOdVswbM3LYhVmk6JB+ff6rI3LYt9uLGpmudA6lw/RFTtEH7EZbue+GIx9frq2pgc3mcT8v0U8GqdYA7T/dPLNs+ms80i01A8MvRGrftupBgZGB64GTgegOrqdJrRygBM2jGmv3Zbi1NIEGVOCBj66uc4BO5p3SZ6B5oHjPYMpXt8M6jmiCmDCBdaTHV3BAtHVzUsUgUqpGWaRASA3VgAHtg9vr8dZg8xB1VJcQYP3+SzVvqfbSR0FT/LVtM3gqNM2WQkidSMA9s98fDTv7pssJSQM2O2Tn4j102VQtg3QpYDGjuRkKCe+o6YVZaQ4brRa6UrTXCnCRiL2dpFwx/Hgg9sfQ/wAdZXOM3SkgS0WT/LZaJUBRURweo95D6gjH/Kf11ZN4OyE7ffotoalds4X9flq5ojVPknVC9nk7kqc/HRIjRAiNUkwP2yGB+OpkR1uQkGnfP4fy1A0pXMkwFXs7+uCTnUIKbLAlW9nYY7H5Z0IKj2DoreS3ftpiTCA7qxhYAAgHvnVGYapW0iRCbSxMASA2PkBnTkyLI7zstLr5bhRqDTPNFT9R6jMFzj+Y9DrFXLgOgVMGeqj/AH1fPFyeFGJX3XdAcOO59MYGO3x+uvOVwSJjT76rPU1IAv8Aeiw1tq5J6gSI8kUgjVZCrAFh8QM+np66Wi8lxJ/ZVadj9/VdGoaK6ys71YqmmPSyHzQytEfkwzn9NdTD0DqIn1VjiZkrp1kp1g/YGCqp1znpePIb6574/hrsYYHorCLLaBGyqWYD49tWPd0VrBuVjhVhixVOkAdu/r66rbVJunkGUaJi6dRUfu9dWEXgIt0ugzE9RXvjHrqsEg2UDSDP36pnLI2XGWBwcarLiAowXusTXNKWjHWAD2x/ro1CZmbKoHpumkNR+07ZGD6ZzjVYq5gltKfTv5lO0Rcr1np6gPno1HtiDqiTC4/ebWRUOsMlTK6g5JOAPn39AuuJXpRp9/fRUPpkGBqtEMzUFVCZFikiDAyKigHo6hkd/qFPf5fXWRlTK4T8fvsqKjQJBVXK4moV2dBEQf2cncYHf1A9c/XVT6xcJKsyiZWtvUZWNlkKrjIxjC/nqrxbyTZUOBygBZWhmikkPnt5XT+DucjPpj941ookCxsmZrIWxw1FQlLdpmqTDLCBIjKwZJjgYz8Ph2+PfWjNyZgfT6Ji4zJWdqaipqYjQK/tFRGyvI6kqIsjII+vfIH/AEdThmMTYWVpcctvvujx3D2OGDDPPHBKYnf4qT2QN27YBH7xqw1riDO3xSAFoknRZWrb2CuRJ6yKRZEMgY4VUK4zkD5jsPrnVheKb4n7/uUwpuJBO6PSbgjjM8cqqelxllbOcqCO3r8fz9dWUsWAOyI1gLKyX+2COaQzAKgy3UMZ+gz8dWHHgNJTubOiDNd446aGqjiZom9VJ7qPgTj56sqYiItKqAtKlrbuUrRJ5qT2qpMMkhKooB6e+MfqQdYBjl7SnWZBEFYq93i2XFPMjpKmlSIuRIUJbHqAxx6g/v04xYgrNUa1wkCIWT23uCxWM1R9iudQzBRnoOQe+c/oRouxYPlVuFDG+afkncN82Y90r7lNS3h2kZTEmO0a9I9QfXJBP7tQY0RIAS+FSzOmVUl52S1TWVAhuhd2QgFMYwMN+WT/AC07caJmEHUqM5pPyS4Lxx+9zklxcDEsGBG0ZOX6j3x6DsNO3HDpdOKFEvubLZ4d47JpgsEUtcnfABhwNT32dlo/laA/ROf7b7LAGaypDntgxEd9IMZuQpmpdUld67TZv2k0qJ8ynb8/XTjFEDRQmnMk3Tpt5bIUsHuMiDvgmP8Afoe+jQBIPD/qhX/tpsYKri69St6YjJz+miMWBoEWilE5kSDeGyZUMjXYRDJ7MProjGC0hT+UbhybVe7tkzpJTLdisnYf3RIPz9e3bTe+73hK/wAIWDgtRW47RS5BjcoEo1QuQgL5PbBCntnuf0GgMUJsqTTpz5ltkO+NhxslItyqBIRnvD6/X17aAx3b8leH0tnfRKHIPHHnR053DCKhvRSBn+f8NIOJsTkUv6k//thsfqEf3tICQWA9nfuBjP8AMasGNHT8kXeHeXfmsLfdx7YuFC1LQ35qSoMgZW8h8lVGcY+p7fTU97bPMPyVFVjS2GuglahvjeGzq2wpRQ7npYTKpWYLTyeY+OxRVx6nuO/YdyTqivjWubAn5ffxS1Aws8wH36Lk3Hdw2jbrdX2bdE1LbooJGWldFLMYXJkVgQMZUuVz8lXWbD1wxuR1/gsOHFMEgmP73TDddy2neLRd5orqk1zilf2aOnBViAwAZlIAMbKuex6gSO2mNZjxBF+6qxAplpv6R+3RbHxJSWW1xVW5dxXe20s5hEdJRSEhyAPVjjC9Xw+hydaKdRrBM8xQ4fQB/mPsPv77qQkE+xp7PTUNduWxM6qgneNygaUDLEHHzJ/frW7FUwObQdl2G0mlpEj5rkO5a7blqqVq6Gu2/faLq8qQMwLBScBhkHAXsPyJydZKuKaILVjxFFgMmHD4fBVRwWK7WFzFfKbbSKvdTdmjkK4I9yIEhsAnucDvgA9tJW8E+aPkb/lCvplzmSwkfEf3XP8Ac234/OSd95y1U00YnZGq4SyxkkeXIzDJyD6KAScnOufiBTuJv8f7z8SqzhqkXdPymP0+AWj0+06LbyyDdNTbFpZqUPE9vqqcSk+nQoIIDe8ASenGARkEYqaadIZXHNPr9/CFko4PKS88vy+/rZRP8SKUVRcLZXQ1lZUVcUs0IiqHLypAyo69Ryyj3i+Ok98nsANeU42QSMoP3t8Fj4i0RmmY+emsd/z7KKmFHmK5Bz+E/EflrzxO65TQCCQEaCrqIjJHTTSRiZfLkVWwHX5EfHVhLgJ6JC6SY31WRp3aWqgknpZLiqxMzRsOxQe78PUAsOw9fTV1EPJ0lDxBI6D7/wAqWnBtLW3uWVb0ldc62OJPIAdlCU64VveYdPuZChAQE7/H09XwWmSIcL9/v7Gi20OfzHTQdvl9OuqnBatqW63LbEtlBC9InuvT1WVjyACsyspHQ4Kg4VTnAb4En1ocJsAPv812KeCaACBP399Vs9LQNBb1SrrqWjjjVkRfbDKUPUTlwelMMT6jI+gzq1haACSPrb5/stTKOo/Mj7+qz0FkpmNBVy1EMEETEM5mAV2Y4zkHJ7BvXGSew+WzxWEg9EGYYwCQthmqrNCZKeKqhkZQucOAO/1zonFNKu8AAW1Q4KOkqJZT5qqpIAOfXsPQ/mdWiq2JGirNA5oCu9upBUpD7bSxyNnpTzB1EYzkDP0OlOIpki90jsIdAsgtk7AAg5Pr89O2o0XlHwSBdc/vu2fKnRqYlGVsAFAwwSM/pk6qeW2IKzVcOQZRLDYJj5UjIoJBbpI7sufxfro0y0KunQMytjnsUpAwMnOAP0zq7MD6rQKLokpC2ryFHmKVP+In4fnpXVAAkGHMrSdyXK3wUtZRwVlE9dhlMTPgr2x9PnrFWxrNAUtSmbxdccqLoj0VVNJG1TK8QiZgThSAMZ+A9Dj8/prIK26x1A0tghZGh3lZInlerpamlV4TT9IBcdI/CfX1yCT+erG42DIbH3omZl36brudtpzcKaCtiR/Z5UV0yO5BHy/hrqtJPMQtTAHbWWQa1EZPluvz7acOj1UdShNpbY6qXWNm+IGPXUcbaKeFNwhU1CZ06zH0kjOPiula6PVRtKRbdENrZCxKMqjuTjTZxElN4V7Jt7EhXzV6WTvkj00ucapBTjRDFArIGRcg9h29dAPE3TeHIkBYO6RCCLzo1DgNhgPX5Z1Q6pOiqq0iGk9E3uHnwULyRqnUPUjB6M/DUc87JXMgTC57uupd7bJb6lFhqB73WFwenGR9BrLi6kiHHRUuECIhcKvtXAtBMTIwiZQi9K/DuMnH5/rj4a4eLcYmFie4BYvY6UU5rY6mNC46QS/p0f8ACPgT8f00+BcMv39/NZBTBd92XbbZte2pFBNQ1T01RGWPQG6Uf5ggHsMYPbXZbRaIdELd4MCxW+WuipKfrla40jsTjCydsfLuSdbKeUWVzaZPwWUrFojAeiqpST2IEgzpqjwQrgzc/otKlenjMiGeLPcD5EEjv9PU6z5/msrzYxqs1SVFB5KgVUGST2BJyP3avD2q1lhr9UOR6RpURZusZ7kI3b+Gg1/NKgAN5WKrZYlmRULuXGMhW/01W4iYKre4DVNaxIOumJZgC46j5ben07flpKj9gnBEgLX4nAd5GD9JOfwnWcGLKi030Rq2qEdMDTF3lJAPu+h/X5aeo8uEBMYAkBajUQRvN5M7yVDhzIzEenxPyGe38dYS5oMnZV5XEQue1lLHV1JjRGkjOcg+729cdXrn8tc8sBEFVVGkrn1aBRPJA5cKMhVc9RUEdiMfmRrA8ahUOACeQ27ogR6kNHG69QY46WwM+vz+mtNRmXVI1hcL7pFNRSLHDM0bKje8pPx+A/TRbSIGUjuka0EDus9b6kxzC11kkCU8sweRmXGQADjI9PQA/l9dWsePK42ElWAGfW33+SyVjqfJepnjpZzA7mRTkABfQDJ9ewz8u+tNAmJIj+6uY0TIvP6Id6qaiOSqnoY1hDr0VAB/vxj4qPiPXOs9UmTsEa8i7QrrWRpbq1UEVZWSSIkc5kLNIpUEKM+hGTn9c6dz+TIwXJP36AKum4Xe4yQB/gfFYKKaWllMDhFAUgqT+FwME/n3H79Z85E/RKI++ycNdpKxko2CEIwYFEJZiB6H9f5ac1C4+ieZELJSXqeShSJXgiVlPf3ursc+vz05xDoElNnABDVucdbLAA0N2oIu/YCZu3/XfWQlh1P0K6rXubvb1To7guhEim/wMp7kee2CfXQmn1+n6K9uKq7n1ujw7jusYcpf6aHPw9oZc/w0XOpxr9EfeqomHfVWS+XBQCL/AEwbs3+8sD9D6aBLCNfoUjK1QA81/VOF3BdC7dO4YPTJIqz30/JP9irBVqkWd9R+6NFuG7hy8e4acOwCk+1kdvhpszIk/kU4xFWbHbqE5+/ryW8w7ggZwPhXn93rpQ+nP9ioK1YjzfUK73q7GML9/wALL1Yw1ZnH5ZOiHMiAl8WrHm+v91f73u7sQb/AQRjq9sz2/f8AloFzNZ+hQNWqfxR8f7oXtt0EhdL5GZOwJatHYfq2oHU4/wAoF1edfr/dOxeL1lT/AGgpSQuB/tgGPp+L6DUNWmDE/fyUFWuSId9/NWFZeQCJL9Svn/8Anl9P/i1Y19MwZ/NPNYGC76j904WurpQ3m3iFu5z/AOkVBz+/Vni0htr6o5qs+b6hAaS5ZZhd6EnHfNcpJX8gdQvp6gx80GseNT9UyqUuEx9+vtwLKPw1YywPzOdL4rSdZ+BSeG+J39VjnsFSrZNTah9PaUwf46drmTBd+f7KirhXnQfULO0ElZRYjeS11qgYHm12OkfIEMNTxGCwIj0VradQWIn4/wB1sEdwjdBJU0tliQdQBFeSQfmPf0hqDXMPktIY52rPr/dNkhoq+dZ6yagmpg2RFFcPLWbB7EhmJxnPx7/LVTnUyZLvp+iHhA3P5/un4NhlnDLb6CRY1KEi4qASSMYy3cDpPftq04qXSCPkrDh6cxlt6/eiyAi230tmht4Y/A3GP1/fqe97SPqj7rTJktPzCSg26Zik1BbkHwIuaen17/TROJncfI/sgaFM+ZpHxH7p9G20TlW9iQepBrgw/wDm0TiImD9P7K9uGpGx/wD7f3V3Ox3ZDI1Ew9QRKWGc+vY6Y4k6qe70C6+nqh1L7FCkkU1RKo6wqu3Vn889j+Z1W+uYkBWOw9DQmVrFTUbcedZ4qWnqJSuAH6gI++Ookn3vln4n6DWYVHF1lnfTojS/zWn3iLbMk0UoaWukUjy5FmB9nlPxXrOD2GD275/dU4g3ET9+qqc1h1n4XXEOUpFuu3qu1Udvt0LRE1RanjypEXmE9y5KN0soOOofDtnXK4k1zmkTIWKsGZMgEH4/S6iHJIxVOsIqA9OMd/z15wNXGgRH39+qIgBikdmjJXsO/r30oB0+/v8AylFEGZ2We2tfIbBdDXVFpobxB5MkJhqPRSw7Op79LKRkH8/z1oo1XNktRo1Ghwc8SPkp0cSjb1x29DcZa00VCpJo0mjUED1fqxnOX6vjgjGvWYBssDr+n5ffdd/BeE5sz9nVSGhu+2HgAEtqVGUdWO2f1+Hprp+8O0JXRY2jAiEj7w22hUNXULqcDp7Y/Ptoe8OmQSnNOlaYKyH35YQqqau3dA7qC/b92rPenExN0zWU8o0hMXve1pJc+fQtIyeqlvTPocarbiXpPDo6GJSIb/tVY38qqpkjjOcdTjB+Y/8ADTtxLxr+SIZSvf8ANFa97YkZap6mkDg9QZncEH5/z0rsWQ2ED4Rgk/VP4N0WieJXgukJQEqM1BUjHb0JB1DiXG6Zj6ZFj9UtrzbZHjleuhkbuATUk9j/AN7U97dEzdDwWG5P1/ulG5UJIYVqhunoBWrPp8h72g3GGdbKCk2JH5/3RVukSqojrZSAe3+1H19PnphjCN1BSAuT9UCoroqgAS19YASThatgO/66Hvc3N0SALAn5rX5LDtud2d43kkPxapJ1DiRGyxnBMJJJ+qsLBtxB0Is6r64FQe/6acY0AjROeHU41KT/AGb23gkwzE/WfOk98tsg7hlPWT81sdFVmhhiipblcI4EXCp55wB8hpvfiTCvbh8rcrSYRnudS8gc3W5dQx+GdgMY1BjDEqClJ1MlJe51DxNCbncGB7ZEhyPyOndjj1TimRYEpkJ2QuIq+4xhvXEnc4+GdRuNAsVUaDW7lGe5zGMxGvrCvzMhzojHk6QgaX/Ipl7RIUKrX1PT64J7A4+mp/EHE3CTwehKv7Sy9Q9ulVT6goGx+/RPEjoEPdrarGVTRnM71x6vn0j+WlbxIjVVOwYI1SkcOZmNapYucExL/DTt4q7QFRuBBOt1iblT+bHJNLVo5ABI8kfD0zjSP4kd1U7BdSuN7rp3eqiijlEtHNGxVgAAzAdRxj64/edYqmIzGTosNfDAHKNPspjtF5GppqaKoSB+s9Q6QfXHcn5diO3p+ur24nIICy4WmHT69F2ihlm9lREukYjyMq57dXz9e3r/AE1YeJtK6owsNsVlhV1ixp03AN0/hCSkd/39tWfxMba+qu91Kv7bXFmjaudU9e0xwTnv8f46J4iDdwQ92qA6plOjSv3rUfHqWc9xqe/jYJThCd0IRSovRFVRxjBH96cD8vlqw8RB2Q9yeBAP10+qGwqFRitREx+fnElvppRjmgQGqPwzv6kMx1HukFDntgynIH7tMMa2Lj6JXYSobbJm8U3SzMqOo74V/wAR/dpvfGnQXS+7VAYOiQfMDKPZl7j59h+fbUOMB2S+6OECEOSXoEoaJGA91gMH+n5emmdjxEAIOw7gZOoWFujx+R0ogT/i6Rkn8saz1sWCdCg6k5q0GrruppGngcOTkEeoOfTJ9NZBibWEkrI4RcrSrwlPVR07Rl/aVdo36u2Qe4z/AB1SxzMwOizVKQIWw3NOq1TFY0RGCIo7fT4Z7emratSRGifwIZI0WHq7pJDFBT08iiPoHUCo7H46Dq5J7Ks08oAWNnuElW0MczKjAgda/I9jn9CdK0ZvMdlXmBIXVrWtGtvgIVhmNS34e/7z+Q/TXS99aLLZSoENCKRCKoBIpSGiIYBc5GRj0OPidI/EsJPdO6kcwlantigpRLdkkaSSRJTDFhe6L8x9Tgfu0mHrMbTl2pWWjQBeR0VXii82tiUP0TmWA+aF6cAlhgr8T8fl/LS1arSdfuFKmHdtrb8/16LH26mpaaKD2uZY1kiMmcdzlz8cfIDTtfTA5tbff3qgKRH1/NImt1EK+np4axFo3Rn6s5MeMZGfrkfx0gNMuM6D7hJVoukAan7KxRupKksRn0AxrhNrkmVvLuqTHdV6sNj1Pb66YVDsmDhMlKW6HsQCwJ+B9ToOqO2SgCISxdQRj38fDA9Pz0PGOqBIGgRFuYHcFmPy07a51TEAx0RBdsqAY8H1+Wn8burC8dEsXIAk5Zjn0z20njlKDJtqjC54Vh5nxwAdBtS99U7SIVLdVLZ62UDPoe2nNbYpRrCL96BskN8/jjGh47tFHgCQrLcyWOGYHv8AH4fu0zqpSMjbVL+8+4PmfQaY1yPRORzKluhZinX3xnuP09dAVpOsJwbSri6lPdLqSPkNMa3QotN7q4ugGR5gA/I6Bryqh0KuLsrBT5gUn4kaBrEaJ3EEIn3ngL7ydJ750W1r6oF8RKX95MPQjOP+s6hxEmSpHNCItycjCuhPx7+nf66nj9EwCFDcpctI7Rgk9/pj56jaoF5SmfNCP96liSDH0fAjRFcgySrGKvvVveHcDPbv/I6tbW6pASJ7IgucmAACT6g57fv0DXlFzoMq63ORQAG6CfmdQ173UdmFgrNcH6ivUwAGPX1Oga0ptJHRAF2IIVTIX75wMtkaXxSFA+RZYm4XFe0gRDPnIU46i3r3+A/mc6qfiCfKUTGqxLFHC0hRyX60llZsk9R94En/ADE49NZtRGiRrTF7/cqK9xt0tDJVW+Yq1RTu8bEHIJUkfx15iqyCQViqUy0EbrCIzBJABgAd8nVRcAJKw0zYyntIplKhnWMMQCxGfX44+Or2NBIBFlax2kKZG0bzB9y0UFIfKpoEEKp04/CAOojv6+vc9s69fh8QHCNIXRoQGQ1bZ97KVJ6wAe4yNaRWOyuFQXS1uZIB6we+iK/RMwghKFy+HXH8wDompGqIcALqvvNCvZlx+fpovqKB0CdArC4gAqHXqHoc6DqpmyJuCBqqa4A9XvKV+p0xqj4oPM2hL9vBHwC5z2OMnVZq9EriJ0sqeu6my2B29T2xqxtW2UoF20IYrQMZCAfnpBXugIBslCt6mYjqBHyJGnc9twUWiST0ShcJUUKkjxpjAAY9tKXgm6jifRE+85B1KJpuwx6n+eiHjWEomUP2+THSZpcfLr7emoXCYKBdAuqS4SgqUlctjAOfT8tCWzdWeIbE3KprhO5JaplDZJyCf6aAINygXu+ISlulTEcLWVHf/nP+unzCJAQDyDqrtdas4X2uoA9cBsaSGnVWl5kd1YXOsHQBX1R/Jz/PTBrbiFW+q/cpQvFYo9yqk+Weo+v10sCUG1NwUQ7guTABKt0GO3/WdMQJmLKzx3RASfv64uAwqpAw+THJ+v10crSj4joMoE14rqmNo3qmAb45xqotaDBVZrOIsgLc66FWRKycLnOGlJwdTKxAF40KWbtWkEGsqe3c+/6nSmm3oi574sSmDSRzL0zNVOAxYKJMAN9O3b104aBdVuYCZJshRLSQt1rTOjeh/aHuNMXKvwWh03WQiq6VfWkZsdu8rY0CRrAVoyzcW9U5S9SR46YX6QMAec2P5/TQaLK3xpsnibpnUJmkiIHfvK3+uo2ofwwrBiNzt3TyPe9RHgm2Up/75ydMXPPLKIxwnyo39vajCYtsDfP3zpS5++6uOPt5fqlf29JDB7Wqr2wQ/rpvEfOt1PfxplSv7fxKc/dcvoQT1/DSGq+TpKs9+aNkob+hC5FBKO//ABaYvcdErce0GYQf7eRE/wC4OSfkx9P3aGdwGqqGObuEKPfcPSA1E4cfEOTnVbqryLRZRuMbNwgS75p5kZJKGZlPb3j66DXvgWCr9/aRAC16su9BUFituBUn0Mpwf66gc+ZtZU1HsI0+q1apjhqaqOoiSmpI1wfL98gkfPt+WmzScxMn0WF9NpIIsPitka8CSNIpBQrEo90BWOP3j+Gmc4m0rWasi4ED76Ko7lbR0CemtcuFwS0Hcn88as8Rw0NiqgGEgPATwVm3CQZKG0Kfn5f/AIagrO2VoZS2ATmC7WYe4RbadA3ulWPp88Y9fpqOxLtSforQWDQJ01zsknutUUDD5Z9f01WcRInf0THIbEW9VZqu19RKTW/p/wA+D/LTmsIglTKJkKhPaZFys9IT9HGmGISBrTohlrPIuBNRsfT8YzqOrkiUxoNPqm5obSclVpwD3H7Qajq3VUuwzIC4K1Y6pgkZPfJbBx9fl664MyTdYQ4zCuayGMN1OAwPxHYf+Gg2oMsFWUyDYokVUWieTz/3Edh9NTxRo5WC4JBRFqi3ZHZx6sAx/npfFAElLPLBRDXFGDuXMZyD64/MacPRYTN1b2spgmQL2B6cnH7z20wqSICa4vKKayQdIBdXb/myB/1/DSmpN1DVdaVda5znrl6D1EZB9fy1A4ItfaTa/wCiLFNIclZZnOPzHp8dQVAiGm8JYrC6NlvLbGfUHPcaHifRR1UESrmpdcEsc9+3SNTOEhqGQdv1VGpk8vIl6TnHYafN3Vuebj6Ia1cgMh6ijY7Er2P6/HSmp11TTcwngqpCiu58sn0HpnTZxoEQ2RJSRXBc5mBI7AAHTCFUDHmVNVsD+LJwMlWz+mhIFig87dFSVnV36kjb1PU2CR+WgHgRGqg6I61pynvg57DDd21BVumJhI9uI8wtIowcYI9NAOkQESTBhL9tLEYwwxn4d+389OXjdExp0VxVjDHA7jsCACP11PFt3SsymeiW9aqoC7RhM9znB0wrWEJhEJQqgCGwue2P+s6tfVtCaBPZXNR1HBdBnv3PppDURLZcIKG1cgR8OcfHv2H1P/hoiqRcCyhI6rG1FXLKUZZFIGB1qx6sfp+f66zVXSZ1ARbAICxMtY1OXZKhql1TI6VPu9/nk4yMjVBqRpsoCFlZqhnjgmDxKWQqMP8AQMD2/L11c+qCA5Fplt9Fx/eiIboKyL0qYUZ8f8QGCf4DXI4gBmBFrLHiHRcaFaEPx1EYCg9Of11jMBsrA03IGhWSsMqU9yt8shAjWeN/XGAGB9f01dhn5X8yjNYOikfRxJSy1FRAvls0pZwFA6gQMjA9SMnv+evQNLRzBdRrYWZ+8cdMjShYyezE4GrnVYGZxVjRJsrtcJA7qZmGO5B7dvnnUNVp1KIJ+CIax1CnzOsD6en0OrW1BdBw3nVKNxlySpGcfI40HVepSuMRCULg/RklXIPy7frpRV2CsdBHdJe4OQw6kJxjKnRzmRKVzwLHVWFeVYs7jpB7ZGc/lpBUaNEhOpN/v6q4r8krkfU+vf8A6Oia24UhX+8CuCsnVn5j+WnbiANSl3kK63LHbsGzk5bJ/LQFXronmPVLFylAGcsPT176BqoAFJNxJALAkY9M/HTGrsdVW514VxcD2/8AVqMZHfJ0W1RqpmBSjclOeoS5xgY/h31A8wU7iJhWFwQRkidyB64OdQ1BIaELE66K63MkfjbP0x3+ugKp0TskWSVuPvZVyzE/E/xOmFYyoDJ1S3uTlgEdh2740zqu6DySYGySbm6k5YkgEjt39NTPAlK597KvvHIHVL29D29dJ4k6pi6SkG5sMjJKd++n8UlVgqjdGGSJQRn5fPQdXtZMDElqD96Ov4u4yPjgjOo6pN0rDuifeZPvEhj8e49dBtXqjNsxSvvFj6MB82zqwVjPZDNJACt95SFeoDIHbOqnVT11RJvIVLcuoyYkAI+Xw0XVdEAdVRunfCMjH0zkaGe+qhqTok/ekmMsiFfzHbTsqX1Uz2iEQ3M9Ks3ujt3z/DQ8WZG6afokPdVUJ1FkGR+umdWvATNeI11VNcwAch37dsf/AH0grwiTNyg/eo6SxDj6AZxp2OBSZxKt96DHUeon8jnRc+8aqAndX+8wqlnjkXHr1aTOYVYd1VC5IAcrIRjv640XVWmxCgeNEM3aHuvUQ3r6E6UVb3TmoFb7ziJHvH5n3cabxIuVUQ0a6+ir7xh6Sxcfr20DUAEotcFYXKJgckkn5EaY15TlwSPvCAdmkUD6nAH0/PSmsZhVsFo6pLV8OceaCc4HfTeKD8FHEAhUa2FgAHBHpnOgaqaQYAQzWRAD9ooz8c6PiglKdOVWasQNkugOe3fOoKk3KUXKpamNgWEg/XtjTF4iEwLTdYLc97qLXYLrX0TolbFGDH1qCOrqHqPj2ydc3imNNOjmabyraLZcQQuf7a5Zpa2For9CKGVf/XR945PzXOQfyyNYsPx5pE1FW9toA+/8rXl3VdXbrBtT4yMdBB/P17a5bMWZku+iJJLrAFOId01ypgx2xhnOQzYP8dWtxZAIJv6ItEbfVEbdNWyswpLcyA/+0cZH7v66jsYS4wQUzSPKltvFVDdVLREZOeiqwSfzI0BjiZJ/VRzWhpAQv7Y1je+aC3NGB6CYnHz+Gi3iBOpH1+apc4R2RhvRSgc0YV8DqxOvb6dxkaZvELR1TtLTcBO494hUzUUlQkg7gpKrdQ+WO2PTRGOvpJRzp2N5wM/lNRVKIcAEuuVOOwxnTN4jBhWN7K77wp40kVKKqncdlHWg6hj/ADZHx+egccNtUpcItqEun3lQtGBNT10MmMt7gIU/IEHJ+WmbxC3Mqi5p8qdDd9rkfoQVajHoYSf3d9BuPbrCYubmEfqqj3fbnBlZK2Efh6TEWx+oP66I4gybi/wVromxhUd02snImqCuMAeQ37z207sbT+CLnwInTsntNuC2zx9cNUAowG6wV/mNOMcwDmMJqQzCQnMd4pC7t7dCwY4BV/UfAjOg3Fs+CbKSZKcG60nRkVtOp7gEsCfXVjcS2IzJC0i6ELxBC/XLVUYQL2HUCD/0dT3ll76JSxwMlXW/WuUyH2ulQ4Vg3UO4/IfDUGKbBcTZQDeEWnulLUM70k1NMmMAK+er9+oyu29wma7XcJx7TlehVDMO+VHYH6D9dWGpaQg+NAENayQ9JeIKD7w8xh1D8sd9AVCfKUc3UIy1jlmaOKUAAnv6N+enbUMyULRIGicotVJ5kfsNVLMo80oqlisYGSx7dlA75+vrp21IsVY1peYaJ/xf5C6EayMxECGqVO+QWx2+mRk6jy2ZSu5ohDWtpFcQ9cka/Nz2UfzOiXgiSo54HKCryVAYOGRekfhGB74+fr6/l6aqNaAYRMlYaqgWYJFUIkR6WyQxwG7YBx8vr9dISCYVkg6fJN6gyU1MfZ8NSrnqjBJ8rI/wk/4c9/ppXgNEN0VAlvoFq13jeutUdQEzPT4Oc/AnuPyGRrFUGZt1KrS5lrlaK6+XVMzqRkY+h1ne20BcwHnObdIXrSTp/Fg/Xt6aVpAv9+qRjXTddr2rdWrKAROJBVwnpft/eL8CPie3r9QddfD4gFsArpYd2ZsbhZzzVdZVeRH6sg5X3f5/I6vdUJsFpETI+wrPIBE0cpUJkqucnsBj/wAdDOIjdWNFjKcJKUjLq7pLgAEnPYaYOAEDdRxJuNk2F0aSrFOoV4wCGYMPcbHxHy/rqqjiTMDRCoGwJsU7FT0uUDyspXGcjA/PtrUauxSOmbnVCmrZYovM6/eGB7o9Bkd+/wAdU1K0OEFBjRkvqh1FzmCylkESAYV1YnqPr39Menp30j6hBmUbG6x1Pc5zJlWVo1OO7flnStrGLpbAQsytx6oy4UNIBggDPfJyNXU69uqDInRY6i3DBW1FRTL5mVXOCnSox6/6apo4oueRBuq87cuUlZb2o5GHywx6N2Gfz1pNSdETpHREkqFeMTOGV/wgHJHr/wBemh4gJ1UIDgZQmrFifywZVGACcn/r6abPugIiyulbh+lnb9c9j8tQEosdDrqz1PuoTLKg7nPr1DQzdUXkFDauiQ9PWDlcjJxkfT5/DQzjVKICuK9HAAdzJ8fd7H/r+mj4gn0TZhoAqNWvd/OP4u4PYD/w0wqCJQIBAjVUaiXrDK46O5yT2/8ADQ8aUA+STskrWMwXssjeg79+39dKahKIdEJIqpAMMwDdRGA3fRc8dUSIBlW9rcrjqAA7EdXY6HiiLJHCBfVWFWB0iSJ0dsjJGcj6dxp/FKjIGiS9ZMvZgqj1HqTj4fHSipO6UzEEXQ3rJH6fcLZx8xgfDvqeLdQmYslm4SYUdchQnKhRgaPikiDqmkxlCs9czKY/eI9B3OP36jnpXuJtskmumHTlSQe/ZfT+GdA1QDCVzuX+yu1e6Bi0pDE9lxoZ5TkkJJq6kd1kLIfkfT92mbUsg0uMz9/ZVva5ApKvNF8feHc/L6anjAamyYm1pSGrpSCwkkJz6ken7tMKsIg81yrpcXYMQXYk57jtn/Ttpc++6Vzp0ukJdHyGDF+5B+GPy0xePKAgXbuSfvIkL1jLkdvePvD56U1TMBAuGh/yqNycquSAxB90/P8Ar+eoaqBd2SGucrL2KqSckYxn56IrXSh03CQLhOyqRCjAd+oHAA/fotrSNVBpEJIuJI7LEQcnscn66Q1CTqoKgIkpP3iPdVgox2+ffTBwBKBIKubgAisYgPd9Wzkn/r+eg6tF0GOOWTr3SRXAsV8kBzqGvN/vZLImN0Nq4dHT5Z7nvgDA/TRNUbpnwBACAa1QQEQemSB3yfhn/wANMHlCQLBXSviV8Dr6sn4+v6aXxtiq26wPv9lY1/4pF8wH0z9f+u2la+2VWEgGZuubb+vcrpHYzEWjdVmeQN3HqPTXn+L4pzj4ewWqnAB7rjjRKxRo+ox5AwBnHw1zWkarJV8vKt/HsvvmRJIvX8z29ca05m7KxzHSbIgFNkiOT9pk5HYkjTU8uidrRMtRVWMsqGX0OPyz9NQ5SblFweG2CGaanJHSy+g7sRgd/lpXEQq3slpGpQwlOEXEkQGcD3sBj9PpoBzRqrKbTlkKno0byyKpFk/4RjB7fvzq7l2TeCQMyN7M+UYTOFXt2Ix+8jJ1XEIGiTdFVGUxiJ2j9cLjvoANm6gBGiMAUBVg34SeoHLHHw/PQc5okJzE2GiSqsYmAiLh1wrgElT8wMj+OqyQR0lVmR3Q2hyFcrU4HY9h3x8PX89PN7aqttMm+yCUU9LGjq2I7YOP550zpkFHLJvKA1YlOzdUbKVJGC6jP6Z0znXywo0luoQXucbZZup2Px8z07fLUc6bDRMKgF0WK6xgAeZJGSMtkjA9P36rGsqoVL3MSsnHVQzlZIah0XOAzOPd/jp3OGpstHoVRkdVk6KtHc9wAwHV+/VYItKrfJuCnCOFVuqoXHSOx6Tkfv05qA2CdjSArRyxYy9XF1/LABA0+YabpqeYyJ1Tvrkb0quoD0Ck5zoGHG11YQ6URKipSUMlbIkYC56pCM9vh31Gug+bqpTa4eieffNwQlluPfGCTMcDv2yDqzxMvlKtBcdYWQp943y3iu9hvkkTVED08wBB82NvxKc57H44x2Gm8TMNVfRxb6WZzTqIO9j6pjFuC4pLk1cEkZYYBwTj+WrDiN5WN74dpZOhf6vzYyKiIr691X3T9OwH5aIxDpGUq0gTYIMt/rFaZWemkRj268DpUfwz8fjo+8OJMFVuj7+/1QRuCrIUGelRk/EMj3hj49u+iKz7EHRBrgLQPmm4vlxMnUtXBI3SVCnsO49SR3+Oq2vdm7JMx1CHBcHhWriZIjE6FOkS9OAf0+mj4ux/VFsxG3qFjjCzLGsnlLIPQ9eQf4aqIWQYZWamPUx6whJx69l0sCEDhTmlPaSaoo5oqiKZSUXpIY5Vx8tWisWmQnZRc0gytoG5ocBxAoUYLAH/AK7atdjhedVsY1pv+6bNuynSSU+VUAnJBDeox6ev6anvfZK1zc0gpf8Aa+jXCrBWdPcEiQFh+mT+edOcX2TCqAZansG67QsQQPVKwPpglRj9e/z1Z72yIARkE66q6butsjtIaqZPeHu9Jwx+fYY+uiMa3RwSZwTrH36K1XuW3ytTiOryoYBwQQOnOT/IarfimuMgK1z7a6pUu5KWWBlFbSGToZgpViQfgASMaY4hsdFRUfa8IFNfKN6dcVUKOHz0tnuPqRqCuI5kGEZZBhZCC8Uy9nqIgvfARj/M/HU94YeXr2TgGdUWO608SoQV6+4Xpf8AF3+OrGYpsXStpG53+Cc/f9Fl2aqMbeignGP4emo7EsjKQnpUybn9EgXqjwS9wEKYwCW9R+746AxLALqvKZtaEX75gcCOO5qy5z7wA7f9fu07MQ3VNkfFt+32Uo3WAqPMqYHb8OM+v5k+vpp/HEwCjkM8wV1ucMKmRpYHkb0OV90Z+h9dQV2gwTZLlcDni/33RDdKfDAVUI+IzIBkY7ntqv3lkASrGsMSAkC50zrGPaqSM4OSSM/QatbiGySSl8O4yhDa7UpOHqo2wewUg/x0PeGbKOYYgpbXWkYgiVAe+QJAM/louxDYAJULTFldbkEYqgMrHuffB6fpk9vTOlNYTEhQOM6fqhe3HzAjlgSMkH5ad1W6Qg7orTSSIkohRkBA6gcFh+vxz8dQPGpKD9FTTsGPYKD3wp9B+elbUi5TBpAuEI1SMxIfpTGCSDn1+Pz07KohK61gqkaHu4lVWABLAYx+p9NK6o3qgWjrdZOGjr3szXclnoEqFpWYnJMhHUB+WCP3jSuxLM4YTc3A7dVuZgMQcO/FBvI0gE9C7T42/dYv2qSJmAzGpzhz8fn9P003iCAufUMEti90qSd/eBkBUnq9CT9M5zotc0BOCYkf3SpalyAI5I3PqThv/sNHNIsoTohNWKP2Jk6SV/F8WI+v5ajKhCBJBVzVgSDDJ5QH4SckfXRzblO8yLaKy1hcsyj3B2HVkFj+XbRDzvoplGaUJqzMnQoz09yDkYb45x8dAujRBxvEIa1MowMKoH0IwfX8/TVhdBgpWkmwCR7WikgmNpH74x2J/wCvloOdKSzbEXVnq4wGMvXE+cdPTj+Q1WbFVuaJkqzVIbrIDMgXPUwHy+ug5ycNBdCEapB1BVVWI74A6Qf+u+pmMomAIhUKnr90EEEHBA7Afp/XQzSZCRpBOXVIExYDsVU5PSAOnOOxOmNfcouY0kQrGfyiPNB6SfQ/AY9P3aQuOiQkC5H7obTKcFfd+YCnufh9PnpnPsgQBtZX9pIJYqqNjPu9v4HTNqHcq6ICG9RCOmQMQD3IIIznvqp1YbKuqGxITVrhB1hJGCsR8SOpv66XxWg5UuaSCBZAqrvbqQSNNVqpiIU4PUy/IY76pq42m0K4UQVzTclyhuFUtbGRJAy+WgwepwPU4/U+uuLiaoe8kfduq0RDfitXZw6AxsoYjJ/LI7Y+Z1S8GbaLK/SAsrJWU8jtA1T5kmM5bsB8f+vy1U2q6ZKte0Ax1RoZE95w8LEYAZR6n45Px+PbV7KqenTE2CqSrpkZhHNOJiMlVzjP+vf46rqVDuE2thZDhqYGYs0juWJ7sfT4fDQzuAiLLPktBRumFleJXZO+GAAIx8O37tWNxEAwrBSJBARVqY6dsvKZukdvcBI/M6IrmNFd4ZB7o4rQ0sTdQp5SQ3R09/17nRbVsbWCmUT0KybVMrASExTRehK4H659RpfGvCsczfohe0pIQ3s0brk5yQAPqdQ17iEhEnRJBXrAX2QgHPbHv9vmD8DpWvVdSmiS1kKuFiSEVB7lkfqGP1+GkbXM6p5/pF02jucHV5C+Q5UnK9IIP5/PVxxLgQTogNwfkjrXRRqzmmpIx1YH7IZ/TTjFuAVkAbaqoL5QsoMppoGZu48kP7vzyPQ6IrkmHJGlh2Hx+/qjx3u2M03VCAg9G6Bhh+WmpYtxbcpSKesIi1luqo3khoqc9xgOoJzoHEECWxdMWMNwElZaIMont8B9M4T0/XVXvDg66RtKnEZUGaS2hJGe3RqAO2Pho+9uBgCyIpU7mLIkNRaGTqa3osjA9I7Yz+unbidoTCjTva6MWty9LezqpJwe4GO3p20oxQiCETRbHIFYPbAzKY6ZjjJJPbTU8RIvuixgm2vqgtUW330SGjZx+FR8fy0WVjMqFjQCk+1WgBCsMLDOCVAHScfP5503jE+qVwaJDQqkrrfI7qtCvun8Rx736eup7xJ0TOczNDQiedbIwsjUxUjB+Jx8sDUdWtEWUhsSdFTXaCInoKupJIw7evzPbS+IbyPooXRfZWNzYkKz0jIThffYfDsM+mo2tHKPyQD7QY+aP5tWEZacIIyvf9qWAIHzzoir0Nk5D26K0cld0ESdBc4wFlOBo55sNkrXOvI+qdeZUeWvmxOpJySZQSR9PloCpluU/hOIiEjzEHSJIQEGe4mGCNQ19ZGqV1MyLXSh5LMP2LBMAAeaMnv21GVdJUcAdBZDNLBMCFo5sj4dXZfqProuefmkY0QYCIsETYxTVBJ7DvjPbRqVTEqBpO0q5hjWP3aKfOcdXb1+Pw03iHdHwBsEiKA4OKZinpl/X0+miax9PqgKciw+iuY/fOaYhMZzk6QVHaI+GJsEPpnDu7QSCMLnJUALol5+aDg6Yj6JyuVPvRu6DvkBSD3/APvpfFhF7SdQkxTo3ZVAJ7gEj1/TTOxCDDFgLJ1HI7J1MMOCQFII/X0xpPEvqiwEROip552DMyJ2z2KjH8vlp21nDUokuva3wS0q5epVjSFO47MAP17j19dF1czqgDJkN/JIatqXIjkRHZexAw3SM/DtphUcBrdB7jm0+/REFbInmMKdS3p2ZcE/D10BXJIEpswuYVfebszItPgKe4yO5x/130HVyoHQ6C1HarMaU5R4Jw6EsqnLRd8AHt+vbOrDVIIv9/FQOIERZCeplKgiKoUFs5BXI/eNVvrxyouNoAgICzurszGtYEd+txgH6DAxoGrN0suLocEtq5elCpU5+PUNP4siAo5xgEIPtUOemWKMygYHvD+Glz8sIyAZISS4AGDSqq/iXv3/AI6jqhlRxIIAKGKsEqsdTTwAjIHXkkfDB/poF5AkpHTYj81ZKpm8zNX1kD16hhfz0prEaoNLiSJunKzIwZHkduoZ7HsfT66njAG2itY4kXlNpKqdGCwGB0IwC8n9NTxJB/ZVl2yH7fMB1NJTwqceshIP8NAOGhS5nDm0SZa+coyCqTp9WPmHAI9O2f46UOAEnX7+4ROJqRkBt6/om5mqWfIuQ8vsSMEDTlwgEyqgXk3KOkyh8x1dSrMfeIncZ03ikAACyJIm5VJUiMkR11RF8cGY+o/M6niggQmMzIKcSV0wZiLlNkjuxl7nH09Pj66BrGPVCqXH0SHrKjpVIrhNLF2PvSd8j07j+WmFQ5YOisdnDZVCvuMIZEmbHqcuTg/l30adUjRKWkkgoslyup6WjqlVz+HJLEfl27HVrsU4GxlNDjzR6Ski53pgh9qp8Z9Xzn9SRpjXcIvHwU8N3RIF6vBkLBqeT4EL2U/p/wBfDVXvTyTJVLpBnLurter10khaSM+oIA7HSuxFQCJSlpB0Q4Lte6UK0hiqQGLDze/fHw/00aWIcND+qDS4aj7+9k6N/uqAYW3Kx931OT/H1+umGOfAko5TGiGl/uCdAFHRMAe58wnq/ec6Pvr5kEIMEWj6/qjJf6jo/a0CMufVHGSPoD8NX++ODgCFCw7BLe/r1OzULgjvjrB/L8tK3HOgff6JCIP39Fb+0kChEjp5x/jOR1dz9Qe2rKmNgXCVsgxKptxxIoZ45mJOO5AJ+Pz0j8dGyvYHESFgpt3xtKBFTTiDpIZmIBB+BA+P5azux5JtZIAZAAn9lp09dU1ldHULI7sF7Mzehz+LXPbmiTqrTUl4aNEgor1Lu0rPIx6pX9c9+5Hwz/rphUOWYslvmsUeumado1VFWPpACA4AUen5/wDR1CDJJV1WpaAsXMy+8QwjUdgioc5/PQOknZZqzidNPmryW/CjLSuMHKlT20obKIo7Kxop16GiYoB3GBkfLQbRtY/f6p203bfqjo0+GVgMkYY9OMnOf36V8zmIVjQd/olLJP0N+xkbq7dwB/LvpC0DRVNdYn90OHrKNGywg59SD73+umDSJI2UZpYJ7CXeIklCQe2M5H1+utAZlN1ewXVLI594Rq4z7xHbtn6fHVBYRZAZinaTskjhIoWBHYZ9P+vlotYTLldltpZNJnmqZRTo4giP4unI7/njQfTET0VF5hXFKsatCKhlJb06znOg2BaElWmRN7+qs4YtC5rWjYj3VcHH5d/hoODZsFWcx+H380ZIZ+y9ZZT2wqj3f1GtFitIZclIEbsroyzEkZICdQP6/AaGToo4bH7+/sq6RdMRVFcYAJyR6/LOPr/DQcALpWjlkCDZJEayMiydRJ7v73YflgY0WkFs6IFsJ4IKdsyxMY2H4W7gY+Pb1I0C0XEKFjZt96p6AOhMTM7du3UQTn9M6Tw7yES20f2VkM0CDpjAABAAb+mgAJhEHKd1U007KnmiJm6veDN6DPx0zWaEImoDqgS0ntccJkmZEDYwrZz2/jomBPdWGkfRFpsYUpUq6KMEuFbq+GD8vjoUw0gQq2tA0SXfymkD1EasxK4b1P6AemmDwWwLhWTrKtApToj84sAwwrx4Bz8ifz1Cw6oeHr2TpFVSzPNCqA9wCM5z8e319dMQM06myc07iEeIUkrSipnqpqft0CKVVOfmcggj+Oo1o1Iv8bJntmxKZKIQwVJnAH4ABnP6fnoCnPmSAbJTQLEgkYiVi2CCPT8hp3DREUGxI1RAsBifqLOpGezEDP8ADQDoMBI2mG2/VXp4/wAEqVEiKi4GXJ6R8c98aj9ZAVjGxYJwXjjifNWGRc9i+f1GhsCrA0i86K4iMhilhfzM+8MLkEfHTiRbSFU6mDcf5S81URcCjeaMHPV7qj69gMnQzECSdeqaQBpCGlbUdTxGJoeoe7gdh+QxoAOkkFQ1mi0QCni1lUzYDsyEjKlcenw08ZocEA+TISnnqGUIjRhur/AQSv56AJ23+7Jg46Qm2KqEuOurjQ9RZiw6h+XrqNYSOZSo4jS0pXVLIhImqJIv8QLnIH7v5aam0RCDTImVTxkmSEicp2wrMcN9CP8AXSEaHZB2m6L5IMEcMcghTB/ZghVUevfvp3SD3Q8MFsbLHJTUqS5Z0THY9x7vb17d9KDLZIsqW0G6HqjyVMcYDRV8jkZJAOQo+AzqrxDOWEzGXgFEF7WFlE80T59Rg4B+f89M0EnKArGuymSnCVtK7LIrSrLj4MT2/Mj8tMXQYKUNBMkojyReWzSTtGoxgeZ6/qdLmkxr99EHUgdd02jw8yoBO3oc9WOn65zq4XCBYCAESeI9IZjOp6uwY5wfpjtpCCD2TGmJF0TzH8rMkaEAerDv+v8ADRL7iblQNGVNWrI0JABQkEH9mcIMfLRgCCbIANmxSFeUskUSyOpOcmL3R8cahfukY0k5QkzTimMcvtLRSMewAxn6YIxpRBaAEr6ZF56fd0RKsuSq1L5QZYugAb/LqxzhGYiAnY0E3P5ontClRL1SoqkDBT8YPxGqyZFt0wY3YqxnWQoYqkdfUQVMOMjVgqblHKCBlQZESeN3EqSAd8eWQW+nrql5uVU9gg5UAwBMd5CpPr0sfh8840C+bD9EgokapMMZbqdKmMMoGV984+vf0OmLhqUrqZKS7U8MiGWpV5G7EOhP65OjTqNBgJzSIvqgVMKq69AlYsVDdK5B+Py9NKXy66StR26/FOI2JU5jhjH+EtGTkZ/++mDgbn9FDTAum1REzz9EbVBRD7xRQFUD5fPUZbmKL6QiCkgSsCYytSevPS/ugfE/rpQSAICDaAmxS1pWmyZVpYQuD70ncD9P66fMI5lW2g4mG6IfkMUJjMZjwOnpPfVmYTZaTR5eybPJUwydCxMhzjOcd/z0hc6dEpZsLd06zOoEirKH7AYIDY0c3LcJS0i4KE8lYQXVpn6T6lj7p/19NOJ6JgCYk/f6pa11YARHHVzgdsJ8T9Sew/LVDg6dPv73QgxBTb70rkVvMp5VfPyPY/LUeCke8kEFGM88sYkIdAT3Bdl6c/z1YIlQtLhE/VXqqqFXLeyzw9OOktIz9Qx3/P4/LVTiY0CD6YBubpmtWEkB9m6ox6guTjP5fTTBpBkWMeqJc2TEwrrcUjfLhQx9GUsQo+g0zZN2qQyZmE2lr5Jw0YqPZ1ByP+Jvl2Hw/wBdLlIuVWHAiJTlLlUdwGlkf06urscD4jSlhjKAnAAN1j3ZpQgmqKmQA5xg4H+n6aBpybDVQAlouhoIlAUdXyP/AF8NHKZQewC0q6Zl6goKKO3bPc6LafySNj8KdQBkRo2KuWA6cn0OfXQLZ2RptcDlN/7pC0k7q7KiyyjJwR6HHz+OrKnRXeE75JtPSVzAHysnPUTnGe3qdUvablVVKRLOpQxcZ0GJqZmmIz7wx2/4jqoMIuRAVucEkEXTyKpjIUSRU6dRz14yB+n+mmYXExrZWwNwkS1fQ0hjUmIfEHGPyGo5pJ7ousZGiua+kChV86OQ9+ojuDoCne/qqi9kSUwWqpyR5kr+XjJ7HI0cpAmElPLNjKdLNE5LSVQjjyAOkEZHyzpgSTBErU2C7VOhPTRHpEnWB72e47/mP10csnRIco0SFkWSRY0LrHnPce6Tj56RogkKNLTBB3V1boqkhSnYDuvWcjP6/HTXMiPv0S5uaEaaTo8uDqK5bu3T+L9RqoERCrcIsfvqiRrG/XPF0PgEAkFjn/TVjoFmhFtIZkiOSTCMkrLk9wBgfvGnFOSLWVzWt2N1T1E4h6FmjXqOApGD+uqxYqXDYKvDFNIW84SySgZXp90AH4404F4F/u32FKTbXRZSYQCIqgxg57N2z+f00oeJj7+ylNLVJyHZHSGXzWJUdzk/E57+mmDTOkIVGtj6Jy3UhHT0u57FlQnv8s50oEXnRO9g6fmmQeaaVpZixhK9RC47H5HHz0AANdlU1hI6J6yyFBMKiGEd1GTgD6kflqeIIsrRS3H33V0hZ4RVGd6hFJ6RgJk/NQe/66gZrCjqZFyZCaLUBR1RUykggt1DGB9dM0v2sEGRqEuSSKTpVJIY5Bg4LaamQXadVYGj0ThV6gTL+0XqPb/iP+mmdb1UewFyEIpkbtFTgMM9u7Hv3Omc/mCjmgOBI1RXkqJpVj6YEjYd1I9fr6aUgNv0TVB+FquHqYmBQIob1IYHA1MxiAiKZ2RRUy9AjiMCkepUAlfy0WuAUAMc26N55QH2yCOpkIwfy1AeijWgeb7+/qrt5LRSgLDTH1OAMkfl6EaBf+LVWMpyDlsgNUwNEkipArKMZAGGI+mg6QAR97KttISkxXSGoljBimjkAKplMYz8z9dAzeR8UoqNJsjPVTqAViiAz+Hv1dv6ajXG0o5yBGwVzJVnNYZgsSnPUo7Z9MeugCNIugCScw0QzJV1EjSJIzMABgR59f66lQiJGisuNUSNKhWMTSTL2Jz0HKn4flq0AOExCRrCNVdGrQAklRJLJnHmMO2PX9RoOcBDtkZI1MlEhqp1n6llhnPQRlR8Pl8tEuluYKOGX1KvUVk/SQsqKVBJQDv+oOi65lGuYEK00lwNPHMjUwj6cnCfuAz/APfS+pVbwcokJYH7MZTOO/Y4BOjrZBzLAHVM5iZHHdEYgjLjOfj2x8NI0QR0++qRw5pi4R/aIhExSIyn1U9eM/Xvpi689VGtEGyJEIZ27PMoV/RvRfy+emLbghOACbI8tNGV8sSkN+I5HT7v1/hoNIzSE1YGYKS8ApjLIlZNEwHSxck5/L4AaNODcd1DTmBKMI0YovmU5Ocgtlst/rpSLSJULCYhWdQpdqiTpPbrwxKk/l8vy0zSDBiUAw6u3STMxEk0ckI6BnJjZs9vQD46QmddP7oFgjVNp/aZ0RGqJynTjqUdIQD65znUJk6IZZIbNkOI+VHEorUIDZDthj+WjDYtZKWEW19UJqoJN0GrkkGCSTGB1fke+mLhlgBETMJSNHM3uO8zjLt5nrj5A/6fLQgbdkDSaTOu6BVwVKSRESCKNmIEi5yMn6Z9NQA6k26I1GkaJVTS1VQIEjnKxrnse3V+eq8sSXKstdEBNlhlpzFClezkMCy4IVT+ei1jSC4C6LGuBAJVjT1TdTB1MZYqMev1OSe2hlEEpyBcO1VewmVvOURyOSFVu/UT9NFjQDF+6qNM5pKyEFAUjRpJZoh+HIfOP640agAcQRqnDI1smwpp6ch4GR0Ukgl8BTn8tKGtgA2SgCbSUta+OOQwl5ugA9TRnK9X56jKh1ama62VOKq4RQqwdZSWGOknv3+fbS+IdBcJpa0xoD9E2kuVI4jDK3X2GQcgD9R6jOmJN50Smo3TdIirKCNmAkJY+pAOWP6jvjTdgrDliAUeSsto81fa3LP09RPct/DtqQSlc5swVaCso3U4rSMdiCgB7fE6LyA6AE7D0ShVRzef5dargAZTyzjHz1cxzdpTlwzSFY0/WyOsrBfxqQSMflpDGioLCVTsoTojlEgABORhh+ZxqkifKCmDW2i5TXMnSVJjRSQwAbuBnUDTaNQkcCQRCSwNOrJPCJWBGMgHt+n56hdAm6hoyboUFTFPIkVPRqz5ywT/ABDHfP8A4ajbnNMC6rDADEXS1rKSJR0vEznOehSf351YDuncG2lV7ergJGWdW93pYher9R3GlZMJS5v4QlechMaToVhJz8wB+fxGoHEDv+qDQ2Q0W++qIZ0yi+YYARjCgHtj17ab1CsyENAQHWMkJF1tE56c9OD6/wAfTUc4l8bpazJOt0mQwqS7yztn3er/AIvhkDSujQBQsykHojoqgRBLjB0HGA698fLTuANwEKdMxIIVOABhXQOQMdKrgj5/TQc4SmqMEaffzTCSnDBmkLTkA+67YP6nRBiFW+i46zbZba18jq5EM9rtUmfiade+uc3FO6rWXMmS0JyK2xvIq1O2rXUMPwkBl/kdOzGvAk/oi0U92/mhTSbNklME23FQYJLrO47/ACHfTDGuJmEfDoElgn5pBXaNPEHSwidQ3brkLHTjGZQMsKjwKOXmBSKip2th4jZREGH4kIDfxGldxI9EXMpAQVhmg2+wIjkucUZPcFUOf5aQYoG5EJ2hhkIiU9nLpi5VaqDkK9OMEZ9PXTisJ5QgWtI1RordbxMJI7mY174DRHC/z1Uyo34/f5IMDfKDaU4eyvO/VFfaFIm9RhwcfljTzTIgzP3oncw7II22gZPMuVslIyciUqw/hjTl7C2AVldROpKB9zXFJehGo5Kc4IPtYyD/AKarMZrFEB05bo8lku4JNNTRyv2/DIhx+mdWgiIBC0Oplp0TGa27nMbRi1mPqzhlAZv1xosp7ZtEHOcRBCxr0G4oo1WWmqyuRklT3z+Wl8CbqZnARKfU1RV06JEKZpWC4LPEW7Z9fTGhTpua6RICZrxl6pgbrUxTSyvSovc+8Yj7v1Go5jgAFQ+s0XgIK7kdSRLDBJkjv09JP0yNIxzidFW2vHM5GpbpSTSSFURCynC5+OlzTqradQOJA0TsSxsq+0OmOokhmHb8hprG2339/oiDsUmV0Sb/AGSlSVOnA6ZMjH5fPUDupTPgHSQncUrlcSUojjIx09Weo/lpmmIG6am68aK59mVA6U6wt/w49NOHmb6pgGZb2VMFlXJIR8j0Oe2nsRBTPMyTqliqpFk6PNcuOxI9R+/VQfsrQeYCZQUqafOZKmUHPSq5PvZ+eo10jv8AklO4KtKI5sPKxbp90HBABx8O+iHgiECCd0Q01PHib2mRZVUdlIIz9dXeNIjVECNUNI0TLEyOX9AWLAd+2NIXWt9/f3KUQTE3VhTk9BkZYxnOVQsf1+miST9j79FGsk33V1SMI8bFJHOcEqQfh8BpBsoxglKj63kZHQRwnvgsR/1+WpmgyUPNZycwiBGzHSMGbv3bOB66niHykoBoEEaIfUwmaM9MaMDkN73UPl9NAa5lJId2RYBTeSSJokjLYVVBzn66arUCsFKBPdWmeHJT2p+5HujOf1OiXSbahKW90SXpRYooqieUtg9fUCf10CZMK17Rlumxd/LHQs6v3Hde7D5dv5nUJm0KoiPREglmPWs8rv19vdXsO2oY1n6ouLh8URyViZkkKxg57gZ1BU0m6j35dNEATSAPKvllVIPceh+ZOg5wiSq3ESb2+9VaF5O7tVxVFP8AIxev6nUaRElLnc50kiU5LFpIZUiWT4dPYBfr3/XRbY6qWgkBOEGelPIjdj+HLjsNTxOp0TFoFwLpazPBl0plDZwSnfH5/PUdUIuSoLG6x0NX5tQ7sOtT7rOO4J/6+H00S8tgyq2lpdKyMdWXwQy5B9AuB/H9NQVJuFcNUKZVqWileUrj3T0E/uwO2hI1SHWZhVKWTDIzp8QB2P8AD0+GoHbgpBDZMpRcyQmV5irE9gV7t+vrqARIF04YM102cxxxuGpo19wZwuO/zxq8VNgZTFt5CHGYZ5GMUflL9UHy+egHEC1/v9VVkBMNjojLG/uqsPvdQ9SMMD6/l8NVgxZMaVwSkAmKYwxZdWbIUEYP0z8tEFsySi8OktG6eSV0IeRXp8yJge93z2zpBUzaFAgNEwmMlbKyrIlIqxE4VCoHf/i/nohu86pM5dtZNJJa7pjESogY4BC+p/oNQmTdR7osNU9ijrYVwJIfJJ97HYt9c507GtBuq+cFClgq5SxBiiQerBuw+n56rzQTe6Lru5gkQRiUsal6eOBV79CFj+g9M6sa4WJlQhxMBN6hIppVWlWrjg7hTIAP3DQyZrgBJKV92ygyO7QvJjCsx740CAjBJJ6pmtBK0qxGGEr/AIgreo/M6sAJEqsAkybfsjCgI92aljC5OOlu+nJLjKIpgiIsiNRR4cxUk7OCABkY1QGmYG5Vnh3IIuFUdHGg/a0s7ysCGwwxn541bUO1lG0xMBNRb4QSppp0Q989Y7aLXCbqGlqRKf01OkKFIvbyoOSBjv6/DSuIlAU8upKqaZ4w3kQzIrDpYEjJB+WdI5+YX7KDMHCNVUMUJRZSK4OoycoAR9c6cATeJS02g8pKZrLcBKGCiSA9vX1Gqg2RZQuAbCP+yRumOCojRsgsqjtn17acmbINAG8FMjTM7lC1XGvop8tR1D8x6DQMzP6oFsXJRJE6ECQxMAe3U/8AhA9fzOoMxN0pygWSUaXDJ7O5JHc+uBn+WpJhNSA6aojSyTSBURelcAhjog7myscQUKORy2GhheYDswcnHfUaDqDZAuOYQrIlRK7T+TGue+QB/LStaL82qBe6QQE3liuAZfLWDsSTkd2GnLNpSHOTLRBSlpLkIpVRThiMnzO5xoAtI1srHuKVDFXoqiRI3Qk+8SGx3+Oi+DulJcTzaJzF6U/+Ztcqrv6furaOvyWTp/8Aez+R1hb5B6hNv99QmlV/fS/5NdB+rfUfkFditR6Ikv8Aur/mNLR29f0CyVvxfeyYVHq35D+WqP8A3PmqDqgx/wB1+g1rHmb8F0afmd97IsP4x+Wi/wAv33VFTy/AfmspF+JvyH8hrNT8p+CodofT9EVf75P8w/lpqfmP/cF0DqfQfkjP/dH8tUYjyD1/RKfM74IU34R/l/prVS8wWOt+yLR+h/yHTu87fvquhhtH+h/VE+K/mNW1fN8P1T09KfwWYp/SD9f56R2/x/VLX1C2ak/C3+VdXO29f1SnzP8AU/kg1n9yv66B8xWHG/7Xy/Rc4uXqv5auZofvdVO3WvQf303+XWvF/wC78vyQ3P30Vq7/AHg/5NZ6vlH31V7NT99Eim/HT/8AvBoVPMVpZqfVbDU/7zSfn/Q6rwP+y74/mEh8nyTWs/vF/wAi/wBdHD+b5/krTqExX1b/ADf66qr/AH9Fnq6FOov7z/uDS4zzD4fqnb/ulAT8cX+U6uP+031Cu6fBJP8AfL/mP8tXVvKPRDD6H0/dOl/u/wBf6aowWrfvdIPL8P0WZp/90h/znUraOVr/ACJrB/fS/wCf/XVZ87lsq+cfe6M391N/mT+Z1r/9j4Lku/H99UiD/wBX/mP8tc6p/uH0/VXU/wAPqfyCaJ/+If8AfH9NaWa/Na9x97J43+8Sf5f6arw/+yPgq8P5x6/umq+sX+T+utNbyffRPS1d6ptTf/ic/wCf9dU/hPx/Mqv/AN9voni/3kH+Z9Sh/sfJY2+dvx/VEj9F/wAp/nq/8JW3Yfe5WOj/ALif8z/LUxX+4fiqqPk+P6LMQ/3NR/lXVLvI30CFby/BNaj/AHN/8yaQ6hI3R/p+oTVPwQfmuqm+ZvqU2C8rvQfms2n903+Ua0t1b6n8wlo/7abN/fxf5R/8o1a7zPVjtFak/uqX/Mf5axVfP990jdR6ptV/7qP/AH4/rrW7zN9D+iR+rv8Au/RP5f8Ad4Pzb+epT86vdqfvqsZS/wB/+raLUlfyffULPL+Of/MP66qHk+f5hXV/P8vyKVTf7xJ+WrWJx5mpunqfyP8AXQZ5vvsrHeb4funUf92n5H/5dHEJXeY/FKm/DH/l/poDUpcP/uhYKn/C3+dv56vP+18D+RVTND6rBt+Jf/e/10mzfT9FSPK71/RbkPSn/wAp/nqmn5B6pho30CEP6D+Wqa/k++qrZv6H9Fj7l6Sf+8GtNHVWcQ8quvrJ+Q/rrVT8330CoxG3wS4f9x/7zf11lZ/tj4fotJ8zvT9UqX+8of8ALrThfP8AFZW/7fwCVF+Nvz1gdqP+4/qtQ1Pono/vE/yf11tp+f4qpu/oEqn/AN3l/wAzf11S7yN9VK2/30SIfUf5dA6H1P5K3C7eiDWf70P8ui7b0CNL/dC1mX8E/wDlH/zarf5x8fyV9bzj0KzkH92P/dp/PVlXZZBqfQ/mlP8Ajpvy1XW/3B6/ukq6u9T+idVfpX/5f6atZ/tt9VWNvU/ksVRf3zf5W/kNNT8jkKerlkIvwU/+cf001HzLLU1CG3+8Sf5W1XW85+H5K6n5viiD+5H6/wAtIzylNV8v31Rj+Nv/AHmq8Tr99lH6n4LDTf3I/PRf/uffRb6ug9CndH+FvzH8tO7y/FYmaKy/jk/zf6aXEaO9SrmaBNX/AN6b/MdbKfkPo1V4f/cP3siy/wC7H/N/XSv8wVlLytTBPx/97TjT76pKvlX/2Q==</binary><binary id="image1" content-type="image/png">iVBORw0KGgoAAAANSUhEUgAAADAAAAAgCAIAAADbtmxLAAABmGlDQ1BpY2MAAHjapdG/axMBGMbxTy4tldJSwSAiHW4ootKCqIOrVShIkRIrJNUluUvaQi4Nd1dEXAQHF4cOXVRcLOLirJv4BygIggqCi7sUBRcpcbiDgtBBfOGF5/315eV9qR7qRUk2EpL087S+MB82mivh2BeBcUcddrwVZYOLS0uLDrRfH1Xgw1wvSjL/ZpNxJ4uohFiKBmlOZYC7t/JBTmUXtWitFROMYDZtNFcIzqDWLvRl1FYL3UAtXa5fIughXC30A4TtQr9AGK2lCcFbzMRJPybYxWScxDFVGE16m1G5ZwUTnf71aziPaXUsYB4h2tjEOnrIMVfG/QJyAC/GtKvYKFlRqQe4jbTkrGKtZM+WvZvI0CnjbtnfKb1XMtBoroR//yzrnjtbbDRxhdFvw+HP04w9Zu/+cPj76XC4t0P1M2+29+c3trnwnerWfm7mCVP3ePl6P9d+xqstjn0dtNIWitMG3S4/njPZ5Mh7xm/8b734Z1m384nlOyy+4+EjTnSZunkyzsP1ft5J+63eKWT1hXn4AzDofghlJQBJAAAACXBIWXMAAAsSAAALEgHS3X78AAACInpUWHRSYXcgcHJvZmlsZSB0eXBlIGV4aWYAAHjahVRJtiQhCNx7ijpCMIhyHNPU9/oGffxeaNY3p/5VC5IAQkAhtL9/evh8Pp+PiwaNKZubAYDuugNcMH4ZIAN6A6ATo68kdAA8VQ1DkoEIq2EILiBiALIQDTISWvz3SSQNJHwnilWTGgC/ZMSa1Fc8TDznZH4rgWOtRrwQKGh8VyNZ8bAY9Ccj1EGXUI0JwNE3n3itxrzis7Sq1TgBiNMwesKo1TjfcdZqXBaiWRpLrcbbEjBLU63G9QGv1bit+CSKWi2W8+3QLDluF/wIBgBEaNQWNSjFzHj7/zgOP92EBap3v2BqlNi2pEbGVi0yBNwkcRPiTVxIJDVLRgJxEXGLRgAgLBASkiIIwlIEYgyBJCnC4lKExN6yGSW6SD961nvvQaxhBZq4rbptbX1HlJPSokN37t9m9957a5utDux7Xwk06WnWWOJ2yqgkPqW4e2urnmNPK0HMtq0Hkkc7ZbSXUleHiNMIoGy7r/ppEwAIV+Amv1rS/3ghgCz23ns+m/HrASdJMWT2chsBiS2z73fcLGd+3E8hZ05nQ81zzOW2n8Saj1VzwTMHZ+g6xcPg5ozLASM7Z/hl9kaPnPFQmrcyvm8lFKbrAQwAoegtYFy34rEXRSFP/qEo4tmQ0wywlwPyG5G/BJQXvF5wOR4k7m9HjlupR/y6Mp42RjhWxm+Oh99BvMrwD3UCiGvkpxuRAAAACXZwQWcAAAAwAAAAIACELJ4GAAALGklEQVRYw11YW48dV1b+1tq7qs6t+/TldPsSx3bbcRwncWY0A4LMCOYFXpgHJCR4QvwAnpAQj/wB/gR/ACR4QUKDECMUEjLOZew4zsRxuu122+52n9Pnfuqy9/p4qNNtD1tLpVKpap/vrMu31rdl/nAgIjSpF0kAJAEHGJwAAIQheqeARVqomCQZGUkjSYLmTAyAkCJiESRVNYQAaL3h8k3SzPj6MjEzsr7SqyoAcRABQItRVZ14kqifmNEkTZNiUZiZ934xm4WE3mva8GYGAA5UJ8YYIyCipiKk1ZuTBAhQBGZQFRKvTAgBaQBIeOekBqpa+0gBxFgAlmhqhixJzUKMRVEUx/3RWmel3z9xzrVX2+tuRb3WnrDKVFUEgKlCVWI055WMZ76AieipX0AYzYwQUZqZqJD0tKCqFJAxhKiqSZKooirj06fPMt/odlezhngFYar+0e7jxWLR6/Vc7ubzpNnM4BlDSDLvvQ8hnAYFIlCFRUDEjASgIGFGEcBIoSrMCFAVhgiKTxJPkgJVSeBBhKqaTCb5Ip4cD/efPP/g9q2soSvdTp7nAuv2Vk/2BoHFyWgRYxVjbDezRiMDMicNxqCqqhIZVZxZVK3zaRkgXYaMdeDMoMoapSpo8GSE1t6ihaCqPs3WV/VwPpxOp8fHRw++cUmq7XYzSbLV1W5vu3fw7Emn0xwcD+ZzF8vKQtlI09R7J6SXOldgEDEwAmdguMyYV/lEVWEkARExEkoVBxHWxeUSFefK6fTJ48dlme/sXN7a3vjVnf8NIQ6Hk1ajOZ+Nf/3ZZ9Uij0V+fedqM0v2nz5ut7LtCz1GC2WVJqmry1KgZKLqlbo0qLPanJrAVKgSRX/LPElxQF0smiDy6Ojo7pd3qXLjxo2r1y8fnwxORpN8Nt/u9fLF5OTFcRVKDWE0HJZF2O71IsOzZ0+e7D3tdDo7168miU9SJ6IhBIGD2KuKMpHaPwoFXkXq9Aak+/u//TsFRCEgEAljjFtbW+UiHPb765sbJ8M+Y9HtdAbDgWs0pSge7O1u9Tar+Xwwmy0m03I0XpgbjydZlk2n43armaVOJIqQDEIIIKBABK/iBYuAnT4HwJrx1CkhRosAIRBBo93ImunO25dv/eBmb231+rUrRTH/we1ba+udhw/uSoZGOzt38Vx/1D85folYLhazqpg3mj5ruNWVTqPhxcEsAOa8ihJiAhMEQVChCgXmhKcWT41O6IGq5kCjqPOTk9F4PF7rrlvKRtQHjx/d2Lk+mgy+evrwhzs3Xuzv0tmbb5z79LNPzm9utdorEoNkzPPx+x+812o10tR7DyCqUwCMQUUIUqm2JOolbb/GjmbwoDGS9GZBnYM4IS0E5+TChS1Nk7Z28uPhW29euvPRf2fN1pdffNE1vXnzxsGgf/B036duvbce5tXG2uZkfnL79q3t8+sA4Rws0CJIAOI8LADUusLqeC0rTl4RJgyg1Fe+fB7yUrxTQoRWVoExbWTjl6P5fD7dO6yIF4P+bDK/92T3hzffLWGffPq5c7K1uf7hj3+PrLqbqxffuDQc9VdWVtY31846l1CFqJlalk8gr/UxAIzLLrZkbVK5WHgHhFIYmS+K6ZhFkY/Hi/5gPOhLUzvnu73L59KVxjyffXH314vFIsbYaTXeuXFtcHx4sPd9S+3l84PMwTsyBrMgQhUIgrEUREWUU4O8uhcLdW45BsWpiVRgoSyYTxYn/ee7e9/f/2Z8eOwYm8pko4EktDvpzOZXL5z3Dd3b2/vi/r1G0795cat//GxrvWPTaW+lvdVdXUkTCaVagAUrF6wKVSAGxIAQJEZYiVjSSrBSq4SVWCFWKINYpQzK4FHmhqjOgbF/+Hx0dJyXtv/46ZuXtrrd1V6ruRhNJqPZlfbq5999/Dt/+LNf/tf/nEyH585t73338OrVS3E8Pnl+MJnOi7i4fG1no7cJ79Sh7vPISwCwZYCERN3TjQCFZFxGE3FJV97iXCGIKBZlcyV799zbIdhsNnvyaP/x3r6Z+Tx02i6Kv/7WO8bFX/3ZT37xyZ2yf9Ta2n73vZ1vf/Xlv338+R/97MOVjc63X99fbXduvfuONBJTAlDxiBGAWKQZSVn2BZ4lDYwAlDQzkF7LEmYQyUSTdkvTzNuiZLz25vlOt3N0cPTwxcH7W2/9+NbN0Uef3Pvs6w/+9KcraePb3+z+6NKF+cHLvvN/89d/2SQsTSdr3clwMh0M1nvr0ki4yI0iQgBSu8dYOwxm4BIEyTrTEY1mHrNpZD3KiMIhlLEokljKWueyytsX3ji/2rqzuzt4Obh95eLd3+ztf7Xv1e2sp8OXw73h8Od//FNNtIh5Rqx322tZWoWimo1c7hQi4mgBxtPpA3VBkXQ0M8BOh5VoS3D8j3+CACqsR4EYzUyIalqaCqCxyIsB/uFf//lPfv93R/2jf/z4m0Zmf/6j977af/wXH/7B6ubK+dVV2+g6D0Yzg4OoA0kRrYoiEXcarFfzq7IueJKsYZktAXl7MRURiARakiQ08xAACHCGybj/i3v3ZoNyDa3/vPPg59cuf/fi4GKjPRmH99cuHT5+Ouv3ipV5b2ve2lxRdfPJLMa4ttKxEEl68ZH52bh4xkDhbLI2OYNiBpL+cHfmnKvfq2nf+eWXi2L+6PgQh42nk+GVc1uf7h9+f1T8ZOftXz76flu7L07Gs7FttCYvknH74PiDt24kjWa/PyvLElupJ2OMZFXBROS3hnoz8sxBS9+YYemhrw9L55xCFCYSalgR7Ehy/+DFnChC0kq3m37j9nr2L7uPnrw8UBb//t2emGsnybW8OW9M3uhc+fbprNWW0Qwh6MwKAQGEEIhlpccYSVLl/wkPM4unqEj6+7MyUZeIpj6pRxOJjDGO5qNpbNLsWTiSyt/dex5mR1Ui+9Phxe72w+moI1mmViSbG7xQNNpHlrhKBnkkcbIwi5WZGegpgMYYq6oCoKoiamZAfB1TWCoq+o/2DxzEiU/TNHXeBCGEqqqKGKGIDPOFTedDY8x8M5HEIRlXi5D7TtrsVpv5cDbZyB69eL7a6IjIfD6NNBHJy1A3tcRJCOV4Nmq1OiqZUgFznonzZVWIECoqXjWpijJGevVipFkZqipYKt6JE1XXjj5tJHk+n41jptrtrifqptNpq9WaTMcqyXon9VlqxHgyi5GjWa6qeZ5DJcsyM6OomVm04WQwnY3XIGkCQGEhzktjORoN8yp3zqVpI0lSUNXB59OhiChE1RdaSK0XSTNqoSSbmQe8F8Bi4jRN00WRr3TY7jSzJAEAQZIkCBUQo1aqmtSTHmJkrGApQtu7lodKKXDQGCyaaJo4mgeAEEPM667sd59/dyoQpUYDUQBCpZiqqmrNIgCEIKlgWS1OTl4OYl9gRoo40VgrRhGpP0G9qMZgFieTKgaKOFXQgolaCE7MBOrgnEO0aKWfLI7rWRaAnC4ATv3ZpiLiVQFYoCmzLAuhHI5eMsInIBkNUXTZUAERAVlvFSrziZoZFxOaaK3HAJOw1K9ArQXKMl/MJ7Ld6Z0l/1m86qMCGEXEe7+EW0+g4iFljCHxLQGcWq0NUp/Ur52K+Vc3ohrrFrs8PzhlJgBiKt7MYoxVKIpiIRudtdc9QSxheTPnHIAYCaNzTlXNzKg+YWRQpgKQRjGIB8Pyb0BJnv1ikFoYOwBEBKAEqFQlaRalFtqkc440n3IZrNp7Z4LExMpgy4SAVBaFVp9zhBCIaBQnDqhPSQgKIAJPksal+AG8ogpRnQCIUVRFoSEE9QIaLNCpqiPFQUK0/wPxadi/ncvxsAAAACV0RVh0ZGF0ZTpjcmVhdGUAMjAxMS0wMi0yOFQwMjo1NTowMiswMTowMGbLlncAAAAldEVYdGRhdGU6bW9kaWZ5ADIwMTEtMDItMjhUMDI6NTU6MDIrMDE6MDAXli7LAAAAEXRFWHRqcGVnOmNvbG9yc3BhY2UAMix1VZ8AAAAgdEVYdGpwZWc6c2FtcGxpbmctZmFjdG9yADF4MSwxeDEsMXgx6ZX8cAAAAABJRU5ErkJggg==</binary></FictionBook>
+<FictionBook xmlns="http://www.gribuser.ru/xml/fictionbook/2.0" xmlns:l="http://www.w3.org/1999/xlink"><description><title-info><genre>unrecognised</genre></title-info><document-info><program-used>pandoc</program-used></document-info></description><body><title><p /></title><section><p>This example test if Pandoc correctly embeds images into FictionBook.</p><p>Small inline image: <image l:href="#image1" l:type="inlineImageType" alt="alt text a small PNG image" />.</p><p>Paragraph image:</p><image l:href="#image2" l:type="imageType" alt="alt text of a big JPEG image" title="image title text" /><p>alt text of a big missing image</p><p>A missing image inline: alt text of missing image.</p></section></body><binary id="image2" content-type="image/jpeg">/9j/4AAQSkZJRgABAQEASABIAAD/4QOoRXhpZgAATU0AKgAAAAgAFgD+AAQAAAABAAAAAQEPAAIAAAAUAAABFgEQAAIAAAAUAAABKgESAAMAAAABAAEAAAExAAIAAAAdAAABPgEyAAIAAAAUAAABXEdGAAkAAAABAAAAAkdJAAkAAAABAAAAKIdpAAQAAAABAAACXMYSAAEAAAAEAQEAAMYTAAEAAAAEAQEAAMYUAAIAAAAMAAABcMYhAAoAAAAJAAABfMYiAAoAAAAJAAABxMYnAAUAAAADAAACDMYoAAUAAAADAAACJMYqAAoAAAABAAACPMYrAAUAAAABAAACRMYsAAUAAAABAAACTMYuAAUAAAABAAACVMZaAAMAAAABABEAAMZbAAMAAAABABUAAAAAAABQRU5UQVggICAgICAgICAgICAgAFBFTlRBWCBLMjBEICAgICAgICAAZGFya3RhYmxlIDAuNy4xKzkxM35nYTA5MzllYQAAMjAxMTowMjowNiAwNzoyOToxNgBQRU5UQVggSzIwRAAAAZM/AAEAAP//NuAAAQAA///jlgABAAD//2viAAEAAAABh0EAAQAAAABNLwABAAD//+62AAEAAAAAKd8AAQAAAAFHQAABAAAAASNbAAEAAP//py8AAQAA///Z7gABAAD//4X3AAEAAAABWGsAAQAAAAAZVgABAAD//9qsAAEAAAAAUBMAAQAAAACr2QABAAAAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAEAAAABdAAAAQAAAAEAAAABAAAAAWX//4AAAAEAAAAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAVgpoABQAAAAEAAANegp0ABQAAAAEAAANmiCIAAwAAAAEAAQAAiCcAAwAAAAEAyAAAkAMAAgAAABQAAANukAQAAgAAABQAAAOCkgQACgAAAAEAAAOWkgcAAwAAAAEABQAAkgkAAwAAAAEAEAAAkgoABQAAAAEAAAOeoAEAAwAAAAEAAQAAohcAAwAAAAEAAgAApAEAAwAAAAEAAAAApAIAAwAAAAEAAQAApAMAAwAAAAEAAAAApAUAAwAAAAEAhwAApAYAAwAAAAEAAAAApAgAAwAAAAEAAAAApAkAAwAAAAEAAAAApAoAAwAAAAEAAAAApAwAAwAAAAEAAwAAAAAAAAAAAAEAAAAyAAAAHAAAAAoyMDExOjAyOjA2IDA3OjI5OjE2ADIwMTE6MDI6MDYgMDc6Mjk6MTYAAAAACgAAAAoAAP/iAxhJQ0NfUFJPRklMRQABAQAAAwhsY21zBCAAAG1udHJSR0IgWFlaIAfbAAIACgAWABAAGmFjc3BBUFBMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD21gABAAAAANMtbGNtcwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADWRlc2MAAAEgAAAAUGNwcnQAAAFwAAAAgHd0cHQAAAHwAAAAFGNoYWQAAAIEAAAALHJYWVoAAAIwAAAAFGJYWVoAAAJEAAAAFGdYWVoAAAJYAAAAFHJUUkMAAAJsAAAAIGdUUkMAAAKMAAAAIGJUUkMAAAKsAAAAIGNocm0AAALMAAAAJGRtbmQAAALwAAAADWRtZGQAAAMAAAAABW1sdWMAAAAAAAAAAQAAAAxlblVTAAAANAAAABwAUgAAAEcAAABCAAAAIAAAAGIAAAB1AAAAaQAAAGwAAAB0AAAALQAAAGkAAABuAAAAAAAAbWx1YwAAAAAAAAABAAAADGVuVVMAAABkAAAAHABOAAAAbwAAACAAAABjAAAAbwAAAHAAAAB5AAAAcgAAAGkAAABnAAAAaAAAAHQAAAAsAAAAIAAAAHUAAABzAAAAZQAAACAAAABmAAAAcgAAAGUAAABlAAAAbAAAAHkAAAAAAABYWVogAAAAAAAA9tYAAQAAAADTLXNmMzIAAAAAAAEMSgAABeP///MqAAAHmwAA/Yf///ui///9owAAA9gAAMCUWFlaIAAAAAAAAG+UAAA47gAAA5BYWVogAAAAAAAAJJ0AAA+DAAC2vlhZWiAAAAAAAABipQAAt5AAABjecGFyYQAAAAAAAwAAAAJmZgAA8qcAAA1ZAAAT0AAACltwYXJhAAAAAAADAAAAAmZmAADypwAADVkAABPQAAAKW3BhcmEAAAAAAAMAAAACZmYAAPKnAAANWQAAE9AAAApbY2hybQAAAAAAAwAAAACj1wAAVHsAAEzNAACZmgAAJmYAAA9cKGR0IGludGVybmFsKQAAAHNSR0IAAAAA/9sAQwAbEhQXFBEbFxYXHhwbIChCKyglJShROj0wQmBVZWRfVV1baniZgWpxkHNbXYW1hpCeo6utq2eAvMm6pseZqKuk/9sAQwEcHh4oIyhOKytOpG5dbqSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSk/8AAEQgAgADAAwERAAIRAQMRAf/EABkAAAMBAQEAAAAAAAAAAAAAAAEAAwQCBf/EADIQAAEDAwMDAQYGAgMAAAAAAAEAAhEDEiExE1EEQWEiQpFxI4GxFFLwMqEF0eEkYsH/xAAXAQEBAQEAAAAAAAAAAAAAAAAAAQID/8QAGxEBAQEBAAMBAAAAAAAAAAAAABEBEgIxIUH/2gAMAwEAAhEDEQA/APehabMIGEDCBhAwgYQMoATGdQgQ4GI7oCgEIFAoGEAVAhAoAgYQBAECigqNCwhRSiFBw54aEUWvDhIKDpERqGDMqqg6rIsbr2Co7Y4lrc50Ed8qC4cDjugMogoFAECgUUEAhAoAgEKhQBBoWAoFAHCfiqMtZxaCKhjz2VGShXLPS6QQ3ug1N6gbgaQZicaICKm48lkY0M6oOOoDGupkyWE5xp+iiAWupsYHD1EAADlFdF74ggNdOkIKNJLrSSecILtUBhAECgCBQBAqgIAgCBQaFlCgCDJ1FdzMNJB4wqrhlZrzZVBDoiI1QZOrpOkOa8ENabCRM+CqE1A1jS4EEDMHA+iDU53oaYDT2jUf5UGZ1V0xJudaSD7JDhn9cKjS2s0VxcC5wAjnKg5fdV6p0uAa0DPYKjRRe1lIxmO/KhCOpaHkGdYQXDge6AoGEAQKAIAgUAQBAEGhZQoFBCo2nock9lVQNA33tdLRm3Uqo46mi1/TuioSw5k+yeUEqDTUZ8zBJ26k89j+uQipvApN/Duabg2WPHcDsgl1Nz6FOrTa6bXH08RP+EGiqW0unNYGXO9cHXJwPsglcRSD3ujxMl0qi7XAUjL4GjQ6JKgpSBj0tdkyC46oNNJrvaIlBaFAoFAECiggCBKAIAqLrLJQcvzgIoNZGpKI5exuvqEdwUGd729O4vvDmu/cMSPKqslaqyk8vJ/49QWuH5D2093uQ9KPO70oeS4GnrGsDBQZqrrehaWEQabmEf8Aa0/eFUFkGmKlYkuHpYzsTpJ5RVWU3Bw26bQ4CCT7I+PPj7IK0KT3m4YaDgnNyg2tptmXep3JQdhoGigKAIFFBAoAgUAQBAFRZZQzCDlzgAgQ7X4IIPebvVFvCqpWhziXMf4kf4QQqspNllgdRcYgey49vH68Koy9NVrs6mpRAc5zRJDtXdp90IJdU67pOlptxc4N8yJE/wAomrUKdT8W8UTdTZ6GnWwd/wCZRWi5oI6ZrvDiOOPiUVrY4N0LwYjtCgowOH7iZQWBwiFQKoVFBAoAilAEAQBUVlZZAnCKy1XuktbBPHCKl+IcwAvY4azkH7FUVaWuALXYJmRlB2RTAFznE83FSpGbqdupSfFQ3EYBP/qtIxMu6nrBd8vqqTDkcgj+DJV/Eef1dRzXFjwWPbUJI4mMq4mvV6YGh07KDQQ97cN5Pcnx/pRrMEDp6QABugF1xzn7ZRcaadakykJdaJ0/0oq9PqGVDgzGAiRYOlEgygZQCVFMoFAJQMooSgZQCVR1KyhJkIOQwNGNUHDgACYM+EVnqUHXBzKQBPMEfUK1GZ+410VDafyDv8Ciqsp06jMummYwMZ8oRne/Z/selc4Sc0y8e0IxPmVfxncms398xv4qi4NBLhHxz3V8U8saemfuPcX66uz7m/AKa3mNvUPLg2lSaHVHic+yOSpienNDotl0l7nuOpHpn3JuqtUokmWvLTyM/dKho3NJbUJ8HlFaAUDKhAlCGUIEoplCBKBlCBKLAlCDcoQbkIbkI5JzPCEcl0unhCOKoY8RUAI4KpGDqKh6T1seXUnDLXajyr7SRz1RNb+vp1Wj1sAqN76Jns3LlYeurs6ur04ozI9+VrMjHltkaw5tB220es4lx08lZ9unr439I9tMRfcXZLjqSppy1NqBxQg3IQCQTlCCHQhDcoQLkWG5CBchDchAuRYFyENyEC5UiW8FeWoO8FJpB3gk0h3gkIBqgDukIx9RVvBjLQJE5WsxNZWl7hEkjTOR9VYyFB1nyKl8tGCDqO2EiePz5rA+KXW/KcCA4QSr+OW/PL49I7TAHON9QnLu/wCvCjtMxQVWgztyfphSKvT6m15Gg7JFahVBCkWODW+aMwISI73UindCQDdHKQO4kA3PKQDcSB3UgG6kA3UgG6rBlFUcrpHPsdzykOhvKQ6O4kOk6tUuFo96Q6RqOhoaDMJGenDazGttkDukOk6lQ1HE0yL2SQQYlIm+VY5NSvI18qOdutTasumJI/hWN55K0nuyBE95KRrPJelJ/f7kjXTQHwNUi9OTU+Z9EidO9xIvQbiQ6O55SHTk1Y7pDo7iQ6O4kOg3PKQ6DcKQ6O4eUh0BqFInTFkFbcBDnA4JQd3P/MULoEuOpJQc2lBzUkDRBwAXGFEFzYHhFZSbapjGVn9RSnnAKuC4vGkiOFpape8QbihdHdf+YoXXO48u/cULpudyUKEnlCg57gNShXLajicklCu7jOqFC9w7lCg6s8DBKhdD8Q8nVC6O+7lC6d1x9pUup7zuVmhFZ3KtB33cpSnfdylKd535ilKTWJ1KUEVY0SgGpISjNVy6eVnUVoODW6K4K7ytUd5KBveEoG4JnKUdbyUDdSgGpIhKgMdalB3AlU3jlKOS4FKjlQHEaqgY5QQuKwG8oDeVQ3lShvPCoN6BvShvQckyoC10CFR1egb0DegbwgbwgbggbvKBvHKBuQN/lKG/ygF3lAl3lKOHunRQCFAIKA5QDKBQGUCqFAoplEMoplEFAoFAJQKBQP0QKBQBAoFB/9k=</binary><binary id="image1" content-type="image/png">iVBORw0KGgoAAAANSUhEUgAAADAAAAAgCAIAAADbtmxLAAABmGlDQ1BpY2MAAHjapdG/axMBGMbxTy4tldJSwSAiHW4ootKCqIOrVShIkRIrJNUluUvaQi4Nd1dEXAQHF4cOXVRcLOLirJv4BygIggqCi7sUBRcpcbiDgtBBfOGF5/315eV9qR7qRUk2EpL087S+MB82mivh2BeBcUcddrwVZYOLS0uLDrRfH1Xgw1wvSjL/ZpNxJ4uohFiKBmlOZYC7t/JBTmUXtWitFROMYDZtNFcIzqDWLvRl1FYL3UAtXa5fIughXC30A4TtQr9AGK2lCcFbzMRJPybYxWScxDFVGE16m1G5ZwUTnf71aziPaXUsYB4h2tjEOnrIMVfG/QJyAC/GtKvYKFlRqQe4jbTkrGKtZM+WvZvI0CnjbtnfKb1XMtBoroR//yzrnjtbbDRxhdFvw+HP04w9Zu/+cPj76XC4t0P1M2+29+c3trnwnerWfm7mCVP3ePl6P9d+xqstjn0dtNIWitMG3S4/njPZ5Mh7xm/8b734Z1m384nlOyy+4+EjTnSZunkyzsP1ft5J+63eKWT1hXn4AzDofghlJQBJAAAACXBIWXMAAAsSAAALEgHS3X78AAACInpUWHRSYXcgcHJvZmlsZSB0eXBlIGV4aWYAAHjahVRJtiQhCNx7ijpCMIhyHNPU9/oGffxeaNY3p/5VC5IAQkAhtL9/evh8Pp+PiwaNKZubAYDuugNcMH4ZIAN6A6ATo68kdAA8VQ1DkoEIq2EILiBiALIQDTISWvz3SSQNJHwnilWTGgC/ZMSa1Fc8TDznZH4rgWOtRrwQKGh8VyNZ8bAY9Ccj1EGXUI0JwNE3n3itxrzis7Sq1TgBiNMwesKo1TjfcdZqXBaiWRpLrcbbEjBLU63G9QGv1bit+CSKWi2W8+3QLDluF/wIBgBEaNQWNSjFzHj7/zgOP92EBap3v2BqlNi2pEbGVi0yBNwkcRPiTVxIJDVLRgJxEXGLRgAgLBASkiIIwlIEYgyBJCnC4lKExN6yGSW6SD961nvvQaxhBZq4rbptbX1HlJPSokN37t9m9957a5utDux7Xwk06WnWWOJ2yqgkPqW4e2urnmNPK0HMtq0Hkkc7ZbSXUleHiNMIoGy7r/ppEwAIV+Amv1rS/3ghgCz23ns+m/HrASdJMWT2chsBiS2z73fcLGd+3E8hZ05nQ81zzOW2n8Saj1VzwTMHZ+g6xcPg5ozLASM7Z/hl9kaPnPFQmrcyvm8lFKbrAQwAoegtYFy34rEXRSFP/qEo4tmQ0wywlwPyG5G/BJQXvF5wOR4k7m9HjlupR/y6Mp42RjhWxm+Oh99BvMrwD3UCiGvkpxuRAAAACXZwQWcAAAAwAAAAIACELJ4GAAALGklEQVRYw11YW48dV1b+1tq7qs6t+/TldPsSx3bbcRwncWY0A4LMCOYFXpgHJCR4QvwAnpAQj/wB/gR/ACR4QUKDECMUEjLOZew4zsRxuu122+52n9Pnfuqy9/p4qNNtD1tLpVKpap/vrMu31rdl/nAgIjSpF0kAJAEHGJwAAIQheqeARVqomCQZGUkjSYLmTAyAkCJiESRVNYQAaL3h8k3SzPj6MjEzsr7SqyoAcRABQItRVZ14kqifmNEkTZNiUZiZ934xm4WE3mva8GYGAA5UJ8YYIyCipiKk1ZuTBAhQBGZQFRKvTAgBaQBIeOekBqpa+0gBxFgAlmhqhixJzUKMRVEUx/3RWmel3z9xzrVX2+tuRb3WnrDKVFUEgKlCVWI055WMZ76AieipX0AYzYwQUZqZqJD0tKCqFJAxhKiqSZKooirj06fPMt/odlezhngFYar+0e7jxWLR6/Vc7ubzpNnM4BlDSDLvvQ8hnAYFIlCFRUDEjASgIGFGEcBIoSrMCFAVhgiKTxJPkgJVSeBBhKqaTCb5Ip4cD/efPP/g9q2soSvdTp7nAuv2Vk/2BoHFyWgRYxVjbDezRiMDMicNxqCqqhIZVZxZVK3zaRkgXYaMdeDMoMoapSpo8GSE1t6ihaCqPs3WV/VwPpxOp8fHRw++cUmq7XYzSbLV1W5vu3fw7Emn0xwcD+ZzF8vKQtlI09R7J6SXOldgEDEwAmdguMyYV/lEVWEkARExEkoVBxHWxeUSFefK6fTJ48dlme/sXN7a3vjVnf8NIQ6Hk1ajOZ+Nf/3ZZ9Uij0V+fedqM0v2nz5ut7LtCz1GC2WVJqmry1KgZKLqlbo0qLPanJrAVKgSRX/LPElxQF0smiDy6Ojo7pd3qXLjxo2r1y8fnwxORpN8Nt/u9fLF5OTFcRVKDWE0HJZF2O71IsOzZ0+e7D3tdDo7168miU9SJ6IhBIGD2KuKMpHaPwoFXkXq9Aak+/u//TsFRCEgEAljjFtbW+UiHPb765sbJ8M+Y9HtdAbDgWs0pSge7O1u9Tar+Xwwmy0m03I0XpgbjydZlk2n43armaVOJIqQDEIIIKBABK/iBYuAnT4HwJrx1CkhRosAIRBBo93ImunO25dv/eBmb231+rUrRTH/we1ba+udhw/uSoZGOzt38Vx/1D85folYLhazqpg3mj5ruNWVTqPhxcEsAOa8ihJiAhMEQVChCgXmhKcWT41O6IGq5kCjqPOTk9F4PF7rrlvKRtQHjx/d2Lk+mgy+evrwhzs3Xuzv0tmbb5z79LNPzm9utdorEoNkzPPx+x+812o10tR7DyCqUwCMQUUIUqm2JOolbb/GjmbwoDGS9GZBnYM4IS0E5+TChS1Nk7Z28uPhW29euvPRf2fN1pdffNE1vXnzxsGgf/B036duvbce5tXG2uZkfnL79q3t8+sA4Rws0CJIAOI8LADUusLqeC0rTl4RJgyg1Fe+fB7yUrxTQoRWVoExbWTjl6P5fD7dO6yIF4P+bDK/92T3hzffLWGffPq5c7K1uf7hj3+PrLqbqxffuDQc9VdWVtY31846l1CFqJlalk8gr/UxAIzLLrZkbVK5WHgHhFIYmS+K6ZhFkY/Hi/5gPOhLUzvnu73L59KVxjyffXH314vFIsbYaTXeuXFtcHx4sPd9S+3l84PMwTsyBrMgQhUIgrEUREWUU4O8uhcLdW45BsWpiVRgoSyYTxYn/ee7e9/f/2Z8eOwYm8pko4EktDvpzOZXL5z3Dd3b2/vi/r1G0795cat//GxrvWPTaW+lvdVdXUkTCaVagAUrF6wKVSAGxIAQJEZYiVjSSrBSq4SVWCFWKINYpQzK4FHmhqjOgbF/+Hx0dJyXtv/46ZuXtrrd1V6ruRhNJqPZlfbq5999/Dt/+LNf/tf/nEyH585t73338OrVS3E8Pnl+MJnOi7i4fG1no7cJ79Sh7vPISwCwZYCERN3TjQCFZFxGE3FJV97iXCGIKBZlcyV799zbIdhsNnvyaP/x3r6Z+Tx02i6Kv/7WO8bFX/3ZT37xyZ2yf9Ta2n73vZ1vf/Xlv338+R/97MOVjc63X99fbXduvfuONBJTAlDxiBGAWKQZSVn2BZ4lDYwAlDQzkF7LEmYQyUSTdkvTzNuiZLz25vlOt3N0cPTwxcH7W2/9+NbN0Uef3Pvs6w/+9KcraePb3+z+6NKF+cHLvvN/89d/2SQsTSdr3clwMh0M1nvr0ki4yI0iQgBSu8dYOwxm4BIEyTrTEY1mHrNpZD3KiMIhlLEokljKWueyytsX3ji/2rqzuzt4Obh95eLd3+ztf7Xv1e2sp8OXw73h8Od//FNNtIh5Rqx322tZWoWimo1c7hQi4mgBxtPpA3VBkXQ0M8BOh5VoS3D8j3+CACqsR4EYzUyIalqaCqCxyIsB/uFf//lPfv93R/2jf/z4m0Zmf/6j977af/wXH/7B6ubK+dVV2+g6D0Yzg4OoA0kRrYoiEXcarFfzq7IueJKsYZktAXl7MRURiARakiQ08xAACHCGybj/i3v3ZoNyDa3/vPPg59cuf/fi4GKjPRmH99cuHT5+Ouv3ipV5b2ve2lxRdfPJLMa4ttKxEEl68ZH52bh4xkDhbLI2OYNiBpL+cHfmnKvfq2nf+eWXi2L+6PgQh42nk+GVc1uf7h9+f1T8ZOftXz76flu7L07Gs7FttCYvknH74PiDt24kjWa/PyvLElupJ2OMZFXBROS3hnoz8sxBS9+YYemhrw9L55xCFCYSalgR7Ehy/+DFnChC0kq3m37j9nr2L7uPnrw8UBb//t2emGsnybW8OW9M3uhc+fbprNWW0Qwh6MwKAQGEEIhlpccYSVLl/wkPM4unqEj6+7MyUZeIpj6pRxOJjDGO5qNpbNLsWTiSyt/dex5mR1Ui+9Phxe72w+moI1mmViSbG7xQNNpHlrhKBnkkcbIwi5WZGegpgMYYq6oCoKoiamZAfB1TWCoq+o/2DxzEiU/TNHXeBCGEqqqKGKGIDPOFTedDY8x8M5HEIRlXi5D7TtrsVpv5cDbZyB69eL7a6IjIfD6NNBHJy1A3tcRJCOV4Nmq1OiqZUgFznonzZVWIECoqXjWpijJGevVipFkZqipYKt6JE1XXjj5tJHk+n41jptrtrifqptNpq9WaTMcqyXon9VlqxHgyi5GjWa6qeZ5DJcsyM6OomVm04WQwnY3XIGkCQGEhzktjORoN8yp3zqVpI0lSUNXB59OhiChE1RdaSK0XSTNqoSSbmQe8F8Bi4jRN00WRr3TY7jSzJAEAQZIkCBUQo1aqmtSTHmJkrGApQtu7lodKKXDQGCyaaJo4mgeAEEPM667sd59/dyoQpUYDUQBCpZiqqmrNIgCEIKlgWS1OTl4OYl9gRoo40VgrRhGpP0G9qMZgFieTKgaKOFXQgolaCE7MBOrgnEO0aKWfLI7rWRaAnC4ATv3ZpiLiVQFYoCmzLAuhHI5eMsInIBkNUXTZUAERAVlvFSrziZoZFxOaaK3HAJOw1K9ArQXKMl/MJ7Ld6Z0l/1m86qMCGEXEe7+EW0+g4iFljCHxLQGcWq0NUp/Ur52K+Vc3ohrrFrs8PzhlJgBiKt7MYoxVKIpiIRudtdc9QSxheTPnHIAYCaNzTlXNzKg+YWRQpgKQRjGIB8Pyb0BJnv1ikFoYOwBEBKAEqFQlaRalFtqkc440n3IZrNp7Z4LExMpgy4SAVBaFVp9zhBCIaBQnDqhPSQgKIAJPksal+AG8ogpRnQCIUVRFoSEE9QIaLNCpqiPFQUK0/wPxadi/ncvxsAAAACV0RVh0ZGF0ZTpjcmVhdGUAMjAxMS0wMi0yOFQwMjo1NTowMiswMTowMGbLlncAAAAldEVYdGRhdGU6bW9kaWZ5ADIwMTEtMDItMjhUMDI6NTU6MDIrMDE6MDAXli7LAAAAEXRFWHRqcGVnOmNvbG9yc3BhY2UAMix1VZ8AAAAgdEVYdGpwZWc6c2FtcGxpbmctZmFjdG9yADF4MSwxeDEsMXgx6ZX8cAAAAABJRU5ErkJggg==</binary></FictionBook>
diff --git a/test/fb2/meta.fb2 b/test/fb2/meta.fb2
new file mode 100644
--- /dev/null
+++ b/test/fb2/meta.fb2
@@ -0,0 +1,3 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<FictionBook xmlns="http://www.gribuser.ru/xml/fictionbook/2.0" xmlns:l="http://www.w3.org/1999/xlink"><description><title-info><genre>unrecognised</genre><book-title>Book title</book-title><annotation><p>This is the abstract.</p><p>It consists of two paragraphs.</p></annotation></title-info><document-info><program-used>pandoc</program-used></document-info></description><body><title><p>Book title</p></title></body></FictionBook>
+
diff --git a/test/fb2/meta.markdown b/test/fb2/meta.markdown
new file mode 100644
--- /dev/null
+++ b/test/fb2/meta.markdown
@@ -0,0 +1,7 @@
+---
+title: Book title
+abstract: |
+  This is the abstract.
+
+  It consists of two paragraphs.
+---
diff --git a/test/fb2/reader/emphasis.fb2 b/test/fb2/reader/emphasis.fb2
new file mode 100644
--- /dev/null
+++ b/test/fb2/reader/emphasis.fb2
@@ -0,0 +1,11 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<FictionBook xmlns="http://www.gribuser.ru/xml/fictionbook/2.0" xmlns:l="http://www.w3.org/1999/xlink">
+	<body>
+		<section>
+			<p>Plain, <strong>strong</strong>, <emphasis>emphasis</emphasis>, <strong><emphasis>strong emphasis</emphasis></strong>, <emphasis><strong>emphasized strong</strong></emphasis>.</p>
+			<p>Strikethrough: <strikethrough>deleted</strikethrough></p>
+			<p><sub>Subscript</sub> and <sup>superscript</sup></p>
+			<p>Some <code>code</code></p>
+		</section>
+	</body>
+</FictionBook>
diff --git a/test/fb2/reader/emphasis.native b/test/fb2/reader/emphasis.native
new file mode 100644
--- /dev/null
+++ b/test/fb2/reader/emphasis.native
@@ -0,0 +1,35 @@
+Pandoc
+  Meta { unMeta = fromList [] }
+  [ Div
+      ( "" , [ "section" ] , [] )
+      [ Para
+          [ Str "Plain,"
+          , Space
+          , Strong [ Str "strong" ]
+          , Str ","
+          , Space
+          , Emph [ Str "emphasis" ]
+          , Str ","
+          , Space
+          , Strong [ Emph [ Str "strong" , Space , Str "emphasis" ] ]
+          , Str ","
+          , Space
+          , Emph
+              [ Strong [ Str "emphasized" , Space , Str "strong" ] ]
+          , Str "."
+          ]
+      , Para
+          [ Str "Strikethrough:"
+          , Space
+          , Strikeout [ Str "deleted" ]
+          ]
+      , Para
+          [ Subscript [ Str "Subscript" ]
+          , Space
+          , Str "and"
+          , Space
+          , Superscript [ Str "superscript" ]
+          ]
+      , Para [ Str "Some" , Space , Code ( "" , [] , [] ) "code" ]
+      ]
+  ]
diff --git a/test/fb2/reader/epigraph.fb2 b/test/fb2/reader/epigraph.fb2
new file mode 100644
--- /dev/null
+++ b/test/fb2/reader/epigraph.fb2
@@ -0,0 +1,18 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<FictionBook xmlns="http://www.gribuser.ru/xml/fictionbook/2.0" xmlns:l="http://www.w3.org/1999/xlink">
+	<body>
+		<epigraph>
+			<p>Body epigraph</p>
+		</epigraph>
+		<section>
+			<epigraph>
+				<p>Section epigraph</p>
+			</epigraph>
+			<section>
+				<epigraph>
+					<p>Subsection epigraph</p>
+				</epigraph>
+			</section>
+		</section>
+	</body>
+</FictionBook>
diff --git a/test/fb2/reader/epigraph.native b/test/fb2/reader/epigraph.native
new file mode 100644
--- /dev/null
+++ b/test/fb2/reader/epigraph.native
@@ -0,0 +1,18 @@
+Pandoc
+  Meta { unMeta = fromList [] }
+  [ Div
+      ( "" , [ "epigraph" ] , [] )
+      [ Para [ Str "Body" , Space , Str "epigraph" ] ]
+  , Div
+      ( "" , [ "section" ] , [] )
+      [ Div
+          ( "" , [ "epigraph" ] , [] )
+          [ Para [ Str "Section" , Space , Str "epigraph" ] ]
+      , Div
+          ( "" , [ "section" ] , [] )
+          [ Div
+              ( "" , [ "epigraph" ] , [] )
+              [ Para [ Str "Subsection" , Space , Str "epigraph" ] ]
+          ]
+      ]
+  ]
diff --git a/test/fb2/reader/meta.fb2 b/test/fb2/reader/meta.fb2
new file mode 100644
--- /dev/null
+++ b/test/fb2/reader/meta.fb2
@@ -0,0 +1,26 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<FictionBook xmlns="http://www.gribuser.ru/xml/fictionbook/2.0" xmlns:l="http://www.w3.org/1999/xlink">
+	<description>
+		<title-info>
+			<author>
+				<first-name>First</first-name>
+				<middle-name>Middle</middle-name>
+				<last-name>Last</last-name>
+			</author>
+			<author>
+				<first-name>Another</first-name>
+				<last-name>Author</last-name>
+			</author>
+			<book-title>Book title</book-title>
+			<annotation>
+				<p>Book annotation</p>
+				<p>Second paragraph of book annotation</p>
+			</annotation>
+			<keywords>foo, bar, baz</keywords>
+			<date>2018</date>
+		</title-info>
+	</description>
+	<body>
+		<title><p>Body title</p></title>
+	</body>
+</FictionBook>
diff --git a/test/fb2/reader/meta.native b/test/fb2/reader/meta.native
new file mode 100644
--- /dev/null
+++ b/test/fb2/reader/meta.native
@@ -0,0 +1,48 @@
+Pandoc
+  Meta
+    { unMeta =
+        fromList
+          [ ( "abstract"
+            , MetaBlocks
+                [ Para [ Str "Book" , Space , Str "annotation" ]
+                , Para
+                    [ Str "Second"
+                    , Space
+                    , Str "paragraph"
+                    , Space
+                    , Str "of"
+                    , Space
+                    , Str "book"
+                    , Space
+                    , Str "annotation"
+                    ]
+                ]
+            )
+          , ( "author"
+            , MetaList
+                [ MetaInlines
+                    [ Str "First"
+                    , Space
+                    , Str "Middle"
+                    , Space
+                    , Str "Last"
+                    ]
+                , MetaInlines [ Str "Another" , Space , Str "Author" ]
+                ]
+            )
+          , ( "date" , MetaInlines [ Str "2018" ] )
+          , ( "keywords"
+            , MetaList
+                [ MetaString "foo"
+                , MetaString "bar"
+                , MetaString "baz"
+                ]
+            )
+          , ( "title"
+            , MetaInlines [ Str "Book" , Space , Str "title" ]
+            )
+          ]
+    }
+  [ Header
+      1 ( "" , [] , [] ) [ Str "Body" , Space , Str "title" ]
+  ]
diff --git a/test/fb2/reader/notes.fb2 b/test/fb2/reader/notes.fb2
new file mode 100644
--- /dev/null
+++ b/test/fb2/reader/notes.fb2
@@ -0,0 +1,19 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<FictionBook xmlns="http://www.gribuser.ru/xml/fictionbook/2.0" xmlns:l="http://www.w3.org/1999/xlink">
+	<body>
+		<section>
+			<p>Note <a l:href="#n1" type="note">1</a>.</p>
+			<p>Second note <a l:href="#n2" type="note">2</a>.</p>
+		</section>
+	</body>
+	<body name="notes">
+		<section id="n1">
+			<title><p>1</p></title>
+			<p>Note contents</p>
+		</section>
+		<section id="n2">
+			<title><p>2</p></title>
+			<p>Second note contents.</p>
+		</section>
+	</body>
+</FictionBook>
diff --git a/test/fb2/reader/notes.native b/test/fb2/reader/notes.native
new file mode 100644
--- /dev/null
+++ b/test/fb2/reader/notes.native
@@ -0,0 +1,28 @@
+Pandoc
+  Meta { unMeta = fromList [] }
+  [ Div
+      ( "" , [ "section" ] , [] )
+      [ Para
+          [ Str "Note"
+          , Space
+          , Note [ Para [ Str "Note" , Space , Str "contents" ] ]
+          , Str "."
+          ]
+      , Para
+          [ Str "Second"
+          , Space
+          , Str "note"
+          , Space
+          , Note
+              [ Para
+                  [ Str "Second"
+                  , Space
+                  , Str "note"
+                  , Space
+                  , Str "contents."
+                  ]
+              ]
+          , Str "."
+          ]
+      ]
+  ]
diff --git a/test/fb2/reader/poem.fb2 b/test/fb2/reader/poem.fb2
new file mode 100644
--- /dev/null
+++ b/test/fb2/reader/poem.fb2
@@ -0,0 +1,28 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<FictionBook xmlns="http://www.gribuser.ru/xml/fictionbook/2.0" xmlns:l="http://www.w3.org/1999/xlink">
+	<body>
+		<section>
+			<poem>
+				<title>
+					<p>Poem title</p>
+				</title>
+				<epigraph>
+					<p>Poem epigraph</p>
+				</epigraph>
+				<stanza>
+					<subtitle>Subtitle</subtitle>
+					<title>
+						<p>First stanza title</p>
+					</title>
+					<v>Verse</v>
+					<v><emphasis>More</emphasis> verse</v>
+				</stanza>
+				<stanza>
+					<v>One more stanza</v>
+				</stanza>
+				<text-author>Author</text-author>
+				<date>April 2018</date>
+			</poem>
+		</section>
+	</body>
+</FictionBook>
diff --git a/test/fb2/reader/poem.native b/test/fb2/reader/poem.native
new file mode 100644
--- /dev/null
+++ b/test/fb2/reader/poem.native
@@ -0,0 +1,25 @@
+Pandoc
+  Meta { unMeta = fromList [] }
+  [ Div
+      ( "" , [ "section" ] , [] )
+      [ Header
+          2 ( "" , [] , [] ) [ Str "Poem" , Space , Str "title" ]
+      , Div
+          ( "" , [ "epigraph" ] , [] )
+          [ Para [ Str "Poem" , Space , Str "epigraph" ] ]
+      , Header 2 ( "" , [ "unnumbered" ] , [] ) [ Str "Subtitle" ]
+      , Header
+          2
+          ( "" , [] , [] )
+          [ Str "First" , Space , Str "stanza" , Space , Str "title" ]
+      , LineBlock
+          [ [ Str "Verse" ]
+          , [ Emph [ Str "More" ] , Space , Str "verse" ]
+          ]
+      , LineBlock
+          [ [ Str "One" , Space , Str "more" , Space , Str "stanza" ]
+          ]
+      , Para [ Str "Author" ]
+      , Para [ Str "April" , Space , Str "2018" ]
+      ]
+  ]
diff --git a/test/fb2/reader/titles.fb2 b/test/fb2/reader/titles.fb2
new file mode 100644
--- /dev/null
+++ b/test/fb2/reader/titles.fb2
@@ -0,0 +1,18 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<FictionBook xmlns="http://www.gribuser.ru/xml/fictionbook/2.0" xmlns:l="http://www.w3.org/1999/xlink">
+	<body>
+		<title><p>Body title</p></title>
+		<section>
+			<title><p>Section title</p></title>
+			<section>
+				<title>
+					<p>Subsection title</p>
+					<p>with multiple paragraphs</p>
+				</title>
+			</section>
+			<section>
+				<title><p>Another subsection title</p></title>
+			</section>
+		</section>
+	</body>
+</FictionBook>
diff --git a/test/fb2/reader/titles.native b/test/fb2/reader/titles.native
new file mode 100644
--- /dev/null
+++ b/test/fb2/reader/titles.native
@@ -0,0 +1,38 @@
+Pandoc
+  Meta { unMeta = fromList [] }
+  [ Header
+      1 ( "" , [] , [] ) [ Str "Body" , Space , Str "title" ]
+  , Div
+      ( "" , [ "section" ] , [] )
+      [ Header
+          2 ( "" , [] , [] ) [ Str "Section" , Space , Str "title" ]
+      , Div
+          ( "" , [ "section" ] , [] )
+          [ Header
+              3
+              ( "" , [] , [] )
+              [ Str "Subsection"
+              , Space
+              , Str "title"
+              , LineBreak
+              , Str "with"
+              , Space
+              , Str "multiple"
+              , Space
+              , Str "paragraphs"
+              ]
+          ]
+      , Div
+          ( "" , [ "section" ] , [] )
+          [ Header
+              3
+              ( "" , [] , [] )
+              [ Str "Another"
+              , Space
+              , Str "subsection"
+              , Space
+              , Str "title"
+              ]
+          ]
+      ]
+  ]
diff --git a/test/fb2/test.jpg b/test/fb2/test.jpg
Binary files a/test/fb2/test.jpg and b/test/fb2/test.jpg differ
diff --git a/test/fb2/titles.fb2 b/test/fb2/titles.fb2
--- a/test/fb2/titles.fb2
+++ b/test/fb2/titles.fb2
@@ -1,3 +1,3 @@
 <?xml version="1.0" encoding="UTF-8"?>
-<FictionBook xmlns="http://www.gribuser.ru/xml/fictionbook/2.0" xmlns:l="http://www.w3.org/1999/xlink"><description><title-info><genre>unrecognised</genre></title-info><document-info><program-used>pandoc</program-used></document-info></description><body><title><p /></title><section><title><p>Simple title</p></title><p>This example tests if Pandoc doesn’t insert forbidden elements in FictionBook titles.</p></section><section><title><p>Emphasized Strong Title</p></title></section></body></FictionBook>
+<FictionBook xmlns="http://www.gribuser.ru/xml/fictionbook/2.0" xmlns:l="http://www.w3.org/1999/xlink"><description><title-info><genre>unrecognised</genre></title-info><document-info><program-used>pandoc</program-used></document-info></description><body><title><p /></title><section 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/fb2/titles.markdown b/test/fb2/titles.markdown
--- a/test/fb2/titles.markdown
+++ b/test/fb2/titles.markdown
@@ -1,6 +1,6 @@
 # Simple title
 
-This example tests if Pandoc doesn't insert forbidden elements in FictionBook titles.
+This example tests FictionBook titles.
 
 # *Emphasized* **Strong** Title
 
diff --git a/test/haddock-reader.native b/test/haddock-reader.native
--- a/test/haddock-reader.native
+++ b/test/haddock-reader.native
@@ -1,31 +1,401 @@
-Pandoc (Meta {unMeta = fromList []})
-[Para [Str "This",Space,Str "file",Space,Str "tests",Space,Str "the",Space,Str "Pandoc",Space,Str "reader",Space,Str "for",Space,Str "Haddock.",SoftBreak,Str "We've",Space,Str "borrowed",Space,Str "examples",Space,Str "from",Space,Str "Haddock's",Space,Str "documentation:",Space,Link ("",[],[]) [Str "http://www.haskell.org/haddock/doc/html/ch03s08.html"] ("http://www.haskell.org/haddock/doc/html/ch03s08.html","http://www.haskell.org/haddock/doc/html/ch03s08.html"),Str "."]
-,Para [Str "The",Space,Str "following",Space,Str "characters",Space,Str "have",Space,Str "special",Space,Str "meanings",Space,Str "in",Space,Str "Haddock,",Space,Str "/,",Space,Str "',",Space,Str "`,",Space,Str "\",",Space,Str "@,",Space,Str "<,",Space,Str "so",Space,Str "they",Space,Str "must",Space,Str "be",Space,Str "escaped."]
-,Para [Str "*",Space,Str "This",Space,Str "is",Space,Str "a",Space,Str "paragraph,",Space,Str "not",Space,Str "a",Space,Str "list",Space,Str "item.",SoftBreak,Str ">",Space,Str "This",Space,Str "sentence",Space,Str "is",Space,Str "not",Space,Str "code.",SoftBreak,Str ">>>",Space,Str "This",Space,Str "is",Space,Str "not",Space,Str "an",Space,Str "example."]
-,Para [Str "The",Space,Str "references",Space,Str "\955,",Space,Str "\955",Space,Str "and",Space,Str "\955",Space,Str "all",Space,Str "represent",Space,Str "the",Space,Str "lower-case",Space,Str "letter",Space,Str "lambda."]
-,Para [Str "This",Space,Str "is",Space,Str "a",Space,Str "code",Space,Str "block:"]
-,CodeBlock ("",[],[]) "map :: (a -> b) -> [a] -> [b]\nmap _ []     = []\nmap f (x:xs) = f x : map f xs"
-,Para [Str "This",Space,Str "is",Space,Str "another",Space,Str "code",Space,Str "block:"]
-,Para [Code ("",[],[]) "f x = x + x.",LineBreak,Code ("",[],[]) "The @...@ code block ",Emph [Code ("",[],[]) "interprets markup normally"],Code ("",[],[]) ".",Code ("",["haskell","module"],[]) "Module.Foo",Code ("",[],[]) "",LineBreak,Code ("",[],[]) "\"Hello World\""]
-,Para [Str "Haddock",Space,Str "supports",Space,Str "REPL",Space,Str "examples:"]
-,Para [Code ("",["prompt"],[]) ">>>",Space,Code ("",["haskell","expr"],[]) "fib 10",LineBreak,Code ("",["result"],[]) "55"]
-,Para [Code ("",["prompt"],[]) ">>>",Space,Code ("",["haskell","expr"],[]) "putStrLn \"foo\\nbar\"",LineBreak,Code ("",["result"],[]) "foo",LineBreak,Code ("",["result"],[]) "bar"]
-,Para [Str "That",Space,Str "was",Space,Emph [Str "really",Space,Str "cool"],Str "!",SoftBreak,Str "I",Space,Str "had",Space,Str "no",Space,Str "idea",Space,Code ("",[],[]) "fib 10 = 55",Str "."]
-,Para [Str "This",Space,Str "module",Space,Str "defines",Space,Str "the",Space,Str "type",Space,Code ("",["haskell","identifier"],[]) "T",Str ".",SoftBreak,Str "The",Space,Str "identifier",Space,Code ("",["haskell","identifier"],[]) "M.T",Space,Str "is",Space,Str "not",Space,Str "in",Space,Str "scope",SoftBreak,Str "I",Space,Str "don't",Space,Str "have",Space,Str "to",Space,Str "escape",Space,Str "my",Space,Str "apostrophes;",Space,Str "great,",Space,Str "isn't",Space,Str "it?",SoftBreak,Str "This",Space,Str "is",Space,Str "a",Space,Str "reference",Space,Str "to",Space,Str "the",Space,Code ("",["haskell","module"],[]) "Foo",Space,Str "module."]
-,Para [Str "This",Space,Str "is",Space,Str "a",Space,Str "bulleted",Space,Str "list:"]
-,BulletList
- [[Para [Str "first",Space,Str "item"]]
- ,[Para [Str "second",Space,Str "item"]]]
-,Para [Str "This",Space,Str "is",Space,Str "an",Space,Str "enumerated",Space,Str "list:"]
-,OrderedList (1,DefaultStyle,DefaultDelim)
- [[Para [Str "first",Space,Str "item"]]
- ,[Para [Str "second",Space,Str "item"]]]
-,Para [Str "This",Space,Str "is",Space,Str "a",Space,Str "definition",Space,Str "list:"]
-,DefinitionList
- [([Code ("",[],[]) "foo"],
-   [[Para [Str "The",Space,Str "description",Space,Str "of",Space,Code ("",[],[]) "foo",Str "."]]])
- ,([Code ("",[],[]) "bar"],
-   [[Para [Str "The",Space,Str "description",Space,Str "of",Space,Code ("",[],[]) "bar",Str "."]]])]
-,Para [Str "Here",Space,Str "is",Space,Str "a",Space,Str "link:",Space,Link ("",[],[]) [Str "http://haskell.org"] ("http://haskell.org","http://haskell.org")]
-,Para [Link ("",[],[]) [Str "Haskell"] ("http://haskell.org","http://haskell.org"),Space,Str "is",Space,Str "a",Space,Str "fun",Space,Str "language!"]
-,Para [Link ("",[],[]) [Str "Click",Space,Str "Here!"] ("http://example.com","http://example.com")]]
+Pandoc
+  Meta { unMeta = fromList [] }
+  [ Para
+      [ Str "This"
+      , Space
+      , Str "file"
+      , Space
+      , Str "tests"
+      , Space
+      , Str "the"
+      , Space
+      , Str "Pandoc"
+      , Space
+      , Str "reader"
+      , Space
+      , Str "for"
+      , Space
+      , Str "Haddock."
+      , SoftBreak
+      , Str "We've"
+      , Space
+      , Str "borrowed"
+      , Space
+      , Str "examples"
+      , Space
+      , Str "from"
+      , Space
+      , Str "Haddock's"
+      , Space
+      , Str "documentation:"
+      , Space
+      , Link
+          ( "" , [] , [] )
+          [ Str "http://www.haskell.org/haddock/doc/html/ch03s08.html"
+          ]
+          ( "http://www.haskell.org/haddock/doc/html/ch03s08.html"
+          , "http://www.haskell.org/haddock/doc/html/ch03s08.html"
+          )
+      , Str "."
+      ]
+  , Para
+      [ Str "The"
+      , Space
+      , Str "following"
+      , Space
+      , Str "characters"
+      , Space
+      , Str "have"
+      , Space
+      , Str "special"
+      , Space
+      , Str "meanings"
+      , Space
+      , Str "in"
+      , Space
+      , Str "Haddock,"
+      , Space
+      , Str "/,"
+      , Space
+      , Str "',"
+      , Space
+      , Str "`,"
+      , Space
+      , Str "\","
+      , Space
+      , Str "@,"
+      , Space
+      , Str "<,"
+      , Space
+      , Str "so"
+      , Space
+      , Str "they"
+      , Space
+      , Str "must"
+      , Space
+      , Str "be"
+      , Space
+      , Str "escaped."
+      ]
+  , Para
+      [ Str "*"
+      , Space
+      , Str "This"
+      , Space
+      , Str "is"
+      , Space
+      , Str "a"
+      , Space
+      , Str "paragraph,"
+      , Space
+      , Str "not"
+      , Space
+      , Str "a"
+      , Space
+      , Str "list"
+      , Space
+      , Str "item."
+      , SoftBreak
+      , Str ">"
+      , Space
+      , Str "This"
+      , Space
+      , Str "sentence"
+      , Space
+      , Str "is"
+      , Space
+      , Str "not"
+      , Space
+      , Str "code."
+      , SoftBreak
+      , Str ">>>"
+      , Space
+      , Str "This"
+      , Space
+      , Str "is"
+      , Space
+      , Str "not"
+      , Space
+      , Str "an"
+      , Space
+      , Str "example."
+      ]
+  , Para
+      [ Str "The"
+      , Space
+      , Str "references"
+      , Space
+      , Str "\955,"
+      , Space
+      , Str "\955"
+      , Space
+      , Str "and"
+      , Space
+      , Str "\955"
+      , Space
+      , Str "all"
+      , Space
+      , Str "represent"
+      , Space
+      , Str "the"
+      , Space
+      , Str "lower-case"
+      , Space
+      , Str "letter"
+      , Space
+      , Str "lambda."
+      ]
+  , Para
+      [ Str "This"
+      , Space
+      , Str "is"
+      , Space
+      , Str "a"
+      , Space
+      , Str "code"
+      , Space
+      , Str "block:"
+      ]
+  , CodeBlock
+      ( "" , [] , [] )
+      "map :: (a -> b) -> [a] -> [b]\nmap _ []     = []\nmap f (x:xs) = f x : map f xs"
+  , Para
+      [ Str "This"
+      , Space
+      , Str "is"
+      , Space
+      , Str "another"
+      , Space
+      , Str "code"
+      , Space
+      , Str "block:"
+      ]
+  , Para
+      [ Code ( "" , [] , [] ) "f x = x + x."
+      , LineBreak
+      , Code ( "" , [] , [] ) "The @...@ code block "
+      , Emph
+          [ Code ( "" , [] , [] ) "interprets markup normally" ]
+      , Code ( "" , [] , [] ) "."
+      , Code ( "" , [ "haskell" , "module" ] , [] ) "Module.Foo"
+      , Code ( "" , [] , [] ) ""
+      , LineBreak
+      , Code ( "" , [] , [] ) "\"Hello World\""
+      ]
+  , Para
+      [ Str "Haddock"
+      , Space
+      , Str "supports"
+      , Space
+      , Str "REPL"
+      , Space
+      , Str "examples:"
+      ]
+  , Para
+      [ Code ( "" , [ "prompt" ] , [] ) ">>>"
+      , Space
+      , Code ( "" , [ "haskell" , "expr" ] , [] ) "fib 10"
+      , LineBreak
+      , Code ( "" , [ "result" ] , [] ) "55"
+      ]
+  , Para
+      [ Code ( "" , [ "prompt" ] , [] ) ">>>"
+      , Space
+      , Code
+          ( "" , [ "haskell" , "expr" ] , [] )
+          "putStrLn \"foo\\nbar\""
+      , LineBreak
+      , Code ( "" , [ "result" ] , [] ) "foo"
+      , LineBreak
+      , Code ( "" , [ "result" ] , [] ) "bar"
+      ]
+  , Para
+      [ Str "That"
+      , Space
+      , Str "was"
+      , Space
+      , Emph [ Str "really" , Space , Str "cool" ]
+      , Str "!"
+      , SoftBreak
+      , Str "I"
+      , Space
+      , Str "had"
+      , Space
+      , Str "no"
+      , Space
+      , Str "idea"
+      , Space
+      , Code ( "" , [] , [] ) "fib 10 = 55"
+      , Str "."
+      ]
+  , Para
+      [ Str "This"
+      , Space
+      , Str "module"
+      , Space
+      , Str "defines"
+      , Space
+      , Str "the"
+      , Space
+      , Str "type"
+      , Space
+      , Code ( "" , [ "haskell" , "identifier" ] , [] ) "T"
+      , Str "."
+      , SoftBreak
+      , Str "The"
+      , Space
+      , Str "identifier"
+      , Space
+      , Code ( "" , [ "haskell" , "identifier" ] , [] ) "M.T"
+      , Space
+      , Str "is"
+      , Space
+      , Str "not"
+      , Space
+      , Str "in"
+      , Space
+      , Str "scope"
+      , SoftBreak
+      , Str "I"
+      , Space
+      , Str "don't"
+      , Space
+      , Str "have"
+      , Space
+      , Str "to"
+      , Space
+      , Str "escape"
+      , Space
+      , Str "my"
+      , Space
+      , Str "apostrophes;"
+      , Space
+      , Str "great,"
+      , Space
+      , Str "isn't"
+      , Space
+      , Str "it?"
+      , SoftBreak
+      , Str "This"
+      , Space
+      , Str "is"
+      , Space
+      , Str "a"
+      , Space
+      , Str "reference"
+      , Space
+      , Str "to"
+      , Space
+      , Str "the"
+      , Space
+      , Code ( "" , [ "haskell" , "module" ] , [] ) "Foo"
+      , Space
+      , Str "module."
+      ]
+  , Para
+      [ Str "This"
+      , Space
+      , Str "is"
+      , Space
+      , Str "a"
+      , Space
+      , Str "bulleted"
+      , Space
+      , Str "list:"
+      ]
+  , BulletList
+      [ [ Para [ Str "first" , Space , Str "item" ] ]
+      , [ Para [ Str "second" , Space , Str "item" ] ]
+      ]
+  , Para
+      [ Str "This"
+      , Space
+      , Str "is"
+      , Space
+      , Str "an"
+      , Space
+      , Str "enumerated"
+      , Space
+      , Str "list:"
+      ]
+  , OrderedList
+      ( 1 , DefaultStyle , DefaultDelim )
+      [ [ Para [ Str "first" , Space , Str "item" ] ]
+      , [ Para [ Str "second" , Space , Str "item" ] ]
+      ]
+  , Para
+      [ Str "This"
+      , Space
+      , Str "is"
+      , Space
+      , Str "a"
+      , Space
+      , Str "definition"
+      , Space
+      , Str "list:"
+      ]
+  , DefinitionList
+      [ ( [ Code ( "" , [] , [] ) "foo" ]
+        , [ [ Para
+                [ Str "The"
+                , Space
+                , Str "description"
+                , Space
+                , Str "of"
+                , Space
+                , Code ( "" , [] , [] ) "foo"
+                , Str "."
+                ]
+            ]
+          ]
+        )
+      , ( [ Code ( "" , [] , [] ) "bar" ]
+        , [ [ Para
+                [ Str "The"
+                , Space
+                , Str "description"
+                , Space
+                , Str "of"
+                , Space
+                , Code ( "" , [] , [] ) "bar"
+                , Str "."
+                ]
+            ]
+          ]
+        )
+      ]
+  , Para
+      [ Str "Here"
+      , Space
+      , Str "is"
+      , Space
+      , Str "a"
+      , Space
+      , Str "link:"
+      , Space
+      , Link
+          ( "" , [] , [] )
+          [ Str "http://haskell.org" ]
+          ( "http://haskell.org" , "http://haskell.org" )
+      ]
+  , Para
+      [ Link
+          ( "" , [] , [] )
+          [ Str "Haskell" ]
+          ( "http://haskell.org" , "http://haskell.org" )
+      , Space
+      , Str "is"
+      , Space
+      , Str "a"
+      , Space
+      , Str "fun"
+      , Space
+      , Str "language!"
+      ]
+  , Para
+      [ Link
+          ( "" , [] , [] )
+          [ Str "Click" , Space , Str "Here!" ]
+          ( "http://example.com" , "http://example.com" )
+      ]
+  ]
diff --git a/test/html-reader.html b/test/html-reader.html
--- a/test/html-reader.html
+++ b/test/html-reader.html
@@ -81,6 +81,10 @@
 </blockquote>
 <p>And a following paragraph.</p>
 <hr />
+<h1>Inline quotes</h1>
+<p>Normal text but then a <q cite="https://www.imdb.com/title/tt0062622/quotes/qt0396921">inline quote</q>.</p>
+<p><q>Missing a cite attribute means its just normal text</q></p>
+<hr />
 <h1>Code Blocks</h1>
 <p>Code:</p>
 <pre><code>---- (should be four hyphens)
@@ -483,6 +487,7 @@
     </tbody>
 </table>
 <hr />
+<p>Row headers</p>
 <table>
     <thead>
     <tr>
@@ -519,6 +524,9 @@
         <td>2</td>
         <td>3</td>
     </tr>
+    <tr>
+        <td colspan="3">Details</td>
+    </tr>
     </tbody>
     <tfoot>
     <tr>
@@ -530,12 +538,37 @@
 </table>
 <hr />
 <table>
+    <tbody>
     <tr>
         <th>X</th>
         <th>Y</th>
         <th>Z</th>
     </tr>
     <tr>
+        <td>1</td>
+        <td>2</td>
+        <td>3</td>
+    </tr>
+    <tr>
+        <td colspan="3">Details</td>
+    </tr>
+    </tbody>
+    <tfoot>
+    <tr>
+        <th>4</th>
+        <td>5</td>
+        <td>6</td>
+    </tr>
+    </tfoot>
+</table>
+<hr />
+<table>
+    <tr>
+        <th>X</th>
+        <th>Y</th>
+        <th>Z</th>
+    </tr>
+    <tr>
         <th>1</th>
         <th>2</th>
         <th>3</th>
@@ -652,6 +685,7 @@
     </tbody>
 </table>
 <hr />
+<p>tbody tags omitted</p>
 <table>
     <tr>
         <td>1</td>
@@ -665,6 +699,7 @@
     </tr>
 </table>
 <hr />
+<p>empty head</p>
 <table>
     <thead>
     </thead>
@@ -682,6 +717,7 @@
     </tbody>
 </table>
 <hr />
+<p>explicit body and foot</p>
 <table>
     <tbody>
     <tr>
@@ -697,6 +733,78 @@
         <td>6</td>
     </tr>
     </tfoot>
+</table>
+<h2>Colspans and Rowspans</h2>
+<table>
+    <tr>
+        <td colspan="2">1 and 2</td>
+        <td>3</td>
+    </tr>
+    <tr>
+        <td colspan="3">4, 5, and 6</td>
+    </tr>
+</table>
+<hr/>
+<table>
+    <thead>
+    <tr>
+        <th colspan="3">Numbers</th>
+    </tr>
+    </thead>
+    <tbody>
+    <tr>
+        <td rowspan="2">1 and 4</td>
+        <td>2</td>
+        <td>3</td>
+    </tr>
+    <tr>
+        <td>5</td>
+        <td>6</td>
+    </tr>
+    </tbody>
+</table>
+<h2>Attributes</h2>
+<table id="attrib-test-table">
+  <thead class="table-head">
+    <tr class="table-head-row">
+      <th abbr="x" colspan="3">Cat X</th>
+    </tr>
+    <tbody data-part="body" class="main">
+    <tr data-part="row">
+        <td data-part="cell">1</td>
+        <td valign="bottom">2</td>
+        <td style="color: #151950">3</td>
+    </tr>
+    </tbody>
+    <tfoot class="summary">
+    <tr bgcolor="#ccc">
+        <td data-square="true">4</td>
+        <td>5</td>
+        <td>6</td>
+    </tr>
+    </tfoot>
+</table>
+<h2>Tag omission</h2>
+<p>thead, tbody, and tfoot</p>
+<table>
+    <thead>
+        <tr>
+            <td>X</td>
+            <td>Y</td>
+            <td>Z</td>
+        </tr>
+    <tbody>
+        <tr>
+            <td>1</td>
+            <td>2</td>
+            <td>3</td>
+        </tr>
+    <tfoot>
+        <tr>
+            <td>4</td>
+            <td>5</td>
+            <td>6</td>
+        </tr>
 </table>
 <h2>Empty Tables</h2>
 <p>This section should be empty.</p>
diff --git a/test/html-reader.native b/test/html-reader.native
--- a/test/html-reader.native
+++ b/test/html-reader.native
@@ -1,473 +1,3383 @@
-Pandoc (Meta {unMeta = fromList [("generator",MetaInlines [Str "pandoc"]),("title",MetaInlines [Str "Pandoc",Space,Str "Test",Space,Str "Suite"])]})
-[Para [Str "This",Space,Str "is",Space,Str "a",Space,Str "set",Space,Str "of",Space,Str "tests",Space,Str "for",Space,Str "pandoc.",Space,Str "Most",Space,Str "of",Space,Str "them",Space,Str "are",Space,Str "adapted",Space,Str "from",Space,Str "John",Space,Str "Gruber's",Space,Str "markdown",Space,Str "test",Space,Str "suite."]
-,HorizontalRule
-,Header 1 ("headers",[],[]) [Str "Headers"]
-,Header 2 ("level-2-with-an-embedded-link",[],[]) [Str "Level",Space,Str "2",Space,Str "with",Space,Str "an",Space,Link ("",[],[]) [Str "embedded",Space,Str "link"] ("/url","")]
-,Header 3 ("level-3-with-emphasis",[],[]) [Str "Level",Space,Str "3",Space,Str "with",Space,Emph [Str "emphasis"]]
-,Header 4 ("level-4",[],[]) [Str "Level",Space,Str "4"]
-,Header 5 ("level-5",[],[]) [Str "Level",Space,Str "5"]
-,Header 1 ("level-1",[],[]) [Str "Level",Space,Str "1"]
-,Header 2 ("level-2-with-emphasis",[],[]) [Str "Level",Space,Str "2",Space,Str "with",Space,Emph [Str "emphasis"]]
-,Header 3 ("level-3",[],[]) [Str "Level",Space,Str "3"]
-,Para [Str "with",Space,Str "no",Space,Str "blank",Space,Str "line"]
-,Header 2 ("level-2",[],[]) [Str "Level",Space,Str "2"]
-,Para [Str "with",Space,Str "no",Space,Str "blank",Space,Str "line"]
-,HorizontalRule
-,Header 1 ("paragraphs",[],[]) [Str "Paragraphs"]
-,Para [Str "Here's",Space,Str "a",Space,Str "regular",Space,Str "paragraph."]
-,Para [Str "In",Space,Str "Markdown",Space,Str "1.0.0",Space,Str "and",Space,Str "earlier.",Space,Str "Version",Space,Str "8.",Space,Str "This",Space,Str "line",Space,Str "turns",Space,Str "into",Space,Str "a",Space,Str "list",Space,Str "item.",Space,Str "Because",Space,Str "a",Space,Str "hard-wrapped",Space,Str "line",Space,Str "in",Space,Str "the",Space,Str "middle",Space,Str "of",Space,Str "a",Space,Str "paragraph",Space,Str "looked",Space,Str "like",Space,Str "a",Space,Str "list",Space,Str "item."]
-,Para [Str "Here's",Space,Str "one",Space,Str "with",Space,Str "a",Space,Str "bullet.",Space,Str "*",Space,Str "criminey."]
-,Para [Str "There",Space,Str "should",Space,Str "be",Space,Str "a",Space,Str "hard",Space,Str "line",Space,Str "break",LineBreak,Str "here."]
-,HorizontalRule
-,Header 1 ("block-quotes",[],[]) [Str "Block",Space,Str "Quotes"]
-,Para [Str "E-mail",Space,Str "style:"]
-,BlockQuote
- [Para [Str "This",Space,Str "is",Space,Str "a",Space,Str "block",Space,Str "quote.",Space,Str "It",Space,Str "is",Space,Str "pretty",Space,Str "short."]]
-,BlockQuote
- [Para [Str "Code",Space,Str "in",Space,Str "a",Space,Str "block",Space,Str "quote:"]
- ,CodeBlock ("",[],[]) "sub status {\n    print \"working\";\n}"
- ,Para [Str "A",Space,Str "list:"]
- ,OrderedList (1,DefaultStyle,DefaultDelim)
-  [[Plain [Str "item",Space,Str "one"]]
-  ,[Plain [Str "item",Space,Str "two"]]]
- ,Para [Str "Nested",Space,Str "block",Space,Str "quotes:"]
- ,BlockQuote
-  [Para [Str "nested"]]
- ,BlockQuote
-  [Para [Str "nested"]]]
-,Para [Str "This",Space,Str "should",Space,Str "not",Space,Str "be",Space,Str "a",Space,Str "block",Space,Str "quote:",Space,Str "2",Space,Str ">",Space,Str "1."]
-,Para [Str "Box-style:"]
-,BlockQuote
- [Para [Str "Example:"]
- ,CodeBlock ("",[],[]) "sub status {\n    print \"working\";\n}"]
-,BlockQuote
- [OrderedList (1,DefaultStyle,DefaultDelim)
-  [[Plain [Str "do",Space,Str "laundry"]]
-  ,[Plain [Str "take",Space,Str "out",Space,Str "the",Space,Str "trash"]]]]
-,Para [Str "Here's",Space,Str "a",Space,Str "nested",Space,Str "one:"]
-,BlockQuote
- [Para [Str "Joe",Space,Str "said:"]
- ,BlockQuote
-  [Para [Str "Don't",Space,Str "quote",Space,Str "me."]]]
-,Para [Str "And",Space,Str "a",Space,Str "following",Space,Str "paragraph."]
-,HorizontalRule
-,Header 1 ("code-blocks",[],[]) [Str "Code",Space,Str "Blocks"]
-,Para [Str "Code:"]
-,CodeBlock ("",[],[]) "---- (should be four hyphens)\n\nsub status {\n    print \"working\";\n}\n\nthis code block is indented by one tab"
-,Para [Str "And:"]
-,CodeBlock ("",[],[]) "    this code block is indented by two tabs\n\nThese should not be escaped:  \\$ \\\\ \\> \\[ \\{"
-,HorizontalRule
-,Header 1 ("lists",[],[]) [Str "Lists"]
-,Header 2 ("unordered",[],[]) [Str "Unordered"]
-,Para [Str "Asterisks",Space,Str "tight:"]
-,BulletList
- [[Plain [Str "asterisk",Space,Str "1"]]
- ,[Plain [Str "asterisk",Space,Str "2"]]
- ,[Plain [Str "asterisk",Space,Str "3"]]]
-,Para [Str "Asterisks",Space,Str "loose:"]
-,BulletList
- [[Para [Str "asterisk",Space,Str "1"]]
- ,[Para [Str "asterisk",Space,Str "2"]]
- ,[Para [Str "asterisk",Space,Str "3"]]]
-,Para [Str "Pluses",Space,Str "tight:"]
-,BulletList
- [[Plain [Str "Plus",Space,Str "1"]]
- ,[Plain [Str "Plus",Space,Str "2"]]
- ,[Plain [Str "Plus",Space,Str "3"]]]
-,Para [Str "Pluses",Space,Str "loose:"]
-,BulletList
- [[Para [Str "Plus",Space,Str "1"]]
- ,[Para [Str "Plus",Space,Str "2"]]
- ,[Para [Str "Plus",Space,Str "3"]]]
-,Para [Str "Minuses",Space,Str "tight:"]
-,BulletList
- [[Plain [Str "Minus",Space,Str "1"]]
- ,[Plain [Str "Minus",Space,Str "2"]]
- ,[Plain [Str "Minus",Space,Str "3"]]]
-,Para [Str "Minuses",Space,Str "loose:"]
-,BulletList
- [[Para [Str "Minus",Space,Str "1"]]
- ,[Para [Str "Minus",Space,Str "2"]]
- ,[Para [Str "Minus",Space,Str "3"]]]
-,Header 2 ("ordered",[],[]) [Str "Ordered"]
-,Para [Str "Tight:"]
-,OrderedList (1,DefaultStyle,DefaultDelim)
- [[Plain [Str "First"]]
- ,[Plain [Str "Second"]]
- ,[Plain [Str "Third"]]]
-,Para [Str "and:"]
-,OrderedList (1,DefaultStyle,DefaultDelim)
- [[Plain [Str "One"]]
- ,[Plain [Str "Two"]]
- ,[Plain [Str "Three"]]]
-,Para [Str "Loose",Space,Str "using",Space,Str "tabs:"]
-,OrderedList (1,DefaultStyle,DefaultDelim)
- [[Para [Str "First"]]
- ,[Para [Str "Second"]]
- ,[Para [Str "Third"]]]
-,Para [Str "and",Space,Str "using",Space,Str "spaces:"]
-,OrderedList (1,DefaultStyle,DefaultDelim)
- [[Para [Str "One"]]
- ,[Para [Str "Two"]]
- ,[Para [Str "Three"]]]
-,Para [Str "Multiple",Space,Str "paragraphs:"]
-,OrderedList (1,DefaultStyle,DefaultDelim)
- [[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's",Space,Str "back."]]
- ,[Para [Str "Item",Space,Str "2."]]
- ,[Para [Str "Item",Space,Str "3."]]]
-,Para [Str "List",Space,Str "styles:"]
-,OrderedList (1,DefaultStyle,DefaultDelim)
- []
-,OrderedList (1,LowerRoman,DefaultDelim)
- []
-,OrderedList (1,LowerRoman,DefaultDelim)
- []
-,OrderedList (1,DefaultStyle,DefaultDelim)
- []
-,OrderedList (1,LowerRoman,DefaultDelim)
- []
-,OrderedList (1,LowerRoman,DefaultDelim)
- []
-,Header 2 ("nested",[],[]) [Str "Nested"]
-,BulletList
- [[Plain [Str "Tab"]
-  ,BulletList
-   [[Plain [Str "Tab"]
-    ,BulletList
-     [[Plain [Str "Tab"]]]]]]]
-,Para [Str "Here's",Space,Str "another:"]
-,OrderedList (1,DefaultStyle,DefaultDelim)
- [[Plain [Str "First"]]
- ,[Plain [Str "Second:"]
-  ,BulletList
-   [[Plain [Str "Fee"]]
-   ,[Plain [Str "Fie"]]
-   ,[Plain [Str "Foe"]]]]
- ,[Plain [Str "Third"]]]
-,Para [Str "Same",Space,Str "thing",Space,Str "but",Space,Str "with",Space,Str "paragraphs:"]
-,OrderedList (1,DefaultStyle,DefaultDelim)
- [[Para [Str "First"]]
- ,[Para [Str "Second:"]
-  ,BulletList
-   [[Plain [Str "Fee"]]
-   ,[Plain [Str "Fie"]]
-   ,[Plain [Str "Foe"]]]]
- ,[Para [Str "Third"]]]
-,Header 2 ("tabs-and-spaces",[],[]) [Str "Tabs",Space,Str "and",Space,Str "spaces"]
-,BulletList
- [[Para [Str "this",Space,Str "is",Space,Str "a",Space,Str "list",Space,Str "item",Space,Str "indented",Space,Str "with",Space,Str "tabs"]]
- ,[Para [Str "this",Space,Str "is",Space,Str "a",Space,Str "list",Space,Str "item",Space,Str "indented",Space,Str "with",Space,Str "spaces"]
-  ,BulletList
-   [[Para [Str "this",Space,Str "is",Space,Str "an",Space,Str "example",Space,Str "list",Space,Str "item",Space,Str "indented",Space,Str "with",Space,Str "tabs"]]
-   ,[Para [Str "this",Space,Str "is",Space,Str "an",Space,Str "example",Space,Str "list",Space,Str "item",Space,Str "indented",Space,Str "with",Space,Str "spaces"]]]]]
-,Header 2 ("fancy-list-markers",[],[]) [Str "Fancy",Space,Str "list",Space,Str "markers"]
-,OrderedList (2,Decimal,DefaultDelim)
- [[Plain [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,DefaultDelim)
-   [[Plain [Str "sublist",Space,Str "with",Space,Str "roman",Space,Str "numerals,",Space,Str "starting",Space,Str "with",Space,Str "4"]]
-   ,[Plain [Str "more",Space,Str "items"]
-    ,OrderedList (1,UpperAlpha,DefaultDelim)
-     [[Plain [Str "a",Space,Str "subsublist"]]
-     ,[Plain [Str "a",Space,Str "subsublist"]]]]]]]
-,Para [Str "Nesting:"]
-,OrderedList (1,UpperAlpha,DefaultDelim)
- [[Plain [Str "Upper",Space,Str "Alpha"]
-  ,OrderedList (1,UpperRoman,DefaultDelim)
-   [[Plain [Str "Upper",Space,Str "Roman."]
-    ,OrderedList (6,Decimal,DefaultDelim)
-     [[Plain [Str "Decimal",Space,Str "start",Space,Str "with",Space,Str "6"]
-      ,OrderedList (3,LowerAlpha,DefaultDelim)
-       [[Plain [Str "Lower",Space,Str "alpha",Space,Str "with",Space,Str "paren"]]]]]]]]]
-,Para [Str "Autonumbering:"]
-,OrderedList (1,DefaultStyle,DefaultDelim)
- [[Plain [Str "Autonumber."]]
- ,[Plain [Str "More."]
-  ,OrderedList (1,DefaultStyle,DefaultDelim)
-   [[Plain [Str "Nested."]]]]]
-,HorizontalRule
-,Header 2 ("definition",[],[]) [Str "Definition"]
-,DefinitionList
- [([Str "Violin"],
-   [[Plain [Str "Stringed",Space,Str "musical",Space,Str "instrument."]]
-   ,[Plain [Str "Torture",Space,Str "device."]]])
- ,([Str "Cello",LineBreak,Str "Violoncello"],
-   [[Plain [Str "Low-voiced",Space,Str "stringed",Space,Str "instrument."]]])]
-,HorizontalRule
-,Header 1 ("inline-markup",[],[]) [Str "Inline",Space,Str "Markup"]
-,Para [Str "This",Space,Str "is",Space,Emph [Str "emphasized"],Str ",",Space,Str "and",Space,Str "so",Space,Emph [Str "is",Space,Str "this"],Str "."]
-,Para [Str "This",Space,Str "is",Space,Strong [Str "strong"],Str ",",Space,Str "and",Space,Str "so",Space,Strong [Str "is",Space,Str "this"],Str "."]
-,Para [Str "Empty",Space,Strong [],Space,Str "and",Space,Emph [],Str "."]
-,Para [Str "An",Space,Emph [Link ("",[],[]) [Str "emphasized",Space,Str "link"] ("/url","")],Str "."]
-,Para [Strong [Emph [Str "This",Space,Str "is",Space,Str "strong",Space,Str "and",Space,Str "em."]]]
-,Para [Str "So",Space,Str "is",Space,Strong [Emph [Str "this"]],Space,Str "word."]
-,Para [Strong [Emph [Str "This",Space,Str "is",Space,Str "strong",Space,Str "and",Space,Str "em."]]]
-,Para [Str "So",Space,Str "is",Space,Strong [Emph [Str "this"]],Space,Str "word."]
-,Para [Str "This",Space,Str "is",Space,Str "code:",Space,Code ("",[],[]) ">",Str ",",Space,Code ("",[],[]) "$",Str ",",Space,Code ("",[],[]) "\\",Str ",",Space,Code ("",[],[]) "\\$",Str ",",Space,Code ("",[],[]) "<html>",Str "."]
-,Para [Str "This",Space,Str "is",Space,SmallCaps [Str "small",Space,Str "caps"],Str "."]
-,Para [Str "These",Space,Str "are",Space,Str "all",Space,Str "underlined:",Space,Span ("",["underline"],[]) [Str "foo"],Space,Str "and",Space,Span ("",["underline"],[]) [Str "bar"],Str "."]
-,Para [Str "These",Space,Str "are",Space,Str "all",Space,Str "strikethrough:",Space,Strikeout [Str "foo"],Str ",",Space,Strikeout [Str "bar"],Str ",",Space,Str "and",Space,Strikeout [Str "baz"],Str "."]
-,HorizontalRule
-,Header 1 ("smart-quotes-ellipses-dashes",[],[]) [Str "Smart",Space,Str "quotes,",Space,Str "ellipses,",Space,Str "dashes"]
-,Para [Str "\"Hello,\"",Space,Str "said",Space,Str "the",Space,Str "spider.",Space,Str "\"'Shelob'",Space,Str "is",Space,Str "my",Space,Str "name.\""]
-,Para [Str "'A',",Space,Str "'B',",Space,Str "and",Space,Str "'C'",Space,Str "are",Space,Str "letters."]
-,Para [Str "'Oak,'",Space,Str "'elm,'",Space,Str "and",Space,Str "'beech'",Space,Str "are",Space,Str "names",Space,Str "of",Space,Str "trees.",Space,Str "So",Space,Str "is",Space,Str "'pine.'"]
-,Para [Str "'He",Space,Str "said,",Space,Str "\"I",Space,Str "want",Space,Str "to",Space,Str "go.\"'",Space,Str "Were",Space,Str "you",Space,Str "alive",Space,Str "in",Space,Str "the",Space,Str "70's?"]
-,Para [Str "Here",Space,Str "is",Space,Str "some",Space,Str "quoted",Space,Str "'",Code ("",[],[]) "code",Str "'",Space,Str "and",Space,Str "a",Space,Str "\"",Link ("",[],[]) [Str "quoted",Space,Str "link"] ("http://example.com/?foo=1&bar=2",""),Str "\"."]
-,Para [Str "Some",Space,Str "dashes:",Space,Str "one---two",Space,Str "---",Space,Str "three--four",Space,Str "--",Space,Str "five."]
-,Para [Str "Dashes",Space,Str "between",Space,Str "numbers:",Space,Str "5-7,",Space,Str "255-66,",Space,Str "1987-1999."]
-,Para [Str "Ellipses...and.",Space,Str ".",Space,Str ".and",Space,Str ".",Space,Str ".",Space,Str ".",Space,Str "."]
-,HorizontalRule
-,Header 1 ("latex",[],[]) [Str "LaTeX"]
-,BulletList
- [[Plain [Str "\\cite[22-23]{smith.1899}"]]
- ,[Plain [Str "\\doublespacing"]]
- ,[Plain [Str "$2+2=4$"]]
- ,[Plain [Str "$x",Space,Str "\\in",Space,Str "y$"]]
- ,[Plain [Str "$\\alpha",Space,Str "\\wedge",Space,Str "\\omega$"]]
- ,[Plain [Str "$223$"]]
- ,[Plain [Str "$p$-Tree"]]
- ,[Plain [Str "$\\frac{d}{dx}f(x)=\\lim_{h\\to",Space,Str "0}\\frac{f(x+h)-f(x)}{h}$"]]
- ,[Plain [Str "Here's",Space,Str "one",Space,Str "that",Space,Str "has",Space,Str "a",Space,Str "line",Space,Str "break",Space,Str "in",Space,Str "it:",Space,Str "$\\alpha",Space,Str "+",Space,Str "\\omega",Space,Str "\\times",Space,Str "x^2$."]]]
-,Para [Str "These",Space,Str "shouldn't",Space,Str "be",Space,Str "math:"]
-,BulletList
- [[Plain [Str "To",Space,Str "get",Space,Str "the",Space,Str "famous",Space,Str "equation,",Space,Str "write",Space,Code ("",[],[]) "$e = mc^2$",Str "."]]
- ,[Plain [Str "$22,000",Space,Str "is",Space,Str "a",Space,Emph [Str "lot"],Space,Str "of",Space,Str "money.",Space,Str "So",Space,Str "is",Space,Str "$34,000.",Space,Str "(It",Space,Str "worked",Space,Str "if",Space,Str "\"lot\"",Space,Str "is",Space,Str "emphasized.)"]]
- ,[Plain [Str "Escaped",Space,Code ("",[],[]) "$",Str ":",Space,Str "$73",Space,Emph [Str "this",Space,Str "should",Space,Str "be",Space,Str "emphasized"],Space,Str "23$."]]]
-,Para [Str "Here's",Space,Str "a",Space,Str "LaTeX",Space,Str "table:"]
-,Para [Str "\\begin{tabular}{|l|l|}\\hline",Space,Str "Animal",Space,Str "&",Space,Str "Number",Space,Str "\\\\",Space,Str "\\hline",Space,Str "Dog",Space,Str "&",Space,Str "2",Space,Str "\\\\",Space,Str "Cat",Space,Str "&",Space,Str "1",Space,Str "\\\\",Space,Str "\\hline",Space,Str "\\end{tabular}"]
-,HorizontalRule
-,Header 1 ("special-characters",[],[]) [Str "Special",Space,Str "Characters"]
-,Para [Str "Here",Space,Str "is",Space,Str "some",Space,Str "unicode:"]
-,BulletList
- [[Plain [Str "I",Space,Str "hat:",Space,Str "\206"]]
- ,[Plain [Str "o",Space,Str "umlaut:",Space,Str "\246"]]
- ,[Plain [Str "section:",Space,Str "\167"]]
- ,[Plain [Str "set",Space,Str "membership:",Space,Str "\8712"]]
- ,[Plain [Str "copyright:",Space,Str "\169"]]]
-,Para [Str "AT&T",Space,Str "has",Space,Str "an",Space,Str "ampersand",Space,Str "in",Space,Str "their",Space,Str "name."]
-,Para [Str "AT&T",Space,Str "is",Space,Str "another",Space,Str "way",Space,Str "to",Space,Str "write",Space,Str "it."]
-,Para [Str "This",Space,Str "&",Space,Str "that."]
-,Para [Str "4",Space,Str "<",Space,Str "5."]
-,Para [Str "6",Space,Str ">",Space,Str "5."]
-,Para [Str "Backslash:",Space,Str "\\"]
-,Para [Str "Backtick:",Space,Str "`"]
-,Para [Str "Asterisk:",Space,Str "*"]
-,Para [Str "Underscore:",Space,Str "_"]
-,Para [Str "Left",Space,Str "brace:",Space,Str "{"]
-,Para [Str "Right",Space,Str "brace:",Space,Str "}"]
-,Para [Str "Left",Space,Str "bracket:",Space,Str "["]
-,Para [Str "Right",Space,Str "bracket:",Space,Str "]"]
-,Para [Str "Left",Space,Str "paren:",Space,Str "("]
-,Para [Str "Right",Space,Str "paren:",Space,Str ")"]
-,Para [Str "Greater-than:",Space,Str ">"]
-,Para [Str "Hash:",Space,Str "#"]
-,Para [Str "Period:",Space,Str "."]
-,Para [Str "Bang:",Space,Str "!"]
-,Para [Str "Plus:",Space,Str "+"]
-,Para [Str "Minus:",Space,Str "-"]
-,HorizontalRule
-,Header 1 ("links",[],[]) [Str "Links"]
-,Header 2 ("explicit",[],[]) [Str "Explicit"]
-,Para [Str "Just",Space,Str "a",Space,Link ("",[],[]) [Str "URL"] ("/url/",""),Str "."]
-,Para [Link ("",[],[]) [Str "URL",Space,Str "and",Space,Str "title"] ("/url/","title"),Str "."]
-,Para [Link ("",[],[]) [Str "URL",Space,Str "and",Space,Str "title"] ("/url/","title preceded by two spaces"),Str "."]
-,Para [Link ("",[],[]) [Str "URL",Space,Str "and",Space,Str "title"] ("/url/","title preceded by a tab"),Str "."]
-,Para [Link ("",[],[]) [Str "URL",Space,Str "and",Space,Str "title"] ("/url/","title with \"quotes\" in it")]
-,Para [Link ("",[],[]) [Str "URL",Space,Str "and",Space,Str "title"] ("/url/","title with single quotes")]
-,Para [Str "Email",Space,Str "link",Space,Str "(nobody",Space,Str "[at]",Space,Str "nowhere.net)"]
-,Para [Link ("",[],[]) [Str "Empty"] ("",""),Str "."]
-,Header 2 ("reference",[],[]) [Str "Reference"]
-,Para [Str "Foo",Space,Link ("",[],[]) [Str "bar"] ("/url/",""),Str "."]
-,Para [Str "Foo",Space,Link ("",[],[]) [Str "bar"] ("/url/",""),Str "."]
-,Para [Str "Foo",Space,Link ("",[],[]) [Str "bar"] ("/url/",""),Str "."]
-,Para [Str "With",Space,Link ("",[],[]) [Str "embedded",Space,Str "[brackets]"] ("/url/",""),Str "."]
-,Para [Link ("",[],[]) [Str "b"] ("/url/",""),Space,Str "by",Space,Str "itself",Space,Str "should",Space,Str "be",Space,Str "a",Space,Str "link."]
-,Para [Str "Indented",Space,Link ("",[],[]) [Str "once"] ("/url",""),Str "."]
-,Para [Str "Indented",Space,Link ("",[],[]) [Str "twice"] ("/url",""),Str "."]
-,Para [Str "Indented",Space,Link ("",[],[]) [Str "thrice"] ("/url",""),Str "."]
-,Para [Str "This",Space,Str "should",Space,Str "[not]",Space,Str "be",Space,Str "a",Space,Str "link."]
-,CodeBlock ("",[],[]) "[not]: /url"
-,Para [Str "Foo",Space,Link ("",[],[]) [Str "bar"] ("/url/","Title with \"quotes\" inside"),Str "."]
-,Para [Str "Foo",Space,Link ("",[],[]) [Str "biz"] ("/url/","Title with \"quote\" inside"),Str "."]
-,Header 2 ("with-ampersands",[],[]) [Str "With",Space,Str "ampersands"]
-,Para [Str "Here's",Space,Str "a",Space,Link ("",[],[]) [Str "link",Space,Str "with",Space,Str "an",Space,Str "ampersand",Space,Str "in",Space,Str "the",Space,Str "URL"] ("http://example.com/?foo=1&bar=2",""),Str "."]
-,Para [Str "Here's",Space,Str "a",Space,Str "link",Space,Str "with",Space,Str "an",Space,Str "amersand",Space,Str "in",Space,Str "the",Space,Str "link",Space,Str "text:",Space,Link ("",[],[]) [Str "AT&T"] ("http://att.com/","AT&T"),Str "."]
-,Para [Str "Here's",Space,Str "an",Space,Link ("",[],[]) [Str "inline",Space,Str "link"] ("/script?foo=1&bar=2",""),Str "."]
-,Para [Str "Here's",Space,Str "an",Space,Link ("",[],[]) [Str "inline",Space,Str "link",Space,Str "in",Space,Str "pointy",Space,Str "braces"] ("/script?foo=1&bar=2",""),Str "."]
-,Header 2 ("autolinks",[],[]) [Str "Autolinks"]
-,Para [Str "With",Space,Str "an",Space,Str "ampersand:",Space,Link ("",[],[]) [Str "http://example.com/?foo=1&bar=2"] ("http://example.com/?foo=1&bar=2","")]
-,BulletList
- [[Plain [Str "In",Space,Str "a",Space,Str "list?"]]
- ,[Plain [Link ("",[],[]) [Str "http://example.com/"] ("http://example.com/","")]]
- ,[Plain [Str "It",Space,Str "should."]]]
-,Para [Str "An",Space,Str "e-mail",Space,Str "address:",Space,Str "nobody",Space,Str "[at]",Space,Str "nowhere.net"]
-,BlockQuote
- [Para [Str "Blockquoted:",Space,Link ("",[],[]) [Str "http://example.com/"] ("http://example.com/","")]]
-,Para [Str "Auto-links",Space,Str "should",Space,Str "not",Space,Str "occur",Space,Str "here:",Space,Code ("",[],[]) "<http://example.com/>"]
-,CodeBlock ("",[],[]) "or here: <http://example.com/>"
-,HorizontalRule
-,Header 1 ("images",[],[]) [Str "Images"]
-,Para [Str "From",Space,Str "\"Voyage",Space,Str "dans",Space,Str "la",Space,Str "Lune\"",Space,Str "by",Space,Str "Georges",Space,Str "Melies",Space,Str "(1902):"]
-,Para [Image ("",[],[]) [Str "lalune"] ("lalune.jpg","Voyage dans la Lune")]
-,Para [Str "Here",Space,Str "is",Space,Str "a",Space,Str "movie",Space,Image ("",[],[]) [Str "movie"] ("movie.jpg",""),Space,Str "icon."]
-,HorizontalRule
-,Header 1 ("footnotes",[],[]) [Str "Footnotes"]
-,Para [Str "Here",Space,Str "is",Space,Str "a",Space,Str "footnote",Space,Str "reference",Link ("",[],[]) [Str "(1)"] ("#note_1",""),Str ",",Space,Str "and",Space,Str "another",Link ("",[],[]) [Str "(longnote)"] ("#note_longnote",""),Str ".",Space,Str "This",Space,Str "should",Space,Emph [Str "not"],Space,Str "be",Space,Str "a",Space,Str "footnote",Space,Str "reference,",Space,Str "because",Space,Str "it",Space,Str "contains",Space,Str "a",Space,Str "space^(my",Space,Str "note)."]
-,Para [Link ("",[],[]) [Str "(1)"] ("#ref_1",""),Space,Str "Here",Space,Str "is",Space,Str "the",Space,Str "footnote.",Space,Str "It",Space,Str "can",Space,Str "go",Space,Str "anywhere",Space,Str "in",Space,Str "the",Space,Str "document,",Space,Str "not",Space,Str "just",Space,Str "at",Space,Str "the",Space,Str "end."]
-,Para [Link ("",[],[]) [Str "(longnote)"] ("#ref_longnote",""),Space,Str "Here's",Space,Str "the",Space,Str "other",Space,Str "note.",Space,Str "This",Space,Str "one",Space,Str "contains",Space,Str "multiple",Space,Str "blocks."]
-,Para [Str "Caret",Space,Str "characters",Space,Str "are",Space,Str "used",Space,Str "to",Space,Str "indicate",Space,Str "that",Space,Str "the",Space,Str "blocks",Space,Str "all",Space,Str "belong",Space,Str "to",Space,Str "a",Space,Str "single",Space,Str "footnote",Space,Str "(as",Space,Str "with",Space,Str "block",Space,Str "quotes)."]
-,CodeBlock ("",[],[]) "  { <code> }"
-,Para [Str "If",Space,Str "you",Space,Str "want,",Space,Str "you",Space,Str "can",Space,Str "use",Space,Str "a",Space,Str "caret",Space,Str "at",Space,Str "the",Space,Str "beginning",Space,Str "of",Space,Str "every",Space,Str "line,",Space,Str "as",Space,Str "with",Space,Str "blockquotes,",Space,Str "but",Space,Str "all",Space,Str "that",Space,Str "you",Space,Str "need",Space,Str "is",Space,Str "a",Space,Str "caret",Space,Str "at",Space,Str "the",Space,Str "beginning",Space,Str "of",Space,Str "the",Space,Str "first",Space,Str "line",Space,Str "of",Space,Str "the",Space,Str "block",Space,Str "and",Space,Str "any",Space,Str "preceding",Space,Str "blank",Space,Str "lines."]
-,Para [Str "text",Space,Emph [Str "Leading",Space,Str "space"]]
-,Para [Emph [Str "Trailing",Space,Str "space"],Space,Str "text"]
-,Para [Str "text",Space,Emph [Str "Leading",Space,Str "spaces"]]
-,Para [Emph [Str "Trailing",Space,Str "spaces"],Space,Str "text"]
-,Header 1 ("tables",[],[]) [Str "Tables"]
-,Header 2 ("tables-with-headers",[],[]) [Str "Tables",Space,Str "with",Space,Str "Headers"]
-,Table [] [AlignDefault,AlignDefault,AlignDefault] [0.0,0.0,0.0]
- [[Plain [Str "X"]]
- ,[Plain [Str "Y"]]
- ,[Plain [Str "Z"]]]
- [[[Plain [Str "1"]]
-  ,[Plain [Str "2"]]
-  ,[Plain [Str "3"]]]
- ,[[Plain [Str "4"]]
-  ,[Plain [Str "5"]]
-  ,[Plain [Str "6"]]]]
-,HorizontalRule
-,Table [] [AlignDefault,AlignDefault,AlignDefault] [0.0,0.0,0.0]
- [[Plain [Str "X"]]
- ,[Plain [Str "Y"]]
- ,[Plain [Str "Z"]]]
- [[[Plain [Str "1"]]
-  ,[Plain [Str "2"]]
-  ,[Plain [Str "3"]]]
- ,[[Plain [Str "4"]]
-  ,[Plain [Str "5"]]
-  ,[Plain [Str "6"]]]]
-,HorizontalRule
-,Table [] [AlignDefault,AlignDefault,AlignDefault] [0.0,0.0,0.0]
- [[Plain [Str "X"]]
- ,[Plain [Str "Y"]]
- ,[Plain [Str "Z"]]]
- [[[Plain [Str "1"]]
-  ,[Plain [Str "2"]]
-  ,[Plain [Str "3"]]]
- ,[[Plain [Str "4"]]
-  ,[Plain [Str "5"]]
-  ,[Plain [Str "6"]]]]
-,HorizontalRule
-,Table [] [AlignDefault,AlignDefault,AlignDefault] [0.0,0.0,0.0]
- [[Plain [Str "X"]]
- ,[Plain [Str "Y"]]
- ,[Plain [Str "Z"]]]
- [[[Plain [Str "1"]]
-  ,[Plain [Str "2"]]
-  ,[Plain [Str "3"]]]
- ,[[Plain [Str "4"]]
-  ,[Plain [Str "5"]]
-  ,[Plain [Str "6"]]]]
-,HorizontalRule
-,Table [] [AlignDefault,AlignDefault,AlignDefault] [0.0,0.0,0.0]
- [[Plain [Str "X"]]
- ,[Plain [Str "Y"]]
- ,[Plain [Str "Z"]]]
- [[[Plain [Str "1"]]
-  ,[Plain [Str "2"]]
-  ,[Plain [Str "3"]]]
- ,[[Plain [Str "4"]]
-  ,[Plain [Str "5"]]
-  ,[Plain [Str "6"]]]]
-,HorizontalRule
-,Table [] [AlignDefault,AlignDefault,AlignDefault] [0.0,0.0,0.0]
- [[Plain [Str "X"]]
- ,[Plain [Str "Y"]]
- ,[Plain [Str "Z"]]]
- [[[Plain [Str "1"]]
-  ,[Plain [Str "2"]]
-  ,[Plain [Str "3"]]]
- ,[[Plain [Str "4"]]
-  ,[Plain [Str "5"]]
-  ,[Plain [Str "6"]]]]
-,HorizontalRule
-,Table [] [AlignDefault,AlignDefault,AlignDefault] [0.0,0.0,0.0]
- [[Plain [Str "X"]]
- ,[Plain [Str "Y"]]
- ,[Plain [Str "Z"]]]
- [[[Plain [Str "1"]]
-  ,[Plain [Str "2"]]
-  ,[Plain [Str "3"]]]
- ,[[Plain [Str "4"]]
-  ,[Plain [Str "5"]]
-  ,[Plain [Str "6"]]]]
-,HorizontalRule
-,Table [] [AlignDefault,AlignDefault,AlignDefault] [0.0,0.0,0.0]
- [[Plain [Str "X"]]
- ,[Plain [Str "Y"]]
- ,[Plain [Str "Z"]]]
- [[[Plain [Str "1"]]
-  ,[Plain [Str "2"]]
-  ,[Plain [Str "3"]]]
- ,[[Plain [Str "4"]]
-  ,[Plain [Str "5"]]
-  ,[Plain [Str "6"]]]]
-,HorizontalRule
-,Table [] [AlignDefault,AlignDefault,AlignDefault] [0.3333333333333333,0.3333333333333333,0.3333333333333333]
- [[Plain [Str "X"]]
- ,[Plain [Str "Y"]]
- ,[Plain [Str "Z"]]]
- [[[Plain [Str "1"]]
-  ,[Para [Str "2"]]
-  ,[Plain [Str "3"]]]
- ,[[Plain [Str "4"]]
-  ,[Plain [Str "5"]]
-  ,[Plain [Str "6"]]]]
-,Header 2 ("tables-without-headers",[],[]) [Str "Tables",Space,Str "without",Space,Str "Headers"]
-,Table [] [AlignDefault,AlignDefault,AlignDefault] [0.0,0.0,0.0]
- [[]
- ,[]
- ,[]]
- [[[Plain [Str "1"]]
-  ,[Plain [Str "2"]]
-  ,[Plain [Str "3"]]]
- ,[[Plain [Str "4"]]
-  ,[Plain [Str "5"]]
-  ,[Plain [Str "6"]]]]
-,HorizontalRule
-,Table [] [AlignDefault,AlignDefault,AlignDefault] [0.0,0.0,0.0]
- [[]
- ,[]
- ,[]]
- [[[Plain [Str "1"]]
-  ,[Plain [Str "2"]]
-  ,[Plain [Str "3"]]]
- ,[[Plain [Str "4"]]
-  ,[Plain [Str "5"]]
-  ,[Plain [Str "6"]]]]
-,HorizontalRule
-,Table [] [AlignDefault,AlignDefault,AlignDefault] [0.0,0.0,0.0]
- [[]
- ,[]
- ,[]]
- [[[Plain [Str "1"]]
-  ,[Plain [Str "2"]]
-  ,[Plain [Str "3"]]]
- ,[[Plain [Str "4"]]
-  ,[Plain [Str "5"]]
-  ,[Plain [Str "6"]]]]
-,HorizontalRule
-,Table [] [AlignDefault,AlignDefault,AlignDefault] [0.0,0.0,0.0]
- [[]
- ,[]
- ,[]]
- [[[Plain [Str "1"]]
-  ,[Plain [Str "2"]]
-  ,[Plain [Str "3"]]]
- ,[[Plain [Str "4"]]
-  ,[Plain [Str "5"]]
-  ,[Plain [Str "6"]]]]
-,Header 2 ("empty-tables",[],[]) [Str "Empty",Space,Str "Tables"]
-,Para [Str "This",Space,Str "section",Space,Str "should",Space,Str "be",Space,Str "empty."]]
+Pandoc
+  Meta
+    { unMeta =
+        fromList
+          [ ( "generator" , MetaInlines [ Str "pandoc" ] )
+          , ( "title"
+            , MetaInlines
+                [ Str "Pandoc"
+                , Space
+                , Str "Test"
+                , Space
+                , Str "Suite"
+                ]
+            )
+          ]
+    }
+  [ Header
+      1
+      ( "pandoc-test-suite" , [ "title" ] , [] )
+      [ Str "Pandoc" , Space , Str "Test" , Space , Str "Suite" ]
+  , Para
+      [ Str "This"
+      , Space
+      , Str "is"
+      , Space
+      , Str "a"
+      , Space
+      , Str "set"
+      , Space
+      , Str "of"
+      , Space
+      , Str "tests"
+      , Space
+      , Str "for"
+      , Space
+      , Str "pandoc."
+      , Space
+      , Str "Most"
+      , Space
+      , Str "of"
+      , Space
+      , Str "them"
+      , Space
+      , Str "are"
+      , Space
+      , Str "adapted"
+      , Space
+      , Str "from"
+      , Space
+      , Str "John"
+      , Space
+      , Str "Gruber's"
+      , Space
+      , Str "markdown"
+      , Space
+      , Str "test"
+      , Space
+      , Str "suite."
+      ]
+  , HorizontalRule
+  , Header 1 ( "headers" , [] , [] ) [ Str "Headers" ]
+  , Header
+      2
+      ( "level-2-with-an-embedded-link" , [] , [] )
+      [ Str "Level"
+      , Space
+      , Str "2"
+      , Space
+      , Str "with"
+      , Space
+      , Str "an"
+      , Space
+      , Link
+          ( "" , [] , [] )
+          [ Str "embedded" , Space , Str "link" ]
+          ( "/url" , "" )
+      ]
+  , Header
+      3
+      ( "level-3-with-emphasis" , [] , [] )
+      [ Str "Level"
+      , Space
+      , Str "3"
+      , Space
+      , Str "with"
+      , Space
+      , Emph [ Str "emphasis" ]
+      ]
+  , Header
+      4 ( "level-4" , [] , [] ) [ Str "Level" , Space , Str "4" ]
+  , Header
+      5 ( "level-5" , [] , [] ) [ Str "Level" , Space , Str "5" ]
+  , Header
+      1 ( "level-1" , [] , [] ) [ Str "Level" , Space , Str "1" ]
+  , Header
+      2
+      ( "level-2-with-emphasis" , [] , [] )
+      [ Str "Level"
+      , Space
+      , Str "2"
+      , Space
+      , Str "with"
+      , Space
+      , Emph [ Str "emphasis" ]
+      ]
+  , Header
+      3 ( "level-3" , [] , [] ) [ Str "Level" , Space , Str "3" ]
+  , Para
+      [ Str "with"
+      , Space
+      , Str "no"
+      , Space
+      , Str "blank"
+      , Space
+      , Str "line"
+      ]
+  , Header
+      2 ( "level-2" , [] , [] ) [ Str "Level" , Space , Str "2" ]
+  , Para
+      [ Str "with"
+      , Space
+      , Str "no"
+      , Space
+      , Str "blank"
+      , Space
+      , Str "line"
+      ]
+  , HorizontalRule
+  , Header 1 ( "paragraphs" , [] , [] ) [ Str "Paragraphs" ]
+  , Para
+      [ Str "Here's"
+      , Space
+      , Str "a"
+      , Space
+      , Str "regular"
+      , Space
+      , Str "paragraph."
+      ]
+  , Para
+      [ Str "In"
+      , Space
+      , Str "Markdown"
+      , Space
+      , Str "1.0.0"
+      , Space
+      , Str "and"
+      , Space
+      , Str "earlier."
+      , Space
+      , Str "Version"
+      , Space
+      , Str "8."
+      , Space
+      , Str "This"
+      , Space
+      , Str "line"
+      , Space
+      , Str "turns"
+      , Space
+      , Str "into"
+      , Space
+      , Str "a"
+      , Space
+      , Str "list"
+      , Space
+      , Str "item."
+      , Space
+      , Str "Because"
+      , Space
+      , Str "a"
+      , Space
+      , Str "hard-wrapped"
+      , Space
+      , Str "line"
+      , Space
+      , Str "in"
+      , Space
+      , Str "the"
+      , Space
+      , Str "middle"
+      , Space
+      , Str "of"
+      , Space
+      , Str "a"
+      , Space
+      , Str "paragraph"
+      , Space
+      , Str "looked"
+      , Space
+      , Str "like"
+      , Space
+      , Str "a"
+      , Space
+      , Str "list"
+      , Space
+      , Str "item."
+      ]
+  , Para
+      [ Str "Here's"
+      , Space
+      , Str "one"
+      , Space
+      , Str "with"
+      , Space
+      , Str "a"
+      , Space
+      , Str "bullet."
+      , Space
+      , Str "*"
+      , Space
+      , Str "criminey."
+      ]
+  , Para
+      [ Str "There"
+      , Space
+      , Str "should"
+      , Space
+      , Str "be"
+      , Space
+      , Str "a"
+      , Space
+      , Str "hard"
+      , Space
+      , Str "line"
+      , Space
+      , Str "break"
+      , LineBreak
+      , Str "here."
+      ]
+  , HorizontalRule
+  , Header
+      1
+      ( "block-quotes" , [] , [] )
+      [ Str "Block" , Space , Str "Quotes" ]
+  , Para [ Str "E-mail" , Space , Str "style:" ]
+  , BlockQuote
+      [ Para
+          [ Str "This"
+          , Space
+          , Str "is"
+          , Space
+          , Str "a"
+          , Space
+          , Str "block"
+          , Space
+          , Str "quote."
+          , Space
+          , Str "It"
+          , Space
+          , Str "is"
+          , Space
+          , Str "pretty"
+          , Space
+          , Str "short."
+          ]
+      ]
+  , BlockQuote
+      [ Para
+          [ Str "Code"
+          , Space
+          , Str "in"
+          , Space
+          , Str "a"
+          , Space
+          , Str "block"
+          , Space
+          , Str "quote:"
+          ]
+      , CodeBlock
+          ( "" , [] , [] ) "sub status {\n    print \"working\";\n}"
+      , Para [ Str "A" , Space , Str "list:" ]
+      , OrderedList
+          ( 1 , DefaultStyle , DefaultDelim )
+          [ [ Plain [ Str "item" , Space , Str "one" ] ]
+          , [ Plain [ Str "item" , Space , Str "two" ] ]
+          ]
+      , Para
+          [ Str "Nested"
+          , Space
+          , Str "block"
+          , Space
+          , Str "quotes:"
+          ]
+      , BlockQuote [ Para [ Str "nested" ] ]
+      , BlockQuote [ Para [ Str "nested" ] ]
+      ]
+  , Para
+      [ Str "This"
+      , Space
+      , Str "should"
+      , Space
+      , Str "not"
+      , Space
+      , Str "be"
+      , Space
+      , Str "a"
+      , Space
+      , Str "block"
+      , Space
+      , Str "quote:"
+      , Space
+      , Str "2"
+      , Space
+      , Str ">"
+      , Space
+      , Str "1."
+      ]
+  , Para [ Str "Box-style:" ]
+  , BlockQuote
+      [ Para [ Str "Example:" ]
+      , CodeBlock
+          ( "" , [] , [] ) "sub status {\n    print \"working\";\n}"
+      ]
+  , BlockQuote
+      [ OrderedList
+          ( 1 , DefaultStyle , DefaultDelim )
+          [ [ Plain [ Str "do" , Space , Str "laundry" ] ]
+          , [ Plain
+                [ Str "take"
+                , Space
+                , Str "out"
+                , Space
+                , Str "the"
+                , Space
+                , Str "trash"
+                ]
+            ]
+          ]
+      ]
+  , Para
+      [ Str "Here's"
+      , Space
+      , Str "a"
+      , Space
+      , Str "nested"
+      , Space
+      , Str "one:"
+      ]
+  , BlockQuote
+      [ Para [ Str "Joe" , Space , Str "said:" ]
+      , BlockQuote
+          [ Para
+              [ Str "Don't" , Space , Str "quote" , Space , Str "me." ]
+          ]
+      ]
+  , Para
+      [ Str "And"
+      , Space
+      , Str "a"
+      , Space
+      , Str "following"
+      , Space
+      , Str "paragraph."
+      ]
+  , HorizontalRule
+  , Header
+      1
+      ( "inline-quotes" , [] , [] )
+      [ Str "Inline" , Space , Str "quotes" ]
+  , Para
+      [ Str "Normal"
+      , Space
+      , Str "text"
+      , Space
+      , Str "but"
+      , Space
+      , Str "then"
+      , Space
+      , Str "a"
+      , Space
+      , Quoted
+          DoubleQuote
+          [ Span
+              ( ""
+              , []
+              , [ ( "cite"
+                  , "https://www.imdb.com/title/tt0062622/quotes/qt0396921"
+                  )
+                ]
+              )
+              [ Str "inline" , Space , Str "quote" ]
+          ]
+      , Str "."
+      ]
+  , Para
+      [ Quoted
+          DoubleQuote
+          [ Str "Missing"
+          , Space
+          , Str "a"
+          , Space
+          , Str "cite"
+          , Space
+          , Str "attribute"
+          , Space
+          , Str "means"
+          , Space
+          , Str "its"
+          , Space
+          , Str "just"
+          , Space
+          , Str "normal"
+          , Space
+          , Str "text"
+          ]
+      ]
+  , HorizontalRule
+  , Header
+      1
+      ( "code-blocks" , [] , [] )
+      [ Str "Code" , Space , Str "Blocks" ]
+  , Para [ Str "Code:" ]
+  , CodeBlock
+      ( "" , [] , [] )
+      "---- (should be four hyphens)\n\nsub status {\n    print \"working\";\n}\n\nthis code block is indented by one tab"
+  , Para [ Str "And:" ]
+  , CodeBlock
+      ( "" , [] , [] )
+      "    this code block is indented by two tabs\n\nThese should not be escaped:  \\$ \\\\ \\> \\[ \\{"
+  , HorizontalRule
+  , Header 1 ( "lists" , [] , [] ) [ Str "Lists" ]
+  , Header 2 ( "unordered" , [] , [] ) [ Str "Unordered" ]
+  , Para [ Str "Asterisks" , Space , Str "tight:" ]
+  , BulletList
+      [ [ Plain [ Str "asterisk" , Space , Str "1" ] ]
+      , [ Plain [ Str "asterisk" , Space , Str "2" ] ]
+      , [ Plain [ Str "asterisk" , Space , Str "3" ] ]
+      ]
+  , Para [ Str "Asterisks" , Space , Str "loose:" ]
+  , BulletList
+      [ [ Para [ Str "asterisk" , Space , Str "1" ] ]
+      , [ Para [ Str "asterisk" , Space , Str "2" ] ]
+      , [ Para [ Str "asterisk" , Space , Str "3" ] ]
+      ]
+  , Para [ Str "Pluses" , Space , Str "tight:" ]
+  , BulletList
+      [ [ Plain [ Str "Plus" , Space , Str "1" ] ]
+      , [ Plain [ Str "Plus" , Space , Str "2" ] ]
+      , [ Plain [ Str "Plus" , Space , Str "3" ] ]
+      ]
+  , Para [ Str "Pluses" , Space , Str "loose:" ]
+  , BulletList
+      [ [ Para [ Str "Plus" , Space , Str "1" ] ]
+      , [ Para [ Str "Plus" , Space , Str "2" ] ]
+      , [ Para [ Str "Plus" , Space , Str "3" ] ]
+      ]
+  , Para [ Str "Minuses" , Space , Str "tight:" ]
+  , BulletList
+      [ [ Plain [ Str "Minus" , Space , Str "1" ] ]
+      , [ Plain [ Str "Minus" , Space , Str "2" ] ]
+      , [ Plain [ Str "Minus" , Space , Str "3" ] ]
+      ]
+  , Para [ Str "Minuses" , Space , Str "loose:" ]
+  , BulletList
+      [ [ Para [ Str "Minus" , Space , Str "1" ] ]
+      , [ Para [ Str "Minus" , Space , Str "2" ] ]
+      , [ Para [ Str "Minus" , Space , Str "3" ] ]
+      ]
+  , Header 2 ( "ordered" , [] , [] ) [ Str "Ordered" ]
+  , Para [ Str "Tight:" ]
+  , OrderedList
+      ( 1 , DefaultStyle , DefaultDelim )
+      [ [ Plain [ Str "First" ] ]
+      , [ Plain [ Str "Second" ] ]
+      , [ Plain [ Str "Third" ] ]
+      ]
+  , Para [ Str "and:" ]
+  , OrderedList
+      ( 1 , DefaultStyle , DefaultDelim )
+      [ [ Plain [ Str "One" ] ]
+      , [ Plain [ Str "Two" ] ]
+      , [ Plain [ Str "Three" ] ]
+      ]
+  , Para
+      [ Str "Loose" , Space , Str "using" , Space , Str "tabs:" ]
+  , OrderedList
+      ( 1 , DefaultStyle , DefaultDelim )
+      [ [ Para [ Str "First" ] ]
+      , [ Para [ Str "Second" ] ]
+      , [ Para [ Str "Third" ] ]
+      ]
+  , Para
+      [ Str "and" , Space , Str "using" , Space , Str "spaces:" ]
+  , OrderedList
+      ( 1 , DefaultStyle , DefaultDelim )
+      [ [ Para [ Str "One" ] ]
+      , [ Para [ Str "Two" ] ]
+      , [ Para [ Str "Three" ] ]
+      ]
+  , Para [ Str "Multiple" , Space , Str "paragraphs:" ]
+  , OrderedList
+      ( 1 , DefaultStyle , DefaultDelim )
+      [ [ 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's"
+            , Space
+            , Str "back."
+            ]
+        ]
+      , [ Para [ Str "Item" , Space , Str "2." ] ]
+      , [ Para [ Str "Item" , Space , Str "3." ] ]
+      ]
+  , Para [ Str "List" , Space , Str "styles:" ]
+  , OrderedList ( 1 , DefaultStyle , DefaultDelim ) []
+  , OrderedList ( 1 , LowerRoman , DefaultDelim ) []
+  , OrderedList ( 1 , LowerRoman , DefaultDelim ) []
+  , OrderedList ( 1 , DefaultStyle , DefaultDelim ) []
+  , OrderedList ( 1 , LowerRoman , DefaultDelim ) []
+  , OrderedList ( 1 , LowerRoman , DefaultDelim ) []
+  , Header 2 ( "nested" , [] , [] ) [ Str "Nested" ]
+  , BulletList
+      [ [ Plain [ Str "Tab" ]
+        , BulletList
+            [ [ Plain [ Str "Tab" ]
+              , BulletList [ [ Plain [ Str "Tab" ] ] ]
+              ]
+            ]
+        ]
+      ]
+  , Para [ Str "Here's" , Space , Str "another:" ]
+  , OrderedList
+      ( 1 , DefaultStyle , DefaultDelim )
+      [ [ Plain [ Str "First" ] ]
+      , [ Plain [ Str "Second:" ]
+        , BulletList
+            [ [ Plain [ Str "Fee" ] ]
+            , [ Plain [ Str "Fie" ] ]
+            , [ Plain [ Str "Foe" ] ]
+            ]
+        ]
+      , [ Plain [ Str "Third" ] ]
+      ]
+  , Para
+      [ Str "Same"
+      , Space
+      , Str "thing"
+      , Space
+      , Str "but"
+      , Space
+      , Str "with"
+      , Space
+      , Str "paragraphs:"
+      ]
+  , OrderedList
+      ( 1 , DefaultStyle , DefaultDelim )
+      [ [ Para [ Str "First" ] ]
+      , [ Para [ Str "Second:" ]
+        , BulletList
+            [ [ Plain [ Str "Fee" ] ]
+            , [ Plain [ Str "Fie" ] ]
+            , [ Plain [ Str "Foe" ] ]
+            ]
+        ]
+      , [ Para [ Str "Third" ] ]
+      ]
+  , Header
+      2
+      ( "tabs-and-spaces" , [] , [] )
+      [ Str "Tabs" , Space , Str "and" , Space , Str "spaces" ]
+  , BulletList
+      [ [ Para
+            [ Str "this"
+            , Space
+            , Str "is"
+            , Space
+            , Str "a"
+            , Space
+            , Str "list"
+            , Space
+            , Str "item"
+            , Space
+            , Str "indented"
+            , Space
+            , Str "with"
+            , Space
+            , Str "tabs"
+            ]
+        ]
+      , [ Para
+            [ Str "this"
+            , Space
+            , Str "is"
+            , Space
+            , Str "a"
+            , Space
+            , Str "list"
+            , Space
+            , Str "item"
+            , Space
+            , Str "indented"
+            , Space
+            , Str "with"
+            , Space
+            , Str "spaces"
+            ]
+        , BulletList
+            [ [ Para
+                  [ Str "this"
+                  , Space
+                  , Str "is"
+                  , Space
+                  , Str "an"
+                  , Space
+                  , Str "example"
+                  , Space
+                  , Str "list"
+                  , Space
+                  , Str "item"
+                  , Space
+                  , Str "indented"
+                  , Space
+                  , Str "with"
+                  , Space
+                  , Str "tabs"
+                  ]
+              ]
+            , [ Para
+                  [ Str "this"
+                  , Space
+                  , Str "is"
+                  , Space
+                  , Str "an"
+                  , Space
+                  , Str "example"
+                  , Space
+                  , Str "list"
+                  , Space
+                  , Str "item"
+                  , Space
+                  , Str "indented"
+                  , Space
+                  , Str "with"
+                  , Space
+                  , Str "spaces"
+                  ]
+              ]
+            ]
+        ]
+      ]
+  , Header
+      2
+      ( "fancy-list-markers" , [] , [] )
+      [ Str "Fancy" , Space , Str "list" , Space , Str "markers" ]
+  , OrderedList
+      ( 2 , Decimal , DefaultDelim )
+      [ [ Plain
+            [ 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 , DefaultDelim )
+            [ [ Plain
+                  [ Str "sublist"
+                  , Space
+                  , Str "with"
+                  , Space
+                  , Str "roman"
+                  , Space
+                  , Str "numerals,"
+                  , Space
+                  , Str "starting"
+                  , Space
+                  , Str "with"
+                  , Space
+                  , Str "4"
+                  ]
+              ]
+            , [ Plain [ Str "more" , Space , Str "items" ]
+              , OrderedList
+                  ( 1 , UpperAlpha , DefaultDelim )
+                  [ [ Plain [ Str "a" , Space , Str "subsublist" ] ]
+                  , [ Plain [ Str "a" , Space , Str "subsublist" ] ]
+                  ]
+              ]
+            ]
+        ]
+      ]
+  , Para [ Str "Nesting:" ]
+  , OrderedList
+      ( 1 , UpperAlpha , DefaultDelim )
+      [ [ Plain [ Str "Upper" , Space , Str "Alpha" ]
+        , OrderedList
+            ( 1 , UpperRoman , DefaultDelim )
+            [ [ Plain [ Str "Upper" , Space , Str "Roman." ]
+              , OrderedList
+                  ( 6 , Decimal , DefaultDelim )
+                  [ [ Plain
+                        [ Str "Decimal"
+                        , Space
+                        , Str "start"
+                        , Space
+                        , Str "with"
+                        , Space
+                        , Str "6"
+                        ]
+                    , OrderedList
+                        ( 3 , LowerAlpha , DefaultDelim )
+                        [ [ Plain
+                              [ Str "Lower"
+                              , Space
+                              , Str "alpha"
+                              , Space
+                              , Str "with"
+                              , Space
+                              , Str "paren"
+                              ]
+                          ]
+                        ]
+                    ]
+                  ]
+              ]
+            ]
+        ]
+      ]
+  , Para [ Str "Autonumbering:" ]
+  , OrderedList
+      ( 1 , DefaultStyle , DefaultDelim )
+      [ [ Plain [ Str "Autonumber." ] ]
+      , [ Plain [ Str "More." ]
+        , OrderedList
+            ( 1 , DefaultStyle , DefaultDelim )
+            [ [ Plain [ Str "Nested." ] ] ]
+        ]
+      ]
+  , HorizontalRule
+  , Header 2 ( "definition" , [] , [] ) [ Str "Definition" ]
+  , DefinitionList
+      [ ( [ Str "Violin" ]
+        , [ [ Plain
+                [ Str "Stringed"
+                , Space
+                , Str "musical"
+                , Space
+                , Str "instrument."
+                ]
+            ]
+          , [ Plain [ Str "Torture" , Space , Str "device." ] ]
+          ]
+        )
+      , ( [ Str "Cello" , LineBreak , Str "Violoncello" ]
+        , [ [ Plain
+                [ Str "Low-voiced"
+                , Space
+                , Str "stringed"
+                , Space
+                , Str "instrument."
+                ]
+            ]
+          ]
+        )
+      ]
+  , HorizontalRule
+  , Header
+      1
+      ( "inline-markup" , [] , [] )
+      [ Str "Inline" , Space , Str "Markup" ]
+  , Para
+      [ Str "This"
+      , Space
+      , Str "is"
+      , Space
+      , Emph [ Str "emphasized" ]
+      , Str ","
+      , Space
+      , Str "and"
+      , Space
+      , Str "so"
+      , Space
+      , Emph [ Str "is" , Space , Str "this" ]
+      , Str "."
+      ]
+  , Para
+      [ Str "This"
+      , Space
+      , Str "is"
+      , Space
+      , Strong [ Str "strong" ]
+      , Str ","
+      , Space
+      , Str "and"
+      , Space
+      , Str "so"
+      , Space
+      , Strong [ Str "is" , Space , Str "this" ]
+      , Str "."
+      ]
+  , Para
+      [ Str "Empty"
+      , Space
+      , Strong []
+      , Space
+      , Str "and"
+      , Space
+      , Emph []
+      , Str "."
+      ]
+  , Para
+      [ Str "An"
+      , Space
+      , Emph
+          [ Link
+              ( "" , [] , [] )
+              [ Str "emphasized" , Space , Str "link" ]
+              ( "/url" , "" )
+          ]
+      , Str "."
+      ]
+  , Para
+      [ Strong
+          [ Emph
+              [ Str "This"
+              , Space
+              , Str "is"
+              , Space
+              , Str "strong"
+              , Space
+              , Str "and"
+              , Space
+              , Str "em."
+              ]
+          ]
+      ]
+  , Para
+      [ Str "So"
+      , Space
+      , Str "is"
+      , Space
+      , Strong [ Emph [ Str "this" ] ]
+      , Space
+      , Str "word."
+      ]
+  , Para
+      [ Strong
+          [ Emph
+              [ Str "This"
+              , Space
+              , Str "is"
+              , Space
+              , Str "strong"
+              , Space
+              , Str "and"
+              , Space
+              , Str "em."
+              ]
+          ]
+      ]
+  , Para
+      [ Str "So"
+      , Space
+      , Str "is"
+      , Space
+      , Strong [ Emph [ Str "this" ] ]
+      , Space
+      , Str "word."
+      ]
+  , Para
+      [ Str "This"
+      , Space
+      , Str "is"
+      , Space
+      , Str "code:"
+      , Space
+      , Code ( "" , [] , [] ) ">"
+      , Str ","
+      , Space
+      , Code ( "" , [] , [] ) "$"
+      , Str ","
+      , Space
+      , Code ( "" , [] , [] ) "\\"
+      , Str ","
+      , Space
+      , Code ( "" , [] , [] ) "\\$"
+      , Str ","
+      , Space
+      , Code ( "" , [] , [] ) "<html>"
+      , Str "."
+      ]
+  , Para
+      [ Str "This"
+      , Space
+      , Str "is"
+      , Space
+      , SmallCaps [ Str "small" , Space , Str "caps" ]
+      , Str "."
+      ]
+  , Para
+      [ Str "These"
+      , Space
+      , Str "are"
+      , Space
+      , Str "all"
+      , Space
+      , Str "underlined:"
+      , Space
+      , Underline [ Str "foo" ]
+      , Space
+      , Str "and"
+      , Space
+      , Underline [ Str "bar" ]
+      , Str "."
+      ]
+  , Para
+      [ Str "These"
+      , Space
+      , Str "are"
+      , Space
+      , Str "all"
+      , Space
+      , Str "strikethrough:"
+      , Space
+      , Strikeout [ Str "foo" ]
+      , Str ","
+      , Space
+      , Strikeout [ Str "bar" ]
+      , Str ","
+      , Space
+      , Str "and"
+      , Space
+      , Strikeout [ Str "baz" ]
+      , Str "."
+      ]
+  , HorizontalRule
+  , Header
+      1
+      ( "smart-quotes-ellipses-dashes" , [] , [] )
+      [ Str "Smart"
+      , Space
+      , Str "quotes,"
+      , Space
+      , Str "ellipses,"
+      , Space
+      , Str "dashes"
+      ]
+  , Para
+      [ Str "\"Hello,\""
+      , Space
+      , Str "said"
+      , Space
+      , Str "the"
+      , Space
+      , Str "spider."
+      , Space
+      , Str "\"'Shelob'"
+      , Space
+      , Str "is"
+      , Space
+      , Str "my"
+      , Space
+      , Str "name.\""
+      ]
+  , Para
+      [ Str "'A',"
+      , Space
+      , Str "'B',"
+      , Space
+      , Str "and"
+      , Space
+      , Str "'C'"
+      , Space
+      , Str "are"
+      , Space
+      , Str "letters."
+      ]
+  , Para
+      [ Str "'Oak,'"
+      , Space
+      , Str "'elm,'"
+      , Space
+      , Str "and"
+      , Space
+      , Str "'beech'"
+      , Space
+      , Str "are"
+      , Space
+      , Str "names"
+      , Space
+      , Str "of"
+      , Space
+      , Str "trees."
+      , Space
+      , Str "So"
+      , Space
+      , Str "is"
+      , Space
+      , Str "'pine.'"
+      ]
+  , Para
+      [ Str "'He"
+      , Space
+      , Str "said,"
+      , Space
+      , Str "\"I"
+      , Space
+      , Str "want"
+      , Space
+      , Str "to"
+      , Space
+      , Str "go.\"'"
+      , Space
+      , Str "Were"
+      , Space
+      , Str "you"
+      , Space
+      , Str "alive"
+      , Space
+      , Str "in"
+      , Space
+      , Str "the"
+      , Space
+      , Str "70's?"
+      ]
+  , Para
+      [ Str "Here"
+      , Space
+      , Str "is"
+      , Space
+      , Str "some"
+      , Space
+      , Str "quoted"
+      , Space
+      , Str "'"
+      , Code ( "" , [] , [] ) "code"
+      , Str "'"
+      , Space
+      , Str "and"
+      , Space
+      , Str "a"
+      , Space
+      , Str "\""
+      , Link
+          ( "" , [] , [] )
+          [ Str "quoted" , Space , Str "link" ]
+          ( "http://example.com/?foo=1&bar=2" , "" )
+      , Str "\"."
+      ]
+  , Para
+      [ Str "Some"
+      , Space
+      , Str "dashes:"
+      , Space
+      , Str "one---two"
+      , Space
+      , Str "---"
+      , Space
+      , Str "three--four"
+      , Space
+      , Str "--"
+      , Space
+      , Str "five."
+      ]
+  , Para
+      [ Str "Dashes"
+      , Space
+      , Str "between"
+      , Space
+      , Str "numbers:"
+      , Space
+      , Str "5-7,"
+      , Space
+      , Str "255-66,"
+      , Space
+      , Str "1987-1999."
+      ]
+  , Para
+      [ Str "Ellipses...and."
+      , Space
+      , Str "."
+      , Space
+      , Str ".and"
+      , Space
+      , Str "."
+      , Space
+      , Str "."
+      , Space
+      , Str "."
+      , Space
+      , Str "."
+      ]
+  , HorizontalRule
+  , Header 1 ( "latex" , [] , [] ) [ Str "LaTeX" ]
+  , BulletList
+      [ [ Plain [ Str "\\cite[22-23]{smith.1899}" ] ]
+      , [ Plain [ Str "\\doublespacing" ] ]
+      , [ Plain [ Str "$2+2=4$" ] ]
+      , [ Plain
+            [ Str "$x" , Space , Str "\\in" , Space , Str "y$" ]
+        ]
+      , [ Plain
+            [ Str "$\\alpha"
+            , Space
+            , Str "\\wedge"
+            , Space
+            , Str "\\omega$"
+            ]
+        ]
+      , [ Plain [ Str "$223$" ] ]
+      , [ Plain [ Str "$p$-Tree" ] ]
+      , [ Plain
+            [ Str "$\\frac{d}{dx}f(x)=\\lim_{h\\to"
+            , Space
+            , Str "0}\\frac{f(x+h)-f(x)}{h}$"
+            ]
+        ]
+      , [ Plain
+            [ Str "Here's"
+            , Space
+            , Str "one"
+            , Space
+            , Str "that"
+            , Space
+            , Str "has"
+            , Space
+            , Str "a"
+            , Space
+            , Str "line"
+            , Space
+            , Str "break"
+            , Space
+            , Str "in"
+            , Space
+            , Str "it:"
+            , Space
+            , Str "$\\alpha"
+            , Space
+            , Str "+"
+            , Space
+            , Str "\\omega"
+            , Space
+            , Str "\\times"
+            , Space
+            , Str "x^2$."
+            ]
+        ]
+      ]
+  , Para
+      [ Str "These"
+      , Space
+      , Str "shouldn't"
+      , Space
+      , Str "be"
+      , Space
+      , Str "math:"
+      ]
+  , BulletList
+      [ [ Plain
+            [ Str "To"
+            , Space
+            , Str "get"
+            , Space
+            , Str "the"
+            , Space
+            , Str "famous"
+            , Space
+            , Str "equation,"
+            , Space
+            , Str "write"
+            , Space
+            , Code ( "" , [] , [] ) "$e = mc^2$"
+            , Str "."
+            ]
+        ]
+      , [ Plain
+            [ Str "$22,000"
+            , Space
+            , Str "is"
+            , Space
+            , Str "a"
+            , Space
+            , Emph [ Str "lot" ]
+            , Space
+            , Str "of"
+            , Space
+            , Str "money."
+            , Space
+            , Str "So"
+            , Space
+            , Str "is"
+            , Space
+            , Str "$34,000."
+            , Space
+            , Str "(It"
+            , Space
+            , Str "worked"
+            , Space
+            , Str "if"
+            , Space
+            , Str "\"lot\""
+            , Space
+            , Str "is"
+            , Space
+            , Str "emphasized.)"
+            ]
+        ]
+      , [ Plain
+            [ Str "Escaped"
+            , Space
+            , Code ( "" , [] , [] ) "$"
+            , Str ":"
+            , Space
+            , Str "$73"
+            , Space
+            , Emph
+                [ Str "this"
+                , Space
+                , Str "should"
+                , Space
+                , Str "be"
+                , Space
+                , Str "emphasized"
+                ]
+            , Space
+            , Str "23$."
+            ]
+        ]
+      ]
+  , Para
+      [ Str "Here's"
+      , Space
+      , Str "a"
+      , Space
+      , Str "LaTeX"
+      , Space
+      , Str "table:"
+      ]
+  , Para
+      [ Str "\\begin{tabular}{|l|l|}\\hline"
+      , Space
+      , Str "Animal"
+      , Space
+      , Str "&"
+      , Space
+      , Str "Number"
+      , Space
+      , Str "\\\\"
+      , Space
+      , Str "\\hline"
+      , Space
+      , Str "Dog"
+      , Space
+      , Str "&"
+      , Space
+      , Str "2"
+      , Space
+      , Str "\\\\"
+      , Space
+      , Str "Cat"
+      , Space
+      , Str "&"
+      , Space
+      , Str "1"
+      , Space
+      , Str "\\\\"
+      , Space
+      , Str "\\hline"
+      , Space
+      , Str "\\end{tabular}"
+      ]
+  , HorizontalRule
+  , Header
+      1
+      ( "special-characters" , [] , [] )
+      [ Str "Special" , Space , Str "Characters" ]
+  , Para
+      [ Str "Here"
+      , Space
+      , Str "is"
+      , Space
+      , Str "some"
+      , Space
+      , Str "unicode:"
+      ]
+  , BulletList
+      [ [ Plain
+            [ Str "I" , Space , Str "hat:" , Space , Str "\206" ]
+        ]
+      , [ Plain
+            [ Str "o" , Space , Str "umlaut:" , Space , Str "\246" ]
+        ]
+      , [ Plain [ Str "section:" , Space , Str "\167" ] ]
+      , [ Plain
+            [ Str "set"
+            , Space
+            , Str "membership:"
+            , Space
+            , Str "\8712"
+            ]
+        ]
+      , [ Plain [ Str "copyright:" , Space , Str "\169" ] ]
+      ]
+  , Para
+      [ Str "AT&T"
+      , Space
+      , Str "has"
+      , Space
+      , Str "an"
+      , Space
+      , Str "ampersand"
+      , Space
+      , Str "in"
+      , Space
+      , Str "their"
+      , Space
+      , Str "name."
+      ]
+  , Para
+      [ Str "AT&T"
+      , Space
+      , Str "is"
+      , Space
+      , Str "another"
+      , Space
+      , Str "way"
+      , Space
+      , Str "to"
+      , Space
+      , Str "write"
+      , Space
+      , Str "it."
+      ]
+  , Para
+      [ Str "This" , Space , Str "&" , Space , Str "that." ]
+  , Para [ Str "4" , Space , Str "<" , Space , Str "5." ]
+  , Para [ Str "6" , Space , Str ">" , Space , Str "5." ]
+  , Para [ Str "Backslash:" , Space , Str "\\" ]
+  , Para [ Str "Backtick:" , Space , Str "`" ]
+  , Para [ Str "Asterisk:" , Space , Str "*" ]
+  , Para [ Str "Underscore:" , Space , Str "_" ]
+  , Para
+      [ Str "Left" , Space , Str "brace:" , Space , Str "{" ]
+  , Para
+      [ Str "Right" , Space , Str "brace:" , Space , Str "}" ]
+  , Para
+      [ Str "Left" , Space , Str "bracket:" , Space , Str "[" ]
+  , Para
+      [ Str "Right" , Space , Str "bracket:" , Space , Str "]" ]
+  , Para
+      [ Str "Left" , Space , Str "paren:" , Space , Str "(" ]
+  , Para
+      [ Str "Right" , Space , Str "paren:" , Space , Str ")" ]
+  , Para [ Str "Greater-than:" , Space , Str ">" ]
+  , Para [ Str "Hash:" , Space , Str "#" ]
+  , Para [ Str "Period:" , Space , Str "." ]
+  , Para [ Str "Bang:" , Space , Str "!" ]
+  , Para [ Str "Plus:" , Space , Str "+" ]
+  , Para [ Str "Minus:" , Space , Str "-" ]
+  , HorizontalRule
+  , Header 1 ( "links" , [] , [] ) [ Str "Links" ]
+  , Header 2 ( "explicit" , [] , [] ) [ Str "Explicit" ]
+  , Para
+      [ Str "Just"
+      , Space
+      , Str "a"
+      , Space
+      , Link ( "" , [] , [] ) [ Str "URL" ] ( "/url/" , "" )
+      , Str "."
+      ]
+  , Para
+      [ Link
+          ( "" , [] , [] )
+          [ Str "URL" , Space , Str "and" , Space , Str "title" ]
+          ( "/url/" , "title" )
+      , Str "."
+      ]
+  , Para
+      [ Link
+          ( "" , [] , [] )
+          [ Str "URL" , Space , Str "and" , Space , Str "title" ]
+          ( "/url/" , "title preceded by two spaces" )
+      , Str "."
+      ]
+  , Para
+      [ Link
+          ( "" , [] , [] )
+          [ Str "URL" , Space , Str "and" , Space , Str "title" ]
+          ( "/url/" , "title preceded by a tab" )
+      , Str "."
+      ]
+  , Para
+      [ Link
+          ( "" , [] , [] )
+          [ Str "URL" , Space , Str "and" , Space , Str "title" ]
+          ( "/url/" , "title with \"quotes\" in it" )
+      ]
+  , Para
+      [ Link
+          ( "" , [] , [] )
+          [ Str "URL" , Space , Str "and" , Space , Str "title" ]
+          ( "/url/" , "title with single quotes" )
+      ]
+  , Para
+      [ Str "Email"
+      , Space
+      , Str "link"
+      , Space
+      , Str "(nobody"
+      , Space
+      , Str "[at]"
+      , Space
+      , Str "nowhere.net)"
+      ]
+  , Para
+      [ Link ( "" , [] , [] ) [ Str "Empty" ] ( "" , "" )
+      , Str "."
+      ]
+  , Header 2 ( "reference" , [] , [] ) [ Str "Reference" ]
+  , Para
+      [ Str "Foo"
+      , Space
+      , Link ( "" , [] , [] ) [ Str "bar" ] ( "/url/" , "" )
+      , Str "."
+      ]
+  , Para
+      [ Str "Foo"
+      , Space
+      , Link ( "" , [] , [] ) [ Str "bar" ] ( "/url/" , "" )
+      , Str "."
+      ]
+  , Para
+      [ Str "Foo"
+      , Space
+      , Link ( "" , [] , [] ) [ Str "bar" ] ( "/url/" , "" )
+      , Str "."
+      ]
+  , Para
+      [ Str "With"
+      , Space
+      , Link
+          ( "" , [] , [] )
+          [ Str "embedded" , Space , Str "[brackets]" ]
+          ( "/url/" , "" )
+      , Str "."
+      ]
+  , Para
+      [ Link ( "" , [] , [] ) [ Str "b" ] ( "/url/" , "" )
+      , Space
+      , Str "by"
+      , Space
+      , Str "itself"
+      , Space
+      , Str "should"
+      , Space
+      , Str "be"
+      , Space
+      , Str "a"
+      , Space
+      , Str "link."
+      ]
+  , Para
+      [ Str "Indented"
+      , Space
+      , Link ( "" , [] , [] ) [ Str "once" ] ( "/url" , "" )
+      , Str "."
+      ]
+  , Para
+      [ Str "Indented"
+      , Space
+      , Link ( "" , [] , [] ) [ Str "twice" ] ( "/url" , "" )
+      , Str "."
+      ]
+  , Para
+      [ Str "Indented"
+      , Space
+      , Link ( "" , [] , [] ) [ Str "thrice" ] ( "/url" , "" )
+      , Str "."
+      ]
+  , Para
+      [ Str "This"
+      , Space
+      , Str "should"
+      , Space
+      , Str "[not]"
+      , Space
+      , Str "be"
+      , Space
+      , Str "a"
+      , Space
+      , Str "link."
+      ]
+  , CodeBlock ( "" , [] , [] ) "[not]: /url"
+  , Para
+      [ Str "Foo"
+      , Space
+      , Link
+          ( "" , [] , [] )
+          [ Str "bar" ]
+          ( "/url/" , "Title with \"quotes\" inside" )
+      , Str "."
+      ]
+  , Para
+      [ Str "Foo"
+      , Space
+      , Link
+          ( "" , [] , [] )
+          [ Str "biz" ]
+          ( "/url/" , "Title with \"quote\" inside" )
+      , Str "."
+      ]
+  , Header
+      2
+      ( "with-ampersands" , [] , [] )
+      [ Str "With" , Space , Str "ampersands" ]
+  , Para
+      [ Str "Here's"
+      , Space
+      , Str "a"
+      , Space
+      , Link
+          ( "" , [] , [] )
+          [ Str "link"
+          , Space
+          , Str "with"
+          , Space
+          , Str "an"
+          , Space
+          , Str "ampersand"
+          , Space
+          , Str "in"
+          , Space
+          , Str "the"
+          , Space
+          , Str "URL"
+          ]
+          ( "http://example.com/?foo=1&bar=2" , "" )
+      , Str "."
+      ]
+  , Para
+      [ Str "Here's"
+      , Space
+      , Str "a"
+      , Space
+      , Str "link"
+      , Space
+      , Str "with"
+      , Space
+      , Str "an"
+      , Space
+      , Str "amersand"
+      , Space
+      , Str "in"
+      , Space
+      , Str "the"
+      , Space
+      , Str "link"
+      , Space
+      , Str "text:"
+      , Space
+      , Link
+          ( "" , [] , [] )
+          [ Str "AT&T" ]
+          ( "http://att.com/" , "AT&T" )
+      , Str "."
+      ]
+  , Para
+      [ Str "Here's"
+      , Space
+      , Str "an"
+      , Space
+      , Link
+          ( "" , [] , [] )
+          [ Str "inline" , Space , Str "link" ]
+          ( "/script?foo=1&bar=2" , "" )
+      , Str "."
+      ]
+  , Para
+      [ Str "Here's"
+      , Space
+      , Str "an"
+      , Space
+      , Link
+          ( "" , [] , [] )
+          [ Str "inline"
+          , Space
+          , Str "link"
+          , Space
+          , Str "in"
+          , Space
+          , Str "pointy"
+          , Space
+          , Str "braces"
+          ]
+          ( "/script?foo=1&bar=2" , "" )
+      , Str "."
+      ]
+  , Header 2 ( "autolinks" , [] , [] ) [ Str "Autolinks" ]
+  , Para
+      [ Str "With"
+      , Space
+      , Str "an"
+      , Space
+      , Str "ampersand:"
+      , Space
+      , Link
+          ( "" , [] , [] )
+          [ Str "http://example.com/?foo=1&bar=2" ]
+          ( "http://example.com/?foo=1&bar=2" , "" )
+      ]
+  , BulletList
+      [ [ Plain
+            [ Str "In" , Space , Str "a" , Space , Str "list?" ]
+        ]
+      , [ Plain
+            [ Link
+                ( "" , [] , [] )
+                [ Str "http://example.com/" ]
+                ( "http://example.com/" , "" )
+            ]
+        ]
+      , [ Plain [ Str "It" , Space , Str "should." ] ]
+      ]
+  , Para
+      [ Str "An"
+      , Space
+      , Str "e-mail"
+      , Space
+      , Str "address:"
+      , Space
+      , Str "nobody"
+      , Space
+      , Str "[at]"
+      , Space
+      , Str "nowhere.net"
+      ]
+  , BlockQuote
+      [ Para
+          [ Str "Blockquoted:"
+          , Space
+          , Link
+              ( "" , [] , [] )
+              [ Str "http://example.com/" ]
+              ( "http://example.com/" , "" )
+          ]
+      ]
+  , Para
+      [ Str "Auto-links"
+      , Space
+      , Str "should"
+      , Space
+      , Str "not"
+      , Space
+      , Str "occur"
+      , Space
+      , Str "here:"
+      , Space
+      , Code ( "" , [] , [] ) "<http://example.com/>"
+      ]
+  , CodeBlock
+      ( "" , [] , [] ) "or here: <http://example.com/>"
+  , HorizontalRule
+  , Header 1 ( "images" , [] , [] ) [ Str "Images" ]
+  , Para
+      [ Str "From"
+      , Space
+      , Str "\"Voyage"
+      , Space
+      , Str "dans"
+      , Space
+      , Str "la"
+      , Space
+      , Str "Lune\""
+      , Space
+      , Str "by"
+      , Space
+      , Str "Georges"
+      , Space
+      , Str "Melies"
+      , Space
+      , Str "(1902):"
+      ]
+  , Para
+      [ Image
+          ( "" , [] , [] )
+          [ Str "lalune" ]
+          ( "lalune.jpg" , "Voyage dans la Lune" )
+      ]
+  , Para
+      [ Str "Here"
+      , Space
+      , Str "is"
+      , Space
+      , Str "a"
+      , Space
+      , Str "movie"
+      , Space
+      , Image
+          ( "" , [] , [] ) [ Str "movie" ] ( "movie.jpg" , "" )
+      , Space
+      , Str "icon."
+      ]
+  , HorizontalRule
+  , Header 1 ( "footnotes" , [] , [] ) [ Str "Footnotes" ]
+  , Para
+      [ Str "Here"
+      , Space
+      , Str "is"
+      , Space
+      , Str "a"
+      , Space
+      , Str "footnote"
+      , Space
+      , Str "reference"
+      , Link ( "" , [] , [] ) [ Str "(1)" ] ( "#note_1" , "" )
+      , Str ","
+      , Space
+      , Str "and"
+      , Space
+      , Str "another"
+      , Link
+          ( "" , [] , [] )
+          [ Str "(longnote)" ]
+          ( "#note_longnote" , "" )
+      , Str "."
+      , Space
+      , Str "This"
+      , Space
+      , Str "should"
+      , Space
+      , Emph [ Str "not" ]
+      , Space
+      , Str "be"
+      , Space
+      , Str "a"
+      , Space
+      , Str "footnote"
+      , Space
+      , Str "reference,"
+      , Space
+      , Str "because"
+      , Space
+      , Str "it"
+      , Space
+      , Str "contains"
+      , Space
+      , Str "a"
+      , Space
+      , Str "space^(my"
+      , Space
+      , Str "note)."
+      ]
+  , Para
+      [ Link ( "" , [] , [] ) [ Str "(1)" ] ( "#ref_1" , "" )
+      , Space
+      , Str "Here"
+      , Space
+      , Str "is"
+      , Space
+      , Str "the"
+      , Space
+      , Str "footnote."
+      , Space
+      , Str "It"
+      , Space
+      , Str "can"
+      , Space
+      , Str "go"
+      , Space
+      , Str "anywhere"
+      , Space
+      , Str "in"
+      , Space
+      , Str "the"
+      , Space
+      , Str "document,"
+      , Space
+      , Str "not"
+      , Space
+      , Str "just"
+      , Space
+      , Str "at"
+      , Space
+      , Str "the"
+      , Space
+      , Str "end."
+      ]
+  , Para
+      [ Link
+          ( "" , [] , [] )
+          [ Str "(longnote)" ]
+          ( "#ref_longnote" , "" )
+      , Space
+      , Str "Here's"
+      , Space
+      , Str "the"
+      , Space
+      , Str "other"
+      , Space
+      , Str "note."
+      , Space
+      , Str "This"
+      , Space
+      , Str "one"
+      , Space
+      , Str "contains"
+      , Space
+      , Str "multiple"
+      , Space
+      , Str "blocks."
+      ]
+  , Para
+      [ Str "Caret"
+      , Space
+      , Str "characters"
+      , Space
+      , Str "are"
+      , Space
+      , Str "used"
+      , Space
+      , Str "to"
+      , Space
+      , Str "indicate"
+      , Space
+      , Str "that"
+      , Space
+      , Str "the"
+      , Space
+      , Str "blocks"
+      , Space
+      , Str "all"
+      , Space
+      , Str "belong"
+      , Space
+      , Str "to"
+      , Space
+      , Str "a"
+      , Space
+      , Str "single"
+      , Space
+      , Str "footnote"
+      , Space
+      , Str "(as"
+      , Space
+      , Str "with"
+      , Space
+      , Str "block"
+      , Space
+      , Str "quotes)."
+      ]
+  , CodeBlock ( "" , [] , [] ) "  { <code> }"
+  , Para
+      [ Str "If"
+      , Space
+      , Str "you"
+      , Space
+      , Str "want,"
+      , Space
+      , Str "you"
+      , Space
+      , Str "can"
+      , Space
+      , Str "use"
+      , Space
+      , Str "a"
+      , Space
+      , Str "caret"
+      , Space
+      , Str "at"
+      , Space
+      , Str "the"
+      , Space
+      , Str "beginning"
+      , Space
+      , Str "of"
+      , Space
+      , Str "every"
+      , Space
+      , Str "line,"
+      , Space
+      , Str "as"
+      , Space
+      , Str "with"
+      , Space
+      , Str "blockquotes,"
+      , Space
+      , Str "but"
+      , Space
+      , Str "all"
+      , Space
+      , Str "that"
+      , Space
+      , Str "you"
+      , Space
+      , Str "need"
+      , Space
+      , Str "is"
+      , Space
+      , Str "a"
+      , Space
+      , Str "caret"
+      , Space
+      , Str "at"
+      , Space
+      , Str "the"
+      , Space
+      , Str "beginning"
+      , Space
+      , Str "of"
+      , Space
+      , Str "the"
+      , Space
+      , Str "first"
+      , Space
+      , Str "line"
+      , Space
+      , Str "of"
+      , Space
+      , Str "the"
+      , Space
+      , Str "block"
+      , Space
+      , Str "and"
+      , Space
+      , Str "any"
+      , Space
+      , Str "preceding"
+      , Space
+      , Str "blank"
+      , Space
+      , Str "lines."
+      ]
+  , Para
+      [ Str "text"
+      , Space
+      , Emph [ Str "Leading" , Space , Str "space" ]
+      ]
+  , Para
+      [ Emph [ Str "Trailing" , Space , Str "space" ]
+      , Space
+      , Str "text"
+      ]
+  , Para
+      [ Str "text"
+      , Space
+      , Emph [ Str "Leading" , Space , Str "spaces" ]
+      ]
+  , Para
+      [ Emph [ Str "Trailing" , Space , Str "spaces" ]
+      , Space
+      , Str "text"
+      ]
+  , Header 1 ( "tables" , [] , [] ) [ Str "Tables" ]
+  , Header
+      2
+      ( "tables-with-headers" , [] , [] )
+      [ Str "Tables"
+      , Space
+      , Str "with"
+      , Space
+      , Str "Headers"
+      ]
+  , Table
+      ( "" , [] , [] )
+      (Caption Nothing [])
+      [ ( AlignDefault , ColWidthDefault )
+      , ( AlignDefault , ColWidthDefault )
+      , ( AlignDefault , ColWidthDefault )
+      ]
+      (TableHead
+         ( "" , [] , [] )
+         [ Row
+             ( "" , [] , [] )
+             [ Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "X" ] ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "Y" ] ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "Z" ] ]
+             ]
+         ])
+      [ TableBody
+          ( "" , [] , [] )
+          (RowHeadColumns 0)
+          []
+          [ Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "1" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "2" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "3" ] ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "4" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "5" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "6" ] ]
+              ]
+          ]
+      ]
+      (TableFoot ( "" , [] , [] ) [])
+  , HorizontalRule
+  , Table
+      ( "" , [] , [] )
+      (Caption Nothing [])
+      [ ( AlignDefault , ColWidthDefault )
+      , ( AlignDefault , ColWidthDefault )
+      , ( AlignDefault , ColWidthDefault )
+      ]
+      (TableHead
+         ( "" , [] , [] )
+         [ Row
+             ( "" , [] , [] )
+             [ Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "X" ] ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "Y" ] ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "Z" ] ]
+             ]
+         ])
+      [ TableBody
+          ( "" , [] , [] )
+          (RowHeadColumns 0)
+          []
+          [ Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "1" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "2" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "3" ] ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "4" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "5" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "6" ] ]
+              ]
+          ]
+      ]
+      (TableFoot ( "" , [] , [] ) [])
+  , HorizontalRule
+  , Para [ Str "Row" , Space , Str "headers" ]
+  , Table
+      ( "" , [] , [] )
+      (Caption Nothing [])
+      [ ( AlignDefault , ColWidthDefault )
+      , ( AlignDefault , ColWidthDefault )
+      , ( AlignDefault , ColWidthDefault )
+      ]
+      (TableHead
+         ( "" , [] , [] )
+         [ Row
+             ( "" , [] , [] )
+             [ Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "X" ] ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "Y" ] ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "Z" ] ]
+             ]
+         ])
+      [ TableBody
+          ( "" , [] , [] )
+          (RowHeadColumns 1)
+          []
+          [ Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "1" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "2" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "3" ] ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "4" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "5" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "6" ] ]
+              ]
+          ]
+      ]
+      (TableFoot ( "" , [] , [] ) [])
+  , HorizontalRule
+  , Table
+      ( "" , [] , [] )
+      (Caption Nothing [])
+      [ ( AlignDefault , ColWidthDefault )
+      , ( AlignDefault , ColWidthDefault )
+      , ( AlignDefault , ColWidthDefault )
+      ]
+      (TableHead
+         ( "" , [] , [] )
+         [ Row
+             ( "" , [] , [] )
+             [ Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "X" ] ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "Y" ] ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "Z" ] ]
+             ]
+         ])
+      [ TableBody
+          ( "" , [] , [] )
+          (RowHeadColumns 0)
+          []
+          [ Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "1" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "2" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "3" ] ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 3)
+                  [ Plain [ Str "Details" ] ]
+              ]
+          ]
+      ]
+      (TableFoot
+         ( "" , [] , [] )
+         [ Row
+             ( "" , [] , [] )
+             [ Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "4" ] ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "5" ] ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "6" ] ]
+             ]
+         ])
+  , HorizontalRule
+  , Table
+      ( "" , [] , [] )
+      (Caption Nothing [])
+      [ ( AlignDefault , ColWidthDefault )
+      , ( AlignDefault , ColWidthDefault )
+      , ( AlignDefault , ColWidthDefault )
+      ]
+      (TableHead ( "" , [] , [] ) [])
+      [ TableBody
+          ( "" , [] , [] )
+          (RowHeadColumns 0)
+          [ Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "X" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "Y" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "Z" ] ]
+              ]
+          ]
+          [ Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "1" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "2" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "3" ] ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 3)
+                  [ Plain [ Str "Details" ] ]
+              ]
+          ]
+      ]
+      (TableFoot
+         ( "" , [] , [] )
+         [ Row
+             ( "" , [] , [] )
+             [ Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "4" ] ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "5" ] ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "6" ] ]
+             ]
+         ])
+  , HorizontalRule
+  , Table
+      ( "" , [] , [] )
+      (Caption Nothing [])
+      [ ( AlignDefault , ColWidthDefault )
+      , ( AlignDefault , ColWidthDefault )
+      , ( AlignDefault , ColWidthDefault )
+      ]
+      (TableHead
+         ( "" , [] , [] )
+         [ Row
+             ( "" , [] , [] )
+             [ Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "X" ] ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "Y" ] ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "Z" ] ]
+             ]
+         ])
+      [ TableBody
+          ( "" , [] , [] )
+          (RowHeadColumns 0)
+          [ Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "1" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "2" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "3" ] ]
+              ]
+          ]
+          [ Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "4" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "5" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "6" ] ]
+              ]
+          ]
+      ]
+      (TableFoot ( "" , [] , [] ) [])
+  , HorizontalRule
+  , Table
+      ( "" , [] , [] )
+      (Caption Nothing [])
+      [ ( AlignDefault , ColWidthDefault )
+      , ( AlignDefault , ColWidthDefault )
+      , ( AlignDefault , ColWidthDefault )
+      ]
+      (TableHead ( "" , [] , [] ) [])
+      [ TableBody
+          ( "" , [] , [] )
+          (RowHeadColumns 0)
+          [ Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "X" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "Y" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "Z" ] ]
+              ]
+          ]
+          [ Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "1" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "2" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "3" ] ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "4" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "5" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "6" ] ]
+              ]
+          ]
+      ]
+      (TableFoot ( "" , [] , [] ) [])
+  , HorizontalRule
+  , Table
+      ( "" , [] , [] )
+      (Caption Nothing [])
+      [ ( AlignDefault , ColWidthDefault )
+      , ( AlignDefault , ColWidthDefault )
+      , ( AlignDefault , ColWidthDefault )
+      ]
+      (TableHead ( "" , [] , [] ) [])
+      [ TableBody
+          ( "" , [] , [] )
+          (RowHeadColumns 0)
+          [ Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "X" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "Y" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "Z" ] ]
+              ]
+          ]
+          [ Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "1" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "2" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "3" ] ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "4" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "5" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "6" ] ]
+              ]
+          ]
+      ]
+      (TableFoot ( "" , [] , [] ) [])
+  , HorizontalRule
+  , Table
+      ( "" , [] , [] )
+      (Caption Nothing [])
+      [ ( AlignDefault , ColWidthDefault )
+      , ( AlignDefault , ColWidthDefault )
+      , ( AlignDefault , ColWidthDefault )
+      ]
+      (TableHead
+         ( "" , [] , [] )
+         [ Row
+             ( "" , [] , [] )
+             [ Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "X" ] ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "Y" ] ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "Z" ] ]
+             ]
+         ])
+      [ TableBody
+          ( "" , [] , [] )
+          (RowHeadColumns 0)
+          []
+          [ Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "1" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "2" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "3" ] ]
+              ]
+          ]
+      , TableBody
+          ( "" , [] , [] )
+          (RowHeadColumns 0)
+          []
+          [ Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "4" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "5" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "6" ] ]
+              ]
+          ]
+      ]
+      (TableFoot ( "" , [] , [] ) [])
+  , HorizontalRule
+  , Table
+      ( "" , [] , [] )
+      (Caption Nothing [])
+      [ ( AlignDefault , ColWidthDefault )
+      , ( AlignDefault , ColWidthDefault )
+      , ( AlignDefault , ColWidthDefault )
+      ]
+      (TableHead
+         ( "" , [] , [] )
+         [ Row
+             ( "" , [] , [] )
+             [ Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "X" ] ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "Y" ] ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "Z" ] ]
+             ]
+         ])
+      [ TableBody
+          ( "" , [] , [] )
+          (RowHeadColumns 0)
+          []
+          [ Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "1" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para [ Str "2" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "3" ] ]
+              ]
+          ]
+      , TableBody
+          ( "" , [] , [] )
+          (RowHeadColumns 0)
+          []
+          [ Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "4" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "5" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "6" ] ]
+              ]
+          ]
+      ]
+      (TableFoot ( "" , [] , [] ) [])
+  , Header
+      2
+      ( "tables-without-headers" , [] , [] )
+      [ Str "Tables"
+      , Space
+      , Str "without"
+      , Space
+      , Str "Headers"
+      ]
+  , Table
+      ( "" , [] , [] )
+      (Caption Nothing [])
+      [ ( AlignDefault , ColWidthDefault )
+      , ( AlignDefault , ColWidthDefault )
+      , ( AlignDefault , ColWidthDefault )
+      ]
+      (TableHead ( "" , [] , [] ) [])
+      [ TableBody
+          ( "" , [] , [] )
+          (RowHeadColumns 0)
+          []
+          [ Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "1" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "2" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "3" ] ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "4" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "5" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "6" ] ]
+              ]
+          ]
+      ]
+      (TableFoot ( "" , [] , [] ) [])
+  , HorizontalRule
+  , Para
+      [ Str "tbody" , Space , Str "tags" , Space , Str "omitted" ]
+  , Table
+      ( "" , [] , [] )
+      (Caption Nothing [])
+      [ ( AlignDefault , ColWidthDefault )
+      , ( AlignDefault , ColWidthDefault )
+      , ( AlignDefault , ColWidthDefault )
+      ]
+      (TableHead ( "" , [] , [] ) [])
+      [ TableBody
+          ( "" , [] , [] )
+          (RowHeadColumns 0)
+          []
+          [ Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "1" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "2" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "3" ] ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "4" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "5" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "6" ] ]
+              ]
+          ]
+      ]
+      (TableFoot ( "" , [] , [] ) [])
+  , HorizontalRule
+  , Para [ Str "empty" , Space , Str "head" ]
+  , Table
+      ( "" , [] , [] )
+      (Caption Nothing [])
+      [ ( AlignDefault , ColWidthDefault )
+      , ( AlignDefault , ColWidthDefault )
+      , ( AlignDefault , ColWidthDefault )
+      ]
+      (TableHead ( "" , [] , [] ) [])
+      [ TableBody
+          ( "" , [] , [] )
+          (RowHeadColumns 0)
+          []
+          [ Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "1" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "2" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "3" ] ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "4" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "5" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "6" ] ]
+              ]
+          ]
+      ]
+      (TableFoot ( "" , [] , [] ) [])
+  , HorizontalRule
+  , Para
+      [ Str "explicit"
+      , Space
+      , Str "body"
+      , Space
+      , Str "and"
+      , Space
+      , Str "foot"
+      ]
+  , Table
+      ( "" , [] , [] )
+      (Caption Nothing [])
+      [ ( AlignDefault , ColWidthDefault )
+      , ( AlignDefault , ColWidthDefault )
+      , ( AlignDefault , ColWidthDefault )
+      ]
+      (TableHead ( "" , [] , [] ) [])
+      [ TableBody
+          ( "" , [] , [] )
+          (RowHeadColumns 0)
+          []
+          [ Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "1" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "2" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "3" ] ]
+              ]
+          ]
+      ]
+      (TableFoot
+         ( "" , [] , [] )
+         [ Row
+             ( "" , [] , [] )
+             [ Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "4" ] ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "5" ] ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "6" ] ]
+             ]
+         ])
+  , Header
+      2
+      ( "colspans-and-rowspans" , [] , [] )
+      [ Str "Colspans"
+      , Space
+      , Str "and"
+      , Space
+      , Str "Rowspans"
+      ]
+  , Table
+      ( "" , [] , [] )
+      (Caption Nothing [])
+      [ ( AlignDefault , ColWidthDefault )
+      , ( AlignDefault , ColWidthDefault )
+      , ( AlignDefault , ColWidthDefault )
+      ]
+      (TableHead ( "" , [] , [] ) [])
+      [ TableBody
+          ( "" , [] , [] )
+          (RowHeadColumns 0)
+          []
+          [ Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 2)
+                  [ Plain
+                      [ Str "1" , Space , Str "and" , Space , Str "2" ]
+                  ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "3" ] ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 3)
+                  [ Plain
+                      [ Str "4,"
+                      , Space
+                      , Str "5,"
+                      , Space
+                      , Str "and"
+                      , Space
+                      , Str "6"
+                      ]
+                  ]
+              ]
+          ]
+      ]
+      (TableFoot ( "" , [] , [] ) [])
+  , HorizontalRule
+  , Table
+      ( "" , [] , [] )
+      (Caption Nothing [])
+      [ ( AlignDefault , ColWidthDefault )
+      , ( AlignDefault , ColWidthDefault )
+      , ( AlignDefault , ColWidthDefault )
+      ]
+      (TableHead
+         ( "" , [] , [] )
+         [ Row
+             ( "" , [] , [] )
+             [ Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 3)
+                 [ Plain [ Str "Numbers" ] ]
+             ]
+         ])
+      [ TableBody
+          ( "" , [] , [] )
+          (RowHeadColumns 0)
+          []
+          [ Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 2)
+                  (ColSpan 1)
+                  [ Plain
+                      [ Str "1" , Space , Str "and" , Space , Str "4" ]
+                  ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "2" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "3" ] ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "5" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "6" ] ]
+              ]
+          ]
+      ]
+      (TableFoot ( "" , [] , [] ) [])
+  , Header 2 ( "attributes" , [] , [] ) [ Str "Attributes" ]
+  , Table
+      ( "attrib-test-table" , [] , [] )
+      (Caption Nothing [])
+      [ ( AlignDefault , ColWidthDefault )
+      , ( AlignDefault , ColWidthDefault )
+      , ( AlignDefault , ColWidthDefault )
+      ]
+      (TableHead
+         ( "" , [ "table-head" ] , [] )
+         [ Row
+             ( "" , [ "table-head-row" ] , [] )
+             [ Cell
+                 ( "" , [] , [ ( "abbr" , "x" ) ] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 3)
+                 [ Plain [ Str "Cat" , Space , Str "X" ] ]
+             ]
+         ])
+      [ TableBody
+          ( "" , [ "main" ] , [ ( "part" , "body" ) ] )
+          (RowHeadColumns 0)
+          []
+          [ Row
+              ( "" , [] , [ ( "part" , "row" ) ] )
+              [ Cell
+                  ( "" , [] , [ ( "part" , "cell" ) ] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "1" ] ]
+              , Cell
+                  ( "" , [] , [ ( "valign" , "bottom" ) ] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "2" ] ]
+              , Cell
+                  ( "" , [] , [ ( "style" , "color: #151950" ) ] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "3" ] ]
+              ]
+          ]
+      ]
+      (TableFoot
+         ( "" , [ "summary" ] , [] )
+         [ Row
+             ( "" , [] , [ ( "bgcolor" , "#ccc" ) ] )
+             [ Cell
+                 ( "" , [] , [ ( "square" , "true" ) ] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "4" ] ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "5" ] ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "6" ] ]
+             ]
+         ])
+  , Header
+      2
+      ( "tag-omission" , [] , [] )
+      [ Str "Tag" , Space , Str "omission" ]
+  , Para
+      [ Str "thead,"
+      , Space
+      , Str "tbody,"
+      , Space
+      , Str "and"
+      , Space
+      , Str "tfoot"
+      ]
+  , Table
+      ( "" , [] , [] )
+      (Caption Nothing [])
+      [ ( AlignDefault , ColWidthDefault )
+      , ( AlignDefault , ColWidthDefault )
+      , ( AlignDefault , ColWidthDefault )
+      ]
+      (TableHead
+         ( "" , [] , [] )
+         [ Row
+             ( "" , [] , [] )
+             [ Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "X" ] ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "Y" ] ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "Z" ] ]
+             ]
+         ])
+      [ TableBody
+          ( "" , [] , [] )
+          (RowHeadColumns 0)
+          []
+          [ Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "1" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "2" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "3" ] ]
+              ]
+          ]
+      ]
+      (TableFoot
+         ( "" , [] , [] )
+         [ Row
+             ( "" , [] , [] )
+             [ Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "4" ] ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "5" ] ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "6" ] ]
+             ]
+         ])
+  , Header
+      2
+      ( "empty-tables" , [] , [] )
+      [ Str "Empty" , Space , Str "Tables" ]
+  , Para
+      [ Str "This"
+      , Space
+      , Str "section"
+      , Space
+      , Str "should"
+      , Space
+      , Str "be"
+      , Space
+      , Str "empty."
+      ]
+  ]
diff --git a/test/ipynb/mime.ipynb b/test/ipynb/mime.ipynb
new file mode 100644
--- /dev/null
+++ b/test/ipynb/mime.ipynb
@@ -0,0 +1,187 @@
+{
+ "cells": [
+  {
+   "cell_type": "code",
+   "execution_count": 1,
+   "id": "0ad1fbe7-107b-4668-ae4d-8ce4ae9a4400",
+   "metadata": {},
+   "outputs": [],
+   "source": [
+    "from __future__ import annotations\n",
+    "\n",
+    "from dataclasses import dataclass"
+   ]
+  },
+  {
+   "cell_type": "code",
+   "execution_count": 2,
+   "id": "c2d3a9f4-dfdb-4ced-bbcd-3dfd1780af80",
+   "metadata": {},
+   "outputs": [
+    {
+     "name": "stdout",
+     "output_type": "stream",
+     "text": [
+      "7.29.0\n"
+     ]
+    }
+   ],
+   "source": [
+    "import IPython\n",
+    "\n",
+    "print(IPython.__version__)"
+   ]
+  },
+  {
+   "cell_type": "markdown",
+   "id": "21e7a4a1-0cf8-48cc-823c-dca698ae6853",
+   "metadata": {},
+   "source": [
+    "Supported IPython display formatters:"
+   ]
+  },
+  {
+   "cell_type": "code",
+   "execution_count": 3,
+   "id": "053cdbc4-b157-4e3e-9c86-8f374770d006",
+   "metadata": {},
+   "outputs": [
+    {
+     "name": "stdout",
+     "output_type": "stream",
+     "text": [
+      "text/plain\n",
+      "text/html\n",
+      "text/markdown\n",
+      "image/svg+xml\n",
+      "image/png\n",
+      "application/pdf\n",
+      "image/jpeg\n",
+      "text/latex\n",
+      "application/json\n",
+      "application/javascript\n"
+     ]
+    }
+   ],
+   "source": [
+    "ip = get_ipython()\n",
+    "for mime in ip.display_formatter.formatters:\n",
+    "    print(mime)"
+   ]
+  },
+  {
+   "cell_type": "markdown",
+   "id": "d79b063d-ce81-497b-a0ea-5b2e2972e845",
+   "metadata": {},
+   "source": [
+    "Let's write a simple class that will output different mime:"
+   ]
+  },
+  {
+   "cell_type": "code",
+   "execution_count": 4,
+   "id": "c847636c-1c45-432e-9d8d-7310dd7f5637",
+   "metadata": {},
+   "outputs": [],
+   "source": [
+    "@dataclass\n",
+    "class Mime:\n",
+    "    math: str\n",
+    "\n",
+    "    def _repr_mimebundle_(\n",
+    "        self,\n",
+    "        include: Container[str] | None = None,\n",
+    "        exclude: Container[str] | None = None,\n",
+    "        **kwargs,\n",
+    "    ) -> dict[str, str]:\n",
+    "        string = self.math\n",
+    "        data = {\n",
+    "            \"text/plain\": string,\n",
+    "            \"text/html\": (latex := f\"\\\\[{string}\\\\]\"),\n",
+    "            \"text/markdown\": f\"$${string}$$\",\n",
+    "            # \"image/svg+xml\":,\n",
+    "            # \"image/png\":,\n",
+    "            # \"application/pdf\":,\n",
+    "            # \"image/jpeg\":,\n",
+    "            \"text/latex\": latex,\n",
+    "            # \"application/json\":,\n",
+    "            # \"application/javascript\":,\n",
+    "        }\n",
+    "        if include:\n",
+    "            data = {k: v for k, v in data.items() if k in include}\n",
+    "        if exclude:\n",
+    "            data = {k: v for k, v in data.items() if k not in exclude}\n",
+    "        return data"
+   ]
+  },
+  {
+   "cell_type": "code",
+   "execution_count": 5,
+   "id": "4fa54f22-0c3a-4809-91f7-ea7101ff1907",
+   "metadata": {},
+   "outputs": [],
+   "source": [
+    "mime = Mime(\"E = mc^2\")"
+   ]
+  },
+  {
+   "cell_type": "code",
+   "execution_count": 6,
+   "id": "c419e6a6-240c-4af0-a244-5f1526705c30",
+   "metadata": {},
+   "outputs": [
+    {
+     "data": {
+      "text/html": [
+       "\\[E = mc^2\\]"
+      ],
+      "text/latex": [
+       "\\[E = mc^2\\]"
+      ],
+      "text/markdown": [
+       "$$E = mc^2$$"
+      ],
+      "text/plain": [
+       "E = mc^2"
+      ]
+     },
+     "execution_count": 6,
+     "metadata": {},
+     "output_type": "execute_result"
+    }
+   ],
+   "source": [
+    "mime"
+   ]
+  },
+  {
+   "cell_type": "markdown",
+   "id": "bf140b8e-16ac-4670-9778-f1c1d9486f9d",
+   "metadata": {},
+   "source": [
+    "Note that #7561 made ipynb reader aware of this, and #7563 made ipynb writer aware of this."
+   ]
+  }
+ ],
+ "metadata": {
+  "kernelspec": {
+   "display_name": "Python 3 (ipykernel)",
+   "language": "python",
+   "name": "python3"
+  },
+  "language_info": {
+   "codemirror_mode": {
+    "name": "ipython",
+    "version": 3
+   },
+   "file_extension": ".py",
+   "mimetype": "text/x-python",
+   "name": "python",
+   "nbconvert_exporter": "python",
+   "pygments_lexer": "ipython3",
+   "version": "3.9.6"
+  }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 5
+}
diff --git a/test/ipynb/mime.native b/test/ipynb/mime.native
new file mode 100644
--- /dev/null
+++ b/test/ipynb/mime.native
@@ -0,0 +1,154 @@
+[ Div
+    ( "0ad1fbe7-107b-4668-ae4d-8ce4ae9a4400"
+    , [ "cell" , "code" ]
+    , [ ( "execution_count" , "1" ) ]
+    )
+    [ CodeBlock
+        ( "" , [ "python" ] , [] )
+        "from __future__ import annotations\n\nfrom dataclasses import dataclass"
+    ]
+, Div
+    ( "c2d3a9f4-dfdb-4ced-bbcd-3dfd1780af80"
+    , [ "cell" , "code" ]
+    , [ ( "execution_count" , "2" ) ]
+    )
+    [ CodeBlock
+        ( "" , [ "python" ] , [] )
+        "import IPython\n\nprint(IPython.__version__)"
+    , Div
+        ( "" , [ "output" , "stream" , "stdout" ] , [] )
+        [ CodeBlock ( "" , [] , [] ) "7.29.0\n" ]
+    ]
+, Div
+    ( "21e7a4a1-0cf8-48cc-823c-dca698ae6853"
+    , [ "cell" , "markdown" ]
+    , []
+    )
+    [ Para
+        [ Str "Supported"
+        , Space
+        , Str "IPython"
+        , Space
+        , Str "display"
+        , Space
+        , Str "formatters:"
+        ]
+    ]
+, Div
+    ( "053cdbc4-b157-4e3e-9c86-8f374770d006"
+    , [ "cell" , "code" ]
+    , [ ( "execution_count" , "3" ) ]
+    )
+    [ CodeBlock
+        ( "" , [ "python" ] , [] )
+        "ip = get_ipython()\nfor mime in ip.display_formatter.formatters:\n    print(mime)"
+    , Div
+        ( "" , [ "output" , "stream" , "stdout" ] , [] )
+        [ CodeBlock
+            ( "" , [] , [] )
+            "text/plain\ntext/html\ntext/markdown\nimage/svg+xml\nimage/png\napplication/pdf\nimage/jpeg\ntext/latex\napplication/json\napplication/javascript\n"
+        ]
+    ]
+, Div
+    ( "d79b063d-ce81-497b-a0ea-5b2e2972e845"
+    , [ "cell" , "markdown" ]
+    , []
+    )
+    [ Para
+        [ Str "Let's"
+        , Space
+        , Str "write"
+        , Space
+        , Str "a"
+        , Space
+        , Str "simple"
+        , Space
+        , Str "class"
+        , Space
+        , Str "that"
+        , Space
+        , Str "will"
+        , Space
+        , Str "output"
+        , Space
+        , Str "different"
+        , Space
+        , Str "mime:"
+        ]
+    ]
+, Div
+    ( "c847636c-1c45-432e-9d8d-7310dd7f5637"
+    , [ "cell" , "code" ]
+    , [ ( "execution_count" , "4" ) ]
+    )
+    [ CodeBlock
+        ( "" , [ "python" ] , [] )
+        "@dataclass\nclass Mime:\n    math: str\n\n    def _repr_mimebundle_(\n        self,\n        include: Container[str] | None = None,\n        exclude: Container[str] | None = None,\n        **kwargs,\n    ) -> dict[str, str]:\n        string = self.math\n        data = {\n            \"text/plain\": string,\n            \"text/html\": (latex := f\"\\\\[{string}\\\\]\"),\n            \"text/markdown\": f\"$${string}$$\",\n            # \"image/svg+xml\":,\n            # \"image/png\":,\n            # \"application/pdf\":,\n            # \"image/jpeg\":,\n            \"text/latex\": latex,\n            # \"application/json\":,\n            # \"application/javascript\":,\n        }\n        if include:\n            data = {k: v for k, v in data.items() if k in include}\n        if exclude:\n            data = {k: v for k, v in data.items() if k not in exclude}\n        return data"
+    ]
+, Div
+    ( "4fa54f22-0c3a-4809-91f7-ea7101ff1907"
+    , [ "cell" , "code" ]
+    , [ ( "execution_count" , "5" ) ]
+    )
+    [ CodeBlock
+        ( "" , [ "python" ] , [] ) "mime = Mime(\"E = mc^2\")"
+    ]
+, Div
+    ( "c419e6a6-240c-4af0-a244-5f1526705c30"
+    , [ "cell" , "code" ]
+    , [ ( "execution_count" , "6" ) ]
+    )
+    [ CodeBlock ( "" , [ "python" ] , [] ) "mime"
+    , Div
+        ( ""
+        , [ "output" , "execute_result" ]
+        , [ ( "execution_count" , "6" ) ]
+        )
+        [ RawBlock (Format "html") "\\[E = mc^2\\]"
+        , RawBlock (Format "latex") "\\[E = mc^2\\]"
+        , RawBlock (Format "markdown") "$$E = mc^2$$"
+        , CodeBlock ( "" , [] , [] ) "E = mc^2"
+        ]
+    ]
+, Div
+    ( "bf140b8e-16ac-4670-9778-f1c1d9486f9d"
+    , [ "cell" , "markdown" ]
+    , []
+    )
+    [ Para
+        [ Str "Note"
+        , Space
+        , Str "that"
+        , Space
+        , Str "#7561"
+        , Space
+        , Str "made"
+        , Space
+        , Str "ipynb"
+        , Space
+        , Str "reader"
+        , Space
+        , Str "aware"
+        , Space
+        , Str "of"
+        , Space
+        , Str "this,"
+        , Space
+        , Str "and"
+        , Space
+        , Str "#7563"
+        , Space
+        , Str "made"
+        , Space
+        , Str "ipynb"
+        , Space
+        , Str "writer"
+        , Space
+        , Str "aware"
+        , Space
+        , Str "of"
+        , Space
+        , Str "this."
+        ]
+    ]
+]
diff --git a/test/ipynb/mime.out.ipynb b/test/ipynb/mime.out.ipynb
new file mode 100644
--- /dev/null
+++ b/test/ipynb/mime.out.ipynb
@@ -0,0 +1,169 @@
+{
+ "cells": [
+  {
+   "cell_type": "code",
+   "execution_count": 1,
+   "metadata": {},
+   "outputs": [],
+   "source": [
+    "from __future__ import annotations\n",
+    "\n",
+    "from dataclasses import dataclass"
+   ],
+   "id": "0ad1fbe7-107b-4668-ae4d-8ce4ae9a4400"
+  },
+  {
+   "cell_type": "code",
+   "execution_count": 2,
+   "metadata": {},
+   "outputs": [
+    {
+     "output_type": "stream",
+     "name": "stdout",
+     "text": [
+      "7.29.0\n"
+     ]
+    }
+   ],
+   "source": [
+    "import IPython\n",
+    "\n",
+    "print(IPython.__version__)"
+   ],
+   "id": "c2d3a9f4-dfdb-4ced-bbcd-3dfd1780af80"
+  },
+  {
+   "cell_type": "markdown",
+   "metadata": {},
+   "source": [
+    "Supported IPython display formatters:"
+   ],
+   "id": "21e7a4a1-0cf8-48cc-823c-dca698ae6853"
+  },
+  {
+   "cell_type": "code",
+   "execution_count": 3,
+   "metadata": {},
+   "outputs": [
+    {
+     "output_type": "stream",
+     "name": "stdout",
+     "text": [
+      "text/plain\n",
+      "text/html\n",
+      "text/markdown\n",
+      "image/svg+xml\n",
+      "image/png\n",
+      "application/pdf\n",
+      "image/jpeg\n",
+      "text/latex\n",
+      "application/json\n",
+      "application/javascript\n"
+     ]
+    }
+   ],
+   "source": [
+    "ip = get_ipython()\n",
+    "for mime in ip.display_formatter.formatters:\n",
+    "    print(mime)"
+   ],
+   "id": "053cdbc4-b157-4e3e-9c86-8f374770d006"
+  },
+  {
+   "cell_type": "markdown",
+   "metadata": {},
+   "source": [
+    "Let's write a simple class that will output different mime:"
+   ],
+   "id": "d79b063d-ce81-497b-a0ea-5b2e2972e845"
+  },
+  {
+   "cell_type": "code",
+   "execution_count": 4,
+   "metadata": {},
+   "outputs": [],
+   "source": [
+    "@dataclass\n",
+    "class Mime:\n",
+    "    math: str\n",
+    "\n",
+    "    def _repr_mimebundle_(\n",
+    "        self,\n",
+    "        include: Container[str] | None = None,\n",
+    "        exclude: Container[str] | None = None,\n",
+    "        **kwargs,\n",
+    "    ) -> dict[str, str]:\n",
+    "        string = self.math\n",
+    "        data = {\n",
+    "            \"text/plain\": string,\n",
+    "            \"text/html\": (latex := f\"\\\\[{string}\\\\]\"),\n",
+    "            \"text/markdown\": f\"$${string}$$\",\n",
+    "            # \"image/svg+xml\":,\n",
+    "            # \"image/png\":,\n",
+    "            # \"application/pdf\":,\n",
+    "            # \"image/jpeg\":,\n",
+    "            \"text/latex\": latex,\n",
+    "            # \"application/json\":,\n",
+    "            # \"application/javascript\":,\n",
+    "        }\n",
+    "        if include:\n",
+    "            data = {k: v for k, v in data.items() if k in include}\n",
+    "        if exclude:\n",
+    "            data = {k: v for k, v in data.items() if k not in exclude}\n",
+    "        return data"
+   ],
+   "id": "c847636c-1c45-432e-9d8d-7310dd7f5637"
+  },
+  {
+   "cell_type": "code",
+   "execution_count": 5,
+   "metadata": {},
+   "outputs": [],
+   "source": [
+    "mime = Mime(\"E = mc^2\")"
+   ],
+   "id": "4fa54f22-0c3a-4809-91f7-ea7101ff1907"
+  },
+  {
+   "cell_type": "code",
+   "execution_count": 6,
+   "metadata": {},
+   "outputs": [
+    {
+     "output_type": "execute_result",
+     "execution_count": 6,
+     "metadata": {},
+     "data": {
+      "text/html": [
+       "\\[E = mc^2\\]"
+      ],
+      "text/latex": [
+       "\\[E = mc^2\\]"
+      ],
+      "text/markdown": [
+       "$$E = mc^2$$"
+      ],
+      "text/plain": [
+       "E = mc^2"
+      ]
+     }
+    }
+   ],
+   "source": [
+    "mime"
+   ],
+   "id": "c419e6a6-240c-4af0-a244-5f1526705c30"
+  },
+  {
+   "cell_type": "markdown",
+   "metadata": {},
+   "source": [
+    "Note that #7561 made ipynb reader aware of this, and #7563 made ipynb writer aware of this."
+   ],
+   "id": "bf140b8e-16ac-4670-9778-f1c1d9486f9d"
+  }
+ ],
+ "nbformat": 4,
+ "nbformat_minor": 5,
+ "metadata": {}
+}
diff --git a/test/ipynb/rank.ipynb b/test/ipynb/rank.ipynb
new file mode 100644
--- /dev/null
+++ b/test/ipynb/rank.ipynb
@@ -0,0 +1,60 @@
+{
+ "cells": [
+  {
+   "cell_type": "code",
+   "execution_count": 1,
+   "id": "5cf8f54d-bf3c-4db2-996d-22662a86ad43",
+   "metadata": {},
+   "outputs": [],
+   "source": [
+    "import matplotlib.pyplot as plt"
+   ]
+  },
+  {
+   "cell_type": "code",
+   "execution_count": 2,
+   "id": "a0228622-9ff8-4392-9ddd-f70a90f0e106",
+   "metadata": {},
+   "outputs": [
+    {
+     "data": {
+      "text/html": "<p><em>you should see this when converting from ipynb to html instead of the image below.</em></p>",
+      "image/png": "iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAYAAACp8Z5+AAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjUuMCwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy8/fFQqAAAACXBIWXMAAACdAAAAnQGPcuduAAAASUlEQVR4nGNkYGBgc1HM+/lfkI/hqQ0XAwsDAwPDzSphBi6h/wwlahsgAiJCHxkkBL4zWLA8YGBkYGBgZGBg4GRgYPjDwMDABADgfgxL+wQIRAAAAABJRU5ErkJggg==\n",
+      "text/plain": [
+       "<Figure size 4x4 with 1 Axes>"
+      ]
+     },
+     "metadata": {
+      "needs_background": "light"
+     },
+     "output_type": "display_data"
+    }
+   ],
+   "source": [
+    "fig, ax = plt.subplots(figsize=(1, 1), dpi=4)\n",
+    "ax.imshow([[0, 1], [2, 3]]);"
+   ]
+  }
+ ],
+ "metadata": {
+  "kernelspec": {
+   "display_name": "Python 3 (ipykernel)",
+   "language": "python",
+   "name": "python3"
+  },
+  "language_info": {
+   "codemirror_mode": {
+    "name": "ipython",
+    "version": 3
+   },
+   "file_extension": ".py",
+   "mimetype": "text/x-python",
+   "name": "python",
+   "nbconvert_exporter": "python",
+   "pygments_lexer": "ipython3",
+   "version": "3.10.0"
+  }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 5
+}
diff --git a/test/ipynb/rank.out.html b/test/ipynb/rank.out.html
new file mode 100644
--- /dev/null
+++ b/test/ipynb/rank.out.html
@@ -0,0 +1,14 @@
+<div id="5cf8f54d-bf3c-4db2-996d-22662a86ad43" class="cell code"
+data-execution_count="1">
+<div class="sourceCode" id="cb1"><pre
+class="sourceCode python"><code class="sourceCode python"><span id="cb1-1"><a href="#cb1-1" aria-hidden="true" tabindex="-1"></a><span class="im">import</span> matplotlib.pyplot <span class="im">as</span> plt</span></code></pre></div>
+</div>
+<div id="a0228622-9ff8-4392-9ddd-f70a90f0e106" class="cell code"
+data-execution_count="2">
+<div class="sourceCode" id="cb2"><pre
+class="sourceCode python"><code class="sourceCode python"><span id="cb2-1"><a href="#cb2-1" aria-hidden="true" tabindex="-1"></a>fig, ax <span class="op">=</span> plt.subplots(figsize<span class="op">=</span>(<span class="dv">1</span>, <span class="dv">1</span>), dpi<span class="op">=</span><span class="dv">4</span>)</span>
+<span id="cb2-2"><a href="#cb2-2" aria-hidden="true" tabindex="-1"></a>ax.imshow([[<span class="dv">0</span>, <span class="dv">1</span>], [<span class="dv">2</span>, <span class="dv">3</span>]])<span class="op">;</span></span></code></pre></div>
+<div class="output display_data">
+<p><em>you should see this when converting from ipynb to html instead of the image below.</em></p>
+</div>
+</div>
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,15 @@
+Pandoc (Meta {unMeta = fromList [("jupyter",MetaMap (fromList [("nbformat",MetaInlines [Str "4"]),("nbformat_minor",MetaInlines [Str "5"])]))]})
+[Div ("uid1",["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 ("uid2",["cell","code"],[])
+ [CodeBlock ("",["python"],[]) "print(\"hello\")"]
+,Div ("uid3",["cell","markdown"],[])
+ [Header 2 ("pyout",[],[]) [Str "Pyout"]]
+,Div ("uid4",["cell","code"],[("execution_count","2")])
+ [CodeBlock ("",["python"],[]) "from IPython.display import HTML\nHTML(\"\"\"\n<script>\nconsole.log(\"hello\");\n</script>\n<b>HTML</b>\n\"\"\")"
+ ,Div ("uid5",["output","execute_result"],[("execution_count","2")])
+  [RawBlock (Format "html") "<script>\nconsole.log(\"hello\");\n</script>\n<b>HTML</b>\nhello"]]
+,Div ("uid6",["cell","markdown"],[("tags","[\"foo\",\"bar\"]")])
+ [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,91 @@
+{
+ "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."
+   ],
+   "id": "uid1"
+  },
+  {
+   "cell_type": "code",
+   "execution_count": null,
+   "metadata": {},
+   "outputs": [],
+   "source": [
+    "print(\"hello\")"
+   ],
+   "id": "uid2"
+  },
+  {
+   "cell_type": "markdown",
+   "metadata": {},
+   "source": [
+    "Pyout\n",
+    "-----"
+   ],
+   "id": "uid3"
+  },
+  {
+   "cell_type": "code",
+   "execution_count": 2,
+   "metadata": {},
+   "outputs": [
+    {
+     "output_type": "execute_result",
+     "execution_count": 2,
+     "metadata": {},
+     "data": {
+      "text/html": [
+       "<script>\n",
+       "console.log(\"hello\");\n",
+       "</script>\n",
+       "<b>HTML</b>\n",
+       "hello"
+      ]
+     }
+    }
+   ],
+   "source": [
+    "from IPython.display import HTML\n",
+    "HTML(\"\"\"\n",
+    "<script>\n",
+    "console.log(\"hello\");\n",
+    "</script>\n",
+    "<b>HTML</b>\n",
+    "\"\"\")"
+   ],
+   "id": "uid4"
+  },
+  {
+   "cell_type": "markdown",
+   "metadata": {
+    "tags": [
+     "foo",
+     "bar"
+    ]
+   },
+   "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": "/9j/4AAQSkZJRgABAQEAeAB4AAD/2wBDAAYEBQYFBAYGBQYHBwYIChAKCgkJChQODwwQFxQYGBcU\nFhYaHSUfGhsjHBYWICwgIyYnKSopGR8tMC0oMCUoKSj/2wBDAQcHBwoIChMKChMoGhYaKCgoKCgo\nKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCj/wAARCAD6APoDAREA\nAhEBAxEB/8QAHAAAAAcBAQAAAAAAAAAAAAAAAQIDBAUGBwAI/8QAPhAAAgEDAwIEBAQFAgUFAAMA\nAQIDAAQRBRIhBjETIkFRB2FxgRQykaEjQlKxwRXwFjNictEIJEPh8SZTgv/EABcBAQEBAQAAAAAA\nAAAAAAAAAAABAgT/xAAbEQEBAQEAAwEAAAAAAAAAAAAAARECEiExQf/aAAwDAQACEQMRAD8A2t0Y\noQpwT2qVzMV+N3UHgrDY2eoM0y58VEbgfp9K1yMRmnuJ5h40jyYHGSeKrWE8u2QAApOMdqGCsmT8\nh70TAJwMAZx249aKBy4c9vTNUC0zDCgmmmG7Ockjkj1PrUTAjcy5XP0ouCgHae4IomOJHhgIc55P\nHY0Uk5IXLMcUBQ27n96JYO2MYLebHtRBA7BcMx29sdxQJqwZRtIP+BQKpjHHc+xzigNGoAO/k+nP\nAoAYlee5oBiGeWySO9AJCgY5PHagFCADzj2GaA2N2TkjA/U0HMwbPPeiyBLDfkkj04FCl1cBMgn6\nURwYFGySR6D2oAeQDAxnHGKAhU4IbGc+tFwnwDj9aK7f8v2oNu+IHxNvJdXmt9EmKWSqArA/mPvx\nUxMZNe3Ml1dvNcMzSSEsxPOferJhht/OWyAPc0UfdgDcuM8n50AMCykZFARsngcY/egTcbjnJz9O\n9AB2kZGSQOcUCX8x83bntQCMruJ4B7D1oCyOGzxtJ9M80CAdg5UjFE0aFJrghLeNpHY4IRdx/QUN\nWCw6D6q1EZttEvirHAZ4ig/U4qw1b9H+CHVN3Mq6hJaWMJ5ZjJ4hA/7R3P3q3ET+pf8Ap/lWNm03\nXkkkA8qTW+3PHupP9qxopV78G+s7VSV0+OcAn/kzqSfscVvIKzqPTWu6XKE1LSL+Bhz5oDg/cd6l\nEZzGwLrtPqrA8frUCJfcw9gfegUjZsEAffNADyHt78UAjCjzDJxRcO5Pw3gwCGOVJQp8ZncMGOeN\noxwMY96GCbQffFFcUXKjDDt2NEo+N3yyM5z3okKuqJgIzONoJyuMGi4QfGcqSfXBoYHJx659qKIR\nnnsfUGgJn/poJYoTIGLY+eDzQFlQK2G/KCTmgbspfO0qce/agPGcR7nHf9vnQFfBPlOc88Gg7uuc\nc/M0Bd208YJJweKAYrea4kKQICRGW5IUYUZJ570DYqcknt3FE0VuVyDzj1oamOlulda6puvC0a0e\nZVIWSbtGn1Y1NNbX0x8ENH0qL8X1NdtqDoNxiQbIh8u+WpqL70Tc6fcxypouiRadbW8hhLFFXcB7\nEdz+tNFvEZxkmmgShbA9PlUA+Hgg/wBqDgmBkd6ArJuJBGR7VdEdqWgaVqMfh6hp9pcLj/5Ig2Ka\nKJrvwW6S1EFoLaWwmPIe2fAz81ORTRm3UfwI1mzBbRL+K/ReyS/w3x/b+1Wexmev9O6xoE2zWdOu\nbUDszr5T9G7H9auCJj2n3PPrUXTlGBB2kYx96GlQMjJJHuRRXBgDgk8DtRKH8w4OfYA0SUlIMsFX\nJ4oujHH8ufnRRGOSNoJNAeFC77F2jPucfvQFEqgY3nj/AKaCUY58wwq54AoCzOmVMke9QeRnGR7Z\noEIF7pnaTk49KDpSSwQntQJsGKjgggZ9uDQc4OOe1Am2UCkHOR7dqA8t/cSW8MEkrGGEsUTPCk4z\nj9KJT3pzQtS6m1aPT9Jh8SVxlmJwqL/UfYURuuhfArR7f8NLrF1cXciKDJCrbI2b7c4+9NGtaRpt\nrpdqltYW0VtAn5Y41wBUodvGjqUdQyn0YZqAIreOBFSFFRF7BQAKA1xcRwKplcJuOBn1NAR7y2ik\nWMzoZnGVQHJNAuQcD3oBKkD2FBy8jnvQFxnjjmg4rxwKBMqCBtPNA3vbCC+tngvYo54HGGSRQQR9\nDV0Y91n8DNOvFkuOmZmsrk5PgSNuiY98D1X+1XRhWu6DqWgX72er2j2069t/ZvmD2IoGG7jbnj1F\nFlB224PB+VClN4DYJHyAojmPGCck8cetCAxgjPp6UaAGKtx6+9ATAXO7nFBw8HHLN+goJhBuj2Fe\nAcnmgNazW8U0vjweODGyqpYrsYjytx3x3oGa5LEEjH9XvQGlgmjjMmQq4HBPfPYgevagG5nhe3tk\nFuInQHxJQTmQntn0wKBKTlAeDx60DSY+U9zn+mgsnQvROr9Y3W2xi8KxV8SXUnCrjvj1Y/IUR6c6\nA6H03o6wMVgrSXMoBmuX/NIf8Djt/eiLfjJwO9ZBiOfmKDhktzQAzYBLZ8oyaDF+rOptVv8AUjNZ\nL4tjA/lT+kr3wvqTQX/pi3Y+DqFxKXurmFWAaPaVzg4I/b0oHlxqV7penRTXFu93dPLsESYB2k8n\n7CgnradLq1WaIOFI/K42sPkRQCg3Kcd6Dgp3d6AdrGg5VxnjmgKWB8uQGxnFAUgKuSefSghuqNC0\njXbAWGtxQyJKdsYc4YMf6T6GtDzR8S/hnqfSUz3NvuvNILYSZR5o+ezj/Pb6UGfLzyD/AJoFFySQ\nVBHpQDJ5kGByPahAbWxn5+po0OF3D+XPtQJsNwOe+aAuygmMkebgHnHFALHYpJwSeGz2oGpOJWAI\n49BQEZlYAHkg4oARVOMvtBIJJ7AUAX6xxSOsUgmjViFcKRuHviiVfvhT8NZuqpk1LVFeHRkPlHZp\nznsP+n50qPS+mWVppdnFa2cEcFtGu1I41ChR8qyHVxK8cLPDD4kgGVQHBNAa0maaBJGTYzDJXOcU\nCy5JOaA2OMfoaArkheM7vlQNYNOtoWLJCgLHJwo5NApPKLaNpGRQB6j2oGmnRvcyNd3O/DkeErLh\nkWgklIdCyZOCRzxzQEeRxhdpUnncBkD5UCxXjJ7+tAlctMsIMLohz5mcZAH09aBQYdQwyAeaAuA7\nMAQxHH0oG1481nbGVInuWU5Kr+bHrgepoKB1u+o6jqlvBH05NevEBPBK0pQR4I4BHZj+1Bb9IS7l\nsFtNWtYwDGFYB/EXHqpJ7/WtQYx8VfhGbdZtV6Uh8gy81mpyR6koPb5UGKY4YkeYd88fbFAI5AC9\n8c5oQBb+U9+9GnN5RgDgjOPWgAN3yMfWgAqc91/UUD2RSSRg9+49KCR6e0WfX9WS0icRwgb55WOF\nijH5nP0FBYNRi6dSR7HRNPmu0hOW1GaXaZMdwBwAP3oynE0XRYrFtV02wS4ECj8dp1wcsE7eJEf3\n9qlFZ616ZttPu7Kbp9Zbi0vYzNCcgjHqoHuKsEp8LPh7P1PqjXerxywaXaviRSu1pWH8g+XuflQe\nmIIY7S3SK3hVIo12pGoAAA7AClEL1N1RH0/oTalcwx+IACLaSQKx59Ppmshv0D1jH1ZbTubU27xk\nkAnKsuSMg/UUFluLlLaJXETyecKAg554zigXiubeRnSKeJ5FOGVXBIPsaBLULoWkIfw3kYsAqIOS\nTQJMbpm3oqlmwACeF9yfn+1A+Bx34oE5IY5P+YFbnPIzQKAckHuRQCAQOO1AL8r9KDhkZOT9M8UC\ncrxgAyYJzwD70CT3Itxm8kgi3fly+P7/AOKA9pskhEkZysnOfeg6RH8w3tgjAHtQRZ1uystSg0m5\neRJ2UbHceV8fP3oJkBSAVII9xQFdSRwKDDvjN8L/AMSJte6chxcgFrm1QcSf9aj39x61YMH8Q+Ck\nfhqpQncxBDH5H6VRwXJ/Ke1Am2QchuMYOaNFSAVznB9qAm8f10D2RmX8jDHP3oLbebtA6ej0m2Lr\nfX6LcX7IMskf8kf6HcffIoG8yTadZxSTxCK3kRZUwSFfkruIJ78GhiS6Y1OS3160uZJFWO5bwZtx\nzuQ8bcfPNMZXvo2wsLnQ9R0q/maJNNv5Yo3bjCuMAHPzqA2jdUan0lF0/ZXcElxp9zE+5WVd/DE7\n1IPPB7H2po1bSNXsdYthLp1ykyEcj+ZT817ioITrnoux6vs1gv5JYnjz4ckZ/Ln5etA+6N0BemdB\nttMina4WEFfFdQpIJJ7D60E5I4Vo9qnnsQO1A3k0yzeTxhCizZJ3qNpz9RQO449igMSxHGW5NAIw\nBtUAUAMORkfegMhG3jtQD8+fvQGXJz7UAHuRQA5YDI5FB0qCQA5yaCs2/SFit/Jd3AmvJ2bO64ct\nt5zwD2oLMilVAUDgcAelAJLbhgZz3oGN9HPIYmhtrWRw2czjt7Y+dA+h3mJS67W9gc0AvuLYANAD\npkZABHY85oPOnxy+Hx06Z+odGjC2jt/7qBRwjH+cY9D6/OrKMebcceHwfaqCYIyDgZ96GhHOFJI4\n/WjQpXnsaCz9J6fDqGvRC8OLO3Vri5PB/hqMkfc4H3oDT3UupapcXrKS9zISgDdhnAGPbsKC5aLL\nBHq9p01c6bbagPE23kpJYhmz5IySAAMj6nNGdRnT2lu3V9vaQQrJDHfCMFj5kAfufsMUFogu5H0j\nrLUYXK+Lq0aRse/lf/8AOKlFfudagvbnQpNQRmtILydCwPdCQcgMOMZFQanPoeiawBd9M6s9jeKP\nK1vKQp+RFA4septa6fuFtuqbRrmzx5b+BAdo927A+vsflQXfTr2z1O3W5025juIW/mjOR9KAZI91\n4khaRNo4XdwT9KAl3b2+oWpjMoZWbOVfnI9sUCrXUNssUU8w3sQoJH5jQLvwQQC3NAKvuUPtK54w\naDg23v6UA7weBnNAIOBigMr+hoOjdZQdhBx3waAVG0Z7UBWfAOQSflQChyNxBAxQRutarb6bHALi\n9trSW4kEcJnGd7ewFA/j8QEK/IA/MBjmgWDDBB7igj9dupLTTbiaHZ4oQ7A7bQW9ATVgwXSNV6on\nl8azW6t45pWdxHIxWA/zNtz7A8Glg2S1u7fX+nt0J/H2c4MMhmQoW9GBUjj60g8sfEHpebpDqi4s\nHLG2Y77eQ486E8fcdvtVFekGW4UfegKVAAKgnFGhuDzxQXbpDTZF6a13UnUqrCOzQ5wGZmXIJ+lE\n0ppkEK6nJcRWcTW9hA08iKcjcowpye/mxQ0+6VRbC/jvLm48L8LG9y8pIOXxkDnuSTipqHXQMng3\nes9S3fhn8DbvcZI5Mr/lH700dc3Dad8NtPs4nU6jeXD6nMCwBRF5XOfU8YHrTNJFF1X8RawW1jc4\nGxTKNrZB385yPkBTFw1stSu7Ni9tPLGSQfK5Aphi8J8UNUm6fn0u72yvJ5fGbuF/39aYYtGgadp9\n/axXnRetzaXqnhqZI3bEcj4547Ak/X6UxFisPiXe6NMdO65057eQAr+LhUlHHbOPX07UwWXpQ6Bq\nMo1LpgW0sioVI8Qgxk+684qC028M5890Y3kHKbUwF+lA4LDOzu2M4FAOG3DaoI9cntQdJxzQEyR2\n59f/AKoGl5fSQRFo7ZpB/MhYIR9zxQdayyXKb7gqox5Yo2yB9WHc0DPUIWnhWKxkuYFRs5gcKWbP\nY59KBkx6isVeSGW31JNwHhyOUkA+o8v9qCfjkMo/LJFKqBmRvSgc2swnRyFcYODuXGfpQMtRsLK8\nvYJL+wjuGiUtHK6hghz6Z7H6UEmCsig84I9RigiruC9t0DaaVmIIHhTOQMeuGwT9qCJ1ywv9T0U2\n9xFFiaVBJGHz5M5ODgYPY/arKJPTtLW1t44i7SKq48w8x+ZPrTRJoipGFQAAdgKgzX47dMJrXSrX\nkUe6807MykDkp/MP8/aro80FQyZ+tUJ7hvH0x270XQ7KGtXvIk0T4c9P2bIhkvpnvJVfjIxhf7qf\ntRDXpu0/1DpzXltUlkvmWMBI+2zdnn64oYa6yX0XTm0i4jQ3t6wmuV53xov5UPpyeeKyLbpFtZ6X\npmn6TqNq7/ic6pqQRR/DVf8Alq2fTOP0FXBnXU+ox32o3lzeW+JrxlMXHKR9wfbJ/tVWK5f3AnaA\njafCTwwcY4BOM/qKKSjA4Dg8j37UHZKkE5P0olSFlcLDdJPbTNBOigjxOVZu3+80Rbbnrq9l0t9I\n6isRd2rgKpPlZMdyre9An07oupoh1zo2+lea2fMlr+WZFx7ZwwqWDVug/ihDq7R6b1EPwmpMNokP\nlVj8xng1BqEUe1EAJOMDOc5oDSxq6YYeuaAJF4oCBUQ7mJ45zQHYB14wR86AVjBXyjge1AEcRTHl\nA9hQE8kbgEohJ5yQM0ETHNqMOr3IZQ9tIMQyEjKt7D3FBLqywRPJKTuxlj3zQI3Ut14e+yhWRj28\nQ7RjH60EfpF3rU/jLqFrHbS4/hqpJXH19aCRa8jgiVr1xGwXzYyf99qA9tc29/aRXFnKs1vINyOO\n2KByoxwe9AYocHGKBvdwLcWzxSLuR1KuD6gjBoPHXWujt071Nf6YSSkUnkJ4yp5H7f2rQgWAA3Y+\n1An4j/1t+tBrHxKuYS+gx24LRx6ZFtI/lz60FY0+/v8ASphNpd68EpXY5AGNvzFF1YOirZbzVrvX\n9dkNxZWH8eeaY5Lyj8qj7kcVlETqOqXd/HrPUNzcNE16Tbwxf1JkEgD2AA/etBte9R2Oq2cv+p6X\nHJfBFjgmjkMaRgAAEqO5o1FWfbgjsR8+9AlI5CgEggeoNAq0iug8uD7g80KKmCcZ7fPmjJzJfT/h\nWtjJvhOPK/OOe49u9A96X1W90/VrRtNkkSfxQF8I5yScdvX6UGidSLpfVFzcvbRiy6kgZBGysFW7\nB9T7HHNSjU+o9S1iz0e2uNLmX8RYxJ+KgYeVwVGTn5d6gjug/iU3UOt/6TewQpP59skL5B29x/8A\nYoNHPB78Ggb2l3bXO78PKsoyVyvIBHBFAoSkbfyhn4GfWgTnmWFN7ybAvc4Jz9hQRdx1dp0S3Dw+\nJJHbDdPIUZUjX3yRz9Bmrgzbqb4x9Oxho4bB751O5HPkXPsc80wQHT/xrJ1IHUbGKO0kdRiBiAgz\n+YjnsPpTKN/tLy3vLOK5t5klt5F3LKhyCPemAYLuK5XMDEj1OCP71ArGWLMPT0oIbU7h11u2t49O\nllWWNm/FIRsjI4AI/egfQ2ktpbww2XgxoDl9wJ49cUCHUGv2GixM13Mkcm0squwUH5/SrgxDW/jF\ncXOteHb3otrKEEiRISRM3zGc49v1qDT+gfiBpvV7y2unxTxywRhz4ozuHbOR2+9Bmf8A6kNIEWpa\nZqiooEqtBIR6kHI/atfRjDEt3AKjgVQjug9j+lQWh72e/htTOzyeCnhHPomeMYoJvQum7vVD47K9\njpsQBkvZ5NoAHcgUAa7rKamE0Lp9Xh0G1OZZTwZSO8jn9cCsivdS38F9cJDZIY7G2URxKe5x/MT7\nnNaEKrENwAFPPlosFwS2cd/cc0UlIm3JOeKDo2LH+UA0SjgDk98URzPiJ2449e/NAbS7v8PdpKkp\nikQ5WQLkqccGgmYNQmXWLeQLG9wVRQVPlcj+Yn3xQa98OviAjz3WjdXSpFdliEuJCNjDtsJ7enep\nRdel+kdL0rqOTVdIsoYklV1dixO3nunpg9jUCnU3WMeka5b2EUcl3JInmigQs6ZPlJAHY8+vpQP9\nO1m3nthNo0cTwM2JDwoVj6H5gd6CbhtUiVn8TcXO4ktkZ+We1BAf8Z6fZ2uqXWpyxQrbStGseQzM\nB2IA961B59+IHXmodXal+HsPFh04HbHCo25+bY/zQWv4f/CCxvII73qC8iuXYb1tYZeF9txHf6U3\nBatX+DvSl86x6cr2dwjbnEUmcj6Enj6U8hLdJdEX/SmowJp2tTT6Oc+La3HO0442+3NBf1LmRUjj\nQAfmc+nyHvWQockYyQcY3CgaabaPZxGNnaUFi3mPb6f+KA2q3RstNurnBxDE0mPfCk1YPMemaP1L\n8RtYN9fJPc2aMUaVmCKg54H0z6VRYendf6Z6T1W56a6j6fgfwJyguhGJmPzbIzjHtSjTn0zSunbi\n01fSkt9Os5GAmWNCDOGxtXb6HnNZEZ8etOF90DPKFy1rKk3zAzg/3rXI8u7zvOTg4zVoTLDJ81QW\nDTb2SwuvFgcrkbXwM5H0PFGqsjpd6+kcT61Nc2ieb8OikFc/9PA+WfSjKA1nWBzpFlZ/hLWM4KH8\nzsPVj6mghN4IyQRk5NGo5BkFmyAfSgVjChdpGO/FAXYpOHLBe/FAQqoBJbA9sUBGxgtgEj/eaCf6\nDGjt1TZf8RNGumKS7mQZQkDIB+WaMrf8Ub/ovV7V20JIYL62K4khhCLOCcEcAdu9BmCuEQvxvyFU\ng42+v+/rQaj0zax/EXRY9Nns0t9TtM+BqCKAjEclXA98jn+1Si7Cz6u6O0tLjTrxLu2tQJJrDwcK\nE/m2M2SfeoLrpupDV9Mh1OytUS2vIN8m4BZQf6T7+vPpj50GfdK9L6rJqk1y1y0elRDKRqdjHHoy\nDhjx39e9BZr7fagW0j3kul3iETRqHkeF8ZBUjkZIxjtk5rQ86dW6r+O1OcW0UtvaRsY4oWfLKBxz\n7k/5NA46P6X1rqS6WPS7V9v88rAqi/f3oN46X6C1DSotkus+BIwKl8hn2+3PapROXPT2t20bPY6k\nJ5UGYmbIfIHGW5z68VBI6DrzzWSrrAjtrwFUbDja5OBlfuaCbluJLeNwIpLiVF3bVXAP0Pv8qBxL\nO8cYcW7vnuqkAigNFKs8CyxlwG/lcYI+1A31ayF/pt1auSFmiaM/LIxVgwfoO413o3qqfSLyUSwo\ndogAyZVGcbPTPr71aNDvendJ6wtbu7Fi1lezK0bS4VZMjtnFZE0bC5u9Jh0qRAr2yw4uWx59vBI4\n4PegN1tpbap0lqOk2sipLPB4aFsnHbBNOR5A1exFhqFxbeKkngyMhdOxIPcVuhiZFz/zBUEwcKvY\nnP6fWi0+6chjn6h062uATFLcRrIMnzAsO9EehNR+GvTV3GUh0+O2YsGaWHIf9amjIfib0no3S0Vt\nFY3M000zMzLJtLKvvkenyx96oz0rwNjA8cj2osFLbVAbOc9jRQiXOAwxnj3oBlAxwDj37UDY+vHO\nQeTQBIdqjcPMfnQwJclWyBgCjJBFeefw4VaVycBUGST2wAKD0L8H9C1rSIILjWLSCytY1lZASVnl\nL4PI/wD8+vvUo1uwbxI5GkjdVc7isvOBjtj2qBWKFZiQ8CJCB5FHYj5jHFArDbQ20ey3RY1HOAOP\nsKCH1u61CPSLt9MtlXUHUrbCbJBbPdtvYetXR5T1y2udD6lni1ErJdJLvlK4wWOCePvVgsV/8Sr6\n7UW1vA0NiowIonMe4+7FeT9ARQRmodWa9EYpPBhs1Tygw26rk9xknkn70EjonxZ17TXjAeKTkZ3L\n+YZ7N8vpSjX+lOpNM6umgkMG3EgBV1DYbG4kewz2NZGkC43CP8MPFBONysMAD50DaHVH8S6N1a+B\naxMUjd280pA5wPb296DrXWLK9WNoJdtwybxDKPDcAnHIoJBifTBzzmgaz2UFzPFNNbwvLCcxuygl\nT7igdRRKg8qAZ5JAAzQEnuYoHiSWQIZW2ID/ADH2H6UERr12BY6hueIQJaO7SK/nHfnHtx3pyPGW\noN4jynuCfU963RF+DL/UtQWTkjaWY/8ATnHFGql+j1VerdJY8r+KiJz/ANwoy9C/EjqSbpbRY723\nRJC8ojIcZ4IJ/wAVkecer9en1+9FzeLCCq4URjgDP7mtLhteadBY2kMczyHUpcO0YxtiUjgH/q9c\nelAiLy1kjCX1ruyMLNGdrj0+h+lE0+t+kNQltJ7yKS3jgiTxUFw/hySp7qp70NV6YEBgWUNjBoaK\neAODnHrRoVgDnBP0ozpxZ2f4y5trVeGuJFiBPpk4zQep9C0LTembS30fQbWP8ZsDyTugZgf6ix9f\nYZpbgmbXSmXULaa6kMzpltzcjJ//AGpaLCY1CDsF74PrUCgHY0HbSx7Z96BGUfxB2xjtQZ11t0Tb\n6jNfyw2wM18gV5AcBdpzyPnV0Yp1F0o/TEczXjXaTOQYpIk3QlT3B9Rj0zVl0VKbVppImheUSwbs\ngFfXHc0De0tri/ujFYQSSyfmKopPHqaDV/g9p+padr/gkSRTzKu0kZRlPLYPbOPf2pg9GWzRCMJA\nFxH5do4wayKX1z/G0CdzqLWRkiaTxQBLudclQvovbv3oMU/4Z67uwnUAt3u1Zw42yhmx3/Ln8v0o\nN86L1d00i3i1UiGQIocNnEbnkqT2xgiguEbI4DIysp7EHNAZnxQQ/Usksej3EsCl5EUthR5sY52/\nMjigr6Qrp3R15LqEcIlmgdpFGAsY2navPJApyPJtwd8rnGBuJz6Gt0MzGSTyf0qCwSKA5ZsAjnn2\notTXQYj/AOMNIDqCrXUZwf8AuGDRG6fF6Gyfo6+ub0CR4EPgIScLIeAcfc1keatN0661a+S3sYTP\nKzAbV9B7/StLrQ/iXp9pYLp8elWsUM11AzXMqt53I7g7j244oiB6W6Tn6j2TeAy2FspTeB+Z+/8A\nmgtnWlvpdl1Dp1pq07Ja20GFQpuDHHAwPf39KDHriVTKSPOCeBnHHtQGsrG5v5pfwcTOIlMjgEeV\nfck0XRIreS7uUigRpJXOEVe5PtRE/wBJ9HaxqvUcdhNFJp0lviaSWVcMgzxgdySeBipo9T6O8Npp\nUJ1K4iW5KgSvIyqxb5jPH0paJm1NvKivE6Mp7MpyP1FQLRTwy58F0cjuAckfagOTtO3+Y8igMWCI\nWbOPlzQNhNBOWEbq5Q+YKc4+tAD7JEZgQfXj0oI/VtIttXsZLW5hRopByCP/ADVlGRa78Erae63a\nXK1tG3LAncM/Kmh10l8IZdBv4rxtTE0yggJsyoz6/P0po0zSNKEMdo9xGnjxuzkqMAEgjj7Gmial\njWQMgyCRyQcGoITqHT7q/a30+G2jFmwLSzl8GPBGFA9c5NBPRwJDbpHCipEi4CjtigqfWltqCaG8\nWhNbxyzOBIs8W8FcY4+dWQQ/wtuZdIGqadrknhy2u2QyOSEZOeRngY+XvTBZZevOmhC8janbqiZ5\n3Zzj2FMFcs+sh1ZqsFrp8UkGkrlpbh+DNzhVX5Z5NQTfXyWUXSV2t+wW3EZ5I4HHt61eYPI0mA5C\n9snFaoLsPv8AvUEk5JcA8cZG480WnOlXX4PVLO4yQ0cyP244Yf8AiiPUfUump1B0/c2O8xfi4v8A\nmL3UcGpgw/SujNX0Trj8PpckimOMvHO/kEg9Rjs3PpV0aFq/Qqa1ZJ/qcrverEqNOwGM+uMfemiV\ntrKbQdMNjp9rvtkhPht6mU5yT8u1BkvXg1qXUtOvddgRY1R3j2YHiMvZSD27CgzSCyuNQ1KK0giL\n3Mz4VAOc/wDignoNNOnaHeiW8hgkku/Al2+Ziqgn09M0ETp0qpqSmGKOdFcEeLwMfPHag3JLuCRt\nPmQWsDhNphtVAcn1w3BPFSwDdWGpX1/OYdOtbbSrlQ80szHdn0GR24/c1AbWemdatLbTJdGvJIJy\npDQwMV3exwOPatSz9Ei/R+txy2mr3evyHV4miWIDhGwwyGA7nGRS2YNZAUBWYDdjGayEvxMYB3nY\nu4KCfU+woG93c2enWs1xcPFDCp8zEgDPzq4GGgz22saS1zZSZhkdsFePXt86YHWmySeLNDMYikZ4\nYNlvvUD+VARxQJqgwRQHUAAe2O1AWOFRM8mDlgB37fagb6reXFt4ItLZJnZsuWfaI0Hdjwcn2FAz\n0nWX1i4u4xY3VpFbv4eZ1x4vGdy/KgkriN2aMRlQoOW3DOR/5qwYr1P1tp2pdS3WnanKkGh24kRl\n2eaYgcb/AFxnnAqiv9Jno0dRLJPbtdQtkNPIALaMnODsPPpSjbdK0DTbWQXui+Gsco3BU5hPP5gP\nT7VkU74t6PZHpq/1N5ZZbwrtRnmOwDPOFJwPsK1xR5ybudw788VaC5X2WoJRULSBpAe5PA/aiinA\nZnHck4A70THq/Qr23/4Y0u4lmCpLBGA7epxjH60Du+WGOBvFlFuWOFcYyCfbPrUojri6k06xX8PF\nNfBUJ3ltzM3scVBjfVvVXVNit5dapNDZGQGK3shjeAe7YHIwAOT3zVggNTiu+orrR4p7m+upJFR7\nh3TPhggDaoBwRjnPH5hV0af0xotnoD3l5dWdrY2YjGLhwPEHoef996CC6m0HpuPpk3Wny2s9sJPH\nJ3AeI2D39T37UGU9QTDULuGPSLPwIyoVIYk2lj6/X70G2/DPp0hVudRuBLcwxhRGkeEjB9M+p96D\nSLprVHiieaAE+YxHkke4H1qUOIBawL4uAuc8nvj71AwjRtQ1eO78QNp9odyLju/qT8uf70Gb6r8S\npLzryy0vp+4NxYSSCEswI2u2Rn3OOD9qC4dVamen9NlaC7tUaIFvCmnHiy4HJXJxnOeDVwed+rOv\nLnqSyWO4jZSru/kc7ck+30GKosXw2+KmqaDJDY3jR3OmqNoRhtZAP6SP7Ggtmt63qbTJ1XLazJps\nlwBFblypEOAA7L2OWANS+xrnR2vW3UmjJeWp8wJSRf6WHeoJdSPMCRmgMq8DmgBpNsgUIxBGSccD\n70DczmS8MDWoe28MN4+f588rj980CktuJZYpFdlKZ4B4OfegQ1hpIrVjbsRMBhBj8x9qsHnX/hm3\n6y1O/u9V1ddPmS6aD8OkQdyxOSe4OMmqLUvwQsYY4Xjv7m4YEEhwFyMY7fXB5pRbvhp0jqfSMV7b\n6jqZvLGQAwxAEBDk54PuD6VkVb49a5DBpiaNaeF/FIaQDumOwpzMGDEZQZ5+VboR8In1I+9QWDY6\ngFn7jjHpQhtJEFbAGBnijT0P8H7qPVOh47a42yNaymPBOcDupoykep+m73V7g/8Av2itQowvJIx6\nj5/OpRjfUWrax051RPY6LqFy8YACkebO4Z7HjNWCY0ToW2utJbqPreW5na4O4R78cehY9+fQVKLX\n05p1ro97awC4kX8VFmJLeEKdoyfOxJPbHbHYVAz0rqKPWNauri9t1ktJgILYgEiNFJ/Op9STmrBB\ndeaFCo0y3jt444DI3jLE204Y5DD+9UPPhv0NaRtPq99mSLOy22nOfdh75oNC0vT7m1uJGvGiii3A\nW8UDbQAeDu9zUohLlhouqap1VciF4I1FtbxSthtobBIPuTn7VBJ2vUth1TYk2ULi9iALwyKQYz6Z\n9CM0Ft060/DWEcDHe2Mucdye9BFW3SekWt3LPb2cUTsd2UGCG9x7VYMzufhzdX/WmoXj+BPpx3I7\nXZMmXYckc8EVRKaP8I+nXikLQuxOQSTnBzj6UEjonw90XSrq3S3s7dplJcl1EhGDx396lFx1TQ4N\nVjaC7UNCU2lAO/8AvNWDCLp9X+E/WgWImXSp2LRq7eSRT3B9iP8AFSjd9P1+21TRodVsMS2rLmTb\nyUGOePXFQSltcLcW0c1vh4mXcjDswoDLdRm4FvISsgXeTghDzjAPbPyzmgVFxCzuiOC0WN3sM+5o\nDqySJmNg3rx7UFb60tNUubGJdFdEvhIdryflUFSM49TVgyTQenJemOorf/U4H1Fpp1edAh/hOQTu\nQ9375JA4q0bnbPBcxxT20wkjKkqYzlT9ayGWu38um2MbLEJ7iRtoUds+/wAgBzQeW/iHqi6j1Pdz\neL44HkL9txHtWhVUOVyvHNB2F9zQT8hUAhAdp5FCG0mSAzE4HGDRppvwL1bwOpJbEsFiuYyVX3de\nR98Zoy2ZtRgmjkSRZocEp51K7se3vUow/rfpFE124mVpfD4mk2MWdCc4A+VWCH1281/UmFnpklzP\nYRFBEG8uGC4yQfcn9alGgaJo95rRsbi53WaxwrHOm7BjYcHnvz/moJaw07pXSI5IW1K0CQnDhpAW\nB9R796CudY62msTRW+gadI8KnDXMkLLv9MA8HGOKC3dAXF1dRfh75f41moi4G0AdwcfTj7UFhv7R\njqMBV5AJFZHkR8FRjIx6CgpXVNjJ1JqNn07p26CztSJLlpIydyj2J+fGaC+afplrazqLa3SKNIgg\nx3IHYUEsBk4wQc4oK11L1z070/M9rql6wuVA3QopLcjNBDwfFboqeSO2W7kQNxuaEhQfnQLt8Tui\nreVoV1UeXnckTFT9DigHRuv+mbu9ZV1W3Nyc4IRlVl9O47/KgtU+s6baw+JcX1umRkAuM/p3oK/1\nt0rYdX6cqXKESqN8Ug/Mp9P1qwZ702mo9GdUTWJsmOn3EY8CAORGXJAwScjJ5q0bJDNLb6YklxbK\nsgA3wwndg9sDtWQN3aw3ZKTwLLEQOGORn6ehoG1vYAw3FikRt7JSuH3Hc/GSc5P0oHn4aO2uGuYy\niose044wBQIm6F1dwfh5ARs8R8L2BHGfnQHv9PS4PjxrGLtFKxysm4qD3oCxboIIo7e1jhQHzAYU\nJ8wP8VYM56j1ktaal1BMrS2sAaK1OQDD6eUepY9yfQVR5zv7hrmaSaRtzyHJY0DcE4BPIPb5UBwO\nO4oJYzFvzEYHAH9XvQhNZN7AEgDOSDRo/wBA1SXRdVtNQgb/AJUgfBHcZ/8AGaGPVlhPbarZ2t5C\nEeORBKje2RUrI1zYxTBhMinIwcjvUEcugWkO4AMisMEA8N69u3yoERrOhWNxNYy6hapcxAeJHM+D\n8u9ASLStLlm/EWdpZyxy+Z3RQ3I5B44oJKTT4blFWSNBEOeBg5+goFYbOK1TKhIxnIbGMH50Cpcy\no6AMrIcM2OD68Ggb6Lbbllu5Cd88hYBu6rztWglSNkfm4P70Gaat8Rba96w0vp3R2mhufxyi4kO3\nYyDOV9+f8VYMw+P0cP8Ax4JVuEKzW8bEr5tuMj0+lUZ7Y2X4288GK+towRlZXYqv9uKCQi6YmbT2\nu11GzaJWKnYxbBB49KCFnhubdiwL+U8OhP60ElpXUFxY6nDdXQF0qYbZKxwT9vWg3npb42aHcmC1\n1C3uLSQjEkpIdQfr3xUondP6x6e6tv7e101hczRzrNtaFiFC/wAxPYHtUF+lj8bYCTgMG59cUC4O\nBQQOo2eoXepFTeL/AKYQN1sEwWx6Fu+DQLX2kw3Ok3Vjas9qJ48Exd1PHb9KCE6R0G86Ut7mK71K\nK4gklM7TyKRIBjtjtjj96AOreudJsrMJbXksk8jBCbVdzRjONxBHP/3QQ9x1jcWGkERWWqXdpMPC\nt7x4wfFOOWPbA+fAqwZr8TJ9Qbp2ymvEjsrSTEVvawyHz45Lv6E4wPqaoyl8g91OKDlYEc8mgKW5\nPH7UE80f8PPHl7gDFAZkUjawUIQG8w5ouknAUbl9Dg59KK1X4Z9XXFvo8mlRXax3KHfBG8Rk3qe6\njHOc54+dMZO7jr/qK8vWtba4tYu38TwvDOMc8N60wPLbrW10PS7pnvrnUtbAKobgBUUk9jg8f/lM\nC2rydMdRSaRqWoLEbx4UefwxkL2BVvvn9Klgv3Tp0lPxFno6wJ4IVmEOMEHsf2xUD2e4ks7n+NGD\naCMu8q8lCMcEfPNA6tW/EwrMybEYZUHnI9Cf/FAzu7G4LXTWs38SRNqhs4Bz3z9KCO6x07UNT6al\ntNMvEs7xkC7nPlI9R2/egwbrDT+r+kupLCeK9nu3KBYGRy+QvdWFWCU6avtA6h1iKDqLRhpmpvkx\nz2p8JGb3z7k557VRX77TdHteuPBut401CAouyXGcdvmASaC069030brYaay/CwPFwWspRErfUN7U\nGZX2hWSiY6ZrMc0CvhUlBUk/UcGgiLq2mtG8F54yDwfDfIoGkrRsSZXwOB2zmgsvw06XHVfUcFvI\n22xQ753Ze4H8v3OBUo9a6XodjpltHbabDHZIhVsQqBuA9DxznFQTQUe5oDYGMnn7UEbpV3JqDyz+\nBJFbBtsXiDBf/qx6CgDXL42cSRwGM3UzBQrHGFzy32oG2i2kKTSI80lzMow0rqQoyew+3tQO59Kt\nJJRI9rEzgg7igz3z/egZ6paJdGGwW4eBXy7pGeXUdwT6A5qwebPjJrcOr9TvbWZQ2Onr+Gi2nIJH\ncj7+vyqigOuRk+vtxQAqEk4BU0ABj7j96CzzKxYD0GeM0CQG3OMAjkfOgbSZwzE4PJyfWi6caTdz\naffW95akrPFIrLg/tRHpGzs9C6t0W31FrO3Y43MrcbH9c/eloZ6v0JpWoKlrHHBbScSFEHYc5Pz7\n1NDXUoJrK1g0dvw9qsspW3nXaN6KMrHnH5ieSfan0U3Rr1uidaRbiwk8BUSS6naQkjc3ZcHaRnn7\n0wbja6lZX+nw3NvMksM+FXnPJ9DUCeoXj2hSG2t2km7op4U/f/FAvHaNePb3N0jRzRA7VD8Akc9u\n/FAvcxnawZQ3HYtjJoKfDFAdeub6Vo1dSULIBtTbgYOfU8jNWUVvrm5ih0m1urixhlsI5HJliOwR\n5/LkkHHJPamjHdQ0HWdemlutN0+YWBYtC0rHDhjwVz3zWgx1n4e9U6QE8XT5Zd//APR5se9XBXbj\nS9S0zAvbO5tyWKAOhG4/KpQ3ZHXO5JFK98qRUGhfCbph77Uvx91pv463wVjR0LR7s483796WjW7r\nTrXpHWrSW2YK7lmXTbaIFpCRjjHOOSeeBipaNLtXuIre3R43lnkGXYADZnnmoH6Dkbzn6UDGWe9a\n/hKG3jsW8riQMJS3svp86B6zgMQmDtGT8qDNb6XUpOoPx72tzOkjFYowOduDwDjj70Gg6Wsq2KNe\nAJKRuKk52fIn5DvVkENrvW+iaSAsl0txI2Asdud5Yk4A4pgzv4l9ST6JZSXbyyprWpw+FFa5G21g\nz5icfzH3pgwCSQlh688+tUEwjjngZ7UHAHuWAHpn+1AXj5frQWXOGBZcKSe3c/rQIyAtnI27eBj/\nADQIMAuH8vHBB9DQwVpPLjOckEZ/ahi9/Czqj/S9VhtLm6aG1uZFUsT5VOfX5Gpg9GiNJArxsrxs\nv1BHypYGF7pljeG3kvLZSlqzNGGxhSRjP6GoG1yLUWiWc2nSPA4KJGItyYHYHHarop3wu0jWYNUv\nzriNBp8ErraRMANxJ/N7nA7ZqDUHgSQLvAbacjI7H3oOuIFuYzGS68jJRyp4+lA0m0yDwGjiTw3b\nzBwTuDe+TQVbV+mLmW1NtbSok9weZiC2zPLEZ+/FBM6Xo40/TYdL8Jr21G4vJcuCck55HbFWUKQ/\nh4tR/DTz2o8TK21qmMgKOf8AfpmrokljG1i5BHI57D5VNorut9Lab1LA638W6H8sboNrqQckq3pn\ntV0RWsfD6K7SGC3vTFahQJY2iVmkI9d+Mimie0Hp2DQ7AQacio3JZgqjcT3zxk1KHGldPWtnqMup\nS5uNTmGGnk5KjGNqf0r8qgmkhVGcquGblm96BDUZZYLGVrdN8+MIvux7UGKTdXdbaRrFvbaxbWN4\nd58BmwCjHPORycLx2q4LNe9S9TdN6I13qkWmzSXdwBCGlO4hiMKAB2A9ag0WySQwpLLtMjDcQBhV\nz6CgoHxF17XbnUYunulgsUsu4TTvjIUAEhR+x4qwZwtkOi7651PXJobm4tohHbQhdgecjnaPZeOf\neqMy1vWLvWNQlvb+ZpJpWyT2A9gB6Cgjy5AO4A5oAGRgBR39aA7Z8MkFtxPY0AbV9UGfpQWhj5Tk\nBQGxuBoEGG1iQCyHvj1oELgSkK6oRnIBIxzRdJ28Q3+fHiAds96LoH3AF1wCfyijNbF8JviI1rbQ\n6Pq/iSopxFOx5Uf0n3qUbWQk8II2SRyDPuCDUHMpSIiJQSBwDwKAgTxApnEbyIQ+APyn0+9A5B3A\ngfmoEWgcb3VlMpGFYjt+negSs7zxH/C3RWO9UElM8SAHG5fl/agNdXcEbJAZ1WadvDQDJO7Gf7c0\nED1dqWv2enzw6Rb24nZfJd3EwREHqxyMZHzOKBbT7H8PZWTK5uZ9o3Xm1SzEry5PsT7UFF+JnUez\nSZ9LttRs2km2m5KSFWXDZI491AyBzVwK6J8T7CRtPjee0tbaGAtdNISdoXgLEo5JJxyfSmC6aF1f\no2vELZXDJOxwkMybHYe4HtUFiJWJd8rKqjuTQcZV8SNI0dy43BlGVA+ZoBniE0RU7tp77Tg5zQUv\n4hNrU2tdNWOhylPEnaS5UHGYlAzn5cn74oHGt6l0z07k6nJC123HhKPFlbPptGTj9q0Kx0XMvU+t\ny6vqQtpWlZo4LOdGDWsak8Aflycgk+v2qC8a1q8OnaXLPOz2kCIWkZ+CqjgYx6n0xTBkmp9Sabp0\nKdRyI5vJkaGw08MVKIDw8jA557896QY1q2o3eqXr3N7O8skjnlnzgn5e1UMCGV/MOM0BJFOVwfX0\noFtgZTjkg8UBtpOeO1B3hg85FBZXVMM+VJAA2+h96BO4IMJ/p7qvuKBKacmOKB5CYYx5UzgDPfHz\noGwD5OApJHAHrQEAk8NWdNpx+XdkA0AIGhkGWOQcgg8UGw/DP4kmwhi07WCTZqAiSbstGc4+pFKN\nvs5o7q2Sa3kWaJxkOp4NZDOHUh/qL2k8LW78eG7kbZv+0+/yoEZp7fUpX/BXpgvYZTCSRtO7vtwe\n/vQdY6jeyatPp91FEPw8aSNMoYbi2cADt6Z70DS60KW7luJdV1JniJzBtURG2b0KN7+/vQKSWUWn\nLLqN3cSLP4ex5Y8jxiPykr23+nzzigpXUPVOu6Vqmmf8UWttb9OXDqkjRnfI3H849uRkDOKC0axL\nFr+nLB0rrUMM0bqCIGGGX1AH09qsGc9UfBiTV9Vhu9Pu5oPGLNeG6bczN7jHvVEr058Gre3sLeDV\nrmOdo3LmSFNjEH+XdntQXO51XQOl5YrCKGWa8SMYS3tzMyLjjJHb9alDqz1S5ktJ7nVdLmSVDiOO\nNfEMiE4Xy+h9xUDm11CaTxEOn3VmpHFxKFCr9s5GPmKAus6jb9M6RJf3c88yxpjcxL7uM5OO3HrQ\nVTSupoOuYdZMTSpptriNFtXKXDA/Pjhs9h2xQOJ7Xpnpa2S91WK2swqjbGw3ysfcnuxrQsGmapYv\npwvra1FtDL52Mi+Gx49sZoMb+LXV0t+jWl3OYLGTO2zjx4h2nyszHsG4/Sgxt5ZJmEsjl3PB3GgS\nlyXBxkDnNADseB2PsaA8SoXQyFgmQCV70B5R/EIjYmPJxnvigEKcYDfrQF2/X9aCwqC7l2zwfT/F\nAJJ5747E5oGTqZArKOfccftQHZWwmOD23Z4NAEkTEBmwR7g5AoG7KSSE5HyFAMTyQsMHa/cEcEc5\noL58P+v7rppdryPNAXx+GfsQe7Z9D2/Wg3zSdX0fqzT08F433eYwscOpHt9PcVkQPW632mX9vfWd\nrbXiRgrIdu2eHIwGD57+nIoKdc/ELVdC0u5afp27SUtta5vJMMzk+UDjzYHtQWDpj4gxXmif/wAi\ntXZkGZzFGW8MehZO+PmM0Fibr/poWQmF6xXA2xmFg59sKRk0C2nQP1KFvdb0vwIUJNtDKcsVP8zD\n0Jx2oJDTNA0vR5p7qzs44pJOXkUc/SgNfa/pNvbF5L2JgTsCo2WJzjGKA1jcNcxOF/m/I0zbt4+g\nxgenNA5s7CCxWWYQxpNLgyMiY3nt2oHajcuexAoEL1C1uyFkVHO1ixHb17/KgwT4rdXWep6oul2O\npywaTYqVLxDyySDjaM9x6Z+tWDPdB1TW7Wa9sumpGlursqMQRlpXwd3BA4571RcdN0i41G7h/wBS\nmNxqdkwn1O6u5/4cAXlYgcnngE/pQNvih8S211obHRyYbWInfJG/Ex9MD2+tBmNzcTXTtJcSSSSH\nH5jngDAH0oEdxbg5A9wKAzPwO+fegSLfLJoFoR5fUfegXOcHGAT8qAM+XaBzQCCwGDuyPlQWJpV3\n7Q5TIweM7u/f9qA9vNYpFML2KaR8YiaJgAh55PvQRvnYoqA+MThcDnPai4PKWQlH3K6tggjnPaiE\nmz4ZznBPfFAVWG0AZDH1z2HzoE7lhv8AJIHI/mGRQI8AEeuOMGgndN6pu7V4RJLKY4WDLhypXj0o\nNL6d+MMS4ttetDdQgDNwAPEwPRh2NZGkabrvTXVZiexvba5aI+ILWZQG3Y4IDdvtQScvTdjK8cht\nFjkQ+VlYgqPXGKA17daV07apJrV9CsZbELTgbu3YY78UEHf9evJ4K9P6JqGoiR1XxjCUjAJ5OT3N\nBM9YdSWPTenwy3t7bWbSuBunUthfUhRyT+1BA2vXnS/jGdeo9LnIHljeLwSCe5zgmgejrOz1S3kG\nhazoaXYGAJ5Sw3e38uaCsJfX02rPD1XfXtvcCXdBJGjLbOO+EK88Y7nIoLB1H1Bb6WkN1ddSQ29i\no/5MZEjzt7DGTjj2FXNGUfEH4wRaxCtnp2kwGGM7llvBvIOO4XOAe/fNMwZbqusalfLBHfzSvFH+\nSIgKo+igYqiwWfWV30rpp03p6exJnUPJexQnxuR+Ulu2PkKCrT6jcSiTxZnbxCWcFidxPJJ96BBD\nlQ35fbFAbahBHJIGO+KAIwg5YnB455oDkKcbW7UAOowSMjOORQcCVXPp+9AqDkHcDmgMNpHPcUBT\nuzQWCJXcFvKR2Y0CMiqjnz4UcH/6oG8gKluwxyAfSjQ6ylEJBJfv37/OiYQMjbjkZXOSP/FEELAE\nkNn1waBCXdjORnPoc80CZeTb5wQe2BQAm4y7jlhjvQcWO3cW4GB7ZpgGC5a3uUeNyGQ5GCR+45pg\nt+l/EzqLTgxj1O5Zc4CSOXCj70wOE+Jd/Pq0V7qVvb3bISAWUBhnuc+/2pgvkHx0soLaNIdKkEiq\nR5yDg47cYpgresfELSNc1n8VrFtAw2ZBiiywwcgeb14x2xTBYNA13ozUo/GOqWVizDc1nf6crIh/\n7wOf1rOURvVupdE6ncpFeakiSWsZdbjSLfw1Zs+VVyMHA75xWsFDHU0idTJdf65rT28YKpPvHjKp\n9Bk49qYK/rGpXF/qU9zPdyzyyMSJJAAx9ifnVlwNZ7vxYEh8GAEHO8DDH5H5U0IPK8jHxSzFQAMn\nOKgJkFwPT6UBlAII5z3zQCjnA5OKBXeuAT9KABMA208DtxQHRhzgUC3KjJx9z2oAP6/L3NAHC8Hg\n/XNAcNtGe4oEy5yeaCdLk7yx2qQCAO1AmXZSSexHbPNAhJuLJkgjvzRonuAJy2cd8UCbyOi453Dj\n7GiYTZyVPPl74oYLJIyq68EH3Gf3oYTDEjLbiP1FEDHOUOdgOfXIBFAm77j5Mnng/WgLI5UE8Eg9\niO9AnuJbuQx5wOBQFRxuIbOc54PrQK28ws76F722EyI4d4HJUOPb35yKBm8oeQsi4BPbPb71RyYI\nHmPGRg00GRsbsHIPY0Bg52AEEseBUCQJyOPXtQDtcdvvjtQCQ/GBwKAuXU4PrQBvZE5IGeO1Affj\nBJ57UBvEO045HagFWAAzktQKIzBeMg0C5kz5mOG/WgMrDJJ7jmgEnIyOccYoA3cEMRj05oC7/wDe\nBQTduzEoNxwcZGaAJOWfPNAlISVOT60aIQfkj+amgJ3bnnigKeFGPQUCf/x0Smw4V8exogX/AOY3\n+/SgKxKxeU459KAgJOckntQJkkcgkGgAAFFz/XQEmJaY7jnk96BM9yPQelAf/wCX7UBv/jagGP8A\nKB6ZoDf00HMfO/0oAH5TQA/5moECSMDPFAvGASMjPP8AigVX+b60BW7/AHoHEJJD55oDd4snv70C\nsSjCcDmgVAAbgYoGYJ3nk9qBUAYHAoP/2Q==\n"
+    }
+   },
+   "id": "uid6"
+  }
+ ],
+ "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,103 @@
+Pandoc
+  Meta
+    { unMeta =
+        fromList
+          [ ( "jupyter"
+            , MetaMap
+                (fromList
+                   [ ( "nbformat" , MetaString "4" )
+                   , ( "nbformat_minor" , MetaString "5" )
+                   ])
+            )
+          ]
+    }
+  [ Div
+      ( "uid1" , [ "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
+      ( "uid2" , [ "cell" , "code" ] , [] )
+      [ CodeBlock ( "" , [ "python" ] , [] ) "print(\"hello\")" ]
+  , Div
+      ( "uid3" , [ "cell" , "markdown" ] , [] )
+      [ Header 2 ( "pyout" , [] , [] ) [ Str "Pyout" ] ]
+  , Div
+      ( "uid4"
+      , [ "cell" , "code" ]
+      , [ ( "execution_count" , "2" ) ]
+      )
+      [ CodeBlock
+          ( "" , [ "python" ] , [] )
+          "from IPython.display import HTML\nHTML(\"\"\"\n<script>\nconsole.log(\"hello\");\n</script>\n<b>HTML</b>\n\"\"\")"
+      , Div
+          ( ""
+          , [ "output" , "execute_result" ]
+          , [ ( "execution_count" , "2" ) ]
+          )
+          [ RawBlock
+              (Format "html")
+              "<script>\nconsole.log(\"hello\");\n</script>\n<b>HTML</b>\nhello"
+          ]
+      ]
+  , Div
+      ( "uid6"
+      , [ "cell" , "markdown" ]
+      , [ ( "tags" , "[\"foo\",\"bar\"]" ) ]
+      )
+      [ Header 2 ( "image" , [] , [] ) [ Str "Image" ]
+      , Para
+          [ Str "This"
+          , Space
+          , Str "image"
+          , Space
+          , Image
+              ( "" , [] , [] )
+              [ Str "the" , Space , Str "moon" ]
+              ( "uid6-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/jats-reader.native b/test/jats-reader.native
--- a/test/jats-reader.native
+++ b/test/jats-reader.native
@@ -1,422 +1,3673 @@
-Pandoc (Meta {unMeta = fromList [("author",MetaList [MetaInlines [Str "John",Space,Str "MacFarlane"]]),("title",MetaInlines [Str "Pandoc",Space,Str "Test",Space,Str "Suite"])]})
-[Para [Str "This",Space,Str "is",Space,Str "a",Space,Str "set",Space,Str "of",Space,Str "tests",Space,Str "for",Space,Str "pandoc.",Space,Str "Most",Space,Str "of",Space,Str "them",Space,Str "are",Space,Str "adapted",Space,Str "from",Space,Str "John",SoftBreak,Str "Gruber's",Space,Str "markdown",Space,Str "test",Space,Str "suite."]
-,Header 1 ("headers",[],[]) [Str "Headers"]
-,Header 2 ("level-2-with-an-embedded-link",[],[]) [Str "Level",Space,Str "2",Space,Str "with",Space,Str "an",SoftBreak,Link ("",[],[]) [Str "embedded",SoftBreak,Str "link"] ("/url","")]
-,Header 3 ("level-3-with-emphasis",[],[]) [Str "Level",Space,Str "3",Space,Str "with",Space,Emph [Str "emphasis"]]
-,Header 4 ("level-4",[],[]) [Str "Level",Space,Str "4"]
-,Header 5 ("level-5",[],[]) [Str "Level",Space,Str "5"]
-,Header 1 ("level-1",[],[]) [Str "Level",Space,Str "1"]
-,Header 2 ("level-2-with-emphasis",[],[]) [Str "Level",Space,Str "2",Space,Str "with",Space,Emph [Str "emphasis"]]
-,Header 3 ("level-3",[],[]) [Str "Level",Space,Str "3"]
-,Para [Str "with",Space,Str "no",Space,Str "blank",Space,Str "line"]
-,Header 2 ("level-2",[],[]) [Str "Level",Space,Str "2"]
-,Para [Str "with",Space,Str "no",Space,Str "blank",Space,Str "line"]
-,Header 1 ("paragraphs",[],[]) [Str "Paragraphs"]
-,Para [Str "Here's",Space,Str "a",Space,Str "regular",Space,Str "paragraph."]
-,Para [Str "In",Space,Str "Markdown",Space,Str "1.0.0",Space,Str "and",Space,Str "earlier.",Space,Str "Version",Space,Str "8.",Space,Str "This",Space,Str "line",Space,Str "turns",Space,Str "into",Space,Str "a",SoftBreak,Str "list",Space,Str "item.",Space,Str "Because",Space,Str "a",Space,Str "hard-wrapped",Space,Str "line",Space,Str "in",Space,Str "the",Space,Str "middle",Space,Str "of",Space,Str "a",Space,Str "paragraph",SoftBreak,Str "looked",Space,Str "like",Space,Str "a",Space,Str "list",Space,Str "item."]
-,Para [Str "Here's",Space,Str "one",Space,Str "with",Space,Str "a",Space,Str "bullet.",Space,Str "*",Space,Str "criminey."]
-,Para [Str "There",Space,Str "should",Space,Str "be",Space,Str "a",Space,Str "hard",Space,Str "line",Space,Str "break",LineBreak,Str "here."]
-,Header 1 ("block-quotes",[],[]) [Str "Block",Space,Str "Quotes"]
-,Para [Str "E-mail",Space,Str "style:"]
-,BlockQuote
- [Para [Str "This",Space,Str "is",Space,Str "a",Space,Str "block",Space,Str "quote.",Space,Str "It",Space,Str "is",Space,Str "pretty",Space,Str "short."]]
-,BlockQuote
- [Para [Str "Code",Space,Str "in",Space,Str "a",Space,Str "block",Space,Str "quote:"]
- ,CodeBlock ("",[],[]) "sub status {\n    print \"working\";\n}"
- ,Para [Str "A",Space,Str "list:"]
- ,OrderedList (1,DefaultStyle,DefaultDelim)
-  [[Para [Str "item",Space,Str "one"]]
-  ,[Para [Str "item",Space,Str "two"]]]
- ,Para [Str "Nested",Space,Str "block",Space,Str "quotes:"]
- ,BlockQuote
-  [Para [Str "nested"]]
- ,BlockQuote
-  [Para [Str "nested"]]]
-,Para [Str "This",Space,Str "should",Space,Str "not",Space,Str "be",Space,Str "a",Space,Str "block",Space,Str "quote:",Space,Str "2",Space,Str ">",Space,Str "1."]
-,Para [Str "Box-style:"]
-,BlockQuote
- [Para [Str "Example:"]
- ,CodeBlock ("",[],[]) "sub status {\n    print \"working\";\n}"]
-,BlockQuote
- [OrderedList (1,DefaultStyle,DefaultDelim)
-  [[Para [Str "do",Space,Str "laundry"]]
-  ,[Para [Str "take",Space,Str "out",Space,Str "the",Space,Str "trash"]]]]
-,Para [Str "Here's",Space,Str "a",Space,Str "nested",Space,Str "one:"]
-,BlockQuote
- [Para [Str "Joe",Space,Str "said:"]
- ,BlockQuote
-  [Para [Str "Don't",Space,Str "quote",Space,Str "me."]]]
-,Para [Str "And",Space,Str "a",Space,Str "following",Space,Str "paragraph."]
-,Header 1 ("code-blocks",[],[]) [Str "Code",Space,Str "Blocks"]
-,Para [Str "Code:"]
-,CodeBlock ("",[],[]) "---- (should be four hyphens)\n\nsub status {\n    print \"working\";\n}\n\nthis code block is indented by one tab"
-,Para [Str "And:"]
-,CodeBlock ("",[],[]) "    this code block is indented by two tabs\n\nThese should not be escaped:  \\$ \\\\ \\> \\[ \\{"
-,Header 1 ("lists",[],[]) [Str "Lists"]
-,Header 2 ("unordered",[],[]) [Str "Unordered"]
-,Para [Str "Asterisks",Space,Str "tight:"]
-,BulletList
- [[Para [Str "asterisk",Space,Str "1"]]
- ,[Para [Str "asterisk",Space,Str "2"]]
- ,[Para [Str "asterisk",Space,Str "3"]]]
-,Para [Str "Asterisks",Space,Str "loose:"]
-,BulletList
- [[Para [Str "asterisk",Space,Str "1"]]
- ,[Para [Str "asterisk",Space,Str "2"]]
- ,[Para [Str "asterisk",Space,Str "3"]]]
-,Para [Str "Pluses",Space,Str "tight:"]
-,BulletList
- [[Para [Str "Plus",Space,Str "1"]]
- ,[Para [Str "Plus",Space,Str "2"]]
- ,[Para [Str "Plus",Space,Str "3"]]]
-,Para [Str "Pluses",Space,Str "loose:"]
-,BulletList
- [[Para [Str "Plus",Space,Str "1"]]
- ,[Para [Str "Plus",Space,Str "2"]]
- ,[Para [Str "Plus",Space,Str "3"]]]
-,Para [Str "Minuses",Space,Str "tight:"]
-,BulletList
- [[Para [Str "Minus",Space,Str "1"]]
- ,[Para [Str "Minus",Space,Str "2"]]
- ,[Para [Str "Minus",Space,Str "3"]]]
-,Para [Str "Minuses",Space,Str "loose:"]
-,BulletList
- [[Para [Str "Minus",Space,Str "1"]]
- ,[Para [Str "Minus",Space,Str "2"]]
- ,[Para [Str "Minus",Space,Str "3"]]]
-,Header 2 ("ordered",[],[]) [Str "Ordered"]
-,Para [Str "Tight:"]
-,OrderedList (1,DefaultStyle,DefaultDelim)
- [[Para [Str "First"]]
- ,[Para [Str "Second"]]
- ,[Para [Str "Third"]]]
-,Para [Str "and:"]
-,OrderedList (1,DefaultStyle,DefaultDelim)
- [[Para [Str "One"]]
- ,[Para [Str "Two"]]
- ,[Para [Str "Three"]]]
-,Para [Str "Loose",Space,Str "using",Space,Str "tabs:"]
-,OrderedList (1,DefaultStyle,DefaultDelim)
- [[Para [Str "First"]]
- ,[Para [Str "Second"]]
- ,[Para [Str "Third"]]]
-,Para [Str "and",Space,Str "using",Space,Str "spaces:"]
-,OrderedList (1,DefaultStyle,DefaultDelim)
- [[Para [Str "One"]]
- ,[Para [Str "Two"]]
- ,[Para [Str "Three"]]]
-,Para [Str "Multiple",Space,Str "paragraphs:"]
-,OrderedList (1,DefaultStyle,DefaultDelim)
- [[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",SoftBreak,Str "dog's",Space,Str "back."]]
- ,[Para [Str "Item",Space,Str "2."]]
- ,[Para [Str "Item",Space,Str "3."]]]
-,Para [Str "List",Space,Str "styles:"]
-,OrderedList (1,DefaultStyle,DefaultDelim)
- []
-,OrderedList (1,LowerRoman,DefaultDelim)
- []
-,Header 2 ("nested",[],[]) [Str "Nested"]
-,BulletList
- [[Para [Str "Tab"]
-  ,BulletList
-   [[Para [Str "Tab"]
-    ,BulletList
-     [[Para [Str "Tab"]]]]]]]
-,Para [Str "Here's",Space,Str "another:"]
-,OrderedList (1,DefaultStyle,DefaultDelim)
- [[Para [Str "First"]]
- ,[Para [Str "Second:"]
-  ,BulletList
-   [[Para [Str "Fee"]]
-   ,[Para [Str "Fie"]]
-   ,[Para [Str "Foe"]]]]
- ,[Para [Str "Third"]]]
-,Para [Str "Same",Space,Str "thing",Space,Str "but",Space,Str "with",Space,Str "paragraphs:"]
-,OrderedList (1,DefaultStyle,DefaultDelim)
- [[Para [Str "First"]]
- ,[Para [Str "Second:"]
-  ,BulletList
-   [[Para [Str "Fee"]]
-   ,[Para [Str "Fie"]]
-   ,[Para [Str "Foe"]]]]
- ,[Para [Str "Third"]]]
-,Header 2 ("tabs-and-spaces",[],[]) [Str "Tabs",Space,Str "and",Space,Str "spaces"]
-,BulletList
- [[Para [Str "this",Space,Str "is",Space,Str "a",Space,Str "list",Space,Str "item",Space,Str "indented",Space,Str "with",Space,Str "tabs"]]
- ,[Para [Str "this",Space,Str "is",Space,Str "a",Space,Str "list",Space,Str "item",Space,Str "indented",Space,Str "with",Space,Str "spaces"]
-  ,BulletList
-   [[Para [Str "this",Space,Str "is",Space,Str "an",Space,Str "example",Space,Str "list",Space,Str "item",Space,Str "indented",Space,Str "with",Space,Str "tabs"]]
-   ,[Para [Str "this",Space,Str "is",Space,Str "an",Space,Str "example",Space,Str "list",Space,Str "item",Space,Str "indented",Space,Str "with",Space,Str "spaces"]]]]]
-,Header 2 ("fancy-list-markers",[],[]) [Str "Fancy",Space,Str "list",Space,Str "markers"]
-,Para [Str "Autonumbering:"]
-,OrderedList (1,DefaultStyle,DefaultDelim)
- [[Para [Str "Autonumber."]]
- ,[Para [Str "More."]
-  ,OrderedList (1,DefaultStyle,DefaultDelim)
-   [[Para [Str "Nested."]]]]]
-,Header 2 ("definition",[],[]) [Str "Definition"]
-,DefinitionList
- [([Str "Violin"],
-   [[Para [Str "Stringed",Space,Str "musical",Space,Str "instrument."]
-    ,Para [Str "Torture",Space,Str "device."]]])
- ,([Str "Cello",LineBreak,Str "Violoncello"],
-   [[Para [Str "Low-voiced",Space,Str "stringed",Space,Str "instrument."]]])]
-,Header 1 ("inline-markup",[],[]) [Str "Inline",Space,Str "Markup"]
-,Para [Str "This",Space,Str "is",Space,Emph [Str "emphasized"],Str ",",Space,Str "and",Space,Str "so",Space,Emph [Str "is",SoftBreak,Str "this"],Str "."]
-,Para [Str "This",Space,Str "is",Space,Strong [Str "strong"],Str ",",Space,Str "and",Space,Str "so",SoftBreak,Strong [Str "is",Space,Str "this"],Str "."]
-,Para [Str "Empty",Space,Strong [],Space,Str "and",Space,Emph [],Str "."]
-,Para [Str "An",SoftBreak,Emph [Link ("",[],[]) [Str "emphasized",SoftBreak,Str "link"] ("/url","")],Str "."]
-,Para [Strong [Emph [Str "This",Space,Str "is",Space,Str "strong",Space,Str "and",Space,Str "em."]]]
-,Para [Str "So",Space,Str "is",Space,Strong [Emph [Str "this"]],Space,Str "word."]
-,Para [Strong [Emph [Str "This",Space,Str "is",Space,Str "strong",Space,Str "and",Space,Str "em."]]]
-,Para [Str "So",Space,Str "is",Space,Strong [Emph [Str "this"]],Space,Str "word."]
-,Para [Str "This",Space,Str "is",Space,Str "code:",Space,Code ("",[],[]) ">",Str ",",Space,Code ("",[],[]) "$",Str ",",SoftBreak,Code ("",[],[]) "\\",Str ",",Space,Code ("",[],[]) "\\$",Str ",",SoftBreak,Code ("",[],[]) "<html>",Str "."]
-,Para [Str "This",Space,Str "is",Space,SmallCaps [Str "small",Space,Str "caps"],Str "."]
-,Para [Str "These",Space,Str "are",Space,Str "all",Space,Str "underlined:",Space,Str "foo",Space,Str "and",Space,Str "bar."]
-,Para [Str "These",Space,Str "are",Space,Str "all",Space,Str "strikethrough:",Space,Strikeout [Str "foo"],Str ",",SoftBreak,Strikeout [Str "bar"],Str ",",Space,Str "and",Space,Strikeout [Str "baz"],Str "."]
-,Header 1 ("smart-quotes-ellipses-dashes",[],[]) [Str "Smart",Space,Str "quotes,",Space,Str "ellipses,",Space,Str "dashes"]
-,Para [Str "\"Hello,\"",Space,Str "said",Space,Str "the",Space,Str "spider.",Space,Str "\"'Shelob'",Space,Str "is",Space,Str "my",Space,Str "name.\""]
-,Para [Str "'A',",Space,Str "'B',",Space,Str "and",Space,Str "'C'",Space,Str "are",Space,Str "letters."]
-,Para [Str "'Oak,'",Space,Str "'elm,'",Space,Str "and",Space,Str "'beech'",Space,Str "are",Space,Str "names",Space,Str "of",Space,Str "trees.",Space,Str "So",Space,Str "is",Space,Str "'pine.'"]
-,Para [Str "'He",Space,Str "said,",Space,Str "\"I",Space,Str "want",Space,Str "to",Space,Str "go.\"'",Space,Str "Were",Space,Str "you",Space,Str "alive",Space,Str "in",Space,Str "the",Space,Str "70's?"]
-,Para [Str "Here",Space,Str "is",Space,Str "some",Space,Str "quoted",Space,Str "'",Code ("",[],[]) "code",Str "'",Space,Str "and",Space,Str "a",SoftBreak,Str "\"",Link ("",[],[]) [Str "quoted",SoftBreak,Str "link"] ("http://example.com/?foo=1&bar=2",""),Str "\"."]
-,Para [Str "Some",Space,Str "dashes:",Space,Str "one---two",Space,Str "---",Space,Str "three--four",Space,Str "--",Space,Str "five."]
-,Para [Str "Dashes",Space,Str "between",Space,Str "numbers:",Space,Str "5-7,",Space,Str "255-66,",Space,Str "1987-1999."]
-,Para [Str "Ellipses...and.",Space,Str ".",Space,Str ".and",Space,Str ".",Space,Str ".",Space,Str ".",Space,Str "."]
-,Header 1 ("latex",[],[]) [Str "LaTeX"]
-,BulletList
- [[Para [Str "\\cite[22-23]{smith.1899}"]]
- ,[Para [Str "\\doublespacing"]]
- ,[Para [Str "$2+2=4$"]]
- ,[Para [Str "$x",Space,Str "\\in",Space,Str "y$"]]
- ,[Para [Str "$\\alpha",Space,Str "\\wedge",Space,Str "\\omega$"]]
- ,[Para [Str "$223$"]]
- ,[Para [Str "$p$-Tree"]]
- ,[Para [Str "$\\frac{d}{dx}f(x)=\\lim_{h\\to",Space,Str "0}\\frac{f(x+h)-f(x)}{h}$"]]
- ,[Para [Str "Here's",Space,Str "one",Space,Str "that",Space,Str "has",Space,Str "a",Space,Str "line",Space,Str "break",Space,Str "in",Space,Str "it:",Space,Str "$\\alpha",Space,Str "+",Space,Str "\\omega",Space,Str "\\times",SoftBreak,Str "x^2$."]]]
-,Para [Str "These",Space,Str "shouldn't",Space,Str "be",Space,Str "math:"]
-,BulletList
- [[Para [Str "To",Space,Str "get",Space,Str "the",Space,Str "famous",Space,Str "equation,",Space,Str "write",SoftBreak,Code ("",[],[]) "$e = mc^2$",Str "."]]
- ,[Para [Str "$22,000",Space,Str "is",Space,Str "a",Space,Emph [Str "lot"],Space,Str "of",Space,Str "money.",Space,Str "So",Space,Str "is",Space,Str "$34,000.",Space,Str "(It",SoftBreak,Str "worked",Space,Str "if",Space,Str "\"lot\"",Space,Str "is",Space,Str "emphasized.)"]]
- ,[Para [Str "Escaped",Space,Code ("",[],[]) "$",Str ":",Space,Str "$73",Space,Emph [Str "this",Space,Str "should",Space,Str "be",SoftBreak,Str "emphasized"],Space,Str "23$."]]]
-,Para [Str "Here's",Space,Str "a",Space,Str "LaTeX",Space,Str "table:"]
-,Para [Str "\\begin{tabular}{|l|l|}\\hline",Space,Str "Animal",Space,Str "&",Space,Str "Number",Space,Str "\\\\",Space,Str "\\hline",Space,Str "Dog",Space,Str "&",SoftBreak,Str "2",Space,Str "\\\\",Space,Str "Cat",Space,Str "&",Space,Str "1",Space,Str "\\\\",Space,Str "\\hline",Space,Str "\\end{tabular}"]
-,Header 1 ("special-characters",[],[]) [Str "Special",Space,Str "Characters"]
-,Para [Str "Here",Space,Str "is",Space,Str "some",Space,Str "unicode:"]
-,BulletList
- [[Para [Str "I",Space,Str "hat:",Space,Str "\206"]]
- ,[Para [Str "o",Space,Str "umlaut:",Space,Str "\246"]]
- ,[Para [Str "section:",Space,Str "\167"]]
- ,[Para [Str "set",Space,Str "membership:",Space,Str "elem"]]
- ,[Para [Str "copyright:",Space,Str "\169"]]]
-,Para [Str "AT&T",Space,Str "has",Space,Str "an",Space,Str "ampersand",Space,Str "in",Space,Str "their",Space,Str "name."]
-,Para [Str "AT&T",Space,Str "is",Space,Str "another",Space,Str "way",Space,Str "to",Space,Str "write",Space,Str "it."]
-,Para [Str "This",Space,Str "&",Space,Str "that."]
-,Para [Str "4",Space,Str "<",Space,Str "5."]
-,Para [Str "6",Space,Str ">",Space,Str "5."]
-,Para [Str "Backslash:",Space,Str "\\"]
-,Para [Str "Backtick:",Space,Str "`"]
-,Para [Str "Asterisk:",Space,Str "*"]
-,Para [Str "Underscore:",Space,Str "_"]
-,Para [Str "Left",Space,Str "brace:",Space,Str "{"]
-,Para [Str "Right",Space,Str "brace:",Space,Str "}"]
-,Para [Str "Left",Space,Str "bracket:",Space,Str "["]
-,Para [Str "Right",Space,Str "bracket:",Space,Str "]"]
-,Para [Str "Left",Space,Str "paren:",Space,Str "("]
-,Para [Str "Right",Space,Str "paren:",Space,Str ")"]
-,Para [Str "Greater-than:",Space,Str ">"]
-,Para [Str "Hash:",Space,Str "#"]
-,Para [Str "Period:",Space,Str "."]
-,Para [Str "Bang:",Space,Str "!"]
-,Para [Str "Plus:",Space,Str "+"]
-,Para [Str "Minus:",Space,Str "-"]
-,Header 1 ("links",[],[]) [Str "Links"]
-,Header 2 ("explicit",[],[]) [Str "Explicit"]
-,Para [Str "Just",Space,Str "a",SoftBreak,Link ("",[],[]) [Str "URL"] ("/url/",""),Str "."]
-,Para [Link ("",[],[]) [Str "URL",SoftBreak,Str "and",Space,Str "title"] ("/url/","title"),Str "."]
-,Para [Link ("",[],[]) [Str "URL",SoftBreak,Str "and",Space,Str "title"] ("/url/","title preceded by two spaces"),Str "."]
-,Para [Link ("",[],[]) [Str "URL",SoftBreak,Str "and",Space,Str "title"] ("/url/","title preceded by a tab"),Str "."]
-,Para [Link ("",[],[]) [Str "URL",SoftBreak,Str "and",Space,Str "title"] ("/url/","title with \"quotes\" in it")]
-,Para [Link ("",[],[]) [Str "URL",SoftBreak,Str "and",Space,Str "title"] ("/url/","title with single quotes")]
-,Para [Str "Email",Space,Str "link",Space,Str "(nobody",Space,Str "[at]",Space,Str "nowhere.net)"]
-,Para [Link ("",[],[]) [Str "Empty"] ("",""),Str "."]
-,Header 2 ("reference",[],[]) [Str "Reference"]
-,Para [Str "Foo",SoftBreak,Link ("",[],[]) [Str "bar"] ("/url/",""),Str "."]
-,Para [Str "Foo",SoftBreak,Link ("",[],[]) [Str "bar"] ("/url/",""),Str "."]
-,Para [Str "Foo",SoftBreak,Link ("",[],[]) [Str "bar"] ("/url/",""),Str "."]
-,Para [Str "With",Space,Link ("",[],[]) [Str "embedded",SoftBreak,Str "[brackets]"] ("/url/",""),Str "."]
-,Para [Link ("",[],[]) [Str "b"] ("/url/",""),Space,Str "by",SoftBreak,Str "itself",Space,Str "should",Space,Str "be",Space,Str "a",Space,Str "link."]
-,Para [Str "Indented",SoftBreak,Link ("",[],[]) [Str "once"] ("/url",""),Str "."]
-,Para [Str "Indented",SoftBreak,Link ("",[],[]) [Str "twice"] ("/url",""),Str "."]
-,Para [Str "Indented",SoftBreak,Link ("",[],[]) [Str "thrice"] ("/url",""),Str "."]
-,Para [Str "This",Space,Str "should",Space,Str "[not]",Space,Str "be",Space,Str "a",Space,Str "link."]
-,CodeBlock ("",[],[]) "[not]: /url"
-,Para [Str "Foo",SoftBreak,Link ("",[],[]) [Str "bar"] ("/url/","Title with \"quotes\" inside"),Str "."]
-,Para [Str "Foo",SoftBreak,Link ("",[],[]) [Str "biz"] ("/url/","Title with \"quote\" inside"),Str "."]
-,Header 2 ("with-ampersands",[],[]) [Str "With",Space,Str "ampersands"]
-,Para [Str "Here's",Space,Str "a",SoftBreak,Link ("",[],[]) [Str "link",SoftBreak,Str "with",Space,Str "an",Space,Str "ampersand",Space,Str "in",Space,Str "the",Space,Str "URL"] ("http://example.com/?foo=1&bar=2",""),Str "."]
-,Para [Str "Here's",Space,Str "a",Space,Str "link",Space,Str "with",Space,Str "an",Space,Str "amersand",Space,Str "in",Space,Str "the",Space,Str "link",Space,Str "text:",SoftBreak,Link ("",[],[]) [Str "AT&T"] ("http://att.com/","AT&T"),Str "."]
-,Para [Str "Here's",Space,Str "an",SoftBreak,Link ("",[],[]) [Str "inline",SoftBreak,Str "link"] ("/script?foo=1&bar=2",""),Str "."]
-,Para [Str "Here's",Space,Str "an",SoftBreak,Link ("",[],[]) [Str "inline",SoftBreak,Str "link",Space,Str "in",Space,Str "pointy",Space,Str "braces"] ("/script?foo=1&bar=2",""),Str "."]
-,Header 2 ("autolinks",[],[]) [Str "Autolinks"]
-,Para [Str "With",Space,Str "an",Space,Str "ampersand:",SoftBreak,Link ("",[],[]) [Str "http://example.com/?foo=1&bar=2"] ("http://example.com/?foo=1&bar=2","")]
-,BulletList
- [[Para [Str "In",Space,Str "a",Space,Str "list?"]]
- ,[Para [Link ("",[],[]) [Str "http://example.com/"] ("http://example.com/","")]]
- ,[Para [Str "It",Space,Str "should."]]]
-,Para [Str "An",Space,Str "e-mail",Space,Str "address:",Space,Str "nobody",Space,Str "[at]",Space,Str "nowhere.net"]
-,BlockQuote
- [Para [Str "Blockquoted:",SoftBreak,Link ("",[],[]) [Str "http://example.com/"] ("http://example.com/","")]]
-,Para [Str "Auto-links",Space,Str "should",Space,Str "not",Space,Str "occur",Space,Str "here:",SoftBreak,Code ("",[],[]) "<http://example.com/>"]
-,CodeBlock ("",[],[]) "or here: <http://example.com/>"
-,Header 1 ("images",[],[]) [Str "Images"]
-,Para [Str "From",Space,Str "\"Voyage",Space,Str "dans",Space,Str "la",Space,Str "Lune\"",Space,Str "by",Space,Str "Georges",Space,Str "Melies",Space,Str "(1902):"]
-,Para [Image ("",[],[]) [] ("lalune.jpg","Voyage dans la Lune")]
-,Para [Str "Here",Space,Str "is",Space,Str "a",Space,Str "movie",SoftBreak,Image ("",[],[]) [] ("movie.jpg",""),SoftBreak,Str "icon."]
-,Header 1 ("footnotes",[],[]) [Str "Footnotes"]
-,Para [Str "Here",Space,Str "is",Space,Str "a",Space,Str "footnote",Space,Str "reference",Link ("",[],[]) [Str "(1)"] ("#note_1",""),Str ",",SoftBreak,Str "and",SoftBreak,Str "another",Link ("",[],[]) [Str "(longnote)"] ("#note_longnote",""),Str ".",SoftBreak,Str "This",Space,Str "should",Space,Emph [Str "not"],Space,Str "be",Space,Str "a",Space,Str "footnote",Space,Str "reference,",Space,Str "because",Space,Str "it",SoftBreak,Str "contains",Space,Str "a",Space,Str "space^(my",Space,Str "note)."]
-,Para [Link ("",[],[]) [Str "(1)"] ("#ref_1",""),Space,Str "Here",Space,Str "is",Space,Str "the",Space,Str "footnote.",Space,Str "It",Space,Str "can",SoftBreak,Str "go",Space,Str "anywhere",Space,Str "in",Space,Str "the",Space,Str "document,",Space,Str "not",Space,Str "just",Space,Str "at",Space,Str "the",Space,Str "end."]
-,Para [Link ("",[],[]) [Str "(longnote)"] ("#ref_longnote",""),Space,Str "Here's",SoftBreak,Str "the",Space,Str "other",Space,Str "note.",Space,Str "This",Space,Str "one",Space,Str "contains",Space,Str "multiple",Space,Str "blocks."]
-,Para [Str "Caret",Space,Str "characters",Space,Str "are",Space,Str "used",Space,Str "to",Space,Str "indicate",Space,Str "that",Space,Str "the",Space,Str "blocks",Space,Str "all",Space,Str "belong",Space,Str "to",SoftBreak,Str "a",Space,Str "single",Space,Str "footnote",Space,Str "(as",Space,Str "with",Space,Str "block",Space,Str "quotes)."]
-,CodeBlock ("",[],[]) "  { <code> }"
-,Para [Str "If",Space,Str "you",Space,Str "want,",Space,Str "you",Space,Str "can",Space,Str "use",Space,Str "a",Space,Str "caret",Space,Str "at",Space,Str "the",Space,Str "beginning",Space,Str "of",Space,Str "every",Space,Str "line,",Space,Str "as",SoftBreak,Str "with",Space,Str "blockquotes,",Space,Str "but",Space,Str "all",Space,Str "that",Space,Str "you",Space,Str "need",Space,Str "is",Space,Str "a",Space,Str "caret",Space,Str "at",Space,Str "the",Space,Str "beginning",SoftBreak,Str "of",Space,Str "the",Space,Str "first",Space,Str "line",Space,Str "of",Space,Str "the",Space,Str "block",Space,Str "and",Space,Str "any",Space,Str "preceding",Space,Str "blank",Space,Str "lines."]
-,Para [Str "text",Space,Emph [Str "Leading",Space,Str "space"]]
-,Para [Emph [Str "Trailing",Space,Str "space"],Space,Str "text"]
-,Para [Str "text",Space,Emph [Str "Leading",Space,Str "spaces"]]
-,Para [Emph [Str "Trailing",Space,Str "spaces"],Space,Str "text"]
-,Header 1 ("tables",[],[]) [Str "Tables"]
-,Header 2 ("tables-with-headers",[],[]) [Str "Tables",Space,Str "with",Space,Str "Headers"]
-,Table [] [AlignLeft,AlignLeft,AlignLeft] [0.0,0.0,0.0]
- [[Para [Str "X"]]
- ,[Para [Str "Y"]]
- ,[Para [Str "Z"]]]
- [[[Para [Str "1"]]
-  ,[Para [Str "2"]]
-  ,[Para [Str "3"]]]
- ,[[Para [Str "4"]]
-  ,[Para [Str "5"]]
-  ,[Para [Str "6"]]]]
-,Table [] [AlignLeft,AlignLeft,AlignLeft] [0.0,0.0,0.0]
- [[Para [Str "X"]]
- ,[Para [Str "Y"]]
- ,[Para [Str "Z"]]]
- [[[Para [Str "1"]]
-  ,[Para [Str "2"]]
-  ,[Para [Str "3"]]]
- ,[[Para [Str "4"]]
-  ,[Para [Str "5"]]
-  ,[Para [Str "6"]]]]
-,Table [] [AlignLeft,AlignLeft,AlignLeft] [0.0,0.0,0.0]
- [[Para [Str "X"]]
- ,[Para [Str "Y"]]
- ,[Para [Str "Z"]]]
- [[[Para [Str "1"]]
-  ,[Para [Str "2"]]
-  ,[Para [Str "3"]]]
- ,[[Para [Str "4"]]
-  ,[Para [Str "5"]]
-  ,[Para [Str "6"]]]]
-,Table [] [AlignLeft,AlignLeft,AlignLeft] [0.0,0.0,0.0]
- [[Para [Str "X"]]
- ,[Para [Str "Y"]]
- ,[Para [Str "Z"]]]
- [[[Para [Str "1"]]
-  ,[Para [Str "2"]]
-  ,[Para [Str "3"]]]
- ,[[Para [Str "4"]]
-  ,[Para [Str "5"]]
-  ,[Para [Str "6"]]]]
-,Table [] [AlignLeft,AlignLeft,AlignLeft] [0.0,0.0,0.0]
- [[Para [Str "X"]]
- ,[Para [Str "Y"]]
- ,[Para [Str "Z"]]]
- [[[Para [Str "1"]]
-  ,[Para [Str "2"]]
-  ,[Para [Str "3"]]]
- ,[[Para [Str "4"]]
-  ,[Para [Str "5"]]
-  ,[Para [Str "6"]]]]
-,Table [] [AlignLeft,AlignLeft,AlignLeft] [0.0,0.0,0.0]
- [[Para [Str "X"]]
- ,[Para [Str "Y"]]
- ,[Para [Str "Z"]]]
- [[[Para [Str "1"]]
-  ,[Para [Str "2"]]
-  ,[Para [Str "3"]]]
- ,[[Para [Str "4"]]
-  ,[Para [Str "5"]]
-  ,[Para [Str "6"]]]]
-,Table [] [AlignLeft,AlignLeft,AlignLeft] [0.0,0.0,0.0]
- [[Para [Str "X"]]
- ,[Para [Str "Y"]]
- ,[Para [Str "Z"]]]
- [[[Para [Str "1"]]
-  ,[Para [Str "2"]]
-  ,[Para [Str "3"]]]
- ,[[Para [Str "4"]]
-  ,[Para [Str "5"]]
-  ,[Para [Str "6"]]]]
-,Table [] [AlignLeft,AlignLeft,AlignLeft] [0.0,0.0,0.0]
- [[Para [Str "X"]]
- ,[Para [Str "Y"]]
- ,[Para [Str "Z"]]]
- [[[Para [Str "1"]]
-  ,[Para [Str "2"]]
-  ,[Para [Str "3"]]]
- ,[[Para [Str "4"]]
-  ,[Para [Str "5"]]
-  ,[Para [Str "6"]]]]
-,Table [] [AlignLeft,AlignLeft,AlignLeft] [0.0,0.0,0.0]
- [[Para [Str "X"]]
- ,[Para [Str "Y"]]
- ,[Para [Str "Z"]]]
- [[[Para [Str "1"]]
-  ,[Para [Str "2"]]
-  ,[Para [Str "3"]]]
- ,[[Para [Str "4"]]
-  ,[Para [Str "5"]]
-  ,[Para [Str "6"]]]]
-,Header 2 ("tables-without-headers",[],[]) [Str "Tables",Space,Str "without",Space,Str "Headers"]
-,Table [] [AlignLeft,AlignLeft,AlignLeft] [0.0,0.0,0.0]
- [[]
- ,[]
- ,[]]
- [[[Para [Str "1"]]
-  ,[Para [Str "2"]]
-  ,[Para [Str "3"]]]
- ,[[Para [Str "4"]]
-  ,[Para [Str "5"]]
-  ,[Para [Str "6"]]]]
-,Table [] [AlignLeft,AlignLeft,AlignLeft] [0.0,0.0,0.0]
- [[]
- ,[]
- ,[]]
- [[[Para [Str "1"]]
-  ,[Para [Str "2"]]
-  ,[Para [Str "3"]]]
- ,[[Para [Str "4"]]
-  ,[Para [Str "5"]]
-  ,[Para [Str "6"]]]]
-,Table [] [AlignLeft,AlignLeft,AlignLeft] [0.0,0.0,0.0]
- [[]
- ,[]
- ,[]]
- [[[Para [Str "1"]]
-  ,[Para [Str "2"]]
-  ,[Para [Str "3"]]]
- ,[[Para [Str "4"]]
-  ,[Para [Str "5"]]
-  ,[Para [Str "6"]]]]
-,Table [] [AlignLeft,AlignLeft,AlignLeft] [0.0,0.0,0.0]
- [[]
- ,[]
- ,[]]
- [[[Para [Str "1"]]
-  ,[Para [Str "2"]]
-  ,[Para [Str "3"]]]
- ,[[Para [Str "4"]]
-  ,[Para [Str "5"]]
-  ,[Para [Str "6"]]]]
-,Header 2 ("empty-tables",[],[]) [Str "Empty",Space,Str "Tables"]
-,Para [Str "This",Space,Str "section",Space,Str "should",Space,Str "be",Space,Str "empty."]]
+Pandoc
+  Meta
+    { unMeta =
+        fromList
+          [ ( "author"
+            , MetaList
+                [ MetaInlines [ Str "John" , Space , Str "MacFarlane" ]
+                , MetaInlines [ Str "Anonymous" ]
+                ]
+            )
+          , ( "copyright"
+            , MetaMap
+                (fromList
+                   [ ( "holder" , MetaString "MacFarlane et al" )
+                   , ( "statement"
+                     , MetaString "\169 2023, MacFarlane et al"
+                     )
+                   , ( "year" , MetaString "2023" )
+                   ])
+            )
+          , ( "license"
+            , MetaMap
+                (fromList
+                   [ ( "link"
+                     , MetaString
+                         "https://creativecommons.org/licenses/by/4.0/"
+                     )
+                   , ( "text"
+                     , MetaString
+                         "This document is distributed under a Creative Commons Attribution 4.0 International license."
+                     )
+                   , ( "type" , MetaString "open-access" )
+                   ])
+            )
+          , ( "references"
+            , MetaList
+                [ MetaMap (fromList [ ( "id" , MetaString "note_1" ) ])
+                , MetaMap
+                    (fromList [ ( "id" , MetaString "note_longnote" ) ])
+                ]
+            )
+          , ( "title"
+            , MetaInlines
+                [ Str "Pandoc"
+                , Space
+                , Str "Test"
+                , Space
+                , Str "Suite"
+                ]
+            )
+          ]
+    }
+  [ Para
+      [ Str "This"
+      , Space
+      , Str "is"
+      , Space
+      , Str "a"
+      , Space
+      , Str "set"
+      , Space
+      , Str "of"
+      , Space
+      , Str "tests"
+      , Space
+      , Str "for"
+      , Space
+      , Str "pandoc."
+      , Space
+      , Str "Most"
+      , Space
+      , Str "of"
+      , Space
+      , Str "them"
+      , Space
+      , Str "are"
+      , Space
+      , Str "adapted"
+      , Space
+      , Str "from"
+      , Space
+      , Str "John"
+      , Space
+      , Str "Gruber's"
+      , Space
+      , Str "markdown"
+      , Space
+      , Str "test"
+      , Space
+      , Str "suite."
+      ]
+  , Header 1 ( "headers" , [] , [] ) [ Str "Headers" ]
+  , Header
+      2
+      ( "level-2-with-an-embedded-link" , [] , [] )
+      [ Str "Level"
+      , Space
+      , Str "2"
+      , Space
+      , Str "with"
+      , Space
+      , Str "an"
+      , SoftBreak
+      , Link
+          ( "" , [] , [] )
+          [ Str "embedded" , SoftBreak , Str "link" ]
+          ( "/url" , "" )
+      ]
+  , Header
+      3
+      ( "level-3-with-emphasis" , [] , [] )
+      [ Str "Level"
+      , Space
+      , Str "3"
+      , Space
+      , Str "with"
+      , Space
+      , Emph [ Str "emphasis" ]
+      ]
+  , Header
+      4 ( "level-4" , [] , [] ) [ Str "Level" , Space , Str "4" ]
+  , Header
+      5 ( "level-5" , [] , [] ) [ Str "Level" , Space , Str "5" ]
+  , Header
+      1 ( "level-1" , [] , [] ) [ Str "Level" , Space , Str "1" ]
+  , Header
+      2
+      ( "level-2-with-emphasis" , [] , [] )
+      [ Str "Level"
+      , Space
+      , Str "2"
+      , Space
+      , Str "with"
+      , Space
+      , Emph [ Str "emphasis" ]
+      ]
+  , Header
+      3 ( "level-3" , [] , [] ) [ Str "Level" , Space , Str "3" ]
+  , Para
+      [ Str "with"
+      , Space
+      , Str "no"
+      , Space
+      , Str "blank"
+      , Space
+      , Str "line"
+      ]
+  , Header
+      2 ( "level-2" , [] , [] ) [ Str "Level" , Space , Str "2" ]
+  , Para
+      [ Str "with"
+      , Space
+      , Str "no"
+      , Space
+      , Str "blank"
+      , Space
+      , Str "line"
+      ]
+  , Header 1 ( "paragraphs" , [] , [] ) [ Str "Paragraphs" ]
+  , Para
+      [ Str "Here's"
+      , Space
+      , Str "a"
+      , Space
+      , Str "regular"
+      , Space
+      , Str "paragraph."
+      ]
+  , Para
+      [ Str "In"
+      , Space
+      , Str "Markdown"
+      , Space
+      , Str "1.0.0"
+      , Space
+      , Str "and"
+      , Space
+      , Str "earlier."
+      , Space
+      , Str "Version"
+      , Space
+      , Str "8."
+      , Space
+      , Str "This"
+      , Space
+      , Str "line"
+      , Space
+      , Str "turns"
+      , Space
+      , Str "into"
+      , Space
+      , Str "a"
+      , Space
+      , Str "list"
+      , Space
+      , Str "item."
+      , Space
+      , Str "Because"
+      , Space
+      , Str "a"
+      , Space
+      , Str "hard-wrapped"
+      , Space
+      , Str "line"
+      , Space
+      , Str "in"
+      , Space
+      , Str "the"
+      , Space
+      , Str "middle"
+      , Space
+      , Str "of"
+      , Space
+      , Str "a"
+      , Space
+      , Str "paragraph"
+      , Space
+      , Str "looked"
+      , Space
+      , Str "like"
+      , Space
+      , Str "a"
+      , Space
+      , Str "list"
+      , Space
+      , Str "item."
+      ]
+  , Para
+      [ Str "Here's"
+      , Space
+      , Str "one"
+      , Space
+      , Str "with"
+      , Space
+      , Str "a"
+      , Space
+      , Str "bullet."
+      , Space
+      , Str "*"
+      , Space
+      , Str "criminey."
+      ]
+  , Para
+      [ Str "There"
+      , Space
+      , Str "should"
+      , Space
+      , Str "be"
+      , Space
+      , Str "a"
+      , Space
+      , Strong
+          [ Str "hard"
+          , Space
+          , Str "line"
+          , Space
+          , Str "break"
+          , LineBreak
+          ]
+      , Str "here."
+      ]
+  , Header 1 ( "statements" , [] , [] ) [ Str "Statements" ]
+  , Header
+      2 ( "" , [] , [] ) [ Str "CAP" , Space , Str "TITLE" ]
+  , Para
+      [ Str "Some"
+      , Space
+      , Str "text"
+      , Space
+      , Str "to"
+      , Space
+      , Str "make"
+      , Space
+      , Str "this"
+      , Space
+      , Str "regular"
+      ]
+  , Header
+      1
+      ( "block-quotes" , [] , [] )
+      [ Str "Block" , Space , Str "Quotes" ]
+  , Para [ Str "E-mail" , Space , Str "style:" ]
+  , BlockQuote
+      [ Para
+          [ Str "This"
+          , Space
+          , Str "is"
+          , Space
+          , Str "a"
+          , Space
+          , Str "block"
+          , Space
+          , Str "quote."
+          , Space
+          , Str "It"
+          , Space
+          , Str "is"
+          , Space
+          , Str "pretty"
+          , Space
+          , Str "short."
+          ]
+      ]
+  , BlockQuote
+      [ Para
+          [ Str "Code"
+          , Space
+          , Str "in"
+          , Space
+          , Str "a"
+          , Space
+          , Str "block"
+          , Space
+          , Str "quote:"
+          ]
+      , CodeBlock
+          ( "" , [] , [] ) "sub status {\n    print \"working\";\n}"
+      , Para [ Str "A" , Space , Str "list:" ]
+      , OrderedList
+          ( 1 , DefaultStyle , DefaultDelim )
+          [ [ Para [ Str "item" , Space , Str "one" ] ]
+          , [ Para [ Str "item" , Space , Str "two" ] ]
+          ]
+      , Para
+          [ Str "Nested"
+          , Space
+          , Str "block"
+          , Space
+          , Str "quotes:"
+          ]
+      , BlockQuote [ Para [ Str "nested" ] ]
+      , BlockQuote [ Para [ Str "nested" ] ]
+      ]
+  , Para
+      [ Str "This"
+      , Space
+      , Str "should"
+      , Space
+      , Str "not"
+      , Space
+      , Str "be"
+      , Space
+      , Str "a"
+      , Space
+      , Str "block"
+      , Space
+      , Str "quote:"
+      , Space
+      , Str "2"
+      , Space
+      , Str ">"
+      , Space
+      , Str "1."
+      ]
+  , Para [ Str "Box-style:" ]
+  , BlockQuote
+      [ Para [ Str "Example:" ]
+      , CodeBlock
+          ( "" , [] , [] ) "sub status {\n    print \"working\";\n}"
+      ]
+  , BlockQuote
+      [ OrderedList
+          ( 1 , DefaultStyle , DefaultDelim )
+          [ [ Para [ Str "do" , Space , Str "laundry" ] ]
+          , [ Para
+                [ Str "take"
+                , Space
+                , Str "out"
+                , Space
+                , Str "the"
+                , Space
+                , Str "trash"
+                ]
+            ]
+          ]
+      ]
+  , Para
+      [ Str "Here's"
+      , Space
+      , Str "a"
+      , Space
+      , Str "nested"
+      , Space
+      , Str "one:"
+      ]
+  , BlockQuote
+      [ Para [ Str "Joe" , Space , Str "said:" ]
+      , BlockQuote
+          [ Para
+              [ Str "Don't" , Space , Str "quote" , Space , Str "me." ]
+          ]
+      ]
+  , Para
+      [ Str "And"
+      , Space
+      , Str "a"
+      , Space
+      , Str "following"
+      , Space
+      , Str "paragraph."
+      ]
+  , Para
+      [ Str "Here"
+      , Space
+      , Str "is"
+      , Space
+      , Str "a"
+      , Space
+      , Str "block"
+      , Space
+      , Str "quote"
+      , Space
+      , Str "inside"
+      , Space
+      , Str "a"
+      , Space
+      , Str "paragraph."
+      , Space
+      , Str "Start"
+      , Space
+      , Str "of"
+      , Space
+      , Str "a"
+      , Space
+      , Str "paragraph"
+      , Space
+      , Str "is"
+      , Space
+      , Str "here,"
+      , Space
+      , Str "and"
+      , Space
+      , Str "the"
+      , Space
+      , Str "quote"
+      , Space
+      , Str "is"
+      , Space
+      , Str "below:"
+      ]
+  , BlockQuote
+      [ Para
+          [ Str "My" , Space , Str "block" , Space , Str "quote" ]
+      ]
+  , Para
+      [ Str "End"
+      , Space
+      , Str "of"
+      , Space
+      , Str "a"
+      , Space
+      , Str "paragraph"
+      ]
+  , Header 1 ( "formulae" , [] , [] ) [ Str "Formulae" ]
+  , Header
+      2
+      ( "inline-formulae" , [] , [] )
+      [ Str "Inline"
+      , Space
+      , Str "formulae"
+      , Space
+      , Str "with"
+      , Space
+      , Emph [ Str "inline-formula" ]
+      ]
+  , Para
+      [ Strong
+          [ Str "Inside" , Space , Str "a" , Space , Str "paragraph" ]
+      , Str ","
+      , Space
+      , Str "should"
+      , Space
+      , Str "be"
+      , Space
+      , Str "natively"
+      , Space
+      , Str "coded"
+      , Space
+      , Str "inside"
+      , Space
+      , Str "the"
+      , Space
+      , Str "paragraph,"
+      , Space
+      , Str "and"
+      , Space
+      , Str "show"
+      , Space
+      , Str "inline:"
+      ]
+  , Para
+      [ Str "Einstein"
+      , Space
+      , Str "showed"
+      , Space
+      , Str "that"
+      , Space
+      , Math InlineMath "e=mc^2"
+      , Str "."
+      , SoftBreak
+      , Str "This"
+      , Space
+      , Str "formula"
+      , Space
+      , Str "is"
+      , Space
+      , Str "important"
+      , Space
+      , Str "because\8230"
+      ]
+  , Header
+      2
+      ( "disp-formulae" , [] , [] )
+      [ Str "Block"
+      , Space
+      , Str "formulae"
+      , Space
+      , Str "with"
+      , Space
+      , Emph [ Str "disp-formula" ]
+      ]
+  , Para
+      [ Strong
+          [ Str "Inside" , Space , Str "a" , Space , Str "paragraph" ]
+      , Str ","
+      , Space
+      , Str "should"
+      , Space
+      , Str "be"
+      , Space
+      , Str "natively"
+      , Space
+      , Str "coded"
+      , Space
+      , Str "inside"
+      , Space
+      , Str "the"
+      , Space
+      , Str "paragraph,"
+      , Space
+      , Str "but"
+      , Space
+      , Str "show"
+      , Space
+      , Str "as"
+      , Space
+      , Str "block:"
+      ]
+  , Para
+      [ Str "Einstein"
+      , Space
+      , Str "showed"
+      , Space
+      , Str "that"
+      , Space
+      , Math DisplayMath "e=mc^2"
+      , Str "."
+      , SoftBreak
+      , Str "This"
+      , Space
+      , Str "formula"
+      , Space
+      , Str "is"
+      , Space
+      , Str "important"
+      , Space
+      , Str "because\8230"
+      ]
+  , Para
+      [ Strong
+          [ Str "Outside"
+          , Space
+          , Str "a"
+          , Space
+          , Str "paragraph"
+          ]
+      , Str ","
+      , Space
+      , Str "should"
+      , Space
+      , Str "show"
+      , Space
+      , Str "as"
+      , Space
+      , Str "block:"
+      ]
+  , Para
+      [ Str "Einstein"
+      , Space
+      , Str "showed"
+      , Space
+      , Str "that"
+      ]
+  , Div
+      ( "" , [ "disp-formula" ] , [] )
+      [ Para [ Math DisplayMath "e=mc^2" ] ]
+  , Para
+      [ Str "This"
+      , Space
+      , Str "formula"
+      , Space
+      , Str "is"
+      , Space
+      , Str "important"
+      , Space
+      , Str "because\8230"
+      ]
+  , Header
+      2
+      ( "no-formula-wrapper" , [] , [] )
+      [ Str "Without"
+      , Space
+      , Str "a"
+      , Space
+      , Str "formula"
+      , Space
+      , Str "wrapper"
+      ]
+  , Para
+      [ Strong
+          [ Str "Inside" , Space , Str "a" , Space , Str "paragraph" ]
+      , Str ","
+      , Space
+      , Str "should"
+      , Space
+      , Str "show"
+      , Space
+      , Str "inline:"
+      ]
+  , Para
+      [ Str "Einstein"
+      , Space
+      , Str "showed"
+      , Space
+      , Str "that"
+      , Space
+      , Math InlineMath "e=mc^2"
+      , Str "."
+      , SoftBreak
+      , Str "This"
+      , Space
+      , Str "formula"
+      , Space
+      , Str "is"
+      , Space
+      , Str "important"
+      , Space
+      , Str "because\8230"
+      ]
+  , Para
+      [ Strong
+          [ Str "Outside"
+          , Space
+          , Str "a"
+          , Space
+          , Str "paragraph"
+          ]
+      , Str ","
+      , Space
+      , Str "should"
+      , Space
+      , Str "show"
+      , Space
+      , Str "as"
+      , Space
+      , Str "block:"
+      ]
+  , Para
+      [ Str "Einstein"
+      , Space
+      , Str "showed"
+      , Space
+      , Str "that"
+      ]
+  , Para [ Math DisplayMath "e=mc^2" ]
+  , Para
+      [ Str "This"
+      , Space
+      , Str "formula"
+      , Space
+      , Str "is"
+      , Space
+      , Str "important"
+      , Space
+      , Str "because\8230"
+      ]
+  , Header
+      2
+      ( "misc-formulae" , [] , [] )
+      [ Str "Formulae"
+      , Space
+      , Str "with"
+      , Space
+      , Str "miscelaneus"
+      , Space
+      , Str "elements"
+      ]
+  , Para
+      [ Str "Regardless"
+      , Space
+      , Str "of"
+      , Space
+      , Str "whether"
+      , Space
+      , Str "or"
+      , Space
+      , Str "not"
+      , Space
+      , Str "they"
+      , Space
+      , Str "are"
+      , Space
+      , Str "inside"
+      , Space
+      , Str "a"
+      , Space
+      , Str "paragraph,"
+      , Space
+      , Str "should"
+      , Space
+      , Str "be"
+      , Space
+      , Str "wrapped"
+      , Space
+      , Str "in"
+      , Space
+      , Str "a"
+      , Space
+      , Str "div,"
+      , Space
+      , Str "and"
+      , Space
+      , Str "displayed"
+      , Space
+      , Str "in"
+      , Space
+      , Str "a"
+      , Space
+      , Str "block:"
+      ]
+  , Para
+      [ Strong
+          [ Str "Inside"
+          , Space
+          , Str "a"
+          , Space
+          , Str "paragraph:"
+          ]
+      ]
+  , Para
+      [ Str "Einstein"
+      , Space
+      , Str "definitely"
+      , Space
+      , Str "showed"
+      , Space
+      , Str "that"
+      ]
+  , Div
+      ( "" , [ "disp-formula" ] , [] )
+      [ Para [ Str "Abstract" , Space , Str "text" ]
+      , Para
+          [ Image
+              ( "graphic001"
+              , [ "This"
+                , "is"
+                , "the"
+                , "role"
+                , "of"
+                , "the"
+                , "graphic"
+                ]
+              , []
+              )
+              [ Str "Alternative"
+              , Space
+              , Str "text"
+              , Space
+              , Str "of"
+              , Space
+              , Str "the"
+              , Space
+              , Str "graphic"
+              ]
+              ( "https://lh3.googleusercontent.com/dB7iirJ3ncQaVMBGE2YX-WCeoAVIChb6NAzoFcKCFChMsrixJvD7ZRbvcaC-ceXEzXYaoH4K5vaoRDsUyBHFkpIDPnsn3bnzovbvi0a2Gg=s660"
+              , "This is the title of the graphic"
+              )
+          ]
+      , Para [ Math DisplayMath "e=mc^2" ]
+      ]
+  , Para
+      [ Str "."
+      , SoftBreak
+      , Str "This"
+      , Space
+      , Str "formula"
+      , Space
+      , Str "is"
+      , Space
+      , Str "important"
+      , Space
+      , Str "because\8230"
+      ]
+  , Para
+      [ Strong
+          [ Str "Outside"
+          , Space
+          , Str "of"
+          , Space
+          , Str "a"
+          , Space
+          , Str "paragraph:"
+          ]
+      ]
+  , Para
+      [ Str "Paragraph"
+      , Space
+      , Str "before:"
+      , Space
+      , Str "Einstein"
+      , Space
+      , Str "showed"
+      , Space
+      , Str "that"
+      ]
+  , Div
+      ( "" , [ "disp-formula" ] , [] )
+      [ Para [ Str "Abstract" , Space , Str "text" ]
+      , Para
+          [ Image
+              ( "graphic003" , [] , [] )
+              [ Str "Alternative"
+              , Space
+              , Str "text"
+              , Space
+              , Str "1"
+              ]
+              ( "Title 3" , "" )
+          ]
+      , Para [ Math DisplayMath "e=mc^2" ]
+      ]
+  , Para
+      [ Str "This"
+      , Space
+      , Str "formula"
+      , Space
+      , Str "is"
+      , Space
+      , Str "important"
+      , Space
+      , Str "because\8230"
+      ]
+  , Figure
+      ( "fig-1" , [] , [] )
+      (Caption Nothing [ Plain [ Str "bar" ] ])
+      [ Plain [ Str "alternative-decription" ]
+      , Para [ Image ( "" , [] , [] ) [] ( "foo.png" , "" ) ]
+      ]
+  , Header
+      1
+      ( "code-blocks" , [] , [] )
+      [ Str "Code" , Space , Str "Blocks" ]
+  , Para [ Str "Code:" ]
+  , CodeBlock
+      ( "" , [] , [] )
+      "---- (should be four hyphens)\n\nsub status {\n    print \"working\";\n}\n\nthis code block is indented by one tab"
+  , Para [ Str "And:" ]
+  , CodeBlock
+      ( "" , [] , [] )
+      "    this code block is indented by two tabs\n\nThese should not be escaped:  \\$ \\\\ \\> \\[ \\{"
+  , Header 1 ( "lists" , [] , [] ) [ Str "Lists" ]
+  , Header 2 ( "unordered" , [] , [] ) [ Str "Unordered" ]
+  , Para [ Str "Asterisks" , Space , Str "tight:" ]
+  , BulletList
+      [ [ Para [ Str "asterisk" , Space , Str "1" ] ]
+      , [ Para [ Str "asterisk" , Space , Str "2" ] ]
+      , [ Para [ Str "asterisk" , Space , Str "3" ] ]
+      ]
+  , Para [ Str "Asterisks" , Space , Str "loose:" ]
+  , BulletList
+      [ [ Para [ Str "asterisk" , Space , Str "1" ] ]
+      , [ Para [ Str "asterisk" , Space , Str "2" ] ]
+      , [ Para [ Str "asterisk" , Space , Str "3" ] ]
+      ]
+  , Para [ Str "Pluses" , Space , Str "tight:" ]
+  , BulletList
+      [ [ Para [ Str "Plus" , Space , Str "1" ] ]
+      , [ Para [ Str "Plus" , Space , Str "2" ] ]
+      , [ Para [ Str "Plus" , Space , Str "3" ] ]
+      ]
+  , Para [ Str "Pluses" , Space , Str "loose:" ]
+  , BulletList
+      [ [ Para [ Str "Plus" , Space , Str "1" ] ]
+      , [ Para [ Str "Plus" , Space , Str "2" ] ]
+      , [ Para [ Str "Plus" , Space , Str "3" ] ]
+      ]
+  , Para [ Str "Minuses" , Space , Str "tight:" ]
+  , BulletList
+      [ [ Para [ Str "Minus" , Space , Str "1" ] ]
+      , [ Para [ Str "Minus" , Space , Str "2" ] ]
+      , [ Para [ Str "Minus" , Space , Str "3" ] ]
+      ]
+  , Para [ Str "Minuses" , Space , Str "loose:" ]
+  , BulletList
+      [ [ Para [ Str "Minus" , Space , Str "1" ] ]
+      , [ Para [ Str "Minus" , Space , Str "2" ] ]
+      , [ Para [ Str "Minus" , Space , Str "3" ] ]
+      ]
+  , Header 2 ( "ordered" , [] , [] ) [ Str "Ordered" ]
+  , Para [ Str "Tight:" ]
+  , OrderedList
+      ( 1 , DefaultStyle , DefaultDelim )
+      [ [ Para [ Str "First" ] ]
+      , [ Para [ Str "Second" ] ]
+      , [ Para [ Str "Third" ] ]
+      ]
+  , Para [ Str "and:" ]
+  , OrderedList
+      ( 1 , DefaultStyle , DefaultDelim )
+      [ [ Para [ Str "One" ] ]
+      , [ Para [ Str "Two" ] ]
+      , [ Para [ Str "Three" ] ]
+      ]
+  , Para
+      [ Str "Loose" , Space , Str "using" , Space , Str "tabs:" ]
+  , OrderedList
+      ( 1 , DefaultStyle , DefaultDelim )
+      [ [ Para [ Str "First" ] ]
+      , [ Para [ Str "Second" ] ]
+      , [ Para [ Str "Third" ] ]
+      ]
+  , Para
+      [ Str "and" , Space , Str "using" , Space , Str "spaces:" ]
+  , OrderedList
+      ( 1 , DefaultStyle , DefaultDelim )
+      [ [ Para [ Str "One" ] ]
+      , [ Para [ Str "Two" ] ]
+      , [ Para [ Str "Three" ] ]
+      ]
+  , Para [ Str "Multiple" , Space , Str "paragraphs:" ]
+  , OrderedList
+      ( 1 , DefaultStyle , DefaultDelim )
+      [ [ 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"
+            , SoftBreak
+            , Str "dog's"
+            , Space
+            , Str "back."
+            ]
+        ]
+      , [ Para [ Str "Item" , Space , Str "2." ] ]
+      , [ Para [ Str "Item" , Space , Str "3." ] ]
+      ]
+  , Para [ Str "List" , Space , Str "styles:" ]
+  , OrderedList
+      ( 1 , DefaultStyle , DefaultDelim )
+      [ [ Para [ Str "one" ] ]
+      , [ Para [ Str "two" ] ]
+      , [ Para [ Str "three" ] ]
+      ]
+  , OrderedList
+      ( 1 , LowerRoman , DefaultDelim )
+      [ [ Para [ Str "one" ] ]
+      , [ Para [ Str "two" ] ]
+      , [ Para [ Str "three" ] ]
+      ]
+  , Header 2 ( "nested" , [] , [] ) [ Str "Nested" ]
+  , BulletList
+      [ [ Para [ Str "Tab" ]
+        , BulletList
+            [ [ Para [ Str "Tab" ]
+              , BulletList [ [ Para [ Str "Tab" ] ] ]
+              ]
+            ]
+        ]
+      ]
+  , Para [ Str "Here's" , Space , Str "another:" ]
+  , OrderedList
+      ( 1 , DefaultStyle , DefaultDelim )
+      [ [ Para [ Str "First" ] ]
+      , [ Para [ Str "Second:" ]
+        , BulletList
+            [ [ Para [ Str "Fee" ] ]
+            , [ Para [ Str "Fie" ] ]
+            , [ Para [ Str "Foe" ] ]
+            ]
+        ]
+      , [ Para [ Str "Third" ] ]
+      ]
+  , Para
+      [ Str "Same"
+      , Space
+      , Str "thing"
+      , Space
+      , Str "but"
+      , Space
+      , Str "with"
+      , Space
+      , Str "paragraphs:"
+      ]
+  , OrderedList
+      ( 1 , DefaultStyle , DefaultDelim )
+      [ [ Para [ Str "First" ] ]
+      , [ Para [ Str "Second:" ]
+        , BulletList
+            [ [ Para [ Str "Fee" ] ]
+            , [ Para [ Str "Fie" ] ]
+            , [ Para [ Str "Foe" ] ]
+            ]
+        ]
+      , [ Para [ Str "Third" ] ]
+      ]
+  , Header
+      2
+      ( "tabs-and-spaces" , [] , [] )
+      [ Str "Tabs" , Space , Str "and" , Space , Str "spaces" ]
+  , BulletList
+      [ [ Para
+            [ Str "this"
+            , Space
+            , Str "is"
+            , Space
+            , Str "a"
+            , Space
+            , Str "list"
+            , Space
+            , Str "item"
+            , Space
+            , Str "indented"
+            , Space
+            , Str "with"
+            , Space
+            , Str "tabs"
+            ]
+        ]
+      , [ Para
+            [ Str "this"
+            , Space
+            , Str "is"
+            , Space
+            , Str "a"
+            , Space
+            , Str "list"
+            , Space
+            , Str "item"
+            , Space
+            , Str "indented"
+            , Space
+            , Str "with"
+            , Space
+            , Str "spaces"
+            ]
+        , BulletList
+            [ [ Para
+                  [ Str "this"
+                  , Space
+                  , Str "is"
+                  , Space
+                  , Str "an"
+                  , Space
+                  , Str "example"
+                  , Space
+                  , Str "list"
+                  , Space
+                  , Str "item"
+                  , Space
+                  , Str "indented"
+                  , Space
+                  , Str "with"
+                  , Space
+                  , Str "tabs"
+                  ]
+              ]
+            , [ Para
+                  [ Str "this"
+                  , Space
+                  , Str "is"
+                  , Space
+                  , Str "an"
+                  , Space
+                  , Str "example"
+                  , Space
+                  , Str "list"
+                  , Space
+                  , Str "item"
+                  , Space
+                  , Str "indented"
+                  , Space
+                  , Str "with"
+                  , Space
+                  , Str "spaces"
+                  ]
+              ]
+            ]
+        ]
+      ]
+  , Header
+      2
+      ( "fancy-list-markers" , [] , [] )
+      [ Str "Fancy" , Space , Str "list" , Space , Str "markers" ]
+  , Para [ Str "Autonumbering:" ]
+  , OrderedList
+      ( 1 , DefaultStyle , DefaultDelim )
+      [ [ Para [ Str "Autonumber." ] ]
+      , [ Para [ Str "More." ]
+        , OrderedList
+            ( 1 , DefaultStyle , DefaultDelim )
+            [ [ Para [ Str "Nested." ] ] ]
+        ]
+      ]
+  , Header 2 ( "definition" , [] , [] ) [ Str "Definition" ]
+  , DefinitionList
+      [ ( [ Str "Violin" ]
+        , [ [ Para
+                [ Str "Stringed"
+                , Space
+                , Str "musical"
+                , Space
+                , Str "instrument."
+                ]
+            , Para [ Str "Torture" , Space , Str "device." ]
+            ]
+          ]
+        )
+      , ( [ Str "Cello"
+          , Strong [ LineBreak ]
+          , Str "Violoncello"
+          ]
+        , [ [ Para
+                [ Str "Low-voiced"
+                , Space
+                , Str "stringed"
+                , Space
+                , Str "instrument."
+                ]
+            ]
+          ]
+        )
+      ]
+  , Header
+      2
+      ( "list-inside-paragraph" , [] , [] )
+      [ Str "List"
+      , Space
+      , Str "inside"
+      , Space
+      , Str "a"
+      , Space
+      , Str "paragraph"
+      ]
+  , Para
+      [ Str "Start"
+      , Space
+      , Str "of"
+      , Space
+      , Str "a"
+      , Space
+      , Str "paragraph."
+      ]
+  , BulletList
+      [ [ Para [ Str "Red" ] ] , [ Para [ Str "Blue" ] ] ]
+  , Para
+      [ Str "End" , Space , Str "of" , Space , Str "paragraph." ]
+  , Header
+      1
+      ( "inline-markup" , [] , [] )
+      [ Str "Inline" , Space , Str "Markup" ]
+  , Para
+      [ Str "This"
+      , Space
+      , Str "is"
+      , Space
+      , Emph [ Str "emphasized" ]
+      , Str ","
+      , Space
+      , Str "and"
+      , Space
+      , Str "so"
+      , Space
+      , Emph [ Str "is" , SoftBreak , Str "this" ]
+      , Str "."
+      ]
+  , Para
+      [ Str "This"
+      , Space
+      , Str "is"
+      , Space
+      , Strong [ Str "strong" ]
+      , Str ","
+      , Space
+      , Str "and"
+      , Space
+      , Str "so"
+      , SoftBreak
+      , Strong [ Str "is" , Space , Str "this" ]
+      , Str "."
+      ]
+  , Para
+      [ Str "Empty"
+      , Space
+      , Strong []
+      , Space
+      , Str "and"
+      , Space
+      , Emph []
+      , Str "."
+      ]
+  , Para
+      [ Str "An"
+      , SoftBreak
+      , Emph
+          [ Link
+              ( "" , [] , [] )
+              [ Str "emphasized" , SoftBreak , Str "link" ]
+              ( "/url" , "" )
+          ]
+      , Str "."
+      ]
+  , Para
+      [ Strong
+          [ Emph
+              [ Str "This"
+              , Space
+              , Str "is"
+              , Space
+              , Str "strong"
+              , Space
+              , Str "and"
+              , Space
+              , Str "em."
+              ]
+          ]
+      ]
+  , Para
+      [ Str "So"
+      , Space
+      , Str "is"
+      , Space
+      , Strong [ Emph [ Str "this" ] ]
+      , Space
+      , Str "word."
+      ]
+  , Para
+      [ Strong
+          [ Emph
+              [ Str "This"
+              , Space
+              , Str "is"
+              , Space
+              , Str "strong"
+              , Space
+              , Str "and"
+              , Space
+              , Str "em."
+              ]
+          ]
+      ]
+  , Para
+      [ Str "So"
+      , Space
+      , Str "is"
+      , Space
+      , Strong [ Emph [ Str "this" ] ]
+      , Space
+      , Str "word."
+      ]
+  , Para
+      [ Str "This"
+      , Space
+      , Str "is"
+      , Space
+      , Str "code:"
+      , Space
+      , Code ( "" , [] , [] ) ">"
+      , Str ","
+      , Space
+      , Code ( "" , [] , [] ) "$"
+      , Str ","
+      , SoftBreak
+      , Code ( "" , [] , [] ) "\\"
+      , Str ","
+      , Space
+      , Code ( "" , [] , [] ) "\\$"
+      , Str ","
+      , SoftBreak
+      , Code ( "" , [] , [] ) "<html>"
+      , Str "."
+      ]
+  , Para
+      [ Str "This"
+      , Space
+      , Str "is"
+      , Space
+      , SmallCaps [ Str "small" , Space , Str "caps" ]
+      , Str "."
+      ]
+  , Para
+      [ Str "These"
+      , Space
+      , Str "are"
+      , Space
+      , Str "all"
+      , Space
+      , Str "underlined:"
+      , Space
+      , Str "foo"
+      , Space
+      , Str "and"
+      , Space
+      , Str "bar."
+      ]
+  , Para
+      [ Str "These"
+      , Space
+      , Str "are"
+      , Space
+      , Str "all"
+      , Space
+      , Str "strikethrough:"
+      , Space
+      , Strikeout [ Str "foo" ]
+      , Str ","
+      , SoftBreak
+      , Strikeout [ Str "bar" ]
+      , Str ","
+      , Space
+      , Str "and"
+      , Space
+      , Strikeout [ Str "baz" ]
+      , Str "."
+      ]
+  , Header
+      1
+      ( "smart-quotes-ellipses-dashes" , [] , [] )
+      [ Str "Smart"
+      , Space
+      , Str "quotes,"
+      , Space
+      , Str "ellipses,"
+      , Space
+      , Str "dashes"
+      ]
+  , Para
+      [ Str "\"Hello,\""
+      , Space
+      , Str "said"
+      , Space
+      , Str "the"
+      , Space
+      , Str "spider."
+      , Space
+      , Str "\"'Shelob'"
+      , Space
+      , Str "is"
+      , Space
+      , Str "my"
+      , Space
+      , Str "name.\""
+      ]
+  , Para
+      [ Str "'A',"
+      , Space
+      , Str "'B',"
+      , Space
+      , Str "and"
+      , Space
+      , Str "'C'"
+      , Space
+      , Str "are"
+      , Space
+      , Str "letters."
+      ]
+  , Para
+      [ Str "'Oak,'"
+      , Space
+      , Str "'elm,'"
+      , Space
+      , Str "and"
+      , Space
+      , Str "'beech'"
+      , Space
+      , Str "are"
+      , Space
+      , Str "names"
+      , Space
+      , Str "of"
+      , Space
+      , Str "trees."
+      , Space
+      , Str "So"
+      , Space
+      , Str "is"
+      , Space
+      , Str "'pine.'"
+      ]
+  , Para
+      [ Str "'He"
+      , Space
+      , Str "said,"
+      , Space
+      , Str "\"I"
+      , Space
+      , Str "want"
+      , Space
+      , Str "to"
+      , Space
+      , Str "go.\"'"
+      , Space
+      , Str "Were"
+      , Space
+      , Str "you"
+      , Space
+      , Str "alive"
+      , Space
+      , Str "in"
+      , Space
+      , Str "the"
+      , Space
+      , Str "70's?"
+      ]
+  , Para
+      [ Str "Here"
+      , Space
+      , Str "is"
+      , Space
+      , Str "some"
+      , Space
+      , Str "quoted"
+      , Space
+      , Str "'"
+      , Code ( "" , [] , [] ) "code"
+      , Str "'"
+      , Space
+      , Str "and"
+      , Space
+      , Str "a"
+      , SoftBreak
+      , Str "\""
+      , Link
+          ( "" , [] , [] )
+          [ Str "quoted" , SoftBreak , Str "link" ]
+          ( "http://example.com/?foo=1&bar=2" , "" )
+      , Str "\"."
+      ]
+  , Para
+      [ Str "Some"
+      , Space
+      , Str "dashes:"
+      , Space
+      , Str "one---two"
+      , Space
+      , Str "---"
+      , Space
+      , Str "three--four"
+      , Space
+      , Str "--"
+      , Space
+      , Str "five."
+      ]
+  , Para
+      [ Str "Dashes"
+      , Space
+      , Str "between"
+      , Space
+      , Str "numbers:"
+      , Space
+      , Str "5-7,"
+      , Space
+      , Str "255-66,"
+      , Space
+      , Str "1987-1999."
+      ]
+  , Para
+      [ Str "Ellipses...and."
+      , Space
+      , Str "."
+      , Space
+      , Str ".and"
+      , Space
+      , Str "."
+      , Space
+      , Str "."
+      , Space
+      , Str "."
+      , Space
+      , Str "."
+      ]
+  , Header 1 ( "latex" , [] , [] ) [ Str "LaTeX" ]
+  , BulletList
+      [ [ Para [ Str "\\cite[22-23]{smith.1899}" ] ]
+      , [ Para [ Str "\\doublespacing" ] ]
+      , [ Para [ Str "$2+2=4$" ] ]
+      , [ Para
+            [ Str "$x" , Space , Str "\\in" , Space , Str "y$" ]
+        ]
+      , [ Para
+            [ Str "$\\alpha"
+            , Space
+            , Str "\\wedge"
+            , Space
+            , Str "\\omega$"
+            ]
+        ]
+      , [ Para [ Str "$223$" ] ]
+      , [ Para [ Str "$p$-Tree" ] ]
+      , [ Para
+            [ Str "$\\frac{d}{dx}f(x)=\\lim_{h\\to"
+            , Space
+            , Str "0}\\frac{f(x+h)-f(x)}{h}$"
+            ]
+        ]
+      , [ Para
+            [ Str "Here's"
+            , Space
+            , Str "one"
+            , Space
+            , Str "that"
+            , Space
+            , Str "has"
+            , Space
+            , Str "a"
+            , Space
+            , Str "line"
+            , Space
+            , Str "break"
+            , Space
+            , Str "in"
+            , Space
+            , Str "it:"
+            , Space
+            , Str "$\\alpha"
+            , Space
+            , Str "+"
+            , Space
+            , Str "\\omega"
+            , Space
+            , Str "\\times"
+            , SoftBreak
+            , Str "x^2$."
+            ]
+        ]
+      ]
+  , Para
+      [ Str "These"
+      , Space
+      , Str "shouldn't"
+      , Space
+      , Str "be"
+      , Space
+      , Str "math:"
+      ]
+  , BulletList
+      [ [ Para
+            [ Str "To"
+            , Space
+            , Str "get"
+            , Space
+            , Str "the"
+            , Space
+            , Str "famous"
+            , Space
+            , Str "equation,"
+            , Space
+            , Str "write"
+            , SoftBreak
+            , Code ( "" , [] , [] ) "$e = mc^2$"
+            , Str "."
+            ]
+        ]
+      , [ Para
+            [ Str "$22,000"
+            , Space
+            , Str "is"
+            , Space
+            , Str "a"
+            , Space
+            , Emph [ Str "lot" ]
+            , Space
+            , Str "of"
+            , Space
+            , Str "money."
+            , Space
+            , Str "So"
+            , Space
+            , Str "is"
+            , Space
+            , Str "$34,000."
+            , Space
+            , Str "(It"
+            , SoftBreak
+            , Str "worked"
+            , Space
+            , Str "if"
+            , Space
+            , Str "\"lot\""
+            , Space
+            , Str "is"
+            , Space
+            , Str "emphasized.)"
+            ]
+        ]
+      , [ Para
+            [ Str "Escaped"
+            , Space
+            , Code ( "" , [] , [] ) "$"
+            , Str ":"
+            , Space
+            , Str "$73"
+            , Space
+            , Emph
+                [ Str "this"
+                , Space
+                , Str "should"
+                , Space
+                , Str "be"
+                , SoftBreak
+                , Str "emphasized"
+                ]
+            , Space
+            , Str "23$."
+            ]
+        ]
+      ]
+  , Para
+      [ Str "Here's"
+      , Space
+      , Str "a"
+      , Space
+      , Str "LaTeX"
+      , Space
+      , Str "table:"
+      ]
+  , Para
+      [ Str "\\begin{tabular}{|l|l|}\\hline"
+      , Space
+      , Str "Animal"
+      , Space
+      , Str "&"
+      , Space
+      , Str "Number"
+      , Space
+      , Str "\\\\"
+      , Space
+      , Str "\\hline"
+      , Space
+      , Str "Dog"
+      , Space
+      , Str "&"
+      , SoftBreak
+      , Str "2"
+      , Space
+      , Str "\\\\"
+      , Space
+      , Str "Cat"
+      , Space
+      , Str "&"
+      , Space
+      , Str "1"
+      , Space
+      , Str "\\\\"
+      , Space
+      , Str "\\hline"
+      , Space
+      , Str "\\end{tabular}"
+      ]
+  , Header
+      1
+      ( "special-characters" , [] , [] )
+      [ Str "Special" , Space , Str "Characters" ]
+  , Para
+      [ Str "Here"
+      , Space
+      , Str "is"
+      , Space
+      , Str "some"
+      , Space
+      , Str "unicode:"
+      ]
+  , BulletList
+      [ [ Para
+            [ Str "I" , Space , Str "hat:" , Space , Str "\206" ]
+        ]
+      , [ Para
+            [ Str "o" , Space , Str "umlaut:" , Space , Str "\246" ]
+        ]
+      , [ Para [ Str "section:" , Space , Str "\167" ] ]
+      , [ Para
+            [ Str "set"
+            , Space
+            , Str "membership:"
+            , Space
+            , Str "elem"
+            ]
+        ]
+      , [ Para [ Str "copyright:" , Space , Str "\169" ] ]
+      ]
+  , Para
+      [ Str "AT&T"
+      , Space
+      , Str "has"
+      , Space
+      , Str "an"
+      , Space
+      , Str "ampersand"
+      , Space
+      , Str "in"
+      , Space
+      , Str "their"
+      , Space
+      , Str "name."
+      ]
+  , Para
+      [ Str "AT&T"
+      , Space
+      , Str "is"
+      , Space
+      , Str "another"
+      , Space
+      , Str "way"
+      , Space
+      , Str "to"
+      , Space
+      , Str "write"
+      , Space
+      , Str "it."
+      ]
+  , Para
+      [ Str "This" , Space , Str "&" , Space , Str "that." ]
+  , Para [ Str "4" , Space , Str "<" , Space , Str "5." ]
+  , Para [ Str "6" , Space , Str ">" , Space , Str "5." ]
+  , Para [ Str "Backslash:" , Space , Str "\\" ]
+  , Para [ Str "Backtick:" , Space , Str "`" ]
+  , Para [ Str "Asterisk:" , Space , Str "*" ]
+  , Para [ Str "Underscore:" , Space , Str "_" ]
+  , Para
+      [ Str "Left" , Space , Str "brace:" , Space , Str "{" ]
+  , Para
+      [ Str "Right" , Space , Str "brace:" , Space , Str "}" ]
+  , Para
+      [ Str "Left" , Space , Str "bracket:" , Space , Str "[" ]
+  , Para
+      [ Str "Right" , Space , Str "bracket:" , Space , Str "]" ]
+  , Para
+      [ Str "Left" , Space , Str "paren:" , Space , Str "(" ]
+  , Para
+      [ Str "Right" , Space , Str "paren:" , Space , Str ")" ]
+  , Para [ Str "Greater-than:" , Space , Str ">" ]
+  , Para [ Str "Hash:" , Space , Str "#" ]
+  , Para [ Str "Period:" , Space , Str "." ]
+  , Para [ Str "Bang:" , Space , Str "!" ]
+  , Para [ Str "Plus:" , Space , Str "+" ]
+  , Para [ Str "Minus:" , Space , Str "-" ]
+  , Header 1 ( "links" , [] , [] ) [ Str "Links" ]
+  , Header 2 ( "explicit" , [] , [] ) [ Str "Explicit" ]
+  , Para
+      [ Str "Just"
+      , Space
+      , Str "a"
+      , SoftBreak
+      , Link ( "" , [] , [] ) [ Str "URL" ] ( "/url/" , "" )
+      , Str "."
+      ]
+  , Para
+      [ Link
+          ( "" , [] , [] )
+          [ Str "URL" , SoftBreak , Str "and" , Space , Str "title" ]
+          ( "/url/" , "title" )
+      , Str "."
+      ]
+  , Para
+      [ Link
+          ( "" , [] , [] )
+          [ Str "URL" , SoftBreak , Str "and" , Space , Str "title" ]
+          ( "/url/" , "title preceded by two spaces" )
+      , Str "."
+      ]
+  , Para
+      [ Link
+          ( "" , [] , [] )
+          [ Str "URL" , SoftBreak , Str "and" , Space , Str "title" ]
+          ( "/url/" , "title preceded by a tab" )
+      , Str "."
+      ]
+  , Para
+      [ Link
+          ( "" , [] , [] )
+          [ Str "URL" , SoftBreak , Str "and" , Space , Str "title" ]
+          ( "/url/" , "title with \"quotes\" in it" )
+      ]
+  , Para
+      [ Link
+          ( "" , [] , [] )
+          [ Str "URL" , SoftBreak , Str "and" , Space , Str "title" ]
+          ( "/url/" , "title with single quotes" )
+      ]
+  , Para
+      [ Str "Email"
+      , Space
+      , Str "link"
+      , Space
+      , Str "(nobody"
+      , Space
+      , Str "[at]"
+      , Space
+      , Str "nowhere.net)"
+      ]
+  , Para
+      [ Link ( "" , [] , [] ) [ Str "Empty" ] ( "" , "" )
+      , Str "."
+      ]
+  , Header 2 ( "reference" , [] , [] ) [ Str "Reference" ]
+  , Para
+      [ Str "Foo"
+      , SoftBreak
+      , Link ( "" , [] , [] ) [ Str "bar" ] ( "/url/" , "" )
+      , Str "."
+      ]
+  , Para
+      [ Str "Foo"
+      , SoftBreak
+      , Link ( "" , [] , [] ) [ Str "bar" ] ( "/url/" , "" )
+      , Str "."
+      ]
+  , Para
+      [ Str "Foo"
+      , SoftBreak
+      , Link ( "" , [] , [] ) [ Str "bar" ] ( "/url/" , "" )
+      , Str "."
+      ]
+  , Para
+      [ Str "With"
+      , Space
+      , Link
+          ( "" , [] , [] )
+          [ Str "embedded" , SoftBreak , Str "[brackets]" ]
+          ( "/url/" , "" )
+      , Str "."
+      ]
+  , Para
+      [ Link ( "" , [] , [] ) [ Str "b" ] ( "/url/" , "" )
+      , Space
+      , Str "by"
+      , SoftBreak
+      , Str "itself"
+      , Space
+      , Str "should"
+      , Space
+      , Str "be"
+      , Space
+      , Str "a"
+      , Space
+      , Str "link."
+      ]
+  , Para
+      [ Str "Indented"
+      , SoftBreak
+      , Link ( "" , [] , [] ) [ Str "once" ] ( "/url" , "" )
+      , Str "."
+      ]
+  , Para
+      [ Str "Indented"
+      , SoftBreak
+      , Link ( "" , [] , [] ) [ Str "twice" ] ( "/url" , "" )
+      , Str "."
+      ]
+  , Para
+      [ Str "Indented"
+      , SoftBreak
+      , Link ( "" , [] , [] ) [ Str "thrice" ] ( "/url" , "" )
+      , Str "."
+      ]
+  , Para
+      [ Str "This"
+      , Space
+      , Str "should"
+      , Space
+      , Str "[not]"
+      , Space
+      , Str "be"
+      , Space
+      , Str "a"
+      , Space
+      , Str "link."
+      ]
+  , CodeBlock ( "" , [] , [] ) "[not]: /url"
+  , Para
+      [ Str "Foo"
+      , SoftBreak
+      , Link
+          ( "" , [] , [] )
+          [ Str "bar" ]
+          ( "/url/" , "Title with \"quotes\" inside" )
+      , Str "."
+      ]
+  , Para
+      [ Str "Foo"
+      , SoftBreak
+      , Link
+          ( "" , [] , [] )
+          [ Str "biz" ]
+          ( "/url/" , "Title with \"quote\" inside" )
+      , Str "."
+      ]
+  , Header
+      2
+      ( "with-ampersands" , [] , [] )
+      [ Str "With" , Space , Str "ampersands" ]
+  , Para
+      [ Str "Here's"
+      , Space
+      , Str "a"
+      , SoftBreak
+      , Link
+          ( "" , [] , [] )
+          [ Str "link"
+          , SoftBreak
+          , Str "with"
+          , Space
+          , Str "an"
+          , Space
+          , Str "ampersand"
+          , Space
+          , Str "in"
+          , Space
+          , Str "the"
+          , Space
+          , Str "URL"
+          ]
+          ( "http://example.com/?foo=1&bar=2" , "" )
+      , Str "."
+      ]
+  , Para
+      [ Str "Here's"
+      , Space
+      , Str "a"
+      , Space
+      , Str "link"
+      , Space
+      , Str "with"
+      , Space
+      , Str "an"
+      , Space
+      , Str "amersand"
+      , Space
+      , Str "in"
+      , Space
+      , Str "the"
+      , Space
+      , Str "link"
+      , Space
+      , Str "text:"
+      , SoftBreak
+      , Link
+          ( "" , [] , [] )
+          [ Str "AT&T" ]
+          ( "http://att.com/" , "AT&T" )
+      , Str "."
+      ]
+  , Para
+      [ Str "Here's"
+      , Space
+      , Str "an"
+      , SoftBreak
+      , Link
+          ( "" , [] , [] )
+          [ Str "inline" , SoftBreak , Str "link" ]
+          ( "/script?foo=1&bar=2" , "" )
+      , Str "."
+      ]
+  , Para
+      [ Str "Here's"
+      , Space
+      , Str "an"
+      , SoftBreak
+      , Link
+          ( "" , [] , [] )
+          [ Str "inline"
+          , SoftBreak
+          , Str "link"
+          , Space
+          , Str "in"
+          , Space
+          , Str "pointy"
+          , Space
+          , Str "braces"
+          ]
+          ( "/script?foo=1&bar=2" , "" )
+      , Str "."
+      ]
+  , Header 2 ( "autolinks" , [] , [] ) [ Str "Autolinks" ]
+  , Para
+      [ Str "With"
+      , Space
+      , Str "an"
+      , Space
+      , Str "ampersand:"
+      , SoftBreak
+      , Link
+          ( "" , [] , [] )
+          [ Str "http://example.com/?foo=1&bar=2" ]
+          ( "http://example.com/?foo=1&bar=2" , "" )
+      ]
+  , BulletList
+      [ [ Para
+            [ Str "In" , Space , Str "a" , Space , Str "list?" ]
+        ]
+      , [ Para
+            [ Link
+                ( "" , [] , [] )
+                [ Str "http://example.com/" ]
+                ( "http://example.com/" , "" )
+            ]
+        ]
+      , [ Para [ Str "It" , Space , Str "should." ] ]
+      ]
+  , Para
+      [ Str "An"
+      , Space
+      , Str "e-mail"
+      , Space
+      , Str "address:"
+      , Space
+      , Str "nobody"
+      , Space
+      , Str "[at]"
+      , Space
+      , Str "nowhere.net"
+      ]
+  , BlockQuote
+      [ Para
+          [ Str "Blockquoted:"
+          , SoftBreak
+          , Link
+              ( "" , [] , [] )
+              [ Str "http://example.com/" ]
+              ( "http://example.com/" , "" )
+          ]
+      ]
+  , Para
+      [ Str "Auto-links"
+      , Space
+      , Str "should"
+      , Space
+      , Str "not"
+      , Space
+      , Str "occur"
+      , Space
+      , Str "here:"
+      , SoftBreak
+      , Code ( "" , [] , [] ) "<http://example.com/>"
+      ]
+  , CodeBlock
+      ( "" , [] , [] ) "or here: <http://example.com/>"
+  , Header 1 ( "images" , [] , [] ) [ Str "Images" ]
+  , Para
+      [ Str "From"
+      , Space
+      , Str "\"Voyage"
+      , Space
+      , Str "dans"
+      , Space
+      , Str "la"
+      , Space
+      , Str "Lune\""
+      , Space
+      , Str "by"
+      , Space
+      , Str "Georges"
+      , Space
+      , Str "Melies"
+      , Space
+      , Str "(1902):"
+      ]
+  , Para
+      [ Image
+          ( "" , [] , [] ) [] ( "lalune.jpg" , "Voyage dans la Lune" )
+      ]
+  , Para
+      [ Str "Here"
+      , Space
+      , Str "is"
+      , Space
+      , Str "a"
+      , Space
+      , Str "movie"
+      , SoftBreak
+      , Image ( "" , [] , [] ) [] ( "movie.jpg" , "" )
+      , SoftBreak
+      , Str "icon."
+      ]
+  , Header 1 ( "footnotes" , [] , [] ) [ Str "Footnotes" ]
+  , Para
+      [ Str "Here"
+      , Space
+      , Str "is"
+      , Space
+      , Str "a"
+      , Space
+      , Str "footnote"
+      , Space
+      , Str "reference"
+      , Link ( "" , [] , [] ) [ Str "(1)" ] ( "#note_1" , "" )
+      , Str ","
+      , SoftBreak
+      , Str "and"
+      , SoftBreak
+      , Str "another"
+      , Link
+          ( "" , [] , [] )
+          [ Str "(longnote)" ]
+          ( "#note_longnote" , "" )
+      , Str "."
+      , SoftBreak
+      , Str "This"
+      , Space
+      , Str "should"
+      , Space
+      , Emph [ Str "not" ]
+      , Space
+      , Str "be"
+      , Space
+      , Str "a"
+      , Space
+      , Str "footnote"
+      , Space
+      , Str "reference,"
+      , Space
+      , Str "because"
+      , Space
+      , Str "it"
+      , SoftBreak
+      , Str "contains"
+      , Space
+      , Str "a"
+      , Space
+      , Str "space^(my"
+      , Space
+      , Str "note)."
+      ]
+  , Para
+      [ Link ( "" , [] , [] ) [ Str "(1)" ] ( "#ref_1" , "" )
+      , Space
+      , Str "Here"
+      , Space
+      , Str "is"
+      , Space
+      , Str "the"
+      , Space
+      , Str "footnote."
+      , Space
+      , Str "It"
+      , Space
+      , Str "can"
+      , SoftBreak
+      , Str "go"
+      , Space
+      , Str "anywhere"
+      , Space
+      , Str "in"
+      , Space
+      , Str "the"
+      , Space
+      , Str "document,"
+      , Space
+      , Str "not"
+      , Space
+      , Str "just"
+      , Space
+      , Str "at"
+      , Space
+      , Str "the"
+      , Space
+      , Str "end."
+      ]
+  , Para
+      [ Link
+          ( "" , [] , [] )
+          [ Str "(longnote)" ]
+          ( "#ref_longnote" , "" )
+      , Space
+      , Str "Here's"
+      , SoftBreak
+      , Str "the"
+      , Space
+      , Str "other"
+      , Space
+      , Str "note."
+      , Space
+      , Str "This"
+      , Space
+      , Str "one"
+      , Space
+      , Str "contains"
+      , Space
+      , Str "multiple"
+      , Space
+      , Str "blocks."
+      ]
+  , Para
+      [ Str "Caret"
+      , Space
+      , Str "characters"
+      , Space
+      , Str "are"
+      , Space
+      , Str "used"
+      , Space
+      , Str "to"
+      , Space
+      , Str "indicate"
+      , Space
+      , Str "that"
+      , Space
+      , Str "the"
+      , Space
+      , Str "blocks"
+      , Space
+      , Str "all"
+      , Space
+      , Str "belong"
+      , Space
+      , Str "to"
+      , SoftBreak
+      , Str "a"
+      , Space
+      , Str "single"
+      , Space
+      , Str "footnote"
+      , Space
+      , Str "(as"
+      , Space
+      , Str "with"
+      , Space
+      , Str "block"
+      , Space
+      , Str "quotes)."
+      ]
+  , CodeBlock ( "" , [] , [] ) "  { <code> }"
+  , Para
+      [ Str "If"
+      , Space
+      , Str "you"
+      , Space
+      , Str "want,"
+      , Space
+      , Str "you"
+      , Space
+      , Str "can"
+      , Space
+      , Str "use"
+      , Space
+      , Str "a"
+      , Space
+      , Str "caret"
+      , Space
+      , Str "at"
+      , Space
+      , Str "the"
+      , Space
+      , Str "beginning"
+      , Space
+      , Str "of"
+      , Space
+      , Str "every"
+      , Space
+      , Str "line,"
+      , Space
+      , Str "as"
+      , SoftBreak
+      , Str "with"
+      , Space
+      , Str "blockquotes,"
+      , Space
+      , Str "but"
+      , Space
+      , Str "all"
+      , Space
+      , Str "that"
+      , Space
+      , Str "you"
+      , Space
+      , Str "need"
+      , Space
+      , Str "is"
+      , Space
+      , Str "a"
+      , Space
+      , Str "caret"
+      , Space
+      , Str "at"
+      , Space
+      , Str "the"
+      , Space
+      , Str "beginning"
+      , SoftBreak
+      , Str "of"
+      , Space
+      , Str "the"
+      , Space
+      , Str "first"
+      , Space
+      , Str "line"
+      , Space
+      , Str "of"
+      , Space
+      , Str "the"
+      , Space
+      , Str "block"
+      , Space
+      , Str "and"
+      , Space
+      , Str "any"
+      , Space
+      , Str "preceding"
+      , Space
+      , Str "blank"
+      , Space
+      , Str "lines."
+      ]
+  , Para
+      [ Str "text"
+      , Space
+      , Emph [ Str "Leading" , Space , Str "space" ]
+      ]
+  , Para
+      [ Emph [ Str "Trailing" , Space , Str "space" ]
+      , Space
+      , Str "text"
+      ]
+  , Para
+      [ Str "text"
+      , Space
+      , Emph [ Str "Leading" , Space , Str "spaces" ]
+      ]
+  , Para
+      [ Emph [ Str "Trailing" , Space , Str "spaces" ]
+      , Space
+      , Str "text"
+      ]
+  , Header 1 ( "tables" , [] , [] ) [ Str "Tables" ]
+  , Header
+      2
+      ( "tables-with-headers" , [] , [] )
+      [ Str "Tables"
+      , Space
+      , Str "with"
+      , Space
+      , Str "Headers"
+      ]
+  , Div
+      ( "" , [ "table-wrap" ] , [] )
+      [ Table
+          ( "" , [] , [] )
+          (Caption Nothing [])
+          [ ( AlignLeft , ColWidthDefault )
+          , ( AlignLeft , ColWidthDefault )
+          , ( AlignLeft , ColWidthDefault )
+          ]
+          (TableHead
+             ( "" , [] , [] )
+             [ Row
+                 ( "" , [] , [] )
+                 [ Cell
+                     ( "" , [] , [] )
+                     AlignDefault
+                     (RowSpan 1)
+                     (ColSpan 1)
+                     [ Para [ Str "X" ] ]
+                 , Cell
+                     ( "" , [] , [] )
+                     AlignDefault
+                     (RowSpan 1)
+                     (ColSpan 1)
+                     [ Para [ Str "Y" ] ]
+                 , Cell
+                     ( "" , [] , [] )
+                     AlignDefault
+                     (RowSpan 1)
+                     (ColSpan 1)
+                     [ Para [ Str "Z" ] ]
+                 ]
+             ])
+          [ TableBody
+              ( "" , [] , [] )
+              (RowHeadColumns 0)
+              []
+              [ Row
+                  ( "" , [] , [] )
+                  [ Cell
+                      ( "" , [] , [] )
+                      AlignDefault
+                      (RowSpan 1)
+                      (ColSpan 1)
+                      [ Para [ Str "1" ] ]
+                  , Cell
+                      ( "" , [] , [] )
+                      AlignDefault
+                      (RowSpan 1)
+                      (ColSpan 1)
+                      [ Para [ Str "2" ] ]
+                  , Cell
+                      ( "" , [] , [] )
+                      AlignDefault
+                      (RowSpan 1)
+                      (ColSpan 1)
+                      [ Para [ Str "3" ] ]
+                  ]
+              , Row
+                  ( "" , [] , [] )
+                  [ Cell
+                      ( "" , [] , [] )
+                      AlignDefault
+                      (RowSpan 1)
+                      (ColSpan 1)
+                      [ Para [ Str "4" ] ]
+                  , Cell
+                      ( "" , [] , [] )
+                      AlignDefault
+                      (RowSpan 1)
+                      (ColSpan 1)
+                      [ Para [ Str "5" ] ]
+                  , Cell
+                      ( "" , [] , [] )
+                      AlignDefault
+                      (RowSpan 1)
+                      (ColSpan 1)
+                      [ Para [ Str "6" ] ]
+                  ]
+              ]
+          ]
+          (TableFoot ( "" , [] , [] ) [])
+      ]
+  , Div
+      ( "" , [ "table-wrap" ] , [] )
+      [ Table
+          ( "" , [] , [] )
+          (Caption Nothing [])
+          [ ( AlignLeft , ColWidthDefault )
+          , ( AlignLeft , ColWidthDefault )
+          , ( AlignLeft , ColWidthDefault )
+          ]
+          (TableHead
+             ( "" , [] , [] )
+             [ Row
+                 ( "" , [] , [] )
+                 [ Cell
+                     ( "" , [] , [] )
+                     AlignDefault
+                     (RowSpan 1)
+                     (ColSpan 1)
+                     [ Para [ Str "X" ] ]
+                 , Cell
+                     ( "" , [] , [] )
+                     AlignDefault
+                     (RowSpan 1)
+                     (ColSpan 1)
+                     [ Para [ Str "Y" ] ]
+                 , Cell
+                     ( "" , [] , [] )
+                     AlignDefault
+                     (RowSpan 1)
+                     (ColSpan 1)
+                     [ Para [ Str "Z" ] ]
+                 ]
+             ])
+          [ TableBody
+              ( "" , [] , [] )
+              (RowHeadColumns 0)
+              []
+              [ Row
+                  ( "" , [] , [] )
+                  [ Cell
+                      ( "" , [] , [] )
+                      AlignDefault
+                      (RowSpan 1)
+                      (ColSpan 1)
+                      [ Para [ Str "1" ] ]
+                  , Cell
+                      ( "" , [] , [] )
+                      AlignDefault
+                      (RowSpan 1)
+                      (ColSpan 1)
+                      [ Para [ Str "2" ] ]
+                  , Cell
+                      ( "" , [] , [] )
+                      AlignDefault
+                      (RowSpan 1)
+                      (ColSpan 1)
+                      [ Para [ Str "3" ] ]
+                  ]
+              , Row
+                  ( "" , [] , [] )
+                  [ Cell
+                      ( "" , [] , [] )
+                      AlignDefault
+                      (RowSpan 1)
+                      (ColSpan 1)
+                      [ Para [ Str "4" ] ]
+                  , Cell
+                      ( "" , [] , [] )
+                      AlignDefault
+                      (RowSpan 1)
+                      (ColSpan 1)
+                      [ Para [ Str "5" ] ]
+                  , Cell
+                      ( "" , [] , [] )
+                      AlignDefault
+                      (RowSpan 1)
+                      (ColSpan 1)
+                      [ Para [ Str "6" ] ]
+                  ]
+              ]
+          ]
+          (TableFoot ( "" , [] , [] ) [])
+      ]
+  , Div
+      ( "" , [ "table-wrap" ] , [] )
+      [ Table
+          ( "" , [] , [] )
+          (Caption Nothing [])
+          [ ( AlignLeft , ColWidthDefault )
+          , ( AlignLeft , ColWidthDefault )
+          , ( AlignLeft , ColWidthDefault )
+          ]
+          (TableHead
+             ( "" , [] , [] )
+             [ Row
+                 ( "" , [] , [] )
+                 [ Cell
+                     ( "" , [] , [] )
+                     AlignDefault
+                     (RowSpan 1)
+                     (ColSpan 1)
+                     [ Para [ Str "X" ] ]
+                 , Cell
+                     ( "" , [] , [] )
+                     AlignDefault
+                     (RowSpan 1)
+                     (ColSpan 1)
+                     [ Para [ Str "Y" ] ]
+                 , Cell
+                     ( "" , [] , [] )
+                     AlignDefault
+                     (RowSpan 1)
+                     (ColSpan 1)
+                     [ Para [ Str "Z" ] ]
+                 ]
+             ])
+          [ TableBody
+              ( "" , [] , [] )
+              (RowHeadColumns 0)
+              []
+              [ Row
+                  ( "" , [] , [] )
+                  [ Cell
+                      ( "" , [] , [] )
+                      AlignDefault
+                      (RowSpan 1)
+                      (ColSpan 1)
+                      [ Para [ Str "1" ] ]
+                  , Cell
+                      ( "" , [] , [] )
+                      AlignDefault
+                      (RowSpan 1)
+                      (ColSpan 1)
+                      [ Para [ Str "2" ] ]
+                  , Cell
+                      ( "" , [] , [] )
+                      AlignDefault
+                      (RowSpan 1)
+                      (ColSpan 1)
+                      [ Para [ Str "3" ] ]
+                  ]
+              , Row
+                  ( "" , [] , [] )
+                  [ Cell
+                      ( "" , [] , [] )
+                      AlignDefault
+                      (RowSpan 1)
+                      (ColSpan 1)
+                      [ Para [ Str "4" ] ]
+                  , Cell
+                      ( "" , [] , [] )
+                      AlignDefault
+                      (RowSpan 1)
+                      (ColSpan 1)
+                      [ Para [ Str "5" ] ]
+                  , Cell
+                      ( "" , [] , [] )
+                      AlignDefault
+                      (RowSpan 1)
+                      (ColSpan 1)
+                      [ Para [ Str "6" ] ]
+                  ]
+              ]
+          ]
+          (TableFoot ( "" , [] , [] ) [])
+      ]
+  , Div
+      ( "" , [ "table-wrap" ] , [] )
+      [ Table
+          ( "" , [] , [] )
+          (Caption Nothing [])
+          [ ( AlignLeft , ColWidthDefault )
+          , ( AlignLeft , ColWidthDefault )
+          , ( AlignLeft , ColWidthDefault )
+          ]
+          (TableHead
+             ( "" , [] , [] )
+             [ Row
+                 ( "" , [] , [] )
+                 [ Cell
+                     ( "" , [] , [] )
+                     AlignDefault
+                     (RowSpan 1)
+                     (ColSpan 1)
+                     [ Para [ Str "X" ] ]
+                 , Cell
+                     ( "" , [] , [] )
+                     AlignDefault
+                     (RowSpan 1)
+                     (ColSpan 1)
+                     [ Para [ Str "Y" ] ]
+                 , Cell
+                     ( "" , [] , [] )
+                     AlignDefault
+                     (RowSpan 1)
+                     (ColSpan 1)
+                     [ Para [ Str "Z" ] ]
+                 ]
+             ])
+          [ TableBody
+              ( "" , [] , [] )
+              (RowHeadColumns 0)
+              []
+              [ Row
+                  ( "" , [] , [] )
+                  [ Cell
+                      ( "" , [] , [] )
+                      AlignDefault
+                      (RowSpan 1)
+                      (ColSpan 1)
+                      [ Para [ Str "1" ] ]
+                  , Cell
+                      ( "" , [] , [] )
+                      AlignDefault
+                      (RowSpan 1)
+                      (ColSpan 1)
+                      [ Para [ Str "2" ] ]
+                  , Cell
+                      ( "" , [] , [] )
+                      AlignDefault
+                      (RowSpan 1)
+                      (ColSpan 1)
+                      [ Para [ Str "3" ] ]
+                  ]
+              , Row
+                  ( "" , [] , [] )
+                  [ Cell
+                      ( "" , [] , [] )
+                      AlignDefault
+                      (RowSpan 1)
+                      (ColSpan 1)
+                      [ Para [ Str "4" ] ]
+                  , Cell
+                      ( "" , [] , [] )
+                      AlignDefault
+                      (RowSpan 1)
+                      (ColSpan 1)
+                      [ Para [ Str "5" ] ]
+                  , Cell
+                      ( "" , [] , [] )
+                      AlignDefault
+                      (RowSpan 1)
+                      (ColSpan 1)
+                      [ Para [ Str "6" ] ]
+                  ]
+              ]
+          ]
+          (TableFoot ( "" , [] , [] ) [])
+      ]
+  , Div
+      ( "" , [ "table-wrap" ] , [] )
+      [ Table
+          ( "" , [] , [] )
+          (Caption Nothing [])
+          [ ( AlignLeft , ColWidthDefault )
+          , ( AlignLeft , ColWidthDefault )
+          , ( AlignLeft , ColWidthDefault )
+          ]
+          (TableHead
+             ( "" , [] , [] )
+             [ Row
+                 ( "" , [] , [] )
+                 [ Cell
+                     ( "" , [] , [] )
+                     AlignDefault
+                     (RowSpan 1)
+                     (ColSpan 1)
+                     [ Para [ Str "X" ] ]
+                 , Cell
+                     ( "" , [] , [] )
+                     AlignDefault
+                     (RowSpan 1)
+                     (ColSpan 1)
+                     [ Para [ Str "Y" ] ]
+                 , Cell
+                     ( "" , [] , [] )
+                     AlignDefault
+                     (RowSpan 1)
+                     (ColSpan 1)
+                     [ Para [ Str "Z" ] ]
+                 ]
+             ])
+          [ TableBody
+              ( "" , [] , [] )
+              (RowHeadColumns 0)
+              []
+              [ Row
+                  ( "" , [] , [] )
+                  [ Cell
+                      ( "" , [] , [] )
+                      AlignDefault
+                      (RowSpan 1)
+                      (ColSpan 1)
+                      [ Para [ Str "1" ] ]
+                  , Cell
+                      ( "" , [] , [] )
+                      AlignDefault
+                      (RowSpan 1)
+                      (ColSpan 1)
+                      [ Para [ Str "2" ] ]
+                  , Cell
+                      ( "" , [] , [] )
+                      AlignDefault
+                      (RowSpan 1)
+                      (ColSpan 1)
+                      [ Para [ Str "3" ] ]
+                  ]
+              , Row
+                  ( "" , [] , [] )
+                  [ Cell
+                      ( "" , [] , [] )
+                      AlignDefault
+                      (RowSpan 1)
+                      (ColSpan 1)
+                      [ Para [ Str "4" ] ]
+                  , Cell
+                      ( "" , [] , [] )
+                      AlignDefault
+                      (RowSpan 1)
+                      (ColSpan 1)
+                      [ Para [ Str "5" ] ]
+                  , Cell
+                      ( "" , [] , [] )
+                      AlignDefault
+                      (RowSpan 1)
+                      (ColSpan 1)
+                      [ Para [ Str "6" ] ]
+                  ]
+              ]
+          ]
+          (TableFoot ( "" , [] , [] ) [])
+      ]
+  , Div
+      ( "" , [ "table-wrap" ] , [] )
+      [ Table
+          ( "" , [] , [] )
+          (Caption Nothing [])
+          [ ( AlignLeft , ColWidthDefault )
+          , ( AlignLeft , ColWidthDefault )
+          , ( AlignLeft , ColWidthDefault )
+          ]
+          (TableHead
+             ( "" , [] , [] )
+             [ Row
+                 ( "" , [] , [] )
+                 [ Cell
+                     ( "" , [] , [] )
+                     AlignDefault
+                     (RowSpan 1)
+                     (ColSpan 1)
+                     [ Para [ Str "X" ] ]
+                 , Cell
+                     ( "" , [] , [] )
+                     AlignDefault
+                     (RowSpan 1)
+                     (ColSpan 1)
+                     [ Para [ Str "Y" ] ]
+                 , Cell
+                     ( "" , [] , [] )
+                     AlignDefault
+                     (RowSpan 1)
+                     (ColSpan 1)
+                     [ Para [ Str "Z" ] ]
+                 ]
+             ])
+          [ TableBody
+              ( "" , [] , [] )
+              (RowHeadColumns 0)
+              []
+              [ Row
+                  ( "" , [] , [] )
+                  [ Cell
+                      ( "" , [] , [] )
+                      AlignDefault
+                      (RowSpan 1)
+                      (ColSpan 1)
+                      [ Para [ Str "1" ] ]
+                  , Cell
+                      ( "" , [] , [] )
+                      AlignDefault
+                      (RowSpan 1)
+                      (ColSpan 1)
+                      [ Para [ Str "2" ] ]
+                  , Cell
+                      ( "" , [] , [] )
+                      AlignDefault
+                      (RowSpan 1)
+                      (ColSpan 1)
+                      [ Para [ Str "3" ] ]
+                  ]
+              , Row
+                  ( "" , [] , [] )
+                  [ Cell
+                      ( "" , [] , [] )
+                      AlignDefault
+                      (RowSpan 1)
+                      (ColSpan 1)
+                      [ Para [ Str "4" ] ]
+                  , Cell
+                      ( "" , [] , [] )
+                      AlignDefault
+                      (RowSpan 1)
+                      (ColSpan 1)
+                      [ Para [ Str "5" ] ]
+                  , Cell
+                      ( "" , [] , [] )
+                      AlignDefault
+                      (RowSpan 1)
+                      (ColSpan 1)
+                      [ Para [ Str "6" ] ]
+                  ]
+              ]
+          ]
+          (TableFoot ( "" , [] , [] ) [])
+      ]
+  , Div
+      ( "" , [ "table-wrap" ] , [] )
+      [ Table
+          ( "" , [] , [] )
+          (Caption Nothing [])
+          [ ( AlignLeft , ColWidthDefault )
+          , ( AlignLeft , ColWidthDefault )
+          , ( AlignLeft , ColWidthDefault )
+          ]
+          (TableHead
+             ( "" , [] , [] )
+             [ Row
+                 ( "" , [] , [] )
+                 [ Cell
+                     ( "" , [] , [] )
+                     AlignDefault
+                     (RowSpan 1)
+                     (ColSpan 1)
+                     [ Para [ Str "X" ] ]
+                 , Cell
+                     ( "" , [] , [] )
+                     AlignDefault
+                     (RowSpan 1)
+                     (ColSpan 1)
+                     [ Para [ Str "Y" ] ]
+                 , Cell
+                     ( "" , [] , [] )
+                     AlignDefault
+                     (RowSpan 1)
+                     (ColSpan 1)
+                     [ Para [ Str "Z" ] ]
+                 ]
+             ])
+          [ TableBody
+              ( "" , [] , [] )
+              (RowHeadColumns 0)
+              []
+              [ Row
+                  ( "" , [] , [] )
+                  [ Cell
+                      ( "" , [] , [] )
+                      AlignDefault
+                      (RowSpan 1)
+                      (ColSpan 1)
+                      [ Para [ Str "1" ] ]
+                  , Cell
+                      ( "" , [] , [] )
+                      AlignDefault
+                      (RowSpan 1)
+                      (ColSpan 1)
+                      [ Para [ Str "2" ] ]
+                  , Cell
+                      ( "" , [] , [] )
+                      AlignDefault
+                      (RowSpan 1)
+                      (ColSpan 1)
+                      [ Para [ Str "3" ] ]
+                  ]
+              , Row
+                  ( "" , [] , [] )
+                  [ Cell
+                      ( "" , [] , [] )
+                      AlignDefault
+                      (RowSpan 1)
+                      (ColSpan 1)
+                      [ Para [ Str "4" ] ]
+                  , Cell
+                      ( "" , [] , [] )
+                      AlignDefault
+                      (RowSpan 1)
+                      (ColSpan 1)
+                      [ Para [ Str "5" ] ]
+                  , Cell
+                      ( "" , [] , [] )
+                      AlignDefault
+                      (RowSpan 1)
+                      (ColSpan 1)
+                      [ Para [ Str "6" ] ]
+                  ]
+              ]
+          ]
+          (TableFoot ( "" , [] , [] ) [])
+      ]
+  , Div
+      ( "" , [ "table-wrap" ] , [] )
+      [ Table
+          ( "" , [] , [] )
+          (Caption Nothing [])
+          [ ( AlignLeft , ColWidthDefault )
+          , ( AlignLeft , ColWidthDefault )
+          , ( AlignLeft , ColWidthDefault )
+          ]
+          (TableHead
+             ( "" , [] , [] )
+             [ Row
+                 ( "" , [] , [] )
+                 [ Cell
+                     ( "" , [] , [] )
+                     AlignDefault
+                     (RowSpan 1)
+                     (ColSpan 1)
+                     [ Para [ Str "r1a" ] ]
+                 , Cell
+                     ( "" , [] , [] )
+                     AlignDefault
+                     (RowSpan 1)
+                     (ColSpan 1)
+                     [ Para [ Str "r1b" ] ]
+                 , Cell
+                     ( "" , [] , [] )
+                     AlignDefault
+                     (RowSpan 1)
+                     (ColSpan 1)
+                     [ Para [ Str "r1c" ] ]
+                 ]
+             , Row
+                 ( "" , [] , [] )
+                 [ Cell
+                     ( "" , [] , [] )
+                     AlignDefault
+                     (RowSpan 1)
+                     (ColSpan 1)
+                     [ Para [ Str "X" ] ]
+                 , Cell
+                     ( "" , [] , [] )
+                     AlignDefault
+                     (RowSpan 1)
+                     (ColSpan 1)
+                     [ Para [ Str "Y" ] ]
+                 , Cell
+                     ( "" , [] , [] )
+                     AlignDefault
+                     (RowSpan 1)
+                     (ColSpan 1)
+                     [ Para [ Str "Z" ] ]
+                 ]
+             ])
+          [ TableBody
+              ( "" , [] , [] )
+              (RowHeadColumns 0)
+              []
+              [ Row
+                  ( "" , [] , [] )
+                  [ Cell
+                      ( "" , [] , [] )
+                      AlignDefault
+                      (RowSpan 1)
+                      (ColSpan 1)
+                      [ Para [ Str "1" ] ]
+                  , Cell
+                      ( "" , [] , [] )
+                      AlignDefault
+                      (RowSpan 1)
+                      (ColSpan 1)
+                      [ Para [ Str "2" ] ]
+                  , Cell
+                      ( "" , [] , [] )
+                      AlignDefault
+                      (RowSpan 1)
+                      (ColSpan 1)
+                      [ Para [ Str "3" ] ]
+                  ]
+              , Row
+                  ( "" , [] , [] )
+                  [ Cell
+                      ( "" , [] , [] )
+                      AlignDefault
+                      (RowSpan 1)
+                      (ColSpan 1)
+                      [ Para [ Str "4" ] ]
+                  , Cell
+                      ( "" , [] , [] )
+                      AlignDefault
+                      (RowSpan 1)
+                      (ColSpan 1)
+                      [ Para [ Str "5" ] ]
+                  , Cell
+                      ( "" , [] , [] )
+                      AlignDefault
+                      (RowSpan 1)
+                      (ColSpan 1)
+                      [ Para [ Str "6" ] ]
+                  ]
+              ]
+          ]
+          (TableFoot ( "" , [] , [] ) [])
+      ]
+  , Div
+      ( "" , [ "table-wrap" ] , [] )
+      [ Table
+          ( "" , [] , [] )
+          (Caption Nothing [])
+          [ ( AlignLeft , ColWidthDefault )
+          , ( AlignLeft , ColWidthDefault )
+          , ( AlignLeft , ColWidthDefault )
+          ]
+          (TableHead
+             ( "" , [] , [] )
+             [ Row
+                 ( "" , [] , [] )
+                 [ Cell
+                     ( "" , [] , [] )
+                     AlignDefault
+                     (RowSpan 1)
+                     (ColSpan 1)
+                     [ Para [ Str "X" ] ]
+                 , Cell
+                     ( "" , [] , [] )
+                     AlignDefault
+                     (RowSpan 1)
+                     (ColSpan 1)
+                     [ Para [ Str "Y" ] ]
+                 , Cell
+                     ( "" , [] , [] )
+                     AlignDefault
+                     (RowSpan 1)
+                     (ColSpan 1)
+                     [ Para [ Str "Z" ] ]
+                 ]
+             ])
+          [ TableBody
+              ( "" , [] , [] )
+              (RowHeadColumns 0)
+              []
+              [ Row
+                  ( "" , [] , [] )
+                  [ Cell
+                      ( "" , [] , [] )
+                      AlignDefault
+                      (RowSpan 1)
+                      (ColSpan 1)
+                      [ Para [ Str "1" ] ]
+                  , Cell
+                      ( "" , [] , [] )
+                      AlignDefault
+                      (RowSpan 1)
+                      (ColSpan 1)
+                      [ Para [ Str "2" ] ]
+                  , Cell
+                      ( "" , [] , [] )
+                      AlignDefault
+                      (RowSpan 1)
+                      (ColSpan 1)
+                      [ Para [ Str "3" ] ]
+                  ]
+              , Row
+                  ( "" , [] , [] )
+                  [ Cell
+                      ( "" , [] , [] )
+                      AlignDefault
+                      (RowSpan 1)
+                      (ColSpan 1)
+                      [ Para [ Str "4" ] ]
+                  , Cell
+                      ( "" , [] , [] )
+                      AlignDefault
+                      (RowSpan 1)
+                      (ColSpan 1)
+                      [ Para [ Str "5" ] ]
+                  , Cell
+                      ( "" , [] , [] )
+                      AlignDefault
+                      (RowSpan 1)
+                      (ColSpan 1)
+                      [ Para [ Str "6" ] ]
+                  ]
+              ]
+          ]
+          (TableFoot ( "" , [] , [] ) [])
+      ]
+  , Header
+      2
+      ( "tables-without-headers" , [] , [] )
+      [ Str "Tables"
+      , Space
+      , Str "without"
+      , Space
+      , Str "Headers"
+      ]
+  , Div
+      ( "" , [ "table-wrap" ] , [] )
+      [ Table
+          ( "" , [] , [] )
+          (Caption Nothing [])
+          [ ( AlignLeft , ColWidthDefault )
+          , ( AlignLeft , ColWidthDefault )
+          , ( AlignLeft , ColWidthDefault )
+          ]
+          (TableHead ( "" , [] , [] ) [])
+          [ TableBody
+              ( "" , [] , [] )
+              (RowHeadColumns 0)
+              []
+              [ Row
+                  ( "" , [] , [] )
+                  [ Cell
+                      ( "" , [] , [] )
+                      AlignDefault
+                      (RowSpan 1)
+                      (ColSpan 1)
+                      [ Para [ Str "1" ] ]
+                  , Cell
+                      ( "" , [] , [] )
+                      AlignDefault
+                      (RowSpan 1)
+                      (ColSpan 1)
+                      [ Para [ Str "2" ] ]
+                  , Cell
+                      ( "" , [] , [] )
+                      AlignDefault
+                      (RowSpan 1)
+                      (ColSpan 1)
+                      [ Para [ Str "3" ] ]
+                  ]
+              , Row
+                  ( "" , [] , [] )
+                  [ Cell
+                      ( "" , [] , [] )
+                      AlignDefault
+                      (RowSpan 1)
+                      (ColSpan 1)
+                      [ Para [ Str "4" ] ]
+                  , Cell
+                      ( "" , [] , [] )
+                      AlignDefault
+                      (RowSpan 1)
+                      (ColSpan 1)
+                      [ Para [ Str "5" ] ]
+                  , Cell
+                      ( "" , [] , [] )
+                      AlignDefault
+                      (RowSpan 1)
+                      (ColSpan 1)
+                      [ Para [ Str "6" ] ]
+                  ]
+              ]
+          ]
+          (TableFoot ( "" , [] , [] ) [])
+      ]
+  , Div
+      ( "" , [ "table-wrap" ] , [] )
+      [ Table
+          ( "" , [] , [] )
+          (Caption Nothing [])
+          [ ( AlignLeft , ColWidthDefault )
+          , ( AlignLeft , ColWidthDefault )
+          , ( AlignLeft , ColWidthDefault )
+          ]
+          (TableHead ( "" , [] , [] ) [])
+          [ TableBody
+              ( "" , [] , [] )
+              (RowHeadColumns 0)
+              []
+              [ Row
+                  ( "" , [] , [] )
+                  [ Cell
+                      ( "" , [] , [] )
+                      AlignDefault
+                      (RowSpan 1)
+                      (ColSpan 1)
+                      [ Para [ Str "1" ] ]
+                  , Cell
+                      ( "" , [] , [] )
+                      AlignDefault
+                      (RowSpan 1)
+                      (ColSpan 1)
+                      [ Para [ Str "2" ] ]
+                  , Cell
+                      ( "" , [] , [] )
+                      AlignDefault
+                      (RowSpan 1)
+                      (ColSpan 1)
+                      [ Para [ Str "3" ] ]
+                  ]
+              , Row
+                  ( "" , [] , [] )
+                  [ Cell
+                      ( "" , [] , [] )
+                      AlignDefault
+                      (RowSpan 1)
+                      (ColSpan 1)
+                      [ Para [ Str "4" ] ]
+                  , Cell
+                      ( "" , [] , [] )
+                      AlignDefault
+                      (RowSpan 1)
+                      (ColSpan 1)
+                      [ Para [ Str "5" ] ]
+                  , Cell
+                      ( "" , [] , [] )
+                      AlignDefault
+                      (RowSpan 1)
+                      (ColSpan 1)
+                      [ Para [ Str "6" ] ]
+                  ]
+              ]
+          ]
+          (TableFoot ( "" , [] , [] ) [])
+      ]
+  , Div
+      ( "" , [ "table-wrap" ] , [] )
+      [ Table
+          ( "" , [] , [] )
+          (Caption Nothing [])
+          [ ( AlignLeft , ColWidthDefault )
+          , ( AlignLeft , ColWidthDefault )
+          , ( AlignLeft , ColWidthDefault )
+          ]
+          (TableHead ( "" , [] , [] ) [])
+          [ TableBody
+              ( "" , [] , [] )
+              (RowHeadColumns 0)
+              []
+              [ Row
+                  ( "" , [] , [] )
+                  [ Cell
+                      ( "" , [] , [] )
+                      AlignDefault
+                      (RowSpan 1)
+                      (ColSpan 1)
+                      [ Para [ Str "1" ] ]
+                  , Cell
+                      ( "" , [] , [] )
+                      AlignDefault
+                      (RowSpan 1)
+                      (ColSpan 1)
+                      [ Para [ Str "2" ] ]
+                  , Cell
+                      ( "" , [] , [] )
+                      AlignDefault
+                      (RowSpan 1)
+                      (ColSpan 1)
+                      [ Para [ Str "3" ] ]
+                  ]
+              , Row
+                  ( "" , [] , [] )
+                  [ Cell
+                      ( "" , [] , [] )
+                      AlignDefault
+                      (RowSpan 1)
+                      (ColSpan 1)
+                      [ Para [ Str "4" ] ]
+                  , Cell
+                      ( "" , [] , [] )
+                      AlignDefault
+                      (RowSpan 1)
+                      (ColSpan 1)
+                      [ Para [ Str "5" ] ]
+                  , Cell
+                      ( "" , [] , [] )
+                      AlignDefault
+                      (RowSpan 1)
+                      (ColSpan 1)
+                      [ Para [ Str "6" ] ]
+                  ]
+              ]
+          ]
+          (TableFoot ( "" , [] , [] ) [])
+      ]
+  , Div
+      ( "" , [ "table-wrap" ] , [] )
+      [ Table
+          ( "" , [] , [] )
+          (Caption Nothing [])
+          [ ( AlignLeft , ColWidthDefault )
+          , ( AlignLeft , ColWidthDefault )
+          , ( AlignLeft , ColWidthDefault )
+          ]
+          (TableHead ( "" , [] , [] ) [])
+          [ TableBody
+              ( "" , [] , [] )
+              (RowHeadColumns 0)
+              []
+              [ Row
+                  ( "" , [] , [] )
+                  [ Cell
+                      ( "" , [] , [] )
+                      AlignDefault
+                      (RowSpan 1)
+                      (ColSpan 1)
+                      [ Para [ Str "1" ] ]
+                  , Cell
+                      ( "" , [] , [] )
+                      AlignDefault
+                      (RowSpan 1)
+                      (ColSpan 1)
+                      [ Para [ Str "2" ] ]
+                  , Cell
+                      ( "" , [] , [] )
+                      AlignDefault
+                      (RowSpan 1)
+                      (ColSpan 1)
+                      [ Para [ Str "3" ] ]
+                  ]
+              , Row
+                  ( "" , [] , [] )
+                  [ Cell
+                      ( "" , [] , [] )
+                      AlignDefault
+                      (RowSpan 1)
+                      (ColSpan 1)
+                      [ Para [ Str "4" ] ]
+                  , Cell
+                      ( "" , [] , [] )
+                      AlignDefault
+                      (RowSpan 1)
+                      (ColSpan 1)
+                      [ Para [ Str "5" ] ]
+                  , Cell
+                      ( "" , [] , [] )
+                      AlignDefault
+                      (RowSpan 1)
+                      (ColSpan 1)
+                      [ Para [ Str "6" ] ]
+                  ]
+              ]
+          ]
+          (TableFoot ( "" , [] , [] ) [])
+      ]
+  , Header
+      2
+      ( "table-with-spans-and-alignments" , [] , [] )
+      [ Str "Tables"
+      , Space
+      , Str "with"
+      , Space
+      , Str "spans"
+      , Space
+      , Str "and"
+      , Space
+      , Str "alignments"
+      ]
+  , Div
+      ( "" , [ "table-wrap" ] , [] )
+      [ Table
+          ( "" , [] , [] )
+          (Caption Nothing [])
+          [ ( AlignLeft , ColWidthDefault )
+          , ( AlignLeft , ColWidthDefault )
+          , ( AlignLeft , ColWidthDefault )
+          ]
+          (TableHead
+             ( "" , [] , [] )
+             [ Row
+                 ( "" , [] , [] )
+                 [ Cell
+                     ( "" , [] , [] )
+                     AlignDefault
+                     (RowSpan 1)
+                     (ColSpan 2)
+                     [ Para [ Str "1" ] ]
+                 , Cell
+                     ( "" , [] , [] )
+                     AlignRight
+                     (RowSpan 1)
+                     (ColSpan 1)
+                     [ Para [ Str "2" ] ]
+                 ]
+             ])
+          [ TableBody
+              ( "" , [] , [] )
+              (RowHeadColumns 0)
+              []
+              [ Row
+                  ( "" , [] , [] )
+                  [ Cell
+                      ( "" , [] , [] )
+                      AlignDefault
+                      (RowSpan 1)
+                      (ColSpan 2)
+                      [ Para [ Str "1" ] ]
+                  , Cell
+                      ( "" , [] , [] )
+                      AlignLeft
+                      (RowSpan 1)
+                      (ColSpan 1)
+                      [ Para [ Str "2" ] ]
+                  ]
+              , Row
+                  ( "" , [] , [] )
+                  [ Cell
+                      ( "" , [] , [] )
+                      AlignDefault
+                      (RowSpan 2)
+                      (ColSpan 1)
+                      [ Para [ Str "4" ] ]
+                  , Cell
+                      ( "" , [] , [] )
+                      AlignDefault
+                      (RowSpan 1)
+                      (ColSpan 1)
+                      [ Para [ Str "5" ] ]
+                  , Cell
+                      ( "" , [] , [] )
+                      AlignDefault
+                      (RowSpan 1)
+                      (ColSpan 1)
+                      [ Para [ Str "6" ] ]
+                  ]
+              , Row
+                  ( "" , [] , [] )
+                  [ Cell
+                      ( "" , [] , [] )
+                      AlignDefault
+                      (RowSpan 1)
+                      (ColSpan 2)
+                      [ Para [ Str "7" ] ]
+                  ]
+              ]
+          ]
+          (TableFoot ( "" , [] , [] ) [])
+      ]
+  , Header
+      2
+      ( "table-with-footer" , [] , [] )
+      [ Str "Table" , Space , Str "with" , Space , Str "footer" ]
+  , Div
+      ( "" , [ "table-wrap" ] , [] )
+      [ Table
+          ( "" , [] , [] )
+          (Caption Nothing [])
+          [ ( AlignLeft , ColWidthDefault )
+          , ( AlignLeft , ColWidthDefault )
+          , ( AlignLeft , ColWidthDefault )
+          ]
+          (TableHead ( "" , [] , [] ) [])
+          [ TableBody
+              ( "" , [] , [] )
+              (RowHeadColumns 0)
+              []
+              [ Row
+                  ( "" , [] , [] )
+                  [ Cell
+                      ( "" , [] , [] )
+                      AlignDefault
+                      (RowSpan 1)
+                      (ColSpan 1)
+                      [ Para [ Str "1" ] ]
+                  , Cell
+                      ( "" , [] , [] )
+                      AlignDefault
+                      (RowSpan 1)
+                      (ColSpan 1)
+                      [ Para [ Str "2" ] ]
+                  , Cell
+                      ( "" , [] , [] )
+                      AlignDefault
+                      (RowSpan 1)
+                      (ColSpan 1)
+                      [ Para [ Str "3" ] ]
+                  ]
+              ]
+          ]
+          (TableFoot
+             ( "" , [] , [] )
+             [ Row
+                 ( "" , [] , [] )
+                 [ Cell
+                     ( "" , [] , [] )
+                     AlignRight
+                     (RowSpan 1)
+                     (ColSpan 1)
+                     [ Para [ Str "f1" ] ]
+                 , Cell
+                     ( "" , [] , [] )
+                     AlignDefault
+                     (RowSpan 1)
+                     (ColSpan 1)
+                     [ Para [ Str "f2" ] ]
+                 , Cell
+                     ( "" , [] , [] )
+                     AlignDefault
+                     (RowSpan 1)
+                     (ColSpan 1)
+                     [ Para [ Str "f3" ] ]
+                 ]
+             , Row
+                 ( "" , [] , [] )
+                 [ Cell
+                     ( "" , [] , [] )
+                     AlignRight
+                     (RowSpan 1)
+                     (ColSpan 1)
+                     [ Para [ Str "f4" ] ]
+                 , Cell
+                     ( "" , [] , [] )
+                     AlignDefault
+                     (RowSpan 1)
+                     (ColSpan 1)
+                     [ Para [ Str "f5" ] ]
+                 , Cell
+                     ( "" , [] , [] )
+                     AlignDefault
+                     (RowSpan 1)
+                     (ColSpan 1)
+                     [ Para [ Str "f6" ] ]
+                 ]
+             ])
+      ]
+  , Header
+      2
+      ( "table-with-multiple-bodies" , [] , [] )
+      [ Str "Table"
+      , Space
+      , Str "With"
+      , Space
+      , Str "Multiple"
+      , Space
+      , Str "Bodies"
+      ]
+  , Div
+      ( "" , [ "table-wrap" ] , [] )
+      [ Table
+          ( "" , [] , [] )
+          (Caption Nothing [])
+          [ ( AlignLeft , ColWidthDefault )
+          , ( AlignLeft , ColWidthDefault )
+          , ( AlignLeft , ColWidthDefault )
+          ]
+          (TableHead ( "" , [] , [] ) [])
+          [ TableBody
+              ( "" , [] , [] )
+              (RowHeadColumns 0)
+              []
+              [ Row
+                  ( "" , [] , [] )
+                  [ Cell
+                      ( "" , [] , [] )
+                      AlignRight
+                      (RowSpan 1)
+                      (ColSpan 1)
+                      [ Para [ Str "a1" ] ]
+                  , Cell
+                      ( "" , [] , [] )
+                      AlignDefault
+                      (RowSpan 1)
+                      (ColSpan 1)
+                      [ Para [ Str "a2" ] ]
+                  , Cell
+                      ( "" , [] , [] )
+                      AlignDefault
+                      (RowSpan 1)
+                      (ColSpan 1)
+                      [ Para [ Str "a3" ] ]
+                  ]
+              ]
+          , TableBody
+              ( "" , [] , [] )
+              (RowHeadColumns 0)
+              []
+              [ Row
+                  ( "" , [] , [] )
+                  [ Cell
+                      ( "" , [] , [] )
+                      AlignDefault
+                      (RowSpan 1)
+                      (ColSpan 1)
+                      [ Para [ Str "b1" ] ]
+                  , Cell
+                      ( "" , [] , [] )
+                      AlignDefault
+                      (RowSpan 1)
+                      (ColSpan 1)
+                      [ Para [ Str "b2" ] ]
+                  , Cell
+                      ( "" , [] , [] )
+                      AlignDefault
+                      (RowSpan 1)
+                      (ColSpan 1)
+                      [ Para [ Str "b3" ] ]
+                  ]
+              ]
+          ]
+          (TableFoot ( "" , [] , [] ) [])
+      ]
+  , Header
+      2
+      ( "empty-tables" , [] , [] )
+      [ Str "Empty" , Space , Str "Tables" ]
+  , Para
+      [ Str "This"
+      , Space
+      , Str "section"
+      , Space
+      , Str "should"
+      , Space
+      , Str "be"
+      , Space
+      , Str "empty."
+      ]
+  , Header 1 ( "" , [] , [] ) [ Str "References" ]
+  , Div ( "refs" , [] , [] ) []
+  , Header 1 ( "" , [] , [] ) [ Str "Notes" ]
+  , Div ( "refs" , [] , [] ) []
+  ]
diff --git a/test/jats-reader.xml b/test/jats-reader.xml
--- a/test/jats-reader.xml
+++ b/test/jats-reader.xml
@@ -1,1785 +1,1460 @@
 <?xml version="1.0" encoding="utf-8" ?>
-<!DOCTYPE article PUBLIC "-//NLM//DTD JATS (Z39.96) Journal Publishing DTD v1.0 20120330//EN"
-                  "JATS-journalpublishing1.dtd">
-<article xmlns:mml="http://www.w3.org/1998/Math/MathML" xmlns:xlink="http://www.w3.org/1999/xlink" dtd-version="1.0" article-type="other">
-<front>
-<journal-meta>
-<journal-title-group>
-</journal-title-group>
-<publisher>
-<publisher-name></publisher-name>
-</publisher>
-</journal-meta>
-<article-meta>
-<title-group>
-<article-title>Pandoc Test Suite</article-title>
-</title-group>
-<contrib-group>
-  <contrib contrib-type="author">
-    <name>
-      <surname>MacFarlane</surname>
-      <given-names>John</given-names>
-    </name>
-  <contrib contrib-type="author">
-    <name>
-      <surname>Anonymous</surname>
-    </name>
-  </contrib>
-</contrib-group>
-</article-meta>
-</front>
-<body>
-<p>
-  This is a set of tests for pandoc. Most of them are adapted from John
-  Gruber's markdown test suite.
-</p>
-<sec id="headers">
-  <title>Headers</title>
-  <sec id="level-2-with-an-embedded-link">
-    <title>Level 2 with an
-    <ext-link ext-link-type="uri" xlink:href="/url">embedded
-    link</ext-link></title>
-    <sec id="level-3-with-emphasis">
-      <title>Level 3 with <italic>emphasis</italic></title>
-      <sec id="level-4">
-        <title>Level 4</title>
-        <sec id="level-5">
-          <title>Level 5</title>
-        </sec>
-      </sec>
-    </sec>
-  </sec>
-</sec>
-<sec id="level-1">
-  <title>Level 1</title>
-  <sec id="level-2-with-emphasis">
-    <title>Level 2 with <italic>emphasis</italic></title>
-    <sec id="level-3">
-      <title>Level 3</title>
-      <p>
-        with no blank line
-      </p>
-    </sec>
-  </sec>
-  <sec id="level-2">
-    <title>Level 2</title>
-    <p>
-      with no blank line
-    </p>
-  </sec>
-</sec>
-<sec id="paragraphs">
-  <title>Paragraphs</title>
-  <p>
-    Here's a regular paragraph.
-  </p>
-  <p>
-    In Markdown 1.0.0 and earlier. Version 8. This line turns into a
-    list item. Because a hard-wrapped line in the middle of a paragraph
-    looked like a list item.
-  </p>
-  <p>
-    Here's one with a bullet. * criminey.
-  </p>
-  <p>
-    There should be a hard line break<break />here.
-  </p>
-</sec>
-<sec id="block-quotes">
-  <title>Block Quotes</title>
-  <p>
-    E-mail style:
-  </p>
-  <disp-quote>
-    <p>
-      This is a block quote. It is pretty short.
-    </p>
-  </disp-quote>
-  <disp-quote>
-    <p>
-      Code in a block quote:
-    </p>
-    <preformat>sub status {
-    print &quot;working&quot;;
-}</preformat>
-    <p>
-      A list:
-    </p>
-    <list list-type="order">
-      <list-item>
-        <p>
-          item one
-        </p>
-      </list-item>
-      <list-item>
-        <p>
-          item two
-        </p>
-      </list-item>
-    </list>
-    <p>
-      Nested block quotes:
-    </p>
-    <disp-quote>
-      <p>
-        nested
-      </p>
-    </disp-quote>
-    <disp-quote>
-      <p>
-        nested
-      </p>
-    </disp-quote>
-  </disp-quote>
-  <p>
-    This should not be a block quote: 2 &gt; 1.
-  </p>
-  <p>
-    Box-style:
-  </p>
-  <disp-quote>
-    <p>
-      Example:
-    </p>
-    <preformat>sub status {
-    print &quot;working&quot;;
-}</preformat>
-  </disp-quote>
-  <disp-quote>
-    <list list-type="order">
-      <list-item>
-        <p>
-          do laundry
-        </p>
-      </list-item>
-      <list-item>
-        <p>
-          take out the trash
-        </p>
-      </list-item>
-    </list>
-  </disp-quote>
-  <p>
-    Here's a nested one:
-  </p>
-  <disp-quote>
-    <p>
-      Joe said:
-    </p>
-    <disp-quote>
-      <p>
-        Don't quote me.
-      </p>
-    </disp-quote>
-  </disp-quote>
-  <p>
-    And a following paragraph.
-  </p>
-</sec>
-<sec id="code-blocks">
-  <title>Code Blocks</title>
-  <p>
-    Code:
-  </p>
-  <preformat>---- (should be four hyphens)
-
-sub status {
-    print &quot;working&quot;;
-}
-
-this code block is indented by one tab</preformat>
-  <p>
-    And:
-  </p>
-  <preformat>    this code block is indented by two tabs
-
-These should not be escaped:  \$ \\ \&gt; \[ \{</preformat>
-</sec>
-<sec id="lists">
-  <title>Lists</title>
-  <sec id="unordered">
-    <title>Unordered</title>
-    <p>
-      Asterisks tight:
-    </p>
-    <list list-type="bullet">
-      <list-item>
-        <p>
-          asterisk 1
-        </p>
-      </list-item>
-      <list-item>
-        <p>
-          asterisk 2
-        </p>
-      </list-item>
-      <list-item>
-        <p>
-          asterisk 3
-        </p>
-      </list-item>
-    </list>
-    <p>
-      Asterisks loose:
-    </p>
-    <list list-type="bullet">
-      <list-item>
-        <p>
-          asterisk 1
-        </p>
-      </list-item>
-      <list-item>
-        <p>
-          asterisk 2
-        </p>
-      </list-item>
-      <list-item>
-        <p>
-          asterisk 3
-        </p>
-      </list-item>
-    </list>
-    <p>
-      Pluses tight:
-    </p>
-    <list list-type="bullet">
-      <list-item>
-        <p>
-          Plus 1
-        </p>
-      </list-item>
-      <list-item>
-        <p>
-          Plus 2
-        </p>
-      </list-item>
-      <list-item>
-        <p>
-          Plus 3
-        </p>
-      </list-item>
-    </list>
-    <p>
-      Pluses loose:
-    </p>
-    <list list-type="bullet">
-      <list-item>
-        <p>
-          Plus 1
-        </p>
-      </list-item>
-      <list-item>
-        <p>
-          Plus 2
-        </p>
-      </list-item>
-      <list-item>
-        <p>
-          Plus 3
-        </p>
-      </list-item>
-    </list>
-    <p>
-      Minuses tight:
-    </p>
-    <list list-type="bullet">
-      <list-item>
-        <p>
-          Minus 1
-        </p>
-      </list-item>
-      <list-item>
-        <p>
-          Minus 2
-        </p>
-      </list-item>
-      <list-item>
-        <p>
-          Minus 3
-        </p>
-      </list-item>
-    </list>
-    <p>
-      Minuses loose:
-    </p>
-    <list list-type="bullet">
-      <list-item>
-        <p>
-          Minus 1
-        </p>
-      </list-item>
-      <list-item>
-        <p>
-          Minus 2
-        </p>
-      </list-item>
-      <list-item>
-        <p>
-          Minus 3
-        </p>
-      </list-item>
-    </list>
-  </sec>
-  <sec id="ordered">
-    <title>Ordered</title>
-    <p>
-      Tight:
-    </p>
-    <list list-type="order">
-      <list-item>
-        <p>
-          First
-        </p>
-      </list-item>
-      <list-item>
-        <p>
-          Second
-        </p>
-      </list-item>
-      <list-item>
-        <p>
-          Third
-        </p>
-      </list-item>
-    </list>
-    <p>
-      and:
-    </p>
-    <list list-type="order">
-      <list-item>
-        <p>
-          One
-        </p>
-      </list-item>
-      <list-item>
-        <p>
-          Two
-        </p>
-      </list-item>
-      <list-item>
-        <p>
-          Three
-        </p>
-      </list-item>
-    </list>
-    <p>
-      Loose using tabs:
-    </p>
-    <list list-type="order">
-      <list-item>
-        <p>
-          First
-        </p>
-      </list-item>
-      <list-item>
-        <p>
-          Second
-        </p>
-      </list-item>
-      <list-item>
-        <p>
-          Third
-        </p>
-      </list-item>
-    </list>
-    <p>
-      and using spaces:
-    </p>
-    <list list-type="order">
-      <list-item>
-        <p>
-          One
-        </p>
-      </list-item>
-      <list-item>
-        <p>
-          Two
-        </p>
-      </list-item>
-      <list-item>
-        <p>
-          Three
-        </p>
-      </list-item>
-    </list>
-    <p>
-      Multiple paragraphs:
-    </p>
-    <list list-type="order">
-      <list-item>
-        <p>
-          Item 1, graf one.
-        </p>
-        <p>
-          Item 1. graf two. The quick brown fox jumped over the lazy
-          dog's back.
-        </p>
-      </list-item>
-      <list-item>
-        <p>
-          Item 2.
-        </p>
-      </list-item>
-      <list-item>
-        <p>
-          Item 3.
-        </p>
-      </list-item>
-    </list>
-    <p>
-      List styles:
-    </p>
-    <list list-type="order"></list>
-    <list list-type="roman-lower"></list>
-  </sec>
-  <sec id="nested">
-    <title>Nested</title>
-    <list list-type="bullet">
-      <list-item>
-        <p>
-          Tab
-        </p>
-        <list list-type="bullet">
-          <list-item>
-            <p>
-              Tab
-            </p>
-            <list list-type="bullet">
-              <list-item>
-                <p>
-                  Tab
-                </p>
-              </list-item>
-            </list>
-          </list-item>
-        </list>
-      </list-item>
-    </list>
-    <p>
-      Here's another:
-    </p>
-    <list list-type="order">
-      <list-item>
-        <p>
-          First
-        </p>
-      </list-item>
-      <list-item>
-        <p>
-          Second:
-        </p>
-        <list list-type="bullet">
-          <list-item>
-            <p>
-              Fee
-            </p>
-          </list-item>
-          <list-item>
-            <p>
-              Fie
-            </p>
-          </list-item>
-          <list-item>
-            <p>
-              Foe
-            </p>
-          </list-item>
-        </list>
-      </list-item>
-      <list-item>
-        <p>
-          Third
-        </p>
-      </list-item>
-    </list>
-    <p>
-      Same thing but with paragraphs:
-    </p>
-    <list list-type="order">
-      <list-item>
-        <p>
-          First
-        </p>
-      </list-item>
-      <list-item>
-        <p>
-          Second:
-        </p>
-        <list list-type="bullet">
-          <list-item>
-            <p>
-              Fee
-            </p>
-          </list-item>
-          <list-item>
-            <p>
-              Fie
-            </p>
-          </list-item>
-          <list-item>
-            <p>
-              Foe
-            </p>
-          </list-item>
-        </list>
-      </list-item>
-      <list-item>
-        <p>
-          Third
-        </p>
-      </list-item>
-    </list>
-  </sec>
-  <sec id="tabs-and-spaces">
-    <title>Tabs and spaces</title>
-    <list list-type="bullet">
-      <list-item>
-        <p>
-          this is a list item indented with tabs
-        </p>
-      </list-item>
-      <list-item>
-        <p>
-          this is a list item indented with spaces
-        </p>
-        <list list-type="bullet">
-          <list-item>
-            <p>
-              this is an example list item indented with tabs
-            </p>
-          </list-item>
-          <list-item>
-            <p>
-              this is an example list item indented with spaces
-            </p>
-          </list-item>
-        </list>
-      </list-item>
-    </list>
-  </sec>
-  <sec id="fancy-list-markers">
-    <title>Fancy list markers</title>
-    <p>
-      Autonumbering:
-    </p>
-    <list list-type="order">
-      <list-item>
-        <p>
-          Autonumber.
-        </p>
-      </list-item>
-      <list-item>
-        <p>
-          More.
-        </p>
-        <list list-type="order">
-          <list-item>
-            <p>
-              Nested.
-            </p>
-          </list-item>
-        </list>
-      </list-item>
-    </list>
-  </sec>
-  <sec id="definition">
-    <title>Definition</title>
-    <def-list>
-      <def-item>
-        <term>
-          Violin
-        </term>
-        <def>
-          <p>
-            Stringed musical instrument.
-          </p>
-          <p>
-            Torture device.
-          </p>
-        </def>
-      </def-item>
-      <def-item>
-        <term>
-          Cello<break />Violoncello
-        </term>
-        <def>
-          <p>
-            Low-voiced stringed instrument.
-          </p>
-        </def>
-      </def-item>
-    </def-list>
-  </sec>
-</sec>
-<sec id="inline-markup">
-  <title>Inline Markup</title>
-  <p>
-    This is <italic>emphasized</italic>, and so <italic>is
-    this</italic>.
-  </p>
-  <p>
-    This is <bold role="strong">strong</bold>, and so
-    <bold role="strong">is this</bold>.
-  </p>
-  <p>
-    Empty <bold role="strong"></bold> and <italic></italic>.
-  </p>
-  <p>
-    An
-    <italic><ext-link ext-link-type="uri" xlink:href="/url">emphasized
-    link</ext-link></italic>.
-  </p>
-  <p>
-    <bold role="strong"><italic>This is strong and em.</italic></bold>
-  </p>
-  <p>
-    So is <bold role="strong"><italic>this</italic></bold> word.
-  </p>
-  <p>
-    <bold role="strong"><italic>This is strong and em.</italic></bold>
-  </p>
-  <p>
-    So is <bold role="strong"><italic>this</italic></bold> word.
-  </p>
-  <p>
-    This is code: <monospace>&gt;</monospace>, <monospace>$</monospace>,
-    <monospace>\</monospace>, <monospace>\$</monospace>,
-    <monospace>&lt;html&gt;</monospace>.
-  </p>
-  <p>
-    This is <sc role="smallcaps">small caps</sc>.
-  </p>
-  <p>
-    These are all underlined: foo and bar.
-  </p>
-  <p>
-    These are all strikethrough: <strike>foo</strike>,
-    <strike>bar</strike>, and <strike>baz</strike>.
-  </p>
-</sec>
-<sec id="smart-quotes-ellipses-dashes">
-  <title>Smart quotes, ellipses, dashes</title>
-  <p>
-    &quot;Hello,&quot; said the spider. &quot;'Shelob' is my name.&quot;
-  </p>
-  <p>
-    'A', 'B', and 'C' are letters.
-  </p>
-  <p>
-    'Oak,' 'elm,' and 'beech' are names of trees. So is 'pine.'
-  </p>
-  <p>
-    'He said, &quot;I want to go.&quot;' Were you alive in the 70's?
-  </p>
-  <p>
-    Here is some quoted '<monospace>code</monospace>' and a
-    &quot;<ext-link ext-link-type="uri" xlink:href="http://example.com/?foo=1&amp;bar=2">quoted
-    link</ext-link>&quot;.
-  </p>
-  <p>
-    Some dashes: one---two --- three--four -- five.
-  </p>
-  <p>
-    Dashes between numbers: 5-7, 255-66, 1987-1999.
-  </p>
-  <p>
-    Ellipses...and. . .and . . . .
-  </p>
-</sec>
-<sec id="latex">
-  <title>LaTeX</title>
-  <list list-type="bullet">
-    <list-item>
-      <p>
-        \cite[22-23]{smith.1899}
-      </p>
-    </list-item>
-    <list-item>
-      <p>
-        \doublespacing
-      </p>
-    </list-item>
-    <list-item>
-      <p>
-        $2+2=4$
-      </p>
-    </list-item>
-    <list-item>
-      <p>
-        $x \in y$
-      </p>
-    </list-item>
-    <list-item>
-      <p>
-        $\alpha \wedge \omega$
-      </p>
-    </list-item>
-    <list-item>
-      <p>
-        $223$
-      </p>
-    </list-item>
-    <list-item>
-      <p>
-        $p$-Tree
-      </p>
-    </list-item>
-    <list-item>
-      <p>
-        $\frac{d}{dx}f(x)=\lim_{h\to 0}\frac{f(x+h)-f(x)}{h}$
-      </p>
-    </list-item>
-    <list-item>
-      <p>
-        Here's one that has a line break in it: $\alpha + \omega \times
-        x^2$.
-      </p>
-    </list-item>
-  </list>
-  <p>
-    These shouldn't be math:
-  </p>
-  <list list-type="bullet">
-    <list-item>
-      <p>
-        To get the famous equation, write
-        <monospace>$e = mc^2$</monospace>.
-      </p>
-    </list-item>
-    <list-item>
-      <p>
-        $22,000 is a <italic>lot</italic> of money. So is $34,000. (It
-        worked if &quot;lot&quot; is emphasized.)
-      </p>
-    </list-item>
-    <list-item>
-      <p>
-        Escaped <monospace>$</monospace>: $73 <italic>this should be
-        emphasized</italic> 23$.
-      </p>
-    </list-item>
-  </list>
-  <p>
-    Here's a LaTeX table:
-  </p>
-  <p>
-    \begin{tabular}{|l|l|}\hline Animal &amp; Number \\ \hline Dog &amp;
-    2 \\ Cat &amp; 1 \\ \hline \end{tabular}
-  </p>
-</sec>
-<sec id="special-characters">
-  <title>Special Characters</title>
-  <p>
-    Here is some unicode:
-  </p>
-  <list list-type="bullet">
-    <list-item>
-      <p>
-        I hat: Î
-      </p>
-    </list-item>
-    <list-item>
-      <p>
-        o umlaut: ö
-      </p>
-    </list-item>
-    <list-item>
-      <p>
-        section: §
-      </p>
-    </list-item>
-    <list-item>
-      <p>
-        set membership: elem
-      </p>
-    </list-item>
-    <list-item>
-      <p>
-        copyright: ©
-      </p>
-    </list-item>
-  </list>
-  <p>
-    AT&amp;T has an ampersand in their name.
-  </p>
-  <p>
-    AT&amp;T is another way to write it.
-  </p>
-  <p>
-    This &amp; that.
-  </p>
-  <p>
-    4 &lt; 5.
-  </p>
-  <p>
-    6 &gt; 5.
-  </p>
-  <p>
-    Backslash: \
-  </p>
-  <p>
-    Backtick: `
-  </p>
-  <p>
-    Asterisk: *
-  </p>
-  <p>
-    Underscore: _
-  </p>
-  <p>
-    Left brace: {
-  </p>
-  <p>
-    Right brace: }
-  </p>
-  <p>
-    Left bracket: [
-  </p>
-  <p>
-    Right bracket: ]
-  </p>
-  <p>
-    Left paren: (
-  </p>
-  <p>
-    Right paren: )
-  </p>
-  <p>
-    Greater-than: &gt;
-  </p>
-  <p>
-    Hash: #
-  </p>
-  <p>
-    Period: .
-  </p>
-  <p>
-    Bang: !
-  </p>
-  <p>
-    Plus: +
-  </p>
-  <p>
-    Minus: -
-  </p>
-</sec>
-<sec id="links">
-  <title>Links</title>
-  <sec id="explicit">
-    <title>Explicit</title>
-    <p>
-      Just a
-      <ext-link ext-link-type="uri" xlink:href="/url/">URL</ext-link>.
-    </p>
-    <p>
-      <ext-link ext-link-type="uri" xlink:href="/url/" xlink:title="title">URL
-      and title</ext-link>.
-    </p>
-    <p>
-      <ext-link ext-link-type="uri" xlink:href="/url/" xlink:title="title preceded by two spaces">URL
-      and title</ext-link>.
-    </p>
-    <p>
-      <ext-link ext-link-type="uri" xlink:href="/url/" xlink:title="title preceded by a tab">URL
-      and title</ext-link>.
-    </p>
-    <p>
-      <ext-link ext-link-type="uri" xlink:href="/url/" xlink:title="title with &quot;quotes&quot; in it">URL
-      and title</ext-link>
-    </p>
-    <p>
-      <ext-link ext-link-type="uri" xlink:href="/url/" xlink:title="title with single quotes">URL
-      and title</ext-link>
-    </p>
-    <p>
-      Email link (nobody [at] nowhere.net)
-    </p>
-    <p>
-      <ext-link ext-link-type="uri" xlink:href="">Empty</ext-link>.
-    </p>
-  </sec>
-  <sec id="reference">
-    <title>Reference</title>
-    <p>
-      Foo
-      <ext-link ext-link-type="uri" xlink:href="/url/">bar</ext-link>.
-    </p>
-    <p>
-      Foo
-      <ext-link ext-link-type="uri" xlink:href="/url/">bar</ext-link>.
-    </p>
-    <p>
-      Foo
-      <ext-link ext-link-type="uri" xlink:href="/url/">bar</ext-link>.
-    </p>
-    <p>
-      With <ext-link ext-link-type="uri" xlink:href="/url/">embedded
-      [brackets]</ext-link>.
-    </p>
-    <p>
-      <ext-link ext-link-type="uri" xlink:href="/url/">b</ext-link> by
-      itself should be a link.
-    </p>
-    <p>
-      Indented
-      <ext-link ext-link-type="uri" xlink:href="/url">once</ext-link>.
-    </p>
-    <p>
-      Indented
-      <ext-link ext-link-type="uri" xlink:href="/url">twice</ext-link>.
-    </p>
-    <p>
-      Indented
-      <ext-link ext-link-type="uri" xlink:href="/url">thrice</ext-link>.
-    </p>
-    <p>
-      This should [not] be a link.
-    </p>
-    <preformat>[not]: /url</preformat>
-    <p>
-      Foo
-      <ext-link ext-link-type="uri" xlink:href="/url/" xlink:title="Title with &quot;quotes&quot; inside">bar</ext-link>.
-    </p>
-    <p>
-      Foo
-      <ext-link ext-link-type="uri" xlink:href="/url/" xlink:title="Title with &quot;quote&quot; inside">biz</ext-link>.
-    </p>
-  </sec>
-  <sec id="with-ampersands">
-    <title>With ampersands</title>
-    <p>
-      Here's a
-      <ext-link ext-link-type="uri" xlink:href="http://example.com/?foo=1&amp;bar=2">link
-      with an ampersand in the URL</ext-link>.
-    </p>
-    <p>
-      Here's a link with an amersand in the link text:
-      <ext-link ext-link-type="uri" xlink:href="http://att.com/" xlink:title="AT&amp;T">AT&amp;T</ext-link>.
-    </p>
-    <p>
-      Here's an
-      <ext-link ext-link-type="uri" xlink:href="/script?foo=1&amp;bar=2">inline
-      link</ext-link>.
-    </p>
-    <p>
-      Here's an
-      <ext-link ext-link-type="uri" xlink:href="/script?foo=1&amp;bar=2">inline
-      link in pointy braces</ext-link>.
-    </p>
-  </sec>
-  <sec id="autolinks">
-    <title>Autolinks</title>
-    <p>
-      With an ampersand:
-      <ext-link ext-link-type="uri" xlink:href="http://example.com/?foo=1&amp;bar=2">http://example.com/?foo=1&amp;bar=2</ext-link>
-    </p>
-    <list list-type="bullet">
-      <list-item>
-        <p>
-          In a list?
-        </p>
-      </list-item>
-      <list-item>
-        <p>
-          <ext-link ext-link-type="uri" xlink:href="http://example.com/">http://example.com/</ext-link>
-        </p>
-      </list-item>
-      <list-item>
-        <p>
-          It should.
-        </p>
-      </list-item>
-    </list>
-    <p>
-      An e-mail address: nobody [at] nowhere.net
-    </p>
-    <disp-quote>
-      <p>
-        Blockquoted:
-        <ext-link ext-link-type="uri" xlink:href="http://example.com/">http://example.com/</ext-link>
-      </p>
-    </disp-quote>
-    <p>
-      Auto-links should not occur here:
-      <monospace>&lt;http://example.com/&gt;</monospace>
-    </p>
-    <preformat>or here: &lt;http://example.com/&gt;</preformat>
-  </sec>
-</sec>
-<sec id="images">
-  <title>Images</title>
-  <p>
-    From &quot;Voyage dans la Lune&quot; by Georges Melies (1902):
-  </p>
-  <p>
-    <inline-graphic mimetype="image" mime-subtype="jpeg" xlink:href="lalune.jpg" xlink:title="Voyage dans la Lune" />
-  </p>
-  <p>
-    Here is a movie
-    <inline-graphic mimetype="image" mime-subtype="jpeg" xlink:href="movie.jpg" />
-    icon.
-  </p>
-</sec>
-<sec id="footnotes">
-  <title>Footnotes</title>
-  <p>
-    Here is a footnote reference<xref alt="(1)" rid="note_1">(1)</xref>,
-    and
-    another<xref alt="(longnote)" rid="note_longnote">(longnote)</xref>.
-    This should <italic>not</italic> be a footnote reference, because it
-    contains a space^(my note).
-  </p>
-  <p>
-    <xref alt="(1)" rid="ref_1">(1)</xref> Here is the footnote. It can
-    go anywhere in the document, not just at the end.
-  </p>
-  <p>
-    <xref alt="(longnote)" rid="ref_longnote">(longnote)</xref> Here's
-    the other note. This one contains multiple blocks.
-  </p>
-  <p>
-    Caret characters are used to indicate that the blocks all belong to
-    a single footnote (as with block quotes).
-  </p>
-  <preformat>  { &lt;code&gt; }</preformat>
-  <p>
-    If you want, you can use a caret at the beginning of every line, as
-    with blockquotes, but all that you need is a caret at the beginning
-    of the first line of the block and any preceding blank lines.
-  </p>
-  <p>
-    text <italic>Leading space</italic>
-  </p>
-  <p>
-    <italic>Trailing space</italic> text
-  </p>
-  <p>
-    text <italic>Leading spaces</italic>
-  </p>
-  <p>
-    <italic>Trailing spaces</italic> text
-  </p>
-</sec>
-<sec id="tables">
-  <title>Tables</title>
-  <sec id="tables-with-headers">
-    <title>Tables with Headers</title>
-    <table>
-      <col align="left" />
-      <col align="left" />
-      <col align="left" />
-      <thead>
-        <tr>
-          <th>
-            <p>
-              X
-            </p>
-          </th>
-          <th>
-            <p>
-              Y
-            </p>
-          </th>
-          <th>
-            <p>
-              Z
-            </p>
-          </th>
-        </tr>
-      </thead>
-      <tbody>
-        <tr>
-          <td>
-            <p>
-              1
-            </p>
-          </td>
-          <td>
-            <p>
-              2
-            </p>
-          </td>
-          <td>
-            <p>
-              3
-            </p>
-          </td>
-        </tr>
-        <tr>
-          <td>
-            <p>
-              4
-            </p>
-          </td>
-          <td>
-            <p>
-              5
-            </p>
-          </td>
-          <td>
-            <p>
-              6
-            </p>
-          </td>
-        </tr>
-      </tbody>
-    </table>
-    <table>
-      <col align="left" />
-      <col align="left" />
-      <col align="left" />
-      <thead>
-        <tr>
-          <th>
-            <p>
-              X
-            </p>
-          </th>
-          <th>
-            <p>
-              Y
-            </p>
-          </th>
-          <th>
-            <p>
-              Z
-            </p>
-          </th>
-        </tr>
-      </thead>
-      <tbody>
-        <tr>
-          <td>
-            <p>
-              1
-            </p>
-          </td>
-          <td>
-            <p>
-              2
-            </p>
-          </td>
-          <td>
-            <p>
-              3
-            </p>
-          </td>
-        </tr>
-        <tr>
-          <td>
-            <p>
-              4
-            </p>
-          </td>
-          <td>
-            <p>
-              5
-            </p>
-          </td>
-          <td>
-            <p>
-              6
-            </p>
-          </td>
-        </tr>
-      </tbody>
-    </table>
-    <table>
-      <col align="left" />
-      <col align="left" />
-      <col align="left" />
-      <thead>
-        <tr>
-          <th>
-            <p>
-              X
-            </p>
-          </th>
-          <th>
-            <p>
-              Y
-            </p>
-          </th>
-          <th>
-            <p>
-              Z
-            </p>
-          </th>
-        </tr>
-      </thead>
-      <tbody>
-        <tr>
-          <td>
-            <p>
-              1
-            </p>
-          </td>
-          <td>
-            <p>
-              2
-            </p>
-          </td>
-          <td>
-            <p>
-              3
-            </p>
-          </td>
-        </tr>
-        <tr>
-          <td>
-            <p>
-              4
-            </p>
-          </td>
-          <td>
-            <p>
-              5
-            </p>
-          </td>
-          <td>
-            <p>
-              6
-            </p>
-          </td>
-        </tr>
-      </tbody>
-    </table>
-    <table>
-      <col align="left" />
-      <col align="left" />
-      <col align="left" />
-      <thead>
-        <tr>
-          <th>
-            <p>
-              X
-            </p>
-          </th>
-          <th>
-            <p>
-              Y
-            </p>
-          </th>
-          <th>
-            <p>
-              Z
-            </p>
-          </th>
-        </tr>
-      </thead>
-      <tbody>
-        <tr>
-          <td>
-            <p>
-              1
-            </p>
-          </td>
-          <td>
-            <p>
-              2
-            </p>
-          </td>
-          <td>
-            <p>
-              3
-            </p>
-          </td>
-        </tr>
-        <tr>
-          <td>
-            <p>
-              4
-            </p>
-          </td>
-          <td>
-            <p>
-              5
-            </p>
-          </td>
-          <td>
-            <p>
-              6
-            </p>
-          </td>
-        </tr>
-      </tbody>
-    </table>
-    <table>
-      <col align="left" />
-      <col align="left" />
-      <col align="left" />
-      <thead>
-        <tr>
-          <th>
-            <p>
-              X
-            </p>
-          </th>
-          <th>
-            <p>
-              Y
-            </p>
-          </th>
-          <th>
-            <p>
-              Z
-            </p>
-          </th>
-        </tr>
-      </thead>
-      <tbody>
-        <tr>
-          <td>
-            <p>
-              1
-            </p>
-          </td>
-          <td>
-            <p>
-              2
-            </p>
-          </td>
-          <td>
-            <p>
-              3
-            </p>
-          </td>
-        </tr>
-        <tr>
-          <td>
-            <p>
-              4
-            </p>
-          </td>
-          <td>
-            <p>
-              5
-            </p>
-          </td>
-          <td>
-            <p>
-              6
-            </p>
-          </td>
-        </tr>
-      </tbody>
-    </table>
-    <table>
-      <col align="left" />
-      <col align="left" />
-      <col align="left" />
-      <thead>
-        <tr>
-          <th>
-            <p>
-              X
-            </p>
-          </th>
-          <th>
-            <p>
-              Y
-            </p>
-          </th>
-          <th>
-            <p>
-              Z
-            </p>
-          </th>
-        </tr>
-      </thead>
-      <tbody>
-        <tr>
-          <td>
-            <p>
-              1
-            </p>
-          </td>
-          <td>
-            <p>
-              2
-            </p>
-          </td>
-          <td>
-            <p>
-              3
-            </p>
-          </td>
-        </tr>
-        <tr>
-          <td>
-            <p>
-              4
-            </p>
-          </td>
-          <td>
-            <p>
-              5
-            </p>
-          </td>
-          <td>
-            <p>
-              6
-            </p>
-          </td>
-        </tr>
-      </tbody>
-    </table>
-    <table>
-      <col align="left" />
-      <col align="left" />
-      <col align="left" />
-      <thead>
-        <tr>
-          <th>
-            <p>
-              X
-            </p>
-          </th>
-          <th>
-            <p>
-              Y
-            </p>
-          </th>
-          <th>
-            <p>
-              Z
-            </p>
-          </th>
-        </tr>
-      </thead>
-      <tbody>
-        <tr>
-          <td>
-            <p>
-              1
-            </p>
-          </td>
-          <td>
-            <p>
-              2
-            </p>
-          </td>
-          <td>
-            <p>
-              3
-            </p>
-          </td>
-        </tr>
-        <tr>
-          <td>
-            <p>
-              4
-            </p>
-          </td>
-          <td>
-            <p>
-              5
-            </p>
-          </td>
-          <td>
-            <p>
-              6
-            </p>
-          </td>
-        </tr>
-      </tbody>
-    </table>
-    <table>
-      <col align="left" />
-      <col align="left" />
-      <col align="left" />
-      <thead>
-        <tr>
-          <th>
-            <p>
-              X
-            </p>
-          </th>
-          <th>
-            <p>
-              Y
-            </p>
-          </th>
-          <th>
-            <p>
-              Z
-            </p>
-          </th>
-        </tr>
-      </thead>
-      <tbody>
-        <tr>
-          <td>
-            <p>
-              1
-            </p>
-          </td>
-          <td>
-            <p>
-              2
-            </p>
-          </td>
-          <td>
-            <p>
-              3
-            </p>
-          </td>
-        </tr>
-        <tr>
-          <td>
-            <p>
-              4
-            </p>
-          </td>
-          <td>
-            <p>
-              5
-            </p>
-          </td>
-          <td>
-            <p>
-              6
-            </p>
-          </td>
-        </tr>
-      </tbody>
-    </table>
-    <table>
-      <col width="33*" align="left" />
-      <col width="33*" align="left" />
-      <col width="33*" align="left" />
-      <thead>
-        <tr>
-          <th>
-            <p>
-              X
-            </p>
-          </th>
-          <th>
-            <p>
-              Y
-            </p>
-          </th>
-          <th>
-            <p>
-              Z
-            </p>
-          </th>
-        </tr>
-      </thead>
-      <tbody>
-        <tr>
-          <td>
-            <p>
-              1
-            </p>
-          </td>
-          <td>
-            <p>
-              2
-            </p>
-          </td>
-          <td>
-            <p>
-              3
-            </p>
-          </td>
-        </tr>
-        <tr>
-          <td>
-            <p>
-              4
-            </p>
-          </td>
-          <td>
-            <p>
-              5
-            </p>
-          </td>
-          <td>
-            <p>
-              6
-            </p>
-          </td>
-        </tr>
-      </tbody>
-    </table>
-  </sec>
-  <sec id="tables-without-headers">
-    <title>Tables without Headers</title>
-    <table>
-      <col align="left" />
-      <col align="left" />
-      <col align="left" />
-      <tbody>
-        <tr>
-          <td>
-            <p>
-              1
-            </p>
-          </td>
-          <td>
-            <p>
-              2
-            </p>
-          </td>
-          <td>
-            <p>
-              3
-            </p>
-          </td>
-        </tr>
-        <tr>
-          <td>
-            <p>
-              4
-            </p>
-          </td>
-          <td>
-            <p>
-              5
-            </p>
-          </td>
-          <td>
-            <p>
-              6
-            </p>
-          </td>
-        </tr>
-      </tbody>
-    </table>
-    <table>
-      <col align="left" />
-      <col align="left" />
-      <col align="left" />
-      <tbody>
-        <tr>
-          <td>
-            <p>
-              1
-            </p>
-          </td>
-          <td>
-            <p>
-              2
-            </p>
-          </td>
-          <td>
-            <p>
-              3
-            </p>
-          </td>
-        </tr>
-        <tr>
-          <td>
-            <p>
-              4
-            </p>
-          </td>
-          <td>
-            <p>
-              5
-            </p>
-          </td>
-          <td>
-            <p>
-              6
-            </p>
-          </td>
-        </tr>
-      </tbody>
-    </table>
-    <table>
-      <col align="left" />
-      <col align="left" />
-      <col align="left" />
-      <tbody>
-        <tr>
-          <td>
-            <p>
-              1
-            </p>
-          </td>
-          <td>
-            <p>
-              2
-            </p>
-          </td>
-          <td>
-            <p>
-              3
-            </p>
-          </td>
-        </tr>
-        <tr>
-          <td>
-            <p>
-              4
-            </p>
-          </td>
-          <td>
-            <p>
-              5
-            </p>
-          </td>
-          <td>
-            <p>
-              6
-            </p>
-          </td>
-        </tr>
-      </tbody>
-    </table>
-    <table>
-      <col align="left" />
-      <col align="left" />
-      <col align="left" />
-      <tbody>
-        <tr>
-          <td>
-            <p>
-              1
-            </p>
-          </td>
-          <td>
-            <p>
-              2
-            </p>
-          </td>
-          <td>
-            <p>
-              3
-            </p>
-          </td>
-        </tr>
-        <tr>
-          <td>
-            <p>
-              4
-            </p>
-          </td>
-          <td>
-            <p>
-              5
-            </p>
-          </td>
-          <td>
-            <p>
-              6
-            </p>
-          </td>
-        </tr>
-      </tbody>
-    </table>
-  </sec>
-  <sec id="empty-tables">
-    <title>Empty Tables</title>
-    <p>
-      This section should be empty.
-    </p>
-  </sec>
-</sec>
-</body>
-<back>
+<!DOCTYPE article PUBLIC "-//NLM//DTD JATS (Z39.96) Journal Archiving and Interchange DTD v1.2 20190208//EN"
+                  "JATS-archivearticle1.dtd">
+<article xmlns:mml="http://www.w3.org/1998/Math/MathML" xmlns:xlink="http://www.w3.org/1999/xlink" dtd-version="1.2" article-type="other">
+<processing-meta base-tagset="archiving" mathml-version="3.0" table-model="xhtml" tagset-family="jats">
+    <restricted-by>pmc</restricted-by>
+</processing-meta>
+<front>
+<journal-meta>
+<journal-title-group>
+</journal-title-group>
+<publisher>
+<publisher-name></publisher-name>
+</publisher>
+</journal-meta>
+<article-meta>
+<title-group>
+<article-title>Pandoc Test Suite</article-title>
+</title-group>
+<contrib-group>
+  <contrib contrib-type="author">
+    <name>
+      <surname>MacFarlane</surname>
+      <given-names>John</given-names>
+    </name>
+  </contrib>
+  <contrib contrib-type="author">
+    <name>
+      <surname>Anonymous</surname>
+    </name>
+  </contrib>
+</contrib-group>
+<permissions>
+        <copyright-statement>© 2023, MacFarlane et al</copyright-statement>
+        <copyright-year>2023</copyright-year>
+        <copyright-holder>MacFarlane et al</copyright-holder>
+        <license license-type="open-access">
+          <ali:license_ref xmlns:ali="http://www.niso.org/schemas/ali/1.0/">https://creativecommons.org/licenses/by/4.0/</ali:license_ref>
+          <license-p>This document is distributed under a Creative Commons Attribution 4.0 International license.</license-p>
+        </license>
+      </permissions>
+</article-meta>
+</front>
+<body>
+<p>This is a set of tests for pandoc. Most of them are adapted from John Gruber's markdown test suite.</p>
+<sec id="headers">
+  <title>Headers</title>
+  <sec id="level-2-with-an-embedded-link">
+    <title>Level 2 with an
+    <ext-link ext-link-type="uri" xlink:href="/url">embedded
+    link</ext-link></title>
+    <sec id="level-3-with-emphasis">
+      <title>Level 3 with <italic>emphasis</italic></title>
+      <sec id="level-4">
+        <title>Level 4</title>
+        <sec id="level-5">
+          <title>Level 5</title>
+        </sec>
+      </sec>
+    </sec>
+  </sec>
+</sec>
+<sec id="level-1">
+  <title>Level 1</title>
+  <sec id="level-2-with-emphasis">
+    <title>Level 2 with <italic>emphasis</italic></title>
+    <sec id="level-3">
+      <title>Level 3</title>
+      <p>with no blank line</p>
+    </sec>
+  </sec>
+  <sec id="level-2">
+    <title>Level 2</title>
+    <p>with no blank line</p>
+  </sec>
+</sec>
+<sec id="paragraphs">
+  <title>Paragraphs</title>
+  <p>Here's a regular paragraph.</p>
+  <p>In Markdown 1.0.0 and earlier. Version 8. This line turns into a list item. Because a hard-wrapped line in the middle of a paragraph looked like a list item.</p>
+  <p>Here's one with a bullet. * criminey.</p>
+  <p>There should be a <bold>hard line break<break /></bold>here.</p>
+</sec>
+<sec id="statements">
+  <title> Statements </title>
+  <statement>
+    <label> A label for a statement</label>
+    <title> CAP TITLE </title>
+    <p> Some text to make this regular </p>
+  </statement>
+</sec>
+<sec id="block-quotes">
+  <title>Block Quotes</title>
+  <p>E-mail style:</p>
+  <disp-quote>
+    <p>This is a block quote. It is pretty short.</p>
+  </disp-quote>
+  <disp-quote>
+    <p>Code in a block quote:</p>
+    <preformat>sub status {
+    print &quot;working&quot;;
+}</preformat>
+    <p>A list:</p>
+    <list list-type="order">
+      <list-item>
+        <p>item one</p>
+      </list-item>
+      <list-item>
+        <p>item two</p>
+      </list-item>
+    </list>
+    <p>Nested block quotes:</p>
+    <disp-quote>
+      <p>nested</p>
+    </disp-quote>
+    <disp-quote>
+      <p>nested</p>
+    </disp-quote>
+  </disp-quote>
+  <p>This should not be a block quote: 2 &gt; 1.</p>
+  <p>Box-style:</p>
+  <disp-quote>
+    <p>Example:</p>
+    <preformat>sub status {
+    print &quot;working&quot;;
+}</preformat>
+  </disp-quote>
+  <disp-quote>
+    <list list-type="order">
+      <list-item>
+        <p>do laundry</p>
+      </list-item>
+      <list-item>
+        <p>take out the trash</p>
+      </list-item>
+    </list>
+  </disp-quote>
+  <p>Here's a nested one:</p>
+  <disp-quote>
+    <p>Joe said:</p>
+    <disp-quote>
+      <p>Don't quote me.</p>
+    </disp-quote>
+  </disp-quote>
+  <p>And a following paragraph.</p>
+  <p>
+     Here is a block quote inside a paragraph. Start of a paragraph is here, and the quote is below:
+      <disp-quote>
+        <p>My block quote</p>
+      </disp-quote>
+     End of a paragraph
+  </p>
+</sec>
+<sec id="formulae">
+  <title>Formulae</title>
+  <sec id="inline-formulae">
+    <title>Inline formulae with <italic>inline-formula</italic></title>
+    <p><bold>Inside a paragraph</bold>, should be natively coded inside the paragraph, and show inline:</p>
+    <p>Einstein showed that <inline-formula><alternatives>
+      <tex-math><![CDATA[e=mc^2]]></tex-math>
+      <mml:math display="inline" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mrow><mml:mi>e</mml:mi><mml:mo>=</mml:mo><mml:mi>m</mml:mi><mml:msup><mml:mi>c</mml:mi><mml:mn>2</mml:mn></mml:msup></mml:mrow></mml:math></alternatives></inline-formula>.
+      This formula is important because…</p>
+  </sec>
+  <sec id="disp-formulae">
+    <title>Block formulae with <italic>disp-formula</italic></title>
+    <p><bold>Inside a paragraph</bold>, should be natively coded inside the paragraph, but show as block:</p>
+    <p>Einstein showed that <disp-formula><alternatives>
+      <tex-math><![CDATA[e=mc^2]]></tex-math>
+      <mml:math display="block" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mrow><mml:mi>e</mml:mi><mml:mo>=</mml:mo><mml:mi>m</mml:mi><mml:msup><mml:mi>c</mml:mi><mml:mn>2</mml:mn></mml:msup></mml:mrow></mml:math></alternatives></disp-formula>.
+      This formula is important because…</p>
+    <p><bold>Outside a paragraph</bold>, should show as block:</p>
+    <p>Einstein showed that </p>
+    <disp-formula><alternatives>
+      <tex-math><![CDATA[e=mc^2]]></tex-math>
+      <mml:math display="block" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mrow><mml:mi>e</mml:mi><mml:mo>=</mml:mo><mml:mi>m</mml:mi><mml:msup><mml:mi>c</mml:mi><mml:mn>2</mml:mn></mml:msup></mml:mrow></mml:math></alternatives></disp-formula>
+    <p>This formula is important because…</p>
+  </sec>
+  <sec id="no-formula-wrapper">
+    <title>Without a formula wrapper</title>
+    <p><bold>Inside a paragraph</bold>, should show inline:</p>
+    <p>Einstein showed that <alternatives>
+      <tex-math><![CDATA[e=mc^2]]></tex-math>
+      <mml:math display="inline" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mrow><mml:mi>e</mml:mi><mml:mo>=</mml:mo><mml:mi>m</mml:mi><mml:msup><mml:mi>c</mml:mi><mml:mn>2</mml:mn></mml:msup></mml:mrow></mml:math></alternatives>.
+      This formula is important because…</p>
+    <p><bold>Outside a paragraph</bold>, should show as block:</p>
+    <p>Einstein showed that </p>
+    <alternatives>
+      <tex-math><![CDATA[e=mc^2]]></tex-math>
+      <mml:math display="block" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mrow><mml:mi>e</mml:mi><mml:mo>=</mml:mo><mml:mi>m</mml:mi><mml:msup><mml:mi>c</mml:mi><mml:mn>2</mml:mn></mml:msup></mml:mrow></mml:math></alternatives>
+    <p>This formula is important because…</p>
+  </sec>
+  <sec id="misc-formulae">
+    <title>Formulae with miscelaneus elements</title>
+    <p>Regardless of whether or not they are inside a paragraph, should be wrapped in a div, and displayed in a block:</p>
+    <p><bold>Inside a paragraph:</bold></p>
+    <p>Einstein definitely showed that 
+      <disp-formula>
+        <abstract>
+          <p>Abstract text</p>
+        </abstract>
+        <graphic id="graphic001"
+        xlink:href="https://lh3.googleusercontent.com/dB7iirJ3ncQaVMBGE2YX-WCeoAVIChb6NAzoFcKCFChMsrixJvD7ZRbvcaC-ceXEzXYaoH4K5vaoRDsUyBHFkpIDPnsn3bnzovbvi0a2Gg=s660"
+        xlink:title="This is the title of the graphic"
+        xlink:role="This is the role of the graphic">
+          <alt-text>Alternative text of the graphic</alt-text>
+          <caption>
+            <title>This is the title of the caption</title>
+            <p>Google doodle from 14 March 2003</p></caption>
+        </graphic>
+        <alternatives>
+          <tex-math><![CDATA[e=mc^2]]></tex-math>
+          <mml:math display="block" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mrow><mml:mi>e</mml:mi><mml:mo>=</mml:mo><mml:mi>m</mml:mi><mml:msup><mml:mi>c</mml:mi><mml:mn>2</mml:mn></mml:msup></mml:mrow></mml:math>
+          <graphic id="graphic001"
+          xlink:href="https://lh3.googleusercontent.com/dB7iirJ3ncQaVMBGE2YX-WCeoAVIChb6NAzoFcKCFChMsrixJvD7ZRbvcaC-ceXEzXYaoH4K5vaoRDsUyBHFkpIDPnsn3bnzovbvi0a2Gg=s660"
+          xlink:title="Title 2">
+            <alt-text>Alternative text 2</alt-text>
+            <caption><p>Google doodle from 14 March 2003</p></caption>
+          </graphic>
+        </alternatives>
+      </disp-formula>.
+      This formula is important because…</p>
+    <p><bold>Outside of a paragraph:</bold></p>
+    <p>Paragraph before: Einstein showed that </p>
+    <disp-formula>
+      <abstract>
+        <p>Abstract text</p>
+      </abstract>
+      <graphic id="graphic003"
+      xlink:href="https://lh3.googleusercontent.com/dB7iirJ3ncQaVMBGE2YX-WCeoAVIChb6NAzoFcKCFChMsrixJvD7ZRbvcaC-ceXEzXYaoH4K5vaoRDsUyBHFkpIDPnsn3bnzovbvi0a2Gg=s660"
+      xlink:href="Title 3">
+        <alt-text>Alternative text 1</alt-text>
+        <caption><p>Google doodle from 14 March 2003</p></caption>
+      </graphic>
+      <alternatives>
+        <tex-math><![CDATA[e=mc^2]]></tex-math>
+        <mml:math display="block" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mrow><mml:mi>e</mml:mi><mml:mo>=</mml:mo><mml:mi>m</mml:mi><mml:msup><mml:mi>c</mml:mi><mml:mn>2</mml:mn></mml:msup></mml:mrow></mml:math>
+        <graphic id="graphic004"
+        xlink:href="https://lh3.googleusercontent.com/dB7iirJ3ncQaVMBGE2YX-WCeoAVIChb6NAzoFcKCFChMsrixJvD7ZRbvcaC-ceXEzXYaoH4K5vaoRDsUyBHFkpIDPnsn3bnzovbvi0a2Gg=s660"
+        xlink:href="Title 4">
+          <alt-text>Alternative text 2</alt-text>
+          <caption><p>Google doodle from 14 March 2003</p></caption>
+        </graphic>
+      </alternatives>
+    </disp-formula>
+    <p>This formula is important because…</p>
+  </sec>
+</sec>
+<sec id="figures">
+  <fig id="fig-1">
+    <caption>
+      <p>bar</p>
+    </caption>
+    <alt-text>alternative-decription</alt-text>
+    <graphic xlink:href="foo.png" xlink:alt-text="baz" />
+  </fig>
+</sec>
+<sec id="code-blocks">
+  <title>Code Blocks</title>
+  <p>Code:</p>
+  <preformat>---- (should be four hyphens)
+
+sub status {
+    print &quot;working&quot;;
+}
+
+this code block is indented by one tab</preformat>
+  <p>And:</p>
+  <preformat>    this code block is indented by two tabs
+
+These should not be escaped:  \$ \\ \&gt; \[ \{</preformat>
+</sec>
+<sec id="lists">
+  <title>Lists</title>
+  <sec id="unordered">
+    <title>Unordered</title>
+    <p>Asterisks tight:</p>
+    <list list-type="bullet">
+      <list-item>
+        <p>asterisk 1</p>
+      </list-item>
+      <list-item>
+        <p>asterisk 2</p>
+      </list-item>
+      <list-item>
+        <p>asterisk 3</p>
+      </list-item>
+    </list>
+    <p>Asterisks loose:</p>
+    <list list-type="bullet">
+      <list-item>
+        <p>asterisk 1</p>
+      </list-item>
+      <list-item>
+        <p>asterisk 2</p>
+      </list-item>
+      <list-item>
+        <p>asterisk 3</p>
+      </list-item>
+    </list>
+    <p>Pluses tight:</p>
+    <list list-type="bullet">
+      <list-item>
+        <p>Plus 1</p>
+      </list-item>
+      <list-item>
+        <p>Plus 2</p>
+      </list-item>
+      <list-item>
+        <p>Plus 3</p>
+      </list-item>
+    </list>
+    <p>Pluses loose:</p>
+    <list list-type="bullet">
+      <list-item>
+        <p>Plus 1</p>
+      </list-item>
+      <list-item>
+        <p>Plus 2</p>
+      </list-item>
+      <list-item>
+        <p>Plus 3</p>
+      </list-item>
+    </list>
+    <p>Minuses tight:</p>
+    <list list-type="bullet">
+      <list-item>
+        <p>Minus 1</p>
+      </list-item>
+      <list-item>
+        <p>Minus 2</p>
+      </list-item>
+      <list-item>
+        <p>Minus 3</p>
+      </list-item>
+    </list>
+    <p>Minuses loose:</p>
+    <list list-type="bullet">
+      <list-item>
+        <p>Minus 1</p>
+      </list-item>
+      <list-item>
+        <p>Minus 2</p>
+      </list-item>
+      <list-item>
+        <p>Minus 3</p>
+      </list-item>
+    </list>
+  </sec>
+  <sec id="ordered">
+    <title>Ordered</title>
+    <p>Tight:</p>
+    <list list-type="order">
+      <list-item>
+        <p>First</p>
+      </list-item>
+      <list-item>
+        <p>Second</p>
+      </list-item>
+      <list-item>
+        <p>Third</p>
+      </list-item>
+    </list>
+    <p>and:</p>
+    <list list-type="order">
+      <list-item>
+        <p>One</p>
+      </list-item>
+      <list-item>
+        <p>Two</p>
+      </list-item>
+      <list-item>
+        <p>Three</p>
+      </list-item>
+    </list>
+    <p>Loose using tabs:</p>
+    <list list-type="order">
+      <list-item>
+        <p>First</p>
+      </list-item>
+      <list-item>
+        <p>Second</p>
+      </list-item>
+      <list-item>
+        <p>Third</p>
+      </list-item>
+    </list>
+    <p>and using spaces:</p>
+    <list list-type="order">
+      <list-item>
+        <p>One</p>
+      </list-item>
+      <list-item>
+        <p>Two</p>
+      </list-item>
+      <list-item>
+        <p>Three</p>
+      </list-item>
+    </list>
+    <p>Multiple paragraphs:</p>
+    <list list-type="order">
+      <list-item>
+        <p>Item 1, graf one.</p>
+        <p>Item 1. graf two. The quick brown fox jumped over the lazy
+          dog's back.</p>
+      </list-item>
+      <list-item>
+        <p>Item 2.</p>
+      </list-item>
+      <list-item>
+        <p>Item 3.</p>
+      </list-item>
+    </list>
+    <p>List styles:</p>
+    <list list-type="order">
+      <list-item><p>one</p></list-item><x>,</x>
+      <list-item><p>two</p></list-item><x>,</x>
+      <list-item><p>three</p></list-item>
+    </list>
+    <list list-type="roman-lower">
+      <list-item><p>one</p></list-item><x>,</x>
+      <list-item><p>two</p></list-item><x>,</x>
+      <list-item><p>three</p></list-item>
+    </list>
+  </sec>
+  <sec id="nested">
+    <title>Nested</title>
+    <list list-type="bullet">
+      <list-item>
+        <p>Tab</p>
+        <list list-type="bullet">
+          <list-item>
+            <p>Tab</p>
+            <list list-type="bullet">
+              <list-item>
+                <p>Tab</p>
+              </list-item>
+            </list>
+          </list-item>
+        </list>
+      </list-item>
+    </list>
+    <p>Here's another:</p>
+    <list list-type="order">
+      <list-item>
+        <p>First</p>
+      </list-item>
+      <list-item>
+        <p>Second:</p>
+        <list list-type="bullet">
+          <list-item>
+            <p>Fee</p>
+          </list-item>
+          <list-item>
+            <p>Fie</p>
+          </list-item>
+          <list-item>
+            <p>Foe</p>
+          </list-item>
+        </list>
+      </list-item>
+      <list-item>
+        <p>Third</p>
+      </list-item>
+    </list>
+    <p>Same thing but with paragraphs:</p>
+    <list list-type="order">
+      <list-item>
+        <p>First</p>
+      </list-item>
+      <list-item>
+        <p>Second:</p>
+        <list list-type="bullet">
+          <list-item>
+            <p>Fee</p>
+          </list-item>
+          <list-item>
+            <p>Fie</p>
+          </list-item>
+          <list-item>
+            <p>Foe</p>
+          </list-item>
+        </list>
+      </list-item>
+      <list-item>
+        <p>Third</p>
+      </list-item>
+    </list>
+  </sec>
+  <sec id="tabs-and-spaces">
+    <title>Tabs and spaces</title>
+    <list list-type="bullet">
+      <list-item>
+        <p>this is a list item indented with tabs</p>
+      </list-item>
+      <list-item>
+        <p>this is a list item indented with spaces</p>
+        <list list-type="bullet">
+          <list-item>
+            <p>this is an example list item indented with tabs</p>
+          </list-item>
+          <list-item>
+            <p>this is an example list item indented with spaces</p>
+          </list-item>
+        </list>
+      </list-item>
+    </list>
+  </sec>
+  <sec id="fancy-list-markers">
+    <title>Fancy list markers</title>
+    <p>Autonumbering:</p>
+    <list list-type="order">
+      <list-item>
+        <p>Autonumber.</p>
+      </list-item>
+      <list-item>
+        <p>More.</p>
+        <list list-type="order">
+          <list-item>
+            <p>Nested.</p>
+          </list-item>
+        </list>
+      </list-item>
+    </list>
+  </sec>
+  <sec id="definition">
+    <title>Definition</title>
+    <def-list>
+      <def-item>
+        <term>
+          Violin
+        </term>
+        <def>
+          <p>Stringed musical instrument.</p>
+          <p>Torture device.</p>
+        </def>
+      </def-item>
+      <def-item>
+        <term>
+          Cello<bold><break /></bold>Violoncello
+        </term>
+        <def>
+          <p>Low-voiced stringed instrument.</p>
+        </def>
+      </def-item>
+    </def-list>
+  </sec>
+  <sec id="list-inside-paragraph">
+    <title>List inside a paragraph</title>
+    <p>
+      Start of a paragraph.
+      <list list-type="bullet">
+        <list-item>
+          <label>&#8226;</label>
+          <p>Red</p>
+        </list-item>
+        <list-item>
+          <label>&#8226;</label>
+          <p>Blue</p>
+        </list-item>
+      </list>
+      End of paragraph.
+    </p>
+  </sec>
+</sec>
+<sec id="inline-markup">
+  <title>Inline Markup</title>
+  <p>This is <italic>emphasized</italic>, and so <italic>is
+    this</italic>.</p>
+  <p>This is <bold>strong</bold>, and so
+    <bold>is this</bold>.</p>
+  <p>Empty <bold></bold> and <italic></italic>.</p>
+  <p>An
+    <italic><ext-link ext-link-type="uri" xlink:href="/url">emphasized
+    link</ext-link></italic>.</p>
+  <p><bold><italic>This is strong and em.</italic></bold></p>
+  <p>So is <bold><italic>this</italic></bold> word.</p>
+  <p><bold><italic>This is strong and em.</italic></bold></p>
+  <p>So is <bold><italic>this</italic></bold> word.</p>
+  <p>This is code: <monospace>&gt;</monospace>, <monospace>$</monospace>,
+    <monospace>\</monospace>, <monospace>\$</monospace>,
+    <monospace>&lt;html&gt;</monospace>.</p>
+  <p>This is <sc>small caps</sc>.</p>
+  <p>These are all underlined: foo and bar.</p>
+  <p>These are all strikethrough: <strike>foo</strike>,
+    <strike>bar</strike>, and <strike>baz</strike>.</p>
+</sec>
+<sec id="smart-quotes-ellipses-dashes">
+  <title>Smart quotes, ellipses, dashes</title>
+  <p>&quot;Hello,&quot; said the spider. &quot;'Shelob' is my name.&quot;</p>
+  <p>'A', 'B', and 'C' are letters.</p>
+  <p>'Oak,' 'elm,' and 'beech' are names of trees. So is 'pine.'</p>
+  <p>'He said, &quot;I want to go.&quot;' Were you alive in the 70's?</p>
+  <p>Here is some quoted '<monospace>code</monospace>' and a
+    &quot;<ext-link ext-link-type="uri" xlink:href="http://example.com/?foo=1&amp;bar=2">quoted
+    link</ext-link>&quot;.</p>
+  <p>Some dashes: one---two --- three--four -- five.</p>
+  <p>Dashes between numbers: 5-7, 255-66, 1987-1999.</p>
+  <p>Ellipses...and. . .and . . . .</p>
+</sec>
+<sec id="latex">
+  <title>LaTeX</title>
+  <list list-type="bullet">
+    <list-item>
+      <p>\cite[22-23]{smith.1899}</p>
+    </list-item>
+    <list-item>
+      <p>\doublespacing</p>
+    </list-item>
+    <list-item>
+      <p>$2+2=4$</p>
+    </list-item>
+    <list-item>
+      <p>$x \in y$</p>
+    </list-item>
+    <list-item>
+      <p>$\alpha \wedge \omega$</p>
+    </list-item>
+    <list-item>
+      <p>$223$</p>
+    </list-item>
+    <list-item>
+      <p>$p$-Tree</p>
+    </list-item>
+    <list-item>
+      <p>$\frac{d}{dx}f(x)=\lim_{h\to 0}\frac{f(x+h)-f(x)}{h}$</p>
+    </list-item>
+    <list-item>
+      <p>Here's one that has a line break in it: $\alpha + \omega \times
+        x^2$.</p>
+    </list-item>
+  </list>
+  <p>These shouldn't be math:</p>
+  <list list-type="bullet">
+    <list-item>
+      <p>To get the famous equation, write
+        <monospace>$e = mc^2$</monospace>.</p>
+    </list-item>
+    <list-item>
+      <p>$22,000 is a <italic>lot</italic> of money. So is $34,000. (It
+        worked if &quot;lot&quot; is emphasized.)</p>
+    </list-item>
+    <list-item>
+      <p>Escaped <monospace>$</monospace>: $73 <italic>this should be
+        emphasized</italic> 23$.</p>
+    </list-item>
+  </list>
+  <p>Here's a LaTeX table:</p>
+  <p>\begin{tabular}{|l|l|}\hline Animal &amp; Number \\ \hline Dog &amp;
+    2 \\ Cat &amp; 1 \\ \hline \end{tabular}</p>
+</sec>
+<sec id="special-characters">
+  <title>Special Characters</title>
+  <p>Here is some unicode:</p>
+  <list list-type="bullet">
+    <list-item>
+      <p>I hat: Î</p>
+    </list-item>
+    <list-item>
+      <p>o umlaut: ö</p>
+    </list-item>
+    <list-item>
+      <p>section: §</p>
+    </list-item>
+    <list-item>
+      <p>set membership: elem</p>
+    </list-item>
+    <list-item>
+      <p>copyright: ©</p>
+    </list-item>
+  </list>
+  <p>AT&amp;T has an ampersand in their name.</p>
+  <p>AT&amp;T is another way to write it.</p>
+  <p>This &amp; that.</p>
+  <p>4 &lt; 5.</p>
+  <p>6 &gt; 5.</p>
+  <p>Backslash: \</p>
+  <p>Backtick: `</p>
+  <p>Asterisk: *</p>
+  <p>Underscore: _</p>
+  <p>Left brace: {</p>
+  <p>Right brace: }</p>
+  <p>Left bracket: [</p>
+  <p>Right bracket: ]</p>
+  <p>Left paren: (</p>
+  <p>Right paren: )</p>
+  <p>Greater-than: &gt;</p>
+  <p>Hash: #</p>
+  <p>Period: .</p>
+  <p>Bang: !</p>
+  <p>Plus: +</p>
+  <p>Minus: -</p>
+</sec>
+<sec id="links">
+  <title>Links</title>
+  <sec id="explicit">
+    <title>Explicit</title>
+    <p>Just a
+      <ext-link ext-link-type="uri" xlink:href="/url/">URL</ext-link>.</p>
+    <p><ext-link ext-link-type="uri" xlink:href="/url/" xlink:title="title">URL
+      and title</ext-link>.</p>
+    <p><ext-link ext-link-type="uri" xlink:href="/url/" xlink:title="title preceded by two spaces">URL
+      and title</ext-link>.</p>
+    <p><ext-link ext-link-type="uri" xlink:href="/url/" xlink:title="title preceded by a tab">URL
+      and title</ext-link>.</p>
+    <p><ext-link ext-link-type="uri" xlink:href="/url/" xlink:title="title with &quot;quotes&quot; in it">URL
+      and title</ext-link></p>
+    <p><ext-link ext-link-type="uri" xlink:href="/url/" xlink:title="title with single quotes">URL
+      and title</ext-link></p>
+    <p>Email link (nobody [at] nowhere.net)</p>
+    <p><ext-link ext-link-type="uri" xlink:href="">Empty</ext-link>.</p>
+  </sec>
+  <sec id="reference">
+    <title>Reference</title>
+    <p>Foo
+      <ext-link ext-link-type="uri" xlink:href="/url/">bar</ext-link>.</p>
+    <p>Foo
+      <ext-link ext-link-type="uri" xlink:href="/url/">bar</ext-link>.</p>
+    <p>Foo
+      <ext-link ext-link-type="uri" xlink:href="/url/">bar</ext-link>.</p>
+    <p>With <ext-link ext-link-type="uri" xlink:href="/url/">embedded
+      [brackets]</ext-link>.</p>
+    <p><ext-link ext-link-type="uri" xlink:href="/url/">b</ext-link> by
+      itself should be a link.</p>
+    <p>Indented
+      <ext-link ext-link-type="uri" xlink:href="/url">once</ext-link>.</p>
+    <p>Indented
+      <ext-link ext-link-type="uri" xlink:href="/url">twice</ext-link>.</p>
+    <p>Indented
+      <ext-link ext-link-type="uri" xlink:href="/url">thrice</ext-link>.</p>
+    <p>This should [not] be a link.</p>
+    <preformat>[not]: /url</preformat>
+    <p>Foo
+      <ext-link ext-link-type="uri" xlink:href="/url/" xlink:title="Title with &quot;quotes&quot; inside">bar</ext-link>.</p>
+    <p>Foo
+      <ext-link ext-link-type="uri" xlink:href="/url/" xlink:title="Title with &quot;quote&quot; inside">biz</ext-link>.</p>
+  </sec>
+  <sec id="with-ampersands">
+    <title>With ampersands</title>
+    <p>Here's a
+      <ext-link ext-link-type="uri" xlink:href="http://example.com/?foo=1&amp;bar=2">link
+      with an ampersand in the URL</ext-link>.</p>
+    <p>Here's a link with an amersand in the link text:
+      <ext-link ext-link-type="uri" xlink:href="http://att.com/" xlink:title="AT&amp;T">AT&amp;T</ext-link>.</p>
+    <p>Here's an
+      <ext-link ext-link-type="uri" xlink:href="/script?foo=1&amp;bar=2">inline
+      link</ext-link>.</p>
+    <p>Here's an
+      <ext-link ext-link-type="uri" xlink:href="/script?foo=1&amp;bar=2">inline
+      link in pointy braces</ext-link>.</p>
+  </sec>
+  <sec id="autolinks">
+    <title>Autolinks</title>
+    <p>With an ampersand:
+      <ext-link ext-link-type="uri" xlink:href="http://example.com/?foo=1&amp;bar=2">http://example.com/?foo=1&amp;bar=2</ext-link></p>
+    <list list-type="bullet">
+      <list-item>
+        <p>In a list?</p>
+      </list-item>
+      <list-item>
+        <p><ext-link ext-link-type="uri" xlink:href="http://example.com/">http://example.com/</ext-link></p>
+      </list-item>
+      <list-item>
+        <p>It should.</p>
+      </list-item>
+    </list>
+    <p>An e-mail address: nobody [at] nowhere.net</p>
+    <disp-quote>
+      <p>Blockquoted:
+        <ext-link ext-link-type="uri" xlink:href="http://example.com/">http://example.com/</ext-link></p>
+    </disp-quote>
+    <p>Auto-links should not occur here:
+      <monospace>&lt;http://example.com/&gt;</monospace></p>
+    <preformat>or here: &lt;http://example.com/&gt;</preformat>
+  </sec>
+</sec>
+<sec id="images">
+  <title>Images</title>
+  <p>From &quot;Voyage dans la Lune&quot; by Georges Melies (1902):</p>
+  <p><inline-graphic mimetype="image" mime-subtype="jpeg" xlink:href="lalune.jpg" xlink:title="Voyage dans la Lune" /></p>
+  <p>Here is a movie
+    <inline-graphic mimetype="image" mime-subtype="jpeg" xlink:href="movie.jpg" />
+    icon.</p>
+</sec>
+<sec id="footnotes">
+  <title>Footnotes</title>
+  <p>Here is a footnote reference<xref alt="(1)" rid="note_1">(1)</xref>,
+    and
+    another<xref alt="(longnote)" rid="note_longnote">(longnote)</xref>.
+    This should <italic>not</italic> be a footnote reference, because it
+    contains a space^(my note).</p>
+  <p><xref alt="(1)" rid="ref_1">(1)</xref> Here is the footnote. It can
+    go anywhere in the document, not just at the end.</p>
+  <p><xref alt="(longnote)" rid="ref_longnote">(longnote)</xref> Here's
+    the other note. This one contains multiple blocks.</p>
+  <p>Caret characters are used to indicate that the blocks all belong to
+    a single footnote (as with block quotes).</p>
+  <preformat>  { &lt;code&gt; }</preformat>
+  <p>If you want, you can use a caret at the beginning of every line, as
+    with blockquotes, but all that you need is a caret at the beginning
+    of the first line of the block and any preceding blank lines.</p>
+  <p>text <italic>Leading space</italic></p>
+  <p><italic>Trailing space</italic> text</p>
+  <p>text <italic>Leading spaces</italic></p>
+  <p><italic>Trailing spaces</italic> text</p>
+</sec>
+<sec id="tables">
+  <title>Tables</title>
+  <sec id="tables-with-headers">
+    <title>Tables with Headers</title>
+    <table-wrap><table>
+      <col align="left" />
+      <col align="left" />
+      <col align="left" />
+      <thead>
+        <tr>
+          <th>
+            <p>X</p>
+          </th>
+          <th>
+            <p>Y</p>
+          </th>
+          <th>
+            <p>Z</p>
+          </th>
+        </tr>
+      </thead>
+      <tbody>
+        <tr>
+          <td>
+            <p>1</p>
+          </td>
+          <td>
+            <p>2</p>
+          </td>
+          <td>
+            <p>3</p>
+          </td>
+        </tr>
+        <tr>
+          <td>
+            <p>4</p>
+          </td>
+          <td>
+            <p>5</p>
+          </td>
+          <td>
+            <p>6</p>
+          </td>
+        </tr>
+      </tbody>
+    </table></table-wrap>
+    <table-wrap><table>
+      <col align="left" />
+      <col align="left" />
+      <col align="left" />
+      <thead>
+        <tr>
+          <th>
+            <p>X</p>
+          </th>
+          <th>
+            <p>Y</p>
+          </th>
+          <th>
+            <p>Z</p>
+          </th>
+        </tr>
+      </thead>
+      <tbody>
+        <tr>
+          <td>
+            <p>1</p>
+          </td>
+          <td>
+            <p>2</p>
+          </td>
+          <td>
+            <p>3</p>
+          </td>
+        </tr>
+        <tr>
+          <td>
+            <p>4</p>
+          </td>
+          <td>
+            <p>5</p>
+          </td>
+          <td>
+            <p>6</p>
+          </td>
+        </tr>
+      </tbody>
+    </table></table-wrap>
+    <table-wrap><table>
+      <col align="left" />
+      <col align="left" />
+      <col align="left" />
+      <thead>
+        <tr>
+          <th>
+            <p>X</p>
+          </th>
+          <th>
+            <p>Y</p>
+          </th>
+          <th>
+            <p>Z</p>
+          </th>
+        </tr>
+      </thead>
+      <tbody>
+        <tr>
+          <td>
+            <p>1</p>
+          </td>
+          <td>
+            <p>2</p>
+          </td>
+          <td>
+            <p>3</p>
+          </td>
+        </tr>
+        <tr>
+          <td>
+            <p>4</p>
+          </td>
+          <td>
+            <p>5</p>
+          </td>
+          <td>
+            <p>6</p>
+          </td>
+        </tr>
+      </tbody>
+    </table></table-wrap>
+    <table-wrap><table>
+      <col align="left" />
+      <col align="left" />
+      <col align="left" />
+      <thead>
+        <tr>
+          <th>
+            <p>X</p>
+          </th>
+          <th>
+            <p>Y</p>
+          </th>
+          <th>
+            <p>Z</p>
+          </th>
+        </tr>
+      </thead>
+      <tbody>
+        <tr>
+          <td>
+            <p>1</p>
+          </td>
+          <td>
+            <p>2</p>
+          </td>
+          <td>
+            <p>3</p>
+          </td>
+        </tr>
+        <tr>
+          <td>
+            <p>4</p>
+          </td>
+          <td>
+            <p>5</p>
+          </td>
+          <td>
+            <p>6</p>
+          </td>
+        </tr>
+      </tbody>
+    </table></table-wrap>
+    <table-wrap><table>
+      <col align="left" />
+      <col align="left" />
+      <col align="left" />
+      <thead>
+        <tr>
+          <th>
+            <p>X</p>
+          </th>
+          <th>
+            <p>Y</p>
+          </th>
+          <th>
+            <p>Z</p>
+          </th>
+        </tr>
+      </thead>
+      <tbody>
+        <tr>
+          <td>
+            <p>1</p>
+          </td>
+          <td>
+            <p>2</p>
+          </td>
+          <td>
+            <p>3</p>
+          </td>
+        </tr>
+        <tr>
+          <td>
+            <p>4</p>
+          </td>
+          <td>
+            <p>5</p>
+          </td>
+          <td>
+            <p>6</p>
+          </td>
+        </tr>
+      </tbody>
+    </table></table-wrap>
+    <table-wrap><table>
+      <col align="left" />
+      <col align="left" />
+      <col align="left" />
+      <thead>
+        <tr>
+          <th>
+            <p>X</p>
+          </th>
+          <th>
+            <p>Y</p>
+          </th>
+          <th>
+            <p>Z</p>
+          </th>
+        </tr>
+      </thead>
+      <tbody>
+        <tr>
+          <td>
+            <p>1</p>
+          </td>
+          <td>
+            <p>2</p>
+          </td>
+          <td>
+            <p>3</p>
+          </td>
+        </tr>
+        <tr>
+          <td>
+            <p>4</p>
+          </td>
+          <td>
+            <p>5</p>
+          </td>
+          <td>
+            <p>6</p>
+          </td>
+        </tr>
+      </tbody>
+    </table></table-wrap>
+    <table-wrap><table>
+      <col align="left" />
+      <col align="left" />
+      <col align="left" />
+      <thead>
+        <tr>
+          <th>
+            <p>X</p>
+          </th>
+          <th>
+            <p>Y</p>
+          </th>
+          <th>
+            <p>Z</p>
+          </th>
+        </tr>
+      </thead>
+      <tbody>
+        <tr>
+          <td>
+            <p>1</p>
+          </td>
+          <td>
+            <p>2</p>
+          </td>
+          <td>
+            <p>3</p>
+          </td>
+        </tr>
+        <tr>
+          <td>
+            <p>4</p>
+          </td>
+          <td>
+            <p>5</p>
+          </td>
+          <td>
+            <p>6</p>
+          </td>
+        </tr>
+      </tbody>
+    </table></table-wrap>
+    <table-wrap><table>
+      <col align="left" />
+      <col align="left" />
+      <col align="left" />
+      <thead>
+        <tr>
+          <th>
+            <p>r1a</p>
+          </th>
+          <th>
+            <p>r1b</p>
+          </th>
+          <th>
+            <p>r1c</p>
+          </th>
+        </tr>
+        <tr>
+          <th>
+            <p>X</p>
+          </th>
+          <th>
+            <p>Y</p>
+          </th>
+          <th>
+            <p>Z</p>
+          </th>
+        </tr>
+      </thead>
+      <tbody>
+        <tr>
+          <td>
+            <p>1</p>
+          </td>
+          <td>
+            <p>2</p>
+          </td>
+          <td>
+            <p>3</p>
+          </td>
+        </tr>
+        <tr>
+          <td>
+            <p>4</p>
+          </td>
+          <td>
+            <p>5</p>
+          </td>
+          <td>
+            <p>6</p>
+          </td>
+        </tr>
+      </tbody>
+    </table></table-wrap>
+    <table-wrap><table>
+      <col width="33*" align="left" />
+      <col width="33*" align="left" />
+      <col width="33*" align="left" />
+      <thead>
+        <tr>
+          <th>
+            <p>X</p>
+          </th>
+          <th>
+            <p>Y</p>
+          </th>
+          <th>
+            <p>Z</p>
+          </th>
+        </tr>
+      </thead>
+      <tbody>
+        <tr>
+          <td>
+            <p>1</p>
+          </td>
+          <td>
+            <p>2</p>
+          </td>
+          <td>
+            <p>3</p>
+          </td>
+        </tr>
+        <tr>
+          <td>
+            <p>4</p>
+          </td>
+          <td>
+            <p>5</p>
+          </td>
+          <td>
+            <p>6</p>
+          </td>
+        </tr>
+      </tbody>
+    </table></table-wrap>
+  </sec>
+  <sec id="tables-without-headers">
+    <title>Tables without Headers</title>
+    <table-wrap><table>
+      <col align="left" />
+      <col align="left" />
+      <col align="left" />
+      <tbody>
+        <tr>
+          <td>
+            <p>1</p>
+          </td>
+          <td>
+            <p>2</p>
+          </td>
+          <td>
+            <p>3</p>
+          </td>
+        </tr>
+        <tr>
+          <td>
+            <p>4</p>
+          </td>
+          <td>
+            <p>5</p>
+          </td>
+          <td>
+            <p>6</p>
+          </td>
+        </tr>
+      </tbody>
+    </table></table-wrap>
+    <table-wrap><table>
+      <col align="left" />
+      <col align="left" />
+      <col align="left" />
+      <tbody>
+        <tr>
+          <td>
+            <p>1</p>
+          </td>
+          <td>
+            <p>2</p>
+          </td>
+          <td>
+            <p>3</p>
+          </td>
+        </tr>
+        <tr>
+          <td>
+            <p>4</p>
+          </td>
+          <td>
+            <p>5</p>
+          </td>
+          <td>
+            <p>6</p>
+          </td>
+        </tr>
+      </tbody>
+    </table></table-wrap>
+    <table-wrap><table>
+      <col align="left" />
+      <col align="left" />
+      <col align="left" />
+      <tbody>
+        <tr>
+          <td>
+            <p>1</p>
+          </td>
+          <td>
+            <p>2</p>
+          </td>
+          <td>
+            <p>3</p>
+          </td>
+        </tr>
+        <tr>
+          <td>
+            <p>4</p>
+          </td>
+          <td>
+            <p>5</p>
+          </td>
+          <td>
+            <p>6</p>
+          </td>
+        </tr>
+      </tbody>
+    </table></table-wrap>
+    <table-wrap><table>
+      <col align="left" />
+      <col align="left" />
+      <col align="left" />
+      <tbody>
+        <tr>
+          <td>
+            <p>1</p>
+          </td>
+          <td>
+            <p>2</p>
+          </td>
+          <td>
+            <p>3</p>
+          </td>
+        </tr>
+        <tr>
+          <td>
+            <p>4</p>
+          </td>
+          <td>
+            <p>5</p>
+          </td>
+          <td>
+            <p>6</p>
+          </td>
+        </tr>
+      </tbody>
+    </table></table-wrap>
+  </sec>
+  <sec id="table-with-spans-and-alignments">
+    <title>Tables with spans and alignments</title>
+    <table-wrap><table>
+      <col align="left" />
+      <col align="left" />
+      <col align="left" />
+      <thead>
+        <tr>
+            <td colspan="2">
+                <p>1</p>
+            </td>
+            <td align="right">
+                <p>2</p>
+            </td>
+        </tr>
+      </thead>
+      <tbody>
+        <tr>
+        <td colspan="2">
+            <p>1</p>
+        </td>
+        <td align="left">
+            <p>2</p>
+        </td>
+        </tr>
+        <tr>
+        <td rowspan="2">
+            <p>4</p>
+        </td>
+        <td>
+            <p>5</p>
+        </td>
+        <td>
+            <p>6</p>
+        </td>
+        </tr>
+        <tr>
+        <td colspan="2">
+            <p>7</p>
+        </td>
+        </tr>
+      </tbody>
+    </table></table-wrap>
+  </sec>
+  <sec id="table-with-footer">
+    <title>Table with footer</title>
+    <table-wrap><table>
+      <col align="left" />
+      <col align="left" />
+      <col align="left" />
+      <tfoot>
+        <tr>
+          <td align="right">
+            <p>f1</p>
+          </td>
+          <td>
+            <p>f2</p>
+          </td>
+          <td>
+            <p>f3</p>
+          </td>
+        </tr>
+        <tr>
+          <td align="right">
+            <p>f4</p>
+          </td>
+          <td>
+            <p>f5</p>
+          </td>
+          <td>
+            <p>f6</p>
+          </td>
+        </tr>
+      </tfoot>
+      <tbody>
+        <tr>
+          <td>
+            <p>1</p>
+          </td>
+          <td>
+            <p>2</p>
+          </td>
+          <td>
+            <p>3</p>
+          </td>
+        </tr>
+      </tbody>
+    </table></table-wrap>
+  </sec>
+  <sec id="table-with-multiple-bodies">
+    <title>Table With Multiple Bodies</title>
+    <table-wrap><table>
+      <col align="left" />
+      <col align="left" />
+      <col align="left" />
+      <tbody>
+        <tr>
+          <td align="right">
+            <p>a1</p>
+          </td>
+          <td>
+            <p>a2</p>
+          </td>
+          <td>
+            <p>a3</p>
+          </td>
+        </tr>
+      </tbody>
+      <tbody>
+        <tr>
+          <td>
+            <p>b1</p>
+          </td>
+          <td>
+            <p>b2</p>
+          </td>
+          <td>
+            <p>b3</p>
+          </td>
+        </tr>
+      </tbody>
+    </table></table-wrap>
+  </sec>
+  <sec id="empty-tables">
+    <title>Empty Tables</title>
+    <p>This section should be empty.</p>
+  </sec>
+</sec>
+</body>
+<back>
+  <ref-list>
+    <title>References</title>
+    <ref id="ref_1"><note><p>This is reference 1</p></note></ref>
+    <ref id="ref_longnote"><note><p>This is a long note</p></note></ref>
+  </ref-list>
+  <ref-list>
+    <title>Notes</title>
+    <ref id="note_1"><note><p>This is note 1</p></note></ref>
+    <ref id="note_longnote"><note><p>This is another long note</p></note></ref>
+  </ref-list>
 </back>
 </article>
diff --git a/test/jira-reader.jira b/test/jira-reader.jira
new file mode 100644
--- /dev/null
+++ b/test/jira-reader.jira
@@ -0,0 +1,284 @@
+h1. {anchor:headers}Headers
+h2. {anchor:level-2-with-an-embedded-link}Level 2 with an [embedded link|https://test.example/url]
+h3. {anchor:level-3-with-emphasis}Level 3 with _emphasis_
+h4. Level 4
+h5. Level 5
+h6. Level 6
+
+h0. this is not a header.
+
+----
+h1. Paragraphs
+Here’s a regular paragraph.
+
+Here’s one with a bullet. * criminey.
+
+There should be a hard line break
+here.
+
+----
+h1. Block Quotes
+E-mail style:
+
+bq. This is a block quote. It is pretty short.
+{quote}
+Code in a block quote:
+
+{code:java}
+sub status {
+    print "working";
+}
+{code}
+
+An enumeration:
+
+# item one
+# item two
+{quote}
+
+A following paragraph.
+
+----
+h1. Code Blocks
+
+Code:
+
+{code:java}
+---- (should be four hyphens)
+
+sub status {
+    print "working";
+}
+{code}
+And:
+
+{code:java}
+    this code block is indented by two tabs
+
+These should not be escaped:  \$ \\ \> \[ \{
+{code}
+
+----
+h1. {anchor:lists}Lists
+h2. {anchor:unordered}Unordered
+Asterisks:
+
+* asterisk 1
+* asterisk 2
+* asterisk 3
+
+Minuses:
+
+- Minus 1
+- Minus 2
+- Minus 3
+
+h2. Ordered
+
+# First
+# Second
+# Third
+
+Linebreak in paragraph:
+
+# Item 1, line one.
+Item 1. line two. The quick brown fox jumped over the lazy dog’s back.
+# Item 2.
+# Item 3.
+
+h2. Nested
+* Tab
+** Tab
+*** Tab
+
+Here’s another:
+
+# First
+# Second:
+#* Fee
+#* Fie
+#* Foe
+# Third
+
+Nested enumerations:
+
+# Essential
+## Important
+### Relevant
+#### Insignificant
+
+----
+h1. Linebreaks and Markup in Lists
+
+* *apple*
+red fruit
+* *orange*
+orange fruit
+* *banana*
+yellow fruit
+
+Multiple blocks with italics:
+
+* *_apple_*
+red fruit
+contains seeds, crisp, pleasant to taste
+* *_orange_*
+orange fruit
+{code:java}
+{ orange code block }
+{code}
+bq. orange block quote
+
+----
+h1. Colored Text Blocks
+{color:red}
+This is red.
+{color}
+
+h2. Eiffel 65
+
+{color:blue}
+da ba dee
+{color}
+
+----
+h1. Inline Markup
+This is _emphasized_, and so _is this_.
+
+This is *strong*, and so *is this*.
+
+An _[emphasized link|https://my.example/url]_.
+
+*_This is strong and em._*
+
+So is *_this_* word.
+
+This is code: {{>}}, {{$}}, {{&bsol;}}, {{&bsol;$}}, {{<html>}}.
+
+-This is _strikeout_.-
+
+Superscripts: a{^}bc{^}d a{^}_hello_{^} a{^}hello there{^}.
+
+Subscripts: H{~}2{~}O, C{~}6{~}H{~}12{~}O{~}6{~}, C{~} n {~}H{~}_2n_{~}O{~}n{~}.
+
+These should not be superscripts or subscripts, because of markers used within words: a^b c^d, a~b c~d.
+
+----
+h1. Dashes, and emoticons
+
+Some dashes: one -- two --- three.
+
+Sure (/)
+Nope (x)
+
+Nice :D
+
+Capital d\:D
+
+----
+h1. Math
+
+* 2 + 2 = 4
+* _x_ ∈ {_}y{_}
+* _α_ ∧ {_}ω{_}
+* _p_-Tree
+* Here’s one more: _α_ + {_}ω{_} × {_}x{_}^2^.
+
+
+----
+h1. Special Characters
+Here is some unicode:
+
+* I hat: Î
+* o umlaut: ö
+* section: §
+* set membership: ∈
+* copyright: ©
+
+AT&T has an ampersand in their name.
+
+AT&amp;T is another way to write it.
+
+This & that.
+
+4 < 5.
+
+6 > 5.
+
+Backslash: &bsol;
+
+Backtick: `
+
+Asterisk: *
+
+Underscore: _
+
+Left brace: {
+
+Right brace: }
+
+Left bracket: [
+
+Right bracket: ]
+
+Left paren: (
+
+Right paren: )
+
+Greater-than: >
+
+Hash: #
+
+Period: .
+
+Bang: !
+
+Plus: +
+
+Minus: -
+
+----
+h1. Links
+h2. Explicit
+Just a [URL|https://example.org/url].
+
+[File URL|file://some/file/name/].
+
+[IRC link|irc://example.org/pandoc].
+
+[Email link|mailto:nobody@nowhere.invalid]
+
+[Not a link|not a URL].
+
+h2. Reference
+With [embedded \[brackets\]|https://example.net/url/].
+
+https://pandoc.org by itself should be a link.
+
+h2. With ampersands
+Here’s a [link with an ampersand in the URL|http://example.com/?foo=1&bar=2].
+
+Here’s a link with an ampersand in the link text: [AT&T|http://att.com/].
+
+h2. Autolinks
+With an ampersand: http://example.com/?foo=1&bar=2
+
+* In a list?
+* http://example.com/
+* It should.
+
+An e-mail address: mailto:nobody@nowhere.invalid
+
+bq. Blockquoted: http://example.com/
+
+{code:java}
+Autolink should not occur here: <http://example.com/>
+{code}
+
+----
+h1. Images
+From "Voyage dans la Lune" by Georges Melies (1902):
+
+!lalune.jpg!
+
+Here is a movie !movie.jpg! icon.
diff --git a/test/jira-reader.native b/test/jira-reader.native
new file mode 100644
--- /dev/null
+++ b/test/jira-reader.native
@@ -0,0 +1,947 @@
+Pandoc
+  Meta { unMeta = fromList [] }
+  [ Header
+      1
+      ( "" , [] , [] )
+      [ Span ( "headers" , [] , [] ) [] , Str "Headers" ]
+  , Header
+      2
+      ( "" , [] , [] )
+      [ Span ( "level-2-with-an-embedded-link" , [] , [] ) []
+      , Str "Level"
+      , Space
+      , Str "2"
+      , Space
+      , Str "with"
+      , Space
+      , Str "an"
+      , Space
+      , Link
+          ( "" , [] , [] )
+          [ Str "embedded" , Space , Str "link" ]
+          ( "https://test.example/url" , "" )
+      ]
+  , Header
+      3
+      ( "" , [] , [] )
+      [ Span ( "level-3-with-emphasis" , [] , [] ) []
+      , Str "Level"
+      , Space
+      , Str "3"
+      , Space
+      , Str "with"
+      , Space
+      , Emph [ Str "emphasis" ]
+      ]
+  , Header
+      4 ( "" , [] , [] ) [ Str "Level" , Space , Str "4" ]
+  , Header
+      5 ( "" , [] , [] ) [ Str "Level" , Space , Str "5" ]
+  , Header
+      6 ( "" , [] , [] ) [ Str "Level" , Space , Str "6" ]
+  , Para
+      [ Str "h0."
+      , Space
+      , Str "this"
+      , Space
+      , Str "is"
+      , Space
+      , Str "not"
+      , Space
+      , Str "a"
+      , Space
+      , Str "header."
+      ]
+  , HorizontalRule
+  , Header 1 ( "" , [] , [] ) [ Str "Paragraphs" ]
+  , Para
+      [ Str "Here\8217s"
+      , Space
+      , Str "a"
+      , Space
+      , Str "regular"
+      , Space
+      , Str "paragraph."
+      ]
+  , Para
+      [ Str "Here\8217s"
+      , Space
+      , Str "one"
+      , Space
+      , Str "with"
+      , Space
+      , Str "a"
+      , Space
+      , Str "bullet."
+      , Space
+      , Str "*"
+      , Space
+      , Str "criminey."
+      ]
+  , Para
+      [ Str "There"
+      , Space
+      , Str "should"
+      , Space
+      , Str "be"
+      , Space
+      , Str "a"
+      , Space
+      , Str "hard"
+      , Space
+      , Str "line"
+      , Space
+      , Str "break"
+      , LineBreak
+      , Str "here."
+      ]
+  , HorizontalRule
+  , Header
+      1 ( "" , [] , [] ) [ Str "Block" , Space , Str "Quotes" ]
+  , Para [ Str "E-mail" , Space , Str "style:" ]
+  , BlockQuote
+      [ Para
+          [ Str "This"
+          , Space
+          , Str "is"
+          , Space
+          , Str "a"
+          , Space
+          , Str "block"
+          , Space
+          , Str "quote."
+          , Space
+          , Str "It"
+          , Space
+          , Str "is"
+          , Space
+          , Str "pretty"
+          , Space
+          , Str "short."
+          ]
+      ]
+  , BlockQuote
+      [ Para
+          [ Str "Code"
+          , Space
+          , Str "in"
+          , Space
+          , Str "a"
+          , Space
+          , Str "block"
+          , Space
+          , Str "quote:"
+          ]
+      , CodeBlock
+          ( "" , [ "java" ] , [] )
+          "sub status {\n    print \"working\";\n}\n"
+      , Para [ Str "An" , Space , Str "enumeration:" ]
+      , OrderedList
+          ( 1 , DefaultStyle , DefaultDelim )
+          [ [ Para [ Str "item" , Space , Str "one" ] ]
+          , [ Para [ Str "item" , Space , Str "two" ] ]
+          ]
+      ]
+  , Para
+      [ Str "A"
+      , Space
+      , Str "following"
+      , Space
+      , Str "paragraph."
+      ]
+  , HorizontalRule
+  , Header
+      1 ( "" , [] , [] ) [ Str "Code" , Space , Str "Blocks" ]
+  , Para [ Str "Code:" ]
+  , CodeBlock
+      ( "" , [ "java" ] , [] )
+      "---- (should be four hyphens)\n\nsub status {\n    print \"working\";\n}\n"
+  , Para [ Str "And:" ]
+  , CodeBlock
+      ( "" , [ "java" ] , [] )
+      "    this code block is indented by two tabs\n\nThese should not be escaped:  \\$ \\\\ \\> \\[ \\{\n"
+  , HorizontalRule
+  , Header
+      1
+      ( "" , [] , [] )
+      [ Span ( "lists" , [] , [] ) [] , Str "Lists" ]
+  , Header
+      2
+      ( "" , [] , [] )
+      [ Span ( "unordered" , [] , [] ) [] , Str "Unordered" ]
+  , Para [ Str "Asterisks:" ]
+  , BulletList
+      [ [ Para [ Str "asterisk" , Space , Str "1" ] ]
+      , [ Para [ Str "asterisk" , Space , Str "2" ] ]
+      , [ Para [ Str "asterisk" , Space , Str "3" ] ]
+      ]
+  , Para [ Str "Minuses:" ]
+  , BulletList
+      [ [ Para [ Str "Minus" , Space , Str "1" ] ]
+      , [ Para [ Str "Minus" , Space , Str "2" ] ]
+      , [ Para [ Str "Minus" , Space , Str "3" ] ]
+      ]
+  , Header 2 ( "" , [] , [] ) [ Str "Ordered" ]
+  , OrderedList
+      ( 1 , DefaultStyle , DefaultDelim )
+      [ [ Para [ Str "First" ] ]
+      , [ Para [ Str "Second" ] ]
+      , [ Para [ Str "Third" ] ]
+      ]
+  , Para
+      [ Str "Linebreak"
+      , Space
+      , Str "in"
+      , Space
+      , Str "paragraph:"
+      ]
+  , OrderedList
+      ( 1 , DefaultStyle , DefaultDelim )
+      [ [ Para
+            [ Str "Item"
+            , Space
+            , Str "1,"
+            , Space
+            , Str "line"
+            , Space
+            , Str "one."
+            , LineBreak
+            , Str "Item"
+            , Space
+            , Str "1."
+            , Space
+            , Str "line"
+            , 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"
+            , Space
+            , Str "back."
+            ]
+        ]
+      , [ Para [ Str "Item" , Space , Str "2." ] ]
+      , [ Para [ Str "Item" , Space , Str "3." ] ]
+      ]
+  , Header 2 ( "" , [] , [] ) [ Str "Nested" ]
+  , BulletList
+      [ [ Para [ Str "Tab" ]
+        , BulletList
+            [ [ Para [ Str "Tab" ]
+              , BulletList [ [ Para [ Str "Tab" ] ] ]
+              ]
+            ]
+        ]
+      ]
+  , Para [ Str "Here\8217s" , Space , Str "another:" ]
+  , OrderedList
+      ( 1 , DefaultStyle , DefaultDelim )
+      [ [ Para [ Str "First" ] ]
+      , [ Para [ Str "Second:" ]
+        , BulletList
+            [ [ Para [ Str "Fee" ] ]
+            , [ Para [ Str "Fie" ] ]
+            , [ Para [ Str "Foe" ] ]
+            ]
+        ]
+      , [ Para [ Str "Third" ] ]
+      ]
+  , Para [ Str "Nested" , Space , Str "enumerations:" ]
+  , OrderedList
+      ( 1 , DefaultStyle , DefaultDelim )
+      [ [ Para [ Str "Essential" ]
+        , OrderedList
+            ( 1 , DefaultStyle , DefaultDelim )
+            [ [ Para [ Str "Important" ]
+              , OrderedList
+                  ( 1 , DefaultStyle , DefaultDelim )
+                  [ [ Para [ Str "Relevant" ]
+                    , OrderedList
+                        ( 1 , DefaultStyle , DefaultDelim )
+                        [ [ Para [ Str "Insignificant" ] ] ]
+                    ]
+                  ]
+              ]
+            ]
+        ]
+      ]
+  , HorizontalRule
+  , Header
+      1
+      ( "" , [] , [] )
+      [ Str "Linebreaks"
+      , Space
+      , Str "and"
+      , Space
+      , Str "Markup"
+      , Space
+      , Str "in"
+      , Space
+      , Str "Lists"
+      ]
+  , BulletList
+      [ [ Para
+            [ Strong [ Str "apple" ]
+            , LineBreak
+            , Str "red"
+            , Space
+            , Str "fruit"
+            ]
+        ]
+      , [ Para
+            [ Strong [ Str "orange" ]
+            , LineBreak
+            , Str "orange"
+            , Space
+            , Str "fruit"
+            ]
+        ]
+      , [ Para
+            [ Strong [ Str "banana" ]
+            , LineBreak
+            , Str "yellow"
+            , Space
+            , Str "fruit"
+            ]
+        ]
+      ]
+  , Para
+      [ Str "Multiple"
+      , Space
+      , Str "blocks"
+      , Space
+      , Str "with"
+      , Space
+      , Str "italics:"
+      ]
+  , BulletList
+      [ [ Para
+            [ Strong [ Emph [ Str "apple" ] ]
+            , LineBreak
+            , Str "red"
+            , Space
+            , Str "fruit"
+            , LineBreak
+            , Str "contains"
+            , Space
+            , Str "seeds,"
+            , Space
+            , Str "crisp,"
+            , Space
+            , Str "pleasant"
+            , Space
+            , Str "to"
+            , Space
+            , Str "taste"
+            ]
+        ]
+      , [ Para
+            [ Strong [ Emph [ Str "orange" ] ]
+            , LineBreak
+            , Str "orange"
+            , Space
+            , Str "fruit"
+            ]
+        , CodeBlock
+            ( "" , [ "java" ] , [] ) "{ orange code block }\n"
+        , BlockQuote
+            [ Para
+                [ Str "orange"
+                , Space
+                , Str "block"
+                , Space
+                , Str "quote"
+                ]
+            ]
+        ]
+      ]
+  , HorizontalRule
+  , Header
+      1
+      ( "" , [] , [] )
+      [ Str "Colored"
+      , Space
+      , Str "Text"
+      , Space
+      , Str "Blocks"
+      ]
+  , Div
+      ( "" , [] , [ ( "color" , "red" ) ] )
+      [ Para
+          [ LineBreak
+          , Str "This"
+          , Space
+          , Str "is"
+          , Space
+          , Str "red."
+          ]
+      ]
+  , Header
+      2 ( "" , [] , [] ) [ Str "Eiffel" , Space , Str "65" ]
+  , Div
+      ( "" , [] , [ ( "color" , "blue" ) ] )
+      [ Para
+          [ LineBreak
+          , Str "da"
+          , Space
+          , Str "ba"
+          , Space
+          , Str "dee"
+          ]
+      ]
+  , HorizontalRule
+  , Header
+      1 ( "" , [] , [] ) [ Str "Inline" , Space , Str "Markup" ]
+  , Para
+      [ Str "This"
+      , Space
+      , Str "is"
+      , Space
+      , Emph [ Str "emphasized" ]
+      , Str ","
+      , Space
+      , Str "and"
+      , Space
+      , Str "so"
+      , Space
+      , Emph [ Str "is" , Space , Str "this" ]
+      , Str "."
+      ]
+  , Para
+      [ Str "This"
+      , Space
+      , Str "is"
+      , Space
+      , Strong [ Str "strong" ]
+      , Str ","
+      , Space
+      , Str "and"
+      , Space
+      , Str "so"
+      , Space
+      , Strong [ Str "is" , Space , Str "this" ]
+      , Str "."
+      ]
+  , Para
+      [ Str "An"
+      , Space
+      , Emph
+          [ Link
+              ( "" , [] , [] )
+              [ Str "emphasized" , Space , Str "link" ]
+              ( "https://my.example/url" , "" )
+          ]
+      , Str "."
+      ]
+  , Para
+      [ Strong
+          [ Emph
+              [ Str "This"
+              , Space
+              , Str "is"
+              , Space
+              , Str "strong"
+              , Space
+              , Str "and"
+              , Space
+              , Str "em."
+              ]
+          ]
+      ]
+  , Para
+      [ Str "So"
+      , Space
+      , Str "is"
+      , Space
+      , Strong [ Emph [ Str "this" ] ]
+      , Space
+      , Str "word."
+      ]
+  , Para
+      [ Str "This"
+      , Space
+      , Str "is"
+      , Space
+      , Str "code:"
+      , Space
+      , Code ( "" , [] , [] ) ">"
+      , Str ","
+      , Space
+      , Code ( "" , [] , [] ) "$"
+      , Str ","
+      , Space
+      , Code ( "" , [] , [] ) "\\"
+      , Str ","
+      , Space
+      , Code ( "" , [] , [] ) "\\$"
+      , Str ","
+      , Space
+      , Code ( "" , [] , [] ) "<html>"
+      , Str "."
+      ]
+  , Para
+      [ Strikeout
+          [ Str "This"
+          , Space
+          , Str "is"
+          , Space
+          , Emph [ Str "strikeout" ]
+          , Str "."
+          ]
+      ]
+  , Para
+      [ Str "Superscripts:"
+      , Space
+      , Str "a"
+      , Superscript [ Str "bc" ]
+      , Str "d"
+      , Space
+      , Str "a"
+      , Superscript [ Emph [ Str "hello" ] ]
+      , Space
+      , Str "a"
+      , Superscript [ Str "hello\160there" ]
+      , Str "."
+      ]
+  , Para
+      [ Str "Subscripts:"
+      , Space
+      , Str "H"
+      , Subscript [ Str "2" ]
+      , Str "O,"
+      , Space
+      , Str "C"
+      , Subscript [ Str "6" ]
+      , Str "H"
+      , Subscript [ Str "12" ]
+      , Str "O"
+      , Subscript [ Str "6" ]
+      , Str ","
+      , Space
+      , Str "C"
+      , Subscript [ Str "\160n\160" ]
+      , Str "H"
+      , Subscript [ Emph [ Str "2n" ] ]
+      , Str "O"
+      , Subscript [ Str "n" ]
+      , Str "."
+      ]
+  , Para
+      [ Str "These"
+      , Space
+      , Str "should"
+      , Space
+      , Str "not"
+      , Space
+      , Str "be"
+      , Space
+      , Str "superscripts"
+      , Space
+      , Str "or"
+      , Space
+      , Str "subscripts,"
+      , Space
+      , Str "because"
+      , Space
+      , Str "of"
+      , Space
+      , Str "markers"
+      , Space
+      , Str "used"
+      , Space
+      , Str "within"
+      , Space
+      , Str "words:"
+      , Space
+      , Str "a^b"
+      , Space
+      , Str "c^d,"
+      , Space
+      , Str "a~b"
+      , Space
+      , Str "c~d."
+      ]
+  , HorizontalRule
+  , Header
+      1
+      ( "" , [] , [] )
+      [ Str "Dashes,"
+      , Space
+      , Str "and"
+      , Space
+      , Str "emoticons"
+      ]
+  , Para
+      [ Str "Some"
+      , Space
+      , Str "dashes:"
+      , Space
+      , Str "one"
+      , Space
+      , Str "\8211"
+      , Space
+      , Str "two"
+      , Space
+      , Str "\8212"
+      , Space
+      , Str "three."
+      ]
+  , Para
+      [ Str "Sure"
+      , Space
+      , Str "\10004"
+      , LineBreak
+      , Str "Nope"
+      , Space
+      , Str "\10060"
+      ]
+  , Para [ Str "Nice" , Space , Str "\128515" ]
+  , Para [ Str "Capital" , Space , Str "d:D" ]
+  , HorizontalRule
+  , Header 1 ( "" , [] , [] ) [ Str "Math" ]
+  , BulletList
+      [ [ Para [ Str "2\8197+\8197\&2\8196=\8196\&4" ] ]
+      , [ Para
+            [ Emph [ Str "x" ]
+            , Str "\8196\8712\8196"
+            , Emph [ Str "y" ]
+            ]
+        ]
+      , [ Para
+            [ Emph [ Str "\945" ]
+            , Str "\8197\8743\8197"
+            , Emph [ Str "\969" ]
+            ]
+        ]
+      , [ Para [ Emph [ Str "p" ] , Str "-Tree" ] ]
+      , [ Para
+            [ Str "Here\8217s"
+            , Space
+            , Str "one"
+            , Space
+            , Str "more:"
+            , Space
+            , Emph [ Str "\945" ]
+            , Str "\8197+\8197"
+            , Emph [ Str "\969" ]
+            , Str "\8197\215\8197"
+            , Emph [ Str "x" ]
+            , Superscript [ Str "2" ]
+            , Str "."
+            ]
+        ]
+      ]
+  , HorizontalRule
+  , Header
+      1
+      ( "" , [] , [] )
+      [ Str "Special" , Space , Str "Characters" ]
+  , Para
+      [ Str "Here"
+      , Space
+      , Str "is"
+      , Space
+      , Str "some"
+      , Space
+      , Str "unicode:"
+      ]
+  , BulletList
+      [ [ Para
+            [ Str "I" , Space , Str "hat:" , Space , Str "\206" ]
+        ]
+      , [ Para
+            [ Str "o" , Space , Str "umlaut:" , Space , Str "\246" ]
+        ]
+      , [ Para [ Str "section:" , Space , Str "\167" ] ]
+      , [ Para
+            [ Str "set"
+            , Space
+            , Str "membership:"
+            , Space
+            , Str "\8712"
+            ]
+        ]
+      , [ Para [ Str "copyright:" , Space , Str "\169" ] ]
+      ]
+  , Para
+      [ Str "AT&T"
+      , Space
+      , Str "has"
+      , Space
+      , Str "an"
+      , Space
+      , Str "ampersand"
+      , Space
+      , Str "in"
+      , Space
+      , Str "their"
+      , Space
+      , Str "name."
+      ]
+  , Para
+      [ Str "AT&T"
+      , Space
+      , Str "is"
+      , Space
+      , Str "another"
+      , Space
+      , Str "way"
+      , Space
+      , Str "to"
+      , Space
+      , Str "write"
+      , Space
+      , Str "it."
+      ]
+  , Para
+      [ Str "This" , Space , Str "&" , Space , Str "that." ]
+  , Para [ Str "4" , Space , Str "<" , Space , Str "5." ]
+  , Para [ Str "6" , Space , Str ">" , Space , Str "5." ]
+  , Para [ Str "Backslash:" , Space , Str "\\" ]
+  , Para [ Str "Backtick:" , Space , Str "`" ]
+  , Para [ Str "Asterisk:" , Space , Str "*" ]
+  , Para [ Str "Underscore:" , Space , Str "_" ]
+  , Para
+      [ Str "Left" , Space , Str "brace:" , Space , Str "{" ]
+  , Para
+      [ Str "Right" , Space , Str "brace:" , Space , Str "}" ]
+  , Para
+      [ Str "Left" , Space , Str "bracket:" , Space , Str "[" ]
+  , Para
+      [ Str "Right" , Space , Str "bracket:" , Space , Str "]" ]
+  , Para
+      [ Str "Left" , Space , Str "paren:" , Space , Str "(" ]
+  , Para
+      [ Str "Right" , Space , Str "paren:" , Space , Str ")" ]
+  , Para [ Str "Greater-than:" , Space , Str ">" ]
+  , Para [ Str "Hash:" , Space , Str "#" ]
+  , Para [ Str "Period:" , Space , Str "." ]
+  , Para [ Str "Bang:" , Space , Str "!" ]
+  , Para [ Str "Plus:" , Space , Str "+" ]
+  , Para [ Str "Minus:" , Space , Str "-" ]
+  , HorizontalRule
+  , Header 1 ( "" , [] , [] ) [ Str "Links" ]
+  , Header 2 ( "" , [] , [] ) [ Str "Explicit" ]
+  , Para
+      [ Str "Just"
+      , Space
+      , Str "a"
+      , Space
+      , Link
+          ( "" , [] , [] )
+          [ Str "URL" ]
+          ( "https://example.org/url" , "" )
+      , Str "."
+      ]
+  , Para
+      [ Link
+          ( "" , [] , [] )
+          [ Str "File" , Space , Str "URL" ]
+          ( "file://some/file/name/" , "" )
+      , Str "."
+      ]
+  , Para
+      [ Link
+          ( "" , [] , [] )
+          [ Str "IRC" , Space , Str "link" ]
+          ( "irc://example.org/pandoc" , "" )
+      , Str "."
+      ]
+  , Para
+      [ Link
+          ( "" , [] , [] )
+          [ Str "Email" , Space , Str "link" ]
+          ( "mailto:nobody@nowhere.invalid" , "" )
+      ]
+  , Para
+      [ Str "[Not"
+      , Space
+      , Str "a"
+      , Space
+      , Str "link|not"
+      , Space
+      , Str "a"
+      , Space
+      , Str "URL]."
+      ]
+  , Header 2 ( "" , [] , [] ) [ Str "Reference" ]
+  , Para
+      [ Str "With"
+      , Space
+      , Link
+          ( "" , [] , [] )
+          [ Str "embedded" , Space , Str "[brackets]" ]
+          ( "https://example.net/url/" , "" )
+      , Str "."
+      ]
+  , Para
+      [ Link
+          ( "" , [] , [] )
+          [ Str "https://pandoc.org" ]
+          ( "https://pandoc.org" , "" )
+      , Space
+      , Str "by"
+      , Space
+      , Str "itself"
+      , Space
+      , Str "should"
+      , Space
+      , Str "be"
+      , Space
+      , Str "a"
+      , Space
+      , Str "link."
+      ]
+  , Header
+      2 ( "" , [] , [] ) [ Str "With" , Space , Str "ampersands" ]
+  , Para
+      [ Str "Here\8217s"
+      , Space
+      , Str "a"
+      , Space
+      , Link
+          ( "" , [] , [] )
+          [ Str "link"
+          , Space
+          , Str "with"
+          , Space
+          , Str "an"
+          , Space
+          , Str "ampersand"
+          , Space
+          , Str "in"
+          , Space
+          , Str "the"
+          , Space
+          , Str "URL"
+          ]
+          ( "http://example.com/?foo=1&bar=2" , "" )
+      , Str "."
+      ]
+  , Para
+      [ Str "Here\8217s"
+      , Space
+      , Str "a"
+      , Space
+      , Str "link"
+      , Space
+      , Str "with"
+      , Space
+      , Str "an"
+      , Space
+      , Str "ampersand"
+      , Space
+      , Str "in"
+      , Space
+      , Str "the"
+      , Space
+      , Str "link"
+      , Space
+      , Str "text:"
+      , Space
+      , Link
+          ( "" , [] , [] ) [ Str "AT&T" ] ( "http://att.com/" , "" )
+      , Str "."
+      ]
+  , Header 2 ( "" , [] , [] ) [ Str "Autolinks" ]
+  , Para
+      [ Str "With"
+      , Space
+      , Str "an"
+      , Space
+      , Str "ampersand:"
+      , Space
+      , Link
+          ( "" , [] , [] )
+          [ Str "http://example.com/?foo=1&bar=2" ]
+          ( "http://example.com/?foo=1&bar=2" , "" )
+      ]
+  , BulletList
+      [ [ Para
+            [ Str "In" , Space , Str "a" , Space , Str "list?" ]
+        ]
+      , [ Para
+            [ Link
+                ( "" , [] , [] )
+                [ Str "http://example.com/" ]
+                ( "http://example.com/" , "" )
+            ]
+        ]
+      , [ Para [ Str "It" , Space , Str "should." ] ]
+      ]
+  , Para
+      [ Str "An"
+      , Space
+      , Str "e-mail"
+      , Space
+      , Str "address:"
+      , Space
+      , Link
+          ( "" , [] , [] )
+          [ Str "mailto:nobody@nowhere.invalid" ]
+          ( "mailto:nobody@nowhere.invalid" , "" )
+      ]
+  , BlockQuote
+      [ Para
+          [ Str "Blockquoted:"
+          , Space
+          , Link
+              ( "" , [] , [] )
+              [ Str "http://example.com/" ]
+              ( "http://example.com/" , "" )
+          ]
+      ]
+  , CodeBlock
+      ( "" , [ "java" ] , [] )
+      "Autolink should not occur here: <http://example.com/>\n"
+  , HorizontalRule
+  , Header 1 ( "" , [] , [] ) [ Str "Images" ]
+  , Para
+      [ Str "From"
+      , Space
+      , Str "\"Voyage"
+      , Space
+      , Str "dans"
+      , Space
+      , Str "la"
+      , Space
+      , Str "Lune\""
+      , Space
+      , Str "by"
+      , Space
+      , Str "Georges"
+      , Space
+      , Str "Melies"
+      , Space
+      , Str "(1902):"
+      ]
+  , Para [ Image ( "" , [] , [] ) [] ( "lalune.jpg" , "" ) ]
+  , Para
+      [ Str "Here"
+      , Space
+      , Str "is"
+      , Space
+      , Str "a"
+      , Space
+      , Str "movie"
+      , Space
+      , Image ( "" , [] , [] ) [] ( "movie.jpg" , "" )
+      , Space
+      , Str "icon."
+      ]
+  ]
diff --git a/test/latex-reader.latex b/test/latex-reader.latex
--- a/test/latex-reader.latex
+++ b/test/latex-reader.latex
@@ -1,23 +1,18 @@
 \documentclass{article}
-\usepackage[mathletters]{ucs}
 \usepackage[utf8x]{inputenc}
-\setlength{\parindent}{0pt}
-\setlength{\parskip}{6pt plus 2pt minus 1pt}
 
-\usepackage[breaklinks=true,unicode=true]{hyperref}
+\usepackage{hyperref}
 \usepackage[normalem]{ulem}
-% avoid problems with \sout in headers with hyperref:
-\pdfstringdefDisableCommands{\renewcommand{\sout}{}}
 \usepackage{enumerate}
+\usepackage{setspace}
 \usepackage{fancyvrb}
 \usepackage{graphicx}
-\usepackage{url}
-
-\setcounter{secnumdepth}{0}
 \VerbatimFootnotes % allows verbatim text in footnotes
+
 \title{Pandoc Test Suite}
 \author{John MacFarlane \and Anonymous}
 \date{July 17, 2006}
+
 \begin{document}
 \maketitle
 
diff --git a/test/latex-reader.native b/test/latex-reader.native
--- a/test/latex-reader.native
+++ b/test/latex-reader.native
@@ -1,375 +1,2291 @@
-Pandoc (Meta {unMeta = fromList [("author",MetaList [MetaInlines [Str "John",Space,Str "MacFarlane"],MetaInlines [Str "Anonymous"]]),("date",MetaInlines [Str "July",Space,Str "17,",Space,Str "2006"]),("title",MetaInlines [Str "Pandoc",Space,Str "Test",Space,Str "Suite"])]})
-[RawBlock (Format "latex") "\\maketitle"
-,Para [Str "This",Space,Str "is",Space,Str "a",Space,Str "set",Space,Str "of",Space,Str "tests",Space,Str "for",Space,Str "pandoc.",Space,Str "Most",Space,Str "of",Space,Str "them",Space,Str "are",Space,Str "adapted",Space,Str "from",SoftBreak,Str "John",Space,Str "Gruber\8217s",Space,Str "markdown",Space,Str "test",Space,Str "suite."]
-,HorizontalRule
-,Header 1 ("headers",[],[]) [Str "Headers"]
-,Header 2 ("level-2-with-an-embedded-link",[],[]) [Str "Level",Space,Str "2",Space,Str "with",Space,Str "an",Space,Link ("",[],[]) [Str "embedded",Space,Str "link"] ("/url","")]
-,Header 3 ("level-3-with-emphasis",[],[]) [Str "Level",Space,Str "3",Space,Str "with",Space,Emph [Str "emphasis"]]
-,Para [Str "Level",Space,Str "4"]
-,Para [Str "Level",Space,Str "5"]
-,Header 1 ("level-1",[],[]) [Str "Level",Space,Str "1"]
-,Header 2 ("level-2-with-emphasis",[],[]) [Str "Level",Space,Str "2",Space,Str "with",Space,Emph [Str "emphasis"]]
-,Header 3 ("level-3",[],[]) [Str "Level",Space,Str "3"]
-,Para [Str "with",Space,Str "no",Space,Str "blank",Space,Str "line"]
-,Header 2 ("level-2",[],[]) [Str "Level",Space,Str "2"]
-,Para [Str "with",Space,Str "no",Space,Str "blank",Space,Str "line"]
-,HorizontalRule
-,Header 1 ("paragraphs",[],[]) [Str "Paragraphs"]
-,Para [Str "Here\8217s",Space,Str "a",Space,Str "regular",Space,Str "paragraph."]
-,Para [Str "In",Space,Str "Markdown",Space,Str "1.0.0",Space,Str "and",Space,Str "earlier.",Space,Str "Version",Space,Str "8.",Space,Str "This",Space,Str "line",Space,Str "turns",Space,Str "into",Space,Str "a",SoftBreak,Str "list",Space,Str "item.",Space,Str "Because",Space,Str "a",Space,Str "hard-wrapped",Space,Str "line",Space,Str "in",Space,Str "the",Space,Str "middle",Space,Str "of",Space,Str "a",Space,Str "paragraph",SoftBreak,Str "looked",Space,Str "like",Space,Str "a",Space,Str "list",Space,Str "item."]
-,Para [Str "Here\8217s",Space,Str "one",Space,Str "with",Space,Str "a",Space,Str "bullet.",Space,Str "*",Space,Str "criminey."]
-,Para [Str "There",Space,Str "should",Space,Str "be",Space,Str "a",Space,Str "hard",Space,Str "line",Space,Str "break",LineBreak,Str "here."]
-,HorizontalRule
-,Header 1 ("block-quotes",[],[]) [Str "Block",Space,Str "Quotes"]
-,Para [Str "E-mail",Space,Str "style:"]
-,BlockQuote
- [Para [Str "This",Space,Str "is",Space,Str "a",Space,Str "block",Space,Str "quote.",Space,Str "It",Space,Str "is",Space,Str "pretty",Space,Str "short."]]
-,BlockQuote
- [Para [Str "Code",Space,Str "in",Space,Str "a",Space,Str "block",Space,Str "quote:"]
- ,CodeBlock ("",[],[]) "sub status {\n    print \"working\";\n}"
- ,Para [Str "A",Space,Str "list:"]
- ,OrderedList (1,Decimal,Period)
-  [[Para [Str "item",Space,Str "one"]]
-  ,[Para [Str "item",Space,Str "two"]]]
- ,Para [Str "Nested",Space,Str "block",Space,Str "quotes:"]
- ,BlockQuote
-  [Para [Str "nested"]]
- ,BlockQuote
-  [Para [Str "nested"]]]
-,Para [Str "This",Space,Str "should",Space,Str "not",Space,Str "be",Space,Str "a",Space,Str "block",Space,Str "quote:",Space,Str "2",Space,Str ">",Space,Str "1."]
-,Para [Str "Box-style:"]
-,BlockQuote
- [Para [Str "Example:"]
- ,CodeBlock ("",[],[]) "sub status {\n    print \"working\";\n}"]
-,BlockQuote
- [OrderedList (1,Decimal,Period)
-  [[Para [Str "do",Space,Str "laundry"]]
-  ,[Para [Str "take",Space,Str "out",Space,Str "the",Space,Str "trash"]]]]
-,Para [Str "Here\8217s",Space,Str "a",Space,Str "nested",Space,Str "one:"]
-,BlockQuote
- [Para [Str "Joe",Space,Str "said:"]
- ,BlockQuote
-  [Para [Str "Don\8217t",Space,Str "quote",Space,Str "me."]]]
-,Para [Str "And",Space,Str "a",Space,Str "following",Space,Str "paragraph."]
-,HorizontalRule
-,Header 1 ("code-blocks",[],[]) [Str "Code",Space,Str "Blocks"]
-,Para [Str "Code:"]
-,CodeBlock ("",[],[]) "---- (should be four hyphens)\n\nsub status {\n    print \"working\";\n}\n\nthis code block is indented by one tab"
-,Para [Str "And:"]
-,CodeBlock ("",[],[]) "    this code block is indented by two tabs\n\nThese should not be escaped:  \\$ \\\\ \\> \\[ \\{"
-,Para [Str "this",Space,Str "has",Space,Emph [Str "two",LineBreak,Str "lines"]]
-,HorizontalRule
-,Header 1 ("lists",[],[]) [Str "Lists"]
-,Header 2 ("unordered",[],[]) [Str "Unordered"]
-,Para [Str "Asterisks",Space,Str "tight:"]
-,BulletList
- [[Para [Str "asterisk",Space,Str "1"]]
- ,[Para [Str "asterisk",Space,Str "2"]]
- ,[Para [Str "asterisk",Space,Str "3"]]]
-,Para [Str "Asterisks",Space,Str "loose:"]
-,BulletList
- [[Para [Str "asterisk",Space,Str "1"]]
- ,[Para [Str "asterisk",Space,Str "2"]]
- ,[Para [Str "asterisk",Space,Str "3"]]]
-,Para [Str "Pluses",Space,Str "tight:"]
-,BulletList
- [[Para [Str "Plus",Space,Str "1"]]
- ,[Para [Str "Plus",Space,Str "2"]]
- ,[Para [Str "Plus",Space,Str "3"]]]
-,Para [Str "Pluses",Space,Str "loose:"]
-,BulletList
- [[Para [Str "Plus",Space,Str "1"]]
- ,[Para [Str "Plus",Space,Str "2"]]
- ,[Para [Str "Plus",Space,Str "3"]]]
-,Para [Str "Minuses",Space,Str "tight:"]
-,BulletList
- [[Para [Str "Minus",Space,Str "1"]]
- ,[Para [Str "Minus",Space,Str "2"]]
- ,[Para [Str "Minus",Space,Str "3"]]]
-,Para [Str "Minuses",Space,Str "loose:"]
-,BulletList
- [[Para [Str "Minus",Space,Str "1"]]
- ,[Para [Str "Minus",Space,Str "2"]]
- ,[Para [Str "Minus",Space,Str "3"]]]
-,Header 2 ("ordered",[],[]) [Str "Ordered"]
-,Para [Str "Tight:"]
-,OrderedList (1,Decimal,Period)
- [[Para [Str "First"]]
- ,[Para [Str "Second"]]
- ,[Para [Str "Third"]]]
-,Para [Str "and:"]
-,OrderedList (1,Decimal,Period)
- [[Para [Str "One"]]
- ,[Para [Str "Two"]]
- ,[Para [Str "Three"]]]
-,Para [Str "Loose",Space,Str "using",Space,Str "tabs:"]
-,OrderedList (1,Decimal,Period)
- [[Para [Str "First"]]
- ,[Para [Str "Second"]]
- ,[Para [Str "Third"]]]
-,Para [Str "and",Space,Str "using",Space,Str "spaces:"]
-,OrderedList (1,Decimal,Period)
- [[Para [Str "One"]]
- ,[Para [Str "Two"]]
- ,[Para [Str "Three"]]]
-,Para [Str "Multiple",Space,Str "paragraphs:"]
-,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."]]
- ,[Para [Str "Item",Space,Str "2."]]
- ,[Para [Str "Item",Space,Str "3."]]]
-,Header 2 ("nested",[],[]) [Str "Nested"]
-,BulletList
- [[Para [Str "Tab"]
-  ,BulletList
-   [[Para [Str "Tab"]
-    ,BulletList
-     [[Para [Str "Tab"]]]]]]]
-,Para [Str "Here\8217s",Space,Str "another:"]
-,OrderedList (1,Decimal,Period)
- [[Para [Str "First"]]
- ,[Para [Str "Second:"]
-  ,BulletList
-   [[Para [Str "Fee"]]
-   ,[Para [Str "Fie"]]
-   ,[Para [Str "Foe"]]]]
- ,[Para [Str "Third"]]]
-,Para [Str "Same",Space,Str "thing",Space,Str "but",Space,Str "with",Space,Str "paragraphs:"]
-,OrderedList (1,Decimal,Period)
- [[Para [Str "First"]]
- ,[Para [Str "Second:"]
-  ,BulletList
-   [[Para [Str "Fee"]]
-   ,[Para [Str "Fie"]]
-   ,[Para [Str "Foe"]]]]
- ,[Para [Str "Third"]]]
-,Header 2 ("tabs-and-spaces",[],[]) [Str "Tabs",Space,Str "and",Space,Str "spaces"]
-,BulletList
- [[Para [Str "this",Space,Str "is",Space,Str "a",Space,Str "list",Space,Str "item",Space,Str "indented",Space,Str "with",Space,Str "tabs"]]
- ,[Para [Str "this",Space,Str "is",Space,Str "a",Space,Str "list",Space,Str "item",Space,Str "indented",Space,Str "with",Space,Str "spaces"]
-  ,BulletList
-   [[Para [Str "this",Space,Str "is",Space,Str "an",Space,Str "example",Space,Str "list",Space,Str "item",Space,Str "indented",Space,Str "with",Space,Str "tabs"]]
-   ,[Para [Str "this",Space,Str "is",Space,Str "an",Space,Str "example",Space,Str "list",Space,Str "item",Space,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)
- [[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)
-   [[Para [Str "sublist",Space,Str "with",Space,Str "roman",Space,Str "numerals,",Space,Str "starting",Space,Str "with",Space,Str "4"]]
-   ,[Para [Str "more",Space,Str "items"]
-    ,OrderedList (1,UpperAlpha,TwoParens)
-     [[Para [Str "a",Space,Str "subsublist"]]
-     ,[Para [Str "a",Space,Str "subsublist"]]]]]]]
-,Para [Str "Nesting:"]
-,OrderedList (1,UpperAlpha,Period)
- [[Para [Str "Upper",Space,Str "Alpha"]
-  ,OrderedList (1,UpperRoman,Period)
-   [[Para [Str "Upper",Space,Str "Roman."]
-    ,OrderedList (6,Decimal,TwoParens)
-     [[Para [Str "Decimal",Space,Str "start",Space,Str "with",Space,Str "6"]
-      ,OrderedList (3,LowerAlpha,OneParen)
-       [[Para [Str "Lower",Space,Str "alpha",Space,Str "with",Space,Str "paren"]]]]]]]]]
-,Para [Str "Autonumbering:"]
-,OrderedList (1,DefaultStyle,DefaultDelim)
- [[Para [Str "Autonumber."]]
- ,[Para [Str "More."]
-  ,OrderedList (1,DefaultStyle,DefaultDelim)
-   [[Para [Str "Nested."]]]]]
-,Para [Str "Should",Space,Str "not",Space,Str "be",Space,Str "a",Space,Str "list",Space,Str "item:"]
-,Para [Str "M.A.",Space,Str "2007"]
-,Para [Str "B.",Space,Str "Williams"]
-,HorizontalRule
-,Header 1 ("definition-lists",[],[]) [Str "Definition",Space,Str "Lists"]
-,Para [Str "Tight",Space,Str "using",Space,Str "spaces:"]
-,DefinitionList
- [([Str "apple"],
-   [[Para [Str "red",Space,Str "fruit"]]])
- ,([Str "orange"],
-   [[Para [Str "orange",Space,Str "fruit"]]])
- ,([Str "banana"],
-   [[Para [Str "yellow",Space,Str "fruit"]]])]
-,Para [Str "Tight",Space,Str "using",Space,Str "tabs:"]
-,DefinitionList
- [([Str "apple"],
-   [[Para [Str "red",Space,Str "fruit"]]])
- ,([Str "orange"],
-   [[Para [Str "orange",Space,Str "fruit"]]])
- ,([Str "banana"],
-   [[Para [Str "yellow",Space,Str "fruit"]]])]
-,Para [Str "Loose:"]
-,DefinitionList
- [([Str "apple"],
-   [[Para [Str "red",Space,Str "fruit"]]])
- ,([Str "orange"],
-   [[Para [Str "orange",Space,Str "fruit"]]])
- ,([Str "banana"],
-   [[Para [Str "yellow",Space,Str "fruit"]]])]
-,Para [Str "Multiple",Space,Str "blocks",Space,Str "with",Space,Str "italics:"]
-,DefinitionList
- [([Emph [Str "apple"]],
-   [[Para [Str "red",Space,Str "fruit"]
-    ,Para [Str "contains",Space,Str "seeds,",Space,Str "crisp,",Space,Str "pleasant",Space,Str "to",Space,Str "taste"]]])
- ,([Emph [Str "orange"]],
-   [[Para [Str "orange",Space,Str "fruit"]
-    ,CodeBlock ("",[],[]) "{ orange code block }"
-    ,BlockQuote
-     [Para [Str "orange",Space,Str "block",Space,Str "quote"]]]])]
-,Header 1 ("html-blocks",[],[]) [Str "HTML",Space,Str "Blocks"]
-,Para [Str "Simple",Space,Str "block",Space,Str "on",Space,Str "one",Space,Str "line:"]
-,Para [Str "foo",SoftBreak,Str "And",Space,Str "nested",Space,Str "without",Space,Str "indentation:"]
-,Para [Str "foo",SoftBreak,Str "bar",SoftBreak,Str "Interpreted",Space,Str "markdown",Space,Str "in",Space,Str "a",Space,Str "table:"]
-,Para [Str "This",Space,Str "is",Space,Emph [Str "emphasized"],SoftBreak,Str "And",Space,Str "this",Space,Str "is",Space,Strong [Str "strong"],SoftBreak,Str "Here\8217s",Space,Str "a",Space,Str "simple",Space,Str "block:"]
-,Para [Str "foo",SoftBreak,Str "This",Space,Str "should",Space,Str "be",Space,Str "a",Space,Str "code",Space,Str "block,",Space,Str "though:"]
-,CodeBlock ("",[],[]) "<div>\n    foo\n</div>"
-,Para [Str "As",Space,Str "should",Space,Str "this:"]
-,CodeBlock ("",[],[]) "<div>foo</div>"
-,Para [Str "Now,",Space,Str "nested:"]
-,Para [Str "foo",SoftBreak,Str "This",Space,Str "should",Space,Str "just",Space,Str "be",Space,Str "an",Space,Str "HTML",Space,Str "comment:"]
-,Para [Str "Multiline:"]
-,Para [Str "Code",Space,Str "block:"]
-,CodeBlock ("",[],[]) "<!-- Comment -->"
-,Para [Str "Just",Space,Str "plain",Space,Str "comment,",Space,Str "with",Space,Str "trailing",Space,Str "spaces",Space,Str "on",Space,Str "the",Space,Str "line:"]
-,Para [Str "Code:"]
-,CodeBlock ("",[],[]) "<hr />"
-,Para [Str "Hr\8217s:"]
-,HorizontalRule
-,Header 1 ("inline-markup",[],[]) [Str "Inline",Space,Str "Markup"]
-,Para [Str "This",Space,Str "is",Space,Emph [Str "emphasized"],Str ",",Space,Str "and",Space,Str "so",Space,Emph [Str "is",Space,Str "this"],Str "."]
-,Para [Str "This",Space,Str "is",Space,Strong [Str "strong"],Str ",",Space,Str "and",Space,Str "so",Space,Strong [Str "is",Space,Str "this"],Str "."]
-,Para [Str "An",Space,Emph [Link ("",[],[]) [Str "emphasized",Space,Str "link"] ("/url","")],Str "."]
-,Para [Strong [Emph [Str "This",Space,Str "is",Space,Str "strong",Space,Str "and",Space,Str "em."]]]
-,Para [Str "So",Space,Str "is",Space,Strong [Emph [Str "this"]],Space,Str "word."]
-,Para [Strong [Emph [Str "This",Space,Str "is",Space,Str "strong",Space,Str "and",Space,Str "em."]]]
-,Para [Str "So",Space,Str "is",Space,Strong [Emph [Str "this"]],Space,Str "word."]
-,Para [Str "This",Space,Str "is",Space,Str "code:",Space,Code ("",[],[]) ">",Str ",",Space,Code ("",[],[]) "$",Str ",",Space,Code ("",[],[]) "\\",Str ",",Space,Code ("",[],[]) "\\$",Str ",",SoftBreak,Code ("",[],[]) "<html>",Str "."]
-,Para [Strikeout [Str "This",Space,Str "is",Space,Emph [Str "strikeout"],Str "."]]
-,Para [Str "Superscripts:",Space,Str "a",Superscript [Str "bc"],Str "d",SoftBreak,Str "a",Superscript [Emph [Str "hello"]],Space,Str "a",Superscript [Str "hello",Space,Str "there"],Str "."]
-,Para [Str "Subscripts:",Space,Str "H",Subscript [Str "2"],Str "O,",Space,Str "H",Subscript [Str "23"],Str "O,",SoftBreak,Str "H",Subscript [Str "many",Space,Str "of",Space,Str "them"],Str "O."]
-,Para [Str "These",Space,Str "should",Space,Str "not",Space,Str "be",Space,Str "superscripts",Space,Str "or",Space,Str "subscripts,",Space,Str "because",Space,Str "of",Space,Str "the",SoftBreak,Str "unescaped",Space,Str "spaces:",Space,Str "a^b",Space,Str "c^d,",Space,Str "a",Math InlineMath "\\sim",Str "b",SoftBreak,Str "c",Math InlineMath "\\sim",Str "d."]
-,HorizontalRule
-,Header 1 ("smart-quotes-ellipses-dashes",[],[]) [Str "Smart",Space,Str "quotes,",Space,Str "ellipses,",Space,Str "dashes"]
-,Para [Quoted DoubleQuote [Str "Hello,"],Space,Str "said",Space,Str "the",Space,Str "spider.",Space,Quoted DoubleQuote [Str "\8198",Quoted SingleQuote [Str "Shelob"],Space,Str "is",Space,Str "my",Space,Str "name."]]
-,Para [Quoted SingleQuote [Str "A"],Str ",",Space,Quoted SingleQuote [Str "B"],Str ",",Space,Str "and",Space,Quoted SingleQuote [Str "C"],Space,Str "are",Space,Str "letters."]
-,Para [Quoted SingleQuote [Str "Oak,"],Space,Quoted SingleQuote [Str "elm,"],Space,Str "and",Space,Quoted SingleQuote [Str "beech"],Space,Str "are",Space,Str "names",Space,Str "of",Space,Str "trees.",Space,Str "So",Space,Str "is",Space,Quoted SingleQuote [Str "pine."]]
-,Para [Quoted SingleQuote [Str "He",Space,Str "said,",Space,Quoted DoubleQuote [Str "I",Space,Str "want",Space,Str "to",Space,Str "go."],Str "\8198"],Space,Str "Were",Space,Str "you",Space,Str "alive",Space,Str "in",Space,Str "the",Space,Str "70\8217s?"]
-,Para [Str "Here",Space,Str "is",Space,Str "some",Space,Str "quoted",Space,Quoted SingleQuote [Code ("",[],[]) "code"],Space,Str "and",Space,Str "a",SoftBreak,Quoted DoubleQuote [Link ("",[],[]) [Str "quoted",Space,Str "link"] ("http://example.com/?foo=1&bar=2","")],Str "."]
-,Para [Str "Some",Space,Str "dashes:",Space,Str "one\8212two\8212three\8212four\8212five."]
-,Para [Str "Dashes",Space,Str "between",Space,Str "numbers:",Space,Str "5\8211\&7,",Space,Str "255\8211\&66,",Space,Str "1987\8211\&1999."]
-,Para [Str "Ellipses\8230and\8230and\8230."]
-,HorizontalRule
-,Header 1 ("latex",[],[]) [Str "LaTeX"]
-,BulletList
- [[Para [Cite [Citation {citationId = "smith.1899", citationPrefix = [], citationSuffix = [Str "22-23"], citationMode = NormalCitation, citationNoteNum = 0, citationHash = 0}] [RawInline (Format "latex") "\\cite[22-23]{smith.1899}"]]]
- ,[RawBlock (Format "latex") "\\doublespacing"]
- ,[Para [Math InlineMath "2+2=4"]]
- ,[Para [Math InlineMath "x \\in y"]]
- ,[Para [Math InlineMath "\\alpha \\wedge \\omega"]]
- ,[Para [Math InlineMath "223"]]
- ,[Para [Math InlineMath "p",Str "-Tree"]]
- ,[Para [Math InlineMath "\\frac{d}{dx}f(x)=\\lim_{h\\to 0}\\frac{f(x+h)-f(x)}{h}"]]
- ,[Para [Str "Here\8217s",Space,Str "one",Space,Str "that",Space,Str "has",Space,Str "a",Space,Str "line",Space,Str "break",Space,Str "in",Space,Str "it:",SoftBreak,Math InlineMath "\\alpha + \\omega \\times x^2",Str "."]]]
-,Para [Str "These",Space,Str "shouldn\8217t",Space,Str "be",Space,Str "math:"]
-,BulletList
- [[Para [Str "To",Space,Str "get",Space,Str "the",Space,Str "famous",Space,Str "equation,",Space,Str "write",Space,Code ("",[],[]) "$e = mc^2$",Str "."]]
- ,[Para [Str "$22,000",Space,Str "is",Space,Str "a",Space,Emph [Str "lot"],Space,Str "of",Space,Str "money.",Space,Str "So",Space,Str "is",Space,Str "$34,000.",Space,Str "(It",Space,Str "worked",Space,Str "if",SoftBreak,Quoted DoubleQuote [Str "lot"],Space,Str "is",Space,Str "emphasized.)"]]
- ,[Para [Str "Escaped",Space,Code ("",[],[]) "$",Str ":",Space,Str "$73",Space,Emph [Str "this",Space,Str "should",Space,Str "be",Space,Str "emphasized"],Space,Str "23$."]]]
-,Para [Str "Here\8217s",Space,Str "a",Space,Str "LaTeX",Space,Str "table:"]
-,Table [] [AlignLeft,AlignLeft] [0.0,0.0]
- [[Plain [Str "Animal"]]
- ,[Plain [Str "Number"]]]
- [[[Plain [Str "Dog"]]
-  ,[Plain [Str "2"]]]
- ,[[Plain [Str "Cat"]]
-  ,[Plain [Str "1"]]]]
-,Para [Str "A",Space,Str "table",Space,Str "with",Space,Str "one",Space,Str "column:"]
-,Table [] [AlignCenter] [0.0]
- [[]]
- [[[Plain [Str "Animal"]]]
- ,[[Plain [Str "Vegetable"]]]]
-,HorizontalRule
-,Header 1 ("special-characters",[],[]) [Str "Special",Space,Str "Characters"]
-,Para [Str "Here",Space,Str "is",Space,Str "some",Space,Str "unicode:"]
-,BulletList
- [[Para [Str "I",Space,Str "hat:",Space,Str "\206"]]
- ,[Para [Str "o",Space,Str "umlaut:",Space,Str "\246"]]
- ,[Para [Str "section:",Space,Str "\167"]]
- ,[Para [Str "set",Space,Str "membership:",Space,Str "\8712"]]
- ,[Para [Str "copyright:",Space,Str "\169"]]]
-,Para [Str "AT&T",Space,Str "has",Space,Str "an",Space,Str "ampersand",Space,Str "in",Space,Str "their",Space,Str "name."]
-,Para [Str "AT&T",Space,Str "is",Space,Str "another",Space,Str "way",Space,Str "to",Space,Str "write",Space,Str "it."]
-,Para [Str "This",Space,Str "&",Space,Str "that."]
-,Para [Str "4",Space,Str "<",Space,Str "5."]
-,Para [Str "6",Space,Str ">",Space,Str "5."]
-,Para [Str "Backslash:",Space,Str "\\"]
-,Para [Str "Backtick:",Space,Str "\8216"]
-,Para [Str "Asterisk:",Space,Str "*"]
-,Para [Str "Underscore:",Space,Str "_"]
-,Para [Str "Left",Space,Str "brace:",Space,Str "{"]
-,Para [Str "Right",Space,Str "brace:",Space,Str "}"]
-,Para [Str "Left",Space,Str "bracket:",Space,Str "["]
-,Para [Str "Right",Space,Str "bracket:",Space,Str "]"]
-,Para [Str "Left",Space,Str "paren:",Space,Str "("]
-,Para [Str "Right",Space,Str "paren:",Space,Str ")"]
-,Para [Str "Greater-than:",Space,Str ">"]
-,Para [Str "Hash:",Space,Str "#"]
-,Para [Str "Period:",Space,Str "."]
-,Para [Str "Bang:",Space,Str "!"]
-,Para [Str "Plus:",Space,Str "+"]
-,Para [Str "Minus:",Space,Str "-"]
-,HorizontalRule
-,Header 1 ("links",[],[]) [Str "Links"]
-,Header 2 ("explicit",[],[]) [Str "Explicit"]
-,Para [Str "Just",Space,Str "a",Space,Link ("",[],[]) [Str "URL"] ("/url/",""),Str "."]
-,Para [Link ("",[],[]) [Str "URL",Space,Str "and",Space,Str "title"] ("/url/",""),Str "."]
-,Para [Link ("",[],[]) [Str "URL",Space,Str "and",Space,Str "title"] ("/url/",""),Str "."]
-,Para [Link ("",[],[]) [Str "URL",Space,Str "and",Space,Str "title"] ("/url/",""),Str "."]
-,Para [Link ("",[],[]) [Str "URL",Space,Str "and",Space,Str "title"] ("/url/","")]
-,Para [Link ("",[],[]) [Str "URL",Space,Str "and",Space,Str "title"] ("/url/","")]
-,Para [Link ("",[],[]) [Str "with_underscore"] ("/url/with_underscore","")]
-,Para [Link ("",[],[]) [Str "Email",Space,Str "link"] ("mailto:nobody@nowhere.net","")]
-,Para [Link ("",[],[]) [Str "Empty"] ("",""),Str "."]
-,Header 2 ("reference",[],[]) [Str "Reference"]
-,Para [Str "Foo",Space,Link ("",[],[]) [Str "bar"] ("/url/",""),Str "."]
-,Para [Str "Foo",Space,Link ("",[],[]) [Str "bar"] ("/url/",""),Str "."]
-,Para [Str "Foo",Space,Link ("",[],[]) [Str "bar"] ("/url/",""),Str "."]
-,Para [Str "With",Space,Link ("",[],[]) [Str "embedded",Space,Str "[brackets]"] ("/url/",""),Str "."]
-,Para [Link ("",[],[]) [Str "b"] ("/url/",""),Space,Str "by",Space,Str "itself",Space,Str "should",Space,Str "be",Space,Str "a",Space,Str "link."]
-,Para [Str "Indented",Space,Link ("",[],[]) [Str "once"] ("/url",""),Str "."]
-,Para [Str "Indented",Space,Link ("",[],[]) [Str "twice"] ("/url",""),Str "."]
-,Para [Str "Indented",Space,Link ("",[],[]) [Str "thrice"] ("/url",""),Str "."]
-,Para [Str "This",Space,Str "should",Space,Str "[not][]",Space,Str "be",Space,Str "a",Space,Str "link."]
-,CodeBlock ("",[],[]) "[not]: /url"
-,Para [Str "Foo",Space,Link ("",[],[]) [Str "bar"] ("/url/",""),Str "."]
-,Para [Str "Foo",Space,Link ("",[],[]) [Str "biz"] ("/url/",""),Str "."]
-,Header 2 ("with-ampersands",[],[]) [Str "With",Space,Str "ampersands"]
-,Para [Str "Here\8217s",Space,Str "a",SoftBreak,Link ("",[],[]) [Str "link",Space,Str "with",Space,Str "an",Space,Str "ampersand",Space,Str "in",Space,Str "the",Space,Str "URL"] ("http://example.com/?foo=1&bar=2",""),Str "."]
-,Para [Str "Here\8217s",Space,Str "a",Space,Str "link",Space,Str "with",Space,Str "an",Space,Str "amersand",Space,Str "in",Space,Str "the",Space,Str "link",Space,Str "text:",SoftBreak,Link ("",[],[]) [Str "AT&T"] ("http://att.com/",""),Str "."]
-,Para [Str "Here\8217s",Space,Str "an",Space,Link ("",[],[]) [Str "inline",Space,Str "link"] ("/script?foo=1&bar=2",""),Str "."]
-,Para [Str "Here\8217s",Space,Str "an",SoftBreak,Link ("",[],[]) [Str "inline",Space,Str "link",Space,Str "in",Space,Str "pointy",Space,Str "braces"] ("/script?foo=1&bar=2",""),Str "."]
-,Header 2 ("autolinks",[],[]) [Str "Autolinks"]
-,Para [Str "With",Space,Str "an",Space,Str "ampersand:",Space,Link ("",[],[]) [Str "http://example.com/?foo=1&bar=2"] ("http://example.com/?foo=1&bar=2","")]
-,BulletList
- [[Para [Str "In",Space,Str "a",Space,Str "list?"]]
- ,[Para [Link ("",[],[]) [Str "http://example.com/"] ("http://example.com/","")]]
- ,[Para [Str "It",Space,Str "should."]]]
-,Para [Str "An",Space,Str "e-mail",Space,Str "address:",SoftBreak,Link ("",[],[]) [Str "nobody@nowhere.net"] ("mailto:nobody@nowhere.net","")]
-,BlockQuote
- [Para [Str "Blockquoted:",Space,Link ("",[],[]) [Str "http://example.com/"] ("http://example.com/","")]]
-,Para [Str "Auto-links",Space,Str "should",Space,Str "not",Space,Str "occur",Space,Str "here:",Space,Code ("",[],[]) "<http://example.com/>"]
-,CodeBlock ("",[],[]) "or here: <http://example.com/>"
-,HorizontalRule
-,Header 1 ("images",[],[]) [Str "Images"]
-,Para [Str "From",Space,Quoted DoubleQuote [Str "Voyage",Space,Str "dans",Space,Str "la",Space,Str "Lune"],Space,Str "by",Space,Str "Georges",Space,Str "Melies",Space,Str "(1902):"]
-,Para [Image ("",[],[]) [Str "image"] ("lalune.jpg","")]
-,Para [Str "Here",Space,Str "is",Space,Str "a",Space,Str "movie",Space,Image ("",[],[]) [Str "image"] ("movie.jpg",""),Space,Str "icon."]
-,HorizontalRule
-,Header 1 ("footnotes",[],[]) [Str "Footnotes"]
-,Para [Str "Here",Space,Str "is",Space,Str "a",Space,Str "footnote",SoftBreak,Str "reference,",Note [Para [Str "Here",Space,Str "is",Space,Str "the",Space,Str "footnote.",Space,Str "It",Space,Str "can",Space,Str "go",Space,Str "anywhere",Space,Str "after",Space,Str "the",Space,Str "footnote",SoftBreak,Str "reference.",Space,Str "It",Space,Str "need",Space,Str "not",Space,Str "be",Space,Str "placed",Space,Str "at",Space,Str "the",Space,Str "end",Space,Str "of",Space,Str "the",Space,Str "document."]],SoftBreak,Str "and",SoftBreak,Str "another.",Note [Para [Str "Here\8217s",Space,Str "the",Space,Str "long",Space,Str "note.",Space,Str "This",Space,Str "one",Space,Str "contains",Space,Str "multiple",Space,Str "blocks."],Para [Str "Subsequent",Space,Str "blocks",Space,Str "are",Space,Str "indented",Space,Str "to",Space,Str "show",Space,Str "that",Space,Str "they",Space,Str "belong",Space,Str "to",Space,Str "the",SoftBreak,Str "footnote",Space,Str "(as",Space,Str "with",Space,Str "list",Space,Str "items)."],CodeBlock ("",[],[]) "  { <code> }",Para [Str "If",Space,Str "you",Space,Str "want,",Space,Str "you",Space,Str "can",Space,Str "indent",Space,Str "every",Space,Str "line,",Space,Str "but",Space,Str "you",Space,Str "can",Space,Str "also",Space,Str "be",Space,Str "lazy",SoftBreak,Str "and",Space,Str "just",Space,Str "indent",Space,Str "the",Space,Str "first",Space,Str "line",Space,Str "of",Space,Str "each",Space,Str "block."]],SoftBreak,Str "This",Space,Str "should",Space,Emph [Str "not"],Space,Str "be",Space,Str "a",Space,Str "footnote",Space,Str "reference,",Space,Str "because",Space,Str "it",Space,Str "contains",SoftBreak,Str "a",Space,Str "space.[^my",Space,Str "note]",Space,Str "Here",Space,Str "is",Space,Str "an",Space,Str "inline",SoftBreak,Str "note.",Note [Para [Str "This",Space,Str "is",Space,Emph [Str "easier"],Space,Str "to",Space,Str "type.",Space,Str "Inline",Space,Str "notes",Space,Str "may",Space,Str "contain",SoftBreak,Link ("",[],[]) [Str "links"] ("http://google.com",""),Space,Str "and",Space,Code ("",[],[]) "]",Space,Str "verbatim",Space,Str "characters,",SoftBreak,Str "as",Space,Str "well",Space,Str "as",Space,Str "[bracketed",Space,Str "text]."]]]
-,BlockQuote
- [Para [Str "Notes",Space,Str "can",Space,Str "go",Space,Str "in",Space,Str "quotes.",Note [Para [Str "In",Space,Str "quote."]]]]
-,OrderedList (1,Decimal,Period)
- [[Para [Str "And",Space,Str "in",Space,Str "list",Space,Str "items.",Note [Para [Str "In",Space,Str "list."]]]]]
-,Para [Str "This",Space,Str "paragraph",Space,Str "should",Space,Str "not",Space,Str "be",Space,Str "part",Space,Str "of",Space,Str "the",Space,Str "note,",Space,Str "as",Space,Str "it",Space,Str "is",Space,Str "not",SoftBreak,Str "indented."]
-,Header 1 ("escaped-characters",[],[]) [Str "Escaped",Space,Str "characters"]
-,Para [Str "$",Space,Str "%",Space,Str "&",Space,Str "#",Space,Str "_",Space,Str "{",Space,Str "}"]]
+Pandoc
+  Meta
+    { unMeta =
+        fromList
+          [ ( "author"
+            , MetaList
+                [ MetaInlines [ Str "John" , Space , Str "MacFarlane" ]
+                , MetaInlines [ Str "Anonymous" ]
+                ]
+            )
+          , ( "date"
+            , MetaInlines
+                [ Str "July" , Space , Str "17," , Space , Str "2006" ]
+            )
+          , ( "title"
+            , MetaInlines
+                [ Str "Pandoc"
+                , Space
+                , Str "Test"
+                , Space
+                , Str "Suite"
+                ]
+            )
+          ]
+    }
+  [ RawBlock (Format "latex") "\\maketitle"
+  , Para
+      [ Str "This"
+      , Space
+      , Str "is"
+      , Space
+      , Str "a"
+      , Space
+      , Str "set"
+      , Space
+      , Str "of"
+      , Space
+      , Str "tests"
+      , Space
+      , Str "for"
+      , Space
+      , Str "pandoc."
+      , Space
+      , Str "Most"
+      , Space
+      , Str "of"
+      , Space
+      , Str "them"
+      , Space
+      , Str "are"
+      , Space
+      , Str "adapted"
+      , Space
+      , Str "from"
+      , SoftBreak
+      , Str "John"
+      , Space
+      , Str "Gruber\8217s"
+      , Space
+      , Str "markdown"
+      , Space
+      , Str "test"
+      , Space
+      , Str "suite."
+      ]
+  , Div ( "" , [ "center" ] , [] ) [ HorizontalRule ]
+  , Header 1 ( "headers" , [] , [] ) [ Str "Headers" ]
+  , Header
+      2
+      ( "level-2-with-an-embedded-link" , [] , [] )
+      [ Str "Level"
+      , Space
+      , Str "2"
+      , Space
+      , Str "with"
+      , Space
+      , Str "an"
+      , Space
+      , Link
+          ( "" , [] , [] )
+          [ Str "embedded" , Space , Str "link" ]
+          ( "/url" , "" )
+      ]
+  , Header
+      3
+      ( "level-3-with-emphasis" , [] , [] )
+      [ Str "Level"
+      , Space
+      , Str "3"
+      , Space
+      , Str "with"
+      , Space
+      , Emph [ Str "emphasis" ]
+      ]
+  , Para [ Str "Level" , Space , Str "4" ]
+  , Para [ Str "Level" , Space , Str "5" ]
+  , Header
+      1 ( "level-1" , [] , [] ) [ Str "Level" , Space , Str "1" ]
+  , Header
+      2
+      ( "level-2-with-emphasis" , [] , [] )
+      [ Str "Level"
+      , Space
+      , Str "2"
+      , Space
+      , Str "with"
+      , Space
+      , Emph [ Str "emphasis" ]
+      ]
+  , Header
+      3 ( "level-3" , [] , [] ) [ Str "Level" , Space , Str "3" ]
+  , Para
+      [ Str "with"
+      , Space
+      , Str "no"
+      , Space
+      , Str "blank"
+      , Space
+      , Str "line"
+      ]
+  , Header
+      2 ( "level-2" , [] , [] ) [ Str "Level" , Space , Str "2" ]
+  , Para
+      [ Str "with"
+      , Space
+      , Str "no"
+      , Space
+      , Str "blank"
+      , Space
+      , Str "line"
+      ]
+  , Div ( "" , [ "center" ] , [] ) [ HorizontalRule ]
+  , Header 1 ( "paragraphs" , [] , [] ) [ Str "Paragraphs" ]
+  , Para
+      [ Str "Here\8217s"
+      , Space
+      , Str "a"
+      , Space
+      , Str "regular"
+      , Space
+      , Str "paragraph."
+      ]
+  , Para
+      [ Str "In"
+      , Space
+      , Str "Markdown"
+      , Space
+      , Str "1.0.0"
+      , Space
+      , Str "and"
+      , Space
+      , Str "earlier."
+      , Space
+      , Str "Version"
+      , Space
+      , Str "8."
+      , Space
+      , Str "This"
+      , Space
+      , Str "line"
+      , Space
+      , Str "turns"
+      , Space
+      , Str "into"
+      , Space
+      , Str "a"
+      , SoftBreak
+      , Str "list"
+      , Space
+      , Str "item."
+      , Space
+      , Str "Because"
+      , Space
+      , Str "a"
+      , Space
+      , Str "hard-wrapped"
+      , Space
+      , Str "line"
+      , Space
+      , Str "in"
+      , Space
+      , Str "the"
+      , Space
+      , Str "middle"
+      , Space
+      , Str "of"
+      , Space
+      , Str "a"
+      , Space
+      , Str "paragraph"
+      , SoftBreak
+      , Str "looked"
+      , Space
+      , Str "like"
+      , Space
+      , Str "a"
+      , Space
+      , Str "list"
+      , Space
+      , Str "item."
+      ]
+  , Para
+      [ Str "Here\8217s"
+      , Space
+      , Str "one"
+      , Space
+      , Str "with"
+      , Space
+      , Str "a"
+      , Space
+      , Str "bullet."
+      , Space
+      , Str "*"
+      , Space
+      , Str "criminey."
+      ]
+  , Para
+      [ Str "There"
+      , Space
+      , Str "should"
+      , Space
+      , Str "be"
+      , Space
+      , Str "a"
+      , Space
+      , Str "hard"
+      , Space
+      , Str "line"
+      , Space
+      , Str "break"
+      , LineBreak
+      , Str "here."
+      ]
+  , Div ( "" , [ "center" ] , [] ) [ HorizontalRule ]
+  , Header
+      1
+      ( "block-quotes" , [] , [] )
+      [ Str "Block" , Space , Str "Quotes" ]
+  , Para [ Str "E-mail" , Space , Str "style:" ]
+  , BlockQuote
+      [ Para
+          [ Str "This"
+          , Space
+          , Str "is"
+          , Space
+          , Str "a"
+          , Space
+          , Str "block"
+          , Space
+          , Str "quote."
+          , Space
+          , Str "It"
+          , Space
+          , Str "is"
+          , Space
+          , Str "pretty"
+          , Space
+          , Str "short."
+          ]
+      ]
+  , BlockQuote
+      [ Para
+          [ Str "Code"
+          , Space
+          , Str "in"
+          , Space
+          , Str "a"
+          , Space
+          , Str "block"
+          , Space
+          , Str "quote:"
+          ]
+      , CodeBlock
+          ( "" , [] , [] ) "sub status {\n    print \"working\";\n}"
+      , Para [ Str "A" , Space , Str "list:" ]
+      , OrderedList
+          ( 1 , Decimal , Period )
+          [ [ Para [ Str "item" , Space , Str "one" ] ]
+          , [ Para [ Str "item" , Space , Str "two" ] ]
+          ]
+      , Para
+          [ Str "Nested"
+          , Space
+          , Str "block"
+          , Space
+          , Str "quotes:"
+          ]
+      , BlockQuote [ Para [ Str "nested" ] ]
+      , BlockQuote [ Para [ Str "nested" ] ]
+      ]
+  , Para
+      [ Str "This"
+      , Space
+      , Str "should"
+      , Space
+      , Str "not"
+      , Space
+      , Str "be"
+      , Space
+      , Str "a"
+      , Space
+      , Str "block"
+      , Space
+      , Str "quote:"
+      , Space
+      , Str "2"
+      , Space
+      , Str ">"
+      , Space
+      , Str "1."
+      ]
+  , Para [ Str "Box-style:" ]
+  , BlockQuote
+      [ Para [ Str "Example:" ]
+      , CodeBlock
+          ( "" , [] , [] ) "sub status {\n    print \"working\";\n}"
+      ]
+  , BlockQuote
+      [ OrderedList
+          ( 1 , Decimal , Period )
+          [ [ Para [ Str "do" , Space , Str "laundry" ] ]
+          , [ Para
+                [ Str "take"
+                , Space
+                , Str "out"
+                , Space
+                , Str "the"
+                , Space
+                , Str "trash"
+                ]
+            ]
+          ]
+      ]
+  , Para
+      [ Str "Here\8217s"
+      , Space
+      , Str "a"
+      , Space
+      , Str "nested"
+      , Space
+      , Str "one:"
+      ]
+  , BlockQuote
+      [ Para [ Str "Joe" , Space , Str "said:" ]
+      , BlockQuote
+          [ Para
+              [ Str "Don\8217t"
+              , Space
+              , Str "quote"
+              , Space
+              , Str "me."
+              ]
+          ]
+      ]
+  , Para
+      [ Str "And"
+      , Space
+      , Str "a"
+      , Space
+      , Str "following"
+      , Space
+      , Str "paragraph."
+      ]
+  , Div ( "" , [ "center" ] , [] ) [ HorizontalRule ]
+  , Header
+      1
+      ( "code-blocks" , [] , [] )
+      [ Str "Code" , Space , Str "Blocks" ]
+  , Para [ Str "Code:" ]
+  , CodeBlock
+      ( "" , [] , [] )
+      "---- (should be four hyphens)\n\nsub status {\n    print \"working\";\n}\n\nthis code block is indented by one tab"
+  , Para [ Str "And:" ]
+  , CodeBlock
+      ( "" , [] , [] )
+      "    this code block is indented by two tabs\n\nThese should not be escaped:  \\$ \\\\ \\> \\[ \\{"
+  , Para
+      [ Str "this"
+      , Space
+      , Str "has"
+      , Space
+      , Emph [ Str "two" , LineBreak , Str "lines" ]
+      ]
+  , Div ( "" , [ "center" ] , [] ) [ HorizontalRule ]
+  , Header 1 ( "lists" , [] , [] ) [ Str "Lists" ]
+  , Header 2 ( "unordered" , [] , [] ) [ Str "Unordered" ]
+  , Para [ Str "Asterisks" , Space , Str "tight:" ]
+  , BulletList
+      [ [ Para [ Str "asterisk" , Space , Str "1" ] ]
+      , [ Para [ Str "asterisk" , Space , Str "2" ] ]
+      , [ Para [ Str "asterisk" , Space , Str "3" ] ]
+      ]
+  , Para [ Str "Asterisks" , Space , Str "loose:" ]
+  , BulletList
+      [ [ Para [ Str "asterisk" , Space , Str "1" ] ]
+      , [ Para [ Str "asterisk" , Space , Str "2" ] ]
+      , [ Para [ Str "asterisk" , Space , Str "3" ] ]
+      ]
+  , Para [ Str "Pluses" , Space , Str "tight:" ]
+  , BulletList
+      [ [ Para [ Str "Plus" , Space , Str "1" ] ]
+      , [ Para [ Str "Plus" , Space , Str "2" ] ]
+      , [ Para [ Str "Plus" , Space , Str "3" ] ]
+      ]
+  , Para [ Str "Pluses" , Space , Str "loose:" ]
+  , BulletList
+      [ [ Para [ Str "Plus" , Space , Str "1" ] ]
+      , [ Para [ Str "Plus" , Space , Str "2" ] ]
+      , [ Para [ Str "Plus" , Space , Str "3" ] ]
+      ]
+  , Para [ Str "Minuses" , Space , Str "tight:" ]
+  , BulletList
+      [ [ Para [ Str "Minus" , Space , Str "1" ] ]
+      , [ Para [ Str "Minus" , Space , Str "2" ] ]
+      , [ Para [ Str "Minus" , Space , Str "3" ] ]
+      ]
+  , Para [ Str "Minuses" , Space , Str "loose:" ]
+  , BulletList
+      [ [ Para [ Str "Minus" , Space , Str "1" ] ]
+      , [ Para [ Str "Minus" , Space , Str "2" ] ]
+      , [ Para [ Str "Minus" , Space , Str "3" ] ]
+      ]
+  , Header 2 ( "ordered" , [] , [] ) [ Str "Ordered" ]
+  , Para [ Str "Tight:" ]
+  , OrderedList
+      ( 1 , Decimal , Period )
+      [ [ Para [ Str "First" ] ]
+      , [ Para [ Str "Second" ] ]
+      , [ Para [ Str "Third" ] ]
+      ]
+  , Para [ Str "and:" ]
+  , OrderedList
+      ( 1 , Decimal , Period )
+      [ [ Para [ Str "One" ] ]
+      , [ Para [ Str "Two" ] ]
+      , [ Para [ Str "Three" ] ]
+      ]
+  , Para
+      [ Str "Loose" , Space , Str "using" , Space , Str "tabs:" ]
+  , OrderedList
+      ( 1 , Decimal , Period )
+      [ [ Para [ Str "First" ] ]
+      , [ Para [ Str "Second" ] ]
+      , [ Para [ Str "Third" ] ]
+      ]
+  , Para
+      [ Str "and" , Space , Str "using" , Space , Str "spaces:" ]
+  , OrderedList
+      ( 1 , Decimal , Period )
+      [ [ Para [ Str "One" ] ]
+      , [ Para [ Str "Two" ] ]
+      , [ Para [ Str "Three" ] ]
+      ]
+  , Para [ Str "Multiple" , Space , Str "paragraphs:" ]
+  , 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."
+            ]
+        ]
+      , [ Para [ Str "Item" , Space , Str "2." ] ]
+      , [ Para [ Str "Item" , Space , Str "3." ] ]
+      ]
+  , Header 2 ( "nested" , [] , [] ) [ Str "Nested" ]
+  , BulletList
+      [ [ Para [ Str "Tab" ]
+        , BulletList
+            [ [ Para [ Str "Tab" ]
+              , BulletList [ [ Para [ Str "Tab" ] ] ]
+              ]
+            ]
+        ]
+      ]
+  , Para [ Str "Here\8217s" , Space , Str "another:" ]
+  , OrderedList
+      ( 1 , Decimal , Period )
+      [ [ Para [ Str "First" ] ]
+      , [ Para [ Str "Second:" ]
+        , BulletList
+            [ [ Para [ Str "Fee" ] ]
+            , [ Para [ Str "Fie" ] ]
+            , [ Para [ Str "Foe" ] ]
+            ]
+        ]
+      , [ Para [ Str "Third" ] ]
+      ]
+  , Para
+      [ Str "Same"
+      , Space
+      , Str "thing"
+      , Space
+      , Str "but"
+      , Space
+      , Str "with"
+      , Space
+      , Str "paragraphs:"
+      ]
+  , OrderedList
+      ( 1 , Decimal , Period )
+      [ [ Para [ Str "First" ] ]
+      , [ Para [ Str "Second:" ]
+        , BulletList
+            [ [ Para [ Str "Fee" ] ]
+            , [ Para [ Str "Fie" ] ]
+            , [ Para [ Str "Foe" ] ]
+            ]
+        ]
+      , [ Para [ Str "Third" ] ]
+      ]
+  , Header
+      2
+      ( "tabs-and-spaces" , [] , [] )
+      [ Str "Tabs" , Space , Str "and" , Space , Str "spaces" ]
+  , BulletList
+      [ [ Para
+            [ Str "this"
+            , Space
+            , Str "is"
+            , Space
+            , Str "a"
+            , Space
+            , Str "list"
+            , Space
+            , Str "item"
+            , Space
+            , Str "indented"
+            , Space
+            , Str "with"
+            , Space
+            , Str "tabs"
+            ]
+        ]
+      , [ Para
+            [ Str "this"
+            , Space
+            , Str "is"
+            , Space
+            , Str "a"
+            , Space
+            , Str "list"
+            , Space
+            , Str "item"
+            , Space
+            , Str "indented"
+            , Space
+            , Str "with"
+            , Space
+            , Str "spaces"
+            ]
+        , BulletList
+            [ [ Para
+                  [ Str "this"
+                  , Space
+                  , Str "is"
+                  , Space
+                  , Str "an"
+                  , Space
+                  , Str "example"
+                  , Space
+                  , Str "list"
+                  , Space
+                  , Str "item"
+                  , Space
+                  , Str "indented"
+                  , Space
+                  , Str "with"
+                  , Space
+                  , Str "tabs"
+                  ]
+              ]
+            , [ Para
+                  [ Str "this"
+                  , Space
+                  , Str "is"
+                  , Space
+                  , Str "an"
+                  , Space
+                  , Str "example"
+                  , Space
+                  , Str "list"
+                  , Space
+                  , Str "item"
+                  , Space
+                  , 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 )
+      [ [ 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 )
+            [ [ Para
+                  [ Str "sublist"
+                  , Space
+                  , Str "with"
+                  , Space
+                  , Str "roman"
+                  , Space
+                  , Str "numerals,"
+                  , Space
+                  , Str "starting"
+                  , Space
+                  , Str "with"
+                  , Space
+                  , Str "4"
+                  ]
+              ]
+            , [ Para [ Str "more" , Space , Str "items" ]
+              , OrderedList
+                  ( 1 , UpperAlpha , TwoParens )
+                  [ [ Para [ Str "a" , Space , Str "subsublist" ] ]
+                  , [ Para [ Str "a" , Space , Str "subsublist" ] ]
+                  ]
+              ]
+            ]
+        ]
+      ]
+  , Para [ Str "Nesting:" ]
+  , OrderedList
+      ( 1 , UpperAlpha , Period )
+      [ [ Para [ Str "Upper" , Space , Str "Alpha" ]
+        , OrderedList
+            ( 1 , UpperRoman , Period )
+            [ [ Para [ Str "Upper" , Space , Str "Roman." ]
+              , OrderedList
+                  ( 6 , Decimal , TwoParens )
+                  [ [ Para
+                        [ Str "Decimal"
+                        , Space
+                        , Str "start"
+                        , Space
+                        , Str "with"
+                        , Space
+                        , Str "6"
+                        ]
+                    , OrderedList
+                        ( 3 , LowerAlpha , OneParen )
+                        [ [ Para
+                              [ Str "Lower"
+                              , Space
+                              , Str "alpha"
+                              , Space
+                              , Str "with"
+                              , Space
+                              , Str "paren"
+                              ]
+                          ]
+                        ]
+                    ]
+                  ]
+              ]
+            ]
+        ]
+      ]
+  , Para [ Str "Autonumbering:" ]
+  , OrderedList
+      ( 1 , DefaultStyle , DefaultDelim )
+      [ [ Para [ Str "Autonumber." ] ]
+      , [ Para [ Str "More." ]
+        , OrderedList
+            ( 1 , DefaultStyle , DefaultDelim )
+            [ [ Para [ Str "Nested." ] ] ]
+        ]
+      ]
+  , Para
+      [ Str "Should"
+      , Space
+      , Str "not"
+      , Space
+      , Str "be"
+      , Space
+      , Str "a"
+      , Space
+      , Str "list"
+      , Space
+      , Str "item:"
+      ]
+  , Para [ Str "M.A." , Space , Str "2007" ]
+  , Para [ Str "B." , Space , Str "Williams" ]
+  , Div ( "" , [ "center" ] , [] ) [ HorizontalRule ]
+  , Header
+      1
+      ( "definition-lists" , [] , [] )
+      [ Str "Definition" , Space , Str "Lists" ]
+  , Para
+      [ Str "Tight"
+      , Space
+      , Str "using"
+      , Space
+      , Str "spaces:"
+      ]
+  , DefinitionList
+      [ ( [ Str "apple" ]
+        , [ [ Para [ Str "red" , Space , Str "fruit" ] ] ]
+        )
+      , ( [ Str "orange" ]
+        , [ [ Para [ Str "orange" , Space , Str "fruit" ] ] ]
+        )
+      , ( [ Str "banana" ]
+        , [ [ Para [ Str "yellow" , Space , Str "fruit" ] ] ]
+        )
+      ]
+  , Para
+      [ Str "Tight" , Space , Str "using" , Space , Str "tabs:" ]
+  , DefinitionList
+      [ ( [ Str "apple" ]
+        , [ [ Para [ Str "red" , Space , Str "fruit" ] ] ]
+        )
+      , ( [ Str "orange" ]
+        , [ [ Para [ Str "orange" , Space , Str "fruit" ] ] ]
+        )
+      , ( [ Str "banana" ]
+        , [ [ Para [ Str "yellow" , Space , Str "fruit" ] ] ]
+        )
+      ]
+  , Para [ Str "Loose:" ]
+  , DefinitionList
+      [ ( [ Str "apple" ]
+        , [ [ Para [ Str "red" , Space , Str "fruit" ] ] ]
+        )
+      , ( [ Str "orange" ]
+        , [ [ Para [ Str "orange" , Space , Str "fruit" ] ] ]
+        )
+      , ( [ Str "banana" ]
+        , [ [ Para [ Str "yellow" , Space , Str "fruit" ] ] ]
+        )
+      ]
+  , Para
+      [ Str "Multiple"
+      , Space
+      , Str "blocks"
+      , Space
+      , Str "with"
+      , Space
+      , Str "italics:"
+      ]
+  , DefinitionList
+      [ ( [ Emph [ Str "apple" ] ]
+        , [ [ Para [ Str "red" , Space , Str "fruit" ]
+            , Para
+                [ Str "contains"
+                , Space
+                , Str "seeds,"
+                , Space
+                , Str "crisp,"
+                , Space
+                , Str "pleasant"
+                , Space
+                , Str "to"
+                , Space
+                , Str "taste"
+                ]
+            ]
+          ]
+        )
+      , ( [ Emph [ Str "orange" ] ]
+        , [ [ Para [ Str "orange" , Space , Str "fruit" ]
+            , CodeBlock ( "" , [] , [] ) "{ orange code block }"
+            , BlockQuote
+                [ Para
+                    [ Str "orange"
+                    , Space
+                    , Str "block"
+                    , Space
+                    , Str "quote"
+                    ]
+                ]
+            ]
+          ]
+        )
+      ]
+  , Header
+      1
+      ( "html-blocks" , [] , [] )
+      [ Str "HTML" , Space , Str "Blocks" ]
+  , Para
+      [ Str "Simple"
+      , Space
+      , Str "block"
+      , Space
+      , Str "on"
+      , Space
+      , Str "one"
+      , Space
+      , Str "line:"
+      ]
+  , Para
+      [ Str "foo"
+      , SoftBreak
+      , Str "And"
+      , Space
+      , Str "nested"
+      , Space
+      , Str "without"
+      , Space
+      , Str "indentation:"
+      ]
+  , Para
+      [ Str "foo"
+      , SoftBreak
+      , Str "bar"
+      , SoftBreak
+      , Str "Interpreted"
+      , Space
+      , Str "markdown"
+      , Space
+      , Str "in"
+      , Space
+      , Str "a"
+      , Space
+      , Str "table:"
+      ]
+  , Para
+      [ Str "This"
+      , Space
+      , Str "is"
+      , Space
+      , Emph [ Str "emphasized" ]
+      , SoftBreak
+      , Str "And"
+      , Space
+      , Str "this"
+      , Space
+      , Str "is"
+      , Space
+      , Strong [ Str "strong" ]
+      , SoftBreak
+      , Str "Here\8217s"
+      , Space
+      , Str "a"
+      , Space
+      , Str "simple"
+      , Space
+      , Str "block:"
+      ]
+  , Para
+      [ Str "foo"
+      , SoftBreak
+      , Str "This"
+      , Space
+      , Str "should"
+      , Space
+      , Str "be"
+      , Space
+      , Str "a"
+      , Space
+      , Str "code"
+      , Space
+      , Str "block,"
+      , Space
+      , Str "though:"
+      ]
+  , CodeBlock ( "" , [] , [] ) "<div>\n    foo\n</div>"
+  , Para
+      [ Str "As" , Space , Str "should" , Space , Str "this:" ]
+  , CodeBlock ( "" , [] , [] ) "<div>foo</div>"
+  , Para [ Str "Now," , Space , Str "nested:" ]
+  , Para
+      [ Str "foo"
+      , SoftBreak
+      , Str "This"
+      , Space
+      , Str "should"
+      , Space
+      , Str "just"
+      , Space
+      , Str "be"
+      , Space
+      , Str "an"
+      , Space
+      , Str "HTML"
+      , Space
+      , Str "comment:"
+      ]
+  , Para [ Str "Multiline:" ]
+  , Para [ Str "Code" , Space , Str "block:" ]
+  , CodeBlock ( "" , [] , [] ) "<!-- Comment -->"
+  , Para
+      [ Str "Just"
+      , Space
+      , Str "plain"
+      , Space
+      , Str "comment,"
+      , Space
+      , Str "with"
+      , Space
+      , Str "trailing"
+      , Space
+      , Str "spaces"
+      , Space
+      , Str "on"
+      , Space
+      , Str "the"
+      , Space
+      , Str "line:"
+      ]
+  , Para [ Str "Code:" ]
+  , CodeBlock ( "" , [] , [] ) "<hr />"
+  , Para [ Str "Hr\8217s:" ]
+  , Div ( "" , [ "center" ] , [] ) [ HorizontalRule ]
+  , Header
+      1
+      ( "inline-markup" , [] , [] )
+      [ Str "Inline" , Space , Str "Markup" ]
+  , Para
+      [ Str "This"
+      , Space
+      , Str "is"
+      , Space
+      , Emph [ Str "emphasized" ]
+      , Str ","
+      , Space
+      , Str "and"
+      , Space
+      , Str "so"
+      , Space
+      , Emph [ Str "is" , Space , Str "this" ]
+      , Str "."
+      ]
+  , Para
+      [ Str "This"
+      , Space
+      , Str "is"
+      , Space
+      , Strong [ Str "strong" ]
+      , Str ","
+      , Space
+      , Str "and"
+      , Space
+      , Str "so"
+      , Space
+      , Strong [ Str "is" , Space , Str "this" ]
+      , Str "."
+      ]
+  , Para
+      [ Str "An"
+      , Space
+      , Emph
+          [ Link
+              ( "" , [] , [] )
+              [ Str "emphasized" , Space , Str "link" ]
+              ( "/url" , "" )
+          ]
+      , Str "."
+      ]
+  , Para
+      [ Strong
+          [ Emph
+              [ Str "This"
+              , Space
+              , Str "is"
+              , Space
+              , Str "strong"
+              , Space
+              , Str "and"
+              , Space
+              , Str "em."
+              ]
+          ]
+      ]
+  , Para
+      [ Str "So"
+      , Space
+      , Str "is"
+      , Space
+      , Strong [ Emph [ Str "this" ] ]
+      , Space
+      , Str "word."
+      ]
+  , Para
+      [ Strong
+          [ Emph
+              [ Str "This"
+              , Space
+              , Str "is"
+              , Space
+              , Str "strong"
+              , Space
+              , Str "and"
+              , Space
+              , Str "em."
+              ]
+          ]
+      ]
+  , Para
+      [ Str "So"
+      , Space
+      , Str "is"
+      , Space
+      , Strong [ Emph [ Str "this" ] ]
+      , Space
+      , Str "word."
+      ]
+  , Para
+      [ Str "This"
+      , Space
+      , Str "is"
+      , Space
+      , Str "code:"
+      , Space
+      , Code ( "" , [] , [] ) ">"
+      , Str ","
+      , Space
+      , Code ( "" , [] , [] ) "$"
+      , Str ","
+      , Space
+      , Code ( "" , [] , [] ) "\\"
+      , Str ","
+      , Space
+      , Code ( "" , [] , [] ) "\\$"
+      , Str ","
+      , SoftBreak
+      , Code ( "" , [] , [] ) "<html>"
+      , Str "."
+      ]
+  , Para
+      [ Strikeout
+          [ Str "This"
+          , Space
+          , Str "is"
+          , Space
+          , Emph [ Str "strikeout" ]
+          , Str "."
+          ]
+      ]
+  , Para
+      [ Str "Superscripts:"
+      , Space
+      , Str "a"
+      , Superscript [ Str "bc" ]
+      , Str "d"
+      , SoftBreak
+      , Str "a"
+      , Superscript [ Emph [ Str "hello" ] ]
+      , Space
+      , Str "a"
+      , Superscript [ Str "hello" , Space , Str "there" ]
+      , Str "."
+      ]
+  , Para
+      [ Str "Subscripts:"
+      , Space
+      , Str "H"
+      , Subscript [ Str "2" ]
+      , Str "O,"
+      , Space
+      , Str "H"
+      , Subscript [ Str "23" ]
+      , Str "O,"
+      , SoftBreak
+      , Str "H"
+      , Subscript
+          [ Str "many" , Space , Str "of" , Space , Str "them" ]
+      , Str "O."
+      ]
+  , Para
+      [ Str "These"
+      , Space
+      , Str "should"
+      , Space
+      , Str "not"
+      , Space
+      , Str "be"
+      , Space
+      , Str "superscripts"
+      , Space
+      , Str "or"
+      , Space
+      , Str "subscripts,"
+      , Space
+      , Str "because"
+      , Space
+      , Str "of"
+      , Space
+      , Str "the"
+      , SoftBreak
+      , Str "unescaped"
+      , Space
+      , Str "spaces:"
+      , Space
+      , Str "a^b"
+      , Space
+      , Str "c^d,"
+      , Space
+      , Str "a"
+      , Math InlineMath "\\sim"
+      , Str "b"
+      , SoftBreak
+      , Str "c"
+      , Math InlineMath "\\sim"
+      , Str "d."
+      ]
+  , Div ( "" , [ "center" ] , [] ) [ HorizontalRule ]
+  , Header
+      1
+      ( "smart-quotes-ellipses-dashes" , [] , [] )
+      [ Str "Smart"
+      , Space
+      , Str "quotes,"
+      , Space
+      , Str "ellipses,"
+      , Space
+      , Str "dashes"
+      ]
+  , Para
+      [ Quoted DoubleQuote [ Str "Hello," ]
+      , Space
+      , Str "said"
+      , Space
+      , Str "the"
+      , Space
+      , Str "spider."
+      , Space
+      , Quoted
+          DoubleQuote
+          [ Str "\8198"
+          , Quoted SingleQuote [ Str "Shelob" ]
+          , Space
+          , Str "is"
+          , Space
+          , Str "my"
+          , Space
+          , Str "name."
+          ]
+      ]
+  , Para
+      [ Quoted SingleQuote [ Str "A" ]
+      , Str ","
+      , Space
+      , Quoted SingleQuote [ Str "B" ]
+      , Str ","
+      , Space
+      , Str "and"
+      , Space
+      , Quoted SingleQuote [ Str "C" ]
+      , Space
+      , Str "are"
+      , Space
+      , Str "letters."
+      ]
+  , Para
+      [ Quoted SingleQuote [ Str "Oak," ]
+      , Space
+      , Quoted SingleQuote [ Str "elm," ]
+      , Space
+      , Str "and"
+      , Space
+      , Quoted SingleQuote [ Str "beech" ]
+      , Space
+      , Str "are"
+      , Space
+      , Str "names"
+      , Space
+      , Str "of"
+      , Space
+      , Str "trees."
+      , Space
+      , Str "So"
+      , Space
+      , Str "is"
+      , Space
+      , Quoted SingleQuote [ Str "pine." ]
+      ]
+  , Para
+      [ Quoted
+          SingleQuote
+          [ Str "He"
+          , Space
+          , Str "said,"
+          , Space
+          , Quoted
+              DoubleQuote
+              [ Str "I"
+              , Space
+              , Str "want"
+              , Space
+              , Str "to"
+              , Space
+              , Str "go."
+              ]
+          , Str "\8198"
+          ]
+      , Space
+      , Str "Were"
+      , Space
+      , Str "you"
+      , Space
+      , Str "alive"
+      , Space
+      , Str "in"
+      , Space
+      , Str "the"
+      , Space
+      , Str "70\8217s?"
+      ]
+  , Para
+      [ Str "Here"
+      , Space
+      , Str "is"
+      , Space
+      , Str "some"
+      , Space
+      , Str "quoted"
+      , Space
+      , Quoted SingleQuote [ Code ( "" , [] , [] ) "code" ]
+      , Space
+      , Str "and"
+      , Space
+      , Str "a"
+      , SoftBreak
+      , Quoted
+          DoubleQuote
+          [ Link
+              ( "" , [] , [] )
+              [ Str "quoted" , Space , Str "link" ]
+              ( "http://example.com/?foo=1&bar=2" , "" )
+          ]
+      , Str "."
+      ]
+  , Para
+      [ Str "Some"
+      , Space
+      , Str "dashes:"
+      , Space
+      , Str "one\8212two\8212three\8212four\8212five."
+      ]
+  , Para
+      [ Str "Dashes"
+      , Space
+      , Str "between"
+      , Space
+      , Str "numbers:"
+      , Space
+      , Str "5\8211\&7,"
+      , Space
+      , Str "255\8211\&66,"
+      , Space
+      , Str "1987\8211\&1999."
+      ]
+  , Para [ Str "Ellipses\8230and\8230and\8230." ]
+  , Div ( "" , [ "center" ] , [] ) [ HorizontalRule ]
+  , Header 1 ( "latex" , [] , [] ) [ Str "LaTeX" ]
+  , BulletList
+      [ [ Para
+            [ Cite
+                [ Citation
+                    { citationId = "smith.1899"
+                    , citationPrefix = []
+                    , citationSuffix = [ Str "22-23" ]
+                    , citationMode = NormalCitation
+                    , citationNoteNum = 0
+                    , citationHash = 0
+                    }
+                ]
+                [ RawInline (Format "latex") "\\cite[22-23]{smith.1899}"
+                ]
+            ]
+        ]
+      , [ RawBlock (Format "latex") "\\doublespacing" ]
+      , [ Para [ Math InlineMath "2+2=4" ] ]
+      , [ Para [ Math InlineMath "x \\in y" ] ]
+      , [ Para [ Math InlineMath "\\alpha \\wedge \\omega" ] ]
+      , [ Para [ Math InlineMath "223" ] ]
+      , [ Para [ Math InlineMath "p" , Str "-Tree" ] ]
+      , [ Para
+            [ Math
+                InlineMath
+                "\\frac{d}{dx}f(x)=\\lim_{h\\to 0}\\frac{f(x+h)-f(x)}{h}"
+            ]
+        ]
+      , [ Para
+            [ Str "Here\8217s"
+            , Space
+            , Str "one"
+            , Space
+            , Str "that"
+            , Space
+            , Str "has"
+            , Space
+            , Str "a"
+            , Space
+            , Str "line"
+            , Space
+            , Str "break"
+            , Space
+            , Str "in"
+            , Space
+            , Str "it:"
+            , SoftBreak
+            , Math InlineMath "\\alpha + \\omega \\times x^2"
+            , Str "."
+            ]
+        ]
+      ]
+  , Para
+      [ Str "These"
+      , Space
+      , Str "shouldn\8217t"
+      , Space
+      , Str "be"
+      , Space
+      , Str "math:"
+      ]
+  , BulletList
+      [ [ Para
+            [ Str "To"
+            , Space
+            , Str "get"
+            , Space
+            , Str "the"
+            , Space
+            , Str "famous"
+            , Space
+            , Str "equation,"
+            , Space
+            , Str "write"
+            , Space
+            , Code ( "" , [] , [] ) "$e = mc^2$"
+            , Str "."
+            ]
+        ]
+      , [ Para
+            [ Str "$22,000"
+            , Space
+            , Str "is"
+            , Space
+            , Str "a"
+            , Space
+            , Emph [ Str "lot" ]
+            , Space
+            , Str "of"
+            , Space
+            , Str "money."
+            , Space
+            , Str "So"
+            , Space
+            , Str "is"
+            , Space
+            , Str "$34,000."
+            , Space
+            , Str "(It"
+            , Space
+            , Str "worked"
+            , Space
+            , Str "if"
+            , SoftBreak
+            , Quoted DoubleQuote [ Str "lot" ]
+            , Space
+            , Str "is"
+            , Space
+            , Str "emphasized.)"
+            ]
+        ]
+      , [ Para
+            [ Str "Escaped"
+            , Space
+            , Code ( "" , [] , [] ) "$"
+            , Str ":"
+            , Space
+            , Str "$73"
+            , Space
+            , Emph
+                [ Str "this"
+                , Space
+                , Str "should"
+                , Space
+                , Str "be"
+                , Space
+                , Str "emphasized"
+                ]
+            , Space
+            , Str "23$."
+            ]
+        ]
+      ]
+  , Para
+      [ Str "Here\8217s"
+      , Space
+      , Str "a"
+      , Space
+      , Str "LaTeX"
+      , Space
+      , Str "table:"
+      ]
+  , Table
+      ( "" , [] , [] )
+      (Caption Nothing [])
+      [ ( AlignLeft , ColWidthDefault )
+      , ( AlignLeft , ColWidthDefault )
+      ]
+      (TableHead
+         ( "" , [] , [] )
+         [ Row
+             ( "" , [] , [] )
+             [ Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "Animal" ] ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "Number" ] ]
+             ]
+         ])
+      [ TableBody
+          ( "" , [] , [] )
+          (RowHeadColumns 0)
+          []
+          [ Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "Dog" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "2" ] ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "Cat" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "1" ] ]
+              ]
+          ]
+      ]
+      (TableFoot ( "" , [] , [] ) [])
+  , Para
+      [ Str "A"
+      , Space
+      , Str "table"
+      , Space
+      , Str "with"
+      , Space
+      , Str "one"
+      , Space
+      , Str "column:"
+      ]
+  , Table
+      ( "" , [] , [] )
+      (Caption Nothing [])
+      [ ( AlignCenter , ColWidthDefault ) ]
+      (TableHead ( "" , [] , [] ) [])
+      [ TableBody
+          ( "" , [] , [] )
+          (RowHeadColumns 0)
+          []
+          [ Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "Animal" ] ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "Vegetable" ] ]
+              ]
+          ]
+      ]
+      (TableFoot ( "" , [] , [] ) [])
+  , Div ( "" , [ "center" ] , [] ) [ HorizontalRule ]
+  , Header
+      1
+      ( "special-characters" , [] , [] )
+      [ Str "Special" , Space , Str "Characters" ]
+  , Para
+      [ Str "Here"
+      , Space
+      , Str "is"
+      , Space
+      , Str "some"
+      , Space
+      , Str "unicode:"
+      ]
+  , BulletList
+      [ [ Para
+            [ Str "I" , Space , Str "hat:" , Space , Str "\206" ]
+        ]
+      , [ Para
+            [ Str "o" , Space , Str "umlaut:" , Space , Str "\246" ]
+        ]
+      , [ Para [ Str "section:" , Space , Str "\167" ] ]
+      , [ Para
+            [ Str "set"
+            , Space
+            , Str "membership:"
+            , Space
+            , Str "\8712"
+            ]
+        ]
+      , [ Para [ Str "copyright:" , Space , Str "\169" ] ]
+      ]
+  , Para
+      [ Str "AT&T"
+      , Space
+      , Str "has"
+      , Space
+      , Str "an"
+      , Space
+      , Str "ampersand"
+      , Space
+      , Str "in"
+      , Space
+      , Str "their"
+      , Space
+      , Str "name."
+      ]
+  , Para
+      [ Str "AT&T"
+      , Space
+      , Str "is"
+      , Space
+      , Str "another"
+      , Space
+      , Str "way"
+      , Space
+      , Str "to"
+      , Space
+      , Str "write"
+      , Space
+      , Str "it."
+      ]
+  , Para
+      [ Str "This" , Space , Str "&" , Space , Str "that." ]
+  , Para [ Str "4" , Space , Str "<" , Space , Str "5." ]
+  , Para [ Str "6" , Space , Str ">" , Space , Str "5." ]
+  , Para [ Str "Backslash:" , Space , Str "\\" ]
+  , Para [ Str "Backtick:" , Space , Str "\8216" ]
+  , Para [ Str "Asterisk:" , Space , Str "*" ]
+  , Para [ Str "Underscore:" , Space , Str "_" ]
+  , Para
+      [ Str "Left" , Space , Str "brace:" , Space , Str "{" ]
+  , Para
+      [ Str "Right" , Space , Str "brace:" , Space , Str "}" ]
+  , Para
+      [ Str "Left" , Space , Str "bracket:" , Space , Str "[" ]
+  , Para
+      [ Str "Right" , Space , Str "bracket:" , Space , Str "]" ]
+  , Para
+      [ Str "Left" , Space , Str "paren:" , Space , Str "(" ]
+  , Para
+      [ Str "Right" , Space , Str "paren:" , Space , Str ")" ]
+  , Para [ Str "Greater-than:" , Space , Str ">" ]
+  , Para [ Str "Hash:" , Space , Str "#" ]
+  , Para [ Str "Period:" , Space , Str "." ]
+  , Para [ Str "Bang:" , Space , Str "!" ]
+  , Para [ Str "Plus:" , Space , Str "+" ]
+  , Para [ Str "Minus:" , Space , Str "-" ]
+  , Div ( "" , [ "center" ] , [] ) [ HorizontalRule ]
+  , Header 1 ( "links" , [] , [] ) [ Str "Links" ]
+  , Header 2 ( "explicit" , [] , [] ) [ Str "Explicit" ]
+  , Para
+      [ Str "Just"
+      , Space
+      , Str "a"
+      , Space
+      , Link ( "" , [] , [] ) [ Str "URL" ] ( "/url/" , "" )
+      , Str "."
+      ]
+  , Para
+      [ Link
+          ( "" , [] , [] )
+          [ Str "URL" , Space , Str "and" , Space , Str "title" ]
+          ( "/url/" , "" )
+      , Str "."
+      ]
+  , Para
+      [ Link
+          ( "" , [] , [] )
+          [ Str "URL" , Space , Str "and" , Space , Str "title" ]
+          ( "/url/" , "" )
+      , Str "."
+      ]
+  , Para
+      [ Link
+          ( "" , [] , [] )
+          [ Str "URL" , Space , Str "and" , Space , Str "title" ]
+          ( "/url/" , "" )
+      , Str "."
+      ]
+  , Para
+      [ Link
+          ( "" , [] , [] )
+          [ Str "URL" , Space , Str "and" , Space , Str "title" ]
+          ( "/url/" , "" )
+      ]
+  , Para
+      [ Link
+          ( "" , [] , [] )
+          [ Str "URL" , Space , Str "and" , Space , Str "title" ]
+          ( "/url/" , "" )
+      ]
+  , Para
+      [ Link
+          ( "" , [] , [] )
+          [ Str "with_underscore" ]
+          ( "/url/with_underscore" , "" )
+      ]
+  , Para
+      [ Link
+          ( "" , [] , [] )
+          [ Str "Email" , Space , Str "link" ]
+          ( "mailto:nobody@nowhere.net" , "" )
+      ]
+  , Para
+      [ Link ( "" , [] , [] ) [ Str "Empty" ] ( "" , "" )
+      , Str "."
+      ]
+  , Header 2 ( "reference" , [] , [] ) [ Str "Reference" ]
+  , Para
+      [ Str "Foo"
+      , Space
+      , Link ( "" , [] , [] ) [ Str "bar" ] ( "/url/" , "" )
+      , Str "."
+      ]
+  , Para
+      [ Str "Foo"
+      , Space
+      , Link ( "" , [] , [] ) [ Str "bar" ] ( "/url/" , "" )
+      , Str "."
+      ]
+  , Para
+      [ Str "Foo"
+      , Space
+      , Link ( "" , [] , [] ) [ Str "bar" ] ( "/url/" , "" )
+      , Str "."
+      ]
+  , Para
+      [ Str "With"
+      , Space
+      , Link
+          ( "" , [] , [] )
+          [ Str "embedded" , Space , Str "[brackets]" ]
+          ( "/url/" , "" )
+      , Str "."
+      ]
+  , Para
+      [ Link ( "" , [] , [] ) [ Str "b" ] ( "/url/" , "" )
+      , Space
+      , Str "by"
+      , Space
+      , Str "itself"
+      , Space
+      , Str "should"
+      , Space
+      , Str "be"
+      , Space
+      , Str "a"
+      , Space
+      , Str "link."
+      ]
+  , Para
+      [ Str "Indented"
+      , Space
+      , Link ( "" , [] , [] ) [ Str "once" ] ( "/url" , "" )
+      , Str "."
+      ]
+  , Para
+      [ Str "Indented"
+      , Space
+      , Link ( "" , [] , [] ) [ Str "twice" ] ( "/url" , "" )
+      , Str "."
+      ]
+  , Para
+      [ Str "Indented"
+      , Space
+      , Link ( "" , [] , [] ) [ Str "thrice" ] ( "/url" , "" )
+      , Str "."
+      ]
+  , Para
+      [ Str "This"
+      , Space
+      , Str "should"
+      , Space
+      , Str "[not][]"
+      , Space
+      , Str "be"
+      , Space
+      , Str "a"
+      , Space
+      , Str "link."
+      ]
+  , CodeBlock ( "" , [] , [] ) "[not]: /url"
+  , Para
+      [ Str "Foo"
+      , Space
+      , Link ( "" , [] , [] ) [ Str "bar" ] ( "/url/" , "" )
+      , Str "."
+      ]
+  , Para
+      [ Str "Foo"
+      , Space
+      , Link ( "" , [] , [] ) [ Str "biz" ] ( "/url/" , "" )
+      , Str "."
+      ]
+  , Header
+      2
+      ( "with-ampersands" , [] , [] )
+      [ Str "With" , Space , Str "ampersands" ]
+  , Para
+      [ Str "Here\8217s"
+      , Space
+      , Str "a"
+      , SoftBreak
+      , Link
+          ( "" , [] , [] )
+          [ Str "link"
+          , Space
+          , Str "with"
+          , Space
+          , Str "an"
+          , Space
+          , Str "ampersand"
+          , Space
+          , Str "in"
+          , Space
+          , Str "the"
+          , Space
+          , Str "URL"
+          ]
+          ( "http://example.com/?foo=1&bar=2" , "" )
+      , Str "."
+      ]
+  , Para
+      [ Str "Here\8217s"
+      , Space
+      , Str "a"
+      , Space
+      , Str "link"
+      , Space
+      , Str "with"
+      , Space
+      , Str "an"
+      , Space
+      , Str "amersand"
+      , Space
+      , Str "in"
+      , Space
+      , Str "the"
+      , Space
+      , Str "link"
+      , Space
+      , Str "text:"
+      , SoftBreak
+      , Link
+          ( "" , [] , [] ) [ Str "AT&T" ] ( "http://att.com/" , "" )
+      , Str "."
+      ]
+  , Para
+      [ Str "Here\8217s"
+      , Space
+      , Str "an"
+      , Space
+      , Link
+          ( "" , [] , [] )
+          [ Str "inline" , Space , Str "link" ]
+          ( "/script?foo=1&bar=2" , "" )
+      , Str "."
+      ]
+  , Para
+      [ Str "Here\8217s"
+      , Space
+      , Str "an"
+      , SoftBreak
+      , Link
+          ( "" , [] , [] )
+          [ Str "inline"
+          , Space
+          , Str "link"
+          , Space
+          , Str "in"
+          , Space
+          , Str "pointy"
+          , Space
+          , Str "braces"
+          ]
+          ( "/script?foo=1&bar=2" , "" )
+      , Str "."
+      ]
+  , Header 2 ( "autolinks" , [] , [] ) [ Str "Autolinks" ]
+  , Para
+      [ Str "With"
+      , Space
+      , Str "an"
+      , Space
+      , Str "ampersand:"
+      , Space
+      , Link
+          ( "" , [ "uri" ] , [] )
+          [ Str "http://example.com/?foo=1&bar=2" ]
+          ( "http://example.com/?foo=1&bar=2" , "" )
+      ]
+  , BulletList
+      [ [ Para
+            [ Str "In" , Space , Str "a" , Space , Str "list?" ]
+        ]
+      , [ Para
+            [ Link
+                ( "" , [ "uri" ] , [] )
+                [ Str "http://example.com/" ]
+                ( "http://example.com/" , "" )
+            ]
+        ]
+      , [ Para [ Str "It" , Space , Str "should." ] ]
+      ]
+  , Para
+      [ Str "An"
+      , Space
+      , Str "e-mail"
+      , Space
+      , Str "address:"
+      , SoftBreak
+      , Link
+          ( "" , [] , [] )
+          [ Str "nobody@nowhere.net" ]
+          ( "mailto:nobody@nowhere.net" , "" )
+      ]
+  , BlockQuote
+      [ Para
+          [ Str "Blockquoted:"
+          , Space
+          , Link
+              ( "" , [ "uri" ] , [] )
+              [ Str "http://example.com/" ]
+              ( "http://example.com/" , "" )
+          ]
+      ]
+  , Para
+      [ Str "Auto-links"
+      , Space
+      , Str "should"
+      , Space
+      , Str "not"
+      , Space
+      , Str "occur"
+      , Space
+      , Str "here:"
+      , Space
+      , Code ( "" , [] , [] ) "<http://example.com/>"
+      ]
+  , CodeBlock
+      ( "" , [] , [] ) "or here: <http://example.com/>"
+  , Div ( "" , [ "center" ] , [] ) [ HorizontalRule ]
+  , Header 1 ( "images" , [] , [] ) [ Str "Images" ]
+  , Para
+      [ Str "From"
+      , Space
+      , Quoted
+          DoubleQuote
+          [ Str "Voyage"
+          , Space
+          , Str "dans"
+          , Space
+          , Str "la"
+          , Space
+          , Str "Lune"
+          ]
+      , Space
+      , Str "by"
+      , Space
+      , Str "Georges"
+      , Space
+      , Str "Melies"
+      , Space
+      , Str "(1902):"
+      ]
+  , Para
+      [ Image
+          ( "" , [] , [] ) [ Str "image" ] ( "lalune.jpg" , "" )
+      ]
+  , Para
+      [ Str "Here"
+      , Space
+      , Str "is"
+      , Space
+      , Str "a"
+      , Space
+      , Str "movie"
+      , Space
+      , Image
+          ( "" , [] , [] ) [ Str "image" ] ( "movie.jpg" , "" )
+      , Space
+      , Str "icon."
+      ]
+  , Div ( "" , [ "center" ] , [] ) [ HorizontalRule ]
+  , Header 1 ( "footnotes" , [] , [] ) [ Str "Footnotes" ]
+  , Para
+      [ Str "Here"
+      , Space
+      , Str "is"
+      , Space
+      , Str "a"
+      , Space
+      , Str "footnote"
+      , SoftBreak
+      , Str "reference,"
+      , Note
+          [ Para
+              [ Str "Here"
+              , Space
+              , Str "is"
+              , Space
+              , Str "the"
+              , Space
+              , Str "footnote."
+              , Space
+              , Str "It"
+              , Space
+              , Str "can"
+              , Space
+              , Str "go"
+              , Space
+              , Str "anywhere"
+              , Space
+              , Str "after"
+              , Space
+              , Str "the"
+              , Space
+              , Str "footnote"
+              , SoftBreak
+              , Str "reference."
+              , Space
+              , Str "It"
+              , Space
+              , Str "need"
+              , Space
+              , Str "not"
+              , Space
+              , Str "be"
+              , Space
+              , Str "placed"
+              , Space
+              , Str "at"
+              , Space
+              , Str "the"
+              , Space
+              , Str "end"
+              , Space
+              , Str "of"
+              , Space
+              , Str "the"
+              , Space
+              , Str "document."
+              ]
+          ]
+      , SoftBreak
+      , Str "and"
+      , SoftBreak
+      , Str "another."
+      , Note
+          [ Para
+              [ Str "Here\8217s"
+              , Space
+              , Str "the"
+              , Space
+              , Str "long"
+              , Space
+              , Str "note."
+              , Space
+              , Str "This"
+              , Space
+              , Str "one"
+              , Space
+              , Str "contains"
+              , Space
+              , Str "multiple"
+              , Space
+              , Str "blocks."
+              ]
+          , Para
+              [ Str "Subsequent"
+              , Space
+              , Str "blocks"
+              , Space
+              , Str "are"
+              , Space
+              , Str "indented"
+              , Space
+              , Str "to"
+              , Space
+              , Str "show"
+              , Space
+              , Str "that"
+              , Space
+              , Str "they"
+              , Space
+              , Str "belong"
+              , Space
+              , Str "to"
+              , Space
+              , Str "the"
+              , SoftBreak
+              , Str "footnote"
+              , Space
+              , Str "(as"
+              , Space
+              , Str "with"
+              , Space
+              , Str "list"
+              , Space
+              , Str "items)."
+              ]
+          , CodeBlock ( "" , [] , [] ) "  { <code> }"
+          , Para
+              [ Str "If"
+              , Space
+              , Str "you"
+              , Space
+              , Str "want,"
+              , Space
+              , Str "you"
+              , Space
+              , Str "can"
+              , Space
+              , Str "indent"
+              , Space
+              , Str "every"
+              , Space
+              , Str "line,"
+              , Space
+              , Str "but"
+              , Space
+              , Str "you"
+              , Space
+              , Str "can"
+              , Space
+              , Str "also"
+              , Space
+              , Str "be"
+              , Space
+              , Str "lazy"
+              , SoftBreak
+              , Str "and"
+              , Space
+              , Str "just"
+              , Space
+              , Str "indent"
+              , Space
+              , Str "the"
+              , Space
+              , Str "first"
+              , Space
+              , Str "line"
+              , Space
+              , Str "of"
+              , Space
+              , Str "each"
+              , Space
+              , Str "block."
+              ]
+          ]
+      , SoftBreak
+      , Str "This"
+      , Space
+      , Str "should"
+      , Space
+      , Emph [ Str "not" ]
+      , Space
+      , Str "be"
+      , Space
+      , Str "a"
+      , Space
+      , Str "footnote"
+      , Space
+      , Str "reference,"
+      , Space
+      , Str "because"
+      , Space
+      , Str "it"
+      , Space
+      , Str "contains"
+      , SoftBreak
+      , Str "a"
+      , Space
+      , Str "space.[^my"
+      , Space
+      , Str "note]"
+      , Space
+      , Str "Here"
+      , Space
+      , Str "is"
+      , Space
+      , Str "an"
+      , Space
+      , Str "inline"
+      , SoftBreak
+      , Str "note."
+      , Note
+          [ Para
+              [ Str "This"
+              , Space
+              , Str "is"
+              , Space
+              , Emph [ Str "easier" ]
+              , Space
+              , Str "to"
+              , Space
+              , Str "type."
+              , Space
+              , Str "Inline"
+              , Space
+              , Str "notes"
+              , Space
+              , Str "may"
+              , Space
+              , Str "contain"
+              , SoftBreak
+              , Link
+                  ( "" , [] , [] )
+                  [ Str "links" ]
+                  ( "http://google.com" , "" )
+              , Space
+              , Str "and"
+              , Space
+              , Code ( "" , [] , [] ) "]"
+              , Space
+              , Str "verbatim"
+              , Space
+              , Str "characters,"
+              , SoftBreak
+              , Str "as"
+              , Space
+              , Str "well"
+              , Space
+              , Str "as"
+              , Space
+              , Str "[bracketed"
+              , Space
+              , Str "text]."
+              ]
+          ]
+      ]
+  , BlockQuote
+      [ Para
+          [ Str "Notes"
+          , Space
+          , Str "can"
+          , Space
+          , Str "go"
+          , Space
+          , Str "in"
+          , Space
+          , Str "quotes."
+          , Note [ Para [ Str "In" , Space , Str "quote." ] ]
+          ]
+      ]
+  , OrderedList
+      ( 1 , Decimal , Period )
+      [ [ Para
+            [ Str "And"
+            , Space
+            , Str "in"
+            , Space
+            , Str "list"
+            , Space
+            , Str "items."
+            , Note [ Para [ Str "In" , Space , Str "list." ] ]
+            ]
+        ]
+      ]
+  , Para
+      [ Str "This"
+      , Space
+      , Str "paragraph"
+      , Space
+      , Str "should"
+      , Space
+      , Str "not"
+      , Space
+      , Str "be"
+      , Space
+      , Str "part"
+      , Space
+      , Str "of"
+      , Space
+      , Str "the"
+      , Space
+      , Str "note,"
+      , Space
+      , Str "as"
+      , Space
+      , Str "it"
+      , Space
+      , Str "is"
+      , Space
+      , Str "not"
+      , SoftBreak
+      , Str "indented."
+      ]
+  , Header
+      1
+      ( "escaped-characters" , [] , [] )
+      [ Str "Escaped" , Space , Str "characters" ]
+  , Para
+      [ Str "$"
+      , Space
+      , Str "%"
+      , Space
+      , Str "&"
+      , Space
+      , Str "#"
+      , Space
+      , Str "_"
+      , Space
+      , Str "{"
+      , Space
+      , Str "}"
+      ]
+  ]
diff --git a/test/lhs-test-markdown.native b/test/lhs-test-markdown.native
--- a/test/lhs-test-markdown.native
+++ b/test/lhs-test-markdown.native
@@ -1,8 +1,124 @@
-[Header 1 ("lhs-test",[],[]) [Str "lhs",Space,Str "test"]
-,Para [Code ("",[],[]) "unsplit",Space,Str "is",Space,Str "an",Space,Str "arrow",Space,Str "that",Space,Str "takes",Space,Str "a",Space,Str "pair",Space,Str "of",Space,Str "values",Space,Str "and",Space,Str "combines",Space,Str "them",Space,Str "to",SoftBreak,Str "return",Space,Str "a",Space,Str "single",Space,Str "value:"]
-,CodeBlock ("",["sourceCode","literate","haskell"],[]) "unsplit :: (Arrow a) => (b -> c -> d) -> a (b, c) d\nunsplit = arr . uncurry\n          -- arr (\\op (x,y) -> x `op` y)"
-,Para [Code ("",[],[]) "(***)",Space,Str "combines",Space,Str "two",Space,Str "arrows",Space,Str "into",Space,Str "a",Space,Str "new",Space,Str "arrow",Space,Str "by",Space,Str "running",Space,Str "the",Space,Str "two",Space,Str "arrows",Space,Str "on",Space,Str "a",SoftBreak,Str "pair",Space,Str "of",Space,Str "values",Space,Str "(one",Space,Str "arrow",Space,Str "on",Space,Str "the",Space,Str "first",Space,Str "item",Space,Str "of",Space,Str "the",Space,Str "pair",Space,Str "and",Space,Str "one",Space,Str "arrow",Space,Str "on",Space,Str "the",SoftBreak,Str "second",Space,Str "item",Space,Str "of",Space,Str "the",Space,Str "pair)."]
-,CodeBlock ("",[],[]) "f *** g = first f >>> second g"
-,Para [Str "Block",Space,Str "quote:"]
-,BlockQuote
- [Para [Str "foo",Space,Str "bar"]]]
+[ Header
+    1
+    ( "lhs-test" , [] , [] )
+    [ Str "lhs" , Space , Str "test" ]
+, Para
+    [ Code ( "" , [] , [] ) "unsplit"
+    , Space
+    , Str "is"
+    , Space
+    , Str "an"
+    , Space
+    , Str "arrow"
+    , Space
+    , Str "that"
+    , Space
+    , Str "takes"
+    , Space
+    , Str "a"
+    , Space
+    , Str "pair"
+    , Space
+    , Str "of"
+    , Space
+    , Str "values"
+    , Space
+    , Str "and"
+    , Space
+    , Str "combines"
+    , Space
+    , Str "them"
+    , Space
+    , Str "to"
+    , SoftBreak
+    , Str "return"
+    , Space
+    , Str "a"
+    , Space
+    , Str "single"
+    , Space
+    , Str "value:"
+    ]
+, CodeBlock
+    ( "" , [ "haskell" , "literate" ] , [] )
+    "unsplit :: (Arrow a) => (b -> c -> d) -> a (b, c) d\nunsplit = arr . uncurry\n          -- arr (\\op (x,y) -> x `op` y)"
+, Para
+    [ Code ( "" , [] , [] ) "(***)"
+    , Space
+    , Str "combines"
+    , Space
+    , Str "two"
+    , Space
+    , Str "arrows"
+    , Space
+    , Str "into"
+    , Space
+    , Str "a"
+    , Space
+    , Str "new"
+    , Space
+    , Str "arrow"
+    , Space
+    , Str "by"
+    , Space
+    , Str "running"
+    , Space
+    , Str "the"
+    , Space
+    , Str "two"
+    , Space
+    , Str "arrows"
+    , Space
+    , Str "on"
+    , Space
+    , Str "a"
+    , SoftBreak
+    , Str "pair"
+    , Space
+    , Str "of"
+    , Space
+    , Str "values"
+    , Space
+    , Str "(one"
+    , Space
+    , Str "arrow"
+    , Space
+    , Str "on"
+    , Space
+    , Str "the"
+    , Space
+    , Str "first"
+    , Space
+    , Str "item"
+    , Space
+    , Str "of"
+    , Space
+    , Str "the"
+    , Space
+    , Str "pair"
+    , Space
+    , Str "and"
+    , Space
+    , Str "one"
+    , Space
+    , Str "arrow"
+    , Space
+    , Str "on"
+    , Space
+    , Str "the"
+    , SoftBreak
+    , Str "second"
+    , Space
+    , Str "item"
+    , Space
+    , Str "of"
+    , Space
+    , Str "the"
+    , Space
+    , Str "pair)."
+    ]
+, CodeBlock
+    ( "" , [] , [] ) "f *** g = first f >>> second g"
+, Para [ Str "Block" , Space , Str "quote:" ]
+, BlockQuote [ Para [ Str "foo" , Space , Str "bar" ] ]
+]
diff --git a/test/lhs-test.html b/test/lhs-test.html
--- a/test/lhs-test.html
+++ b/test/lhs-test.html
@@ -1,92 +1,9 @@
-<!DOCTYPE html>
-<html xmlns="http://www.w3.org/1999/xhtml" lang="" xml:lang="">
-<head>
-  <meta charset="utf-8" />
-  <meta name="generator" content="pandoc" />
-  <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes" />
-  <title>lhs-test</title>
-  <style type="text/css">
-      code{white-space: pre-wrap;}
-      span.smallcaps{font-variant: small-caps;}
-      span.underline{text-decoration: underline;}
-      div.column{display: inline-block; vertical-align: top; width: 50%;}
-  </style>
-  <style type="text/css">
-a.sourceLine { display: inline-block; line-height: 1.25; }
-a.sourceLine { pointer-events: none; color: inherit; text-decoration: inherit; }
-a.sourceLine:empty { height: 1.2em; position: absolute; }
-.sourceCode { overflow: visible; }
-code.sourceCode { white-space: pre; position: relative; }
-div.sourceCode { margin: 1em 0; }
-pre.sourceCode { margin: 0; }
-@media screen {
-div.sourceCode { overflow: auto; }
-}
-@media print {
-code.sourceCode { white-space: pre-wrap; }
-a.sourceLine { text-indent: -1em; padding-left: 1em; }
-}
-pre.numberSource a.sourceLine
-  { position: relative; }
-pre.numberSource a.sourceLine:empty
-  { position: absolute; }
-pre.numberSource a.sourceLine::before
-  { content: attr(data-line-number);
-    position: absolute; left: -5em; text-align: right; vertical-align: baseline;
-    border: none; pointer-events: all;
-    -webkit-touch-callout: none; -webkit-user-select: none;
-    -khtml-user-select: none; -moz-user-select: none;
-    -ms-user-select: none; user-select: none;
-    padding: 0 4px; width: 4em;
-    color: #aaaaaa;
-  }
-pre.numberSource { margin-left: 3em; border-left: 1px solid #aaaaaa;  padding-left: 4px; }
-div.sourceCode
-  {  }
-@media screen {
-a.sourceLine::before { text-decoration: underline; }
-}
-code span.al { color: #ff0000; font-weight: bold; } /* Alert */
-code span.an { color: #60a0b0; font-weight: bold; font-style: italic; } /* Annotation */
-code span.at { color: #7d9029; } /* Attribute */
-code span.bn { color: #40a070; } /* BaseN */
-code span.bu { } /* BuiltIn */
-code span.cf { color: #007020; font-weight: bold; } /* ControlFlow */
-code span.ch { color: #4070a0; } /* Char */
-code span.cn { color: #880000; } /* Constant */
-code span.co { color: #60a0b0; font-style: italic; } /* Comment */
-code span.cv { color: #60a0b0; font-weight: bold; font-style: italic; } /* CommentVar */
-code span.do { color: #ba2121; font-style: italic; } /* Documentation */
-code span.dt { color: #902000; } /* DataType */
-code span.dv { color: #40a070; } /* DecVal */
-code span.er { color: #ff0000; font-weight: bold; } /* Error */
-code span.ex { } /* Extension */
-code span.fl { color: #40a070; } /* Float */
-code span.fu { color: #06287e; } /* Function */
-code span.im { } /* Import */
-code span.in { color: #60a0b0; font-weight: bold; font-style: italic; } /* Information */
-code span.kw { color: #007020; font-weight: bold; } /* Keyword */
-code span.op { color: #666666; } /* Operator */
-code span.ot { color: #007020; } /* Other */
-code span.pp { color: #bc7a00; } /* Preprocessor */
-code span.sc { color: #4070a0; } /* SpecialChar */
-code span.ss { color: #bb6688; } /* SpecialString */
-code span.st { color: #4070a0; } /* String */
-code span.va { color: #19177c; } /* Variable */
-code span.vs { color: #4070a0; } /* VerbatimString */
-code span.wa { color: #60a0b0; font-weight: bold; font-style: italic; } /* Warning */
-  </style>
-  <!--[if lt IE 9]>
-    <script src="//cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.3/html5shiv-printshiv.min.js"></script>
-  <![endif]-->
-</head>
-<body>
 <h1 id="lhs-test">lhs test</h1>
 <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 literate haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb1-1" data-line-number="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" data-line-number="2">unsplit <span class="fu">=</span> arr <span class="fu">.</span> uncurry</a>
-<a class="sourceLine" id="cb1-3" data-line-number="3">          <span class="co">-- arr (\op (x,y) -&gt; x `op` y)</span></a></code></pre></div>
+<div class="sourceCode" id="cb1"><pre class="sourceCode haskell literate"><code class="sourceCode haskell"><span id="cb1-1"><a href="#cb1-1" aria-hidden="true" tabindex="-1"></a><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</span>
+<span id="cb1-2"><a href="#cb1-2" aria-hidden="true" tabindex="-1"></a>unsplit <span class="ot">=</span> arr <span class="op">.</span> <span class="fu">uncurry</span></span>
+<span id="cb1-3"><a href="#cb1-3" aria-hidden="true" tabindex="-1"></a>          <span class="co">-- arr (\op (x,y) -&gt; x `op` y)</span></span></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
 second item of the pair).</p>
@@ -95,5 +12,3 @@
 <blockquote>
 <p>foo bar</p>
 </blockquote>
-</body>
-</html>
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
@@ -1,92 +1,9 @@
-<!DOCTYPE html>
-<html xmlns="http://www.w3.org/1999/xhtml" lang="" xml:lang="">
-<head>
-  <meta charset="utf-8" />
-  <meta name="generator" content="pandoc" />
-  <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes" />
-  <title>lhs-test</title>
-  <style type="text/css">
-      code{white-space: pre-wrap;}
-      span.smallcaps{font-variant: small-caps;}
-      span.underline{text-decoration: underline;}
-      div.column{display: inline-block; vertical-align: top; width: 50%;}
-  </style>
-  <style type="text/css">
-a.sourceLine { display: inline-block; line-height: 1.25; }
-a.sourceLine { pointer-events: none; color: inherit; text-decoration: inherit; }
-a.sourceLine:empty { height: 1.2em; position: absolute; }
-.sourceCode { overflow: visible; }
-code.sourceCode { white-space: pre; position: relative; }
-div.sourceCode { margin: 1em 0; }
-pre.sourceCode { margin: 0; }
-@media screen {
-div.sourceCode { overflow: auto; }
-}
-@media print {
-code.sourceCode { white-space: pre-wrap; }
-a.sourceLine { text-indent: -1em; padding-left: 1em; }
-}
-pre.numberSource a.sourceLine
-  { position: relative; }
-pre.numberSource a.sourceLine:empty
-  { position: absolute; }
-pre.numberSource a.sourceLine::before
-  { content: attr(data-line-number);
-    position: absolute; left: -5em; text-align: right; vertical-align: baseline;
-    border: none; pointer-events: all;
-    -webkit-touch-callout: none; -webkit-user-select: none;
-    -khtml-user-select: none; -moz-user-select: none;
-    -ms-user-select: none; user-select: none;
-    padding: 0 4px; width: 4em;
-    color: #aaaaaa;
-  }
-pre.numberSource { margin-left: 3em; border-left: 1px solid #aaaaaa;  padding-left: 4px; }
-div.sourceCode
-  {  }
-@media screen {
-a.sourceLine::before { text-decoration: underline; }
-}
-code span.al { color: #ff0000; font-weight: bold; } /* Alert */
-code span.an { color: #60a0b0; font-weight: bold; font-style: italic; } /* Annotation */
-code span.at { color: #7d9029; } /* Attribute */
-code span.bn { color: #40a070; } /* BaseN */
-code span.bu { } /* BuiltIn */
-code span.cf { color: #007020; font-weight: bold; } /* ControlFlow */
-code span.ch { color: #4070a0; } /* Char */
-code span.cn { color: #880000; } /* Constant */
-code span.co { color: #60a0b0; font-style: italic; } /* Comment */
-code span.cv { color: #60a0b0; font-weight: bold; font-style: italic; } /* CommentVar */
-code span.do { color: #ba2121; font-style: italic; } /* Documentation */
-code span.dt { color: #902000; } /* DataType */
-code span.dv { color: #40a070; } /* DecVal */
-code span.er { color: #ff0000; font-weight: bold; } /* Error */
-code span.ex { } /* Extension */
-code span.fl { color: #40a070; } /* Float */
-code span.fu { color: #06287e; } /* Function */
-code span.im { } /* Import */
-code span.in { color: #60a0b0; font-weight: bold; font-style: italic; } /* Information */
-code span.kw { color: #007020; font-weight: bold; } /* Keyword */
-code span.op { color: #666666; } /* Operator */
-code span.ot { color: #007020; } /* Other */
-code span.pp { color: #bc7a00; } /* Preprocessor */
-code span.sc { color: #4070a0; } /* SpecialChar */
-code span.ss { color: #bb6688; } /* SpecialString */
-code span.st { color: #4070a0; } /* String */
-code span.va { color: #19177c; } /* Variable */
-code span.vs { color: #4070a0; } /* VerbatimString */
-code span.wa { color: #60a0b0; font-weight: bold; font-style: italic; } /* Warning */
-  </style>
-  <!--[if lt IE 9]>
-    <script src="//cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.3/html5shiv-printshiv.min.js"></script>
-  <![endif]-->
-</head>
-<body>
 <h1 id="lhs-test">lhs test</h1>
 <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 literate literatehaskell"><code class="sourceCode literatehaskell"><a class="sourceLine" id="cb1-1" data-line-number="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" data-line-number="2"><span class="ot">&gt;</span> unsplit <span class="fu">=</span> arr <span class="fu">.</span> uncurry</a>
-<a class="sourceLine" id="cb1-3" data-line-number="3"><span class="ot">&gt;</span>           <span class="co">-- arr (\op (x,y) -&gt; x `op` y)</span></a></code></pre></div>
+<div class="sourceCode" id="cb1"><pre class="sourceCode literatehaskell literate"><code class="sourceCode literatehaskell"><span id="cb1-1"><a href="#cb1-1" aria-hidden="true" tabindex="-1"></a><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</span>
+<span id="cb1-2"><a href="#cb1-2" aria-hidden="true" tabindex="-1"></a><span class="ot">&gt;</span> unsplit <span class="ot">=</span> arr <span class="op">.</span> <span class="fu">uncurry</span></span>
+<span id="cb1-3"><a href="#cb1-3" aria-hidden="true" tabindex="-1"></a><span class="ot">&gt;</span>           <span class="co">-- arr (\op (x,y) -&gt; x `op` y)</span></span></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
 second item of the pair).</p>
@@ -95,5 +12,3 @@
 <blockquote>
 <p>foo bar</p>
 </blockquote>
-</body>
-</html>
diff --git a/test/lhs-test.latex b/test/lhs-test.latex
--- a/test/lhs-test.latex
+++ b/test/lhs-test.latex
@@ -1,110 +1,13 @@
-\PassOptionsToPackage{unicode=true}{hyperref} % options for packages loaded elsewhere
-\PassOptionsToPackage{hyphens}{url}
-%
-\documentclass[]{article}
-\usepackage{lmodern}
-\usepackage{amssymb,amsmath}
-\usepackage{ifxetex,ifluatex}
-\usepackage{fixltx2e} % provides \textsubscript
-\ifnum 0\ifxetex 1\fi\ifluatex 1\fi=0 % if pdftex
-  \usepackage[T1]{fontenc}
-  \usepackage[utf8]{inputenc}
-  \usepackage{textcomp} % provides euro and other symbols
-\else % if luatex or xelatex
-  \usepackage{unicode-math}
-  \defaultfontfeatures{Ligatures=TeX,Scale=MatchLowercase}
-\fi
-% use upquote if available, for straight quotes in verbatim environments
-\IfFileExists{upquote.sty}{\usepackage{upquote}}{}
-% use microtype if available
-\IfFileExists{microtype.sty}{%
-\usepackage[]{microtype}
-\UseMicrotypeSet[protrusion]{basicmath} % disable protrusion for tt fonts
-}{}
-\IfFileExists{parskip.sty}{%
-\usepackage{parskip}
-}{% else
-\setlength{\parindent}{0pt}
-\setlength{\parskip}{6pt plus 2pt minus 1pt}
-}
-\usepackage{hyperref}
-\hypersetup{
-            pdfborder={0 0 0},
-            breaklinks=true}
-\urlstyle{same}  % don't use monospace font for urls
-\usepackage{color}
-\usepackage{fancyvrb}
-\newcommand{\VerbBar}{|}
-\newcommand{\VERB}{\Verb[commandchars=\\\{\}]}
-\DefineVerbatimEnvironment{Highlighting}{Verbatim}{commandchars=\\\{\}}
-% Add ',fontsize=\small' for more characters per line
-\newenvironment{Shaded}{}{}
-\newcommand{\AlertTok}[1]{\textcolor[rgb]{1.00,0.00,0.00}{\textbf{#1}}}
-\newcommand{\AnnotationTok}[1]{\textcolor[rgb]{0.38,0.63,0.69}{\textbf{\textit{#1}}}}
-\newcommand{\AttributeTok}[1]{\textcolor[rgb]{0.49,0.56,0.16}{#1}}
-\newcommand{\BaseNTok}[1]{\textcolor[rgb]{0.25,0.63,0.44}{#1}}
-\newcommand{\BuiltInTok}[1]{#1}
-\newcommand{\CharTok}[1]{\textcolor[rgb]{0.25,0.44,0.63}{#1}}
-\newcommand{\CommentTok}[1]{\textcolor[rgb]{0.38,0.63,0.69}{\textit{#1}}}
-\newcommand{\CommentVarTok}[1]{\textcolor[rgb]{0.38,0.63,0.69}{\textbf{\textit{#1}}}}
-\newcommand{\ConstantTok}[1]{\textcolor[rgb]{0.53,0.00,0.00}{#1}}
-\newcommand{\ControlFlowTok}[1]{\textcolor[rgb]{0.00,0.44,0.13}{\textbf{#1}}}
-\newcommand{\DataTypeTok}[1]{\textcolor[rgb]{0.56,0.13,0.00}{#1}}
-\newcommand{\DecValTok}[1]{\textcolor[rgb]{0.25,0.63,0.44}{#1}}
-\newcommand{\DocumentationTok}[1]{\textcolor[rgb]{0.73,0.13,0.13}{\textit{#1}}}
-\newcommand{\ErrorTok}[1]{\textcolor[rgb]{1.00,0.00,0.00}{\textbf{#1}}}
-\newcommand{\ExtensionTok}[1]{#1}
-\newcommand{\FloatTok}[1]{\textcolor[rgb]{0.25,0.63,0.44}{#1}}
-\newcommand{\FunctionTok}[1]{\textcolor[rgb]{0.02,0.16,0.49}{#1}}
-\newcommand{\ImportTok}[1]{#1}
-\newcommand{\InformationTok}[1]{\textcolor[rgb]{0.38,0.63,0.69}{\textbf{\textit{#1}}}}
-\newcommand{\KeywordTok}[1]{\textcolor[rgb]{0.00,0.44,0.13}{\textbf{#1}}}
-\newcommand{\NormalTok}[1]{#1}
-\newcommand{\OperatorTok}[1]{\textcolor[rgb]{0.40,0.40,0.40}{#1}}
-\newcommand{\OtherTok}[1]{\textcolor[rgb]{0.00,0.44,0.13}{#1}}
-\newcommand{\PreprocessorTok}[1]{\textcolor[rgb]{0.74,0.48,0.00}{#1}}
-\newcommand{\RegionMarkerTok}[1]{#1}
-\newcommand{\SpecialCharTok}[1]{\textcolor[rgb]{0.25,0.44,0.63}{#1}}
-\newcommand{\SpecialStringTok}[1]{\textcolor[rgb]{0.73,0.40,0.53}{#1}}
-\newcommand{\StringTok}[1]{\textcolor[rgb]{0.25,0.44,0.63}{#1}}
-\newcommand{\VariableTok}[1]{\textcolor[rgb]{0.10,0.09,0.49}{#1}}
-\newcommand{\VerbatimStringTok}[1]{\textcolor[rgb]{0.25,0.44,0.63}{#1}}
-\newcommand{\WarningTok}[1]{\textcolor[rgb]{0.38,0.63,0.69}{\textbf{\textit{#1}}}}
-\setlength{\emergencystretch}{3em}  % prevent overfull lines
-\providecommand{\tightlist}{%
-  \setlength{\itemsep}{0pt}\setlength{\parskip}{0pt}}
-\setcounter{secnumdepth}{0}
-% Redefines (sub)paragraphs to behave more like sections
-\ifx\paragraph\undefined\else
-\let\oldparagraph\paragraph
-\renewcommand{\paragraph}[1]{\oldparagraph{#1}\mbox{}}
-\fi
-\ifx\subparagraph\undefined\else
-\let\oldsubparagraph\subparagraph
-\renewcommand{\subparagraph}[1]{\oldsubparagraph{#1}\mbox{}}
-\fi
-
-% set default figure placement to htbp
-\makeatletter
-\def\fps@figure{htbp}
-\makeatother
-
-
-\date{}
-
-\begin{document}
-
-\hypertarget{lhs-test}{%
-\section{lhs test}\label{lhs-test}}
+\section{lhs test}\label{lhs-test}
 
 \texttt{unsplit} is an arrow that takes a pair of values and combines them to
 return a single value:
 
 \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{.}\NormalTok{ uncurry}
-          \CommentTok{-- arr (\textbackslash{}op (x,y) -> x `op` y)}
+\OtherTok{unsplit ::}\NormalTok{ (}\DataTypeTok{Arrow}\NormalTok{ a) }\OtherTok{=\textgreater{}}\NormalTok{ (b }\OtherTok{{-}\textgreater{}}\NormalTok{ c }\OtherTok{{-}\textgreater{}}\NormalTok{ d) }\OtherTok{{-}\textgreater{}}\NormalTok{ a (b, c) d}
+\NormalTok{unsplit }\OtherTok{=}\NormalTok{ arr }\OperatorTok{.} \FunctionTok{uncurry}
+          \CommentTok{{-}{-} arr (\textbackslash{}op (x,y) {-}\textgreater{} x \textasciigrave{}op\textasciigrave{} y)}
 \end{Highlighting}
 \end{Shaded}
 
@@ -121,5 +24,3 @@
 \begin{quote}
 foo bar
 \end{quote}
-
-\end{document}
diff --git a/test/lhs-test.latex+lhs b/test/lhs-test.latex+lhs
--- a/test/lhs-test.latex+lhs
+++ b/test/lhs-test.latex+lhs
@@ -1,66 +1,4 @@
-\PassOptionsToPackage{unicode=true}{hyperref} % options for packages loaded elsewhere
-\PassOptionsToPackage{hyphens}{url}
-%
-\documentclass[]{article}
-\usepackage{lmodern}
-\usepackage{amssymb,amsmath}
-\usepackage{ifxetex,ifluatex}
-\usepackage{fixltx2e} % provides \textsubscript
-\ifnum 0\ifxetex 1\fi\ifluatex 1\fi=0 % if pdftex
-  \usepackage[T1]{fontenc}
-  \usepackage[utf8]{inputenc}
-  \usepackage{textcomp} % provides euro and other symbols
-\else % if luatex or xelatex
-  \usepackage{unicode-math}
-  \defaultfontfeatures{Ligatures=TeX,Scale=MatchLowercase}
-\fi
-% use upquote if available, for straight quotes in verbatim environments
-\IfFileExists{upquote.sty}{\usepackage{upquote}}{}
-% use microtype if available
-\IfFileExists{microtype.sty}{%
-\usepackage[]{microtype}
-\UseMicrotypeSet[protrusion]{basicmath} % disable protrusion for tt fonts
-}{}
-\IfFileExists{parskip.sty}{%
-\usepackage{parskip}
-}{% else
-\setlength{\parindent}{0pt}
-\setlength{\parskip}{6pt plus 2pt minus 1pt}
-}
-\usepackage{hyperref}
-\hypersetup{
-            pdfborder={0 0 0},
-            breaklinks=true}
-\urlstyle{same}  % don't use monospace font for urls
-\usepackage{listings}
-\newcommand{\passthrough}[1]{#1}
-\lstnewenvironment{code}{\lstset{language=Haskell,basicstyle=\small\ttfamily}}{}
-\setlength{\emergencystretch}{3em}  % prevent overfull lines
-\providecommand{\tightlist}{%
-  \setlength{\itemsep}{0pt}\setlength{\parskip}{0pt}}
-\setcounter{secnumdepth}{0}
-% Redefines (sub)paragraphs to behave more like sections
-\ifx\paragraph\undefined\else
-\let\oldparagraph\paragraph
-\renewcommand{\paragraph}[1]{\oldparagraph{#1}\mbox{}}
-\fi
-\ifx\subparagraph\undefined\else
-\let\oldsubparagraph\subparagraph
-\renewcommand{\subparagraph}[1]{\oldsubparagraph{#1}\mbox{}}
-\fi
-
-% set default figure placement to htbp
-\makeatletter
-\def\fps@figure{htbp}
-\makeatother
-
-
-\date{}
-
-\begin{document}
-
-\hypertarget{lhs-test}{%
-\section{lhs test}\label{lhs-test}}
+\section{lhs test}\label{lhs-test}
 
 \texttt{unsplit} is an arrow that takes a pair of values and combines them to
 return a single value:
@@ -84,5 +22,3 @@
 \begin{quote}
 foo bar
 \end{quote}
-
-\end{document}
diff --git a/test/lhs-test.markdown b/test/lhs-test.markdown
--- a/test/lhs-test.markdown
+++ b/test/lhs-test.markdown
@@ -4,7 +4,7 @@
 `unsplit` is an arrow that takes a pair of values and combines them to
 return a single value:
 
-``` {.sourceCode .literate .haskell}
+``` {.haskell .literate}
 unsplit :: (Arrow a) => (b -> c -> d) -> a (b, c) d
 unsplit = arr . uncurry
           -- arr (\op (x,y) -> x `op` y)
diff --git a/test/lhs-test.native b/test/lhs-test.native
--- a/test/lhs-test.native
+++ b/test/lhs-test.native
@@ -1,8 +1,124 @@
-[Header 1 ("lhs-test",[],[]) [Str "lhs",Space,Str "test"]
-,Para [Code ("",[],[]) "unsplit",Space,Str "is",Space,Str "an",Space,Str "arrow",Space,Str "that",Space,Str "takes",Space,Str "a",Space,Str "pair",Space,Str "of",Space,Str "values",Space,Str "and",Space,Str "combines",Space,Str "them",Space,Str "to",SoftBreak,Str "return",Space,Str "a",Space,Str "single",Space,Str "value:"]
-,CodeBlock ("",["sourceCode","literate","haskell"],[]) "unsplit :: (Arrow a) => (b -> c -> d) -> a (b, c) d\nunsplit = arr . uncurry\n          -- arr (\\op (x,y) -> x `op` y)"
-,Para [Code ("",[],[]) "(***)",Space,Str "combines",Space,Str "two",Space,Str "arrows",Space,Str "into",Space,Str "a",Space,Str "new",Space,Str "arrow",Space,Str "by",Space,Str "running",Space,Str "the",Space,Str "two",Space,Str "arrows",Space,Str "on",Space,Str "a",SoftBreak,Str "pair",Space,Str "of",Space,Str "values",Space,Str "(one",Space,Str "arrow",Space,Str "on",Space,Str "the",Space,Str "first",Space,Str "item",Space,Str "of",Space,Str "the",Space,Str "pair",Space,Str "and",Space,Str "one",Space,Str "arrow",Space,Str "on",Space,Str "the",SoftBreak,Str "second",Space,Str "item",Space,Str "of",Space,Str "the",Space,Str "pair)."]
-,CodeBlock ("",[],[]) "f *** g = first f >>> second g"
-,Para [Str "Block",Space,Str "quote:"]
-,BlockQuote
- [Para [Str "foo",Space,Str "bar"]]]
+[ Header
+    1
+    ( "lhs-test" , [] , [] )
+    [ Str "lhs" , Space , Str "test" ]
+, Para
+    [ Code ( "" , [] , [] ) "unsplit"
+    , Space
+    , Str "is"
+    , Space
+    , Str "an"
+    , Space
+    , Str "arrow"
+    , Space
+    , Str "that"
+    , Space
+    , Str "takes"
+    , Space
+    , Str "a"
+    , Space
+    , Str "pair"
+    , Space
+    , Str "of"
+    , Space
+    , Str "values"
+    , Space
+    , Str "and"
+    , Space
+    , Str "combines"
+    , Space
+    , Str "them"
+    , Space
+    , Str "to"
+    , SoftBreak
+    , Str "return"
+    , Space
+    , Str "a"
+    , Space
+    , Str "single"
+    , Space
+    , Str "value:"
+    ]
+, CodeBlock
+    ( "" , [ "haskell" , "literate" ] , [] )
+    "unsplit :: (Arrow a) => (b -> c -> d) -> a (b, c) d\nunsplit = arr . uncurry\n          -- arr (\\op (x,y) -> x `op` y)"
+, Para
+    [ Code ( "" , [] , [] ) "(***)"
+    , Space
+    , Str "combines"
+    , Space
+    , Str "two"
+    , Space
+    , Str "arrows"
+    , Space
+    , Str "into"
+    , Space
+    , Str "a"
+    , Space
+    , Str "new"
+    , Space
+    , Str "arrow"
+    , Space
+    , Str "by"
+    , Space
+    , Str "running"
+    , Space
+    , Str "the"
+    , Space
+    , Str "two"
+    , Space
+    , Str "arrows"
+    , Space
+    , Str "on"
+    , Space
+    , Str "a"
+    , SoftBreak
+    , Str "pair"
+    , Space
+    , Str "of"
+    , Space
+    , Str "values"
+    , Space
+    , Str "(one"
+    , Space
+    , Str "arrow"
+    , Space
+    , Str "on"
+    , Space
+    , Str "the"
+    , Space
+    , Str "first"
+    , Space
+    , Str "item"
+    , Space
+    , Str "of"
+    , Space
+    , Str "the"
+    , Space
+    , Str "pair"
+    , Space
+    , Str "and"
+    , Space
+    , Str "one"
+    , Space
+    , Str "arrow"
+    , Space
+    , Str "on"
+    , Space
+    , Str "the"
+    , SoftBreak
+    , Str "second"
+    , Space
+    , Str "item"
+    , Space
+    , Str "of"
+    , Space
+    , Str "the"
+    , Space
+    , Str "pair)."
+    ]
+, CodeBlock
+    ( "" , [] , [] ) "f *** g = first f >>> second g"
+, Para [ Str "Block" , Space , Str "quote:" ]
+, BlockQuote [ Para [ Str "foo" , Space , Str "bar" ] ]
+]
diff --git a/test/lhs-test.rst b/test/lhs-test.rst
--- a/test/lhs-test.rst
+++ b/test/lhs-test.rst
@@ -6,9 +6,9 @@
 
 .. code:: haskell
 
-    unsplit :: (Arrow a) => (b -> c -> d) -> a (b, c) d
-    unsplit = arr . uncurry
-              -- arr (\op (x,y) -> x `op` y)
+   unsplit :: (Arrow a) => (b -> c -> d) -> a (b, c) d
+   unsplit = arr . uncurry
+             -- arr (\op (x,y) -> x `op` y)
 
 ``(***)`` combines two arrows into a new arrow by running the two arrows on a
 pair of values (one arrow on the first item of the pair and one arrow on the
@@ -16,8 +16,8 @@
 
 ::
 
-    f *** g = first f >>> second g
+   f *** g = first f >>> second g
 
 Block quote:
 
-    foo bar
+   foo bar
diff --git a/test/lhs-test.rst+lhs b/test/lhs-test.rst+lhs
--- a/test/lhs-test.rst+lhs
+++ b/test/lhs-test.rst+lhs
@@ -14,8 +14,8 @@
 
 ::
 
-    f *** g = first f >>> second g
+   f *** g = first f >>> second g
 
 Block quote:
 
-    foo bar
+   foo bar
diff --git a/test/lua/attr-test.lua b/test/lua/attr-test.lua
deleted file mode 100644
--- a/test/lua/attr-test.lua
+++ /dev/null
@@ -1,6 +0,0 @@
-function Div (div)
-  div.attributes.five = ("%d"):format(div.attributes.two + div.attributes.three)
-  div.attributes.two = nil
-  div.attributes.one = "eins"
-  return div
-end
diff --git a/test/lua/block-count.lua b/test/lua/block-count.lua
deleted file mode 100644
--- a/test/lua/block-count.lua
+++ /dev/null
@@ -1,11 +0,0 @@
-local num_blocks = 0
-
-function Block(el)
-  num_blocks = num_blocks + 1
-end
-
-function Pandoc(blocks, meta)
-  return pandoc.Pandoc {
-    pandoc.Para{pandoc.Str(num_blocks)}
-  }
-end
diff --git a/test/lua/hello-world-doc.lua b/test/lua/hello-world-doc.lua
deleted file mode 100644
--- a/test/lua/hello-world-doc.lua
+++ /dev/null
@@ -1,10 +0,0 @@
-return {
-  {
-    Pandoc = function(doc)
-      local meta = {}
-      local hello = { pandoc.Str "Hello,", pandoc.Space(), pandoc.Str "World!" }
-      local blocks = { pandoc.Para(hello) }
-      return pandoc.Pandoc(blocks, meta)
-    end
-  }
-}
diff --git a/test/lua/implicit-doc-filter.lua b/test/lua/implicit-doc-filter.lua
deleted file mode 100644
--- a/test/lua/implicit-doc-filter.lua
+++ /dev/null
@@ -1,6 +0,0 @@
-function Doc (doc)
-  local meta = {}
-  local hello = { pandoc.Str "Hello,", pandoc.Space(), pandoc.Str "World!" }
-  local blocks = { pandoc.Para(hello) }
-  return pandoc.Pandoc(blocks, meta)
-end
diff --git a/test/lua/markdown-reader.lua b/test/lua/markdown-reader.lua
deleted file mode 100644
--- a/test/lua/markdown-reader.lua
+++ /dev/null
@@ -1,12 +0,0 @@
-return {
-  {
-    RawBlock = function (elem)
-      if elem.format == "markdown" then
-        local pd = pandoc.read(elem.text, "markdown")
-        return pd.blocks[1]
-      else
-        return elem
-      end
-    end,
-  }
-}
diff --git a/test/lua/metatable-catch-all.lua b/test/lua/metatable-catch-all.lua
deleted file mode 100644
--- a/test/lua/metatable-catch-all.lua
+++ /dev/null
@@ -1,20 +0,0 @@
-local num_inlines = 0
-
-function catch_all(el)
-  if el.tag and pandoc.Inline.constructor[el.tag] then
-    num_inlines = num_inlines + 1
-  end
-end
-
-function Pandoc(blocks, meta)
-  return pandoc.Pandoc {
-    pandoc.Para{pandoc.Str(num_inlines)}
-  }
-end
-
-return {
-  setmetatable(
-    {Pandoc = Pandoc},
-    {__index = function(_) return catch_all end}
-  )
-}
diff --git a/test/lua/plain-to-para.lua b/test/lua/plain-to-para.lua
deleted file mode 100644
--- a/test/lua/plain-to-para.lua
+++ /dev/null
@@ -1,6 +0,0 @@
-return {
-  { Plain = function (elem)
-      return pandoc.Para(elem.content)
-  end,
-  }
-}
diff --git a/test/lua/single-to-double-quoted.lua b/test/lua/single-to-double-quoted.lua
deleted file mode 100644
--- a/test/lua/single-to-double-quoted.lua
+++ /dev/null
@@ -1,10 +0,0 @@
-return {
-  {
-    Quoted = function (elem)
-      if elem.quotetype == "SingleQuote" then
-        elem.quotetype = "DoubleQuote"
-      end
-      return elem
-    end,
-  }
-}
diff --git a/test/lua/smallcaps-title.lua b/test/lua/smallcaps-title.lua
deleted file mode 100644
--- a/test/lua/smallcaps-title.lua
+++ /dev/null
@@ -1,12 +0,0 @@
-return {
-  {
-    Meta = function(meta)
-      -- The call to `MetaInlines` is redundant and used for testing purposes
-      -- only. The explicit use of a MetaValue constructor is only useful when
-      -- used with an empty table: `MetaInlines{}` is read differently than
-      -- `MetaBlocks{}`.
-      meta.title = pandoc.MetaInlines{pandoc.SmallCaps(meta.title)}
-      return meta
-    end
-  }
-}
diff --git a/test/lua/strmacro.lua b/test/lua/strmacro.lua
deleted file mode 100644
--- a/test/lua/strmacro.lua
+++ /dev/null
@@ -1,11 +0,0 @@
-return {
-  {
-    Str = function (elem)
-      if elem.text == "{{helloworld}}" then
-        return pandoc.Emph {pandoc.Str "Hello, World"}
-      else
-        return elem
-      end
-    end,
-  }
-}
diff --git a/test/lua/test-pandoc-utils.lua b/test/lua/test-pandoc-utils.lua
deleted file mode 100644
--- a/test/lua/test-pandoc-utils.lua
+++ /dev/null
@@ -1,115 +0,0 @@
-utils = require 'pandoc.utils'
-
--- hierarchicalize
-------------------------------------------------------------------------
-function test_hierarchicalize ()
-  local blks = {
-    pandoc.Header(1, {pandoc.Str 'First'}),
-    pandoc.Header(2, {pandoc.Str 'Second'}),
-    pandoc.Header(2, {pandoc.Str 'Third'}),
-  }
-  local hblks = utils.hierarchicalize(blks)
-  return hblks[1].t == "Sec"
-    and hblks[1].contents[1].t == "Sec"
-    and hblks[1].contents[2].numbering[1] == 1
-    and hblks[1].contents[2].numbering[2] == 2
-end
-
--- SHA1
-------------------------------------------------------------------------
-function test_sha1 ()
-  local ref_hash = '0a0a9f2a6772942557ab5355d76af442f8f65e01'
-  local hash = utils.sha1 'Hello, World!'
-  return hash == ref_hash
-end
-
--- Pipe
-------------------------------------------------------------------------
-function file_exists (filename)
-  local fh = io.open(filename, 'r')
-  return fh ~= nil and (fh:close() or true)
-end
-
-function warn (...) io.stderr:write(...) end
-
-function test_pipe ()
-  if not file_exists('/bin/sed') then
-    warn 'Did not find /bin/sed, skipping test'
-    return true
-  end
-  local pipe_result = pandoc.pipe('/bin/sed', {'-e', 's/a/b/'}, 'abc')
-  return pipe_result == 'bbc'
-end
-
-function test_failing_pipe ()
-  if not file_exists('/bin/false') then
-    warn 'Did not find /bin/false, skipping test'
-    return true
-  end
-  local res, err = pcall(pandoc.pipe, '/bin/false', {}, 'abc')
-  return not res and
-    err.command == '/bin/false' and
-    err.error_code == 1 and
-    err.output == ''
-end
-
--- Read
-------------------------------------------------------------------------
-function test_read ()
-  local valid_markdown = '*Hello*, World!\n'
-  local res = pandoc.read(valid_markdown).blocks[1].content
-  return res[1].t == 'Emph' and res[3].t == 'Space' and res[4].t == 'Str'
-end
-
-function test_failing_read ()
-  local res, err = pcall(pandoc.read, 'foo', 'nosuchreader')
-  return not res and err:match 'Unknown reader: nosuchreader'
-end
-
--- Stringify
-------------------------------------------------------------------------
-function test_stringify ()
-  local inline = pandoc.Emph{
-    pandoc.Str 'Cogito',
-    pandoc.Space(),
-    pandoc.Str 'ergo',
-    pandoc.Space(),
-    pandoc.Str 'sum.',
-  }
-  return utils.stringify(inline) == 'Cogito ergo sum.'
-end
-
--- to_roman_numeral
-------------------------------------------------------------------------
-function test_to_roman_numeral ()
-  return utils.to_roman_numeral(1888) == 'MDCCCLXXXVIII'
-    -- calling with a string fails
-    and not pcall(utils.to_roman_numeral, 'not a number')
-end
-
--- normalize_date
-------------------------------------------------------------------------
-function test_normalize_date ()
-  return utils.normalize_date("12/31/2017") == '2017-12-31'
-    and utils.normalize_date("pandoc") == nil
-end
-
--- Return result
-------------------------------------------------------------------------
-function run(fn)
-  return fn() and "OK" or "FAIL"
-end
-
-function Para (el)
-  return {
-    pandoc.Plain{pandoc.Str("hierarchicalize: " .. run(test_hierarchicalize))},
-    pandoc.Plain{pandoc.Str("normalize_date: " .. run(test_normalize_date))},
-    pandoc.Plain{pandoc.Str("pipe: " .. run(test_pipe))},
-    pandoc.Plain{pandoc.Str("failing pipe: " .. run(test_failing_pipe))},
-    pandoc.Plain{pandoc.Str("read: " .. run(test_read))},
-    pandoc.Plain{pandoc.Str("failing read: " .. run(test_failing_read))},
-    pandoc.Plain{pandoc.Str("sha1: " .. run(test_sha1))},
-    pandoc.Plain{pandoc.Str("stringify: " .. run(test_stringify))},
-    pandoc.Plain{pandoc.Str("to_roman_numeral: " .. run(test_to_roman_numeral))},
-  }
-end
diff --git a/test/lua/undiv.lua b/test/lua/undiv.lua
deleted file mode 100644
--- a/test/lua/undiv.lua
+++ /dev/null
@@ -1,3 +0,0 @@
-function Div(el)
-  return el.content
-end
diff --git a/test/lua/uppercase-header.lua b/test/lua/uppercase-header.lua
deleted file mode 100644
--- a/test/lua/uppercase-header.lua
+++ /dev/null
@@ -1,9 +0,0 @@
-local text = require 'text'
-
-local function str_to_uppercase (s)
-  return pandoc.Str(text.upper(s.text))
-end
-
-function Header (el)
-  return pandoc.walk_block(el, {Str = str_to_uppercase})
-end
diff --git a/test/man-reader.man b/test/man-reader.man
new file mode 100644
--- /dev/null
+++ b/test/man-reader.man
@@ -0,0 +1,391 @@
+.TH "PANDOC-MAN-TESTS" "1" "Oct 17, 2018" "v1.0.1" "Pandoc Tests"
+.PP
+This is a set of tests for pandoc.
+.PP
+   *   *   *   *   *
+.SH Headers
+.SH Level 1
+.SS Level 2
+
+   *   *   *   *   *
+.SH Paragraphs
+.PP
+Here's a regular paragraph.
+.PP
+Another paragraph
+In Markdown 1.0.0 and earlier.
+Version 8.
+This line turns into a list item.
+Because a hard\-wrapped line in the middle of a paragraph looked like a list
+item.
+.PP
+There should be a hard line break
+.PD 0
+.P
+.PD
+here.
+.PP
+   *   *   *   *   *
+.SH Block Quotes
+Code in a block quote:
+.RS
+.nf
+\f[C]
+sub\ status\ {
+\ \ \ \ print\ "working";
+}
+\f[]
+.fi
+.RE
+.PP
+A list:
+.IP "1." 3
+item one
+.IP "2." 3
+item two
+.PP
+.SH Code Blocks
+.PP
+Code:
+.IP
+.nf
+\f[C]
+\-\-\-\- (should be four hyphens)
+
+sub status {
+    print "working";
+}
+
+\f[]
+.fi
+.PP
+And:
+.IP
+.nf
+\f[C]
+\tthis code line is indented by one tab
+\f[]
+.fi
+.PP
+   *   *   *   *   *
+.SH Lists
+.SS Unordered
+.PP
+Asterisks:
+.IP \[bu] 2
+asterisk 1
+.IP \[bu] 2
+asterisk 2
+.IP \[bu] 2
+asterisk 3
+.PP
+.SS Ordered
+.IP "1." 3
+First
+.IP "2." 3
+Second
+.IP "3." 3
+Third
+.PP
+.SS Nested
+.IP \[bu] 2
+Tab
+.RS 2
+.IP \[bu] 2
+Tab
+.RS 2
+.IP \[bu] 2
+Tab
+.RE
+.RE
+.PP
+Here's another:
+.IP "1." 3
+First
+.IP "2." 3
+Second:
+.RS 4
+.IP \[bu] 2
+Fee
+.IP \[bu] 2
+Fie
+.IP \[bu] 2
+Foe
+.RE
+.IP "3." 3
+Third
+.PP
+Same thing:
+.IP "1." 3
+First
+.IP "2." 3
+Second:
+.RS 4
+.IP \[bu] 2
+Fee
+.IP \[bu] 2
+Fie
+.IP \[bu] 2
+Foe
+.RE
+.IP "3." 3
+Third
+.SS different styles:
+.IP "A." 3
+Upper Alpha
+.RS 4
+.IP "I." 3
+Upper Roman.
+.RS 4
+.IP "(6)" 4
+Decimal start with 6
+.RS 4
+.IP "c)" 3
+Lower alpha with paren
+.RE
+.RE
+.RE
+.SS Ordered
+Definition lists
+.TP
+.B term1
+definition 1
+.RS
+.PP
+continued
+.RE
+.TP
+.B term2
+definition 2
+   *   *   *   *   *
+.SH Special Characters
+AT&T has an ampersand in their name.
+.PP
+4 < 5.
+.PP
+6 > 5.
+.PP
+Backslash: \\
+.PP
+Backtick: `
+.PP
+Asterisk: *
+.PP
+Underscore: _
+.PP
+Left brace: {
+.PP
+Right brace: }
+.PP
+Left bracket: [
+.PP
+Right bracket: ]
+.PP
+Left paren: (
+.PP
+Right paren: )
+.PP
+Greater\-than: >
+.PP
+Hash: #
+.PP
+Period: .
+.PP
+Bang: !
+.PP
+Plus: +
+.PP
+Minus: \-
+.PP
+.SH Links
+.PP
+.UR http://\:example.com
+some random
+site
+.UE .
+.PP
+.MT me@example.com
+my email address
+.ME .
+.SH Macros
+.de au
+.B
+Me Myself
+..
+.de auth !!
+.I
+The author is \\$1.
+.!!
+.au
+and I.
+.auth "John Jones"
+.ds me The \f[B]Author\f[R]
+It's \*(me.
+.SH Tables
+.TS
+tab(@);
+r l c l.
+T{
+Right
+T}@T{
+Left
+T}@T{
+Center
+T}@T{
+Default
+T}
+_
+T{
+12
+T}@T{
+12
+T}@T{
+12
+T}@T{
+12
+T}
+T{
+123
+T}@T{
+123
+T}@T{
+123
+T}@T{
+123
+T}
+T{
+1
+T}@T{
+1
+T}@T{
+1
+T}@T{
+1
+T}
+.TE
+.TS
+allbox tab(;);
+rlcl.
+T{
+Right
+T};T{
+Left
+T};T{
+Center
+T};T{
+Left
+\f[I]more\f[R]
+T}
+_
+T{
+12
+T};T{
+12
+T};T{
+12
+T};T{
+12
+T}
+T{
+123
+T};T{
+123
+T};T{
+123
+T};T{
+123
+T}
+T{
+1
+T};T{
+1
+T};T{
+1
+T};T{
+1
+T}
+.TE
+.TS
+tab(@);
+cw(10.5n) lw(9.6n) rw(11.4n) lw(24.5n).
+T{
+Centered Header
+T}@T{
+Left Aligned
+T}@T{
+Right Aligned
+T}@T{
+Default aligned
+T}
+_
+T{
+First
+T}@T{
+row
+T}@T{
+12.0
+T}@T{
+Example of a row that spans multiple lines.
+T}
+T{
+Second
+T}@T{
+row
+T}@T{
+5.0
+T}@T{
+Here\[cq]s another one.
+Note the blank line between rows.
+T}
+.TE
+.PP
+Table without column headers:
+.PP
+.TS
+tab(@);
+r l c r.
+T{
+12
+T}@T{
+12
+T}@T{
+12
+T}@T{
+12
+T}
+T{
+123
+T}@T{
+123
+T}@T{
+123
+T}@T{
+123
+T}
+T{
+1
+T}@T{
+1
+T}@T{
+1
+T}@T{
+1
+T}
+.TE
+.TS
+tab(@);
+rl.
+a@b
+T{
+.PP
+one
+.PP
+two
+T}@T{
+.nf
+some
+   code
+.fi
+T}
+.TE
+
diff --git a/test/man-reader.native b/test/man-reader.native
new file mode 100644
--- /dev/null
+++ b/test/man-reader.native
@@ -0,0 +1,951 @@
+Pandoc
+  Meta
+    { unMeta =
+        fromList
+          [ ( "date"
+            , MetaInlines
+                [ Str "Oct" , Space , Str "17," , Space , Str "2018" ]
+            )
+          , ( "footer" , MetaInlines [ Str "v1.0.1" ] )
+          , ( "header"
+            , MetaInlines [ Str "Pandoc" , Space , Str "Tests" ]
+            )
+          , ( "section" , MetaInlines [ Str "1" ] )
+          , ( "title" , MetaInlines [ Str "PANDOC-MAN-TESTS" ] )
+          ]
+    }
+  [ Para
+      [ Str "This"
+      , Space
+      , Str "is"
+      , Space
+      , Str "a"
+      , Space
+      , Str "set"
+      , Space
+      , Str "of"
+      , Space
+      , Str "tests"
+      , Space
+      , Str "for"
+      , Space
+      , Str "pandoc."
+      ]
+  , Para
+      [ Str "*"
+      , Space
+      , Str "*"
+      , Space
+      , Str "*"
+      , Space
+      , Str "*"
+      , Space
+      , Str "*"
+      ]
+  , Header 1 ( "headers" , [] , [] ) [ Str "Headers" ]
+  , Header
+      1 ( "level-1" , [] , [] ) [ Str "Level" , Space , Str "1" ]
+  , Header
+      2 ( "level-2" , [] , [] ) [ Str "Level" , Space , Str "2" ]
+  , Para
+      [ Str "*"
+      , Space
+      , Str "*"
+      , Space
+      , Str "*"
+      , Space
+      , Str "*"
+      , Space
+      , Str "*"
+      ]
+  , Header 1 ( "paragraphs" , [] , [] ) [ Str "Paragraphs" ]
+  , Para
+      [ Str "Here's"
+      , Space
+      , Str "a"
+      , Space
+      , Str "regular"
+      , Space
+      , Str "paragraph."
+      ]
+  , Para
+      [ Str "Another"
+      , Space
+      , Str "paragraph"
+      , Space
+      , Str "In"
+      , Space
+      , Str "Markdown"
+      , Space
+      , Str "1.0.0"
+      , Space
+      , Str "and"
+      , Space
+      , Str "earlier."
+      , Space
+      , Str "Version"
+      , Space
+      , Str "8."
+      , Space
+      , Str "This"
+      , Space
+      , Str "line"
+      , Space
+      , Str "turns"
+      , Space
+      , Str "into"
+      , Space
+      , Str "a"
+      , Space
+      , Str "list"
+      , Space
+      , Str "item."
+      , Space
+      , Str "Because"
+      , Space
+      , Str "a"
+      , Space
+      , Str "hard-wrapped"
+      , Space
+      , Str "line"
+      , Space
+      , Str "in"
+      , Space
+      , Str "the"
+      , Space
+      , Str "middle"
+      , Space
+      , Str "of"
+      , Space
+      , Str "a"
+      , Space
+      , Str "paragraph"
+      , Space
+      , Str "looked"
+      , Space
+      , Str "like"
+      , Space
+      , Str "a"
+      , Space
+      , Str "list"
+      , Space
+      , Str "item."
+      ]
+  , Para
+      [ Str "There"
+      , Space
+      , Str "should"
+      , Space
+      , Str "be"
+      , Space
+      , Str "a"
+      , Space
+      , Str "hard"
+      , Space
+      , Str "line"
+      , Space
+      , Str "break"
+      ]
+  , Para [ Str "here." ]
+  , Para
+      [ Str "*"
+      , Space
+      , Str "*"
+      , Space
+      , Str "*"
+      , Space
+      , Str "*"
+      , Space
+      , Str "*"
+      ]
+  , Header
+      1
+      ( "block-quotes" , [] , [] )
+      [ Str "Block" , Space , Str "Quotes" ]
+  , Para
+      [ Str "Code"
+      , Space
+      , Str "in"
+      , Space
+      , Str "a"
+      , Space
+      , Str "block"
+      , Space
+      , Str "quote:"
+      ]
+  , BlockQuote
+      [ CodeBlock
+          ( "" , [] , [] ) "sub status {\n    print \"working\";\n}"
+      ]
+  , Para [ Str "A" , Space , Str "list:" ]
+  , OrderedList
+      ( 1 , Decimal , Period )
+      [ [ Para [ Str "item" , Space , Str "one" ] ]
+      , [ Para [ Str "item" , Space , Str "two" ] ]
+      ]
+  , Header
+      1
+      ( "code-blocks" , [] , [] )
+      [ Str "Code" , Space , Str "Blocks" ]
+  , Para [ Str "Code:" ]
+  , CodeBlock
+      ( "" , [] , [] )
+      "---- (should be four hyphens)\n\nsub status {\n    print \"working\";\n}\n"
+  , Para [ Str "And:" ]
+  , CodeBlock
+      ( "" , [] , [] ) "\tthis code line is indented by one tab"
+  , Para
+      [ Str "*"
+      , Space
+      , Str "*"
+      , Space
+      , Str "*"
+      , Space
+      , Str "*"
+      , Space
+      , Str "*"
+      ]
+  , Header 1 ( "lists" , [] , [] ) [ Str "Lists" ]
+  , Header 2 ( "unordered" , [] , [] ) [ Str "Unordered" ]
+  , Para [ Str "Asterisks:" ]
+  , BulletList
+      [ [ Para [ Str "asterisk" , Space , Str "1" ] ]
+      , [ Para [ Str "asterisk" , Space , Str "2" ] ]
+      , [ Para [ Str "asterisk" , Space , Str "3" ] ]
+      ]
+  , Header 2 ( "ordered" , [] , [] ) [ Str "Ordered" ]
+  , OrderedList
+      ( 1 , Decimal , Period )
+      [ [ Para [ Str "First" ] ]
+      , [ Para [ Str "Second" ] ]
+      , [ Para [ Str "Third" ] ]
+      ]
+  , Header 2 ( "nested" , [] , [] ) [ Str "Nested" ]
+  , BulletList
+      [ [ Para [ Str "Tab" ]
+        , BulletList
+            [ [ Para [ Str "Tab" ]
+              , BulletList [ [ Para [ Str "Tab" ] ] ]
+              ]
+            ]
+        ]
+      ]
+  , Para [ Str "Here's" , Space , Str "another:" ]
+  , OrderedList
+      ( 1 , Decimal , Period )
+      [ [ Para [ Str "First" ] ]
+      , [ Para [ Str "Second:" ]
+        , BulletList
+            [ [ Para [ Str "Fee" ] ]
+            , [ Para [ Str "Fie" ] ]
+            , [ Para [ Str "Foe" ] ]
+            ]
+        ]
+      , [ Para [ Str "Third" ] ]
+      ]
+  , Para [ Str "Same" , Space , Str "thing:" ]
+  , OrderedList
+      ( 1 , Decimal , Period )
+      [ [ Para [ Str "First" ] ]
+      , [ Para [ Str "Second:" ]
+        , BulletList
+            [ [ Para [ Str "Fee" ] ]
+            , [ Para [ Str "Fie" ] ]
+            , [ Para [ Str "Foe" ] ]
+            ]
+        ]
+      , [ Para [ Str "Third" ] ]
+      ]
+  , Header
+      2
+      ( "different-styles" , [] , [] )
+      [ Str "different" , Space , Str "styles:" ]
+  , OrderedList
+      ( 1 , UpperAlpha , Period )
+      [ [ Para [ Str "Upper" , Space , Str "Alpha" ]
+        , OrderedList
+            ( 1 , UpperRoman , Period )
+            [ [ Para [ Str "Upper" , Space , Str "Roman." ]
+              , OrderedList
+                  ( 6 , Decimal , TwoParens )
+                  [ [ Para
+                        [ Str "Decimal"
+                        , Space
+                        , Str "start"
+                        , Space
+                        , Str "with"
+                        , Space
+                        , Str "6"
+                        ]
+                    , OrderedList
+                        ( 3 , LowerAlpha , OneParen )
+                        [ [ Para
+                              [ Str "Lower"
+                              , Space
+                              , Str "alpha"
+                              , Space
+                              , Str "with"
+                              , Space
+                              , Str "paren"
+                              ]
+                          ]
+                        ]
+                    ]
+                  ]
+              ]
+            ]
+        ]
+      ]
+  , Header 2 ( "ordered-1" , [] , [] ) [ Str "Ordered" ]
+  , Para [ Str "Definition" , Space , Str "lists" ]
+  , DefinitionList
+      [ ( [ Strong [ Str "term1" ] ]
+        , [ [ Para [ Str "definition" , Space , Str "1" ]
+            , Para [ Str "continued" ]
+            ]
+          ]
+        )
+      , ( [ Strong [ Str "term2" ] ]
+        , [ [ Para
+                [ Str "definition"
+                , Space
+                , Str "2"
+                , Space
+                , Str "*"
+                , Space
+                , Str "*"
+                , Space
+                , Str "*"
+                , Space
+                , Str "*"
+                , Space
+                , Str "*"
+                ]
+            ]
+          ]
+        )
+      ]
+  , Header
+      1
+      ( "special-characters" , [] , [] )
+      [ Str "Special" , Space , Str "Characters" ]
+  , Para
+      [ Str "AT&T"
+      , Space
+      , Str "has"
+      , Space
+      , Str "an"
+      , Space
+      , Str "ampersand"
+      , Space
+      , Str "in"
+      , Space
+      , Str "their"
+      , Space
+      , Str "name."
+      ]
+  , Para [ Str "4" , Space , Str "<" , Space , Str "5." ]
+  , Para [ Str "6" , Space , Str ">" , Space , Str "5." ]
+  , Para [ Str "Backslash:" , Space , Str "\\" ]
+  , Para [ Str "Backtick:" , Space , Str "`" ]
+  , Para [ Str "Asterisk:" , Space , Str "*" ]
+  , Para [ Str "Underscore:" , Space , Str "_" ]
+  , Para
+      [ Str "Left" , Space , Str "brace:" , Space , Str "{" ]
+  , Para
+      [ Str "Right" , Space , Str "brace:" , Space , Str "}" ]
+  , Para
+      [ Str "Left" , Space , Str "bracket:" , Space , Str "[" ]
+  , Para
+      [ Str "Right" , Space , Str "bracket:" , Space , Str "]" ]
+  , Para
+      [ Str "Left" , Space , Str "paren:" , Space , Str "(" ]
+  , Para
+      [ Str "Right" , Space , Str "paren:" , Space , Str ")" ]
+  , Para [ Str "Greater-than:" , Space , Str ">" ]
+  , Para [ Str "Hash:" , Space , Str "#" ]
+  , Para [ Str "Period:" , Space , Str "." ]
+  , Para [ Str "Bang:" , Space , Str "!" ]
+  , Para [ Str "Plus:" , Space , Str "+" ]
+  , Para [ Str "Minus:" , Space , Str "-" ]
+  , Header 1 ( "links" , [] , [] ) [ Str "Links" ]
+  , Para
+      [ Link
+          ( "" , [] , [] )
+          [ Str "some" , Space , Str "randomsite" ]
+          ( "http://example.com" , "" )
+      , Str "."
+      ]
+  , Para
+      [ Link
+          ( "" , [] , [] )
+          [ Str "my" , Space , Str "email" , Space , Str "address" ]
+          ( "mailto:me@example.com" , "" )
+      , Str "."
+      ]
+  , Header 1 ( "macros" , [] , [] ) [ Str "Macros" ]
+  , Para
+      [ Strong [ Str "Me" , Space , Str "Myself" ]
+      , Space
+      , Str "and"
+      , Space
+      , Str "I."
+      , Space
+      , Emph
+          [ Str "The"
+          , Space
+          , Str "author"
+          , Space
+          , Str "is"
+          , Space
+          , Str "John"
+          , Space
+          , Str "Jones."
+          ]
+      , Space
+      , Str "It's"
+      , Space
+      , Str "The"
+      , Space
+      , Strong [ Str "Author" ]
+      , Str "."
+      ]
+  , Header 1 ( "tables" , [] , [] ) [ Str "Tables" ]
+  , Table
+      ( "" , [] , [] )
+      (Caption Nothing [])
+      [ ( AlignRight , ColWidthDefault )
+      , ( AlignLeft , ColWidthDefault )
+      , ( AlignCenter , ColWidthDefault )
+      , ( AlignLeft , ColWidthDefault )
+      ]
+      (TableHead
+         ( "" , [] , [] )
+         [ Row
+             ( "" , [] , [] )
+             [ Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "Right" ] ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "Left" ] ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "Center" ] ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "Default" ] ]
+             ]
+         ])
+      [ TableBody
+          ( "" , [] , [] )
+          (RowHeadColumns 0)
+          []
+          [ Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "12" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "12" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "12" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "12" ] ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "123" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "123" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "123" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "123" ] ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "1" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "1" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "1" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "1" ] ]
+              ]
+          ]
+      ]
+      (TableFoot ( "" , [] , [] ) [])
+  , Table
+      ( "" , [] , [] )
+      (Caption Nothing [])
+      [ ( AlignRight , ColWidthDefault )
+      , ( AlignLeft , ColWidthDefault )
+      , ( AlignCenter , ColWidthDefault )
+      , ( AlignLeft , ColWidthDefault )
+      ]
+      (TableHead
+         ( "" , [] , [] )
+         [ Row
+             ( "" , [] , [] )
+             [ Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "Right" ] ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "Left" ] ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "Center" ] ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "Left" , Space , Emph [ Str "more" ] ] ]
+             ]
+         ])
+      [ TableBody
+          ( "" , [] , [] )
+          (RowHeadColumns 0)
+          []
+          [ Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "12" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "12" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "12" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "12" ] ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "123" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "123" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "123" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "123" ] ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "1" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "1" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "1" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "1" ] ]
+              ]
+          ]
+      ]
+      (TableFoot ( "" , [] , [] ) [])
+  , Table
+      ( "" , [] , [] )
+      (Caption Nothing [])
+      [ ( AlignCenter , ColWidthDefault )
+      , ( AlignLeft , ColWidthDefault )
+      , ( AlignRight , ColWidthDefault )
+      , ( AlignLeft , ColWidthDefault )
+      ]
+      (TableHead
+         ( "" , [] , [] )
+         [ Row
+             ( "" , [] , [] )
+             [ Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "Centered" , Space , Str "Header" ] ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "Left" , Space , Str "Aligned" ] ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "Right" , Space , Str "Aligned" ] ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "Default" , Space , Str "aligned" ] ]
+             ]
+         ])
+      [ TableBody
+          ( "" , [] , [] )
+          (RowHeadColumns 0)
+          []
+          [ Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "First" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "row" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "12.0" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain
+                      [ Str "Example"
+                      , Space
+                      , Str "of"
+                      , Space
+                      , Str "a"
+                      , Space
+                      , Str "row"
+                      , Space
+                      , Str "that"
+                      , Space
+                      , Str "spans"
+                      , Space
+                      , Str "multiple"
+                      , Space
+                      , Str "lines."
+                      ]
+                  ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "Second" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "row" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "5.0" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain
+                      [ Str "Here\8217s"
+                      , Space
+                      , Str "another"
+                      , Space
+                      , Str "one."
+                      , Space
+                      , Str "Note"
+                      , Space
+                      , Str "the"
+                      , Space
+                      , Str "blank"
+                      , Space
+                      , Str "line"
+                      , Space
+                      , Str "between"
+                      , Space
+                      , Str "rows."
+                      ]
+                  ]
+              ]
+          ]
+      ]
+      (TableFoot ( "" , [] , [] ) [])
+  , Para
+      [ Str "Table"
+      , Space
+      , Str "without"
+      , Space
+      , Str "column"
+      , Space
+      , Str "headers:"
+      ]
+  , Table
+      ( "" , [] , [] )
+      (Caption Nothing [])
+      [ ( AlignRight , ColWidthDefault )
+      , ( AlignLeft , ColWidthDefault )
+      , ( AlignCenter , ColWidthDefault )
+      , ( AlignRight , ColWidthDefault )
+      ]
+      (TableHead ( "" , [] , [] ) [])
+      [ TableBody
+          ( "" , [] , [] )
+          (RowHeadColumns 0)
+          []
+          [ Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "12" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "12" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "12" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "12" ] ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "123" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "123" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "123" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "123" ] ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "1" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "1" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "1" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "1" ] ]
+              ]
+          ]
+      ]
+      (TableFoot ( "" , [] , [] ) [])
+  , Table
+      ( "" , [] , [] )
+      (Caption Nothing [])
+      [ ( AlignRight , ColWidth 0.5 )
+      , ( AlignLeft , ColWidth 0.5 )
+      ]
+      (TableHead ( "" , [] , [] ) [])
+      [ TableBody
+          ( "" , [] , [] )
+          (RowHeadColumns 0)
+          []
+          [ Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "a" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "b" ] ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para [ Str "one" ] , Para [ Str "two" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ CodeBlock ( "" , [] , [] ) "some\n   code" ]
+              ]
+          ]
+      ]
+      (TableFoot ( "" , [] , [] ) [])
+  ]
diff --git a/test/markdown-citations.native b/test/markdown-citations.native
--- a/test/markdown-citations.native
+++ b/test/markdown-citations.native
@@ -1,17 +1,522 @@
-[Header 1 ("pandoc-with-citeproc-hs",[],[]) [Str "Pandoc",Space,Str "with",Space,Str "citeproc-hs"]
-,BulletList
- [[Para [Cite [Citation {citationId = "nonexistent", citationPrefix = [], citationSuffix = [], citationMode = NormalCitation, citationNoteNum = 0, citationHash = 0}] [Str "[@nonexistent]"]]]
- ,[Para [Cite [Citation {citationId = "nonexistent", citationPrefix = [], citationSuffix = [], citationMode = AuthorInText, citationNoteNum = 0, citationHash = 0}] [Str "@nonexistent"]]]
- ,[Para [Cite [Citation {citationId = "item1", citationPrefix = [], citationSuffix = [], citationMode = AuthorInText, citationNoteNum = 0, citationHash = 0}] [Str "@item1"],Space,Str "says",Space,Str "blah."]]
- ,[Para [Cite [Citation {citationId = "item1", citationPrefix = [], citationSuffix = [Str "p.\160\&30"], citationMode = AuthorInText, citationNoteNum = 0, citationHash = 0}] [Str "@item1",Space,Str "[p.",Space,Str "30]"],Space,Str "says",Space,Str "blah."]]
- ,[Para [Cite [Citation {citationId = "item1", citationPrefix = [], citationSuffix = [Str "p.\160\&30,",Space,Str "with",Space,Str "suffix"], citationMode = AuthorInText, citationNoteNum = 0, citationHash = 0}] [Str "@item1",Space,Str "[p.",Space,Str "30,",Space,Str "with",Space,Str "suffix]"],Space,Str "says",Space,Str "blah."]]
- ,[Para [Cite [Citation {citationId = "item1", citationPrefix = [], citationSuffix = [], citationMode = AuthorInText, citationNoteNum = 0, citationHash = 0},Citation {citationId = "item2", citationPrefix = [], citationSuffix = [Space,Str "p.\160\&30"], citationMode = SuppressAuthor, citationNoteNum = 0, citationHash = 0},Citation {citationId = "\1087\1091\1085\1082\1090\&3", citationPrefix = [Str "see",Space,Str "also"], citationSuffix = [], citationMode = NormalCitation, citationNoteNum = 0, citationHash = 0}] [Str "@item1",Space,Str "[-@item2",Space,Str "p.",Space,Str "30;",Space,Str "see",Space,Str "also",Space,Str "@\1087\1091\1085\1082\1090\&3]"],Space,Str "says",Space,Str "blah."]]
- ,[Para [Str "In",Space,Str "a",Space,Str "note.",Note [Para [Cite [Citation {citationId = "\1087\1091\1085\1082\1090\&3", citationPrefix = [], citationSuffix = [Str "p.\160\&12"], citationMode = AuthorInText, citationNoteNum = 0, citationHash = 0}] [Str "@\1087\1091\1085\1082\1090\&3",Space,Str "[p.",Space,Str "12]"],Space,Str "and",Space,Str "a",Space,Str "citation",Space,Str "without",Space,Str "locators",Space,Cite [Citation {citationId = "\1087\1091\1085\1082\1090\&3", citationPrefix = [], citationSuffix = [], citationMode = NormalCitation, citationNoteNum = 0, citationHash = 0}] [Str "[@\1087\1091\1085\1082\1090\&3]"],Str "."]]]]
- ,[Para [Str "A",Space,Str "citation",Space,Str "group",Space,Cite [Citation {citationId = "item1", citationPrefix = [Str "see"], citationSuffix = [Space,Str "chap.",Space,Str "3"], citationMode = NormalCitation, citationNoteNum = 0, citationHash = 0},Citation {citationId = "\1087\1091\1085\1082\1090\&3", citationPrefix = [Str "also"], citationSuffix = [Space,Str "p.\160\&34-35"], citationMode = NormalCitation, citationNoteNum = 0, citationHash = 0}] [Str "[see",Space,Str "@item1",Space,Str "chap.",Space,Str "3;",Space,Str "also",Space,Str "@\1087\1091\1085\1082\1090\&3",Space,Str "p.",Space,Str "34-35]"],Str "."]]
- ,[Para [Str "Another",Space,Str "one",Space,Cite [Citation {citationId = "item1", citationPrefix = [Str "see"], citationSuffix = [Space,Str "p.\160\&34-35"], citationMode = NormalCitation, citationNoteNum = 0, citationHash = 0}] [Str "[see",Space,Str "@item1",Space,Str "p.",Space,Str "34-35]"],Str "."]]
- ,[Para [Str "And",Space,Str "another",Space,Str "one",Space,Str "in",Space,Str "a",Space,Str "note.",Note [Para [Str "Some",Space,Str "citations",Space,Cite [Citation {citationId = "item1", citationPrefix = [Str "see"], citationSuffix = [Space,Str "chap.",Space,Str "3"], citationMode = NormalCitation, citationNoteNum = 0, citationHash = 0},Citation {citationId = "\1087\1091\1085\1082\1090\&3", citationPrefix = [], citationSuffix = [], citationMode = NormalCitation, citationNoteNum = 0, citationHash = 0},Citation {citationId = "item2", citationPrefix = [], citationSuffix = [], citationMode = NormalCitation, citationNoteNum = 0, citationHash = 0}] [Str "[see",Space,Str "@item1",Space,Str "chap.",Space,Str "3;",Space,Str "@\1087\1091\1085\1082\1090\&3;",Space,Str "@item2]"],Str "."]]]]
- ,[Para [Str "Citation",Space,Str "with",Space,Str "a",Space,Str "suffix",Space,Str "and",Space,Str "locator",Space,Cite [Citation {citationId = "item1", citationPrefix = [], citationSuffix = [Space,Str "pp.\160\&33,",Space,Str "35-37,",Space,Str "and",Space,Str "nowhere",Space,Str "else"], citationMode = NormalCitation, citationNoteNum = 0, citationHash = 0}] [Str "[@item1",Space,Str "pp.",Space,Str "33,",Space,Str "35-37,",Space,Str "and",Space,Str "nowhere",Space,Str "else]"],Str "."]]
- ,[Para [Str "Citation",Space,Str "with",Space,Str "suffix",Space,Str "only",Space,Cite [Citation {citationId = "item1", citationPrefix = [], citationSuffix = [Space,Str "and",Space,Str "nowhere",Space,Str "else"], citationMode = NormalCitation, citationNoteNum = 0, citationHash = 0}] [Str "[@item1",Space,Str "and",Space,Str "nowhere",Space,Str "else]"],Str "."]]
- ,[Para [Str "Now",Space,Str "some",Space,Str "modifiers.",Note [Para [Str "Like",Space,Str "a",Space,Str "citation",Space,Str "without",Space,Str "author:",Space,Cite [Citation {citationId = "item1", citationPrefix = [], citationSuffix = [], citationMode = SuppressAuthor, citationNoteNum = 0, citationHash = 0}] [Str "[-@item1]"],Str ",",Space,Str "and",Space,Str "now",Space,Str "Doe",Space,Str "with",Space,Str "a",Space,Str "locator",Space,Cite [Citation {citationId = "item2", citationPrefix = [], citationSuffix = [Space,Str "p.\160\&44"], citationMode = SuppressAuthor, citationNoteNum = 0, citationHash = 0}] [Str "[-@item2",Space,Str "p.",Space,Str "44]"],Str "."]]]]
- ,[Para [Str "With",Space,Str "some",Space,Str "markup",Space,Cite [Citation {citationId = "item1", citationPrefix = [Emph [Str "see"]], citationSuffix = [Space,Str "p.",Space,Strong [Str "32"]], citationMode = NormalCitation, citationNoteNum = 0, citationHash = 0}] [Str "[*see*",Space,Str "@item1",Space,Str "p.",Space,Str "**32**]"],Str "."]]]
-,Header 1 ("references",[],[]) [Str "References"]]
+[ Header
+    1
+    ( "pandoc-with-citeproc-hs" , [] , [] )
+    [ Str "Pandoc"
+    , Space
+    , Str "with"
+    , Space
+    , Str "citeproc-hs"
+    ]
+, BulletList
+    [ [ Para
+          [ Cite
+              [ Citation
+                  { citationId = "nonexistent"
+                  , citationPrefix = []
+                  , citationSuffix = []
+                  , citationMode = NormalCitation
+                  , citationNoteNum = 1
+                  , citationHash = 0
+                  }
+              ]
+              [ Str "[@nonexistent]" ]
+          ]
+      ]
+    , [ Para
+          [ Cite
+              [ Citation
+                  { citationId = "nonexistent"
+                  , citationPrefix = []
+                  , citationSuffix = []
+                  , citationMode = AuthorInText
+                  , citationNoteNum = 2
+                  , citationHash = 0
+                  }
+              ]
+              [ Str "@nonexistent" ]
+          ]
+      ]
+    , [ Para
+          [ Cite
+              [ Citation
+                  { citationId = "item1"
+                  , citationPrefix = []
+                  , citationSuffix = []
+                  , citationMode = AuthorInText
+                  , citationNoteNum = 3
+                  , citationHash = 0
+                  }
+              ]
+              [ Str "@item1" ]
+          , Space
+          , Str "says"
+          , Space
+          , Str "blah."
+          ]
+      ]
+    , [ Para
+          [ Cite
+              [ Citation
+                  { citationId = "item1"
+                  , citationPrefix = []
+                  , citationSuffix = [ Str "p.\160\&30" ]
+                  , citationMode = AuthorInText
+                  , citationNoteNum = 4
+                  , citationHash = 0
+                  }
+              ]
+              [ Str "@item1" , Space , Str "[p." , Space , Str "30]" ]
+          , Space
+          , Str "says"
+          , Space
+          , Str "blah."
+          ]
+      ]
+    , [ Para
+          [ Cite
+              [ Citation
+                  { citationId = "item1"
+                  , citationPrefix = []
+                  , citationSuffix =
+                      [ Str "p.\160\&30,"
+                      , Space
+                      , Str "with"
+                      , Space
+                      , Str "suffix"
+                      ]
+                  , citationMode = AuthorInText
+                  , citationNoteNum = 5
+                  , citationHash = 0
+                  }
+              ]
+              [ Str "@item1"
+              , Space
+              , Str "[p."
+              , Space
+              , Str "30,"
+              , Space
+              , Str "with"
+              , Space
+              , Str "suffix]"
+              ]
+          , Space
+          , Str "says"
+          , Space
+          , Str "blah."
+          ]
+      ]
+    , [ Para
+          [ Cite
+              [ Citation
+                  { citationId = "item1"
+                  , citationPrefix = []
+                  , citationSuffix = []
+                  , citationMode = AuthorInText
+                  , citationNoteNum = 6
+                  , citationHash = 0
+                  }
+              , Citation
+                  { citationId = "item2"
+                  , citationPrefix = []
+                  , citationSuffix = [ Space , Str "p.\160\&30" ]
+                  , citationMode = SuppressAuthor
+                  , citationNoteNum = 6
+                  , citationHash = 0
+                  }
+              , Citation
+                  { citationId = "\1087\1091\1085\1082\1090\&3"
+                  , citationPrefix = [ Str "see" , Space , Str "also" ]
+                  , citationSuffix = []
+                  , citationMode = NormalCitation
+                  , citationNoteNum = 6
+                  , citationHash = 0
+                  }
+              ]
+              [ Str "@item1"
+              , Space
+              , Str "[-@item2"
+              , Space
+              , Str "p."
+              , Space
+              , Str "30;"
+              , Space
+              , Str "see"
+              , Space
+              , Str "also"
+              , Space
+              , Str "@\1087\1091\1085\1082\1090\&3]"
+              ]
+          , Space
+          , Str "says"
+          , Space
+          , Str "blah."
+          ]
+      ]
+    , [ Para
+          [ Str "In"
+          , Space
+          , Str "a"
+          , Space
+          , Str "note."
+          , Note
+              [ Para
+                  [ Cite
+                      [ Citation
+                          { citationId = "\1087\1091\1085\1082\1090\&3"
+                          , citationPrefix = []
+                          , citationSuffix = [ Str "p.\160\&12" ]
+                          , citationMode = AuthorInText
+                          , citationNoteNum = 7
+                          , citationHash = 0
+                          }
+                      ]
+                      [ Str "@\1087\1091\1085\1082\1090\&3"
+                      , Space
+                      , Str "[p."
+                      , Space
+                      , Str "12]"
+                      ]
+                  , Space
+                  , Str "and"
+                  , Space
+                  , Str "a"
+                  , Space
+                  , Str "citation"
+                  , Space
+                  , Str "without"
+                  , Space
+                  , Str "locators"
+                  , Space
+                  , Cite
+                      [ Citation
+                          { citationId = "\1087\1091\1085\1082\1090\&3"
+                          , citationPrefix = []
+                          , citationSuffix = []
+                          , citationMode = NormalCitation
+                          , citationNoteNum = 7
+                          , citationHash = 0
+                          }
+                      ]
+                      [ Str "[@\1087\1091\1085\1082\1090\&3]" ]
+                  , Str "."
+                  ]
+              ]
+          ]
+      ]
+    , [ Para
+          [ Str "A"
+          , Space
+          , Str "citation"
+          , Space
+          , Str "group"
+          , Space
+          , Cite
+              [ Citation
+                  { citationId = "item1"
+                  , citationPrefix = [ Str "see" ]
+                  , citationSuffix = [ Space , Str "chap.\160\&3" ]
+                  , citationMode = NormalCitation
+                  , citationNoteNum = 8
+                  , citationHash = 0
+                  }
+              , Citation
+                  { citationId = "\1087\1091\1085\1082\1090\&3"
+                  , citationPrefix = [ Str "also" ]
+                  , citationSuffix = [ Space , Str "p.\160\&34-35" ]
+                  , citationMode = NormalCitation
+                  , citationNoteNum = 8
+                  , citationHash = 0
+                  }
+              ]
+              [ Str "[see"
+              , Space
+              , Str "@item1"
+              , Space
+              , Str "chap."
+              , Space
+              , Str "3;"
+              , Space
+              , Str "also"
+              , Space
+              , Str "@\1087\1091\1085\1082\1090\&3"
+              , Space
+              , Str "p."
+              , Space
+              , Str "34-35]"
+              ]
+          , Str "."
+          ]
+      ]
+    , [ Para
+          [ Str "Another"
+          , Space
+          , Str "one"
+          , Space
+          , Cite
+              [ Citation
+                  { citationId = "item1"
+                  , citationPrefix = [ Str "see" ]
+                  , citationSuffix = [ Space , Str "p.\160\&34-35" ]
+                  , citationMode = NormalCitation
+                  , citationNoteNum = 9
+                  , citationHash = 0
+                  }
+              ]
+              [ Str "[see"
+              , Space
+              , Str "@item1"
+              , Space
+              , Str "p."
+              , Space
+              , Str "34-35]"
+              ]
+          , Str "."
+          ]
+      ]
+    , [ Para
+          [ Str "And"
+          , Space
+          , Str "another"
+          , Space
+          , Str "one"
+          , Space
+          , Str "in"
+          , Space
+          , Str "a"
+          , Space
+          , Str "note."
+          , Note
+              [ Para
+                  [ Str "Some"
+                  , Space
+                  , Str "citations"
+                  , Space
+                  , Cite
+                      [ Citation
+                          { citationId = "item1"
+                          , citationPrefix = [ Str "see" ]
+                          , citationSuffix =
+                              [ Space , Str "chap.\160\&3" ]
+                          , citationMode = NormalCitation
+                          , citationNoteNum = 10
+                          , citationHash = 0
+                          }
+                      , Citation
+                          { citationId = "\1087\1091\1085\1082\1090\&3"
+                          , citationPrefix = []
+                          , citationSuffix = []
+                          , citationMode = NormalCitation
+                          , citationNoteNum = 10
+                          , citationHash = 0
+                          }
+                      , Citation
+                          { citationId = "item2"
+                          , citationPrefix = []
+                          , citationSuffix = []
+                          , citationMode = NormalCitation
+                          , citationNoteNum = 10
+                          , citationHash = 0
+                          }
+                      ]
+                      [ Str "[see"
+                      , Space
+                      , Str "@item1"
+                      , Space
+                      , Str "chap."
+                      , Space
+                      , Str "3;"
+                      , Space
+                      , Str "@\1087\1091\1085\1082\1090\&3;"
+                      , Space
+                      , Str "@item2]"
+                      ]
+                  , Str "."
+                  ]
+              ]
+          ]
+      ]
+    , [ Para
+          [ Str "Citation"
+          , Space
+          , Str "with"
+          , Space
+          , Str "a"
+          , Space
+          , Str "suffix"
+          , Space
+          , Str "and"
+          , Space
+          , Str "locator"
+          , Space
+          , Cite
+              [ Citation
+                  { citationId = "item1"
+                  , citationPrefix = []
+                  , citationSuffix =
+                      [ Space
+                      , Str "pp.\160\&33,"
+                      , Space
+                      , Str "35-37,"
+                      , Space
+                      , Str "and"
+                      , Space
+                      , Str "nowhere"
+                      , Space
+                      , Str "else"
+                      ]
+                  , citationMode = NormalCitation
+                  , citationNoteNum = 11
+                  , citationHash = 0
+                  }
+              ]
+              [ Str "[@item1"
+              , Space
+              , Str "pp."
+              , Space
+              , Str "33,"
+              , Space
+              , Str "35-37,"
+              , Space
+              , Str "and"
+              , Space
+              , Str "nowhere"
+              , Space
+              , Str "else]"
+              ]
+          , Str "."
+          ]
+      ]
+    , [ Para
+          [ Str "Citation"
+          , Space
+          , Str "with"
+          , Space
+          , Str "suffix"
+          , Space
+          , Str "only"
+          , Space
+          , Cite
+              [ Citation
+                  { citationId = "item1"
+                  , citationPrefix = []
+                  , citationSuffix =
+                      [ Space
+                      , Str "and"
+                      , Space
+                      , Str "nowhere"
+                      , Space
+                      , Str "else"
+                      ]
+                  , citationMode = NormalCitation
+                  , citationNoteNum = 12
+                  , citationHash = 0
+                  }
+              ]
+              [ Str "[@item1"
+              , Space
+              , Str "and"
+              , Space
+              , Str "nowhere"
+              , Space
+              , Str "else]"
+              ]
+          , Str "."
+          ]
+      ]
+    , [ Para
+          [ Str "Now"
+          , Space
+          , Str "some"
+          , Space
+          , Str "modifiers."
+          , Note
+              [ Para
+                  [ Str "Like"
+                  , Space
+                  , Str "a"
+                  , Space
+                  , Str "citation"
+                  , Space
+                  , Str "without"
+                  , Space
+                  , Str "author:"
+                  , Space
+                  , Cite
+                      [ Citation
+                          { citationId = "item1"
+                          , citationPrefix = []
+                          , citationSuffix = []
+                          , citationMode = SuppressAuthor
+                          , citationNoteNum = 13
+                          , citationHash = 0
+                          }
+                      ]
+                      [ Str "[-@item1]" ]
+                  , Str ","
+                  , Space
+                  , Str "and"
+                  , Space
+                  , Str "now"
+                  , Space
+                  , Str "Doe"
+                  , Space
+                  , Str "with"
+                  , Space
+                  , Str "a"
+                  , Space
+                  , Str "locator"
+                  , Space
+                  , Cite
+                      [ Citation
+                          { citationId = "item2"
+                          , citationPrefix = []
+                          , citationSuffix =
+                              [ Space , Str "p.\160\&44" ]
+                          , citationMode = SuppressAuthor
+                          , citationNoteNum = 13
+                          , citationHash = 0
+                          }
+                      ]
+                      [ Str "[-@item2"
+                      , Space
+                      , Str "p."
+                      , Space
+                      , Str "44]"
+                      ]
+                  , Str "."
+                  ]
+              ]
+          ]
+      ]
+    , [ Para
+          [ Str "With"
+          , Space
+          , Str "some"
+          , Space
+          , Str "markup"
+          , Space
+          , Cite
+              [ Citation
+                  { citationId = "item1"
+                  , citationPrefix = [ Emph [ Str "see" ] ]
+                  , citationSuffix =
+                      [ Space , Str "p.\160" , Strong [ Str "32" ] ]
+                  , citationMode = NormalCitation
+                  , citationNoteNum = 14
+                  , citationHash = 0
+                  }
+              ]
+              [ Str "[*see*"
+              , Space
+              , Str "@item1"
+              , Space
+              , Str "p."
+              , Space
+              , Str "**32**]"
+              ]
+          , Str "."
+          ]
+      ]
+    ]
+, Header 1 ( "references" , [] , [] ) [ Str "References" ]
+]
diff --git a/test/markdown-reader-more.native b/test/markdown-reader-more.native
--- a/test/markdown-reader-more.native
+++ b/test/markdown-reader-more.native
@@ -1,196 +1,1715 @@
-Pandoc (Meta {unMeta = fromList [("author",MetaList [MetaInlines [Str "Author",Space,Str "One"],MetaInlines [Str "Author",Space,Str "Two"],MetaInlines [Str "Author",Space,Str "Three"],MetaInlines [Str "Author",Space,Str "Four"]]),("title",MetaInlines [Str "Title",SoftBreak,Str "spanning",Space,Str "multiple",Space,Str "lines"])]})
-[Header 1 ("additional-markdown-reader-tests",[],[]) [Str "Additional",Space,Str "markdown",Space,Str "reader",Space,Str "tests"]
-,Header 2 ("blank-line-before-url-in-link-reference",[],[]) [Str "Blank",Space,Str "line",Space,Str "before",Space,Str "URL",Space,Str "in",Space,Str "link",Space,Str "reference"]
-,Para [Link ("",[],[]) [Str "foo"] ("/url",""),Space,Str "and",Space,Link ("",[],[]) [Str "bar"] ("/url","title")]
-,Header 2 ("raw-context-environments",[],[]) [Str "Raw",Space,Str "ConTeXt",Space,Str "environments"]
-,RawBlock (Format "context") "\\placeformula \\startformula\n   L_{1} = L_{2}\n   \\stopformula\n\n\\start[a2]\n\\start[a2]\n\\stop[a2]\n\\stop[a2]"
-,Header 2 ("raw-latex-environments",[],[]) [Str "Raw",Space,Str "LaTeX",Space,Str "environments"]
-,RawBlock (Format "latex") "\\begin{center}\n\\begin{tikzpicture}[baseline={([yshift=+-.5ex]current bounding box.center)}, level distance=24pt]\n\\Tree [.{S} [.NP John\\index{i} ] [.VP [.V likes ] [.NP himself\\index{i,*j} ]]]\n\\end{tikzpicture}\n\\end{center}"
-,Header 2 ("urls-with-spaces-and-punctuation",[],[]) [Str "URLs",Space,Str "with",Space,Str "spaces",Space,Str "and",Space,Str "punctuation"]
-,Para [Link ("",[],[]) [Str "foo"] ("/bar%20and%20baz",""),SoftBreak,Link ("",[],[]) [Str "foo"] ("/bar%20and%20baz",""),SoftBreak,Link ("",[],[]) [Str "foo"] ("/bar%20and%20baz",""),SoftBreak,Link ("",[],[]) [Str "foo"] ("bar%20baz","title")]
-,Para [Link ("",[],[]) [Str "baz"] ("/foo%20foo",""),Space,Link ("",[],[]) [Str "bam"] ("/foo%20fee",""),Space,Link ("",[],[]) [Str "bork"] ("/foo/zee%20zob","title")]
-,Para [Link ("",[],[]) [Str "Ward\8217s",Space,Str "method."] ("http://en.wikipedia.org/wiki/Ward's_method","")]
-,Header 2 ("horizontal-rules-with-spaces-at-end",[],[]) [Str "Horizontal",Space,Str "rules",Space,Str "with",Space,Str "spaces",Space,Str "at",Space,Str "end"]
-,HorizontalRule
-,HorizontalRule
-,Header 2 ("raw-html-before-header",[],[]) [Str "Raw",Space,Str "HTML",Space,Str "before",Space,Str "header"]
-,Para [RawInline (Format "html") "<a>",RawInline (Format "html") "</a>"]
-,Header 3 ("my-header",[],[]) [Str "my",Space,Str "header"]
-,Header 2 ("in-math",[],[]) [Str "$",Space,Str "in",Space,Str "math"]
-,Para [Math InlineMath "\\$2 + \\$3"]
-,Para [Math InlineMath "x = \\text{the $n$th root of $y$}"]
-,Para [Str "This",Space,Str "should",Space,Str "not",Space,Str "be",Space,Str "math:"]
-,Para [Str "$PATH",Space,Str "90",Space,Str "$PATH"]
-,Header 2 ("commented-out-list-item",[],[]) [Str "Commented-out",Space,Str "list",Space,Str "item"]
-,BulletList
- [[Plain [Str "one",SoftBreak,RawInline (Format "html") "<!--\n- two\n-->"]]
- ,[Plain [Str "three"]]]
-,Header 2 ("indented-code-at-beginning-of-list",[],[]) [Str "Indented",Space,Str "code",Space,Str "at",Space,Str "beginning",Space,Str "of",Space,Str "list"]
-,BulletList
- [[CodeBlock ("",[],[]) "code\ncode"
-  ,OrderedList (1,Decimal,Period)
-   [[CodeBlock ("",[],[]) "code\ncode"]
-   ,[CodeBlock ("",[],[]) "code\ncode"]]
-  ,BulletList
-   [[CodeBlock ("",[],[]) "code\ncode"]
-   ,[Plain [Str "no",Space,Str "code"]]]]]
-,Header 2 ("backslash-newline",[],[]) [Str "Backslash",Space,Str "newline"]
-,Para [Str "hi",LineBreak,Str "there"]
-,Header 2 ("code-spans",[],[]) [Str "Code",Space,Str "spans"]
-,Para [Code ("",[],[]) "hi\\"]
-,Para [Code ("",[],[]) "hi there"]
-,Para [Code ("",[],[]) "hi````there"]
-,Para [Str "`hi"]
-,Para [Str "there`"]
-,Header 2 ("multilingual-urls",[],[]) [Str "Multilingual",Space,Str "URLs"]
-,Para [Link ("",[],[]) [Str "http://\27979.com?\27979=\27979"] ("http://\27979.com?\27979=\27979","")]
-,Para [Link ("",[],[]) [Str "foo"] ("/bar/\27979?x=\27979","title")]
-,Para [Link ("",[],[]) [Str "\27979@foo.\27979.baz"] ("mailto:\27979@foo.\27979.baz","")]
-,Header 2 ("numbered-examples",[],[]) [Str "Numbered",Space,Str "examples"]
-,OrderedList (1,Example,TwoParens)
- [[Plain [Str "First",Space,Str "example."]]
- ,[Plain [Str "Second",Space,Str "example."]]]
-,Para [Str "Explanation",Space,Str "of",Space,Str "examples",Space,Str "(2)",Space,Str "and",Space,Str "(3)."]
-,OrderedList (3,Example,TwoParens)
- [[Plain [Str "Third",Space,Str "example."]]]
-,Header 2 ("macros",[],[]) [Str "Macros"]
-,Para [Math InlineMath "\\langle x,y \\rangle"]
-,Header 2 ("case-insensitive-references",[],[]) [Str "Case-insensitive",Space,Str "references"]
-,Para [Link ("",[],[]) [Str "Fum"] ("/fum","")]
-,Para [Link ("",[],[]) [Str "FUM"] ("/fum","")]
-,Para [Link ("",[],[]) [Str "bat"] ("/bat","")]
-,Header 2 ("curly-smart-quotes",[],[]) [Str "Curly",Space,Str "smart",Space,Str "quotes"]
-,Para [Quoted DoubleQuote [Str "Hi"]]
-,Para [Quoted SingleQuote [Str "Hi"]]
-,Header 2 ("consecutive-lists",[],[]) [Str "Consecutive",Space,Str "lists"]
-,BulletList
- [[Plain [Str "one"]]
- ,[Plain [Str "two"]]]
-,OrderedList (1,Decimal,Period)
- [[Plain [Str "one"]]
- ,[Plain [Str "two"]]]
-,OrderedList (1,LowerAlpha,Period)
- [[Plain [Str "one"]]
- ,[Plain [Str "two"]]]
-,Header 2 ("implicit-header-references",[],[]) [Str "Implicit",Space,Str "header",Space,Str "references"]
-,Header 3 ("my-header-1",[],[]) [Str "My",Space,Str "header"]
-,Header 3 ("my-other-header",[],[]) [Str "My",Space,Str "other",Space,Str "header"]
-,Para [Str "A",Space,Str "link",Space,Str "to",Space,Link ("",[],[]) [Str "My",Space,Str "header"] ("#my-header-1",""),Str "."]
-,Para [Str "Another",Space,Str "link",Space,Str "to",Space,Link ("",[],[]) [Str "it"] ("#my-header-1",""),Str "."]
-,Para [Str "Should",Space,Str "be",Space,Link ("",[],[]) [Str "case",Space,Str "insensitive"] ("#my-header-1",""),Str "."]
-,Para [Str "Link",Space,Str "to",Space,Link ("",[],[]) [Str "Explicit",Space,Str "header",Space,Str "attributes"] ("#foobar",""),Str "."]
-,Para [Str "But",Space,Str "this",Space,Str "is",Space,Str "not",Space,Str "a",Space,Str "link",Space,Str "to",Space,Link ("",[],[]) [Str "My",Space,Str "other",Space,Str "header"] ("/foo",""),Str ",",Space,Str "since",Space,Str "the",Space,Str "reference",Space,Str "is",Space,Str "defined."]
-,Header 2 ("foobar",["baz"],[("key","val")]) [Str "Explicit",Space,Str "header",Space,Str "attributes"]
-,BlockQuote
- [Header 2 ("foobar",["baz"],[("key","val")]) [Str "Header",Space,Str "attributes",Space,Str "inside",Space,Str "block",Space,Str "quote"]]
-,Header 2 ("line-blocks",[],[]) [Str "Line",Space,Str "blocks"]
-,LineBlock
- [[Str "But",Space,Str "can",Space,Str "a",Space,Str "bee",Space,Str "be",Space,Str "said",Space,Str "to",Space,Str "be"]
- ,[Str "\160\160\160\160or",Space,Str "not",Space,Str "to",Space,Str "be",Space,Str "an",Space,Str "entire",Space,Str "bee,"]
- ,[Str "\160\160\160\160\160\160\160\160when",Space,Str "half",Space,Str "the",Space,Str "bee",Space,Str "is",Space,Str "not",Space,Str "a",Space,Str "bee,"]
- ,[Str "\160\160\160\160\160\160\160\160\160\160\160\160due",Space,Str "to",Space,Str "some",Space,Str "ancient",Space,Str "injury?"]
- ,[]
- ,[Str "Continuation",Space,Str "line"]
- ,[Str "\160\160and",Space,Str "another"]]
-,Header 2 ("grid-tables",[],[]) [Str "Grid",Space,Str "Tables"]
-,Table [] [AlignDefault,AlignDefault,AlignDefault] [0.2638888888888889,0.16666666666666666,0.18055555555555555]
- [[Plain [Str "col",Space,Str "1"]]
- ,[Plain [Str "col",Space,Str "2"]]
- ,[Plain [Str "col",Space,Str "3"]]]
- [[[Plain [Str "r1",Space,Str "a",SoftBreak,Str "r1",Space,Str "bis"]]
-  ,[Plain [Str "b",SoftBreak,Str "b",Space,Str "2"]]
-  ,[Plain [Str "c",SoftBreak,Str "c",Space,Str "2"]]]
- ,[[Plain [Str "r2",Space,Str "d"]]
-  ,[Plain [Str "e"]]
-  ,[Plain [Str "f"]]]]
-,Para [Str "Headless"]
-,Table [] [AlignDefault,AlignDefault,AlignDefault] [0.2638888888888889,0.16666666666666666,0.18055555555555555]
- [[]
- ,[]
- ,[]]
- [[[Plain [Str "r1",Space,Str "a",SoftBreak,Str "r1",Space,Str "bis"]]
-  ,[Plain [Str "b",SoftBreak,Str "b",Space,Str "2"]]
-  ,[Plain [Str "c",SoftBreak,Str "c",Space,Str "2"]]]
- ,[[Plain [Str "r2",Space,Str "d"]]
-  ,[Plain [Str "e"]]
-  ,[Plain [Str "f"]]]]
-,Para [Str "With",Space,Str "alignments"]
-,Table [] [AlignRight,AlignLeft,AlignCenter] [0.2638888888888889,0.16666666666666666,0.18055555555555555]
- [[Plain [Str "col",Space,Str "1"]]
- ,[Plain [Str "col",Space,Str "2"]]
- ,[Plain [Str "col",Space,Str "3"]]]
- [[[Plain [Str "r1",Space,Str "a",SoftBreak,Str "r1",Space,Str "bis"]]
-  ,[Plain [Str "b",SoftBreak,Str "b",Space,Str "2"]]
-  ,[Plain [Str "c",SoftBreak,Str "c",Space,Str "2"]]]
- ,[[Plain [Str "r2",Space,Str "d"]]
-  ,[Plain [Str "e"]]
-  ,[Plain [Str "f"]]]]
-,Para [Str "Headless",Space,Str "with",Space,Str "alignments"]
-,Table [] [AlignRight,AlignLeft,AlignCenter] [0.2638888888888889,0.16666666666666666,0.18055555555555555]
- [[]
- ,[]
- ,[]]
- [[[Plain [Str "r1",Space,Str "a",SoftBreak,Str "r1",Space,Str "bis"]]
-  ,[Plain [Str "b",SoftBreak,Str "b",Space,Str "2"]]
-  ,[Plain [Str "c",SoftBreak,Str "c",Space,Str "2"]]]
- ,[[Plain [Str "r2",Space,Str "d"]]
-  ,[Plain [Str "e"]]
-  ,[Plain [Str "f"]]]]
-,Para [Str "Spaces",Space,Str "at",Space,Str "ends",Space,Str "of",Space,Str "lines"]
-,Table [] [AlignDefault,AlignDefault,AlignDefault] [0.2638888888888889,0.16666666666666666,0.18055555555555555]
- [[]
- ,[]
- ,[]]
- [[[Plain [Str "r1",Space,Str "a",SoftBreak,Str "r1",Space,Str "bis"]]
-  ,[Plain [Str "b",SoftBreak,Str "b",Space,Str "2"]]
-  ,[Plain [Str "c",SoftBreak,Str "c",Space,Str "2"]]]
- ,[[Plain [Str "r2",Space,Str "d"]]
-  ,[Plain [Str "e"]]
-  ,[Plain [Str "f"]]]]
-,Para [Str "Multiple",Space,Str "blocks",Space,Str "in",Space,Str "a",Space,Str "cell"]
-,Table [] [AlignDefault,AlignDefault,AlignDefault] [0.2638888888888889,0.16666666666666666,0.18055555555555555]
- [[]
- ,[]
- ,[]]
- [[[Header 1 ("col-1",[],[]) [Str "col",Space,Str "1"]
-   ,Plain [Str "col",Space,Str "1"]]
-  ,[Header 1 ("col-2",[],[]) [Str "col",Space,Str "2"]
-   ,Plain [Str "col",Space,Str "2"]]
-  ,[Header 1 ("col-3",[],[]) [Str "col",Space,Str "3"]
-   ,Plain [Str "col",Space,Str "3"]]]
- ,[[Para [Str "r1",Space,Str "a"]
-   ,Para [Str "r1",Space,Str "bis"]]
-  ,[BulletList
-    [[Plain [Str "b"]]
-    ,[Plain [Str "b",Space,Str "2"]]
-    ,[Plain [Str "b",Space,Str "2"]]]]
-  ,[Plain [Str "c",SoftBreak,Str "c",Space,Str "2",SoftBreak,Str "c",Space,Str "2"]]]]
-,Para [Str "Empty",Space,Str "cells"]
-,Table [] [AlignDefault,AlignDefault] [5.555555555555555e-2,5.555555555555555e-2]
- [[]
- ,[]]
- [[[]
-  ,[]]]
-,Header 2 ("entities-in-links-and-titles",[],[]) [Str "Entities",Space,Str "in",Space,Str "links",Space,Str "and",Space,Str "titles"]
-,Para [Link ("",[],[]) [Str "link"] ("/\252rl","\246\246!")]
-,Para [Link ("",[],[]) [Str "http://g\246\246gle.com"] ("http://g\246\246gle.com","")]
-,Para [Link ("",[],[]) [Str "me@ex\228mple.com"] ("mailto:me@ex\228mple.com","")]
-,Para [Link ("",[],[]) [Str "foobar"] ("/\252rl","\246\246!")]
-,Header 2 ("parentheses-in-urls",[],[]) [Str "Parentheses",Space,Str "in",Space,Str "URLs"]
-,Para [Link ("",[],[]) [Str "link"] ("/hi(there)","")]
-,Para [Link ("",[],[]) [Str "link"] ("/hithere)","")]
-,Para [Link ("",[],[]) [Str "linky"] ("hi_(there_(nested))","")]
-,Header 2 ("backslashes-in-link-references",[],[]) [Str "Backslashes",Space,Str "in",Space,Str "link",Space,Str "references"]
-,Para [Link ("",[],[]) [Str "*",RawInline (Format "tex") "\\a"] ("b","")]
-,Header 2 ("reference-link-fallbacks",[],[]) [Str "Reference",Space,Str "link",Space,Str "fallbacks"]
-,Para [Str "[",Emph [Str "not",Space,Str "a",Space,Str "link"],Str "]",Space,Str "[",Emph [Str "nope"],Str "]\8230"]
-,Header 2 ("reference-link-followed-by-a-citation",[],[]) [Str "Reference",Space,Str "link",Space,Str "followed",Space,Str "by",Space,Str "a",Space,Str "citation"]
-,Para [Str "MapReduce",Space,Str "is",Space,Str "a",Space,Str "paradigm",Space,Str "popularized",Space,Str "by",Space,Link ("",[],[]) [Str "Google"] ("http://google.com",""),Space,Cite [Citation {citationId = "mapreduce", citationPrefix = [], citationSuffix = [], citationMode = NormalCitation, citationNoteNum = 0, citationHash = 0}] [Str "[@mapreduce]"],Space,Str "as",Space,Str "its",SoftBreak,Str "most",Space,Str "vocal",Space,Str "proponent."]
-,Header 2 ("empty-reference-links",[],[]) [Str "Empty",Space,Str "reference",Space,Str "links"]
-,Para [Str "bar"]
-,Para [Link ("",[],[]) [Str "foo2"] ("","")]
-,Header 2 ("wrapping-shouldnt-introduce-new-list-items",[],[]) [Str "Wrapping",Space,Str "shouldn\8217t",Space,Str "introduce",Space,Str "new",Space,Str "list",Space,Str "items"]
-,BulletList
- [[Plain [Str "blah",Space,Str "blah",Space,Str "blah",Space,Str "blah",Space,Str "blah",Space,Str "blah",Space,Str "blah",Space,Str "blah",Space,Str "blah",Space,Str "blah",Space,Str "blah",Space,Str "blah",Space,Str "blah",Space,Str "blah",Space,Str "2015."]]]
-,Header 2 ("bracketed-spans",[],[]) [Str "Bracketed",Space,Str "spans"]
-,Para [Span ("id",["class"],[("key","val")]) [Emph [Str "foo"],Space,Str "bar",Space,Str "baz",Space,Link ("",[],[]) [Str "link"] ("url","")]]]
+Pandoc
+  Meta
+    { unMeta =
+        fromList
+          [ ( "author"
+            , MetaList
+                [ MetaInlines [ Str "Author" , Space , Str "One" ]
+                , MetaInlines [ Str "Author" , Space , Str "Two" ]
+                , MetaInlines [ Str "Author" , Space , Str "Three" ]
+                , MetaInlines [ Str "Author" , Space , Str "Four" ]
+                ]
+            )
+          , ( "title"
+            , MetaInlines
+                [ Str "Title"
+                , SoftBreak
+                , Str "spanning"
+                , Space
+                , Str "multiple"
+                , Space
+                , Str "lines"
+                ]
+            )
+          ]
+    }
+  [ Header
+      1
+      ( "additional-markdown-reader-tests" , [] , [] )
+      [ Str "Additional"
+      , Space
+      , Str "markdown"
+      , Space
+      , Str "reader"
+      , Space
+      , Str "tests"
+      ]
+  , Header
+      2
+      ( "blank-line-before-url-in-link-reference" , [] , [] )
+      [ Str "Blank"
+      , Space
+      , Str "line"
+      , Space
+      , Str "before"
+      , Space
+      , Str "URL"
+      , Space
+      , Str "in"
+      , Space
+      , Str "link"
+      , Space
+      , Str "reference"
+      ]
+  , Para
+      [ Link ( "" , [] , [] ) [ Str "foo" ] ( "/url" , "" )
+      , Space
+      , Str "and"
+      , Space
+      , Link ( "" , [] , [] ) [ Str "bar" ] ( "/url" , "title" )
+      ]
+  , Header
+      2
+      ( "raw-context-environments" , [] , [] )
+      [ Str "Raw"
+      , Space
+      , Str "ConTeXt"
+      , Space
+      , Str "environments"
+      ]
+  , RawBlock (Format "tex") "\\placeformula \\startformula"
+  , Para
+      [ Str "L_{1}"
+      , Space
+      , Str "="
+      , Space
+      , Str "L_{2}"
+      , SoftBreak
+      , RawInline (Format "tex") "\\stopformula"
+      ]
+  , RawBlock
+      (Format "tex")
+      "\\start[a2]\n\\start[a2]\n\\stop[a2]\n\\stop[a2]"
+  , Header
+      2
+      ( "raw-latex-environments" , [] , [] )
+      [ Str "Raw"
+      , Space
+      , Str "LaTeX"
+      , Space
+      , Str "environments"
+      ]
+  , RawBlock
+      (Format "tex")
+      "\\begin{center}\n\\begin{tikzpicture}[baseline={([yshift=+-.5ex]current bounding box.center)}, level distance=24pt]\n\\Tree [.{S} [.NP John\\index{i} ] [.VP [.V likes ] [.NP himself\\index{i,*j} ]]]\n\\end{tikzpicture}\n\\end{center}"
+  , Header
+      2
+      ( "urls-with-spaces-and-punctuation" , [] , [] )
+      [ Str "URLs"
+      , Space
+      , Str "with"
+      , Space
+      , Str "spaces"
+      , Space
+      , Str "and"
+      , Space
+      , Str "punctuation"
+      ]
+  , Para
+      [ Link
+          ( "" , [] , [] ) [ Str "foo" ] ( "/bar%20and%20baz" , "" )
+      , SoftBreak
+      , Link
+          ( "" , [] , [] ) [ Str "foo" ] ( "/bar%20and%20baz" , "" )
+      , SoftBreak
+      , Link
+          ( "" , [] , [] ) [ Str "foo" ] ( "/bar%20and%20baz" , "" )
+      , SoftBreak
+      , Link
+          ( "" , [] , [] ) [ Str "foo" ] ( "bar%20baz" , "title" )
+      ]
+  , Para
+      [ Link ( "" , [] , [] ) [ Str "baz" ] ( "/foo%20foo" , "" )
+      , Space
+      , Link ( "" , [] , [] ) [ Str "bam" ] ( "/foo%20fee" , "" )
+      , Space
+      , Link
+          ( "" , [] , [] )
+          [ Str "bork" ]
+          ( "/foo/zee%20zob" , "title" )
+      ]
+  , Para
+      [ Link
+          ( "" , [] , [] )
+          [ Str "Ward\8217s" , Space , Str "method." ]
+          ( "http://en.wikipedia.org/wiki/Ward's_method" , "" )
+      ]
+  , Header
+      2
+      ( "horizontal-rules-with-spaces-at-end" , [] , [] )
+      [ Str "Horizontal"
+      , Space
+      , Str "rules"
+      , Space
+      , Str "with"
+      , Space
+      , Str "spaces"
+      , Space
+      , Str "at"
+      , Space
+      , Str "end"
+      ]
+  , HorizontalRule
+  , HorizontalRule
+  , Header
+      2
+      ( "raw-html-before-header" , [] , [] )
+      [ Str "Raw"
+      , Space
+      , Str "HTML"
+      , Space
+      , Str "before"
+      , Space
+      , Str "header"
+      ]
+  , Para
+      [ RawInline (Format "html") "<a>"
+      , RawInline (Format "html") "</a>"
+      ]
+  , Header
+      3
+      ( "my-header" , [] , [] )
+      [ Str "my" , Space , Str "header" ]
+  , Header
+      2
+      ( "in-math" , [] , [] )
+      [ Str "$" , Space , Str "in" , Space , Str "math" ]
+  , Para [ Math InlineMath "\\$2 + \\$3" ]
+  , Para
+      [ Math InlineMath "x = \\text{the $n$th root of $y$}" ]
+  , Para
+      [ Str "This"
+      , Space
+      , Str "should"
+      , Space
+      , Str "not"
+      , Space
+      , Str "be"
+      , Space
+      , Str "math:"
+      ]
+  , Para
+      [ Str "$PATH" , Space , Str "90" , Space , Str "$PATH" ]
+  , Header
+      2
+      ( "commented-out-list-item" , [] , [] )
+      [ Str "Commented-out"
+      , Space
+      , Str "list"
+      , Space
+      , Str "item"
+      ]
+  , BulletList
+      [ [ Plain [ Str "one" , SoftBreak , Str "<!\8211" ] ]
+      , [ Plain [ Str "two" , SoftBreak , Str "\8211>" ] ]
+      , [ Plain [ Str "three" ] ]
+      ]
+  , Header
+      2
+      ( "indented-code-at-beginning-of-list" , [] , [] )
+      [ Str "Indented"
+      , Space
+      , Str "code"
+      , Space
+      , Str "at"
+      , Space
+      , Str "beginning"
+      , Space
+      , Str "of"
+      , Space
+      , Str "list"
+      ]
+  , BulletList
+      [ [ CodeBlock ( "" , [] , [] ) "code\ncode"
+        , OrderedList
+            ( 1 , Decimal , Period )
+            [ [ CodeBlock ( "" , [] , [] ) "code\ncode" ]
+            , [ CodeBlock ( "" , [] , [] ) "code\ncode" ]
+            ]
+        , BulletList
+            [ [ CodeBlock ( "" , [] , [] ) "code\ncode" ]
+            , [ Plain [ Str "no" , Space , Str "code" ] ]
+            ]
+        ]
+      ]
+  , Header
+      2
+      ( "backslash-newline" , [] , [] )
+      [ Str "Backslash" , Space , Str "newline" ]
+  , Para [ Str "hi" , LineBreak , Str "there" ]
+  , Header
+      2
+      ( "code-spans" , [] , [] )
+      [ Str "Code" , Space , Str "spans" ]
+  , Para [ Code ( "" , [] , [] ) "hi\\" ]
+  , Para [ Code ( "" , [] , [] ) "hi there" ]
+  , Para [ Code ( "" , [] , [] ) "hi````there" ]
+  , Para [ Str "`hi" ]
+  , Para [ Str "there`" ]
+  , Header
+      2
+      ( "multilingual-urls" , [] , [] )
+      [ Str "Multilingual" , Space , Str "URLs" ]
+  , Para
+      [ Link
+          ( "" , [ "uri" ] , [] )
+          [ Str "http://\27979.com?\27979=\27979" ]
+          ( "http://\27979.com?\27979=\27979" , "" )
+      ]
+  , Para
+      [ Link
+          ( "" , [] , [] )
+          [ Str "foo" ]
+          ( "/bar/\27979?x=\27979" , "title" )
+      ]
+  , Para
+      [ Link
+          ( "" , [ "email" ] , [] )
+          [ Str "\27979@foo.\27979.baz" ]
+          ( "mailto:\27979@foo.\27979.baz" , "" )
+      ]
+  , Header
+      2
+      ( "numbered-examples" , [] , [] )
+      [ Str "Numbered" , Space , Str "examples" ]
+  , OrderedList
+      ( 1 , Example , TwoParens )
+      [ [ Plain [ Str "First" , Space , Str "example." ] ]
+      , [ Plain [ Str "Second" , Space , Str "example." ] ]
+      ]
+  , Para
+      [ Str "Explanation"
+      , Space
+      , Str "of"
+      , Space
+      , Str "examples"
+      , Space
+      , Str "(2)"
+      , Space
+      , Str "and"
+      , Space
+      , Str "(3)."
+      ]
+  , OrderedList
+      ( 3 , Example , TwoParens )
+      [ [ Plain [ Str "Third" , Space , Str "example." ] ] ]
+  , Header 2 ( "macros" , [] , [] ) [ Str "Macros" ]
+  , RawBlock
+      (Format "tex")
+      "\\newcommand{\\tuple}[1]{\\langle #1 \\rangle}"
+  , Para [ Math InlineMath "\\langle x,y \\rangle" ]
+  , Header
+      2
+      ( "case-insensitive-references" , [] , [] )
+      [ Str "Case-insensitive" , Space , Str "references" ]
+  , Para
+      [ Link ( "" , [] , [] ) [ Str "Fum" ] ( "/fum" , "" ) ]
+  , Para
+      [ Link ( "" , [] , [] ) [ Str "FUM" ] ( "/fum" , "" ) ]
+  , Para
+      [ Link ( "" , [] , [] ) [ Str "bat" ] ( "/bat" , "" ) ]
+  , Header
+      2
+      ( "curly-smart-quotes" , [] , [] )
+      [ Str "Curly" , Space , Str "smart" , Space , Str "quotes" ]
+  , Para [ Str "\8220Hi\8221" ]
+  , Para [ Str "\8216Hi\8217" ]
+  , Header
+      2
+      ( "consecutive-lists" , [] , [] )
+      [ Str "Consecutive" , Space , Str "lists" ]
+  , BulletList
+      [ [ Plain [ Str "one" ] ] , [ Plain [ Str "two" ] ] ]
+  , OrderedList
+      ( 1 , Decimal , Period )
+      [ [ Plain [ Str "one" ] ] , [ Plain [ Str "two" ] ] ]
+  , OrderedList
+      ( 1 , LowerAlpha , Period )
+      [ [ Plain [ Str "one" ] ] , [ Plain [ Str "two" ] ] ]
+  , Header
+      2
+      ( "implicit-header-references" , [] , [] )
+      [ Str "Implicit"
+      , Space
+      , Str "header"
+      , Space
+      , Str "references"
+      ]
+  , Header
+      3
+      ( "my-header-1" , [] , [] )
+      [ Str "My" , Space , Str "header" ]
+  , Header
+      3
+      ( "my-other-header" , [] , [] )
+      [ Str "My" , Space , Str "other" , Space , Str "header" ]
+  , Para
+      [ Str "A"
+      , Space
+      , Str "link"
+      , Space
+      , Str "to"
+      , Space
+      , Link
+          ( "" , [] , [] )
+          [ Str "My" , Space , Str "header" ]
+          ( "#my-header" , "" )
+      , Str "."
+      ]
+  , Para
+      [ Str "Another"
+      , Space
+      , Str "link"
+      , Space
+      , Str "to"
+      , Space
+      , Link ( "" , [] , [] ) [ Str "it" ] ( "#my-header" , "" )
+      , Str "."
+      ]
+  , Para
+      [ Str "Should"
+      , Space
+      , Str "be"
+      , Space
+      , Link
+          ( "" , [] , [] )
+          [ Str "case" , Space , Str "insensitive" ]
+          ( "#my-header" , "" )
+      , Str "."
+      ]
+  , Para
+      [ Str "Link"
+      , Space
+      , Str "to"
+      , Space
+      , Link
+          ( "" , [] , [] )
+          [ Str "Explicit"
+          , Space
+          , Str "header"
+          , Space
+          , Str "attributes"
+          ]
+          ( "#foobar" , "" )
+      , Str "."
+      ]
+  , Para
+      [ Str "But"
+      , Space
+      , Str "this"
+      , Space
+      , Str "is"
+      , Space
+      , Str "not"
+      , Space
+      , Str "a"
+      , Space
+      , Str "link"
+      , Space
+      , Str "to"
+      , Space
+      , Link
+          ( "" , [] , [] )
+          [ Str "My" , Space , Str "other" , Space , Str "header" ]
+          ( "/foo" , "" )
+      , Str ","
+      , Space
+      , Str "since"
+      , Space
+      , Str "the"
+      , Space
+      , Str "reference"
+      , Space
+      , Str "is"
+      , Space
+      , Str "defined."
+      ]
+  , Header
+      2
+      ( "foobar" , [ "baz" ] , [ ( "key" , "val" ) ] )
+      [ Str "Explicit"
+      , Space
+      , Str "header"
+      , Space
+      , Str "attributes"
+      ]
+  , BlockQuote
+      [ Header
+          2
+          ( "foobar" , [ "baz" ] , [ ( "key" , "val" ) ] )
+          [ Str "Header"
+          , Space
+          , Str "attributes"
+          , Space
+          , Str "inside"
+          , Space
+          , Str "block"
+          , Space
+          , Str "quote"
+          ]
+      ]
+  , Header
+      2
+      ( "line-blocks" , [] , [] )
+      [ Str "Line" , Space , Str "blocks" ]
+  , LineBlock
+      [ [ Str "But"
+        , Space
+        , Str "can"
+        , Space
+        , Str "a"
+        , Space
+        , Str "bee"
+        , Space
+        , Str "be"
+        , Space
+        , Str "said"
+        , Space
+        , Str "to"
+        , Space
+        , Str "be"
+        ]
+      , [ Str "\160\160\160\160or"
+        , Space
+        , Str "not"
+        , Space
+        , Str "to"
+        , Space
+        , Str "be"
+        , Space
+        , Str "an"
+        , Space
+        , Str "entire"
+        , Space
+        , Str "bee,"
+        ]
+      , [ Str "\160\160\160\160\160\160\160\160when"
+        , Space
+        , Str "half"
+        , Space
+        , Str "the"
+        , Space
+        , Str "bee"
+        , Space
+        , Str "is"
+        , Space
+        , Str "not"
+        , Space
+        , Str "a"
+        , Space
+        , Str "bee,"
+        ]
+      , [ Str
+            "\160\160\160\160\160\160\160\160\160\160\160\160due"
+        , Space
+        , Str "to"
+        , Space
+        , Str "some"
+        , Space
+        , Str "ancient"
+        , Space
+        , Str "injury?"
+        ]
+      , []
+      , [ Str "Continuation" , Space , Str "line" ]
+      , [ Str "\160\160and" , Space , Str "another" ]
+      ]
+  , Header
+      2
+      ( "grid-tables" , [] , [] )
+      [ Str "Grid" , Space , Str "Tables" ]
+  , Table
+      ( "" , [] , [] )
+      (Caption Nothing [])
+      [ ( AlignDefault , ColWidth 0.2638888888888889 )
+      , ( AlignDefault , ColWidth 0.16666666666666666 )
+      , ( AlignDefault , ColWidth 0.18055555555555555 )
+      ]
+      (TableHead
+         ( "" , [] , [] )
+         [ Row
+             ( "" , [] , [] )
+             [ Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "col" , Space , Str "1" ] ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "col" , Space , Str "2" ] ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "col" , Space , Str "3" ] ]
+             ]
+         ])
+      [ TableBody
+          ( "" , [] , [] )
+          (RowHeadColumns 0)
+          []
+          [ Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain
+                      [ Str "r1"
+                      , Space
+                      , Str "a"
+                      , SoftBreak
+                      , Str "r1"
+                      , Space
+                      , Str "bis"
+                      ]
+                  ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain
+                      [ Str "b"
+                      , SoftBreak
+                      , Str "b"
+                      , Space
+                      , Str "2"
+                      ]
+                  ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain
+                      [ Str "c"
+                      , SoftBreak
+                      , Str "c"
+                      , Space
+                      , Str "2"
+                      ]
+                  ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "r2" , Space , Str "d" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "e" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "f" ] ]
+              ]
+          ]
+      ]
+      (TableFoot ( "" , [] , [] ) [])
+  , Para [ Str "Headless" ]
+  , Table
+      ( "" , [] , [] )
+      (Caption Nothing [])
+      [ ( AlignDefault , ColWidth 0.2638888888888889 )
+      , ( AlignDefault , ColWidth 0.16666666666666666 )
+      , ( AlignDefault , ColWidth 0.18055555555555555 )
+      ]
+      (TableHead ( "" , [] , [] ) [])
+      [ TableBody
+          ( "" , [] , [] )
+          (RowHeadColumns 0)
+          []
+          [ Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain
+                      [ Str "r1"
+                      , Space
+                      , Str "a"
+                      , SoftBreak
+                      , Str "r1"
+                      , Space
+                      , Str "bis"
+                      ]
+                  ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain
+                      [ Str "b"
+                      , SoftBreak
+                      , Str "b"
+                      , Space
+                      , Str "2"
+                      ]
+                  ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain
+                      [ Str "c"
+                      , SoftBreak
+                      , Str "c"
+                      , Space
+                      , Str "2"
+                      ]
+                  ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "r2" , Space , Str "d" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "e" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "f" ] ]
+              ]
+          ]
+      ]
+      (TableFoot ( "" , [] , [] ) [])
+  , Para [ Str "With" , Space , Str "alignments" ]
+  , Table
+      ( "" , [] , [] )
+      (Caption Nothing [])
+      [ ( AlignRight , ColWidth 0.2638888888888889 )
+      , ( AlignLeft , ColWidth 0.16666666666666666 )
+      , ( AlignCenter , ColWidth 0.18055555555555555 )
+      ]
+      (TableHead
+         ( "" , [] , [] )
+         [ Row
+             ( "" , [] , [] )
+             [ Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "col" , Space , Str "1" ] ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "col" , Space , Str "2" ] ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "col" , Space , Str "3" ] ]
+             ]
+         ])
+      [ TableBody
+          ( "" , [] , [] )
+          (RowHeadColumns 0)
+          []
+          [ Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain
+                      [ Str "r1"
+                      , Space
+                      , Str "a"
+                      , SoftBreak
+                      , Str "r1"
+                      , Space
+                      , Str "bis"
+                      ]
+                  ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain
+                      [ Str "b"
+                      , SoftBreak
+                      , Str "b"
+                      , Space
+                      , Str "2"
+                      ]
+                  ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain
+                      [ Str "c"
+                      , SoftBreak
+                      , Str "c"
+                      , Space
+                      , Str "2"
+                      ]
+                  ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "r2" , Space , Str "d" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "e" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "f" ] ]
+              ]
+          ]
+      ]
+      (TableFoot ( "" , [] , [] ) [])
+  , Para
+      [ Str "Headless"
+      , Space
+      , Str "with"
+      , Space
+      , Str "alignments"
+      ]
+  , Table
+      ( "" , [] , [] )
+      (Caption Nothing [])
+      [ ( AlignRight , ColWidth 0.2638888888888889 )
+      , ( AlignLeft , ColWidth 0.16666666666666666 )
+      , ( AlignCenter , ColWidth 0.18055555555555555 )
+      ]
+      (TableHead ( "" , [] , [] ) [])
+      [ TableBody
+          ( "" , [] , [] )
+          (RowHeadColumns 0)
+          []
+          [ Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain
+                      [ Str "r1"
+                      , Space
+                      , Str "a"
+                      , SoftBreak
+                      , Str "r1"
+                      , Space
+                      , Str "bis"
+                      ]
+                  ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain
+                      [ Str "b"
+                      , SoftBreak
+                      , Str "b"
+                      , Space
+                      , Str "2"
+                      ]
+                  ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain
+                      [ Str "c"
+                      , SoftBreak
+                      , Str "c"
+                      , Space
+                      , Str "2"
+                      ]
+                  ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "r2" , Space , Str "d" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "e" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "f" ] ]
+              ]
+          ]
+      ]
+      (TableFoot ( "" , [] , [] ) [])
+  , Para
+      [ Str "Spaces"
+      , Space
+      , Str "at"
+      , Space
+      , Str "ends"
+      , Space
+      , Str "of"
+      , Space
+      , Str "lines"
+      ]
+  , Table
+      ( "" , [] , [] )
+      (Caption Nothing [])
+      [ ( AlignDefault , ColWidth 0.2638888888888889 )
+      , ( AlignDefault , ColWidth 0.16666666666666666 )
+      , ( AlignDefault , ColWidth 0.18055555555555555 )
+      ]
+      (TableHead ( "" , [] , [] ) [])
+      [ TableBody
+          ( "" , [] , [] )
+          (RowHeadColumns 0)
+          []
+          [ Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain
+                      [ Str "r1"
+                      , Space
+                      , Str "a"
+                      , SoftBreak
+                      , Str "r1"
+                      , Space
+                      , Str "bis"
+                      ]
+                  ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain
+                      [ Str "b"
+                      , SoftBreak
+                      , Str "b"
+                      , Space
+                      , Str "2"
+                      ]
+                  ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain
+                      [ Str "c"
+                      , SoftBreak
+                      , Str "c"
+                      , Space
+                      , Str "2"
+                      ]
+                  ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "r2" , Space , Str "d" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "e" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "f" ] ]
+              ]
+          ]
+      ]
+      (TableFoot ( "" , [] , [] ) [])
+  , Para
+      [ Str "Multiple"
+      , Space
+      , Str "blocks"
+      , Space
+      , Str "in"
+      , Space
+      , Str "a"
+      , Space
+      , Str "cell"
+      ]
+  , Table
+      ( "" , [] , [] )
+      (Caption Nothing [])
+      [ ( AlignDefault , ColWidth 0.2638888888888889 )
+      , ( AlignDefault , ColWidth 0.16666666666666666 )
+      , ( AlignDefault , ColWidth 0.18055555555555555 )
+      ]
+      (TableHead ( "" , [] , [] ) [])
+      [ TableBody
+          ( "" , [] , [] )
+          (RowHeadColumns 0)
+          []
+          [ Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Header
+                      1
+                      ( "col-1" , [] , [] )
+                      [ Str "col" , Space , Str "1" ]
+                  , Para [ Str "col" , Space , Str "1" ]
+                  ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Header
+                      1
+                      ( "col-2" , [] , [] )
+                      [ Str "col" , Space , Str "2" ]
+                  , Para [ Str "col" , Space , Str "2" ]
+                  ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Header
+                      1
+                      ( "col-3" , [] , [] )
+                      [ Str "col" , Space , Str "3" ]
+                  , Para [ Str "col" , Space , Str "3" ]
+                  ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para [ Str "r1" , Space , Str "a" ]
+                  , Para [ Str "r1" , Space , Str "bis" ]
+                  ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ BulletList
+                      [ [ Plain [ Str "b" ] ]
+                      , [ Plain [ Str "b" , Space , Str "2" ] ]
+                      , [ Plain [ Str "b" , Space , Str "2" ] ]
+                      ]
+                  ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain
+                      [ Str "c"
+                      , SoftBreak
+                      , Str "c"
+                      , Space
+                      , Str "2"
+                      , SoftBreak
+                      , Str "c"
+                      , Space
+                      , Str "2"
+                      ]
+                  ]
+              ]
+          ]
+      ]
+      (TableFoot ( "" , [] , [] ) [])
+  , Para
+      [ Str "East"
+      , Space
+      , Str "Asian"
+      , Space
+      , Str "characters"
+      , Space
+      , Str "have"
+      , Space
+      , Str "double"
+      , Space
+      , Str "width"
+      ]
+  , Table
+      ( "" , [] , [] )
+      (Caption Nothing [])
+      [ ( AlignDefault , ColWidth 4.1666666666666664e-2 )
+      , ( AlignDefault , ColWidth 6.944444444444445e-2 )
+      ]
+      (TableHead ( "" , [] , [] ) [])
+      [ TableBody
+          ( "" , [] , [] )
+          (RowHeadColumns 0)
+          []
+          [ Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "\39770" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "fish" ] ]
+              ]
+          ]
+      ]
+      (TableFoot ( "" , [] , [] ) [])
+  , Para
+      [ Str "Zero-width"
+      , Space
+      , Str "space"
+      , Space
+      , Str "in"
+      , Space
+      , Str "German"
+      ]
+  , Table
+      ( "" , [] , [] )
+      (Caption Nothing [])
+      [ ( AlignDefault , ColWidth 0.1111111111111111 )
+      , ( AlignDefault , ColWidth 0.1111111111111111 )
+      ]
+      (TableHead ( "" , [] , [] ) [])
+      [ TableBody
+          ( "" , [] , [] )
+          (RowHeadColumns 0)
+          []
+          [ Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "German" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "English" ] ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "Auf\8204lage" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "edition" ] ]
+              ]
+          ]
+      ]
+      (TableFoot ( "" , [] , [] ) [])
+  , Para
+      [ Str "Zero-width"
+      , Space
+      , Str "non-joiner"
+      , Space
+      , Str "in"
+      , Space
+      , Str "Persian"
+      ]
+  , Table
+      ( "" , [] , [] )
+      (Caption Nothing [])
+      [ ( AlignDefault , ColWidth 0.1111111111111111 )
+      , ( AlignDefault , ColWidth 0.1388888888888889 )
+      ]
+      (TableHead ( "" , [] , [] ) [])
+      [ TableBody
+          ( "" , [] , [] )
+          (RowHeadColumns 0)
+          []
+          [ Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain
+                      [ Str "\1605\1740\8204\1582\1608\1575\1607\1605" ]
+                  ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain
+                      [ Str "I"
+                      , Space
+                      , Str "want"
+                      , Space
+                      , Str "to"
+                      ]
+                  ]
+              ]
+          ]
+      ]
+      (TableFoot ( "" , [] , [] ) [])
+  , Para [ Str "Empty" , Space , Str "cells" ]
+  , Table
+      ( "" , [] , [] )
+      (Caption Nothing [])
+      [ ( AlignDefault , ColWidth 5.555555555555555e-2 )
+      , ( AlignDefault , ColWidth 5.555555555555555e-2 )
+      ]
+      (TableHead ( "" , [] , [] ) [])
+      [ TableBody
+          ( "" , [] , [] )
+          (RowHeadColumns 0)
+          []
+          [ Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  []
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  []
+              ]
+          ]
+      ]
+      (TableFoot ( "" , [] , [] ) [])
+  , Para
+      [ Str "Table"
+      , Space
+      , Str "with"
+      , Space
+      , Str "cells"
+      , Space
+      , Str "spanning"
+      , Space
+      , Str "multiple"
+      , Space
+      , Str "rows"
+      , Space
+      , Str "or"
+      , Space
+      , Str "columns:"
+      ]
+  , Table
+      ( "" , [] , [] )
+      (Caption Nothing [])
+      [ ( AlignDefault , ColWidth 0.19444444444444445 )
+      , ( AlignDefault , ColWidth 0.1111111111111111 )
+      , ( AlignDefault , ColWidth 0.1527777777777778 )
+      ]
+      (TableHead
+         ( "" , [] , [] )
+         [ Row
+             ( "" , [] , [] )
+             [ Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 2)
+                 [ Plain [ Str "Property" ] ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "Earth" ] ]
+             ]
+         ])
+      [ TableBody
+          ( "" , [] , [] )
+          (RowHeadColumns 0)
+          []
+          [ Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 3)
+                  (ColSpan 1)
+                  [ Plain
+                      [ Str "Temperature"
+                      , SoftBreak
+                      , Str "1961-1990"
+                      ]
+                  ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "min" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "-89.2" , Space , Str "\176C" ] ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "mean" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "14" , Space , Str "\176C" ] ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "min" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "56.7" , Space , Str "\176C" ] ]
+              ]
+          ]
+      ]
+      (TableFoot ( "" , [] , [] ) [])
+  , Para
+      [ Str "Table"
+      , Space
+      , Str "with"
+      , Space
+      , Str "complex"
+      , Space
+      , Str "header:"
+      ]
+  , Table
+      ( "" , [] , [] )
+      (Caption Nothing [])
+      [ ( AlignDefault , ColWidth 0.3055555555555556 )
+      , ( AlignDefault , ColWidth 0.1111111111111111 )
+      , ( AlignDefault , ColWidth 0.1111111111111111 )
+      , ( AlignDefault , ColWidth 0.1111111111111111 )
+      ]
+      (TableHead
+         ( "" , [] , [] )
+         [ Row
+             ( "" , [] , [] )
+             [ Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 2)
+                 (ColSpan 1)
+                 [ Plain [ Str "Location" ] ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 3)
+                 [ Plain
+                     [ Str "Temperature"
+                     , Space
+                     , Str "1961-1990"
+                     , SoftBreak
+                     , Str "in"
+                     , Space
+                     , Str "degree"
+                     , Space
+                     , Str "Celsius"
+                     ]
+                 ]
+             ]
+         , Row
+             ( "" , [] , [] )
+             [ Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "min" ] ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "mean" ] ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "max" ] ]
+             ]
+         ])
+      [ TableBody
+          ( "" , [] , [] )
+          (RowHeadColumns 0)
+          []
+          [ Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "Antarctica" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "-89.2" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "N/A" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "19.8" ] ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "Earth" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "-89.2" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "14" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "56.7" ] ]
+              ]
+          ]
+      ]
+      (TableFoot ( "" , [] , [] ) [])
+  , Header
+      2
+      ( "entities-in-links-and-titles" , [] , [] )
+      [ Str "Entities"
+      , Space
+      , Str "in"
+      , Space
+      , Str "links"
+      , Space
+      , Str "and"
+      , Space
+      , Str "titles"
+      ]
+  , Para
+      [ Link
+          ( "" , [] , [] ) [ Str "link" ] ( "/\252rl" , "\246\246!" )
+      ]
+  , Para
+      [ Link
+          ( "" , [ "uri" ] , [] )
+          [ Str "http://g\246\246gle.com" ]
+          ( "http://g\246\246gle.com" , "" )
+      ]
+  , Para
+      [ Link
+          ( "" , [ "email" ] , [] )
+          [ Str "me@ex\228mple.com" ]
+          ( "mailto:me@ex\228mple.com" , "" )
+      ]
+  , Para
+      [ Link
+          ( "" , [] , [] )
+          [ Str "foobar" ]
+          ( "/\252rl" , "\246\246!" )
+      ]
+  , Header
+      2
+      ( "parentheses-in-urls" , [] , [] )
+      [ Str "Parentheses"
+      , Space
+      , Str "in"
+      , Space
+      , Str "URLs"
+      ]
+  , Para
+      [ Link ( "" , [] , [] ) [ Str "link" ] ( "/hi(there)" , "" )
+      ]
+  , Para
+      [ Link ( "" , [] , [] ) [ Str "link" ] ( "/hithere)" , "" )
+      ]
+  , Para
+      [ Link
+          ( "" , [] , [] )
+          [ Str "linky" ]
+          ( "hi_(there_(nested))" , "" )
+      ]
+  , Header
+      2
+      ( "backslashes-in-link-references" , [] , [] )
+      [ Str "Backslashes"
+      , Space
+      , Str "in"
+      , Space
+      , Str "link"
+      , Space
+      , Str "references"
+      ]
+  , Para
+      [ Link
+          ( "" , [] , [] )
+          [ Str "*" , RawInline (Format "tex") "\\a" ]
+          ( "b" , "" )
+      ]
+  , Header
+      2
+      ( "reference-link-fallbacks" , [] , [] )
+      [ Str "Reference"
+      , Space
+      , Str "link"
+      , Space
+      , Str "fallbacks"
+      ]
+  , Para
+      [ Str "["
+      , Emph [ Str "not" , Space , Str "a" , Space , Str "link" ]
+      , Str "]"
+      , Space
+      , Str "["
+      , Emph [ Str "nope" ]
+      , Str "]\8230"
+      ]
+  , Header
+      2
+      ( "reference-link-followed-by-a-citation" , [] , [] )
+      [ Str "Reference"
+      , Space
+      , Str "link"
+      , Space
+      , Str "followed"
+      , Space
+      , Str "by"
+      , Space
+      , Str "a"
+      , Space
+      , Str "citation"
+      ]
+  , Para
+      [ Str "MapReduce"
+      , Space
+      , Str "is"
+      , Space
+      , Str "a"
+      , Space
+      , Str "paradigm"
+      , Space
+      , Str "popularized"
+      , Space
+      , Str "by"
+      , Space
+      , Link
+          ( "" , [] , [] )
+          [ Str "Google" ]
+          ( "http://google.com" , "" )
+      , Space
+      , Cite
+          [ Citation
+              { citationId = "mapreduce"
+              , citationPrefix = []
+              , citationSuffix = []
+              , citationMode = NormalCitation
+              , citationNoteNum = 2
+              , citationHash = 0
+              }
+          ]
+          [ Str "[@mapreduce]" ]
+      , Space
+      , Str "as"
+      , Space
+      , Str "its"
+      , SoftBreak
+      , Str "most"
+      , Space
+      , Str "vocal"
+      , Space
+      , Str "proponent."
+      ]
+  , Header
+      2
+      ( "empty-reference-links" , [] , [] )
+      [ Str "Empty"
+      , Space
+      , Str "reference"
+      , Space
+      , Str "links"
+      ]
+  , Para [ Str "bar" ]
+  , Para [ Link ( "" , [] , [] ) [ Str "foo2" ] ( "" , "" ) ]
+  , Header
+      2
+      ( "wrapping-shouldnt-introduce-new-list-items" , [] , [] )
+      [ Str "Wrapping"
+      , Space
+      , Str "shouldn\8217t"
+      , Space
+      , Str "introduce"
+      , Space
+      , Str "new"
+      , Space
+      , Str "list"
+      , Space
+      , Str "items"
+      ]
+  , BulletList
+      [ [ Plain
+            [ Str "blah"
+            , Space
+            , Str "blah"
+            , Space
+            , Str "blah"
+            , Space
+            , Str "blah"
+            , Space
+            , Str "blah"
+            , Space
+            , Str "blah"
+            , Space
+            , Str "blah"
+            , Space
+            , Str "blah"
+            , Space
+            , Str "blah"
+            , Space
+            , Str "blah"
+            , Space
+            , Str "blah"
+            , Space
+            , Str "blah"
+            , Space
+            , Str "blah"
+            , Space
+            , Str "blah"
+            , Space
+            , Str "2015."
+            ]
+        ]
+      ]
+  , Header
+      2
+      ( "bracketed-spans" , [] , [] )
+      [ Str "Bracketed" , Space , Str "spans" ]
+  , Para
+      [ Span
+          ( "id" , [ "class" ] , [ ( "key" , "val" ) ] )
+          [ Emph [ Str "foo" ]
+          , Space
+          , Str "bar"
+          , Space
+          , Str "baz"
+          , Space
+          , Link ( "" , [] , [] ) [ Str "link" ] ( "url" , "" )
+          ]
+      ]
+  ]
diff --git a/test/markdown-reader-more.txt b/test/markdown-reader-more.txt
--- a/test/markdown-reader-more.txt
+++ b/test/markdown-reader-more.txt
@@ -260,11 +260,57 @@
 | r1 bis           | - b 2     | c 2        |
 +------------------+-----------+------------+
 
+East Asian characters have double width
+
++--+----+
+|魚|fish|
++--+----+
+
+Zero-width space in German
+
++-------+-------+
+|German |English|
++-------+-------+
+|Auf‌lage|edition|
++-------+-------+
+
+Zero-width non-joiner in Persian
+
++-------+---------+
+|می‌خواهم|I want to|
++-------+---------+
+
 Empty cells
 
 +---+---+
 |   |   |
 +---+---+
+
+
+Table with cells spanning multiple rows or columns:
+
++---------------------+----------+
+| Property            | Earth    |
++=============+=======+==========+
+|             | min   | -89.2 °C |
+| Temperature +-------+----------+
+| 1961-1990   | mean  | 14 °C    |
+|             +-------+----------+
+|             | min   | 56.7 °C  |
++-------------+-------+----------+
+
+Table with complex header:
+
++---------------------+-----------------------+
+| Location            | Temperature 1961-1990 |
+|                     | in degree Celsius     |
+|                     +-------+-------+-------+
+|                     | min   | mean  | max   |
++=====================+=======+=======+=======+
+| Antarctica          | -89.2 | N/A   | 19.8  |
++---------------------+-------+-------+-------+
+| Earth               | -89.2 | 14    | 56.7  |
++---------------------+-------+-------+-------+
 
 ## Entities in links and titles
 
diff --git a/test/mediawiki-reader.native b/test/mediawiki-reader.native
--- a/test/mediawiki-reader.native
+++ b/test/mediawiki-reader.native
@@ -1,262 +1,1395 @@
-Pandoc (Meta {unMeta = fromList []})
-[Header 1 ("header",[],[]) [Str "header"]
-,Header 2 ("header-level-two",[],[]) [Str "header",Space,Str "level",Space,Str "two"]
-,Header 3 ("header-level-3",[],[]) [Str "header",Space,Str "level",Space,Str "3"]
-,Header 4 ("header-level-four",[],[]) [Str "header",Space,Emph [Str "level"],Space,Str "four"]
-,Header 5 ("header-level-5",[],[]) [Str "header",Space,Str "level",Space,Str "5"]
-,Header 6 ("header-level-6",[],[]) [Str "header",Space,Str "level",Space,Str "6"]
-,Para [Str "=======",Space,Str "not",Space,Str "a",Space,Str "header",Space,Str "========"]
-,Para [Code ("",[],[]) "==\160not\160a\160header\160=="]
-,Header 2 ("emph-and-strong",[],[]) [Str "emph",Space,Str "and",Space,Str "strong"]
-,Para [Emph [Str "emph"],Space,Strong [Str "strong"]]
-,Para [Strong [Emph [Str "strong",Space,Str "and",Space,Str "emph"]]]
-,Para [Strong [Emph [Str "emph",Space,Str "inside"],Space,Str "strong"]]
-,Para [Strong [Str "strong",Space,Str "with",Space,Emph [Str "emph"]]]
-,Para [Emph [Strong [Str "strong",Space,Str "inside"],Space,Str "emph"]]
-,Header 2 ("horizontal-rule",[],[]) [Str "horizontal",Space,Str "rule"]
-,Para [Str "top"]
-,HorizontalRule
-,Para [Str "bottom"]
-,HorizontalRule
-,Header 2 ("nowiki",[],[]) [Str "nowiki"]
-,Para [Str "''not",Space,Str "emph''"]
-,Header 2 ("strikeout",[],[]) [Str "strikeout"]
-,Para [Strikeout [Str "This",Space,Str "is",Space,Emph [Str "struck",Space,Str "out"]]]
-,Header 2 ("entities",[],[]) [Str "entities"]
-,Para [Str "hi",Space,Str "&",Space,Str "low"]
-,Para [Str "hi",Space,Str "&",Space,Str "low"]
-,Para [Str "G\246del"]
-,Para [Str "\777\2730"]
-,Header 2 ("comments",[],[]) [Str "comments"]
-,Para [Str "inline",Space,Str "comment"]
-,Para [Str "between",Space,Str "blocks"]
-,Header 2 ("linebreaks",[],[]) [Str "linebreaks"]
-,Para [Str "hi",LineBreak,Str "there"]
-,Para [Str "hi",LineBreak,Str "there"]
-,Header 2 ("indents",[],[]) [Str ":",Space,Str "indents"]
-,Para [Str "hi"]
-,DefinitionList
- [([],
-   [[Plain [Str "there"]]])]
-,Para [Str "bud"]
-,Para [Str "hi"]
-,DefinitionList
- [([],
-   [[DefinitionList
-     [([],
-       [[Plain [Str "there"]]])]]])]
-,Para [Str "bud"]
-,Header 2 ("p-tags",[],[]) [Str "p",Space,Str "tags"]
-,Para [Str "hi",Space,Str "there"]
-,Para [Str "bud"]
-,Para [Str "another"]
-,Header 2 ("raw-html",[],[]) [Str "raw",Space,Str "html"]
-,Para [Str "hi",Space,RawInline (Format "html") "<span style=\"color:red\">",Emph [Str "there"],RawInline (Format "html") "</span>",Str "."]
-,Para [RawInline (Format "html") "<ins>",Str "inserted",RawInline (Format "html") "</ins>"]
-,RawBlock (Format "html") "<div class=\"special\">"
-,Para [Str "hi",Space,Emph [Str "there"]]
-,RawBlock (Format "html") "</div>"
-,Header 2 ("sup-sub-del",[],[]) [Str "sup,",Space,Str "sub,",Space,Str "del"]
-,Para [Str "H",Subscript [Str "2"],Str "O",Space,Str "base",Superscript [Emph [Str "exponent"]],SoftBreak,Strikeout [Str "hello"]]
-,Header 2 ("inline-code",[],[]) [Str "inline",Space,Str "code"]
-,Para [Code ("",[],[]) "*\8594*",Space,Code ("",[],[]) "typed",Space,Code ("",["haskell"],[]) ">>="]
-,Header 2 ("code-blocks",[],[]) [Str "code",Space,Str "blocks"]
-,CodeBlock ("",[],[]) "case xs of\n     (_:_) -> reverse xs\n     []    -> ['*']"
-,CodeBlock ("",["haskell"],[]) "case xs of\n     (_:_) -> reverse xs\n     []    -> ['*']"
-,CodeBlock ("",["ruby","numberLines"],[("startFrom","100")]) "widgets.each do |w|\n  print w.price\nend"
-,Header 2 ("block-quotes",[],[]) [Str "block",Space,Str "quotes"]
-,Para [Str "Regular",Space,Str "paragraph"]
-,BlockQuote
- [Para [Str "This",Space,Str "is",Space,Str "a",Space,Str "block",Space,Str "quote."]
- ,Para [Str "With",Space,Str "two",Space,Str "paragraphs."]]
-,Para [Str "Nother",Space,Str "paragraph."]
-,Header 2 ("external-links",[],[]) [Str "external",Space,Str "links"]
-,Para [Link ("",[],[]) [Emph [Str "Google"],Space,Str "search",Space,Str "engine"] ("http://google.com","")]
-,Para [Link ("",[],[]) [Str "http://pandoc.org"] ("http://pandoc.org","")]
-,Para [Link ("",[],[]) [Str "1"] ("http://google.com",""),Space,Link ("",[],[]) [Str "2"] ("http://yahoo.com","")]
-,Para [Link ("",[],[]) [Str "email",Space,Str "me"] ("mailto:info@example.org","")]
-,Header 2 ("internal-links",[],[]) [Str "internal",Space,Str "links"]
-,Para [Link ("",[],[]) [Str "Help"] ("Help","wikilink")]
-,Para [Link ("",[],[]) [Str "the",Space,Str "help",Space,Str "page"] ("Help","wikilink")]
-,Para [Link ("",[],[]) [Str "Helpers"] ("Help","wikilink")]
-,Para [Link ("",[],[]) [Str "Help"] ("Help","wikilink"),Str "ers"]
-,Para [Link ("",[],[]) [Str "Contents"] ("Help:Contents","wikilink")]
-,Para [Link ("",[],[]) [Str "#My",Space,Str "anchor"] ("#My_anchor","wikilink")]
-,Para [Link ("",[],[]) [Str "and",Space,Str "text"] ("Page#with_anchor","wikilink")]
-,Header 2 ("images",[],[]) [Str "images"]
-,Para [Image ("",[],[]) [Str "caption"] ("example.jpg","fig:caption")]
-,Para [Image ("",[],[]) [Str "the",Space,Emph [Str "caption"],Space,Str "with",Space,Link ("",[],[]) [Str "external",Space,Str "link"] ("http://google.com","")] ("example.jpg","fig:the caption with external link")]
-,Para [Image ("",[],[("width","30"),("height","40")]) [Str "caption"] ("example.jpg","fig:caption")]
-,Para [Image ("",[],[("width","30")]) [Str "caption"] ("example.jpg","fig:caption")]
-,Para [Image ("",[],[("width","30")]) [Str "caption"] ("example.jpg","fig:caption")]
-,Para [Image ("",[],[]) [Str "example.jpg"] ("example.jpg","fig:example.jpg")]
-,Para [Image ("",[],[]) [Str "example_es.jpg"] ("example_es.jpg","fig:example_es.jpg")]
-,Header 2 ("lists",[],[]) [Str "lists"]
-,BulletList
- [[Plain [Str "Start",Space,Str "each",Space,Str "line"]]
- ,[Plain [Str "with",Space,Str "an",Space,Str "asterisk",Space,Str "(*)."]
-  ,BulletList
-   [[Plain [Str "More",Space,Str "asterisks",Space,Str "gives",Space,Str "deeper"]
-    ,BulletList
-     [[Plain [Str "and",Space,Str "deeper",Space,Str "levels."]]]]]]
- ,[Plain [Str "Line",Space,Str "breaks",LineBreak,Str "don't",Space,Str "break",Space,Str "levels."]
-  ,BulletList
-   [[BulletList
-     [[Plain [Str "But",Space,Str "jumping",Space,Str "levels",Space,Str "creates",Space,Str "empty",Space,Str "space."]]]]]]]
-,Para [Str "Any",Space,Str "other",Space,Str "start",Space,Str "ends",Space,Str "the",Space,Str "list."]
-,BulletList
- [[BulletList
-   [[Plain [Str "two"]]]]
- ,[Plain [Str "one"]]]
-,OrderedList (1,DefaultStyle,DefaultDelim)
- [[Plain [Str "Start",Space,Str "each",Space,Str "line"]]
- ,[Plain [Str "with",Space,Str "a",Space,Str "number",Space,Str "sign",Space,Str "(#)."]
-  ,OrderedList (1,DefaultStyle,DefaultDelim)
-   [[Plain [Str "More",Space,Str "number",Space,Str "signs",Space,Str "gives",Space,Str "deeper"]
-    ,OrderedList (1,DefaultStyle,DefaultDelim)
-     [[Plain [Str "and",Space,Str "deeper"]]
-     ,[Plain [Str "levels."]]]]]]
- ,[Plain [Str "Line",Space,Str "breaks",LineBreak,Str "don't",Space,Str "break",Space,Str "levels."]
-  ,OrderedList (1,DefaultStyle,DefaultDelim)
-   [[OrderedList (1,DefaultStyle,DefaultDelim)
-     [[Plain [Str "But",Space,Str "jumping",Space,Str "levels",Space,Str "creates",Space,Str "empty",Space,Str "space."]]]]]]
- ,[Plain [Str "Blank",Space,Str "lines"]]]
-,OrderedList (1,DefaultStyle,DefaultDelim)
- [[Plain [Str "end",Space,Str "the",Space,Str "list",Space,Str "and",Space,Str "start",Space,Str "another."]]]
-,Para [Str "Any",Space,Str "other",Space,Str "start",Space,Str "also",SoftBreak,Str "ends",Space,Str "the",Space,Str "list."]
-,DefinitionList
- [([Str "item",Space,Str "1"],
-   [[Plain [Str "definition",Space,Str "1"]]])
- ,([Str "item",Space,Str "2"],
-   [[Plain [Str "definition",Space,Str "2-1"]]
-   ,[Plain [Str "definition",Space,Str "2-2"]]])]
-,OrderedList (1,DefaultStyle,DefaultDelim)
- [[Plain [Str "one"]]
- ,[Plain [Str "two"]
-  ,BulletList
-   [[Plain [Str "two",Space,Str "point",Space,Str "one"]]
-   ,[Plain [Str "two",Space,Str "point",Space,Str "two"]]]]
- ,[Plain [Str "three"]
-  ,DefinitionList
-   [([Str "three",Space,Str "item",Space,Str "one"],
-     [[Plain [Str "three",Space,Str "def",Space,Str "one"]]])]]
- ,[Plain [Str "four"]
-  ,DefinitionList
-   [([],
-     [[Plain [Str "four",Space,Str "def",Space,Str "one"]]
-     ,[Plain [Str "this",Space,Str "looks",Space,Str "like",Space,Str "a",Space,Str "continuation"]]
-     ,[Plain [Str "and",Space,Str "is",Space,Str "often",Space,Str "used"]]
-     ,[Plain [Str "instead",LineBreak,Str "of",Space,Str "<br/>"]]])]]
- ,[Plain [RawInline (Format "mediawiki") "{{{template\n|author=John\n|title=My Book\n}}}"]
-  ,OrderedList (1,DefaultStyle,DefaultDelim)
-   [[Plain [Str "five",Space,Str "sub",Space,Str "1"]
-    ,OrderedList (1,DefaultStyle,DefaultDelim)
-     [[Plain [Str "five",Space,Str "sub",Space,Str "1",Space,Str "sub",Space,Str "1"]]]]
-   ,[Plain [Str "five",Space,Str "sub",Space,Str "2"]]]]]
-,OrderedList (1,DefaultStyle,DefaultDelim)
- [[Plain [Str "list",Space,Str "item",Space,Emph [Str "emph"]]
-  ,OrderedList (1,DefaultStyle,DefaultDelim)
-   [[Plain [Str "list",Space,Str "item",Space,Str "B1"]]
-   ,[Plain [Str "list",Space,Str "item",Space,Str "B2"]]]
-  ,Para [Str "continuing",Space,Str "list",Space,Str "item",Space,Str "A1"]]
- ,[Plain [Str "list",Space,Str "item",Space,Str "A2"]]]
-,OrderedList (1,DefaultStyle,DefaultDelim)
- [[Plain [Str "abc"]]
- ,[Plain [Str "def"]]
- ,[Plain [Str "ghi"]]]
-,OrderedList (9,DefaultStyle,DefaultDelim)
- [[Plain [Str "Amsterdam"]]
- ,[Plain [Str "Rotterdam"]]
- ,[Plain [Str "The",Space,Str "Hague"]]]
-,Header 2 ("math",[],[]) [Str "math"]
-,Para [Str "Here",Space,Str "is",Space,Str "some",Space,Math InlineMath "x=\\frac{y^\\pi}{z}",Str "."]
-,Para [Str "With",Space,Str "spaces:",Space,Math InlineMath "x=\\frac{y^\\pi}{z}",Str "."]
-,Header 2 ("preformatted-blocks",[],[]) [Str "preformatted",Space,Str "blocks"]
-,Para [Code ("",[],[]) "Start\160each\160line\160with\160a\160space.",LineBreak,Code ("",[],[]) "Text\160is\160",Strong [Code ("",[],[]) "preformatted"],Code ("",[],[]) "\160and",LineBreak,Emph [Code ("",[],[]) "markups"],Code ("",[],[]) "\160",Strong [Emph [Code ("",[],[]) "can"]],Code ("",[],[]) "\160be\160done."]
-,Para [Code ("",[],[]) "\160hell\160\160\160\160\160\160yeah"]
-,Para [Code ("",[],[]) "Start\160with\160a\160space\160in\160the\160first\160column,",LineBreak,Code ("",[],[]) "(before\160the\160<nowiki>).",LineBreak,Code ("",[],[]) "",LineBreak,Code ("",[],[]) "Then\160your\160block\160format\160will\160be",LineBreak,Code ("",[],[]) "\160\160\160\160maintained.",LineBreak,Code ("",[],[]) "",LineBreak,Code ("",[],[]) "This\160is\160good\160for\160copying\160in\160code\160blocks:",LineBreak,Code ("",[],[]) "",LineBreak,Code ("",[],[]) "def\160function():",LineBreak,Code ("",[],[]) "\160\160\160\160\"\"\"documentation\160string\"\"\"",LineBreak,Code ("",[],[]) "",LineBreak,Code ("",[],[]) "\160\160\160\160if\160True:",LineBreak,Code ("",[],[]) "\160\160\160\160\160\160\160\160print\160True",LineBreak,Code ("",[],[]) "\160\160\160\160else:",LineBreak,Code ("",[],[]) "\160\160\160\160\160\160\160\160print\160False"]
-,Para [Str "Not"]
-,RawBlock (Format "html") "<hr/>"
-,Para [Str "preformatted"]
-,Para [Str "Don't",Space,Str "need"]
-,Para [Code ("",[],[]) "a\160blank\160line"]
-,Para [Str "around",Space,Str "a",Space,Str "preformatted",Space,Str "block."]
-,Header 2 ("templates",[],[]) [Str "templates"]
-,RawBlock (Format "mediawiki") "{{Welcome}}"
-,RawBlock (Format "mediawiki") "{{Foo:Bar}}"
-,RawBlock (Format "mediawiki") "{{Thankyou|all your effort|Me}}"
-,Para [Str "Written",Space,RawInline (Format "mediawiki") "{{{date}}}",Space,Str "by",Space,RawInline (Format "mediawiki") "{{{name}}}",Str "."]
-,Header 2 ("tables",[],[]) [Str "tables"]
-,Table [] [AlignDefault,AlignDefault] [0.0,0.0]
- [[]
- ,[]]
- [[[Para [Str "Orange"]]
-  ,[Para [Str "Apple"]]]
- ,[[Para [Str "Bread"]]
-  ,[Para [Str "Pie"]]]
- ,[[Para [Str "Butter"]]
-  ,[Para [Str "Ice",Space,Str "cream"]]]]
-,Table [Str "Food",Space,Str "complements"] [AlignDefault,AlignDefault] [0.0,0.0]
- [[Para [Str "Orange"]]
- ,[Para [Str "Apple"]]]
- [[[Para [Str "Bread"]]
-  ,[Para [Str "Pie"]]]
- ,[[Para [Str "Butter"]]
-  ,[Para [Str "Ice",Space,Str "cream"]]]]
-,Table [Str "Food",Space,Str "complements"] [AlignDefault,AlignDefault] [0.0,0.0]
- [[Para [Str "Orange"]]
- ,[Para [Str "Apple"]]]
- [[[Para [Str "Bread"]
-   ,Para [Str "and",Space,Str "cheese"]]
-  ,[Para [Str "Pie"]
-   ,OrderedList (1,DefaultStyle,DefaultDelim)
-    [[Plain [Str "apple"]]
-    ,[Plain [Str "carrot"]]]]]]
-,Table [] [AlignDefault,AlignDefault,AlignDefault] [0.0,0.0,0.0]
- [[]
- ,[]
- ,[]]
- [[[Para [Str "Orange"]]
-  ,[Para [Str "Apple"]]
-  ,[Para [Str "more"]]]
- ,[[Para [Str "Bread"]]
-  ,[Para [Str "Pie"]]
-  ,[Para [Str "more"]]]
- ,[[Para [Str "Butter"]]
-  ,[Para [Str "Ice",Space,Str "cream"]]
-  ,[Para [Str "and",Space,Str "more"]]]]
-,Table [] [AlignLeft,AlignRight,AlignCenter] [0.25,0.125,0.125]
- [[Para [Str "Left"]]
- ,[Para [Str "Right"]]
- ,[Para [Str "Center"]]]
- [[[Para [Str "left"]]
-  ,[Para [Str "15.00"]]
-  ,[Para [Str "centered"]]]
- ,[[Para [Str "more"]]
-  ,[Para [Str "2.0"]]
-  ,[Para [Str "more"]]]]
-,Table [] [AlignDefault,AlignDefault] [0.0,0.0]
- [[]
- ,[]]
- [[[Para [Str "Orange"]]
-  ,[Para [Str "Apple"]]]
- ,[[Para [Str "Bread"]]
-  ,[Table [] [AlignDefault,AlignDefault] [0.0,0.0]
-    [[Para [Str "fruit"]]
-    ,[Para [Str "topping"]]]
-    [[[Para [Str "apple"]]
-     ,[Para [Str "ice",Space,Str "cream"]]]]]]
- ,[[Para [Str "Butter"]]
-  ,[Para [Str "Ice",Space,Str "cream"]]]]
-,Table [] [AlignDefault] [0.0]
- [[]]
- [[[Para [Str "Orange"]]]]
-,Para [Str "Paragraph",Space,Str "after",Space,Str "the",Space,Str "table."]
-,Table [] [AlignDefault,AlignDefault] [0.0,0.0]
- [[Para [Str "fruit"]]
- ,[Para [Str "topping"]]]
- [[[Para [Str "apple"]]
-  ,[Para [Str "ice",Space,Str "cream"]]]]
-,Header 2 ("notes",[],[]) [Str "notes"]
-,Para [Str "My",Space,Str "note!",Note [Plain [Str "This."]]]
-,Para [Str "URL",Space,Str "note.",Note [Plain [Link ("",[],[]) [Str "http://docs.python.org/library/functions.html#range"] ("http://docs.python.org/library/functions.html#range","")]]]]
+Pandoc
+  Meta { unMeta = fromList [] }
+  [ Header 1 ( "header" , [] , [] ) [ Str "header" ]
+  , Header
+      2
+      ( "header_level_two" , [] , [] )
+      [ Str "header" , Space , Str "level" , Space , Str "two" ]
+  , Header
+      3
+      ( "header_level_3" , [] , [] )
+      [ Str "header" , Space , Str "level" , Space , Str "3" ]
+  , Header
+      4
+      ( "header_level_four" , [] , [] )
+      [ Str "header"
+      , Space
+      , Emph [ Str "level" ]
+      , Space
+      , Str "four"
+      ]
+  , Header
+      5
+      ( "header_level_5" , [] , [] )
+      [ Str "header" , Space , Str "level" , Space , Str "5" ]
+  , Header
+      6
+      ( "header_level_6" , [] , [] )
+      [ Str "header" , Space , Str "level" , Space , Str "6" ]
+  , Para
+      [ Str "======="
+      , Space
+      , Str "not"
+      , Space
+      , Str "a"
+      , Space
+      , Str "header"
+      , Space
+      , Str "========"
+      ]
+  , Para
+      [ Code ( "" , [] , [] ) "==\160not\160a\160header\160==" ]
+  , Header
+      2
+      ( "emph_and_strong" , [] , [] )
+      [ Str "emph" , Space , Str "and" , Space , Str "strong" ]
+  , Para
+      [ Emph [ Str "emph" ] , Space , Strong [ Str "strong" ] ]
+  , Para
+      [ Strong
+          [ Emph
+              [ Str "strong" , Space , Str "and" , Space , Str "emph" ]
+          ]
+      ]
+  , Para
+      [ Strong
+          [ Emph [ Str "emph" , Space , Str "inside" ]
+          , Space
+          , Str "strong"
+          ]
+      ]
+  , Para
+      [ Strong
+          [ Str "strong"
+          , Space
+          , Str "with"
+          , Space
+          , Emph [ Str "emph" ]
+          ]
+      ]
+  , Para
+      [ Emph
+          [ Strong [ Str "strong" , Space , Str "inside" ]
+          , Space
+          , Str "emph"
+          ]
+      ]
+  , Header
+      2
+      ( "horizontal_rule" , [] , [] )
+      [ Str "horizontal" , Space , Str "rule" ]
+  , Para [ Str "top" ]
+  , HorizontalRule
+  , Para [ Str "bottom" ]
+  , HorizontalRule
+  , Header 2 ( "nowiki" , [] , [] ) [ Str "nowiki" ]
+  , Para [ Str "''not" , Space , Str "emph''" ]
+  , Header 2 ( "strikeout" , [] , [] ) [ Str "strikeout" ]
+  , Para
+      [ Strikeout
+          [ Str "This"
+          , Space
+          , Str "is"
+          , Space
+          , Emph [ Str "struck" , Space , Str "out" ]
+          ]
+      ]
+  , Header 2 ( "entities" , [] , [] ) [ Str "entities" ]
+  , Para [ Str "hi" , Space , Str "&" , Space , Str "low" ]
+  , Para [ Str "hi" , Space , Str "&" , Space , Str "low" ]
+  , Para [ Str "G\246del" ]
+  , Para [ Str "\777\2730" ]
+  , Header 2 ( "comments" , [] , [] ) [ Str "comments" ]
+  , Para [ Str "inline" , Space , Str "comment" ]
+  , Para [ Str "between" , Space , Str "blocks" ]
+  , Header 2 ( "linebreaks" , [] , [] ) [ Str "linebreaks" ]
+  , Para [ Str "hi" , LineBreak , Str "there" ]
+  , Para [ Str "hi" , LineBreak , Str "there" ]
+  , Header
+      2
+      ( "indents" , [] , [] )
+      [ Str ":" , Space , Str "indents" ]
+  , Para [ Str "hi" ]
+  , DefinitionList [ ( [] , [ [ Plain [ Str "there" ] ] ] ) ]
+  , Para [ Str "bud" ]
+  , Para [ Str "hi" ]
+  , DefinitionList
+      [ ( []
+        , [ [ DefinitionList
+                [ ( [] , [ [ Plain [ Str "there" ] ] ] ) ]
+            ]
+          ]
+        )
+      ]
+  , Para [ Str "bud" ]
+  , Header
+      2 ( "p_tags" , [] , [] ) [ Str "p" , Space , Str "tags" ]
+  , Para [ Str "hi" , Space , Str "there" ]
+  , Para [ Str "bud" ]
+  , Para [ Str "another" ]
+  , Header
+      2
+      ( "raw_html" , [] , [] )
+      [ Str "raw" , Space , Str "html" ]
+  , Para
+      [ Str "hi"
+      , Space
+      , RawInline (Format "html") "<span style=\"color:red\">"
+      , Emph [ Str "there" ]
+      , RawInline (Format "html") "</span>"
+      , Str "."
+      ]
+  , Para
+      [ RawInline (Format "html") "<ins>"
+      , Str "inserted"
+      , RawInline (Format "html") "</ins>"
+      ]
+  , RawBlock (Format "html") "<div class=\"special\">"
+  , Para [ Str "hi" , Space , Emph [ Str "there" ] ]
+  , RawBlock (Format "html") "</div>"
+  , Header
+      2
+      ( "sup_sub_del" , [] , [] )
+      [ Str "sup," , Space , Str "sub," , Space , Str "del" ]
+  , Para
+      [ Str "H"
+      , Subscript [ Str "2" ]
+      , Str "O"
+      , Space
+      , Str "base"
+      , Superscript [ Emph [ Str "exponent" ] ]
+      , SoftBreak
+      , Strikeout [ Str "hello" ]
+      ]
+  , Header
+      2
+      ( "inline_code" , [] , [] )
+      [ Str "inline" , Space , Str "code" ]
+  , Para
+      [ Code ( "" , [] , [] ) "*\8594*"
+      , Space
+      , Code ( "" , [] , [] ) "typed"
+      , Space
+      , Code ( "" , [ "haskell" ] , [] ) ">>="
+      ]
+  , Header
+      2
+      ( "code_blocks" , [] , [] )
+      [ Str "code" , Space , Str "blocks" ]
+  , CodeBlock
+      ( "" , [] , [] )
+      "case xs of\n     (_:_) -> reverse xs\n     []    -> ['*']"
+  , CodeBlock
+      ( "" , [ "haskell" ] , [] )
+      "case xs of\n     (_:_) -> reverse xs\n     []    -> ['*']"
+  , CodeBlock
+      ( ""
+      , [ "ruby" , "numberLines" ]
+      , [ ( "startFrom" , "100" ) ]
+      )
+      "widgets.each do |w|\n  print w.price\nend"
+  , Header
+      2
+      ( "block_quotes" , [] , [] )
+      [ Str "block" , Space , Str "quotes" ]
+  , Para [ Str "Regular" , Space , Str "paragraph" ]
+  , BlockQuote
+      [ Para
+          [ Str "This"
+          , Space
+          , Str "is"
+          , Space
+          , Str "a"
+          , Space
+          , Str "block"
+          , Space
+          , Str "quote."
+          ]
+      , Para
+          [ Str "With"
+          , Space
+          , Str "two"
+          , Space
+          , Str "paragraphs."
+          ]
+      ]
+  , Para [ Str "Nother" , Space , Str "paragraph." ]
+  , Header
+      2
+      ( "external_links" , [] , [] )
+      [ Str "external" , Space , Str "links" ]
+  , Para
+      [ Link
+          ( "" , [] , [] )
+          [ Emph [ Str "Google" ]
+          , Space
+          , Str "search"
+          , Space
+          , Str "engine"
+          ]
+          ( "http://google.com" , "" )
+      ]
+  , Para
+      [ Link
+          ( "" , [] , [] )
+          [ Str "http://pandoc.org" ]
+          ( "http://pandoc.org" , "" )
+      ]
+  , Para
+      [ Link
+          ( "" , [] , [] ) [ Str "1" ] ( "http://google.com" , "" )
+      , Space
+      , Link
+          ( "" , [] , [] ) [ Str "2" ] ( "http://yahoo.com" , "" )
+      ]
+  , Para
+      [ Link
+          ( "" , [] , [] )
+          [ Str "email" , Space , Str "me" ]
+          ( "mailto:info@example.org" , "" )
+      ]
+  , Header
+      2
+      ( "internal_links" , [] , [] )
+      [ Str "internal" , Space , Str "links" ]
+  , Para
+      [ Link
+          ( "" , [ "wikilink" ] , [] )
+          [ Str "Help" ]
+          ( "Help" , "Help" )
+      ]
+  , Para
+      [ Link
+          ( "" , [ "wikilink" ] , [] )
+          [ Str "the" , Space , Str "help" , Space , Str "page" ]
+          ( "Help" , "the help page" )
+      ]
+  , Para
+      [ Link
+          ( "" , [ "wikilink" ] , [] )
+          [ Str "Helpers" ]
+          ( "Help" , "Help" )
+      ]
+  , Para
+      [ Link
+          ( "" , [ "wikilink" ] , [] )
+          [ Str "Help" ]
+          ( "Help" , "Help" )
+      , Str "ers"
+      ]
+  , Para
+      [ Link
+          ( "" , [ "wikilink" ] , [] )
+          [ Str "Contents" ]
+          ( "Help:Contents" , "Contents" )
+      ]
+  , Para
+      [ Link
+          ( "" , [ "wikilink" ] , [] )
+          [ Str "#My" , Space , Str "anchor" ]
+          ( "#My_anchor" , "#My anchor" )
+      ]
+  , Para
+      [ Link
+          ( "" , [ "wikilink" ] , [] )
+          [ Str "and" , Space , Str "text" ]
+          ( "Page#with_anchor" , "and text" )
+      ]
+  , Header 2 ( "images" , [] , [] ) [ Str "images" ]
+  , Figure
+      ( "" , [] , [] )
+      (Caption Nothing [ Plain [ Str "caption" ] ])
+      [ Plain
+          [ Image ( "" , [] , [] ) [] ( "example.jpg" , "caption" ) ]
+      ]
+  , Figure
+      ( "" , [] , [] )
+      (Caption
+         Nothing
+         [ Plain
+             [ Str "the"
+             , Space
+             , Emph [ Str "caption" ]
+             , Space
+             , Str "with"
+             , Space
+             , Link
+                 ( "" , [] , [] )
+                 [ Str "external" , Space , Str "link" ]
+                 ( "http://google.com" , "" )
+             ]
+         ])
+      [ Plain
+          [ Image
+              ( "" , [] , [] )
+              []
+              ( "example.jpg" , "the caption with external link" )
+          ]
+      ]
+  , Figure
+      ( "" , [] , [] )
+      (Caption Nothing [ Plain [ Str "caption" ] ])
+      [ Plain
+          [ Image
+              ( "" , [] , [ ( "width" , "30" ) , ( "height" , "40" ) ] )
+              []
+              ( "example.jpg" , "caption" )
+          ]
+      ]
+  , Figure
+      ( "" , [] , [] )
+      (Caption Nothing [ Plain [ Str "caption" ] ])
+      [ Plain
+          [ Image
+              ( "" , [] , [ ( "width" , "30" ) ] )
+              []
+              ( "example.jpg" , "caption" )
+          ]
+      ]
+  , Figure
+      ( "" , [] , [] )
+      (Caption Nothing [ Plain [ Str "caption" ] ])
+      [ Plain
+          [ Image
+              ( "" , [] , [ ( "width" , "30" ) ] )
+              []
+              ( "example.jpg" , "caption" )
+          ]
+      ]
+  , Figure
+      ( "" , [] , [] )
+      (Caption Nothing [ Plain [ Str "example.jpg" ] ])
+      [ Plain
+          [ Image
+              ( "" , [] , [] ) [] ( "example.jpg" , "example.jpg" )
+          ]
+      ]
+  , Figure
+      ( "" , [] , [] )
+      (Caption Nothing [ Plain [ Str "example_es.jpg" ] ])
+      [ Plain
+          [ Image
+              ( "" , [] , [] )
+              []
+              ( "example_es.jpg" , "example_es.jpg" )
+          ]
+      ]
+  , Header 2 ( "lists" , [] , [] ) [ Str "lists" ]
+  , BulletList
+      [ [ Plain
+            [ Str "Start" , Space , Str "each" , Space , Str "line" ]
+        ]
+      , [ Plain
+            [ Str "with"
+            , Space
+            , Str "an"
+            , Space
+            , Str "asterisk"
+            , Space
+            , Str "(*)."
+            ]
+        , BulletList
+            [ [ Plain
+                  [ Str "More"
+                  , Space
+                  , Str "asterisks"
+                  , Space
+                  , Str "gives"
+                  , Space
+                  , Str "deeper"
+                  ]
+              , BulletList
+                  [ [ Plain
+                        [ Str "and"
+                        , Space
+                        , Str "deeper"
+                        , Space
+                        , Str "levels."
+                        ]
+                    ]
+                  ]
+              ]
+            ]
+        ]
+      , [ Plain
+            [ Str "Line"
+            , Space
+            , Str "breaks"
+            , LineBreak
+            , Str "don't"
+            , Space
+            , Str "break"
+            , Space
+            , Str "levels."
+            ]
+        , BulletList
+            [ [ BulletList
+                  [ [ Plain
+                        [ Str "But"
+                        , Space
+                        , Str "jumping"
+                        , Space
+                        , Str "levels"
+                        , Space
+                        , Str "creates"
+                        , Space
+                        , Str "empty"
+                        , Space
+                        , Str "space."
+                        ]
+                    ]
+                  ]
+              ]
+            ]
+        ]
+      ]
+  , Para
+      [ Str "Any"
+      , Space
+      , Str "other"
+      , Space
+      , Str "start"
+      , Space
+      , Str "ends"
+      , Space
+      , Str "the"
+      , Space
+      , Str "list."
+      ]
+  , BulletList
+      [ [ BulletList [ [ Plain [ Str "two" ] ] ] ]
+      , [ Plain [ Str "one" ] ]
+      ]
+  , OrderedList
+      ( 1 , DefaultStyle , DefaultDelim )
+      [ [ Plain
+            [ Str "Start" , Space , Str "each" , Space , Str "line" ]
+        ]
+      , [ Plain
+            [ Str "with"
+            , Space
+            , Str "a"
+            , Space
+            , Str "number"
+            , Space
+            , Str "sign"
+            , Space
+            , Str "(#)."
+            ]
+        , OrderedList
+            ( 1 , DefaultStyle , DefaultDelim )
+            [ [ Plain
+                  [ Str "More"
+                  , Space
+                  , Str "number"
+                  , Space
+                  , Str "signs"
+                  , Space
+                  , Str "gives"
+                  , Space
+                  , Str "deeper"
+                  ]
+              , OrderedList
+                  ( 1 , DefaultStyle , DefaultDelim )
+                  [ [ Plain [ Str "and" , Space , Str "deeper" ] ]
+                  , [ Plain [ Str "levels." ] ]
+                  ]
+              ]
+            ]
+        ]
+      , [ Plain
+            [ Str "Line"
+            , Space
+            , Str "breaks"
+            , LineBreak
+            , Str "don't"
+            , Space
+            , Str "break"
+            , Space
+            , Str "levels."
+            ]
+        , OrderedList
+            ( 1 , DefaultStyle , DefaultDelim )
+            [ [ OrderedList
+                  ( 1 , DefaultStyle , DefaultDelim )
+                  [ [ Plain
+                        [ Str "But"
+                        , Space
+                        , Str "jumping"
+                        , Space
+                        , Str "levels"
+                        , Space
+                        , Str "creates"
+                        , Space
+                        , Str "empty"
+                        , Space
+                        , Str "space."
+                        ]
+                    ]
+                  ]
+              ]
+            ]
+        ]
+      , [ Plain [ Str "Blank" , Space , Str "lines" ] ]
+      ]
+  , OrderedList
+      ( 1 , DefaultStyle , DefaultDelim )
+      [ [ Plain
+            [ Str "end"
+            , Space
+            , Str "the"
+            , Space
+            , Str "list"
+            , Space
+            , Str "and"
+            , Space
+            , Str "start"
+            , Space
+            , Str "another."
+            ]
+        ]
+      ]
+  , Para
+      [ Str "Any"
+      , Space
+      , Str "other"
+      , Space
+      , Str "start"
+      , Space
+      , Str "also"
+      , SoftBreak
+      , Str "ends"
+      , Space
+      , Str "the"
+      , Space
+      , Str "list."
+      ]
+  , DefinitionList
+      [ ( [ Str "item" , Space , Str "1" ]
+        , [ [ Plain [ Str "definition" , Space , Str "1" ] ] ]
+        )
+      , ( [ Str "item" , Space , Str "2" ]
+        , [ [ Plain [ Str "definition" , Space , Str "2-1" ] ]
+          , [ Plain [ Str "definition" , Space , Str "2-2" ] ]
+          ]
+        )
+      ]
+  , OrderedList
+      ( 1 , DefaultStyle , DefaultDelim )
+      [ [ Plain [ Str "one" ] ]
+      , [ Plain [ Str "two" ]
+        , BulletList
+            [ [ Plain
+                  [ Str "two"
+                  , Space
+                  , Str "point"
+                  , Space
+                  , Str "one"
+                  ]
+              ]
+            , [ Plain
+                  [ Str "two"
+                  , Space
+                  , Str "point"
+                  , Space
+                  , Str "two"
+                  ]
+              ]
+            ]
+        ]
+      , [ Plain [ Str "three" ]
+        , DefinitionList
+            [ ( [ Str "three" , Space , Str "item" , Space , Str "one" ]
+              , [ [ Plain
+                      [ Str "three"
+                      , Space
+                      , Str "def"
+                      , Space
+                      , Str "one"
+                      ]
+                  ]
+                ]
+              )
+            ]
+        ]
+      , [ Plain [ Str "four" ]
+        , DefinitionList
+            [ ( []
+              , [ [ Plain
+                      [ Str "four"
+                      , Space
+                      , Str "def"
+                      , Space
+                      , Str "one"
+                      ]
+                  ]
+                , [ Plain
+                      [ Str "this"
+                      , Space
+                      , Str "looks"
+                      , Space
+                      , Str "like"
+                      , Space
+                      , Str "a"
+                      , Space
+                      , Str "continuation"
+                      ]
+                  ]
+                , [ Plain
+                      [ Str "and"
+                      , Space
+                      , Str "is"
+                      , Space
+                      , Str "often"
+                      , Space
+                      , Str "used"
+                      ]
+                  ]
+                , [ Plain
+                      [ Str "instead"
+                      , LineBreak
+                      , Str "of"
+                      , Space
+                      , Str "<br/>"
+                      ]
+                  ]
+                ]
+              )
+            ]
+        ]
+      , [ Plain
+            [ RawInline
+                (Format "mediawiki")
+                "{{{template\n|author=John\n|title=My Book\n}}}"
+            ]
+        , OrderedList
+            ( 1 , DefaultStyle , DefaultDelim )
+            [ [ Plain
+                  [ Str "five" , Space , Str "sub" , Space , Str "1" ]
+              , OrderedList
+                  ( 1 , DefaultStyle , DefaultDelim )
+                  [ [ Plain
+                        [ Str "five"
+                        , Space
+                        , Str "sub"
+                        , Space
+                        , Str "1"
+                        , Space
+                        , Str "sub"
+                        , Space
+                        , Str "1"
+                        ]
+                    ]
+                  ]
+              ]
+            , [ Plain
+                  [ Str "five" , Space , Str "sub" , Space , Str "2" ]
+              ]
+            ]
+        ]
+      ]
+  , OrderedList
+      ( 1 , DefaultStyle , DefaultDelim )
+      [ [ Plain
+            [ Str "list"
+            , Space
+            , Str "item"
+            , Space
+            , Emph [ Str "emph" ]
+            ]
+        , OrderedList
+            ( 1 , DefaultStyle , DefaultDelim )
+            [ [ Plain
+                  [ Str "list" , Space , Str "item" , Space , Str "B1" ]
+              ]
+            , [ Plain
+                  [ Str "list" , Space , Str "item" , Space , Str "B2" ]
+              ]
+            ]
+        , Para
+            [ Str "continuing"
+            , Space
+            , Str "list"
+            , Space
+            , Str "item"
+            , Space
+            , Str "A1"
+            ]
+        ]
+      , [ Plain
+            [ Str "list" , Space , Str "item" , Space , Str "A2" ]
+        ]
+      ]
+  , OrderedList
+      ( 1 , DefaultStyle , DefaultDelim )
+      [ [ Plain [ Str "abc" ] ]
+      , [ Plain [ Str "def" ] ]
+      , [ Plain [ Str "ghi" ] ]
+      ]
+  , OrderedList
+      ( 9 , DefaultStyle , DefaultDelim )
+      [ [ Plain [ Str "Amsterdam" ] ]
+      , [ Plain [ Str "Rotterdam" ] ]
+      , [ Plain [ Str "The" , Space , Str "Hague" ] ]
+      ]
+  , Header 2 ( "math" , [] , [] ) [ Str "math" ]
+  , Para
+      [ Str "Here"
+      , Space
+      , Str "is"
+      , Space
+      , Str "some"
+      , Space
+      , Math InlineMath "x=\\frac{y^\\pi}{z}"
+      , Str "."
+      ]
+  , Para
+      [ Str "With"
+      , Space
+      , Str "spaces:"
+      , Space
+      , Math InlineMath "x=\\frac{y^\\pi}{z}"
+      , Str "."
+      ]
+  , Header
+      2
+      ( "preformatted_blocks" , [] , [] )
+      [ Str "preformatted" , Space , Str "blocks" ]
+  , Para
+      [ Code
+          ( "" , [] , [] )
+          "Start\160each\160line\160with\160a\160space."
+      , LineBreak
+      , Code ( "" , [] , [] ) "Text\160is\160"
+      , Strong [ Code ( "" , [] , [] ) "preformatted" ]
+      , Code ( "" , [] , [] ) "\160and"
+      , LineBreak
+      , Emph [ Code ( "" , [] , [] ) "markups" ]
+      , Code ( "" , [] , [] ) "\160"
+      , Strong [ Emph [ Code ( "" , [] , [] ) "can" ] ]
+      , Code ( "" , [] , [] ) "\160be\160done."
+      ]
+  , Para
+      [ Code
+          ( "" , [] , [] ) "\160hell\160\160\160\160\160\160yeah"
+      ]
+  , Para
+      [ Code
+          ( "" , [] , [] )
+          "Start\160with\160a\160space\160in\160the\160first\160column,"
+      , LineBreak
+      , Code ( "" , [] , [] ) "(before\160the\160<nowiki>)."
+      , LineBreak
+      , Code ( "" , [] , [] ) ""
+      , LineBreak
+      , Code
+          ( "" , [] , [] )
+          "Then\160your\160block\160format\160will\160be"
+      , LineBreak
+      , Code ( "" , [] , [] ) "\160\160\160\160maintained."
+      , LineBreak
+      , Code ( "" , [] , [] ) ""
+      , LineBreak
+      , Code
+          ( "" , [] , [] )
+          "This\160is\160good\160for\160copying\160in\160code\160blocks:"
+      , LineBreak
+      , Code ( "" , [] , [] ) ""
+      , LineBreak
+      , Code ( "" , [] , [] ) "def\160function():"
+      , LineBreak
+      , Code
+          ( "" , [] , [] )
+          "\160\160\160\160\"\"\"documentation\160string\"\"\""
+      , LineBreak
+      , Code ( "" , [] , [] ) ""
+      , LineBreak
+      , Code ( "" , [] , [] ) "\160\160\160\160if\160True:"
+      , LineBreak
+      , Code
+          ( "" , [] , [] )
+          "\160\160\160\160\160\160\160\160print\160True"
+      , LineBreak
+      , Code ( "" , [] , [] ) "\160\160\160\160else:"
+      , LineBreak
+      , Code
+          ( "" , [] , [] )
+          "\160\160\160\160\160\160\160\160print\160False"
+      ]
+  , Para [ Str "Not" ]
+  , RawBlock (Format "html") "<hr/>"
+  , Para [ Str "preformatted" ]
+  , Para [ Str "Don't" , Space , Str "need" ]
+  , Para [ Code ( "" , [] , [] ) "a\160blank\160line" ]
+  , Para
+      [ Str "around"
+      , Space
+      , Str "a"
+      , Space
+      , Str "preformatted"
+      , Space
+      , Str "block."
+      ]
+  , Header 2 ( "templates" , [] , [] ) [ Str "templates" ]
+  , RawBlock (Format "mediawiki") "{{Welcome}}"
+  , RawBlock (Format "mediawiki") "{{Foo:Bar}}"
+  , RawBlock
+      (Format "mediawiki") "{{Thankyou|all your effort|Me}}"
+  , Para
+      [ Str "Written"
+      , Space
+      , RawInline (Format "mediawiki") "{{{date}}}"
+      , Space
+      , Str "by"
+      , Space
+      , RawInline (Format "mediawiki") "{{{name}}}"
+      , Str "."
+      ]
+  , Header 2 ( "tables" , [] , [] ) [ Str "tables" ]
+  , Table
+      ( "" , [] , [] )
+      (Caption Nothing [])
+      [ ( AlignDefault , ColWidthDefault )
+      , ( AlignDefault , ColWidthDefault )
+      ]
+      (TableHead ( "" , [] , [] ) [])
+      [ TableBody
+          ( "" , [] , [] )
+          (RowHeadColumns 0)
+          []
+          [ Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para [ Str "Orange" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para [ Str "Apple" ] ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para [ Str "Bread" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para [ Str "Pie" ] ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para [ Str "Butter" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para [ Str "Ice" , Space , Str "cream" ] ]
+              ]
+          ]
+      ]
+      (TableFoot ( "" , [] , [] ) [])
+  , Table
+      ( "" , [] , [] )
+      (Caption
+         Nothing
+         [ Plain [ Str "Food" , Space , Str "complements" ] ])
+      [ ( AlignDefault , ColWidthDefault )
+      , ( AlignDefault , ColWidthDefault )
+      ]
+      (TableHead
+         ( "" , [] , [] )
+         [ Row
+             ( "" , [] , [] )
+             [ Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Para [ Str "Orange" ] ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Para [ Str "Apple" ] ]
+             ]
+         ])
+      [ TableBody
+          ( "" , [] , [] )
+          (RowHeadColumns 0)
+          []
+          [ Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para [ Str "Bread" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para [ Str "Pie" ] ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para [ Str "Butter" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para [ Str "Ice" , Space , Str "cream" ] ]
+              ]
+          ]
+      ]
+      (TableFoot ( "" , [] , [] ) [])
+  , Table
+      ( "" , [] , [] )
+      (Caption
+         Nothing
+         [ Plain [ Str "Food" , Space , Str "complements" ] ])
+      [ ( AlignDefault , ColWidthDefault )
+      , ( AlignDefault , ColWidthDefault )
+      ]
+      (TableHead
+         ( "" , [] , [] )
+         [ Row
+             ( "" , [] , [] )
+             [ Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Para [ Str "Orange" ] ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Para [ Str "Apple" ] ]
+             ]
+         ])
+      [ TableBody
+          ( "" , [] , [] )
+          (RowHeadColumns 0)
+          []
+          [ Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para [ Str "Bread" ]
+                  , Para [ Str "and" , Space , Str "cheese" ]
+                  ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para [ Str "Pie" ]
+                  , OrderedList
+                      ( 1 , DefaultStyle , DefaultDelim )
+                      [ [ Plain [ Str "apple" ] ]
+                      , [ Plain [ Str "carrot" ] ]
+                      ]
+                  ]
+              ]
+          ]
+      ]
+      (TableFoot ( "" , [] , [] ) [])
+  , Table
+      ( "" , [] , [] )
+      (Caption Nothing [])
+      [ ( AlignDefault , ColWidthDefault )
+      , ( AlignDefault , ColWidthDefault )
+      , ( AlignDefault , ColWidthDefault )
+      ]
+      (TableHead ( "" , [] , [] ) [])
+      [ TableBody
+          ( "" , [] , [] )
+          (RowHeadColumns 0)
+          []
+          [ Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para [ Str "Orange" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para [ Str "Apple" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para [ Str "more" ] ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para [ Str "Bread" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para [ Str "Pie" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para [ Str "more" ] ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para [ Str "Butter" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para [ Str "Ice" , Space , Str "cream" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para [ Str "and" , Space , Str "more" ] ]
+              ]
+          ]
+      ]
+      (TableFoot ( "" , [] , [] ) [])
+  , Table
+      ( "" , [] , [] )
+      (Caption Nothing [])
+      [ ( AlignLeft , ColWidth 0.25 )
+      , ( AlignRight , ColWidth 0.125 )
+      , ( AlignCenter , ColWidth 0.125 )
+      ]
+      (TableHead
+         ( "" , [] , [] )
+         [ Row
+             ( "" , [] , [] )
+             [ Cell
+                 ( "" , [] , [ ( "width" , "50%" ) ] )
+                 AlignLeft
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Para [ Str "Left" ] ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignRight
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Para [ Str "Right" ] ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignCenter
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Para [ Str "Center" ] ]
+             ]
+         ])
+      [ TableBody
+          ( "" , [] , [] )
+          (RowHeadColumns 0)
+          []
+          [ Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para [ Str "left" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para [ Str "15.00" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para [ Str "centered" ] ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para [ Str "more" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para [ Str "2.0" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para [ Str "more" ] ]
+              ]
+          ]
+      ]
+      (TableFoot ( "" , [] , [] ) [])
+  , Table
+      ( "" , [] , [] )
+      (Caption Nothing [])
+      [ ( AlignDefault , ColWidthDefault )
+      , ( AlignDefault , ColWidthDefault )
+      ]
+      (TableHead ( "" , [] , [] ) [])
+      [ TableBody
+          ( "" , [] , [] )
+          (RowHeadColumns 0)
+          []
+          [ Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para [ Str "Orange" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para [ Str "Apple" ] ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para [ Str "Bread" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Table
+                      ( "" , [] , [] )
+                      (Caption Nothing [])
+                      [ ( AlignDefault , ColWidthDefault )
+                      , ( AlignDefault , ColWidthDefault )
+                      ]
+                      (TableHead
+                         ( "" , [] , [] )
+                         [ Row
+                             ( "" , [] , [] )
+                             [ Cell
+                                 ( "" , [] , [] )
+                                 AlignDefault
+                                 (RowSpan 1)
+                                 (ColSpan 1)
+                                 [ Para [ Str "fruit" ] ]
+                             , Cell
+                                 ( "" , [] , [] )
+                                 AlignDefault
+                                 (RowSpan 1)
+                                 (ColSpan 1)
+                                 [ Para [ Str "topping" ] ]
+                             ]
+                         ])
+                      [ TableBody
+                          ( "" , [] , [] )
+                          (RowHeadColumns 0)
+                          []
+                          [ Row
+                              ( "" , [] , [] )
+                              [ Cell
+                                  ( "" , [] , [] )
+                                  AlignDefault
+                                  (RowSpan 1)
+                                  (ColSpan 1)
+                                  [ Para [ Str "apple" ] ]
+                              , Cell
+                                  ( "" , [] , [] )
+                                  AlignDefault
+                                  (RowSpan 1)
+                                  (ColSpan 1)
+                                  [ Para
+                                      [ Str "ice"
+                                      , Space
+                                      , Str "cream"
+                                      ]
+                                  ]
+                              ]
+                          ]
+                      ]
+                      (TableFoot ( "" , [] , [] ) [])
+                  ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para [ Str "Butter" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para [ Str "Ice" , Space , Str "cream" ] ]
+              ]
+          ]
+      ]
+      (TableFoot ( "" , [] , [] ) [])
+  , Table
+      ( "" , [] , [] )
+      (Caption Nothing [])
+      [ ( AlignDefault , ColWidthDefault ) ]
+      (TableHead ( "" , [] , [] ) [])
+      [ TableBody
+          ( "" , [] , [] )
+          (RowHeadColumns 0)
+          []
+          [ Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para [ Str "Orange" ] ]
+              ]
+          ]
+      ]
+      (TableFoot ( "" , [] , [] ) [])
+  , Para
+      [ Str "Paragraph"
+      , Space
+      , Str "after"
+      , Space
+      , Str "the"
+      , Space
+      , Str "table."
+      ]
+  , Table
+      ( "" , [] , [] )
+      (Caption Nothing [])
+      [ ( AlignDefault , ColWidthDefault )
+      , ( AlignDefault , ColWidthDefault )
+      ]
+      (TableHead
+         ( "" , [] , [] )
+         [ Row
+             ( "" , [] , [] )
+             [ Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Para [ Str "fruit" ] ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Para [ Str "topping" ] ]
+             ]
+         ])
+      [ TableBody
+          ( "" , [] , [] )
+          (RowHeadColumns 0)
+          []
+          [ Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para [ Str "apple" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para [ Str "ice" , Space , Str "cream" ] ]
+              ]
+          ]
+      ]
+      (TableFoot ( "" , [] , [] ) [])
+  , Header 2 ( "notes" , [] , [] ) [ Str "notes" ]
+  , Para
+      [ Str "My"
+      , Space
+      , Str "note!"
+      , Note [ Plain [ Str "This." ] ]
+      ]
+  , Para
+      [ Str "URL"
+      , Space
+      , Str "note."
+      , Note
+          [ Plain
+              [ Link
+                  ( "" , [] , [] )
+                  [ Str
+                      "http://docs.python.org/library/functions.html#range"
+                  ]
+                  ( "http://docs.python.org/library/functions.html#range"
+                  , ""
+                  )
+              ]
+          ]
+      ]
+  ]
diff --git a/test/odt/markdown/blockquote2.md b/test/odt/markdown/blockquote2.md
new file mode 100644
--- /dev/null
+++ b/test/odt/markdown/blockquote2.md
@@ -0,0 +1,3 @@
+Paragraph
+
+> A blockquote.
diff --git a/test/odt/markdown/formula.md b/test/odt/markdown/formula.md
new file mode 100644
--- /dev/null
+++ b/test/odt/markdown/formula.md
@@ -0,0 +1,1 @@
+$$E = {m \cdot c^{2}}$$
diff --git a/test/odt/native/imageIndex.native b/test/odt/native/imageIndex.native
--- a/test/odt/native/imageIndex.native
+++ b/test/odt/native/imageIndex.native
@@ -1,1 +1,28 @@
-[Para [Image ("",[],[("width","5.292cm"),("height","5.292cm")]) [Str "Abbildung",Space,Str "1:",Space,Str "Image",Space,Str "caption"] ("Pictures/10000000000000FA000000FAD6A15225.jpg","fig:")]]
+[ Figure
+  ( "" , [] , [] )
+  (Caption
+     Nothing
+     [ Plain
+         [ Str "Image"
+         , Space
+         , Str "caption"
+         ]
+     ])
+  [ Plain
+      [ Image
+          ( ""
+          , []
+          , [ ( "width" , "5.292cm" ) , ( "height" , "5.292cm" ) ]
+          )
+          [ Str "Abbildung"
+          , Space
+          , Str "1:"
+          , Space
+          , Str "Image"
+          , Space
+          , Str "caption"
+          ]
+          ( "Pictures/10000000000000FA000000FAD6A15225.jpg" , "" )
+      ]
+  ]
+]
diff --git a/test/odt/native/imageRelative.native b/test/odt/native/imageRelative.native
new file mode 100644
--- /dev/null
+++ b/test/odt/native/imageRelative.native
@@ -0,0 +1,10 @@
+[ Para
+    [ Image
+        ( ""
+        , []
+        , [ ( "width" , "5.292cm" ) , ( "height" , "5.292cm" ) ]
+        )
+        []
+        ( "../../lalune.jpg" , "" )
+    ]
+]
diff --git a/test/odt/native/imageWithCaption.native b/test/odt/native/imageWithCaption.native
--- a/test/odt/native/imageWithCaption.native
+++ b/test/odt/native/imageWithCaption.native
@@ -1,1 +1,28 @@
-[Para [Image ("",[],[("width","5.292cm"),("height","5.292cm")]) [Str "Abbildung",Space,Str "1:",Space,Str "Image",Space,Str "caption"] ("Pictures/10000000000000FA000000FAD6A15225.jpg","fig:")]]
+[ Figure
+  ( "" , [] , [] )
+  (Caption
+     Nothing
+     [ Plain
+         [ Str "Image"
+         , Space
+         , Str "caption"
+         ]
+     ])
+  [ Plain
+      [ Image
+          ( ""
+          , []
+          , [ ( "width" , "5.292cm" ) , ( "height" , "5.292cm" ) ]
+          )
+          [ Str "Abbildung"
+          , Space
+          , Str "1:"
+          , Space
+          , Str "Image"
+          , Space
+          , Str "caption"
+          ]
+          ( "Pictures/10000000000000FA000000FAD6A15225.jpg" , "" )
+      ]
+  ]
+]
diff --git a/test/odt/native/listContinueNumbering.native b/test/odt/native/listContinueNumbering.native
new file mode 100644
--- /dev/null
+++ b/test/odt/native/listContinueNumbering.native
@@ -0,0 +1,89 @@
+[ OrderedList
+    ( 1 , Decimal , Period )
+    [ [ Plain
+            [ Str "Some" , Space , Str "text" , Space , Str "(1.)" ]
+        ]
+    ]
+, Para []
+, Para
+    [ Str "Some"
+    , Space
+    , Str "text"
+    , Space
+    , Str "in"
+    , Space
+    , Str "between."
+    ]
+, Para []
+, OrderedList
+    ( 2 , Decimal , Period )
+    [ [ Plain
+            [ Str "Some" , Space , Str "text" , Space , Str "(2.)" ]
+        ]
+    , [ Plain
+            [ Str "Some" , Space , Str "text" , Space , Str "(3.)" ]
+        ]
+    ]
+, Para []
+, Para
+    [ Str "Some"
+    , Space
+    , Str "text"
+    , Space
+    , Str "in"
+    , Space
+    , Str "between."
+    ]
+, Para []
+, OrderedList
+    ( 4 , Decimal , Period )
+    [ [ Plain
+            [ Str "Some" , Space , Str "text" , Space , Str "(4.)" ]
+        ]
+    ]
+, Para []
+, Para
+    [ Str "Some"
+    , Space
+    , Str "text"
+    , Space
+    , Str "before"
+    , Space
+    , Str "starting"
+    , Space
+    , Str "new"
+    , Space
+    , Str "list"
+    , Space
+    , Str "from"
+    , Space
+    , Str "1."
+    ]
+, Para []
+, OrderedList
+    ( 1 , Decimal , Period )
+    [ [ Plain
+            [ Str "Some" , Space , Str "text" , Space , Str "(1.)" ]
+        ]
+    ]
+, Para []
+, Para
+    [ Str "Some"
+    , Space
+    , Str "text"
+    , Space
+    , Str "in"
+    , Space
+    , Str "between."
+    ]
+, Para []
+, OrderedList
+    ( 2 , Decimal , Period )
+    [ [ Plain
+            [ Str "Some" , Space , Str "text" , Space , Str "(2.)" ]
+        ]
+    , [ Plain
+            [ Str "Some" , Space , Str "text" , Space , Str "(3.)" ]
+        ]
+    ]
+]
diff --git a/test/odt/native/listContinueNumbering2.native b/test/odt/native/listContinueNumbering2.native
new file mode 100644
--- /dev/null
+++ b/test/odt/native/listContinueNumbering2.native
@@ -0,0 +1,95 @@
+[ OrderedList
+    ( 1 , Decimal , Period )
+    [ [ Para [ Str "Top" , Space , Str "one" ]
+      , OrderedList
+          ( 1 , LowerAlpha , Period )
+          [[ Plain
+             [ Str "Sub"
+             , Space
+             , Str "item"
+             , Space
+             , Str "1.a"
+             ]
+            ]
+          , [ Plain
+              [ Str "Sub"
+              , Space
+              , Str "item"
+              , Space
+              , Str "1.b"
+              ]
+            ]
+          ]
+      ]
+    ]
+, Para []
+, Para
+    [ Str "Some"
+    , Space
+    , Str "text"
+    , Space
+    , Str "in"
+    , Space
+    , Str "between."
+    ]
+, Para []
+, OrderedList
+    ( 2 , Decimal , Period )
+    [ [ Para [ Str "Top" , Space , Str "two" ]
+      , OrderedList
+          ( 1 , LowerAlpha , Period )
+          [ [ Plain
+              [ Str "Sub"
+              , Space
+              , Str "item"
+              , Space
+              , Str "2.a"
+              ]
+            ]
+          , [ Plain
+              [ Str "Sub"
+              , Space
+              , Str "item"
+              , Space
+              , Str "2.b"
+              ]
+            ]
+          ]
+      ]
+    ]
+, Para []
+, Para
+    [ Str "Some"
+    , Space
+    , Str "text"
+    , Space
+    , Str "in"
+    , Space
+    , Str "between."
+    ]
+, Para []
+, OrderedList
+    ( 3 , Decimal , Period )
+    [ [ Para [ Str "Top" , Space , Str "three" ]
+      , OrderedList
+          ( 1 , LowerAlpha , Period )
+          [ [ Plain
+              [ Str "Sub"
+              , Space
+              , Str "item"
+              , Space
+              , Str "3.a"
+              ]
+            ]
+          , [ Plain
+              [ Str "Sub"
+              , Space
+              , Str "item"
+              , Space
+              , Str "3.b"
+              ]
+            ]
+          ]
+      ]
+    ]
+]
diff --git a/test/odt/native/orderedListHeader.native b/test/odt/native/orderedListHeader.native
new file mode 100644
--- /dev/null
+++ b/test/odt/native/orderedListHeader.native
@@ -0,0 +1,80 @@
+[ OrderedList
+    ( 1 , Decimal , Period )
+    [ [ Plain
+          [ Str "A"
+          , Space
+          , Str "list"
+          , Space
+          , Str "item"
+          , Space
+          , Str "(list-header)"
+          ]
+      ]
+    , [ Plain [ Str "A" , Space , Str "second" ] ]
+    , [ Para [ Str "A" , Space , Str "third" ]
+      , OrderedList
+          ( 1 , Decimal , Period )
+          [ [ Para
+                [ Str "New"
+                , Space
+                , Str "level!"
+                , Space
+                , Str "(list-header)"
+                ]
+            , OrderedList
+                ( 1 , Decimal , Period )
+                [ [ Plain
+                      [ Str "And"
+                      , Space
+                      , Str "another!"
+                      , Space
+                      , Str "(list-header)"
+                      ]
+                  ]
+                , [ Plain
+                      [ Str "It's"
+                      , Space
+                      , Str "great"
+                      , Space
+                      , Str "up"
+                      , Space
+                      , Str "here!"
+                      ]
+                  ]
+                ]
+            ]
+          , [ Plain [ Str "Oh" , Space , Str "noes" ] ]
+          , [ Plain [ Str "We" , Space , Str "fell!" ] ]
+          ]
+      ]
+    , [ Plain [ Str "Maybe" , Space , Str "someone" ] ]
+    , [ Plain [ Str "Pushed" , Space , Str "us?" ] ]
+    ]
+, Para []
+, OrderedList
+    ( 4 , Decimal , Period )
+    [ [ Plain
+          [ Str "Start"
+          , Space
+          , Str "new"
+          , Space
+          , Str "list,"
+          , Space
+          , Str "but"
+          , Space
+          , Str "a"
+          , Space
+          , Str "different"
+          , Space
+          , Str "starting"
+          , Space
+          , Str "point."
+          , Space
+          , Str "(list-header)"
+          ]
+      ]
+    , [ Plain
+          [ Str "Because" , Space , Str "we" , Space , Str "can." ]
+      ]
+    ]
+]
diff --git a/test/odt/native/preformattedText.native b/test/odt/native/preformattedText.native
new file mode 100644
--- /dev/null
+++ b/test/odt/native/preformattedText.native
@@ -0,0 +1,4 @@
+[ CodeBlock
+    ( "" , [] , [] )
+    "void main() {\n    printf(\"Hello world\");\n}"
+]
diff --git a/test/odt/native/preformattedTextParentStyle.native b/test/odt/native/preformattedTextParentStyle.native
new file mode 100644
--- /dev/null
+++ b/test/odt/native/preformattedTextParentStyle.native
@@ -0,0 +1,4 @@
+[ CodeBlock
+    ( "" , [] , [] )
+    "void main() {\n    printf(\"Hello world\");\n}"
+]
diff --git a/test/odt/native/simpleTable.native b/test/odt/native/simpleTable.native
--- a/test/odt/native/simpleTable.native
+++ b/test/odt/native/simpleTable.native
@@ -1,1 +1,1 @@
-[Table [] [AlignDefault,AlignDefault] [0.0,0.0] [[],[]] [[[Plain [Str "Content"]],[Plain [Str "More",Space,Str "content"]]]],Para []]
+[Table ("",[],[]) (Caption Nothing []) [(AlignDefault,ColWidthDefault),(AlignDefault,ColWidthDefault)] (TableHead ("",[],[]) []) [TableBody ("",[],[]) (RowHeadColumns 0) [] [Row ("",[],[]) [Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1) [Plain [Str "Content"]],Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1) [Plain [Str "More",Space,Str "content"]]]]] (TableFoot ("",[],[]) []),Para []]
diff --git a/test/odt/native/simpleTableWithCaption.native b/test/odt/native/simpleTableWithCaption.native
--- a/test/odt/native/simpleTableWithCaption.native
+++ b/test/odt/native/simpleTableWithCaption.native
@@ -1,1 +1,1 @@
-[Table [Str "Table",Space,Str "1:",Space,Str "Some",Space,Str "caption",Space,Str "for",Space,Str "a",Space,Str "table"] [AlignDefault,AlignDefault] [0.0,0.0] [[],[]] [[[Plain [Str "Content"]],[Plain [Str "More",Space,Str "content"]]]],Para []]
+[Table ("",[],[]) (Caption Nothing [Para [Str "Table",Space,Str "1:",Space,Str "Some",Space,Str "caption",Space,Str "for",Space,Str "a",Space,Str "table"]]) [(AlignDefault,ColWidthDefault),(AlignDefault,ColWidthDefault)] (TableHead ("",[],[]) []) [TableBody ("",[],[]) (RowHeadColumns 0) [] [Row ("",[],[]) [Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1) [Plain [Str "Content"]],Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1) [Plain [Str "More",Space,Str "content"]]]]] (TableFoot ("",[],[]) []),Para []]
diff --git a/test/odt/native/simpleTableWithHeader.native b/test/odt/native/simpleTableWithHeader.native
new file mode 100644
--- /dev/null
+++ b/test/odt/native/simpleTableWithHeader.native
@@ -0,0 +1,79 @@
+[ Table
+    ( "" , [] , [] )
+    (Caption Nothing [])
+    [ ( AlignDefault , ColWidthDefault )
+    , ( AlignDefault , ColWidthDefault )
+    , ( AlignDefault , ColWidthDefault )
+    ]
+    (TableHead
+       ( "" , [] , [] )
+       [ Row
+           ( "" , [] , [] )
+           [ Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "A" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "B" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "C" ] ]
+           ]
+       ])
+    [ TableBody
+        ( "" , [] , [] )
+        (RowHeadColumns 0)
+        []
+        [ Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "1" ] ]
+            , Cell
+                ( "" , [] , [] ) AlignDefault (RowSpan 1) (ColSpan 1) [ Plain [] ]
+            , Cell
+                ( "" , [] , [] ) AlignDefault (RowSpan 1) (ColSpan 1) [ Plain [] ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "2" ] ]
+            , Cell
+                ( "" , [] , [] ) AlignDefault (RowSpan 1) (ColSpan 1) [ Plain [] ]
+            , Cell
+                ( "" , [] , [] ) AlignDefault (RowSpan 1) (ColSpan 1) [ Plain [] ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "3" ] ]
+            , Cell
+                ( "" , [] , [] ) AlignDefault (RowSpan 1) (ColSpan 1) [ Plain [] ]
+            , Cell
+                ( "" , [] , [] ) AlignDefault (RowSpan 1) (ColSpan 1) [ Plain [] ]
+            ]
+        ]
+    ]
+    (TableFoot ( "" , [] , [] ) [])
+, Para []
+]
diff --git a/test/odt/native/simpleTableWithMultipleHeaderRows.native b/test/odt/native/simpleTableWithMultipleHeaderRows.native
new file mode 100644
--- /dev/null
+++ b/test/odt/native/simpleTableWithMultipleHeaderRows.native
@@ -0,0 +1,125 @@
+[ Table
+    ( "" , [] , [] )
+    (Caption Nothing [])
+    [ ( AlignDefault , ColWidthDefault )
+    , ( AlignDefault , ColWidthDefault )
+    , ( AlignDefault , ColWidthDefault )
+    ]
+    (TableHead
+       ( "" , [] , [] )
+       [ Row
+           ( "" , [] , [] )
+           [ Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "A" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "B" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "C" ] ]
+           ]
+       , Row
+           ( "" , [] , [] )
+           [ Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "I" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "II" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "II" ] ]
+           ]
+       ])
+    [ TableBody
+        ( "" , [] , [] )
+        (RowHeadColumns 0)
+        []
+        [ Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "1" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [] ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "2" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [] ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "3" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [] ]
+            ]
+        ]
+    ]
+    (TableFoot ( "" , [] , [] ) [])
+, Para []
+]
+
diff --git a/test/odt/native/sourceText.native b/test/odt/native/sourceText.native
new file mode 100644
--- /dev/null
+++ b/test/odt/native/sourceText.native
@@ -0,0 +1,11 @@
+[ Header
+    1
+    ( "test-foo" , [] , [] )
+    [ Span ( "anchor" , [] , [] ) []
+    , Str "Test"
+    , Space
+    , Code ( "" , [] , [] ) "foo"
+    ]
+, Para
+    [ Str "Hello" , Space , Code ( "" , [] , [] ) "world" ]
+]
diff --git a/test/odt/native/tab.native b/test/odt/native/tab.native
new file mode 100644
--- /dev/null
+++ b/test/odt/native/tab.native
@@ -0,0 +1,1 @@
+[Para [Str "Three",Space,Str "tabs",Space,Str "between",Space,Str "A",Space,Str "and",Space,Str "B",Space,Str "will",Space,Str "be",Space,Str "converted",Space,Str "to",Space,Str "one",Space,Str "Space:",Space,Str "A",Space,Str "B."]]
diff --git a/test/odt/native/tableWithContents.native b/test/odt/native/tableWithContents.native
--- a/test/odt/native/tableWithContents.native
+++ b/test/odt/native/tableWithContents.native
@@ -1,1 +1,1 @@
-[Table [] [AlignDefault,AlignDefault] [0.0,0.0] [[],[]]  [[[Plain [Str "A"]],[Plain [Str "B"]]],[[Plain [Str "C"]],[Plain [Str "D"]]]],Para []]
+[Table ("",[],[]) (Caption Nothing []) [(AlignDefault,ColWidthDefault),(AlignDefault,ColWidthDefault)] (TableHead ("",[],[]) []) [TableBody ("",[],[]) (RowHeadColumns 0) [] [Row ("",[],[]) [Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1) [Plain [Str "A"]],Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1) [Plain [Str "B"]]],Row ("",[],[]) [Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1) [Plain [Str "C"]],Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1) [Plain [Str "D"]]]]] (TableFoot ("",[],[]) []),Para []]
diff --git a/test/odt/native/tableWithSpans.native b/test/odt/native/tableWithSpans.native
new file mode 100644
--- /dev/null
+++ b/test/odt/native/tableWithSpans.native
@@ -0,0 +1,134 @@
+[ Table
+    ( "" , [] , [] )
+    (Caption Nothing [])
+    [ ( AlignDefault , ColWidthDefault )
+    , ( AlignDefault , ColWidthDefault )
+    , ( AlignDefault , ColWidthDefault )
+    ]
+    (TableHead
+       ( "" , [] , [] )
+       [ Row
+           ( "" , [] , [] )
+           [ Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 2)
+               (ColSpan 1)
+               [ Plain
+                   [ Str "H1"
+                   , Space
+                   , Str "Rowspan"
+                   , Space
+                   , Str "2"
+                   ]
+               ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "H1-2" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "H1-3" ] ]
+           ]
+       , Row
+           ( "" , [] , [] )
+           [ Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 2)
+               [ Plain [ Str "H2-2/3" ] ]
+           ]
+       ])
+    [ TableBody
+        ( "" , [] , [] )
+        (RowHeadColumns 0)
+        []
+        [ Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "B1-1" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "B1-2" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 3)
+                (ColSpan 1)
+                [ Plain [ Str "Rowspan" , Space , Str "3" ] ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "B2-1" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "B2-2" ] ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 2)
+                [ Plain [ Str "Columnspan" , Space , Str "2" ] ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "B4-1" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 2)
+                (ColSpan 2)
+                [ Plain
+                    [ Str "Columnspan"
+                    , Space
+                    , Str "&"
+                    , Space
+                    , Str "Rowspan"
+                    , Space
+                    , Str "2"
+                    ]
+                ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "B5-1" ] ]
+            ]
+        ]
+    ]
+    (TableFoot ( "" , [] , [] ) [])
+, Para []
+]
diff --git a/test/odt/native/unorderedListHeader.native b/test/odt/native/unorderedListHeader.native
new file mode 100644
--- /dev/null
+++ b/test/odt/native/unorderedListHeader.native
@@ -0,0 +1,50 @@
+[ BulletList
+    [ [ Plain
+          [ Str "A"
+          , Space
+          , Str "list"
+          , Space
+          , Str "item"
+          , Space
+          , Str "(list-header)"
+          ]
+      ]
+    , [ Plain [ Str "A" , Space , Str "second" ] ]
+    , [ Para [ Str "A" , Space , Str "third" ]
+      , BulletList
+          [ [ Para
+                [ Str "New"
+                , Space
+                , Str "level!"
+                , Space
+                , Str "(list-header)"
+                ]
+            , BulletList
+                [ [ Plain
+                      [ Str "And"
+                      , Space
+                      , Str "another!"
+                      , Space
+                      , Str "(list-header)"
+                      ]
+                  ]
+                , [ Plain
+                      [ Str "It's"
+                      , Space
+                      , Str "great"
+                      , Space
+                      , Str "up"
+                      , Space
+                      , Str "here!"
+                      ]
+                  ]
+                ]
+            ]
+          , [ Plain [ Str "Oh" , Space , Str "noes" ] ]
+          , [ Plain [ Str "We" , Space , Str "fell!" ] ]
+          ]
+      ]
+    , [ Plain [ Str "Maybe" , Space , Str "someone" ] ]
+    , [ Plain [ Str "Pushed" , Space , Str "us?" ] ]
+    ]
+]
diff --git a/test/odt/odt/blockquote2.odt b/test/odt/odt/blockquote2.odt
new file mode 100644
Binary files /dev/null and b/test/odt/odt/blockquote2.odt differ
diff --git a/test/odt/odt/imageRelative.odt b/test/odt/odt/imageRelative.odt
new file mode 100644
Binary files /dev/null and b/test/odt/odt/imageRelative.odt differ
diff --git a/test/odt/odt/listContinueNumbering.odt b/test/odt/odt/listContinueNumbering.odt
new file mode 100644
Binary files /dev/null and b/test/odt/odt/listContinueNumbering.odt differ
diff --git a/test/odt/odt/listContinueNumbering2.odt b/test/odt/odt/listContinueNumbering2.odt
new file mode 100644
Binary files /dev/null and b/test/odt/odt/listContinueNumbering2.odt differ
diff --git a/test/odt/odt/orderedListHeader.odt b/test/odt/odt/orderedListHeader.odt
new file mode 100644
Binary files /dev/null and b/test/odt/odt/orderedListHeader.odt differ
diff --git a/test/odt/odt/preformattedText.odt b/test/odt/odt/preformattedText.odt
new file mode 100644
Binary files /dev/null and b/test/odt/odt/preformattedText.odt differ
diff --git a/test/odt/odt/preformattedTextParentStyle.odt b/test/odt/odt/preformattedTextParentStyle.odt
new file mode 100644
Binary files /dev/null and b/test/odt/odt/preformattedTextParentStyle.odt differ
diff --git a/test/odt/odt/simpleTableWithHeader.odt b/test/odt/odt/simpleTableWithHeader.odt
new file mode 100644
Binary files /dev/null and b/test/odt/odt/simpleTableWithHeader.odt differ
diff --git a/test/odt/odt/simpleTableWithMultipleHeaderRows.odt b/test/odt/odt/simpleTableWithMultipleHeaderRows.odt
new file mode 100644
Binary files /dev/null and b/test/odt/odt/simpleTableWithMultipleHeaderRows.odt differ
diff --git a/test/odt/odt/sourceText.odt b/test/odt/odt/sourceText.odt
new file mode 100644
Binary files /dev/null and b/test/odt/odt/sourceText.odt differ
diff --git a/test/odt/odt/tab.odt b/test/odt/odt/tab.odt
new file mode 100644
Binary files /dev/null and b/test/odt/odt/tab.odt differ
diff --git a/test/odt/odt/tableWithSpans.odt b/test/odt/odt/tableWithSpans.odt
new file mode 100644
Binary files /dev/null and b/test/odt/odt/tableWithSpans.odt differ
diff --git a/test/odt/odt/unorderedListHeader.odt b/test/odt/odt/unorderedListHeader.odt
new file mode 100644
Binary files /dev/null and b/test/odt/odt/unorderedListHeader.odt differ
diff --git a/test/opml-reader.native b/test/opml-reader.native
--- a/test/opml-reader.native
+++ b/test/opml-reader.native
@@ -1,66 +1,123 @@
-Pandoc (Meta {unMeta = fromList [("author",MetaList [MetaInlines [Str "Dave",Space,Str "Winer"]]),("date",MetaInlines [Str "Thu,",Space,Str "14",Space,Str "Jul",Space,Str "2005",Space,Str "23:41:05",Space,Str "GMT"]),("title",MetaInlines [Str "States"])]})
-[Header 1 ("",[],[]) [Str "United",Space,Str "States"]
-,Header 2 ("",[],[]) [Str "Far",Space,Str "West"]
-,Header 3 ("",[],[]) [Str "Alaska"]
-,Header 3 ("",[],[]) [Str "California"]
-,Header 3 ("",[],[]) [Str "Hawaii"]
-,Header 3 ("",[],[]) [Strong [Str "Nevada"]]
-,Para [Str "I",Space,Str "lived",Space,Str "here",Space,Emph [Str "once"],Str "."]
-,Para [Str "Loved",Space,Str "it."]
-,Header 4 ("",[],[]) [Link ("",[],[]) [Str "Reno"] ("http://www.reno.gov","")]
-,Header 4 ("",[],[]) [Str "Las",Space,Str "Vegas"]
-,Header 4 ("",[],[]) [Str "Ely"]
-,Header 4 ("",[],[]) [Str "Gerlach"]
-,Header 3 ("",[],[]) [Str "Oregon"]
-,Header 3 ("",[],[]) [Str "Washington"]
-,Header 2 ("",[],[]) [Str "Great",Space,Str "Plains"]
-,Header 3 ("",[],[]) [Str "Kansas"]
-,Header 3 ("",[],[]) [Str "Nebraska"]
-,Header 3 ("",[],[]) [Str "North",Space,Str "Dakota"]
-,Header 3 ("",[],[]) [Str "Oklahoma"]
-,Header 3 ("",[],[]) [Str "South",Space,Str "Dakota"]
-,Header 2 ("",[],[]) [Str "Mid-Atlantic"]
-,Header 3 ("",[],[]) [Str "Delaware"]
-,Header 3 ("",[],[]) [Str "Maryland"]
-,Header 3 ("",[],[]) [Str "New",Space,Str "Jersey"]
-,Header 3 ("",[],[]) [Str "New",Space,Str "York"]
-,Header 3 ("",[],[]) [Str "Pennsylvania"]
-,Header 2 ("",[],[]) [Str "Midwest"]
-,Header 3 ("",[],[]) [Str "Illinois"]
-,Header 3 ("",[],[]) [Str "Indiana"]
-,Header 3 ("",[],[]) [Str "Iowa"]
-,Header 3 ("",[],[]) [Str "Kentucky"]
-,Header 3 ("",[],[]) [Str "Michigan"]
-,Header 3 ("",[],[]) [Str "Minnesota"]
-,Header 3 ("",[],[]) [Str "Missouri"]
-,Header 3 ("",[],[]) [Str "Ohio"]
-,Header 3 ("",[],[]) [Str "West",Space,Str "Virginia"]
-,Header 3 ("",[],[]) [Str "Wisconsin"]
-,Header 2 ("",[],[]) [Str "Mountains"]
-,Header 3 ("",[],[]) [Str "Colorado"]
-,Header 3 ("",[],[]) [Str "Idaho"]
-,Header 3 ("",[],[]) [Str "Montana"]
-,Header 3 ("",[],[]) [Str "Utah"]
-,Header 3 ("",[],[]) [Str "Wyoming"]
-,Header 2 ("",[],[]) [Str "New",Space,Str "England"]
-,Header 3 ("",[],[]) [Str "Connecticut"]
-,Header 3 ("",[],[]) [Str "Maine"]
-,Header 3 ("",[],[]) [Str "Massachusetts"]
-,Header 3 ("",[],[]) [Str "New",Space,Str "Hampshire"]
-,Header 3 ("",[],[]) [Str "Rhode",Space,Str "Island"]
-,Header 3 ("",[],[]) [Str "Vermont"]
-,Header 2 ("",[],[]) [Str "South"]
-,Header 3 ("",[],[]) [Str "Alabama"]
-,Header 3 ("",[],[]) [Str "Arkansas"]
-,Header 3 ("",[],[]) [Str "Florida"]
-,Header 3 ("",[],[]) [Str "Georgia"]
-,Header 3 ("",[],[]) [Str "Louisiana"]
-,Header 3 ("",[],[]) [Str "Mississippi"]
-,Header 3 ("",[],[]) [Str "North",Space,Str "Carolina"]
-,Header 3 ("",[],[]) [Str "South",Space,Str "Carolina"]
-,Header 3 ("",[],[]) [Str "Tennessee"]
-,Header 3 ("",[],[]) [Str "Virginia"]
-,Header 2 ("",[],[]) [Str "Southwest"]
-,Header 3 ("",[],[]) [Str "Arizona"]
-,Header 3 ("",[],[]) [Str "New",Space,Str "Mexico"]
-,Header 3 ("",[],[]) [Str "Texas"]]
+Pandoc
+  Meta
+    { unMeta =
+        fromList
+          [ ( "author"
+            , MetaList
+                [ MetaInlines [ Str "Dave" , Space , Str "Winer" ] ]
+            )
+          , ( "date"
+            , MetaInlines
+                [ Str "Thu,"
+                , Space
+                , Str "14"
+                , Space
+                , Str "Jul"
+                , Space
+                , Str "2005"
+                , Space
+                , Str "23:41:05"
+                , Space
+                , Str "GMT"
+                ]
+            )
+          , ( "title" , MetaInlines [ Str "States" ] )
+          ]
+    }
+  [ Header
+      1 ( "" , [] , [] ) [ Str "United" , Space , Str "States" ]
+  , Header
+      2 ( "" , [] , [] ) [ Str "Far" , Space , Str "West" ]
+  , Header 3 ( "" , [] , [] ) [ Str "Alaska" ]
+  , Header 3 ( "" , [] , [] ) [ Str "California" ]
+  , Header 3 ( "" , [] , [] ) [ Str "Hawaii" ]
+  , Header 3 ( "" , [] , [] ) [ Strong [ Str "Nevada" ] ]
+  , Para
+      [ Str "I"
+      , Space
+      , Str "lived"
+      , Space
+      , Str "here"
+      , Space
+      , Emph [ Str "once" ]
+      , Str "."
+      ]
+  , Para [ Str "Loved" , Space , Str "it." ]
+  , Header
+      4
+      ( "" , [] , [] )
+      [ Link
+          ( "" , [] , [] )
+          [ Str "Reno" ]
+          ( "http://www.reno.gov" , "" )
+      ]
+  , Header
+      4 ( "" , [] , [] ) [ Str "Las" , Space , Str "Vegas" ]
+  , Header 4 ( "" , [] , [] ) [ Str "Ely" ]
+  , Header 4 ( "" , [] , [] ) [ Str "Gerlach" ]
+  , Header 3 ( "" , [] , [] ) [ Str "Oregon" ]
+  , Header 3 ( "" , [] , [] ) [ Str "Washington" ]
+  , Header
+      2 ( "" , [] , [] ) [ Str "Great" , Space , Str "Plains" ]
+  , Header 3 ( "" , [] , [] ) [ Str "Kansas" ]
+  , Header 3 ( "" , [] , [] ) [ Str "Nebraska" ]
+  , Header
+      3 ( "" , [] , [] ) [ Str "North" , Space , Str "Dakota" ]
+  , Header 3 ( "" , [] , [] ) [ Str "Oklahoma" ]
+  , Header
+      3 ( "" , [] , [] ) [ Str "South" , Space , Str "Dakota" ]
+  , Header 2 ( "" , [] , [] ) [ Str "Mid-Atlantic" ]
+  , Header 3 ( "" , [] , [] ) [ Str "Delaware" ]
+  , Header 3 ( "" , [] , [] ) [ Str "Maryland" ]
+  , Header
+      3 ( "" , [] , [] ) [ Str "New" , Space , Str "Jersey" ]
+  , Header
+      3 ( "" , [] , [] ) [ Str "New" , Space , Str "York" ]
+  , Header 3 ( "" , [] , [] ) [ Str "Pennsylvania" ]
+  , Header 2 ( "" , [] , [] ) [ Str "Midwest" ]
+  , Header 3 ( "" , [] , [] ) [ Str "Illinois" ]
+  , Header 3 ( "" , [] , [] ) [ Str "Indiana" ]
+  , Header 3 ( "" , [] , [] ) [ Str "Iowa" ]
+  , Header 3 ( "" , [] , [] ) [ Str "Kentucky" ]
+  , Header 3 ( "" , [] , [] ) [ Str "Michigan" ]
+  , Header 3 ( "" , [] , [] ) [ Str "Minnesota" ]
+  , Header 3 ( "" , [] , [] ) [ Str "Missouri" ]
+  , Header 3 ( "" , [] , [] ) [ Str "Ohio" ]
+  , Header
+      3 ( "" , [] , [] ) [ Str "West" , Space , Str "Virginia" ]
+  , Header 3 ( "" , [] , [] ) [ Str "Wisconsin" ]
+  , Header 2 ( "" , [] , [] ) [ Str "Mountains" ]
+  , Header 3 ( "" , [] , [] ) [ Str "Colorado" ]
+  , Header 3 ( "" , [] , [] ) [ Str "Idaho" ]
+  , Header 3 ( "" , [] , [] ) [ Str "Montana" ]
+  , Header 3 ( "" , [] , [] ) [ Str "Utah" ]
+  , Header 3 ( "" , [] , [] ) [ Str "Wyoming" ]
+  , Header
+      2 ( "" , [] , [] ) [ Str "New" , Space , Str "England" ]
+  , Header 3 ( "" , [] , [] ) [ Str "Connecticut" ]
+  , Header 3 ( "" , [] , [] ) [ Str "Maine" ]
+  , Header 3 ( "" , [] , [] ) [ Str "Massachusetts" ]
+  , Header
+      3 ( "" , [] , [] ) [ Str "New" , Space , Str "Hampshire" ]
+  , Header
+      3 ( "" , [] , [] ) [ Str "Rhode" , Space , Str "Island" ]
+  , Header 3 ( "" , [] , [] ) [ Str "Vermont" ]
+  , Header 2 ( "" , [] , [] ) [ Str "South" ]
+  , Header 3 ( "" , [] , [] ) [ Str "Alabama" ]
+  , Header 3 ( "" , [] , [] ) [ Str "Arkansas" ]
+  , Header 3 ( "" , [] , [] ) [ Str "Florida" ]
+  , Header 3 ( "" , [] , [] ) [ Str "Georgia" ]
+  , Header 3 ( "" , [] , [] ) [ Str "Louisiana" ]
+  , Header 3 ( "" , [] , [] ) [ Str "Mississippi" ]
+  , Header
+      3 ( "" , [] , [] ) [ Str "North" , Space , Str "Carolina" ]
+  , Header
+      3 ( "" , [] , [] ) [ Str "South" , Space , Str "Carolina" ]
+  , Header 3 ( "" , [] , [] ) [ Str "Tennessee" ]
+  , Header 3 ( "" , [] , [] ) [ Str "Virginia" ]
+  , Header 2 ( "" , [] , [] ) [ Str "Southwest" ]
+  , Header 3 ( "" , [] , [] ) [ Str "Arizona" ]
+  , Header
+      3 ( "" , [] , [] ) [ Str "New" , Space , Str "Mexico" ]
+  , Header 3 ( "" , [] , [] ) [ Str "Texas" ]
+  ]
diff --git a/test/org-select-tags.native b/test/org-select-tags.native
new file mode 100644
--- /dev/null
+++ b/test/org-select-tags.native
@@ -0,0 +1,103 @@
+Pandoc
+  Meta { unMeta = fromList [] }
+  [ Header
+      1
+      ( "will-appear-because-it-is-the-ancestor-of-something-tagged-yes"
+      , []
+      , []
+      )
+      [ Str "Will"
+      , Space
+      , Str "appear"
+      , Space
+      , Str "because"
+      , Space
+      , Str "it"
+      , Space
+      , Str "is"
+      , Space
+      , Str "the"
+      , Space
+      , Str "ancestor"
+      , Space
+      , Str "of"
+      , Space
+      , Str "something"
+      , Space
+      , Str "tagged"
+      , Space
+      , Str "\"yes\""
+      ]
+  , Header
+      2
+      ( "will-appear" , [] , [] )
+      [ Str "Will"
+      , Space
+      , Str "appear"
+      , Space
+      , Span
+          ( "" , [ "tag" ] , [ ( "tag-name" , "yes" ) ] )
+          [ SmallCaps [ Str "yes" ] ]
+      ]
+  , Header
+      3
+      ( "will-appear-since-the-entire-subtree-of-something-selected-will-appear"
+      , []
+      , []
+      )
+      [ Str "Will"
+      , Space
+      , Str "appear"
+      , Space
+      , Str "since"
+      , Space
+      , Str "the"
+      , Space
+      , Str "entire"
+      , Space
+      , Str "subtree"
+      , Space
+      , Str "of"
+      , Space
+      , Str "something"
+      , Space
+      , Str "selected"
+      , Space
+      , Str "will"
+      , Space
+      , Str "appear"
+      ]
+  , OrderedList
+      ( 1 , DefaultStyle , DefaultDelim )
+      [ [ Para [ Str "Will" , Space , Str "appear" ] ] ]
+  , Header
+      2
+      ( "will-appear-because-it-is-the-ancestor-of-something-listed-in-select-tags"
+      , []
+      , []
+      )
+      [ Str "Will"
+      , Space
+      , Str "appear"
+      , Space
+      , Str "because"
+      , Space
+      , Str "it"
+      , Space
+      , Str "is"
+      , Space
+      , Str "the"
+      , Space
+      , Str "ancestor"
+      , Space
+      , Str "of"
+      , Space
+      , Str "something"
+      , Space
+      , Str "listed"
+      , Space
+      , Str "in"
+      , Space
+      , Str "SELECT-TAGS"
+      ]
+  ]
diff --git a/test/org-select-tags.org b/test/org-select-tags.org
new file mode 100644
--- /dev/null
+++ b/test/org-select-tags.org
@@ -0,0 +1,17 @@
+#+select_tags: yes no
+#+exclude_tags: no
+
+In a document containing one or more trees containing a tag
+listed in SELECT_TAGS, only those trees and their ancestor nodes will appear;
+this text and any other text preceding the first headline
+won't appear for such documents.
+
+* Will appear because it is the ancestor of something tagged "yes"
+** Will appear                                                           :yes:
+*** Will appear since the entire subtree of something selected will appear
+**** Will appear
+*** Will not appear since this has tagged with something in EXCLUDE-TAGS :no:
+** Will not appear since it's not an ancestor of listed in SELECT-TAGS
+** Will appear because it is the ancestor of something listed in SELECT-TAGS
+*** Will not appear because it has an EXCLUDE-TAG, but since "no" is also listed as a SELECT-TAG, it will force its parent to appear :no:
+* Will not appear
diff --git a/test/pipe-tables.native b/test/pipe-tables.native
--- a/test/pipe-tables.native
+++ b/test/pipe-tables.native
@@ -1,115 +1,927 @@
-[Para [Str "Simplest",Space,Str "table",Space,Str "without",Space,Str "caption:"]
-,Table [] [AlignDefault,AlignDefault,AlignDefault] [0.0,0.0,0.0]
- [[Plain [Str "Default1"]]
- ,[Plain [Str "Default2"]]
- ,[Plain [Str "Default3"]]]
- [[[Plain [Str "12"]]
-  ,[Plain [Str "12"]]
-  ,[Plain [Str "12"]]]
- ,[[Plain [Str "123"]]
-  ,[Plain [Str "123"]]
-  ,[Plain [Str "123"]]]
- ,[[Plain [Str "1"]]
-  ,[Plain [Str "1"]]
-  ,[Plain [Str "1"]]]]
-,Para [Str "Simple",Space,Str "table",Space,Str "with",Space,Str "caption:"]
-,Table [Str "Demonstration",Space,Str "of",Space,Str "simple",Space,Str "table",Space,Str "syntax."] [AlignRight,AlignLeft,AlignDefault,AlignCenter] [0.0,0.0,0.0,0.0]
- [[Plain [Str "Right"]]
- ,[Plain [Str "Left"]]
- ,[Plain [Str "Default"]]
- ,[Plain [Str "Center"]]]
- [[[Plain [Str "12"]]
-  ,[Plain [Str "12"]]
-  ,[Plain [Str "12"]]
-  ,[Plain [Str "12"]]]
- ,[[Plain [Str "123"]]
-  ,[Plain [Str "123"]]
-  ,[Plain [Str "123"]]
-  ,[Plain [Str "123"]]]
- ,[[Plain [Str "1"]]
-  ,[Plain [Str "1"]]
-  ,[Plain [Str "1"]]
-  ,[Plain [Str "1"]]]]
-,Para [Str "Simple",Space,Str "table",Space,Str "without",Space,Str "caption:"]
-,Table [] [AlignRight,AlignLeft,AlignCenter] [0.0,0.0,0.0]
- [[Plain [Str "Right"]]
- ,[Plain [Str "Left"]]
- ,[Plain [Str "Center"]]]
- [[[Plain [Str "12"]]
-  ,[Plain [Str "12"]]
-  ,[Plain [Str "12"]]]
- ,[[Plain [Str "123"]]
-  ,[Plain [Str "123"]]
-  ,[Plain [Str "123"]]]
- ,[[Plain [Str "1"]]
-  ,[Plain [Str "1"]]
-  ,[Plain [Str "1"]]]]
-,Para [Str "Headerless",Space,Str "table",Space,Str "without",Space,Str "caption:"]
-,Table [] [AlignRight,AlignLeft,AlignCenter] [0.0,0.0,0.0]
- [[]
- ,[]
- ,[]]
- [[[Plain [Str "12"]]
-  ,[Plain [Str "12"]]
-  ,[Plain [Str "12"]]]
- ,[[Plain [Str "123"]]
-  ,[Plain [Str "123"]]
-  ,[Plain [Str "123"]]]
- ,[[Plain [Str "1"]]
-  ,[Plain [Str "1"]]
-  ,[Plain [Str "1"]]]]
-,Para [Str "Table",Space,Str "without",Space,Str "sides:"]
-,Table [] [AlignDefault,AlignRight] [0.0,0.0]
- [[Plain [Str "Fruit"]]
- ,[Plain [Str "Quantity"]]]
- [[[Plain [Str "apple"]]
-  ,[Plain [Str "5"]]]
- ,[[Plain [Str "orange"]]
-  ,[Plain [Str "17"]]]
- ,[[Plain [Str "pear"]]
-  ,[Plain [Str "302"]]]]
-,Para [Str "One-column:"]
-,Table [] [AlignDefault] [0.0]
- [[Plain [Str "hi"]]]
- [[[Plain [Str "lo"]]]]
-,Para [Str "Header-less",Space,Str "one-column:"]
-,Table [] [AlignCenter] [0.0]
- [[]]
- [[[Plain [Str "hi"]]]]
-,Para [Str "Indented",Space,Str "left",Space,Str "column:"]
-,Table [] [AlignRight,AlignLeft] [0.0,0.0]
- [[Plain [Str "Number",Space,Str "of",Space,Str "siblings"]]
- ,[Plain [Str "Salary"]]]
- [[[Plain [Str "3"]]
-  ,[Plain [Str "33"]]]
- ,[[Plain [Str "4"]]
-  ,[Plain [Str "44"]]]]
-,Para [Str "Long",Space,Str "pipe",Space,Str "table",Space,Str "with",Space,Str "relative",Space,Str "widths:"]
-,Table [] [AlignDefault,AlignDefault,AlignDefault] [0.15517241379310345,0.1724137931034483,0.6724137931034483]
- [[Plain [Str "Default1"]]
- ,[Plain [Str "Default2"]]
- ,[Plain [Str "Default3"]]]
- [[[Plain [Str "123"]]
-  ,[Plain [Str "this",Space,Str "is",Space,Str "a",Space,Str "table",Space,Str "cell"]]
-  ,[Plain [Str "and",Space,Str "this",Space,Str "is",Space,Str "a",Space,Str "really",Space,Str "long",Space,Str "table",Space,Str "cell",Space,Str "that",Space,Str "will",Space,Str "probably",Space,Str "need",Space,Str "wrapping"]]]
- ,[[Plain [Str "123"]]
-  ,[Plain [Str "123"]]
-  ,[Plain [Str "123"]]]]
-,Para [Str "Pipe",Space,Str "table",Space,Str "with",Space,Str "no",Space,Str "body:"]
-,Table [] [AlignDefault] [0.0]
- [[Plain [Str "Header"]]]
- []
-,Para [Str "Pipe",Space,Str "table",Space,Str "with",Space,Str "tricky",Space,Str "cell",Space,Str "contents",Space,Str "(see",Space,Str "#2765):"]
-,Table [] [AlignLeft,AlignRight,AlignRight] [0.0,0.0,0.0]
- [[]
- ,[Plain [Str "IP_gene8-_1st"]]
- ,[Plain [Str "IP_gene8+_1st"]]]
- [[[Plain [Str "IP_gene8-_1st"]]
-  ,[Plain [Str "1.0000000"]]
-  ,[Plain [Str "0.4357325"]]]
- ,[[Plain [Str "IP_gene8+_1st"]]
-  ,[Plain [Str "0.4357325"]]
-  ,[Plain [Str "1.0000000"]]]
- ,[[Plain [Str "foo",Code ("",[],[]) "bar|baz"]]
-  ,[Plain [Str "and|escaped"]]
-  ,[Plain [Str "3.0000000"]]]]]
+[ Para
+    [ Str "Simplest"
+    , Space
+    , Str "table"
+    , Space
+    , Str "without"
+    , Space
+    , Str "caption:"
+    ]
+, Table
+    ( "" , [] , [] )
+    (Caption Nothing [])
+    [ ( AlignDefault , ColWidthDefault )
+    , ( AlignDefault , ColWidthDefault )
+    , ( AlignDefault , ColWidthDefault )
+    ]
+    (TableHead
+       ( "" , [] , [] )
+       [ Row
+           ( "" , [] , [] )
+           [ Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "Default1" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "Default2" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "Default3" ] ]
+           ]
+       ])
+    [ TableBody
+        ( "" , [] , [] )
+        (RowHeadColumns 0)
+        []
+        [ Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "12" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "12" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "12" ] ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "123" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "123" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "123" ] ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "1" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "1" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "1" ] ]
+            ]
+        ]
+    ]
+    (TableFoot ( "" , [] , [] ) [])
+, Para
+    [ Str "Simple"
+    , Space
+    , Str "table"
+    , Space
+    , Str "with"
+    , Space
+    , Str "caption:"
+    ]
+, Table
+    ( "" , [] , [] )
+    (Caption
+       Nothing
+       [ Plain
+           [ Str "Demonstration"
+           , Space
+           , Str "of"
+           , Space
+           , Str "simple"
+           , Space
+           , Str "table"
+           , Space
+           , Str "syntax."
+           ]
+       ])
+    [ ( AlignRight , ColWidthDefault )
+    , ( AlignLeft , ColWidthDefault )
+    , ( AlignDefault , ColWidthDefault )
+    , ( AlignCenter , ColWidthDefault )
+    ]
+    (TableHead
+       ( "" , [] , [] )
+       [ Row
+           ( "" , [] , [] )
+           [ Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "Right" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "Left" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "Default" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "Center" ] ]
+           ]
+       ])
+    [ TableBody
+        ( "" , [] , [] )
+        (RowHeadColumns 0)
+        []
+        [ Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "12" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "12" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "12" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "12" ] ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "123" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "123" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "123" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "123" ] ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "1" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "1" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "1" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "1" ] ]
+            ]
+        ]
+    ]
+    (TableFoot ( "" , [] , [] ) [])
+, Para
+    [ Str "Simple"
+    , Space
+    , Str "table"
+    , Space
+    , Str "without"
+    , Space
+    , Str "caption:"
+    ]
+, Table
+    ( "" , [] , [] )
+    (Caption Nothing [])
+    [ ( AlignRight , ColWidthDefault )
+    , ( AlignLeft , ColWidthDefault )
+    , ( AlignCenter , ColWidthDefault )
+    ]
+    (TableHead
+       ( "" , [] , [] )
+       [ Row
+           ( "" , [] , [] )
+           [ Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "Right" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "Left" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "Center" ] ]
+           ]
+       ])
+    [ TableBody
+        ( "" , [] , [] )
+        (RowHeadColumns 0)
+        []
+        [ Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "12" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "12" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "12" ] ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "123" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "123" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "123" ] ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "1" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "1" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "1" ] ]
+            ]
+        ]
+    ]
+    (TableFoot ( "" , [] , [] ) [])
+, Para
+    [ Str "Headerless"
+    , Space
+    , Str "table"
+    , Space
+    , Str "without"
+    , Space
+    , Str "caption:"
+    ]
+, Table
+    ( "" , [] , [] )
+    (Caption Nothing [])
+    [ ( AlignRight , ColWidthDefault )
+    , ( AlignLeft , ColWidthDefault )
+    , ( AlignCenter , ColWidthDefault )
+    ]
+    (TableHead ( "" , [] , [] ) [])
+    [ TableBody
+        ( "" , [] , [] )
+        (RowHeadColumns 0)
+        []
+        [ Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "12" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "12" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "12" ] ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "123" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "123" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "123" ] ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "1" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "1" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "1" ] ]
+            ]
+        ]
+    ]
+    (TableFoot ( "" , [] , [] ) [])
+, Para
+    [ Str "Table" , Space , Str "without" , Space , Str "sides:" ]
+, Table
+    ( "" , [] , [] )
+    (Caption Nothing [])
+    [ ( AlignDefault , ColWidthDefault )
+    , ( AlignRight , ColWidthDefault )
+    ]
+    (TableHead
+       ( "" , [] , [] )
+       [ Row
+           ( "" , [] , [] )
+           [ Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "Fruit" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "Quantity" ] ]
+           ]
+       ])
+    [ TableBody
+        ( "" , [] , [] )
+        (RowHeadColumns 0)
+        []
+        [ Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "apple" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "5" ] ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "orange" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "17" ] ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "pear" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "302" ] ]
+            ]
+        ]
+    ]
+    (TableFoot ( "" , [] , [] ) [])
+, Para [ Str "One-column:" ]
+, Table
+    ( "" , [] , [] )
+    (Caption Nothing [])
+    [ ( AlignDefault , ColWidthDefault ) ]
+    (TableHead
+       ( "" , [] , [] )
+       [ Row
+           ( "" , [] , [] )
+           [ Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "hi" ] ]
+           ]
+       ])
+    [ TableBody
+        ( "" , [] , [] )
+        (RowHeadColumns 0)
+        []
+        [ Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "lo" ] ]
+            ]
+        ]
+    ]
+    (TableFoot ( "" , [] , [] ) [])
+, Para [ Str "Header-less" , Space , Str "one-column:" ]
+, Table
+    ( "" , [] , [] )
+    (Caption Nothing [])
+    [ ( AlignCenter , ColWidthDefault ) ]
+    (TableHead ( "" , [] , [] ) [])
+    [ TableBody
+        ( "" , [] , [] )
+        (RowHeadColumns 0)
+        []
+        [ Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "hi" ] ]
+            ]
+        ]
+    ]
+    (TableFoot ( "" , [] , [] ) [])
+, Para
+    [ Str "Indented" , Space , Str "left" , Space , Str "column:" ]
+, Table
+    ( "" , [] , [] )
+    (Caption Nothing [])
+    [ ( AlignRight , ColWidthDefault )
+    , ( AlignLeft , ColWidthDefault )
+    ]
+    (TableHead
+       ( "" , [] , [] )
+       [ Row
+           ( "" , [] , [] )
+           [ Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain
+                   [ Str "Number" , Space , Str "of" , Space , Str "siblings" ]
+               ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "Salary" ] ]
+           ]
+       ])
+    [ TableBody
+        ( "" , [] , [] )
+        (RowHeadColumns 0)
+        []
+        [ Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "3" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "33" ] ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "4" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "44" ] ]
+            ]
+        ]
+    ]
+    (TableFoot ( "" , [] , [] ) [])
+, Para
+    [ Str "Long"
+    , Space
+    , Str "pipe"
+    , Space
+    , Str "table"
+    , Space
+    , Str "with"
+    , Space
+    , Str "relative"
+    , Space
+    , Str "widths:"
+    ]
+, Table
+    ( "" , [] , [] )
+    (Caption Nothing [])
+    [ ( AlignDefault , ColWidth 0.15517241379310345 )
+    , ( AlignDefault , ColWidth 0.1724137931034483 )
+    , ( AlignDefault , ColWidth 0.6724137931034483 )
+    ]
+    (TableHead
+       ( "" , [] , [] )
+       [ Row
+           ( "" , [] , [] )
+           [ Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "Default1" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "Default2" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "Default3" ] ]
+           ]
+       ])
+    [ TableBody
+        ( "" , [] , [] )
+        (RowHeadColumns 0)
+        []
+        [ Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "123" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain
+                    [ Str "this"
+                    , Space
+                    , Str "is"
+                    , Space
+                    , Str "a"
+                    , Space
+                    , Str "table"
+                    , Space
+                    , Str "cell"
+                    ]
+                ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain
+                    [ Str "and"
+                    , Space
+                    , Str "this"
+                    , Space
+                    , Str "is"
+                    , Space
+                    , Str "a"
+                    , Space
+                    , Str "really"
+                    , Space
+                    , Str "long"
+                    , Space
+                    , Str "table"
+                    , Space
+                    , Str "cell"
+                    , Space
+                    , Str "that"
+                    , Space
+                    , Str "will"
+                    , Space
+                    , Str "probably"
+                    , Space
+                    , Str "need"
+                    , Space
+                    , Str "wrapping"
+                    ]
+                ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "123" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "123" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "123" ] ]
+            ]
+        ]
+    ]
+    (TableFoot ( "" , [] , [] ) [])
+, Para
+    [ Str "Pipe"
+    , Space
+    , Str "table"
+    , Space
+    , Str "with"
+    , Space
+    , Str "no"
+    , Space
+    , Str "body:"
+    ]
+, Table
+    ( "" , [] , [] )
+    (Caption Nothing [])
+    [ ( AlignDefault , ColWidthDefault ) ]
+    (TableHead
+       ( "" , [] , [] )
+       [ Row
+           ( "" , [] , [] )
+           [ Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "Header" ] ]
+           ]
+       ])
+    [ TableBody ( "" , [] , [] ) (RowHeadColumns 0) [] [] ]
+    (TableFoot ( "" , [] , [] ) [])
+, Para
+    [ Str "Pipe"
+    , Space
+    , Str "table"
+    , Space
+    , Str "with"
+    , Space
+    , Str "tricky"
+    , Space
+    , Str "cell"
+    , Space
+    , Str "contents"
+    , Space
+    , Str "(see"
+    , Space
+    , Str "#2765):"
+    ]
+, Table
+    ( "" , [] , [] )
+    (Caption Nothing [])
+    [ ( AlignLeft , ColWidthDefault )
+    , ( AlignRight , ColWidthDefault )
+    , ( AlignRight , ColWidthDefault )
+    ]
+    (TableHead
+       ( "" , [] , [] )
+       [ Row
+           ( "" , [] , [] )
+           [ Cell ( "" , [] , [] ) AlignDefault (RowSpan 1) (ColSpan 1) []
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "IP_gene8-_1st" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "IP_gene8+_1st" ] ]
+           ]
+       ])
+    [ TableBody
+        ( "" , [] , [] )
+        (RowHeadColumns 0)
+        []
+        [ Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "IP_gene8-_1st" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "1.0000000" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "0.4357325" ] ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "IP_gene8+_1st" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "0.4357325" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "1.0000000" ] ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "foo" , Code ( "" , [] , [] ) "bar|baz" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "and|escaped" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "3.0000000" ] ]
+            ]
+        ]
+    ]
+    (TableFoot ( "" , [] , [] ) [])
+]
diff --git a/test/pod-reader.native b/test/pod-reader.native
new file mode 100644
--- /dev/null
+++ b/test/pod-reader.native
@@ -0,0 +1,393 @@
+[ Header
+    1
+    ( "" , [] , [] )
+    [ Str "POD" , Space , Str "TEST" , Space , Str "SUITE" ]
+, Para
+    [ Str "This"
+    , Space
+    , Str "is"
+    , Space
+    , Str "a"
+    , Space
+    , Str "test"
+    , Space
+    , Link
+        ( "" , [] , [] )
+        [ Str "Pod" ]
+        ( "https://perldoc.pl/perlpod" , "" )
+    , Space
+    , Str "document"
+    , Space
+    , Str "for"
+    , Space
+    , Str "pandoc."
+    ]
+, Header 2 ( "" , [] , [] ) [ Str "Head" , Space , Str "2" ]
+, Header
+    3
+    ( "" , [] , [] )
+    [ Str "Head"
+    , Space
+    , Str "3:"
+    , Space
+    , Emph [ Str "The>" , Space , Str "<Return" ]
+    ]
+, Header
+    4
+    ( "" , [] , [] )
+    [ Str "How"
+    , Space
+    , Str "to"
+    , Space
+    , Str "use"
+    , Space
+    , Str "the"
+    , Space
+    , Link
+        ( "" , [] , [ ( "manual" , "ls(1)" ) ] )
+        [ Str "ls(1)" ]
+        ( "" , "" )
+    , Space
+    , Str "command,"
+    , Space
+    , Str "an"
+    , Space
+    , Str "introduction"
+    ]
+, Header
+    5
+    ( "" , [] , [] )
+    [ Code ( "" , [] , [] ) "Ricky Jay"
+    , Space
+    , Str "and"
+    , Space
+    , Str "his"
+    , Space
+    , Str "52"
+    , Space
+    , Str "assistants"
+    ]
+, Header
+    6
+    ( "" , [] , [] )
+    [ Str "The"
+    , Space
+    , Str "=head5"
+    , Space
+    , Str "and"
+    , Space
+    , Str "=head6"
+    , Space
+    , Str "commands"
+    , Space
+    , Str "are"
+    , Space
+    , Str "newer"
+    , Space
+    , Str "and"
+    , Space
+    , Str "my"
+    , Space
+    , Str "syntax"
+    , Space
+    , Str "highlighting"
+    , Space
+    , Str "doesn't"
+    , Space
+    , Str "recognize"
+    , Space
+    , Str "them."
+    , Space
+    , Str "In"
+    , Space
+    , Str "any"
+    , Space
+    , Str "case,"
+    , Space
+    , Str "it"
+    , Space
+    , Str "should"
+    , Space
+    , Str "be"
+    , Space
+    , Str "possible"
+    , Space
+    , Str "to"
+    , Space
+    , Str "have"
+    , Space
+    , Str "a"
+    , Space
+    , Str "very"
+    , Space
+    , Str "long"
+    , Space
+    , Str "paragraph"
+    , Space
+    , Str "in"
+    , Space
+    , Str "the"
+    , Space
+    , Str "heading."
+    ]
+, Header
+    6
+    ( "" , [] , [] )
+    [ Str "It"
+    , Space
+    , Str "should"
+    , Space
+    , Str "also"
+    , Space
+    , Str "be"
+    , Space
+    , Str "possible"
+    , Space
+    , Str "to"
+    , Space
+    , Str "start"
+    , Space
+    , Str "the"
+    , Space
+    , Str "heading"
+    , Space
+    , Str "paragraph"
+    , Space
+    , Str "on"
+    , Space
+    , Str "the"
+    , Space
+    , Str "next"
+    , Space
+    , Str "line"
+    ]
+, RawBlock
+    (Format "html")
+    "<strong>This is a raw block destined for the HTML format</strong>\n\n"
+, BulletList
+    [ [ Para [ Str "Bulleted" , Space , Str "list" ] ]
+    , [ Para [ Str "Ordered" , Space , Str "list" ]
+      , OrderedList
+          ( 1 , DefaultStyle , DefaultDelim )
+          [ [ Para
+                [ Str "Here's"
+                , Space
+                , Str "a"
+                , Space
+                , Str "verbatim"
+                , Space
+                , Str "paragraph"
+                , Space
+                , Str "in"
+                , Space
+                , Str "this"
+                , Space
+                , Str "list"
+                , Space
+                , Str "item:"
+                ]
+            , CodeBlock
+                ( "" , [] , [] )
+                "    this is a code block\nthis is still part of the code block\n  so is this.\nIt seems that the prefixed spaces in verbatim blocks in pod don't get stripped.\n\n This should continue the previous code block despite the intervening blank\n line, because the first line starts with a space\n\n\n\n    the above blank lines with varying numbers of spaces should also be in\n the code block\n    pod formatters should (but not must) expand tabs by default\nso we're not special casing pandoc's behavior there in any way\n"
+            , Para
+                [ Str "Wow,"
+                , Space
+                , Str "that"
+                , Space
+                , Str "was"
+                , Space
+                , Str "fun."
+                ]
+            ]
+          , [ Para [ Str "Definition" , Space , Str "list" ]
+            , DefinitionList
+                [ ( [ Span
+                        ( "" , [] , [] )
+                        [ Str "Marvin"
+                        , Space
+                        , Str "the"
+                        , Space
+                        , Str "Martian"
+                        ]
+                    ]
+                  , [ [ Para
+                          [ Str "A"
+                          , Space
+                          , Str "cartoon"
+                          , Space
+                          , Str "alien"
+                          ]
+                      ]
+                    ]
+                  )
+                , ( [ Span
+                        ( "" , [] , [] )
+                        [ Emph
+                            [ Str "The"
+                            , Space
+                            , Str "Sun"
+                            , Space
+                            , Str "Also"
+                            , Space
+                            , Str "Rises"
+                            ]
+                        ]
+                    ]
+                  , [ [ Para
+                          [ Str "A"
+                          , Space
+                          , Str "novel"
+                          , Space
+                          , Str "by"
+                          , Space
+                          , Str "Ernest"
+                          , Space
+                          , Str "Hemingway"
+                          ]
+                      ]
+                    ]
+                  )
+                , ( [ Span
+                        ( "" , [] , [] )
+                        [ Code ( "" , [] , [] ) "undefined" ]
+                    ]
+                  , [ [] ]
+                  )
+                , ( [ Span
+                        ( "" , [] , [] )
+                        [ Str "And"
+                        , Space
+                        , Str "now,"
+                        , Space
+                        , Str "a"
+                        , Space
+                        , Str "quotation"
+                        ]
+                    ]
+                  , [ [ BlockQuote
+                          [ Para
+                              [ Str "Where's"
+                              , Space
+                              , Str "my"
+                              , Space
+                              , Str "space"
+                              , Space
+                              , Str "modulator?"
+                              ]
+                          ]
+                      ]
+                    ]
+                  )
+                ]
+            ]
+          , [ Para
+                [ Str "And"
+                , Space
+                , Str "the"
+                , Space
+                , Str "list"
+                , Space
+                , Str "continues."
+                ]
+            ]
+          ]
+      ]
+    , [ Para
+          [ Str "And"
+          , Space
+          , Str "so"
+          , Space
+          , Str "does"
+          , Space
+          , Str "the"
+          , Space
+          , Str "other"
+          , Space
+          , Str "one,"
+          , Space
+          , Str "even"
+          , Space
+          , Str "if"
+          , Space
+          , Str "I"
+          , Space
+          , Str "forget"
+          , Space
+          , Str "the"
+          , Space
+          , Str "asterisk."
+          ]
+      ]
+    ]
+, Div
+    ( "" , [ "neat" ] , [] )
+    [ Para
+        [ Str "This"
+        , Space
+        , Str "is"
+        , Space
+        , Str "a"
+        , Space
+        , Str "div"
+        , Space
+        , Str "for"
+        , Space
+        , Str "our"
+        , Space
+        , Str "purposes."
+        ]
+    , Para
+        [ Str "It"
+        , Space
+        , Str "should"
+        , Space
+        , Str "parse"
+        , Space
+        , Strong [ Str "content" ]
+        , Space
+        , Str "inside"
+        , Space
+        , Str "of"
+        , Space
+        , Str "it."
+        ]
+    , BulletList
+        [ [ Para [ Str "Like" , Space , Str "this" ] ] ]
+    ]
+, Div
+    ( "" , [ "excitement" ] , [] )
+    [ Para
+        [ Str "this"
+        , Space
+        , Str "is"
+        , Space
+        , Str "its"
+        , Space
+        , Str "own"
+        , Space
+        , Str "div"
+        ]
+    ]
+, RawBlock
+    (Format "html") " <p>and this is its own raw block</p>\n"
+, RawBlock (Format "html") "\n<p>so is this</p>\n"
+, Header
+    2
+    ( "" , [] , [] )
+    [ Code ( "" , [] , [] ) "=cut"
+    , Space
+    , Str "before"
+    , Space
+    , Str "any"
+    , Space
+    , Code ( "" , [] , [] ) "=item"
+    , Space
+    , Str "in"
+    , Space
+    , Code ( "" , [] , [] ) "=over"
+    ]
+, BulletList
+    [ [ Para [ Str "a" ] , Para [ Str "b" ] ]
+    , [ Para [ Str "c" ] ]
+    ]
+]
diff --git a/test/pod-reader.pod b/test/pod-reader.pod
new file mode 100644
--- /dev/null
+++ b/test/pod-reader.pod
@@ -0,0 +1,155 @@
+text before any Pod commands is not parsed, which is unusual for formats
+supported by pandoc, but 
+
+=head1 POD TEST SUITE
+
+This is a test L<Pod|https://perldoc.pl/perlpod> document for pandoc.
+
+=encoding utf8
+
+=head2 Head 2
+
+=head3 Head 3: I<< The> <Return >>
+
+=head4 How to use the L<ls(1)> command,
+an introduction
+
+=head5 C<Ricky Jay> and his 52 assistants
+
+=head6 The =head5 and =head6 commands are newer and my syntax highlighting
+doesn't recognize them. In any case, it should be possible to have a very long
+paragraph in the heading.
+
+=head6
+It should also be possible to start the heading paragraph on the next line
+
+=cut
+
+This doesn't get parsed at all.
+
+=begin html
+
+<strong>This is a raw block destined for the HTML format</strong>
+
+=end html
+
+=over
+
+=item *
+
+Bulleted list
+
+=item *
+
+Ordered list
+
+=over
+
+=item 1.
+
+Here's a verbatim paragraph in this list item:
+
+    this is a code block
+this is still part of the code block
+  so is this.
+It seems that the prefixed spaces in verbatim blocks in pod don't get stripped.
+
+ This should continue the previous code block despite the intervening blank
+ line, because the first line starts with a space
+    
+
+ 
+    the above blank lines with varying numbers of spaces should also be in
+ the code block
+	pod formatters should (but not must) expand tabs by default
+so we're not special casing pandoc's behavior there in any way
+
+Wow, that was fun.
+
+=item 2.
+
+Definition list
+
+=over
+
+=item Marvin the MZ<>artian
+
+A cartoon alien
+
+=item I<The Sun
+Also Rises>
+
+A novel by Ernest Hemingway
+
+=item C<undefined>
+
+=item And now, a quotation
+
+=over
+
+Where's my space modulator?
+
+=back
+
+=back
+
+=item 3.
+
+And the list continues.
+
+=back
+
+=item
+
+And so does the other one, even if I forget the asterisk.
+
+=back
+
+=begin :neat
+
+This is a div for our purposes.
+
+It should parse B<< content >> inside of it.
+
+=over
+
+=item
+
+Like this
+
+=back
+
+=end :neat
+
+=for :excitement this is its own div
+
+=for html <p>and this is its own raw block</p>
+
+=for html
+<p>so is this</p>
+
+=head2 C<=cut> before any C<=item> in C<=over>
+
+=over
+
+=cut
+
+blah
+
+=item *
+
+a
+
+=cut
+
+blah blah
+
+=pod
+
+b
+
+=item *
+
+c
+
+=back
diff --git a/test/pptx-reader/basic.native b/test/pptx-reader/basic.native
new file mode 100644
--- /dev/null
+++ b/test/pptx-reader/basic.native
@@ -0,0 +1,149 @@
+[ Header 2 ( "slide-1" , [] , [] ) [ Str "LLMs" ]
+, BulletList
+    [ [ Plain
+          [ Str
+              "Provider  \61664 Available LLMs \8211 who manages? How?"
+          ]
+      ]
+    , [ Plain
+          [ Str
+              "EW maintained list of \8220approved\8221 LLMs for Universal workers"
+          ]
+      ]
+    , [ Plain
+          [ Str
+              "Rebuilding of UWs to the \8220Newgen\8221 thing completely"
+          ]
+      ]
+    , [ Plain [ Str "Streaming support" ] ]
+    , [ Plain [ Str "Multimodal (voice streaming) models?" ] ]
+    ]
+, Header
+    2
+    ( "slide-2" , [] , [] )
+    [ Str "Everworker   venn   diagram" ]
+, Para [ Str "SKILLS" ]
+, Para [ Str "" ]
+, Para [ Str "Specialized Workers / Workflows:" ]
+, Para [ Str "" ]
+, Para [ Str "n8n, UI Path, " ]
+, Para [ Str "other RPA" ]
+, Para [ Str "BRAINS" ]
+, Para [ Str "" ]
+, Para [ Str "Universal Workers / AI Agents:" ]
+, Para [ Str "" ]
+, Para [ Str "openai , anthropic," ]
+, Para [ Str "Crew AI, other " ]
+, Para [ Str "\8220AI natives\8221" ]
+, Para [ Str "KNOWLEDGE " ]
+, Para [ Str "" ]
+, Para [ Str "Data / " ]
+, Para [ Str "RAG Pipelines" ]
+, Para [ Str "" ]
+, Para
+    [ Str "Vector DBs, specialized data prep vendors, \8230" ]
+, Para [ Str "glean" ]
+, Para [ Str "EW" ]
+, Header 2 ( "slide-3" , [] , [] ) [ Str "Table" ]
+, Table
+    ( "" , [] , [] )
+    (Caption Nothing [])
+    [ ( AlignDefault , ColWidthDefault )
+    , ( AlignDefault , ColWidthDefault )
+    , ( AlignDefault , ColWidthDefault )
+    ]
+    (TableHead
+       ( "" , [] , [] )
+       [ Row
+           ( "" , [] , [] )
+           [ Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "Col1" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "Col2" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "Col3" ] ]
+           ]
+       ])
+    [ TableBody
+        ( "" , [] , [] )
+        (RowHeadColumns 0)
+        []
+        [ Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "Name" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "Anton" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "Antich" ] ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "Age" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "23" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "years" ] ]
+            ]
+        ]
+    ]
+    (TableFoot ( "" , [] , [] ) [])
+, Para
+    [ Image
+        ( "" , [] , [] ) [] ( "ppt/media/image1.png" , "Picture 6" )
+    ]
+, Header 2 ( "slide-4" , [] , [] ) [ Str "Smart Art" ]
+, Div
+    ( ""
+    , [ "smartart" , "chevron2" ]
+    , [ ( "layout" , "chevron2" ) ]
+    )
+    [ Para [ Strong [ Str "First" ] ]
+    , BulletList
+        [ [ Plain [ Str "another" ] ]
+        , [ Plain [ Str "subtitle" ] ]
+        ]
+    , Para [ Strong [ Str "Second" ] ]
+    , BulletList
+        [ [ Plain [ Str "and yet again" ] ]
+        , [ Plain [ Str "yet more" ] ]
+        ]
+    ]
+]
diff --git a/test/pptx-reader/basic.pptx b/test/pptx-reader/basic.pptx
new file mode 100644
Binary files /dev/null and b/test/pptx-reader/basic.pptx differ
diff --git a/test/pptx/background-image/input.native b/test/pptx/background-image/input.native
new file mode 100644
--- /dev/null
+++ b/test/pptx/background-image/input.native
@@ -0,0 +1,17 @@
+[Header 1 ("section-header-with-background-image",[],[("background-image","movie.jpg")]) [Str "Section",Space,Str "Header",Space,Str "(with",Space,Str "background",Space,Str "image)"]
+,Header 2 ("slide-1",[],[("background-image","lalune.jpg")]) [Str "Slide",Space,Str "1"]
+,Para [Str "This",Space,Str "slide",Space,Str "has",Space,Str "a",Space,Str "moon",Space,Str "background."]
+,Header 2 ("slide-2",[],[("background-image","movie.jpg")]) [Str "Slide",Space,Str "2"]
+,Para [Str "This",Space,Str "slide",Space,Str "has",Space,Str "a",Space,Str "movie",Space,Str "background."]
+,Header 2 ("slide-3",[],[("background-image","movie.jpg")]) [Str "Slide",Space,Str "3"]
+,Div ("",["columns"],[])
+ [Div ("",["column"],[])
+  [Para [Str "Background",Space,Str "images",Space,Str "work",Space,Str "in",Space,Str "two-column",Space,Str "layout."]]
+ ,Div ("",["column"],[])
+  [Para [Str "hello"]]]
+,Header 2 ("slide-4",[],[("background-image","movie.jpg")]) [Str "Slide",Space,Str "4"]
+,Para [Str "You",Space,Str "can",Space,Str "have",Space,Str "images",Space,Str "on",Space,Str "slides",Space,Str "that",Space,Str "have",Space,Str "background",Space,Str "images:"]
+,Para [Image ("",[],[]) [Str "An",Space,Str "image"] ("lalune.jpg","fig:")]
+,Header 2 ("section",[],[("background-image","lalune.jpg")]) []
+,Div ("",["notes"],[])
+ [Para [Str "Blank",Space,Str "slides",Space,Str "can",Space,Str "have",Space,Str "background",Space,Str "images."]]]
diff --git a/test/pptx/background-image/output.pptx b/test/pptx/background-image/output.pptx
new file mode 100644
Binary files /dev/null and b/test/pptx/background-image/output.pptx differ
diff --git a/test/pptx/background-image/templated.pptx b/test/pptx/background-image/templated.pptx
new file mode 100644
Binary files /dev/null and b/test/pptx/background-image/templated.pptx differ
diff --git a/test/pptx/blanks/just-speaker-notes/input.native b/test/pptx/blanks/just-speaker-notes/input.native
new file mode 100644
--- /dev/null
+++ b/test/pptx/blanks/just-speaker-notes/input.native
@@ -0,0 +1,7 @@
+[Header 1 ("first-slide",[],[]) [Str "First",Space,Str "slide"]
+,Para [Str "Nothing",Space,Str "to",Space,Str "see",Space,Str "here"]
+,Header 1 ("section",[],[]) []
+,Div ("",["notes"],[])
+ [Para [Str "Some",Space,Str "notes",Space,Str "here:",Space,Str "this",Space,Str "first",Space,Str "slide",Space,Str "should",Space,Str "use",Space,Str "the",Space,Str "Blank",Space,Str "template"]]
+,Header 1 ("third-slide",[],[]) [Str "Third",Space,Str "slide"]
+,Para [Str "The",Space,Str "second",Space,Str "slide",Space,Str "should",Space,Str "be",Space,Str "blank"]]
diff --git a/test/pptx/blanks/just-speaker-notes/output.pptx b/test/pptx/blanks/just-speaker-notes/output.pptx
new file mode 100644
Binary files /dev/null and b/test/pptx/blanks/just-speaker-notes/output.pptx differ
diff --git a/test/pptx/blanks/just-speaker-notes/templated.pptx b/test/pptx/blanks/just-speaker-notes/templated.pptx
new file mode 100644
Binary files /dev/null and b/test/pptx/blanks/just-speaker-notes/templated.pptx differ
diff --git a/test/pptx/blanks/nbsp-in-body/input.native b/test/pptx/blanks/nbsp-in-body/input.native
new file mode 100644
--- /dev/null
+++ b/test/pptx/blanks/nbsp-in-body/input.native
@@ -0,0 +1,6 @@
+[Header 1 ("first-slide",[],[]) [Str "First",Space,Str "slide"]
+,Para [Str "Uninteresting,",Space,Str "normal"]
+,Header 1 ("section",[],[]) []
+,Para [Str "\160"]
+,Header 1 ("third-slide",[],[]) [Str "Third",Space,Str "slide"]
+,Para [Str "Was",Space,Str "the",Space,Str "previous",Space,Str "one",Space,Str "blank?"]]
diff --git a/test/pptx/blanks/nbsp-in-body/output.pptx b/test/pptx/blanks/nbsp-in-body/output.pptx
new file mode 100644
Binary files /dev/null and b/test/pptx/blanks/nbsp-in-body/output.pptx differ
diff --git a/test/pptx/blanks/nbsp-in-body/templated.pptx b/test/pptx/blanks/nbsp-in-body/templated.pptx
new file mode 100644
Binary files /dev/null and b/test/pptx/blanks/nbsp-in-body/templated.pptx differ
diff --git a/test/pptx/blanks/nbsp-in-heading/input.native b/test/pptx/blanks/nbsp-in-heading/input.native
new file mode 100644
--- /dev/null
+++ b/test/pptx/blanks/nbsp-in-heading/input.native
@@ -0,0 +1,5 @@
+[Header 1 ("first-slide",[],[]) [Str "First",Space,Str "slide"]
+,Para [Str "Uninteresting,",Space,Str "normal"]
+,Header 1 ("section",[],[]) [Str "\160"]
+,Header 1 ("third-slide",[],[]) [Str "Third",Space,Str "slide"]
+,Para [Str "Was",Space,Str "the",Space,Str "previous",Space,Str "one",Space,Str "blank?"]]
diff --git a/test/pptx/blanks/nbsp-in-heading/output.pptx b/test/pptx/blanks/nbsp-in-heading/output.pptx
new file mode 100644
Binary files /dev/null and b/test/pptx/blanks/nbsp-in-heading/output.pptx differ
diff --git a/test/pptx/blanks/nbsp-in-heading/templated.pptx b/test/pptx/blanks/nbsp-in-heading/templated.pptx
new file mode 100644
Binary files /dev/null and b/test/pptx/blanks/nbsp-in-heading/templated.pptx differ
diff --git a/test/pptx/code-custom/output.pptx b/test/pptx/code-custom/output.pptx
new file mode 100644
Binary files /dev/null and b/test/pptx/code-custom/output.pptx differ
diff --git a/test/pptx/code-custom/templated.pptx b/test/pptx/code-custom/templated.pptx
new file mode 100644
Binary files /dev/null and b/test/pptx/code-custom/templated.pptx differ
diff --git a/test/pptx/code/input.native b/test/pptx/code/input.native
new file mode 100644
--- /dev/null
+++ b/test/pptx/code/input.native
@@ -0,0 +1,21 @@
+[Header 1 ("header-with-inline-code",[],[]) [Str "Header",Space,Str "with",Space,Code ("",[],[]) "inline code"]
+,CodeBlock ("",[],[]) "Code at level 0"
+,BulletList
+ [[Para [Str "Bullet",Space,Str "item",Space,Str "with",Space,Code ("",[],[]) "inline code"]
+  ,CodeBlock ("",[],[]) "Code block at level 1"
+  ,BulletList
+   [[Para [Str "with",Space,Code ("",[],[]) "nested"]
+    ,CodeBlock ("",[],[]) "lvl2\nlvl2\nlvl2"
+    ,Header 2 ("second-heading-level-with-code",[],[]) [Str "Second",Space,Str "heading",Space,Str "level",Space,Str "with",Space,Code ("",[],[]) "code"]]]]]
+,Header 1 ("syntax-highlighting",[],[]) [Str "Syntax",Space,Str "highlighting"]
+,CodeBlock ("",["haskell"],[]) "id :: a -> a\nid x = x"
+,BulletList
+ [[Para [Str "Nested"]
+  ,CodeBlock ("",["haskell"],[]) "g :: Int -> Int\ng x = x * 3"]]
+,Header 1 ("two-column-slide",[],[]) [Str "Two",Space,Str "column",Space,Str "slide"]
+,Div ("",["columns"],[])
+ [Div ("",["column"],[("width","50%")])
+  [BulletList
+   [[Plain [Str "A",Space,Str "total",Space,Str "alternative",Space,Str "for",Space,Code ("",[],[]) "head"]]]]
+ ,Div ("",["column"],[("width","50%")])
+  [CodeBlock ("",[],[]) "safeHead :: [a] -> Maybe a\nsafeHead [] = Nothing\nsafeHead (x:_) = Just x"]]]
diff --git a/test/pptx/code/output.pptx b/test/pptx/code/output.pptx
new file mode 100644
Binary files /dev/null and b/test/pptx/code/output.pptx differ
diff --git a/test/pptx/code/templated.pptx b/test/pptx/code/templated.pptx
new file mode 100644
Binary files /dev/null and b/test/pptx/code/templated.pptx differ
diff --git a/test/pptx/comparison/both-columns/input.native b/test/pptx/comparison/both-columns/input.native
new file mode 100644
--- /dev/null
+++ b/test/pptx/comparison/both-columns/input.native
@@ -0,0 +1,23 @@
+[Header 1 ("a-slide",[],[]) [Str "A",Space,Str "slide"]
+,Div ("",["columns"],[])
+ [Div ("",["column"],[])
+  [Para [Str "A",Space,Str "paragraph",Space,Str "here"]
+  ,Table ("",[],[]) (Caption Nothing
+   [])
+   [(AlignDefault,ColWidth 0.125)
+   ,(AlignDefault,ColWidth 0.125)]
+   (TableHead ("",[],[])
+   [])
+   [(TableBody ("",[],[]) (RowHeadColumns 0)
+    []
+    [Row ("",[],[])
+     [Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+      [Plain [Str "plus"]]
+     ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+      [Plain [Str "a",Space,Str "table"]]]])]
+   (TableFoot ("",[],[])
+   [])
+  ,Para [Str "Then",Space,Str "some",Space,Str "more",Space,Str "text"]]
+ ,Div ("",["column"],[])
+  [Para [Str "A",Space,Str "paragraph",Space,Str "here"]
+  ,Para [Image ("",[],[]) [Str "Plus",Space,Str "an",Space,Str "image"] ("lalune.jpg","fig:")]]]]
diff --git a/test/pptx/comparison/both-columns/output.pptx b/test/pptx/comparison/both-columns/output.pptx
new file mode 100644
Binary files /dev/null and b/test/pptx/comparison/both-columns/output.pptx differ
diff --git a/test/pptx/comparison/both-columns/templated.pptx b/test/pptx/comparison/both-columns/templated.pptx
new file mode 100644
Binary files /dev/null and b/test/pptx/comparison/both-columns/templated.pptx differ
diff --git a/test/pptx/comparison/extra-image/input.native b/test/pptx/comparison/extra-image/input.native
new file mode 100644
--- /dev/null
+++ b/test/pptx/comparison/extra-image/input.native
@@ -0,0 +1,24 @@
+[Header 1 ("a-slide",[],[]) [Str "A",Space,Str "slide"]
+,Div ("",["columns"],[])
+ [Div ("",["column"],[])
+  [Para [Str "A",Space,Str "paragraph",Space,Str "here"]
+  ,Table ("",[],[]) (Caption Nothing
+   [])
+   [(AlignDefault,ColWidth 0.125)
+   ,(AlignDefault,ColWidth 0.125)]
+   (TableHead ("",[],[])
+   [])
+   [(TableBody ("",[],[]) (RowHeadColumns 0)
+    []
+    [Row ("",[],[])
+     [Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+      [Plain [Str "plus"]]
+     ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+      [Plain [Str "a",Space,Str "table"]]]])]
+   (TableFoot ("",[],[])
+   [])
+  ,Para [Str "Then",Space,Str "some",Space,Str "more",Space,Str "text"]]
+ ,Div ("",["column"],[])
+  [Para [Str "A",Space,Str "paragraph",Space,Str "here"]
+  ,Para [Image ("",[],[]) [Str "Plus",Space,Str "an",Space,Str "image"] ("lalune.jpg","fig:")]
+  ,Para [Image ("",[],[]) [Str "And",Space,Str "another",Space,Str "image"] ("lalune.jpg","fig:")]]]]
diff --git a/test/pptx/comparison/extra-image/output.pptx b/test/pptx/comparison/extra-image/output.pptx
new file mode 100644
Binary files /dev/null and b/test/pptx/comparison/extra-image/output.pptx differ
diff --git a/test/pptx/comparison/extra-image/templated.pptx b/test/pptx/comparison/extra-image/templated.pptx
new file mode 100644
Binary files /dev/null and b/test/pptx/comparison/extra-image/templated.pptx differ
diff --git a/test/pptx/comparison/extra-text/input.native b/test/pptx/comparison/extra-text/input.native
new file mode 100644
--- /dev/null
+++ b/test/pptx/comparison/extra-text/input.native
@@ -0,0 +1,23 @@
+[Header 1 ("a-slide",[],[]) [Str "A",Space,Str "slide"]
+,Div ("",["columns"],[])
+ [Div ("",["column"],[])
+  [Para [Str "A",Space,Str "paragraph",Space,Str "here"]
+  ,Table ("",[],[]) (Caption Nothing
+   [])
+   [(AlignDefault,ColWidth 0.125)
+   ,(AlignDefault,ColWidth 0.125)]
+   (TableHead ("",[],[])
+   [])
+   [(TableBody ("",[],[]) (RowHeadColumns 0)
+    []
+    [Row ("",[],[])
+     [Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+      [Plain [Str "plus"]]
+     ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+      [Plain [Str "a",Space,Str "table"]]]])]
+   (TableFoot ("",[],[])
+   [])
+  ,Para [Str "Then",Space,Str "some",Space,Str "more",Space,Str "text"]]
+ ,Div ("",["column"],[])
+  [Para [Str "A",Space,Str "paragraph",Space,Str "here"]
+  ,Para [Image ("",[],[]) [Str "Plus",Space,Str "an",Space,Str "image"] ("lalune.jpg","fig:")]]]]
diff --git a/test/pptx/comparison/extra-text/output.pptx b/test/pptx/comparison/extra-text/output.pptx
new file mode 100644
Binary files /dev/null and b/test/pptx/comparison/extra-text/output.pptx differ
diff --git a/test/pptx/comparison/extra-text/templated.pptx b/test/pptx/comparison/extra-text/templated.pptx
new file mode 100644
Binary files /dev/null and b/test/pptx/comparison/extra-text/templated.pptx differ
diff --git a/test/pptx/comparison/non-text-first/input.native b/test/pptx/comparison/non-text-first/input.native
new file mode 100644
--- /dev/null
+++ b/test/pptx/comparison/non-text-first/input.native
@@ -0,0 +1,21 @@
+[Header 1 ("a-slide",[],[]) [Str "A",Space,Str "slide"]
+,Div ("",["columns"],[])
+ [Div ("",["column"],[])
+  [Table ("",[],[]) (Caption Nothing
+   [])
+   [(AlignDefault,ColWidth 0.125)
+   ,(AlignDefault,ColWidth 0.125)]
+   (TableHead ("",[],[])
+   [])
+   [(TableBody ("",[],[]) (RowHeadColumns 0)
+    []
+    [Row ("",[],[])
+     [Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+      [Plain [Str "a"]]
+     ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+      [Plain [Str "table"]]]])]
+   (TableFoot ("",[],[])
+   [])
+  ,Para [Str "Plus",Space,Str "a",Space,Str "paragraph",Space,Str "here"]]
+ ,Div ("",["column"],[])
+  [Para [Image ("",[],[]) [Str "Just",Space,Str "an",Space,Str "image",Space,Str "on",Space,Str "this",Space,Str "side"] ("lalune.jpg","fig:")]]]]
diff --git a/test/pptx/comparison/non-text-first/output.pptx b/test/pptx/comparison/non-text-first/output.pptx
new file mode 100644
Binary files /dev/null and b/test/pptx/comparison/non-text-first/output.pptx differ
diff --git a/test/pptx/comparison/non-text-first/templated.pptx b/test/pptx/comparison/non-text-first/templated.pptx
new file mode 100644
Binary files /dev/null and b/test/pptx/comparison/non-text-first/templated.pptx differ
diff --git a/test/pptx/comparison/one-column/input.native b/test/pptx/comparison/one-column/input.native
new file mode 100644
--- /dev/null
+++ b/test/pptx/comparison/one-column/input.native
@@ -0,0 +1,21 @@
+[Header 1 ("a-slide",[],[]) [Str "A",Space,Str "slide"]
+,Div ("",["columns"],[])
+ [Div ("",["column"],[])
+  [Para [Str "A",Space,Str "paragraph",Space,Str "here"]
+  ,Table ("",[],[]) (Caption Nothing
+   [])
+   [(AlignDefault,ColWidth 0.125)
+   ,(AlignDefault,ColWidth 0.125)]
+   (TableHead ("",[],[])
+   [])
+   [(TableBody ("",[],[]) (RowHeadColumns 0)
+    []
+    [Row ("",[],[])
+     [Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+      [Plain [Str "plus"]]
+     ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+      [Plain [Str "a",Space,Str "table"]]]])]
+   (TableFoot ("",[],[])
+   [])]
+ ,Div ("",["column"],[])
+  [Para [Str "Only",Space,Str "a",Space,Str "paragraph",Space,Str "here"]]]]
diff --git a/test/pptx/comparison/one-column/output.pptx b/test/pptx/comparison/one-column/output.pptx
new file mode 100644
Binary files /dev/null and b/test/pptx/comparison/one-column/output.pptx differ
diff --git a/test/pptx/comparison/one-column/templated.pptx b/test/pptx/comparison/one-column/templated.pptx
new file mode 100644
Binary files /dev/null and b/test/pptx/comparison/one-column/templated.pptx differ
diff --git a/test/pptx/content-with-caption/heading-text-image/input.native b/test/pptx/content-with-caption/heading-text-image/input.native
new file mode 100644
--- /dev/null
+++ b/test/pptx/content-with-caption/heading-text-image/input.native
@@ -0,0 +1,3 @@
+[Header 1 ("a-slide",[],[]) [Str "A",Space,Str "slide"]
+,Para [Str "Some",Space,Str "text",Space,Str "here"]
+,Para [Image ("",[],[]) [Str "Followed",Space,Str "by",Space,Str "a",Space,Str "picture"] ("lalune.jpg","fig:")]]
diff --git a/test/pptx/content-with-caption/heading-text-image/output.pptx b/test/pptx/content-with-caption/heading-text-image/output.pptx
new file mode 100644
Binary files /dev/null and b/test/pptx/content-with-caption/heading-text-image/output.pptx differ
diff --git a/test/pptx/content-with-caption/heading-text-image/templated.pptx b/test/pptx/content-with-caption/heading-text-image/templated.pptx
new file mode 100644
Binary files /dev/null and b/test/pptx/content-with-caption/heading-text-image/templated.pptx differ
diff --git a/test/pptx/content-with-caption/image-text/input.native b/test/pptx/content-with-caption/image-text/input.native
new file mode 100644
--- /dev/null
+++ b/test/pptx/content-with-caption/image-text/input.native
@@ -0,0 +1,2 @@
+[Para [Image ("",[],[]) [Str "The",Space,Str "picture",Space,Str "first"] ("lalune.jpg","fig:")]
+,Para [Str "Then",Space,Str "some",Space,Str "text",Space,Str "here"]]
diff --git a/test/pptx/content-with-caption/image-text/output.pptx b/test/pptx/content-with-caption/image-text/output.pptx
new file mode 100644
Binary files /dev/null and b/test/pptx/content-with-caption/image-text/output.pptx differ
diff --git a/test/pptx/content-with-caption/image-text/templated.pptx b/test/pptx/content-with-caption/image-text/templated.pptx
new file mode 100644
Binary files /dev/null and b/test/pptx/content-with-caption/image-text/templated.pptx differ
diff --git a/test/pptx/content-with-caption/text-image/input.native b/test/pptx/content-with-caption/text-image/input.native
new file mode 100644
--- /dev/null
+++ b/test/pptx/content-with-caption/text-image/input.native
@@ -0,0 +1,2 @@
+[Para [Str "Some",Space,Str "text",Space,Str "here"]
+,Para [Image ("",[],[]) [Str "Followed",Space,Str "by",Space,Str "a",Space,Str "picture"] ("lalune.jpg","fig:")]]
diff --git a/test/pptx/content-with-caption/text-image/output.pptx b/test/pptx/content-with-caption/text-image/output.pptx
new file mode 100644
Binary files /dev/null and b/test/pptx/content-with-caption/text-image/output.pptx differ
diff --git a/test/pptx/content-with-caption/text-image/templated.pptx b/test/pptx/content-with-caption/text-image/templated.pptx
new file mode 100644
Binary files /dev/null and b/test/pptx/content-with-caption/text-image/templated.pptx differ
diff --git a/test/pptx/document-properties-short-desc/input.native b/test/pptx/document-properties-short-desc/input.native
new file mode 100644
--- /dev/null
+++ b/test/pptx/document-properties-short-desc/input.native
@@ -0,0 +1,2 @@
+Pandoc (Meta {unMeta = fromList [("author",MetaList [MetaInlines [Str "A.",Space,Str "M."]]),("description",MetaInlines [Str "Short",Space,RawInline (Format "html") "<i>",Str "description",RawInline (Format "html") "</i>",Space,Str "&."]),("keywords",MetaList [MetaInlines [Str "keyword",Space,Str "1"],MetaInlines [Str "keyword",Space,Str "2"]]),("subject",MetaInlines [Str "This",Space,Str "is",Space,Str "the",Space,Str "subject"]),("title",MetaInlines [Str "Testing",Space,Str "custom",Space,Str "properties"])]})
+[Para [Str "Testing",Space,Str "document",Space,Str "properties"]]
diff --git a/test/pptx/document-properties-short-desc/output.pptx b/test/pptx/document-properties-short-desc/output.pptx
new file mode 100644
Binary files /dev/null and b/test/pptx/document-properties-short-desc/output.pptx differ
diff --git a/test/pptx/document-properties-short-desc/templated.pptx b/test/pptx/document-properties-short-desc/templated.pptx
new file mode 100644
Binary files /dev/null and b/test/pptx/document-properties-short-desc/templated.pptx differ
diff --git a/test/pptx/document-properties/input.native b/test/pptx/document-properties/input.native
new file mode 100644
--- /dev/null
+++ b/test/pptx/document-properties/input.native
@@ -0,0 +1,2 @@
+Pandoc (Meta {unMeta = fromList [("Company",MetaInlines [Str "My",Space,Str "Company"]),("Second Custom Property",MetaInlines [Str "Second",Space,Str "custom",Space,Str "property",Space,Str "value"]),("abstract",MetaBlocks [Plain [Str "Quite",Space,Str "a",Space,Str "long",Space,Str "description",SoftBreak,Str "spanning",Space,Str "several",Space,Str "lines"]]),("author",MetaList [MetaInlines [Str "A.",Space,Str "M."]]),("category",MetaInlines [Str "My",Space,Str "Category"]),("custom1",MetaInlines [Str "First",Space,Str "custom",Space,Str "property",Space,Str "value"]),("custom3",MetaInlines [Str "Escaping",Space,Str "amp",Space,Str "&",Space,Str "."]),("custom4",MetaInlines [Str "Escaping",Space,Str "LT,GT",Space,Str "<",Space,Str "asdf",Space,Str ">",Space,Str "<"]),("custom5",MetaInlines [Str "Escaping",Space,Str "html",Space,RawInline (Format "html") "<i>",Str "asdf",RawInline (Format "html") "</i>"]),("custom6",MetaInlines [Str "Escaping",Space,Emph [Str "MD"],Space,Str "\225",Space,Str "a"]),("custom9",MetaInlines [Str "Extended",Space,Str "chars:",Space,Str "\8364",Space,Str "\225",Space,Str "\233",Space,Str "\237",Space,Str "\243",Space,Str "\250",Space,Str "$"]),("description",MetaBlocks [Para [Str "Long",Space,Str "description",Space,Str "spanning",SoftBreak,Str "several",Space,Str "lines."],Plain [Str "This",Space,Str "is",Space,Str "\225",Space,Str "second",Space,RawInline (Format "html") "<i>",Str "line",RawInline (Format "html") "</i>",Str "."]]),("keywords",MetaList [MetaInlines [Str "keyword",Space,Str "1"],MetaInlines [Str "keyword",Space,Str "2"]]),("lang",MetaInlines [Str "en-US"]),("nested-custom",MetaList [MetaMap (fromList [("custom 7",MetaInlines [Str "Nested",Space,Str "Custom",Space,Str "value",Space,Str "7"])]),MetaMap (fromList [("custom 8",MetaInlines [Str "Nested",Space,Str "Custom",Space,Str "value",Space,Str "8"])])]),("subject",MetaInlines [Str "This",Space,Str "is",Space,Str "the",Space,Str "subject"]),("subtitle",MetaInlines [Str "This",Space,Str "is",Space,Str "a",Space,Str "subtitle"]),("title",MetaInlines [Str "Testing",Space,Str "custom",Space,Str "properties"])]})
+[Para [Str "Testing",Space,Str "document",Space,Str "properties"]]
diff --git a/test/pptx/document-properties/output.pptx b/test/pptx/document-properties/output.pptx
new file mode 100644
Binary files /dev/null and b/test/pptx/document-properties/output.pptx differ
diff --git a/test/pptx/document-properties/templated.pptx b/test/pptx/document-properties/templated.pptx
new file mode 100644
Binary files /dev/null and b/test/pptx/document-properties/templated.pptx differ
diff --git a/test/pptx/endnotes-toc/output.pptx b/test/pptx/endnotes-toc/output.pptx
new file mode 100644
Binary files /dev/null and b/test/pptx/endnotes-toc/output.pptx differ
diff --git a/test/pptx/endnotes-toc/templated.pptx b/test/pptx/endnotes-toc/templated.pptx
new file mode 100644
Binary files /dev/null and b/test/pptx/endnotes-toc/templated.pptx differ
diff --git a/test/pptx/endnotes/input.native b/test/pptx/endnotes/input.native
new file mode 100644
--- /dev/null
+++ b/test/pptx/endnotes/input.native
@@ -0,0 +1,2 @@
+Pandoc (Meta {unMeta = fromList []})
+[Para [Str "Here",Space,Str "is",Space,Str "one",Space,Str "note.",Note [Para [Str "Here",Space,Str "is",Space,Str "the",Space,Str "note."]],Space,Str "And",Space,Str "one",Space,Str "more",Space,Str "note.",Note [Para [Str "And",Space,Str "another",Space,Str "note."]]]]
diff --git a/test/pptx/endnotes/output.pptx b/test/pptx/endnotes/output.pptx
new file mode 100644
Binary files /dev/null and b/test/pptx/endnotes/output.pptx differ
diff --git a/test/pptx/endnotes/templated.pptx b/test/pptx/endnotes/templated.pptx
new file mode 100644
Binary files /dev/null and b/test/pptx/endnotes/templated.pptx differ
diff --git a/test/pptx/footer/basic/output.pptx b/test/pptx/footer/basic/output.pptx
new file mode 100644
Binary files /dev/null and b/test/pptx/footer/basic/output.pptx differ
diff --git a/test/pptx/footer/basic/reference.pptx b/test/pptx/footer/basic/reference.pptx
new file mode 100644
Binary files /dev/null and b/test/pptx/footer/basic/reference.pptx differ
diff --git a/test/pptx/footer/fixed-date/output.pptx b/test/pptx/footer/fixed-date/output.pptx
new file mode 100644
Binary files /dev/null and b/test/pptx/footer/fixed-date/output.pptx differ
diff --git a/test/pptx/footer/fixed-date/reference.pptx b/test/pptx/footer/fixed-date/reference.pptx
new file mode 100644
Binary files /dev/null and b/test/pptx/footer/fixed-date/reference.pptx differ
diff --git a/test/pptx/footer/higher-slide-number/output.pptx b/test/pptx/footer/higher-slide-number/output.pptx
new file mode 100644
Binary files /dev/null and b/test/pptx/footer/higher-slide-number/output.pptx differ
diff --git a/test/pptx/footer/higher-slide-number/reference.pptx b/test/pptx/footer/higher-slide-number/reference.pptx
new file mode 100644
Binary files /dev/null and b/test/pptx/footer/higher-slide-number/reference.pptx differ
diff --git a/test/pptx/footer/input.native b/test/pptx/footer/input.native
new file mode 100644
--- /dev/null
+++ b/test/pptx/footer/input.native
@@ -0,0 +1,66 @@
+Pandoc (Meta {unMeta = fromList [("author",MetaInlines [Str "Me"]),("date",MetaInlines [Str "14/09/1995"]),("title",MetaInlines [Str "Slides"])]})
+[Header 2 ("slide-1",[],[]) [Str "Slide",Space,Str "1"]
+,Para [Str "Hello",Space,Str "there"]
+,Header 1 ("layouts",[],[]) [Str "Layouts"]
+,Header 2 ("slide-3",[],[]) [Str "Slide",Space,Str "3"]
+,Para [Str "Does",Space,Str "it",Space,Str "work",Space,Str "on",Space,Str "other",Space,Str "layouts?"]
+,Table ("",[],[]) (Caption Nothing
+ [])
+ [(AlignDefault,ColWidth 5.555555555555555e-2)
+ ,(AlignDefault,ColWidth 5.555555555555555e-2)]
+ (TableHead ("",[],[])
+ [])
+ [(TableBody ("",[],[]) (RowHeadColumns 0)
+  []
+  [Row ("",[],[])
+   [Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "1"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "2"]]]])]
+ (TableFoot ("",[],[])
+ [])
+,Header 2 ("slide-4",[],[]) [Str "Slide",Space,Str "4"]
+,Div ("",["columns"],[])
+ [Div ("",["column"],[])
+  [Para [Str "hello",Space,Str "hello"]]
+ ,Div ("",["column"],[])
+  [Para [Str "goood",Space,Str "bye"]]]
+,Header 2 ("slide-5",[],[]) [Str "Slide",Space,Str "5"]
+,Div ("",["columns"],[])
+ [Div ("",["column"],[])
+  [Para [Str "Hello",Space,Str "there"]
+  ,Table ("",[],[]) (Caption Nothing
+   [])
+   [(AlignDefault,ColWidth 5.555555555555555e-2)
+   ,(AlignDefault,ColWidth 5.555555555555555e-2)]
+   (TableHead ("",[],[])
+   [])
+   [(TableBody ("",[],[]) (RowHeadColumns 0)
+    []
+    [Row ("",[],[])
+     [Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+      [Plain [Str "1"]]
+     ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+      [Plain [Str "2"]]]])]
+   (TableFoot ("",[],[])
+   [])]
+ ,Div ("",["column"],[])
+  [Para [Str "oh",Space,Str "wait"]
+  ,Table ("",[],[]) (Caption Nothing
+   [])
+   [(AlignDefault,ColWidth 5.555555555555555e-2)
+   ,(AlignDefault,ColWidth 5.555555555555555e-2)]
+   (TableHead ("",[],[])
+   [])
+   [(TableBody ("",[],[]) (RowHeadColumns 0)
+    []
+    [Row ("",[],[])
+     [Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+      [Plain [Str "1"]]
+     ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+      [Plain [Str "2"]]]])]
+   (TableFoot ("",[],[])
+   [])]]
+,Header 2 ("section",[],[]) []
+,Div ("",["notes"],[])
+ [Para [Str "This",Space,Str "is",Space,Str "a",Space,Str "blank",Space,Str "slide:",Space,Str "does",Space,Str "it",Space,Str "have",Space,Str "a",Space,Str "footer?"]]]
diff --git a/test/pptx/footer/no-title-slide/output.pptx b/test/pptx/footer/no-title-slide/output.pptx
new file mode 100644
Binary files /dev/null and b/test/pptx/footer/no-title-slide/output.pptx differ
diff --git a/test/pptx/footer/no-title-slide/reference.pptx b/test/pptx/footer/no-title-slide/reference.pptx
new file mode 100644
Binary files /dev/null and b/test/pptx/footer/no-title-slide/reference.pptx differ
diff --git a/test/pptx/images/input.native b/test/pptx/images/input.native
new file mode 100644
--- /dev/null
+++ b/test/pptx/images/input.native
@@ -0,0 +1,5 @@
+Pandoc (Meta {unMeta = fromList []})
+[Para [Image ("",[],[]) [] ("lalune.jpg","")]
+,Para [Image ("",[],[]) [Str "The",Space,Str "Moon"] ("lalune.jpg","fig:")]
+,Header 1 ("one-more",[],[]) [Str "One",Space,Str "More"]
+,Para [Image ("",[],[]) [Str "The",Space,Str "Moon"] ("lalune.jpg","fig:")]]
diff --git a/test/pptx/images/output.pptx b/test/pptx/images/output.pptx
new file mode 100644
Binary files /dev/null and b/test/pptx/images/output.pptx differ
diff --git a/test/pptx/images/templated.pptx b/test/pptx/images/templated.pptx
new file mode 100644
Binary files /dev/null and b/test/pptx/images/templated.pptx differ
diff --git a/test/pptx/incremental-lists/with-flag/input.native b/test/pptx/incremental-lists/with-flag/input.native
new file mode 100644
--- /dev/null
+++ b/test/pptx/incremental-lists/with-flag/input.native
@@ -0,0 +1,139 @@
+[Header 1 ("slide-1-content",[],[]) [Str "Slide",Space,Str "1",Space,Str "(Content)"]
+,BulletList
+ [[Plain [Str "These"]]
+ ,[Plain [Str "bullets"]]
+ ,[Plain [Str "should"]]
+ ,[Plain [Str "be"]]
+ ,[Plain [Str "incremental"]]]
+,Header 1 ("slide-2-content",[],[]) [Str "Slide",Space,Str "2",Space,Str "(Content)"]
+,BulletList
+ [[Para [Str "as"]]
+ ,[Para [Str "should"]]
+ ,[Para [Str "these"]]]
+,Header 1 ("slide-3-content",[],[]) [Str "Slide",Space,Str "3",Space,Str "(Content)"]
+,Para [Str "Even",Space,Str "with",Space,Str "some",Space,Str "text",Space,Str "first,",Space,Str "these",Space,Str "should:"]
+,BulletList
+ [[Plain [Str "also"]]
+ ,[Plain [Str "be"]]
+ ,[Plain [Str "incremental"]]]
+,Header 1 ("slide-4-content",[],[]) [Str "Slide",Space,Str "4",Space,Str "(Content)"]
+,OrderedList (1,Decimal,Period)
+ [[Plain [Str "These"]]
+ ,[Plain [Str "are"]]
+ ,[Plain [Str "incremental"]]]
+,Para [Str "But",Space,Str "this",Space,Str "text",Space,Str "isn\8217t"]
+,BulletList
+ [[Plain [Str "But"]]
+ ,[Plain [Str "these"]]
+ ,[Plain [Str "are"]]]
+,Header 1 ("slide-5-two-content",[],[]) [Str "Slide",Space,Str "5",Space,Str "(Two",Space,Str "Content)"]
+,Div ("",["columns"],[])
+ [Div ("",["column"],[])
+  [Para [Str "Incremental",Space,Str "on",Space,Str "the",Space,Str "left:"]
+  ,BulletList
+   [[Plain [Str "one"]]
+   ,[Plain [Str "by"]]
+   ,[Plain [Str "one"]]]
+  ,Para [Str "With",Space,Str "something",Space,Str "below"]]
+ ,Div ("",["column"],[])
+  [Para [Str "Incremental",Space,Str "on",Space,Str "the",Space,Str "right:"]
+  ,BulletList
+   [[Plain [Str "one"]]
+   ,[Plain [Str "by"]]
+   ,[Plain [Str "one"]]]
+  ,Para [Str "With",Space,Str "something",Space,Str "else",Space,Str "below"]]]
+,Header 1 ("slide-6-two-content-right",[],[]) [Str "Slide",Space,Str "6",Space,Str "(Two",Space,Str "Content",Space,Str "Right)"]
+,Div ("",["columns"],[])
+ [Div ("",["column"],[])
+  [Para [Image ("",[],[]) [Str "an",Space,Str "image"] ("lalune.jpg","fig:")]]
+ ,Div ("",["column"],[])
+  [BulletList
+   [[Plain [Str "An"]]
+   ,[Plain [Str "Incremental"]]
+   ,[Plain [Str "List"]]]]]
+,Header 1 ("slide-7-content-with-caption",[],[]) [Str "Slide",Space,Str "7",Space,Str "(Content",Space,Str "with",Space,Str "Caption)"]
+,Para [Str "First,",Space,Str "we",Space,Str "have",Space,Str "some",Space,Str "incremental",Space,Str "bullets:"]
+,BulletList
+ [[Plain [Str "one"]]
+ ,[Plain [Str "two"]]
+ ,[Plain [Str "three"]]]
+,Para [Str "Then,",Space,Str "a",Space,Str "picture:"]
+,Para [Image ("",[],[]) [Str "An",Space,Str "image"] ("./lalune.jpg","fig:")]
+,Header 1 ("slide-8-comparison",[],[]) [Str "Slide",Space,Str "8",Space,Str "(Comparison)"]
+,Div ("",["columns"],[])
+ [Div ("",["column"],[])
+  [BulletList
+   [[Plain [Str "one"]]
+   ,[Plain [Str "two"]]
+   ,[Plain [Str "three"]]]
+  ,Para [Image ("",[],[]) [Str "An",Space,Str "image"] ("./lalune.jpg","fig:")]]
+ ,Div ("",["column"],[])
+  [OrderedList (1,Decimal,Period)
+   [[Plain [Str "one"]]
+   ,[Plain [Str "two"]]
+   ,[Plain [Str "three"]]]
+  ,Table ("",[],[]) (Caption Nothing
+   [])
+   [(AlignDefault,ColWidth 5.555555555555555e-2)]
+   (TableHead ("",[],[])
+   [Row ("",[],[])
+    [Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+     [Plain [Str "1"]]]])
+   [(TableBody ("",[],[]) (RowHeadColumns 0)
+    []
+    [Row ("",[],[])
+     [Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+      [Plain [Str "2"]]]])]
+   (TableFoot ("",[],[])
+   [])]]
+,Header 1 ("slide-9-content",[],[]) [Str "Slide",Space,Str "9",Space,Str "(Content)"]
+,Div ("",["nonincremental"],[])
+ [BulletList
+  [[Plain [Str "these"]]
+  ,[Plain [Str "are"]]
+  ,[Plain [Str "not"]]
+  ,[Plain [Str "incremental"]]]]
+,BulletList
+ [[Plain [Str "these"]]
+ ,[Plain [Str "are"]]]
+,Header 1 ("slide-10-content",[],[]) [Str "Slide",Space,Str "10",Space,Str "(Content)"]
+,Div ("",["incremental","nonincremental"],[])
+ [BulletList
+  [[Plain [Str "these"]]
+  ,[Plain [Str "are"]]
+  ,[Plain [Str "incremental"]]
+  ,[Plain [Str "(the",Space,Str "incremental",Space,Str "class",Space,Str "wins)"]]]]
+,Header 1 ("slide-11-content",[],[]) [Str "Slide",Space,Str "11",Space,Str "(Content)"]
+,Para [Str "These",Space,Str "bullets",Space,Str "are",Space,Str "not",Space,Str "incremental:"]
+,BlockQuote
+ [BulletList
+  [[Plain [Str "one"]]
+  ,[Plain [Str "two"]]
+  ,[Plain [Str "three"]]]]
+,Para [Str "These",Space,Str "are:"]
+,Div ("",["nonincremental"],[])
+ [BlockQuote
+  [BulletList
+   [[Plain [Str "one"]]
+   ,[Plain [Str "two"]]
+   ,[Plain [Str "three"]]]]]
+,Para [Str "These",Space,Str "are",Space,Str "not:"]
+,BlockQuote
+ [Div ("",["nonincremental"],[])
+  [BulletList
+   [[Plain [Str "one"]]
+   ,[Plain [Str "two"]]
+   ,[Plain [Str "three"]]]]]
+,Header 1 ("slide-12-content",[],[]) [Str "Slide",Space,Str "12",Space,Str "(Content)"]
+,Div ("",["nonincremental"],[])
+ [Div ("",["incremental"],[])
+  [BulletList
+   [[Plain [Str "these"]]
+   ,[Plain [Str "are"]]
+   ,[Plain [Str "incremental"]]]]]
+,Div ("",["incremental"],[])
+ [Div ("",["nonincremental"],[])
+  [BulletList
+   [[Plain [Str "these"]]
+   ,[Plain [Str "are"]]
+   ,[Plain [Str "not"]]]]]]
diff --git a/test/pptx/incremental-lists/with-flag/output.pptx b/test/pptx/incremental-lists/with-flag/output.pptx
new file mode 100644
Binary files /dev/null and b/test/pptx/incremental-lists/with-flag/output.pptx differ
diff --git a/test/pptx/incremental-lists/with-flag/templated.pptx b/test/pptx/incremental-lists/with-flag/templated.pptx
new file mode 100644
Binary files /dev/null and b/test/pptx/incremental-lists/with-flag/templated.pptx differ
diff --git a/test/pptx/incremental-lists/without-flag/input.native b/test/pptx/incremental-lists/without-flag/input.native
new file mode 100644
--- /dev/null
+++ b/test/pptx/incremental-lists/without-flag/input.native
@@ -0,0 +1,137 @@
+[Header 1 ("slide-1-content",[],[]) [Str "Slide",Space,Str "1",Space,Str "(Content)"]
+,Div ("",["incremental"],[])
+ [BulletList
+  [[Plain [Str "These"]]
+  ,[Plain [Str "bullets"]]
+  ,[Plain [Str "should"]]
+  ,[Plain [Str "be"]]
+  ,[Plain [Str "incremental"]]]]
+,Header 1 ("slide-2-content",[],[]) [Str "Slide",Space,Str "2",Space,Str "(Content)"]
+,BulletList
+ [[Plain [Str "These"]]
+ ,[Plain [Str "are"]]
+ ,[Plain [Str "not"]]]
+,Header 1 ("slide-3-content",[],[]) [Str "Slide",Space,Str "3",Space,Str "(Content)"]
+,Para [Str "Even",Space,Str "with",Space,Str "some",Space,Str "text",Space,Str "first,",Space,Str "these",Space,Str "should:"]
+,Div ("",["incremental"],[])
+ [BulletList
+  [[Plain [Str "also"]]
+  ,[Plain [Str "be"]]
+  ,[Plain [Str "incremental"]]]]
+,Header 1 ("slide-4-content",[],[]) [Str "Slide",Space,Str "4",Space,Str "(Content)"]
+,Div ("",["incremental"],[])
+ [OrderedList (1,Decimal,Period)
+  [[Plain [Str "These"]]
+  ,[Plain [Str "are"]]
+  ,[Plain [Str "incremental"]]]]
+,Para [Str "But",Space,Str "this",Space,Str "text",Space,Str "isn\8217t"]
+,Header 1 ("slide-5-two-content",[],[]) [Str "Slide",Space,Str "5",Space,Str "(Two",Space,Str "Content)"]
+,Div ("",["columns"],[])
+ [Div ("",["column"],[])
+  [Para [Str "Incremental",Space,Str "on",Space,Str "the",Space,Str "left:"]
+  ,Div ("",["incremental"],[])
+   [BulletList
+    [[Plain [Str "one"]]
+    ,[Plain [Str "by"]]
+    ,[Plain [Str "one"]]]]
+  ,Para [Str "With",Space,Str "something",Space,Str "below"]]
+ ,Div ("",["column"],[])
+  [Para [Str "Incremental",Space,Str "on",Space,Str "the",Space,Str "right:"]
+  ,Div ("",["incremental"],[])
+   [BulletList
+    [[Plain [Str "one"]]
+    ,[Plain [Str "by"]]
+    ,[Plain [Str "one"]]]]
+  ,BulletList
+   [[Plain [Str "already"]]
+   ,[Plain [Str "here"]]
+   ,[Plain [Str "though"]]]]]
+,Header 1 ("slide-6-two-content-right",[],[]) [Str "Slide",Space,Str "6",Space,Str "(Two",Space,Str "Content",Space,Str "Right)"]
+,Div ("",["columns"],[])
+ [Div ("",["column"],[])
+  [Para [Image ("",[],[]) [Str "an",Space,Str "image"] ("lalune.jpg","fig:")]]
+ ,Div ("",["column"],[])
+  [Div ("",["incremental"],[])
+   [BulletList
+    [[Plain [Str "An"]]
+    ,[Plain [Str "Incremental"]]
+    ,[Plain [Str "List"]]]]]]
+,Header 1 ("slide-7-content-with-caption",[],[]) [Str "Slide",Space,Str "7",Space,Str "(Content",Space,Str "with",Space,Str "Caption)"]
+,Para [Str "First,",Space,Str "we",Space,Str "have",Space,Str "some",Space,Str "incremental",Space,Str "bullets:"]
+,Div ("",["incremental"],[])
+ [BulletList
+  [[Plain [Str "one"]]
+  ,[Plain [Str "two"]]
+  ,[Plain [Str "three"]]]]
+,Para [Str "Then,",Space,Str "a",Space,Str "picture:"]
+,Para [Image ("",[],[]) [Str "An",Space,Str "image"] ("./lalune.jpg","fig:")]
+,Header 1 ("slide-8-comparison",[],[]) [Str "Slide",Space,Str "8",Space,Str "(Comparison)"]
+,Div ("",["columns"],[])
+ [Div ("",["column"],[])
+  [Div ("",["incremental"],[])
+   [BulletList
+    [[Plain [Str "one"]]
+    ,[Plain [Str "two"]]
+    ,[Plain [Str "three"]]]]
+  ,Para [Image ("",[],[]) [Str "An",Space,Str "image"] ("./lalune.jpg","fig:")]]
+ ,Div ("",["column"],[])
+  [Div ("",["incremental"],[])
+   [OrderedList (1,Decimal,Period)
+    [[Plain [Str "one"]]
+    ,[Plain [Str "two"]]
+    ,[Plain [Str "three"]]]]
+  ,Table ("",[],[]) (Caption Nothing
+   [])
+   [(AlignDefault,ColWidth 5.555555555555555e-2)]
+   (TableHead ("",[],[])
+   [Row ("",[],[])
+    [Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+     [Plain [Str "1"]]]])
+   [(TableBody ("",[],[]) (RowHeadColumns 0)
+    []
+    [Row ("",[],[])
+     [Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+      [Plain [Str "2"]]]])]
+   (TableFoot ("",[],[])
+   [])]]
+,Header 1 ("slide-10-content",[],[]) [Str "Slide",Space,Str "10",Space,Str "(Content)"]
+,Div ("",["incremental","nonincremental"],[])
+ [BulletList
+  [[Plain [Str "these"]]
+  ,[Plain [Str "are"]]
+  ,[Plain [Str "incremental"]]
+  ,[Plain [Str "(the",Space,Str "incremental",Space,Str "class",Space,Str "wins)"]]]]
+,Header 1 ("slide-11-content",[],[]) [Str "Slide",Space,Str "11",Space,Str "(Content)"]
+,Para [Str "These",Space,Str "bullets",Space,Str "are",Space,Str "incremental:"]
+,BlockQuote
+ [BulletList
+  [[Plain [Str "one"]]
+  ,[Plain [Str "two"]]
+  ,[Plain [Str "three"]]]]
+,Para [Str "These",Space,Str "are",Space,Str "not:"]
+,Div ("",["incremental"],[])
+ [BlockQuote
+  [BulletList
+   [[Plain [Str "one"]]
+   ,[Plain [Str "two"]]
+   ,[Plain [Str "three"]]]]]
+,Para [Str "These",Space,Str "are:"]
+,BlockQuote
+ [Div ("",["incremental"],[])
+  [BulletList
+   [[Plain [Str "one"]]
+   ,[Plain [Str "two"]]
+   ,[Plain [Str "three"]]]]]
+,Header 1 ("slide-12-content",[],[]) [Str "Slide",Space,Str "12",Space,Str "(Content)"]
+,Div ("",["nonincremental"],[])
+ [Div ("",["incremental"],[])
+  [BulletList
+   [[Plain [Str "these"]]
+   ,[Plain [Str "are"]]
+   ,[Plain [Str "incremental"]]]]]
+,Div ("",["incremental"],[])
+ [Div ("",["nonincremental"],[])
+  [BulletList
+   [[Plain [Str "these"]]
+   ,[Plain [Str "are"]]
+   ,[Plain [Str "not"]]]]]]
diff --git a/test/pptx/incremental-lists/without-flag/output.pptx b/test/pptx/incremental-lists/without-flag/output.pptx
new file mode 100644
Binary files /dev/null and b/test/pptx/incremental-lists/without-flag/output.pptx differ
diff --git a/test/pptx/incremental-lists/without-flag/templated.pptx b/test/pptx/incremental-lists/without-flag/templated.pptx
new file mode 100644
Binary files /dev/null and b/test/pptx/incremental-lists/without-flag/templated.pptx differ
diff --git a/test/pptx/inline-formatting/input.native b/test/pptx/inline-formatting/input.native
new file mode 100644
--- /dev/null
+++ b/test/pptx/inline-formatting/input.native
@@ -0,0 +1,5 @@
+[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/output.pptx b/test/pptx/inline-formatting/output.pptx
new file mode 100644
Binary files /dev/null and b/test/pptx/inline-formatting/output.pptx differ
diff --git a/test/pptx/inline-formatting/templated.pptx b/test/pptx/inline-formatting/templated.pptx
new file mode 100644
Binary files /dev/null and b/test/pptx/inline-formatting/templated.pptx differ
diff --git a/test/pptx/layouts/deleted.pptx b/test/pptx/layouts/deleted.pptx
new file mode 100644
Binary files /dev/null and b/test/pptx/layouts/deleted.pptx differ
diff --git a/test/pptx/layouts/input.native b/test/pptx/layouts/input.native
new file mode 100644
--- /dev/null
+++ b/test/pptx/layouts/input.native
@@ -0,0 +1,23 @@
+Pandoc (Meta {unMeta = fromList [("title",MetaInlines [Str "Testing",Space,Str "Layouts"])]})
+[Header 2 ("slide-1",[],[]) [Str "Slide",Space,Str "1"]
+,Para [Str "This",Space,Str "is",Space,Str "a",Space,Str "title",Space,Str "and",Space,Str "content",Space,Str "slide"]
+,Header 2 ("slide-2",[],[]) [Str "Slide",Space,Str "2"]
+,Div ("",["columns"],[])
+ [Div ("",["column"],[])
+  [Para [Str "This"]]
+ ,Div ("",["column"],[])
+  [Para [Str "\8230is",Space,Str "a",Space,Str "two-column",Space,Str "slide"]]]
+,Header 2 ("slide-3",[],[]) [Str "Slide",Space,Str "3"]
+,Para [Str "This",Space,Str "slide",Space,Str "is",Space,Str "a",Space,Str "Content",Space,Str "with",Space,Str "Caption",Space,Str "slide"]
+,Para [Image ("",[],[]) [Str "Content"] ("lalune.jpg","fig:")]
+,Header 2 ("slide-4",[],[]) [Str "Slide",Space,Str "4"]
+,Div ("",["columns"],[])
+ [Div ("",["column"],[])
+  [Para [Str "This",Space,Str "slide",Space,Str "is",Space,Str "a",Space,Str "Comparison",Space,Str "slide:"]
+  ,Para [Image ("",[],[]) [Str "Content"] ("lalune.jpg","fig:")]]
+ ,Div ("",["column"],[])
+  [Para [Str "Here",Space,Str "is",Space,Str "some",Space,Str "other",Space,Str "text"]]]
+,Header 1 ("section-header",[],[]) [Str "Section",Space,Str "header"]
+,Header 2 ("section",[],[]) []
+,Div ("",["notes"],[])
+ [Para [Str "This",Space,Str "is",Space,Str "a",Space,Str "blank",Space,Str "slide"]]]
diff --git a/test/pptx/layouts/moved.pptx b/test/pptx/layouts/moved.pptx
new file mode 100644
Binary files /dev/null and b/test/pptx/layouts/moved.pptx differ
diff --git a/test/pptx/list-level/input.native b/test/pptx/list-level/input.native
new file mode 100644
--- /dev/null
+++ b/test/pptx/list-level/input.native
@@ -0,0 +1,20 @@
+[Header 1 ("slide",[],[]) [Str "Slide"]
+,BulletList
+ [[Para [Str "Top-level"]
+  ,Para [Str "With",Space,Str "continuation",Space,Str "paragraph"]]
+ ,[Para [Str "Then:"]
+  ,BulletList
+   [[Plain [Str "nested"]]
+   ,[Plain [Str "list"]]
+   ,[Plain [Str "items"]]]]]
+,Header 1 ("slide-1",[],[]) [Str "Slide"]
+,Para [Str "Paragraph."]
+,OrderedList (1,Decimal,Period)
+ [[Para [Str "Top-level"]
+  ,Para [Str "Continuation"]
+  ,OrderedList (1,Decimal,Period)
+   [[Para [Str "Sub-list"]
+    ,Para [Str "With",Space,Str "Continuation"]]
+   ,[Para [Str "(still",Space,Str "sub-list)"]]]]
+ ,[Para [Str "(back",Space,Str "to",Space,Str "top-level)"]]]
+,Para [Str "Paragraph."]]
diff --git a/test/pptx/list-level/output.pptx b/test/pptx/list-level/output.pptx
new file mode 100644
Binary files /dev/null and b/test/pptx/list-level/output.pptx differ
diff --git a/test/pptx/list-level/templated.pptx b/test/pptx/list-level/templated.pptx
new file mode 100644
Binary files /dev/null and b/test/pptx/list-level/templated.pptx differ
diff --git a/test/pptx/lists/input.native b/test/pptx/lists/input.native
new file mode 100644
--- /dev/null
+++ b/test/pptx/lists/input.native
@@ -0,0 +1,18 @@
+[Header 1 ("lists",[],[]) [Str "Lists"]
+,BulletList
+ [[Para [Str "Bulleted",Space,Str "bulleted",Space,Str "lists."]]
+ ,[Para [Str "And",Space,Str "go",Space,Str "to",Space,Str "arbitrary",Space,Str "depth."]
+  ,BulletList
+   [[Para [Str "Like",Space,Str "this"]
+    ,BulletList
+     [[Plain [Str "Or",Space,Str "this"]]]]
+   ,[Para [Str "Back",Space,Str "to",Space,Str "here."]]]]]
+,Header 1 ("lists-continued",[],[]) [Str "Lists",Space,Str "(continued)"]
+,Para [Str "Lists",Space,Str "can",Space,Str "also",Space,Str "be",Space,Str "numbered:"]
+,OrderedList (1,Decimal,Period)
+ [[Para [Str "Tomatoes"]]
+ ,[Para [Str "Potatoes",Space,Str "of",Space,Str "various",Space,Str "sorts"]
+  ,OrderedList (1,LowerAlpha,Period)
+   [[Para [Str "sweet",Space,Str "potatoes"]]
+   ,[Para [Str "russet",Space,Str "potates"]]]]
+ ,[Para [Str "Tornadoes,",Space,Str "for",Space,Str "the",Space,Str "rhyme."]]]]
diff --git a/test/pptx/lists/output.pptx b/test/pptx/lists/output.pptx
new file mode 100644
Binary files /dev/null and b/test/pptx/lists/output.pptx differ
diff --git a/test/pptx/lists/templated.pptx b/test/pptx/lists/templated.pptx
new file mode 100644
Binary files /dev/null and b/test/pptx/lists/templated.pptx differ
diff --git a/test/pptx/metadata-speaker-notes/input.native b/test/pptx/metadata-speaker-notes/input.native
new file mode 100644
--- /dev/null
+++ b/test/pptx/metadata-speaker-notes/input.native
@@ -0,0 +1,3 @@
+Pandoc (Meta {unMeta = fromList [("author",MetaInlines [Str "Jesse",Space,Str "Rosenthal"]),("notes",MetaBlocks [Para [Str "These",Space,Str "are",Space,Str "speaker",Space,Str "notes",Space,Str "from",Space,Str "metadata."]]),("title",MetaInlines [Str "Testing"])]})
+[Header 1 ("a-header",[],[]) [Str "A",Space,Str "header"]
+,Para [Str "And",Space,Str "a",Space,Str "new",Space,Str "slide."]]
diff --git a/test/pptx/metadata-speaker-notes/output.pptx b/test/pptx/metadata-speaker-notes/output.pptx
new file mode 100644
Binary files /dev/null and b/test/pptx/metadata-speaker-notes/output.pptx differ
diff --git a/test/pptx/metadata-speaker-notes/templated.pptx b/test/pptx/metadata-speaker-notes/templated.pptx
new file mode 100644
Binary files /dev/null and b/test/pptx/metadata-speaker-notes/templated.pptx differ
diff --git a/test/pptx/pauses/without-incremental/output.pptx b/test/pptx/pauses/without-incremental/output.pptx
new file mode 100644
Binary files /dev/null and b/test/pptx/pauses/without-incremental/output.pptx differ
diff --git a/test/pptx/pauses/without-incremental/templated.pptx b/test/pptx/pauses/without-incremental/templated.pptx
new file mode 100644
Binary files /dev/null and b/test/pptx/pauses/without-incremental/templated.pptx differ
diff --git a/test/pptx/raw-ooxml/input.native b/test/pptx/raw-ooxml/input.native
new file mode 100644
--- /dev/null
+++ b/test/pptx/raw-ooxml/input.native
@@ -0,0 +1,3 @@
+[Para [Str "Here",Space,Str "is",Space,Str "some",Space,Str "text,",Space,Str "written",Space,Str "as",Space,Str "a",Space,Str "raw",Space,Str "inline:",Space,RawInline (Format "openxml") "<a:r><a:rPr /><a:t>Here are examples of </a:t></a:r><a:r><a:rPr i=\"1\" /><a:t>italics</a:t></a:r><a:r><a:rPr /><a:t>, </a:t></a:r><a:r><a:rPr b=\"1\" /><a:t>bold</a:t></a:r>"]
+,HorizontalRule
+,RawBlock (Format "openxml") "<p:sp>\n        <p:nvSpPr>\n          <p:cNvPr id=\"3\" name=\"Content Placeholder 2\" />\n          <p:cNvSpPr>\n            <a:spLocks noGrp=\"1\" />\n          </p:cNvSpPr>\n          <p:nvPr>\n            <p:ph idx=\"1\" />\n          </p:nvPr>\n        </p:nvSpPr>\n        <p:spPr />\n        <p:txBody>\n          <a:bodyPr />\n          <a:lstStyle />\n          <a:p>\n            <a:pPr lvl=\"1\" />\n            <a:r>\n              <a:rPr />\n              <a:t>Bulleted bulleted lists.</a:t>\n            </a:r>\n          </a:p>\n          <a:p>\n            <a:pPr lvl=\"1\" />\n            <a:r>\n              <a:rPr />\n              <a:t>And go to arbitrary depth.</a:t>\n            </a:r>\n          </a:p>\n          <a:p>\n            <a:pPr lvl=\"2\" />\n            <a:r>\n              <a:rPr />\n              <a:t>Like this</a:t>\n            </a:r>\n          </a:p>\n          <a:p>\n            <a:pPr lvl=\"3\" />\n            <a:r>\n              <a:rPr />\n              <a:t>Or this</a:t>\n            </a:r>\n          </a:p>\n          <a:p>\n            <a:pPr lvl=\"2\" />\n            <a:r>\n              <a:rPr />\n              <a:t>Back to here.</a:t>\n            </a:r>\n          </a:p>\n        </p:txBody>\n      </p:sp>"]
diff --git a/test/pptx/raw-ooxml/output.pptx b/test/pptx/raw-ooxml/output.pptx
new file mode 100644
Binary files /dev/null and b/test/pptx/raw-ooxml/output.pptx differ
diff --git a/test/pptx/raw-ooxml/templated.pptx b/test/pptx/raw-ooxml/templated.pptx
new file mode 100644
Binary files /dev/null and b/test/pptx/raw-ooxml/templated.pptx differ
diff --git a/test/pptx/reference-deleted-layouts.pptx b/test/pptx/reference-deleted-layouts.pptx
new file mode 100644
Binary files /dev/null and b/test/pptx/reference-deleted-layouts.pptx differ
diff --git a/test/pptx/reference-depth.pptx b/test/pptx/reference-depth.pptx
new file mode 100644
Binary files /dev/null and b/test/pptx/reference-depth.pptx differ
diff --git a/test/pptx/reference-moved-layouts.pptx b/test/pptx/reference-moved-layouts.pptx
new file mode 100644
Binary files /dev/null and b/test/pptx/reference-moved-layouts.pptx differ
diff --git a/test/pptx/reference-no-slides.pptx b/test/pptx/reference-no-slides.pptx
new file mode 100644
Binary files /dev/null and b/test/pptx/reference-no-slides.pptx differ
diff --git a/test/pptx/reference-no-slides/add-slides/input.native b/test/pptx/reference-no-slides/add-slides/input.native
new file mode 100644
--- /dev/null
+++ b/test/pptx/reference-no-slides/add-slides/input.native
@@ -0,0 +1,14 @@
+[ Header
+    2
+    ( "first-slide" , [] , [] )
+    [ Str "First" , Space , Str "Slide" ]
+, Para [ Str "Title" ]
+, Header
+    2
+    ( "second-slide" , [] , [] )
+    [ Str "Second" , Space , Str "Slide" ]
+, BulletList
+    [ [ Plain [ Str "First" , Space , Str "item" ] ]
+    , [ Plain [ Str "Second" , Space , Str "item" ] ]
+    ]
+]
diff --git a/test/pptx/reference-no-slides/add-slides/output.pptx b/test/pptx/reference-no-slides/add-slides/output.pptx
new file mode 100644
Binary files /dev/null and b/test/pptx/reference-no-slides/add-slides/output.pptx differ
diff --git a/test/pptx/reference-no-slides/with-notes/input.native b/test/pptx/reference-no-slides/with-notes/input.native
new file mode 100644
--- /dev/null
+++ b/test/pptx/reference-no-slides/with-notes/input.native
@@ -0,0 +1,70 @@
+[ Header
+    2
+    ( "first-slide" , [] , [] )
+    [ Str "First" , Space , Str "Slide" ]
+, Para
+    [ Str "First"
+    , Space
+    , Str "slide"
+    , Space
+    , Str "with"
+    , Space
+    , Str "notes"
+    ]
+, Div
+    ( "" , [ "notes" ] , [] )
+    [ Para
+        [ Str "Notes"
+        , Space
+        , Str "for"
+        , Space
+        , Str "the"
+        , Space
+        , Str "first"
+        , Space
+        , Str "slide"
+        ]
+    ]
+, Header
+    2
+    ( "second-slide" , [] , [] )
+    [ Str "Second" , Space , Str "Slide" ]
+, Para
+    [ Str "Slide"
+    , Space
+    , Str "without"
+    , Space
+    , Str "notes"
+    ]
+, Header
+    2
+    ( "third-slide" , [] , [] )
+    [ Str "Third" , Space , Str "Slide" ]
+, Para
+    [ Str "Slide"
+    , Space
+    , Str "with"
+    , Space
+    , Str "notes"
+    , Space
+    , Str "again"
+    ]
+, BulletList
+    [ [ Plain [ Str "First" , Space , Str "item" ] ]
+    , [ Plain [ Str "Second" , Space , Str "item" ] ]
+    ]
+, Div
+    ( "" , [ "notes" ] , [] )
+    [ Para
+        [ Str "Notes"
+        , Space
+        , Str "for"
+        , Space
+        , Str "the"
+        , Space
+        , Str "third"
+        , Space
+        , Str "slides"
+        ]
+    ]
+]
diff --git a/test/pptx/reference-no-slides/with-notes/output.pptx b/test/pptx/reference-no-slides/with-notes/output.pptx
new file mode 100644
Binary files /dev/null and b/test/pptx/reference-no-slides/with-notes/output.pptx differ
diff --git a/test/pptx/remove-empty-slides/input.native b/test/pptx/remove-empty-slides/input.native
new file mode 100644
--- /dev/null
+++ b/test/pptx/remove-empty-slides/input.native
@@ -0,0 +1,5 @@
+[Para [Str "Content"]
+,Para [Image ("",[],[]) [] ("lalune.jpg",""),Space,RawInline (Format "html") "<!--  -->"]
+,HorizontalRule
+,HorizontalRule
+,Para [Str "More",Space,Str "content"]]
diff --git a/test/pptx/remove-empty-slides/output.pptx b/test/pptx/remove-empty-slides/output.pptx
new file mode 100644
Binary files /dev/null and b/test/pptx/remove-empty-slides/output.pptx differ
diff --git a/test/pptx/remove-empty-slides/templated.pptx b/test/pptx/remove-empty-slides/templated.pptx
new file mode 100644
Binary files /dev/null and b/test/pptx/remove-empty-slides/templated.pptx differ
diff --git a/test/pptx/single-column/image/input.native b/test/pptx/single-column/image/input.native
new file mode 100644
--- /dev/null
+++ b/test/pptx/single-column/image/input.native
@@ -0,0 +1,22 @@
+[ Header
+    1
+    ( "single-column" , [] , [] )
+    [ Str "Single" , Space , Str "column" ]
+, Div
+    ( "" , [ "columns" ] , [] )
+    [ Div
+        ( "" , [ "column" ] , [] )
+        [ Figure
+            ( "" , [] , [] )
+            (Caption
+               Nothing [ Plain [ Str "an" , Space , Str "image" ] ])
+            [ Plain
+                [ Image
+                    ( "" , [] , [] )
+                    [ Str "an" , Space , Str "image" ]
+                    ( "lalune.jpg" , "" )
+                ]
+            ]
+        ]
+    ]
+]
diff --git a/test/pptx/single-column/image/output.pptx b/test/pptx/single-column/image/output.pptx
new file mode 100644
Binary files /dev/null and b/test/pptx/single-column/image/output.pptx differ
diff --git a/test/pptx/single-column/image/templated.pptx b/test/pptx/single-column/image/templated.pptx
new file mode 100644
Binary files /dev/null and b/test/pptx/single-column/image/templated.pptx differ
diff --git a/test/pptx/single-column/text/input.native b/test/pptx/single-column/text/input.native
new file mode 100644
--- /dev/null
+++ b/test/pptx/single-column/text/input.native
@@ -0,0 +1,13 @@
+[ Header
+    1
+    ( "single-column" , [] , [] )
+    [ Str "Single" , Space , Str "column" ]
+, Div
+    ( "" , [ "columns" ] , [] )
+    [ Div
+        ( "" , [ "column" ] , [] )
+        [ Para [ Str "One" , Space , Str "paragraph." ]
+        , Para [ Str "Another" , Space , Str "paragraph." ]
+        ]
+    ]
+]
diff --git a/test/pptx/single-column/text/output.pptx b/test/pptx/single-column/text/output.pptx
new file mode 100644
Binary files /dev/null and b/test/pptx/single-column/text/output.pptx differ
diff --git a/test/pptx/single-column/text/templated.pptx b/test/pptx/single-column/text/templated.pptx
new file mode 100644
Binary files /dev/null and b/test/pptx/single-column/text/templated.pptx differ
diff --git a/test/pptx/slide-breaks-slide-level-1/output.pptx b/test/pptx/slide-breaks-slide-level-1/output.pptx
new file mode 100644
Binary files /dev/null and b/test/pptx/slide-breaks-slide-level-1/output.pptx differ
diff --git a/test/pptx/slide-breaks-slide-level-1/templated.pptx b/test/pptx/slide-breaks-slide-level-1/templated.pptx
new file mode 100644
Binary files /dev/null and b/test/pptx/slide-breaks-slide-level-1/templated.pptx differ
diff --git a/test/pptx/slide-breaks-toc/output.pptx b/test/pptx/slide-breaks-toc/output.pptx
new file mode 100644
Binary files /dev/null and b/test/pptx/slide-breaks-toc/output.pptx differ
diff --git a/test/pptx/slide-breaks-toc/templated.pptx b/test/pptx/slide-breaks-toc/templated.pptx
new file mode 100644
Binary files /dev/null and b/test/pptx/slide-breaks-toc/templated.pptx differ
diff --git a/test/pptx/slide-breaks/input.native b/test/pptx/slide-breaks/input.native
new file mode 100644
--- /dev/null
+++ b/test/pptx/slide-breaks/input.native
@@ -0,0 +1,7 @@
+Pandoc (Meta {unMeta = fromList []})
+[Para [Str "Break",Space,Str "with",Space,Str "a",Space,Str "new",Space,Str "section-level",Space,Str "header"]
+,Header 1 ("below-section-level",[],[]) [Str "Below",Space,Str "section-level"]
+,Header 2 ("section-level",[],[]) [Str "Section-level"]
+,Para [Str "Third",Space,Str "slide",Space,Str "(with",Space,Str "a",Space,Str "section-level",Space,Str "of",Space,Str "2)"]
+,HorizontalRule
+,Para [Str "This",Space,Str "is",Space,Str "another",Space,Str "slide."]]
diff --git a/test/pptx/slide-breaks/output.pptx b/test/pptx/slide-breaks/output.pptx
new file mode 100644
Binary files /dev/null and b/test/pptx/slide-breaks/output.pptx differ
diff --git a/test/pptx/slide-breaks/templated.pptx b/test/pptx/slide-breaks/templated.pptx
new file mode 100644
Binary files /dev/null and b/test/pptx/slide-breaks/templated.pptx differ
diff --git a/test/pptx/slide-level-0/h1-h2-with-table/input.native b/test/pptx/slide-level-0/h1-h2-with-table/input.native
new file mode 100644
--- /dev/null
+++ b/test/pptx/slide-level-0/h1-h2-with-table/input.native
@@ -0,0 +1,14 @@
+[Header 1 ("hello",[],[]) [Str "Hello"]
+,Header 2 ("there",[],[]) [Str "There"]
+,Table ("",[],[]) (Caption Nothing
+ [])
+ [(AlignDefault,ColWidth 5.555555555555555e-2)]
+ (TableHead ("",[],[])
+ [])
+ [(TableBody ("",[],[]) (RowHeadColumns 0)
+  []
+  [Row ("",[],[])
+   [Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "1"]]]])]
+ (TableFoot ("",[],[])
+ [])]
diff --git a/test/pptx/slide-level-0/h1-h2-with-table/output.pptx b/test/pptx/slide-level-0/h1-h2-with-table/output.pptx
new file mode 100644
Binary files /dev/null and b/test/pptx/slide-level-0/h1-h2-with-table/output.pptx differ
diff --git a/test/pptx/slide-level-0/h1-h2-with-table/templated.pptx b/test/pptx/slide-level-0/h1-h2-with-table/templated.pptx
new file mode 100644
Binary files /dev/null and b/test/pptx/slide-level-0/h1-h2-with-table/templated.pptx differ
diff --git a/test/pptx/slide-level-0/h1-with-image/input.native b/test/pptx/slide-level-0/h1-with-image/input.native
new file mode 100644
--- /dev/null
+++ b/test/pptx/slide-level-0/h1-with-image/input.native
@@ -0,0 +1,2 @@
+[Header 1 ("hello",[],[]) [Str "Hello"]
+,Para [Image ("",[],[]) [Str "An",Space,Str "image"] ("lalune.jpg","fig:")]]
diff --git a/test/pptx/slide-level-0/h1-with-image/output.pptx b/test/pptx/slide-level-0/h1-with-image/output.pptx
new file mode 100644
Binary files /dev/null and b/test/pptx/slide-level-0/h1-with-image/output.pptx differ
diff --git a/test/pptx/slide-level-0/h1-with-image/templated.pptx b/test/pptx/slide-level-0/h1-with-image/templated.pptx
new file mode 100644
Binary files /dev/null and b/test/pptx/slide-level-0/h1-with-image/templated.pptx differ
diff --git a/test/pptx/slide-level-0/h1-with-table/input.native b/test/pptx/slide-level-0/h1-with-table/input.native
new file mode 100644
--- /dev/null
+++ b/test/pptx/slide-level-0/h1-with-table/input.native
@@ -0,0 +1,13 @@
+[Header 1 ("hello",[],[]) [Str "Hello"]
+,Table ("",[],[]) (Caption Nothing
+ [])
+ [(AlignDefault,ColWidth 5.555555555555555e-2)]
+ (TableHead ("",[],[])
+ [])
+ [(TableBody ("",[],[]) (RowHeadColumns 0)
+  []
+  [Row ("",[],[])
+   [Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "1"]]]])]
+ (TableFoot ("",[],[])
+ [])]
diff --git a/test/pptx/slide-level-0/h1-with-table/output.pptx b/test/pptx/slide-level-0/h1-with-table/output.pptx
new file mode 100644
Binary files /dev/null and b/test/pptx/slide-level-0/h1-with-table/output.pptx differ
diff --git a/test/pptx/slide-level-0/h1-with-table/templated.pptx b/test/pptx/slide-level-0/h1-with-table/templated.pptx
new file mode 100644
Binary files /dev/null and b/test/pptx/slide-level-0/h1-with-table/templated.pptx differ
diff --git a/test/pptx/slide-level-0/h2-with-image/input.native b/test/pptx/slide-level-0/h2-with-image/input.native
new file mode 100644
--- /dev/null
+++ b/test/pptx/slide-level-0/h2-with-image/input.native
@@ -0,0 +1,2 @@
+[Header 2 ("hello",[],[]) [Str "Hello"]
+,Para [Image ("",[],[]) [Str "An",Space,Str "image"] ("lalune.jpg","fig:")]]
diff --git a/test/pptx/slide-level-0/h2-with-image/output.pptx b/test/pptx/slide-level-0/h2-with-image/output.pptx
new file mode 100644
Binary files /dev/null and b/test/pptx/slide-level-0/h2-with-image/output.pptx differ
diff --git a/test/pptx/slide-level-0/h2-with-image/templated.pptx b/test/pptx/slide-level-0/h2-with-image/templated.pptx
new file mode 100644
Binary files /dev/null and b/test/pptx/slide-level-0/h2-with-image/templated.pptx differ
diff --git a/test/pptx/speaker-notes-after-metadata/input.native b/test/pptx/speaker-notes-after-metadata/input.native
new file mode 100644
--- /dev/null
+++ b/test/pptx/speaker-notes-after-metadata/input.native
@@ -0,0 +1,5 @@
+Pandoc (Meta {unMeta = fromList [("author",MetaInlines [Str "Jesse",Space,Str "Rosenthal"]),("title",MetaInlines [Str "Testing"])]})
+[Div ("",["notes"],[])
+ [Para [Str "Some",Space,Str "speaker",Space,Str "notes"]]
+,Header 1 ("a-header",[],[]) [Str "A",Space,Str "header"]
+,Para [Str "And",Space,Str "a",Space,Str "new",Space,Str "slide."]]
diff --git a/test/pptx/speaker-notes-after-metadata/output.pptx b/test/pptx/speaker-notes-after-metadata/output.pptx
new file mode 100644
Binary files /dev/null and b/test/pptx/speaker-notes-after-metadata/output.pptx differ
diff --git a/test/pptx/speaker-notes-after-metadata/templated.pptx b/test/pptx/speaker-notes-after-metadata/templated.pptx
new file mode 100644
Binary files /dev/null and b/test/pptx/speaker-notes-after-metadata/templated.pptx differ
diff --git a/test/pptx/speaker-notes-afterheader/input.native b/test/pptx/speaker-notes-afterheader/input.native
new file mode 100644
--- /dev/null
+++ b/test/pptx/speaker-notes-afterheader/input.native
@@ -0,0 +1,3 @@
+[Header 1 ("here-is-a-single-header",[],[]) [Str "Here",Space,Str "is",Space,Str "a",Space,Str "single",Space,Str "header"]
+,Div ("",["notes"],[])
+ [Para [Str "and",Space,Str "here",Space,Str "are",Space,Str "some",Space,Str "notes"]]]
diff --git a/test/pptx/speaker-notes-afterheader/output.pptx b/test/pptx/speaker-notes-afterheader/output.pptx
new file mode 100644
Binary files /dev/null and b/test/pptx/speaker-notes-afterheader/output.pptx differ
diff --git a/test/pptx/speaker-notes-afterheader/templated.pptx b/test/pptx/speaker-notes-afterheader/templated.pptx
new file mode 100644
Binary files /dev/null and b/test/pptx/speaker-notes-afterheader/templated.pptx differ
diff --git a/test/pptx/speaker-notes-afterseps/input.native b/test/pptx/speaker-notes-afterseps/input.native
new file mode 100644
--- /dev/null
+++ b/test/pptx/speaker-notes-afterseps/input.native
@@ -0,0 +1,63 @@
+[Para [Image ("",[],[]) [Str "The",Space,Str "moon"] ("lalune.jpg","fig:")]
+,Div ("",["notes"],[])
+ [Para [Str "chicken",Space,Str "and",Space,Str "dumplings"]]
+,Table ("",[],[]) (Caption Nothing
+ [Para [Str "Demonstration",Space,Str "of",Space,Str "simple",Space,Str "table",Space,Str "syntax,",Space,Str "with",Space,Str "alignment"]])
+ [(AlignRight,ColWidthDefault)
+ ,(AlignLeft,ColWidthDefault)
+ ,(AlignCenter,ColWidthDefault)
+ ,(AlignDefault,ColWidthDefault)]
+ (TableHead ("",[],[])
+ [Row ("",[],[])
+  [Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+   [Plain [Str "Right"]]
+  ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+   [Plain [Str "Left"]]
+  ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+   [Plain [Str "Center"]]
+  ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+   [Plain [Str "Default"]]]])
+ [(TableBody ("",[],[]) (RowHeadColumns 0)
+  []
+  [Row ("",[],[])
+   [Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "12"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "12"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "12"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "12"]]]
+  ,Row ("",[],[])
+   [Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "123"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "123"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "123"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "123"]]]
+  ,Row ("",[],[])
+   [Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "1"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "1"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "1"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "1"]]]])]
+ (TableFoot ("",[],[])
+ [])
+,Div ("",["notes"],[])
+ [Para [Str "foo",Space,Str "bar"]]
+,Div ("",["columns"],[])
+ [Div ("",["column"],[])
+  [BulletList
+   [[Para [Str "some",Space,Str "stuff"]]
+   ,[Para [Str "some",Space,Str "more",Space,Str "stuff"]]]
+  ,Div ("",["notes"],[])
+   [Para [Str "Some",Space,Str "notes",Space,Str "inside",Space,Str "a",Space,Str "column"]]]
+ ,Div ("",["column"],[])
+  [Para [Str "Some",Space,Str "other",Space,Emph [Str "stuff"]]]]
+,Div ("",["notes"],[])
+ [Para [Str "Some",Space,Str "notes",Space,Str "outside",Space,Str "the",Space,Str "column"]]]
diff --git a/test/pptx/speaker-notes-afterseps/output.pptx b/test/pptx/speaker-notes-afterseps/output.pptx
new file mode 100644
Binary files /dev/null and b/test/pptx/speaker-notes-afterseps/output.pptx differ
diff --git a/test/pptx/speaker-notes-afterseps/templated.pptx b/test/pptx/speaker-notes-afterseps/templated.pptx
new file mode 100644
Binary files /dev/null and b/test/pptx/speaker-notes-afterseps/templated.pptx differ
diff --git a/test/pptx/speaker-notes/input.native b/test/pptx/speaker-notes/input.native
new file mode 100644
--- /dev/null
+++ b/test/pptx/speaker-notes/input.native
@@ -0,0 +1,17 @@
+[Para [Str "Here",Space,Str "is",Space,Str "a",Space,Str "slide."]
+,Div ("",["notes"],[])
+ [Para [Str "Here",Space,Str "is",Space,Str "a",Space,Str "note."]
+ ,Para [Str "Here",Space,Str "is",Space,Emph [Str "some"],Space,Strong [Str "other"],Space,Str "formatting."]]
+,HorizontalRule
+,Para [Str "A",Space,Str "page",Space,Str "with",Space,Str "no",Space,Str "speaker",Space,Str "notes"]
+,HorizontalRule
+,Div ("",["notes"],[])
+ [Para [Str "The",Space,Str "first",Space,Str "note",Space,Str "div"]]
+,Para [Str "A",Space,Str "page",Space,Str "with",Space,Str "two",Space,Str "notes."]
+,Div ("",["notes"],[])
+ [Para [Str "The",Space,Str "second",Space,Str "note",Space,Str "div"]]
+,HorizontalRule
+,Para [Str "Strip",Space,Str "links",Space,Str "and",Space,Str "footnotes."]
+,Div ("",["notes"],[])
+ [Para [Str "No",Space,Link ("",[],[]) [Str "link"] ("https://www.google.com",""),Space,Str "here."]
+ ,Para [Str "No",Space,Str "note",Space,Str "here.",Note [Para [Str "You\8217ll",Space,Str "never",Space,Str "read",Space,Str "this"]]]]]
diff --git a/test/pptx/speaker-notes/output.pptx b/test/pptx/speaker-notes/output.pptx
new file mode 100644
Binary files /dev/null and b/test/pptx/speaker-notes/output.pptx differ
diff --git a/test/pptx/speaker-notes/templated.pptx b/test/pptx/speaker-notes/templated.pptx
new file mode 100644
Binary files /dev/null and b/test/pptx/speaker-notes/templated.pptx differ
diff --git a/test/pptx/start-numbering-at/input.native b/test/pptx/start-numbering-at/input.native
new file mode 100644
--- /dev/null
+++ b/test/pptx/start-numbering-at/input.native
@@ -0,0 +1,9 @@
+[Header 2 ("example-numbering-mwe",[],[]) [Str "Example",Space,Str "numbering",Space,Str "MWE"]
+,Para [Str "This",Space,Str "is",Space,Str "a",Space,Str "slide",Space,Str "with",Space,Str "examples",Space,Str "in",Space,Str "(1)",Space,Str "and",Space,Str "(2)"]
+,OrderedList (1,Example,TwoParens)
+ [[Plain [Str "First"]]
+ ,[Plain [Str "Second"]]]
+,Header 2 ("a-second-slide",[],[]) [Str "A",Space,Str "second",Space,Str "slide"]
+,Para [Str "This",Space,Str "second",Space,Str "slide",Space,Str "has",Space,Str "a",Space,Str "third",Space,Str "example",Space,Str "in",Space,Str "(3)."]
+,OrderedList (3,Example,TwoParens)
+ [[Plain [Str "Third"]]]]
diff --git a/test/pptx/start-numbering-at/output.pptx b/test/pptx/start-numbering-at/output.pptx
new file mode 100644
Binary files /dev/null and b/test/pptx/start-numbering-at/output.pptx differ
diff --git a/test/pptx/start-numbering-at/templated.pptx b/test/pptx/start-numbering-at/templated.pptx
new file mode 100644
Binary files /dev/null and b/test/pptx/start-numbering-at/templated.pptx differ
diff --git a/test/pptx/tables/input.native b/test/pptx/tables/input.native
new file mode 100644
--- /dev/null
+++ b/test/pptx/tables/input.native
@@ -0,0 +1,95 @@
+[Header 2 ("a-table-with-a-caption",[],[]) [Str "A",Space,Str "Table,",Space,Str "with",Space,Str "a",Space,Str "caption"]
+,Table ("",[],[]) (Caption Nothing
+ [Para [Str "Demonstration",Space,Str "of",Space,Str "simple",Space,Str "table",Space,Str "syntax,",Space,Str "with",Space,Str "alignment"]])
+ [(AlignRight,ColWidthDefault)
+ ,(AlignLeft,ColWidthDefault)
+ ,(AlignCenter,ColWidthDefault)
+ ,(AlignDefault,ColWidthDefault)]
+ (TableHead ("",[],[])
+ [Row ("",[],[])
+  [Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+   [Plain [Str "Right"]]
+  ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+   [Plain [Str "Left"]]
+  ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+   [Plain [Str "Center"]]
+  ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+   [Plain [Str "Default"]]]])
+ [(TableBody ("",[],[]) (RowHeadColumns 0)
+  []
+  [Row ("",[],[])
+   [Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "12"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "12"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "12"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "12"]]]
+  ,Row ("",[],[])
+   [Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "123"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "123"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "123"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "123"]]]
+  ,Row ("",[],[])
+   [Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "1"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "1"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "1"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "1"]]]])]
+ (TableFoot ("",[],[])
+ [])
+,Table ("",[],[]) (Caption Nothing
+ [])
+ [(AlignRight,ColWidthDefault)
+ ,(AlignLeft,ColWidthDefault)
+ ,(AlignCenter,ColWidthDefault)
+ ,(AlignDefault,ColWidthDefault)]
+ (TableHead ("",[],[])
+ [Row ("",[],[])
+  [Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+   [Plain [Str "Right"]]
+  ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+   [Plain [Str "Left"]]
+  ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+   [Plain [Str "Center"]]
+  ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+   [Plain [Str "Default"]]]])
+ [(TableBody ("",[],[]) (RowHeadColumns 0)
+  []
+  [Row ("",[],[])
+   [Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "12"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "12"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "12"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "12"]]]
+  ,Row ("",[],[])
+   [Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "123"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "123"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "123"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "123"]]]
+  ,Row ("",[],[])
+   [Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "1"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "1"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "1"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "1"]]]])]
+ (TableFoot ("",[],[])
+ [])]
diff --git a/test/pptx/tables/output.pptx b/test/pptx/tables/output.pptx
new file mode 100644
Binary files /dev/null and b/test/pptx/tables/output.pptx differ
diff --git a/test/pptx/tables/templated.pptx b/test/pptx/tables/templated.pptx
new file mode 100644
Binary files /dev/null and b/test/pptx/tables/templated.pptx differ
diff --git a/test/pptx/two-column/all-text/input.native b/test/pptx/two-column/all-text/input.native
new file mode 100644
--- /dev/null
+++ b/test/pptx/two-column/all-text/input.native
@@ -0,0 +1,9 @@
+Pandoc (Meta {unMeta = fromList []})
+[Header 1 ("two-column-layout",[],[]) [Str "Two-Column",Space,Str "Layout"]
+,Div ("",["columns"],[])
+ [Div ("",["column"],[])
+  [Para [Str "One",Space,Str "paragraph."]
+  ,Para [Str "Another",Space,Str "paragraph."]]
+ ,Div ("",["column"],[])
+  [Para [Str "Second",Space,Str "column",Space,Str "paragraph."]
+  ,Para [Str "Another",Space,Str "second",Space,Str "paragraph."]]]]
diff --git a/test/pptx/two-column/all-text/output.pptx b/test/pptx/two-column/all-text/output.pptx
new file mode 100644
Binary files /dev/null and b/test/pptx/two-column/all-text/output.pptx differ
diff --git a/test/pptx/two-column/all-text/templated.pptx b/test/pptx/two-column/all-text/templated.pptx
new file mode 100644
Binary files /dev/null and b/test/pptx/two-column/all-text/templated.pptx differ
diff --git a/test/pptx/two-column/text-and-image/input.native b/test/pptx/two-column/text-and-image/input.native
new file mode 100644
--- /dev/null
+++ b/test/pptx/two-column/text-and-image/input.native
@@ -0,0 +1,12 @@
+[Header 1 ("slide-1",[],[]) [Str "Slide",Space,Str "1"]
+,Div ("",["columns"],[])
+ [Div ("",["column"],[])
+  [Para [Image ("",[],[]) [Str "an",Space,Str "image"] ("lalune.jpg","fig:")]]
+ ,Div ("",["column"],[])
+  [Para [Str "This",Space,Str "should",Space,Str "use",Space,Str "Two",Space,Str "Content,",Space,Emph [Str "not"],Space,Str "Comparison!"]]]
+,Header 1 ("slide-2",[],[]) [Str "Slide",Space,Str "2"]
+,Div ("",["columns"],[])
+ [Div ("",["column"],[])
+  [Para [Str "This",Space,Str "should",Space,Str "also",Space,Str "use",Space,Str "Two",Space,Str "Content"]]
+ ,Div ("",["column"],[])
+  [Para [Image ("",[],[]) [Str "an",Space,Str "image"] ("lalune.jpg","fig:")]]]]
diff --git a/test/pptx/two-column/text-and-image/output.pptx b/test/pptx/two-column/text-and-image/output.pptx
new file mode 100644
Binary files /dev/null and b/test/pptx/two-column/text-and-image/output.pptx differ
diff --git a/test/pptx/two-column/text-and-image/templated.pptx b/test/pptx/two-column/text-and-image/templated.pptx
new file mode 100644
Binary files /dev/null and b/test/pptx/two-column/text-and-image/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
@@ -1,335 +1,1948 @@
-Pandoc (Meta {unMeta = fromList [("author",MetaList [MetaInlines [Str "John",Space,Str "MacFarlane"],MetaInlines [Str "Anonymous"]]),("date",MetaInlines [Str "July",Space,Str "17,",Space,Str "2006"]),("revision",MetaBlocks [Para [Str "3"]]),("subtitle",MetaInlines [Str "Subtitle"]),("title",MetaInlines [Str "Pandoc",Space,Str "Test",Space,Str "Suite"])]})
-[Header 1 ("level-one-header",[],[]) [Str "Level",Space,Str "one",Space,Str "header"]
-,Para [Str "This",Space,Str "is",Space,Str "a",Space,Str "set",Space,Str "of",Space,Str "tests",Space,Str "for",Space,Str "pandoc.",Space,Str "Most",Space,Str "of",Space,Str "them",Space,Str "are",Space,Str "adapted",Space,Str "from",SoftBreak,Str "John",Space,Str "Gruber\8217s",Space,Str "markdown",Space,Str "test",Space,Str "suite."]
-,Header 2 ("level-two-header",[],[]) [Str "Level",Space,Str "two",Space,Str "header"]
-,Header 3 ("level-three",[],[]) [Str "Level",Space,Str "three"]
-,Header 4 ("level-four-with-emphasis",[],[]) [Str "Level",Space,Str "four",Space,Str "with",Space,Emph [Str "emphasis"]]
-,Header 5 ("level-five",[],[]) [Str "Level",Space,Str "five"]
-,Header 1 ("paragraphs",[],[]) [Str "Paragraphs"]
-,Para [Str "Here\8217s",Space,Str "a",Space,Str "regular",Space,Str "paragraph."]
-,Para [Str "In",Space,Str "Markdown",Space,Str "1.0.0",Space,Str "and",Space,Str "earlier.",Space,Str "Version",SoftBreak,Str "8.",Space,Str "This",Space,Str "line",Space,Str "turns",Space,Str "into",Space,Str "a",Space,Str "list",Space,Str "item.",SoftBreak,Str "Because",Space,Str "a",Space,Str "hard-wrapped",Space,Str "line",Space,Str "in",Space,Str "the",SoftBreak,Str "middle",Space,Str "of",Space,Str "a",Space,Str "paragraph",Space,Str "looked",Space,Str "like",Space,Str "a",SoftBreak,Str "list",Space,Str "item."]
-,Para [Str "Here\8217s",Space,Str "one",Space,Str "with",Space,Str "a",Space,Str "bullet.",SoftBreak,Str "*",Space,Str "criminey."]
-,Para [Str "Horizontal",Space,Str "rule:"]
-,HorizontalRule
-,Para [Str "Another:"]
-,HorizontalRule
-,Header 1 ("block-quotes",[],[]) [Str "Block",Space,Str "Quotes"]
-,Para [Str "Here\8217s",Space,Str "a",Space,Str "block",Space,Str "quote:"]
-,BlockQuote
- [Para [Str "This",Space,Str "is",Space,Str "a",Space,Str "block",Space,Str "quote.",SoftBreak,Str "It",Space,Str "is",Space,Str "pretty",Space,Str "short."]]
-,Para [Str "Here\8217s",Space,Str "another,",Space,Str "differently",Space,Str "indented:"]
-,BlockQuote
- [Para [Str "This",Space,Str "is",Space,Str "a",Space,Str "block",Space,Str "quote.",SoftBreak,Str "It\8217s",Space,Str "indented",Space,Str "with",Space,Str "a",Space,Str "tab."]
- ,Para [Str "Code",Space,Str "in",Space,Str "a",Space,Str "block",Space,Str "quote:"]
- ,CodeBlock ("",[],[]) "sub status {\n    print \"working\";\n}"
- ,Para [Str "List",Space,Str "in",Space,Str "a",Space,Str "block",Space,Str "quote:"]
- ,OrderedList (1,Decimal,Period)
-  [[Plain [Str "item",Space,Str "one"]]
-  ,[Plain [Str "item",Space,Str "two"]]]
- ,Para [Str "Nested",Space,Str "block",Space,Str "quotes:"]
- ,BlockQuote
-  [Para [Str "nested"]
-  ,BlockQuote
-   [Para [Str "nested"]]]]
-,Header 1 ("code-blocks",[],[]) [Str "Code",Space,Str "Blocks"]
-,Para [Str "Code:"]
-,CodeBlock ("",[],[]) "---- (should be four hyphens)\n\nsub status {\n    print \"working\";\n}"
-,CodeBlock ("",[],[]) "this code block is indented by one tab"
-,Para [Str "And:"]
-,CodeBlock ("",[],[]) "this block is indented by two tabs\n\nThese should not be escaped:  \\$ \\\\ \\> \\[ \\{"
-,Para [Str "And:"]
-,CodeBlock ("",["sourceCode","python"],[]) "def my_function(x):\n    return x + 1"
-,Header 1 ("lists",[],[]) [Str "Lists"]
-,Header 2 ("unordered",[],[]) [Str "Unordered"]
-,Para [Str "Asterisks",Space,Str "tight:"]
-,BulletList
- [[Plain [Str "asterisk",Space,Str "1"]]
- ,[Plain [Str "asterisk",Space,Str "2"]]
- ,[Plain [Str "asterisk",Space,Str "3"]]]
-,Para [Str "Asterisks",Space,Str "loose:"]
-,BulletList
- [[Plain [Str "asterisk",Space,Str "1"]]
- ,[Plain [Str "asterisk",Space,Str "2"]]
- ,[Plain [Str "asterisk",Space,Str "3"]]]
-,Para [Str "Pluses",Space,Str "tight:"]
-,BulletList
- [[Plain [Str "Plus",Space,Str "1"]]
- ,[Plain [Str "Plus",Space,Str "2"]]
- ,[Plain [Str "Plus",Space,Str "3"]]]
-,Para [Str "Pluses",Space,Str "loose:"]
-,BulletList
- [[Plain [Str "Plus",Space,Str "1"]]
- ,[Plain [Str "Plus",Space,Str "2"]]
- ,[Plain [Str "Plus",Space,Str "3"]]]
-,Para [Str "Minuses",Space,Str "tight:"]
-,BulletList
- [[Plain [Str "Minus",Space,Str "1"]]
- ,[Plain [Str "Minus",Space,Str "2"]]
- ,[Plain [Str "Minus",Space,Str "3"]]]
-,Para [Str "Minuses",Space,Str "loose:"]
-,BulletList
- [[Plain [Str "Minus",Space,Str "1"]]
- ,[Plain [Str "Minus",Space,Str "2"]]
- ,[Plain [Str "Minus",Space,Str "3"]]]
-,Header 2 ("ordered",[],[]) [Str "Ordered"]
-,Para [Str "Tight:"]
-,OrderedList (1,Decimal,Period)
- [[Plain [Str "First"]]
- ,[Plain [Str "Second"]]
- ,[Plain [Str "Third"]]]
-,Para [Str "and:"]
-,OrderedList (1,Decimal,Period)
- [[Plain [Str "One"]]
- ,[Plain [Str "Two"]]
- ,[Plain [Str "Three"]]]
-,Para [Str "Loose",Space,Str "using",Space,Str "tabs:"]
-,OrderedList (1,Decimal,Period)
- [[Plain [Str "First"]]
- ,[Plain [Str "Second"]]
- ,[Plain [Str "Third"]]]
-,Para [Str "and",Space,Str "using",Space,Str "spaces:"]
-,OrderedList (1,Decimal,Period)
- [[Plain [Str "One"]]
- ,[Plain [Str "Two"]]
- ,[Plain [Str "Three"]]]
-,Para [Str "Multiple",Space,Str "paragraphs:"]
-,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 "Nested:"]
-,BulletList
- [[Plain [Str "Tab"]
-  ,BulletList
-   [[Plain [Str "Tab"]
-    ,BulletList
-     [[Plain [Str "Tab"]]]]]]]
-,Para [Str "Here\8217s",Space,Str "another:"]
-,OrderedList (1,Decimal,Period)
- [[Plain [Str "First"]]
- ,[Para [Str "Second:"]
-  ,BlockQuote
-   [BulletList
-    [[Plain [Str "Fee"]]
-    ,[Plain [Str "Fie"]]
-    ,[Plain [Str "Foe"]]]]]
- ,[Plain [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 "and",Space,Str "now",Space,Str "3"]
-  ,Para [Str "with",Space,Str "a",Space,Str "continuation"]
-  ,OrderedList (4,LowerRoman,Period)
-   [[Plain [Str "sublist",Space,Str "with",Space,Str "roman",Space,Str "numerals,",Space,Str "starting",Space,Str "with",Space,Str "4"]]
-   ,[Plain [Str "more",Space,Str "items"]
-    ,OrderedList (1,UpperAlpha,TwoParens)
-     [[Plain [Str "a",Space,Str "subsublist"]]
-     ,[Plain [Str "a",Space,Str "subsublist"]]]]]]]
-,Para [Str "Nesting:"]
-,OrderedList (1,UpperAlpha,Period)
- [[Plain [Str "Upper",Space,Str "Alpha"]
-  ,OrderedList (1,UpperRoman,Period)
-   [[Plain [Str "Upper",Space,Str "Roman."]
-    ,OrderedList (6,Decimal,TwoParens)
-     [[Plain [Str "Decimal",Space,Str "start",Space,Str "with",Space,Str "6"]
-      ,OrderedList (3,LowerAlpha,OneParen)
-       [[Plain [Str "Lower",Space,Str "alpha",Space,Str "with",Space,Str "paren"]]]]]]]]]
-,Para [Str "Autonumbering:"]
-,OrderedList (1,DefaultStyle,DefaultDelim)
- [[Plain [Str "Autonumber."]]
- ,[Plain [Str "More."]
-  ,OrderedList (1,DefaultStyle,DefaultDelim)
-   [[Plain [Str "Nested."]]]]]
-,Para [Str "Autonumbering",Space,Str "with",Space,Str "explicit",Space,Str "start:"]
-,OrderedList (4,LowerAlpha,TwoParens)
- [[Plain [Str "item",Space,Str "1"]]
- ,[Plain [Str "item",Space,Str "2"]]]
-,Header 2 ("definition",[],[]) [Str "Definition"]
-,DefinitionList
- [([Str "term",Space,Str "1"],
-   [[Para [Str "Definition",Space,Str "1."]]])
- ,([Str "term",Space,Str "2"],
-   [[Para [Str "Definition",Space,Str "2,",Space,Str "paragraph",Space,Str "1."]
-    ,Para [Str "Definition",Space,Str "2,",Space,Str "paragraph",Space,Str "2."]]])
- ,([Str "term",Space,Str "with",Space,Emph [Str "emphasis"]],
-   [[Para [Str "Definition",Space,Str "3."]]])]
-,Header 1 ("field-lists",[],[]) [Str "Field",Space,Str "Lists"]
-,BlockQuote
- [DefinitionList
-  [([Str "address"],
-    [[Para [Str "61",Space,Str "Main",Space,Str "St."]]])
-  ,([Str "city"],
-    [[Para [Emph [Str "Nowhere"],Str ",",Space,Str "MA,",SoftBreak,Str "USA"]]])
-  ,([Str "phone"],
-    [[Para [Str "123-4567"]]])]]
-,DefinitionList
- [([Str "address"],
-   [[Para [Str "61",Space,Str "Main",Space,Str "St."]]])
- ,([Str "city"],
-   [[Para [Emph [Str "Nowhere"],Str ",",Space,Str "MA,",SoftBreak,Str "USA"]]])
- ,([Str "phone"],
-   [[Para [Str "123-4567"]]])]
-,Header 1 ("html-blocks",[],[]) [Str "HTML",Space,Str "Blocks"]
-,Para [Str "Simple",Space,Str "block",Space,Str "on",Space,Str "one",Space,Str "line:"]
-,RawBlock (Format "html") "<div>foo</div>"
-,Para [Str "Now,",Space,Str "nested:"]
-,RawBlock (Format "html") "<div>\n    <div>\n        <div>\n            foo\n        </div>\n    </div>\n</div>"
-,Header 1 ("latex-block",[],[]) [Str "LaTeX",Space,Str "Block"]
-,RawBlock (Format "latex") "\\begin{tabular}{|l|l|}\\hline\nAnimal & Number \\\\ \\hline\nDog    & 2      \\\\\nCat    & 1      \\\\ \\hline\n\\end{tabular}"
-,Header 1 ("inline-markup",[],[]) [Str "Inline",Space,Str "Markup"]
-,Para [Str "This",Space,Str "is",Space,Emph [Str "emphasized"],Str ".",Space,Str "This",Space,Str "is",Space,Strong [Str "strong"],Str "."]
-,Para [Str "This",Space,Str "is",Space,Str "code:",Space,Code ("",[],[]) ">",Str ",",Space,Code ("",[],[]) "$",Str ",",Space,Code ("",[],[]) "\\",Str ",",Space,Code ("",[],[]) "\\$",Str ",",Space,Code ("",[],[]) "<html>",Str "."]
-,Para [Str "This",Space,Str "is",Subscript [Str "subscripted"],Space,Str "and",Space,Str "this",Space,Str "is",Space,Superscript [Str "superscripted"],Str "."]
-,Header 1 ("special-characters",[],[]) [Str "Special",Space,Str "Characters"]
-,Para [Str "Here",Space,Str "is",Space,Str "some",Space,Str "unicode:"]
-,BulletList
- [[Plain [Str "I",Space,Str "hat:",Space,Str "\206"]]
- ,[Plain [Str "o",Space,Str "umlaut:",Space,Str "\246"]]
- ,[Plain [Str "section:",Space,Str "\167"]]
- ,[Plain [Str "set",Space,Str "membership:",Space,Str "\8712"]]
- ,[Plain [Str "copyright:",Space,Str "\169"]]]
-,Para [Str "AT&T",Space,Str "has",Space,Str "an",Space,Str "ampersand",Space,Str "in",Space,Str "their",Space,Str "name."]
-,Para [Str "This",Space,Str "&",Space,Str "that."]
-,Para [Str "4",Space,Str "<",Space,Str "5."]
-,Para [Str "6",Space,Str ">",Space,Str "5."]
-,Para [Str "Backslash:",Space,Str "\\"]
-,Para [Str "Backtick:",Space,Str "`"]
-,Para [Str "Asterisk:",Space,Str "*"]
-,Para [Str "Underscore:",Space,Str "_"]
-,Para [Str "Left",Space,Str "brace:",Space,Str "{"]
-,Para [Str "Right",Space,Str "brace:",Space,Str "}"]
-,Para [Str "Left",Space,Str "bracket:",Space,Str "["]
-,Para [Str "Right",Space,Str "bracket:",Space,Str "]"]
-,Para [Str "Left",Space,Str "paren:",Space,Str "("]
-,Para [Str "Right",Space,Str "paren:",Space,Str ")"]
-,Para [Str "Greater-than:",Space,Str ">"]
-,Para [Str "Hash:",Space,Str "#"]
-,Para [Str "Period:",Space,Str "."]
-,Para [Str "Bang:",Space,Str "!"]
-,Para [Str "Plus:",Space,Str "+"]
-,Para [Str "Minus:",Space,Str "-"]
-,Header 1 ("links",[],[]) [Str "Links"]
-,Para [Str "Explicit:",Space,Str "a",Space,Link ("",[],[]) [Str "URL"] ("/url/",""),Str "."]
-,Para [Str "Explicit",Space,Str "with",Space,Str "no",Space,Str "label:",Space,Link ("",[],[]) [Str "foo"] ("foo",""),Str "."]
-,Para [Str "Two",Space,Str "anonymous",Space,Str "links:",Space,Link ("",[],[]) [Str "the",Space,Str "first"] ("/url1/",""),Space,Str "and",Space,Link ("",[],[]) [Str "the",Space,Str "second"] ("/url2/","")]
-,Para [Str "Reference",Space,Str "links:",Space,Link ("",[],[]) [Str "link1"] ("/url1/",""),Space,Str "and",Space,Link ("",[],[]) [Str "link2"] ("/url2/",""),Space,Str "and",Space,Link ("",[],[]) [Str "link1"] ("/url1/",""),Space,Str "again."]
-,Para [Str "Another",Space,Link ("",[],[]) [Str "style",Space,Str "of",Space,Str "reference",Space,Str "link"] ("/url1/",""),Str "."]
-,Para [Str "Here\8217s",Space,Str "a",Space,Link ("",[],[]) [Str "link",Space,Str "with",Space,Str "an",Space,Str "ampersand",Space,Str "in",Space,Str "the",Space,Str "URL"] ("http://example.com/?foo=1&bar=2",""),Str "."]
-,Para [Str "Here\8217s",Space,Str "a",Space,Str "link",Space,Str "with",Space,Str "an",Space,Str "amersand",Space,Str "in",Space,Str "the",Space,Str "link",Space,Str "text:",Space,Link ("",[],[]) [Str "AT&T"] ("/url/",""),Str "."]
-,Para [Str "Autolinks:",Space,Link ("",[],[]) [Str "http://example.com/?foo=1&bar=2"] ("http://example.com/?foo=1&bar=2",""),Space,Str "and",Space,Link ("",[],[]) [Str "nobody@nowhere.net"] ("mailto:nobody@nowhere.net",""),Str "."]
-,Para [Str "But",Space,Str "not",Space,Str "here:"]
-,CodeBlock ("",[],[]) "http://example.com/"
-,Header 1 ("images",[],[]) [Str "Images"]
-,Para [Str "From",Space,Quoted DoubleQuote [Str "Voyage",Space,Str "dans",Space,Str "la",Space,Str "Lune"],Space,Str "by",Space,Str "Georges",Space,Str "Melies",Space,Str "(1902):"]
-,Para [Image ("",[],[]) [Str "image"] ("lalune.jpg","")]
-,Para [Image ("",[],[("height","2343px")]) [Str "Voyage dans la Lune"] ("lalune.jpg","")]
-,Para [Str "Here",Space,Str "is",Space,Str "a",Space,Str "movie",Space,Image ("",[],[]) [Str "movie"] ("movie.jpg",""),Space,Str "icon."]
-,Para [Str "And",Space,Str "an",Space,Link ("",[],[]) [Image ("",[],[]) [Str "A movie"] ("movie.jpg","")] ("/url",""),Str "."]
-,Header 1 ("comments",[],[]) [Str "Comments"]
-,Para [Str "First",Space,Str "paragraph"]
-,Para [Str "Another",Space,Str "paragraph"]
-,Para [Str "A",Space,Str "third",Space,Str "paragraph"]
-,Header 1 ("line-blocks",[],[]) [Str "Line",Space,Str "blocks"]
-,LineBlock
- [[Str "But",Space,Str "can",Space,Str "a",Space,Str "bee",Space,Str "be",Space,Str "said",Space,Str "to",Space,Str "be"]
- ,[Str "\160\160\160\160or",Space,Str "not",Space,Str "to",Space,Str "be",Space,Str "an",Space,Str "entire",Space,Str "bee,"]
- ,[Str "\160\160\160\160\160\160\160\160when",Space,Str "half",Space,Str "the",Space,Str "bee",Space,Str "is",Space,Str "not",Space,Str "a",Space,Str "bee,"]
- ,[Str "\160\160\160\160\160\160\160\160\160\160\160\160due",Space,Str "to",Space,Str "some",Space,Str "ancient",Space,Str "injury?"]
- ,[]
- ,[Str "Continuation",Space,Str "line"]
- ,[Str "\160\160and",Space,Str "another"]]
-,Header 1 ("simple-tables",[],[]) [Str "Simple",Space,Str "Tables"]
-,Table [] [AlignDefault,AlignDefault,AlignDefault] [0.0,0.0,0.0]
- [[Plain [Str "col",Space,Str "1"]]
- ,[Plain [Str "col",Space,Str "2"]]
- ,[Plain [Str "col",Space,Str "3"]]]
- [[[Plain [Str "r1",Space,Str "a"]]
-  ,[Plain [Str "b"]]
-  ,[Plain [Str "c"]]]
- ,[[Plain [Str "r2",Space,Str "d"]]
-  ,[Plain [Str "e"]]
-  ,[Plain [Str "f"]]]]
-,Para [Str "Headless"]
-,Table [] [AlignDefault,AlignDefault,AlignDefault] [0.0,0.0,0.0]
- [[]
- ,[]
- ,[]]
- [[[Plain [Str "r1",Space,Str "a"]]
-  ,[Plain [Str "b"]]
-  ,[Plain [Str "c"]]]
- ,[[Plain [Str "r2",Space,Str "d"]]
-  ,[Plain [Str "e"]]
-  ,[Plain [Str "f"]]]]
-,Header 1 ("grid-tables",[],[]) [Str "Grid",Space,Str "Tables"]
-,Table [] [AlignDefault,AlignDefault,AlignDefault] [0.2375,0.15,0.1625]
- [[Plain [Str "col",Space,Str "1"]]
- ,[Plain [Str "col",Space,Str "2"]]
- ,[Plain [Str "col",Space,Str "3"]]]
- [[[Plain [Str "r1",Space,Str "a",SoftBreak,Str "r1",Space,Str "bis"]]
-  ,[Plain [Str "b",SoftBreak,Str "b",Space,Str "2"]]
-  ,[Plain [Str "c",SoftBreak,Str "c",Space,Str "2"]]]
- ,[[Plain [Str "r2",Space,Str "d"]]
-  ,[Plain [Str "e"]]
-  ,[Plain [Str "f"]]]]
-,Para [Str "Headless"]
-,Table [] [AlignDefault,AlignDefault,AlignDefault] [0.2375,0.15,0.1625]
- [[]
- ,[]
- ,[]]
- [[[Plain [Str "r1",Space,Str "a",SoftBreak,Str "r1",Space,Str "bis"]]
-  ,[Plain [Str "b",SoftBreak,Str "b",Space,Str "2"]]
-  ,[Plain [Str "c",SoftBreak,Str "c",Space,Str "2"]]]
- ,[[Plain [Str "r2",Space,Str "d"]]
-  ,[Plain [Str "e"]]
-  ,[Plain [Str "f"]]]]
-,Para [Str "Spaces",Space,Str "at",Space,Str "ends",Space,Str "of",Space,Str "lines"]
-,Table [] [AlignDefault,AlignDefault,AlignDefault] [0.2375,0.15,0.1625]
- [[]
- ,[]
- ,[]]
- [[[Plain [Str "r1",Space,Str "a",SoftBreak,Str "r1",Space,Str "bis"]]
-  ,[Plain [Str "b",SoftBreak,Str "b",Space,Str "2"]]
-  ,[Plain [Str "c",SoftBreak,Str "c",Space,Str "2"]]]
- ,[[Plain [Str "r2",Space,Str "d"]]
-  ,[Plain [Str "e"]]
-  ,[Plain [Str "f"]]]]
-,Para [Str "Multiple",Space,Str "blocks",Space,Str "in",Space,Str "a",Space,Str "cell"]
-,Table [] [AlignDefault,AlignDefault,AlignDefault] [0.2375,0.15,0.1625]
- [[]
- ,[]
- ,[]]
- [[[Para [Str "r1",Space,Str "a"]
-   ,Para [Str "r1",Space,Str "bis"]]
-  ,[BulletList
-    [[Plain [Str "b"]]
-    ,[Plain [Str "b",Space,Str "2"]]
-    ,[Plain [Str "b",Space,Str "2"]]]]
-  ,[Plain [Str "c",SoftBreak,Str "c",Space,Str "2",SoftBreak,Str "c",Space,Str "2"]]]]
-,Header 1 ("footnotes",[],[]) [Str "Footnotes"]
-,Para [Note [Para [Str "Note",Space,Str "with",Space,Str "one",Space,Str "line."]]]
-,Para [Note [Para [Str "Note",Space,Str "with",SoftBreak,Str "continuation",Space,Str "line."]]]
-,Para [Note [Para [Str "Note",Space,Str "with"],Para [Str "continuation",Space,Str "block."]]]
-,Para [Note [Para [Str "Note",Space,Str "with",SoftBreak,Str "continuation",Space,Str "line"],Para [Str "and",Space,Str "a",Space,Str "second",Space,Str "para."]]]
-,Para [Str "Not",Space,Str "in",Space,Str "note."]
-,Header 1 ("math",[],[]) [Str "Math"]
-,Para [Str "Some",Space,Str "inline",Space,Str "math",Space,Math InlineMath "E=mc^2",Str ".",Space,Str "Now",Space,Str "some",SoftBreak,Str "display",Space,Str "math:"]
-,Para [Math DisplayMath "E=mc^2"]
-,Para [Math DisplayMath "E = mc^2"]
-,Para [Math DisplayMath "E = mc^2",Math DisplayMath "\\alpha = \\beta"]
-,Para [Math DisplayMath "E &= mc^2\\\\\nF &= \\pi E",Math DisplayMath "F &= \\gamma \\alpha^2"]
-,Para [Str "All",Space,Str "done."]
-,Header 1 ("default-role",[],[]) [Str "Default-Role"]
-,Para [Str "Try",Space,Str "changing",Space,Str "the",Space,Str "default",Space,Str "role",Space,Str "to",Space,Str "a",Space,Str "few",Space,Str "different",Space,Str "things."]
-,Header 2 ("doesnt-break-title-parsing",[],[]) [Str "Doesn\8217t",Space,Str "Break",Space,Str "Title",Space,Str "Parsing"]
-,Para [Str "Inline",Space,Str "math:",Space,Math InlineMath "E=mc^2",Space,Str "or",Space,Math InlineMath "E=mc^2",Space,Str "or",Space,Math InlineMath "E=mc^2",Str ".",SoftBreak,Str "Other",Space,Str "roles:",Space,Superscript [Str "super"],Str ",",Space,Subscript [Str "sub"],Str "."]
-,Para [Math DisplayMath "\\alpha = beta",Math DisplayMath "E = mc^2"]
-,Para [Str "Some",Space,Superscript [Str "of"],Space,Str "these",Space,Superscript [Str "words"],Space,Str "are",Space,Str "in",Space,Superscript [Str "superscript"],Str "."]
-,Para [Str "Reset",Space,Str "default-role",Space,Str "to",Space,Str "the",Space,Str "default",Space,Str "default."]
-,Para [Str "And",Space,Str "now",Space,Str "some-invalid-string-3231231",Space,Str "is",Space,Str "nonsense."]
-,Para [Str "And",Space,Str "now",Space,Str "with",Space,RawInline (Format "html") "<b>inline</b> <span id=\"test\">HTML</span>",Str "."]
-,Para [Str "And",Space,Str "some",Space,Str "inline",Space,Str "haskell",Space,Code ("",["haskell","sourceCode"],[]) "fmap id [1,2..10]",Str "."]
-,Para [Str "Indirect",Space,Str "python",Space,Str "role",Space,Code ("",["py","python","indirect","sourceCode"],[]) "[x*x for x in [1,2,3,4,5]]",Str "."]
-,Para [Str "Different",Space,Str "indirect",Space,Str "C",Space,Code ("",["c","different-indirect","sourceCode"],[]) "int x = 15;",Str "."]
-,Header 2 ("literal-symbols",[],[]) [Str "Literal",Space,Str "symbols"]
-,Para [Str "2*2",Space,Str "=",Space,Str "4*1"]]
+Pandoc
+  Meta
+    { unMeta =
+        fromList
+          [ ( "author"
+            , MetaList
+                [ MetaInlines [ Str "John" , Space , Str "MacFarlane" ]
+                , MetaInlines [ Str "Anonymous" ]
+                ]
+            )
+          , ( "date"
+            , MetaInlines
+                [ Str "July" , Space , Str "17," , Space , Str "2006" ]
+            )
+          , ( "revision" , MetaInlines [ Str "3" ] )
+          , ( "subtitle" , MetaInlines [ Str "Subtitle" ] )
+          , ( "title"
+            , MetaInlines
+                [ Str "Pandoc" , Space , Str "Test" , Space , Str "Suite" ]
+            )
+          ]
+    }
+  [ Header
+      1
+      ( "level-one-header" , [] , [] )
+      [ Str "Level" , Space , Str "one" , Space , Str "header" ]
+  , Para
+      [ Str "This"
+      , Space
+      , Str "is"
+      , Space
+      , Str "a"
+      , Space
+      , Str "set"
+      , Space
+      , Str "of"
+      , Space
+      , Str "tests"
+      , Space
+      , Str "for"
+      , Space
+      , Str "pandoc."
+      , Space
+      , Str "Most"
+      , Space
+      , Str "of"
+      , Space
+      , Str "them"
+      , Space
+      , Str "are"
+      , Space
+      , Str "adapted"
+      , Space
+      , Str "from"
+      , SoftBreak
+      , Str "John"
+      , Space
+      , Str "Gruber\8217s"
+      , Space
+      , Str "markdown"
+      , Space
+      , Str "test"
+      , Space
+      , Str "suite."
+      ]
+  , Header
+      2
+      ( "level-two-header" , [] , [] )
+      [ Str "Level" , Space , Str "two" , Space , Str "header" ]
+  , Header
+      3 ( "level-three" , [] , [] ) [ Str "Level" , Space , Str "three" ]
+  , Header
+      4
+      ( "level-four-with-emphasis" , [] , [] )
+      [ Str "Level"
+      , Space
+      , Str "four"
+      , Space
+      , Str "with"
+      , Space
+      , Emph [ Str "emphasis" ]
+      ]
+  , Header
+      5 ( "level-five" , [] , [] ) [ Str "Level" , Space , Str "five" ]
+  , Header 1 ( "paragraphs" , [] , [] ) [ Str "Paragraphs" ]
+  , Para
+      [ Str "Here\8217s"
+      , Space
+      , Str "a"
+      , Space
+      , Str "regular"
+      , Space
+      , Str "paragraph."
+      ]
+  , Para
+      [ Str "In"
+      , Space
+      , Str "Markdown"
+      , Space
+      , Str "1.0.0"
+      , Space
+      , Str "and"
+      , Space
+      , Str "earlier."
+      , Space
+      , Str "Version"
+      , SoftBreak
+      , Str "8."
+      , Space
+      , Str "This"
+      , Space
+      , Str "line"
+      , Space
+      , Str "turns"
+      , Space
+      , Str "into"
+      , Space
+      , Str "a"
+      , Space
+      , Str "list"
+      , Space
+      , Str "item."
+      , SoftBreak
+      , Str "Because"
+      , Space
+      , Str "a"
+      , Space
+      , Str "hard-wrapped"
+      , Space
+      , Str "line"
+      , Space
+      , Str "in"
+      , Space
+      , Str "the"
+      , SoftBreak
+      , Str "middle"
+      , Space
+      , Str "of"
+      , Space
+      , Str "a"
+      , Space
+      , Str "paragraph"
+      , Space
+      , Str "looked"
+      , Space
+      , Str "like"
+      , Space
+      , Str "a"
+      , SoftBreak
+      , Str "list"
+      , Space
+      , Str "item."
+      ]
+  , Para
+      [ Str "Here\8217s"
+      , Space
+      , Str "one"
+      , Space
+      , Str "with"
+      , Space
+      , Str "a"
+      , Space
+      , Str "bullet."
+      , SoftBreak
+      , Str "*"
+      , Space
+      , Str "criminey."
+      ]
+  , Para [ Str "Horizontal" , Space , Str "rule:" ]
+  , HorizontalRule
+  , Para [ Str "Another:" ]
+  , HorizontalRule
+  , Header
+      1
+      ( "block-quotes" , [] , [] )
+      [ Str "Block" , Space , Str "Quotes" ]
+  , Para
+      [ Str "Here\8217s"
+      , Space
+      , Str "a"
+      , Space
+      , Str "block"
+      , Space
+      , Str "quote:"
+      ]
+  , BlockQuote
+      [ Para
+          [ Str "This"
+          , Space
+          , Str "is"
+          , Space
+          , Str "a"
+          , Space
+          , Str "block"
+          , Space
+          , Str "quote."
+          , SoftBreak
+          , Str "It"
+          , Space
+          , Str "is"
+          , Space
+          , Str "pretty"
+          , Space
+          , Str "short."
+          ]
+      ]
+  , Para
+      [ Str "Here\8217s"
+      , Space
+      , Str "another,"
+      , Space
+      , Str "differently"
+      , Space
+      , Str "indented:"
+      ]
+  , BlockQuote
+      [ Para
+          [ Str "This"
+          , Space
+          , Str "is"
+          , Space
+          , Str "a"
+          , Space
+          , Str "block"
+          , Space
+          , Str "quote."
+          , SoftBreak
+          , Str "It\8217s"
+          , Space
+          , Str "indented"
+          , Space
+          , Str "with"
+          , Space
+          , Str "a"
+          , Space
+          , Str "tab."
+          ]
+      , Para
+          [ Str "Code"
+          , Space
+          , Str "in"
+          , Space
+          , Str "a"
+          , Space
+          , Str "block"
+          , Space
+          , Str "quote:"
+          ]
+      , CodeBlock
+          ( "" , [] , [] ) "sub status {\n    print \"working\";\n}"
+      , Para
+          [ Str "List"
+          , Space
+          , Str "in"
+          , Space
+          , Str "a"
+          , Space
+          , Str "block"
+          , Space
+          , Str "quote:"
+          ]
+      , OrderedList
+          ( 1 , Decimal , Period )
+          [ [ Plain [ Str "item" , Space , Str "one" ] ]
+          , [ Plain [ Str "item" , Space , Str "two" ] ]
+          ]
+      , Para
+          [ Str "Nested" , Space , Str "block" , Space , Str "quotes:" ]
+      , BlockQuote
+          [ Para [ Str "nested" ] , BlockQuote [ Para [ Str "nested" ] ] ]
+      ]
+  , Header
+      1 ( "code-blocks" , [] , [] ) [ Str "Code" , Space , Str "Blocks" ]
+  , Para [ Str "Code:" ]
+  , CodeBlock
+      ( "" , [] , [] )
+      "---- (should be four hyphens)\n\nsub status {\n    print \"working\";\n}"
+  , CodeBlock
+      ( "" , [] , [] ) "this code block is indented by one tab"
+  , Para [ Str "And:" ]
+  , CodeBlock
+      ( "" , [] , [] )
+      "this block is indented by two tabs\n\nThese should not be escaped:  \\$ \\\\ \\> \\[ \\{"
+  , Para [ Str "And:" ]
+  , CodeBlock
+      ( "" , [ "python" ] , [] ) "def my_function(x):\n    return x + 1"
+  , Para
+      [ Str "If"
+      , Space
+      , Str "we"
+      , Space
+      , Str "use"
+      , Space
+      , Str "the"
+      , Space
+      , Str "highlight"
+      , Space
+      , Str "directive,"
+      , Space
+      , Str "we"
+      , Space
+      , Str "can"
+      , Space
+      , Str "specify"
+      , Space
+      , Str "a"
+      , Space
+      , Str "default"
+      , Space
+      , Str "language"
+      , SoftBreak
+      , Str "for"
+      , Space
+      , Str "literate"
+      , Space
+      , Str "blocks."
+      ]
+  , CodeBlock
+      ( "" , [ "haskell" ] , [] )
+      "-- this code is in haskell\ndata Tree = Leaf | Node Tree Tree"
+  , CodeBlock
+      ( "" , [ "haskell" ] , [] )
+      "-- this code is in haskell too\ndata Nat = Zero | Succ Nat"
+  , CodeBlock
+      ( "" , [ "javascript" ] , [] )
+      "-- this code is in javascript\nlet f = (x, y) => x + y"
+  , Header 1 ( "lists" , [] , [] ) [ Str "Lists" ]
+  , Header 2 ( "unordered" , [] , [] ) [ Str "Unordered" ]
+  , Para [ Str "Asterisks" , Space , Str "tight:" ]
+  , BulletList
+      [ [ Plain [ Str "asterisk" , Space , Str "1" ] ]
+      , [ Plain [ Str "asterisk" , Space , Str "2" ] ]
+      , [ Plain [ Str "asterisk" , Space , Str "3" ] ]
+      ]
+  , Para [ Str "Asterisks" , Space , Str "loose:" ]
+  , BulletList
+      [ [ Plain [ Str "asterisk" , Space , Str "1" ] ]
+      , [ Plain [ Str "asterisk" , Space , Str "2" ] ]
+      , [ Plain [ Str "asterisk" , Space , Str "3" ] ]
+      ]
+  , Para [ Str "Pluses" , Space , Str "tight:" ]
+  , BulletList
+      [ [ Plain [ Str "Plus" , Space , Str "1" ] ]
+      , [ Plain [ Str "Plus" , Space , Str "2" ] ]
+      , [ Plain [ Str "Plus" , Space , Str "3" ] ]
+      ]
+  , Para [ Str "Pluses" , Space , Str "loose:" ]
+  , BulletList
+      [ [ Plain [ Str "Plus" , Space , Str "1" ] ]
+      , [ Plain [ Str "Plus" , Space , Str "2" ] ]
+      , [ Plain [ Str "Plus" , Space , Str "3" ] ]
+      ]
+  , Para [ Str "Minuses" , Space , Str "tight:" ]
+  , BulletList
+      [ [ Plain [ Str "Minus" , Space , Str "1" ] ]
+      , [ Plain [ Str "Minus" , Space , Str "2" ] ]
+      , [ Plain [ Str "Minus" , Space , Str "3" ] ]
+      ]
+  , Para [ Str "Minuses" , Space , Str "loose:" ]
+  , BulletList
+      [ [ Plain [ Str "Minus" , Space , Str "1" ] ]
+      , [ Plain [ Str "Minus" , Space , Str "2" ] ]
+      , [ Plain [ Str "Minus" , Space , Str "3" ] ]
+      ]
+  , Header 2 ( "ordered" , [] , [] ) [ Str "Ordered" ]
+  , Para [ Str "Tight:" ]
+  , OrderedList
+      ( 1 , Decimal , Period )
+      [ [ Plain [ Str "First" ] ]
+      , [ Plain [ Str "Second" ] ]
+      , [ Plain [ Str "Third" ] ]
+      ]
+  , Para [ Str "and:" ]
+  , OrderedList
+      ( 1 , Decimal , Period )
+      [ [ Plain [ Str "One" ] ]
+      , [ Plain [ Str "Two" ] ]
+      , [ Plain [ Str "Three" ] ]
+      ]
+  , Para [ Str "Loose" , Space , Str "using" , Space , Str "tabs:" ]
+  , OrderedList
+      ( 1 , Decimal , Period )
+      [ [ Plain [ Str "First" ] ]
+      , [ Plain [ Str "Second" ] ]
+      , [ Plain [ Str "Third" ] ]
+      ]
+  , Para [ Str "and" , Space , Str "using" , Space , Str "spaces:" ]
+  , OrderedList
+      ( 1 , Decimal , Period )
+      [ [ Plain [ Str "One" ] ]
+      , [ Plain [ Str "Two" ] ]
+      , [ Plain [ Str "Three" ] ]
+      ]
+  , Para [ Str "Multiple" , Space , Str "paragraphs:" ]
+  , 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."
+            ]
+        ]
+      , [ Para [ Str "Item" , Space , Str "2." ] ]
+      , [ Para [ Str "Item" , Space , Str "3." ] ]
+      ]
+  , Para [ Str "Nested:" ]
+  , BulletList
+      [ [ Plain [ Str "Tab" ]
+        , BulletList
+            [ [ Plain [ Str "Tab" ] , BulletList [ [ Plain [ Str "Tab" ] ] ] ]
+            ]
+        ]
+      ]
+  , Para [ Str "Here\8217s" , Space , Str "another:" ]
+  , OrderedList
+      ( 1 , Decimal , Period )
+      [ [ Para [ Str "First" ] ]
+      , [ Para [ Str "Second:" ]
+        , BlockQuote
+            [ BulletList
+                [ [ Plain [ Str "Fee" ] ]
+                , [ Plain [ Str "Fie" ] ]
+                , [ Plain [ Str "Foe" ] ]
+                ]
+            ]
+        ]
+      , [ Para [ Str "Third" ] ]
+      ]
+  , Header
+      2
+      ( "fancy-list-markers" , [] , [] )
+      [ Str "Fancy" , Space , Str "list" , Space , Str "markers" ]
+  , OrderedList
+      ( 2 , Decimal , TwoParens )
+      [ [ 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 )
+            [ [ Plain
+                  [ Str "sublist"
+                  , Space
+                  , Str "with"
+                  , Space
+                  , Str "roman"
+                  , Space
+                  , Str "numerals,"
+                  , Space
+                  , Str "starting"
+                  , Space
+                  , Str "with"
+                  , Space
+                  , Str "4"
+                  ]
+              ]
+            , [ Plain [ Str "more" , Space , Str "items" ]
+              , OrderedList
+                  ( 1 , UpperAlpha , TwoParens )
+                  [ [ Plain [ Str "a" , Space , Str "subsublist" ] ]
+                  , [ Plain [ Str "a" , Space , Str "subsublist" ] ]
+                  ]
+              ]
+            ]
+        ]
+      ]
+  , Para [ Str "Nesting:" ]
+  , OrderedList
+      ( 1 , UpperAlpha , Period )
+      [ [ Plain [ Str "Upper" , Space , Str "Alpha" ]
+        , OrderedList
+            ( 1 , UpperRoman , Period )
+            [ [ Plain [ Str "Upper" , Space , Str "Roman." ]
+              , OrderedList
+                  ( 6 , Decimal , TwoParens )
+                  [ [ Plain
+                        [ Str "Decimal"
+                        , Space
+                        , Str "start"
+                        , Space
+                        , Str "with"
+                        , Space
+                        , Str "6"
+                        ]
+                    , OrderedList
+                        ( 3 , LowerAlpha , OneParen )
+                        [ [ Plain
+                              [ Str "Lower"
+                              , Space
+                              , Str "alpha"
+                              , Space
+                              , Str "with"
+                              , Space
+                              , Str "paren"
+                              ]
+                          ]
+                        ]
+                    ]
+                  ]
+              ]
+            ]
+        ]
+      ]
+  , Para [ Str "Autonumbering:" ]
+  , OrderedList
+      ( 1 , DefaultStyle , DefaultDelim )
+      [ [ Plain [ Str "Autonumber." ] ]
+      , [ Plain [ Str "More." ]
+        , OrderedList
+            ( 1 , DefaultStyle , DefaultDelim ) [ [ Plain [ Str "Nested." ] ] ]
+        ]
+      ]
+  , Para
+      [ Str "Autonumbering"
+      , Space
+      , Str "with"
+      , Space
+      , Str "explicit"
+      , Space
+      , Str "start:"
+      ]
+  , OrderedList
+      ( 4 , LowerAlpha , TwoParens )
+      [ [ Plain [ Str "item" , Space , Str "1" ] ]
+      , [ Plain [ Str "item" , Space , Str "2" ] ]
+      ]
+  , Header 2 ( "definition" , [] , [] ) [ Str "Definition" ]
+  , DefinitionList
+      [ ( [ Str "term" , Space , Str "1" ]
+        , [ [ Para [ Str "Definition" , Space , Str "1." ] ] ]
+        )
+      , ( [ Str "term" , Space , Str "2" ]
+        , [ [ Para
+                [ Str "Definition"
+                , Space
+                , Str "2,"
+                , Space
+                , Str "paragraph"
+                , Space
+                , Str "1."
+                ]
+            , Para
+                [ Str "Definition"
+                , Space
+                , Str "2,"
+                , Space
+                , Str "paragraph"
+                , Space
+                , Str "2."
+                ]
+            ]
+          ]
+        )
+      , ( [ Str "term"
+          , Space
+          , Str "with"
+          , Space
+          , Emph [ Str "emphasis" ]
+          ]
+        , [ [ Para [ Str "Definition" , Space , Str "3." ] ] ]
+        )
+      ]
+  , Header
+      1 ( "field-lists" , [] , [] ) [ Str "Field" , Space , Str "Lists" ]
+  , BlockQuote
+      [ DefinitionList
+          [ ( [ Str "address" ]
+            , [ [ Plain [ Str "61" , Space , Str "Main" , Space , Str "St." ] ]
+              ]
+            )
+          , ( [ Str "city" ]
+            , [ [ Plain
+                    [ Emph [ Str "Nowhere" ]
+                    , Str ","
+                    , Space
+                    , Str "MA,"
+                    , SoftBreak
+                    , Str "USA"
+                    ]
+                ]
+              ]
+            )
+          , ( [ Str "phone" ] , [ [ Plain [ Str "123-4567" ] ] ] )
+          ]
+      ]
+  , DefinitionList
+      [ ( [ Str "address" ]
+        , [ [ Plain [ Str "61" , Space , Str "Main" , Space , Str "St." ] ]
+          ]
+        )
+      , ( [ Str "city" ]
+        , [ [ Plain
+                [ Emph [ Str "Nowhere" ]
+                , Str ","
+                , Space
+                , Str "MA,"
+                , SoftBreak
+                , Str "USA"
+                ]
+            ]
+          ]
+        )
+      , ( [ Str "phone" ] , [ [ Plain [ Str "123-4567" ] ] ] )
+      ]
+  , Header
+      1 ( "html-blocks" , [] , [] ) [ Str "HTML" , Space , Str "Blocks" ]
+  , Para
+      [ Str "Simple"
+      , Space
+      , Str "block"
+      , Space
+      , Str "on"
+      , Space
+      , Str "one"
+      , Space
+      , Str "line:"
+      ]
+  , RawBlock (Format "html") "<div>foo</div>"
+  , Para [ Str "Now," , Space , Str "nested:" ]
+  , RawBlock
+      (Format "html")
+      "<div>\n    <div>\n        <div>\n            foo\n        </div>\n    </div>\n</div>"
+  , Header
+      1 ( "latex-block" , [] , [] ) [ Str "LaTeX" , Space , Str "Block" ]
+  , RawBlock
+      (Format "latex")
+      "\\begin{tabular}{|l|l|}\\hline\nAnimal & Number \\\\ \\hline\nDog    & 2      \\\\\nCat    & 1      \\\\ \\hline\n\\end{tabular}"
+  , Header
+      1
+      ( "inline-markup" , [] , [] )
+      [ Str "Inline" , Space , Str "Markup" ]
+  , Para
+      [ Str "This"
+      , Space
+      , Str "is"
+      , Space
+      , Emph [ Str "emphasized" ]
+      , Str "."
+      , Space
+      , Str "This"
+      , Space
+      , Str "is"
+      , Space
+      , Strong [ Str "strong" ]
+      , Str "."
+      ]
+  , Para
+      [ Str "This"
+      , Space
+      , Str "is"
+      , Space
+      , Str "code:"
+      , Space
+      , Code ( "" , [] , [] ) ">"
+      , Str ","
+      , Space
+      , Code ( "" , [] , [] ) "$"
+      , Str ","
+      , Space
+      , Code ( "" , [] , [] ) "\\"
+      , Str ","
+      , Space
+      , Code ( "" , [] , [] ) "\\$"
+      , Str ","
+      , Space
+      , Code ( "" , [] , [] ) "<html>"
+      , Str "."
+      ]
+  , Para
+      [ Str "This"
+      , Space
+      , Str "is"
+      , Subscript [ Str "subscripted" ]
+      , Space
+      , Str "and"
+      , Space
+      , Str "this"
+      , Space
+      , Str "is"
+      , Space
+      , Superscript [ Str "superscripted" ]
+      , Str "."
+      ]
+  , Header
+      1
+      ( "special-characters" , [] , [] )
+      [ Str "Special" , Space , Str "Characters" ]
+  , Para
+      [ Str "Here"
+      , Space
+      , Str "is"
+      , Space
+      , Str "some"
+      , Space
+      , Str "unicode:"
+      ]
+  , BulletList
+      [ [ Plain [ Str "I" , Space , Str "hat:" , Space , Str "\206" ] ]
+      , [ Plain [ Str "o" , Space , Str "umlaut:" , Space , Str "\246" ]
+        ]
+      , [ Plain [ Str "section:" , Space , Str "\167" ] ]
+      , [ Plain
+            [ Str "set" , Space , Str "membership:" , Space , Str "\8712" ]
+        ]
+      , [ Plain [ Str "copyright:" , Space , Str "\169" ] ]
+      ]
+  , Para
+      [ Str "AT&T"
+      , Space
+      , Str "has"
+      , Space
+      , Str "an"
+      , Space
+      , Str "ampersand"
+      , Space
+      , Str "in"
+      , Space
+      , Str "their"
+      , Space
+      , Str "name."
+      ]
+  , Para [ Str "This" , Space , Str "&" , Space , Str "that." ]
+  , Para [ Str "4" , Space , Str "<" , Space , Str "5." ]
+  , Para [ Str "6" , Space , Str ">" , Space , Str "5." ]
+  , Para [ Str "Backslash:" , Space , Str "\\" ]
+  , Para [ Str "Backtick:" , Space , Str "`" ]
+  , Para [ Str "Asterisk:" , Space , Str "*" ]
+  , Para [ Str "Underscore:" , Space , Str "_" ]
+  , Para [ Str "Left" , Space , Str "brace:" , Space , Str "{" ]
+  , Para [ Str "Right" , Space , Str "brace:" , Space , Str "}" ]
+  , Para [ Str "Left" , Space , Str "bracket:" , Space , Str "[" ]
+  , Para [ Str "Right" , Space , Str "bracket:" , Space , Str "]" ]
+  , Para [ Str "Left" , Space , Str "paren:" , Space , Str "(" ]
+  , Para [ Str "Right" , Space , Str "paren:" , Space , Str ")" ]
+  , Para [ Str "Greater-than:" , Space , Str ">" ]
+  , Para [ Str "Hash:" , Space , Str "#" ]
+  , Para [ Str "Period:" , Space , Str "." ]
+  , Para [ Str "Bang:" , Space , Str "!" ]
+  , Para [ Str "Plus:" , Space , Str "+" ]
+  , Para [ Str "Minus:" , Space , Str "-" ]
+  , Header 1 ( "links" , [] , [] ) [ Str "Links" ]
+  , Para
+      [ Str "Explicit:"
+      , Space
+      , Str "a"
+      , Space
+      , Link ( "" , [] , [] ) [ Str "URL" ] ( "/url/" , "" )
+      , Str "."
+      ]
+  , Para
+      [ Str "Explicit"
+      , Space
+      , Str "with"
+      , Space
+      , Str "no"
+      , Space
+      , Str "label:"
+      , Space
+      , Link ( "" , [] , [] ) [ Str "foo" ] ( "foo" , "" )
+      , Str "."
+      ]
+  , Para
+      [ Str "Two"
+      , Space
+      , Str "anonymous"
+      , Space
+      , Str "links:"
+      , Space
+      , Link
+          ( "" , [] , [] )
+          [ Str "the" , Space , Str "first" ]
+          ( "/url1/" , "" )
+      , Space
+      , Str "and"
+      , Space
+      , Link
+          ( "" , [] , [] )
+          [ Str "the" , Space , Str "second" ]
+          ( "/url2/" , "" )
+      ]
+  , Para
+      [ Str "Reference"
+      , Space
+      , Str "links:"
+      , Space
+      , Link ( "" , [] , [] ) [ Str "link1" ] ( "/url1/" , "" )
+      , Space
+      , Str "and"
+      , Space
+      , Link ( "" , [] , [] ) [ Str "link2" ] ( "/url2/" , "" )
+      , Space
+      , Str "and"
+      , Space
+      , Link ( "" , [] , [] ) [ Str "link1" ] ( "/url1/" , "" )
+      , Space
+      , Str "again."
+      ]
+  , Para
+      [ Str "Another"
+      , Space
+      , Link
+          ( "" , [] , [] )
+          [ Str "style"
+          , Space
+          , Str "of"
+          , Space
+          , Str "reference"
+          , Space
+          , Str "link"
+          ]
+          ( "/url1/" , "" )
+      , Str "."
+      ]
+  , Para
+      [ Str "Here\8217s"
+      , Space
+      , Str "a"
+      , Space
+      , Link
+          ( "" , [] , [] )
+          [ Str "link"
+          , Space
+          , Str "with"
+          , Space
+          , Str "an"
+          , Space
+          , Str "ampersand"
+          , Space
+          , Str "in"
+          , Space
+          , Str "the"
+          , Space
+          , Str "URL"
+          ]
+          ( "http://example.com/?foo=1&bar=2" , "" )
+      , Str "."
+      ]
+  , Para
+      [ Str "Here\8217s"
+      , Space
+      , Str "a"
+      , Space
+      , Str "link"
+      , Space
+      , Str "with"
+      , Space
+      , Str "an"
+      , Space
+      , Str "amersand"
+      , Space
+      , Str "in"
+      , Space
+      , Str "the"
+      , Space
+      , Str "link"
+      , Space
+      , Str "text:"
+      , Space
+      , Link ( "" , [] , [] ) [ Str "AT&T" ] ( "/url/" , "" )
+      , Str "."
+      ]
+  , Para
+      [ Str "Autolinks:"
+      , Space
+      , Link
+          ( "" , [] , [] )
+          [ Str "http://example.com/?foo=1&bar=2" ]
+          ( "http://example.com/?foo=1&bar=2" , "" )
+      , Space
+      , Str "and"
+      , Space
+      , Link
+          ( "" , [] , [] )
+          [ Str "nobody@nowhere.net" ]
+          ( "mailto:nobody@nowhere.net" , "" )
+      , Str "."
+      ]
+  , Para [ Str "But" , Space , Str "not" , Space , Str "here:" ]
+  , CodeBlock ( "" , [] , [] ) "http://example.com/"
+  , Header 1 ( "images" , [] , [] ) [ Str "Images" ]
+  , Para
+      [ Str "From"
+      , Space
+      , Quoted
+          DoubleQuote
+          [ Str "Voyage"
+          , Space
+          , Str "dans"
+          , Space
+          , Str "la"
+          , Space
+          , Str "Lune"
+          ]
+      , Space
+      , Str "by"
+      , Space
+      , Str "Georges"
+      , Space
+      , Str "Melies"
+      , Space
+      , Str "(1902):"
+      ]
+  , Para
+      [ Image ( "" , [] , [] ) [ Str "image" ] ( "lalune.jpg" , "" ) ]
+  , Para
+      [ Image
+          ( "" , [] , [ ( "height" , "2343px" ) ] )
+          [ Str "Voyage dans la Lune" ]
+          ( "lalune.jpg" , "" )
+      ]
+  , Para
+      [ Str "Here"
+      , Space
+      , Str "is"
+      , Space
+      , Str "a"
+      , Space
+      , Str "movie"
+      , Space
+      , Image ( "" , [] , [] ) [ Str "movie" ] ( "movie.jpg" , "" )
+      , Space
+      , Str "icon."
+      ]
+  , Para
+      [ Str "And"
+      , Space
+      , Str "an"
+      , Space
+      , Link
+          ( "" , [] , [] )
+          [ Image ( "" , [] , [] ) [ Str "A movie" ] ( "movie.jpg" , "" ) ]
+          ( "/url" , "" )
+      , Str "."
+      ]
+  , Header 1 ( "comments" , [] , [] ) [ Str "Comments" ]
+  , Para [ Str "First" , Space , Str "paragraph" ]
+  , Para [ Str "Another" , Space , Str "paragraph" ]
+  , Para [ Str "A" , Space , Str "third" , Space , Str "paragraph" ]
+  , Header
+      1 ( "line-blocks" , [] , [] ) [ Str "Line" , Space , Str "blocks" ]
+  , LineBlock
+      [ [ Str "But"
+        , Space
+        , Str "can"
+        , Space
+        , Str "a"
+        , Space
+        , Str "bee"
+        , Space
+        , Str "be"
+        , Space
+        , Str "said"
+        , Space
+        , Str "to"
+        , Space
+        , Str "be"
+        ]
+      , [ Str "\160\160\160\160or"
+        , Space
+        , Str "not"
+        , Space
+        , Str "to"
+        , Space
+        , Str "be"
+        , Space
+        , Str "an"
+        , Space
+        , Str "entire"
+        , Space
+        , Str "bee,"
+        ]
+      , [ Str "\160\160\160\160\160\160\160\160when"
+        , Space
+        , Str "half"
+        , Space
+        , Str "the"
+        , Space
+        , Str "bee"
+        , Space
+        , Str "is"
+        , Space
+        , Str "not"
+        , Space
+        , Str "a"
+        , Space
+        , Str "bee,"
+        ]
+      , [ Str "\160\160\160\160\160\160\160\160\160\160\160\160due"
+        , Space
+        , Str "to"
+        , Space
+        , Str "some"
+        , Space
+        , Str "ancient"
+        , Space
+        , Str "injury?"
+        ]
+      , []
+      , [ Str "Continuation" , Space , Str "line" ]
+      , [ Str "\160\160and" , Space , Str "another" ]
+      ]
+  , Header
+      1
+      ( "simple-tables" , [] , [] )
+      [ Str "Simple" , Space , Str "Tables" ]
+  , Table
+      ( "" , [] , [] )
+      (Caption Nothing [])
+      [ ( AlignDefault , ColWidthDefault )
+      , ( AlignDefault , ColWidthDefault )
+      , ( AlignDefault , ColWidthDefault )
+      ]
+      (TableHead
+         ( "" , [] , [] )
+         [ Row
+             ( "" , [] , [] )
+             [ Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "col" , Space , Str "1" ] ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "col" , Space , Str "2" ] ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "col" , Space , Str "3" ] ]
+             ]
+         ])
+      [ TableBody
+          ( "" , [] , [] )
+          (RowHeadColumns 0)
+          []
+          [ Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "r1" , Space , Str "a" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "b" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "c" ] ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "r2" , Space , Str "d" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "e" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "f" ] ]
+              ]
+          ]
+      ]
+      (TableFoot ( "" , [] , [] ) [])
+  , Para [ Str "Headless" ]
+  , Table
+      ( "" , [] , [] )
+      (Caption Nothing [])
+      [ ( AlignDefault , ColWidthDefault )
+      , ( AlignDefault , ColWidthDefault )
+      , ( AlignDefault , ColWidthDefault )
+      ]
+      (TableHead ( "" , [] , [] ) [])
+      [ TableBody
+          ( "" , [] , [] )
+          (RowHeadColumns 0)
+          []
+          [ Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "r1" , Space , Str "a" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "b" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "c" ] ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "r2" , Space , Str "d" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "e" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "f" ] ]
+              ]
+          ]
+      ]
+      (TableFoot ( "" , [] , [] ) [])
+  , Header
+      1 ( "grid-tables" , [] , [] ) [ Str "Grid" , Space , Str "Tables" ]
+  , Table
+      ( "" , [] , [] )
+      (Caption Nothing [])
+      [ ( AlignDefault , ColWidth 0.2375 )
+      , ( AlignDefault , ColWidth 0.15 )
+      , ( AlignDefault , ColWidth 0.1625 )
+      ]
+      (TableHead
+         ( "" , [] , [] )
+         [ Row
+             ( "" , [] , [] )
+             [ Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "col" , Space , Str "1" ] ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "col" , Space , Str "2" ] ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "col" , Space , Str "3" ] ]
+             ]
+         ])
+      [ TableBody
+          ( "" , [] , [] )
+          (RowHeadColumns 0)
+          []
+          [ Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain
+                      [ Str "r1"
+                      , Space
+                      , Str "a"
+                      , SoftBreak
+                      , Str "r1"
+                      , Space
+                      , Str "bis"
+                      ]
+                  ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "b" , SoftBreak , Str "b" , Space , Str "2" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "c" , SoftBreak , Str "c" , Space , Str "2" ] ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "r2" , Space , Str "d" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "e" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "f" ] ]
+              ]
+          ]
+      ]
+      (TableFoot ( "" , [] , [] ) [])
+  , Para [ Str "Headless" ]
+  , Table
+      ( "" , [] , [] )
+      (Caption Nothing [])
+      [ ( AlignDefault , ColWidth 0.2375 )
+      , ( AlignDefault , ColWidth 0.15 )
+      , ( AlignDefault , ColWidth 0.1625 )
+      ]
+      (TableHead ( "" , [] , [] ) [])
+      [ TableBody
+          ( "" , [] , [] )
+          (RowHeadColumns 0)
+          []
+          [ Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain
+                      [ Str "r1"
+                      , Space
+                      , Str "a"
+                      , SoftBreak
+                      , Str "r1"
+                      , Space
+                      , Str "bis"
+                      ]
+                  ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "b" , SoftBreak , Str "b" , Space , Str "2" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "c" , SoftBreak , Str "c" , Space , Str "2" ] ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "r2" , Space , Str "d" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "e" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "f" ] ]
+              ]
+          ]
+      ]
+      (TableFoot ( "" , [] , [] ) [])
+  , Para
+      [ Str "Spaces"
+      , Space
+      , Str "at"
+      , Space
+      , Str "ends"
+      , Space
+      , Str "of"
+      , Space
+      , Str "lines"
+      ]
+  , Table
+      ( "" , [] , [] )
+      (Caption Nothing [])
+      [ ( AlignDefault , ColWidth 0.2375 )
+      , ( AlignDefault , ColWidth 0.15 )
+      , ( AlignDefault , ColWidth 0.1625 )
+      ]
+      (TableHead ( "" , [] , [] ) [])
+      [ TableBody
+          ( "" , [] , [] )
+          (RowHeadColumns 0)
+          []
+          [ Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain
+                      [ Str "r1"
+                      , Space
+                      , Str "a"
+                      , SoftBreak
+                      , Str "r1"
+                      , Space
+                      , Str "bis"
+                      ]
+                  ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "b" , SoftBreak , Str "b" , Space , Str "2" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "c" , SoftBreak , Str "c" , Space , Str "2" ] ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "r2" , Space , Str "d" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "e" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "f" ] ]
+              ]
+          ]
+      ]
+      (TableFoot ( "" , [] , [] ) [])
+  , Para
+      [ Str "Multiple"
+      , Space
+      , Str "blocks"
+      , Space
+      , Str "in"
+      , Space
+      , Str "a"
+      , Space
+      , Str "cell"
+      ]
+  , Table
+      ( "" , [] , [] )
+      (Caption Nothing [])
+      [ ( AlignDefault , ColWidth 0.2375 )
+      , ( AlignDefault , ColWidth 0.15 )
+      , ( AlignDefault , ColWidth 0.1625 )
+      ]
+      (TableHead ( "" , [] , [] ) [])
+      [ TableBody
+          ( "" , [] , [] )
+          (RowHeadColumns 0)
+          []
+          [ Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para [ Str "r1" , Space , Str "a" ]
+                  , Para [ Str "r1" , Space , Str "bis" ]
+                  ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ BulletList
+                      [ [ Plain [ Str "b" ] ]
+                      , [ Plain [ Str "b" , Space , Str "2" ] ]
+                      , [ Plain [ Str "b" , Space , Str "2" ] ]
+                      ]
+                  ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain
+                      [ Str "c"
+                      , SoftBreak
+                      , Str "c"
+                      , Space
+                      , Str "2"
+                      , SoftBreak
+                      , Str "c"
+                      , Space
+                      , Str "2"
+                      ]
+                  ]
+              ]
+          ]
+      ]
+      (TableFoot ( "" , [] , [] ) [])
+  , Para
+      [ Str "Table"
+      , Space
+      , Str "with"
+      , Space
+      , Str "cells"
+      , Space
+      , Str "spanning"
+      , Space
+      , Str "multiple"
+      , Space
+      , Str "rows"
+      , Space
+      , Str "or"
+      , Space
+      , Str "columns:"
+      ]
+  , Table
+      ( "" , [] , [] )
+      (Caption Nothing [])
+      [ ( AlignDefault , ColWidth 0.175 )
+      , ( AlignDefault , ColWidth 0.1 )
+      , ( AlignDefault , ColWidth 0.1375 )
+      ]
+      (TableHead
+         ( "" , [] , [] )
+         [ Row
+             ( "" , [] , [] )
+             [ Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 2)
+                 [ Plain [ Str "Property" ] ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "Earth" ] ]
+             ]
+         ])
+      [ TableBody
+          ( "" , [] , [] )
+          (RowHeadColumns 0)
+          []
+          [ Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 3)
+                  (ColSpan 1)
+                  [ Plain [ Str "Temperature" , SoftBreak , Str "1961-1990" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "min" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "-89.2" , Space , Str "\176C" ] ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "mean" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "14" , Space , Str "\176C" ] ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "min" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "56.7" , Space , Str "\176C" ] ]
+              ]
+          ]
+      ]
+      (TableFoot ( "" , [] , [] ) [])
+  , Para
+      [ Str "Table"
+      , Space
+      , Str "with"
+      , Space
+      , Str "complex"
+      , Space
+      , Str "header:"
+      ]
+  , Table
+      ( "" , [] , [] )
+      (Caption Nothing [])
+      [ ( AlignDefault , ColWidth 0.275 )
+      , ( AlignDefault , ColWidth 0.1 )
+      , ( AlignDefault , ColWidth 0.1 )
+      , ( AlignDefault , ColWidth 0.1 )
+      ]
+      (TableHead
+         ( "" , [] , [] )
+         [ Row
+             ( "" , [] , [] )
+             [ Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 2)
+                 (ColSpan 1)
+                 [ Plain [ Str "Location" ] ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 3)
+                 [ Plain
+                     [ Str "Temperature"
+                     , Space
+                     , Str "1961-1990"
+                     , SoftBreak
+                     , Str "in"
+                     , Space
+                     , Str "degree"
+                     , Space
+                     , Str "Celsius"
+                     ]
+                 ]
+             ]
+         , Row
+             ( "" , [] , [] )
+             [ Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "min" ] ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "mean" ] ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "max" ] ]
+             ]
+         ])
+      [ TableBody
+          ( "" , [] , [] )
+          (RowHeadColumns 0)
+          []
+          [ Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "Antarctica" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "-89.2" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "N/A" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "19.8" ] ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "Earth" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "-89.2" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "14" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "56.7" ] ]
+              ]
+          ]
+      ]
+      (TableFoot ( "" , [] , [] ) [])
+  , Header 1 ( "footnotes" , [] , [] ) [ Str "Footnotes" ]
+  , Para
+      [ Note
+          [ Para
+              [ Str "Note"
+              , Space
+              , Str "with"
+              , Space
+              , Str "one"
+              , Space
+              , Str "line."
+              ]
+          ]
+      ]
+  , Para
+      [ Note
+          [ Para
+              [ Str "Note"
+              , Space
+              , Str "with"
+              , SoftBreak
+              , Str "continuation"
+              , Space
+              , Str "line."
+              ]
+          ]
+      ]
+  , Para
+      [ Note
+          [ Para [ Str "Note" , Space , Str "with" ]
+          , Para [ Str "continuation" , Space , Str "block." ]
+          ]
+      ]
+  , Para
+      [ Note
+          [ Para
+              [ Str "Note"
+              , Space
+              , Str "with"
+              , SoftBreak
+              , Str "continuation"
+              , Space
+              , Str "line"
+              ]
+          , Para
+              [ Str "and"
+              , Space
+              , Str "a"
+              , Space
+              , Str "second"
+              , Space
+              , Str "para."
+              ]
+          ]
+      ]
+  , Para [ Str "Not" , Space , Str "in" , Space , Str "note." ]
+  , Header 1 ( "math" , [] , [] ) [ Str "Math" ]
+  , Para
+      [ Str "Some"
+      , Space
+      , Str "inline"
+      , Space
+      , Str "math"
+      , Space
+      , Math InlineMath "E=mc^2"
+      , Str "."
+      , Space
+      , Str "Now"
+      , Space
+      , Str "some"
+      , SoftBreak
+      , Str "display"
+      , Space
+      , Str "math:"
+      ]
+  , Para [ Math DisplayMath "E=mc^2" ]
+  , Para [ Math DisplayMath "E = mc^2" ]
+  , Para
+      [ Math DisplayMath "E = mc^2"
+      , Math DisplayMath "\\alpha = \\beta"
+      ]
+  , Para
+      [ Span
+          ( "" , [] , [ ( "label" , "hithere" ) , ( "nowrap" , "" ) ] )
+          [ Math
+              DisplayMath
+              "\\begin{aligned}\nE &= mc^2\\\\\nF &= \\pi E\n\\end{aligned}"
+          , Math DisplayMath "F &= \\gamma \\alpha^2"
+          ]
+      ]
+  , Para [ Str "All" , Space , Str "done." ]
+  , Header 1 ( "default-role" , [] , [] ) [ Str "Default-Role" ]
+  , Para
+      [ Str "Try"
+      , Space
+      , Str "changing"
+      , Space
+      , Str "the"
+      , Space
+      , Str "default"
+      , Space
+      , Str "role"
+      , Space
+      , Str "to"
+      , Space
+      , Str "a"
+      , Space
+      , Str "few"
+      , Space
+      , Str "different"
+      , Space
+      , Str "things."
+      ]
+  , Header
+      2
+      ( "doesnt-break-title-parsing" , [] , [] )
+      [ Str "Doesn\8217t"
+      , Space
+      , Str "Break"
+      , Space
+      , Str "Title"
+      , Space
+      , Str "Parsing"
+      ]
+  , Para
+      [ Str "Inline"
+      , Space
+      , Str "math:"
+      , Space
+      , Math InlineMath "E=mc^2"
+      , Space
+      , Str "or"
+      , Space
+      , Math InlineMath "E=mc^2"
+      , Space
+      , Str "or"
+      , Space
+      , Math InlineMath "E=mc^2"
+      , Str "."
+      , SoftBreak
+      , Str "Other"
+      , Space
+      , Str "roles:"
+      , Space
+      , Superscript [ Str "super" ]
+      , Str ","
+      , Space
+      , Subscript [ Str "sub" ]
+      , Str "."
+      ]
+  , Para
+      [ Math DisplayMath "\\alpha = beta" , Math DisplayMath "E = mc^2" ]
+  , Para
+      [ Str "Some"
+      , Space
+      , Superscript [ Str "of" ]
+      , Space
+      , Str "these"
+      , Space
+      , Superscript [ Str "words" ]
+      , Space
+      , Str "are"
+      , Space
+      , Str "in"
+      , Space
+      , Superscript [ Str "superscript" ]
+      , Str "."
+      ]
+  , Para
+      [ Str "Reset"
+      , Space
+      , Str "default-role"
+      , Space
+      , Str "to"
+      , Space
+      , Str "the"
+      , Space
+      , Str "default"
+      , Space
+      , Str "default."
+      ]
+  , Para
+      [ Str "And"
+      , Space
+      , Str "now"
+      , Space
+      , Span
+          ( "" , [ "title-ref" ] , [] ) [ Str "some-invalid-string-3231231" ]
+      , Space
+      , Str "is"
+      , Space
+      , Str "nonsense."
+      ]
+  , Para
+      [ Str "And"
+      , Space
+      , Str "now"
+      , Space
+      , Str "with"
+      , Space
+      , RawInline
+          (Format "html") "<b>inline</b> <span id=\"test\">HTML</span>"
+      , Str "."
+      ]
+  , Para
+      [ Str "And"
+      , Space
+      , Str "some"
+      , Space
+      , Str "inline"
+      , Space
+      , Str "haskell"
+      , Space
+      , Code ( "" , [ "haskell" ] , [] ) "fmap id [1,2..10]"
+      , Str "."
+      ]
+  , Para
+      [ Str "Indirect"
+      , Space
+      , Str "python"
+      , Space
+      , Str "role"
+      , Space
+      , Code
+          ( "" , [ "py" , "python" , "indirect" ] , [] )
+          "[x*x for x in [1,2,3,4,5]]"
+      , Str "."
+      ]
+  , Para
+      [ Str "Different"
+      , Space
+      , Str "indirect"
+      , Space
+      , Str "C"
+      , Space
+      , Code ( "" , [ "c" , "different-indirect" ] , [] ) "int x = 15;"
+      , Str "."
+      ]
+  , Header
+      2
+      ( "literal-symbols" , [] , [] )
+      [ Str "Literal" , Space , Str "symbols" ]
+  , Para [ Str "2*2" , Space , Str "=" , Space , Str "4*1" ]
+  ]
diff --git a/test/rst-reader.rst b/test/rst-reader.rst
--- a/test/rst-reader.rst
+++ b/test/rst-reader.rst
@@ -107,6 +107,30 @@
    def my_function(x):
        return x + 1
 
+If we use the highlight directive, we can specify a default language
+for literate blocks.
+
+.. highlight:: haskell
+
+::
+
+  -- this code is in haskell
+  data Tree = Leaf | Node Tree Tree
+
+::
+
+  -- this code is in haskell too
+  data Nat = Zero | Succ Nat
+
+.. highlight:: javascript
+
+::
+
+  -- this code is in javascript
+  let f = (x, y) => x + y
+
+.. highlight::
+
 Lists
 =====
 
@@ -192,7 +216,7 @@
 
 	Item 1. graf two. The quick brown fox jumped over the lazy dog's
 	back.
-	
+
 2.	Item 2.
 
 3.	Item 3.
@@ -518,6 +542,31 @@
 |                  | - b 2     | c 2        | 
 | r1 bis           | - b 2     | c 2        | 
 +------------------+-----------+------------+
+
+Table with cells spanning multiple rows or columns:
+
++---------------------+----------+
+| Property            | Earth    |
++=============+=======+==========+
+|             | min   | -89.2 °C |
+| Temperature +-------+----------+
+| 1961-1990   | mean  | 14 °C    |
+|             +-------+----------+
+|             | min   | 56.7 °C  |
++-------------+-------+----------+
+
+Table with complex header:
+
++---------------------+-----------------------+
+| Location            | Temperature 1961-1990 |
+|                     | in degree Celsius     |
+|                     +-------+-------+-------+
+|                     | min   | mean  | max   |
++=====================+=======+=======+=======+
+| Antarctica          | -89.2 | N/A   | 19.8  |
++---------------------+-------+-------+-------+
+| Earth               | -89.2 | 14    | 56.7  |
++---------------------+-------+-------+-------+
 
 Footnotes
 =========
diff --git a/test/rtf/accent.native b/test/rtf/accent.native
new file mode 100644
--- /dev/null
+++ b/test/rtf/accent.native
@@ -0,0 +1,18 @@
+Pandoc
+  Meta { unMeta = fromList [] }
+  [ Para
+      [ Str "le"
+      , Space
+      , Str "caf\233"
+      , Space
+      , Str "o\249"
+      , Space
+      , Str "on"
+      , Space
+      , Str "ne"
+      , Space
+      , Str "fume"
+      , Space
+      , Str "pas"
+      ]
+  ]
diff --git a/test/rtf/accent.rtf b/test/rtf/accent.rtf
new file mode 100644
--- /dev/null
+++ b/test/rtf/accent.rtf
@@ -0,0 +1,3 @@
+{\rtf1\ansi
+{ le caf\'e9 o\'f9 on ne fume pas }
+}
diff --git a/test/rtf/bookmark.native b/test/rtf/bookmark.native
new file mode 100644
--- /dev/null
+++ b/test/rtf/bookmark.native
@@ -0,0 +1,11 @@
+Pandoc
+  Meta { unMeta = fromList [] }
+  [ Para
+      [ Span ( "bookmark_1" , [] , [] ) [ Str "Bookmark_1" ] ]
+  , Para
+      [ Link
+          ( "" , [] , [] )
+          [ Str "click" , Space , Str "me" ]
+          ( "#bookmark_1" , "" )
+      ]
+  ]
diff --git a/test/rtf/bookmark.rtf b/test/rtf/bookmark.rtf
new file mode 100644
--- /dev/null
+++ b/test/rtf/bookmark.rtf
@@ -0,0 +1,8 @@
+{\rtf1\ansi
+\pard
+{\*\bkmkstart bookmark_1}Bookmark_1{\*\bkmkend bookmark_1}
+\par
+\pard
+{\field{\*\fldinst { HYPERLINK  \\l "bookmark_1" }}{\fldrslt{click me}}}
+\par
+}
diff --git a/test/rtf/footnote.native b/test/rtf/footnote.native
new file mode 100644
--- /dev/null
+++ b/test/rtf/footnote.native
@@ -0,0 +1,130 @@
+Pandoc
+  Meta { unMeta = fromList [] }
+  [ Para
+      [ Str "Mead's"
+      , Space
+      , Str "landmark"
+      , Space
+      , Str "study"
+      , Space
+      , Str "has"
+      , Space
+      , Str "been"
+      , Space
+      , Str "amply"
+      , Space
+      , Str "annotated."
+      , Note
+          [ Para
+              [ Str "See"
+              , Space
+              , Str "Sahlins,"
+              , Space
+              , Str "Bateson,"
+              , Space
+              , Str "and"
+              , Space
+              , Str "Geertz"
+              , Space
+              , Str "for"
+              , Space
+              , Str "a"
+              , Space
+              , Str "complete"
+              , Space
+              , Str "bibliography."
+              ]
+          ]
+      , Space
+      , Str "It"
+      , Space
+      , Str "was"
+      , Space
+      , Str "her"
+      , Space
+      , Str "work"
+      , Space
+      , Str "in"
+      , Space
+      , Str "America"
+      , Space
+      , Str "during"
+      , Space
+      , Str "the"
+      , Space
+      , Str "Second"
+      , Space
+      , Str "World"
+      , Space
+      , Str "War,"
+      , Space
+      , Str "however,"
+      , Space
+      , Str "that"
+      , Space
+      , Str "forms"
+      , Space
+      , Str "the"
+      , Space
+      , Str "basis"
+      , Space
+      , Str "for"
+      , Space
+      , Str "the"
+      , Space
+      , Str "paper."
+      , Space
+      , Str "As"
+      , Space
+      , Str "others"
+      , Space
+      , Str "have"
+      , Space
+      , Str "noted,"
+      , Note
+          [ Para
+              [ Str "A"
+              , Space
+              , Str "complete"
+              , Space
+              , Str "bibliography"
+              , Space
+              , Str "will"
+              , Space
+              , Str "be"
+              , Space
+              , Str "found"
+              , Space
+              , Str "at"
+              , Space
+              , Str "the"
+              , Space
+              , Str "end"
+              , Space
+              , Str "of"
+              , Space
+              , Str "this"
+              , Space
+              , Str "chapter."
+              ]
+          ]
+      , Space
+      , Str "this"
+      , Space
+      , Str "period"
+      , Space
+      , Str "was"
+      , Space
+      , Str "a"
+      , Space
+      , Str "turning"
+      , Space
+      , Str "point"
+      , Space
+      , Str "for"
+      , Space
+      , Str "Margaret"
+      , Space
+      , Str "Mead."
+      ]
+  ]
diff --git a/test/rtf/footnote.rtf b/test/rtf/footnote.rtf
new file mode 100644
--- /dev/null
+++ b/test/rtf/footnote.rtf
@@ -0,0 +1,11 @@
+{\rtf1\ansi
+\ftnbj\ftnrestart \sectd \linemod0\linex0\endnhere \pard\plain
+\ri1170 \fs20 {\pu6 Mead's landmark study has been amply annotated.\chftn
+{\footnote \pard\plain \s246 \fs20 {\up6\chftn }
+See Sahlins, Bateson, and Geertz for a complete bibliography.} It was 
+her work in America during the Second World War, however, that forms 
+the basis for the paper. As others have noted,\chftn
+{\footnote \pard\plain \s246 \fs20 {\up6\chftn}
+A complete bibliography will be found at the end of this chapter.} 
+this period was a turning point for Margaret Mead.}
+\par}
diff --git a/test/rtf/formatting.native b/test/rtf/formatting.native
new file mode 100644
--- /dev/null
+++ b/test/rtf/formatting.native
@@ -0,0 +1,45 @@
+Pandoc
+  Meta
+    { unMeta =
+        fromList
+          [ ( "operator"
+            , MetaInlines [ Str "John" , Space , Str "MacFarlane" ]
+            )
+          ]
+    }
+  [ Para
+      [ Str "This"
+      , Space
+      , Str "is"
+      , Space
+      , Str "a"
+      , Space
+      , Str "test"
+      , Space
+      , Str "of"
+      , Space
+      , Str "FORMATTING."
+      , Space
+      , Str "This"
+      , Space
+      , Str "is"
+      , Space
+      , Str "hidden:"
+      , Space
+      , Str "."
+      ]
+  , Para [ SmallCaps [ Str "Small" , Space , Str "Caps" ] ]
+  , Para [ Strong [ Str "bold" ] ]
+  , Para [ Emph [ Str "italics" ] ]
+  , Para
+      [ Strong
+          [ Str "bold"
+          , Space
+          , Emph [ Str "and" , Space , Str "italics" ]
+          ]
+      ]
+  , Para [ Underline [ Str "underlined" ] ]
+  , Para [ Strikeout [ Str "strikeout" ] ]
+  , Para [ Str "x" , Superscript [ Str "superscript" ] ]
+  , Para [ Str "x" , Subscript [ Str "subscript" ] ]
+  ]
diff --git a/test/rtf/formatting.rtf b/test/rtf/formatting.rtf
new file mode 100644
--- /dev/null
+++ b/test/rtf/formatting.rtf
@@ -0,0 +1,201 @@
+{\rtf1\adeflang1025\ansi\ansicpg1252\uc1\adeff31507\deff0\stshfdbch31505\stshfloch31506\stshfhich31506\stshfbi31507\deflang1033\deflangfe1033\themelang1033\themelangfe0\themelangcs0{\fonttbl{\f0\fbidi \froman\fcharset0\fprq2{\*\panose 02020603050405020304}Times New Roman;}{\f4\fbidi \fnil\fcharset0\fprq2{\*\panose 00000000000000000000}Helvetica;}
+{\f34\fbidi \froman\fcharset0\fprq2{\*\panose 02040503050406030204}Cambria Math;}{\flomajor\f31500\fbidi \froman\fcharset0\fprq2{\*\panose 02020603050405020304}Times New Roman;}
+{\fdbmajor\f31501\fbidi \froman\fcharset0\fprq2{\*\panose 02020603050405020304}Times New Roman;}{\fhimajor\f31502\fbidi \fswiss\fcharset0\fprq2{\*\panose 020f0302020204030204}Calibri Light;}
+{\fbimajor\f31503\fbidi \froman\fcharset0\fprq2{\*\panose 02020603050405020304}Times New Roman;}{\flominor\f31504\fbidi \froman\fcharset0\fprq2{\*\panose 02020603050405020304}Times New Roman;}
+{\fdbminor\f31505\fbidi \froman\fcharset0\fprq2{\*\panose 02020603050405020304}Times New Roman;}{\fhiminor\f31506\fbidi \fswiss\fcharset0\fprq2{\*\panose 020f0502020204030204}Calibri;}
+{\fbiminor\f31507\fbidi \froman\fcharset0\fprq2{\*\panose 02020603050405020304}Times New Roman;}{\f1068\fbidi \froman\fcharset238\fprq2 Times New Roman CE;}{\f1069\fbidi \froman\fcharset204\fprq2 Times New Roman Cyr;}
+{\f1071\fbidi \froman\fcharset161\fprq2 Times New Roman Greek;}{\f1072\fbidi \froman\fcharset162\fprq2 Times New Roman Tur;}{\f1073\fbidi \froman\fcharset177\fprq2 Times New Roman (Hebrew);}
+{\f1074\fbidi \froman\fcharset178\fprq2 Times New Roman (Arabic);}{\f1075\fbidi \froman\fcharset186\fprq2 Times New Roman Baltic;}{\f1076\fbidi \froman\fcharset163\fprq2 Times New Roman (Vietnamese);}{\f1108\fbidi \fnil\fcharset238\fprq2 Helvetica CE;}
+{\f1109\fbidi \fnil\fcharset204\fprq2 Helvetica Cyr;}{\f1111\fbidi \fnil\fcharset161\fprq2 Helvetica Greek;}{\f1112\fbidi \fnil\fcharset162\fprq2 Helvetica Tur;}{\f1115\fbidi \fnil\fcharset186\fprq2 Helvetica Baltic;}
+{\f1116\fbidi \fnil\fcharset163\fprq2 Helvetica (Vietnamese);}{\f1408\fbidi \froman\fcharset238\fprq2 Cambria Math CE;}{\f1409\fbidi \froman\fcharset204\fprq2 Cambria Math Cyr;}{\f1411\fbidi \froman\fcharset161\fprq2 Cambria Math Greek;}
+{\f1412\fbidi \froman\fcharset162\fprq2 Cambria Math Tur;}{\f1415\fbidi \froman\fcharset186\fprq2 Cambria Math Baltic;}{\f1416\fbidi \froman\fcharset163\fprq2 Cambria Math (Vietnamese);}
+{\flomajor\f31508\fbidi \froman\fcharset238\fprq2 Times New Roman CE;}{\flomajor\f31509\fbidi \froman\fcharset204\fprq2 Times New Roman Cyr;}{\flomajor\f31511\fbidi \froman\fcharset161\fprq2 Times New Roman Greek;}
+{\flomajor\f31512\fbidi \froman\fcharset162\fprq2 Times New Roman Tur;}{\flomajor\f31513\fbidi \froman\fcharset177\fprq2 Times New Roman (Hebrew);}{\flomajor\f31514\fbidi \froman\fcharset178\fprq2 Times New Roman (Arabic);}
+{\flomajor\f31515\fbidi \froman\fcharset186\fprq2 Times New Roman Baltic;}{\flomajor\f31516\fbidi \froman\fcharset163\fprq2 Times New Roman (Vietnamese);}{\fdbmajor\f31518\fbidi \froman\fcharset238\fprq2 Times New Roman CE;}
+{\fdbmajor\f31519\fbidi \froman\fcharset204\fprq2 Times New Roman Cyr;}{\fdbmajor\f31521\fbidi \froman\fcharset161\fprq2 Times New Roman Greek;}{\fdbmajor\f31522\fbidi \froman\fcharset162\fprq2 Times New Roman Tur;}
+{\fdbmajor\f31523\fbidi \froman\fcharset177\fprq2 Times New Roman (Hebrew);}{\fdbmajor\f31524\fbidi \froman\fcharset178\fprq2 Times New Roman (Arabic);}{\fdbmajor\f31525\fbidi \froman\fcharset186\fprq2 Times New Roman Baltic;}
+{\fdbmajor\f31526\fbidi \froman\fcharset163\fprq2 Times New Roman (Vietnamese);}{\fhimajor\f31528\fbidi \fswiss\fcharset238\fprq2 Calibri Light CE;}{\fhimajor\f31529\fbidi \fswiss\fcharset204\fprq2 Calibri Light Cyr;}
+{\fhimajor\f31531\fbidi \fswiss\fcharset161\fprq2 Calibri Light Greek;}{\fhimajor\f31532\fbidi \fswiss\fcharset162\fprq2 Calibri Light Tur;}{\fhimajor\f31533\fbidi \fswiss\fcharset177\fprq2 Calibri Light (Hebrew);}
+{\fhimajor\f31534\fbidi \fswiss\fcharset178\fprq2 Calibri Light (Arabic);}{\fhimajor\f31535\fbidi \fswiss\fcharset186\fprq2 Calibri Light Baltic;}{\fhimajor\f31536\fbidi \fswiss\fcharset163\fprq2 Calibri Light (Vietnamese);}
+{\fbimajor\f31538\fbidi \froman\fcharset238\fprq2 Times New Roman CE;}{\fbimajor\f31539\fbidi \froman\fcharset204\fprq2 Times New Roman Cyr;}{\fbimajor\f31541\fbidi \froman\fcharset161\fprq2 Times New Roman Greek;}
+{\fbimajor\f31542\fbidi \froman\fcharset162\fprq2 Times New Roman Tur;}{\fbimajor\f31543\fbidi \froman\fcharset177\fprq2 Times New Roman (Hebrew);}{\fbimajor\f31544\fbidi \froman\fcharset178\fprq2 Times New Roman (Arabic);}
+{\fbimajor\f31545\fbidi \froman\fcharset186\fprq2 Times New Roman Baltic;}{\fbimajor\f31546\fbidi \froman\fcharset163\fprq2 Times New Roman (Vietnamese);}{\flominor\f31548\fbidi \froman\fcharset238\fprq2 Times New Roman CE;}
+{\flominor\f31549\fbidi \froman\fcharset204\fprq2 Times New Roman Cyr;}{\flominor\f31551\fbidi \froman\fcharset161\fprq2 Times New Roman Greek;}{\flominor\f31552\fbidi \froman\fcharset162\fprq2 Times New Roman Tur;}
+{\flominor\f31553\fbidi \froman\fcharset177\fprq2 Times New Roman (Hebrew);}{\flominor\f31554\fbidi \froman\fcharset178\fprq2 Times New Roman (Arabic);}{\flominor\f31555\fbidi \froman\fcharset186\fprq2 Times New Roman Baltic;}
+{\flominor\f31556\fbidi \froman\fcharset163\fprq2 Times New Roman (Vietnamese);}{\fdbminor\f31558\fbidi \froman\fcharset238\fprq2 Times New Roman CE;}{\fdbminor\f31559\fbidi \froman\fcharset204\fprq2 Times New Roman Cyr;}
+{\fdbminor\f31561\fbidi \froman\fcharset161\fprq2 Times New Roman Greek;}{\fdbminor\f31562\fbidi \froman\fcharset162\fprq2 Times New Roman Tur;}{\fdbminor\f31563\fbidi \froman\fcharset177\fprq2 Times New Roman (Hebrew);}
+{\fdbminor\f31564\fbidi \froman\fcharset178\fprq2 Times New Roman (Arabic);}{\fdbminor\f31565\fbidi \froman\fcharset186\fprq2 Times New Roman Baltic;}{\fdbminor\f31566\fbidi \froman\fcharset163\fprq2 Times New Roman (Vietnamese);}
+{\fhiminor\f31568\fbidi \fswiss\fcharset238\fprq2 Calibri CE;}{\fhiminor\f31569\fbidi \fswiss\fcharset204\fprq2 Calibri Cyr;}{\fhiminor\f31571\fbidi \fswiss\fcharset161\fprq2 Calibri Greek;}{\fhiminor\f31572\fbidi \fswiss\fcharset162\fprq2 Calibri Tur;}
+{\fhiminor\f31575\fbidi \fswiss\fcharset186\fprq2 Calibri Baltic;}{\fbiminor\f31578\fbidi \froman\fcharset238\fprq2 Times New Roman CE;}{\fbiminor\f31579\fbidi \froman\fcharset204\fprq2 Times New Roman Cyr;}
+{\fbiminor\f31581\fbidi \froman\fcharset161\fprq2 Times New Roman Greek;}{\fbiminor\f31582\fbidi \froman\fcharset162\fprq2 Times New Roman Tur;}{\fbiminor\f31583\fbidi \froman\fcharset177\fprq2 Times New Roman (Hebrew);}
+{\fbiminor\f31584\fbidi \froman\fcharset178\fprq2 Times New Roman (Arabic);}{\fbiminor\f31585\fbidi \froman\fcharset186\fprq2 Times New Roman Baltic;}{\fbiminor\f31586\fbidi \froman\fcharset163\fprq2 Times New Roman (Vietnamese);}}
+{\colortbl;\red0\green0\blue0;\red0\green0\blue255;\red0\green255\blue255;\red0\green255\blue0;\red255\green0\blue255;\red255\green0\blue0;\red255\green255\blue0;\red255\green255\blue255;\red0\green0\blue128;\red0\green128\blue128;\red0\green128\blue0;
+\red128\green0\blue128;\red128\green0\blue0;\red128\green128\blue0;\red128\green128\blue128;\red192\green192\blue192;\red0\green0\blue0;\red0\green0\blue0;}{\*\defchp \fs24\loch\af31506\hich\af31506\dbch\af31505 }{\*\defpap 
+\ql \li0\ri0\widctlpar\wrapdefault\aspalpha\aspnum\faauto\adjustright\rin0\lin0\itap0 }\noqfpromote {\stylesheet{\ql \li0\ri0\widctlpar\wrapdefault\aspalpha\aspnum\faauto\adjustright\rin0\lin0\itap0 \rtlch\fcs1 \af31507\afs24\alang1025 \ltrch\fcs0 
+\fs24\lang1033\langfe1033\loch\f31506\hich\af31506\dbch\af31505\cgrid\langnp1033\langfenp1033 \snext0 \sqformat \spriority0 Normal;}{\*\cs10 \additive \ssemihidden \sunhideused \spriority1 Default Paragraph Font;}{\*
+\ts11\tsrowd\trftsWidthB3\trpaddl108\trpaddr108\trpaddfl3\trpaddft3\trpaddfb3\trpaddfr3\tblind0\tblindtype3\tsvertalt\tsbrdrt\tsbrdrl\tsbrdrb\tsbrdrr\tsbrdrdgl\tsbrdrdgr\tsbrdrh\tsbrdrv 
+\ql \li0\ri0\widctlpar\wrapdefault\aspalpha\aspnum\faauto\adjustright\rin0\lin0\itap0 \rtlch\fcs1 \af31507\afs24\alang1025 \ltrch\fcs0 \fs24\lang1033\langfe1033\loch\f31506\hich\af31506\dbch\af31505\cgrid\langnp1033\langfenp1033 
+\snext11 \ssemihidden \sunhideused Normal Table;}}{\*\rsidtbl \rsid2168431\rsid14113975}{\mmathPr\mmathFont34\mbrkBin0\mbrkBinSub0\msmallFrac0\mdispDef1\mlMargin0\mrMargin0\mdefJc1\mwrapIndent1440\mintLim0\mnaryLim1}{\info{\operator John MacFarlane}
+{\creatim\yr2021\mo8\dy4\hr17\min1}{\revtim\yr2021\mo8\dy4\hr17\min2}{\version2}{\edmins1}{\nofpages1}{\nofwords21}{\nofchars120}{\nofcharsws140}{\vern6543}}{\*\xmlnstbl {\xmlns1 http://schemas.microsoft.com/office/word/2003/wordml}}
+\paperw12240\paperh15840\margl1440\margr1440\margt1440\margb1440\gutter0\ltrsect 
+\widowctrl\ftnbj\aenddoc\trackmoves0\trackformatting1\donotembedsysfont0\relyonvml0\donotembedlingdata1\grfdocevents0\validatexml0\showplaceholdtext0\ignoremixedcontent0\saveinvalidxml0\showxmlerrors0\horzdoc\dghspace120\dgvspace120\dghorigin1701
+\dgvorigin1984\dghshow0\dgvshow3\jcompress\viewkind1\viewscale100\rsidroot2168431 \fet0{\*\wgrffmtfilter 2450}\ilfomacatclnup0\ltrpar \sectd \ltrsect\linex0\sectdefaultcl\sftnbj {\*\pnseclvl1\pnucrm\pnstart1\pnindent720\pnhang {\pntxta .}}{\*\pnseclvl2
+\pnucltr\pnstart1\pnindent720\pnhang {\pntxta .}}{\*\pnseclvl3\pndec\pnstart1\pnindent720\pnhang {\pntxta .}}{\*\pnseclvl4\pnlcltr\pnstart1\pnindent720\pnhang {\pntxta )}}{\*\pnseclvl5\pndec\pnstart1\pnindent720\pnhang {\pntxtb (}{\pntxta )}}{\*\pnseclvl6
+\pnlcltr\pnstart1\pnindent720\pnhang {\pntxtb (}{\pntxta )}}{\*\pnseclvl7\pnlcrm\pnstart1\pnindent720\pnhang {\pntxtb (}{\pntxta )}}{\*\pnseclvl8\pnlcltr\pnstart1\pnindent720\pnhang {\pntxtb (}{\pntxta )}}{\*\pnseclvl9\pnlcrm\pnstart1\pnindent720\pnhang 
+{\pntxtb (}{\pntxta )}}\pard\plain \ltrpar\ql \li0\ri0\nowidctlpar\tx720\tx1440\tx2160\tx2880\tx3600\tx4320\tx5040\tx5760\tx6480\tx7200\tx7920\tx8640\wrapdefault\faauto\rin0\lin0\itap0 \rtlch\fcs1 \af31507\afs24\alang1025 \ltrch\fcs0 
+\fs24\lang1033\langfe1033\loch\af31506\hich\af31506\dbch\af31505\cgrid\langnp1033\langfenp1033 {\rtlch\fcs1 \af4 \ltrch\fcs0 \f4\insrsid14113975 \hich\af4\dbch\af31505\loch\f4 This is a test of }{\rtlch\fcs1 \af4 \ltrch\fcs0 
+\caps\f4\insrsid14113975\charrsid2168431 \hich\af4\dbch\af31505\loch\f4 formatting}{\rtlch\fcs1 \af4 \ltrch\fcs0 \f4\insrsid14113975 .}{\rtlch\fcs1 \af4 \ltrch\fcs0 \f4\insrsid2168431 \hich\af4\dbch\af31505\loch\f4   This is hidden: }{\rtlch\fcs1 \af4 
+\ltrch\fcs0 \v\f4\insrsid2168431\charrsid2168431 \hich\af4\dbch\af31505\loch\f4 secret}{\rtlch\fcs1 \af4 \ltrch\fcs0 \f4\insrsid2168431 .}{\rtlch\fcs1 \af4 \ltrch\fcs0 \f4\insrsid14113975 
+\par }{\rtlch\fcs1 \af4 \ltrch\fcs0 \scaps\f4\insrsid14113975\charrsid2168431 \hich\af4\dbch\af31505\loch\f4 Small Caps
+\par }{\rtlch\fcs1 \ab\af4 \ltrch\fcs0 \b\f4\insrsid14113975 \hich\af4\dbch\af31505\loch\f4 bold}{\rtlch\fcs1 \af4 \ltrch\fcs0 \f4\insrsid14113975 
+\par }{\rtlch\fcs1 \ai\af4 \ltrch\fcs0 \i\f4\insrsid14113975 \hich\af4\dbch\af31505\loch\f4 italics}{\rtlch\fcs1 \af4 \ltrch\fcs0 \f4\insrsid14113975 
+\par }{\rtlch\fcs1 \ab\af4 \ltrch\fcs0 \b\f4\insrsid14113975 \hich\af4\dbch\af31505\loch\f4 bold }{\rtlch\fcs1 \ab\ai\af4 \ltrch\fcs0 \b\i\f4\insrsid14113975 \hich\af4\dbch\af31505\loch\f4 and italics}{\rtlch\fcs1 \af4 \ltrch\fcs0 \f4\insrsid14113975 
+\par }{\rtlch\fcs1 \af4 \ltrch\fcs0 \f4\ul\insrsid14113975 \hich\af4\dbch\af31505\loch\f4 underlined}{\rtlch\fcs1 \af4 \ltrch\fcs0 \f4\insrsid14113975 
+\par }{\rtlch\fcs1 \af4 \ltrch\fcs0 \strike\f4\insrsid14113975 \hich\af4\dbch\af31505\loch\f4 strikeout
+\par }{\rtlch\fcs1 \af4 \ltrch\fcs0 \f4\insrsid14113975 \hich\af4\dbch\af31505\loch\f4 x}{\rtlch\fcs1 \af4 \ltrch\fcs0 \f4\super\insrsid14113975 \hich\af4\dbch\af31505\loch\f4 superscript}{\rtlch\fcs1 \af4 \ltrch\fcs0 \f4\insrsid14113975 
+\par \hich\af4\dbch\af31505\loch\f4 x}{\rtlch\fcs1 \af4 \ltrch\fcs0 \f4\sub\insrsid14113975 \hich\af4\dbch\af31505\loch\f4 subscript}{\rtlch\fcs1 \af4 \ltrch\fcs0 \f4\insrsid14113975 
+\par }{\*\themedata 504b030414000600080000002100e9de0fbfff0000001c020000130000005b436f6e74656e745f54797065735d2e786d6cac91cb4ec3301045f748fc83e52d4a
+9cb2400825e982c78ec7a27cc0c8992416c9d8b2a755fbf74cd25442a820166c2cd933f79e3be372bd1f07b5c3989ca74aaff2422b24eb1b475da5df374fd9ad
+5689811a183c61a50f98f4babebc2837878049899a52a57be670674cb23d8e90721f90a4d2fa3802cb35762680fd800ecd7551dc18eb899138e3c943d7e503b6
+b01d583deee5f99824e290b4ba3f364eac4a430883b3c092d4eca8f946c916422ecab927f52ea42b89a1cd59c254f919b0e85e6535d135a8de20f20b8c12c3b0
+0c895fcf6720192de6bf3b9e89ecdbd6596cbcdd8eb28e7c365ecc4ec1ff1460f53fe813d3cc7f5b7f020000ffff0300504b030414000600080000002100a5d6
+a7e7c0000000360100000b0000005f72656c732f2e72656c73848fcf6ac3300c87ef85bd83d17d51d2c31825762fa590432fa37d00e1287f68221bdb1bebdb4f
+c7060abb0884a4eff7a93dfeae8bf9e194e720169aaa06c3e2433fcb68e1763dbf7f82c985a4a725085b787086a37bdbb55fbc50d1a33ccd311ba548b6309512
+0f88d94fbc52ae4264d1c910d24a45db3462247fa791715fd71f989e19e0364cd3f51652d73760ae8fa8c9ffb3c330cc9e4fc17faf2ce545046e37944c69e462
+a1a82fe353bd90a865aad41ed0b5b8f9d6fd010000ffff0300504b0304140006000800000021006b799616830000008a0000001c0000007468656d652f746865
+6d652f7468656d654d616e616765722e786d6c0ccc4d0ac3201040e17da17790d93763bb284562b2cbaebbf600439c1a41c7a0d29fdbd7e5e38337cedf14d59b
+4b0d592c9c070d8a65cd2e88b7f07c2ca71ba8da481cc52c6ce1c715e6e97818c9b48d13df49c873517d23d59085adb5dd20d6b52bd521ef2cdd5eb9246a3d8b
+4757e8d3f729e245eb2b260a0238fd010000ffff0300504b030414000600080000002100b6f4679893070000c9200000160000007468656d652f7468656d652f
+7468656d65312e786d6cec59cd8b1bc915bf07f23f347d97f5d5ad8fc1f2a24fcfda33b6b164873dd648a5eef2547789aad28cc56208de532e81c026e49085bd
+ed21842cecc22eb9e48f31d8249b3f22afaa5bdd5552c99e191c3061463074977eefd5afde7bf5de53d5ddcf5e26d4bbc05c1096f6fcfa9d9aefe174ce16248d
+7afeb3d9a4d2f13d2151ba4094a5b8e76fb0f03fbbf7eb5fdd454732c609f6403e1547a8e7c752ae8eaa5531876124eeb0154ee1bb25e30992f0caa3ea82a34b
+d09bd06aa3566b55134452df4b51026a1f2f97648ebd9952e9dfdb2a1f53784da5500373caa74a35b6243476715e5708b11143cabd0b447b3eccb3609733fc52
+fa1e4542c2173dbfa6fffceabdbb5574940b517940d6909be8bf5c2e17589c37f49c3c3a2b260d823068f50bfd1a40e53e6edc1eb7c6ad429f06a0f91c569a71
+b175b61bc320c71aa0ecd1a17bd41e35eb16ded0dfdce3dc0fd5c7c26b50a63fd8c34f2643b0a285d7a00c1feee1c3417730b2f56b50866fede1dbb5fe28685b
+fa3528a6243ddf43d7c25673b85d6d0159327aec8477c360d26ee4ca4b144443115d6a8a254be5a1584bd00bc6270050408a24493db959e1259a43140f112567
+9c7827248a21f056286502866b8ddaa4d684ffea13e827ed5174849121ad780113b137a4f87862cec94af6fc07a0d537206f7ffef9cdeb1fdfbcfee9cd575fbd
+79fdf77c6eadca923b466964cafdf2dd1ffef3cd6fbd7ffff0ed2f5fff319b7a172f4cfcbbbffdeedd3ffef93ef5b0e2d2146ffff4fdbb1fbf7ffbe7dfffebaf
+5f3bb4f7393a33e1339260e13dc297de5396c0021dfcf119bf9ec42c46c494e8a791402952b338f48f656ca11f6d10450edc00db767cce21d5b880f7d72f2cc2
+d398af2571687c182716f094313a60dc6985876a2ec3ccb3751ab927e76b13f714a10bd7dc43945a5e1eaf579063894be530c616cd2714a5124538c5d253dfb1
+738c1dabfb8210cbaea764ce99604be97d41bc01224e93ccc899154da5d03149c02f1b1741f0b7659bd3e7de8051d7aa47f8c246c2de40d4417e86a965c6fb68
+2d51e252394309350d7e8264ec2239ddf0b9891b0b099e8e3065de78818570c93ce6b05ec3e90f21cdb8dd7e4a37898de4929cbb749e20c64ce4889d0f6394ac
+5cd829496313fbb938871045de13265df05366ef10f50e7e40e941773f27d872f787b3c133c8b026a53240d4376beef0e57dccacf89d6ee8126157aae9f3c44a
+b17d4e9cd131584756689f604cd1255a60ec3dfbdcc160c05696cd4bd20f62c82ac7d815580f901dabea3dc5027a25d5dcece7c91322ac909de2881de073bad9
+493c1b9426881fd2fc08bc6eda7c0ca52e7105c0633a3f37818f08f480102f4ea33c16a0c308ee835a9fc4c82a60ea5db8e375c32dff5d658fc1be7c61d1b8c2
+be04197c6d1948eca6cc7b6d3343d49aa00c9819822ec3956e41c4727f29a28aab165b3be596f6a62ddd00dd91d5f42424fd6007b4d3fb84ffbbde073a8cb77f
+f9c6b10f3e4ebfe3566c25ab6b763a8792c9f14e7f7308b7dbd50c195f904fbfa919a175fa04431dd9cf58b73dcd6d4fe3ffdff73487f6f36d2773a8dfb8ed64
+7ce8306e3b99fc70e5e3743265f3027d8d3af0c80e7af4b14f72f0d46749289dca0dc527421ffc08f83db398c0a092d3279eb838055cc5f0a8ca1c4c60e1228e
+b48cc799fc0d91f134462b381daafb4a492472d591f0564cc0a1911e76ea5678ba4e4ed9223becacd7d5c16656590592e5782d2cc6e1a04a66e856bb3cc02bd4
+6bb6913e68dd1250b2d721614c6693683a48b4b783ca48fa58178ce620a157f65158741d2c3a4afdd6557b2c805ae115f8c1edc1cff49e1f06200242701e07cd
+f942f92973f5d6bbda991fd3d3878c69450034d8db08283ddd555c0f2e4fad2e0bb52b78da2261849b4d425b46377822869fc17974aad1abd0b8aeafbba54b2d
+7aca147a3e08ad9246bbf33e1637f535c8ede6069a9a9982a6de65cf6f35430899395af5fc251c1ac363b282d811ea3717a211dcbccc25cf36fc4d32cb8a0b39
+4222ce0cae934e960d122231f728497abe5a7ee1069aea1ca2b9d51b90103e59725d482b9f1a3970baed64bc5ce2b934dd6e8c284b67af90e1b35ce1fc568bdf
+1cac24d91adc3d8d1797de195df3a708422c6cd795011744c0dd413db3e682c0655891c8caf8db294c79da356fa3740c65e388ae62945714339967709dca0b3a
+faadb081f196af190c6a98242f8467912ab0a651ad6a5a548d8cc3c1aafb6121653923699635d3ca2aaa6abab39835c3b60cecd8f26645de60b53531e434b3c2
+67a97b37e576b7b96ea74f28aa0418bcb09fa3ea5ea12018d4cac92c6a8af17e1a56393b1fb56bc776811fa07695226164fdd656ed8edd8a1ae19c0e066f54f9
+416e376a6168b9ed2bb5a5f5adb979b1cdce5e40f2184197bba6526857c2c92e47d0104d754f92a50dd8222f65be35e0c95b73d2f3bfac85fd60d80887955a27
+1c57826650ab74c27eb3d20fc3667d1cd66ba341e31514161927f530bbb19fc00506dde4f7f67a7cefee3ed9ded1dc99b3a4caf4dd7c5513d777f7f5c6e1bb7b
+8f40d2f9b2d598749bdd41abd26df627956034e854bac3d6a0326a0ddba3c9681876ba9357be77a1c141bf390c5ae34ea5551f0e2b41aba6e877ba9576d068f4
+8376bf330efaaff23606569ea58fdc16605ecdebde7f010000ffff0300504b0304140006000800000021000dd1909fb60000001b010000270000007468656d65
+2f7468656d652f5f72656c732f7468656d654d616e616765722e786d6c2e72656c73848f4d0ac2301484f78277086f6fd3ba109126dd88d0add40384e4350d36
+3f2451eced0dae2c082e8761be9969bb979dc9136332de3168aa1a083ae995719ac16db8ec8e4052164e89d93b64b060828e6f37ed1567914b284d262452282e
+3198720e274a939cd08a54f980ae38a38f56e422a3a641c8bbd048f7757da0f19b017cc524bd62107bd5001996509affb3fd381a89672f1f165dfe514173d985
+0528a2c6cce0239baa4c04ca5bbabac4df000000ffff0300504b01022d0014000600080000002100e9de0fbfff0000001c020000130000000000000000000000
+0000000000005b436f6e74656e745f54797065735d2e786d6c504b01022d0014000600080000002100a5d6a7e7c0000000360100000b00000000000000000000
+000000300100005f72656c732f2e72656c73504b01022d00140006000800000021006b799616830000008a0000001c0000000000000000000000000019020000
+7468656d652f7468656d652f7468656d654d616e616765722e786d6c504b01022d0014000600080000002100b6f4679893070000c92000001600000000000000
+000000000000d60200007468656d652f7468656d652f7468656d65312e786d6c504b01022d00140006000800000021000dd1909fb60000001b01000027000000
+000000000000000000009d0a00007468656d652f7468656d652f5f72656c732f7468656d654d616e616765722e786d6c2e72656c73504b050600000000050005005d010000980b00000000}
+{\*\colorschememapping 3c3f786d6c2076657273696f6e3d22312e302220656e636f64696e673d225554462d3822207374616e64616c6f6e653d22796573223f3e0d0a3c613a636c724d
+617020786d6c6e733a613d22687474703a2f2f736368656d61732e6f70656e786d6c666f726d6174732e6f72672f64726177696e676d6c2f323030362f6d6169
+6e22206267313d226c743122207478313d22646b3122206267323d226c743222207478323d22646b322220616363656e74313d22616363656e74312220616363
+656e74323d22616363656e74322220616363656e74333d22616363656e74332220616363656e74343d22616363656e74342220616363656e74353d22616363656e74352220616363656e74363d22616363656e74362220686c696e6b3d22686c696e6b2220666f6c486c696e6b3d22666f6c486c696e6b222f3e}
+{\*\latentstyles\lsdstimax376\lsdlockeddef0\lsdsemihiddendef0\lsdunhideuseddef0\lsdqformatdef0\lsdprioritydef99{\lsdlockedexcept \lsdqformat1 \lsdpriority0 \lsdlocked0 Normal;\lsdqformat1 \lsdpriority9 \lsdlocked0 heading 1;
+\lsdsemihidden1 \lsdunhideused1 \lsdqformat1 \lsdpriority9 \lsdlocked0 heading 2;\lsdsemihidden1 \lsdunhideused1 \lsdqformat1 \lsdpriority9 \lsdlocked0 heading 3;\lsdsemihidden1 \lsdunhideused1 \lsdqformat1 \lsdpriority9 \lsdlocked0 heading 4;
+\lsdsemihidden1 \lsdunhideused1 \lsdqformat1 \lsdpriority9 \lsdlocked0 heading 5;\lsdsemihidden1 \lsdunhideused1 \lsdqformat1 \lsdpriority9 \lsdlocked0 heading 6;\lsdsemihidden1 \lsdunhideused1 \lsdqformat1 \lsdpriority9 \lsdlocked0 heading 7;
+\lsdsemihidden1 \lsdunhideused1 \lsdqformat1 \lsdpriority9 \lsdlocked0 heading 8;\lsdsemihidden1 \lsdunhideused1 \lsdqformat1 \lsdpriority9 \lsdlocked0 heading 9;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 index 1;
+\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 index 2;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 index 3;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 index 4;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 index 5;
+\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 index 6;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 index 7;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 index 8;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 index 9;
+\lsdsemihidden1 \lsdunhideused1 \lsdpriority39 \lsdlocked0 toc 1;\lsdsemihidden1 \lsdunhideused1 \lsdpriority39 \lsdlocked0 toc 2;\lsdsemihidden1 \lsdunhideused1 \lsdpriority39 \lsdlocked0 toc 3;
+\lsdsemihidden1 \lsdunhideused1 \lsdpriority39 \lsdlocked0 toc 4;\lsdsemihidden1 \lsdunhideused1 \lsdpriority39 \lsdlocked0 toc 5;\lsdsemihidden1 \lsdunhideused1 \lsdpriority39 \lsdlocked0 toc 6;
+\lsdsemihidden1 \lsdunhideused1 \lsdpriority39 \lsdlocked0 toc 7;\lsdsemihidden1 \lsdunhideused1 \lsdpriority39 \lsdlocked0 toc 8;\lsdsemihidden1 \lsdunhideused1 \lsdpriority39 \lsdlocked0 toc 9;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Normal Indent;
+\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 footnote text;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 annotation text;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 header;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 footer;
+\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 index heading;\lsdsemihidden1 \lsdunhideused1 \lsdqformat1 \lsdpriority35 \lsdlocked0 caption;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 table of figures;
+\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 envelope address;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 envelope return;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 footnote reference;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 annotation reference;
+\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 line number;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 page number;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 endnote reference;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 endnote text;
+\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 table of authorities;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 macro;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 toa heading;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 List;
+\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 List Bullet;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 List Number;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 List 2;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 List 3;
+\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 List 4;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 List 5;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 List Bullet 2;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 List Bullet 3;
+\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 List Bullet 4;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 List Bullet 5;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 List Number 2;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 List Number 3;
+\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 List Number 4;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 List Number 5;\lsdqformat1 \lsdpriority10 \lsdlocked0 Title;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Closing;
+\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Signature;\lsdsemihidden1 \lsdunhideused1 \lsdpriority1 \lsdlocked0 Default Paragraph Font;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Body Text;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Body Text Indent;
+\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 List Continue;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 List Continue 2;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 List Continue 3;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 List Continue 4;
+\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 List Continue 5;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Message Header;\lsdqformat1 \lsdpriority11 \lsdlocked0 Subtitle;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Salutation;
+\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Date;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Body Text First Indent;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Body Text First Indent 2;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Note Heading;
+\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Body Text 2;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Body Text 3;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Body Text Indent 2;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Body Text Indent 3;
+\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Block Text;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Hyperlink;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 FollowedHyperlink;\lsdqformat1 \lsdpriority22 \lsdlocked0 Strong;
+\lsdqformat1 \lsdpriority20 \lsdlocked0 Emphasis;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Document Map;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Plain Text;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 E-mail Signature;
+\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 HTML Top of Form;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 HTML Bottom of Form;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Normal (Web);\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 HTML Acronym;
+\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 HTML Address;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 HTML Cite;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 HTML Code;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 HTML Definition;
+\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 HTML Keyboard;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 HTML Preformatted;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 HTML Sample;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 HTML Typewriter;
+\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 HTML Variable;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Normal Table;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 annotation subject;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 No List;
+\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Outline List 1;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Outline List 2;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Outline List 3;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Table Simple 1;
+\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Table Simple 2;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Table Simple 3;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Table Classic 1;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Table Classic 2;
+\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Table Classic 3;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Table Classic 4;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Table Colorful 1;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Table Colorful 2;
+\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Table Colorful 3;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Table Columns 1;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Table Columns 2;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Table Columns 3;
+\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Table Columns 4;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Table Columns 5;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Table Grid 1;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Table Grid 2;
+\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Table Grid 3;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Table Grid 4;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Table Grid 5;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Table Grid 6;
+\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Table Grid 7;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Table Grid 8;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Table List 1;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Table List 2;
+\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Table List 3;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Table List 4;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Table List 5;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Table List 6;
+\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Table List 7;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Table List 8;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Table 3D effects 1;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Table 3D effects 2;
+\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Table 3D effects 3;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Table Contemporary;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Table Elegant;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Table Professional;
+\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Table Subtle 1;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Table Subtle 2;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Table Web 1;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Table Web 2;
+\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Table Web 3;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Balloon Text;\lsdpriority39 \lsdlocked0 Table Grid;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Table Theme;\lsdsemihidden1 \lsdlocked0 Placeholder Text;
+\lsdqformat1 \lsdpriority1 \lsdlocked0 No Spacing;\lsdpriority60 \lsdlocked0 Light Shading;\lsdpriority61 \lsdlocked0 Light List;\lsdpriority62 \lsdlocked0 Light Grid;\lsdpriority63 \lsdlocked0 Medium Shading 1;\lsdpriority64 \lsdlocked0 Medium Shading 2;
+\lsdpriority65 \lsdlocked0 Medium List 1;\lsdpriority66 \lsdlocked0 Medium List 2;\lsdpriority67 \lsdlocked0 Medium Grid 1;\lsdpriority68 \lsdlocked0 Medium Grid 2;\lsdpriority69 \lsdlocked0 Medium Grid 3;\lsdpriority70 \lsdlocked0 Dark List;
+\lsdpriority71 \lsdlocked0 Colorful Shading;\lsdpriority72 \lsdlocked0 Colorful List;\lsdpriority73 \lsdlocked0 Colorful Grid;\lsdpriority60 \lsdlocked0 Light Shading Accent 1;\lsdpriority61 \lsdlocked0 Light List Accent 1;
+\lsdpriority62 \lsdlocked0 Light Grid Accent 1;\lsdpriority63 \lsdlocked0 Medium Shading 1 Accent 1;\lsdpriority64 \lsdlocked0 Medium Shading 2 Accent 1;\lsdpriority65 \lsdlocked0 Medium List 1 Accent 1;\lsdsemihidden1 \lsdlocked0 Revision;
+\lsdqformat1 \lsdpriority34 \lsdlocked0 List Paragraph;\lsdqformat1 \lsdpriority29 \lsdlocked0 Quote;\lsdqformat1 \lsdpriority30 \lsdlocked0 Intense Quote;\lsdpriority66 \lsdlocked0 Medium List 2 Accent 1;\lsdpriority67 \lsdlocked0 Medium Grid 1 Accent 1;
+\lsdpriority68 \lsdlocked0 Medium Grid 2 Accent 1;\lsdpriority69 \lsdlocked0 Medium Grid 3 Accent 1;\lsdpriority70 \lsdlocked0 Dark List Accent 1;\lsdpriority71 \lsdlocked0 Colorful Shading Accent 1;\lsdpriority72 \lsdlocked0 Colorful List Accent 1;
+\lsdpriority73 \lsdlocked0 Colorful Grid Accent 1;\lsdpriority60 \lsdlocked0 Light Shading Accent 2;\lsdpriority61 \lsdlocked0 Light List Accent 2;\lsdpriority62 \lsdlocked0 Light Grid Accent 2;\lsdpriority63 \lsdlocked0 Medium Shading 1 Accent 2;
+\lsdpriority64 \lsdlocked0 Medium Shading 2 Accent 2;\lsdpriority65 \lsdlocked0 Medium List 1 Accent 2;\lsdpriority66 \lsdlocked0 Medium List 2 Accent 2;\lsdpriority67 \lsdlocked0 Medium Grid 1 Accent 2;\lsdpriority68 \lsdlocked0 Medium Grid 2 Accent 2;
+\lsdpriority69 \lsdlocked0 Medium Grid 3 Accent 2;\lsdpriority70 \lsdlocked0 Dark List Accent 2;\lsdpriority71 \lsdlocked0 Colorful Shading Accent 2;\lsdpriority72 \lsdlocked0 Colorful List Accent 2;\lsdpriority73 \lsdlocked0 Colorful Grid Accent 2;
+\lsdpriority60 \lsdlocked0 Light Shading Accent 3;\lsdpriority61 \lsdlocked0 Light List Accent 3;\lsdpriority62 \lsdlocked0 Light Grid Accent 3;\lsdpriority63 \lsdlocked0 Medium Shading 1 Accent 3;\lsdpriority64 \lsdlocked0 Medium Shading 2 Accent 3;
+\lsdpriority65 \lsdlocked0 Medium List 1 Accent 3;\lsdpriority66 \lsdlocked0 Medium List 2 Accent 3;\lsdpriority67 \lsdlocked0 Medium Grid 1 Accent 3;\lsdpriority68 \lsdlocked0 Medium Grid 2 Accent 3;\lsdpriority69 \lsdlocked0 Medium Grid 3 Accent 3;
+\lsdpriority70 \lsdlocked0 Dark List Accent 3;\lsdpriority71 \lsdlocked0 Colorful Shading Accent 3;\lsdpriority72 \lsdlocked0 Colorful List Accent 3;\lsdpriority73 \lsdlocked0 Colorful Grid Accent 3;\lsdpriority60 \lsdlocked0 Light Shading Accent 4;
+\lsdpriority61 \lsdlocked0 Light List Accent 4;\lsdpriority62 \lsdlocked0 Light Grid Accent 4;\lsdpriority63 \lsdlocked0 Medium Shading 1 Accent 4;\lsdpriority64 \lsdlocked0 Medium Shading 2 Accent 4;\lsdpriority65 \lsdlocked0 Medium List 1 Accent 4;
+\lsdpriority66 \lsdlocked0 Medium List 2 Accent 4;\lsdpriority67 \lsdlocked0 Medium Grid 1 Accent 4;\lsdpriority68 \lsdlocked0 Medium Grid 2 Accent 4;\lsdpriority69 \lsdlocked0 Medium Grid 3 Accent 4;\lsdpriority70 \lsdlocked0 Dark List Accent 4;
+\lsdpriority71 \lsdlocked0 Colorful Shading Accent 4;\lsdpriority72 \lsdlocked0 Colorful List Accent 4;\lsdpriority73 \lsdlocked0 Colorful Grid Accent 4;\lsdpriority60 \lsdlocked0 Light Shading Accent 5;\lsdpriority61 \lsdlocked0 Light List Accent 5;
+\lsdpriority62 \lsdlocked0 Light Grid Accent 5;\lsdpriority63 \lsdlocked0 Medium Shading 1 Accent 5;\lsdpriority64 \lsdlocked0 Medium Shading 2 Accent 5;\lsdpriority65 \lsdlocked0 Medium List 1 Accent 5;\lsdpriority66 \lsdlocked0 Medium List 2 Accent 5;
+\lsdpriority67 \lsdlocked0 Medium Grid 1 Accent 5;\lsdpriority68 \lsdlocked0 Medium Grid 2 Accent 5;\lsdpriority69 \lsdlocked0 Medium Grid 3 Accent 5;\lsdpriority70 \lsdlocked0 Dark List Accent 5;\lsdpriority71 \lsdlocked0 Colorful Shading Accent 5;
+\lsdpriority72 \lsdlocked0 Colorful List Accent 5;\lsdpriority73 \lsdlocked0 Colorful Grid Accent 5;\lsdpriority60 \lsdlocked0 Light Shading Accent 6;\lsdpriority61 \lsdlocked0 Light List Accent 6;\lsdpriority62 \lsdlocked0 Light Grid Accent 6;
+\lsdpriority63 \lsdlocked0 Medium Shading 1 Accent 6;\lsdpriority64 \lsdlocked0 Medium Shading 2 Accent 6;\lsdpriority65 \lsdlocked0 Medium List 1 Accent 6;\lsdpriority66 \lsdlocked0 Medium List 2 Accent 6;
+\lsdpriority67 \lsdlocked0 Medium Grid 1 Accent 6;\lsdpriority68 \lsdlocked0 Medium Grid 2 Accent 6;\lsdpriority69 \lsdlocked0 Medium Grid 3 Accent 6;\lsdpriority70 \lsdlocked0 Dark List Accent 6;\lsdpriority71 \lsdlocked0 Colorful Shading Accent 6;
+\lsdpriority72 \lsdlocked0 Colorful List Accent 6;\lsdpriority73 \lsdlocked0 Colorful Grid Accent 6;\lsdqformat1 \lsdpriority19 \lsdlocked0 Subtle Emphasis;\lsdqformat1 \lsdpriority21 \lsdlocked0 Intense Emphasis;
+\lsdqformat1 \lsdpriority31 \lsdlocked0 Subtle Reference;\lsdqformat1 \lsdpriority32 \lsdlocked0 Intense Reference;\lsdqformat1 \lsdpriority33 \lsdlocked0 Book Title;\lsdsemihidden1 \lsdunhideused1 \lsdpriority37 \lsdlocked0 Bibliography;
+\lsdsemihidden1 \lsdunhideused1 \lsdqformat1 \lsdpriority39 \lsdlocked0 TOC Heading;\lsdpriority41 \lsdlocked0 Plain Table 1;\lsdpriority42 \lsdlocked0 Plain Table 2;\lsdpriority43 \lsdlocked0 Plain Table 3;\lsdpriority44 \lsdlocked0 Plain Table 4;
+\lsdpriority45 \lsdlocked0 Plain Table 5;\lsdpriority40 \lsdlocked0 Grid Table Light;\lsdpriority46 \lsdlocked0 Grid Table 1 Light;\lsdpriority47 \lsdlocked0 Grid Table 2;\lsdpriority48 \lsdlocked0 Grid Table 3;\lsdpriority49 \lsdlocked0 Grid Table 4;
+\lsdpriority50 \lsdlocked0 Grid Table 5 Dark;\lsdpriority51 \lsdlocked0 Grid Table 6 Colorful;\lsdpriority52 \lsdlocked0 Grid Table 7 Colorful;\lsdpriority46 \lsdlocked0 Grid Table 1 Light Accent 1;\lsdpriority47 \lsdlocked0 Grid Table 2 Accent 1;
+\lsdpriority48 \lsdlocked0 Grid Table 3 Accent 1;\lsdpriority49 \lsdlocked0 Grid Table 4 Accent 1;\lsdpriority50 \lsdlocked0 Grid Table 5 Dark Accent 1;\lsdpriority51 \lsdlocked0 Grid Table 6 Colorful Accent 1;
+\lsdpriority52 \lsdlocked0 Grid Table 7 Colorful Accent 1;\lsdpriority46 \lsdlocked0 Grid Table 1 Light Accent 2;\lsdpriority47 \lsdlocked0 Grid Table 2 Accent 2;\lsdpriority48 \lsdlocked0 Grid Table 3 Accent 2;
+\lsdpriority49 \lsdlocked0 Grid Table 4 Accent 2;\lsdpriority50 \lsdlocked0 Grid Table 5 Dark Accent 2;\lsdpriority51 \lsdlocked0 Grid Table 6 Colorful Accent 2;\lsdpriority52 \lsdlocked0 Grid Table 7 Colorful Accent 2;
+\lsdpriority46 \lsdlocked0 Grid Table 1 Light Accent 3;\lsdpriority47 \lsdlocked0 Grid Table 2 Accent 3;\lsdpriority48 \lsdlocked0 Grid Table 3 Accent 3;\lsdpriority49 \lsdlocked0 Grid Table 4 Accent 3;
+\lsdpriority50 \lsdlocked0 Grid Table 5 Dark Accent 3;\lsdpriority51 \lsdlocked0 Grid Table 6 Colorful Accent 3;\lsdpriority52 \lsdlocked0 Grid Table 7 Colorful Accent 3;\lsdpriority46 \lsdlocked0 Grid Table 1 Light Accent 4;
+\lsdpriority47 \lsdlocked0 Grid Table 2 Accent 4;\lsdpriority48 \lsdlocked0 Grid Table 3 Accent 4;\lsdpriority49 \lsdlocked0 Grid Table 4 Accent 4;\lsdpriority50 \lsdlocked0 Grid Table 5 Dark Accent 4;
+\lsdpriority51 \lsdlocked0 Grid Table 6 Colorful Accent 4;\lsdpriority52 \lsdlocked0 Grid Table 7 Colorful Accent 4;\lsdpriority46 \lsdlocked0 Grid Table 1 Light Accent 5;\lsdpriority47 \lsdlocked0 Grid Table 2 Accent 5;
+\lsdpriority48 \lsdlocked0 Grid Table 3 Accent 5;\lsdpriority49 \lsdlocked0 Grid Table 4 Accent 5;\lsdpriority50 \lsdlocked0 Grid Table 5 Dark Accent 5;\lsdpriority51 \lsdlocked0 Grid Table 6 Colorful Accent 5;
+\lsdpriority52 \lsdlocked0 Grid Table 7 Colorful Accent 5;\lsdpriority46 \lsdlocked0 Grid Table 1 Light Accent 6;\lsdpriority47 \lsdlocked0 Grid Table 2 Accent 6;\lsdpriority48 \lsdlocked0 Grid Table 3 Accent 6;
+\lsdpriority49 \lsdlocked0 Grid Table 4 Accent 6;\lsdpriority50 \lsdlocked0 Grid Table 5 Dark Accent 6;\lsdpriority51 \lsdlocked0 Grid Table 6 Colorful Accent 6;\lsdpriority52 \lsdlocked0 Grid Table 7 Colorful Accent 6;
+\lsdpriority46 \lsdlocked0 List Table 1 Light;\lsdpriority47 \lsdlocked0 List Table 2;\lsdpriority48 \lsdlocked0 List Table 3;\lsdpriority49 \lsdlocked0 List Table 4;\lsdpriority50 \lsdlocked0 List Table 5 Dark;
+\lsdpriority51 \lsdlocked0 List Table 6 Colorful;\lsdpriority52 \lsdlocked0 List Table 7 Colorful;\lsdpriority46 \lsdlocked0 List Table 1 Light Accent 1;\lsdpriority47 \lsdlocked0 List Table 2 Accent 1;\lsdpriority48 \lsdlocked0 List Table 3 Accent 1;
+\lsdpriority49 \lsdlocked0 List Table 4 Accent 1;\lsdpriority50 \lsdlocked0 List Table 5 Dark Accent 1;\lsdpriority51 \lsdlocked0 List Table 6 Colorful Accent 1;\lsdpriority52 \lsdlocked0 List Table 7 Colorful Accent 1;
+\lsdpriority46 \lsdlocked0 List Table 1 Light Accent 2;\lsdpriority47 \lsdlocked0 List Table 2 Accent 2;\lsdpriority48 \lsdlocked0 List Table 3 Accent 2;\lsdpriority49 \lsdlocked0 List Table 4 Accent 2;
+\lsdpriority50 \lsdlocked0 List Table 5 Dark Accent 2;\lsdpriority51 \lsdlocked0 List Table 6 Colorful Accent 2;\lsdpriority52 \lsdlocked0 List Table 7 Colorful Accent 2;\lsdpriority46 \lsdlocked0 List Table 1 Light Accent 3;
+\lsdpriority47 \lsdlocked0 List Table 2 Accent 3;\lsdpriority48 \lsdlocked0 List Table 3 Accent 3;\lsdpriority49 \lsdlocked0 List Table 4 Accent 3;\lsdpriority50 \lsdlocked0 List Table 5 Dark Accent 3;
+\lsdpriority51 \lsdlocked0 List Table 6 Colorful Accent 3;\lsdpriority52 \lsdlocked0 List Table 7 Colorful Accent 3;\lsdpriority46 \lsdlocked0 List Table 1 Light Accent 4;\lsdpriority47 \lsdlocked0 List Table 2 Accent 4;
+\lsdpriority48 \lsdlocked0 List Table 3 Accent 4;\lsdpriority49 \lsdlocked0 List Table 4 Accent 4;\lsdpriority50 \lsdlocked0 List Table 5 Dark Accent 4;\lsdpriority51 \lsdlocked0 List Table 6 Colorful Accent 4;
+\lsdpriority52 \lsdlocked0 List Table 7 Colorful Accent 4;\lsdpriority46 \lsdlocked0 List Table 1 Light Accent 5;\lsdpriority47 \lsdlocked0 List Table 2 Accent 5;\lsdpriority48 \lsdlocked0 List Table 3 Accent 5;
+\lsdpriority49 \lsdlocked0 List Table 4 Accent 5;\lsdpriority50 \lsdlocked0 List Table 5 Dark Accent 5;\lsdpriority51 \lsdlocked0 List Table 6 Colorful Accent 5;\lsdpriority52 \lsdlocked0 List Table 7 Colorful Accent 5;
+\lsdpriority46 \lsdlocked0 List Table 1 Light Accent 6;\lsdpriority47 \lsdlocked0 List Table 2 Accent 6;\lsdpriority48 \lsdlocked0 List Table 3 Accent 6;\lsdpriority49 \lsdlocked0 List Table 4 Accent 6;
+\lsdpriority50 \lsdlocked0 List Table 5 Dark Accent 6;\lsdpriority51 \lsdlocked0 List Table 6 Colorful Accent 6;\lsdpriority52 \lsdlocked0 List Table 7 Colorful Accent 6;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Mention;
+\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Smart Hyperlink;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Hashtag;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Unresolved Mention;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Smart Link;}}{\*\datastore }}
diff --git a/test/rtf/heading.native b/test/rtf/heading.native
new file mode 100644
--- /dev/null
+++ b/test/rtf/heading.native
@@ -0,0 +1,10 @@
+Pandoc
+  Meta { unMeta = fromList [] }
+  [ Header
+      1 ( "" , [] , [] ) [ Str "Heading" , Space , Str "1" ]
+  , Header
+      2 ( "" , [] , [] ) [ Str "Heading" , Space , Str "2" ]
+  , Header
+      3 ( "" , [] , [] ) [ Str "Heading" , Space , Str "3" ]
+  , Para [ Str "Paragraph" ]
+  ]
diff --git a/test/rtf/heading.rtf b/test/rtf/heading.rtf
new file mode 100644
--- /dev/null
+++ b/test/rtf/heading.rtf
@@ -0,0 +1,223 @@
+{\rtf1\adeflang1025\ansi\ansicpg1252\uc1\adeff31507\deff0\stshfdbch31506\stshfloch31506\stshfhich31506\stshfbi31507\deflang1033\deflangfe1033\themelang1033\themelangfe0\themelangcs0{\fonttbl{\f0\fbidi \froman\fcharset0\fprq2{\*\panose 02020603050405020304}Times New Roman;}{\f34\fbidi \froman\fcharset0\fprq2{\*\panose 02040503050406030204}Cambria Math;}
+{\f37\fbidi \fswiss\fcharset0\fprq2{\*\panose 020f0502020204030204}Calibri;}{\f38\fbidi \fswiss\fcharset0\fprq2{\*\panose 020f0302020204030204}Calibri Light;}{\flomajor\f31500\fbidi \froman\fcharset0\fprq2{\*\panose 02020603050405020304}Times New Roman;}
+{\fdbmajor\f31501\fbidi \froman\fcharset0\fprq2{\*\panose 02020603050405020304}Times New Roman;}{\fhimajor\f31502\fbidi \fswiss\fcharset0\fprq2{\*\panose 020f0302020204030204}Calibri Light;}
+{\fbimajor\f31503\fbidi \froman\fcharset0\fprq2{\*\panose 02020603050405020304}Times New Roman;}{\flominor\f31504\fbidi \froman\fcharset0\fprq2{\*\panose 02020603050405020304}Times New Roman;}
+{\fdbminor\f31505\fbidi \froman\fcharset0\fprq2{\*\panose 02020603050405020304}Times New Roman;}{\fhiminor\f31506\fbidi \fswiss\fcharset0\fprq2{\*\panose 020f0502020204030204}Calibri;}
+{\fbiminor\f31507\fbidi \froman\fcharset0\fprq2{\*\panose 02020603050405020304}Times New Roman;}{\f44\fbidi \froman\fcharset238\fprq2 Times New Roman CE;}{\f45\fbidi \froman\fcharset204\fprq2 Times New Roman Cyr;}
+{\f47\fbidi \froman\fcharset161\fprq2 Times New Roman Greek;}{\f48\fbidi \froman\fcharset162\fprq2 Times New Roman Tur;}{\f49\fbidi \froman\fcharset177\fprq2 Times New Roman (Hebrew);}{\f50\fbidi \froman\fcharset178\fprq2 Times New Roman (Arabic);}
+{\f51\fbidi \froman\fcharset186\fprq2 Times New Roman Baltic;}{\f52\fbidi \froman\fcharset163\fprq2 Times New Roman (Vietnamese);}{\f384\fbidi \froman\fcharset238\fprq2 Cambria Math CE;}{\f385\fbidi \froman\fcharset204\fprq2 Cambria Math Cyr;}
+{\f387\fbidi \froman\fcharset161\fprq2 Cambria Math Greek;}{\f388\fbidi \froman\fcharset162\fprq2 Cambria Math Tur;}{\f391\fbidi \froman\fcharset186\fprq2 Cambria Math Baltic;}{\f392\fbidi \froman\fcharset163\fprq2 Cambria Math (Vietnamese);}
+{\f414\fbidi \fswiss\fcharset238\fprq2 Calibri CE;}{\f415\fbidi \fswiss\fcharset204\fprq2 Calibri Cyr;}{\f417\fbidi \fswiss\fcharset161\fprq2 Calibri Greek;}{\f418\fbidi \fswiss\fcharset162\fprq2 Calibri Tur;}
+{\f419\fbidi \fswiss\fcharset177\fprq2 Calibri (Hebrew);}{\f420\fbidi \fswiss\fcharset178\fprq2 Calibri (Arabic);}{\f421\fbidi \fswiss\fcharset186\fprq2 Calibri Baltic;}{\f422\fbidi \fswiss\fcharset163\fprq2 Calibri (Vietnamese);}
+{\f424\fbidi \fswiss\fcharset238\fprq2 Calibri Light CE;}{\f425\fbidi \fswiss\fcharset204\fprq2 Calibri Light Cyr;}{\f427\fbidi \fswiss\fcharset161\fprq2 Calibri Light Greek;}{\f428\fbidi \fswiss\fcharset162\fprq2 Calibri Light Tur;}
+{\f429\fbidi \fswiss\fcharset177\fprq2 Calibri Light (Hebrew);}{\f430\fbidi \fswiss\fcharset178\fprq2 Calibri Light (Arabic);}{\f431\fbidi \fswiss\fcharset186\fprq2 Calibri Light Baltic;}{\f432\fbidi \fswiss\fcharset163\fprq2 Calibri Light (Vietnamese);}
+{\flomajor\f31508\fbidi \froman\fcharset238\fprq2 Times New Roman CE;}{\flomajor\f31509\fbidi \froman\fcharset204\fprq2 Times New Roman Cyr;}{\flomajor\f31511\fbidi \froman\fcharset161\fprq2 Times New Roman Greek;}
+{\flomajor\f31512\fbidi \froman\fcharset162\fprq2 Times New Roman Tur;}{\flomajor\f31513\fbidi \froman\fcharset177\fprq2 Times New Roman (Hebrew);}{\flomajor\f31514\fbidi \froman\fcharset178\fprq2 Times New Roman (Arabic);}
+{\flomajor\f31515\fbidi \froman\fcharset186\fprq2 Times New Roman Baltic;}{\flomajor\f31516\fbidi \froman\fcharset163\fprq2 Times New Roman (Vietnamese);}{\fdbmajor\f31518\fbidi \froman\fcharset238\fprq2 Times New Roman CE;}
+{\fdbmajor\f31519\fbidi \froman\fcharset204\fprq2 Times New Roman Cyr;}{\fdbmajor\f31521\fbidi \froman\fcharset161\fprq2 Times New Roman Greek;}{\fdbmajor\f31522\fbidi \froman\fcharset162\fprq2 Times New Roman Tur;}
+{\fdbmajor\f31523\fbidi \froman\fcharset177\fprq2 Times New Roman (Hebrew);}{\fdbmajor\f31524\fbidi \froman\fcharset178\fprq2 Times New Roman (Arabic);}{\fdbmajor\f31525\fbidi \froman\fcharset186\fprq2 Times New Roman Baltic;}
+{\fdbmajor\f31526\fbidi \froman\fcharset163\fprq2 Times New Roman (Vietnamese);}{\fhimajor\f31528\fbidi \fswiss\fcharset238\fprq2 Calibri Light CE;}{\fhimajor\f31529\fbidi \fswiss\fcharset204\fprq2 Calibri Light Cyr;}
+{\fhimajor\f31531\fbidi \fswiss\fcharset161\fprq2 Calibri Light Greek;}{\fhimajor\f31532\fbidi \fswiss\fcharset162\fprq2 Calibri Light Tur;}{\fhimajor\f31533\fbidi \fswiss\fcharset177\fprq2 Calibri Light (Hebrew);}
+{\fhimajor\f31534\fbidi \fswiss\fcharset178\fprq2 Calibri Light (Arabic);}{\fhimajor\f31535\fbidi \fswiss\fcharset186\fprq2 Calibri Light Baltic;}{\fhimajor\f31536\fbidi \fswiss\fcharset163\fprq2 Calibri Light (Vietnamese);}
+{\fbimajor\f31538\fbidi \froman\fcharset238\fprq2 Times New Roman CE;}{\fbimajor\f31539\fbidi \froman\fcharset204\fprq2 Times New Roman Cyr;}{\fbimajor\f31541\fbidi \froman\fcharset161\fprq2 Times New Roman Greek;}
+{\fbimajor\f31542\fbidi \froman\fcharset162\fprq2 Times New Roman Tur;}{\fbimajor\f31543\fbidi \froman\fcharset177\fprq2 Times New Roman (Hebrew);}{\fbimajor\f31544\fbidi \froman\fcharset178\fprq2 Times New Roman (Arabic);}
+{\fbimajor\f31545\fbidi \froman\fcharset186\fprq2 Times New Roman Baltic;}{\fbimajor\f31546\fbidi \froman\fcharset163\fprq2 Times New Roman (Vietnamese);}{\flominor\f31548\fbidi \froman\fcharset238\fprq2 Times New Roman CE;}
+{\flominor\f31549\fbidi \froman\fcharset204\fprq2 Times New Roman Cyr;}{\flominor\f31551\fbidi \froman\fcharset161\fprq2 Times New Roman Greek;}{\flominor\f31552\fbidi \froman\fcharset162\fprq2 Times New Roman Tur;}
+{\flominor\f31553\fbidi \froman\fcharset177\fprq2 Times New Roman (Hebrew);}{\flominor\f31554\fbidi \froman\fcharset178\fprq2 Times New Roman (Arabic);}{\flominor\f31555\fbidi \froman\fcharset186\fprq2 Times New Roman Baltic;}
+{\flominor\f31556\fbidi \froman\fcharset163\fprq2 Times New Roman (Vietnamese);}{\fdbminor\f31558\fbidi \froman\fcharset238\fprq2 Times New Roman CE;}{\fdbminor\f31559\fbidi \froman\fcharset204\fprq2 Times New Roman Cyr;}
+{\fdbminor\f31561\fbidi \froman\fcharset161\fprq2 Times New Roman Greek;}{\fdbminor\f31562\fbidi \froman\fcharset162\fprq2 Times New Roman Tur;}{\fdbminor\f31563\fbidi \froman\fcharset177\fprq2 Times New Roman (Hebrew);}
+{\fdbminor\f31564\fbidi \froman\fcharset178\fprq2 Times New Roman (Arabic);}{\fdbminor\f31565\fbidi \froman\fcharset186\fprq2 Times New Roman Baltic;}{\fdbminor\f31566\fbidi \froman\fcharset163\fprq2 Times New Roman (Vietnamese);}
+{\fhiminor\f31568\fbidi \fswiss\fcharset238\fprq2 Calibri CE;}{\fhiminor\f31569\fbidi \fswiss\fcharset204\fprq2 Calibri Cyr;}{\fhiminor\f31571\fbidi \fswiss\fcharset161\fprq2 Calibri Greek;}{\fhiminor\f31572\fbidi \fswiss\fcharset162\fprq2 Calibri Tur;}
+{\fhiminor\f31573\fbidi \fswiss\fcharset177\fprq2 Calibri (Hebrew);}{\fhiminor\f31574\fbidi \fswiss\fcharset178\fprq2 Calibri (Arabic);}{\fhiminor\f31575\fbidi \fswiss\fcharset186\fprq2 Calibri Baltic;}
+{\fhiminor\f31576\fbidi \fswiss\fcharset163\fprq2 Calibri (Vietnamese);}{\fbiminor\f31578\fbidi \froman\fcharset238\fprq2 Times New Roman CE;}{\fbiminor\f31579\fbidi \froman\fcharset204\fprq2 Times New Roman Cyr;}
+{\fbiminor\f31581\fbidi \froman\fcharset161\fprq2 Times New Roman Greek;}{\fbiminor\f31582\fbidi \froman\fcharset162\fprq2 Times New Roman Tur;}{\fbiminor\f31583\fbidi \froman\fcharset177\fprq2 Times New Roman (Hebrew);}
+{\fbiminor\f31584\fbidi \froman\fcharset178\fprq2 Times New Roman (Arabic);}{\fbiminor\f31585\fbidi \froman\fcharset186\fprq2 Times New Roman Baltic;}{\fbiminor\f31586\fbidi \froman\fcharset163\fprq2 Times New Roman (Vietnamese);}}
+{\colortbl;\red0\green0\blue0;\red0\green0\blue255;\red0\green255\blue255;\red0\green255\blue0;\red255\green0\blue255;\red255\green0\blue0;\red255\green255\blue0;\red255\green255\blue255;\red0\green0\blue128;\red0\green128\blue128;\red0\green128\blue0;
+\red128\green0\blue128;\red128\green0\blue0;\red128\green128\blue0;\red128\green128\blue128;\red192\green192\blue192;\red0\green0\blue0;\red0\green0\blue0;\caccentone\ctint255\cshade191\red47\green84\blue150;
+\caccentone\ctint255\cshade127\red31\green55\blue99;}{\*\defchp \f31506\fs22 }{\*\defpap \ql \li0\ri0\sa160\sl259\slmult1\widctlpar\wrapdefault\aspalpha\aspnum\faauto\adjustright\rin0\lin0\itap0 }\noqfpromote {\stylesheet{\ql \li0\ri0\sa160\sl259\slmult1
+\widctlpar\wrapdefault\aspalpha\aspnum\faauto\adjustright\rin0\lin0\itap0 \rtlch\fcs1 \af31507\afs22\alang1025 \ltrch\fcs0 \f31506\fs22\lang1033\langfe1033\cgrid\langnp1033\langfenp1033 \snext0 \sqformat \spriority0 Normal;}{
+\s1\ql \li0\ri0\sb240\sl259\slmult1\keep\keepn\widctlpar\wrapdefault\aspalpha\aspnum\faauto\outlinelevel0\adjustright\rin0\lin0\itap0 \rtlch\fcs1 \af31503\afs32\alang1025 \ltrch\fcs0 
+\fs32\cf19\lang1033\langfe1033\loch\f31502\hich\af31502\dbch\af31501\cgrid\langnp1033\langfenp1033 \sbasedon0 \snext0 \slink15 \sqformat \spriority9 \styrsid2496039 heading 1;}{\s2\ql \li0\ri0\sb40\sl259\slmult1
+\keep\keepn\widctlpar\wrapdefault\aspalpha\aspnum\faauto\outlinelevel1\adjustright\rin0\lin0\itap0 \rtlch\fcs1 \af31503\afs26\alang1025 \ltrch\fcs0\b\fs26\cf19\lang1033\langfe1033\loch\f31502\hich\af31502\dbch\af31501\cgrid\langnp1033\langfenp1033 
+\sbasedon0 \snext0 \slink16 \sunhideused \sqformat \spriority9 \styrsid2496039 heading 2;}{\s3\ql \li0\ri0\sb40\sl259\slmult1\keep\keepn\widctlpar\wrapdefault\aspalpha\aspnum\faauto\outlinelevel2\adjustright\rin0\lin0\itap0 \rtlch\fcs1 
+\af31503\afs24\alang1025 \ltrch\fcs0 \fs24\cf20\lang1033\langfe1033\loch\f31502\hich\af31502\dbch\af31501\cgrid\langnp1033\langfenp1033 \sbasedon0 \snext0 \slink17 \sunhideused \sqformat \spriority9 \styrsid2496039 heading 3;}{\*\cs10 \additive 
+\ssemihidden \sunhideused \spriority1 Default Paragraph Font;}{\*\ts11\tsrowd\trftsWidthB3\trpaddl108\trpaddr108\trpaddfl3\trpaddft3\trpaddfb3\trpaddfr3\tblind0\tblindtype3\tsvertalt\tsbrdrt\tsbrdrl\tsbrdrb\tsbrdrr\tsbrdrdgl\tsbrdrdgr\tsbrdrh\tsbrdrv 
+\ql \li0\ri0\sa160\sl259\slmult1\widctlpar\wrapdefault\aspalpha\aspnum\faauto\adjustright\rin0\lin0\itap0 \rtlch\fcs1 \af31507\afs22\alang1025 \ltrch\fcs0 \f31506\fs22\lang1033\langfe1033\cgrid\langnp1033\langfenp1033 \snext11 \ssemihidden \sunhideused 
+Normal Table;}{\*\cs15 \additive \rtlch\fcs1 \af31503\afs32 \ltrch\fcs0 \fs32\cf19\loch\f31502\hich\af31502\dbch\af31501 \sbasedon10 \slink1 \slocked \spriority9 \styrsid2496039 Heading 1 Char;}{\*\cs16 \additive \rtlch\fcs1 \af31503\afs26 \ltrch\fcs0 
+\fs26\cf19\loch\f31502\hich\af31502\dbch\af31501 \sbasedon10 \slink2 \slocked \spriority9 \styrsid2496039 Heading 2 Char;}{\*\cs17 \additive \rtlch\fcs1 \af31503\afs24 \ltrch\fcs0 \fs24\cf20\loch\f31502\hich\af31502\dbch\af31501 
+\sbasedon10 \slink3 \slocked \spriority9 \styrsid2496039 Heading 3 Char;}}{\*\rsidtbl \rsid1718450\rsid2496039\rsid2631807\rsid4616182\rsid10489260}{\mmathPr\mmathFont34\mbrkBin0\mbrkBinSub0\msmallFrac0\mdispDef1\mlMargin0\mrMargin0\mdefJc1
+\mwrapIndent1440\mintLim0\mnaryLim1}
+{\*\xmlnstbl {\xmlns1 http://schemas.microsoft.com/office/word/2003/wordml}}\paperw12240\paperh15840\margl1440\margr1440\margt1440\margb1440\gutter0\ltrsect 
+\widowctrl\ftnbj\aenddoc\trackmoves0\trackformatting1\donotembedsysfont1\relyonvml0\donotembedlingdata0\grfdocevents0\validatexml1\showplaceholdtext0\ignoremixedcontent0\saveinvalidxml0\showxmlerrors1\noxlattoyen
+\expshrtn\noultrlspc\dntblnsbdb\nospaceforul\formshade\horzdoc\dgmargin\dghspace180\dgvspace180\dghorigin1440\dgvorigin1440\dghshow1\dgvshow1
+\jexpand\viewkind1\viewscale100\pgbrdrhead\pgbrdrfoot\splytwnine\ftnlytwnine\htmautsp\nolnhtadjtbl\useltbaln\alntblind\lytcalctblwd\lyttblrtgr\lnbrkrule\nobrkwrptbl\snaptogridincell\allowfieldendsel\wrppunct
+\asianbrkrule\rsidroot2496039\newtblstyruls\nogrowautofit\usenormstyforlist\noindnmbrts\felnbrelev\nocxsptable\indrlsweleven\noafcnsttbl\afelev\utinl\hwelev\spltpgpar\notcvasp\notbrkcnstfrctbl\notvatxbx\krnprsnet\cachedcolbal \nouicompat \fet0
+{\*\wgrffmtfilter 2450}\nofeaturethrottle1\ilfomacatclnup0\ltrpar \sectd \ltrsect\linex0\endnhere\sectlinegrid360\sectdefaultcl\sftnbj {\*\pnseclvl1\pnucrm\pnstart1\pnindent720\pnhang {\pntxta .}}{\*\pnseclvl2\pnucltr\pnstart1\pnindent720\pnhang 
+{\pntxta .}}{\*\pnseclvl3\pndec\pnstart1\pnindent720\pnhang {\pntxta .}}{\*\pnseclvl4\pnlcltr\pnstart1\pnindent720\pnhang {\pntxta )}}{\*\pnseclvl5\pndec\pnstart1\pnindent720\pnhang {\pntxtb (}{\pntxta )}}{\*\pnseclvl6\pnlcltr\pnstart1\pnindent720\pnhang 
+{\pntxtb (}{\pntxta )}}{\*\pnseclvl7\pnlcrm\pnstart1\pnindent720\pnhang {\pntxtb (}{\pntxta )}}{\*\pnseclvl8\pnlcltr\pnstart1\pnindent720\pnhang {\pntxtb (}{\pntxta )}}{\*\pnseclvl9\pnlcrm\pnstart1\pnindent720\pnhang {\pntxtb (}{\pntxta )}}
+\pard\plain \ltrpar\s1\ql \li0\ri0\sb240\sl259\slmult1\keep\keepn\widctlpar\wrapdefault\aspalpha\aspnum\faauto\outlinelevel0\adjustright\rin0\lin0\itap0\pararsid2496039 \rtlch\fcs1 \af31503\afs32\alang1025 \ltrch\fcs0 
+\fs32\cf19\lang1033\langfe1033\loch\af31502\hich\af31502\dbch\af31501\cgrid\langnp1033\langfenp1033 {\rtlch\fcs1 \af31503 \ltrch\fcs0 \insrsid2496039 \hich\af31502\dbch\af31501\loch\f31502 H\hich\af31502\dbch\af31501\loch\f31502 eading 1}{\rtlch\fcs1 
+\af31503 \ltrch\fcs0 \insrsid2631807 
+\par }\pard\plain \ltrpar\s2\ql \li0\ri0\sb40\sl259\slmult1\keep\keepn\widctlpar\wrapdefault\aspalpha\aspnum\faauto\outlinelevel1\adjustright\rin0\lin0\itap0\pararsid2496039 \rtlch\fcs1 \af31503\afs26\alang1025 \ltrch\fcs0 
+\fs26\cf19\lang1033\langfe1033\loch\af31502\hich\af31502\dbch\af31501\cgrid\langnp1033\langfenp1033 {\rtlch\fcs1 \af31503 \ltrch\fcs0 \insrsid2496039 \hich\af31502\dbch\af31501\loch\f31502 H\hich\af31502\dbch\af31501\loch\f31502 eading }{\rtlch\fcs1 
+\af31503 \ltrch\fcs0 \insrsid2496039 \hich\af31502\dbch\af31501\loch\f31502 2}{\rtlch\fcs1 \af31503 \ltrch\fcs0 \insrsid2496039 
+\par }\pard\plain \ltrpar\s3\ql \li0\ri0\sb40\sl259\slmult1\keep\keepn\widctlpar\wrapdefault\aspalpha\aspnum\faauto\outlinelevel2\adjustright\rin0\lin0\itap0\pararsid2496039 \rtlch\fcs1 \af31503\afs24\alang1025 \ltrch\fcs0 
+\fs24\cf20\lang1033\langfe1033\loch\af31502\hich\af31502\dbch\af31501\cgrid\langnp1033\langfenp1033 {\rtlch\fcs1 \af31503 \ltrch\fcs0 \insrsid2496039 \hich\af31502\dbch\af31501\loch\f31502 H\hich\af31502\dbch\af31501\loch\f31502 eading }{\rtlch\fcs1 
+\af31503 \ltrch\fcs0 \insrsid2496039 \hich\af31502\dbch\af31501\loch\f31502 3}{\rtlch\fcs1 \af31503 \ltrch\fcs0 \insrsid2496039 
+\par }\pard\plain \ltrpar\ql \li0\ri0\sa160\sl259\slmult1\widctlpar\wrapdefault\aspalpha\aspnum\faauto\adjustright\rin0\lin0\itap0 \rtlch\fcs1 \af31507\afs22\alang1025 \ltrch\fcs0 \f31506\fs22\lang1033\langfe1033\cgrid\langnp1033\langfenp1033 {\rtlch\fcs1 
+\af31507 \ltrch\fcs0 \insrsid2496039 Paragraph
+\par }{\*\themedata 504b030414000600080000002100e9de0fbfff0000001c020000130000005b436f6e74656e745f54797065735d2e786d6cac91cb4ec3301045f748fc83e52d4a
+9cb2400825e982c78ec7a27cc0c8992416c9d8b2a755fbf74cd25442a820166c2cd933f79e3be372bd1f07b5c3989ca74aaff2422b24eb1b475da5df374fd9ad
+5689811a183c61a50f98f4babebc2837878049899a52a57be670674cb23d8e90721f90a4d2fa3802cb35762680fd800ecd7551dc18eb899138e3c943d7e503b6
+b01d583deee5f99824e290b4ba3f364eac4a430883b3c092d4eca8f946c916422ecab927f52ea42b89a1cd59c254f919b0e85e6535d135a8de20f20b8c12c3b0
+0c895fcf6720192de6bf3b9e89ecdbd6596cbcdd8eb28e7c365ecc4ec1ff1460f53fe813d3cc7f5b7f020000ffff0300504b030414000600080000002100a5d6
+a7e7c0000000360100000b0000005f72656c732f2e72656c73848fcf6ac3300c87ef85bd83d17d51d2c31825762fa590432fa37d00e1287f68221bdb1bebdb4f
+c7060abb0884a4eff7a93dfeae8bf9e194e720169aaa06c3e2433fcb68e1763dbf7f82c985a4a725085b787086a37bdbb55fbc50d1a33ccd311ba548b6309512
+0f88d94fbc52ae4264d1c910d24a45db3462247fa791715fd71f989e19e0364cd3f51652d73760ae8fa8c9ffb3c330cc9e4fc17faf2ce545046e37944c69e462
+a1a82fe353bd90a865aad41ed0b5b8f9d6fd010000ffff0300504b0304140006000800000021006b799616830000008a0000001c0000007468656d652f746865
+6d652f7468656d654d616e616765722e786d6c0ccc4d0ac3201040e17da17790d93763bb284562b2cbaebbf600439c1a41c7a0d29fdbd7e5e38337cedf14d59b
+4b0d592c9c070d8a65cd2e88b7f07c2ca71ba8da481cc52c6ce1c715e6e97818c9b48d13df49c873517d23d59085adb5dd20d6b52bd521ef2cdd5eb9246a3d8b
+4757e8d3f729e245eb2b260a0238fd010000ffff0300504b030414000600080000002100d3130843c40600008b1a0000160000007468656d652f7468656d652f
+7468656d65312e786d6cec595d8bdb46147d2ff43f08bd3bfe92fcb1c41b6cd9ceb6d94d42eca4e4716c8fadc98e344633de8d0981923c160aa569e943037deb
+43691b48a02fe9afd936a54d217fa17746b63c638fbb9b2585a5640d8b343af7ce997bafce1d4997afdc8fa87384134e58dc708b970aae83e3211b9178d2706f
+f7bbb99aeb7081e211a22cc60d778eb97b65f7c30f2ea31d11e2083b601ff31dd4704321a63bf93c1fc230e297d814c7706dcc920809384d26f951828ec16f44
+f3a542a1928f10895d274611b8bd311e932176fad2a5bbbb74dea1701a0b2e078634e949d7d8b050d8d1615122f89c0734718e106db830cf881df7f17de13a14
+7101171a6e41fdb9f9ddcb79b4b330a2628bad66d7557f0bbb85c1e8b0a4e64c26836c52cff3bd4a33f3af00546ce23ad54ea553c9fc29001a0e61a52917d367
+b514780bac064a0f2dbedbd576b968e035ffe50dce4d5ffe0cbc02a5febd0d7cb71b40140dbc02a5787f03efb7eaadb6e95f81527c65035f2d34db5ed5f0af40
+2125f1e106bae057cac172b51964cce89e155ef7bd6eb5b470be42413564d525a718b3586cabb508dd6349170012489120b123e6533c4643a8e20051324888b3
+4f262114de14c58cc370a154e816caf05ffe3c75a4328a7630d2ac252f60c23786241f870f1332150df763f0ea6a90372f7f7cf3f2b973f2e8c5c9a35f4e1e3f
+3e79f473eac8b0da43f144b77afdfd177f3ffdd4f9ebf977af9f7c65c7731dfffb4f9ffdf6eb977620ac741582575f3ffbe3c5b357df7cfee70f4f2cf0668206
+3abc4f22cc9debf8d8b9c52258980a81c91c0f92b7b3e88788e816cd78c2518ce42c16ff1d111ae8eb73449105d7c26604ef24203136e0d5d93d83702f4c6682
+583c5e0b230378c0186db1c41a856b722e2dccfd593cb14f9ecc74dc2d848e6c73072836f2db994d415b89cd65106283e64d8a62812638c6c291d7d821c696d5
+dd25c488eb0119268cb3b170ee12a7858835247d3230aa6965b44722c8cbdc4610f26dc4e6e08ed362d4b6ea363e32917057206a21dfc7d408e355341328b2b9
+eca388ea01df4722b491eccd93a18eeb7001999e60ca9cce08736eb3b991c07ab5a45f0379b1a7fd80ce231399087268f3b98f18d3916d761884289adab03d12
+873af6237e08258a9c9b4cd8e007ccbc43e439e401c55bd37d876023dda7abc16d50569dd2aa40e4955962c9e555cc8cfaedcde91861253520fc869e47243e55
+dcd764ddff6f651d84f4d5b74f2dabbaa882de4c88f58eda5b93f16db875f10e583222175fbbdb6816dfc470bb6c36b0f7d2fd5ebaddffbd746fbb9fdfbd60af
+341ae45b6e15d3adbadab8475bf7ed6342694fcc29dee76aebcea1338dba3028edd4332bce9ee3a6211cca3b192630709304291b2761e21322c25e88a6b0bf2f
+bad2c9842f5c4fb833651cb6fd6ad8ea5be2e92c3a60a3f471b558948fa6a978702456e3053f1b87470d91a22bd5d52358e65eb19da847e5250169fb3624b4c9
+4c12650b89ea725006493d9843d02c24d4cade098bba85454dba5fa66a830550cbb2025b2707365c0dd7f7c0048ce0890a513c92794a53bdccae4ae6bbccf4b6
+601a1500fb886505ac325d975cb72e4fae2e2db53364da20a1959b49424546f5301ea2115e54a71c3d0b8db7cd757d9552839e0c859a0f4a6b45a35afb3716e7
+cd35d8ad6b038d75a5a0b173dc702b651f4a6688a60d770c8ffd70184da176b8dcf2223a8177674391a437fc7994659a70d1463c4c03ae4427558388089c3894
+440d572e3f4b038d9586286ec51208c28525570759b968e420e96692f1788c87424fbb3622239d9e82c2a75a61bdaacccf0f96966c06e9ee85a363674067c92d
+0425e6578b328023c2e1ed4f318de688c0ebcc4cc856f5b7d69816b2abbf4f5435948e233a0dd1a2a3e8629ec295946774d4591603ed6cb16608a8169245231c
+4c6483d5836a74d3ac6ba41cb676ddd38d64e434d15cf54c435564d7b4ab9831c3b20dacc5f27c4d5e63b50c31689adee153e95e97dcfa52ebd6f60959978080
+67f1b374dd3334048dda6a32839a64bc29c352b317a366ef582ef0146a6769129aea57966ed7e296f508eb743078aece0f76eb550b43e3e5be52455a7df7d03f
+4db0c13d108f36bc049e51c1552ae1c343826043d4537b925436e016b92f16b7061c39b38434dc0705bfe905253fc8156a7e27e795bd42aee637cbb9a6ef978b
+1dbf5868b74a0fa1b188302afae937972ebc8aa2f3c5971735bef1f5255abe6dbb3464519ea9af2b79455c7d7d2996b67f7d710888ce834aa95b2fd75b955cbd
+dcece6bc76ab96ab079556ae5d09aaed6e3bf06bf5ee43d7395260af590ebc4aa796ab148320e7550a927ead9eab7aa552d3ab366b1daff970b18d8195a7f2b1
+88058457f1dafd070000ffff0300504b0304140006000800000021000dd1909fb60000001b010000270000007468656d652f7468656d652f5f72656c732f7468
+656d654d616e616765722e786d6c2e72656c73848f4d0ac2301484f78277086f6fd3ba109126dd88d0add40384e4350d363f2451eced0dae2c082e8761be9969
+bb979dc9136332de3168aa1a083ae995719ac16db8ec8e4052164e89d93b64b060828e6f37ed1567914b284d262452282e3198720e274a939cd08a54f980ae38
+a38f56e422a3a641c8bbd048f7757da0f19b017cc524bd62107bd5001996509affb3fd381a89672f1f165dfe514173d9850528a2c6cce0239baa4c04ca5bbaba
+c4df000000ffff0300504b01022d0014000600080000002100e9de0fbfff0000001c0200001300000000000000000000000000000000005b436f6e74656e745f
+54797065735d2e786d6c504b01022d0014000600080000002100a5d6a7e7c0000000360100000b00000000000000000000000000300100005f72656c732f2e72
+656c73504b01022d00140006000800000021006b799616830000008a0000001c00000000000000000000000000190200007468656d652f7468656d652f746865
+6d654d616e616765722e786d6c504b01022d0014000600080000002100d3130843c40600008b1a00001600000000000000000000000000d60200007468656d65
+2f7468656d652f7468656d65312e786d6c504b01022d00140006000800000021000dd1909fb60000001b0100002700000000000000000000000000ce0900007468656d652f7468656d652f5f72656c732f7468656d654d616e616765722e786d6c2e72656c73504b050600000000050005005d010000c90a00000000}
+{\*\colorschememapping 3c3f786d6c2076657273696f6e3d22312e302220656e636f64696e673d225554462d3822207374616e64616c6f6e653d22796573223f3e0d0a3c613a636c724d
+617020786d6c6e733a613d22687474703a2f2f736368656d61732e6f70656e786d6c666f726d6174732e6f72672f64726177696e676d6c2f323030362f6d6169
+6e22206267313d226c743122207478313d22646b3122206267323d226c743222207478323d22646b322220616363656e74313d22616363656e74312220616363
+656e74323d22616363656e74322220616363656e74333d22616363656e74332220616363656e74343d22616363656e74342220616363656e74353d22616363656e74352220616363656e74363d22616363656e74362220686c696e6b3d22686c696e6b2220666f6c486c696e6b3d22666f6c486c696e6b222f3e}
+{\*\latentstyles\lsdstimax375\lsdlockeddef0\lsdsemihiddendef0\lsdunhideuseddef0\lsdqformatdef0\lsdprioritydef99{\lsdlockedexcept \lsdqformat1 \lsdpriority0 \lsdlocked0 Normal;\lsdqformat1 \lsdpriority9 \lsdlocked0 heading 1;
+\lsdsemihidden1 \lsdunhideused1 \lsdqformat1 \lsdpriority9 \lsdlocked0 heading 2;\lsdsemihidden1 \lsdunhideused1 \lsdqformat1 \lsdpriority9 \lsdlocked0 heading 3;\lsdsemihidden1 \lsdunhideused1 \lsdqformat1 \lsdpriority9 \lsdlocked0 heading 4;
+\lsdsemihidden1 \lsdunhideused1 \lsdqformat1 \lsdpriority9 \lsdlocked0 heading 5;\lsdsemihidden1 \lsdunhideused1 \lsdqformat1 \lsdpriority9 \lsdlocked0 heading 6;\lsdsemihidden1 \lsdunhideused1 \lsdqformat1 \lsdpriority9 \lsdlocked0 heading 7;
+\lsdsemihidden1 \lsdunhideused1 \lsdqformat1 \lsdpriority9 \lsdlocked0 heading 8;\lsdsemihidden1 \lsdunhideused1 \lsdqformat1 \lsdpriority9 \lsdlocked0 heading 9;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 index 1;
+\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 index 2;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 index 3;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 index 4;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 index 5;
+\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 index 6;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 index 7;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 index 8;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 index 9;
+\lsdsemihidden1 \lsdunhideused1 \lsdpriority39 \lsdlocked0 toc 1;\lsdsemihidden1 \lsdunhideused1 \lsdpriority39 \lsdlocked0 toc 2;\lsdsemihidden1 \lsdunhideused1 \lsdpriority39 \lsdlocked0 toc 3;
+\lsdsemihidden1 \lsdunhideused1 \lsdpriority39 \lsdlocked0 toc 4;\lsdsemihidden1 \lsdunhideused1 \lsdpriority39 \lsdlocked0 toc 5;\lsdsemihidden1 \lsdunhideused1 \lsdpriority39 \lsdlocked0 toc 6;
+\lsdsemihidden1 \lsdunhideused1 \lsdpriority39 \lsdlocked0 toc 7;\lsdsemihidden1 \lsdunhideused1 \lsdpriority39 \lsdlocked0 toc 8;\lsdsemihidden1 \lsdunhideused1 \lsdpriority39 \lsdlocked0 toc 9;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Normal Indent;
+\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 footnote text;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 annotation text;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 header;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 footer;
+\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 index heading;\lsdsemihidden1 \lsdunhideused1 \lsdqformat1 \lsdpriority35 \lsdlocked0 caption;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 table of figures;
+\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 envelope address;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 envelope return;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 footnote reference;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 annotation reference;
+\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 line number;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 page number;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 endnote reference;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 endnote text;
+\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 table of authorities;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 macro;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 toa heading;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 List;
+\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 List Bullet;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 List Number;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 List 2;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 List 3;
+\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 List 4;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 List 5;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 List Bullet 2;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 List Bullet 3;
+\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 List Bullet 4;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 List Bullet 5;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 List Number 2;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 List Number 3;
+\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 List Number 4;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 List Number 5;\lsdqformat1 \lsdpriority10 \lsdlocked0 Title;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Closing;
+\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Signature;\lsdsemihidden1 \lsdunhideused1 \lsdpriority1 \lsdlocked0 Default Paragraph Font;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Body Text;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Body Text Indent;
+\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 List Continue;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 List Continue 2;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 List Continue 3;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 List Continue 4;
+\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 List Continue 5;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Message Header;\lsdqformat1 \lsdpriority11 \lsdlocked0 Subtitle;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Salutation;
+\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Date;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Body Text First Indent;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Body Text First Indent 2;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Note Heading;
+\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Body Text 2;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Body Text 3;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Body Text Indent 2;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Body Text Indent 3;
+\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Block Text;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Hyperlink;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 FollowedHyperlink;\lsdqformat1 \lsdpriority22 \lsdlocked0 Strong;
+\lsdqformat1 \lsdpriority20 \lsdlocked0 Emphasis;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Document Map;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Plain Text;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 E-mail Signature;
+\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 HTML Top of Form;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 HTML Bottom of Form;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Normal (Web);\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 HTML Acronym;
+\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 HTML Address;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 HTML Cite;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 HTML Code;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 HTML Definition;
+\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 HTML Keyboard;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 HTML Preformatted;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 HTML Sample;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 HTML Typewriter;
+\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 HTML Variable;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Normal Table;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 annotation subject;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 No List;
+\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Outline List 1;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Outline List 2;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Outline List 3;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Table Simple 1;
+\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Table Simple 2;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Table Simple 3;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Table Classic 1;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Table Classic 2;
+\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Table Classic 3;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Table Classic 4;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Table Colorful 1;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Table Colorful 2;
+\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Table Colorful 3;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Table Columns 1;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Table Columns 2;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Table Columns 3;
+\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Table Columns 4;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Table Columns 5;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Table Grid 1;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Table Grid 2;
+\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Table Grid 3;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Table Grid 4;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Table Grid 5;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Table Grid 6;
+\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Table Grid 7;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Table Grid 8;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Table List 1;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Table List 2;
+\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Table List 3;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Table List 4;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Table List 5;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Table List 6;
+\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Table List 7;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Table List 8;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Table 3D effects 1;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Table 3D effects 2;
+\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Table 3D effects 3;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Table Contemporary;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Table Elegant;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Table Professional;
+\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Table Subtle 1;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Table Subtle 2;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Table Web 1;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Table Web 2;
+\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Table Web 3;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Balloon Text;\lsdpriority39 \lsdlocked0 Table Grid;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Table Theme;\lsdsemihidden1 \lsdlocked0 Placeholder Text;
+\lsdqformat1 \lsdpriority1 \lsdlocked0 No Spacing;\lsdpriority60 \lsdlocked0 Light Shading;\lsdpriority61 \lsdlocked0 Light List;\lsdpriority62 \lsdlocked0 Light Grid;\lsdpriority63 \lsdlocked0 Medium Shading 1;\lsdpriority64 \lsdlocked0 Medium Shading 2;
+\lsdpriority65 \lsdlocked0 Medium List 1;\lsdpriority66 \lsdlocked0 Medium List 2;\lsdpriority67 \lsdlocked0 Medium Grid 1;\lsdpriority68 \lsdlocked0 Medium Grid 2;\lsdpriority69 \lsdlocked0 Medium Grid 3;\lsdpriority70 \lsdlocked0 Dark List;
+\lsdpriority71 \lsdlocked0 Colorful Shading;\lsdpriority72 \lsdlocked0 Colorful List;\lsdpriority73 \lsdlocked0 Colorful Grid;\lsdpriority60 \lsdlocked0 Light Shading Accent 1;\lsdpriority61 \lsdlocked0 Light List Accent 1;
+\lsdpriority62 \lsdlocked0 Light Grid Accent 1;\lsdpriority63 \lsdlocked0 Medium Shading 1 Accent 1;\lsdpriority64 \lsdlocked0 Medium Shading 2 Accent 1;\lsdpriority65 \lsdlocked0 Medium List 1 Accent 1;\lsdsemihidden1 \lsdlocked0 Revision;
+\lsdqformat1 \lsdpriority34 \lsdlocked0 List Paragraph;\lsdqformat1 \lsdpriority29 \lsdlocked0 Quote;\lsdqformat1 \lsdpriority30 \lsdlocked0 Intense Quote;\lsdpriority66 \lsdlocked0 Medium List 2 Accent 1;\lsdpriority67 \lsdlocked0 Medium Grid 1 Accent 1;
+\lsdpriority68 \lsdlocked0 Medium Grid 2 Accent 1;\lsdpriority69 \lsdlocked0 Medium Grid 3 Accent 1;\lsdpriority70 \lsdlocked0 Dark List Accent 1;\lsdpriority71 \lsdlocked0 Colorful Shading Accent 1;\lsdpriority72 \lsdlocked0 Colorful List Accent 1;
+\lsdpriority73 \lsdlocked0 Colorful Grid Accent 1;\lsdpriority60 \lsdlocked0 Light Shading Accent 2;\lsdpriority61 \lsdlocked0 Light List Accent 2;\lsdpriority62 \lsdlocked0 Light Grid Accent 2;\lsdpriority63 \lsdlocked0 Medium Shading 1 Accent 2;
+\lsdpriority64 \lsdlocked0 Medium Shading 2 Accent 2;\lsdpriority65 \lsdlocked0 Medium List 1 Accent 2;\lsdpriority66 \lsdlocked0 Medium List 2 Accent 2;\lsdpriority67 \lsdlocked0 Medium Grid 1 Accent 2;\lsdpriority68 \lsdlocked0 Medium Grid 2 Accent 2;
+\lsdpriority69 \lsdlocked0 Medium Grid 3 Accent 2;\lsdpriority70 \lsdlocked0 Dark List Accent 2;\lsdpriority71 \lsdlocked0 Colorful Shading Accent 2;\lsdpriority72 \lsdlocked0 Colorful List Accent 2;\lsdpriority73 \lsdlocked0 Colorful Grid Accent 2;
+\lsdpriority60 \lsdlocked0 Light Shading Accent 3;\lsdpriority61 \lsdlocked0 Light List Accent 3;\lsdpriority62 \lsdlocked0 Light Grid Accent 3;\lsdpriority63 \lsdlocked0 Medium Shading 1 Accent 3;\lsdpriority64 \lsdlocked0 Medium Shading 2 Accent 3;
+\lsdpriority65 \lsdlocked0 Medium List 1 Accent 3;\lsdpriority66 \lsdlocked0 Medium List 2 Accent 3;\lsdpriority67 \lsdlocked0 Medium Grid 1 Accent 3;\lsdpriority68 \lsdlocked0 Medium Grid 2 Accent 3;\lsdpriority69 \lsdlocked0 Medium Grid 3 Accent 3;
+\lsdpriority70 \lsdlocked0 Dark List Accent 3;\lsdpriority71 \lsdlocked0 Colorful Shading Accent 3;\lsdpriority72 \lsdlocked0 Colorful List Accent 3;\lsdpriority73 \lsdlocked0 Colorful Grid Accent 3;\lsdpriority60 \lsdlocked0 Light Shading Accent 4;
+\lsdpriority61 \lsdlocked0 Light List Accent 4;\lsdpriority62 \lsdlocked0 Light Grid Accent 4;\lsdpriority63 \lsdlocked0 Medium Shading 1 Accent 4;\lsdpriority64 \lsdlocked0 Medium Shading 2 Accent 4;\lsdpriority65 \lsdlocked0 Medium List 1 Accent 4;
+\lsdpriority66 \lsdlocked0 Medium List 2 Accent 4;\lsdpriority67 \lsdlocked0 Medium Grid 1 Accent 4;\lsdpriority68 \lsdlocked0 Medium Grid 2 Accent 4;\lsdpriority69 \lsdlocked0 Medium Grid 3 Accent 4;\lsdpriority70 \lsdlocked0 Dark List Accent 4;
+\lsdpriority71 \lsdlocked0 Colorful Shading Accent 4;\lsdpriority72 \lsdlocked0 Colorful List Accent 4;\lsdpriority73 \lsdlocked0 Colorful Grid Accent 4;\lsdpriority60 \lsdlocked0 Light Shading Accent 5;\lsdpriority61 \lsdlocked0 Light List Accent 5;
+\lsdpriority62 \lsdlocked0 Light Grid Accent 5;\lsdpriority63 \lsdlocked0 Medium Shading 1 Accent 5;\lsdpriority64 \lsdlocked0 Medium Shading 2 Accent 5;\lsdpriority65 \lsdlocked0 Medium List 1 Accent 5;\lsdpriority66 \lsdlocked0 Medium List 2 Accent 5;
+\lsdpriority67 \lsdlocked0 Medium Grid 1 Accent 5;\lsdpriority68 \lsdlocked0 Medium Grid 2 Accent 5;\lsdpriority69 \lsdlocked0 Medium Grid 3 Accent 5;\lsdpriority70 \lsdlocked0 Dark List Accent 5;\lsdpriority71 \lsdlocked0 Colorful Shading Accent 5;
+\lsdpriority72 \lsdlocked0 Colorful List Accent 5;\lsdpriority73 \lsdlocked0 Colorful Grid Accent 5;\lsdpriority60 \lsdlocked0 Light Shading Accent 6;\lsdpriority61 \lsdlocked0 Light List Accent 6;\lsdpriority62 \lsdlocked0 Light Grid Accent 6;
+\lsdpriority63 \lsdlocked0 Medium Shading 1 Accent 6;\lsdpriority64 \lsdlocked0 Medium Shading 2 Accent 6;\lsdpriority65 \lsdlocked0 Medium List 1 Accent 6;\lsdpriority66 \lsdlocked0 Medium List 2 Accent 6;
+\lsdpriority67 \lsdlocked0 Medium Grid 1 Accent 6;\lsdpriority68 \lsdlocked0 Medium Grid 2 Accent 6;\lsdpriority69 \lsdlocked0 Medium Grid 3 Accent 6;\lsdpriority70 \lsdlocked0 Dark List Accent 6;\lsdpriority71 \lsdlocked0 Colorful Shading Accent 6;
+\lsdpriority72 \lsdlocked0 Colorful List Accent 6;\lsdpriority73 \lsdlocked0 Colorful Grid Accent 6;\lsdqformat1 \lsdpriority19 \lsdlocked0 Subtle Emphasis;\lsdqformat1 \lsdpriority21 \lsdlocked0 Intense Emphasis;
+\lsdqformat1 \lsdpriority31 \lsdlocked0 Subtle Reference;\lsdqformat1 \lsdpriority32 \lsdlocked0 Intense Reference;\lsdqformat1 \lsdpriority33 \lsdlocked0 Book Title;\lsdsemihidden1 \lsdunhideused1 \lsdpriority37 \lsdlocked0 Bibliography;
+\lsdsemihidden1 \lsdunhideused1 \lsdqformat1 \lsdpriority39 \lsdlocked0 TOC Heading;\lsdpriority41 \lsdlocked0 Plain Table 1;\lsdpriority42 \lsdlocked0 Plain Table 2;\lsdpriority43 \lsdlocked0 Plain Table 3;\lsdpriority44 \lsdlocked0 Plain Table 4;
+\lsdpriority45 \lsdlocked0 Plain Table 5;\lsdpriority40 \lsdlocked0 Grid Table Light;\lsdpriority46 \lsdlocked0 Grid Table 1 Light;\lsdpriority47 \lsdlocked0 Grid Table 2;\lsdpriority48 \lsdlocked0 Grid Table 3;\lsdpriority49 \lsdlocked0 Grid Table 4;
+\lsdpriority50 \lsdlocked0 Grid Table 5 Dark;\lsdpriority51 \lsdlocked0 Grid Table 6 Colorful;\lsdpriority52 \lsdlocked0 Grid Table 7 Colorful;\lsdpriority46 \lsdlocked0 Grid Table 1 Light Accent 1;\lsdpriority47 \lsdlocked0 Grid Table 2 Accent 1;
+\lsdpriority48 \lsdlocked0 Grid Table 3 Accent 1;\lsdpriority49 \lsdlocked0 Grid Table 4 Accent 1;\lsdpriority50 \lsdlocked0 Grid Table 5 Dark Accent 1;\lsdpriority51 \lsdlocked0 Grid Table 6 Colorful Accent 1;
+\lsdpriority52 \lsdlocked0 Grid Table 7 Colorful Accent 1;\lsdpriority46 \lsdlocked0 Grid Table 1 Light Accent 2;\lsdpriority47 \lsdlocked0 Grid Table 2 Accent 2;\lsdpriority48 \lsdlocked0 Grid Table 3 Accent 2;
+\lsdpriority49 \lsdlocked0 Grid Table 4 Accent 2;\lsdpriority50 \lsdlocked0 Grid Table 5 Dark Accent 2;\lsdpriority51 \lsdlocked0 Grid Table 6 Colorful Accent 2;\lsdpriority52 \lsdlocked0 Grid Table 7 Colorful Accent 2;
+\lsdpriority46 \lsdlocked0 Grid Table 1 Light Accent 3;\lsdpriority47 \lsdlocked0 Grid Table 2 Accent 3;\lsdpriority48 \lsdlocked0 Grid Table 3 Accent 3;\lsdpriority49 \lsdlocked0 Grid Table 4 Accent 3;
+\lsdpriority50 \lsdlocked0 Grid Table 5 Dark Accent 3;\lsdpriority51 \lsdlocked0 Grid Table 6 Colorful Accent 3;\lsdpriority52 \lsdlocked0 Grid Table 7 Colorful Accent 3;\lsdpriority46 \lsdlocked0 Grid Table 1 Light Accent 4;
+\lsdpriority47 \lsdlocked0 Grid Table 2 Accent 4;\lsdpriority48 \lsdlocked0 Grid Table 3 Accent 4;\lsdpriority49 \lsdlocked0 Grid Table 4 Accent 4;\lsdpriority50 \lsdlocked0 Grid Table 5 Dark Accent 4;
+\lsdpriority51 \lsdlocked0 Grid Table 6 Colorful Accent 4;\lsdpriority52 \lsdlocked0 Grid Table 7 Colorful Accent 4;\lsdpriority46 \lsdlocked0 Grid Table 1 Light Accent 5;\lsdpriority47 \lsdlocked0 Grid Table 2 Accent 5;
+\lsdpriority48 \lsdlocked0 Grid Table 3 Accent 5;\lsdpriority49 \lsdlocked0 Grid Table 4 Accent 5;\lsdpriority50 \lsdlocked0 Grid Table 5 Dark Accent 5;\lsdpriority51 \lsdlocked0 Grid Table 6 Colorful Accent 5;
+\lsdpriority52 \lsdlocked0 Grid Table 7 Colorful Accent 5;\lsdpriority46 \lsdlocked0 Grid Table 1 Light Accent 6;\lsdpriority47 \lsdlocked0 Grid Table 2 Accent 6;\lsdpriority48 \lsdlocked0 Grid Table 3 Accent 6;
+\lsdpriority49 \lsdlocked0 Grid Table 4 Accent 6;\lsdpriority50 \lsdlocked0 Grid Table 5 Dark Accent 6;\lsdpriority51 \lsdlocked0 Grid Table 6 Colorful Accent 6;\lsdpriority52 \lsdlocked0 Grid Table 7 Colorful Accent 6;
+\lsdpriority46 \lsdlocked0 List Table 1 Light;\lsdpriority47 \lsdlocked0 List Table 2;\lsdpriority48 \lsdlocked0 List Table 3;\lsdpriority49 \lsdlocked0 List Table 4;\lsdpriority50 \lsdlocked0 List Table 5 Dark;
+\lsdpriority51 \lsdlocked0 List Table 6 Colorful;\lsdpriority52 \lsdlocked0 List Table 7 Colorful;\lsdpriority46 \lsdlocked0 List Table 1 Light Accent 1;\lsdpriority47 \lsdlocked0 List Table 2 Accent 1;\lsdpriority48 \lsdlocked0 List Table 3 Accent 1;
+\lsdpriority49 \lsdlocked0 List Table 4 Accent 1;\lsdpriority50 \lsdlocked0 List Table 5 Dark Accent 1;\lsdpriority51 \lsdlocked0 List Table 6 Colorful Accent 1;\lsdpriority52 \lsdlocked0 List Table 7 Colorful Accent 1;
+\lsdpriority46 \lsdlocked0 List Table 1 Light Accent 2;\lsdpriority47 \lsdlocked0 List Table 2 Accent 2;\lsdpriority48 \lsdlocked0 List Table 3 Accent 2;\lsdpriority49 \lsdlocked0 List Table 4 Accent 2;
+\lsdpriority50 \lsdlocked0 List Table 5 Dark Accent 2;\lsdpriority51 \lsdlocked0 List Table 6 Colorful Accent 2;\lsdpriority52 \lsdlocked0 List Table 7 Colorful Accent 2;\lsdpriority46 \lsdlocked0 List Table 1 Light Accent 3;
+\lsdpriority47 \lsdlocked0 List Table 2 Accent 3;\lsdpriority48 \lsdlocked0 List Table 3 Accent 3;\lsdpriority49 \lsdlocked0 List Table 4 Accent 3;\lsdpriority50 \lsdlocked0 List Table 5 Dark Accent 3;
+\lsdpriority51 \lsdlocked0 List Table 6 Colorful Accent 3;\lsdpriority52 \lsdlocked0 List Table 7 Colorful Accent 3;\lsdpriority46 \lsdlocked0 List Table 1 Light Accent 4;\lsdpriority47 \lsdlocked0 List Table 2 Accent 4;
+\lsdpriority48 \lsdlocked0 List Table 3 Accent 4;\lsdpriority49 \lsdlocked0 List Table 4 Accent 4;\lsdpriority50 \lsdlocked0 List Table 5 Dark Accent 4;\lsdpriority51 \lsdlocked0 List Table 6 Colorful Accent 4;
+\lsdpriority52 \lsdlocked0 List Table 7 Colorful Accent 4;\lsdpriority46 \lsdlocked0 List Table 1 Light Accent 5;\lsdpriority47 \lsdlocked0 List Table 2 Accent 5;\lsdpriority48 \lsdlocked0 List Table 3 Accent 5;
+\lsdpriority49 \lsdlocked0 List Table 4 Accent 5;\lsdpriority50 \lsdlocked0 List Table 5 Dark Accent 5;\lsdpriority51 \lsdlocked0 List Table 6 Colorful Accent 5;\lsdpriority52 \lsdlocked0 List Table 7 Colorful Accent 5;
+\lsdpriority46 \lsdlocked0 List Table 1 Light Accent 6;\lsdpriority47 \lsdlocked0 List Table 2 Accent 6;\lsdpriority48 \lsdlocked0 List Table 3 Accent 6;\lsdpriority49 \lsdlocked0 List Table 4 Accent 6;
+\lsdpriority50 \lsdlocked0 List Table 5 Dark Accent 6;\lsdpriority51 \lsdlocked0 List Table 6 Colorful Accent 6;\lsdpriority52 \lsdlocked0 List Table 7 Colorful Accent 6;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Mention;
+\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Smart Hyperlink;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Hashtag;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Unresolved Mention;}}{\*\datastore 010500000200000018000000
+4d73786d6c322e534158584d4c5265616465722e362e3000000000000000000000060000
+d0cf11e0a1b11ae1000000000000000000000000000000003e000300feff090006000000000000000000000001000000010000000000000000100000feffffff00000000feffffff0000000000000000ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
+ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
+ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
+ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
+fffffffffffffffffdfffffffeffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
+ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
+ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
+ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
+ffffffffffffffffffffffffffffffff52006f006f007400200045006e00740072007900000000000000000000000000000000000000000000000000000000000000000000000000000000000000000016000500ffffffffffffffffffffffff0c6ad98892f1d411a65f0040963251e5000000000000000000000000b002
+c4a57123d401feffffff00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000ffffffffffffffffffffffff00000000000000000000000000000000000000000000000000000000
+00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000ffffffffffffffffffffffff0000000000000000000000000000000000000000000000000000
+000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000ffffffffffffffffffffffff000000000000000000000000000000000000000000000000
+0000000000000000000000000000000000000000000000000105000000000000}}
diff --git a/test/rtf/image.native b/test/rtf/image.native
new file mode 100644
--- /dev/null
+++ b/test/rtf/image.native
@@ -0,0 +1,12 @@
+Pandoc
+  Meta { unMeta = fromList [] }
+  [ Para
+      [ Image
+          ( ""
+          , []
+          , [ ( "width" , "2.0in" ) , ( "height" , "2.0in" ) ]
+          )
+          [ Str "image" ]
+          ( "f9d88c3dbe18f6a7f5670e994a947d51216cdf0e.jpg" , "" )
+      ]
+  ]
diff --git a/test/rtf/image.rtf b/test/rtf/image.rtf
new file mode 100644
--- /dev/null
+++ b/test/rtf/image.rtf
@@ -0,0 +1,6 @@
+{\rtf1\ansi\deff0{\fonttbl{\f0 \fswiss Helvetica;}{\f1 \fmodern Courier;}}
+{\colortbl;\red255\green0\blue0;\red0\green0\blue255;}
+\widowctrl\hyphauto
+
+{\pard \ql \f0 \sa180 \li0 \fi0 {\pict\jpegblip\picw250\pich250\picwgoal2880\pichgoal2880 \bin ffd8ffe000104a46494600010101007800780000ffdb00430006040506050406060506070706080a100a0a09090a140e0f0c1017141818171416161a1d251f1a1b231c1616202c20232627292a29191f2d302d283025282928ffdb0043010707070a080a130a0a13281a161a2828282828282828282828282828282828282828282828282828282828282828282828282828282828282828282828282828ffc000110800fa00fa03011100021101031101ffc4001c0000000701010000000000000000000000010203040506070008ffc4003e100002010303020404040502050500030001020300041105122106311322415107617181143291a1234252b1c115f016336272d1082443e1f1265382ffc40017010101010100000000000000000000000000010204ffc4001b11010101010003010000000000000000000001110212213141ffda000c03010002110311003f00dadd18a10a704f6a95ccc57e37750782b0d8d9ea0cd32e7c5446e07e9f4ad723119a7b89e61e348f260719278aad613cbb640002938c76a182b264fc87bd13009c0c019c76e3d68a072e1cf6f4cd502d330c28269a61bb39c923923d4fad44c08dccb95cfd28b8280769ee08a263891e1808739e4f1d8d149392172cc714050dbb9fde8960ed8c60b79b1ed44103b05c331dbdb1dc5026ac1946d20ff8140aa631c773ec738a0346a003bf93e9cf02801895e7b9a01886796c923bd0090a06393c76a0142003ce3d86680d8dd9392303f5341ccc1b3cf7a2c812c37e4923d381429757013209fa511c18146c9247a0f6a007900c0c671c6280854e086c673eb45c27c038fd68aedff2fda836ef881f136f25d5e6b7d1262964aa02b03f98fbf153131935edcc97576f35c33349212cc4f39f7ab26186dfce5b200f73451f7600dcb8cf27e7400c0b291914046c9e0718fde81371b8e7273f4ef4007691919240e714097f31f376e7b5008caee27807b0f5a02c8e1b3c6d27d33cd0201d839523144d1a149ae084b78da47638211771fd050d582c3a0faab5119b6d12f8ab1c06788a0fd4e2ac356fd1fe08754ddccaba849696309e598c9e2103fed1dcfdeadc44fea5ff00a7f956366d375e492403ca935bedcf1eea4ff6ac68a55efc1beb3b552574f8e7009ff933a927ec715bc82b3a8f4d6bba5ca1352d22fe061cf9a0383f71dea5119cc6c0baed3eaac0f1fad40897dcc3d81f7a052366c1007df3400f21edefc5008c28f30c9c5170ee4fc37830086395250a7c66770c18e78da31c0c63de8609b41f7c515c5172a30c3b76344a3e377cb2339cf7a242aea89808cce368272b8c1a2e107c672a49f5c1a181c9c7ae7da8a2119e7b1f5068099ffa68258a132062d8f9e0f34059502b61bf2824e681bb297ced2a71efda80f19c47b9c77fdbe74057c13e539cf3c1a0eeeb9c73f33405ddb4f18249c1e28062b79ae242902024465b9214614649e7bd0362a7249eddc513456e5720f38f5a1a98e96e95d6baa6ebc2d1ad1e65521649bb469f563534d6d7d31f04347d2a2fc5f535db6a0e83718906c887cbbe5a9a8bef44dce9f731ca9a2e89169d6d6f2184b1455dc07b11dcfeb4d16f119c649a681285b03d3e5500f87820ff006a0e098191de80ac9b8904647b55d11da9681a56a31f87a869f6970b8ffe4883629a289aefc16e92d441682da5b098f21ed9f033f353914d19b751fc08d66cc16d12fe2bf45ec92ff0df1fdbfb559ec667aff4eeb1a04db359d3ae6d40eccebe53f46ec7f5ab82263da7dcf3eb5174e5181076918c7de869503232491ee4515c1803824f03b51287f30e0e7d803449494832c157278a2e8c71fcb9f9d144639236824d01e142efb1768cfb9c7ef40512a818de78ff00a682518e7cc30ab9e00a02cce9953247bd41e467191ed9a04205ee99da4e4e3d283a524b0427b5026c18a8e082067db8341ce0e39ed409b6502907391edda80f2dfdc496f0c124ac6184b144cf0a4e338fd2894f7a7342d4ba9b568f4fd261f12571966270a8bfd47d8511bae85f02b47b7fc34bac5d5c5dc88a0c90ab6c8d9bedce3ef4d1ad691a6dae976a96d616d15b409f9638d70054a1dbc68ea51d4329f4619a8022b78e04548515117b05000a035c5c4702a995c26e3819f534047bcb68a458cce866719540724d02e41c0f7a012a40f6141cbc8e7bd01719e38e6838af1c0a04ca8206d3cd037bdb082fad9e0bd8a39e0718649141047d0d5d18f759fc0cd3af164b8e9999acae4e4f81236e898f7c0f55fed574615aee83a96817ef67abda3db4ebdb7f66f983d88a061bb8db9e3d45165076db83c1f950a53780d8247c80a2398f182724f1c7ad080c608cfa7a51a0062adc7afbd0130173bb9c5070f071cb37e82826106e8f615e01c9e680d6b35bc534be3c1e3831b2aa962bb188f2b71df1de819ae4b1048c7f57bd01a58268e332642ae0704f7cf6207af6a01b99e17b7b6416e227407c494139909ed9f4c0a04a4e501e0f1eb40d263e53dce7fa682c9d0bd13abf58dd6db18bc2b157c4975270ab8ef8f563f21447a73a03a1f4de8eb031582b497328066b97fcd21ff038edfde88b7e32703bd64188e7e6283864b73400cd804b67ca3268317eacea6d56ff005233592f8b6303f953fa4af7c2fa93417fe98b763e0ea171297bab98558068f695ce0e08fdbd281e5c6a57ba5e9d14d716ef7774f2ec112601da4f27ec2827ada74bab559a20e148fcae36b0f91140283729c77a0e0a7777a01dac68395719e39a029607cb901b19c501480ab9279f4a086ea8d0b48d76c0586b7143224a76c61ce1831fe93e86b43cd1f12fe19ea7d2533dcdbeebcd20b612651e68f9ece3fcf6fa5067cbcf20ff009a051724905411e94032799060723da8406d6c67e7ea68d0e1770fe5cfb5026c37039ef9a02eca098c91e6e01e71c500b1d8a49c12786cf6a06a4e256008e3d050119958007920e2801154e32fb4120927b014017eb1c523ac5209a356215c291b87be28957ef853f0d66eaa99352d515e1d190f947669ce7b0ffa7e74a8f4be996569a5d9c56b6704705b46bb5238d42851f2ac875712bc70b3c30f892019540704d01ad2669a0491936330c95ce7140b2e4939a03638c7e8680ae485e33bbe540d60d3ada162c90a02c7270a39340a4f28b68da4645007a8f6a069a746f73235ddcefc391e12b2e1916824948742c99382473c73404791c617695279dc0640f9502c578c9efeb4095cb4cb0830ba21cf999c6401f4f5a05061d430c8079a02e03b3004311c7d281b5e3cd676c65489ee594e4aafe6c7ae07a9a0a075bbea3a8ea96f047d3935ebc404f04ad29411e08e011d98fed416fd212ee5b05b4d5ad6300c615807f1171eaa49eff5ad418c7c55f8466dd66d57a521f20cbcd66a7247a9283dbe5418a63862479877cf1f6c5008e400bdf1ce684016fe53dfbd1a73794600e08ce3d6800377c8c7d6800a9cf75fd4503d91492460f7ee3d28247a7b459f5fd592d22711c206f9e563858a31f99cfd050583518ba75247b1d134f9aed21396d4669769931dc01c003f7a329c4d17458ac5b55d36c12e040a3f1da75c1cb04ede2447f7f6a94567ad7a66db4fbbb29ba7d65b8b4bd8ccd09c8231eaa07b8ab04a7c2cf87b3f53ea8d77abc72c1a5dabe2452bb5a561fc83e5ee7e541e988218ed2dd22b7855228d76a46a00000ec00a510bd4dd511f4fe84da95cc31f880022da4902b1e7d3e99ac86fd03d631f565b4ee6d4dbbc649009cab2e48c83f514165b8b94b6895c44f279c280839e78ce28178ae6de46748a789e453865570483ec6812d42e85a421fc37918b00a883924d024c6e99b7a2a966c0009e17dc9f9fed40f81c77e28139218e4ff9815b9cf23340a01c907b9140201038ed402fcafd28386464e4fd33c50272bc60032609cf00fbd024f722dc66f24822ddf972f8feff00e280f69b24844919cac9ce7de83a447f30ded823007b50459d6ecacb528349b979127651b1dc795f1f3f7a0990148054823dc5015d491c0a0c3be337c2ff00c489b5ee9c87172016b9b541c49ff5a8f7f71eb560c1fc43e0a47e1aa94277310431f91fa551c1727f29ed409b641c86e31839a3454805739c1f6a026f1fd740f64665fc8c31cfde82db79bb40e9e8f49b62eb7d7e8b717ec832c91ff247fa1dc7df2281bcc9369d671493c422b7911654c1215f92bb8827bf068624ba635392df5eb4b9924558ee5bc19b71cee43c6dc7cf34c657be8db0b0b9d0f51d2afe668934dbf9628ddb8c2b8c0073f3a80da37546a7d25174fd95dc125c69f7313ee5655dfc313bd483cf07b1f6a68d5b48d5ec758b612e9d7293211c8fe653f35ee2a084eb9e8bb1eafb3582fe496278f3e1c919fcb9f97ad03ee8dd017a6741b6d3229dae161057c5750a48249ec3eb4139238568f6a9e7b103b5037934cb3793c610a2cd9277a8da73f5140ee38f6280c4b11c65b934023006d50050030e4647de80c846de3b500fcf9fbd0197273ed4007b91400e580c8e45074a82400e72682b36fd2162b7f25ddc09af2766ceeb872db79cf00f6a0b3229550140e07007a50092db860673de818df473c862686dad6470d9cce3b7b63e740fa1de6252ebb5bd81cd00bee2d800d003a6464004763ce683ce9f1cbe1f1d3a67ea1d1a30b68edffba814708c7f9c63d0fafceaca31e6dc71e1f07daa82608c83819f7a1a11ce149238fd68d0a579ec682cfd27a7c3a86bd10bc38b3b756b8b93c1fe1a8c91f7381f7a034f752ea5aa5c5eb292f732128037619c018f6ec282e5a2cb047abda74d5ce9b6da80f136de4a496219b3e48c92000323ea73467519d3da5bb757dbda410ac90c77c23058f99007ee7ec31416882ee47d23acb5185caf8bab4691b1efe57fff0038a9457ee75a82f6e7429350466b482f2742c0f74241c80c38c64541a9cfa1e89ac0177d33ab3d8de28f2b5bca429f91140e2c7a9b5ae9fb85b6ea9b46b9b3c796fe040768f76ec0fafb1f9505df4ebdb3d4edd6e74db98ee216fe68ce47d280648f75e2485a44da385ddc13f4a025ddbdbea16a633286566ce55f9c8f6c502ad750db2c514f30dec428247e6340bbf04100b73402afb943ed2b9e30683836defe9403bc1e06734020e06280cafe8683a375941d841c77c1a0151b467b50159f00e4127e5402872371040c5046eb5aadbe9b1c02e2f6dad25b89047099c677b7b0140fe3f1010afc803f3018e68160c3041ee2823f5dba92d34db89a1d9e2843b03b6d05bd013560c1748d57aa2797c6b35bab78e6959dc47231580ff336dcfb03c1a58364b5bbb7d7fa7b7427f1f673830c8664285bd1815238fad20f2c7c41e979ba43aa2e2c1cb1b663bede438f3a13c7dc76fb5515e9065b851f7a02950002a09c51a1b83cf14176e90d3645e9ad7752752aac23b3439c066665c827e944d29a6410aea725c4567135bd840d3c88a723728c29c9efe6c50d3ee9545b0bf8ef2e6e3c2fc2c6f72f2920e5f19039ee4938a9a875d03278377acf52ddf867f036ef71923932bfe51fbd3475cdc369df0db4fb389d4ea37970fa9cc0b00511795ce7d4f181eb4cd2451755fc45ac16d637381b14ca36b641dfce723e4053170d6cb52bbb362f6d3cb19241f2b9029862f09f143549ba7e7d2eef6caf2797c66ee17fdfd69862d1a069da7dfdac579d17adcda5ea9e1a992376c4723e39e3b024fd7e94c458ac3e25dee8d31d3bae74e7b79002bf8b8549471db38f5f4ed4c165e943a06a328d4ba605b4b22a1523c420c64fbaf38a82d36f0ce7cf7463790729b53017e940e0b0ceceed8ce0500e1b70daa08f5c9ed41d271cd0132476e7d7ff00aa069797d2411168ed9a41fcc858211f73c5075acb25ca6fb82aa31e58a36c81f561dcd033d42169e158ac64b98151b3981c2966cf639f4a064c7a8ac55e4865b7d493701e1c8e52403ea3cbfda827e390ca3f2c914aa81991bd281cdacc2747215c60e0ee5c67e940cb51b0b2bcbd824bfb08ee1a252d1caea1821cfa67b1fa504982b2283ce08f518a08abb82f6dd0369a5662081e14ce40c7ae1b04fda82275cb0bfd4f4536f7114589a5412461f3e4ce4e0e060f63f6ab2893d3b4b5b5b78e22ed22aae3cc3cc7e64fad3449a22a461500007602a0cd7e3b74c26b5d2ad79147baf34eccca40e4a7f30ff3f6aba3cd0543267eb5427b86f1f4c76ef45d0eca1ad5ef224d13e1cf4fd9b22192fa67bc955f8c8c617fba9fb510d7a6ed3fd43a735e5b54964be658c048fb6cdd9e7eb8a186bac97d174e6d22e23437b7ac26b95e77c68bf950fa7279e2b22dba45b59e97a669fa4ea36aeff89cea9a90451fc355ff0096ad9f4ce3f41570675d4fa8c77da8de5cde5be26bc653171ca47dc1f6c9fed5562b97f70276808da7c24f0c1c63804e33fa8a2928c0e0383c8f7ed41d92a41393f4a2548595c2c37493db4cd04e8a08f139566edfef3445b6e7aeaf65d2df48ea2b11776ae02a93e564c772adef409f4ee8ba9a21d73a36fa579ad9f325afe599171ed9c30a960d5ba0fe2843abb47a6f510fc26a4c36890f9558fcc6783506a1147b510024e30339ce680d2c6ae9861eb9a009178a0205443b989e39cd01d8075e3047ce80563057ca381ed4011c4531e503d85013c91b804a21279c903341131cda8c3abdc8650f6d20c4321232adec3dc504bab2c113c9293bb1963df3408dd4b75e1efb2856463dbc43b4631fad047e9177ad4fe32ea16b1db4b8fe1aa92571f5f5a0916bc8e0895af5c46c17cd8c9ff7da80f6d736f7f6915c59cab35bc837238ed8a072a31c1ef4062870718a06f7702dc5b3c522ee4752ae0fa8230683c75d6ba3b74ef535fe984929149e4278ca9e47edfdab42058003763ed409f88ffd6dfad06b1f12ae612fa0c76e0b471e9916d23f973eb4158d3efeff004a984da5debc1295d8e4018dbf3145d583a2ad96f356bbd7f5d90dc59587f1e79a6392f28fcaa3ee47159444ea3aa5ddfc7acf50dcdc344d7a4dbc317f52641200f6000fdeb41b5ef51d8eab672ffa9e971c97c11638268e431a46000012a3b9a351567db823b11f3ef40948e428048207a8340ab48ae83cb83ee0f3428a982719edf3e68c9cc97d3fe15ad8c9be138f2bf38e7b8f6ef40f7a5f55bdd3f56b46d3649127f1405f08e7249c76f5fa50689d48ba5f545cdcbdb462cba9206411b2b055bb07d4fb1c73528d4fa8f52d62cf47b6b8d2e65fc458c49f8a818795c151939f977a823ba0fe253750eb7fe937b04293f9f6c90be41dbdc7ff006283473c1efc1a06f69776d73bbf0f2aca32572bc80470450284a46dfca19f819f5a04e799614def26c0bdce09cfd85045dc75769d12dc3c3e2491db0dd3c85195235f7c91cfd066ae0cdba9be31f4ec61a386c1ef9d4ee473e45cfb1cf34c101d3ff1ac9d481d46c628ed24751881880833f988e7b0fa5328dfed2f2def2ce2b9b79925b791772ca87208f7a60182ee2b95cc0c48f53823fbd40ac658b30f4f4a086d4ee1d75bb6b78f4e965596366fc5211b23238008fde81f43692da5bc30d97831a0397dc09e3d714087506bf61a2c4cd77324726d2caaec141f9fd2ae0c435bf8c57173ad7876f7a2daca10489121244cdf319ce3dbf5a834fe81f881a6f57bcb6ba7c53c72c11873e28cee1db391dbef4199ff00ea4348116a5a66a8a8a04aad04847a90723f6ad7d18c312ddc02a3815423ba0f63fa541687bd9efe1b533b3c9e0a78473e899e318a09bd0ba6eef543e3b2bd8e9b10064bd9e4da001dc81401aeeb29a984d0ba7d5e1d06d4e6594f06523bc8e7f5c0ac8af752dfc17d7090d9218ec6d9447129ee71fcc4fb9cd6842ab10dc0014f3e5a2c1704b671dfdc734525226dc939e283a362c7f940344a380393df144733e2276e38f5efcd01b4bbbfc3dda4a9298a44395902e4a9c70682660d4265d62de40b1bdc1545054f95c8fe627df141af7c3af8808f3dd68dd5d2a45765884b8908d8c3b6c27b7a77a945d7a5fa474bd2ba8e4d5748b28624955d5d8b13b79ee9e983d8d40a753758c7a46b96f6114725dc92279a2810b3a64f94900763cfafa503fd3b59b79ed84da34713c0cd890f0a158fa1f981de826e1b548959fc4dc5cee24b6467e59ed4101ff19e9f676baa5d6a72c50adb4ad1ac790ccc076200f7ad41e7df881d79a87576a5f87b0f161d381db1c2a36e7e6d8ff3416bf87ff082c6f208ef7a82f22b9761bd6d619785f6dc477fa53705ab57f83bd297ceb1e9caf67708db9c4526723e849e3e94f212dd25d117fd29a8c09a76b534fa39cf8b6b71ced38e36fb73417f52e64548e34007e673e9f21ef590a1c918c90718dc281a69b68f67118d9da5058b798f6fa7fe280daadd1b2d36eae70710c4d263df0a4d583cc7a668fd4bf11b5837d7c93dcd9a3146959822a0e781f4cfa55161e9dd7fa67a4f55b9e9aea3e9f81fc09ca0ba118998fcdb2338c7b528d39f4cd2ba76e2d357d292df4eb391809963420ce1b1b576fa1e7359119f1eb4e17dd033ca172d6b2a4df303383fdeb5c8f2eef3bce4e0e335684cb0c9f354160d36f64b0baf16072b91b5f03391f43c51aab23a5debe91c4fad4d73689e6fc3a290573ff4f03e59f4a3280d67581ce916567f84b58ce0a1fccec3d58fa9a084de08c90464e4d1a8e419059b201f4a05630a176918efc50176293872c17bf14042aa0125b03db14046c60b60123fde6827fa0c68edd5365ff11346ba6292ee64194240c807e59a32b7fc51bfe8bd5ed5db424860beb62b89218422ce09c11c01dbbd0660ae110bf1bf2154838dbebfefeb41a8f4cdac7f117458f4d9ecd2df53b4cf81a822808c47255c0f7c8e7fb54a2ec2cfabba3b4b4b8d3af12eedad40926b0f070a13f9b633649f7a82eba6ea4357d321d4ecad512daf20df26e016507fa4fbfaf3e98f9d067dd2bd2faac9aa4d72d72d1e9510ca46a7631c7a320e18f1dfd7bd059afb7da816d23de4ba5de211346a1e4785f190548e4648c63b64e6b43ce9d5baafe3b539c5b452dbda46c638a167cb281c73ee4ff9340e3a3fa5f5aea4ba58f4bb57dbfcf2b02a8bf7f7a0de3a5fa0b50d2a2d92eb3e048c0a97c867dbedcf6a944e5cf4f6b76d1b3d8ea42795066266c87c81c65b9cfaf15048e83af3cd64abac08edaf01546c38dae4e0657ee6826e5b892de3702292e2545ddb55700fd0fbfca81c4b3bc718716eef9eeaa402280d14ab3c0b2c65c06fe571823ed40df56b217fa6dd5ab9216689a33f2c8c558307e83b8d77a37aaa7d22f2512c28768800c9954671b3d33ebef568d0ef7a7749eb0b5bbbb162d657b32b46d2e1564c8ed9c5644d1b0b9bbd261d2a440af6cb0e2e5b1e7dbc1238e0f7a0375b696daa7496a3a4dac8a92cf078685b271db04d391e40d5ec4586a1716de2a49e0c8c85d3b120f715ba1899173ff305413070abd89cfe9f5a2d3ee9c8639fa874eb6b804c52dc46b20c9f302c3bd11e84d47e1af4d5dc6521d3e3b662c19a58721ff5a9a321f89bd27a374b456d158dccd34d333332c9b4b2afbe47a7cb1f7aa33d2bc0d8c0f1c8f6a2c14b6d501b39cf63450897380c319e3de8065031c038f7ed40d8faf1ce41e4d004876a8dc3cc7e743025c956c818028c904579e7f0e15695c9c0541924f6c00283d0bf07f42d6b48820b8d62d20b2b58d656404959e52f83c8ff00fcfafbd4a35bb06f12391a48dd55cee2b2f3818ed8f6a8158a159890f02242079147623e631c502b0db436d1ecb7458d4738038fb0a087d6eeb508f48bb7d32d95750752b6c26c905b3ddb6f61eb574794f5cb6b9d0fa9678b512b25d24bbe52b8c1638278fbd582c57ff12afaed45b5bc0d0d8a8c08a2731ee3eec5793f40450466a1d59af446293c186cd53ca0c36eab93dc649e49fbd048e89f1675ed35e301e293919dcbf9867b37cbe94a35fe94ea4d33aba6824306dc48015750d86c6e247b0cf63591a40b8dc23fc30f14138dcac3000f9d03687547f12e8dd5af816b13148dddbcd29039c0f6f6f7a0eb5d62caf5636825db70c9bc4328f0dc0271c8a090627d3073ce681acf6505ccf14d35bc2f2c2731bb28254fb8a075144a83ca806792400334049ee6281e2496408656d880ff0031f61fa50446bd76058ea1b9e21025a3bb48afe71df9c7b71de9c8f196a0de23ca7b827d4f7add117e0cbfd4b5059392369663ff004e71c51aa97e8f555eadd258f2bf8a889cff00dc28cbd0bf123a926e96d163bdb74490bca2321c678209ff001591e71eafd7a7d7ef45cde2c20aae144638033fb9ad2e1b5e69d058da431ccf21d4a5c3b4631b62523807feaf5c7a50222f2d648c25f5aeec8c2cd19dae3d3e87e944d3eb7e90d425b49ef2292de38224f1505c3f8724a9eeaa7bd0d57a60406059436306868a7803839c7ad1a158039c13f4a33a716767f8cb9b6b55e1ae2458813e9938cd07a9f42d0b4de99b4b7d1f41b58ff19b03c93ba06607fa8b1f5f619a5b8266d74a65d42da6ba90cce996dcdc8c9fff006a5a2c2635083b05ef83eb5028076341db4b1ed9f7a04651fc41db18ed419d75b744dbea335fcb0db0335f2057901c05da73c8f9d5d18a75174a3f4c47335e35da4ce418a489374254f707d463d33565d1529b569a489a17944b06ec8057d71dcd037b4b6b8bfba31584124b27e62a8a4f1ea68357f83da7ea5a76bfe0912453ccabb49194653cb60f6ce3dfda983d196cd108c2401711f9768e306b2297d73fc6d02773a8b591922693c5004bb9d72542fa2f6efde8314ff867aeeec27500b77bb5670e36ca19b1dff2e7f2fd2837ce8bd5dd348b78b552219022870d9c46e792a4f6c608a0b846c8e03232b29ec41cd0199f1410fd4b24b1e8f712c0a5e4452d851e6c639dbf3238a0afa42ba77475e4ba8470896681da45180b18da76af3c9029c8f26dc1df2b9c606e273e86b743331924f27f4a82c12280e59b008e79f6a2d4d74188ff00e30d203a82ad7519c1ff00b860d11ba7c5e86c9fa3afae6f4091e043e021270b21e01c7dcd6479ab4dd3aeb56be4b7b184cf2b301b57d07bfd2b4bad0fe25e9f6960ba7c7a55ac50cd750335ccaade7723b83b8f6e38a2207a5ba4e7ea3d93780cb616ca53781f99fbff009a0b675a5be9765d43a75a6ad3b25adb4185429b831c70303dfdfd2831eb8954ca48f3827819c71ed406b2b1b9bf9a5fc1c4ce2253238047957dc9345d122b792eee522811a495ce1157b93ed444ff0049f476b1aaf51c761345269d25be269259570c833c6077249e062a68f53e8ef0da69509d4ae225b92a04af232ab16f98cf1f4a5a266d4dbca8af13a329ecca723f51502d14f0cb9f05d1c8ee01c91f6a0393b4edfe63c8a031608859b38f97340d84d04e5846eae50f9829ce3eb400fb24466041f5e3d2823f56d22db57b192d6e61468a41c823ff0035651916bbf04ada7badda5cad6d1b72c09dc33f2a6875d25f0865d06fe2bc6d4c4d3282026cca8cfafcfd29a34cd234a10c768f711a78f1bb392a3001208e3ec69a26a58d640c832091c90706a084ea1d3eeafdadf4f86da3166c0b4b397c18f046140f5ce4d04f4702436e91c28a9122e028ed8a0a9f5a5b6a09a1bc5a135bc72cce048b3c5bc15c638f9d59043fc2db997481aa69dae49e1cb6bb643239211939e467818f97bd305965ebce9a10bc8da9dbaa2679dd9ce3d8530572cfac87566ab05ae9f1490692b9696e1f833738555f96793504df5f25945d2576b7ec16dc46792381c7b7ad5e60f234980e42f6c9c56a82ec3eff00bd4124e49700f1c646e3cd169ce9575f83d52cee324347323f6e3861ff008a23d47d4ba6a75074fdcd8ef317e2e2ff0098bdd4706a60c3f4ae8cd5f44eb8fc3e97248a638cbc73bf90483d463b373e9574685abf42a6b5649fea72bbdeac4a8d3b018cfae31f7a6895b6b29b41d30d8e9f6bbed9213e1b7a994e724fcbb5064bd7835a9752d3af75d8116354778f660788cbd9483dbb0a0cd20b2b8d43528ad2088bdcccf854039cff00e2827a0d34e9da1de896f2182492efc0976f998aa827d3d334113a74aa9a9298628e74570478bc0c7cf1da83724bb8246d3e6416b0384da61b5501c9f5c3704f152c037561a95f5fce61d3ad6db4ab950f34b331dd9f4191db8fdcd406d67a675ab4b6d325d1af248272a43430315ddec7038f6ad4b3f448bf47eb71cb69abddebf21d5e26896203846c30c8603b9c6452d9835901405660376319ac84bf13180779d8bb82827d4fb0a06f777367a75acd7170f1430a9f331200cfceae061a0cf6dac692d7365266191db0578f5edf3a6075a6c9278b3433188a467860d96fbd40fe540471409aa0c1140750001ed8ed4058e15133c983960077edf6a06faade5c5b7822d2d926766cb967da2341dd8f0727d85033d27597d62e2ee3163756915bbf8799d71e2f19dcbf2a092b88dd9a311950a0e5b70ce47fe6ac18af53f5b69da9752dd69da9ca906876e24465d9e69881c6ff005c679c0aa2bfd267a347512c93dbb5d42d90d3c800b68c9ce0ec3cfa528db74ad034db5905ee8be1ac728dc153984f3f980f4fb56453be2de8f647a6aff53796596f0aed46798ec033ce149c0fb0ad71479c9bb9dc3bf3c55a0b95f65a825150b481a407b93c0fda8a29c06671dc93803bd131eafd0af6dffe18d2ee25982a4b04603b7a9c631fad03bbe586381bc5945b96385718c827db3eb5288eb8ba934eb15fc3c535f05427796dcccdec7150637d5bd55d5362b7975aa4d0d919018adec8637807bb60723000e4f7cd58203538aefa8aeb478a7b9beba924547b8774cf8608036a80704639cf1f9855d1a7f4c68b67a03de5e5d59dad8d988c62e1c0f107a1e7fdf7a082ea6d07a6e3e99375a7cb6b3db093c727701e2360f7f53dfb50653d4130d42ee18f48b3f0232a15218936963ebf5fbd06dbf0cfa74855b9d46e04b730c6144691e12307d33ea7de8348ba6b5478a279a004f98c479247b81f5a9438805ac0be2e02e73c9ef8fbd40c2346d43578eefc40da7da1dc8b8eefea4fcb9fef419beabf12a4bcebcb2d2fa7ee0dc58492084b30236bb6467dce383f6a0b87556a67a7f4d95a0bbb5468816f0a69c78b2e072572719ce78357079dfab3af2e7a92c963b88d94abbbf91cedc93edf418aa2c5f0dbe2a6a9a0c90d8de34773a6a8da1186d6403fa48fec682d9adeb7a9b4c9d572dacc9a6c9700456e5ca910e000ecbd8e580352fb1ae7476bd6dd49a325e5a9f3025245fe961dea097523cc0919a032af039a006936c81423104649c703ef40dcce64bc3035a87b6f0c378f9fe7cf2b8fdf340a4b6e25962915d94a67807839f7a043586922b5636ec44c061063f31f6ab079d7fe19b7eb2d4efeef55d5d74f992e9a0fc3a441dcb13927b838c9aa2d4bf042c618e178efee6e18104870172318edf5c1e6945bbe1a748ea7d2315edbea3a99bcb190030c401010e4e783ee0fa56455be3d6b90c1a6268d69e17f1486900ee98ec29ccc183119419e7e55ba11f089f523ef5058363a8059fb8e31e9421b491056c01819e28d3d0ff07eea3d53a1e3b6b8db235aca63c139c0eea68ca47a9fa6ef757b83ff00bf68ad428c2f248c7a8f9fcea518df516adac74e7544f63a2ea172f1800291e6cee19ec78cd5826344e85b6bad25ba8fade5b99dae0ee11efc71e858f7e7d054a2d7d39a75ae8f7b6b00b8917f1516624b78429da327cec493db1db1d8540cf4aea28f58d6aeae2f6dd64b498082d880488d149fcea7d4939ab04175e6850a8d32de3b78e380c8de32c4db4e18e430fef543cf86fd0d691b4fabdf6648b3b2db69ce7dd87be68342d2f4fb9b5b891af1a28a2dc05bc5036d001e0eef7352884b961a2ea9aa7555c885e08d45b5bc52b61b686c120fb939fb541276bd4b61d53624d942e2f6200bc32290633e99f4233416dd3ad3f0d611c0c77b632e71dc9ef41156dd27a45addcb3dbd9c513b1dd941821bdc7b558333b9f873757fd69a85e3f813e9c7723b5d93265d872473c11544a68ff08fa75e290b42ec4e4124e70738fa5048e89f0f745d2aeadd2decedda6525c975121183c77f7a945c754d0e0d563682ed43425369403bff00bcd58308ba7d5fe13f5a05889974a9d8b46aede4914f707d88ff001528ddf4fd7edb54d1a1d56c312dab2e64dbc9418e78f5c541296d70b716d1cd6f8789977230ecc280cb7519b816f212b205de4e0843ce300f6cfcb39a0545c42cee88e0b458ddec33ee680eac92266360debc7b5056fad2d354b9b189745744be121daf27e550548ce3d4d58324d07a725e98ea2b7ff5381f5169a7579d021fe13904ee43ddfbe49038ab46e76cf05cc714f6d309232a4a98ce54fd6b2196bb7f2e9b631b2c427b891b6851db3eff002007341e5bf887aa2ea3d4f77378be381e42fdb711ed5a1554395caf1cd07617dcd04fc85402101da791421b49920331381c60d1a69bf02f56f03a925b12c162b98c955f775e47df19a32d99b518268e4491668704a79d4aeec7b7bd4a30feb7e9144d76e265697c3e2693631674273803e556087d76f35fd49859e9925ccf611141106f2e182e3241f727f5a94681a268f79ad1b1b8b9dd66b1c2b1ce9bb06361c1e7bf3fe6a096b0d3ba57488e485b52b40909c386901607d47bf7a0ae758eb69ac4d15be81a748f0a9c35cc90b2eff4c03c1c638a0b77405c5d5d45f87be5fe359a88b81b401dc1c7d38fb50586fed18ea3015790091591e447c1518c8c7a0a0a5754d8c9d49a8d9f4ee9dba0b3b5224b9692327728f627e7c6682f9a7e996b6b3a8b6b748a348820c7720761412c064e3041ce282b5d4bd73d3bd3f33daea97ac2e540dd0a292dc8cd043c1f15ba2a7923b65bb910371b9a12141f9d02edf13ba2ade56857551e5e77244c54fd0e280746ebfe99bbbd655d56dcdc9ce08465565f4ee3bfca82d53eb3a6dac3e25c5f5ba646402e33fa77a0aff5b74ad8757e9ca972844aa37c520fcca7d3f5ab067bd369a8f467544d626c98e9f7118f0200e4465c903049c8c9e6ad1b24334b6fa6249716cab20037c309dd83db03b5640dddac3764a4f02cb1103863919fa7a1a06d6f600c37162911b7b252b87dc773f1927393f4a079f868edae1ae6328a8b1ed38e30050226e85d5dc1f879011b3c47c2f604719f9d01eff4f4b83e3c6b18bb452b1cac9b8a83de80b16e8208a3b7b58e1407cc061427cc0ff1560ce7a8f592d69a97504cad2dac01a2b53900c3e9e51ea58f727d0551e73bfb86b99a49a46dcf21c96340dc13804f20f6f9501c0e3b8a0963316fcc4607007f57bd084d64dec01200ce483468ff0040d525d1755b4d4206ff0095207c11dc67ff0019a18f56584f6daad9dade4211e39104a8ded9152b235cd8c530613229c8c1c8ef50472e81690ee00322b0c100f0debdbb7ca8111ace856371358cba85aa5cc407891ccf83f2ef4048b4ad2e59bf116769672c72f99dd1437239078e2824a4d3e1b94559234110e781839fa0a0561b38ad532a12319c86c6307e740a9732a3a00cac870cd8e0faf0681be8b6db965bb909df3c85806eeabced5a09523647e6e0fef419a6adf116daf7ac34be9dd1da686e7f1ca2e243b76320ce57df9ff1560cc3e3f470ff00c78255b842b35bc6c4af9b6e323d3e95467b6365f8dbcf062beb68c119595d8aaff6e282422e9899b4f6bb5d46cda2562a76316c1078f4a0859e1b9b762c0bf94f0e84feb4125a57505c58ea70dd5d0174a986d92b1c13f6f5a0de7a5be366877260b5d42dee2d2423124a487507ebdf15289dd3fac7a7bab6feded74d61733473acdb5a162142ff00313d81ed505fa58fc6d809380c1b9f5c502e0e05040ea367a85dea454de2ff00a610375b04c16c7a16ef8340b5f6930dce9375636acf6a278f04c5dd4f1dbf4a084e91d06f3a52dee62bbd4a2b882494ced3c8a448063b63b638fde803ab7ae749b2b3096d792c93c8c109b55dcd18ce3710473ffdd043dc758dc5869044565aa5dda4c3c2b7bc78c1f14e3963db03e7c0ab066bf1327d41ba76ca6bc48ecad24c456f6b0c87cf8e4bbfa138c0fa9aa3297c83dd4e28395811cf2680a5b93c7ed413cd1ff0f3c797b8031406645236b0508406f30e68ba49c051b97d0e0e7d28ad57e19f575c5be8f269515dac772877c11bc464dea7ba8c739ce78f9d3193bb8ebfea2bcbd6b5b6b8b58bb7f13c2f0ce31cf0deb4c0f2dbad6d743d2ee99efae752d6c02a86e0054524f6383c7ff94c0b6af274c75149a46a5a82c46f1e1479fc3190bd8156fbe7f4a960bf74e9d253f1167a3ac09e0856610e3041ec7f6c540f67b892cee7f8d18368232ef2af2508c7047cf340ead5bf130accc9b1186541e723d09ffc5033bbb1b82d74d6b37f1244daa1b38073df3f4a08eeb1d3b50d4fa6a5b4d32f12cef1902ee73e523d476fde8306eb0d3fabfa4ba92c278af67bb7281606472f90bdd58558253a6afb40ea1d62283a8b461a66a6f931cf6a7c2466f7cfb939e7b5515fbed3747b5eb8f06eb78d35080a2ec9719c76f98049a0b4ebdd37d1bad869acbf0b03c5c16b29444adf50ded41995f68564a263a66b31cd02be152505493f51c1a088bab69ad1bc179e320f07c37c8a0692b46c4995f0381db39a0b2fc34e971d57d4705bc8db6c50ef9dd97b81fcbf7381528f5ae97a1d8e996d1db69b0c7648855b10a81b80f43c739c54134147b9a036063279fb5046e957726a0f2cfe04915b06db1788305ffeac7a0a00d72f8d9c491c06337533050ac7185cf2df6a06da2da4293488f34973328c34aea428c9ec3eded40ee7d2ad249448f6b133820ee2833df3fde819ea96897461b05b87815f2ee919e5d47704fa039ab079b3e326b70eafd4ef6d6650d8e9ebf868b69c8247723efebf2aa280eb9193ebedc5002a124e015340018fb8fde82cf32b1603d0678cd02406dce3008e47ce81b499c331383c9c9f5a2e9c69377369f7d6f796a4acf148acb83fb511e91b3b3d0bab745b7d45acedd8e3732b71b1fd73f7a5a19eafd09a56a0a96b1c705b49c48510761ce4fcfbd4d0d752826b2b583476fc3daacb295b79d768de8a32b1e71f989e49f6a7d14dd1af5ba275a45b8b093c054492ea769092373765c1da4679fbd306e36ba9595fe9f0dcdbcc92c33e1579cf27d0d409ea178f68521b6b76926ee8a7853f7ff140bc768d78f6f73748d1cd103b543f0091cf6efc502f7319dac194371d8b6326829f0c501d7ae6fa568d5d4942c806d4db81839f53c8cd59456fae6e628749b5bab8b1865b08e4726588ec11e7f2e49071c93da9a31dd4341d675e9a5bad374f9858162d0b4ac70e18f0573df35a0c759f87bd53a404f174f965dfff00f479b1ef570576e34bd4b4cc0bdb3b9b7258a00e846e3f2a94376475cee4914af7ca9150685f09ba61efb52fc7dd69bf8eb7c158d1d0b47bb38f37efde968d6eeb4eb5e91d6ad25b660aee59974db6881690918e31ce39279e062a5a34bb57b88adedd1e379679065d80036679e6a07e8391bce7e940c659ef5afe1286de3b16f2b8903094b7b2fa7ce81eb380c4260ed193f2a0cd6fa5d4a4ea0fc7bdadcce923158a3039db83c038e3ef41a0e96b2ad8a35e009291b8a939d9f227e43bd590436bbd6fa269202c974b7123602c76e779624e00e29833bf897d493e896525dbcb2a6b5a9c3e1456b91b6d60cf989c7f31f7a60c02490961ebcf3eb541308e39e067b507007b96007a67fb50178f97eb4165ce18165c2927b773fad023202d9c8dbb7818ff003408300b87f2f1c107d0d0c15a4f2e339c90467f6a18bdfc2cea8ff4bd561b4b9ba686d6e64552c4f954e7d7e46a60f4688d240af1b2bc6cbf5047ca960617ba658de1b792f2d94a5ab33461b18524633fa1a81b5c8b5168967369d23c0e0a24622dc981d81c76aba29df0bb48d660d52fceb88d069f04aeb69130037127f37b9c0ed9a8350781240bbc06da72323b1f7a0eb8816e633192ebc8c9472a78fa50349b4c83c068e24f0ddbcc1c13b837be4d055b57e98b996d4db5b4a893dc1e6620b6ccf2c467efc504ce97a38d3f4d874bf09af6d46e2f25cb82724e791db15650a43f878b51fc34f3da8f132b6d6a98c80a39ff007e99aba249631b58b9047239ec3e55368aeeb7d2da6f52c0eb7f16e87f2c6e836ba90724ab7a67b55d115ac7c3e8aed2182def4c56a14096368959a423d77e3229a27b41e9d8343b01069c8a8dc9660aa3713df3c64d4a1c695d3d6b67a8cba94b9b8d4e61869e4e4a8c636a7f4afcaa09a485519caae19b966f7a0435196582c656b74df3e308beec7b50629375775b691ac5bdb6b16d6378779f019b00a31cf391c9c2f1daae0b35ef52f5374de88d77aa45a6cd25ddc0108694ee2188c28007603d6a0d16c92430a4b2ed3230dc401855cfa0a0a07c45d7b5db9d462e9ee960b14b2ee134ef8c850012147ec78ab0670b643a2efae753d72686e6e2da211db42176079c8e768f65e39f7aa332d6f58bbd635096f6fe6692695b24f603d801e82823cb900ee00e68006460051dfd680ed9f0c905b713d8d006d5f5419fa505a18f94e40501b1b81a04186d62402c87be3d6810b81290aea8467201231cd1749dbc437f9f1e201db3de8ba07dc0175c027f28a335b17c26f888d6b6d0e8fabf892a29c453b1e547f49f7a946d6424f08236491c833ee0835073294888894120700f0280813c40a6711bc8843e00fca7d3ef40e41dc081f9a811681c6f7565329185623b7e9de812b3bcf11ff0b74563bd50494cf120071b97e5fda80d7577046c9019d5669dbc340324eec67fb734103d5da96bf67a7cf0e916f6e2765f25ddc4c11107ab1c8c647cce2816d3ec7f0f6564cae6e67da375e6d52cc4af2e4fb13ed4145f899d47b3499f4bb6d46cda49b69b92921565c3648e3dd40c81cd5c0ae89f13ec246d3e379ed2d6da180b5d34849da1780b128e49271c9f4a60ba685d5fa36bc42d95c324ec7090cc9b1d87b81ed50588958977cacaaa3b9341c655f12348d1dcb8dc1946540f99a019e2134454eeda7bed3839cd052fe2136b536b5d3563a1ca53c49da4b9507198940ce7e5c9fbe281c6b7a974cf4ee4ea7242d76dc784a3c595b3e9b464e3f6ad0ac745ccbd4fadcbabea42da56959a382ce7460d6b1a93c01f97272093ebf6a82f1ad6af0e9da5cb3cecf6902216919f82aa3818c7a9f4c530649a9f5269ba7429d472239bc991a1b0d3c3152880f0f23039e7bf3de90635ab6a377aa5ebdcdecef2c9239e59f3827e5ed54302195fcc38cd01245395c1f5f4a05b606538e483c501b6939e3b5077860f3914165754c33e549000dbe87de813b820c27fa7baafb8a04a69c98e281e42618c795338033df1f3a06c03e4e029247007ad010093c35674da71f977640340081a190658e41c820f141b0fc33f8926c218b4ed609366a02249bb2d19ce3ea4528dbece68eead926b7916689c643a9e0d643387521fea2f693c2d6efc786ee46d9bfed3eff2a04669edf5295ff057a60bd865309246d3bbbedc1efef41d63a8dec9ab4fa7dd4510fc3c69234ca186e2d9c003b7a67bd034bad0a5bb96e25d575267889cc1b54446d9bd0a37bfbfbd02925945a72cba8dddc48b3f87b1e58f23c623f292bdb7fa7cf38a0a5750f54ebba56a9a67fc516b6d6fd3970ea9234677c8dc7f38f6e4640ce282d1ac4b16bfa72c1d2bad430cd1ba822061865f5007d3daac19cf547c189357d561bbd3eee683c62cd786e9b73337b8c7bd512bd39f06adedec2de0d5ae639da372e6485363107f97767b505cee755d03a5e58ac228659af123184b7b733322e38c91dbf5a943ab3d52e64b49ee755d2e64950e238e35f10c884e17cbe87dc540e6d7509a4f110e9f7566a471712850abf6ce463e6280bacea36fd33a4497f773cf32c698dcc4beee33938edc7ad05534aea683ae61d64c4d2a69b6b88d16d5ca5c303f3e386cf61db140e27b5e99e96b64bdd562b6b30aa36c6c37cac7dc9eec6b42c1a66a962fa70beb6b516d0cbe76322f86c78f6c66831bf8b5d5d2dfa35a5dce60b1933b6ce3c788769f2b331ec1b8fd2831b79649984b239773c1dc68129725c1c640e73400ec781d8fb1a03c4a85d0c8582640257bd01e51fc42236263c9c67be280429c6037eb405dbf5fd682c2a0bb976cf07d3fc5009279ef8ec4e68193a9902b28e7dc71fb501d95b098e0f6dd9e0d0049131019b047b8390281bb292484e47c8500c4f242c3076bf704704739a0be7c3febfbae9a5daf23cd017c7e19fb107bb67d0f6fd6837cd2757d1fab34f4f05e37dde630b1c3a91edf4f7159103d6eb7da65fdbdf59dadb5e2460ac876ed9e1c8c060f9efe9c8a0a75cfc42d5742d2ee5a7e9dbb494b6d6b9bc930cce4f940e3cd81ed4160e98f88315e689fff0022b57664199cc5196f0c7a164ef8f98cd0589baffa68590985eb15c0db1985839f6c2919340b69d03f5285bdd6f4bf021424db4329cb153fccc3d09c76a090d3340d2f479a7bab3b38e2924e5e451cfd280d7dafe936f6c5e4bd89813b02a36589ce318a0358dc35cc4e17f9bf234cdbb78fa0c607a7340e6cec20b1596610c6934b8323226379edda81da8dcb9ec40a042f50b5bb21645473b58b11dbd7bfca8304f8add5d67a9ea8ba5d8ea72c1a4d8a952f10f2c920e368cf71e99fad5833dd0754d6ed66bdb2e9a91a5babb2a310465a57c1ddc1038e7bd5171d3748b8d46ee1ff005298dc6a764c27d4eeaee7fe1c01795881c9e7804fe940dbe287c4b6d75a1b1d1c986d62277c91bf131f4c0f6fad0663737135d3b497124924871f98e7803007d2811dc5b83903dc0a0333f03be7de8122df2c9a05a11e5f51f7a05ce7071804fca8033e5da0734020b0183bb23e5416269577ed0e5323078ceeefdff6a03dbcd62914c2f629a47c622689800879e4fbd046f9d8a2a03e31385c0e73da8b83ca590947dcaead8208e73da8849b3e19ce704f7c5015586d006431f5cf61f3a04ee586ff002481c8fe6191408f0011eb8e30682774dea9bbb5784492ca6385832e1ca95e3d2834be9df8c312e2db5eb4375080337000f1303d18763591a469baef4d755989ec6f6dae5a23e20b599406dd8e080ddbed41272f4dd8caf1c86d163910f9595882a3d718a035edd695d3b6a926b57d0ac65b10b4e06eedd863bf141077fd7af2782bd3fa26a1a8891d57c630948c0279393dcd04cf5875258f4de9f0cb7b7b6d66d2b81ba752d85f5214724fed41036bd79d2fe319d7a8f4b9c81e58de2f04827b9ce09a07a3acecf54b790685ace8697606009e52c377b7f2e682b097d7d36acf0f55df5edbdc0977412468cb6ce3be10af3c63b9c8a0b0751f505be9690dd5d752436f62a3fe4c6448f3b7b0c64e38f615734651f107e3045ac42b67a7693018633b965bc1bc838ee173807bf7cd33065baaeb1a95f2c11dfcd2bc51fe48880aa3e8a062a8b059f595df4ae9a74de9e9ec499d43c97b1427c6e47e525bb63e4282ad3ea3712893c599dbc4259c1627713c927de81043950df97db1406da8411c92063be280230839627078e79a0390a71b5bb5003a8c1232338e4507025573e9fbd02a0e41dc0e680c3691cf714053bb34160895dc16f291d98d02322aa39f3e14707ffaa06f202a5bb0c7201f4a343aca51090497efdfbfce89840c8db8e46573923ff14410b00490d9f5c1a0425dd8ce4673e873cd0265e4dbe7041ed814009b8cbb8e5863bd07163b7716e0607b6698060b96b7b9478dc8643918247ee39a60b7e97f133a8b4e0c63d4ee597380923970a3ef4c0e13e25dfcfab457ba95bdbddb212016501867b9cfbfda982f907c74b282da34874a9048aa479c83838edc62982b7ac7c42d235cd67f15ac5b40c366418a2cb0c1c81e6f5e31db14c160d035de8cd4a3f18ea96562cc37359dfe9cac887fef039fd6b39446f56ea5d13a9dca4579a922496b1975b8d22dfc3566cf9557230703be715ac1431d4d2275325d7fae6b4f6f182a93ef1e32a9f41938f6a60afeb1a95c5fea53dccf772cf2c8c489240031f627e7565c0d67bbf160487c1801073bc0c31f91f953420f2bc8c7c52cc540032738a809905c0f4fa501940208e73df34028e703938a0577ae013f4a001300db4f03b71407461ce0502dca8c9c7dcf6a003fafcbdcd0070bc1e0fd734070db467b8a04cb9c9e68274b93bcb1daa40200ed4099765249ec476cf340849b8b264823bf34689ee009cb671df1409bc8e8b8e770e3ec68984d9c953cf97be2860b248caaebc107dc67f7a184c31232db88fd451031ce50e76039f5c8045026efb8f93279e0fd680b239504f0483d88ef409ee25bb90c79c0e050151c6e21b39ce783eb40adbcc2cefa17bdb61322387781c950e3dbdf9c8a066f28790b22e013db3dbef54726081e63c6460d34191b1bb0720f634060e7600412c781502409c8e3d7b500ed71dbef8ed40243f181c0a02e5d4e0fad006f644e4819e3b501f7e3049e7b501bc43b4e391da80558003392d40a23305e320d02e64cf998e1bf5a032b0c927b8e68049c8c8e71c6280377043118f4e680bbff00de0504ddbb3128371c1c64668024e59f3cd02521254e4fad1a2107e48fe6a6809ddb9e78a029e1463d05027ffc744a6c3857c7b1a205ff00e637fbf4a02b12b1794e39f4a02024e7249ed409924720906800005173fd7404989698ee39e4f7a04cf723d07a501fff0097ed406ffe36a018ff00281e99a037f4d0731f3bfd28007e53400ff99a810248c0cf140bc60123233cff008a0557f9beb4056eff007a07109243e79a03778b27bfbd02b128c27039a054001b818a06609de793da815006070283ffd9}\par}
+}
diff --git a/test/rtf/link.native b/test/rtf/link.native
new file mode 100644
--- /dev/null
+++ b/test/rtf/link.native
@@ -0,0 +1,9 @@
+Pandoc
+  Meta { unMeta = fromList [] }
+  [ Para
+      [ Link
+          ( "" , [] , [] )
+          [ Str "pandoc" ]
+          ( "http://pandoc.org" , "" )
+      ]
+  ]
diff --git a/test/rtf/link.rtf b/test/rtf/link.rtf
new file mode 100644
--- /dev/null
+++ b/test/rtf/link.rtf
@@ -0,0 +1,7 @@
+{\rtf1\ansi\deff0{\fonttbl{\f0 \fswiss Helvetica;}{\f1 \fmodern Courier;}}
+{\colortbl;\red255\green0\blue0;\red0\green0\blue255;}
+\widowctrl\hyphauto
+
+{\pard \ql \f0 \sa180 \li0 \fi0 {\field{\*\fldinst{HYPERLINK "http://pandoc.org"}}{\fldrslt{pandoc}}}
+\par}
+}
diff --git a/test/rtf/list_complex.native b/test/rtf/list_complex.native
new file mode 100644
--- /dev/null
+++ b/test/rtf/list_complex.native
@@ -0,0 +1,64 @@
+Pandoc
+  Meta
+    { unMeta =
+        fromList
+          [ ( "author"
+            , MetaInlines [ Str "Cynthia" , Space , Str "Johnson" ]
+            )
+          , ( "operator"
+            , MetaInlines [ Str "John" , Space , Str "MacFarlane" ]
+            )
+          , ( "title"
+            , MetaInlines
+                [ Str "Text"
+                , Space
+                , Str "before"
+                , Space
+                , Str "list"
+                ]
+            )
+          ]
+    }
+  [ OrderedList
+      ( 1 , Decimal , Period )
+      [ [ Para [ Str "One" ] ]
+      , [ Para [ Str "Two" ]
+        , OrderedList
+            ( 1 , LowerAlpha , Period )
+            [ [ Para [ Str "Three" ] ]
+            , [ Para [ Str "Four" ]
+              , OrderedList
+                  ( 1 , LowerRoman , Period )
+                  [ [ Para [ Str "Five" ] ]
+                  , [ Para [ Str "Six" ]
+                    , OrderedList
+                        ( 1 , UpperAlpha , Period )
+                        [ [ Para [ Str "Seven" ] ]
+                        , [ Para [ Str "Eight" ]
+                          , OrderedList
+                              ( 1 , UpperRoman , Period )
+                              [ [ Para [ Str "Nine" ] ]
+                              , [ Para [ Str "Ten" ]
+                                , BulletList
+                                    [ [ Para [ Str "Eleven" ] ]
+                                    , [ Para [ Str "Twelve" ] ]
+                                    ]
+                                ]
+                              ]
+                          ]
+                        ]
+                    ]
+                  ]
+              ]
+            ]
+        ]
+      ]
+  , Para
+      [ Str "Out" , Space , Str "of" , Space , Str "list!" ]
+  , Para [ Str "Start" , Space , Str "with" ]
+  , OrderedList
+      ( 7 , Decimal , Period )
+      [ [ Para [ Str "Seven" , Space , Str "Start" ] ]
+      , [ Para [ Str "Eight" , Space , Str "Continue" ] ]
+      ]
+  ]
diff --git a/test/rtf/list_complex.rtf b/test/rtf/list_complex.rtf
new file mode 100644
--- /dev/null
+++ b/test/rtf/list_complex.rtf
@@ -0,0 +1,299 @@
+{\rtf1\adeflang1025\ansi\ansicpg1252\uc1\adeff45\deff0\stshfdbch31505\stshfloch31506\stshfhich31506\stshfbi0\deflang1033\deflangfe1033\themelang1033\themelangfe0\themelangcs0{\fonttbl{\f0\fbidi \froman\fcharset0\fprq2{\*\panose 02020603050405020304}Times New Roman;}{\f2\fbidi \fmodern\fcharset0\fprq1{\*\panose 02070309020205020404}Courier New;}
+{\f3\fbidi \fdecor\fcharset2\fprq2{\*\panose 00000000000000000000}Symbol;}{\f34\fbidi \froman\fcharset0\fprq2{\*\panose 02040503050406030204}Cambria Math;}{\f45\fbidi \fnil\fcharset0\fprq2{\*\panose 00000000000000000000}Times;}
+{\flomajor\f31500\fbidi \froman\fcharset0\fprq2{\*\panose 02020603050405020304}Times New Roman;}{\fdbmajor\f31501\fbidi \froman\fcharset0\fprq2{\*\panose 02020603050405020304}Times New Roman;}
+{\fhimajor\f31502\fbidi \fswiss\fcharset0\fprq2{\*\panose 020f0302020204030204}Calibri Light;}{\fbimajor\f31503\fbidi \froman\fcharset0\fprq2{\*\panose 02020603050405020304}Times New Roman;}
+{\flominor\f31504\fbidi \froman\fcharset0\fprq2{\*\panose 02020603050405020304}Times New Roman;}{\fdbminor\f31505\fbidi \froman\fcharset0\fprq2{\*\panose 02020603050405020304}Times New Roman;}
+{\fhiminor\f31506\fbidi \fswiss\fcharset0\fprq2{\*\panose 020f0502020204030204}Calibri;}{\fbiminor\f31507\fbidi \froman\fcharset0\fprq2{\*\panose 02020603050405020304}Times New Roman;}{\f52\fbidi \froman\fcharset238\fprq2 Times New Roman CE;}
+{\f53\fbidi \froman\fcharset204\fprq2 Times New Roman Cyr;}{\f55\fbidi \froman\fcharset161\fprq2 Times New Roman Greek;}{\f56\fbidi \froman\fcharset162\fprq2 Times New Roman Tur;}{\f57\fbidi \froman\fcharset177\fprq2 Times New Roman (Hebrew);}
+{\f58\fbidi \froman\fcharset178\fprq2 Times New Roman (Arabic);}{\f59\fbidi \froman\fcharset186\fprq2 Times New Roman Baltic;}{\f60\fbidi \froman\fcharset163\fprq2 Times New Roman (Vietnamese);}{\f72\fbidi \fmodern\fcharset238\fprq1 Courier New CE;}
+{\f73\fbidi \fmodern\fcharset204\fprq1 Courier New Cyr;}{\f75\fbidi \fmodern\fcharset161\fprq1 Courier New Greek;}{\f76\fbidi \fmodern\fcharset162\fprq1 Courier New Tur;}{\f77\fbidi \fmodern\fcharset177\fprq1 Courier New (Hebrew);}
+{\f78\fbidi \fmodern\fcharset178\fprq1 Courier New (Arabic);}{\f79\fbidi \fmodern\fcharset186\fprq1 Courier New Baltic;}{\f80\fbidi \fmodern\fcharset163\fprq1 Courier New (Vietnamese);}{\f392\fbidi \froman\fcharset238\fprq2 Cambria Math CE;}
+{\f393\fbidi \froman\fcharset204\fprq2 Cambria Math Cyr;}{\f395\fbidi \froman\fcharset161\fprq2 Cambria Math Greek;}{\f396\fbidi \froman\fcharset162\fprq2 Cambria Math Tur;}{\f399\fbidi \froman\fcharset186\fprq2 Cambria Math Baltic;}
+{\f400\fbidi \froman\fcharset163\fprq2 Cambria Math (Vietnamese);}{\f502\fbidi \fnil\fcharset238\fprq2 Times CE;}{\f503\fbidi \fnil\fcharset204\fprq2 Times Cyr;}{\f505\fbidi \fnil\fcharset161\fprq2 Times Greek;}
+{\f506\fbidi \fnil\fcharset162\fprq2 Times Tur;}{\f509\fbidi \fnil\fcharset186\fprq2 Times Baltic;}{\f510\fbidi \fnil\fcharset163\fprq2 Times (Vietnamese);}{\flomajor\f31508\fbidi \froman\fcharset238\fprq2 Times New Roman CE;}
+{\flomajor\f31509\fbidi \froman\fcharset204\fprq2 Times New Roman Cyr;}{\flomajor\f31511\fbidi \froman\fcharset161\fprq2 Times New Roman Greek;}{\flomajor\f31512\fbidi \froman\fcharset162\fprq2 Times New Roman Tur;}
+{\flomajor\f31513\fbidi \froman\fcharset177\fprq2 Times New Roman (Hebrew);}{\flomajor\f31514\fbidi \froman\fcharset178\fprq2 Times New Roman (Arabic);}{\flomajor\f31515\fbidi \froman\fcharset186\fprq2 Times New Roman Baltic;}
+{\flomajor\f31516\fbidi \froman\fcharset163\fprq2 Times New Roman (Vietnamese);}{\fdbmajor\f31518\fbidi \froman\fcharset238\fprq2 Times New Roman CE;}{\fdbmajor\f31519\fbidi \froman\fcharset204\fprq2 Times New Roman Cyr;}
+{\fdbmajor\f31521\fbidi \froman\fcharset161\fprq2 Times New Roman Greek;}{\fdbmajor\f31522\fbidi \froman\fcharset162\fprq2 Times New Roman Tur;}{\fdbmajor\f31523\fbidi \froman\fcharset177\fprq2 Times New Roman (Hebrew);}
+{\fdbmajor\f31524\fbidi \froman\fcharset178\fprq2 Times New Roman (Arabic);}{\fdbmajor\f31525\fbidi \froman\fcharset186\fprq2 Times New Roman Baltic;}{\fdbmajor\f31526\fbidi \froman\fcharset163\fprq2 Times New Roman (Vietnamese);}
+{\fhimajor\f31528\fbidi \fswiss\fcharset238\fprq2 Calibri Light CE;}{\fhimajor\f31529\fbidi \fswiss\fcharset204\fprq2 Calibri Light Cyr;}{\fhimajor\f31531\fbidi \fswiss\fcharset161\fprq2 Calibri Light Greek;}
+{\fhimajor\f31532\fbidi \fswiss\fcharset162\fprq2 Calibri Light Tur;}{\fhimajor\f31533\fbidi \fswiss\fcharset177\fprq2 Calibri Light (Hebrew);}{\fhimajor\f31534\fbidi \fswiss\fcharset178\fprq2 Calibri Light (Arabic);}
+{\fhimajor\f31535\fbidi \fswiss\fcharset186\fprq2 Calibri Light Baltic;}{\fhimajor\f31536\fbidi \fswiss\fcharset163\fprq2 Calibri Light (Vietnamese);}{\fbimajor\f31538\fbidi \froman\fcharset238\fprq2 Times New Roman CE;}
+{\fbimajor\f31539\fbidi \froman\fcharset204\fprq2 Times New Roman Cyr;}{\fbimajor\f31541\fbidi \froman\fcharset161\fprq2 Times New Roman Greek;}{\fbimajor\f31542\fbidi \froman\fcharset162\fprq2 Times New Roman Tur;}
+{\fbimajor\f31543\fbidi \froman\fcharset177\fprq2 Times New Roman (Hebrew);}{\fbimajor\f31544\fbidi \froman\fcharset178\fprq2 Times New Roman (Arabic);}{\fbimajor\f31545\fbidi \froman\fcharset186\fprq2 Times New Roman Baltic;}
+{\fbimajor\f31546\fbidi \froman\fcharset163\fprq2 Times New Roman (Vietnamese);}{\flominor\f31548\fbidi \froman\fcharset238\fprq2 Times New Roman CE;}{\flominor\f31549\fbidi \froman\fcharset204\fprq2 Times New Roman Cyr;}
+{\flominor\f31551\fbidi \froman\fcharset161\fprq2 Times New Roman Greek;}{\flominor\f31552\fbidi \froman\fcharset162\fprq2 Times New Roman Tur;}{\flominor\f31553\fbidi \froman\fcharset177\fprq2 Times New Roman (Hebrew);}
+{\flominor\f31554\fbidi \froman\fcharset178\fprq2 Times New Roman (Arabic);}{\flominor\f31555\fbidi \froman\fcharset186\fprq2 Times New Roman Baltic;}{\flominor\f31556\fbidi \froman\fcharset163\fprq2 Times New Roman (Vietnamese);}
+{\fdbminor\f31558\fbidi \froman\fcharset238\fprq2 Times New Roman CE;}{\fdbminor\f31559\fbidi \froman\fcharset204\fprq2 Times New Roman Cyr;}{\fdbminor\f31561\fbidi \froman\fcharset161\fprq2 Times New Roman Greek;}
+{\fdbminor\f31562\fbidi \froman\fcharset162\fprq2 Times New Roman Tur;}{\fdbminor\f31563\fbidi \froman\fcharset177\fprq2 Times New Roman (Hebrew);}{\fdbminor\f31564\fbidi \froman\fcharset178\fprq2 Times New Roman (Arabic);}
+{\fdbminor\f31565\fbidi \froman\fcharset186\fprq2 Times New Roman Baltic;}{\fdbminor\f31566\fbidi \froman\fcharset163\fprq2 Times New Roman (Vietnamese);}{\fhiminor\f31568\fbidi \fswiss\fcharset238\fprq2 Calibri CE;}
+{\fhiminor\f31569\fbidi \fswiss\fcharset204\fprq2 Calibri Cyr;}{\fhiminor\f31571\fbidi \fswiss\fcharset161\fprq2 Calibri Greek;}{\fhiminor\f31572\fbidi \fswiss\fcharset162\fprq2 Calibri Tur;}
+{\fhiminor\f31575\fbidi \fswiss\fcharset186\fprq2 Calibri Baltic;}{\fbiminor\f31578\fbidi \froman\fcharset238\fprq2 Times New Roman CE;}{\fbiminor\f31579\fbidi \froman\fcharset204\fprq2 Times New Roman Cyr;}
+{\fbiminor\f31581\fbidi \froman\fcharset161\fprq2 Times New Roman Greek;}{\fbiminor\f31582\fbidi \froman\fcharset162\fprq2 Times New Roman Tur;}{\fbiminor\f31583\fbidi \froman\fcharset177\fprq2 Times New Roman (Hebrew);}
+{\fbiminor\f31584\fbidi \froman\fcharset178\fprq2 Times New Roman (Arabic);}{\fbiminor\f31585\fbidi \froman\fcharset186\fprq2 Times New Roman Baltic;}{\fbiminor\f31586\fbidi \froman\fcharset163\fprq2 Times New Roman (Vietnamese);}}
+{\colortbl;\red0\green0\blue0;\red0\green0\blue255;\red0\green255\blue255;\red0\green255\blue0;\red255\green0\blue255;\red255\green0\blue0;\red255\green255\blue0;\red255\green255\blue255;\red0\green0\blue128;\red0\green128\blue128;\red0\green128\blue0;
+\red128\green0\blue128;\red128\green0\blue0;\red128\green128\blue0;\red128\green128\blue128;\red192\green192\blue192;\red0\green0\blue0;\red0\green0\blue0;}{\*\defchp \fs24\loch\af31506\hich\af31506\dbch\af31505 }{\*\defpap 
+\ql \li0\ri0\widctlpar\wrapdefault\aspalpha\aspnum\faauto\adjustright\rin0\lin0\itap0 }\noqfpromote {\stylesheet{\ql \li0\ri0\widctlpar\wrapdefault\aspalpha\aspnum\faauto\adjustright\rin0\lin0\itap0 \rtlch\fcs1 \af45\afs24\alang1025 \ltrch\fcs0 
+\fs24\lang1033\langfe1033\loch\f45\hich\af45\dbch\af31505\cgrid\langnp1033\langfenp1033 \snext0 \sqformat \spriority0 Normal;}{\*\cs10 \additive Default Paragraph Font;}{\*
+\ts11\tsrowd\trftsWidthB3\trpaddl108\trpaddr108\trpaddfl3\trpaddft3\trpaddfb3\trpaddfr3\trcbpat1\trcfpat1\tblind0\tblindtype3\tsvertalt\tsbrdrt\tsbrdrl\tsbrdrb\tsbrdrr\tsbrdrdgl\tsbrdrdgr\tsbrdrh\tsbrdrv 
+\ql \li0\ri0\widctlpar\wrapdefault\aspalpha\aspnum\faauto\adjustright\rin0\lin0\itap0 \rtlch\fcs1 \af0\afs24\alang1025 \ltrch\fcs0 \fs24\lang1033\langfe1033\loch\f31506\hich\af31506\dbch\af31505\cgrid\langnp1033\langfenp1033 
+\snext11 \ssemihidden \sunhideused Normal Table;}}{\*\listtable{\list\listtemplateid2032649{\listlevel\levelnfc23\levelnfcn23\leveljc0\leveljcn0\levelfollow0\levelstartat1\levelspace0\levelindent0{\leveltext\'01\u-3913 _;}{\levelnumbers;}
+\fs28\cf0\loch\af3\hich\af3\dbch\af0\fbias0\hres0\chhres0 \fi-360\li360\jclisttab\tx360\lin360 }{\listlevel\levelnfc0\levelnfcn0\leveljc0\leveljcn0\levelfollow0\levelstartat1\levelspace0\levelindent0{\leveltext\'04\'00.\'01.;}{\levelnumbers\'01\'03;}
+\rtlch\fcs1 \af0 \ltrch\fcs0 \hres0\chhres0 \fi-432\li792\jclisttab\tx792\lin792 }{\listlevel\levelnfc0\levelnfcn0\leveljc0\leveljcn0\levelfollow0\levelstartat1\levelspace0\levelindent0{\leveltext\'06\'00.\'01.\'02.;}{\levelnumbers\'01\'03\'05;}
+\rtlch\fcs1 \af0 \ltrch\fcs0 \hres0\chhres0 \fi-504\li1224\jclisttab\tx1440\lin1224 }{\listlevel\levelnfc0\levelnfcn0\leveljc0\leveljcn0\levelfollow0\levelstartat1\levelspace0\levelindent0{\leveltext\'08\'00.\'01.\'02.\'03.;}{\levelnumbers
+\'01\'03\'05\'07;}\rtlch\fcs1 \af0 \ltrch\fcs0 \hres0\chhres0 \fi-648\li1728\jclisttab\tx2160\lin1728 }{\listlevel\levelnfc0\levelnfcn0\leveljc0\leveljcn0\levelfollow0\levelstartat1\levelspace0\levelindent0{\leveltext
+\'0a\'00.\'01.\'02.\'03.\'04.;}{\levelnumbers\'01\'03\'05\'07\'09;}\rtlch\fcs1 \af0 \ltrch\fcs0 \hres0\chhres0 \fi-792\li2232\jclisttab\tx2520\lin2232 }{\listlevel\levelnfc0\levelnfcn0\leveljc0\leveljcn0\levelfollow0\levelstartat1\levelspace0\levelindent0
+{\leveltext\'0c\'00.\'01.\'02.\'03.\'04.\'05.;}{\levelnumbers\'01\'03\'05\'07\'09\'0b;}\rtlch\fcs1 \af0 \ltrch\fcs0 \hres0\chhres0 \fi-936\li2736\jclisttab\tx3240\lin2736 }{\listlevel\levelnfc0\levelnfcn0\leveljc0\leveljcn0\levelfollow0\levelstartat1
+\levelspace0\levelindent0{\leveltext\'0e\'00.\'01.\'02.\'03.\'04.\'05.\'06.;}{\levelnumbers\'01\'03\'05\'07\'09\'0b\'0d;}\rtlch\fcs1 \af0 \ltrch\fcs0 \hres0\chhres0 \fi-1080\li3240\jclisttab\tx3600\lin3240 }{\listlevel\levelnfc0\levelnfcn0\leveljc0
+\leveljcn0\levelfollow0\levelstartat1\levelspace0\levelindent0{\leveltext\'10\'00.\'01.\'02.\'03.\'04.\'05.\'06.\'07.;}{\levelnumbers\'01\'03\'05\'07\'09\'0b\'0d\'0f;}\rtlch\fcs1 \af0 \ltrch\fcs0 \hres0\chhres0 \fi-1224\li3744\jclisttab\tx4320\lin3744 }
+{\listlevel\levelnfc0\levelnfcn0\leveljc0\leveljcn0\levelfollow0\levelstartat1\levelspace0\levelindent0{\leveltext\'12\'00.\'01.\'02.\'03.\'04.\'05.\'06.\'07.\'08.;}{\levelnumbers\'01\'03\'05\'07\'09\'0b\'0d\'0f\'11;}\rtlch\fcs1 \af0 \ltrch\fcs0 
+\hres0\chhres0 \fi-1440\li4320\jclisttab\tx4680\lin4320 }{\listname ;}\listid161162663}{\list\listtemplateid-1055851588{\listlevel\levelnfc0\levelnfcn0\leveljc0\leveljcn0\levelfollow0\levelstartat1\levelspace0\levelindent0{\leveltext
+\'02\'00.;}{\levelnumbers\'01;}\rtlch\fcs1 \af0 \ltrch\fcs0 \fbias0\hres0\chhres0 \fi-360\li720\lin720 }{\listlevel\levelnfc4\levelnfcn4\leveljc0\leveljcn0\levelfollow0\levelstartat1\levelspace0\levelindent0{\leveltext\'02\'01.;}{\levelnumbers\'01;}
+\rtlch\fcs1 \af0 \ltrch\fcs0 \hres0\chhres0 \fi-360\li1440\lin1440 }{\listlevel\levelnfc2\levelnfcn2\leveljc2\leveljcn2\levelfollow0\levelstartat1\levelspace0\levelindent0{\leveltext\'02\'02.;}{\levelnumbers\'01;}\rtlch\fcs1 \af0 \ltrch\fcs0 
+\hres0\chhres0 \fi-180\li2160\lin2160 }{\listlevel\levelnfc3\levelnfcn3\leveljc0\leveljcn0\levelfollow0\levelstartat1\levelspace360\levelindent0{\leveltext\'02\'03.;}{\levelnumbers\'01;}\rtlch\fcs1 \af0 \ltrch\fcs0 \hres0\chhres0 \fi-360\li2880\lin2880 }
+{\listlevel\levelnfc1\levelnfcn1\leveljc2\leveljcn2\levelfollow0\levelstartat1\levelspace540\levelindent0{\leveltext\'02\'04.;}{\levelnumbers\'01;}\rtlch\fcs1 \af0 \ltrch\fcs0 \hres0\chhres0 \fi-180\li3420\lin3420 }{\listlevel\levelnfc23\levelnfcn23
+\leveljc0\leveljcn0\levelfollow0\levelstartat1\levelspace360\levelindent0{\leveltext\'01o;}{\levelnumbers;}\f2\fbias0\hres0\chhres0 \fi-360\li4500\lin4500 }{\listlevel\levelnfc0\levelnfcn0\leveljc0\leveljcn0\levelfollow0\levelstartat1\levelspace0
+\levelindent0{\leveltext\'02\'06.;}{\levelnumbers\'01;}\rtlch\fcs1 \af0 \ltrch\fcs0 \hres0\chhres0 \fi-360\li5040\lin5040 }{\listlevel\levelnfc4\levelnfcn4\leveljc0\leveljcn0\levelfollow0\levelstartat1\levelspace0\levelindent0{\leveltext
+\'02\'07.;}{\levelnumbers\'01;}\rtlch\fcs1 \af0 \ltrch\fcs0 \hres0\chhres0 \fi-360\li5760\lin5760 }{\listlevel\levelnfc2\levelnfcn2\leveljc2\leveljcn2\levelfollow0\levelstartat1\levelspace0\levelindent0{\leveltext\'02\'08.;}{\levelnumbers\'01;}
+\rtlch\fcs1 \af0 \ltrch\fcs0 \hres0\chhres0 \fi-180\li6480\lin6480 }{\listname ;}\listid180975272}{\list\listtemplateid-1055851588\listhybrid{\listlevel\levelnfc0\levelnfcn0\leveljc0\leveljcn0\levelfollow0\levelstartat1\levelspace0\levelindent0{\leveltext
+\leveltemplateid67698703\'02\'00.;}{\levelnumbers\'01;}\rtlch\fcs1 \af0 \ltrch\fcs0 \fbias0\hres0\chhres0 \fi-360\li720\lin720 }{\listlevel\levelnfc4\levelnfcn4\leveljc0\leveljcn0\levelfollow0\levelstartat1\levelspace0\levelindent0{\leveltext
+\leveltemplateid67698713\'02\'01.;}{\levelnumbers\'01;}\rtlch\fcs1 \af0 \ltrch\fcs0 \hres0\chhres0 \fi-360\li1440\lin1440 }{\listlevel\levelnfc2\levelnfcn2\leveljc2\leveljcn2\levelfollow0\levelstartat1\levelspace0\levelindent0{\leveltext
+\leveltemplateid67698715\'02\'02.;}{\levelnumbers\'01;}\rtlch\fcs1 \af0 \ltrch\fcs0 \hres0\chhres0 \fi-180\li2160\lin2160 }{\listlevel\levelnfc3\levelnfcn3\leveljc0\leveljcn0\levelfollow0\levelstartat1\levelspace360\levelindent0{\leveltext
+\leveltemplateid67698709\'02\'03.;}{\levelnumbers\'01;}\rtlch\fcs1 \af0 \ltrch\fcs0 \hres0\chhres0 \fi-360\li2880\lin2880 }{\listlevel\levelnfc1\levelnfcn1\leveljc2\leveljcn2\levelfollow0\levelstartat1\levelspace540\levelindent0{\leveltext
+\leveltemplateid67698707\'02\'04.;}{\levelnumbers\'01;}\rtlch\fcs1 \af0 \ltrch\fcs0 \hres0\chhres0 \fi-180\li3420\lin3420 }{\listlevel\levelnfc23\levelnfcn23\leveljc0\leveljcn0\levelfollow0\levelstartat1\levelspace360\levelindent0{\leveltext
+\leveltemplateid67698691\'01o;}{\levelnumbers;}\f2\fbias0\hres0\chhres0 \fi-360\li4500\lin4500 }{\listlevel\levelnfc0\levelnfcn0\leveljc0\leveljcn0\levelfollow0\levelstartat1\lvltentative\levelspace0\levelindent0{\leveltext\leveltemplateid67698703
+\'02\'06.;}{\levelnumbers\'01;}\rtlch\fcs1 \af0 \ltrch\fcs0 \hres0\chhres0 \fi-360\li5040\lin5040 }{\listlevel\levelnfc4\levelnfcn4\leveljc0\leveljcn0\levelfollow0\levelstartat1\lvltentative\levelspace0\levelindent0{\leveltext\leveltemplateid67698713
+\'02\'07.;}{\levelnumbers\'01;}\rtlch\fcs1 \af0 \ltrch\fcs0 \hres0\chhres0 \fi-360\li5760\lin5760 }{\listlevel\levelnfc2\levelnfcn2\leveljc2\leveljcn2\levelfollow0\levelstartat1\lvltentative\levelspace0\levelindent0{\leveltext\leveltemplateid67698715
+\'02\'08.;}{\levelnumbers\'01;}\rtlch\fcs1 \af0 \ltrch\fcs0 \hres0\chhres0 \fi-180\li6480\lin6480 }{\listname ;}\listid581336416}{\list\listtemplateid-1516889114\listhybrid{\listlevel\levelnfc0\levelnfcn0\leveljc0\leveljcn0\levelfollow0\levelstartat1
+\levelspace0\levelindent0{\leveltext\leveltemplateid67698703\'02\'00.;}{\levelnumbers\'01;}\rtlch\fcs1 \af0 \ltrch\fcs0 \fbias0\hres0\chhres0 \fi-360\li720\lin720 }{\listlevel\levelnfc4\levelnfcn4\leveljc0\leveljcn0\levelfollow0\levelstartat1\lvltentative
+\levelspace0\levelindent0{\leveltext\leveltemplateid67698713\'02\'01.;}{\levelnumbers\'01;}\rtlch\fcs1 \af0 \ltrch\fcs0 \hres0\chhres0 \fi-360\li1440\lin1440 }{\listlevel\levelnfc2\levelnfcn2\leveljc2\leveljcn2\levelfollow0\levelstartat1\lvltentative
+\levelspace0\levelindent0{\leveltext\leveltemplateid67698715\'02\'02.;}{\levelnumbers\'01;}\rtlch\fcs1 \af0 \ltrch\fcs0 \hres0\chhres0 \fi-180\li2160\lin2160 }{\listlevel\levelnfc0\levelnfcn0\leveljc0\leveljcn0\levelfollow0\levelstartat1\lvltentative
+\levelspace0\levelindent0{\leveltext\leveltemplateid67698703\'02\'03.;}{\levelnumbers\'01;}\rtlch\fcs1 \af0 \ltrch\fcs0 \hres0\chhres0 \fi-360\li2880\lin2880 }{\listlevel\levelnfc4\levelnfcn4\leveljc0\leveljcn0\levelfollow0\levelstartat1\lvltentative
+\levelspace0\levelindent0{\leveltext\leveltemplateid67698713\'02\'04.;}{\levelnumbers\'01;}\rtlch\fcs1 \af0 \ltrch\fcs0 \hres0\chhres0 \fi-360\li3600\lin3600 }{\listlevel\levelnfc2\levelnfcn2\leveljc2\leveljcn2\levelfollow0\levelstartat1\lvltentative
+\levelspace0\levelindent0{\leveltext\leveltemplateid67698715\'02\'05.;}{\levelnumbers\'01;}\rtlch\fcs1 \af0 \ltrch\fcs0 \hres0\chhres0 \fi-180\li4320\lin4320 }{\listlevel\levelnfc0\levelnfcn0\leveljc0\leveljcn0\levelfollow0\levelstartat1\lvltentative
+\levelspace0\levelindent0{\leveltext\leveltemplateid67698703\'02\'06.;}{\levelnumbers\'01;}\rtlch\fcs1 \af0 \ltrch\fcs0 \hres0\chhres0 \fi-360\li5040\lin5040 }{\listlevel\levelnfc4\levelnfcn4\leveljc0\leveljcn0\levelfollow0\levelstartat1\lvltentative
+\levelspace0\levelindent0{\leveltext\leveltemplateid67698713\'02\'07.;}{\levelnumbers\'01;}\rtlch\fcs1 \af0 \ltrch\fcs0 \hres0\chhres0 \fi-360\li5760\lin5760 }{\listlevel\levelnfc2\levelnfcn2\leveljc2\leveljcn2\levelfollow0\levelstartat1\lvltentative
+\levelspace0\levelindent0{\leveltext\leveltemplateid67698715\'02\'08.;}{\levelnumbers\'01;}\rtlch\fcs1 \af0 \ltrch\fcs0 \hres0\chhres0 \fi-180\li6480\lin6480 }{\listname ;}\listid592708402}{\list\listtemplateid353931476{\listlevel\levelnfc0\levelnfcn0
+\leveljc0\leveljcn0\levelfollow0\levelstartat1\levelspace0\levelindent0{\leveltext\'02\'00.;}{\levelnumbers\'01;}\rtlch\fcs1 \af0 \ltrch\fcs0 \fbias0\hres0\chhres0 \fi-360\li720\lin720 }{\listlevel\levelnfc4\levelnfcn4\leveljc0\leveljcn0\levelfollow0
+\levelstartat1\levelspace0\levelindent0{\leveltext\'02\'01.;}{\levelnumbers\'01;}\rtlch\fcs1 \af0 \ltrch\fcs0 \hres0\chhres0 \fi-360\li1440\lin1440 }{\listlevel\levelnfc2\levelnfcn2\leveljc2\leveljcn2\levelfollow0\levelstartat1\levelspace0\levelindent0
+{\leveltext\'02\'02.;}{\levelnumbers\'01;}\rtlch\fcs1 \af0 \ltrch\fcs0 \hres0\chhres0 \fi-180\li2160\lin2160 }{\listlevel\levelnfc3\levelnfcn3\leveljc0\leveljcn0\levelfollow0\levelstartat1\levelspace360\levelindent0{\leveltext\'02\'03.;}{\levelnumbers
+\'01;}\rtlch\fcs1 \af0 \ltrch\fcs0 \hres0\chhres0 \fi-360\li2880\lin2880 }{\listlevel\levelnfc1\levelnfcn1\leveljc2\leveljcn2\levelfollow0\levelstartat1\levelspace540\levelindent0{\leveltext\'02\'04.;}{\levelnumbers\'01;}\rtlch\fcs1 \af0 \ltrch\fcs0 
+\hres0\chhres0 \fi-180\li3420\lin3420 }{\listlevel\levelnfc2\levelnfcn2\leveljc2\leveljcn2\levelfollow0\levelstartat1\levelspace0\levelindent0{\leveltext\'02\'05.;}{\levelnumbers\'01;}\rtlch\fcs1 \af0 \ltrch\fcs0 \hres0\chhres0 \fi-180\li4320\lin4320 }
+{\listlevel\levelnfc0\levelnfcn0\leveljc0\leveljcn0\levelfollow0\levelstartat1\levelspace0\levelindent0{\leveltext\'02\'06.;}{\levelnumbers\'01;}\rtlch\fcs1 \af0 \ltrch\fcs0 \hres0\chhres0 \fi-360\li5040\lin5040 }{\listlevel\levelnfc4\levelnfcn4\leveljc0
+\leveljcn0\levelfollow0\levelstartat1\levelspace0\levelindent0{\leveltext\'02\'07.;}{\levelnumbers\'01;}\rtlch\fcs1 \af0 \ltrch\fcs0 \hres0\chhres0 \fi-360\li5760\lin5760 }{\listlevel\levelnfc2\levelnfcn2\leveljc2\leveljcn2\levelfollow0\levelstartat1
+\levelspace0\levelindent0{\leveltext\'02\'08.;}{\levelnumbers\'01;}\rtlch\fcs1 \af0 \ltrch\fcs0 \hres0\chhres0 \fi-180\li6480\lin6480 }{\listname ;}\listid621182402}{\list\listtemplateid-37037068{\listlevel\levelnfc0\levelnfcn0\leveljc0\leveljcn0
+\levelfollow0\levelstartat1\levelspace0\levelindent0{\leveltext\'02\'00.;}{\levelnumbers\'01;}\rtlch\fcs1 \af0 \ltrch\fcs0 \fbias0\hres0\chhres0 \fi-360\li720\lin720 }{\listlevel\levelnfc4\levelnfcn4\leveljc0\leveljcn0\levelfollow0\levelstartat1
+\levelspace0\levelindent0{\leveltext\'02\'01.;}{\levelnumbers\'01;}\rtlch\fcs1 \af0 \ltrch\fcs0 \hres0\chhres0 \fi-360\li1440\lin1440 }{\listlevel\levelnfc2\levelnfcn2\leveljc2\leveljcn2\levelfollow0\levelstartat1\levelspace0\levelindent0{\leveltext
+\'02\'02.;}{\levelnumbers\'01;}\rtlch\fcs1 \af0 \ltrch\fcs0 \hres0\chhres0 \fi-180\li2160\lin2160 }{\listlevel\levelnfc0\levelnfcn0\leveljc0\leveljcn0\levelfollow0\levelstartat1\levelspace0\levelindent0{\leveltext\'02\'03.;}{\levelnumbers\'01;}
+\rtlch\fcs1 \af0 \ltrch\fcs0 \hres0\chhres0 \fi-360\li2880\lin2880 }{\listlevel\levelnfc4\levelnfcn4\leveljc0\leveljcn0\levelfollow0\levelstartat1\levelspace0\levelindent0{\leveltext\'02\'04.;}{\levelnumbers\'01;}\rtlch\fcs1 \af0 \ltrch\fcs0 
+\hres0\chhres0 \fi-360\li3600\lin3600 }{\listlevel\levelnfc2\levelnfcn2\leveljc2\leveljcn2\levelfollow0\levelstartat1\levelspace0\levelindent0{\leveltext\'02\'05.;}{\levelnumbers\'01;}\rtlch\fcs1 \af0 \ltrch\fcs0 \hres0\chhres0 \fi-180\li4320\lin4320 }
+{\listlevel\levelnfc0\levelnfcn0\leveljc0\leveljcn0\levelfollow0\levelstartat1\levelspace0\levelindent0{\leveltext\'02\'06.;}{\levelnumbers\'01;}\rtlch\fcs1 \af0 \ltrch\fcs0 \hres0\chhres0 \fi-360\li5040\lin5040 }{\listlevel\levelnfc4\levelnfcn4\leveljc0
+\leveljcn0\levelfollow0\levelstartat1\levelspace0\levelindent0{\leveltext\'02\'07.;}{\levelnumbers\'01;}\rtlch\fcs1 \af0 \ltrch\fcs0 \hres0\chhres0 \fi-360\li5760\lin5760 }{\listlevel\levelnfc2\levelnfcn2\leveljc2\leveljcn2\levelfollow0\levelstartat1
+\levelspace0\levelindent0{\leveltext\'02\'08.;}{\levelnumbers\'01;}\rtlch\fcs1 \af0 \ltrch\fcs0 \hres0\chhres0 \fi-180\li6480\lin6480 }{\listname ;}\listid982349901}{\list\listtemplateid-2094603378{\listlevel\levelnfc0\levelnfcn0\leveljc0\leveljcn0
+\levelfollow0\levelstartat1\levelspace0\levelindent0{\leveltext\'02\'00.;}{\levelnumbers\'01;}\rtlch\fcs1 \af0 \ltrch\fcs0 \fbias0\hres0\chhres0 \fi-360\li720\lin720 }{\listlevel\levelnfc4\levelnfcn4\leveljc0\leveljcn0\levelfollow0\levelstartat1
+\levelspace0\levelindent0{\leveltext\'02\'01.;}{\levelnumbers\'01;}\rtlch\fcs1 \af0 \ltrch\fcs0 \hres0\chhres0 \fi-360\li1440\lin1440 }{\listlevel\levelnfc2\levelnfcn2\leveljc2\leveljcn2\levelfollow0\levelstartat1\levelspace0\levelindent0{\leveltext
+\'02\'02.;}{\levelnumbers\'01;}\rtlch\fcs1 \af0 \ltrch\fcs0 \hres0\chhres0 \fi-180\li2160\lin2160 }{\listlevel\levelnfc0\levelnfcn0\leveljc0\leveljcn0\levelfollow0\levelstartat1\levelspace0\levelindent0{\leveltext\'02\'03.;}{\levelnumbers\'01;}
+\rtlch\fcs1 \af0 \ltrch\fcs0 \hres0\chhres0 \fi-360\li2880\lin2880 }{\listlevel\levelnfc4\levelnfcn4\leveljc0\leveljcn0\levelfollow0\levelstartat1\levelspace0\levelindent0{\leveltext\'02\'04.;}{\levelnumbers\'01;}\rtlch\fcs1 \af0 \ltrch\fcs0 
+\hres0\chhres0 \fi-360\li3600\lin3600 }{\listlevel\levelnfc2\levelnfcn2\leveljc2\leveljcn2\levelfollow0\levelstartat1\levelspace0\levelindent0{\leveltext\'02\'05.;}{\levelnumbers\'01;}\rtlch\fcs1 \af0 \ltrch\fcs0 \hres0\chhres0 \fi-180\li4320\lin4320 }
+{\listlevel\levelnfc0\levelnfcn0\leveljc0\leveljcn0\levelfollow0\levelstartat1\levelspace0\levelindent0{\leveltext\'02\'06.;}{\levelnumbers\'01;}\rtlch\fcs1 \af0 \ltrch\fcs0 \hres0\chhres0 \fi-360\li5040\lin5040 }{\listlevel\levelnfc4\levelnfcn4\leveljc0
+\leveljcn0\levelfollow0\levelstartat1\levelspace0\levelindent0{\leveltext\'02\'07.;}{\levelnumbers\'01;}\rtlch\fcs1 \af0 \ltrch\fcs0 \hres0\chhres0 \fi-360\li5760\lin5760 }{\listlevel\levelnfc2\levelnfcn2\leveljc2\leveljcn2\levelfollow0\levelstartat1
+\levelspace0\levelindent0{\leveltext\'02\'08.;}{\levelnumbers\'01;}\rtlch\fcs1 \af0 \ltrch\fcs0 \hres0\chhres0 \fi-180\li6480\lin6480 }{\listname ;}\listid1082678316}{\list\listtemplateid166376406\listhybrid{\listlevel\levelnfc0\levelnfcn0\leveljc0
+\leveljcn0\levelfollow0\levelstartat7\levelspace0\levelindent0{\leveltext\leveltemplateid-1898031884\'02\'00.;}{\levelnumbers\'01;}\rtlch\fcs1 \af0 \ltrch\fcs0 \fbias0\hres0\chhres0 \fi-360\li720\lin720 }{\listlevel\levelnfc4\levelnfcn4\leveljc0\leveljcn0
+\levelfollow0\levelstartat1\lvltentative\levelspace0\levelindent0{\leveltext\leveltemplateid67698713\'02\'01.;}{\levelnumbers\'01;}\rtlch\fcs1 \af0 \ltrch\fcs0 \hres0\chhres0 \fi-360\li1440\lin1440 }{\listlevel\levelnfc2\levelnfcn2\leveljc2\leveljcn2
+\levelfollow0\levelstartat1\lvltentative\levelspace0\levelindent0{\leveltext\leveltemplateid67698715\'02\'02.;}{\levelnumbers\'01;}\rtlch\fcs1 \af0 \ltrch\fcs0 \hres0\chhres0 \fi-180\li2160\lin2160 }{\listlevel\levelnfc0\levelnfcn0\leveljc0\leveljcn0
+\levelfollow0\levelstartat1\lvltentative\levelspace0\levelindent0{\leveltext\leveltemplateid67698703\'02\'03.;}{\levelnumbers\'01;}\rtlch\fcs1 \af0 \ltrch\fcs0 \hres0\chhres0 \fi-360\li2880\lin2880 }{\listlevel\levelnfc4\levelnfcn4\leveljc0\leveljcn0
+\levelfollow0\levelstartat1\lvltentative\levelspace0\levelindent0{\leveltext\leveltemplateid67698713\'02\'04.;}{\levelnumbers\'01;}\rtlch\fcs1 \af0 \ltrch\fcs0 \hres0\chhres0 \fi-360\li3600\lin3600 }{\listlevel\levelnfc2\levelnfcn2\leveljc2\leveljcn2
+\levelfollow0\levelstartat1\lvltentative\levelspace0\levelindent0{\leveltext\leveltemplateid67698715\'02\'05.;}{\levelnumbers\'01;}\rtlch\fcs1 \af0 \ltrch\fcs0 \hres0\chhres0 \fi-180\li4320\lin4320 }{\listlevel\levelnfc0\levelnfcn0\leveljc0\leveljcn0
+\levelfollow0\levelstartat1\lvltentative\levelspace0\levelindent0{\leveltext\leveltemplateid67698703\'02\'06.;}{\levelnumbers\'01;}\rtlch\fcs1 \af0 \ltrch\fcs0 \hres0\chhres0 \fi-360\li5040\lin5040 }{\listlevel\levelnfc4\levelnfcn4\leveljc0\leveljcn0
+\levelfollow0\levelstartat1\lvltentative\levelspace0\levelindent0{\leveltext\leveltemplateid67698713\'02\'07.;}{\levelnumbers\'01;}\rtlch\fcs1 \af0 \ltrch\fcs0 \hres0\chhres0 \fi-360\li5760\lin5760 }{\listlevel\levelnfc2\levelnfcn2\leveljc2\leveljcn2
+\levelfollow0\levelstartat1\lvltentative\levelspace0\levelindent0{\leveltext\leveltemplateid67698715\'02\'08.;}{\levelnumbers\'01;}\rtlch\fcs1 \af0 \ltrch\fcs0 \hres0\chhres0 \fi-180\li6480\lin6480 }{\listname ;}\listid1306352145}
+{\list\listtemplateid2032649{\listlevel\levelnfc0\levelnfcn0\leveljc0\leveljcn0\levelfollow0\levelstartat1\levelspace0\levelindent0{\leveltext\'02\'00.;}{\levelnumbers\'01;}\rtlch\fcs1 \af0 \ltrch\fcs0 \hres0\chhres0 \fi-360\li360\jclisttab\tx360\lin360 }
+{\listlevel\levelnfc0\levelnfcn0\leveljc0\leveljcn0\levelfollow0\levelstartat1\levelspace0\levelindent0{\leveltext\'04\'00.\'01.;}{\levelnumbers\'01\'03;}\rtlch\fcs1 \af0 \ltrch\fcs0 \hres0\chhres0 \fi-432\li792\jclisttab\tx792\lin792 }{\listlevel
+\levelnfc0\levelnfcn0\leveljc0\leveljcn0\levelfollow0\levelstartat1\levelspace0\levelindent0{\leveltext\'06\'00.\'01.\'02.;}{\levelnumbers\'01\'03\'05;}\rtlch\fcs1 \af0 \ltrch\fcs0 \hres0\chhres0 \fi-504\li1224\jclisttab\tx1440\lin1224 }{\listlevel
+\levelnfc0\levelnfcn0\leveljc0\leveljcn0\levelfollow0\levelstartat1\levelspace0\levelindent0{\leveltext\'08\'00.\'01.\'02.\'03.;}{\levelnumbers\'01\'03\'05\'07;}\rtlch\fcs1 \af0 \ltrch\fcs0 \hres0\chhres0 \fi-648\li1728\jclisttab\tx2160\lin1728 }
+{\listlevel\levelnfc0\levelnfcn0\leveljc0\leveljcn0\levelfollow0\levelstartat1\levelspace0\levelindent0{\leveltext\'0a\'00.\'01.\'02.\'03.\'04.;}{\levelnumbers\'01\'03\'05\'07\'09;}\rtlch\fcs1 \af0 \ltrch\fcs0 \hres0\chhres0 \fi-792\li2232
+\jclisttab\tx2520\lin2232 }{\listlevel\levelnfc0\levelnfcn0\leveljc0\leveljcn0\levelfollow0\levelstartat1\levelspace0\levelindent0{\leveltext\'0c\'00.\'01.\'02.\'03.\'04.\'05.;}{\levelnumbers\'01\'03\'05\'07\'09\'0b;}\rtlch\fcs1 \af0 \ltrch\fcs0 
+\hres0\chhres0 \fi-936\li2736\jclisttab\tx3240\lin2736 }{\listlevel\levelnfc0\levelnfcn0\leveljc0\leveljcn0\levelfollow0\levelstartat1\levelspace0\levelindent0{\leveltext\'0e\'00.\'01.\'02.\'03.\'04.\'05.\'06.;}{\levelnumbers\'01\'03\'05\'07\'09\'0b\'0d;}
+\rtlch\fcs1 \af0 \ltrch\fcs0 \hres0\chhres0 \fi-1080\li3240\jclisttab\tx3600\lin3240 }{\listlevel\levelnfc0\levelnfcn0\leveljc0\leveljcn0\levelfollow0\levelstartat1\levelspace0\levelindent0{\leveltext
+\'10\'00.\'01.\'02.\'03.\'04.\'05.\'06.\'07.;}{\levelnumbers\'01\'03\'05\'07\'09\'0b\'0d\'0f;}\rtlch\fcs1 \af0 \ltrch\fcs0 \hres0\chhres0 \fi-1224\li3744\jclisttab\tx4320\lin3744 }{\listlevel\levelnfc0\levelnfcn0\leveljc0\leveljcn0\levelfollow0
+\levelstartat1\levelspace0\levelindent0{\leveltext\'12\'00.\'01.\'02.\'03.\'04.\'05.\'06.\'07.\'08.;}{\levelnumbers\'01\'03\'05\'07\'09\'0b\'0d\'0f\'11;}\rtlch\fcs1 \af0 \ltrch\fcs0 \hres0\chhres0 \fi-1440\li4320\jclisttab\tx4680\lin4320 }{\listname 
+;}\listid1517575639}{\list\listtemplateid-2069710980{\listlevel\levelnfc0\levelnfcn0\leveljc0\leveljcn0\levelfollow0\levelstartat1\levelspace0\levelindent0{\leveltext\'02\'00.;}{\levelnumbers\'01;}\rtlch\fcs1 \af0 \ltrch\fcs0 \fbias0\hres0\chhres0 
+\fi-360\li720\lin720 }{\listlevel\levelnfc4\levelnfcn4\leveljc0\leveljcn0\levelfollow0\levelstartat1\levelspace0\levelindent0{\leveltext\'02\'01.;}{\levelnumbers\'01;}\rtlch\fcs1 \af0 \ltrch\fcs0 \hres0\chhres0 \fi-360\li1440\lin1440 }{\listlevel
+\levelnfc2\levelnfcn2\leveljc2\leveljcn2\levelfollow0\levelstartat1\levelspace0\levelindent0{\leveltext\'02\'02.;}{\levelnumbers\'01;}\rtlch\fcs1 \af0 \ltrch\fcs0 \hres0\chhres0 \fi-180\li2160\lin2160 }{\listlevel\levelnfc3\levelnfcn3\leveljc0\leveljcn0
+\levelfollow0\levelstartat1\levelspace360\levelindent0{\leveltext\'02\'03.;}{\levelnumbers\'01;}\rtlch\fcs1 \af0 \ltrch\fcs0 \hres0\chhres0 \fi-360\li2880\lin2880 }{\listlevel\levelnfc4\levelnfcn4\leveljc0\leveljcn0\levelfollow0\levelstartat1\levelspace0
+\levelindent0{\leveltext\'02\'04.;}{\levelnumbers\'01;}\rtlch\fcs1 \af0 \ltrch\fcs0 \hres0\chhres0 \fi-360\li3600\lin3600 }{\listlevel\levelnfc2\levelnfcn2\leveljc2\leveljcn2\levelfollow0\levelstartat1\levelspace0\levelindent0{\leveltext
+\'02\'05.;}{\levelnumbers\'01;}\rtlch\fcs1 \af0 \ltrch\fcs0 \hres0\chhres0 \fi-180\li4320\lin4320 }{\listlevel\levelnfc0\levelnfcn0\leveljc0\leveljcn0\levelfollow0\levelstartat1\levelspace0\levelindent0{\leveltext\'02\'06.;}{\levelnumbers\'01;}
+\rtlch\fcs1 \af0 \ltrch\fcs0 \hres0\chhres0 \fi-360\li5040\lin5040 }{\listlevel\levelnfc4\levelnfcn4\leveljc0\leveljcn0\levelfollow0\levelstartat1\levelspace0\levelindent0{\leveltext\'02\'07.;}{\levelnumbers\'01;}\rtlch\fcs1 \af0 \ltrch\fcs0 
+\hres0\chhres0 \fi-360\li5760\lin5760 }{\listlevel\levelnfc2\levelnfcn2\leveljc2\leveljcn2\levelfollow0\levelstartat1\levelspace0\levelindent0{\leveltext\'02\'08.;}{\levelnumbers\'01;}\rtlch\fcs1 \af0 \ltrch\fcs0 \hres0\chhres0 \fi-180\li6480\lin6480 }
+{\listname ;}\listid1762801537}}{\*\listoverridetable{\listoverride\listid1517575639\listoverridecount0\ls1}{\listoverride\listid161162663\listoverridecount0\ls2}{\listoverride\listid581336416\listoverridecount0\ls3}{\listoverride\listid1082678316
+\listoverridecount0\ls4}{\listoverride\listid1762801537\listoverridecount0\ls5}{\listoverride\listid621182402\listoverridecount0\ls6}{\listoverride\listid592708402\listoverridecount0\ls7}{\listoverride\listid180975272\listoverridecount0\ls8}
+{\listoverride\listid1306352145\listoverridecount0\levelstartat7\ls9}{\listoverride\listid982349901\listoverridecount0\ls10}}{\*\rsidtbl \rsid329053\rsid3617154\rsid3749795\rsid9258424}{\mmathPr\mmathFont34\mbrkBin0\mbrkBinSub0\msmallFrac0\mdispDef1\mlMargin0\mrMargin0
+\mdefJc1\mwrapIndent1440\mintLim0\mnaryLim1}{\info{\title Text before list}{\author Cynthia Johnson}{\operator John MacFarlane}{\creatim\yr2003\mo10\dy13\hr19\min55}{\revtim\yr2021\mo8\dy9\hr10\min28}{\version4}{\edmins6}{\nofpages1}{\nofwords15}
+{\nofchars87}{\nofcharsws101}{\vern4617}}{\*\xmlnstbl {\xmlns1 http://schemas.microsoft.com/office/word/2003/wordml}}\paperw12240\paperh15840\margl1440\margr1440\margt1440\margb1440\gutter0\ltrsect 
+\widowctrl\ftnbj\aenddoc\trackmoves0\trackformatting1\donotembedsysfont0\relyonvml0\donotembedlingdata1\grfdocevents0\validatexml0\showplaceholdtext0\ignoremixedcontent0\saveinvalidxml0\showxmlerrors0\noxlattoyen
+\expshrtn\noultrlspc\dntblnsbdb\nospaceforul\formshade\horzdoc\dghspace180\dgvspace180\dghorigin1701\dgvorigin1984\dghshow0\dgvshow0
+\jexpand\viewkind1\viewscale154\pgbrdrhead\pgbrdrfoot\splytwnine\ftnlytwnine\htmautsp\nolnhtadjtbl\useltbaln\alntblind\lytcalctblwd\lyttblrtgr\lnbrkrule\rsidroot3749795 \fet0{\*\wgrffmtfilter 2450}\ilfomacatclnup0\ltrpar \sectd \ltrsect
+\linex0\endnhere\sectdefaultcl\sftnbj {\*\pnseclvl1\pnucrm\pnstart1\pnindent720\pnhang {\pntxta .}}{\*\pnseclvl2\pnucltr\pnstart1\pnindent720\pnhang {\pntxta .}}{\*\pnseclvl3\pndec\pnstart1\pnindent720\pnhang {\pntxta .}}{\*\pnseclvl4
+\pnlcltr\pnstart1\pnindent720\pnhang {\pntxta )}}{\*\pnseclvl5\pndec\pnstart1\pnindent720\pnhang {\pntxtb (}{\pntxta )}}{\*\pnseclvl6\pnlcltr\pnstart1\pnindent720\pnhang {\pntxtb (}{\pntxta )}}{\*\pnseclvl7\pnlcrm\pnstart1\pnindent720\pnhang {\pntxtb (}
+{\pntxta )}}{\*\pnseclvl8\pnlcltr\pnstart1\pnindent720\pnhang {\pntxtb (}{\pntxta )}}{\*\pnseclvl9\pnlcrm\pnstart1\pnindent720\pnhang {\pntxtb (}{\pntxta )}}{\listtext\pard\plain\ltrpar \rtlch\fcs1 \af0 \ltrch\fcs0 \f45\insrsid9258424 
+\hich\af45\dbch\af31505\loch\f45 1.\tab}\pard\plain \ltrpar\ql \fi-360\li720\ri0\widctlpar\wrapdefault\aspalpha\aspnum\faauto\ls3\adjustright\rin0\lin720\itap0\pararsid9258424 \rtlch\fcs1 \af45\afs24\alang1025 \ltrch\fcs0 
+\fs24\lang1033\langfe1033\loch\af45\hich\af45\dbch\af31505\cgrid\langnp1033\langfenp1033 {\rtlch\fcs1 \af45 \ltrch\fcs0 \insrsid9258424 \hich\af45\dbch\af31505\loch\f45 One}{\rtlch\fcs1 \af45 \ltrch\fcs0 \insrsid329053 
+\par {\listtext\pard\plain\ltrpar \rtlch\fcs1 \af0 \ltrch\fcs0 \f45\insrsid9258424 \hich\af45\dbch\af31505\loch\f45 2.\tab}}{\rtlch\fcs1 \af45 \ltrch\fcs0 \insrsid9258424 \hich\af45\dbch\af31505\loch\f45 Two
+\par {\listtext\pard\plain\ltrpar \rtlch\fcs1 \af0 \ltrch\fcs0 \f45\insrsid9258424 \hich\af45\dbch\af31505\loch\f45 a.\tab}}\pard \ltrpar
+\ql \fi-360\li1440\ri0\widctlpar\wrapdefault\aspalpha\aspnum\faauto\ls3\ilvl1\adjustright\rin0\lin1440\itap0\pararsid9258424 {\rtlch\fcs1 \af45 \ltrch\fcs0 \insrsid9258424 \hich\af45\dbch\af31505\loch\f45 Three
+\par {\listtext\pard\plain\ltrpar \rtlch\fcs1 \af0 \ltrch\fcs0 \f45\insrsid9258424 \hich\af45\dbch\af31505\loch\f45 b.\tab}\hich\af45\dbch\af31505\loch\f45 Four
+\par {\listtext\pard\plain\ltrpar \rtlch\fcs1 \af0 \ltrch\fcs0 \f45\insrsid9258424 \hich\af45\dbch\af31505\loch\f45 i.\tab}}\pard \ltrpar
+\ql \fi-180\li2160\ri0\widctlpar\wrapdefault\aspalpha\aspnum\faauto\ls3\ilvl2\adjustright\rin0\lin2160\itap0\pararsid9258424 {\rtlch\fcs1 \af45 \ltrch\fcs0 \insrsid9258424 \hich\af45\dbch\af31505\loch\f45 Five
+\par {\listtext\pard\plain\ltrpar \rtlch\fcs1 \af0 \ltrch\fcs0 \f45\insrsid9258424 \hich\af45\dbch\af31505\loch\f45 ii.\tab}\hich\af45\dbch\af31505\loch\f45 Six
+\par {\listtext\pard\plain\ltrpar \rtlch\fcs1 \af0 \ltrch\fcs0 \f45\insrsid9258424 \hich\af45\dbch\af31505\loch\f45 A.\tab}}\pard \ltrpar
+\ql \fi-360\li2880\ri0\widctlpar\wrapdefault\aspalpha\aspnum\faauto\ls3\ilvl3\adjustright\rin0\lin2880\itap0\pararsid9258424 {\rtlch\fcs1 \af45 \ltrch\fcs0 \insrsid9258424 \hich\af45\dbch\af31505\loch\f45 Seven
+\par {\listtext\pard\plain\ltrpar \rtlch\fcs1 \af0 \ltrch\fcs0 \f45\insrsid9258424 \hich\af45\dbch\af31505\loch\f45 B.\tab}\hich\af45\dbch\af31505\loch\f45 Eight
+\par {\listtext\pard\plain\ltrpar \rtlch\fcs1 \af0 \ltrch\fcs0 \f45\insrsid9258424 \hich\af45\dbch\af31505\loch\f45 I.\tab}}\pard \ltrpar
+\ql \fi-180\li3420\ri0\widctlpar\wrapdefault\aspalpha\aspnum\faauto\ls3\ilvl4\adjustright\rin0\lin3420\itap0\pararsid9258424 {\rtlch\fcs1 \af45 \ltrch\fcs0 \insrsid9258424 \hich\af45\dbch\af31505\loch\f45 Nine
+\par {\listtext\pard\plain\ltrpar \rtlch\fcs1 \af0 \ltrch\fcs0 \f45\insrsid9258424 \hich\af45\dbch\af31505\loch\f45 II.\tab}\hich\af45\dbch\af31505\loch\f45 Ten
+\par {\listtext\pard\plain\ltrpar \rtlch\fcs1 \af45 \ltrch\fcs0 \f2\insrsid9258424 \hich\af2\dbch\af31505\loch\f2 o\tab}}\pard \ltrpar\ql \fi-360\li4500\ri0\widctlpar\wrapdefault\aspalpha\aspnum\faauto\ls3\ilvl5\adjustright\rin0\lin4500\itap0\pararsid9258424 {
+\rtlch\fcs1 \af45 \ltrch\fcs0 \insrsid9258424 \hich\af45\dbch\af31505\loch\f45 Eleven
+\par {\listtext\pard\plain\ltrpar \rtlch\fcs1 \af45 \ltrch\fcs0 \f2\insrsid9258424 \hich\af2\dbch\af31505\loch\f2 o\tab}\hich\af45\dbch\af31505\loch\f45 Twelve
+\par }\pard \ltrpar\ql \li0\ri0\widctlpar\wrapdefault\aspalpha\aspnum\faauto\adjustright\rin0\lin0\itap0\pararsid9258424 {\rtlch\fcs1 \af45 \ltrch\fcs0 \insrsid9258424 \hich\af45\dbch\af31505\loch\f45 Out of list!
+\par }\pard \ltrpar\ql \li0\ri0\widctlpar\wrapdefault\aspalpha\aspnum\faauto\adjustright\rin0\lin0\itap0\pararsid3617154 {\rtlch\fcs1 \af45 \ltrch\fcs0 \insrsid3617154 \hich\af45\dbch\af31505\loch\f45 Start with
+\par {\listtext\pard\plain\ltrpar \rtlch\fcs1 \af45 \ltrch\fcs0 \f45\insrsid3617154 \hich\af45\dbch\af31505\loch\f45 7.\tab}}\pard \ltrpar\ql \fi-360\li720\ri0\widctlpar\wrapdefault\aspalpha\aspnum\faauto\ls9\adjustright\rin0\lin720\itap0\pararsid3617154 {
+\rtlch\fcs1 \af45 \ltrch\fcs0 \insrsid3617154 \hich\af45\dbch\af31505\loch\f45 Seven Start
+\par {\listtext\pard\plain\ltrpar \rtlch\fcs1 \af45 \ltrch\fcs0 \f45\insrsid3617154 \hich\af45\dbch\af31505\loch\f45 8.\tab}\hich\af45\dbch\af31505\loch\f45 Eight Continue
+\par }\pard \ltrpar\ql \li0\ri0\widctlpar\wrapdefault\aspalpha\aspnum\faauto\adjustright\rin0\lin0\itap0\pararsid3617154 {\rtlch\fcs1 \af45 \ltrch\fcs0 \insrsid3617154 
+\par }\pard \ltrpar\ql \li4140\ri0\widctlpar\wrapdefault\aspalpha\aspnum\faauto\adjustright\rin0\lin4140\itap0\pararsid9258424 {\rtlch\fcs1 \af45 \ltrch\fcs0 \insrsid9258424 
+\par }{\rtlch\fcs1 \af45 \ltrch\fcs0 \insrsid3617154 
+\par }{\*\themedata 504b030414000600080000002100e9de0fbfff0000001c020000130000005b436f6e74656e745f54797065735d2e786d6cac91cb4ec3301045f748fc83e52d4a
+9cb2400825e982c78ec7a27cc0c8992416c9d8b2a755fbf74cd25442a820166c2cd933f79e3be372bd1f07b5c3989ca74aaff2422b24eb1b475da5df374fd9ad
+5689811a183c61a50f98f4babebc2837878049899a52a57be670674cb23d8e90721f90a4d2fa3802cb35762680fd800ecd7551dc18eb899138e3c943d7e503b6
+b01d583deee5f99824e290b4ba3f364eac4a430883b3c092d4eca8f946c916422ecab927f52ea42b89a1cd59c254f919b0e85e6535d135a8de20f20b8c12c3b0
+0c895fcf6720192de6bf3b9e89ecdbd6596cbcdd8eb28e7c365ecc4ec1ff1460f53fe813d3cc7f5b7f020000ffff0300504b030414000600080000002100a5d6
+a7e7c0000000360100000b0000005f72656c732f2e72656c73848fcf6ac3300c87ef85bd83d17d51d2c31825762fa590432fa37d00e1287f68221bdb1bebdb4f
+c7060abb0884a4eff7a93dfeae8bf9e194e720169aaa06c3e2433fcb68e1763dbf7f82c985a4a725085b787086a37bdbb55fbc50d1a33ccd311ba548b6309512
+0f88d94fbc52ae4264d1c910d24a45db3462247fa791715fd71f989e19e0364cd3f51652d73760ae8fa8c9ffb3c330cc9e4fc17faf2ce545046e37944c69e462
+a1a82fe353bd90a865aad41ed0b5b8f9d6fd010000ffff0300504b0304140006000800000021006b799616830000008a0000001c0000007468656d652f746865
+6d652f7468656d654d616e616765722e786d6c0ccc4d0ac3201040e17da17790d93763bb284562b2cbaebbf600439c1a41c7a0d29fdbd7e5e38337cedf14d59b
+4b0d592c9c070d8a65cd2e88b7f07c2ca71ba8da481cc52c6ce1c715e6e97818c9b48d13df49c873517d23d59085adb5dd20d6b52bd521ef2cdd5eb9246a3d8b
+4757e8d3f729e245eb2b260a0238fd010000ffff0300504b030414000600080000002100b6f4679893070000c9200000160000007468656d652f7468656d652f
+7468656d65312e786d6cec59cd8b1bc915bf07f23f347d97f5d5ad8fc1f2a24fcfda33b6b164873dd648a5eef2547789aad28cc56208de532e81c026e49085bd
+ed21842cecc22eb9e48f31d8249b3f22afaa5bdd5552c99e191c3061463074977eefd5afde7bf5de53d5ddcf5e26d4bbc05c1096f6fcfa9d9aefe174ce16248d
+7afeb3d9a4d2f13d2151ba4094a5b8e76fb0f03fbbf7eb5fdd454732c609f6403e1547a8e7c752ae8eaa5531876124eeb0154ee1bb25e30992f0caa3ea82a34b
+d09bd06aa3566b55134452df4b51026a1f2f97648ebd9952e9dfdb2a1f53784da5500373caa74a35b6243476715e5708b11143cabd0b447b3eccb3609733fc52
+fa1e4542c2173dbfa6fffceabdbb5574940b517940d6909be8bf5c2e17589c37f49c3c3a2b260d823068f50bfd1a40e53e6edc1eb7c6ad429f06a0f91c569a71
+b175b61bc320c71aa0ecd1a17bd41e35eb16ded0dfdce3dc0fd5c7c26b50a63fd8c34f2643b0a285d7a00c1feee1c3417730b2f56b50866fede1dbb5fe28685b
+fa3528a6243ddf43d7c25673b85d6d0159327aec8477c360d26ee4ca4b144443115d6a8a254be5a1584bd00bc6270050408a24493db959e1259a43140f112567
+9c7827248a21f056286502866b8ddaa4d684ffea13e827ed5174849121ad780113b137a4f87862cec94af6fc07a0d537206f7ffef9cdeb1fdfbcfee9cd575fbd
+79fdf77c6eadca923b466964cafdf2dd1ffef3cd6fbd7ffff0ed2f5fff319b7a172f4cfcbbbffdeedd3ffef93ef5b0e2d2146ffff4fdbb1fbf7ffbe7dfffebaf
+5f3bb4f7393a33e1339260e13dc297de5396c0021dfcf119bf9ec42c46c494e8a791402952b338f48f656ca11f6d10450edc00db767cce21d5b880f7d72f2cc2
+d398af2571687c182716f094313a60dc6985876a2ec3ccb3751ab927e76b13f714a10bd7dc43945a5e1eaf579063894be530c616cd2714a5124538c5d253dfb1
+738c1dabfb8210cbaea764ce99604be97d41bc01224e93ccc899154da5d03149c02f1b1741f0b7659bd3e7de8051d7aa47f8c246c2de40d4417e86a965c6fb68
+2d51e252394309350d7e8264ec2239ddf0b9891b0b099e8e3065de78818570c93ce6b05ec3e90f21cdb8dd7e4a37898de4929cbb749e20c64ce4889d0f6394ac
+5cd829496313fbb938871045de13265df05366ef10f50e7e40e941773f27d872f787b3c133c8b026a53240d4376beef0e57dccacf89d6ee8126157aae9f3c44a
+b17d4e9cd131584756689f604cd1255a60ec3dfbdcc160c05696cd4bd20f62c82ac7d815580f901dabea3dc5027a25d5dcece7c91322ac909de2881de073bad9
+493c1b9426881fd2fc08bc6eda7c0ca52e7105c0633a3f37818f08f480102f4ea33c16a0c308ee835a9fc4c82a60ea5db8e375c32dff5d658fc1be7c61d1b8c2
+be04197c6d1948eca6cc7b6d3343d49aa00c9819822ec3956e41c4727f29a28aab165b3be596f6a62ddd00dd91d5f42424fd6007b4d3fb84ffbbde073a8cb77f
+f9c6b10f3e4ebfe3566c25ab6b763a8792c9f14e7f7308b7dbd50c195f904fbfa919a175fa04431dd9cf58b73dcd6d4fe3ffdff73487f6f36d2773a8dfb8ed64
+7ce8306e3b99fc70e5e3743265f3027d8d3af0c80e7af4b14f72f0d46749289dca0dc527421ffc08f83db398c0a092d3279eb838055cc5f0a8ca1c4c60e1228e
+b48cc799fc0d91f134462b381daafb4a492472d591f0564cc0a1911e76ea5678ba4e4ed9223becacd7d5c16656590592e5782d2cc6e1a04a66e856bb3cc02bd4
+6bb6913e68dd1250b2d721614c6693683a48b4b783ca48fa58178ce620a157f65158741d2c3a4afdd6557b2c805ae115f8c1edc1cff49e1f06200242701e07cd
+f942f92973f5d6bbda991fd3d3878c69450034d8db08283ddd555c0f2e4fad2e0bb52b78da2261849b4d425b46377822869fc17974aad1abd0b8aeafbba54b2d
+7aca147a3e08ad9246bbf33e1637f535c8ede6069a9a9982a6de65cf6f35430899395af5fc251c1ac363b282d811ea3717a211dcbccc25cf36fc4d32cb8a0b39
+4222ce0cae934e960d122231f728497abe5a7ee1069aea1ca2b9d51b90103e59725d482b9f1a3970baed64bc5ce2b934dd6e8c284b67af90e1b35ce1fc568bdf
+1cac24d91adc3d8d1797de195df3a708422c6cd795011744c0dd413db3e682c0655891c8caf8db294c79da356fa3740c65e388ae62945714339967709dca0b3a
+faadb081f196af190c6a98242f8467912ab0a651ad6a5a548d8cc3c1aafb6121653923699635d3ca2aaa6abab39835c3b60cecd8f26645de60b53531e434b3c2
+67a97b37e576b7b96ea74f28aa0418bcb09fa3ea5ea12018d4cac92c6a8af17e1a56393b1fb56bc776811fa07695226164fdd656ed8edd8a1ae19c0e066f54f9
+416e376a6168b9ed2bb5a5f5adb979b1cdce5e40f2184197bba6526857c2c92e47d0104d754f92a50dd8222f65be35e0c95b73d2f3bfac85fd60d80887955a27
+1c57826650ab74c27eb3d20fc3667d1cd66ba341e31514161927f530bbb19fc00506dde4f7f67a7cefee3ed9ded1dc99b3a4caf4dd7c5513d777f7f5c6e1bb7b
+8f40d2f9b2d598749bdd41abd26df627956034e854bac3d6a0326a0ddba3c9681876ba9357be77a1c141bf390c5ae34ea5551f0e2b41aba6e877ba9576d068f4
+8376bf330efaaff23606569ea58fdc16605ecdebde7f010000ffff0300504b0304140006000800000021000dd1909fb60000001b010000270000007468656d65
+2f7468656d652f5f72656c732f7468656d654d616e616765722e786d6c2e72656c73848f4d0ac2301484f78277086f6fd3ba109126dd88d0add40384e4350d36
+3f2451eced0dae2c082e8761be9969bb979dc9136332de3168aa1a083ae995719ac16db8ec8e4052164e89d93b64b060828e6f37ed1567914b284d262452282e
+3198720e274a939cd08a54f980ae38a38f56e422a3a641c8bbd048f7757da0f19b017cc524bd62107bd5001996509affb3fd381a89672f1f165dfe514173d985
+0528a2c6cce0239baa4c04ca5bbabac4df000000ffff0300504b01022d0014000600080000002100e9de0fbfff0000001c020000130000000000000000000000
+0000000000005b436f6e74656e745f54797065735d2e786d6c504b01022d0014000600080000002100a5d6a7e7c0000000360100000b00000000000000000000
+000000300100005f72656c732f2e72656c73504b01022d00140006000800000021006b799616830000008a0000001c0000000000000000000000000019020000
+7468656d652f7468656d652f7468656d654d616e616765722e786d6c504b01022d0014000600080000002100b6f4679893070000c92000001600000000000000
+000000000000d60200007468656d652f7468656d652f7468656d65312e786d6c504b01022d00140006000800000021000dd1909fb60000001b01000027000000
+000000000000000000009d0a00007468656d652f7468656d652f5f72656c732f7468656d654d616e616765722e786d6c2e72656c73504b050600000000050005005d010000980b00000000}
+{\*\colorschememapping 3c3f786d6c2076657273696f6e3d22312e302220656e636f64696e673d225554462d3822207374616e64616c6f6e653d22796573223f3e0d0a3c613a636c724d
+617020786d6c6e733a613d22687474703a2f2f736368656d61732e6f70656e786d6c666f726d6174732e6f72672f64726177696e676d6c2f323030362f6d6169
+6e22206267313d226c743122207478313d22646b3122206267323d226c743222207478323d22646b322220616363656e74313d22616363656e74312220616363
+656e74323d22616363656e74322220616363656e74333d22616363656e74332220616363656e74343d22616363656e74342220616363656e74353d22616363656e74352220616363656e74363d22616363656e74362220686c696e6b3d22686c696e6b2220666f6c486c696e6b3d22666f6c486c696e6b222f3e}
+{\*\latentstyles\lsdstimax376\lsdlockeddef0\lsdsemihiddendef0\lsdunhideuseddef0\lsdqformatdef0\lsdprioritydef99{\lsdlockedexcept \lsdqformat1 \lsdpriority0 \lsdlocked0 Normal;\lsdqformat1 \lsdpriority9 \lsdlocked0 heading 1;
+\lsdsemihidden1 \lsdunhideused1 \lsdqformat1 \lsdpriority9 \lsdlocked0 heading 2;\lsdsemihidden1 \lsdunhideused1 \lsdqformat1 \lsdpriority9 \lsdlocked0 heading 3;\lsdsemihidden1 \lsdunhideused1 \lsdqformat1 \lsdpriority9 \lsdlocked0 heading 4;
+\lsdsemihidden1 \lsdunhideused1 \lsdqformat1 \lsdpriority9 \lsdlocked0 heading 5;\lsdsemihidden1 \lsdunhideused1 \lsdqformat1 \lsdpriority9 \lsdlocked0 heading 6;\lsdsemihidden1 \lsdunhideused1 \lsdqformat1 \lsdpriority9 \lsdlocked0 heading 7;
+\lsdsemihidden1 \lsdunhideused1 \lsdqformat1 \lsdpriority9 \lsdlocked0 heading 8;\lsdsemihidden1 \lsdunhideused1 \lsdqformat1 \lsdpriority9 \lsdlocked0 heading 9;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 index 1;
+\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 index 2;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 index 3;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 index 4;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 index 5;
+\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 index 6;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 index 7;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 index 8;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 index 9;
+\lsdsemihidden1 \lsdunhideused1 \lsdpriority39 \lsdlocked0 toc 1;\lsdsemihidden1 \lsdunhideused1 \lsdpriority39 \lsdlocked0 toc 2;\lsdsemihidden1 \lsdunhideused1 \lsdpriority39 \lsdlocked0 toc 3;
+\lsdsemihidden1 \lsdunhideused1 \lsdpriority39 \lsdlocked0 toc 4;\lsdsemihidden1 \lsdunhideused1 \lsdpriority39 \lsdlocked0 toc 5;\lsdsemihidden1 \lsdunhideused1 \lsdpriority39 \lsdlocked0 toc 6;
+\lsdsemihidden1 \lsdunhideused1 \lsdpriority39 \lsdlocked0 toc 7;\lsdsemihidden1 \lsdunhideused1 \lsdpriority39 \lsdlocked0 toc 8;\lsdsemihidden1 \lsdunhideused1 \lsdpriority39 \lsdlocked0 toc 9;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Normal Indent;
+\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 footnote text;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 annotation text;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 header;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 footer;
+\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 index heading;\lsdsemihidden1 \lsdunhideused1 \lsdqformat1 \lsdpriority35 \lsdlocked0 caption;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 table of figures;
+\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 envelope address;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 envelope return;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 footnote reference;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 annotation reference;
+\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 line number;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 page number;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 endnote reference;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 endnote text;
+\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 table of authorities;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 macro;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 toa heading;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 List;
+\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 List Bullet;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 List Number;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 List 2;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 List 3;
+\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 List 4;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 List 5;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 List Bullet 2;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 List Bullet 3;
+\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 List Bullet 4;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 List Bullet 5;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 List Number 2;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 List Number 3;
+\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 List Number 4;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 List Number 5;\lsdqformat1 \lsdpriority10 \lsdlocked0 Title;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Closing;
+\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Signature;\lsdsemihidden1 \lsdlocked0 Default Paragraph Font;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Body Text;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Body Text Indent;
+\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 List Continue;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 List Continue 2;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 List Continue 3;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 List Continue 4;
+\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 List Continue 5;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Message Header;\lsdqformat1 \lsdpriority11 \lsdlocked0 Subtitle;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Salutation;
+\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Date;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Body Text First Indent;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Body Text First Indent 2;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Note Heading;
+\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Body Text 2;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Body Text 3;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Body Text Indent 2;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Body Text Indent 3;
+\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Block Text;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Hyperlink;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 FollowedHyperlink;\lsdqformat1 \lsdpriority22 \lsdlocked0 Strong;
+\lsdqformat1 \lsdpriority20 \lsdlocked0 Emphasis;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Document Map;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Plain Text;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 E-mail Signature;
+\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 HTML Top of Form;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 HTML Bottom of Form;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Normal (Web);\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 HTML Acronym;
+\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 HTML Address;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 HTML Cite;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 HTML Code;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 HTML Definition;
+\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 HTML Keyboard;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 HTML Preformatted;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 HTML Sample;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 HTML Typewriter;
+\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 HTML Variable;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 annotation subject;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 No List;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Outline List 1;
+\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Outline List 2;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Outline List 3;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Balloon Text;\lsdpriority39 \lsdlocked0 Table Grid;
+\lsdsemihidden1 \lsdlocked0 Placeholder Text;\lsdqformat1 \lsdpriority1 \lsdlocked0 No Spacing;\lsdpriority60 \lsdlocked0 Light Shading;\lsdpriority61 \lsdlocked0 Light List;\lsdpriority62 \lsdlocked0 Light Grid;
+\lsdpriority63 \lsdlocked0 Medium Shading 1;\lsdpriority64 \lsdlocked0 Medium Shading 2;\lsdpriority65 \lsdlocked0 Medium List 1;\lsdpriority66 \lsdlocked0 Medium List 2;\lsdpriority67 \lsdlocked0 Medium Grid 1;\lsdpriority68 \lsdlocked0 Medium Grid 2;
+\lsdpriority69 \lsdlocked0 Medium Grid 3;\lsdpriority70 \lsdlocked0 Dark List;\lsdpriority71 \lsdlocked0 Colorful Shading;\lsdpriority72 \lsdlocked0 Colorful List;\lsdpriority73 \lsdlocked0 Colorful Grid;\lsdpriority60 \lsdlocked0 Light Shading Accent 1;
+\lsdpriority61 \lsdlocked0 Light List Accent 1;\lsdpriority62 \lsdlocked0 Light Grid Accent 1;\lsdpriority63 \lsdlocked0 Medium Shading 1 Accent 1;\lsdpriority64 \lsdlocked0 Medium Shading 2 Accent 1;\lsdpriority65 \lsdlocked0 Medium List 1 Accent 1;
+\lsdsemihidden1 \lsdlocked0 Revision;\lsdqformat1 \lsdpriority34 \lsdlocked0 List Paragraph;\lsdqformat1 \lsdpriority29 \lsdlocked0 Quote;\lsdqformat1 \lsdpriority30 \lsdlocked0 Intense Quote;\lsdpriority66 \lsdlocked0 Medium List 2 Accent 1;
+\lsdpriority67 \lsdlocked0 Medium Grid 1 Accent 1;\lsdpriority68 \lsdlocked0 Medium Grid 2 Accent 1;\lsdpriority69 \lsdlocked0 Medium Grid 3 Accent 1;\lsdpriority70 \lsdlocked0 Dark List Accent 1;\lsdpriority71 \lsdlocked0 Colorful Shading Accent 1;
+\lsdpriority72 \lsdlocked0 Colorful List Accent 1;\lsdpriority73 \lsdlocked0 Colorful Grid Accent 1;\lsdpriority60 \lsdlocked0 Light Shading Accent 2;\lsdpriority61 \lsdlocked0 Light List Accent 2;\lsdpriority62 \lsdlocked0 Light Grid Accent 2;
+\lsdpriority63 \lsdlocked0 Medium Shading 1 Accent 2;\lsdpriority64 \lsdlocked0 Medium Shading 2 Accent 2;\lsdpriority65 \lsdlocked0 Medium List 1 Accent 2;\lsdpriority66 \lsdlocked0 Medium List 2 Accent 2;
+\lsdpriority67 \lsdlocked0 Medium Grid 1 Accent 2;\lsdpriority68 \lsdlocked0 Medium Grid 2 Accent 2;\lsdpriority69 \lsdlocked0 Medium Grid 3 Accent 2;\lsdpriority70 \lsdlocked0 Dark List Accent 2;\lsdpriority71 \lsdlocked0 Colorful Shading Accent 2;
+\lsdpriority72 \lsdlocked0 Colorful List Accent 2;\lsdpriority73 \lsdlocked0 Colorful Grid Accent 2;\lsdpriority60 \lsdlocked0 Light Shading Accent 3;\lsdpriority61 \lsdlocked0 Light List Accent 3;\lsdpriority62 \lsdlocked0 Light Grid Accent 3;
+\lsdpriority63 \lsdlocked0 Medium Shading 1 Accent 3;\lsdpriority64 \lsdlocked0 Medium Shading 2 Accent 3;\lsdpriority65 \lsdlocked0 Medium List 1 Accent 3;\lsdpriority66 \lsdlocked0 Medium List 2 Accent 3;
+\lsdpriority67 \lsdlocked0 Medium Grid 1 Accent 3;\lsdpriority68 \lsdlocked0 Medium Grid 2 Accent 3;\lsdpriority69 \lsdlocked0 Medium Grid 3 Accent 3;\lsdpriority70 \lsdlocked0 Dark List Accent 3;\lsdpriority71 \lsdlocked0 Colorful Shading Accent 3;
+\lsdpriority72 \lsdlocked0 Colorful List Accent 3;\lsdpriority73 \lsdlocked0 Colorful Grid Accent 3;\lsdpriority60 \lsdlocked0 Light Shading Accent 4;\lsdpriority61 \lsdlocked0 Light List Accent 4;\lsdpriority62 \lsdlocked0 Light Grid Accent 4;
+\lsdpriority63 \lsdlocked0 Medium Shading 1 Accent 4;\lsdpriority64 \lsdlocked0 Medium Shading 2 Accent 4;\lsdpriority65 \lsdlocked0 Medium List 1 Accent 4;\lsdpriority66 \lsdlocked0 Medium List 2 Accent 4;
+\lsdpriority67 \lsdlocked0 Medium Grid 1 Accent 4;\lsdpriority68 \lsdlocked0 Medium Grid 2 Accent 4;\lsdpriority69 \lsdlocked0 Medium Grid 3 Accent 4;\lsdpriority70 \lsdlocked0 Dark List Accent 4;\lsdpriority71 \lsdlocked0 Colorful Shading Accent 4;
+\lsdpriority72 \lsdlocked0 Colorful List Accent 4;\lsdpriority73 \lsdlocked0 Colorful Grid Accent 4;\lsdpriority60 \lsdlocked0 Light Shading Accent 5;\lsdpriority61 \lsdlocked0 Light List Accent 5;\lsdpriority62 \lsdlocked0 Light Grid Accent 5;
+\lsdpriority63 \lsdlocked0 Medium Shading 1 Accent 5;\lsdpriority64 \lsdlocked0 Medium Shading 2 Accent 5;\lsdpriority65 \lsdlocked0 Medium List 1 Accent 5;\lsdpriority66 \lsdlocked0 Medium List 2 Accent 5;
+\lsdpriority67 \lsdlocked0 Medium Grid 1 Accent 5;\lsdpriority68 \lsdlocked0 Medium Grid 2 Accent 5;\lsdpriority69 \lsdlocked0 Medium Grid 3 Accent 5;\lsdpriority70 \lsdlocked0 Dark List Accent 5;\lsdpriority71 \lsdlocked0 Colorful Shading Accent 5;
+\lsdpriority72 \lsdlocked0 Colorful List Accent 5;\lsdpriority73 \lsdlocked0 Colorful Grid Accent 5;\lsdpriority60 \lsdlocked0 Light Shading Accent 6;\lsdpriority61 \lsdlocked0 Light List Accent 6;\lsdpriority62 \lsdlocked0 Light Grid Accent 6;
+\lsdpriority63 \lsdlocked0 Medium Shading 1 Accent 6;\lsdpriority64 \lsdlocked0 Medium Shading 2 Accent 6;\lsdpriority65 \lsdlocked0 Medium List 1 Accent 6;\lsdpriority66 \lsdlocked0 Medium List 2 Accent 6;
+\lsdpriority67 \lsdlocked0 Medium Grid 1 Accent 6;\lsdpriority68 \lsdlocked0 Medium Grid 2 Accent 6;\lsdpriority69 \lsdlocked0 Medium Grid 3 Accent 6;\lsdpriority70 \lsdlocked0 Dark List Accent 6;\lsdpriority71 \lsdlocked0 Colorful Shading Accent 6;
+\lsdpriority72 \lsdlocked0 Colorful List Accent 6;\lsdpriority73 \lsdlocked0 Colorful Grid Accent 6;\lsdqformat1 \lsdpriority19 \lsdlocked0 Subtle Emphasis;\lsdqformat1 \lsdpriority21 \lsdlocked0 Intense Emphasis;
+\lsdqformat1 \lsdpriority31 \lsdlocked0 Subtle Reference;\lsdqformat1 \lsdpriority32 \lsdlocked0 Intense Reference;\lsdqformat1 \lsdpriority33 \lsdlocked0 Book Title;\lsdsemihidden1 \lsdunhideused1 \lsdpriority37 \lsdlocked0 Bibliography;
+\lsdsemihidden1 \lsdunhideused1 \lsdqformat1 \lsdpriority39 \lsdlocked0 TOC Heading;\lsdpriority41 \lsdlocked0 Plain Table 1;\lsdpriority42 \lsdlocked0 Plain Table 2;\lsdpriority43 \lsdlocked0 Plain Table 3;\lsdpriority44 \lsdlocked0 Plain Table 4;
+\lsdpriority45 \lsdlocked0 Plain Table 5;\lsdpriority40 \lsdlocked0 Grid Table Light;\lsdpriority46 \lsdlocked0 Grid Table 1 Light;\lsdpriority47 \lsdlocked0 Grid Table 2;\lsdpriority48 \lsdlocked0 Grid Table 3;\lsdpriority49 \lsdlocked0 Grid Table 4;
+\lsdpriority50 \lsdlocked0 Grid Table 5 Dark;\lsdpriority51 \lsdlocked0 Grid Table 6 Colorful;\lsdpriority52 \lsdlocked0 Grid Table 7 Colorful;\lsdpriority46 \lsdlocked0 Grid Table 1 Light Accent 1;\lsdpriority47 \lsdlocked0 Grid Table 2 Accent 1;
+\lsdpriority48 \lsdlocked0 Grid Table 3 Accent 1;\lsdpriority49 \lsdlocked0 Grid Table 4 Accent 1;\lsdpriority50 \lsdlocked0 Grid Table 5 Dark Accent 1;\lsdpriority51 \lsdlocked0 Grid Table 6 Colorful Accent 1;
+\lsdpriority52 \lsdlocked0 Grid Table 7 Colorful Accent 1;\lsdpriority46 \lsdlocked0 Grid Table 1 Light Accent 2;\lsdpriority47 \lsdlocked0 Grid Table 2 Accent 2;\lsdpriority48 \lsdlocked0 Grid Table 3 Accent 2;
+\lsdpriority49 \lsdlocked0 Grid Table 4 Accent 2;\lsdpriority50 \lsdlocked0 Grid Table 5 Dark Accent 2;\lsdpriority51 \lsdlocked0 Grid Table 6 Colorful Accent 2;\lsdpriority52 \lsdlocked0 Grid Table 7 Colorful Accent 2;
+\lsdpriority46 \lsdlocked0 Grid Table 1 Light Accent 3;\lsdpriority47 \lsdlocked0 Grid Table 2 Accent 3;\lsdpriority48 \lsdlocked0 Grid Table 3 Accent 3;\lsdpriority49 \lsdlocked0 Grid Table 4 Accent 3;
+\lsdpriority50 \lsdlocked0 Grid Table 5 Dark Accent 3;\lsdpriority51 \lsdlocked0 Grid Table 6 Colorful Accent 3;\lsdpriority52 \lsdlocked0 Grid Table 7 Colorful Accent 3;\lsdpriority46 \lsdlocked0 Grid Table 1 Light Accent 4;
+\lsdpriority47 \lsdlocked0 Grid Table 2 Accent 4;\lsdpriority48 \lsdlocked0 Grid Table 3 Accent 4;\lsdpriority49 \lsdlocked0 Grid Table 4 Accent 4;\lsdpriority50 \lsdlocked0 Grid Table 5 Dark Accent 4;
+\lsdpriority51 \lsdlocked0 Grid Table 6 Colorful Accent 4;\lsdpriority52 \lsdlocked0 Grid Table 7 Colorful Accent 4;\lsdpriority46 \lsdlocked0 Grid Table 1 Light Accent 5;\lsdpriority47 \lsdlocked0 Grid Table 2 Accent 5;
+\lsdpriority48 \lsdlocked0 Grid Table 3 Accent 5;\lsdpriority49 \lsdlocked0 Grid Table 4 Accent 5;\lsdpriority50 \lsdlocked0 Grid Table 5 Dark Accent 5;\lsdpriority51 \lsdlocked0 Grid Table 6 Colorful Accent 5;
+\lsdpriority52 \lsdlocked0 Grid Table 7 Colorful Accent 5;\lsdpriority46 \lsdlocked0 Grid Table 1 Light Accent 6;\lsdpriority47 \lsdlocked0 Grid Table 2 Accent 6;\lsdpriority48 \lsdlocked0 Grid Table 3 Accent 6;
+\lsdpriority49 \lsdlocked0 Grid Table 4 Accent 6;\lsdpriority50 \lsdlocked0 Grid Table 5 Dark Accent 6;\lsdpriority51 \lsdlocked0 Grid Table 6 Colorful Accent 6;\lsdpriority52 \lsdlocked0 Grid Table 7 Colorful Accent 6;
+\lsdpriority46 \lsdlocked0 List Table 1 Light;\lsdpriority47 \lsdlocked0 List Table 2;\lsdpriority48 \lsdlocked0 List Table 3;\lsdpriority49 \lsdlocked0 List Table 4;\lsdpriority50 \lsdlocked0 List Table 5 Dark;
+\lsdpriority51 \lsdlocked0 List Table 6 Colorful;\lsdpriority52 \lsdlocked0 List Table 7 Colorful;\lsdpriority46 \lsdlocked0 List Table 1 Light Accent 1;\lsdpriority47 \lsdlocked0 List Table 2 Accent 1;\lsdpriority48 \lsdlocked0 List Table 3 Accent 1;
+\lsdpriority49 \lsdlocked0 List Table 4 Accent 1;\lsdpriority50 \lsdlocked0 List Table 5 Dark Accent 1;\lsdpriority51 \lsdlocked0 List Table 6 Colorful Accent 1;\lsdpriority52 \lsdlocked0 List Table 7 Colorful Accent 1;
+\lsdpriority46 \lsdlocked0 List Table 1 Light Accent 2;\lsdpriority47 \lsdlocked0 List Table 2 Accent 2;\lsdpriority48 \lsdlocked0 List Table 3 Accent 2;\lsdpriority49 \lsdlocked0 List Table 4 Accent 2;
+\lsdpriority50 \lsdlocked0 List Table 5 Dark Accent 2;\lsdpriority51 \lsdlocked0 List Table 6 Colorful Accent 2;\lsdpriority52 \lsdlocked0 List Table 7 Colorful Accent 2;\lsdpriority46 \lsdlocked0 List Table 1 Light Accent 3;
+\lsdpriority47 \lsdlocked0 List Table 2 Accent 3;\lsdpriority48 \lsdlocked0 List Table 3 Accent 3;\lsdpriority49 \lsdlocked0 List Table 4 Accent 3;\lsdpriority50 \lsdlocked0 List Table 5 Dark Accent 3;
+\lsdpriority51 \lsdlocked0 List Table 6 Colorful Accent 3;\lsdpriority52 \lsdlocked0 List Table 7 Colorful Accent 3;\lsdpriority46 \lsdlocked0 List Table 1 Light Accent 4;\lsdpriority47 \lsdlocked0 List Table 2 Accent 4;
+\lsdpriority48 \lsdlocked0 List Table 3 Accent 4;\lsdpriority49 \lsdlocked0 List Table 4 Accent 4;\lsdpriority50 \lsdlocked0 List Table 5 Dark Accent 4;\lsdpriority51 \lsdlocked0 List Table 6 Colorful Accent 4;
+\lsdpriority52 \lsdlocked0 List Table 7 Colorful Accent 4;\lsdpriority46 \lsdlocked0 List Table 1 Light Accent 5;\lsdpriority47 \lsdlocked0 List Table 2 Accent 5;\lsdpriority48 \lsdlocked0 List Table 3 Accent 5;
+\lsdpriority49 \lsdlocked0 List Table 4 Accent 5;\lsdpriority50 \lsdlocked0 List Table 5 Dark Accent 5;\lsdpriority51 \lsdlocked0 List Table 6 Colorful Accent 5;\lsdpriority52 \lsdlocked0 List Table 7 Colorful Accent 5;
+\lsdpriority46 \lsdlocked0 List Table 1 Light Accent 6;\lsdpriority47 \lsdlocked0 List Table 2 Accent 6;\lsdpriority48 \lsdlocked0 List Table 3 Accent 6;\lsdpriority49 \lsdlocked0 List Table 4 Accent 6;
+\lsdpriority50 \lsdlocked0 List Table 5 Dark Accent 6;\lsdpriority51 \lsdlocked0 List Table 6 Colorful Accent 6;\lsdpriority52 \lsdlocked0 List Table 7 Colorful Accent 6;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Mention;
+\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Smart Hyperlink;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Hashtag;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Unresolved Mention;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Smart Link;}}{\*\datastore }}
diff --git a/test/rtf/list_simple.native b/test/rtf/list_simple.native
new file mode 100644
--- /dev/null
+++ b/test/rtf/list_simple.native
@@ -0,0 +1,10 @@
+Pandoc
+  Meta { unMeta = fromList [] }
+  [ BulletList
+      [ [ Para [ Str "one" ] ]
+      , [ Para [ Str "two" ]
+        , BulletList [ [ Para [ Str "sub" ] ] ]
+        ]
+      ]
+  , BulletList [ [ Para [ Str "new" , Space , Str "list" ] ] ]
+  ]
diff --git a/test/rtf/list_simple.rtf b/test/rtf/list_simple.rtf
new file mode 100644
--- /dev/null
+++ b/test/rtf/list_simple.rtf
@@ -0,0 +1,17 @@
+{\rtf1\ansi\ansicpg1252\cocoartf2513
+\cocoatextscaling0\cocoaplatform0{\fonttbl\f0\fswiss\fcharset0 Helvetica;}
+{\colortbl;\red255\green255\blue255;}
+{\*\expandedcolortbl;;}
+{\*\listtable{\list\listtemplateid1\listhybrid{\listlevel\levelnfc23\levelnfcn23\leveljc0\leveljcn0\levelfollow0\levelstartat1\levelspace360\levelindent0{\*\levelmarker \{disc\}}{\leveltext\leveltemplateid1\'01\uc0\u8226 ;}{\levelnumbers;}\fi-360\li720\lin720 }{\listlevel\levelnfc23\levelnfcn23\leveljc0\leveljcn0\levelfollow0\levelstartat1\levelspace360\levelindent0{\*\levelmarker \{hyphen\}}{\leveltext\leveltemplateid2\'01\uc0\u8259 ;}{\levelnumbers;}\fi-360\li1440\lin1440 }{\listname ;}\listid1}
+{\list\listtemplateid2\listhybrid{\listlevel\levelnfc23\levelnfcn23\leveljc0\leveljcn0\levelfollow0\levelstartat1\levelspace360\levelindent0{\*\levelmarker \{disc\}}{\leveltext\leveltemplateid101\'01\uc0\u8226 ;}{\levelnumbers;}\fi-360\li720\lin720 }{\listname ;}\listid2}}
+{\*\listoverridetable{\listoverride\listid1\listoverridecount0\ls1}{\listoverride\listid2\listoverridecount0\ls2}}
+\margl1440\margr1440\vieww11520\viewh8400\viewkind0
+\pard\tx220\tx720\tx1440\tx2160\tx2880\tx3600\tx4320\tx5040\tx5760\tx6480\tx7200\tx7920\tx8640\li720\fi-720\pardirnatural\partightenfactor0
+\ls1\ilvl0
+\f0\fs24 \cf0 {\listtext	\uc0\u8226 	}one\
+{\listtext	\uc0\u8226 	}two\
+\pard\tx940\tx1440\tx2160\tx2880\tx3600\tx4320\tx5040\tx5760\tx6480\tx7200\tx7920\tx8640\li1440\fi-1440\pardirnatural\partightenfactor0
+\ls1\ilvl1\cf0 {\listtext	\uc0\u8259 	}sub\
+\pard\tx220\tx720\tx1440\tx2160\tx2880\tx3600\tx4320\tx5040\tx5760\tx6480\tx7200\tx7920\tx8640\li720\fi-720\pardirnatural\partightenfactor0
+\ls2\ilvl0\cf0 {\listtext	\uc0\u8226 	}new list\
+}
diff --git a/test/rtf/table_error_codes.native b/test/rtf/table_error_codes.native
new file mode 100644
--- /dev/null
+++ b/test/rtf/table_error_codes.native
@@ -0,0 +1,422 @@
+Pandoc
+  Meta { unMeta = fromList [] }
+  [ Table
+      ( "" , [] , [] )
+      (Caption Nothing [])
+      [ ( AlignDefault , ColWidthDefault )
+      , ( AlignDefault , ColWidthDefault )
+      ]
+      (TableHead ( "" , [] , [] ) [])
+      [ TableBody
+          ( "" , [] , [] )
+          (RowHeadColumns 0)
+          []
+          [ Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para [ Str "Code" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para [ Str "Error" ] ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para [ Str "3" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para [ Str "PandocFailOnWarningError" ] ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para [ Str "4" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para [ Str "PandocAppError" ] ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para [ Str "5" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para [ Str "PandocTemplateError" ] ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para [ Str "6" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para [ Str "PandocOptionError" ] ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para [ Str "21" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para [ Str "PandocUnknownReaderError" ] ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para [ Str "22" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para [ Str "PandocUnknownWriterError" ] ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para [ Str "23" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para [ Str "PandocUnsupportedExtensionError" ] ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para [ Str "24" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para [ Str "PandocCiteprocError" ] ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para [ Str "31" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para [ Str "PandocEpubSubdirectoryError" ] ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para [ Str "43" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para [ Str "PandocPDFError" ] ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para [ Str "44" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para [ Str "PandocXMLError" ] ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para [ Str "47" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para [ Str "PandocPDFProgramNotFoundError" ] ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para [ Str "61" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para [ Str "PandocHttpError" ] ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para [ Str "62" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para [ Str "PandocShouldNeverHappenError" ] ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para [ Str "63" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para [ Str "PandocSomeError" ] ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para [ Str "64" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para [ Str "PandocParseError" ] ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para [ Str "65" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para [ Str "PandocParsecError" ] ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para [ Str "66" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para [ Str "PandocMakePDFError" ] ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para [ Str "67" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para [ Str "PandocSyntaxMapError" ] ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para [ Str "83" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para [ Str "PandocFilterError" ] ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para [ Str "91" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para [ Str "PandocMacroLoop" ] ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para [ Str "92" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para [ Str "PandocUTF8DecodingError" ] ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para [ Str "93" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para [ Str "PandocIpynbDecodingError" ] ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para [ Str "94" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para [ Str "PandocUnsupportedCharsetError" ] ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para [ Str "97" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para [ Str "PandocCouldNotFindDataFileError" ] ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para [ Str "99" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para [ Str "PandocResourceNotFound" ] ]
+              ]
+          ]
+      ]
+      (TableFoot ( "" , [] , [] ) [])
+  ]
diff --git a/test/rtf/table_error_codes.rtf b/test/rtf/table_error_codes.rtf
new file mode 100644
--- /dev/null
+++ b/test/rtf/table_error_codes.rtf
@@ -0,0 +1,300 @@
+{\rtf1\ansi
+{
+\trowd \trgaph120
+\clbrdrb\brdrs\cellx4320\clbrdrb\brdrs\cellx8640
+\trkeep\intbl
+{
+{{\pard\intbl \qr \f0 \sa0 \li0 \fi0 Code\par}
+\cell}
+{{\pard\intbl \ql \f0 \sa0 \li0 \fi0 Error\par}
+\cell}
+}
+\intbl\row}
+{
+\trowd \trgaph120
+\cellx4320\cellx8640
+\trkeep\intbl
+{
+{{\pard\intbl \qr \f0 \sa0 \li0 \fi0 3\par}
+\cell}
+{{\pard\intbl \ql \f0 \sa0 \li0 \fi0 PandocFailOnWarningError\par}
+\cell}
+}
+\intbl\row}
+{
+\trowd \trgaph120
+\cellx4320\cellx8640
+\trkeep\intbl
+{
+{{\pard\intbl \qr \f0 \sa0 \li0 \fi0 4\par}
+\cell}
+{{\pard\intbl \ql \f0 \sa0 \li0 \fi0 PandocAppError\par}
+\cell}
+}
+\intbl\row}
+{
+\trowd \trgaph120
+\cellx4320\cellx8640
+\trkeep\intbl
+{
+{{\pard\intbl \qr \f0 \sa0 \li0 \fi0 5\par}
+\cell}
+{{\pard\intbl \ql \f0 \sa0 \li0 \fi0 PandocTemplateError\par}
+\cell}
+}
+\intbl\row}
+{
+\trowd \trgaph120
+\cellx4320\cellx8640
+\trkeep\intbl
+{
+{{\pard\intbl \qr \f0 \sa0 \li0 \fi0 6\par}
+\cell}
+{{\pard\intbl \ql \f0 \sa0 \li0 \fi0 PandocOptionError\par}
+\cell}
+}
+\intbl\row}
+{
+\trowd \trgaph120
+\cellx4320\cellx8640
+\trkeep\intbl
+{
+{{\pard\intbl \qr \f0 \sa0 \li0 \fi0 21\par}
+\cell}
+{{\pard\intbl \ql \f0 \sa0 \li0 \fi0 PandocUnknownReaderError\par}
+\cell}
+}
+\intbl\row}
+{
+\trowd \trgaph120
+\cellx4320\cellx8640
+\trkeep\intbl
+{
+{{\pard\intbl \qr \f0 \sa0 \li0 \fi0 22\par}
+\cell}
+{{\pard\intbl \ql \f0 \sa0 \li0 \fi0 PandocUnknownWriterError\par}
+\cell}
+}
+\intbl\row}
+{
+\trowd \trgaph120
+\cellx4320\cellx8640
+\trkeep\intbl
+{
+{{\pard\intbl \qr \f0 \sa0 \li0 \fi0 23\par}
+\cell}
+{{\pard\intbl \ql \f0 \sa0 \li0 \fi0 PandocUnsupportedExtensionError\par}
+\cell}
+}
+\intbl\row}
+{
+\trowd \trgaph120
+\cellx4320\cellx8640
+\trkeep\intbl
+{
+{{\pard\intbl \qr \f0 \sa0 \li0 \fi0 24\par}
+\cell}
+{{\pard\intbl \ql \f0 \sa0 \li0 \fi0 PandocCiteprocError\par}
+\cell}
+}
+\intbl\row}
+{
+\trowd \trgaph120
+\cellx4320\cellx8640
+\trkeep\intbl
+{
+{{\pard\intbl \qr \f0 \sa0 \li0 \fi0 31\par}
+\cell}
+{{\pard\intbl \ql \f0 \sa0 \li0 \fi0 PandocEpubSubdirectoryError\par}
+\cell}
+}
+\intbl\row}
+{
+\trowd \trgaph120
+\cellx4320\cellx8640
+\trkeep\intbl
+{
+{{\pard\intbl \qr \f0 \sa0 \li0 \fi0 43\par}
+\cell}
+{{\pard\intbl \ql \f0 \sa0 \li0 \fi0 PandocPDFError\par}
+\cell}
+}
+\intbl\row}
+{
+\trowd \trgaph120
+\cellx4320\cellx8640
+\trkeep\intbl
+{
+{{\pard\intbl \qr \f0 \sa0 \li0 \fi0 44\par}
+\cell}
+{{\pard\intbl \ql \f0 \sa0 \li0 \fi0 PandocXMLError\par}
+\cell}
+}
+\intbl\row}
+{
+\trowd \trgaph120
+\cellx4320\cellx8640
+\trkeep\intbl
+{
+{{\pard\intbl \qr \f0 \sa0 \li0 \fi0 47\par}
+\cell}
+{{\pard\intbl \ql \f0 \sa0 \li0 \fi0 PandocPDFProgramNotFoundError\par}
+\cell}
+}
+\intbl\row}
+{
+\trowd \trgaph120
+\cellx4320\cellx8640
+\trkeep\intbl
+{
+{{\pard\intbl \qr \f0 \sa0 \li0 \fi0 61\par}
+\cell}
+{{\pard\intbl \ql \f0 \sa0 \li0 \fi0 PandocHttpError\par}
+\cell}
+}
+\intbl\row}
+{
+\trowd \trgaph120
+\cellx4320\cellx8640
+\trkeep\intbl
+{
+{{\pard\intbl \qr \f0 \sa0 \li0 \fi0 62\par}
+\cell}
+{{\pard\intbl \ql \f0 \sa0 \li0 \fi0 PandocShouldNeverHappenError\par}
+\cell}
+}
+\intbl\row}
+{
+\trowd \trgaph120
+\cellx4320\cellx8640
+\trkeep\intbl
+{
+{{\pard\intbl \qr \f0 \sa0 \li0 \fi0 63\par}
+\cell}
+{{\pard\intbl \ql \f0 \sa0 \li0 \fi0 PandocSomeError\par}
+\cell}
+}
+\intbl\row}
+{
+\trowd \trgaph120
+\cellx4320\cellx8640
+\trkeep\intbl
+{
+{{\pard\intbl \qr \f0 \sa0 \li0 \fi0 64\par}
+\cell}
+{{\pard\intbl \ql \f0 \sa0 \li0 \fi0 PandocParseError\par}
+\cell}
+}
+\intbl\row}
+{
+\trowd \trgaph120
+\cellx4320\cellx8640
+\trkeep\intbl
+{
+{{\pard\intbl \qr \f0 \sa0 \li0 \fi0 65\par}
+\cell}
+{{\pard\intbl \ql \f0 \sa0 \li0 \fi0 PandocParsecError\par}
+\cell}
+}
+\intbl\row}
+{
+\trowd \trgaph120
+\cellx4320\cellx8640
+\trkeep\intbl
+{
+{{\pard\intbl \qr \f0 \sa0 \li0 \fi0 66\par}
+\cell}
+{{\pard\intbl \ql \f0 \sa0 \li0 \fi0 PandocMakePDFError\par}
+\cell}
+}
+\intbl\row}
+{
+\trowd \trgaph120
+\cellx4320\cellx8640
+\trkeep\intbl
+{
+{{\pard\intbl \qr \f0 \sa0 \li0 \fi0 67\par}
+\cell}
+{{\pard\intbl \ql \f0 \sa0 \li0 \fi0 PandocSyntaxMapError\par}
+\cell}
+}
+\intbl\row}
+{
+\trowd \trgaph120
+\cellx4320\cellx8640
+\trkeep\intbl
+{
+{{\pard\intbl \qr \f0 \sa0 \li0 \fi0 83\par}
+\cell}
+{{\pard\intbl \ql \f0 \sa0 \li0 \fi0 PandocFilterError\par}
+\cell}
+}
+\intbl\row}
+{
+\trowd \trgaph120
+\cellx4320\cellx8640
+\trkeep\intbl
+{
+{{\pard\intbl \qr \f0 \sa0 \li0 \fi0 91\par}
+\cell}
+{{\pard\intbl \ql \f0 \sa0 \li0 \fi0 PandocMacroLoop\par}
+\cell}
+}
+\intbl\row}
+{
+\trowd \trgaph120
+\cellx4320\cellx8640
+\trkeep\intbl
+{
+{{\pard\intbl \qr \f0 \sa0 \li0 \fi0 92\par}
+\cell}
+{{\pard\intbl \ql \f0 \sa0 \li0 \fi0 PandocUTF8DecodingError\par}
+\cell}
+}
+\intbl\row}
+{
+\trowd \trgaph120
+\cellx4320\cellx8640
+\trkeep\intbl
+{
+{{\pard\intbl \qr \f0 \sa0 \li0 \fi0 93\par}
+\cell}
+{{\pard\intbl \ql \f0 \sa0 \li0 \fi0 PandocIpynbDecodingError\par}
+\cell}
+}
+\intbl\row}
+{
+\trowd \trgaph120
+\cellx4320\cellx8640
+\trkeep\intbl
+{
+{{\pard\intbl \qr \f0 \sa0 \li0 \fi0 94\par}
+\cell}
+{{\pard\intbl \ql \f0 \sa0 \li0 \fi0 PandocUnsupportedCharsetError\par}
+\cell}
+}
+\intbl\row}
+{
+\trowd \trgaph120
+\cellx4320\cellx8640
+\trkeep\intbl
+{
+{{\pard\intbl \qr \f0 \sa0 \li0 \fi0 97\par}
+\cell}
+{{\pard\intbl \ql \f0 \sa0 \li0 \fi0 PandocCouldNotFindDataFileError\par}
+\cell}
+}
+\intbl\row}
+{
+\trowd \trgaph120
+\cellx4320\cellx8640
+\trkeep\intbl
+{
+{{\pard\intbl \qr \f0 \sa0 \li0 \fi0 99\par}
+\cell}
+{{\pard\intbl \ql \f0 \sa0 \li0 \fi0 PandocResourceNotFound\par}
+\cell}
+}
+\intbl\row}
+{\pard \ql \f0 \sa180 \li0 \fi0 \par}
+}
diff --git a/test/rtf/table_simple.native b/test/rtf/table_simple.native
new file mode 100644
--- /dev/null
+++ b/test/rtf/table_simple.native
@@ -0,0 +1,73 @@
+Pandoc
+  Meta { unMeta = fromList [] }
+  [ Table
+      ( "" , [] , [] )
+      (Caption Nothing [])
+      [ ( AlignDefault , ColWidthDefault )
+      , ( AlignDefault , ColWidthDefault )
+      , ( AlignDefault , ColWidthDefault )
+      , ( AlignDefault , ColWidthDefault )
+      ]
+      (TableHead ( "" , [] , [] ) [])
+      [ TableBody
+          ( "" , [] , [] )
+          (RowHeadColumns 0)
+          []
+          [ Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para [ Str "A" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para [ Str "B" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para [ Str "C" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para [ Str "D" ] ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para [ Str "E" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para [ Str "F" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para [ Str "G" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Para [ Str "H" ] ]
+              ]
+          ]
+      ]
+      (TableFoot ( "" , [] , [] ) [])
+  ]
diff --git a/test/rtf/table_simple.rtf b/test/rtf/table_simple.rtf
new file mode 100644
--- /dev/null
+++ b/test/rtf/table_simple.rtf
@@ -0,0 +1,19 @@
+{\rtf1\ansi
+\par
+\trowd
+\cellx10836
+\pard \intbl A \cell
+\pard \intbl B \cell
+\pard \intbl C \cell
+\pard \intbl D \cell
+\row
+\trowd
+\cellx10836
+\pard \intbl E \cell
+\pard \intbl F \cell
+\pard \intbl G \cell
+\pard \intbl H \cell
+\row
+\pard
+}
+
diff --git a/test/rtf/unicode.native b/test/rtf/unicode.native
new file mode 100644
--- /dev/null
+++ b/test/rtf/unicode.native
@@ -0,0 +1,3 @@
+Pandoc
+  Meta { unMeta = fromList [] }
+  [ Para [ Str "\8220hi\8221\8216hi\8217\61623\945\228" ] ]
diff --git a/test/rtf/unicode.rtf b/test/rtf/unicode.rtf
new file mode 100644
--- /dev/null
+++ b/test/rtf/unicode.rtf
@@ -0,0 +1,9 @@
+{\rtf1\ansi
+\pard
+\'93hi\'94
+\u8216\'93hi\u8217\'94
+\u-3913?
+\u945a
+{\uc2\u228\'E8a}
+\par
+}
diff --git a/test/s5-basic.html b/test/s5-basic.html
--- a/test/s5-basic.html
+++ b/test/s5-basic.html
@@ -11,10 +11,27 @@
   <meta name="date" content="2006-07-15" />
   <title>My S5 Document</title>
   <style type="text/css">
-      code{white-space: pre-wrap;}
-      span.smallcaps{font-variant: small-caps;}
-      span.underline{text-decoration: underline;}
-      div.column{display: inline-block; vertical-align: top; width: 50%;}
+    /* Default styles provided by pandoc.
+    ** See https://pandoc.org/MANUAL.html#variables-for-html for config info.
+    */
+    span.smallcaps{font-variant: small-caps;}
+    div.columns{display: flex; gap: 1.5em;}
+    div.column{flex: auto;}
+    @media screen {
+    div.columns{gap: min(4vw, 1.5em);}
+    div.column{overflow-x: auto;}
+    }
+    div.hanging-indent{margin-left: 1.5em; text-indent: -1.5em;}
+    /* The extra [class] is a hack that increases specificity enough to
+       override a similar rule in reveal.js */
+    ul.task-list[class]{list-style: none;}
+    ul.task-list li input[type="checkbox"] {
+      font-size: inherit;
+      width: 0.8em;
+      margin: 0 0.8em 0.2em -1.6em;
+      vertical-align: middle;
+    }
+    .display.math{display: block; text-align: center; margin: 0.5rem auto;}
   </style>
   <!-- configuration parameters -->
   <meta name="defaultView" content="slideshow" />
@@ -53,7 +70,8 @@
 <div id="math" class="slide section level1">
 <h1>Math</h1>
 <ul>
-<li><span class="math inline">$\frac{d}{dx}f(x)=\lim_{h\to 0}\frac{f(x+h)-f(x)}{h}$</span></li>
+<li><span class="math inline">$\frac{d}{dx}f(x)=\lim_{h\to
+0}\frac{f(x+h)-f(x)}{h}$</span></li>
 </ul>
 </div>
 </div>
diff --git a/test/s5-fancy.html b/test/s5-fancy.html
--- a/test/s5-fancy.html
+++ b/test/s5-fancy.html
@@ -11,10 +11,26 @@
   <meta name="date" content="2006-07-15" />
   <title>My S5 Document</title>
   <style type="text/css">
-      code{white-space: pre-wrap;}
-      span.smallcaps{font-variant: small-caps;}
-      span.underline{text-decoration: underline;}
-      div.column{display: inline-block; vertical-align: top; width: 50%;}
+    /* Default styles provided by pandoc.
+    ** See https://pandoc.org/MANUAL.html#variables-for-html for config info.
+    */
+    span.smallcaps{font-variant: small-caps;}
+    div.columns{display: flex; gap: 1.5em;}
+    div.column{flex: auto;}
+    @media screen {
+    div.columns{gap: min(4vw, 1.5em);}
+    div.column{overflow-x: auto;}
+    }
+    div.hanging-indent{margin-left: 1.5em; text-indent: -1.5em;}
+    /* The extra [class] is a hack that increases specificity enough to
+       override a similar rule in reveal.js */
+    ul.task-list[class]{list-style: none;}
+    ul.task-list li input[type="checkbox"] {
+      font-size: inherit;
+      width: 0.8em;
+      margin: 0 0.8em 0.2em -1.6em;
+      vertical-align: middle;
+    }
   </style>
   <!-- configuration parameters -->
   <meta name="defaultView" content="slideshow" />
@@ -26,207 +42,9 @@
   <link rel="stylesheet" href="s5/default/opera.css" type="text/css" media="projection" id="operaFix" />
   <!-- S5 JS -->
   <script src="s5/default/slides.js" type="text/javascript"></script>
-  <script type="text/javascript">/*<![CDATA[*/
-  /*
-  LaTeXMathML.js from http://math.etsu.edu/LaTeXMathML/
-  Adapted by Jeff Knisely and Douglas Woodall from ASCIIMathML.js v. 1.4.7,
-  (c) 2005 Peter Jipsen http://www.chapman.edu/~jipsen.
-  Released under the GNU General Public License version 2 or later.
-  See the GNU General Public License (at http://www.gnu.org/copyleft/gpl.html)
-  for more details.
-  */
-  var checkForMathML=true;var notifyIfNoMathML=true;var alertIfNoMathML=false;var mathcolor="";var mathfontfamily="";var showasciiformulaonhover=true;var isIE=document.createElementNS==null;if(document.getElementById==null)
-  alert("This webpage requires a recent browser such as \nMozilla/Netscape 7+ or Internet Explorer 6+MathPlayer")
-  function AMcreateElementXHTML(t){if(isIE)return document.createElement(t);else return document.createElementNS("http://www.w3.org/1999/xhtml",t);}
-  function AMnoMathMLNote(){var nd=AMcreateElementXHTML("h3");nd.setAttribute("align","center")
-  nd.appendChild(AMcreateElementXHTML("p"));nd.appendChild(document.createTextNode("To view the "));var an=AMcreateElementXHTML("a");an.appendChild(document.createTextNode("LaTeXMathML"));an.setAttribute("href","http://www.maths.nott.ac.uk/personal/drw/lm.html");nd.appendChild(an);nd.appendChild(document.createTextNode(" notation use Internet Explorer 6+"));an=AMcreateElementXHTML("a");an.appendChild(document.createTextNode("MathPlayer"));an.setAttribute("href","http://www.dessci.com/en/products/mathplayer/download.htm");nd.appendChild(an);nd.appendChild(document.createTextNode(" or Netscape/Mozilla/Firefox"));nd.appendChild(AMcreateElementXHTML("p"));return nd;}
-  function AMisMathMLavailable(){if(navigator.appName.slice(0,8)=="Netscape")
-  if(navigator.appVersion.slice(0,1)>="5")return null;else return AMnoMathMLNote();else if(navigator.appName.slice(0,9)=="Microsoft")
-  try{var ActiveX=new ActiveXObject("MathPlayer.Factory.1");return null;}catch(e){return AMnoMathMLNote();}
-  else return AMnoMathMLNote();}
-  var AMcal=[0xEF35,0x212C,0xEF36,0xEF37,0x2130,0x2131,0xEF38,0x210B,0x2110,0xEF39,0xEF3A,0x2112,0x2133,0xEF3B,0xEF3C,0xEF3D,0xEF3E,0x211B,0xEF3F,0xEF40,0xEF41,0xEF42,0xEF43,0xEF44,0xEF45,0xEF46];var AMfrk=[0xEF5D,0xEF5E,0x212D,0xEF5F,0xEF60,0xEF61,0xEF62,0x210C,0x2111,0xEF63,0xEF64,0xEF65,0xEF66,0xEF67,0xEF68,0xEF69,0xEF6A,0x211C,0xEF6B,0xEF6C,0xEF6D,0xEF6E,0xEF6F,0xEF70,0xEF71,0x2128];var AMbbb=[0xEF8C,0xEF8D,0x2102,0xEF8E,0xEF8F,0xEF90,0xEF91,0x210D,0xEF92,0xEF93,0xEF94,0xEF95,0xEF96,0x2115,0xEF97,0x2119,0x211A,0x211D,0xEF98,0xEF99,0xEF9A,0xEF9B,0xEF9C,0xEF9D,0xEF9E,0x2124];var CONST=0,UNARY=1,BINARY=2,INFIX=3,LEFTBRACKET=4,RIGHTBRACKET=5,SPACE=6,UNDEROVER=7,DEFINITION=8,TEXT=9,BIG=10,LONG=11,STRETCHY=12,MATRIX=13;var AMsqrt={input:"\\sqrt",tag:"msqrt",output:"sqrt",ttype:UNARY},AMroot={input:"\\root",tag:"mroot",output:"root",ttype:BINARY},AMfrac={input:"\\frac",tag:"mfrac",output:"/",ttype:BINARY},AMover={input:"\\stackrel",tag:"mover",output:"stackrel",ttype:BINARY},AMatop={input:"\\atop",tag:"mfrac",output:"",ttype:INFIX},AMchoose={input:"\\choose",tag:"mfrac",output:"",ttype:INFIX},AMsub={input:"_",tag:"msub",output:"_",ttype:INFIX},AMsup={input:"^",tag:"msup",output:"^",ttype:INFIX},AMtext={input:"\\mathrm",tag:"mtext",output:"text",ttype:TEXT},AMmbox={input:"\\mbox",tag:"mtext",output:"mbox",ttype:TEXT};var AMsymbols=[{input:"\\alpha",tag:"mi",output:"\u03B1",ttype:CONST},{input:"\\beta",tag:"mi",output:"\u03B2",ttype:CONST},{input:"\\gamma",tag:"mi",output:"\u03B3",ttype:CONST},{input:"\\delta",tag:"mi",output:"\u03B4",ttype:CONST},{input:"\\epsilon",tag:"mi",output:"\u03B5",ttype:CONST},{input:"\\varepsilon",tag:"mi",output:"\u025B",ttype:CONST},{input:"\\zeta",tag:"mi",output:"\u03B6",ttype:CONST},{input:"\\eta",tag:"mi",output:"\u03B7",ttype:CONST},{input:"\\theta",tag:"mi",output:"\u03B8",ttype:CONST},{input:"\\vartheta",tag:"mi",output:"\u03D1",ttype:CONST},{input:"\\iota",tag:"mi",output:"\u03B9",ttype:CONST},{input:"\\kappa",tag:"mi",output:"\u03BA",ttype:CONST},{input:"\\lambda",tag:"mi",output:"\u03BB",ttype:CONST},{input:"\\mu",tag:"mi",output:"\u03BC",ttype:CONST},{input:"\\nu",tag:"mi",output:"\u03BD",ttype:CONST},{input:"\\xi",tag:"mi",output:"\u03BE",ttype:CONST},{input:"\\pi",tag:"mi",output:"\u03C0",ttype:CONST},{input:"\\varpi",tag:"mi",output:"\u03D6",ttype:CONST},{input:"\\rho",tag:"mi",output:"\u03C1",ttype:CONST},{input:"\\varrho",tag:"mi",output:"\u03F1",ttype:CONST},{input:"\\varsigma",tag:"mi",output:"\u03C2",ttype:CONST},{input:"\\sigma",tag:"mi",output:"\u03C3",ttype:CONST},{input:"\\tau",tag:"mi",output:"\u03C4",ttype:CONST},{input:"\\upsilon",tag:"mi",output:"\u03C5",ttype:CONST},{input:"\\phi",tag:"mi",output:"\u03C6",ttype:CONST},{input:"\\varphi",tag:"mi",output:"\u03D5",ttype:CONST},{input:"\\chi",tag:"mi",output:"\u03C7",ttype:CONST},{input:"\\psi",tag:"mi",output:"\u03C8",ttype:CONST},{input:"\\omega",tag:"mi",output:"\u03C9",ttype:CONST},{input:"\\Gamma",tag:"mo",output:"\u0393",ttype:CONST},{input:"\\Delta",tag:"mo",output:"\u0394",ttype:CONST},{input:"\\Theta",tag:"mo",output:"\u0398",ttype:CONST},{input:"\\Lambda",tag:"mo",output:"\u039B",ttype:CONST},{input:"\\Xi",tag:"mo",output:"\u039E",ttype:CONST},{input:"\\Pi",tag:"mo",output:"\u03A0",ttype:CONST},{input:"\\Sigma",tag:"mo",output:"\u03A3",ttype:CONST},{input:"\\Upsilon",tag:"mo",output:"\u03A5",ttype:CONST},{input:"\\Phi",tag:"mo",output:"\u03A6",ttype:CONST},{input:"\\Psi",tag:"mo",output:"\u03A8",ttype:CONST},{input:"\\Omega",tag:"mo",output:"\u03A9",ttype:CONST},{input:"\\frac12",tag:"mo",output:"\u00BD",ttype:CONST},{input:"\\frac14",tag:"mo",output:"\u00BC",ttype:CONST},{input:"\\frac34",tag:"mo",output:"\u00BE",ttype:CONST},{input:"\\frac13",tag:"mo",output:"\u2153",ttype:CONST},{input:"\\frac23",tag:"mo",output:"\u2154",ttype:CONST},{input:"\\frac15",tag:"mo",output:"\u2155",ttype:CONST},{input:"\\frac25",tag:"mo",output:"\u2156",ttype:CONST},{input:"\\frac35",tag:"mo",output:"\u2157",ttype:CONST},{input:"\\frac45",tag:"mo",output:"\u2158",ttype:CONST},{input:"\\frac16",tag:"mo",output:"\u2159",ttype:CONST},{input:"\\frac56",tag:"mo",output:"\u215A",ttype:CONST},{input:"\\frac18",tag:"mo",output:"\u215B",ttype:CONST},{input:"\\frac38",tag:"mo",output:"\u215C",ttype:CONST},{input:"\\frac58",tag:"mo",output:"\u215D",ttype:CONST},{input:"\\frac78",tag:"mo",output:"\u215E",ttype:CONST},{input:"\\pm",tag:"mo",output:"\u00B1",ttype:CONST},{input:"\\mp",tag:"mo",output:"\u2213",ttype:CONST},{input:"\\triangleleft",tag:"mo",output:"\u22B2",ttype:CONST},{input:"\\triangleright",tag:"mo",output:"\u22B3",ttype:CONST},{input:"\\cdot",tag:"mo",output:"\u22C5",ttype:CONST},{input:"\\star",tag:"mo",output:"\u22C6",ttype:CONST},{input:"\\ast",tag:"mo",output:"\u002A",ttype:CONST},{input:"\\times",tag:"mo",output:"\u00D7",ttype:CONST},{input:"\\div",tag:"mo",output:"\u00F7",ttype:CONST},{input:"\\circ",tag:"mo",output:"\u2218",ttype:CONST},{input:"\\bullet",tag:"mo",output:"\u2022",ttype:CONST},{input:"\\oplus",tag:"mo",output:"\u2295",ttype:CONST},{input:"\\ominus",tag:"mo",output:"\u2296",ttype:CONST},{input:"\\otimes",tag:"mo",output:"\u2297",ttype:CONST},{input:"\\bigcirc",tag:"mo",output:"\u25CB",ttype:CONST},{input:"\\oslash",tag:"mo",output:"\u2298",ttype:CONST},{input:"\\odot",tag:"mo",output:"\u2299",ttype:CONST},{input:"\\land",tag:"mo",output:"\u2227",ttype:CONST},{input:"\\wedge",tag:"mo",output:"\u2227",ttype:CONST},{input:"\\lor",tag:"mo",output:"\u2228",ttype:CONST},{input:"\\vee",tag:"mo",output:"\u2228",ttype:CONST},{input:"\\cap",tag:"mo",output:"\u2229",ttype:CONST},{input:"\\cup",tag:"mo",output:"\u222A",ttype:CONST},{input:"\\sqcap",tag:"mo",output:"\u2293",ttype:CONST},{input:"\\sqcup",tag:"mo",output:"\u2294",ttype:CONST},{input:"\\uplus",tag:"mo",output:"\u228E",ttype:CONST},{input:"\\amalg",tag:"mo",output:"\u2210",ttype:CONST},{input:"\\bigtriangleup",tag:"mo",output:"\u25B3",ttype:CONST},{input:"\\bigtriangledown",tag:"mo",output:"\u25BD",ttype:CONST},{input:"\\dag",tag:"mo",output:"\u2020",ttype:CONST},{input:"\\dagger",tag:"mo",output:"\u2020",ttype:CONST},{input:"\\ddag",tag:"mo",output:"\u2021",ttype:CONST},{input:"\\ddagger",tag:"mo",output:"\u2021",ttype:CONST},{input:"\\lhd",tag:"mo",output:"\u22B2",ttype:CONST},{input:"\\rhd",tag:"mo",output:"\u22B3",ttype:CONST},{input:"\\unlhd",tag:"mo",output:"\u22B4",ttype:CONST},{input:"\\unrhd",tag:"mo",output:"\u22B5",ttype:CONST},{input:"\\sum",tag:"mo",output:"\u2211",ttype:UNDEROVER},{input:"\\prod",tag:"mo",output:"\u220F",ttype:UNDEROVER},{input:"\\bigcap",tag:"mo",output:"\u22C2",ttype:UNDEROVER},{input:"\\bigcup",tag:"mo",output:"\u22C3",ttype:UNDEROVER},{input:"\\bigwedge",tag:"mo",output:"\u22C0",ttype:UNDEROVER},{input:"\\bigvee",tag:"mo",output:"\u22C1",ttype:UNDEROVER},{input:"\\bigsqcap",tag:"mo",output:"\u2A05",ttype:UNDEROVER},{input:"\\bigsqcup",tag:"mo",output:"\u2A06",ttype:UNDEROVER},{input:"\\coprod",tag:"mo",output:"\u2210",ttype:UNDEROVER},{input:"\\bigoplus",tag:"mo",output:"\u2A01",ttype:UNDEROVER},{input:"\\bigotimes",tag:"mo",output:"\u2A02",ttype:UNDEROVER},{input:"\\bigodot",tag:"mo",output:"\u2A00",ttype:UNDEROVER},{input:"\\biguplus",tag:"mo",output:"\u2A04",ttype:UNDEROVER},{input:"\\int",tag:"mo",output:"\u222B",ttype:CONST},{input:"\\oint",tag:"mo",output:"\u222E",ttype:CONST},{input:":=",tag:"mo",output:":=",ttype:CONST},{input:"\\lt",tag:"mo",output:"<",ttype:CONST},{input:"\\gt",tag:"mo",output:">",ttype:CONST},{input:"\\ne",tag:"mo",output:"\u2260",ttype:CONST},{input:"\\neq",tag:"mo",output:"\u2260",ttype:CONST},{input:"\\le",tag:"mo",output:"\u2264",ttype:CONST},{input:"\\leq",tag:"mo",output:"\u2264",ttype:CONST},{input:"\\leqslant",tag:"mo",output:"\u2264",ttype:CONST},{input:"\\ge",tag:"mo",output:"\u2265",ttype:CONST},{input:"\\geq",tag:"mo",output:"\u2265",ttype:CONST},{input:"\\geqslant",tag:"mo",output:"\u2265",ttype:CONST},{input:"\\equiv",tag:"mo",output:"\u2261",ttype:CONST},{input:"\\ll",tag:"mo",output:"\u226A",ttype:CONST},{input:"\\gg",tag:"mo",output:"\u226B",ttype:CONST},{input:"\\doteq",tag:"mo",output:"\u2250",ttype:CONST},{input:"\\prec",tag:"mo",output:"\u227A",ttype:CONST},{input:"\\succ",tag:"mo",output:"\u227B",ttype:CONST},{input:"\\preceq",tag:"mo",output:"\u227C",ttype:CONST},{input:"\\succeq",tag:"mo",output:"\u227D",ttype:CONST},{input:"\\subset",tag:"mo",output:"\u2282",ttype:CONST},{input:"\\supset",tag:"mo",output:"\u2283",ttype:CONST},{input:"\\subseteq",tag:"mo",output:"\u2286",ttype:CONST},{input:"\\supseteq",tag:"mo",output:"\u2287",ttype:CONST},{input:"\\sqsubset",tag:"mo",output:"\u228F",ttype:CONST},{input:"\\sqsupset",tag:"mo",output:"\u2290",ttype:CONST},{input:"\\sqsubseteq",tag:"mo",output:"\u2291",ttype:CONST},{input:"\\sqsupseteq",tag:"mo",output:"\u2292",ttype:CONST},{input:"\\sim",tag:"mo",output:"\u223C",ttype:CONST},{input:"\\simeq",tag:"mo",output:"\u2243",ttype:CONST},{input:"\\approx",tag:"mo",output:"\u2248",ttype:CONST},{input:"\\cong",tag:"mo",output:"\u2245",ttype:CONST},{input:"\\Join",tag:"mo",output:"\u22C8",ttype:CONST},{input:"\\bowtie",tag:"mo",output:"\u22C8",ttype:CONST},{input:"\\in",tag:"mo",output:"\u2208",ttype:CONST},{input:"\\ni",tag:"mo",output:"\u220B",ttype:CONST},{input:"\\owns",tag:"mo",output:"\u220B",ttype:CONST},{input:"\\propto",tag:"mo",output:"\u221D",ttype:CONST},{input:"\\vdash",tag:"mo",output:"\u22A2",ttype:CONST},{input:"\\dashv",tag:"mo",output:"\u22A3",ttype:CONST},{input:"\\models",tag:"mo",output:"\u22A8",ttype:CONST},{input:"\\perp",tag:"mo",output:"\u22A5",ttype:CONST},{input:"\\smile",tag:"mo",output:"\u2323",ttype:CONST},{input:"\\frown",tag:"mo",output:"\u2322",ttype:CONST},{input:"\\asymp",tag:"mo",output:"\u224D",ttype:CONST},{input:"\\notin",tag:"mo",output:"\u2209",ttype:CONST},{input:"\\begin{eqnarray}",output:"X",ttype:MATRIX,invisible:true},{input:"\\begin{array}",output:"X",ttype:MATRIX,invisible:true},{input:"\\\\",output:"}&{",ttype:DEFINITION},{input:"\\end{eqnarray}",output:"}}",ttype:DEFINITION},{input:"\\end{array}",output:"}}",ttype:DEFINITION},{input:"\\big",tag:"mo",output:"X",atval:"1.2",ieval:"2.2",ttype:BIG},{input:"\\Big",tag:"mo",output:"X",atval:"1.6",ieval:"2.6",ttype:BIG},{input:"\\bigg",tag:"mo",output:"X",atval:"2.2",ieval:"3.2",ttype:BIG},{input:"\\Bigg",tag:"mo",output:"X",atval:"2.9",ieval:"3.9",ttype:BIG},{input:"\\left",tag:"mo",output:"X",ttype:LEFTBRACKET},{input:"\\right",tag:"mo",output:"X",ttype:RIGHTBRACKET},{input:"{",output:"{",ttype:LEFTBRACKET,invisible:true},{input:"}",output:"}",ttype:RIGHTBRACKET,invisible:true},{input:"(",tag:"mo",output:"(",atval:"1",ttype:STRETCHY},{input:"[",tag:"mo",output:"[",atval:"1",ttype:STRETCHY},{input:"\\lbrack",tag:"mo",output:"[",atval:"1",ttype:STRETCHY},{input:"\\{",tag:"mo",output:"{",atval:"1",ttype:STRETCHY},{input:"\\lbrace",tag:"mo",output:"{",atval:"1",ttype:STRETCHY},{input:"\\langle",tag:"mo",output:"\u2329",atval:"1",ttype:STRETCHY},{input:"\\lfloor",tag:"mo",output:"\u230A",atval:"1",ttype:STRETCHY},{input:"\\lceil",tag:"mo",output:"\u2308",atval:"1",ttype:STRETCHY},{input:")",tag:"mo",output:")",rtag:"mi",atval:"1",ttype:STRETCHY},{input:"]",tag:"mo",output:"]",rtag:"mi",atval:"1",ttype:STRETCHY},{input:"\\rbrack",tag:"mo",output:"]",rtag:"mi",atval:"1",ttype:STRETCHY},{input:"\\}",tag:"mo",output:"}",rtag:"mi",atval:"1",ttype:STRETCHY},{input:"\\rbrace",tag:"mo",output:"}",rtag:"mi",atval:"1",ttype:STRETCHY},{input:"\\rangle",tag:"mo",output:"\u232A",rtag:"mi",atval:"1",ttype:STRETCHY},{input:"\\rfloor",tag:"mo",output:"\u230B",rtag:"mi",atval:"1",ttype:STRETCHY},{input:"\\rceil",tag:"mo",output:"\u2309",rtag:"mi",atval:"1",ttype:STRETCHY},{input:"|",tag:"mo",output:"\u2223",atval:"1",ttype:STRETCHY},{input:"\\|",tag:"mo",output:"\u2225",atval:"1",ttype:STRETCHY},{input:"\\vert",tag:"mo",output:"\u2223",atval:"1",ttype:STRETCHY},{input:"\\Vert",tag:"mo",output:"\u2225",atval:"1",ttype:STRETCHY},{input:"\\mid",tag:"mo",output:"\u2223",atval:"1",ttype:STRETCHY},{input:"\\parallel",tag:"mo",output:"\u2225",atval:"1",ttype:STRETCHY},{input:"/",tag:"mo",output:"/",atval:"1.01",ttype:STRETCHY},{input:"\\backslash",tag:"mo",output:"\u2216",atval:"1",ttype:STRETCHY},{input:"\\setminus",tag:"mo",output:"\\",ttype:CONST},{input:"\\!",tag:"mspace",atname:"width",atval:"-0.167em",ttype:SPACE},{input:"\\,",tag:"mspace",atname:"width",atval:"0.167em",ttype:SPACE},{input:"\\>",tag:"mspace",atname:"width",atval:"0.222em",ttype:SPACE},{input:"\\:",tag:"mspace",atname:"width",atval:"0.222em",ttype:SPACE},{input:"\\;",tag:"mspace",atname:"width",atval:"0.278em",ttype:SPACE},{input:"~",tag:"mspace",atname:"width",atval:"0.333em",ttype:SPACE},{input:"\\quad",tag:"mspace",atname:"width",atval:"1em",ttype:SPACE},{input:"\\qquad",tag:"mspace",atname:"width",atval:"2em",ttype:SPACE},{input:"\\prime",tag:"mo",output:"\u2032",ttype:CONST},{input:"'",tag:"mo",output:"\u02B9",ttype:CONST},{input:"''",tag:"mo",output:"\u02BA",ttype:CONST},{input:"'''",tag:"mo",output:"\u2034",ttype:CONST},{input:"''''",tag:"mo",output:"\u2057",ttype:CONST},{input:"\\ldots",tag:"mo",output:"\u2026",ttype:CONST},{input:"\\cdots",tag:"mo",output:"\u22EF",ttype:CONST},{input:"\\vdots",tag:"mo",output:"\u22EE",ttype:CONST},{input:"\\ddots",tag:"mo",output:"\u22F1",ttype:CONST},{input:"\\forall",tag:"mo",output:"\u2200",ttype:CONST},{input:"\\exists",tag:"mo",output:"\u2203",ttype:CONST},{input:"\\Re",tag:"mo",output:"\u211C",ttype:CONST},{input:"\\Im",tag:"mo",output:"\u2111",ttype:CONST},{input:"\\aleph",tag:"mo",output:"\u2135",ttype:CONST},{input:"\\hbar",tag:"mo",output:"\u210F",ttype:CONST},{input:"\\ell",tag:"mo",output:"\u2113",ttype:CONST},{input:"\\wp",tag:"mo",output:"\u2118",ttype:CONST},{input:"\\emptyset",tag:"mo",output:"\u2205",ttype:CONST},{input:"\\infty",tag:"mo",output:"\u221E",ttype:CONST},{input:"\\surd",tag:"mo",output:"\\sqrt{}",ttype:DEFINITION},{input:"\\partial",tag:"mo",output:"\u2202",ttype:CONST},{input:"\\nabla",tag:"mo",output:"\u2207",ttype:CONST},{input:"\\triangle",tag:"mo",output:"\u25B3",ttype:CONST},{input:"\\therefore",tag:"mo",output:"\u2234",ttype:CONST},{input:"\\angle",tag:"mo",output:"\u2220",ttype:CONST},{input:"\\diamond",tag:"mo",output:"\u22C4",ttype:CONST},{input:"\\Diamond",tag:"mo",output:"\u25C7",ttype:CONST},{input:"\\neg",tag:"mo",output:"\u00AC",ttype:CONST},{input:"\\lnot",tag:"mo",output:"\u00AC",ttype:CONST},{input:"\\bot",tag:"mo",output:"\u22A5",ttype:CONST},{input:"\\top",tag:"mo",output:"\u22A4",ttype:CONST},{input:"\\square",tag:"mo",output:"\u25AB",ttype:CONST},{input:"\\Box",tag:"mo",output:"\u25A1",ttype:CONST},{input:"\\wr",tag:"mo",output:"\u2240",ttype:CONST},{input:"\\arccos",tag:"mi",output:"arccos",ttype:UNARY,func:true},{input:"\\arcsin",tag:"mi",output:"arcsin",ttype:UNARY,func:true},{input:"\\arctan",tag:"mi",output:"arctan",ttype:UNARY,func:true},{input:"\\arg",tag:"mi",output:"arg",ttype:UNARY,func:true},{input:"\\cos",tag:"mi",output:"cos",ttype:UNARY,func:true},{input:"\\cosh",tag:"mi",output:"cosh",ttype:UNARY,func:true},{input:"\\cot",tag:"mi",output:"cot",ttype:UNARY,func:true},{input:"\\coth",tag:"mi",output:"coth",ttype:UNARY,func:true},{input:"\\csc",tag:"mi",output:"csc",ttype:UNARY,func:true},{input:"\\deg",tag:"mi",output:"deg",ttype:UNARY,func:true},{input:"\\det",tag:"mi",output:"det",ttype:UNARY,func:true},{input:"\\dim",tag:"mi",output:"dim",ttype:UNARY,func:true},{input:"\\exp",tag:"mi",output:"exp",ttype:UNARY,func:true},{input:"\\gcd",tag:"mi",output:"gcd",ttype:UNARY,func:true},{input:"\\hom",tag:"mi",output:"hom",ttype:UNARY,func:true},{input:"\\inf",tag:"mo",output:"inf",ttype:UNDEROVER},{input:"\\ker",tag:"mi",output:"ker",ttype:UNARY,func:true},{input:"\\lg",tag:"mi",output:"lg",ttype:UNARY,func:true},{input:"\\lim",tag:"mo",output:"lim",ttype:UNDEROVER},{input:"\\liminf",tag:"mo",output:"liminf",ttype:UNDEROVER},{input:"\\limsup",tag:"mo",output:"limsup",ttype:UNDEROVER},{input:"\\ln",tag:"mi",output:"ln",ttype:UNARY,func:true},{input:"\\log",tag:"mi",output:"log",ttype:UNARY,func:true},{input:"\\max",tag:"mo",output:"max",ttype:UNDEROVER},{input:"\\min",tag:"mo",output:"min",ttype:UNDEROVER},{input:"\\Pr",tag:"mi",output:"Pr",ttype:UNARY,func:true},{input:"\\sec",tag:"mi",output:"sec",ttype:UNARY,func:true},{input:"\\sin",tag:"mi",output:"sin",ttype:UNARY,func:true},{input:"\\sinh",tag:"mi",output:"sinh",ttype:UNARY,func:true},{input:"\\sup",tag:"mo",output:"sup",ttype:UNDEROVER},{input:"\\tan",tag:"mi",output:"tan",ttype:UNARY,func:true},{input:"\\tanh",tag:"mi",output:"tanh",ttype:UNARY,func:true},{input:"\\gets",tag:"mo",output:"\u2190",ttype:CONST},{input:"\\leftarrow",tag:"mo",output:"\u2190",ttype:CONST},{input:"\\to",tag:"mo",output:"\u2192",ttype:CONST},{input:"\\rightarrow",tag:"mo",output:"\u2192",ttype:CONST},{input:"\\leftrightarrow",tag:"mo",output:"\u2194",ttype:CONST},{input:"\\uparrow",tag:"mo",output:"\u2191",ttype:CONST},{input:"\\downarrow",tag:"mo",output:"\u2193",ttype:CONST},{input:"\\updownarrow",tag:"mo",output:"\u2195",ttype:CONST},{input:"\\Leftarrow",tag:"mo",output:"\u21D0",ttype:CONST},{input:"\\Rightarrow",tag:"mo",output:"\u21D2",ttype:CONST},{input:"\\Leftrightarrow",tag:"mo",output:"\u21D4",ttype:CONST},{input:"\\iff",tag:"mo",output:"~\\Longleftrightarrow~",ttype:DEFINITION},{input:"\\Uparrow",tag:"mo",output:"\u21D1",ttype:CONST},{input:"\\Downarrow",tag:"mo",output:"\u21D3",ttype:CONST},{input:"\\Updownarrow",tag:"mo",output:"\u21D5",ttype:CONST},{input:"\\mapsto",tag:"mo",output:"\u21A6",ttype:CONST},{input:"\\longleftarrow",tag:"mo",output:"\u2190",ttype:LONG},{input:"\\longrightarrow",tag:"mo",output:"\u2192",ttype:LONG},{input:"\\longleftrightarrow",tag:"mo",output:"\u2194",ttype:LONG},{input:"\\Longleftarrow",tag:"mo",output:"\u21D0",ttype:LONG},{input:"\\Longrightarrow",tag:"mo",output:"\u21D2",ttype:LONG},{input:"\\Longleftrightarrow",tag:"mo",output:"\u21D4",ttype:LONG},{input:"\\longmapsto",tag:"mo",output:"\u21A6",ttype:CONST},AMsqrt,AMroot,AMfrac,AMover,AMsub,AMsup,AMtext,AMmbox,AMatop,AMchoose,{input:"\\acute",tag:"mover",output:"\u00B4",ttype:UNARY,acc:true},{input:"\\grave",tag:"mover",output:"\u0060",ttype:UNARY,acc:true},{input:"\\breve",tag:"mover",output:"\u02D8",ttype:UNARY,acc:true},{input:"\\check",tag:"mover",output:"\u02C7",ttype:UNARY,acc:true},{input:"\\dot",tag:"mover",output:".",ttype:UNARY,acc:true},{input:"\\ddot",tag:"mover",output:"..",ttype:UNARY,acc:true},{input:"\\mathring",tag:"mover",output:"\u00B0",ttype:UNARY,acc:true},{input:"\\vec",tag:"mover",output:"\u20D7",ttype:UNARY,acc:true},{input:"\\overrightarrow",tag:"mover",output:"\u20D7",ttype:UNARY,acc:true},{input:"\\overleftarrow",tag:"mover",output:"\u20D6",ttype:UNARY,acc:true},{input:"\\hat",tag:"mover",output:"\u005E",ttype:UNARY,acc:true},{input:"\\widehat",tag:"mover",output:"\u0302",ttype:UNARY,acc:true},{input:"\\tilde",tag:"mover",output:"~",ttype:UNARY,acc:true},{input:"\\widetilde",tag:"mover",output:"\u02DC",ttype:UNARY,acc:true},{input:"\\bar",tag:"mover",output:"\u203E",ttype:UNARY,acc:true},{input:"\\overbrace",tag:"mover",output:"\uFE37",ttype:UNARY,acc:true},{input:"\\overbracket",tag:"mover",output:"\u23B4",ttype:UNARY,acc:true},{input:"\\overline",tag:"mover",output:"\u00AF",ttype:UNARY,acc:true},{input:"\\underbrace",tag:"munder",output:"\uFE38",ttype:UNARY,acc:true},{input:"\\underbracket",tag:"munder",output:"\u23B5",ttype:UNARY,acc:true},{input:"\\underline",tag:"munder",output:"\u00AF",ttype:UNARY,acc:true},{input:"\\displaystyle",tag:"mstyle",atname:"displaystyle",atval:"true",ttype:UNARY},{input:"\\textstyle",tag:"mstyle",atname:"displaystyle",atval:"false",ttype:UNARY},{input:"\\scriptstyle",tag:"mstyle",atname:"scriptlevel",atval:"1",ttype:UNARY},{input:"\\scriptscriptstyle",tag:"mstyle",atname:"scriptlevel",atval:"2",ttype:UNARY},{input:"\\textrm",tag:"mstyle",output:"\\mathrm",ttype:DEFINITION},{input:"\\mathbf",tag:"mstyle",atname:"mathvariant",atval:"bold",ttype:UNARY},{input:"\\textbf",tag:"mstyle",atname:"mathvariant",atval:"bold",ttype:UNARY},{input:"\\mathit",tag:"mstyle",atname:"mathvariant",atval:"italic",ttype:UNARY},{input:"\\textit",tag:"mstyle",atname:"mathvariant",atval:"italic",ttype:UNARY},{input:"\\mathtt",tag:"mstyle",atname:"mathvariant",atval:"monospace",ttype:UNARY},{input:"\\texttt",tag:"mstyle",atname:"mathvariant",atval:"monospace",ttype:UNARY},{input:"\\mathsf",tag:"mstyle",atname:"mathvariant",atval:"sans-serif",ttype:UNARY},{input:"\\mathbb",tag:"mstyle",atname:"mathvariant",atval:"double-struck",ttype:UNARY,codes:AMbbb},{input:"\\mathcal",tag:"mstyle",atname:"mathvariant",atval:"script",ttype:UNARY,codes:AMcal},{input:"\\mathfrak",tag:"mstyle",atname:"mathvariant",atval:"fraktur",ttype:UNARY,codes:AMfrk},{input:"\\textcolor",tag:"mstyle",atname:"mathvariant",atval:"mathcolor",ttype:BINARY},{input:"\\colorbox",tag:"mstyle",atname:"mathvariant",atval:"background",ttype:BINARY}];function compareNames(s1,s2){if(s1.input>s2.input)return 1
-  else return-1;}
-  var AMnames=[];function AMinitSymbols(){AMsymbols.sort(compareNames);for(i=0;i<AMsymbols.length;i++)AMnames[i]=AMsymbols[i].input;}
-  var AMmathml="http://www.w3.org/1998/Math/MathML";function AMcreateElementMathML(t){if(isIE)return document.createElement("m:"+t);else return document.createElementNS(AMmathml,t);}
-  function AMcreateMmlNode(t,frag){if(isIE)var node=document.createElement("m:"+t);else var node=document.createElementNS(AMmathml,t);node.appendChild(frag);return node;}
-  function newcommand(oldstr,newstr){AMsymbols=AMsymbols.concat([{input:oldstr,tag:"mo",output:newstr,ttype:DEFINITION}]);}
-  function AMremoveCharsAndBlanks(str,n){var st;st=str.slice(n);for(var i=0;i<st.length&&st.charCodeAt(i)<=32;i=i+1);return st.slice(i);}
-  function AMposition(arr,str,n){if(n==0){var h,m;n=-1;h=arr.length;while(n+1<h){m=(n+h)>>1;if(arr[m]<str)n=m;else h=m;}
-  return h;}else
-  for(var i=n;i<arr.length&&arr[i]<str;i++);return i;}
-  function AMgetSymbol(str){var k=0;var j=0;var mk;var st;var tagst;var match="";var more=true;for(var i=1;i<=str.length&&more;i++){st=str.slice(0,i);j=k;k=AMposition(AMnames,st,j);if(k<AMnames.length&&str.slice(0,AMnames[k].length)==AMnames[k]){match=AMnames[k];mk=k;i=match.length;}
-  more=k<AMnames.length&&str.slice(0,AMnames[k].length)>=AMnames[k];}
-  AMpreviousSymbol=AMcurrentSymbol;if(match!=""){AMcurrentSymbol=AMsymbols[mk].ttype;return AMsymbols[mk];}
-  AMcurrentSymbol=CONST;k=1;st=str.slice(0,1);if("0"<=st&&st<="9")tagst="mn";else tagst=(("A">st||st>"Z")&&("a">st||st>"z")?"mo":"mi");return{input:st,tag:tagst,output:st,ttype:CONST};}
-  var AMpreviousSymbol,AMcurrentSymbol;function AMparseSexpr(str){var symbol,node,result,result2,i,st,newFrag=document.createDocumentFragment();str=AMremoveCharsAndBlanks(str,0);symbol=AMgetSymbol(str);if(symbol==null||symbol.ttype==RIGHTBRACKET)
-  return[null,str,null];if(symbol.ttype==DEFINITION){str=symbol.output+AMremoveCharsAndBlanks(str,symbol.input.length);symbol=AMgetSymbol(str);if(symbol==null||symbol.ttype==RIGHTBRACKET)
-  return[null,str,null];}
-  str=AMremoveCharsAndBlanks(str,symbol.input.length);switch(symbol.ttype){case SPACE:node=AMcreateElementMathML(symbol.tag);node.setAttribute(symbol.atname,symbol.atval);return[node,str,symbol.tag];case UNDEROVER:if(isIE){if(symbol.input.substr(0,4)=="\\big"){str="\\"+symbol.input.substr(4)+str;symbol=AMgetSymbol(str);symbol.ttype=UNDEROVER;str=AMremoveCharsAndBlanks(str,symbol.input.length);}}
-  return[AMcreateMmlNode(symbol.tag,document.createTextNode(symbol.output)),str,symbol.tag];case CONST:var output=symbol.output;if(isIE){if(symbol.input=="'")
-  output="\u2032";else if(symbol.input=="''")
-  output="\u2033";else if(symbol.input=="'''")
-  output="\u2033\u2032";else if(symbol.input=="''''")
-  output="\u2033\u2033";else if(symbol.input=="\\square")
-  output="\u25A1";else if(symbol.input.substr(0,5)=="\\frac"){var denom=symbol.input.substr(6,1);if(denom=="5"||denom=="6"){str=symbol.input.replace(/\\frac/,"\\frac ")+str;return[node,str,symbol.tag];}}}
-  node=AMcreateMmlNode(symbol.tag,document.createTextNode(output));return[node,str,symbol.tag];case LONG:node=AMcreateMmlNode(symbol.tag,document.createTextNode(symbol.output));node.setAttribute("minsize","1.5");node.setAttribute("maxsize","1.5");node=AMcreateMmlNode("mover",node);node.appendChild(AMcreateElementMathML("mspace"));return[node,str,symbol.tag];case STRETCHY:if(isIE&&symbol.input=="\\backslash")
-  symbol.output="\\";node=AMcreateMmlNode(symbol.tag,document.createTextNode(symbol.output));if(symbol.input=="|"||symbol.input=="\\vert"||symbol.input=="\\|"||symbol.input=="\\Vert"){node.setAttribute("lspace","0em");node.setAttribute("rspace","0em");}
-  node.setAttribute("maxsize",symbol.atval);if(symbol.rtag!=null)
-  return[node,str,symbol.rtag];else
-  return[node,str,symbol.tag];case BIG:var atval=symbol.atval;if(isIE)
-  atval=symbol.ieval;symbol=AMgetSymbol(str);if(symbol==null)
-  return[null,str,null];str=AMremoveCharsAndBlanks(str,symbol.input.length);node=AMcreateMmlNode(symbol.tag,document.createTextNode(symbol.output));if(isIE){var space=AMcreateElementMathML("mspace");space.setAttribute("height",atval+"ex");node=AMcreateMmlNode("mrow",node);node.appendChild(space);}else{node.setAttribute("minsize",atval);node.setAttribute("maxsize",atval);}
-  return[node,str,symbol.tag];case LEFTBRACKET:if(symbol.input=="\\left"){symbol=AMgetSymbol(str);if(symbol!=null){if(symbol.input==".")
-  symbol.invisible=true;str=AMremoveCharsAndBlanks(str,symbol.input.length);}}
-  result=AMparseExpr(str,true,false);if(symbol==null||(typeof symbol.invisible=="boolean"&&symbol.invisible))
-  node=AMcreateMmlNode("mrow",result[0]);else{node=AMcreateMmlNode("mo",document.createTextNode(symbol.output));node=AMcreateMmlNode("mrow",node);node.appendChild(result[0]);}
-  return[node,result[1],result[2]];case MATRIX:if(symbol.input=="\\begin{array}"){var mask="";symbol=AMgetSymbol(str);str=AMremoveCharsAndBlanks(str,0);if(symbol==null)
-  mask="l";else{str=AMremoveCharsAndBlanks(str,symbol.input.length);if(symbol.input!="{")
-  mask="l";else do{symbol=AMgetSymbol(str);if(symbol!=null){str=AMremoveCharsAndBlanks(str,symbol.input.length);if(symbol.input!="}")
-  mask=mask+symbol.input;}}while(symbol!=null&&symbol.input!=""&&symbol.input!="}");}
-  result=AMparseExpr("{"+str,true,true);node=AMcreateMmlNode("mtable",result[0]);mask=mask.replace(/l/g,"left ");mask=mask.replace(/r/g,"right ");mask=mask.replace(/c/g,"center ");node.setAttribute("columnalign",mask);node.setAttribute("displaystyle","false");if(isIE)
-  return[node,result[1],null];var lspace=AMcreateElementMathML("mspace");lspace.setAttribute("width","0.167em");var rspace=AMcreateElementMathML("mspace");rspace.setAttribute("width","0.167em");var node1=AMcreateMmlNode("mrow",lspace);node1.appendChild(node);node1.appendChild(rspace);return[node1,result[1],null];}else{result=AMparseExpr("{"+str,true,true);node=AMcreateMmlNode("mtable",result[0]);if(isIE)
-  node.setAttribute("columnspacing","0.25em");else
-  node.setAttribute("columnspacing","0.167em");node.setAttribute("columnalign","right center left");node.setAttribute("displaystyle","true");node=AMcreateMmlNode("mrow",node);return[node,result[1],null];}
-  case TEXT:if(str.charAt(0)=="{")i=str.indexOf("}");else i=0;if(i==-1)
-  i=str.length;st=str.slice(1,i);if(st.charAt(0)==" "){node=AMcreateElementMathML("mspace");node.setAttribute("width","0.33em");newFrag.appendChild(node);}
-  newFrag.appendChild(AMcreateMmlNode(symbol.tag,document.createTextNode(st)));if(st.charAt(st.length-1)==" "){node=AMcreateElementMathML("mspace");node.setAttribute("width","0.33em");newFrag.appendChild(node);}
-  str=AMremoveCharsAndBlanks(str,i+1);return[AMcreateMmlNode("mrow",newFrag),str,null];case UNARY:result=AMparseSexpr(str);if(result[0]==null)return[AMcreateMmlNode(symbol.tag,document.createTextNode(symbol.output)),str];if(typeof symbol.func=="boolean"&&symbol.func){st=str.charAt(0);if(st=="^"||st=="_"||st==","){return[AMcreateMmlNode(symbol.tag,document.createTextNode(symbol.output)),str,symbol.tag];}else{node=AMcreateMmlNode("mrow",AMcreateMmlNode(symbol.tag,document.createTextNode(symbol.output)));if(isIE){var space=AMcreateElementMathML("mspace");space.setAttribute("width","0.167em");node.appendChild(space);}
-  node.appendChild(result[0]);return[node,result[1],symbol.tag];}}
-  if(symbol.input=="\\sqrt"){if(isIE){var space=AMcreateElementMathML("mspace");space.setAttribute("height","1.2ex");space.setAttribute("width","0em");node=AMcreateMmlNode(symbol.tag,result[0])
-  node.appendChild(space);return[node,result[1],symbol.tag];}else
-  return[AMcreateMmlNode(symbol.tag,result[0]),result[1],symbol.tag];}else if(typeof symbol.acc=="boolean"&&symbol.acc){node=AMcreateMmlNode(symbol.tag,result[0]);var output=symbol.output;if(isIE){if(symbol.input=="\\hat")
-  output="\u0302";else if(symbol.input=="\\widehat")
-  output="\u005E";else if(symbol.input=="\\bar")
-  output="\u00AF";else if(symbol.input=="\\grave")
-  output="\u0300";else if(symbol.input=="\\tilde")
-  output="\u0303";}
-  var node1=AMcreateMmlNode("mo",document.createTextNode(output));if(symbol.input=="\\vec"||symbol.input=="\\check")
-  node1.setAttribute("maxsize","1.2");if(isIE&&symbol.input=="\\bar")
-  node1.setAttribute("maxsize","0.5");if(symbol.input=="\\underbrace"||symbol.input=="\\underline")
-  node1.setAttribute("accentunder","true");else
-  node1.setAttribute("accent","true");node.appendChild(node1);if(symbol.input=="\\overbrace"||symbol.input=="\\underbrace")
-  node.ttype=UNDEROVER;return[node,result[1],symbol.tag];}else{if(!isIE&&typeof symbol.codes!="undefined"){for(i=0;i<result[0].childNodes.length;i++)
-  if(result[0].childNodes[i].nodeName=="mi"||result[0].nodeName=="mi"){st=(result[0].nodeName=="mi"?result[0].firstChild.nodeValue:result[0].childNodes[i].firstChild.nodeValue);var newst=[];for(var j=0;j<st.length;j++)
-  if(st.charCodeAt(j)>64&&st.charCodeAt(j)<91)newst=newst+
-  String.fromCharCode(symbol.codes[st.charCodeAt(j)-65]);else newst=newst+st.charAt(j);if(result[0].nodeName=="mi")
-  result[0]=AMcreateElementMathML("mo").appendChild(document.createTextNode(newst));else result[0].replaceChild(AMcreateElementMathML("mo").appendChild(document.createTextNode(newst)),result[0].childNodes[i]);}}
-  node=AMcreateMmlNode(symbol.tag,result[0]);node.setAttribute(symbol.atname,symbol.atval);if(symbol.input=="\\scriptstyle"||symbol.input=="\\scriptscriptstyle")
-  node.setAttribute("displaystyle","false");return[node,result[1],symbol.tag];}
-  case BINARY:result=AMparseSexpr(str);if(result[0]==null)return[AMcreateMmlNode("mo",document.createTextNode(symbol.input)),str,null];result2=AMparseSexpr(result[1]);if(result2[0]==null)return[AMcreateMmlNode("mo",document.createTextNode(symbol.input)),str,null];if(symbol.input=="\\textcolor"||symbol.input=="\\colorbox"){var tclr=str.match(/\{\s*([#\w]+)\s*\}/);str=str.replace(/\{\s*[#\w]+\s*\}/,"");if(tclr!=null){if(IsColorName.test(tclr[1].toLowerCase())){tclr=LaTeXColor[tclr[1].toLowerCase()];}else{tclr=tclr[1];}
-  node=AMcreateElementMathML("mstyle");node.setAttribute(symbol.atval,tclr);node.appendChild(result2[0]);return[node,result2[1],symbol.tag];}}
-  if(symbol.input=="\\root"||symbol.input=="\\stackrel")newFrag.appendChild(result2[0]);newFrag.appendChild(result[0]);if(symbol.input=="\\frac")newFrag.appendChild(result2[0]);return[AMcreateMmlNode(symbol.tag,newFrag),result2[1],symbol.tag];case INFIX:str=AMremoveCharsAndBlanks(str,symbol.input.length);return[AMcreateMmlNode("mo",document.createTextNode(symbol.output)),str,symbol.tag];default:return[AMcreateMmlNode(symbol.tag,document.createTextNode(symbol.output)),str,symbol.tag];}}
-  function AMparseIexpr(str){var symbol,sym1,sym2,node,result,tag,underover;str=AMremoveCharsAndBlanks(str,0);sym1=AMgetSymbol(str);result=AMparseSexpr(str);node=result[0];str=result[1];tag=result[2];symbol=AMgetSymbol(str);if(symbol.ttype==INFIX){str=AMremoveCharsAndBlanks(str,symbol.input.length);result=AMparseSexpr(str);if(result[0]==null)
-  result[0]=AMcreateMmlNode("mo",document.createTextNode("\u25A1"));str=result[1];tag=result[2];if(symbol.input=="_"||symbol.input=="^"){sym2=AMgetSymbol(str);tag=null;underover=((sym1.ttype==UNDEROVER)||(node.ttype==UNDEROVER));if(symbol.input=="_"&&sym2.input=="^"){str=AMremoveCharsAndBlanks(str,sym2.input.length);var res2=AMparseSexpr(str);str=res2[1];tag=res2[2];node=AMcreateMmlNode((underover?"munderover":"msubsup"),node);node.appendChild(result[0]);node.appendChild(res2[0]);}else if(symbol.input=="_"){node=AMcreateMmlNode((underover?"munder":"msub"),node);node.appendChild(result[0]);}else{node=AMcreateMmlNode((underover?"mover":"msup"),node);node.appendChild(result[0]);}
-  node=AMcreateMmlNode("mrow",node);}else{node=AMcreateMmlNode(symbol.tag,node);if(symbol.input=="\\atop"||symbol.input=="\\choose")
-  node.setAttribute("linethickness","0ex");node.appendChild(result[0]);if(symbol.input=="\\choose")
-  node=AMcreateMmlNode("mfenced",node);}}
-  return[node,str,tag];}
-  function AMparseExpr(str,rightbracket,matrix){var symbol,node,result,i,tag,newFrag=document.createDocumentFragment();do{str=AMremoveCharsAndBlanks(str,0);result=AMparseIexpr(str);node=result[0];str=result[1];tag=result[2];symbol=AMgetSymbol(str);if(node!=undefined){if((tag=="mn"||tag=="mi")&&symbol!=null&&typeof symbol.func=="boolean"&&symbol.func){var space=AMcreateElementMathML("mspace");space.setAttribute("width","0.167em");node=AMcreateMmlNode("mrow",node);node.appendChild(space);}
-  newFrag.appendChild(node);}}while((symbol.ttype!=RIGHTBRACKET)&&symbol!=null&&symbol.output!="");tag=null;if(symbol.ttype==RIGHTBRACKET){if(symbol.input=="\\right"){str=AMremoveCharsAndBlanks(str,symbol.input.length);symbol=AMgetSymbol(str);if(symbol!=null&&symbol.input==".")
-  symbol.invisible=true;if(symbol!=null)
-  tag=symbol.rtag;}
-  if(symbol!=null)
-  str=AMremoveCharsAndBlanks(str,symbol.input.length);var len=newFrag.childNodes.length;if(matrix&&len>0&&newFrag.childNodes[len-1].nodeName=="mrow"&&len>1&&newFrag.childNodes[len-2].nodeName=="mo"&&newFrag.childNodes[len-2].firstChild.nodeValue=="&"){var pos=[];var m=newFrag.childNodes.length;for(i=0;matrix&&i<m;i=i+2){pos[i]=[];node=newFrag.childNodes[i];for(var j=0;j<node.childNodes.length;j++)
-  if(node.childNodes[j].firstChild.nodeValue=="&")
-  pos[i][pos[i].length]=j;}
-  var row,frag,n,k,table=document.createDocumentFragment();for(i=0;i<m;i=i+2){row=document.createDocumentFragment();frag=document.createDocumentFragment();node=newFrag.firstChild;n=node.childNodes.length;k=0;for(j=0;j<n;j++){if(typeof pos[i][k]!="undefined"&&j==pos[i][k]){node.removeChild(node.firstChild);row.appendChild(AMcreateMmlNode("mtd",frag));k++;}else frag.appendChild(node.firstChild);}
-  row.appendChild(AMcreateMmlNode("mtd",frag));if(newFrag.childNodes.length>2){newFrag.removeChild(newFrag.firstChild);newFrag.removeChild(newFrag.firstChild);}
-  table.appendChild(AMcreateMmlNode("mtr",row));}
-  return[table,str];}
-  if(typeof symbol.invisible!="boolean"||!symbol.invisible){node=AMcreateMmlNode("mo",document.createTextNode(symbol.output));newFrag.appendChild(node);}}
-  return[newFrag,str,tag];}
-  function AMparseMath(str){var result,node=AMcreateElementMathML("mstyle");var cclr=str.match(/\\color\s*\{\s*([#\w]+)\s*\}/);str=str.replace(/\\color\s*\{\s*[#\w]+\s*\}/g,"");if(cclr!=null){if(IsColorName.test(cclr[1].toLowerCase())){cclr=LaTeXColor[cclr[1].toLowerCase()];}else{cclr=cclr[1];}
-  node.setAttribute("mathcolor",cclr);}else{if(mathcolor!="")node.setAttribute("mathcolor",mathcolor);};if(mathfontfamily!="")node.setAttribute("fontfamily",mathfontfamily);node.appendChild(AMparseExpr(str.replace(/^\s+/g,""),false,false)[0]);node=AMcreateMmlNode("math",node);if(showasciiformulaonhover)
-  node.setAttribute("title",str.replace(/\s+/g," "));if(false){var fnode=AMcreateElementXHTML("font");fnode.setAttribute("face",mathfontfamily);fnode.appendChild(node);return fnode;}
-  return node;}
-  function AMstrarr2docFrag(arr,linebreaks){var newFrag=document.createDocumentFragment();var expr=false;for(var i=0;i<arr.length;i++){if(expr)newFrag.appendChild(AMparseMath(arr[i]));else{var arri=(linebreaks?arr[i].split("\n\n"):[arr[i]]);newFrag.appendChild(AMcreateElementXHTML("span").appendChild(document.createTextNode(arri[0])));for(var j=1;j<arri.length;j++){newFrag.appendChild(AMcreateElementXHTML("p"));newFrag.appendChild(AMcreateElementXHTML("span").appendChild(document.createTextNode(arri[j])));}}
-  expr=!expr;}
-  return newFrag;}
-  function AMprocessNodeR(n,linebreaks){var mtch,str,arr,frg,i;if(n.childNodes.length==0){if((n.nodeType!=8||linebreaks)&&n.parentNode.nodeName!="form"&&n.parentNode.nodeName!="FORM"&&n.parentNode.nodeName!="textarea"&&n.parentNode.nodeName!="TEXTAREA"&&n.parentNode.nodeName!="pre"&&n.parentNode.nodeName!="PRE"){str=n.nodeValue;if(!(str==null)){str=str.replace(/\r\n\r\n/g,"\n\n");str=str.replace(/\x20+/g," ");str=str.replace(/\s*\r\n/g," ");mtch=(str.indexOf("\$")==-1?false:true);str=str.replace(/([^\\])\$/g,"$1 \$");str=str.replace(/^\$/," \$");arr=str.split(" \$");for(i=0;i<arr.length;i++)
-  arr[i]=arr[i].replace(/\\\$/g,"\$");if(arr.length>1||mtch){if(checkForMathML){checkForMathML=false;var nd=AMisMathMLavailable();AMnoMathML=nd!=null;if(AMnoMathML&&notifyIfNoMathML)
-  if(alertIfNoMathML)
-  alert("To view the ASCIIMathML notation use Internet Explorer 6 +\nMathPlayer (free from www.dessci.com)\nor Firefox/Mozilla/Netscape");else AMbody.insertBefore(nd,AMbody.childNodes[0]);}
-  if(!AMnoMathML){frg=AMstrarr2docFrag(arr,n.nodeType==8);var len=frg.childNodes.length;n.parentNode.replaceChild(frg,n);return len-1;}else return 0;}}}else return 0;}else if(n.nodeName!="math"){for(i=0;i<n.childNodes.length;i++)
-  i+=AMprocessNodeR(n.childNodes[i],linebreaks);}
-  return 0;}
-  function AMprocessNode(n,linebreaks,spanclassAM){var frag,st;if(spanclassAM!=null){frag=document.getElementsByTagName("span")
-  for(var i=0;i<frag.length;i++)
-  if(frag[i].className=="AM")
-  AMprocessNodeR(frag[i],linebreaks);}else{try{st=n.innerHTML;}catch(err){}
-  if(st==null||st.indexOf("\$")!=-1)
-  AMprocessNodeR(n,linebreaks);}
-  if(isIE){frag=document.getElementsByTagName('math');for(var i=0;i<frag.length;i++)frag[i].update()}}
-  var inAppendix=false;var sectionCntr=0;var IEcommentWarning=true;var biblist=[];var bibcntr=0;var LaTeXCounter=[];LaTeXCounter["definition"]=0;LaTeXCounter["proposition"]=0;LaTeXCounter["lemma"]=0;LaTeXCounter["theorem"]=0;LaTeXCounter["corollary"]=0;LaTeXCounter["example"]=0;LaTeXCounter["exercise"]=0;LaTeXCounter["subsection"]=0;LaTeXCounter["subsubsection"]=0;LaTeXCounter["figure"]=0;LaTeXCounter["equation"]=0;LaTeXCounter["table"]=0;var LaTeXColor=[];LaTeXColor["greenyellow"]="#D9FF4F";LaTeXColor["yellow"]="#FFFF00";LaTeXColor["goldenrod"]="#FFE529";LaTeXColor["dandelion"]="#FFB529";LaTeXColor["apricot"]="#FFAD7A";LaTeXColor["peach"]="#FF804D";LaTeXColor["melon"]="#FF8A80";LaTeXColor["yelloworange"]="#FF9400";LaTeXColor["orange"]="#FF6321";LaTeXColor["burntorange"]="#FF7D00";LaTeXColor["bittersweet"]="#C20300";LaTeXColor["redorange"]="#FF3B21";LaTeXColor["mahogany"]="#A60000";LaTeXColor["maroon"]="#AD0000";LaTeXColor["brickred"]="#B80000";LaTeXColor["red"]="#FF0000";LaTeXColor["orangered"]="#FF0080";LaTeXColor["rubinered"]="#FF00DE";LaTeXColor["wildstrawberry"]="#FF0A9C";LaTeXColor["salmon"]="#FF789E";LaTeXColor["carnationpink"]="#FF5EFF";LaTeXColor["magenta"]="#FF00FF";LaTeXColor["violetred"]="#FF30FF";LaTeXColor["rhodamine"]="#FF2EFF";LaTeXColor["mulberry"]="#A314FA";LaTeXColor["redviolet"]="#9600A8";LaTeXColor["fuchsia"]="#7303EB";LaTeXColor["lavender"]="#FF85FF";LaTeXColor["thistle"]="#E069FF";LaTeXColor["orchid"]="#AD5CFF";LaTeXColor["darkorchid"]="#9933CC";LaTeXColor["purple"]="#8C24FF";LaTeXColor["plum"]="#8000FF";LaTeXColor["violet"]="#361FFF";LaTeXColor["royalpurple"]="#401AFF";LaTeXColor["blueviolet"]="#1A0DF5";LaTeXColor["periwinkle"]="#6E73FF";LaTeXColor["cadetblue"]="#616EC4";LaTeXColor["cornflowerblue"]="#59DEFF";LaTeXColor["midnightblue"]="#007091";LaTeXColor["navyblue"]="#0F75FF";LaTeXColor["royalblue"]="#0080FF";LaTeXColor["blue"]="#0000FF";LaTeXColor["cerulean"]="#0FE3FF";LaTeXColor["cyan"]="#00FFFF";LaTeXColor["processblue"]="#0AFFFF";LaTeXColor["skyblue"]="#61FFE0";LaTeXColor["turquoise"]="#26FFCC";LaTeXColor["tealblue"]="#1FFAA3";LaTeXColor["aquamarine"]="#2EFFB2";LaTeXColor["bluegreen"]="#26FFAB";LaTeXColor["emerald"]="#00FF80";LaTeXColor["junglegreen"]="#03FF7A";LaTeXColor["seagreen"]="#4FFF80";LaTeXColor["green"]="#00FF00";LaTeXColor["forestgreen"]="#00E000";LaTeXColor["pinegreen"]="#00BF29";LaTeXColor["limegreen"]="#80FF00";LaTeXColor["yellowgreen"]="#8FFF42";LaTeXColor["springgreen"]="#BDFF3D";LaTeXColor["olivegreen"]="#009900";LaTeXColor["rawsienna"]="#8C0000";LaTeXColor["sepia"]="#4D0000";LaTeXColor["brown"]="#660000";LaTeXColor["tan"]="#DB9470";LaTeXColor["gray"]="#808080";LaTeXColor["grey"]="#808080";LaTeXColor["black"]="#000000";LaTeXColor["white"]="#FFFFFF";var IsColorName=/^(?:greenyellow|yellow|goldenrod|dandelion|apricot|peach|melon|yelloworange|orange|burntorange|bittersweet|redorange|mahogany|maroon|brickred|red|orangered|rubinered|wildstrawberry|salmon|carnationpink|magenta|violetred|rhodamine|mulberry|redviolet|fuchsia|lavender|thistle|orchid|darkorchid|purple|plum|violet|royalpurple|blueviolet|periwinkle|cadetblue|cornflowerblue|midnightblue|navyblue|royalblue|blue|cerulean|cyan|processblue|skyblue|turquoise|tealblue|aquamarine|bluegreen|emerald|junglegreen|seagreen|green|forestgreen|pinegreen|limegreen|yellowgreen|springgreen|olivegreen|rawsienna|sepia|brown|tan|gray|grey|black|white)$/;var IsCounter=/^(?:definition|proposition|lemma|theorem|corollary|example|exercise|subsection|subsubsection|figure|equation|table)$/;var IsLaTeXElement=/^(?:displayequation|title|author|address|date|abstract|keyword|section|subsection|subsubsection|ref|cite|thebibliography|definition|proposition|lemma|theorem|corollary|example|exercise|itemize|enumerate|enddefinition|endproposition|endlemma|endtheorem|endcorollary|endexample|endexercise|enditemize|endenumerate|LaTeXMathMLlabel|LaTeXMathML|smallskip|medskip|bigskip|quote|quotation|endquote|endquotation|center|endcenter|description|enddescription|inlinemath)$/;var IsTextOnlyArea=/^(?:form|textarea|pre)$/i;var tableid=0;function makeNumberString(cntr){if(sectionCntr>0){if(inAppendix){return"A"+sectionCntr+"."+cntr;}else{return sectionCntr+"."+cntr;}}else{return""+cntr;}};function LaTeXpreProcess(thebody){var TheBody=thebody;if(TheBody.hasChildNodes()){if(!(IsLaTeXElement.test(TheBody.className)))
-  {for(var i=0;i<TheBody.childNodes.length;i++){LaTeXpreProcess(TheBody.childNodes[i])}}}
-  else{if(TheBody.nodeType==3&&!(IsTextOnlyArea.test(TheBody.parentNode.nodeName)))
-  {var str=TheBody.nodeValue;if(!(str==null)){str=str.replace(/\\%/g,"<per>");str=str.replace(/%[^\n]*(?=\n)/g,"");str=str.replace(/%[^\r]*(?=\r)/g,"");str=str.replace(/%[^\n]*$/,"")
-  if(isIE&&str.match(/%/g)!=null&&IEcommentWarning){alert("Comments may not have parsed properly.  Try putting in <pre class='LaTeX><div>..</div></pre> structure.");IEcommentWarning=false;}
-  str=str.replace(/<per>/g,"%");if(str.match(/XXX[\s\S]*/)!=null){var tmp=str.match(/XXX[\s\S]*/)[0];var tmpstr=tmp.charCodeAt(7)+"::"+tmp.charCodeAt(8)+"::"+tmp.charCodeAt(9)+"::"+tmp.charCodeAt(10)+"::"+tmp.charCodeAt(11)+"::"+tmp.charCodeAt(12)+"::"+tmp.charCodeAt(13);alert(tmpstr);}
-  str=str.replace(/([^\\])\\(\s)/g,"$1\u00A0$2");str=str.replace(/\\quad/g,"\u2001");str=str.replace(/\\qquad/g,"\u2001\u2001");str=str.replace(/\\enspace/g,"\u2002");str=str.replace(/\\;/g,"\u2004");str=str.replace(/\\:/g,"\u2005");str=str.replace(/\\,/g,"\u2006");str=str.replace(/\\thinspace/g,"\u200A");str=str.replace(/([^\\])~/g,"$1\u00A0");str=str.replace(/\\~/g,"~");str=str.replace(/\\\[/g," <DEQ> $\\displaystyle{");str=str.replace(/\\\]/g,"}$ <DEQ> ");str=str.replace(/\$\$/g,"${$<DEQ>$}$");str=str.replace(/\\begin\s*\{\s*array\s*\}/g,"\\begin{array}");str=str.replace(/\\end\s*\{\s*array\s*\}/g,"\\end{array}");str=str.replace(/\\begin\s*\{\s*eqnarray\s*\}/g,"  <DEQ>eqno$\\begin{eqnarray}");str=str.replace(/\\end\s*\{\s*eqnarray\s*\}/g,"\\end{eqnarray}$<DEQ>  ");str=str.replace(/\\begin\s*\{\s*eqnarray\*\s*\}/g,"  <DEQ>$\\begin{eqnarray}");str=str.replace(/\\end\s*\{\s*eqnarray\*\s*\}/g,"\\end{eqnarray}$<DEQ>  ");str=str.replace(/\\begin\s*\{\s*displaymath\s*\}/g," <DEQ> $\\displaystyle{");str=str.replace(/\\end\s*\{\s*displaymath\s*\}/g,"}$ <DEQ> ");str=str.replace(/\\begin\s*\{\s*equation\s*\*\s*\}/g," <DEQ> $\\displaystyle{");str=str.replace(/\\end\s*\{\s*equation\s*\*\s*\}/g,"}$ <DEQ> ");str=str.replace(/\\begin\s*\{\s*equation\s*\}/g," <DEQ>eqno$\\displaystyle{");str=str.replace(/\\end\s*\{\s*equation\s*\}/g,"}$ <DEQ> ");str=str.split("<DEQ>");var newFrag=document.createDocumentFragment();for(var i=0;i<str.length;i++){if(i%2){var DEQtable=document.createElement("table");DEQtable.className='displayequation';var DEQtbody=document.createElement("tbody");var DEQtr=document.createElement("tr");var DEQtdeq=document.createElement("td");DEQtdeq.className='eq';str[i]=str[i].replace(/\$\}\$/g,"$\\displaystyle{");str[i]=str[i].replace(/\$\{\$/g,"}");var lbl=str[i].match(/\\label\s*\{\s*(\w+)\s*\}/);var ISeqno=str[i].match(/^eqno/);str[i]=str[i].replace(/^eqno/," ");str[i]=str[i].replace(/\\label\s*\{\s*\w+\s*\}/," ");DEQtdeq.appendChild(document.createTextNode(str[i]));DEQtr.appendChild(DEQtdeq);str[i]=str[i].replace(/\\nonumber/g,"");if(ISeqno!=null||lbl!=null){var DEQtdno=document.createElement("td");DEQtdno.className='eqno';LaTeXCounter["equation"]++;var eqnoString=makeNumberString(LaTeXCounter["equation"]);var DEQanchor=document.createElement("a");if(lbl!=null){DEQanchor.id=lbl[1]};DEQanchor.className="eqno";var anchorSpan=document.createElement("span");anchorSpan.className="eqno";anchorSpan.style.display="none";anchorSpan.appendChild(document.createTextNode(eqnoString));DEQanchor.appendChild(anchorSpan);DEQtdno.appendChild(DEQanchor);var DEQspan=document.createElement("span");DEQspan.className="eqno";DEQspan.appendChild(document.createTextNode("("+eqnoString+")"));DEQtdno.appendChild(DEQspan);DEQtr.appendChild(DEQtdno);}
-  DEQtbody.appendChild(DEQtr);DEQtable.appendChild(DEQtbody);newFrag.appendChild(DEQtable);}
-  else{str[i]=str[i].replace(/\$\}\$/g,"");str[i]=str[i].replace(/\$\{\$/g,"");str[i]=str[i].replace(/\\maketitle/g,"");str[i]=str[i].replace(/\\begin\s*\{\s*document\s*\}/g,"");str[i]=str[i].replace(/\\end\s*\{\s*document\s*\}/g,"");str[i]=str[i].replace(/\\documentclass[^\}]*?\}/g,"");str[i]=str[i].replace(/\\usepackage[^\}]*?\}/g,"");str[i]=str[i].replace(/\\noindent/g,"");str[i]=str[i].replace(/\\notag/g,"");str[i]=str[i].replace(/\\ref\s*\{\s*(\w+)\}/g," \\[ref\\]$1\\[ ");str[i]=str[i].replace(/\\url\s*\{\s*([^\}\n]+)\}/g," \\[url\\]$1\\[ ");str[i]=str[i].replace(/\\href\s*\{\s*([^\}]+)\}\s*\{\s*([^\}]+)\}/g," \\[href\\]$1\\]$2\\[ ");str[i]=str[i].replace(/\\cite\s*\{\s*(\w+)\}/g," \\[cite\\]$1\\[ ");str[i]=str[i].replace(/\\qed/g,"\u220E");str[i]=str[i].replace(/\\endproof/g,"\u220E");str[i]=str[i].replace(/\\proof/g,"\\textbf{Proof: }");str[i]=str[i].replace(/\\n(?=\s)/g," \\[br\\] \\[ ");str[i]=str[i].replace(/\\newline/g," \\[br\\] \\[ ");str[i]=str[i].replace(/\\linebreak/g," \\[br\\] \\[ ");str[i]=str[i].replace(/\\smallskip/g," \\[logicalbreak\\]smallskip\\[ ");str[i]=str[i].replace(/\\medskip/g," \\[logicalbreak\\]medskip\\[ ");str[i]=str[i].replace(/\\bigskip/g," \\[logicalbreak\\]bigskip\\[ ");str[i]=str[i].replace(/[\n\r]+[ \f\n\r\t\v\u2028\u2029]*[\n\r]+/g," \\[logicalbreak\\]LaTeXMathML\\[ ");if(isIE){str[i]=str[i].replace(/\r/g," ");}
-  str[i]=str[i].replace(/\\bibitem\s*([^\{]*\{\s*\w*\s*\})/g," \\[bibitem\\]$1\\[ ");str[i]=str[i].replace(/\\bibitem\s*/g," \\[bibitem\\] \\[ ");str[i]=str[i].replace(/\\item\s*\[\s*(\w+)\s*\]/g," \\[alistitem\\]$1\\[ ");str[i]=str[i].replace(/\\item\s*/g," \\[alistitem\\] \\[ ");str[i]=str[i].replace(/\\appendix/g," \\[appendix\\] \\[ ");str[i]=str[i].replace(/\\begin\s*\{\s*figure\s*\}([\s\S]+?)\\end\s*\{\s*figure\s*\}/g," \\[figure\\]$1\\[ ");str[i]=str[i].replace(/\\begin\s*\{\s*table\s*\}([\s\S]+?)\\end\s*\{\s*table\s*\}/g," \\[table\\]$1\\[ ");str[i]=str[i].replace(/\\begin\s*\{\s*theorem\s*\}/g," \\[theorem\\]Theorem \\[ ");str[i]=str[i].replace(/\\end\s*\{\s*theorem\s*\}/g," \\[endtheorem\\] \\[ ");str[i]=str[i].replace(/\\begin\s*\{\s*definition\s*\}/g," \\[definition\\]Definition \\[ ");str[i]=str[i].replace(/\\end\s*\{\s*definition\s*\}/g," \\[enddefinition\\] \\[ ");str[i]=str[i].replace(/\\begin\s*\{\s*lemma\s*\}/g," \\[lemma\\]Lemma \\[ ");str[i]=str[i].replace(/\\end\s*\{\s*lemma\s*\}/g," \\[endlemma\\] \\[ ");str[i]=str[i].replace(/\\begin\s*\{\s*corollary\s*\}/g," \\[corollary\\]Corollary \\[ ");str[i]=str[i].replace(/\\end\s*\{\s*corollary\s*\}/g," \\[endcorollary\\] \\[ ");str[i]=str[i].replace(/\\begin\s*\{\s*proposition\s*\}/g," \\[proposition\\]Proposition \\[ ");str[i]=str[i].replace(/\\end\s*\{\s*proposition\s*\}/g," \\[endproposition\\] \\[ ");str[i]=str[i].replace(/\\begin\s*\{\s*example\s*\}/g," \\[example\\]Example \\[ ");str[i]=str[i].replace(/\\end\s*\{\s*example\s*\}/g," \\[endexample\\] \\[ ");str[i]=str[i].replace(/\\begin\s*\{\s*exercise\s*\}/g," \\[exercise\\]Exercise \\[ ");str[i]=str[i].replace(/\\end\s*\{\s*exercise\s*\}/g," \\[endexercise\\] \\[ ");str[i]=str[i].replace(/\\begin\s*\{\s*thebibliography\s*\}\s*\{\s*\w+\s*\}/g," \\[thebibliography\\]References \\[ ");str[i]=str[i].replace(/\\begin\s*\{\s*thebibliography\s*\}/g," \\[thebibliography\\]References \\[ ");str[i]=str[i].replace(/\\end\s*\{\s*thebibliography\s*\}/g," \\[endthebibliography\\]References \\[ ");str[i]=str[i].replace(/\\begin\s*\{\s*proof\s*\}/g," \\[proof\\]Proof: \\[ ");if(isIE){str[i]=str[i].replace(/\\end\s*\{\s*proof\s*\}/g,"\u220E \\[endproof\\] \\[ ");}else{str[i]=str[i].replace(/\\end\s*\{\s*proof\s*\}/g," \\[endproof\\] \\[ ");}
-  str[i]=str[i].replace(/\\title\s*\{\s*([^\}]+)\}/g," \\[title\\] \\[$1 \\[endtitle\\] \\[ ");str[i]=str[i].replace(/\\author\s*\{\s*([^\}]+)\}/g," \\[author\\] \\[$1 \\[endauthor\\] \\[ ");str[i]=str[i].replace(/\\address\s*\{\s*([^\}]+)\}/g," \\[address\\] \\[$1 \\[endaddress\\] \\[ ");str[i]=str[i].replace(/\\date\s*\{\s*([^\}]+)\}/g," \\[date\\] \\[$1 \\[enddate\\] \\[ ");str[i]=str[i].replace(/\\begin\s*\{\s*keyword\s*\}/g," \\[keyword\\] \\[ ");str[i]=str[i].replace(/\\end\s*\{\s*keyword\s*\}/g," \\[endkeyword\\] \\[ ");str[i]=str[i].replace(/\\begin\s*\{\s*abstract\s*\}/g," \\[abstract\\] \\[ ");str[i]=str[i].replace(/\\end\s*\{\s*abstract\s*\}/g," \\[endabstract\\] \\[ ");str[i]=str[i].replace(/\\begin\s*\{\s*(?!array|tabular)(\w+)\s*\}/g," \\[$1\\] \\[ ");str[i]=str[i].replace(/\\end\s*\{\s*(?!array|tabular)(\w+)\s*\}/g," \\[end$1\\] \\[ ");var sectionIndex=str[i].search(/\\section\s*\{\s*[\s\S]+\}/);while(sectionIndex>=0){str[i]=str[i].replace(/\\section\s*\{/," \\[section\\]");var delimcnt=1;for(var ii=sectionIndex;ii<str[i].length;ii++){if(str[i].charAt(ii)=="{"){delimcnt++};if(str[i].charAt(ii)=="}"){delimcnt--};if(delimcnt==0){str[i]=str[i].substring(0,ii)+"\\[ "+str[i].substring(ii+1,str[i].length);break;}};sectionIndex=str[i].search(/\\section\s*\{\s*[\s\S]+\}/);}
-  sectionIndex=str[i].search(/\\subsection\s*\{\s*[\s\S]+\}/);while(sectionIndex>=0){str[i]=str[i].replace(/\\subsection\s*\{/," \\[subsection\\]");var delimcnt=1;for(var ii=sectionIndex;ii<str[i].length;ii++){if(str[i].charAt(ii)=="{"){delimcnt++};if(str[i].charAt(ii)=="}"){delimcnt--};if(delimcnt==0){str[i]=str[i].substring(0,ii)+"\\[ "+str[i].substring(ii+1,str[i].length);break;}};sectionIndex=str[i].search(/\\subsection\s*\{\s*[\s\S]+\}/);}
-  sectionIndex=str[i].search(/\\subsubsection\s*\{\s*[\s\S]+\}/);while(sectionIndex>=0){str[i]=str[i].replace(/\\subsubsection\s*\{/," \\[subsubsection\\]");var delimcnt=1;for(var ii=sectionIndex;ii<str[i].length;ii++){if(str[i].charAt(ii)=="{"){delimcnt++};if(str[i].charAt(ii)=="}"){delimcnt--};if(delimcnt==0){str[i]=str[i].substring(0,ii)+"\\[ "+str[i].substring(ii+1,str[i].length);break;}};sectionIndex=str[i].search(/\\subsubsection\s*\{\s*[\s\S]+\}/);}
-  var CatToNextEven="";var strtmp=str[i].split("\\[");for(var j=0;j<strtmp.length;j++){if(j%2){var strtmparray=strtmp[j].split("\\]");switch(strtmparray[0]){case"section":var nodeTmp=document.createElement("H2");nodeTmp.className='section';sectionCntr++;for(var div in LaTeXCounter){LaTeXCounter[div]=0};var nodeAnchor=document.createElement("a");if(inAppendix){nodeAnchor.className='appendixsection';}else{nodeAnchor.className='section';}
-  var nodeNumString=makeNumberString("");var anchorSpan=document.createElement("span");anchorSpan.className="section";anchorSpan.style.display="none";anchorSpan.appendChild(document.createTextNode(nodeNumString));nodeAnchor.appendChild(anchorSpan);nodeTmp.appendChild(nodeAnchor);var nodeSpan=document.createElement("span");nodeSpan.className='section';nodeSpan.appendChild(document.createTextNode(nodeNumString+" "));nodeTmp.appendChild(nodeSpan);nodeTmp.appendChild(document.createTextNode(strtmparray[1]));newFrag.appendChild(nodeTmp);break;case"subsection":var nodeTmp=document.createElement("H3");nodeTmp.className='subsection';LaTeXCounter["subsection"]++;LaTeXCounter["subsubsection"]=0;var nodeAnchor=document.createElement("a");nodeAnchor.className='subsection';var nodeNumString=makeNumberString(LaTeXCounter["subsection"]);var anchorSpan=document.createElement("span");anchorSpan.className="subsection";anchorSpan.style.display="none";anchorSpan.appendChild(document.createTextNode(nodeNumString));nodeAnchor.appendChild(anchorSpan);nodeTmp.appendChild(nodeAnchor);var nodeSpan=document.createElement("span");nodeSpan.className='subsection';nodeSpan.appendChild(document.createTextNode(nodeNumString+". "));nodeTmp.appendChild(nodeSpan);nodeTmp.appendChild(document.createTextNode(strtmparray[1]));newFrag.appendChild(nodeTmp);break;case"subsubsection":var nodeTmp=document.createElement("H4");nodeTmp.className='subsubsection';LaTeXCounter["subsubsection"]++;var nodeAnchor=document.createElement("a");nodeAnchor.className='subsubsection';var nodeNumString=makeNumberString(LaTeXCounter["subsection"]+"."+LaTeXCounter["subsubsection"]);var anchorSpan=document.createElement("span");anchorSpan.className="subsubsection";anchorSpan.style.display="none";anchorSpan.appendChild(document.createTextNode(nodeNumString));nodeAnchor.appendChild(anchorSpan);nodeTmp.appendChild(nodeAnchor);var nodeSpan=document.createElement("span");nodeSpan.className='subsubsection';nodeSpan.appendChild(document.createTextNode(nodeNumString+". "));nodeTmp.appendChild(nodeSpan);nodeTmp.appendChild(document.createTextNode(strtmparray[1]));newFrag.appendChild(nodeTmp);break;case"href":var nodeTmp=document.createElement("a");nodeTmp.className='LaTeXMathML';nodeTmp.href=strtmparray[1];nodeTmp.appendChild(document.createTextNode(strtmparray[2]));newFrag.appendChild(nodeTmp);break;case"url":var nodeTmp=document.createElement("a");nodeTmp.className='LaTeXMathML';nodeTmp.href=strtmparray[1];nodeTmp.appendChild(document.createTextNode(strtmparray[1]));newFrag.appendChild(nodeTmp);break;case"figure":var nodeTmp=document.createElement("table");nodeTmp.className='figure';var FIGtbody=document.createElement("tbody");var FIGlbl=strtmparray[1].match(/\\label\s*\{\s*(\w+)\s*\}/);strtmparray[1]=strtmparray[1].replace(/\\label\s*\{\w+\}/g,"");var capIndex=strtmparray[1].search(/\\caption\s*\{[\s\S]+\}/);var FIGcap="";if(capIndex>=0){var tmp=strtmparray[1];var delimcnt=0;var capstart=-1;for(var pos=capIndex;pos<tmp.length;pos++){if(tmp.charAt(pos)=="{"){delimcnt++};if(tmp.charAt(pos)=="}"){delimcnt--};if(delimcnt==1&&capstart<0){capstart=pos+1};if(delimcnt==0&&capstart>0){capend=pos-1;FIGcap=tmp.substring(capstart,pos);break}}}
-  var FIGtr2=document.createElement("tr");var FIGtd2=document.createElement("td");FIGtd2.className="caption";var FIGanchor=document.createElement("a");FIGanchor.className="figure";if(FIGlbl!=null){FIGanchor.id=FIGlbl[1];}
-  LaTeXCounter["figure"]++;var fignmbr=makeNumberString(LaTeXCounter["figure"]);var anchorSpan=document.createElement("span");anchorSpan.className="figure";anchorSpan.style.display="none";anchorSpan.appendChild(document.createTextNode(fignmbr));FIGanchor.appendChild(anchorSpan);FIGtd2.appendChild(FIGanchor);var FIGspan=document.createElement("span");FIGspan.className="figure";FIGspan.appendChild(document.createTextNode("Figure "+fignmbr+". "));FIGtd2.appendChild(FIGspan);FIGtd2.appendChild(document.createTextNode(""+FIGcap));FIGtr2.appendChild(FIGtd2);FIGtbody.appendChild(FIGtr2);var IsSpecial=false;var FIGinfo=strtmparray[1].match(/\\includegraphics\s*\{([^\}]+)\}/);if(FIGinfo==null){FIGinfo=strtmparray[1].match(/\\includegraphics\s*\[[^\]]*\]\s*\{\s*([^\}]+)\s*\}/);}
-  if(FIGinfo==null){FIGinfo=strtmparray[1].match(/\\special\s*\{\s*([^\}]+)\}/);IsSpecial=true};if(FIGinfo!=null){var FIGtr1=document.createElement("tr");var FIGtd1=document.createElement("td");FIGtd1.className="image";var FIGimg=document.createElement("img");var FIGsrc=FIGinfo[1];FIGimg.src=FIGsrc;FIGimg.alt="Figure "+FIGsrc+" did not load";FIGimg.title="Figure "+fignmbr+". "+FIGcap;FIGimg.id="figure"+fignmbr;FIGtd1.appendChild(FIGimg);FIGtr1.appendChild(FIGtd1);FIGtbody.appendChild(FIGtr1);}
-  nodeTmp.appendChild(FIGtbody);newFrag.appendChild(nodeTmp);break;case"table":var nodeTmp=document.createElement("table");if(strtmparray[1].search(/\\centering/)>=0){nodeTmp.className='LaTeXtable centered';nodeTmp.align="center";}else{nodeTmp.className='LaTeXtable';};tableid++;nodeTmp.id="LaTeXtable"+tableid;var TABlbl=strtmparray[1].match(/\\label\s*\{\s*(\w+)\s*\}/);strtmparray[1]=strtmparray[1].replace(/\\label\s*\{\w+\}/g,"");var capIndex=strtmparray[1].search(/\\caption\s*\{[\s\S]+\}/);var TABcap="";if(capIndex>=0){var tmp=strtmparray[1];var delimcnt=0;var capstart=-1;for(var pos=capIndex;pos<tmp.length;pos++){if(tmp.charAt(pos)=="{"){delimcnt++};if(tmp.charAt(pos)=="}"){delimcnt--};if(delimcnt==1&&capstart<0){capstart=pos+1};if(delimcnt==0&&capstart>0){capend=pos-1;TABcap=tmp.substring(capstart,pos);break}}}
-  if(TABcap!=""){var TABtbody=document.createElement("tbody");var TABcaption=document.createElement("caption");TABcaption.className="LaTeXtable centered";var TABanchor=document.createElement("a");TABanchor.className="LaTeXtable";if(TABlbl!=null){TABanchor.id=TABlbl[1];}
-  LaTeXCounter["table"]++;var tabnmbr=makeNumberString(LaTeXCounter["table"]);var anchorSpan=document.createElement("span");anchorSpan.className="LaTeXtable";anchorSpan.style.display="none";anchorSpan.appendChild(document.createTextNode(tabnmbr));TABanchor.appendChild(anchorSpan);TABcaption.appendChild(TABanchor);var TABspan=document.createElement("span");TABspan.className="LaTeXtable";TABspan.appendChild(document.createTextNode("Table "+tabnmbr+". "));TABcaption.appendChild(TABspan);TABcaption.appendChild(document.createTextNode(""+TABcap));nodeTmp.appendChild(TABcaption);}
-  var TABinfo=strtmparray[1].match(/\\begin\s*\{\s*tabular\s*\}([\s\S]+)\\end\s*\{\s*tabular\s*\}/);if(TABinfo!=null){var TABtbody=document.createElement('tbody');var TABrow=null;var TABcell=null;var row=0;var col=0;var TABalign=TABinfo[1].match(/^\s*\{([^\}]+)\}/);TABinfo=TABinfo[1].replace(/^\s*\{[^\}]+\}/,"");TABinfo=TABinfo.replace(/\\hline/g,"");TABalign[1]=TABalign[1].replace(/\|/g,"");TABalign[1]=TABalign[1].replace(/\s/g,"");TABinfo=TABinfo.split("\\\\");for(row=0;row<TABinfo.length;row++){TABrow=document.createElement("tr");TABinfo[row]=TABinfo[row].split("&");for(col=0;col<TABinfo[row].length;col++){TABcell=document.createElement("td");switch(TABalign[1].charAt(col)){case"l":TABcell.align="left";break;case"c":TABcell.align="center";break;case"r":TABcell.align="right";break;default:TABcell.align="left";};TABcell.appendChild(document.createTextNode(TABinfo[row][col]));TABrow.appendChild(TABcell);}
-  TABtbody.appendChild(TABrow);}
-  nodeTmp.appendChild(TABtbody);}
-  newFrag.appendChild(nodeTmp);break;case"logicalbreak":var nodeTmp=document.createElement("p");nodeTmp.className=strtmparray[1];nodeTmp.appendChild(document.createTextNode("\u00A0"));newFrag.appendChild(nodeTmp);break;case"appendix":inAppendix=true;sectionCntr=0;break;case"alistitem":var EndDiv=document.createElement("div");EndDiv.className="endlistitem";newFrag.appendChild(EndDiv);var BegDiv=document.createElement("div");BegDiv.className="listitem";if(strtmparray[1]!=" "){var BegSpan=document.createElement("span");BegSpan.className="listitemmarker";var boldBegSpan=document.createElement("b");boldBegSpan.appendChild(document.createTextNode(strtmparray[1]+" "));BegSpan.appendChild(boldBegSpan);BegDiv.appendChild(BegSpan);}
-  newFrag.appendChild(BegDiv);break;case"br":newFrag.appendChild(document.createElement("br"));break;case"bibitem":newFrag.appendChild(document.createElement("br"));var nodeTmp=document.createElement("a");nodeTmp.className='bibitem';var nodeSpan=document.createElement("span");nodeSpan.className='bibitem';bibcntr++;var lbl=strtmparray[1].match(/\{\s*(\w+)\s*\}/);strtmparray[1]=strtmparray[1].replace(/\s*\{\s*\w+\s*\}/g,"");strtmparray[1]=strtmparray[1].replace(/^\s*\[/,"");strtmparray[1]=strtmparray[1].replace(/\s*\]$/,"");strtmparray[1]=strtmparray[1].replace(/^\s+|\s+$/g,"");if(lbl==null){biblist[bibcntr]="bibitem"+bibcntr}else{biblist[bibcntr]=lbl[1];};nodeTmp.name=biblist[bibcntr];nodeTmp.id=biblist[bibcntr];if(strtmparray[1]!=""){nodeSpan.appendChild(document.createTextNode(strtmparray[1]));}else{nodeSpan.appendChild(document.createTextNode("["+bibcntr+"]"));}
-  nodeTmp.appendChild(nodeSpan);newFrag.appendChild(nodeTmp);break;case"cite":var nodeTmp=document.createElement("a");nodeTmp.className='cite';nodeTmp.name='cite';nodeTmp.href="#"+strtmparray[1];newFrag.appendChild(nodeTmp);break;case"ref":var nodeTmp=document.createElement("a");nodeTmp.className='ref';nodeTmp.name='ref';nodeTmp.href="#"+strtmparray[1];newFrag.appendChild(nodeTmp);break;default:var nodeTmp=document.createElement("div");nodeTmp.className=strtmparray[0];if(IsCounter.test(strtmparray[0])){LaTeXCounter[strtmparray[0]]++;var nodeAnchor=document.createElement("a");nodeAnchor.className=strtmparray[0];var divnum=makeNumberString(LaTeXCounter[strtmparray[0]]);var anchorSpan=document.createElement("span");anchorSpan.className=strtmparray[0];anchorSpan.appendChild(document.createTextNode(divnum));anchorSpan.style.display="none";nodeAnchor.appendChild(anchorSpan);nodeTmp.appendChild(nodeAnchor);var nodeSpan=document.createElement("span");nodeSpan.className=strtmparray[0];nodeSpan.appendChild(document.createTextNode(strtmparray[1]+" "+divnum+". "));nodeTmp.appendChild(nodeSpan);}
-  if(isIE){if(strtmparray[0]==("thebibliography"||"abstract"||"keyword"||"proof")){var nodeSpan=document.createElement("span");nodeSpan.className=strtmparray[0];nodeSpan.appendChild(document.createTextNode(strtmparray[1]));nodeTmp.appendChild(nodeSpan);}}
-  if(strtmparray[0]=="endenumerate"||strtmparray[0]=="enditemize"||strtmparray[0]=="enddescription"){var endDiv=document.createElement("div");endDiv.className="endlistitem";newFrag.appendChild(endDiv);}
-  newFrag.appendChild(nodeTmp);if(strtmparray[0]=="enumerate"||strtmparray[0]=="itemize"||strtmparray[0]=="description"){var endDiv=document.createElement("div");endDiv.className="listitem";newFrag.appendChild(endDiv);}}}else{strtmp[j]=strtmp[j].replace(/\\\$/g,"<per>");strtmp[j]=strtmp[j].replace(/\$([^\$]+)\$/g," \\[$1\\[ ");strtmp[j]=strtmp[j].replace(/<per>/g,"\\$");strtmp[j]=strtmp[j].replace(/\\begin\s*\{\s*math\s*\}([\s\S]+?)\\end\s*\{\s*math\s*\}/g," \\[$1\\[ ");var strtmptmp=strtmp[j].split("\\[");for(var jjj=0;jjj<strtmptmp.length;jjj++){if(jjj%2){var nodeTmp=document.createElement("span");nodeTmp.className='inlinemath';nodeTmp.appendChild(document.createTextNode("$"+strtmptmp[jjj]+"$"));newFrag.appendChild(nodeTmp);}else{var TagIndex=strtmptmp[jjj].search(/\\\w+/);var tmpIndex=TagIndex;while(tmpIndex>-1){if(/^\\textcolor/.test(strtmptmp[jjj].substring(TagIndex,strtmptmp[jjj].length))){strtmptmp[jjj]=strtmptmp[jjj].replace(/\\textcolor\s*\{\s*(\w+)\s*\}\s*/," \\[textcolor\\]$1\\]|");}else{if(/^\\colorbox/.test(strtmptmp[jjj].substring(TagIndex,strtmptmp[jjj].length))){strtmptmp[jjj]=strtmptmp[jjj].replace(/\\colorbox\s*\{\s*(\w+)\s*\}\s*/," \\[colorbox\\]$1\\]|");}else{strtmptmp[jjj]=strtmptmp[jjj].substring(0,TagIndex)+strtmptmp[jjj].substring(TagIndex,strtmptmp[jjj].length).replace(/\\\s*(\w+)\s*/," \\[$1\\]|");}}
-  TagIndex+=strtmptmp[jjj].substring(TagIndex,strtmptmp[jjj].length).search(/\|/);TagIndex++;strtmptmp[jjj]=strtmptmp[jjj].replace(/\\\]\|/,"\\] ");if(strtmptmp[jjj].charAt(TagIndex)=="{"){strtmptmp[jjj]=strtmptmp[jjj].substring(0,TagIndex)+strtmptmp[jjj].substring(TagIndex+1,strtmptmp[jjj].length);var delimcnt=1;for(var kk=TagIndex;kk<strtmptmp[jjj].length;kk++){if(strtmptmp[jjj].charAt(kk)=="{"){delimcnt++};if(strtmptmp[jjj].charAt(kk)=="}"){delimcnt--};if(delimcnt==0){break;}}
-  strtmptmp[jjj]=strtmptmp[jjj].substring(0,kk)+"\\[ "+strtmptmp[jjj].substring(kk+1,strtmptmp[jjj].length);TagIndex=kk+3;}else{strtmptmp[jjj]=strtmptmp[jjj].substring(0,TagIndex)+"\\[ "+strtmptmp[jjj].substring(TagIndex+1,strtmptmp[jjj].length);TagIndex=TagIndex+3;}
-  if(TagIndex<strtmptmp[jjj].length){tmpIndex=strtmptmp[jjj].substring(TagIndex,strtmptmp[jjj].length).search(/\\\w+/);}
-  else{tmpIndex=-1};TagIndex+=tmpIndex;}
-  strtmptmp[jjj]=strtmptmp[jjj].replace(/\\\\\s*\\\\/g,"\\\\");strtmptmp[jjj]=strtmptmp[jjj].replace(/\\\\/g," \\[br\\] \\[ ");strtmptmp[jjj]=strtmptmp[jjj].replace(/\\label\s*\{\s*(\w+)\s*\}/g," \\[a\\]$1\\[ ");var strlbls=strtmptmp[jjj].split("\\[");for(var jj=0;jj<strlbls.length;jj++){if(jj%2){var strtmparray=strlbls[jj].split("\\]");switch(strtmparray[0]){case"textcolor":var nodeTmp=document.createElement("span");nodeTmp.className='LaTeXColor';if(IsColorName.test(strtmparray[1].toLowerCase())){nodeTmp.style.color=LaTeXColor[strtmparray[1].toLowerCase()];}else{nodeTmp.style.color=strtmparray[1];};nodeTmp.appendChild(document.createTextNode(strtmparray[2]));newFrag.appendChild(nodeTmp);break;case"colorbox":var nodeTmp=document.createElement("span");nodeTmp.className='LaTeXColor';if(IsColorName.test(strtmparray[1].toLowerCase())){nodeTmp.style.background=LaTeXColor[strtmparray[1].toLowerCase()];}else{nodeTmp.style.background=strtmparray[1];};nodeTmp.appendChild(document.createTextNode(strtmparray[2]));newFrag.appendChild(nodeTmp);break;case"br":newFrag.appendChild(document.createElement("br"));break;case"a":var nodeTmp=document.createElement("a");nodeTmp.className='LaTeXMathMLlabel';nodeTmp.id=strtmparray[1];nodeTmp.style.display="none";newFrag.appendChild(nodeTmp);break;default:var nodeTmp=document.createElement("span");nodeTmp.className=strtmparray[0];nodeTmp.appendChild(document.createTextNode(strtmparray[1]))
-  newFrag.appendChild(nodeTmp);}}else{newFrag.appendChild(document.createTextNode(strlbls[jj]));}}}}}}}};TheBody.parentNode.replaceChild(newFrag,TheBody);}}}
-  return TheBody;}
-  function LaTeXDivsAndRefs(thebody){var TheBody=thebody;var EndDivClass=null;var AllDivs=TheBody.getElementsByTagName("div");var lbl2id="";var lblnode=null;for(var i=AllDivs.length-1;i>=0;i--){EndDivClass=AllDivs[i].className.match(/end\w+/);if(EndDivClass!=null){EndDivClass=EndDivClass[0];var DivClass=EndDivClass.substring(3,EndDivClass.length);var EndDivNode=AllDivs[i];break;}}
-  while(EndDivClass!=null){var newFrag=document.createDocumentFragment();var RootNode=EndDivNode.parentNode;var ClassCount=1;while(EndDivNode.previousSibling!=null&&ClassCount>0){switch(EndDivNode.previousSibling.className){case EndDivClass:ClassCount++;newFrag.insertBefore(EndDivNode.previousSibling,newFrag.firstChild);break;case DivClass:if(EndDivNode.previousSibling.nodeName=="DIV"){ClassCount--;if(lbl2id!=""){EndDivNode.previousSibling.id=lbl2id;lbl2id=""}
-  if(ClassCount==0){RootNode=EndDivNode.previousSibling;}else{newFrag.insertBefore(EndDivNode.previousSibling,newFrag.firstChild);}};break;case'LaTeXMathMLlabel':lbl2id=EndDivNode.previousSibling.id;EndDivNode.parentNode.removeChild(EndDivNode.previousSibling);break;default:newFrag.insertBefore(EndDivNode.previousSibling,newFrag.firstChild);}}
-  RootNode.appendChild(newFrag);EndDivNode.parentNode.removeChild(EndDivNode);AllDivs=TheBody.getElementsByTagName("DIV");for(i=AllDivs.length-1;i>=0;i--){EndDivClass=AllDivs[i].className.match(/end\w+/);if(EndDivClass!=null){ClassCount=0;EndDivClass=EndDivClass[0];DivClass=EndDivClass.substring(3,EndDivClass.length);EndDivNode=AllDivs[i];RootNode=EndDivNode.parentNode;break;}}}
-  var AllDivs=TheBody.getElementsByTagName("div");var DIV2LI=null;for(var i=0;i<AllDivs.length;i++){if(AllDivs[i].className=="itemize"||AllDivs[i].className=="enumerate"||AllDivs[i].className=="description"){if(AllDivs[i].className=="itemize"){RootNode=document.createElement("UL");}else{RootNode=document.createElement("OL");}
-  RootNode.className='LaTeXMathML';if(AllDivs[i].hasChildNodes()){AllDivs[i].removeChild(AllDivs[i].firstChild)};while(AllDivs[i].hasChildNodes()){if(AllDivs[i].firstChild.hasChildNodes()){DIV2LI=document.createElement("LI");while(AllDivs[i].firstChild.hasChildNodes()){DIV2LI.appendChild(AllDivs[i].firstChild.firstChild);}
-  if(DIV2LI.firstChild.className=="listitemmarker"){DIV2LI.style.listStyleType="none";}
-  RootNode.appendChild(DIV2LI)}
-  AllDivs[i].removeChild(AllDivs[i].firstChild);}
-  AllDivs[i].appendChild(RootNode);}}
-  var AllAnchors=TheBody.getElementsByTagName("a");for(var i=0;i<AllAnchors.length;i++){if(AllAnchors[i].className=="ref"||AllAnchors[i].className=="cite"){var label=AllAnchors[i].href.match(/\#(\w+)/);if(label!=null){var labelNode=document.getElementById(label[1]);if(labelNode!=null){var TheSpans=labelNode.getElementsByTagName("SPAN");if(TheSpans!=null){var refNode=TheSpans[0].cloneNode(true);refNode.style.display="inline"
-  refNode.className=AllAnchors[i].className;AllAnchors[i].appendChild(refNode);}}}}}
-  return TheBody;}
-  var AMbody;var AMnoMathML=false,AMtranslated=false;function translate(spanclassAM){if(!AMtranslated){AMtranslated=true;AMinitSymbols();var LaTeXContainers=[];var AllContainers=document.getElementsByTagName('*');var ExtendName="";for(var k=0,l=0;k<AllContainers.length;k++){ExtendName=" "+AllContainers[k].className+" ";if(ExtendName.match(/\sLaTeX\s/)!=null){LaTeXContainers[l]=AllContainers[k];l++;}};if(LaTeXContainers.length>0){for(var m=0;m<LaTeXContainers.length;m++){AMbody=LaTeXContainers[m];try{AMbody=LaTeXDivsAndRefs(LaTeXpreProcess(AMbody));}catch(err){alert("Unknown Error: Defaulting to Original LaTeXMathML");}
-  if(AMbody.tagName=="PRE"){var PreChilds=document.createDocumentFragment();var DivChilds=document.createElement("DIV");while(AMbody.hasChildNodes()){DivChilds.appendChild(AMbody.firstChild);}
-  PreChilds.appendChild(DivChilds);AMbody.parentNode.replaceChild(PreChilds,AMbody);AMbody=DivChilds;}
-  AMprocessNode(AMbody,false,spanclassAM);}}else{AMbody=document.getElementsByTagName("body")[0];try{AMbody=LaTeXDivsAndRefs(LaTeXpreProcess(AMbody));}catch(err){alert("Unknown Error: Defaulting to Original LaTeXMathML");}
-  AMprocessNode(AMbody,false,spanclassAM);}}}
-  if(isIE){document.write("<object id=\"mathplayer\" classid=\"clsid:32F66A20-7614-11D4-BD11-00104BD3F987\"></object>");document.write("<?import namespace=\"m\" implementation=\"#mathplayer\"?>");}
-  function generic()
-  {translate();};if(typeof window.addEventListener!='undefined')
-  {window.addEventListener('load',generic,false);}
-  else if(typeof document.addEventListener!='undefined')
-  {document.addEventListener('load',generic,false);}
-  else if(typeof window.attachEvent!='undefined')
-  {window.attachEvent('onload',generic);}
-  else
-  {if(typeof window.onload=='function')
-  {var existing=onload;window.onload=function()
-  {existing();generic();};}
-  else
-  {window.onload=generic;}}
-  /*]]>*/
-  </script>
+  <script defer=""
+  src="https://cdn.jsdelivr.net/npm/mathjax@4/tex-chtml.js"
+  type="text/javascript"></script>
 </head>
 <body>
 <div class="layout">
@@ -254,7 +72,8 @@
 <div id="math" class="slide section level1">
 <h1>Math</h1>
 <ul class="incremental">
-<li><span class="LaTeX">$\frac{d}{dx}f(x)=\lim_{h\to 0}\frac{f(x+h)-f(x)}{h}$</span></li>
+<li><span class="math inline">\(\frac{d}{dx}f(x)=\lim_{h\to
+0}\frac{f(x+h)-f(x)}{h}\)</span></li>
 </ul>
 </div>
 </div>
diff --git a/test/s5-fragment.html b/test/s5-fragment.html
--- a/test/s5-fragment.html
+++ b/test/s5-fragment.html
@@ -5,5 +5,6 @@
 </ul>
 <h1 id="math">Math</h1>
 <ul>
-<li><span class="math inline">$\frac{d}{dx}f(x)=\lim_{h\to 0}\frac{f(x+h)-f(x)}{h}$</span></li>
+<li><span class="math inline">$\frac{d}{dx}f(x)=\lim_{h\to
+0}\frac{f(x+h)-f(x)}{h}$</span></li>
 </ul>
diff --git a/test/s5-inserts.html b/test/s5-inserts.html
--- a/test/s5-inserts.html
+++ b/test/s5-inserts.html
@@ -3,16 +3,33 @@
 <head>
   <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
   <meta http-equiv="Content-Style-Type" content="text/css" />
-  <meta name="generator" content="pandoc" />
+  <meta name="generator" content="pandoc " />
   <meta name="author" content="Sam Smith" />
   <meta name="author" content="Jen Jones" />
   <meta name="date" content="2006-07-15" />
   <title>My S5 Document</title>
   <style type="text/css">
-      code{white-space: pre-wrap;}
-      span.smallcaps{font-variant: small-caps;}
-      span.underline{text-decoration: underline;}
-      div.column{display: inline-block; vertical-align: top; width: 50%;}
+    /* Default styles provided by pandoc.
+    ** See https://pandoc.org/MANUAL.html#variables-for-html for config info.
+    */
+    span.smallcaps{font-variant: small-caps;}
+    div.columns{display: flex; gap: 1.5em;}
+    div.column{flex: auto;}
+    @media screen {
+    div.columns{gap: min(4vw, 1.5em);}
+    div.column{overflow-x: auto;}
+    }
+    div.hanging-indent{margin-left: 1.5em; text-indent: -1.5em;}
+    /* The extra [class] is a hack that increases specificity enough to
+       override a similar rule in reveal.js */
+    ul.task-list[class]{list-style: none;}
+    ul.task-list li input[type="checkbox"] {
+      font-size: inherit;
+      width: 0.8em;
+      margin: 0 0.8em 0.2em -1.6em;
+      vertical-align: middle;
+    }
+    .display.math{display: block; text-align: center; margin: 0.5rem auto;}
   </style>
   <link rel="stylesheet" href="main.css" type="text/css" />
   STUFF INSERTED
@@ -32,7 +49,8 @@
 </ul>
 <h1 id="math">Math</h1>
 <ul>
-<li><span class="math inline">$\frac{d}{dx}f(x)=\lim_{h\to 0}\frac{f(x+h)-f(x)}{h}$</span></li>
+<li><span class="math inline">$\frac{d}{dx}f(x)=\lim_{h\to
+0}\frac{f(x+h)-f(x)}{h}$</span></li>
 </ul>
 STUFF INSERTED
 </body>
diff --git a/test/tables-rstsubset.native b/test/tables-rstsubset.native
--- a/test/tables-rstsubset.native
+++ b/test/tables-rstsubset.native
@@ -1,114 +1,964 @@
-[Para [Str "Simple",Space,Str "table",Space,Str "with",Space,Str "caption:"]
-,Table [Str "Demonstration",Space,Str "of",Space,Str "simple",Space,Str "table",Space,Str "syntax."] [AlignDefault,AlignDefault,AlignDefault,AlignDefault] [0.1,8.75e-2,0.1125,0.125]
- [[Plain [Str "Right"]]
- ,[Plain [Str "Left"]]
- ,[Plain [Str "Center"]]
- ,[Plain [Str "Default"]]]
- [[[Plain [Str "12"]]
-  ,[Plain [Str "12"]]
-  ,[Plain [Str "12"]]
-  ,[Plain [Str "12"]]]
- ,[[Plain [Str "123"]]
-  ,[Plain [Str "123"]]
-  ,[Plain [Str "123"]]
-  ,[Plain [Str "123"]]]
- ,[[Plain [Str "1"]]
-  ,[Plain [Str "1"]]
-  ,[Plain [Str "1"]]
-  ,[Plain [Str "1"]]]]
-,Para [Str "Simple",Space,Str "table",Space,Str "without",Space,Str "caption:"]
-,Table [] [AlignDefault,AlignDefault,AlignDefault,AlignDefault] [0.1,8.75e-2,0.1125,0.125]
- [[Plain [Str "Right"]]
- ,[Plain [Str "Left"]]
- ,[Plain [Str "Center"]]
- ,[Plain [Str "Default"]]]
- [[[Plain [Str "12"]]
-  ,[Plain [Str "12"]]
-  ,[Plain [Str "12"]]
-  ,[Plain [Str "12"]]]
- ,[[Plain [Str "123"]]
-  ,[Plain [Str "123"]]
-  ,[Plain [Str "123"]]
-  ,[Plain [Str "123"]]]
- ,[[Plain [Str "1"]]
-  ,[Plain [Str "1"]]
-  ,[Plain [Str "1"]]
-  ,[Plain [Str "1"]]]]
-,Para [Str "Simple",Space,Str "table",Space,Str "indented",Space,Str "two",Space,Str "spaces:"]
-,Table [Str "Demonstration",Space,Str "of",Space,Str "simple",Space,Str "table",Space,Str "syntax."] [AlignDefault,AlignDefault,AlignDefault,AlignDefault] [0.1,8.75e-2,0.1125,0.125]
- [[Plain [Str "Right"]]
- ,[Plain [Str "Left"]]
- ,[Plain [Str "Center"]]
- ,[Plain [Str "Default"]]]
- [[[Plain [Str "12"]]
-  ,[Plain [Str "12"]]
-  ,[Plain [Str "12"]]
-  ,[Plain [Str "12"]]]
- ,[[Plain [Str "123"]]
-  ,[Plain [Str "123"]]
-  ,[Plain [Str "123"]]
-  ,[Plain [Str "123"]]]
- ,[[Plain [Str "1"]]
-  ,[Plain [Str "1"]]
-  ,[Plain [Str "1"]]
-  ,[Plain [Str "1"]]]]
-,Para [Str "Multiline",Space,Str "table",Space,Str "with",Space,Str "caption:"]
-,Table [Str "Here\8217s",Space,Str "the",Space,Str "caption.",Space,Str "It",Space,Str "may",Space,Str "span",Space,Str "multiple",Space,Str "lines."] [AlignDefault,AlignDefault,AlignDefault,AlignDefault] [0.1375,0.125,0.15,0.325]
- [[Plain [Str "Centered",SoftBreak,Str "Header"]]
- ,[Plain [Str "Left",SoftBreak,Str "Aligned"]]
- ,[Plain [Str "Right",SoftBreak,Str "Aligned"]]
- ,[Plain [Str "Default",Space,Str "aligned"]]]
- [[[Plain [Str "First"]]
-  ,[Plain [Str "row"]]
-  ,[Plain [Str "12.0"]]
-  ,[Plain [Str "Example",Space,Str "of",Space,Str "a",Space,Str "row",Space,Str "that",SoftBreak,Str "spans",Space,Str "multiple",Space,Str "lines."]]]
- ,[[Plain [Str "Second"]]
-  ,[Plain [Str "row"]]
-  ,[Plain [Str "5.0"]]
-  ,[Plain [Str "Here\8217s",Space,Str "another",Space,Str "one.",SoftBreak,Str "Note",Space,Str "the",Space,Str "blank",Space,Str "line",SoftBreak,Str "between",Space,Str "rows."]]]]
-,Para [Str "Multiline",Space,Str "table",Space,Str "without",Space,Str "caption:"]
-,Table [] [AlignDefault,AlignDefault,AlignDefault,AlignDefault] [0.1375,0.125,0.15,0.325]
- [[Plain [Str "Centered",SoftBreak,Str "Header"]]
- ,[Plain [Str "Left",SoftBreak,Str "Aligned"]]
- ,[Plain [Str "Right",SoftBreak,Str "Aligned"]]
- ,[Plain [Str "Default",Space,Str "aligned"]]]
- [[[Plain [Str "First"]]
-  ,[Plain [Str "row"]]
-  ,[Plain [Str "12.0"]]
-  ,[Plain [Str "Example",Space,Str "of",Space,Str "a",Space,Str "row",Space,Str "that",SoftBreak,Str "spans",Space,Str "multiple",Space,Str "lines."]]]
- ,[[Plain [Str "Second"]]
-  ,[Plain [Str "row"]]
-  ,[Plain [Str "5.0"]]
-  ,[Plain [Str "Here\8217s",Space,Str "another",Space,Str "one.",SoftBreak,Str "Note",Space,Str "the",Space,Str "blank",Space,Str "line",SoftBreak,Str "between",Space,Str "rows."]]]]
-,Para [Str "Table",Space,Str "without",Space,Str "column",Space,Str "headers:"]
-,Table [] [AlignDefault,AlignDefault,AlignDefault,AlignDefault] [7.5e-2,7.5e-2,7.5e-2,7.5e-2]
- [[]
- ,[]
- ,[]
- ,[]]
- [[[Plain [Str "12"]]
-  ,[Plain [Str "12"]]
-  ,[Plain [Str "12"]]
-  ,[Plain [Str "12"]]]
- ,[[Plain [Str "123"]]
-  ,[Plain [Str "123"]]
-  ,[Plain [Str "123"]]
-  ,[Plain [Str "123"]]]
- ,[[Plain [Str "1"]]
-  ,[Plain [Str "1"]]
-  ,[Plain [Str "1"]]
-  ,[Plain [Str "1"]]]]
-,Para [Str "Multiline",Space,Str "table",Space,Str "without",Space,Str "column",Space,Str "headers:"]
-,Table [] [AlignDefault,AlignDefault,AlignDefault,AlignDefault] [0.1375,0.125,0.15,0.325]
- [[]
- ,[]
- ,[]
- ,[]]
- [[[Plain [Str "First"]]
-  ,[Plain [Str "row"]]
-  ,[Plain [Str "12.0"]]
-  ,[Plain [Str "Example",Space,Str "of",Space,Str "a",Space,Str "row",Space,Str "that",SoftBreak,Str "spans",Space,Str "multiple",Space,Str "lines."]]]
- ,[[Plain [Str "Second"]]
-  ,[Plain [Str "row"]]
-  ,[Plain [Str "5.0"]]
-  ,[Plain [Str "Here\8217s",Space,Str "another",Space,Str "one.",SoftBreak,Str "Note",Space,Str "the",Space,Str "blank",Space,Str "line",SoftBreak,Str "between",Space,Str "rows."]]]]]
+[ Para
+    [ Str "Simple"
+    , Space
+    , Str "table"
+    , Space
+    , Str "with"
+    , Space
+    , Str "caption:"
+    ]
+, Table
+    ( "" , [] , [] )
+    (Caption
+       Nothing
+       [ Plain
+           [ Str "Demonstration"
+           , Space
+           , Str "of"
+           , Space
+           , Str "simple"
+           , Space
+           , Str "table"
+           , Space
+           , Str "syntax."
+           ]
+       ])
+    [ ( AlignDefault , ColWidthDefault )
+    , ( AlignDefault , ColWidthDefault )
+    , ( AlignDefault , ColWidthDefault )
+    , ( AlignDefault , ColWidthDefault )
+    ]
+    (TableHead
+       ( "" , [] , [] )
+       [ Row
+           ( "" , [] , [] )
+           [ Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "Right" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "Left" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "Center" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "Default" ] ]
+           ]
+       ])
+    [ TableBody
+        ( "" , [] , [] )
+        (RowHeadColumns 0)
+        []
+        [ Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "12" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "12" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "12" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "12" ] ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "123" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "123" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "123" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "123" ] ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "1" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "1" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "1" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "1" ] ]
+            ]
+        ]
+    ]
+    (TableFoot ( "" , [] , [] ) [])
+, Para
+    [ Str "Simple"
+    , Space
+    , Str "table"
+    , Space
+    , Str "without"
+    , Space
+    , Str "caption:"
+    ]
+, Table
+    ( "" , [] , [] )
+    (Caption Nothing [])
+    [ ( AlignDefault , ColWidthDefault )
+    , ( AlignDefault , ColWidthDefault )
+    , ( AlignDefault , ColWidthDefault )
+    , ( AlignDefault , ColWidthDefault )
+    ]
+    (TableHead
+       ( "" , [] , [] )
+       [ Row
+           ( "" , [] , [] )
+           [ Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "Right" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "Left" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "Center" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "Default" ] ]
+           ]
+       ])
+    [ TableBody
+        ( "" , [] , [] )
+        (RowHeadColumns 0)
+        []
+        [ Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "12" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "12" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "12" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "12" ] ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "123" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "123" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "123" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "123" ] ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "1" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "1" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "1" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "1" ] ]
+            ]
+        ]
+    ]
+    (TableFoot ( "" , [] , [] ) [])
+, Para
+    [ Str "Simple"
+    , Space
+    , Str "table"
+    , Space
+    , Str "indented"
+    , Space
+    , Str "two"
+    , Space
+    , Str "spaces:"
+    ]
+, Table
+    ( "" , [] , [] )
+    (Caption
+       Nothing
+       [ Plain
+           [ Str "Demonstration"
+           , Space
+           , Str "of"
+           , Space
+           , Str "simple"
+           , Space
+           , Str "table"
+           , Space
+           , Str "syntax."
+           ]
+       ])
+    [ ( AlignDefault , ColWidthDefault )
+    , ( AlignDefault , ColWidthDefault )
+    , ( AlignDefault , ColWidthDefault )
+    , ( AlignDefault , ColWidthDefault )
+    ]
+    (TableHead
+       ( "" , [] , [] )
+       [ Row
+           ( "" , [] , [] )
+           [ Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "Right" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "Left" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "Center" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "Default" ] ]
+           ]
+       ])
+    [ TableBody
+        ( "" , [] , [] )
+        (RowHeadColumns 0)
+        []
+        [ Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "12" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "12" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "12" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "12" ] ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "123" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "123" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "123" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "123" ] ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "1" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "1" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "1" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "1" ] ]
+            ]
+        ]
+    ]
+    (TableFoot ( "" , [] , [] ) [])
+, Para
+    [ Str "Multiline"
+    , Space
+    , Str "table"
+    , Space
+    , Str "with"
+    , Space
+    , Str "caption:"
+    ]
+, Table
+    ( "" , [] , [] )
+    (Caption
+       Nothing
+       [ Plain
+           [ Str "Here\8217s"
+           , Space
+           , Str "the"
+           , Space
+           , Str "caption."
+           , Space
+           , Str "It"
+           , Space
+           , Str "may"
+           , Space
+           , Str "span"
+           , Space
+           , Str "multiple"
+           , Space
+           , Str "lines."
+           ]
+       ])
+    [ ( AlignDefault , ColWidth 0.15 )
+    , ( AlignDefault , ColWidth 0.1375 )
+    , ( AlignDefault , ColWidth 0.1625 )
+    , ( AlignDefault , ColWidth 0.35 )
+    ]
+    (TableHead
+       ( "" , [] , [] )
+       [ Row
+           ( "" , [] , [] )
+           [ Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "Centered" , SoftBreak , Str "Header" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "Left" , SoftBreak , Str "Aligned" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "Right" , SoftBreak , Str "Aligned" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "Default" , Space , Str "aligned" ] ]
+           ]
+       ])
+    [ TableBody
+        ( "" , [] , [] )
+        (RowHeadColumns 0)
+        []
+        [ Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "First" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "row" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "12.0" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain
+                    [ Str "Example"
+                    , Space
+                    , Str "of"
+                    , Space
+                    , Str "a"
+                    , Space
+                    , Str "row"
+                    , Space
+                    , Str "that"
+                    , SoftBreak
+                    , Str "spans"
+                    , Space
+                    , Str "multiple"
+                    , Space
+                    , Str "lines."
+                    ]
+                ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "Second" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "row" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "5.0" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain
+                    [ Str "Here\8217s"
+                    , Space
+                    , Str "another"
+                    , Space
+                    , Str "one."
+                    , Space
+                    , Str "Note"
+                    , SoftBreak
+                    , Str "the"
+                    , Space
+                    , Str "blank"
+                    , Space
+                    , Str "line"
+                    , Space
+                    , Str "between"
+                    , SoftBreak
+                    , Str "rows."
+                    ]
+                ]
+            ]
+        ]
+    ]
+    (TableFoot ( "" , [] , [] ) [])
+, Para
+    [ Str "Multiline"
+    , Space
+    , Str "table"
+    , Space
+    , Str "without"
+    , Space
+    , Str "caption:"
+    ]
+, Table
+    ( "" , [] , [] )
+    (Caption Nothing [])
+    [ ( AlignDefault , ColWidth 0.15 )
+    , ( AlignDefault , ColWidth 0.1375 )
+    , ( AlignDefault , ColWidth 0.1625 )
+    , ( AlignDefault , ColWidth 0.35 )
+    ]
+    (TableHead
+       ( "" , [] , [] )
+       [ Row
+           ( "" , [] , [] )
+           [ Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "Centered" , SoftBreak , Str "Header" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "Left" , SoftBreak , Str "Aligned" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "Right" , SoftBreak , Str "Aligned" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "Default" , Space , Str "aligned" ] ]
+           ]
+       ])
+    [ TableBody
+        ( "" , [] , [] )
+        (RowHeadColumns 0)
+        []
+        [ Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "First" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "row" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "12.0" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain
+                    [ Str "Example"
+                    , Space
+                    , Str "of"
+                    , Space
+                    , Str "a"
+                    , Space
+                    , Str "row"
+                    , Space
+                    , Str "that"
+                    , SoftBreak
+                    , Str "spans"
+                    , Space
+                    , Str "multiple"
+                    , Space
+                    , Str "lines."
+                    ]
+                ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "Second" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "row" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "5.0" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain
+                    [ Str "Here\8217s"
+                    , Space
+                    , Str "another"
+                    , Space
+                    , Str "one."
+                    , Space
+                    , Str "Note"
+                    , SoftBreak
+                    , Str "the"
+                    , Space
+                    , Str "blank"
+                    , Space
+                    , Str "line"
+                    , Space
+                    , Str "between"
+                    , SoftBreak
+                    , Str "rows."
+                    ]
+                ]
+            ]
+        ]
+    ]
+    (TableFoot ( "" , [] , [] ) [])
+, Para
+    [ Str "Table"
+    , Space
+    , Str "without"
+    , Space
+    , Str "column"
+    , Space
+    , Str "headers:"
+    ]
+, Table
+    ( "" , [] , [] )
+    (Caption Nothing [])
+    [ ( AlignDefault , ColWidthDefault )
+    , ( AlignDefault , ColWidthDefault )
+    , ( AlignDefault , ColWidthDefault )
+    , ( AlignDefault , ColWidthDefault )
+    ]
+    (TableHead ( "" , [] , [] ) [])
+    [ TableBody
+        ( "" , [] , [] )
+        (RowHeadColumns 0)
+        []
+        [ Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "12" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "12" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "12" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "12" ] ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "123" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "123" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "123" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "123" ] ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "1" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "1" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "1" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "1" ] ]
+            ]
+        ]
+    ]
+    (TableFoot ( "" , [] , [] ) [])
+, Para
+    [ Str "Multiline"
+    , Space
+    , Str "table"
+    , Space
+    , Str "without"
+    , Space
+    , Str "column"
+    , Space
+    , Str "headers:"
+    ]
+, Table
+    ( "" , [] , [] )
+    (Caption Nothing [])
+    [ ( AlignDefault , ColWidth 0.15 )
+    , ( AlignDefault , ColWidth 0.1375 )
+    , ( AlignDefault , ColWidth 0.1625 )
+    , ( AlignDefault , ColWidth 0.35 )
+    ]
+    (TableHead ( "" , [] , [] ) [])
+    [ TableBody
+        ( "" , [] , [] )
+        (RowHeadColumns 0)
+        []
+        [ Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "First" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "row" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "12.0" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain
+                    [ Str "Example"
+                    , Space
+                    , Str "of"
+                    , Space
+                    , Str "a"
+                    , Space
+                    , Str "row"
+                    , Space
+                    , Str "that"
+                    , SoftBreak
+                    , Str "spans"
+                    , Space
+                    , Str "multiple"
+                    , Space
+                    , Str "lines."
+                    ]
+                ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "Second" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "row" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "5.0" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain
+                    [ Str "Here\8217s"
+                    , Space
+                    , Str "another"
+                    , Space
+                    , Str "one."
+                    , Space
+                    , Str "Note"
+                    , SoftBreak
+                    , Str "the"
+                    , Space
+                    , Str "blank"
+                    , Space
+                    , Str "line"
+                    , Space
+                    , Str "between"
+                    , SoftBreak
+                    , Str "rows."
+                    ]
+                ]
+            ]
+        ]
+    ]
+    (TableFoot ( "" , [] , [] ) [])
+]
diff --git a/test/tables.asciidoc b/test/tables.asciidoc
--- a/test/tables.asciidoc
+++ b/test/tables.asciidoc
@@ -2,66 +2,66 @@
 
 .Demonstration of simple table syntax.
 [cols=">,<,^,",options="header",]
-|============================
+|===
 |Right |Left |Center |Default
 |12 |12 |12 |12
 |123 |123 |123 |123
 |1 |1 |1 |1
-|============================
+|===
 
 Simple table without caption:
 
 [cols=">,<,^,",options="header",]
-|============================
+|===
 |Right |Left |Center |Default
 |12 |12 |12 |12
 |123 |123 |123 |123
 |1 |1 |1 |1
-|============================
+|===
 
 Simple table indented two spaces:
 
 .Demonstration of simple table syntax.
 [cols=">,<,^,",options="header",]
-|============================
+|===
 |Right |Left |Center |Default
 |12 |12 |12 |12
 |123 |123 |123 |123
 |1 |1 |1 |1
-|============================
+|===
 
 Multiline table with caption:
 
 .Here’s the caption. It may span multiple lines.
-[width="78%",cols="^21%,<17%,>20%,<42%",options="header",]
-|=======================================================================
+[width="80%",cols="^20%,<17%,>20%,<43%",options="header",]
+|===
 |Centered Header |Left Aligned |Right Aligned |Default aligned
 |First |row |12.0 |Example of a row that spans multiple lines.
 |Second |row |5.0 |Here’s another one. Note the blank line between rows.
-|=======================================================================
+|===
 
 Multiline table without caption:
 
-[width="78%",cols="^21%,<17%,>20%,<42%",options="header",]
-|=======================================================================
+[width="80%",cols="^20%,<17%,>20%,<43%",options="header",]
+|===
 |Centered Header |Left Aligned |Right Aligned |Default aligned
 |First |row |12.0 |Example of a row that spans multiple lines.
 |Second |row |5.0 |Here’s another one. Note the blank line between rows.
-|=======================================================================
+|===
 
 Table without column headers:
 
 [cols=">,<,^,>",]
-|==================
+|===
 |12 |12 |12 |12
 |123 |123 |123 |123
 |1 |1 |1 |1
-|==================
+|===
 
 Multiline table without column headers:
 
-[width="78%",cols="^21%,<17%,>20%,42%",]
-|=======================================================================
+[width="80%",cols="^20%,<17%,>20%,43%",]
+|===
 |First |row |12.0 |Example of a row that spans multiple lines.
 |Second |row |5.0 |Here’s another one. Note the blank line between rows.
-|=======================================================================
+|===
diff --git a/test/tables.asciidoc_legacy b/test/tables.asciidoc_legacy
new file mode 100644
--- /dev/null
+++ b/test/tables.asciidoc_legacy
@@ -0,0 +1,67 @@
+Simple table with caption:
+
+.Demonstration of simple table syntax.
+[cols=">,<,^,",options="header",]
+|===
+|Right |Left |Center |Default
+|12 |12 |12 |12
+|123 |123 |123 |123
+|1 |1 |1 |1
+|===
+
+Simple table without caption:
+
+[cols=">,<,^,",options="header",]
+|===
+|Right |Left |Center |Default
+|12 |12 |12 |12
+|123 |123 |123 |123
+|1 |1 |1 |1
+|===
+
+Simple table indented two spaces:
+
+.Demonstration of simple table syntax.
+[cols=">,<,^,",options="header",]
+|===
+|Right |Left |Center |Default
+|12 |12 |12 |12
+|123 |123 |123 |123
+|1 |1 |1 |1
+|===
+
+Multiline table with caption:
+
+.Here’s the caption. It may span multiple lines.
+[width="80%",cols="^20%,<17%,>20%,<43%",options="header",]
+|===
+|Centered Header |Left Aligned |Right Aligned |Default aligned
+|First |row |12.0 |Example of a row that spans multiple lines.
+|Second |row |5.0 |Here’s another one. Note the blank line between rows.
+|===
+
+Multiline table without caption:
+
+[width="80%",cols="^20%,<17%,>20%,<43%",options="header",]
+|===
+|Centered Header |Left Aligned |Right Aligned |Default aligned
+|First |row |12.0 |Example of a row that spans multiple lines.
+|Second |row |5.0 |Here’s another one. Note the blank line between rows.
+|===
+
+Table without column headers:
+
+[cols=">,<,^,>",]
+|===
+|12 |12 |12 |12
+|123 |123 |123 |123
+|1 |1 |1 |1
+|===
+
+Multiline table without column headers:
+
+[width="80%",cols="^20%,<17%,>20%,43%",]
+|===
+|First |row |12.0 |Example of a row that spans multiple lines.
+|Second |row |5.0 |Here’s another one. Note the blank line between rows.
+|===
diff --git a/test/tables.bbcode b/test/tables.bbcode
new file mode 100644
--- /dev/null
+++ b/test/tables.bbcode
@@ -0,0 +1,60 @@
+Simple table with caption:
+
+Demonstration of simple table syntax.
+[table]
+[tr][th]Right[/th][th]Left[/th][th]Center[/th][th]Default[/th][/tr]
+[tr][td]12[/td][td]12[/td][td]12[/td][td]12[/td][/tr]
+[tr][td]123[/td][td]123[/td][td]123[/td][td]123[/td][/tr]
+[tr][td]1[/td][td]1[/td][td]1[/td][td]1[/td][/tr]
+[/table]
+
+Simple table without caption:
+
+[table]
+[tr][th]Right[/th][th]Left[/th][th]Center[/th][th]Default[/th][/tr]
+[tr][td]12[/td][td]12[/td][td]12[/td][td]12[/td][/tr]
+[tr][td]123[/td][td]123[/td][td]123[/td][td]123[/td][/tr]
+[tr][td]1[/td][td]1[/td][td]1[/td][td]1[/td][/tr]
+[/table]
+
+Simple table indented two spaces:
+
+Demonstration of simple table syntax.
+[table]
+[tr][th]Right[/th][th]Left[/th][th]Center[/th][th]Default[/th][/tr]
+[tr][td]12[/td][td]12[/td][td]12[/td][td]12[/td][/tr]
+[tr][td]123[/td][td]123[/td][td]123[/td][td]123[/td][/tr]
+[tr][td]1[/td][td]1[/td][td]1[/td][td]1[/td][/tr]
+[/table]
+
+Multiline table with caption:
+
+Here's the caption. It may span multiple lines.
+[table]
+[tr][th]Centered Header[/th][th]Left Aligned[/th][th]Right Aligned[/th][th]Default aligned[/th][/tr]
+[tr][td]First[/td][td]row[/td][td]12.0[/td][td]Example of a row that spans multiple lines.[/td][/tr]
+[tr][td]Second[/td][td]row[/td][td]5.0[/td][td]Here's another one. Note the blank line between rows.[/td][/tr]
+[/table]
+
+Multiline table without caption:
+
+[table]
+[tr][th]Centered Header[/th][th]Left Aligned[/th][th]Right Aligned[/th][th]Default aligned[/th][/tr]
+[tr][td]First[/td][td]row[/td][td]12.0[/td][td]Example of a row that spans multiple lines.[/td][/tr]
+[tr][td]Second[/td][td]row[/td][td]5.0[/td][td]Here's another one. Note the blank line between rows.[/td][/tr]
+[/table]
+
+Table without column headers:
+
+[table]
+[tr][td]12[/td][td]12[/td][td]12[/td][td]12[/td][/tr]
+[tr][td]123[/td][td]123[/td][td]123[/td][td]123[/td][/tr]
+[tr][td]1[/td][td]1[/td][td]1[/td][td]1[/td][/tr]
+[/table]
+
+Multiline table without column headers:
+
+[table]
+[tr][td]First[/td][td]row[/td][td]12.0[/td][td]Example of a row that spans multiple lines.[/td][/tr]
+[tr][td]Second[/td][td]row[/td][td]5.0[/td][td]Here's another one. Note the blank line between rows.[/td][/tr]
+[/table]
diff --git a/test/tables.context b/test/tables.context
--- a/test/tables.context
+++ b/test/tables.context
@@ -1,175 +1,258 @@
 Simple table with caption:
 
-\placetable{Demonstration of simple table syntax.}
-\starttable[|r|l|c|l|]
-\HL
-\NC Right
-\NC Left
-\NC Center
-\NC Default
-\NC\AR
-\HL
-\NC 12
-\NC 12
-\NC 12
-\NC 12
-\NC\AR
-\NC 123
-\NC 123
-\NC 123
-\NC 123
-\NC\AR
-\NC 1
-\NC 1
-\NC 1
-\NC 1
-\NC\AR
-\HL
-\stoptable
+\startplacetable[title={Demonstration of simple table syntax.}]
+\startxtable
+\startxtablehead[head]
+\startxrowgroup[lastrow]
+\startxrow
+\startxcell[align=left] Right \stopxcell
+\startxcell[align=right] Left \stopxcell
+\startxcell[align=middle] Center \stopxcell
+\startxcell Default \stopxcell
+\stopxrow
+\stopxrowgroup
+\stopxtablehead
+\startxtablebody[body]
+\startxrow
+\startxcell[align=left] 12 \stopxcell
+\startxcell[align=right] 12 \stopxcell
+\startxcell[align=middle] 12 \stopxcell
+\startxcell 12 \stopxcell
+\stopxrow
+\startxrow
+\startxcell[align=left] 123 \stopxcell
+\startxcell[align=right] 123 \stopxcell
+\startxcell[align=middle] 123 \stopxcell
+\startxcell 123 \stopxcell
+\stopxrow
+\startxrowgroup[lastrow]
+\startxrow
+\startxcell[align=left] 1 \stopxcell
+\startxcell[align=right] 1 \stopxcell
+\startxcell[align=middle] 1 \stopxcell
+\startxcell 1 \stopxcell
+\stopxrow
+\stopxrowgroup
+\stopxtablebody
+\startxtablefoot[foot]
+\stopxtablefoot
+\stopxtable
+\stopplacetable
 
 Simple table without caption:
 
-\placetable[none]{}
-\starttable[|r|l|c|l|]
-\HL
-\NC Right
-\NC Left
-\NC Center
-\NC Default
-\NC\AR
-\HL
-\NC 12
-\NC 12
-\NC 12
-\NC 12
-\NC\AR
-\NC 123
-\NC 123
-\NC 123
-\NC 123
-\NC\AR
-\NC 1
-\NC 1
-\NC 1
-\NC 1
-\NC\AR
-\HL
-\stoptable
+\startplacetable[location=none]
+\startxtable
+\startxtablehead[head]
+\startxrowgroup[lastrow]
+\startxrow
+\startxcell[align=left] Right \stopxcell
+\startxcell[align=right] Left \stopxcell
+\startxcell[align=middle] Center \stopxcell
+\startxcell Default \stopxcell
+\stopxrow
+\stopxrowgroup
+\stopxtablehead
+\startxtablebody[body]
+\startxrow
+\startxcell[align=left] 12 \stopxcell
+\startxcell[align=right] 12 \stopxcell
+\startxcell[align=middle] 12 \stopxcell
+\startxcell 12 \stopxcell
+\stopxrow
+\startxrow
+\startxcell[align=left] 123 \stopxcell
+\startxcell[align=right] 123 \stopxcell
+\startxcell[align=middle] 123 \stopxcell
+\startxcell 123 \stopxcell
+\stopxrow
+\startxrowgroup[lastrow]
+\startxrow
+\startxcell[align=left] 1 \stopxcell
+\startxcell[align=right] 1 \stopxcell
+\startxcell[align=middle] 1 \stopxcell
+\startxcell 1 \stopxcell
+\stopxrow
+\stopxrowgroup
+\stopxtablebody
+\startxtablefoot[foot]
+\stopxtablefoot
+\stopxtable
+\stopplacetable
 
 Simple table indented two spaces:
 
-\placetable{Demonstration of simple table syntax.}
-\starttable[|r|l|c|l|]
-\HL
-\NC Right
-\NC Left
-\NC Center
-\NC Default
-\NC\AR
-\HL
-\NC 12
-\NC 12
-\NC 12
-\NC 12
-\NC\AR
-\NC 123
-\NC 123
-\NC 123
-\NC 123
-\NC\AR
-\NC 1
-\NC 1
-\NC 1
-\NC 1
-\NC\AR
-\HL
-\stoptable
+\startplacetable[title={Demonstration of simple table syntax.}]
+\startxtable
+\startxtablehead[head]
+\startxrowgroup[lastrow]
+\startxrow
+\startxcell[align=left] Right \stopxcell
+\startxcell[align=right] Left \stopxcell
+\startxcell[align=middle] Center \stopxcell
+\startxcell Default \stopxcell
+\stopxrow
+\stopxrowgroup
+\stopxtablehead
+\startxtablebody[body]
+\startxrow
+\startxcell[align=left] 12 \stopxcell
+\startxcell[align=right] 12 \stopxcell
+\startxcell[align=middle] 12 \stopxcell
+\startxcell 12 \stopxcell
+\stopxrow
+\startxrow
+\startxcell[align=left] 123 \stopxcell
+\startxcell[align=right] 123 \stopxcell
+\startxcell[align=middle] 123 \stopxcell
+\startxcell 123 \stopxcell
+\stopxrow
+\startxrowgroup[lastrow]
+\startxrow
+\startxcell[align=left] 1 \stopxcell
+\startxcell[align=right] 1 \stopxcell
+\startxcell[align=middle] 1 \stopxcell
+\startxcell 1 \stopxcell
+\stopxrow
+\stopxrowgroup
+\stopxtablebody
+\startxtablefoot[foot]
+\stopxtablefoot
+\stopxtable
+\stopplacetable
 
 Multiline table with caption:
 
-\placetable{Here's the caption. It may span multiple lines.}
-\starttable[|cp(0.15\textwidth)|lp(0.14\textwidth)|rp(0.16\textwidth)|lp(0.34\textwidth)|]
-\HL
-\NC Centered Header
-\NC Left Aligned
-\NC Right Aligned
-\NC Default aligned
-\NC\AR
-\HL
-\NC First
-\NC row
-\NC 12.0
-\NC Example of a row that spans multiple lines.
-\NC\AR
-\NC Second
-\NC row
-\NC 5.0
-\NC Here's another one. Note the blank line between rows.
-\NC\AR
-\HL
-\stoptable
+\startplacetable[title={Here's the caption. It may span multiple lines.}]
+\startxtable
+\startxtablehead[head]
+\startxrowgroup[lastrow]
+\startxrow
+\startxcell[align=middle,width={0.15\textwidth}] Centered Header \stopxcell
+\startxcell[align=right,width={0.14\textwidth}] Left Aligned \stopxcell
+\startxcell[align=left,width={0.16\textwidth}] Right Aligned \stopxcell
+\startxcell[align=right,width={0.35\textwidth}] Default aligned \stopxcell
+\stopxrow
+\stopxrowgroup
+\stopxtablehead
+\startxtablebody[body]
+\startxrow
+\startxcell[align=middle,width={0.15\textwidth}] First \stopxcell
+\startxcell[align=right,width={0.14\textwidth}] row \stopxcell
+\startxcell[align=left,width={0.16\textwidth}] 12.0 \stopxcell
+\startxcell[align=right,width={0.35\textwidth}] Example of a row that spans
+multiple lines. \stopxcell
+\stopxrow
+\startxrowgroup[lastrow]
+\startxrow
+\startxcell[align=middle,width={0.15\textwidth}] Second \stopxcell
+\startxcell[align=right,width={0.14\textwidth}] row \stopxcell
+\startxcell[align=left,width={0.16\textwidth}] 5.0 \stopxcell
+\startxcell[align=right,width={0.35\textwidth}] Here's another one. Note the
+blank line between rows. \stopxcell
+\stopxrow
+\stopxrowgroup
+\stopxtablebody
+\startxtablefoot[foot]
+\stopxtablefoot
+\stopxtable
+\stopplacetable
 
 Multiline table without caption:
 
-\placetable[none]{}
-\starttable[|cp(0.15\textwidth)|lp(0.14\textwidth)|rp(0.16\textwidth)|lp(0.34\textwidth)|]
-\HL
-\NC Centered Header
-\NC Left Aligned
-\NC Right Aligned
-\NC Default aligned
-\NC\AR
-\HL
-\NC First
-\NC row
-\NC 12.0
-\NC Example of a row that spans multiple lines.
-\NC\AR
-\NC Second
-\NC row
-\NC 5.0
-\NC Here's another one. Note the blank line between rows.
-\NC\AR
-\HL
-\stoptable
+\startplacetable[location=none]
+\startxtable
+\startxtablehead[head]
+\startxrowgroup[lastrow]
+\startxrow
+\startxcell[align=middle,width={0.15\textwidth}] Centered Header \stopxcell
+\startxcell[align=right,width={0.14\textwidth}] Left Aligned \stopxcell
+\startxcell[align=left,width={0.16\textwidth}] Right Aligned \stopxcell
+\startxcell[align=right,width={0.35\textwidth}] Default aligned \stopxcell
+\stopxrow
+\stopxrowgroup
+\stopxtablehead
+\startxtablebody[body]
+\startxrow
+\startxcell[align=middle,width={0.15\textwidth}] First \stopxcell
+\startxcell[align=right,width={0.14\textwidth}] row \stopxcell
+\startxcell[align=left,width={0.16\textwidth}] 12.0 \stopxcell
+\startxcell[align=right,width={0.35\textwidth}] Example of a row that spans
+multiple lines. \stopxcell
+\stopxrow
+\startxrowgroup[lastrow]
+\startxrow
+\startxcell[align=middle,width={0.15\textwidth}] Second \stopxcell
+\startxcell[align=right,width={0.14\textwidth}] row \stopxcell
+\startxcell[align=left,width={0.16\textwidth}] 5.0 \stopxcell
+\startxcell[align=right,width={0.35\textwidth}] Here's another one. Note the
+blank line between rows. \stopxcell
+\stopxrow
+\stopxrowgroup
+\stopxtablebody
+\startxtablefoot[foot]
+\stopxtablefoot
+\stopxtable
+\stopplacetable
 
 Table without column headers:
 
-\placetable[none]{}
-\starttable[|r|l|c|r|]
-\HL
-\NC 12
-\NC 12
-\NC 12
-\NC 12
-\NC\AR
-\NC 123
-\NC 123
-\NC 123
-\NC 123
-\NC\AR
-\NC 1
-\NC 1
-\NC 1
-\NC 1
-\NC\AR
-\HL
-\stoptable
+\startplacetable[location=none]
+\startxtable
+\startxtablehead[head]
+\stopxtablehead
+\startxtablebody[body]
+\startxrow
+\startxcell[align=left] 12 \stopxcell
+\startxcell[align=right] 12 \stopxcell
+\startxcell[align=middle] 12 \stopxcell
+\startxcell[align=left] 12 \stopxcell
+\stopxrow
+\startxrow
+\startxcell[align=left] 123 \stopxcell
+\startxcell[align=right] 123 \stopxcell
+\startxcell[align=middle] 123 \stopxcell
+\startxcell[align=left] 123 \stopxcell
+\stopxrow
+\startxrowgroup[lastrow]
+\startxrow
+\startxcell[align=left] 1 \stopxcell
+\startxcell[align=right] 1 \stopxcell
+\startxcell[align=middle] 1 \stopxcell
+\startxcell[align=left] 1 \stopxcell
+\stopxrow
+\stopxrowgroup
+\stopxtablebody
+\startxtablefoot[foot]
+\stopxtablefoot
+\stopxtable
+\stopplacetable
 
 Multiline table without column headers:
 
-\placetable[none]{}
-\starttable[|cp(0.15\textwidth)|lp(0.14\textwidth)|rp(0.16\textwidth)|lp(0.34\textwidth)|]
-\HL
-\NC First
-\NC row
-\NC 12.0
-\NC Example of a row that spans multiple lines.
-\NC\AR
-\NC Second
-\NC row
-\NC 5.0
-\NC Here's another one. Note the blank line between rows.
-\NC\AR
-\HL
-\stoptable
+\startplacetable[location=none]
+\startxtable
+\startxtablehead[head]
+\stopxtablehead
+\startxtablebody[body]
+\startxrow
+\startxcell[align=middle,width={0.15\textwidth}] First \stopxcell
+\startxcell[align=right,width={0.14\textwidth}] row \stopxcell
+\startxcell[align=left,width={0.16\textwidth}] 12.0 \stopxcell
+\startxcell[width={0.35\textwidth}] Example of a row that spans multiple
+lines. \stopxcell
+\stopxrow
+\startxrowgroup[lastrow]
+\startxrow
+\startxcell[align=middle,width={0.15\textwidth}] Second \stopxcell
+\startxcell[align=right,width={0.14\textwidth}] row \stopxcell
+\startxcell[align=left,width={0.16\textwidth}] 5.0 \stopxcell
+\startxcell[width={0.35\textwidth}] Here's another one. Note the blank line
+between rows. \stopxcell
+\stopxrow
+\stopxrowgroup
+\stopxtablebody
+\startxtablefoot[foot]
+\stopxtablefoot
+\stopxtable
+\stopplacetable
diff --git a/test/tables.custom b/test/tables.custom
deleted file mode 100644
--- a/test/tables.custom
+++ /dev/null
@@ -1,201 +0,0 @@
-<p>Simple table with caption:</p>
-
-<table>
-<caption>Demonstration of simple table syntax.</caption>
-<tr class="header">
-<th align="right">Right</th>
-<th align="left">Left</th>
-<th align="center">Center</th>
-<th align="left">Default</th>
-</tr>
-<tr class="odd">
-<td align="right">12</td>
-<td align="left">12</td>
-<td align="center">12</td>
-<td align="left">12</td>
-</tr>
-<tr class="even">
-<td align="right">123</td>
-<td align="left">123</td>
-<td align="center">123</td>
-<td align="left">123</td>
-</tr>
-<tr class="odd">
-<td align="right">1</td>
-<td align="left">1</td>
-<td align="center">1</td>
-<td align="left">1</td>
-</tr>
-</table
-
-<p>Simple table without caption:</p>
-
-<table>
-<tr class="header">
-<th align="right">Right</th>
-<th align="left">Left</th>
-<th align="center">Center</th>
-<th align="left">Default</th>
-</tr>
-<tr class="odd">
-<td align="right">12</td>
-<td align="left">12</td>
-<td align="center">12</td>
-<td align="left">12</td>
-</tr>
-<tr class="even">
-<td align="right">123</td>
-<td align="left">123</td>
-<td align="center">123</td>
-<td align="left">123</td>
-</tr>
-<tr class="odd">
-<td align="right">1</td>
-<td align="left">1</td>
-<td align="center">1</td>
-<td align="left">1</td>
-</tr>
-</table
-
-<p>Simple table indented two spaces:</p>
-
-<table>
-<caption>Demonstration of simple table syntax.</caption>
-<tr class="header">
-<th align="right">Right</th>
-<th align="left">Left</th>
-<th align="center">Center</th>
-<th align="left">Default</th>
-</tr>
-<tr class="odd">
-<td align="right">12</td>
-<td align="left">12</td>
-<td align="center">12</td>
-<td align="left">12</td>
-</tr>
-<tr class="even">
-<td align="right">123</td>
-<td align="left">123</td>
-<td align="center">123</td>
-<td align="left">123</td>
-</tr>
-<tr class="odd">
-<td align="right">1</td>
-<td align="left">1</td>
-<td align="center">1</td>
-<td align="left">1</td>
-</tr>
-</table
-
-<p>Multiline table with caption:</p>
-
-<table>
-<caption>Here’s the caption.
-It may span multiple lines.</caption>
-<col width="15%" />
-<col width="14%" />
-<col width="16%" />
-<col width="34%" />
-<tr class="header">
-<th align="center">Centered
-Header</th>
-<th align="left">Left
-Aligned</th>
-<th align="right">Right
-Aligned</th>
-<th align="left">Default aligned</th>
-</tr>
-<tr class="odd">
-<td align="center">First</td>
-<td align="left">row</td>
-<td align="right">12.0</td>
-<td align="left">Example of a row that spans
-multiple lines.</td>
-</tr>
-<tr class="even">
-<td align="center">Second</td>
-<td align="left">row</td>
-<td align="right">5.0</td>
-<td align="left">Here’s another one. Note
-the blank line between rows.</td>
-</tr>
-</table
-
-<p>Multiline table without caption:</p>
-
-<table>
-<col width="15%" />
-<col width="14%" />
-<col width="16%" />
-<col width="34%" />
-<tr class="header">
-<th align="center">Centered
-Header</th>
-<th align="left">Left
-Aligned</th>
-<th align="right">Right
-Aligned</th>
-<th align="left">Default aligned</th>
-</tr>
-<tr class="odd">
-<td align="center">First</td>
-<td align="left">row</td>
-<td align="right">12.0</td>
-<td align="left">Example of a row that spans
-multiple lines.</td>
-</tr>
-<tr class="even">
-<td align="center">Second</td>
-<td align="left">row</td>
-<td align="right">5.0</td>
-<td align="left">Here’s another one. Note
-the blank line between rows.</td>
-</tr>
-</table
-
-<p>Table without column headers:</p>
-
-<table>
-<tr class="odd">
-<td align="right">12</td>
-<td align="left">12</td>
-<td align="center">12</td>
-<td align="right">12</td>
-</tr>
-<tr class="even">
-<td align="right">123</td>
-<td align="left">123</td>
-<td align="center">123</td>
-<td align="right">123</td>
-</tr>
-<tr class="odd">
-<td align="right">1</td>
-<td align="left">1</td>
-<td align="center">1</td>
-<td align="right">1</td>
-</tr>
-</table
-
-<p>Multiline table without column headers:</p>
-
-<table>
-<col width="15%" />
-<col width="14%" />
-<col width="16%" />
-<col width="34%" />
-<tr class="odd">
-<td align="center">First</td>
-<td align="left">row</td>
-<td align="right">12.0</td>
-<td align="left">Example of a row that spans
-multiple lines.</td>
-</tr>
-<tr class="even">
-<td align="center">Second</td>
-<td align="left">row</td>
-<td align="right">5.0</td>
-<td align="left">Here’s another one. Note
-the blank line between rows.</td>
-</tr>
-</table
-
diff --git a/test/tables.djot b/test/tables.djot
new file mode 100644
--- /dev/null
+++ b/test/tables.djot
@@ -0,0 +1,56 @@
+Simple table with caption:
+
+| Right | Left | Center | Default |
+|------:|:-----|:------:|-------|
+|    12 | 12   |   12   | 12      |
+|   123 | 123  |  123   | 123     |
+|     1 | 1    |   1    | 1       |
+
+^ Demonstration of simple table syntax.
+
+Simple table without caption:
+
+| Right | Left | Center | Default |
+|------:|:-----|:------:|-------|
+|    12 | 12   |   12   | 12      |
+|   123 | 123  |  123   | 123     |
+|     1 | 1    |   1    | 1       |
+
+Simple table indented two spaces:
+
+| Right | Left | Center | Default |
+|------:|:-----|:------:|-------|
+|    12 | 12   |   12   | 12      |
+|   123 | 123  |  123   | 123     |
+|     1 | 1    |   1    | 1       |
+
+^ Demonstration of simple table syntax.
+
+Multiline table with caption:
+
+| Centered Header | Left Aligned | Right Aligned | Default aligned                                       |
+|:---------------:|:-------------|--------------:|:------------------------------------------------------|
+|      First      | row          |          12.0 | Example of a row that spans multiple lines.           |
+|     Second      | row          |           5.0 | Here's another one. Note the blank line between rows. |
+
+^ Here's the caption. It may span multiple lines.
+
+Multiline table without caption:
+
+| Centered Header | Left Aligned | Right Aligned | Default aligned                                       |
+|:---------------:|:-------------|--------------:|:------------------------------------------------------|
+|      First      | row          |          12.0 | Example of a row that spans multiple lines.           |
+|     Second      | row          |           5.0 | Here's another one. Note the blank line between rows. |
+
+Table without column headers:
+
+|----:|:----|:---:|----:|
+|  12 | 12  | 12  |  12 |
+| 123 | 123 | 123 | 123 |
+|   1 | 1   |  1  |   1 |
+
+Multiline table without column headers:
+
+|:------:|:----|-----:|-----------------------------------------------------|
+| First  | row | 12.0 | Example of a row that spans multiple lines.           |
+| Second | row |  5.0 | Here's another one. Note the blank line between rows. |
diff --git a/test/tables.docbook4 b/test/tables.docbook4
--- a/test/tables.docbook4
+++ b/test/tables.docbook4
@@ -2,9 +2,7 @@
   Simple table with caption:
 </para>
 <table>
-  <title>
-    Demonstration of simple table syntax.
-  </title>
+  <title>Demonstration of simple table syntax.</title>
   <tgroup cols="4">
     <colspec align="right" />
     <colspec align="left" />
@@ -147,9 +145,7 @@
   Simple table indented two spaces:
 </para>
 <table>
-  <title>
-    Demonstration of simple table syntax.
-  </title>
+  <title>Demonstration of simple table syntax.</title>
   <tgroup cols="4">
     <colspec align="right" />
     <colspec align="left" />
@@ -221,14 +217,12 @@
   Multiline table with caption:
 </para>
 <table>
-  <title>
-    Here’s the caption. It may span multiple lines.
-  </title>
+  <title>Here’s the caption. It may span multiple lines.</title>
   <tgroup cols="4">
     <colspec colwidth="15*" align="center" />
     <colspec colwidth="13*" align="left" />
     <colspec colwidth="16*" align="right" />
-    <colspec colwidth="33*" align="left" />
+    <colspec colwidth="35*" align="left" />
     <thead>
       <row>
         <entry>
@@ -285,7 +279,7 @@
     <colspec colwidth="15*" align="center" />
     <colspec colwidth="13*" align="left" />
     <colspec colwidth="16*" align="right" />
-    <colspec colwidth="33*" align="left" />
+    <colspec colwidth="35*" align="left" />
     <thead>
       <row>
         <entry>
@@ -397,7 +391,7 @@
     <colspec colwidth="15*" align="center" />
     <colspec colwidth="13*" align="left" />
     <colspec colwidth="16*" align="right" />
-    <colspec colwidth="33*" align="left" />
+    <colspec colwidth="35*" align="left" />
     <tbody>
       <row>
         <entry>
diff --git a/test/tables.docbook5 b/test/tables.docbook5
--- a/test/tables.docbook5
+++ b/test/tables.docbook5
@@ -2,9 +2,7 @@
   Simple table with caption:
 </para>
 <table>
-  <title>
-    Demonstration of simple table syntax.
-  </title>
+  <title>Demonstration of simple table syntax.</title>
   <tgroup cols="4">
     <colspec align="right" />
     <colspec align="left" />
@@ -147,9 +145,7 @@
   Simple table indented two spaces:
 </para>
 <table>
-  <title>
-    Demonstration of simple table syntax.
-  </title>
+  <title>Demonstration of simple table syntax.</title>
   <tgroup cols="4">
     <colspec align="right" />
     <colspec align="left" />
@@ -221,14 +217,12 @@
   Multiline table with caption:
 </para>
 <table>
-  <title>
-    Here’s the caption. It may span multiple lines.
-  </title>
+  <title>Here’s the caption. It may span multiple lines.</title>
   <tgroup cols="4">
     <colspec colwidth="15*" align="center" />
     <colspec colwidth="13*" align="left" />
     <colspec colwidth="16*" align="right" />
-    <colspec colwidth="33*" align="left" />
+    <colspec colwidth="35*" align="left" />
     <thead>
       <row>
         <entry>
@@ -285,7 +279,7 @@
     <colspec colwidth="15*" align="center" />
     <colspec colwidth="13*" align="left" />
     <colspec colwidth="16*" align="right" />
-    <colspec colwidth="33*" align="left" />
+    <colspec colwidth="35*" align="left" />
     <thead>
       <row>
         <entry>
@@ -397,7 +391,7 @@
     <colspec colwidth="15*" align="center" />
     <colspec colwidth="13*" align="left" />
     <colspec colwidth="16*" align="right" />
-    <colspec colwidth="33*" align="left" />
+    <colspec colwidth="35*" align="left" />
     <tbody>
       <row>
         <entry>
diff --git a/test/tables.dokuwiki b/test/tables.dokuwiki
--- a/test/tables.dokuwiki
+++ b/test/tables.dokuwiki
@@ -44,4 +44,3 @@
 
 |  First   |row  |  12.0|Example of a row that spans multiple lines.          |
 |  Second  |row  |   5.0|Here’s another one. Note the blank line between rows.|
-
diff --git a/test/tables.fb2 b/test/tables.fb2
--- a/test/tables.fb2
+++ b/test/tables.fb2
@@ -1,3 +1,15 @@
 <?xml version="1.0" encoding="UTF-8"?>
-<FictionBook xmlns="http://www.gribuser.ru/xml/fictionbook/2.0" xmlns:l="http://www.w3.org/1999/xlink"><description><title-info><genre>unrecognised</genre></title-info><document-info><program-used>pandoc</program-used></document-info></description><body><title><p /></title><section><p>Simple table with caption:</p><table><tr><th align="right">Right</th><th align="left">Left</th><th align="center">Center</th><th align="left">Default</th></tr><tr><td align="right">12</td><td align="left">12</td><td align="center">12</td><td align="left">12</td></tr><tr><td align="right">123</td><td align="left">123</td><td align="center">123</td><td align="left">123</td></tr><tr><td align="right">1</td><td align="left">1</td><td align="center">1</td><td align="left">1</td></tr></table><p><emphasis>Demonstration of simple table syntax.</emphasis></p><p>Simple table without caption:</p><table><tr><th align="right">Right</th><th align="left">Left</th><th align="center">Center</th><th align="left">Default</th></tr><tr><td align="right">12</td><td align="left">12</td><td align="center">12</td><td align="left">12</td></tr><tr><td align="right">123</td><td align="left">123</td><td align="center">123</td><td align="left">123</td></tr><tr><td align="right">1</td><td align="left">1</td><td align="center">1</td><td align="left">1</td></tr></table><p><emphasis /></p><p>Simple table indented two spaces:</p><table><tr><th align="right">Right</th><th align="left">Left</th><th align="center">Center</th><th align="left">Default</th></tr><tr><td align="right">12</td><td align="left">12</td><td align="center">12</td><td align="left">12</td></tr><tr><td align="right">123</td><td align="left">123</td><td align="center">123</td><td align="left">123</td></tr><tr><td align="right">1</td><td align="left">1</td><td align="center">1</td><td align="left">1</td></tr></table><p><emphasis>Demonstration of simple table syntax.</emphasis></p><p>Multiline table with caption:</p><table><tr><th align="center">Centered Header</th><th align="left">Left Aligned</th><th align="right">Right Aligned</th><th align="left">Default aligned</th></tr><tr><td align="center">First</td><td align="left">row</td><td align="right">12.0</td><td align="left">Example of a row that spans multiple lines.</td></tr><tr><td align="center">Second</td><td align="left">row</td><td align="right">5.0</td><td align="left">Here’s another one. Note the blank line between rows.</td></tr></table><p><emphasis>Here’s the caption. It may span multiple lines.</emphasis></p><p>Multiline table without caption:</p><table><tr><th align="center">Centered Header</th><th align="left">Left Aligned</th><th align="right">Right Aligned</th><th align="left">Default aligned</th></tr><tr><td align="center">First</td><td align="left">row</td><td align="right">12.0</td><td align="left">Example of a row that spans multiple lines.</td></tr><tr><td align="center">Second</td><td align="left">row</td><td align="right">5.0</td><td align="left">Here’s another one. Note the blank line between rows.</td></tr></table><p><emphasis /></p><p>Table without column headers:</p><table><tr><th align="right" /><th align="left" /><th align="center" /><th align="right" /></tr><tr><td align="right">12</td><td align="left">12</td><td align="center">12</td><td align="right">12</td></tr><tr><td align="right">123</td><td align="left">123</td><td align="center">123</td><td align="right">123</td></tr><tr><td align="right">1</td><td align="left">1</td><td align="center">1</td><td align="right">1</td></tr></table><p><emphasis /></p><p>Multiline table without column headers:</p><table><tr><th align="center" /><th align="left" /><th align="right" /><th align="left" /></tr><tr><td align="center">First</td><td align="left">row</td><td align="right">12.0</td><td align="left">Example of a row that spans multiple lines.</td></tr><tr><td align="center">Second</td><td align="left">row</td><td align="right">5.0</td><td align="left">Here’s another one. Note the blank line between rows.</td></tr></table><p><emphasis /></p></section></body></FictionBook>
-
+<FictionBook xmlns="http://www.gribuser.ru/xml/fictionbook/2.0" xmlns:l="http://www.w3.org/1999/xlink"><description><title-info><genre>unrecognised</genre></title-info><document-info><program-used>pandoc</program-used></document-info></description><body><title><p /></title><section><p>Simple table with caption:</p><table><tr><th align="right">Right</th><th align="left">Left</th><th align="center">Center</th><th align="left">Default</th></tr><tr><td align="right">12</td><td align="left">12</td><td align="center">12</td><td align="left">12</td></tr><tr><td align="right">123</td><td align="left">123</td><td align="center">123</td><td align="left">123</td></tr><tr><td align="right">1</td><td align="left">1</td><td align="center">1</td><td align="left">1</td></tr></table><p><emphasis>Demonstration of simple table syntax.</emphasis></p><p>Simple table without caption:</p><table><tr><th align="right">Right</th><th align="left">Left</th><th align="center">Center</th><th align="left">Default</th></tr><tr><td align="right">12</td><td align="left">12</td><td align="center">12</td><td align="left">12</td></tr><tr><td align="right">123</td><td align="left">123</td><td align="center">123</td><td align="left">123</td></tr><tr><td align="right">1</td><td align="left">1</td><td align="center">1</td><td align="left">1</td></tr></table><p><emphasis /></p><p>Simple table indented two spaces:</p><table><tr><th align="right">Right</th><th align="left">Left</th><th align="center">Center</th><th align="left">Default</th></tr><tr><td align="right">12</td><td align="left">12</td><td align="center">12</td><td align="left">12</td></tr><tr><td align="right">123</td><td align="left">123</td><td align="center">123</td><td align="left">123</td></tr><tr><td align="right">1</td><td align="left">1</td><td align="center">1</td><td align="left">1</td></tr></table><p><emphasis>Demonstration of simple table syntax.</emphasis></p><p>Multiline table with caption:</p><table><tr><th align="center">Centered
+Header</th><th align="left">Left
+Aligned</th><th align="right">Right
+Aligned</th><th align="left">Default aligned</th></tr><tr><td align="center">First</td><td align="left">row</td><td align="right">12.0</td><td align="left">Example of a row that spans
+multiple lines.</td></tr><tr><td align="center">Second</td><td align="left">row</td><td align="right">5.0</td><td align="left">Here’s another one. Note
+the blank line between rows.</td></tr></table><p><emphasis>Here’s the caption.
+It may span multiple lines.</emphasis></p><p>Multiline table without caption:</p><table><tr><th align="center">Centered
+Header</th><th align="left">Left
+Aligned</th><th align="right">Right
+Aligned</th><th align="left">Default aligned</th></tr><tr><td align="center">First</td><td align="left">row</td><td align="right">12.0</td><td align="left">Example of a row that spans
+multiple lines.</td></tr><tr><td align="center">Second</td><td align="left">row</td><td align="right">5.0</td><td align="left">Here’s another one. Note
+the blank line between rows.</td></tr></table><p><emphasis /></p><p>Table without column headers:</p><table><tr><td align="right">12</td><td align="left">12</td><td align="center">12</td><td align="right">12</td></tr><tr><td align="right">123</td><td align="left">123</td><td align="center">123</td><td align="right">123</td></tr><tr><td align="right">1</td><td align="left">1</td><td align="center">1</td><td align="right">1</td></tr></table><p><emphasis /></p><p>Multiline table without column headers:</p><table><tr><td align="center">First</td><td align="left">row</td><td align="right">12.0</td><td align="left">Example of a row that spans
+multiple lines.</td></tr><tr><td align="center">Second</td><td align="left">row</td><td align="right">5.0</td><td align="left">Here’s another one. Note
+the blank line between rows.</td></tr></table><p><emphasis /></p></section></body></FictionBook>
diff --git a/test/tables.haddock b/test/tables.haddock
--- a/test/tables.haddock
+++ b/test/tables.haddock
@@ -1,76 +1,90 @@
 Simple table with caption:
 
->     Right Left    Center  Default
->   ------- ------ -------- ---------
->        12 12        12    12
->       123 123      123    123
->         1 1         1     1
->
->   Demonstration of simple table syntax.
++-------+------+--------+---------+
+| Right | Left | Center | Default |
++======:+:=====+:======:+=========+
+| 12    | 12   | 12     | 12      |
++-------+------+--------+---------+
+| 123   | 123  | 123    | 123     |
++-------+------+--------+---------+
+| 1     | 1    | 1      | 1       |
++-------+------+--------+---------+
 
+Demonstration of simple table syntax.
+
 Simple table without caption:
 
->     Right Left    Center  Default
->   ------- ------ -------- ---------
->        12 12        12    12
->       123 123      123    123
->         1 1         1     1
++-------+------+--------+---------+
+| Right | Left | Center | Default |
++======:+:=====+:======:+=========+
+| 12    | 12   | 12     | 12      |
++-------+------+--------+---------+
+| 123   | 123  | 123    | 123     |
++-------+------+--------+---------+
+| 1     | 1    | 1      | 1       |
++-------+------+--------+---------+
 
 Simple table indented two spaces:
 
->     Right Left    Center  Default
->   ------- ------ -------- ---------
->        12 12        12    12
->       123 123      123    123
->         1 1         1     1
->
->   Demonstration of simple table syntax.
++-------+------+--------+---------+
+| Right | Left | Center | Default |
++======:+:=====+:======:+=========+
+| 12    | 12   | 12     | 12      |
++-------+------+--------+---------+
+| 123   | 123  | 123    | 123     |
++-------+------+--------+---------+
+| 1     | 1    | 1      | 1       |
++-------+------+--------+---------+
 
+Demonstration of simple table syntax.
+
 Multiline table with caption:
 
->   --------------------------------------------------------------
->    Centered   Left              Right Default aligned
->     Header    Aligned         Aligned 
->   ----------- ---------- ------------ --------------------------
->      First    row                12.0 Example of a row that
->                                       spans multiple lines.
->
->     Second    row                 5.0 Here’s another one. Note
->                                       the blank line between
->                                       rows.
->   --------------------------------------------------------------
->
->   Here’s the caption. It may span multiple lines.
++-----------+----------+------------+---------------------------+
+| Centered  | Left     | Right      | Default aligned           |
+| Header    | Aligned  | Aligned    |                           |
++:=========:+:=========+===========:+:==========================+
+| First     | row      | 12.0       | Example of a row that     |
+|           |          |            | spans multiple lines.     |
++-----------+----------+------------+---------------------------+
+| Second    | row      | 5.0        | Here’s another one. Note  |
+|           |          |            | the blank line between    |
+|           |          |            | rows.                     |
++-----------+----------+------------+---------------------------+
 
+Here’s the caption. It may span multiple lines.
+
 Multiline table without caption:
 
->   --------------------------------------------------------------
->    Centered   Left              Right Default aligned
->     Header    Aligned         Aligned 
->   ----------- ---------- ------------ --------------------------
->      First    row                12.0 Example of a row that
->                                       spans multiple lines.
->
->     Second    row                 5.0 Here’s another one. Note
->                                       the blank line between
->                                       rows.
->   --------------------------------------------------------------
++-----------+----------+------------+---------------------------+
+| Centered  | Left     | Right      | Default aligned           |
+| Header    | Aligned  | Aligned    |                           |
++:=========:+:=========+===========:+:==========================+
+| First     | row      | 12.0       | Example of a row that     |
+|           |          |            | spans multiple lines.     |
++-----------+----------+------------+---------------------------+
+| Second    | row      | 5.0        | Here’s another one. Note  |
+|           |          |            | the blank line between    |
+|           |          |            | rows.                     |
++-----------+----------+------------+---------------------------+
 
 Table without column headers:
 
->   ----- ----- ----- -----
->      12 12     12      12
->     123 123    123    123
->       1 1       1       1
->   ----- ----- ----- -----
++----:+:----+:---:+----:+
+| 12  | 12  | 12  | 12  |
++-----+-----+-----+-----+
+| 123 | 123 | 123 | 123 |
++-----+-----+-----+-----+
+| 1   | 1   | 1   | 1   |
++-----+-----+-----+-----+
 
 Multiline table without column headers:
 
->   ----------- ---------- ------------ --------------------------
->      First    row                12.0 Example of a row that
->                                       spans multiple lines.
->
->     Second    row                 5.0 Here’s another one. Note
->                                       the blank line between
->                                       rows.
->   ----------- ---------- ------------ --------------------------
++:---------:+:---------+-----------:+---------------------------+
+| First     | row      | 12.0       | Example of a row that     |
+|           |          |            | spans multiple lines.     |
++-----------+----------+------------+---------------------------+
+| Second    | row      | 5.0        | Here’s another one. Note  |
+|           |          |            | the blank line between    |
+|           |          |            | rows.                     |
++-----------+----------+------------+---------------------------+
diff --git a/test/tables.html4 b/test/tables.html4
--- a/test/tables.html4
+++ b/test/tables.html4
@@ -2,7 +2,7 @@
 <table>
 <caption>Demonstration of simple table syntax.</caption>
 <thead>
-<tr class="header">
+<tr>
 <th align="right">Right</th>
 <th align="left">Left</th>
 <th align="center">Center</th>
@@ -10,19 +10,19 @@
 </tr>
 </thead>
 <tbody>
-<tr class="odd">
+<tr>
 <td align="right">12</td>
 <td align="left">12</td>
 <td align="center">12</td>
 <td>12</td>
 </tr>
-<tr class="even">
+<tr>
 <td align="right">123</td>
 <td align="left">123</td>
 <td align="center">123</td>
 <td>123</td>
 </tr>
-<tr class="odd">
+<tr>
 <td align="right">1</td>
 <td align="left">1</td>
 <td align="center">1</td>
@@ -33,7 +33,7 @@
 <p>Simple table without caption:</p>
 <table>
 <thead>
-<tr class="header">
+<tr>
 <th align="right">Right</th>
 <th align="left">Left</th>
 <th align="center">Center</th>
@@ -41,19 +41,19 @@
 </tr>
 </thead>
 <tbody>
-<tr class="odd">
+<tr>
 <td align="right">12</td>
 <td align="left">12</td>
 <td align="center">12</td>
 <td>12</td>
 </tr>
-<tr class="even">
+<tr>
 <td align="right">123</td>
 <td align="left">123</td>
 <td align="center">123</td>
 <td>123</td>
 </tr>
-<tr class="odd">
+<tr>
 <td align="right">1</td>
 <td align="left">1</td>
 <td align="center">1</td>
@@ -65,7 +65,7 @@
 <table>
 <caption>Demonstration of simple table syntax.</caption>
 <thead>
-<tr class="header">
+<tr>
 <th align="right">Right</th>
 <th align="left">Left</th>
 <th align="center">Center</th>
@@ -73,19 +73,19 @@
 </tr>
 </thead>
 <tbody>
-<tr class="odd">
+<tr>
 <td align="right">12</td>
 <td align="left">12</td>
 <td align="center">12</td>
 <td>12</td>
 </tr>
-<tr class="even">
+<tr>
 <td align="right">123</td>
 <td align="left">123</td>
 <td align="center">123</td>
 <td>123</td>
 </tr>
-<tr class="odd">
+<tr>
 <td align="right">1</td>
 <td align="left">1</td>
 <td align="center">1</td>
@@ -94,16 +94,16 @@
 </tbody>
 </table>
 <p>Multiline table with caption:</p>
-<table style="width:79%;">
+<table style="width:80%;">
 <caption>Here’s the caption. It may span multiple lines.</caption>
 <colgroup>
 <col width="15%" />
 <col width="13%" />
 <col width="16%" />
-<col width="33%" />
+<col width="35%" />
 </colgroup>
 <thead>
-<tr class="header">
+<tr>
 <th align="center">Centered Header</th>
 <th align="left">Left Aligned</th>
 <th align="right">Right Aligned</th>
@@ -111,13 +111,13 @@
 </tr>
 </thead>
 <tbody>
-<tr class="odd">
+<tr>
 <td align="center">First</td>
 <td align="left">row</td>
 <td align="right">12.0</td>
 <td align="left">Example of a row that spans multiple lines.</td>
 </tr>
-<tr class="even">
+<tr>
 <td align="center">Second</td>
 <td align="left">row</td>
 <td align="right">5.0</td>
@@ -126,15 +126,15 @@
 </tbody>
 </table>
 <p>Multiline table without caption:</p>
-<table style="width:79%;">
+<table style="width:80%;">
 <colgroup>
 <col width="15%" />
 <col width="13%" />
 <col width="16%" />
-<col width="33%" />
+<col width="35%" />
 </colgroup>
 <thead>
-<tr class="header">
+<tr>
 <th align="center">Centered Header</th>
 <th align="left">Left Aligned</th>
 <th align="right">Right Aligned</th>
@@ -142,13 +142,13 @@
 </tr>
 </thead>
 <tbody>
-<tr class="odd">
+<tr>
 <td align="center">First</td>
 <td align="left">row</td>
 <td align="right">12.0</td>
 <td align="left">Example of a row that spans multiple lines.</td>
 </tr>
-<tr class="even">
+<tr>
 <td align="center">Second</td>
 <td align="left">row</td>
 <td align="right">5.0</td>
@@ -159,19 +159,19 @@
 <p>Table without column headers:</p>
 <table>
 <tbody>
-<tr class="odd">
+<tr>
 <td align="right">12</td>
 <td align="left">12</td>
 <td align="center">12</td>
 <td align="right">12</td>
 </tr>
-<tr class="even">
+<tr>
 <td align="right">123</td>
 <td align="left">123</td>
 <td align="center">123</td>
 <td align="right">123</td>
 </tr>
-<tr class="odd">
+<tr>
 <td align="right">1</td>
 <td align="left">1</td>
 <td align="center">1</td>
@@ -180,21 +180,21 @@
 </tbody>
 </table>
 <p>Multiline table without column headers:</p>
-<table style="width:79%;">
+<table style="width:80%;">
 <colgroup>
 <col width="15%" />
 <col width="13%" />
 <col width="16%" />
-<col width="33%" />
+<col width="35%" />
 </colgroup>
 <tbody>
-<tr class="odd">
+<tr>
 <td align="center">First</td>
 <td align="left">row</td>
 <td align="right">12.0</td>
 <td>Example of a row that spans multiple lines.</td>
 </tr>
-<tr class="even">
+<tr>
 <td align="center">Second</td>
 <td align="left">row</td>
 <td align="right">5.0</td>
diff --git a/test/tables.html5 b/test/tables.html5
--- a/test/tables.html5
+++ b/test/tables.html5
@@ -2,7 +2,7 @@
 <table>
 <caption>Demonstration of simple table syntax.</caption>
 <thead>
-<tr class="header">
+<tr>
 <th style="text-align: right;">Right</th>
 <th style="text-align: left;">Left</th>
 <th style="text-align: center;">Center</th>
@@ -10,19 +10,19 @@
 </tr>
 </thead>
 <tbody>
-<tr class="odd">
+<tr>
 <td style="text-align: right;">12</td>
 <td style="text-align: left;">12</td>
 <td style="text-align: center;">12</td>
 <td>12</td>
 </tr>
-<tr class="even">
+<tr>
 <td style="text-align: right;">123</td>
 <td style="text-align: left;">123</td>
 <td style="text-align: center;">123</td>
 <td>123</td>
 </tr>
-<tr class="odd">
+<tr>
 <td style="text-align: right;">1</td>
 <td style="text-align: left;">1</td>
 <td style="text-align: center;">1</td>
@@ -33,7 +33,7 @@
 <p>Simple table without caption:</p>
 <table>
 <thead>
-<tr class="header">
+<tr>
 <th style="text-align: right;">Right</th>
 <th style="text-align: left;">Left</th>
 <th style="text-align: center;">Center</th>
@@ -41,19 +41,19 @@
 </tr>
 </thead>
 <tbody>
-<tr class="odd">
+<tr>
 <td style="text-align: right;">12</td>
 <td style="text-align: left;">12</td>
 <td style="text-align: center;">12</td>
 <td>12</td>
 </tr>
-<tr class="even">
+<tr>
 <td style="text-align: right;">123</td>
 <td style="text-align: left;">123</td>
 <td style="text-align: center;">123</td>
 <td>123</td>
 </tr>
-<tr class="odd">
+<tr>
 <td style="text-align: right;">1</td>
 <td style="text-align: left;">1</td>
 <td style="text-align: center;">1</td>
@@ -65,7 +65,7 @@
 <table>
 <caption>Demonstration of simple table syntax.</caption>
 <thead>
-<tr class="header">
+<tr>
 <th style="text-align: right;">Right</th>
 <th style="text-align: left;">Left</th>
 <th style="text-align: center;">Center</th>
@@ -73,19 +73,19 @@
 </tr>
 </thead>
 <tbody>
-<tr class="odd">
+<tr>
 <td style="text-align: right;">12</td>
 <td style="text-align: left;">12</td>
 <td style="text-align: center;">12</td>
 <td>12</td>
 </tr>
-<tr class="even">
+<tr>
 <td style="text-align: right;">123</td>
 <td style="text-align: left;">123</td>
 <td style="text-align: center;">123</td>
 <td>123</td>
 </tr>
-<tr class="odd">
+<tr>
 <td style="text-align: right;">1</td>
 <td style="text-align: left;">1</td>
 <td style="text-align: center;">1</td>
@@ -94,16 +94,16 @@
 </tbody>
 </table>
 <p>Multiline table with caption:</p>
-<table style="width:79%;">
+<table style="width:80%;">
 <caption>Here’s the caption. It may span multiple lines.</caption>
 <colgroup>
 <col style="width: 15%" />
 <col style="width: 13%" />
 <col style="width: 16%" />
-<col style="width: 33%" />
+<col style="width: 35%" />
 </colgroup>
 <thead>
-<tr class="header">
+<tr>
 <th style="text-align: center;">Centered Header</th>
 <th style="text-align: left;">Left Aligned</th>
 <th style="text-align: right;">Right Aligned</th>
@@ -111,30 +111,31 @@
 </tr>
 </thead>
 <tbody>
-<tr class="odd">
+<tr>
 <td style="text-align: center;">First</td>
 <td style="text-align: left;">row</td>
 <td style="text-align: right;">12.0</td>
 <td style="text-align: left;">Example of a row that spans multiple lines.</td>
 </tr>
-<tr class="even">
+<tr>
 <td style="text-align: center;">Second</td>
 <td style="text-align: left;">row</td>
 <td style="text-align: right;">5.0</td>
-<td style="text-align: left;">Here’s another one. Note the blank line between rows.</td>
+<td style="text-align: left;">Here’s another one. Note the blank line between
+rows.</td>
 </tr>
 </tbody>
 </table>
 <p>Multiline table without caption:</p>
-<table style="width:79%;">
+<table style="width:80%;">
 <colgroup>
 <col style="width: 15%" />
 <col style="width: 13%" />
 <col style="width: 16%" />
-<col style="width: 33%" />
+<col style="width: 35%" />
 </colgroup>
 <thead>
-<tr class="header">
+<tr>
 <th style="text-align: center;">Centered Header</th>
 <th style="text-align: left;">Left Aligned</th>
 <th style="text-align: right;">Right Aligned</th>
@@ -142,36 +143,37 @@
 </tr>
 </thead>
 <tbody>
-<tr class="odd">
+<tr>
 <td style="text-align: center;">First</td>
 <td style="text-align: left;">row</td>
 <td style="text-align: right;">12.0</td>
 <td style="text-align: left;">Example of a row that spans multiple lines.</td>
 </tr>
-<tr class="even">
+<tr>
 <td style="text-align: center;">Second</td>
 <td style="text-align: left;">row</td>
 <td style="text-align: right;">5.0</td>
-<td style="text-align: left;">Here’s another one. Note the blank line between rows.</td>
+<td style="text-align: left;">Here’s another one. Note the blank line between
+rows.</td>
 </tr>
 </tbody>
 </table>
 <p>Table without column headers:</p>
 <table>
 <tbody>
-<tr class="odd">
+<tr>
 <td style="text-align: right;">12</td>
 <td style="text-align: left;">12</td>
 <td style="text-align: center;">12</td>
 <td style="text-align: right;">12</td>
 </tr>
-<tr class="even">
+<tr>
 <td style="text-align: right;">123</td>
 <td style="text-align: left;">123</td>
 <td style="text-align: center;">123</td>
 <td style="text-align: right;">123</td>
 </tr>
-<tr class="odd">
+<tr>
 <td style="text-align: right;">1</td>
 <td style="text-align: left;">1</td>
 <td style="text-align: center;">1</td>
@@ -180,21 +182,21 @@
 </tbody>
 </table>
 <p>Multiline table without column headers:</p>
-<table style="width:79%;">
+<table style="width:80%;">
 <colgroup>
 <col style="width: 15%" />
 <col style="width: 13%" />
 <col style="width: 16%" />
-<col style="width: 33%" />
+<col style="width: 35%" />
 </colgroup>
 <tbody>
-<tr class="odd">
+<tr>
 <td style="text-align: center;">First</td>
 <td style="text-align: left;">row</td>
 <td style="text-align: right;">12.0</td>
 <td>Example of a row that spans multiple lines.</td>
 </tr>
-<tr class="even">
+<tr>
 <td style="text-align: center;">Second</td>
 <td style="text-align: left;">row</td>
 <td style="text-align: right;">5.0</td>
diff --git a/test/tables.icml b/test/tables.icml
--- a/test/tables.icml
+++ b/test/tables.icml
@@ -395,7 +395,7 @@
   <Column Name="0" SingleColumnWidth="75.0" />
   <Column Name="1" SingleColumnWidth="68.75" />
   <Column Name="2" SingleColumnWidth="81.25" />
-  <Column Name="3" SingleColumnWidth="168.75" />
+  <Column Name="3" SingleColumnWidth="175.0" />
   <Cell Name="0:0" AppliedCellStyle="CellStyle/Cell">
     <ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/TablePar &gt; TableHeader &gt; CenterAlign">
       <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
@@ -497,7 +497,7 @@
   <Column Name="0" SingleColumnWidth="75.0" />
   <Column Name="1" SingleColumnWidth="68.75" />
   <Column Name="2" SingleColumnWidth="81.25" />
-  <Column Name="3" SingleColumnWidth="168.75" />
+  <Column Name="3" SingleColumnWidth="175.0" />
   <Cell Name="0:0" AppliedCellStyle="CellStyle/Cell">
     <ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/TablePar &gt; TableHeader &gt; CenterAlign">
       <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
@@ -695,7 +695,7 @@
   <Column Name="0" SingleColumnWidth="75.0" />
   <Column Name="1" SingleColumnWidth="68.75" />
   <Column Name="2" SingleColumnWidth="81.25" />
-  <Column Name="3" SingleColumnWidth="168.75" />
+  <Column Name="3" SingleColumnWidth="175.0" />
   <Cell Name="0:0" AppliedCellStyle="CellStyle/Cell">
     <ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/TablePar &gt; CenterAlign">
       <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
diff --git a/test/tables.jats b/test/tables.jats
deleted file mode 100644
--- a/test/tables.jats
+++ /dev/null
@@ -1,430 +0,0 @@
-<p>
-  Simple table with caption:
-</p>
-<table-wrap>
-  <caption>
-    <p>
-      Demonstration of simple table syntax.
-    </p>
-  </caption>
-  <table>
-    <col align="right" />
-    <col align="left" />
-    <col align="center" />
-    <col align="left" />
-    <thead>
-      <tr>
-        <th>
-          Right
-        </th>
-        <th>
-          Left
-        </th>
-        <th>
-          Center
-        </th>
-        <th>
-          Default
-        </th>
-      </tr>
-    </thead>
-    <tbody>
-      <tr>
-        <td>
-          12
-        </td>
-        <td>
-          12
-        </td>
-        <td>
-          12
-        </td>
-        <td>
-          12
-        </td>
-      </tr>
-      <tr>
-        <td>
-          123
-        </td>
-        <td>
-          123
-        </td>
-        <td>
-          123
-        </td>
-        <td>
-          123
-        </td>
-      </tr>
-      <tr>
-        <td>
-          1
-        </td>
-        <td>
-          1
-        </td>
-        <td>
-          1
-        </td>
-        <td>
-          1
-        </td>
-      </tr>
-    </tbody>
-  </table>
-</table-wrap>
-<p>
-  Simple table without caption:
-</p>
-<table>
-  <col align="right" />
-  <col align="left" />
-  <col align="center" />
-  <col align="left" />
-  <thead>
-    <tr>
-      <th>
-        Right
-      </th>
-      <th>
-        Left
-      </th>
-      <th>
-        Center
-      </th>
-      <th>
-        Default
-      </th>
-    </tr>
-  </thead>
-  <tbody>
-    <tr>
-      <td>
-        12
-      </td>
-      <td>
-        12
-      </td>
-      <td>
-        12
-      </td>
-      <td>
-        12
-      </td>
-    </tr>
-    <tr>
-      <td>
-        123
-      </td>
-      <td>
-        123
-      </td>
-      <td>
-        123
-      </td>
-      <td>
-        123
-      </td>
-    </tr>
-    <tr>
-      <td>
-        1
-      </td>
-      <td>
-        1
-      </td>
-      <td>
-        1
-      </td>
-      <td>
-        1
-      </td>
-    </tr>
-  </tbody>
-</table>
-<p>
-  Simple table indented two spaces:
-</p>
-<table-wrap>
-  <caption>
-    <p>
-      Demonstration of simple table syntax.
-    </p>
-  </caption>
-  <table>
-    <col align="right" />
-    <col align="left" />
-    <col align="center" />
-    <col align="left" />
-    <thead>
-      <tr>
-        <th>
-          Right
-        </th>
-        <th>
-          Left
-        </th>
-        <th>
-          Center
-        </th>
-        <th>
-          Default
-        </th>
-      </tr>
-    </thead>
-    <tbody>
-      <tr>
-        <td>
-          12
-        </td>
-        <td>
-          12
-        </td>
-        <td>
-          12
-        </td>
-        <td>
-          12
-        </td>
-      </tr>
-      <tr>
-        <td>
-          123
-        </td>
-        <td>
-          123
-        </td>
-        <td>
-          123
-        </td>
-        <td>
-          123
-        </td>
-      </tr>
-      <tr>
-        <td>
-          1
-        </td>
-        <td>
-          1
-        </td>
-        <td>
-          1
-        </td>
-        <td>
-          1
-        </td>
-      </tr>
-    </tbody>
-  </table>
-</table-wrap>
-<p>
-  Multiline table with caption:
-</p>
-<table-wrap>
-  <caption>
-    <p>
-      Here’s the caption. It may span multiple lines.
-    </p>
-  </caption>
-  <table>
-    <col width="15*" align="center" />
-    <col width="13*" align="left" />
-    <col width="16*" align="right" />
-    <col width="33*" align="left" />
-    <thead>
-      <tr>
-        <th>
-          Centered Header
-        </th>
-        <th>
-          Left Aligned
-        </th>
-        <th>
-          Right Aligned
-        </th>
-        <th>
-          Default aligned
-        </th>
-      </tr>
-    </thead>
-    <tbody>
-      <tr>
-        <td>
-          First
-        </td>
-        <td>
-          row
-        </td>
-        <td>
-          12.0
-        </td>
-        <td>
-          Example of a row that spans multiple lines.
-        </td>
-      </tr>
-      <tr>
-        <td>
-          Second
-        </td>
-        <td>
-          row
-        </td>
-        <td>
-          5.0
-        </td>
-        <td>
-          Here’s another one. Note the blank line between rows.
-        </td>
-      </tr>
-    </tbody>
-  </table>
-</table-wrap>
-<p>
-  Multiline table without caption:
-</p>
-<table>
-  <col width="15*" align="center" />
-  <col width="13*" align="left" />
-  <col width="16*" align="right" />
-  <col width="33*" align="left" />
-  <thead>
-    <tr>
-      <th>
-        Centered Header
-      </th>
-      <th>
-        Left Aligned
-      </th>
-      <th>
-        Right Aligned
-      </th>
-      <th>
-        Default aligned
-      </th>
-    </tr>
-  </thead>
-  <tbody>
-    <tr>
-      <td>
-        First
-      </td>
-      <td>
-        row
-      </td>
-      <td>
-        12.0
-      </td>
-      <td>
-        Example of a row that spans multiple lines.
-      </td>
-    </tr>
-    <tr>
-      <td>
-        Second
-      </td>
-      <td>
-        row
-      </td>
-      <td>
-        5.0
-      </td>
-      <td>
-        Here’s another one. Note the blank line between rows.
-      </td>
-    </tr>
-  </tbody>
-</table>
-<p>
-  Table without column headers:
-</p>
-<table>
-  <col align="right" />
-  <col align="left" />
-  <col align="center" />
-  <col align="right" />
-  <tbody>
-    <tr>
-      <td>
-        12
-      </td>
-      <td>
-        12
-      </td>
-      <td>
-        12
-      </td>
-      <td>
-        12
-      </td>
-    </tr>
-    <tr>
-      <td>
-        123
-      </td>
-      <td>
-        123
-      </td>
-      <td>
-        123
-      </td>
-      <td>
-        123
-      </td>
-    </tr>
-    <tr>
-      <td>
-        1
-      </td>
-      <td>
-        1
-      </td>
-      <td>
-        1
-      </td>
-      <td>
-        1
-      </td>
-    </tr>
-  </tbody>
-</table>
-<p>
-  Multiline table without column headers:
-</p>
-<table>
-  <col width="15*" align="center" />
-  <col width="13*" align="left" />
-  <col width="16*" align="right" />
-  <col width="33*" align="left" />
-  <tbody>
-    <tr>
-      <td>
-        First
-      </td>
-      <td>
-        row
-      </td>
-      <td>
-        12.0
-      </td>
-      <td>
-        Example of a row that spans multiple lines.
-      </td>
-    </tr>
-    <tr>
-      <td>
-        Second
-      </td>
-      <td>
-        row
-      </td>
-      <td>
-        5.0
-      </td>
-      <td>
-        Here’s another one. Note the blank line between rows.
-      </td>
-    </tr>
-  </tbody>
-</table>
diff --git a/test/tables.jats_archiving b/test/tables.jats_archiving
new file mode 100644
--- /dev/null
+++ b/test/tables.jats_archiving
@@ -0,0 +1,226 @@
+<p>Simple table with caption:</p>
+<table-wrap>
+  <caption>
+    <p>Demonstration of simple table syntax.</p>
+  </caption>
+  <table>
+    <thead>
+      <tr>
+        <th align="right">Right</th>
+        <th align="left">Left</th>
+        <th align="center">Center</th>
+        <th>Default</th>
+      </tr>
+    </thead>
+    <tbody>
+      <tr>
+        <td align="right">12</td>
+        <td align="left">12</td>
+        <td align="center">12</td>
+        <td>12</td>
+      </tr>
+      <tr>
+        <td align="right">123</td>
+        <td align="left">123</td>
+        <td align="center">123</td>
+        <td>123</td>
+      </tr>
+      <tr>
+        <td align="right">1</td>
+        <td align="left">1</td>
+        <td align="center">1</td>
+        <td>1</td>
+      </tr>
+    </tbody>
+  </table>
+</table-wrap>
+<p>Simple table without caption:</p>
+<table-wrap>
+  <table>
+    <thead>
+      <tr>
+        <th align="right">Right</th>
+        <th align="left">Left</th>
+        <th align="center">Center</th>
+        <th>Default</th>
+      </tr>
+    </thead>
+    <tbody>
+      <tr>
+        <td align="right">12</td>
+        <td align="left">12</td>
+        <td align="center">12</td>
+        <td>12</td>
+      </tr>
+      <tr>
+        <td align="right">123</td>
+        <td align="left">123</td>
+        <td align="center">123</td>
+        <td>123</td>
+      </tr>
+      <tr>
+        <td align="right">1</td>
+        <td align="left">1</td>
+        <td align="center">1</td>
+        <td>1</td>
+      </tr>
+    </tbody>
+  </table>
+</table-wrap>
+<p>Simple table indented two spaces:</p>
+<table-wrap>
+  <caption>
+    <p>Demonstration of simple table syntax.</p>
+  </caption>
+  <table>
+    <thead>
+      <tr>
+        <th align="right">Right</th>
+        <th align="left">Left</th>
+        <th align="center">Center</th>
+        <th>Default</th>
+      </tr>
+    </thead>
+    <tbody>
+      <tr>
+        <td align="right">12</td>
+        <td align="left">12</td>
+        <td align="center">12</td>
+        <td>12</td>
+      </tr>
+      <tr>
+        <td align="right">123</td>
+        <td align="left">123</td>
+        <td align="center">123</td>
+        <td>123</td>
+      </tr>
+      <tr>
+        <td align="right">1</td>
+        <td align="left">1</td>
+        <td align="center">1</td>
+        <td>1</td>
+      </tr>
+    </tbody>
+  </table>
+</table-wrap>
+<p>Multiline table with caption:</p>
+<table-wrap>
+  <caption>
+    <p>Here’s the caption. It may span multiple lines.</p>
+  </caption>
+  <table>
+    <colgroup>
+      <col width="15%" />
+      <col width="14%" />
+      <col width="16%" />
+      <col width="35%" />
+    </colgroup>
+    <thead>
+      <tr>
+        <th align="center">Centered Header</th>
+        <th align="left">Left Aligned</th>
+        <th align="right">Right Aligned</th>
+        <th align="left">Default aligned</th>
+      </tr>
+    </thead>
+    <tbody>
+      <tr>
+        <td align="center">First</td>
+        <td align="left">row</td>
+        <td align="right">12.0</td>
+        <td align="left">Example of a row that spans multiple lines.</td>
+      </tr>
+      <tr>
+        <td align="center">Second</td>
+        <td align="left">row</td>
+        <td align="right">5.0</td>
+        <td align="left">Here’s another one. Note the blank line between
+        rows.</td>
+      </tr>
+    </tbody>
+  </table>
+</table-wrap>
+<p>Multiline table without caption:</p>
+<table-wrap>
+  <table>
+    <colgroup>
+      <col width="15%" />
+      <col width="14%" />
+      <col width="16%" />
+      <col width="35%" />
+    </colgroup>
+    <thead>
+      <tr>
+        <th align="center">Centered Header</th>
+        <th align="left">Left Aligned</th>
+        <th align="right">Right Aligned</th>
+        <th align="left">Default aligned</th>
+      </tr>
+    </thead>
+    <tbody>
+      <tr>
+        <td align="center">First</td>
+        <td align="left">row</td>
+        <td align="right">12.0</td>
+        <td align="left">Example of a row that spans multiple lines.</td>
+      </tr>
+      <tr>
+        <td align="center">Second</td>
+        <td align="left">row</td>
+        <td align="right">5.0</td>
+        <td align="left">Here’s another one. Note the blank line between
+        rows.</td>
+      </tr>
+    </tbody>
+  </table>
+</table-wrap>
+<p>Table without column headers:</p>
+<table-wrap>
+  <table>
+    <tbody>
+      <tr>
+        <td align="right">12</td>
+        <td align="left">12</td>
+        <td align="center">12</td>
+        <td align="right">12</td>
+      </tr>
+      <tr>
+        <td align="right">123</td>
+        <td align="left">123</td>
+        <td align="center">123</td>
+        <td align="right">123</td>
+      </tr>
+      <tr>
+        <td align="right">1</td>
+        <td align="left">1</td>
+        <td align="center">1</td>
+        <td align="right">1</td>
+      </tr>
+    </tbody>
+  </table>
+</table-wrap>
+<p>Multiline table without column headers:</p>
+<table-wrap>
+  <table>
+    <colgroup>
+      <col width="15%" />
+      <col width="14%" />
+      <col width="16%" />
+      <col width="35%" />
+    </colgroup>
+    <tbody>
+      <tr>
+        <td align="center">First</td>
+        <td align="left">row</td>
+        <td align="right">12.0</td>
+        <td>Example of a row that spans multiple lines.</td>
+      </tr>
+      <tr>
+        <td align="center">Second</td>
+        <td align="left">row</td>
+        <td align="right">5.0</td>
+        <td>Here’s another one. Note the blank line between rows.</td>
+      </tr>
+    </tbody>
+  </table>
+</table-wrap>
diff --git a/test/tables.jats_articleauthoring b/test/tables.jats_articleauthoring
new file mode 100644
--- /dev/null
+++ b/test/tables.jats_articleauthoring
@@ -0,0 +1,226 @@
+<p>Simple table with caption:</p>
+<table-wrap>
+  <caption>
+    <p>Demonstration of simple table syntax.</p>
+  </caption>
+  <table>
+    <thead>
+      <tr>
+        <th align="right">Right</th>
+        <th align="left">Left</th>
+        <th align="center">Center</th>
+        <th>Default</th>
+      </tr>
+    </thead>
+    <tbody>
+      <tr>
+        <td align="right">12</td>
+        <td align="left">12</td>
+        <td align="center">12</td>
+        <td>12</td>
+      </tr>
+      <tr>
+        <td align="right">123</td>
+        <td align="left">123</td>
+        <td align="center">123</td>
+        <td>123</td>
+      </tr>
+      <tr>
+        <td align="right">1</td>
+        <td align="left">1</td>
+        <td align="center">1</td>
+        <td>1</td>
+      </tr>
+    </tbody>
+  </table>
+</table-wrap>
+<p>Simple table without caption:</p>
+<table-wrap>
+  <table>
+    <thead>
+      <tr>
+        <th align="right">Right</th>
+        <th align="left">Left</th>
+        <th align="center">Center</th>
+        <th>Default</th>
+      </tr>
+    </thead>
+    <tbody>
+      <tr>
+        <td align="right">12</td>
+        <td align="left">12</td>
+        <td align="center">12</td>
+        <td>12</td>
+      </tr>
+      <tr>
+        <td align="right">123</td>
+        <td align="left">123</td>
+        <td align="center">123</td>
+        <td>123</td>
+      </tr>
+      <tr>
+        <td align="right">1</td>
+        <td align="left">1</td>
+        <td align="center">1</td>
+        <td>1</td>
+      </tr>
+    </tbody>
+  </table>
+</table-wrap>
+<p>Simple table indented two spaces:</p>
+<table-wrap>
+  <caption>
+    <p>Demonstration of simple table syntax.</p>
+  </caption>
+  <table>
+    <thead>
+      <tr>
+        <th align="right">Right</th>
+        <th align="left">Left</th>
+        <th align="center">Center</th>
+        <th>Default</th>
+      </tr>
+    </thead>
+    <tbody>
+      <tr>
+        <td align="right">12</td>
+        <td align="left">12</td>
+        <td align="center">12</td>
+        <td>12</td>
+      </tr>
+      <tr>
+        <td align="right">123</td>
+        <td align="left">123</td>
+        <td align="center">123</td>
+        <td>123</td>
+      </tr>
+      <tr>
+        <td align="right">1</td>
+        <td align="left">1</td>
+        <td align="center">1</td>
+        <td>1</td>
+      </tr>
+    </tbody>
+  </table>
+</table-wrap>
+<p>Multiline table with caption:</p>
+<table-wrap>
+  <caption>
+    <p>Here’s the caption. It may span multiple lines.</p>
+  </caption>
+  <table>
+    <colgroup>
+      <col width="15%" />
+      <col width="14%" />
+      <col width="16%" />
+      <col width="35%" />
+    </colgroup>
+    <thead>
+      <tr>
+        <th align="center">Centered Header</th>
+        <th align="left">Left Aligned</th>
+        <th align="right">Right Aligned</th>
+        <th align="left">Default aligned</th>
+      </tr>
+    </thead>
+    <tbody>
+      <tr>
+        <td align="center">First</td>
+        <td align="left">row</td>
+        <td align="right">12.0</td>
+        <td align="left">Example of a row that spans multiple lines.</td>
+      </tr>
+      <tr>
+        <td align="center">Second</td>
+        <td align="left">row</td>
+        <td align="right">5.0</td>
+        <td align="left">Here’s another one. Note the blank line between
+        rows.</td>
+      </tr>
+    </tbody>
+  </table>
+</table-wrap>
+<p>Multiline table without caption:</p>
+<table-wrap>
+  <table>
+    <colgroup>
+      <col width="15%" />
+      <col width="14%" />
+      <col width="16%" />
+      <col width="35%" />
+    </colgroup>
+    <thead>
+      <tr>
+        <th align="center">Centered Header</th>
+        <th align="left">Left Aligned</th>
+        <th align="right">Right Aligned</th>
+        <th align="left">Default aligned</th>
+      </tr>
+    </thead>
+    <tbody>
+      <tr>
+        <td align="center">First</td>
+        <td align="left">row</td>
+        <td align="right">12.0</td>
+        <td align="left">Example of a row that spans multiple lines.</td>
+      </tr>
+      <tr>
+        <td align="center">Second</td>
+        <td align="left">row</td>
+        <td align="right">5.0</td>
+        <td align="left">Here’s another one. Note the blank line between
+        rows.</td>
+      </tr>
+    </tbody>
+  </table>
+</table-wrap>
+<p>Table without column headers:</p>
+<table-wrap>
+  <table>
+    <tbody>
+      <tr>
+        <td align="right">12</td>
+        <td align="left">12</td>
+        <td align="center">12</td>
+        <td align="right">12</td>
+      </tr>
+      <tr>
+        <td align="right">123</td>
+        <td align="left">123</td>
+        <td align="center">123</td>
+        <td align="right">123</td>
+      </tr>
+      <tr>
+        <td align="right">1</td>
+        <td align="left">1</td>
+        <td align="center">1</td>
+        <td align="right">1</td>
+      </tr>
+    </tbody>
+  </table>
+</table-wrap>
+<p>Multiline table without column headers:</p>
+<table-wrap>
+  <table>
+    <colgroup>
+      <col width="15%" />
+      <col width="14%" />
+      <col width="16%" />
+      <col width="35%" />
+    </colgroup>
+    <tbody>
+      <tr>
+        <td align="center">First</td>
+        <td align="left">row</td>
+        <td align="right">12.0</td>
+        <td>Example of a row that spans multiple lines.</td>
+      </tr>
+      <tr>
+        <td align="center">Second</td>
+        <td align="left">row</td>
+        <td align="right">5.0</td>
+        <td>Here’s another one. Note the blank line between rows.</td>
+      </tr>
+    </tbody>
+  </table>
+</table-wrap>
diff --git a/test/tables.jats_publishing b/test/tables.jats_publishing
new file mode 100644
--- /dev/null
+++ b/test/tables.jats_publishing
@@ -0,0 +1,226 @@
+<p>Simple table with caption:</p>
+<table-wrap>
+  <caption>
+    <p>Demonstration of simple table syntax.</p>
+  </caption>
+  <table>
+    <thead>
+      <tr>
+        <th align="right">Right</th>
+        <th align="left">Left</th>
+        <th align="center">Center</th>
+        <th>Default</th>
+      </tr>
+    </thead>
+    <tbody>
+      <tr>
+        <td align="right">12</td>
+        <td align="left">12</td>
+        <td align="center">12</td>
+        <td>12</td>
+      </tr>
+      <tr>
+        <td align="right">123</td>
+        <td align="left">123</td>
+        <td align="center">123</td>
+        <td>123</td>
+      </tr>
+      <tr>
+        <td align="right">1</td>
+        <td align="left">1</td>
+        <td align="center">1</td>
+        <td>1</td>
+      </tr>
+    </tbody>
+  </table>
+</table-wrap>
+<p>Simple table without caption:</p>
+<table-wrap>
+  <table>
+    <thead>
+      <tr>
+        <th align="right">Right</th>
+        <th align="left">Left</th>
+        <th align="center">Center</th>
+        <th>Default</th>
+      </tr>
+    </thead>
+    <tbody>
+      <tr>
+        <td align="right">12</td>
+        <td align="left">12</td>
+        <td align="center">12</td>
+        <td>12</td>
+      </tr>
+      <tr>
+        <td align="right">123</td>
+        <td align="left">123</td>
+        <td align="center">123</td>
+        <td>123</td>
+      </tr>
+      <tr>
+        <td align="right">1</td>
+        <td align="left">1</td>
+        <td align="center">1</td>
+        <td>1</td>
+      </tr>
+    </tbody>
+  </table>
+</table-wrap>
+<p>Simple table indented two spaces:</p>
+<table-wrap>
+  <caption>
+    <p>Demonstration of simple table syntax.</p>
+  </caption>
+  <table>
+    <thead>
+      <tr>
+        <th align="right">Right</th>
+        <th align="left">Left</th>
+        <th align="center">Center</th>
+        <th>Default</th>
+      </tr>
+    </thead>
+    <tbody>
+      <tr>
+        <td align="right">12</td>
+        <td align="left">12</td>
+        <td align="center">12</td>
+        <td>12</td>
+      </tr>
+      <tr>
+        <td align="right">123</td>
+        <td align="left">123</td>
+        <td align="center">123</td>
+        <td>123</td>
+      </tr>
+      <tr>
+        <td align="right">1</td>
+        <td align="left">1</td>
+        <td align="center">1</td>
+        <td>1</td>
+      </tr>
+    </tbody>
+  </table>
+</table-wrap>
+<p>Multiline table with caption:</p>
+<table-wrap>
+  <caption>
+    <p>Here’s the caption. It may span multiple lines.</p>
+  </caption>
+  <table>
+    <colgroup>
+      <col width="15%" />
+      <col width="14%" />
+      <col width="16%" />
+      <col width="35%" />
+    </colgroup>
+    <thead>
+      <tr>
+        <th align="center">Centered Header</th>
+        <th align="left">Left Aligned</th>
+        <th align="right">Right Aligned</th>
+        <th align="left">Default aligned</th>
+      </tr>
+    </thead>
+    <tbody>
+      <tr>
+        <td align="center">First</td>
+        <td align="left">row</td>
+        <td align="right">12.0</td>
+        <td align="left">Example of a row that spans multiple lines.</td>
+      </tr>
+      <tr>
+        <td align="center">Second</td>
+        <td align="left">row</td>
+        <td align="right">5.0</td>
+        <td align="left">Here’s another one. Note the blank line between
+        rows.</td>
+      </tr>
+    </tbody>
+  </table>
+</table-wrap>
+<p>Multiline table without caption:</p>
+<table-wrap>
+  <table>
+    <colgroup>
+      <col width="15%" />
+      <col width="14%" />
+      <col width="16%" />
+      <col width="35%" />
+    </colgroup>
+    <thead>
+      <tr>
+        <th align="center">Centered Header</th>
+        <th align="left">Left Aligned</th>
+        <th align="right">Right Aligned</th>
+        <th align="left">Default aligned</th>
+      </tr>
+    </thead>
+    <tbody>
+      <tr>
+        <td align="center">First</td>
+        <td align="left">row</td>
+        <td align="right">12.0</td>
+        <td align="left">Example of a row that spans multiple lines.</td>
+      </tr>
+      <tr>
+        <td align="center">Second</td>
+        <td align="left">row</td>
+        <td align="right">5.0</td>
+        <td align="left">Here’s another one. Note the blank line between
+        rows.</td>
+      </tr>
+    </tbody>
+  </table>
+</table-wrap>
+<p>Table without column headers:</p>
+<table-wrap>
+  <table>
+    <tbody>
+      <tr>
+        <td align="right">12</td>
+        <td align="left">12</td>
+        <td align="center">12</td>
+        <td align="right">12</td>
+      </tr>
+      <tr>
+        <td align="right">123</td>
+        <td align="left">123</td>
+        <td align="center">123</td>
+        <td align="right">123</td>
+      </tr>
+      <tr>
+        <td align="right">1</td>
+        <td align="left">1</td>
+        <td align="center">1</td>
+        <td align="right">1</td>
+      </tr>
+    </tbody>
+  </table>
+</table-wrap>
+<p>Multiline table without column headers:</p>
+<table-wrap>
+  <table>
+    <colgroup>
+      <col width="15%" />
+      <col width="14%" />
+      <col width="16%" />
+      <col width="35%" />
+    </colgroup>
+    <tbody>
+      <tr>
+        <td align="center">First</td>
+        <td align="left">row</td>
+        <td align="right">12.0</td>
+        <td>Example of a row that spans multiple lines.</td>
+      </tr>
+      <tr>
+        <td align="center">Second</td>
+        <td align="left">row</td>
+        <td align="right">5.0</td>
+        <td>Here’s another one. Note the blank line between rows.</td>
+      </tr>
+    </tbody>
+  </table>
+</table-wrap>
diff --git a/test/tables.jira b/test/tables.jira
new file mode 100644
--- /dev/null
+++ b/test/tables.jira
@@ -0,0 +1,43 @@
+Simple table with caption:
+
+|| Right || Left || Center || Default ||
+| 12 | 12 | 12 | 12 |
+| 123 | 123 | 123 | 123 |
+| 1 | 1 | 1 | 1 |
+
+Simple table without caption:
+
+|| Right || Left || Center || Default ||
+| 12 | 12 | 12 | 12 |
+| 123 | 123 | 123 | 123 |
+| 1 | 1 | 1 | 1 |
+
+Simple table indented two spaces:
+
+|| Right || Left || Center || Default ||
+| 12 | 12 | 12 | 12 |
+| 123 | 123 | 123 | 123 |
+| 1 | 1 | 1 | 1 |
+
+Multiline table with caption:
+
+|| Centered Header || Left Aligned || Right Aligned || Default aligned ||
+| First | row | 12.0 | Example of a row that spans multiple lines. |
+| Second | row | 5.0 | Here’s another one. Note the blank line between rows. |
+
+Multiline table without caption:
+
+|| Centered Header || Left Aligned || Right Aligned || Default aligned ||
+| First | row | 12.0 | Example of a row that spans multiple lines. |
+| Second | row | 5.0 | Here’s another one. Note the blank line between rows. |
+
+Table without column headers:
+
+| 12 | 12 | 12 | 12 |
+| 123 | 123 | 123 | 123 |
+| 1 | 1 | 1 | 1 |
+
+Multiline table without column headers:
+
+| First | row | 12.0 | Example of a row that spans multiple lines. |
+| Second | row | 5.0 | Here’s another one. Note the blank line between rows. |
diff --git a/test/tables.latex b/test/tables.latex
--- a/test/tables.latex
+++ b/test/tables.latex
@@ -2,169 +2,148 @@
 
 \begin{longtable}[]{@{}rlcl@{}}
 \caption{Demonstration of simple table syntax.}\tabularnewline
-\toprule
-Right & Left & Center & Default\tabularnewline
-\midrule
+\toprule\noalign{}
+Right & Left & Center & Default \\
+\midrule\noalign{}
 \endfirsthead
-\toprule
-Right & Left & Center & Default\tabularnewline
-\midrule
+\toprule\noalign{}
+Right & Left & Center & Default \\
+\midrule\noalign{}
 \endhead
-12 & 12 & 12 & 12\tabularnewline
-123 & 123 & 123 & 123\tabularnewline
-1 & 1 & 1 & 1\tabularnewline
-\bottomrule
+\bottomrule\noalign{}
+\endlastfoot
+12 & 12 & 12 & 12 \\
+123 & 123 & 123 & 123 \\
+1 & 1 & 1 & 1 \\
 \end{longtable}
 
 Simple table without caption:
 
+{\def\LTcaptype{none} % do not increment counter
 \begin{longtable}[]{@{}rlcl@{}}
-\toprule
-Right & Left & Center & Default\tabularnewline
-\midrule
+\toprule\noalign{}
+Right & Left & Center & Default \\
+\midrule\noalign{}
 \endhead
-12 & 12 & 12 & 12\tabularnewline
-123 & 123 & 123 & 123\tabularnewline
-1 & 1 & 1 & 1\tabularnewline
-\bottomrule
+\bottomrule\noalign{}
+\endlastfoot
+12 & 12 & 12 & 12 \\
+123 & 123 & 123 & 123 \\
+1 & 1 & 1 & 1 \\
 \end{longtable}
+}
 
 Simple table indented two spaces:
 
 \begin{longtable}[]{@{}rlcl@{}}
 \caption{Demonstration of simple table syntax.}\tabularnewline
-\toprule
-Right & Left & Center & Default\tabularnewline
-\midrule
+\toprule\noalign{}
+Right & Left & Center & Default \\
+\midrule\noalign{}
 \endfirsthead
-\toprule
-Right & Left & Center & Default\tabularnewline
-\midrule
+\toprule\noalign{}
+Right & Left & Center & Default \\
+\midrule\noalign{}
 \endhead
-12 & 12 & 12 & 12\tabularnewline
-123 & 123 & 123 & 123\tabularnewline
-1 & 1 & 1 & 1\tabularnewline
-\bottomrule
+\bottomrule\noalign{}
+\endlastfoot
+12 & 12 & 12 & 12 \\
+123 & 123 & 123 & 123 \\
+1 & 1 & 1 & 1 \\
 \end{longtable}
 
 Multiline table with caption:
 
-\begin{longtable}[]{@{}clrl@{}}
+\begin{longtable}[]{@{}
+  >{\centering\arraybackslash}p{(\linewidth - 6\tabcolsep) * \real{0.1500}}
+  >{\raggedright\arraybackslash}p{(\linewidth - 6\tabcolsep) * \real{0.1375}}
+  >{\raggedleft\arraybackslash}p{(\linewidth - 6\tabcolsep) * \real{0.1625}}
+  >{\raggedright\arraybackslash}p{(\linewidth - 6\tabcolsep) * \real{0.3500}}@{}}
 \caption{Here's the caption. It may span multiple lines.}\tabularnewline
-\toprule
-\begin{minipage}[b]{0.13\columnwidth}\centering
-Centered Header\strut
-\end{minipage} & \begin{minipage}[b]{0.12\columnwidth}\raggedright
-Left Aligned\strut
-\end{minipage} & \begin{minipage}[b]{0.14\columnwidth}\raggedleft
-Right Aligned\strut
-\end{minipage} & \begin{minipage}[b]{0.30\columnwidth}\raggedright
-Default aligned\strut
-\end{minipage}\tabularnewline
-\midrule
+\toprule\noalign{}
+\begin{minipage}[b]{\linewidth}\centering
+Centered Header
+\end{minipage} & \begin{minipage}[b]{\linewidth}\raggedright
+Left Aligned
+\end{minipage} & \begin{minipage}[b]{\linewidth}\raggedleft
+Right Aligned
+\end{minipage} & \begin{minipage}[b]{\linewidth}\raggedright
+Default aligned
+\end{minipage} \\
+\midrule\noalign{}
 \endfirsthead
-\toprule
-\begin{minipage}[b]{0.13\columnwidth}\centering
-Centered Header\strut
-\end{minipage} & \begin{minipage}[b]{0.12\columnwidth}\raggedright
-Left Aligned\strut
-\end{minipage} & \begin{minipage}[b]{0.14\columnwidth}\raggedleft
-Right Aligned\strut
-\end{minipage} & \begin{minipage}[b]{0.30\columnwidth}\raggedright
-Default aligned\strut
-\end{minipage}\tabularnewline
-\midrule
+\toprule\noalign{}
+\begin{minipage}[b]{\linewidth}\centering
+Centered Header
+\end{minipage} & \begin{minipage}[b]{\linewidth}\raggedright
+Left Aligned
+\end{minipage} & \begin{minipage}[b]{\linewidth}\raggedleft
+Right Aligned
+\end{minipage} & \begin{minipage}[b]{\linewidth}\raggedright
+Default aligned
+\end{minipage} \\
+\midrule\noalign{}
 \endhead
-\begin{minipage}[t]{0.13\columnwidth}\centering
-First\strut
-\end{minipage} & \begin{minipage}[t]{0.12\columnwidth}\raggedright
-row\strut
-\end{minipage} & \begin{minipage}[t]{0.14\columnwidth}\raggedleft
-12.0\strut
-\end{minipage} & \begin{minipage}[t]{0.30\columnwidth}\raggedright
-Example of a row that spans multiple lines.\strut
-\end{minipage}\tabularnewline
-\begin{minipage}[t]{0.13\columnwidth}\centering
-Second\strut
-\end{minipage} & \begin{minipage}[t]{0.12\columnwidth}\raggedright
-row\strut
-\end{minipage} & \begin{minipage}[t]{0.14\columnwidth}\raggedleft
-5.0\strut
-\end{minipage} & \begin{minipage}[t]{0.30\columnwidth}\raggedright
-Here's another one. Note the blank line between rows.\strut
-\end{minipage}\tabularnewline
-\bottomrule
+\bottomrule\noalign{}
+\endlastfoot
+First & row & 12.0 & Example of a row that spans multiple lines. \\
+Second & row & 5.0 & Here's another one. Note the blank line between rows. \\
 \end{longtable}
 
 Multiline table without caption:
 
-\begin{longtable}[]{@{}clrl@{}}
-\toprule
-\begin{minipage}[b]{0.13\columnwidth}\centering
-Centered Header\strut
-\end{minipage} & \begin{minipage}[b]{0.12\columnwidth}\raggedright
-Left Aligned\strut
-\end{minipage} & \begin{minipage}[b]{0.14\columnwidth}\raggedleft
-Right Aligned\strut
-\end{minipage} & \begin{minipage}[b]{0.30\columnwidth}\raggedright
-Default aligned\strut
-\end{minipage}\tabularnewline
-\midrule
+{\def\LTcaptype{none} % do not increment counter
+\begin{longtable}[]{@{}
+  >{\centering\arraybackslash}p{(\linewidth - 6\tabcolsep) * \real{0.1500}}
+  >{\raggedright\arraybackslash}p{(\linewidth - 6\tabcolsep) * \real{0.1375}}
+  >{\raggedleft\arraybackslash}p{(\linewidth - 6\tabcolsep) * \real{0.1625}}
+  >{\raggedright\arraybackslash}p{(\linewidth - 6\tabcolsep) * \real{0.3500}}@{}}
+\toprule\noalign{}
+\begin{minipage}[b]{\linewidth}\centering
+Centered Header
+\end{minipage} & \begin{minipage}[b]{\linewidth}\raggedright
+Left Aligned
+\end{minipage} & \begin{minipage}[b]{\linewidth}\raggedleft
+Right Aligned
+\end{minipage} & \begin{minipage}[b]{\linewidth}\raggedright
+Default aligned
+\end{minipage} \\
+\midrule\noalign{}
 \endhead
-\begin{minipage}[t]{0.13\columnwidth}\centering
-First\strut
-\end{minipage} & \begin{minipage}[t]{0.12\columnwidth}\raggedright
-row\strut
-\end{minipage} & \begin{minipage}[t]{0.14\columnwidth}\raggedleft
-12.0\strut
-\end{minipage} & \begin{minipage}[t]{0.30\columnwidth}\raggedright
-Example of a row that spans multiple lines.\strut
-\end{minipage}\tabularnewline
-\begin{minipage}[t]{0.13\columnwidth}\centering
-Second\strut
-\end{minipage} & \begin{minipage}[t]{0.12\columnwidth}\raggedright
-row\strut
-\end{minipage} & \begin{minipage}[t]{0.14\columnwidth}\raggedleft
-5.0\strut
-\end{minipage} & \begin{minipage}[t]{0.30\columnwidth}\raggedright
-Here's another one. Note the blank line between rows.\strut
-\end{minipage}\tabularnewline
-\bottomrule
+\bottomrule\noalign{}
+\endlastfoot
+First & row & 12.0 & Example of a row that spans multiple lines. \\
+Second & row & 5.0 & Here's another one. Note the blank line between rows. \\
 \end{longtable}
+}
 
 Table without column headers:
 
+{\def\LTcaptype{none} % do not increment counter
 \begin{longtable}[]{@{}rlcr@{}}
-\toprule
+\toprule\noalign{}
 \endhead
-12 & 12 & 12 & 12\tabularnewline
-123 & 123 & 123 & 123\tabularnewline
-1 & 1 & 1 & 1\tabularnewline
-\bottomrule
+\bottomrule\noalign{}
+\endlastfoot
+12 & 12 & 12 & 12 \\
+123 & 123 & 123 & 123 \\
+1 & 1 & 1 & 1 \\
 \end{longtable}
+}
 
 Multiline table without column headers:
 
-\begin{longtable}[]{@{}clrl@{}}
-\toprule
+{\def\LTcaptype{none} % do not increment counter
+\begin{longtable}[]{@{}
+  >{\centering\arraybackslash}p{(\linewidth - 6\tabcolsep) * \real{0.1500}}
+  >{\raggedright\arraybackslash}p{(\linewidth - 6\tabcolsep) * \real{0.1375}}
+  >{\raggedleft\arraybackslash}p{(\linewidth - 6\tabcolsep) * \real{0.1625}}
+  >{\raggedright\arraybackslash}p{(\linewidth - 6\tabcolsep) * \real{0.3500}}@{}}
+\toprule\noalign{}
 \endhead
-\begin{minipage}[t]{0.13\columnwidth}\centering
-First\strut
-\end{minipage} & \begin{minipage}[t]{0.12\columnwidth}\raggedright
-row\strut
-\end{minipage} & \begin{minipage}[t]{0.14\columnwidth}\raggedleft
-12.0\strut
-\end{minipage} & \begin{minipage}[t]{0.30\columnwidth}\raggedright
-Example of a row that spans multiple lines.\strut
-\end{minipage}\tabularnewline
-\begin{minipage}[t]{0.13\columnwidth}\centering
-Second\strut
-\end{minipage} & \begin{minipage}[t]{0.12\columnwidth}\raggedright
-row\strut
-\end{minipage} & \begin{minipage}[t]{0.14\columnwidth}\raggedleft
-5.0\strut
-\end{minipage} & \begin{minipage}[t]{0.30\columnwidth}\raggedright
-Here's another one. Note the blank line between rows.\strut
-\end{minipage}\tabularnewline
-\bottomrule
+\bottomrule\noalign{}
+\endlastfoot
+First & row & 12.0 & Example of a row that spans multiple lines. \\
+Second & row & 5.0 & Here's another one. Note the blank line between rows. \\
 \end{longtable}
+}
diff --git a/test/tables.man b/test/tables.man
--- a/test/tables.man
+++ b/test/tables.man
@@ -135,10 +135,10 @@
 .PP
 Multiline table with caption:
 .PP
-Here's the caption. It may span multiple lines.
+Here\(cqs the caption. It may span multiple lines.
 .TS
 tab(@);
-cw(10.5n) lw(9.6n) rw(11.4n) lw(23.6n).
+cw(10.5n) lw(9.6n) rw(11.4n) lw(24.5n).
 T{
 Centered Header
 T}@T{
@@ -165,7 +165,7 @@
 T}@T{
 5.0
 T}@T{
-Here's another one.
+Here\(cqs another one.
 Note the blank line between rows.
 T}
 .TE
@@ -174,7 +174,7 @@
 .PP
 .TS
 tab(@);
-cw(10.5n) lw(9.6n) rw(11.4n) lw(23.6n).
+cw(10.5n) lw(9.6n) rw(11.4n) lw(24.5n).
 T{
 Centered Header
 T}@T{
@@ -201,7 +201,7 @@
 T}@T{
 5.0
 T}@T{
-Here's another one.
+Here\(cqs another one.
 Note the blank line between rows.
 T}
 .TE
@@ -244,7 +244,7 @@
 .PP
 .TS
 tab(@);
-cw(10.5n) lw(9.6n) rw(11.4n) lw(23.6n).
+cw(10.5n) lw(9.6n) rw(11.4n) lw(24.5n).
 T{
 First
 T}@T{
@@ -261,7 +261,7 @@
 T}@T{
 5.0
 T}@T{
-Here's another one.
+Here\(cqs another one.
 Note the blank line between rows.
 T}
 .TE
diff --git a/test/tables.markdown b/test/tables.markdown
--- a/test/tables.markdown
+++ b/test/tables.markdown
@@ -28,33 +28,33 @@
 
 Multiline table with caption:
 
-  --------------------------------------------------------------
+  ---------------------------------------------------------------
    Centered   Left              Right Default aligned
     Header    Aligned         Aligned 
-  ----------- ---------- ------------ --------------------------
-     First    row                12.0 Example of a row that
-                                      spans multiple lines.
+  ----------- ---------- ------------ ---------------------------
+     First    row                12.0 Example of a row that spans
+                                      multiple lines.
 
     Second    row                 5.0 Here's another one. Note
                                       the blank line between
                                       rows.
-  --------------------------------------------------------------
+  ---------------------------------------------------------------
 
   : Here's the caption. It may span multiple lines.
 
 Multiline table without caption:
 
-  --------------------------------------------------------------
+  ---------------------------------------------------------------
    Centered   Left              Right Default aligned
     Header    Aligned         Aligned 
-  ----------- ---------- ------------ --------------------------
-     First    row                12.0 Example of a row that
-                                      spans multiple lines.
+  ----------- ---------- ------------ ---------------------------
+     First    row                12.0 Example of a row that spans
+                                      multiple lines.
 
     Second    row                 5.0 Here's another one. Note
                                       the blank line between
                                       rows.
-  --------------------------------------------------------------
+  ---------------------------------------------------------------
 
 Table without column headers:
 
@@ -66,11 +66,11 @@
 
 Multiline table without column headers:
 
-  ----------- ---------- ------------ --------------------------
-     First    row                12.0 Example of a row that
-                                      spans multiple lines.
+  ----------- ---------- ------------ ---------------------------
+     First    row                12.0 Example of a row that spans
+                                      multiple lines.
 
     Second    row                 5.0 Here's another one. Note
                                       the blank line between
                                       rows.
-  ----------- ---------- ------------ --------------------------
+  ----------- ---------- ------------ ---------------------------
diff --git a/test/tables.markua b/test/tables.markua
new file mode 100644
--- /dev/null
+++ b/test/tables.markua
@@ -0,0 +1,58 @@
+Simple table with caption:
+
+| Right | Left | Center | Default |
+|------:|:-----|:------:|---------|
+|    12 | 12   |   12   | 12      |
+|   123 | 123  |  123   | 123     |
+|     1 | 1    |   1    | 1       |
+
+Demonstration of simple table syntax.
+
+Simple table without caption:
+
+| Right | Left | Center | Default |
+|------:|:-----|:------:|---------|
+|    12 | 12   |   12   | 12      |
+|   123 | 123  |  123   | 123     |
+|     1 | 1    |   1    | 1       |
+
+Simple table indented two spaces:
+
+| Right | Left | Center | Default |
+|------:|:-----|:------:|---------|
+|    12 | 12   |   12   | 12      |
+|   123 | 123  |  123   | 123     |
+|     1 | 1    |   1    | 1       |
+
+Demonstration of simple table syntax.
+
+Multiline table with caption:
+
+| Centered Header | Left Aligned | Right Aligned | Default aligned |
+|:--:|:---|---:|:---|
+| First | row | 12.0 | Example of a row that spans multiple lines. |
+| Second | row | 5.0 | Here’s another one. Note the blank line between rows. |
+
+Here’s the caption. It may span multiple lines.
+
+Multiline table without caption:
+
+| Centered Header | Left Aligned | Right Aligned | Default aligned |
+|:--:|:---|---:|:---|
+| First | row | 12.0 | Example of a row that spans multiple lines. |
+| Second | row | 5.0 | Here’s another one. Note the blank line between rows. |
+
+Table without column headers:
+
+|     |     |     |     |
+|----:|:----|:---:|----:|
+|  12 | 12  | 12  |  12 |
+| 123 | 123 | 123 | 123 |
+|   1 | 1   |  1  |   1 |
+
+Multiline table without column headers:
+
+|        |     |      |                                                       |
+|:------:|:----|-----:|-------------------------------------------------------|
+| First  | row | 12.0 | Example of a row that spans multiple lines.           |
+| Second | row |  5.0 | Here’s another one. Note the blank line between rows. |
diff --git a/test/tables.mediawiki b/test/tables.mediawiki
--- a/test/tables.mediawiki
+++ b/test/tables.mediawiki
@@ -1,146 +1,152 @@
 Simple table with caption:
 
-{|
+{| class="wikitable"
 |+ Demonstration of simple table syntax.
-!align="right"| Right
-! Left
-!align="center"| Center
+|-
+! style="text-align: right;"| Right
+! style="text-align: left;"| Left
+! style="text-align: center;"| Center
 ! Default
 |-
-|align="right"| 12
-| 12
-|align="center"| 12
+| style="text-align: right;"| 12
+| style="text-align: left;"| 12
+| style="text-align: center;"| 12
 | 12
 |-
-|align="right"| 123
-| 123
-|align="center"| 123
+| style="text-align: right;"| 123
+| style="text-align: left;"| 123
+| style="text-align: center;"| 123
 | 123
 |-
-|align="right"| 1
-| 1
-|align="center"| 1
+| style="text-align: right;"| 1
+| style="text-align: left;"| 1
+| style="text-align: center;"| 1
 | 1
 |}
 
 Simple table without caption:
 
-{|
-!align="right"| Right
-! Left
-!align="center"| Center
+{| class="wikitable"
+|-
+! style="text-align: right;"| Right
+! style="text-align: left;"| Left
+! style="text-align: center;"| Center
 ! Default
 |-
-|align="right"| 12
-| 12
-|align="center"| 12
+| style="text-align: right;"| 12
+| style="text-align: left;"| 12
+| style="text-align: center;"| 12
 | 12
 |-
-|align="right"| 123
-| 123
-|align="center"| 123
+| style="text-align: right;"| 123
+| style="text-align: left;"| 123
+| style="text-align: center;"| 123
 | 123
 |-
-|align="right"| 1
-| 1
-|align="center"| 1
+| style="text-align: right;"| 1
+| style="text-align: left;"| 1
+| style="text-align: center;"| 1
 | 1
 |}
 
 Simple table indented two spaces:
 
-{|
+{| class="wikitable"
 |+ Demonstration of simple table syntax.
-!align="right"| Right
-! Left
-!align="center"| Center
+|-
+! style="text-align: right;"| Right
+! style="text-align: left;"| Left
+! style="text-align: center;"| Center
 ! Default
 |-
-|align="right"| 12
-| 12
-|align="center"| 12
+| style="text-align: right;"| 12
+| style="text-align: left;"| 12
+| style="text-align: center;"| 12
 | 12
 |-
-|align="right"| 123
-| 123
-|align="center"| 123
+| style="text-align: right;"| 123
+| style="text-align: left;"| 123
+| style="text-align: center;"| 123
 | 123
 |-
-|align="right"| 1
-| 1
-|align="center"| 1
+| style="text-align: right;"| 1
+| style="text-align: left;"| 1
+| style="text-align: center;"| 1
 | 1
 |}
 
 Multiline table with caption:
 
-{|
+{| class="wikitable"
 |+ Here’s the caption. It may span multiple lines.
-!align="center" width="15%"| Centered Header
-!width="13%"| Left Aligned
-!align="right" width="16%"| Right Aligned
-!width="33%"| Default aligned
 |-
-|align="center"| First
-| row
-|align="right"| 12.0
-| Example of a row that spans multiple lines.
+! style="text-align: center;"| Centered Header
+! style="text-align: left;"| Left Aligned
+! style="text-align: right;"| Right Aligned
+! style="text-align: left;"| Default aligned
 |-
-|align="center"| Second
-| row
-|align="right"| 5.0
-| Here’s another one. Note the blank line between rows.
+| style="text-align: center;"| First
+| style="text-align: left;"| row
+| style="text-align: right;"| 12.0
+| style="text-align: left;"| Example of a row that spans multiple lines.
+|-
+| style="text-align: center;"| Second
+| style="text-align: left;"| row
+| style="text-align: right;"| 5.0
+| style="text-align: left;"| Here’s another one. Note the blank line between rows.
 |}
 
 Multiline table without caption:
 
-{|
-!align="center" width="15%"| Centered Header
-!width="13%"| Left Aligned
-!align="right" width="16%"| Right Aligned
-!width="33%"| Default aligned
+{| class="wikitable"
 |-
-|align="center"| First
-| row
-|align="right"| 12.0
-| Example of a row that spans multiple lines.
+! style="text-align: center;"| Centered Header
+! style="text-align: left;"| Left Aligned
+! style="text-align: right;"| Right Aligned
+! style="text-align: left;"| Default aligned
 |-
-|align="center"| Second
-| row
-|align="right"| 5.0
-| Here’s another one. Note the blank line between rows.
+| style="text-align: center;"| First
+| style="text-align: left;"| row
+| style="text-align: right;"| 12.0
+| style="text-align: left;"| Example of a row that spans multiple lines.
+|-
+| style="text-align: center;"| Second
+| style="text-align: left;"| row
+| style="text-align: right;"| 5.0
+| style="text-align: left;"| Here’s another one. Note the blank line between rows.
 |}
 
 Table without column headers:
 
-{|
-|align="right"| 12
-| 12
-|align="center"| 12
-|align="right"| 12
+{| class="wikitable"
 |-
-|align="right"| 123
-| 123
-|align="center"| 123
-|align="right"| 123
+| style="text-align: right;"| 12
+| style="text-align: left;"| 12
+| style="text-align: center;"| 12
+| style="text-align: right;"| 12
 |-
-|align="right"| 1
-| 1
-|align="center"| 1
-|align="right"| 1
+| style="text-align: right;"| 123
+| style="text-align: left;"| 123
+| style="text-align: center;"| 123
+| style="text-align: right;"| 123
+|-
+| style="text-align: right;"| 1
+| style="text-align: left;"| 1
+| style="text-align: center;"| 1
+| style="text-align: right;"| 1
 |}
 
 Multiline table without column headers:
 
-{|
-|align="center" width="15%"| First
-|width="13%"| row
-|align="right" width="16%"| 12.0
-|width="33%"| Example of a row that spans multiple lines.
+{| class="wikitable"
 |-
-|align="center"| Second
-| row
-|align="right"| 5.0
+| style="text-align: center;"| First
+| style="text-align: left;"| row
+| style="text-align: right;"| 12.0
+| Example of a row that spans multiple lines.
+|-
+| style="text-align: center;"| Second
+| style="text-align: left;"| row
+| style="text-align: right;"| 5.0
 | Here’s another one. Note the blank line between rows.
 |}
-
diff --git a/test/tables.ms b/test/tables.ms
--- a/test/tables.ms
+++ b/test/tables.ms
@@ -2,6 +2,7 @@
 Simple table with caption:
 .PP
 Demonstration of simple table syntax.
+.na
 .TS
 delim(@@) tab(	);
 r l c l.
@@ -43,9 +44,11 @@
 1
 T}
 .TE
+.ad
 .LP
 Simple table without caption:
 .PP
+.na
 .TS
 delim(@@) tab(	);
 r l c l.
@@ -87,10 +90,12 @@
 1
 T}
 .TE
+.ad
 .LP
 Simple table indented two spaces:
 .PP
 Demonstration of simple table syntax.
+.na
 .TS
 delim(@@) tab(	);
 r l c l.
@@ -132,13 +137,16 @@
 1
 T}
 .TE
+.ad
 .LP
 Multiline table with caption:
 .PP
-Here's the caption. It may span multiple lines.
+Here\(cqs the caption. It may span multiple lines.
+.na
+.nr LLold \n[LL]
 .TS
 delim(@@) tab(	);
-cw(10.5n) lw(9.6n) rw(11.4n) lw(23.6n).
+cw(10.5n) lw(9.6n) rw(11.4n) lw(24.5n).
 T{
 Centered Header
 T}	T{
@@ -150,31 +158,43 @@
 T}
 _
 T{
+.nr LL 10.5n
 First
 T}	T{
+.nr LL 9.6n
 row
 T}	T{
+.nr LL 11.4n
 12.0
 T}	T{
+.nr LL 24.5n
 Example of a row that spans multiple lines.
 T}
 T{
+.nr LL 10.5n
 Second
 T}	T{
+.nr LL 9.6n
 row
 T}	T{
+.nr LL 11.4n
 5.0
 T}	T{
-Here's another one.
+.nr LL 24.5n
+Here\(cqs another one.
 Note the blank line between rows.
 T}
 .TE
+.nr LL \n[LLold]
+.ad
 .LP
 Multiline table without caption:
 .PP
+.na
+.nr LLold \n[LL]
 .TS
 delim(@@) tab(	);
-cw(10.5n) lw(9.6n) rw(11.4n) lw(23.6n).
+cw(10.5n) lw(9.6n) rw(11.4n) lw(24.5n).
 T{
 Centered Header
 T}	T{
@@ -186,28 +206,39 @@
 T}
 _
 T{
+.nr LL 10.5n
 First
 T}	T{
+.nr LL 9.6n
 row
 T}	T{
+.nr LL 11.4n
 12.0
 T}	T{
+.nr LL 24.5n
 Example of a row that spans multiple lines.
 T}
 T{
+.nr LL 10.5n
 Second
 T}	T{
+.nr LL 9.6n
 row
 T}	T{
+.nr LL 11.4n
 5.0
 T}	T{
-Here's another one.
+.nr LL 24.5n
+Here\(cqs another one.
 Note the blank line between rows.
 T}
 .TE
+.nr LL \n[LLold]
+.ad
 .LP
 Table without column headers:
 .PP
+.na
 .TS
 delim(@@) tab(	);
 r l c r.
@@ -239,29 +270,42 @@
 1
 T}
 .TE
+.ad
 .LP
 Multiline table without column headers:
 .PP
+.na
+.nr LLold \n[LL]
 .TS
 delim(@@) tab(	);
-cw(10.5n) lw(9.6n) rw(11.4n) lw(23.6n).
+cw(10.5n) lw(9.6n) rw(11.4n) lw(24.5n).
 T{
+.nr LL 10.5n
 First
 T}	T{
+.nr LL 9.6n
 row
 T}	T{
+.nr LL 11.4n
 12.0
 T}	T{
+.nr LL 24.5n
 Example of a row that spans multiple lines.
 T}
 T{
+.nr LL 10.5n
 Second
 T}	T{
+.nr LL 9.6n
 row
 T}	T{
+.nr LL 11.4n
 5.0
 T}	T{
-Here's another one.
+.nr LL 24.5n
+Here\(cqs another one.
 Note the blank line between rows.
 T}
 .TE
+.nr LL \n[LLold]
+.ad
diff --git a/test/tables.muse b/test/tables.muse
--- a/test/tables.muse
+++ b/test/tables.muse
@@ -23,17 +23,30 @@
 
 Multiline table with caption:
 
- Centered Header || Left Aligned || Right Aligned || Default aligned
- First           |  row          |  12.0          |  Example of a row that spans multiple lines.
- Second          |  row          |  5.0           |  Here’s another one. Note the blank line between rows.
- |+ Here’s the caption. It may span multiple lines. +|
-
++:---------:+:---------+-----------:+:--------------------------+
+| Centered  | Left     | Right      | Default aligned           |
+| Header    | Aligned  | Aligned    |                           |
++-----------+----------+------------+---------------------------+
+| First     | row      | 12.0       | Example of a row that     |
+|           |          |            | spans multiple lines.     |
++-----------+----------+------------+---------------------------+
+| Second    | row      | 5.0        | Here’s another one. Note  |
+|           |          |            | the blank line between    |
+|           |          |            | rows.                     |
++-----------+----------+------------+---------------------------+
 Multiline table without caption:
 
- Centered Header || Left Aligned || Right Aligned || Default aligned
- First           |  row          |  12.0          |  Example of a row that spans multiple lines.
- Second          |  row          |  5.0           |  Here’s another one. Note the blank line between rows.
-
++:---------:+:---------+-----------:+:--------------------------+
+| Centered  | Left     | Right      | Default aligned           |
+| Header    | Aligned  | Aligned    |                           |
++-----------+----------+------------+---------------------------+
+| First     | row      | 12.0       | Example of a row that     |
+|           |          |            | spans multiple lines.     |
++-----------+----------+------------+---------------------------+
+| Second    | row      | 5.0        | Here’s another one. Note  |
+|           |          |            | the blank line between    |
+|           |          |            | rows.                     |
++-----------+----------+------------+---------------------------+
 Table without column headers:
 
  12  | 12  | 12  | 12
@@ -42,5 +55,11 @@
 
 Multiline table without column headers:
 
- First  | row | 12.0 | Example of a row that spans multiple lines.
- Second | row | 5.0  | Here’s another one. Note the blank line between rows.
++:---------:+:---------+-----------:+---------------------------+
+| First     | row      | 12.0       | Example of a row that     |
+|           |          |            | spans multiple lines.     |
++-----------+----------+------------+---------------------------+
+| Second    | row      | 5.0        | Here’s another one. Note  |
+|           |          |            | the blank line between    |
+|           |          |            | rows.                     |
++-----------+----------+------------+---------------------------+
diff --git a/test/tables.native b/test/tables.native
--- a/test/tables.native
+++ b/test/tables.native
@@ -1,114 +1,964 @@
-[Para [Str "Simple",Space,Str "table",Space,Str "with",Space,Str "caption:"]
-,Table [Str "Demonstration",Space,Str "of",Space,Str "simple",Space,Str "table",Space,Str "syntax."] [AlignRight,AlignLeft,AlignCenter,AlignDefault] [0.0,0.0,0.0,0.0]
- [[Plain [Str "Right"]]
- ,[Plain [Str "Left"]]
- ,[Plain [Str "Center"]]
- ,[Plain [Str "Default"]]]
- [[[Plain [Str "12"]]
-  ,[Plain [Str "12"]]
-  ,[Plain [Str "12"]]
-  ,[Plain [Str "12"]]]
- ,[[Plain [Str "123"]]
-  ,[Plain [Str "123"]]
-  ,[Plain [Str "123"]]
-  ,[Plain [Str "123"]]]
- ,[[Plain [Str "1"]]
-  ,[Plain [Str "1"]]
-  ,[Plain [Str "1"]]
-  ,[Plain [Str "1"]]]]
-,Para [Str "Simple",Space,Str "table",Space,Str "without",Space,Str "caption:"]
-,Table [] [AlignRight,AlignLeft,AlignCenter,AlignDefault] [0.0,0.0,0.0,0.0]
- [[Plain [Str "Right"]]
- ,[Plain [Str "Left"]]
- ,[Plain [Str "Center"]]
- ,[Plain [Str "Default"]]]
- [[[Plain [Str "12"]]
-  ,[Plain [Str "12"]]
-  ,[Plain [Str "12"]]
-  ,[Plain [Str "12"]]]
- ,[[Plain [Str "123"]]
-  ,[Plain [Str "123"]]
-  ,[Plain [Str "123"]]
-  ,[Plain [Str "123"]]]
- ,[[Plain [Str "1"]]
-  ,[Plain [Str "1"]]
-  ,[Plain [Str "1"]]
-  ,[Plain [Str "1"]]]]
-,Para [Str "Simple",Space,Str "table",Space,Str "indented",Space,Str "two",Space,Str "spaces:"]
-,Table [Str "Demonstration",Space,Str "of",Space,Str "simple",Space,Str "table",Space,Str "syntax."] [AlignRight,AlignLeft,AlignCenter,AlignDefault] [0.0,0.0,0.0,0.0]
- [[Plain [Str "Right"]]
- ,[Plain [Str "Left"]]
- ,[Plain [Str "Center"]]
- ,[Plain [Str "Default"]]]
- [[[Plain [Str "12"]]
-  ,[Plain [Str "12"]]
-  ,[Plain [Str "12"]]
-  ,[Plain [Str "12"]]]
- ,[[Plain [Str "123"]]
-  ,[Plain [Str "123"]]
-  ,[Plain [Str "123"]]
-  ,[Plain [Str "123"]]]
- ,[[Plain [Str "1"]]
-  ,[Plain [Str "1"]]
-  ,[Plain [Str "1"]]
-  ,[Plain [Str "1"]]]]
-,Para [Str "Multiline",Space,Str "table",Space,Str "with",Space,Str "caption:"]
-,Table [Str "Here\8217s",Space,Str "the",Space,Str "caption.",SoftBreak,Str "It",Space,Str "may",Space,Str "span",Space,Str "multiple",Space,Str "lines."] [AlignCenter,AlignLeft,AlignRight,AlignLeft] [0.15,0.1375,0.1625,0.3375]
- [[Plain [Str "Centered",SoftBreak,Str "Header"]]
- ,[Plain [Str "Left",SoftBreak,Str "Aligned"]]
- ,[Plain [Str "Right",SoftBreak,Str "Aligned"]]
- ,[Plain [Str "Default",Space,Str "aligned"]]]
- [[[Plain [Str "First"]]
-  ,[Plain [Str "row"]]
-  ,[Plain [Str "12.0"]]
-  ,[Plain [Str "Example",Space,Str "of",Space,Str "a",Space,Str "row",Space,Str "that",Space,Str "spans",SoftBreak,Str "multiple",Space,Str "lines."]]]
- ,[[Plain [Str "Second"]]
-  ,[Plain [Str "row"]]
-  ,[Plain [Str "5.0"]]
-  ,[Plain [Str "Here\8217s",Space,Str "another",Space,Str "one.",Space,Str "Note",SoftBreak,Str "the",Space,Str "blank",Space,Str "line",Space,Str "between",Space,Str "rows."]]]]
-,Para [Str "Multiline",Space,Str "table",Space,Str "without",Space,Str "caption:"]
-,Table [] [AlignCenter,AlignLeft,AlignRight,AlignLeft] [0.15,0.1375,0.1625,0.3375]
- [[Plain [Str "Centered",SoftBreak,Str "Header"]]
- ,[Plain [Str "Left",SoftBreak,Str "Aligned"]]
- ,[Plain [Str "Right",SoftBreak,Str "Aligned"]]
- ,[Plain [Str "Default",Space,Str "aligned"]]]
- [[[Plain [Str "First"]]
-  ,[Plain [Str "row"]]
-  ,[Plain [Str "12.0"]]
-  ,[Plain [Str "Example",Space,Str "of",Space,Str "a",Space,Str "row",Space,Str "that",Space,Str "spans",SoftBreak,Str "multiple",Space,Str "lines."]]]
- ,[[Plain [Str "Second"]]
-  ,[Plain [Str "row"]]
-  ,[Plain [Str "5.0"]]
-  ,[Plain [Str "Here\8217s",Space,Str "another",Space,Str "one.",Space,Str "Note",SoftBreak,Str "the",Space,Str "blank",Space,Str "line",Space,Str "between",Space,Str "rows."]]]]
-,Para [Str "Table",Space,Str "without",Space,Str "column",Space,Str "headers:"]
-,Table [] [AlignRight,AlignLeft,AlignCenter,AlignRight] [0.0,0.0,0.0,0.0]
- [[]
- ,[]
- ,[]
- ,[]]
- [[[Plain [Str "12"]]
-  ,[Plain [Str "12"]]
-  ,[Plain [Str "12"]]
-  ,[Plain [Str "12"]]]
- ,[[Plain [Str "123"]]
-  ,[Plain [Str "123"]]
-  ,[Plain [Str "123"]]
-  ,[Plain [Str "123"]]]
- ,[[Plain [Str "1"]]
-  ,[Plain [Str "1"]]
-  ,[Plain [Str "1"]]
-  ,[Plain [Str "1"]]]]
-,Para [Str "Multiline",Space,Str "table",Space,Str "without",Space,Str "column",Space,Str "headers:"]
-,Table [] [AlignCenter,AlignLeft,AlignRight,AlignDefault] [0.15,0.1375,0.1625,0.3375]
- [[]
- ,[]
- ,[]
- ,[]]
- [[[Plain [Str "First"]]
-  ,[Plain [Str "row"]]
-  ,[Plain [Str "12.0"]]
-  ,[Plain [Str "Example",Space,Str "of",Space,Str "a",Space,Str "row",Space,Str "that",Space,Str "spans",SoftBreak,Str "multiple",Space,Str "lines."]]]
- ,[[Plain [Str "Second"]]
-  ,[Plain [Str "row"]]
-  ,[Plain [Str "5.0"]]
-  ,[Plain [Str "Here\8217s",Space,Str "another",Space,Str "one.",Space,Str "Note",SoftBreak,Str "the",Space,Str "blank",Space,Str "line",Space,Str "between",Space,Str "rows."]]]]]
+[ Para
+    [ Str "Simple"
+    , Space
+    , Str "table"
+    , Space
+    , Str "with"
+    , Space
+    , Str "caption:"
+    ]
+, Table
+    ( "" , [] , [] )
+    (Caption
+       Nothing
+       [ Plain
+           [ Str "Demonstration"
+           , Space
+           , Str "of"
+           , Space
+           , Str "simple"
+           , Space
+           , Str "table"
+           , Space
+           , Str "syntax."
+           ]
+       ])
+    [ ( AlignRight , ColWidthDefault )
+    , ( AlignLeft , ColWidthDefault )
+    , ( AlignCenter , ColWidthDefault )
+    , ( AlignDefault , ColWidthDefault )
+    ]
+    (TableHead
+       ( "" , [] , [] )
+       [ Row
+           ( "" , [] , [] )
+           [ Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "Right" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "Left" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "Center" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "Default" ] ]
+           ]
+       ])
+    [ TableBody
+        ( "" , [] , [] )
+        (RowHeadColumns 0)
+        []
+        [ Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "12" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "12" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "12" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "12" ] ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "123" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "123" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "123" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "123" ] ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "1" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "1" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "1" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "1" ] ]
+            ]
+        ]
+    ]
+    (TableFoot ( "" , [] , [] ) [])
+, Para
+    [ Str "Simple"
+    , Space
+    , Str "table"
+    , Space
+    , Str "without"
+    , Space
+    , Str "caption:"
+    ]
+, Table
+    ( "" , [] , [] )
+    (Caption Nothing [])
+    [ ( AlignRight , ColWidthDefault )
+    , ( AlignLeft , ColWidthDefault )
+    , ( AlignCenter , ColWidthDefault )
+    , ( AlignDefault , ColWidthDefault )
+    ]
+    (TableHead
+       ( "" , [] , [] )
+       [ Row
+           ( "" , [] , [] )
+           [ Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "Right" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "Left" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "Center" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "Default" ] ]
+           ]
+       ])
+    [ TableBody
+        ( "" , [] , [] )
+        (RowHeadColumns 0)
+        []
+        [ Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "12" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "12" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "12" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "12" ] ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "123" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "123" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "123" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "123" ] ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "1" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "1" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "1" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "1" ] ]
+            ]
+        ]
+    ]
+    (TableFoot ( "" , [] , [] ) [])
+, Para
+    [ Str "Simple"
+    , Space
+    , Str "table"
+    , Space
+    , Str "indented"
+    , Space
+    , Str "two"
+    , Space
+    , Str "spaces:"
+    ]
+, Table
+    ( "" , [] , [] )
+    (Caption
+       Nothing
+       [ Plain
+           [ Str "Demonstration"
+           , Space
+           , Str "of"
+           , Space
+           , Str "simple"
+           , Space
+           , Str "table"
+           , Space
+           , Str "syntax."
+           ]
+       ])
+    [ ( AlignRight , ColWidthDefault )
+    , ( AlignLeft , ColWidthDefault )
+    , ( AlignCenter , ColWidthDefault )
+    , ( AlignDefault , ColWidthDefault )
+    ]
+    (TableHead
+       ( "" , [] , [] )
+       [ Row
+           ( "" , [] , [] )
+           [ Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "Right" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "Left" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "Center" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "Default" ] ]
+           ]
+       ])
+    [ TableBody
+        ( "" , [] , [] )
+        (RowHeadColumns 0)
+        []
+        [ Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "12" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "12" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "12" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "12" ] ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "123" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "123" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "123" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "123" ] ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "1" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "1" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "1" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "1" ] ]
+            ]
+        ]
+    ]
+    (TableFoot ( "" , [] , [] ) [])
+, Para
+    [ Str "Multiline"
+    , Space
+    , Str "table"
+    , Space
+    , Str "with"
+    , Space
+    , Str "caption:"
+    ]
+, Table
+    ( "" , [] , [] )
+    (Caption
+       Nothing
+       [ Plain
+           [ Str "Here\8217s"
+           , Space
+           , Str "the"
+           , Space
+           , Str "caption."
+           , SoftBreak
+           , Str "It"
+           , Space
+           , Str "may"
+           , Space
+           , Str "span"
+           , Space
+           , Str "multiple"
+           , Space
+           , Str "lines."
+           ]
+       ])
+    [ ( AlignCenter , ColWidth 0.15 )
+    , ( AlignLeft , ColWidth 0.1375 )
+    , ( AlignRight , ColWidth 0.1625 )
+    , ( AlignLeft , ColWidth 0.35 )
+    ]
+    (TableHead
+       ( "" , [] , [] )
+       [ Row
+           ( "" , [] , [] )
+           [ Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "Centered" , SoftBreak , Str "Header" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "Left" , SoftBreak , Str "Aligned" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "Right" , SoftBreak , Str "Aligned" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "Default" , Space , Str "aligned" ] ]
+           ]
+       ])
+    [ TableBody
+        ( "" , [] , [] )
+        (RowHeadColumns 0)
+        []
+        [ Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "First" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "row" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "12.0" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain
+                    [ Str "Example"
+                    , Space
+                    , Str "of"
+                    , Space
+                    , Str "a"
+                    , Space
+                    , Str "row"
+                    , Space
+                    , Str "that"
+                    , Space
+                    , Str "spans"
+                    , SoftBreak
+                    , Str "multiple"
+                    , Space
+                    , Str "lines."
+                    ]
+                ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "Second" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "row" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "5.0" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain
+                    [ Str "Here\8217s"
+                    , Space
+                    , Str "another"
+                    , Space
+                    , Str "one."
+                    , Space
+                    , Str "Note"
+                    , SoftBreak
+                    , Str "the"
+                    , Space
+                    , Str "blank"
+                    , Space
+                    , Str "line"
+                    , Space
+                    , Str "between"
+                    , Space
+                    , Str "rows."
+                    ]
+                ]
+            ]
+        ]
+    ]
+    (TableFoot ( "" , [] , [] ) [])
+, Para
+    [ Str "Multiline"
+    , Space
+    , Str "table"
+    , Space
+    , Str "without"
+    , Space
+    , Str "caption:"
+    ]
+, Table
+    ( "" , [] , [] )
+    (Caption Nothing [])
+    [ ( AlignCenter , ColWidth 0.15 )
+    , ( AlignLeft , ColWidth 0.1375 )
+    , ( AlignRight , ColWidth 0.1625 )
+    , ( AlignLeft , ColWidth 0.35 )
+    ]
+    (TableHead
+       ( "" , [] , [] )
+       [ Row
+           ( "" , [] , [] )
+           [ Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "Centered" , SoftBreak , Str "Header" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "Left" , SoftBreak , Str "Aligned" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "Right" , SoftBreak , Str "Aligned" ] ]
+           , Cell
+               ( "" , [] , [] )
+               AlignDefault
+               (RowSpan 1)
+               (ColSpan 1)
+               [ Plain [ Str "Default" , Space , Str "aligned" ] ]
+           ]
+       ])
+    [ TableBody
+        ( "" , [] , [] )
+        (RowHeadColumns 0)
+        []
+        [ Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "First" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "row" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "12.0" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain
+                    [ Str "Example"
+                    , Space
+                    , Str "of"
+                    , Space
+                    , Str "a"
+                    , Space
+                    , Str "row"
+                    , Space
+                    , Str "that"
+                    , Space
+                    , Str "spans"
+                    , SoftBreak
+                    , Str "multiple"
+                    , Space
+                    , Str "lines."
+                    ]
+                ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "Second" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "row" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "5.0" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain
+                    [ Str "Here\8217s"
+                    , Space
+                    , Str "another"
+                    , Space
+                    , Str "one."
+                    , Space
+                    , Str "Note"
+                    , SoftBreak
+                    , Str "the"
+                    , Space
+                    , Str "blank"
+                    , Space
+                    , Str "line"
+                    , Space
+                    , Str "between"
+                    , Space
+                    , Str "rows."
+                    ]
+                ]
+            ]
+        ]
+    ]
+    (TableFoot ( "" , [] , [] ) [])
+, Para
+    [ Str "Table"
+    , Space
+    , Str "without"
+    , Space
+    , Str "column"
+    , Space
+    , Str "headers:"
+    ]
+, Table
+    ( "" , [] , [] )
+    (Caption Nothing [])
+    [ ( AlignRight , ColWidthDefault )
+    , ( AlignLeft , ColWidthDefault )
+    , ( AlignCenter , ColWidthDefault )
+    , ( AlignRight , ColWidthDefault )
+    ]
+    (TableHead ( "" , [] , [] ) [])
+    [ TableBody
+        ( "" , [] , [] )
+        (RowHeadColumns 0)
+        []
+        [ Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "12" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "12" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "12" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "12" ] ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "123" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "123" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "123" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "123" ] ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "1" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "1" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "1" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "1" ] ]
+            ]
+        ]
+    ]
+    (TableFoot ( "" , [] , [] ) [])
+, Para
+    [ Str "Multiline"
+    , Space
+    , Str "table"
+    , Space
+    , Str "without"
+    , Space
+    , Str "column"
+    , Space
+    , Str "headers:"
+    ]
+, Table
+    ( "" , [] , [] )
+    (Caption Nothing [])
+    [ ( AlignCenter , ColWidth 0.15 )
+    , ( AlignLeft , ColWidth 0.1375 )
+    , ( AlignRight , ColWidth 0.1625 )
+    , ( AlignDefault , ColWidth 0.35 )
+    ]
+    (TableHead ( "" , [] , [] ) [])
+    [ TableBody
+        ( "" , [] , [] )
+        (RowHeadColumns 0)
+        []
+        [ Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "First" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "row" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "12.0" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain
+                    [ Str "Example"
+                    , Space
+                    , Str "of"
+                    , Space
+                    , Str "a"
+                    , Space
+                    , Str "row"
+                    , Space
+                    , Str "that"
+                    , Space
+                    , Str "spans"
+                    , SoftBreak
+                    , Str "multiple"
+                    , Space
+                    , Str "lines."
+                    ]
+                ]
+            ]
+        , Row
+            ( "" , [] , [] )
+            [ Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "Second" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "row" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain [ Str "5.0" ] ]
+            , Cell
+                ( "" , [] , [] )
+                AlignDefault
+                (RowSpan 1)
+                (ColSpan 1)
+                [ Plain
+                    [ Str "Here\8217s"
+                    , Space
+                    , Str "another"
+                    , Space
+                    , Str "one."
+                    , Space
+                    , Str "Note"
+                    , SoftBreak
+                    , Str "the"
+                    , Space
+                    , Str "blank"
+                    , Space
+                    , Str "line"
+                    , Space
+                    , Str "between"
+                    , Space
+                    , Str "rows."
+                    ]
+                ]
+            ]
+        ]
+    ]
+    (TableFoot ( "" , [] , [] ) [])
+]
diff --git a/test/tables.opendocument b/test/tables.opendocument
--- a/test/tables.opendocument
+++ b/test/tables.opendocument
@@ -1,4 +1,6 @@
 <text:p text:style-name="Text_20_body">Simple table with caption:</text:p>
+<text:p text:style-name="TableCaption">Demonstration of simple table
+syntax.</text:p>
 <table:table table:name="Table1" table:style-name="Table1">
   <table:table-column table:style-name="Table1.A" />
   <table:table-column table:style-name="Table1.B" />
@@ -6,64 +8,63 @@
   <table:table-column table:style-name="Table1.D" />
   <table:table-header-rows>
     <table:table-row>
-      <table:table-cell table:style-name="Table1.A1" office:value-type="string">
+      <table:table-cell table:style-name="TableHeaderRowCell" office:value-type="string">
         <text:p text:style-name="P1">Right</text:p>
       </table:table-cell>
-      <table:table-cell table:style-name="Table1.A1" office:value-type="string">
+      <table:table-cell table:style-name="TableHeaderRowCell" office:value-type="string">
         <text:p text:style-name="Table_20_Heading">Left</text:p>
       </table:table-cell>
-      <table:table-cell table:style-name="Table1.A1" office:value-type="string">
+      <table:table-cell table:style-name="TableHeaderRowCell" office:value-type="string">
         <text:p text:style-name="P2">Center</text:p>
       </table:table-cell>
-      <table:table-cell table:style-name="Table1.A1" office:value-type="string">
+      <table:table-cell table:style-name="TableHeaderRowCell" office:value-type="string">
         <text:p text:style-name="Table_20_Heading">Default</text:p>
       </table:table-cell>
     </table:table-row>
   </table:table-header-rows>
   <table:table-row>
-    <table:table-cell table:style-name="Table1.A1" office:value-type="string">
+    <table:table-cell table:style-name="TableRowCell" office:value-type="string">
       <text:p text:style-name="P3">12</text:p>
     </table:table-cell>
-    <table:table-cell table:style-name="Table1.A1" office:value-type="string">
+    <table:table-cell table:style-name="TableRowCell" office:value-type="string">
       <text:p text:style-name="Table_20_Contents">12</text:p>
     </table:table-cell>
-    <table:table-cell table:style-name="Table1.A1" office:value-type="string">
+    <table:table-cell table:style-name="TableRowCell" office:value-type="string">
       <text:p text:style-name="P4">12</text:p>
     </table:table-cell>
-    <table:table-cell table:style-name="Table1.A1" office:value-type="string">
+    <table:table-cell table:style-name="TableRowCell" office:value-type="string">
       <text:p text:style-name="Table_20_Contents">12</text:p>
     </table:table-cell>
   </table:table-row>
   <table:table-row>
-    <table:table-cell table:style-name="Table1.A1" office:value-type="string">
+    <table:table-cell table:style-name="TableRowCell" office:value-type="string">
       <text:p text:style-name="P3">123</text:p>
     </table:table-cell>
-    <table:table-cell table:style-name="Table1.A1" office:value-type="string">
+    <table:table-cell table:style-name="TableRowCell" office:value-type="string">
       <text:p text:style-name="Table_20_Contents">123</text:p>
     </table:table-cell>
-    <table:table-cell table:style-name="Table1.A1" office:value-type="string">
+    <table:table-cell table:style-name="TableRowCell" office:value-type="string">
       <text:p text:style-name="P4">123</text:p>
     </table:table-cell>
-    <table:table-cell table:style-name="Table1.A1" office:value-type="string">
+    <table:table-cell table:style-name="TableRowCell" office:value-type="string">
       <text:p text:style-name="Table_20_Contents">123</text:p>
     </table:table-cell>
   </table:table-row>
   <table:table-row>
-    <table:table-cell table:style-name="Table1.A1" office:value-type="string">
+    <table:table-cell table:style-name="TableRowCell" office:value-type="string">
       <text:p text:style-name="P3">1</text:p>
     </table:table-cell>
-    <table:table-cell table:style-name="Table1.A1" office:value-type="string">
+    <table:table-cell table:style-name="TableRowCell" office:value-type="string">
       <text:p text:style-name="Table_20_Contents">1</text:p>
     </table:table-cell>
-    <table:table-cell table:style-name="Table1.A1" office:value-type="string">
+    <table:table-cell table:style-name="TableRowCell" office:value-type="string">
       <text:p text:style-name="P4">1</text:p>
     </table:table-cell>
-    <table:table-cell table:style-name="Table1.A1" office:value-type="string">
+    <table:table-cell table:style-name="TableRowCell" office:value-type="string">
       <text:p text:style-name="Table_20_Contents">1</text:p>
     </table:table-cell>
   </table:table-row>
 </table:table>
-<text:p text:style-name="Table">Demonstration of simple table syntax.</text:p>
 <text:p text:style-name="First_20_paragraph">Simple table without
 caption:</text:p>
 <table:table table:name="Table2" table:style-name="Table2">
@@ -73,65 +74,67 @@
   <table:table-column table:style-name="Table2.D" />
   <table:table-header-rows>
     <table:table-row>
-      <table:table-cell table:style-name="Table2.A1" office:value-type="string">
+      <table:table-cell table:style-name="TableHeaderRowCell" office:value-type="string">
         <text:p text:style-name="P5">Right</text:p>
       </table:table-cell>
-      <table:table-cell table:style-name="Table2.A1" office:value-type="string">
+      <table:table-cell table:style-name="TableHeaderRowCell" office:value-type="string">
         <text:p text:style-name="Table_20_Heading">Left</text:p>
       </table:table-cell>
-      <table:table-cell table:style-name="Table2.A1" office:value-type="string">
+      <table:table-cell table:style-name="TableHeaderRowCell" office:value-type="string">
         <text:p text:style-name="P6">Center</text:p>
       </table:table-cell>
-      <table:table-cell table:style-name="Table2.A1" office:value-type="string">
+      <table:table-cell table:style-name="TableHeaderRowCell" office:value-type="string">
         <text:p text:style-name="Table_20_Heading">Default</text:p>
       </table:table-cell>
     </table:table-row>
   </table:table-header-rows>
   <table:table-row>
-    <table:table-cell table:style-name="Table2.A1" office:value-type="string">
+    <table:table-cell table:style-name="TableRowCell" office:value-type="string">
       <text:p text:style-name="P7">12</text:p>
     </table:table-cell>
-    <table:table-cell table:style-name="Table2.A1" office:value-type="string">
+    <table:table-cell table:style-name="TableRowCell" office:value-type="string">
       <text:p text:style-name="Table_20_Contents">12</text:p>
     </table:table-cell>
-    <table:table-cell table:style-name="Table2.A1" office:value-type="string">
+    <table:table-cell table:style-name="TableRowCell" office:value-type="string">
       <text:p text:style-name="P8">12</text:p>
     </table:table-cell>
-    <table:table-cell table:style-name="Table2.A1" office:value-type="string">
+    <table:table-cell table:style-name="TableRowCell" office:value-type="string">
       <text:p text:style-name="Table_20_Contents">12</text:p>
     </table:table-cell>
   </table:table-row>
   <table:table-row>
-    <table:table-cell table:style-name="Table2.A1" office:value-type="string">
+    <table:table-cell table:style-name="TableRowCell" office:value-type="string">
       <text:p text:style-name="P7">123</text:p>
     </table:table-cell>
-    <table:table-cell table:style-name="Table2.A1" office:value-type="string">
+    <table:table-cell table:style-name="TableRowCell" office:value-type="string">
       <text:p text:style-name="Table_20_Contents">123</text:p>
     </table:table-cell>
-    <table:table-cell table:style-name="Table2.A1" office:value-type="string">
+    <table:table-cell table:style-name="TableRowCell" office:value-type="string">
       <text:p text:style-name="P8">123</text:p>
     </table:table-cell>
-    <table:table-cell table:style-name="Table2.A1" office:value-type="string">
+    <table:table-cell table:style-name="TableRowCell" office:value-type="string">
       <text:p text:style-name="Table_20_Contents">123</text:p>
     </table:table-cell>
   </table:table-row>
   <table:table-row>
-    <table:table-cell table:style-name="Table2.A1" office:value-type="string">
+    <table:table-cell table:style-name="TableRowCell" office:value-type="string">
       <text:p text:style-name="P7">1</text:p>
     </table:table-cell>
-    <table:table-cell table:style-name="Table2.A1" office:value-type="string">
+    <table:table-cell table:style-name="TableRowCell" office:value-type="string">
       <text:p text:style-name="Table_20_Contents">1</text:p>
     </table:table-cell>
-    <table:table-cell table:style-name="Table2.A1" office:value-type="string">
+    <table:table-cell table:style-name="TableRowCell" office:value-type="string">
       <text:p text:style-name="P8">1</text:p>
     </table:table-cell>
-    <table:table-cell table:style-name="Table2.A1" office:value-type="string">
+    <table:table-cell table:style-name="TableRowCell" office:value-type="string">
       <text:p text:style-name="Table_20_Contents">1</text:p>
     </table:table-cell>
   </table:table-row>
 </table:table>
 <text:p text:style-name="First_20_paragraph">Simple table indented two
 spaces:</text:p>
+<text:p text:style-name="TableCaption">Demonstration of simple table
+syntax.</text:p>
 <table:table table:name="Table3" table:style-name="Table3">
   <table:table-column table:style-name="Table3.A" />
   <table:table-column table:style-name="Table3.B" />
@@ -139,66 +142,67 @@
   <table:table-column table:style-name="Table3.D" />
   <table:table-header-rows>
     <table:table-row>
-      <table:table-cell table:style-name="Table3.A1" office:value-type="string">
+      <table:table-cell table:style-name="TableHeaderRowCell" office:value-type="string">
         <text:p text:style-name="P9">Right</text:p>
       </table:table-cell>
-      <table:table-cell table:style-name="Table3.A1" office:value-type="string">
+      <table:table-cell table:style-name="TableHeaderRowCell" office:value-type="string">
         <text:p text:style-name="Table_20_Heading">Left</text:p>
       </table:table-cell>
-      <table:table-cell table:style-name="Table3.A1" office:value-type="string">
+      <table:table-cell table:style-name="TableHeaderRowCell" office:value-type="string">
         <text:p text:style-name="P10">Center</text:p>
       </table:table-cell>
-      <table:table-cell table:style-name="Table3.A1" office:value-type="string">
+      <table:table-cell table:style-name="TableHeaderRowCell" office:value-type="string">
         <text:p text:style-name="Table_20_Heading">Default</text:p>
       </table:table-cell>
     </table:table-row>
   </table:table-header-rows>
   <table:table-row>
-    <table:table-cell table:style-name="Table3.A1" office:value-type="string">
+    <table:table-cell table:style-name="TableRowCell" office:value-type="string">
       <text:p text:style-name="P11">12</text:p>
     </table:table-cell>
-    <table:table-cell table:style-name="Table3.A1" office:value-type="string">
+    <table:table-cell table:style-name="TableRowCell" office:value-type="string">
       <text:p text:style-name="Table_20_Contents">12</text:p>
     </table:table-cell>
-    <table:table-cell table:style-name="Table3.A1" office:value-type="string">
+    <table:table-cell table:style-name="TableRowCell" office:value-type="string">
       <text:p text:style-name="P12">12</text:p>
     </table:table-cell>
-    <table:table-cell table:style-name="Table3.A1" office:value-type="string">
+    <table:table-cell table:style-name="TableRowCell" office:value-type="string">
       <text:p text:style-name="Table_20_Contents">12</text:p>
     </table:table-cell>
   </table:table-row>
   <table:table-row>
-    <table:table-cell table:style-name="Table3.A1" office:value-type="string">
+    <table:table-cell table:style-name="TableRowCell" office:value-type="string">
       <text:p text:style-name="P11">123</text:p>
     </table:table-cell>
-    <table:table-cell table:style-name="Table3.A1" office:value-type="string">
+    <table:table-cell table:style-name="TableRowCell" office:value-type="string">
       <text:p text:style-name="Table_20_Contents">123</text:p>
     </table:table-cell>
-    <table:table-cell table:style-name="Table3.A1" office:value-type="string">
+    <table:table-cell table:style-name="TableRowCell" office:value-type="string">
       <text:p text:style-name="P12">123</text:p>
     </table:table-cell>
-    <table:table-cell table:style-name="Table3.A1" office:value-type="string">
+    <table:table-cell table:style-name="TableRowCell" office:value-type="string">
       <text:p text:style-name="Table_20_Contents">123</text:p>
     </table:table-cell>
   </table:table-row>
   <table:table-row>
-    <table:table-cell table:style-name="Table3.A1" office:value-type="string">
+    <table:table-cell table:style-name="TableRowCell" office:value-type="string">
       <text:p text:style-name="P11">1</text:p>
     </table:table-cell>
-    <table:table-cell table:style-name="Table3.A1" office:value-type="string">
+    <table:table-cell table:style-name="TableRowCell" office:value-type="string">
       <text:p text:style-name="Table_20_Contents">1</text:p>
     </table:table-cell>
-    <table:table-cell table:style-name="Table3.A1" office:value-type="string">
+    <table:table-cell table:style-name="TableRowCell" office:value-type="string">
       <text:p text:style-name="P12">1</text:p>
     </table:table-cell>
-    <table:table-cell table:style-name="Table3.A1" office:value-type="string">
+    <table:table-cell table:style-name="TableRowCell" office:value-type="string">
       <text:p text:style-name="Table_20_Contents">1</text:p>
     </table:table-cell>
   </table:table-row>
 </table:table>
-<text:p text:style-name="Table">Demonstration of simple table syntax.</text:p>
 <text:p text:style-name="First_20_paragraph">Multiline table with
 caption:</text:p>
+<text:p text:style-name="TableCaption">Here’s the caption. It may span multiple
+lines.</text:p>
 <table:table table:name="Table4" table:style-name="Table4">
   <table:table-column table:style-name="Table4.A" />
   <table:table-column table:style-name="Table4.B" />
@@ -206,53 +210,51 @@
   <table:table-column table:style-name="Table4.D" />
   <table:table-header-rows>
     <table:table-row>
-      <table:table-cell table:style-name="Table4.A1" office:value-type="string">
+      <table:table-cell table:style-name="TableHeaderRowCell" office:value-type="string">
         <text:p text:style-name="P13">Centered Header</text:p>
       </table:table-cell>
-      <table:table-cell table:style-name="Table4.A1" office:value-type="string">
+      <table:table-cell table:style-name="TableHeaderRowCell" office:value-type="string">
         <text:p text:style-name="Table_20_Heading">Left Aligned</text:p>
       </table:table-cell>
-      <table:table-cell table:style-name="Table4.A1" office:value-type="string">
+      <table:table-cell table:style-name="TableHeaderRowCell" office:value-type="string">
         <text:p text:style-name="P14">Right Aligned</text:p>
       </table:table-cell>
-      <table:table-cell table:style-name="Table4.A1" office:value-type="string">
+      <table:table-cell table:style-name="TableHeaderRowCell" office:value-type="string">
         <text:p text:style-name="Table_20_Heading">Default aligned</text:p>
       </table:table-cell>
     </table:table-row>
   </table:table-header-rows>
   <table:table-row>
-    <table:table-cell table:style-name="Table4.A1" office:value-type="string">
+    <table:table-cell table:style-name="TableRowCell" office:value-type="string">
       <text:p text:style-name="P15">First</text:p>
     </table:table-cell>
-    <table:table-cell table:style-name="Table4.A1" office:value-type="string">
+    <table:table-cell table:style-name="TableRowCell" office:value-type="string">
       <text:p text:style-name="Table_20_Contents">row</text:p>
     </table:table-cell>
-    <table:table-cell table:style-name="Table4.A1" office:value-type="string">
+    <table:table-cell table:style-name="TableRowCell" office:value-type="string">
       <text:p text:style-name="P16">12.0</text:p>
     </table:table-cell>
-    <table:table-cell table:style-name="Table4.A1" office:value-type="string">
+    <table:table-cell table:style-name="TableRowCell" office:value-type="string">
       <text:p text:style-name="Table_20_Contents">Example of a row that spans
       multiple lines.</text:p>
     </table:table-cell>
   </table:table-row>
   <table:table-row>
-    <table:table-cell table:style-name="Table4.A1" office:value-type="string">
+    <table:table-cell table:style-name="TableRowCell" office:value-type="string">
       <text:p text:style-name="P15">Second</text:p>
     </table:table-cell>
-    <table:table-cell table:style-name="Table4.A1" office:value-type="string">
+    <table:table-cell table:style-name="TableRowCell" office:value-type="string">
       <text:p text:style-name="Table_20_Contents">row</text:p>
     </table:table-cell>
-    <table:table-cell table:style-name="Table4.A1" office:value-type="string">
+    <table:table-cell table:style-name="TableRowCell" office:value-type="string">
       <text:p text:style-name="P16">5.0</text:p>
     </table:table-cell>
-    <table:table-cell table:style-name="Table4.A1" office:value-type="string">
+    <table:table-cell table:style-name="TableRowCell" office:value-type="string">
       <text:p text:style-name="Table_20_Contents">Here’s another one. Note the
       blank line between rows.</text:p>
     </table:table-cell>
   </table:table-row>
 </table:table>
-<text:p text:style-name="Table">Here’s the caption. It may span multiple
-lines.</text:p>
 <text:p text:style-name="First_20_paragraph">Multiline table without
 caption:</text:p>
 <table:table table:name="Table5" table:style-name="Table5">
@@ -262,46 +264,46 @@
   <table:table-column table:style-name="Table5.D" />
   <table:table-header-rows>
     <table:table-row>
-      <table:table-cell table:style-name="Table5.A1" office:value-type="string">
+      <table:table-cell table:style-name="TableHeaderRowCell" office:value-type="string">
         <text:p text:style-name="P17">Centered Header</text:p>
       </table:table-cell>
-      <table:table-cell table:style-name="Table5.A1" office:value-type="string">
+      <table:table-cell table:style-name="TableHeaderRowCell" office:value-type="string">
         <text:p text:style-name="Table_20_Heading">Left Aligned</text:p>
       </table:table-cell>
-      <table:table-cell table:style-name="Table5.A1" office:value-type="string">
+      <table:table-cell table:style-name="TableHeaderRowCell" office:value-type="string">
         <text:p text:style-name="P18">Right Aligned</text:p>
       </table:table-cell>
-      <table:table-cell table:style-name="Table5.A1" office:value-type="string">
+      <table:table-cell table:style-name="TableHeaderRowCell" office:value-type="string">
         <text:p text:style-name="Table_20_Heading">Default aligned</text:p>
       </table:table-cell>
     </table:table-row>
   </table:table-header-rows>
   <table:table-row>
-    <table:table-cell table:style-name="Table5.A1" office:value-type="string">
+    <table:table-cell table:style-name="TableRowCell" office:value-type="string">
       <text:p text:style-name="P19">First</text:p>
     </table:table-cell>
-    <table:table-cell table:style-name="Table5.A1" office:value-type="string">
+    <table:table-cell table:style-name="TableRowCell" office:value-type="string">
       <text:p text:style-name="Table_20_Contents">row</text:p>
     </table:table-cell>
-    <table:table-cell table:style-name="Table5.A1" office:value-type="string">
+    <table:table-cell table:style-name="TableRowCell" office:value-type="string">
       <text:p text:style-name="P20">12.0</text:p>
     </table:table-cell>
-    <table:table-cell table:style-name="Table5.A1" office:value-type="string">
+    <table:table-cell table:style-name="TableRowCell" office:value-type="string">
       <text:p text:style-name="Table_20_Contents">Example of a row that spans
       multiple lines.</text:p>
     </table:table-cell>
   </table:table-row>
   <table:table-row>
-    <table:table-cell table:style-name="Table5.A1" office:value-type="string">
+    <table:table-cell table:style-name="TableRowCell" office:value-type="string">
       <text:p text:style-name="P19">Second</text:p>
     </table:table-cell>
-    <table:table-cell table:style-name="Table5.A1" office:value-type="string">
+    <table:table-cell table:style-name="TableRowCell" office:value-type="string">
       <text:p text:style-name="Table_20_Contents">row</text:p>
     </table:table-cell>
-    <table:table-cell table:style-name="Table5.A1" office:value-type="string">
+    <table:table-cell table:style-name="TableRowCell" office:value-type="string">
       <text:p text:style-name="P20">5.0</text:p>
     </table:table-cell>
-    <table:table-cell table:style-name="Table5.A1" office:value-type="string">
+    <table:table-cell table:style-name="TableRowCell" office:value-type="string">
       <text:p text:style-name="Table_20_Contents">Here’s another one. Note the
       blank line between rows.</text:p>
     </table:table-cell>
@@ -315,44 +317,44 @@
   <table:table-column table:style-name="Table6.C" />
   <table:table-column table:style-name="Table6.D" />
   <table:table-row>
-    <table:table-cell table:style-name="Table6.A1" office:value-type="string">
+    <table:table-cell table:style-name="TableRowCell" office:value-type="string">
       <text:p text:style-name="P24">12</text:p>
     </table:table-cell>
-    <table:table-cell table:style-name="Table6.A1" office:value-type="string">
+    <table:table-cell table:style-name="TableRowCell" office:value-type="string">
       <text:p text:style-name="Table_20_Contents">12</text:p>
     </table:table-cell>
-    <table:table-cell table:style-name="Table6.A1" office:value-type="string">
+    <table:table-cell table:style-name="TableRowCell" office:value-type="string">
       <text:p text:style-name="P25">12</text:p>
     </table:table-cell>
-    <table:table-cell table:style-name="Table6.A1" office:value-type="string">
+    <table:table-cell table:style-name="TableRowCell" office:value-type="string">
       <text:p text:style-name="P26">12</text:p>
     </table:table-cell>
   </table:table-row>
   <table:table-row>
-    <table:table-cell table:style-name="Table6.A1" office:value-type="string">
+    <table:table-cell table:style-name="TableRowCell" office:value-type="string">
       <text:p text:style-name="P24">123</text:p>
     </table:table-cell>
-    <table:table-cell table:style-name="Table6.A1" office:value-type="string">
+    <table:table-cell table:style-name="TableRowCell" office:value-type="string">
       <text:p text:style-name="Table_20_Contents">123</text:p>
     </table:table-cell>
-    <table:table-cell table:style-name="Table6.A1" office:value-type="string">
+    <table:table-cell table:style-name="TableRowCell" office:value-type="string">
       <text:p text:style-name="P25">123</text:p>
     </table:table-cell>
-    <table:table-cell table:style-name="Table6.A1" office:value-type="string">
+    <table:table-cell table:style-name="TableRowCell" office:value-type="string">
       <text:p text:style-name="P26">123</text:p>
     </table:table-cell>
   </table:table-row>
   <table:table-row>
-    <table:table-cell table:style-name="Table6.A1" office:value-type="string">
+    <table:table-cell table:style-name="TableRowCell" office:value-type="string">
       <text:p text:style-name="P24">1</text:p>
     </table:table-cell>
-    <table:table-cell table:style-name="Table6.A1" office:value-type="string">
+    <table:table-cell table:style-name="TableRowCell" office:value-type="string">
       <text:p text:style-name="Table_20_Contents">1</text:p>
     </table:table-cell>
-    <table:table-cell table:style-name="Table6.A1" office:value-type="string">
+    <table:table-cell table:style-name="TableRowCell" office:value-type="string">
       <text:p text:style-name="P25">1</text:p>
     </table:table-cell>
-    <table:table-cell table:style-name="Table6.A1" office:value-type="string">
+    <table:table-cell table:style-name="TableRowCell" office:value-type="string">
       <text:p text:style-name="P26">1</text:p>
     </table:table-cell>
   </table:table-row>
@@ -365,31 +367,31 @@
   <table:table-column table:style-name="Table7.C" />
   <table:table-column table:style-name="Table7.D" />
   <table:table-row>
-    <table:table-cell table:style-name="Table7.A1" office:value-type="string">
+    <table:table-cell table:style-name="TableRowCell" office:value-type="string">
       <text:p text:style-name="P29">First</text:p>
     </table:table-cell>
-    <table:table-cell table:style-name="Table7.A1" office:value-type="string">
+    <table:table-cell table:style-name="TableRowCell" office:value-type="string">
       <text:p text:style-name="Table_20_Contents">row</text:p>
     </table:table-cell>
-    <table:table-cell table:style-name="Table7.A1" office:value-type="string">
+    <table:table-cell table:style-name="TableRowCell" office:value-type="string">
       <text:p text:style-name="P30">12.0</text:p>
     </table:table-cell>
-    <table:table-cell table:style-name="Table7.A1" office:value-type="string">
+    <table:table-cell table:style-name="TableRowCell" office:value-type="string">
       <text:p text:style-name="Table_20_Contents">Example of a row that spans
       multiple lines.</text:p>
     </table:table-cell>
   </table:table-row>
   <table:table-row>
-    <table:table-cell table:style-name="Table7.A1" office:value-type="string">
+    <table:table-cell table:style-name="TableRowCell" office:value-type="string">
       <text:p text:style-name="P29">Second</text:p>
     </table:table-cell>
-    <table:table-cell table:style-name="Table7.A1" office:value-type="string">
+    <table:table-cell table:style-name="TableRowCell" office:value-type="string">
       <text:p text:style-name="Table_20_Contents">row</text:p>
     </table:table-cell>
-    <table:table-cell table:style-name="Table7.A1" office:value-type="string">
+    <table:table-cell table:style-name="TableRowCell" office:value-type="string">
       <text:p text:style-name="P30">5.0</text:p>
     </table:table-cell>
-    <table:table-cell table:style-name="Table7.A1" office:value-type="string">
+    <table:table-cell table:style-name="TableRowCell" office:value-type="string">
       <text:p text:style-name="Table_20_Contents">Here’s another one. Note the
       blank line between rows.</text:p>
     </table:table-cell>
diff --git a/test/tables.org b/test/tables.org
--- a/test/tables.org
+++ b/test/tables.org
@@ -1,51 +1,51 @@
 Simple table with caption:
 
-| Right   | Left   | Center   | Default   |
-|---------+--------+----------+-----------|
-| 12      | 12     | 12       | 12        |
-| 123     | 123    | 123      | 123       |
-| 1       | 1      | 1        | 1         |
-#+CAPTION: Demonstration of simple table syntax.
+| Right | Left | Center | Default |
+|-------+------+--------+---------|
+| 12    | 12   | 12     | 12      |
+| 123   | 123  | 123    | 123     |
+| 1     | 1    | 1      | 1       |
+#+caption: Demonstration of simple table syntax.
 
 Simple table without caption:
 
-| Right   | Left   | Center   | Default   |
-|---------+--------+----------+-----------|
-| 12      | 12     | 12       | 12        |
-| 123     | 123    | 123      | 123       |
-| 1       | 1      | 1        | 1         |
+| Right | Left | Center | Default |
+|-------+------+--------+---------|
+| 12    | 12   | 12     | 12      |
+| 123   | 123  | 123    | 123     |
+| 1     | 1    | 1      | 1       |
 
 Simple table indented two spaces:
 
-| Right   | Left   | Center   | Default   |
-|---------+--------+----------+-----------|
-| 12      | 12     | 12       | 12        |
-| 123     | 123    | 123      | 123       |
-| 1       | 1      | 1        | 1         |
-#+CAPTION: Demonstration of simple table syntax.
+| Right | Left | Center | Default |
+|-------+------+--------+---------|
+| 12    | 12   | 12     | 12      |
+| 123   | 123  | 123    | 123     |
+| 1     | 1    | 1      | 1       |
+#+caption: Demonstration of simple table syntax.
 
 Multiline table with caption:
 
-| Centered Header   | Left Aligned   | Right Aligned   | Default aligned                                         |
-|-------------------+----------------+-----------------+---------------------------------------------------------|
-| First             | row            | 12.0            | Example of a row that spans multiple lines.             |
-| Second            | row            | 5.0             | Here's another one. Note the blank line between rows.   |
-#+CAPTION: Here's the caption. It may span multiple lines.
+| Centered Header | Left Aligned | Right Aligned | Default aligned                                       |
+|-----------------+--------------+---------------+-------------------------------------------------------|
+| First           | row          | 12.0          | Example of a row that spans multiple lines.           |
+| Second          | row          | 5.0           | Here's another one. Note the blank line between rows. |
+#+caption: Here's the caption. It may span multiple lines.
 
 Multiline table without caption:
 
-| Centered Header   | Left Aligned   | Right Aligned   | Default aligned                                         |
-|-------------------+----------------+-----------------+---------------------------------------------------------|
-| First             | row            | 12.0            | Example of a row that spans multiple lines.             |
-| Second            | row            | 5.0             | Here's another one. Note the blank line between rows.   |
+| Centered Header | Left Aligned | Right Aligned | Default aligned                                       |
+|-----------------+--------------+---------------+-------------------------------------------------------|
+| First           | row          | 12.0          | Example of a row that spans multiple lines.           |
+| Second          | row          | 5.0           | Here's another one. Note the blank line between rows. |
 
 Table without column headers:
 
-| 12    | 12    | 12    | 12    |
-| 123   | 123   | 123   | 123   |
-| 1     | 1     | 1     | 1     |
+| 12  | 12  | 12  | 12  |
+| 123 | 123 | 123 | 123 |
+| 1   | 1   | 1   | 1   |
 
 Multiline table without column headers:
 
-| First    | row   | 12.0   | Example of a row that spans multiple lines.             |
-| Second   | row   | 5.0    | Here's another one. Note the blank line between rows.   |
+| First  | row | 12.0 | Example of a row that spans multiple lines.           |
+| Second | row | 5.0  | Here's another one. Note the blank line between rows. |
diff --git a/test/tables.plain b/test/tables.plain
--- a/test/tables.plain
+++ b/test/tables.plain
@@ -28,33 +28,33 @@
 
 Multiline table with caption:
 
-  --------------------------------------------------------------
+  ---------------------------------------------------------------
    Centered   Left              Right Default aligned
     Header    Aligned         Aligned 
-  ----------- ---------- ------------ --------------------------
-     First    row                12.0 Example of a row that
-                                      spans multiple lines.
+  ----------- ---------- ------------ ---------------------------
+     First    row                12.0 Example of a row that spans
+                                      multiple lines.
 
     Second    row                 5.0 Here’s another one. Note
                                       the blank line between
                                       rows.
-  --------------------------------------------------------------
+  ---------------------------------------------------------------
 
   : Here’s the caption. It may span multiple lines.
 
 Multiline table without caption:
 
-  --------------------------------------------------------------
+  ---------------------------------------------------------------
    Centered   Left              Right Default aligned
     Header    Aligned         Aligned 
-  ----------- ---------- ------------ --------------------------
-     First    row                12.0 Example of a row that
-                                      spans multiple lines.
+  ----------- ---------- ------------ ---------------------------
+     First    row                12.0 Example of a row that spans
+                                      multiple lines.
 
     Second    row                 5.0 Here’s another one. Note
                                       the blank line between
                                       rows.
-  --------------------------------------------------------------
+  ---------------------------------------------------------------
 
 Table without column headers:
 
@@ -66,11 +66,11 @@
 
 Multiline table without column headers:
 
-  ----------- ---------- ------------ --------------------------
-     First    row                12.0 Example of a row that
-                                      spans multiple lines.
+  ----------- ---------- ------------ ---------------------------
+     First    row                12.0 Example of a row that spans
+                                      multiple lines.
 
     Second    row                 5.0 Here’s another one. Note
                                       the blank line between
                                       rows.
-  ----------- ---------- ------------ --------------------------
+  ----------- ---------- ------------ ---------------------------
diff --git a/test/tables.rst b/test/tables.rst
--- a/test/tables.rst
+++ b/test/tables.rst
@@ -2,89 +2,81 @@
 
 .. table:: Demonstration of simple table syntax.
 
-   +-------+------+--------+---------+
-   | Right | Left | Center | Default |
-   +=======+======+========+=========+
-   | 12    | 12   | 12     | 12      |
-   +-------+------+--------+---------+
-   | 123   | 123  | 123    | 123     |
-   +-------+------+--------+---------+
-   | 1     | 1    | 1      | 1       |
-   +-------+------+--------+---------+
+   ===== ==== ====== =======
+   Right Left Center Default
+   ===== ==== ====== =======
+   12    12   12     12
+   123   123  123    123
+   1     1    1      1
+   ===== ==== ====== =======
 
 Simple table without caption:
 
-+-------+------+--------+---------+
-| Right | Left | Center | Default |
-+=======+======+========+=========+
-| 12    | 12   | 12     | 12      |
-+-------+------+--------+---------+
-| 123   | 123  | 123    | 123     |
-+-------+------+--------+---------+
-| 1     | 1    | 1      | 1       |
-+-------+------+--------+---------+
+===== ==== ====== =======
+Right Left Center Default
+===== ==== ====== =======
+12    12   12     12
+123   123  123    123
+1     1    1      1
+===== ==== ====== =======
 
 Simple table indented two spaces:
 
 .. table:: Demonstration of simple table syntax.
 
-   +-------+------+--------+---------+
-   | Right | Left | Center | Default |
-   +=======+======+========+=========+
-   | 12    | 12   | 12     | 12      |
-   +-------+------+--------+---------+
-   | 123   | 123  | 123    | 123     |
-   +-------+------+--------+---------+
-   | 1     | 1    | 1      | 1       |
-   +-------+------+--------+---------+
+   ===== ==== ====== =======
+   Right Left Center Default
+   ===== ==== ====== =======
+   12    12   12     12
+   123   123  123    123
+   1     1    1      1
+   ===== ==== ====== =======
 
 Multiline table with caption:
 
 .. table:: Here’s the caption. It may span multiple lines.
 
-   +----------+---------+-----------+-------------------------+
-   | Centered | Left    | Right     | Default aligned         |
-   | Header   | Aligned | Aligned   |                         |
-   +==========+=========+===========+=========================+
-   | First    | row     | 12.0      | Example of a row that   |
-   |          |         |           | spans multiple lines.   |
-   +----------+---------+-----------+-------------------------+
-   | Second   | row     | 5.0       | Here’s another one.     |
-   |          |         |           | Note the blank line     |
-   |          |         |           | between rows.           |
-   +----------+---------+-----------+-------------------------+
+   +-----------+----------+------------+---------------------------+
+   | Centered  | Left     | Right      | Default aligned           |
+   | Header    | Aligned  | Aligned    |                           |
+   +===========+==========+============+===========================+
+   | First     | row      | 12.0       | Example of a row that     |
+   |           |          |            | spans multiple lines.     |
+   +-----------+----------+------------+---------------------------+
+   | Second    | row      | 5.0        | Here’s another one. Note  |
+   |           |          |            | the blank line between    |
+   |           |          |            | rows.                     |
+   +-----------+----------+------------+---------------------------+
 
 Multiline table without caption:
 
-+----------+---------+-----------+-------------------------+
-| Centered | Left    | Right     | Default aligned         |
-| Header   | Aligned | Aligned   |                         |
-+==========+=========+===========+=========================+
-| First    | row     | 12.0      | Example of a row that   |
-|          |         |           | spans multiple lines.   |
-+----------+---------+-----------+-------------------------+
-| Second   | row     | 5.0       | Here’s another one.     |
-|          |         |           | Note the blank line     |
-|          |         |           | between rows.           |
-+----------+---------+-----------+-------------------------+
++-----------+----------+------------+---------------------------+
+| Centered  | Left     | Right      | Default aligned           |
+| Header    | Aligned  | Aligned    |                           |
++===========+==========+============+===========================+
+| First     | row      | 12.0       | Example of a row that     |
+|           |          |            | spans multiple lines.     |
++-----------+----------+------------+---------------------------+
+| Second    | row      | 5.0        | Here’s another one. Note  |
+|           |          |            | the blank line between    |
+|           |          |            | rows.                     |
++-----------+----------+------------+---------------------------+
 
 Table without column headers:
 
-+-----+-----+-----+-----+
-| 12  | 12  | 12  | 12  |
-+-----+-----+-----+-----+
-| 123 | 123 | 123 | 123 |
-+-----+-----+-----+-----+
-| 1   | 1   | 1   | 1   |
-+-----+-----+-----+-----+
+=== === === ===
+12  12  12  12
+123 123 123 123
+1   1   1   1
+=== === === ===
 
 Multiline table without column headers:
 
-+----------+---------+-----------+-------------------------+
-| First    | row     | 12.0      | Example of a row that   |
-|          |         |           | spans multiple lines.   |
-+----------+---------+-----------+-------------------------+
-| Second   | row     | 5.0       | Here’s another one.     |
-|          |         |           | Note the blank line     |
-|          |         |           | between rows.           |
-+----------+---------+-----------+-------------------------+
++-----------+----------+------------+---------------------------+
+| First     | row      | 12.0       | Example of a row that     |
+|           |          |            | spans multiple lines.     |
++-----------+----------+------------+---------------------------+
+| Second    | row      | 5.0        | Here’s another one. Note  |
+|           |          |            | the blank line between    |
+|           |          |            | rows.                     |
++-----------+----------+------------+---------------------------+
diff --git a/test/tables.rtf b/test/tables.rtf
--- a/test/tables.rtf
+++ b/test/tables.rtf
@@ -187,7 +187,7 @@
 {\pard \ql \f0 \sa180 \li0 \fi0 Multiline table with caption:\par}
 {
 \trowd \trgaph120
-\clbrdrb\brdrs\cellx1296\clbrdrb\brdrs\cellx2484\clbrdrb\brdrs\cellx3888\clbrdrb\brdrs\cellx6804
+\clbrdrb\brdrs\cellx1296\clbrdrb\brdrs\cellx2484\clbrdrb\brdrs\cellx3888\clbrdrb\brdrs\cellx6912
 \trkeep\intbl
 {
 {{\pard\intbl \qc \f0 \sa0 \li0 \fi0 Centered Header\par}
@@ -202,7 +202,7 @@
 \intbl\row}
 {
 \trowd \trgaph120
-\cellx1296\cellx2484\cellx3888\cellx6804
+\cellx1296\cellx2484\cellx3888\cellx6912
 \trkeep\intbl
 {
 {{\pard\intbl \qc \f0 \sa0 \li0 \fi0 First\par}
@@ -217,7 +217,7 @@
 \intbl\row}
 {
 \trowd \trgaph120
-\cellx1296\cellx2484\cellx3888\cellx6804
+\cellx1296\cellx2484\cellx3888\cellx6912
 \trkeep\intbl
 {
 {{\pard\intbl \qc \f0 \sa0 \li0 \fi0 Second\par}
@@ -234,7 +234,7 @@
 {\pard \ql \f0 \sa180 \li0 \fi0 Multiline table without caption:\par}
 {
 \trowd \trgaph120
-\clbrdrb\brdrs\cellx1296\clbrdrb\brdrs\cellx2484\clbrdrb\brdrs\cellx3888\clbrdrb\brdrs\cellx6804
+\clbrdrb\brdrs\cellx1296\clbrdrb\brdrs\cellx2484\clbrdrb\brdrs\cellx3888\clbrdrb\brdrs\cellx6912
 \trkeep\intbl
 {
 {{\pard\intbl \qc \f0 \sa0 \li0 \fi0 Centered Header\par}
@@ -249,7 +249,7 @@
 \intbl\row}
 {
 \trowd \trgaph120
-\cellx1296\cellx2484\cellx3888\cellx6804
+\cellx1296\cellx2484\cellx3888\cellx6912
 \trkeep\intbl
 {
 {{\pard\intbl \qc \f0 \sa0 \li0 \fi0 First\par}
@@ -264,7 +264,7 @@
 \intbl\row}
 {
 \trowd \trgaph120
-\cellx1296\cellx2484\cellx3888\cellx6804
+\cellx1296\cellx2484\cellx3888\cellx6912
 \trkeep\intbl
 {
 {{\pard\intbl \qc \f0 \sa0 \li0 \fi0 Second\par}
@@ -328,7 +328,7 @@
 {\pard \ql \f0 \sa180 \li0 \fi0 Multiline table without column headers:\par}
 {
 \trowd \trgaph120
-\cellx1296\cellx2484\cellx3888\cellx6804
+\cellx1296\cellx2484\cellx3888\cellx6912
 \trkeep\intbl
 {
 {{\pard\intbl \qc \f0 \sa0 \li0 \fi0 First\par}
@@ -343,7 +343,7 @@
 \intbl\row}
 {
 \trowd \trgaph120
-\cellx1296\cellx2484\cellx3888\cellx6804
+\cellx1296\cellx2484\cellx3888\cellx6912
 \trkeep\intbl
 {
 {{\pard\intbl \qc \f0 \sa0 \li0 \fi0 Second\par}
@@ -357,4 +357,3 @@
 }
 \intbl\row}
 {\pard \ql \f0 \sa180 \li0 \fi0 \par}
-
diff --git a/test/tables.tei b/test/tables.tei
--- a/test/tables.tei
+++ b/test/tables.tei
@@ -123,12 +123,6 @@
 </table>
 <p>Table without column headers:</p>
 <table>
-  <row role="label">
-    <cell></cell>
-    <cell></cell>
-    <cell></cell>
-    <cell></cell>
-  </row>
   <row>
     <cell><p>12</p></cell>
     <cell><p>12</p></cell>
@@ -150,12 +144,6 @@
 </table>
 <p>Multiline table without column headers:</p>
 <table>
-  <row role="label">
-    <cell></cell>
-    <cell></cell>
-    <cell></cell>
-    <cell></cell>
-  </row>
   <row>
     <cell><p>First</p></cell>
     <cell><p>row</p></cell>
diff --git a/test/tables.texinfo b/test/tables.texinfo
--- a/test/tables.texinfo
+++ b/test/tables.texinfo
@@ -3,7 +3,7 @@
 
 Simple table with caption:
 
-@float
+@float Table
 @multitable {Right} {Left} {Center} {Default} 
 @headitem 
 Right
@@ -55,7 +55,7 @@
 
 Simple table indented two spaces:
 
-@float
+@float Table
 @multitable {Right} {Left} {Center} {Default} 
 @headitem 
 Right
@@ -82,8 +82,8 @@
 @end float
 Multiline table with caption:
 
-@float
-@multitable @columnfractions 0.15 0.14 0.16 0.34 
+@float Table
+@multitable @columnfractions 0.15 0.14 0.16 0.35 
 @headitem 
 Centered Header
  @tab Left Aligned
@@ -104,7 +104,7 @@
 @end float
 Multiline table without caption:
 
-@multitable @columnfractions 0.15 0.14 0.16 0.34 
+@multitable @columnfractions 0.15 0.14 0.16 0.35 
 @headitem 
 Centered Header
  @tab Left Aligned
@@ -144,7 +144,7 @@
 
 Multiline table without column headers:
 
-@multitable @columnfractions 0.15 0.14 0.16 0.34 
+@multitable @columnfractions 0.15 0.14 0.16 0.35 
 @item 
 First
  @tab row
diff --git a/test/tables.textile b/test/tables.textile
--- a/test/tables.textile
+++ b/test/tables.textile
@@ -3,7 +3,7 @@
 <table>
 <caption>Demonstration of simple table syntax.</caption>
 <thead>
-<tr class="header">
+<tr>
 <th align="right">Right</th>
 <th align="left">Left</th>
 <th align="center">Center</th>
@@ -11,19 +11,19 @@
 </tr>
 </thead>
 <tbody>
-<tr class="odd">
+<tr>
 <td align="right">12</td>
 <td align="left">12</td>
 <td align="center">12</td>
 <td align="left">12</td>
 </tr>
-<tr class="even">
+<tr>
 <td align="right">123</td>
 <td align="left">123</td>
 <td align="center">123</td>
 <td align="left">123</td>
 </tr>
-<tr class="odd">
+<tr>
 <td align="right">1</td>
 <td align="left">1</td>
 <td align="center">1</td>
@@ -44,7 +44,7 @@
 <table>
 <caption>Demonstration of simple table syntax.</caption>
 <thead>
-<tr class="header">
+<tr>
 <th align="right">Right</th>
 <th align="left">Left</th>
 <th align="center">Center</th>
@@ -52,19 +52,19 @@
 </tr>
 </thead>
 <tbody>
-<tr class="odd">
+<tr>
 <td align="right">12</td>
 <td align="left">12</td>
 <td align="center">12</td>
 <td align="left">12</td>
 </tr>
-<tr class="even">
+<tr>
 <td align="right">123</td>
 <td align="left">123</td>
 <td align="center">123</td>
 <td align="left">123</td>
 </tr>
-<tr class="odd">
+<tr>
 <td align="right">1</td>
 <td align="left">1</td>
 <td align="center">1</td>
@@ -80,9 +80,9 @@
 <col width="15%" />
 <col width="13%" />
 <col width="16%" />
-<col width="33%" />
+<col width="35%" />
 <thead>
-<tr class="header">
+<tr>
 <th align="center">Centered Header</th>
 <th align="left">Left Aligned</th>
 <th align="right">Right Aligned</th>
@@ -90,13 +90,13 @@
 </tr>
 </thead>
 <tbody>
-<tr class="odd">
+<tr>
 <td align="center">First</td>
 <td align="left">row</td>
 <td align="right">12.0</td>
 <td align="left">Example of a row that spans multiple lines.</td>
 </tr>
-<tr class="even">
+<tr>
 <td align="center">Second</td>
 <td align="left">row</td>
 <td align="right">5.0</td>
@@ -111,9 +111,9 @@
 <col width="15%" />
 <col width="13%" />
 <col width="16%" />
-<col width="33%" />
+<col width="35%" />
 <thead>
-<tr class="header">
+<tr>
 <th align="center">Centered Header</th>
 <th align="left">Left Aligned</th>
 <th align="right">Right Aligned</th>
@@ -121,13 +121,13 @@
 </tr>
 </thead>
 <tbody>
-<tr class="odd">
+<tr>
 <td align="center">First</td>
 <td align="left">row</td>
 <td align="right">12.0</td>
 <td align="left">Example of a row that spans multiple lines.</td>
 </tr>
-<tr class="even">
+<tr>
 <td align="center">Second</td>
 <td align="left">row</td>
 <td align="right">5.0</td>
@@ -148,15 +148,15 @@
 <col width="15%" />
 <col width="13%" />
 <col width="16%" />
-<col width="33%" />
+<col width="35%" />
 <tbody>
-<tr class="odd">
+<tr>
 <td align="center">First</td>
 <td align="left">row</td>
 <td align="right">12.0</td>
 <td align="left">Example of a row that spans multiple lines.</td>
 </tr>
-<tr class="even">
+<tr>
 <td align="center">Second</td>
 <td align="left">row</td>
 <td align="right">5.0</td>
@@ -164,4 +164,3 @@
 </tr>
 </tbody>
 </table>
-
diff --git a/test/tables.txt b/test/tables.txt
--- a/test/tables.txt
+++ b/test/tables.txt
@@ -72,4 +72,3 @@
    Second   row                5.0  Here's another one.  Note
                                     the blank line between rows.
 ----------  ---------  -----------  ---------------------------
-
diff --git a/test/tables.typst b/test/tables.typst
new file mode 100644
--- /dev/null
+++ b/test/tables.typst
@@ -0,0 +1,105 @@
+Simple table with caption:
+
+#figure(
+  align(center)[#table(
+    columns: 4,
+    align: (right,left,center,auto,),
+    table.header([Right], [Left], [Center], [Default],),
+    table.hline(),
+    [12], [12], [12], [12],
+    [123], [123], [123], [123],
+    [1], [1], [1], [1],
+  )]
+  , caption: [Demonstration of simple table syntax.]
+  , kind: table
+  )
+
+Simple table without caption:
+
+#figure(
+  align(center)[#table(
+    columns: 4,
+    align: (right,left,center,auto,),
+    table.header([Right], [Left], [Center], [Default],),
+    table.hline(),
+    [12], [12], [12], [12],
+    [123], [123], [123], [123],
+    [1], [1], [1], [1],
+  )]
+  , kind: table
+  )
+
+Simple table indented two spaces:
+
+#figure(
+  align(center)[#table(
+    columns: 4,
+    align: (right,left,center,auto,),
+    table.header([Right], [Left], [Center], [Default],),
+    table.hline(),
+    [12], [12], [12], [12],
+    [123], [123], [123], [123],
+    [1], [1], [1], [1],
+  )]
+  , caption: [Demonstration of simple table syntax.]
+  , kind: table
+  )
+
+Multiline table with caption:
+
+#figure(
+  align(center)[#table(
+    columns: (15%, 13.75%, 16.25%, 35%),
+    align: (center,left,right,left,),
+    table.header([Centered Header], [Left Aligned], [Right Aligned], [Default
+      aligned],),
+    table.hline(),
+    [First], [row], [12.0], [Example of a row that spans multiple lines.],
+    [Second], [row], [5.0], [Here's another one. Note the blank line between
+    rows.],
+  )]
+  , caption: [Here's the caption. It may span multiple lines.]
+  , kind: table
+  )
+
+Multiline table without caption:
+
+#figure(
+  align(center)[#table(
+    columns: (15%, 13.75%, 16.25%, 35%),
+    align: (center,left,right,left,),
+    table.header([Centered Header], [Left Aligned], [Right Aligned], [Default
+      aligned],),
+    table.hline(),
+    [First], [row], [12.0], [Example of a row that spans multiple lines.],
+    [Second], [row], [5.0], [Here's another one. Note the blank line between
+    rows.],
+  )]
+  , kind: table
+  )
+
+Table without column headers:
+
+#figure(
+  align(center)[#table(
+    columns: 4,
+    align: (right,left,center,right,),
+    [12], [12], [12], [12],
+    [123], [123], [123], [123],
+    [1], [1], [1], [1],
+  )]
+  , kind: table
+  )
+
+Multiline table without column headers:
+
+#figure(
+  align(center)[#table(
+    columns: (15%, 13.75%, 16.25%, 35%),
+    align: (center,left,right,auto,),
+    [First], [row], [12.0], [Example of a row that spans multiple lines.],
+    [Second], [row], [5.0], [Here's another one. Note the blank line between
+    rows.],
+  )]
+  , kind: table
+  )
diff --git a/test/tables.vimdoc b/test/tables.vimdoc
new file mode 100644
--- /dev/null
+++ b/test/tables.vimdoc
@@ -0,0 +1,65 @@
+Simple table with caption:
+
+      Right Left    Center  Default ~
+         12 12        12    12
+        123 123      123    123
+          1 1         1     1
+
+    Demonstration of simple table syntax.
+
+Simple table without caption:
+
+      Right Left    Center  Default ~
+         12 12        12    12
+        123 123      123    123
+          1 1         1     1
+
+Simple table indented two spaces:
+
+      Right Left    Center  Default ~
+         12 12        12    12
+        123 123      123    123
+          1 1         1     1
+
+    Demonstration of simple table syntax.
+
+Multiline table with caption:
+
+     Centered  Left           Right Default aligned
+      Header   Aligned      Aligned  ~
+
+      First    row             12.0 Example of a row that
+                                    spans multiple lines.
+
+      Second   row              5.0 Here's another one.
+                                    Note the blank line
+                                    between rows.
+
+    Here's the caption. It may span multiple lines.
+
+Multiline table without caption:
+
+     Centered  Left           Right Default aligned
+      Header   Aligned      Aligned  ~
+
+      First    row             12.0 Example of a row that
+                                    spans multiple lines.
+
+      Second   row              5.0 Here's another one.
+                                    Note the blank line
+                                    between rows.
+
+Table without column headers:
+
+       12 12     12      12
+      123 123    123    123
+        1 1       1       1
+
+Multiline table without column headers:
+
+      First   row            12.0 Example of a row that
+                                  spans multiple lines.
+
+     Second   row             5.0 Here's another one.
+                                  Note the blank line
+                                  between rows.
diff --git a/test/tables.xwiki b/test/tables.xwiki
new file mode 100644
--- /dev/null
+++ b/test/tables.xwiki
@@ -0,0 +1,45 @@
+Simple table with caption:
+
+|=Right |=Left |=Center |=Default
+|12 |12 |12 |12
+|123 |123 |123 |123
+|1 |1 |1 |1
+
+Simple table without caption:
+
+|=Right |=Left |=Center |=Default
+|12 |12 |12 |12
+|123 |123 |123 |123
+|1 |1 |1 |1
+
+Simple table indented two spaces:
+
+|=Right |=Left |=Center |=Default
+|12 |12 |12 |12
+|123 |123 |123 |123
+|1 |1 |1 |1
+
+Multiline table with caption:
+
+|=Centered Header |=Left Aligned |=Right Aligned |=Default aligned
+|First |row |12.0 |Example of a row that spans multiple lines.
+|Second |row |5.0 |Here’s another one. Note the blank line between rows.
+
+Multiline table without caption:
+
+|=Centered Header |=Left Aligned |=Right Aligned |=Default aligned
+|First |row |12.0 |Example of a row that spans multiple lines.
+|Second |row |5.0 |Here’s another one. Note the blank line between rows.
+
+Table without column headers:
+
+|= |= |= |=
+|12 |12 |12 |12
+|123 |123 |123 |123
+|1 |1 |1 |1
+
+Multiline table without column headers:
+
+|= |= |= |=
+|First |row |12.0 |Example of a row that spans multiple lines.
+|Second |row |5.0 |Here’s another one. Note the blank line between rows.
diff --git a/test/tables.zimwiki b/test/tables.zimwiki
--- a/test/tables.zimwiki
+++ b/test/tables.zimwiki
@@ -53,4 +53,3 @@
 |:--------:|:----|-----:|-----------------------------------------------------|
 |  First   |row  |  12.0|Example of a row that spans multiple lines.          |
 |  Second  |row  |   5.0|Here’s another one. Note the blank line between rows.|
-
diff --git a/test/tables/nordics.html4 b/test/tables/nordics.html4
new file mode 100644
--- /dev/null
+++ b/test/tables/nordics.html4
@@ -0,0 +1,59 @@
+<table id="nordics" source="wikipedia">
+<caption><p>States belonging to the <em>Nordics.</em></p></caption>
+<colgroup>
+<col width="30%" />
+<col width="30%" />
+<col width="20%" />
+<col width="20%" />
+</colgroup>
+<thead class="simple-head">
+<tr>
+<th align="center">Name</th>
+<th align="center">Capital</th>
+<th align="center">Population<br />
+(in 2018)</th>
+<th align="center">Area<br />
+(in km<sup>2</sup>)</th>
+</tr>
+</thead>
+<tbody class="souvereign-states">
+<tr class="country">
+<th align="center">Denmark</th>
+<td align="left">Copenhagen</td>
+<td align="left">5,809,502</td>
+<td align="left">43,094</td>
+</tr>
+<tr class="country">
+<th align="center">Finland</th>
+<td align="left">Helsinki</td>
+<td align="left">5,537,364</td>
+<td align="left">338,145</td>
+</tr>
+<tr class="country">
+<th align="center">Iceland</th>
+<td align="left">Reykjavik</td>
+<td align="left">343,518</td>
+<td align="left">103,000</td>
+</tr>
+<tr class="country">
+<th align="center">Norway</th>
+<td align="left">Oslo</td>
+<td align="left">5,372,191</td>
+<td align="left">323,802</td>
+</tr>
+<tr class="country">
+<th align="center">Sweden</th>
+<td align="left">Stockholm</td>
+<td align="left">10,313,447</td>
+<td align="left">450,295</td>
+</tr>
+</tbody><tfoot>
+<tr id="summary">
+<td align="center">Total</td>
+<td align="left"></td>
+<td id="total-population" align="left">27,376,022</td>
+<td id="total-area" align="left">1,258,336</td>
+</tr>
+</tfoot>
+
+</table>
diff --git a/test/tables/nordics.html5 b/test/tables/nordics.html5
new file mode 100644
--- /dev/null
+++ b/test/tables/nordics.html5
@@ -0,0 +1,59 @@
+<table id="nordics" data-source="wikipedia">
+<caption><p>States belonging to the <em>Nordics.</em></p></caption>
+<colgroup>
+<col style="width: 30%" />
+<col style="width: 30%" />
+<col style="width: 20%" />
+<col style="width: 20%" />
+</colgroup>
+<thead class="simple-head">
+<tr>
+<th style="text-align: center;">Name</th>
+<th style="text-align: center;">Capital</th>
+<th style="text-align: center;">Population<br />
+(in 2018)</th>
+<th style="text-align: center;">Area<br />
+(in km<sup>2</sup>)</th>
+</tr>
+</thead>
+<tbody class="souvereign-states">
+<tr class="country">
+<th style="text-align: center;">Denmark</th>
+<td style="text-align: left;">Copenhagen</td>
+<td style="text-align: left;">5,809,502</td>
+<td style="text-align: left;">43,094</td>
+</tr>
+<tr class="country">
+<th style="text-align: center;">Finland</th>
+<td style="text-align: left;">Helsinki</td>
+<td style="text-align: left;">5,537,364</td>
+<td style="text-align: left;">338,145</td>
+</tr>
+<tr class="country">
+<th style="text-align: center;">Iceland</th>
+<td style="text-align: left;">Reykjavik</td>
+<td style="text-align: left;">343,518</td>
+<td style="text-align: left;">103,000</td>
+</tr>
+<tr class="country">
+<th style="text-align: center;">Norway</th>
+<td style="text-align: left;">Oslo</td>
+<td style="text-align: left;">5,372,191</td>
+<td style="text-align: left;">323,802</td>
+</tr>
+<tr class="country">
+<th style="text-align: center;">Sweden</th>
+<td style="text-align: left;">Stockholm</td>
+<td style="text-align: left;">10,313,447</td>
+<td style="text-align: left;">450,295</td>
+</tr>
+</tbody><tfoot>
+<tr id="summary">
+<td style="text-align: center;">Total</td>
+<td style="text-align: left;"></td>
+<td id="total-population" style="text-align: left;">27,376,022</td>
+<td id="total-area" style="text-align: left;">1,258,336</td>
+</tr>
+</tfoot>
+
+</table>
diff --git a/test/tables/nordics.jats_archiving b/test/tables/nordics.jats_archiving
new file mode 100644
--- /dev/null
+++ b/test/tables/nordics.jats_archiving
@@ -0,0 +1,56 @@
+<table-wrap>
+  <caption>
+    <p>States belonging to the <italic>Nordics.</italic></p>
+  </caption>
+  <table id="nordics">
+    <colgroup>
+      <col width="30%" />
+      <col width="30%" />
+      <col width="20%" />
+      <col width="20%" />
+    </colgroup>
+    <thead>
+      <tr>
+        <th align="center">Name</th>
+        <th align="center">Capital</th>
+        <th align="center">Population<break/>(in 2018)</th>
+        <th align="center">Area<break/>(in km<sup>2</sup>)</th>
+      </tr>
+    </thead>
+    <tfoot>
+      <tr id="summary">
+        <td align="center">Total</td>
+        <td align="left"></td>
+        <td align="left" id="total-population">27,376,022</td>
+        <td align="left" id="total-area">1,258,336</td>
+      </tr>
+    </tfoot>
+    <tbody>
+      <tr>
+        <th align="center">Denmark</th><td align="left">Copenhagen</td>
+        <td align="left">5,809,502</td>
+        <td align="left">43,094</td>
+      </tr>
+      <tr>
+        <th align="center">Finland</th><td align="left">Helsinki</td>
+        <td align="left">5,537,364</td>
+        <td align="left">338,145</td>
+      </tr>
+      <tr>
+        <th align="center">Iceland</th><td align="left">Reykjavik</td>
+        <td align="left">343,518</td>
+        <td align="left">103,000</td>
+      </tr>
+      <tr>
+        <th align="center">Norway</th><td align="left">Oslo</td>
+        <td align="left">5,372,191</td>
+        <td align="left">323,802</td>
+      </tr>
+      <tr>
+        <th align="center">Sweden</th><td align="left">Stockholm</td>
+        <td align="left">10,313,447</td>
+        <td align="left">450,295</td>
+      </tr>
+    </tbody>
+  </table>
+</table-wrap>
diff --git a/test/tables/nordics.latex b/test/tables/nordics.latex
new file mode 100644
--- /dev/null
+++ b/test/tables/nordics.latex
@@ -0,0 +1,45 @@
+\begin{longtable}[]{@{}
+  >{\centering\arraybackslash}p{(\linewidth - 6\tabcolsep) * \real{0.3000}}
+  >{\raggedright\arraybackslash}p{(\linewidth - 6\tabcolsep) * \real{0.3000}}
+  >{\raggedright\arraybackslash}p{(\linewidth - 6\tabcolsep) * \real{0.2000}}
+  >{\raggedright\arraybackslash}p{(\linewidth - 6\tabcolsep) * \real{0.2000}}@{}}
+\caption[Nordic countries]{States belonging to the
+\emph{Nordics.}}\label{nordics}\tabularnewline
+\toprule\noalign{}
+\begin{minipage}[b]{\linewidth}\centering
+Name
+\end{minipage} & \begin{minipage}[b]{\linewidth}\centering
+Capital
+\end{minipage} & \begin{minipage}[b]{\linewidth}\centering
+Population\\
+(in 2018)\strut
+\end{minipage} & \begin{minipage}[b]{\linewidth}\centering
+Area\\
+(in km\textsuperscript{2})\strut
+\end{minipage} \\
+\midrule\noalign{}
+\endfirsthead
+\toprule\noalign{}
+\begin{minipage}[b]{\linewidth}\centering
+Name
+\end{minipage} & \begin{minipage}[b]{\linewidth}\centering
+Capital
+\end{minipage} & \begin{minipage}[b]{\linewidth}\centering
+Population\\
+(in 2018)\strut
+\end{minipage} & \begin{minipage}[b]{\linewidth}\centering
+Area\\
+(in km\textsuperscript{2})\strut
+\end{minipage} \\
+\midrule\noalign{}
+\endhead
+\midrule\noalign{}
+Total & & 27,376,022 & 1,258,336 \\
+\bottomrule\noalign{}
+\endlastfoot
+Denmark & Copenhagen & 5,809,502 & 43,094 \\
+Finland & Helsinki & 5,537,364 & 338,145 \\
+Iceland & Reykjavik & 343,518 & 103,000 \\
+Norway & Oslo & 5,372,191 & 323,802 \\
+Sweden & Stockholm & 10,313,447 & 450,295 \\
+\end{longtable}
diff --git a/test/tables/nordics.markdown b/test/tables/nordics.markdown
new file mode 100644
--- /dev/null
+++ b/test/tables/nordics.markdown
@@ -0,0 +1,18 @@
++-----------------------+-----------------------+---------------+---------------+
+| Name                  | Capital               | Population\   | Area\         |
+|                       |                       | (in 2018)     | (in km^2^)    |
++:=====================:+:======================+:==============+:==============+
+| Denmark               | Copenhagen            | 5,809,502     | 43,094        |
++-----------------------+-----------------------+---------------+---------------+
+| Finland               | Helsinki              | 5,537,364     | 338,145       |
++-----------------------+-----------------------+---------------+---------------+
+| Iceland               | Reykjavik             | 343,518       | 103,000       |
++-----------------------+-----------------------+---------------+---------------+
+| Norway                | Oslo                  | 5,372,191     | 323,802       |
++-----------------------+-----------------------+---------------+---------------+
+| Sweden                | Stockholm             | 10,313,447    | 450,295       |
++=======================+=======================+===============+===============+
+| Total                 |                       | 27,376,022    | 1,258,336     |
++=======================+=======================+===============+===============+
+
+: States belonging to the *Nordics.* {#nordics source="wikipedia"}
diff --git a/test/tables/nordics.mediawiki b/test/tables/nordics.mediawiki
new file mode 100644
--- /dev/null
+++ b/test/tables/nordics.mediawiki
@@ -0,0 +1,40 @@
+{| id="nordics" class="wikitable" data-source="wikipedia"
+|+ States belonging to the ''Nordics.''
+|-
+! style="text-align: center;"| Name
+! style="text-align: center;"| Capital
+! style="text-align: center;"| Population<br />
+(in 2018)
+! style="text-align: center;"| Area<br />
+(in km<sup>2</sup>)
+|- class="country"
+! style="text-align: center;"| Denmark
+| style="text-align: left;"| Copenhagen
+| style="text-align: left;"| 5,809,502
+| style="text-align: left;"| 43,094
+|- class="country"
+! style="text-align: center;"| Finland
+| style="text-align: left;"| Helsinki
+| style="text-align: left;"| 5,537,364
+| style="text-align: left;"| 338,145
+|- class="country"
+! style="text-align: center;"| Iceland
+| style="text-align: left;"| Reykjavik
+| style="text-align: left;"| 343,518
+| style="text-align: left;"| 103,000
+|- class="country"
+! style="text-align: center;"| Norway
+| style="text-align: left;"| Oslo
+| style="text-align: left;"| 5,372,191
+| style="text-align: left;"| 323,802
+|- class="country"
+! style="text-align: center;"| Sweden
+| style="text-align: left;"| Stockholm
+| style="text-align: left;"| 10,313,447
+| style="text-align: left;"| 450,295
+|- id="summary"
+! style="text-align: center;"| Total
+! style="text-align: left;"|
+! id="total-population" style="text-align: left;"| 27,376,022
+! id="total-area" style="text-align: left;"| 1,258,336
+|}
diff --git a/test/tables/nordics.native b/test/tables/nordics.native
new file mode 100644
--- /dev/null
+++ b/test/tables/nordics.native
@@ -0,0 +1,73 @@
+[Table ("nordics",[],[("source","wikipedia")]) (Caption (Just [Str "Nordic",Space,Str "countries"])
+ [Para [Str "States",Space,Str "belonging",Space,Str "to",Space,Str "the",Space,Emph [Str "Nordics."]]])
+ [(AlignCenter,ColWidth 0.3)
+ ,(AlignLeft,ColWidth 0.3)
+ ,(AlignLeft,ColWidth 0.2)
+ ,(AlignLeft,ColWidth 0.2)]
+ (TableHead ("",["simple-head"],[])
+ [Row ("",[],[])
+  [Cell ("",[],[]) AlignCenter (RowSpan 1) (ColSpan 1)
+   [Plain [Str "Name"]]
+  ,Cell ("",[],[]) AlignCenter (RowSpan 1) (ColSpan 1)
+   [Plain [Str "Capital"]]
+  ,Cell ("",[],[]) AlignCenter (RowSpan 1) (ColSpan 1)
+   [Plain [Str "Population",LineBreak,Str "(in",Space,Str "2018)"]]
+  ,Cell ("",[],[]) AlignCenter (RowSpan 1) (ColSpan 1)
+   [Plain [Str "Area",LineBreak,Str "(in",Space,Str "km",Superscript [Str "2"],Str ")"]]]])
+ [(TableBody ("",["souvereign-states"],[]) (RowHeadColumns 1)
+  []
+  [Row ("",["country"],[])
+   [Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "Denmark"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "Copenhagen"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "5,809,502"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "43,094"]]]
+  ,Row ("",["country"],[])
+   [Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "Finland"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "Helsinki"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "5,537,364"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "338,145"]]]
+  ,Row ("",["country"],[])
+   [Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "Iceland"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "Reykjavik"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "343,518"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "103,000"]]]
+  ,Row ("",["country"],[])
+   [Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "Norway"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "Oslo"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "5,372,191"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "323,802"]]]
+  ,Row ("",["country"],[])
+   [Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "Sweden"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "Stockholm"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "10,313,447"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "450,295"]]]])]
+ (TableFoot ("",[],[])
+ [Row ("summary",[],[])
+  [Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+   [Plain [Str "Total"]]
+  ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+   []
+  ,Cell ("total-population",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+   [Plain [Str "27,376,022"]]
+  ,Cell ("total-area",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+   [Plain [Str "1,258,336"]]]])]
diff --git a/test/tables/nordics.typst b/test/tables/nordics.typst
new file mode 100644
--- /dev/null
+++ b/test/tables/nordics.typst
@@ -0,0 +1,21 @@
+#figure(
+  align(center)[#table(
+    columns: (30%, 30%, 20%, 20%),
+    align: (center,left,left,left,),
+    table.header(table.cell(align: center)[Name], table.cell(align: center)[Capital], table.cell(align: center)[Population
+      \ (in 2018)], table.cell(align: center)[Area \ (in km#super[2])],),
+    table.hline(),
+    [Denmark], [Copenhagen], [5,809,502], [43,094],
+    [Finland], [Helsinki], [5,537,364], [338,145],
+    [Iceland], [Reykjavik], [343,518], [103,000],
+    [Norway], [Oslo], [5,372,191], [323,802],
+    [Sweden], [Stockholm], [10,313,447], [450,295],
+    table.hline(),
+    table.footer([Total], [], [27,376,022], [1,258,336],),
+  )]
+  , caption: [States belonging to the #emph[Nordics.]
+
+  ]
+  , kind: table
+  )
+<nordics>
diff --git a/test/tables/planets.html4 b/test/tables/planets.html4
new file mode 100644
--- /dev/null
+++ b/test/tables/planets.html4
@@ -0,0 +1,133 @@
+<table>
+<caption><p>Data about the planets of our solar system.</p></caption>
+<thead>
+<tr>
+<th colspan="2" align="center"></th>
+<th>Name</th>
+<th align="right">Mass (10^24kg)</th>
+<th align="right">Diameter (km)</th>
+<th align="right">Density (kg/m^3)</th>
+<th align="right">Gravity (m/s^2)</th>
+<th align="right">Length of day (hours)</th>
+<th align="right">Distance from Sun (10^6km)</th>
+<th align="right">Mean temperature (C)</th>
+<th align="right">Number of moons</th>
+<th>Notes</th>
+</tr>
+</thead>
+<tbody>
+<tr>
+<th colspan="2" rowspan="4" align="center">Terrestrial planets</th>
+<th>Mercury</th>
+<td align="right">0.330</td>
+<td align="right">4,879</td>
+<td align="right">5427</td>
+<td align="right">3.7</td>
+<td align="right">4222.6</td>
+<td align="right">57.9</td>
+<td align="right">167</td>
+<td align="right">0</td>
+<td>Closest to the Sun</td>
+</tr>
+<tr>
+<th>Venus</th>
+<td align="right">4.87</td>
+<td align="right">12,104</td>
+<td align="right">5243</td>
+<td align="right">8.9</td>
+<td align="right">2802.0</td>
+<td align="right">108.2</td>
+<td align="right">464</td>
+<td align="right">0</td>
+<td></td>
+</tr>
+<tr>
+<th>Earth</th>
+<td align="right">5.97</td>
+<td align="right">12,756</td>
+<td align="right">5514</td>
+<td align="right">9.8</td>
+<td align="right">24.0</td>
+<td align="right">149.6</td>
+<td align="right">15</td>
+<td align="right">1</td>
+<td>Our world</td>
+</tr>
+<tr>
+<th>Mars</th>
+<td align="right">0.642</td>
+<td align="right">6,792</td>
+<td align="right">3933</td>
+<td align="right">3.7</td>
+<td align="right">24.7</td>
+<td align="right">227.9</td>
+<td align="right">-65</td>
+<td align="right">2</td>
+<td>The red planet</td>
+</tr>
+<tr>
+<th rowspan="4" align="center">Jovian planets</th>
+<th rowspan="2" align="center">Gas giants</th>
+<th>Jupiter</th>
+<td align="right">1898</td>
+<td align="right">142,984</td>
+<td align="right">1326</td>
+<td align="right">23.1</td>
+<td align="right">9.9</td>
+<td align="right">778.6</td>
+<td align="right">-110</td>
+<td align="right">67</td>
+<td>The largest planet</td>
+</tr>
+<tr>
+<th>Saturn</th>
+<td align="right">568</td>
+<td align="right">120,536</td>
+<td align="right">687</td>
+<td align="right">9.0</td>
+<td align="right">10.7</td>
+<td align="right">1433.5</td>
+<td align="right">-140</td>
+<td align="right">62</td>
+<td></td>
+</tr>
+<tr>
+<th rowspan="2" align="center">Ice giants</th>
+<th>Uranus</th>
+<td align="right">86.8</td>
+<td align="right">51,118</td>
+<td align="right">1271</td>
+<td align="right">8.7</td>
+<td align="right">17.2</td>
+<td align="right">2872.5</td>
+<td align="right">-195</td>
+<td align="right">27</td>
+<td></td>
+</tr>
+<tr>
+<th>Neptune</th>
+<td align="right">102</td>
+<td align="right">49,528</td>
+<td align="right">1638</td>
+<td align="right">11.0</td>
+<td align="right">16.1</td>
+<td align="right">4495.1</td>
+<td align="right">-200</td>
+<td align="right">14</td>
+<td></td>
+</tr>
+<tr>
+<th colspan="2" align="center">Dwarf planets</th>
+<th>Pluto</th>
+<td align="right">0.0146</td>
+<td align="right">2,370</td>
+<td align="right">2095</td>
+<td align="right">0.7</td>
+<td align="right">153.3</td>
+<td align="right">5906.4</td>
+<td align="right">-225</td>
+<td align="right">5</td>
+<td>Declassified as a planet in 2006.</td>
+</tr>
+</tbody>
+</table>
diff --git a/test/tables/planets.html5 b/test/tables/planets.html5
new file mode 100644
--- /dev/null
+++ b/test/tables/planets.html5
@@ -0,0 +1,133 @@
+<table>
+<caption><p>Data about the planets of our solar system.</p></caption>
+<thead>
+<tr>
+<th colspan="2" style="text-align: center;"></th>
+<th>Name</th>
+<th style="text-align: right;">Mass (10^24kg)</th>
+<th style="text-align: right;">Diameter (km)</th>
+<th style="text-align: right;">Density (kg/m^3)</th>
+<th style="text-align: right;">Gravity (m/s^2)</th>
+<th style="text-align: right;">Length of day (hours)</th>
+<th style="text-align: right;">Distance from Sun (10^6km)</th>
+<th style="text-align: right;">Mean temperature (C)</th>
+<th style="text-align: right;">Number of moons</th>
+<th>Notes</th>
+</tr>
+</thead>
+<tbody>
+<tr>
+<th colspan="2" rowspan="4" style="text-align: center;">Terrestrial planets</th>
+<th>Mercury</th>
+<td style="text-align: right;">0.330</td>
+<td style="text-align: right;">4,879</td>
+<td style="text-align: right;">5427</td>
+<td style="text-align: right;">3.7</td>
+<td style="text-align: right;">4222.6</td>
+<td style="text-align: right;">57.9</td>
+<td style="text-align: right;">167</td>
+<td style="text-align: right;">0</td>
+<td>Closest to the Sun</td>
+</tr>
+<tr>
+<th>Venus</th>
+<td style="text-align: right;">4.87</td>
+<td style="text-align: right;">12,104</td>
+<td style="text-align: right;">5243</td>
+<td style="text-align: right;">8.9</td>
+<td style="text-align: right;">2802.0</td>
+<td style="text-align: right;">108.2</td>
+<td style="text-align: right;">464</td>
+<td style="text-align: right;">0</td>
+<td></td>
+</tr>
+<tr>
+<th>Earth</th>
+<td style="text-align: right;">5.97</td>
+<td style="text-align: right;">12,756</td>
+<td style="text-align: right;">5514</td>
+<td style="text-align: right;">9.8</td>
+<td style="text-align: right;">24.0</td>
+<td style="text-align: right;">149.6</td>
+<td style="text-align: right;">15</td>
+<td style="text-align: right;">1</td>
+<td>Our world</td>
+</tr>
+<tr>
+<th>Mars</th>
+<td style="text-align: right;">0.642</td>
+<td style="text-align: right;">6,792</td>
+<td style="text-align: right;">3933</td>
+<td style="text-align: right;">3.7</td>
+<td style="text-align: right;">24.7</td>
+<td style="text-align: right;">227.9</td>
+<td style="text-align: right;">-65</td>
+<td style="text-align: right;">2</td>
+<td>The red planet</td>
+</tr>
+<tr>
+<th rowspan="4" style="text-align: center;">Jovian planets</th>
+<th rowspan="2" style="text-align: center;">Gas giants</th>
+<th>Jupiter</th>
+<td style="text-align: right;">1898</td>
+<td style="text-align: right;">142,984</td>
+<td style="text-align: right;">1326</td>
+<td style="text-align: right;">23.1</td>
+<td style="text-align: right;">9.9</td>
+<td style="text-align: right;">778.6</td>
+<td style="text-align: right;">-110</td>
+<td style="text-align: right;">67</td>
+<td>The largest planet</td>
+</tr>
+<tr>
+<th>Saturn</th>
+<td style="text-align: right;">568</td>
+<td style="text-align: right;">120,536</td>
+<td style="text-align: right;">687</td>
+<td style="text-align: right;">9.0</td>
+<td style="text-align: right;">10.7</td>
+<td style="text-align: right;">1433.5</td>
+<td style="text-align: right;">-140</td>
+<td style="text-align: right;">62</td>
+<td></td>
+</tr>
+<tr>
+<th rowspan="2" style="text-align: center;">Ice giants</th>
+<th>Uranus</th>
+<td style="text-align: right;">86.8</td>
+<td style="text-align: right;">51,118</td>
+<td style="text-align: right;">1271</td>
+<td style="text-align: right;">8.7</td>
+<td style="text-align: right;">17.2</td>
+<td style="text-align: right;">2872.5</td>
+<td style="text-align: right;">-195</td>
+<td style="text-align: right;">27</td>
+<td></td>
+</tr>
+<tr>
+<th>Neptune</th>
+<td style="text-align: right;">102</td>
+<td style="text-align: right;">49,528</td>
+<td style="text-align: right;">1638</td>
+<td style="text-align: right;">11.0</td>
+<td style="text-align: right;">16.1</td>
+<td style="text-align: right;">4495.1</td>
+<td style="text-align: right;">-200</td>
+<td style="text-align: right;">14</td>
+<td></td>
+</tr>
+<tr>
+<th colspan="2" style="text-align: center;">Dwarf planets</th>
+<th>Pluto</th>
+<td style="text-align: right;">0.0146</td>
+<td style="text-align: right;">2,370</td>
+<td style="text-align: right;">2095</td>
+<td style="text-align: right;">0.7</td>
+<td style="text-align: right;">153.3</td>
+<td style="text-align: right;">5906.4</td>
+<td style="text-align: right;">-225</td>
+<td style="text-align: right;">5</td>
+<td>Declassified as a planet in 2006.</td>
+</tr>
+</tbody>
+</table>
diff --git a/test/tables/planets.jats_archiving b/test/tables/planets.jats_archiving
new file mode 100644
--- /dev/null
+++ b/test/tables/planets.jats_archiving
@@ -0,0 +1,128 @@
+<table-wrap>
+  <caption>
+    <p>Data about the planets of our solar system.</p>
+  </caption>
+  <table>
+    <thead>
+      <tr>
+        <th align="center" colspan="2"></th>
+        <th>Name</th>
+        <th align="right">Mass (10^24kg)</th>
+        <th align="right">Diameter (km)</th>
+        <th align="right">Density (kg/m^3)</th>
+        <th align="right">Gravity (m/s^2)</th>
+        <th align="right">Length of day (hours)</th>
+        <th align="right">Distance from Sun (10^6km)</th>
+        <th align="right">Mean temperature (C)</th>
+        <th align="right">Number of moons</th>
+        <th>Notes</th>
+      </tr>
+    </thead>
+    <tbody>
+      <tr>
+        <th align="center" rowspan="4" colspan="2">Terrestrial planets</th>
+        <th>Mercury</th><td align="right">0.330</td>
+        <td align="right">4,879</td>
+        <td align="right">5427</td>
+        <td align="right">3.7</td>
+        <td align="right">4222.6</td>
+        <td align="right">57.9</td>
+        <td align="right">167</td>
+        <td align="right">0</td>
+        <td>Closest to the Sun</td>
+      </tr>
+      <tr>
+        <th>Venus</th><td align="right">4.87</td>
+        <td align="right">12,104</td>
+        <td align="right">5243</td>
+        <td align="right">8.9</td>
+        <td align="right">2802.0</td>
+        <td align="right">108.2</td>
+        <td align="right">464</td>
+        <td align="right">0</td>
+        <td></td>
+      </tr>
+      <tr>
+        <th>Earth</th><td align="right">5.97</td>
+        <td align="right">12,756</td>
+        <td align="right">5514</td>
+        <td align="right">9.8</td>
+        <td align="right">24.0</td>
+        <td align="right">149.6</td>
+        <td align="right">15</td>
+        <td align="right">1</td>
+        <td>Our world</td>
+      </tr>
+      <tr>
+        <th>Mars</th><td align="right">0.642</td>
+        <td align="right">6,792</td>
+        <td align="right">3933</td>
+        <td align="right">3.7</td>
+        <td align="right">24.7</td>
+        <td align="right">227.9</td>
+        <td align="right">-65</td>
+        <td align="right">2</td>
+        <td>The red planet</td>
+      </tr>
+      <tr>
+        <th align="center" rowspan="4">Jovian planets</th>
+        <th align="center" rowspan="2">Gas giants</th>
+        <th>Jupiter</th><td align="right">1898</td>
+        <td align="right">142,984</td>
+        <td align="right">1326</td>
+        <td align="right">23.1</td>
+        <td align="right">9.9</td>
+        <td align="right">778.6</td>
+        <td align="right">-110</td>
+        <td align="right">67</td>
+        <td>The largest planet</td>
+      </tr>
+      <tr>
+        <th>Saturn</th><td align="right">568</td>
+        <td align="right">120,536</td>
+        <td align="right">687</td>
+        <td align="right">9.0</td>
+        <td align="right">10.7</td>
+        <td align="right">1433.5</td>
+        <td align="right">-140</td>
+        <td align="right">62</td>
+        <td></td>
+      </tr>
+      <tr>
+        <th align="center" rowspan="2">Ice giants</th>
+        <th>Uranus</th><td align="right">86.8</td>
+        <td align="right">51,118</td>
+        <td align="right">1271</td>
+        <td align="right">8.7</td>
+        <td align="right">17.2</td>
+        <td align="right">2872.5</td>
+        <td align="right">-195</td>
+        <td align="right">27</td>
+        <td></td>
+      </tr>
+      <tr>
+        <th>Neptune</th><td align="right">102</td>
+        <td align="right">49,528</td>
+        <td align="right">1638</td>
+        <td align="right">11.0</td>
+        <td align="right">16.1</td>
+        <td align="right">4495.1</td>
+        <td align="right">-200</td>
+        <td align="right">14</td>
+        <td></td>
+      </tr>
+      <tr>
+        <th align="center" colspan="2">Dwarf planets</th>
+        <th>Pluto</th><td align="right">0.0146</td>
+        <td align="right">2,370</td>
+        <td align="right">2095</td>
+        <td align="right">0.7</td>
+        <td align="right">153.3</td>
+        <td align="right">5906.4</td>
+        <td align="right">-225</td>
+        <td align="right">5</td>
+        <td>Declassified as a planet in 2006.</td>
+      </tr>
+    </tbody>
+  </table>
+</table-wrap>
diff --git a/test/tables/planets.latex b/test/tables/planets.latex
new file mode 100644
--- /dev/null
+++ b/test/tables/planets.latex
@@ -0,0 +1,36 @@
+\begin{longtable}[]{@{}cclrrrrrrrrl@{}}
+\caption{Data about the planets of our solar system.}\tabularnewline
+\toprule\noalign{}
+\multicolumn{2}{@{}c}{%
+} & Name & Mass (10\^{}24kg) & Diameter (km) & Density (kg/m\^{}3) & Gravity
+(m/s\^{}2) & Length of day (hours) & Distance from Sun (10\^{}6km) & Mean
+temperature (C) & Number of moons & Notes \\
+\midrule\noalign{}
+\endfirsthead
+\toprule\noalign{}
+\multicolumn{2}{@{}c}{%
+} & Name & Mass (10\^{}24kg) & Diameter (km) & Density (kg/m\^{}3) & Gravity
+(m/s\^{}2) & Length of day (hours) & Distance from Sun (10\^{}6km) & Mean
+temperature (C) & Number of moons & Notes \\
+\midrule\noalign{}
+\endhead
+\bottomrule\noalign{}
+\endlastfoot
+\multicolumn{2}{@{}c}{%
+\multirow{4}{*}{\centering\arraybackslash Terrestrial planets}} & Mercury &
+0.330 & 4,879 & 5427 & 3.7 & 4222.6 & 57.9 & 167 & 0 & Closest to the Sun \\
+& & Venus & 4.87 & 12,104 & 5243 & 8.9 & 2802.0 & 108.2 & 464 & 0 & \\
+& & Earth & 5.97 & 12,756 & 5514 & 9.8 & 24.0 & 149.6 & 15 & 1 & Our world \\
+& & Mars & 0.642 & 6,792 & 3933 & 3.7 & 24.7 & 227.9 & -65 & 2 & The red
+planet \\
+\multirow{4}{*}{\centering\arraybackslash Jovian planets} &
+\multirow{2}{*}{\centering\arraybackslash Gas giants} & Jupiter & 1898 & 142,984
+& 1326 & 23.1 & 9.9 & 778.6 & -110 & 67 & The largest planet \\
+& & Saturn & 568 & 120,536 & 687 & 9.0 & 10.7 & 1433.5 & -140 & 62 & \\
+& \multirow{2}{*}{\centering\arraybackslash Ice giants} & Uranus & 86.8 & 51,118
+& 1271 & 8.7 & 17.2 & 2872.5 & -195 & 27 & \\
+& & Neptune & 102 & 49,528 & 1638 & 11.0 & 16.1 & 4495.1 & -200 & 14 & \\
+\multicolumn{2}{@{}c}{%
+Dwarf planets} & Pluto & 0.0146 & 2,370 & 2095 & 0.7 & 153.3 & 5906.4 & -225 & 5
+& Declassified as a planet in 2006. \\
+\end{longtable}
diff --git a/test/tables/planets.markdown b/test/tables/planets.markdown
new file mode 100644
--- /dev/null
+++ b/test/tables/planets.markdown
@@ -0,0 +1,31 @@
++------------------+---------+------------+----------+-----------+----------+---------+-----------+-------------+--------+--------------+
+|                  | Name    | Mass       | Diameter | Density   | Gravity  | Length  | Distance  | Mean        | Number | Notes        |
+|                  |         | (10\^24kg) | (km)     | (kg/m\^3) | (m/s\^2) | of day  | from Sun  | temperature | of     |              |
+|                  |         |            |          |           |          | (hours) | (10\^6km) | (C)         | moons  |              |
++:=======:+:======:+=========+===========:+=========:+==========:+=========:+========:+==========:+============:+=======:+==============+
+| Terrestrial      | Mercury | 0.330      | 4,879    | 5427      | 3.7      | 4222.6  | 57.9      | 167         | 0      | Closest to   |
+| planets          |         |            |          |           |          |         |           |             |        | the Sun      |
+|                  +---------+------------+----------+-----------+----------+---------+-----------+-------------+--------+--------------+
+|                  | Venus   | 4.87       | 12,104   | 5243      | 8.9      | 2802.0  | 108.2     | 464         | 0      |              |
+|                  +---------+------------+----------+-----------+----------+---------+-----------+-------------+--------+--------------+
+|                  | Earth   | 5.97       | 12,756   | 5514      | 9.8      | 24.0    | 149.6     | 15          | 1      | Our world    |
+|                  +---------+------------+----------+-----------+----------+---------+-----------+-------------+--------+--------------+
+|                  | Mars    | 0.642      | 6,792    | 3933      | 3.7      | 24.7    | 227.9     | -65         | 2      | The red      |
+|                  |         |            |          |           |          |         |           |             |        | planet       |
++---------+--------+---------+------------+----------+-----------+----------+---------+-----------+-------------+--------+--------------+
+| Jovian  | Gas    | Jupiter | 1898       | 142,984  | 1326      | 23.1     | 9.9     | 778.6     | -110        | 67     | The largest  |
+| planets | giants |         |            |          |           |          |         |           |             |        | planet       |
+|         |        +---------+------------+----------+-----------+----------+---------+-----------+-------------+--------+--------------+
+|         |        | Saturn  | 568        | 120,536  | 687       | 9.0      | 10.7    | 1433.5    | -140        | 62     |              |
+|         +--------+---------+------------+----------+-----------+----------+---------+-----------+-------------+--------+--------------+
+|         | Ice    | Uranus  | 86.8       | 51,118   | 1271      | 8.7      | 17.2    | 2872.5    | -195        | 27     |              |
+|         | giants |         |            |          |           |          |         |           |             |        |              |
+|         |        +---------+------------+----------+-----------+----------+---------+-----------+-------------+--------+--------------+
+|         |        | Neptune | 102        | 49,528   | 1638      | 11.0     | 16.1    | 4495.1    | -200        | 14     |              |
++---------+--------+---------+------------+----------+-----------+----------+---------+-----------+-------------+--------+--------------+
+| Dwarf planets    | Pluto   | 0.0146     | 2,370    | 2095      | 0.7      | 153.3   | 5906.4    | -225        | 5      | Declassified |
+|                  |         |            |          |           |          |         |           |             |        | as a planet  |
+|                  |         |            |          |           |          |         |           |             |        | in 2006.     |
++------------------+---------+------------+----------+-----------+----------+---------+-----------+-------------+--------+--------------+
+
+: Data about the planets of our solar system.
diff --git a/test/tables/planets.mediawiki b/test/tables/planets.mediawiki
new file mode 100644
--- /dev/null
+++ b/test/tables/planets.mediawiki
@@ -0,0 +1,119 @@
+{| class="wikitable"
+|+ Data about the planets of our solar system.
+|-
+! colspan="2" style="text-align: center;"|
+! Name
+! style="text-align: right;"| Mass (10^24kg)
+! style="text-align: right;"| Diameter (km)
+! style="text-align: right;"| Density (kg/m^3)
+! style="text-align: right;"| Gravity (m/s^2)
+! style="text-align: right;"| Length of day (hours)
+! style="text-align: right;"| Distance from Sun (10^6km)
+! style="text-align: right;"| Mean temperature (C)
+! style="text-align: right;"| Number of moons
+! Notes
+|-
+! rowspan="4" colspan="2" style="text-align: center;"| Terrestrial planets
+! Mercury
+| style="text-align: right;"| 0.330
+| style="text-align: right;"| 4,879
+| style="text-align: right;"| 5427
+| style="text-align: right;"| 3.7
+| style="text-align: right;"| 4222.6
+| style="text-align: right;"| 57.9
+| style="text-align: right;"| 167
+| style="text-align: right;"| 0
+| Closest to the Sun
+|-
+! Venus
+| style="text-align: right;"| 4.87
+| style="text-align: right;"| 12,104
+| style="text-align: right;"| 5243
+| style="text-align: right;"| 8.9
+| style="text-align: right;"| 2802.0
+| style="text-align: right;"| 108.2
+| style="text-align: right;"| 464
+| style="text-align: right;"| 0
+|
+|-
+! Earth
+| style="text-align: right;"| 5.97
+| style="text-align: right;"| 12,756
+| style="text-align: right;"| 5514
+| style="text-align: right;"| 9.8
+| style="text-align: right;"| 24.0
+| style="text-align: right;"| 149.6
+| style="text-align: right;"| 15
+| style="text-align: right;"| 1
+| Our world
+|-
+! Mars
+| style="text-align: right;"| 0.642
+| style="text-align: right;"| 6,792
+| style="text-align: right;"| 3933
+| style="text-align: right;"| 3.7
+| style="text-align: right;"| 24.7
+| style="text-align: right;"| 227.9
+| style="text-align: right;"| -65
+| style="text-align: right;"| 2
+| The red planet
+|-
+! rowspan="4" style="text-align: center;"| Jovian planets
+! rowspan="2" style="text-align: center;"| Gas giants
+! Jupiter
+| style="text-align: right;"| 1898
+| style="text-align: right;"| 142,984
+| style="text-align: right;"| 1326
+| style="text-align: right;"| 23.1
+| style="text-align: right;"| 9.9
+| style="text-align: right;"| 778.6
+| style="text-align: right;"| -110
+| style="text-align: right;"| 67
+| The largest planet
+|-
+! Saturn
+| style="text-align: right;"| 568
+| style="text-align: right;"| 120,536
+| style="text-align: right;"| 687
+| style="text-align: right;"| 9.0
+| style="text-align: right;"| 10.7
+| style="text-align: right;"| 1433.5
+| style="text-align: right;"| -140
+| style="text-align: right;"| 62
+|
+|-
+! rowspan="2" style="text-align: center;"| Ice giants
+! Uranus
+| style="text-align: right;"| 86.8
+| style="text-align: right;"| 51,118
+| style="text-align: right;"| 1271
+| style="text-align: right;"| 8.7
+| style="text-align: right;"| 17.2
+| style="text-align: right;"| 2872.5
+| style="text-align: right;"| -195
+| style="text-align: right;"| 27
+|
+|-
+! Neptune
+| style="text-align: right;"| 102
+| style="text-align: right;"| 49,528
+| style="text-align: right;"| 1638
+| style="text-align: right;"| 11.0
+| style="text-align: right;"| 16.1
+| style="text-align: right;"| 4495.1
+| style="text-align: right;"| -200
+| style="text-align: right;"| 14
+|
+|-
+! colspan="2" style="text-align: center;"| Dwarf planets
+! Pluto
+| style="text-align: right;"| 0.0146
+| style="text-align: right;"| 2,370
+| style="text-align: right;"| 2095
+| style="text-align: right;"| 0.7
+| style="text-align: right;"| 153.3
+| style="text-align: right;"| 5906.4
+| style="text-align: right;"| -225
+| style="text-align: right;"| 5
+| Declassified as a planet in 2006.
+|}
diff --git a/test/tables/planets.native b/test/tables/planets.native
new file mode 100644
--- /dev/null
+++ b/test/tables/planets.native
@@ -0,0 +1,241 @@
+[Table ("",[],[]) (Caption Nothing
+ [Para [Str "Data",Space,Str "about",Space,Str "the",Space,Str "planets",Space,Str "of",Space,Str "our",Space,Str "solar",Space,Str "system."]])
+ [(AlignCenter,ColWidthDefault)
+ ,(AlignCenter,ColWidthDefault)
+ ,(AlignDefault,ColWidthDefault)
+ ,(AlignRight,ColWidthDefault)
+ ,(AlignRight,ColWidthDefault)
+ ,(AlignRight,ColWidthDefault)
+ ,(AlignRight,ColWidthDefault)
+ ,(AlignRight,ColWidthDefault)
+ ,(AlignRight,ColWidthDefault)
+ ,(AlignRight,ColWidthDefault)
+ ,(AlignRight,ColWidthDefault)
+ ,(AlignDefault,ColWidthDefault)]
+ (TableHead ("",[],[])
+ [Row ("",[],[])
+  [Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 2)
+   []
+  ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+   [Plain [Str "Name"]]
+  ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+   [Plain [Str "Mass",Space,Str "(10^24kg)"]]
+  ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+   [Plain [Str "Diameter",Space,Str "(km)"]]
+  ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+   [Plain [Str "Density",Space,Str "(kg/m^3)"]]
+  ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+   [Plain [Str "Gravity",Space,Str "(m/s^2)"]]
+  ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+   [Plain [Str "Length",Space,Str "of",Space,Str "day",Space,Str "(hours)"]]
+  ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+   [Plain [Str "Distance",Space,Str "from",Space,Str "Sun",Space,Str "(10^6km)"]]
+  ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+   [Plain [Str "Mean",Space,Str "temperature",Space,Str "(C)"]]
+  ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+   [Plain [Str "Number",Space,Str "of",Space,Str "moons"]]
+  ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+   [Plain [Str "Notes"]]]])
+ [(TableBody ("",[],[]) (RowHeadColumns 3)
+  []
+  [Row ("",[],[])
+   [Cell ("",[],[]) AlignDefault (RowSpan 4) (ColSpan 2)
+    [Plain [Str "Terrestrial",Space,Str "planets"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "Mercury"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "0.330"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "4,879"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "5427"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "3.7"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "4222.6"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "57.9"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "167"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "0"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "Closest",Space,Str "to",Space,Str "the",Space,Str "Sun"]]]
+  ,Row ("",[],[])
+   [Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "Venus"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "4.87"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "12,104"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "5243"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "8.9"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "2802.0"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "108.2"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "464"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "0"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    []]
+  ,Row ("",[],[])
+   [Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "Earth"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "5.97"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "12,756"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "5514"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "9.8"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "24.0"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "149.6"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "15"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "1"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "Our",Space,Str "world"]]]
+  ,Row ("",[],[])
+   [Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "Mars"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "0.642"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "6,792"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "3933"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "3.7"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "24.7"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "227.9"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "-65"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "2"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "The",Space,Str "red",Space,Str "planet"]]]
+  ,Row ("",[],[])
+   [Cell ("",[],[]) AlignDefault (RowSpan 4) (ColSpan 1)
+    [Plain [Str "Jovian",Space,Str "planets"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 2) (ColSpan 1)
+    [Plain [Str "Gas",Space,Str "giants"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "Jupiter"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "1898"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "142,984"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "1326"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "23.1"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "9.9"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "778.6"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "-110"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "67"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "The",Space,Str "largest",Space,Str "planet"]]]
+  ,Row ("",[],[])
+   [Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "Saturn"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "568"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "120,536"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "687"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "9.0"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "10.7"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "1433.5"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "-140"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "62"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    []]
+  ,Row ("",[],[])
+   [Cell ("",[],[]) AlignDefault (RowSpan 2) (ColSpan 1)
+    [Plain [Str "Ice",Space,Str "giants"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "Uranus"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "86.8"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "51,118"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "1271"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "8.7"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "17.2"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "2872.5"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "-195"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "27"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    []]
+  ,Row ("",[],[])
+   [Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "Neptune"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "102"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "49,528"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "1638"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "11.0"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "16.1"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "4495.1"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "-200"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "14"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    []]
+  ,Row ("",[],[])
+   [Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 2)
+    [Plain [Str "Dwarf",Space,Str "planets"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "Pluto"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "0.0146"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "2,370"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "2095"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "0.7"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "153.3"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "5906.4"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "-225"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "5"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "Declassified",Space,Str "as",Space,Str "a",Space,Str "planet",Space,Str "in",Space,Str "2006."]]]])]
+ (TableFoot ("",[],[])
+ [])]
diff --git a/test/tables/planets.typst b/test/tables/planets.typst
new file mode 100644
--- /dev/null
+++ b/test/tables/planets.typst
@@ -0,0 +1,33 @@
+#figure(
+  align(center)[#table(
+    columns: 12,
+    align: (center,center,auto,right,right,right,right,right,right,right,right,auto,),
+    table.header(table.cell(colspan: 2)[], [Name], [Mass (10^24kg)], [Diameter
+      (km)], [Density (kg/m^3)], [Gravity (m/s^2)], [Length of day
+      (hours)], [Distance from Sun (10^6km)], [Mean temperature (C)], [Number of
+      moons], [Notes],),
+    table.hline(),
+    table.cell(rowspan: 4, colspan: 2)[Terrestrial
+    planets], [Mercury], [0.330], [4,879], [5427], [3.7], [4222.6], [57.9], [167], [0], [Closest
+    to the Sun],
+    [Venus], [4.87], [12,104], [5243], [8.9], [2802.0], [108.2], [464], [0], [],
+    [Earth], [5.97], [12,756], [5514], [9.8], [24.0], [149.6], [15], [1], [Our
+    world],
+    [Mars], [0.642], [6,792], [3933], [3.7], [24.7], [227.9], [-65], [2], [The
+    red planet],
+    table.cell(rowspan: 4)[Jovian planets], table.cell(rowspan: 2)[Gas
+    giants], [Jupiter], [1898], [142,984], [1326], [23.1], [9.9], [778.6], [-110], [67], [The
+    largest planet],
+    [Saturn], [568], [120,536], [687], [9.0], [10.7], [1433.5], [-140], [62], [],
+    table.cell(rowspan: 2)[Ice
+    giants], [Uranus], [86.8], [51,118], [1271], [8.7], [17.2], [2872.5], [-195], [27], [],
+    [Neptune], [102], [49,528], [1638], [11.0], [16.1], [4495.1], [-200], [14], [],
+    table.cell(colspan: 2)[Dwarf
+    planets], [Pluto], [0.0146], [2,370], [2095], [0.7], [153.3], [5906.4], [-225], [5], [Declassified
+    as a planet in 2006.],
+  )]
+  , caption: [Data about the planets of our solar system.
+
+  ]
+  , kind: table
+  )
diff --git a/test/tables/students.html4 b/test/tables/students.html4
new file mode 100644
--- /dev/null
+++ b/test/tables/students.html4
@@ -0,0 +1,55 @@
+<table id="students" source="mdn">
+<caption><p>List of Students</p></caption>
+<colgroup>
+<col width="50%" />
+<col width="50%" />
+</colgroup>
+<thead>
+<tr>
+<th align="center">Student ID</th>
+<th align="center">Name</th>
+</tr>
+</thead>
+<tbody class="souvereign-states">
+<tr>
+<th colspan="2" align="left">Computer Science</th>
+</tr>
+
+<tr>
+<td align="left">3741255</td>
+<td align="left">Jones, Martha</td>
+</tr>
+<tr>
+<td align="left">4077830</td>
+<td align="left">Pierce, Benjamin</td>
+</tr>
+<tr>
+<td align="left">5151701</td>
+<td align="left">Kirk, James</td>
+</tr>
+</tbody>
+<tbody>
+<tr>
+<th colspan="2" align="left">Russian Literature</th>
+</tr>
+
+<tr>
+<td align="left">3971244</td>
+<td align="left">Nim, Victor</td>
+</tr>
+</tbody>
+<tbody>
+<tr>
+<th colspan="2" align="left">Astrophysics</th>
+</tr>
+
+<tr>
+<td align="left">4100332</td>
+<td align="left">Petrov, Alexandra</td>
+</tr>
+<tr>
+<td align="left">4100332</td>
+<td align="left">Toyota, Hiroko</td>
+</tr>
+</tbody>
+</table>
diff --git a/test/tables/students.html5 b/test/tables/students.html5
new file mode 100644
--- /dev/null
+++ b/test/tables/students.html5
@@ -0,0 +1,55 @@
+<table id="students" data-source="mdn">
+<caption><p>List of Students</p></caption>
+<colgroup>
+<col style="width: 50%" />
+<col style="width: 50%" />
+</colgroup>
+<thead>
+<tr>
+<th style="text-align: center;">Student ID</th>
+<th style="text-align: center;">Name</th>
+</tr>
+</thead>
+<tbody class="souvereign-states">
+<tr>
+<th colspan="2" style="text-align: left;">Computer Science</th>
+</tr>
+
+<tr>
+<td style="text-align: left;">3741255</td>
+<td style="text-align: left;">Jones, Martha</td>
+</tr>
+<tr>
+<td style="text-align: left;">4077830</td>
+<td style="text-align: left;">Pierce, Benjamin</td>
+</tr>
+<tr>
+<td style="text-align: left;">5151701</td>
+<td style="text-align: left;">Kirk, James</td>
+</tr>
+</tbody>
+<tbody>
+<tr>
+<th colspan="2" style="text-align: left;">Russian Literature</th>
+</tr>
+
+<tr>
+<td style="text-align: left;">3971244</td>
+<td style="text-align: left;">Nim, Victor</td>
+</tr>
+</tbody>
+<tbody>
+<tr>
+<th colspan="2" style="text-align: left;">Astrophysics</th>
+</tr>
+
+<tr>
+<td style="text-align: left;">4100332</td>
+<td style="text-align: left;">Petrov, Alexandra</td>
+</tr>
+<tr>
+<td style="text-align: left;">4100332</td>
+<td style="text-align: left;">Toyota, Hiroko</td>
+</tr>
+</tbody>
+</table>
diff --git a/test/tables/students.jats_archiving b/test/tables/students.jats_archiving
new file mode 100644
--- /dev/null
+++ b/test/tables/students.jats_archiving
@@ -0,0 +1,56 @@
+<table-wrap>
+  <caption>
+    <p>List of Students</p>
+  </caption>
+  <table id="students">
+    <colgroup>
+      <col width="50%" />
+      <col width="50%" />
+    </colgroup>
+    <thead>
+      <tr>
+        <th align="center">Student ID</th>
+        <th align="center">Name</th>
+      </tr>
+    </thead>
+    <tbody>
+      <tr>
+        <th align="left" colspan="2">Computer Science</th>
+      </tr>
+      <tr>
+        <td align="left">3741255</td>
+        <td align="left">Jones, Martha</td>
+      </tr>
+      <tr>
+        <td align="left">4077830</td>
+        <td align="left">Pierce, Benjamin</td>
+      </tr>
+      <tr>
+        <td align="left">5151701</td>
+        <td align="left">Kirk, James</td>
+      </tr>
+    </tbody>
+    <tbody>
+      <tr>
+        <th align="left" colspan="2">Russian Literature</th>
+      </tr>
+      <tr>
+        <td align="left">3971244</td>
+        <td align="left">Nim, Victor</td>
+      </tr>
+    </tbody>
+    <tbody>
+      <tr>
+        <th align="left" colspan="2">Astrophysics</th>
+      </tr>
+      <tr>
+        <td align="left">4100332</td>
+        <td align="left">Petrov, Alexandra</td>
+      </tr>
+      <tr>
+        <td align="left">4100332</td>
+        <td align="left">Toyota, Hiroko</td>
+      </tr>
+    </tbody>
+  </table>
+</table-wrap>
diff --git a/test/tables/students.latex b/test/tables/students.latex
new file mode 100644
--- /dev/null
+++ b/test/tables/students.latex
@@ -0,0 +1,35 @@
+\begin{longtable}[]{@{}
+  >{\raggedright\arraybackslash}p{(\linewidth - 2\tabcolsep) * \real{0.5000}}
+  >{\raggedright\arraybackslash}p{(\linewidth - 2\tabcolsep) * \real{0.5000}}@{}}
+\caption{List of Students}\label{students}\tabularnewline
+\toprule\noalign{}
+\begin{minipage}[b]{\linewidth}\centering
+Student ID
+\end{minipage} & \begin{minipage}[b]{\linewidth}\centering
+Name
+\end{minipage} \\
+\midrule\noalign{}
+\endfirsthead
+\toprule\noalign{}
+\begin{minipage}[b]{\linewidth}\centering
+Student ID
+\end{minipage} & \begin{minipage}[b]{\linewidth}\centering
+Name
+\end{minipage} \\
+\midrule\noalign{}
+\endhead
+\bottomrule\noalign{}
+\endlastfoot
+\multicolumn{2}{@{}>{\raggedright\arraybackslash}p{(\linewidth - 2\tabcolsep) * \real{1.0000} + 2\tabcolsep}@{}}{%
+Computer Science} \\
+3741255 & Jones, Martha \\
+4077830 & Pierce, Benjamin \\
+5151701 & Kirk, James \\
+\multicolumn{2}{@{}>{\raggedright\arraybackslash}p{(\linewidth - 2\tabcolsep) * \real{1.0000} + 2\tabcolsep}@{}}{%
+Russian Literature} \\
+3971244 & Nim, Victor \\
+\multicolumn{2}{@{}>{\raggedright\arraybackslash}p{(\linewidth - 2\tabcolsep) * \real{1.0000} + 2\tabcolsep}@{}}{%
+Astrophysics} \\
+4100332 & Petrov, Alexandra \\
+4100332 & Toyota, Hiroko \\
+\end{longtable}
diff --git a/test/tables/students.markdown b/test/tables/students.markdown
new file mode 100644
--- /dev/null
+++ b/test/tables/students.markdown
@@ -0,0 +1,23 @@
++-----------------------------------------+-----------------------------------------+
+| Student ID                              | Name                                    |
++:========================================+:========================================+
+| Computer Science                                                                  |
++-----------------------------------------+-----------------------------------------+
+| 3741255                                 | Jones, Martha                           |
++-----------------------------------------+-----------------------------------------+
+| 4077830                                 | Pierce, Benjamin                        |
++-----------------------------------------+-----------------------------------------+
+| 5151701                                 | Kirk, James                             |
++-----------------------------------------+-----------------------------------------+
+| Russian Literature                                                                |
++-----------------------------------------+-----------------------------------------+
+| 3971244                                 | Nim, Victor                             |
++-----------------------------------------+-----------------------------------------+
+| Astrophysics                                                                      |
++-----------------------------------------+-----------------------------------------+
+| 4100332                                 | Petrov, Alexandra                       |
++-----------------------------------------+-----------------------------------------+
+| 4100332                                 | Toyota, Hiroko                          |
++-----------------------------------------+-----------------------------------------+
+
+: List of Students {#students source="mdn"}
diff --git a/test/tables/students.mediawiki b/test/tables/students.mediawiki
new file mode 100644
--- /dev/null
+++ b/test/tables/students.mediawiki
@@ -0,0 +1,30 @@
+{| id="students" class="wikitable" data-source="mdn"
+|+ List of Students
+|-
+! style="text-align: center;"| Student ID
+! style="text-align: center;"| Name
+|-
+! colspan="2" style="text-align: left;"| Computer Science
+|-
+| style="text-align: left;"| 3741255
+| style="text-align: left;"| Jones, Martha
+|-
+| style="text-align: left;"| 4077830
+| style="text-align: left;"| Pierce, Benjamin
+|-
+| style="text-align: left;"| 5151701
+| style="text-align: left;"| Kirk, James
+|-
+! colspan="2" style="text-align: left;"| Russian Literature
+|-
+| style="text-align: left;"| 3971244
+| style="text-align: left;"| Nim, Victor
+|-
+! colspan="2" style="text-align: left;"| Astrophysics
+|-
+| style="text-align: left;"| 4100332
+| style="text-align: left;"| Petrov, Alexandra
+|-
+| style="text-align: left;"| 4100332
+| style="text-align: left;"| Toyota, Hiroko
+|}
diff --git a/test/tables/students.native b/test/tables/students.native
new file mode 100644
--- /dev/null
+++ b/test/tables/students.native
@@ -0,0 +1,54 @@
+[Table ("students",[],[("source","mdn")]) (Caption Nothing
+ [Para [Str "List",Space,Str "of",Space,Str "Students"]])
+ [(AlignLeft,ColWidth 0.5)
+ ,(AlignLeft,ColWidth 0.5)]
+ (TableHead ("",[],[])
+ [Row ("",[],[])
+  [Cell ("",[],[]) AlignCenter (RowSpan 1) (ColSpan 1)
+   [Plain [Str "Student",Space,Str "ID"]]
+  ,Cell ("",[],[]) AlignCenter (RowSpan 1) (ColSpan 1)
+   [Plain [Str "Name"]]]])
+ [(TableBody ("",["souvereign-states"],[]) (RowHeadColumns 0)
+  [Row ("",[],[])
+   [Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 2)
+    [Plain [Str "Computer",Space,Str "Science"]]]]
+  [Row ("",[],[])
+   [Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "3741255"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "Jones,",Space,Str "Martha"]]]
+  ,Row ("",[],[])
+   [Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "4077830"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "Pierce,",Space,Str "Benjamin"]]]
+  ,Row ("",[],[])
+   [Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "5151701"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "Kirk,",Space,Str "James"]]]])
+ ,(TableBody ("",[],[]) (RowHeadColumns 0)
+  [Row ("",[],[])
+   [Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 2)
+    [Plain [Str "Russian",Space,Str "Literature"]]]]
+  [Row ("",[],[])
+   [Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "3971244"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "Nim,",Space,Str "Victor"]]]])
+ ,(TableBody ("",[],[]) (RowHeadColumns 0)
+  [Row ("",[],[])
+   [Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 2)
+    [Plain [Str "Astrophysics"]]]]
+  [Row ("",[],[])
+   [Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "4100332"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "Petrov,",Space,Str "Alexandra"]]]
+  ,Row ("",[],[])
+   [Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "4100332"]]
+   ,Cell ("",[],[]) AlignDefault (RowSpan 1) (ColSpan 1)
+    [Plain [Str "Toyota,",Space,Str "Hiroko"]]]])]
+ (TableFoot ("",[],[])
+ [])]
diff --git a/test/tables/students.typst b/test/tables/students.typst
new file mode 100644
--- /dev/null
+++ b/test/tables/students.typst
@@ -0,0 +1,26 @@
+#figure(
+  align(center)[#table(
+    columns: (50%, 50%),
+    align: (left,left,),
+    table.header(table.cell(align: center)[Student
+      ID], table.cell(align: center)[Name],),
+    table.hline(),
+    table.cell(colspan: 2)[Computer Science],
+    table.hline(),
+    [3741255], [Jones, Martha],
+    [4077830], [Pierce, Benjamin],
+    [5151701], [Kirk, James],
+    table.cell(colspan: 2)[Russian Literature],
+    table.hline(),
+    [3971244], [Nim, Victor],
+    table.cell(colspan: 2)[Astrophysics],
+    table.hline(),
+    [4100332], [Petrov, Alexandra],
+    [4100332], [Toyota, Hiroko],
+  )]
+  , caption: [List of Students
+
+  ]
+  , kind: table
+  )
+<students>
diff --git a/test/test-pandoc.hs b/test/test-pandoc.hs
--- a/test/test-pandoc.hs
+++ b/test/test-pandoc.hs
@@ -1,54 +1,77 @@
-{-# OPTIONS_GHC -Wall #-}
-
-module Main where
+module Main (main) where
 
+import System.Environment (getArgs, getExecutablePath)
+import qualified Control.Exception as E
+import Text.Pandoc.App (convertWithOpts, handleOptInfo, defaultOpts, options,
+                        parseOptionsFromArgs)
+import Text.Pandoc.Error (handleError)
+import Text.Pandoc.Scripting (noEngine)
 import GHC.IO.Encoding
 import Test.Tasty
 import qualified Tests.Command
-import qualified Tests.Lua
 import qualified Tests.Old
 import qualified Tests.Readers.Creole
 import qualified Tests.Readers.Docx
+import qualified Tests.Readers.Pptx
+import qualified Tests.Readers.Xlsx
+import qualified Tests.Readers.DokuWiki
 import qualified Tests.Readers.EPUB
+import qualified Tests.Readers.FB2
 import qualified Tests.Readers.HTML
 import qualified Tests.Readers.JATS
+import qualified Tests.Readers.Jira
 import qualified Tests.Readers.LaTeX
 import qualified Tests.Readers.Markdown
 import qualified Tests.Readers.Muse
-import qualified Tests.Readers.Odt
+import qualified Tests.Readers.ODT
 import qualified Tests.Readers.Org
 import qualified Tests.Readers.RST
+import qualified Tests.Readers.RTF
 import qualified Tests.Readers.Txt2Tags
+import qualified Tests.Readers.Man
+import qualified Tests.Readers.Mdoc
+import qualified Tests.Readers.Pod
 import qualified Tests.Shared
 import qualified Tests.Writers.AsciiDoc
 import qualified Tests.Writers.ConTeXt
-import qualified Tests.Writers.Docbook
+import qualified Tests.Writers.DocBook
 import qualified Tests.Writers.Docx
 import qualified Tests.Writers.FB2
 import qualified Tests.Writers.HTML
 import qualified Tests.Writers.JATS
+import qualified Tests.Writers.Jira
 import qualified Tests.Writers.LaTeX
 import qualified Tests.Writers.Markdown
+import qualified Tests.Writers.Ms
 import qualified Tests.Writers.Muse
 import qualified Tests.Writers.Native
 import qualified Tests.Writers.Org
 import qualified Tests.Writers.Plain
 import qualified Tests.Writers.Powerpoint
 import qualified Tests.Writers.RST
+import qualified Tests.Writers.AnnotatedTable
 import qualified Tests.Writers.TEI
+import qualified Tests.Writers.Markua
+import qualified Tests.Writers.BBCode
+import qualified Tests.XML
+import qualified Tests.MediaBag
 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
+        , testGroup "Old" (Tests.Old.tests pandocPath)
         , testGroup "Shared" Tests.Shared.tests
+        , testGroup "MediaBag" Tests.MediaBag.tests
+        , testGroup "XML" Tests.XML.tests
         , testGroup "Writers"
           [ testGroup "Native" Tests.Writers.Native.tests
           , testGroup "ConTeXt" Tests.Writers.ConTeXt.tests
           , testGroup "LaTeX" Tests.Writers.LaTeX.tests
           , testGroup "HTML" Tests.Writers.HTML.tests
           , testGroup "JATS" Tests.Writers.JATS.tests
-          , testGroup "Docbook" Tests.Writers.Docbook.tests
+          , testGroup "Jira" Tests.Writers.Jira.tests
+          , testGroup "Docbook" Tests.Writers.DocBook.tests
           , testGroup "Markdown" Tests.Writers.Markdown.tests
           , testGroup "Org" Tests.Writers.Org.tests
           , testGroup "Plain" Tests.Writers.Plain.tests
@@ -56,28 +79,53 @@
           , testGroup "Docx" Tests.Writers.Docx.tests
           , testGroup "RST" Tests.Writers.RST.tests
           , testGroup "TEI" Tests.Writers.TEI.tests
+          , testGroup "markua" Tests.Writers.Markua.tests
           , testGroup "Muse" Tests.Writers.Muse.tests
           , testGroup "FB2" Tests.Writers.FB2.tests
           , testGroup "PowerPoint" Tests.Writers.Powerpoint.tests
+          , testGroup "Ms" Tests.Writers.Ms.tests
+          , testGroup "AnnotatedTable" Tests.Writers.AnnotatedTable.tests
+          , testGroup "BBCode" Tests.Writers.BBCode.tests
           ]
         , testGroup "Readers"
           [ testGroup "LaTeX" Tests.Readers.LaTeX.tests
           , testGroup "Markdown" Tests.Readers.Markdown.tests
           , testGroup "HTML" Tests.Readers.HTML.tests
           , testGroup "JATS" Tests.Readers.JATS.tests
+          , testGroup "Jira" Tests.Readers.Jira.tests
           , testGroup "Org" Tests.Readers.Org.tests
           , testGroup "RST" Tests.Readers.RST.tests
+          , testGroup "RTF" Tests.Readers.RTF.tests
           , testGroup "Docx" Tests.Readers.Docx.tests
-          , testGroup "Odt" Tests.Readers.Odt.tests
+          , testGroup "Pptx" Tests.Readers.Pptx.tests
+          , testGroup "Xlsx" Tests.Readers.Xlsx.tests
+          , testGroup "ODT" Tests.Readers.ODT.tests
           , testGroup "Txt2Tags" Tests.Readers.Txt2Tags.tests
           , testGroup "EPUB" Tests.Readers.EPUB.tests
           , testGroup "Muse" Tests.Readers.Muse.tests
           , testGroup "Creole" Tests.Readers.Creole.tests
+          , testGroup "Man" Tests.Readers.Man.tests
+          , testGroup "Mdoc" Tests.Readers.Mdoc.tests
+          , testGroup "FB2" Tests.Readers.FB2.tests
+          , testGroup "DokuWiki" Tests.Readers.DokuWiki.tests
+          , testGroup "Pod" Tests.Readers.Pod.tests
           ]
-        , testGroup "Lua filters" Tests.Lua.tests
         ]
 
 main :: IO ()
 main = do
   setLocaleEncoding utf8
-  inDirectory "test" $ defaultMain tests
+  args <- getArgs
+  case args of
+    "--emulate":args' -> -- emulate pandoc executable
+          E.catch
+            (do
+              res <- parseOptionsFromArgs options defaultOpts "pandoc" args'
+              case res of
+                Left e -> handleOptInfo noEngine e
+                Right opts -> convertWithOpts noEngine opts)
+            (handleError . Left)
+    _ -> inDirectory "test" $ do
+           fp <- getExecutablePath
+           -- putStrLn $ "Using pandoc executable at " ++ fp
+           defaultMain $ tests fp
diff --git a/test/testsuite.native b/test/testsuite.native
--- a/test/testsuite.native
+++ b/test/testsuite.native
@@ -1,409 +1,2238 @@
-Pandoc (Meta {unMeta = fromList [("author",MetaList [MetaInlines [Str "John",Space,Str "MacFarlane"],MetaInlines [Str "Anonymous"]]),("date",MetaInlines [Str "July",Space,Str "17,",Space,Str "2006"]),("title",MetaInlines [Str "Pandoc",Space,Str "Test",Space,Str "Suite"])]})
-[Para [Str "This",Space,Str "is",Space,Str "a",Space,Str "set",Space,Str "of",Space,Str "tests",Space,Str "for",Space,Str "pandoc.",Space,Str "Most",Space,Str "of",Space,Str "them",Space,Str "are",Space,Str "adapted",Space,Str "from",SoftBreak,Str "John",Space,Str "Gruber\8217s",Space,Str "markdown",Space,Str "test",Space,Str "suite."]
-,HorizontalRule
-,Header 1 ("headers",[],[]) [Str "Headers"]
-,Header 2 ("level-2-with-an-embedded-link",[],[]) [Str "Level",Space,Str "2",Space,Str "with",Space,Str "an",Space,Link ("",[],[]) [Str "embedded",Space,Str "link"] ("/url","")]
-,Header 3 ("level-3-with-emphasis",[],[]) [Str "Level",Space,Str "3",Space,Str "with",Space,Emph [Str "emphasis"]]
-,Header 4 ("level-4",[],[]) [Str "Level",Space,Str "4"]
-,Header 5 ("level-5",[],[]) [Str "Level",Space,Str "5"]
-,Header 1 ("level-1",[],[]) [Str "Level",Space,Str "1"]
-,Header 2 ("level-2-with-emphasis",[],[]) [Str "Level",Space,Str "2",Space,Str "with",Space,Emph [Str "emphasis"]]
-,Header 3 ("level-3",[],[]) [Str "Level",Space,Str "3"]
-,Para [Str "with",Space,Str "no",Space,Str "blank",Space,Str "line"]
-,Header 2 ("level-2",[],[]) [Str "Level",Space,Str "2"]
-,Para [Str "with",Space,Str "no",Space,Str "blank",Space,Str "line"]
-,HorizontalRule
-,Header 1 ("paragraphs",[],[]) [Str "Paragraphs"]
-,Para [Str "Here\8217s",Space,Str "a",Space,Str "regular",Space,Str "paragraph."]
-,Para [Str "In",Space,Str "Markdown",Space,Str "1.0.0",Space,Str "and",Space,Str "earlier.",Space,Str "Version",SoftBreak,Str "8.",Space,Str "This",Space,Str "line",Space,Str "turns",Space,Str "into",Space,Str "a",Space,Str "list",Space,Str "item.",SoftBreak,Str "Because",Space,Str "a",Space,Str "hard-wrapped",Space,Str "line",Space,Str "in",Space,Str "the",SoftBreak,Str "middle",Space,Str "of",Space,Str "a",Space,Str "paragraph",Space,Str "looked",Space,Str "like",Space,Str "a",SoftBreak,Str "list",Space,Str "item."]
-,Para [Str "Here\8217s",Space,Str "one",Space,Str "with",Space,Str "a",Space,Str "bullet.",SoftBreak,Str "*",Space,Str "criminey."]
-,Para [Str "There",Space,Str "should",Space,Str "be",Space,Str "a",Space,Str "hard",Space,Str "line",Space,Str "break",LineBreak,Str "here."]
-,HorizontalRule
-,Header 1 ("block-quotes",[],[]) [Str "Block",Space,Str "Quotes"]
-,Para [Str "E-mail",Space,Str "style:"]
-,BlockQuote
- [Para [Str "This",Space,Str "is",Space,Str "a",Space,Str "block",Space,Str "quote.",SoftBreak,Str "It",Space,Str "is",Space,Str "pretty",Space,Str "short."]]
-,BlockQuote
- [Para [Str "Code",Space,Str "in",Space,Str "a",Space,Str "block",Space,Str "quote:"]
- ,CodeBlock ("",[],[]) "sub status {\n    print \"working\";\n}"
- ,Para [Str "A",Space,Str "list:"]
- ,OrderedList (1,Decimal,Period)
-  [[Plain [Str "item",Space,Str "one"]]
-  ,[Plain [Str "item",Space,Str "two"]]]
- ,Para [Str "Nested",Space,Str "block",Space,Str "quotes:"]
- ,BlockQuote
-  [Para [Str "nested"]]
- ,BlockQuote
-  [Para [Str "nested"]]]
-,Para [Str "This",Space,Str "should",Space,Str "not",Space,Str "be",Space,Str "a",Space,Str "block",Space,Str "quote:",Space,Str "2",SoftBreak,Str ">",Space,Str "1."]
-,Para [Str "And",Space,Str "a",Space,Str "following",Space,Str "paragraph."]
-,HorizontalRule
-,Header 1 ("code-blocks",[],[]) [Str "Code",Space,Str "Blocks"]
-,Para [Str "Code:"]
-,CodeBlock ("",[],[]) "---- (should be four hyphens)\n\nsub status {\n    print \"working\";\n}\n\nthis code block is indented by one tab"
-,Para [Str "And:"]
-,CodeBlock ("",[],[]) "    this code block is indented by two tabs\n\nThese should not be escaped:  \\$ \\\\ \\> \\[ \\{"
-,HorizontalRule
-,Header 1 ("lists",[],[]) [Str "Lists"]
-,Header 2 ("unordered",[],[]) [Str "Unordered"]
-,Para [Str "Asterisks",Space,Str "tight:"]
-,BulletList
- [[Plain [Str "asterisk",Space,Str "1"]]
- ,[Plain [Str "asterisk",Space,Str "2"]]
- ,[Plain [Str "asterisk",Space,Str "3"]]]
-,Para [Str "Asterisks",Space,Str "loose:"]
-,BulletList
- [[Para [Str "asterisk",Space,Str "1"]]
- ,[Para [Str "asterisk",Space,Str "2"]]
- ,[Para [Str "asterisk",Space,Str "3"]]]
-,Para [Str "Pluses",Space,Str "tight:"]
-,BulletList
- [[Plain [Str "Plus",Space,Str "1"]]
- ,[Plain [Str "Plus",Space,Str "2"]]
- ,[Plain [Str "Plus",Space,Str "3"]]]
-,Para [Str "Pluses",Space,Str "loose:"]
-,BulletList
- [[Para [Str "Plus",Space,Str "1"]]
- ,[Para [Str "Plus",Space,Str "2"]]
- ,[Para [Str "Plus",Space,Str "3"]]]
-,Para [Str "Minuses",Space,Str "tight:"]
-,BulletList
- [[Plain [Str "Minus",Space,Str "1"]]
- ,[Plain [Str "Minus",Space,Str "2"]]
- ,[Plain [Str "Minus",Space,Str "3"]]]
-,Para [Str "Minuses",Space,Str "loose:"]
-,BulletList
- [[Para [Str "Minus",Space,Str "1"]]
- ,[Para [Str "Minus",Space,Str "2"]]
- ,[Para [Str "Minus",Space,Str "3"]]]
-,Header 2 ("ordered",[],[]) [Str "Ordered"]
-,Para [Str "Tight:"]
-,OrderedList (1,Decimal,Period)
- [[Plain [Str "First"]]
- ,[Plain [Str "Second"]]
- ,[Plain [Str "Third"]]]
-,Para [Str "and:"]
-,OrderedList (1,Decimal,Period)
- [[Plain [Str "One"]]
- ,[Plain [Str "Two"]]
- ,[Plain [Str "Three"]]]
-,Para [Str "Loose",Space,Str "using",Space,Str "tabs:"]
-,OrderedList (1,Decimal,Period)
- [[Para [Str "First"]]
- ,[Para [Str "Second"]]
- ,[Para [Str "Third"]]]
-,Para [Str "and",Space,Str "using",Space,Str "spaces:"]
-,OrderedList (1,Decimal,Period)
- [[Para [Str "One"]]
- ,[Para [Str "Two"]]
- ,[Para [Str "Three"]]]
-,Para [Str "Multiple",Space,Str "paragraphs:"]
-,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."]]
- ,[Para [Str "Item",Space,Str "2."]]
- ,[Para [Str "Item",Space,Str "3."]]]
-,Header 2 ("nested",[],[]) [Str "Nested"]
-,BulletList
- [[Plain [Str "Tab"]
-  ,BulletList
-   [[Plain [Str "Tab"]
-    ,BulletList
-     [[Plain [Str "Tab"]]]]]]]
-,Para [Str "Here\8217s",Space,Str "another:"]
-,OrderedList (1,Decimal,Period)
- [[Plain [Str "First"]]
- ,[Plain [Str "Second:"]
-  ,BulletList
-   [[Plain [Str "Fee"]]
-   ,[Plain [Str "Fie"]]
-   ,[Plain [Str "Foe"]]]]
- ,[Plain [Str "Third"]]]
-,Para [Str "Same",Space,Str "thing",Space,Str "but",Space,Str "with",Space,Str "paragraphs:"]
-,OrderedList (1,Decimal,Period)
- [[Para [Str "First"]]
- ,[Para [Str "Second:"]
-  ,BulletList
-   [[Plain [Str "Fee"]]
-   ,[Plain [Str "Fie"]]
-   ,[Plain [Str "Foe"]]]]
- ,[Para [Str "Third"]]]
-,Header 2 ("tabs-and-spaces",[],[]) [Str "Tabs",Space,Str "and",Space,Str "spaces"]
-,BulletList
- [[Para [Str "this",Space,Str "is",Space,Str "a",Space,Str "list",Space,Str "item",SoftBreak,Str "indented",Space,Str "with",Space,Str "tabs"]]
- ,[Para [Str "this",Space,Str "is",Space,Str "a",Space,Str "list",Space,Str "item",SoftBreak,Str "indented",Space,Str "with",Space,Str "spaces"]
-  ,BulletList
-   [[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 "tabs"]]
-   ,[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 "and",Space,Str "now",Space,Str "3"]
-  ,Para [Str "with",Space,Str "a",Space,Str "continuation"]
-  ,OrderedList (4,LowerRoman,Period)
-   [[Plain [Str "sublist",Space,Str "with",Space,Str "roman",Space,Str "numerals,",SoftBreak,Str "starting",Space,Str "with",Space,Str "4"]]
-   ,[Plain [Str "more",Space,Str "items"]
-    ,OrderedList (1,UpperAlpha,TwoParens)
-     [[Plain [Str "a",Space,Str "subsublist"]]
-     ,[Plain [Str "a",Space,Str "subsublist"]]]]]]]
-,Para [Str "Nesting:"]
-,OrderedList (1,UpperAlpha,Period)
- [[Plain [Str "Upper",Space,Str "Alpha"]
-  ,OrderedList (1,UpperRoman,Period)
-   [[Plain [Str "Upper",Space,Str "Roman."]
-    ,OrderedList (6,Decimal,TwoParens)
-     [[Plain [Str "Decimal",Space,Str "start",Space,Str "with",Space,Str "6"]
-      ,OrderedList (3,LowerAlpha,OneParen)
-       [[Plain [Str "Lower",Space,Str "alpha",Space,Str "with",Space,Str "paren"]]]]]]]]]
-,Para [Str "Autonumbering:"]
-,OrderedList (1,DefaultStyle,DefaultDelim)
- [[Plain [Str "Autonumber."]]
- ,[Plain [Str "More."]
-  ,OrderedList (1,DefaultStyle,DefaultDelim)
-   [[Plain [Str "Nested."]]]]]
-,Para [Str "Should",Space,Str "not",Space,Str "be",Space,Str "a",Space,Str "list",Space,Str "item:"]
-,Para [Str "M.A.\160\&2007"]
-,Para [Str "B.",Space,Str "Williams"]
-,HorizontalRule
-,Header 1 ("definition-lists",[],[]) [Str "Definition",Space,Str "Lists"]
-,Para [Str "Tight",Space,Str "using",Space,Str "spaces:"]
-,DefinitionList
- [([Str "apple"],
-   [[Plain [Str "red",Space,Str "fruit"]]])
- ,([Str "orange"],
-   [[Plain [Str "orange",Space,Str "fruit"]]])
- ,([Str "banana"],
-   [[Plain [Str "yellow",Space,Str "fruit"]]])]
-,Para [Str "Tight",Space,Str "using",Space,Str "tabs:"]
-,DefinitionList
- [([Str "apple"],
-   [[Plain [Str "red",Space,Str "fruit"]]])
- ,([Str "orange"],
-   [[Plain [Str "orange",Space,Str "fruit"]]])
- ,([Str "banana"],
-   [[Plain [Str "yellow",Space,Str "fruit"]]])]
-,Para [Str "Loose:"]
-,DefinitionList
- [([Str "apple"],
-   [[Para [Str "red",Space,Str "fruit"]]])
- ,([Str "orange"],
-   [[Para [Str "orange",Space,Str "fruit"]]])
- ,([Str "banana"],
-   [[Para [Str "yellow",Space,Str "fruit"]]])]
-,Para [Str "Multiple",Space,Str "blocks",Space,Str "with",Space,Str "italics:"]
-,DefinitionList
- [([Emph [Str "apple"]],
-   [[Para [Str "red",Space,Str "fruit"]
-    ,Para [Str "contains",Space,Str "seeds,",SoftBreak,Str "crisp,",Space,Str "pleasant",Space,Str "to",Space,Str "taste"]]])
- ,([Emph [Str "orange"]],
-   [[Para [Str "orange",Space,Str "fruit"]
-    ,CodeBlock ("",[],[]) "{ orange code block }"
-    ,BlockQuote
-     [Para [Str "orange",Space,Str "block",Space,Str "quote"]]]])]
-,Para [Str "Multiple",Space,Str "definitions,",Space,Str "tight:"]
-,DefinitionList
- [([Str "apple"],
-   [[Plain [Str "red",Space,Str "fruit"]]
-   ,[Plain [Str "computer"]]])
- ,([Str "orange"],
-   [[Plain [Str "orange",Space,Str "fruit"]]
-   ,[Plain [Str "bank"]]])]
-,Para [Str "Multiple",Space,Str "definitions,",Space,Str "loose:"]
-,DefinitionList
- [([Str "apple"],
-   [[Para [Str "red",Space,Str "fruit"]]
-   ,[Para [Str "computer"]]])
- ,([Str "orange"],
-   [[Para [Str "orange",Space,Str "fruit"]]
-   ,[Para [Str "bank"]]])]
-,Para [Str "Blank",Space,Str "line",Space,Str "after",Space,Str "term,",Space,Str "indented",Space,Str "marker,",Space,Str "alternate",Space,Str "markers:"]
-,DefinitionList
- [([Str "apple"],
-   [[Para [Str "red",Space,Str "fruit"]]
-   ,[Para [Str "computer"]]])
- ,([Str "orange"],
-   [[Para [Str "orange",Space,Str "fruit"]
-    ,OrderedList (1,Decimal,Period)
-     [[Plain [Str "sublist"]]
-     ,[Plain [Str "sublist"]]]]])]
-,Header 1 ("html-blocks",[],[]) [Str "HTML",Space,Str "Blocks"]
-,Para [Str "Simple",Space,Str "block",Space,Str "on",Space,Str "one",Space,Str "line:"]
-,Div ("",[],[])
- [Plain [Str "foo"]]
-,Para [Str "And",Space,Str "nested",Space,Str "without",Space,Str "indentation:"]
-,Div ("",[],[])
- [Div ("",[],[])
-  [Div ("",[],[])
-   [Para [Str "foo"]]]
- ,Div ("",[],[])
-  [Plain [Str "bar"]]]
-,Para [Str "Interpreted",Space,Str "markdown",Space,Str "in",Space,Str "a",Space,Str "table:"]
-,RawBlock (Format "html") "<table>"
-,RawBlock (Format "html") "<tr>"
-,RawBlock (Format "html") "<td>"
-,Plain [Str "This",Space,Str "is",Space,Emph [Str "emphasized"]]
-,RawBlock (Format "html") "</td>"
-,RawBlock (Format "html") "<td>"
-,Plain [Str "And",Space,Str "this",Space,Str "is",Space,Strong [Str "strong"]]
-,RawBlock (Format "html") "</td>"
-,RawBlock (Format "html") "</tr>"
-,RawBlock (Format "html") "</table>"
-,RawBlock (Format "html") "<script type=\"text/javascript\">document.write('This *should not* be interpreted as markdown');</script>"
-,Para [Str "Here\8217s",Space,Str "a",Space,Str "simple",Space,Str "block:"]
-,Div ("",[],[])
- [Para [Str "foo"]]
-,Para [Str "This",Space,Str "should",Space,Str "be",Space,Str "a",Space,Str "code",Space,Str "block,",Space,Str "though:"]
-,CodeBlock ("",[],[]) "<div>\n    foo\n</div>"
-,Para [Str "As",Space,Str "should",Space,Str "this:"]
-,CodeBlock ("",[],[]) "<div>foo</div>"
-,Para [Str "Now,",Space,Str "nested:"]
-,Div ("",[],[])
- [Div ("",[],[])
-  [Div ("",[],[])
-   [Plain [Str "foo"]]]]
-,Para [Str "This",Space,Str "should",Space,Str "just",Space,Str "be",Space,Str "an",Space,Str "HTML",Space,Str "comment:"]
-,RawBlock (Format "html") "<!-- Comment -->"
-,Para [Str "Multiline:"]
-,RawBlock (Format "html") "<!--\nBlah\nBlah\n-->"
-,RawBlock (Format "html") "<!--\n    This is another comment.\n-->"
-,Para [Str "Code",Space,Str "block:"]
-,CodeBlock ("",[],[]) "<!-- Comment -->"
-,Para [Str "Just",Space,Str "plain",Space,Str "comment,",Space,Str "with",Space,Str "trailing",Space,Str "spaces",Space,Str "on",Space,Str "the",Space,Str "line:"]
-,RawBlock (Format "html") "<!-- foo -->"
-,Para [Str "Code:"]
-,CodeBlock ("",[],[]) "<hr />"
-,Para [Str "Hr\8217s:"]
-,RawBlock (Format "html") "<hr>"
-,RawBlock (Format "html") "<hr />"
-,RawBlock (Format "html") "<hr />"
-,RawBlock (Format "html") "<hr>"
-,RawBlock (Format "html") "<hr />"
-,RawBlock (Format "html") "<hr />"
-,RawBlock (Format "html") "<hr class=\"foo\" id=\"bar\" />"
-,RawBlock (Format "html") "<hr class=\"foo\" id=\"bar\" />"
-,RawBlock (Format "html") "<hr class=\"foo\" id=\"bar\">"
-,HorizontalRule
-,Header 1 ("inline-markup",[],[]) [Str "Inline",Space,Str "Markup"]
-,Para [Str "This",Space,Str "is",Space,Emph [Str "emphasized"],Str ",",Space,Str "and",Space,Str "so",Space,Emph [Str "is",Space,Str "this"],Str "."]
-,Para [Str "This",Space,Str "is",Space,Strong [Str "strong"],Str ",",Space,Str "and",Space,Str "so",Space,Strong [Str "is",Space,Str "this"],Str "."]
-,Para [Str "An",Space,Emph [Link ("",[],[]) [Str "emphasized",Space,Str "link"] ("/url","")],Str "."]
-,Para [Strong [Emph [Str "This",Space,Str "is",Space,Str "strong",Space,Str "and",Space,Str "em."]]]
-,Para [Str "So",Space,Str "is",Space,Strong [Emph [Str "this"]],Space,Str "word."]
-,Para [Strong [Emph [Str "This",Space,Str "is",Space,Str "strong",Space,Str "and",Space,Str "em."]]]
-,Para [Str "So",Space,Str "is",Space,Strong [Emph [Str "this"]],Space,Str "word."]
-,Para [Str "This",Space,Str "is",Space,Str "code:",Space,Code ("",[],[]) ">",Str ",",Space,Code ("",[],[]) "$",Str ",",Space,Code ("",[],[]) "\\",Str ",",Space,Code ("",[],[]) "\\$",Str ",",Space,Code ("",[],[]) "<html>",Str "."]
-,Para [Strikeout [Str "This",Space,Str "is",Space,Emph [Str "strikeout"],Str "."]]
-,Para [Str "Superscripts:",Space,Str "a",Superscript [Str "bc"],Str "d",Space,Str "a",Superscript [Emph [Str "hello"]],Space,Str "a",Superscript [Str "hello\160there"],Str "."]
-,Para [Str "Subscripts:",Space,Str "H",Subscript [Str "2"],Str "O,",Space,Str "H",Subscript [Str "23"],Str "O,",Space,Str "H",Subscript [Str "many\160of\160them"],Str "O."]
-,Para [Str "These",Space,Str "should",Space,Str "not",Space,Str "be",Space,Str "superscripts",Space,Str "or",Space,Str "subscripts,",SoftBreak,Str "because",Space,Str "of",Space,Str "the",Space,Str "unescaped",Space,Str "spaces:",Space,Str "a^b",Space,Str "c^d,",Space,Str "a~b",Space,Str "c~d."]
-,HorizontalRule
-,Header 1 ("smart-quotes-ellipses-dashes",[],[]) [Str "Smart",Space,Str "quotes,",Space,Str "ellipses,",Space,Str "dashes"]
-,Para [Quoted DoubleQuote [Str "Hello,"],Space,Str "said",Space,Str "the",Space,Str "spider.",Space,Quoted DoubleQuote [Quoted SingleQuote [Str "Shelob"],Space,Str "is",Space,Str "my",Space,Str "name."]]
-,Para [Quoted SingleQuote [Str "A"],Str ",",Space,Quoted SingleQuote [Str "B"],Str ",",Space,Str "and",Space,Quoted SingleQuote [Str "C"],Space,Str "are",Space,Str "letters."]
-,Para [Quoted SingleQuote [Str "Oak,"],Space,Quoted SingleQuote [Str "elm,"],Space,Str "and",Space,Quoted SingleQuote [Str "beech"],Space,Str "are",Space,Str "names",Space,Str "of",Space,Str "trees.",SoftBreak,Str "So",Space,Str "is",Space,Quoted SingleQuote [Str "pine."]]
-,Para [Quoted SingleQuote [Str "He",Space,Str "said,",Space,Quoted DoubleQuote [Str "I",Space,Str "want",Space,Str "to",Space,Str "go."]],Space,Str "Were",Space,Str "you",Space,Str "alive",Space,Str "in",Space,Str "the",SoftBreak,Str "70\8217s?"]
-,Para [Str "Here",Space,Str "is",Space,Str "some",Space,Str "quoted",Space,Quoted SingleQuote [Code ("",[],[]) "code"],Space,Str "and",Space,Str "a",Space,Quoted DoubleQuote [Link ("",[],[]) [Str "quoted",Space,Str "link"] ("http://example.com/?foo=1&bar=2","")],Str "."]
-,Para [Str "Some",Space,Str "dashes:",Space,Str "one\8212two",Space,Str "\8212",Space,Str "three\8212four",Space,Str "\8212",Space,Str "five."]
-,Para [Str "Dashes",Space,Str "between",Space,Str "numbers:",Space,Str "5\8211\&7,",Space,Str "255\8211\&66,",Space,Str "1987\8211\&1999."]
-,Para [Str "Ellipses\8230and\8230and\8230."]
-,HorizontalRule
-,Header 1 ("latex",[],[]) [Str "LaTeX"]
-,BulletList
- [[Plain [RawInline (Format "tex") "\\cite[22-23]{smith.1899}"]]
- ,[Plain [Math InlineMath "2+2=4"]]
- ,[Plain [Math InlineMath "x \\in y"]]
- ,[Plain [Math InlineMath "\\alpha \\wedge \\omega"]]
- ,[Plain [Math InlineMath "223"]]
- ,[Plain [Math InlineMath "p",Str "-Tree"]]
- ,[Plain [Str "Here\8217s",Space,Str "some",Space,Str "display",Space,Str "math:",SoftBreak,Math DisplayMath "\\frac{d}{dx}f(x)=\\lim_{h\\to 0}\\frac{f(x+h)-f(x)}{h}"]]
- ,[Plain [Str "Here\8217s",Space,Str "one",Space,Str "that",Space,Str "has",Space,Str "a",Space,Str "line",Space,Str "break",Space,Str "in",Space,Str "it:",Space,Math InlineMath "\\alpha + \\omega \\times x^2",Str "."]]]
-,Para [Str "These",Space,Str "shouldn\8217t",Space,Str "be",Space,Str "math:"]
-,BulletList
- [[Plain [Str "To",Space,Str "get",Space,Str "the",Space,Str "famous",Space,Str "equation,",Space,Str "write",Space,Code ("",[],[]) "$e = mc^2$",Str "."]]
- ,[Plain [Str "$22,000",Space,Str "is",Space,Str "a",Space,Emph [Str "lot"],Space,Str "of",Space,Str "money.",Space,Str "So",Space,Str "is",Space,Str "$34,000.",SoftBreak,Str "(It",Space,Str "worked",Space,Str "if",Space,Quoted DoubleQuote [Str "lot"],Space,Str "is",Space,Str "emphasized.)"]]
- ,[Plain [Str "Shoes",Space,Str "($20)",Space,Str "and",Space,Str "socks",Space,Str "($5)."]]
- ,[Plain [Str "Escaped",Space,Code ("",[],[]) "$",Str ":",Space,Str "$73",Space,Emph [Str "this",Space,Str "should",Space,Str "be",Space,Str "emphasized"],Space,Str "23$."]]]
-,Para [Str "Here\8217s",Space,Str "a",Space,Str "LaTeX",Space,Str "table:"]
-,RawBlock (Format "latex") "\\begin{tabular}{|l|l|}\\hline\nAnimal & Number \\\\ \\hline\nDog    & 2      \\\\\nCat    & 1      \\\\ \\hline\n\\end{tabular}"
-,HorizontalRule
-,Header 1 ("special-characters",[],[]) [Str "Special",Space,Str "Characters"]
-,Para [Str "Here",Space,Str "is",Space,Str "some",Space,Str "unicode:"]
-,BulletList
- [[Plain [Str "I",Space,Str "hat:",Space,Str "\206"]]
- ,[Plain [Str "o",Space,Str "umlaut:",Space,Str "\246"]]
- ,[Plain [Str "section:",Space,Str "\167"]]
- ,[Plain [Str "set",Space,Str "membership:",Space,Str "\8712"]]
- ,[Plain [Str "copyright:",Space,Str "\169"]]]
-,Para [Str "AT&T",Space,Str "has",Space,Str "an",Space,Str "ampersand",Space,Str "in",Space,Str "their",Space,Str "name."]
-,Para [Str "AT&T",Space,Str "is",Space,Str "another",Space,Str "way",Space,Str "to",Space,Str "write",Space,Str "it."]
-,Para [Str "This",Space,Str "&",Space,Str "that."]
-,Para [Str "4",Space,Str "<",Space,Str "5."]
-,Para [Str "6",Space,Str ">",Space,Str "5."]
-,Para [Str "Backslash:",Space,Str "\\"]
-,Para [Str "Backtick:",Space,Str "`"]
-,Para [Str "Asterisk:",Space,Str "*"]
-,Para [Str "Underscore:",Space,Str "_"]
-,Para [Str "Left",Space,Str "brace:",Space,Str "{"]
-,Para [Str "Right",Space,Str "brace:",Space,Str "}"]
-,Para [Str "Left",Space,Str "bracket:",Space,Str "["]
-,Para [Str "Right",Space,Str "bracket:",Space,Str "]"]
-,Para [Str "Left",Space,Str "paren:",Space,Str "("]
-,Para [Str "Right",Space,Str "paren:",Space,Str ")"]
-,Para [Str "Greater-than:",Space,Str ">"]
-,Para [Str "Hash:",Space,Str "#"]
-,Para [Str "Period:",Space,Str "."]
-,Para [Str "Bang:",Space,Str "!"]
-,Para [Str "Plus:",Space,Str "+"]
-,Para [Str "Minus:",Space,Str "-"]
-,HorizontalRule
-,Header 1 ("links",[],[]) [Str "Links"]
-,Header 2 ("explicit",[],[]) [Str "Explicit"]
-,Para [Str "Just",Space,Str "a",Space,Link ("",[],[]) [Str "URL"] ("/url/",""),Str "."]
-,Para [Link ("",[],[]) [Str "URL",Space,Str "and",Space,Str "title"] ("/url/","title"),Str "."]
-,Para [Link ("",[],[]) [Str "URL",Space,Str "and",Space,Str "title"] ("/url/","title preceded by two spaces"),Str "."]
-,Para [Link ("",[],[]) [Str "URL",Space,Str "and",Space,Str "title"] ("/url/","title preceded by a tab"),Str "."]
-,Para [Link ("",[],[]) [Str "URL",Space,Str "and",Space,Str "title"] ("/url/","title with \"quotes\" in it")]
-,Para [Link ("",[],[]) [Str "URL",Space,Str "and",Space,Str "title"] ("/url/","title with single quotes")]
-,Para [Link ("",[],[]) [Str "with_underscore"] ("/url/with_underscore","")]
-,Para [Link ("",[],[]) [Str "Email",Space,Str "link"] ("mailto:nobody@nowhere.net","")]
-,Para [Link ("",[],[]) [Str "Empty"] ("",""),Str "."]
-,Header 2 ("reference",[],[]) [Str "Reference"]
-,Para [Str "Foo",Space,Link ("",[],[]) [Str "bar"] ("/url/",""),Str "."]
-,Para [Str "With",Space,Link ("",[],[]) [Str "embedded",Space,Str "[brackets]"] ("/url/",""),Str "."]
-,Para [Link ("",[],[]) [Str "b"] ("/url/",""),Space,Str "by",Space,Str "itself",Space,Str "should",Space,Str "be",Space,Str "a",Space,Str "link."]
-,Para [Str "Indented",Space,Link ("",[],[]) [Str "once"] ("/url",""),Str "."]
-,Para [Str "Indented",Space,Link ("",[],[]) [Str "twice"] ("/url",""),Str "."]
-,Para [Str "Indented",Space,Link ("",[],[]) [Str "thrice"] ("/url",""),Str "."]
-,Para [Str "This",Space,Str "should",Space,Str "[not][]",Space,Str "be",Space,Str "a",Space,Str "link."]
-,CodeBlock ("",[],[]) "[not]: /url"
-,Para [Str "Foo",Space,Link ("",[],[]) [Str "bar"] ("/url/","Title with \"quotes\" inside"),Str "."]
-,Para [Str "Foo",Space,Link ("",[],[]) [Str "biz"] ("/url/","Title with \"quote\" inside"),Str "."]
-,Header 2 ("with-ampersands",[],[]) [Str "With",Space,Str "ampersands"]
-,Para [Str "Here\8217s",Space,Str "a",Space,Link ("",[],[]) [Str "link",Space,Str "with",Space,Str "an",Space,Str "ampersand",Space,Str "in",Space,Str "the",Space,Str "URL"] ("http://example.com/?foo=1&bar=2",""),Str "."]
-,Para [Str "Here\8217s",Space,Str "a",Space,Str "link",Space,Str "with",Space,Str "an",Space,Str "amersand",Space,Str "in",Space,Str "the",Space,Str "link",Space,Str "text:",Space,Link ("",[],[]) [Str "AT&T"] ("http://att.com/","AT&T"),Str "."]
-,Para [Str "Here\8217s",Space,Str "an",Space,Link ("",[],[]) [Str "inline",Space,Str "link"] ("/script?foo=1&bar=2",""),Str "."]
-,Para [Str "Here\8217s",Space,Str "an",Space,Link ("",[],[]) [Str "inline",Space,Str "link",Space,Str "in",Space,Str "pointy",Space,Str "braces"] ("/script?foo=1&bar=2",""),Str "."]
-,Header 2 ("autolinks",[],[]) [Str "Autolinks"]
-,Para [Str "With",Space,Str "an",Space,Str "ampersand:",Space,Link ("",[],[]) [Str "http://example.com/?foo=1&bar=2"] ("http://example.com/?foo=1&bar=2","")]
-,BulletList
- [[Plain [Str "In",Space,Str "a",Space,Str "list?"]]
- ,[Plain [Link ("",[],[]) [Str "http://example.com/"] ("http://example.com/","")]]
- ,[Plain [Str "It",Space,Str "should."]]]
-,Para [Str "An",Space,Str "e-mail",Space,Str "address:",Space,Link ("",[],[]) [Str "nobody@nowhere.net"] ("mailto:nobody@nowhere.net","")]
-,BlockQuote
- [Para [Str "Blockquoted:",Space,Link ("",[],[]) [Str "http://example.com/"] ("http://example.com/","")]]
-,Para [Str "Auto-links",Space,Str "should",Space,Str "not",Space,Str "occur",Space,Str "here:",Space,Code ("",[],[]) "<http://example.com/>"]
-,CodeBlock ("",[],[]) "or here: <http://example.com/>"
-,HorizontalRule
-,Header 1 ("images",[],[]) [Str "Images"]
-,Para [Str "From",Space,Quoted DoubleQuote [Str "Voyage",Space,Str "dans",Space,Str "la",Space,Str "Lune"],Space,Str "by",Space,Str "Georges",Space,Str "Melies",Space,Str "(1902):"]
-,Para [Image ("",[],[]) [Str "lalune"] ("lalune.jpg","fig:Voyage dans la Lune")]
-,Para [Str "Here",Space,Str "is",Space,Str "a",Space,Str "movie",Space,Image ("",[],[]) [Str "movie"] ("movie.jpg",""),Space,Str "icon."]
-,HorizontalRule
-,Header 1 ("footnotes",[],[]) [Str "Footnotes"]
-,Para [Str "Here",Space,Str "is",Space,Str "a",Space,Str "footnote",Space,Str "reference,",Note [Para [Str "Here",Space,Str "is",Space,Str "the",Space,Str "footnote.",Space,Str "It",Space,Str "can",Space,Str "go",Space,Str "anywhere",Space,Str "after",Space,Str "the",Space,Str "footnote",SoftBreak,Str "reference.",Space,Str "It",Space,Str "need",Space,Str "not",Space,Str "be",Space,Str "placed",Space,Str "at",Space,Str "the",Space,Str "end",Space,Str "of",Space,Str "the",Space,Str "document."]],Space,Str "and",Space,Str "another.",Note [Para [Str "Here\8217s",Space,Str "the",Space,Str "long",Space,Str "note.",Space,Str "This",Space,Str "one",Space,Str "contains",Space,Str "multiple",SoftBreak,Str "blocks."],Para [Str "Subsequent",Space,Str "blocks",Space,Str "are",Space,Str "indented",Space,Str "to",Space,Str "show",Space,Str "that",Space,Str "they",Space,Str "belong",Space,Str "to",Space,Str "the",SoftBreak,Str "footnote",Space,Str "(as",Space,Str "with",Space,Str "list",Space,Str "items)."],CodeBlock ("",[],[]) "  { <code> }",Para [Str "If",Space,Str "you",Space,Str "want,",Space,Str "you",Space,Str "can",Space,Str "indent",Space,Str "every",Space,Str "line,",Space,Str "but",Space,Str "you",Space,Str "can",Space,Str "also",Space,Str "be",SoftBreak,Str "lazy",Space,Str "and",Space,Str "just",Space,Str "indent",Space,Str "the",Space,Str "first",Space,Str "line",Space,Str "of",Space,Str "each",Space,Str "block."]],SoftBreak,Str "This",Space,Str "should",Space,Emph [Str "not"],Space,Str "be",Space,Str "a",Space,Str "footnote",Space,Str "reference,",Space,Str "because",Space,Str "it",SoftBreak,Str "contains",Space,Str "a",Space,Str "space.[^my",Space,Str "note]",Space,Str "Here",Space,Str "is",Space,Str "an",Space,Str "inline",Space,Str "note.",Note [Para [Str "This",SoftBreak,Str "is",Space,Emph [Str "easier"],Space,Str "to",Space,Str "type.",Space,Str "Inline",Space,Str "notes",Space,Str "may",Space,Str "contain",SoftBreak,Link ("",[],[]) [Str "links"] ("http://google.com",""),Space,Str "and",Space,Code ("",[],[]) "]",Space,Str "verbatim",Space,Str "characters,",SoftBreak,Str "as",Space,Str "well",Space,Str "as",Space,Str "[bracketed",Space,Str "text]."]]]
-,BlockQuote
- [Para [Str "Notes",Space,Str "can",Space,Str "go",Space,Str "in",Space,Str "quotes.",Note [Para [Str "In",Space,Str "quote."]]]]
-,OrderedList (1,Decimal,Period)
- [[Plain [Str "And",Space,Str "in",Space,Str "list",Space,Str "items.",Note [Para [Str "In",Space,Str "list."]]]]]
-,Para [Str "This",Space,Str "paragraph",Space,Str "should",Space,Str "not",Space,Str "be",Space,Str "part",Space,Str "of",Space,Str "the",Space,Str "note,",Space,Str "as",Space,Str "it",Space,Str "is",Space,Str "not",Space,Str "indented."]]
+Pandoc
+  Meta
+    { unMeta =
+        fromList
+          [ ( "author"
+            , MetaList
+                [ MetaInlines [ Str "John" , Space , Str "MacFarlane" ]
+                , MetaInlines [ Str "Anonymous" ]
+                ]
+            )
+          , ( "date"
+            , MetaInlines
+                [ Str "July" , Space , Str "17," , Space , Str "2006" ]
+            )
+          , ( "title"
+            , MetaInlines
+                [ Str "Pandoc"
+                , Space
+                , Str "Test"
+                , Space
+                , Str "Suite"
+                ]
+            )
+          ]
+    }
+  [ Para
+      [ Str "This"
+      , Space
+      , Str "is"
+      , Space
+      , Str "a"
+      , Space
+      , Str "set"
+      , Space
+      , Str "of"
+      , Space
+      , Str "tests"
+      , Space
+      , Str "for"
+      , Space
+      , Str "pandoc."
+      , Space
+      , Str "Most"
+      , Space
+      , Str "of"
+      , Space
+      , Str "them"
+      , Space
+      , Str "are"
+      , Space
+      , Str "adapted"
+      , Space
+      , Str "from"
+      , SoftBreak
+      , Str "John"
+      , Space
+      , Str "Gruber\8217s"
+      , Space
+      , Str "markdown"
+      , Space
+      , Str "test"
+      , Space
+      , Str "suite."
+      ]
+  , HorizontalRule
+  , Header 1 ( "headers" , [] , [] ) [ Str "Headers" ]
+  , Header
+      2
+      ( "level-2-with-an-embedded-link" , [] , [] )
+      [ Str "Level"
+      , Space
+      , Str "2"
+      , Space
+      , Str "with"
+      , Space
+      , Str "an"
+      , Space
+      , Link
+          ( "" , [] , [] )
+          [ Str "embedded" , Space , Str "link" ]
+          ( "/url" , "" )
+      ]
+  , Header
+      3
+      ( "level-3-with-emphasis" , [] , [] )
+      [ Str "Level"
+      , Space
+      , Str "3"
+      , Space
+      , Str "with"
+      , Space
+      , Emph [ Str "emphasis" ]
+      ]
+  , Header
+      4 ( "level-4" , [] , [] ) [ Str "Level" , Space , Str "4" ]
+  , Header
+      5 ( "level-5" , [] , [] ) [ Str "Level" , Space , Str "5" ]
+  , Header
+      1 ( "level-1" , [] , [] ) [ Str "Level" , Space , Str "1" ]
+  , Header
+      2
+      ( "level-2-with-emphasis" , [] , [] )
+      [ Str "Level"
+      , Space
+      , Str "2"
+      , Space
+      , Str "with"
+      , Space
+      , Emph [ Str "emphasis" ]
+      ]
+  , Header
+      3 ( "level-3" , [] , [] ) [ Str "Level" , Space , Str "3" ]
+  , Para
+      [ Str "with"
+      , Space
+      , Str "no"
+      , Space
+      , Str "blank"
+      , Space
+      , Str "line"
+      ]
+  , Header
+      2 ( "level-2" , [] , [] ) [ Str "Level" , Space , Str "2" ]
+  , Para
+      [ Str "with"
+      , Space
+      , Str "no"
+      , Space
+      , Str "blank"
+      , Space
+      , Str "line"
+      ]
+  , HorizontalRule
+  , Header 1 ( "paragraphs" , [] , [] ) [ Str "Paragraphs" ]
+  , Para
+      [ Str "Here\8217s"
+      , Space
+      , Str "a"
+      , Space
+      , Str "regular"
+      , Space
+      , Str "paragraph."
+      ]
+  , Para
+      [ Str "In"
+      , Space
+      , Str "Markdown"
+      , Space
+      , Str "1.0.0"
+      , Space
+      , Str "and"
+      , Space
+      , Str "earlier."
+      , Space
+      , Str "Version"
+      , SoftBreak
+      , Str "8."
+      , Space
+      , Str "This"
+      , Space
+      , Str "line"
+      , Space
+      , Str "turns"
+      , Space
+      , Str "into"
+      , Space
+      , Str "a"
+      , Space
+      , Str "list"
+      , Space
+      , Str "item."
+      , SoftBreak
+      , Str "Because"
+      , Space
+      , Str "a"
+      , Space
+      , Str "hard-wrapped"
+      , Space
+      , Str "line"
+      , Space
+      , Str "in"
+      , Space
+      , Str "the"
+      , SoftBreak
+      , Str "middle"
+      , Space
+      , Str "of"
+      , Space
+      , Str "a"
+      , Space
+      , Str "paragraph"
+      , Space
+      , Str "looked"
+      , Space
+      , Str "like"
+      , Space
+      , Str "a"
+      , SoftBreak
+      , Str "list"
+      , Space
+      , Str "item."
+      ]
+  , Para
+      [ Str "Here\8217s"
+      , Space
+      , Str "one"
+      , Space
+      , Str "with"
+      , Space
+      , Str "a"
+      , Space
+      , Str "bullet."
+      , SoftBreak
+      , Str "*"
+      , Space
+      , Str "criminey."
+      ]
+  , Para
+      [ Str "There"
+      , Space
+      , Str "should"
+      , Space
+      , Str "be"
+      , Space
+      , Str "a"
+      , Space
+      , Str "hard"
+      , Space
+      , Str "line"
+      , Space
+      , Str "break"
+      , LineBreak
+      , Str "here."
+      ]
+  , HorizontalRule
+  , Header
+      1
+      ( "block-quotes" , [] , [] )
+      [ Str "Block" , Space , Str "Quotes" ]
+  , Para [ Str "E-mail" , Space , Str "style:" ]
+  , BlockQuote
+      [ Para
+          [ Str "This"
+          , Space
+          , Str "is"
+          , Space
+          , Str "a"
+          , Space
+          , Str "block"
+          , Space
+          , Str "quote."
+          , SoftBreak
+          , Str "It"
+          , Space
+          , Str "is"
+          , Space
+          , Str "pretty"
+          , Space
+          , Str "short."
+          ]
+      ]
+  , BlockQuote
+      [ Para
+          [ Str "Code"
+          , Space
+          , Str "in"
+          , Space
+          , Str "a"
+          , Space
+          , Str "block"
+          , Space
+          , Str "quote:"
+          ]
+      , CodeBlock
+          ( "" , [] , [] ) "sub status {\n    print \"working\";\n}"
+      , Para [ Str "A" , Space , Str "list:" ]
+      , OrderedList
+          ( 1 , Decimal , Period )
+          [ [ Plain [ Str "item" , Space , Str "one" ] ]
+          , [ Plain [ Str "item" , Space , Str "two" ] ]
+          ]
+      , Para
+          [ Str "Nested"
+          , Space
+          , Str "block"
+          , Space
+          , Str "quotes:"
+          ]
+      , BlockQuote [ Para [ Str "nested" ] ]
+      , BlockQuote [ Para [ Str "nested" ] ]
+      ]
+  , Para
+      [ Str "This"
+      , Space
+      , Str "should"
+      , Space
+      , Str "not"
+      , Space
+      , Str "be"
+      , Space
+      , Str "a"
+      , Space
+      , Str "block"
+      , Space
+      , Str "quote:"
+      , Space
+      , Str "2"
+      , SoftBreak
+      , Str ">"
+      , Space
+      , Str "1."
+      ]
+  , Para
+      [ Str "And"
+      , Space
+      , Str "a"
+      , Space
+      , Str "following"
+      , Space
+      , Str "paragraph."
+      ]
+  , HorizontalRule
+  , Header
+      1
+      ( "code-blocks" , [] , [] )
+      [ Str "Code" , Space , Str "Blocks" ]
+  , Para [ Str "Code:" ]
+  , CodeBlock
+      ( "" , [] , [] )
+      "---- (should be four hyphens)\n\nsub status {\n    print \"working\";\n}\n\nthis code block is indented by one tab"
+  , Para [ Str "And:" ]
+  , CodeBlock
+      ( "" , [] , [] )
+      "    this code block is indented by two tabs\n\nThese should not be escaped:  \\$ \\\\ \\> \\[ \\{"
+  , HorizontalRule
+  , Header 1 ( "lists" , [] , [] ) [ Str "Lists" ]
+  , Header 2 ( "unordered" , [] , [] ) [ Str "Unordered" ]
+  , Para [ Str "Asterisks" , Space , Str "tight:" ]
+  , BulletList
+      [ [ Plain [ Str "asterisk" , Space , Str "1" ] ]
+      , [ Plain [ Str "asterisk" , Space , Str "2" ] ]
+      , [ Plain [ Str "asterisk" , Space , Str "3" ] ]
+      ]
+  , Para [ Str "Asterisks" , Space , Str "loose:" ]
+  , BulletList
+      [ [ Para [ Str "asterisk" , Space , Str "1" ] ]
+      , [ Para [ Str "asterisk" , Space , Str "2" ] ]
+      , [ Para [ Str "asterisk" , Space , Str "3" ] ]
+      ]
+  , Para [ Str "Pluses" , Space , Str "tight:" ]
+  , BulletList
+      [ [ Plain [ Str "Plus" , Space , Str "1" ] ]
+      , [ Plain [ Str "Plus" , Space , Str "2" ] ]
+      , [ Plain [ Str "Plus" , Space , Str "3" ] ]
+      ]
+  , Para [ Str "Pluses" , Space , Str "loose:" ]
+  , BulletList
+      [ [ Para [ Str "Plus" , Space , Str "1" ] ]
+      , [ Para [ Str "Plus" , Space , Str "2" ] ]
+      , [ Para [ Str "Plus" , Space , Str "3" ] ]
+      ]
+  , Para [ Str "Minuses" , Space , Str "tight:" ]
+  , BulletList
+      [ [ Plain [ Str "Minus" , Space , Str "1" ] ]
+      , [ Plain [ Str "Minus" , Space , Str "2" ] ]
+      , [ Plain [ Str "Minus" , Space , Str "3" ] ]
+      ]
+  , Para [ Str "Minuses" , Space , Str "loose:" ]
+  , BulletList
+      [ [ Para [ Str "Minus" , Space , Str "1" ] ]
+      , [ Para [ Str "Minus" , Space , Str "2" ] ]
+      , [ Para [ Str "Minus" , Space , Str "3" ] ]
+      ]
+  , Header 2 ( "ordered" , [] , [] ) [ Str "Ordered" ]
+  , Para [ Str "Tight:" ]
+  , OrderedList
+      ( 1 , Decimal , Period )
+      [ [ Plain [ Str "First" ] ]
+      , [ Plain [ Str "Second" ] ]
+      , [ Plain [ Str "Third" ] ]
+      ]
+  , Para [ Str "and:" ]
+  , OrderedList
+      ( 1 , Decimal , Period )
+      [ [ Plain [ Str "One" ] ]
+      , [ Plain [ Str "Two" ] ]
+      , [ Plain [ Str "Three" ] ]
+      ]
+  , Para
+      [ Str "Loose" , Space , Str "using" , Space , Str "tabs:" ]
+  , OrderedList
+      ( 1 , Decimal , Period )
+      [ [ Para [ Str "First" ] ]
+      , [ Para [ Str "Second" ] ]
+      , [ Para [ Str "Third" ] ]
+      ]
+  , Para
+      [ Str "and" , Space , Str "using" , Space , Str "spaces:" ]
+  , OrderedList
+      ( 1 , Decimal , Period )
+      [ [ Para [ Str "One" ] ]
+      , [ Para [ Str "Two" ] ]
+      , [ Para [ Str "Three" ] ]
+      ]
+  , Para [ Str "Multiple" , Space , Str "paragraphs:" ]
+  , 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."
+            ]
+        ]
+      , [ Para [ Str "Item" , Space , Str "2." ] ]
+      , [ Para [ Str "Item" , Space , Str "3." ] ]
+      ]
+  , Header 2 ( "nested" , [] , [] ) [ Str "Nested" ]
+  , BulletList
+      [ [ Plain [ Str "Tab" ]
+        , BulletList
+            [ [ Plain [ Str "Tab" ]
+              , BulletList [ [ Plain [ Str "Tab" ] ] ]
+              ]
+            ]
+        ]
+      ]
+  , Para [ Str "Here\8217s" , Space , Str "another:" ]
+  , OrderedList
+      ( 1 , Decimal , Period )
+      [ [ Plain [ Str "First" ] ]
+      , [ Plain [ Str "Second:" ]
+        , BulletList
+            [ [ Plain [ Str "Fee" ] ]
+            , [ Plain [ Str "Fie" ] ]
+            , [ Plain [ Str "Foe" ] ]
+            ]
+        ]
+      , [ Plain [ Str "Third" ] ]
+      ]
+  , Para
+      [ Str "Same"
+      , Space
+      , Str "thing"
+      , Space
+      , Str "but"
+      , Space
+      , Str "with"
+      , Space
+      , Str "paragraphs:"
+      ]
+  , OrderedList
+      ( 1 , Decimal , Period )
+      [ [ Para [ Str "First" ] ]
+      , [ Para [ Str "Second:" ]
+        , BulletList
+            [ [ Plain [ Str "Fee" ] ]
+            , [ Plain [ Str "Fie" ] ]
+            , [ Plain [ Str "Foe" ] ]
+            ]
+        ]
+      , [ Para [ Str "Third" ] ]
+      ]
+  , Header
+      2
+      ( "tabs-and-spaces" , [] , [] )
+      [ Str "Tabs" , Space , Str "and" , Space , Str "spaces" ]
+  , BulletList
+      [ [ Para
+            [ Str "this"
+            , Space
+            , Str "is"
+            , Space
+            , Str "a"
+            , Space
+            , Str "list"
+            , Space
+            , Str "item"
+            , SoftBreak
+            , Str "indented"
+            , Space
+            , Str "with"
+            , Space
+            , Str "tabs"
+            ]
+        ]
+      , [ Para
+            [ Str "this"
+            , Space
+            , Str "is"
+            , Space
+            , Str "a"
+            , Space
+            , Str "list"
+            , Space
+            , Str "item"
+            , SoftBreak
+            , Str "indented"
+            , Space
+            , Str "with"
+            , Space
+            , Str "spaces"
+            ]
+        , BulletList
+            [ [ 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 "tabs"
+                  ]
+              ]
+            , [ 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 )
+      [ [ 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 )
+            [ [ Plain
+                  [ Str "sublist"
+                  , Space
+                  , Str "with"
+                  , Space
+                  , Str "roman"
+                  , Space
+                  , Str "numerals,"
+                  , SoftBreak
+                  , Str "starting"
+                  , Space
+                  , Str "with"
+                  , Space
+                  , Str "4"
+                  ]
+              ]
+            , [ Plain [ Str "more" , Space , Str "items" ]
+              , OrderedList
+                  ( 1 , UpperAlpha , TwoParens )
+                  [ [ Plain [ Str "a" , Space , Str "subsublist" ] ]
+                  , [ Plain [ Str "a" , Space , Str "subsublist" ] ]
+                  ]
+              ]
+            ]
+        ]
+      ]
+  , Para [ Str "Nesting:" ]
+  , OrderedList
+      ( 1 , UpperAlpha , Period )
+      [ [ Plain [ Str "Upper" , Space , Str "Alpha" ]
+        , OrderedList
+            ( 1 , UpperRoman , Period )
+            [ [ Plain [ Str "Upper" , Space , Str "Roman." ]
+              , OrderedList
+                  ( 6 , Decimal , TwoParens )
+                  [ [ Plain
+                        [ Str "Decimal"
+                        , Space
+                        , Str "start"
+                        , Space
+                        , Str "with"
+                        , Space
+                        , Str "6"
+                        ]
+                    , OrderedList
+                        ( 3 , LowerAlpha , OneParen )
+                        [ [ Plain
+                              [ Str "Lower"
+                              , Space
+                              , Str "alpha"
+                              , Space
+                              , Str "with"
+                              , Space
+                              , Str "paren"
+                              ]
+                          ]
+                        ]
+                    ]
+                  ]
+              ]
+            ]
+        ]
+      ]
+  , Para [ Str "Autonumbering:" ]
+  , OrderedList
+      ( 1 , DefaultStyle , DefaultDelim )
+      [ [ Plain [ Str "Autonumber." ] ]
+      , [ Plain [ Str "More." ]
+        , OrderedList
+            ( 1 , DefaultStyle , DefaultDelim )
+            [ [ Plain [ Str "Nested." ] ] ]
+        ]
+      ]
+  , Para
+      [ Str "Should"
+      , Space
+      , Str "not"
+      , Space
+      , Str "be"
+      , Space
+      , Str "a"
+      , Space
+      , Str "list"
+      , Space
+      , Str "item:"
+      ]
+  , Para [ Str "M.A.\160\&2007" ]
+  , Para [ Str "B." , Space , Str "Williams" ]
+  , HorizontalRule
+  , Header
+      1
+      ( "definition-lists" , [] , [] )
+      [ Str "Definition" , Space , Str "Lists" ]
+  , Para
+      [ Str "Tight"
+      , Space
+      , Str "using"
+      , Space
+      , Str "spaces:"
+      ]
+  , DefinitionList
+      [ ( [ Str "apple" ]
+        , [ [ Plain [ Str "red" , Space , Str "fruit" ] ] ]
+        )
+      , ( [ Str "orange" ]
+        , [ [ Plain [ Str "orange" , Space , Str "fruit" ] ] ]
+        )
+      , ( [ Str "banana" ]
+        , [ [ Plain [ Str "yellow" , Space , Str "fruit" ] ] ]
+        )
+      ]
+  , Para
+      [ Str "Tight" , Space , Str "using" , Space , Str "tabs:" ]
+  , DefinitionList
+      [ ( [ Str "apple" ]
+        , [ [ Plain [ Str "red" , Space , Str "fruit" ] ] ]
+        )
+      , ( [ Str "orange" ]
+        , [ [ Plain [ Str "orange" , Space , Str "fruit" ] ] ]
+        )
+      , ( [ Str "banana" ]
+        , [ [ Plain [ Str "yellow" , Space , Str "fruit" ] ] ]
+        )
+      ]
+  , Para [ Str "Loose:" ]
+  , DefinitionList
+      [ ( [ Str "apple" ]
+        , [ [ Para [ Str "red" , Space , Str "fruit" ] ] ]
+        )
+      , ( [ Str "orange" ]
+        , [ [ Para [ Str "orange" , Space , Str "fruit" ] ] ]
+        )
+      , ( [ Str "banana" ]
+        , [ [ Para [ Str "yellow" , Space , Str "fruit" ] ] ]
+        )
+      ]
+  , Para
+      [ Str "Multiple"
+      , Space
+      , Str "blocks"
+      , Space
+      , Str "with"
+      , Space
+      , Str "italics:"
+      ]
+  , DefinitionList
+      [ ( [ Emph [ Str "apple" ] ]
+        , [ [ Para [ Str "red" , Space , Str "fruit" ]
+            , Para
+                [ Str "contains"
+                , Space
+                , Str "seeds,"
+                , SoftBreak
+                , Str "crisp,"
+                , Space
+                , Str "pleasant"
+                , Space
+                , Str "to"
+                , Space
+                , Str "taste"
+                ]
+            ]
+          ]
+        )
+      , ( [ Emph [ Str "orange" ] ]
+        , [ [ Para [ Str "orange" , Space , Str "fruit" ]
+            , CodeBlock ( "" , [] , [] ) "{ orange code block }"
+            , BlockQuote
+                [ Para
+                    [ Str "orange"
+                    , Space
+                    , Str "block"
+                    , Space
+                    , Str "quote"
+                    ]
+                ]
+            ]
+          ]
+        )
+      ]
+  , Para
+      [ Str "Multiple"
+      , Space
+      , Str "definitions,"
+      , Space
+      , Str "tight:"
+      ]
+  , DefinitionList
+      [ ( [ Str "apple" ]
+        , [ [ Plain [ Str "red" , Space , Str "fruit" ] ]
+          , [ Plain [ Str "computer" ] ]
+          ]
+        )
+      , ( [ Str "orange" ]
+        , [ [ Plain [ Str "orange" , Space , Str "fruit" ] ]
+          , [ Plain [ Str "bank" ] ]
+          ]
+        )
+      ]
+  , Para
+      [ Str "Multiple"
+      , Space
+      , Str "definitions,"
+      , Space
+      , Str "loose:"
+      ]
+  , DefinitionList
+      [ ( [ Str "apple" ]
+        , [ [ Para [ Str "red" , Space , Str "fruit" ] ]
+          , [ Para [ Str "computer" ] ]
+          ]
+        )
+      , ( [ Str "orange" ]
+        , [ [ Para [ Str "orange" , Space , Str "fruit" ] ]
+          , [ Para [ Str "bank" ] ]
+          ]
+        )
+      ]
+  , Para
+      [ Str "Blank"
+      , Space
+      , Str "line"
+      , Space
+      , Str "after"
+      , Space
+      , Str "term,"
+      , Space
+      , Str "indented"
+      , Space
+      , Str "marker,"
+      , Space
+      , Str "alternate"
+      , Space
+      , Str "markers:"
+      ]
+  , DefinitionList
+      [ ( [ Str "apple" ]
+        , [ [ Para [ Str "red" , Space , Str "fruit" ] ]
+          , [ Para [ Str "computer" ] ]
+          ]
+        )
+      , ( [ Str "orange" ]
+        , [ [ Para [ Str "orange" , Space , Str "fruit" ]
+            , OrderedList
+                ( 1 , Decimal , Period )
+                [ [ Plain [ Str "sublist" ] ]
+                , [ Plain [ Str "sublist" ] ]
+                ]
+            ]
+          ]
+        )
+      ]
+  , Header
+      1
+      ( "html-blocks" , [] , [] )
+      [ Str "HTML" , Space , Str "Blocks" ]
+  , Para
+      [ Str "Simple"
+      , Space
+      , Str "block"
+      , Space
+      , Str "on"
+      , Space
+      , Str "one"
+      , Space
+      , Str "line:"
+      ]
+  , Div ( "" , [] , [] ) [ Plain [ Str "foo" ] ]
+  , Para
+      [ Str "And"
+      , Space
+      , Str "nested"
+      , Space
+      , Str "without"
+      , Space
+      , Str "indentation:"
+      ]
+  , Div
+      ( "" , [] , [] )
+      [ Div
+          ( "" , [] , [] )
+          [ Div ( "" , [] , [] ) [ Para [ Str "foo" ] ] ]
+      , Div ( "" , [] , [] ) [ Plain [ Str "bar" ] ]
+      ]
+  , Para
+      [ Str "Interpreted"
+      , Space
+      , Str "markdown"
+      , Space
+      , Str "in"
+      , Space
+      , Str "a"
+      , Space
+      , Str "table:"
+      ]
+  , RawBlock (Format "html") "<table>"
+  , RawBlock (Format "html") "<tr>"
+  , RawBlock (Format "html") "<td>"
+  , Plain
+      [ Str "This"
+      , Space
+      , Str "is"
+      , Space
+      , Emph [ Str "emphasized" ]
+      ]
+  , RawBlock (Format "html") "</td>"
+  , RawBlock (Format "html") "<td>"
+  , Plain
+      [ Str "And"
+      , Space
+      , Str "this"
+      , Space
+      , Str "is"
+      , Space
+      , Strong [ Str "strong" ]
+      ]
+  , RawBlock (Format "html") "</td>"
+  , RawBlock (Format "html") "</tr>"
+  , RawBlock (Format "html") "</table>"
+  , RawBlock
+      (Format "html")
+      "<script type=\"text/javascript\">document.write('This *should not* be interpreted as markdown');</script>"
+  , Para
+      [ Str "Here\8217s"
+      , Space
+      , Str "a"
+      , Space
+      , Str "simple"
+      , Space
+      , Str "block:"
+      ]
+  , Div ( "" , [] , [] ) [ Para [ Str "foo" ] ]
+  , Para
+      [ Str "This"
+      , Space
+      , Str "should"
+      , Space
+      , Str "be"
+      , Space
+      , Str "a"
+      , Space
+      , Str "code"
+      , Space
+      , Str "block,"
+      , Space
+      , Str "though:"
+      ]
+  , CodeBlock ( "" , [] , [] ) "<div>\n    foo\n</div>"
+  , Para
+      [ Str "As" , Space , Str "should" , Space , Str "this:" ]
+  , CodeBlock ( "" , [] , [] ) "<div>foo</div>"
+  , Para [ Str "Now," , Space , Str "nested:" ]
+  , Div
+      ( "" , [] , [] )
+      [ Div
+          ( "" , [] , [] )
+          [ Div ( "" , [] , [] ) [ Plain [ Str "foo" ] ] ]
+      ]
+  , Para
+      [ Str "This"
+      , Space
+      , Str "should"
+      , Space
+      , Str "just"
+      , Space
+      , Str "be"
+      , Space
+      , Str "an"
+      , Space
+      , Str "HTML"
+      , Space
+      , Str "comment:"
+      ]
+  , RawBlock (Format "html") "<!-- Comment -->"
+  , Para [ Str "Multiline:" ]
+  , RawBlock (Format "html") "<!--\nBlah\nBlah\n-->"
+  , RawBlock
+      (Format "html") "<!--\n    This is another comment.\n-->"
+  , Para [ Str "Code" , Space , Str "block:" ]
+  , CodeBlock ( "" , [] , [] ) "<!-- Comment -->"
+  , Para
+      [ Str "Just"
+      , Space
+      , Str "plain"
+      , Space
+      , Str "comment,"
+      , Space
+      , Str "with"
+      , Space
+      , Str "trailing"
+      , Space
+      , Str "spaces"
+      , Space
+      , Str "on"
+      , Space
+      , Str "the"
+      , Space
+      , Str "line:"
+      ]
+  , RawBlock (Format "html") "<!-- foo -->"
+  , Para [ Str "Code:" ]
+  , CodeBlock ( "" , [] , [] ) "<hr />"
+  , Para [ Str "Hr\8217s:" ]
+  , RawBlock (Format "html") "<hr>"
+  , RawBlock (Format "html") "<hr />"
+  , RawBlock (Format "html") "<hr />"
+  , RawBlock (Format "html") "<hr>"
+  , RawBlock (Format "html") "<hr />"
+  , RawBlock (Format "html") "<hr />"
+  , RawBlock (Format "html") "<hr class=\"foo\" id=\"bar\" />"
+  , RawBlock (Format "html") "<hr class=\"foo\" id=\"bar\" />"
+  , RawBlock (Format "html") "<hr class=\"foo\" id=\"bar\">"
+  , HorizontalRule
+  , Header
+      1
+      ( "inline-markup" , [] , [] )
+      [ Str "Inline" , Space , Str "Markup" ]
+  , Para
+      [ Str "This"
+      , Space
+      , Str "is"
+      , Space
+      , Emph [ Str "emphasized" ]
+      , Str ","
+      , Space
+      , Str "and"
+      , Space
+      , Str "so"
+      , Space
+      , Emph [ Str "is" , Space , Str "this" ]
+      , Str "."
+      ]
+  , Para
+      [ Str "This"
+      , Space
+      , Str "is"
+      , Space
+      , Strong [ Str "strong" ]
+      , Str ","
+      , Space
+      , Str "and"
+      , Space
+      , Str "so"
+      , Space
+      , Strong [ Str "is" , Space , Str "this" ]
+      , Str "."
+      ]
+  , Para
+      [ Str "An"
+      , Space
+      , Emph
+          [ Link
+              ( "" , [] , [] )
+              [ Str "emphasized" , Space , Str "link" ]
+              ( "/url" , "" )
+          ]
+      , Str "."
+      ]
+  , Para
+      [ Strong
+          [ Emph
+              [ Str "This"
+              , Space
+              , Str "is"
+              , Space
+              , Str "strong"
+              , Space
+              , Str "and"
+              , Space
+              , Str "em."
+              ]
+          ]
+      ]
+  , Para
+      [ Str "So"
+      , Space
+      , Str "is"
+      , Space
+      , Strong [ Emph [ Str "this" ] ]
+      , Space
+      , Str "word."
+      ]
+  , Para
+      [ Strong
+          [ Emph
+              [ Str "This"
+              , Space
+              , Str "is"
+              , Space
+              , Str "strong"
+              , Space
+              , Str "and"
+              , Space
+              , Str "em."
+              ]
+          ]
+      ]
+  , Para
+      [ Str "So"
+      , Space
+      , Str "is"
+      , Space
+      , Strong [ Emph [ Str "this" ] ]
+      , Space
+      , Str "word."
+      ]
+  , Para
+      [ Str "This"
+      , Space
+      , Str "is"
+      , Space
+      , Str "code:"
+      , Space
+      , Code ( "" , [] , [] ) ">"
+      , Str ","
+      , Space
+      , Code ( "" , [] , [] ) "$"
+      , Str ","
+      , Space
+      , Code ( "" , [] , [] ) "\\"
+      , Str ","
+      , Space
+      , Code ( "" , [] , [] ) "\\$"
+      , Str ","
+      , Space
+      , Code ( "" , [] , [] ) "<html>"
+      , Str "."
+      ]
+  , Para
+      [ Strikeout
+          [ Str "This"
+          , Space
+          , Str "is"
+          , Space
+          , Emph [ Str "strikeout" ]
+          , Str "."
+          ]
+      ]
+  , Para
+      [ Str "Superscripts:"
+      , Space
+      , Str "a"
+      , Superscript [ Str "bc" ]
+      , Str "d"
+      , Space
+      , Str "a"
+      , Superscript [ Emph [ Str "hello" ] ]
+      , Space
+      , Str "a"
+      , Superscript [ Str "hello\160there" ]
+      , Str "."
+      ]
+  , Para
+      [ Str "Subscripts:"
+      , Space
+      , Str "H"
+      , Subscript [ Str "2" ]
+      , Str "O,"
+      , Space
+      , Str "H"
+      , Subscript [ Str "23" ]
+      , Str "O,"
+      , Space
+      , Str "H"
+      , Subscript [ Str "many\160of\160them" ]
+      , Str "O."
+      ]
+  , Para
+      [ Str "These"
+      , Space
+      , Str "should"
+      , Space
+      , Str "not"
+      , Space
+      , Str "be"
+      , Space
+      , Str "superscripts"
+      , Space
+      , Str "or"
+      , Space
+      , Str "subscripts,"
+      , SoftBreak
+      , Str "because"
+      , Space
+      , Str "of"
+      , Space
+      , Str "the"
+      , Space
+      , Str "unescaped"
+      , Space
+      , Str "spaces:"
+      , Space
+      , Str "a^b"
+      , Space
+      , Str "c^d,"
+      , Space
+      , Str "a~b"
+      , Space
+      , Str "c~d."
+      ]
+  , HorizontalRule
+  , Header
+      1
+      ( "smart-quotes-ellipses-dashes" , [] , [] )
+      [ Str "Smart"
+      , Space
+      , Str "quotes,"
+      , Space
+      , Str "ellipses,"
+      , Space
+      , Str "dashes"
+      ]
+  , Para
+      [ Quoted DoubleQuote [ Str "Hello," ]
+      , Space
+      , Str "said"
+      , Space
+      , Str "the"
+      , Space
+      , Str "spider."
+      , Space
+      , Quoted
+          DoubleQuote
+          [ Quoted SingleQuote [ Str "Shelob" ]
+          , Space
+          , Str "is"
+          , Space
+          , Str "my"
+          , Space
+          , Str "name."
+          ]
+      ]
+  , Para
+      [ Quoted SingleQuote [ Str "A" ]
+      , Str ","
+      , Space
+      , Quoted SingleQuote [ Str "B" ]
+      , Str ","
+      , Space
+      , Str "and"
+      , Space
+      , Quoted SingleQuote [ Str "C" ]
+      , Space
+      , Str "are"
+      , Space
+      , Str "letters."
+      ]
+  , Para
+      [ Quoted SingleQuote [ Str "Oak," ]
+      , Space
+      , Quoted SingleQuote [ Str "elm," ]
+      , Space
+      , Str "and"
+      , Space
+      , Quoted SingleQuote [ Str "beech" ]
+      , Space
+      , Str "are"
+      , Space
+      , Str "names"
+      , Space
+      , Str "of"
+      , Space
+      , Str "trees."
+      , SoftBreak
+      , Str "So"
+      , Space
+      , Str "is"
+      , Space
+      , Quoted SingleQuote [ Str "pine." ]
+      ]
+  , Para
+      [ Quoted
+          SingleQuote
+          [ Str "He"
+          , Space
+          , Str "said,"
+          , Space
+          , Quoted
+              DoubleQuote
+              [ Str "I"
+              , Space
+              , Str "want"
+              , Space
+              , Str "to"
+              , Space
+              , Str "go."
+              ]
+          ]
+      , Space
+      , Str "Were"
+      , Space
+      , Str "you"
+      , Space
+      , Str "alive"
+      , Space
+      , Str "in"
+      , Space
+      , Str "the"
+      , SoftBreak
+      , Str "70\8217s?"
+      ]
+  , Para
+      [ Str "Here"
+      , Space
+      , Str "is"
+      , Space
+      , Str "some"
+      , Space
+      , Str "quoted"
+      , Space
+      , Quoted SingleQuote [ Code ( "" , [] , [] ) "code" ]
+      , Space
+      , Str "and"
+      , Space
+      , Str "a"
+      , Space
+      , Quoted
+          DoubleQuote
+          [ Link
+              ( "" , [] , [] )
+              [ Str "quoted" , Space , Str "link" ]
+              ( "http://example.com/?foo=1&bar=2" , "" )
+          ]
+      , Str "."
+      ]
+  , Para
+      [ Str "Some"
+      , Space
+      , Str "dashes:"
+      , Space
+      , Str "one\8212two"
+      , Space
+      , Str "\8212"
+      , Space
+      , Str "three\8212four"
+      , Space
+      , Str "\8212"
+      , Space
+      , Str "five."
+      ]
+  , Para
+      [ Str "Dashes"
+      , Space
+      , Str "between"
+      , Space
+      , Str "numbers:"
+      , Space
+      , Str "5\8211\&7,"
+      , Space
+      , Str "255\8211\&66,"
+      , Space
+      , Str "1987\8211\&1999."
+      ]
+  , Para [ Str "Ellipses\8230and\8230and\8230." ]
+  , HorizontalRule
+  , Header 1 ( "latex" , [] , [] ) [ Str "LaTeX" ]
+  , BulletList
+      [ [ Plain
+            [ RawInline (Format "tex") "\\cite[22-23]{smith.1899}" ]
+        ]
+      , [ Plain [ Math InlineMath "2+2=4" ] ]
+      , [ Plain [ Math InlineMath "x \\in y" ] ]
+      , [ Plain [ Math InlineMath "\\alpha \\wedge \\omega" ] ]
+      , [ Plain [ Math InlineMath "223" ] ]
+      , [ Plain [ Math InlineMath "p" , Str "-Tree" ] ]
+      , [ Plain
+            [ Str "Here\8217s"
+            , Space
+            , Str "some"
+            , Space
+            , Str "display"
+            , Space
+            , Str "math:"
+            , SoftBreak
+            , Math
+                DisplayMath
+                "\\frac{d}{dx}f(x)=\\lim_{h\\to 0}\\frac{f(x+h)-f(x)}{h}"
+            ]
+        ]
+      , [ Plain
+            [ Str "Here\8217s"
+            , Space
+            , Str "one"
+            , Space
+            , Str "that"
+            , Space
+            , Str "has"
+            , Space
+            , Str "a"
+            , Space
+            , Str "line"
+            , Space
+            , Str "break"
+            , Space
+            , Str "in"
+            , Space
+            , Str "it:"
+            , Space
+            , Math InlineMath "\\alpha + \\omega \\times x^2"
+            , Str "."
+            ]
+        ]
+      ]
+  , Para
+      [ Str "These"
+      , Space
+      , Str "shouldn\8217t"
+      , Space
+      , Str "be"
+      , Space
+      , Str "math:"
+      ]
+  , BulletList
+      [ [ Plain
+            [ Str "To"
+            , Space
+            , Str "get"
+            , Space
+            , Str "the"
+            , Space
+            , Str "famous"
+            , Space
+            , Str "equation,"
+            , Space
+            , Str "write"
+            , Space
+            , Code ( "" , [] , [] ) "$e = mc^2$"
+            , Str "."
+            ]
+        ]
+      , [ Plain
+            [ Str "$22,000"
+            , Space
+            , Str "is"
+            , Space
+            , Str "a"
+            , Space
+            , Emph [ Str "lot" ]
+            , Space
+            , Str "of"
+            , Space
+            , Str "money."
+            , Space
+            , Str "So"
+            , Space
+            , Str "is"
+            , Space
+            , Str "$34,000."
+            , SoftBreak
+            , Str "(It"
+            , Space
+            , Str "worked"
+            , Space
+            , Str "if"
+            , Space
+            , Quoted DoubleQuote [ Str "lot" ]
+            , Space
+            , Str "is"
+            , Space
+            , Str "emphasized.)"
+            ]
+        ]
+      , [ Plain
+            [ Str "Shoes"
+            , Space
+            , Str "($20)"
+            , Space
+            , Str "and"
+            , Space
+            , Str "socks"
+            , Space
+            , Str "($5)."
+            ]
+        ]
+      , [ Plain
+            [ Str "Escaped"
+            , Space
+            , Code ( "" , [] , [] ) "$"
+            , Str ":"
+            , Space
+            , Str "$73"
+            , Space
+            , Emph
+                [ Str "this"
+                , Space
+                , Str "should"
+                , Space
+                , Str "be"
+                , Space
+                , Str "emphasized"
+                ]
+            , Space
+            , Str "23$."
+            ]
+        ]
+      ]
+  , Para
+      [ Str "Here\8217s"
+      , Space
+      , Str "a"
+      , Space
+      , Str "LaTeX"
+      , Space
+      , Str "table:"
+      ]
+  , RawBlock
+      (Format "tex")
+      "\\begin{tabular}{|l|l|}\\hline\nAnimal & Number \\\\ \\hline\nDog    & 2      \\\\\nCat    & 1      \\\\ \\hline\n\\end{tabular}"
+  , HorizontalRule
+  , Header
+      1
+      ( "special-characters" , [] , [] )
+      [ Str "Special" , Space , Str "Characters" ]
+  , Para
+      [ Str "Here"
+      , Space
+      , Str "is"
+      , Space
+      , Str "some"
+      , Space
+      , Str "unicode:"
+      ]
+  , BulletList
+      [ [ Plain
+            [ Str "I" , Space , Str "hat:" , Space , Str "\206" ]
+        ]
+      , [ Plain
+            [ Str "o" , Space , Str "umlaut:" , Space , Str "\246" ]
+        ]
+      , [ Plain [ Str "section:" , Space , Str "\167" ] ]
+      , [ Plain
+            [ Str "set"
+            , Space
+            , Str "membership:"
+            , Space
+            , Str "\8712"
+            ]
+        ]
+      , [ Plain [ Str "copyright:" , Space , Str "\169" ] ]
+      ]
+  , Para
+      [ Str "AT&T"
+      , Space
+      , Str "has"
+      , Space
+      , Str "an"
+      , Space
+      , Str "ampersand"
+      , Space
+      , Str "in"
+      , Space
+      , Str "their"
+      , Space
+      , Str "name."
+      ]
+  , Para
+      [ Str "AT&T"
+      , Space
+      , Str "is"
+      , Space
+      , Str "another"
+      , Space
+      , Str "way"
+      , Space
+      , Str "to"
+      , Space
+      , Str "write"
+      , Space
+      , Str "it."
+      ]
+  , Para
+      [ Str "This" , Space , Str "&" , Space , Str "that." ]
+  , Para [ Str "4" , Space , Str "<" , Space , Str "5." ]
+  , Para [ Str "6" , Space , Str ">" , Space , Str "5." ]
+  , Para [ Str "Backslash:" , Space , Str "\\" ]
+  , Para [ Str "Backtick:" , Space , Str "`" ]
+  , Para [ Str "Asterisk:" , Space , Str "*" ]
+  , Para [ Str "Underscore:" , Space , Str "_" ]
+  , Para
+      [ Str "Left" , Space , Str "brace:" , Space , Str "{" ]
+  , Para
+      [ Str "Right" , Space , Str "brace:" , Space , Str "}" ]
+  , Para
+      [ Str "Left" , Space , Str "bracket:" , Space , Str "[" ]
+  , Para
+      [ Str "Right" , Space , Str "bracket:" , Space , Str "]" ]
+  , Para
+      [ Str "Left" , Space , Str "paren:" , Space , Str "(" ]
+  , Para
+      [ Str "Right" , Space , Str "paren:" , Space , Str ")" ]
+  , Para [ Str "Greater-than:" , Space , Str ">" ]
+  , Para [ Str "Hash:" , Space , Str "#" ]
+  , Para [ Str "Period:" , Space , Str "." ]
+  , Para [ Str "Bang:" , Space , Str "!" ]
+  , Para [ Str "Plus:" , Space , Str "+" ]
+  , Para [ Str "Minus:" , Space , Str "-" ]
+  , HorizontalRule
+  , Header 1 ( "links" , [] , [] ) [ Str "Links" ]
+  , Header 2 ( "explicit" , [] , [] ) [ Str "Explicit" ]
+  , Para
+      [ Str "Just"
+      , Space
+      , Str "a"
+      , Space
+      , Link ( "" , [] , [] ) [ Str "URL" ] ( "/url/" , "" )
+      , Str "."
+      ]
+  , Para
+      [ Link
+          ( "" , [] , [] )
+          [ Str "URL" , Space , Str "and" , Space , Str "title" ]
+          ( "/url/" , "title" )
+      , Str "."
+      ]
+  , Para
+      [ Link
+          ( "" , [] , [] )
+          [ Str "URL" , Space , Str "and" , Space , Str "title" ]
+          ( "/url/" , "title preceded by two spaces" )
+      , Str "."
+      ]
+  , Para
+      [ Link
+          ( "" , [] , [] )
+          [ Str "URL" , Space , Str "and" , Space , Str "title" ]
+          ( "/url/" , "title preceded by a tab" )
+      , Str "."
+      ]
+  , Para
+      [ Link
+          ( "" , [] , [] )
+          [ Str "URL" , Space , Str "and" , Space , Str "title" ]
+          ( "/url/" , "title with \"quotes\" in it" )
+      ]
+  , Para
+      [ Link
+          ( "" , [] , [] )
+          [ Str "URL" , Space , Str "and" , Space , Str "title" ]
+          ( "/url/" , "title with single quotes" )
+      ]
+  , Para
+      [ Link
+          ( "" , [] , [] )
+          [ Str "with_underscore" ]
+          ( "/url/with_underscore" , "" )
+      ]
+  , Para
+      [ Link
+          ( "" , [] , [] )
+          [ Str "Email" , Space , Str "link" ]
+          ( "mailto:nobody@nowhere.net" , "" )
+      ]
+  , Para
+      [ Link ( "" , [] , [] ) [ Str "Empty" ] ( "" , "" )
+      , Str "."
+      ]
+  , Header 2 ( "reference" , [] , [] ) [ Str "Reference" ]
+  , Para
+      [ Str "Foo"
+      , Space
+      , Link ( "" , [] , [] ) [ Str "bar" ] ( "/url/" , "" )
+      , Str "."
+      ]
+  , Para
+      [ Str "With"
+      , Space
+      , Link
+          ( "" , [] , [] )
+          [ Str "embedded" , Space , Str "[brackets]" ]
+          ( "/url/" , "" )
+      , Str "."
+      ]
+  , Para
+      [ Link ( "" , [] , [] ) [ Str "b" ] ( "/url/" , "" )
+      , Space
+      , Str "by"
+      , Space
+      , Str "itself"
+      , Space
+      , Str "should"
+      , Space
+      , Str "be"
+      , Space
+      , Str "a"
+      , Space
+      , Str "link."
+      ]
+  , Para
+      [ Str "Indented"
+      , Space
+      , Link ( "" , [] , [] ) [ Str "once" ] ( "/url" , "" )
+      , Str "."
+      ]
+  , Para
+      [ Str "Indented"
+      , Space
+      , Link ( "" , [] , [] ) [ Str "twice" ] ( "/url" , "" )
+      , Str "."
+      ]
+  , Para
+      [ Str "Indented"
+      , Space
+      , Link ( "" , [] , [] ) [ Str "thrice" ] ( "/url" , "" )
+      , Str "."
+      ]
+  , Para
+      [ Str "This"
+      , Space
+      , Str "should"
+      , Space
+      , Str "[not][]"
+      , Space
+      , Str "be"
+      , Space
+      , Str "a"
+      , Space
+      , Str "link."
+      ]
+  , CodeBlock ( "" , [] , [] ) "[not]: /url"
+  , Para
+      [ Str "Foo"
+      , Space
+      , Link
+          ( "" , [] , [] )
+          [ Str "bar" ]
+          ( "/url/" , "Title with \"quotes\" inside" )
+      , Str "."
+      ]
+  , Para
+      [ Str "Foo"
+      , Space
+      , Link
+          ( "" , [] , [] )
+          [ Str "biz" ]
+          ( "/url/" , "Title with \"quote\" inside" )
+      , Str "."
+      ]
+  , Header
+      2
+      ( "with-ampersands" , [] , [] )
+      [ Str "With" , Space , Str "ampersands" ]
+  , Para
+      [ Str "Here\8217s"
+      , Space
+      , Str "a"
+      , Space
+      , Link
+          ( "" , [] , [] )
+          [ Str "link"
+          , Space
+          , Str "with"
+          , Space
+          , Str "an"
+          , Space
+          , Str "ampersand"
+          , Space
+          , Str "in"
+          , Space
+          , Str "the"
+          , Space
+          , Str "URL"
+          ]
+          ( "http://example.com/?foo=1&bar=2" , "" )
+      , Str "."
+      ]
+  , Para
+      [ Str "Here\8217s"
+      , Space
+      , Str "a"
+      , Space
+      , Str "link"
+      , Space
+      , Str "with"
+      , Space
+      , Str "an"
+      , Space
+      , Str "amersand"
+      , Space
+      , Str "in"
+      , Space
+      , Str "the"
+      , Space
+      , Str "link"
+      , Space
+      , Str "text:"
+      , Space
+      , Link
+          ( "" , [] , [] )
+          [ Str "AT&T" ]
+          ( "http://att.com/" , "AT&T" )
+      , Str "."
+      ]
+  , Para
+      [ Str "Here\8217s"
+      , Space
+      , Str "an"
+      , Space
+      , Link
+          ( "" , [] , [] )
+          [ Str "inline" , Space , Str "link" ]
+          ( "/script?foo=1&bar=2" , "" )
+      , Str "."
+      ]
+  , Para
+      [ Str "Here\8217s"
+      , Space
+      , Str "an"
+      , Space
+      , Link
+          ( "" , [] , [] )
+          [ Str "inline"
+          , Space
+          , Str "link"
+          , Space
+          , Str "in"
+          , Space
+          , Str "pointy"
+          , Space
+          , Str "braces"
+          ]
+          ( "/script?foo=1&bar=2" , "" )
+      , Str "."
+      ]
+  , Header 2 ( "autolinks" , [] , [] ) [ Str "Autolinks" ]
+  , Para
+      [ Str "With"
+      , Space
+      , Str "an"
+      , Space
+      , Str "ampersand:"
+      , Space
+      , Link
+          ( "" , [ "uri" ] , [] )
+          [ Str "http://example.com/?foo=1&bar=2" ]
+          ( "http://example.com/?foo=1&bar=2" , "" )
+      ]
+  , BulletList
+      [ [ Plain
+            [ Str "In" , Space , Str "a" , Space , Str "list?" ]
+        ]
+      , [ Plain
+            [ Link
+                ( "" , [ "uri" ] , [] )
+                [ Str "http://example.com/" ]
+                ( "http://example.com/" , "" )
+            ]
+        ]
+      , [ Plain [ Str "It" , Space , Str "should." ] ]
+      ]
+  , Para
+      [ Str "An"
+      , Space
+      , Str "e-mail"
+      , Space
+      , Str "address:"
+      , Space
+      , Link
+          ( "" , [ "email" ] , [] )
+          [ Str "nobody@nowhere.net" ]
+          ( "mailto:nobody@nowhere.net" , "" )
+      ]
+  , BlockQuote
+      [ Para
+          [ Str "Blockquoted:"
+          , Space
+          , Link
+              ( "" , [ "uri" ] , [] )
+              [ Str "http://example.com/" ]
+              ( "http://example.com/" , "" )
+          ]
+      ]
+  , Para
+      [ Str "Auto-links"
+      , Space
+      , Str "should"
+      , Space
+      , Str "not"
+      , Space
+      , Str "occur"
+      , Space
+      , Str "here:"
+      , Space
+      , Code ( "" , [] , [] ) "<http://example.com/>"
+      ]
+  , CodeBlock
+      ( "" , [] , [] ) "or here: <http://example.com/>"
+  , HorizontalRule
+  , Header 1 ( "images" , [] , [] ) [ Str "Images" ]
+  , Para
+      [ Str "From"
+      , Space
+      , Quoted
+          DoubleQuote
+          [ Str "Voyage"
+          , Space
+          , Str "dans"
+          , Space
+          , Str "la"
+          , Space
+          , Str "Lune"
+          ]
+      , Space
+      , Str "by"
+      , Space
+      , Str "Georges"
+      , Space
+      , Str "Melies"
+      , Space
+      , Str "(1902):"
+      ]
+  , Figure
+      ( "" , [] , [] )
+      (Caption Nothing [ Plain [ Str "lalune" ] ])
+      [ Plain
+          [ Image
+              ( "" , [] , [] )
+              [ Str "lalune" ]
+              ( "lalune.jpg" , "Voyage dans la Lune" )
+          ]
+      ]
+  , Para
+      [ Str "Here"
+      , Space
+      , Str "is"
+      , Space
+      , Str "a"
+      , Space
+      , Str "movie"
+      , Space
+      , Image
+          ( "" , [] , [] ) [ Str "movie" ] ( "movie.jpg" , "" )
+      , Space
+      , Str "icon."
+      ]
+  , HorizontalRule
+  , Header 1 ( "footnotes" , [] , [] ) [ Str "Footnotes" ]
+  , Para
+      [ Str "Here"
+      , Space
+      , Str "is"
+      , Space
+      , Str "a"
+      , Space
+      , Str "footnote"
+      , Space
+      , Str "reference,"
+      , Note
+          [ Para
+              [ Str "Here"
+              , Space
+              , Str "is"
+              , Space
+              , Str "the"
+              , Space
+              , Str "footnote."
+              , Space
+              , Str "It"
+              , Space
+              , Str "can"
+              , Space
+              , Str "go"
+              , Space
+              , Str "anywhere"
+              , Space
+              , Str "after"
+              , Space
+              , Str "the"
+              , Space
+              , Str "footnote"
+              , SoftBreak
+              , Str "reference."
+              , Space
+              , Str "It"
+              , Space
+              , Str "need"
+              , Space
+              , Str "not"
+              , Space
+              , Str "be"
+              , Space
+              , Str "placed"
+              , Space
+              , Str "at"
+              , Space
+              , Str "the"
+              , Space
+              , Str "end"
+              , Space
+              , Str "of"
+              , Space
+              , Str "the"
+              , Space
+              , Str "document."
+              ]
+          ]
+      , Space
+      , Str "and"
+      , Space
+      , Str "another."
+      , Note
+          [ Para
+              [ Str "Here\8217s"
+              , Space
+              , Str "the"
+              , Space
+              , Str "long"
+              , Space
+              , Str "note."
+              , Space
+              , Str "This"
+              , Space
+              , Str "one"
+              , Space
+              , Str "contains"
+              , Space
+              , Str "multiple"
+              , SoftBreak
+              , Str "blocks."
+              ]
+          , Para
+              [ Str "Subsequent"
+              , Space
+              , Str "blocks"
+              , Space
+              , Str "are"
+              , Space
+              , Str "indented"
+              , Space
+              , Str "to"
+              , Space
+              , Str "show"
+              , Space
+              , Str "that"
+              , Space
+              , Str "they"
+              , Space
+              , Str "belong"
+              , Space
+              , Str "to"
+              , Space
+              , Str "the"
+              , SoftBreak
+              , Str "footnote"
+              , Space
+              , Str "(as"
+              , Space
+              , Str "with"
+              , Space
+              , Str "list"
+              , Space
+              , Str "items)."
+              ]
+          , CodeBlock ( "" , [] , [] ) "  { <code> }"
+          , Para
+              [ Str "If"
+              , Space
+              , Str "you"
+              , Space
+              , Str "want,"
+              , Space
+              , Str "you"
+              , Space
+              , Str "can"
+              , Space
+              , Str "indent"
+              , Space
+              , Str "every"
+              , Space
+              , Str "line,"
+              , Space
+              , Str "but"
+              , Space
+              , Str "you"
+              , Space
+              , Str "can"
+              , Space
+              , Str "also"
+              , Space
+              , Str "be"
+              , SoftBreak
+              , Str "lazy"
+              , Space
+              , Str "and"
+              , Space
+              , Str "just"
+              , Space
+              , Str "indent"
+              , Space
+              , Str "the"
+              , Space
+              , Str "first"
+              , Space
+              , Str "line"
+              , Space
+              , Str "of"
+              , Space
+              , Str "each"
+              , Space
+              , Str "block."
+              ]
+          ]
+      , SoftBreak
+      , Str "This"
+      , Space
+      , Str "should"
+      , Space
+      , Emph [ Str "not" ]
+      , Space
+      , Str "be"
+      , Space
+      , Str "a"
+      , Space
+      , Str "footnote"
+      , Space
+      , Str "reference,"
+      , Space
+      , Str "because"
+      , Space
+      , Str "it"
+      , SoftBreak
+      , Str "contains"
+      , Space
+      , Str "a"
+      , Space
+      , Str "space.[^my"
+      , Space
+      , Str "note]"
+      , Space
+      , Str "Here"
+      , Space
+      , Str "is"
+      , Space
+      , Str "an"
+      , Space
+      , Str "inline"
+      , Space
+      , Str "note."
+      , Note
+          [ Para
+              [ Str "This"
+              , SoftBreak
+              , Str "is"
+              , Space
+              , Emph [ Str "easier" ]
+              , Space
+              , Str "to"
+              , Space
+              , Str "type."
+              , Space
+              , Str "Inline"
+              , Space
+              , Str "notes"
+              , Space
+              , Str "may"
+              , Space
+              , Str "contain"
+              , SoftBreak
+              , Link
+                  ( "" , [] , [] )
+                  [ Str "links" ]
+                  ( "http://google.com" , "" )
+              , Space
+              , Str "and"
+              , Space
+              , Code ( "" , [] , [] ) "]"
+              , Space
+              , Str "verbatim"
+              , Space
+              , Str "characters,"
+              , SoftBreak
+              , Str "as"
+              , Space
+              , Str "well"
+              , Space
+              , Str "as"
+              , Space
+              , Str "[bracketed"
+              , Space
+              , Str "text]."
+              ]
+          ]
+      ]
+  , BlockQuote
+      [ Para
+          [ Str "Notes"
+          , Space
+          , Str "can"
+          , Space
+          , Str "go"
+          , Space
+          , Str "in"
+          , Space
+          , Str "quotes."
+          , Note [ Para [ Str "In" , Space , Str "quote." ] ]
+          ]
+      ]
+  , OrderedList
+      ( 1 , Decimal , Period )
+      [ [ Plain
+            [ Str "And"
+            , Space
+            , Str "in"
+            , Space
+            , Str "list"
+            , Space
+            , Str "items."
+            , Note [ Para [ Str "In" , Space , Str "list." ] ]
+            ]
+        ]
+      ]
+  , Para
+      [ Str "This"
+      , Space
+      , Str "paragraph"
+      , Space
+      , Str "should"
+      , Space
+      , Str "not"
+      , Space
+      , Str "be"
+      , Space
+      , Str "part"
+      , Space
+      , Str "of"
+      , Space
+      , Str "the"
+      , Space
+      , Str "note,"
+      , Space
+      , Str "as"
+      , Space
+      , Str "it"
+      , Space
+      , Str "is"
+      , Space
+      , Str "not"
+      , Space
+      , Str "indented."
+      ]
+  ]
diff --git a/test/testsuite.txt b/test/testsuite.txt
--- a/test/testsuite.txt
+++ b/test/testsuite.txt
@@ -522,8 +522,7 @@
 - $p$-Tree
 - Here's some display math:
   $$\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:  $\alpha + \omega \times
-x^2$.  
+- Here's one that has a line break in it:  $\alpha + \omega \times x^2$.  
 
 These shouldn't be math:
 
diff --git a/test/textile-reader.native b/test/textile-reader.native
--- a/test/textile-reader.native
+++ b/test/textile-reader.native
@@ -1,180 +1,1290 @@
-Pandoc (Meta {unMeta = fromList []})
-[Para [Str "This",Space,Str "is",Space,Str "a",Space,Str "set",Space,Str "of",Space,Str "tests",Space,Str "for",Space,Str "pandoc",Space,Str "Textile",Space,Str "Reader.",Space,Str "Part",Space,Str "of",Space,Str "it",Space,Str "comes",LineBreak,Str "from",Space,Str "John",Space,Str "Gruber\8217s",Space,Str "markdown",Space,Str "test",Space,Str "suite."]
-,HorizontalRule
-,Header 1 ("headers",[],[]) [Str "Headers"]
-,Header 2 ("level-2-with-an-embeded-link",[],[]) [Str "Level",Space,Str "2",Space,Str "with",Space,Str "an",Space,Link ("",[],[]) [Str "embeded",Space,Str "link"] ("http://www.example.com","")]
-,Header 3 ("level-3-with-emphasis",[],[]) [Str "Level",Space,Str "3",Space,Str "with",Space,Strong [Str "emphasis"]]
-,Header 4 ("level-4",[],[]) [Str "Level",Space,Str "4"]
-,Header 5 ("level-5",[],[]) [Str "Level",Space,Str "5"]
-,Header 6 ("level-6",[],[]) [Str "Level",Space,Str "6"]
-,Header 1 ("paragraphs",[],[]) [Str "Paragraphs"]
-,Para [Str "Here\8217s",Space,Str "a",Space,Str "regular",Space,Str "paragraph."]
-,Para [Str "Line",Space,Str "breaks",Space,Str "are",Space,Str "preserved",Space,Str "in",Space,Str "textile,",Space,Str "so",Space,Str "you",Space,Str "can",Space,Str "not",Space,Str "wrap",Space,Str "your",Space,Str "very",LineBreak,Str "long",Space,Str "paragraph",Space,Str "with",Space,Str "your",Space,Str "favourite",Space,Str "text",Space,Str "editor",Space,Str "and",Space,Str "have",Space,Str "it",Space,Str "rendered",LineBreak,Str "with",Space,Str "no",Space,Str "break."]
-,Para [Str "Here\8217s",Space,Str "one",Space,Str "with",Space,Str "a",Space,Str "bullet."]
-,BulletList
- [[Plain [Str "criminey."]]]
-,Para [Str "There",Space,Str "should",Space,Str "be",Space,Str "a",Space,Str "paragraph",Space,Str "break",Space,Str "between",Space,Str "here"]
-,Para [Str "and",Space,Str "here."]
-,Para [Str "pandoc",Space,Str "converts",Space,Str "textile."]
-,Header 1 ("block-quotes",[],[]) [Str "Block",Space,Str "Quotes"]
-,BlockQuote
- [Para [Str "This",Space,Str "is",Space,Str "a",Space,Str "famous",Space,Str "quote",Space,Str "from",Space,Str "somebody.",Space,Str "He",Space,Str "had",Space,Str "a",Space,Str "lot",Space,Str "of",Space,Str "things",Space,Str "to",LineBreak,Str "say,",Space,Str "so",Space,Str "the",Space,Str "text",Space,Str "is",Space,Str "really",Space,Str "really",Space,Str "long",Space,Str "and",Space,Str "spans",Space,Str "on",Space,Str "multiple",Space,Str "lines."]]
-,Para [Str "And",Space,Str "a",Space,Str "following",Space,Str "paragraph."]
-,Header 1 ("code-blocks",[],[]) [Str "Code",Space,Str "Blocks"]
-,Para [Str "Code:"]
-,CodeBlock ("",[],[]) "    ---- (should be four hyphens)\n\n    sub status {\n        print \"working\";\n    }\n\n    this code block is indented by one tab"
-,Para [Str "And:"]
-,CodeBlock ("",[],[]) "        this code block is indented by two tabs\n\n    These should not be escaped:  \\$ \\\\ \\> \\[ \\{"
-,CodeBlock ("",[],[]) "Code block with .bc\n        continued\n    @</\\"
-,CodeBlock ("",[],[]) "extended code block\n\n        continued"
-,Para [Str "ended",Space,Str "by",Space,Str "paragraph"]
-,Para [Str "Inline",Space,Str "code:",Space,Code ("",[],[]) "<tt>",Str ",",Space,Code ("",[],[]) "@",Str "."]
-,Header 1 ("notextile",[],[]) [Str "Notextile"]
-,Para [Str "A",Space,Str "block",Space,Str "of",Space,Str "text",Space,Str "can",Space,Str "be",Space,Str "protected",Space,Str "with",Space,Str "notextile",Space,Str ":"]
-,Para [Str "\nNo *bold* and\n* no bullet\n"]
-,Para [Str "and",Space,Str "inlines",Space,Str "can",Space,Str "be",Space,Str "protected",Space,Str "with",Space,Str "double *equals (=)* markup."]
-,Header 1 ("lists",[],[]) [Str "Lists"]
-,Header 2 ("unordered",[],[]) [Str "Unordered"]
-,Para [Str "Asterisks",Space,Str "tight:"]
-,BulletList
- [[Plain [Str "asterisk",Space,Str "1"]]
- ,[Plain [Str "asterisk",Space,Str "2"]]
- ,[Plain [Str "asterisk",Space,Str "3"]]]
-,Para [Str "With",Space,Str "line",Space,Str "breaks:"]
-,BulletList
- [[Plain [Str "asterisk",Space,Str "1",LineBreak,Str "newline"]]
- ,[Plain [Str "asterisk",Space,Str "2"]]]
-,Header 2 ("ordered",[],[]) [Str "Ordered"]
-,Para [Str "Tight:"]
-,OrderedList (1,DefaultStyle,DefaultDelim)
- [[Plain [Str "First"]]
- ,[Plain [Str "Second"]]
- ,[Plain [Str "Third"]]]
-,Header 2 ("nested",[],[]) [Str "Nested"]
-,BulletList
- [[Plain [Str "ui",Space,Str "1"]
-  ,BulletList
-   [[Plain [Str "ui",Space,Str "1.1"]
-    ,OrderedList (1,DefaultStyle,DefaultDelim)
-     [[Plain [Str "oi",Space,Str "1.1.1"]]
-     ,[Plain [Str "oi",Space,Str "1.1.2"]]]]
-   ,[Plain [Str "ui",Space,Str "1.2"]]]]
- ,[Plain [Str "ui",Space,Str "2"]
-  ,OrderedList (1,DefaultStyle,DefaultDelim)
-   [[Plain [Str "oi",Space,Str "2.1"]
-    ,BulletList
-     [[Plain [Str "ui",Space,Str "2.1.1"]]
-     ,[Plain [Str "ui",Space,Str "2.1.2"]]]]]]]
-,Header 2 ("issue-1500",[],[]) [Str "Issue",Space,Str "#1500"]
-,BulletList
- [[Plain [Str "one"]]
- ,[Plain [Str "two",LineBreak,Str "->",Space,Str "and",Space,Str "more"]]]
-,Header 2 ("issue-1513",[],[]) [Str "Issue",Space,Str "#1513"]
-,Para [Str "List:"]
-,BulletList
- [[Plain [Str "one"]]
- ,[Plain [Str "two"]]]
-,Header 2 ("definition-list",[],[]) [Str "Definition",Space,Str "List"]
-,DefinitionList
- [([Str "coffee"],
-   [[Plain [Str "Hot",Space,Str "and",Space,Str "black"]]])
- ,([Str "tea"],
-   [[Plain [Str "Also",Space,Str "hot,",Space,Str "but",Space,Str "a",Space,Str "little",Space,Str "less",Space,Str "black"]]])
- ,([Str "milk"],
-   [[Para [Str "Nourishing",Space,Str "beverage",Space,Str "for",Space,Str "baby",Space,Str "cows."]
-    ,Para [Str "Cold",Space,Str "drink",Space,Str "that",Space,Str "goes",Space,Str "great",Space,Str "with",Space,Str "cookies."]]])
- ,([Str "beer"],
-   [[Plain [Str "fresh",Space,Str "and",Space,Str "bitter"]]])]
-,Header 1 ("inline-markup",[],[]) [Str "Inline",Space,Str "Markup"]
-,Para [Str "This",Space,Str "is",Space,Emph [Str "emphasized"],Str ",",Space,Str "and",Space,Str "so",Space,Emph [Str "is",Space,Str "this"],Str ".",LineBreak,Str "This",Space,Str "is",Space,Strong [Str "strong"],Str ",",Space,Str "and",Space,Str "so",Space,Strong [Str "is",Space,Str "this"],Str ".",LineBreak,Str "This",Space,Str "is",Space,Span ("",["underline"],[]) [Str "inserted"],Str ",",Space,Str "and",Space,Str "this",Space,Str "is",Space,Strikeout [Str "deleted"],Str ".",LineBreak,Str "Hyphenated-words-are-ok,",Space,Str "as",Space,Str "well",Space,Str "as",Space,Str "strange_underscore_notation.",LineBreak,Str "A",Space,Link ("",[],[]) [Strong [Str "strong",Space,Str "link"]] ("http://www.foobar.com",""),Str "."]
-,Para [Emph [Strong [Str "This",Space,Str "is",Space,Str "strong",Space,Str "and",Space,Str "em."]],LineBreak,Str "So",Space,Str "is",Space,Strong [Emph [Str "this"]],Space,Str "word",Space,Str "and",Space,Emph [Strong [Str "that",Space,Str "one"]],Str ".",LineBreak,Strikeout [Str "This",Space,Str "is",Space,Str "strikeout",Space,Str "and",Space,Strong [Str "strong"]]]
-,Para [Str "Superscripts:",Space,Str "a",Superscript [Str "bc"],Str "d",Space,Str "a",Space,Superscript [Strong [Str "hello"]],Space,Str "a",Superscript [Str "hello",Space,Str "there"],Str ".",LineBreak,Str "Subscripts:",Space,Subscript [Str "here"],Space,Str "H",Space,Subscript [Str "2"],Str "O,",Space,Str "H",Space,Subscript [Str "23"],Str "O,",Space,Str "H",Space,Subscript [Str "many",Space,Str "of",Space,Str "them"],Str "O."]
-,Para [Str "Dashes",Space,Str ":",Space,Str "How",Space,Str "cool",Space,Str "\8212",Space,Str "automatic",Space,Str "dashes."]
-,Para [Str "Elipses",Space,Str ":",Space,Str "He",Space,Str "thought",Space,Str "and",Space,Str "thought",Space,Str "\8230",Space,Str "and",Space,Str "then",Space,Str "thought",Space,Str "some",Space,Str "more."]
-,Para [Str "Quotes",Space,Str "and",Space,Str "apostrophes",Space,Str ":",Space,Quoted DoubleQuote [Str "I\8217d",Space,Str "like",Space,Str "to",Space,Str "thank",Space,Str "you"],Space,Str "for",Space,Str "example."]
-,Header 1 ("links",[],[]) [Str "Links"]
-,Header 2 ("explicit",[],[]) [Str "Explicit"]
-,Para [Str "Just",Space,Str "a",Space,Link ("",[],[]) [Str "url"] ("http://www.url.com","")]
-,Para [Link ("",[],[]) [Str "Email",Space,Str "link"] ("mailto:nobody@nowhere.net","")]
-,Para [Quoted DoubleQuote [Str "not",Space,Str "a",Space,Str "link"],Str ":",Space,Str "foo"]
-,Para [Str "Automatic",Space,Str "linking",Space,Str "to",Space,Link ("",[],[]) [Str "http://www.example.com"] ("http://www.example.com",""),Str "."]
-,Para [Link ("",[],[]) [Str "Example"] ("http://www.example.com/",""),Str ":",Space,Str "Example",Space,Str "of",Space,Str "a",Space,Str "link",Space,Str "followed",Space,Str "by",Space,Str "a",Space,Str "colon."]
-,Para [Str "A",Space,Str "link",Link ("",[],[]) [Str "with",Space,Str "brackets"] ("http://www.example.com",""),Str "and",Space,Str "no",Space,Str "spaces."]
-,Header 1 ("tables",[],[]) [Str "Tables"]
-,Para [Str "Textile",Space,Str "allows",Space,Str "tables",Space,Str "with",Space,Str "and",Space,Str "without",Space,Str "headers",Space,Str ":"]
-,Header 2 ("without-headers",[],[]) [Str "Without",Space,Str "headers"]
-,Table [] [AlignDefault,AlignDefault,AlignDefault] [0.0,0.0,0.0]
- [[]
- ,[]
- ,[]]
- [[[Plain [Str "name"]]
-  ,[Plain [Str "age"]]
-  ,[Plain [Str "sex"]]]
- ,[[Plain [Str "joan"]]
-  ,[Plain [Str "24"]]
-  ,[Plain [Str "f"]]]
- ,[[Plain [Str "archie"]]
-  ,[Plain [Str "29"]]
-  ,[Plain [Str "m"]]]
- ,[[Plain [Str "bella"]]
-  ,[Plain [Str "45"]]
-  ,[Plain [Str "f"]]]]
-,Para [Str "and",Space,Str "some",Space,Str "text",Space,Str "following",Space,Str "\8230"]
-,Header 2 ("with-headers",[],[]) [Str "With",Space,Str "headers"]
-,Table [] [AlignDefault,AlignDefault,AlignDefault] [0.0,0.0,0.0]
- [[Plain [Str "name"]]
- ,[Plain [Str "age"]]
- ,[Plain [Str "sex"]]]
- [[[Plain [Str "joan"]]
-  ,[Plain [Str "24"]]
-  ,[Plain [Str "f"]]]
- ,[[Plain [Str "archie"]]
-  ,[Plain [Str "29"]]
-  ,[Plain [Str "m"]]]
- ,[[Plain [Str "bella"]]
-  ,[Plain [Str "45"]]
-  ,[Plain [Str "f"]]]]
-,Header 1 ("images",[],[]) [Str "Images"]
-,Para [Str "Textile",Space,Str "inline",Space,Str "image",Space,Str "syntax,",Space,Str "like",LineBreak,Str "here",Space,Image ("",[],[]) [Str "this is the alt text"] ("this_is_an_image.png","this is the alt text"),LineBreak,Str "and",Space,Str "here",Space,Image ("",[],[]) [Str ""] ("this_is_an_image.png",""),Str "."]
-,Header 1 ("attributes",[],[]) [Str "Attributes"]
-,Header 2 ("ident",["bar","foo"],[("style","color:red;"),("lang","en")]) [Str "HTML",Space,Str "and",Space,Str "CSS",Space,Str "attributes",Space,Str "are",Space,Str "parsed",Space,Str "in",Space,Str "headers."]
-,Header 2 ("centered",[],[("style","text-align:center;")]) [Str "Centered"]
-,Header 2 ("right",[],[("style","text-align:right;")]) [Str "Right"]
-,Header 2 ("justified",[],[("lang","en"),("style","color:blue;text-align:justify;")]) [Str "Justified"]
-,Para [Str "as",Space,Str "well",Space,Str "as",Space,Strong [Span ("",["foo"],[]) [Str "inline",Space,Str "attributes"]],Space,Str "of",Space,Span ("",[],[("style","color:red;")]) [Str "all",Space,Str "kind"]]
-,Para [Str "and",Space,Str "paragraph",Space,Str "attributes,",Space,Str "and",Space,Str "table",Space,Str "attributes."]
-,Table [] [AlignDefault,AlignDefault,AlignDefault] [0.0,0.0,0.0]
- [[]
- ,[]
- ,[]]
- [[[Plain [Str "name"]]
-  ,[Plain [Str "age"]]
-  ,[Plain [Str "sex"]]]
- ,[[Plain [Str "joan"]]
-  ,[Plain [Str "24"]]
-  ,[Plain [Str "f"]]]]
-,Para [Emph [Str "(class#id)",Space,Str "emph"]]
-,Para [Emph [Str "(no",Space,Str "class#id)",Space,Str "emph"]]
-,Header 1 ("entities",[],[]) [Str "Entities"]
-,Para [Str "*",LineBreak,Str "&"]
-,Header 1 ("raw-html",[],[]) [Str "Raw",Space,Str "HTML"]
-,Para [Str "However,",Space,RawInline (Format "html") "<strong>",Space,Str "raw",Space,Str "HTML",Space,Str "inlines",Space,RawInline (Format "html") "</strong>",Space,Str "are",Space,Str "accepted,",Space,Str "as",Space,Str "well",Space,Str "as",Space,Str ":"]
-,RawBlock (Format "html") "<div class=\"foobar\">"
-,Para [Str "any",Space,Strong [Str "Raw",Space,Str "HTML",Space,Str "Block"],Space,Str "with",Space,Str "bold"]
-,RawBlock (Format "html") "</div>"
-,Para [Str "Html",Space,Str "blocks",Space,Str "can"]
-,RawBlock (Format "html") "<div>"
-,Para [Str "interrupt",Space,Str "paragraphs"]
-,RawBlock (Format "html") "</div>"
-,Para [Str "as",Space,Str "well."]
-,Para [Str "Can",Space,Str "you",Space,Str "prove",Space,Str "that",Space,Str "2",Space,Str "<",Space,Str "3",Space,Str "?"]
-,Header 1 ("acronyms-and-marks",[],[]) [Str "Acronyms",Space,Str "and",Space,Str "marks"]
-,Para [Str "PBS (Public Broadcasting System)"]
-,Para [Str "Hi\8482"]
-,Para [Str "Hi",Space,Str "\8482"]
-,Para [Str "\174",Space,Str "Hi\174"]
-,Para [Str "Hi\169\&2008",Space,Str "\169",Space,Str "2008"]
-,Header 1 ("footnotes",[],[]) [Str "Footnotes"]
-,Para [Str "A",Space,Str "note.",Note [Para [Str "The",Space,Str "note",LineBreak,Str "is",Space,Str "here!"]],Space,Str "Another",Space,Str "note",Note [Para [Str "Other",Space,Str "note."]],Str "."]
-,Header 1 ("comment-blocks",[],[]) [Str "Comment",Space,Str "blocks"]
-,Para [Str "not",Space,Str "a",Space,Str "comment."]]
+Pandoc
+  Meta { unMeta = fromList [] }
+  [ Para
+      [ Str "This"
+      , Space
+      , Str "is"
+      , Space
+      , Str "a"
+      , Space
+      , Str "set"
+      , Space
+      , Str "of"
+      , Space
+      , Str "tests"
+      , Space
+      , Str "for"
+      , Space
+      , Str "pandoc"
+      , Space
+      , Str "Textile"
+      , Space
+      , Str "Reader."
+      , Space
+      , Str "Part"
+      , Space
+      , Str "of"
+      , Space
+      , Str "it"
+      , Space
+      , Str "comes"
+      , LineBreak
+      , Str "from"
+      , Space
+      , Str "John"
+      , Space
+      , Str "Gruber\8217s"
+      , Space
+      , Str "markdown"
+      , Space
+      , Str "test"
+      , Space
+      , Str "suite."
+      ]
+  , HorizontalRule
+  , Header 1 ( "headers" , [] , [] ) [ Str "Headers" ]
+  , Header
+      2
+      ( "level-2-with-an-embedded-link" , [] , [] )
+      [ Str "Level"
+      , Space
+      , Str "2"
+      , Space
+      , Str "with"
+      , Space
+      , Str "an"
+      , Space
+      , Link
+          ( "" , [] , [] )
+          [ Str "embedded" , Space , Str "link" ]
+          ( "http://www.example.com" , "" )
+      ]
+  , Header
+      3
+      ( "level-3-with-emphasis" , [] , [] )
+      [ Str "Level"
+      , Space
+      , Str "3"
+      , Space
+      , Str "with"
+      , Space
+      , Strong [ Str "emphasis" ]
+      ]
+  , Header
+      4 ( "level-4" , [] , [] ) [ Str "Level" , Space , Str "4" ]
+  , Header
+      5 ( "level-5" , [] , [] ) [ Str "Level" , Space , Str "5" ]
+  , Header
+      6 ( "level-6" , [] , [] ) [ Str "Level" , Space , Str "6" ]
+  , Header 1 ( "paragraphs" , [] , [] ) [ Str "Paragraphs" ]
+  , Para
+      [ Str "Here\8217s"
+      , Space
+      , Str "a"
+      , Space
+      , Str "regular"
+      , Space
+      , Str "paragraph."
+      ]
+  , Para
+      [ Str "Line"
+      , Space
+      , Str "breaks"
+      , Space
+      , Str "are"
+      , Space
+      , Str "preserved"
+      , Space
+      , Str "in"
+      , Space
+      , Str "textile,"
+      , Space
+      , Str "so"
+      , Space
+      , Str "you"
+      , Space
+      , Str "can"
+      , Space
+      , Str "not"
+      , Space
+      , Str "wrap"
+      , Space
+      , Str "your"
+      , Space
+      , Str "very"
+      , LineBreak
+      , Str "long"
+      , Space
+      , Str "paragraph"
+      , Space
+      , Str "with"
+      , Space
+      , Str "your"
+      , Space
+      , Str "favourite"
+      , Space
+      , Str "text"
+      , Space
+      , Str "editor"
+      , Space
+      , Str "and"
+      , Space
+      , Str "have"
+      , Space
+      , Str "it"
+      , Space
+      , Str "rendered"
+      , LineBreak
+      , Str "with"
+      , Space
+      , Str "no"
+      , Space
+      , Str "break."
+      ]
+  , Para
+      [ Str "Here\8217s"
+      , Space
+      , Str "one"
+      , Space
+      , Str "with"
+      , Space
+      , Str "a"
+      , Space
+      , Str "bullet."
+      ]
+  , BulletList [ [ Plain [ Str "criminey." ] ] ]
+  , Para
+      [ Str "There"
+      , Space
+      , Str "should"
+      , Space
+      , Str "be"
+      , Space
+      , Str "a"
+      , Space
+      , Str "paragraph"
+      , Space
+      , Str "break"
+      , Space
+      , Str "between"
+      , Space
+      , Str "here"
+      ]
+  , Para [ Str "and" , Space , Str "here." ]
+  , Para
+      [ Str "pandoc"
+      , Space
+      , Str "converts"
+      , Space
+      , Str "textile."
+      ]
+  , Header
+      1
+      ( "block-quotes" , [] , [] )
+      [ Str "Block" , Space , Str "Quotes" ]
+  , BlockQuote
+      [ Para
+          [ Str "This"
+          , Space
+          , Str "is"
+          , Space
+          , Str "a"
+          , Space
+          , Str "famous"
+          , Space
+          , Str "quote"
+          , Space
+          , Str "from"
+          , Space
+          , Str "somebody."
+          , Space
+          , Str "He"
+          , Space
+          , Str "had"
+          , Space
+          , Str "a"
+          , Space
+          , Str "lot"
+          , Space
+          , Str "of"
+          , Space
+          , Str "things"
+          , Space
+          , Str "to"
+          , LineBreak
+          , Str "say,"
+          , Space
+          , Str "so"
+          , Space
+          , Str "the"
+          , Space
+          , Str "text"
+          , Space
+          , Str "is"
+          , Space
+          , Str "really"
+          , Space
+          , Str "really"
+          , Space
+          , Str "long"
+          , Space
+          , Str "and"
+          , Space
+          , Str "spans"
+          , Space
+          , Str "on"
+          , Space
+          , Str "multiple"
+          , Space
+          , Str "lines."
+          ]
+      ]
+  , Para
+      [ Str "And"
+      , Space
+      , Str "a"
+      , Space
+      , Str "following"
+      , Space
+      , Str "paragraph."
+      ]
+  , Header
+      1
+      ( "code-blocks" , [] , [] )
+      [ Str "Code" , Space , Str "Blocks" ]
+  , Para [ Str "Code:" ]
+  , CodeBlock
+      ( "" , [] , [] )
+      "    ---- (should be four hyphens)\n\n    sub status {\n        print \"working\";\n    }\n\n    this code block is indented by one tab"
+  , Para [ Str "And:" ]
+  , CodeBlock
+      ( "" , [] , [] )
+      "        this code block is indented by two tabs\n\n    These should not be escaped:  \\$ \\\\ \\> \\[ \\{"
+  , CodeBlock
+      ( "" , [] , [] )
+      "Code block with .bc\n        continued\n    @</\\"
+  , CodeBlock
+      ( "" , [] , [] ) "extended code block\n\n        continued"
+  , Para
+      [ Str "ended" , Space , Str "by" , Space , Str "paragraph" ]
+  , Para
+      [ Str "Inline"
+      , Space
+      , Str "code:"
+      , Space
+      , Code ( "" , [] , [] ) "<tt>"
+      , Str ","
+      , Space
+      , Code ( "" , [] , [] ) "@"
+      , Str "."
+      ]
+  , Header 1 ( "notextile" , [] , [] ) [ Str "Notextile" ]
+  , Para
+      [ Str "A"
+      , Space
+      , Str "block"
+      , Space
+      , Str "of"
+      , Space
+      , Str "text"
+      , Space
+      , Str "can"
+      , Space
+      , Str "be"
+      , Space
+      , Str "protected"
+      , Space
+      , Str "with"
+      , Space
+      , Str "notextile"
+      , Space
+      , Str ":"
+      ]
+  , Para [ Str "\nNo *bold* and\n* no bullet\n" ]
+  , Para
+      [ Str "and"
+      , Space
+      , Str "inlines"
+      , Space
+      , Str "can"
+      , Space
+      , Str "be"
+      , Space
+      , Str "protected"
+      , Space
+      , Str "with"
+      , Space
+      , Str "double *equals (=)* markup."
+      ]
+  , Header 1 ( "lists" , [] , [] ) [ Str "Lists" ]
+  , Header 2 ( "unordered" , [] , [] ) [ Str "Unordered" ]
+  , Para [ Str "Asterisks" , Space , Str "tight:" ]
+  , BulletList
+      [ [ Plain [ Str "asterisk" , Space , Str "1" ] ]
+      , [ Plain [ Str "asterisk" , Space , Str "2" ] ]
+      , [ Plain [ Str "asterisk" , Space , Str "3" ] ]
+      ]
+  , Para
+      [ Str "With" , Space , Str "line" , Space , Str "breaks:" ]
+  , BulletList
+      [ [ Plain
+            [ Str "asterisk"
+            , Space
+            , Str "1"
+            , LineBreak
+            , Str "newline"
+            ]
+        ]
+      , [ Plain [ Str "asterisk" , Space , Str "2" ] ]
+      ]
+  , Header 2 ( "ordered" , [] , [] ) [ Str "Ordered" ]
+  , Para [ Str "Tight:" ]
+  , OrderedList
+      ( 1 , DefaultStyle , DefaultDelim )
+      [ [ Plain [ Str "First" ] ]
+      , [ Plain [ Str "Second" ] ]
+      , [ Plain [ Str "Third" ] ]
+      ]
+  , Header 2 ( "nested" , [] , [] ) [ Str "Nested" ]
+  , BulletList
+      [ [ Plain [ Str "ui" , Space , Str "1" ]
+        , BulletList
+            [ [ Plain [ Str "ui" , Space , Str "1.1" ]
+              , OrderedList
+                  ( 1 , DefaultStyle , DefaultDelim )
+                  [ [ Plain [ Str "oi" , Space , Str "1.1.1" ] ]
+                  , [ Plain [ Str "oi" , Space , Str "1.1.2" ] ]
+                  ]
+              ]
+            , [ Plain [ Str "ui" , Space , Str "1.2" ] ]
+            ]
+        ]
+      , [ Plain [ Str "ui" , Space , Str "2" ]
+        , OrderedList
+            ( 1 , DefaultStyle , DefaultDelim )
+            [ [ Plain [ Str "oi" , Space , Str "2.1" ]
+              , BulletList
+                  [ [ Plain [ Str "ui" , Space , Str "2.1.1" ] ]
+                  , [ Plain [ Str "ui" , Space , Str "2.1.2" ] ]
+                  ]
+              ]
+            ]
+        ]
+      ]
+  , Header
+      2
+      ( "issue-1500" , [] , [] )
+      [ Str "Issue" , Space , Str "#1500" ]
+  , BulletList
+      [ [ Plain [ Str "one" ] ]
+      , [ Plain
+            [ Str "two"
+            , LineBreak
+            , Str "->"
+            , Space
+            , Str "and"
+            , Space
+            , Str "more"
+            ]
+        ]
+      ]
+  , Header
+      2
+      ( "issue-1513" , [] , [] )
+      [ Str "Issue" , Space , Str "#1513" ]
+  , Para [ Str "List:" ]
+  , BulletList
+      [ [ Plain [ Str "one" ] ] , [ Plain [ Str "two" ] ] ]
+  , Header
+      2
+      ( "definition-list" , [] , [] )
+      [ Str "Definition" , Space , Str "List" ]
+  , DefinitionList
+      [ ( [ Str "coffee" ]
+        , [ [ Plain
+                [ Str "Hot" , Space , Str "and" , Space , Str "black" ]
+            ]
+          ]
+        )
+      , ( [ Str "tea" ]
+        , [ [ Plain
+                [ Str "Also"
+                , Space
+                , Str "hot,"
+                , Space
+                , Str "but"
+                , Space
+                , Str "a"
+                , Space
+                , Str "little"
+                , Space
+                , Str "less"
+                , Space
+                , Str "black"
+                ]
+            ]
+          ]
+        )
+      , ( [ Str "milk" ]
+        , [ [ Para
+                [ Str "Nourishing"
+                , Space
+                , Str "beverage"
+                , Space
+                , Str "for"
+                , Space
+                , Str "baby"
+                , Space
+                , Str "cows."
+                ]
+            , Para
+                [ Str "Cold"
+                , Space
+                , Str "drink"
+                , Space
+                , Str "that"
+                , Space
+                , Str "goes"
+                , Space
+                , Str "great"
+                , Space
+                , Str "with"
+                , Space
+                , Str "cookies."
+                ]
+            ]
+          ]
+        )
+      , ( [ Str "beer" ]
+        , [ [ Plain
+                [ Str "fresh"
+                , Space
+                , Str "and"
+                , Space
+                , Str "bitter"
+                ]
+            ]
+          ]
+        )
+      ]
+  , Header
+      1
+      ( "inline-markup" , [] , [] )
+      [ Str "Inline" , Space , Str "Markup" ]
+  , Para
+      [ Str "This"
+      , Space
+      , Str "is"
+      , Space
+      , Emph [ Str "emphasized" ]
+      , Str ","
+      , Space
+      , Str "and"
+      , Space
+      , Str "so"
+      , Space
+      , Emph [ Str "is" , Space , Str "this" ]
+      , Str "."
+      , LineBreak
+      , Str "This"
+      , Space
+      , Str "is"
+      , Space
+      , Strong [ Str "strong" ]
+      , Str ","
+      , Space
+      , Str "and"
+      , Space
+      , Str "so"
+      , Space
+      , Strong [ Str "is" , Space , Str "this" ]
+      , Str "."
+      , LineBreak
+      , Str "This"
+      , Space
+      , Str "is"
+      , Space
+      , Underline [ Str "inserted" ]
+      , Str ","
+      , Space
+      , Str "and"
+      , Space
+      , Str "this"
+      , Space
+      , Str "is"
+      , Space
+      , Strikeout [ Str "deleted" ]
+      , Str "."
+      , LineBreak
+      , Str "Hyphenated-words-are-ok,"
+      , Space
+      , Str "as"
+      , Space
+      , Str "well"
+      , Space
+      , Str "as"
+      , Space
+      , Str "strange_underscore_notation."
+      , LineBreak
+      , Str "A"
+      , Space
+      , Link
+          ( "" , [] , [] )
+          [ Strong [ Str "strong" , Space , Str "link" ] ]
+          ( "http://www.foobar.com" , "" )
+      , Str "."
+      ]
+  , Para
+      [ Emph
+          [ Strong
+              [ Str "This"
+              , Space
+              , Str "is"
+              , Space
+              , Str "strong"
+              , Space
+              , Str "and"
+              , Space
+              , Str "em."
+              ]
+          ]
+      , LineBreak
+      , Str "So"
+      , Space
+      , Str "is"
+      , Space
+      , Strong [ Emph [ Str "this" ] ]
+      , Space
+      , Str "word"
+      , Space
+      , Str "and"
+      , Space
+      , Emph [ Strong [ Str "that" , Space , Str "one" ] ]
+      , Str "."
+      , LineBreak
+      , Strikeout
+          [ Str "This"
+          , Space
+          , Str "is"
+          , Space
+          , Str "strikeout"
+          , Space
+          , Str "and"
+          , Space
+          , Strong [ Str "strong" ]
+          ]
+      ]
+  , Para
+      [ Str "Superscripts:"
+      , Space
+      , Str "a"
+      , Superscript [ Str "bc" ]
+      , Str "d"
+      , Space
+      , Str "a"
+      , Space
+      , Superscript [ Strong [ Str "hello" ] ]
+      , Space
+      , Str "a"
+      , Superscript [ Str "hello" , Space , Str "there" ]
+      , Str "."
+      , LineBreak
+      , Str "Subscripts:"
+      , Space
+      , Subscript [ Str "here" ]
+      , Space
+      , Str "H"
+      , Space
+      , Subscript [ Str "2" ]
+      , Str "O,"
+      , Space
+      , Str "H"
+      , Space
+      , Subscript [ Str "23" ]
+      , Str "O,"
+      , Space
+      , Str "H"
+      , Space
+      , Subscript
+          [ Str "many" , Space , Str "of" , Space , Str "them" ]
+      , Str "O."
+      ]
+  , Para
+      [ Str "Dashes"
+      , Space
+      , Str ":"
+      , Space
+      , Str "How"
+      , Space
+      , Str "cool"
+      , Space
+      , Str "\8212"
+      , Space
+      , Str "automatic"
+      , Space
+      , Str "dashes."
+      ]
+  , Para
+      [ Str "Ellipses"
+      , Space
+      , Str ":"
+      , Space
+      , Str "He"
+      , Space
+      , Str "thought"
+      , Space
+      , Str "and"
+      , Space
+      , Str "thought"
+      , Space
+      , Str "\8230"
+      , Space
+      , Str "and"
+      , Space
+      , Str "then"
+      , Space
+      , Str "thought"
+      , Space
+      , Str "some"
+      , Space
+      , Str "more."
+      ]
+  , Para
+      [ Str "Quotes"
+      , Space
+      , Str "and"
+      , Space
+      , Str "apostrophes"
+      , Space
+      , Str ":"
+      , Space
+      , Quoted
+          DoubleQuote
+          [ Str "I\8217d"
+          , Space
+          , Str "like"
+          , Space
+          , Str "to"
+          , Space
+          , Str "thank"
+          , Space
+          , Str "you"
+          ]
+      , Space
+      , Str "for"
+      , Space
+      , Str "example."
+      ]
+  , Header 1 ( "links" , [] , [] ) [ Str "Links" ]
+  , Header 2 ( "explicit" , [] , [] ) [ Str "Explicit" ]
+  , Para
+      [ Str "Just"
+      , Space
+      , Str "a"
+      , Space
+      , Link
+          ( "" , [] , [] ) [ Str "url" ] ( "http://www.url.com" , "" )
+      ]
+  , Para
+      [ Link
+          ( "" , [] , [] )
+          [ Str "Email" , Space , Str "link" ]
+          ( "mailto:nobody@nowhere.net" , "" )
+      ]
+  , Para
+      [ Quoted
+          DoubleQuote
+          [ Str "not" , Space , Str "a" , Space , Str "link" ]
+      , Str ":"
+      , Space
+      , Str "foo"
+      ]
+  , Para
+      [ Str "Automatic"
+      , Space
+      , Str "linking"
+      , Space
+      , Str "to"
+      , Space
+      , Link
+          ( "" , [] , [] )
+          [ Str "http://www.example.com" ]
+          ( "http://www.example.com" , "" )
+      , Str "."
+      ]
+  , Para
+      [ Link
+          ( "" , [] , [] )
+          [ Str "Example" ]
+          ( "http://www.example.com/" , "" )
+      , Str ":"
+      , Space
+      , Str "Example"
+      , Space
+      , Str "of"
+      , Space
+      , Str "a"
+      , Space
+      , Str "link"
+      , Space
+      , Str "followed"
+      , Space
+      , Str "by"
+      , Space
+      , Str "a"
+      , Space
+      , Str "colon."
+      ]
+  , Para
+      [ Str "A"
+      , Space
+      , Str "link"
+      , Link
+          ( "" , [] , [] )
+          [ Str "with" , Space , Str "brackets" ]
+          ( "http://www.example.com" , "" )
+      , Str "and"
+      , Space
+      , Str "no"
+      , Space
+      , Str "spaces."
+      ]
+  , Para
+      [ Str "A"
+      , Space
+      , Link
+          ( "" , [] , [] ) [ Str "link" ] ( "ftp://example.com" , "" )
+      , Space
+      , Str "to"
+      , Space
+      , Str "a"
+      , Space
+      , Str "named"
+      , Space
+      , Str "target"
+      ]
+  , Para
+      [ Str "A"
+      , Space
+      , Link ( "" , [] , [] ) [ Str "link" ] ( "missing" , "" )
+      , Space
+      , Str "to"
+      , Space
+      , Str "a"
+      , Space
+      , Str "missing"
+      , Space
+      , Str "target"
+      ]
+  , Header 1 ( "tables" , [] , [] ) [ Str "Tables" ]
+  , Para
+      [ Str "Textile"
+      , Space
+      , Str "allows"
+      , Space
+      , Str "tables"
+      , Space
+      , Str "with"
+      , Space
+      , Str "and"
+      , Space
+      , Str "without"
+      , Space
+      , Str "headers"
+      , Space
+      , Str ":"
+      ]
+  , Header
+      2
+      ( "without-headers" , [] , [] )
+      [ Str "Without" , Space , Str "headers" ]
+  , Table
+      ( "" , [] , [] )
+      (Caption Nothing [])
+      [ ( AlignDefault , ColWidthDefault )
+      , ( AlignDefault , ColWidthDefault )
+      , ( AlignDefault , ColWidthDefault )
+      ]
+      (TableHead ( "" , [] , [] ) [])
+      [ TableBody
+          ( "" , [] , [] )
+          (RowHeadColumns 0)
+          []
+          [ Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "name" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "age" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "sex" ] ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "joan" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "24" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "f" ] ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "archie" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "29" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "m" ] ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "bella" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "45" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "f" ] ]
+              ]
+          ]
+      ]
+      (TableFoot ( "" , [] , [] ) [])
+  , Para
+      [ Str "and"
+      , Space
+      , Str "some"
+      , Space
+      , Str "text"
+      , Space
+      , Str "following"
+      , Space
+      , Str "\8230"
+      ]
+  , Header
+      2
+      ( "with-headers" , [] , [] )
+      [ Str "With" , Space , Str "headers" ]
+  , Table
+      ( "" , [] , [] )
+      (Caption Nothing [])
+      [ ( AlignDefault , ColWidthDefault )
+      , ( AlignDefault , ColWidthDefault )
+      , ( AlignDefault , ColWidthDefault )
+      ]
+      (TableHead
+         ( "" , [] , [] )
+         [ Row
+             ( "" , [] , [] )
+             [ Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "name" ] ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "age" ] ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "sex" ] ]
+             ]
+         ])
+      [ TableBody
+          ( "" , [] , [] )
+          (RowHeadColumns 0)
+          []
+          [ Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "joan" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "24" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "f" ] ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "archie" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "29" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "m" ] ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "bella" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "45" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "f" ] ]
+              ]
+          ]
+      ]
+      (TableFoot ( "" , [] , [] ) [])
+  , Header 1 ( "images" , [] , [] ) [ Str "Images" ]
+  , Para
+      [ Str "Textile"
+      , Space
+      , Str "inline"
+      , Space
+      , Str "image"
+      , Space
+      , Str "syntax,"
+      , Space
+      , Str "like"
+      , LineBreak
+      , Str "here"
+      , Space
+      , Image
+          ( "" , [] , [] )
+          [ Str "this is the alt text" ]
+          ( "this_is_an_image.png" , "this is the alt text" )
+      , LineBreak
+      , Str "and"
+      , Space
+      , Str "here"
+      , Space
+      , Image
+          ( "" , [] , [] ) [ Str "" ] ( "this_is_an_image.png" , "" )
+      , Str "."
+      ]
+  , Header 1 ( "attributes" , [] , [] ) [ Str "Attributes" ]
+  , Header
+      2
+      ( "ident"
+      , [ "bar" , "foo" ]
+      , [ ( "style" , "color:red;" ) , ( "lang" , "en" ) ]
+      )
+      [ Str "HTML"
+      , Space
+      , Str "and"
+      , Space
+      , Str "CSS"
+      , Space
+      , Str "attributes"
+      , Space
+      , Str "are"
+      , Space
+      , Str "parsed"
+      , Space
+      , Str "in"
+      , Space
+      , Str "headers."
+      ]
+  , Header
+      2
+      ( "centered" , [] , [ ( "style" , "text-align:center;" ) ] )
+      [ Str "Centered" ]
+  , Header
+      2
+      ( "right" , [] , [ ( "style" , "text-align:right;" ) ] )
+      [ Str "Right" ]
+  , Header
+      2
+      ( "justified"
+      , []
+      , [ ( "lang" , "en" )
+        , ( "style" , "color:blue;text-align:justify;" )
+        ]
+      )
+      [ Str "Justified" ]
+  , Para
+      [ Str "as"
+      , Space
+      , Str "well"
+      , Space
+      , Str "as"
+      , Space
+      , Strong
+          [ Span
+              ( "" , [ "foo" ] , [] )
+              [ Str "inline" , Space , Str "attributes" ]
+          ]
+      , Space
+      , Str "of"
+      , Space
+      , Span
+          ( "" , [] , [ ( "style" , "color:red;" ) ] )
+          [ Str "all" , Space , Str "kind" ]
+      ]
+  , Div
+      ( "" , [] , [ ( "style" , "color:green;" ) ] )
+      [ Para
+          [ Str "and"
+          , Space
+          , Str "paragraph"
+          , Space
+          , Str "attributes,"
+          , Space
+          , Str "and"
+          , Space
+          , Str "table"
+          , Space
+          , Str "attributes."
+          ]
+      ]
+  , Table
+      ( "" , [] , [] )
+      (Caption Nothing [])
+      [ ( AlignDefault , ColWidthDefault )
+      , ( AlignDefault , ColWidthDefault )
+      , ( AlignDefault , ColWidthDefault )
+      ]
+      (TableHead ( "" , [] , [] ) [])
+      [ TableBody
+          ( "" , [] , [] )
+          (RowHeadColumns 0)
+          []
+          [ Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "name" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "age" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "sex" ] ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "joan" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "24" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "f" ] ]
+              ]
+          ]
+      ]
+      (TableFoot ( "" , [] , [] ) [])
+  , Para [ Emph [ Str "(class#id)" , Space , Str "emph" ] ]
+  , Para
+      [ Emph
+          [ Str "(no" , Space , Str "class#id)" , Space , Str "emph" ]
+      ]
+  , Header 1 ( "entities" , [] , [] ) [ Str "Entities" ]
+  , Para [ Str "*" , LineBreak , Str "&" ]
+  , Header
+      1
+      ( "raw-html" , [] , [] )
+      [ Str "Raw" , Space , Str "HTML" ]
+  , Para
+      [ Str "However,"
+      , Space
+      , RawInline (Format "html") "<strong>"
+      , Space
+      , Str "raw"
+      , Space
+      , Str "HTML"
+      , Space
+      , Str "inlines"
+      , Space
+      , RawInline (Format "html") "</strong>"
+      , Space
+      , Str "are"
+      , Space
+      , Str "accepted,"
+      , Space
+      , Str "as"
+      , Space
+      , Str "well"
+      , Space
+      , Str "as"
+      , Space
+      , Str ":"
+      ]
+  , RawBlock (Format "html") "<div class=\"foobar\">"
+  , Para
+      [ Str "any"
+      , Space
+      , Strong
+          [ Str "Raw" , Space , Str "HTML" , Space , Str "Block" ]
+      , Space
+      , Str "with"
+      , Space
+      , Str "bold"
+      ]
+  , RawBlock (Format "html") "</div>"
+  , Para
+      [ Str "Html" , Space , Str "blocks" , Space , Str "can" ]
+  , RawBlock (Format "html") "<div>"
+  , Para [ Str "interrupt" , Space , Str "paragraphs" ]
+  , RawBlock (Format "html") "</div>"
+  , Para [ Str "as" , Space , Str "well." ]
+  , Para
+      [ Str "Can"
+      , Space
+      , Str "you"
+      , Space
+      , Str "prove"
+      , Space
+      , Str "that"
+      , Space
+      , Str "2"
+      , Space
+      , Str "<"
+      , Space
+      , Str "3"
+      , Space
+      , Str "?"
+      ]
+  , Header
+      1
+      ( "acronyms-and-marks" , [] , [] )
+      [ Str "Acronyms" , Space , Str "and" , Space , Str "marks" ]
+  , Para [ Str "PBS (Public Broadcasting System)" ]
+  , Para [ Str "Hi\8482" ]
+  , Para [ Str "Hi" , Space , Str "\8482" ]
+  , Para [ Str "\174" , Space , Str "Hi\174" ]
+  , Para
+      [ Str "Hi\169\&2008"
+      , Space
+      , Str "\169"
+      , Space
+      , Str "2008"
+      ]
+  , Header 1 ( "footnotes" , [] , [] ) [ Str "Footnotes" ]
+  , Para
+      [ Str "A"
+      , Space
+      , Str "note."
+      , Note
+          [ Para
+              [ Str "The"
+              , Space
+              , Str "note"
+              , LineBreak
+              , Str "is"
+              , Space
+              , Str "here!"
+              ]
+          ]
+      , Space
+      , Str "Another"
+      , Space
+      , Str "note"
+      , Note [ Para [ Str "Other" , Space , Str "note." ] ]
+      , Str "."
+      ]
+  , Header
+      1
+      ( "comment-blocks" , [] , [] )
+      [ Str "Comment" , Space , Str "blocks" ]
+  , Para
+      [ Str "not" , Space , Str "a" , Space , Str "comment." ]
+  ]
diff --git a/test/textile-reader.textile b/test/textile-reader.textile
--- a/test/textile-reader.textile
+++ b/test/textile-reader.textile
@@ -5,7 +5,7 @@
 
 h1. Headers
 
-h2. Level 2 with an "embeded link":http://www.example.com
+h2. Level 2 with an "embedded link":http://www.example.com
 
 h3. Level 3 with *emphasis*
 
@@ -162,7 +162,7 @@
 
 Dashes : How cool -- automatic dashes.
 
-Elipses : He thought and thought ... and then thought some more.
+Ellipses : He thought and thought ... and then thought some more.
 
 Quotes and apostrophes : "I'd like to thank you" for example.
 
@@ -183,6 +183,10 @@
 
 A link["with brackets":http://www.example.com]and no spaces.
 
+A "link":link-target to a named target
+
+A "link":missing to a missing target
+
 h1. Tables
 
 Textile allows tables with and without headers :
@@ -269,7 +273,7 @@
 fn1. The note
 is here!
 
-fn2. Other note.
+fn2^. Other note.
 
 h1. Comment blocks
 
@@ -277,3 +281,5 @@
 is here.
 
 not a comment.
+
+[link-target]ftp://example.com
diff --git a/test/tikiwiki-reader.native b/test/tikiwiki-reader.native
--- a/test/tikiwiki-reader.native
+++ b/test/tikiwiki-reader.native
@@ -1,130 +1,782 @@
-Pandoc (Meta {unMeta = fromList []})
-[Header 1 ("header",[],[]) [Str "header"]
-,Header 2 ("header-level-two",[],[]) [Str "header",Space,Str "level",Space,Str "two"]
-,Header 3 ("header-level-3",[],[]) [Str "header",Space,Str "level",Space,Str "3"]
-,Header 4 ("header-_level_-four",[],[]) [Str "header",Space,Str "_level_",Space,Str "four"]
-,Header 5 ("header-level-5",[],[]) [Str "header",Space,Str "level",Space,Str "5"]
-,Header 6 ("header-level-6",[],[]) [Str "header",Space,Str "level",Space,Str "6"]
-,Para [Str "!!!!!!!",Space,Str "not",Space,Str "a",Space,Str "header"]
-,Para [Str "--++",Space,Str "not",Space,Str "a",Space,Str "header"]
-,Header 1 ("emph-and-strong",[],[]) [Str "emph",Space,Str "and",Space,Str "strong"]
-,Para [Emph [Str "emph"],Space,Strong [Str "strong"]]
-,Para [Emph [Strong [Str "strong",Space,Str "and",Space,Str "emph",Space,Str "1"]]]
-,Para [Strong [Emph [Str "strong",Space,Str "and",Space,Str "emph",Space,Str "2"]]]
-,Para [Strong [Emph [Str "emph",Space,Str "inside"],Space,Str "strong"]]
-,Para [Strong [Str "strong",Space,Str "with",Space,Emph [Str "emph"]]]
-,Para [Emph [Strong [Str "strong",Space,Str "inside"],Space,Str "emph"]]
-,Header 1 ("horizontal-rule",[],[]) [Str "horizontal",Space,Str "rule"]
-,Para [Str "top"]
-,HorizontalRule
-,Para [Str "bottom"]
-,HorizontalRule
-,Header 1 ("nop",[],[]) [Str "nop"]
-,Para [Str "__not emph__"]
-,Header 1 ("entities",[],[]) [Str "entities"]
-,Para [Str "hi",Space,Str "&",Space,Str "low"]
-,Para [Str "hi",Space,Str "&",Space,Str "low"]
-,Para [Str "G\246del"]
-,Para [Str "\777\2730"]
-,Header 1 ("linebreaks",[],[]) [Str "linebreaks"]
-,Para [Str "hi",LineBreak,Str "there"]
-,Para [Str "hi",LineBreak,Str "there"]
-,Header 1 ("inline-code",[],[]) [Str "inline",Space,Str "code"]
-,Para [Code ("",[],[]) "*\8594*",Space,Code ("",[],[]) "typed",Space,Code ("",[],[]) ">>="]
-,Header 1 ("code-blocks",[],[]) [Str "code",Space,Str "blocks"]
-,CodeBlock ("",[],[]) "\ncase xs of\n     (_:_) -> reverse xs\n     []    -> ['*']\n"
-,CodeBlock ("",["haskell"],[("colors","haskell"),("ln","0")]) "\ncase xs of\n     (_:_) -> reverse xs\n     []    -> ['*']\n"
-,Header 1 ("external-links",[],[]) [Str "external",Space,Str "links"]
-,Para [Link ("",[],[]) [Emph [Str "Google"],Space,Str "search",Space,Str "engine"] ("http://google.com","")]
-,Para [Link ("",[],[]) [Str "http://pandoc.org"] ("http://pandoc.org","")]
-,Para [Link ("",[],[]) [Str "http://google.com"] ("http://google.com",""),Space,Link ("",[],[]) [Str "http://yahoo.com"] ("http://yahoo.com","")]
-,Para [Link ("",[],[]) [Str "email",Space,Str "me"] ("mailto:info@example.org","")]
-,Para [Str "http://google.com"]
-,Para [Str "info@example.org"]
-,Header 1 ("lists",[],[]) [Str "lists"]
-,BulletList
- [[Plain [Str "Start",Space,Str "each",Space,Str "line",Space]]
- ,[Plain [Str "with",Space,Str "an",Space,Str "asterisk",Space,Str "(*).",Space]
-  ,BulletList
-   [[Plain [Str "More",Space,Str "asterisks",Space,Str "gives",Space,Str "deeper",Space]
-    ,BulletList
-     [[Plain [Str "and",Space,Str "deeper",Space,Str "levels.",Space]]]]]]
- ,[Plain [Str "Line",Space,Str "breaks",LineBreak,Str "don't",Space,Str "break",Space,Str "levels.",Space]]
- ,[Plain [Str "Continuations",Space,Str "are",Space,Str "also",Space,Str "possible",Space]
-  ,BulletList
-   [[Plain [Str "and",Space,Str "do",Space,Str "not",Space,Str "break",Space,Str "the",Space,Str "list",Space,Str "flow",Space]]]]
- ,[Plain [Str "Level",Space,Str "one",Space]]]
-,Para [Str "Any",Space,Str "other",Space,Str "start",Space,Str "ends",Space,Str "the",Space,Str "list."]
-,OrderedList (1,DefaultStyle,DefaultDelim)
- [[Plain [Str "Start",Space,Str "each",Space,Str "line",Space]]
- ,[Plain [Str "with",Space,Str "a",Space,Str "number",Space,Str "(1.).",Space]
-  ,OrderedList (1,DefaultStyle,DefaultDelim)
-   [[Plain [Str "More",Space,Str "number",Space,Str "signs",Space,Str "gives",Space,Str "deeper",Space]
-    ,OrderedList (1,DefaultStyle,DefaultDelim)
-     [[Plain [Str "and",Space,Str "deeper",Space]]
-     ,[Plain [Str "levels.",Space]]]]]]
- ,[Plain [Str "Line",Space,Str "breaks",LineBreak,Str "don't",Space,Str "break",Space,Str "levels.",Space]]
- ,[Plain [Str "Blank",Space,Str "lines",Space]]]
-,OrderedList (1,DefaultStyle,DefaultDelim)
- [[Plain [Str "end",Space,Str "the",Space,Str "list",Space,Str "and",Space,Str "start",Space,Str "another.",Space]]]
-,Para [Str "Any",Space,Str "other",Space,Str "start",Space,Str "also",Space,Str "ends",Space,Str "the",Space,Str "list."]
-,DefinitionList
- [([Str "item",Space,Str "1"],
-   [[Plain [Str "definition",Space,Str "1",Space]]])
- ,([Str "item",Space,Str "2"],
-   [[Plain [Str "definition",Space,Str "2-1",Space,Str "definition",Space,Str "2-2",Space]]])
- ,([Str "item",Space,Emph [Str "3"]],
-   [[Plain [Str "definition",Space,Emph [Str "3"],Space]]])]
-,OrderedList (1,DefaultStyle,DefaultDelim)
- [[Plain [Str "one",Space]]
- ,[Plain [Str "two",Space]
-  ,BulletList
-   [[Plain [Str "two",Space,Str "point",Space,Str "one",Space]]
-   ,[Plain [Str "two",Space,Str "point",Space,Str "two",Space]]]]
- ,[Plain [Str "three",Space]]
- ,[Plain [Str "four",Space]]
- ,[Plain [Str "five",Space]
-  ,OrderedList (1,DefaultStyle,DefaultDelim)
-   [[Plain [Str "five",Space,Str "sub",Space,Str "1",Space]
-    ,OrderedList (1,DefaultStyle,DefaultDelim)
-     [[Plain [Str "five",Space,Str "sub",Space,Str "1",Space,Str "sub",Space,Str "1",Space]]]]
-   ,[Plain [Str "five",Space,Str "sub",Space,Str "2",Space]]]]]
-,Header 1 ("tables",[],[]) [Str "tables"]
-,Table [] [AlignDefault,AlignDefault] [0.0,0.0]
- [[Plain [Str ""]]
- ,[Plain [Str ""]]]
- [[[Plain [Str "Orange"]]
-  ,[Plain [Str "Apple"]]]
- ,[[Plain [Str "Bread"]]
-  ,[Plain [Str "Pie"]]]
- ,[[Plain [Str "Butter"]]
-  ,[Plain [Str "Ice",Space,Str "cream"]]]]
-,Table [] [AlignDefault,AlignDefault] [0.0,0.0]
- [[Plain [Str ""]]
- ,[Plain [Str ""]]]
- [[[Plain [Str "Orange"]]
-  ,[Plain [Str "Apple"]]]
- ,[[Plain [Str "Bread"]]
-  ,[Plain [Str "Pie"]]]
- ,[[Plain [Strong [Str "Butter"]]]
-  ,[Plain [Str "Ice",Space,Str "cream"]]]]
-,Table [] [AlignDefault,AlignDefault] [0.0,0.0]
- [[Plain [Str ""]]
- ,[Plain [Str ""]]]
- [[[Plain [Str "Orange"]]
-  ,[Plain [Str "Apple"]]]
- ,[[Plain [Str "Bread",LineBreak,LineBreak,Str "and",Space,Str "cheese"]]
-  ,[Plain [Str "Pie",LineBreak,LineBreak,Strong [Str "apple"],Space,Str "and",Space,Emph [Str "carrot"],Space]]]]
-,Table [] [AlignDefault,AlignDefault,AlignDefault] [0.0,0.0,0.0]
- [[Plain [Str ""]]
- ,[Plain [Str ""]]
- ,[Plain [Str ""]]]
- [[[Plain [Space,Str "Orange",Space]]
-  ,[Plain [Space,Str "Apple",Space]]
-  ,[Plain [Space,Str "more"]]]
- ,[[Plain [Space,Str "Bread",Space]]
-  ,[Plain [Space,Str "Pie",Space]]
-  ,[Plain [Space,Str "more"]]]
- ,[[Plain [Space,Str "Butter",Space]]
-  ,[Plain [Space,Str "Ice",Space,Str "cream",Space]]
-  ,[Plain [Space,Str "and",Space,Str "more",Space]]]]]
+Pandoc
+  Meta { unMeta = fromList [] }
+  [ Header 1 ( "header" , [] , [] ) [ Str "header" ]
+  , Header
+      2
+      ( "header-level-two" , [] , [] )
+      [ Str "header" , Space , Str "level" , Space , Str "two" ]
+  , Header
+      3
+      ( "header-level-3" , [] , [] )
+      [ Str "header" , Space , Str "level" , Space , Str "3" ]
+  , Header
+      4
+      ( "header-_level_-four" , [] , [] )
+      [ Str "header"
+      , Space
+      , Str "_level_"
+      , Space
+      , Str "four"
+      ]
+  , Header
+      5
+      ( "header-level-5" , [] , [] )
+      [ Str "header" , Space , Str "level" , Space , Str "5" ]
+  , Header
+      6
+      ( "header-level-6" , [] , [] )
+      [ Str "header" , Space , Str "level" , Space , Str "6" ]
+  , Para
+      [ Str "!!!!!!!"
+      , Space
+      , Str "not"
+      , Space
+      , Str "a"
+      , Space
+      , Str "header"
+      ]
+  , Para
+      [ Str "--++"
+      , Space
+      , Str "not"
+      , Space
+      , Str "a"
+      , Space
+      , Str "header"
+      ]
+  , Header
+      1
+      ( "emph-and-strong" , [] , [] )
+      [ Str "emph" , Space , Str "and" , Space , Str "strong" ]
+  , Para
+      [ Emph [ Str "emph" ] , Space , Strong [ Str "strong" ] ]
+  , Para
+      [ Emph
+          [ Strong
+              [ Str "strong"
+              , Space
+              , Str "and"
+              , Space
+              , Str "emph"
+              , Space
+              , Str "1"
+              ]
+          ]
+      ]
+  , Para
+      [ Strong
+          [ Emph
+              [ Str "strong"
+              , Space
+              , Str "and"
+              , Space
+              , Str "emph"
+              , Space
+              , Str "2"
+              ]
+          ]
+      ]
+  , Para
+      [ Strong
+          [ Emph [ Str "emph" , Space , Str "inside" ]
+          , Space
+          , Str "strong"
+          ]
+      ]
+  , Para
+      [ Strong
+          [ Str "strong"
+          , Space
+          , Str "with"
+          , Space
+          , Emph [ Str "emph" ]
+          ]
+      ]
+  , Para
+      [ Emph
+          [ Strong [ Str "strong" , Space , Str "inside" ]
+          , Space
+          , Str "emph"
+          ]
+      ]
+  , Header
+      1
+      ( "other-inlines" , [] , [] )
+      [ Str "other" , Space , Str "inlines" ]
+  , Para
+      [ Underline [ Str "underlined" , Space , Str "text" ] ]
+  , Para [ Strikeout [ Str "strikeout" ] ]
+  , Header
+      1
+      ( "horizontal-rule" , [] , [] )
+      [ Str "horizontal" , Space , Str "rule" ]
+  , Para [ Str "top" ]
+  , HorizontalRule
+  , Para [ Str "bottom" ]
+  , HorizontalRule
+  , Header 1 ( "nop" , [] , [] ) [ Str "nop" ]
+  , Para [ Str "__not emph__" ]
+  , Header 1 ( "entities" , [] , [] ) [ Str "entities" ]
+  , Para [ Str "hi" , Space , Str "&" , Space , Str "low" ]
+  , Para [ Str "hi" , Space , Str "&" , Space , Str "low" ]
+  , Para [ Str "G\246del" ]
+  , Para [ Str "\777\2730" ]
+  , Header 1 ( "linebreaks" , [] , [] ) [ Str "linebreaks" ]
+  , Para [ Str "hi" , LineBreak , Str "there" ]
+  , Para [ Str "hi" , LineBreak , Str "there" ]
+  , Header
+      1
+      ( "inline-code" , [] , [] )
+      [ Str "inline" , Space , Str "code" ]
+  , Para
+      [ Code ( "" , [] , [] ) "*\8594*"
+      , Space
+      , Code ( "" , [] , [] ) "typed"
+      , Space
+      , Code ( "" , [] , [] ) ">>="
+      ]
+  , Header
+      1
+      ( "code-blocks" , [] , [] )
+      [ Str "code" , Space , Str "blocks" ]
+  , CodeBlock
+      ( "" , [] , [] )
+      "\ncase xs of\n     (_:_) -> reverse xs\n     []    -> ['*']\n"
+  , CodeBlock
+      ( ""
+      , [ "haskell" ]
+      , [ ( "colors" , "haskell" ) , ( "ln" , "0" ) ]
+      )
+      "\ncase xs of\n     (_:_) -> reverse xs\n     []    -> ['*']\n"
+  , Header
+      1
+      ( "external-links" , [] , [] )
+      [ Str "external" , Space , Str "links" ]
+  , Para
+      [ Link
+          ( "" , [] , [] )
+          [ Emph [ Str "Google" ]
+          , Space
+          , Str "search"
+          , Space
+          , Str "engine"
+          ]
+          ( "http://google.com" , "" )
+      ]
+  , Para
+      [ Link
+          ( "" , [] , [] )
+          [ Str "http://pandoc.org" ]
+          ( "http://pandoc.org" , "" )
+      ]
+  , Para
+      [ Link
+          ( "" , [] , [] )
+          [ Str "http://google.com" ]
+          ( "http://google.com" , "" )
+      , Space
+      , Link
+          ( "" , [] , [] )
+          [ Str "http://yahoo.com" ]
+          ( "http://yahoo.com" , "" )
+      ]
+  , Para
+      [ Link
+          ( "" , [] , [] )
+          [ Str "email" , Space , Str "me" ]
+          ( "mailto:info@example.org" , "" )
+      ]
+  , Para [ Str "http://google.com" ]
+  , Para [ Str "info@example.org" ]
+  , Header 1 ( "lists" , [] , [] ) [ Str "lists" ]
+  , BulletList
+      [ [ Plain
+            [ Str "Start" , Space , Str "each" , Space , Str "line" ]
+        ]
+      , [ Plain
+            [ Str "with"
+            , Space
+            , Str "an"
+            , Space
+            , Str "asterisk"
+            , Space
+            , Str "(*)."
+            ]
+        , BulletList
+            [ [ Plain
+                  [ Str "More"
+                  , Space
+                  , Str "asterisks"
+                  , Space
+                  , Str "gives"
+                  , Space
+                  , Str "deeper"
+                  ]
+              , BulletList
+                  [ [ Plain
+                        [ Str "and"
+                        , Space
+                        , Str "deeper"
+                        , Space
+                        , Str "levels."
+                        ]
+                    ]
+                  ]
+              ]
+            ]
+        ]
+      , [ Plain
+            [ Str "Line"
+            , Space
+            , Str "breaks"
+            , LineBreak
+            , Str "don't"
+            , Space
+            , Str "break"
+            , Space
+            , Str "levels."
+            ]
+        ]
+      , [ Plain
+            [ Str "Continuations"
+            , Space
+            , Str "are"
+            , Space
+            , Str "also"
+            , Space
+            , Str "possible"
+            ]
+        , BulletList
+            [ [ Plain
+                  [ Str "and"
+                  , Space
+                  , Str "do"
+                  , Space
+                  , Str "not"
+                  , Space
+                  , Str "break"
+                  , Space
+                  , Str "the"
+                  , Space
+                  , Str "list"
+                  , Space
+                  , Str "flow"
+                  ]
+              ]
+            ]
+        ]
+      , [ Plain [ Str "Level" , Space , Str "one" ] ]
+      ]
+  , Para
+      [ Str "Any"
+      , Space
+      , Str "other"
+      , Space
+      , Str "start"
+      , Space
+      , Str "ends"
+      , Space
+      , Str "the"
+      , Space
+      , Str "list."
+      ]
+  , OrderedList
+      ( 1 , DefaultStyle , DefaultDelim )
+      [ [ Plain
+            [ Str "Start" , Space , Str "each" , Space , Str "line" ]
+        ]
+      , [ Plain
+            [ Str "with"
+            , Space
+            , Str "a"
+            , Space
+            , Str "number"
+            , Space
+            , Str "(1.)."
+            ]
+        , OrderedList
+            ( 1 , DefaultStyle , DefaultDelim )
+            [ [ Plain
+                  [ Str "More"
+                  , Space
+                  , Str "number"
+                  , Space
+                  , Str "signs"
+                  , Space
+                  , Str "gives"
+                  , Space
+                  , Str "deeper"
+                  ]
+              , OrderedList
+                  ( 1 , DefaultStyle , DefaultDelim )
+                  [ [ Plain [ Str "and" , Space , Str "deeper" ] ]
+                  , [ Plain [ Str "levels." ] ]
+                  ]
+              ]
+            ]
+        ]
+      , [ Plain
+            [ Str "Line"
+            , Space
+            , Str "breaks"
+            , LineBreak
+            , Str "don't"
+            , Space
+            , Str "break"
+            , Space
+            , Str "levels."
+            ]
+        ]
+      , [ Plain [ Str "Blank" , Space , Str "lines" ] ]
+      ]
+  , OrderedList
+      ( 1 , DefaultStyle , DefaultDelim )
+      [ [ Plain
+            [ Str "end"
+            , Space
+            , Str "the"
+            , Space
+            , Str "list"
+            , Space
+            , Str "and"
+            , Space
+            , Str "start"
+            , Space
+            , Str "another."
+            ]
+        ]
+      ]
+  , Para
+      [ Str "Any"
+      , Space
+      , Str "other"
+      , Space
+      , Str "start"
+      , Space
+      , Str "also"
+      , Space
+      , Str "ends"
+      , Space
+      , Str "the"
+      , Space
+      , Str "list."
+      ]
+  , DefinitionList
+      [ ( [ Str "item" , Space , Str "1" ]
+        , [ [ Plain [ Str "definition" , Space , Str "1" ] ] ]
+        )
+      , ( [ Str "item" , Space , Str "2" ]
+        , [ [ Plain
+                [ Str "definition"
+                , Space
+                , Str "2-1"
+                , Space
+                , Str "definition"
+                , Space
+                , Str "2-2"
+                ]
+            ]
+          ]
+        )
+      , ( [ Str "item" , Space , Emph [ Str "3" ] ]
+        , [ [ Plain [ Str "definition" , Space , Emph [ Str "3" ] ]
+            ]
+          ]
+        )
+      ]
+  , OrderedList
+      ( 1 , DefaultStyle , DefaultDelim )
+      [ [ Plain [ Str "one" ] ]
+      , [ Plain [ Str "two" ]
+        , BulletList
+            [ [ Plain
+                  [ Str "two"
+                  , Space
+                  , Str "point"
+                  , Space
+                  , Str "one"
+                  ]
+              ]
+            , [ Plain
+                  [ Str "two"
+                  , Space
+                  , Str "point"
+                  , Space
+                  , Str "two"
+                  ]
+              ]
+            ]
+        ]
+      , [ Plain [ Str "three" ] ]
+      , [ Plain [ Str "four" ] ]
+      , [ Plain [ Str "five" ]
+        , OrderedList
+            ( 1 , DefaultStyle , DefaultDelim )
+            [ [ Plain
+                  [ Str "five" , Space , Str "sub" , Space , Str "1" ]
+              , OrderedList
+                  ( 1 , DefaultStyle , DefaultDelim )
+                  [ [ Plain
+                        [ Str "five"
+                        , Space
+                        , Str "sub"
+                        , Space
+                        , Str "1"
+                        , Space
+                        , Str "sub"
+                        , Space
+                        , Str "1"
+                        ]
+                    ]
+                  ]
+              ]
+            , [ Plain
+                  [ Str "five" , Space , Str "sub" , Space , Str "2" ]
+              ]
+            ]
+        ]
+      ]
+  , Header 1 ( "tables" , [] , [] ) [ Str "tables" ]
+  , Table
+      ( "" , [] , [] )
+      (Caption Nothing [])
+      [ ( AlignDefault , ColWidthDefault )
+      , ( AlignDefault , ColWidthDefault )
+      ]
+      (TableHead
+         ( "" , [] , [] )
+         [ Row
+             ( "" , [] , [] )
+             [ Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "" ] ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "" ] ]
+             ]
+         ])
+      [ TableBody
+          ( "" , [] , [] )
+          (RowHeadColumns 0)
+          []
+          [ Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "Orange" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "Apple" ] ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "Bread" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "Pie" ] ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "Butter" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "Ice" , Space , Str "cream" ] ]
+              ]
+          ]
+      ]
+      (TableFoot ( "" , [] , [] ) [])
+  , Table
+      ( "" , [] , [] )
+      (Caption Nothing [])
+      [ ( AlignDefault , ColWidthDefault )
+      , ( AlignDefault , ColWidthDefault )
+      ]
+      (TableHead
+         ( "" , [] , [] )
+         [ Row
+             ( "" , [] , [] )
+             [ Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "" ] ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "" ] ]
+             ]
+         ])
+      [ TableBody
+          ( "" , [] , [] )
+          (RowHeadColumns 0)
+          []
+          [ Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "Orange" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "Apple" ] ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "Bread" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "Pie" ] ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Strong [ Str "Butter" ] ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "Ice" , Space , Str "cream" ] ]
+              ]
+          ]
+      ]
+      (TableFoot ( "" , [] , [] ) [])
+  , Table
+      ( "" , [] , [] )
+      (Caption Nothing [])
+      [ ( AlignDefault , ColWidthDefault )
+      , ( AlignDefault , ColWidthDefault )
+      ]
+      (TableHead
+         ( "" , [] , [] )
+         [ Row
+             ( "" , [] , [] )
+             [ Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "" ] ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "" ] ]
+             ]
+         ])
+      [ TableBody
+          ( "" , [] , [] )
+          (RowHeadColumns 0)
+          []
+          [ Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "Orange" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "Apple" ] ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain
+                      [ Str "Bread"
+                      , LineBreak
+                      , LineBreak
+                      , Str "and"
+                      , Space
+                      , Str "cheese"
+                      ]
+                  ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain
+                      [ Str "Pie"
+                      , LineBreak
+                      , LineBreak
+                      , Strong [ Str "apple" ]
+                      , Space
+                      , Str "and"
+                      , Space
+                      , Emph [ Str "carrot" ]
+                      , Space
+                      ]
+                  ]
+              ]
+          ]
+      ]
+      (TableFoot ( "" , [] , [] ) [])
+  , Table
+      ( "" , [] , [] )
+      (Caption Nothing [])
+      [ ( AlignDefault , ColWidthDefault )
+      , ( AlignDefault , ColWidthDefault )
+      , ( AlignDefault , ColWidthDefault )
+      ]
+      (TableHead
+         ( "" , [] , [] )
+         [ Row
+             ( "" , [] , [] )
+             [ Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "" ] ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "" ] ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "" ] ]
+             ]
+         ])
+      [ TableBody
+          ( "" , [] , [] )
+          (RowHeadColumns 0)
+          []
+          [ Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Space , Str "Orange" , Space ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Space , Str "Apple" , Space ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Space , Str "more" ] ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Space , Str "Bread" , Space ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Space , Str "Pie" , Space ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Space , Str "more" ] ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Space , Str "Butter" , Space ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain
+                      [ Space
+                      , Str "Ice"
+                      , Space
+                      , Str "cream"
+                      , Space
+                      ]
+                  ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain
+                      [ Space , Str "and" , Space , Str "more" , Space ]
+                  ]
+              ]
+          ]
+      ]
+      (TableFoot ( "" , [] , [] ) [])
+  ]
diff --git a/test/tikiwiki-reader.tikiwiki b/test/tikiwiki-reader.tikiwiki
--- a/test/tikiwiki-reader.tikiwiki
+++ b/test/tikiwiki-reader.tikiwiki
@@ -28,6 +28,12 @@
 
 ''__strong inside__ emph''
 
+! other inlines
+
+===underlined text===
+
+--strikeout--
+
 ! horizontal rule
 
 top
diff --git a/test/twiki-reader.native b/test/twiki-reader.native
--- a/test/twiki-reader.native
+++ b/test/twiki-reader.native
@@ -1,174 +1,879 @@
-Pandoc (Meta {unMeta = fromList []})
-[Header 1 ("header",[],[]) [Str "header"]
-,Header 2 ("header-level-two",[],[]) [Str "header",Space,Str "level",Space,Str "two"]
-,Header 3 ("header-level-3",[],[]) [Str "header",Space,Str "level",Space,Str "3"]
-,Header 4 ("header-level-four",[],[]) [Str "header",Space,Emph [Str "level"],Space,Str "four"]
-,Header 5 ("header-level-5",[],[]) [Str "header",Space,Str "level",Space,Str "5"]
-,Header 6 ("header-level-6",[],[]) [Str "header",Space,Str "level",Space,Str "6"]
-,Para [Str "---+++++++",Space,Str "not",Space,Str "a",Space,Str "header"]
-,Para [Str "--++",Space,Str "not",Space,Str "a",Space,Str "header"]
-,Header 1 ("emph-and-strong",[],[]) [Str "emph",Space,Str "and",Space,Str "strong"]
-,Para [Emph [Str "emph"],Space,Strong [Str "strong"]]
-,Para [Emph [Strong [Str "strong",Space,Str "and",Space,Str "emph"]]]
-,Para [Strong [Emph [Str "emph",Space,Str "inside"],Space,Str "strong"]]
-,Para [Strong [Str "strong",Space,Str "with",Space,Emph [Str "emph"]]]
-,Para [Emph [Strong [Str "strong",Space,Str "inside"],Space,Str "emph"]]
-,Header 1 ("horizontal-rule",[],[]) [Str "horizontal",Space,Str "rule"]
-,Para [Str "top"]
-,HorizontalRule
-,Para [Str "bottom"]
-,HorizontalRule
-,Header 1 ("nop",[],[]) [Str "nop"]
-,Para [Str "_not",Space,Str "emph_"]
-,Header 1 ("entities",[],[]) [Str "entities"]
-,Para [Str "hi",Space,Str "&",Space,Str "low"]
-,Para [Str "hi",Space,Str "&",Space,Str "low"]
-,Para [Str "G\246del"]
-,Para [Str "\777\2730"]
-,Header 1 ("comments",[],[]) [Str "comments"]
-,Para [Str "inline",Space,Str "comment"]
-,Para [Str "between",Space,Str "blocks"]
-,Header 1 ("linebreaks",[],[]) [Str "linebreaks"]
-,Para [Str "hi",LineBreak,Str "there"]
-,Para [Str "hi",LineBreak,Str "there"]
-,Header 1 ("inline-code",[],[]) [Str "inline",Space,Str "code"]
-,Para [Code ("",[],[]) "*\8594*",Space,Code ("",[],[]) "typed",Space,Code ("",["haskell"],[]) ">>="]
-,Header 1 ("code-blocks",[],[]) [Str "code",Space,Str "blocks"]
-,CodeBlock ("",[],[]) "case xs of\n     (_:_) -> reverse xs\n     []    -> ['*']"
-,CodeBlock ("",["haskell"],[]) "case xs of\n     (_:_) -> reverse xs\n     []    -> ['*']"
-,Header 1 ("block-quotes",[],[]) [Str "block",Space,Str "quotes"]
-,Para [Str "Regular",Space,Str "paragraph"]
-,BlockQuote
- [Para [Str "This",Space,Str "is",Space,Str "a",Space,Str "block",Space,Str "quote."]
- ,Para [Str "With",Space,Str "two",Space,Str "paragraphs."]]
-,Para [Str "Nother",Space,Str "paragraph."]
-,Header 1 ("external-links",[],[]) [Str "external",Space,Str "links"]
-,Para [Link ("",[],[]) [Emph [Str "Google"],Space,Str "search",Space,Str "engine"] ("http://google.com","")]
-,Para [Link ("",[],[]) [Str "http://pandoc.org"] ("http://pandoc.org","")]
-,Para [Link ("",[],[]) [Str "http://google.com"] ("http://google.com",""),Space,Link ("",[],[]) [Str "http://yahoo.com"] ("http://yahoo.com","")]
-,Para [Link ("",[],[]) [Str "email",Space,Str "me"] ("mailto:info@example.org","")]
-,Para [Str "http://google.com"]
-,Para [Str "http://google.com"]
-,Para [Str "http://google.com"]
-,Para [Str "info@example.org"]
-,Para [Str "info@example.org"]
-,Para [Str "info@example.org"]
-,Header 1 ("lists",[],[]) [Str "lists"]
-,BulletList
- [[Plain [Str "Start",Space,Str "each",Space,Str "line"]]
- ,[Plain [Str "with",Space,Str "an",Space,Str "asterisk",Space,Str "(*)."]
-  ,BulletList
-   [[Plain [Str "More",Space,Str "asterisks",Space,Str "gives",Space,Str "deeper"]
-    ,BulletList
-     [[Plain [Str "and",Space,Str "deeper",Space,Str "levels."]]]]]]
- ,[Plain [Str "Line",Space,Str "breaks",LineBreak,Str "don't",Space,Str "break",Space,Str "levels."]]
- ,[Plain [Str "Continuations",Space,Str "are",Space,Str "also",Space,Str "possible"]
-  ,BulletList
-   [[Plain [Str "and",Space,Str "do",Space,Str "not",Space,Str "break",Space,Str "the",Space,Str "list",Space,Str "flow"]]]]
- ,[Plain [Str "Level",Space,Str "one"]]]
-,Para [Str "Any",Space,Str "other",Space,Str "start",Space,Str "ends",Space,Str "the",Space,Str "list."]
-,OrderedList (1,DefaultStyle,DefaultDelim)
- [[Plain [Str "Start",Space,Str "each",Space,Str "line"]]
- ,[Plain [Str "with",Space,Str "a",Space,Str "number",Space,Str "(1.)."]
-  ,OrderedList (1,DefaultStyle,DefaultDelim)
-   [[Plain [Str "More",Space,Str "number",Space,Str "signs",Space,Str "gives",Space,Str "deeper"]
-    ,OrderedList (1,DefaultStyle,DefaultDelim)
-     [[Plain [Str "and",Space,Str "deeper"]]
-     ,[Plain [Str "levels."]]]]]]
- ,[Plain [Str "Line",Space,Str "breaks",LineBreak,Str "don't",Space,Str "break",Space,Str "levels."]]
- ,[Plain [Str "Blank",Space,Str "lines"]]]
-,OrderedList (1,DefaultStyle,DefaultDelim)
- [[Plain [Str "end",Space,Str "the",Space,Str "list",Space,Str "and",Space,Str "start",Space,Str "another."]]]
-,Para [Str "Any",Space,Str "other",Space,Str "start",Space,Str "also",Space,Str "ends",Space,Str "the",Space,Str "list."]
-,DefinitionList
- [([Str "item",Space,Str "1"],
-   [[Plain [Str "definition",Space,Str "1"]]])
- ,([Str "item",Space,Str "2"],
-   [[Plain [Str "definition",Space,Str "2-1",Space,Str "definition",Space,Str "2-2"]]])
- ,([Str "item",Space,Emph [Str "3"]],
-   [[Plain [Str "definition",Space,Emph [Str "3"]]]])]
-,OrderedList (1,DefaultStyle,DefaultDelim)
- [[Plain [Str "one"]]
- ,[Plain [Str "two"]
-  ,BulletList
-   [[Plain [Str "two",Space,Str "point",Space,Str "one"]]
-   ,[Plain [Str "two",Space,Str "point",Space,Str "two"]]]]
- ,[Plain [Str "three"]
-  ,DefinitionList
-   [([Str "three",Space,Str "item",Space,Str "one"],
-     [[Plain [Str "three",Space,Str "def",Space,Str "one"]]])]]
- ,[Plain [Str "four"]
-  ,DefinitionList
-   [([Str "four",Space,Str "def",Space,Str "one"],
-     [[Plain [Str "this",Space,Str "is",Space,Str "a",Space,Str "continuation"]]])]]
- ,[Plain [Str "five"]
-  ,OrderedList (1,DefaultStyle,DefaultDelim)
-   [[Plain [Str "five",Space,Str "sub",Space,Str "1"]
-    ,OrderedList (1,DefaultStyle,DefaultDelim)
-     [[Plain [Str "five",Space,Str "sub",Space,Str "1",Space,Str "sub",Space,Str "1"]]]]
-   ,[Plain [Str "five",Space,Str "sub",Space,Str "2"]]]]]
-,OrderedList (1,DefaultStyle,DefaultDelim)
- [[Plain [Str "other"]
-  ,OrderedList (1,UpperRoman,DefaultDelim)
-   [[Plain [Str "list"]]
-   ,[Plain [Str "styles"]]]]
- ,[Plain [Str "are"]
-  ,OrderedList (1,LowerRoman,DefaultDelim)
-   [[Plain [Str "also"]]
-   ,[Plain [Str "possible"]]]]
- ,[Plain [Str "all"]
-  ,OrderedList (1,LowerAlpha,DefaultDelim)
-   [[Plain [Str "the"]]
-   ,[Plain [Str "different"]]
-   ,[Plain [Str "styles"]]]]
- ,[Plain [Str "are"]
-  ,OrderedList (1,UpperAlpha,DefaultDelim)
-   [[Plain [Str "implemented"]]
-   ,[Plain [Str "and"]]
-   ,[Plain [Str "supported"]]]]]
-,Header 1 ("tables",[],[]) [Str "tables"]
-,Table [] [AlignDefault,AlignDefault] [0.0,0.0]
- [[]
- ,[]]
- [[[Plain [Str "Orange"]]
-  ,[Plain [Str "Apple"]]]
- ,[[Plain [Str "Bread"]]
-  ,[Plain [Str "Pie"]]]
- ,[[Plain [Str "Butter"]]
-  ,[Plain [Str "Ice",Space,Str "cream"]]]]
-,Table [] [AlignLeft,AlignLeft] [0.0,0.0]
- [[Plain [Str "Orange"]]
- ,[Plain [Str "Apple"]]]
- [[[Plain [Str "Bread"]]
-  ,[Plain [Str "Pie"]]]
- ,[[Plain [Strong [Str "Butter"]]]
-  ,[Plain [Str "Ice",Space,Str "cream"]]]]
-,Table [] [AlignLeft,AlignLeft] [0.0,0.0]
- [[Plain [Str "Orange"]]
- ,[Plain [Str "Apple"]]]
- [[[Plain [Str "Bread",LineBreak,LineBreak,Str "and",Space,Str "cheese"]]
-  ,[Plain [Str "Pie",LineBreak,LineBreak,Strong [Str "apple"],Space,Str "and",Space,Emph [Str "carrot"]]]]]
-,Table [] [AlignDefault,AlignDefault,AlignDefault] [0.0,0.0,0.0]
- [[]
- ,[]
- ,[]]
- [[[Plain [Str "Orange"]]
-  ,[Plain [Str "Apple"]]
-  ,[Plain [Str "more"]]]
- ,[[Plain [Str "Bread"]]
-  ,[Plain [Str "Pie"]]
-  ,[Plain [Str "more"]]]
- ,[[Plain [Str "Butter"]]
-  ,[Plain [Str "Ice",Space,Str "cream"]]
-  ,[Plain [Str "and",Space,Str "more"]]]]
-,Header 1 ("macros",[],[]) [Str "macros"]
-,Para [Span ("",["twiki-macro","TEST"],[]) []]
-,Para [Span ("",["twiki-macro","TEST"],[]) [Str ""]]
-,Para [Span ("",["twiki-macro","TEST"],[]) [Str "content with spaces"]]
-,Para [Span ("",["twiki-macro","TEST"],[]) [Str "content with spaces"]]
-,Para [Span ("",["twiki-macro","TEST"],[("ARG1","test")]) [Str "content with spaces"]]
-,Para [Span ("",["twiki-macro","TEST"],[]) [Str "content with spaces ARG1=test"]]
-,Para [Span ("",["twiki-macro","TEST"],[("ARG1","test")]) [Str "content with spaces"]]
-,Para [Span ("",["twiki-macro","TEST"],[("ARG1","test"),("ARG2","test2")]) [Str ""]]
-,Para [Span ("",["twiki-macro","TEST"],[("ARG1","test"),("ARG2","test2")]) [Str ""]]
-,Para [Span ("",["twiki-macro","TEST"],[("ARG1","test"),("ARG2","test2")]) [Str "multiline\ndoes also work"]]]
+Pandoc
+  Meta { unMeta = fromList [] }
+  [ Header 1 ( "header" , [] , [] ) [ Str "header" ]
+  , Header
+      2
+      ( "header-level-two" , [] , [] )
+      [ Str "header" , Space , Str "level" , Space , Str "two" ]
+  , Header
+      3
+      ( "header-level-3" , [] , [] )
+      [ Str "header" , Space , Str "level" , Space , Str "3" ]
+  , Header
+      4
+      ( "header-level-four" , [] , [] )
+      [ Str "header"
+      , Space
+      , Emph [ Str "level" ]
+      , Space
+      , Str "four"
+      ]
+  , Header
+      5
+      ( "header-level-5" , [] , [] )
+      [ Str "header" , Space , Str "level" , Space , Str "5" ]
+  , Header
+      6
+      ( "header-level-6" , [] , [] )
+      [ Str "header" , Space , Str "level" , Space , Str "6" ]
+  , Para
+      [ Str "---+++++++"
+      , Space
+      , Str "not"
+      , Space
+      , Str "a"
+      , Space
+      , Str "header"
+      ]
+  , Para
+      [ Str "--++"
+      , Space
+      , Str "not"
+      , Space
+      , Str "a"
+      , Space
+      , Str "header"
+      ]
+  , Header
+      1
+      ( "emph-and-strong" , [] , [] )
+      [ Str "emph" , Space , Str "and" , Space , Str "strong" ]
+  , Para
+      [ Emph [ Str "emph" ] , Space , Strong [ Str "strong" ] ]
+  , Para
+      [ Emph
+          [ Strong
+              [ Str "strong" , Space , Str "and" , Space , Str "emph" ]
+          ]
+      ]
+  , Para
+      [ Strong
+          [ Emph [ Str "emph" , Space , Str "inside" ]
+          , Space
+          , Str "strong"
+          ]
+      ]
+  , Para
+      [ Strong
+          [ Str "strong"
+          , Space
+          , Str "with"
+          , Space
+          , Emph [ Str "emph" ]
+          ]
+      ]
+  , Para
+      [ Emph
+          [ Strong [ Str "strong" , Space , Str "inside" ]
+          , Space
+          , Str "emph"
+          ]
+      ]
+  , Header
+      1
+      ( "horizontal-rule" , [] , [] )
+      [ Str "horizontal" , Space , Str "rule" ]
+  , Para [ Str "top" ]
+  , HorizontalRule
+  , Para [ Str "bottom" ]
+  , HorizontalRule
+  , Header 1 ( "nop" , [] , [] ) [ Str "nop" ]
+  , Para [ Str "_not" , Space , Str "emph_" ]
+  , Header 1 ( "entities" , [] , [] ) [ Str "entities" ]
+  , Para [ Str "hi" , Space , Str "&" , Space , Str "low" ]
+  , Para [ Str "hi" , Space , Str "&" , Space , Str "low" ]
+  , Para [ Str "G\246del" ]
+  , Para [ Str "\777\2730" ]
+  , Header 1 ( "comments" , [] , [] ) [ Str "comments" ]
+  , Para [ Str "inline" , Space , Str "comment" ]
+  , Para [ Str "between" , Space , Str "blocks" ]
+  , Header 1 ( "linebreaks" , [] , [] ) [ Str "linebreaks" ]
+  , Para [ Str "hi" , LineBreak , Str "there" ]
+  , Para [ Str "hi" , LineBreak , Str "there" ]
+  , Header
+      1
+      ( "inline-code" , [] , [] )
+      [ Str "inline" , Space , Str "code" ]
+  , Para
+      [ Code ( "" , [] , [] ) "*\8594*"
+      , Space
+      , Code ( "" , [] , [] ) "typed"
+      , Space
+      , Code ( "" , [ "haskell" ] , [] ) ">>="
+      ]
+  , Header
+      1
+      ( "code-blocks" , [] , [] )
+      [ Str "code" , Space , Str "blocks" ]
+  , CodeBlock
+      ( "" , [] , [] )
+      "case xs of\n     (_:_) -> reverse xs\n     []    -> ['*']"
+  , CodeBlock
+      ( "" , [ "haskell" ] , [] )
+      "case xs of\n     (_:_) -> reverse xs\n     []    -> ['*']"
+  , Header
+      1
+      ( "block-quotes" , [] , [] )
+      [ Str "block" , Space , Str "quotes" ]
+  , Para [ Str "Regular" , Space , Str "paragraph" ]
+  , BlockQuote
+      [ Para
+          [ Str "This"
+          , Space
+          , Str "is"
+          , Space
+          , Str "a"
+          , Space
+          , Str "block"
+          , Space
+          , Str "quote."
+          ]
+      , Para
+          [ Str "With"
+          , Space
+          , Str "two"
+          , Space
+          , Str "paragraphs."
+          ]
+      ]
+  , Para [ Str "Nother" , Space , Str "paragraph." ]
+  , Header
+      1
+      ( "internal-links" , [] , [] )
+      [ Str "internal" , Space , Str "links" ]
+  , Para
+      [ Link
+          ( "" , [ "wikilink" ] , [] )
+          [ Str "MySimplePage" ]
+          ( "MySimplePage" , "" )
+      ]
+  , Para
+      [ Link
+          ( "" , [ "wikilink" ] , [] )
+          [ Str "My23Page23" ]
+          ( "My23Page23" , "" )
+      ]
+  , Header
+      1
+      ( "external-links" , [] , [] )
+      [ Str "external" , Space , Str "links" ]
+  , Para
+      [ Link
+          ( "" , [] , [] )
+          [ Emph [ Str "Google" ]
+          , Space
+          , Str "search"
+          , Space
+          , Str "engine"
+          ]
+          ( "http://google.com" , "" )
+      ]
+  , Para
+      [ Link
+          ( "" , [] , [] )
+          [ Str "http://pandoc.org" ]
+          ( "http://pandoc.org" , "" )
+      ]
+  , Para
+      [ Link
+          ( "" , [] , [] )
+          [ Str "http://google.com" ]
+          ( "http://google.com" , "" )
+      , Space
+      , Link
+          ( "" , [] , [] )
+          [ Str "http://yahoo.com" ]
+          ( "http://yahoo.com" , "" )
+      ]
+  , Para
+      [ Link
+          ( "" , [] , [] )
+          [ Str "email" , Space , Str "me" ]
+          ( "mailto:info@example.org" , "" )
+      ]
+  , Para [ Str "http://google.com" ]
+  , Para [ Str "http://google.com" ]
+  , Para [ Str "http://google.com" ]
+  , Para [ Str "info@example.org" ]
+  , Para [ Str "info@example.org" ]
+  , Para [ Str "info@example.org" ]
+  , Header 1 ( "lists" , [] , [] ) [ Str "lists" ]
+  , BulletList
+      [ [ Plain
+            [ Str "Start" , Space , Str "each" , Space , Str "line" ]
+        ]
+      , [ Plain
+            [ Str "with"
+            , Space
+            , Str "an"
+            , Space
+            , Str "asterisk"
+            , Space
+            , Str "(*)."
+            ]
+        , BulletList
+            [ [ Plain
+                  [ Str "More"
+                  , Space
+                  , Str "asterisks"
+                  , Space
+                  , Str "gives"
+                  , Space
+                  , Str "deeper"
+                  ]
+              , BulletList
+                  [ [ Plain
+                        [ Str "and"
+                        , Space
+                        , Str "deeper"
+                        , Space
+                        , Str "levels."
+                        ]
+                    ]
+                  ]
+              ]
+            ]
+        ]
+      , [ Plain
+            [ Str "Line"
+            , Space
+            , Str "breaks"
+            , LineBreak
+            , Str "don't"
+            , Space
+            , Str "break"
+            , Space
+            , Str "levels."
+            ]
+        ]
+      , [ Plain
+            [ Str "Continuations"
+            , Space
+            , Str "are"
+            , Space
+            , Str "also"
+            , Space
+            , Str "possible"
+            ]
+        , BulletList
+            [ [ Plain
+                  [ Str "and"
+                  , Space
+                  , Str "do"
+                  , Space
+                  , Str "not"
+                  , Space
+                  , Str "break"
+                  , Space
+                  , Str "the"
+                  , Space
+                  , Str "list"
+                  , Space
+                  , Str "flow"
+                  ]
+              ]
+            ]
+        ]
+      , [ Plain [ Str "Level" , Space , Str "one" ] ]
+      ]
+  , Para
+      [ Str "Any"
+      , Space
+      , Str "other"
+      , Space
+      , Str "start"
+      , Space
+      , Str "ends"
+      , Space
+      , Str "the"
+      , Space
+      , Str "list."
+      ]
+  , OrderedList
+      ( 1 , DefaultStyle , DefaultDelim )
+      [ [ Plain
+            [ Str "Start" , Space , Str "each" , Space , Str "line" ]
+        ]
+      , [ Plain
+            [ Str "with"
+            , Space
+            , Str "a"
+            , Space
+            , Str "number"
+            , Space
+            , Str "(1.)."
+            ]
+        , OrderedList
+            ( 1 , DefaultStyle , DefaultDelim )
+            [ [ Plain
+                  [ Str "More"
+                  , Space
+                  , Str "number"
+                  , Space
+                  , Str "signs"
+                  , Space
+                  , Str "gives"
+                  , Space
+                  , Str "deeper"
+                  ]
+              , OrderedList
+                  ( 1 , DefaultStyle , DefaultDelim )
+                  [ [ Plain [ Str "and" , Space , Str "deeper" ] ]
+                  , [ Plain [ Str "levels." ] ]
+                  ]
+              ]
+            ]
+        ]
+      , [ Plain
+            [ Str "Line"
+            , Space
+            , Str "breaks"
+            , LineBreak
+            , Str "don't"
+            , Space
+            , Str "break"
+            , Space
+            , Str "levels."
+            ]
+        ]
+      , [ Plain [ Str "Blank" , Space , Str "lines" ] ]
+      ]
+  , OrderedList
+      ( 1 , DefaultStyle , DefaultDelim )
+      [ [ Plain
+            [ Str "end"
+            , Space
+            , Str "the"
+            , Space
+            , Str "list"
+            , Space
+            , Str "and"
+            , Space
+            , Str "start"
+            , Space
+            , Str "another."
+            ]
+        ]
+      ]
+  , Para
+      [ Str "Any"
+      , Space
+      , Str "other"
+      , Space
+      , Str "start"
+      , Space
+      , Str "also"
+      , Space
+      , Str "ends"
+      , Space
+      , Str "the"
+      , Space
+      , Str "list."
+      ]
+  , DefinitionList
+      [ ( [ Str "item" , Space , Str "1" ]
+        , [ [ Plain [ Str "definition" , Space , Str "1" ] ] ]
+        )
+      , ( [ Str "item" , Space , Str "2" ]
+        , [ [ Plain
+                [ Str "definition"
+                , Space
+                , Str "2-1"
+                , Space
+                , Str "definition"
+                , Space
+                , Str "2-2"
+                ]
+            ]
+          ]
+        )
+      , ( [ Str "item" , Space , Emph [ Str "3" ] ]
+        , [ [ Plain [ Str "definition" , Space , Emph [ Str "3" ] ]
+            ]
+          ]
+        )
+      ]
+  , OrderedList
+      ( 1 , DefaultStyle , DefaultDelim )
+      [ [ Plain [ Str "one" ] ]
+      , [ Plain [ Str "two" ]
+        , BulletList
+            [ [ Plain
+                  [ Str "two"
+                  , Space
+                  , Str "point"
+                  , Space
+                  , Str "one"
+                  ]
+              ]
+            , [ Plain
+                  [ Str "two"
+                  , Space
+                  , Str "point"
+                  , Space
+                  , Str "two"
+                  ]
+              ]
+            ]
+        ]
+      , [ Plain [ Str "three" ]
+        , DefinitionList
+            [ ( [ Str "three" , Space , Str "item" , Space , Str "one" ]
+              , [ [ Plain
+                      [ Str "three"
+                      , Space
+                      , Str "def"
+                      , Space
+                      , Str "one"
+                      ]
+                  ]
+                ]
+              )
+            ]
+        ]
+      , [ Plain [ Str "four" ]
+        , DefinitionList
+            [ ( [ Str "four" , Space , Str "def" , Space , Str "one" ]
+              , [ [ Plain
+                      [ Str "this"
+                      , Space
+                      , Str "is"
+                      , Space
+                      , Str "a"
+                      , Space
+                      , Str "continuation"
+                      ]
+                  ]
+                ]
+              )
+            ]
+        ]
+      , [ Plain [ Str "five" ]
+        , OrderedList
+            ( 1 , DefaultStyle , DefaultDelim )
+            [ [ Plain
+                  [ Str "five" , Space , Str "sub" , Space , Str "1" ]
+              , OrderedList
+                  ( 1 , DefaultStyle , DefaultDelim )
+                  [ [ Plain
+                        [ Str "five"
+                        , Space
+                        , Str "sub"
+                        , Space
+                        , Str "1"
+                        , Space
+                        , Str "sub"
+                        , Space
+                        , Str "1"
+                        ]
+                    ]
+                  ]
+              ]
+            , [ Plain
+                  [ Str "five" , Space , Str "sub" , Space , Str "2" ]
+              ]
+            ]
+        ]
+      ]
+  , OrderedList
+      ( 1 , DefaultStyle , DefaultDelim )
+      [ [ Plain [ Str "other" ]
+        , OrderedList
+            ( 1 , UpperRoman , DefaultDelim )
+            [ [ Plain [ Str "list" ] ] , [ Plain [ Str "styles" ] ] ]
+        ]
+      , [ Plain [ Str "are" ]
+        , OrderedList
+            ( 1 , LowerRoman , DefaultDelim )
+            [ [ Plain [ Str "also" ] ] , [ Plain [ Str "possible" ] ] ]
+        ]
+      , [ Plain [ Str "all" ]
+        , OrderedList
+            ( 1 , LowerAlpha , DefaultDelim )
+            [ [ Plain [ Str "the" ] ]
+            , [ Plain [ Str "different" ] ]
+            , [ Plain [ Str "styles" ] ]
+            ]
+        ]
+      , [ Plain [ Str "are" ]
+        , OrderedList
+            ( 1 , UpperAlpha , DefaultDelim )
+            [ [ Plain [ Str "implemented" ] ]
+            , [ Plain [ Str "and" ] ]
+            , [ Plain [ Str "supported" ] ]
+            ]
+        ]
+      ]
+  , Header 1 ( "tables" , [] , [] ) [ Str "tables" ]
+  , Table
+      ( "" , [] , [] )
+      (Caption Nothing [])
+      [ ( AlignDefault , ColWidthDefault )
+      , ( AlignDefault , ColWidthDefault )
+      ]
+      (TableHead
+         ( "" , [] , [] )
+         [ Row
+             ( "" , [] , [] )
+             [ Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 []
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 []
+             ]
+         ])
+      [ TableBody
+          ( "" , [] , [] )
+          (RowHeadColumns 0)
+          []
+          [ Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "Orange" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "Apple" ] ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "Bread" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "Pie" ] ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "Butter" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "Ice" , Space , Str "cream" ] ]
+              ]
+          ]
+      ]
+      (TableFoot ( "" , [] , [] ) [])
+  , Table
+      ( "" , [] , [] )
+      (Caption Nothing [])
+      [ ( AlignLeft , ColWidthDefault )
+      , ( AlignLeft , ColWidthDefault )
+      ]
+      (TableHead
+         ( "" , [] , [] )
+         [ Row
+             ( "" , [] , [] )
+             [ Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "Orange" ] ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "Apple" ] ]
+             ]
+         ])
+      [ TableBody
+          ( "" , [] , [] )
+          (RowHeadColumns 0)
+          []
+          [ Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "Bread" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "Pie" ] ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Strong [ Str "Butter" ] ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "Ice" , Space , Str "cream" ] ]
+              ]
+          ]
+      ]
+      (TableFoot ( "" , [] , [] ) [])
+  , Table
+      ( "" , [] , [] )
+      (Caption Nothing [])
+      [ ( AlignLeft , ColWidthDefault )
+      , ( AlignLeft , ColWidthDefault )
+      ]
+      (TableHead
+         ( "" , [] , [] )
+         [ Row
+             ( "" , [] , [] )
+             [ Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "Orange" ] ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "Apple" ] ]
+             ]
+         ])
+      [ TableBody
+          ( "" , [] , [] )
+          (RowHeadColumns 0)
+          []
+          [ Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain
+                      [ Str "Bread"
+                      , LineBreak
+                      , LineBreak
+                      , Str "and"
+                      , Space
+                      , Str "cheese"
+                      ]
+                  ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain
+                      [ Str "Pie"
+                      , LineBreak
+                      , LineBreak
+                      , Strong [ Str "apple" ]
+                      , Space
+                      , Str "and"
+                      , Space
+                      , Emph [ Str "carrot" ]
+                      ]
+                  ]
+              ]
+          ]
+      ]
+      (TableFoot ( "" , [] , [] ) [])
+  , Table
+      ( "" , [] , [] )
+      (Caption Nothing [])
+      [ ( AlignDefault , ColWidthDefault )
+      , ( AlignDefault , ColWidthDefault )
+      , ( AlignDefault , ColWidthDefault )
+      ]
+      (TableHead
+         ( "" , [] , [] )
+         [ Row
+             ( "" , [] , [] )
+             [ Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 []
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 []
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 []
+             ]
+         ])
+      [ TableBody
+          ( "" , [] , [] )
+          (RowHeadColumns 0)
+          []
+          [ Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "Orange" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "Apple" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "more" ] ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "Bread" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "Pie" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "more" ] ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "Butter" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "Ice" , Space , Str "cream" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "and" , Space , Str "more" ] ]
+              ]
+          ]
+      ]
+      (TableFoot ( "" , [] , [] ) [])
+  , Header 1 ( "macros" , [] , [] ) [ Str "macros" ]
+  , Para [ Span ( "" , [ "twiki-macro" , "TEST" ] , [] ) [] ]
+  , Para
+      [ Span ( "" , [ "twiki-macro" , "TEST" ] , [] ) [ Str "" ] ]
+  , Para
+      [ Span
+          ( "" , [ "twiki-macro" , "TEST" ] , [] )
+          [ Str "content with spaces" ]
+      ]
+  , Para
+      [ Span
+          ( "" , [ "twiki-macro" , "TEST" ] , [] )
+          [ Str "content with spaces" ]
+      ]
+  , Para
+      [ Span
+          ( ""
+          , [ "twiki-macro" , "TEST" ]
+          , [ ( "ARG1" , "test" ) ]
+          )
+          [ Str "content with spaces" ]
+      ]
+  , Para
+      [ Span
+          ( "" , [ "twiki-macro" , "TEST" ] , [] )
+          [ Str "content with spaces ARG1=test" ]
+      ]
+  , Para
+      [ Span
+          ( ""
+          , [ "twiki-macro" , "TEST" ]
+          , [ ( "ARG1" , "test" ) ]
+          )
+          [ Str "content with spaces" ]
+      ]
+  , Para
+      [ Span
+          ( ""
+          , [ "twiki-macro" , "TEST" ]
+          , [ ( "ARG1" , "test" ) , ( "ARG2" , "test2" ) ]
+          )
+          [ Str "" ]
+      ]
+  , Para
+      [ Span
+          ( ""
+          , [ "twiki-macro" , "TEST" ]
+          , [ ( "ARG1" , "test" ) , ( "ARG2" , "test2" ) ]
+          )
+          [ Str "" ]
+      ]
+  , Para
+      [ Span
+          ( ""
+          , [ "twiki-macro" , "TEST" ]
+          , [ ( "ARG1" , "test" ) , ( "ARG2" , "test2" ) ]
+          )
+          [ Str "multiline\ndoes also work" ]
+      ]
+  ]
diff --git a/test/twiki-reader.twiki b/test/twiki-reader.twiki
--- a/test/twiki-reader.twiki
+++ b/test/twiki-reader.twiki
@@ -93,6 +93,12 @@
 </blockquote>
 Nother paragraph.
 
+---+ internal links
+
+MySimplePage
+
+My23Page23
+
 ---+ external links
 
 [[http://google.com][<i>Google</i> search engine]]
diff --git a/test/txt2tags.native b/test/txt2tags.native
--- a/test/txt2tags.native
+++ b/test/txt2tags.native
@@ -1,611 +1,5299 @@
-Pandoc (Meta {unMeta = fromList [("author",MetaList [MetaInlines [Str "author"]]),("date",MetaInlines [Str "date"]),("includeconf",MetaString "rules.conf"),("title",MetaInlines [Str "Txt2tags",Space,Str "Markup",Space,Str "Rules"])]})
-[Para [Str "This",Space,Str "document",Space,Str "describes",Space,Str "all",Space,Str "the",Space,Str "details",Space,Str "about",Space,Str "each",Space,Str "txt2tags",Space,Str "mark.",SoftBreak,Str "The",Space,Str "target",Space,Str "audience",Space,Str "are",Space,Strong [Str "experienced"],Space,Str "users.",Space,Str "You",Space,Str "may",Space,Str "find",Space,Str "it",SoftBreak,Str "useful",Space,Str "if",Space,Str "you",Space,Str "want",Space,Str "to",Space,Str "master",Space,Str "the",Space,Str "marks",Space,Str "or",Space,Str "solve",Space,Str "a",Space,Str "specific",Space,Str "problem",SoftBreak,Str "about",Space,Str "a",Space,Str "mark."]
-,Para [Str "If",Space,Str "you",Space,Str "are",Space,Str "new",Space,Str "to",Space,Str "txt2tags",Space,Str "or",Space,Str "just",Space,Str "want",Space,Str "to",Space,Str "know",Space,Str "which",Space,Str "are",Space,Str "the",SoftBreak,Str "available",Space,Str "marks,",Space,Str "please",Space,Str "read",Space,Str "the",Space,Link ("",[],[]) [Str "Markup",Space,Str "Demo"] ("MARKUPDEMO",""),Str "."]
-,Para [Str "Note",Space,Str "1:",Space,Str "This",Space,Str "document",Space,Str "is",Space,Str "generated",Space,Str "directly",Space,Str "from",Space,Str "the",Space,Str "txt2tags",SoftBreak,Str "test-suite.",Space,Str "All",Space,Str "the",Space,Str "rules",Space,Str "mentioned",Space,Str "here",Space,Str "are",Space,Str "100%",Space,Str "in",Space,Str "sync",Space,Str "with",Space,Str "the",SoftBreak,Str "current",Space,Str "program",Space,Str "code."]
-,Para [Str "Note",Space,Str "2:",Space,Str "A",Space,Str "good",Space,Str "practice",Space,Str "is",Space,Str "to",Space,Str "consult",Space,Link ("",[],[]) [Str "the",Space,Str "sources"] ("rules.t2t",""),Space,Str "when",SoftBreak,Str "reading,",Space,Str "to",Space,Str "see",Space,Str "how",Space,Str "the",Space,Str "texts",Space,Str "were",Space,Str "made."]
-,Para [Str "Table",Space,Str "of",Space,Str "Contents:"]
-,HorizontalRule
-,Header 1 ("paragraph",[],[]) [Str "Paragraph"]
-,Para [Str "A",Space,Str "paragraph",Space,Str "is",Space,Str "composed",Space,Str "by",Space,Str "one",Space,Str "or",Space,Str "more",Space,Str "lines.",SoftBreak,Str "A",Space,Str "blank",Space,Str "line",Space,Str "(or",Space,Str "a",Space,Str "table,",Space,Str "or",Space,Str "a",Space,Str "list)",Space,Str "ends",Space,Str "the",SoftBreak,Str "current",Space,Str "paragraph."]
-,Para [Str "Leading",Space,Str "and",Space,Str "trailing",Space,Str "spaces",Space,Str "are",Space,Str "ignored."]
-,Para [Str "A",Space,Str "comment",Space,Str "line",Space,Str "can",Space,Str "be",Space,Str "placed",Space,Str "inside",Space,Str "a",Space,Str "paragraph.",SoftBreak,Str "It",Space,Str "will",Space,Str "not",Space,Str "affect",Space,Str "it."]
-,Para [Str "The",Space,Str "end",Space,Str "of",Space,Str "the",Space,Str "file",Space,Str "(EOF)",Space,Str "closes",Space,Str "the",SoftBreak,Str "currently",Space,Str "open",Space,Str "paragraph."]
-,Header 1 ("comment",[],[]) [Str "Comment"]
-,Para [Str "%",Space,Str "not",Space,Str "on",Space,Str "the",Space,Str "line",Space,Str "beginning",Space,Str "(at",Space,Str "column",Space,Str "2)"]
-,Para [Str "some",Space,Str "text",Space,Str "%",Space,Str "half",Space,Str "line",Space,Str "comments",Space,Str "are",Space,Str "not",Space,Str "allowed"]
-,Header 1 ("line",[],[]) [Str "Line"]
-,HorizontalRule
-,HorizontalRule
-,HorizontalRule
-,HorizontalRule
-,HorizontalRule
-,HorizontalRule
-,HorizontalRule
-,HorizontalRule
-,HorizontalRule
-,HorizontalRule
-,HorizontalRule
-,Para [Strikeout [Str "-----"],SoftBreak,Strikeout [Str "-------",Space,Str "--------"]]
-,Para [Strikeout [Str "-------+--------"]]
-,Para [Str "(",Space,Strikeout [Str "----------------"],Space,Str ")"]
-,Header 1 ("inline",[],[]) [Str "Inline"]
-,Para [Str "i)",Space,Strong [Str "b"],Space,Emph [Str "i"],Space,Span ("",["underline"],[]) [Str "u"],Space,Strikeout [Str "s"],Space,Code ("",[],[]) "m",Space,Str "r",Space,RawInline (Format "html") "t",SoftBreak,Str "i)",Space,Strong [Str "bo"],Space,Emph [Str "it"],Space,Span ("",["underline"],[]) [Str "un"],Space,Strikeout [Str "st"],Space,Code ("",[],[]) "mo",Space,Str "ra",Space,RawInline (Format "html") "tg",SoftBreak,Str "i)",Space,Strong [Str "bold"],Space,Emph [Str "ital"],Space,Span ("",["underline"],[]) [Str "undr"],Space,Strikeout [Str "strk"],Space,Code ("",[],[]) "mono",Space,Str "raw",Space,RawInline (Format "html") "tggd",SoftBreak,Str "i)",Space,Strong [Str "bo",Space,Str "ld"],Space,Emph [Str "it",Space,Str "al"],Space,Span ("",["underline"],[]) [Str "un",Space,Str "dr"],Space,Strikeout [Str "st",Space,Str "rk"],Space,Code ("",[],[]) "mo no",Space,Str "r",Space,Str "aw",Space,RawInline (Format "html") "tg gd",SoftBreak,Str "i)",Space,Strong [Str "bo",Space,Str "*",Space,Str "ld"],Space,Emph [Str "it",Space,Str "/",Space,Str "al"],Space,Span ("",["underline"],[]) [Str "un",Space,Str "_",Space,Str "dr"],Space,Strikeout [Str "st",Space,Str "-",Space,Str "rk"],Space,Code ("",[],[]) "mo ` no",Space,Str "r",Space,Str "\"",Space,Str "aw",Space,RawInline (Format "html") "tg ' gd",SoftBreak,Str "i)",Space,Strong [Str "bo",Space,Str "**ld"],Space,Emph [Str "it",Space,Str "//al"],Space,Span ("",["underline"],[]) [Str "un",Space,Str "__dr"],Space,Strikeout [Str "st",Space,Str "--rk"],Space,Code ("",[],[]) "mo ``no",Space,Str "r",Space,Str "\"\"aw",Space,RawInline (Format "html") "tg ''gd",SoftBreak,Str "i)",Space,Strong [Str "bo",Space,Str "**",Space,Str "ld"],Space,Emph [Str "it",Space,Str "//",Space,Str "al"],Space,Span ("",["underline"],[]) [Str "un",Space,Str "__",Space,Str "dr"],Space,Strikeout [Str "st",Space,Str "--",Space,Str "rk"],Space,Code ("",[],[]) "mo `` no",Space,Str "r",Space,Str "\"\"",Space,Str "aw",Space,RawInline (Format "html") "tg '' gd",SoftBreak,Str "i)",Space,Strong [Str "**bold**"],Space,Emph [Str "//ital//"],Space,Span ("",["underline"],[]) [Str "__undr__"],Space,Strikeout [Str "--strk--"],Space,Code ("",[],[]) "``mono``",Space,Str "\"\"raw\"\"",Space,RawInline (Format "html") "''tggd''",SoftBreak,Str "i)",Space,Strong [Str "*bold*"],Space,Emph [Str "/ital/"],Space,Span ("",["underline"],[]) [Str "_undr_"],Space,Strikeout [Str "-strk-"],Space,Code ("",[],[]) "`mono`",Space,Str "\"raw\"",Space,RawInline (Format "html") "'tggd'"]
-,Para [Str "i)",Space,Strong [Str "*"],Space,Emph [Str "/"],Space,Span ("",["underline"],[]) [Str "_"],Space,Strikeout [Str "-"],Space,Code ("",[],[]) "`",Space,Str "\"",Space,RawInline (Format "html") "'",SoftBreak,Str "i)",Space,Strong [Str "**"],Space,Emph [Str "//"],Space,Span ("",["underline"],[]) [Str "__"],Space,Strikeout [Str "--"],Space,Code ("",[],[]) "``",Space,Str "\"\"",Space,RawInline (Format "html") "''",SoftBreak,Str "i)",Space,Strong [Str "***"],Space,Emph [Str "///"],Space,Span ("",["underline"],[]) [Str "___"],Space,Strikeout [Str "---"],Space,Code ("",[],[]) "```",Space,Str "\"\"\"",Space,RawInline (Format "html") "'''",SoftBreak,Str "i)",Space,Strong [Str "****"],Space,Emph [Str "////"],Space,Span ("",["underline"],[]) [Str "____"],Space,Strikeout [Str "----"],Space,Code ("",[],[]) "````",Space,Str "\"\"\"\"",Space,RawInline (Format "html") "''''",SoftBreak,Str "i)",Space,Strong [Str "*****"],Space,Emph [Str "/////"],Space,Span ("",["underline"],[]) [Str "_____"],Space,Strikeout [Str "-----"],Space,Code ("",[],[]) "`````",Space,Str "\"\"\"\"\"",Space,RawInline (Format "html") "'''''",SoftBreak,Str "i)",Space,Strong [Str "******"],Space,Emph [Str "//////"],Space,Span ("",["underline"],[]) [Str "______"],Space,Strikeout [Str "------"],Space,Code ("",[],[]) "``````",Space,Str "\"\"\"\"\"\"",Space,RawInline (Format "html") "''''''"]
-,Para [Str "i)",Space,Str "****",Space,Str "////",Space,Str "____",Space,Str "----",Space,Str "````",Space,Str "\"\"\"\"",Space,Str "''''",SoftBreak,Str "i)",Space,Str "**",Space,Str "**",Space,Str "//",Space,Str "//",Space,Str "__",Space,Str "__",Space,Str "--",Space,Str "--",Space,Str "``",Space,Str "``",Space,Str "\"\"",Space,Str "\"\"",Space,Str "''",Space,Str "''"]
-,Para [Str "i)",Space,Str "**",Space,Str "bold**",Space,Str "//",Space,Str "ital//",Space,Str "__",Space,Str "undr__",Space,Str "--",Space,Str "strk--",Space,Str "``",Space,Str "mono``",Space,Str "\"\"",Space,Str "raw\"\"",Space,Str "''",Space,Str "tggd''",SoftBreak,Str "i)",Space,Str "**bold",Space,Str "**",Space,Str "//ital",Space,Str "//",Space,Str "__undr",Space,Str "__",Space,Str "--strk",Space,Str "--",Space,Str "``mono",Space,Str "``",Space,Str "\"\"raw",Space,Str "\"\"",Space,Str "''tggd",Space,Str "''",SoftBreak,Str "i)",Space,Str "**",Space,Str "bold",Space,Str "**",Space,Str "//",Space,Str "ital",Space,Str "//",Space,Str "__",Space,Str "undr",Space,Str "__",Space,Str "--",Space,Str "strk",Space,Str "--",Space,Str "``",Space,Str "mono",Space,Str "``",Space,Str "\"\"",Space,Str "raw",Space,Str "\"\"",Space,Str "''",Space,Str "tggd",Space,Str "''"]
-,Header 1 ("link",[],[]) [Str "Link"]
-,Para [Link ("",[],[]) [Str "mailto:user@domain.com"] ("user@domain.com",""),SoftBreak,Link ("",[],[]) [Str "mailto:user@domain.com"] ("user@domain.com",""),Str ".",SoftBreak,Link ("",[],[]) [Str "mailto:user@domain.com"] ("user@domain.com",""),Str ".",Space,Str "any",Space,Str "text.",SoftBreak,Str "any",Space,Str "text:",Space,Link ("",[],[]) [Str "mailto:user@domain.com"] ("user@domain.com",""),Str ".",Space,Str "any",Space,Str "text.",SoftBreak,Link ("",[],[]) [Str "label"] ("user@domain.com",""),SoftBreak,Link ("",[],[]) [Str "mailto:user@domain.com?subject=bla"] ("user@domain.com?subject=bla",""),SoftBreak,Link ("",[],[]) [Str "mailto:user@domain.com?subject=bla"] ("user@domain.com?subject=bla",""),Str ".",SoftBreak,Link ("",[],[]) [Str "mailto:user@domain.com?subject=bla"] ("user@domain.com?subject=bla",""),Str ",",SoftBreak,Link ("",[],[]) [Str "mailto:user@domain.com?subject=bla&cc=otheruser@domain.com"] ("user@domain.com?subject=bla&cc=otheruser@domain.com",""),SoftBreak,Link ("",[],[]) [Str "mailto:user@domain.com?subject=bla&cc=otheruser@domain.com"] ("user@domain.com?subject=bla&cc=otheruser@domain.com",""),Str ".",SoftBreak,Link ("",[],[]) [Str "mailto:user@domain.com?subject=bla&cc=otheruser@domain.com"] ("user@domain.com?subject=bla&cc=otheruser@domain.com",""),Str ",",SoftBreak,Link ("",[],[]) [Str "label"] ("user@domain.com?subject=bla&cc=otheruser@domain.com",""),Str ".",SoftBreak,Link ("",[],[]) [Str "label"] ("user@domain.com?subject=bla&cc=otheruser@domain.com.",""),Str ".",SoftBreak,Link ("",[],[]) [Str "http://www.domain.com"] ("http://www.domain.com",""),SoftBreak,Link ("",[],[]) [Str "http://www.domain.com/dir/"] ("http://www.domain.com/dir/",""),SoftBreak,Link ("",[],[]) [Str "http://www.domain.com/dir///"] ("http://www.domain.com/dir///",""),SoftBreak,Link ("",[],[]) [Str "http://www.domain.com."] ("http://www.domain.com.",""),SoftBreak,Link ("",[],[]) [Str "http://www.domain.com,"] ("http://www.domain.com,",""),SoftBreak,Link ("",[],[]) [Str "http://www.domain.com."] ("http://www.domain.com.",""),Space,Str "any",Space,Str "text.",SoftBreak,Link ("",[],[]) [Str "http://www.domain.com,"] ("http://www.domain.com,",""),Space,Str "any",Space,Str "text.",SoftBreak,Link ("",[],[]) [Str "http://www.domain.com/dir/."] ("http://www.domain.com/dir/.",""),Space,Str "any",Space,Str "text.",SoftBreak,Str "any",Space,Str "text:",Space,Link ("",[],[]) [Str "http://www.domain.com."] ("http://www.domain.com.",""),Space,Str "any",Space,Str "text.",SoftBreak,Str "any",Space,Str "text:",Space,Link ("",[],[]) [Str "http://www.domain.com/dir/."] ("http://www.domain.com/dir/.",""),Space,Str "any",Space,Str "text.",SoftBreak,Str "any",Space,Str "text:",Space,Link ("",[],[]) [Str "http://www.domain.com/dir/index.html."] ("http://www.domain.com/dir/index.html.",""),Space,Str "any",Space,Str "text.",SoftBreak,Str "any",Space,Str "text:",Space,Link ("",[],[]) [Str "http://www.domain.com/dir/index.html,"] ("http://www.domain.com/dir/index.html,",""),Space,Str "any",Space,Str "text.",SoftBreak,Link ("",[],[]) [Str "http://www.domain.com/dir/#anchor"] ("http://www.domain.com/dir/#anchor",""),SoftBreak,Link ("",[],[]) [Str "http://www.domain.com/dir/index.html#anchor"] ("http://www.domain.com/dir/index.html#anchor",""),SoftBreak,Link ("",[],[]) [Str "http://www.domain.com/dir/index.html#anchor."] ("http://www.domain.com/dir/index.html#anchor.",""),SoftBreak,Link ("",[],[]) [Str "http://www.domain.com/dir/#anchor."] ("http://www.domain.com/dir/#anchor.",""),Space,Str "any",Space,Str "text.",SoftBreak,Link ("",[],[]) [Str "http://www.domain.com/dir/index.html#anchor."] ("http://www.domain.com/dir/index.html#anchor.",""),Space,Str "any",Space,Str "text.",SoftBreak,Str "any",Space,Str "text:",Space,Link ("",[],[]) [Str "http://www.domain.com/dir/#anchor."] ("http://www.domain.com/dir/#anchor.",""),Space,Str "any",Space,Str "text.",SoftBreak,Str "any",Space,Str "text:",Space,Link ("",[],[]) [Str "http://www.domain.com/dir/index.html#anchor."] ("http://www.domain.com/dir/index.html#anchor.",""),Space,Str "any",Space,Str "text.",SoftBreak,Link ("",[],[]) [Str "http://domain.com?a=a@a.a&b=a+b+c."] ("http://domain.com?a=a@a.a&b=a+b+c.",""),SoftBreak,Link ("",[],[]) [Str "http://domain.com?a=a@a.a&b=a+b+c,"] ("http://domain.com?a=a@a.a&b=a+b+c,",""),SoftBreak,Link ("",[],[]) [Str "http://domain.com/bla.cgi?a=a@a.a&b=a+b+c."] ("http://domain.com/bla.cgi?a=a@a.a&b=a+b+c.",""),SoftBreak,Link ("",[],[]) [Str "http://domain.com/bla.cgi?a=a@a.a&b=a+b+c@."] ("http://domain.com/bla.cgi?a=a@a.a&b=a+b+c@.",""),SoftBreak,Link ("",[],[]) [Str "http://domain.com?a=a@a.a&b=a+b+c.#anchor"] ("http://domain.com?a=a@a.a&b=a+b+c.#anchor",""),SoftBreak,Link ("",[],[]) [Str "http://domain.com/bla.cgi?a=a@a.a&b=a+b+c.#anchor"] ("http://domain.com/bla.cgi?a=a@a.a&b=a+b+c.#anchor",""),SoftBreak,Link ("",[],[]) [Str "http://domain.com/bla.cgi?a=a@a.a&b=a+b+c@.#anchor"] ("http://domain.com/bla.cgi?a=a@a.a&b=a+b+c@.#anchor",""),SoftBreak,Link ("",[],[]) [Str "http://user:password@domain.com/bla.html."] ("http://user:password@domain.com/bla.html.",""),SoftBreak,Link ("",[],[]) [Str "http://user:password@domain.com/dir/."] ("http://user:password@domain.com/dir/.",""),SoftBreak,Link ("",[],[]) [Str "http://user:password@domain.com."] ("http://user:password@domain.com.",""),SoftBreak,Link ("",[],[]) [Str "http://user:@domain.com."] ("http://user:@domain.com.",""),SoftBreak,Link ("",[],[]) [Str "http://user@domain.com."] ("http://user@domain.com.",""),SoftBreak,Link ("",[],[]) [Str "http://user:password@domain.com/bla.cgi?a=a@a.a&b=a+b+c.#anchor"] ("http://user:password@domain.com/bla.cgi?a=a@a.a&b=a+b+c.#anchor",""),SoftBreak,Link ("",[],[]) [Str "http://user:password@domain.com/bla.cgi?a=a@a.a&b=a+b+c@#anchor"] ("http://user:password@domain.com/bla.cgi?a=a@a.a&b=a+b+c@#anchor",""),SoftBreak,Link ("",[],[]) [Str "label"] ("www.domain.com",""),SoftBreak,Str "[",Space,Str "label",Space,Link ("",[],[]) [Str "www.domain.com"] ("www.domain.com",""),Str "]",SoftBreak,Link ("",[],[]) [Str "label",Space] ("www.domain.com",""),SoftBreak,Link ("",[],[]) [Str "anchor",Space] ("http://www.domain.com/dir/index.html#anchor.",""),SoftBreak,Link ("",[],[]) [Str "login",Space] ("http://user:password@domain.com/bla.html",""),SoftBreak,Link ("",[],[]) [Str "form",Space] ("http://www.domain.com/bla.cgi?a=a@a.a&b=a+b+c.",""),SoftBreak,Link ("",[],[]) [Str "form",Space,Str "&",Space,Str "anchor"] ("http://www.domain.com/bla.cgi?a=a@a.a&b=a+b+c.#anchor",""),SoftBreak,Link ("",[],[]) [Str "login",Space,Str "&",Space,Str "form",Space] ("http://user:password@domain.com/bla.cgi?a=a@a.a&b=a+b+c.",""),SoftBreak,Link ("",[],[]) [Str "local",Space,Str "link",Space,Str "up",Space] ("..",""),SoftBreak,Link ("",[],[]) [Str "local",Space,Str "link",Space,Str "file",Space] ("bla.html",""),SoftBreak,Link ("",[],[]) [Str "local",Space,Str "link",Space,Str "anchor",Space] ("#anchor",""),SoftBreak,Link ("",[],[]) [Str "local",Space,Str "link",Space,Str "file/anchor"] ("bla.html#anchor",""),SoftBreak,Link ("",[],[]) [Str "local",Space,Str "link",Space,Str "file/anchor"] ("bla.html#anchor.",""),SoftBreak,Link ("",[],[]) [Str "local",Space,Str "link",Space,Str "img",Space] ("abc.gif",""),SoftBreak,Link ("",[],[]) [Str "www.fake.com"] ("www.domain.com",""),SoftBreak,Link ("",[],[]) [Str "http://domain.com:8080/~user/_st-r@a=n$g,e/index%20new.htm"] ("http://domain.com:8080/~user/_st-r@a=n$g,e/index%20new.htm",""),SoftBreak,Link ("",[],[]) [Str "http://domain.com:8080/~user/_st-r@a=n$g,e/index%20new.htm?a=/%22&b=+.@*_-"] ("http://domain.com:8080/~user/_st-r@a=n$g,e/index%20new.htm?a=/%22&b=+.@*_-",""),SoftBreak,Link ("",[],[]) [Str "http://domain.com:8080/~user/_st-r@a=n$g,e/index%20new.htm?a=/%22&b=+.@*_-#anchor_"] ("http://domain.com:8080/~user/_st-r@a=n$g,e/index%20new.htm?a=/%22&b=+.@*_-#anchor_",""),Str "-1%.",SoftBreak,Link ("",[],[]) [Str "http://foo._user-9:pass!#$%&*()+word@domain.com:8080/~user/_st-r@a=n$g,e/index%20new.htm?a=/%22&b=+.@*_-#anchor_"] ("http://foo._user-9:pass!#$%&*()+word@domain.com:8080/~user/_st-r@a=n$g,e/index%20new.htm?a=/%22&b=+.@*_-#anchor_",""),Str "-1%.",SoftBreak,Link ("",[],[]) [Str "http://L1.com"] ("http://L1.com",""),Space,Str "!",Space,Link ("",[],[]) [Str "mailto:L2@www.com"] ("L2@www.com",""),Space,Str "!",Space,Link ("",[],[]) [Str "L3"] ("www.com",""),Space,Str "!",Space,Link ("",[],[]) [Str "L4"] ("w@ww.com",""),Space,Str "!",Space,Link ("",[],[]) [Str "www.L5.com"] ("www.L5.com",""),SoftBreak,Link ("",[],[]) [Str "www.domain.com"] ("www.domain.com",""),SoftBreak,Link ("",[],[]) [Str "www2.domain.com"] ("www2.domain.com",""),SoftBreak,Link ("",[],[]) [Str "ftp.domain.com"] ("ftp.domain.com",""),SoftBreak,Link ("",[],[]) [Str "WWW.DOMAIN.COM"] ("WWW.DOMAIN.COM",""),SoftBreak,Link ("",[],[]) [Str "FTP.DOMAIN.COM"] ("FTP.DOMAIN.COM",""),SoftBreak,Link ("",[],[]) [Str "label"] ("www.domain.com",""),SoftBreak,Link ("",[],[]) [Str "label"] ("ftp.domain.com",""),SoftBreak,Link ("",[],[]) [Str "label"] ("WWW.DOMAIN.COM",""),SoftBreak,Link ("",[],[]) [Str "label"] ("FTP.DOMAIN.COM",""),SoftBreak,Str "[label",Space,Link ("",[],[]) [Str "www.domain.com"] ("www.domain.com",""),Space,Str "]",SoftBreak,Str "[label]",Space,Link ("",[],[]) [Str "www.domain.com"] ("www.domain.com",""),Str "]"]
-,Header 1 ("image",[],[]) [Str "Image"]
-,Para [Image ("",[],[]) [] ("img.png","")]
-,Para [Link ("",[],[]) [Image ("",[],[]) [] ("img.png","")] ("http://txt2tags.org","")]
-,Para [Image ("",[],[]) [] ("img.png",""),Space,Str "Image",Space,Str "at",Space,Str "the",Space,Str "line",Space,Str "beginning."]
-,Para [Str "Image",Space,Str "in",Space,Str "the",Space,Str "middle",Space,Image ("",[],[]) [] ("img.png",""),Space,Str "of",Space,Str "the",Space,Str "line."]
-,Para [Str "Image",Space,Str "at",Space,Str "the",Space,Str "line",Space,Str "end.",Space,Image ("",[],[]) [] ("img.png","")]
-,Para [Image ("",[],[]) [] ("img.png",""),SoftBreak,Image ("",[],[]) [] ("img.png",""),SoftBreak,Image ("",[],[]) [] ("img.png","")]
-,Para [Image ("",[],[]) [] ("img.png",""),Image ("",[],[]) [] ("img.png","")]
-,Para [Str "Images",Space,Image ("",[],[]) [] ("img.png",""),Space,Str "mixed",Space,Image ("",[],[]) [] ("img.png",""),Space,Str "with",Space,Image ("",[],[]) [] ("img.png",""),Space,Str "text."]
-,Para [Str "Images",Space,Str "glued",Space,Str "together:",Space,Image ("",[],[]) [] ("img.png",""),Image ("",[],[]) [] ("img.png",""),Image ("",[],[]) [] ("img.png",""),Str "."]
-,Para [Str "[img.png",Space,Str "]"]
-,Para [Str "[",Space,Str "img.png]"]
-,Para [Str "[",Space,Str "img.png",Space,Str "]"]
-,Header 1 ("numtitle",[],[]) [Str "Numbered",Space,Str "Title"]
-,Header 1 ("",[],[]) [Str "Title",Space,Str "Level",Space,Str "1"]
-,Header 2 ("",[],[]) [Str "Title",Space,Str "Level",Space,Str "2"]
-,Header 3 ("",[],[]) [Str "Title",Space,Str "Level",Space,Str "3"]
-,Header 4 ("",[],[]) [Str "Title",Space,Str "Level",Space,Str "4"]
-,Header 5 ("",[],[]) [Str "Title",Space,Str "Level",Space,Str "5"]
-,Header 1 ("lab_el-1",[],[]) [Str "Title",Space,Str "Level",Space,Str "1"]
-,Header 2 ("lab_el-2",[],[]) [Str "Title",Space,Str "Level",Space,Str "2"]
-,Header 3 ("lab_el-3",[],[]) [Str "Title",Space,Str "Level",Space,Str "3"]
-,Header 4 ("lab_el-4",[],[]) [Str "Title",Space,Str "Level",Space,Str "4"]
-,Header 5 ("lab_el-5",[],[]) [Str "Title",Space,Str "Level",Space,Str "5"]
-,Header 3 ("",[],[]) [Str "Title",Space,Str "Level",Space,Str "3"]
-,Header 3 ("",[],[]) [Str "Title",Space,Str "Level",Space,Str "3"]
-,Header 3 ("",[],[]) [Str "Title",Space,Str "Level",Space,Str "3"]
-,Header 3 ("",[],[]) [Str "Title",Space,Str "Level",Space,Str "3"]
-,Header 3 ("",[],[]) [Str "Title",Space,Str "Level",Space,Str "3"]
-,Header 3 ("lab_el-9",[],[]) [Str "Title",Space,Str "Level",Space,Str "3"]
-,Para [Str "+Not",Space,Str "Title"]
-,Para [Str "++Not",Space,Str "Title+"]
-,Para [Str "+++Not",Space,Str "Title++++",SoftBreak,Str "++++++Not",Space,Str "Title",Space,Str "6++++++"]
-,Para [Str "+++++++Not",Space,Str "Title",Space,Str "7+++++++",SoftBreak,Str "+Not",Space,Str "Title+",Space,Str "[label1]",SoftBreak,Str "+Not",Space,Str "Title+[",Space,Str "label",Space,Str "]",SoftBreak,Str "+Not",Space,Str "Title+[la/bel]"]
-,Header 1 ("title",[],[]) [Str "Title"]
-,Header 1 ("",[],[]) [Str "Title",Space,Str "Level",Space,Str "1"]
-,Header 2 ("",[],[]) [Str "Title",Space,Str "Level",Space,Str "2"]
-,Header 3 ("",[],[]) [Str "Title",Space,Str "Level",Space,Str "3"]
-,Header 4 ("",[],[]) [Str "Title",Space,Str "Level",Space,Str "4"]
-,Header 5 ("",[],[]) [Str "Title",Space,Str "Level",Space,Str "5"]
-,Header 1 ("lab_el-1",[],[]) [Str "Title",Space,Str "Level",Space,Str "1"]
-,Header 2 ("lab_el-2",[],[]) [Str "Title",Space,Str "Level",Space,Str "2"]
-,Header 3 ("lab_el-3",[],[]) [Str "Title",Space,Str "Level",Space,Str "3"]
-,Header 4 ("lab_el-4",[],[]) [Str "Title",Space,Str "Level",Space,Str "4"]
-,Header 5 ("lab_el-5",[],[]) [Str "Title",Space,Str "Level",Space,Str "5"]
-,Header 3 ("",[],[]) [Str "Title",Space,Str "Level",Space,Str "3"]
-,Header 3 ("",[],[]) [Str "Title",Space,Str "Level",Space,Str "3"]
-,Header 3 ("",[],[]) [Str "Title",Space,Str "Level",Space,Str "3"]
-,Header 3 ("",[],[]) [Str "Title",Space,Str "Level",Space,Str "3"]
-,Header 3 ("",[],[]) [Str "Title",Space,Str "Level",Space,Str "3"]
-,Header 3 ("lab_el-9",[],[]) [Str "Title",Space,Str "Level",Space,Str "3"]
-,Para [Str "=Not",Space,Str "Title"]
-,Para [Str "==Not",Space,Str "Title="]
-,Para [Str "===Not",Space,Str "Title====",SoftBreak,Str "======Not",Space,Str "Title",Space,Str "6======"]
-,Para [Str "=======Not",Space,Str "Title",Space,Str "7=======",SoftBreak,Str "=Not",Space,Str "Title=",Space,Str "[label1]",SoftBreak,Str "=Not",Space,Str "Title=[",Space,Str "label",Space,Str "]",SoftBreak,Str "=Not",Space,Str "Title=[la/bel]"]
-,Header 1 ("quote",[],[]) [Str "Quote"]
-,BlockQuote
- [Para [Str "To",Space,Str "quote",Space,Str "a",Space,Str "paragraph,",Space,Str "just",Space,Str "prefix",Space,Str "it",Space,Str "by",Space,Str "a",Space,Str "TAB",SoftBreak,Str "character.",Space,Str "All",Space,Str "the",Space,Str "lines",Space,Str "of",Space,Str "the",Space,Str "paragraph",Space,Str "must",SoftBreak,Str "begin",Space,Str "with",Space,Str "a",Space,Str "TAB."]]
-,Para [Str "Any",Space,Str "non-tabbed",Space,Str "line",Space,Str "closes",Space,Str "the",Space,Str "quote",Space,Str "block."]
-,BlockQuote
- [Para [Str "The",Space,Str "number",Space,Str "of",Space,Str "leading",Space,Str "TABs",Space,Str "identifies",Space,Str "the",Space,Str "quote",SoftBreak,Str "block",Space,Str "depth.",Space,Str "This",Space,Str "is",Space,Str "quote",Space,Str "level",Space,Str "1."]
- ,BlockQuote
-  [Para [Str "With",Space,Str "two",Space,Str "TABs,",Space,Str "we",Space,Str "are",Space,Str "on",Space,Str "the",Space,Str "quote",SoftBreak,Str "level",Space,Str "2."]
-  ,BlockQuote
-   [Para [Str "The",Space,Str "more",Space,Str "TABs,",Space,Str "more",Space,Str "deep",Space,Str "is",SoftBreak,Str "the",Space,Str "quote",Space,Str "level."]
-   ,BlockQuote
-    [Para [Str "There",Space,Str "isn't",Space,Str "a",Space,Str "limit."]]]]]
-,BlockQuote
- [BlockQuote
-  [BlockQuote
-   [BlockQuote
-    [Para [Str "This",Space,Str "quote",Space,Str "starts",Space,Str "at",SoftBreak,Str "level",Space,Str "4."]]
-   ,Para [Str "Then",Space,Str "its",Space,Str "depth",Space,Str "is",Space,Str "decreased."]]
-  ,Para [Str "Counting",Space,Str "down,",Space,Str "one",Space,Str "by",Space,Str "one."]]
- ,Para [Str "Until",Space,Str "the",Space,Str "level",Space,Str "1."]]
-,BlockQuote
- [BlockQuote
-  [BlockQuote
-   [Para [Str "Unlike",Space,Str "lists,",Space,Str "any",Space,Str "quote",Space,Str "block",Space,Str "is",SoftBreak,Str "independent,",Space,Str "not",Space,Str "part",Space,Str "of",Space,Str "a",Space,Str "tree."]]]
- ,Para [Str "The",Space,Str "TAB",Space,Str "count",Space,Str "don't",Space,Str "need",Space,Str "to",Space,Str "be",Space,Str "incremental",SoftBreak,Str "by",Space,Str "one."]
- ,BlockQuote
-  [BlockQuote
-   [BlockQuote
-    [Para [Str "The",Space,Str "nesting",Space,Str "don't",Space,Str "need",SoftBreak,Str "to",Space,Str "follow",Space,Str "any",Space,Str "rule."]]]
-  ,Para [Str "Quotes",Space,Str "can",Space,Str "be",Space,Str "opened",Space,Str "and",Space,Str "closed",SoftBreak,Str "in",Space,Str "any",Space,Str "way."]
-  ,BlockQuote
-   [BlockQuote
-    [BlockQuote
-     [Para [Str "You",Space,Str "choose."]]]]]]
-,BlockQuote
- [Para [Str "Some",Space,Str "targets",Space,Str "(as",Space,Str "sgml)",Space,Str "don't",Space,Str "support",Space,Str "the",SoftBreak,Str "nesting",Space,Str "of",Space,Str "quotes.",Space,Str "There",Space,Str "is",Space,Str "only",Space,Str "one",Space,Str "quote",SoftBreak,Str "level."]
- ,BlockQuote
-  [Para [Str "In",Space,Str "this",Space,Str "case,",Space,Str "no",Space,Str "matter",Space,Str "how",Space,Str "much",SoftBreak,Str "TABs",Space,Str "are",Space,Str "used",Space,Str "to",Space,Str "define",Space,Str "the",Space,Str "quote",SoftBreak,Str "block,",Space,Str "it",Space,Str "always",Space,Str "will",Space,Str "be",Space,Str "level",Space,Str "1."]]]
-,BlockQuote
- [Para [Str "Spaces",Space,Str "AFTER",Space,Str "the",Space,Str "TAB",Space,Str "character",Space,Str "are",Space,Str "allowed.",SoftBreak,Str "But",Space,Str "be",Space,Str "careful,",Space,Str "it",Space,Str "can",Space,Str "be",Space,Str "confusing."]]
-,Para [Str "Spaces",Space,Str "BEFORE",Space,Str "the",Space,Str "TAB",Space,Str "character",SoftBreak,Str "invalidate",Space,Str "the",Space,Str "mark.",Space,Str "It's",Space,Str "not",Space,Str "quote."]
-,BlockQuote
- [Para [Str "Paragraph",Space,Str "breaks",Space,Str "inside",Space,Str "a",Space,Str "quote",Space,Str "aren't",SoftBreak,Str "possible."]
- ,Para [Str "This",Space,Str "sample",Space,Str "are",Space,Str "two",Space,Str "separated",Space,Str "quoted",SoftBreak,Str "paragraphs,",Space,Str "not",Space,Str "a",Space,Str "quote",Space,Str "block",Space,Str "with",SoftBreak,Str "two",Space,Str "paragraphs",Space,Str "inside."]]
-,BlockQuote
- [Para [Str "The",Space,Str "end",Space,Str "of",Space,Str "the",Space,Str "file",Space,Str "(EOF)",Space,Str "closes",Space,Str "the",SoftBreak,Str "currently",Space,Str "open",Space,Str "quote",Space,Str "block."]]
-,Header 1 ("raw",[],[]) [Str "Raw"]
-,Para [Str "A raw line.\n"]
-,Para [Str "  Another raw line, with leading spaces.\n"]
-,Para [Str "A raw area delimited\n       by lines with marks.\n"]
-,Para [Str "Trailing spaces and TABs after the area marks\nare allowed, but not encouraged nor documented.\n"]
-,Para [Str "\"\"\"Not",Space,Str "a",Space,Str "raw",Space,Str "line,",Space,Str "need",Space,Str "one",Space,Str "space",Space,Str "after",Space,Str "mark."]
-,Para [Str "\"\"\"",SoftBreak,Str "Not",Space,Str "a",Space,Str "raw",Space,Str "area.",SoftBreak,Str "The",Space,Str "marks",Space,Str "must",Space,Str "be",Space,Str "at",Space,Str "the",Space,Str "line",Space,Str "beginning,",SoftBreak,Str "no",Space,Str "leading",Space,Str "spaces.",SoftBreak,Str "\"\"\""]
-,Para [Str "The end of the file (EOF) closes\nthe currently open raw area.\n"]
-,Header 1 ("verbatim",[],[]) [Str "Verbatim"]
-,CodeBlock ("",[],[]) "A verbatim line.\n"
-,CodeBlock ("",[],[]) "  Another verbatim line, with leading spaces.\n"
-,CodeBlock ("",[],[]) "A verbatim area delimited\n       by lines with marks.\n"
-,CodeBlock ("",[],[]) "Trailing spaces and TABs after the area marks\nare allowed, but not encouraged nor documented.\n"
-,Para [Str "```Not",Space,Str "a",Space,Str "verbatim",Space,Str "line,",Space,Str "need",Space,Str "one",Space,Str "space",Space,Str "after",Space,Str "mark."]
-,Para [Str "```",SoftBreak,Str "Not",Space,Str "a",Space,Str "verbatim",Space,Str "area.",SoftBreak,Str "The",Space,Str "marks",Space,Str "must",Space,Str "be",Space,Str "at",Space,Str "the",Space,Str "line",Space,Str "beginning,",SoftBreak,Str "no",Space,Str "leading",Space,Str "spaces.",SoftBreak,Str "```"]
-,CodeBlock ("",[],[]) "The end of the file (EOF) closes\nthe currently open verbatim area.\n"
-,Header 1 ("deflist",[],[]) [Str "Definition",Space,Str "List"]
-,DefinitionList
- [([Str "Definition",Space,Str "list"],
-   [[Plain [Str "A",Space,Str "list",Space,Str "with",Space,Str "terms"]]])
- ,([Str "Start",Space,Str "term",Space,Str "with",Space,Str "colon"],
-   [[Plain [Str "And",Space,Str "its",Space,Str "definition",Space,Str "follows"]]])]
-,Header 1 ("numlist",[],[]) [Str "Numbered",Space,Str "List"]
-,Para [Str "See",Space,Link ("",[],[]) [Str "List"] ("#list",""),Str ",",Space,Str "the",Space,Str "same",Space,Str "rules",Space,Str "apply."]
-,Header 1 ("list",[],[]) [Str "List"]
-,BulletList
- [[Plain [Str "Use",Space,Str "the",Space,Str "hyphen",Space,Str "to",Space,Str "prefix",Space,Str "list",Space,Str "items."]]
- ,[Plain [Str "There",Space,Str "must",Space,Str "be",Space,Str "one",Space,Str "space",Space,Str "after",Space,Str "the",Space,Str "hyphen."]]
- ,[Plain [Str "The",Space,Str "list",Space,Str "is",Space,Str "closed",Space,Str "by",Space,Str "two",Space,Str "consecutive",Space,Str "blank",Space,Str "lines."]]]
-,BulletList
- [[Plain [Str "The",Space,Str "list",Space,Str "can",Space,Str "be",Space,Str "indented",Space,Str "on",Space,Str "the",Space,Str "source",Space,Str "document."]]
- ,[Plain [Str "You",Space,Str "can",Space,Str "use",Space,Str "any",Space,Str "number",Space,Str "of",Space,Str "spaces."]]
- ,[Plain [Str "The",Space,Str "result",Space,Str "will",Space,Str "be",Space,Str "the",Space,Str "same."]]]
-,BulletList
- [[Para [Str "Let",Space,Str "one",Space,Str "blank",Space,Str "line",Space,Str "between",Space,Str "the",Space,Str "list",Space,Str "items."]]
- ,[Para [Str "It",Space,Str "will",Space,Str "be",Space,Str "maintained",Space,Str "on",Space,Str "the",Space,Str "conversion."]]
- ,[Para [Str "Some",Space,Str "targets",Space,Str "don't",Space,Str "support",Space,Str "this",Space,Str "behavior."]]
- ,[Para [Str "This",Space,Str "one",Space,Str "was",Space,Str "separated",Space,Str "by",Space,Str "a",Space,Str "line",Space,Str "with",Space,Str "blanks.",SoftBreak,Str "You",Space,Str "can",Space,Str "also",Space,Str "put",Space,Str "a",Space,Str "blank",Space,Str "line",Space,Str "inside"]
-  ,Para [Str "the",Space,Str "item",Space,Str "contents",Space,Str "and",Space,Str "it",Space,Str "will",Space,Str "be",Space,Str "preserved."]]]
-,Para [Str "-This",Space,Str "is",Space,Str "not",Space,Str "a",Space,Str "list",Space,Str "(no",Space,Str "space)"]
-,Para [Str "-",Space,Str "This",Space,Str "is",Space,Str "not",Space,Str "a",Space,Str "list",Space,Str "(more",Space,Str "than",Space,Str "one",Space,Str "space)"]
-,Para [Str "-",Space,Str "This",Space,Str "is",Space,Str "not",Space,Str "a",Space,Str "list",Space,Str "(a",Space,Str "TAB",Space,Str "instead",Space,Str "the",Space,Str "space)"]
-,BulletList
- [[BulletList
-   [[Plain [Str "This",Space,Str "is",Space,Str "a",Space,Str "list"]]]]
- ,[OrderedList (1,DefaultStyle,DefaultDelim)
-   [[Plain [Str "This",Space,Str "is",Space,Str "a",Space,Str "list"]]]]
- ,[DefinitionList
-   [([Str "This",Space,Str "is",Space,Str "a",Space,Str "list"],
-     [[]])]]]
-,BulletList
- [[Plain [Str "This",Space,Str "is",Space,Str "the",Space,Str "\"mother\"",Space,Str "list",Space,Str "first",Space,Str "item."]]
- ,[Plain [Str "Here",Space,Str "is",Space,Str "the",Space,Str "second,",Space,Str "but",Space,Str "inside",Space,Str "this",Space,Str "item,"]
-  ,BulletList
-   [[Plain [Str "there",Space,Str "is",Space,Str "a",Space,Str "sublist,",Space,Str "with",Space,Str "its",Space,Str "own",Space,Str "items."]]
-   ,[Plain [Str "Note",Space,Str "that",Space,Str "the",Space,Str "items",Space,Str "of",Space,Str "the",Space,Str "same",Space,Str "sublist"]]
-   ,[Plain [Str "must",Space,Str "have",Space,Str "the",Space,Str "same",Space,Str "indentation."]
-    ,BulletList
-     [[Plain [Str "And",Space,Str "this",Space,Str "can",Space,Str "go",Space,Str "on,",Space,Str "opening",Space,Str "sublists."]
-      ,BulletList
-       [[Plain [Str "Just",Space,Str "add",Space,Str "leading",Space,Str "spaces",Space,Str "before",Space,Str "the"]]
-       ,[Plain [Str "hyphen",Space,Str "and",Space,Str "sublists",Space,Str "will",Space,Str "be",Space,Str "opened."]]
-       ,[Plain [Str "The",Space,Str "two",Space,Str "blank",Space,Str "lines",Space,Str "closes",Space,Str "them",Space,Str "all."]]]]]]]]]
-,BulletList
- [[Plain [Str "When",Space,Str "nesting",Space,Str "lists,",Space,Str "the",Space,Str "additional",Space,Str "spaces",Space,Str "are",Space,Str "free."]]
- ,[Plain [Str "You",Space,Str "can",Space,Str "add",Space,Str "just",Space,Str "one,"]
-  ,BulletList
-   [[Plain [Str "or",Space,Str "many."]
-    ,BulletList
-     [[Plain [Str "What",Space,Str "matters",Space,Str "is",Space,Str "to",Space,Str "put",Space,Str "more",Space,Str "than",Space,Str "the",Space,Str "previous."]]
-     ,[Plain [Str "But",Space,Str "remember",Space,Str "that",Space,Str "the",Space,Str "other",Space,Str "items",Space,Str "of",Space,Str "the",Space,Str "same",Space,Str "list"]]
-     ,[Plain [Str "must",Space,Str "use",Space,Str "the",Space,Str "same",Space,Str "indentation."]]]]]]]
-,BulletList
- [[Plain [Str "There",Space,Str "is",Space,Str "not",Space,Str "a",Space,Str "depth",Space,Str "limit,"]
-  ,BulletList
-   [[Plain [Str "you",Space,Str "can",Space,Str "go",Space,Str "deeper",Space,Str "and",Space,Str "deeper."]
-    ,BulletList
-     [[Plain [Str "But",Space,Str "some",Space,Str "targets",Space,Str "may",Space,Str "have",Space,Str "restrictions."]
-      ,BulletList
-       [[Plain [Str "The",Space,Str "LaTeX",Space,Str "maximum",Space,Str "is",Space,Str "here,",Space,Str "4",Space,Str "levels."]]]]]]]]]
-,BulletList
- [[Plain [Str "Reverse",Space,Str "nesting",Space,Str "doesn't",Space,Str "work."]]
- ,[Plain [Str "Because",Space,Str "a",Space,Str "sublist",Space,Str "*must*",Space,Str "have",Space,Str "a",Space,Str "mother",Space,Str "list."]]
- ,[Plain [Str "It's",Space,Str "the",Space,Str "list",Space,Str "concept,",Space,Str "not",Space,Str "a",Space,Str "txt2tags",Space,Str "limitation."]]
- ,[Plain [Str "All",Space,Str "this",Space,Str "sublists",Space,Str "will",Space,Str "be",Space,Str "bumped",Space,Str "to",Space,Str "mother",Space,Str "lists."]]
- ,[Plain [Str "At",Space,Str "level",Space,Str "1,",Space,Str "like",Space,Str "this",Space,Str "one."]]]
-,BulletList
- [[Plain [Str "Level",Space,Str "1"]
-  ,BulletList
-   [[Plain [Str "Level",Space,Str "2"]
-    ,BulletList
-     [[Plain [Str "Level",Space,Str "3"]
-      ,BulletList
-       [[Plain [Str "Level",Space,Str "4"]]]]
-     ,[Plain [Str "Level",Space,Str "3",Space,Str "--",Space,Str "(closed",Space,Str "Level",Space,Str "4)"]]]]
-   ,[Plain [Str "Level",Space,Str "2",Space,Str "--",Space,Str "(closed",Space,Str "Level",Space,Str "3)"]]]]
- ,[Plain [Str "Level",Space,Str "1",Space,Str "--",Space,Str "(closed",Space,Str "Level",Space,Str "2)"]]]
-,BulletList
- [[Plain [Str "Level",Space,Str "1"]
-  ,BulletList
-   [[Plain [Str "Level",Space,Str "2"]
-    ,BulletList
-     [[Plain [Str "Level",Space,Str "3"]
-      ,BulletList
-       [[Plain [Str "Level",Space,Str "4"]]]]]]]]
- ,[Plain [Str "Level",Space,Str "1",Space,Str "--",Space,Str "(closed",Space,Str "Level",Space,Str "4,",Space,Str "Level",Space,Str "3",Space,Str "and",Space,Str "Level",Space,Str "2)"]]]
-,BulletList
- [[Para [Str "Level",Space,Str "1"]
-  ,BulletList
-   [[Para [Str "Level",Space,Str "2",Space,Str "--",Space,Str "blank",Space,Str "BEFORE",Space,Str "and",Space,Str "AFTER",Space,Str "(in)"]
-    ,BulletList
-     [[Plain [Str "Level",Space,Str "3"]]]]]]]
-,BulletList
- [[Plain [Str "Level",Space,Str "4"]]]
-,BulletList
- [[Para [Str "Level",Space,Str "3"]]
- ,[Para [Str "Level",Space,Str "2",Space,Str "--",Space,Str "blank",Space,Str "BEFORE",Space,Str "and",Space,Str "AFTER",Space,Str "(out)"]]
- ,[Para [Str "Level",Space,Str "1"]
-  ,BulletList
-   [[Para [Str "Level",Space,Str "2",Space,Str "--",Space,Str "blank",Space,Str "BEFORE",Space,Str "(spaces)",Space,Str "and",Space,Str "AFTER",Space,Str "(TAB)"]
-    ,BulletList
-     [[Plain [Str "Level",Space,Str "3"]]]]]]]
-,BulletList
- [[Plain [Str "Level",Space,Str "1"]
-  ,BulletList
-   [[Plain [Str "Level",Space,Str "2"]
-    ,BulletList
-     [[Plain [Str "Level",Space,Str "3"]
-      ,BulletList
-       [[Plain [Str "Level",Space,Str "4"]]
-       ,[Plain [Str "Level",Space,Str "3.5",Space,Str "???"]]]]
-     ,[Plain [Str "Level",Space,Str "3"]]
-     ,[Plain [Str "Level",Space,Str "2.5",Space,Str "???"]]]]
-   ,[Plain [Str "Level",Space,Str "2"]]
-   ,[Plain [Str "Level",Space,Str "1.5",Space,Str "???"]]]]
- ,[Plain [Str "Level",Space,Str "1"]]]
-,BulletList
- [[Plain [Str "This",Space,Str "list",Space,Str "is",Space,Str "closed",Space,Str "by",Space,Str "a",Space,Str "line",Space,Str "with",Space,Str "spaces",Space,Str "and",Space,Str "other",Space,Str "with",Space,Str "TABs"]]]
-,BulletList
- [[Plain [Str "This",Space,Str "list",Space,Str "is",Space,Str "NOT",Space,Str "closed",Space,Str "by",Space,Str "two",Space,Str "comment",Space,Str "lines"]]]
-,BulletList
- [[Plain [Str "This",Space,Str "list",Space,Str "is",Space,Str "closed",Space,Str "by",Space,Str "a",Space,Str "line",Space,Str "with",Space,Str "spaces",Space,Str "and",Space,Str "TAB,"]]
- ,[Plain [Str "then",Space,Str "a",Space,Str "comment",Space,Str "line,",Space,Str "then",Space,Str "an",Space,Str "empty",Space,Str "line."]]]
-,BulletList
- [[Plain [Str "Level",Space,Str "1"]
-  ,BulletList
-   [[Plain [Str "Level",Space,Str "2"]
-    ,BulletList
-     [[Plain [Str "Level",Space,Str "3"]]]
-    ,Plain [Str "-",SoftBreak,Str "Level",Space,Str "2"]]]
-  ,Plain [Str "-",SoftBreak,Str "Level",Space,Str "1"]]]
-,Para [Str "-"]
-,BulletList
- [[Plain [Str "Empty",Space,Str "item",Space,Str "with",Space,Str "trailing",Space,Str "spaces."]]]
-,Para [Str "-"]
-,BulletList
- [[Plain [Str "Empty",Space,Str "item",Space,Str "with",Space,Str "trailing",Space,Str "TAB."]]]
-,Para [Str "-"]
-,BulletList
- [[Plain [Str "If",Space,Str "the",Space,Str "end",Space,Str "of",Space,Str "the",Space,Str "file",Space,Str "(EOF)",Space,Str "is",Space,Str "hit,"]
-  ,BulletList
-   [[Plain [Str "all",Space,Str "the",Space,Str "currently",Space,Str "opened",Space,Str "list",Space,Str "are",Space,Str "closed,"]
-    ,BulletList
-     [[Plain [Str "just",Space,Str "like",Space,Str "when",Space,Str "using",Space,Str "the",Space,Str "two",Space,Str "blank",Space,Str "lines."]]]]]]]
-,Header 1 ("table",[],[]) [Str "Table"]
-,Table [] [AlignRight] [0.0]
- [[]]
- [[[Plain [Str "Cell",Space,Str "1"]]]]
-,Table [] [AlignCenter,AlignCenter,AlignRight] [0.0,0.0,0.0]
- [[]
- ,[]
- ,[]]
- [[[Plain [Str "Cell",Space,Str "1"]]
-  ,[Plain [Str "Cell",Space,Str "2"]]
-  ,[Plain [Str "Cell",Space,Str "3"]]]]
-,Table [] [AlignCenter,AlignCenter,AlignCenter] [0.0,0.0,0.0]
- [[]
- ,[]
- ,[]]
- [[[Plain [Str "Cell",Space,Str "1"]]
-  ,[Plain [Str "Cell",Space,Str "2"]]
-  ,[Plain [Str "Cell",Space,Str "3"]]]]
-,Para [Str "||",Space,Str "Cell",Space,Str "1",Space,Str "|",Space,Str "Cell",Space,Str "2",Space,Str "|",Space,Str "Cell",Space,Str "3",Space,Str "|"]
-,Table [] [AlignCenter,AlignCenter,AlignCenter] [0.0,0.0,0.0]
- [[]
- ,[]
- ,[]]
- [[[Plain [Str "Cell",Space,Str "1"]]
-  ,[Plain [Str "Cell",Space,Str "2"]]
-  ,[Plain [Str "Cell",Space,Str "3"]]]]
-,Table [] [AlignDefault,AlignCenter,AlignDefault] [0.0,0.0,0.0]
- [[Plain [Str "Heading"]]
- ,[Plain [Str "Heading"]]
- ,[Plain [Str "Heading"]]]
- [[[Plain [Str "<-"]]
-  ,[Plain [Str "--"]]
-  ,[Plain [Str "->"]]]
- ,[[Plain [Str "--"]]
-  ,[Plain [Str "--"]]
-  ,[Plain [Str "--"]]]
- ,[[Plain [Str "->"]]
-  ,[Plain [Str "--"]]
-  ,[Plain [Str "<-"]]]]
-,Table [] [AlignDefault,AlignDefault,AlignCenter,AlignCenter] [0.0,0.0,0.0,0.0]
- [[Plain [Str "1"]]
- ,[Plain [Str "2"]]
- ,[Plain [Str "3+4"]]
- ,[]]
- [[[Plain [Str "1"]]
-  ,[Plain [Str "2"]]
-  ,[Plain [Str "3"]]
-  ,[Plain [Str "4"]]]
- ,[[Plain [Str "1+2+3"]]
-  ,[Plain [Str "4"]]
-  ,[]
-  ,[]]
- ,[[Plain [Str "1"]]
-  ,[Plain [Str "2+3"]]
-  ,[Plain [Str "4"]]
-  ,[]]
- ,[[Plain [Str "1+2+3+4"]]
-  ,[]
-  ,[]
-  ,[]]]
-,Table [] [AlignCenter,AlignCenter,AlignCenter,AlignCenter] [0.0,0.0,0.0,0.0]
- [[]
- ,[]
- ,[]
- ,[]]
- [[[Plain [Str "0"]]
-  ,[Plain [Str "1"]]
-  ,[Plain [Str "2"]]
-  ,[]]
- ,[[Plain [Str "4"]]
-  ,[Plain [Str "5"]]
-  ,[]
-  ,[Plain [Str "7"]]]
- ,[[Plain [Str "8"]]
-  ,[]
-  ,[Plain [Str "A"]]
-  ,[Plain [Str "B"]]]
- ,[[]
-  ,[Plain [Str "D"]]
-  ,[Plain [Str "E"]]
-  ,[Plain [Str "F"]]]]
-,Table [] [AlignCenter,AlignCenter,AlignCenter,AlignCenter,AlignCenter] [0.0,0.0,0.0,0.0,0.0]
- [[]
- ,[]
- ,[]
- ,[]
- ,[]]
- [[[Plain [Str "1"]]
-  ,[]
-  ,[]
-  ,[]
-  ,[]]
- ,[[Plain [Str "1"]]
-  ,[Plain [Str "2"]]
-  ,[]
-  ,[]
-  ,[]]
- ,[[Plain [Str "1"]]
-  ,[Plain [Str "2"]]
-  ,[Plain [Str "3"]]
-  ,[]
-  ,[]]
- ,[[Plain [Str "1"]]
-  ,[Plain [Str "2"]]
-  ,[Plain [Str "3"]]
-  ,[Plain [Str "4"]]
-  ,[]]
- ,[[Plain [Str "1"]]
-  ,[Plain [Str "2"]]
-  ,[Plain [Str "3"]]
-  ,[Plain [Str "4"]]
-  ,[Plain [Str "5"]]]]
-,Table [] [AlignDefault,AlignCenter,AlignCenter,AlignCenter,AlignCenter] [0.0,0.0,0.0,0.0,0.0]
- [[]
- ,[]
- ,[]
- ,[]
- ,[]]
- [[[Plain [Str "Jan"]]
-  ,[]
-  ,[]
-  ,[]
-  ,[]]
- ,[[Plain [Str "Fev"]]
-  ,[]
-  ,[]
-  ,[]
-  ,[]]
- ,[[Plain [Str "Mar"]]
-  ,[]
-  ,[]
-  ,[]
-  ,[]]
- ,[[Plain [Str "Apr"]]
-  ,[]
-  ,[]
-  ,[]
-  ,[]]
- ,[[Plain [Str "May"]]
-  ,[]
-  ,[]
-  ,[]
-  ,[]]
- ,[[Plain [Str "20%"]]
-  ,[Plain [Str "40%"]]
-  ,[Plain [Str "60%"]]
-  ,[Plain [Str "80%"]]
-  ,[Plain [Str "100%"]]]]
-,Table [] [AlignCenter,AlignDefault,AlignDefault,AlignCenter,AlignCenter] [0.0,0.0,0.0,0.0,0.0]
- [[]
- ,[]
- ,[]
- ,[]
- ,[]]
- [[[]
-  ,[]
-  ,[Plain [Str "/"]]
-  ,[]
-  ,[]]
- ,[[]
-  ,[Plain [Str "/",Space,Str "/",Space,Str "/",Space,Str "/",Space,Str "/"]]
-  ,[]
-  ,[]
-  ,[]]
- ,[[Plain [Str "/",Space,Str "/",Space,Str "/",Space,Str "/",Space,Str "/",Space,Str "/",Space,Str "/",Space,Str "/",Space,Str "/"]]
-  ,[]
-  ,[]
-  ,[]
-  ,[]]
- ,[[]
-  ,[Plain [Str "o"]]
-  ,[]
-  ,[Plain [Str "o"]]
-  ,[]]
- ,[[]
-  ,[]
-  ,[Plain [Str "."]]
-  ,[]
-  ,[]]
- ,[[]
-  ,[Plain [Str "=",Space,Str "=",Space,Str "=",Space,Str "="]]
-  ,[]
-  ,[]
-  ,[]]]
-,Table [] [AlignCenter,AlignCenter,AlignCenter,AlignCenter,AlignCenter,AlignCenter,AlignCenter,AlignCenter] [0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0]
- [[]
- ,[]
- ,[]
- ,[]
- ,[]
- ,[]
- ,[]
- ,[]]
- [[[Plain [Str "01"]]
-  ,[Plain [Str "02"]]
-  ,[]
-  ,[]
-  ,[Plain [Str "05"]]
-  ,[]
-  ,[Plain [Str "07"]]
-  ,[]]
- ,[[]
-  ,[]
-  ,[Plain [Str "11"]]
-  ,[]
-  ,[Plain [Str "13"]]
-  ,[]
-  ,[]
-  ,[Plain [Str "16"]]]
- ,[[Plain [Str "17"]]
-  ,[]
-  ,[Plain [Str "19"]]
-  ,[Plain [Str "20"]]
-  ,[]
-  ,[]
-  ,[Plain [Str "23"]]
-  ,[]]
- ,[[Plain [Str "25"]]
-  ,[Plain [Str "26"]]
-  ,[]
-  ,[]
-  ,[Plain [Str "29"]]
-  ,[Plain [Str "30"]]
-  ,[]
-  ,[Plain [Str "32"]]]
- ,[[]
-  ,[]
-  ,[Plain [Str "35"]]
-  ,[]
-  ,[Plain [Str "37"]]
-  ,[]
-  ,[Plain [Str "39"]]
-  ,[Plain [Str "40"]]]]
-,Table [] [AlignCenter,AlignCenter,AlignCenter,AlignCenter,AlignCenter,AlignCenter,AlignCenter,AlignCenter,AlignCenter,AlignCenter,AlignCenter,AlignCenter,AlignCenter,AlignCenter,AlignCenter,AlignCenter,AlignCenter,AlignCenter,AlignCenter,AlignCenter,AlignCenter,AlignCenter,AlignCenter,AlignCenter,AlignCenter,AlignCenter,AlignCenter,AlignCenter,AlignCenter,AlignCenter,AlignCenter,AlignCenter] [0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0]
- [[]
- ,[]
- ,[]
- ,[]
- ,[]
- ,[]
- ,[]
- ,[]
- ,[]
- ,[]
- ,[]
- ,[]
- ,[]
- ,[]
- ,[]
- ,[]
- ,[]
- ,[]
- ,[]
- ,[]
- ,[]
- ,[]
- ,[]
- ,[]
- ,[]
- ,[]
- ,[]
- ,[]
- ,[]
- ,[]
- ,[]
- ,[]]
- [[[Plain [Str "0"]]
-  ,[Plain [Str "1"]]
-  ,[Plain [Str "2"]]
-  ,[Plain [Str "3"]]
-  ,[Plain [Str "4"]]
-  ,[Plain [Str "5"]]
-  ,[Plain [Str "6"]]
-  ,[Plain [Str "7"]]
-  ,[Plain [Str "8"]]
-  ,[Plain [Str "9"]]
-  ,[Plain [Str "A"]]
-  ,[Plain [Str "B"]]
-  ,[Plain [Str "C"]]
-  ,[Plain [Str "D"]]
-  ,[Plain [Str "E"]]
-  ,[Plain [Str "F"]]
-  ,[Plain [Str "0"]]
-  ,[Plain [Str "1"]]
-  ,[Plain [Str "2"]]
-  ,[Plain [Str "3"]]
-  ,[Plain [Str "4"]]
-  ,[Plain [Str "5"]]
-  ,[Plain [Str "6"]]
-  ,[Plain [Str "7"]]
-  ,[Plain [Str "8"]]
-  ,[Plain [Str "9"]]
-  ,[Plain [Str "A"]]
-  ,[Plain [Str "B"]]
-  ,[Plain [Str "C"]]
-  ,[Plain [Str "D"]]
-  ,[Plain [Str "E"]]
-  ,[Plain [Str "F"]]]]
-,Table [] [AlignCenter] [0.0]
- [[]]
- [[[]]
- ,[[]]
- ,[[]]]
-,Para [Str "|this|is|not|a|table|"]
-,Para [Str "|this|",Space,Str "is|",Space,Str "not|",Space,Str "a|",Space,Str "table|"]
-,Para [Str "|this",Space,Str "|is",Space,Str "|not",Space,Str "|a",Space,Str "|table",Space,Str "|"]
-,Para [Str "|",Space,Str "this\t|",Space,Str "is\t|",Space,Str "not\t|",Space,Str "a\t|",Space,Str "table\t|"]
-,HorizontalRule
-,Para [Str "The",Space,Str "End."]]
+Pandoc
+  Meta
+    { unMeta =
+        fromList
+          [ ( "author" , MetaList [ MetaInlines [ Str "author" ] ] )
+          , ( "date" , MetaInlines [ Str "date" ] )
+          , ( "includeconf" , MetaString "rules.conf" )
+          , ( "title"
+            , MetaInlines
+                [ Str "Txt2tags"
+                , Space
+                , Str "Markup"
+                , Space
+                , Str "Rules"
+                ]
+            )
+          ]
+    }
+  [ Para
+      [ Str "This"
+      , Space
+      , Str "document"
+      , Space
+      , Str "describes"
+      , Space
+      , Str "all"
+      , Space
+      , Str "the"
+      , Space
+      , Str "details"
+      , Space
+      , Str "about"
+      , Space
+      , Str "each"
+      , Space
+      , Str "txt2tags"
+      , Space
+      , Str "mark."
+      , SoftBreak
+      , Str "The"
+      , Space
+      , Str "target"
+      , Space
+      , Str "audience"
+      , Space
+      , Str "are"
+      , Space
+      , Strong [ Str "experienced" ]
+      , Space
+      , Str "users."
+      , Space
+      , Str "You"
+      , Space
+      , Str "may"
+      , Space
+      , Str "find"
+      , Space
+      , Str "it"
+      , SoftBreak
+      , Str "useful"
+      , Space
+      , Str "if"
+      , Space
+      , Str "you"
+      , Space
+      , Str "want"
+      , Space
+      , Str "to"
+      , Space
+      , Str "master"
+      , Space
+      , Str "the"
+      , Space
+      , Str "marks"
+      , Space
+      , Str "or"
+      , Space
+      , Str "solve"
+      , Space
+      , Str "a"
+      , Space
+      , Str "specific"
+      , Space
+      , Str "problem"
+      , SoftBreak
+      , Str "about"
+      , Space
+      , Str "a"
+      , Space
+      , Str "mark."
+      ]
+  , Para
+      [ Str "If"
+      , Space
+      , Str "you"
+      , Space
+      , Str "are"
+      , Space
+      , Str "new"
+      , Space
+      , Str "to"
+      , Space
+      , Str "txt2tags"
+      , Space
+      , Str "or"
+      , Space
+      , Str "just"
+      , Space
+      , Str "want"
+      , Space
+      , Str "to"
+      , Space
+      , Str "know"
+      , Space
+      , Str "which"
+      , Space
+      , Str "are"
+      , Space
+      , Str "the"
+      , SoftBreak
+      , Str "available"
+      , Space
+      , Str "marks,"
+      , Space
+      , Str "please"
+      , Space
+      , Str "read"
+      , Space
+      , Str "the"
+      , Space
+      , Link
+          ( "" , [] , [] )
+          [ Str "Markup" , Space , Str "Demo" ]
+          ( "MARKUPDEMO" , "" )
+      , Str "."
+      ]
+  , Para
+      [ Str "Note"
+      , Space
+      , Str "1:"
+      , Space
+      , Str "This"
+      , Space
+      , Str "document"
+      , Space
+      , Str "is"
+      , Space
+      , Str "generated"
+      , Space
+      , Str "directly"
+      , Space
+      , Str "from"
+      , Space
+      , Str "the"
+      , Space
+      , Str "txt2tags"
+      , SoftBreak
+      , Str "test-suite."
+      , Space
+      , Str "All"
+      , Space
+      , Str "the"
+      , Space
+      , Str "rules"
+      , Space
+      , Str "mentioned"
+      , Space
+      , Str "here"
+      , Space
+      , Str "are"
+      , Space
+      , Str "100%"
+      , Space
+      , Str "in"
+      , Space
+      , Str "sync"
+      , Space
+      , Str "with"
+      , Space
+      , Str "the"
+      , SoftBreak
+      , Str "current"
+      , Space
+      , Str "program"
+      , Space
+      , Str "code."
+      ]
+  , Para
+      [ Str "Note"
+      , Space
+      , Str "2:"
+      , Space
+      , Str "A"
+      , Space
+      , Str "good"
+      , Space
+      , Str "practice"
+      , Space
+      , Str "is"
+      , Space
+      , Str "to"
+      , Space
+      , Str "consult"
+      , Space
+      , Link
+          ( "" , [] , [] )
+          [ Str "the" , Space , Str "sources" ]
+          ( "rules.t2t" , "" )
+      , Space
+      , Str "when"
+      , SoftBreak
+      , Str "reading,"
+      , Space
+      , Str "to"
+      , Space
+      , Str "see"
+      , Space
+      , Str "how"
+      , Space
+      , Str "the"
+      , Space
+      , Str "texts"
+      , Space
+      , Str "were"
+      , Space
+      , Str "made."
+      ]
+  , Para
+      [ Str "Table" , Space , Str "of" , Space , Str "Contents:" ]
+  , HorizontalRule
+  , Header 1 ( "paragraph" , [] , [] ) [ Str "Paragraph" ]
+  , Para
+      [ Str "A"
+      , Space
+      , Str "paragraph"
+      , Space
+      , Str "is"
+      , Space
+      , Str "composed"
+      , Space
+      , Str "by"
+      , Space
+      , Str "one"
+      , Space
+      , Str "or"
+      , Space
+      , Str "more"
+      , Space
+      , Str "lines."
+      , SoftBreak
+      , Str "A"
+      , Space
+      , Str "blank"
+      , Space
+      , Str "line"
+      , Space
+      , Str "(or"
+      , Space
+      , Str "a"
+      , Space
+      , Str "table,"
+      , Space
+      , Str "or"
+      , Space
+      , Str "a"
+      , Space
+      , Str "list)"
+      , Space
+      , Str "ends"
+      , Space
+      , Str "the"
+      , SoftBreak
+      , Str "current"
+      , Space
+      , Str "paragraph."
+      ]
+  , Para
+      [ Str "Leading"
+      , Space
+      , Str "and"
+      , Space
+      , Str "trailing"
+      , Space
+      , Str "spaces"
+      , Space
+      , Str "are"
+      , Space
+      , Str "ignored."
+      ]
+  , Para
+      [ Str "A"
+      , Space
+      , Str "comment"
+      , Space
+      , Str "line"
+      , Space
+      , Str "can"
+      , Space
+      , Str "be"
+      , Space
+      , Str "placed"
+      , Space
+      , Str "inside"
+      , Space
+      , Str "a"
+      , Space
+      , Str "paragraph."
+      , SoftBreak
+      , Str "It"
+      , Space
+      , Str "will"
+      , Space
+      , Str "not"
+      , Space
+      , Str "affect"
+      , Space
+      , Str "it."
+      ]
+  , Para
+      [ Str "The"
+      , Space
+      , Str "end"
+      , Space
+      , Str "of"
+      , Space
+      , Str "the"
+      , Space
+      , Str "file"
+      , Space
+      , Str "(EOF)"
+      , Space
+      , Str "closes"
+      , Space
+      , Str "the"
+      , SoftBreak
+      , Str "currently"
+      , Space
+      , Str "open"
+      , Space
+      , Str "paragraph."
+      ]
+  , Header 1 ( "comment" , [] , [] ) [ Str "Comment" ]
+  , Para
+      [ Str "%"
+      , Space
+      , Str "not"
+      , Space
+      , Str "on"
+      , Space
+      , Str "the"
+      , Space
+      , Str "line"
+      , Space
+      , Str "beginning"
+      , Space
+      , Str "(at"
+      , Space
+      , Str "column"
+      , Space
+      , Str "2)"
+      ]
+  , Para
+      [ Str "some"
+      , Space
+      , Str "text"
+      , Space
+      , Str "%"
+      , Space
+      , Str "half"
+      , Space
+      , Str "line"
+      , Space
+      , Str "comments"
+      , Space
+      , Str "are"
+      , Space
+      , Str "not"
+      , Space
+      , Str "allowed"
+      ]
+  , Header 1 ( "line" , [] , [] ) [ Str "Line" ]
+  , HorizontalRule
+  , HorizontalRule
+  , HorizontalRule
+  , HorizontalRule
+  , HorizontalRule
+  , HorizontalRule
+  , HorizontalRule
+  , HorizontalRule
+  , HorizontalRule
+  , HorizontalRule
+  , HorizontalRule
+  , Para
+      [ Strikeout [ Str "-----" ]
+      , SoftBreak
+      , Strikeout [ Str "-------" , Space , Str "--------" ]
+      ]
+  , Para [ Strikeout [ Str "-------+--------" ] ]
+  , Para
+      [ Str "("
+      , Space
+      , Strikeout [ Str "----------------" ]
+      , Space
+      , Str ")"
+      ]
+  , Header 1 ( "inline" , [] , [] ) [ Str "Inline" ]
+  , Para
+      [ Str "i)"
+      , Space
+      , Strong [ Str "b" ]
+      , Space
+      , Emph [ Str "i" ]
+      , Space
+      , Underline [ Str "u" ]
+      , Space
+      , Strikeout [ Str "s" ]
+      , Space
+      , Code ( "" , [] , [] ) "m"
+      , Space
+      , Str "r"
+      , Space
+      , RawInline (Format "html") "t"
+      , SoftBreak
+      , Str "i)"
+      , Space
+      , Strong [ Str "bo" ]
+      , Space
+      , Emph [ Str "it" ]
+      , Space
+      , Underline [ Str "un" ]
+      , Space
+      , Strikeout [ Str "st" ]
+      , Space
+      , Code ( "" , [] , [] ) "mo"
+      , Space
+      , Str "ra"
+      , Space
+      , RawInline (Format "html") "tg"
+      , SoftBreak
+      , Str "i)"
+      , Space
+      , Strong [ Str "bold" ]
+      , Space
+      , Emph [ Str "ital" ]
+      , Space
+      , Underline [ Str "undr" ]
+      , Space
+      , Strikeout [ Str "strk" ]
+      , Space
+      , Code ( "" , [] , [] ) "mono"
+      , Space
+      , Str "raw"
+      , Space
+      , RawInline (Format "html") "tggd"
+      , SoftBreak
+      , Str "i)"
+      , Space
+      , Strong [ Str "bo" , Space , Str "ld" ]
+      , Space
+      , Emph [ Str "it" , Space , Str "al" ]
+      , Space
+      , Underline [ Str "un" , Space , Str "dr" ]
+      , Space
+      , Strikeout [ Str "st" , Space , Str "rk" ]
+      , Space
+      , Code ( "" , [] , [] ) "mo no"
+      , Space
+      , Str "r"
+      , Space
+      , Str "aw"
+      , Space
+      , RawInline (Format "html") "tg gd"
+      , SoftBreak
+      , Str "i)"
+      , Space
+      , Strong [ Str "bo" , Space , Str "*" , Space , Str "ld" ]
+      , Space
+      , Emph [ Str "it" , Space , Str "/" , Space , Str "al" ]
+      , Space
+      , Underline
+          [ Str "un" , Space , Str "_" , Space , Str "dr" ]
+      , Space
+      , Strikeout
+          [ Str "st" , Space , Str "-" , Space , Str "rk" ]
+      , Space
+      , Code ( "" , [] , [] ) "mo ` no"
+      , Space
+      , Str "r"
+      , Space
+      , Str "\""
+      , Space
+      , Str "aw"
+      , Space
+      , RawInline (Format "html") "tg ' gd"
+      , SoftBreak
+      , Str "i)"
+      , Space
+      , Strong [ Str "bo" , Space , Str "**ld" ]
+      , Space
+      , Emph [ Str "it" , Space , Str "//al" ]
+      , Space
+      , Underline [ Str "un" , Space , Str "__dr" ]
+      , Space
+      , Strikeout [ Str "st" , Space , Str "--rk" ]
+      , Space
+      , Code ( "" , [] , [] ) "mo ``no"
+      , Space
+      , Str "r"
+      , Space
+      , Str "\"\"aw"
+      , Space
+      , RawInline (Format "html") "tg ''gd"
+      , SoftBreak
+      , Str "i)"
+      , Space
+      , Strong [ Str "bo" , Space , Str "**" , Space , Str "ld" ]
+      , Space
+      , Emph [ Str "it" , Space , Str "//" , Space , Str "al" ]
+      , Space
+      , Underline
+          [ Str "un" , Space , Str "__" , Space , Str "dr" ]
+      , Space
+      , Strikeout
+          [ Str "st" , Space , Str "--" , Space , Str "rk" ]
+      , Space
+      , Code ( "" , [] , [] ) "mo `` no"
+      , Space
+      , Str "r"
+      , Space
+      , Str "\"\""
+      , Space
+      , Str "aw"
+      , Space
+      , RawInline (Format "html") "tg '' gd"
+      , SoftBreak
+      , Str "i)"
+      , Space
+      , Strong [ Str "**bold**" ]
+      , Space
+      , Emph [ Str "//ital//" ]
+      , Space
+      , Underline [ Str "__undr__" ]
+      , Space
+      , Strikeout [ Str "--strk--" ]
+      , Space
+      , Code ( "" , [] , [] ) "``mono``"
+      , Space
+      , Str "\"\"raw\"\""
+      , Space
+      , RawInline (Format "html") "''tggd''"
+      , SoftBreak
+      , Str "i)"
+      , Space
+      , Strong [ Str "*bold*" ]
+      , Space
+      , Emph [ Str "/ital/" ]
+      , Space
+      , Underline [ Str "_undr_" ]
+      , Space
+      , Strikeout [ Str "-strk-" ]
+      , Space
+      , Code ( "" , [] , [] ) "`mono`"
+      , Space
+      , Str "\"raw\""
+      , Space
+      , RawInline (Format "html") "'tggd'"
+      ]
+  , Para
+      [ Str "i)"
+      , Space
+      , Strong [ Str "*" ]
+      , Space
+      , Emph [ Str "/" ]
+      , Space
+      , Underline [ Str "_" ]
+      , Space
+      , Strikeout [ Str "-" ]
+      , Space
+      , Code ( "" , [] , [] ) "`"
+      , Space
+      , Str "\""
+      , Space
+      , RawInline (Format "html") "'"
+      , SoftBreak
+      , Str "i)"
+      , Space
+      , Strong [ Str "**" ]
+      , Space
+      , Emph [ Str "//" ]
+      , Space
+      , Underline [ Str "__" ]
+      , Space
+      , Strikeout [ Str "--" ]
+      , Space
+      , Code ( "" , [] , [] ) "``"
+      , Space
+      , Str "\"\""
+      , Space
+      , RawInline (Format "html") "''"
+      , SoftBreak
+      , Str "i)"
+      , Space
+      , Strong [ Str "***" ]
+      , Space
+      , Emph [ Str "///" ]
+      , Space
+      , Underline [ Str "___" ]
+      , Space
+      , Strikeout [ Str "---" ]
+      , Space
+      , Code ( "" , [] , [] ) "```"
+      , Space
+      , Str "\"\"\""
+      , Space
+      , RawInline (Format "html") "'''"
+      , SoftBreak
+      , Str "i)"
+      , Space
+      , Strong [ Str "****" ]
+      , Space
+      , Emph [ Str "////" ]
+      , Space
+      , Underline [ Str "____" ]
+      , Space
+      , Strikeout [ Str "----" ]
+      , Space
+      , Code ( "" , [] , [] ) "````"
+      , Space
+      , Str "\"\"\"\""
+      , Space
+      , RawInline (Format "html") "''''"
+      , SoftBreak
+      , Str "i)"
+      , Space
+      , Strong [ Str "*****" ]
+      , Space
+      , Emph [ Str "/////" ]
+      , Space
+      , Underline [ Str "_____" ]
+      , Space
+      , Strikeout [ Str "-----" ]
+      , Space
+      , Code ( "" , [] , [] ) "`````"
+      , Space
+      , Str "\"\"\"\"\""
+      , Space
+      , RawInline (Format "html") "'''''"
+      , SoftBreak
+      , Str "i)"
+      , Space
+      , Strong [ Str "******" ]
+      , Space
+      , Emph [ Str "//////" ]
+      , Space
+      , Underline [ Str "______" ]
+      , Space
+      , Strikeout [ Str "------" ]
+      , Space
+      , Code ( "" , [] , [] ) "``````"
+      , Space
+      , Str "\"\"\"\"\"\""
+      , Space
+      , RawInline (Format "html") "''''''"
+      ]
+  , Para
+      [ Str "i)"
+      , Space
+      , Str "****"
+      , Space
+      , Str "////"
+      , Space
+      , Str "____"
+      , Space
+      , Str "----"
+      , Space
+      , Str "````"
+      , Space
+      , Str "\"\"\"\""
+      , Space
+      , Str "''''"
+      , SoftBreak
+      , Str "i)"
+      , Space
+      , Str "**"
+      , Space
+      , Str "**"
+      , Space
+      , Str "//"
+      , Space
+      , Str "//"
+      , Space
+      , Str "__"
+      , Space
+      , Str "__"
+      , Space
+      , Str "--"
+      , Space
+      , Str "--"
+      , Space
+      , Str "``"
+      , Space
+      , Str "``"
+      , Space
+      , Str "\"\""
+      , Space
+      , Str "\"\""
+      , Space
+      , Str "''"
+      , Space
+      , Str "''"
+      ]
+  , Para
+      [ Str "i)"
+      , Space
+      , Str "**"
+      , Space
+      , Str "bold**"
+      , Space
+      , Str "//"
+      , Space
+      , Str "ital//"
+      , Space
+      , Str "__"
+      , Space
+      , Str "undr__"
+      , Space
+      , Str "--"
+      , Space
+      , Str "strk--"
+      , Space
+      , Str "``"
+      , Space
+      , Str "mono``"
+      , Space
+      , Str "\"\""
+      , Space
+      , Str "raw\"\""
+      , Space
+      , Str "''"
+      , Space
+      , Str "tggd''"
+      , SoftBreak
+      , Str "i)"
+      , Space
+      , Str "**bold"
+      , Space
+      , Str "**"
+      , Space
+      , Str "//ital"
+      , Space
+      , Str "//"
+      , Space
+      , Str "__undr"
+      , Space
+      , Str "__"
+      , Space
+      , Str "--strk"
+      , Space
+      , Str "--"
+      , Space
+      , Str "``mono"
+      , Space
+      , Str "``"
+      , Space
+      , Str "\"\"raw"
+      , Space
+      , Str "\"\""
+      , Space
+      , Str "''tggd"
+      , Space
+      , Str "''"
+      , SoftBreak
+      , Str "i)"
+      , Space
+      , Str "**"
+      , Space
+      , Str "bold"
+      , Space
+      , Str "**"
+      , Space
+      , Str "//"
+      , Space
+      , Str "ital"
+      , Space
+      , Str "//"
+      , Space
+      , Str "__"
+      , Space
+      , Str "undr"
+      , Space
+      , Str "__"
+      , Space
+      , Str "--"
+      , Space
+      , Str "strk"
+      , Space
+      , Str "--"
+      , Space
+      , Str "``"
+      , Space
+      , Str "mono"
+      , Space
+      , Str "``"
+      , Space
+      , Str "\"\""
+      , Space
+      , Str "raw"
+      , Space
+      , Str "\"\""
+      , Space
+      , Str "''"
+      , Space
+      , Str "tggd"
+      , Space
+      , Str "''"
+      ]
+  , Header 1 ( "link" , [] , [] ) [ Str "Link" ]
+  , Para
+      [ Link
+          ( "" , [] , [] )
+          [ Str "mailto:user@domain.com" ]
+          ( "user@domain.com" , "" )
+      , SoftBreak
+      , Link
+          ( "" , [] , [] )
+          [ Str "mailto:user@domain.com" ]
+          ( "user@domain.com" , "" )
+      , Str "."
+      , SoftBreak
+      , Link
+          ( "" , [] , [] )
+          [ Str "mailto:user@domain.com" ]
+          ( "user@domain.com" , "" )
+      , Str "."
+      , Space
+      , Str "any"
+      , Space
+      , Str "text."
+      , SoftBreak
+      , Str "any"
+      , Space
+      , Str "text:"
+      , Space
+      , Link
+          ( "" , [] , [] )
+          [ Str "mailto:user@domain.com" ]
+          ( "user@domain.com" , "" )
+      , Str "."
+      , Space
+      , Str "any"
+      , Space
+      , Str "text."
+      , SoftBreak
+      , Link
+          ( "" , [] , [] ) [ Str "label" ] ( "user@domain.com" , "" )
+      , SoftBreak
+      , Link
+          ( "" , [] , [] )
+          [ Str "mailto:user@domain.com?subject=bla" ]
+          ( "user@domain.com?subject=bla" , "" )
+      , SoftBreak
+      , Link
+          ( "" , [] , [] )
+          [ Str "mailto:user@domain.com?subject=bla" ]
+          ( "user@domain.com?subject=bla" , "" )
+      , Str "."
+      , SoftBreak
+      , Link
+          ( "" , [] , [] )
+          [ Str "mailto:user@domain.com?subject=bla" ]
+          ( "user@domain.com?subject=bla" , "" )
+      , Str ","
+      , SoftBreak
+      , Link
+          ( "" , [] , [] )
+          [ Str
+              "mailto:user@domain.com?subject=bla&cc=otheruser@domain.com"
+          ]
+          ( "user@domain.com?subject=bla&cc=otheruser@domain.com"
+          , ""
+          )
+      , SoftBreak
+      , Link
+          ( "" , [] , [] )
+          [ Str
+              "mailto:user@domain.com?subject=bla&cc=otheruser@domain.com"
+          ]
+          ( "user@domain.com?subject=bla&cc=otheruser@domain.com"
+          , ""
+          )
+      , Str "."
+      , SoftBreak
+      , Link
+          ( "" , [] , [] )
+          [ Str
+              "mailto:user@domain.com?subject=bla&cc=otheruser@domain.com"
+          ]
+          ( "user@domain.com?subject=bla&cc=otheruser@domain.com"
+          , ""
+          )
+      , Str ","
+      , SoftBreak
+      , Link
+          ( "" , [] , [] )
+          [ Str "label" ]
+          ( "user@domain.com?subject=bla&cc=otheruser@domain.com"
+          , ""
+          )
+      , Str "."
+      , SoftBreak
+      , Link
+          ( "" , [] , [] )
+          [ Str "label" ]
+          ( "user@domain.com?subject=bla&cc=otheruser@domain.com."
+          , ""
+          )
+      , Str "."
+      , SoftBreak
+      , Link
+          ( "" , [] , [] )
+          [ Str "http://www.domain.com" ]
+          ( "http://www.domain.com" , "" )
+      , SoftBreak
+      , Link
+          ( "" , [] , [] )
+          [ Str "http://www.domain.com/dir/" ]
+          ( "http://www.domain.com/dir/" , "" )
+      , SoftBreak
+      , Link
+          ( "" , [] , [] )
+          [ Str "http://www.domain.com/dir///" ]
+          ( "http://www.domain.com/dir///" , "" )
+      , SoftBreak
+      , Link
+          ( "" , [] , [] )
+          [ Str "http://www.domain.com." ]
+          ( "http://www.domain.com." , "" )
+      , SoftBreak
+      , Link
+          ( "" , [] , [] )
+          [ Str "http://www.domain.com," ]
+          ( "http://www.domain.com," , "" )
+      , SoftBreak
+      , Link
+          ( "" , [] , [] )
+          [ Str "http://www.domain.com." ]
+          ( "http://www.domain.com." , "" )
+      , Space
+      , Str "any"
+      , Space
+      , Str "text."
+      , SoftBreak
+      , Link
+          ( "" , [] , [] )
+          [ Str "http://www.domain.com," ]
+          ( "http://www.domain.com," , "" )
+      , Space
+      , Str "any"
+      , Space
+      , Str "text."
+      , SoftBreak
+      , Link
+          ( "" , [] , [] )
+          [ Str "http://www.domain.com/dir/." ]
+          ( "http://www.domain.com/dir/." , "" )
+      , Space
+      , Str "any"
+      , Space
+      , Str "text."
+      , SoftBreak
+      , Str "any"
+      , Space
+      , Str "text:"
+      , Space
+      , Link
+          ( "" , [] , [] )
+          [ Str "http://www.domain.com." ]
+          ( "http://www.domain.com." , "" )
+      , Space
+      , Str "any"
+      , Space
+      , Str "text."
+      , SoftBreak
+      , Str "any"
+      , Space
+      , Str "text:"
+      , Space
+      , Link
+          ( "" , [] , [] )
+          [ Str "http://www.domain.com/dir/." ]
+          ( "http://www.domain.com/dir/." , "" )
+      , Space
+      , Str "any"
+      , Space
+      , Str "text."
+      , SoftBreak
+      , Str "any"
+      , Space
+      , Str "text:"
+      , Space
+      , Link
+          ( "" , [] , [] )
+          [ Str "http://www.domain.com/dir/index.html." ]
+          ( "http://www.domain.com/dir/index.html." , "" )
+      , Space
+      , Str "any"
+      , Space
+      , Str "text."
+      , SoftBreak
+      , Str "any"
+      , Space
+      , Str "text:"
+      , Space
+      , Link
+          ( "" , [] , [] )
+          [ Str "http://www.domain.com/dir/index.html," ]
+          ( "http://www.domain.com/dir/index.html," , "" )
+      , Space
+      , Str "any"
+      , Space
+      , Str "text."
+      , SoftBreak
+      , Link
+          ( "" , [] , [] )
+          [ Str "http://www.domain.com/dir/#anchor" ]
+          ( "http://www.domain.com/dir/#anchor" , "" )
+      , SoftBreak
+      , Link
+          ( "" , [] , [] )
+          [ Str "http://www.domain.com/dir/index.html#anchor" ]
+          ( "http://www.domain.com/dir/index.html#anchor" , "" )
+      , SoftBreak
+      , Link
+          ( "" , [] , [] )
+          [ Str "http://www.domain.com/dir/index.html#anchor." ]
+          ( "http://www.domain.com/dir/index.html#anchor." , "" )
+      , SoftBreak
+      , Link
+          ( "" , [] , [] )
+          [ Str "http://www.domain.com/dir/#anchor." ]
+          ( "http://www.domain.com/dir/#anchor." , "" )
+      , Space
+      , Str "any"
+      , Space
+      , Str "text."
+      , SoftBreak
+      , Link
+          ( "" , [] , [] )
+          [ Str "http://www.domain.com/dir/index.html#anchor." ]
+          ( "http://www.domain.com/dir/index.html#anchor." , "" )
+      , Space
+      , Str "any"
+      , Space
+      , Str "text."
+      , SoftBreak
+      , Str "any"
+      , Space
+      , Str "text:"
+      , Space
+      , Link
+          ( "" , [] , [] )
+          [ Str "http://www.domain.com/dir/#anchor." ]
+          ( "http://www.domain.com/dir/#anchor." , "" )
+      , Space
+      , Str "any"
+      , Space
+      , Str "text."
+      , SoftBreak
+      , Str "any"
+      , Space
+      , Str "text:"
+      , Space
+      , Link
+          ( "" , [] , [] )
+          [ Str "http://www.domain.com/dir/index.html#anchor." ]
+          ( "http://www.domain.com/dir/index.html#anchor." , "" )
+      , Space
+      , Str "any"
+      , Space
+      , Str "text."
+      , SoftBreak
+      , Link
+          ( "" , [] , [] )
+          [ Str "http://domain.com?a=a@a.a&b=a+b+c." ]
+          ( "http://domain.com?a=a@a.a&b=a+b+c." , "" )
+      , SoftBreak
+      , Link
+          ( "" , [] , [] )
+          [ Str "http://domain.com?a=a@a.a&b=a+b+c," ]
+          ( "http://domain.com?a=a@a.a&b=a+b+c," , "" )
+      , SoftBreak
+      , Link
+          ( "" , [] , [] )
+          [ Str "http://domain.com/bla.cgi?a=a@a.a&b=a+b+c." ]
+          ( "http://domain.com/bla.cgi?a=a@a.a&b=a+b+c." , "" )
+      , SoftBreak
+      , Link
+          ( "" , [] , [] )
+          [ Str "http://domain.com/bla.cgi?a=a@a.a&b=a+b+c@." ]
+          ( "http://domain.com/bla.cgi?a=a@a.a&b=a+b+c@." , "" )
+      , SoftBreak
+      , Link
+          ( "" , [] , [] )
+          [ Str "http://domain.com?a=a@a.a&b=a+b+c.#anchor" ]
+          ( "http://domain.com?a=a@a.a&b=a+b+c.#anchor" , "" )
+      , SoftBreak
+      , Link
+          ( "" , [] , [] )
+          [ Str "http://domain.com/bla.cgi?a=a@a.a&b=a+b+c.#anchor" ]
+          ( "http://domain.com/bla.cgi?a=a@a.a&b=a+b+c.#anchor" , "" )
+      , SoftBreak
+      , Link
+          ( "" , [] , [] )
+          [ Str "http://domain.com/bla.cgi?a=a@a.a&b=a+b+c@.#anchor" ]
+          ( "http://domain.com/bla.cgi?a=a@a.a&b=a+b+c@.#anchor"
+          , ""
+          )
+      , SoftBreak
+      , Link
+          ( "" , [] , [] )
+          [ Str "http://user:password@domain.com/bla.html." ]
+          ( "http://user:password@domain.com/bla.html." , "" )
+      , SoftBreak
+      , Link
+          ( "" , [] , [] )
+          [ Str "http://user:password@domain.com/dir/." ]
+          ( "http://user:password@domain.com/dir/." , "" )
+      , SoftBreak
+      , Link
+          ( "" , [] , [] )
+          [ Str "http://user:password@domain.com." ]
+          ( "http://user:password@domain.com." , "" )
+      , SoftBreak
+      , Link
+          ( "" , [] , [] )
+          [ Str "http://user:@domain.com." ]
+          ( "http://user:@domain.com." , "" )
+      , SoftBreak
+      , Link
+          ( "" , [] , [] )
+          [ Str "http://user@domain.com." ]
+          ( "http://user@domain.com." , "" )
+      , SoftBreak
+      , Link
+          ( "" , [] , [] )
+          [ Str
+              "http://user:password@domain.com/bla.cgi?a=a@a.a&b=a+b+c.#anchor"
+          ]
+          ( "http://user:password@domain.com/bla.cgi?a=a@a.a&b=a+b+c.#anchor"
+          , ""
+          )
+      , SoftBreak
+      , Link
+          ( "" , [] , [] )
+          [ Str
+              "http://user:password@domain.com/bla.cgi?a=a@a.a&b=a+b+c@#anchor"
+          ]
+          ( "http://user:password@domain.com/bla.cgi?a=a@a.a&b=a+b+c@#anchor"
+          , ""
+          )
+      , SoftBreak
+      , Link
+          ( "" , [] , [] ) [ Str "label" ] ( "www.domain.com" , "" )
+      , SoftBreak
+      , Str "["
+      , Space
+      , Str "label"
+      , Space
+      , Link
+          ( "" , [] , [] )
+          [ Str "www.domain.com" ]
+          ( "www.domain.com" , "" )
+      , Str "]"
+      , SoftBreak
+      , Link
+          ( "" , [] , [] )
+          [ Str "label" , Space ]
+          ( "www.domain.com" , "" )
+      , SoftBreak
+      , Link
+          ( "" , [] , [] )
+          [ Str "anchor" , Space ]
+          ( "http://www.domain.com/dir/index.html#anchor." , "" )
+      , SoftBreak
+      , Link
+          ( "" , [] , [] )
+          [ Str "login" , Space ]
+          ( "http://user:password@domain.com/bla.html" , "" )
+      , SoftBreak
+      , Link
+          ( "" , [] , [] )
+          [ Str "form" , Space ]
+          ( "http://www.domain.com/bla.cgi?a=a@a.a&b=a+b+c." , "" )
+      , SoftBreak
+      , Link
+          ( "" , [] , [] )
+          [ Str "form" , Space , Str "&" , Space , Str "anchor" ]
+          ( "http://www.domain.com/bla.cgi?a=a@a.a&b=a+b+c.#anchor"
+          , ""
+          )
+      , SoftBreak
+      , Link
+          ( "" , [] , [] )
+          [ Str "login"
+          , Space
+          , Str "&"
+          , Space
+          , Str "form"
+          , Space
+          ]
+          ( "http://user:password@domain.com/bla.cgi?a=a@a.a&b=a+b+c."
+          , ""
+          )
+      , SoftBreak
+      , Link
+          ( "" , [] , [] )
+          [ Str "local"
+          , Space
+          , Str "link"
+          , Space
+          , Str "up"
+          , Space
+          ]
+          ( ".." , "" )
+      , SoftBreak
+      , Link
+          ( "" , [] , [] )
+          [ Str "local"
+          , Space
+          , Str "link"
+          , Space
+          , Str "file"
+          , Space
+          ]
+          ( "bla.html" , "" )
+      , SoftBreak
+      , Link
+          ( "" , [] , [] )
+          [ Str "local"
+          , Space
+          , Str "link"
+          , Space
+          , Str "anchor"
+          , Space
+          ]
+          ( "#anchor" , "" )
+      , SoftBreak
+      , Link
+          ( "" , [] , [] )
+          [ Str "local"
+          , Space
+          , Str "link"
+          , Space
+          , Str "file/anchor"
+          ]
+          ( "bla.html#anchor" , "" )
+      , SoftBreak
+      , Link
+          ( "" , [] , [] )
+          [ Str "local"
+          , Space
+          , Str "link"
+          , Space
+          , Str "file/anchor"
+          ]
+          ( "bla.html#anchor." , "" )
+      , SoftBreak
+      , Link
+          ( "" , [] , [] )
+          [ Str "local"
+          , Space
+          , Str "link"
+          , Space
+          , Str "img"
+          , Space
+          ]
+          ( "abc.gif" , "" )
+      , SoftBreak
+      , Link
+          ( "" , [] , [] )
+          [ Str "www.fake.com" ]
+          ( "www.domain.com" , "" )
+      , SoftBreak
+      , Link
+          ( "" , [] , [] )
+          [ Str
+              "http://domain.com:8080/~user/_st-r@a=n$g,e/index%20new.htm"
+          ]
+          ( "http://domain.com:8080/~user/_st-r@a=n$g,e/index%20new.htm"
+          , ""
+          )
+      , SoftBreak
+      , Link
+          ( "" , [] , [] )
+          [ Str
+              "http://domain.com:8080/~user/_st-r@a=n$g,e/index%20new.htm?a=/%22&b=+.@*_-"
+          ]
+          ( "http://domain.com:8080/~user/_st-r@a=n$g,e/index%20new.htm?a=/%22&b=+.@*_-"
+          , ""
+          )
+      , SoftBreak
+      , Link
+          ( "" , [] , [] )
+          [ Str
+              "http://domain.com:8080/~user/_st-r@a=n$g,e/index%20new.htm?a=/%22&b=+.@*_-#anchor_"
+          ]
+          ( "http://domain.com:8080/~user/_st-r@a=n$g,e/index%20new.htm?a=/%22&b=+.@*_-#anchor_"
+          , ""
+          )
+      , Str "-1%."
+      , SoftBreak
+      , Link
+          ( "" , [] , [] )
+          [ Str
+              "http://foo._user-9:pass!#$%&*()+word@domain.com:8080/~user/_st-r@a=n$g,e/index%20new.htm?a=/%22&b=+.@*_-#anchor_"
+          ]
+          ( "http://foo._user-9:pass!#$%&*()+word@domain.com:8080/~user/_st-r@a=n$g,e/index%20new.htm?a=/%22&b=+.@*_-#anchor_"
+          , ""
+          )
+      , Str "-1%."
+      , SoftBreak
+      , Link
+          ( "" , [] , [] )
+          [ Str "http://L1.com" ]
+          ( "http://L1.com" , "" )
+      , Space
+      , Str "!"
+      , Space
+      , Link
+          ( "" , [] , [] )
+          [ Str "mailto:L2@www.com" ]
+          ( "L2@www.com" , "" )
+      , Space
+      , Str "!"
+      , Space
+      , Link ( "" , [] , [] ) [ Str "L3" ] ( "www.com" , "" )
+      , Space
+      , Str "!"
+      , Space
+      , Link ( "" , [] , [] ) [ Str "L4" ] ( "w@ww.com" , "" )
+      , Space
+      , Str "!"
+      , Space
+      , Link
+          ( "" , [] , [] ) [ Str "www.L5.com" ] ( "www.L5.com" , "" )
+      , SoftBreak
+      , Link
+          ( "" , [] , [] )
+          [ Str "www.domain.com" ]
+          ( "www.domain.com" , "" )
+      , SoftBreak
+      , Link
+          ( "" , [] , [] )
+          [ Str "www2.domain.com" ]
+          ( "www2.domain.com" , "" )
+      , SoftBreak
+      , Link
+          ( "" , [] , [] )
+          [ Str "ftp.domain.com" ]
+          ( "ftp.domain.com" , "" )
+      , SoftBreak
+      , Link
+          ( "" , [] , [] )
+          [ Str "WWW.DOMAIN.COM" ]
+          ( "WWW.DOMAIN.COM" , "" )
+      , SoftBreak
+      , Link
+          ( "" , [] , [] )
+          [ Str "FTP.DOMAIN.COM" ]
+          ( "FTP.DOMAIN.COM" , "" )
+      , SoftBreak
+      , Link
+          ( "" , [] , [] ) [ Str "label" ] ( "www.domain.com" , "" )
+      , SoftBreak
+      , Link
+          ( "" , [] , [] ) [ Str "label" ] ( "ftp.domain.com" , "" )
+      , SoftBreak
+      , Link
+          ( "" , [] , [] ) [ Str "label" ] ( "WWW.DOMAIN.COM" , "" )
+      , SoftBreak
+      , Link
+          ( "" , [] , [] ) [ Str "label" ] ( "FTP.DOMAIN.COM" , "" )
+      , SoftBreak
+      , Str "[label"
+      , Space
+      , Link
+          ( "" , [] , [] )
+          [ Str "www.domain.com" ]
+          ( "www.domain.com" , "" )
+      , Space
+      , Str "]"
+      , SoftBreak
+      , Str "[label]"
+      , Space
+      , Link
+          ( "" , [] , [] )
+          [ Str "www.domain.com" ]
+          ( "www.domain.com" , "" )
+      , Str "]"
+      ]
+  , Header 1 ( "image" , [] , [] ) [ Str "Image" ]
+  , Para [ Image ( "" , [] , [] ) [] ( "img.png" , "" ) ]
+  , Para
+      [ Link
+          ( "" , [] , [] )
+          [ Image ( "" , [] , [] ) [] ( "img.png" , "" ) ]
+          ( "https://txt2tags.org" , "" )
+      ]
+  , Para
+      [ Image ( "" , [] , [] ) [] ( "img.png" , "" )
+      , Space
+      , Str "Image"
+      , Space
+      , Str "at"
+      , Space
+      , Str "the"
+      , Space
+      , Str "line"
+      , Space
+      , Str "beginning."
+      ]
+  , Para
+      [ Str "Image"
+      , Space
+      , Str "in"
+      , Space
+      , Str "the"
+      , Space
+      , Str "middle"
+      , Space
+      , Image ( "" , [] , [] ) [] ( "img.png" , "" )
+      , Space
+      , Str "of"
+      , Space
+      , Str "the"
+      , Space
+      , Str "line."
+      ]
+  , Para
+      [ Str "Image"
+      , Space
+      , Str "at"
+      , Space
+      , Str "the"
+      , Space
+      , Str "line"
+      , Space
+      , Str "end."
+      , Space
+      , Image ( "" , [] , [] ) [] ( "img.png" , "" )
+      ]
+  , Para
+      [ Image ( "" , [] , [] ) [] ( "img.png" , "" )
+      , SoftBreak
+      , Image ( "" , [] , [] ) [] ( "img.png" , "" )
+      , SoftBreak
+      , Image ( "" , [] , [] ) [] ( "img.png" , "" )
+      ]
+  , Para
+      [ Image ( "" , [] , [] ) [] ( "img.png" , "" )
+      , Image ( "" , [] , [] ) [] ( "img.png" , "" )
+      ]
+  , Para
+      [ Str "Images"
+      , Space
+      , Image ( "" , [] , [] ) [] ( "img.png" , "" )
+      , Space
+      , Str "mixed"
+      , Space
+      , Image ( "" , [] , [] ) [] ( "img.png" , "" )
+      , Space
+      , Str "with"
+      , Space
+      , Image ( "" , [] , [] ) [] ( "img.png" , "" )
+      , Space
+      , Str "text."
+      ]
+  , Para
+      [ Str "Images"
+      , Space
+      , Str "glued"
+      , Space
+      , Str "together:"
+      , Space
+      , Image ( "" , [] , [] ) [] ( "img.png" , "" )
+      , Image ( "" , [] , [] ) [] ( "img.png" , "" )
+      , Image ( "" , [] , [] ) [] ( "img.png" , "" )
+      , Str "."
+      ]
+  , Para [ Str "[img.png" , Space , Str "]" ]
+  , Para [ Str "[" , Space , Str "img.png]" ]
+  , Para [ Str "[" , Space , Str "img.png" , Space , Str "]" ]
+  , Header
+      1
+      ( "numtitle" , [] , [] )
+      [ Str "Numbered" , Space , Str "Title" ]
+  , Header
+      1
+      ( "" , [] , [] )
+      [ Str "Title" , Space , Str "Level" , Space , Str "1" ]
+  , Header
+      2
+      ( "" , [] , [] )
+      [ Str "Title" , Space , Str "Level" , Space , Str "2" ]
+  , Header
+      3
+      ( "" , [] , [] )
+      [ Str "Title" , Space , Str "Level" , Space , Str "3" ]
+  , Header
+      4
+      ( "" , [] , [] )
+      [ Str "Title" , Space , Str "Level" , Space , Str "4" ]
+  , Header
+      5
+      ( "" , [] , [] )
+      [ Str "Title" , Space , Str "Level" , Space , Str "5" ]
+  , Header
+      1
+      ( "lab_el-1" , [] , [] )
+      [ Str "Title" , Space , Str "Level" , Space , Str "1" ]
+  , Header
+      2
+      ( "lab_el-2" , [] , [] )
+      [ Str "Title" , Space , Str "Level" , Space , Str "2" ]
+  , Header
+      3
+      ( "lab_el-3" , [] , [] )
+      [ Str "Title" , Space , Str "Level" , Space , Str "3" ]
+  , Header
+      4
+      ( "lab_el-4" , [] , [] )
+      [ Str "Title" , Space , Str "Level" , Space , Str "4" ]
+  , Header
+      5
+      ( "lab_el-5" , [] , [] )
+      [ Str "Title" , Space , Str "Level" , Space , Str "5" ]
+  , Header
+      3
+      ( "" , [] , [] )
+      [ Str "Title" , Space , Str "Level" , Space , Str "3" ]
+  , Header
+      3
+      ( "" , [] , [] )
+      [ Str "Title" , Space , Str "Level" , Space , Str "3" ]
+  , Header
+      3
+      ( "" , [] , [] )
+      [ Str "Title" , Space , Str "Level" , Space , Str "3" ]
+  , Header
+      3
+      ( "" , [] , [] )
+      [ Str "Title" , Space , Str "Level" , Space , Str "3" ]
+  , Header
+      3
+      ( "" , [] , [] )
+      [ Str "Title" , Space , Str "Level" , Space , Str "3" ]
+  , Header
+      3
+      ( "lab_el-9" , [] , [] )
+      [ Str "Title" , Space , Str "Level" , Space , Str "3" ]
+  , Para [ Str "+Not" , Space , Str "Title" ]
+  , Para [ Str "++Not" , Space , Str "Title+" ]
+  , Para
+      [ Str "+++Not"
+      , Space
+      , Str "Title++++"
+      , SoftBreak
+      , Str "++++++Not"
+      , Space
+      , Str "Title"
+      , Space
+      , Str "6++++++"
+      ]
+  , Para
+      [ Str "+++++++Not"
+      , Space
+      , Str "Title"
+      , Space
+      , Str "7+++++++"
+      , SoftBreak
+      , Str "+Not"
+      , Space
+      , Str "Title+"
+      , Space
+      , Str "[label1]"
+      , SoftBreak
+      , Str "+Not"
+      , Space
+      , Str "Title+["
+      , Space
+      , Str "label"
+      , Space
+      , Str "]"
+      , SoftBreak
+      , Str "+Not"
+      , Space
+      , Str "Title+[la/bel]"
+      ]
+  , Header 1 ( "title" , [] , [] ) [ Str "Title" ]
+  , Header
+      1
+      ( "" , [] , [] )
+      [ Str "Title" , Space , Str "Level" , Space , Str "1" ]
+  , Header
+      2
+      ( "" , [] , [] )
+      [ Str "Title" , Space , Str "Level" , Space , Str "2" ]
+  , Header
+      3
+      ( "" , [] , [] )
+      [ Str "Title" , Space , Str "Level" , Space , Str "3" ]
+  , Header
+      4
+      ( "" , [] , [] )
+      [ Str "Title" , Space , Str "Level" , Space , Str "4" ]
+  , Header
+      5
+      ( "" , [] , [] )
+      [ Str "Title" , Space , Str "Level" , Space , Str "5" ]
+  , Header
+      1
+      ( "lab_el-1" , [] , [] )
+      [ Str "Title" , Space , Str "Level" , Space , Str "1" ]
+  , Header
+      2
+      ( "lab_el-2" , [] , [] )
+      [ Str "Title" , Space , Str "Level" , Space , Str "2" ]
+  , Header
+      3
+      ( "lab_el-3" , [] , [] )
+      [ Str "Title" , Space , Str "Level" , Space , Str "3" ]
+  , Header
+      4
+      ( "lab_el-4" , [] , [] )
+      [ Str "Title" , Space , Str "Level" , Space , Str "4" ]
+  , Header
+      5
+      ( "lab_el-5" , [] , [] )
+      [ Str "Title" , Space , Str "Level" , Space , Str "5" ]
+  , Header
+      3
+      ( "" , [] , [] )
+      [ Str "Title" , Space , Str "Level" , Space , Str "3" ]
+  , Header
+      3
+      ( "" , [] , [] )
+      [ Str "Title" , Space , Str "Level" , Space , Str "3" ]
+  , Header
+      3
+      ( "" , [] , [] )
+      [ Str "Title" , Space , Str "Level" , Space , Str "3" ]
+  , Header
+      3
+      ( "" , [] , [] )
+      [ Str "Title" , Space , Str "Level" , Space , Str "3" ]
+  , Header
+      3
+      ( "" , [] , [] )
+      [ Str "Title" , Space , Str "Level" , Space , Str "3" ]
+  , Header
+      3
+      ( "lab_el-9" , [] , [] )
+      [ Str "Title" , Space , Str "Level" , Space , Str "3" ]
+  , Para [ Str "=Not" , Space , Str "Title" ]
+  , Para [ Str "==Not" , Space , Str "Title=" ]
+  , Para
+      [ Str "===Not"
+      , Space
+      , Str "Title===="
+      , SoftBreak
+      , Str "======Not"
+      , Space
+      , Str "Title"
+      , Space
+      , Str "6======"
+      ]
+  , Para
+      [ Str "=======Not"
+      , Space
+      , Str "Title"
+      , Space
+      , Str "7======="
+      , SoftBreak
+      , Str "=Not"
+      , Space
+      , Str "Title="
+      , Space
+      , Str "[label1]"
+      , SoftBreak
+      , Str "=Not"
+      , Space
+      , Str "Title=["
+      , Space
+      , Str "label"
+      , Space
+      , Str "]"
+      , SoftBreak
+      , Str "=Not"
+      , Space
+      , Str "Title=[la/bel]"
+      ]
+  , Header 1 ( "quote" , [] , [] ) [ Str "Quote" ]
+  , BlockQuote
+      [ Para
+          [ Str "To"
+          , Space
+          , Str "quote"
+          , Space
+          , Str "a"
+          , Space
+          , Str "paragraph,"
+          , Space
+          , Str "just"
+          , Space
+          , Str "prefix"
+          , Space
+          , Str "it"
+          , Space
+          , Str "by"
+          , Space
+          , Str "a"
+          , Space
+          , Str "TAB"
+          , SoftBreak
+          , Str "character."
+          , Space
+          , Str "All"
+          , Space
+          , Str "the"
+          , Space
+          , Str "lines"
+          , Space
+          , Str "of"
+          , Space
+          , Str "the"
+          , Space
+          , Str "paragraph"
+          , Space
+          , Str "must"
+          , SoftBreak
+          , Str "begin"
+          , Space
+          , Str "with"
+          , Space
+          , Str "a"
+          , Space
+          , Str "TAB."
+          ]
+      ]
+  , Para
+      [ Str "Any"
+      , Space
+      , Str "non-tabbed"
+      , Space
+      , Str "line"
+      , Space
+      , Str "closes"
+      , Space
+      , Str "the"
+      , Space
+      , Str "quote"
+      , Space
+      , Str "block."
+      ]
+  , BlockQuote
+      [ Para
+          [ Str "The"
+          , Space
+          , Str "number"
+          , Space
+          , Str "of"
+          , Space
+          , Str "leading"
+          , Space
+          , Str "TABs"
+          , Space
+          , Str "identifies"
+          , Space
+          , Str "the"
+          , Space
+          , Str "quote"
+          , SoftBreak
+          , Str "block"
+          , Space
+          , Str "depth."
+          , Space
+          , Str "This"
+          , Space
+          , Str "is"
+          , Space
+          , Str "quote"
+          , Space
+          , Str "level"
+          , Space
+          , Str "1."
+          ]
+      , BlockQuote
+          [ Para
+              [ Str "With"
+              , Space
+              , Str "two"
+              , Space
+              , Str "TABs,"
+              , Space
+              , Str "we"
+              , Space
+              , Str "are"
+              , Space
+              , Str "on"
+              , Space
+              , Str "the"
+              , Space
+              , Str "quote"
+              , SoftBreak
+              , Str "level"
+              , Space
+              , Str "2."
+              ]
+          , BlockQuote
+              [ Para
+                  [ Str "The"
+                  , Space
+                  , Str "more"
+                  , Space
+                  , Str "TABs,"
+                  , Space
+                  , Str "more"
+                  , Space
+                  , Str "deep"
+                  , Space
+                  , Str "is"
+                  , SoftBreak
+                  , Str "the"
+                  , Space
+                  , Str "quote"
+                  , Space
+                  , Str "level."
+                  ]
+              , BlockQuote
+                  [ Para
+                      [ Str "There"
+                      , Space
+                      , Str "isn't"
+                      , Space
+                      , Str "a"
+                      , Space
+                      , Str "limit."
+                      ]
+                  ]
+              ]
+          ]
+      ]
+  , BlockQuote
+      [ BlockQuote
+          [ BlockQuote
+              [ BlockQuote
+                  [ Para
+                      [ Str "This"
+                      , Space
+                      , Str "quote"
+                      , Space
+                      , Str "starts"
+                      , Space
+                      , Str "at"
+                      , SoftBreak
+                      , Str "level"
+                      , Space
+                      , Str "4."
+                      ]
+                  ]
+              , Para
+                  [ Str "Then"
+                  , Space
+                  , Str "its"
+                  , Space
+                  , Str "depth"
+                  , Space
+                  , Str "is"
+                  , Space
+                  , Str "decreased."
+                  ]
+              ]
+          , Para
+              [ Str "Counting"
+              , Space
+              , Str "down,"
+              , Space
+              , Str "one"
+              , Space
+              , Str "by"
+              , Space
+              , Str "one."
+              ]
+          ]
+      , Para
+          [ Str "Until"
+          , Space
+          , Str "the"
+          , Space
+          , Str "level"
+          , Space
+          , Str "1."
+          ]
+      ]
+  , BlockQuote
+      [ BlockQuote
+          [ BlockQuote
+              [ Para
+                  [ Str "Unlike"
+                  , Space
+                  , Str "lists,"
+                  , Space
+                  , Str "any"
+                  , Space
+                  , Str "quote"
+                  , Space
+                  , Str "block"
+                  , Space
+                  , Str "is"
+                  , SoftBreak
+                  , Str "independent,"
+                  , Space
+                  , Str "not"
+                  , Space
+                  , Str "part"
+                  , Space
+                  , Str "of"
+                  , Space
+                  , Str "a"
+                  , Space
+                  , Str "tree."
+                  ]
+              ]
+          ]
+      , Para
+          [ Str "The"
+          , Space
+          , Str "TAB"
+          , Space
+          , Str "count"
+          , Space
+          , Str "don't"
+          , Space
+          , Str "need"
+          , Space
+          , Str "to"
+          , Space
+          , Str "be"
+          , Space
+          , Str "incremental"
+          , SoftBreak
+          , Str "by"
+          , Space
+          , Str "one."
+          ]
+      , BlockQuote
+          [ BlockQuote
+              [ BlockQuote
+                  [ Para
+                      [ Str "The"
+                      , Space
+                      , Str "nesting"
+                      , Space
+                      , Str "don't"
+                      , Space
+                      , Str "need"
+                      , SoftBreak
+                      , Str "to"
+                      , Space
+                      , Str "follow"
+                      , Space
+                      , Str "any"
+                      , Space
+                      , Str "rule."
+                      ]
+                  ]
+              ]
+          , Para
+              [ Str "Quotes"
+              , Space
+              , Str "can"
+              , Space
+              , Str "be"
+              , Space
+              , Str "opened"
+              , Space
+              , Str "and"
+              , Space
+              , Str "closed"
+              , SoftBreak
+              , Str "in"
+              , Space
+              , Str "any"
+              , Space
+              , Str "way."
+              ]
+          , BlockQuote
+              [ BlockQuote
+                  [ BlockQuote
+                      [ Para [ Str "You" , Space , Str "choose." ] ]
+                  ]
+              ]
+          ]
+      ]
+  , BlockQuote
+      [ Para
+          [ Str "Some"
+          , Space
+          , Str "targets"
+          , Space
+          , Str "(as"
+          , Space
+          , Str "sgml)"
+          , Space
+          , Str "don't"
+          , Space
+          , Str "support"
+          , Space
+          , Str "the"
+          , SoftBreak
+          , Str "nesting"
+          , Space
+          , Str "of"
+          , Space
+          , Str "quotes."
+          , Space
+          , Str "There"
+          , Space
+          , Str "is"
+          , Space
+          , Str "only"
+          , Space
+          , Str "one"
+          , Space
+          , Str "quote"
+          , SoftBreak
+          , Str "level."
+          ]
+      , BlockQuote
+          [ Para
+              [ Str "In"
+              , Space
+              , Str "this"
+              , Space
+              , Str "case,"
+              , Space
+              , Str "no"
+              , Space
+              , Str "matter"
+              , Space
+              , Str "how"
+              , Space
+              , Str "much"
+              , SoftBreak
+              , Str "TABs"
+              , Space
+              , Str "are"
+              , Space
+              , Str "used"
+              , Space
+              , Str "to"
+              , Space
+              , Str "define"
+              , Space
+              , Str "the"
+              , Space
+              , Str "quote"
+              , SoftBreak
+              , Str "block,"
+              , Space
+              , Str "it"
+              , Space
+              , Str "always"
+              , Space
+              , Str "will"
+              , Space
+              , Str "be"
+              , Space
+              , Str "level"
+              , Space
+              , Str "1."
+              ]
+          ]
+      ]
+  , BlockQuote
+      [ Para
+          [ Str "Spaces"
+          , Space
+          , Str "AFTER"
+          , Space
+          , Str "the"
+          , Space
+          , Str "TAB"
+          , Space
+          , Str "character"
+          , Space
+          , Str "are"
+          , Space
+          , Str "allowed."
+          , SoftBreak
+          , Str "But"
+          , Space
+          , Str "be"
+          , Space
+          , Str "careful,"
+          , Space
+          , Str "it"
+          , Space
+          , Str "can"
+          , Space
+          , Str "be"
+          , Space
+          , Str "confusing."
+          ]
+      ]
+  , Para
+      [ Str "Spaces"
+      , Space
+      , Str "BEFORE"
+      , Space
+      , Str "the"
+      , Space
+      , Str "TAB"
+      , Space
+      , Str "character"
+      , SoftBreak
+      , Str "invalidate"
+      , Space
+      , Str "the"
+      , Space
+      , Str "mark."
+      , Space
+      , Str "It's"
+      , Space
+      , Str "not"
+      , Space
+      , Str "quote."
+      ]
+  , BlockQuote
+      [ Para
+          [ Str "Paragraph"
+          , Space
+          , Str "breaks"
+          , Space
+          , Str "inside"
+          , Space
+          , Str "a"
+          , Space
+          , Str "quote"
+          , Space
+          , Str "aren't"
+          , SoftBreak
+          , Str "possible."
+          ]
+      , Para
+          [ Str "This"
+          , Space
+          , Str "sample"
+          , Space
+          , Str "are"
+          , Space
+          , Str "two"
+          , Space
+          , Str "separated"
+          , Space
+          , Str "quoted"
+          , SoftBreak
+          , Str "paragraphs,"
+          , Space
+          , Str "not"
+          , Space
+          , Str "a"
+          , Space
+          , Str "quote"
+          , Space
+          , Str "block"
+          , Space
+          , Str "with"
+          , SoftBreak
+          , Str "two"
+          , Space
+          , Str "paragraphs"
+          , Space
+          , Str "inside."
+          ]
+      ]
+  , BlockQuote
+      [ Para
+          [ Str "The"
+          , Space
+          , Str "end"
+          , Space
+          , Str "of"
+          , Space
+          , Str "the"
+          , Space
+          , Str "file"
+          , Space
+          , Str "(EOF)"
+          , Space
+          , Str "closes"
+          , Space
+          , Str "the"
+          , SoftBreak
+          , Str "currently"
+          , Space
+          , Str "open"
+          , Space
+          , Str "quote"
+          , Space
+          , Str "block."
+          ]
+      ]
+  , Header 1 ( "raw" , [] , [] ) [ Str "Raw" ]
+  , Para [ Str "A raw line.\n" ]
+  , Para [ Str "  Another raw line, with leading spaces.\n" ]
+  , Para
+      [ Str "A raw area delimited\n       by lines with marks.\n"
+      ]
+  , Para
+      [ Str
+          "Trailing spaces and TABs after the area marks\nare allowed, but not encouraged nor documented.\n"
+      ]
+  , Para
+      [ Str "\"\"\"Not"
+      , Space
+      , Str "a"
+      , Space
+      , Str "raw"
+      , Space
+      , Str "line,"
+      , Space
+      , Str "need"
+      , Space
+      , Str "one"
+      , Space
+      , Str "space"
+      , Space
+      , Str "after"
+      , Space
+      , Str "mark."
+      ]
+  , Para
+      [ Str "\"\"\""
+      , SoftBreak
+      , Str "Not"
+      , Space
+      , Str "a"
+      , Space
+      , Str "raw"
+      , Space
+      , Str "area."
+      , SoftBreak
+      , Str "The"
+      , Space
+      , Str "marks"
+      , Space
+      , Str "must"
+      , Space
+      , Str "be"
+      , Space
+      , Str "at"
+      , Space
+      , Str "the"
+      , Space
+      , Str "line"
+      , Space
+      , Str "beginning,"
+      , SoftBreak
+      , Str "no"
+      , Space
+      , Str "leading"
+      , Space
+      , Str "spaces."
+      , SoftBreak
+      , Str "\"\"\""
+      ]
+  , Para
+      [ Str
+          "The end of the file (EOF) closes\nthe currently open raw area.\n"
+      ]
+  , Header 1 ( "verbatim" , [] , [] ) [ Str "Verbatim" ]
+  , CodeBlock ( "" , [] , [] ) "A verbatim line.\n"
+  , CodeBlock
+      ( "" , [] , [] )
+      "  Another verbatim line, with leading spaces.\n"
+  , CodeBlock
+      ( "" , [] , [] )
+      "A verbatim area delimited\n       by lines with marks.\n"
+  , CodeBlock
+      ( "" , [] , [] )
+      "Trailing spaces and TABs after the area marks\nare allowed, but not encouraged nor documented.\n"
+  , Para
+      [ Str "```Not"
+      , Space
+      , Str "a"
+      , Space
+      , Str "verbatim"
+      , Space
+      , Str "line,"
+      , Space
+      , Str "need"
+      , Space
+      , Str "one"
+      , Space
+      , Str "space"
+      , Space
+      , Str "after"
+      , Space
+      , Str "mark."
+      ]
+  , Para
+      [ Str "```"
+      , SoftBreak
+      , Str "Not"
+      , Space
+      , Str "a"
+      , Space
+      , Str "verbatim"
+      , Space
+      , Str "area."
+      , SoftBreak
+      , Str "The"
+      , Space
+      , Str "marks"
+      , Space
+      , Str "must"
+      , Space
+      , Str "be"
+      , Space
+      , Str "at"
+      , Space
+      , Str "the"
+      , Space
+      , Str "line"
+      , Space
+      , Str "beginning,"
+      , SoftBreak
+      , Str "no"
+      , Space
+      , Str "leading"
+      , Space
+      , Str "spaces."
+      , SoftBreak
+      , Str "```"
+      ]
+  , CodeBlock
+      ( "" , [] , [] )
+      "The end of the file (EOF) closes\nthe currently open verbatim area.\n"
+  , Header
+      1
+      ( "deflist" , [] , [] )
+      [ Str "Definition" , Space , Str "List" ]
+  , DefinitionList
+      [ ( [ Str "Definition" , Space , Str "list" ]
+        , [ [ Plain
+                [ Str "A"
+                , Space
+                , Str "list"
+                , Space
+                , Str "with"
+                , Space
+                , Str "terms"
+                ]
+            ]
+          ]
+        )
+      , ( [ Str "Start"
+          , Space
+          , Str "term"
+          , Space
+          , Str "with"
+          , Space
+          , Str "colon"
+          ]
+        , [ [ Plain
+                [ Str "And"
+                , Space
+                , Str "its"
+                , Space
+                , Str "definition"
+                , Space
+                , Str "follows"
+                ]
+            ]
+          ]
+        )
+      ]
+  , Header
+      1
+      ( "numlist" , [] , [] )
+      [ Str "Numbered" , Space , Str "List" ]
+  , Para
+      [ Str "See"
+      , Space
+      , Link ( "" , [] , [] ) [ Str "List" ] ( "#list" , "" )
+      , Str ","
+      , Space
+      , Str "the"
+      , Space
+      , Str "same"
+      , Space
+      , Str "rules"
+      , Space
+      , Str "apply."
+      ]
+  , Header 1 ( "list" , [] , [] ) [ Str "List" ]
+  , BulletList
+      [ [ Plain
+            [ Str "Use"
+            , Space
+            , Str "the"
+            , Space
+            , Str "hyphen"
+            , Space
+            , Str "to"
+            , Space
+            , Str "prefix"
+            , Space
+            , Str "list"
+            , Space
+            , Str "items."
+            ]
+        ]
+      , [ Plain
+            [ Str "There"
+            , Space
+            , Str "must"
+            , Space
+            , Str "be"
+            , Space
+            , Str "one"
+            , Space
+            , Str "space"
+            , Space
+            , Str "after"
+            , Space
+            , Str "the"
+            , Space
+            , Str "hyphen."
+            ]
+        ]
+      , [ Plain
+            [ Str "The"
+            , Space
+            , Str "list"
+            , Space
+            , Str "is"
+            , Space
+            , Str "closed"
+            , Space
+            , Str "by"
+            , Space
+            , Str "two"
+            , Space
+            , Str "consecutive"
+            , Space
+            , Str "blank"
+            , Space
+            , Str "lines."
+            ]
+        ]
+      ]
+  , BulletList
+      [ [ Plain
+            [ Str "The"
+            , Space
+            , Str "list"
+            , Space
+            , Str "can"
+            , Space
+            , Str "be"
+            , Space
+            , Str "indented"
+            , Space
+            , Str "on"
+            , Space
+            , Str "the"
+            , Space
+            , Str "source"
+            , Space
+            , Str "document."
+            ]
+        ]
+      , [ Plain
+            [ Str "You"
+            , Space
+            , Str "can"
+            , Space
+            , Str "use"
+            , Space
+            , Str "any"
+            , Space
+            , Str "number"
+            , Space
+            , Str "of"
+            , Space
+            , Str "spaces."
+            ]
+        ]
+      , [ Plain
+            [ Str "The"
+            , Space
+            , Str "result"
+            , Space
+            , Str "will"
+            , Space
+            , Str "be"
+            , Space
+            , Str "the"
+            , Space
+            , Str "same."
+            ]
+        ]
+      ]
+  , BulletList
+      [ [ Para
+            [ Str "Let"
+            , Space
+            , Str "one"
+            , Space
+            , Str "blank"
+            , Space
+            , Str "line"
+            , Space
+            , Str "between"
+            , Space
+            , Str "the"
+            , Space
+            , Str "list"
+            , Space
+            , Str "items."
+            ]
+        ]
+      , [ Para
+            [ Str "It"
+            , Space
+            , Str "will"
+            , Space
+            , Str "be"
+            , Space
+            , Str "maintained"
+            , Space
+            , Str "on"
+            , Space
+            , Str "the"
+            , Space
+            , Str "conversion."
+            ]
+        ]
+      , [ Para
+            [ Str "Some"
+            , Space
+            , Str "targets"
+            , Space
+            , Str "don't"
+            , Space
+            , Str "support"
+            , Space
+            , Str "this"
+            , Space
+            , Str "behavior."
+            ]
+        ]
+      , [ Para
+            [ Str "This"
+            , Space
+            , Str "one"
+            , Space
+            , Str "was"
+            , Space
+            , Str "separated"
+            , Space
+            , Str "by"
+            , Space
+            , Str "a"
+            , Space
+            , Str "line"
+            , Space
+            , Str "with"
+            , Space
+            , Str "blanks."
+            , SoftBreak
+            , Str "You"
+            , Space
+            , Str "can"
+            , Space
+            , Str "also"
+            , Space
+            , Str "put"
+            , Space
+            , Str "a"
+            , Space
+            , Str "blank"
+            , Space
+            , Str "line"
+            , Space
+            , Str "inside"
+            ]
+        , Para
+            [ Str "the"
+            , Space
+            , Str "item"
+            , Space
+            , Str "contents"
+            , Space
+            , Str "and"
+            , Space
+            , Str "it"
+            , Space
+            , Str "will"
+            , Space
+            , Str "be"
+            , Space
+            , Str "preserved."
+            ]
+        ]
+      ]
+  , Para
+      [ Str "-This"
+      , Space
+      , Str "is"
+      , Space
+      , Str "not"
+      , Space
+      , Str "a"
+      , Space
+      , Str "list"
+      , Space
+      , Str "(no"
+      , Space
+      , Str "space)"
+      ]
+  , Para
+      [ Str "-"
+      , Space
+      , Str "This"
+      , Space
+      , Str "is"
+      , Space
+      , Str "not"
+      , Space
+      , Str "a"
+      , Space
+      , Str "list"
+      , Space
+      , Str "(more"
+      , Space
+      , Str "than"
+      , Space
+      , Str "one"
+      , Space
+      , Str "space)"
+      ]
+  , Para
+      [ Str "-"
+      , Space
+      , Str "This"
+      , Space
+      , Str "is"
+      , Space
+      , Str "not"
+      , Space
+      , Str "a"
+      , Space
+      , Str "list"
+      , Space
+      , Str "(a"
+      , Space
+      , Str "TAB"
+      , Space
+      , Str "instead"
+      , Space
+      , Str "the"
+      , Space
+      , Str "space)"
+      ]
+  , BulletList
+      [ [ BulletList
+            [ [ Plain
+                  [ Str "This"
+                  , Space
+                  , Str "is"
+                  , Space
+                  , Str "a"
+                  , Space
+                  , Str "list"
+                  ]
+              ]
+            ]
+        ]
+      , [ OrderedList
+            ( 1 , DefaultStyle , DefaultDelim )
+            [ [ Plain
+                  [ Str "This"
+                  , Space
+                  , Str "is"
+                  , Space
+                  , Str "a"
+                  , Space
+                  , Str "list"
+                  ]
+              ]
+            ]
+        ]
+      , [ DefinitionList
+            [ ( [ Str "This"
+                , Space
+                , Str "is"
+                , Space
+                , Str "a"
+                , Space
+                , Str "list"
+                ]
+              , [ [] ]
+              )
+            ]
+        ]
+      ]
+  , BulletList
+      [ [ Plain
+            [ Str "This"
+            , Space
+            , Str "is"
+            , Space
+            , Str "the"
+            , Space
+            , Str "\"mother\""
+            , Space
+            , Str "list"
+            , Space
+            , Str "first"
+            , Space
+            , Str "item."
+            ]
+        ]
+      , [ Plain
+            [ Str "Here"
+            , Space
+            , Str "is"
+            , Space
+            , Str "the"
+            , Space
+            , Str "second,"
+            , Space
+            , Str "but"
+            , Space
+            , Str "inside"
+            , Space
+            , Str "this"
+            , Space
+            , Str "item,"
+            ]
+        , BulletList
+            [ [ Plain
+                  [ Str "there"
+                  , Space
+                  , Str "is"
+                  , Space
+                  , Str "a"
+                  , Space
+                  , Str "sublist,"
+                  , Space
+                  , Str "with"
+                  , Space
+                  , Str "its"
+                  , Space
+                  , Str "own"
+                  , Space
+                  , Str "items."
+                  ]
+              ]
+            , [ Plain
+                  [ Str "Note"
+                  , Space
+                  , Str "that"
+                  , Space
+                  , Str "the"
+                  , Space
+                  , Str "items"
+                  , Space
+                  , Str "of"
+                  , Space
+                  , Str "the"
+                  , Space
+                  , Str "same"
+                  , Space
+                  , Str "sublist"
+                  ]
+              ]
+            , [ Plain
+                  [ Str "must"
+                  , Space
+                  , Str "have"
+                  , Space
+                  , Str "the"
+                  , Space
+                  , Str "same"
+                  , Space
+                  , Str "indentation."
+                  ]
+              , BulletList
+                  [ [ Plain
+                        [ Str "And"
+                        , Space
+                        , Str "this"
+                        , Space
+                        , Str "can"
+                        , Space
+                        , Str "go"
+                        , Space
+                        , Str "on,"
+                        , Space
+                        , Str "opening"
+                        , Space
+                        , Str "sublists."
+                        ]
+                    , BulletList
+                        [ [ Plain
+                              [ Str "Just"
+                              , Space
+                              , Str "add"
+                              , Space
+                              , Str "leading"
+                              , Space
+                              , Str "spaces"
+                              , Space
+                              , Str "before"
+                              , Space
+                              , Str "the"
+                              ]
+                          ]
+                        , [ Plain
+                              [ Str "hyphen"
+                              , Space
+                              , Str "and"
+                              , Space
+                              , Str "sublists"
+                              , Space
+                              , Str "will"
+                              , Space
+                              , Str "be"
+                              , Space
+                              , Str "opened."
+                              ]
+                          ]
+                        , [ Plain
+                              [ Str "The"
+                              , Space
+                              , Str "two"
+                              , Space
+                              , Str "blank"
+                              , Space
+                              , Str "lines"
+                              , Space
+                              , Str "closes"
+                              , Space
+                              , Str "them"
+                              , Space
+                              , Str "all."
+                              ]
+                          ]
+                        ]
+                    ]
+                  ]
+              ]
+            ]
+        ]
+      ]
+  , BulletList
+      [ [ Plain
+            [ Str "When"
+            , Space
+            , Str "nesting"
+            , Space
+            , Str "lists,"
+            , Space
+            , Str "the"
+            , Space
+            , Str "additional"
+            , Space
+            , Str "spaces"
+            , Space
+            , Str "are"
+            , Space
+            , Str "free."
+            ]
+        ]
+      , [ Plain
+            [ Str "You"
+            , Space
+            , Str "can"
+            , Space
+            , Str "add"
+            , Space
+            , Str "just"
+            , Space
+            , Str "one,"
+            ]
+        , BulletList
+            [ [ Plain [ Str "or" , Space , Str "many." ]
+              , BulletList
+                  [ [ Plain
+                        [ Str "What"
+                        , Space
+                        , Str "matters"
+                        , Space
+                        , Str "is"
+                        , Space
+                        , Str "to"
+                        , Space
+                        , Str "put"
+                        , Space
+                        , Str "more"
+                        , Space
+                        , Str "than"
+                        , Space
+                        , Str "the"
+                        , Space
+                        , Str "previous."
+                        ]
+                    ]
+                  , [ Plain
+                        [ Str "But"
+                        , Space
+                        , Str "remember"
+                        , Space
+                        , Str "that"
+                        , Space
+                        , Str "the"
+                        , Space
+                        , Str "other"
+                        , Space
+                        , Str "items"
+                        , Space
+                        , Str "of"
+                        , Space
+                        , Str "the"
+                        , Space
+                        , Str "same"
+                        , Space
+                        , Str "list"
+                        ]
+                    ]
+                  , [ Plain
+                        [ Str "must"
+                        , Space
+                        , Str "use"
+                        , Space
+                        , Str "the"
+                        , Space
+                        , Str "same"
+                        , Space
+                        , Str "indentation."
+                        ]
+                    ]
+                  ]
+              ]
+            ]
+        ]
+      ]
+  , BulletList
+      [ [ Plain
+            [ Str "There"
+            , Space
+            , Str "is"
+            , Space
+            , Str "not"
+            , Space
+            , Str "a"
+            , Space
+            , Str "depth"
+            , Space
+            , Str "limit,"
+            ]
+        , BulletList
+            [ [ Plain
+                  [ Str "you"
+                  , Space
+                  , Str "can"
+                  , Space
+                  , Str "go"
+                  , Space
+                  , Str "deeper"
+                  , Space
+                  , Str "and"
+                  , Space
+                  , Str "deeper."
+                  ]
+              , BulletList
+                  [ [ Plain
+                        [ Str "But"
+                        , Space
+                        , Str "some"
+                        , Space
+                        , Str "targets"
+                        , Space
+                        , Str "may"
+                        , Space
+                        , Str "have"
+                        , Space
+                        , Str "restrictions."
+                        ]
+                    , BulletList
+                        [ [ Plain
+                              [ Str "The"
+                              , Space
+                              , Str "LaTeX"
+                              , Space
+                              , Str "maximum"
+                              , Space
+                              , Str "is"
+                              , Space
+                              , Str "here,"
+                              , Space
+                              , Str "4"
+                              , Space
+                              , Str "levels."
+                              ]
+                          ]
+                        ]
+                    ]
+                  ]
+              ]
+            ]
+        ]
+      ]
+  , BulletList
+      [ [ Plain
+            [ Str "Reverse"
+            , Space
+            , Str "nesting"
+            , Space
+            , Str "doesn't"
+            , Space
+            , Str "work."
+            ]
+        ]
+      , [ Plain
+            [ Str "Because"
+            , Space
+            , Str "a"
+            , Space
+            , Str "sublist"
+            , Space
+            , Str "*must*"
+            , Space
+            , Str "have"
+            , Space
+            , Str "a"
+            , Space
+            , Str "mother"
+            , Space
+            , Str "list."
+            ]
+        ]
+      , [ Plain
+            [ Str "It's"
+            , Space
+            , Str "the"
+            , Space
+            , Str "list"
+            , Space
+            , Str "concept,"
+            , Space
+            , Str "not"
+            , Space
+            , Str "a"
+            , Space
+            , Str "txt2tags"
+            , Space
+            , Str "limitation."
+            ]
+        ]
+      , [ Plain
+            [ Str "All"
+            , Space
+            , Str "this"
+            , Space
+            , Str "sublists"
+            , Space
+            , Str "will"
+            , Space
+            , Str "be"
+            , Space
+            , Str "bumped"
+            , Space
+            , Str "to"
+            , Space
+            , Str "mother"
+            , Space
+            , Str "lists."
+            ]
+        ]
+      , [ Plain
+            [ Str "At"
+            , Space
+            , Str "level"
+            , Space
+            , Str "1,"
+            , Space
+            , Str "like"
+            , Space
+            , Str "this"
+            , Space
+            , Str "one."
+            ]
+        ]
+      ]
+  , BulletList
+      [ [ Plain [ Str "Level" , Space , Str "1" ]
+        , BulletList
+            [ [ Plain [ Str "Level" , Space , Str "2" ]
+              , BulletList
+                  [ [ Plain [ Str "Level" , Space , Str "3" ]
+                    , BulletList
+                        [ [ Plain [ Str "Level" , Space , Str "4" ] ] ]
+                    ]
+                  , [ Plain
+                        [ Str "Level"
+                        , Space
+                        , Str "3"
+                        , Space
+                        , Str "--"
+                        , Space
+                        , Str "(closed"
+                        , Space
+                        , Str "Level"
+                        , Space
+                        , Str "4)"
+                        ]
+                    ]
+                  ]
+              ]
+            , [ Plain
+                  [ Str "Level"
+                  , Space
+                  , Str "2"
+                  , Space
+                  , Str "--"
+                  , Space
+                  , Str "(closed"
+                  , Space
+                  , Str "Level"
+                  , Space
+                  , Str "3)"
+                  ]
+              ]
+            ]
+        ]
+      , [ Plain
+            [ Str "Level"
+            , Space
+            , Str "1"
+            , Space
+            , Str "--"
+            , Space
+            , Str "(closed"
+            , Space
+            , Str "Level"
+            , Space
+            , Str "2)"
+            ]
+        ]
+      ]
+  , BulletList
+      [ [ Plain [ Str "Level" , Space , Str "1" ]
+        , BulletList
+            [ [ Plain [ Str "Level" , Space , Str "2" ]
+              , BulletList
+                  [ [ Plain [ Str "Level" , Space , Str "3" ]
+                    , BulletList
+                        [ [ Plain [ Str "Level" , Space , Str "4" ] ] ]
+                    ]
+                  ]
+              ]
+            ]
+        ]
+      , [ Plain
+            [ Str "Level"
+            , Space
+            , Str "1"
+            , Space
+            , Str "--"
+            , Space
+            , Str "(closed"
+            , Space
+            , Str "Level"
+            , Space
+            , Str "4,"
+            , Space
+            , Str "Level"
+            , Space
+            , Str "3"
+            , Space
+            , Str "and"
+            , Space
+            , Str "Level"
+            , Space
+            , Str "2)"
+            ]
+        ]
+      ]
+  , BulletList
+      [ [ Para [ Str "Level" , Space , Str "1" ]
+        , BulletList
+            [ [ Para
+                  [ Str "Level"
+                  , Space
+                  , Str "2"
+                  , Space
+                  , Str "--"
+                  , Space
+                  , Str "blank"
+                  , Space
+                  , Str "BEFORE"
+                  , Space
+                  , Str "and"
+                  , Space
+                  , Str "AFTER"
+                  , Space
+                  , Str "(in)"
+                  ]
+              , BulletList
+                  [ [ Plain [ Str "Level" , Space , Str "3" ] ] ]
+              ]
+            ]
+        ]
+      ]
+  , BulletList [ [ Plain [ Str "Level" , Space , Str "4" ] ] ]
+  , BulletList
+      [ [ Para [ Str "Level" , Space , Str "3" ] ]
+      , [ Para
+            [ Str "Level"
+            , Space
+            , Str "2"
+            , Space
+            , Str "--"
+            , Space
+            , Str "blank"
+            , Space
+            , Str "BEFORE"
+            , Space
+            , Str "and"
+            , Space
+            , Str "AFTER"
+            , Space
+            , Str "(out)"
+            ]
+        ]
+      , [ Para [ Str "Level" , Space , Str "1" ]
+        , BulletList
+            [ [ Para
+                  [ Str "Level"
+                  , Space
+                  , Str "2"
+                  , Space
+                  , Str "--"
+                  , Space
+                  , Str "blank"
+                  , Space
+                  , Str "BEFORE"
+                  , Space
+                  , Str "(spaces)"
+                  , Space
+                  , Str "and"
+                  , Space
+                  , Str "AFTER"
+                  , Space
+                  , Str "(TAB)"
+                  ]
+              , BulletList
+                  [ [ Plain [ Str "Level" , Space , Str "3" ] ] ]
+              ]
+            ]
+        ]
+      ]
+  , BulletList
+      [ [ Plain [ Str "Level" , Space , Str "1" ]
+        , BulletList
+            [ [ Plain [ Str "Level" , Space , Str "2" ]
+              , BulletList
+                  [ [ Plain [ Str "Level" , Space , Str "3" ]
+                    , BulletList
+                        [ [ Plain [ Str "Level" , Space , Str "4" ] ]
+                        , [ Plain
+                              [ Str "Level"
+                              , Space
+                              , Str "3.5"
+                              , Space
+                              , Str "???"
+                              ]
+                          ]
+                        ]
+                    ]
+                  , [ Plain [ Str "Level" , Space , Str "3" ] ]
+                  , [ Plain
+                        [ Str "Level"
+                        , Space
+                        , Str "2.5"
+                        , Space
+                        , Str "???"
+                        ]
+                    ]
+                  ]
+              ]
+            , [ Plain [ Str "Level" , Space , Str "2" ] ]
+            , [ Plain
+                  [ Str "Level"
+                  , Space
+                  , Str "1.5"
+                  , Space
+                  , Str "???"
+                  ]
+              ]
+            ]
+        ]
+      , [ Plain [ Str "Level" , Space , Str "1" ] ]
+      ]
+  , BulletList
+      [ [ Plain
+            [ Str "This"
+            , Space
+            , Str "list"
+            , Space
+            , Str "is"
+            , Space
+            , Str "closed"
+            , Space
+            , Str "by"
+            , Space
+            , Str "a"
+            , Space
+            , Str "line"
+            , Space
+            , Str "with"
+            , Space
+            , Str "spaces"
+            , Space
+            , Str "and"
+            , Space
+            , Str "other"
+            , Space
+            , Str "with"
+            , Space
+            , Str "TABs"
+            ]
+        ]
+      ]
+  , BulletList
+      [ [ Plain
+            [ Str "This"
+            , Space
+            , Str "list"
+            , Space
+            , Str "is"
+            , Space
+            , Str "NOT"
+            , Space
+            , Str "closed"
+            , Space
+            , Str "by"
+            , Space
+            , Str "two"
+            , Space
+            , Str "comment"
+            , Space
+            , Str "lines"
+            ]
+        ]
+      ]
+  , BulletList
+      [ [ Plain
+            [ Str "This"
+            , Space
+            , Str "list"
+            , Space
+            , Str "is"
+            , Space
+            , Str "closed"
+            , Space
+            , Str "by"
+            , Space
+            , Str "a"
+            , Space
+            , Str "line"
+            , Space
+            , Str "with"
+            , Space
+            , Str "spaces"
+            , Space
+            , Str "and"
+            , Space
+            , Str "TAB,"
+            ]
+        ]
+      , [ Plain
+            [ Str "then"
+            , Space
+            , Str "a"
+            , Space
+            , Str "comment"
+            , Space
+            , Str "line,"
+            , Space
+            , Str "then"
+            , Space
+            , Str "an"
+            , Space
+            , Str "empty"
+            , Space
+            , Str "line."
+            ]
+        ]
+      ]
+  , BulletList
+      [ [ Plain [ Str "Level" , Space , Str "1" ]
+        , BulletList
+            [ [ Plain [ Str "Level" , Space , Str "2" ]
+              , BulletList
+                  [ [ Plain [ Str "Level" , Space , Str "3" ] ] ]
+              , Plain
+                  [ Str "-"
+                  , SoftBreak
+                  , Str "Level"
+                  , Space
+                  , Str "2"
+                  ]
+              ]
+            ]
+        , Plain
+            [ Str "-" , SoftBreak , Str "Level" , Space , Str "1" ]
+        ]
+      ]
+  , Para [ Str "-" ]
+  , BulletList
+      [ [ Plain
+            [ Str "Empty"
+            , Space
+            , Str "item"
+            , Space
+            , Str "with"
+            , Space
+            , Str "trailing"
+            , Space
+            , Str "spaces."
+            ]
+        ]
+      ]
+  , Para [ Str "-" ]
+  , BulletList
+      [ [ Plain
+            [ Str "Empty"
+            , Space
+            , Str "item"
+            , Space
+            , Str "with"
+            , Space
+            , Str "trailing"
+            , Space
+            , Str "TAB."
+            ]
+        ]
+      ]
+  , Para [ Str "-" ]
+  , BulletList
+      [ [ Plain
+            [ Str "If"
+            , Space
+            , Str "the"
+            , Space
+            , Str "end"
+            , Space
+            , Str "of"
+            , Space
+            , Str "the"
+            , Space
+            , Str "file"
+            , Space
+            , Str "(EOF)"
+            , Space
+            , Str "is"
+            , Space
+            , Str "hit,"
+            ]
+        , BulletList
+            [ [ Plain
+                  [ Str "all"
+                  , Space
+                  , Str "the"
+                  , Space
+                  , Str "currently"
+                  , Space
+                  , Str "opened"
+                  , Space
+                  , Str "list"
+                  , Space
+                  , Str "are"
+                  , Space
+                  , Str "closed,"
+                  ]
+              , BulletList
+                  [ [ Plain
+                        [ Str "just"
+                        , Space
+                        , Str "like"
+                        , Space
+                        , Str "when"
+                        , Space
+                        , Str "using"
+                        , Space
+                        , Str "the"
+                        , Space
+                        , Str "two"
+                        , Space
+                        , Str "blank"
+                        , Space
+                        , Str "lines."
+                        ]
+                    ]
+                  ]
+              ]
+            ]
+        ]
+      ]
+  , Header 1 ( "table" , [] , [] ) [ Str "Table" ]
+  , Table
+      ( "" , [] , [] )
+      (Caption Nothing [])
+      [ ( AlignRight , ColWidthDefault ) ]
+      (TableHead ( "" , [] , [] ) [])
+      [ TableBody
+          ( "" , [] , [] )
+          (RowHeadColumns 0)
+          []
+          [ Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "Cell" , Space , Str "1" ] ]
+              ]
+          ]
+      ]
+      (TableFoot ( "" , [] , [] ) [])
+  , Table
+      ( "" , [] , [] )
+      (Caption Nothing [])
+      [ ( AlignCenter , ColWidthDefault )
+      , ( AlignCenter , ColWidthDefault )
+      , ( AlignRight , ColWidthDefault )
+      ]
+      (TableHead ( "" , [] , [] ) [])
+      [ TableBody
+          ( "" , [] , [] )
+          (RowHeadColumns 0)
+          []
+          [ Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "Cell" , Space , Str "1" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "Cell" , Space , Str "2" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "Cell" , Space , Str "3" ] ]
+              ]
+          ]
+      ]
+      (TableFoot ( "" , [] , [] ) [])
+  , Table
+      ( "" , [] , [] )
+      (Caption Nothing [])
+      [ ( AlignCenter , ColWidthDefault )
+      , ( AlignCenter , ColWidthDefault )
+      , ( AlignCenter , ColWidthDefault )
+      ]
+      (TableHead ( "" , [] , [] ) [])
+      [ TableBody
+          ( "" , [] , [] )
+          (RowHeadColumns 0)
+          []
+          [ Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "Cell" , Space , Str "1" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "Cell" , Space , Str "2" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "Cell" , Space , Str "3" ] ]
+              ]
+          ]
+      ]
+      (TableFoot ( "" , [] , [] ) [])
+  , Para
+      [ Str "||"
+      , Space
+      , Str "Cell"
+      , Space
+      , Str "1"
+      , Space
+      , Str "|"
+      , Space
+      , Str "Cell"
+      , Space
+      , Str "2"
+      , Space
+      , Str "|"
+      , Space
+      , Str "Cell"
+      , Space
+      , Str "3"
+      , Space
+      , Str "|"
+      ]
+  , Table
+      ( "" , [] , [] )
+      (Caption Nothing [])
+      [ ( AlignCenter , ColWidthDefault )
+      , ( AlignCenter , ColWidthDefault )
+      , ( AlignCenter , ColWidthDefault )
+      ]
+      (TableHead ( "" , [] , [] ) [])
+      [ TableBody
+          ( "" , [] , [] )
+          (RowHeadColumns 0)
+          []
+          [ Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "Cell" , Space , Str "1" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "Cell" , Space , Str "2" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "Cell" , Space , Str "3" ] ]
+              ]
+          ]
+      ]
+      (TableFoot ( "" , [] , [] ) [])
+  , Table
+      ( "" , [] , [] )
+      (Caption Nothing [])
+      [ ( AlignDefault , ColWidthDefault )
+      , ( AlignCenter , ColWidthDefault )
+      , ( AlignDefault , ColWidthDefault )
+      ]
+      (TableHead
+         ( "" , [] , [] )
+         [ Row
+             ( "" , [] , [] )
+             [ Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "Heading" ] ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "Heading" ] ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "Heading" ] ]
+             ]
+         ])
+      [ TableBody
+          ( "" , [] , [] )
+          (RowHeadColumns 0)
+          []
+          [ Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "<-" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "--" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "->" ] ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "--" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "--" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "--" ] ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "->" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "--" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "<-" ] ]
+              ]
+          ]
+      ]
+      (TableFoot ( "" , [] , [] ) [])
+  , Table
+      ( "" , [] , [] )
+      (Caption Nothing [])
+      [ ( AlignDefault , ColWidthDefault )
+      , ( AlignDefault , ColWidthDefault )
+      , ( AlignCenter , ColWidthDefault )
+      , ( AlignCenter , ColWidthDefault )
+      ]
+      (TableHead
+         ( "" , [] , [] )
+         [ Row
+             ( "" , [] , [] )
+             [ Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "1" ] ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "2" ] ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "3+4" ] ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 []
+             ]
+         ])
+      [ TableBody
+          ( "" , [] , [] )
+          (RowHeadColumns 0)
+          []
+          [ Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "1" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "2" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "3" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "4" ] ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "1+2+3" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "4" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  []
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  []
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "1" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "2+3" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "4" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  []
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "1+2+3+4" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  []
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  []
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  []
+              ]
+          ]
+      ]
+      (TableFoot ( "" , [] , [] ) [])
+  , Table
+      ( "" , [] , [] )
+      (Caption Nothing [])
+      [ ( AlignCenter , ColWidthDefault )
+      , ( AlignCenter , ColWidthDefault )
+      , ( AlignCenter , ColWidthDefault )
+      , ( AlignCenter , ColWidthDefault )
+      ]
+      (TableHead ( "" , [] , [] ) [])
+      [ TableBody
+          ( "" , [] , [] )
+          (RowHeadColumns 0)
+          []
+          [ Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "0" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "1" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "2" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  []
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "4" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "5" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  []
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "7" ] ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "8" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  []
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "A" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "B" ] ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  []
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "D" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "E" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "F" ] ]
+              ]
+          ]
+      ]
+      (TableFoot ( "" , [] , [] ) [])
+  , Table
+      ( "" , [] , [] )
+      (Caption Nothing [])
+      [ ( AlignCenter , ColWidthDefault )
+      , ( AlignCenter , ColWidthDefault )
+      , ( AlignCenter , ColWidthDefault )
+      , ( AlignCenter , ColWidthDefault )
+      , ( AlignCenter , ColWidthDefault )
+      ]
+      (TableHead ( "" , [] , [] ) [])
+      [ TableBody
+          ( "" , [] , [] )
+          (RowHeadColumns 0)
+          []
+          [ Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "1" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  []
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  []
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  []
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  []
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "1" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "2" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  []
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  []
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  []
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "1" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "2" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "3" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  []
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  []
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "1" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "2" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "3" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "4" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  []
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "1" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "2" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "3" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "4" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "5" ] ]
+              ]
+          ]
+      ]
+      (TableFoot ( "" , [] , [] ) [])
+  , Table
+      ( "" , [] , [] )
+      (Caption Nothing [])
+      [ ( AlignDefault , ColWidthDefault )
+      , ( AlignCenter , ColWidthDefault )
+      , ( AlignCenter , ColWidthDefault )
+      , ( AlignCenter , ColWidthDefault )
+      , ( AlignCenter , ColWidthDefault )
+      ]
+      (TableHead ( "" , [] , [] ) [])
+      [ TableBody
+          ( "" , [] , [] )
+          (RowHeadColumns 0)
+          []
+          [ Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "Jan" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  []
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  []
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  []
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  []
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "Fev" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  []
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  []
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  []
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  []
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "Mar" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  []
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  []
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  []
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  []
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "Apr" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  []
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  []
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  []
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  []
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "May" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  []
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  []
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  []
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  []
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "20%" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "40%" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "60%" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "80%" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "100%" ] ]
+              ]
+          ]
+      ]
+      (TableFoot ( "" , [] , [] ) [])
+  , Table
+      ( "" , [] , [] )
+      (Caption Nothing [])
+      [ ( AlignCenter , ColWidthDefault )
+      , ( AlignDefault , ColWidthDefault )
+      , ( AlignDefault , ColWidthDefault )
+      , ( AlignCenter , ColWidthDefault )
+      , ( AlignCenter , ColWidthDefault )
+      ]
+      (TableHead ( "" , [] , [] ) [])
+      [ TableBody
+          ( "" , [] , [] )
+          (RowHeadColumns 0)
+          []
+          [ Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  []
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  []
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "/" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  []
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  []
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  []
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain
+                      [ Str "/"
+                      , Space
+                      , Str "/"
+                      , Space
+                      , Str "/"
+                      , Space
+                      , Str "/"
+                      , Space
+                      , Str "/"
+                      ]
+                  ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  []
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  []
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  []
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain
+                      [ Str "/"
+                      , Space
+                      , Str "/"
+                      , Space
+                      , Str "/"
+                      , Space
+                      , Str "/"
+                      , Space
+                      , Str "/"
+                      , Space
+                      , Str "/"
+                      , Space
+                      , Str "/"
+                      , Space
+                      , Str "/"
+                      , Space
+                      , Str "/"
+                      ]
+                  ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  []
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  []
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  []
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  []
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  []
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "o" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  []
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "o" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  []
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  []
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  []
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "." ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  []
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  []
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  []
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain
+                      [ Str "="
+                      , Space
+                      , Str "="
+                      , Space
+                      , Str "="
+                      , Space
+                      , Str "="
+                      ]
+                  ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  []
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  []
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  []
+              ]
+          ]
+      ]
+      (TableFoot ( "" , [] , [] ) [])
+  , Table
+      ( "" , [] , [] )
+      (Caption Nothing [])
+      [ ( AlignCenter , ColWidthDefault )
+      , ( AlignCenter , ColWidthDefault )
+      , ( AlignCenter , ColWidthDefault )
+      , ( AlignCenter , ColWidthDefault )
+      , ( AlignCenter , ColWidthDefault )
+      , ( AlignCenter , ColWidthDefault )
+      , ( AlignCenter , ColWidthDefault )
+      , ( AlignCenter , ColWidthDefault )
+      ]
+      (TableHead ( "" , [] , [] ) [])
+      [ TableBody
+          ( "" , [] , [] )
+          (RowHeadColumns 0)
+          []
+          [ Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "01" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "02" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  []
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  []
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "05" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  []
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "07" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  []
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  []
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  []
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "11" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  []
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "13" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  []
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  []
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "16" ] ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "17" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  []
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "19" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "20" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  []
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  []
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "23" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  []
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "25" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "26" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  []
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  []
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "29" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "30" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  []
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "32" ] ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  []
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  []
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "35" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  []
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "37" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  []
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "39" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "40" ] ]
+              ]
+          ]
+      ]
+      (TableFoot ( "" , [] , [] ) [])
+  , Table
+      ( "" , [] , [] )
+      (Caption Nothing [])
+      [ ( AlignCenter , ColWidthDefault )
+      , ( AlignCenter , ColWidthDefault )
+      , ( AlignCenter , ColWidthDefault )
+      , ( AlignCenter , ColWidthDefault )
+      , ( AlignCenter , ColWidthDefault )
+      , ( AlignCenter , ColWidthDefault )
+      , ( AlignCenter , ColWidthDefault )
+      , ( AlignCenter , ColWidthDefault )
+      , ( AlignCenter , ColWidthDefault )
+      , ( AlignCenter , ColWidthDefault )
+      , ( AlignCenter , ColWidthDefault )
+      , ( AlignCenter , ColWidthDefault )
+      , ( AlignCenter , ColWidthDefault )
+      , ( AlignCenter , ColWidthDefault )
+      , ( AlignCenter , ColWidthDefault )
+      , ( AlignCenter , ColWidthDefault )
+      , ( AlignCenter , ColWidthDefault )
+      , ( AlignCenter , ColWidthDefault )
+      , ( AlignCenter , ColWidthDefault )
+      , ( AlignCenter , ColWidthDefault )
+      , ( AlignCenter , ColWidthDefault )
+      , ( AlignCenter , ColWidthDefault )
+      , ( AlignCenter , ColWidthDefault )
+      , ( AlignCenter , ColWidthDefault )
+      , ( AlignCenter , ColWidthDefault )
+      , ( AlignCenter , ColWidthDefault )
+      , ( AlignCenter , ColWidthDefault )
+      , ( AlignCenter , ColWidthDefault )
+      , ( AlignCenter , ColWidthDefault )
+      , ( AlignCenter , ColWidthDefault )
+      , ( AlignCenter , ColWidthDefault )
+      , ( AlignCenter , ColWidthDefault )
+      ]
+      (TableHead ( "" , [] , [] ) [])
+      [ TableBody
+          ( "" , [] , [] )
+          (RowHeadColumns 0)
+          []
+          [ Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "0" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "1" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "2" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "3" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "4" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "5" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "6" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "7" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "8" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "9" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "A" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "B" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "C" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "D" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "E" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "F" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "0" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "1" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "2" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "3" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "4" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "5" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "6" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "7" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "8" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "9" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "A" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "B" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "C" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "D" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "E" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "F" ] ]
+              ]
+          ]
+      ]
+      (TableFoot ( "" , [] , [] ) [])
+  , Table
+      ( "" , [] , [] )
+      (Caption Nothing [])
+      [ ( AlignCenter , ColWidthDefault ) ]
+      (TableHead ( "" , [] , [] ) [])
+      [ TableBody
+          ( "" , [] , [] )
+          (RowHeadColumns 0)
+          []
+          [ Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  []
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  []
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  []
+              ]
+          ]
+      ]
+      (TableFoot ( "" , [] , [] ) [])
+  , Para [ Str "|this|is|not|a|table|" ]
+  , Para
+      [ Str "|this|"
+      , Space
+      , Str "is|"
+      , Space
+      , Str "not|"
+      , Space
+      , Str "a|"
+      , Space
+      , Str "table|"
+      ]
+  , Para
+      [ Str "|this"
+      , Space
+      , Str "|is"
+      , Space
+      , Str "|not"
+      , Space
+      , Str "|a"
+      , Space
+      , Str "|table"
+      , Space
+      , Str "|"
+      ]
+  , Para
+      [ Str "|"
+      , Space
+      , Str "this\t|"
+      , Space
+      , Str "is\t|"
+      , Space
+      , Str "not\t|"
+      , Space
+      , Str "a\t|"
+      , Space
+      , Str "table\t|"
+      ]
+  , HorizontalRule
+  , Para [ Str "The" , Space , Str "End." ]
+  ]
diff --git a/test/txt2tags.t2t b/test/txt2tags.t2t
--- a/test/txt2tags.t2t
+++ b/test/txt2tags.t2t
@@ -136,7 +136,7 @@
 %%% Syntax: Repetition is greedy
 %% When the mark character is repeated many times,
 %% the contents are expanded to the largest possible.
-%% Thats why they are greedy, the outer marks are
+%% That's why they are greedy, the outer marks are
 %% the ones used.
 
 i)  *****         /////         _____         -----         `````        """""        '''''
@@ -270,7 +270,7 @@
 [img.png]
 
 %%% Syntax: Image pointing to a link: [[img] link]
-[[img.png] http://txt2tags.org]
+[[img.png] https://txt2tags.org]
 
 %%% Align: Image position is preserved when inside paragraph
 [img.png] Image at the line beginning.
diff --git a/test/typst-reader.native b/test/typst-reader.native
new file mode 100644
--- /dev/null
+++ b/test/typst-reader.native
@@ -0,0 +1,5349 @@
+Pandoc
+  Meta { unMeta = fromList [] }
+  [ Header
+      1
+      ( "" , [] , [] )
+      [ Str "Fibonacci" , Space , Str "sequence" ]
+  , Para
+      [ Str "The"
+      , Space
+      , Str "Fibonacci"
+      , Space
+      , Str "sequence"
+      , Space
+      , Str "is"
+      , Space
+      , Str "defined"
+      , Space
+      , Str "through"
+      , Space
+      , Str "the"
+      , SoftBreak
+      , Str "recurrence"
+      , Space
+      , Str "relation"
+      , Space
+      , Math InlineMath "F_{n} = F_{n - 1} + F_{n - 2}"
+      , Str "."
+      , SoftBreak
+      , Str "It"
+      , Space
+      , Str "can"
+      , Space
+      , Str "also"
+      , Space
+      , Str "be"
+      , Space
+      , Str "expressed"
+      , Space
+      , Str "in"
+      , Space
+      , Emph [ Str "closed" , Space , Str "form:" ]
+      ]
+  , Para
+      [ Math
+          DisplayMath
+          "F_{n} = \\left\\lfloor {\\frac{1}{\\sqrt{5}}\\phi^{n}} \\right\\rceil,\\quad\\phi = \\frac{1 + \\sqrt{5}}{2}"
+      ]
+  , Para
+      [ Str "The"
+      , Space
+      , Str "first"
+      , Space
+      , Str "8"
+      , Space
+      , Str "numbers"
+      , Space
+      , Str "of"
+      , Space
+      , Str "the"
+      , Space
+      , Str "sequence"
+      , Space
+      , Str "are:"
+      ]
+  , Div
+      ( "" , [] , [ ( "align" , "center" ) ] )
+      [ Table
+          ( "" , [] , [] )
+          (Caption Nothing [])
+          [ ( AlignDefault , ColWidthDefault )
+          , ( AlignDefault , ColWidthDefault )
+          , ( AlignDefault , ColWidthDefault )
+          , ( AlignDefault , ColWidthDefault )
+          , ( AlignDefault , ColWidthDefault )
+          , ( AlignDefault , ColWidthDefault )
+          , ( AlignDefault , ColWidthDefault )
+          , ( AlignDefault , ColWidthDefault )
+          ]
+          (TableHead ( "" , [] , [] ) [])
+          [ TableBody
+              ( "" , [] , [] )
+              (RowHeadColumns 0)
+              []
+              [ Row
+                  ( "" , [] , [] )
+                  [ Cell
+                      ( "" , [] , [] )
+                      AlignDefault
+                      (RowSpan 1)
+                      (ColSpan 1)
+                      [ Para [ Math InlineMath "F_{1}" ] ]
+                  , Cell
+                      ( "" , [] , [] )
+                      AlignDefault
+                      (RowSpan 1)
+                      (ColSpan 1)
+                      [ Para [ Math InlineMath "F_{2}" ] ]
+                  , Cell
+                      ( "" , [] , [] )
+                      AlignDefault
+                      (RowSpan 1)
+                      (ColSpan 1)
+                      [ Para [ Math InlineMath "F_{3}" ] ]
+                  , Cell
+                      ( "" , [] , [] )
+                      AlignDefault
+                      (RowSpan 1)
+                      (ColSpan 1)
+                      [ Para [ Math InlineMath "F_{4}" ] ]
+                  , Cell
+                      ( "" , [] , [] )
+                      AlignDefault
+                      (RowSpan 1)
+                      (ColSpan 1)
+                      [ Para [ Math InlineMath "F_{5}" ] ]
+                  , Cell
+                      ( "" , [] , [] )
+                      AlignDefault
+                      (RowSpan 1)
+                      (ColSpan 1)
+                      [ Para [ Math InlineMath "F_{6}" ] ]
+                  , Cell
+                      ( "" , [] , [] )
+                      AlignDefault
+                      (RowSpan 1)
+                      (ColSpan 1)
+                      [ Para [ Math InlineMath "F_{7}" ] ]
+                  , Cell
+                      ( "" , [] , [] )
+                      AlignDefault
+                      (RowSpan 1)
+                      (ColSpan 1)
+                      [ Para [ Math InlineMath "F_{8}" ] ]
+                  ]
+              , Row
+                  ( "" , [] , [] )
+                  [ Cell
+                      ( "" , [] , [] )
+                      AlignDefault
+                      (RowSpan 1)
+                      (ColSpan 1)
+                      [ Para [ Str "1" ] ]
+                  , Cell
+                      ( "" , [] , [] )
+                      AlignDefault
+                      (RowSpan 1)
+                      (ColSpan 1)
+                      [ Para [ Str "1" ] ]
+                  , Cell
+                      ( "" , [] , [] )
+                      AlignDefault
+                      (RowSpan 1)
+                      (ColSpan 1)
+                      [ Para [ Str "2" ] ]
+                  , Cell
+                      ( "" , [] , [] )
+                      AlignDefault
+                      (RowSpan 1)
+                      (ColSpan 1)
+                      [ Para [ Str "3" ] ]
+                  , Cell
+                      ( "" , [] , [] )
+                      AlignDefault
+                      (RowSpan 1)
+                      (ColSpan 1)
+                      [ Para [ Str "5" ] ]
+                  , Cell
+                      ( "" , [] , [] )
+                      AlignDefault
+                      (RowSpan 1)
+                      (ColSpan 1)
+                      [ Para [ Str "8" ] ]
+                  , Cell
+                      ( "" , [] , [] )
+                      AlignDefault
+                      (RowSpan 1)
+                      (ColSpan 1)
+                      [ Para [ Str "13" ] ]
+                  , Cell
+                      ( "" , [] , [] )
+                      AlignDefault
+                      (RowSpan 1)
+                      (ColSpan 1)
+                      [ Para [ Str "21" ] ]
+                  ]
+              ]
+          ]
+          (TableFoot ( "" , [] , [] ) [])
+      ]
+  , Div
+      ( "" , [ "columns-flow" ] , [ ( "count" , "2" ) ] )
+      [ Para
+          [ Span
+              ( "" , [] , [ ( "align" , "center" ) ] )
+              [ Link
+                  ( "" , [] , [] )
+                  [ SoftBreak
+                  , Strong
+                      [ Str "Typst"
+                      , Space
+                      , Str "Math"
+                      , Space
+                      , Str "for"
+                      , Space
+                      , Str "Undergrads"
+                      ]
+                  , SoftBreak
+                  ]
+                  ( "https://github.com/johanvx/typst-undergradmath"
+                  , ""
+                  )
+              ]
+          ]
+      , Para
+          [ Str "This"
+          , Space
+          , Str "is"
+          , Space
+          , Str "a"
+          , Space
+          , Str "Typst"
+          , Space
+          , Str "port"
+          , Space
+          , Str "of"
+          , Space
+          , Emph
+              [ Span
+                  ( "" , [ "box" ] , [] )
+                  [ Str "L\8202A\8202"
+                  , Span ( "" , [ "box" ] , [] ) [ Str "T\8202E\8202X" ]
+                  ]
+              , Space
+              , Str "Math"
+              , Space
+              , Str "for"
+              , Space
+              , Str "Undergrads"
+              ]
+          , Space
+          , Str "by"
+          , Space
+          , Str "Jim"
+          , Space
+          , Str "Hefferon."
+          , SoftBreak
+          , Str "The"
+          , Space
+          , Str "original"
+          , Space
+          , Str "version"
+          , Space
+          , Str "is"
+          , Space
+          , Str "available"
+          , Space
+          , Str "at"
+          , Space
+          , Underline
+              [ Link
+                  ( "" , [] , [] )
+                  [ Str "https://gitlab.com/jim.hefferon/undergradmath"
+                  ]
+                  ( "https://gitlab.com/jim.hefferon/undergradmath"
+                  , ""
+                  )
+              ]
+          , Str "."
+          ]
+      , Para
+          [ Strong
+              [ Str "Meaning"
+              , Space
+              , Str "of"
+              , Space
+              , Str "annotations\8192\160"
+              ]
+          ]
+      , Table
+          ( "" , [] , [] )
+          (Caption Nothing [])
+          [ ( AlignLeft , ColWidth 0.3333333333333333 )
+          , ( AlignLeft , ColWidth 0.6666666666666666 )
+          ]
+          (TableHead ( "" , [] , [] ) [])
+          [ TableBody
+              ( "" , [] , [] )
+              (RowHeadColumns 0)
+              []
+              [ Row
+                  ( "" , [] , [] )
+                  [ Cell
+                      ( "" , [] , [] )
+                      AlignDefault
+                      (RowSpan 1)
+                      (ColSpan 1)
+                      [ Para
+                          [ Span
+                              ( "" , [ "box" ] , [] )
+                              [ Str "2023-05-22"
+                              , Space
+                              , Str "\10060"
+                              ]
+                          ]
+                      ]
+                  , Cell
+                      ( "" , [] , [] )
+                      AlignDefault
+                      (RowSpan 1)
+                      (ColSpan 1)
+                      [ Para
+                          [ Str "This"
+                          , Space
+                          , Str "is"
+                          , Space
+                          , Str "unavailable."
+                          , Space
+                          , Str "Last"
+                          , Space
+                          , Str "check"
+                          , Space
+                          , Str "date"
+                          , Space
+                          , Str "is"
+                          , Space
+                          , Str "2023-05-22."
+                          ]
+                      ]
+                  ]
+              ]
+          ]
+          (TableFoot ( "" , [] , [] ) [])
+      , Para [ Span ( "unavailable" , [] , [] ) [] ]
+      , Table
+          ( "" , [] , [] )
+          (Caption Nothing [])
+          [ ( AlignLeft , ColWidth 0.3333333333333333 )
+          , ( AlignLeft , ColWidth 0.6666666666666666 )
+          ]
+          (TableHead ( "" , [] , [] ) [])
+          [ TableBody
+              ( "" , [] , [] )
+              (RowHeadColumns 0)
+              []
+              [ Row
+                  ( "" , [] , [] )
+                  [ Cell
+                      ( "" , [] , [] )
+                      AlignDefault
+                      (RowSpan 1)
+                      (ColSpan 1)
+                      [ Para
+                          [ Span
+                              ( "" , [ "box" ] , [] ) [ Str "\128166" ]
+                          ]
+                      ]
+                  , Cell
+                      ( "" , [] , [] )
+                      AlignDefault
+                      (RowSpan 1)
+                      (ColSpan 1)
+                      [ Para
+                          [ Str "Get"
+                          , Space
+                          , Str "this"
+                          , Space
+                          , Str "in"
+                          , Space
+                          , Str "a"
+                          , Space
+                          , Str "tricky"
+                          , Space
+                          , Str "way."
+                          , Space
+                          , Str "Need"
+                          , Space
+                          , Str "a"
+                          , Space
+                          , Str "simpler"
+                          , Space
+                          , Str "method."
+                          ]
+                      ]
+                  ]
+              ]
+          ]
+          (TableFoot ( "" , [] , [] ) [])
+      , Para [ Span ( "tricky" , [] , [] ) [] ]
+      , Table
+          ( "" , [] , [] )
+          (Caption Nothing [])
+          [ ( AlignLeft , ColWidth 0.3333333333333333 )
+          , ( AlignLeft , ColWidth 0.6666666666666666 )
+          ]
+          (TableHead ( "" , [] , [] ) [])
+          [ TableBody
+              ( "" , [] , [] )
+              (RowHeadColumns 0)
+              []
+              [ Row
+                  ( "" , [] , [] )
+                  [ Cell
+                      ( "" , [] , [] )
+                      AlignDefault
+                      (RowSpan 1)
+                      (ColSpan 1)
+                      [ Para
+                          [ Span
+                              ( "" , [ "box" ] , [] )
+                              [ Str "No"
+                              , Space
+                              , Str "idea"
+                              , Space
+                              , Str "\128533"
+                              ]
+                          ]
+                      ]
+                  , Cell
+                      ( "" , [] , [] )
+                      AlignDefault
+                      (RowSpan 1)
+                      (ColSpan 1)
+                      [ Para
+                          [ Str "Don\8217t"
+                          , Space
+                          , Str "know"
+                          , Space
+                          , Str "how"
+                          , Space
+                          , Str "to"
+                          , Space
+                          , Str "get"
+                          , Space
+                          , Str "this."
+                          ]
+                      ]
+                  ]
+              ]
+          ]
+          (TableFoot ( "" , [] , [] ) [])
+      , Para [ Span ( "noidea" , [] , [] ) [] ]
+      , Para
+          [ Strong [ Str "Rule" , Space , Str "One\8192\160" ]
+          , Str "Any"
+          , Space
+          , Str "mathematics"
+          , Space
+          , Str "at"
+          , Space
+          , Str "all,"
+          , Space
+          , Str "even"
+          , Space
+          , Str "a"
+          , Space
+          , Str "single"
+          , Space
+          , Str "character,"
+          , Space
+          , Str "gets"
+          , Space
+          , Str "a"
+          , Space
+          , Str "mathematical"
+          , Space
+          , Str "setting."
+          , SoftBreak
+          , Str "Thus,"
+          , Space
+          , Str "for"
+          , Space
+          , Str "\8220the"
+          , Space
+          , Str "value"
+          , Space
+          , Str "of"
+          , Space
+          , Math InlineMath "x"
+          , Space
+          , Str "is"
+          , Space
+          , Math InlineMath "7"
+          , Str "\8221"
+          , Space
+          , Str "enter"
+          , Space
+          , Code ( "" , [] , [] ) "the value of $x$ is $7$"
+          , Str "."
+          ]
+      , Para
+          [ Strong [ Str "Template\8192\160" ]
+          , Str "Your"
+          , Space
+          , Str "document"
+          , Space
+          , Str "should"
+          , Space
+          , Str "contain"
+          , Space
+          , Str "at"
+          , Space
+          , Str "least"
+          , Space
+          , Str "this."
+          ]
+      , Table
+          ( "" , [] , [] )
+          (Caption Nothing [])
+          [ ( AlignDefault , ColWidthDefault )
+          , ( AlignDefault , ColWidthDefault )
+          ]
+          (TableHead ( "" , [] , [] ) [])
+          [ TableBody
+              ( "" , [] , [] )
+              (RowHeadColumns 0)
+              []
+              [ Row
+                  ( "" , [] , [] )
+                  [ Cell
+                      ( "" , [] , [] )
+                      AlignDefault
+                      (RowSpan 1)
+                      (ColSpan 1)
+                      []
+                  , Cell
+                      ( "" , [] , [] )
+                      AlignDefault
+                      (RowSpan 1)
+                      (ColSpan 1)
+                      [ CodeBlock
+                          ( "" , [] , [] ) "-- document body here --"
+                      ]
+                  ]
+              ]
+          ]
+          (TableFoot ( "" , [] , [] ) [])
+      , Para
+          [ Strong
+              [ Str "Common" , Space , Str "constructs\8192\160" ]
+          ]
+      , Div
+          ( "" , [] , [ ( "align" , "center" ) ] )
+          [ Table
+              ( "" , [] , [] )
+              (Caption Nothing [])
+              [ ( AlignLeft , ColWidthDefault )
+              , ( AlignLeft , ColWidthDefault )
+              ]
+              (TableHead ( "" , [] , [] ) [])
+              [ TableBody
+                  ( "" , [] , [] )
+                  (RowHeadColumns 0)
+                  []
+                  [ Row
+                      ( "" , [] , [] )
+                      [ Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "x^{2}"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "x^2"
+                                  ]
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\sqrt{2}"
+                                  , Str ","
+                                  , Space
+                                  , Math InlineMath "\\sqrt[n]{3}"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "sqrt(2)"
+                                  , Str ","
+                                  , Space
+                                  , Code ( "" , [] , [] ) "root(n, 3)"
+                                  ]
+                              ]
+                          ]
+                      ]
+                  , Row
+                      ( "" , [] , [] )
+                      [ Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "x_{i,j}"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "x_(i, j)"
+                                  ]
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\frac{2}{3}"
+                                  , Str ","
+                                  , Space
+                                  , Math InlineMath "2/3"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "2 / 3"
+                                  , Str ","
+                                  , Space
+                                  , Code ( "" , [] , [] ) "2 \\/ 3"
+                                  , Space
+                                  , Str "or"
+                                  , Space
+                                  , Code ( "" , [] , [] ) "2 slash 3"
+                                  ]
+                              ]
+                          ]
+                      ]
+                  ]
+              ]
+              (TableFoot ( "" , [] , [] ) [])
+          ]
+      , Para
+          [ Strong
+              [ Str "Calligraphic" , Space , Str "letters\8192\160" ]
+          , Str "Use"
+          , Space
+          , Str "as"
+          , Space
+          , Str "in"
+          , Space
+          , Code ( "" , [] , [] ) "$cal(A)$"
+          , Str "."
+          ]
+      , Para
+          [ Math DisplayMath "\\mathcal{ABCDEFGHIJKLMNOPQRSTUVWXYZ}" ]
+      , Para
+          [ Str "Getting"
+          , Space
+          , Str "script"
+          , Space
+          , Str "letters"
+          , Space
+          , Str "is"
+          , Space
+          , Link
+              ( "" , [ "ref" ] , [] )
+              [ Str "[unavailable]" ]
+              ( "#unavailable" , "" )
+          , Str "."
+          ]
+      , Para [ Strong [ Str "Greek\8192\160" ] ]
+      , Div
+          ( "" , [] , [ ( "align" , "center" ) ] )
+          [ Table
+              ( "" , [] , [] )
+              (Caption Nothing [])
+              [ ( AlignLeft , ColWidthDefault )
+              , ( AlignLeft , ColWidthDefault )
+              ]
+              (TableHead ( "" , [] , [] ) [])
+              [ TableBody
+                  ( "" , [] , [] )
+                  (RowHeadColumns 0)
+                  []
+                  [ Row
+                      ( "" , [] , [] )
+                      [ Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\alpha"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "alpha"
+                                  ]
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\xi"
+                                  , Str ","
+                                  , Space
+                                  , Math InlineMath "\\Xi"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "xi"
+                                  , Str ","
+                                  , Space
+                                  , Code ( "" , [] , [] ) "Xi"
+                                  ]
+                              ]
+                          ]
+                      ]
+                  , Row
+                      ( "" , [] , [] )
+                      [ Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\beta"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "beta"
+                                  ]
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\959"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "omicron"
+                                  ]
+                              ]
+                          ]
+                      ]
+                  , Row
+                      ( "" , [] , [] )
+                      [ Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\gamma"
+                                  , Str ","
+                                  , Space
+                                  , Math InlineMath "\\Gamma"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "gamma"
+                                  , Str ","
+                                  , Space
+                                  , Code ( "" , [] , [] ) "Gamma"
+                                  ]
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\pi"
+                                  , Str ","
+                                  , Space
+                                  , Math InlineMath "\\Pi"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "pi"
+                                  , Str ","
+                                  , Space
+                                  , Code ( "" , [] , [] ) "Pi"
+                                  ]
+                              ]
+                          ]
+                      ]
+                  , Row
+                      ( "" , [] , [] )
+                      [ Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\delta"
+                                  , Str ","
+                                  , Space
+                                  , Math InlineMath "\\Delta"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "delta"
+                                  , Str ","
+                                  , Space
+                                  , Code ( "" , [] , [] ) "Delta"
+                                  ]
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\varpi"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "pi.alt"
+                                  ]
+                              ]
+                          ]
+                      ]
+                  , Row
+                      ( "" , [] , [] )
+                      [ Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\epsilon"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "epsilon.alt"
+                                  ]
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\rho"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "rho"
+                                  ]
+                              ]
+                          ]
+                      ]
+                  , Row
+                      ( "" , [] , [] )
+                      [ Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\varepsilon"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "epsilon"
+                                  ]
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\varrho"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "rho.alt"
+                                  ]
+                              ]
+                          ]
+                      ]
+                  , Row
+                      ( "" , [] , [] )
+                      [ Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\zeta"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "zeta"
+                                  ]
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\sigma"
+                                  , Str ","
+                                  , Space
+                                  , Math InlineMath "\\Sigma"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "sigma"
+                                  , Str ","
+                                  , Space
+                                  , Code ( "" , [] , [] ) "Sigma"
+                                  ]
+                              ]
+                          ]
+                      ]
+                  , Row
+                      ( "" , [] , [] )
+                      [ Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\eta"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "eta"
+                                  ]
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\varsigma"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "\\u{03C2}"
+                                  , Space
+                                  , Link
+                                      ( "" , [ "ref" ] , [] )
+                                      [ Str "[tricky]" ]
+                                      ( "#tricky" , "" )
+                                  ]
+                              ]
+                          ]
+                      ]
+                  , Row
+                      ( "" , [] , [] )
+                      [ Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\theta"
+                                  , Str ","
+                                  , Space
+                                  , Math InlineMath "\\Theta"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "theta"
+                                  , Str ","
+                                  , Space
+                                  , Code ( "" , [] , [] ) "Theta"
+                                  ]
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\tau"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "tau"
+                                  ]
+                              ]
+                          ]
+                      ]
+                  , Row
+                      ( "" , [] , [] )
+                      [ Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\vartheta"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "theta.alt"
+                                  ]
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\upsilon"
+                                  , Str ","
+                                  , Space
+                                  , Math InlineMath "\\Upsilon"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "upsilon"
+                                  , Str ","
+                                  , Space
+                                  , Code ( "" , [] , [] ) "Upsilon"
+                                  ]
+                              ]
+                          ]
+                      ]
+                  , Row
+                      ( "" , [] , [] )
+                      [ Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\iota"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "iota"
+                                  ]
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\phi"
+                                  , Str ","
+                                  , Space
+                                  , Math InlineMath "\\Phi"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "phi.alt"
+                                  , Str ","
+                                  , Space
+                                  , Code ( "" , [] , [] ) "Phi"
+                                  ]
+                              ]
+                          ]
+                      ]
+                  , Row
+                      ( "" , [] , [] )
+                      [ Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\kappa"
+                                  , Str "\8192"
+                                  , Math InlineMath "\922"
+                                  ]
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\varphi"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "phi"
+                                  ]
+                              ]
+                          ]
+                      ]
+                  , Row
+                      ( "" , [] , [] )
+                      [ Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\lambda"
+                                  , Str ","
+                                  , Space
+                                  , Math InlineMath "\\Lambda"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "lambda"
+                                  , Str ","
+                                  , Space
+                                  , Code ( "" , [] , [] ) "Lambda"
+                                  ]
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\chi"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "chi"
+                                  ]
+                              ]
+                          ]
+                      ]
+                  , Row
+                      ( "" , [] , [] )
+                      [ Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\mu"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "mu"
+                                  ]
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\psi"
+                                  , Str ","
+                                  , Space
+                                  , Math InlineMath "\\Psi"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "psi"
+                                  , Str ","
+                                  , Space
+                                  , Code ( "" , [] , [] ) "Psi"
+                                  ]
+                              ]
+                          ]
+                      ]
+                  , Row
+                      ( "" , [] , [] )
+                      [ Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\nu"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "nu"
+                                  ]
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\omega"
+                                  , Str ","
+                                  , Space
+                                  , Math InlineMath "\\Omega"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "omega"
+                                  , Str ","
+                                  , Space
+                                  , Code ( "" , [] , [] ) "Omega"
+                                  ]
+                              ]
+                          ]
+                      ]
+                  ]
+              ]
+              (TableFoot ( "" , [] , [] ) [])
+          ]
+      , Para
+          [ Strong
+              [ Str "Sets"
+              , Space
+              , Str "and"
+              , Space
+              , Str "logic\8192\160"
+              ]
+          ]
+      , Div
+          ( "" , [] , [ ( "align" , "center" ) ] )
+          [ Table
+              ( "" , [] , [] )
+              (Caption Nothing [])
+              [ ( AlignLeft , ColWidthDefault )
+              , ( AlignLeft , ColWidthDefault )
+              , ( AlignLeft , ColWidthDefault )
+              ]
+              (TableHead ( "" , [] , [] ) [])
+              [ TableBody
+                  ( "" , [] , [] )
+                  (RowHeadColumns 0)
+                  []
+                  [ Row
+                      ( "" , [] , [] )
+                      [ Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\cup"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "union"
+                                  ]
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\mathbb{R}"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "RR"
+                                  , Str ","
+                                  , Space
+                                  , Code ( "" , [] , [] ) "bb(R)"
+                                  ]
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\forall"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "forall"
+                                  ]
+                              ]
+                          ]
+                      ]
+                  , Row
+                      ( "" , [] , [] )
+                      [ Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\cap"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "sect"
+                                  ]
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\mathbb{Z}"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "ZZ"
+                                  , Str ","
+                                  , Space
+                                  , Code ( "" , [] , [] ) "bb(Z)"
+                                  ]
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\exists"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "exists"
+                                  ]
+                              ]
+                          ]
+                      ]
+                  , Row
+                      ( "" , [] , [] )
+                      [ Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\subset"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "subset"
+                                  ]
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\mathbb{Q}"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "QQ"
+                                  , Str ","
+                                  , Space
+                                  , Code ( "" , [] , [] ) "bb(Q)"
+                                  ]
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\neg"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "not"
+                                  ]
+                              ]
+                          ]
+                      ]
+                  , Row
+                      ( "" , [] , [] )
+                      [ Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\subseteq"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "subset.eq"
+                                  ]
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\mathbb{N}"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "NN"
+                                  , Str ","
+                                  , Space
+                                  , Code ( "" , [] , [] ) "bb(N)"
+                                  ]
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\vee"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "or"
+                                  ]
+                              ]
+                          ]
+                      ]
+                  , Row
+                      ( "" , [] , [] )
+                      [ Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\supset"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "supset"
+                                  ]
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\mathbb{C}"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "CC"
+                                  , Str ","
+                                  , Space
+                                  , Code ( "" , [] , [] ) "bb(C)"
+                                  ]
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\land"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "and"
+                                  ]
+                              ]
+                          ]
+                      ]
+                  , Row
+                      ( "" , [] , [] )
+                      [ Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\supseteq"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "supset.eq"
+                                  ]
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\varnothing"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "diameter"
+                                  ]
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\vdash"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "tack.r"
+                                  ]
+                              ]
+                          ]
+                      ]
+                  , Row
+                      ( "" , [] , [] )
+                      [ Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\in"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "in"
+                                  ]
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\varnothing"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "nothing"
+                                  ]
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\models"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "models"
+                                  ]
+                              ]
+                          ]
+                      ]
+                  , Row
+                      ( "" , [] , [] )
+                      [ Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\notin"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "in.not"
+                                  ]
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\1488"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "alef"
+                                  ]
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\smallsetminus"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "without"
+                                  ]
+                              ]
+                          ]
+                      ]
+                  ]
+              ]
+              (TableFoot ( "" , [] , [] ) [])
+          ]
+      , Para
+          [ Str "Negate"
+          , Space
+          , Str "an"
+          , Space
+          , Str "operator,"
+          , Space
+          , Str "as"
+          , Space
+          , Str "in"
+          , Space
+          , Math InlineMath "\8836"
+          , Str ","
+          , Space
+          , Str "with"
+          , Space
+          , Code ( "" , [] , [] ) "subset.not"
+          , Str "."
+          , SoftBreak
+          , Str "Get"
+          , Space
+          , Str "the"
+          , Space
+          , Str "set"
+          , Space
+          , Str "complement"
+          , Space
+          , Math InlineMath "A^{\\mathsf{c}}"
+          , Space
+          , Str "with"
+          , Space
+          , Code ( "" , [] , [] ) "A^(sans(c))"
+          , Space
+          , Str "(or"
+          , Space
+          , Math InlineMath "A^{\\complement}"
+          , Space
+          , Str "with"
+          , Space
+          , Code ( "" , [] , [] ) "A^(complement)"
+          , Str ","
+          , Space
+          , Str "or"
+          , Space
+          , Math InlineMath "\\overline{A}"
+          , Space
+          , Str "with"
+          , Space
+          , Code ( "" , [] , [] ) "overline(A)"
+          , Str ")."
+          ]
+      , DefinitionList
+          [ ( [ Str "Remark" ]
+            , [ [ Para
+                    [ Str "Using"
+                    , Space
+                    , Code ( "" , [] , [] ) "diameter"
+                    , Space
+                    , Str "for"
+                    , Space
+                    , Code ( "" , [] , [] ) "\\varnothing"
+                    , Space
+                    , Str "may"
+                    , Space
+                    , Str "cause"
+                    , Space
+                    , Str "some"
+                    , Space
+                    , Str "confusion."
+                    , Space
+                    , Str "However,"
+                    , Space
+                    , Span
+                        ( "" , [ "box" ] , [] )
+                        [ Str "L\8202A\8202"
+                        , Span
+                            ( "" , [ "box" ] , [] )
+                            [ Str "T\8202E\8202X" ]
+                        ]
+                    , Space
+                    , Str "also"
+                    , Space
+                    , Str "uses"
+                    , Space
+                    , Math InlineMath "\\varnothing"
+                    , Space
+                    , Str "("
+                    , Code ( "" , [] , [] ) "\\u{2300}"
+                    , Str ")"
+                    , Space
+                    , Str "instead"
+                    , Space
+                    , Str "of"
+                    , Space
+                    , Math InlineMath "\\varnothing"
+                    , Space
+                    , Str "("
+                    , Code ( "" , [] , [] ) "\\u{2205}"
+                    , Str "),"
+                    , Space
+                    , Str "see"
+                    , Space
+                    , Underline
+                        [ Link
+                            ( "" , [] , [] )
+                            [ Str "newcm"
+                            , Space
+                            , Math InlineMath "\167"
+                            , Str "13.3"
+                            ]
+                            ( "https://mirrors.sustech.edu.cn/CTAN/fonts/newcomputermodern/doc/newcm-doc.pdf"
+                            , ""
+                            )
+                        ]
+                    , Str "."
+                    , SoftBreak
+                    , Str "Another"
+                    , Space
+                    , Str "solution"
+                    , Space
+                    , Str "is"
+                    , Space
+                    , Str "to"
+                    , Space
+                    , Str "use"
+                    , Space
+                    , Code
+                        ( "" , [] , [] )
+                        "text(font: \"Fira Sans\", nothing)"
+                    , Str ","
+                    , Space
+                    , Str "but"
+                    , Space
+                    , Str "the"
+                    , Space
+                    , Str "resultant"
+                    , Space
+                    , Str "glyph"
+                    , Space
+                    , Math InlineMath "\\varnothing"
+                    , Space
+                    , Str "is"
+                    , Space
+                    , Str "subtly"
+                    , Space
+                    , Str "different"
+                    , Space
+                    , Str "from"
+                    , Space
+                    , Str "the"
+                    , Space
+                    , Str "widely"
+                    , Space
+                    , Str "used"
+                    , Space
+                    , Str "one."
+                    , SoftBreak
+                    , Str "Ultimately,"
+                    , Space
+                    , Str "the"
+                    , Space
+                    , Str "choice"
+                    , Space
+                    , Str "is"
+                    , Space
+                    , Str "always"
+                    , Space
+                    , Strong [ Str "your" , Space , Str "decision" ]
+                    , Str "."
+                    ]
+                ]
+              ]
+            )
+          ]
+      , Para [ Strong [ Str "Decorations\8192\160" ] ]
+      , Div
+          ( "" , [] , [ ( "align" , "center" ) ] )
+          [ Table
+              ( "" , [] , [] )
+              (Caption Nothing [])
+              [ ( AlignLeft , ColWidthDefault )
+              , ( AlignLeft , ColWidthDefault )
+              , ( AlignLeft , ColWidthDefault )
+              ]
+              (TableHead ( "" , [] , [] ) [])
+              [ TableBody
+                  ( "" , [] , [] )
+                  (RowHeadColumns 0)
+                  []
+                  [ Row
+                      ( "" , [] , [] )
+                      [ Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "f'"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "f'"
+                                  , Str ","
+                                  , Space
+                                  , Code ( "" , [] , [] ) "f prime"
+                                  ]
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\dot{a}"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "dot(a)"
+                                  ]
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\widetilde{a}"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "tilde(a)"
+                                  ]
+                              ]
+                          ]
+                      ]
+                  , Row
+                      ( "" , [] , [] )
+                      [ Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "f''"
+                                  , Str "\8192"
+                                  , Code
+                                      ( "" , [] , [] ) "f prime.double"
+                                  ]
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\ddot{a}"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "diaer(a)"
+                                  ]
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\overline{a}"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "macron(a)"
+                                  ]
+                              ]
+                          ]
+                      ]
+                  , Row
+                      ( "" , [] , [] )
+                      [ Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\Sigma^{\\ast}"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "Sigma^*"
+                                  ]
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\hat{a}"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "hat(a)"
+                                  ]
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math
+                                      InlineMath
+                                      "\\overset{\\rightarrow}{a}"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "arrow(a)"
+                                  ]
+                              ]
+                          ]
+                      ]
+                  ]
+              ]
+              (TableFoot ( "" , [] , [] ) [])
+          ]
+      , Para
+          [ Str "If"
+          , Space
+          , Str "the"
+          , Space
+          , Str "decorated"
+          , Space
+          , Str "letter"
+          , Space
+          , Str "is"
+          , Space
+          , Math InlineMath "i"
+          , Space
+          , Str "or"
+          , Space
+          , Math InlineMath "j"
+          , Space
+          , Str "then"
+          , Space
+          , Str "some"
+          , Space
+          , Str "decorations"
+          , Space
+          , Str "need"
+          , Space
+          , Code ( "" , [] , [] ) "\\u{1D6A4}"
+          , Space
+          , Link
+              ( "" , [ "ref" ] , [] )
+              [ Str "[tricky]" ]
+              ( "#tricky" , "" )
+          , Space
+          , Str "and"
+          , Space
+          , Code ( "" , [] , [] ) "\\u{1D6A5}"
+          , Space
+          , Link
+              ( "" , [ "ref" ] , [] )
+              [ Str "[tricky]" ]
+              ( "#tricky" , "" )
+          , Str ","
+          , Space
+          , Str "as"
+          , Space
+          , Str "in"
+          , Space
+          , Math InlineMath "\\overset{\\rightarrow}{\\imath}"
+          , Space
+          , Str "with"
+          , Space
+          , Code ( "" , [] , [] ) "arrow(\\u{1D6A4})"
+          , Str "."
+          , SoftBreak
+          , Str "Some"
+          , Space
+          , Str "authors"
+          , Space
+          , Str "use"
+          , Space
+          , Str "boldface"
+          , Space
+          , Str "for"
+          , Space
+          , Str "vectors:"
+          , Space
+          , Code ( "" , [] , [] ) "bold(x)"
+          , Str "."
+          ]
+      , Para
+          [ Str "Entering"
+          , Space
+          , Code ( "" , [] , [] ) "overline(x + y)"
+          , Space
+          , Str "produces"
+          , Space
+          , Math InlineMath "\\overline{x + y}"
+          , Str ","
+          , Space
+          , Str "and"
+          , Space
+          , Code ( "" , [] , [] ) "hat(x + y)"
+          , Space
+          , Str "gives"
+          , Space
+          , Math InlineMath "\\hat{x + y}"
+          , Str "."
+          , SoftBreak
+          , Str "Comment"
+          , Space
+          , Str "on"
+          , Space
+          , Str "an"
+          , Space
+          , Str "expression"
+          , Space
+          , Str "as"
+          , Space
+          , Str "here"
+          , Space
+          , Str "(there"
+          , Space
+          , Str "is"
+          , Space
+          , Str "also"
+          , Space
+          , Code ( "" , [] , [] ) "overbrace(..)"
+          , Str ")."
+          ]
+      , Para
+          [ Span
+              ( "" , [] , [ ( "align" , "center" ) ] )
+              [ Span
+                  ( "" , [ "box" ] , [] )
+                  [ Math
+                      InlineMath "\\underset{|A|}{\\underbrace{x + y}}"
+                  , Str "\8192"
+                  , Code ( "" , [] , [] ) "underbrace(x + y, |A|)"
+                  ]
+              ]
+          ]
+      , Para
+          [ Strong [ Str "Dots\8192\160" ]
+          , Str "Use"
+          , Space
+          , Str "low"
+          , Space
+          , Str "dots"
+          , Space
+          , Str "in"
+          , Space
+          , Str "a"
+          , Space
+          , Str "list"
+          , Space
+          , Math InlineMath "\\left\\{ 0,1,2,\\ldots \\right\\}"
+          , Str ","
+          , Space
+          , Str "entered"
+          , Space
+          , Str "as"
+          , Space
+          , Code ( "" , [] , [] ) "{0, 1, 2, ...}"
+          , Str "."
+          , SoftBreak
+          , Str "Use"
+          , Space
+          , Str "centered"
+          , Space
+          , Str "dots"
+          , Space
+          , Str "in"
+          , Space
+          , Str "a"
+          , Space
+          , Str "sum"
+          , Space
+          , Str "or"
+          , Space
+          , Str "product"
+          , Space
+          , Math InlineMath "1 + \\cdots + 100"
+          , Str ","
+          , Space
+          , Str "entered"
+          , Space
+          , Str "as"
+          , Space
+          , Code ( "" , [] , [] ) "1 + dots.h.c + 100"
+          , Str "."
+          , SoftBreak
+          , Str "You"
+          , Space
+          , Str "can"
+          , Space
+          , Str "also"
+          , Space
+          , Str "get"
+          , Space
+          , Str "vertical"
+          , Space
+          , Str "dots"
+          , Space
+          , Code ( "" , [] , [] ) "dots.v"
+          , Str ","
+          , Space
+          , Str "diagonal"
+          , Space
+          , Str "dots"
+          , Space
+          , Code ( "" , [] , [] ) "dots.down"
+          , Space
+          , Str "and"
+          , Space
+          , Str "anti-diagonal"
+          , Space
+          , Str "dots"
+          , Space
+          , Code ( "" , [] , [] ) "dots.up"
+          , Str "."
+          ]
+      , Para
+          [ Strong [ Str "Roman" , Space , Str "names\8192\160" ]
+          , Str "Just"
+          , Space
+          , Str "type"
+          , Space
+          , Str "them!"
+          ]
+      , Div
+          ( "" , [] , [ ( "align" , "center" ) ] )
+          [ Table
+              ( "" , [] , [] )
+              (Caption Nothing [])
+              [ ( AlignLeft , ColWidthDefault )
+              , ( AlignLeft , ColWidthDefault )
+              , ( AlignLeft , ColWidthDefault )
+              ]
+              (TableHead ( "" , [] , [] ) [])
+              [ TableBody
+                  ( "" , [] , [] )
+                  (RowHeadColumns 0)
+                  []
+                  [ Row
+                      ( "" , [] , [] )
+                      [ Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\sin"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "sin"
+                                  ]
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\sinh"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "sinh"
+                                  ]
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\arcsin"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "arcsin"
+                                  ]
+                              ]
+                          ]
+                      ]
+                  , Row
+                      ( "" , [] , [] )
+                      [ Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\cos"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "cos"
+                                  ]
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\cosh"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "cosh"
+                                  ]
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\arccos"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "arccos"
+                                  ]
+                              ]
+                          ]
+                      ]
+                  , Row
+                      ( "" , [] , [] )
+                      [ Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\tan"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "tan"
+                                  ]
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\tanh"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "tanh"
+                                  ]
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\arctan"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "arctan"
+                                  ]
+                              ]
+                          ]
+                      ]
+                  , Row
+                      ( "" , [] , [] )
+                      [ Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\sec"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "sec"
+                                  ]
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\coth"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "coth"
+                                  ]
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\min"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "min"
+                                  ]
+                              ]
+                          ]
+                      ]
+                  , Row
+                      ( "" , [] , [] )
+                      [ Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\csc"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "csc"
+                                  ]
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\det"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "det"
+                                  ]
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\max"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "max"
+                                  ]
+                              ]
+                          ]
+                      ]
+                  , Row
+                      ( "" , [] , [] )
+                      [ Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\cot"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "cot"
+                                  ]
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\dim"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "dim"
+                                  ]
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\inf"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "inf"
+                                  ]
+                              ]
+                          ]
+                      ]
+                  , Row
+                      ( "" , [] , [] )
+                      [ Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\exp"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "exp"
+                                  ]
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\ker"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "ker"
+                                  ]
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\sup"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "sup"
+                                  ]
+                              ]
+                          ]
+                      ]
+                  , Row
+                      ( "" , [] , [] )
+                      [ Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\log"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "log"
+                                  ]
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\deg"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "deg"
+                                  ]
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\liminf"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "liminf"
+                                  ]
+                              ]
+                          ]
+                      ]
+                  , Row
+                      ( "" , [] , [] )
+                      [ Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\ln"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "ln"
+                                  ]
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\arg"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "arg"
+                                  ]
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\limsup"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "limsup"
+                                  ]
+                              ]
+                          ]
+                      ]
+                  , Row
+                      ( "" , [] , [] )
+                      [ Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\lg"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "lg"
+                                  ]
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\gcd"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "gcd"
+                                  ]
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\lim"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "lim"
+                                  ]
+                              ]
+                          ]
+                      ]
+                  ]
+              ]
+              (TableFoot ( "" , [] , [] ) [])
+          ]
+      , Para
+          [ Strong [ Str "Other" , Space , Str "symbols\8192\160" ] ]
+      , Div
+          ( "" , [] , [ ( "align" , "center" ) ] )
+          [ Table
+              ( "" , [] , [] )
+              (Caption Nothing [])
+              [ ( AlignLeft , ColWidthDefault )
+              , ( AlignLeft , ColWidthDefault )
+              , ( AlignLeft , ColWidthDefault )
+              ]
+              (TableHead ( "" , [] , [] ) [])
+              [ TableBody
+                  ( "" , [] , [] )
+                  (RowHeadColumns 0)
+                  []
+                  [ Row
+                      ( "" , [] , [] )
+                      [ Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "<"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "<"
+                                  , Str ","
+                                  , Space
+                                  , Code ( "" , [] , [] ) "lt"
+                                  ]
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\angle"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "angle"
+                                  ]
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\cdot"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "dot"
+                                  ]
+                              ]
+                          ]
+                      ]
+                  , Row
+                      ( "" , [] , [] )
+                      [ Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\leq"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "<="
+                                  , Str ","
+                                  , Space
+                                  , Code ( "" , [] , [] ) "lt.eq"
+                                  ]
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\measuredangle"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "angle.arc"
+                                  ]
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\pm"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "plus.minus"
+                                  ]
+                              ]
+                          ]
+                      ]
+                  , Row
+                      ( "" , [] , [] )
+                      [ Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath ">"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) ">"
+                                  , Str ","
+                                  , Space
+                                  , Code ( "" , [] , [] ) "gt"
+                                  ]
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\ell"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "ell"
+                                  ]
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\mp"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "minus.plus"
+                                  ]
+                              ]
+                          ]
+                      ]
+                  , Row
+                      ( "" , [] , [] )
+                      [ Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\geq"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) ">="
+                                  , Str ","
+                                  , Space
+                                  , Code ( "" , [] , [] ) "gt.eq"
+                                  ]
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\parallel"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "parallel"
+                                  ]
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\times"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "times"
+                                  ]
+                              ]
+                          ]
+                      ]
+                  , Row
+                      ( "" , [] , [] )
+                      [ Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\neq"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "!="
+                                  , Str ","
+                                  , Space
+                                  , Code ( "" , [] , [] ) "eq.not"
+                                  ]
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "45{^\\circ}"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "45 degree"
+                                  ]
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\div"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "div"
+                                  ]
+                              ]
+                          ]
+                      ]
+                  , Row
+                      ( "" , [] , [] )
+                      [ Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\ll"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "<<"
+                                  , Str ","
+                                  , Space
+                                  , Code ( "" , [] , [] ) "lt.double"
+                                  ]
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\cong"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "tilde.equiv"
+                                  ]
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\ast"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "*"
+                                  , Str ","
+                                  , Space
+                                  , Code ( "" , [] , [] ) "ast"
+                                  ]
+                              ]
+                          ]
+                      ]
+                  , Row
+                      ( "" , [] , [] )
+                      [ Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\gg"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) ">>"
+                                  , Str ","
+                                  , Space
+                                  , Code ( "" , [] , [] ) "gt.double"
+                                  ]
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\ncong"
+                                  , Str "\8192"
+                                  , Code
+                                      ( "" , [] , [] ) "tilde.equiv.not"
+                                  ]
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\mid"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "divides"
+                                  ]
+                              ]
+                          ]
+                      ]
+                  , Row
+                      ( "" , [] , [] )
+                      [ Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\approx"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "approx"
+                                  ]
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\sim"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "tilde"
+                                  ]
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\nmid"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "divides.not"
+                                  ]
+                              ]
+                          ]
+                      ]
+                  , Row
+                      ( "" , [] , [] )
+                      [ Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\asymp"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "\\u{224D}"
+                                  , Space
+                                  , Link
+                                      ( "" , [ "ref" ] , [] )
+                                      [ Str "[tricky]" ]
+                                      ( "#tricky" , "" )
+                                  ]
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\simeq"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "tilde.eq"
+                                  ]
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "n!"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "n!"
+                                  ]
+                              ]
+                          ]
+                      ]
+                  , Row
+                      ( "" , [] , [] )
+                      [ Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\equiv"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "equiv"
+                                  ]
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\nsim"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "tilde.not"
+                                  ]
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\partial"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "diff"
+                                  ]
+                              ]
+                          ]
+                      ]
+                  , Row
+                      ( "" , [] , [] )
+                      [ Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\prec"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "prec"
+                                  ]
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\oplus"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "plus.circle"
+                                  ]
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\nabla"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "nabla"
+                                  ]
+                              ]
+                          ]
+                      ]
+                  , Row
+                      ( "" , [] , [] )
+                      [ Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\preceq"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "prec.eq"
+                                  ]
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\ominus"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "minus.circle"
+                                  ]
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\295"
+                                  , Str "\8192"
+                                  , Code
+                                      ( "" , [] , [] ) "planck.reduce"
+                                  ]
+                              ]
+                          ]
+                      ]
+                  , Row
+                      ( "" , [] , [] )
+                      [ Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\succ"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "succ"
+                                  ]
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\odot"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "dot.circle"
+                                  ]
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\circ"
+                                  , Str "\8192"
+                                  , Code
+                                      ( "" , [] , [] )
+                                      "circle.stroked.tiny"
+                                  ]
+                              ]
+                          ]
+                      ]
+                  , Row
+                      ( "" , [] , [] )
+                      [ Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\succeq"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "succ.eq"
+                                  ]
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\otimes"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "times.circle"
+                                  ]
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\star"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "star"
+                                  ]
+                              ]
+                          ]
+                      ]
+                  , Row
+                      ( "" , [] , [] )
+                      [ Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\propto"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "prop"
+                                  ]
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\oslash"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "\\u{2298}"
+                                  , Space
+                                  , Link
+                                      ( "" , [ "ref" ] , [] )
+                                      [ Str "[tricky]" ]
+                                      ( "#tricky" , "" )
+                                  ]
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\sqrt{}"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "sqrt(\"\")"
+                                  ]
+                              ]
+                          ]
+                      ]
+                  , Row
+                      ( "" , [] , [] )
+                      [ Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\doteq"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "\\u{2250}"
+                                  , Space
+                                  , Link
+                                      ( "" , [ "ref" ] , [] )
+                                      [ Str "[tricky]" ]
+                                      ( "#tricky" , "" )
+                                  ]
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\upharpoonright"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "harpoon.tr"
+                                  ]
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\10003"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "checkmark"
+                                  ]
+                              ]
+                          ]
+                      ]
+                  ]
+              ]
+              (TableFoot ( "" , [] , [] ) [])
+          ]
+      , Para
+          [ Str "Use"
+          , Space
+          , Code ( "" , [] , [] ) "a divides b"
+          , Space
+          , Str "for"
+          , Space
+          , Str "the"
+          , Space
+          , Str "divides"
+          , Space
+          , Str "relation,"
+          , Space
+          , Math InlineMath "a \\mid b"
+          , Str ","
+          , Space
+          , Str "and"
+          , Space
+          , Code ( "" , [] , [] ) "a divides.not b"
+          , Space
+          , Str "for"
+          , Space
+          , Str "the"
+          , Space
+          , Str "negation,"
+          , Space
+          , Math InlineMath "a \\nmid b"
+          , Str "."
+          , SoftBreak
+          , Str "Use"
+          , Space
+          , Code ( "" , [] , [] ) "|"
+          , Space
+          , Str "to"
+          , Space
+          , Str "get"
+          , Space
+          , Str "set"
+          , Space
+          , Str "builder"
+          , Space
+          , Str "notation"
+          , Space
+          , Math
+              InlineMath
+              "\\left\\{ a \\in S~|~a\\text{ is odd} \\right\\}"
+          , Space
+          , Str "with"
+          , Space
+          , Code ( "" , [] , [] ) "{a in S | a \"is odd\"}"
+          , Str "."
+          ]
+      , Para [ Strong [ Str "Arrows\8192\160" ] ]
+      , Div
+          ( "" , [] , [ ( "align" , "center" ) ] )
+          [ Table
+              ( "" , [] , [] )
+              (Caption Nothing [])
+              [ ( AlignLeft , ColWidthDefault )
+              , ( AlignLeft , ColWidthDefault )
+              ]
+              (TableHead ( "" , [] , [] ) [])
+              [ TableBody
+                  ( "" , [] , [] )
+                  (RowHeadColumns 0)
+                  []
+                  [ Row
+                      ( "" , [] , [] )
+                      [ Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\rightarrow"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "->"
+                                  , Str ","
+                                  , Space
+                                  , Code ( "" , [] , [] ) "arrow.r"
+                                  ]
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\mapsto"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "|->"
+                                  , Str ","
+                                  , Space
+                                  , Code ( "" , [] , [] ) "arrow.r.bar"
+                                  ]
+                              ]
+                          ]
+                      ]
+                  , Row
+                      ( "" , [] , [] )
+                      [ Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\nrightarrow"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "arrow.r.not"
+                                  ]
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\longmapsto"
+                                  , Str "\8192"
+                                  , Code
+                                      ( "" , [] , [] )
+                                      "arrow.r.long.bar"
+                                  ]
+                              ]
+                          ]
+                      ]
+                  , Row
+                      ( "" , [] , [] )
+                      [ Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\longrightarrow"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "arrow.r.long"
+                                  ]
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\leftarrow"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "<-"
+                                  , Str ","
+                                  , Space
+                                  , Code ( "" , [] , [] ) "arrow.l"
+                                  ]
+                              ]
+                          ]
+                      ]
+                  , Row
+                      ( "" , [] , [] )
+                      [ Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\Rightarrow"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "=>"
+                                  , Str ","
+                                  , Space
+                                  , Code
+                                      ( "" , [] , [] ) "arrow.r.double"
+                                  ]
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math
+                                      InlineMath "\\longleftrightarrow"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "<-->"
+                                  , Str ","
+                                  , Space
+                                  , Code
+                                      ( "" , [] , [] ) "arrow.l.r.long"
+                                  ]
+                              ]
+                          ]
+                      ]
+                  , Row
+                      ( "" , [] , [] )
+                      [ Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\nRightarrow"
+                                  , Str "\8192"
+                                  , Code
+                                      ( "" , [] , [] )
+                                      "arrow.r.double.not"
+                                  ]
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\downarrow"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "arrow.b"
+                                  ]
+                              ]
+                          ]
+                      ]
+                  , Row
+                      ( "" , [] , [] )
+                      [ Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\Longrightarrow"
+                                  , Str "\8192"
+                                  , Code
+                                      ( "" , [] , [] )
+                                      "arrow.r.double.long"
+                                  ]
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\uparrow"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "arrow.t"
+                                  ]
+                              ]
+                          ]
+                      ]
+                  , Row
+                      ( "" , [] , [] )
+                      [ Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\rightsquigarrow"
+                                  , Str "\8192"
+                                  , Code
+                                      ( "" , [] , [] ) "arrow.squiggly"
+                                  ]
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\updownarrow"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "arrow.t.b"
+                                  ]
+                              ]
+                          ]
+                      ]
+                  ]
+              ]
+              (TableFoot ( "" , [] , [] ) [])
+          ]
+      , Para
+          [ Str "The"
+          , Space
+          , Str "right"
+          , Space
+          , Str "arrows"
+          , Space
+          , Str "in"
+          , Space
+          , Str "the"
+          , Space
+          , Str "first"
+          , Space
+          , Str "column"
+          , Space
+          , Str "have"
+          , Space
+          , Str "matching"
+          , Space
+          , Str "left"
+          , Space
+          , Str "arrows,"
+          , Space
+          , Str "such"
+          , Space
+          , Str "as"
+          , Space
+          , Code ( "" , [] , [] ) "arrow.l.not"
+          , Str ","
+          , Space
+          , Str "and"
+          , Space
+          , Str "there"
+          , Space
+          , Str "are"
+          , Space
+          , Str "some"
+          , Space
+          , Str "other"
+          , Space
+          , Str "matches"
+          , Space
+          , Str "for"
+          , Space
+          , Str "down"
+          , Space
+          , Str "arrows,"
+          , Space
+          , Str "etc."
+          ]
+      , Para
+          [ Strong
+              [ Str "Variable-sized"
+              , Space
+              , Str "operators\8192\160"
+              ]
+          , Str "The"
+          , Space
+          , Str "summation"
+          , Space
+          , Math InlineMath "\\sum_{j = 0}^{3}j^{2}"
+          , Space
+          , Code ( "" , [] , [] ) "sum_(j = 0)^3 j^2"
+          , Space
+          , Str "and"
+          , Space
+          , Str "the"
+          , Space
+          , Str "integral"
+          , Space
+          , Math InlineMath "\\int_{x = 0}^{3}x^{2}dx"
+          , Space
+          , Code ( "" , [] , [] ) "integral_(x = 0)^3 x^2 dif x"
+          , Space
+          , Str "expand"
+          , Space
+          , Str "when"
+          , Space
+          , Str "displayed."
+          ]
+      , Para
+          [ Math
+              DisplayMath
+              "\\sum_{j = 0}^{3}j^{2}\\qquad\\int_{x = 0}^{3}x^{2}dx"
+          ]
+      , Para
+          [ Str "These"
+          , Space
+          , Str "do"
+          , Space
+          , Str "the"
+          , Space
+          , Str "same."
+          ]
+      , Div
+          ( "" , [] , [ ( "align" , "center" ) ] )
+          [ Table
+              ( "" , [] , [] )
+              (Caption Nothing [])
+              [ ( AlignLeft , ColWidthDefault )
+              , ( AlignLeft , ColWidthDefault )
+              , ( AlignLeft , ColWidthDefault )
+              ]
+              (TableHead ( "" , [] , [] ) [])
+              [ TableBody
+                  ( "" , [] , [] )
+                  (RowHeadColumns 0)
+                  []
+                  [ Row
+                      ( "" , [] , [] )
+                      [ Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\int"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "integral"
+                                  ]
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\iiint"
+                                  , Str "\8192"
+                                  , Code
+                                      ( "" , [] , [] ) "integral.triple"
+                                  ]
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\bigcup"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "union.big"
+                                  ]
+                              ]
+                          ]
+                      ]
+                  , Row
+                      ( "" , [] , [] )
+                      [ Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\iint"
+                                  , Str "\8192"
+                                  , Code
+                                      ( "" , [] , [] ) "integral.double"
+                                  ]
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\oint"
+                                  , Str "\8192"
+                                  , Code
+                                      ( "" , [] , [] ) "integral.cont"
+                                  ]
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\bigcap"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "sect.big"
+                                  ]
+                              ]
+                          ]
+                      ]
+                  ]
+              ]
+              (TableFoot ( "" , [] , [] ) [])
+          ]
+      , Para [ Strong [ Str "Fences\8192\160" ] ]
+      , Div
+          ( "" , [] , [ ( "align" , "center" ) ] )
+          [ Table
+              ( "" , [] , [] )
+              (Caption Nothing [])
+              [ ( AlignLeft , ColWidthDefault )
+              , ( AlignLeft , ColWidthDefault )
+              , ( AlignLeft , ColWidthDefault )
+              ]
+              (TableHead ( "" , [] , [] ) [])
+              [ TableBody
+                  ( "" , [] , [] )
+                  (RowHeadColumns 0)
+                  []
+                  [ Row
+                      ( "" , [] , [] )
+                      [ Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "()"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "()"
+                                  ]
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\langle\\rangle"
+                                  , Str "\8192"
+                                  , Code
+                                      ( "" , [] , [] ) "angle.l angle.r"
+                                  ]
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math
+                                      InlineMath "\\left| {} \\right|"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "abs(\"\")"
+                                  ]
+                              ]
+                          ]
+                      ]
+                  , Row
+                      ( "" , [] , [] )
+                      [ Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math InlineMath "\\lbrack\\rbrack"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "[]"
+                                  ]
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math
+                                      InlineMath
+                                      "\\left\\lfloor {} \\right\\rfloor"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "floor(\"\")"
+                                  ]
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math
+                                      InlineMath
+                                      "\\left\\| {} \\right\\|"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "norm(\"\")"
+                                  ]
+                              ]
+                          ]
+                      ]
+                  , Row
+                      ( "" , [] , [] )
+                      [ Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math
+                                      InlineMath "\\left\\{ \\right\\}"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "{}"
+                                  ]
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Span
+                                  ( "" , [ "box" ] , [] )
+                                  [ Math
+                                      InlineMath
+                                      "\\left\\lceil {} \\right\\rceil"
+                                  , Str "\8192"
+                                  , Code ( "" , [] , [] ) "ceil(\"\")"
+                                  ]
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          []
+                      ]
+                  ]
+              ]
+              (TableFoot ( "" , [] , [] ) [])
+          ]
+      , Para
+          [ Str "Fix"
+          , Space
+          , Str "the"
+          , Space
+          , Str "size"
+          , Space
+          , Str "with"
+          , Space
+          , Str "the"
+          , Space
+          , Code ( "" , [] , [] ) "lr"
+          , Space
+          , Str "function."
+          ]
+      , Div
+          ( "" , [] , [ ( "align" , "center" ) ] )
+          [ Table
+              ( "" , [] , [] )
+              (Caption Nothing [])
+              [ ( AlignLeft , ColWidthDefault )
+              , ( AlignLeft , ColWidthDefault )
+              ]
+              (TableHead ( "" , [] , [] ) [])
+              [ TableBody
+                  ( "" , [] , [] )
+                  (RowHeadColumns 0)
+                  []
+                  [ Row
+                      ( "" , [] , [] )
+                      [ Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Math
+                                  DisplayMath
+                                  "\\left. \\left\\lbrack \\sum_{k = 0}^{n}e^{k^{2}} \\right\\rbrack \\right."
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ CodeBlock
+                              ( "" , [] , [] )
+                              "lr([sum_(k = 0)^n e^(k^2)], size: #50%)"
+                          ]
+                      ]
+                  ]
+              ]
+              (TableFoot ( "" , [] , [] ) [])
+          ]
+      , Para
+          [ Str "To"
+          , Space
+          , Str "have"
+          , Space
+          , Str "them"
+          , Space
+          , Str "grow"
+          , Space
+          , Str "with"
+          , Space
+          , Str "the"
+          , Space
+          , Str "enclosed"
+          , Space
+          , Str "formula,"
+          , Space
+          , Str "also"
+          , Space
+          , Str "use"
+          , Space
+          , Str "the"
+          , Space
+          , Code ( "" , [] , [] ) "lr"
+          , Space
+          , Str "function."
+          ]
+      , Div
+          ( "" , [] , [ ( "align" , "center" ) ] )
+          [ Table
+              ( "" , [] , [] )
+              (Caption Nothing [])
+              [ ( AlignLeft , ColWidthDefault )
+              , ( AlignLeft , ColWidthDefault )
+              ]
+              (TableHead ( "" , [] , [] ) [])
+              [ TableBody
+                  ( "" , [] , [] )
+                  (RowHeadColumns 0)
+                  []
+                  [ Row
+                      ( "" , [] , [] )
+                      [ Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Math
+                                  DisplayMath
+                                  "\\left\\langle i,2^{2^{i}} \\right\\rangle"
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ CodeBlock
+                              ( "" , [] , [] )
+                              "lr(angle.l i, 2^(2^i) angle.r)"
+                          ]
+                      ]
+                  ]
+              ]
+              (TableFoot ( "" , [] , [] ) [])
+          ]
+      , Para
+          [ Str "Fences"
+          , Space
+          , Str "scale"
+          , Space
+          , Str "by"
+          , Space
+          , Str "default"
+          , Space
+          , Str "if"
+          , Space
+          , Str "entered"
+          , Space
+          , Str "directly"
+          , Space
+          , Str "as"
+          , Space
+          , Str "codepoints,"
+          , Space
+          , Str "and"
+          , Space
+          , Str "don\8217t"
+          , Space
+          , Str "scale"
+          , Space
+          , Str "automatically"
+          , Space
+          , Str "if"
+          , Space
+          , Str "entered"
+          , Space
+          , Str "as"
+          , Space
+          , Str "symbol"
+          , Space
+          , Str "notation."
+          ]
+      , Div
+          ( "" , [] , [ ( "align" , "center" ) ] )
+          [ Table
+              ( "" , [] , [] )
+              (Caption Nothing [])
+              [ ( AlignLeft , ColWidthDefault )
+              , ( AlignLeft , ColWidthDefault )
+              ]
+              (TableHead ( "" , [] , [] ) [])
+              [ TableBody
+                  ( "" , [] , [] )
+                  (RowHeadColumns 0)
+                  []
+                  [ Row
+                      ( "" , [] , [] )
+                      [ Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Math
+                                  DisplayMath
+                                  "\\left( \\frac{1}{n^{\\alpha}} \\right)"
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ CodeBlock ( "" , [] , [] ) "(1 / n^(alpha))"
+                          ]
+                      ]
+                  , Row
+                      ( "" , [] , [] )
+                      [ Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Math
+                                  DisplayMath "(\\frac{1}{n^{\\alpha}})"
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ CodeBlock
+                              ( "" , [] , [] )
+                              "paren.l 1 / n^(alpha) paren.r"
+                          ]
+                      ]
+                  ]
+              ]
+              (TableFoot ( "" , [] , [] ) [])
+          ]
+      , Para
+          [ Str "The"
+          , Space
+          , Code ( "" , [] , [] ) "lr"
+          , Space
+          , Str "function"
+          , Space
+          , Str "also"
+          , Space
+          , Str "allows"
+          , Space
+          , Str "to"
+          , Space
+          , Str "scale"
+          , Space
+          , Str "unmatched"
+          , Space
+          , Str "delimiters"
+          , Space
+          , Str "and"
+          , Space
+          , Str "one-side"
+          , Space
+          , Str "fences."
+          ]
+      , Div
+          ( "" , [] , [ ( "align" , "center" ) ] )
+          [ Table
+              ( "" , [] , [] )
+              (Caption Nothing [])
+              [ ( AlignLeft , ColWidthDefault )
+              , ( AlignLeft , ColWidthDefault )
+              ]
+              (TableHead ( "" , [] , [] ) [])
+              [ TableBody
+                  ( "" , [] , [] )
+                  (RowHeadColumns 0)
+                  []
+                  [ Row
+                      ( "" , [] , [] )
+                      [ Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Math
+                                  DisplayMath
+                                  "\\left. \\frac{df}{dx} \\right|_{x_{0}}"
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ CodeBlock
+                              ( "" , [] , [] )
+                              "lr(frac(dif f, dif x) |)_(x_0)"
+                          ]
+                      ]
+                  ]
+              ]
+              (TableFoot ( "" , [] , [] ) [])
+          ]
+      , Para
+          [ Strong [ Str "Arrays," , Space , Str "Matrices\8192\160" ]
+          , Str "Get"
+          , Space
+          , Str "a"
+          , Space
+          , Str "matrix"
+          , Space
+          , Str "with"
+          , Space
+          , Str "the"
+          , Space
+          , Code ( "" , [] , [] ) "mat"
+          , Space
+          , Str "function."
+          , Space
+          , Str "You"
+          , Space
+          , Str "can"
+          , Space
+          , Str "pass"
+          , Space
+          , Str "an"
+          , Space
+          , Str "array"
+          , Space
+          , Str "to"
+          , Space
+          , Str "it."
+          ]
+      , Div
+          ( "" , [] , [ ( "align" , "center" ) ] )
+          [ Table
+              ( "" , [] , [] )
+              (Caption Nothing [])
+              [ ( AlignLeft , ColWidthDefault )
+              , ( AlignLeft , ColWidthDefault )
+              ]
+              (TableHead ( "" , [] , [] ) [])
+              [ TableBody
+                  ( "" , [] , [] )
+                  (RowHeadColumns 0)
+                  []
+                  [ Row
+                      ( "" , [] , [] )
+                      [ Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Math
+                                  DisplayMath
+                                  "\\begin{pmatrix}\na & b \\\\\nc & d\n\\end{pmatrix}"
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ CodeBlock
+                              ( "" , [] , [] ) "$ mat(a, b; c, d) $"
+                          ]
+                      ]
+                  ]
+              ]
+              (TableFoot ( "" , [] , [] ) [])
+          ]
+      , Para
+          [ Str "In"
+          , Space
+          , Str "Typst,"
+          , Space
+          , Underline
+              [ Link
+                  ( "" , [] , [] )
+                  [ Str "array" ]
+                  ( "https://typst.app/docs/reference/typst/array"
+                  , ""
+                  )
+              ]
+          , Space
+          , Str "is"
+          , Space
+          , Str "a"
+          , Space
+          , Str "sequence"
+          , Space
+          , Str "of"
+          , Space
+          , Str "values,"
+          , SoftBreak
+          , Str "while"
+          , Space
+          , Str "in"
+          , Space
+          , Span
+              ( "" , [ "box" ] , [] )
+              [ Str "L\8202A\8202"
+              , Span ( "" , [ "box" ] , [] ) [ Str "T\8202E\8202X" ]
+              ]
+          , Str ","
+          , Space
+          , Str "array"
+          , Space
+          , Str "is"
+          , Space
+          , Str "a"
+          , Space
+          , Str "matrix"
+          , Space
+          , Str "without"
+          , Space
+          , Str "fences,"
+          , Space
+          , Str "which"
+          , Space
+          , Str "is"
+          , Space
+          , Code ( "" , [] , [] ) "$mat(delim: #none, ..)$"
+          , Space
+          , Str "in"
+          , Space
+          , Str "Typst."
+          ]
+      , Para
+          [ Str "For"
+          , Space
+          , Str "the"
+          , Space
+          , Str "determinant"
+          , Space
+          , Str "use"
+          , Space
+          , Code ( "" , [] , [] ) "|A|"
+          , Str ","
+          , Space
+          , Str "text"
+          , Space
+          , Str "operator"
+          , Space
+          , Math InlineMath "\\det"
+          , Space
+          , Code ( "" , [] , [] ) "det"
+          , Space
+          , Str "or"
+          , Space
+          , Code ( "" , [] , [] ) "mat(delim: \"|\", ..)"
+          , Str "."
+          ]
+      , Para
+          [ Str "Definition"
+          , Space
+          , Str "by"
+          , Space
+          , Str "cases"
+          , Space
+          , Str "can"
+          , Space
+          , Str "be"
+          , Space
+          , Str "easily"
+          , Space
+          , Str "obtained"
+          , Space
+          , Str "with"
+          , Space
+          , Str "the"
+          , Space
+          , Code ( "" , [] , [] ) "cases"
+          , Space
+          , Str "function."
+          ]
+      , Div
+          ( "" , [] , [ ( "align" , "center" ) ] )
+          [ Table
+              ( "" , [] , [] )
+              (Caption Nothing [])
+              [ ( AlignLeft , ColWidthDefault )
+              , ( AlignLeft , ColWidthDefault )
+              ]
+              (TableHead ( "" , [] , [] ) [])
+              [ TableBody
+                  ( "" , [] , [] )
+                  (RowHeadColumns 0)
+                  []
+                  [ Row
+                      ( "" , [] , [] )
+                      [ Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Math
+                                  DisplayMath
+                                  "f_{n} = \\begin{cases}\na & \\text{if }n = 0 \\\\\nr \\cdot f_{n - 1} & \\text{else }\n\\end{cases}"
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ CodeBlock
+                              ( "" , [] , [] )
+                              "$ f_n = cases(\n  a &\"if\" n = 0,\n  r dot f_(n - 1) &\"else\"\n) $"
+                          ]
+                      ]
+                  ]
+              ]
+              (TableFoot ( "" , [] , [] ) [])
+          ]
+      , Para
+          [ Strong
+              [ Str "Spacing"
+              , Space
+              , Str "in"
+              , Space
+              , Str "mathematics\8192\160"
+              ]
+          , Str "Improve"
+          , Space
+          , Math InlineMath "\\sqrt{2}x"
+          , Space
+          , Str "to"
+          , Space
+          , Math InlineMath "\\sqrt{2}\\, x"
+          , Space
+          , Str "with"
+          , Space
+          , Str "a"
+          , Space
+          , Str "thin"
+          , Space
+          , Str "space,"
+          , Space
+          , Str "as"
+          , Space
+          , Str "in"
+          , Space
+          , Code ( "" , [] , [] ) "sqrt(2) thin x"
+          , Str "."
+          , SoftBreak
+          , Str "Slightly"
+          , Space
+          , Str "wider"
+          , Space
+          , Str "are"
+          , Space
+          , Code ( "" , [] , [] ) "medium"
+          , Space
+          , Str "and"
+          , Space
+          , Code ( "" , [] , [] ) "thick"
+          , Space
+          , Str "(the"
+          , Space
+          , Str "three"
+          , Space
+          , Str "are"
+          , Space
+          , Str "in"
+          , Space
+          , Str "ratio"
+          , Space
+          , Math InlineMath "3:4:5"
+          , Str ")."
+          , SoftBreak
+          , Str "Bigger"
+          , Space
+          , Str "space"
+          , Space
+          , Str "is"
+          , Space
+          , Code ( "" , [] , [] ) "quad"
+          , Space
+          , Str "for"
+          , Space
+          , Math InlineMath "\\rightarrow \\quad \\leftarrow"
+          , Str ","
+          , Space
+          , Str "which"
+          , Space
+          , Str "is"
+          , Space
+          , Str "useful"
+          , Space
+          , Str "between"
+          , Space
+          , Str "parts"
+          , Space
+          , Str "of"
+          , Space
+          , Str "a"
+          , Space
+          , Str "display."
+          , SoftBreak
+          , Str "Get"
+          , Space
+          , Str "arbitrary"
+          , Space
+          , Str "space"
+          , Space
+          , Str "with"
+          , Space
+          , Str "the"
+          , Space
+          , Code ( "" , [] , [] ) "h"
+          , Space
+          , Str "function."
+          , SoftBreak
+          , Str "For"
+          , Space
+          , Str "example,"
+          , Space
+          , Str "use"
+          , Space
+          , Code ( "" , [] , [] ) "#h(2em)"
+          , Space
+          , Str "for"
+          , Space
+          , Code ( "" , [] , [] ) "\\qquad"
+          , Space
+          , Str "in"
+          , Space
+          , Span
+              ( "" , [ "box" ] , [] )
+              [ Str "L\8202A\8202"
+              , Span ( "" , [ "box" ] , [] ) [ Str "T\8202E\8202X" ]
+              ]
+          , Space
+          , Str "and"
+          , Space
+          , Code ( "" , [] , [] ) "#h(-0.1667em)"
+          , Space
+          , Str "for"
+          , Space
+          , Code ( "" , [] , [] ) "\\!"
+          , Str "."
+          ]
+      , Para
+          [ Strong
+              [ Str "Displayed" , Space , Str "equations\8192\160" ]
+          , Str "Display"
+          , Space
+          , Str "equations"
+          , Space
+          , Str "in"
+          , Space
+          , Str "a"
+          , Space
+          , Str "block"
+          , Space
+          , Str "level"
+          , Space
+          , Str "using"
+          , Space
+          , Code ( "" , [] , [] ) "$ ... $"
+          , Space
+          , Str "with"
+          , Space
+          , Str "at"
+          , Space
+          , Str "least"
+          , Space
+          , Str "one"
+          , Space
+          , Str "space"
+          , Space
+          , Str "separating"
+          , Space
+          , Str "the"
+          , Space
+          , Str "math"
+          , Space
+          , Str "content"
+          , Space
+          , Str "and"
+          , Space
+          , Str "the"
+          , Space
+          , Code ( "" , [] , [] ) "$"
+          , Str "."
+          ]
+      , Div
+          ( "" , [] , [ ( "align" , "center" ) ] )
+          [ Table
+              ( "" , [] , [] )
+              (Caption Nothing [])
+              [ ( AlignLeft , ColWidthDefault )
+              , ( AlignLeft , ColWidthDefault )
+              ]
+              (TableHead ( "" , [] , [] ) [])
+              [ TableBody
+                  ( "" , [] , [] )
+                  (RowHeadColumns 0)
+                  []
+                  [ Row
+                      ( "" , [] , [] )
+                      [ Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Math DisplayMath "S = k \\cdot \\lg W" ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ CodeBlock
+                              ( "" , [] , [] ) "$ S = k dot lg W $"
+                          ]
+                      ]
+                  ]
+              ]
+              (TableFoot ( "" , [] , [] ) [])
+          ]
+      , Para
+          [ Str "You"
+          , Space
+          , Str "can"
+          , Space
+          , Str "break"
+          , Space
+          , Str "into"
+          , Space
+          , Str "multiple"
+          , Space
+          , Str "lines."
+          ]
+      , Div
+          ( "" , [] , [ ( "align" , "center" ) ] )
+          [ Table
+              ( "" , [] , [] )
+              (Caption Nothing [])
+              [ ( AlignLeft , ColWidthDefault )
+              , ( AlignLeft , ColWidthDefault )
+              ]
+              (TableHead ( "" , [] , [] ) [])
+              [ TableBody
+                  ( "" , [] , [] )
+                  (RowHeadColumns 0)
+                  []
+                  [ Row
+                      ( "" , [] , [] )
+                      [ Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Math
+                                  DisplayMath
+                                  "\\begin{array}{r}\n\\sin(x) = x - \\frac{x^{3}}{3!} \\\\\n + \\frac{x^{5}}{5!} - \\cdots\n\\end{array}"
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ CodeBlock
+                              ( "" , [] , [] )
+                              "$ sin(x) = x - x^3 / 3! \\\n    + x^5 / 5! - dots.h.c $"
+                          ]
+                      ]
+                  ]
+              ]
+              (TableFoot ( "" , [] , [] ) [])
+          ]
+      , Para
+          [ Str "Align"
+          , Space
+          , Str "equations"
+          , Space
+          , Str "using"
+          , Space
+          , Code ( "" , [] , [] ) "&"
+          ]
+      , Div
+          ( "" , [] , [ ( "align" , "center" ) ] )
+          [ Table
+              ( "" , [] , [] )
+              (Caption Nothing [])
+              [ ( AlignLeft , ColWidthDefault )
+              , ( AlignLeft , ColWidthDefault )
+              ]
+              (TableHead ( "" , [] , [] ) [])
+              [ TableBody
+                  ( "" , [] , [] )
+                  (RowHeadColumns 0)
+                  []
+                  [ Row
+                      ( "" , [] , [] )
+                      [ Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Math
+                                  DisplayMath
+                                  "\\begin{aligned}\n\\nabla \\cdot \\mathbf{D} & = \\rho \\\\\n\\nabla \\cdot \\mathbf{B} & = 0\n\\end{aligned}"
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ CodeBlock
+                              ( "" , [] , [] )
+                              "$ nabla dot bold(D) &= rho \\\n  nabla dot bold(B) &= 0 $"
+                          ]
+                      ]
+                  ]
+              ]
+              (TableFoot ( "" , [] , [] ) [])
+          ]
+      , Para
+          [ Str "(the"
+          , Space
+          , Str "left"
+          , Space
+          , Str "or"
+          , Space
+          , Str "right"
+          , Space
+          , Str "side"
+          , Space
+          , Str "of"
+          , Space
+          , Str "an"
+          , Space
+          , Str "alignment"
+          , Space
+          , Str "can"
+          , Space
+          , Str "be"
+          , Space
+          , Str "empty)."
+          , SoftBreak
+          , Str "Get"
+          , Space
+          , Str "a"
+          , Space
+          , Str "numbered"
+          , Space
+          , Str "version"
+          , Space
+          , Str "by"
+          , Space
+          , Code ( "" , [] , [] ) "#set math.equation(numbering: ..)"
+          , Str "."
+          ]
+      , Para
+          [ Strong
+              [ Str "Calculus" , Space , Str "examples\8192\160" ]
+          , Str "The"
+          , Space
+          , Str "last"
+          , Space
+          , Str "three"
+          , Space
+          , Str "here"
+          , Space
+          , Str "are"
+          , Space
+          , Str "display"
+          , Space
+          , Str "style."
+          ]
+      , Div
+          ( "" , [] , [ ( "align" , "center" ) ] )
+          [ Table
+              ( "" , [] , [] )
+              (Caption Nothing [])
+              [ ( AlignDefault , ColWidthDefault )
+              , ( AlignDefault , ColWidthDefault )
+              ]
+              (TableHead ( "" , [] , [] ) [])
+              [ TableBody
+                  ( "" , [] , [] )
+                  (RowHeadColumns 0)
+                  []
+                  [ Row
+                      ( "" , [] , [] )
+                      [ Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Math
+                                  InlineMath
+                                  "f:{\\mathbb{R}} \\rightarrow {\\mathbb{R}}"
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ CodeBlock ( "" , [] , [] ) "f: RR -> RR" ]
+                      ]
+                  , Row
+                      ( "" , [] , [] )
+                      [ Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Math InlineMath "9.8\\ \\text{ m/s}^{2}"
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Code
+                                  ( "" , [] , [] ) "\"9.8\" \"m/s\"^2"
+                              , Space
+                              , Link
+                                  ( "" , [ "ref" ] , [] )
+                                  [ Str "[tricky]" ]
+                                  ( "#tricky" , "" )
+                              ]
+                          ]
+                      ]
+                  , Row
+                      ( "" , [] , [] )
+                      [ Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Math
+                                  DisplayMath
+                                  "\\lim\\limits_{h \\rightarrow 0}\\frac{f(x + h) - f(x)}{h}"
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ CodeBlock
+                              ( "" , [] , [] )
+                              "lim_(h -> 0) (f(x + h) - f(x)) / h"
+                          ]
+                      ]
+                  , Row
+                      ( "" , [] , [] )
+                      [ Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Math
+                                  DisplayMath
+                                  "\\int x^{2}dx = x^{3}/3 + C"
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ CodeBlock
+                              ( "" , [] , [] )
+                              "integral x^2 dif x = x^3 \\/ 3 + C"
+                          ]
+                      ]
+                  , Row
+                      ( "" , [] , [] )
+                      [ Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Math
+                                  DisplayMath
+                                  "\\nabla = \\mathbf{i}\\frac{d}{dx} + \\mathbf{j}\\frac{d}{dy} + \\mathbf{k}\\frac{d}{dz}"
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ CodeBlock
+                              ( "" , [] , [] )
+                              "nabla = bold(i) dif / (dif x) + bold(j) dif / (dif y) + bold(k) dif / (dif z)"
+                          ]
+                      ]
+                  ]
+              ]
+              (TableFoot ( "" , [] , [] ) [])
+          ]
+      , Para
+          [ Strong
+              [ Str "Discrete"
+              , Space
+              , Str "mathematics"
+              , Space
+              , Str "examples\8192\160"
+              ]
+          , Str "For"
+          , Space
+          , Str "modulo,"
+          , Space
+          , Str "there"
+          , Space
+          , Str "is"
+          , Space
+          , Str "a"
+          , Space
+          , Str "symbol"
+          , Space
+          , Math InlineMath "\\equiv"
+          , Space
+          , Str "from"
+          , Space
+          , Code ( "" , [] , [] ) "equiv"
+          , Space
+          , Str "and"
+          , Space
+          , Str "a"
+          , Space
+          , Str "text"
+          , Space
+          , Str "operator"
+          , Space
+          , Math InlineMath "\\operatorname{mod}"
+          , Space
+          , Str "from"
+          , Space
+          , Code ( "" , [] , [] ) "mod"
+          , Str "."
+          ]
+      , Para
+          [ Str "For"
+          , Space
+          , Str "combinations"
+          , Space
+          , Str "the"
+          , Space
+          , Str "binomial"
+          , Space
+          , Str "symbol"
+          , Space
+          , Math InlineMath "\\binom{n}{k}"
+          , Space
+          , Str "is"
+          , Space
+          , Str "from"
+          , Space
+          , Code ( "" , [] , [] ) "binom(n, k)"
+          , Str "."
+          , SoftBreak
+          , Str "This"
+          , Space
+          , Str "resizes"
+          , Space
+          , Str "to"
+          , Space
+          , Str "be"
+          , Space
+          , Str "bigger"
+          , Space
+          , Str "in"
+          , Space
+          , Str "a"
+          , Space
+          , Str "display."
+          ]
+      , Para
+          [ Str "For"
+          , Space
+          , Str "permutations"
+          , Space
+          , Str "use"
+          , Space
+          , Math InlineMath "n^{\\underline{r}}"
+          , Space
+          , Str "from"
+          , Space
+          , Code ( "" , [] , [] ) "n^(underline(r))"
+          , Space
+          , Str "(some"
+          , Space
+          , Str "authors"
+          , Space
+          , Str "use"
+          , Space
+          , Math InlineMath "P(n,r)"
+          , Str ","
+          , Space
+          , Str "or"
+          , Space
+          , Math InlineMath "{}_{n}P_{r}"
+          , Space
+          , Str "from"
+          , Space
+          , Code ( "" , [] , [] ) "\"\"_n P_r"
+          , Str ")."
+          ]
+      , Para
+          [ Strong
+              [ Str "Statistics" , Space , Str "examples\8192\160" ]
+          ]
+      , Div
+          ( "" , [] , [ ( "align" , "center" ) ] )
+          [ Table
+              ( "" , [] , [] )
+              (Caption Nothing [])
+              [ ( AlignDefault , ColWidthDefault )
+              , ( AlignDefault , ColWidthDefault )
+              ]
+              (TableHead ( "" , [] , [] ) [])
+              [ TableBody
+                  ( "" , [] , [] )
+                  (RowHeadColumns 0)
+                  []
+                  [ Row
+                      ( "" , [] , [] )
+                      [ Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Math
+                                  InlineMath
+                                  "\\sigma^{2} = \\sqrt{{\\sum(x_{i} - \\mu)}^{2}/N}"
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ CodeBlock
+                              ( "" , [] , [] )
+                              "sigma^2 = sqrt(sum(x_i - mu)^2 \\/ N)"
+                          ]
+                      ]
+                  , Row
+                      ( "" , [] , [] )
+                      [ Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ Para
+                              [ Math
+                                  InlineMath
+                                  "E(X) = \\mu_{X} = \\sum(x_{i} - P\\left( x_{i} \\right))"
+                              ]
+                          ]
+                      , Cell
+                          ( "" , [] , [] )
+                          AlignDefault
+                          (RowSpan 1)
+                          (ColSpan 1)
+                          [ CodeBlock
+                              ( "" , [] , [] )
+                              "E(X) = mu_X = sum(x_i - P(x_i))"
+                          ]
+                      ]
+                  ]
+              ]
+              (TableFoot ( "" , [] , [] ) [])
+          ]
+      , Para
+          [ Str "The"
+          , Space
+          , Str "probability"
+          , Space
+          , Str "density"
+          , Space
+          , Str "of"
+          , Space
+          , Str "the"
+          , Space
+          , Str "normal"
+          , Space
+          , Str "distribution"
+          ]
+      , Para
+          [ Math
+              DisplayMath
+              "\\frac{1}{\\sqrt{2\\sigma^{2}\\pi}}e^{- \\frac{(x - \\mu)^{2}}{2\\sigma^{2}}}"
+          ]
+      , Para
+          [ Str "comes" , Space , Str "from" , Space , Str "this." ]
+      , Table
+          ( "" , [] , [] )
+          (Caption Nothing [])
+          [ ( AlignDefault , ColWidthDefault )
+          , ( AlignDefault , ColWidthDefault )
+          ]
+          (TableHead ( "" , [] , [] ) [])
+          [ TableBody
+              ( "" , [] , [] )
+              (RowHeadColumns 0)
+              []
+              [ Row
+                  ( "" , [] , [] )
+                  [ Cell
+                      ( "" , [] , [] )
+                      AlignDefault
+                      (RowSpan 1)
+                      (ColSpan 1)
+                      []
+                  , Cell
+                      ( "" , [] , [] )
+                      AlignDefault
+                      (RowSpan 1)
+                      (ColSpan 1)
+                      [ CodeBlock
+                          ( "" , [] , [] )
+                          "1 / sqrt(2 sigma^2 pi)\n  e^(- (x - mu)^2 / (2 sigma^2))"
+                      ]
+                  ]
+              ]
+          ]
+          (TableFoot ( "" , [] , [] ) [])
+      , Para
+          [ Strong [ Str "For" , Space , Str "more\8192\160" ]
+          , Str "See"
+          , Space
+          , Str "also"
+          , Space
+          , Str "the"
+          , Space
+          , Str "Typst"
+          , Space
+          , Str "Documentation"
+          , Space
+          , Str "at"
+          , Space
+          , Underline
+              [ Link
+                  ( "" , [] , [] )
+                  [ Str "https://typst.app/docs" ]
+                  ( "https://typst.app/docs" , "" )
+              ]
+          , Str "."
+          ]
+      , HorizontalRule
+      , Para
+          [ Str "johanvx"
+          , Space
+          , Str "("
+          , Underline
+              [ Link
+                  ( "" , [] , [] )
+                  [ Str "https://github.com/johanvx" ]
+                  ( "https://github.com/johanvx" , "" )
+              ]
+          , Str ")"
+          , Space
+          , Str "\8202\8193"
+          , Space
+          , Str "2023-05-22"
+          ]
+      ]
+  ]
diff --git a/test/typst-reader.typ b/test/typst-reader.typ
new file mode 100644
--- /dev/null
+++ b/test/typst-reader.typ
@@ -0,0 +1,28 @@
+#set page(width: 10cm, height: auto)
+#set heading(numbering: "1.")
+
+= Fibonacci sequence
+The Fibonacci sequence is defined through the
+recurrence relation $F_n = F_(n-1) + F_(n-2)$.
+It can also be expressed in _closed form:_
+
+$ F_n = round(1 / sqrt(5) phi.alt^n), quad
+  phi.alt = (1 + sqrt(5)) / 2 $
+
+#let count = 8
+#let nums = range(1, count + 1)
+#let fib(n) = (
+  if n <= 2 { 1 }
+  else { fib(n - 1) + fib(n - 2) }
+)
+
+The first #count numbers of the sequence are:
+
+#align(center, table(
+  columns: count,
+  ..nums.map(n => $F_#n$),
+  ..nums.map(n => str(fib(n))),
+))
+
+#include "undergradmath.typ"
+
diff --git a/test/undergradmath.typ b/test/undergradmath.typ
new file mode 100644
--- /dev/null
+++ b/test/undergradmath.typ
@@ -0,0 +1,510 @@
+// Licensed under the Creative Commons Attribution-ShareAlike 4.0 International License.
+// https://creativecommons.org/licenses/by-sa/4.0/
+
+// Meta data
+#set document(title: "Typst Math for Undergrads", author: "johanvx")
+
+// Margin
+#set page(margin: 0.5in)
+
+// Font size
+#let scriptsize = 7pt
+#let normalsize = 10pt
+#let large = 12pt
+#set text(size: normalsize, lang: "en")
+
+// Some horizontal spacing
+#let kern(length) = h(length, weak: true)
+#let enspace = kern(0.5em)
+#let qquad = h(2em)
+
+// For table/grid, something like "lhs \enspace rhs"
+#let cell(lhs, rhs) = box(lhs + enspace + rhs)
+// Grid for code blocks
+#set grid(columns: (2em, auto))
+// Table for math-code listing
+#set table(stroke: none, align: horizon + left, inset: 0pt, row-gutter: 0.45em)
+
+// LaTeX and TeX logos
+#let TeX = style(styles => {
+  let e = measure(text(normalsize, "E"), styles)
+  let T = "T"
+  let E = text(normalsize, baseline: e.height / 2, "E")
+  let X = "X"
+  box(T + kern(-0.1667em) + E + kern(-0.125em) + X)
+})
+#let LaTeX = style(styles => {
+  let l = measure(text(10pt, "L"), styles)
+  let a = measure(text(7pt, "A"), styles)
+  let L = "L"
+  let A = text(7pt, baseline: a.height - l.height, "A")
+  box(L + kern(-0.36em) + A + kern(-0.15em) + TeX)
+})
+
+// Update date
+#let date = "2023-05-22"
+
+// Unavailable (last check date)
+#show "??": box(text(red, [#date #emoji.crossmark]))
+// Tricky
+#show "!!": box(text(blue, emoji.drops))
+// No idea
+#show "?!": box(text(orange, [No idea #emoji.face.unhappy]))
+// Tricky figure numbering
+#set figure(numbering: n => {
+  ([??], [!!], [?!]).at(n - 1)
+})
+// No prefix
+#set ref(supplement: "")
+
+// Justified paragraphs
+#set par(justify: true)
+
+// Two-column body
+#show: rest => columns(2, rest)
+
+// headcolor
+#let headcolor = rgb("004225")
+
+// Run-in sections, like LaTeX \paragraph
+#show heading.where(
+  level: 1
+): it => text(
+  size: normalsize,
+  weight: "bold",
+  fill: headcolor,
+  it.body + h(0.67em)
+)
+
+// Black raw code
+// #show raw.where(block: false): it => { it.text }
+
+// Title
+#align(center, link("https://github.com/johanvx/typst-undergradmath")[
+  #text(large, headcolor)[*Typst Math for Undergrads*]
+])
+
+// Put this here to avoid affecting the title
+#show link: underline
+
+This is a Typst port of _#LaTeX Math for Undergrads_ by Jim Hefferon.
+The original version is available at #link("https://gitlab.com/jim.hefferon/undergradmath").
+
+= Meaning of annotations
+#figure(
+  table(
+    columns: (1fr, 2fr),
+    [??], [This is unavailable. Last check date is #date.],
+  )
+) <unavailable>
+#figure(
+  table(
+    columns: (1fr, 2fr),
+    [!!], [Get this in a tricky way. Need a simpler method.],
+  )
+) <tricky>
+#figure(
+  table(
+    columns: (1fr, 2fr),
+    [?!], [Don't know how to get this.],
+  )
+) <noidea>
+
+= Rule One
+Any mathematics at all, even a single character, gets a mathematical setting.
+Thus, for "the value of $x$ is $7$" enter `the value of $x$ is $7$`.
+
+= Template
+Your document should contain at least this.
+
+#grid(
+  "",
+  ```
+  -- document body here --
+  ```
+)
+
+= Common constructs
+#align(center, table(
+  columns: 2,
+  column-gutter: 1.5em,
+  cell($x^2$, `x^2`),
+  cell([$sqrt(2)$, $root(n, 3)$], [`sqrt(2)`, `root(n, 3)`]),
+  cell($x_(i, j)$, `x_(i, j)`),
+  cell([$2 / 3$, $2 \/ 3$], [`2 / 3`, `2 \/ 3` or `2 slash 3`]), // Maybe use `slash`?
+))
+
+= Calligraphic letters
+Use as in `$cal(A)$`.
+
+$ cal(A B C D E F G H I J K L M N O P Q R S T U V W X Y Z) $
+
+Getting script letters is @unavailable.
+
+= Greek
+#align(center, table(
+  columns: 2,
+  column-gutter: 1em,
+  cell($alpha$, `alpha`), cell([$xi$, $Xi$], [`xi`, `Xi`]),
+  cell($beta$, `beta`), cell($omicron$, `omicron`),
+  cell([$gamma$, $Gamma$], [`gamma`, `Gamma`]), cell([$pi$, $Pi$], [`pi`, `Pi`]),
+  cell([$delta$, $Delta$], [`delta`, `Delta`]), cell($pi.alt$, `pi.alt`),
+  cell($epsilon.alt$, `epsilon.alt`), cell($rho$, `rho`),
+  cell($epsilon$, `epsilon`), cell($rho.alt$, `rho.alt`),
+  cell($zeta$, `zeta`), cell([$sigma$, $Sigma$], [`sigma`, `Sigma`]),
+  cell($eta$, `eta`), cell($\u{03C2}$, [`\u{03C2}` @tricky]),
+  cell([$theta$, $Theta$], [`theta`, `Theta`]), cell($tau$, `tau`),
+  cell($theta.alt$, `theta.alt`), cell([$upsilon$, $Upsilon$], [`upsilon`, `Upsilon`]),
+  cell($iota$, `iota`), cell([$phi.alt$, $Phi$], [`phi.alt`, `Phi`]),
+  cell($kappa$, $Kappa$), cell($phi$, `phi`),
+  cell([$lambda$, $Lambda$], [`lambda`, `Lambda`]), cell($chi$, `chi`),
+  cell($mu$, `mu`), cell([$psi$, $Psi$], [`psi`, `Psi`]),
+  cell($nu$, `nu`), cell([$omega$, $Omega$], [`omega`, `Omega`]),
+))
+
+= Sets and logic
+#align(center, table(
+  columns: 3,
+  column-gutter: 1em,
+  cell($union$, `union`), cell($RR$, [`RR`, `bb(R)`]), cell($forall$, `forall`),
+  cell($sect$, `sect`), cell($bb(Z)$, [`ZZ`, `bb(Z)`]), cell($exists$, `exists`),
+  cell($subset$, `subset`), cell($bb(Q)$, [`QQ`, `bb(Q)`]), cell($not$, `not`),
+  cell($subset.eq$, `subset.eq`), cell($bb(N)$, [`NN`, `bb(N)`]), cell($or$, `or`),
+  cell($supset$, `supset`), cell($bb(C)$, [`CC`, `bb(C)`]), cell($and$, `and`),
+  cell($supset.eq$, `supset.eq`), cell($diameter$, [`diameter`]), cell($tack.r$, `tack.r`),
+  cell($in$, `in`), cell($nothing$, `nothing`), cell($models$, `models`),
+  cell($in.not$, `in.not`), cell($alef$, `alef`), cell($without$, `without`),
+))
+
+Negate an operator, as in $subset.not$, with `subset.not`.
+Get the set complement $A^(sans(c))$ with `A^(sans(c))` (or $A^(complement)$ with `A^(complement)`, or $overline(A)$ with `overline(A)`).
+
+// https://www.ctan.org/tex-archive/fonts/newcomputermodern
+//
+// README
+//
+//     Version 3.93
+//
+//       Provides access to Russian and Greek guillemotleft and guillemotright
+//     using the character variant tables cv3 and cv4 respectively.
+//
+//       The Math fonts provide the character \varnothing, an alternative to \emptyset,
+//     through Character Variant cv01. The fontsetup package provides the option
+//     'varnothing' to easily switch to the alternative character.
+
+// https://mirrors.sustech.edu.cn/CTAN/fonts/newcomputermodern/doc/newcm-doc.pdf
+// The NewComputerModern FontFamily §13.3
+// The Math fonts provide the character \varnothing (⌀, U+2300), as an alternative to \emptyset (a slashed zero), through Character Variant cv01.
+// The fontsetup package provides the option ‘varnothing’ to easily switch to the alternative character.
+
+/ Remark: Using `diameter` for `\varnothing` may cause some confusion. However, #LaTeX also uses $diameter$ (`\u{2300}`) instead of $\u{2205}$ (`\u{2205}`), see #link("https://mirrors.sustech.edu.cn/CTAN/fonts/newcomputermodern/doc/newcm-doc.pdf")[newcm $section$13.3].
+  Another solution is to use `text(font: "Fira Sans", nothing)`, but the resultant glyph $text(font: "Fira Sans", nothing)$ is subtly different from the widely used one.
+  Ultimately, the choice is always *your decision*.
+
+= Decorations
+#align(center, table(
+  columns: 3,
+  column-gutter: 1em,
+  cell($f'$, [`f'`, `f prime`]), cell($dot(a)$, `dot(a)`), cell($tilde(a)$, `tilde(a)`),
+  cell($f prime.double$, `f prime.double`), cell($diaer(a)$, `diaer(a)`), cell($macron(a)$, `macron(a)`),
+  cell($Sigma^*$, `Sigma^*`), cell($hat(a)$, `hat(a)`), cell($arrow(a)$, `arrow(a)`),
+))
+
+If the decorated letter is $i$ or $j$ then some decorations need `\u{1D6A4}` @tricky and `\u{1D6A5}` @tricky, as in $arrow(\u{1D6A4})$ with `arrow(\u{1D6A4})`.
+Some authors use boldface for vectors: `bold(x)`.
+
+Entering `overline(x + y)` produces $overline(x + y)$, and `hat(x + y)` gives $hat(x + y)$.
+Comment on an expression as here (there is also `overbrace(..)`).
+
+#align(center, cell(
+  $underbrace(x + y, |A|)$,
+  `underbrace(x + y, |A|)`,
+))
+
+= Dots
+Use low dots in a list ${0, 1, 2, ...}$, entered as `{0, 1, 2, ...}`.
+Use centered dots in a sum or product $1 + dots.h.c + 100$, entered as  `1 + dots.h.c + 100`.
+You can also get vertical dots `dots.v`, diagonal dots `dots.down` and anti-diagonal dots `dots.up`.
+
+= Roman names
+Just type them!
+
+#align(center, table(
+  columns: 3,
+  column-gutter: 1.5em,
+  cell($sin$, `sin`), cell($sinh$, `sinh`), cell($arcsin$, `arcsin`),
+  cell($cos$, `cos`), cell($cosh$, `cosh`), cell($arccos$, `arccos`),
+  cell($tan$, `tan`), cell($tanh$, `tanh`), cell($arctan$, `arctan`),
+  cell($sec$, `sec`), cell($coth$, `coth`), cell($min$, `min`),
+  cell($csc$, `csc`), cell($det$, `det`), cell($max$, `max`),
+  cell($cot$, `cot`), cell($dim$, `dim`), cell($inf$, `inf`),
+  cell($exp$, `exp`), cell($ker$, `ker`), cell($sup$, `sup`),
+  cell($log$, `log`), cell($deg$, `deg`), cell($liminf$, `liminf`),
+  cell($ln$, `ln`), cell($arg$, `arg`), cell($limsup$, `limsup`),
+  cell($lg$, `lg`), cell($gcd$, `gcd`), cell($lim$, `lim`),
+))
+
+= Other symbols
+#align(center, table(
+  columns: 3,
+  column-gutter: 1.2em,
+  cell($<$, [`<`, `lt`]), cell($angle$, `angle`), cell($dot$, [`dot`]),
+  cell($<=$, [`<=`, `lt.eq`]), cell($angle.arc$, `angle.arc`), cell($plus.minus$, `plus.minus`),
+  cell($>$, [`>`, `gt`]), cell($ell$, `ell`), cell($minus.plus$, `minus.plus`),
+  cell($>=$, [`>=`, `gt.eq`]), cell($parallel$, `parallel`), cell($times$, `times`),
+  cell($!=$, [`!=`, `eq.not`]), cell($45 degree$, `45 degree`), cell($div$, `div`),
+  cell($<<$, [`<<`, `lt.double`]), cell($tilde.equiv$, `tilde.equiv`), cell($*$, [`*`, `ast`]),
+  cell($>>$, [`>>`, `gt.double`]), cell($tilde.equiv.not$, `tilde.equiv.not`), cell($divides$, `divides`),
+  cell($approx$, `approx`), cell($tilde$, `tilde`), cell($divides.not$, `divides.not`),
+  cell($\u{224D}$, [`\u{224D}` @tricky]), cell($tilde.eq$, `tilde.eq`), cell($n!$, `n!`),
+  cell($equiv$, `equiv`), cell($tilde.not$, `tilde.not`), cell($diff$, `diff`),
+  cell($prec$, `prec`), cell($plus.circle$, `plus.circle`), cell($nabla$, `nabla`),
+  cell($prec.eq$, `prec.eq`), cell($minus.circle$, `minus.circle`), cell($planck.reduce$, `planck.reduce`),
+  cell($succ$, `succ`), cell($dot.circle$, `dot.circle`), cell($circle.stroked.tiny$, `circle.stroked.tiny`),
+  cell($succ.eq$, `succ.eq`), cell($times.circle$, `times.circle`), cell($star$, `star`),
+  cell($prop$, `prop`), cell($\u{2298}$, [`\u{2298}` @tricky]), cell($sqrt("")$, `sqrt("")`),
+  cell($\u{2250}$, [`\u{2250}` @tricky]), cell($harpoon.tr$, `harpoon.tr`), cell($checkmark$, `checkmark`),
+))
+
+Use `a divides b` for the divides relation, $a divides b$, and `a divides.not b` for the negation, $a divides.not b$.
+Use `|` to get set builder notation ${a in S | a "is odd"}$ with `{a in S | a "is odd"}`.
+
+= Arrows
+#align(center, table(
+  columns: 2,
+  column-gutter: 1.5em,
+  cell($->$, [`->`, `arrow.r`]), cell($|->$, [`|->`, `arrow.r.bar`]),
+  cell($arrow.r.not$, `arrow.r.not`), cell($arrow.r.long.bar$, `arrow.r.long.bar`),
+  cell($arrow.r.long$, `arrow.r.long`), cell($<-$, [`<-`, `arrow.l`]),
+  cell($=>$, [`=>`, `arrow.r.double`]), cell($<-->$, [`<-->`, `arrow.l.r.long`]),
+  cell($arrow.r.double.not$, `arrow.r.double.not`), cell($arrow.b$, `arrow.b`),
+  cell($arrow.r.double.long$, `arrow.r.double.long`), cell($arrow.t$, `arrow.t`),
+  cell($arrow.squiggly$, `arrow.squiggly`), cell($arrow.t.b$, `arrow.t.b`),
+))
+
+The right arrows in the first column have matching left arrows, such as `arrow.l.not`, and there are some other matches for down arrows, etc.
+
+= Variable-sized operators
+The summation $sum_(j = 0)^3 j^2$ `sum_(j = 0)^3 j^2` and the integral $integral_(x = 0)^3 x^2 dif x$ `integral_(x = 0)^3 x^2 dif x` expand when displayed.
+
+$ sum_(j = 0)^3 j^2 qquad integral_(x = 0)^3 x^2 dif x $
+
+These do the same.
+
+#align(center, table(
+  columns: 3,
+  cell($integral$, `integral`), cell($integral.triple$, `integral.triple`), cell($union.big$, `union.big`),
+  cell($integral.double$, `integral.double`), cell($integral.cont$, `integral.cont`), cell($sect.big$, `sect.big`),
+))
+
+= Fences
+#align(center, table(
+  columns: 3,
+  column-gutter: 1.5em,
+  cell($()$, `()`), cell($angle.l angle.r$, `angle.l angle.r`), cell($abs("")$, `abs("")`),
+  cell($[]$, `[]`), cell($floor("")$, `floor("")`), cell($norm("")$, `norm("")`),
+  cell(${}$, `{}`), cell($ceil("")$, `ceil("")`),
+))
+
+Fix the size with the `lr` function.
+
+#align(center, table(
+  columns: 2,
+  column-gutter: 0.5em,
+  $ lr([sum_(k = 0)^n e^(k^2)], size: #50%) $,
+  ```
+  lr([sum_(k = 0)^n e^(k^2)], size: #50%)
+  ```,
+))
+
+To have them grow with the enclosed formula, also use the `lr` function.
+
+#align(center, table(
+  columns: 2,
+  column-gutter: 1em,
+  $ lr(angle.l i, 2^(2^i) angle.r) $,
+  ```
+  lr(angle.l i, 2^(2^i) angle.r)
+  ```,
+))
+
+Fences scale by default if entered directly as codepoints, and don't scale automatically if entered as symbol notation.
+
+#align(center, table(
+  columns: 2,
+  column-gutter: 1em,
+  $ (1 / n^(alpha)) $,
+  ```
+  (1 / n^(alpha))
+  ```,
+  $ paren.l 1 / n^(alpha) paren.r $,
+  ```
+  paren.l 1 / n^(alpha) paren.r
+  ```,
+))
+
+The `lr` function also allows to scale unmatched delimiters and one-side fences.
+
+#align(center, table(
+  columns: 2,
+  column-gutter: 1em,
+  $ lr(frac(dif f, dif x) |)_(x_0) $,
+  ```
+  lr(frac(dif f, dif x) |)_(x_0)
+  ```,
+))
+
+= Arrays, Matrices
+Get a matrix with the `mat` function. You can pass an array to it.
+
+#align(center, table(
+  columns: 2,
+  column-gutter: 1em,
+  $ mat(a, b; c, d) $,
+  ```
+  $ mat(a, b; c, d) $
+  ```
+))
+
+In Typst, #link("https://typst.app/docs/reference/typst/array")[array] is a sequence of values,
+while in #LaTeX, array is a matrix without fences, which is `$mat(delim: #none, ..)$` in Typst.
+
+For the determinant use `|A|`, text operator $det$ `det` or `mat(delim: "|", ..)`.
+
+Definition by cases can be easily obtained with the `cases` function.
+
+#align(center, table(
+  columns: 2,
+  column-gutter: 1em,
+  $ f_n = cases(
+    a &"if" n = 0,
+    r dot f_(n - 1) &"else"
+  ) $,
+  ```
+  $ f_n = cases(
+    a &"if" n = 0,
+    r dot f_(n - 1) &"else"
+  ) $
+  ```
+))
+
+= Spacing in mathematics
+Improve $sqrt(2) x$ to $sqrt(2) thin x$ with a thin space, as in `sqrt(2) thin x`.
+Slightly wider are `medium` and `thick` (the three are in ratio $3 : 4 : 5$).
+Bigger space is `quad` for $arrow.r quad arrow.l$, which is useful between parts of a display.
+Get arbitrary space with the `h` function.
+For example, use `#h(2em)` for `\qquad` in #LaTeX and `#h(-0.1667em)` for `\!`.
+
+= Displayed equations
+Display equations in a block level using `$ ... $` with at least one space separating the math content and the `$`.
+
+#align(center, table(
+  columns: 2,
+  column-gutter: 1em,
+  $ S = k dot lg W $,
+  ```
+  $ S = k dot lg W $
+  ```,
+))
+
+You can break into multiple lines.
+
+#align(center, table(
+  columns: 2,
+  column-gutter: 1em,
+  $ sin(x) = x - x^3 / 3! \
+      + x^5 / 5! - dots.h.c $,
+  ```
+  $ sin(x) = x - x^3 / 3! \
+      + x^5 / 5! - dots.h.c $
+  ```,
+))
+
+Align equations using `&`
+
+#align(center, table(
+  columns: 2,
+  column-gutter: 1em,
+  $ nabla dot bold(D) &= rho \
+    nabla dot bold(B) &= 0 $,
+  ```
+  $ nabla dot bold(D) &= rho \
+    nabla dot bold(B) &= 0 $
+  ```,
+))
+
+(the left or right side of an alignment can be empty).
+Get a numbered version by `#set math.equation(numbering: ..)`.
+
+= Calculus examples
+The last three here are display style.
+
+#align(center, table(
+  align: horizon,
+  columns: 2,
+  column-gutter: 1em,
+  block($f: RR -> RR$),
+  ```
+  f: RR -> RR
+  ```,
+  block($"9.8" "m/s"^2$),
+  block([`"9.8" "m/s"^2` @tricky]),
+  $ lim_(h->0) (f(x+h)-f(x))/h $,
+  ```
+  lim_(h -> 0) (f(x + h) - f(x)) / h
+  ```,
+  $ integral x^2 dif x = x^3 \/ 3 + C $,
+  ```
+  integral x^2 dif x = x^3 \/ 3 + C
+  ```,
+  $ nabla = bold(i) dif / (dif x) + bold(j) dif / (dif y) + bold(k) dif / (dif z) $,
+  ```
+  nabla = bold(i) dif / (dif x) + bold(j) dif / (dif y) + bold(k) dif / (dif z)
+  ```,
+))
+
+= Discrete mathematics examples
+For modulo, there is a symbol $equiv$ from `equiv` and a text operator $mod$ from `mod`.
+
+For combinations the binomial symbol $binom(n, k)$ is from `binom(n, k)`.
+This resizes to be bigger in a display.
+
+For permutations use $n^(underline(r))$ from `n^(underline(r))` (some authors use $P(n, r)$, or $""_n P_r$ from `""_n P_r`).
+
+= Statistics examples
+#align(center, table(
+  align: horizon,
+  columns: 2,
+  block($sigma^2 = sqrt(sum(x_i - mu)^2 \/ N)$),
+  ```
+  sigma^2 = sqrt(sum(x_i - mu)^2 \/ N)
+  ```,
+  block($E(X) = mu_X = sum(x_i - P(x_i))$),
+  ```
+  E(X) = mu_X = sum(x_i - P(x_i))
+  ```,
+))
+
+The probability density of the normal distribution
+
+$ 1 / sqrt(2 sigma^2 pi) e^(- (x - mu)^2 / (2 sigma^2)) $
+
+comes from this.
+
+#grid(
+  "",
+  ```
+  1 / sqrt(2 sigma^2 pi)
+    e^(- (x - mu)^2 / (2 sigma^2))
+  ```
+)
+
+= For more
+See also the Typst Documentation at #link("https://typst.app/docs").
+
+#v(1fr)
+
+#block(
+  line(length: 100%, stroke: headcolor) +
+  text(headcolor)[johanvx (https://github.com/johanvx) #h(1fr) #date]
+)
diff --git a/test/vimdoc/definition-lists.markdown b/test/vimdoc/definition-lists.markdown
new file mode 100644
--- /dev/null
+++ b/test/vimdoc/definition-lists.markdown
@@ -0,0 +1,70 @@
+---
+vimdoc-prefix: pandoc
+abstract: "A short description"
+filename: "definition-lists.txt"
+author: Author
+title: Title
+---
+
+## Basic
+
+Term 1
+:   Definition I
+
+Term 2
+:   Definition II
+
+Term 3
+:   Definition III
+
+## Code
+
+<!-- Source: <https://github.com/ggandor/leap.nvim/blob/c4a215acef90749851d85ddba08bc282867b50eb/doc/leap.txt#L283-L294> -->
+
+`leap.opts.keys.next_target`
+: Jump to the next available target (use the previous search pattern if no input
+  has been given). `:h leap-repeat`
+
+`leap.opts.keys.prev_target`
+: Jump to the previous target (revert `next_target`).
+
+`leap.opts.keys.next_group`
+: Shift to the next group of labeled targets.
+
+`leap.opts.keys.prev_group`
+: Shift to the previous group of labeled targets (revert `next_group`).
+
+## Span
+
+[Important concept]{#important-concept}
+: Definition
+
+[I am too long to fit on the same line as a reference, so reference is put above me!]{#i-am-too-long}
+: Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
+  tempor incididunt ut labore et dolore magna aliqua.
+
+## Commands
+
+In markdown vim commands are represented as inline code starting with colon (ie.
+`:MyCommand`), but writer strips the backticks
+
+`:FnlCompileBuffer`{#:FnlCompileBuffer}
+
+:   Compiles current active fennel buffer
+
+`:FnlCompile[!]`{#:FnlCompile}
+
+:   Diff compiles all indexed fennel files
+    If bang! is present then forcefully compiles all `source` files
+
+`:[range]Fnl {expr}`{#:Fnl}
+
+:    Evaluates {expr} or range
+
+     ```
+     :'<,'>Fnl
+
+     :Fnl (print "Hello World")
+
+     :Fnl (values some_var)
+     ```
diff --git a/test/vimdoc/definition-lists.vimdoc b/test/vimdoc/definition-lists.vimdoc
new file mode 100644
--- /dev/null
+++ b/test/vimdoc/definition-lists.vimdoc
@@ -0,0 +1,71 @@
+*definition-lists.txt*	A short description
+
+                               Title by Author
+
+
+                                       Type |gO| to see the table of contents.
+
+Basic ........................................................... |pandoc-basic|
+Code ............................................................. |pandoc-code|
+Span ............................................................. |pandoc-span|
+Commands ..................................................... |pandoc-commands|
+
+------------------------------------------------------------------------------
+Basic                                                             *pandoc-basic*
+
+Term 1
+    Definition I
+Term 2
+    Definition II
+Term 3
+    Definition III
+
+------------------------------------------------------------------------------
+Code                                                               *pandoc-code*
+
+`leap.opts.keys.next_target`
+    Jump to the next available target (use the previous search pattern if no
+    input has been given). |leap-repeat|
+`leap.opts.keys.prev_target`
+    Jump to the previous target (revert `next_target`).
+`leap.opts.keys.next_group`
+    Shift to the next group of labeled targets.
+`leap.opts.keys.prev_group`
+    Shift to the previous group of labeled targets (revert `next_group`).
+
+------------------------------------------------------------------------------
+Span                                                               *pandoc-span*
+
+Important concept                                     *pandoc-important-concept*
+    Definition
+                                                          *pandoc-i-am-too-long*
+I am too long to fit on the same line as a reference, so reference is put
+above me!
+    Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
+    tempor incididunt ut labore et dolore magna aliqua.
+
+------------------------------------------------------------------------------
+Commands                                                       *pandoc-commands*
+
+In markdown vim commands are represented as inline code starting with colon
+(ie. `:MyCommand`), but writer strips the backticks
+
+:FnlCompileBuffer                                            *:FnlCompileBuffer*
+    Compiles current active fennel buffer
+
+:FnlCompile[!]                                                     *:FnlCompile*
+    Diff compiles all indexed fennel files If bang! is present then forcefully
+    compiles all `source` files
+
+:[range]Fnl {expr}                                                        *:Fnl*
+    Evaluates {expr} or range
+
+    >
+        :'<,'>Fnl
+
+        :Fnl (print "Hello World")
+
+        :Fnl (values some_var)
+<
+
+ vim:tw=78:sw=4:ts=4:ft=help:norl:et:
diff --git a/test/vimdoc/headers-numbered.vimdoc b/test/vimdoc/headers-numbered.vimdoc
new file mode 100644
--- /dev/null
+++ b/test/vimdoc/headers-numbered.vimdoc
@@ -0,0 +1,108 @@
+                                       Type |gO| to see the table of contents.
+
+1. unremarkable header 1 ............................... |unremarkable-header-1|
+  1.1 unremarkable header 2 ............................ |unremarkable-header-2|
+      1.1.1 unremarkable header 3 ...................... |unremarkable-header-3|
+      1.1.2 unremarkable header 3 .................... |unremarkable-header-3-1|
+  unremarkable header 2 .............................. |unremarkable-header-2-1|
+    unremarkable header 3 ............................ |unremarkable-header-3-2|
+    unremarkable header 3 ............................ |unremarkable-header-3-3|
+2. bold italic underline strikethrough ............................... |short11|
+  2.1 superscript2 subscript3 ........................................ |short21|
+      2.1.1 smallcaps code inline math display math .................. |short31|
+      2.1.2 link image ............................................... |short32|
+3. Long header 1 long header 1 long header 1 long header 1 long heade... |long1|
+  3.1 Long header 2 long header 2 long header 2 long header 2 long h... |long21|
+      3.1.1 Long header 3 long header 3 long header 3 long header 3.... |long31|
+      3.1.2 Long header 3 long header 3 long header 3 long header 3.... |long32|
+  3.2 Long header 2 long header 2 long header 2 long header 2 long h... |long22|
+      3.2.1 Long header 3 long header 3 long header 3 long header 3.... |long33|
+      3.2.2 Long header 3 long header 3 long header 3 long header 3.... |long34|
+4. ... |long-header-1-long-header-1-long-header-1-long-header-1-long-header-1-long-header-1-long-header-1|
+  4.1 ... |long-header-2-long-header-2-long-header-2-long-header-2-long-header-2-long-header-2-long-header-2|
+      4.1.1 ... |long-header-3-long-header-3-long-header-3-long-header-3-long-header-3-long-header-3-long-header-3|
+      4.1.2 ... |long-header-3-long-header-3-long-header-3-long-header-3-long-header-3-long-header-3-long-header-3-1|
+  4.2 ... |long-header-2-long-header-2-long-header-2-long-header-2-long-header-2-long-header-2-long-header-2-1|
+      4.2.1 ... |long-header-3-long-header-3-long-header-3-long-header-3-long-header-3-long-header-3-long-header-3-2|
+      4.2.2 ... |long-header-3-long-header-3-long-header-3-long-header-3-long-header-3-long-header-3-long-header-3-3|
+
+
+Headers with a short title and implicit ref. Last 3 headers are unnumbered.
+
+==============================================================================
+unremarkable header 1                                    *unremarkable-header-1*
+
+------------------------------------------------------------------------------
+unremarkable header 2                                    *unremarkable-header-2*
+
+UNREMARKABLE HEADER 3                                    *unremarkable-header-3*
+
+UNREMARKABLE HEADER 3                                  *unremarkable-header-3-1*
+
+------------------------------------------------------------------------------
+unremarkable header 2                                  *unremarkable-header-2-1*
+
+UNREMARKABLE HEADER 3                                  *unremarkable-header-3-2*
+
+UNREMARKABLE HEADER 3                                  *unremarkable-header-3-3*
+
+ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
+
+Headers with various inline elements
+
+==============================================================================
+bold italic underline strikethrough                                    *short11*
+
+------------------------------------------------------------------------------
+superscript2 subscript3                                                *short21*
+
+SMALLCAPS `code` `$inline math$` `$display math$`                      *short31*
+
+LINK example.com                                                       *short32*
+
+ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
+
+Headers with a long name and explicit short ref
+
+==============================================================================
+Long header 1 long header 1 long header 1 long header 1 long header 1 long header 1 long header 1 *long1*
+
+------------------------------------------------------------------------------
+Long header 2 long header 2 long header 2 long header 2 long header 2 long header 2 long header 2 *long21*
+
+LONG HEADER 3 LONG HEADER 3 LONG HEADER 3 LONG HEADER 3 LONG HEADER 3 LONG HEADER 3 LONG HEADER 3 *long31*
+
+LONG HEADER 3 LONG HEADER 3 LONG HEADER 3 LONG HEADER 3 LONG HEADER 3 LONG HEADER 3 LONG HEADER 3 *long32*
+
+------------------------------------------------------------------------------
+Long header 2 long header 2 long header 2 long header 2 long header 2 long header 2 long header 2 *long22*
+
+LONG HEADER 3 LONG HEADER 3 LONG HEADER 3 LONG HEADER 3 LONG HEADER 3 LONG HEADER 3 LONG HEADER 3 *long33*
+
+LONG HEADER 3 LONG HEADER 3 LONG HEADER 3 LONG HEADER 3 LONG HEADER 3 LONG HEADER 3 LONG HEADER 3 *long34*
+
+ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
+
+Headers with a long name and implicit ref.
+
+Since implicit ref is very lengthy, there is no way to fit it. Therefore title
+is not rendered and the references exceed the columns (textwidth) limit
+
+==============================================================================
+Long header 1 long header 1 long header 1 long header 1 long header 1 long header 1 long header 1 *long-header-1-long-header-1-long-header-1-long-header-1-long-header-1-long-header-1-long-header-1*
+
+------------------------------------------------------------------------------
+Long header 2 long header 2 long header 2 long header 2 long header 2 long header 2 long header 2 *long-header-2-long-header-2-long-header-2-long-header-2-long-header-2-long-header-2-long-header-2*
+
+LONG HEADER 3 LONG HEADER 3 LONG HEADER 3 LONG HEADER 3 LONG HEADER 3 LONG HEADER 3 LONG HEADER 3 *long-header-3-long-header-3-long-header-3-long-header-3-long-header-3-long-header-3-long-header-3*
+
+LONG HEADER 3 LONG HEADER 3 LONG HEADER 3 LONG HEADER 3 LONG HEADER 3 LONG HEADER 3 LONG HEADER 3 *long-header-3-long-header-3-long-header-3-long-header-3-long-header-3-long-header-3-long-header-3-1*
+
+------------------------------------------------------------------------------
+Long header 2 long header 2 long header 2 long header 2 long header 2 long header 2 long header 2 *long-header-2-long-header-2-long-header-2-long-header-2-long-header-2-long-header-2-long-header-2-1*
+
+LONG HEADER 3 LONG HEADER 3 LONG HEADER 3 LONG HEADER 3 LONG HEADER 3 LONG HEADER 3 LONG HEADER 3 *long-header-3-long-header-3-long-header-3-long-header-3-long-header-3-long-header-3-long-header-3-2*
+
+LONG HEADER 3 LONG HEADER 3 LONG HEADER 3 LONG HEADER 3 LONG HEADER 3 LONG HEADER 3 LONG HEADER 3 *long-header-3-long-header-3-long-header-3-long-header-3-long-header-3-long-header-3-long-header-3-3*
+
+ vim:tw=78:sw=4:ts=4:ft=help:norl:et:
diff --git a/test/vimdoc/headers.markdown b/test/vimdoc/headers.markdown
new file mode 100644
--- /dev/null
+++ b/test/vimdoc/headers.markdown
@@ -0,0 +1,45 @@
+Headers with a short title and implicit ref. Last 3 headers are unnumbered.
+
+# unremarkable header 1
+## unremarkable header 2
+### unremarkable header 3
+### unremarkable header 3
+## unremarkable header 2 {.unnumbered}
+### unremarkable header 3 {.unnumbered}
+### unremarkable header 3 {.unnumbered}
+
+---
+
+Headers with various inline elements
+
+# **bold** *italic* [underline]{.underline} ~strikethrough~ {#short11}
+## superscript^2^ subscript~3~ {#short21}
+### [smallcaps]{.smallcaps} `code` $inline math$ $$display math$$ {#short31}
+### [link](example.com) ![image](https://duckduckgo.com/favicon.ico) {#short32}
+
+---
+
+Headers with a long name and explicit short ref
+
+# Long header 1 long header 1 long header 1 long header 1 long header 1 long header 1 long header 1 {#long1}
+## Long header 2 long header 2 long header 2 long header 2 long header 2 long header 2 long header 2 {#long21}
+### Long header 3 long header 3 long header 3 long header 3 long header 3 long header 3 long header 3 {#long31}
+### Long header 3 long header 3 long header 3 long header 3 long header 3 long header 3 long header 3 {#long32}
+## Long header 2 long header 2 long header 2 long header 2 long header 2 long header 2 long header 2 {#long22}
+### Long header 3 long header 3 long header 3 long header 3 long header 3 long header 3 long header 3 {#long33}
+### Long header 3 long header 3 long header 3 long header 3 long header 3 long header 3 long header 3 {#long34}
+
+---
+
+Headers with a long name and implicit ref.
+
+Since implicit ref is very lengthy, there is no way to fit it. Therefore title
+is not rendered and the references exceed the columns (textwidth) limit
+
+# Long header 1 long header 1 long header 1 long header 1 long header 1 long header 1 long header 1
+## Long header 2 long header 2 long header 2 long header 2 long header 2 long header 2 long header 2
+### Long header 3 long header 3 long header 3 long header 3 long header 3 long header 3 long header 3
+### Long header 3 long header 3 long header 3 long header 3 long header 3 long header 3 long header 3
+## Long header 2 long header 2 long header 2 long header 2 long header 2 long header 2 long header 2
+### Long header 3 long header 3 long header 3 long header 3 long header 3 long header 3 long header 3
+### Long header 3 long header 3 long header 3 long header 3 long header 3 long header 3 long header 3
diff --git a/test/vimdoc/headers.vimdoc b/test/vimdoc/headers.vimdoc
new file mode 100644
--- /dev/null
+++ b/test/vimdoc/headers.vimdoc
@@ -0,0 +1,94 @@
+                                       Type |gO| to see the table of contents.
+
+unremarkable header 1 .................................. |unremarkable-header-1|
+  unremarkable header 2 ................................ |unremarkable-header-2|
+  unremarkable header 2 .............................. |unremarkable-header-2-1|
+bold italic underline strikethrough .................................. |short11|
+  superscript2 subscript3 ............................................ |short21|
+Long header 1 long header 1 long header 1 long header 1 long header 1... |long1|
+  Long header 2 long header 2 long header 2 long header 2 long heade... |long21|
+  Long header 2 long header 2 long header 2 long header 2 long heade... |long22|
+... |long-header-1-long-header-1-long-header-1-long-header-1-long-header-1-long-header-1-long-header-1|
+  ... |long-header-2-long-header-2-long-header-2-long-header-2-long-header-2-long-header-2-long-header-2|
+  ... |long-header-2-long-header-2-long-header-2-long-header-2-long-header-2-long-header-2-long-header-2-1|
+
+
+Headers with a short title and implicit ref. Last 3 headers are unnumbered.
+
+==============================================================================
+unremarkable header 1                                    *unremarkable-header-1*
+
+------------------------------------------------------------------------------
+unremarkable header 2                                    *unremarkable-header-2*
+
+UNREMARKABLE HEADER 3                                    *unremarkable-header-3*
+
+UNREMARKABLE HEADER 3                                  *unremarkable-header-3-1*
+
+------------------------------------------------------------------------------
+unremarkable header 2                                  *unremarkable-header-2-1*
+
+UNREMARKABLE HEADER 3                                  *unremarkable-header-3-2*
+
+UNREMARKABLE HEADER 3                                  *unremarkable-header-3-3*
+
+ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
+
+Headers with various inline elements
+
+==============================================================================
+bold italic underline strikethrough                                    *short11*
+
+------------------------------------------------------------------------------
+superscript2 subscript3                                                *short21*
+
+SMALLCAPS `code` `$inline math$` `$display math$`                      *short31*
+
+LINK example.com                                                       *short32*
+
+ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
+
+Headers with a long name and explicit short ref
+
+==============================================================================
+Long header 1 long header 1 long header 1 long header 1 long header 1 long header 1 long header 1 *long1*
+
+------------------------------------------------------------------------------
+Long header 2 long header 2 long header 2 long header 2 long header 2 long header 2 long header 2 *long21*
+
+LONG HEADER 3 LONG HEADER 3 LONG HEADER 3 LONG HEADER 3 LONG HEADER 3 LONG HEADER 3 LONG HEADER 3 *long31*
+
+LONG HEADER 3 LONG HEADER 3 LONG HEADER 3 LONG HEADER 3 LONG HEADER 3 LONG HEADER 3 LONG HEADER 3 *long32*
+
+------------------------------------------------------------------------------
+Long header 2 long header 2 long header 2 long header 2 long header 2 long header 2 long header 2 *long22*
+
+LONG HEADER 3 LONG HEADER 3 LONG HEADER 3 LONG HEADER 3 LONG HEADER 3 LONG HEADER 3 LONG HEADER 3 *long33*
+
+LONG HEADER 3 LONG HEADER 3 LONG HEADER 3 LONG HEADER 3 LONG HEADER 3 LONG HEADER 3 LONG HEADER 3 *long34*
+
+ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
+
+Headers with a long name and implicit ref.
+
+Since implicit ref is very lengthy, there is no way to fit it. Therefore title
+is not rendered and the references exceed the columns (textwidth) limit
+
+==============================================================================
+Long header 1 long header 1 long header 1 long header 1 long header 1 long header 1 long header 1 *long-header-1-long-header-1-long-header-1-long-header-1-long-header-1-long-header-1-long-header-1*
+
+------------------------------------------------------------------------------
+Long header 2 long header 2 long header 2 long header 2 long header 2 long header 2 long header 2 *long-header-2-long-header-2-long-header-2-long-header-2-long-header-2-long-header-2-long-header-2*
+
+LONG HEADER 3 LONG HEADER 3 LONG HEADER 3 LONG HEADER 3 LONG HEADER 3 LONG HEADER 3 LONG HEADER 3 *long-header-3-long-header-3-long-header-3-long-header-3-long-header-3-long-header-3-long-header-3*
+
+LONG HEADER 3 LONG HEADER 3 LONG HEADER 3 LONG HEADER 3 LONG HEADER 3 LONG HEADER 3 LONG HEADER 3 *long-header-3-long-header-3-long-header-3-long-header-3-long-header-3-long-header-3-long-header-3-1*
+
+------------------------------------------------------------------------------
+Long header 2 long header 2 long header 2 long header 2 long header 2 long header 2 long header 2 *long-header-2-long-header-2-long-header-2-long-header-2-long-header-2-long-header-2-long-header-2-1*
+
+LONG HEADER 3 LONG HEADER 3 LONG HEADER 3 LONG HEADER 3 LONG HEADER 3 LONG HEADER 3 LONG HEADER 3 *long-header-3-long-header-3-long-header-3-long-header-3-long-header-3-long-header-3-long-header-3-2*
+
+LONG HEADER 3 LONG HEADER 3 LONG HEADER 3 LONG HEADER 3 LONG HEADER 3 LONG HEADER 3 LONG HEADER 3 *long-header-3-long-header-3-long-header-3-long-header-3-long-header-3-long-header-3-long-header-3-3*
+
+ vim:tw=78:sw=4:ts=4:ft=help:norl:et:
diff --git a/test/vimdoc/vim-online-doc.markdown b/test/vimdoc/vim-online-doc.markdown
new file mode 100644
--- /dev/null
+++ b/test/vimdoc/vim-online-doc.markdown
@@ -0,0 +1,42 @@
+# Online vim documentation
+
+While vim documentation can be accessed with `:help`, it may be beneficial to
+link to the websites inside readme/markdown docs. Two most common websites are:
+
+- <https://vimhelp.org/> and
+- <https://neovim.io/doc/user>
+
+Also it is not uncommon to reference documentation as `:h <topic>`
+
+## Links to vimhelp.org {#vimhelp-links}
+
+For introduction to writing help files see
+<https://vimhelp.org/helphelp.txt.html#help-writing>
+
+Named link: [vimhelp link](https://vimhelp.org/helphelp.txt.html#help-writing)
+
+## Links to neo.vimhelp.org {#neo-vimhelp-links}
+
+For introduction to writing help files see
+<https://neo.vimhelp.org/helphelp.txt.html#help-writing>
+
+Named link: [vimhelp link](https://neo.vimhelp.org/helphelp.txt.html#help-writing)
+
+## Links to neovim.io {#neovim-io-links}
+
+For introduction to writing help files see
+<https://neovim.io/doc/user/helphelp.html#help-writing>
+
+Named link: [neovim.io link](https://neovim.io/doc/user/helphelp.html#help-writing)
+
+You can also reference whole files with topic omitted:
+<https://neovim.io/doc/user/vim_diff.html>
+
+## :h-style documentation {#colon-h-docs}
+
+For introduction to writing help files see
+`:h help-writing`
+
+Long name for `:help` is also supported: `:help help-writing`
+
+This is malformed: `:help help-writing `, but this is not: `:help  help-writing`
diff --git a/test/vimdoc/vim-online-doc.vimdoc b/test/vimdoc/vim-online-doc.vimdoc
new file mode 100644
--- /dev/null
+++ b/test/vimdoc/vim-online-doc.vimdoc
@@ -0,0 +1,53 @@
+                                       Type |gO| to see the table of contents.
+
+Online vim documentation ............................ |online-vim-documentation|
+  Links to vimhelp.org ......................................... |vimhelp-links|
+  Links to neo.vimhelp.org ................................. |neo-vimhelp-links|
+  Links to neovim.io ......................................... |neovim-io-links|
+  :h-style documentation ........................................ |colon-h-docs|
+
+==============================================================================
+Online vim documentation                              *online-vim-documentation*
+
+While vim documentation can be accessed with `:help`, it may be beneficial to
+link to the websites inside readme/markdown docs. Two most common websites
+are:
+
+- https://vimhelp.org/ and
+- https://neovim.io/doc/user
+
+Also it is not uncommon to reference documentation as |<topic>|
+
+------------------------------------------------------------------------------
+Links to vimhelp.org                                             *vimhelp-links*
+
+For introduction to writing help files see |help-writing|
+
+Named link: vimhelp link |help-writing|
+
+------------------------------------------------------------------------------
+Links to neo.vimhelp.org                                     *neo-vimhelp-links*
+
+For introduction to writing help files see |help-writing|
+
+Named link: vimhelp link |help-writing|
+
+------------------------------------------------------------------------------
+Links to neovim.io                                             *neovim-io-links*
+
+For introduction to writing help files see |help-writing|
+
+Named link: neovim.io link |help-writing|
+
+You can also reference whole files with topic omitted: |vim_diff.txt|
+
+------------------------------------------------------------------------------
+:h-style documentation                                            *colon-h-docs*
+
+For introduction to writing help files see |help-writing|
+
+Long name for `:help` is also supported: |help-writing|
+
+This is malformed: |help-writing|, but this is not: |help-writing|
+
+ vim:tw=78:sw=4:ts=4:ft=help:norl:et:
diff --git a/test/vimwiki-reader.native b/test/vimwiki-reader.native
--- a/test/vimwiki-reader.native
+++ b/test/vimwiki-reader.native
@@ -1,309 +1,2429 @@
-Pandoc (Meta {unMeta = fromList [("date",MetaInlines [Str "2017-05-01"]),("title",MetaInlines [Str "title"])]})
-[Header 1 ("implemented",[],[]) [Emph [Span ("implemented",[],[]) [],Strong [Str "implemented"]]]
-,Header 1 ("header",[],[]) [Str "header"]
-,Header 2 ("header level two",[],[]) [Str "header",Space,Str "level",Space,Str "two"]
-,Header 3 ("header level 3",[],[]) [Str "header",Space,Code ("",[],[]) "level",Space,Str "3"]
-,Header 4 ("header level four",[],[]) [Str "header",Space,Strikeout [Str "level"],Space,Str "four"]
-,Header 5 ("header level 5",[],[]) [Str "header",Space,Emph [Span ("level",[],[]) [],Strong [Str "level"],Space,Str "5"]]
-,Header 6 ("header level 6",[],[]) [Str "header",Space,Str "level",Space,Str "6"]
-,Para [Str "=======",Space,Str "not",Space,Str "a",Space,Str "header",Space,Str "========"]
-,Para [Str "hi==",Space,Str "not",Space,Str "a",Space,Str "header",Space,Str "=="]
-,Para [Str "===",Space,Str "not",Space,Str "a",Space,Str "header",Space,Str "=="]
-,Para [Str "===",Space,Str "not",Space,Str "a",Space,Str "header",Space,Str "===-"]
-,Para [Str "not",Space,Str "a",Space,Str "header:"]
-,Para [Str "=n="]
-,Para [Str "===",Space,Str "not",Space,Str "a",Space,Str "header",Space,Str "===="]
-,Header 2 ("centred header",["justcenter"],[]) [Str "centred",Space,Str "header"]
-,Header 2 ("header with some == in between",[],[]) [Str "header",Space,Str "with",Space,Str "some",Space,Code ("",[],[]) "==",Space,Str "in",Space,Str "between"]
-,Header 2 ("header with some == in between",[],[]) [Str "header",Space,Str "with",Space,Str "some",Space,Str "==",Space,Str "in",Space,Str "between"]
-,Header 2 ("header with some ==in between",[],[]) [Str "header",Space,Str "with",Space,Str "some",Space,Str "==in",Space,Str "between"]
-,Header 2 ("emph strong and strikeout",[],[]) [Str "emph",Space,Str "strong",Space,Str "and",Space,Str "strikeout"]
-,Para [Emph [Str "emph"],Space,Span ("strong",[],[]) [],Strong [Str "strong"]]
-,Para [Span ("strong and emph",[],[]) [],Strong [Emph [Str "strong",Space,Str "and",Space,Str "emph"]]]
-,Para [Emph [Span ("emph and strong",[],[]) [],Strong [Str "emph",Space,Str "and",Space,Str "strong"]]]
-,Para [Span ("emph inside strong",[],[]) [],Strong [Emph [Str "emph",Space,Str "inside"],Space,Str "strong"]]
-,Para [Span ("strong with emph",[],[]) [],Strong [Str "strong",Space,Str "with",Space,Emph [Str "emph"]]]
-,Para [Emph [Span ("strong inside",[],[]) [],Strong [Str "strong",Space,Str "inside"],Space,Str "emph"]]
-,Para [Emph [Strikeout [Str "strikeout"],Space,Str "inside",Space,Str "emph"]]
-,Para [Strikeout [Str "This",Space,Str "is",Space,Emph [Str "struck",Space,Str "out"],Space,Str "with",Space,Str "emph"]]
-,Para [Str "*not",SoftBreak,Str "strong*"]
-,Para [Str "just",Space,Str "two",Space,Str "stars:",Space,Str "**"]
-,Para [Str "just",Space,Str "two",Space,Str "underscores:",Space,Str "__"]
-,Para [Str "just",Space,Str "four",Space,Str "~s:",Space,Str "~~~~"]
-,Para [Str "_not",SoftBreak,Str "emph_"]
-,Para [Str "~~not",SoftBreak,Str "strikeout~~"]
-,Header 2 ("horizontal rule",[],[]) [Str "horizontal",Space,Str "rule"]
-,Para [Str "top"]
-,HorizontalRule
-,Para [Str "middle"]
-,HorizontalRule
-,Para [Str "not",Space,Str "a",Space,Str "rule-----"]
-,Para [Str "not",Space,Str "a",Space,Str "rule",Space,Str "(trailing",Space,Str "spaces):",SoftBreak,Str "-----"]
-,Para [Str "not",Space,Str "a",Space,Str "rule",Space,Str "(leading",Space,Str "spaces):",SoftBreak,Str "----"]
-,Header 2 ("comments",[],[]) [Str "comments"]
-,Para [Str "this",SoftBreak,Str "is",Space,Str "%%",Space,Str "not",Space,Str "secret"]
-,Header 2 ("inline code",[],[]) [Str "inline",Space,Str "code"]
-,Para [Str "Here",Space,Str "is",Space,Str "some",Space,Code ("",[],[]) "inline code",Str "."]
-,Para [Str "Just",Space,Str "two",Space,Str "backticks:",Space,Str "``"]
-,Header 2 ("preformatted text",[],[]) [Str "preformatted",Space,Str "text"]
-,CodeBlock ("",[],[]) "  Tyger! Tyger! burning bright\n   In the forests of the night,\n    What immortal hand or eye\n     Could frame thy fearful symmetry?\n  In what distant deeps or skies\n   Burnt the fire of thine eyes?\n    On what wings dare he aspire?\n     What the hand dare sieze the fire?"
-,Header 3 ("preformatted text with attributes",[],[]) [Str "preformatted",Space,Str "text",Space,Str "with",Space,Str "attributes"]
-,CodeBlock ("",[],[("class","python"),("style","color:blue")]) " for i in range(1, 5):\n     print(i)"
-,Header 2 ("block quotes",[],[]) [Str "block",Space,Str "quotes"]
-,BlockQuote
- [Plain [Str "(indentation",Space,Str "4",Space,Str "spaces)",Space,Str "This",Space,Str "would",Space,Str "be",Space,Str "a",Space,Str "blockquote",Space,Str "in",Space,Str "Vimwiki.",Space,Str "It",Space,Str "is",Space,Str "not",Space,Span ("highlighted",[],[]) [],Strong [Str "highlighted"],Space,Str "in",Space,Str "Vim",Space,Str "but",SoftBreak,Str "(indentation",Space,Str "1",Space,Str "space",Space,Str "followed",Space,Str "by",Space,Str "1",Space,Str "tab",Space,Str "of",Space,Str "width",Space,Str "4)",Space,Str "could",Space,Str "be",Space,Str "styled",Space,Str "by",Space,Str "CSS",Space,Str "in",Space,Str "HTML.",Space,Str "Blockquotes",Space,Str "are",Space,Str "usually",Space,Str "used",Space,Str "to",Space,Str "quote",Space,Str "a",SoftBreak,Str "(indentation",Space,Str "1",Space,Str "tab",Space,Str "of",Space,Str "width",Space,Str "4)",Space,Str "long",Space,Str "piece",Space,Str "of",Space,Str "text",Space,Str "from",Space,Str "another",Space,Str "source.",Space,Strikeout [Str "blah",Space,Str "blah"],Space,Span ("-blockquote",[],[]) [Str ""],Span ("blockquote",["tag"],[]) [Str "blockquote"]]]
-,Header 2 ("external links",[],[]) [Str "external",Space,Str "links"]
-,Para [Link ("",[],[]) [Emph [Str "Google"],Space,Str "search",Space,Str "engine"] ("http://google.com","")]
-,Para [Link ("",[],[]) [Str "http://pandoc.org"] ("http://pandoc.org","")]
-,Para [Link ("",[],[]) [Str "ftp://vim.org"] ("ftp://vim.org","")]
-,Para [Link ("",[],[]) [Str "http://google.com"] ("http://google.com","")]
-,Para [Link ("",[],[]) [Str "email",Space,Str "me"] ("mailto:info@example.org","")]
-,Para [Link ("",[],[]) [Str "mailto:hello@bye.com"] ("mailto:hello@bye.com","")]
-,Header 2 ("internal links",[],[]) [Str "internal",Space,Str "links"]
-,Para [Link ("",[],[]) [Str "This is a link"] ("This is a link.html","")]
-,Para [Link ("",[],[]) [Str "Description",Space,Str "of",Space,Str "the",Space,Str "link"] ("This is a link source.html","")]
-,Para [Link ("",[],[]) [Str "projects/Important Project 1"] ("projects/Important Project 1.html",""),SoftBreak,Link ("",[],[]) [Str "../index"] ("../index.html",""),SoftBreak,Link ("",[],[]) [Str "Other",Space,Str "files"] ("a subdirectory/","")]
-,Para [Link ("",[],[]) [Str "try",Space,Str "me",Space,Str "to",Space,Str "test",Space,Str "tag",Space,Str "anchors"] ("#tag-one","")]
-,Para [Link ("",[],[]) [Str "try",Space,Str "me",Space,Str "to",Space,Str "test",Space,Str "header",Space,Str "anchors"] ("#block quotes","")]
-,Para [Link ("",[],[]) [Str "try",Space,Str "me",Space,Str "to",Space,Str "test",Space,Str "strong",Space,Str "anchors"] ("#strong","")]
-,Para [Link ("",[],[]) [Str "Tasks",Space,Str "for",Space,Str "tomorrow"] ("Todo List.html#Tomorrow","")]
-,Para [Link ("",[],[]) [Str "diary:2017-05-01"] ("diary/2017-05-01.html","")]
-,Para [Link ("",[],[]) [Str "Important",Space,Str "Data"] ("file:../assets/data.csv","")]
-,Header 3 ("links with thumbnails",[],[]) [Str "links",Space,Str "with",Space,Str "thumbnails"]
-,Para [Link ("",[],[]) [Image ("",[],[]) [Str ""] ("./movie.jpg","")] ("http://www.google.com","")]
-,Header 2 ("images",[],[]) [Str "images"]
-,Para [Image ("",[],[]) [Str ""] ("file:./lalune.jpg","")]
-,Para [Image ("",[],[]) [Str "Vimwiki"] ("http://vimwiki.googlecode.com/hg/images/vimwiki_logo.png",""),SoftBreak,Image ("",[],[]) [Str ""] ("file:./movie.jpg","")]
-,Header 3 ("image with attributes",[],[]) [Str "image",Space,Str "with",Space,Str "attributes"]
-,Para [Image ("",[],[("style","width:150px;height:120px;")]) [Emph [Str "cool",Space,Str "stuff"]] ("lalune.jpg","")]
-,Para [Image ("",[],[("style","font-color:red")]) [Span ("Non-existing",[],[]) [],Strong [Str "Non-existing"],Space,Str "image"] ("nonexist.jpg","")]
-,Para [Image ("",[],[("style","width:150px;height:120px;")]) [Emph [Str "cool",Space,Str "stuff"]] ("lalune.jpg","")]
-,Header 2 ("lists",[],[]) [Str "lists"]
-,OrderedList (1,DefaultStyle,DefaultDelim)
- [[Plain [Str "ordered",Space,Str "list",Space,Str "item",Space,Str "1,",Space,Str "and",Space,Str "here",Space,Str "is",Space,Str "some",Space,Str "math",Space,Str "belonging",Space,Str "to",Space,Str "list",Space,Str "item",Space,Str "1"]
-  ,Para [Math DisplayMath "a^2 + b^2 = c^2"]
-  ,Plain [Str "and",Space,Str "some",Space,Str "preformatted",Space,Str "and",Space,Str "tables",Space,Str "belonging",Space,Str "to",Space,Str "item",Space,Str "1",Space,Str "as",Space,Str "well"]
-  ,CodeBlock ("",[],[]) "I'm part of item 1."
-  ,Table [] [AlignDefault,AlignDefault] [0.0,0.0]
-   [[]
-   ,[]]
-   [[[Plain [Str "this",Space,Str "table"]]
-    ,[Plain [Str "is"]]]
-   ,[[Plain [Str "also",Space,Str "a",Space,Str "part"]]
-    ,[Plain [Str "of",Space,Str "item",Space,Str "1"]]]]
-  ,Plain [Str "and",Space,Str "some",Space,Str "more",Space,Str "text",Space,Str "belonging",Space,Str "to",Space,Str "item",Space,Str "1."]]
- ,[Plain [Str "ordered",Space,Str "list",Space,Str "item",Space,Str "2"]]]
-,BulletList
- [[Plain [Str "Bulleted",Space,Str "list",Space,Str "item",Space,Str "1"]]
- ,[Plain [Str "Bulleted",Space,Str "list",Space,Str "item",Space,Str "2"]]]
-,OrderedList (1,DefaultStyle,DefaultDelim)
- [[Plain [Str "Bulleted",Space,Str "list",Space,Str "item",Space,Str "1"]]
- ,[Plain [Str "the",Space,Str "#",Space,Str "become",Space,Str "numbers",Space,Str "when",Space,Str "converted",Space,Str "to",Space,Str "HTML"]]]
-,BulletList
- [[Plain [Str "Bulleted",Space,Str "list",Space,Str "item",Space,Str "1"]]
- ,[Plain [Str "Bulleted",Space,Str "list",Space,Str "item",Space,Str "2"]]]
-,BulletList
- [[Plain [Str "Item",Space,Str "1"]]
- ,[Plain [Str "Item",Space,Str "2"]
-  ,OrderedList (1,DefaultStyle,DefaultDelim)
-   [[Plain [Str "Sub",Space,Str "item",Space,Str "1",Space,Str "(indentation",Space,Str "4",Space,Str "spaces)",SoftBreak,Str "Sub",Space,Str "item",Space,Str "1",Space,Str "continued",Space,Str "line.",SoftBreak,Str "Sub",Space,Str "item",Space,Str "1",Space,Str "next",Space,Str "continued",Space,Str "line."]]
-   ,[Plain [Str "Sub",Space,Str "item",Space,Str "2,",Space,Str "as",Space,Str "an",Space,Str "ordered",Space,Str "list",Space,Str "item",Space,Str "even",Space,Str "though",Space,Str "the",Space,Str "identifier",Space,Str "is",Space,Code ("",[],[]) "*",Space,Str "(indentation",Space,Str "2",Space,Str "spaces",Space,Str "followed",Space,Str "by",Space,Str "one",Space,Str "tab",Space,Str "of",Space,Str "width",Space,Str "4)"]]
-   ,[Plain [Str "etc.",SoftBreak,Str "Continuation",Space,Str "of",Space,Str "Item",Space,Str "2",SoftBreak,Str "Next",Space,Str "continuation",Space,Str "of",Space,Str "Item",Space,Str "2"]]]]]
-,Para [Str "But",Space,Str "this",Space,Str "is",Space,Str "a",Space,Str "new",Space,Str "paragraph."]
-,OrderedList (1,DefaultStyle,DefaultDelim)
- [[Plain [Str "1"]
-  ,BulletList
-   [[Plain [Code ("",[],[]) "1.1"]]]]
- ,[Plain [Str "2"]
-  ,BulletList
-   [[Plain [Str "2.1"]]]]]
-,BulletList
- [[Plain [Str "3"]]]
-,Header 3 ("ordered lists with non-# identifiers",[],[]) [Str "ordered",Space,Str "lists",Space,Str "with",Space,Str "non-#",Space,Str "identifiers"]
-,OrderedList (1,DefaultStyle,DefaultDelim)
- [[Plain [Str "Numbered",Space,Str "list",Space,Str "item",Space,Str "1"]]
- ,[Plain [Str "Numbered",Space,Str "list",Space,Str "item",Space,Str "2"]]
- ,[Plain [Str "Numbered",Space,Str "list",Space,Str "item",Space,Str "3"]]]
-,OrderedList (1,DefaultStyle,DefaultDelim)
- [[Plain [Str "Numbered",Space,Str "list",Space,Str "item",Space,Str "1"]]
- ,[Plain [Str "Numbered",Space,Str "list",Space,Str "item",Space,Str "2"]]
- ,[Plain [Str "Numbered",Space,Str "list",Space,Str "item",Space,Str "3"]]]
-,OrderedList (1,DefaultStyle,DefaultDelim)
- [[Plain [Str "Numbered",Space,Str "list",Space,Str "item",Space,Str "1"]]
- ,[Plain [Str "Numbered",Space,Str "list",Space,Str "item",Space,Str "2"]]
- ,[Plain [Str "Numbered",Space,Str "list",Space,Str "item",Space,Str "3"]]]
-,OrderedList (1,DefaultStyle,DefaultDelim)
- [[Plain [Str "Numbered",Space,Str "list",Space,Str "item",Space,Str "1"]]
- ,[Plain [Str "Numbered",Space,Str "list",Space,Str "item",Space,Str "2"]]
- ,[Plain [Str "Numbered",Space,Str "list",Space,Str "item",Space,Str "3"]]]
-,OrderedList (1,DefaultStyle,DefaultDelim)
- [[Plain [Str "Numbered",Space,Str "list",Space,Str "item",Space,Str "1"]]
- ,[Plain [Str "Numbered",Space,Str "list",Space,Str "item",Space,Str "2"]]
- ,[Plain [Str "Numbered",Space,Str "list",Space,Str "item",Space,Str "3"]]]
-,OrderedList (1,DefaultStyle,DefaultDelim)
- [[Plain [Str "Numbered",Space,Str "list",Space,Str "item",Space,Str "1"]]
- ,[Plain [Str "Numbered",Space,Str "list",Space,Str "item",Space,Str "2"]]
- ,[Plain [Str "Numbered",Space,Str "list",Space,Str "item",Space,Str "3"]]]
-,OrderedList (1,DefaultStyle,DefaultDelim)
- [[Plain [Str "Numbered",Space,Str "list",Space,Str "item",Space,Str "1"]]
- ,[Plain [Str "Numbered",Space,Str "list",Space,Str "item",Space,Str "2"]]
- ,[Plain [Str "Numbered",Space,Str "list",Space,Str "item",Space,Str "3"]]]
-,BulletList
- [[Plain [Str "Bulleted",Space,Str "list",Space,Str "item",Space,Str "1"]]
- ,[Plain [Str "Bulleted",Space,Str "list",Space,Str "item",Space,Str "2"]
-  ,OrderedList (1,DefaultStyle,DefaultDelim)
-   [[Plain [Str "Numbered",Space,Str "list",Space,Str "sub",Space,Str "item",Space,Str "1"]]
-   ,[Plain [Str "more",Space,Str "..."]
-    ,BulletList
-     [[Plain [Str "and",Space,Str "more",Space,Str "..."]]
-     ,[Plain [Str "..."]]]]
-   ,[Plain [Str "Numbered",Space,Str "list",Space,Str "sub",Space,Str "item",Space,Str "3"]
-    ,OrderedList (1,DefaultStyle,DefaultDelim)
-     [[Plain [Str "Numbered",Space,Str "list",Space,Str "sub",Space,Str "sub",Space,Str "item",Space,Str "1"]]
-     ,[Plain [Str "Numbered",Space,Str "list",Space,Str "sub",Space,Str "sub",Space,Str "item",Space,Str "2"]]]]
-   ,[Plain [Str "etc."]]]]
- ,[Plain [Str "Bulleted",Space,Str "list",Space,Str "item",Space,Str "3"]]]
-,Header 2 ("todo lists",[],[]) [Str "todo",Space,Str "lists"]
-,BulletList
- [[Plain [Span ("",["done0"],[]) [],Str "task",Space,Str "1"]
-  ,OrderedList (1,DefaultStyle,DefaultDelim)
-   [[Plain [Span ("",["done1"],[]) [],Str "5"]]]]
- ,[Plain [Span ("",["done2"],[]) [],Str "3"]]
- ,[Plain [Str "[]",Space,Str "not",Space,Str "a",Space,Str "todo",Space,Str "item"]]
- ,[Plain [Str "[",Space,Str "]not",Space,Str "a",Space,Str "todo",Space,Str "item"]]
- ,[Plain [Str "[r]",Space,Str "not",Space,Str "a",Space,Str "todo",Space,Str "item"]]
- ,[Plain [Str "[",Space,Str "]",Space,Str "not",Space,Str "a",Space,Str "todo",Space,Str "item"]]
- ,[Plain [Span ("",["done2"],[]) [],Str "a",Space,Str "tab",Space,Str "in",Space,Str "the",Space,Str "todo",Space,Str "list",Space,Str "marker",Space,Code ("",[],[]) "[ ]"]
-  ,OrderedList (1,DefaultStyle,DefaultDelim)
-   [[Plain [Span ("",["done3"],[]) [],Str "4",SoftBreak,Str "5"]]
-   ,[Plain [Span ("",["done4"],[]) []]
-    ,Table [] [AlignDefault,AlignDefault] [0.0,0.0]
-     [[]
-     ,[]]
-     [[[Plain [Str "a"]]
-      ,[Plain [Str "b"]]]]]]]
- ,[Plain [Span ("",["done4"],[]) [],Str "task",Space,Str "2"]]]
-,Header 2 ("math",[],[]) [Str "math"]
-,Para [Math InlineMath " \\sum_i a_i^2 = 1 "]
-,Para [Math DisplayMath "\\sum_i a_i^2\n=\n1"]
-,Para [Math DisplayMath "\\begin{aligned}\n\\sum_i a_i^2 &= 1 + 1 \\\\\n&= 2.\n\\end{aligned}"]
-,Para [Str "edge",Space,Str "case",Space,Str "(the",Space,Code ("",[],[]) "c^2 + ",Space,Str "after",Space,Str "the",Space,Str "multline",Space,Str "tag",Space,Str "is",Space,Str "in",Space,Str "the",Space,Str "equation):"]
-,Para [Math DisplayMath "\\begin{gathered}\nc^2 + \na^2 + b^2\n\\end{gathered}"]
-,Para [Str "edge",Space,Str "case",Space,Str "(the",Space,Str "tag",Space,Str "is",Space,Code ("",[],[]) "hello%bye",Str ")"]
-,Para [Math DisplayMath "\\begin{hello%bye}\n\\int_a^b f(x) dx\n\\end{hello%bye}"]
-,Para [Str "Just",Space,Str "two",Space,Str "dollar",Space,Str "signs:",Space,Str "$$"]
-,Para [Str "[not",Space,Str "math]",Space,Str "You",Space,Str "have",Space,Str "$1",SoftBreak,Str "and",Space,Str "I",Space,Str "have",Space,Str "$1."]
-,Header 2 ("tags",[],[]) [Str "tags"]
-,Para [Span ("-tag-one",[],[]) [Str ""],Span ("tag-one",["tag"],[]) [Str "tag-one"],Space,Span ("-tag-two",[],[]) [Str ""],Span ("tag-two",["tag"],[]) [Str "tag-two"]]
-,Header 2 ("tables",[],[]) [Str "tables"]
-,Table [] [AlignDefault,AlignDefault,AlignDefault] [0.0,0.0,0.0]
- [[Plain [Str "Year"]]
- ,[Plain [Str "Temperature",Space,Str "(low)"]]
- ,[Plain [Str "Temperature",Space,Str "(high)"]]]
- [[[Plain [Str "1900"]]
-  ,[Plain [Str "-10"]]
-  ,[Plain [Str "25"]]]
- ,[[Plain [Str "1910"]]
-  ,[Plain [Str "-15"]]
-  ,[Plain [Str "30"]]]
- ,[[Plain [Str "1920"]]
-  ,[Plain [Str "-10"]]
-  ,[Plain [Str "32"]]]
- ,[[Plain [Str "1930"]]
-  ,[Plain [Emph [Str "N/A"]]]
-  ,[Plain [Emph [Str "N/A"]]]]
- ,[[Plain [Str "1940"]]
-  ,[Plain [Str "-2"]]
-  ,[Plain [Str "40"]]]]
-,Header 3 ("centered headerless tables",[],[]) [Str "centered",Space,Str "headerless",Space,Str "tables"]
-,Div ("",["center"],[])
- [Table [] [AlignDefault,AlignDefault] [0.0,0.0]
-  [[]
-  ,[]]
-  [[[Plain [Str "a"]]
-   ,[Plain [Str "b"]]]
-  ,[[Plain [Str "c"]]
-   ,[Plain [Str "d"]]]]]
-,Header 2 ("paragraphs",[],[]) [Str "paragraphs"]
-,Para [Str "This",Space,Str "is",Space,Str "first",Space,Str "paragraph",SoftBreak,Str "with",Space,Str "two",Space,Str "lines."]
-,Para [Str "This",Space,Str "is",Space,Str "a",Space,Str "second",Space,Str "paragraph",Space,Str "with",SoftBreak,Str "two",Space,Str "lines",Space,Str "after",Space,Str "many",Space,Str "blank",Space,Str "lines."]
-,Header 2 ("definition list",[],[]) [Str "definition",Space,Str "list"]
-,DefinitionList
- [([Str "Term",Space,Str "1"],
-   [[Plain [Str "Definition",Space,Str "1"]]])
- ,([Str "Term",Space,Str "2"],
-   [[Plain [Str "Definition",Space,Str "2"]]
-   ,[Plain [Str "Definition",Space,Str "3"]]])
- ,([Str "Term",Space,Str "::",Space,Span ("separated",[],[]) [],Strong [Str "separated"],Space,Str "by",Space,Str "::",Space,Emph [Str "double",Space,Str "colons"]],
-   [[Plain [Str "Def1"]]
-   ,[Plain [Str "Def2"]]])
- ,([Str "Term",Space,Str "with",Space,Str "lots",Space,Str "of",Space,Str "trailing",Space,Str "colons:::::::"],
-   [[Plain [Str "Definition"]]])
- ,([Str "::",Space,Str "This",Space,Str "is",Space,Str "::",Space,Str "A",Space,Str "term",Space,Str "(rather",Space,Str "than",Space,Str "a",Space,Str "definition)"],
-   [[Plain [Str "and",Space,Str "this",Space,Str "is",Space,Str "a",Space,Str "definition"]]])
- ,([Str "Term",Space,Str "Without",Space,Str "definitions"],
-   [[]])
- ,([Str "Part",Space,Str "::",Space,Str "of",Space,Str "::",Space,Str "dt"],
-   [[Plain [Str "part",Space,Str "of",Space,Str "::dd"]]])]
-,DefinitionList
- [([],
-   [[Plain [Str "Definition",Space,Str "1",Space,Str "without",Space,Str "a",Space,Str "term"]]
-   ,[Plain [Str "Definition",Space,Str "2",Space,Str "without",Space,Str "a",Space,Str "term"]]])]
-,DefinitionList
- [([Str "T1"],
-   [[Plain [Str "D1"]]])]
-,Para [Str "new",Space,Str "paragraph"]
-,DefinitionList
- [([Str "T1"],
-   [[Plain [Str "D1"]]])]
-,Para [Str "Not::Definition"]
-,Para [Str "Not",Space,Str "::Definition"]
-,Para [Str "::Not",Space,Str "definition"]
-,BlockQuote
- [Plain [Str "::",Space,Str "blockquote"]]
-,BlockQuote
- [Plain [Str "block",Space,Str "::",Space,Str "quote"]]
-,Header 2 ("metadata placeholders",[],[]) [Str "metadata",Space,Str "placeholders"]
-,Para [Str "%this",Space,Str "is",Space,Str "not",Space,Str "a",Space,Str "placeholder"]
-,Para [Str "placeholders",SoftBreak,Str "serves",Space,Str "as",Space,Str "space",Space,Str "/",Space,Str "softbreak",Space,Str "in",Space,Str "paragraphs"]
-,Header 2 ("sup, sub",[],[]) [Str "sup,",Space,Str "sub"]
-,Para [Str "super",Superscript [Str "script"]]
-,Para [Str "sub",Subscript [Str "script"]]
-,Header 2 ("the todo mark",[],[]) [Str "the",Space,Str "todo",Space,Str "mark"]
-,Para [Span ("",["todo"],[]) [Str "TODO:"]]
-,Header 1 ("not implemented yet",[],[]) [Emph [Span ("not implemented yet",[],[]) [],Strong [Str "not",Space,Str "implemented",Space,Str "yet"]]]
-,Header 2 ("tables with spans",[],[]) [Str "tables",Space,Str "with",Space,Str "spans"]
-,Table [] [AlignDefault,AlignDefault,AlignDefault,AlignDefault] [0.0,0.0,0.0,0.0]
- [[]
- ,[]
- ,[]
- ,[]]
- [[[Plain [Str "a"]]
-  ,[Plain [Str "b"]]
-  ,[Plain [Str "c"]]
-  ,[Plain [Str "d"]]]
- ,[[Plain [Str "\\/"]]
-  ,[Plain [Str "e"]]
-  ,[Plain [Str ">"]]
-  ,[Plain [Str "f"]]]
- ,[[Plain [Str "\\/"]]
-  ,[Plain [Str "\\/"]]
-  ,[Plain [Str ">"]]
-  ,[Plain [Str "g"]]]
- ,[[Plain [Str "h"]]
-  ,[Plain [Str ">"]]
-  ,[Plain [Str ">"]]
-  ,[Plain [Str ">"]]]]
-,Header 2 ("tables with multiple lines of headers",[],[]) [Str "tables",Space,Str "with",Space,Str "multiple",Space,Str "lines",Space,Str "of",Space,Str "headers"]
-,Table [] [AlignDefault,AlignDefault] [0.0,0.0]
- [[]
- ,[]]
- [[[Plain [Str "a"]]
-  ,[Plain [Str "b"]]]
- ,[[Plain [Str "c"]]
-  ,[Plain [Str "d"]]]
- ,[[Plain [Str "---"]]
-  ,[Plain [Str "---"]]]]
-,Header 2 ("some other placeholders",[],[]) [Str "some",Space,Str "other",Space,Str "placeholders"]
-,Para [Code ("",[],[]) "template",Space,Str "placeholder",Space,Str "is",Space,Str "ignored."]
-,Para [Code ("",[],[]) "nohtml",Space,Str "placeholder",Space,Str "is",Space,Str "ignored."]]
+Pandoc
+  Meta
+    { unMeta =
+        fromList
+          [ ( "date" , MetaInlines [ Str "2017-05-01" ] )
+          , ( "title" , MetaInlines [ Str "title" ] )
+          ]
+    }
+  [ Header
+      1
+      ( "implemented" , [] , [] )
+      [ Emph
+          [ Span ( "implemented" , [] , [] ) []
+          , Strong [ Str "implemented" ]
+          ]
+      ]
+  , Header 1 ( "header" , [] , [] ) [ Str "header" ]
+  , Header
+      2
+      ( "header level two" , [] , [] )
+      [ Str "header" , Space , Str "level" , Space , Str "two" ]
+  , Header
+      3
+      ( "header level 3" , [] , [] )
+      [ Str "header"
+      , Space
+      , Code ( "" , [] , [] ) "level"
+      , Space
+      , Str "3"
+      ]
+  , Header
+      4
+      ( "header level four" , [] , [] )
+      [ Str "header"
+      , Space
+      , Strikeout [ Str "level" ]
+      , Space
+      , Str "four"
+      ]
+  , Header
+      5
+      ( "header level 5" , [] , [] )
+      [ Str "header"
+      , Space
+      , Emph
+          [ Span ( "level" , [] , [] ) []
+          , Strong [ Str "level" ]
+          , Space
+          , Str "5"
+          ]
+      ]
+  , Header
+      6
+      ( "header level 6" , [] , [] )
+      [ Str "header" , Space , Str "level" , Space , Str "6" ]
+  , Para
+      [ Str "======="
+      , Space
+      , Str "not"
+      , Space
+      , Str "a"
+      , Space
+      , Str "header"
+      , Space
+      , Str "========"
+      ]
+  , Para
+      [ Str "hi=="
+      , Space
+      , Str "not"
+      , Space
+      , Str "a"
+      , Space
+      , Str "header"
+      , Space
+      , Str "=="
+      ]
+  , Para
+      [ Str "==="
+      , Space
+      , Str "not"
+      , Space
+      , Str "a"
+      , Space
+      , Str "header"
+      , Space
+      , Str "=="
+      ]
+  , Para
+      [ Str "==="
+      , Space
+      , Str "not"
+      , Space
+      , Str "a"
+      , Space
+      , Str "header"
+      , Space
+      , Str "===-"
+      ]
+  , Para
+      [ Str "not" , Space , Str "a" , Space , Str "header:" ]
+  , Para [ Str "=n=" ]
+  , Para
+      [ Str "==="
+      , Space
+      , Str "not"
+      , Space
+      , Str "a"
+      , Space
+      , Str "header"
+      , Space
+      , Str "===="
+      ]
+  , Header
+      2
+      ( "centred header" , [ "justcenter" ] , [] )
+      [ Str "centred" , Space , Str "header" ]
+  , Header
+      2
+      ( "header with some == in between" , [] , [] )
+      [ Str "header"
+      , Space
+      , Str "with"
+      , Space
+      , Str "some"
+      , Space
+      , Code ( "" , [] , [] ) "=="
+      , Space
+      , Str "in"
+      , Space
+      , Str "between"
+      ]
+  , Header
+      2
+      ( "header with some == in between" , [] , [] )
+      [ Str "header"
+      , Space
+      , Str "with"
+      , Space
+      , Str "some"
+      , Space
+      , Str "=="
+      , Space
+      , Str "in"
+      , Space
+      , Str "between"
+      ]
+  , Header
+      2
+      ( "header with some ==in between" , [] , [] )
+      [ Str "header"
+      , Space
+      , Str "with"
+      , Space
+      , Str "some"
+      , Space
+      , Str "==in"
+      , Space
+      , Str "between"
+      ]
+  , Header
+      2
+      ( "emph strong and strikeout" , [] , [] )
+      [ Str "emph"
+      , Space
+      , Str "strong"
+      , Space
+      , Str "and"
+      , Space
+      , Str "strikeout"
+      ]
+  , Para
+      [ Emph [ Str "emph" ]
+      , Space
+      , Span ( "strong" , [] , [] ) []
+      , Strong [ Str "strong" ]
+      ]
+  , Para
+      [ Span ( "strong and emph" , [] , [] ) []
+      , Strong
+          [ Emph
+              [ Str "strong" , Space , Str "and" , Space , Str "emph" ]
+          ]
+      ]
+  , Para
+      [ Emph
+          [ Span ( "emph and strong" , [] , [] ) []
+          , Strong
+              [ Str "emph" , Space , Str "and" , Space , Str "strong" ]
+          ]
+      ]
+  , Para
+      [ Span ( "emph inside strong" , [] , [] ) []
+      , Strong
+          [ Emph [ Str "emph" , Space , Str "inside" ]
+          , Space
+          , Str "strong"
+          ]
+      ]
+  , Para
+      [ Span ( "strong with emph" , [] , [] ) []
+      , Strong
+          [ Str "strong"
+          , Space
+          , Str "with"
+          , Space
+          , Emph [ Str "emph" ]
+          ]
+      ]
+  , Para
+      [ Emph
+          [ Span ( "strong inside" , [] , [] ) []
+          , Strong [ Str "strong" , Space , Str "inside" ]
+          , Space
+          , Str "emph"
+          ]
+      ]
+  , Para
+      [ Emph
+          [ Strikeout [ Str "strikeout" ]
+          , Space
+          , Str "inside"
+          , Space
+          , Str "emph"
+          ]
+      ]
+  , Para
+      [ Strikeout
+          [ Str "This"
+          , Space
+          , Str "is"
+          , Space
+          , Emph [ Str "struck" , Space , Str "out" ]
+          , Space
+          , Str "with"
+          , Space
+          , Str "emph"
+          ]
+      ]
+  , Para [ Str "*not" , SoftBreak , Str "strong*" ]
+  , Para
+      [ Str "just"
+      , Space
+      , Str "two"
+      , Space
+      , Str "stars:"
+      , Space
+      , Str "**"
+      ]
+  , Para
+      [ Str "just"
+      , Space
+      , Str "two"
+      , Space
+      , Str "underscores:"
+      , Space
+      , Str "__"
+      ]
+  , Para
+      [ Str "just"
+      , Space
+      , Str "four"
+      , Space
+      , Str "~s:"
+      , Space
+      , Str "~~~~"
+      ]
+  , Para [ Str "_not" , SoftBreak , Str "emph_" ]
+  , Para [ Str "~~not" , SoftBreak , Str "strikeout~~" ]
+  , Header
+      2
+      ( "horizontal rule" , [] , [] )
+      [ Str "horizontal" , Space , Str "rule" ]
+  , Para [ Str "top" ]
+  , HorizontalRule
+  , Para [ Str "middle" ]
+  , HorizontalRule
+  , Para
+      [ Str "not" , Space , Str "a" , Space , Str "rule-----" ]
+  , Para
+      [ Str "not"
+      , Space
+      , Str "a"
+      , Space
+      , Str "rule"
+      , Space
+      , Str "(trailing"
+      , Space
+      , Str "spaces):"
+      , SoftBreak
+      , Str "-----"
+      ]
+  , Para
+      [ Str "not"
+      , Space
+      , Str "a"
+      , Space
+      , Str "rule"
+      , Space
+      , Str "(leading"
+      , Space
+      , Str "spaces):"
+      , SoftBreak
+      , Str "----"
+      ]
+  , Header 2 ( "comments" , [] , [] ) [ Str "comments" ]
+  , Para
+      [ Str "this"
+      , SoftBreak
+      , Str "is"
+      , Space
+      , Str "%%"
+      , Space
+      , Str "not"
+      , Space
+      , Str "secret"
+      ]
+  , Header
+      2
+      ( "inline code" , [] , [] )
+      [ Str "inline" , Space , Str "code" ]
+  , Para
+      [ Str "Here"
+      , Space
+      , Str "is"
+      , Space
+      , Str "some"
+      , Space
+      , Code ( "" , [] , [] ) "inline code"
+      , Str "."
+      ]
+  , Para
+      [ Str "Just"
+      , Space
+      , Str "two"
+      , Space
+      , Str "backticks:"
+      , Space
+      , Str "``"
+      ]
+  , Header
+      2
+      ( "preformatted text" , [] , [] )
+      [ Str "preformatted" , Space , Str "text" ]
+  , CodeBlock
+      ( "" , [] , [] )
+      "  Tyger! Tyger! burning bright\n   In the forests of the night,\n    What immortal hand or eye\n     Could frame thy fearful symmetry?\n  In what distant deeps or skies\n   Burnt the fire of thine eyes?\n    On what wings dare he aspire?\n     What the hand dare sieze the fire?"
+  , Header
+      3
+      ( "preformatted text with attributes" , [] , [] )
+      [ Str "preformatted"
+      , Space
+      , Str "text"
+      , Space
+      , Str "with"
+      , Space
+      , Str "attributes"
+      ]
+  , CodeBlock
+      ( ""
+      , []
+      , [ ( "class" , "python" ) , ( "style" , "color:blue" ) ]
+      )
+      " for i in range(1, 5):\n     print(i)"
+  , Header
+      3
+      ( "preformatted text with nested syntax" , [] , [] )
+      [ Str "preformatted"
+      , Space
+      , Str "text"
+      , Space
+      , Str "with"
+      , Space
+      , Str "nested"
+      , Space
+      , Str "syntax"
+      ]
+  , CodeBlock ( "" , [ "sql" ] , [] ) "SELECT * FROM table"
+  , Header
+      3
+      ( "empty preformatted text" , [] , [] )
+      [ Str "empty"
+      , Space
+      , Str "preformatted"
+      , Space
+      , Str "text"
+      ]
+  , CodeBlock ( "" , [] , [] ) ""
+  , Header
+      2
+      ( "block quotes" , [] , [] )
+      [ Str "block" , Space , Str "quotes" ]
+  , BlockQuote
+      [ Plain
+          [ Str "(indentation"
+          , Space
+          , Str "4"
+          , Space
+          , Str "spaces)"
+          , Space
+          , Str "This"
+          , Space
+          , Str "would"
+          , Space
+          , Str "be"
+          , Space
+          , Str "a"
+          , Space
+          , Str "blockquote"
+          , Space
+          , Str "in"
+          , Space
+          , Str "Vimwiki."
+          , Space
+          , Str "It"
+          , Space
+          , Str "is"
+          , Space
+          , Str "not"
+          , Space
+          , Span ( "highlighted" , [] , [] ) []
+          , Strong [ Str "highlighted" ]
+          , Space
+          , Str "in"
+          , Space
+          , Str "Vim"
+          , Space
+          , Str "but"
+          , SoftBreak
+          , Str "(indentation"
+          , Space
+          , Str "1"
+          , Space
+          , Str "space"
+          , Space
+          , Str "followed"
+          , Space
+          , Str "by"
+          , Space
+          , Str "1"
+          , Space
+          , Str "tab"
+          , Space
+          , Str "of"
+          , Space
+          , Str "width"
+          , Space
+          , Str "4)"
+          , Space
+          , Str "could"
+          , Space
+          , Str "be"
+          , Space
+          , Str "styled"
+          , Space
+          , Str "by"
+          , Space
+          , Str "CSS"
+          , Space
+          , Str "in"
+          , Space
+          , Str "HTML."
+          , Space
+          , Str "Blockquotes"
+          , Space
+          , Str "are"
+          , Space
+          , Str "usually"
+          , Space
+          , Str "used"
+          , Space
+          , Str "to"
+          , Space
+          , Str "quote"
+          , Space
+          , Str "a"
+          , SoftBreak
+          , Str "(indentation"
+          , Space
+          , Str "1"
+          , Space
+          , Str "tab"
+          , Space
+          , Str "of"
+          , Space
+          , Str "width"
+          , Space
+          , Str "4)"
+          , Space
+          , Str "long"
+          , Space
+          , Str "piece"
+          , Space
+          , Str "of"
+          , Space
+          , Str "text"
+          , Space
+          , Str "from"
+          , Space
+          , Str "another"
+          , Space
+          , Str "source."
+          , Space
+          , Strikeout [ Str "blah" , Space , Str "blah" ]
+          , Space
+          , Span ( "-blockquote" , [] , [] ) [ Str "" ]
+          , Span
+              ( "blockquote" , [ "tag" ] , [] ) [ Str "blockquote" ]
+          ]
+      ]
+  , Header
+      2
+      ( "external links" , [] , [] )
+      [ Str "external" , Space , Str "links" ]
+  , Para
+      [ Link
+          ( "" , [] , [] )
+          [ Emph [ Str "Google" ]
+          , Space
+          , Str "search"
+          , Space
+          , Str "engine"
+          ]
+          ( "http://google.com" , "" )
+      ]
+  , Para
+      [ Link
+          ( "" , [] , [] )
+          [ Str "http://pandoc.org" ]
+          ( "http://pandoc.org" , "" )
+      ]
+  , Para
+      [ Link
+          ( "" , [] , [] )
+          [ Str "ftp://vim.org" ]
+          ( "ftp://vim.org" , "" )
+      ]
+  , Para
+      [ Link
+          ( "" , [] , [] )
+          [ Str "http://google.com" ]
+          ( "http://google.com" , "" )
+      ]
+  , Para
+      [ Link
+          ( "" , [] , [] )
+          [ Str "email" , Space , Str "me" ]
+          ( "mailto:info@example.org" , "" )
+      ]
+  , Para
+      [ Link
+          ( "" , [] , [] )
+          [ Str "mailto:hello@bye.com" ]
+          ( "mailto:hello@bye.com" , "" )
+      ]
+  , Header
+      2
+      ( "internal links" , [] , [] )
+      [ Str "internal" , Space , Str "links" ]
+  , Para
+      [ Link
+          ( "" , [ "wikilink" ] , [] )
+          [ Str "This is a link" ]
+          ( "This is a link" , "" )
+      ]
+  , Para
+      [ Link
+          ( "" , [ "wikilink" ] , [] )
+          [ Str "Description"
+          , Space
+          , Str "of"
+          , Space
+          , Str "the"
+          , Space
+          , Str "link"
+          ]
+          ( "This is a link source" , "" )
+      ]
+  , Para
+      [ Link
+          ( "" , [ "wikilink" ] , [] )
+          [ Str "projects/Important Project 1" ]
+          ( "projects/Important Project 1" , "" )
+      , SoftBreak
+      , Link
+          ( "" , [ "wikilink" ] , [] )
+          [ Str "../index" ]
+          ( "../index" , "" )
+      , SoftBreak
+      , Link
+          ( "" , [ "wikilink" ] , [] )
+          [ Str "Other" , Space , Str "files" ]
+          ( "a subdirectory/" , "" )
+      ]
+  , Para
+      [ Link
+          ( "" , [ "wikilink" ] , [] )
+          [ Str "try"
+          , Space
+          , Str "me"
+          , Space
+          , Str "to"
+          , Space
+          , Str "test"
+          , Space
+          , Str "tag"
+          , Space
+          , Str "anchors"
+          ]
+          ( "#tag-one" , "" )
+      ]
+  , Para
+      [ Link
+          ( "" , [ "wikilink" ] , [] )
+          [ Str "try"
+          , Space
+          , Str "me"
+          , Space
+          , Str "to"
+          , Space
+          , Str "test"
+          , Space
+          , Str "header"
+          , Space
+          , Str "anchors"
+          ]
+          ( "#block quotes" , "" )
+      ]
+  , Para
+      [ Link
+          ( "" , [ "wikilink" ] , [] )
+          [ Str "try"
+          , Space
+          , Str "me"
+          , Space
+          , Str "to"
+          , Space
+          , Str "test"
+          , Space
+          , Str "strong"
+          , Space
+          , Str "anchors"
+          ]
+          ( "#strong" , "" )
+      ]
+  , Para
+      [ Link
+          ( "" , [ "wikilink" ] , [] )
+          [ Str "Tasks" , Space , Str "for" , Space , Str "tomorrow" ]
+          ( "Todo List#Tomorrow" , "" )
+      ]
+  , Para
+      [ Link
+          ( "" , [ "wikilink" ] , [] )
+          [ Str "diary:2017-05-01" ]
+          ( "diary/2017-05-01" , "" )
+      ]
+  , Para
+      [ Link
+          ( "" , [] , [] )
+          [ Str "Important" , Space , Str "Data" ]
+          ( "file:../assets/data.csv" , "" )
+      ]
+  , Header
+      3
+      ( "links with thumbnails" , [] , [] )
+      [ Str "links"
+      , Space
+      , Str "with"
+      , Space
+      , Str "thumbnails"
+      ]
+  , Para
+      [ Link
+          ( "" , [] , [] )
+          [ Image ( "" , [] , [] ) [ Str "" ] ( "./movie.jpg" , "" ) ]
+          ( "http://www.google.com" , "" )
+      ]
+  , Header 2 ( "images" , [] , [] ) [ Str "images" ]
+  , Para
+      [ Image
+          ( "" , [] , [] ) [ Str "" ] ( "file:./lalune.jpg" , "" )
+      ]
+  , Para
+      [ Image
+          ( "" , [] , [] )
+          [ Str "Vimwiki" ]
+          ( "http://vimwiki.googlecode.com/hg/images/vimwiki_logo.png"
+          , ""
+          )
+      , SoftBreak
+      , Image
+          ( "" , [] , [] ) [ Str "" ] ( "file:./movie.jpg" , "" )
+      ]
+  , Header
+      3
+      ( "image with attributes" , [] , [] )
+      [ Str "image"
+      , Space
+      , Str "with"
+      , Space
+      , Str "attributes"
+      ]
+  , Para
+      [ Image
+          ( "" , [] , [ ( "style" , "width:150px;height:120px;" ) ] )
+          [ Emph [ Str "cool" , Space , Str "stuff" ] ]
+          ( "lalune.jpg" , "" )
+      ]
+  , Para
+      [ Image
+          ( "" , [] , [ ( "style" , "font-color:red" ) ] )
+          [ Span ( "Non-existing" , [] , [] ) []
+          , Strong [ Str "Non-existing" ]
+          , Space
+          , Str "image"
+          ]
+          ( "nonexist.jpg" , "" )
+      ]
+  , Para
+      [ Image
+          ( "" , [] , [ ( "style" , "width:150px;height:120px;" ) ] )
+          [ Emph [ Str "cool" , Space , Str "stuff" ] ]
+          ( "lalune.jpg" , "" )
+      ]
+  , Header 2 ( "lists" , [] , [] ) [ Str "lists" ]
+  , OrderedList
+      ( 1 , DefaultStyle , DefaultDelim )
+      [ [ Plain
+            [ Str "ordered"
+            , Space
+            , Str "list"
+            , Space
+            , Str "item"
+            , Space
+            , Str "1,"
+            , Space
+            , Str "and"
+            , Space
+            , Str "here"
+            , Space
+            , Str "is"
+            , Space
+            , Str "some"
+            , Space
+            , Str "math"
+            , Space
+            , Str "belonging"
+            , Space
+            , Str "to"
+            , Space
+            , Str "list"
+            , Space
+            , Str "item"
+            , Space
+            , Str "1"
+            ]
+        , Para [ Math DisplayMath "a^2 + b^2 = c^2" ]
+        , Plain
+            [ Str "and"
+            , Space
+            , Str "some"
+            , Space
+            , Str "preformatted"
+            , Space
+            , Str "and"
+            , Space
+            , Str "tables"
+            , Space
+            , Str "belonging"
+            , Space
+            , Str "to"
+            , Space
+            , Str "item"
+            , Space
+            , Str "1"
+            , Space
+            , Str "as"
+            , Space
+            , Str "well"
+            ]
+        , CodeBlock ( "" , [] , [] ) "I'm part of item 1."
+        , Table
+            ( "" , [] , [] )
+            (Caption Nothing [])
+            [ ( AlignDefault , ColWidthDefault )
+            , ( AlignDefault , ColWidthDefault )
+            ]
+            (TableHead
+               ( "" , [] , [] )
+               [ Row
+                   ( "" , [] , [] )
+                   [ Cell
+                       ( "" , [] , [] )
+                       AlignDefault
+                       (RowSpan 1)
+                       (ColSpan 1)
+                       []
+                   , Cell
+                       ( "" , [] , [] )
+                       AlignDefault
+                       (RowSpan 1)
+                       (ColSpan 1)
+                       []
+                   ]
+               ])
+            [ TableBody
+                ( "" , [] , [] )
+                (RowHeadColumns 0)
+                []
+                [ Row
+                    ( "" , [] , [] )
+                    [ Cell
+                        ( "" , [] , [] )
+                        AlignDefault
+                        (RowSpan 1)
+                        (ColSpan 1)
+                        [ Plain [ Str "this" , Space , Str "table" ] ]
+                    , Cell
+                        ( "" , [] , [] )
+                        AlignDefault
+                        (RowSpan 1)
+                        (ColSpan 1)
+                        [ Plain [ Str "is" ] ]
+                    ]
+                , Row
+                    ( "" , [] , [] )
+                    [ Cell
+                        ( "" , [] , [] )
+                        AlignDefault
+                        (RowSpan 1)
+                        (ColSpan 1)
+                        [ Plain
+                            [ Str "also"
+                            , Space
+                            , Str "a"
+                            , Space
+                            , Str "part"
+                            ]
+                        ]
+                    , Cell
+                        ( "" , [] , [] )
+                        AlignDefault
+                        (RowSpan 1)
+                        (ColSpan 1)
+                        [ Plain
+                            [ Str "of"
+                            , Space
+                            , Str "item"
+                            , Space
+                            , Str "1"
+                            ]
+                        ]
+                    ]
+                ]
+            ]
+            (TableFoot ( "" , [] , [] ) [])
+        , Plain
+            [ Str "and"
+            , Space
+            , Str "some"
+            , Space
+            , Str "more"
+            , Space
+            , Str "text"
+            , Space
+            , Str "belonging"
+            , Space
+            , Str "to"
+            , Space
+            , Str "item"
+            , Space
+            , Str "1."
+            ]
+        ]
+      , [ Plain
+            [ Str "ordered"
+            , Space
+            , Str "list"
+            , Space
+            , Str "item"
+            , Space
+            , Str "2"
+            ]
+        ]
+      ]
+  , BulletList
+      [ [ Plain
+            [ Str "Bulleted"
+            , Space
+            , Str "list"
+            , Space
+            , Str "item"
+            , Space
+            , Str "1"
+            ]
+        ]
+      , [ Plain
+            [ Str "Bulleted"
+            , Space
+            , Str "list"
+            , Space
+            , Str "item"
+            , Space
+            , Str "2"
+            ]
+        ]
+      ]
+  , OrderedList
+      ( 1 , DefaultStyle , DefaultDelim )
+      [ [ Plain
+            [ Str "Bulleted"
+            , Space
+            , Str "list"
+            , Space
+            , Str "item"
+            , Space
+            , Str "1"
+            ]
+        ]
+      , [ Plain
+            [ Str "the"
+            , Space
+            , Str "#"
+            , Space
+            , Str "become"
+            , Space
+            , Str "numbers"
+            , Space
+            , Str "when"
+            , Space
+            , Str "converted"
+            , Space
+            , Str "to"
+            , Space
+            , Str "HTML"
+            ]
+        ]
+      ]
+  , BulletList
+      [ [ Plain
+            [ Str "Bulleted"
+            , Space
+            , Str "list"
+            , Space
+            , Str "item"
+            , Space
+            , Str "1"
+            ]
+        ]
+      , [ Plain
+            [ Str "Bulleted"
+            , Space
+            , Str "list"
+            , Space
+            , Str "item"
+            , Space
+            , Str "2"
+            ]
+        ]
+      ]
+  , BulletList
+      [ [ Plain [ Str "Item" , Space , Str "1" ] ]
+      , [ Plain [ Str "Item" , Space , Str "2" ]
+        , OrderedList
+            ( 1 , DefaultStyle , DefaultDelim )
+            [ [ Plain
+                  [ Str "Sub"
+                  , Space
+                  , Str "item"
+                  , Space
+                  , Str "1"
+                  , Space
+                  , Str "(indentation"
+                  , Space
+                  , Str "4"
+                  , Space
+                  , Str "spaces)"
+                  , SoftBreak
+                  , Str "Sub"
+                  , Space
+                  , Str "item"
+                  , Space
+                  , Str "1"
+                  , Space
+                  , Str "continued"
+                  , Space
+                  , Str "line."
+                  , SoftBreak
+                  , Str "Sub"
+                  , Space
+                  , Str "item"
+                  , Space
+                  , Str "1"
+                  , Space
+                  , Str "next"
+                  , Space
+                  , Str "continued"
+                  , Space
+                  , Str "line."
+                  ]
+              ]
+            , [ Plain
+                  [ Str "Sub"
+                  , Space
+                  , Str "item"
+                  , Space
+                  , Str "2,"
+                  , Space
+                  , Str "as"
+                  , Space
+                  , Str "an"
+                  , Space
+                  , Str "ordered"
+                  , Space
+                  , Str "list"
+                  , Space
+                  , Str "item"
+                  , Space
+                  , Str "even"
+                  , Space
+                  , Str "though"
+                  , Space
+                  , Str "the"
+                  , Space
+                  , Str "identifier"
+                  , Space
+                  , Str "is"
+                  , Space
+                  , Code ( "" , [] , [] ) "*"
+                  , Space
+                  , Str "(indentation"
+                  , Space
+                  , Str "2"
+                  , Space
+                  , Str "spaces"
+                  , Space
+                  , Str "followed"
+                  , Space
+                  , Str "by"
+                  , Space
+                  , Str "one"
+                  , Space
+                  , Str "tab"
+                  , Space
+                  , Str "of"
+                  , Space
+                  , Str "width"
+                  , Space
+                  , Str "4)"
+                  ]
+              ]
+            , [ Plain
+                  [ Str "etc."
+                  , SoftBreak
+                  , Str "Continuation"
+                  , Space
+                  , Str "of"
+                  , Space
+                  , Str "Item"
+                  , Space
+                  , Str "2"
+                  , SoftBreak
+                  , Str "Next"
+                  , Space
+                  , Str "continuation"
+                  , Space
+                  , Str "of"
+                  , Space
+                  , Str "Item"
+                  , Space
+                  , Str "2"
+                  ]
+              ]
+            ]
+        ]
+      ]
+  , Para
+      [ Str "But"
+      , Space
+      , Str "this"
+      , Space
+      , Str "is"
+      , Space
+      , Str "a"
+      , Space
+      , Str "new"
+      , Space
+      , Str "paragraph."
+      ]
+  , OrderedList
+      ( 1 , DefaultStyle , DefaultDelim )
+      [ [ Plain [ Str "1" ]
+        , BulletList [ [ Plain [ Code ( "" , [] , [] ) "1.1" ] ] ]
+        ]
+      , [ Plain [ Str "2" ]
+        , BulletList [ [ Plain [ Str "2.1" ] ] ]
+        ]
+      ]
+  , BulletList [ [ Plain [ Str "3" ] ] ]
+  , Header
+      3
+      ( "ordered lists with non-# identifiers" , [] , [] )
+      [ Str "ordered"
+      , Space
+      , Str "lists"
+      , Space
+      , Str "with"
+      , Space
+      , Str "non-#"
+      , Space
+      , Str "identifiers"
+      ]
+  , OrderedList
+      ( 1 , DefaultStyle , DefaultDelim )
+      [ [ Plain
+            [ Str "Numbered"
+            , Space
+            , Str "list"
+            , Space
+            , Str "item"
+            , Space
+            , Str "1"
+            ]
+        ]
+      , [ Plain
+            [ Str "Numbered"
+            , Space
+            , Str "list"
+            , Space
+            , Str "item"
+            , Space
+            , Str "2"
+            ]
+        ]
+      , [ Plain
+            [ Str "Numbered"
+            , Space
+            , Str "list"
+            , Space
+            , Str "item"
+            , Space
+            , Str "3"
+            ]
+        ]
+      ]
+  , OrderedList
+      ( 1 , DefaultStyle , DefaultDelim )
+      [ [ Plain
+            [ Str "Numbered"
+            , Space
+            , Str "list"
+            , Space
+            , Str "item"
+            , Space
+            , Str "1"
+            ]
+        ]
+      , [ Plain
+            [ Str "Numbered"
+            , Space
+            , Str "list"
+            , Space
+            , Str "item"
+            , Space
+            , Str "2"
+            ]
+        ]
+      , [ Plain
+            [ Str "Numbered"
+            , Space
+            , Str "list"
+            , Space
+            , Str "item"
+            , Space
+            , Str "3"
+            ]
+        ]
+      ]
+  , OrderedList
+      ( 1 , DefaultStyle , DefaultDelim )
+      [ [ Plain
+            [ Str "Numbered"
+            , Space
+            , Str "list"
+            , Space
+            , Str "item"
+            , Space
+            , Str "1"
+            ]
+        ]
+      , [ Plain
+            [ Str "Numbered"
+            , Space
+            , Str "list"
+            , Space
+            , Str "item"
+            , Space
+            , Str "2"
+            ]
+        ]
+      , [ Plain
+            [ Str "Numbered"
+            , Space
+            , Str "list"
+            , Space
+            , Str "item"
+            , Space
+            , Str "3"
+            ]
+        ]
+      ]
+  , OrderedList
+      ( 1 , DefaultStyle , DefaultDelim )
+      [ [ Plain
+            [ Str "Numbered"
+            , Space
+            , Str "list"
+            , Space
+            , Str "item"
+            , Space
+            , Str "1"
+            ]
+        ]
+      , [ Plain
+            [ Str "Numbered"
+            , Space
+            , Str "list"
+            , Space
+            , Str "item"
+            , Space
+            , Str "2"
+            ]
+        ]
+      , [ Plain
+            [ Str "Numbered"
+            , Space
+            , Str "list"
+            , Space
+            , Str "item"
+            , Space
+            , Str "3"
+            ]
+        ]
+      ]
+  , OrderedList
+      ( 1 , DefaultStyle , DefaultDelim )
+      [ [ Plain
+            [ Str "Numbered"
+            , Space
+            , Str "list"
+            , Space
+            , Str "item"
+            , Space
+            , Str "1"
+            ]
+        ]
+      , [ Plain
+            [ Str "Numbered"
+            , Space
+            , Str "list"
+            , Space
+            , Str "item"
+            , Space
+            , Str "2"
+            ]
+        ]
+      , [ Plain
+            [ Str "Numbered"
+            , Space
+            , Str "list"
+            , Space
+            , Str "item"
+            , Space
+            , Str "3"
+            ]
+        ]
+      ]
+  , OrderedList
+      ( 1 , DefaultStyle , DefaultDelim )
+      [ [ Plain
+            [ Str "Numbered"
+            , Space
+            , Str "list"
+            , Space
+            , Str "item"
+            , Space
+            , Str "1"
+            ]
+        ]
+      , [ Plain
+            [ Str "Numbered"
+            , Space
+            , Str "list"
+            , Space
+            , Str "item"
+            , Space
+            , Str "2"
+            ]
+        ]
+      , [ Plain
+            [ Str "Numbered"
+            , Space
+            , Str "list"
+            , Space
+            , Str "item"
+            , Space
+            , Str "3"
+            ]
+        ]
+      ]
+  , OrderedList
+      ( 1 , DefaultStyle , DefaultDelim )
+      [ [ Plain
+            [ Str "Numbered"
+            , Space
+            , Str "list"
+            , Space
+            , Str "item"
+            , Space
+            , Str "1"
+            ]
+        ]
+      , [ Plain
+            [ Str "Numbered"
+            , Space
+            , Str "list"
+            , Space
+            , Str "item"
+            , Space
+            , Str "2"
+            ]
+        ]
+      , [ Plain
+            [ Str "Numbered"
+            , Space
+            , Str "list"
+            , Space
+            , Str "item"
+            , Space
+            , Str "3"
+            ]
+        ]
+      ]
+  , BulletList
+      [ [ Plain
+            [ Str "Bulleted"
+            , Space
+            , Str "list"
+            , Space
+            , Str "item"
+            , Space
+            , Str "1"
+            ]
+        ]
+      , [ Plain
+            [ Str "Bulleted"
+            , Space
+            , Str "list"
+            , Space
+            , Str "item"
+            , Space
+            , Str "2"
+            ]
+        , OrderedList
+            ( 1 , DefaultStyle , DefaultDelim )
+            [ [ Plain
+                  [ Str "Numbered"
+                  , Space
+                  , Str "list"
+                  , Space
+                  , Str "sub"
+                  , Space
+                  , Str "item"
+                  , Space
+                  , Str "1"
+                  ]
+              ]
+            , [ Plain [ Str "more" , Space , Str "..." ]
+              , BulletList
+                  [ [ Plain
+                        [ Str "and"
+                        , Space
+                        , Str "more"
+                        , Space
+                        , Str "..."
+                        ]
+                    ]
+                  , [ Plain [ Str "..." ] ]
+                  ]
+              ]
+            , [ Plain
+                  [ Str "Numbered"
+                  , Space
+                  , Str "list"
+                  , Space
+                  , Str "sub"
+                  , Space
+                  , Str "item"
+                  , Space
+                  , Str "3"
+                  ]
+              , OrderedList
+                  ( 1 , DefaultStyle , DefaultDelim )
+                  [ [ Plain
+                        [ Str "Numbered"
+                        , Space
+                        , Str "list"
+                        , Space
+                        , Str "sub"
+                        , Space
+                        , Str "sub"
+                        , Space
+                        , Str "item"
+                        , Space
+                        , Str "1"
+                        ]
+                    ]
+                  , [ Plain
+                        [ Str "Numbered"
+                        , Space
+                        , Str "list"
+                        , Space
+                        , Str "sub"
+                        , Space
+                        , Str "sub"
+                        , Space
+                        , Str "item"
+                        , Space
+                        , Str "2"
+                        ]
+                    ]
+                  ]
+              ]
+            , [ Plain [ Str "etc." ] ]
+            ]
+        ]
+      , [ Plain
+            [ Str "Bulleted"
+            , Space
+            , Str "list"
+            , Space
+            , Str "item"
+            , Space
+            , Str "3"
+            ]
+        ]
+      ]
+  , Header
+      2
+      ( "todo lists" , [] , [] )
+      [ Str "todo" , Space , Str "lists" ]
+  , BulletList
+      [ [ Plain
+            [ Span ( "" , [ "done0" ] , [] ) []
+            , Str "task"
+            , Space
+            , Str "1"
+            ]
+        , OrderedList
+            ( 1 , DefaultStyle , DefaultDelim )
+            [ [ Plain [ Span ( "" , [ "done1" ] , [] ) [] , Str "5" ] ]
+            ]
+        ]
+      , [ Plain [ Span ( "" , [ "done2" ] , [] ) [] , Str "3" ] ]
+      , [ Plain
+            [ Str "[]"
+            , Space
+            , Str "not"
+            , Space
+            , Str "a"
+            , Space
+            , Str "todo"
+            , Space
+            , Str "item"
+            ]
+        ]
+      , [ Plain
+            [ Str "["
+            , Space
+            , Str "]not"
+            , Space
+            , Str "a"
+            , Space
+            , Str "todo"
+            , Space
+            , Str "item"
+            ]
+        ]
+      , [ Plain
+            [ Str "[r]"
+            , Space
+            , Str "not"
+            , Space
+            , Str "a"
+            , Space
+            , Str "todo"
+            , Space
+            , Str "item"
+            ]
+        ]
+      , [ Plain
+            [ Str "["
+            , Space
+            , Str "]"
+            , Space
+            , Str "not"
+            , Space
+            , Str "a"
+            , Space
+            , Str "todo"
+            , Space
+            , Str "item"
+            ]
+        ]
+      , [ Plain
+            [ Span ( "" , [ "done2" ] , [] ) []
+            , Str "a"
+            , Space
+            , Str "tab"
+            , Space
+            , Str "in"
+            , Space
+            , Str "the"
+            , Space
+            , Str "todo"
+            , Space
+            , Str "list"
+            , Space
+            , Str "marker"
+            , Space
+            , Code ( "" , [] , [] ) "[ ]"
+            ]
+        , OrderedList
+            ( 1 , DefaultStyle , DefaultDelim )
+            [ [ Plain
+                  [ Span ( "" , [ "done3" ] , [] ) []
+                  , Str "4"
+                  , SoftBreak
+                  , Str "5"
+                  ]
+              ]
+            , [ Plain [ Span ( "" , [ "done4" ] , [] ) [] ]
+              , Table
+                  ( "" , [] , [] )
+                  (Caption Nothing [])
+                  [ ( AlignDefault , ColWidthDefault )
+                  , ( AlignDefault , ColWidthDefault )
+                  ]
+                  (TableHead
+                     ( "" , [] , [] )
+                     [ Row
+                         ( "" , [] , [] )
+                         [ Cell
+                             ( "" , [] , [] )
+                             AlignDefault
+                             (RowSpan 1)
+                             (ColSpan 1)
+                             []
+                         , Cell
+                             ( "" , [] , [] )
+                             AlignDefault
+                             (RowSpan 1)
+                             (ColSpan 1)
+                             []
+                         ]
+                     ])
+                  [ TableBody
+                      ( "" , [] , [] )
+                      (RowHeadColumns 0)
+                      []
+                      [ Row
+                          ( "" , [] , [] )
+                          [ Cell
+                              ( "" , [] , [] )
+                              AlignDefault
+                              (RowSpan 1)
+                              (ColSpan 1)
+                              [ Plain [ Str "a" ] ]
+                          , Cell
+                              ( "" , [] , [] )
+                              AlignDefault
+                              (RowSpan 1)
+                              (ColSpan 1)
+                              [ Plain [ Str "b" ] ]
+                          ]
+                      ]
+                  ]
+                  (TableFoot ( "" , [] , [] ) [])
+              ]
+            ]
+        ]
+      , [ Plain
+            [ Span ( "" , [ "done4" ] , [] ) []
+            , Str "task"
+            , Space
+            , Str "2"
+            ]
+        ]
+      ]
+  , Header 2 ( "math" , [] , [] ) [ Str "math" ]
+  , Para [ Math InlineMath " \\sum_i a_i^2 = 1 " ]
+  , Para [ Math DisplayMath "\\sum_i a_i^2\n=\n1" ]
+  , Para
+      [ Math
+          DisplayMath
+          "\\begin{aligned}\n\\sum_i a_i^2 &= 1 + 1 \\\\\n&= 2.\n\\end{aligned}"
+      ]
+  , Para
+      [ Str "edge"
+      , Space
+      , Str "case"
+      , Space
+      , Str "(the"
+      , Space
+      , Code ( "" , [] , [] ) "c^2 + "
+      , Space
+      , Str "after"
+      , Space
+      , Str "the"
+      , Space
+      , Str "multline"
+      , Space
+      , Str "tag"
+      , Space
+      , Str "is"
+      , Space
+      , Str "in"
+      , Space
+      , Str "the"
+      , Space
+      , Str "equation):"
+      ]
+  , Para
+      [ Math
+          DisplayMath
+          "\\begin{gathered}\nc^2 + \na^2 + b^2\n\\end{gathered}"
+      ]
+  , Para
+      [ Str "edge"
+      , Space
+      , Str "case"
+      , Space
+      , Str "(the"
+      , Space
+      , Str "tag"
+      , Space
+      , Str "is"
+      , Space
+      , Code ( "" , [] , [] ) "hello%bye"
+      , Str ")"
+      ]
+  , Para
+      [ Math
+          DisplayMath
+          "\\begin{hello%bye}\n\\int_a^b f(x) dx\n\\end{hello%bye}"
+      ]
+  , Para
+      [ Str "Just"
+      , Space
+      , Str "two"
+      , Space
+      , Str "dollar"
+      , Space
+      , Str "signs:"
+      , Space
+      , Str "$$"
+      ]
+  , Para
+      [ Str "[not"
+      , Space
+      , Str "math]"
+      , Space
+      , Str "You"
+      , Space
+      , Str "have"
+      , Space
+      , Str "$1"
+      , SoftBreak
+      , Str "and"
+      , Space
+      , Str "I"
+      , Space
+      , Str "have"
+      , Space
+      , Str "$1."
+      ]
+  , Header 2 ( "tags" , [] , [] ) [ Str "tags" ]
+  , Para
+      [ Span ( "-tag-one" , [] , [] ) [ Str "" ]
+      , Span ( "tag-one" , [ "tag" ] , [] ) [ Str "tag-one" ]
+      , Space
+      , Span ( "-tag-two" , [] , [] ) [ Str "" ]
+      , Span ( "tag-two" , [ "tag" ] , [] ) [ Str "tag-two" ]
+      ]
+  , Header 2 ( "tables" , [] , [] ) [ Str "tables" ]
+  , Table
+      ( "" , [] , [] )
+      (Caption Nothing [])
+      [ ( AlignDefault , ColWidthDefault )
+      , ( AlignDefault , ColWidthDefault )
+      , ( AlignDefault , ColWidthDefault )
+      ]
+      (TableHead
+         ( "" , [] , [] )
+         [ Row
+             ( "" , [] , [] )
+             [ Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "Year" ] ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "Temperature" , Space , Str "(low)" ] ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "Temperature" , Space , Str "(high)" ] ]
+             ]
+         ])
+      [ TableBody
+          ( "" , [] , [] )
+          (RowHeadColumns 0)
+          []
+          [ Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "1900" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "-10" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "25" ] ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "1910" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "-15" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "30" ] ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "1920" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "-10" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "32" ] ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "1930" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Emph [ Str "N/A" ] ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Emph [ Str "N/A" ] ] ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "1940" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "-2" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "40" ] ]
+              ]
+          ]
+      ]
+      (TableFoot ( "" , [] , [] ) [])
+  , Header
+      3
+      ( "centered headerless tables" , [] , [] )
+      [ Str "centered"
+      , Space
+      , Str "headerless"
+      , Space
+      , Str "tables"
+      ]
+  , Div
+      ( "" , [ "center" ] , [] )
+      [ Table
+          ( "" , [] , [] )
+          (Caption Nothing [])
+          [ ( AlignDefault , ColWidthDefault )
+          , ( AlignDefault , ColWidthDefault )
+          ]
+          (TableHead
+             ( "" , [] , [] )
+             [ Row
+                 ( "" , [] , [] )
+                 [ Cell
+                     ( "" , [] , [] )
+                     AlignDefault
+                     (RowSpan 1)
+                     (ColSpan 1)
+                     []
+                 , Cell
+                     ( "" , [] , [] )
+                     AlignDefault
+                     (RowSpan 1)
+                     (ColSpan 1)
+                     []
+                 ]
+             ])
+          [ TableBody
+              ( "" , [] , [] )
+              (RowHeadColumns 0)
+              []
+              [ Row
+                  ( "" , [] , [] )
+                  [ Cell
+                      ( "" , [] , [] )
+                      AlignDefault
+                      (RowSpan 1)
+                      (ColSpan 1)
+                      [ Plain [ Str "a" ] ]
+                  , Cell
+                      ( "" , [] , [] )
+                      AlignDefault
+                      (RowSpan 1)
+                      (ColSpan 1)
+                      [ Plain [ Str "b" ] ]
+                  ]
+              , Row
+                  ( "" , [] , [] )
+                  [ Cell
+                      ( "" , [] , [] )
+                      AlignDefault
+                      (RowSpan 1)
+                      (ColSpan 1)
+                      [ Plain [ Str "c" ] ]
+                  , Cell
+                      ( "" , [] , [] )
+                      AlignDefault
+                      (RowSpan 1)
+                      (ColSpan 1)
+                      [ Plain [ Str "d" ] ]
+                  ]
+              ]
+          ]
+          (TableFoot ( "" , [] , [] ) [])
+      ]
+  , Header 2 ( "paragraphs" , [] , [] ) [ Str "paragraphs" ]
+  , Para
+      [ Str "This"
+      , Space
+      , Str "is"
+      , Space
+      , Str "first"
+      , Space
+      , Str "paragraph"
+      , SoftBreak
+      , Str "with"
+      , Space
+      , Str "two"
+      , Space
+      , Str "lines."
+      ]
+  , Para
+      [ Str "This"
+      , Space
+      , Str "is"
+      , Space
+      , Str "a"
+      , Space
+      , Str "second"
+      , Space
+      , Str "paragraph"
+      , Space
+      , Str "with"
+      , SoftBreak
+      , Str "two"
+      , Space
+      , Str "lines"
+      , Space
+      , Str "after"
+      , Space
+      , Str "many"
+      , Space
+      , Str "blank"
+      , Space
+      , Str "lines."
+      ]
+  , Header
+      2
+      ( "definition list" , [] , [] )
+      [ Str "definition" , Space , Str "list" ]
+  , DefinitionList
+      [ ( [ Str "Term" , Space , Str "1" ]
+        , [ [ Plain [ Str "Definition" , Space , Str "1" ] ] ]
+        )
+      , ( [ Str "Term" , Space , Str "2" ]
+        , [ [ Plain [ Str "Definition" , Space , Str "2" ] ]
+          , [ Plain [ Str "Definition" , Space , Str "3" ] ]
+          ]
+        )
+      , ( [ Str "Term"
+          , Space
+          , Str "::"
+          , Space
+          , Span ( "separated" , [] , [] ) []
+          , Strong [ Str "separated" ]
+          , Space
+          , Str "by"
+          , Space
+          , Str "::"
+          , Space
+          , Emph [ Str "double" , Space , Str "colons" ]
+          ]
+        , [ [ Plain [ Str "Def1" ] ] , [ Plain [ Str "Def2" ] ] ]
+        )
+      , ( [ Str "Term"
+          , Space
+          , Str "with"
+          , Space
+          , Str "lots"
+          , Space
+          , Str "of"
+          , Space
+          , Str "trailing"
+          , Space
+          , Str "colons:::::::"
+          ]
+        , [ [ Plain [ Str "Definition" ] ] ]
+        )
+      , ( [ Str "::"
+          , Space
+          , Str "This"
+          , Space
+          , Str "is"
+          , Space
+          , Str "::"
+          , Space
+          , Str "A"
+          , Space
+          , Str "term"
+          , Space
+          , Str "(rather"
+          , Space
+          , Str "than"
+          , Space
+          , Str "a"
+          , Space
+          , Str "definition)"
+          ]
+        , [ [ Plain
+                [ Str "and"
+                , Space
+                , Str "this"
+                , Space
+                , Str "is"
+                , Space
+                , Str "a"
+                , Space
+                , Str "definition"
+                ]
+            ]
+          ]
+        )
+      , ( [ Str "Term"
+          , Space
+          , Str "Without"
+          , Space
+          , Str "definitions"
+          ]
+        , [ [] ]
+        )
+      , ( [ Str "Part"
+          , Space
+          , Str "::"
+          , Space
+          , Str "of"
+          , Space
+          , Str "::"
+          , Space
+          , Str "dt"
+          ]
+        , [ [ Plain
+                [ Str "part" , Space , Str "of" , Space , Str "::dd" ]
+            ]
+          ]
+        )
+      ]
+  , DefinitionList
+      [ ( []
+        , [ [ Plain
+                [ Str "Definition"
+                , Space
+                , Str "1"
+                , Space
+                , Str "without"
+                , Space
+                , Str "a"
+                , Space
+                , Str "term"
+                ]
+            ]
+          , [ Plain
+                [ Str "Definition"
+                , Space
+                , Str "2"
+                , Space
+                , Str "without"
+                , Space
+                , Str "a"
+                , Space
+                , Str "term"
+                ]
+            ]
+          ]
+        )
+      ]
+  , DefinitionList
+      [ ( [ Str "T1" ] , [ [ Plain [ Str "D1" ] ] ] ) ]
+  , Para [ Str "new" , Space , Str "paragraph" ]
+  , DefinitionList
+      [ ( [ Str "T1" ] , [ [ Plain [ Str "D1" ] ] ] ) ]
+  , Para [ Str "Not::Definition" ]
+  , Para [ Str "Not" , Space , Str "::Definition" ]
+  , Para [ Str "::Not" , Space , Str "definition" ]
+  , BlockQuote
+      [ Plain [ Str "::" , Space , Str "blockquote" ] ]
+  , BlockQuote
+      [ Plain
+          [ Str "block" , Space , Str "::" , Space , Str "quote" ]
+      ]
+  , Header
+      2
+      ( "metadata placeholders" , [] , [] )
+      [ Str "metadata" , Space , Str "placeholders" ]
+  , Para
+      [ Str "%this"
+      , Space
+      , Str "is"
+      , Space
+      , Str "not"
+      , Space
+      , Str "a"
+      , Space
+      , Str "placeholder"
+      ]
+  , Para
+      [ Str "placeholders"
+      , SoftBreak
+      , Str "serves"
+      , Space
+      , Str "as"
+      , Space
+      , Str "space"
+      , Space
+      , Str "/"
+      , Space
+      , Str "softbreak"
+      , Space
+      , Str "in"
+      , Space
+      , Str "paragraphs"
+      ]
+  , Header
+      2
+      ( "sup, sub" , [] , [] )
+      [ Str "sup," , Space , Str "sub" ]
+  , Para [ Str "super" , Superscript [ Str "script" ] ]
+  , Para [ Str "sub" , Subscript [ Str "script" ] ]
+  , Header
+      2
+      ( "the todo mark" , [] , [] )
+      [ Str "the" , Space , Str "todo" , Space , Str "mark" ]
+  , Para [ Span ( "" , [ "todo" ] , [] ) [ Str "TODO:" ] ]
+  , Header
+      1
+      ( "not implemented yet" , [] , [] )
+      [ Emph
+          [ Span ( "not implemented yet" , [] , [] ) []
+          , Strong
+              [ Str "not"
+              , Space
+              , Str "implemented"
+              , Space
+              , Str "yet"
+              ]
+          ]
+      ]
+  , Header
+      2
+      ( "tables with spans" , [] , [] )
+      [ Str "tables" , Space , Str "with" , Space , Str "spans" ]
+  , Table
+      ( "" , [] , [] )
+      (Caption Nothing [])
+      [ ( AlignDefault , ColWidthDefault )
+      , ( AlignDefault , ColWidthDefault )
+      , ( AlignDefault , ColWidthDefault )
+      , ( AlignDefault , ColWidthDefault )
+      ]
+      (TableHead
+         ( "" , [] , [] )
+         [ Row
+             ( "" , [] , [] )
+             [ Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 []
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 []
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 []
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 []
+             ]
+         ])
+      [ TableBody
+          ( "" , [] , [] )
+          (RowHeadColumns 0)
+          []
+          [ Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "a" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "b" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "c" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "d" ] ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "\\/" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "e" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str ">" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "f" ] ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "\\/" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "\\/" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str ">" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "g" ] ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "h" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str ">" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str ">" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str ">" ] ]
+              ]
+          ]
+      ]
+      (TableFoot ( "" , [] , [] ) [])
+  , Header
+      2
+      ( "tables with multiple lines of headers" , [] , [] )
+      [ Str "tables"
+      , Space
+      , Str "with"
+      , Space
+      , Str "multiple"
+      , Space
+      , Str "lines"
+      , Space
+      , Str "of"
+      , Space
+      , Str "headers"
+      ]
+  , Table
+      ( "" , [] , [] )
+      (Caption Nothing [])
+      [ ( AlignDefault , ColWidthDefault )
+      , ( AlignDefault , ColWidthDefault )
+      ]
+      (TableHead
+         ( "" , [] , [] )
+         [ Row
+             ( "" , [] , [] )
+             [ Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 []
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 []
+             ]
+         ])
+      [ TableBody
+          ( "" , [] , [] )
+          (RowHeadColumns 0)
+          []
+          [ Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "a" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "b" ] ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "c" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "d" ] ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "---" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "---" ] ]
+              ]
+          ]
+      ]
+      (TableFoot ( "" , [] , [] ) [])
+  , Header
+      2
+      ( "some other placeholders" , [] , [] )
+      [ Str "some"
+      , Space
+      , Str "other"
+      , Space
+      , Str "placeholders"
+      ]
+  , Para
+      [ Code ( "" , [] , [] ) "template"
+      , Space
+      , Str "placeholder"
+      , Space
+      , Str "is"
+      , Space
+      , Str "ignored."
+      ]
+  , Para
+      [ Code ( "" , [] , [] ) "nohtml"
+      , Space
+      , Str "placeholder"
+      , Space
+      , Str "is"
+      , Space
+      , Str "ignored."
+      ]
+  ]
diff --git a/test/vimwiki-reader.wiki b/test/vimwiki-reader.wiki
--- a/test/vimwiki-reader.wiki
+++ b/test/vimwiki-reader.wiki
@@ -116,7 +116,18 @@
  for i in range(1, 5):
      print(i)
  }}}
- 
+
+=== preformatted text with nested syntax ===
+
+{{{sql
+SELECT * FROM table
+}}}
+
+=== empty preformatted text ===
+
+{{{
+}}}
+
 == block quotes ==
 
     (indentation 4 spaces) This would be a blockquote in Vimwiki. It is not *highlighted* in Vim but
diff --git a/test/writer.asciidoc b/test/writer.asciidoc
--- a/test/writer.asciidoc
+++ b/test/writer.asciidoc
@@ -1,57 +1,38 @@
-Pandoc Test Suite
-=================
+= Pandoc Test Suite
 John MacFarlane; Anonymous
 July 17, 2006
+:stem: latexmath
 
 This is a set of tests for pandoc. Most of them are adapted from John Gruber’s
 markdown test suite.
 
 '''''
 
-[[headers]]
-Headers
--------
+== Headers
 
-[[level-2-with-an-embedded-link]]
-Level 2 with an link:/url[embedded link]
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+=== Level 2 with an link:/url[embedded link]
 
-[[level-3-with-emphasis]]
-Level 3 with _emphasis_
-^^^^^^^^^^^^^^^^^^^^^^^
+==== Level 3 with _emphasis_
 
-[[level-4]]
-Level 4
-+++++++
+===== Level 4
 
-[[level-5]]
-Level 5
+====== Level 5
 
-[[level-1]]
-Level 1
--------
+== Level 1
 
-[[level-2-with-emphasis]]
-Level 2 with _emphasis_
-~~~~~~~~~~~~~~~~~~~~~~~
+=== Level 2 with _emphasis_
 
-[[level-3]]
-Level 3
-^^^^^^^
+==== Level 3
 
 with no blank line
 
-[[level-2]]
-Level 2
-~~~~~~~
+=== Level 2
 
 with no blank line
 
 '''''
 
-[[paragraphs]]
-Paragraphs
-----------
+== Paragraphs
 
 Here’s a regular paragraph.
 
@@ -59,24 +40,22 @@
 Because a hard-wrapped line in the middle of a paragraph looked like a list
 item.
 
-Here’s one with a bullet. * criminey.
+Here’s one with a bullet. ++*++ criminey.
 
 There should be a hard line break +
 here.
 
 '''''
 
-[[block-quotes]]
-Block Quotes
-------------
+== Block Quotes
 
 E-mail style:
 
-__________________________________________
+____
 This is a block quote. It is pretty short.
-__________________________________________
+____
 
-______________________
+____
 --
 Code in a block quote:
 
@@ -88,31 +67,30 @@
 
 A list:
 
-1.  item one
-2.  item two
+[arabic]
+. item one
+. item two
 
 Nested block quotes:
 
-______
+____
 nested
-______
+____
 
-______
+____
 nested
-______
+____
 
 --
-______________________
+____
 
-This should not be a block quote: 2 > 1.
+This should not be a block quote: 2 ++>++ 1.
 
 And a following paragraph.
 
 '''''
 
-[[code-blocks]]
-Code Blocks
------------
+== Code Blocks
 
 Code:
 
@@ -136,13 +114,9 @@
 
 '''''
 
-[[lists]]
-Lists
------
+== Lists
 
-[[unordered]]
-Unordered
-~~~~~~~~~
+=== Unordered
 
 Asterisks tight:
 
@@ -180,45 +154,46 @@
 * Minus 2
 * Minus 3
 
-[[ordered]]
-Ordered
-~~~~~~~
+=== Ordered
 
 Tight:
 
-1.  First
-2.  Second
-3.  Third
+[arabic]
+. First
+. Second
+. Third
 
 and:
 
-1.  One
-2.  Two
-3.  Three
+[arabic]
+. One
+. Two
+. Three
 
 Loose using tabs:
 
-1.  First
-2.  Second
-3.  Third
+[arabic]
+. First
+. Second
+. Third
 
 and using spaces:
 
-1.  One
-2.  Two
-3.  Three
+[arabic]
+. One
+. Two
+. Three
 
 Multiple paragraphs:
 
-1.  Item 1, graf one.
+[arabic]
+. Item 1, graf one.
 +
 Item 1. graf two. The quick brown fox jumped over the lazy dog’s back.
-2.  Item 2.
-3.  Item 3.
+. Item 2.
+. Item 3.
 
-[[nested]]
-Nested
-~~~~~~
+=== Nested
 
 * Tab
 ** Tab
@@ -226,56 +201,61 @@
 
 Here’s another:
 
-1.  First
-2.  Second:
+[arabic]
+. First
+. Second:
 * Fee
 * Fie
 * Foe
-3.  Third
+. Third
 
 Same thing but with paragraphs:
 
-1.  First
-2.  Second:
+[arabic]
+. First
+. Second:
 * Fee
 * Fie
 * Foe
-3.  Third
+. Third
 
-[[tabs-and-spaces]]
-Tabs and spaces
-~~~~~~~~~~~~~~~
+=== Tabs and spaces
 
 * this is a list item indented with tabs
 * this is a list item indented with spaces
 ** this is an example list item indented with tabs
 ** this is an example list item indented with spaces
 
-[[fancy-list-markers]]
-Fancy list markers
-~~~~~~~~~~~~~~~~~~
+=== Fancy list markers
 
-1.  begins with 2
-2.  and now 3
+[arabic, start=2]
+. begins with 2
+. and now 3
 +
 with a continuation
-a.  sublist with roman numerals, starting with 4
-b.  more items
-A.  a subsublist
-B.  a subsublist
+[lowerroman, start=4]
+.. sublist with roman numerals, starting with 4
+.. more items
+[upperalpha]
+... a subsublist
+... a subsublist
 
 Nesting:
 
-A.  Upper Alpha
-A.  Upper Roman.
-1.  Decimal start with 6
-a.  Lower alpha with paren
+[upperalpha]
+. Upper Alpha
+[upperroman]
+.. Upper Roman.
+[arabic, start=6]
+... Decimal start with 6
+[loweralpha, start=3]
+.... Lower alpha with paren
 
 Autonumbering:
 
-1.  Autonumber.
-2.  More.
-1.  Nested.
+. Autonumber.
+. More.
+.. Nested.
 
 Should not be a list item:
 
@@ -285,9 +265,7 @@
 
 '''''
 
-[[definition-lists]]
-Definition Lists
-----------------
+== Definition Lists
 
 Tight using spaces:
 
@@ -329,9 +307,9 @@
 { orange code block }
 ....
   +
-  __________________
+  ____
   orange block quote
-  __________________
+  ____
 
 Multiple definitions, tight:
 
@@ -364,12 +342,11 @@
 orange::
   orange fruit
   +
-  1.  sublist
-  2.  sublist
+  [arabic]
+  . sublist
+  . sublist
 
-[[html-blocks]]
-HTML Blocks
------------
+== HTML Blocks
 
 Simple block on one line:
 
@@ -431,9 +408,7 @@
 
 '''''
 
-[[inline-markup]]
-Inline Markup
--------------
+== Inline Markup
 
 This is _emphasized_, and so _is this_.
 
@@ -449,33 +424,31 @@
 
 So is *_this_* word.
 
-This is code: `>`, `$`, `\`, `\$`, `<html>`.
+This is code: `++>++`, `$`, `++\++`, `++\++$`, `++<++html++>++`.
 
-[line-through]*This is _strikeout_.*
+[line-through]#This is _strikeout_.#
 
 Superscripts: a^bc^d a^_hello_^ a^hello there^.
 
 Subscripts: H~2~O, H~23~O, H~many of them~O.
 
-These should not be superscripts or subscripts, because of the unescaped
-spaces: a^b c^d, a~b c~d.
+These should not be superscripts or subscripts, because of the unescaped spaces:
+a^b c^d, a~b c~d.
 
 '''''
 
-[[smart-quotes-ellipses-dashes]]
-Smart quotes, ellipses, dashes
-------------------------------
+== Smart quotes, ellipses, dashes
 
-``Hello,'' said the spider. ```Shelob' is my name.''
+"`Hello,`" said the spider. "`'`Shelob`' is my name.`"
 
-`A', `B', and `C' are letters.
+'`A`', '`B`', and '`C`' are letters.
 
-`Oak,' `elm,' and `beech' are names of trees. So is `pine.'
+'`Oak,`' '`elm,`' and '`beech`' are names of trees. So is '`pine.`'
 
-`He said, ``I want to go.''' Were you alive in the 70’s?
+'`He said, "`I want to go.`"`' Were you alive in the 70’s?
 
-Here is some quoted ``code`' and a ``http://example.com/?foo=1&bar=2[quoted
-link]''.
+Here is some quoted '``code``' and a "`http://example.com/?foo=1&bar=2[quoted
+link]`".
 
 Some dashes: one—two — three—four — five.
 
@@ -485,25 +458,27 @@
 
 '''''
 
-[[latex]]
-LaTeX
------
+== LaTeX
 
 * 
-* latexmath:[$2+2=4$]
-* latexmath:[$x \in y$]
-* latexmath:[$\alpha \wedge \omega$]
-* latexmath:[$223$]
-* latexmath:[$p$]-Tree
+* latexmath:[2+2=4]
+* latexmath:[x \in y]
+* latexmath:[\alpha \wedge \omega]
+* 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$].
+latexmath:[\alpha + \omega \times x^2].
 
 These shouldn’t be math:
 
 * To get the famous equation, write `$e = mc^2$`.
-* $22,000 is a _lot_ of money. So is $34,000. (It worked if ``lot'' is
+* $22,000 is a _lot_ of money. So is $34,000. (It worked if "`lot`" is
 emphasized.)
 * Shoes ($20) and socks ($5).
 * Escaped `$`: $73 _this should be emphasized_ 23$.
@@ -512,9 +487,7 @@
 
 '''''
 
-[[special-characters]]
-Special Characters
-------------------
+== Special Characters
 
 Here is some unicode:
 
@@ -530,51 +503,47 @@
 
 This & that.
 
-4 < 5.
+4 ++<++ 5.
 
-6 > 5.
+6 ++>++ 5.
 
-Backslash: \
+Backslash: ++\++
 
-Backtick: `
+Backtick: ++`++
 
-Asterisk: *
+Asterisk: ++*++
 
-Underscore: _
+Underscore: ++_++
 
-Left brace: \{
+Left brace: ++{++
 
 Right brace: }
 
-Left bracket: [
+Left bracket: ++[++
 
-Right bracket: ]
+Right bracket: ++]++
 
 Left paren: (
 
 Right paren: )
 
-Greater-than: >
+Greater-than: ++>++
 
-Hash: #
+Hash: ++#++
 
 Period: .
 
 Bang: !
 
-Plus: +
+Plus: {plus}
 
 Minus: -
 
 '''''
 
-[[links]]
-Links
------
+== Links
 
-[[explicit]]
-Explicit
-~~~~~~~~
+=== Explicit
 
 Just a link:/url/[URL].
 
@@ -588,19 +557,17 @@
 
 link:/url/[URL and title]
 
-link:/url/with_underscore[with_underscore]
+link:/url/with_underscore[with++_++underscore]
 
 mailto:nobody@nowhere.net[Email link]
 
 link:[Empty].
 
-[[reference]]
-Reference
-~~~~~~~~~
+=== Reference
 
 Foo link:/url/[bar].
 
-With link:/url/[embedded [brackets]].
+With link:/url/[embedded ++[++brackets++]++].
 
 link:/url/[b] by itself should be a link.
 
@@ -610,7 +577,7 @@
 
 Indented link:/url[thrice].
 
-This should [not][] be a link.
+This should ++[++not++][]++ be a link.
 
 ....
 [not]: /url
@@ -620,9 +587,7 @@
 
 Foo link:/url/[biz].
 
-[[with-ampersands]]
-With ampersands
-~~~~~~~~~~~~~~~
+=== With ampersands
 
 Here’s a http://example.com/?foo=1&bar=2[link with an ampersand in the URL].
 
@@ -632,9 +597,7 @@
 
 Here’s an link:/script?foo=1&bar=2[inline link in pointy braces].
 
-[[autolinks]]
-Autolinks
-~~~~~~~~~
+=== Autolinks
 
 With an ampersand: http://example.com/?foo=1&bar=2
 
@@ -644,11 +607,11 @@
 
 An e-mail address: nobody@nowhere.net
 
-________________________________
+____
 Blockquoted: http://example.com/
-________________________________
+____
 
-Auto-links should not occur here: `<http://example.com/>`
+Auto-links should not occur here: `++<++http://example.com/++>++`
 
 ....
 or here: <http://example.com/>
@@ -656,34 +619,32 @@
 
 '''''
 
-[[images]]
-Images
-------
+== Images
 
-From ``Voyage dans la Lune'' by Georges Melies (1902):
+From "`Voyage dans la Lune`" by Georges Melies (1902):
 
-image:lalune.jpg[lalune,title="Voyage dans la Lune"]
+.lalune
+image::lalune.jpg[lalune,title="Voyage dans la Lune"]
 
 Here is a movie image:movie.jpg[movie] icon.
 
 '''''
 
-[[footnotes]]
-Footnotes
----------
+== Footnotes
 
-Here is a footnote reference,footnote:[Here is the footnote. It can go
-anywhere after the footnote reference. It need not be placed at the end of the
-document.] and another.[multiblock footnote omitted] This should _not_ be a
-footnote reference, because it contains a space.[^my note] Here is an inline
+Here is a footnote reference,footnote:[Here is the footnote. It can go anywhere
+after the footnote reference. It need not be placed at the end of the document.]
+and another.[multiblock footnote omitted] This should _not_ be a footnote
+reference, because it contains a space.++[++^my note++]++ Here is an inline
 note.footnote:[This is _easier_ to type. Inline notes may contain
-http://google.com[links] and `]` verbatim characters, as well as [bracketed
-text].]
+http://google.com[links] and `++]++` verbatim characters, as well as
+++[++bracketed text++]++.]
 
-___________________________________________
+____
 Notes can go in quotes.footnote:[In quote.]
-___________________________________________
+____
 
-1.  And in list items.footnote:[In list.]
+[arabic]
+. And in list items.footnote:[In list.]
 
 This paragraph should not be part of the note, as it is not indented.
diff --git a/test/writer.asciidoc_legacy b/test/writer.asciidoc_legacy
new file mode 100644
--- /dev/null
+++ b/test/writer.asciidoc_legacy
@@ -0,0 +1,649 @@
+= Pandoc Test Suite
+John MacFarlane; Anonymous
+July 17, 2006
+
+This is a set of tests for pandoc. Most of them are adapted from John Gruber’s
+markdown test suite.
+
+'''''
+
+== Headers
+
+=== Level 2 with an link:/url[embedded link]
+
+==== Level 3 with _emphasis_
+
+===== Level 4
+
+====== Level 5
+
+== Level 1
+
+=== Level 2 with _emphasis_
+
+==== Level 3
+
+with no blank line
+
+=== Level 2
+
+with no blank line
+
+'''''
+
+== Paragraphs
+
+Here’s a regular paragraph.
+
+In Markdown 1.0.0 and earlier. Version 8. This line turns into a list item.
+Because a hard-wrapped line in the middle of a paragraph looked like a list
+item.
+
+Here’s one with a bullet. ++*++ criminey.
+
+There should be a hard line break +
+here.
+
+'''''
+
+== Block Quotes
+
+E-mail style:
+
+____
+This is a block quote. It is pretty short.
+____
+
+____
+--
+Code in a block quote:
+
+....
+sub status {
+    print "working";
+}
+....
+
+A list:
+
+[arabic]
+. item one
+. item two
+
+Nested block quotes:
+
+____
+nested
+____
+
+____
+nested
+____
+
+--
+____
+
+This should not be a block quote: 2 ++>++ 1.
+
+And a following paragraph.
+
+'''''
+
+== Code Blocks
+
+Code:
+
+....
+---- (should be four hyphens)
+
+sub status {
+    print "working";
+}
+
+this code block is indented by one tab
+....
+
+And:
+
+....
+    this code block is indented by two tabs
+
+These should not be escaped:  \$ \\ \> \[ \{
+....
+
+'''''
+
+== Lists
+
+=== Unordered
+
+Asterisks tight:
+
+* asterisk 1
+* asterisk 2
+* asterisk 3
+
+Asterisks loose:
+
+* asterisk 1
+* asterisk 2
+* asterisk 3
+
+Pluses tight:
+
+* Plus 1
+* Plus 2
+* Plus 3
+
+Pluses loose:
+
+* Plus 1
+* Plus 2
+* Plus 3
+
+Minuses tight:
+
+* Minus 1
+* Minus 2
+* Minus 3
+
+Minuses loose:
+
+* Minus 1
+* Minus 2
+* Minus 3
+
+=== Ordered
+
+Tight:
+
+[arabic]
+. First
+. Second
+. Third
+
+and:
+
+[arabic]
+. One
+. Two
+. Three
+
+Loose using tabs:
+
+[arabic]
+. First
+. Second
+. Third
+
+and using spaces:
+
+[arabic]
+. One
+. Two
+. Three
+
+Multiple paragraphs:
+
+[arabic]
+. Item 1, graf one.
++
+Item 1. graf two. The quick brown fox jumped over the lazy dog’s back.
+. Item 2.
+. Item 3.
+
+=== Nested
+
+* Tab
+** Tab
+*** Tab
+
+Here’s another:
+
+[arabic]
+. First
+. Second:
+* Fee
+* Fie
+* Foe
+. Third
+
+Same thing but with paragraphs:
+
+[arabic]
+. First
+. Second:
+* Fee
+* Fie
+* Foe
+. Third
+
+=== Tabs and spaces
+
+* this is a list item indented with tabs
+* this is a list item indented with spaces
+** this is an example list item indented with tabs
+** this is an example list item indented with spaces
+
+=== Fancy list markers
+
+[arabic, start=2]
+. begins with 2
+. and now 3
++
+with a continuation
+[lowerroman, start=4]
+.. sublist with roman numerals, starting with 4
+.. more items
+[upperalpha]
+... a subsublist
+... a subsublist
+
+Nesting:
+
+[upperalpha]
+. Upper Alpha
+[upperroman]
+.. Upper Roman.
+[arabic, start=6]
+... Decimal start with 6
+[loweralpha, start=3]
+.... Lower alpha with paren
+
+Autonumbering:
+
+. Autonumber.
+. More.
+.. Nested.
+
+Should not be a list item:
+
+M.A. 2007
+
+B. Williams
+
+'''''
+
+== Definition Lists
+
+Tight using spaces:
+
+apple::
+  red fruit
+orange::
+  orange fruit
+banana::
+  yellow fruit
+
+Tight using tabs:
+
+apple::
+  red fruit
+orange::
+  orange fruit
+banana::
+  yellow fruit
+
+Loose:
+
+apple::
+  red fruit
+orange::
+  orange fruit
+banana::
+  yellow fruit
+
+Multiple blocks with italics:
+
+_apple_::
+  red fruit
+  +
+  contains seeds, crisp, pleasant to taste
+_orange_::
+  orange fruit
+  +
+....
+{ orange code block }
+....
+  +
+  ____
+  orange block quote
+  ____
+
+Multiple definitions, tight:
+
+apple::
+  red fruit
+  +
+  computer
+orange::
+  orange fruit
+  +
+  bank
+
+Multiple definitions, loose:
+
+apple::
+  red fruit
+  +
+  computer
+orange::
+  orange fruit
+  +
+  bank
+
+Blank line after term, indented marker, alternate markers:
+
+apple::
+  red fruit
+  +
+  computer
+orange::
+  orange fruit
+  +
+  [arabic]
+  . sublist
+  . sublist
+
+== HTML Blocks
+
+Simple block on one line:
+
+foo
+
+And nested without indentation:
+
+foo
+
+bar
+
+Interpreted markdown in a table:
+
+This is _emphasized_
+
+And this is *strong*
+
+Here’s a simple block:
+
+foo
+
+This should be a code block, though:
+
+....
+<div>
+    foo
+</div>
+....
+
+As should this:
+
+....
+<div>foo</div>
+....
+
+Now, nested:
+
+foo
+
+This should just be an HTML comment:
+
+Multiline:
+
+Code block:
+
+....
+<!-- Comment -->
+....
+
+Just plain comment, with trailing spaces on the line:
+
+Code:
+
+....
+<hr />
+....
+
+Hr’s:
+
+'''''
+
+== Inline Markup
+
+This is _emphasized_, and so _is this_.
+
+This is *strong*, and so *is this*.
+
+An _link:/url[emphasized link]_.
+
+*_This is strong and em._*
+
+So is *_this_* word.
+
+*_This is strong and em._*
+
+So is *_this_* word.
+
+This is code: `>`, `$`, `\`, `\$`, `<html>`.
+
+[line-through]#This is _strikeout_.#
+
+Superscripts: a^bc^d a^_hello_^ a^hello there^.
+
+Subscripts: H~2~O, H~23~O, H~many of them~O.
+
+These should not be superscripts or subscripts, because of the unescaped spaces:
+a^b c^d, a~b c~d.
+
+'''''
+
+== Smart quotes, ellipses, dashes
+
+``Hello,'' said the spider. ```Shelob' is my name.''
+
+`A', `B', and `C' are letters.
+
+`Oak,' `elm,' and `beech' are names of trees. So is `pine.'
+
+`He said, ``I want to go.''' Were you alive in the 70’s?
+
+Here is some quoted ``code`' and a ``http://example.com/?foo=1&bar=2[quoted
+link]''.
+
+Some dashes: one—two — three—four — five.
+
+Dashes between numbers: 5–7, 255–66, 1987–1999.
+
+Ellipses…and…and….
+
+'''''
+
+== LaTeX
+
+* 
+* latexmath:[$2+2=4$]
+* latexmath:[$x \in y$]
+* latexmath:[$\alpha \wedge \omega$]
+* 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}\]
+++++
+* Here’s one that has a line break in it:
+latexmath:[$\alpha + \omega \times x^2$].
+
+These shouldn’t be math:
+
+* To get the famous equation, write `$e = mc^2$`.
+* $22,000 is a _lot_ of money. So is $34,000. (It worked if ``lot'' is
+emphasized.)
+* Shoes ($20) and socks ($5).
+* Escaped `$`: $73 _this should be emphasized_ 23$.
+
+Here’s a LaTeX table:
+
+'''''
+
+== Special Characters
+
+Here is some unicode:
+
+* I hat: Î
+* o umlaut: ö
+* section: §
+* set membership: ∈
+* copyright: ©
+
+AT&T has an ampersand in their name.
+
+AT&T is another way to write it.
+
+This & that.
+
+4 ++<++ 5.
+
+6 ++>++ 5.
+
+Backslash: ++\++
+
+Backtick: ++`++
+
+Asterisk: ++*++
+
+Underscore: ++_++
+
+Left brace: ++{++
+
+Right brace: }
+
+Left bracket: ++[++
+
+Right bracket: ++]++
+
+Left paren: (
+
+Right paren: )
+
+Greater-than: ++>++
+
+Hash: ++#++
+
+Period: .
+
+Bang: !
+
+Plus: {plus}
+
+Minus: -
+
+'''''
+
+== Links
+
+=== Explicit
+
+Just a link:/url/[URL].
+
+link:/url/[URL and title].
+
+link:/url/[URL and title].
+
+link:/url/[URL and title].
+
+link:/url/[URL and title]
+
+link:/url/[URL and title]
+
+link:/url/with_underscore[with++_++underscore]
+
+mailto:nobody@nowhere.net[Email link]
+
+link:[Empty].
+
+=== Reference
+
+Foo link:/url/[bar].
+
+With link:/url/[embedded ++[++brackets++]++].
+
+link:/url/[b] by itself should be a link.
+
+Indented link:/url[once].
+
+Indented link:/url[twice].
+
+Indented link:/url[thrice].
+
+This should ++[++not++][]++ be a link.
+
+....
+[not]: /url
+....
+
+Foo link:/url/[bar].
+
+Foo link:/url/[biz].
+
+=== With ampersands
+
+Here’s a http://example.com/?foo=1&bar=2[link with an ampersand in the URL].
+
+Here’s a link with an amersand in the link text: http://att.com/[AT&T].
+
+Here’s an link:/script?foo=1&bar=2[inline link].
+
+Here’s an link:/script?foo=1&bar=2[inline link in pointy braces].
+
+=== Autolinks
+
+With an ampersand: http://example.com/?foo=1&bar=2
+
+* In a list?
+* http://example.com/
+* It should.
+
+An e-mail address: nobody@nowhere.net
+
+____
+Blockquoted: http://example.com/
+____
+
+Auto-links should not occur here: `<http://example.com/>`
+
+....
+or here: <http://example.com/>
+....
+
+'''''
+
+== Images
+
+From ``Voyage dans la Lune'' by Georges Melies (1902):
+
+.lalune
+image::lalune.jpg[lalune,title="Voyage dans la Lune"]
+
+Here is a movie image:movie.jpg[movie] icon.
+
+'''''
+
+== Footnotes
+
+Here is a footnote reference,footnote:[Here is the footnote. It can go anywhere
+after the footnote reference. It need not be placed at the end of the document.]
+and another.[multiblock footnote omitted] This should _not_ be a footnote
+reference, because it contains a space.++[++^my note++]++ Here is an inline
+note.footnote:[This is _easier_ to type. Inline notes may contain
+http://google.com[links] and `]` verbatim characters, as well as ++[++bracketed
+text++]++.]
+
+____
+Notes can go in quotes.footnote:[In quote.]
+____
+
+[arabic]
+. And in list items.footnote:[In list.]
+
+This paragraph should not be part of the note, as it is not indented.
diff --git a/test/writer.bbcode b/test/writer.bbcode
new file mode 100644
--- /dev/null
+++ b/test/writer.bbcode
@@ -0,0 +1,729 @@
+This is a set of tests for pandoc. Most of them are adapted from John Gruber's markdown test suite.
+
+* * *
+
+[u][b]Headers[/b][/u]
+
+[b]Level 2 with an [url=/url]embedded link[/url][/b]
+
+[u]Level 3 with [i]emphasis[/i][/u]
+
+Level 4
+
+Level 5
+
+[u][b]Level 1[/b][/u]
+
+[b]Level 2 with [i]emphasis[/i][/b]
+
+[u]Level 3[/u]
+
+with no blank line
+
+[b]Level 2[/b]
+
+with no blank line
+
+* * *
+
+[u][b]Paragraphs[/b][/u]
+
+Here's a regular paragraph.
+
+In Markdown 1.0.0 and earlier. Version 8. This line turns into a list item. Because a hard-wrapped line in the middle of a paragraph looked like a list item.
+
+Here's one with a bullet. * criminey.
+
+There should be a hard line break
+here.
+
+* * *
+
+[u][b]Block Quotes[/b][/u]
+
+E-mail style:
+
+[quote]
+This is a block quote. It is pretty short.
+[/quote]
+
+[quote]
+Code in a block quote:
+
+[code]sub status {
+    print "working";
+}
+[/code]
+
+A list:
+
+[list=1]
+[*]item one
+[*]item two
+[/list]
+
+Nested block quotes:
+
+[quote]
+nested
+[/quote]
+
+[quote]
+nested
+[/quote]
+[/quote]
+
+This should not be a block quote: 2 > 1.
+
+And a following paragraph.
+
+* * *
+
+[u][b]Code Blocks[/b][/u]
+
+Code:
+
+[code]---- (should be four hyphens)
+
+sub status {
+    print "working";
+}
+
+this code block is indented by one tab
+[/code]
+
+And:
+
+[code]    this code block is indented by two tabs
+
+These should not be escaped:  \$ \\ \> \[ \{
+[/code]
+
+* * *
+
+[u][b]Lists[/b][/u]
+
+[b]Unordered[/b]
+
+Asterisks tight:
+
+[list]
+[*]asterisk 1
+[*]asterisk 2
+[*]asterisk 3
+[/list]
+
+Asterisks loose:
+
+[list]
+[*]asterisk 1
+[*]asterisk 2
+[*]asterisk 3
+[/list]
+
+Pluses tight:
+
+[list]
+[*]Plus 1
+[*]Plus 2
+[*]Plus 3
+[/list]
+
+Pluses loose:
+
+[list]
+[*]Plus 1
+[*]Plus 2
+[*]Plus 3
+[/list]
+
+Minuses tight:
+
+[list]
+[*]Minus 1
+[*]Minus 2
+[*]Minus 3
+[/list]
+
+Minuses loose:
+
+[list]
+[*]Minus 1
+[*]Minus 2
+[*]Minus 3
+[/list]
+
+[b]Ordered[/b]
+
+Tight:
+
+[list=1]
+[*]First
+[*]Second
+[*]Third
+[/list]
+
+and:
+
+[list=1]
+[*]One
+[*]Two
+[*]Three
+[/list]
+
+Loose using tabs:
+
+[list=1]
+[*]First
+[*]Second
+[*]Third
+[/list]
+
+and using spaces:
+
+[list=1]
+[*]One
+[*]Two
+[*]Three
+[/list]
+
+Multiple paragraphs:
+
+[list=1]
+[*]Item 1, graf one.
+
+Item 1. graf two. The quick brown fox jumped over the lazy dog's back.
+[*]Item 2.
+[*]Item 3.
+[/list]
+
+[b]Nested[/b]
+
+[list]
+[*]Tab
+
+[list]
+[*]Tab
+
+[list]
+[*]Tab
+[/list]
+[/list]
+[/list]
+
+Here's another:
+
+[list=1]
+[*]First
+[*]Second:
+
+[list]
+[*]Fee
+[*]Fie
+[*]Foe
+[/list]
+[*]Third
+[/list]
+
+Same thing but with paragraphs:
+
+[list=1]
+[*]First
+[*]Second:
+
+[list]
+[*]Fee
+[*]Fie
+[*]Foe
+[/list]
+[*]Third
+[/list]
+
+[b]Tabs and spaces[/b]
+
+[list]
+[*]this is a list item indented with tabs
+[*]this is a list item indented with spaces
+
+[list]
+[*]this is an example list item indented with tabs
+[*]this is an example list item indented with spaces
+[/list]
+[/list]
+
+[b]Fancy list markers[/b]
+
+[list=1]
+[*]begins with 2
+[*]and now 3
+
+with a continuation
+
+[list=i]
+[*]sublist with roman numerals, starting with 4
+[*]more items
+
+[list=A]
+[*]a subsublist
+[*]a subsublist
+[/list]
+[/list]
+[/list]
+
+Nesting:
+
+[list=A]
+[*]Upper Alpha
+
+[list=I]
+[*]Upper Roman.
+
+[list=1]
+[*]Decimal start with 6
+
+[list=a]
+[*]Lower alpha with paren
+[/list]
+[/list]
+[/list]
+[/list]
+
+Autonumbering:
+
+[list=1]
+[*]Autonumber.
+[*]More.
+
+[list=1]
+[*]Nested.
+[/list]
+[/list]
+
+Should not be a list item:
+
+M.A. 2007
+
+B. Williams
+
+* * *
+
+[u][b]Definition Lists[/b][/u]
+
+Tight using spaces:
+
+apple
+[list]
+[*]red fruit
+[/list]
+orange
+[list]
+[*]orange fruit
+[/list]
+banana
+[list]
+[*]yellow fruit
+[/list]
+
+Tight using tabs:
+
+apple
+[list]
+[*]red fruit
+[/list]
+orange
+[list]
+[*]orange fruit
+[/list]
+banana
+[list]
+[*]yellow fruit
+[/list]
+
+Loose:
+
+apple
+[list]
+[*]red fruit
+[/list]
+orange
+[list]
+[*]orange fruit
+[/list]
+banana
+[list]
+[*]yellow fruit
+[/list]
+
+Multiple blocks with italics:
+
+[i]apple[/i]
+[list]
+[*]red fruit
+
+contains seeds, crisp, pleasant to taste
+[/list]
+[i]orange[/i]
+[list]
+[*]orange fruit
+
+[code]{ orange code block }
+[/code]
+
+[quote]
+orange block quote
+[/quote]
+[/list]
+
+Multiple definitions, tight:
+
+apple
+[list]
+[*]red fruit
+[*]computer
+[/list]
+orange
+[list]
+[*]orange fruit
+[*]bank
+[/list]
+
+Multiple definitions, loose:
+
+apple
+[list]
+[*]red fruit
+[*]computer
+[/list]
+orange
+[list]
+[*]orange fruit
+[*]bank
+[/list]
+
+Blank line after term, indented marker, alternate markers:
+
+apple
+[list]
+[*]red fruit
+[*]computer
+[/list]
+orange
+[list]
+[*]orange fruit
+
+[list=1]
+[*]sublist
+[*]sublist
+[/list]
+[/list]
+
+[u][b]HTML Blocks[/b][/u]
+
+Simple block on one line:
+
+foo
+
+And nested without indentation:
+
+foo
+
+bar
+
+Interpreted markdown in a table:
+
+This is [i]emphasized[/i]
+
+And this is [b]strong[/b]
+
+Here's a simple block:
+
+foo
+
+This should be a code block, though:
+
+[code]<div>
+    foo
+</div>
+[/code]
+
+As should this:
+
+[code]<div>foo</div>
+[/code]
+
+Now, nested:
+
+foo
+
+This should just be an HTML comment:
+
+Multiline:
+
+Code block:
+
+[code]<!-- Comment -->
+[/code]
+
+Just plain comment, with trailing spaces on the line:
+
+Code:
+
+[code]<hr />
+[/code]
+
+Hr's:
+
+* * *
+
+[u][b]Inline Markup[/b][/u]
+
+This is [i]emphasized[/i], and so [i]is this[/i].
+
+This is [b]strong[/b], and so [b]is this[/b].
+
+An [i][url=/url]emphasized link[/url][/i].
+
+[b][i]This is strong and em.[/i][/b]
+
+So is [b][i]this[/i][/b] word.
+
+[b][i]This is strong and em.[/i][/b]
+
+So is [b][i]this[/i][/b] word.
+
+This is code: >, $, \, \$, <html>.
+
+[s]This is [i]strikeout[/i].[/s]
+
+Superscripts: abcd a[i]hello[/i] ahello there.
+
+Subscripts: H2O, H23O, Hmany of themO.
+
+These should not be superscripts or subscripts, because of the unescaped spaces: a^b c^d, a~b c~d.
+
+* * *
+
+[u][b]Smart quotes, ellipses, dashes[/b][/u]
+
+"Hello," said the spider. "'Shelob' is my name."
+
+'A', 'B', and 'C' are letters.
+
+'Oak,' 'elm,' and 'beech' are names of trees. So is 'pine.'
+
+'He said, "I want to go."' Were you alive in the 70's?
+
+Here is some quoted 'code' and a "[url=http://example.com/?foo=1&bar=2]quoted link[/url]".
+
+Some dashes: one---two --- three---four --- five.
+
+Dashes between numbers: 5--7, 255--66, 1987--1999.
+
+Ellipses...and...and....
+
+* * *
+
+[u][b]LaTeX[/b][/u]
+
+[list]
+[*]
+[*]$2+2=4$
+[*]$x \in y$
+[*]$\alpha \wedge \omega$
+[*]$223$
+[*]$p$-Tree
+[*]Here's some display math: [code=latex]$$\frac{d}{dx}f(x)=\lim_{h\to 0}\frac{f(x+h)-f(x)}{h}$$
+[/code]
+[*]Here's one that has a line break in it: $\alpha + \omega \times x^2$.
+[/list]
+
+These shouldn't be math:
+
+[list]
+[*]To get the famous equation, write $e = mc^2$.
+[*]$22,000 is a [i]lot[/i] of money. So is $34,000. (It worked if "lot" is emphasized.)
+[*]Shoes ($20) and socks ($5).
+[*]Escaped $: $73 [i]this should be emphasized[/i] 23$.
+[/list]
+
+Here's a LaTeX table:
+
+* * *
+
+[u][b]Special Characters[/b][/u]
+
+Here is some unicode:
+
+[list]
+[*]I hat: Î
+[*]o umlaut: ö
+[*]section: §
+[*]set membership: ∈
+[*]copyright: ©
+[/list]
+
+AT&T has an ampersand in their name.
+
+AT&T is another way to write it.
+
+This & that.
+
+4 < 5.
+
+6 > 5.
+
+Backslash: \
+
+Backtick: `
+
+Asterisk: *
+
+Underscore: _
+
+Left brace: {
+
+Right brace: }
+
+Left bracket: [
+
+Right bracket: ]
+
+Left paren: (
+
+Right paren: )
+
+Greater-than: >
+
+Hash: #
+
+Period: .
+
+Bang: !
+
+Plus: +
+
+Minus: -
+
+* * *
+
+[u][b]Links[/b][/u]
+
+[b]Explicit[/b]
+
+Just a [url=/url/]URL[/url].
+
+[url=/url/]URL and title[/url].
+
+[url=/url/]URL and title[/url].
+
+[url=/url/]URL and title[/url].
+
+[url=/url/]URL and title[/url]
+
+[url=/url/]URL and title[/url]
+
+[url=/url/with_underscore]with_underscore[/url]
+
+[email=nobody@nowhere.net]Email link[/email]
+
+[url]Empty[/url].
+
+[b]Reference[/b]
+
+Foo [url=/url/]bar[/url].
+
+With [url=/url/]embedded [brackets][/url].
+
+[url=/url/]b[/url] by itself should be a link.
+
+Indented [url=/url]once[/url].
+
+Indented [url=/url]twice[/url].
+
+Indented [url=/url]thrice[/url].
+
+This should [not][] be a link.
+
+[code][not]: /url
+[/code]
+
+Foo [url=/url/]bar[/url].
+
+Foo [url=/url/]biz[/url].
+
+[b]With ampersands[/b]
+
+Here's a [url=http://example.com/?foo=1&bar=2]link with an ampersand in the URL[/url].
+
+Here's a link with an amersand in the link text: [url=http://att.com/]AT&T[/url].
+
+Here's an [url=/script?foo=1&bar=2]inline link[/url].
+
+Here's an [url=/script?foo=1&bar=2]inline link in pointy braces[/url].
+
+[b]Autolinks[/b]
+
+With an ampersand: [url]http://example.com/?foo=1&bar=2[/url]
+
+[list]
+[*]In a list?
+[*][url]http://example.com/[/url]
+[*]It should.
+[/list]
+
+An e-mail address: [email]nobody@nowhere.net[/email]
+
+[quote]
+Blockquoted: [url]http://example.com/[/url]
+[/quote]
+
+Auto-links should not occur here: <http://example.com/>
+
+[code]or here: <http://example.com/>
+[/code]
+
+* * *
+
+[u][b]Images[/b][/u]
+
+From "Voyage dans la Lune" by Georges Melies (1902):
+
+[img alt="lalune" title="Voyage dans la Lune"]lalune.jpg[/img]
+lalune
+
+Here is a movie [img alt="movie"]movie.jpg[/img] icon.
+
+* * *
+
+[u][b]Footnotes[/b][/u]
+
+Here is a footnote reference,(1) and another.(2) This should [i]not[/i] be a footnote reference, because it contains a space.[^my note] Here is an inline note.(3)
+
+[quote]
+Notes can go in quotes.(4)
+[/quote]
+
+[list=1]
+[*]And in list items.(5)
+[/list]
+
+This paragraph should not be part of the note, as it is not indented.
+
+* * *
+
+(1) Here is the footnote. It can go anywhere after the footnote reference. It need not be placed at the end of the document.
+
+(2) Here's the long note. This one contains multiple blocks.
+
+Subsequent blocks are indented to show that they belong to the footnote (as with list items).
+
+[code]  { <code> }
+[/code]
+
+If you want, you can indent every line, but you can also be lazy and just indent the first line of each block.
+
+(3) This is [i]easier[/i] to type. Inline notes may contain [url=http://google.com]links[/url] and ] verbatim characters, as well as [bracketed text].
+
+(4) In quote.
+
+(5) In list.
diff --git a/test/writer.context b/test/writer.context
--- a/test/writer.context
+++ b/test/writer.context
@@ -6,22 +6,25 @@
   style=,
   color=,
   contrastcolor=]
+\setupurl[style=]
 
 % make chapter, section bookmarks visible when opening document
 \placebookmarks[chapter, section, subsection, subsubsection, subsubsubsection, subsubsubsubsection][chapter, section]
-\setupinteractionscreen[option=bookmark]
-\setuptagging[state=start]
+\setupinteractionscreen[option={bookmark,title}]
 
+\setuppagenumbering[location={footer,middle}]
+\setupstructure[state=start,method=auto]
 
 % use microtypography
 \definefontfeature[default][default][script=latn, protrusion=quality, expansion=quality, itlc=yes, textitalics=yes, onum=yes, pnum=yes]
+\definefontfeature[default:tnum][default][tnum=yes, pnum=no]
 \definefontfeature[smallcaps][script=latn, protrusion=quality, expansion=quality, smcp=yes, onum=yes, pnum=yes]
 \setupalign[hz,hanging]
 \setupitaliccorrection[global, always]
 
 \setupbodyfontenvironment[default][em=italic] % use italic as em, not slanted
 
-\definefallbackfamily[mainface][rm][DejaVu Serif][preset=range:greek, force=yes]
+\definefallbackfamily[mainface][rm][CMU Serif][preset=range:greek, force=yes]
 \definefontfamily[mainface][rm][Latin Modern Roman]
 \definefontfamily[mainface][mm][Latin Modern Math]
 \definefontfamily[mainface][ss][Latin Modern Sans]
@@ -30,13 +33,17 @@
 
 \setupwhitespace[medium]
 
-\setuphead[chapter]            [style=\tfd,header=empty]
-\setuphead[section]            [style=\tfc]
-\setuphead[subsection]         [style=\tfb]
+\setuphead[chapter]            [style=\tfd\setupinterlinespace,header=empty]
+\setuphead[section]            [style=\tfc\setupinterlinespace]
+\setuphead[subsection]         [style=\tfb\setupinterlinespace]
 \setuphead[subsubsection]      [style=\bf]
 \setuphead[subsubsubsection]   [style=\sc]
 \setuphead[subsubsubsubsection][style=\it]
 
+\definesectionlevels
+   [default]
+   [section, subsection, subsubsection, subsubsubsection, subsubsubsubsection]
+
 \setuphead[chapter, section, subsection, subsubsection, subsubsubsection, subsubsubsubsection][number=no]
 
 \definedescription
@@ -46,19 +53,26 @@
 \setupitemize[autointro]    % prevent orphan list intro
 \setupitemize[indentnext=no]
 
+\defineitemgroup[enumerate]
+\setupenumerate[each][fit][itemalign=left,distance=.5em,style={\feature[+][default:tnum]}]
+
 \setupfloat[figure][default={here,nonumber}]
 \setupfloat[table][default={here,nonumber}]
 
-\setupthinrules[width=15em] % width of horizontal rules
+\setupxtable[frame=off]
+\setupxtable[head][topframe=on]
+\setupxtable[body][]
+\setupxtable[foot][]
+\setupxtable[lastrow][bottomframe=on]
 
 
 \starttext
 \startalignment[middle]
-  {\tfd Pandoc Test Suite}
+  {\tfd\setupinterlinespace Pandoc Test Suite}
   \smallskip
-  {\tfa John MacFarlane\crlf Anonymous}
+  {\tfa\setupinterlinespace John MacFarlane\crlf Anonymous}
   \smallskip
-  {\tfa July 17, 2006}
+  {\tfa\setupinterlinespace July 17, 2006}
   \bigskip
 \stopalignment
 
@@ -67,33 +81,53 @@
 
 \thinrule
 
-\section[headers]{Headers}
+\startsectionlevel[title={Headers},reference={headers}]
 
-\subsection[level-2-with-an-embedded-link]{Level 2 with an
-\useURL[url1][/url][][embedded link]\from[url1]}
+\startsectionlevel[title={Level 2 with an \goto{embedded
+link}[url(/url)]},reference={level-2-with-an-embedded-link}]
 
-\subsubsection[level-3-with-emphasis]{Level 3 with {\em emphasis}}
+\startsectionlevel[title={Level 3 with {\em
+emphasis}},reference={level-3-with-emphasis}]
 
-\subsubsubsection[level-4]{Level 4}
+\startsectionlevel[title={Level 4},reference={level-4}]
 
-\subsubsubsubsection[level-5]{Level 5}
+\startsectionlevel[title={Level 5},reference={level-5}]
 
-\section[level-1]{Level 1}
+\stopsectionlevel
 
-\subsection[level-2-with-emphasis]{Level 2 with {\em emphasis}}
+\stopsectionlevel
 
-\subsubsection[level-3]{Level 3}
+\stopsectionlevel
 
+\stopsectionlevel
+
+\stopsectionlevel
+
+\startsectionlevel[title={Level 1},reference={level-1}]
+
+\startsectionlevel[title={Level 2 with {\em
+emphasis}},reference={level-2-with-emphasis}]
+
+\startsectionlevel[title={Level 3},reference={level-3}]
+
 with no blank line
 
-\subsection[level-2]{Level 2}
+\stopsectionlevel
 
+\stopsectionlevel
+
+\startsectionlevel[title={Level 2},reference={level-2}]
+
 with no blank line
 
 \thinrule
 
-\section[paragraphs]{Paragraphs}
+\stopsectionlevel
 
+\stopsectionlevel
+
+\startsectionlevel[title={Paragraphs},reference={paragraphs}]
+
 Here's a regular paragraph.
 
 In Markdown 1.0.0 and earlier. Version 8. This line turns into a list item.
@@ -107,8 +141,10 @@
 
 \thinrule
 
-\section[block-quotes]{Block Quotes}
+\stopsectionlevel
 
+\startsectionlevel[title={Block Quotes},reference={block-quotes}]
+
 E-mail style:
 
 \startblockquote
@@ -126,12 +162,12 @@
 
 A list:
 
-\startitemize[n,packed][stopper=.]
+\startenumerate[n,packed][stopper=.]
 \item
   item one
 \item
   item two
-\stopitemize
+\stopenumerate
 
 Nested block quotes:
 
@@ -150,8 +186,10 @@
 
 \thinrule
 
-\section[code-blocks]{Code Blocks}
+\stopsectionlevel
 
+\startsectionlevel[title={Code Blocks},reference={code-blocks}]
+
 Code:
 
 \starttyping
@@ -174,10 +212,12 @@
 
 \thinrule
 
-\section[lists]{Lists}
+\stopsectionlevel
 
-\subsection[unordered]{Unordered}
+\startsectionlevel[title={Lists},reference={lists}]
 
+\startsectionlevel[title={Unordered},reference={unordered}]
+
 Asterisks tight:
 
 \startitemize[packed]
@@ -244,55 +284,57 @@
   Minus 3
 \stopitemize
 
-\subsection[ordered]{Ordered}
+\stopsectionlevel
 
+\startsectionlevel[title={Ordered},reference={ordered}]
+
 Tight:
 
-\startitemize[n,packed][stopper=.]
+\startenumerate[n,packed][stopper=.]
 \item
   First
 \item
   Second
 \item
   Third
-\stopitemize
+\stopenumerate
 
 and:
 
-\startitemize[n,packed][stopper=.]
+\startenumerate[n,packed][stopper=.]
 \item
   One
 \item
   Two
 \item
   Three
-\stopitemize
+\stopenumerate
 
 Loose using tabs:
 
-\startitemize[n][stopper=.]
+\startenumerate[n][stopper=.]
 \item
   First
 \item
   Second
 \item
   Third
-\stopitemize
+\stopenumerate
 
 and using spaces:
 
-\startitemize[n][stopper=.]
+\startenumerate[n][stopper=.]
 \item
   One
 \item
   Two
 \item
   Three
-\stopitemize
+\stopenumerate
 
 Multiple paragraphs:
 
-\startitemize[n][stopper=.]
+\startenumerate[n][stopper=.]
 \item
   Item 1, graf one.
 
@@ -301,10 +343,12 @@
   Item 2.
 \item
   Item 3.
-\stopitemize
+\stopenumerate
 
-\subsection[nested]{Nested}
+\stopsectionlevel
 
+\startsectionlevel[title={Nested},reference={nested}]
+
 \startitemize[packed]
 \item
   Tab
@@ -320,7 +364,7 @@
 
 Here's another:
 
-\startitemize[n,packed][stopper=.]
+\startenumerate[n,packed][stopper=.]
 \item
   First
 \item
@@ -335,11 +379,11 @@
   \stopitemize
 \item
   Third
-\stopitemize
+\stopenumerate
 
 Same thing but with paragraphs:
 
-\startitemize[n][stopper=.]
+\startenumerate[n][stopper=.]
 \item
   First
 \item
@@ -355,10 +399,12 @@
   \stopitemize
 \item
   Third
-\stopitemize
+\stopenumerate
 
-\subsection[tabs-and-spaces]{Tabs and spaces}
+\stopsectionlevel
 
+\startsectionlevel[title={Tabs and spaces},reference={tabs-and-spaces}]
+
 \startitemize
 \item
   this is a list item indented with tabs
@@ -373,9 +419,11 @@
   \stopitemize
 \stopitemize
 
-\subsection[fancy-list-markers]{Fancy list markers}
+\stopsectionlevel
 
-\startitemize[n][start=2,left=(,stopper=),width=2.0em]
+\startsectionlevel[title={Fancy list markers},reference={fancy-list-markers}]
+
+\startenumerate[n][start=2,left=(,stopper=)]
 \item
   begins with 2
 \item
@@ -383,51 +431,51 @@
 
   with a continuation
 
-  \startitemize[r,packed][start=4,stopper=.,width=2.0em]
+  \startenumerate[r,packed][start=4,stopper=.]
   \item
     sublist with roman numerals, starting with 4
   \item
     more items
-    \startitemize[A,packed][left=(,stopper=),width=2.0em]
+    \startenumerate[A,packed][left=(,stopper=)]
     \item
       a subsublist
     \item
       a subsublist
-    \stopitemize
-  \stopitemize
-\stopitemize
+    \stopenumerate
+  \stopenumerate
+\stopenumerate
 
 Nesting:
 
-\startitemize[A,packed][stopper=.]
+\startenumerate[A,packed][stopper=.]
 \item
   Upper Alpha
-  \startitemize[R,packed][stopper=.]
+  \startenumerate[R,packed][stopper=.]
   \item
     Upper Roman.
-    \startitemize[n,packed][start=6,left=(,stopper=),width=2.0em]
+    \startenumerate[n,packed][start=6,left=(,stopper=)]
     \item
       Decimal start with 6
-      \startitemize[a,packed][start=3,stopper=)]
+      \startenumerate[a,packed][start=3,stopper=)]
       \item
         Lower alpha with paren
-      \stopitemize
-    \stopitemize
-  \stopitemize
-\stopitemize
+      \stopenumerate
+    \stopenumerate
+  \stopenumerate
+\stopenumerate
 
 Autonumbering:
 
-\startitemize[n,packed]
+\startenumerate[n,packed]
 \item
   Autonumber.
 \item
   More.
-  \startitemize[a,packed]
+  \startenumerate[a,packed]
   \item
     Nested.
-  \stopitemize
-\stopitemize
+  \stopenumerate
+\stopenumerate
 
 Should not be a list item:
 
@@ -437,8 +485,12 @@
 
 \thinrule
 
-\section[definition-lists]{Definition Lists}
+\stopsectionlevel
 
+\stopsectionlevel
+
+\startsectionlevel[title={Definition Lists},reference={definition-lists}]
+
 Tight using spaces:
 
 \startdescription{apple}
@@ -540,16 +592,18 @@
 \startdescription{orange}
   orange fruit
 
-  \startitemize[n,packed][stopper=.]
+  \startenumerate[n,packed][stopper=.]
   \item
     sublist
   \item
     sublist
-  \stopitemize
+  \stopenumerate
 \stopdescription
 
-\section[html-blocks]{HTML Blocks}
+\stopsectionlevel
 
+\startsectionlevel[title={HTML Blocks},reference={html-blocks}]
+
 Simple block on one line:
 
 foo
@@ -608,13 +662,15 @@
 
 \thinrule
 
-\section[inline-markup]{Inline Markup}
+\stopsectionlevel
 
+\startsectionlevel[title={Inline Markup},reference={inline-markup}]
+
 This is {\em emphasized}, and so {\em is this}.
 
 This is {\bf strong}, and so {\bf is this}.
 
-An {\em \useURL[url2][/url][][emphasized link]\from[url2]}.
+An {\em \goto{emphasized link}[url(/url)]}.
 
 {\bf {\em This is strong and em.}}
 
@@ -632,13 +688,16 @@
 
 Subscripts: H\low{2}O, H\low{23}O, H\low{many~of~them}O.
 
-These should not be superscripts or subscripts, because of the unescaped
-spaces: a^b c^d, a\lettertilde{}b c\lettertilde{}d.
+These should not be superscripts or subscripts, because of the unescaped spaces:
+a^b c^d, a\lettertilde{}b c\lettertilde{}d.
 
 \thinrule
 
-\section[smart-quotes-ellipses-dashes]{Smart quotes, ellipses, dashes}
+\stopsectionlevel
 
+\startsectionlevel[title={Smart quotes, ellipses,
+dashes},reference={smart-quotes-ellipses-dashes}]
+
 \quotation{Hello,} said the spider. \quotation{\quote{Shelob} is my name.}
 
 \quote{A}, \quote{B}, and \quote{C} are letters.
@@ -648,9 +707,8 @@
 
 \quote{He said, \quotation{I want to go.}} Were you alive in the 70's?
 
-Here is some quoted \quote{\type{code}} and a
-\quotation{\useURL[url3][http://example.com/?foo=1&bar=2][][quoted
-link]\from[url3]}.
+Here is some quoted \quote{\type{code}} and a \quotation{\goto{quoted
+link}[url(http://example.com/?foo=1&bar=2)]}.
 
 Some dashes: one---two --- three---four --- five.
 
@@ -660,8 +718,10 @@
 
 \thinrule
 
-\section[latex]{LaTeX}
+\stopsectionlevel
 
+\startsectionlevel[title={LaTeX},reference={latex}]
+
 \startitemize[packed]
 \item
   \cite[22-23]{smith.1899}
@@ -698,10 +758,18 @@
 
 Here's a LaTeX table:
 
+\begin{tabular}{|l|l|}\hline
+Animal & Number \\ \hline
+Dog    & 2      \\
+Cat    & 1      \\ \hline
+\end{tabular}
+
 \thinrule
 
-\section[special-characters]{Special Characters}
+\stopsectionlevel
 
+\startsectionlevel[title={Special Characters},reference={special-characters}]
+
 Here is some unicode:
 
 \startitemize[packed]
@@ -761,83 +829,89 @@
 
 \thinrule
 
-\section[links]{Links}
+\stopsectionlevel
 
-\subsection[explicit]{Explicit}
+\startsectionlevel[title={Links},reference={links}]
 
-Just a \useURL[url4][/url/][][URL]\from[url4].
+\startsectionlevel[title={Explicit},reference={explicit}]
 
-\useURL[url5][/url/][][URL and title]\from[url5].
+Just a \goto{URL}[url(/url/)].
 
-\useURL[url6][/url/][][URL and title]\from[url6].
+\goto{URL and title}[url(/url/)].
 
-\useURL[url7][/url/][][URL and title]\from[url7].
+\goto{URL and title}[url(/url/)].
 
-\useURL[url8][/url/][][URL and title]\from[url8]
+\goto{URL and title}[url(/url/)].
 
-\useURL[url9][/url/][][URL and title]\from[url9]
+\goto{URL and title}[url(/url/)]
 
-\useURL[url10][/url/with_underscore][][with_underscore]\from[url10]
+\goto{URL and title}[url(/url/)]
 
-\useURL[url11][mailto:nobody@nowhere.net][][Email link]\from[url11]
+\goto{with_underscore}[url(/url/with_underscore)]
 
-\useURL[url12][][][Empty]\from[url12].
+\goto{Email link}[url(mailto:nobody@nowhere.net)]
 
-\subsection[reference]{Reference}
+\goto{Empty}[url()].
 
-Foo \useURL[url13][/url/][][bar]\from[url13].
+\stopsectionlevel
 
-With \useURL[url14][/url/][][embedded {[}brackets{]}]\from[url14].
+\startsectionlevel[title={Reference},reference={reference}]
 
-\useURL[url15][/url/][][b]\from[url15] by itself should be a link.
+Foo \goto{bar}[url(/url/)].
 
-Indented \useURL[url16][/url][][once]\from[url16].
+With \goto{embedded {[}brackets{]}}[url(/url/)].
 
-Indented \useURL[url17][/url][][twice]\from[url17].
+\goto{b}[url(/url/)] by itself should be a link.
 
-Indented \useURL[url18][/url][][thrice]\from[url18].
+Indented \goto{once}[url(/url)].
 
+Indented \goto{twice}[url(/url)].
+
+Indented \goto{thrice}[url(/url)].
+
 This should {[}not{]}{[}{]} be a link.
 
 \starttyping
 [not]: /url
 \stoptyping
 
-Foo \useURL[url19][/url/][][bar]\from[url19].
+Foo \goto{bar}[url(/url/)].
 
-Foo \useURL[url20][/url/][][biz]\from[url20].
+Foo \goto{biz}[url(/url/)].
 
-\subsection[with-ampersands]{With ampersands}
+\stopsectionlevel
 
-Here's a \useURL[url21][http://example.com/?foo=1&bar=2][][link with an
-ampersand in the URL]\from[url21].
+\startsectionlevel[title={With ampersands},reference={with-ampersands}]
 
+Here's a \goto{link with an ampersand in the
+URL}[url(http://example.com/?foo=1&bar=2)].
+
 Here's a link with an amersand in the link text:
-\useURL[url22][http://att.com/][][AT&T]\from[url22].
+\goto{AT&T}[url(http://att.com/)].
 
-Here's an \useURL[url23][/script?foo=1&bar=2][][inline link]\from[url23].
+Here's an \goto{inline link}[url(/script?foo=1&bar=2)].
 
-Here's an \useURL[url24][/script?foo=1&bar=2][][inline link in pointy
-braces]\from[url24].
+Here's an \goto{inline link in pointy braces}[url(/script?foo=1&bar=2)].
 
-\subsection[autolinks]{Autolinks}
+\stopsectionlevel
 
-With an ampersand: \useURL[url25][http://example.com/?foo=1&bar=2]\from[url25]
+\startsectionlevel[title={Autolinks},reference={autolinks}]
 
+With an ampersand: \useURL[url1][http://example.com/?foo=1&bar=2]\from[url1]
+
 \startitemize[packed]
 \item
   In a list?
 \item
-  \useURL[url26][http://example.com/]\from[url26]
+  \useURL[url2][http://example.com/]\from[url2]
 \item
   It should.
 \stopitemize
 
-An e-mail address:
-\useURL[url27][mailto:nobody@nowhere.net][][nobody@nowhere.net]\from[url27]
+An e-mail address: \goto{nobody@nowhere.net}[url(mailto:nobody@nowhere.net)]
 
 \startblockquote
-Blockquoted: \useURL[url28][http://example.com/]\from[url28]
+Blockquoted: \useURL[url3][http://example.com/]\from[url3]
 \stopblockquote
 
 Auto-links should not occur here: \type{<http://example.com/>}
@@ -848,23 +922,31 @@
 
 \thinrule
 
-\section[images]{Images}
+\stopsectionlevel
 
+\stopsectionlevel
+
+\startsectionlevel[title={Images},reference={images}]
+
 From \quotation{Voyage dans la Lune} by Georges Melies (1902):
 
-\placefigure{lalune}{\externalfigure[lalune.jpg]}
+\startplacefigure[title={lalune}]
+{\externalfigure[lalune.jpg]}
+\stopplacefigure
 
 Here is a movie {\externalfigure[movie.jpg]} icon.
 
 \thinrule
 
-\section[footnotes]{Footnotes}
+\stopsectionlevel
 
-Here is a footnote reference,\footnote{Here is the footnote. It can go
-  anywhere after the footnote reference. It need not be placed at the end of
-  the document.} and another.\startbuffer Here's the long note. This one
-  contains multiple blocks.
+\startsectionlevel[title={Footnotes},reference={footnotes}]
 
+Here is a footnote reference,\footnote{Here is the footnote. It can go anywhere
+  after the footnote reference. It need not be placed at the end of the
+  document.} and another.\startbuffer Here's the long note. This one contains
+  multiple blocks.
+
   Subsequent blocks are indented to show that they belong to the footnote (as
   with list items).
 
@@ -876,18 +958,20 @@
   indent the first line of each block.\stopbuffer\footnote{\getbuffer} This
 should {\em not} be a footnote reference, because it contains a space.{[}^my
 note{]} Here is an inline note.\footnote{This is {\em easier} to type. Inline
-  notes may contain \useURL[url29][http://google.com][][links]\from[url29] and
-  \type{]} verbatim characters, as well as {[}bracketed text{]}.}
+  notes may contain \goto{links}[url(http://google.com)] and \type{]} verbatim
+  characters, as well as {[}bracketed text{]}.}
 
 \startblockquote
 Notes can go in quotes.\footnote{In quote.}
 \stopblockquote
 
-\startitemize[n,packed][stopper=.]
+\startenumerate[n,packed][stopper=.]
 \item
   And in list items.\footnote{In list.}
-\stopitemize
+\stopenumerate
 
 This paragraph should not be part of the note, as it is not indented.
+
+\stopsectionlevel
 
 \stoptext
diff --git a/test/writer.custom b/test/writer.custom
deleted file mode 100644
--- a/test/writer.custom
+++ /dev/null
@@ -1,783 +0,0 @@
-<p>This is a set of tests for pandoc. Most of them are adapted from
-John Gruber’s markdown test suite.</p>
-
-<hr/>
-
-<h1 id="headers">Headers</h1>
-
-<h2 id="level-2-with-an-embedded-link">Level 2 with an <a href='/url' title=''>embedded link</a></h2>
-
-<h3 id="level-3-with-emphasis">Level 3 with <em>emphasis</em></h3>
-
-<h4 id="level-4">Level 4</h4>
-
-<h5 id="level-5">Level 5</h5>
-
-<h1 id="level-1">Level 1</h1>
-
-<h2 id="level-2-with-emphasis">Level 2 with <em>emphasis</em></h2>
-
-<h3 id="level-3">Level 3</h3>
-
-<p>with no blank line</p>
-
-<h2 id="level-2">Level 2</h2>
-
-<p>with no blank line</p>
-
-<hr/>
-
-<h1 id="paragraphs">Paragraphs</h1>
-
-<p>Here’s a regular paragraph.</p>
-
-<p>In Markdown 1.0.0 and earlier. Version
-8. This line turns into a list item.
-Because a hard-wrapped line in the
-middle of a paragraph looked like a
-list item.</p>
-
-<p>Here’s one with a bullet.
-* criminey.</p>
-
-<p>There should be a hard line break<br/>here.</p>
-
-<hr/>
-
-<h1 id="block-quotes">Block Quotes</h1>
-
-<p>E-mail style:</p>
-
-<blockquote>
-<p>This is a block quote.
-It is pretty short.</p>
-</blockquote>
-
-<blockquote>
-<p>Code in a block quote:</p>
-
-<pre><code>sub status {
-    print &quot;working&quot;;
-}</code></pre>
-
-<p>A list:</p>
-
-<ol>
-<li>item one</li>
-<li>item two</li>
-</ol>
-
-<p>Nested block quotes:</p>
-
-<blockquote>
-<p>nested</p>
-</blockquote>
-
-<blockquote>
-<p>nested</p>
-</blockquote>
-</blockquote>
-
-<p>This should not be a block quote: 2
-&gt; 1.</p>
-
-<p>And a following paragraph.</p>
-
-<hr/>
-
-<h1 id="code-blocks">Code Blocks</h1>
-
-<p>Code:</p>
-
-<pre><code>---- (should be four hyphens)
-
-sub status {
-    print &quot;working&quot;;
-}
-
-this code block is indented by one tab</code></pre>
-
-<p>And:</p>
-
-<pre><code>    this code block is indented by two tabs
-
-These should not be escaped:  \$ \\ \&gt; \[ \{</code></pre>
-
-<hr/>
-
-<h1 id="lists">Lists</h1>
-
-<h2 id="unordered">Unordered</h2>
-
-<p>Asterisks tight:</p>
-
-<ul>
-<li>asterisk 1</li>
-<li>asterisk 2</li>
-<li>asterisk 3</li>
-</ul>
-
-<p>Asterisks loose:</p>
-
-<ul>
-<li><p>asterisk 1</p></li>
-<li><p>asterisk 2</p></li>
-<li><p>asterisk 3</p></li>
-</ul>
-
-<p>Pluses tight:</p>
-
-<ul>
-<li>Plus 1</li>
-<li>Plus 2</li>
-<li>Plus 3</li>
-</ul>
-
-<p>Pluses loose:</p>
-
-<ul>
-<li><p>Plus 1</p></li>
-<li><p>Plus 2</p></li>
-<li><p>Plus 3</p></li>
-</ul>
-
-<p>Minuses tight:</p>
-
-<ul>
-<li>Minus 1</li>
-<li>Minus 2</li>
-<li>Minus 3</li>
-</ul>
-
-<p>Minuses loose:</p>
-
-<ul>
-<li><p>Minus 1</p></li>
-<li><p>Minus 2</p></li>
-<li><p>Minus 3</p></li>
-</ul>
-
-<h2 id="ordered">Ordered</h2>
-
-<p>Tight:</p>
-
-<ol>
-<li>First</li>
-<li>Second</li>
-<li>Third</li>
-</ol>
-
-<p>and:</p>
-
-<ol>
-<li>One</li>
-<li>Two</li>
-<li>Three</li>
-</ol>
-
-<p>Loose using tabs:</p>
-
-<ol>
-<li><p>First</p></li>
-<li><p>Second</p></li>
-<li><p>Third</p></li>
-</ol>
-
-<p>and using spaces:</p>
-
-<ol>
-<li><p>One</p></li>
-<li><p>Two</p></li>
-<li><p>Three</p></li>
-</ol>
-
-<p>Multiple paragraphs:</p>
-
-<ol>
-<li><p>Item 1, graf one.</p>
-
-<p>Item 1. graf two. The quick brown fox jumped over the lazy dog’s
-back.</p></li>
-<li><p>Item 2.</p></li>
-<li><p>Item 3.</p></li>
-</ol>
-
-<h2 id="nested">Nested</h2>
-
-<ul>
-<li>Tab
-
-<ul>
-<li>Tab
-
-<ul>
-<li>Tab</li>
-</ul></li>
-</ul></li>
-</ul>
-
-<p>Here’s another:</p>
-
-<ol>
-<li>First</li>
-<li>Second:
-
-<ul>
-<li>Fee</li>
-<li>Fie</li>
-<li>Foe</li>
-</ul></li>
-<li>Third</li>
-</ol>
-
-<p>Same thing but with paragraphs:</p>
-
-<ol>
-<li><p>First</p></li>
-<li><p>Second:</p>
-
-<ul>
-<li>Fee</li>
-<li>Fie</li>
-<li>Foe</li>
-</ul></li>
-<li><p>Third</p></li>
-</ol>
-
-<h2 id="tabs-and-spaces">Tabs and spaces</h2>
-
-<ul>
-<li><p>this is a list item
-indented with tabs</p></li>
-<li><p>this is a list item
-indented with spaces</p>
-
-<ul>
-<li><p>this is an example list item
-indented with tabs</p></li>
-<li><p>this is an example list item
-indented with spaces</p></li>
-</ul></li>
-</ul>
-
-<h2 id="fancy-list-markers">Fancy list markers</h2>
-
-<ol>
-<li>begins with 2</li>
-<li><p>and now 3</p>
-
-<p>with a continuation</p>
-
-<ol>
-<li>sublist with roman numerals,
-starting with 4</li>
-<li>more items
-
-<ol>
-<li>a subsublist</li>
-<li>a subsublist</li>
-</ol></li>
-</ol></li>
-</ol>
-
-<p>Nesting:</p>
-
-<ol>
-<li>Upper Alpha
-
-<ol>
-<li>Upper Roman.
-
-<ol>
-<li>Decimal start with 6
-
-<ol>
-<li>Lower alpha with paren</li>
-</ol></li>
-</ol></li>
-</ol></li>
-</ol>
-
-<p>Autonumbering:</p>
-
-<ol>
-<li>Autonumber.</li>
-<li>More.
-
-<ol>
-<li>Nested.</li>
-</ol></li>
-</ol>
-
-<p>Should not be a list item:</p>
-
-<p>M.A. 2007</p>
-
-<p>B. Williams</p>
-
-<hr/>
-
-<h1 id="definition-lists">Definition Lists</h1>
-
-<p>Tight using spaces:</p>
-
-<dl>
-<dt>apple</dt>
-<dd>red fruit</dd>
-<dt>orange</dt>
-<dd>orange fruit</dd>
-<dt>banana</dt>
-<dd>yellow fruit</dd>
-</dl>
-
-<p>Tight using tabs:</p>
-
-<dl>
-<dt>apple</dt>
-<dd>red fruit</dd>
-<dt>orange</dt>
-<dd>orange fruit</dd>
-<dt>banana</dt>
-<dd>yellow fruit</dd>
-</dl>
-
-<p>Loose:</p>
-
-<dl>
-<dt>apple</dt>
-<dd><p>red fruit</p></dd>
-<dt>orange</dt>
-<dd><p>orange fruit</p></dd>
-<dt>banana</dt>
-<dd><p>yellow fruit</p></dd>
-</dl>
-
-<p>Multiple blocks with italics:</p>
-
-<dl>
-<dt><em>apple</em></dt>
-<dd><p>red fruit</p>
-
-<p>contains seeds,
-crisp, pleasant to taste</p></dd>
-<dt><em>orange</em></dt>
-<dd><p>orange fruit</p>
-
-<pre><code>{ orange code block }</code></pre>
-
-<blockquote>
-<p>orange block quote</p>
-</blockquote></dd>
-</dl>
-
-<p>Multiple definitions, tight:</p>
-
-<dl>
-<dt>apple</dt>
-<dd>red fruit</dd>
-<dd>computer</dd>
-<dt>orange</dt>
-<dd>orange fruit</dd>
-<dd>bank</dd>
-</dl>
-
-<p>Multiple definitions, loose:</p>
-
-<dl>
-<dt>apple</dt>
-<dd><p>red fruit</p></dd>
-<dd><p>computer</p></dd>
-<dt>orange</dt>
-<dd><p>orange fruit</p></dd>
-<dd><p>bank</p></dd>
-</dl>
-
-<p>Blank line after term, indented marker, alternate markers:</p>
-
-<dl>
-<dt>apple</dt>
-<dd><p>red fruit</p></dd>
-<dd><p>computer</p></dd>
-<dt>orange</dt>
-<dd><p>orange fruit</p>
-
-<ol>
-<li>sublist</li>
-<li>sublist</li>
-</ol></dd>
-</dl>
-
-<h1 id="html-blocks">HTML Blocks</h1>
-
-<p>Simple block on one line:</p>
-
-<div>
-foo</div>
-
-<p>And nested without indentation:</p>
-
-<div>
-<div>
-<div>
-<p>foo</p></div></div>
-
-<div>
-bar</div></div>
-
-<p>Interpreted markdown in a table:</p>
-
-<table>
-
-<tr>
-
-<td>
-
-This is <em>emphasized</em>
-
-</td>
-
-<td>
-
-And this is <strong>strong</strong>
-
-</td>
-
-</tr>
-
-</table>
-
-<script type="text/javascript">document.write('This *should not* be interpreted as markdown');</script>
-
-<p>Here’s a simple block:</p>
-
-<div>
-<p>foo</p></div>
-
-<p>This should be a code block, though:</p>
-
-<pre><code>&lt;div&gt;
-    foo
-&lt;/div&gt;</code></pre>
-
-<p>As should this:</p>
-
-<pre><code>&lt;div&gt;foo&lt;/div&gt;</code></pre>
-
-<p>Now, nested:</p>
-
-<div>
-<div>
-<div>
-foo</div></div></div>
-
-<p>This should just be an HTML comment:</p>
-
-<!-- Comment -->
-
-<p>Multiline:</p>
-
-<!--
-Blah
-Blah
--->
-
-<!--
-    This is another comment.
--->
-
-<p>Code block:</p>
-
-<pre><code>&lt;!-- Comment --&gt;</code></pre>
-
-<p>Just plain comment, with trailing spaces on the line:</p>
-
-<!-- foo -->
-
-<p>Code:</p>
-
-<pre><code>&lt;hr /&gt;</code></pre>
-
-<p>Hr’s:</p>
-
-<hr>
-
-<hr />
-
-<hr />
-
-<hr>
-
-<hr />
-
-<hr />
-
-<hr class="foo" id="bar" />
-
-<hr class="foo" id="bar" />
-
-<hr class="foo" id="bar">
-
-<hr/>
-
-<h1 id="inline-markup">Inline Markup</h1>
-
-<p>This is <em>emphasized</em>, and so <em>is this</em>.</p>
-
-<p>This is <strong>strong</strong>, and so <strong>is this</strong>.</p>
-
-<p>An <em><a href='/url' title=''>emphasized link</a></em>.</p>
-
-<p><strong><em>This is strong and em.</em></strong></p>
-
-<p>So is <strong><em>this</em></strong> word.</p>
-
-<p><strong><em>This is strong and em.</em></strong></p>
-
-<p>So is <strong><em>this</em></strong> word.</p>
-
-<p>This is code: <code>&gt;</code>, <code>$</code>, <code>\</code>, <code>\$</code>, <code>&lt;html&gt;</code>.</p>
-
-<p><del>This is <em>strikeout</em>.</del></p>
-
-<p>Superscripts: a<sup>bc</sup>d a<sup><em>hello</em></sup> a<sup>hello there</sup>.</p>
-
-<p>Subscripts: H<sub>2</sub>O, H<sub>23</sub>O, H<sub>many of them</sub>O.</p>
-
-<p>These should not be superscripts or subscripts,
-because of the unescaped spaces: a^b c^d, a~b c~d.</p>
-
-<hr/>
-
-<h1 id="smart-quotes-ellipses-dashes">Smart quotes, ellipses, dashes</h1>
-
-<p> said the spider. </p>
-
-<p>, , and  are letters.</p>
-
-<p>  and  are names of trees.
-So is </p>
-
-<p> Were you alive in the
-70’s?</p>
-
-<p>Here is some quoted  and a .</p>
-
-<p>Some dashes: one—two — three—four — five.</p>
-
-<p>Dashes between numbers: 5–7, 255–66, 1987–1999.</p>
-
-<p>Ellipses…and…and….</p>
-
-<hr/>
-
-<h1 id="latex">LaTeX</h1>
-
-<ul>
-<li></li>
-<li>\(2+2=4\)</li>
-<li>\(x \in y\)</li>
-<li>\(\alpha \wedge \omega\)</li>
-<li>\(223\)</li>
-<li>\(p\)-Tree</li>
-<li>Here’s some display math:
-\[\frac{d}{dx}f(x)=\lim_{h\to 0}\frac{f(x+h)-f(x)}{h}\]</li>
-<li>Here’s one that has a line break in it: \(\alpha + \omega \times x^2\).</li>
-</ul>
-
-<p>These shouldn’t be math:</p>
-
-<ul>
-<li>To get the famous equation, write <code>$e = mc^2$</code>.</li>
-<li>$22,000 is a <em>lot</em> of money. So is $34,000.
-(It worked if  is emphasized.)</li>
-<li>Shoes ($20) and socks ($5).</li>
-<li>Escaped <code>$</code>: $73 <em>this should be emphasized</em> 23$.</li>
-</ul>
-
-<p>Here’s a LaTeX table:</p>
-
-
-
-<hr/>
-
-<h1 id="special-characters">Special Characters</h1>
-
-<p>Here is some unicode:</p>
-
-<ul>
-<li>I hat: Î</li>
-<li>o umlaut: ö</li>
-<li>section: §</li>
-<li>set membership: ∈</li>
-<li>copyright: ©</li>
-</ul>
-
-<p>AT&amp;T has an ampersand in their name.</p>
-
-<p>AT&amp;T is another way to write it.</p>
-
-<p>This &amp; that.</p>
-
-<p>4 &lt; 5.</p>
-
-<p>6 &gt; 5.</p>
-
-<p>Backslash: \</p>
-
-<p>Backtick: `</p>
-
-<p>Asterisk: *</p>
-
-<p>Underscore: _</p>
-
-<p>Left brace: {</p>
-
-<p>Right brace: }</p>
-
-<p>Left bracket: [</p>
-
-<p>Right bracket: ]</p>
-
-<p>Left paren: (</p>
-
-<p>Right paren: )</p>
-
-<p>Greater-than: &gt;</p>
-
-<p>Hash: #</p>
-
-<p>Period: .</p>
-
-<p>Bang: !</p>
-
-<p>Plus: +</p>
-
-<p>Minus: -</p>
-
-<hr/>
-
-<h1 id="links">Links</h1>
-
-<h2 id="explicit">Explicit</h2>
-
-<p>Just a <a href='/url/' title=''>URL</a>.</p>
-
-<p><a href='/url/' title='title'>URL and title</a>.</p>
-
-<p><a href='/url/' title='title preceded by two spaces'>URL and title</a>.</p>
-
-<p><a href='/url/' title='title preceded by a tab'>URL and title</a>.</p>
-
-<p><a href='/url/' title='title with &quot;quotes&quot; in it'>URL and title</a></p>
-
-<p><a href='/url/' title='title with single quotes'>URL and title</a></p>
-
-<p><a href='/url/with_underscore' title=''>with_underscore</a></p>
-
-<p><a href='mailto:nobody@nowhere.net' title=''>Email link</a></p>
-
-<p><a href='' title=''>Empty</a>.</p>
-
-<h2 id="reference">Reference</h2>
-
-<p>Foo <a href='/url/' title=''>bar</a>.</p>
-
-<p>With <a href='/url/' title=''>embedded [brackets]</a>.</p>
-
-<p><a href='/url/' title=''>b</a> by itself should be a link.</p>
-
-<p>Indented <a href='/url' title=''>once</a>.</p>
-
-<p>Indented <a href='/url' title=''>twice</a>.</p>
-
-<p>Indented <a href='/url' title=''>thrice</a>.</p>
-
-<p>This should [not][] be a link.</p>
-
-<pre><code>[not]: /url</code></pre>
-
-<p>Foo <a href='/url/' title='Title with &quot;quotes&quot; inside'>bar</a>.</p>
-
-<p>Foo <a href='/url/' title='Title with &quot;quote&quot; inside'>biz</a>.</p>
-
-<h2 id="with-ampersands">With ampersands</h2>
-
-<p>Here’s a <a href='http://example.com/?foo=1&amp;bar=2' title=''>link with an ampersand in the URL</a>.</p>
-
-<p>Here’s a link with an amersand in the link text: <a href='http://att.com/' title='AT&amp;T'>AT&amp;T</a>.</p>
-
-<p>Here’s an <a href='/script?foo=1&amp;bar=2' title=''>inline link</a>.</p>
-
-<p>Here’s an <a href='/script?foo=1&amp;bar=2' title=''>inline link in pointy braces</a>.</p>
-
-<h2 id="autolinks">Autolinks</h2>
-
-<p>With an ampersand: <a href='http://example.com/?foo=1&amp;bar=2' title=''>http://example.com/?foo=1&amp;bar=2</a></p>
-
-<ul>
-<li>In a list?</li>
-<li><a href='http://example.com/' title=''>http://example.com/</a></li>
-<li>It should.</li>
-</ul>
-
-<p>An e-mail address: <a href='mailto:nobody@nowhere.net' title=''>nobody@nowhere.net</a></p>
-
-<blockquote>
-<p>Blockquoted: <a href='http://example.com/' title=''>http://example.com/</a></p>
-</blockquote>
-
-<p>Auto-links should not occur here: <code>&lt;http://example.com/&gt;</code></p>
-
-<pre><code>or here: &lt;http://example.com/&gt;</code></pre>
-
-<hr/>
-
-<h1 id="images">Images</h1>
-
-<p>From  by Georges Melies (1902):</p>
-
-<div class="figure">
-<img src="lalune.jpg" title="fig:Voyage dans la Lune"/>
-<p class="caption">lalune</p>
-</div>
-
-<p>Here is a movie <img src='movie.jpg' title=''/> icon.</p>
-
-<hr/>
-
-<h1 id="footnotes">Footnotes</h1>
-
-<p>Here is a footnote reference,<a id="fnref1" href="#fn1"><sup>1</sup></a> and another.<a id="fnref2" href="#fn2"><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 id="fnref3" href="#fn3"><sup>3</sup></a></p>
-
-<blockquote>
-<p>Notes can go in quotes.<a id="fnref4" href="#fn4"><sup>4</sup></a></p>
-</blockquote>
-
-<ol>
-<li>And in list items.<a id="fnref5" href="#fn5"><sup>5</sup></a></li>
-</ol>
-
-<p>This paragraph should not be part of the note, as it is not indented.</p>
-<ol class="footnotes">
-<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">&#8617;</a></p></li>
-<li id="fn2"><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">&#8617;</a></p></li>
-<li id="fn3"><p>This
-is <em>easier</em> to type. Inline notes may contain
-<a href='http://google.com' title=''>links</a> and <code>]</code> verbatim characters,
-as well as [bracketed text]. <a href="#fnref3">&#8617;</a></p></li>
-<li id="fn4"><p>In quote. <a href="#fnref4">&#8617;</a></p></li>
-<li id="fn5"><p>In list. <a href="#fnref5">&#8617;</a></p></li>
-</ol>
-
diff --git a/test/writer.djot b/test/writer.djot
new file mode 100644
--- /dev/null
+++ b/test/writer.djot
@@ -0,0 +1,749 @@
+# Pandoc Test Suite
+
+John MacFarlane
+Anonymous
+
+July 17, 2006
+
+This is a set of tests for pandoc. Most of them are adapted from John Gruber's
+markdown test suite.
+
+* * * *
+
+{#headers}
+# Headers
+
+{#level-2-with-an-embedded-link}
+## Level 2 with an [embedded link](/url)
+
+{#level-3-with-emphasis}
+### Level 3 with _emphasis_
+
+{#level-4}
+#### Level 4
+
+{#level-5}
+##### Level 5
+
+{#level-1}
+# Level 1
+
+{#level-2-with-emphasis}
+## Level 2 with _emphasis_
+
+{#level-3}
+### Level 3
+
+with no blank line
+
+{#level-2}
+## Level 2
+
+with no blank line
+
+* * * *
+
+{#paragraphs}
+# Paragraphs
+
+Here's a regular paragraph.
+
+In Markdown 1.0.0 and earlier. Version 8. This line turns into a list item.
+Because a hard-wrapped line in the middle of a paragraph looked like a list
+item.
+
+Here's one with a bullet. \* criminey.
+
+There should be a hard line break\
+here.
+
+* * * *
+
+{#block-quotes}
+# Block Quotes
+
+E-mail style:
+
+> This is a block quote. It is pretty short.
+
+> Code in a block quote:
+>
+> ```
+> sub status {
+>     print "working";
+> }
+> ```
+>
+> A list:
+>
+> 1. item one
+> 2. item two
+>
+> Nested block quotes:
+>
+> > nested
+>
+> > nested
+
+This should not be a block quote: 2 \> 1.
+
+And a following paragraph.
+
+* * * *
+
+{#code-blocks}
+# Code Blocks
+
+Code:
+
+```
+---- (should be four hyphens)
+
+sub status {
+    print "working";
+}
+
+this code block is indented by one tab
+```
+
+And:
+
+```
+    this code block is indented by two tabs
+
+These should not be escaped:  \$ \\ \> \[ \{
+```
+
+* * * *
+
+{#lists}
+# Lists
+
+{#unordered}
+## Unordered
+
+Asterisks tight:
+
+- asterisk 1
+- asterisk 2
+- asterisk 3
+
+Asterisks loose:
+
+- asterisk 1
+
+- asterisk 2
+
+- asterisk 3
+
+Pluses tight:
+
+- Plus 1
+- Plus 2
+- Plus 3
+
+Pluses loose:
+
+- Plus 1
+
+- Plus 2
+
+- Plus 3
+
+Minuses tight:
+
+- Minus 1
+- Minus 2
+- Minus 3
+
+Minuses loose:
+
+- Minus 1
+
+- Minus 2
+
+- Minus 3
+
+{#ordered}
+## Ordered
+
+Tight:
+
+1. First
+2. Second
+3. Third
+
+and:
+
+1. One
+2. Two
+3. Three
+
+Loose using tabs:
+
+1. First
+
+2. Second
+
+3. Third
+
+and using spaces:
+
+1. One
+
+2. Two
+
+3. Three
+
+Multiple paragraphs:
+
+1. Item 1, graf one.
+
+   Item 1. graf two. The quick brown fox jumped over the lazy dog's back.
+
+2. Item 2.
+
+3. Item 3.
+
+{#nested}
+## Nested
+
+- Tab
+
+  - Tab
+
+    - Tab
+
+Here's another:
+
+1. First
+2. Second:
+
+   - Fee
+   - Fie
+   - Foe
+3. Third
+
+Same thing but with paragraphs:
+
+1. First
+
+2. Second:
+
+   - Fee
+   - Fie
+   - Foe
+
+3. Third
+
+{#tabs-and-spaces}
+## Tabs and spaces
+
+- this is a list item indented with tabs
+
+- this is a list item indented with spaces
+
+  - this is an example list item indented with tabs
+
+  - this is an example list item indented with spaces
+
+{#fancy-list-markers}
+## Fancy list markers
+
+(2) begins with 2
+
+(3) and now 3
+
+    with a continuation
+
+    iv. sublist with roman numerals, starting with 4
+    v. more items
+
+       (A) a subsublist
+       (B) a subsublist
+
+Nesting:
+
+A. Upper Alpha
+
+   I. Upper Roman.
+
+      (6) Decimal start with 6
+
+          c) Lower alpha with paren
+
+Autonumbering:
+
+1. Autonumber.
+2. More.
+
+   1. Nested.
+
+Should not be a list item:
+
+M.A. 2007
+
+B. Williams
+
+* * * *
+
+{#definition-lists}
+# Definition Lists
+
+Tight using spaces:
+
+: apple
+
+  red fruit
+: orange
+
+  orange fruit
+: banana
+
+  yellow fruit
+
+Tight using tabs:
+
+: apple
+
+  red fruit
+: orange
+
+  orange fruit
+: banana
+
+  yellow fruit
+
+Loose:
+
+: apple
+
+  red fruit
+
+: orange
+
+  orange fruit
+
+: banana
+
+  yellow fruit
+
+Multiple blocks with italics:
+
+: _apple_
+
+  red fruit
+
+  contains seeds, crisp, pleasant to taste
+
+: _orange_
+
+  orange fruit
+
+  ```
+  { orange code block }
+  ```
+
+  > orange block quote
+
+Multiple definitions, tight:
+
+: apple
+
+  red fruit
+
+  computer
+: orange
+
+  orange fruit
+
+  bank
+
+Multiple definitions, loose:
+
+: apple
+
+  red fruit
+
+  computer
+
+: orange
+
+  orange fruit
+
+  bank
+
+Blank line after term, indented marker, alternate markers:
+
+: apple
+
+  red fruit
+
+  computer
+
+: orange
+
+  orange fruit
+
+  1. sublist
+  2. sublist
+
+{#html-blocks}
+# HTML Blocks
+
+Simple block on one line:
+
+:::
+foo
+
+:::
+
+And nested without indentation:
+
+::::::
+::::
+:::
+foo
+
+:::
+
+::::
+
+:::
+bar
+
+:::
+
+::::::
+
+Interpreted markdown in a table:
+
+This is _emphasized_
+
+And this is *strong*
+
+Here's a simple block:
+
+:::
+foo
+
+:::
+
+This should be a code block, though:
+
+```
+<div>
+    foo
+</div>
+```
+
+As should this:
+
+```
+<div>foo</div>
+```
+
+Now, nested:
+
+:::::
+::::
+:::
+foo
+
+:::
+
+::::
+
+:::::
+
+This should just be an HTML comment:
+
+Multiline:
+
+Code block:
+
+```
+<!-- Comment -->
+```
+
+Just plain comment, with trailing spaces on the line:
+
+Code:
+
+```
+<hr />
+```
+
+Hr's:
+
+* * * *
+
+{#inline-markup}
+# Inline Markup
+
+This is _emphasized_, and so _is this_.
+
+This is *strong*, and so *is this*.
+
+An _[emphasized link](/url)_.
+
+*_This is strong and em._*
+
+So is *_this_* word.
+
+*_This is strong and em._*
+
+So is *_this_* word.
+
+This is code: `>`, `$`, `\`, `\$`, `<html>`.
+
+{-This is _strikeout_.-}
+
+Superscripts: a^bc^d a^_hello_^ a^hello there^.
+
+Subscripts: H~2~O, H~23~O, H~many of them~O.
+
+These should not be superscripts or subscripts, because of the unescaped spaces:
+a\^b c\^d, a\~b c\~d.
+
+* * * *
+
+{#smart-quotes-ellipses-dashes}
+# Smart quotes, ellipses, dashes
+
+"Hello," said the spider. "'Shelob' is my name."
+
+'A', 'B', and 'C' are letters.
+
+'Oak,' 'elm,' and 'beech' are names of trees. So is 'pine.'
+
+'He said, "I want to go."' Were you alive in the 70's?
+
+Here is some quoted '`code`' and a "[quoted
+link](http://example.com/?foo=1&bar=2)".
+
+Some dashes: one---two --- three---four --- five.
+
+Dashes between numbers: 5--7, 255--66, 1987--1999.
+
+Ellipses...and...and....
+
+* * * *
+
+{#latex}
+# LaTeX
+
+-
+- $`2+2=4`
+- $`x \in y`
+- $`\alpha \wedge \omega`
+- $`223`
+- $`p`-Tree
+- Here's some display math:
+  $$`\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: $`\alpha + \omega \times x^2`.
+
+These shouldn't be math:
+
+- To get the famous equation, write `$e = mc^2$`.
+- $22,000 is a _lot_ of money. So is $34,000. (It worked if "lot" is
+  emphasized.)
+- Shoes ($20) and socks ($5).
+- Escaped `$`\: $73 _this should be emphasized_ 23$.
+
+Here's a LaTeX table:
+
+* * * *
+
+{#special-characters}
+# Special Characters
+
+Here is some unicode:
+
+- I hat: Î
+- o umlaut: ö
+- section: §
+- set membership: ∈
+- copyright: ©
+
+AT&T has an ampersand in their name.
+
+AT&T is another way to write it.
+
+This & that.
+
+4 \< 5.
+
+6 \> 5.
+
+Backslash: \\
+
+Backtick: \`
+
+Asterisk: \*
+
+Underscore: \_
+
+Left brace: \{
+
+Right brace: \}
+
+Left bracket: \[
+
+Right bracket: \]
+
+Left paren: (
+
+Right paren: )
+
+Greater-than: \>
+
+Hash: #
+
+Period: .
+
+Bang: \!
+
+Plus: +
+
+Minus: -
+
+* * * *
+
+{#links}
+# Links
+
+{#explicit}
+## Explicit
+
+Just a [URL](/url/).
+
+[URL and title](/url/){title="title"}.
+
+[URL and title](/url/){title="title preceded by two spaces"}.
+
+[URL and title](/url/){title="title preceded by a tab"}.
+
+[URL and title](/url/){title="title with \"quotes\" in it"}
+
+[URL and title](/url/){title="title with single quotes"}
+
+[with\_underscore](/url/with_underscore)
+
+[Email link](mailto:nobody@nowhere.net)
+
+[Empty]().
+
+{#reference}
+## Reference
+
+Foo [bar](/url/).
+
+With [embedded \[brackets\]](/url/).
+
+[b](/url/) by itself should be a link.
+
+Indented [once](/url).
+
+Indented [twice](/url).
+
+Indented [thrice](/url).
+
+This should \[not\]\[\] be a link.
+
+```
+[not]: /url
+```
+
+Foo [bar](/url/){title="Title with \"quotes\" inside"}.
+
+Foo [biz](/url/){title="Title with \"quote\" inside"}.
+
+{#with-ampersands}
+## With ampersands
+
+Here's a [link with an ampersand in the URL](http://example.com/?foo=1&bar=2).
+
+Here's a link with an amersand in the link text:
+[AT&T](http://att.com/){title="AT&T"}.
+
+Here's an [inline link](/script?foo=1&bar=2).
+
+Here's an [inline link in pointy braces](/script?foo=1&bar=2).
+
+{#autolinks}
+## Autolinks
+
+With an ampersand: <http://example.com/?foo=1&bar=2>
+
+- In a list?
+- <http://example.com/>
+- It should.
+
+An e-mail address: <nobody@nowhere.net>
+
+> Blockquoted: <http://example.com/>
+
+Auto-links should not occur here: `<http://example.com/>`
+
+```
+or here: <http://example.com/>
+```
+
+* * * *
+
+{#images}
+# Images
+
+From "Voyage dans la Lune" by Georges Melies (1902):
+
+::::
+![lalune](lalune.jpg){title="Voyage dans la Lune"}
+
+{.caption}
+:::
+lalune
+
+:::
+
+::::
+
+Here is a movie ![movie](movie.jpg) icon.
+
+* * * *
+
+{#footnotes}
+# Footnotes
+
+Here is a footnote reference,[^1] and another.[^2] This should _not_ be a
+footnote reference, because it contains a space.\[\^my note\] Here is an inline
+note.[^3]
+
+> Notes can go in quotes.[^4]
+
+1. And in list items.[^5]
+
+This paragraph should not be part of the note, as it is not indented.
+
+[^1]: Here is the footnote. It can go anywhere after the footnote reference. It
+    need not be placed at the end of the document.
+
+[^2]: Here's the long note. This one contains multiple blocks.
+
+    Subsequent blocks are indented to show that they belong to the footnote (as
+    with list items).
+
+    ```
+      { <code> }
+    ```
+
+    If you want, you can indent every line, but you can also be lazy and just
+    indent the first line of each block.
+
+[^3]: This is _easier_ to type. Inline notes may contain
+    [links](http://google.com) and `]` verbatim characters, as well as
+    \[bracketed text\].
+
+[^4]: In quote.
+
+[^5]: In list.
diff --git a/test/writer.docbook4 b/test/writer.docbook4
--- a/test/writer.docbook4
+++ b/test/writer.docbook4
@@ -6,1411 +6,1418 @@
     <title>Pandoc Test Suite</title>
     <authorgroup>
       <author>
-        <firstname>John</firstname>
-        <surname>MacFarlane</surname>
-      </author>
-      <author>
-        <firstname></firstname>
-        <surname>Anonymous</surname>
-      </author>
-    </authorgroup>
-    <date>July 17, 2006</date>
-  </articleinfo>
-<para>
-  This is a set of tests for pandoc. Most of them are adapted from John
-  Gruber’s markdown test suite.
-</para>
-<sect1 id="headers">
-  <title>Headers</title>
-  <sect2 id="level-2-with-an-embedded-link">
-    <title>Level 2 with an <ulink url="/url">embedded link</ulink></title>
-    <sect3 id="level-3-with-emphasis">
-      <title>Level 3 with <emphasis>emphasis</emphasis></title>
-      <sect4 id="level-4">
-        <title>Level 4</title>
-        <sect5 id="level-5">
-          <title>Level 5</title>
-          <para>
-          </para>
-        </sect5>
-      </sect4>
-    </sect3>
-  </sect2>
-</sect1>
-<sect1 id="level-1">
-  <title>Level 1</title>
-  <sect2 id="level-2-with-emphasis">
-    <title>Level 2 with <emphasis>emphasis</emphasis></title>
-    <sect3 id="level-3">
-      <title>Level 3</title>
-      <para>
-        with no blank line
-      </para>
-    </sect3>
-  </sect2>
-  <sect2 id="level-2">
-    <title>Level 2</title>
-    <para>
-      with no blank line
-    </para>
-  </sect2>
-</sect1>
-<sect1 id="paragraphs">
-  <title>Paragraphs</title>
-  <para>
-    Here’s a regular paragraph.
-  </para>
-  <para>
-    In Markdown 1.0.0 and earlier. Version 8. This line turns into a list
-    item. Because a hard-wrapped line in the middle of a paragraph looked like
-    a list item.
-  </para>
-  <para>
-    Here’s one with a bullet. * criminey.
-  </para>
-<literallayout>There should be a hard line break
-here.</literallayout>
-</sect1>
-<sect1 id="block-quotes">
-  <title>Block Quotes</title>
-  <para>
-    E-mail style:
-  </para>
-  <blockquote>
-    <para>
-      This is a block quote. It is pretty short.
-    </para>
-  </blockquote>
-  <blockquote>
-    <para>
-      Code in a block quote:
-    </para>
-    <programlisting>
-sub status {
-    print &quot;working&quot;;
-}
-</programlisting>
-    <para>
-      A list:
-    </para>
-    <orderedlist numeration="arabic" spacing="compact">
-      <listitem>
-        <para>
-          item one
-        </para>
-      </listitem>
-      <listitem>
-        <para>
-          item two
-        </para>
-      </listitem>
-    </orderedlist>
-    <para>
-      Nested block quotes:
-    </para>
-    <blockquote>
-      <para>
-        nested
-      </para>
-    </blockquote>
-    <blockquote>
-      <para>
-        nested
-      </para>
-    </blockquote>
-  </blockquote>
-  <para>
-    This should not be a block quote: 2 &gt; 1.
-  </para>
-  <para>
-    And a following paragraph.
-  </para>
-</sect1>
-<sect1 id="code-blocks">
-  <title>Code Blocks</title>
-  <para>
-    Code:
-  </para>
-  <programlisting>
----- (should be four hyphens)
-
-sub status {
-    print &quot;working&quot;;
-}
-
-this code block is indented by one tab
-</programlisting>
-  <para>
-    And:
-  </para>
-  <programlisting>
-    this code block is indented by two tabs
-
-These should not be escaped:  \$ \\ \&gt; \[ \{
-</programlisting>
-</sect1>
-<sect1 id="lists">
-  <title>Lists</title>
-  <sect2 id="unordered">
-    <title>Unordered</title>
-    <para>
-      Asterisks tight:
-    </para>
-    <itemizedlist spacing="compact">
-      <listitem>
-        <para>
-          asterisk 1
-        </para>
-      </listitem>
-      <listitem>
-        <para>
-          asterisk 2
-        </para>
-      </listitem>
-      <listitem>
-        <para>
-          asterisk 3
-        </para>
-      </listitem>
-    </itemizedlist>
-    <para>
-      Asterisks loose:
-    </para>
-    <itemizedlist>
-      <listitem>
-        <para>
-          asterisk 1
-        </para>
-      </listitem>
-      <listitem>
-        <para>
-          asterisk 2
-        </para>
-      </listitem>
-      <listitem>
-        <para>
-          asterisk 3
-        </para>
-      </listitem>
-    </itemizedlist>
-    <para>
-      Pluses tight:
-    </para>
-    <itemizedlist spacing="compact">
-      <listitem>
-        <para>
-          Plus 1
-        </para>
-      </listitem>
-      <listitem>
-        <para>
-          Plus 2
-        </para>
-      </listitem>
-      <listitem>
-        <para>
-          Plus 3
-        </para>
-      </listitem>
-    </itemizedlist>
-    <para>
-      Pluses loose:
-    </para>
-    <itemizedlist>
-      <listitem>
-        <para>
-          Plus 1
-        </para>
-      </listitem>
-      <listitem>
-        <para>
-          Plus 2
-        </para>
-      </listitem>
-      <listitem>
-        <para>
-          Plus 3
-        </para>
-      </listitem>
-    </itemizedlist>
-    <para>
-      Minuses tight:
-    </para>
-    <itemizedlist spacing="compact">
-      <listitem>
-        <para>
-          Minus 1
-        </para>
-      </listitem>
-      <listitem>
-        <para>
-          Minus 2
-        </para>
-      </listitem>
-      <listitem>
-        <para>
-          Minus 3
-        </para>
-      </listitem>
-    </itemizedlist>
-    <para>
-      Minuses loose:
-    </para>
-    <itemizedlist>
-      <listitem>
-        <para>
-          Minus 1
-        </para>
-      </listitem>
-      <listitem>
-        <para>
-          Minus 2
-        </para>
-      </listitem>
-      <listitem>
-        <para>
-          Minus 3
-        </para>
-      </listitem>
-    </itemizedlist>
-  </sect2>
-  <sect2 id="ordered">
-    <title>Ordered</title>
-    <para>
-      Tight:
-    </para>
-    <orderedlist numeration="arabic" spacing="compact">
-      <listitem>
-        <para>
-          First
-        </para>
-      </listitem>
-      <listitem>
-        <para>
-          Second
-        </para>
-      </listitem>
-      <listitem>
-        <para>
-          Third
-        </para>
-      </listitem>
-    </orderedlist>
-    <para>
-      and:
-    </para>
-    <orderedlist numeration="arabic" spacing="compact">
-      <listitem>
-        <para>
-          One
-        </para>
-      </listitem>
-      <listitem>
-        <para>
-          Two
-        </para>
-      </listitem>
-      <listitem>
-        <para>
-          Three
-        </para>
-      </listitem>
-    </orderedlist>
-    <para>
-      Loose using tabs:
-    </para>
-    <orderedlist numeration="arabic">
-      <listitem>
-        <para>
-          First
-        </para>
-      </listitem>
-      <listitem>
-        <para>
-          Second
-        </para>
-      </listitem>
-      <listitem>
-        <para>
-          Third
-        </para>
-      </listitem>
-    </orderedlist>
-    <para>
-      and using spaces:
-    </para>
-    <orderedlist numeration="arabic">
-      <listitem>
-        <para>
-          One
-        </para>
-      </listitem>
-      <listitem>
-        <para>
-          Two
-        </para>
-      </listitem>
-      <listitem>
-        <para>
-          Three
-        </para>
-      </listitem>
-    </orderedlist>
-    <para>
-      Multiple paragraphs:
-    </para>
-    <orderedlist numeration="arabic">
-      <listitem>
-        <para>
-          Item 1, graf one.
-        </para>
-        <para>
-          Item 1. graf two. The quick brown fox jumped over the lazy dog’s
-          back.
-        </para>
-      </listitem>
-      <listitem>
-        <para>
-          Item 2.
-        </para>
-      </listitem>
-      <listitem>
-        <para>
-          Item 3.
-        </para>
-      </listitem>
-    </orderedlist>
-  </sect2>
-  <sect2 id="nested">
-    <title>Nested</title>
-    <itemizedlist spacing="compact">
-      <listitem>
-        <para>
-          Tab
-        </para>
-        <itemizedlist spacing="compact">
-          <listitem>
-            <para>
-              Tab
-            </para>
-            <itemizedlist spacing="compact">
-              <listitem>
-                <para>
-                  Tab
-                </para>
-              </listitem>
-            </itemizedlist>
-          </listitem>
-        </itemizedlist>
-      </listitem>
-    </itemizedlist>
-    <para>
-      Here’s another:
-    </para>
-    <orderedlist numeration="arabic" spacing="compact">
-      <listitem>
-        <para>
-          First
-        </para>
-      </listitem>
-      <listitem>
-        <para>
-          Second:
-        </para>
-        <itemizedlist spacing="compact">
-          <listitem>
-            <para>
-              Fee
-            </para>
-          </listitem>
-          <listitem>
-            <para>
-              Fie
-            </para>
-          </listitem>
-          <listitem>
-            <para>
-              Foe
-            </para>
-          </listitem>
-        </itemizedlist>
-      </listitem>
-      <listitem>
-        <para>
-          Third
-        </para>
-      </listitem>
-    </orderedlist>
-    <para>
-      Same thing but with paragraphs:
-    </para>
-    <orderedlist numeration="arabic">
-      <listitem>
-        <para>
-          First
-        </para>
-      </listitem>
-      <listitem>
-        <para>
-          Second:
-        </para>
-        <itemizedlist spacing="compact">
-          <listitem>
-            <para>
-              Fee
-            </para>
-          </listitem>
-          <listitem>
-            <para>
-              Fie
-            </para>
-          </listitem>
-          <listitem>
-            <para>
-              Foe
-            </para>
-          </listitem>
-        </itemizedlist>
-      </listitem>
-      <listitem>
-        <para>
-          Third
-        </para>
-      </listitem>
-    </orderedlist>
-  </sect2>
-  <sect2 id="tabs-and-spaces">
-    <title>Tabs and spaces</title>
-    <itemizedlist>
-      <listitem>
-        <para>
-          this is a list item indented with tabs
-        </para>
-      </listitem>
-      <listitem>
-        <para>
-          this is a list item indented with spaces
-        </para>
-        <itemizedlist>
-          <listitem>
-            <para>
-              this is an example list item indented with tabs
-            </para>
-          </listitem>
-          <listitem>
-            <para>
-              this is an example list item indented with spaces
-            </para>
-          </listitem>
-        </itemizedlist>
-      </listitem>
-    </itemizedlist>
-  </sect2>
-  <sect2 id="fancy-list-markers">
-    <title>Fancy list markers</title>
-    <orderedlist numeration="arabic">
-      <listitem override="2">
-        <para>
-          begins with 2
-        </para>
-      </listitem>
-      <listitem>
-        <para>
-          and now 3
-        </para>
-        <para>
-          with a continuation
-        </para>
-        <orderedlist numeration="lowerroman" spacing="compact">
-          <listitem override="4">
-            <para>
-              sublist with roman numerals, starting with 4
-            </para>
-          </listitem>
-          <listitem>
-            <para>
-              more items
-            </para>
-            <orderedlist numeration="upperalpha" spacing="compact">
-              <listitem>
-                <para>
-                  a subsublist
-                </para>
-              </listitem>
-              <listitem>
-                <para>
-                  a subsublist
-                </para>
-              </listitem>
-            </orderedlist>
-          </listitem>
-        </orderedlist>
-      </listitem>
-    </orderedlist>
-    <para>
-      Nesting:
-    </para>
-    <orderedlist numeration="upperalpha" spacing="compact">
-      <listitem>
-        <para>
-          Upper Alpha
-        </para>
-        <orderedlist numeration="upperroman" spacing="compact">
-          <listitem>
-            <para>
-              Upper Roman.
-            </para>
-            <orderedlist numeration="arabic" spacing="compact">
-              <listitem override="6">
-                <para>
-                  Decimal start with 6
-                </para>
-                <orderedlist numeration="loweralpha" spacing="compact">
-                  <listitem override="3">
-                    <para>
-                      Lower alpha with paren
-                    </para>
-                  </listitem>
-                </orderedlist>
-              </listitem>
-            </orderedlist>
-          </listitem>
-        </orderedlist>
-      </listitem>
-    </orderedlist>
-    <para>
-      Autonumbering:
-    </para>
-    <orderedlist spacing="compact">
-      <listitem>
-        <para>
-          Autonumber.
-        </para>
-      </listitem>
-      <listitem>
-        <para>
-          More.
-        </para>
-        <orderedlist spacing="compact">
-          <listitem>
-            <para>
-              Nested.
-            </para>
-          </listitem>
-        </orderedlist>
-      </listitem>
-    </orderedlist>
-    <para>
-      Should not be a list item:
-    </para>
-    <para>
-      M.A. 2007
-    </para>
-    <para>
-      B. Williams
-    </para>
-  </sect2>
-</sect1>
-<sect1 id="definition-lists">
-  <title>Definition Lists</title>
-  <para>
-    Tight using spaces:
-  </para>
-  <variablelist spacing="compact">
-    <varlistentry>
-      <term>
-        apple
-      </term>
-      <listitem>
-        <para>
-          red fruit
-        </para>
-      </listitem>
-    </varlistentry>
-    <varlistentry>
-      <term>
-        orange
-      </term>
-      <listitem>
-        <para>
-          orange fruit
-        </para>
-      </listitem>
-    </varlistentry>
-    <varlistentry>
-      <term>
-        banana
-      </term>
-      <listitem>
-        <para>
-          yellow fruit
-        </para>
-      </listitem>
-    </varlistentry>
-  </variablelist>
-  <para>
-    Tight using tabs:
-  </para>
-  <variablelist spacing="compact">
-    <varlistentry>
-      <term>
-        apple
-      </term>
-      <listitem>
-        <para>
-          red fruit
-        </para>
-      </listitem>
-    </varlistentry>
-    <varlistentry>
-      <term>
-        orange
-      </term>
-      <listitem>
-        <para>
-          orange fruit
-        </para>
-      </listitem>
-    </varlistentry>
-    <varlistentry>
-      <term>
-        banana
-      </term>
-      <listitem>
-        <para>
-          yellow fruit
-        </para>
-      </listitem>
-    </varlistentry>
-  </variablelist>
-  <para>
-    Loose:
-  </para>
-  <variablelist>
-    <varlistentry>
-      <term>
-        apple
-      </term>
-      <listitem>
-        <para>
-          red fruit
-        </para>
-      </listitem>
-    </varlistentry>
-    <varlistentry>
-      <term>
-        orange
-      </term>
-      <listitem>
-        <para>
-          orange fruit
-        </para>
-      </listitem>
-    </varlistentry>
-    <varlistentry>
-      <term>
-        banana
-      </term>
-      <listitem>
-        <para>
-          yellow fruit
-        </para>
-      </listitem>
-    </varlistentry>
-  </variablelist>
-  <para>
-    Multiple blocks with italics:
-  </para>
-  <variablelist>
-    <varlistentry>
-      <term>
-        <emphasis>apple</emphasis>
-      </term>
-      <listitem>
-        <para>
-          red fruit
-        </para>
-        <para>
-          contains seeds, crisp, pleasant to taste
-        </para>
-      </listitem>
-    </varlistentry>
-    <varlistentry>
-      <term>
-        <emphasis>orange</emphasis>
-      </term>
-      <listitem>
-        <para>
-          orange fruit
-        </para>
-        <programlisting>
-{ orange code block }
-</programlisting>
-        <blockquote>
-          <para>
-            orange block quote
-          </para>
-        </blockquote>
-      </listitem>
-    </varlistentry>
-  </variablelist>
-  <para>
-    Multiple definitions, tight:
-  </para>
-  <variablelist spacing="compact">
-    <varlistentry>
-      <term>
-        apple
-      </term>
-      <listitem>
-        <para>
-          red fruit
-        </para>
-        <para>
-          computer
-        </para>
-      </listitem>
-    </varlistentry>
-    <varlistentry>
-      <term>
-        orange
-      </term>
-      <listitem>
-        <para>
-          orange fruit
-        </para>
-        <para>
-          bank
-        </para>
-      </listitem>
-    </varlistentry>
-  </variablelist>
-  <para>
-    Multiple definitions, loose:
-  </para>
-  <variablelist>
-    <varlistentry>
-      <term>
-        apple
-      </term>
-      <listitem>
-        <para>
-          red fruit
-        </para>
-        <para>
-          computer
-        </para>
-      </listitem>
-    </varlistentry>
-    <varlistentry>
-      <term>
-        orange
-      </term>
-      <listitem>
-        <para>
-          orange fruit
-        </para>
-        <para>
-          bank
-        </para>
-      </listitem>
-    </varlistentry>
-  </variablelist>
-  <para>
-    Blank line after term, indented marker, alternate markers:
-  </para>
-  <variablelist>
-    <varlistentry>
-      <term>
-        apple
-      </term>
-      <listitem>
-        <para>
-          red fruit
-        </para>
-        <para>
-          computer
-        </para>
-      </listitem>
-    </varlistentry>
-    <varlistentry>
-      <term>
-        orange
-      </term>
-      <listitem>
-        <para>
-          orange fruit
-        </para>
-        <orderedlist numeration="arabic" spacing="compact">
-          <listitem>
-            <para>
-              sublist
-            </para>
-          </listitem>
-          <listitem>
-            <para>
-              sublist
-            </para>
-          </listitem>
-        </orderedlist>
-      </listitem>
-    </varlistentry>
-  </variablelist>
-</sect1>
-<sect1 id="html-blocks">
-  <title>HTML Blocks</title>
-  <para>
-    Simple block on one line:
-  </para>
-  <para>
-    foo
-  </para>
-  <para>
-    And nested without indentation:
-  </para>
-  <para>
-    foo
-  </para>
-  <para>
-    bar
-  </para>
-  <para>
-    Interpreted markdown in a table:
-  </para>
-  <table>
-  <tr>
-  <td>
-  This is <emphasis>emphasized</emphasis>
-  </td>
-  <td>
-  And this is <emphasis role="strong">strong</emphasis>
-  </td>
-  </tr>
-  </table>
-  <script type="text/javascript">document.write('This *should not* be interpreted as markdown');</script>
-  <para>
-    Here’s a simple block:
-  </para>
-  <para>
-    foo
-  </para>
-  <para>
-    This should be a code block, though:
-  </para>
-  <programlisting>
-&lt;div&gt;
-    foo
-&lt;/div&gt;
-</programlisting>
-  <para>
-    As should this:
-  </para>
-  <programlisting>
-&lt;div&gt;foo&lt;/div&gt;
-</programlisting>
-  <para>
-    Now, nested:
-  </para>
-  <para>
-    foo
-  </para>
-  <para>
-    This should just be an HTML comment:
-  </para>
-  <!-- Comment -->
-  <para>
-    Multiline:
-  </para>
-  <!--
-  Blah
-  Blah
-  -->
-  <!--
-      This is another comment.
-  -->
-  <para>
-    Code block:
-  </para>
-  <programlisting>
-&lt;!-- Comment --&gt;
-</programlisting>
-  <para>
-    Just plain comment, with trailing spaces on the line:
-  </para>
-  <!-- foo -->
-  <para>
-    Code:
-  </para>
-  <programlisting>
-&lt;hr /&gt;
-</programlisting>
-  <para>
-    Hr’s:
-  </para>
-  <hr>
-  <hr />
-  <hr />
-  <hr>
-  <hr />
-  <hr />
-  <hr class="foo" id="bar" />
-  <hr class="foo" id="bar" />
-  <hr class="foo" id="bar">
-</sect1>
-<sect1 id="inline-markup">
-  <title>Inline Markup</title>
-  <para>
-    This is <emphasis>emphasized</emphasis>, and so <emphasis>is
-    this</emphasis>.
-  </para>
-  <para>
-    This is <emphasis role="strong">strong</emphasis>, and so
-    <emphasis role="strong">is this</emphasis>.
-  </para>
-  <para>
-    An <emphasis><ulink url="/url">emphasized link</ulink></emphasis>.
-  </para>
-  <para>
-    <emphasis role="strong"><emphasis>This is strong and
-    em.</emphasis></emphasis>
-  </para>
-  <para>
-    So is <emphasis role="strong"><emphasis>this</emphasis></emphasis> word.
-  </para>
-  <para>
-    <emphasis role="strong"><emphasis>This is strong and
-    em.</emphasis></emphasis>
-  </para>
-  <para>
-    So is <emphasis role="strong"><emphasis>this</emphasis></emphasis> word.
-  </para>
-  <para>
-    This is code: <literal>&gt;</literal>, <literal>$</literal>,
-    <literal>\</literal>, <literal>\$</literal>,
-    <literal>&lt;html&gt;</literal>.
-  </para>
-  <para>
-    <emphasis role="strikethrough">This is
-    <emphasis>strikeout</emphasis>.</emphasis>
-  </para>
-  <para>
-    Superscripts: a<superscript>bc</superscript>d
-    a<superscript><emphasis>hello</emphasis></superscript>
-    a<superscript>hello there</superscript>.
-  </para>
-  <para>
-    Subscripts: H<subscript>2</subscript>O, H<subscript>23</subscript>O,
-    H<subscript>many of them</subscript>O.
-  </para>
-  <para>
-    These should not be superscripts or subscripts, because of the unescaped
-    spaces: a^b c^d, a~b c~d.
-  </para>
-</sect1>
-<sect1 id="smart-quotes-ellipses-dashes">
-  <title>Smart quotes, ellipses, dashes</title>
-  <para>
-    <quote>Hello,</quote> said the spider. <quote><quote>Shelob</quote> is my
-    name.</quote>
-  </para>
-  <para>
-    <quote>A</quote>, <quote>B</quote>, and <quote>C</quote> are letters.
-  </para>
-  <para>
-    <quote>Oak,</quote> <quote>elm,</quote> and <quote>beech</quote> are names
-    of trees. So is <quote>pine.</quote>
-  </para>
-  <para>
-    <quote>He said, <quote>I want to go.</quote></quote> Were you alive in the
-    70’s?
-  </para>
-  <para>
-    Here is some quoted <quote><literal>code</literal></quote> and a
-    <quote><ulink url="http://example.com/?foo=1&amp;bar=2">quoted
-    link</ulink></quote>.
-  </para>
-  <para>
-    Some dashes: one—two — three—four — five.
-  </para>
-  <para>
-    Dashes between numbers: 5–7, 255–66, 1987–1999.
-  </para>
-  <para>
-    Ellipses…and…and….
-  </para>
-</sect1>
-<sect1 id="latex">
-  <title>LaTeX</title>
-  <itemizedlist spacing="compact">
-    <listitem>
-      <para>
-      </para>
-    </listitem>
-    <listitem>
-      <para>
-        2 + 2 = 4
-      </para>
-    </listitem>
-    <listitem>
-      <para>
-        <emphasis>x</emphasis> ∈ <emphasis>y</emphasis>
-      </para>
-    </listitem>
-    <listitem>
-      <para>
-        <emphasis>α</emphasis> ∧ <emphasis>ω</emphasis>
-      </para>
-    </listitem>
-    <listitem>
-      <para>
-        223
-      </para>
-    </listitem>
-    <listitem>
-      <para>
-        <emphasis>p</emphasis>-Tree
-      </para>
-    </listitem>
-    <listitem>
-      <para>
-        Here’s some display math:
-        $$\frac{d}{dx}f(x)=\lim_{h\to 0}\frac{f(x+h)-f(x)}{h}$$
-      </para>
-    </listitem>
-    <listitem>
-      <para>
-        Here’s one that has a line break in it:
-        <emphasis>α</emphasis> + <emphasis>ω</emphasis> × <emphasis>x</emphasis><superscript>2</superscript>.
-      </para>
-    </listitem>
-  </itemizedlist>
-  <para>
-    These shouldn’t be math:
-  </para>
-  <itemizedlist spacing="compact">
-    <listitem>
-      <para>
-        To get the famous equation, write <literal>$e = mc^2$</literal>.
-      </para>
-    </listitem>
-    <listitem>
-      <para>
-        $22,000 is a <emphasis>lot</emphasis> of money. So is $34,000. (It
-        worked if <quote>lot</quote> is emphasized.)
-      </para>
-    </listitem>
-    <listitem>
-      <para>
-        Shoes ($20) and socks ($5).
-      </para>
-    </listitem>
-    <listitem>
-      <para>
-        Escaped <literal>$</literal>: $73 <emphasis>this should be
-        emphasized</emphasis> 23$.
-      </para>
-    </listitem>
-  </itemizedlist>
-  <para>
-    Here’s a LaTeX table:
-  </para>
-</sect1>
-<sect1 id="special-characters">
-  <title>Special Characters</title>
-  <para>
-    Here is some unicode:
-  </para>
-  <itemizedlist spacing="compact">
-    <listitem>
-      <para>
-        I hat: Î
-      </para>
-    </listitem>
-    <listitem>
-      <para>
-        o umlaut: ö
-      </para>
-    </listitem>
-    <listitem>
-      <para>
-        section: §
-      </para>
-    </listitem>
-    <listitem>
-      <para>
-        set membership: ∈
-      </para>
-    </listitem>
-    <listitem>
-      <para>
-        copyright: ©
-      </para>
-    </listitem>
-  </itemizedlist>
-  <para>
-    AT&amp;T has an ampersand in their name.
-  </para>
-  <para>
-    AT&amp;T is another way to write it.
-  </para>
-  <para>
-    This &amp; that.
-  </para>
-  <para>
-    4 &lt; 5.
-  </para>
-  <para>
-    6 &gt; 5.
-  </para>
-  <para>
-    Backslash: \
-  </para>
-  <para>
-    Backtick: `
-  </para>
-  <para>
-    Asterisk: *
-  </para>
-  <para>
-    Underscore: _
-  </para>
-  <para>
-    Left brace: {
-  </para>
-  <para>
-    Right brace: }
-  </para>
-  <para>
-    Left bracket: [
-  </para>
-  <para>
-    Right bracket: ]
-  </para>
-  <para>
-    Left paren: (
-  </para>
-  <para>
-    Right paren: )
-  </para>
-  <para>
-    Greater-than: &gt;
-  </para>
-  <para>
-    Hash: #
-  </para>
-  <para>
-    Period: .
-  </para>
-  <para>
-    Bang: !
-  </para>
-  <para>
-    Plus: +
-  </para>
-  <para>
-    Minus: -
-  </para>
-</sect1>
-<sect1 id="links">
-  <title>Links</title>
-  <sect2 id="explicit">
-    <title>Explicit</title>
-    <para>
-      Just a <ulink url="/url/">URL</ulink>.
-    </para>
-    <para>
-      <ulink url="/url/">URL and title</ulink>.
-    </para>
-    <para>
-      <ulink url="/url/">URL and title</ulink>.
-    </para>
-    <para>
-      <ulink url="/url/">URL and title</ulink>.
-    </para>
-    <para>
-      <ulink url="/url/">URL and title</ulink>
-    </para>
-    <para>
-      <ulink url="/url/">URL and title</ulink>
-    </para>
-    <para>
-      <ulink url="/url/with_underscore">with_underscore</ulink>
-    </para>
-    <para>
-      Email link (<email>nobody@nowhere.net</email>)
-    </para>
-    <para>
-      <ulink url="">Empty</ulink>.
-    </para>
-  </sect2>
-  <sect2 id="reference">
-    <title>Reference</title>
-    <para>
-      Foo <ulink url="/url/">bar</ulink>.
-    </para>
-    <para>
-      With <ulink url="/url/">embedded [brackets]</ulink>.
-    </para>
-    <para>
-      <ulink url="/url/">b</ulink> by itself should be a link.
-    </para>
-    <para>
-      Indented <ulink url="/url">once</ulink>.
-    </para>
-    <para>
-      Indented <ulink url="/url">twice</ulink>.
-    </para>
-    <para>
-      Indented <ulink url="/url">thrice</ulink>.
-    </para>
-    <para>
-      This should [not][] be a link.
-    </para>
-    <programlisting>
-[not]: /url
-</programlisting>
-    <para>
-      Foo <ulink url="/url/">bar</ulink>.
-    </para>
-    <para>
-      Foo <ulink url="/url/">biz</ulink>.
-    </para>
-  </sect2>
-  <sect2 id="with-ampersands">
-    <title>With ampersands</title>
-    <para>
-      Here’s a <ulink url="http://example.com/?foo=1&amp;bar=2">link with an
-      ampersand in the URL</ulink>.
-    </para>
-    <para>
-      Here’s a link with an amersand in the link text:
-      <ulink url="http://att.com/">AT&amp;T</ulink>.
-    </para>
-    <para>
-      Here’s an <ulink url="/script?foo=1&amp;bar=2">inline link</ulink>.
-    </para>
-    <para>
-      Here’s an <ulink url="/script?foo=1&amp;bar=2">inline link in pointy
-      braces</ulink>.
-    </para>
-  </sect2>
-  <sect2 id="autolinks">
-    <title>Autolinks</title>
-    <para>
-      With an ampersand:
-      <ulink url="http://example.com/?foo=1&amp;bar=2">http://example.com/?foo=1&amp;bar=2</ulink>
-    </para>
-    <itemizedlist spacing="compact">
-      <listitem>
-        <para>
-          In a list?
-        </para>
-      </listitem>
-      <listitem>
-        <para>
-          <ulink url="http://example.com/">http://example.com/</ulink>
-        </para>
-      </listitem>
-      <listitem>
-        <para>
-          It should.
-        </para>
-      </listitem>
-    </itemizedlist>
-    <para>
-      An e-mail address: <email>nobody@nowhere.net</email>
-    </para>
-    <blockquote>
-      <para>
-        Blockquoted:
-        <ulink url="http://example.com/">http://example.com/</ulink>
-      </para>
-    </blockquote>
-    <para>
-      Auto-links should not occur here:
-      <literal>&lt;http://example.com/&gt;</literal>
-    </para>
-    <programlisting>
-or here: &lt;http://example.com/&gt;
-</programlisting>
-  </sect2>
-</sect1>
-<sect1 id="images">
-  <title>Images</title>
-  <para>
-    From <quote>Voyage dans la Lune</quote> by Georges Melies (1902):
-  </para>
-  <figure>
-    <title>lalune</title>
-    <mediaobject>
-      <imageobject>
-        <imagedata fileref="lalune.jpg" />
-      </imageobject>
-      <textobject><phrase>lalune</phrase></textobject>
-    </mediaobject>
-  </figure>
-  <para>
-    Here is a movie <inlinemediaobject>
-      <imageobject>
-        <imagedata fileref="movie.jpg" />
-      </imageobject>
-    </inlinemediaobject> icon.
-  </para>
-</sect1>
-<sect1 id="footnotes">
-  <title>Footnotes</title>
-  <para>
-    Here is a footnote reference,<footnote>
-      <para>
-        Here is the footnote. It can go anywhere after the footnote reference.
-        It need not be placed at the end of the document.
-      </para>
-    </footnote> and another.<footnote>
-      <para>
-        Here’s the long note. This one contains multiple blocks.
-      </para>
-      <para>
-        Subsequent blocks are indented to show that they belong to the
-        footnote (as with list items).
-      </para>
-      <programlisting>
-  { &lt;code&gt; }
-</programlisting>
-      <para>
-        If you want, you can indent every line, but you can also be lazy and
-        just indent the first line of each block.
-      </para>
-    </footnote> This should <emphasis>not</emphasis> be a footnote reference,
-    because it contains a space.[^my note] Here is an inline note.<footnote>
-      <para>
-        This is <emphasis>easier</emphasis> to type. Inline notes may contain
-        <ulink url="http://google.com">links</ulink> and <literal>]</literal>
-        verbatim characters, as well as [bracketed text].
-      </para>
-    </footnote>
-  </para>
-  <blockquote>
-    <para>
-      Notes can go in quotes.<footnote>
-        <para>
-          In quote.
-        </para>
-      </footnote>
-    </para>
-  </blockquote>
-  <orderedlist numeration="arabic" spacing="compact">
-    <listitem>
-      <para>
-        And in list items.<footnote>
-          <para>
-            In list.
-          </para>
-        </footnote>
-      </para>
-    </listitem>
-  </orderedlist>
-  <para>
-    This paragraph should not be part of the note, as it is not indented.
-  </para>
-</sect1>
+        <personname>
+          <firstname>John</firstname>
+          <surname>MacFarlane</surname>
+        </personname>
+      </author>
+      <author>
+        <personname>
+          <firstname></firstname>
+          <surname>Anonymous</surname>
+        </personname>
+      </author>
+    </authorgroup>
+    <date>July 17, 2006</date>
+  </articleinfo>
+  <para>
+    This is a set of tests for pandoc. Most of them are adapted from John
+    Gruber’s markdown test suite.
+  </para>
+  <sect1 id="headers">
+    <title>Headers</title>
+    <sect2 id="level-2-with-an-embedded-link">
+      <title>Level 2 with an <ulink url="/url">embedded link</ulink></title>
+      <sect3 id="level-3-with-emphasis">
+        <title>Level 3 with <emphasis>emphasis</emphasis></title>
+        <sect4 id="level-4">
+          <title>Level 4</title>
+          <sect5 id="level-5">
+            <title>Level 5</title>
+            <para>
+            </para>
+          </sect5>
+        </sect4>
+      </sect3>
+    </sect2>
+  </sect1>
+  <sect1 id="level-1">
+    <title>Level 1</title>
+    <sect2 id="level-2-with-emphasis">
+      <title>Level 2 with <emphasis>emphasis</emphasis></title>
+      <sect3 id="level-3">
+        <title>Level 3</title>
+        <para>
+          with no blank line
+        </para>
+      </sect3>
+    </sect2>
+    <sect2 id="level-2">
+      <title>Level 2</title>
+      <para>
+        with no blank line
+      </para>
+    </sect2>
+  </sect1>
+  <sect1 id="paragraphs">
+    <title>Paragraphs</title>
+    <para>
+      Here’s a regular paragraph.
+    </para>
+    <para>
+      In Markdown 1.0.0 and earlier. Version 8. This line turns into a list
+      item. Because a hard-wrapped line in the middle of a paragraph looked like
+      a list item.
+    </para>
+    <para>
+      Here’s one with a bullet. * criminey.
+    </para>
+<literallayout>There should be a hard line break
+here.</literallayout>
+  </sect1>
+  <sect1 id="block-quotes">
+    <title>Block Quotes</title>
+    <para>
+      E-mail style:
+    </para>
+    <blockquote>
+      <para>
+        This is a block quote. It is pretty short.
+      </para>
+    </blockquote>
+    <blockquote>
+      <para>
+        Code in a block quote:
+      </para>
+      <programlisting>
+sub status {
+    print &quot;working&quot;;
+}
+</programlisting>
+      <para>
+        A list:
+      </para>
+      <orderedlist numeration="arabic" spacing="compact">
+        <listitem>
+          <para>
+            item one
+          </para>
+        </listitem>
+        <listitem>
+          <para>
+            item two
+          </para>
+        </listitem>
+      </orderedlist>
+      <para>
+        Nested block quotes:
+      </para>
+      <blockquote>
+        <para>
+          nested
+        </para>
+      </blockquote>
+      <blockquote>
+        <para>
+          nested
+        </para>
+      </blockquote>
+    </blockquote>
+    <para>
+      This should not be a block quote: 2 &gt; 1.
+    </para>
+    <para>
+      And a following paragraph.
+    </para>
+  </sect1>
+  <sect1 id="code-blocks">
+    <title>Code Blocks</title>
+    <para>
+      Code:
+    </para>
+    <programlisting>
+---- (should be four hyphens)
+
+sub status {
+    print &quot;working&quot;;
+}
+
+this code block is indented by one tab
+</programlisting>
+    <para>
+      And:
+    </para>
+    <programlisting>
+    this code block is indented by two tabs
+
+These should not be escaped:  \$ \\ \&gt; \[ \{
+</programlisting>
+  </sect1>
+  <sect1 id="lists">
+    <title>Lists</title>
+    <sect2 id="unordered">
+      <title>Unordered</title>
+      <para>
+        Asterisks tight:
+      </para>
+      <itemizedlist spacing="compact">
+        <listitem>
+          <para>
+            asterisk 1
+          </para>
+        </listitem>
+        <listitem>
+          <para>
+            asterisk 2
+          </para>
+        </listitem>
+        <listitem>
+          <para>
+            asterisk 3
+          </para>
+        </listitem>
+      </itemizedlist>
+      <para>
+        Asterisks loose:
+      </para>
+      <itemizedlist>
+        <listitem>
+          <para>
+            asterisk 1
+          </para>
+        </listitem>
+        <listitem>
+          <para>
+            asterisk 2
+          </para>
+        </listitem>
+        <listitem>
+          <para>
+            asterisk 3
+          </para>
+        </listitem>
+      </itemizedlist>
+      <para>
+        Pluses tight:
+      </para>
+      <itemizedlist spacing="compact">
+        <listitem>
+          <para>
+            Plus 1
+          </para>
+        </listitem>
+        <listitem>
+          <para>
+            Plus 2
+          </para>
+        </listitem>
+        <listitem>
+          <para>
+            Plus 3
+          </para>
+        </listitem>
+      </itemizedlist>
+      <para>
+        Pluses loose:
+      </para>
+      <itemizedlist>
+        <listitem>
+          <para>
+            Plus 1
+          </para>
+        </listitem>
+        <listitem>
+          <para>
+            Plus 2
+          </para>
+        </listitem>
+        <listitem>
+          <para>
+            Plus 3
+          </para>
+        </listitem>
+      </itemizedlist>
+      <para>
+        Minuses tight:
+      </para>
+      <itemizedlist spacing="compact">
+        <listitem>
+          <para>
+            Minus 1
+          </para>
+        </listitem>
+        <listitem>
+          <para>
+            Minus 2
+          </para>
+        </listitem>
+        <listitem>
+          <para>
+            Minus 3
+          </para>
+        </listitem>
+      </itemizedlist>
+      <para>
+        Minuses loose:
+      </para>
+      <itemizedlist>
+        <listitem>
+          <para>
+            Minus 1
+          </para>
+        </listitem>
+        <listitem>
+          <para>
+            Minus 2
+          </para>
+        </listitem>
+        <listitem>
+          <para>
+            Minus 3
+          </para>
+        </listitem>
+      </itemizedlist>
+    </sect2>
+    <sect2 id="ordered">
+      <title>Ordered</title>
+      <para>
+        Tight:
+      </para>
+      <orderedlist numeration="arabic" spacing="compact">
+        <listitem>
+          <para>
+            First
+          </para>
+        </listitem>
+        <listitem>
+          <para>
+            Second
+          </para>
+        </listitem>
+        <listitem>
+          <para>
+            Third
+          </para>
+        </listitem>
+      </orderedlist>
+      <para>
+        and:
+      </para>
+      <orderedlist numeration="arabic" spacing="compact">
+        <listitem>
+          <para>
+            One
+          </para>
+        </listitem>
+        <listitem>
+          <para>
+            Two
+          </para>
+        </listitem>
+        <listitem>
+          <para>
+            Three
+          </para>
+        </listitem>
+      </orderedlist>
+      <para>
+        Loose using tabs:
+      </para>
+      <orderedlist numeration="arabic">
+        <listitem>
+          <para>
+            First
+          </para>
+        </listitem>
+        <listitem>
+          <para>
+            Second
+          </para>
+        </listitem>
+        <listitem>
+          <para>
+            Third
+          </para>
+        </listitem>
+      </orderedlist>
+      <para>
+        and using spaces:
+      </para>
+      <orderedlist numeration="arabic">
+        <listitem>
+          <para>
+            One
+          </para>
+        </listitem>
+        <listitem>
+          <para>
+            Two
+          </para>
+        </listitem>
+        <listitem>
+          <para>
+            Three
+          </para>
+        </listitem>
+      </orderedlist>
+      <para>
+        Multiple paragraphs:
+      </para>
+      <orderedlist numeration="arabic">
+        <listitem>
+          <para>
+            Item 1, graf one.
+          </para>
+          <para>
+            Item 1. graf two. The quick brown fox jumped over the lazy dog’s
+            back.
+          </para>
+        </listitem>
+        <listitem>
+          <para>
+            Item 2.
+          </para>
+        </listitem>
+        <listitem>
+          <para>
+            Item 3.
+          </para>
+        </listitem>
+      </orderedlist>
+    </sect2>
+    <sect2 id="nested">
+      <title>Nested</title>
+      <itemizedlist spacing="compact">
+        <listitem>
+          <para>
+            Tab
+          </para>
+          <itemizedlist spacing="compact">
+            <listitem>
+              <para>
+                Tab
+              </para>
+              <itemizedlist spacing="compact">
+                <listitem>
+                  <para>
+                    Tab
+                  </para>
+                </listitem>
+              </itemizedlist>
+            </listitem>
+          </itemizedlist>
+        </listitem>
+      </itemizedlist>
+      <para>
+        Here’s another:
+      </para>
+      <orderedlist numeration="arabic" spacing="compact">
+        <listitem>
+          <para>
+            First
+          </para>
+        </listitem>
+        <listitem>
+          <para>
+            Second:
+          </para>
+          <itemizedlist spacing="compact">
+            <listitem>
+              <para>
+                Fee
+              </para>
+            </listitem>
+            <listitem>
+              <para>
+                Fie
+              </para>
+            </listitem>
+            <listitem>
+              <para>
+                Foe
+              </para>
+            </listitem>
+          </itemizedlist>
+        </listitem>
+        <listitem>
+          <para>
+            Third
+          </para>
+        </listitem>
+      </orderedlist>
+      <para>
+        Same thing but with paragraphs:
+      </para>
+      <orderedlist numeration="arabic">
+        <listitem>
+          <para>
+            First
+          </para>
+        </listitem>
+        <listitem>
+          <para>
+            Second:
+          </para>
+          <itemizedlist spacing="compact">
+            <listitem>
+              <para>
+                Fee
+              </para>
+            </listitem>
+            <listitem>
+              <para>
+                Fie
+              </para>
+            </listitem>
+            <listitem>
+              <para>
+                Foe
+              </para>
+            </listitem>
+          </itemizedlist>
+        </listitem>
+        <listitem>
+          <para>
+            Third
+          </para>
+        </listitem>
+      </orderedlist>
+    </sect2>
+    <sect2 id="tabs-and-spaces">
+      <title>Tabs and spaces</title>
+      <itemizedlist>
+        <listitem>
+          <para>
+            this is a list item indented with tabs
+          </para>
+        </listitem>
+        <listitem>
+          <para>
+            this is a list item indented with spaces
+          </para>
+          <itemizedlist>
+            <listitem>
+              <para>
+                this is an example list item indented with tabs
+              </para>
+            </listitem>
+            <listitem>
+              <para>
+                this is an example list item indented with spaces
+              </para>
+            </listitem>
+          </itemizedlist>
+        </listitem>
+      </itemizedlist>
+    </sect2>
+    <sect2 id="fancy-list-markers">
+      <title>Fancy list markers</title>
+      <orderedlist numeration="arabic" startingnumber="2">
+        <listitem>
+          <para>
+            begins with 2
+          </para>
+        </listitem>
+        <listitem>
+          <para>
+            and now 3
+          </para>
+          <para>
+            with a continuation
+          </para>
+          <orderedlist numeration="lowerroman" spacing="compact" startingnumber="4">
+            <listitem>
+              <para>
+                sublist with roman numerals, starting with 4
+              </para>
+            </listitem>
+            <listitem>
+              <para>
+                more items
+              </para>
+              <orderedlist numeration="upperalpha" spacing="compact">
+                <listitem>
+                  <para>
+                    a subsublist
+                  </para>
+                </listitem>
+                <listitem>
+                  <para>
+                    a subsublist
+                  </para>
+                </listitem>
+              </orderedlist>
+            </listitem>
+          </orderedlist>
+        </listitem>
+      </orderedlist>
+      <para>
+        Nesting:
+      </para>
+      <orderedlist numeration="upperalpha" spacing="compact">
+        <listitem>
+          <para>
+            Upper Alpha
+          </para>
+          <orderedlist numeration="upperroman" spacing="compact">
+            <listitem>
+              <para>
+                Upper Roman.
+              </para>
+              <orderedlist numeration="arabic" spacing="compact" startingnumber="6">
+                <listitem>
+                  <para>
+                    Decimal start with 6
+                  </para>
+                  <orderedlist numeration="loweralpha" spacing="compact" startingnumber="3">
+                    <listitem>
+                      <para>
+                        Lower alpha with paren
+                      </para>
+                    </listitem>
+                  </orderedlist>
+                </listitem>
+              </orderedlist>
+            </listitem>
+          </orderedlist>
+        </listitem>
+      </orderedlist>
+      <para>
+        Autonumbering:
+      </para>
+      <orderedlist spacing="compact">
+        <listitem>
+          <para>
+            Autonumber.
+          </para>
+        </listitem>
+        <listitem>
+          <para>
+            More.
+          </para>
+          <orderedlist spacing="compact">
+            <listitem>
+              <para>
+                Nested.
+              </para>
+            </listitem>
+          </orderedlist>
+        </listitem>
+      </orderedlist>
+      <para>
+        Should not be a list item:
+      </para>
+      <para>
+        M.A. 2007
+      </para>
+      <para>
+        B. Williams
+      </para>
+    </sect2>
+  </sect1>
+  <sect1 id="definition-lists">
+    <title>Definition Lists</title>
+    <para>
+      Tight using spaces:
+    </para>
+    <variablelist spacing="compact">
+      <varlistentry>
+        <term>
+          apple
+        </term>
+        <listitem>
+          <para>
+            red fruit
+          </para>
+        </listitem>
+      </varlistentry>
+      <varlistentry>
+        <term>
+          orange
+        </term>
+        <listitem>
+          <para>
+            orange fruit
+          </para>
+        </listitem>
+      </varlistentry>
+      <varlistentry>
+        <term>
+          banana
+        </term>
+        <listitem>
+          <para>
+            yellow fruit
+          </para>
+        </listitem>
+      </varlistentry>
+    </variablelist>
+    <para>
+      Tight using tabs:
+    </para>
+    <variablelist spacing="compact">
+      <varlistentry>
+        <term>
+          apple
+        </term>
+        <listitem>
+          <para>
+            red fruit
+          </para>
+        </listitem>
+      </varlistentry>
+      <varlistentry>
+        <term>
+          orange
+        </term>
+        <listitem>
+          <para>
+            orange fruit
+          </para>
+        </listitem>
+      </varlistentry>
+      <varlistentry>
+        <term>
+          banana
+        </term>
+        <listitem>
+          <para>
+            yellow fruit
+          </para>
+        </listitem>
+      </varlistentry>
+    </variablelist>
+    <para>
+      Loose:
+    </para>
+    <variablelist>
+      <varlistentry>
+        <term>
+          apple
+        </term>
+        <listitem>
+          <para>
+            red fruit
+          </para>
+        </listitem>
+      </varlistentry>
+      <varlistentry>
+        <term>
+          orange
+        </term>
+        <listitem>
+          <para>
+            orange fruit
+          </para>
+        </listitem>
+      </varlistentry>
+      <varlistentry>
+        <term>
+          banana
+        </term>
+        <listitem>
+          <para>
+            yellow fruit
+          </para>
+        </listitem>
+      </varlistentry>
+    </variablelist>
+    <para>
+      Multiple blocks with italics:
+    </para>
+    <variablelist>
+      <varlistentry>
+        <term>
+          <emphasis>apple</emphasis>
+        </term>
+        <listitem>
+          <para>
+            red fruit
+          </para>
+          <para>
+            contains seeds, crisp, pleasant to taste
+          </para>
+        </listitem>
+      </varlistentry>
+      <varlistentry>
+        <term>
+          <emphasis>orange</emphasis>
+        </term>
+        <listitem>
+          <para>
+            orange fruit
+          </para>
+          <programlisting>
+{ orange code block }
+</programlisting>
+          <blockquote>
+            <para>
+              orange block quote
+            </para>
+          </blockquote>
+        </listitem>
+      </varlistentry>
+    </variablelist>
+    <para>
+      Multiple definitions, tight:
+    </para>
+    <variablelist spacing="compact">
+      <varlistentry>
+        <term>
+          apple
+        </term>
+        <listitem>
+          <para>
+            red fruit
+          </para>
+          <para>
+            computer
+          </para>
+        </listitem>
+      </varlistentry>
+      <varlistentry>
+        <term>
+          orange
+        </term>
+        <listitem>
+          <para>
+            orange fruit
+          </para>
+          <para>
+            bank
+          </para>
+        </listitem>
+      </varlistentry>
+    </variablelist>
+    <para>
+      Multiple definitions, loose:
+    </para>
+    <variablelist>
+      <varlistentry>
+        <term>
+          apple
+        </term>
+        <listitem>
+          <para>
+            red fruit
+          </para>
+          <para>
+            computer
+          </para>
+        </listitem>
+      </varlistentry>
+      <varlistentry>
+        <term>
+          orange
+        </term>
+        <listitem>
+          <para>
+            orange fruit
+          </para>
+          <para>
+            bank
+          </para>
+        </listitem>
+      </varlistentry>
+    </variablelist>
+    <para>
+      Blank line after term, indented marker, alternate markers:
+    </para>
+    <variablelist>
+      <varlistentry>
+        <term>
+          apple
+        </term>
+        <listitem>
+          <para>
+            red fruit
+          </para>
+          <para>
+            computer
+          </para>
+        </listitem>
+      </varlistentry>
+      <varlistentry>
+        <term>
+          orange
+        </term>
+        <listitem>
+          <para>
+            orange fruit
+          </para>
+          <orderedlist numeration="arabic" spacing="compact">
+            <listitem>
+              <para>
+                sublist
+              </para>
+            </listitem>
+            <listitem>
+              <para>
+                sublist
+              </para>
+            </listitem>
+          </orderedlist>
+        </listitem>
+      </varlistentry>
+    </variablelist>
+  </sect1>
+  <sect1 id="html-blocks">
+    <title>HTML Blocks</title>
+    <para>
+      Simple block on one line:
+    </para>
+    <para>
+      foo
+    </para>
+    <para>
+      And nested without indentation:
+    </para>
+    <para>
+      foo
+    </para>
+    <para>
+      bar
+    </para>
+    <para>
+      Interpreted markdown in a table:
+    </para>
+    <table>
+    <tr>
+    <td>
+    This is <emphasis>emphasized</emphasis>
+    </td>
+    <td>
+    And this is <emphasis role="strong">strong</emphasis>
+    </td>
+    </tr>
+    </table>
+    <script type="text/javascript">document.write('This *should not* be interpreted as markdown');</script>
+    <para>
+      Here’s a simple block:
+    </para>
+    <para>
+      foo
+    </para>
+    <para>
+      This should be a code block, though:
+    </para>
+    <programlisting>
+&lt;div&gt;
+    foo
+&lt;/div&gt;
+</programlisting>
+    <para>
+      As should this:
+    </para>
+    <programlisting>
+&lt;div&gt;foo&lt;/div&gt;
+</programlisting>
+    <para>
+      Now, nested:
+    </para>
+    <para>
+      foo
+    </para>
+    <para>
+      This should just be an HTML comment:
+    </para>
+    <!-- Comment -->
+    <para>
+      Multiline:
+    </para>
+    <!--
+    Blah
+    Blah
+    -->
+    <!--
+        This is another comment.
+    -->
+    <para>
+      Code block:
+    </para>
+    <programlisting>
+&lt;!-- Comment --&gt;
+</programlisting>
+    <para>
+      Just plain comment, with trailing spaces on the line:
+    </para>
+    <!-- foo -->
+    <para>
+      Code:
+    </para>
+    <programlisting>
+&lt;hr /&gt;
+</programlisting>
+    <para>
+      Hr’s:
+    </para>
+    <hr>
+    <hr />
+    <hr />
+    <hr>
+    <hr />
+    <hr />
+    <hr class="foo" id="bar" />
+    <hr class="foo" id="bar" />
+    <hr class="foo" id="bar">
+  </sect1>
+  <sect1 id="inline-markup">
+    <title>Inline Markup</title>
+    <para>
+      This is <emphasis>emphasized</emphasis>, and so <emphasis>is
+      this</emphasis>.
+    </para>
+    <para>
+      This is <emphasis role="strong">strong</emphasis>, and so
+      <emphasis role="strong">is this</emphasis>.
+    </para>
+    <para>
+      An <emphasis><ulink url="/url">emphasized link</ulink></emphasis>.
+    </para>
+    <para>
+      <emphasis role="strong"><emphasis>This is strong and
+      em.</emphasis></emphasis>
+    </para>
+    <para>
+      So is <emphasis role="strong"><emphasis>this</emphasis></emphasis> word.
+    </para>
+    <para>
+      <emphasis role="strong"><emphasis>This is strong and
+      em.</emphasis></emphasis>
+    </para>
+    <para>
+      So is <emphasis role="strong"><emphasis>this</emphasis></emphasis> word.
+    </para>
+    <para>
+      This is code: <literal>&gt;</literal>, <literal>$</literal>,
+      <literal>\</literal>, <literal>\$</literal>,
+      <literal>&lt;html&gt;</literal>.
+    </para>
+    <para>
+      <emphasis role="strikethrough">This is
+      <emphasis>strikeout</emphasis>.</emphasis>
+    </para>
+    <para>
+      Superscripts: a<superscript>bc</superscript>d
+      a<superscript><emphasis>hello</emphasis></superscript>
+      a<superscript>hello there</superscript>.
+    </para>
+    <para>
+      Subscripts: H<subscript>2</subscript>O, H<subscript>23</subscript>O,
+      H<subscript>many of them</subscript>O.
+    </para>
+    <para>
+      These should not be superscripts or subscripts, because of the unescaped
+      spaces: a^b c^d, a~b c~d.
+    </para>
+  </sect1>
+  <sect1 id="smart-quotes-ellipses-dashes">
+    <title>Smart quotes, ellipses, dashes</title>
+    <para>
+      <quote>Hello,</quote> said the spider. <quote><quote>Shelob</quote> is my
+      name.</quote>
+    </para>
+    <para>
+      <quote>A</quote>, <quote>B</quote>, and <quote>C</quote> are letters.
+    </para>
+    <para>
+      <quote>Oak,</quote> <quote>elm,</quote> and <quote>beech</quote> are names
+      of trees. So is <quote>pine.</quote>
+    </para>
+    <para>
+      <quote>He said, <quote>I want to go.</quote></quote> Were you alive in the
+      70’s?
+    </para>
+    <para>
+      Here is some quoted <quote><literal>code</literal></quote> and a
+      <quote><ulink url="http://example.com/?foo=1&amp;bar=2">quoted
+      link</ulink></quote>.
+    </para>
+    <para>
+      Some dashes: one—two — three—four — five.
+    </para>
+    <para>
+      Dashes between numbers: 5–7, 255–66, 1987–1999.
+    </para>
+    <para>
+      Ellipses…and…and….
+    </para>
+  </sect1>
+  <sect1 id="latex">
+    <title>LaTeX</title>
+    <itemizedlist spacing="compact">
+      <listitem>
+        <para>
+        </para>
+      </listitem>
+      <listitem>
+        <para>
+          2 + 2 = 4
+        </para>
+      </listitem>
+      <listitem>
+        <para>
+          <emphasis>x</emphasis> ∈ <emphasis>y</emphasis>
+        </para>
+      </listitem>
+      <listitem>
+        <para>
+          <emphasis>α</emphasis> ∧ <emphasis>ω</emphasis>
+        </para>
+      </listitem>
+      <listitem>
+        <para>
+          223
+        </para>
+      </listitem>
+      <listitem>
+        <para>
+          <emphasis>p</emphasis>-Tree
+        </para>
+      </listitem>
+      <listitem>
+        <para>
+          Here’s some display math:
+          $$\frac{d}{dx}f(x)=\lim_{h\to 0}\frac{f(x+h)-f(x)}{h}$$
+        </para>
+      </listitem>
+      <listitem>
+        <para>
+          Here’s one that has a line break in it:
+          <emphasis>α</emphasis> + <emphasis>ω</emphasis> × <emphasis>x</emphasis><superscript>2</superscript>.
+        </para>
+      </listitem>
+    </itemizedlist>
+    <para>
+      These shouldn’t be math:
+    </para>
+    <itemizedlist spacing="compact">
+      <listitem>
+        <para>
+          To get the famous equation, write <literal>$e = mc^2$</literal>.
+        </para>
+      </listitem>
+      <listitem>
+        <para>
+          $22,000 is a <emphasis>lot</emphasis> of money. So is $34,000. (It
+          worked if <quote>lot</quote> is emphasized.)
+        </para>
+      </listitem>
+      <listitem>
+        <para>
+          Shoes ($20) and socks ($5).
+        </para>
+      </listitem>
+      <listitem>
+        <para>
+          Escaped <literal>$</literal>: $73 <emphasis>this should be
+          emphasized</emphasis> 23$.
+        </para>
+      </listitem>
+    </itemizedlist>
+    <para>
+      Here’s a LaTeX table:
+    </para>
+  </sect1>
+  <sect1 id="special-characters">
+    <title>Special Characters</title>
+    <para>
+      Here is some unicode:
+    </para>
+    <itemizedlist spacing="compact">
+      <listitem>
+        <para>
+          I hat: Î
+        </para>
+      </listitem>
+      <listitem>
+        <para>
+          o umlaut: ö
+        </para>
+      </listitem>
+      <listitem>
+        <para>
+          section: §
+        </para>
+      </listitem>
+      <listitem>
+        <para>
+          set membership: ∈
+        </para>
+      </listitem>
+      <listitem>
+        <para>
+          copyright: ©
+        </para>
+      </listitem>
+    </itemizedlist>
+    <para>
+      AT&amp;T has an ampersand in their name.
+    </para>
+    <para>
+      AT&amp;T is another way to write it.
+    </para>
+    <para>
+      This &amp; that.
+    </para>
+    <para>
+      4 &lt; 5.
+    </para>
+    <para>
+      6 &gt; 5.
+    </para>
+    <para>
+      Backslash: \
+    </para>
+    <para>
+      Backtick: `
+    </para>
+    <para>
+      Asterisk: *
+    </para>
+    <para>
+      Underscore: _
+    </para>
+    <para>
+      Left brace: {
+    </para>
+    <para>
+      Right brace: }
+    </para>
+    <para>
+      Left bracket: [
+    </para>
+    <para>
+      Right bracket: ]
+    </para>
+    <para>
+      Left paren: (
+    </para>
+    <para>
+      Right paren: )
+    </para>
+    <para>
+      Greater-than: &gt;
+    </para>
+    <para>
+      Hash: #
+    </para>
+    <para>
+      Period: .
+    </para>
+    <para>
+      Bang: !
+    </para>
+    <para>
+      Plus: +
+    </para>
+    <para>
+      Minus: -
+    </para>
+  </sect1>
+  <sect1 id="links">
+    <title>Links</title>
+    <sect2 id="explicit">
+      <title>Explicit</title>
+      <para>
+        Just a <ulink url="/url/">URL</ulink>.
+      </para>
+      <para>
+        <ulink url="/url/">URL and title</ulink>.
+      </para>
+      <para>
+        <ulink url="/url/">URL and title</ulink>.
+      </para>
+      <para>
+        <ulink url="/url/">URL and title</ulink>.
+      </para>
+      <para>
+        <ulink url="/url/">URL and title</ulink>
+      </para>
+      <para>
+        <ulink url="/url/">URL and title</ulink>
+      </para>
+      <para>
+        <ulink url="/url/with_underscore">with_underscore</ulink>
+      </para>
+      <para>
+        Email link (<email>nobody@nowhere.net</email>)
+      </para>
+      <para>
+        <ulink url="">Empty</ulink>.
+      </para>
+    </sect2>
+    <sect2 id="reference">
+      <title>Reference</title>
+      <para>
+        Foo <ulink url="/url/">bar</ulink>.
+      </para>
+      <para>
+        With <ulink url="/url/">embedded [brackets]</ulink>.
+      </para>
+      <para>
+        <ulink url="/url/">b</ulink> by itself should be a link.
+      </para>
+      <para>
+        Indented <ulink url="/url">once</ulink>.
+      </para>
+      <para>
+        Indented <ulink url="/url">twice</ulink>.
+      </para>
+      <para>
+        Indented <ulink url="/url">thrice</ulink>.
+      </para>
+      <para>
+        This should [not][] be a link.
+      </para>
+      <programlisting>
+[not]: /url
+</programlisting>
+      <para>
+        Foo <ulink url="/url/">bar</ulink>.
+      </para>
+      <para>
+        Foo <ulink url="/url/">biz</ulink>.
+      </para>
+    </sect2>
+    <sect2 id="with-ampersands">
+      <title>With ampersands</title>
+      <para>
+        Here’s a <ulink url="http://example.com/?foo=1&amp;bar=2">link with an
+        ampersand in the URL</ulink>.
+      </para>
+      <para>
+        Here’s a link with an amersand in the link text:
+        <ulink url="http://att.com/">AT&amp;T</ulink>.
+      </para>
+      <para>
+        Here’s an <ulink url="/script?foo=1&amp;bar=2">inline link</ulink>.
+      </para>
+      <para>
+        Here’s an <ulink url="/script?foo=1&amp;bar=2">inline link in pointy
+        braces</ulink>.
+      </para>
+    </sect2>
+    <sect2 id="autolinks">
+      <title>Autolinks</title>
+      <para>
+        With an ampersand:
+        <ulink url="http://example.com/?foo=1&amp;bar=2" role="uri">http://example.com/?foo=1&amp;bar=2</ulink>
+      </para>
+      <itemizedlist spacing="compact">
+        <listitem>
+          <para>
+            In a list?
+          </para>
+        </listitem>
+        <listitem>
+          <para>
+            <ulink url="http://example.com/" role="uri">http://example.com/</ulink>
+          </para>
+        </listitem>
+        <listitem>
+          <para>
+            It should.
+          </para>
+        </listitem>
+      </itemizedlist>
+      <para>
+        An e-mail address: <email>nobody@nowhere.net</email>
+      </para>
+      <blockquote>
+        <para>
+          Blockquoted:
+          <ulink url="http://example.com/" role="uri">http://example.com/</ulink>
+        </para>
+      </blockquote>
+      <para>
+        Auto-links should not occur here:
+        <literal>&lt;http://example.com/&gt;</literal>
+      </para>
+      <programlisting>
+or here: &lt;http://example.com/&gt;
+</programlisting>
+    </sect2>
+  </sect1>
+  <sect1 id="images">
+    <title>Images</title>
+    <para>
+      From <quote>Voyage dans la Lune</quote> by Georges Melies (1902):
+    </para>
+    <figure>
+      <title>lalune</title>
+      <mediaobject>
+        <imageobject>
+          <imagedata fileref="lalune.jpg" />
+        </imageobject>
+        <textobject><phrase>lalune</phrase></textobject>
+      </mediaobject>
+    </figure>
+    <para>
+      Here is a movie <inlinemediaobject>
+        <imageobject>
+          <imagedata fileref="movie.jpg" />
+        </imageobject>
+        <textobject>
+          <phrase>movie</phrase>
+        </textobject>
+      </inlinemediaobject> icon.
+    </para>
+  </sect1>
+  <sect1 id="footnotes">
+    <title>Footnotes</title>
+    <para>
+      Here is a footnote reference,<footnote>
+        <para>
+          Here is the footnote. It can go anywhere after the footnote reference.
+          It need not be placed at the end of the document.
+        </para>
+      </footnote> and another.<footnote>
+        <para>
+          Here’s the long note. This one contains multiple blocks.
+        </para>
+        <para>
+          Subsequent blocks are indented to show that they belong to the
+          footnote (as with list items).
+        </para>
+        <programlisting>
+  { &lt;code&gt; }
+</programlisting>
+        <para>
+          If you want, you can indent every line, but you can also be lazy and
+          just indent the first line of each block.
+        </para>
+      </footnote> This should <emphasis>not</emphasis> be a footnote reference,
+      because it contains a space.[^my note] Here is an inline note.<footnote>
+        <para>
+          This is <emphasis>easier</emphasis> to type. Inline notes may contain
+          <ulink url="http://google.com">links</ulink> and <literal>]</literal>
+          verbatim characters, as well as [bracketed text].
+        </para>
+      </footnote>
+    </para>
+    <blockquote>
+      <para>
+        Notes can go in quotes.<footnote>
+          <para>
+            In quote.
+          </para>
+        </footnote>
+      </para>
+    </blockquote>
+    <orderedlist numeration="arabic" spacing="compact">
+      <listitem>
+        <para>
+          And in list items.<footnote>
+            <para>
+              In list.
+            </para>
+          </footnote>
+        </para>
+      </listitem>
+    </orderedlist>
+    <para>
+      This paragraph should not be part of the note, as it is not indented.
+    </para>
+  </sect1>
 </article>
diff --git a/test/writer.docbook5 b/test/writer.docbook5
--- a/test/writer.docbook5
+++ b/test/writer.docbook5
@@ -7,1385 +7,1392 @@
     <title>Pandoc Test Suite</title>
     <authorgroup>
       <author>
-        <firstname>John</firstname>
-        <surname>MacFarlane</surname>
-      </author>
-      <author>
-        <firstname></firstname>
-        <surname>Anonymous</surname>
-      </author>
-    </authorgroup>
-    <date>July 17, 2006</date>
-  </info>
-<para>
-  This is a set of tests for pandoc. Most of them are adapted from John
-  Gruber’s markdown test suite.
-</para>
-<section xml:id="headers">
-  <title>Headers</title>
-  <section xml:id="level-2-with-an-embedded-link">
-    <title>Level 2 with an <link xlink:href="/url">embedded
-    link</link></title>
-    <section xml:id="level-3-with-emphasis">
-      <title>Level 3 with <emphasis>emphasis</emphasis></title>
-      <section xml:id="level-4">
-        <title>Level 4</title>
-        <section xml:id="level-5">
-          <title>Level 5</title>
-          <para>
-          </para>
-        </section>
-      </section>
-    </section>
-  </section>
-</section>
-<section xml:id="level-1">
-  <title>Level 1</title>
-  <section xml:id="level-2-with-emphasis">
-    <title>Level 2 with <emphasis>emphasis</emphasis></title>
-    <section xml:id="level-3">
-      <title>Level 3</title>
-      <para>
-        with no blank line
-      </para>
-    </section>
-  </section>
-  <section xml:id="level-2">
-    <title>Level 2</title>
-    <para>
-      with no blank line
-    </para>
-  </section>
-</section>
-<section xml:id="paragraphs">
-  <title>Paragraphs</title>
-  <para>
-    Here’s a regular paragraph.
-  </para>
-  <para>
-    In Markdown 1.0.0 and earlier. Version 8. This line turns into a list
-    item. Because a hard-wrapped line in the middle of a paragraph looked like
-    a list item.
-  </para>
-  <para>
-    Here’s one with a bullet. * criminey.
-  </para>
-<literallayout>There should be a hard line break
-here.</literallayout>
-</section>
-<section xml:id="block-quotes">
-  <title>Block Quotes</title>
-  <para>
-    E-mail style:
-  </para>
-  <blockquote>
-    <para>
-      This is a block quote. It is pretty short.
-    </para>
-  </blockquote>
-  <blockquote>
-    <para>
-      Code in a block quote:
-    </para>
-    <programlisting>
-sub status {
-    print &quot;working&quot;;
-}
-</programlisting>
-    <para>
-      A list:
-    </para>
-    <orderedlist numeration="arabic" spacing="compact">
-      <listitem>
-        <para>
-          item one
-        </para>
-      </listitem>
-      <listitem>
-        <para>
-          item two
-        </para>
-      </listitem>
-    </orderedlist>
-    <para>
-      Nested block quotes:
-    </para>
-    <blockquote>
-      <para>
-        nested
-      </para>
-    </blockquote>
-    <blockquote>
-      <para>
-        nested
-      </para>
-    </blockquote>
-  </blockquote>
-  <para>
-    This should not be a block quote: 2 &gt; 1.
-  </para>
-  <para>
-    And a following paragraph.
-  </para>
-</section>
-<section xml:id="code-blocks">
-  <title>Code Blocks</title>
-  <para>
-    Code:
-  </para>
-  <programlisting>
----- (should be four hyphens)
-
-sub status {
-    print &quot;working&quot;;
-}
-
-this code block is indented by one tab
-</programlisting>
-  <para>
-    And:
-  </para>
-  <programlisting>
-    this code block is indented by two tabs
-
-These should not be escaped:  \$ \\ \&gt; \[ \{
-</programlisting>
-</section>
-<section xml:id="lists">
-  <title>Lists</title>
-  <section xml:id="unordered">
-    <title>Unordered</title>
-    <para>
-      Asterisks tight:
-    </para>
-    <itemizedlist spacing="compact">
-      <listitem>
-        <para>
-          asterisk 1
-        </para>
-      </listitem>
-      <listitem>
-        <para>
-          asterisk 2
-        </para>
-      </listitem>
-      <listitem>
-        <para>
-          asterisk 3
-        </para>
-      </listitem>
-    </itemizedlist>
-    <para>
-      Asterisks loose:
-    </para>
-    <itemizedlist>
-      <listitem>
-        <para>
-          asterisk 1
-        </para>
-      </listitem>
-      <listitem>
-        <para>
-          asterisk 2
-        </para>
-      </listitem>
-      <listitem>
-        <para>
-          asterisk 3
-        </para>
-      </listitem>
-    </itemizedlist>
-    <para>
-      Pluses tight:
-    </para>
-    <itemizedlist spacing="compact">
-      <listitem>
-        <para>
-          Plus 1
-        </para>
-      </listitem>
-      <listitem>
-        <para>
-          Plus 2
-        </para>
-      </listitem>
-      <listitem>
-        <para>
-          Plus 3
-        </para>
-      </listitem>
-    </itemizedlist>
-    <para>
-      Pluses loose:
-    </para>
-    <itemizedlist>
-      <listitem>
-        <para>
-          Plus 1
-        </para>
-      </listitem>
-      <listitem>
-        <para>
-          Plus 2
-        </para>
-      </listitem>
-      <listitem>
-        <para>
-          Plus 3
-        </para>
-      </listitem>
-    </itemizedlist>
-    <para>
-      Minuses tight:
-    </para>
-    <itemizedlist spacing="compact">
-      <listitem>
-        <para>
-          Minus 1
-        </para>
-      </listitem>
-      <listitem>
-        <para>
-          Minus 2
-        </para>
-      </listitem>
-      <listitem>
-        <para>
-          Minus 3
-        </para>
-      </listitem>
-    </itemizedlist>
-    <para>
-      Minuses loose:
-    </para>
-    <itemizedlist>
-      <listitem>
-        <para>
-          Minus 1
-        </para>
-      </listitem>
-      <listitem>
-        <para>
-          Minus 2
-        </para>
-      </listitem>
-      <listitem>
-        <para>
-          Minus 3
-        </para>
-      </listitem>
-    </itemizedlist>
-  </section>
-  <section xml:id="ordered">
-    <title>Ordered</title>
-    <para>
-      Tight:
-    </para>
-    <orderedlist numeration="arabic" spacing="compact">
-      <listitem>
-        <para>
-          First
-        </para>
-      </listitem>
-      <listitem>
-        <para>
-          Second
-        </para>
-      </listitem>
-      <listitem>
-        <para>
-          Third
-        </para>
-      </listitem>
-    </orderedlist>
-    <para>
-      and:
-    </para>
-    <orderedlist numeration="arabic" spacing="compact">
-      <listitem>
-        <para>
-          One
-        </para>
-      </listitem>
-      <listitem>
-        <para>
-          Two
-        </para>
-      </listitem>
-      <listitem>
-        <para>
-          Three
-        </para>
-      </listitem>
-    </orderedlist>
-    <para>
-      Loose using tabs:
-    </para>
-    <orderedlist numeration="arabic">
-      <listitem>
-        <para>
-          First
-        </para>
-      </listitem>
-      <listitem>
-        <para>
-          Second
-        </para>
-      </listitem>
-      <listitem>
-        <para>
-          Third
-        </para>
-      </listitem>
-    </orderedlist>
-    <para>
-      and using spaces:
-    </para>
-    <orderedlist numeration="arabic">
-      <listitem>
-        <para>
-          One
-        </para>
-      </listitem>
-      <listitem>
-        <para>
-          Two
-        </para>
-      </listitem>
-      <listitem>
-        <para>
-          Three
-        </para>
-      </listitem>
-    </orderedlist>
-    <para>
-      Multiple paragraphs:
-    </para>
-    <orderedlist numeration="arabic">
-      <listitem>
-        <para>
-          Item 1, graf one.
-        </para>
-        <para>
-          Item 1. graf two. The quick brown fox jumped over the lazy dog’s
-          back.
-        </para>
-      </listitem>
-      <listitem>
-        <para>
-          Item 2.
-        </para>
-      </listitem>
-      <listitem>
-        <para>
-          Item 3.
-        </para>
-      </listitem>
-    </orderedlist>
-  </section>
-  <section xml:id="nested">
-    <title>Nested</title>
-    <itemizedlist spacing="compact">
-      <listitem>
-        <para>
-          Tab
-        </para>
-        <itemizedlist spacing="compact">
-          <listitem>
-            <para>
-              Tab
-            </para>
-            <itemizedlist spacing="compact">
-              <listitem>
-                <para>
-                  Tab
-                </para>
-              </listitem>
-            </itemizedlist>
-          </listitem>
-        </itemizedlist>
-      </listitem>
-    </itemizedlist>
-    <para>
-      Here’s another:
-    </para>
-    <orderedlist numeration="arabic" spacing="compact">
-      <listitem>
-        <para>
-          First
-        </para>
-      </listitem>
-      <listitem>
-        <para>
-          Second:
-        </para>
-        <itemizedlist spacing="compact">
-          <listitem>
-            <para>
-              Fee
-            </para>
-          </listitem>
-          <listitem>
-            <para>
-              Fie
-            </para>
-          </listitem>
-          <listitem>
-            <para>
-              Foe
-            </para>
-          </listitem>
-        </itemizedlist>
-      </listitem>
-      <listitem>
-        <para>
-          Third
-        </para>
-      </listitem>
-    </orderedlist>
-    <para>
-      Same thing but with paragraphs:
-    </para>
-    <orderedlist numeration="arabic">
-      <listitem>
-        <para>
-          First
-        </para>
-      </listitem>
-      <listitem>
-        <para>
-          Second:
-        </para>
-        <itemizedlist spacing="compact">
-          <listitem>
-            <para>
-              Fee
-            </para>
-          </listitem>
-          <listitem>
-            <para>
-              Fie
-            </para>
-          </listitem>
-          <listitem>
-            <para>
-              Foe
-            </para>
-          </listitem>
-        </itemizedlist>
-      </listitem>
-      <listitem>
-        <para>
-          Third
-        </para>
-      </listitem>
-    </orderedlist>
-  </section>
-  <section xml:id="tabs-and-spaces">
-    <title>Tabs and spaces</title>
-    <itemizedlist>
-      <listitem>
-        <para>
-          this is a list item indented with tabs
-        </para>
-      </listitem>
-      <listitem>
-        <para>
-          this is a list item indented with spaces
-        </para>
-        <itemizedlist>
-          <listitem>
-            <para>
-              this is an example list item indented with tabs
-            </para>
-          </listitem>
-          <listitem>
-            <para>
-              this is an example list item indented with spaces
-            </para>
-          </listitem>
-        </itemizedlist>
-      </listitem>
-    </itemizedlist>
-  </section>
-  <section xml:id="fancy-list-markers">
-    <title>Fancy list markers</title>
-    <orderedlist numeration="arabic">
-      <listitem override="2">
-        <para>
-          begins with 2
-        </para>
-      </listitem>
-      <listitem>
-        <para>
-          and now 3
-        </para>
-        <para>
-          with a continuation
-        </para>
-        <orderedlist numeration="lowerroman" spacing="compact">
-          <listitem override="4">
-            <para>
-              sublist with roman numerals, starting with 4
-            </para>
-          </listitem>
-          <listitem>
-            <para>
-              more items
-            </para>
-            <orderedlist numeration="upperalpha" spacing="compact">
-              <listitem>
-                <para>
-                  a subsublist
-                </para>
-              </listitem>
-              <listitem>
-                <para>
-                  a subsublist
-                </para>
-              </listitem>
-            </orderedlist>
-          </listitem>
-        </orderedlist>
-      </listitem>
-    </orderedlist>
-    <para>
-      Nesting:
-    </para>
-    <orderedlist numeration="upperalpha" spacing="compact">
-      <listitem>
-        <para>
-          Upper Alpha
-        </para>
-        <orderedlist numeration="upperroman" spacing="compact">
-          <listitem>
-            <para>
-              Upper Roman.
-            </para>
-            <orderedlist numeration="arabic" spacing="compact">
-              <listitem override="6">
-                <para>
-                  Decimal start with 6
-                </para>
-                <orderedlist numeration="loweralpha" spacing="compact">
-                  <listitem override="3">
-                    <para>
-                      Lower alpha with paren
-                    </para>
-                  </listitem>
-                </orderedlist>
-              </listitem>
-            </orderedlist>
-          </listitem>
-        </orderedlist>
-      </listitem>
-    </orderedlist>
-    <para>
-      Autonumbering:
-    </para>
-    <orderedlist spacing="compact">
-      <listitem>
-        <para>
-          Autonumber.
-        </para>
-      </listitem>
-      <listitem>
-        <para>
-          More.
-        </para>
-        <orderedlist spacing="compact">
-          <listitem>
-            <para>
-              Nested.
-            </para>
-          </listitem>
-        </orderedlist>
-      </listitem>
-    </orderedlist>
-    <para>
-      Should not be a list item:
-    </para>
-    <para>
-      M.A. 2007
-    </para>
-    <para>
-      B. Williams
-    </para>
-  </section>
-</section>
-<section xml:id="definition-lists">
-  <title>Definition Lists</title>
-  <para>
-    Tight using spaces:
-  </para>
-  <variablelist spacing="compact">
-    <varlistentry>
-      <term>
-        apple
-      </term>
-      <listitem>
-        <para>
-          red fruit
-        </para>
-      </listitem>
-    </varlistentry>
-    <varlistentry>
-      <term>
-        orange
-      </term>
-      <listitem>
-        <para>
-          orange fruit
-        </para>
-      </listitem>
-    </varlistentry>
-    <varlistentry>
-      <term>
-        banana
-      </term>
-      <listitem>
-        <para>
-          yellow fruit
-        </para>
-      </listitem>
-    </varlistentry>
-  </variablelist>
-  <para>
-    Tight using tabs:
-  </para>
-  <variablelist spacing="compact">
-    <varlistentry>
-      <term>
-        apple
-      </term>
-      <listitem>
-        <para>
-          red fruit
-        </para>
-      </listitem>
-    </varlistentry>
-    <varlistentry>
-      <term>
-        orange
-      </term>
-      <listitem>
-        <para>
-          orange fruit
-        </para>
-      </listitem>
-    </varlistentry>
-    <varlistentry>
-      <term>
-        banana
-      </term>
-      <listitem>
-        <para>
-          yellow fruit
-        </para>
-      </listitem>
-    </varlistentry>
-  </variablelist>
-  <para>
-    Loose:
-  </para>
-  <variablelist>
-    <varlistentry>
-      <term>
-        apple
-      </term>
-      <listitem>
-        <para>
-          red fruit
-        </para>
-      </listitem>
-    </varlistentry>
-    <varlistentry>
-      <term>
-        orange
-      </term>
-      <listitem>
-        <para>
-          orange fruit
-        </para>
-      </listitem>
-    </varlistentry>
-    <varlistentry>
-      <term>
-        banana
-      </term>
-      <listitem>
-        <para>
-          yellow fruit
-        </para>
-      </listitem>
-    </varlistentry>
-  </variablelist>
-  <para>
-    Multiple blocks with italics:
-  </para>
-  <variablelist>
-    <varlistentry>
-      <term>
-        <emphasis>apple</emphasis>
-      </term>
-      <listitem>
-        <para>
-          red fruit
-        </para>
-        <para>
-          contains seeds, crisp, pleasant to taste
-        </para>
-      </listitem>
-    </varlistentry>
-    <varlistentry>
-      <term>
-        <emphasis>orange</emphasis>
-      </term>
-      <listitem>
-        <para>
-          orange fruit
-        </para>
-        <programlisting>
-{ orange code block }
-</programlisting>
-        <blockquote>
-          <para>
-            orange block quote
-          </para>
-        </blockquote>
-      </listitem>
-    </varlistentry>
-  </variablelist>
-  <para>
-    Multiple definitions, tight:
-  </para>
-  <variablelist spacing="compact">
-    <varlistentry>
-      <term>
-        apple
-      </term>
-      <listitem>
-        <para>
-          red fruit
-        </para>
-        <para>
-          computer
-        </para>
-      </listitem>
-    </varlistentry>
-    <varlistentry>
-      <term>
-        orange
-      </term>
-      <listitem>
-        <para>
-          orange fruit
-        </para>
-        <para>
-          bank
-        </para>
-      </listitem>
-    </varlistentry>
-  </variablelist>
-  <para>
-    Multiple definitions, loose:
-  </para>
-  <variablelist>
-    <varlistentry>
-      <term>
-        apple
-      </term>
-      <listitem>
-        <para>
-          red fruit
-        </para>
-        <para>
-          computer
-        </para>
-      </listitem>
-    </varlistentry>
-    <varlistentry>
-      <term>
-        orange
-      </term>
-      <listitem>
-        <para>
-          orange fruit
-        </para>
-        <para>
-          bank
-        </para>
-      </listitem>
-    </varlistentry>
-  </variablelist>
-  <para>
-    Blank line after term, indented marker, alternate markers:
-  </para>
-  <variablelist>
-    <varlistentry>
-      <term>
-        apple
-      </term>
-      <listitem>
-        <para>
-          red fruit
-        </para>
-        <para>
-          computer
-        </para>
-      </listitem>
-    </varlistentry>
-    <varlistentry>
-      <term>
-        orange
-      </term>
-      <listitem>
-        <para>
-          orange fruit
-        </para>
-        <orderedlist numeration="arabic" spacing="compact">
-          <listitem>
-            <para>
-              sublist
-            </para>
-          </listitem>
-          <listitem>
-            <para>
-              sublist
-            </para>
-          </listitem>
-        </orderedlist>
-      </listitem>
-    </varlistentry>
-  </variablelist>
-</section>
-<section xml:id="html-blocks">
-  <title>HTML Blocks</title>
-  <para>
-    Simple block on one line:
-  </para>
-  <para>
-    foo
-  </para>
-  <para>
-    And nested without indentation:
-  </para>
-  <para>
-    foo
-  </para>
-  <para>
-    bar
-  </para>
-  <para>
-    Interpreted markdown in a table:
-  </para>
-  This is <emphasis>emphasized</emphasis>
-  And this is <emphasis role="strong">strong</emphasis>
-  <para>
-    Here’s a simple block:
-  </para>
-  <para>
-    foo
-  </para>
-  <para>
-    This should be a code block, though:
-  </para>
-  <programlisting>
-&lt;div&gt;
-    foo
-&lt;/div&gt;
-</programlisting>
-  <para>
-    As should this:
-  </para>
-  <programlisting>
-&lt;div&gt;foo&lt;/div&gt;
-</programlisting>
-  <para>
-    Now, nested:
-  </para>
-  <para>
-    foo
-  </para>
-  <para>
-    This should just be an HTML comment:
-  </para>
-  <para>
-    Multiline:
-  </para>
-  <para>
-    Code block:
-  </para>
-  <programlisting>
-&lt;!-- Comment --&gt;
-</programlisting>
-  <para>
-    Just plain comment, with trailing spaces on the line:
-  </para>
-  <para>
-    Code:
-  </para>
-  <programlisting>
-&lt;hr /&gt;
-</programlisting>
-  <para>
-    Hr’s:
-  </para>
-</section>
-<section xml:id="inline-markup">
-  <title>Inline Markup</title>
-  <para>
-    This is <emphasis>emphasized</emphasis>, and so <emphasis>is
-    this</emphasis>.
-  </para>
-  <para>
-    This is <emphasis role="strong">strong</emphasis>, and so
-    <emphasis role="strong">is this</emphasis>.
-  </para>
-  <para>
-    An <emphasis><link xlink:href="/url">emphasized link</link></emphasis>.
-  </para>
-  <para>
-    <emphasis role="strong"><emphasis>This is strong and
-    em.</emphasis></emphasis>
-  </para>
-  <para>
-    So is <emphasis role="strong"><emphasis>this</emphasis></emphasis> word.
-  </para>
-  <para>
-    <emphasis role="strong"><emphasis>This is strong and
-    em.</emphasis></emphasis>
-  </para>
-  <para>
-    So is <emphasis role="strong"><emphasis>this</emphasis></emphasis> word.
-  </para>
-  <para>
-    This is code: <literal>&gt;</literal>, <literal>$</literal>,
-    <literal>\</literal>, <literal>\$</literal>,
-    <literal>&lt;html&gt;</literal>.
-  </para>
-  <para>
-    <emphasis role="strikethrough">This is
-    <emphasis>strikeout</emphasis>.</emphasis>
-  </para>
-  <para>
-    Superscripts: a<superscript>bc</superscript>d
-    a<superscript><emphasis>hello</emphasis></superscript>
-    a<superscript>hello there</superscript>.
-  </para>
-  <para>
-    Subscripts: H<subscript>2</subscript>O, H<subscript>23</subscript>O,
-    H<subscript>many of them</subscript>O.
-  </para>
-  <para>
-    These should not be superscripts or subscripts, because of the unescaped
-    spaces: a^b c^d, a~b c~d.
-  </para>
-</section>
-<section xml:id="smart-quotes-ellipses-dashes">
-  <title>Smart quotes, ellipses, dashes</title>
-  <para>
-    <quote>Hello,</quote> said the spider. <quote><quote>Shelob</quote> is my
-    name.</quote>
-  </para>
-  <para>
-    <quote>A</quote>, <quote>B</quote>, and <quote>C</quote> are letters.
-  </para>
-  <para>
-    <quote>Oak,</quote> <quote>elm,</quote> and <quote>beech</quote> are names
-    of trees. So is <quote>pine.</quote>
-  </para>
-  <para>
-    <quote>He said, <quote>I want to go.</quote></quote> Were you alive in the
-    70’s?
-  </para>
-  <para>
-    Here is some quoted <quote><literal>code</literal></quote> and a
-    <quote><link xlink:href="http://example.com/?foo=1&amp;bar=2">quoted
-    link</link></quote>.
-  </para>
-  <para>
-    Some dashes: one—two — three—four — five.
-  </para>
-  <para>
-    Dashes between numbers: 5–7, 255–66, 1987–1999.
-  </para>
-  <para>
-    Ellipses…and…and….
-  </para>
-</section>
-<section xml:id="latex">
-  <title>LaTeX</title>
-  <itemizedlist spacing="compact">
-    <listitem>
-      <para>
-      </para>
-    </listitem>
-    <listitem>
-      <para>
-        2 + 2 = 4
-      </para>
-    </listitem>
-    <listitem>
-      <para>
-        <emphasis>x</emphasis> ∈ <emphasis>y</emphasis>
-      </para>
-    </listitem>
-    <listitem>
-      <para>
-        <emphasis>α</emphasis> ∧ <emphasis>ω</emphasis>
-      </para>
-    </listitem>
-    <listitem>
-      <para>
-        223
-      </para>
-    </listitem>
-    <listitem>
-      <para>
-        <emphasis>p</emphasis>-Tree
-      </para>
-    </listitem>
-    <listitem>
-      <para>
-        Here’s some display math:
-        $$\frac{d}{dx}f(x)=\lim_{h\to 0}\frac{f(x+h)-f(x)}{h}$$
-      </para>
-    </listitem>
-    <listitem>
-      <para>
-        Here’s one that has a line break in it:
-        <emphasis>α</emphasis> + <emphasis>ω</emphasis> × <emphasis>x</emphasis><superscript>2</superscript>.
-      </para>
-    </listitem>
-  </itemizedlist>
-  <para>
-    These shouldn’t be math:
-  </para>
-  <itemizedlist spacing="compact">
-    <listitem>
-      <para>
-        To get the famous equation, write <literal>$e = mc^2$</literal>.
-      </para>
-    </listitem>
-    <listitem>
-      <para>
-        $22,000 is a <emphasis>lot</emphasis> of money. So is $34,000. (It
-        worked if <quote>lot</quote> is emphasized.)
-      </para>
-    </listitem>
-    <listitem>
-      <para>
-        Shoes ($20) and socks ($5).
-      </para>
-    </listitem>
-    <listitem>
-      <para>
-        Escaped <literal>$</literal>: $73 <emphasis>this should be
-        emphasized</emphasis> 23$.
-      </para>
-    </listitem>
-  </itemizedlist>
-  <para>
-    Here’s a LaTeX table:
-  </para>
-</section>
-<section xml:id="special-characters">
-  <title>Special Characters</title>
-  <para>
-    Here is some unicode:
-  </para>
-  <itemizedlist spacing="compact">
-    <listitem>
-      <para>
-        I hat: Î
-      </para>
-    </listitem>
-    <listitem>
-      <para>
-        o umlaut: ö
-      </para>
-    </listitem>
-    <listitem>
-      <para>
-        section: §
-      </para>
-    </listitem>
-    <listitem>
-      <para>
-        set membership: ∈
-      </para>
-    </listitem>
-    <listitem>
-      <para>
-        copyright: ©
-      </para>
-    </listitem>
-  </itemizedlist>
-  <para>
-    AT&amp;T has an ampersand in their name.
-  </para>
-  <para>
-    AT&amp;T is another way to write it.
-  </para>
-  <para>
-    This &amp; that.
-  </para>
-  <para>
-    4 &lt; 5.
-  </para>
-  <para>
-    6 &gt; 5.
-  </para>
-  <para>
-    Backslash: \
-  </para>
-  <para>
-    Backtick: `
-  </para>
-  <para>
-    Asterisk: *
-  </para>
-  <para>
-    Underscore: _
-  </para>
-  <para>
-    Left brace: {
-  </para>
-  <para>
-    Right brace: }
-  </para>
-  <para>
-    Left bracket: [
-  </para>
-  <para>
-    Right bracket: ]
-  </para>
-  <para>
-    Left paren: (
-  </para>
-  <para>
-    Right paren: )
-  </para>
-  <para>
-    Greater-than: &gt;
-  </para>
-  <para>
-    Hash: #
-  </para>
-  <para>
-    Period: .
-  </para>
-  <para>
-    Bang: !
-  </para>
-  <para>
-    Plus: +
-  </para>
-  <para>
-    Minus: -
-  </para>
-</section>
-<section xml:id="links">
-  <title>Links</title>
-  <section xml:id="explicit">
-    <title>Explicit</title>
-    <para>
-      Just a <link xlink:href="/url/">URL</link>.
-    </para>
-    <para>
-      <link xlink:href="/url/">URL and title</link>.
-    </para>
-    <para>
-      <link xlink:href="/url/">URL and title</link>.
-    </para>
-    <para>
-      <link xlink:href="/url/">URL and title</link>.
-    </para>
-    <para>
-      <link xlink:href="/url/">URL and title</link>
-    </para>
-    <para>
-      <link xlink:href="/url/">URL and title</link>
-    </para>
-    <para>
-      <link xlink:href="/url/with_underscore">with_underscore</link>
-    </para>
-    <para>
-      Email link (<email>nobody@nowhere.net</email>)
-    </para>
-    <para>
-      <link xlink:href="">Empty</link>.
-    </para>
-  </section>
-  <section xml:id="reference">
-    <title>Reference</title>
-    <para>
-      Foo <link xlink:href="/url/">bar</link>.
-    </para>
-    <para>
-      With <link xlink:href="/url/">embedded [brackets]</link>.
-    </para>
-    <para>
-      <link xlink:href="/url/">b</link> by itself should be a link.
-    </para>
-    <para>
-      Indented <link xlink:href="/url">once</link>.
-    </para>
-    <para>
-      Indented <link xlink:href="/url">twice</link>.
-    </para>
-    <para>
-      Indented <link xlink:href="/url">thrice</link>.
-    </para>
-    <para>
-      This should [not][] be a link.
-    </para>
-    <programlisting>
-[not]: /url
-</programlisting>
-    <para>
-      Foo <link xlink:href="/url/">bar</link>.
-    </para>
-    <para>
-      Foo <link xlink:href="/url/">biz</link>.
-    </para>
-  </section>
-  <section xml:id="with-ampersands">
-    <title>With ampersands</title>
-    <para>
-      Here’s a <link xlink:href="http://example.com/?foo=1&amp;bar=2">link
-      with an ampersand in the URL</link>.
-    </para>
-    <para>
-      Here’s a link with an amersand in the link text:
-      <link xlink:href="http://att.com/">AT&amp;T</link>.
-    </para>
-    <para>
-      Here’s an <link xlink:href="/script?foo=1&amp;bar=2">inline link</link>.
-    </para>
-    <para>
-      Here’s an <link xlink:href="/script?foo=1&amp;bar=2">inline link in
-      pointy braces</link>.
-    </para>
-  </section>
-  <section xml:id="autolinks">
-    <title>Autolinks</title>
-    <para>
-      With an ampersand:
-      <link xlink:href="http://example.com/?foo=1&amp;bar=2">http://example.com/?foo=1&amp;bar=2</link>
-    </para>
-    <itemizedlist spacing="compact">
-      <listitem>
-        <para>
-          In a list?
-        </para>
-      </listitem>
-      <listitem>
-        <para>
-          <link xlink:href="http://example.com/">http://example.com/</link>
-        </para>
-      </listitem>
-      <listitem>
-        <para>
-          It should.
-        </para>
-      </listitem>
-    </itemizedlist>
-    <para>
-      An e-mail address: <email>nobody@nowhere.net</email>
-    </para>
-    <blockquote>
-      <para>
-        Blockquoted:
-        <link xlink:href="http://example.com/">http://example.com/</link>
-      </para>
-    </blockquote>
-    <para>
-      Auto-links should not occur here:
-      <literal>&lt;http://example.com/&gt;</literal>
-    </para>
-    <programlisting>
-or here: &lt;http://example.com/&gt;
-</programlisting>
-  </section>
-</section>
-<section xml:id="images">
-  <title>Images</title>
-  <para>
-    From <quote>Voyage dans la Lune</quote> by Georges Melies (1902):
-  </para>
-  <figure>
-    <title>lalune</title>
-    <mediaobject>
-      <imageobject>
-        <imagedata fileref="lalune.jpg" />
-      </imageobject>
-      <textobject><phrase>lalune</phrase></textobject>
-    </mediaobject>
-  </figure>
-  <para>
-    Here is a movie <inlinemediaobject>
-      <imageobject>
-        <imagedata fileref="movie.jpg" />
-      </imageobject>
-    </inlinemediaobject> icon.
-  </para>
-</section>
-<section xml:id="footnotes">
-  <title>Footnotes</title>
-  <para>
-    Here is a footnote reference,<footnote>
-      <para>
-        Here is the footnote. It can go anywhere after the footnote reference.
-        It need not be placed at the end of the document.
-      </para>
-    </footnote> and another.<footnote>
-      <para>
-        Here’s the long note. This one contains multiple blocks.
-      </para>
-      <para>
-        Subsequent blocks are indented to show that they belong to the
-        footnote (as with list items).
-      </para>
-      <programlisting>
-  { &lt;code&gt; }
-</programlisting>
-      <para>
-        If you want, you can indent every line, but you can also be lazy and
-        just indent the first line of each block.
-      </para>
-    </footnote> This should <emphasis>not</emphasis> be a footnote reference,
-    because it contains a space.[^my note] Here is an inline note.<footnote>
-      <para>
-        This is <emphasis>easier</emphasis> to type. Inline notes may contain
-        <link xlink:href="http://google.com">links</link> and
-        <literal>]</literal> verbatim characters, as well as [bracketed text].
-      </para>
-    </footnote>
-  </para>
-  <blockquote>
-    <para>
-      Notes can go in quotes.<footnote>
-        <para>
-          In quote.
-        </para>
-      </footnote>
-    </para>
-  </blockquote>
-  <orderedlist numeration="arabic" spacing="compact">
-    <listitem>
-      <para>
-        And in list items.<footnote>
-          <para>
-            In list.
-          </para>
-        </footnote>
-      </para>
-    </listitem>
-  </orderedlist>
-  <para>
-    This paragraph should not be part of the note, as it is not indented.
-  </para>
-</section>
+        <personname>
+          <firstname>John</firstname>
+          <surname>MacFarlane</surname>
+        </personname>
+      </author>
+      <author>
+        <personname>
+          <firstname></firstname>
+          <surname>Anonymous</surname>
+        </personname>
+      </author>
+    </authorgroup>
+    <date>July 17, 2006</date>
+  </info>
+  <para>
+    This is a set of tests for pandoc. Most of them are adapted from John
+    Gruber’s markdown test suite.
+  </para>
+  <section xml:id="headers">
+    <title>Headers</title>
+    <section xml:id="level-2-with-an-embedded-link">
+      <title>Level 2 with an <link xlink:href="/url">embedded
+      link</link></title>
+      <section xml:id="level-3-with-emphasis">
+        <title>Level 3 with <emphasis>emphasis</emphasis></title>
+        <section xml:id="level-4">
+          <title>Level 4</title>
+          <section xml:id="level-5">
+            <title>Level 5</title>
+            <para>
+            </para>
+          </section>
+        </section>
+      </section>
+    </section>
+  </section>
+  <section xml:id="level-1">
+    <title>Level 1</title>
+    <section xml:id="level-2-with-emphasis">
+      <title>Level 2 with <emphasis>emphasis</emphasis></title>
+      <section xml:id="level-3">
+        <title>Level 3</title>
+        <para>
+          with no blank line
+        </para>
+      </section>
+    </section>
+    <section xml:id="level-2">
+      <title>Level 2</title>
+      <para>
+        with no blank line
+      </para>
+    </section>
+  </section>
+  <section xml:id="paragraphs">
+    <title>Paragraphs</title>
+    <para>
+      Here’s a regular paragraph.
+    </para>
+    <para>
+      In Markdown 1.0.0 and earlier. Version 8. This line turns into a list
+      item. Because a hard-wrapped line in the middle of a paragraph looked like
+      a list item.
+    </para>
+    <para>
+      Here’s one with a bullet. * criminey.
+    </para>
+<literallayout>There should be a hard line break
+here.</literallayout>
+  </section>
+  <section xml:id="block-quotes">
+    <title>Block Quotes</title>
+    <para>
+      E-mail style:
+    </para>
+    <blockquote>
+      <para>
+        This is a block quote. It is pretty short.
+      </para>
+    </blockquote>
+    <blockquote>
+      <para>
+        Code in a block quote:
+      </para>
+      <programlisting>
+sub status {
+    print &quot;working&quot;;
+}
+</programlisting>
+      <para>
+        A list:
+      </para>
+      <orderedlist numeration="arabic" spacing="compact">
+        <listitem>
+          <para>
+            item one
+          </para>
+        </listitem>
+        <listitem>
+          <para>
+            item two
+          </para>
+        </listitem>
+      </orderedlist>
+      <para>
+        Nested block quotes:
+      </para>
+      <blockquote>
+        <para>
+          nested
+        </para>
+      </blockquote>
+      <blockquote>
+        <para>
+          nested
+        </para>
+      </blockquote>
+    </blockquote>
+    <para>
+      This should not be a block quote: 2 &gt; 1.
+    </para>
+    <para>
+      And a following paragraph.
+    </para>
+  </section>
+  <section xml:id="code-blocks">
+    <title>Code Blocks</title>
+    <para>
+      Code:
+    </para>
+    <programlisting>
+---- (should be four hyphens)
+
+sub status {
+    print &quot;working&quot;;
+}
+
+this code block is indented by one tab
+</programlisting>
+    <para>
+      And:
+    </para>
+    <programlisting>
+    this code block is indented by two tabs
+
+These should not be escaped:  \$ \\ \&gt; \[ \{
+</programlisting>
+  </section>
+  <section xml:id="lists">
+    <title>Lists</title>
+    <section xml:id="unordered">
+      <title>Unordered</title>
+      <para>
+        Asterisks tight:
+      </para>
+      <itemizedlist spacing="compact">
+        <listitem>
+          <para>
+            asterisk 1
+          </para>
+        </listitem>
+        <listitem>
+          <para>
+            asterisk 2
+          </para>
+        </listitem>
+        <listitem>
+          <para>
+            asterisk 3
+          </para>
+        </listitem>
+      </itemizedlist>
+      <para>
+        Asterisks loose:
+      </para>
+      <itemizedlist>
+        <listitem>
+          <para>
+            asterisk 1
+          </para>
+        </listitem>
+        <listitem>
+          <para>
+            asterisk 2
+          </para>
+        </listitem>
+        <listitem>
+          <para>
+            asterisk 3
+          </para>
+        </listitem>
+      </itemizedlist>
+      <para>
+        Pluses tight:
+      </para>
+      <itemizedlist spacing="compact">
+        <listitem>
+          <para>
+            Plus 1
+          </para>
+        </listitem>
+        <listitem>
+          <para>
+            Plus 2
+          </para>
+        </listitem>
+        <listitem>
+          <para>
+            Plus 3
+          </para>
+        </listitem>
+      </itemizedlist>
+      <para>
+        Pluses loose:
+      </para>
+      <itemizedlist>
+        <listitem>
+          <para>
+            Plus 1
+          </para>
+        </listitem>
+        <listitem>
+          <para>
+            Plus 2
+          </para>
+        </listitem>
+        <listitem>
+          <para>
+            Plus 3
+          </para>
+        </listitem>
+      </itemizedlist>
+      <para>
+        Minuses tight:
+      </para>
+      <itemizedlist spacing="compact">
+        <listitem>
+          <para>
+            Minus 1
+          </para>
+        </listitem>
+        <listitem>
+          <para>
+            Minus 2
+          </para>
+        </listitem>
+        <listitem>
+          <para>
+            Minus 3
+          </para>
+        </listitem>
+      </itemizedlist>
+      <para>
+        Minuses loose:
+      </para>
+      <itemizedlist>
+        <listitem>
+          <para>
+            Minus 1
+          </para>
+        </listitem>
+        <listitem>
+          <para>
+            Minus 2
+          </para>
+        </listitem>
+        <listitem>
+          <para>
+            Minus 3
+          </para>
+        </listitem>
+      </itemizedlist>
+    </section>
+    <section xml:id="ordered">
+      <title>Ordered</title>
+      <para>
+        Tight:
+      </para>
+      <orderedlist numeration="arabic" spacing="compact">
+        <listitem>
+          <para>
+            First
+          </para>
+        </listitem>
+        <listitem>
+          <para>
+            Second
+          </para>
+        </listitem>
+        <listitem>
+          <para>
+            Third
+          </para>
+        </listitem>
+      </orderedlist>
+      <para>
+        and:
+      </para>
+      <orderedlist numeration="arabic" spacing="compact">
+        <listitem>
+          <para>
+            One
+          </para>
+        </listitem>
+        <listitem>
+          <para>
+            Two
+          </para>
+        </listitem>
+        <listitem>
+          <para>
+            Three
+          </para>
+        </listitem>
+      </orderedlist>
+      <para>
+        Loose using tabs:
+      </para>
+      <orderedlist numeration="arabic">
+        <listitem>
+          <para>
+            First
+          </para>
+        </listitem>
+        <listitem>
+          <para>
+            Second
+          </para>
+        </listitem>
+        <listitem>
+          <para>
+            Third
+          </para>
+        </listitem>
+      </orderedlist>
+      <para>
+        and using spaces:
+      </para>
+      <orderedlist numeration="arabic">
+        <listitem>
+          <para>
+            One
+          </para>
+        </listitem>
+        <listitem>
+          <para>
+            Two
+          </para>
+        </listitem>
+        <listitem>
+          <para>
+            Three
+          </para>
+        </listitem>
+      </orderedlist>
+      <para>
+        Multiple paragraphs:
+      </para>
+      <orderedlist numeration="arabic">
+        <listitem>
+          <para>
+            Item 1, graf one.
+          </para>
+          <para>
+            Item 1. graf two. The quick brown fox jumped over the lazy dog’s
+            back.
+          </para>
+        </listitem>
+        <listitem>
+          <para>
+            Item 2.
+          </para>
+        </listitem>
+        <listitem>
+          <para>
+            Item 3.
+          </para>
+        </listitem>
+      </orderedlist>
+    </section>
+    <section xml:id="nested">
+      <title>Nested</title>
+      <itemizedlist spacing="compact">
+        <listitem>
+          <para>
+            Tab
+          </para>
+          <itemizedlist spacing="compact">
+            <listitem>
+              <para>
+                Tab
+              </para>
+              <itemizedlist spacing="compact">
+                <listitem>
+                  <para>
+                    Tab
+                  </para>
+                </listitem>
+              </itemizedlist>
+            </listitem>
+          </itemizedlist>
+        </listitem>
+      </itemizedlist>
+      <para>
+        Here’s another:
+      </para>
+      <orderedlist numeration="arabic" spacing="compact">
+        <listitem>
+          <para>
+            First
+          </para>
+        </listitem>
+        <listitem>
+          <para>
+            Second:
+          </para>
+          <itemizedlist spacing="compact">
+            <listitem>
+              <para>
+                Fee
+              </para>
+            </listitem>
+            <listitem>
+              <para>
+                Fie
+              </para>
+            </listitem>
+            <listitem>
+              <para>
+                Foe
+              </para>
+            </listitem>
+          </itemizedlist>
+        </listitem>
+        <listitem>
+          <para>
+            Third
+          </para>
+        </listitem>
+      </orderedlist>
+      <para>
+        Same thing but with paragraphs:
+      </para>
+      <orderedlist numeration="arabic">
+        <listitem>
+          <para>
+            First
+          </para>
+        </listitem>
+        <listitem>
+          <para>
+            Second:
+          </para>
+          <itemizedlist spacing="compact">
+            <listitem>
+              <para>
+                Fee
+              </para>
+            </listitem>
+            <listitem>
+              <para>
+                Fie
+              </para>
+            </listitem>
+            <listitem>
+              <para>
+                Foe
+              </para>
+            </listitem>
+          </itemizedlist>
+        </listitem>
+        <listitem>
+          <para>
+            Third
+          </para>
+        </listitem>
+      </orderedlist>
+    </section>
+    <section xml:id="tabs-and-spaces">
+      <title>Tabs and spaces</title>
+      <itemizedlist>
+        <listitem>
+          <para>
+            this is a list item indented with tabs
+          </para>
+        </listitem>
+        <listitem>
+          <para>
+            this is a list item indented with spaces
+          </para>
+          <itemizedlist>
+            <listitem>
+              <para>
+                this is an example list item indented with tabs
+              </para>
+            </listitem>
+            <listitem>
+              <para>
+                this is an example list item indented with spaces
+              </para>
+            </listitem>
+          </itemizedlist>
+        </listitem>
+      </itemizedlist>
+    </section>
+    <section xml:id="fancy-list-markers">
+      <title>Fancy list markers</title>
+      <orderedlist numeration="arabic" startingnumber="2">
+        <listitem>
+          <para>
+            begins with 2
+          </para>
+        </listitem>
+        <listitem>
+          <para>
+            and now 3
+          </para>
+          <para>
+            with a continuation
+          </para>
+          <orderedlist numeration="lowerroman" spacing="compact" startingnumber="4">
+            <listitem>
+              <para>
+                sublist with roman numerals, starting with 4
+              </para>
+            </listitem>
+            <listitem>
+              <para>
+                more items
+              </para>
+              <orderedlist numeration="upperalpha" spacing="compact">
+                <listitem>
+                  <para>
+                    a subsublist
+                  </para>
+                </listitem>
+                <listitem>
+                  <para>
+                    a subsublist
+                  </para>
+                </listitem>
+              </orderedlist>
+            </listitem>
+          </orderedlist>
+        </listitem>
+      </orderedlist>
+      <para>
+        Nesting:
+      </para>
+      <orderedlist numeration="upperalpha" spacing="compact">
+        <listitem>
+          <para>
+            Upper Alpha
+          </para>
+          <orderedlist numeration="upperroman" spacing="compact">
+            <listitem>
+              <para>
+                Upper Roman.
+              </para>
+              <orderedlist numeration="arabic" spacing="compact" startingnumber="6">
+                <listitem>
+                  <para>
+                    Decimal start with 6
+                  </para>
+                  <orderedlist numeration="loweralpha" spacing="compact" startingnumber="3">
+                    <listitem>
+                      <para>
+                        Lower alpha with paren
+                      </para>
+                    </listitem>
+                  </orderedlist>
+                </listitem>
+              </orderedlist>
+            </listitem>
+          </orderedlist>
+        </listitem>
+      </orderedlist>
+      <para>
+        Autonumbering:
+      </para>
+      <orderedlist spacing="compact">
+        <listitem>
+          <para>
+            Autonumber.
+          </para>
+        </listitem>
+        <listitem>
+          <para>
+            More.
+          </para>
+          <orderedlist spacing="compact">
+            <listitem>
+              <para>
+                Nested.
+              </para>
+            </listitem>
+          </orderedlist>
+        </listitem>
+      </orderedlist>
+      <para>
+        Should not be a list item:
+      </para>
+      <para>
+        M.A. 2007
+      </para>
+      <para>
+        B. Williams
+      </para>
+    </section>
+  </section>
+  <section xml:id="definition-lists">
+    <title>Definition Lists</title>
+    <para>
+      Tight using spaces:
+    </para>
+    <variablelist spacing="compact">
+      <varlistentry>
+        <term>
+          apple
+        </term>
+        <listitem>
+          <para>
+            red fruit
+          </para>
+        </listitem>
+      </varlistentry>
+      <varlistentry>
+        <term>
+          orange
+        </term>
+        <listitem>
+          <para>
+            orange fruit
+          </para>
+        </listitem>
+      </varlistentry>
+      <varlistentry>
+        <term>
+          banana
+        </term>
+        <listitem>
+          <para>
+            yellow fruit
+          </para>
+        </listitem>
+      </varlistentry>
+    </variablelist>
+    <para>
+      Tight using tabs:
+    </para>
+    <variablelist spacing="compact">
+      <varlistentry>
+        <term>
+          apple
+        </term>
+        <listitem>
+          <para>
+            red fruit
+          </para>
+        </listitem>
+      </varlistentry>
+      <varlistentry>
+        <term>
+          orange
+        </term>
+        <listitem>
+          <para>
+            orange fruit
+          </para>
+        </listitem>
+      </varlistentry>
+      <varlistentry>
+        <term>
+          banana
+        </term>
+        <listitem>
+          <para>
+            yellow fruit
+          </para>
+        </listitem>
+      </varlistentry>
+    </variablelist>
+    <para>
+      Loose:
+    </para>
+    <variablelist>
+      <varlistentry>
+        <term>
+          apple
+        </term>
+        <listitem>
+          <para>
+            red fruit
+          </para>
+        </listitem>
+      </varlistentry>
+      <varlistentry>
+        <term>
+          orange
+        </term>
+        <listitem>
+          <para>
+            orange fruit
+          </para>
+        </listitem>
+      </varlistentry>
+      <varlistentry>
+        <term>
+          banana
+        </term>
+        <listitem>
+          <para>
+            yellow fruit
+          </para>
+        </listitem>
+      </varlistentry>
+    </variablelist>
+    <para>
+      Multiple blocks with italics:
+    </para>
+    <variablelist>
+      <varlistentry>
+        <term>
+          <emphasis>apple</emphasis>
+        </term>
+        <listitem>
+          <para>
+            red fruit
+          </para>
+          <para>
+            contains seeds, crisp, pleasant to taste
+          </para>
+        </listitem>
+      </varlistentry>
+      <varlistentry>
+        <term>
+          <emphasis>orange</emphasis>
+        </term>
+        <listitem>
+          <para>
+            orange fruit
+          </para>
+          <programlisting>
+{ orange code block }
+</programlisting>
+          <blockquote>
+            <para>
+              orange block quote
+            </para>
+          </blockquote>
+        </listitem>
+      </varlistentry>
+    </variablelist>
+    <para>
+      Multiple definitions, tight:
+    </para>
+    <variablelist spacing="compact">
+      <varlistentry>
+        <term>
+          apple
+        </term>
+        <listitem>
+          <para>
+            red fruit
+          </para>
+          <para>
+            computer
+          </para>
+        </listitem>
+      </varlistentry>
+      <varlistentry>
+        <term>
+          orange
+        </term>
+        <listitem>
+          <para>
+            orange fruit
+          </para>
+          <para>
+            bank
+          </para>
+        </listitem>
+      </varlistentry>
+    </variablelist>
+    <para>
+      Multiple definitions, loose:
+    </para>
+    <variablelist>
+      <varlistentry>
+        <term>
+          apple
+        </term>
+        <listitem>
+          <para>
+            red fruit
+          </para>
+          <para>
+            computer
+          </para>
+        </listitem>
+      </varlistentry>
+      <varlistentry>
+        <term>
+          orange
+        </term>
+        <listitem>
+          <para>
+            orange fruit
+          </para>
+          <para>
+            bank
+          </para>
+        </listitem>
+      </varlistentry>
+    </variablelist>
+    <para>
+      Blank line after term, indented marker, alternate markers:
+    </para>
+    <variablelist>
+      <varlistentry>
+        <term>
+          apple
+        </term>
+        <listitem>
+          <para>
+            red fruit
+          </para>
+          <para>
+            computer
+          </para>
+        </listitem>
+      </varlistentry>
+      <varlistentry>
+        <term>
+          orange
+        </term>
+        <listitem>
+          <para>
+            orange fruit
+          </para>
+          <orderedlist numeration="arabic" spacing="compact">
+            <listitem>
+              <para>
+                sublist
+              </para>
+            </listitem>
+            <listitem>
+              <para>
+                sublist
+              </para>
+            </listitem>
+          </orderedlist>
+        </listitem>
+      </varlistentry>
+    </variablelist>
+  </section>
+  <section xml:id="html-blocks">
+    <title>HTML Blocks</title>
+    <para>
+      Simple block on one line:
+    </para>
+    <para>
+      foo
+    </para>
+    <para>
+      And nested without indentation:
+    </para>
+    <para>
+      foo
+    </para>
+    <para>
+      bar
+    </para>
+    <para>
+      Interpreted markdown in a table:
+    </para>
+    This is <emphasis>emphasized</emphasis>
+    And this is <emphasis role="strong">strong</emphasis>
+    <para>
+      Here’s a simple block:
+    </para>
+    <para>
+      foo
+    </para>
+    <para>
+      This should be a code block, though:
+    </para>
+    <programlisting>
+&lt;div&gt;
+    foo
+&lt;/div&gt;
+</programlisting>
+    <para>
+      As should this:
+    </para>
+    <programlisting>
+&lt;div&gt;foo&lt;/div&gt;
+</programlisting>
+    <para>
+      Now, nested:
+    </para>
+    <para>
+      foo
+    </para>
+    <para>
+      This should just be an HTML comment:
+    </para>
+    <para>
+      Multiline:
+    </para>
+    <para>
+      Code block:
+    </para>
+    <programlisting>
+&lt;!-- Comment --&gt;
+</programlisting>
+    <para>
+      Just plain comment, with trailing spaces on the line:
+    </para>
+    <para>
+      Code:
+    </para>
+    <programlisting>
+&lt;hr /&gt;
+</programlisting>
+    <para>
+      Hr’s:
+    </para>
+  </section>
+  <section xml:id="inline-markup">
+    <title>Inline Markup</title>
+    <para>
+      This is <emphasis>emphasized</emphasis>, and so <emphasis>is
+      this</emphasis>.
+    </para>
+    <para>
+      This is <emphasis role="strong">strong</emphasis>, and so
+      <emphasis role="strong">is this</emphasis>.
+    </para>
+    <para>
+      An <emphasis><link xlink:href="/url">emphasized link</link></emphasis>.
+    </para>
+    <para>
+      <emphasis role="strong"><emphasis>This is strong and
+      em.</emphasis></emphasis>
+    </para>
+    <para>
+      So is <emphasis role="strong"><emphasis>this</emphasis></emphasis> word.
+    </para>
+    <para>
+      <emphasis role="strong"><emphasis>This is strong and
+      em.</emphasis></emphasis>
+    </para>
+    <para>
+      So is <emphasis role="strong"><emphasis>this</emphasis></emphasis> word.
+    </para>
+    <para>
+      This is code: <literal>&gt;</literal>, <literal>$</literal>,
+      <literal>\</literal>, <literal>\$</literal>,
+      <literal>&lt;html&gt;</literal>.
+    </para>
+    <para>
+      <emphasis role="strikethrough">This is
+      <emphasis>strikeout</emphasis>.</emphasis>
+    </para>
+    <para>
+      Superscripts: a<superscript>bc</superscript>d
+      a<superscript><emphasis>hello</emphasis></superscript>
+      a<superscript>hello there</superscript>.
+    </para>
+    <para>
+      Subscripts: H<subscript>2</subscript>O, H<subscript>23</subscript>O,
+      H<subscript>many of them</subscript>O.
+    </para>
+    <para>
+      These should not be superscripts or subscripts, because of the unescaped
+      spaces: a^b c^d, a~b c~d.
+    </para>
+  </section>
+  <section xml:id="smart-quotes-ellipses-dashes">
+    <title>Smart quotes, ellipses, dashes</title>
+    <para>
+      <quote>Hello,</quote> said the spider. <quote><quote>Shelob</quote> is my
+      name.</quote>
+    </para>
+    <para>
+      <quote>A</quote>, <quote>B</quote>, and <quote>C</quote> are letters.
+    </para>
+    <para>
+      <quote>Oak,</quote> <quote>elm,</quote> and <quote>beech</quote> are names
+      of trees. So is <quote>pine.</quote>
+    </para>
+    <para>
+      <quote>He said, <quote>I want to go.</quote></quote> Were you alive in the
+      70’s?
+    </para>
+    <para>
+      Here is some quoted <quote><literal>code</literal></quote> and a
+      <quote><link xlink:href="http://example.com/?foo=1&amp;bar=2">quoted
+      link</link></quote>.
+    </para>
+    <para>
+      Some dashes: one—two — three—four — five.
+    </para>
+    <para>
+      Dashes between numbers: 5–7, 255–66, 1987–1999.
+    </para>
+    <para>
+      Ellipses…and…and….
+    </para>
+  </section>
+  <section xml:id="latex">
+    <title>LaTeX</title>
+    <itemizedlist spacing="compact">
+      <listitem>
+        <para>
+        </para>
+      </listitem>
+      <listitem>
+        <para>
+          2 + 2 = 4
+        </para>
+      </listitem>
+      <listitem>
+        <para>
+          <emphasis>x</emphasis> ∈ <emphasis>y</emphasis>
+        </para>
+      </listitem>
+      <listitem>
+        <para>
+          <emphasis>α</emphasis> ∧ <emphasis>ω</emphasis>
+        </para>
+      </listitem>
+      <listitem>
+        <para>
+          223
+        </para>
+      </listitem>
+      <listitem>
+        <para>
+          <emphasis>p</emphasis>-Tree
+        </para>
+      </listitem>
+      <listitem>
+        <para>
+          Here’s some display math:
+          $$\frac{d}{dx}f(x)=\lim_{h\to 0}\frac{f(x+h)-f(x)}{h}$$
+        </para>
+      </listitem>
+      <listitem>
+        <para>
+          Here’s one that has a line break in it:
+          <emphasis>α</emphasis> + <emphasis>ω</emphasis> × <emphasis>x</emphasis><superscript>2</superscript>.
+        </para>
+      </listitem>
+    </itemizedlist>
+    <para>
+      These shouldn’t be math:
+    </para>
+    <itemizedlist spacing="compact">
+      <listitem>
+        <para>
+          To get the famous equation, write <literal>$e = mc^2$</literal>.
+        </para>
+      </listitem>
+      <listitem>
+        <para>
+          $22,000 is a <emphasis>lot</emphasis> of money. So is $34,000. (It
+          worked if <quote>lot</quote> is emphasized.)
+        </para>
+      </listitem>
+      <listitem>
+        <para>
+          Shoes ($20) and socks ($5).
+        </para>
+      </listitem>
+      <listitem>
+        <para>
+          Escaped <literal>$</literal>: $73 <emphasis>this should be
+          emphasized</emphasis> 23$.
+        </para>
+      </listitem>
+    </itemizedlist>
+    <para>
+      Here’s a LaTeX table:
+    </para>
+  </section>
+  <section xml:id="special-characters">
+    <title>Special Characters</title>
+    <para>
+      Here is some unicode:
+    </para>
+    <itemizedlist spacing="compact">
+      <listitem>
+        <para>
+          I hat: Î
+        </para>
+      </listitem>
+      <listitem>
+        <para>
+          o umlaut: ö
+        </para>
+      </listitem>
+      <listitem>
+        <para>
+          section: §
+        </para>
+      </listitem>
+      <listitem>
+        <para>
+          set membership: ∈
+        </para>
+      </listitem>
+      <listitem>
+        <para>
+          copyright: ©
+        </para>
+      </listitem>
+    </itemizedlist>
+    <para>
+      AT&amp;T has an ampersand in their name.
+    </para>
+    <para>
+      AT&amp;T is another way to write it.
+    </para>
+    <para>
+      This &amp; that.
+    </para>
+    <para>
+      4 &lt; 5.
+    </para>
+    <para>
+      6 &gt; 5.
+    </para>
+    <para>
+      Backslash: \
+    </para>
+    <para>
+      Backtick: `
+    </para>
+    <para>
+      Asterisk: *
+    </para>
+    <para>
+      Underscore: _
+    </para>
+    <para>
+      Left brace: {
+    </para>
+    <para>
+      Right brace: }
+    </para>
+    <para>
+      Left bracket: [
+    </para>
+    <para>
+      Right bracket: ]
+    </para>
+    <para>
+      Left paren: (
+    </para>
+    <para>
+      Right paren: )
+    </para>
+    <para>
+      Greater-than: &gt;
+    </para>
+    <para>
+      Hash: #
+    </para>
+    <para>
+      Period: .
+    </para>
+    <para>
+      Bang: !
+    </para>
+    <para>
+      Plus: +
+    </para>
+    <para>
+      Minus: -
+    </para>
+  </section>
+  <section xml:id="links">
+    <title>Links</title>
+    <section xml:id="explicit">
+      <title>Explicit</title>
+      <para>
+        Just a <link xlink:href="/url/">URL</link>.
+      </para>
+      <para>
+        <link xlink:href="/url/">URL and title</link>.
+      </para>
+      <para>
+        <link xlink:href="/url/">URL and title</link>.
+      </para>
+      <para>
+        <link xlink:href="/url/">URL and title</link>.
+      </para>
+      <para>
+        <link xlink:href="/url/">URL and title</link>
+      </para>
+      <para>
+        <link xlink:href="/url/">URL and title</link>
+      </para>
+      <para>
+        <link xlink:href="/url/with_underscore">with_underscore</link>
+      </para>
+      <para>
+        Email link (<email>nobody@nowhere.net</email>)
+      </para>
+      <para>
+        <link xlink:href="">Empty</link>.
+      </para>
+    </section>
+    <section xml:id="reference">
+      <title>Reference</title>
+      <para>
+        Foo <link xlink:href="/url/">bar</link>.
+      </para>
+      <para>
+        With <link xlink:href="/url/">embedded [brackets]</link>.
+      </para>
+      <para>
+        <link xlink:href="/url/">b</link> by itself should be a link.
+      </para>
+      <para>
+        Indented <link xlink:href="/url">once</link>.
+      </para>
+      <para>
+        Indented <link xlink:href="/url">twice</link>.
+      </para>
+      <para>
+        Indented <link xlink:href="/url">thrice</link>.
+      </para>
+      <para>
+        This should [not][] be a link.
+      </para>
+      <programlisting>
+[not]: /url
+</programlisting>
+      <para>
+        Foo <link xlink:href="/url/">bar</link>.
+      </para>
+      <para>
+        Foo <link xlink:href="/url/">biz</link>.
+      </para>
+    </section>
+    <section xml:id="with-ampersands">
+      <title>With ampersands</title>
+      <para>
+        Here’s a <link xlink:href="http://example.com/?foo=1&amp;bar=2">link
+        with an ampersand in the URL</link>.
+      </para>
+      <para>
+        Here’s a link with an amersand in the link text:
+        <link xlink:href="http://att.com/">AT&amp;T</link>.
+      </para>
+      <para>
+        Here’s an <link xlink:href="/script?foo=1&amp;bar=2">inline link</link>.
+      </para>
+      <para>
+        Here’s an <link xlink:href="/script?foo=1&amp;bar=2">inline link in
+        pointy braces</link>.
+      </para>
+    </section>
+    <section xml:id="autolinks">
+      <title>Autolinks</title>
+      <para>
+        With an ampersand:
+        <link xlink:href="http://example.com/?foo=1&amp;bar=2" role="uri">http://example.com/?foo=1&amp;bar=2</link>
+      </para>
+      <itemizedlist spacing="compact">
+        <listitem>
+          <para>
+            In a list?
+          </para>
+        </listitem>
+        <listitem>
+          <para>
+            <link xlink:href="http://example.com/" role="uri">http://example.com/</link>
+          </para>
+        </listitem>
+        <listitem>
+          <para>
+            It should.
+          </para>
+        </listitem>
+      </itemizedlist>
+      <para>
+        An e-mail address: <email>nobody@nowhere.net</email>
+      </para>
+      <blockquote>
+        <para>
+          Blockquoted:
+          <link xlink:href="http://example.com/" role="uri">http://example.com/</link>
+        </para>
+      </blockquote>
+      <para>
+        Auto-links should not occur here:
+        <literal>&lt;http://example.com/&gt;</literal>
+      </para>
+      <programlisting>
+or here: &lt;http://example.com/&gt;
+</programlisting>
+    </section>
+  </section>
+  <section xml:id="images">
+    <title>Images</title>
+    <para>
+      From <quote>Voyage dans la Lune</quote> by Georges Melies (1902):
+    </para>
+    <figure>
+      <title>lalune</title>
+      <mediaobject>
+        <imageobject>
+          <imagedata fileref="lalune.jpg" />
+        </imageobject>
+        <textobject><phrase>lalune</phrase></textobject>
+      </mediaobject>
+    </figure>
+    <para>
+      Here is a movie <inlinemediaobject>
+        <imageobject>
+          <imagedata fileref="movie.jpg" />
+        </imageobject>
+        <textobject>
+          <phrase>movie</phrase>
+        </textobject>
+      </inlinemediaobject> icon.
+    </para>
+  </section>
+  <section xml:id="footnotes">
+    <title>Footnotes</title>
+    <para>
+      Here is a footnote reference,<footnote>
+        <para>
+          Here is the footnote. It can go anywhere after the footnote reference.
+          It need not be placed at the end of the document.
+        </para>
+      </footnote> and another.<footnote>
+        <para>
+          Here’s the long note. This one contains multiple blocks.
+        </para>
+        <para>
+          Subsequent blocks are indented to show that they belong to the
+          footnote (as with list items).
+        </para>
+        <programlisting>
+  { &lt;code&gt; }
+</programlisting>
+        <para>
+          If you want, you can indent every line, but you can also be lazy and
+          just indent the first line of each block.
+        </para>
+      </footnote> This should <emphasis>not</emphasis> be a footnote reference,
+      because it contains a space.[^my note] Here is an inline note.<footnote>
+        <para>
+          This is <emphasis>easier</emphasis> to type. Inline notes may contain
+          <link xlink:href="http://google.com">links</link> and
+          <literal>]</literal> verbatim characters, as well as [bracketed text].
+        </para>
+      </footnote>
+    </para>
+    <blockquote>
+      <para>
+        Notes can go in quotes.<footnote>
+          <para>
+            In quote.
+          </para>
+        </footnote>
+      </para>
+    </blockquote>
+    <orderedlist numeration="arabic" spacing="compact">
+      <listitem>
+        <para>
+          And in list items.<footnote>
+            <para>
+              In list.
+            </para>
+          </footnote>
+        </para>
+      </listitem>
+    </orderedlist>
+    <para>
+      This paragraph should not be part of the note, as it is not indented.
+    </para>
+  </section>
 </article>
diff --git a/test/writer.dokuwiki b/test/writer.dokuwiki
--- a/test/writer.dokuwiki
+++ b/test/writer.dokuwiki
@@ -48,25 +48,25 @@
 
 > This is a block quote. It is pretty short.
 
-<HTML><blockquote>
-Code in a block quote:
+> Code in a block quote:
 
-<code>
+> <code>
 sub status {
     print "working";
 }
 </code>
-A list:
 
-  - item one
-  - item two
+> A list:
 
-Nested block quotes:
+>   - item one
+>   - item two
 
-> nested
+> Nested block quotes:
 
-> nested
-</blockquote></HTML>
+>> nested
+
+>> nested
+
 This should not be a block quote: 2 > 1.
 
 And a following paragraph.
@@ -87,6 +87,7 @@
 
 this code block is indented by one tab
 </code>
+
 And:
 
 <code>
@@ -95,6 +96,7 @@
 These should not be escaped:  \$ \\ \> \[ \{
 </code>
 
+
 ----
 
 ====== Lists ======
@@ -165,11 +167,12 @@
 
 Multiple paragraphs:
 
-<HTML><ol style="list-style-type: decimal;"></HTML>
-<HTML><li></HTML><HTML><p></HTML>Item 1, graf one.<HTML></p></HTML>
-<HTML><p></HTML>Item 1. graf two. The quick brown fox jumped over the lazy dog’s back.<HTML></p></HTML><HTML></li></HTML>
-<HTML><li></HTML><HTML><p></HTML>Item 2.<HTML></p></HTML><HTML></li></HTML>
-<HTML><li></HTML><HTML><p></HTML>Item 3.<HTML></p></HTML><HTML></li></HTML><HTML></ol></HTML>
+  - <WRAP>
+Item 1, graf one.
+Item 1. graf two. The quick brown fox jumped over the lazy dog’s back.
+</WRAP>
+  - Item 2.
+  - Item 3.
 
 ===== Nested =====
 
@@ -204,32 +207,28 @@
 
 ===== 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>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>
-<HTML><li></HTML>sublist with roman numerals, starting with 4<HTML></li></HTML>
-<HTML><li></HTML>more items
-<HTML><ol style="list-style-type: upper-alpha;"></HTML>
-<HTML><li></HTML>a subsublist<HTML></li></HTML>
-<HTML><li></HTML>a subsublist<HTML></li></HTML><HTML></ol></HTML>
-<HTML></li></HTML><HTML></ol></HTML>
-<HTML></li></HTML><HTML></ol></HTML>
+  - begins with 2
+  - <WRAP>
+and now 3
+with a continuation
+    - sublist with roman numerals, starting with 4
+    - more items
+      - a subsublist
+      - a subsublist
+</WRAP>
 
 Nesting:
 
-<HTML><ol style="list-style-type: upper-alpha;"></HTML>
-<HTML><li></HTML>Upper Alpha
-<HTML><ol style="list-style-type: upper-roman;"></HTML>
-<HTML><li></HTML>Upper Roman.
-<HTML><ol start="6" style="list-style-type: decimal;"></HTML>
-<HTML><li></HTML>Decimal start with 6
-<HTML><ol start="3" style="list-style-type: lower-alpha;"></HTML>
-<HTML><li></HTML>Lower alpha with paren<HTML></li></HTML><HTML></ol></HTML>
-<HTML></li></HTML><HTML></ol></HTML>
-<HTML></li></HTML><HTML></ol></HTML>
-<HTML></li></HTML><HTML></ol></HTML>
+  - <WRAP>
+Upper Alpha
+    - <WRAP>
+Upper Roman.
+      - <WRAP>
+Decimal start with 6
+        - Lower alpha with paren
+</WRAP>
+</WRAP>
+</WRAP>
 
 Autonumbering:
 
@@ -268,31 +267,32 @@
 
 Multiple blocks with italics:
 
-<HTML><dl></HTML>
-<HTML><dt></HTML>//apple//<HTML></dt></HTML>
-<HTML><dd></HTML><HTML><p></HTML>red fruit<HTML></p></HTML>
-<HTML><p></HTML>contains seeds, crisp, pleasant to taste<HTML></p></HTML><HTML></dd></HTML>
-<HTML><dt></HTML>//orange//<HTML></dt></HTML>
-<HTML><dd></HTML><HTML><p></HTML>orange fruit<HTML></p></HTML>
+  * **//apple//** <WRAP>
+red fruit
+contains seeds, crisp, pleasant to taste
+</WRAP>
+  * **//orange//** <WRAP>
+orange fruit
 <code>
 { orange code block }
 </code>
-> <HTML><p></HTML>orange block quote<HTML></p></HTML>
-<HTML></dd></HTML><HTML></dl></HTML>
 
+> orange block quote
+</WRAP>
+
 Multiple definitions, tight:
 
-  * **apple** red fruitcomputer
-  * **orange** orange fruitbank
+  * **apple** red fruit; computer
+  * **orange** orange fruit; bank
 
 Multiple definitions, loose:
 
-  * **apple** red fruitcomputer
-  * **orange** orange fruitbank
+  * **apple** red fruit; computer
+  * **orange** orange fruit; bank
 
 Blank line after term, indented marker, alternate markers:
 
-  * **apple** red fruitcomputer
+  * **apple** red fruit; computer
   * **orange** orange fruit
     - sublist
     - sublist
@@ -314,23 +314,11 @@
 
 Interpreted markdown in a table:
 
-<HTML>
-<table>
-<tr>
-<td>
-</HTML>
+
 This is //emphasized//
-<HTML>
-</td>
-<td>
-</HTML>
+
 And this is **strong**
-<HTML>
-</td>
-</tr>
-</table>
-<script type="text/javascript">document.write('This *should not* be interpreted as markdown');</script>
-</HTML>
+
 Here’s a simple block:
 
 foo
@@ -343,11 +331,13 @@
     foo
 </div>
 </code>
+
 As should this:
 
 <code>
 <div>foo</div>
 </code>
+
 Now, nested:
 
 foo
@@ -356,49 +346,29 @@
 
 This should just be an HTML comment:
 
-<HTML>
-<!-- Comment -->
-</HTML>
+
 Multiline:
 
-<HTML>
-<!--
-Blah
-Blah
--->
-<!--
-    This is another comment.
--->
-</HTML>
+
 Code block:
 
 <code>
 <!-- Comment -->
 </code>
+
 Just plain comment, with trailing spaces on the line:
 
-<HTML>
-<!-- foo -->
-</HTML>
+
 Code:
 
 <code>
 <hr />
 </code>
+
 Hr’s:
 
-<HTML>
-<hr>
-<hr />
-<hr />
-<hr>
-<hr />
-<hr />
-<hr class="foo" id="bar" />
-<hr class="foo" id="bar" />
-<hr class="foo" id="bar">
-</HTML>
 
+
 ----
 
 ====== Inline Markup ======
@@ -571,6 +541,7 @@
 <code>
 [not]: /url
 </code>
+
 Foo [[url/|bar]].
 
 Foo [[url/|biz]].
@@ -603,17 +574,20 @@
 or here: <http://example.com/>
 </code>
 
+
 ----
 
 ====== Images ======
 
 From “Voyage dans la Lune” by Georges Melies (1902):
 
-{{:lalune.jpg|Voyage dans la Lune lalune}}
+{{lalune.jpg|Voyage dans la Lune}}
+lalune
 
-Here is a movie {{:movie.jpg|movie}} icon.
 
+Here is a movie {{movie.jpg|movie}} icon.
 
+
 ----
 
 ====== Footnotes ======
@@ -626,12 +600,13 @@
 <code>
   { <code> }
 </code>
+
 If you want, you can indent every line, but you can also be lazy and just indent the first line of each block.
 )) This should //not// be a footnote reference, because it contains a space.[^my note] Here is an inline note.((This is //easier// to type. Inline notes may contain [[http://google.com|links]] and ''%%]%%'' verbatim characters, as well as [bracketed text].
 ))
 
 > Notes can go in quotes.((In quote.
-> ))
+))
 
   - And in list items.((In list.))
 
diff --git a/test/writer.fb2 b/test/writer.fb2
--- a/test/writer.fb2
+++ b/test/writer.fb2
@@ -3,7 +3,6 @@
 <description>
 <title-info>
 <genre>unrecognised</genre>
-<book-title>Pandoc Test Suite</book-title>
 <author>
 <first-name>John</first-name>
 <last-name>MacFarlane</last-name>
@@ -11,6 +10,7 @@
 <author>
 <nickname>Anonymous</nickname>
 </author>
+<book-title>Pandoc Test Suite</book-title>
 <date>July 17, 2006</date>
 </title-info>
 <document-info>
@@ -22,28 +22,29 @@
 <p>Pandoc Test Suite</p>
 </title>
 <section>
-<p>This is a set of tests for pandoc. Most of them are adapted from John Gruber’s markdown test suite.</p>
-<empty-line />
-<p>——————————</p>
+<p>This is a set of tests for pandoc. Most of them are adapted from
+John Gruber’s markdown test suite.</p>
 <empty-line />
 </section>
-<section>
+<section id="headers">
 <title>
 <p>Headers</p>
 </title>
-<section>
+<section id="level-2-with-an-embedded-link">
 <title>
-<p>Level 2 with an embedded link &lt;/url&gt;</p>
+<p>Level 2 with an <a l:href="/url">embedded link</a>
+</p>
 </title>
-<section>
+<section id="level-3-with-emphasis">
 <title>
-<p>Level 3 with emphasis</p>
+<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>
@@ -52,50 +53,54 @@
 </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</p>
+<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>
 <p>with no blank line</p>
 <empty-line />
-<p>——————————</p>
-<empty-line />
 </section>
 </section>
-<section>
+<section id="paragraphs">
 <title>
 <p>Paragraphs</p>
 </title>
 <p>Here’s a regular paragraph.</p>
-<p>In Markdown 1.0.0 and earlier. Version 8. This line turns into a list item. Because a hard-wrapped line in the middle of a paragraph looked like a list item.</p>
-<p>Here’s one with a bullet. * criminey.</p>
-<p>There should be a hard line break<empty-line />here.</p>
-<empty-line />
-<p>——————————</p>
+<p>In Markdown 1.0.0 and earlier. Version
+8. This line turns into a list item.
+Because a hard-wrapped line in the
+middle of a paragraph looked like a
+list item.</p>
+<p>Here’s one with a bullet.
+* criminey.</p>
+<p>There should be a hard line break
+here.</p>
 <empty-line />
 </section>
-<section>
+<section id="block-quotes">
 <title>
 <p>Block Quotes</p>
 </title>
 <p>E-mail style:</p>
 <cite>
-<p>This is a block quote. It is pretty short.</p>
+<p>This is a block quote.
+It is pretty short.</p>
 </cite>
 <cite>
 <p>Code in a block quote:</p>
@@ -121,13 +126,12 @@
 <p>nested</p>
 </cite>
 </cite>
-<p>This should not be a block quote: 2 &gt; 1.</p>
+<p>This should not be a block quote: 2
+&gt; 1.</p>
 <p>And a following paragraph.</p>
 <empty-line />
-<p>——————————</p>
-<empty-line />
 </section>
-<section>
+<section id="code-blocks">
 <title>
 <p>Code Blocks</p>
 </title>
@@ -171,14 +175,12 @@
 </p>
 <empty-line />
 <empty-line />
-<p>——————————</p>
-<empty-line />
 </section>
-<section>
+<section id="lists">
 <title>
 <p>Lists</p>
 </title>
-<section>
+<section id="unordered">
 <title>
 <p>Unordered</p>
 </title>
@@ -216,7 +218,7 @@
 <p>• Minus 3</p>
 <empty-line />
 </section>
-<section>
+<section id="ordered">
 <title>
 <p>Ordered</p>
 </title>
@@ -245,14 +247,15 @@
 <p>Multiple paragraphs:</p>
 <p>1. Item 1, graf one.</p>
 <empty-line />
-<p>   Item 1. graf two. The quick brown fox jumped over the lazy dog’s back.</p>
+<p>   Item 1. graf two. The quick brown fox jumped over the lazy dog’s
+back.</p>
 <empty-line />
 <p>2. Item 2.</p>
 <empty-line />
 <p>3. Item 3.</p>
 <empty-line />
 </section>
-<section>
+<section id="nested">
 <title>
 <p>Nested</p>
 </title>
@@ -277,29 +280,35 @@
 <p>3. Third</p>
 <empty-line />
 </section>
-<section>
+<section id="tabs-and-spaces">
 <title>
 <p>Tabs and spaces</p>
 </title>
-<p>• this is a list item indented with tabs</p>
+<p>• this is a list item
+indented with tabs</p>
 <empty-line />
-<p>• this is a list item indented with spaces</p>
+<p>• this is a list item
+indented with spaces</p>
 <empty-line />
-<p>• • this is an example list item indented with tabs</p>
+<p>• • this is an example list item
+indented with tabs</p>
 <empty-line />
-<p>• • this is an example list item indented with spaces</p>
+<p>• • this is an example list item
+indented with spaces</p>
 <empty-line />
 </section>
-<section>
+<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>
 <empty-line />
-<p>(3) iv. sublist with roman numerals, starting with 4</p>
+<p>(3) iv. sublist with roman numerals,
+starting with 4</p>
 <p>(3) v. more items</p>
 <p>(3) v. (A) a subsublist</p>
 <p>(3) v. (B) a subsublist</p>
@@ -316,11 +325,9 @@
 <p>M.A. 2007</p>
 <p>B. Williams</p>
 <empty-line />
-<p>——————————</p>
-<empty-line />
 </section>
 </section>
-<section>
+<section id="definition-lists">
 <title>
 <p>Definition Lists</p>
 </title>
@@ -374,7 +381,8 @@
 </p>
 <p>    red fruit</p>
 <empty-line />
-<p>    contains seeds, crisp, pleasant to taste</p>
+<p>    contains seeds,
+crisp, pleasant to taste</p>
 <empty-line />
 <p>
 <strong>
@@ -433,7 +441,7 @@
 <p>1. sublist</p>
 <p>2. sublist</p>
 </section>
-<section>
+<section id="html-blocks">
 <title>
 <p>HTML Blocks</p>
 </title>
@@ -476,18 +484,15 @@
 <empty-line />
 <p>Hr’s:</p>
 <empty-line />
-<p>——————————</p>
-<empty-line />
 </section>
-<section>
+<section id="inline-markup">
 <title>
 <p>Inline Markup</p>
 </title>
 <p>This is <emphasis>emphasized</emphasis>, and so <emphasis>is this</emphasis>.</p>
 <p>This is <strong>strong</strong>, and so <strong>is this</strong>.</p>
-<p>An <emphasis>emphasized link<a l:href="#l1" type="note">
-<sup>[1]</sup>
-</a>
+<p>An <emphasis>
+<a l:href="/url">emphasized link</a>
 </emphasis>.</p>
 <p>
 <strong>
@@ -513,30 +518,27 @@
 <emphasis>hello</emphasis>
 </sup> a<sup>hello there</sup>.</p>
 <p>Subscripts: H<sub>2</sub>O, H<sub>23</sub>O, H<sub>many of them</sub>O.</p>
-<p>These should not be superscripts or subscripts, because of the unescaped spaces: a^b c^d, a~b c~d.</p>
-<empty-line />
-<p>——————————</p>
+<p>These should not be superscripts or subscripts,
+because of the unescaped spaces: a^b c^d, a~b c~d.</p>
 <empty-line />
 </section>
-<section>
+<section id="smart-quotes-ellipses-dashes">
 <title>
 <p>Smart quotes, ellipses, dashes</p>
 </title>
 <p>“Hello,” said the spider. “‘Shelob’ is my name.”</p>
 <p>‘A’, ‘B’, and ‘C’ are letters.</p>
-<p>‘Oak,’ ‘elm,’ and ‘beech’ are names of trees. So is ‘pine.’</p>
-<p>‘He said, “I want to go.”’ Were you alive in the 70’s?</p>
-<p>Here is some quoted ‘<code>code</code>’ and a “quoted link<a l:href="#l2" type="note">
-<sup>[2]</sup>
-</a>”.</p>
+<p>‘Oak,’ ‘elm,’ and ‘beech’ are names of trees.
+So is ‘pine.’</p>
+<p>‘He said, “I want to go.”’ Were you alive in the
+70’s?</p>
+<p>Here is some quoted ‘<code>code</code>’ and a “<a l:href="http://example.com/?foo=1&amp;bar=2">quoted link</a>”.</p>
 <p>Some dashes: one—two — three—four — five.</p>
 <p>Dashes between numbers: 5–7, 255–66, 1987–1999.</p>
 <p>Ellipses…and…and….</p>
 <empty-line />
-<p>——————————</p>
-<empty-line />
 </section>
-<section>
+<section id="latex">
 <title>
 <p>LaTeX</p>
 </title>
@@ -550,20 +552,20 @@
 <p>• <code>223</code>
 </p>
 <p>• <code>p</code>-Tree</p>
-<p>• Here’s some display math: <code>\frac{d}{dx}f(x)=\lim_{h\to 0}\frac{f(x+h)-f(x)}{h}</code>
+<p>• Here’s some display math:
+<code>\frac{d}{dx}f(x)=\lim_{h\to 0}\frac{f(x+h)-f(x)}{h}</code>
 </p>
 <p>• Here’s one that has a line break in it: <code>\alpha + \omega \times x^2</code>.</p>
 <p>These shouldn’t be math:</p>
 <p>• To get the famous equation, write <code>$e = mc^2$</code>.</p>
-<p>• $22,000 is a <emphasis>lot</emphasis> of money. So is $34,000. (It worked if “lot” is emphasized.)</p>
+<p>• $22,000 is a <emphasis>lot</emphasis> of money. So is $34,000.
+(It worked if “lot” is emphasized.)</p>
 <p>• Shoes ($20) and socks ($5).</p>
 <p>• Escaped <code>$</code>: $73 <emphasis>this should be emphasized</emphasis> 23$.</p>
 <p>Here’s a LaTeX table:</p>
 <empty-line />
-<p>——————————</p>
-<empty-line />
 </section>
-<section>
+<section id="special-characters">
 <title>
 <p>Special Characters</p>
 </title>
@@ -595,123 +597,80 @@
 <p>Plus: +</p>
 <p>Minus: -</p>
 <empty-line />
-<p>——————————</p>
-<empty-line />
 </section>
-<section>
+<section id="links">
 <title>
 <p>Links</p>
 </title>
-<section>
+<section id="explicit">
 <title>
 <p>Explicit</p>
 </title>
-<p>Just a URL<a l:href="#l3" type="note">
-<sup>[3]</sup>
-</a>.</p>
-<p>URL and title<a l:href="#l4" type="note">
-<sup>[4]</sup>
-</a>.</p>
-<p>URL and title<a l:href="#l5" type="note">
-<sup>[5]</sup>
-</a>.</p>
-<p>URL and title<a l:href="#l6" type="note">
-<sup>[6]</sup>
-</a>.</p>
-<p>URL and title<a l:href="#l7" type="note">
-<sup>[7]</sup>
-</a>
+<p>Just a <a l:href="/url/">URL</a>.</p>
+<p>
+<a l:href="/url/">URL and title</a>.</p>
+<p>
+<a l:href="/url/">URL and title</a>.</p>
+<p>
+<a l:href="/url/">URL and title</a>.</p>
+<p>
+<a l:href="/url/">URL and title</a>
 </p>
-<p>URL and title<a l:href="#l8" type="note">
-<sup>[8]</sup>
-</a>
+<p>
+<a l:href="/url/">URL and title</a>
 </p>
-<p>with_underscore<a l:href="#l9" type="note">
-<sup>[9]</sup>
-</a>
+<p>
+<a l:href="/url/with_underscore">with_underscore</a>
 </p>
-<p>Email link<a l:href="#l10" type="note">
-<sup>[10]</sup>
-</a>
+<p>
+<a l:href="mailto:nobody@nowhere.net">Email link</a>
 </p>
-<p>Empty<a l:href="#l11" type="note">
-<sup>[11]</sup>
-</a>.</p>
+<p>
+<a l:href="">Empty</a>.</p>
 </section>
-<section>
+<section id="reference">
 <title>
 <p>Reference</p>
 </title>
-<p>Foo bar<a l:href="#l12" type="note">
-<sup>[12]</sup>
-</a>.</p>
-<p>With embedded [brackets]<a l:href="#l13" type="note">
-<sup>[13]</sup>
-</a>.</p>
-<p>b<a l:href="#l14" type="note">
-<sup>[14]</sup>
-</a> by itself should be a link.</p>
-<p>Indented once<a l:href="#l15" type="note">
-<sup>[15]</sup>
-</a>.</p>
-<p>Indented twice<a l:href="#l16" type="note">
-<sup>[16]</sup>
-</a>.</p>
-<p>Indented thrice<a l:href="#l17" type="note">
-<sup>[17]</sup>
-</a>.</p>
+<p>Foo <a l:href="/url/">bar</a>.</p>
+<p>With <a l:href="/url/">embedded [brackets]</a>.</p>
+<p>
+<a l:href="/url/">b</a> by itself should be a link.</p>
+<p>Indented <a l:href="/url">once</a>.</p>
+<p>Indented <a l:href="/url">twice</a>.</p>
+<p>Indented <a l:href="/url">thrice</a>.</p>
 <p>This should [not][] be a link.</p>
 <empty-line />
 <p>
 <code>[not]: /url</code>
 </p>
 <empty-line />
-<p>Foo bar<a l:href="#l18" type="note">
-<sup>[18]</sup>
-</a>.</p>
-<p>Foo biz<a l:href="#l19" type="note">
-<sup>[19]</sup>
-</a>.</p>
+<p>Foo <a l:href="/url/">bar</a>.</p>
+<p>Foo <a l:href="/url/">biz</a>.</p>
 </section>
-<section>
+<section id="with-ampersands">
 <title>
 <p>With ampersands</p>
 </title>
-<p>Here’s a link with an ampersand in the URL<a l:href="#l20" type="note">
-<sup>[20]</sup>
-</a>.</p>
-<p>Here’s a link with an amersand in the link text: AT&amp;T<a l:href="#l21" type="note">
-<sup>[21]</sup>
-</a>.</p>
-<p>Here’s an inline link<a l:href="#l22" type="note">
-<sup>[22]</sup>
-</a>.</p>
-<p>Here’s an inline link in pointy braces<a l:href="#l23" type="note">
-<sup>[23]</sup>
-</a>.</p>
+<p>Here’s a <a l:href="http://example.com/?foo=1&amp;bar=2">link with an ampersand in the URL</a>.</p>
+<p>Here’s a link with an amersand in the link text: <a l:href="http://att.com/">AT&amp;T</a>.</p>
+<p>Here’s an <a l:href="/script?foo=1&amp;bar=2">inline link</a>.</p>
+<p>Here’s an <a l:href="/script?foo=1&amp;bar=2">inline link in pointy braces</a>.</p>
 </section>
-<section>
+<section id="autolinks">
 <title>
 <p>Autolinks</p>
 </title>
-<p>With an ampersand: http://example.com/?foo=1&amp;bar=2<a l:href="#l24" type="note">
-<sup>[24]</sup>
-</a>
+<p>With an ampersand: <a l:href="http://example.com/?foo=1&amp;bar=2">http://example.com/?foo=1&amp;bar=2</a>
 </p>
 <p>• In a list?</p>
-<p>• http://example.com/<a l:href="#l25" type="note">
-<sup>[25]</sup>
-</a>
+<p>• <a l:href="http://example.com/">http://example.com/</a>
 </p>
 <p>• It should.</p>
-<p>An e-mail address: nobody@nowhere.net<a l:href="#l26" type="note">
-<sup>[26]</sup>
-</a>
+<p>An e-mail address: <a l:href="mailto:nobody@nowhere.net">nobody@nowhere.net</a>
 </p>
 <cite>
-<p>Blockquoted: http://example.com/<a l:href="#l27" type="note">
-<sup>[27]</sup>
-</a>
+<p>Blockquoted: <a l:href="http://example.com/">http://example.com/</a>
 </p>
 </cite>
 <p>Auto-links should not occur here: <code>&lt;http://example.com/&gt;</code>
@@ -722,11 +681,9 @@
 </p>
 <empty-line />
 <empty-line />
-<p>——————————</p>
-<empty-line />
 </section>
 </section>
-<section>
+<section id="images">
 <title>
 <p>Images</p>
 </title>
@@ -734,280 +691,66 @@
 <image l:href="#image1" l:type="imageType" alt="lalune" title="Voyage dans la Lune" />
 <p>Here is a movie <image l:href="#image2" l:type="inlineImageType" alt="movie" /> icon.</p>
 <empty-line />
-<p>——————————</p>
-<empty-line />
 </section>
-<section>
+<section id="footnotes">
 <title>
 <p>Footnotes</p>
 </title>
-<p>Here is a footnote reference,<a l:href="#n28" type="note">
-<sup>[28]</sup>
-</a> and another.<a l:href="#n29" type="note">
-<sup>[29]</sup>
-</a> This should <emphasis>not</emphasis> be a footnote reference, because it contains a space.[^my note] Here is an inline note.<a l:href="#n30" type="note">
-<sup>[30]</sup>
-</a>
+<p>Here is a footnote reference,<a l:href="#n1" type="note">[1]</a> and another.<a l:href="#n2" type="note">[2]</a>
+This should <emphasis>not</emphasis> be a footnote reference, because it
+contains a space.[^my note] Here is an inline note.<a l:href="#n3" type="note">[3]</a>
 </p>
 <cite>
-<p>Notes can go in quotes.<a l:href="#n31" type="note">
-<sup>[31]</sup>
-</a>
+<p>Notes can go in quotes.<a l:href="#n4" type="note">[4]</a>
 </p>
 </cite>
-<p>1. And in list items.<a l:href="#n32" type="note">
-<sup>[32]</sup>
-</a>
+<p>1. And in list items.<a l:href="#n5" type="note">[5]</a>
 </p>
 <p>This paragraph should not be part of the note, as it is not indented.</p>
 </section>
 </body>
 <body name="notes">
-<section id="l1">
+<section id="n1">
 <title>
 <p>1</p>
 </title>
-<p>
-<code>/url</code>
-</p>
+<p>Here is the footnote. It can go anywhere after the footnote
+reference. It need not be placed at the end of the document.</p>
 </section>
-<section id="l2">
+<section id="n2">
 <title>
 <p>2</p>
 </title>
-<p>
-<code>http://example.com/?foo=1&amp;bar=2</code>
-</p>
-</section>
-<section id="l3">
-<title>
-<p>3</p>
-</title>
-<p>
-<code>/url/</code>
-</p>
-</section>
-<section id="l4">
-<title>
-<p>4</p>
-</title>
-<p>title: <code>/url/</code>
-</p>
-</section>
-<section id="l5">
-<title>
-<p>5</p>
-</title>
-<p>title preceded by two spaces: <code>/url/</code>
-</p>
-</section>
-<section id="l6">
-<title>
-<p>6</p>
-</title>
-<p>title preceded by a tab: <code>/url/</code>
-</p>
-</section>
-<section id="l7">
-<title>
-<p>7</p>
-</title>
-<p>title with &quot;quotes&quot; in it: <code>/url/</code>
-</p>
-</section>
-<section id="l8">
-<title>
-<p>8</p>
-</title>
-<p>title with single quotes: <code>/url/</code>
-</p>
-</section>
-<section id="l9">
-<title>
-<p>9</p>
-</title>
-<p>
-<code>/url/with_underscore</code>
-</p>
-</section>
-<section id="l10">
-<title>
-<p>10</p>
-</title>
-<p>
-<code>mailto:nobody@nowhere.net</code>
-</p>
-</section>
-<section id="l11">
-<title>
-<p>11</p>
-</title>
-<p>
-<code>
-</code>
-</p>
-</section>
-<section id="l12">
-<title>
-<p>12</p>
-</title>
-<p>
-<code>/url/</code>
-</p>
-</section>
-<section id="l13">
-<title>
-<p>13</p>
-</title>
-<p>
-<code>/url/</code>
-</p>
-</section>
-<section id="l14">
-<title>
-<p>14</p>
-</title>
-<p>
-<code>/url/</code>
-</p>
-</section>
-<section id="l15">
-<title>
-<p>15</p>
-</title>
-<p>
-<code>/url</code>
-</p>
-</section>
-<section id="l16">
-<title>
-<p>16</p>
-</title>
-<p>
-<code>/url</code>
-</p>
-</section>
-<section id="l17">
-<title>
-<p>17</p>
-</title>
-<p>
-<code>/url</code>
-</p>
-</section>
-<section id="l18">
-<title>
-<p>18</p>
-</title>
-<p>Title with &quot;quotes&quot; inside: <code>/url/</code>
-</p>
-</section>
-<section id="l19">
-<title>
-<p>19</p>
-</title>
-<p>Title with &quot;quote&quot; inside: <code>/url/</code>
-</p>
-</section>
-<section id="l20">
-<title>
-<p>20</p>
-</title>
-<p>
-<code>http://example.com/?foo=1&amp;bar=2</code>
-</p>
-</section>
-<section id="l21">
-<title>
-<p>21</p>
-</title>
-<p>AT&amp;T: <code>http://att.com/</code>
-</p>
-</section>
-<section id="l22">
-<title>
-<p>22</p>
-</title>
-<p>
-<code>/script?foo=1&amp;bar=2</code>
-</p>
-</section>
-<section id="l23">
-<title>
-<p>23</p>
-</title>
-<p>
-<code>/script?foo=1&amp;bar=2</code>
-</p>
-</section>
-<section id="l24">
-<title>
-<p>24</p>
-</title>
-<p>
-<code>http://example.com/?foo=1&amp;bar=2</code>
-</p>
-</section>
-<section id="l25">
-<title>
-<p>25</p>
-</title>
-<p>
-<code>http://example.com/</code>
-</p>
-</section>
-<section id="l26">
-<title>
-<p>26</p>
-</title>
-<p>
-<code>mailto:nobody@nowhere.net</code>
-</p>
-</section>
-<section id="l27">
-<title>
-<p>27</p>
-</title>
-<p>
-<code>http://example.com/</code>
-</p>
-</section>
-<section id="n28">
-<title>
-<p>28</p>
-</title>
-<p>Here is the footnote. It can go anywhere after the footnote reference. It need not be placed at the end of the document.</p>
-</section>
-<section id="n29">
-<title>
-<p>29</p>
-</title>
-<p>Here’s the long note. This one contains multiple blocks.</p>
-<p>Subsequent blocks are indented to show that they belong to the footnote (as with list items).</p>
+<p>Here’s the long note. This one contains multiple
+blocks.</p>
+<p>Subsequent blocks are indented to show that they belong to the
+footnote (as with list items).</p>
 <empty-line />
 <p>
 <code>  { &lt;code&gt; }</code>
 </p>
 <empty-line />
-<p>If you want, you can indent every line, but you can also be lazy and just indent the first line of each block.</p>
+<p>If you want, you can indent every line, but you can also be
+lazy and just indent the first line of each block.</p>
 </section>
-<section id="n30">
+<section id="n3">
 <title>
-<p>30</p>
+<p>3</p>
 </title>
-<p>This is <emphasis>easier</emphasis> to type. Inline notes may contain links<a l:href="#l30" type="note">
-<sup>[30]</sup>
-</a> and <code>]</code> verbatim characters, as well as [bracketed text].</p>
+<p>This
+is <emphasis>easier</emphasis> to type. Inline notes may contain
+<a l:href="http://google.com">links</a> and <code>]</code> verbatim characters,
+as well as [bracketed text].</p>
 </section>
-<section id="n31">
+<section id="n4">
 <title>
-<p>31</p>
+<p>4</p>
 </title>
 <p>In quote.</p>
 </section>
-<section id="n32">
+<section id="n5">
 <title>
-<p>32</p>
+<p>5</p>
 </title>
 <p>In list.</p>
 </section>
diff --git a/test/writer.haddock b/test/writer.haddock
--- a/test/writer.haddock
+++ b/test/writer.haddock
@@ -1,7 +1,7 @@
 This is a set of tests for pandoc. Most of them are adapted from John Gruber’s
 markdown test suite.
 
-______________________________________________________________________________
+________________________________________________________________________________
 
 = Headers
 #headers#
@@ -34,7 +34,7 @@
 
 with no blank line
 
-______________________________________________________________________________
+________________________________________________________________________________
 
 = Paragraphs
 #paragraphs#
@@ -50,7 +50,7 @@
 There should be a hard line break
 here.
 
-______________________________________________________________________________
+________________________________________________________________________________
 
 = Block Quotes
 #block-quotes#
@@ -80,7 +80,7 @@
 
 And a following paragraph.
 
-______________________________________________________________________________
+________________________________________________________________________________
 
 = Code Blocks
 #code-blocks#
@@ -101,7 +101,7 @@
 >
 > These should not be escaped:  \$ \\ \> \[ \{
 
-______________________________________________________________________________
+________________________________________________________________________________
 
 = Lists
 #lists#
@@ -206,7 +206,6 @@
     -   Fee
     -   Fie
     -   Foe
-
 3.  Third
 
 Same thing but with paragraphs:
@@ -236,6 +235,7 @@
 #fancy-list-markers#
 
 (2) begins with 2
+
 (3) and now 3
 
     with a continuation
@@ -264,7 +264,7 @@
 
 B. Williams
 
-______________________________________________________________________________
+________________________________________________________________________________
 
 = Definition Lists
 #definition-lists#
@@ -397,7 +397,7 @@
 
 Hr’s:
 
-______________________________________________________________________________
+________________________________________________________________________________
 
 = Inline Markup
 #inline-markup#
@@ -424,10 +424,10 @@
 
 Subscripts: H2O, H23O, Hmany of themO.
 
-These should not be superscripts or subscripts, because of the unescaped
-spaces: a^b c^d, a~b c~d.
+These should not be superscripts or subscripts, because of the unescaped spaces:
+a^b c^d, a~b c~d.
 
-______________________________________________________________________________
+________________________________________________________________________________
 
 = Smart quotes, ellipses, dashes
 #smart-quotes-ellipses-dashes#
@@ -449,20 +449,20 @@
 
 Ellipses…and…and….
 
-______________________________________________________________________________
+________________________________________________________________________________
 
 = LaTeX
 #latex#
 
 -   
--   2 + 2 = 4
--   /x/ ∈ /y/
--   /α/ ∧ /ω/
--   223
--   /p/-Tree
+-   \(2+2=4\)
+-   \(x \in y\)
+-   \(\alpha \wedge \omega\)
+-   \(223\)
+-   \(p\)-Tree
 -   Here’s some display math:
-    $$\\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: /α/ + /ω/ × /x/2.
+    \[\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: \(\alpha + \omega \times x^2\).
 
 These shouldn’t be math:
 
@@ -474,7 +474,7 @@
 
 Here’s a LaTeX table:
 
-______________________________________________________________________________
+________________________________________________________________________________
 
 = Special Characters
 #special-characters#
@@ -529,7 +529,7 @@
 
 Minus: -
 
-______________________________________________________________________________
+________________________________________________________________________________
 
 = Links
 #links#
@@ -606,7 +606,7 @@
 
 > or here: <http://example.com/>
 
-______________________________________________________________________________
+________________________________________________________________________________
 
 = Images
 #images#
@@ -614,17 +614,18 @@
 From “Voyage dans la Lune” by Georges Melies (1902):
 
 <<lalune.jpg lalune>>
+lalune
 
 Here is a movie <<movie.jpg movie>> icon.
 
-______________________________________________________________________________
+________________________________________________________________________________
 
 = Footnotes
 #footnotes#
 
 Here is a footnote reference,<#notes [1]> and another.<#notes [2]> This should
-/not/ be a footnote reference, because it contains a space.[^my note] Here is
-an inline note.<#notes [3]>
+/not/ be a footnote reference, because it contains a space.[^my note] Here is an
+inline note.<#notes [3]>
 
 Notes can go in quotes.<#notes [4]>
 
@@ -639,17 +640,16 @@
 
 2.  Here’s the long note. This one contains multiple blocks.
 
-    Subsequent blocks are indented to show that they belong to the footnote
-    (as with list items).
+    Subsequent blocks are indented to show that they belong to the footnote (as
+    with list items).
 
     >   { <code> }
 
     If you want, you can indent every line, but you can also be lazy and just
     indent the first line of each block.
 
-3.  This is /easier/ to type. Inline notes may contain
-    <http://google.com links> and @]@ verbatim characters, as well as
-    [bracketed text].
+3.  This is /easier/ to type. Inline notes may contain <http://google.com links>
+    and @]@ verbatim characters, as well as [bracketed text].
 
 4.  In quote.
 
diff --git a/test/writer.html4 b/test/writer.html4
--- a/test/writer.html4
+++ b/test/writer.html4
@@ -3,16 +3,179 @@
 <head>
   <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
   <meta http-equiv="Content-Style-Type" content="text/css" />
-  <meta name="generator" content="pandoc" />
+  <meta name="generator" content="pandoc " />
   <meta name="author" content="John MacFarlane" />
   <meta name="author" content="Anonymous" />
   <meta name="date" content="2006-07-17" />
   <title>Pandoc Test Suite</title>
   <style type="text/css">
-      code{white-space: pre-wrap;}
-      span.smallcaps{font-variant: small-caps;}
-      span.underline{text-decoration: underline;}
-      div.column{display: inline-block; vertical-align: top; width: 50%;}
+    /* Default styles provided by pandoc.
+    ** See https://pandoc.org/MANUAL.html#variables-for-html for config info.
+    */
+    html {
+      color: #1a1a1a;
+      background-color: #fdfdfd;
+    }
+    body {
+      margin: 0 auto;
+      max-width: 36em;
+      padding-left: 50px;
+      padding-right: 50px;
+      padding-top: 50px;
+      padding-bottom: 50px;
+      hyphens: auto;
+      overflow-wrap: break-word;
+      text-rendering: optimizeLegibility;
+      font-kerning: normal;
+    }
+    @media (max-width: 600px) {
+      body {
+        font-size: 0.9em;
+        padding: 12px;
+      }
+      h1 {
+        font-size: 1.8em;
+      }
+    }
+    @media print {
+      html {
+        background-color: white;
+      }
+      body {
+        background-color: transparent;
+        color: black;
+        font-size: 12pt;
+      }
+      p, h2, h3 {
+        orphans: 3;
+        widows: 3;
+      }
+      h2, h3, h4 {
+        page-break-after: avoid;
+      }
+    }
+    p {
+      margin: 1em 0;
+    }
+    a {
+      color: #1a1a1a;
+    }
+    a:visited {
+      color: #1a1a1a;
+    }
+    img {
+      max-width: 100%;
+    }
+    svg {
+      height: auto;
+      max-width: 100%;
+    }
+    h1, h2, h3, h4, h5, h6 {
+      margin-top: 1.4em;
+    }
+    h5, h6 {
+      font-size: 1em;
+      font-style: italic;
+    }
+    h6 {
+      font-weight: normal;
+    }
+    ol, ul {
+      padding-left: 1.7em;
+      margin-top: 1em;
+    }
+    li > ol, li > ul {
+      margin-top: 0;
+    }
+    blockquote {
+      margin: 1em 0 1em 1.7em;
+      padding-left: 1em;
+      border-left: 2px solid #e6e6e6;
+      color: #606060;
+    }
+    code {
+      white-space: pre-wrap;
+      font-family: Menlo, Monaco, Consolas, 'Lucida Console', monospace;
+      font-size: 85%;
+      margin: 0;
+      hyphens: manual;
+    }
+    pre {
+      margin: 1em 0;
+      overflow: auto;
+    }
+    pre code {
+      padding: 0;
+      overflow: visible;
+      overflow-wrap: normal;
+    }
+    .sourceCode {
+     background-color: transparent;
+     overflow: visible;
+    }
+    hr {
+      border: none;
+      border-top: 1px solid #1a1a1a;
+      height: 1px;
+      margin: 1em 0;
+    }
+    table {
+      margin: 1em 0;
+      border-collapse: collapse;
+      width: 100%;
+      overflow-x: auto;
+      display: block;
+      font-variant-numeric: lining-nums tabular-nums;
+    }
+    table caption {
+      margin-bottom: 0.75em;
+    }
+    tbody {
+      margin-top: 0.5em;
+      border-top: 1px solid #1a1a1a;
+      border-bottom: 1px solid #1a1a1a;
+    }
+    th {
+      border-top: 1px solid #1a1a1a;
+      padding: 0.25em 0.5em 0.25em 0.5em;
+    }
+    td {
+      padding: 0.125em 0.5em 0.25em 0.5em;
+    }
+    header {
+      margin-bottom: 4em;
+      text-align: center;
+    }
+    #TOC li {
+      list-style: none;
+    }
+    #TOC ul {
+      padding-left: 1.3em;
+    }
+    #TOC > ul {
+      padding-left: 0;
+    }
+    #TOC a:not(:hover) {
+      text-decoration: none;
+    }
+    span.smallcaps{font-variant: small-caps;}
+    div.columns{display: flex; gap: 1.5em;}
+    div.column{flex: auto;}
+    @media screen {
+    div.columns{gap: min(4vw, 1.5em);}
+    div.column{overflow-x: auto;}
+    }
+    div.hanging-indent{margin-left: 1.5em; text-indent: -1.5em;}
+    /* The extra [class] is a hack that increases specificity enough to
+       override a similar rule in reveal.js */
+    ul.task-list[class]{list-style: none;}
+    ul.task-list li input[type="checkbox"] {
+      font-size: inherit;
+      width: 0.8em;
+      margin: 0 0.8em 0.2em -1.6em;
+      vertical-align: middle;
+    }
+    .display.math{display: block; text-align: center; margin: 0.5rem auto;}
   </style>
 </head>
 <body>
@@ -22,10 +185,12 @@
 <h2 class="author">Anonymous</h2>
 <h3 class="date">July 17, 2006</h3>
 </div>
-<p>This is a set of tests for pandoc. Most of them are adapted from John Gruber’s markdown test suite.</p>
+<p>This is a set of tests for pandoc. Most of them are adapted from John
+Gruber’s markdown test suite.</p>
 <hr />
 <h1 id="headers">Headers</h1>
-<h2 id="level-2-with-an-embedded-link">Level 2 with an <a href="/url">embedded link</a></h2>
+<h2 id="level-2-with-an-embedded-link">Level 2 with an <a href="/url">embedded
+link</a></h2>
 <h3 id="level-3-with-emphasis">Level 3 with <em>emphasis</em></h3>
 <h4 id="level-4">Level 4</h4>
 <h5 id="level-5">Level 5</h5>
@@ -38,7 +203,9 @@
 <hr />
 <h1 id="paragraphs">Paragraphs</h1>
 <p>Here’s a regular paragraph.</p>
-<p>In Markdown 1.0.0 and earlier. Version 8. This line turns into a list item. Because a hard-wrapped line in the middle of a paragraph looked like a list item.</p>
+<p>In Markdown 1.0.0 and earlier. Version 8. This line turns into a list item.
+Because a hard-wrapped line in the middle of a paragraph looked like a list
+item.</p>
 <p>Here’s one with a bullet. * criminey.</p>
 <p>There should be a hard line break<br />
 here.</p>
@@ -149,7 +316,8 @@
 <p>Multiple paragraphs:</p>
 <ol style="list-style-type: decimal">
 <li><p>Item 1, graf one.</p>
-<p>Item 1. graf two. The quick brown fox jumped over the lazy dog’s back.</p></li>
+<p>Item 1. graf two. The quick brown fox jumped over the lazy dog’s
+back.</p></li>
 <li><p>Item 2.</p></li>
 <li><p>Item 3.</p></li>
 </ol>
@@ -196,7 +364,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">
@@ -237,47 +405,58 @@
 <p>Tight using spaces:</p>
 <dl>
 <dt>apple</dt>
-<dd>red fruit
+<dd>
+red fruit
 </dd>
 <dt>orange</dt>
-<dd>orange fruit
+<dd>
+orange fruit
 </dd>
 <dt>banana</dt>
-<dd>yellow fruit
+<dd>
+yellow fruit
 </dd>
 </dl>
 <p>Tight using tabs:</p>
 <dl>
 <dt>apple</dt>
-<dd>red fruit
+<dd>
+red fruit
 </dd>
 <dt>orange</dt>
-<dd>orange fruit
+<dd>
+orange fruit
 </dd>
 <dt>banana</dt>
-<dd>yellow fruit
+<dd>
+yellow fruit
 </dd>
 </dl>
 <p>Loose:</p>
 <dl>
 <dt>apple</dt>
-<dd><p>red fruit</p>
+<dd>
+<p>red fruit</p>
 </dd>
 <dt>orange</dt>
-<dd><p>orange fruit</p>
+<dd>
+<p>orange fruit</p>
 </dd>
 <dt>banana</dt>
-<dd><p>yellow fruit</p>
+<dd>
+<p>yellow fruit</p>
 </dd>
 </dl>
 <p>Multiple blocks with italics:</p>
 <dl>
 <dt><em>apple</em></dt>
-<dd><p>red fruit</p>
+<dd>
+<p>red fruit</p>
 <p>contains seeds, crisp, pleasant to taste</p>
 </dd>
 <dt><em>orange</em></dt>
-<dd><p>orange fruit</p>
+<dd>
+<p>orange fruit</p>
 <pre><code>{ orange code block }</code></pre>
 <blockquote>
 <p>orange block quote</p>
@@ -287,38 +466,49 @@
 <p>Multiple definitions, tight:</p>
 <dl>
 <dt>apple</dt>
-<dd>red fruit
+<dd>
+red fruit
 </dd>
-<dd>computer
+<dd>
+computer
 </dd>
 <dt>orange</dt>
-<dd>orange fruit
+<dd>
+orange fruit
 </dd>
-<dd>bank
+<dd>
+bank
 </dd>
 </dl>
 <p>Multiple definitions, loose:</p>
 <dl>
 <dt>apple</dt>
-<dd><p>red fruit</p>
+<dd>
+<p>red fruit</p>
 </dd>
-<dd><p>computer</p>
+<dd>
+<p>computer</p>
 </dd>
 <dt>orange</dt>
-<dd><p>orange fruit</p>
+<dd>
+<p>orange fruit</p>
 </dd>
-<dd><p>bank</p>
+<dd>
+<p>bank</p>
 </dd>
 </dl>
 <p>Blank line after term, indented marker, alternate markers:</p>
 <dl>
 <dt>apple</dt>
-<dd><p>red fruit</p>
+<dd>
+<p>red fruit</p>
 </dd>
-<dd><p>computer</p>
+<dd>
+<p>computer</p>
 </dd>
 <dt>orange</dt>
-<dd><p>orange fruit</p>
+<dd>
+<p>orange fruit</p>
 <ol style="list-style-type: decimal">
 <li>sublist</li>
 <li>sublist</li>
@@ -406,18 +596,22 @@
 <p>So is <strong><em>this</em></strong> word.</p>
 <p><strong><em>This is strong and em.</em></strong></p>
 <p>So is <strong><em>this</em></strong> word.</p>
-<p>This is code: <code>&gt;</code>, <code>$</code>, <code>\</code>, <code>\$</code>, <code>&lt;html&gt;</code>.</p>
+<p>This is code: <code>&gt;</code>, <code>$</code>, <code>\</code>,
+<code>\$</code>, <code>&lt;html&gt;</code>.</p>
 <p><del>This is <em>strikeout</em>.</del></p>
-<p>Superscripts: a<sup>bc</sup>d a<sup><em>hello</em></sup> a<sup>hello there</sup>.</p>
+<p>Superscripts: a<sup>bc</sup>d a<sup><em>hello</em></sup>
+a<sup>hello there</sup>.</p>
 <p>Subscripts: H<sub>2</sub>O, H<sub>23</sub>O, H<sub>many of them</sub>O.</p>
-<p>These should not be superscripts or subscripts, because of the unescaped spaces: a^b c^d, a~b c~d.</p>
+<p>These should not be superscripts or subscripts, because of the unescaped
+spaces: a^b c^d, a~b c~d.</p>
 <hr />
 <h1 id="smart-quotes-ellipses-dashes">Smart quotes, ellipses, dashes</h1>
 <p>“Hello,” said the spider. “‘Shelob’ is my name.”</p>
 <p>‘A’, ‘B’, and ‘C’ are letters.</p>
 <p>‘Oak,’ ‘elm,’ and ‘beech’ are names of trees. So is ‘pine.’</p>
 <p>‘He said, “I want to go.”’ Were you alive in the 70’s?</p>
-<p>Here is some quoted ‘<code>code</code>’ and a “<a href="http://example.com/?foo=1&amp;bar=2">quoted link</a>”.</p>
+<p>Here is some quoted ‘<code>code</code>’ and a “<a
+href="http://example.com/?foo=1&amp;bar=2">quoted link</a>”.</p>
 <p>Some dashes: one—two — three—four — five.</p>
 <p>Dashes between numbers: 5–7, 255–66, 1987–1999.</p>
 <p>Ellipses…and…and….</p>
@@ -430,18 +624,21 @@
 <li><span class="math inline"><em>α</em> ∧ <em>ω</em></span></li>
 <li><span class="math inline">223</span></li>
 <li><span class="math inline"><em>p</em></span>-Tree</li>
-<li>Here’s some display math: <br /><span class="math display">$$\frac{d}{dx}f(x)=\lim_{h\to 0}\frac{f(x+h)-f(x)}{h}$$</span><br /></li>
-<li>Here’s one that has a line break in it: <span class="math inline"><em>α</em> + <em>ω</em> × <em>x</em><sup>2</sup></span>.</li>
+<li>Here’s some display math: <span
+class="math display">$$\frac{d}{dx}f(x)=\lim_{h\to
+0}\frac{f(x+h)-f(x)}{h}$$</span></li>
+<li>Here’s one that has a line break in it: <span
+class="math inline"><em>α</em> + <em>ω</em> × <em>x</em><sup>2</sup></span>.</li>
 </ul>
 <p>These shouldn’t be math:</p>
 <ul>
 <li>To get the famous equation, write <code>$e = mc^2$</code>.</li>
-<li>$22,000 is a <em>lot</em> of money. So is $34,000. (It worked if “lot” is emphasized.)</li>
+<li>$22,000 is a <em>lot</em> of money. So is $34,000. (It worked if “lot” is
+emphasized.)</li>
 <li>Shoes ($20) and socks ($5).</li>
 <li>Escaped <code>$</code>: $73 <em>this should be emphasized</em> 23$.</li>
 </ul>
 <p>Here’s a LaTeX table:</p>
-
 <hr />
 <h1 id="special-characters">Special Characters</h1>
 <p>Here is some unicode:</p>
@@ -480,7 +677,8 @@
 <p><a href="/url/" title="title">URL and title</a>.</p>
 <p><a href="/url/" title="title preceded by two spaces">URL and title</a>.</p>
 <p><a href="/url/" title="title preceded by a tab">URL and title</a>.</p>
-<p><a href="/url/" title="title with &quot;quotes&quot; in it">URL and title</a></p>
+<p><a href="/url/" title="title with &quot;quotes&quot; in it">URL and
+title</a></p>
 <p><a href="/url/" title="title with single quotes">URL and title</a></p>
 <p><a href="/url/with_underscore">with_underscore</a></p>
 <p><a href="mailto:nobody@nowhere.net">Email link</a></p>
@@ -497,52 +695,72 @@
 <p>Foo <a href="/url/" title="Title with &quot;quotes&quot; inside">bar</a>.</p>
 <p>Foo <a href="/url/" title="Title with &quot;quote&quot; inside">biz</a>.</p>
 <h2 id="with-ampersands">With ampersands</h2>
-<p>Here’s a <a href="http://example.com/?foo=1&amp;bar=2">link with an ampersand in the URL</a>.</p>
-<p>Here’s a link with an amersand in the link text: <a href="http://att.com/" title="AT&amp;T">AT&amp;T</a>.</p>
+<p>Here’s a <a href="http://example.com/?foo=1&amp;bar=2">link with an ampersand
+in the URL</a>.</p>
+<p>Here’s a link with an amersand in the link text: <a href="http://att.com/"
+title="AT&amp;T">AT&amp;T</a>.</p>
 <p>Here’s an <a href="/script?foo=1&amp;bar=2">inline link</a>.</p>
-<p>Here’s an <a href="/script?foo=1&amp;bar=2">inline link in pointy braces</a>.</p>
+<p>Here’s an <a href="/script?foo=1&amp;bar=2">inline link in pointy
+braces</a>.</p>
 <h2 id="autolinks">Autolinks</h2>
-<p>With an ampersand: <a href="http://example.com/?foo=1&amp;bar=2" class="uri">http://example.com/?foo=1&amp;bar=2</a></p>
+<p>With an ampersand: <a href="http://example.com/?foo=1&amp;bar=2"
+class="uri">http://example.com/?foo=1&amp;bar=2</a></p>
 <ul>
 <li>In a list?</li>
 <li><a href="http://example.com/" class="uri">http://example.com/</a></li>
 <li>It should.</li>
 </ul>
-<p>An e-mail address: <a href="mailto:nobody@nowhere.net">nobody@nowhere.net</a></p>
+<p>An e-mail address: <a href="mailto:nobody@nowhere.net"
+class="email">nobody@nowhere.net</a></p>
 <blockquote>
-<p>Blockquoted: <a href="http://example.com/" class="uri">http://example.com/</a></p>
+<p>Blockquoted: <a href="http://example.com/"
+class="uri">http://example.com/</a></p>
 </blockquote>
-<p>Auto-links should not occur here: <code>&lt;http://example.com/&gt;</code></p>
+<p>Auto-links should not occur here:
+<code>&lt;http://example.com/&gt;</code></p>
 <pre><code>or here: &lt;http://example.com/&gt;</code></pre>
 <hr />
 <h1 id="images">Images</h1>
 <p>From “Voyage dans la Lune” by Georges Melies (1902):</p>
-<div class="figure">
+<div class="float">
 <img src="lalune.jpg" title="Voyage dans la Lune" alt="lalune" />
-<p class="caption">lalune</p>
+<div class="figcaption">lalune</div>
 </div>
 <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"><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>
 <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"><sup>4</sup></a></p>
 </blockquote>
 <ol style="list-style-type: decimal">
-<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"><sup>5</sup></a></li>
 </ol>
 <p>This paragraph should not be part of the note, as it is not indented.</p>
-<div class="footnotes">
+<div class="footnotes footnotes-end-of-document">
 <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="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>
-<p>Subsequent blocks are indented to show that they belong to the footnote (as with list items).</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">↩︎</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>
 </ol>
 </div>
 </body>
diff --git a/test/writer.html5 b/test/writer.html5
--- a/test/writer.html5
+++ b/test/writer.html5
@@ -1,34 +1,196 @@
 <!DOCTYPE html>
-<html xmlns="http://www.w3.org/1999/xhtml" lang="" xml:lang="">
+<html xmlns="http://www.w3.org/1999/xhtml">
 <head>
   <meta charset="utf-8" />
-  <meta name="generator" content="pandoc" />
+  <meta name="generator" content="pandoc " />
   <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes" />
   <meta name="author" content="John MacFarlane" />
   <meta name="author" content="Anonymous" />
   <meta name="dcterms.date" content="2006-07-17" />
   <title>Pandoc Test Suite</title>
-  <style type="text/css">
-      code{white-space: pre-wrap;}
-      span.smallcaps{font-variant: small-caps;}
-      span.underline{text-decoration: underline;}
-      div.column{display: inline-block; vertical-align: top; width: 50%;}
+  <style>
+    /* Default styles provided by pandoc.
+    ** See https://pandoc.org/MANUAL.html#variables-for-html for config info.
+    */
+    html {
+      color: #1a1a1a;
+      background-color: #fdfdfd;
+    }
+    body {
+      margin: 0 auto;
+      max-width: 36em;
+      padding-left: 50px;
+      padding-right: 50px;
+      padding-top: 50px;
+      padding-bottom: 50px;
+      hyphens: auto;
+      overflow-wrap: break-word;
+      text-rendering: optimizeLegibility;
+      font-kerning: normal;
+    }
+    @media (max-width: 600px) {
+      body {
+        font-size: 0.9em;
+        padding: 12px;
+      }
+      h1 {
+        font-size: 1.8em;
+      }
+    }
+    @media print {
+      html {
+        background-color: white;
+      }
+      body {
+        background-color: transparent;
+        color: black;
+        font-size: 12pt;
+      }
+      p, h2, h3 {
+        orphans: 3;
+        widows: 3;
+      }
+      h2, h3, h4 {
+        page-break-after: avoid;
+      }
+    }
+    p {
+      margin: 1em 0;
+    }
+    a {
+      color: #1a1a1a;
+    }
+    a:visited {
+      color: #1a1a1a;
+    }
+    img {
+      max-width: 100%;
+    }
+    svg {
+      height: auto;
+      max-width: 100%;
+    }
+    h1, h2, h3, h4, h5, h6 {
+      margin-top: 1.4em;
+    }
+    h5, h6 {
+      font-size: 1em;
+      font-style: italic;
+    }
+    h6 {
+      font-weight: normal;
+    }
+    ol, ul {
+      padding-left: 1.7em;
+      margin-top: 1em;
+    }
+    li > ol, li > ul {
+      margin-top: 0;
+    }
+    blockquote {
+      margin: 1em 0 1em 1.7em;
+      padding-left: 1em;
+      border-left: 2px solid #e6e6e6;
+      color: #606060;
+    }
+    code {
+      white-space: pre-wrap;
+      font-family: Menlo, Monaco, Consolas, 'Lucida Console', monospace;
+      font-size: 85%;
+      margin: 0;
+      hyphens: manual;
+    }
+    pre {
+      margin: 1em 0;
+      overflow: auto;
+    }
+    pre code {
+      padding: 0;
+      overflow: visible;
+      overflow-wrap: normal;
+    }
+    .sourceCode {
+     background-color: transparent;
+     overflow: visible;
+    }
+    hr {
+      border: none;
+      border-top: 1px solid #1a1a1a;
+      height: 1px;
+      margin: 1em 0;
+    }
+    table {
+      margin: 1em 0;
+      border-collapse: collapse;
+      width: 100%;
+      overflow-x: auto;
+      display: block;
+      font-variant-numeric: lining-nums tabular-nums;
+    }
+    table caption {
+      margin-bottom: 0.75em;
+    }
+    tbody {
+      margin-top: 0.5em;
+      border-top: 1px solid #1a1a1a;
+      border-bottom: 1px solid #1a1a1a;
+    }
+    th {
+      border-top: 1px solid #1a1a1a;
+      padding: 0.25em 0.5em 0.25em 0.5em;
+    }
+    td {
+      padding: 0.125em 0.5em 0.25em 0.5em;
+    }
+    header {
+      margin-bottom: 4em;
+      text-align: center;
+    }
+    #TOC li {
+      list-style: none;
+    }
+    #TOC ul {
+      padding-left: 1.3em;
+    }
+    #TOC > ul {
+      padding-left: 0;
+    }
+    #TOC a:not(:hover) {
+      text-decoration: none;
+    }
+    span.smallcaps{font-variant: small-caps;}
+    div.columns{display: flex; gap: 1.5em;}
+    div.column{flex: auto;}
+    @media screen {
+    div.columns{gap: min(4vw, 1.5em);}
+    div.column{overflow-x: auto;}
+    }
+    div.hanging-indent{margin-left: 1.5em; text-indent: -1.5em;}
+    /* The extra [class] is a hack that increases specificity enough to
+       override a similar rule in reveal.js */
+    ul.task-list[class]{list-style: none;}
+    ul.task-list li input[type="checkbox"] {
+      font-size: inherit;
+      width: 0.8em;
+      margin: 0 0.8em 0.2em -1.6em;
+      vertical-align: middle;
+    }
+    .display.math{display: block; text-align: center; margin: 0.5rem auto;}
   </style>
-  <!--[if lt IE 9]>
-    <script src="//cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.3/html5shiv-printshiv.min.js"></script>
-  <![endif]-->
 </head>
 <body>
-<header>
+<header id="title-block-header">
 <h1 class="title">Pandoc Test Suite</h1>
 <p class="author">John MacFarlane</p>
 <p class="author">Anonymous</p>
 <p class="date">July 17, 2006</p>
 </header>
-<p>This is a set of tests for pandoc. Most of them are adapted from John Gruber’s markdown test suite.</p>
+<p>This is a set of tests for pandoc. Most of them are adapted from John
+Gruber’s markdown test suite.</p>
 <hr />
 <h1 id="headers">Headers</h1>
-<h2 id="level-2-with-an-embedded-link">Level 2 with an <a href="/url">embedded link</a></h2>
+<h2 id="level-2-with-an-embedded-link">Level 2 with an <a href="/url">embedded
+link</a></h2>
 <h3 id="level-3-with-emphasis">Level 3 with <em>emphasis</em></h3>
 <h4 id="level-4">Level 4</h4>
 <h5 id="level-5">Level 5</h5>
@@ -41,7 +203,9 @@
 <hr />
 <h1 id="paragraphs">Paragraphs</h1>
 <p>Here’s a regular paragraph.</p>
-<p>In Markdown 1.0.0 and earlier. Version 8. This line turns into a list item. Because a hard-wrapped line in the middle of a paragraph looked like a list item.</p>
+<p>In Markdown 1.0.0 and earlier. Version 8. This line turns into a list item.
+Because a hard-wrapped line in the middle of a paragraph looked like a list
+item.</p>
 <p>Here’s one with a bullet. * criminey.</p>
 <p>There should be a hard line break<br />
 here.</p>
@@ -152,7 +316,8 @@
 <p>Multiple paragraphs:</p>
 <ol type="1">
 <li><p>Item 1, graf one.</p>
-<p>Item 1. graf two. The quick brown fox jumped over the lazy dog’s back.</p></li>
+<p>Item 1. graf two. The quick brown fox jumped over the lazy dog’s
+back.</p></li>
 <li><p>Item 2.</p></li>
 <li><p>Item 3.</p></li>
 </ol>
@@ -199,7 +364,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">
@@ -240,47 +405,58 @@
 <p>Tight using spaces:</p>
 <dl>
 <dt>apple</dt>
-<dd>red fruit
+<dd>
+red fruit
 </dd>
 <dt>orange</dt>
-<dd>orange fruit
+<dd>
+orange fruit
 </dd>
 <dt>banana</dt>
-<dd>yellow fruit
+<dd>
+yellow fruit
 </dd>
 </dl>
 <p>Tight using tabs:</p>
 <dl>
 <dt>apple</dt>
-<dd>red fruit
+<dd>
+red fruit
 </dd>
 <dt>orange</dt>
-<dd>orange fruit
+<dd>
+orange fruit
 </dd>
 <dt>banana</dt>
-<dd>yellow fruit
+<dd>
+yellow fruit
 </dd>
 </dl>
 <p>Loose:</p>
 <dl>
 <dt>apple</dt>
-<dd><p>red fruit</p>
+<dd>
+<p>red fruit</p>
 </dd>
 <dt>orange</dt>
-<dd><p>orange fruit</p>
+<dd>
+<p>orange fruit</p>
 </dd>
 <dt>banana</dt>
-<dd><p>yellow fruit</p>
+<dd>
+<p>yellow fruit</p>
 </dd>
 </dl>
 <p>Multiple blocks with italics:</p>
 <dl>
 <dt><em>apple</em></dt>
-<dd><p>red fruit</p>
+<dd>
+<p>red fruit</p>
 <p>contains seeds, crisp, pleasant to taste</p>
 </dd>
 <dt><em>orange</em></dt>
-<dd><p>orange fruit</p>
+<dd>
+<p>orange fruit</p>
 <pre><code>{ orange code block }</code></pre>
 <blockquote>
 <p>orange block quote</p>
@@ -290,38 +466,49 @@
 <p>Multiple definitions, tight:</p>
 <dl>
 <dt>apple</dt>
-<dd>red fruit
+<dd>
+red fruit
 </dd>
-<dd>computer
+<dd>
+computer
 </dd>
 <dt>orange</dt>
-<dd>orange fruit
+<dd>
+orange fruit
 </dd>
-<dd>bank
+<dd>
+bank
 </dd>
 </dl>
 <p>Multiple definitions, loose:</p>
 <dl>
 <dt>apple</dt>
-<dd><p>red fruit</p>
+<dd>
+<p>red fruit</p>
 </dd>
-<dd><p>computer</p>
+<dd>
+<p>computer</p>
 </dd>
 <dt>orange</dt>
-<dd><p>orange fruit</p>
+<dd>
+<p>orange fruit</p>
 </dd>
-<dd><p>bank</p>
+<dd>
+<p>bank</p>
 </dd>
 </dl>
 <p>Blank line after term, indented marker, alternate markers:</p>
 <dl>
 <dt>apple</dt>
-<dd><p>red fruit</p>
+<dd>
+<p>red fruit</p>
 </dd>
-<dd><p>computer</p>
+<dd>
+<p>computer</p>
 </dd>
 <dt>orange</dt>
-<dd><p>orange fruit</p>
+<dd>
+<p>orange fruit</p>
 <ol type="1">
 <li>sublist</li>
 <li>sublist</li>
@@ -409,18 +596,22 @@
 <p>So is <strong><em>this</em></strong> word.</p>
 <p><strong><em>This is strong and em.</em></strong></p>
 <p>So is <strong><em>this</em></strong> word.</p>
-<p>This is code: <code>&gt;</code>, <code>$</code>, <code>\</code>, <code>\$</code>, <code>&lt;html&gt;</code>.</p>
+<p>This is code: <code>&gt;</code>, <code>$</code>, <code>\</code>,
+<code>\$</code>, <code>&lt;html&gt;</code>.</p>
 <p><del>This is <em>strikeout</em>.</del></p>
-<p>Superscripts: a<sup>bc</sup>d a<sup><em>hello</em></sup> a<sup>hello there</sup>.</p>
+<p>Superscripts: a<sup>bc</sup>d a<sup><em>hello</em></sup>
+a<sup>hello there</sup>.</p>
 <p>Subscripts: H<sub>2</sub>O, H<sub>23</sub>O, H<sub>many of them</sub>O.</p>
-<p>These should not be superscripts or subscripts, because of the unescaped spaces: a^b c^d, a~b c~d.</p>
+<p>These should not be superscripts or subscripts, because of the unescaped
+spaces: a^b c^d, a~b c~d.</p>
 <hr />
 <h1 id="smart-quotes-ellipses-dashes">Smart quotes, ellipses, dashes</h1>
 <p>“Hello,” said the spider. “‘Shelob’ is my name.”</p>
 <p>‘A’, ‘B’, and ‘C’ are letters.</p>
 <p>‘Oak,’ ‘elm,’ and ‘beech’ are names of trees. So is ‘pine.’</p>
 <p>‘He said, “I want to go.”’ Were you alive in the 70’s?</p>
-<p>Here is some quoted ‘<code>code</code>’ and a “<a href="http://example.com/?foo=1&amp;bar=2">quoted link</a>”.</p>
+<p>Here is some quoted ‘<code>code</code>’ and a “<a
+href="http://example.com/?foo=1&amp;bar=2">quoted link</a>”.</p>
 <p>Some dashes: one—two — three—four — five.</p>
 <p>Dashes between numbers: 5–7, 255–66, 1987–1999.</p>
 <p>Ellipses…and…and….</p>
@@ -433,18 +624,21 @@
 <li><span class="math inline"><em>α</em> ∧ <em>ω</em></span></li>
 <li><span class="math inline">223</span></li>
 <li><span class="math inline"><em>p</em></span>-Tree</li>
-<li>Here’s some display math: <br /><span class="math display">$$\frac{d}{dx}f(x)=\lim_{h\to 0}\frac{f(x+h)-f(x)}{h}$$</span><br /></li>
-<li>Here’s one that has a line break in it: <span class="math inline"><em>α</em> + <em>ω</em> × <em>x</em><sup>2</sup></span>.</li>
+<li>Here’s some display math: <span
+class="math display">$$\frac{d}{dx}f(x)=\lim_{h\to
+0}\frac{f(x+h)-f(x)}{h}$$</span></li>
+<li>Here’s one that has a line break in it: <span
+class="math inline"><em>α</em> + <em>ω</em> × <em>x</em><sup>2</sup></span>.</li>
 </ul>
 <p>These shouldn’t be math:</p>
 <ul>
 <li>To get the famous equation, write <code>$e = mc^2$</code>.</li>
-<li>$22,000 is a <em>lot</em> of money. So is $34,000. (It worked if “lot” is emphasized.)</li>
+<li>$22,000 is a <em>lot</em> of money. So is $34,000. (It worked if “lot” is
+emphasized.)</li>
 <li>Shoes ($20) and socks ($5).</li>
 <li>Escaped <code>$</code>: $73 <em>this should be emphasized</em> 23$.</li>
 </ul>
 <p>Here’s a LaTeX table:</p>
-
 <hr />
 <h1 id="special-characters">Special Characters</h1>
 <p>Here is some unicode:</p>
@@ -483,7 +677,8 @@
 <p><a href="/url/" title="title">URL and title</a>.</p>
 <p><a href="/url/" title="title preceded by two spaces">URL and title</a>.</p>
 <p><a href="/url/" title="title preceded by a tab">URL and title</a>.</p>
-<p><a href="/url/" title="title with &quot;quotes&quot; in it">URL and title</a></p>
+<p><a href="/url/" title="title with &quot;quotes&quot; in it">URL and
+title</a></p>
 <p><a href="/url/" title="title with single quotes">URL and title</a></p>
 <p><a href="/url/with_underscore">with_underscore</a></p>
 <p><a href="mailto:nobody@nowhere.net">Email link</a></p>
@@ -500,51 +695,77 @@
 <p>Foo <a href="/url/" title="Title with &quot;quotes&quot; inside">bar</a>.</p>
 <p>Foo <a href="/url/" title="Title with &quot;quote&quot; inside">biz</a>.</p>
 <h2 id="with-ampersands">With ampersands</h2>
-<p>Here’s a <a href="http://example.com/?foo=1&amp;bar=2">link with an ampersand in the URL</a>.</p>
-<p>Here’s a link with an amersand in the link text: <a href="http://att.com/" title="AT&amp;T">AT&amp;T</a>.</p>
+<p>Here’s a <a href="http://example.com/?foo=1&amp;bar=2">link with an ampersand
+in the URL</a>.</p>
+<p>Here’s a link with an amersand in the link text: <a href="http://att.com/"
+title="AT&amp;T">AT&amp;T</a>.</p>
 <p>Here’s an <a href="/script?foo=1&amp;bar=2">inline link</a>.</p>
-<p>Here’s an <a href="/script?foo=1&amp;bar=2">inline link in pointy braces</a>.</p>
+<p>Here’s an <a href="/script?foo=1&amp;bar=2">inline link in pointy
+braces</a>.</p>
 <h2 id="autolinks">Autolinks</h2>
-<p>With an ampersand: <a href="http://example.com/?foo=1&amp;bar=2" class="uri">http://example.com/?foo=1&amp;bar=2</a></p>
+<p>With an ampersand: <a href="http://example.com/?foo=1&amp;bar=2"
+class="uri">http://example.com/?foo=1&amp;bar=2</a></p>
 <ul>
 <li>In a list?</li>
 <li><a href="http://example.com/" class="uri">http://example.com/</a></li>
 <li>It should.</li>
 </ul>
-<p>An e-mail address: <a href="mailto:nobody@nowhere.net">nobody@nowhere.net</a></p>
+<p>An e-mail address: <a href="mailto:nobody@nowhere.net"
+class="email">nobody@nowhere.net</a></p>
 <blockquote>
-<p>Blockquoted: <a href="http://example.com/" class="uri">http://example.com/</a></p>
+<p>Blockquoted: <a href="http://example.com/"
+class="uri">http://example.com/</a></p>
 </blockquote>
-<p>Auto-links should not occur here: <code>&lt;http://example.com/&gt;</code></p>
+<p>Auto-links should not occur here:
+<code>&lt;http://example.com/&gt;</code></p>
 <pre><code>or here: &lt;http://example.com/&gt;</code></pre>
 <hr />
 <h1 id="images">Images</h1>
 <p>From “Voyage dans la Lune” by Georges Melies (1902):</p>
 <figure>
-<img src="lalune.jpg" title="Voyage dans la Lune" alt="lalune" /><figcaption>lalune</figcaption>
+<img src="lalune.jpg" title="Voyage dans la Lune" alt="lalune" />
+<figcaption aria-hidden="true">lalune</figcaption>
 </figure>
 <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 id="footnotes" class="footnotes footnotes-end-of-document"
+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="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" role="doc-backlink">↩︎</a></p></li>
 <li id="fn2"><p>Here’s the long note. This one contains multiple blocks.</p>
-<p>Subsequent blocks are indented to show that they belong to the footnote (as with list items).</p>
+<p>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"><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"><p>In quote.<a href="#fnref4" class="footnote-back"
+role="doc-backlink">↩︎</a></p></li>
+<li id="fn5"><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
@@ -64,7 +64,7 @@
         <Properties>
           <BasedOn type="object">$ID/NormalCharacterStyle</BasedOn>
         </Properties>
-      </CharacterStyle> 
+      </CharacterStyle>
     </RootCharacterStyleGroup>
     <RootParagraphStyleGroup Self="pandoc_paragraph_styles">
       <ParagraphStyle Self="$ID/NormalParagraphStyle" Name="$ID/NormalParagraphStyle"
@@ -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>
@@ -420,7 +420,7 @@
         <Properties>
           <BasedOn type="object">$ID/NormalParagraphStyle</BasedOn>
         </Properties>
-      </ParagraphStyle> 
+      </ParagraphStyle>
     </RootParagraphStyleGroup>
     <RootTableStyleGroup Self="pandoc_table_styles">
       <TableStyle Self="TableStyle/Table" Name="Table" />
@@ -444,16 +444,19 @@
 <Br />
 <ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/Header1">
   <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
+    <HyperlinkTextDestination Self="HyperlinkTextDestination/#headers" Name="Destination" DestinationUniqueKey="1" />
     <Content>Headers</Content>
   </CharacterStyleRange>
 </ParagraphStyleRange>
 <Br />
 <ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/Header2">
   <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
+    <HyperlinkTextDestination Self="HyperlinkTextDestination/#level-2-with-an-embedded-link" Name="Destination" DestinationUniqueKey="1" />
     <Content>Level 2 with an </Content>
   </CharacterStyleRange>
   <HyperlinkTextSource Self="htss-1" Name="" Hidden="false">
     <CharacterStyleRange AppliedCharacterStyle="CharacterStyle/Link">
+      <HyperlinkTextDestination Self="HyperlinkTextDestination/#level-2-with-an-embedded-link" Name="Destination" DestinationUniqueKey="1" />
       <Content>embedded link</Content>
     </CharacterStyleRange>
   </HyperlinkTextSource>
@@ -461,42 +464,50 @@
 <Br />
 <ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/Header3">
   <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
+    <HyperlinkTextDestination Self="HyperlinkTextDestination/#level-3-with-emphasis" Name="Destination" DestinationUniqueKey="1" />
     <Content>Level 3 with </Content>
   </CharacterStyleRange>
   <CharacterStyleRange AppliedCharacterStyle="CharacterStyle/Italic">
+    <HyperlinkTextDestination Self="HyperlinkTextDestination/#level-3-with-emphasis" Name="Destination" DestinationUniqueKey="1" />
     <Content>emphasis</Content>
   </CharacterStyleRange>
 </ParagraphStyleRange>
 <Br />
 <ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/Header4">
   <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
+    <HyperlinkTextDestination Self="HyperlinkTextDestination/#level-4" Name="Destination" DestinationUniqueKey="1" />
     <Content>Level 4</Content>
   </CharacterStyleRange>
 </ParagraphStyleRange>
 <Br />
 <ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/Header5">
   <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
+    <HyperlinkTextDestination Self="HyperlinkTextDestination/#level-5" Name="Destination" DestinationUniqueKey="1" />
     <Content>Level 5</Content>
   </CharacterStyleRange>
 </ParagraphStyleRange>
 <Br />
 <ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/Header1">
   <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
+    <HyperlinkTextDestination Self="HyperlinkTextDestination/#level-1" Name="Destination" DestinationUniqueKey="1" />
     <Content>Level 1</Content>
   </CharacterStyleRange>
 </ParagraphStyleRange>
 <Br />
 <ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/Header2">
   <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
+    <HyperlinkTextDestination Self="HyperlinkTextDestination/#level-2-with-emphasis" Name="Destination" DestinationUniqueKey="1" />
     <Content>Level 2 with </Content>
   </CharacterStyleRange>
   <CharacterStyleRange AppliedCharacterStyle="CharacterStyle/Italic">
+    <HyperlinkTextDestination Self="HyperlinkTextDestination/#level-2-with-emphasis" Name="Destination" DestinationUniqueKey="1" />
     <Content>emphasis</Content>
   </CharacterStyleRange>
 </ParagraphStyleRange>
 <Br />
 <ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/Header3">
   <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
+    <HyperlinkTextDestination Self="HyperlinkTextDestination/#level-3" Name="Destination" DestinationUniqueKey="1" />
     <Content>Level 3</Content>
   </CharacterStyleRange>
 </ParagraphStyleRange>
@@ -509,6 +520,7 @@
 <Br />
 <ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/Header2">
   <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
+    <HyperlinkTextDestination Self="HyperlinkTextDestination/#level-2" Name="Destination" DestinationUniqueKey="1" />
     <Content>Level 2</Content>
   </CharacterStyleRange>
 </ParagraphStyleRange>
@@ -521,6 +533,7 @@
 <Br />
 <ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/Header1">
   <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
+    <HyperlinkTextDestination Self="HyperlinkTextDestination/#paragraphs" Name="Destination" DestinationUniqueKey="1" />
     <Content>Paragraphs</Content>
   </CharacterStyleRange>
 </ParagraphStyleRange>
@@ -557,6 +570,7 @@
 <Br />
 <ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/Header1">
   <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
+    <HyperlinkTextDestination Self="HyperlinkTextDestination/#block-quotes" Name="Destination" DestinationUniqueKey="1" />
     <Content>Block Quotes</Content>
   </CharacterStyleRange>
 </ParagraphStyleRange>
@@ -637,6 +651,7 @@
 <Br />
 <ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/Header1">
   <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
+    <HyperlinkTextDestination Self="HyperlinkTextDestination/#code-blocks" Name="Destination" DestinationUniqueKey="1" />
     <Content>Code Blocks</Content>
   </CharacterStyleRange>
 </ParagraphStyleRange>
@@ -675,12 +690,14 @@
 <Br />
 <ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/Header1">
   <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
+    <HyperlinkTextDestination Self="HyperlinkTextDestination/#lists" Name="Destination" DestinationUniqueKey="1" />
     <Content>Lists</Content>
   </CharacterStyleRange>
 </ParagraphStyleRange>
 <Br />
 <ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/Header2">
   <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
+    <HyperlinkTextDestination Self="HyperlinkTextDestination/#unordered" Name="Destination" DestinationUniqueKey="1" />
     <Content>Unordered</Content>
   </CharacterStyleRange>
 </ParagraphStyleRange>
@@ -831,6 +848,7 @@
 <Br />
 <ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/Header2">
   <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
+    <HyperlinkTextDestination Self="HyperlinkTextDestination/#ordered" Name="Destination" DestinationUniqueKey="1" />
     <Content>Ordered</Content>
   </CharacterStyleRange>
 </ParagraphStyleRange>
@@ -945,10 +963,7 @@
 <Br />
 <ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/NumList &gt; subParagraph &gt; Paragraph">
   <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
-    <Content>	</Content>
-  </CharacterStyleRange>
-  <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
-    <Content>Item 1. graf two. The quick brown fox jumped over the lazy dog’s back.</Content>
+    <Content>	Item 1. graf two. The quick brown fox jumped over the lazy dog’s back.</Content>
   </CharacterStyleRange>
 </ParagraphStyleRange>
 <Br />
@@ -966,6 +981,7 @@
 <Br />
 <ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/Header2">
   <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
+    <HyperlinkTextDestination Self="HyperlinkTextDestination/#nested" Name="Destination" DestinationUniqueKey="1" />
     <Content>Nested</Content>
   </CharacterStyleRange>
 </ParagraphStyleRange>
@@ -1074,6 +1090,7 @@
 <Br />
 <ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/Header2">
   <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
+    <HyperlinkTextDestination Self="HyperlinkTextDestination/#tabs-and-spaces" Name="Destination" DestinationUniqueKey="1" />
     <Content>Tabs and spaces</Content>
   </CharacterStyleRange>
 </ParagraphStyleRange>
@@ -1104,11 +1121,12 @@
 <Br />
 <ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/Header2">
   <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
+    <HyperlinkTextDestination Self="HyperlinkTextDestination/#fancy-list-markers" Name="Destination" DestinationUniqueKey="1" />
     <Content>Fancy list markers</Content>
   </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>
@@ -1122,10 +1140,7 @@
 <Br />
 <ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/NumList &gt; subParagraph &gt; Paragraph">
   <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
-    <Content>	</Content>
-  </CharacterStyleRange>
-  <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
-    <Content>with a continuation</Content>
+    <Content>	with a continuation</Content>
   </CharacterStyleRange>
 </ParagraphStyleRange>
 <Br />
@@ -1227,6 +1242,7 @@
 <Br />
 <ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/Header1">
   <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
+    <HyperlinkTextDestination Self="HyperlinkTextDestination/#definition-lists" Name="Destination" DestinationUniqueKey="1" />
     <Content>Definition Lists</Content>
   </CharacterStyleRange>
 </ParagraphStyleRange>
@@ -1539,6 +1555,7 @@
 <Br />
 <ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/Header1">
   <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
+    <HyperlinkTextDestination Self="HyperlinkTextDestination/#html-blocks" Name="Destination" DestinationUniqueKey="1" />
     <Content>HTML Blocks</Content>
   </CharacterStyleRange>
 </ParagraphStyleRange>
@@ -1697,6 +1714,7 @@
 <Br />
 <ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/Header1">
   <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
+    <HyperlinkTextDestination Self="HyperlinkTextDestination/#inline-markup" Name="Destination" DestinationUniqueKey="1" />
     <Content>Inline Markup</Content>
   </CharacterStyleRange>
 </ParagraphStyleRange>
@@ -1891,19 +1909,14 @@
 <Br />
 <ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/Header1">
   <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
+    <HyperlinkTextDestination Self="HyperlinkTextDestination/#smart-quotes-ellipses-dashes" Name="Destination" DestinationUniqueKey="1" />
     <Content>Smart quotes, ellipses, dashes</Content>
   </CharacterStyleRange>
 </ParagraphStyleRange>
 <Br />
 <ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/Paragraph">
   <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
-    <Content>“</Content>
-  </CharacterStyleRange>
-  <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
-    <Content>Hello,</Content>
-  </CharacterStyleRange>
-  <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
-    <Content>”</Content>
+    <Content>“Hello,”</Content>
   </CharacterStyleRange>
   <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
     <Content> said the spider. </Content>
@@ -1912,55 +1925,28 @@
     <Content>“</Content>
   </CharacterStyleRange>
   <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
-    <Content>‘</Content>
-  </CharacterStyleRange>
-  <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
-    <Content>Shelob</Content>
-  </CharacterStyleRange>
-  <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
-    <Content>’</Content>
-  </CharacterStyleRange>
-  <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
-    <Content> is my name.</Content>
+    <Content>‘Shelob’</Content>
   </CharacterStyleRange>
   <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
-    <Content>”</Content>
+    <Content> is my name.”</Content>
   </CharacterStyleRange>
 </ParagraphStyleRange>
 <Br />
 <ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/Paragraph">
   <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
-    <Content>‘</Content>
-  </CharacterStyleRange>
-  <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
-    <Content>A</Content>
-  </CharacterStyleRange>
-  <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
-    <Content>’</Content>
+    <Content>‘A’</Content>
   </CharacterStyleRange>
   <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
     <Content>, </Content>
   </CharacterStyleRange>
   <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
-    <Content>‘</Content>
-  </CharacterStyleRange>
-  <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
-    <Content>B</Content>
-  </CharacterStyleRange>
-  <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
-    <Content>’</Content>
+    <Content>‘B’</Content>
   </CharacterStyleRange>
   <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
     <Content>, and </Content>
   </CharacterStyleRange>
   <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
-    <Content>‘</Content>
-  </CharacterStyleRange>
-  <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
-    <Content>C</Content>
-  </CharacterStyleRange>
-  <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
-    <Content>’</Content>
+    <Content>‘C’</Content>
   </CharacterStyleRange>
   <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
     <Content> are letters.</Content>
@@ -1969,67 +1955,34 @@
 <Br />
 <ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/Paragraph">
   <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
-    <Content>‘</Content>
-  </CharacterStyleRange>
-  <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
-    <Content>Oak,</Content>
-  </CharacterStyleRange>
-  <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
-    <Content>’</Content>
+    <Content>‘Oak,’</Content>
   </CharacterStyleRange>
   <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
     <Content> </Content>
   </CharacterStyleRange>
   <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
-    <Content>‘</Content>
-  </CharacterStyleRange>
-  <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
-    <Content>elm,</Content>
-  </CharacterStyleRange>
-  <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
-    <Content>’</Content>
+    <Content>‘elm,’</Content>
   </CharacterStyleRange>
   <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
     <Content> and </Content>
   </CharacterStyleRange>
   <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
-    <Content>‘</Content>
-  </CharacterStyleRange>
-  <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
-    <Content>beech</Content>
-  </CharacterStyleRange>
-  <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
-    <Content>’</Content>
+    <Content>‘beech’</Content>
   </CharacterStyleRange>
   <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
     <Content> are names of trees. So is </Content>
   </CharacterStyleRange>
   <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
-    <Content>‘</Content>
-  </CharacterStyleRange>
-  <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
-    <Content>pine.</Content>
-  </CharacterStyleRange>
-  <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
-    <Content>’</Content>
+    <Content>‘pine.’</Content>
   </CharacterStyleRange>
 </ParagraphStyleRange>
 <Br />
 <ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/Paragraph">
   <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
-    <Content>‘</Content>
-  </CharacterStyleRange>
-  <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
-    <Content>He said, </Content>
-  </CharacterStyleRange>
-  <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
-    <Content>“</Content>
-  </CharacterStyleRange>
-  <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
-    <Content>I want to go.</Content>
+    <Content>‘He said, </Content>
   </CharacterStyleRange>
   <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
-    <Content>”</Content>
+    <Content>“I want to go.”</Content>
   </CharacterStyleRange>
   <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
     <Content>’</Content>
@@ -2091,6 +2044,7 @@
 <Br />
 <ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/Header1">
   <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
+    <HyperlinkTextDestination Self="HyperlinkTextDestination/#latex" Name="Destination" DestinationUniqueKey="1" />
     <Content>LaTeX</Content>
   </CharacterStyleRange>
 </ParagraphStyleRange>
@@ -2231,13 +2185,7 @@
     <Content> of money. So is $34,000. (It worked if </Content>
   </CharacterStyleRange>
   <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
-    <Content>“</Content>
-  </CharacterStyleRange>
-  <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
-    <Content>lot</Content>
-  </CharacterStyleRange>
-  <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
-    <Content>”</Content>
+    <Content>“lot”</Content>
   </CharacterStyleRange>
   <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
     <Content> is emphasized.)</Content>
@@ -2276,6 +2224,7 @@
 <Br />
 <ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/Header1">
   <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
+    <HyperlinkTextDestination Self="HyperlinkTextDestination/#special-characters" Name="Destination" DestinationUniqueKey="1" />
     <Content>Special Characters</Content>
   </CharacterStyleRange>
 </ParagraphStyleRange>
@@ -2444,12 +2393,14 @@
 <Br />
 <ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/Header1">
   <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
+    <HyperlinkTextDestination Self="HyperlinkTextDestination/#links" Name="Destination" DestinationUniqueKey="1" />
     <Content>Links</Content>
   </CharacterStyleRange>
 </ParagraphStyleRange>
 <Br />
 <ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/Header2">
   <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
+    <HyperlinkTextDestination Self="HyperlinkTextDestination/#explicit" Name="Destination" DestinationUniqueKey="1" />
     <Content>Explicit</Content>
   </CharacterStyleRange>
 </ParagraphStyleRange>
@@ -2546,6 +2497,7 @@
 <Br />
 <ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/Header2">
   <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
+    <HyperlinkTextDestination Self="HyperlinkTextDestination/#reference" Name="Destination" DestinationUniqueKey="1" />
     <Content>Reference</Content>
   </CharacterStyleRange>
 </ParagraphStyleRange>
@@ -2673,6 +2625,7 @@
 <Br />
 <ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/Header2">
   <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
+    <HyperlinkTextDestination Self="HyperlinkTextDestination/#with-ampersands" Name="Destination" DestinationUniqueKey="1" />
     <Content>With ampersands</Content>
   </CharacterStyleRange>
 </ParagraphStyleRange>
@@ -2735,6 +2688,7 @@
 <Br />
 <ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/Header2">
   <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
+    <HyperlinkTextDestination Self="HyperlinkTextDestination/#autolinks" Name="Destination" DestinationUniqueKey="1" />
     <Content>Autolinks</Content>
   </CharacterStyleRange>
 </ParagraphStyleRange>
@@ -2809,6 +2763,7 @@
 <Br />
 <ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/Header1">
   <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
+    <HyperlinkTextDestination Self="HyperlinkTextDestination/#images" Name="Destination" DestinationUniqueKey="1" />
     <Content>Images</Content>
   </CharacterStyleRange>
 </ParagraphStyleRange>
@@ -2818,13 +2773,7 @@
     <Content>From </Content>
   </CharacterStyleRange>
   <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
-    <Content>“</Content>
-  </CharacterStyleRange>
-  <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
-    <Content>Voyage dans la Lune</Content>
-  </CharacterStyleRange>
-  <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
-    <Content>”</Content>
+    <Content>“Voyage dans la Lune”</Content>
   </CharacterStyleRange>
   <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
     <Content> by Georges Melies (1902):</Content>
@@ -2851,6 +2800,7 @@
           <Profile type="string">
             $ID/Embedded
           </Profile>
+          <GraphicBounds Left="0" Top="0" Right="150" Bottom="150" />
         </Properties>
         <Link Self="ueb" LinkResourceURI="file:lalune.jpg" />
       </Image>
@@ -2887,6 +2837,7 @@
           <Profile type="string">
             $ID/Embedded
           </Profile>
+          <GraphicBounds Left="0" Top="0" Right="20" Bottom="22" />
         </Properties>
         <Link Self="ueb" LinkResourceURI="file:movie.jpg" />
       </Image>
@@ -2899,6 +2850,7 @@
 <Br />
 <ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/Header1">
   <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
+    <HyperlinkTextDestination Self="HyperlinkTextDestination/#footnotes" Name="Destination" DestinationUniqueKey="1" />
     <Content>Footnotes</Content>
   </CharacterStyleRange>
 </ParagraphStyleRange>
@@ -2916,10 +2868,7 @@
       </ParagraphStyleRange>
       <ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/Footnote &gt; Paragraph">
         <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
-          <Content>	</Content>
-        </CharacterStyleRange>
-        <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
-          <Content>Here is the footnote. It can go anywhere after the footnote reference. It need not be placed at the end of the document.</Content>
+          <Content>	Here is the footnote. It can go anywhere after the footnote reference. It need not be placed at the end of the document.</Content>
         </CharacterStyleRange>
       </ParagraphStyleRange>
     </Footnote>
@@ -2936,19 +2885,13 @@
       </ParagraphStyleRange>
       <ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/Footnote &gt; Paragraph">
         <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
-          <Content>	</Content>
-        </CharacterStyleRange>
-        <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
-          <Content>Here’s the long note. This one contains multiple blocks.</Content>
+          <Content>	Here’s the long note. This one contains multiple blocks.</Content>
         </CharacterStyleRange>
       </ParagraphStyleRange>
       <Br />
       <ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/Footnote &gt; Paragraph">
         <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
-          <Content>	</Content>
-        </CharacterStyleRange>
-        <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
-          <Content>Subsequent blocks are indented to show that they belong to the footnote (as with list items).</Content>
+          <Content>	Subsequent blocks are indented to show that they belong to the footnote (as with list items).</Content>
         </CharacterStyleRange>
       </ParagraphStyleRange>
       <Br />
@@ -2960,10 +2903,7 @@
       <Br />
       <ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/Footnote &gt; Paragraph">
         <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
-          <Content>	</Content>
-        </CharacterStyleRange>
-        <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
-          <Content>If you want, you can indent every line, but you can also be lazy and just indent the first line of each block.</Content>
+          <Content>	If you want, you can indent every line, but you can also be lazy and just indent the first line of each block.</Content>
         </CharacterStyleRange>
       </ParagraphStyleRange>
     </Footnote>
@@ -2986,10 +2926,7 @@
       </ParagraphStyleRange>
       <ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/Footnote &gt; Paragraph">
         <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
-          <Content>	</Content>
-        </CharacterStyleRange>
-        <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
-          <Content>This is </Content>
+          <Content>	This is </Content>
         </CharacterStyleRange>
         <CharacterStyleRange AppliedCharacterStyle="CharacterStyle/Italic">
           <Content>easier</Content>
@@ -3029,10 +2966,7 @@
       </ParagraphStyleRange>
       <ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/Footnote &gt; Paragraph">
         <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
-          <Content>	</Content>
-        </CharacterStyleRange>
-        <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
-          <Content>In quote.</Content>
+          <Content>	In quote.</Content>
         </CharacterStyleRange>
       </ParagraphStyleRange>
     </Footnote>
@@ -3052,10 +2986,7 @@
       </ParagraphStyleRange>
       <ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/Footnote &gt; Paragraph">
         <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
-          <Content>	</Content>
-        </CharacterStyleRange>
-        <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
-          <Content>In list.</Content>
+          <Content>	In list.</Content>
         </CharacterStyleRange>
       </ParagraphStyleRange>
     </Footnote>
@@ -3070,203 +3001,203 @@
 
   </Story>
   <HyperlinkURLDestination Self="HyperlinkURLDestination/http%3a//google.com" Name="link" DestinationURL="http://google.com" DestinationUniqueKey="1" />
-  <Hyperlink Self="uf-29" Name="http://google.com" Source="htss-29" Visible="true" DestinationUniqueKey="1">
+  <Hyperlink Self="uf-29" Name="http://google.com" Source="htss-29" Visible="false" DestinationUniqueKey="1">
     <Properties>
       <BorderColor type="enumeration">Black</BorderColor>
       <Destination type="object">HyperlinkURLDestination/http%3a//google.com</Destination>
     </Properties>
   </Hyperlink>
   <HyperlinkURLDestination Self="HyperlinkURLDestination/http%3a//example.com/" Name="link" DestinationURL="http://example.com/" DestinationUniqueKey="1" />
-  <Hyperlink Self="uf-28" Name="http://example.com/" Source="htss-28" Visible="true" DestinationUniqueKey="1">
+  <Hyperlink Self="uf-28" Name="http://example.com/" Source="htss-28" Visible="false" DestinationUniqueKey="1">
     <Properties>
       <BorderColor type="enumeration">Black</BorderColor>
       <Destination type="object">HyperlinkURLDestination/http%3a//example.com/</Destination>
     </Properties>
   </Hyperlink>
   <HyperlinkURLDestination Self="HyperlinkURLDestination/mailto%3anobody@nowhere.net" Name="link" DestinationURL="mailto:nobody@nowhere.net" DestinationUniqueKey="1" />
-  <Hyperlink Self="uf-27" Name="mailto:nobody@nowhere.net" Source="htss-27" Visible="true" DestinationUniqueKey="1">
+  <Hyperlink Self="uf-27" Name="mailto:nobody@nowhere.net" Source="htss-27" Visible="false" DestinationUniqueKey="1">
     <Properties>
       <BorderColor type="enumeration">Black</BorderColor>
       <Destination type="object">HyperlinkURLDestination/mailto%3anobody@nowhere.net</Destination>
     </Properties>
   </Hyperlink>
   <HyperlinkURLDestination Self="HyperlinkURLDestination/http%3a//example.com/" Name="link" DestinationURL="http://example.com/" DestinationUniqueKey="1" />
-  <Hyperlink Self="uf-26" Name="http://example.com/" Source="htss-26" Visible="true" DestinationUniqueKey="1">
+  <Hyperlink Self="uf-26" Name="http://example.com/" Source="htss-26" Visible="false" DestinationUniqueKey="1">
     <Properties>
       <BorderColor type="enumeration">Black</BorderColor>
       <Destination type="object">HyperlinkURLDestination/http%3a//example.com/</Destination>
     </Properties>
   </Hyperlink>
   <HyperlinkURLDestination Self="HyperlinkURLDestination/http%3a//example.com/?foo=1&amp;bar=2" Name="link" DestinationURL="http://example.com/?foo=1&amp;bar=2" DestinationUniqueKey="1" />
-  <Hyperlink Self="uf-25" Name="http://example.com/?foo=1&amp;bar=2" Source="htss-25" Visible="true" DestinationUniqueKey="1">
+  <Hyperlink Self="uf-25" Name="http://example.com/?foo=1&amp;bar=2" Source="htss-25" Visible="false" DestinationUniqueKey="1">
     <Properties>
       <BorderColor type="enumeration">Black</BorderColor>
       <Destination type="object">HyperlinkURLDestination/http%3a//example.com/?foo=1&amp;bar=2</Destination>
     </Properties>
   </Hyperlink>
   <HyperlinkURLDestination Self="HyperlinkURLDestination//script?foo=1&amp;bar=2" Name="link" DestinationURL="/script?foo=1&amp;bar=2" DestinationUniqueKey="1" />
-  <Hyperlink Self="uf-24" Name="/script?foo=1&amp;bar=2" Source="htss-24" Visible="true" DestinationUniqueKey="1">
+  <Hyperlink Self="uf-24" Name="/script?foo=1&amp;bar=2" Source="htss-24" Visible="false" DestinationUniqueKey="1">
     <Properties>
       <BorderColor type="enumeration">Black</BorderColor>
       <Destination type="object">HyperlinkURLDestination//script?foo=1&amp;bar=2</Destination>
     </Properties>
   </Hyperlink>
   <HyperlinkURLDestination Self="HyperlinkURLDestination//script?foo=1&amp;bar=2" Name="link" DestinationURL="/script?foo=1&amp;bar=2" DestinationUniqueKey="1" />
-  <Hyperlink Self="uf-23" Name="/script?foo=1&amp;bar=2" Source="htss-23" Visible="true" DestinationUniqueKey="1">
+  <Hyperlink Self="uf-23" Name="/script?foo=1&amp;bar=2" Source="htss-23" Visible="false" DestinationUniqueKey="1">
     <Properties>
       <BorderColor type="enumeration">Black</BorderColor>
       <Destination type="object">HyperlinkURLDestination//script?foo=1&amp;bar=2</Destination>
     </Properties>
   </Hyperlink>
   <HyperlinkURLDestination Self="HyperlinkURLDestination/http%3a//att.com/" Name="link" DestinationURL="http://att.com/" DestinationUniqueKey="1" />
-  <Hyperlink Self="uf-22" Name="http://att.com/" Source="htss-22" Visible="true" DestinationUniqueKey="1">
+  <Hyperlink Self="uf-22" Name="http://att.com/" Source="htss-22" Visible="false" DestinationUniqueKey="1">
     <Properties>
       <BorderColor type="enumeration">Black</BorderColor>
       <Destination type="object">HyperlinkURLDestination/http%3a//att.com/</Destination>
     </Properties>
   </Hyperlink>
   <HyperlinkURLDestination Self="HyperlinkURLDestination/http%3a//example.com/?foo=1&amp;bar=2" Name="link" DestinationURL="http://example.com/?foo=1&amp;bar=2" DestinationUniqueKey="1" />
-  <Hyperlink Self="uf-21" Name="http://example.com/?foo=1&amp;bar=2" Source="htss-21" Visible="true" DestinationUniqueKey="1">
+  <Hyperlink Self="uf-21" Name="http://example.com/?foo=1&amp;bar=2" Source="htss-21" Visible="false" DestinationUniqueKey="1">
     <Properties>
       <BorderColor type="enumeration">Black</BorderColor>
       <Destination type="object">HyperlinkURLDestination/http%3a//example.com/?foo=1&amp;bar=2</Destination>
     </Properties>
   </Hyperlink>
   <HyperlinkURLDestination Self="HyperlinkURLDestination//url/" Name="link" DestinationURL="/url/" DestinationUniqueKey="1" />
-  <Hyperlink Self="uf-20" Name="/url/" Source="htss-20" Visible="true" DestinationUniqueKey="1">
+  <Hyperlink Self="uf-20" Name="/url/" Source="htss-20" Visible="false" DestinationUniqueKey="1">
     <Properties>
       <BorderColor type="enumeration">Black</BorderColor>
       <Destination type="object">HyperlinkURLDestination//url/</Destination>
     </Properties>
   </Hyperlink>
   <HyperlinkURLDestination Self="HyperlinkURLDestination//url/" Name="link" DestinationURL="/url/" DestinationUniqueKey="1" />
-  <Hyperlink Self="uf-19" Name="/url/" Source="htss-19" Visible="true" DestinationUniqueKey="1">
+  <Hyperlink Self="uf-19" Name="/url/" Source="htss-19" Visible="false" DestinationUniqueKey="1">
     <Properties>
       <BorderColor type="enumeration">Black</BorderColor>
       <Destination type="object">HyperlinkURLDestination//url/</Destination>
     </Properties>
   </Hyperlink>
   <HyperlinkURLDestination Self="HyperlinkURLDestination//url" Name="link" DestinationURL="/url" DestinationUniqueKey="1" />
-  <Hyperlink Self="uf-18" Name="/url" Source="htss-18" Visible="true" DestinationUniqueKey="1">
+  <Hyperlink Self="uf-18" Name="/url" Source="htss-18" Visible="false" DestinationUniqueKey="1">
     <Properties>
       <BorderColor type="enumeration">Black</BorderColor>
       <Destination type="object">HyperlinkURLDestination//url</Destination>
     </Properties>
   </Hyperlink>
   <HyperlinkURLDestination Self="HyperlinkURLDestination//url" Name="link" DestinationURL="/url" DestinationUniqueKey="1" />
-  <Hyperlink Self="uf-17" Name="/url" Source="htss-17" Visible="true" DestinationUniqueKey="1">
+  <Hyperlink Self="uf-17" Name="/url" Source="htss-17" Visible="false" DestinationUniqueKey="1">
     <Properties>
       <BorderColor type="enumeration">Black</BorderColor>
       <Destination type="object">HyperlinkURLDestination//url</Destination>
     </Properties>
   </Hyperlink>
   <HyperlinkURLDestination Self="HyperlinkURLDestination//url" Name="link" DestinationURL="/url" DestinationUniqueKey="1" />
-  <Hyperlink Self="uf-16" Name="/url" Source="htss-16" Visible="true" DestinationUniqueKey="1">
+  <Hyperlink Self="uf-16" Name="/url" Source="htss-16" Visible="false" DestinationUniqueKey="1">
     <Properties>
       <BorderColor type="enumeration">Black</BorderColor>
       <Destination type="object">HyperlinkURLDestination//url</Destination>
     </Properties>
   </Hyperlink>
   <HyperlinkURLDestination Self="HyperlinkURLDestination//url/" Name="link" DestinationURL="/url/" DestinationUniqueKey="1" />
-  <Hyperlink Self="uf-15" Name="/url/" Source="htss-15" Visible="true" DestinationUniqueKey="1">
+  <Hyperlink Self="uf-15" Name="/url/" Source="htss-15" Visible="false" DestinationUniqueKey="1">
     <Properties>
       <BorderColor type="enumeration">Black</BorderColor>
       <Destination type="object">HyperlinkURLDestination//url/</Destination>
     </Properties>
   </Hyperlink>
   <HyperlinkURLDestination Self="HyperlinkURLDestination//url/" Name="link" DestinationURL="/url/" DestinationUniqueKey="1" />
-  <Hyperlink Self="uf-14" Name="/url/" Source="htss-14" Visible="true" DestinationUniqueKey="1">
+  <Hyperlink Self="uf-14" Name="/url/" Source="htss-14" Visible="false" DestinationUniqueKey="1">
     <Properties>
       <BorderColor type="enumeration">Black</BorderColor>
       <Destination type="object">HyperlinkURLDestination//url/</Destination>
     </Properties>
   </Hyperlink>
   <HyperlinkURLDestination Self="HyperlinkURLDestination//url/" Name="link" DestinationURL="/url/" DestinationUniqueKey="1" />
-  <Hyperlink Self="uf-13" Name="/url/" Source="htss-13" Visible="true" DestinationUniqueKey="1">
+  <Hyperlink Self="uf-13" Name="/url/" Source="htss-13" Visible="false" DestinationUniqueKey="1">
     <Properties>
       <BorderColor type="enumeration">Black</BorderColor>
       <Destination type="object">HyperlinkURLDestination//url/</Destination>
     </Properties>
   </Hyperlink>
   <HyperlinkURLDestination Self="HyperlinkURLDestination/" Name="link" DestinationURL="" DestinationUniqueKey="1" />
-  <Hyperlink Self="uf-12" Name="" Source="htss-12" Visible="true" DestinationUniqueKey="1">
+  <Hyperlink Self="uf-12" Name="" Source="htss-12" Visible="false" DestinationUniqueKey="1">
     <Properties>
       <BorderColor type="enumeration">Black</BorderColor>
       <Destination type="object">HyperlinkURLDestination/</Destination>
     </Properties>
   </Hyperlink>
   <HyperlinkURLDestination Self="HyperlinkURLDestination/mailto%3anobody@nowhere.net" Name="link" DestinationURL="mailto:nobody@nowhere.net" DestinationUniqueKey="1" />
-  <Hyperlink Self="uf-11" Name="mailto:nobody@nowhere.net" Source="htss-11" Visible="true" DestinationUniqueKey="1">
+  <Hyperlink Self="uf-11" Name="mailto:nobody@nowhere.net" Source="htss-11" Visible="false" DestinationUniqueKey="1">
     <Properties>
       <BorderColor type="enumeration">Black</BorderColor>
       <Destination type="object">HyperlinkURLDestination/mailto%3anobody@nowhere.net</Destination>
     </Properties>
   </Hyperlink>
   <HyperlinkURLDestination Self="HyperlinkURLDestination//url/with_underscore" Name="link" DestinationURL="/url/with_underscore" DestinationUniqueKey="1" />
-  <Hyperlink Self="uf-10" Name="/url/with_underscore" Source="htss-10" Visible="true" DestinationUniqueKey="1">
+  <Hyperlink Self="uf-10" Name="/url/with_underscore" Source="htss-10" Visible="false" DestinationUniqueKey="1">
     <Properties>
       <BorderColor type="enumeration">Black</BorderColor>
       <Destination type="object">HyperlinkURLDestination//url/with_underscore</Destination>
     </Properties>
   </Hyperlink>
   <HyperlinkURLDestination Self="HyperlinkURLDestination//url/" Name="link" DestinationURL="/url/" DestinationUniqueKey="1" />
-  <Hyperlink Self="uf-9" Name="/url/" Source="htss-9" Visible="true" DestinationUniqueKey="1">
+  <Hyperlink Self="uf-9" Name="/url/" Source="htss-9" Visible="false" DestinationUniqueKey="1">
     <Properties>
       <BorderColor type="enumeration">Black</BorderColor>
       <Destination type="object">HyperlinkURLDestination//url/</Destination>
     </Properties>
   </Hyperlink>
   <HyperlinkURLDestination Self="HyperlinkURLDestination//url/" Name="link" DestinationURL="/url/" DestinationUniqueKey="1" />
-  <Hyperlink Self="uf-8" Name="/url/" Source="htss-8" Visible="true" DestinationUniqueKey="1">
+  <Hyperlink Self="uf-8" Name="/url/" Source="htss-8" Visible="false" DestinationUniqueKey="1">
     <Properties>
       <BorderColor type="enumeration">Black</BorderColor>
       <Destination type="object">HyperlinkURLDestination//url/</Destination>
     </Properties>
   </Hyperlink>
   <HyperlinkURLDestination Self="HyperlinkURLDestination//url/" Name="link" DestinationURL="/url/" DestinationUniqueKey="1" />
-  <Hyperlink Self="uf-7" Name="/url/" Source="htss-7" Visible="true" DestinationUniqueKey="1">
+  <Hyperlink Self="uf-7" Name="/url/" Source="htss-7" Visible="false" DestinationUniqueKey="1">
     <Properties>
       <BorderColor type="enumeration">Black</BorderColor>
       <Destination type="object">HyperlinkURLDestination//url/</Destination>
     </Properties>
   </Hyperlink>
   <HyperlinkURLDestination Self="HyperlinkURLDestination//url/" Name="link" DestinationURL="/url/" DestinationUniqueKey="1" />
-  <Hyperlink Self="uf-6" Name="/url/" Source="htss-6" Visible="true" DestinationUniqueKey="1">
+  <Hyperlink Self="uf-6" Name="/url/" Source="htss-6" Visible="false" DestinationUniqueKey="1">
     <Properties>
       <BorderColor type="enumeration">Black</BorderColor>
       <Destination type="object">HyperlinkURLDestination//url/</Destination>
     </Properties>
   </Hyperlink>
   <HyperlinkURLDestination Self="HyperlinkURLDestination//url/" Name="link" DestinationURL="/url/" DestinationUniqueKey="1" />
-  <Hyperlink Self="uf-5" Name="/url/" Source="htss-5" Visible="true" DestinationUniqueKey="1">
+  <Hyperlink Self="uf-5" Name="/url/" Source="htss-5" Visible="false" DestinationUniqueKey="1">
     <Properties>
       <BorderColor type="enumeration">Black</BorderColor>
       <Destination type="object">HyperlinkURLDestination//url/</Destination>
     </Properties>
   </Hyperlink>
   <HyperlinkURLDestination Self="HyperlinkURLDestination//url/" Name="link" DestinationURL="/url/" DestinationUniqueKey="1" />
-  <Hyperlink Self="uf-4" Name="/url/" Source="htss-4" Visible="true" DestinationUniqueKey="1">
+  <Hyperlink Self="uf-4" Name="/url/" Source="htss-4" Visible="false" DestinationUniqueKey="1">
     <Properties>
       <BorderColor type="enumeration">Black</BorderColor>
       <Destination type="object">HyperlinkURLDestination//url/</Destination>
     </Properties>
   </Hyperlink>
   <HyperlinkURLDestination Self="HyperlinkURLDestination/http%3a//example.com/?foo=1&amp;bar=2" Name="link" DestinationURL="http://example.com/?foo=1&amp;bar=2" DestinationUniqueKey="1" />
-  <Hyperlink Self="uf-3" Name="http://example.com/?foo=1&amp;bar=2" Source="htss-3" Visible="true" DestinationUniqueKey="1">
+  <Hyperlink Self="uf-3" Name="http://example.com/?foo=1&amp;bar=2" Source="htss-3" Visible="false" DestinationUniqueKey="1">
     <Properties>
       <BorderColor type="enumeration">Black</BorderColor>
       <Destination type="object">HyperlinkURLDestination/http%3a//example.com/?foo=1&amp;bar=2</Destination>
     </Properties>
   </Hyperlink>
   <HyperlinkURLDestination Self="HyperlinkURLDestination//url" Name="link" DestinationURL="/url" DestinationUniqueKey="1" />
-  <Hyperlink Self="uf-2" Name="/url" Source="htss-2" Visible="true" DestinationUniqueKey="1">
+  <Hyperlink Self="uf-2" Name="/url" Source="htss-2" Visible="false" DestinationUniqueKey="1">
     <Properties>
       <BorderColor type="enumeration">Black</BorderColor>
       <Destination type="object">HyperlinkURLDestination//url</Destination>
     </Properties>
   </Hyperlink>
   <HyperlinkURLDestination Self="HyperlinkURLDestination//url" Name="link" DestinationURL="/url" DestinationUniqueKey="1" />
-  <Hyperlink Self="uf-1" Name="/url" Source="htss-1" Visible="true" DestinationUniqueKey="1">
+  <Hyperlink Self="uf-1" Name="/url" Source="htss-1" Visible="false" DestinationUniqueKey="1">
     <Properties>
       <BorderColor type="enumeration">Black</BorderColor>
       <Destination type="object">HyperlinkURLDestination//url</Destination>
diff --git a/test/writer.jats b/test/writer.jats
deleted file mode 100644
--- a/test/writer.jats
+++ /dev/null
@@ -1,1448 +0,0 @@
-<?xml version="1.0" encoding="utf-8" ?>
-<!DOCTYPE article PUBLIC "-//NLM//DTD JATS (Z39.96) Journal Publishing DTD v1.0 20120330//EN"
-                  "JATS-journalpublishing1.dtd">
-<article xmlns:mml="http://www.w3.org/1998/Math/MathML" xmlns:xlink="http://www.w3.org/1999/xlink" dtd-version="1.0" article-type="other">
-<front>
-<journal-meta>
-<journal-title-group>
-</journal-title-group>
-<publisher>
-<publisher-name></publisher-name>
-</publisher>
-</journal-meta>
-<article-meta>
-<title-group>
-<article-title>Pandoc Test Suite</article-title>
-</title-group>
-<contrib-group>
-<contrib contrib-type="author">
-<name>
-<string-name>John MacFarlane</string-name>
-</name>
-</contrib>
-<contrib contrib-type="author">
-<name>
-<string-name>Anonymous</string-name>
-</name>
-</contrib>
-</contrib-group>
-<pub-date pub-type="epub">
-<string-date>July 17, 2006</string-date>
-</pub-date>
-</article-meta>
-</front>
-<body>
-<p>
-  This is a set of tests for pandoc. Most of them are adapted from John
-  Gruber’s markdown test suite.
-</p>
-<sec id="headers">
-  <title>Headers</title>
-  <sec id="level-2-with-an-embedded-link">
-    <title>Level 2 with an
-    <ext-link ext-link-type="uri" xlink:href="/url">embedded
-    link</ext-link></title>
-    <sec id="level-3-with-emphasis">
-      <title>Level 3 with <italic>emphasis</italic></title>
-      <sec id="level-4">
-        <title>Level 4</title>
-        <sec id="level-5">
-          <title>Level 5</title>
-        </sec>
-      </sec>
-    </sec>
-  </sec>
-</sec>
-<sec id="level-1">
-  <title>Level 1</title>
-  <sec id="level-2-with-emphasis">
-    <title>Level 2 with <italic>emphasis</italic></title>
-    <sec id="level-3">
-      <title>Level 3</title>
-      <p>
-        with no blank line
-      </p>
-    </sec>
-  </sec>
-  <sec id="level-2">
-    <title>Level 2</title>
-    <p>
-      with no blank line
-    </p>
-  </sec>
-</sec>
-<sec id="paragraphs">
-  <title>Paragraphs</title>
-  <p>
-    Here’s a regular paragraph.
-  </p>
-  <p>
-    In Markdown 1.0.0 and earlier. Version 8. This line turns into a list
-    item. Because a hard-wrapped line in the middle of a paragraph looked like
-    a list item.
-  </p>
-  <p>
-    Here’s one with a bullet. * criminey.
-  </p>
-  <p>
-    There should be a hard line break<break />here.
-  </p>
-</sec>
-<sec id="block-quotes">
-  <title>Block Quotes</title>
-  <p>
-    E-mail style:
-  </p>
-  <disp-quote>
-    <p>
-      This is a block quote. It is pretty short.
-    </p>
-  </disp-quote>
-  <disp-quote>
-    <p>
-      Code in a block quote:
-    </p>
-    <preformat>sub status {
-    print &quot;working&quot;;
-}</preformat>
-    <p>
-      A list:
-    </p>
-    <list list-type="order">
-      <list-item>
-        <p>
-          item one
-        </p>
-      </list-item>
-      <list-item>
-        <p>
-          item two
-        </p>
-      </list-item>
-    </list>
-    <p>
-      Nested block quotes:
-    </p>
-    <disp-quote>
-      <p>
-        nested
-      </p>
-    </disp-quote>
-    <disp-quote>
-      <p>
-        nested
-      </p>
-    </disp-quote>
-  </disp-quote>
-  <p>
-    This should not be a block quote: 2 &gt; 1.
-  </p>
-  <p>
-    And a following paragraph.
-  </p>
-</sec>
-<sec id="code-blocks">
-  <title>Code Blocks</title>
-  <p>
-    Code:
-  </p>
-  <preformat>---- (should be four hyphens)
-
-sub status {
-    print &quot;working&quot;;
-}
-
-this code block is indented by one tab</preformat>
-  <p>
-    And:
-  </p>
-  <preformat>    this code block is indented by two tabs
-
-These should not be escaped:  \$ \\ \&gt; \[ \{</preformat>
-</sec>
-<sec id="lists">
-  <title>Lists</title>
-  <sec id="unordered">
-    <title>Unordered</title>
-    <p>
-      Asterisks tight:
-    </p>
-    <list list-type="bullet">
-      <list-item>
-        <p>
-          asterisk 1
-        </p>
-      </list-item>
-      <list-item>
-        <p>
-          asterisk 2
-        </p>
-      </list-item>
-      <list-item>
-        <p>
-          asterisk 3
-        </p>
-      </list-item>
-    </list>
-    <p>
-      Asterisks loose:
-    </p>
-    <list list-type="bullet">
-      <list-item>
-        <p>
-          asterisk 1
-        </p>
-      </list-item>
-      <list-item>
-        <p>
-          asterisk 2
-        </p>
-      </list-item>
-      <list-item>
-        <p>
-          asterisk 3
-        </p>
-      </list-item>
-    </list>
-    <p>
-      Pluses tight:
-    </p>
-    <list list-type="bullet">
-      <list-item>
-        <p>
-          Plus 1
-        </p>
-      </list-item>
-      <list-item>
-        <p>
-          Plus 2
-        </p>
-      </list-item>
-      <list-item>
-        <p>
-          Plus 3
-        </p>
-      </list-item>
-    </list>
-    <p>
-      Pluses loose:
-    </p>
-    <list list-type="bullet">
-      <list-item>
-        <p>
-          Plus 1
-        </p>
-      </list-item>
-      <list-item>
-        <p>
-          Plus 2
-        </p>
-      </list-item>
-      <list-item>
-        <p>
-          Plus 3
-        </p>
-      </list-item>
-    </list>
-    <p>
-      Minuses tight:
-    </p>
-    <list list-type="bullet">
-      <list-item>
-        <p>
-          Minus 1
-        </p>
-      </list-item>
-      <list-item>
-        <p>
-          Minus 2
-        </p>
-      </list-item>
-      <list-item>
-        <p>
-          Minus 3
-        </p>
-      </list-item>
-    </list>
-    <p>
-      Minuses loose:
-    </p>
-    <list list-type="bullet">
-      <list-item>
-        <p>
-          Minus 1
-        </p>
-      </list-item>
-      <list-item>
-        <p>
-          Minus 2
-        </p>
-      </list-item>
-      <list-item>
-        <p>
-          Minus 3
-        </p>
-      </list-item>
-    </list>
-  </sec>
-  <sec id="ordered">
-    <title>Ordered</title>
-    <p>
-      Tight:
-    </p>
-    <list list-type="order">
-      <list-item>
-        <p>
-          First
-        </p>
-      </list-item>
-      <list-item>
-        <p>
-          Second
-        </p>
-      </list-item>
-      <list-item>
-        <p>
-          Third
-        </p>
-      </list-item>
-    </list>
-    <p>
-      and:
-    </p>
-    <list list-type="order">
-      <list-item>
-        <p>
-          One
-        </p>
-      </list-item>
-      <list-item>
-        <p>
-          Two
-        </p>
-      </list-item>
-      <list-item>
-        <p>
-          Three
-        </p>
-      </list-item>
-    </list>
-    <p>
-      Loose using tabs:
-    </p>
-    <list list-type="order">
-      <list-item>
-        <p>
-          First
-        </p>
-      </list-item>
-      <list-item>
-        <p>
-          Second
-        </p>
-      </list-item>
-      <list-item>
-        <p>
-          Third
-        </p>
-      </list-item>
-    </list>
-    <p>
-      and using spaces:
-    </p>
-    <list list-type="order">
-      <list-item>
-        <p>
-          One
-        </p>
-      </list-item>
-      <list-item>
-        <p>
-          Two
-        </p>
-      </list-item>
-      <list-item>
-        <p>
-          Three
-        </p>
-      </list-item>
-    </list>
-    <p>
-      Multiple paragraphs:
-    </p>
-    <list list-type="order">
-      <list-item>
-        <p>
-          Item 1, graf one.
-        </p>
-        <p>
-          Item 1. graf two. The quick brown fox jumped over the lazy dog’s
-          back.
-        </p>
-      </list-item>
-      <list-item>
-        <p>
-          Item 2.
-        </p>
-      </list-item>
-      <list-item>
-        <p>
-          Item 3.
-        </p>
-      </list-item>
-    </list>
-  </sec>
-  <sec id="nested">
-    <title>Nested</title>
-    <list list-type="bullet">
-      <list-item>
-        <p>
-          Tab
-        </p>
-        <list list-type="bullet">
-          <list-item>
-            <p>
-              Tab
-            </p>
-            <list list-type="bullet">
-              <list-item>
-                <p>
-                  Tab
-                </p>
-              </list-item>
-            </list>
-          </list-item>
-        </list>
-      </list-item>
-    </list>
-    <p>
-      Here’s another:
-    </p>
-    <list list-type="order">
-      <list-item>
-        <p>
-          First
-        </p>
-      </list-item>
-      <list-item>
-        <p>
-          Second:
-        </p>
-        <list list-type="bullet">
-          <list-item>
-            <p>
-              Fee
-            </p>
-          </list-item>
-          <list-item>
-            <p>
-              Fie
-            </p>
-          </list-item>
-          <list-item>
-            <p>
-              Foe
-            </p>
-          </list-item>
-        </list>
-      </list-item>
-      <list-item>
-        <p>
-          Third
-        </p>
-      </list-item>
-    </list>
-    <p>
-      Same thing but with paragraphs:
-    </p>
-    <list list-type="order">
-      <list-item>
-        <p>
-          First
-        </p>
-      </list-item>
-      <list-item>
-        <p>
-          Second:
-        </p>
-        <list list-type="bullet">
-          <list-item>
-            <p>
-              Fee
-            </p>
-          </list-item>
-          <list-item>
-            <p>
-              Fie
-            </p>
-          </list-item>
-          <list-item>
-            <p>
-              Foe
-            </p>
-          </list-item>
-        </list>
-      </list-item>
-      <list-item>
-        <p>
-          Third
-        </p>
-      </list-item>
-    </list>
-  </sec>
-  <sec id="tabs-and-spaces">
-    <title>Tabs and spaces</title>
-    <list list-type="bullet">
-      <list-item>
-        <p>
-          this is a list item indented with tabs
-        </p>
-      </list-item>
-      <list-item>
-        <p>
-          this is a list item indented with spaces
-        </p>
-        <list list-type="bullet">
-          <list-item>
-            <p>
-              this is an example list item indented with tabs
-            </p>
-          </list-item>
-          <list-item>
-            <p>
-              this is an example list item indented with spaces
-            </p>
-          </list-item>
-        </list>
-      </list-item>
-    </list>
-  </sec>
-  <sec id="fancy-list-markers">
-    <title>Fancy list markers</title>
-    <list list-type="order">
-      <list-item>
-        <label>
-          (2)
-        </label>
-        <p>
-          begins with 2
-        </p>
-      </list-item>
-      <list-item>
-        <label>
-          (3)
-        </label>
-        <p>
-          and now 3
-        </p>
-        <p>
-          with a continuation
-        </p>
-        <list list-type="roman-lower">
-          <list-item>
-            <label>
-              iv.
-            </label>
-            <p>
-              sublist with roman numerals, starting with 4
-            </p>
-          </list-item>
-          <list-item>
-            <label>
-              v.
-            </label>
-            <p>
-              more items
-            </p>
-            <list list-type="alpha-upper">
-              <list-item>
-                <label>
-                  (A)
-                </label>
-                <p>
-                  a subsublist
-                </p>
-              </list-item>
-              <list-item>
-                <label>
-                  (B)
-                </label>
-                <p>
-                  a subsublist
-                </p>
-              </list-item>
-            </list>
-          </list-item>
-        </list>
-      </list-item>
-    </list>
-    <p>
-      Nesting:
-    </p>
-    <list list-type="alpha-upper">
-      <list-item>
-        <p>
-          Upper Alpha
-        </p>
-        <list list-type="roman-upper">
-          <list-item>
-            <p>
-              Upper Roman.
-            </p>
-            <list list-type="order">
-              <list-item>
-                <label>
-                  (6)
-                </label>
-                <p>
-                  Decimal start with 6
-                </p>
-                <list list-type="alpha-lower">
-                  <list-item>
-                    <label>
-                      c)
-                    </label>
-                    <p>
-                      Lower alpha with paren
-                    </p>
-                  </list-item>
-                </list>
-              </list-item>
-            </list>
-          </list-item>
-        </list>
-      </list-item>
-    </list>
-    <p>
-      Autonumbering:
-    </p>
-    <list list-type="order">
-      <list-item>
-        <p>
-          Autonumber.
-        </p>
-      </list-item>
-      <list-item>
-        <p>
-          More.
-        </p>
-        <list list-type="order">
-          <list-item>
-            <p>
-              Nested.
-            </p>
-          </list-item>
-        </list>
-      </list-item>
-    </list>
-    <p>
-      Should not be a list item:
-    </p>
-    <p>
-      M.A. 2007
-    </p>
-    <p>
-      B. Williams
-    </p>
-  </sec>
-</sec>
-<sec id="definition-lists">
-  <title>Definition Lists</title>
-  <p>
-    Tight using spaces:
-  </p>
-  <def-list>
-    <def-item>
-      <term>
-        apple
-      </term>
-      <def>
-        <p>
-          red fruit
-        </p>
-      </def>
-    </def-item>
-    <def-item>
-      <term>
-        orange
-      </term>
-      <def>
-        <p>
-          orange fruit
-        </p>
-      </def>
-    </def-item>
-    <def-item>
-      <term>
-        banana
-      </term>
-      <def>
-        <p>
-          yellow fruit
-        </p>
-      </def>
-    </def-item>
-  </def-list>
-  <p>
-    Tight using tabs:
-  </p>
-  <def-list>
-    <def-item>
-      <term>
-        apple
-      </term>
-      <def>
-        <p>
-          red fruit
-        </p>
-      </def>
-    </def-item>
-    <def-item>
-      <term>
-        orange
-      </term>
-      <def>
-        <p>
-          orange fruit
-        </p>
-      </def>
-    </def-item>
-    <def-item>
-      <term>
-        banana
-      </term>
-      <def>
-        <p>
-          yellow fruit
-        </p>
-      </def>
-    </def-item>
-  </def-list>
-  <p>
-    Loose:
-  </p>
-  <def-list>
-    <def-item>
-      <term>
-        apple
-      </term>
-      <def>
-        <p>
-          red fruit
-        </p>
-      </def>
-    </def-item>
-    <def-item>
-      <term>
-        orange
-      </term>
-      <def>
-        <p>
-          orange fruit
-        </p>
-      </def>
-    </def-item>
-    <def-item>
-      <term>
-        banana
-      </term>
-      <def>
-        <p>
-          yellow fruit
-        </p>
-      </def>
-    </def-item>
-  </def-list>
-  <p>
-    Multiple blocks with italics:
-  </p>
-  <def-list>
-    <def-item>
-      <term>
-        <italic>apple</italic>
-      </term>
-      <def>
-        <p>
-          red fruit
-        </p>
-        <p>
-          contains seeds, crisp, pleasant to taste
-        </p>
-      </def>
-    </def-item>
-    <def-item>
-      <term>
-        <italic>orange</italic>
-      </term>
-      <def>
-        <p>
-          orange fruit
-        </p>
-        <preformat>{ orange code block }</preformat>
-        <disp-quote>
-          <p>
-            orange block quote
-          </p>
-        </disp-quote>
-      </def>
-    </def-item>
-  </def-list>
-  <p>
-    Multiple definitions, tight:
-  </p>
-  <def-list>
-    <def-item>
-      <term>
-        apple
-      </term>
-      <def>
-        <p>
-          red fruit
-        </p>
-        <p>
-          computer
-        </p>
-      </def>
-    </def-item>
-    <def-item>
-      <term>
-        orange
-      </term>
-      <def>
-        <p>
-          orange fruit
-        </p>
-        <p>
-          bank
-        </p>
-      </def>
-    </def-item>
-  </def-list>
-  <p>
-    Multiple definitions, loose:
-  </p>
-  <def-list>
-    <def-item>
-      <term>
-        apple
-      </term>
-      <def>
-        <p>
-          red fruit
-        </p>
-        <p>
-          computer
-        </p>
-      </def>
-    </def-item>
-    <def-item>
-      <term>
-        orange
-      </term>
-      <def>
-        <p>
-          orange fruit
-        </p>
-        <p>
-          bank
-        </p>
-      </def>
-    </def-item>
-  </def-list>
-  <p>
-    Blank line after term, indented marker, alternate markers:
-  </p>
-  <def-list>
-    <def-item>
-      <term>
-        apple
-      </term>
-      <def>
-        <p>
-          red fruit
-        </p>
-        <p>
-          computer
-        </p>
-      </def>
-    </def-item>
-    <def-item>
-      <term>
-        orange
-      </term>
-      <def>
-        <p>
-          orange fruit
-        </p>
-        <list list-type="order">
-          <list-item>
-            <p>
-              sublist
-            </p>
-          </list-item>
-          <list-item>
-            <p>
-              sublist
-            </p>
-          </list-item>
-        </list>
-      </def>
-    </def-item>
-  </def-list>
-</sec>
-<sec id="html-blocks">
-  <title>HTML Blocks</title>
-  <p>
-    Simple block on one line:
-  </p>
-  <boxed-text>
-    <p>
-      foo
-    </p>
-  </boxed-text>
-  <p>
-    And nested without indentation:
-  </p>
-  <boxed-text>
-    <boxed-text>
-      <boxed-text>
-        <p>
-          foo
-        </p>
-      </boxed-text>
-    </boxed-text>
-    <boxed-text>
-      <p>
-        bar
-      </p>
-    </boxed-text>
-  </boxed-text>
-  <p>
-    Interpreted markdown in a table:
-  </p>
-  <p>
-    This is <italic>emphasized</italic>
-  </p>
-  <p>
-    And this is <bold role="strong">strong</bold>
-  </p>
-  <p>
-    Here’s a simple block:
-  </p>
-  <boxed-text>
-    <p>
-      foo
-    </p>
-  </boxed-text>
-  <p>
-    This should be a code block, though:
-  </p>
-  <preformat>&lt;div&gt;
-    foo
-&lt;/div&gt;</preformat>
-  <p>
-    As should this:
-  </p>
-  <preformat>&lt;div&gt;foo&lt;/div&gt;</preformat>
-  <p>
-    Now, nested:
-  </p>
-  <boxed-text>
-    <boxed-text>
-      <boxed-text>
-        <p>
-          foo
-        </p>
-      </boxed-text>
-    </boxed-text>
-  </boxed-text>
-  <p>
-    This should just be an HTML comment:
-  </p>
-  <p>
-    Multiline:
-  </p>
-  <p>
-    Code block:
-  </p>
-  <preformat>&lt;!-- Comment --&gt;</preformat>
-  <p>
-    Just plain comment, with trailing spaces on the line:
-  </p>
-  <p>
-    Code:
-  </p>
-  <preformat>&lt;hr /&gt;</preformat>
-  <p>
-    Hr’s:
-  </p>
-</sec>
-<sec id="inline-markup">
-  <title>Inline Markup</title>
-  <p>
-    This is <italic>emphasized</italic>, and so <italic>is this</italic>.
-  </p>
-  <p>
-    This is <bold role="strong">strong</bold>, and so <bold role="strong">is
-    this</bold>.
-  </p>
-  <p>
-    An <italic><ext-link ext-link-type="uri" xlink:href="/url">emphasized
-    link</ext-link></italic>.
-  </p>
-  <p>
-    <bold role="strong"><italic>This is strong and em.</italic></bold>
-  </p>
-  <p>
-    So is <bold role="strong"><italic>this</italic></bold> word.
-  </p>
-  <p>
-    <bold role="strong"><italic>This is strong and em.</italic></bold>
-  </p>
-  <p>
-    So is <bold role="strong"><italic>this</italic></bold> word.
-  </p>
-  <p>
-    This is code: <monospace>&gt;</monospace>, <monospace>$</monospace>,
-    <monospace>\</monospace>, <monospace>\$</monospace>,
-    <monospace>&lt;html&gt;</monospace>.
-  </p>
-  <p>
-    <strike>This is <italic>strikeout</italic>.</strike>
-  </p>
-  <p>
-    Superscripts: a<sup>bc</sup>d a<sup><italic>hello</italic></sup>
-    a<sup>hello there</sup>.
-  </p>
-  <p>
-    Subscripts: H<sub>2</sub>O, H<sub>23</sub>O, H<sub>many of them</sub>O.
-  </p>
-  <p>
-    These should not be superscripts or subscripts, because of the unescaped
-    spaces: a^b c^d, a~b c~d.
-  </p>
-</sec>
-<sec id="smart-quotes-ellipses-dashes">
-  <title>Smart quotes, ellipses, dashes</title>
-  <p>
-    “Hello,” said the spider. “‘Shelob’ is my name.”
-  </p>
-  <p>
-    ‘A’, ‘B’, and ‘C’ are letters.
-  </p>
-  <p>
-    ‘Oak,’ ‘elm,’ and ‘beech’ are names of trees. So is ‘pine.’
-  </p>
-  <p>
-    ‘He said, “I want to go.”’ Were you alive in the 70’s?
-  </p>
-  <p>
-    Here is some quoted ‘<monospace>code</monospace>’ and a
-    “<ext-link ext-link-type="uri" xlink:href="http://example.com/?foo=1&amp;bar=2">quoted
-    link</ext-link>”.
-  </p>
-  <p>
-    Some dashes: one—two — three—four — five.
-  </p>
-  <p>
-    Dashes between numbers: 5–7, 255–66, 1987–1999.
-  </p>
-  <p>
-    Ellipses…and…and….
-  </p>
-</sec>
-<sec id="latex">
-  <title>LaTeX</title>
-  <list list-type="bullet">
-    <list-item>
-      <p>
-      </p>
-    </list-item>
-    <list-item>
-      <p>
-        <inline-formula><alternatives>
-        <tex-math><![CDATA[2+2=4]]></tex-math>
-        <mml:math display="inline" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mrow><mml:mn>2</mml:mn><mml:mo>+</mml:mo><mml:mn>2</mml:mn><mml:mo>=</mml:mo><mml:mn>4</mml:mn></mml:mrow></mml:math></alternatives></inline-formula>
-      </p>
-    </list-item>
-    <list-item>
-      <p>
-        <inline-formula><alternatives>
-        <tex-math><![CDATA[x \in y]]></tex-math>
-        <mml:math display="inline" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mrow><mml:mi>x</mml:mi><mml:mo>∈</mml:mo><mml:mi>y</mml:mi></mml:mrow></mml:math></alternatives></inline-formula>
-      </p>
-    </list-item>
-    <list-item>
-      <p>
-        <inline-formula><alternatives>
-        <tex-math><![CDATA[\alpha \wedge \omega]]></tex-math>
-        <mml:math display="inline" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mrow><mml:mi>α</mml:mi><mml:mo>∧</mml:mo><mml:mi>ω</mml:mi></mml:mrow></mml:math></alternatives></inline-formula>
-      </p>
-    </list-item>
-    <list-item>
-      <p>
-        <inline-formula><alternatives>
-        <tex-math><![CDATA[223]]></tex-math>
-        <mml:math display="inline" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mn>223</mml:mn></mml:math></alternatives></inline-formula>
-      </p>
-    </list-item>
-    <list-item>
-      <p>
-        <inline-formula><alternatives>
-        <tex-math><![CDATA[p]]></tex-math>
-        <mml:math display="inline" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mi>p</mml:mi></mml:math></alternatives></inline-formula>-Tree
-      </p>
-    </list-item>
-    <list-item>
-      <p>
-        Here’s some display math: <disp-formula><alternatives>
-        <tex-math><![CDATA[\frac{d}{dx}f(x)=\lim_{h\to 0}\frac{f(x+h)-f(x)}{h}]]></tex-math>
-        <mml:math display="block" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mrow><mml:mfrac><mml:mi>d</mml:mi><mml:mrow><mml:mi>d</mml:mi><mml:mi>x</mml:mi></mml:mrow></mml:mfrac><mml:mi>f</mml:mi><mml:mo stretchy="false" form="prefix">(</mml:mo><mml:mi>x</mml:mi><mml:mo stretchy="false" form="postfix">)</mml:mo><mml:mo>=</mml:mo><mml:munder><mml:mo>lim</mml:mo><mml:mrow><mml:mi>h</mml:mi><mml:mo>→</mml:mo><mml:mn>0</mml:mn></mml:mrow></mml:munder><mml:mfrac><mml:mrow><mml:mi>f</mml:mi><mml:mo stretchy="false" form="prefix">(</mml:mo><mml:mi>x</mml:mi><mml:mo>+</mml:mo><mml:mi>h</mml:mi><mml:mo stretchy="false" form="postfix">)</mml:mo><mml:mo>−</mml:mo><mml:mi>f</mml:mi><mml:mo stretchy="false" form="prefix">(</mml:mo><mml:mi>x</mml:mi><mml:mo stretchy="false" form="postfix">)</mml:mo></mml:mrow><mml:mi>h</mml:mi></mml:mfrac></mml:mrow></mml:math></alternatives></disp-formula>
-      </p>
-    </list-item>
-    <list-item>
-      <p>
-        Here’s one that has a line break in it: <inline-formula><alternatives>
-        <tex-math><![CDATA[\alpha + \omega \times x^2]]></tex-math>
-        <mml:math display="inline" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mrow><mml:mi>α</mml:mi><mml:mo>+</mml:mo><mml:mi>ω</mml:mi><mml:mo>×</mml:mo><mml:msup><mml:mi>x</mml:mi><mml:mn>2</mml:mn></mml:msup></mml:mrow></mml:math></alternatives></inline-formula>.
-      </p>
-    </list-item>
-  </list>
-  <p>
-    These shouldn’t be math:
-  </p>
-  <list list-type="bullet">
-    <list-item>
-      <p>
-        To get the famous equation, write <monospace>$e = mc^2$</monospace>.
-      </p>
-    </list-item>
-    <list-item>
-      <p>
-        $22,000 is a <italic>lot</italic> of money. So is $34,000. (It worked
-        if “lot” is emphasized.)
-      </p>
-    </list-item>
-    <list-item>
-      <p>
-        Shoes ($20) and socks ($5).
-      </p>
-    </list-item>
-    <list-item>
-      <p>
-        Escaped <monospace>$</monospace>: $73 <italic>this should be
-        emphasized</italic> 23$.
-      </p>
-    </list-item>
-  </list>
-  <p>
-    Here’s a LaTeX table:
-  </p>
-</sec>
-<sec id="special-characters">
-  <title>Special Characters</title>
-  <p>
-    Here is some unicode:
-  </p>
-  <list list-type="bullet">
-    <list-item>
-      <p>
-        I hat: Î
-      </p>
-    </list-item>
-    <list-item>
-      <p>
-        o umlaut: ö
-      </p>
-    </list-item>
-    <list-item>
-      <p>
-        section: §
-      </p>
-    </list-item>
-    <list-item>
-      <p>
-        set membership: ∈
-      </p>
-    </list-item>
-    <list-item>
-      <p>
-        copyright: ©
-      </p>
-    </list-item>
-  </list>
-  <p>
-    AT&amp;T has an ampersand in their name.
-  </p>
-  <p>
-    AT&amp;T is another way to write it.
-  </p>
-  <p>
-    This &amp; that.
-  </p>
-  <p>
-    4 &lt; 5.
-  </p>
-  <p>
-    6 &gt; 5.
-  </p>
-  <p>
-    Backslash: \
-  </p>
-  <p>
-    Backtick: `
-  </p>
-  <p>
-    Asterisk: *
-  </p>
-  <p>
-    Underscore: _
-  </p>
-  <p>
-    Left brace: {
-  </p>
-  <p>
-    Right brace: }
-  </p>
-  <p>
-    Left bracket: [
-  </p>
-  <p>
-    Right bracket: ]
-  </p>
-  <p>
-    Left paren: (
-  </p>
-  <p>
-    Right paren: )
-  </p>
-  <p>
-    Greater-than: &gt;
-  </p>
-  <p>
-    Hash: #
-  </p>
-  <p>
-    Period: .
-  </p>
-  <p>
-    Bang: !
-  </p>
-  <p>
-    Plus: +
-  </p>
-  <p>
-    Minus: -
-  </p>
-</sec>
-<sec id="links">
-  <title>Links</title>
-  <sec id="explicit">
-    <title>Explicit</title>
-    <p>
-      Just a <ext-link ext-link-type="uri" xlink:href="/url/">URL</ext-link>.
-    </p>
-    <p>
-      <ext-link ext-link-type="uri" xlink:href="/url/" xlink:title="title">URL
-      and title</ext-link>.
-    </p>
-    <p>
-      <ext-link ext-link-type="uri" xlink:href="/url/" xlink:title="title preceded by two spaces">URL
-      and title</ext-link>.
-    </p>
-    <p>
-      <ext-link ext-link-type="uri" xlink:href="/url/" xlink:title="title preceded by a tab">URL
-      and title</ext-link>.
-    </p>
-    <p>
-      <ext-link ext-link-type="uri" xlink:href="/url/" xlink:title="title with &quot;quotes&quot; in it">URL
-      and title</ext-link>
-    </p>
-    <p>
-      <ext-link ext-link-type="uri" xlink:href="/url/" xlink:title="title with single quotes">URL
-      and title</ext-link>
-    </p>
-    <p>
-      <ext-link ext-link-type="uri" xlink:href="/url/with_underscore">with_underscore</ext-link>
-    </p>
-    <p>
-      <ext-link ext-link-type="uri" xlink:href="mailto:nobody@nowhere.net">Email
-      link</ext-link>
-    </p>
-    <p>
-      <ext-link ext-link-type="uri" xlink:href="">Empty</ext-link>.
-    </p>
-  </sec>
-  <sec id="reference">
-    <title>Reference</title>
-    <p>
-      Foo <ext-link ext-link-type="uri" xlink:href="/url/">bar</ext-link>.
-    </p>
-    <p>
-      With <ext-link ext-link-type="uri" xlink:href="/url/">embedded
-      [brackets]</ext-link>.
-    </p>
-    <p>
-      <ext-link ext-link-type="uri" xlink:href="/url/">b</ext-link> by itself
-      should be a link.
-    </p>
-    <p>
-      Indented
-      <ext-link ext-link-type="uri" xlink:href="/url">once</ext-link>.
-    </p>
-    <p>
-      Indented
-      <ext-link ext-link-type="uri" xlink:href="/url">twice</ext-link>.
-    </p>
-    <p>
-      Indented
-      <ext-link ext-link-type="uri" xlink:href="/url">thrice</ext-link>.
-    </p>
-    <p>
-      This should [not][] be a link.
-    </p>
-    <preformat>[not]: /url</preformat>
-    <p>
-      Foo
-      <ext-link ext-link-type="uri" xlink:href="/url/" xlink:title="Title with &quot;quotes&quot; inside">bar</ext-link>.
-    </p>
-    <p>
-      Foo
-      <ext-link ext-link-type="uri" xlink:href="/url/" xlink:title="Title with &quot;quote&quot; inside">biz</ext-link>.
-    </p>
-  </sec>
-  <sec id="with-ampersands">
-    <title>With ampersands</title>
-    <p>
-      Here’s a
-      <ext-link ext-link-type="uri" xlink:href="http://example.com/?foo=1&amp;bar=2">link
-      with an ampersand in the URL</ext-link>.
-    </p>
-    <p>
-      Here’s a link with an amersand in the link text:
-      <ext-link ext-link-type="uri" xlink:href="http://att.com/" xlink:title="AT&amp;T">AT&amp;T</ext-link>.
-    </p>
-    <p>
-      Here’s an
-      <ext-link ext-link-type="uri" xlink:href="/script?foo=1&amp;bar=2">inline
-      link</ext-link>.
-    </p>
-    <p>
-      Here’s an
-      <ext-link ext-link-type="uri" xlink:href="/script?foo=1&amp;bar=2">inline
-      link in pointy braces</ext-link>.
-    </p>
-  </sec>
-  <sec id="autolinks">
-    <title>Autolinks</title>
-    <p>
-      With an ampersand:
-      <ext-link ext-link-type="uri" xlink:href="http://example.com/?foo=1&amp;bar=2">http://example.com/?foo=1&amp;bar=2</ext-link>
-    </p>
-    <list list-type="bullet">
-      <list-item>
-        <p>
-          In a list?
-        </p>
-      </list-item>
-      <list-item>
-        <p>
-          <ext-link ext-link-type="uri" xlink:href="http://example.com/">http://example.com/</ext-link>
-        </p>
-      </list-item>
-      <list-item>
-        <p>
-          It should.
-        </p>
-      </list-item>
-    </list>
-    <p>
-      An e-mail address: <email>nobody@nowhere.net</email>
-    </p>
-    <disp-quote>
-      <p>
-        Blockquoted:
-        <ext-link ext-link-type="uri" xlink:href="http://example.com/">http://example.com/</ext-link>
-      </p>
-    </disp-quote>
-    <p>
-      Auto-links should not occur here:
-      <monospace>&lt;http://example.com/&gt;</monospace>
-    </p>
-    <preformat>or here: &lt;http://example.com/&gt;</preformat>
-  </sec>
-</sec>
-<sec id="images">
-  <title>Images</title>
-  <p>
-    From “Voyage dans la Lune” by Georges Melies (1902):
-  </p>
-  <fig>
-    <caption>lalune</caption>
-    <graphic mimetype="image" mime-subtype="jpeg" xlink:href="lalune.jpg" xlink:title="Voyage dans la Lune" />
-  </fig>
-  <p>
-    Here is a movie
-    <inline-graphic mimetype="image" mime-subtype="jpeg" xlink:href="movie.jpg" />
-    icon.
-  </p>
-</sec>
-<sec id="footnotes">
-  <title>Footnotes</title>
-  <p>
-    Here is a footnote reference,<fn>
-      <p>
-        Here is the footnote. It can go anywhere after the footnote reference.
-        It need not be placed at the end of the document.
-      </p>
-    </fn> and another.<fn>
-      <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>
-      <preformat>  { &lt;code&gt; }</preformat>
-      <p>
-        If you want, you can indent every line, but you can also be lazy and
-        just indent the first line of each block.
-      </p>
-    </fn> This should <italic>not</italic> be a footnote reference, because it
-    contains a space.[^my note] Here is an inline note.<fn>
-      <p>
-        This is <italic>easier</italic> to type. Inline notes may contain
-        <ext-link ext-link-type="uri" xlink:href="http://google.com">links</ext-link>
-        and <monospace>]</monospace> verbatim characters, as well as
-        [bracketed text].
-      </p>
-    </fn>
-  </p>
-  <disp-quote>
-    <p>
-      Notes can go in quotes.<fn>
-        <p>
-          In quote.
-        </p>
-      </fn>
-    </p>
-  </disp-quote>
-  <list list-type="order">
-    <list-item>
-      <p>
-        And in list items.<fn>
-          <p>
-            In list.
-          </p>
-        </fn>
-      </p>
-    </list-item>
-  </list>
-  <p>
-    This paragraph should not be part of the note, as it is not indented.
-  </p>
-</sec>
-</body>
-<back>
-</back>
-</article>
diff --git a/test/writer.jats_archiving b/test/writer.jats_archiving
new file mode 100644
--- /dev/null
+++ b/test/writer.jats_archiving
@@ -0,0 +1,883 @@
+<?xml version="1.0" encoding="utf-8" ?>
+<!DOCTYPE article PUBLIC "-//NLM//DTD JATS (Z39.96) Journal Archiving and Interchange DTD v1.2 20190208//EN"
+                  "JATS-archivearticle1.dtd">
+<article xmlns:mml="http://www.w3.org/1998/Math/MathML" xmlns:xlink="http://www.w3.org/1999/xlink" dtd-version="1.2" article-type="other">
+<front>
+<journal-meta>
+<journal-id></journal-id>
+<journal-title-group>
+</journal-title-group>
+<issn></issn>
+<publisher>
+<publisher-name></publisher-name>
+</publisher>
+</journal-meta>
+<article-meta>
+<title-group>
+<article-title>Pandoc Test Suite</article-title>
+</title-group>
+<contrib-group>
+<contrib contrib-type="author">
+<string-name>John MacFarlane</string-name>
+</contrib>
+<contrib contrib-type="author">
+<string-name>Anonymous</string-name>
+</contrib>
+</contrib-group>
+<pub-date date-type="pub" publication-format="electronic" iso-8601-date="2006-07-17">
+<day>17</day>
+<month>7</month>
+<year>2006</year>
+</pub-date>
+<permissions>
+</permissions>
+</article-meta>
+</front>
+<body>
+<p>This is a set of tests for pandoc. Most of them are adapted from John
+Gruber’s markdown test suite.</p>
+<sec id="headers">
+  <title>Headers</title>
+  <sec id="level-2-with-an-embedded-link">
+    <title>Level 2 with an
+    <ext-link ext-link-type="uri" xlink:href="/url">embedded
+    link</ext-link></title>
+    <sec id="level-3-with-emphasis">
+      <title>Level 3 with <italic>emphasis</italic></title>
+      <sec id="level-4">
+        <title>Level 4</title>
+        <sec id="level-5">
+          <title>Level 5</title>
+        </sec>
+      </sec>
+    </sec>
+  </sec>
+</sec>
+<sec id="level-1">
+  <title>Level 1</title>
+  <sec id="level-2-with-emphasis">
+    <title>Level 2 with <italic>emphasis</italic></title>
+    <sec id="level-3">
+      <title>Level 3</title>
+      <p>with no blank line</p>
+    </sec>
+  </sec>
+  <sec id="level-2">
+    <title>Level 2</title>
+    <p>with no blank line</p>
+  </sec>
+</sec>
+<sec id="paragraphs">
+  <title>Paragraphs</title>
+  <p>Here’s a regular paragraph.</p>
+  <p>In Markdown 1.0.0 and earlier. Version 8. This line turns into a list item.
+  Because a hard-wrapped line in the middle of a paragraph looked like a list
+  item.</p>
+  <p>Here’s one with a bullet. * criminey.</p>
+  <p>There should be a hard line break
+  here.</p>
+</sec>
+<sec id="block-quotes">
+  <title>Block Quotes</title>
+  <p>E-mail style:</p>
+  <disp-quote>
+    <p>This is a block quote. It is pretty short.</p>
+  </disp-quote>
+  <disp-quote>
+    <p>Code in a block quote:</p>
+    <preformat>sub status {
+    print &quot;working&quot;;
+}</preformat>
+    <p>A list:</p>
+    <list list-type="order">
+      <list-item>
+        <p>item one</p>
+      </list-item>
+      <list-item>
+        <p>item two</p>
+      </list-item>
+    </list>
+    <p>Nested block quotes:</p>
+    <disp-quote>
+      <p>nested</p>
+    </disp-quote>
+    <disp-quote>
+      <p>nested</p>
+    </disp-quote>
+  </disp-quote>
+  <p>This should not be a block quote: 2 &gt; 1.</p>
+  <p>And a following paragraph.</p>
+</sec>
+<sec id="code-blocks">
+  <title>Code Blocks</title>
+  <p>Code:</p>
+  <preformat>---- (should be four hyphens)
+
+sub status {
+    print &quot;working&quot;;
+}
+
+this code block is indented by one tab</preformat>
+  <p>And:</p>
+  <preformat>    this code block is indented by two tabs
+
+These should not be escaped:  \$ \\ \&gt; \[ \{</preformat>
+</sec>
+<sec id="lists">
+  <title>Lists</title>
+  <sec id="unordered">
+    <title>Unordered</title>
+    <p>Asterisks tight:</p>
+    <list list-type="bullet">
+      <list-item>
+        <p>asterisk 1</p>
+      </list-item>
+      <list-item>
+        <p>asterisk 2</p>
+      </list-item>
+      <list-item>
+        <p>asterisk 3</p>
+      </list-item>
+    </list>
+    <p>Asterisks loose:</p>
+    <list list-type="bullet">
+      <list-item>
+        <p>asterisk 1</p>
+      </list-item>
+      <list-item>
+        <p>asterisk 2</p>
+      </list-item>
+      <list-item>
+        <p>asterisk 3</p>
+      </list-item>
+    </list>
+    <p>Pluses tight:</p>
+    <list list-type="bullet">
+      <list-item>
+        <p>Plus 1</p>
+      </list-item>
+      <list-item>
+        <p>Plus 2</p>
+      </list-item>
+      <list-item>
+        <p>Plus 3</p>
+      </list-item>
+    </list>
+    <p>Pluses loose:</p>
+    <list list-type="bullet">
+      <list-item>
+        <p>Plus 1</p>
+      </list-item>
+      <list-item>
+        <p>Plus 2</p>
+      </list-item>
+      <list-item>
+        <p>Plus 3</p>
+      </list-item>
+    </list>
+    <p>Minuses tight:</p>
+    <list list-type="bullet">
+      <list-item>
+        <p>Minus 1</p>
+      </list-item>
+      <list-item>
+        <p>Minus 2</p>
+      </list-item>
+      <list-item>
+        <p>Minus 3</p>
+      </list-item>
+    </list>
+    <p>Minuses loose:</p>
+    <list list-type="bullet">
+      <list-item>
+        <p>Minus 1</p>
+      </list-item>
+      <list-item>
+        <p>Minus 2</p>
+      </list-item>
+      <list-item>
+        <p>Minus 3</p>
+      </list-item>
+    </list>
+  </sec>
+  <sec id="ordered">
+    <title>Ordered</title>
+    <p>Tight:</p>
+    <list list-type="order">
+      <list-item>
+        <p>First</p>
+      </list-item>
+      <list-item>
+        <p>Second</p>
+      </list-item>
+      <list-item>
+        <p>Third</p>
+      </list-item>
+    </list>
+    <p>and:</p>
+    <list list-type="order">
+      <list-item>
+        <p>One</p>
+      </list-item>
+      <list-item>
+        <p>Two</p>
+      </list-item>
+      <list-item>
+        <p>Three</p>
+      </list-item>
+    </list>
+    <p>Loose using tabs:</p>
+    <list list-type="order">
+      <list-item>
+        <p>First</p>
+      </list-item>
+      <list-item>
+        <p>Second</p>
+      </list-item>
+      <list-item>
+        <p>Third</p>
+      </list-item>
+    </list>
+    <p>and using spaces:</p>
+    <list list-type="order">
+      <list-item>
+        <p>One</p>
+      </list-item>
+      <list-item>
+        <p>Two</p>
+      </list-item>
+      <list-item>
+        <p>Three</p>
+      </list-item>
+    </list>
+    <p>Multiple paragraphs:</p>
+    <list list-type="order">
+      <list-item>
+        <p>Item 1, graf one.</p>
+        <p>Item 1. graf two. The quick brown fox jumped over the lazy dog’s
+        back.</p>
+      </list-item>
+      <list-item>
+        <p>Item 2.</p>
+      </list-item>
+      <list-item>
+        <p>Item 3.</p>
+      </list-item>
+    </list>
+  </sec>
+  <sec id="nested">
+    <title>Nested</title>
+    <list list-type="bullet">
+      <list-item>
+        <p>Tab</p>
+        <list list-type="bullet">
+          <list-item>
+            <p>Tab</p>
+            <list list-type="bullet">
+              <list-item>
+                <p>Tab</p>
+              </list-item>
+            </list>
+          </list-item>
+        </list>
+      </list-item>
+    </list>
+    <p>Here’s another:</p>
+    <list list-type="order">
+      <list-item>
+        <p>First</p>
+      </list-item>
+      <list-item>
+        <p>Second:</p>
+        <list list-type="bullet">
+          <list-item>
+            <p>Fee</p>
+          </list-item>
+          <list-item>
+            <p>Fie</p>
+          </list-item>
+          <list-item>
+            <p>Foe</p>
+          </list-item>
+        </list>
+      </list-item>
+      <list-item>
+        <p>Third</p>
+      </list-item>
+    </list>
+    <p>Same thing but with paragraphs:</p>
+    <list list-type="order">
+      <list-item>
+        <p>First</p>
+      </list-item>
+      <list-item>
+        <p>Second:</p>
+        <list list-type="bullet">
+          <list-item>
+            <p>Fee</p>
+          </list-item>
+          <list-item>
+            <p>Fie</p>
+          </list-item>
+          <list-item>
+            <p>Foe</p>
+          </list-item>
+        </list>
+      </list-item>
+      <list-item>
+        <p>Third</p>
+      </list-item>
+    </list>
+  </sec>
+  <sec id="tabs-and-spaces">
+    <title>Tabs and spaces</title>
+    <list list-type="bullet">
+      <list-item>
+        <p>this is a list item indented with tabs</p>
+      </list-item>
+      <list-item>
+        <p>this is a list item indented with spaces</p>
+        <list list-type="bullet">
+          <list-item>
+            <p>this is an example list item indented with tabs</p>
+          </list-item>
+          <list-item>
+            <p>this is an example list item indented with spaces</p>
+          </list-item>
+        </list>
+      </list-item>
+    </list>
+  </sec>
+  <sec id="fancy-list-markers">
+    <title>Fancy list markers</title>
+    <list list-type="order">
+      <list-item>
+        <label>(2)</label>
+        <p>begins with 2</p>
+      </list-item>
+      <list-item>
+        <label>(3)</label>
+        <p>and now 3</p>
+        <p>with a continuation</p>
+        <list list-type="roman-lower">
+          <list-item>
+            <label>iv.</label>
+            <p>sublist with roman numerals, starting with 4</p>
+          </list-item>
+          <list-item>
+            <label>v.</label>
+            <p>more items</p>
+            <list list-type="alpha-upper">
+              <list-item>
+                <label>(A)</label>
+                <p>a subsublist</p>
+              </list-item>
+              <list-item>
+                <label>(B)</label>
+                <p>a subsublist</p>
+              </list-item>
+            </list>
+          </list-item>
+        </list>
+      </list-item>
+    </list>
+    <p>Nesting:</p>
+    <list list-type="alpha-upper">
+      <list-item>
+        <p>Upper Alpha</p>
+        <list list-type="roman-upper">
+          <list-item>
+            <p>Upper Roman.</p>
+            <list list-type="order">
+              <list-item>
+                <label>(6)</label>
+                <p>Decimal start with 6</p>
+                <list list-type="alpha-lower">
+                  <list-item>
+                    <label>c)</label>
+                    <p>Lower alpha with paren</p>
+                  </list-item>
+                </list>
+              </list-item>
+            </list>
+          </list-item>
+        </list>
+      </list-item>
+    </list>
+    <p>Autonumbering:</p>
+    <list list-type="order">
+      <list-item>
+        <p>Autonumber.</p>
+      </list-item>
+      <list-item>
+        <p>More.</p>
+        <list list-type="order">
+          <list-item>
+            <p>Nested.</p>
+          </list-item>
+        </list>
+      </list-item>
+    </list>
+    <p>Should not be a list item:</p>
+    <p>M.A. 2007</p>
+    <p>B. Williams</p>
+  </sec>
+</sec>
+<sec id="definition-lists">
+  <title>Definition Lists</title>
+  <p>Tight using spaces:</p>
+  <def-list>
+    <def-item>
+      <term>apple</term>
+      <def>
+        <p>red fruit</p>
+      </def>
+    </def-item>
+    <def-item>
+      <term>orange</term>
+      <def>
+        <p>orange fruit</p>
+      </def>
+    </def-item>
+    <def-item>
+      <term>banana</term>
+      <def>
+        <p>yellow fruit</p>
+      </def>
+    </def-item>
+  </def-list>
+  <p>Tight using tabs:</p>
+  <def-list>
+    <def-item>
+      <term>apple</term>
+      <def>
+        <p>red fruit</p>
+      </def>
+    </def-item>
+    <def-item>
+      <term>orange</term>
+      <def>
+        <p>orange fruit</p>
+      </def>
+    </def-item>
+    <def-item>
+      <term>banana</term>
+      <def>
+        <p>yellow fruit</p>
+      </def>
+    </def-item>
+  </def-list>
+  <p>Loose:</p>
+  <def-list>
+    <def-item>
+      <term>apple</term>
+      <def>
+        <p>red fruit</p>
+      </def>
+    </def-item>
+    <def-item>
+      <term>orange</term>
+      <def>
+        <p>orange fruit</p>
+      </def>
+    </def-item>
+    <def-item>
+      <term>banana</term>
+      <def>
+        <p>yellow fruit</p>
+      </def>
+    </def-item>
+  </def-list>
+  <p>Multiple blocks with italics:</p>
+  <def-list>
+    <def-item>
+      <term><italic>apple</italic></term>
+      <def>
+        <p>red fruit</p>
+        <p>contains seeds, crisp, pleasant to taste</p>
+      </def>
+    </def-item>
+    <def-item>
+      <term><italic>orange</italic></term>
+      <def>
+        <p>orange fruit</p>
+        <p specific-use="wrapper">
+          <preformat>{ orange code block }</preformat>
+        </p>
+        <p specific-use="wrapper">
+          <disp-quote>
+            <p>orange block quote</p>
+          </disp-quote>
+        </p>
+      </def>
+    </def-item>
+  </def-list>
+  <p>Multiple definitions, tight:</p>
+  <def-list>
+    <def-item>
+      <term>apple</term>
+      <def>
+        <p>red fruit</p>
+        <p>computer</p>
+      </def>
+    </def-item>
+    <def-item>
+      <term>orange</term>
+      <def>
+        <p>orange fruit</p>
+        <p>bank</p>
+      </def>
+    </def-item>
+  </def-list>
+  <p>Multiple definitions, loose:</p>
+  <def-list>
+    <def-item>
+      <term>apple</term>
+      <def>
+        <p>red fruit</p>
+        <p>computer</p>
+      </def>
+    </def-item>
+    <def-item>
+      <term>orange</term>
+      <def>
+        <p>orange fruit</p>
+        <p>bank</p>
+      </def>
+    </def-item>
+  </def-list>
+  <p>Blank line after term, indented marker, alternate markers:</p>
+  <def-list>
+    <def-item>
+      <term>apple</term>
+      <def>
+        <p>red fruit</p>
+        <p>computer</p>
+      </def>
+    </def-item>
+    <def-item>
+      <term>orange</term>
+      <def>
+        <p>orange fruit</p>
+        <p specific-use="wrapper">
+          <list list-type="order">
+            <list-item>
+              <p>sublist</p>
+            </list-item>
+            <list-item>
+              <p>sublist</p>
+            </list-item>
+          </list>
+        </p>
+      </def>
+    </def-item>
+  </def-list>
+</sec>
+<sec id="html-blocks">
+  <title>HTML Blocks</title>
+  <p>Simple block on one line:</p>
+  <p>foo</p>
+  <p>And nested without indentation:</p>
+  <p>foo</p>
+  <p>bar</p>
+  <p>Interpreted markdown in a table:</p>
+  <p>This is <italic>emphasized</italic></p>
+  <p>And this is <bold>strong</bold></p>
+  <p>Here’s a simple block:</p>
+  <p>foo</p>
+  <p>This should be a code block, though:</p>
+  <preformat>&lt;div&gt;
+    foo
+&lt;/div&gt;</preformat>
+  <p>As should this:</p>
+  <preformat>&lt;div&gt;foo&lt;/div&gt;</preformat>
+  <p>Now, nested:</p>
+  <p>foo</p>
+  <p>This should just be an HTML comment:</p>
+  <p>Multiline:</p>
+  <p>Code block:</p>
+  <preformat>&lt;!-- Comment --&gt;</preformat>
+  <p>Just plain comment, with trailing spaces on the line:</p>
+  <p>Code:</p>
+  <preformat>&lt;hr /&gt;</preformat>
+  <p>Hr’s:</p>
+</sec>
+<sec id="inline-markup">
+  <title>Inline Markup</title>
+  <p>This is <italic>emphasized</italic>, and so <italic>is this</italic>.</p>
+  <p>This is <bold>strong</bold>, and so <bold>is this</bold>.</p>
+  <p>An <italic><ext-link ext-link-type="uri" xlink:href="/url">emphasized
+  link</ext-link></italic>.</p>
+  <p><bold><italic>This is strong and em.</italic></bold></p>
+  <p>So is <bold><italic>this</italic></bold> word.</p>
+  <p><bold><italic>This is strong and em.</italic></bold></p>
+  <p>So is <bold><italic>this</italic></bold> word.</p>
+  <p>This is code: <monospace>&gt;</monospace>, <monospace>$</monospace>,
+  <monospace>\</monospace>, <monospace>\$</monospace>,
+  <monospace>&lt;html&gt;</monospace>.</p>
+  <p><strike>This is <italic>strikeout</italic>.</strike></p>
+  <p>Superscripts: a<sup>bc</sup>d a<sup><italic>hello</italic></sup>
+  a<sup>hello there</sup>.</p>
+  <p>Subscripts: H<sub>2</sub>O, H<sub>23</sub>O, H<sub>many of them</sub>O.</p>
+  <p>These should not be superscripts or subscripts, because of the unescaped
+  spaces: a^b c^d, a~b c~d.</p>
+</sec>
+<sec id="smart-quotes-ellipses-dashes">
+  <title>Smart quotes, ellipses, dashes</title>
+  <p>“Hello,” said the spider. “‘Shelob’ is my name.”</p>
+  <p>‘A’, ‘B’, and ‘C’ are letters.</p>
+  <p>‘Oak,’ ‘elm,’ and ‘beech’ are names of trees. So is ‘pine.’</p>
+  <p>‘He said, “I want to go.”’ Were you alive in the 70’s?</p>
+  <p>Here is some quoted ‘<monospace>code</monospace>’ and a
+  “<ext-link ext-link-type="uri" xlink:href="http://example.com/?foo=1&amp;bar=2">quoted
+  link</ext-link>”.</p>
+  <p>Some dashes: one—two — three—four — five.</p>
+  <p>Dashes between numbers: 5–7, 255–66, 1987–1999.</p>
+  <p>Ellipses…and…and….</p>
+</sec>
+<sec id="latex">
+  <title>LaTeX</title>
+  <list list-type="bullet">
+    <list-item>
+      <p></p>
+    </list-item>
+    <list-item>
+      <p><inline-formula><alternatives>
+      <tex-math><![CDATA[2+2=4]]></tex-math>
+      <mml:math display="inline" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mrow><mml:mn>2</mml:mn><mml:mo>+</mml:mo><mml:mn>2</mml:mn><mml:mo>=</mml:mo><mml:mn>4</mml:mn></mml:mrow></mml:math></alternatives></inline-formula></p>
+    </list-item>
+    <list-item>
+      <p><inline-formula><alternatives>
+      <tex-math><![CDATA[x \in y]]></tex-math>
+      <mml:math display="inline" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mrow><mml:mi>x</mml:mi><mml:mo>∈</mml:mo><mml:mi>y</mml:mi></mml:mrow></mml:math></alternatives></inline-formula></p>
+    </list-item>
+    <list-item>
+      <p><inline-formula><alternatives>
+      <tex-math><![CDATA[\alpha \wedge \omega]]></tex-math>
+      <mml:math display="inline" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mrow><mml:mi>α</mml:mi><mml:mo>∧</mml:mo><mml:mi>ω</mml:mi></mml:mrow></mml:math></alternatives></inline-formula></p>
+    </list-item>
+    <list-item>
+      <p><inline-formula><alternatives>
+      <tex-math><![CDATA[223]]></tex-math>
+      <mml:math display="inline" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mn>223</mml:mn></mml:math></alternatives></inline-formula></p>
+    </list-item>
+    <list-item>
+      <p><inline-formula><alternatives>
+      <tex-math><![CDATA[p]]></tex-math>
+      <mml:math display="inline" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mi>p</mml:mi></mml:math></alternatives></inline-formula>-Tree</p>
+    </list-item>
+    <list-item>
+      <p>Here’s some display math: <disp-formula><alternatives>
+      <tex-math><![CDATA[\frac{d}{dx}f(x)=\lim_{h\to 0}\frac{f(x+h)-f(x)}{h}]]></tex-math>
+      <mml:math display="block" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mrow><mml:mfrac><mml:mi>d</mml:mi><mml:mrow><mml:mi>d</mml:mi><mml:mi>x</mml:mi></mml:mrow></mml:mfrac><mml:mi>f</mml:mi><mml:mo stretchy="false" form="prefix">(</mml:mo><mml:mi>x</mml:mi><mml:mo stretchy="false" form="postfix">)</mml:mo><mml:mo>=</mml:mo><mml:munder><mml:mi mathvariant="normal">lim</mml:mi><mml:mrow><mml:mi>h</mml:mi><mml:mo>→</mml:mo><mml:mn>0</mml:mn></mml:mrow></mml:munder><mml:mfrac><mml:mrow><mml:mi>f</mml:mi><mml:mo stretchy="false" form="prefix">(</mml:mo><mml:mi>x</mml:mi><mml:mo>+</mml:mo><mml:mi>h</mml:mi><mml:mo stretchy="false" form="postfix">)</mml:mo><mml:mo>−</mml:mo><mml:mi>f</mml:mi><mml:mo stretchy="false" form="prefix">(</mml:mo><mml:mi>x</mml:mi><mml:mo stretchy="false" form="postfix">)</mml:mo></mml:mrow><mml:mi>h</mml:mi></mml:mfrac></mml:mrow></mml:math></alternatives></disp-formula></p>
+    </list-item>
+    <list-item>
+      <p>Here’s one that has a line break in it: <inline-formula><alternatives>
+      <tex-math><![CDATA[\alpha + \omega \times x^2]]></tex-math>
+      <mml:math display="inline" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mrow><mml:mi>α</mml:mi><mml:mo>+</mml:mo><mml:mi>ω</mml:mi><mml:mo>×</mml:mo><mml:msup><mml:mi>x</mml:mi><mml:mn>2</mml:mn></mml:msup></mml:mrow></mml:math></alternatives></inline-formula>.</p>
+    </list-item>
+  </list>
+  <p>These shouldn’t be math:</p>
+  <list list-type="bullet">
+    <list-item>
+      <p>To get the famous equation, write
+      <monospace>$e = mc^2$</monospace>.</p>
+    </list-item>
+    <list-item>
+      <p>$22,000 is a <italic>lot</italic> of money. So is $34,000. (It worked
+      if “lot” is emphasized.)</p>
+    </list-item>
+    <list-item>
+      <p>Shoes ($20) and socks ($5).</p>
+    </list-item>
+    <list-item>
+      <p>Escaped <monospace>$</monospace>: $73 <italic>this should be
+      emphasized</italic> 23$.</p>
+    </list-item>
+  </list>
+  <p>Here’s a LaTeX table:</p>
+</sec>
+<sec id="special-characters">
+  <title>Special Characters</title>
+  <p>Here is some unicode:</p>
+  <list list-type="bullet">
+    <list-item>
+      <p>I hat: Î</p>
+    </list-item>
+    <list-item>
+      <p>o umlaut: ö</p>
+    </list-item>
+    <list-item>
+      <p>section: §</p>
+    </list-item>
+    <list-item>
+      <p>set membership: ∈</p>
+    </list-item>
+    <list-item>
+      <p>copyright: ©</p>
+    </list-item>
+  </list>
+  <p>AT&amp;T has an ampersand in their name.</p>
+  <p>AT&amp;T is another way to write it.</p>
+  <p>This &amp; that.</p>
+  <p>4 &lt; 5.</p>
+  <p>6 &gt; 5.</p>
+  <p>Backslash: \</p>
+  <p>Backtick: `</p>
+  <p>Asterisk: *</p>
+  <p>Underscore: _</p>
+  <p>Left brace: {</p>
+  <p>Right brace: }</p>
+  <p>Left bracket: [</p>
+  <p>Right bracket: ]</p>
+  <p>Left paren: (</p>
+  <p>Right paren: )</p>
+  <p>Greater-than: &gt;</p>
+  <p>Hash: #</p>
+  <p>Period: .</p>
+  <p>Bang: !</p>
+  <p>Plus: +</p>
+  <p>Minus: -</p>
+</sec>
+<sec id="links">
+  <title>Links</title>
+  <sec id="explicit">
+    <title>Explicit</title>
+    <p>Just a
+    <ext-link ext-link-type="uri" xlink:href="/url/">URL</ext-link>.</p>
+    <p><ext-link ext-link-type="uri" xlink:href="/url/" xlink:title="title">URL
+    and title</ext-link>.</p>
+    <p><ext-link ext-link-type="uri" xlink:href="/url/" xlink:title="title preceded by two spaces">URL
+    and title</ext-link>.</p>
+    <p><ext-link ext-link-type="uri" xlink:href="/url/" xlink:title="title preceded by a tab">URL
+    and title</ext-link>.</p>
+    <p><ext-link ext-link-type="uri" xlink:href="/url/" xlink:title="title with &quot;quotes&quot; in it">URL
+    and title</ext-link></p>
+    <p><ext-link ext-link-type="uri" xlink:href="/url/" xlink:title="title with single quotes">URL
+    and title</ext-link></p>
+    <p><ext-link ext-link-type="uri" xlink:href="/url/with_underscore">with_underscore</ext-link></p>
+    <p><ext-link ext-link-type="uri" xlink:href="mailto:nobody@nowhere.net">Email
+    link</ext-link></p>
+    <p><ext-link ext-link-type="uri" xlink:href="">Empty</ext-link>.</p>
+  </sec>
+  <sec id="reference">
+    <title>Reference</title>
+    <p>Foo <ext-link ext-link-type="uri" xlink:href="/url/">bar</ext-link>.</p>
+    <p>With <ext-link ext-link-type="uri" xlink:href="/url/">embedded
+    [brackets]</ext-link>.</p>
+    <p><ext-link ext-link-type="uri" xlink:href="/url/">b</ext-link> by itself
+    should be a link.</p>
+    <p>Indented
+    <ext-link ext-link-type="uri" xlink:href="/url">once</ext-link>.</p>
+    <p>Indented
+    <ext-link ext-link-type="uri" xlink:href="/url">twice</ext-link>.</p>
+    <p>Indented
+    <ext-link ext-link-type="uri" xlink:href="/url">thrice</ext-link>.</p>
+    <p>This should [not][] be a link.</p>
+    <preformat>[not]: /url</preformat>
+    <p>Foo
+    <ext-link ext-link-type="uri" xlink:href="/url/" xlink:title="Title with &quot;quotes&quot; inside">bar</ext-link>.</p>
+    <p>Foo
+    <ext-link ext-link-type="uri" xlink:href="/url/" xlink:title="Title with &quot;quote&quot; inside">biz</ext-link>.</p>
+  </sec>
+  <sec id="with-ampersands">
+    <title>With ampersands</title>
+    <p>Here’s a
+    <ext-link ext-link-type="uri" xlink:href="http://example.com/?foo=1&amp;bar=2">link
+    with an ampersand in the URL</ext-link>.</p>
+    <p>Here’s a link with an amersand in the link text:
+    <ext-link ext-link-type="uri" xlink:href="http://att.com/" xlink:title="AT&amp;T">AT&amp;T</ext-link>.</p>
+    <p>Here’s an
+    <ext-link ext-link-type="uri" xlink:href="/script?foo=1&amp;bar=2">inline
+    link</ext-link>.</p>
+    <p>Here’s an
+    <ext-link ext-link-type="uri" xlink:href="/script?foo=1&amp;bar=2">inline
+    link in pointy braces</ext-link>.</p>
+  </sec>
+  <sec id="autolinks">
+    <title>Autolinks</title>
+    <p>With an ampersand:
+    <ext-link ext-link-type="uri" xlink:href="http://example.com/?foo=1&amp;bar=2">http://example.com/?foo=1&amp;bar=2</ext-link></p>
+    <list list-type="bullet">
+      <list-item>
+        <p>In a list?</p>
+      </list-item>
+      <list-item>
+        <p><ext-link ext-link-type="uri" xlink:href="http://example.com/">http://example.com/</ext-link></p>
+      </list-item>
+      <list-item>
+        <p>It should.</p>
+      </list-item>
+    </list>
+    <p>An e-mail address: <email>nobody@nowhere.net</email></p>
+    <disp-quote>
+      <p>Blockquoted:
+      <ext-link ext-link-type="uri" xlink:href="http://example.com/">http://example.com/</ext-link></p>
+    </disp-quote>
+    <p>Auto-links should not occur here:
+    <monospace>&lt;http://example.com/&gt;</monospace></p>
+    <preformat>or here: &lt;http://example.com/&gt;</preformat>
+  </sec>
+</sec>
+<sec id="images">
+  <title>Images</title>
+  <p>From “Voyage dans la Lune” by Georges Melies (1902):</p>
+  <fig>
+    <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
+  <inline-graphic mimetype="image" mime-subtype="jpeg" xlink:href="movie.jpg">
+    <alt-text>movie</alt-text>
+  </inline-graphic> icon.</p>
+</sec>
+<sec id="footnotes">
+  <title>Footnotes</title>
+  <p>Here is a footnote reference,<xref ref-type="fn" rid="fn1">1</xref> and
+  another.<xref ref-type="fn" rid="fn2">2</xref> This should
+  <italic>not</italic> be a footnote reference, because it contains a space.[^my
+  note] Here is an inline note.<xref ref-type="fn" rid="fn3">3</xref></p>
+  <disp-quote>
+    <p>Notes can go in quotes.<xref ref-type="fn" rid="fn4">4</xref></p>
+  </disp-quote>
+  <list list-type="order">
+    <list-item>
+      <p>And in list items.<xref ref-type="fn" rid="fn5">5</xref></p>
+    </list-item>
+  </list>
+  <p>This paragraph should not be part of the note, as it is not indented.</p>
+</sec>
+</body>
+<back>
+<fn-group>
+  <fn id="fn1">
+    <label>1</label><p>Here is the footnote. It can go anywhere after the
+    footnote reference. It need not be placed at the end of the document.</p>
+  </fn>
+  <fn id="fn2">
+    <label>2</label><p>Here’s the long note. This one contains multiple
+    blocks.</p>
+    <p>Subsequent blocks are indented to show that they belong to the footnote
+    (as with list items).</p>
+    <p specific-use="wrapper">
+      <preformat>  { &lt;code&gt; }</preformat>
+    </p>
+    <p>If you want, you can indent every line, but you can also be lazy and just
+    indent the first line of each block.</p>
+  </fn>
+  <fn id="fn3">
+    <label>3</label><p>This is <italic>easier</italic> to type. Inline notes may
+    contain
+    <ext-link ext-link-type="uri" xlink:href="http://google.com">links</ext-link>
+    and <monospace>]</monospace> verbatim characters, as well as [bracketed
+    text].</p>
+  </fn>
+  <fn id="fn4">
+    <label>4</label><p>In quote.</p>
+  </fn>
+  <fn id="fn5">
+    <label>5</label><p>In list.</p>
+  </fn>
+</fn-group>
+</back>
+</article>
diff --git a/test/writer.jats_articleauthoring b/test/writer.jats_articleauthoring
new file mode 100644
--- /dev/null
+++ b/test/writer.jats_articleauthoring
@@ -0,0 +1,857 @@
+<?xml version="1.0" encoding="utf-8" ?>
+<!DOCTYPE article PUBLIC "-//NLM//DTD JATS (Z39.96) Article Authoring DTD v1.2 20190208//EN"
+                  "JATS-articleauthoring1.dtd">
+<article xmlns:mml="http://www.w3.org/1998/Math/MathML" xmlns:xlink="http://www.w3.org/1999/xlink" dtd-version="1.2" article-type="other">
+<front>
+<article-meta>
+<title-group>
+<article-title>Pandoc Test Suite</article-title>
+</title-group>
+<contrib-group>
+<contrib contrib-type="author">
+<string-name>John MacFarlane</string-name>
+</contrib>
+<contrib contrib-type="author">
+<string-name>Anonymous</string-name>
+</contrib>
+</contrib-group>
+<permissions>
+</permissions>
+<abstract>
+
+</abstract>
+</article-meta>
+</front>
+<body>
+<p>This is a set of tests for pandoc. Most of them are adapted from John
+Gruber’s markdown test suite.</p>
+<sec id="headers">
+  <title>Headers</title>
+  <sec id="level-2-with-an-embedded-link">
+    <title>Level 2 with an
+    <ext-link ext-link-type="uri" xlink:href="/url">embedded
+    link</ext-link></title>
+    <sec id="level-3-with-emphasis">
+      <title>Level 3 with <italic>emphasis</italic></title>
+      <sec id="level-4">
+        <title>Level 4</title>
+        <sec id="level-5">
+          <title>Level 5</title>
+        </sec>
+      </sec>
+    </sec>
+  </sec>
+</sec>
+<sec id="level-1">
+  <title>Level 1</title>
+  <sec id="level-2-with-emphasis">
+    <title>Level 2 with <italic>emphasis</italic></title>
+    <sec id="level-3">
+      <title>Level 3</title>
+      <p>with no blank line</p>
+    </sec>
+  </sec>
+  <sec id="level-2">
+    <title>Level 2</title>
+    <p>with no blank line</p>
+  </sec>
+</sec>
+<sec id="paragraphs">
+  <title>Paragraphs</title>
+  <p>Here’s a regular paragraph.</p>
+  <p>In Markdown 1.0.0 and earlier. Version 8. This line turns into a list item.
+  Because a hard-wrapped line in the middle of a paragraph looked like a list
+  item.</p>
+  <p>Here’s one with a bullet. * criminey.</p>
+  <p>There should be a hard line break
+  here.</p>
+</sec>
+<sec id="block-quotes">
+  <title>Block Quotes</title>
+  <p>E-mail style:</p>
+  <disp-quote>
+    <p>This is a block quote. It is pretty short.</p>
+  </disp-quote>
+  <disp-quote>
+    <p>Code in a block quote:</p>
+    <p specific-use="wrapper">
+      <preformat>sub status {
+    print &quot;working&quot;;
+}</preformat>
+    </p>
+    <p>A list:</p>
+    <p specific-use="wrapper">
+      <list list-type="order">
+        <list-item>
+          <p>item one</p>
+        </list-item>
+        <list-item>
+          <p>item two</p>
+        </list-item>
+      </list>
+    </p>
+    <p>Nested block quotes:</p>
+    <p specific-use="wrapper">
+      <disp-quote>
+        <p>nested</p>
+      </disp-quote>
+    </p>
+    <p specific-use="wrapper">
+      <disp-quote>
+        <p>nested</p>
+      </disp-quote>
+    </p>
+  </disp-quote>
+  <p>This should not be a block quote: 2 &gt; 1.</p>
+  <p>And a following paragraph.</p>
+</sec>
+<sec id="code-blocks">
+  <title>Code Blocks</title>
+  <p>Code:</p>
+  <preformat>---- (should be four hyphens)
+
+sub status {
+    print &quot;working&quot;;
+}
+
+this code block is indented by one tab</preformat>
+  <p>And:</p>
+  <preformat>    this code block is indented by two tabs
+
+These should not be escaped:  \$ \\ \&gt; \[ \{</preformat>
+</sec>
+<sec id="lists">
+  <title>Lists</title>
+  <sec id="unordered">
+    <title>Unordered</title>
+    <p>Asterisks tight:</p>
+    <list list-type="bullet">
+      <list-item>
+        <p>asterisk 1</p>
+      </list-item>
+      <list-item>
+        <p>asterisk 2</p>
+      </list-item>
+      <list-item>
+        <p>asterisk 3</p>
+      </list-item>
+    </list>
+    <p>Asterisks loose:</p>
+    <list list-type="bullet">
+      <list-item>
+        <p>asterisk 1</p>
+      </list-item>
+      <list-item>
+        <p>asterisk 2</p>
+      </list-item>
+      <list-item>
+        <p>asterisk 3</p>
+      </list-item>
+    </list>
+    <p>Pluses tight:</p>
+    <list list-type="bullet">
+      <list-item>
+        <p>Plus 1</p>
+      </list-item>
+      <list-item>
+        <p>Plus 2</p>
+      </list-item>
+      <list-item>
+        <p>Plus 3</p>
+      </list-item>
+    </list>
+    <p>Pluses loose:</p>
+    <list list-type="bullet">
+      <list-item>
+        <p>Plus 1</p>
+      </list-item>
+      <list-item>
+        <p>Plus 2</p>
+      </list-item>
+      <list-item>
+        <p>Plus 3</p>
+      </list-item>
+    </list>
+    <p>Minuses tight:</p>
+    <list list-type="bullet">
+      <list-item>
+        <p>Minus 1</p>
+      </list-item>
+      <list-item>
+        <p>Minus 2</p>
+      </list-item>
+      <list-item>
+        <p>Minus 3</p>
+      </list-item>
+    </list>
+    <p>Minuses loose:</p>
+    <list list-type="bullet">
+      <list-item>
+        <p>Minus 1</p>
+      </list-item>
+      <list-item>
+        <p>Minus 2</p>
+      </list-item>
+      <list-item>
+        <p>Minus 3</p>
+      </list-item>
+    </list>
+  </sec>
+  <sec id="ordered">
+    <title>Ordered</title>
+    <p>Tight:</p>
+    <list list-type="order">
+      <list-item>
+        <p>First</p>
+      </list-item>
+      <list-item>
+        <p>Second</p>
+      </list-item>
+      <list-item>
+        <p>Third</p>
+      </list-item>
+    </list>
+    <p>and:</p>
+    <list list-type="order">
+      <list-item>
+        <p>One</p>
+      </list-item>
+      <list-item>
+        <p>Two</p>
+      </list-item>
+      <list-item>
+        <p>Three</p>
+      </list-item>
+    </list>
+    <p>Loose using tabs:</p>
+    <list list-type="order">
+      <list-item>
+        <p>First</p>
+      </list-item>
+      <list-item>
+        <p>Second</p>
+      </list-item>
+      <list-item>
+        <p>Third</p>
+      </list-item>
+    </list>
+    <p>and using spaces:</p>
+    <list list-type="order">
+      <list-item>
+        <p>One</p>
+      </list-item>
+      <list-item>
+        <p>Two</p>
+      </list-item>
+      <list-item>
+        <p>Three</p>
+      </list-item>
+    </list>
+    <p>Multiple paragraphs:</p>
+    <list list-type="order">
+      <list-item>
+        <p>Item 1, graf one.</p>
+        <p>Item 1. graf two. The quick brown fox jumped over the lazy dog’s
+        back.</p>
+      </list-item>
+      <list-item>
+        <p>Item 2.</p>
+      </list-item>
+      <list-item>
+        <p>Item 3.</p>
+      </list-item>
+    </list>
+  </sec>
+  <sec id="nested">
+    <title>Nested</title>
+    <list list-type="bullet">
+      <list-item>
+        <p>Tab</p>
+        <list list-type="bullet">
+          <list-item>
+            <p>Tab</p>
+            <list list-type="bullet">
+              <list-item>
+                <p>Tab</p>
+              </list-item>
+            </list>
+          </list-item>
+        </list>
+      </list-item>
+    </list>
+    <p>Here’s another:</p>
+    <list list-type="order">
+      <list-item>
+        <p>First</p>
+      </list-item>
+      <list-item>
+        <p>Second:</p>
+        <list list-type="bullet">
+          <list-item>
+            <p>Fee</p>
+          </list-item>
+          <list-item>
+            <p>Fie</p>
+          </list-item>
+          <list-item>
+            <p>Foe</p>
+          </list-item>
+        </list>
+      </list-item>
+      <list-item>
+        <p>Third</p>
+      </list-item>
+    </list>
+    <p>Same thing but with paragraphs:</p>
+    <list list-type="order">
+      <list-item>
+        <p>First</p>
+      </list-item>
+      <list-item>
+        <p>Second:</p>
+        <list list-type="bullet">
+          <list-item>
+            <p>Fee</p>
+          </list-item>
+          <list-item>
+            <p>Fie</p>
+          </list-item>
+          <list-item>
+            <p>Foe</p>
+          </list-item>
+        </list>
+      </list-item>
+      <list-item>
+        <p>Third</p>
+      </list-item>
+    </list>
+  </sec>
+  <sec id="tabs-and-spaces">
+    <title>Tabs and spaces</title>
+    <list list-type="bullet">
+      <list-item>
+        <p>this is a list item indented with tabs</p>
+      </list-item>
+      <list-item>
+        <p>this is a list item indented with spaces</p>
+        <list list-type="bullet">
+          <list-item>
+            <p>this is an example list item indented with tabs</p>
+          </list-item>
+          <list-item>
+            <p>this is an example list item indented with spaces</p>
+          </list-item>
+        </list>
+      </list-item>
+    </list>
+  </sec>
+  <sec id="fancy-list-markers">
+    <title>Fancy list markers</title>
+    <list list-type="order">
+      <list-item>
+        <label>(2)</label>
+        <p>begins with 2</p>
+      </list-item>
+      <list-item>
+        <label>(3)</label>
+        <p>and now 3</p>
+        <p>with a continuation</p>
+        <list list-type="order">
+          <list-item>
+            <label>iv.</label>
+            <p>sublist with roman numerals, starting with 4</p>
+          </list-item>
+          <list-item>
+            <label>v.</label>
+            <p>more items</p>
+            <list list-type="order">
+              <list-item>
+                <label>(A)</label>
+                <p>a subsublist</p>
+              </list-item>
+              <list-item>
+                <label>(B)</label>
+                <p>a subsublist</p>
+              </list-item>
+            </list>
+          </list-item>
+        </list>
+      </list-item>
+    </list>
+    <p>Nesting:</p>
+    <list list-type="order">
+      <list-item>
+        <p>Upper Alpha</p>
+        <list list-type="order">
+          <list-item>
+            <p>Upper Roman.</p>
+            <list list-type="order">
+              <list-item>
+                <label>(6)</label>
+                <p>Decimal start with 6</p>
+                <list list-type="order">
+                  <list-item>
+                    <label>c)</label>
+                    <p>Lower alpha with paren</p>
+                  </list-item>
+                </list>
+              </list-item>
+            </list>
+          </list-item>
+        </list>
+      </list-item>
+    </list>
+    <p>Autonumbering:</p>
+    <list list-type="order">
+      <list-item>
+        <p>Autonumber.</p>
+      </list-item>
+      <list-item>
+        <p>More.</p>
+        <list list-type="order">
+          <list-item>
+            <p>Nested.</p>
+          </list-item>
+        </list>
+      </list-item>
+    </list>
+    <p>Should not be a list item:</p>
+    <p>M.A. 2007</p>
+    <p>B. Williams</p>
+  </sec>
+</sec>
+<sec id="definition-lists">
+  <title>Definition Lists</title>
+  <p>Tight using spaces:</p>
+  <def-list>
+    <def-item>
+      <term>apple</term>
+      <def>
+        <p>red fruit</p>
+      </def>
+    </def-item>
+    <def-item>
+      <term>orange</term>
+      <def>
+        <p>orange fruit</p>
+      </def>
+    </def-item>
+    <def-item>
+      <term>banana</term>
+      <def>
+        <p>yellow fruit</p>
+      </def>
+    </def-item>
+  </def-list>
+  <p>Tight using tabs:</p>
+  <def-list>
+    <def-item>
+      <term>apple</term>
+      <def>
+        <p>red fruit</p>
+      </def>
+    </def-item>
+    <def-item>
+      <term>orange</term>
+      <def>
+        <p>orange fruit</p>
+      </def>
+    </def-item>
+    <def-item>
+      <term>banana</term>
+      <def>
+        <p>yellow fruit</p>
+      </def>
+    </def-item>
+  </def-list>
+  <p>Loose:</p>
+  <def-list>
+    <def-item>
+      <term>apple</term>
+      <def>
+        <p>red fruit</p>
+      </def>
+    </def-item>
+    <def-item>
+      <term>orange</term>
+      <def>
+        <p>orange fruit</p>
+      </def>
+    </def-item>
+    <def-item>
+      <term>banana</term>
+      <def>
+        <p>yellow fruit</p>
+      </def>
+    </def-item>
+  </def-list>
+  <p>Multiple blocks with italics:</p>
+  <def-list>
+    <def-item>
+      <term><italic>apple</italic></term>
+      <def>
+        <p>red fruit</p>
+        <p>contains seeds, crisp, pleasant to taste</p>
+      </def>
+    </def-item>
+    <def-item>
+      <term><italic>orange</italic></term>
+      <def>
+        <p>orange fruit</p>
+        <p specific-use="wrapper">
+          <preformat>{ orange code block }</preformat>
+        </p>
+        <p specific-use="wrapper">
+          <disp-quote>
+            <p>orange block quote</p>
+          </disp-quote>
+        </p>
+      </def>
+    </def-item>
+  </def-list>
+  <p>Multiple definitions, tight:</p>
+  <def-list>
+    <def-item>
+      <term>apple</term>
+      <def>
+        <p>red fruit</p>
+        <p>computer</p>
+      </def>
+    </def-item>
+    <def-item>
+      <term>orange</term>
+      <def>
+        <p>orange fruit</p>
+        <p>bank</p>
+      </def>
+    </def-item>
+  </def-list>
+  <p>Multiple definitions, loose:</p>
+  <def-list>
+    <def-item>
+      <term>apple</term>
+      <def>
+        <p>red fruit</p>
+        <p>computer</p>
+      </def>
+    </def-item>
+    <def-item>
+      <term>orange</term>
+      <def>
+        <p>orange fruit</p>
+        <p>bank</p>
+      </def>
+    </def-item>
+  </def-list>
+  <p>Blank line after term, indented marker, alternate markers:</p>
+  <def-list>
+    <def-item>
+      <term>apple</term>
+      <def>
+        <p>red fruit</p>
+        <p>computer</p>
+      </def>
+    </def-item>
+    <def-item>
+      <term>orange</term>
+      <def>
+        <p>orange fruit</p>
+        <p specific-use="wrapper">
+          <list list-type="order">
+            <list-item>
+              <p>sublist</p>
+            </list-item>
+            <list-item>
+              <p>sublist</p>
+            </list-item>
+          </list>
+        </p>
+      </def>
+    </def-item>
+  </def-list>
+</sec>
+<sec id="html-blocks">
+  <title>HTML Blocks</title>
+  <p>Simple block on one line:</p>
+  <p>foo</p>
+  <p>And nested without indentation:</p>
+  <p>foo</p>
+  <p>bar</p>
+  <p>Interpreted markdown in a table:</p>
+  <p>This is <italic>emphasized</italic></p>
+  <p>And this is <bold>strong</bold></p>
+  <p>Here’s a simple block:</p>
+  <p>foo</p>
+  <p>This should be a code block, though:</p>
+  <preformat>&lt;div&gt;
+    foo
+&lt;/div&gt;</preformat>
+  <p>As should this:</p>
+  <preformat>&lt;div&gt;foo&lt;/div&gt;</preformat>
+  <p>Now, nested:</p>
+  <p>foo</p>
+  <p>This should just be an HTML comment:</p>
+  <p>Multiline:</p>
+  <p>Code block:</p>
+  <preformat>&lt;!-- Comment --&gt;</preformat>
+  <p>Just plain comment, with trailing spaces on the line:</p>
+  <p>Code:</p>
+  <preformat>&lt;hr /&gt;</preformat>
+  <p>Hr’s:</p>
+</sec>
+<sec id="inline-markup">
+  <title>Inline Markup</title>
+  <p>This is <italic>emphasized</italic>, and so <italic>is this</italic>.</p>
+  <p>This is <bold>strong</bold>, and so <bold>is this</bold>.</p>
+  <p>An <italic><ext-link ext-link-type="uri" xlink:href="/url">emphasized
+  link</ext-link></italic>.</p>
+  <p><bold><italic>This is strong and em.</italic></bold></p>
+  <p>So is <bold><italic>this</italic></bold> word.</p>
+  <p><bold><italic>This is strong and em.</italic></bold></p>
+  <p>So is <bold><italic>this</italic></bold> word.</p>
+  <p>This is code: <monospace>&gt;</monospace>, <monospace>$</monospace>,
+  <monospace>\</monospace>, <monospace>\$</monospace>,
+  <monospace>&lt;html&gt;</monospace>.</p>
+  <p><strike>This is <italic>strikeout</italic>.</strike></p>
+  <p>Superscripts: a<sup>bc</sup>d a<sup><italic>hello</italic></sup>
+  a<sup>hello there</sup>.</p>
+  <p>Subscripts: H<sub>2</sub>O, H<sub>23</sub>O, H<sub>many of them</sub>O.</p>
+  <p>These should not be superscripts or subscripts, because of the unescaped
+  spaces: a^b c^d, a~b c~d.</p>
+</sec>
+<sec id="smart-quotes-ellipses-dashes">
+  <title>Smart quotes, ellipses, dashes</title>
+  <p>“Hello,” said the spider. “‘Shelob’ is my name.”</p>
+  <p>‘A’, ‘B’, and ‘C’ are letters.</p>
+  <p>‘Oak,’ ‘elm,’ and ‘beech’ are names of trees. So is ‘pine.’</p>
+  <p>‘He said, “I want to go.”’ Were you alive in the 70’s?</p>
+  <p>Here is some quoted ‘<monospace>code</monospace>’ and a
+  “<ext-link ext-link-type="uri" xlink:href="http://example.com/?foo=1&amp;bar=2">quoted
+  link</ext-link>”.</p>
+  <p>Some dashes: one—two — three—four — five.</p>
+  <p>Dashes between numbers: 5–7, 255–66, 1987–1999.</p>
+  <p>Ellipses…and…and….</p>
+</sec>
+<sec id="latex">
+  <title>LaTeX</title>
+  <list list-type="bullet">
+    <list-item>
+      <p></p>
+    </list-item>
+    <list-item>
+      <p><inline-formula><mml:math display="inline" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mrow><mml:mn>2</mml:mn><mml:mo>+</mml:mo><mml:mn>2</mml:mn><mml:mo>=</mml:mo><mml:mn>4</mml:mn></mml:mrow></mml:math></inline-formula></p>
+    </list-item>
+    <list-item>
+      <p><inline-formula><mml:math display="inline" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mrow><mml:mi>x</mml:mi><mml:mo>∈</mml:mo><mml:mi>y</mml:mi></mml:mrow></mml:math></inline-formula></p>
+    </list-item>
+    <list-item>
+      <p><inline-formula><mml:math display="inline" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mrow><mml:mi>α</mml:mi><mml:mo>∧</mml:mo><mml:mi>ω</mml:mi></mml:mrow></mml:math></inline-formula></p>
+    </list-item>
+    <list-item>
+      <p><inline-formula><mml:math display="inline" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mn>223</mml:mn></mml:math></inline-formula></p>
+    </list-item>
+    <list-item>
+      <p><inline-formula><mml:math display="inline" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mi>p</mml:mi></mml:math></inline-formula>-Tree</p>
+    </list-item>
+    <list-item>
+      <p>Here’s some display math:
+      <disp-formula><mml:math display="block" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mrow><mml:mfrac><mml:mi>d</mml:mi><mml:mrow><mml:mi>d</mml:mi><mml:mi>x</mml:mi></mml:mrow></mml:mfrac><mml:mi>f</mml:mi><mml:mo stretchy="false" form="prefix">(</mml:mo><mml:mi>x</mml:mi><mml:mo stretchy="false" form="postfix">)</mml:mo><mml:mo>=</mml:mo><mml:munder><mml:mi mathvariant="normal">lim</mml:mi><mml:mrow><mml:mi>h</mml:mi><mml:mo>→</mml:mo><mml:mn>0</mml:mn></mml:mrow></mml:munder><mml:mfrac><mml:mrow><mml:mi>f</mml:mi><mml:mo stretchy="false" form="prefix">(</mml:mo><mml:mi>x</mml:mi><mml:mo>+</mml:mo><mml:mi>h</mml:mi><mml:mo stretchy="false" form="postfix">)</mml:mo><mml:mo>−</mml:mo><mml:mi>f</mml:mi><mml:mo stretchy="false" form="prefix">(</mml:mo><mml:mi>x</mml:mi><mml:mo stretchy="false" form="postfix">)</mml:mo></mml:mrow><mml:mi>h</mml:mi></mml:mfrac></mml:mrow></mml:math></disp-formula></p>
+    </list-item>
+    <list-item>
+      <p>Here’s one that has a line break in it:
+      <inline-formula><mml:math display="inline" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mrow><mml:mi>α</mml:mi><mml:mo>+</mml:mo><mml:mi>ω</mml:mi><mml:mo>×</mml:mo><mml:msup><mml:mi>x</mml:mi><mml:mn>2</mml:mn></mml:msup></mml:mrow></mml:math></inline-formula>.</p>
+    </list-item>
+  </list>
+  <p>These shouldn’t be math:</p>
+  <list list-type="bullet">
+    <list-item>
+      <p>To get the famous equation, write
+      <monospace>$e = mc^2$</monospace>.</p>
+    </list-item>
+    <list-item>
+      <p>$22,000 is a <italic>lot</italic> of money. So is $34,000. (It worked
+      if “lot” is emphasized.)</p>
+    </list-item>
+    <list-item>
+      <p>Shoes ($20) and socks ($5).</p>
+    </list-item>
+    <list-item>
+      <p>Escaped <monospace>$</monospace>: $73 <italic>this should be
+      emphasized</italic> 23$.</p>
+    </list-item>
+  </list>
+  <p>Here’s a LaTeX table:</p>
+</sec>
+<sec id="special-characters">
+  <title>Special Characters</title>
+  <p>Here is some unicode:</p>
+  <list list-type="bullet">
+    <list-item>
+      <p>I hat: Î</p>
+    </list-item>
+    <list-item>
+      <p>o umlaut: ö</p>
+    </list-item>
+    <list-item>
+      <p>section: §</p>
+    </list-item>
+    <list-item>
+      <p>set membership: ∈</p>
+    </list-item>
+    <list-item>
+      <p>copyright: ©</p>
+    </list-item>
+  </list>
+  <p>AT&amp;T has an ampersand in their name.</p>
+  <p>AT&amp;T is another way to write it.</p>
+  <p>This &amp; that.</p>
+  <p>4 &lt; 5.</p>
+  <p>6 &gt; 5.</p>
+  <p>Backslash: \</p>
+  <p>Backtick: `</p>
+  <p>Asterisk: *</p>
+  <p>Underscore: _</p>
+  <p>Left brace: {</p>
+  <p>Right brace: }</p>
+  <p>Left bracket: [</p>
+  <p>Right bracket: ]</p>
+  <p>Left paren: (</p>
+  <p>Right paren: )</p>
+  <p>Greater-than: &gt;</p>
+  <p>Hash: #</p>
+  <p>Period: .</p>
+  <p>Bang: !</p>
+  <p>Plus: +</p>
+  <p>Minus: -</p>
+</sec>
+<sec id="links">
+  <title>Links</title>
+  <sec id="explicit">
+    <title>Explicit</title>
+    <p>Just a
+    <ext-link ext-link-type="uri" xlink:href="/url/">URL</ext-link>.</p>
+    <p><ext-link ext-link-type="uri" xlink:href="/url/" xlink:title="title">URL
+    and title</ext-link>.</p>
+    <p><ext-link ext-link-type="uri" xlink:href="/url/" xlink:title="title preceded by two spaces">URL
+    and title</ext-link>.</p>
+    <p><ext-link ext-link-type="uri" xlink:href="/url/" xlink:title="title preceded by a tab">URL
+    and title</ext-link>.</p>
+    <p><ext-link ext-link-type="uri" xlink:href="/url/" xlink:title="title with &quot;quotes&quot; in it">URL
+    and title</ext-link></p>
+    <p><ext-link ext-link-type="uri" xlink:href="/url/" xlink:title="title with single quotes">URL
+    and title</ext-link></p>
+    <p><ext-link ext-link-type="uri" xlink:href="/url/with_underscore">with_underscore</ext-link></p>
+    <p><ext-link ext-link-type="uri" xlink:href="mailto:nobody@nowhere.net">Email
+    link</ext-link></p>
+    <p><ext-link ext-link-type="uri" xlink:href="">Empty</ext-link>.</p>
+  </sec>
+  <sec id="reference">
+    <title>Reference</title>
+    <p>Foo <ext-link ext-link-type="uri" xlink:href="/url/">bar</ext-link>.</p>
+    <p>With <ext-link ext-link-type="uri" xlink:href="/url/">embedded
+    [brackets]</ext-link>.</p>
+    <p><ext-link ext-link-type="uri" xlink:href="/url/">b</ext-link> by itself
+    should be a link.</p>
+    <p>Indented
+    <ext-link ext-link-type="uri" xlink:href="/url">once</ext-link>.</p>
+    <p>Indented
+    <ext-link ext-link-type="uri" xlink:href="/url">twice</ext-link>.</p>
+    <p>Indented
+    <ext-link ext-link-type="uri" xlink:href="/url">thrice</ext-link>.</p>
+    <p>This should [not][] be a link.</p>
+    <preformat>[not]: /url</preformat>
+    <p>Foo
+    <ext-link ext-link-type="uri" xlink:href="/url/" xlink:title="Title with &quot;quotes&quot; inside">bar</ext-link>.</p>
+    <p>Foo
+    <ext-link ext-link-type="uri" xlink:href="/url/" xlink:title="Title with &quot;quote&quot; inside">biz</ext-link>.</p>
+  </sec>
+  <sec id="with-ampersands">
+    <title>With ampersands</title>
+    <p>Here’s a
+    <ext-link ext-link-type="uri" xlink:href="http://example.com/?foo=1&amp;bar=2">link
+    with an ampersand in the URL</ext-link>.</p>
+    <p>Here’s a link with an amersand in the link text:
+    <ext-link ext-link-type="uri" xlink:href="http://att.com/" xlink:title="AT&amp;T">AT&amp;T</ext-link>.</p>
+    <p>Here’s an
+    <ext-link ext-link-type="uri" xlink:href="/script?foo=1&amp;bar=2">inline
+    link</ext-link>.</p>
+    <p>Here’s an
+    <ext-link ext-link-type="uri" xlink:href="/script?foo=1&amp;bar=2">inline
+    link in pointy braces</ext-link>.</p>
+  </sec>
+  <sec id="autolinks">
+    <title>Autolinks</title>
+    <p>With an ampersand:
+    <ext-link ext-link-type="uri" xlink:href="http://example.com/?foo=1&amp;bar=2">http://example.com/?foo=1&amp;bar=2</ext-link></p>
+    <list list-type="bullet">
+      <list-item>
+        <p>In a list?</p>
+      </list-item>
+      <list-item>
+        <p><ext-link ext-link-type="uri" xlink:href="http://example.com/">http://example.com/</ext-link></p>
+      </list-item>
+      <list-item>
+        <p>It should.</p>
+      </list-item>
+    </list>
+    <p>An e-mail address: <email>nobody@nowhere.net</email></p>
+    <disp-quote>
+      <p>Blockquoted:
+      <ext-link ext-link-type="uri" xlink:href="http://example.com/">http://example.com/</ext-link></p>
+    </disp-quote>
+    <p>Auto-links should not occur here:
+    <monospace>&lt;http://example.com/&gt;</monospace></p>
+    <preformat>or here: &lt;http://example.com/&gt;</preformat>
+  </sec>
+</sec>
+<sec id="images">
+  <title>Images</title>
+  <p>From “Voyage dans la Lune” by Georges Melies (1902):</p>
+  <fig>
+    <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
+  <inline-graphic mimetype="image" mime-subtype="jpeg" xlink:href="movie.jpg">
+    <alt-text>movie</alt-text>
+  </inline-graphic> icon.</p>
+</sec>
+<sec id="footnotes">
+  <title>Footnotes</title>
+  <p>Here is a footnote reference,<fn>
+    <p>Here is the footnote. It can go anywhere after the footnote reference. It
+    need not be placed at the end of the document.</p>
+  </fn> and another.<fn>
+    <p>Here’s the long note. This one contains multiple blocks.</p>
+    <p>Subsequent blocks are indented to show that they belong to the footnote
+    (as with list items).</p>
+    <p specific-use="wrapper">
+      <preformat>  { &lt;code&gt; }</preformat>
+    </p>
+    <p>If you want, you can indent every line, but you can also be lazy and just
+    indent the first line of each block.</p>
+  </fn> This should <italic>not</italic> be a footnote reference, because it
+  contains a space.[^my note] Here is an inline note.<fn>
+    <p>This is <italic>easier</italic> to type. Inline notes may contain
+    <ext-link ext-link-type="uri" xlink:href="http://google.com">links</ext-link>
+    and <monospace>]</monospace> verbatim characters, as well as [bracketed
+    text].</p>
+  </fn></p>
+  <disp-quote>
+    <p>Notes can go in quotes.<fn>
+      <p>In quote.</p>
+    </fn></p>
+  </disp-quote>
+  <list list-type="order">
+    <list-item>
+      <p>And in list items.<fn>
+        <p>In list.</p>
+      </fn></p>
+    </list-item>
+  </list>
+  <p>This paragraph should not be part of the note, as it is not indented.</p>
+</sec>
+</body>
+<back>
+</back>
+</article>
diff --git a/test/writer.jats_publishing b/test/writer.jats_publishing
new file mode 100644
--- /dev/null
+++ b/test/writer.jats_publishing
@@ -0,0 +1,883 @@
+<?xml version="1.0" encoding="utf-8" ?>
+<!DOCTYPE article PUBLIC "-//NLM//DTD JATS (Z39.96) Journal Publishing DTD v1.2 20190208//EN"
+                  "JATS-publishing1.dtd">
+<article xmlns:mml="http://www.w3.org/1998/Math/MathML" xmlns:xlink="http://www.w3.org/1999/xlink" dtd-version="1.2" article-type="other">
+<front>
+<journal-meta>
+<journal-id></journal-id>
+<journal-title-group>
+</journal-title-group>
+<issn></issn>
+<publisher>
+<publisher-name></publisher-name>
+</publisher>
+</journal-meta>
+<article-meta>
+<title-group>
+<article-title>Pandoc Test Suite</article-title>
+</title-group>
+<contrib-group>
+<contrib contrib-type="author">
+<string-name>John MacFarlane</string-name>
+</contrib>
+<contrib contrib-type="author">
+<string-name>Anonymous</string-name>
+</contrib>
+</contrib-group>
+<pub-date date-type="pub" publication-format="electronic" iso-8601-date="2006-07-17">
+<day>17</day>
+<month>7</month>
+<year>2006</year>
+</pub-date>
+<permissions>
+</permissions>
+</article-meta>
+</front>
+<body>
+<p>This is a set of tests for pandoc. Most of them are adapted from John
+Gruber’s markdown test suite.</p>
+<sec id="headers">
+  <title>Headers</title>
+  <sec id="level-2-with-an-embedded-link">
+    <title>Level 2 with an
+    <ext-link ext-link-type="uri" xlink:href="/url">embedded
+    link</ext-link></title>
+    <sec id="level-3-with-emphasis">
+      <title>Level 3 with <italic>emphasis</italic></title>
+      <sec id="level-4">
+        <title>Level 4</title>
+        <sec id="level-5">
+          <title>Level 5</title>
+        </sec>
+      </sec>
+    </sec>
+  </sec>
+</sec>
+<sec id="level-1">
+  <title>Level 1</title>
+  <sec id="level-2-with-emphasis">
+    <title>Level 2 with <italic>emphasis</italic></title>
+    <sec id="level-3">
+      <title>Level 3</title>
+      <p>with no blank line</p>
+    </sec>
+  </sec>
+  <sec id="level-2">
+    <title>Level 2</title>
+    <p>with no blank line</p>
+  </sec>
+</sec>
+<sec id="paragraphs">
+  <title>Paragraphs</title>
+  <p>Here’s a regular paragraph.</p>
+  <p>In Markdown 1.0.0 and earlier. Version 8. This line turns into a list item.
+  Because a hard-wrapped line in the middle of a paragraph looked like a list
+  item.</p>
+  <p>Here’s one with a bullet. * criminey.</p>
+  <p>There should be a hard line break
+  here.</p>
+</sec>
+<sec id="block-quotes">
+  <title>Block Quotes</title>
+  <p>E-mail style:</p>
+  <disp-quote>
+    <p>This is a block quote. It is pretty short.</p>
+  </disp-quote>
+  <disp-quote>
+    <p>Code in a block quote:</p>
+    <preformat>sub status {
+    print &quot;working&quot;;
+}</preformat>
+    <p>A list:</p>
+    <list list-type="order">
+      <list-item>
+        <p>item one</p>
+      </list-item>
+      <list-item>
+        <p>item two</p>
+      </list-item>
+    </list>
+    <p>Nested block quotes:</p>
+    <disp-quote>
+      <p>nested</p>
+    </disp-quote>
+    <disp-quote>
+      <p>nested</p>
+    </disp-quote>
+  </disp-quote>
+  <p>This should not be a block quote: 2 &gt; 1.</p>
+  <p>And a following paragraph.</p>
+</sec>
+<sec id="code-blocks">
+  <title>Code Blocks</title>
+  <p>Code:</p>
+  <preformat>---- (should be four hyphens)
+
+sub status {
+    print &quot;working&quot;;
+}
+
+this code block is indented by one tab</preformat>
+  <p>And:</p>
+  <preformat>    this code block is indented by two tabs
+
+These should not be escaped:  \$ \\ \&gt; \[ \{</preformat>
+</sec>
+<sec id="lists">
+  <title>Lists</title>
+  <sec id="unordered">
+    <title>Unordered</title>
+    <p>Asterisks tight:</p>
+    <list list-type="bullet">
+      <list-item>
+        <p>asterisk 1</p>
+      </list-item>
+      <list-item>
+        <p>asterisk 2</p>
+      </list-item>
+      <list-item>
+        <p>asterisk 3</p>
+      </list-item>
+    </list>
+    <p>Asterisks loose:</p>
+    <list list-type="bullet">
+      <list-item>
+        <p>asterisk 1</p>
+      </list-item>
+      <list-item>
+        <p>asterisk 2</p>
+      </list-item>
+      <list-item>
+        <p>asterisk 3</p>
+      </list-item>
+    </list>
+    <p>Pluses tight:</p>
+    <list list-type="bullet">
+      <list-item>
+        <p>Plus 1</p>
+      </list-item>
+      <list-item>
+        <p>Plus 2</p>
+      </list-item>
+      <list-item>
+        <p>Plus 3</p>
+      </list-item>
+    </list>
+    <p>Pluses loose:</p>
+    <list list-type="bullet">
+      <list-item>
+        <p>Plus 1</p>
+      </list-item>
+      <list-item>
+        <p>Plus 2</p>
+      </list-item>
+      <list-item>
+        <p>Plus 3</p>
+      </list-item>
+    </list>
+    <p>Minuses tight:</p>
+    <list list-type="bullet">
+      <list-item>
+        <p>Minus 1</p>
+      </list-item>
+      <list-item>
+        <p>Minus 2</p>
+      </list-item>
+      <list-item>
+        <p>Minus 3</p>
+      </list-item>
+    </list>
+    <p>Minuses loose:</p>
+    <list list-type="bullet">
+      <list-item>
+        <p>Minus 1</p>
+      </list-item>
+      <list-item>
+        <p>Minus 2</p>
+      </list-item>
+      <list-item>
+        <p>Minus 3</p>
+      </list-item>
+    </list>
+  </sec>
+  <sec id="ordered">
+    <title>Ordered</title>
+    <p>Tight:</p>
+    <list list-type="order">
+      <list-item>
+        <p>First</p>
+      </list-item>
+      <list-item>
+        <p>Second</p>
+      </list-item>
+      <list-item>
+        <p>Third</p>
+      </list-item>
+    </list>
+    <p>and:</p>
+    <list list-type="order">
+      <list-item>
+        <p>One</p>
+      </list-item>
+      <list-item>
+        <p>Two</p>
+      </list-item>
+      <list-item>
+        <p>Three</p>
+      </list-item>
+    </list>
+    <p>Loose using tabs:</p>
+    <list list-type="order">
+      <list-item>
+        <p>First</p>
+      </list-item>
+      <list-item>
+        <p>Second</p>
+      </list-item>
+      <list-item>
+        <p>Third</p>
+      </list-item>
+    </list>
+    <p>and using spaces:</p>
+    <list list-type="order">
+      <list-item>
+        <p>One</p>
+      </list-item>
+      <list-item>
+        <p>Two</p>
+      </list-item>
+      <list-item>
+        <p>Three</p>
+      </list-item>
+    </list>
+    <p>Multiple paragraphs:</p>
+    <list list-type="order">
+      <list-item>
+        <p>Item 1, graf one.</p>
+        <p>Item 1. graf two. The quick brown fox jumped over the lazy dog’s
+        back.</p>
+      </list-item>
+      <list-item>
+        <p>Item 2.</p>
+      </list-item>
+      <list-item>
+        <p>Item 3.</p>
+      </list-item>
+    </list>
+  </sec>
+  <sec id="nested">
+    <title>Nested</title>
+    <list list-type="bullet">
+      <list-item>
+        <p>Tab</p>
+        <list list-type="bullet">
+          <list-item>
+            <p>Tab</p>
+            <list list-type="bullet">
+              <list-item>
+                <p>Tab</p>
+              </list-item>
+            </list>
+          </list-item>
+        </list>
+      </list-item>
+    </list>
+    <p>Here’s another:</p>
+    <list list-type="order">
+      <list-item>
+        <p>First</p>
+      </list-item>
+      <list-item>
+        <p>Second:</p>
+        <list list-type="bullet">
+          <list-item>
+            <p>Fee</p>
+          </list-item>
+          <list-item>
+            <p>Fie</p>
+          </list-item>
+          <list-item>
+            <p>Foe</p>
+          </list-item>
+        </list>
+      </list-item>
+      <list-item>
+        <p>Third</p>
+      </list-item>
+    </list>
+    <p>Same thing but with paragraphs:</p>
+    <list list-type="order">
+      <list-item>
+        <p>First</p>
+      </list-item>
+      <list-item>
+        <p>Second:</p>
+        <list list-type="bullet">
+          <list-item>
+            <p>Fee</p>
+          </list-item>
+          <list-item>
+            <p>Fie</p>
+          </list-item>
+          <list-item>
+            <p>Foe</p>
+          </list-item>
+        </list>
+      </list-item>
+      <list-item>
+        <p>Third</p>
+      </list-item>
+    </list>
+  </sec>
+  <sec id="tabs-and-spaces">
+    <title>Tabs and spaces</title>
+    <list list-type="bullet">
+      <list-item>
+        <p>this is a list item indented with tabs</p>
+      </list-item>
+      <list-item>
+        <p>this is a list item indented with spaces</p>
+        <list list-type="bullet">
+          <list-item>
+            <p>this is an example list item indented with tabs</p>
+          </list-item>
+          <list-item>
+            <p>this is an example list item indented with spaces</p>
+          </list-item>
+        </list>
+      </list-item>
+    </list>
+  </sec>
+  <sec id="fancy-list-markers">
+    <title>Fancy list markers</title>
+    <list list-type="order">
+      <list-item>
+        <label>(2)</label>
+        <p>begins with 2</p>
+      </list-item>
+      <list-item>
+        <label>(3)</label>
+        <p>and now 3</p>
+        <p>with a continuation</p>
+        <list list-type="roman-lower">
+          <list-item>
+            <label>iv.</label>
+            <p>sublist with roman numerals, starting with 4</p>
+          </list-item>
+          <list-item>
+            <label>v.</label>
+            <p>more items</p>
+            <list list-type="alpha-upper">
+              <list-item>
+                <label>(A)</label>
+                <p>a subsublist</p>
+              </list-item>
+              <list-item>
+                <label>(B)</label>
+                <p>a subsublist</p>
+              </list-item>
+            </list>
+          </list-item>
+        </list>
+      </list-item>
+    </list>
+    <p>Nesting:</p>
+    <list list-type="alpha-upper">
+      <list-item>
+        <p>Upper Alpha</p>
+        <list list-type="roman-upper">
+          <list-item>
+            <p>Upper Roman.</p>
+            <list list-type="order">
+              <list-item>
+                <label>(6)</label>
+                <p>Decimal start with 6</p>
+                <list list-type="alpha-lower">
+                  <list-item>
+                    <label>c)</label>
+                    <p>Lower alpha with paren</p>
+                  </list-item>
+                </list>
+              </list-item>
+            </list>
+          </list-item>
+        </list>
+      </list-item>
+    </list>
+    <p>Autonumbering:</p>
+    <list list-type="order">
+      <list-item>
+        <p>Autonumber.</p>
+      </list-item>
+      <list-item>
+        <p>More.</p>
+        <list list-type="order">
+          <list-item>
+            <p>Nested.</p>
+          </list-item>
+        </list>
+      </list-item>
+    </list>
+    <p>Should not be a list item:</p>
+    <p>M.A. 2007</p>
+    <p>B. Williams</p>
+  </sec>
+</sec>
+<sec id="definition-lists">
+  <title>Definition Lists</title>
+  <p>Tight using spaces:</p>
+  <def-list>
+    <def-item>
+      <term>apple</term>
+      <def>
+        <p>red fruit</p>
+      </def>
+    </def-item>
+    <def-item>
+      <term>orange</term>
+      <def>
+        <p>orange fruit</p>
+      </def>
+    </def-item>
+    <def-item>
+      <term>banana</term>
+      <def>
+        <p>yellow fruit</p>
+      </def>
+    </def-item>
+  </def-list>
+  <p>Tight using tabs:</p>
+  <def-list>
+    <def-item>
+      <term>apple</term>
+      <def>
+        <p>red fruit</p>
+      </def>
+    </def-item>
+    <def-item>
+      <term>orange</term>
+      <def>
+        <p>orange fruit</p>
+      </def>
+    </def-item>
+    <def-item>
+      <term>banana</term>
+      <def>
+        <p>yellow fruit</p>
+      </def>
+    </def-item>
+  </def-list>
+  <p>Loose:</p>
+  <def-list>
+    <def-item>
+      <term>apple</term>
+      <def>
+        <p>red fruit</p>
+      </def>
+    </def-item>
+    <def-item>
+      <term>orange</term>
+      <def>
+        <p>orange fruit</p>
+      </def>
+    </def-item>
+    <def-item>
+      <term>banana</term>
+      <def>
+        <p>yellow fruit</p>
+      </def>
+    </def-item>
+  </def-list>
+  <p>Multiple blocks with italics:</p>
+  <def-list>
+    <def-item>
+      <term><italic>apple</italic></term>
+      <def>
+        <p>red fruit</p>
+        <p>contains seeds, crisp, pleasant to taste</p>
+      </def>
+    </def-item>
+    <def-item>
+      <term><italic>orange</italic></term>
+      <def>
+        <p>orange fruit</p>
+        <p specific-use="wrapper">
+          <preformat>{ orange code block }</preformat>
+        </p>
+        <p specific-use="wrapper">
+          <disp-quote>
+            <p>orange block quote</p>
+          </disp-quote>
+        </p>
+      </def>
+    </def-item>
+  </def-list>
+  <p>Multiple definitions, tight:</p>
+  <def-list>
+    <def-item>
+      <term>apple</term>
+      <def>
+        <p>red fruit</p>
+        <p>computer</p>
+      </def>
+    </def-item>
+    <def-item>
+      <term>orange</term>
+      <def>
+        <p>orange fruit</p>
+        <p>bank</p>
+      </def>
+    </def-item>
+  </def-list>
+  <p>Multiple definitions, loose:</p>
+  <def-list>
+    <def-item>
+      <term>apple</term>
+      <def>
+        <p>red fruit</p>
+        <p>computer</p>
+      </def>
+    </def-item>
+    <def-item>
+      <term>orange</term>
+      <def>
+        <p>orange fruit</p>
+        <p>bank</p>
+      </def>
+    </def-item>
+  </def-list>
+  <p>Blank line after term, indented marker, alternate markers:</p>
+  <def-list>
+    <def-item>
+      <term>apple</term>
+      <def>
+        <p>red fruit</p>
+        <p>computer</p>
+      </def>
+    </def-item>
+    <def-item>
+      <term>orange</term>
+      <def>
+        <p>orange fruit</p>
+        <p specific-use="wrapper">
+          <list list-type="order">
+            <list-item>
+              <p>sublist</p>
+            </list-item>
+            <list-item>
+              <p>sublist</p>
+            </list-item>
+          </list>
+        </p>
+      </def>
+    </def-item>
+  </def-list>
+</sec>
+<sec id="html-blocks">
+  <title>HTML Blocks</title>
+  <p>Simple block on one line:</p>
+  <p>foo</p>
+  <p>And nested without indentation:</p>
+  <p>foo</p>
+  <p>bar</p>
+  <p>Interpreted markdown in a table:</p>
+  <p>This is <italic>emphasized</italic></p>
+  <p>And this is <bold>strong</bold></p>
+  <p>Here’s a simple block:</p>
+  <p>foo</p>
+  <p>This should be a code block, though:</p>
+  <preformat>&lt;div&gt;
+    foo
+&lt;/div&gt;</preformat>
+  <p>As should this:</p>
+  <preformat>&lt;div&gt;foo&lt;/div&gt;</preformat>
+  <p>Now, nested:</p>
+  <p>foo</p>
+  <p>This should just be an HTML comment:</p>
+  <p>Multiline:</p>
+  <p>Code block:</p>
+  <preformat>&lt;!-- Comment --&gt;</preformat>
+  <p>Just plain comment, with trailing spaces on the line:</p>
+  <p>Code:</p>
+  <preformat>&lt;hr /&gt;</preformat>
+  <p>Hr’s:</p>
+</sec>
+<sec id="inline-markup">
+  <title>Inline Markup</title>
+  <p>This is <italic>emphasized</italic>, and so <italic>is this</italic>.</p>
+  <p>This is <bold>strong</bold>, and so <bold>is this</bold>.</p>
+  <p>An <italic><ext-link ext-link-type="uri" xlink:href="/url">emphasized
+  link</ext-link></italic>.</p>
+  <p><bold><italic>This is strong and em.</italic></bold></p>
+  <p>So is <bold><italic>this</italic></bold> word.</p>
+  <p><bold><italic>This is strong and em.</italic></bold></p>
+  <p>So is <bold><italic>this</italic></bold> word.</p>
+  <p>This is code: <monospace>&gt;</monospace>, <monospace>$</monospace>,
+  <monospace>\</monospace>, <monospace>\$</monospace>,
+  <monospace>&lt;html&gt;</monospace>.</p>
+  <p><strike>This is <italic>strikeout</italic>.</strike></p>
+  <p>Superscripts: a<sup>bc</sup>d a<sup><italic>hello</italic></sup>
+  a<sup>hello there</sup>.</p>
+  <p>Subscripts: H<sub>2</sub>O, H<sub>23</sub>O, H<sub>many of them</sub>O.</p>
+  <p>These should not be superscripts or subscripts, because of the unescaped
+  spaces: a^b c^d, a~b c~d.</p>
+</sec>
+<sec id="smart-quotes-ellipses-dashes">
+  <title>Smart quotes, ellipses, dashes</title>
+  <p>“Hello,” said the spider. “‘Shelob’ is my name.”</p>
+  <p>‘A’, ‘B’, and ‘C’ are letters.</p>
+  <p>‘Oak,’ ‘elm,’ and ‘beech’ are names of trees. So is ‘pine.’</p>
+  <p>‘He said, “I want to go.”’ Were you alive in the 70’s?</p>
+  <p>Here is some quoted ‘<monospace>code</monospace>’ and a
+  “<ext-link ext-link-type="uri" xlink:href="http://example.com/?foo=1&amp;bar=2">quoted
+  link</ext-link>”.</p>
+  <p>Some dashes: one—two — three—four — five.</p>
+  <p>Dashes between numbers: 5–7, 255–66, 1987–1999.</p>
+  <p>Ellipses…and…and….</p>
+</sec>
+<sec id="latex">
+  <title>LaTeX</title>
+  <list list-type="bullet">
+    <list-item>
+      <p></p>
+    </list-item>
+    <list-item>
+      <p><inline-formula><alternatives>
+      <tex-math><![CDATA[2+2=4]]></tex-math>
+      <mml:math display="inline" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mrow><mml:mn>2</mml:mn><mml:mo>+</mml:mo><mml:mn>2</mml:mn><mml:mo>=</mml:mo><mml:mn>4</mml:mn></mml:mrow></mml:math></alternatives></inline-formula></p>
+    </list-item>
+    <list-item>
+      <p><inline-formula><alternatives>
+      <tex-math><![CDATA[x \in y]]></tex-math>
+      <mml:math display="inline" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mrow><mml:mi>x</mml:mi><mml:mo>∈</mml:mo><mml:mi>y</mml:mi></mml:mrow></mml:math></alternatives></inline-formula></p>
+    </list-item>
+    <list-item>
+      <p><inline-formula><alternatives>
+      <tex-math><![CDATA[\alpha \wedge \omega]]></tex-math>
+      <mml:math display="inline" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mrow><mml:mi>α</mml:mi><mml:mo>∧</mml:mo><mml:mi>ω</mml:mi></mml:mrow></mml:math></alternatives></inline-formula></p>
+    </list-item>
+    <list-item>
+      <p><inline-formula><alternatives>
+      <tex-math><![CDATA[223]]></tex-math>
+      <mml:math display="inline" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mn>223</mml:mn></mml:math></alternatives></inline-formula></p>
+    </list-item>
+    <list-item>
+      <p><inline-formula><alternatives>
+      <tex-math><![CDATA[p]]></tex-math>
+      <mml:math display="inline" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mi>p</mml:mi></mml:math></alternatives></inline-formula>-Tree</p>
+    </list-item>
+    <list-item>
+      <p>Here’s some display math: <disp-formula><alternatives>
+      <tex-math><![CDATA[\frac{d}{dx}f(x)=\lim_{h\to 0}\frac{f(x+h)-f(x)}{h}]]></tex-math>
+      <mml:math display="block" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mrow><mml:mfrac><mml:mi>d</mml:mi><mml:mrow><mml:mi>d</mml:mi><mml:mi>x</mml:mi></mml:mrow></mml:mfrac><mml:mi>f</mml:mi><mml:mo stretchy="false" form="prefix">(</mml:mo><mml:mi>x</mml:mi><mml:mo stretchy="false" form="postfix">)</mml:mo><mml:mo>=</mml:mo><mml:munder><mml:mi mathvariant="normal">lim</mml:mi><mml:mrow><mml:mi>h</mml:mi><mml:mo>→</mml:mo><mml:mn>0</mml:mn></mml:mrow></mml:munder><mml:mfrac><mml:mrow><mml:mi>f</mml:mi><mml:mo stretchy="false" form="prefix">(</mml:mo><mml:mi>x</mml:mi><mml:mo>+</mml:mo><mml:mi>h</mml:mi><mml:mo stretchy="false" form="postfix">)</mml:mo><mml:mo>−</mml:mo><mml:mi>f</mml:mi><mml:mo stretchy="false" form="prefix">(</mml:mo><mml:mi>x</mml:mi><mml:mo stretchy="false" form="postfix">)</mml:mo></mml:mrow><mml:mi>h</mml:mi></mml:mfrac></mml:mrow></mml:math></alternatives></disp-formula></p>
+    </list-item>
+    <list-item>
+      <p>Here’s one that has a line break in it: <inline-formula><alternatives>
+      <tex-math><![CDATA[\alpha + \omega \times x^2]]></tex-math>
+      <mml:math display="inline" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mrow><mml:mi>α</mml:mi><mml:mo>+</mml:mo><mml:mi>ω</mml:mi><mml:mo>×</mml:mo><mml:msup><mml:mi>x</mml:mi><mml:mn>2</mml:mn></mml:msup></mml:mrow></mml:math></alternatives></inline-formula>.</p>
+    </list-item>
+  </list>
+  <p>These shouldn’t be math:</p>
+  <list list-type="bullet">
+    <list-item>
+      <p>To get the famous equation, write
+      <monospace>$e = mc^2$</monospace>.</p>
+    </list-item>
+    <list-item>
+      <p>$22,000 is a <italic>lot</italic> of money. So is $34,000. (It worked
+      if “lot” is emphasized.)</p>
+    </list-item>
+    <list-item>
+      <p>Shoes ($20) and socks ($5).</p>
+    </list-item>
+    <list-item>
+      <p>Escaped <monospace>$</monospace>: $73 <italic>this should be
+      emphasized</italic> 23$.</p>
+    </list-item>
+  </list>
+  <p>Here’s a LaTeX table:</p>
+</sec>
+<sec id="special-characters">
+  <title>Special Characters</title>
+  <p>Here is some unicode:</p>
+  <list list-type="bullet">
+    <list-item>
+      <p>I hat: Î</p>
+    </list-item>
+    <list-item>
+      <p>o umlaut: ö</p>
+    </list-item>
+    <list-item>
+      <p>section: §</p>
+    </list-item>
+    <list-item>
+      <p>set membership: ∈</p>
+    </list-item>
+    <list-item>
+      <p>copyright: ©</p>
+    </list-item>
+  </list>
+  <p>AT&amp;T has an ampersand in their name.</p>
+  <p>AT&amp;T is another way to write it.</p>
+  <p>This &amp; that.</p>
+  <p>4 &lt; 5.</p>
+  <p>6 &gt; 5.</p>
+  <p>Backslash: \</p>
+  <p>Backtick: `</p>
+  <p>Asterisk: *</p>
+  <p>Underscore: _</p>
+  <p>Left brace: {</p>
+  <p>Right brace: }</p>
+  <p>Left bracket: [</p>
+  <p>Right bracket: ]</p>
+  <p>Left paren: (</p>
+  <p>Right paren: )</p>
+  <p>Greater-than: &gt;</p>
+  <p>Hash: #</p>
+  <p>Period: .</p>
+  <p>Bang: !</p>
+  <p>Plus: +</p>
+  <p>Minus: -</p>
+</sec>
+<sec id="links">
+  <title>Links</title>
+  <sec id="explicit">
+    <title>Explicit</title>
+    <p>Just a
+    <ext-link ext-link-type="uri" xlink:href="/url/">URL</ext-link>.</p>
+    <p><ext-link ext-link-type="uri" xlink:href="/url/" xlink:title="title">URL
+    and title</ext-link>.</p>
+    <p><ext-link ext-link-type="uri" xlink:href="/url/" xlink:title="title preceded by two spaces">URL
+    and title</ext-link>.</p>
+    <p><ext-link ext-link-type="uri" xlink:href="/url/" xlink:title="title preceded by a tab">URL
+    and title</ext-link>.</p>
+    <p><ext-link ext-link-type="uri" xlink:href="/url/" xlink:title="title with &quot;quotes&quot; in it">URL
+    and title</ext-link></p>
+    <p><ext-link ext-link-type="uri" xlink:href="/url/" xlink:title="title with single quotes">URL
+    and title</ext-link></p>
+    <p><ext-link ext-link-type="uri" xlink:href="/url/with_underscore">with_underscore</ext-link></p>
+    <p><ext-link ext-link-type="uri" xlink:href="mailto:nobody@nowhere.net">Email
+    link</ext-link></p>
+    <p><ext-link ext-link-type="uri" xlink:href="">Empty</ext-link>.</p>
+  </sec>
+  <sec id="reference">
+    <title>Reference</title>
+    <p>Foo <ext-link ext-link-type="uri" xlink:href="/url/">bar</ext-link>.</p>
+    <p>With <ext-link ext-link-type="uri" xlink:href="/url/">embedded
+    [brackets]</ext-link>.</p>
+    <p><ext-link ext-link-type="uri" xlink:href="/url/">b</ext-link> by itself
+    should be a link.</p>
+    <p>Indented
+    <ext-link ext-link-type="uri" xlink:href="/url">once</ext-link>.</p>
+    <p>Indented
+    <ext-link ext-link-type="uri" xlink:href="/url">twice</ext-link>.</p>
+    <p>Indented
+    <ext-link ext-link-type="uri" xlink:href="/url">thrice</ext-link>.</p>
+    <p>This should [not][] be a link.</p>
+    <preformat>[not]: /url</preformat>
+    <p>Foo
+    <ext-link ext-link-type="uri" xlink:href="/url/" xlink:title="Title with &quot;quotes&quot; inside">bar</ext-link>.</p>
+    <p>Foo
+    <ext-link ext-link-type="uri" xlink:href="/url/" xlink:title="Title with &quot;quote&quot; inside">biz</ext-link>.</p>
+  </sec>
+  <sec id="with-ampersands">
+    <title>With ampersands</title>
+    <p>Here’s a
+    <ext-link ext-link-type="uri" xlink:href="http://example.com/?foo=1&amp;bar=2">link
+    with an ampersand in the URL</ext-link>.</p>
+    <p>Here’s a link with an amersand in the link text:
+    <ext-link ext-link-type="uri" xlink:href="http://att.com/" xlink:title="AT&amp;T">AT&amp;T</ext-link>.</p>
+    <p>Here’s an
+    <ext-link ext-link-type="uri" xlink:href="/script?foo=1&amp;bar=2">inline
+    link</ext-link>.</p>
+    <p>Here’s an
+    <ext-link ext-link-type="uri" xlink:href="/script?foo=1&amp;bar=2">inline
+    link in pointy braces</ext-link>.</p>
+  </sec>
+  <sec id="autolinks">
+    <title>Autolinks</title>
+    <p>With an ampersand:
+    <ext-link ext-link-type="uri" xlink:href="http://example.com/?foo=1&amp;bar=2">http://example.com/?foo=1&amp;bar=2</ext-link></p>
+    <list list-type="bullet">
+      <list-item>
+        <p>In a list?</p>
+      </list-item>
+      <list-item>
+        <p><ext-link ext-link-type="uri" xlink:href="http://example.com/">http://example.com/</ext-link></p>
+      </list-item>
+      <list-item>
+        <p>It should.</p>
+      </list-item>
+    </list>
+    <p>An e-mail address: <email>nobody@nowhere.net</email></p>
+    <disp-quote>
+      <p>Blockquoted:
+      <ext-link ext-link-type="uri" xlink:href="http://example.com/">http://example.com/</ext-link></p>
+    </disp-quote>
+    <p>Auto-links should not occur here:
+    <monospace>&lt;http://example.com/&gt;</monospace></p>
+    <preformat>or here: &lt;http://example.com/&gt;</preformat>
+  </sec>
+</sec>
+<sec id="images">
+  <title>Images</title>
+  <p>From “Voyage dans la Lune” by Georges Melies (1902):</p>
+  <fig>
+    <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
+  <inline-graphic mimetype="image" mime-subtype="jpeg" xlink:href="movie.jpg">
+    <alt-text>movie</alt-text>
+  </inline-graphic> icon.</p>
+</sec>
+<sec id="footnotes">
+  <title>Footnotes</title>
+  <p>Here is a footnote reference,<xref ref-type="fn" rid="fn1">1</xref> and
+  another.<xref ref-type="fn" rid="fn2">2</xref> This should
+  <italic>not</italic> be a footnote reference, because it contains a space.[^my
+  note] Here is an inline note.<xref ref-type="fn" rid="fn3">3</xref></p>
+  <disp-quote>
+    <p>Notes can go in quotes.<xref ref-type="fn" rid="fn4">4</xref></p>
+  </disp-quote>
+  <list list-type="order">
+    <list-item>
+      <p>And in list items.<xref ref-type="fn" rid="fn5">5</xref></p>
+    </list-item>
+  </list>
+  <p>This paragraph should not be part of the note, as it is not indented.</p>
+</sec>
+</body>
+<back>
+<fn-group>
+  <fn id="fn1">
+    <label>1</label><p>Here is the footnote. It can go anywhere after the
+    footnote reference. It need not be placed at the end of the document.</p>
+  </fn>
+  <fn id="fn2">
+    <label>2</label><p>Here’s the long note. This one contains multiple
+    blocks.</p>
+    <p>Subsequent blocks are indented to show that they belong to the footnote
+    (as with list items).</p>
+    <p specific-use="wrapper">
+      <preformat>  { &lt;code&gt; }</preformat>
+    </p>
+    <p>If you want, you can indent every line, but you can also be lazy and just
+    indent the first line of each block.</p>
+  </fn>
+  <fn id="fn3">
+    <label>3</label><p>This is <italic>easier</italic> to type. Inline notes may
+    contain
+    <ext-link ext-link-type="uri" xlink:href="http://google.com">links</ext-link>
+    and <monospace>]</monospace> verbatim characters, as well as [bracketed
+    text].</p>
+  </fn>
+  <fn id="fn4">
+    <label>4</label><p>In quote.</p>
+  </fn>
+  <fn id="fn5">
+    <label>5</label><p>In list.</p>
+  </fn>
+</fn-group>
+</back>
+</article>
diff --git a/test/writer.jira b/test/writer.jira
new file mode 100644
--- /dev/null
+++ b/test/writer.jira
@@ -0,0 +1,537 @@
+This is a set of tests for pandoc. Most of them are adapted from John Gruber’s markdown test suite.
+
+----
+h1. {anchor:headers}Headers
+h2. {anchor:level-2-with-an-embedded-link}Level 2 with an [embedded link|/url]
+h3. {anchor:level-3-with-emphasis}Level 3 with _emphasis_
+h4. {anchor:level-4}Level 4
+h5. {anchor:level-5}Level 5
+h1. {anchor:level-1}Level 1
+h2. {anchor:level-2-with-emphasis}Level 2 with _emphasis_
+h3. {anchor:level-3}Level 3
+with no blank line
+
+h2. {anchor:level-2}Level 2
+with no blank line
+
+----
+h1. {anchor:paragraphs}Paragraphs
+Here’s a regular paragraph.
+
+In Markdown 1.0.0 and earlier. Version 8. This line turns into a list item. Because a hard-wrapped line in the middle of a paragraph looked like a list item.
+
+Here’s one with a bullet. * criminey.
+
+There should be a hard line break
+here.
+
+----
+h1. {anchor:block-quotes}Block Quotes
+E-mail style:
+
+bq. This is a block quote. It is pretty short.
+{quote}
+Code in a block quote:
+
+{noformat}
+sub status {
+    print "working";
+}{noformat}
+A list:
+
+# item one
+# item two
+
+Nested block quotes:
+
+bq. nested
+bq. nested{quote}
+This should not be a block quote: 2 > 1.
+
+And a following paragraph.
+
+----
+h1. {anchor:code-blocks}Code Blocks
+Code:
+
+{noformat}
+---- (should be four hyphens)
+
+sub status {
+    print "working";
+}
+
+this code block is indented by one tab{noformat}
+And:
+
+{noformat}
+    this code block is indented by two tabs
+
+These should not be escaped:  \$ \\ \> \[ \{{noformat}
+----
+h1. {anchor:lists}Lists
+h2. {anchor:unordered}Unordered
+Asterisks tight:
+
+* asterisk 1
+* asterisk 2
+* asterisk 3
+
+Asterisks loose:
+
+* asterisk 1
+* asterisk 2
+* asterisk 3
+
+Pluses tight:
+
+* Plus 1
+* Plus 2
+* Plus 3
+
+Pluses loose:
+
+* Plus 1
+* Plus 2
+* Plus 3
+
+Minuses tight:
+
+* Minus 1
+* Minus 2
+* Minus 3
+
+Minuses loose:
+
+* Minus 1
+* Minus 2
+* Minus 3
+
+h2. {anchor:ordered}Ordered
+Tight:
+
+# First
+# Second
+# Third
+
+and:
+
+# One
+# Two
+# Three
+
+Loose using tabs:
+
+# First
+# Second
+# Third
+
+and using spaces:
+
+# One
+# Two
+# Three
+
+Multiple paragraphs:
+
+# Item 1, graf one.
+Item 1. graf two. The quick brown fox jumped over the lazy dog’s back.
+# Item 2.
+# Item 3.
+
+h2. {anchor:nested}Nested
+* Tab
+** Tab
+*** Tab
+
+Here’s another:
+
+# First
+# Second:
+#* Fee
+#* Fie
+#* Foe
+# Third
+
+Same thing but with paragraphs:
+
+# First
+# Second:
+#* Fee
+#* Fie
+#* Foe
+# Third
+
+h2. {anchor:tabs-and-spaces}Tabs and spaces
+* this is a list item indented with tabs
+* this is a list item indented with spaces
+** this is an example list item indented with tabs
+** this is an example list item indented with spaces
+
+h2. {anchor:fancy-list-markers}Fancy list markers
+# begins with 2
+# and now 3
+with a continuation
+## sublist with roman numerals, starting with 4
+## more items
+### a subsublist
+### a subsublist
+
+Nesting:
+
+# Upper Alpha
+## Upper Roman.
+### Decimal start with 6
+#### Lower alpha with paren
+
+Autonumbering:
+
+# Autonumber.
+# More.
+## Nested.
+
+Should not be a list item:
+
+M.A. 2007
+
+B. Williams
+
+----
+h1. {anchor:definition-lists}Definition Lists
+Tight using spaces:
+
+* *apple*
+red fruit
+* *orange*
+orange fruit
+* *banana*
+yellow fruit
+
+Tight using tabs:
+
+* *apple*
+red fruit
+* *orange*
+orange fruit
+* *banana*
+yellow fruit
+
+Loose:
+
+* *apple*
+red fruit
+* *orange*
+orange fruit
+* *banana*
+yellow fruit
+
+Multiple blocks with italics:
+
+* *_apple_*
+red fruit
+contains seeds, crisp, pleasant to taste
+* *_orange_*
+orange fruit
+{noformat}
+{ orange code block }{noformat}
+bq. orange block quote
+
+Multiple definitions, tight:
+
+* *apple*
+red fruit
+computer
+* *orange*
+orange fruit
+bank
+
+Multiple definitions, loose:
+
+* *apple*
+red fruit
+computer
+* *orange*
+orange fruit
+bank
+
+Blank line after term, indented marker, alternate markers:
+
+* *apple*
+red fruit
+computer
+* *orange*
+orange fruit
+*# sublist
+*# sublist
+
+h1. {anchor:html-blocks}HTML Blocks
+Simple block on one line:
+
+foo
+
+And nested without indentation:
+
+foo
+
+bar
+
+Interpreted markdown in a table:
+
+This is _emphasized_
+
+And this is *strong*
+
+Here’s a simple block:
+
+foo
+
+This should be a code block, though:
+
+{noformat}
+<div>
+    foo
+</div>{noformat}
+As should this:
+
+{noformat}
+<div>foo</div>{noformat}
+Now, nested:
+
+foo
+
+This should just be an HTML comment:
+
+Multiline:
+
+Code block:
+
+{noformat}
+<!-- Comment -->{noformat}
+Just plain comment, with trailing spaces on the line:
+
+Code:
+
+{noformat}
+<hr />{noformat}
+Hr’s:
+
+----
+h1. {anchor:inline-markup}Inline Markup
+This is _emphasized_, and so _is this_.
+
+This is *strong*, and so *is this*.
+
+An _[emphasized link|/url]_.
+
+*_This is strong and em._*
+
+So is *_this_* word.
+
+*_This is strong and em._*
+
+So is *_this_* word.
+
+This is code: {{>}}, {{$}}, {{&bsol;}}, {{&bsol;$}}, {{<html>}}.
+
+-This is _strikeout_.-
+
+Superscripts: a{^}bc{^}d a{^}_hello_{^} a{^}hello there{^}.
+
+Subscripts: H{~}2{~}O, H{~}23{~}O, H{~}many of them{~}O.
+
+These should not be superscripts or subscripts, because of the unescaped spaces: a^b c^d, a~b c~d.
+
+----
+h1. {anchor:smart-quotes-ellipses-dashes}Smart quotes, ellipses, dashes
+"Hello," said the spider. "'Shelob' is my name."
+
+'A', 'B', and 'C' are letters.
+
+'Oak,' 'elm,' and 'beech' are names of trees. So is 'pine.'
+
+'He said, "I want to go."' Were you alive in the 70’s?
+
+Here is some quoted '{{code}}' and a "[quoted link|http://example.com/?foo=1&bar=2]".
+
+Some dashes: one—two — three—four — five.
+
+Dashes between numbers: 5–7, 255–66, 1987–1999.
+
+Ellipses…and…and….
+
+----
+h1. {anchor:latex}LaTeX
+* 
+* 2 + 2 = 4
+* _x_ ∈ {_}y{_}
+* _α_ ∧ {_}ω{_}
+* 223
+* _p_\-Tree
+* Here’s some display math: 
+$$\frac\{d\}\{dx\}f\(x)=\lim\_\{h\to 0\}&bsol;frac\{f(x+h)-f\(x)\}\{h\}$$
+
+* Here’s one that has a line break in it: _α_ + {_}ω{_} × {_}x{_}^2^.
+
+These shouldn’t be math:
+
+* To get the famous equation, write {{$e = mc^2$}}.
+* $22,000 is a _lot_ of money. So is $34,000. \(It worked if "lot" is emphasized.)
+* Shoes \($20) and socks \($5).
+* Escaped {{$}}: $73 _this should be emphasized_ 23$.
+
+Here’s a LaTeX table:
+
+----
+h1. {anchor:special-characters}Special Characters
+Here is some unicode:
+
+* I hat: Î
+* o umlaut: ö
+* section: §
+* set membership: ∈
+* copyright: ©
+
+AT&T has an ampersand in their name.
+
+AT&T is another way to write it.
+
+This & that.
+
+4 < 5.
+
+6 > 5.
+
+Backslash: &bsol;
+
+Backtick: `
+
+Asterisk: \*
+
+Underscore: \_
+
+Left brace: \{
+
+Right brace: \}
+
+Left bracket: \[
+
+Right bracket: \]
+
+Left paren: \(
+
+Right paren: )
+
+Greater-than: >
+
+Hash: #
+
+Period: .
+
+Bang: \!
+
+Plus: \+
+
+Minus: \-
+
+----
+h1. {anchor:links}Links
+h2. {anchor:explicit}Explicit
+Just a [URL|/url/].
+
+[URL and title|/url/].
+
+[URL and title|/url/].
+
+[URL and title|/url/].
+
+[URL and title|/url/]
+
+[URL and title|/url/]
+
+[with_underscore|/url/with_underscore]
+
+[Email link|mailto:nobody@nowhere.net]
+
+[Empty|].
+
+h2. {anchor:reference}Reference
+Foo [bar|/url/].
+
+With [embedded \[brackets\]|/url/].
+
+[b|/url/] by itself should be a link.
+
+Indented [once|/url].
+
+Indented [twice|/url].
+
+Indented [thrice|/url].
+
+This should \[not\]\[\] be a link.
+
+{noformat}
+[not]: /url{noformat}
+Foo [bar|/url/].
+
+Foo [biz|/url/].
+
+h2. {anchor:with-ampersands}With ampersands
+Here’s a [link with an ampersand in the URL|http://example.com/?foo=1&bar=2].
+
+Here’s a link with an amersand in the link text: [AT&T|http://att.com/].
+
+Here’s an [inline link|/script?foo=1&bar=2].
+
+Here’s an [inline link in pointy braces|/script?foo=1&bar=2].
+
+h2. {anchor:autolinks}Autolinks
+With an ampersand: [http://example.com/?foo=1&bar=2]
+
+* In a list?
+* [http://example.com/]
+* It should.
+
+An e-mail address: [mailto:nobody@nowhere.net]
+
+bq. Blockquoted: [http://example.com/]
+Auto-links should not occur here: {{<http://example.com/>}}
+
+{noformat}
+or here: <http://example.com/>{noformat}
+----
+h1. {anchor:images}Images
+From "Voyage dans la Lune" by Georges Melies \(1902):
+
+!lalune.jpg|title=Voyage dans la Lune, alt=lalune!
+
+Here is a movie !movie.jpg|alt=movie! icon.
+
+----
+h1. {anchor:footnotes}Footnotes
+Here is a footnote reference,[1] and another.[2] This should _not_ be a footnote reference, because it contains a space.\[\^my note\] Here is an inline note.[3]
+
+bq. Notes can go in quotes.[4]
+# And in list items.[5]
+
+This paragraph should not be part of the note, as it is not indented.
+
+
+\[1] Here is the footnote. It can go anywhere after the footnote reference. It need not be placed at the end of the document.
+
+
+\[2] Here’s the long note. This one contains multiple blocks.
+
+Subsequent blocks are indented to show that they belong to the footnote \(as with list items).
+
+{noformat}
+  { <code> }{noformat}
+If you want, you can indent every line, but you can also be lazy and just indent the first line of each block.
+
+
+\[3] This is _easier_ to type. Inline notes may contain [links|http://google.com] and {{\]}} verbatim characters, as well as \[bracketed text].
+
+
+\[4] In quote.
+
+
+\[5] In list.
diff --git a/test/writer.latex b/test/writer.latex
--- a/test/writer.latex
+++ b/test/writer.latex
@@ -1,72 +1,79 @@
-\PassOptionsToPackage{unicode=true}{hyperref} % options for packages loaded elsewhere
+% Options for packages loaded elsewhere
+\PassOptionsToPackage{unicode}{hyperref}
 \PassOptionsToPackage{hyphens}{url}
-%
-\documentclass[]{article}
-\usepackage{lmodern}
-\usepackage{amssymb,amsmath}
-\usepackage{ifxetex,ifluatex}
-\usepackage{fixltx2e} % provides \textsubscript
-\ifnum 0\ifxetex 1\fi\ifluatex 1\fi=0 % if pdftex
+\documentclass[
+]{article}
+\usepackage{xcolor}
+\usepackage{amsmath,amssymb}
+\setcounter{secnumdepth}{-\maxdimen} % remove section numbering
+\usepackage{iftex}
+\ifPDFTeX
   \usepackage[T1]{fontenc}
   \usepackage[utf8]{inputenc}
-  \usepackage{textcomp} % provides euro and other symbols
-\else % if luatex or xelatex
-  \usepackage{unicode-math}
-  \defaultfontfeatures{Ligatures=TeX,Scale=MatchLowercase}
+  \usepackage{textcomp} % provide euro and other symbols
+\else % if luatex or xetex
+  \usepackage{unicode-math} % this also loads fontspec
+  \defaultfontfeatures{Scale=MatchLowercase}
+  \defaultfontfeatures[\rmfamily]{Ligatures=TeX,Scale=1}
 \fi
-% use upquote if available, for straight quotes in verbatim environments
+\usepackage{lmodern}
+\ifPDFTeX\else
+  % xetex/luatex font selection
+\fi
+% Use upquote if available, for straight quotes in verbatim environments
 \IfFileExists{upquote.sty}{\usepackage{upquote}}{}
-% use microtype if available
-\IfFileExists{microtype.sty}{%
-\usepackage[]{microtype}
-\UseMicrotypeSet[protrusion]{basicmath} % disable protrusion for tt fonts
+\IfFileExists{microtype.sty}{% use microtype if available
+  \usepackage[]{microtype}
+  \UseMicrotypeSet[protrusion]{basicmath} % disable protrusion for tt fonts
 }{}
-\IfFileExists{parskip.sty}{%
-\usepackage{parskip}
-}{% else
-\setlength{\parindent}{0pt}
-\setlength{\parskip}{6pt plus 2pt minus 1pt}
-}
+\makeatletter
+\@ifundefined{KOMAClassName}{% if non-KOMA class
+  \IfFileExists{parskip.sty}{%
+    \usepackage{parskip}
+  }{% else
+    \setlength{\parindent}{0pt}
+    \setlength{\parskip}{6pt plus 2pt minus 1pt}}
+}{% if KOMA class
+  \KOMAoptions{parskip=half}}
+\makeatother
 \usepackage{fancyvrb}
-\usepackage{hyperref}
-\hypersetup{
-            pdftitle={Pandoc Test Suite},
-            pdfauthor={John MacFarlane; Anonymous},
-            pdfborder={0 0 0},
-            breaklinks=true}
-\urlstyle{same}  % don't use monospace font for urls
-\VerbatimFootnotes % allows verbatim text in footnotes
-\usepackage{graphicx,grffile}
+\usepackage{graphicx}
 \makeatletter
-\def\maxwidth{\ifdim\Gin@nat@width>\linewidth\linewidth\else\Gin@nat@width\fi}
-\def\maxheight{\ifdim\Gin@nat@height>\textheight\textheight\else\Gin@nat@height\fi}
+\newsavebox\pandoc@box
+\newcommand*\pandocbounded[1]{% scales image to fit in text height/width
+  \sbox\pandoc@box{#1}%
+  \Gscale@div\@tempa{\textheight}{\dimexpr\ht\pandoc@box+\dp\pandoc@box\relax}%
+  \Gscale@div\@tempb{\linewidth}{\wd\pandoc@box}%
+  \ifdim\@tempb\p@<\@tempa\p@\let\@tempa\@tempb\fi% select the smaller of both
+  \ifdim\@tempa\p@<\p@\scalebox{\@tempa}{\usebox\pandoc@box}%
+  \else\usebox{\pandoc@box}%
+  \fi%
+}
+% Set default figure placement to htbp
+\def\fps@figure{htbp}
 \makeatother
-% Scale images if necessary, so that they will not overflow the page
-% margins by default, and it is still possible to overwrite the defaults
-% using explicit options in \includegraphics[width, height, ...]{}
-\setkeys{Gin}{width=\maxwidth,height=\maxheight,keepaspectratio}
-\usepackage[normalem]{ulem}
-% avoid problems with \sout in headers with hyperref:
-\pdfstringdefDisableCommands{\renewcommand{\sout}{}}
-\setlength{\emergencystretch}{3em}  % prevent overfull lines
+\ifLuaTeX
+  \usepackage{luacolor}
+  \usepackage[soul]{lua-ul}
+\else
+  \usepackage{soul}
+\fi
+\setlength{\emergencystretch}{3em} % prevent overfull lines
 \providecommand{\tightlist}{%
   \setlength{\itemsep}{0pt}\setlength{\parskip}{0pt}}
-\setcounter{secnumdepth}{0}
-% Redefines (sub)paragraphs to behave more like sections
-\ifx\paragraph\undefined\else
-\let\oldparagraph\paragraph
-\renewcommand{\paragraph}[1]{\oldparagraph{#1}\mbox{}}
-\fi
-\ifx\subparagraph\undefined\else
-\let\oldsubparagraph\subparagraph
-\renewcommand{\subparagraph}[1]{\oldsubparagraph{#1}\mbox{}}
-\fi
-
-% set default figure placement to htbp
+\usepackage{bookmark}
+\IfFileExists{xurl.sty}{\usepackage{xurl}}{} % add URL line breaks if available
+\urlstyle{same}
+\VerbatimFootnotes % allow verbatim text in footnotes
+% fallback for those not using the hyperref driver hyperxmp:
 \makeatletter
-\def\fps@figure{htbp}
+\@ifundefined{xmpquote}{\newcommand{\xmpquote}[1]{#1}}{}
 \makeatother
-
+\hypersetup{
+  pdftitle={Pandoc Test Suite},
+  pdfauthor={John MacFarlane; Anonymous},
+  hidelinks,
+  pdfcreator={LaTeX via pandoc}}
 
 \title{Pandoc Test Suite}
 \author{John MacFarlane \and Anonymous}
@@ -78,46 +85,36 @@
 This is a set of tests for pandoc. Most of them are adapted from John Gruber's
 markdown test suite.
 
-\begin{center}\rule{0.5\linewidth}{\linethickness}\end{center}
+\begin{center}\rule{0.5\linewidth}{0.5pt}\end{center}
 
-\hypertarget{headers}{%
-\section{Headers}\label{headers}}
+\section{Headers}\label{headers}
 
-\hypertarget{level-2-with-an-embedded-link}{%
 \subsection{\texorpdfstring{Level 2 with an \href{/url}{embedded
-link}}{Level 2 with an embedded link}}\label{level-2-with-an-embedded-link}}
+link}}{Level 2 with an embedded link}}\label{level-2-with-an-embedded-link}
 
-\hypertarget{level-3-with-emphasis}{%
 \subsubsection{\texorpdfstring{Level 3 with
-\emph{emphasis}}{Level 3 with emphasis}}\label{level-3-with-emphasis}}
+\emph{emphasis}}{Level 3 with emphasis}}\label{level-3-with-emphasis}
 
-\hypertarget{level-4}{%
-\paragraph{Level 4}\label{level-4}}
+\paragraph{Level 4}\label{level-4}
 
-\hypertarget{level-5}{%
-\subparagraph{Level 5}\label{level-5}}
+\subparagraph{Level 5}\label{level-5}
 
-\hypertarget{level-1}{%
-\section{Level 1}\label{level-1}}
+\section{Level 1}\label{level-1}
 
-\hypertarget{level-2-with-emphasis}{%
 \subsection{\texorpdfstring{Level 2 with
-\emph{emphasis}}{Level 2 with emphasis}}\label{level-2-with-emphasis}}
+\emph{emphasis}}{Level 2 with emphasis}}\label{level-2-with-emphasis}
 
-\hypertarget{level-3}{%
-\subsubsection{Level 3}\label{level-3}}
+\subsubsection{Level 3}\label{level-3}
 
 with no blank line
 
-\hypertarget{level-2}{%
-\subsection{Level 2}\label{level-2}}
+\subsection{Level 2}\label{level-2}
 
 with no blank line
 
-\begin{center}\rule{0.5\linewidth}{\linethickness}\end{center}
+\begin{center}\rule{0.5\linewidth}{0.5pt}\end{center}
 
-\hypertarget{paragraphs}{%
-\section{Paragraphs}\label{paragraphs}}
+\section{Paragraphs}\label{paragraphs}
 
 Here's a regular paragraph.
 
@@ -130,10 +127,9 @@
 There should be a hard line break\\
 here.
 
-\begin{center}\rule{0.5\linewidth}{\linethickness}\end{center}
+\begin{center}\rule{0.5\linewidth}{0.5pt}\end{center}
 
-\hypertarget{block-quotes}{%
-\section{Block Quotes}\label{block-quotes}}
+\section{Block Quotes}\label{block-quotes}
 
 E-mail style:
 
@@ -176,10 +172,9 @@
 
 And a following paragraph.
 
-\begin{center}\rule{0.5\linewidth}{\linethickness}\end{center}
+\begin{center}\rule{0.5\linewidth}{0.5pt}\end{center}
 
-\hypertarget{code-blocks}{%
-\section{Code Blocks}\label{code-blocks}}
+\section{Code Blocks}\label{code-blocks}
 
 Code:
 
@@ -201,13 +196,11 @@
 These should not be escaped:  \$ \\ \> \[ \{
 \end{verbatim}
 
-\begin{center}\rule{0.5\linewidth}{\linethickness}\end{center}
+\begin{center}\rule{0.5\linewidth}{0.5pt}\end{center}
 
-\hypertarget{lists}{%
-\section{Lists}\label{lists}}
+\section{Lists}\label{lists}
 
-\hypertarget{unordered}{%
-\subsection{Unordered}\label{unordered}}
+\subsection{Unordered}\label{unordered}
 
 Asterisks tight:
 
@@ -278,8 +271,7 @@
   Minus 3
 \end{itemize}
 
-\hypertarget{ordered}{%
-\subsection{Ordered}\label{ordered}}
+\subsection{Ordered}\label{ordered}
 
 Tight:
 
@@ -345,8 +337,7 @@
   Item 3.
 \end{enumerate}
 
-\hypertarget{nested}{%
-\subsection{Nested}\label{nested}}
+\subsection{Nested}\label{nested}
 
 \begin{itemize}
 \tightlist
@@ -411,8 +402,7 @@
   Third
 \end{enumerate}
 
-\hypertarget{tabs-and-spaces}{%
-\subsection{Tabs and spaces}\label{tabs-and-spaces}}
+\subsection{Tabs and spaces}\label{tabs-and-spaces}
 
 \begin{itemize}
 \item
@@ -428,8 +418,7 @@
   \end{itemize}
 \end{itemize}
 
-\hypertarget{fancy-list-markers}{%
-\subsection{Fancy list markers}\label{fancy-list-markers}}
+\subsection{Fancy list markers}\label{fancy-list-markers}
 
 \begin{enumerate}
 \def\labelenumi{(\arabic{enumi})}
@@ -515,10 +504,9 @@
 
 B. Williams
 
-\begin{center}\rule{0.5\linewidth}{\linethickness}\end{center}
+\begin{center}\rule{0.5\linewidth}{0.5pt}\end{center}
 
-\hypertarget{definition-lists}{%
-\section{Definition Lists}\label{definition-lists}}
+\section{Definition Lists}\label{definition-lists}
 
 Tight using spaces:
 
@@ -621,8 +609,7 @@
 \end{enumerate}
 \end{description}
 
-\hypertarget{html-blocks}{%
-\section{HTML Blocks}\label{html-blocks}}
+\section{HTML Blocks}\label{html-blocks}
 
 Simple block on one line:
 
@@ -682,10 +669,9 @@
 
 Hr's:
 
-\begin{center}\rule{0.5\linewidth}{\linethickness}\end{center}
+\begin{center}\rule{0.5\linewidth}{0.5pt}\end{center}
 
-\hypertarget{inline-markup}{%
-\section{Inline Markup}\label{inline-markup}}
+\section{Inline Markup}\label{inline-markup}
 
 This is \emph{emphasized}, and so \emph{is this}.
 
@@ -704,7 +690,7 @@
 This is code: \texttt{\textgreater{}}, \texttt{\$}, \texttt{\textbackslash{}},
 \texttt{\textbackslash{}\$}, \texttt{\textless{}html\textgreater{}}.
 
-\sout{This is \emph{strikeout}.}
+\st{This is \emph{strikeout}.}
 
 Superscripts: a\textsuperscript{bc}d a\textsuperscript{\emph{hello}}
 a\textsuperscript{hello~there}.
@@ -712,13 +698,12 @@
 Subscripts: H\textsubscript{2}O, H\textsubscript{23}O,
 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.
+These should not be superscripts or subscripts, because of the unescaped spaces:
+a\^{}b c\^{}d, a\textasciitilde b c\textasciitilde d.
 
-\begin{center}\rule{0.5\linewidth}{\linethickness}\end{center}
+\begin{center}\rule{0.5\linewidth}{0.5pt}\end{center}
 
-\hypertarget{smart-quotes-ellipses-dashes}{%
-\section{Smart quotes, ellipses, dashes}\label{smart-quotes-ellipses-dashes}}
+\section{Smart quotes, ellipses, dashes}\label{smart-quotes-ellipses-dashes}
 
 ``Hello,'' said the spider. ``\,`Shelob' is my name.''
 
@@ -729,18 +714,17 @@
 `He said, ``I want to go.''\,' Were you alive in the 70's?
 
 Here is some quoted `\texttt{code}' and a
-``\href{http://example.com/?foo=1\&bar=2}{quoted link}''.
+``\href{http://example.com/?foo=1&bar=2}{quoted link}''.
 
 Some dashes: one---two --- three---four --- five.
 
 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}
+\begin{center}\rule{0.5\linewidth}{0.5pt}\end{center}
 
-\hypertarget{latex}{%
-\section{LaTeX}\label{latex}}
+\section{LaTeX}\label{latex}
 
 \begin{itemize}
 \tightlist
@@ -786,10 +770,9 @@
 Cat    & 1      \\ \hline
 \end{tabular}
 
-\begin{center}\rule{0.5\linewidth}{\linethickness}\end{center}
+\begin{center}\rule{0.5\linewidth}{0.5pt}\end{center}
 
-\hypertarget{special-characters}{%
-\section{Special Characters}\label{special-characters}}
+\section{Special Characters}\label{special-characters}
 
 Here is some unicode:
 
@@ -849,13 +832,11 @@
 
 Minus: -
 
-\begin{center}\rule{0.5\linewidth}{\linethickness}\end{center}
+\begin{center}\rule{0.5\linewidth}{0.5pt}\end{center}
 
-\hypertarget{links}{%
-\section{Links}\label{links}}
+\section{Links}\label{links}
 
-\hypertarget{explicit}{%
-\subsection{Explicit}\label{explicit}}
+\subsection{Explicit}\label{explicit}
 
 Just a \href{/url/}{URL}.
 
@@ -875,8 +856,7 @@
 
 \href{}{Empty}.
 
-\hypertarget{reference}{%
-\subsection{Reference}\label{reference}}
+\subsection{Reference}\label{reference}
 
 Foo \href{/url/}{bar}.
 
@@ -900,23 +880,20 @@
 
 Foo \href{/url/}{biz}.
 
-\hypertarget{with-ampersands}{%
-\subsection{With ampersands}\label{with-ampersands}}
+\subsection{With ampersands}\label{with-ampersands}
 
-Here's a \href{http://example.com/?foo=1\&bar=2}{link with an ampersand in the
+Here's a \href{http://example.com/?foo=1&bar=2}{link with an ampersand in the
 URL}.
 
-Here's a link with an amersand in the link text:
-\href{http://att.com/}{AT\&T}.
+Here's a link with an amersand in the link text: \href{http://att.com/}{AT\&T}.
 
-Here's an \href{/script?foo=1\&bar=2}{inline link}.
+Here's an \href{/script?foo=1&bar=2}{inline link}.
 
-Here's an \href{/script?foo=1\&bar=2}{inline link in pointy braces}.
+Here's an \href{/script?foo=1&bar=2}{inline link in pointy braces}.
 
-\hypertarget{autolinks}{%
-\subsection{Autolinks}\label{autolinks}}
+\subsection{Autolinks}\label{autolinks}
 
-With an ampersand: \url{http://example.com/?foo=1\&bar=2}
+With an ampersand: \url{http://example.com/?foo=1&bar=2}
 
 \begin{itemize}
 \tightlist
@@ -942,29 +919,28 @@
 or here: <http://example.com/>
 \end{verbatim}
 
-\begin{center}\rule{0.5\linewidth}{\linethickness}\end{center}
+\begin{center}\rule{0.5\linewidth}{0.5pt}\end{center}
 
-\hypertarget{images}{%
-\section{Images}\label{images}}
+\section{Images}\label{images}
 
 From ``Voyage dans la Lune'' by Georges Melies (1902):
 
 \begin{figure}
 \centering
-\includegraphics{lalune.jpg}
+\pandocbounded{\includegraphics[keepaspectratio,alt={lalune}]{lalune.jpg}}
 \caption{lalune}
 \end{figure}
 
-Here is a movie \includegraphics{movie.jpg} icon.
+Here is a movie
+\pandocbounded{\includegraphics[keepaspectratio,alt={movie}]{movie.jpg}} icon.
 
-\begin{center}\rule{0.5\linewidth}{\linethickness}\end{center}
+\begin{center}\rule{0.5\linewidth}{0.5pt}\end{center}
 
-\hypertarget{footnotes}{%
-\section{Footnotes}\label{footnotes}}
+\section{Footnotes}\label{footnotes}
 
-Here is a footnote reference,\footnote{Here is the footnote. It can go
-  anywhere after the footnote reference. It need not be placed at the end of
-  the document.} and another.\footnote{Here's the long note. This one contains
+Here is a footnote reference,\footnote{Here is the footnote. It can go anywhere
+  after the footnote reference. It need not be placed at the end of the
+  document.} and another.\footnote{Here's the long note. This one contains
   multiple blocks.
 
   Subsequent blocks are indented to show that they belong to the footnote (as
@@ -978,8 +954,8 @@
   indent the first line of each block.} This should \emph{not} be a footnote
 reference, because it contains a space.{[}\^{}my note{]} Here is an inline
 note.\footnote{This is \emph{easier} to type. Inline notes may contain
-  \href{http://google.com}{links} and \texttt{{]}} verbatim characters, as
-  well as {[}bracketed text{]}.}
+  \href{http://google.com}{links} and \texttt{{]}} verbatim characters, as well
+  as {[}bracketed text{]}.}
 
 \begin{quote}
 Notes can go in quotes.\footnote{In quote.}
diff --git a/test/writer.man b/test/writer.man
--- a/test/writer.man
+++ b/test/writer.man
@@ -1,28 +1,24 @@
-.TH "Pandoc Test Suite" "" "July 17, 2006" "" ""
-.hy
+.TH "Pandoc Test Suite" "" "July 17, 2006" ""
 .PP
 This is a set of tests for pandoc.
-Most of them are adapted from John Gruber's markdown test suite.
+Most of them are adapted from John Gruber\(cqs markdown test suite.
 .PP
    *   *   *   *   *
 .SH Headers
-.SS Level 2 with an embedded link (/url)
-.SS Level 3 with \f[I]emphasis\f[]
+.SS Level 2 with an embedded link
+.SS Level 3 with \f[I]emphasis\f[R]
 .SS Level 4
 .SS Level 5
 .SH Level 1
-.SS Level 2 with \f[I]emphasis\f[]
+.SS Level 2 with \f[I]emphasis\f[R]
 .SS Level 3
-.PP
 with no blank line
 .SS Level 2
-.PP
 with no blank line
 .PP
    *   *   *   *   *
 .SH Paragraphs
-.PP
-Here's a regular paragraph.
+Here\(cqs a regular paragraph.
 .PP
 In Markdown 1.0.0 and earlier.
 Version 8.
@@ -30,7 +26,7 @@
 Because a hard\-wrapped line in the middle of a paragraph looked like a list
 item.
 .PP
-Here's one with a bullet.
+Here\(cqs one with a bullet.
 * criminey.
 .PP
 There should be a hard line break
@@ -41,7 +37,6 @@
 .PP
    *   *   *   *   *
 .SH Block Quotes
-.PP
 E\-mail style:
 .RS
 .PP
@@ -52,13 +47,11 @@
 .PP
 Code in a block quote:
 .IP
-.nf
-\f[C]
-sub\ status\ {
-\ \ \ \ print\ "working";
+.EX
+sub status {
+    print \(dqworking\(dq;
 }
-\f[]
-.fi
+.EE
 .PP
 A list:
 .IP "1." 3
@@ -83,84 +76,77 @@
 .PP
    *   *   *   *   *
 .SH Code Blocks
-.PP
 Code:
 .IP
-.nf
-\f[C]
-\-\-\-\-\ (should\ be\ four\ hyphens)
+.EX
+\-\-\-\- (should be four hyphens)
 
-sub\ status\ {
-\ \ \ \ print\ "working";
+sub status {
+    print \(dqworking\(dq;
 }
 
-this\ code\ block\ is\ indented\ by\ one\ tab
-\f[]
-.fi
+this code block is indented by one tab
+.EE
 .PP
 And:
 .IP
-.nf
-\f[C]
-\ \ \ \ this\ code\ block\ is\ indented\ by\ two\ tabs
+.EX
+    this code block is indented by two tabs
 
-These\ should\ not\ be\ escaped:\ \ \\$\ \\\\\ \\>\ \\[\ \\{
-\f[]
-.fi
+These should not be escaped:  \(rs$ \(rs\(rs \(rs> \(rs[ \(rs{
+.EE
 .PP
    *   *   *   *   *
 .SH Lists
 .SS Unordered
-.PP
 Asterisks tight:
-.IP \[bu] 2
+.IP \(bu 2
 asterisk 1
-.IP \[bu] 2
+.IP \(bu 2
 asterisk 2
-.IP \[bu] 2
+.IP \(bu 2
 asterisk 3
 .PP
 Asterisks loose:
-.IP \[bu] 2
+.IP \(bu 2
 asterisk 1
-.IP \[bu] 2
+.IP \(bu 2
 asterisk 2
-.IP \[bu] 2
+.IP \(bu 2
 asterisk 3
 .PP
 Pluses tight:
-.IP \[bu] 2
+.IP \(bu 2
 Plus 1
-.IP \[bu] 2
+.IP \(bu 2
 Plus 2
-.IP \[bu] 2
+.IP \(bu 2
 Plus 3
 .PP
 Pluses loose:
-.IP \[bu] 2
+.IP \(bu 2
 Plus 1
-.IP \[bu] 2
+.IP \(bu 2
 Plus 2
-.IP \[bu] 2
+.IP \(bu 2
 Plus 3
 .PP
 Minuses tight:
-.IP \[bu] 2
+.IP \(bu 2
 Minus 1
-.IP \[bu] 2
+.IP \(bu 2
 Minus 2
-.IP \[bu] 2
+.IP \(bu 2
 Minus 3
 .PP
 Minuses loose:
-.IP \[bu] 2
+.IP \(bu 2
 Minus 1
-.IP \[bu] 2
+.IP \(bu 2
 Minus 2
-.IP \[bu] 2
+.IP \(bu 2
 Minus 3
 .SS Ordered
-.PP
 Tight:
 .IP "1." 3
 First
@@ -200,35 +186,35 @@
 .PP
 Item 1.
 graf two.
-The quick brown fox jumped over the lazy dog's back.
+The quick brown fox jumped over the lazy dog\(cqs back.
 .RE
 .IP "2." 3
 Item 2.
 .IP "3." 3
 Item 3.
 .SS Nested
-.IP \[bu] 2
+.IP \(bu 2
 Tab
 .RS 2
-.IP \[bu] 2
+.IP \(bu 2
 Tab
 .RS 2
-.IP \[bu] 2
+.IP \(bu 2
 Tab
 .RE
 .RE
 .PP
-Here's another:
+Here\(cqs another:
 .IP "1." 3
 First
 .IP "2." 3
 Second:
 .RS 4
-.IP \[bu] 2
+.IP \(bu 2
 Fee
-.IP \[bu] 2
+.IP \(bu 2
 Fie
-.IP \[bu] 2
+.IP \(bu 2
 Foe
 .RE
 .IP "3." 3
@@ -240,24 +226,24 @@
 .IP "2." 3
 Second:
 .RS 4
-.IP \[bu] 2
+.IP \(bu 2
 Fee
-.IP \[bu] 2
+.IP \(bu 2
 Fie
-.IP \[bu] 2
+.IP \(bu 2
 Foe
 .RE
 .IP "3." 3
 Third
 .SS Tabs and spaces
-.IP \[bu] 2
+.IP \(bu 2
 this is a list item indented with tabs
-.IP \[bu] 2
+.IP \(bu 2
 this is a list item indented with spaces
 .RS 2
-.IP \[bu] 2
+.IP \(bu 2
 this is an example list item indented with tabs
-.IP \[bu] 2
+.IP \(bu 2
 this is an example list item indented with spaces
 .RE
 .SS Fancy list markers
@@ -310,81 +296,59 @@
 .PP
 M.A.\ 2007
 .PP
-B.
-Williams
+B. Williams
 .PP
    *   *   *   *   *
 .SH Definition Lists
-.PP
 Tight using spaces:
 .TP
-.B apple
+apple
 red fruit
-.RS
-.RE
 .TP
-.B orange
+orange
 orange fruit
-.RS
-.RE
 .TP
-.B banana
+banana
 yellow fruit
-.RS
-.RE
 .PP
 Tight using tabs:
 .TP
-.B apple
+apple
 red fruit
-.RS
-.RE
 .TP
-.B orange
+orange
 orange fruit
-.RS
-.RE
 .TP
-.B banana
+banana
 yellow fruit
-.RS
-.RE
 .PP
 Loose:
 .TP
-.B apple
+apple
 red fruit
-.RS
-.RE
 .TP
-.B orange
+orange
 orange fruit
-.RS
-.RE
 .TP
-.B banana
+banana
 yellow fruit
-.RS
-.RE
 .PP
 Multiple blocks with italics:
 .TP
-.B \f[I]apple\f[]
+\f[I]apple\f[R]
 red fruit
 .RS
 .PP
 contains seeds, crisp, pleasant to taste
 .RE
 .TP
-.B \f[I]orange\f[]
+\f[I]orange\f[R]
 orange fruit
 .RS
 .IP
-.nf
-\f[C]
-{\ orange\ code\ block\ }
-\f[]
-.fi
+.EX
+{ orange code block }
+.EE
 .RS
 .PP
 orange block quote
@@ -393,51 +357,44 @@
 .PP
 Multiple definitions, tight:
 .TP
-.B apple
+apple
 red fruit
 .RS
-.RE
 computer
-.RS
 .RE
 .TP
-.B orange
+orange
 orange fruit
 .RS
-.RE
 bank
-.RS
 .RE
 .PP
 Multiple definitions, loose:
 .TP
-.B apple
+apple
 red fruit
 .RS
-.RE
+.PP
 computer
-.RS
 .RE
 .TP
-.B orange
+orange
 orange fruit
 .RS
-.RE
+.PP
 bank
-.RS
 .RE
 .PP
 Blank line after term, indented marker, alternate markers:
 .TP
-.B apple
+apple
 red fruit
 .RS
-.RE
+.PP
 computer
-.RS
 .RE
 .TP
-.B orange
+orange
 orange fruit
 .RS
 .IP "1." 3
@@ -446,7 +403,6 @@
 sublist
 .RE
 .SH HTML Blocks
-.PP
 Simple block on one line:
 foo
 .PP
@@ -456,30 +412,26 @@
 bar
 .PP
 Interpreted markdown in a table:
-This is \f[I]emphasized\f[]
-And this is \f[B]strong\f[]
+This is \f[I]emphasized\f[R]
+And this is \f[B]strong\f[R]
 .PP
-Here's a simple block:
+Here\(cqs a simple block:
 .PP
 foo
 .PP
 This should be a code block, though:
 .IP
-.nf
-\f[C]
+.EX
 <div>
-\ \ \ \ foo
+    foo
 </div>
-\f[]
-.fi
+.EE
 .PP
 As should this:
 .IP
-.nf
-\f[C]
+.EX
 <div>foo</div>
-\f[]
-.fi
+.EE
 .PP
 Now, nested:
 foo
@@ -490,124 +442,120 @@
 .PP
 Code block:
 .IP
-.nf
-\f[C]
-<!\-\-\ Comment\ \-\->
-\f[]
-.fi
+.EX
+<!\-\- Comment \-\->
+.EE
 .PP
 Just plain comment, with trailing spaces on the line:
 .PP
 Code:
 .IP
-.nf
-\f[C]
-<hr\ />
-\f[]
-.fi
+.EX
+<hr />
+.EE
 .PP
-Hr's:
+Hr\(cqs:
 .PP
    *   *   *   *   *
 .SH Inline Markup
-.PP
-This is \f[I]emphasized\f[], and so \f[I]is this\f[].
+This is \f[I]emphasized\f[R], and so \f[I]is this\f[R].
 .PP
-This is \f[B]strong\f[], and so \f[B]is this\f[].
+This is \f[B]strong\f[R], and so \f[B]is this\f[R].
 .PP
-An \f[I]emphasized link (/url)\f[].
+An \f[I]emphasized link\f[R].
 .PP
-\f[B]\f[BI]This is strong and em.\f[B]\f[]
+\f[B]\f[BI]This is strong and em.\f[B]\f[R]
 .PP
-So is \f[B]\f[BI]this\f[B]\f[] word.
+So is \f[B]\f[BI]this\f[B]\f[R] word.
 .PP
-\f[B]\f[BI]This is strong and em.\f[B]\f[]
+\f[B]\f[BI]This is strong and em.\f[B]\f[R]
 .PP
-So is \f[B]\f[BI]this\f[B]\f[] word.
+So is \f[B]\f[BI]this\f[B]\f[R] word.
 .PP
-This is code: \f[C]>\f[], \f[C]$\f[], \f[C]\\\f[], \f[C]\\$\f[],
-\f[C]<html>\f[].
+This is code: \f[CR]>\f[R], \f[CR]$\f[R], \f[CR]\(rs\f[R], \f[CR]\(rs$\f[R],
+\f[CR]<html>\f[R].
 .PP
-[STRIKEOUT:This is \f[I]strikeout\f[].]
+[STRIKEOUT:This is \f[I]strikeout\f[R].]
 .PP
-Superscripts: a^bc^d a^\f[I]hello\f[]^ a^hello\ there^.
+Superscripts: a^bc^d a^\f[I]hello\f[R]^ a^hello\ there^.
 .PP
 Subscripts: H~2~O, H~23~O, H~many\ of\ them~O.
 .PP
-These should not be superscripts or subscripts, because of the unescaped
-spaces: a^b c^d, a~b c~d.
+These should not be superscripts or subscripts, because of the unescaped spaces:
+a\(hab c\(had, a\(tib c\(tid.
 .PP
    *   *   *   *   *
 .SH Smart quotes, ellipses, dashes
-.PP
-\[lq]Hello,\[rq] said the spider.
-\[lq]`Shelob' is my name.\[rq]
+\(lqHello,\(rq said the spider.
+\(lq`Shelob' is my name.\(rq
 .PP
 `A', `B', and `C' are letters.
 .PP
 `Oak,' `elm,' and `beech' are names of trees.
 So is `pine.'
 .PP
-`He said, \[lq]I want to go.\[rq]' Were you alive in the 70's?
+`He said, \(lqI want to go.\(rq' Were you alive in the 70\(cqs?
 .PP
-Here is some quoted `\f[C]code\f[]' and a \[lq]quoted
-link (http://example.com/?foo=1&bar=2)\[rq].
+Here is some quoted `\f[CR]code\f[R]' and a \(lq\c
+.UR http://example.com/?foo=1&bar=2
+quoted link
+.UE \c
+\(rq.
 .PP
-Some dashes: one\[em]two \[em] three\[em]four \[em] five.
+Some dashes: one\(emtwo \(em three\(emfour \(em five.
 .PP
-Dashes between numbers: 5\[en]7, 255\[en]66, 1987\[en]1999.
+Dashes between numbers: 5\(en7, 255\(en66, 1987\(en1999.
 .PP
 Ellipses\&...and\&...and\&....
 .PP
    *   *   *   *   *
 .SH LaTeX
-.IP \[bu] 2
-.IP \[bu] 2
+.IP \(bu 2
+.IP \(bu 2
 2 + 2 = 4
-.IP \[bu] 2
-\f[I]x\f[] ∈ \f[I]y\f[]
-.IP \[bu] 2
-\f[I]α\f[] ∧ \f[I]ω\f[]
-.IP \[bu] 2
+.IP \(bu 2
+\f[I]x\f[R] ∈ \f[I]y\f[R]
+.IP \(bu 2
+\f[I]α\f[R] ∧ \f[I]ω\f[R]
+.IP \(bu 2
 223
-.IP \[bu] 2
-\f[I]p\f[]\-Tree
-.IP \[bu] 2
-Here's some display math:
+.IP \(bu 2
+\f[I]p\f[R]\-Tree
+.IP \(bu 2
+Here\(cqs some display math:
 .RS
-$$\\frac{d}{dx}f(x)=\\lim_{h\\to 0}\\frac{f(x+h)\-f(x)}{h}$$
+$$\(rsfrac{d}{dx}f(x)=\(rslim_{h\(rsto 0}\(rsfrac{f(x+h)\-f(x)}{h}$$
 .RE
-.IP \[bu] 2
-Here's one that has a line break in it:
-\f[I]α\f[] + \f[I]ω\f[] × \f[I]x\f[]^2^.
+.IP \(bu 2
+Here\(cqs one that has a line break in it:
+\f[I]α\f[R] + \f[I]ω\f[R] × \f[I]x\f[R]^2^.
 .PP
-These shouldn't be math:
-.IP \[bu] 2
-To get the famous equation, write \f[C]$e\ =\ mc^2$\f[].
-.IP \[bu] 2
-$22,000 is a \f[I]lot\f[] of money.
+These shouldn\(cqt be math:
+.IP \(bu 2
+To get the famous equation, write \f[CR]$e = mc\(ha2$\f[R].
+.IP \(bu 2
+$22,000 is a \f[I]lot\f[R] of money.
 So is $34,000.
-(It worked if \[lq]lot\[rq] is emphasized.)
-.IP \[bu] 2
+(It worked if \(lqlot\(rq is emphasized.)
+.IP \(bu 2
 Shoes ($20) and socks ($5).
-.IP \[bu] 2
-Escaped \f[C]$\f[]: $73 \f[I]this should be emphasized\f[] 23$.
+.IP \(bu 2
+Escaped \f[CR]$\f[R]: $73 \f[I]this should be emphasized\f[R] 23$.
 .PP
-Here's a LaTeX table:
+Here\(cqs a LaTeX table:
 .PP
    *   *   *   *   *
 .SH Special Characters
-.PP
 Here is some unicode:
-.IP \[bu] 2
+.IP \(bu 2
 I hat: Î
-.IP \[bu] 2
+.IP \(bu 2
 o umlaut: ö
-.IP \[bu] 2
+.IP \(bu 2
 section: §
-.IP \[bu] 2
+.IP \(bu 2
 set membership: ∈
-.IP \[bu] 2
+.IP \(bu 2
 copyright: ©
 .PP
 AT&T has an ampersand in their name.
@@ -620,9 +568,9 @@
 .PP
 6 > 5.
 .PP
-Backslash: \\
+Backslash: \(rs
 .PP
-Backtick: `
+Backtick: \(ga
 .PP
 Asterisk: *
 .PP
@@ -655,96 +603,105 @@
    *   *   *   *   *
 .SH Links
 .SS Explicit
-.PP
-Just a URL (/url/).
+Just a URL.
 .PP
-URL and title (/url/).
+URL and title.
 .PP
-URL and title (/url/).
+URL and title.
 .PP
-URL and title (/url/).
+URL and title.
 .PP
-URL and title (/url/)
+URL and title
 .PP
-URL and title (/url/)
+URL and title
 .PP
-with_underscore (/url/with_underscore)
+with_underscore
 .PP
-Email link (mailto:nobody@nowhere.net)
+\c
+.MT nobody@nowhere.net
+Email link
+.ME \c
 .PP
-Empty ().
+Empty.
 .SS Reference
-.PP
-Foo bar (/url/).
+Foo bar.
 .PP
-With embedded [brackets] (/url/).
+With embedded [brackets].
 .PP
-b (/url/) by itself should be a link.
+b by itself should be a link.
 .PP
-Indented once (/url).
+Indented once.
 .PP
-Indented twice (/url).
+Indented twice.
 .PP
-Indented thrice (/url).
+Indented thrice.
 .PP
 This should [not][] be a link.
 .IP
-.nf
-\f[C]
-[not]:\ /url
-\f[]
-.fi
+.EX
+[not]: /url
+.EE
 .PP
-Foo bar (/url/).
+Foo bar.
 .PP
-Foo biz (/url/).
+Foo biz.
 .SS With ampersands
-.PP
-Here's a link with an ampersand in the URL (http://example.com/?foo=1&bar=2).
+Here\(cqs a \c
+.UR http://example.com/?foo=1&bar=2
+link with an ampersand in the URL
+.UE \c
+\&.
 .PP
-Here's a link with an amersand in the link text: AT&T (http://att.com/).
+Here\(cqs a link with an amersand in the link text: \c
+.UR http://att.com/
+AT&T
+.UE \c
+\&.
 .PP
-Here's an inline link (/script?foo=1&bar=2).
+Here\(cqs an inline link.
 .PP
-Here's an inline link in pointy braces (/script?foo=1&bar=2).
+Here\(cqs an inline link in pointy braces.
 .SS Autolinks
-.PP
-With an ampersand: <http://example.com/?foo=1&bar=2>
-.IP \[bu] 2
+With an ampersand: \c
+.UR http://example.com/?foo=1&bar=2
+.UE \c
+.IP \(bu 2
 In a list?
-.IP \[bu] 2
-<http://example.com/>
-.IP \[bu] 2
+.IP \(bu 2
+\c
+.UR http://example.com/
+.UE \c
+.IP \(bu 2
 It should.
 .PP
-An e\-mail address: <nobody@nowhere.net>
+An e\-mail address: \c
+.MT nobody@nowhere.net
+.ME \c
 .RS
 .PP
-Blockquoted: <http://example.com/>
+Blockquoted: \c
+.UR http://example.com/
+.UE \c
 .RE
 .PP
-Auto\-links should not occur here: \f[C]<http://example.com/>\f[]
+Auto\-links should not occur here: \f[CR]<http://example.com/>\f[R]
 .IP
-.nf
-\f[C]
-or\ here:\ <http://example.com/>
-\f[]
-.fi
+.EX
+or here: <http://example.com/>
+.EE
 .PP
    *   *   *   *   *
 .SH Images
-.PP
-From \[lq]Voyage dans la Lune\[rq] by Georges Melies (1902):
-.PP
-[IMAGE: lalune (lalune.jpg)]
+From \(lqVoyage dans la Lune\(rq by Georges Melies (1902):
+[IMAGE: lalune]
+lalune
 .PP
-Here is a movie [IMAGE: movie (movie.jpg)] icon.
+Here is a movie [IMAGE: movie] icon.
 .PP
    *   *   *   *   *
 .SH Footnotes
-.PP
-Here is a footnote reference,[1] and another.[2] This should \f[I]not\f[] be a
-footnote reference, because it contains a space.[^my note] Here is an inline
+Here is a footnote reference,[1] and another.[2] This should \f[I]not\f[R] be a
+footnote reference, because it contains a space.[\(hamy note] Here is an inline
 note.[3]
 .RS
 .PP
@@ -762,25 +719,26 @@
 It need not be placed at the end of the document.
 .SS [2]
 .PP
-Here's the long note.
+Here\(cqs the long note.
 This one contains multiple blocks.
 .PP
-Subsequent blocks are indented to show that they belong to the footnote (as
-with list items).
+Subsequent blocks are indented to show that they belong to the footnote (as with
+list items).
 .IP
-.nf
-\f[C]
-\ \ {\ <code>\ }
-\f[]
-.fi
+.EX
+  { <code> }
+.EE
 .PP
-If you want, you can indent every line, but you can also be lazy and just
-indent the first line of each block.
+If you want, you can indent every line, but you can also be lazy and just indent
+the first line of each block.
 .SS [3]
 .PP
-This is \f[I]easier\f[] to type.
-Inline notes may contain links (http://google.com) and \f[C]]\f[] verbatim
-characters, as well as [bracketed text].
+This is \f[I]easier\f[R] to type.
+Inline notes may contain \c
+.UR http://google.com
+links
+.UE \c
+\ and \f[CR]]\f[R] verbatim characters, as well as [bracketed text].
 .SS [4]
 .PP
 In quote.
diff --git a/test/writer.markdown b/test/writer.markdown
--- a/test/writer.markdown
+++ b/test/writer.markdown
@@ -2,20 +2,18 @@
 author:
 - John MacFarlane
 - Anonymous
-date: 'July 17, 2006'
+date: July 17, 2006
 title: Pandoc Test Suite
 ---
 
 This is a set of tests for pandoc. Most of them are adapted from John Gruber's
 markdown test suite.
 
-------------------------------------------------------------------------------
+--------------------------------------------------------------------------------
 
-Headers
-=======
+# Headers
 
-Level 2 with an [embedded link](/url)
--------------------------------------
+## Level 2 with an [embedded link](/url)
 
 ### Level 3 with *emphasis*
 
@@ -23,25 +21,21 @@
 
 ##### Level 5
 
-Level 1
-=======
+# Level 1
 
-Level 2 with *emphasis*
------------------------
+## Level 2 with *emphasis*
 
 ### Level 3
 
 with no blank line
 
-Level 2
--------
+## Level 2
 
 with no blank line
 
-------------------------------------------------------------------------------
+--------------------------------------------------------------------------------
 
-Paragraphs
-==========
+# Paragraphs
 
 Here's a regular paragraph.
 
@@ -54,10 +48,9 @@
 There should be a hard line break\
 here.
 
-------------------------------------------------------------------------------
+--------------------------------------------------------------------------------
 
-Block Quotes
-============
+# Block Quotes
 
 E-mail style:
 
@@ -84,10 +77,9 @@
 
 And a following paragraph.
 
-------------------------------------------------------------------------------
+--------------------------------------------------------------------------------
 
-Code Blocks
-===========
+# Code Blocks
 
 Code:
 
@@ -105,58 +97,55 @@
 
     These should not be escaped:  \$ \\ \> \[ \{
 
-------------------------------------------------------------------------------
+--------------------------------------------------------------------------------
 
-Lists
-=====
+# Lists
 
-Unordered
----------
+## Unordered
 
 Asterisks tight:
 
--   asterisk 1
--   asterisk 2
--   asterisk 3
+- asterisk 1
+- asterisk 2
+- asterisk 3
 
 Asterisks loose:
 
--   asterisk 1
+- asterisk 1
 
--   asterisk 2
+- asterisk 2
 
--   asterisk 3
+- asterisk 3
 
 Pluses tight:
 
--   Plus 1
--   Plus 2
--   Plus 3
+- Plus 1
+- Plus 2
+- Plus 3
 
 Pluses loose:
 
--   Plus 1
+- Plus 1
 
--   Plus 2
+- Plus 2
 
--   Plus 3
+- Plus 3
 
 Minuses tight:
 
--   Minus 1
--   Minus 2
--   Minus 3
+- Minus 1
+- Minus 2
+- Minus 3
 
 Minuses loose:
 
--   Minus 1
+- Minus 1
 
--   Minus 2
+- Minus 2
 
--   Minus 3
+- Minus 3
 
-Ordered
--------
+## Ordered
 
 Tight:
 
@@ -196,20 +185,19 @@
 
 3.  Item 3.
 
-Nested
-------
+## Nested
 
--   Tab
-    -   Tab
-        -   Tab
+- Tab
+  - Tab
+    - Tab
 
 Here's another:
 
 1.  First
 2.  Second:
-    -   Fee
-    -   Fie
-    -   Foe
+    - Fee
+    - Fie
+    - Foe
 3.  Third
 
 Same thing but with paragraphs:
@@ -218,27 +206,26 @@
 
 2.  Second:
 
-    -   Fee
-    -   Fie
-    -   Foe
+    - Fee
+    - Fie
+    - Foe
 
 3.  Third
 
-Tabs and spaces
----------------
+## Tabs and spaces
 
--   this is a list item indented with tabs
+- this is a list item indented with tabs
 
--   this is a list item indented with spaces
+- this is a list item indented with spaces
 
-    -   this is an example list item indented with tabs
+  - this is an example list item indented with tabs
 
-    -   this is an example list item indented with spaces
+  - this is an example list item indented with spaces
 
-Fancy list markers
-------------------
+## Fancy list markers
 
 (2) begins with 2
+
 (3) and now 3
 
     with a continuation
@@ -267,134 +254,122 @@
 
 B. Williams
 
-------------------------------------------------------------------------------
+--------------------------------------------------------------------------------
 
-Definition Lists
-================
+# Definition Lists
 
 Tight using spaces:
 
 apple
-:   red fruit
+: red fruit
 
 orange
-:   orange fruit
+: orange fruit
 
 banana
-:   yellow fruit
+: yellow fruit
 
 Tight using tabs:
 
 apple
-:   red fruit
+: red fruit
 
 orange
-:   orange fruit
+: orange fruit
 
 banana
-:   yellow fruit
+: yellow fruit
 
 Loose:
 
 apple
 
-:   red fruit
+: red fruit
 
 orange
 
-:   orange fruit
+: orange fruit
 
 banana
 
-:   yellow fruit
+: yellow fruit
 
 Multiple blocks with italics:
 
 *apple*
 
-:   red fruit
+: red fruit
 
-    contains seeds, crisp, pleasant to taste
+  contains seeds, crisp, pleasant to taste
 
 *orange*
 
-:   orange fruit
+: orange fruit
 
-        { orange code block }
+      { orange code block }
 
-    > orange block quote
+  > orange block quote
 
 Multiple definitions, tight:
 
 apple
-:   red fruit
-:   computer
+: red fruit
+: computer
 
 orange
-:   orange fruit
-:   bank
+: orange fruit
+: bank
 
 Multiple definitions, loose:
 
 apple
 
-:   red fruit
+: red fruit
 
-:   computer
+: computer
 
 orange
 
-:   orange fruit
+: orange fruit
 
-:   bank
+: bank
 
 Blank line after term, indented marker, alternate markers:
 
 apple
 
-:   red fruit
+: red fruit
 
-:   computer
+: computer
 
 orange
 
-:   orange fruit
+: orange fruit
 
-    1.  sublist
-    2.  sublist
+  1.  sublist
+  2.  sublist
 
-HTML Blocks
-===========
+# HTML Blocks
 
 Simple block on one line:
 
-<div>
-
+::: {}
 foo
-
-</div>
+:::
 
 And nested without indentation:
 
-<div>
-
-<div>
-
-<div>
-
+:::::: {}
+:::: {}
+::: {}
 foo
-
-</div>
-
-</div>
-
-<div>
+:::
+::::
 
+::: {}
 bar
-
-</div>
-
-</div>
+:::
+::::::
 
 Interpreted markdown in a table:
 
@@ -409,13 +384,12 @@
 </tr>
 </table>
 <script type="text/javascript">document.write('This *should not* be interpreted as markdown');</script>
-Here's a simple block:
 
-<div>
+Here's a simple block:
 
+::: {}
 foo
-
-</div>
+:::
 
 This should be a code block, though:
 
@@ -429,23 +403,18 @@
 
 Now, nested:
 
-<div>
-
-<div>
-
-<div>
-
+::::: {}
+:::: {}
+::: {}
 foo
-
-</div>
-
-</div>
-
-</div>
+:::
+::::
+:::::
 
 This should just be an HTML comment:
 
 <!-- Comment -->
+
 Multiline:
 
 <!--
@@ -455,6 +424,7 @@
 <!--
     This is another comment.
 -->
+
 Code block:
 
     <!-- Comment -->
@@ -462,6 +432,7 @@
 Just plain comment, with trailing spaces on the line:
 
 <!-- foo -->
+
 Code:
 
     <hr />
@@ -478,10 +449,9 @@
 <hr class="foo" id="bar" />
 <hr class="foo" id="bar">
 
-------------------------------------------------------------------------------
+--------------------------------------------------------------------------------
 
-Inline Markup
-=============
+# Inline Markup
 
 This is *emphasized*, and so *is this*.
 
@@ -505,13 +475,12 @@
 
 Subscripts: H~2~O, H~23~O, H~many of them~O.
 
-These should not be superscripts or subscripts, because of the unescaped
-spaces: a\^b c\^d, a\~b c\~d.
+These should not be superscripts or subscripts, because of the unescaped spaces:
+a\^b c\^d, a\~b c\~d.
 
-------------------------------------------------------------------------------
+--------------------------------------------------------------------------------
 
-Smart quotes, ellipses, dashes
-==============================
+# Smart quotes, ellipses, dashes
 
 "Hello," said the spider. "'Shelob' is my name."
 
@@ -530,28 +499,27 @@
 
 Ellipses...and...and....
 
-------------------------------------------------------------------------------
+--------------------------------------------------------------------------------
 
-LaTeX
-=====
+# LaTeX
 
--   \cite[22-23]{smith.1899}
--   $2+2=4$
--   $x \in y$
--   $\alpha \wedge \omega$
--   $223$
--   $p$-Tree
--   Here's some display math:
-    $$\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: $\alpha + \omega \times x^2$.
+- `\cite[22-23]{smith.1899}`{=tex}
+- $2+2=4$
+- $x \in y$
+- $\alpha \wedge \omega$
+- $223$
+- $p$-Tree
+- Here's some display math:
+  $$\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: $\alpha + \omega \times x^2$.
 
 These shouldn't be math:
 
--   To get the famous equation, write `$e = mc^2$`.
--   \$22,000 is a *lot* of money. So is \$34,000. (It worked if "lot" is
-    emphasized.)
--   Shoes (\$20) and socks (\$5).
--   Escaped `$`: \$73 *this should be emphasized* 23\$.
+- To get the famous equation, write `$e = mc^2$`.
+- \$22,000 is a *lot* of money. So is \$34,000. (It worked if "lot" is
+  emphasized.)
+- Shoes (\$20) and socks (\$5).
+- Escaped `$`: \$73 *this should be emphasized* 23\$.
 
 Here's a LaTeX table:
 
@@ -561,18 +529,17 @@
 Cat    & 1      \\ \hline
 \end{tabular}
 
-------------------------------------------------------------------------------
+--------------------------------------------------------------------------------
 
-Special Characters
-==================
+# Special Characters
 
 Here is some unicode:
 
--   I hat: Î
--   o umlaut: ö
--   section: §
--   set membership: ∈
--   copyright: ©
+- I hat: Î
+- o umlaut: ö
+- section: §
+- set membership: ∈
+- copyright: ©
 
 AT&T has an ampersand in their name.
 
@@ -616,13 +583,11 @@
 
 Minus: -
 
-------------------------------------------------------------------------------
+--------------------------------------------------------------------------------
 
-Links
-=====
+# Links
 
-Explicit
---------
+## Explicit
 
 Just a [URL](/url/).
 
@@ -636,14 +601,13 @@
 
 [URL and title](/url/ "title with single quotes")
 
-[with\_underscore](/url/with_underscore)
+[with_underscore](/url/with_underscore)
 
 [Email link](mailto:nobody@nowhere.net)
 
 [Empty]().
 
-Reference
----------
+## Reference
 
 Foo [bar](/url/).
 
@@ -665,26 +629,23 @@
 
 Foo [biz](/url/ "Title with "quote" inside").
 
-With ampersands
----------------
+## With ampersands
 
 Here's a [link with an ampersand in the URL](http://example.com/?foo=1&bar=2).
 
-Here's a link with an amersand in the link text:
-[AT&T](http://att.com/ "AT&T").
+Here's a link with an amersand in the link text: [AT&T](http://att.com/ "AT&T").
 
 Here's an [inline link](/script?foo=1&bar=2).
 
 Here's an [inline link in pointy braces](/script?foo=1&bar=2).
 
-Autolinks
----------
+## Autolinks
 
 With an ampersand: <http://example.com/?foo=1&bar=2>
 
--   In a list?
--   <http://example.com/>
--   It should.
+- In a list?
+- <http://example.com/>
+- It should.
 
 An e-mail address: <nobody@nowhere.net>
 
@@ -694,10 +655,9 @@
 
     or here: <http://example.com/>
 
-------------------------------------------------------------------------------
+--------------------------------------------------------------------------------
 
-Images
-======
+# Images
 
 From "Voyage dans la Lune" by Georges Melies (1902):
 
@@ -705,14 +665,13 @@
 
 Here is a movie ![movie](movie.jpg) icon.
 
-------------------------------------------------------------------------------
+--------------------------------------------------------------------------------
 
-Footnotes
-=========
+# Footnotes
 
 Here is a footnote reference,[^1] and another.[^2] This should *not* be a
-footnote reference, because it contains a space.\[\^my note\] Here is an
-inline note.[^3]
+footnote reference, because it contains a space.\[\^my note\] Here is an inline
+note.[^3]
 
 > Notes can go in quotes.[^4]
 
@@ -720,13 +679,13 @@
 
 This paragraph should not be part of the note, as it is not indented.
 
-[^1]: Here is the footnote. It can go anywhere after the footnote reference.
-    It need not be placed at the end of the document.
+[^1]: Here is the footnote. It can go anywhere after the footnote reference. It
+    need not be placed at the end of the document.
 
 [^2]: Here's the long note. This one contains multiple blocks.
 
-    Subsequent blocks are indented to show that they belong to the footnote
-    (as with list items).
+    Subsequent blocks are indented to show that they belong to the footnote (as
+    with list items).
 
           { <code> }
 
diff --git a/test/writer.markua b/test/writer.markua
new file mode 100644
--- /dev/null
+++ b/test/writer.markua
@@ -0,0 +1,702 @@
+This is a set of tests for pandoc. Most of them are adapted from John Gruber’s
+markdown test suite.
+
+* * *
+
+{id: headers}
+# Headers
+
+{id: level-2-with-an-embedded-link}
+## Level 2 with an [embedded link](/url)
+
+{id: level-3-with-emphasis}
+### Level 3 with *emphasis*
+
+{id: level-4}
+#### Level 4
+
+{id: level-5}
+##### Level 5
+
+{id: level-1}
+# Level 1
+
+{id: level-2-with-emphasis}
+## Level 2 with *emphasis*
+
+{id: level-3}
+### Level 3
+
+with no blank line
+
+{id: level-2}
+## Level 2
+
+with no blank line
+
+* * *
+
+{id: paragraphs}
+# Paragraphs
+
+Here’s a regular paragraph.
+
+In Markdown 1.0.0 and earlier. Version 8. This line turns into a list item.
+Because a hard-wrapped line in the middle of a paragraph looked like a list
+item.
+
+Here’s one with a bullet. * criminey.
+
+There should be a hard line break
+here.
+
+* * *
+
+{id: block-quotes}
+# Block Quotes
+
+E-mail style:
+
+> This is a block quote. It is pretty short.
+
+> Code in a block quote:
+>
+> ```
+> sub status {
+>     print "working";
+> }
+> ```
+>
+> A list:
+>
+> 1. item one
+> 2. item two
+>
+> Nested block quotes:
+>
+> > nested
+>
+> > nested
+
+This should not be a block quote: 2 > 1.
+
+And a following paragraph.
+
+* * *
+
+{id: code-blocks}
+# Code Blocks
+
+Code:
+
+```
+---- (should be four hyphens)
+
+sub status {
+    print "working";
+}
+
+this code block is indented by one tab
+```
+
+And:
+
+```
+    this code block is indented by two tabs
+
+These should not be escaped:  \$ \\ \> \[ \{
+```
+
+* * *
+
+{id: lists}
+# Lists
+
+{id: unordered}
+## Unordered
+
+Asterisks tight:
+
+* asterisk 1
+* asterisk 2
+* asterisk 3
+
+Asterisks loose:
+
+* asterisk 1
+
+* asterisk 2
+
+* asterisk 3
+
+Pluses tight:
+
+* Plus 1
+* Plus 2
+* Plus 3
+
+Pluses loose:
+
+* Plus 1
+
+* Plus 2
+
+* Plus 3
+
+Minuses tight:
+
+* Minus 1
+* Minus 2
+* Minus 3
+
+Minuses loose:
+
+* Minus 1
+
+* Minus 2
+
+* Minus 3
+
+{id: ordered}
+## Ordered
+
+Tight:
+
+1. First
+2. Second
+3. Third
+
+and:
+
+1. One
+2. Two
+3. Three
+
+Loose using tabs:
+
+1. First
+
+2. Second
+
+3. Third
+
+and using spaces:
+
+1. One
+
+2. Two
+
+3. Three
+
+Multiple paragraphs:
+
+1. Item 1, graf one.
+
+    Item 1. graf two. The quick brown fox jumped over the lazy dog’s back.
+
+2. Item 2.
+
+3. Item 3.
+
+{id: nested}
+## Nested
+
+* Tab
+  * Tab
+    * Tab
+
+Here’s another:
+
+1. First
+2. Second:
+    * Fee
+    * Fie
+    * Foe
+3. Third
+
+Same thing but with paragraphs:
+
+1. First
+
+2. Second:
+
+    * Fee
+    * Fie
+    * Foe
+
+3. Third
+
+{id: tabs-and-spaces}
+## Tabs and spaces
+
+* this is a list item indented with tabs
+
+* this is a list item indented with spaces
+
+  * this is an example list item indented with tabs
+
+  * this is an example list item indented with spaces
+
+{id: fancy-list-markers}
+## Fancy list markers
+
+2) begins with 2
+
+3) and now 3
+
+    with a continuation
+
+    iv. sublist with roman numerals, starting with 4
+    v. more items
+        A) a subsublist
+        B) a subsublist
+
+Nesting:
+
+A. Upper Alpha
+    I. Upper Roman.
+        6) Decimal start with 6
+            c) Lower alpha with paren
+
+Autonumbering:
+
+1. Autonumber.
+2. More.
+    1. Nested.
+
+Should not be a list item:
+
+M.A. 2007
+
+B. Williams
+
+* * *
+
+{id: definition-lists}
+# Definition Lists
+
+Tight using spaces:
+
+apple
+: red fruit
+
+orange
+: orange fruit
+
+banana
+: yellow fruit
+
+Tight using tabs:
+
+apple
+: red fruit
+
+orange
+: orange fruit
+
+banana
+: yellow fruit
+
+Loose:
+
+apple
+
+: red fruit
+
+orange
+
+: orange fruit
+
+banana
+
+: yellow fruit
+
+Multiple blocks with italics:
+
+*apple*
+
+: red fruit
+
+  contains seeds, crisp, pleasant to taste
+
+*orange*
+
+: orange fruit
+
+  ```
+  { orange code block }
+  ```
+
+  > orange block quote
+
+Multiple definitions, tight:
+
+apple
+: red fruit
+: computer
+
+orange
+: orange fruit
+: bank
+
+Multiple definitions, loose:
+
+apple
+
+: red fruit
+
+: computer
+
+orange
+
+: orange fruit
+
+: bank
+
+Blank line after term, indented marker, alternate markers:
+
+apple
+
+: red fruit
+
+: computer
+
+orange
+
+: orange fruit
+
+  1. sublist
+  2. sublist
+
+{id: html-blocks}
+# HTML Blocks
+
+Simple block on one line:
+
+foo
+
+And nested without indentation:
+
+foo
+
+bar
+
+Interpreted markdown in a table:
+
+This is *emphasized*
+And this is **strong**
+Here’s a simple block:
+
+foo
+
+This should be a code block, though:
+
+```
+<div>
+    foo
+</div>
+```
+
+As should this:
+
+```
+<div>foo</div>
+```
+
+Now, nested:
+
+foo
+
+This should just be an HTML comment:
+
+Multiline:
+
+Code block:
+
+```
+<!-- Comment -->
+```
+
+Just plain comment, with trailing spaces on the line:
+
+Code:
+
+```
+<hr />
+```
+
+Hr’s:
+
+* * *
+
+{id: inline-markup}
+# Inline Markup
+
+This is *emphasized*, and so *is this*.
+
+This is **strong**, and so **is this**.
+
+An *[emphasized link](/url)*.
+
+***This is strong and em.***
+
+So is ***this*** word.
+
+***This is strong and em.***
+
+So is ***this*** word.
+
+This is code: `>`, `$`, `\`, `\$`, `<html>`.
+
+~~This is *strikeout*.~~
+
+Superscripts: a^bc^d a^*hello*^ a^hello there^.
+
+Subscripts: H~2~O, H~23~O, H~many of them~O.
+
+These should not be superscripts or subscripts, because of the unescaped spaces:
+a^b c^d, a~b c~d.
+
+* * *
+
+{id: smart-quotes-ellipses-dashes}
+# Smart quotes, ellipses, dashes
+
+"Hello," said the spider. "'Shelob' is my name."
+
+'A', 'B', and 'C' are letters.
+
+'Oak,' 'elm,' and 'beech' are names of trees. So is 'pine.'
+
+'He said, "I want to go."' Were you alive in the 70’s?
+
+Here is some quoted '`code`' and a "[quoted
+link](http://example.com/?foo=1&bar=2)".
+
+Some dashes: one—two — three—four — five.
+
+Dashes between numbers: 5–7, 255–66, 1987–1999.
+
+Ellipses…and…and….
+
+* * *
+
+{id: latex}
+# LaTeX
+
+* 
+* `2+2=4`$
+* `x \in y`$
+* `\alpha \wedge \omega`$
+* `223`$
+* `p`$-Tree
+* Here’s some display math:
+
+  {format: latex}
+  ```
+  \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: `\alpha + \omega \times x^2`$.
+
+These shouldn’t be math:
+
+* To get the famous equation, write `$e = mc^2$`.
+* $22,000 is a *lot* of money. So is $34,000. (It worked if "lot" is
+  emphasized.)
+* Shoes ($20) and socks ($5).
+* Escaped `$`: $73 *this should be emphasized* 23$.
+
+Here’s a LaTeX table:
+
+* * *
+
+{id: special-characters}
+# Special Characters
+
+Here is some unicode:
+
+* I hat: Î
+* o umlaut: ö
+* section: §
+* set membership: ∈
+* copyright: ©
+
+AT&T has an ampersand in their name.
+
+AT&T is another way to write it.
+
+This & that.
+
+4 < 5.
+
+6 > 5.
+
+Backslash: \
+
+Backtick: `
+
+Asterisk: *
+
+Underscore: _
+
+Left brace: {
+
+Right brace: }
+
+Left bracket: [
+
+Right bracket: ]
+
+Left paren: (
+
+Right paren: )
+
+Greater-than: >
+
+Hash: #
+
+Period: .
+
+Bang: !
+
+Plus: +
+
+Minus: -
+
+* * *
+
+{id: links}
+# Links
+
+{id: explicit}
+## Explicit
+
+Just a [URL](/url/).
+
+[URL and title](/url/){title: "title"}.
+
+[URL and title](/url/){title: "title preceded by two spaces"}.
+
+[URL and title](/url/){title: "title preceded by a tab"}.
+
+[URL and title](/url/){title: "title with "quotes" in it"}
+
+[URL and title](/url/){title: "title with single quotes"}
+
+[with_underscore](/url/with_underscore)
+
+[Email link](mailto:nobody@nowhere.net)
+
+[Empty]().
+
+{id: reference}
+## Reference
+
+Foo [bar](/url/).
+
+With [embedded [brackets]](/url/).
+
+[b](/url/) by itself should be a link.
+
+Indented [once](/url).
+
+Indented [twice](/url).
+
+Indented [thrice](/url).
+
+This should [not][] be a link.
+
+```
+[not]: /url
+```
+
+Foo [bar](/url/){title: "Title with "quotes" inside"}.
+
+Foo [biz](/url/){title: "Title with "quote" inside"}.
+
+{id: with-ampersands}
+## With ampersands
+
+Here’s a [link with an ampersand in the URL](http://example.com/?foo=1&bar=2).
+
+Here’s a link with an amersand in the link text:
+[AT&T](http://att.com/){title: "AT&T"}.
+
+Here’s an [inline link](/script?foo=1&bar=2).
+
+Here’s an [inline link in pointy braces](/script?foo=1&bar=2).
+
+{id: autolinks}
+## Autolinks
+
+With an ampersand:
+[http:~/~/example.com/?foo=1&bar=2](http://example.com/?foo=1&bar=2){class: uri}
+
+* In a list?
+* [http:~/~/example.com/](http://example.com/){class: uri}
+* It should.
+
+An e-mail address: [nobody@nowhere.net](mailto:nobody@nowhere.net){class: email}
+
+> Blockquoted: [http:~/~/example.com/](http://example.com/){class: uri}
+
+Auto-links should not occur here: `<http://example.com/>`
+
+```
+or here: <http://example.com/>
+```
+
+* * *
+
+{id: images}
+# Images
+
+From "Voyage dans la Lune" by Georges Melies (1902):
+
+{alt: "lalune", title: "Voyage dans la Lune"}
+![](lalune.jpg)
+
+lalune
+
+Here is a movie
+{alt: "movie"}
+![](movie.jpg)
+icon.
+
+* * *
+
+{id: footnotes}
+# Footnotes
+
+Here is a footnote reference,[^1] and another.[^2] This should *not* be a
+footnote reference, because it contains a space.[^my note] Here is an inline
+note.[^3]
+
+> Notes can go in quotes.[^4]
+
+1. And in list items.[^5]
+
+This paragraph should not be part of the note, as it is not indented.
+
+[^1]: Here is the footnote. It can go anywhere after the footnote reference. It
+    need not be placed at the end of the document.
+
+[^2]: Here’s the long note. This one contains multiple blocks.
+
+    Subsequent blocks are indented to show that they belong to the footnote (as
+    with list items).
+
+    ```
+      { <code> }
+    ```
+
+    If you want, you can indent every line, but you can also be lazy and just
+    indent the first line of each block.
+
+[^3]: This is *easier* to type. Inline notes may contain
+    [links](http://google.com) and `]` verbatim characters, as well as
+    [bracketed text].
+
+[^4]: In quote.
+
+[^5]: In list.
diff --git a/test/writer.mediawiki b/test/writer.mediawiki
--- a/test/writer.mediawiki
+++ b/test/writer.mediawiki
@@ -1,33 +1,41 @@
 This is a set of tests for pandoc. Most of them are adapted from John Gruber’s markdown test suite.
 
-
 -----
 
+<span id="headers"></span>
 = Headers =
 
+<span id="level-2-with-an-embedded-link"></span>
 == Level 2 with an [[url|embedded link]] ==
 
+<span id="level-3-with-emphasis"></span>
 === Level 3 with ''emphasis'' ===
 
+<span id="level-4"></span>
 ==== Level 4 ====
 
+<span id="level-5"></span>
 ===== Level 5 =====
 
+<span id="level-1"></span>
 = Level 1 =
 
+<span id="level-2-with-emphasis"></span>
 == Level 2 with ''emphasis'' ==
 
+<span id="level-3"></span>
 === Level 3 ===
 
 with no blank line
 
+<span id="level-2"></span>
 == Level 2 ==
 
 with no blank line
 
-
 -----
 
+<span id="paragraphs"></span>
 = Paragraphs =
 
 Here’s a regular paragraph.
@@ -39,9 +47,9 @@
 There should be a hard line break<br />
 here.
 
-
 -----
 
+<span id="block-quotes"></span>
 = Block Quotes =
 
 E-mail style:
@@ -63,14 +71,15 @@
 <blockquote>nested
 </blockquote>
 <blockquote>nested
-</blockquote></blockquote>
+</blockquote>
+</blockquote>
 This should not be a block quote: 2 &gt; 1.
 
 And a following paragraph.
 
-
 -----
 
+<span id="code-blocks"></span>
 = Code Blocks =
 
 Code:
@@ -90,8 +99,10 @@
 
 -----
 
+<span id="lists"></span>
 = Lists =
 
+<span id="unordered"></span>
 == Unordered ==
 
 Asterisks tight:
@@ -130,6 +141,7 @@
 * Minus 2
 * Minus 3
 
+<span id="ordered"></span>
 == Ordered ==
 
 Tight:
@@ -164,6 +176,7 @@
 <li><p>Item 2.</p></li>
 <li><p>Item 3.</p></li></ol>
 
+<span id="nested"></span>
 == Nested ==
 
 * Tab
@@ -188,6 +201,7 @@
 #* Foe
 # Third
 
+<span id="tabs-and-spaces"></span>
 == Tabs and spaces ==
 
 * this is a list item indented with tabs
@@ -195,10 +209,11 @@
 ** this is an example list item indented with tabs
 ** this is an example list item indented with spaces
 
+<span id="fancy-list-markers"></span>
 == 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;">
@@ -206,9 +221,7 @@
 <li>more items
 <ol style="list-style-type: upper-alpha;">
 <li>a subsublist</li>
-<li>a subsublist</li></ol>
-</li></ol>
-</li></ol>
+<li>a subsublist</li></ol></li></ol></li></ol>
 
 Nesting:
 
@@ -219,10 +232,7 @@
 <ol start="6" style="list-style-type: decimal;">
 <li>Decimal start with 6
 <ol start="3" style="list-style-type: lower-alpha;">
-<li>Lower alpha with paren</li></ol>
-</li></ol>
-</li></ol>
-</li></ol>
+<li>Lower alpha with paren</li></ol></li></ol></li></ol></li></ol>
 
 Autonumbering:
 
@@ -236,9 +246,9 @@
 
 B. Williams
 
-
 -----
 
+<span id="definition-lists"></span>
 = Definition Lists =
 
 Tight using spaces:
@@ -277,7 +287,8 @@
 <dt>''orange''</dt>
 <dd><p>orange fruit</p>
 <pre>{ orange code block }</pre>
-<blockquote><p>orange block quote</p></blockquote></dd></dl>
+<blockquote><p>orange block quote</p>
+</blockquote></dd></dl>
 
 Multiple definitions, tight:
 
@@ -307,36 +318,32 @@
 ;# sublist
 ;# sublist
 
+<span id="html-blocks"></span>
 = HTML Blocks =
 
 Simple block on one line:
 
 <div>
-
 foo
-
 </div>
+
 And nested without indentation:
 
 <div>
-
 <div>
-
 <div>
-
 foo
 
-
 </div>
 
 </div>
-<div>
 
+<div>
 bar
-
 </div>
 
 </div>
+
 Interpreted markdown in a table:
 
 <table>
@@ -353,11 +360,10 @@
 Here’s a simple block:
 
 <div>
-
 foo
 
-
 </div>
+
 This should be a code block, though:
 
 <pre>&lt;div&gt;
@@ -369,18 +375,15 @@
 Now, nested:
 
 <div>
-
 <div>
-
 <div>
-
 foo
-
 </div>
 
 </div>
 
 </div>
+
 This should just be an HTML comment:
 
 <!-- Comment -->
@@ -416,6 +419,7 @@
 
 -----
 
+<span id="inline-markup"></span>
 = Inline Markup =
 
 This is ''emphasized'', and so ''is this''.
@@ -442,9 +446,9 @@
 
 These should not be superscripts or subscripts, because of the unescaped spaces: a^b c^d, a~b c~d.
 
-
 -----
 
+<span id="smart-quotes-ellipses-dashes"></span>
 = Smart quotes, ellipses, dashes =
 
 “Hello,” said the spider. “‘Shelob’ is my name.”
@@ -463,12 +467,12 @@
 
 Ellipses…and…and….
 
-
 -----
 
+<span id="latex"></span>
 = LaTeX =
 
-* 
+*
 * <math display="inline">2+2=4</math>
 * <math display="inline">x \in y</math>
 * <math display="inline">\alpha \wedge \omega</math>
@@ -486,10 +490,9 @@
 
 Here’s a LaTeX table:
 
-
-
 -----
 
+<span id="special-characters"></span>
 = Special Characters =
 
 Here is some unicode:
@@ -542,11 +545,12 @@
 
 Minus: -
 
-
 -----
 
+<span id="links"></span>
 = Links =
 
+<span id="explicit"></span>
 == Explicit ==
 
 Just a [[url/|URL]].
@@ -567,6 +571,7 @@
 
 [[|Empty]].
 
+<span id="reference"></span>
 == Reference ==
 
 Foo [[url/|bar]].
@@ -588,6 +593,7 @@
 
 Foo [[url/|biz]].
 
+<span id="with-ampersands"></span>
 == With ampersands ==
 
 Here’s a [http://example.com/?foo=1&bar=2 link with an ampersand in the URL].
@@ -598,6 +604,7 @@
 
 Here’s an [[script?foo=1&bar=2|inline link in pointy braces]].
 
+<span id="autolinks"></span>
 == Autolinks ==
 
 With an ampersand: http://example.com/?foo=1&bar=2
@@ -616,17 +623,20 @@
 
 -----
 
+<span id="images"></span>
 = Images =
 
 From “Voyage dans la Lune” by Georges Melies (1902):
 
-[[File:lalune.jpg|frame|none|alt=Voyage dans la Lune|caption lalune]]
+<div class="figure">
+[[File:lalune.jpg|lalune]]
+</div>
 
 Here is a movie [[File:movie.jpg|movie]] icon.
 
-
 -----
 
+<span id="footnotes"></span>
 = Footnotes =
 
 Here is a footnote reference,<ref>Here is the footnote. It can go anywhere after the footnote reference. It need not be placed at the end of the document.</ref> and another.<ref>Here’s the long note. This one contains multiple blocks.
diff --git a/test/writer.ms b/test/writer.ms
--- a/test/writer.ms
+++ b/test/writer.ms
@@ -29,19 +29,15 @@
 .\" font family: A, BM, H, HN, N, P, T, ZCM
 .fam T
 .\" paragraph indent
-.nr PI 2m
+.nr PI 0m
 .\" interparagraph space
-.nr PD 0.33v
+.nr PD 0.4v
 .\" footnote width
 .nr FL \n[LL]
 .\" footnote point size
 .nr FPS (\n[PS] - 2000)
 .\" color used for strikeout
 .defcolor strikecolor rgb 0.7 0.7 0.7
-.\" color for links (rgb)
-.ds PDFHREF.COLOUR   0.35 0.00 0.60
-.\" border for links (default none)
-.ds PDFHREF.BORDER   0 0 0
 .\" point size difference between heading levels
 .nr PSINCR 1p
 .\" heading level above which point size no longer changes
@@ -49,6 +45,17 @@
 .\" comment these out if you want a dot after section numbers:
 .als SN SN-NO-DOT
 .als SN-STYLE SN-NO-DOT
+.\" page numbers in footer, centered
+.ds CH
+.ds CF %
+.hy
+.EQ
+delim @@
+.EN
+.\" color for links (rgb)
+.ds PDFHREF.COLOUR   0.35 0.00 0.60
+.\" border for links (default none)
+.ds PDFHREF.BORDER   0 0 0
 .\" pdf outline fold level
 .nr PDFOUTLINE.FOLDLEVEL 3
 .\" start out in outline view
@@ -57,22 +64,21 @@
 .\" PDF metadata
 .pdfinfo /Title "Pandoc Test Suite"
 .pdfinfo /Author "John MacFarlane; Anonymous"
-.hy
-.EQ
-delim @@
-.EN
 .TL
 Pandoc Test Suite
 .AU
 John MacFarlane
 .AU
 Anonymous
-.ND "July 17, 2006"
+.AU
+.sp 0.5
+.ft R
+July 17, 2006
 .\" 1 column (use .2C for two column)
 .1C
 .LP
 This is a set of tests for pandoc.
-Most of them are adapted from John Gruber's markdown test suite.
+Most of them are adapted from John Gruber\(cqs markdown test suite.
 .HLINE
 .SH 1
 Headers
@@ -86,7 +92,7 @@
 .pdfhref O 2 "Level 2 with an embedded link"
 .pdfhref M "level-2-with-an-embedded-link"
 .SH 3
-Level 3 with \f[I]emphasis\f[]
+Level 3 with \f[BI]emphasis\f[B]
 .pdfhref O 3 "Level 3 with emphasis"
 .pdfhref M "level-3-with-emphasis"
 .SH 4
@@ -102,7 +108,7 @@
 .pdfhref O 1 "Level 1"
 .pdfhref M "level-1"
 .SH 2
-Level 2 with \f[I]emphasis\f[]
+Level 2 with \f[BI]emphasis\f[B]
 .pdfhref O 2 "Level 2 with emphasis"
 .pdfhref M "level-2-with-emphasis"
 .SH 3
@@ -123,15 +129,15 @@
 .pdfhref O 1 "Paragraphs"
 .pdfhref M "paragraphs"
 .LP
-Here's a regular paragraph.
+Here\(cqs a regular paragraph.
 .PP
 In Markdown 1.0.0 and earlier.
 Version 8.
 This line turns into a list item.
-Because a hard\-wrapped line in the middle of a paragraph looked like a list
+Because a hard-wrapped line in the middle of a paragraph looked like a list
 item.
 .PP
-Here's one with a bullet.
+Here\(cqs one with a bullet.
 * criminey.
 .PP
 There should be a hard line break
@@ -143,20 +149,20 @@
 .pdfhref O 1 "Block Quotes"
 .pdfhref M "block-quotes"
 .LP
-E\-mail style:
-.RS
+E-mail style:
+.QS
 .LP
 This is a block quote.
 It is pretty short.
-.RE
-.RS
+.QE
+.QS
 .LP
 Code in a block quote:
 .IP
 .nf
 \f[C]
-sub\ status\ {
-\ \ \ \ print\ \[dq]working\[dq];
+sub status {
+    print \(dqworking\(dq;
 }
 \f[]
 .fi
@@ -168,15 +174,15 @@
 item two
 .LP
 Nested block quotes:
-.RS
+.QS
 .LP
 nested
-.RE
-.RS
+.QE
+.QS
 .LP
 nested
-.RE
-.RE
+.QE
+.QE
 .LP
 This should not be a block quote: 2 > 1.
 .PP
@@ -191,13 +197,13 @@
 .IP
 .nf
 \f[C]
-\-\-\-\-\ (should\ be\ four\ hyphens)
+---- (should be four hyphens)
 
-sub\ status\ {
-\ \ \ \ print\ \[dq]working\[dq];
+sub status {
+    print \(dqworking\(dq;
 }
 
-this\ code\ block\ is\ indented\ by\ one\ tab
+this code block is indented by one tab
 \f[]
 .fi
 .LP
@@ -205,9 +211,9 @@
 .IP
 .nf
 \f[C]
-\ \ \ \ this\ code\ block\ is\ indented\ by\ two\ tabs
+    this code block is indented by two tabs
 
-These\ should\ not\ be\ escaped:\ \ \\$\ \\\\\ \\>\ \\[\ \\{
+These should not be escaped:  \(rs$ \(rs\(rs \(rs> \(rs[ \(rs{
 \f[]
 .fi
 .HLINE
@@ -221,51 +227,51 @@
 .pdfhref M "unordered"
 .LP
 Asterisks tight:
-.IP \[bu] 3
+.IP \(bu 3
 asterisk 1
-.IP \[bu] 3
+.IP \(bu 3
 asterisk 2
-.IP \[bu] 3
+.IP \(bu 3
 asterisk 3
 .LP
 Asterisks loose:
-.IP \[bu] 3
+.IP \(bu 3
 asterisk 1
-.IP \[bu] 3
+.IP \(bu 3
 asterisk 2
-.IP \[bu] 3
+.IP \(bu 3
 asterisk 3
 .LP
 Pluses tight:
-.IP \[bu] 3
+.IP \(bu 3
 Plus 1
-.IP \[bu] 3
+.IP \(bu 3
 Plus 2
-.IP \[bu] 3
+.IP \(bu 3
 Plus 3
 .LP
 Pluses loose:
-.IP \[bu] 3
+.IP \(bu 3
 Plus 1
-.IP \[bu] 3
+.IP \(bu 3
 Plus 2
-.IP \[bu] 3
+.IP \(bu 3
 Plus 3
 .LP
 Minuses tight:
-.IP \[bu] 3
+.IP \(bu 3
 Minus 1
-.IP \[bu] 3
+.IP \(bu 3
 Minus 2
-.IP \[bu] 3
+.IP \(bu 3
 Minus 3
 .LP
 Minuses loose:
-.IP \[bu] 3
+.IP \(bu 3
 Minus 1
-.IP \[bu] 3
+.IP \(bu 3
 Minus 2
-.IP \[bu] 3
+.IP \(bu 3
 Minus 3
 .SH 2
 Ordered
@@ -311,7 +317,7 @@
 .PP
 Item 1.
 graf two.
-The quick brown fox jumped over the lazy dog's back.
+The quick brown fox jumped over the lazy dog\(cqs back.
 .RE
 .IP " 2." 4
 Item 2.
@@ -321,28 +327,28 @@
 Nested
 .pdfhref O 2 "Nested"
 .pdfhref M "nested"
-.IP \[bu] 3
+.IP \(bu 3
 Tab
 .RS 3
-.IP \[bu] 3
+.IP \(bu 3
 Tab
 .RS 3
-.IP \[bu] 3
+.IP \(bu 3
 Tab
 .RE
 .RE
 .LP
-Here's another:
+Here\(cqs another:
 .IP " 1." 4
 First
 .IP " 2." 4
 Second:
 .RS 4
-.IP \[bu] 3
+.IP \(bu 3
 Fee
-.IP \[bu] 3
+.IP \(bu 3
 Fie
-.IP \[bu] 3
+.IP \(bu 3
 Foe
 .RE
 .IP " 3." 4
@@ -354,11 +360,11 @@
 .IP " 2." 4
 Second:
 .RS 4
-.IP \[bu] 3
+.IP \(bu 3
 Fee
-.IP \[bu] 3
+.IP \(bu 3
 Fie
-.IP \[bu] 3
+.IP \(bu 3
 Foe
 .RE
 .IP " 3." 4
@@ -367,14 +373,14 @@
 Tabs and spaces
 .pdfhref O 2 "Tabs and spaces"
 .pdfhref M "tabs-and-spaces"
-.IP \[bu] 3
+.IP \(bu 3
 this is a list item indented with tabs
-.IP \[bu] 3
+.IP \(bu 3
 this is a list item indented with spaces
 .RS 3
-.IP \[bu] 3
+.IP \(bu 3
 this is an example list item indented with tabs
-.IP \[bu] 3
+.IP \(bu 3
 this is an example list item indented with spaces
 .RE
 .SH 2
@@ -428,10 +434,9 @@
 .LP
 Should not be a list item:
 .PP
-M.A.\~2007
+M.A.\ 2007
 .PP
-B.
-Williams
+B. Williams
 .HLINE
 .SH 1
 Definition Lists
@@ -439,112 +444,112 @@
 .pdfhref M "definition-lists"
 .LP
 Tight using spaces:
-.IP "apple"
+.IP "\f[B]apple\f[R]" 3
 red fruit
-.RS
+.RS 3
 .RE
-.IP "orange"
+.IP "\f[B]orange\f[R]" 3
 orange fruit
-.RS
+.RS 3
 .RE
-.IP "banana"
+.IP "\f[B]banana\f[R]" 3
 yellow fruit
-.RS
+.RS 3
 .RE
 .LP
 Tight using tabs:
-.IP "apple"
+.IP "\f[B]apple\f[R]" 3
 red fruit
-.RS
+.RS 3
 .RE
-.IP "orange"
+.IP "\f[B]orange\f[R]" 3
 orange fruit
-.RS
+.RS 3
 .RE
-.IP "banana"
+.IP "\f[B]banana\f[R]" 3
 yellow fruit
-.RS
+.RS 3
 .RE
 .LP
 Loose:
-.IP "apple"
+.IP "\f[B]apple\f[R]" 3
 red fruit
-.RS
+.RS 3
 .RE
-.IP "orange"
+.IP "\f[B]orange\f[R]" 3
 orange fruit
-.RS
+.RS 3
 .RE
-.IP "banana"
+.IP "\f[B]banana\f[R]" 3
 yellow fruit
-.RS
+.RS 3
 .RE
 .LP
 Multiple blocks with italics:
-.IP "\f[I]apple\f[]"
+.IP "\f[B]\f[BI]apple\f[B]\f[R]" 3
 red fruit
-.RS
+.RS 3
 .PP
 contains seeds, crisp, pleasant to taste
 .RE
-.IP "\f[I]orange\f[]"
+.IP "\f[B]\f[BI]orange\f[B]\f[R]" 3
 orange fruit
-.RS
+.RS 3
 .IP
 .nf
 \f[C]
-{\ orange\ code\ block\ }
+{ orange code block }
 \f[]
 .fi
-.RS
+.QS
 .LP
 orange block quote
-.RE
+.QE
 .RE
 .LP
 Multiple definitions, tight:
-.IP "apple"
+.IP "\f[B]apple\f[R]" 3
 red fruit
-.RS
+.RS 3
 .RE
 computer
-.RS
+.RS 3
 .RE
-.IP "orange"
+.IP "\f[B]orange\f[R]" 3
 orange fruit
-.RS
+.RS 3
 .RE
 bank
-.RS
+.RS 3
 .RE
 .LP
 Multiple definitions, loose:
-.IP "apple"
+.IP "\f[B]apple\f[R]" 3
 red fruit
-.RS
+.RS 3
 .RE
 computer
-.RS
+.RS 3
 .RE
-.IP "orange"
+.IP "\f[B]orange\f[R]" 3
 orange fruit
-.RS
+.RS 3
 .RE
 bank
-.RS
+.RS 3
 .RE
 .LP
 Blank line after term, indented marker, alternate markers:
-.IP "apple"
+.IP "\f[B]apple\f[R]" 3
 red fruit
-.RS
+.RS 3
 .RE
 computer
-.RS
+.RS 3
 .RE
-.IP "orange"
+.IP "\f[B]orange\f[R]" 3
 orange fruit
-.RS
+.RS 3
 .IP " 1." 4
 sublist
 .IP " 2." 4
@@ -564,10 +569,10 @@
 bar
 .LP
 Interpreted markdown in a table:
-This is \f[I]emphasized\f[]
-And this is \f[B]strong\f[]
+This is \f[I]emphasized\f[R]
+And this is \f[B]strong\f[R]
 .PP
-Here's a simple block:
+Here\(cqs a simple block:
 .LP
 foo
 .LP
@@ -576,7 +581,7 @@
 .nf
 \f[C]
 <div>
-\ \ \ \ foo
+    foo
 </div>
 \f[]
 .fi
@@ -600,7 +605,7 @@
 .IP
 .nf
 \f[C]
-<!\-\-\ Comment\ \-\->
+<!-- Comment -->
 \f[]
 .fi
 .LP
@@ -610,69 +615,69 @@
 .IP
 .nf
 \f[C]
-<hr\ />
+<hr />
 \f[]
 .fi
 .LP
-Hr's:
+Hr\(cqs:
 .HLINE
 .SH 1
 Inline Markup
 .pdfhref O 1 "Inline Markup"
 .pdfhref M "inline-markup"
 .LP
-This is \f[I]emphasized\f[], and so \f[I]is this\f[].
+This is \f[I]emphasized\f[R], and so \f[I]is this\f[R].
 .PP
-This is \f[B]strong\f[], and so \f[B]is this\f[].
+This is \f[B]strong\f[R], and so \f[B]is this\f[R].
 .PP
 An \f[I]\c
 .pdfhref W -D "/url" -A "\c" \
  -- "emphasized link"
-\&\f[].
+\&\f[R].
 .PP
-\f[B]\f[BI]This is strong and em.\f[B]\f[]
+\f[B]\f[BI]This is strong and em.\f[B]\f[R]
 .PP
-So is \f[B]\f[BI]this\f[B]\f[] word.
+So is \f[B]\f[BI]this\f[B]\f[R] word.
 .PP
-\f[B]\f[BI]This is strong and em.\f[B]\f[]
+\f[B]\f[BI]This is strong and em.\f[B]\f[R]
 .PP
-So is \f[B]\f[BI]this\f[B]\f[] word.
+So is \f[B]\f[BI]this\f[B]\f[R] word.
 .PP
-This is code: \f[C]>\f[], \f[C]$\f[], \f[C]\\\f[], \f[C]\\$\f[],
-\f[C]<html>\f[].
+This is code: \f[CR]>\f[R], \f[CR]$\f[R], \f[CR]\(rs\f[R], \f[CR]\(rs$\f[R],
+\f[CR]<html>\f[R].
 .PP
-\m[strikecolor]This is \f[I]strikeout\f[].\m[]
+\m[strikecolor]This is \f[I]strikeout\f[R].\m[]
 .PP
-Superscripts: a\*{bc\*}d a\*{\f[I]hello\f[]\*} a\*{hello\~there\*}.
+Superscripts: a\*{bc\*}d a\*{\f[I]hello\f[R]\*} a\*{hello\ there\*}.
 .PP
-Subscripts: H\*<2\*>O, H\*<23\*>O, H\*<many\~of\~them\*>O.
+Subscripts: H\*<2\*>O, H\*<23\*>O, H\*<many\ of\ them\*>O.
 .PP
-These should not be superscripts or subscripts, because of the unescaped
-spaces: a\[ha]b c\[ha]d, a\[ti]b c\[ti]d.
+These should not be superscripts or subscripts, because of the unescaped spaces:
+a\(hab c\(had, a\(tib c\(tid.
 .HLINE
 .SH 1
 Smart quotes, ellipses, dashes
 .pdfhref O 1 "Smart quotes, ellipses, dashes"
 .pdfhref M "smart-quotes-ellipses-dashes"
 .LP
-\[lq]Hello,\[rq] said the spider.
-\[lq]`Shelob' is my name.\[rq]
+\(lqHello,\(rq said the spider.
+\(lq`Shelob' is my name.\(rq
 .PP
 `A', `B', and `C' are letters.
 .PP
 `Oak,' `elm,' and `beech' are names of trees.
 So is `pine.'
 .PP
-`He said, \[lq]I want to go.\[rq]' Were you alive in the 70's?
+`He said, \(lqI want to go.\(rq' Were you alive in the 70\(cqs?
 .PP
-Here is some quoted `\f[C]code\f[]' and a \[lq]\c
+Here is some quoted `\f[CR]code\f[R]' and a \(lq\c
 .pdfhref W -D "http://example.com/?foo=1&bar=2" -A "\c" \
  -- "quoted link"
-\&\[rq].
+\&\(rq.
 .PP
-Some dashes: one\[em]two \[em] three\[em]four \[em] five.
+Some dashes: one\(emtwo \(em three\(emfour \(em five.
 .PP
-Dashes between numbers: 5\[en]7, 255\[en]66, 1987\[en]1999.
+Dashes between numbers: 5\(en7, 255\(en66, 1987\(en1999.
 .PP
 Ellipses\&...and\&...and\&....
 .HLINE
@@ -680,38 +685,38 @@
 LaTeX
 .pdfhref O 1 "LaTeX"
 .pdfhref M "latex"
-.IP \[bu] 3
-.IP \[bu] 3
+.IP \(bu 3
+.IP \(bu 3
 @2 + 2 = 4@
-.IP \[bu] 3
+.IP \(bu 3
 @x \[u2208] y@
-.IP \[bu] 3
+.IP \(bu 3
 @alpha \[u2227] omega@
-.IP \[bu] 3
+.IP \(bu 3
 @223@
-.IP \[bu] 3
-@p@\-Tree
-.IP \[bu] 3
-Here's some display math:
+.IP \(bu 3
+@p@-Tree
+.IP \(bu 3
+Here\(cqs some display math:
 .EQ
-d over {d x} f ( x ) = lim sub {h -> 0} {f ( x + h ) \[u2212] f ( x )} over h
+d over {d x} f ( x ) = lim from {h -> 0} {f ( x + h ) - f ( x )} over h
 .EN
-.IP \[bu] 3
-Here's one that has a line break in it: @alpha + omega times x sup 2@.
+.IP \(bu 3
+Here\(cqs one that has a line break in it: @alpha + omega times x sup 2@.
 .LP
-These shouldn't be math:
-.IP \[bu] 3
-To get the famous equation, write \f[C]$e\ =\ mc\[ha]2$\f[].
-.IP \[bu] 3
-$22,000 is a \f[I]lot\f[] of money.
+These shouldn\(cqt be math:
+.IP \(bu 3
+To get the famous equation, write \f[CR]$e = mc\(ha2$\f[R].
+.IP \(bu 3
+$22,000 is a \f[I]lot\f[R] of money.
 So is $34,000.
-(It worked if \[lq]lot\[rq] is emphasized.)
-.IP \[bu] 3
+(It worked if \(lqlot\(rq is emphasized.)
+.IP \(bu 3
 Shoes ($20) and socks ($5).
-.IP \[bu] 3
-Escaped \f[C]$\f[]: $73 \f[I]this should be emphasized\f[] 23$.
+.IP \(bu 3
+Escaped \f[CR]$\f[R]: $73 \f[I]this should be emphasized\f[R] 23$.
 .LP
-Here's a LaTeX table:
+Here\(cqs a LaTeX table:
 .HLINE
 .SH 1
 Special Characters
@@ -719,15 +724,15 @@
 .pdfhref M "special-characters"
 .LP
 Here is some unicode:
-.IP \[bu] 3
+.IP \(bu 3
 I hat: Î
-.IP \[bu] 3
+.IP \(bu 3
 o umlaut: ö
-.IP \[bu] 3
+.IP \(bu 3
 section: §
-.IP \[bu] 3
+.IP \(bu 3
 set membership: ∈
-.IP \[bu] 3
+.IP \(bu 3
 copyright: ©
 .LP
 AT&T has an ampersand in their name.
@@ -740,9 +745,9 @@
 .PP
 6 > 5.
 .PP
-Backslash: \\
+Backslash: \(rs
 .PP
-Backtick: \`
+Backtick: \(ga
 .PP
 Asterisk: *
 .PP
@@ -760,7 +765,7 @@
 .PP
 Right paren: )
 .PP
-Greater\-than: >
+Greater-than: >
 .PP
 Hash: #
 .PP
@@ -770,7 +775,7 @@
 .PP
 Plus: +
 .PP
-Minus: \-
+Minus: -
 .HLINE
 .SH 1
 Links
@@ -864,7 +869,7 @@
 .IP
 .nf
 \f[C]
-[not]:\ /url
+[not]: /url
 \f[]
 .fi
 .LP
@@ -882,22 +887,22 @@
 .pdfhref O 2 "With ampersands"
 .pdfhref M "with-ampersands"
 .LP
-Here's a \c
+Here\(cqs a \c
 .pdfhref W -D "http://example.com/?foo=1&bar=2" -A "\c" \
  -- "link with an ampersand in the URL"
 \&.
 .PP
-Here's a link with an amersand in the link text: \c
+Here\(cqs a link with an amersand in the link text: \c
 .pdfhref W -D "http://att.com/" -A "\c" \
  -- "AT&T"
 \&.
 .PP
-Here's an \c
+Here\(cqs an \c
 .pdfhref W -D "/script?foo=1&bar=2" -A "\c" \
  -- "inline link"
 \&.
 .PP
-Here's an \c
+Here\(cqs an \c
 .pdfhref W -D "/script?foo=1&bar=2" -A "\c" \
  -- "inline link in pointy braces"
 \&.
@@ -910,33 +915,33 @@
 .pdfhref W -D "http://example.com/?foo=1&bar=2" -A "\c" \
  -- "http://example.com/?foo=1&bar=2"
 \&
-.IP \[bu] 3
+.IP \(bu 3
 In a list?
-.IP \[bu] 3
+.IP \(bu 3
 \c
 .pdfhref W -D "http://example.com/" -A "\c" \
  -- "http://example.com/"
 \&
-.IP \[bu] 3
+.IP \(bu 3
 It should.
 .LP
-An e\-mail address: \c
+An e-mail address: \c
 .pdfhref W -D "mailto:nobody%40nowhere.net" -A "\c" \
- -- "nobody\@nowhere.net"
+ -- "nobody\(atnowhere.net"
 \&
-.RS
+.QS
 .LP
 Blockquoted: \c
 .pdfhref W -D "http://example.com/" -A "\c" \
  -- "http://example.com/"
 \&
-.RE
+.QE
 .LP
-Auto\-links should not occur here: \f[C]<http://example.com/>\f[]
+Auto-links should not occur here: \f[CR]<http://example.com/>\f[R]
 .IP
 .nf
 \f[C]
-or\ here:\ <http://example.com/>
+or here: <http://example.com/>
 \f[]
 .fi
 .HLINE
@@ -945,11 +950,15 @@
 .pdfhref O 1 "Images"
 .pdfhref M "images"
 .LP
-From \[lq]Voyage dans la Lune\[rq] by Georges Melies (1902):
-.PP
-[IMAGE: lalune]
-.PP
-Here is a movie [IMAGE: movie] icon.
+From \(lqVoyage dans la Lune\(rq by Georges Melies (1902):
+\" .IMAGE "lalune.jpg"
+.ce 1
+lalune
+.sp 1
+.LP
+Here is a movie
+[IMAGE: movie] \" "movie.jpg"
+icon.
 .HLINE
 .SH 1
 Footnotes
@@ -964,37 +973,37 @@
 .FE
 and another.\**
 .FS
-Here's the long note.
+Here\(cqs the long note.
 This one contains multiple blocks.
 .PP
-Subsequent blocks are indented to show that they belong to the footnote (as
-with list items).
+Subsequent blocks are indented to show that they belong to the footnote (as with
+list items).
 .IP
 .nf
 \f[C]
-\ \ {\ <code>\ }
+  { <code> }
 \f[]
 .fi
 .LP
-If you want, you can indent every line, but you can also be lazy and just
-indent the first line of each block.
+If you want, you can indent every line, but you can also be lazy and just indent
+the first line of each block.
 .FE
-This should \f[I]not\f[] be a footnote reference, because it contains a
-space.[\[ha]my note] Here is an inline note.\**
+This should \f[I]not\f[R] be a footnote reference, because it contains a
+space.[\(hamy note] Here is an inline note.\**
 .FS
-This is \f[I]easier\f[] to type.
+This is \f[I]easier\f[R] to type.
 Inline notes may contain \c
 .pdfhref W -D "http://google.com" -A "\c" \
  -- "links"
-\& and \f[C]]\f[] verbatim characters, as well as [bracketed text].
+\& and \f[CR]]\f[R] verbatim characters, as well as [bracketed text].
 .FE
-.RS
+.QS
 .LP
 Notes can go in quotes.\**
 .FS
 In quote.
 .FE
-.RE
+.QE
 .IP " 1." 4
 And in list items.\**
 .FS
diff --git a/test/writer.muse b/test/writer.muse
--- a/test/writer.muse
+++ b/test/writer.muse
@@ -1,4 +1,4 @@
-#author John MacFarlane
+#author John MacFarlane; Anonymous
 #title Pandoc Test Suite
 #date July 17, 2006
 
@@ -11,7 +11,7 @@
 
 ** Level 2 with an [[/url][embedded link]]
 
-*** Level 3 with <em>emphasis</em>
+*** Level 3 with *emphasis*
 
 **** Level 4
 
@@ -19,7 +19,7 @@
 
 * Level 1
 
-** Level 2 with <em>emphasis</em>
+** Level 2 with *emphasis*
 
 *** Level 3
 
@@ -79,7 +79,7 @@
 </quote>
 </quote>
 
-This should not be a block quote: 2 <verbatim>></verbatim> 1.
+This should not be a block quote: 2 > 1.
 
 And a following paragraph.
 
@@ -224,9 +224,9 @@
     with a continuation
 
     iv. sublist with roman numerals, starting with 4
-    v.  more items
-        A. a subsublist
-        B. a subsublist
+    v. more items
+       A. a subsublist
+       B. a subsublist
 
 Nesting:
 
@@ -271,40 +271,37 @@
 
 Multiple blocks with italics:
 
- <em>apple</em> :: red fruit
+ *apple* :: red fruit
 
-                   contains seeds, crisp, pleasant to taste
- <em>orange</em> :: orange fruit
+            contains seeds, crisp, pleasant to taste
+ *orange* :: orange fruit
 
-                    <example>
-                    { orange code block }
-                    </example>
+             <example>
+             { orange code block }
+             </example>
 
-                    <quote>
-                    orange block quote
-                    </quote>
+             <quote>
+             orange block quote
+             </quote>
 
 Multiple definitions, tight:
 
  apple :: red fruit
-          computer
+       :: computer
  orange :: orange fruit
-           bank
+        :: bank
 
 Multiple definitions, loose:
 
  apple :: red fruit
-
-          computer
+       :: computer
  orange :: orange fruit
-
-           bank
+        :: bank
 
 Blank line after term, indented marker, alternate markers:
 
  apple :: red fruit
-
-          computer
+       :: computer
  orange :: orange fruit
 
            1. sublist
@@ -334,7 +331,7 @@
 <td>
 </literal>
 
-This is <em>emphasized</em>
+This is *emphasized*
 
 <literal style="html">
 </td>
@@ -344,7 +341,7 @@
 <td>
 </literal>
 
-And this is <strong>strong</strong>
+And this is **strong**
 
 <literal style="html">
 </td>
@@ -464,47 +461,45 @@
 
 * Inline Markup
 
-This is <em>emphasized</em>, and so <em>is this</em>.
+This is *emphasized*, and so *is this*.
 
-This is <strong>strong</strong>, and so <strong>is this</strong>.
+This is **strong**, and so **is this**.
 
-An <em>[[/url][emphasized link]]</em>.
+An *[[/url][emphasized link]]*.
 
-<strong><em>This is strong and em.</em></strong>
+***This is strong and em.***
 
-So is <strong><em>this</em></strong> word.
+So is ***this*** word.
 
-<strong><em>This is strong and em.</em></strong>
+***This is strong and em.***
 
-So is <strong><em>this</em></strong> word.
+So is ***this*** word.
 
-This is code: <code>></code>, <code>$</code>, <code>\</code>, <code>\$</code>,
-<code><html></code>.
+This is code: =>=, =$=, =\=, =\$=, =<html>=.
 
-<del>This is <em>strikeout</em>.</del>
+<del>This is *strikeout*.</del>
 
-Superscripts: a<sup>bc</sup>d a<sup><em>hello</em></sup>
-a<sup>hello there</sup>.
+Superscripts: a<sup>bc</sup>d a<sup>*hello*</sup> a<sup>hello there</sup>.
 
 Subscripts: H<sub>2</sub>O, H<sub>23</sub>O, H<sub>many of them</sub>O.
 
-These should not be superscripts or subscripts, because of the unescaped
-spaces: a^b c^d, a~b c~d.
+These should not be superscripts or subscripts, because of the unescaped spaces:
+a^b c^d, a~b c~d.
 
 ----
 
 * Smart quotes, ellipses, dashes
 
-"Hello," said the spider. "'Shelob' is my name."
+“Hello,” said the spider. “‘Shelob’ is my name.”
 
-'A', 'B', and 'C' are letters.
+‘A’, ‘B’, and ‘C’ are letters.
 
-'Oak,' 'elm,' and 'beech' are names of trees. So is 'pine.'
+‘Oak,’ ‘elm,’ and ‘beech’ are names of trees. So is ‘pine.’
 
-'He said, "I want to go."' Were you alive in the 70’s?
+‘He said, “I want to go.”’ Were you alive in the 70’s?
 
-Here is some quoted '<code>code</code>' and a
-"[[http://example.com/?foo=1&bar=2][quoted link]]".
+Here is some quoted ‘=code=’ and a “[[http://example.com/?foo=1&bar=2][quoted
+link]]”.
 
 Some dashes: one—two — three—four — five.
 
@@ -517,27 +512,26 @@
 * LaTeX
 
  - <literal style="tex">\cite[22-23]{smith.1899}</literal>
- - 2 + 2 <verbatim>=</verbatim> 4
- - <em>x</em> ∈ <em>y</em>
- - <em>α</em> ∧ <em>ω</em>
+ - <verbatim>2 + 2 = 4</verbatim>
+ - *x* ∈ *y*
+ - *α* ∧ *ω*
  - 223
- - <em>p</em>-Tree
+ - *p*-Tree
  - Here’s some display math:
-   <verse><verbatim>$$\frac{d}{dx}f(x)=\lim_{h\to 0}\frac{f(x+h)-f(x)}{h}$$</verbatim></verse>
- - Here’s one that has a line break in it:
-   <em>α</em> + <em>ω</em> × <em>x</em><sup>2</sup>.
+   <verbatim>$$\frac{d}{dx}f(x)=\lim_{h\to 0}\frac{f(x+h)-f(x)}{h}$$</verbatim>
+ - Here’s one that has a line break in it: *α* + *ω* × *x*<sup>2</sup>.
 
 These shouldn’t be math:
 
  - To get the famous equation, write <code>$e = mc^2$</code>.
- - $22,000 is a <em>lot</em> of money. So is $34,000. (It worked if "lot" is
+ - $22,000 is a *lot* of money. So is $34,000. (It worked if “lot” is
    emphasized.)
  - Shoes ($20) and socks ($5).
- - Escaped <code>$</code>: $73 <em>this should be emphasized</em> 23$.
+ - Escaped =$=: $73 *this should be emphasized* 23$.
 
 Here’s a LaTeX table:
 
-<literal style="latex">
+<literal style="tex">
 \begin{tabular}{|l|l|}\hline
 Animal & Number \\ \hline
 Dog    & 2      \\
@@ -565,7 +559,7 @@
 
 4 <verbatim><</verbatim> 5.
 
-6 <verbatim>></verbatim> 5.
+6 > 5.
 
 Backslash: \
 
@@ -579,15 +573,15 @@
 
 Right brace: }
 
-Left bracket: <verbatim>[</verbatim>
+Left bracket: [
 
-Right bracket: <verbatim>]</verbatim>
+Right bracket: ]
 
 Left paren: (
 
 Right paren: )
 
-Greater-than: <verbatim>></verbatim>
+Greater-than: >
 
 Hash: <verbatim>#</verbatim>
 
@@ -637,7 +631,7 @@
 
 Indented [[/url][thrice]].
 
-This should <verbatim>[not][]</verbatim> be a link.
+This should [not][] be a link.
 
 <example>
 [not]: /url
@@ -649,8 +643,7 @@
 
 ** With ampersands
 
-Here’s a [[http://example.com/?foo=1&bar=2][link with an ampersand in the
-URL]].
+Here’s a [[http://example.com/?foo=1&bar=2][link with an ampersand in the URL]].
 
 Here’s a link with an amersand in the link text: [[http://att.com/][AT&T]].
 
@@ -672,7 +665,7 @@
 Blockquoted: [[http://example.com/]]
 </quote>
 
-Auto-links should not occur here: <code><http://example.com/></code>
+Auto-links should not occur here: =<http://example.com/>=
 
 <example>
 or here: <http://example.com/>
@@ -682,19 +675,18 @@
 
 * Images
 
-From "Voyage dans la Lune" by Georges Melies (1902):
+From “Voyage dans la Lune” by Georges Melies (1902):
 
 [[lalune.jpg][Voyage dans la Lune]]
-
+lalune
 Here is a movie [[movie.jpg][movie]] icon.
 
 ----
 
 * Footnotes
 
-Here is a footnote reference,[1] and another.[2] This should <em>not</em> be a
-footnote reference, because it contains a <verbatim>space.[^my</verbatim>
-<verbatim>note]</verbatim> Here is an inline note.[3]
+Here is a footnote reference,[1] and another.[2] This should *not* be a footnote
+reference, because it contains a space.[^my note] Here is an inline note.[3]
 
 <quote>
 Notes can go in quotes.[4]
@@ -709,8 +701,8 @@
 
 [2] Here’s the long note. This one contains multiple blocks.
 
-    Subsequent blocks are indented to show that they belong to the footnote
-    (as with list items).
+    Subsequent blocks are indented to show that they belong to the footnote (as
+    with list items).
 
     <example>
       { <code> }
@@ -719,9 +711,9 @@
     If you want, you can indent every line, but you can also be lazy and just
     indent the first line of each block.
 
-[3] This is <em>easier</em> to type. Inline notes may contain
-    [[http://google.com][links]] and <code>]</code> verbatim characters, as
-    well as <verbatim>[bracketed</verbatim> <verbatim>text].</verbatim>
+[3] This is *easier* to type. Inline notes may contain
+    [[http://google.com][links]] and =]= verbatim characters, as well as
+    [bracketed text].
 
 [4] In quote.
 
diff --git a/test/writer.native b/test/writer.native
--- a/test/writer.native
+++ b/test/writer.native
@@ -1,409 +1,2170 @@
-Pandoc (Meta {unMeta = fromList [("author",MetaList [MetaInlines [Str "John",Space,Str "MacFarlane"],MetaInlines [Str "Anonymous"]]),("date",MetaInlines [Str "July",Space,Str "17,",Space,Str "2006"]),("title",MetaInlines [Str "Pandoc",Space,Str "Test",Space,Str "Suite"])]})
-[Para [Str "This",Space,Str "is",Space,Str "a",Space,Str "set",Space,Str "of",Space,Str "tests",Space,Str "for",Space,Str "pandoc.",Space,Str "Most",Space,Str "of",Space,Str "them",Space,Str "are",Space,Str "adapted",Space,Str "from",SoftBreak,Str "John",Space,Str "Gruber\8217s",Space,Str "markdown",Space,Str "test",Space,Str "suite."]
-,HorizontalRule
-,Header 1 ("headers",[],[]) [Str "Headers"]
-,Header 2 ("level-2-with-an-embedded-link",[],[]) [Str "Level",Space,Str "2",Space,Str "with",Space,Str "an",Space,Link ("",[],[]) [Str "embedded",Space,Str "link"] ("/url","")]
-,Header 3 ("level-3-with-emphasis",[],[]) [Str "Level",Space,Str "3",Space,Str "with",Space,Emph [Str "emphasis"]]
-,Header 4 ("level-4",[],[]) [Str "Level",Space,Str "4"]
-,Header 5 ("level-5",[],[]) [Str "Level",Space,Str "5"]
-,Header 1 ("level-1",[],[]) [Str "Level",Space,Str "1"]
-,Header 2 ("level-2-with-emphasis",[],[]) [Str "Level",Space,Str "2",Space,Str "with",Space,Emph [Str "emphasis"]]
-,Header 3 ("level-3",[],[]) [Str "Level",Space,Str "3"]
-,Para [Str "with",Space,Str "no",Space,Str "blank",Space,Str "line"]
-,Header 2 ("level-2",[],[]) [Str "Level",Space,Str "2"]
-,Para [Str "with",Space,Str "no",Space,Str "blank",Space,Str "line"]
-,HorizontalRule
-,Header 1 ("paragraphs",[],[]) [Str "Paragraphs"]
-,Para [Str "Here\8217s",Space,Str "a",Space,Str "regular",Space,Str "paragraph."]
-,Para [Str "In",Space,Str "Markdown",Space,Str "1.0.0",Space,Str "and",Space,Str "earlier.",Space,Str "Version",SoftBreak,Str "8.",Space,Str "This",Space,Str "line",Space,Str "turns",Space,Str "into",Space,Str "a",Space,Str "list",Space,Str "item.",SoftBreak,Str "Because",Space,Str "a",Space,Str "hard-wrapped",Space,Str "line",Space,Str "in",Space,Str "the",SoftBreak,Str "middle",Space,Str "of",Space,Str "a",Space,Str "paragraph",Space,Str "looked",Space,Str "like",Space,Str "a",SoftBreak,Str "list",Space,Str "item."]
-,Para [Str "Here\8217s",Space,Str "one",Space,Str "with",Space,Str "a",Space,Str "bullet.",SoftBreak,Str "*",Space,Str "criminey."]
-,Para [Str "There",Space,Str "should",Space,Str "be",Space,Str "a",Space,Str "hard",Space,Str "line",Space,Str "break",LineBreak,Str "here."]
-,HorizontalRule
-,Header 1 ("block-quotes",[],[]) [Str "Block",Space,Str "Quotes"]
-,Para [Str "E-mail",Space,Str "style:"]
-,BlockQuote
- [Para [Str "This",Space,Str "is",Space,Str "a",Space,Str "block",Space,Str "quote.",SoftBreak,Str "It",Space,Str "is",Space,Str "pretty",Space,Str "short."]]
-,BlockQuote
- [Para [Str "Code",Space,Str "in",Space,Str "a",Space,Str "block",Space,Str "quote:"]
- ,CodeBlock ("",[],[]) "sub status {\n    print \"working\";\n}"
- ,Para [Str "A",Space,Str "list:"]
- ,OrderedList (1,Decimal,Period)
-  [[Plain [Str "item",Space,Str "one"]]
-  ,[Plain [Str "item",Space,Str "two"]]]
- ,Para [Str "Nested",Space,Str "block",Space,Str "quotes:"]
- ,BlockQuote
-  [Para [Str "nested"]]
- ,BlockQuote
-  [Para [Str "nested"]]]
-,Para [Str "This",Space,Str "should",Space,Str "not",Space,Str "be",Space,Str "a",Space,Str "block",Space,Str "quote:",Space,Str "2",SoftBreak,Str ">",Space,Str "1."]
-,Para [Str "And",Space,Str "a",Space,Str "following",Space,Str "paragraph."]
-,HorizontalRule
-,Header 1 ("code-blocks",[],[]) [Str "Code",Space,Str "Blocks"]
-,Para [Str "Code:"]
-,CodeBlock ("",[],[]) "---- (should be four hyphens)\n\nsub status {\n    print \"working\";\n}\n\nthis code block is indented by one tab"
-,Para [Str "And:"]
-,CodeBlock ("",[],[]) "    this code block is indented by two tabs\n\nThese should not be escaped:  \\$ \\\\ \\> \\[ \\{"
-,HorizontalRule
-,Header 1 ("lists",[],[]) [Str "Lists"]
-,Header 2 ("unordered",[],[]) [Str "Unordered"]
-,Para [Str "Asterisks",Space,Str "tight:"]
-,BulletList
- [[Plain [Str "asterisk",Space,Str "1"]]
- ,[Plain [Str "asterisk",Space,Str "2"]]
- ,[Plain [Str "asterisk",Space,Str "3"]]]
-,Para [Str "Asterisks",Space,Str "loose:"]
-,BulletList
- [[Para [Str "asterisk",Space,Str "1"]]
- ,[Para [Str "asterisk",Space,Str "2"]]
- ,[Para [Str "asterisk",Space,Str "3"]]]
-,Para [Str "Pluses",Space,Str "tight:"]
-,BulletList
- [[Plain [Str "Plus",Space,Str "1"]]
- ,[Plain [Str "Plus",Space,Str "2"]]
- ,[Plain [Str "Plus",Space,Str "3"]]]
-,Para [Str "Pluses",Space,Str "loose:"]
-,BulletList
- [[Para [Str "Plus",Space,Str "1"]]
- ,[Para [Str "Plus",Space,Str "2"]]
- ,[Para [Str "Plus",Space,Str "3"]]]
-,Para [Str "Minuses",Space,Str "tight:"]
-,BulletList
- [[Plain [Str "Minus",Space,Str "1"]]
- ,[Plain [Str "Minus",Space,Str "2"]]
- ,[Plain [Str "Minus",Space,Str "3"]]]
-,Para [Str "Minuses",Space,Str "loose:"]
-,BulletList
- [[Para [Str "Minus",Space,Str "1"]]
- ,[Para [Str "Minus",Space,Str "2"]]
- ,[Para [Str "Minus",Space,Str "3"]]]
-,Header 2 ("ordered",[],[]) [Str "Ordered"]
-,Para [Str "Tight:"]
-,OrderedList (1,Decimal,Period)
- [[Plain [Str "First"]]
- ,[Plain [Str "Second"]]
- ,[Plain [Str "Third"]]]
-,Para [Str "and:"]
-,OrderedList (1,Decimal,Period)
- [[Plain [Str "One"]]
- ,[Plain [Str "Two"]]
- ,[Plain [Str "Three"]]]
-,Para [Str "Loose",Space,Str "using",Space,Str "tabs:"]
-,OrderedList (1,Decimal,Period)
- [[Para [Str "First"]]
- ,[Para [Str "Second"]]
- ,[Para [Str "Third"]]]
-,Para [Str "and",Space,Str "using",Space,Str "spaces:"]
-,OrderedList (1,Decimal,Period)
- [[Para [Str "One"]]
- ,[Para [Str "Two"]]
- ,[Para [Str "Three"]]]
-,Para [Str "Multiple",Space,Str "paragraphs:"]
-,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."]]
- ,[Para [Str "Item",Space,Str "2."]]
- ,[Para [Str "Item",Space,Str "3."]]]
-,Header 2 ("nested",[],[]) [Str "Nested"]
-,BulletList
- [[Plain [Str "Tab"]
-  ,BulletList
-   [[Plain [Str "Tab"]
-    ,BulletList
-     [[Plain [Str "Tab"]]]]]]]
-,Para [Str "Here\8217s",Space,Str "another:"]
-,OrderedList (1,Decimal,Period)
- [[Plain [Str "First"]]
- ,[Plain [Str "Second:"]
-  ,BulletList
-   [[Plain [Str "Fee"]]
-   ,[Plain [Str "Fie"]]
-   ,[Plain [Str "Foe"]]]]
- ,[Plain [Str "Third"]]]
-,Para [Str "Same",Space,Str "thing",Space,Str "but",Space,Str "with",Space,Str "paragraphs:"]
-,OrderedList (1,Decimal,Period)
- [[Para [Str "First"]]
- ,[Para [Str "Second:"]
-  ,BulletList
-   [[Plain [Str "Fee"]]
-   ,[Plain [Str "Fie"]]
-   ,[Plain [Str "Foe"]]]]
- ,[Para [Str "Third"]]]
-,Header 2 ("tabs-and-spaces",[],[]) [Str "Tabs",Space,Str "and",Space,Str "spaces"]
-,BulletList
- [[Para [Str "this",Space,Str "is",Space,Str "a",Space,Str "list",Space,Str "item",SoftBreak,Str "indented",Space,Str "with",Space,Str "tabs"]]
- ,[Para [Str "this",Space,Str "is",Space,Str "a",Space,Str "list",Space,Str "item",SoftBreak,Str "indented",Space,Str "with",Space,Str "spaces"]
-  ,BulletList
-   [[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 "tabs"]]
-   ,[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 "and",Space,Str "now",Space,Str "3"]
-  ,Para [Str "with",Space,Str "a",Space,Str "continuation"]
-  ,OrderedList (4,LowerRoman,Period)
-   [[Plain [Str "sublist",Space,Str "with",Space,Str "roman",Space,Str "numerals,",SoftBreak,Str "starting",Space,Str "with",Space,Str "4"]]
-   ,[Plain [Str "more",Space,Str "items"]
-    ,OrderedList (1,UpperAlpha,TwoParens)
-     [[Plain [Str "a",Space,Str "subsublist"]]
-     ,[Plain [Str "a",Space,Str "subsublist"]]]]]]]
-,Para [Str "Nesting:"]
-,OrderedList (1,UpperAlpha,Period)
- [[Plain [Str "Upper",Space,Str "Alpha"]
-  ,OrderedList (1,UpperRoman,Period)
-   [[Plain [Str "Upper",Space,Str "Roman."]
-    ,OrderedList (6,Decimal,TwoParens)
-     [[Plain [Str "Decimal",Space,Str "start",Space,Str "with",Space,Str "6"]
-      ,OrderedList (3,LowerAlpha,OneParen)
-       [[Plain [Str "Lower",Space,Str "alpha",Space,Str "with",Space,Str "paren"]]]]]]]]]
-,Para [Str "Autonumbering:"]
-,OrderedList (1,DefaultStyle,DefaultDelim)
- [[Plain [Str "Autonumber."]]
- ,[Plain [Str "More."]
-  ,OrderedList (1,DefaultStyle,DefaultDelim)
-   [[Plain [Str "Nested."]]]]]
-,Para [Str "Should",Space,Str "not",Space,Str "be",Space,Str "a",Space,Str "list",Space,Str "item:"]
-,Para [Str "M.A.\160\&2007"]
-,Para [Str "B.",Space,Str "Williams"]
-,HorizontalRule
-,Header 1 ("definition-lists",[],[]) [Str "Definition",Space,Str "Lists"]
-,Para [Str "Tight",Space,Str "using",Space,Str "spaces:"]
-,DefinitionList
- [([Str "apple"],
-   [[Plain [Str "red",Space,Str "fruit"]]])
- ,([Str "orange"],
-   [[Plain [Str "orange",Space,Str "fruit"]]])
- ,([Str "banana"],
-   [[Plain [Str "yellow",Space,Str "fruit"]]])]
-,Para [Str "Tight",Space,Str "using",Space,Str "tabs:"]
-,DefinitionList
- [([Str "apple"],
-   [[Plain [Str "red",Space,Str "fruit"]]])
- ,([Str "orange"],
-   [[Plain [Str "orange",Space,Str "fruit"]]])
- ,([Str "banana"],
-   [[Plain [Str "yellow",Space,Str "fruit"]]])]
-,Para [Str "Loose:"]
-,DefinitionList
- [([Str "apple"],
-   [[Para [Str "red",Space,Str "fruit"]]])
- ,([Str "orange"],
-   [[Para [Str "orange",Space,Str "fruit"]]])
- ,([Str "banana"],
-   [[Para [Str "yellow",Space,Str "fruit"]]])]
-,Para [Str "Multiple",Space,Str "blocks",Space,Str "with",Space,Str "italics:"]
-,DefinitionList
- [([Emph [Str "apple"]],
-   [[Para [Str "red",Space,Str "fruit"]
-    ,Para [Str "contains",Space,Str "seeds,",SoftBreak,Str "crisp,",Space,Str "pleasant",Space,Str "to",Space,Str "taste"]]])
- ,([Emph [Str "orange"]],
-   [[Para [Str "orange",Space,Str "fruit"]
-    ,CodeBlock ("",[],[]) "{ orange code block }"
-    ,BlockQuote
-     [Para [Str "orange",Space,Str "block",Space,Str "quote"]]]])]
-,Para [Str "Multiple",Space,Str "definitions,",Space,Str "tight:"]
-,DefinitionList
- [([Str "apple"],
-   [[Plain [Str "red",Space,Str "fruit"]]
-   ,[Plain [Str "computer"]]])
- ,([Str "orange"],
-   [[Plain [Str "orange",Space,Str "fruit"]]
-   ,[Plain [Str "bank"]]])]
-,Para [Str "Multiple",Space,Str "definitions,",Space,Str "loose:"]
-,DefinitionList
- [([Str "apple"],
-   [[Para [Str "red",Space,Str "fruit"]]
-   ,[Para [Str "computer"]]])
- ,([Str "orange"],
-   [[Para [Str "orange",Space,Str "fruit"]]
-   ,[Para [Str "bank"]]])]
-,Para [Str "Blank",Space,Str "line",Space,Str "after",Space,Str "term,",Space,Str "indented",Space,Str "marker,",Space,Str "alternate",Space,Str "markers:"]
-,DefinitionList
- [([Str "apple"],
-   [[Para [Str "red",Space,Str "fruit"]]
-   ,[Para [Str "computer"]]])
- ,([Str "orange"],
-   [[Para [Str "orange",Space,Str "fruit"]
-    ,OrderedList (1,Decimal,Period)
-     [[Plain [Str "sublist"]]
-     ,[Plain [Str "sublist"]]]]])]
-,Header 1 ("html-blocks",[],[]) [Str "HTML",Space,Str "Blocks"]
-,Para [Str "Simple",Space,Str "block",Space,Str "on",Space,Str "one",Space,Str "line:"]
-,Div ("",[],[])
- [Plain [Str "foo"]]
-,Para [Str "And",Space,Str "nested",Space,Str "without",Space,Str "indentation:"]
-,Div ("",[],[])
- [Div ("",[],[])
-  [Div ("",[],[])
-   [Para [Str "foo"]]]
- ,Div ("",[],[])
-  [Plain [Str "bar"]]]
-,Para [Str "Interpreted",Space,Str "markdown",Space,Str "in",Space,Str "a",Space,Str "table:"]
-,RawBlock (Format "html") "<table>"
-,RawBlock (Format "html") "<tr>"
-,RawBlock (Format "html") "<td>"
-,Plain [Str "This",Space,Str "is",Space,Emph [Str "emphasized"]]
-,RawBlock (Format "html") "</td>"
-,RawBlock (Format "html") "<td>"
-,Plain [Str "And",Space,Str "this",Space,Str "is",Space,Strong [Str "strong"]]
-,RawBlock (Format "html") "</td>"
-,RawBlock (Format "html") "</tr>"
-,RawBlock (Format "html") "</table>"
-,RawBlock (Format "html") "<script type=\"text/javascript\">document.write('This *should not* be interpreted as markdown');</script>"
-,Para [Str "Here\8217s",Space,Str "a",Space,Str "simple",Space,Str "block:"]
-,Div ("",[],[])
- [Para [Str "foo"]]
-,Para [Str "This",Space,Str "should",Space,Str "be",Space,Str "a",Space,Str "code",Space,Str "block,",Space,Str "though:"]
-,CodeBlock ("",[],[]) "<div>\n    foo\n</div>"
-,Para [Str "As",Space,Str "should",Space,Str "this:"]
-,CodeBlock ("",[],[]) "<div>foo</div>"
-,Para [Str "Now,",Space,Str "nested:"]
-,Div ("",[],[])
- [Div ("",[],[])
-  [Div ("",[],[])
-   [Plain [Str "foo"]]]]
-,Para [Str "This",Space,Str "should",Space,Str "just",Space,Str "be",Space,Str "an",Space,Str "HTML",Space,Str "comment:"]
-,RawBlock (Format "html") "<!-- Comment -->"
-,Para [Str "Multiline:"]
-,RawBlock (Format "html") "<!--\nBlah\nBlah\n-->"
-,RawBlock (Format "html") "<!--\n    This is another comment.\n-->"
-,Para [Str "Code",Space,Str "block:"]
-,CodeBlock ("",[],[]) "<!-- Comment -->"
-,Para [Str "Just",Space,Str "plain",Space,Str "comment,",Space,Str "with",Space,Str "trailing",Space,Str "spaces",Space,Str "on",Space,Str "the",Space,Str "line:"]
-,RawBlock (Format "html") "<!-- foo -->"
-,Para [Str "Code:"]
-,CodeBlock ("",[],[]) "<hr />"
-,Para [Str "Hr\8217s:"]
-,RawBlock (Format "html") "<hr>"
-,RawBlock (Format "html") "<hr />"
-,RawBlock (Format "html") "<hr />"
-,RawBlock (Format "html") "<hr>"
-,RawBlock (Format "html") "<hr />"
-,RawBlock (Format "html") "<hr />"
-,RawBlock (Format "html") "<hr class=\"foo\" id=\"bar\" />"
-,RawBlock (Format "html") "<hr class=\"foo\" id=\"bar\" />"
-,RawBlock (Format "html") "<hr class=\"foo\" id=\"bar\">"
-,HorizontalRule
-,Header 1 ("inline-markup",[],[]) [Str "Inline",Space,Str "Markup"]
-,Para [Str "This",Space,Str "is",Space,Emph [Str "emphasized"],Str ",",Space,Str "and",Space,Str "so",Space,Emph [Str "is",Space,Str "this"],Str "."]
-,Para [Str "This",Space,Str "is",Space,Strong [Str "strong"],Str ",",Space,Str "and",Space,Str "so",Space,Strong [Str "is",Space,Str "this"],Str "."]
-,Para [Str "An",Space,Emph [Link ("",[],[]) [Str "emphasized",Space,Str "link"] ("/url","")],Str "."]
-,Para [Strong [Emph [Str "This",Space,Str "is",Space,Str "strong",Space,Str "and",Space,Str "em."]]]
-,Para [Str "So",Space,Str "is",Space,Strong [Emph [Str "this"]],Space,Str "word."]
-,Para [Strong [Emph [Str "This",Space,Str "is",Space,Str "strong",Space,Str "and",Space,Str "em."]]]
-,Para [Str "So",Space,Str "is",Space,Strong [Emph [Str "this"]],Space,Str "word."]
-,Para [Str "This",Space,Str "is",Space,Str "code:",Space,Code ("",[],[]) ">",Str ",",Space,Code ("",[],[]) "$",Str ",",Space,Code ("",[],[]) "\\",Str ",",Space,Code ("",[],[]) "\\$",Str ",",Space,Code ("",[],[]) "<html>",Str "."]
-,Para [Strikeout [Str "This",Space,Str "is",Space,Emph [Str "strikeout"],Str "."]]
-,Para [Str "Superscripts:",Space,Str "a",Superscript [Str "bc"],Str "d",Space,Str "a",Superscript [Emph [Str "hello"]],Space,Str "a",Superscript [Str "hello\160there"],Str "."]
-,Para [Str "Subscripts:",Space,Str "H",Subscript [Str "2"],Str "O,",Space,Str "H",Subscript [Str "23"],Str "O,",Space,Str "H",Subscript [Str "many\160of\160them"],Str "O."]
-,Para [Str "These",Space,Str "should",Space,Str "not",Space,Str "be",Space,Str "superscripts",Space,Str "or",Space,Str "subscripts,",SoftBreak,Str "because",Space,Str "of",Space,Str "the",Space,Str "unescaped",Space,Str "spaces:",Space,Str "a^b",Space,Str "c^d,",Space,Str "a~b",Space,Str "c~d."]
-,HorizontalRule
-,Header 1 ("smart-quotes-ellipses-dashes",[],[]) [Str "Smart",Space,Str "quotes,",Space,Str "ellipses,",Space,Str "dashes"]
-,Para [Quoted DoubleQuote [Str "Hello,"],Space,Str "said",Space,Str "the",Space,Str "spider.",Space,Quoted DoubleQuote [Quoted SingleQuote [Str "Shelob"],Space,Str "is",Space,Str "my",Space,Str "name."]]
-,Para [Quoted SingleQuote [Str "A"],Str ",",Space,Quoted SingleQuote [Str "B"],Str ",",Space,Str "and",Space,Quoted SingleQuote [Str "C"],Space,Str "are",Space,Str "letters."]
-,Para [Quoted SingleQuote [Str "Oak,"],Space,Quoted SingleQuote [Str "elm,"],Space,Str "and",Space,Quoted SingleQuote [Str "beech"],Space,Str "are",Space,Str "names",Space,Str "of",Space,Str "trees.",SoftBreak,Str "So",Space,Str "is",Space,Quoted SingleQuote [Str "pine."]]
-,Para [Quoted SingleQuote [Str "He",Space,Str "said,",Space,Quoted DoubleQuote [Str "I",Space,Str "want",Space,Str "to",Space,Str "go."]],Space,Str "Were",Space,Str "you",Space,Str "alive",Space,Str "in",Space,Str "the",SoftBreak,Str "70\8217s?"]
-,Para [Str "Here",Space,Str "is",Space,Str "some",Space,Str "quoted",Space,Quoted SingleQuote [Code ("",[],[]) "code"],Space,Str "and",Space,Str "a",Space,Quoted DoubleQuote [Link ("",[],[]) [Str "quoted",Space,Str "link"] ("http://example.com/?foo=1&bar=2","")],Str "."]
-,Para [Str "Some",Space,Str "dashes:",Space,Str "one\8212two",Space,Str "\8212",Space,Str "three\8212four",Space,Str "\8212",Space,Str "five."]
-,Para [Str "Dashes",Space,Str "between",Space,Str "numbers:",Space,Str "5\8211\&7,",Space,Str "255\8211\&66,",Space,Str "1987\8211\&1999."]
-,Para [Str "Ellipses\8230and\8230and\8230."]
-,HorizontalRule
-,Header 1 ("latex",[],[]) [Str "LaTeX"]
-,BulletList
- [[Plain [RawInline (Format "tex") "\\cite[22-23]{smith.1899}"]]
- ,[Plain [Math InlineMath "2+2=4"]]
- ,[Plain [Math InlineMath "x \\in y"]]
- ,[Plain [Math InlineMath "\\alpha \\wedge \\omega"]]
- ,[Plain [Math InlineMath "223"]]
- ,[Plain [Math InlineMath "p",Str "-Tree"]]
- ,[Plain [Str "Here\8217s",Space,Str "some",Space,Str "display",Space,Str "math:",SoftBreak,Math DisplayMath "\\frac{d}{dx}f(x)=\\lim_{h\\to 0}\\frac{f(x+h)-f(x)}{h}"]]
- ,[Plain [Str "Here\8217s",Space,Str "one",Space,Str "that",Space,Str "has",Space,Str "a",Space,Str "line",Space,Str "break",Space,Str "in",Space,Str "it:",Space,Math InlineMath "\\alpha + \\omega \\times x^2",Str "."]]]
-,Para [Str "These",Space,Str "shouldn\8217t",Space,Str "be",Space,Str "math:"]
-,BulletList
- [[Plain [Str "To",Space,Str "get",Space,Str "the",Space,Str "famous",Space,Str "equation,",Space,Str "write",Space,Code ("",[],[]) "$e = mc^2$",Str "."]]
- ,[Plain [Str "$22,000",Space,Str "is",Space,Str "a",Space,Emph [Str "lot"],Space,Str "of",Space,Str "money.",Space,Str "So",Space,Str "is",Space,Str "$34,000.",SoftBreak,Str "(It",Space,Str "worked",Space,Str "if",Space,Quoted DoubleQuote [Str "lot"],Space,Str "is",Space,Str "emphasized.)"]]
- ,[Plain [Str "Shoes",Space,Str "($20)",Space,Str "and",Space,Str "socks",Space,Str "($5)."]]
- ,[Plain [Str "Escaped",Space,Code ("",[],[]) "$",Str ":",Space,Str "$73",Space,Emph [Str "this",Space,Str "should",Space,Str "be",Space,Str "emphasized"],Space,Str "23$."]]]
-,Para [Str "Here\8217s",Space,Str "a",Space,Str "LaTeX",Space,Str "table:"]
-,RawBlock (Format "latex") "\\begin{tabular}{|l|l|}\\hline\nAnimal & Number \\\\ \\hline\nDog    & 2      \\\\\nCat    & 1      \\\\ \\hline\n\\end{tabular}"
-,HorizontalRule
-,Header 1 ("special-characters",[],[]) [Str "Special",Space,Str "Characters"]
-,Para [Str "Here",Space,Str "is",Space,Str "some",Space,Str "unicode:"]
-,BulletList
- [[Plain [Str "I",Space,Str "hat:",Space,Str "\206"]]
- ,[Plain [Str "o",Space,Str "umlaut:",Space,Str "\246"]]
- ,[Plain [Str "section:",Space,Str "\167"]]
- ,[Plain [Str "set",Space,Str "membership:",Space,Str "\8712"]]
- ,[Plain [Str "copyright:",Space,Str "\169"]]]
-,Para [Str "AT&T",Space,Str "has",Space,Str "an",Space,Str "ampersand",Space,Str "in",Space,Str "their",Space,Str "name."]
-,Para [Str "AT&T",Space,Str "is",Space,Str "another",Space,Str "way",Space,Str "to",Space,Str "write",Space,Str "it."]
-,Para [Str "This",Space,Str "&",Space,Str "that."]
-,Para [Str "4",Space,Str "<",Space,Str "5."]
-,Para [Str "6",Space,Str ">",Space,Str "5."]
-,Para [Str "Backslash:",Space,Str "\\"]
-,Para [Str "Backtick:",Space,Str "`"]
-,Para [Str "Asterisk:",Space,Str "*"]
-,Para [Str "Underscore:",Space,Str "_"]
-,Para [Str "Left",Space,Str "brace:",Space,Str "{"]
-,Para [Str "Right",Space,Str "brace:",Space,Str "}"]
-,Para [Str "Left",Space,Str "bracket:",Space,Str "["]
-,Para [Str "Right",Space,Str "bracket:",Space,Str "]"]
-,Para [Str "Left",Space,Str "paren:",Space,Str "("]
-,Para [Str "Right",Space,Str "paren:",Space,Str ")"]
-,Para [Str "Greater-than:",Space,Str ">"]
-,Para [Str "Hash:",Space,Str "#"]
-,Para [Str "Period:",Space,Str "."]
-,Para [Str "Bang:",Space,Str "!"]
-,Para [Str "Plus:",Space,Str "+"]
-,Para [Str "Minus:",Space,Str "-"]
-,HorizontalRule
-,Header 1 ("links",[],[]) [Str "Links"]
-,Header 2 ("explicit",[],[]) [Str "Explicit"]
-,Para [Str "Just",Space,Str "a",Space,Link ("",[],[]) [Str "URL"] ("/url/",""),Str "."]
-,Para [Link ("",[],[]) [Str "URL",Space,Str "and",Space,Str "title"] ("/url/","title"),Str "."]
-,Para [Link ("",[],[]) [Str "URL",Space,Str "and",Space,Str "title"] ("/url/","title preceded by two spaces"),Str "."]
-,Para [Link ("",[],[]) [Str "URL",Space,Str "and",Space,Str "title"] ("/url/","title preceded by a tab"),Str "."]
-,Para [Link ("",[],[]) [Str "URL",Space,Str "and",Space,Str "title"] ("/url/","title with \"quotes\" in it")]
-,Para [Link ("",[],[]) [Str "URL",Space,Str "and",Space,Str "title"] ("/url/","title with single quotes")]
-,Para [Link ("",[],[]) [Str "with_underscore"] ("/url/with_underscore","")]
-,Para [Link ("",[],[]) [Str "Email",Space,Str "link"] ("mailto:nobody@nowhere.net","")]
-,Para [Link ("",[],[]) [Str "Empty"] ("",""),Str "."]
-,Header 2 ("reference",[],[]) [Str "Reference"]
-,Para [Str "Foo",Space,Link ("",[],[]) [Str "bar"] ("/url/",""),Str "."]
-,Para [Str "With",Space,Link ("",[],[]) [Str "embedded",Space,Str "[brackets]"] ("/url/",""),Str "."]
-,Para [Link ("",[],[]) [Str "b"] ("/url/",""),Space,Str "by",Space,Str "itself",Space,Str "should",Space,Str "be",Space,Str "a",Space,Str "link."]
-,Para [Str "Indented",Space,Link ("",[],[]) [Str "once"] ("/url",""),Str "."]
-,Para [Str "Indented",Space,Link ("",[],[]) [Str "twice"] ("/url",""),Str "."]
-,Para [Str "Indented",Space,Link ("",[],[]) [Str "thrice"] ("/url",""),Str "."]
-,Para [Str "This",Space,Str "should",Space,Str "[not][]",Space,Str "be",Space,Str "a",Space,Str "link."]
-,CodeBlock ("",[],[]) "[not]: /url"
-,Para [Str "Foo",Space,Link ("",[],[]) [Str "bar"] ("/url/","Title with \"quotes\" inside"),Str "."]
-,Para [Str "Foo",Space,Link ("",[],[]) [Str "biz"] ("/url/","Title with \"quote\" inside"),Str "."]
-,Header 2 ("with-ampersands",[],[]) [Str "With",Space,Str "ampersands"]
-,Para [Str "Here\8217s",Space,Str "a",Space,Link ("",[],[]) [Str "link",Space,Str "with",Space,Str "an",Space,Str "ampersand",Space,Str "in",Space,Str "the",Space,Str "URL"] ("http://example.com/?foo=1&bar=2",""),Str "."]
-,Para [Str "Here\8217s",Space,Str "a",Space,Str "link",Space,Str "with",Space,Str "an",Space,Str "amersand",Space,Str "in",Space,Str "the",Space,Str "link",Space,Str "text:",Space,Link ("",[],[]) [Str "AT&T"] ("http://att.com/","AT&T"),Str "."]
-,Para [Str "Here\8217s",Space,Str "an",Space,Link ("",[],[]) [Str "inline",Space,Str "link"] ("/script?foo=1&bar=2",""),Str "."]
-,Para [Str "Here\8217s",Space,Str "an",Space,Link ("",[],[]) [Str "inline",Space,Str "link",Space,Str "in",Space,Str "pointy",Space,Str "braces"] ("/script?foo=1&bar=2",""),Str "."]
-,Header 2 ("autolinks",[],[]) [Str "Autolinks"]
-,Para [Str "With",Space,Str "an",Space,Str "ampersand:",Space,Link ("",[],[]) [Str "http://example.com/?foo=1&bar=2"] ("http://example.com/?foo=1&bar=2","")]
-,BulletList
- [[Plain [Str "In",Space,Str "a",Space,Str "list?"]]
- ,[Plain [Link ("",[],[]) [Str "http://example.com/"] ("http://example.com/","")]]
- ,[Plain [Str "It",Space,Str "should."]]]
-,Para [Str "An",Space,Str "e-mail",Space,Str "address:",Space,Link ("",[],[]) [Str "nobody@nowhere.net"] ("mailto:nobody@nowhere.net","")]
-,BlockQuote
- [Para [Str "Blockquoted:",Space,Link ("",[],[]) [Str "http://example.com/"] ("http://example.com/","")]]
-,Para [Str "Auto-links",Space,Str "should",Space,Str "not",Space,Str "occur",Space,Str "here:",Space,Code ("",[],[]) "<http://example.com/>"]
-,CodeBlock ("",[],[]) "or here: <http://example.com/>"
-,HorizontalRule
-,Header 1 ("images",[],[]) [Str "Images"]
-,Para [Str "From",Space,Quoted DoubleQuote [Str "Voyage",Space,Str "dans",Space,Str "la",Space,Str "Lune"],Space,Str "by",Space,Str "Georges",Space,Str "Melies",Space,Str "(1902):"]
-,Para [Image ("",[],[]) [Str "lalune"] ("lalune.jpg","fig:Voyage dans la Lune")]
-,Para [Str "Here",Space,Str "is",Space,Str "a",Space,Str "movie",Space,Image ("",[],[]) [Str "movie"] ("movie.jpg",""),Space,Str "icon."]
-,HorizontalRule
-,Header 1 ("footnotes",[],[]) [Str "Footnotes"]
-,Para [Str "Here",Space,Str "is",Space,Str "a",Space,Str "footnote",Space,Str "reference,",Note [Para [Str "Here",Space,Str "is",Space,Str "the",Space,Str "footnote.",Space,Str "It",Space,Str "can",Space,Str "go",Space,Str "anywhere",Space,Str "after",Space,Str "the",Space,Str "footnote",SoftBreak,Str "reference.",Space,Str "It",Space,Str "need",Space,Str "not",Space,Str "be",Space,Str "placed",Space,Str "at",Space,Str "the",Space,Str "end",Space,Str "of",Space,Str "the",Space,Str "document."]],Space,Str "and",Space,Str "another.",Note [Para [Str "Here\8217s",Space,Str "the",Space,Str "long",Space,Str "note.",Space,Str "This",Space,Str "one",Space,Str "contains",Space,Str "multiple",SoftBreak,Str "blocks."],Para [Str "Subsequent",Space,Str "blocks",Space,Str "are",Space,Str "indented",Space,Str "to",Space,Str "show",Space,Str "that",Space,Str "they",Space,Str "belong",Space,Str "to",Space,Str "the",SoftBreak,Str "footnote",Space,Str "(as",Space,Str "with",Space,Str "list",Space,Str "items)."],CodeBlock ("",[],[]) "  { <code> }",Para [Str "If",Space,Str "you",Space,Str "want,",Space,Str "you",Space,Str "can",Space,Str "indent",Space,Str "every",Space,Str "line,",Space,Str "but",Space,Str "you",Space,Str "can",Space,Str "also",Space,Str "be",SoftBreak,Str "lazy",Space,Str "and",Space,Str "just",Space,Str "indent",Space,Str "the",Space,Str "first",Space,Str "line",Space,Str "of",Space,Str "each",Space,Str "block."]],SoftBreak,Str "This",Space,Str "should",Space,Emph [Str "not"],Space,Str "be",Space,Str "a",Space,Str "footnote",Space,Str "reference,",Space,Str "because",Space,Str "it",SoftBreak,Str "contains",Space,Str "a",Space,Str "space.[^my",Space,Str "note]",Space,Str "Here",Space,Str "is",Space,Str "an",Space,Str "inline",Space,Str "note.",Note [Para [Str "This",SoftBreak,Str "is",Space,Emph [Str "easier"],Space,Str "to",Space,Str "type.",Space,Str "Inline",Space,Str "notes",Space,Str "may",Space,Str "contain",SoftBreak,Link ("",[],[]) [Str "links"] ("http://google.com",""),Space,Str "and",Space,Code ("",[],[]) "]",Space,Str "verbatim",Space,Str "characters,",SoftBreak,Str "as",Space,Str "well",Space,Str "as",Space,Str "[bracketed",Space,Str "text]."]]]
-,BlockQuote
- [Para [Str "Notes",Space,Str "can",Space,Str "go",Space,Str "in",Space,Str "quotes.",Note [Para [Str "In",Space,Str "quote."]]]]
-,OrderedList (1,Decimal,Period)
- [[Plain [Str "And",Space,Str "in",Space,Str "list",Space,Str "items.",Note [Para [Str "In",Space,Str "list."]]]]]
-,Para [Str "This",Space,Str "paragraph",Space,Str "should",Space,Str "not",Space,Str "be",Space,Str "part",Space,Str "of",Space,Str "the",Space,Str "note,",Space,Str "as",Space,Str "it",Space,Str "is",Space,Str "not",Space,Str "indented."]]
+Pandoc
+  Meta
+    { unMeta =
+        fromList
+          [ ( "author"
+            , MetaList
+                [ MetaInlines [ Str "John" , Space , Str "MacFarlane" ]
+                , MetaInlines [ Str "Anonymous" ]
+                ]
+            )
+          , ( "date"
+            , MetaInlines
+                [ Str "July" , Space , Str "17," , Space , Str "2006" ]
+            )
+          , ( "title"
+            , MetaInlines
+                [ Str "Pandoc" , Space , Str "Test" , Space , Str "Suite" ]
+            )
+          ]
+    }
+  [ Para
+      [ Str "This"
+      , Space
+      , Str "is"
+      , Space
+      , Str "a"
+      , Space
+      , Str "set"
+      , Space
+      , Str "of"
+      , Space
+      , Str "tests"
+      , Space
+      , Str "for"
+      , Space
+      , Str "pandoc."
+      , Space
+      , Str "Most"
+      , Space
+      , Str "of"
+      , Space
+      , Str "them"
+      , Space
+      , Str "are"
+      , Space
+      , Str "adapted"
+      , Space
+      , Str "from"
+      , SoftBreak
+      , Str "John"
+      , Space
+      , Str "Gruber\8217s"
+      , Space
+      , Str "markdown"
+      , Space
+      , Str "test"
+      , Space
+      , Str "suite."
+      ]
+  , HorizontalRule
+  , Header 1 ( "headers" , [] , [] ) [ Str "Headers" ]
+  , Header
+      2
+      ( "level-2-with-an-embedded-link" , [] , [] )
+      [ Str "Level"
+      , Space
+      , Str "2"
+      , Space
+      , Str "with"
+      , Space
+      , Str "an"
+      , Space
+      , Link
+          ( "" , [] , [] )
+          [ Str "embedded" , Space , Str "link" ]
+          ( "/url" , "" )
+      ]
+  , Header
+      3
+      ( "level-3-with-emphasis" , [] , [] )
+      [ Str "Level"
+      , Space
+      , Str "3"
+      , Space
+      , Str "with"
+      , Space
+      , Emph [ Str "emphasis" ]
+      ]
+  , Header
+      4 ( "level-4" , [] , [] ) [ Str "Level" , Space , Str "4" ]
+  , Header
+      5 ( "level-5" , [] , [] ) [ Str "Level" , Space , Str "5" ]
+  , Header
+      1 ( "level-1" , [] , [] ) [ Str "Level" , Space , Str "1" ]
+  , Header
+      2
+      ( "level-2-with-emphasis" , [] , [] )
+      [ Str "Level"
+      , Space
+      , Str "2"
+      , Space
+      , Str "with"
+      , Space
+      , Emph [ Str "emphasis" ]
+      ]
+  , Header
+      3 ( "level-3" , [] , [] ) [ Str "Level" , Space , Str "3" ]
+  , Para
+      [ Str "with"
+      , Space
+      , Str "no"
+      , Space
+      , Str "blank"
+      , Space
+      , Str "line"
+      ]
+  , Header
+      2 ( "level-2" , [] , [] ) [ Str "Level" , Space , Str "2" ]
+  , Para
+      [ Str "with"
+      , Space
+      , Str "no"
+      , Space
+      , Str "blank"
+      , Space
+      , Str "line"
+      ]
+  , HorizontalRule
+  , Header 1 ( "paragraphs" , [] , [] ) [ Str "Paragraphs" ]
+  , Para
+      [ Str "Here\8217s"
+      , Space
+      , Str "a"
+      , Space
+      , Str "regular"
+      , Space
+      , Str "paragraph."
+      ]
+  , Para
+      [ Str "In"
+      , Space
+      , Str "Markdown"
+      , Space
+      , Str "1.0.0"
+      , Space
+      , Str "and"
+      , Space
+      , Str "earlier."
+      , Space
+      , Str "Version"
+      , SoftBreak
+      , Str "8."
+      , Space
+      , Str "This"
+      , Space
+      , Str "line"
+      , Space
+      , Str "turns"
+      , Space
+      , Str "into"
+      , Space
+      , Str "a"
+      , Space
+      , Str "list"
+      , Space
+      , Str "item."
+      , SoftBreak
+      , Str "Because"
+      , Space
+      , Str "a"
+      , Space
+      , Str "hard-wrapped"
+      , Space
+      , Str "line"
+      , Space
+      , Str "in"
+      , Space
+      , Str "the"
+      , SoftBreak
+      , Str "middle"
+      , Space
+      , Str "of"
+      , Space
+      , Str "a"
+      , Space
+      , Str "paragraph"
+      , Space
+      , Str "looked"
+      , Space
+      , Str "like"
+      , Space
+      , Str "a"
+      , SoftBreak
+      , Str "list"
+      , Space
+      , Str "item."
+      ]
+  , Para
+      [ Str "Here\8217s"
+      , Space
+      , Str "one"
+      , Space
+      , Str "with"
+      , Space
+      , Str "a"
+      , Space
+      , Str "bullet."
+      , SoftBreak
+      , Str "*"
+      , Space
+      , Str "criminey."
+      ]
+  , Para
+      [ Str "There"
+      , Space
+      , Str "should"
+      , Space
+      , Str "be"
+      , Space
+      , Str "a"
+      , Space
+      , Str "hard"
+      , Space
+      , Str "line"
+      , Space
+      , Str "break"
+      , LineBreak
+      , Str "here."
+      ]
+  , HorizontalRule
+  , Header
+      1
+      ( "block-quotes" , [] , [] )
+      [ Str "Block" , Space , Str "Quotes" ]
+  , Para [ Str "E-mail" , Space , Str "style:" ]
+  , BlockQuote
+      [ Para
+          [ Str "This"
+          , Space
+          , Str "is"
+          , Space
+          , Str "a"
+          , Space
+          , Str "block"
+          , Space
+          , Str "quote."
+          , SoftBreak
+          , Str "It"
+          , Space
+          , Str "is"
+          , Space
+          , Str "pretty"
+          , Space
+          , Str "short."
+          ]
+      ]
+  , BlockQuote
+      [ Para
+          [ Str "Code"
+          , Space
+          , Str "in"
+          , Space
+          , Str "a"
+          , Space
+          , Str "block"
+          , Space
+          , Str "quote:"
+          ]
+      , CodeBlock
+          ( "" , [] , [] ) "sub status {\n    print \"working\";\n}"
+      , Para [ Str "A" , Space , Str "list:" ]
+      , OrderedList
+          ( 1 , Decimal , Period )
+          [ [ Plain [ Str "item" , Space , Str "one" ] ]
+          , [ Plain [ Str "item" , Space , Str "two" ] ]
+          ]
+      , Para
+          [ Str "Nested" , Space , Str "block" , Space , Str "quotes:" ]
+      , BlockQuote [ Para [ Str "nested" ] ]
+      , BlockQuote [ Para [ Str "nested" ] ]
+      ]
+  , Para
+      [ Str "This"
+      , Space
+      , Str "should"
+      , Space
+      , Str "not"
+      , Space
+      , Str "be"
+      , Space
+      , Str "a"
+      , Space
+      , Str "block"
+      , Space
+      , Str "quote:"
+      , Space
+      , Str "2"
+      , SoftBreak
+      , Str ">"
+      , Space
+      , Str "1."
+      ]
+  , Para
+      [ Str "And"
+      , Space
+      , Str "a"
+      , Space
+      , Str "following"
+      , Space
+      , Str "paragraph."
+      ]
+  , HorizontalRule
+  , Header
+      1 ( "code-blocks" , [] , [] ) [ Str "Code" , Space , Str "Blocks" ]
+  , Para [ Str "Code:" ]
+  , CodeBlock
+      ( "" , [] , [] )
+      "---- (should be four hyphens)\n\nsub status {\n    print \"working\";\n}\n\nthis code block is indented by one tab"
+  , Para [ Str "And:" ]
+  , CodeBlock
+      ( "" , [] , [] )
+      "    this code block is indented by two tabs\n\nThese should not be escaped:  \\$ \\\\ \\> \\[ \\{"
+  , HorizontalRule
+  , Header 1 ( "lists" , [] , [] ) [ Str "Lists" ]
+  , Header 2 ( "unordered" , [] , [] ) [ Str "Unordered" ]
+  , Para [ Str "Asterisks" , Space , Str "tight:" ]
+  , BulletList
+      [ [ Plain [ Str "asterisk" , Space , Str "1" ] ]
+      , [ Plain [ Str "asterisk" , Space , Str "2" ] ]
+      , [ Plain [ Str "asterisk" , Space , Str "3" ] ]
+      ]
+  , Para [ Str "Asterisks" , Space , Str "loose:" ]
+  , BulletList
+      [ [ Para [ Str "asterisk" , Space , Str "1" ] ]
+      , [ Para [ Str "asterisk" , Space , Str "2" ] ]
+      , [ Para [ Str "asterisk" , Space , Str "3" ] ]
+      ]
+  , Para [ Str "Pluses" , Space , Str "tight:" ]
+  , BulletList
+      [ [ Plain [ Str "Plus" , Space , Str "1" ] ]
+      , [ Plain [ Str "Plus" , Space , Str "2" ] ]
+      , [ Plain [ Str "Plus" , Space , Str "3" ] ]
+      ]
+  , Para [ Str "Pluses" , Space , Str "loose:" ]
+  , BulletList
+      [ [ Para [ Str "Plus" , Space , Str "1" ] ]
+      , [ Para [ Str "Plus" , Space , Str "2" ] ]
+      , [ Para [ Str "Plus" , Space , Str "3" ] ]
+      ]
+  , Para [ Str "Minuses" , Space , Str "tight:" ]
+  , BulletList
+      [ [ Plain [ Str "Minus" , Space , Str "1" ] ]
+      , [ Plain [ Str "Minus" , Space , Str "2" ] ]
+      , [ Plain [ Str "Minus" , Space , Str "3" ] ]
+      ]
+  , Para [ Str "Minuses" , Space , Str "loose:" ]
+  , BulletList
+      [ [ Para [ Str "Minus" , Space , Str "1" ] ]
+      , [ Para [ Str "Minus" , Space , Str "2" ] ]
+      , [ Para [ Str "Minus" , Space , Str "3" ] ]
+      ]
+  , Header 2 ( "ordered" , [] , [] ) [ Str "Ordered" ]
+  , Para [ Str "Tight:" ]
+  , OrderedList
+      ( 1 , Decimal , Period )
+      [ [ Plain [ Str "First" ] ]
+      , [ Plain [ Str "Second" ] ]
+      , [ Plain [ Str "Third" ] ]
+      ]
+  , Para [ Str "and:" ]
+  , OrderedList
+      ( 1 , Decimal , Period )
+      [ [ Plain [ Str "One" ] ]
+      , [ Plain [ Str "Two" ] ]
+      , [ Plain [ Str "Three" ] ]
+      ]
+  , Para [ Str "Loose" , Space , Str "using" , Space , Str "tabs:" ]
+  , OrderedList
+      ( 1 , Decimal , Period )
+      [ [ Para [ Str "First" ] ]
+      , [ Para [ Str "Second" ] ]
+      , [ Para [ Str "Third" ] ]
+      ]
+  , Para [ Str "and" , Space , Str "using" , Space , Str "spaces:" ]
+  , OrderedList
+      ( 1 , Decimal , Period )
+      [ [ Para [ Str "One" ] ]
+      , [ Para [ Str "Two" ] ]
+      , [ Para [ Str "Three" ] ]
+      ]
+  , Para [ Str "Multiple" , Space , Str "paragraphs:" ]
+  , 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."
+            ]
+        ]
+      , [ Para [ Str "Item" , Space , Str "2." ] ]
+      , [ Para [ Str "Item" , Space , Str "3." ] ]
+      ]
+  , Header 2 ( "nested" , [] , [] ) [ Str "Nested" ]
+  , BulletList
+      [ [ Plain [ Str "Tab" ]
+        , BulletList
+            [ [ Plain [ Str "Tab" ] , BulletList [ [ Plain [ Str "Tab" ] ] ] ]
+            ]
+        ]
+      ]
+  , Para [ Str "Here\8217s" , Space , Str "another:" ]
+  , OrderedList
+      ( 1 , Decimal , Period )
+      [ [ Plain [ Str "First" ] ]
+      , [ Plain [ Str "Second:" ]
+        , BulletList
+            [ [ Plain [ Str "Fee" ] ]
+            , [ Plain [ Str "Fie" ] ]
+            , [ Plain [ Str "Foe" ] ]
+            ]
+        ]
+      , [ Plain [ Str "Third" ] ]
+      ]
+  , Para
+      [ Str "Same"
+      , Space
+      , Str "thing"
+      , Space
+      , Str "but"
+      , Space
+      , Str "with"
+      , Space
+      , Str "paragraphs:"
+      ]
+  , OrderedList
+      ( 1 , Decimal , Period )
+      [ [ Para [ Str "First" ] ]
+      , [ Para [ Str "Second:" ]
+        , BulletList
+            [ [ Plain [ Str "Fee" ] ]
+            , [ Plain [ Str "Fie" ] ]
+            , [ Plain [ Str "Foe" ] ]
+            ]
+        ]
+      , [ Para [ Str "Third" ] ]
+      ]
+  , Header
+      2
+      ( "tabs-and-spaces" , [] , [] )
+      [ Str "Tabs" , Space , Str "and" , Space , Str "spaces" ]
+  , BulletList
+      [ [ Para
+            [ Str "this"
+            , Space
+            , Str "is"
+            , Space
+            , Str "a"
+            , Space
+            , Str "list"
+            , Space
+            , Str "item"
+            , SoftBreak
+            , Str "indented"
+            , Space
+            , Str "with"
+            , Space
+            , Str "tabs"
+            ]
+        ]
+      , [ Para
+            [ Str "this"
+            , Space
+            , Str "is"
+            , Space
+            , Str "a"
+            , Space
+            , Str "list"
+            , Space
+            , Str "item"
+            , SoftBreak
+            , Str "indented"
+            , Space
+            , Str "with"
+            , Space
+            , Str "spaces"
+            ]
+        , BulletList
+            [ [ 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 "tabs"
+                  ]
+              ]
+            , [ 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 )
+      [ [ 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 )
+            [ [ Plain
+                  [ Str "sublist"
+                  , Space
+                  , Str "with"
+                  , Space
+                  , Str "roman"
+                  , Space
+                  , Str "numerals,"
+                  , SoftBreak
+                  , Str "starting"
+                  , Space
+                  , Str "with"
+                  , Space
+                  , Str "4"
+                  ]
+              ]
+            , [ Plain [ Str "more" , Space , Str "items" ]
+              , OrderedList
+                  ( 1 , UpperAlpha , TwoParens )
+                  [ [ Plain [ Str "a" , Space , Str "subsublist" ] ]
+                  , [ Plain [ Str "a" , Space , Str "subsublist" ] ]
+                  ]
+              ]
+            ]
+        ]
+      ]
+  , Para [ Str "Nesting:" ]
+  , OrderedList
+      ( 1 , UpperAlpha , Period )
+      [ [ Plain [ Str "Upper" , Space , Str "Alpha" ]
+        , OrderedList
+            ( 1 , UpperRoman , Period )
+            [ [ Plain [ Str "Upper" , Space , Str "Roman." ]
+              , OrderedList
+                  ( 6 , Decimal , TwoParens )
+                  [ [ Plain
+                        [ Str "Decimal"
+                        , Space
+                        , Str "start"
+                        , Space
+                        , Str "with"
+                        , Space
+                        , Str "6"
+                        ]
+                    , OrderedList
+                        ( 3 , LowerAlpha , OneParen )
+                        [ [ Plain
+                              [ Str "Lower"
+                              , Space
+                              , Str "alpha"
+                              , Space
+                              , Str "with"
+                              , Space
+                              , Str "paren"
+                              ]
+                          ]
+                        ]
+                    ]
+                  ]
+              ]
+            ]
+        ]
+      ]
+  , Para [ Str "Autonumbering:" ]
+  , OrderedList
+      ( 1 , DefaultStyle , DefaultDelim )
+      [ [ Plain [ Str "Autonumber." ] ]
+      , [ Plain [ Str "More." ]
+        , OrderedList
+            ( 1 , DefaultStyle , DefaultDelim ) [ [ Plain [ Str "Nested." ] ] ]
+        ]
+      ]
+  , Para
+      [ Str "Should"
+      , Space
+      , Str "not"
+      , Space
+      , Str "be"
+      , Space
+      , Str "a"
+      , Space
+      , Str "list"
+      , Space
+      , Str "item:"
+      ]
+  , Para [ Str "M.A.\160\&2007" ]
+  , Para [ Str "B." , Space , Str "Williams" ]
+  , HorizontalRule
+  , Header
+      1
+      ( "definition-lists" , [] , [] )
+      [ Str "Definition" , Space , Str "Lists" ]
+  , Para
+      [ Str "Tight" , Space , Str "using" , Space , Str "spaces:" ]
+  , DefinitionList
+      [ ( [ Str "apple" ]
+        , [ [ Plain [ Str "red" , Space , Str "fruit" ] ] ]
+        )
+      , ( [ Str "orange" ]
+        , [ [ Plain [ Str "orange" , Space , Str "fruit" ] ] ]
+        )
+      , ( [ Str "banana" ]
+        , [ [ Plain [ Str "yellow" , Space , Str "fruit" ] ] ]
+        )
+      ]
+  , Para [ Str "Tight" , Space , Str "using" , Space , Str "tabs:" ]
+  , DefinitionList
+      [ ( [ Str "apple" ]
+        , [ [ Plain [ Str "red" , Space , Str "fruit" ] ] ]
+        )
+      , ( [ Str "orange" ]
+        , [ [ Plain [ Str "orange" , Space , Str "fruit" ] ] ]
+        )
+      , ( [ Str "banana" ]
+        , [ [ Plain [ Str "yellow" , Space , Str "fruit" ] ] ]
+        )
+      ]
+  , Para [ Str "Loose:" ]
+  , DefinitionList
+      [ ( [ Str "apple" ]
+        , [ [ Para [ Str "red" , Space , Str "fruit" ] ] ]
+        )
+      , ( [ Str "orange" ]
+        , [ [ Para [ Str "orange" , Space , Str "fruit" ] ] ]
+        )
+      , ( [ Str "banana" ]
+        , [ [ Para [ Str "yellow" , Space , Str "fruit" ] ] ]
+        )
+      ]
+  , Para
+      [ Str "Multiple"
+      , Space
+      , Str "blocks"
+      , Space
+      , Str "with"
+      , Space
+      , Str "italics:"
+      ]
+  , DefinitionList
+      [ ( [ Emph [ Str "apple" ] ]
+        , [ [ Para [ Str "red" , Space , Str "fruit" ]
+            , Para
+                [ Str "contains"
+                , Space
+                , Str "seeds,"
+                , SoftBreak
+                , Str "crisp,"
+                , Space
+                , Str "pleasant"
+                , Space
+                , Str "to"
+                , Space
+                , Str "taste"
+                ]
+            ]
+          ]
+        )
+      , ( [ Emph [ Str "orange" ] ]
+        , [ [ Para [ Str "orange" , Space , Str "fruit" ]
+            , CodeBlock ( "" , [] , [] ) "{ orange code block }"
+            , BlockQuote
+                [ Para
+                    [ Str "orange" , Space , Str "block" , Space , Str "quote" ]
+                ]
+            ]
+          ]
+        )
+      ]
+  , Para
+      [ Str "Multiple"
+      , Space
+      , Str "definitions,"
+      , Space
+      , Str "tight:"
+      ]
+  , DefinitionList
+      [ ( [ Str "apple" ]
+        , [ [ Plain [ Str "red" , Space , Str "fruit" ] ]
+          , [ Plain [ Str "computer" ] ]
+          ]
+        )
+      , ( [ Str "orange" ]
+        , [ [ Plain [ Str "orange" , Space , Str "fruit" ] ]
+          , [ Plain [ Str "bank" ] ]
+          ]
+        )
+      ]
+  , Para
+      [ Str "Multiple"
+      , Space
+      , Str "definitions,"
+      , Space
+      , Str "loose:"
+      ]
+  , DefinitionList
+      [ ( [ Str "apple" ]
+        , [ [ Para [ Str "red" , Space , Str "fruit" ] ]
+          , [ Para [ Str "computer" ] ]
+          ]
+        )
+      , ( [ Str "orange" ]
+        , [ [ Para [ Str "orange" , Space , Str "fruit" ] ]
+          , [ Para [ Str "bank" ] ]
+          ]
+        )
+      ]
+  , Para
+      [ Str "Blank"
+      , Space
+      , Str "line"
+      , Space
+      , Str "after"
+      , Space
+      , Str "term,"
+      , Space
+      , Str "indented"
+      , Space
+      , Str "marker,"
+      , Space
+      , Str "alternate"
+      , Space
+      , Str "markers:"
+      ]
+  , DefinitionList
+      [ ( [ Str "apple" ]
+        , [ [ Para [ Str "red" , Space , Str "fruit" ] ]
+          , [ Para [ Str "computer" ] ]
+          ]
+        )
+      , ( [ Str "orange" ]
+        , [ [ Para [ Str "orange" , Space , Str "fruit" ]
+            , OrderedList
+                ( 1 , Decimal , Period )
+                [ [ Plain [ Str "sublist" ] ] , [ Plain [ Str "sublist" ] ] ]
+            ]
+          ]
+        )
+      ]
+  , Header
+      1 ( "html-blocks" , [] , [] ) [ Str "HTML" , Space , Str "Blocks" ]
+  , Para
+      [ Str "Simple"
+      , Space
+      , Str "block"
+      , Space
+      , Str "on"
+      , Space
+      , Str "one"
+      , Space
+      , Str "line:"
+      ]
+  , Div ( "" , [] , [] ) [ Plain [ Str "foo" ] ]
+  , Para
+      [ Str "And"
+      , Space
+      , Str "nested"
+      , Space
+      , Str "without"
+      , Space
+      , Str "indentation:"
+      ]
+  , Div
+      ( "" , [] , [] )
+      [ Div
+          ( "" , [] , [] ) [ Div ( "" , [] , [] ) [ Para [ Str "foo" ] ] ]
+      , Div ( "" , [] , [] ) [ Plain [ Str "bar" ] ]
+      ]
+  , Para
+      [ Str "Interpreted"
+      , Space
+      , Str "markdown"
+      , Space
+      , Str "in"
+      , Space
+      , Str "a"
+      , Space
+      , Str "table:"
+      ]
+  , RawBlock (Format "html") "<table>"
+  , RawBlock (Format "html") "<tr>"
+  , RawBlock (Format "html") "<td>"
+  , Plain
+      [ Str "This"
+      , Space
+      , Str "is"
+      , Space
+      , Emph [ Str "emphasized" ]
+      ]
+  , RawBlock (Format "html") "</td>"
+  , RawBlock (Format "html") "<td>"
+  , Plain
+      [ Str "And"
+      , Space
+      , Str "this"
+      , Space
+      , Str "is"
+      , Space
+      , Strong [ Str "strong" ]
+      ]
+  , RawBlock (Format "html") "</td>"
+  , RawBlock (Format "html") "</tr>"
+  , RawBlock (Format "html") "</table>"
+  , RawBlock
+      (Format "html")
+      "<script type=\"text/javascript\">document.write('This *should not* be interpreted as markdown');</script>"
+  , Para
+      [ Str "Here\8217s"
+      , Space
+      , Str "a"
+      , Space
+      , Str "simple"
+      , Space
+      , Str "block:"
+      ]
+  , Div ( "" , [] , [] ) [ Para [ Str "foo" ] ]
+  , Para
+      [ Str "This"
+      , Space
+      , Str "should"
+      , Space
+      , Str "be"
+      , Space
+      , Str "a"
+      , Space
+      , Str "code"
+      , Space
+      , Str "block,"
+      , Space
+      , Str "though:"
+      ]
+  , CodeBlock ( "" , [] , [] ) "<div>\n    foo\n</div>"
+  , Para [ Str "As" , Space , Str "should" , Space , Str "this:" ]
+  , CodeBlock ( "" , [] , [] ) "<div>foo</div>"
+  , Para [ Str "Now," , Space , Str "nested:" ]
+  , Div
+      ( "" , [] , [] )
+      [ Div
+          ( "" , [] , [] ) [ Div ( "" , [] , [] ) [ Plain [ Str "foo" ] ] ]
+      ]
+  , Para
+      [ Str "This"
+      , Space
+      , Str "should"
+      , Space
+      , Str "just"
+      , Space
+      , Str "be"
+      , Space
+      , Str "an"
+      , Space
+      , Str "HTML"
+      , Space
+      , Str "comment:"
+      ]
+  , RawBlock (Format "html") "<!-- Comment -->"
+  , Para [ Str "Multiline:" ]
+  , RawBlock (Format "html") "<!--\nBlah\nBlah\n-->"
+  , RawBlock
+      (Format "html") "<!--\n    This is another comment.\n-->"
+  , Para [ Str "Code" , Space , Str "block:" ]
+  , CodeBlock ( "" , [] , [] ) "<!-- Comment -->"
+  , Para
+      [ Str "Just"
+      , Space
+      , Str "plain"
+      , Space
+      , Str "comment,"
+      , Space
+      , Str "with"
+      , Space
+      , Str "trailing"
+      , Space
+      , Str "spaces"
+      , Space
+      , Str "on"
+      , Space
+      , Str "the"
+      , Space
+      , Str "line:"
+      ]
+  , RawBlock (Format "html") "<!-- foo -->"
+  , Para [ Str "Code:" ]
+  , CodeBlock ( "" , [] , [] ) "<hr />"
+  , Para [ Str "Hr\8217s:" ]
+  , RawBlock (Format "html") "<hr>"
+  , RawBlock (Format "html") "<hr />"
+  , RawBlock (Format "html") "<hr />"
+  , RawBlock (Format "html") "<hr>"
+  , RawBlock (Format "html") "<hr />"
+  , RawBlock (Format "html") "<hr />"
+  , RawBlock (Format "html") "<hr class=\"foo\" id=\"bar\" />"
+  , RawBlock (Format "html") "<hr class=\"foo\" id=\"bar\" />"
+  , RawBlock (Format "html") "<hr class=\"foo\" id=\"bar\">"
+  , HorizontalRule
+  , Header
+      1
+      ( "inline-markup" , [] , [] )
+      [ Str "Inline" , Space , Str "Markup" ]
+  , Para
+      [ Str "This"
+      , Space
+      , Str "is"
+      , Space
+      , Emph [ Str "emphasized" ]
+      , Str ","
+      , Space
+      , Str "and"
+      , Space
+      , Str "so"
+      , Space
+      , Emph [ Str "is" , Space , Str "this" ]
+      , Str "."
+      ]
+  , Para
+      [ Str "This"
+      , Space
+      , Str "is"
+      , Space
+      , Strong [ Str "strong" ]
+      , Str ","
+      , Space
+      , Str "and"
+      , Space
+      , Str "so"
+      , Space
+      , Strong [ Str "is" , Space , Str "this" ]
+      , Str "."
+      ]
+  , Para
+      [ Str "An"
+      , Space
+      , Emph
+          [ Link
+              ( "" , [] , [] )
+              [ Str "emphasized" , Space , Str "link" ]
+              ( "/url" , "" )
+          ]
+      , Str "."
+      ]
+  , Para
+      [ Strong
+          [ Emph
+              [ Str "This"
+              , Space
+              , Str "is"
+              , Space
+              , Str "strong"
+              , Space
+              , Str "and"
+              , Space
+              , Str "em."
+              ]
+          ]
+      ]
+  , Para
+      [ Str "So"
+      , Space
+      , Str "is"
+      , Space
+      , Strong [ Emph [ Str "this" ] ]
+      , Space
+      , Str "word."
+      ]
+  , Para
+      [ Strong
+          [ Emph
+              [ Str "This"
+              , Space
+              , Str "is"
+              , Space
+              , Str "strong"
+              , Space
+              , Str "and"
+              , Space
+              , Str "em."
+              ]
+          ]
+      ]
+  , Para
+      [ Str "So"
+      , Space
+      , Str "is"
+      , Space
+      , Strong [ Emph [ Str "this" ] ]
+      , Space
+      , Str "word."
+      ]
+  , Para
+      [ Str "This"
+      , Space
+      , Str "is"
+      , Space
+      , Str "code:"
+      , Space
+      , Code ( "" , [] , [] ) ">"
+      , Str ","
+      , Space
+      , Code ( "" , [] , [] ) "$"
+      , Str ","
+      , Space
+      , Code ( "" , [] , [] ) "\\"
+      , Str ","
+      , Space
+      , Code ( "" , [] , [] ) "\\$"
+      , Str ","
+      , Space
+      , Code ( "" , [] , [] ) "<html>"
+      , Str "."
+      ]
+  , Para
+      [ Strikeout
+          [ Str "This"
+          , Space
+          , Str "is"
+          , Space
+          , Emph [ Str "strikeout" ]
+          , Str "."
+          ]
+      ]
+  , Para
+      [ Str "Superscripts:"
+      , Space
+      , Str "a"
+      , Superscript [ Str "bc" ]
+      , Str "d"
+      , Space
+      , Str "a"
+      , Superscript [ Emph [ Str "hello" ] ]
+      , Space
+      , Str "a"
+      , Superscript [ Str "hello\160there" ]
+      , Str "."
+      ]
+  , Para
+      [ Str "Subscripts:"
+      , Space
+      , Str "H"
+      , Subscript [ Str "2" ]
+      , Str "O,"
+      , Space
+      , Str "H"
+      , Subscript [ Str "23" ]
+      , Str "O,"
+      , Space
+      , Str "H"
+      , Subscript [ Str "many\160of\160them" ]
+      , Str "O."
+      ]
+  , Para
+      [ Str "These"
+      , Space
+      , Str "should"
+      , Space
+      , Str "not"
+      , Space
+      , Str "be"
+      , Space
+      , Str "superscripts"
+      , Space
+      , Str "or"
+      , Space
+      , Str "subscripts,"
+      , SoftBreak
+      , Str "because"
+      , Space
+      , Str "of"
+      , Space
+      , Str "the"
+      , Space
+      , Str "unescaped"
+      , Space
+      , Str "spaces:"
+      , Space
+      , Str "a^b"
+      , Space
+      , Str "c^d,"
+      , Space
+      , Str "a~b"
+      , Space
+      , Str "c~d."
+      ]
+  , HorizontalRule
+  , Header
+      1
+      ( "smart-quotes-ellipses-dashes" , [] , [] )
+      [ Str "Smart"
+      , Space
+      , Str "quotes,"
+      , Space
+      , Str "ellipses,"
+      , Space
+      , Str "dashes"
+      ]
+  , Para
+      [ Quoted DoubleQuote [ Str "Hello," ]
+      , Space
+      , Str "said"
+      , Space
+      , Str "the"
+      , Space
+      , Str "spider."
+      , Space
+      , Quoted
+          DoubleQuote
+          [ Quoted SingleQuote [ Str "Shelob" ]
+          , Space
+          , Str "is"
+          , Space
+          , Str "my"
+          , Space
+          , Str "name."
+          ]
+      ]
+  , Para
+      [ Quoted SingleQuote [ Str "A" ]
+      , Str ","
+      , Space
+      , Quoted SingleQuote [ Str "B" ]
+      , Str ","
+      , Space
+      , Str "and"
+      , Space
+      , Quoted SingleQuote [ Str "C" ]
+      , Space
+      , Str "are"
+      , Space
+      , Str "letters."
+      ]
+  , Para
+      [ Quoted SingleQuote [ Str "Oak," ]
+      , Space
+      , Quoted SingleQuote [ Str "elm," ]
+      , Space
+      , Str "and"
+      , Space
+      , Quoted SingleQuote [ Str "beech" ]
+      , Space
+      , Str "are"
+      , Space
+      , Str "names"
+      , Space
+      , Str "of"
+      , Space
+      , Str "trees."
+      , SoftBreak
+      , Str "So"
+      , Space
+      , Str "is"
+      , Space
+      , Quoted SingleQuote [ Str "pine." ]
+      ]
+  , Para
+      [ Quoted
+          SingleQuote
+          [ Str "He"
+          , Space
+          , Str "said,"
+          , Space
+          , Quoted
+              DoubleQuote
+              [ Str "I"
+              , Space
+              , Str "want"
+              , Space
+              , Str "to"
+              , Space
+              , Str "go."
+              ]
+          ]
+      , Space
+      , Str "Were"
+      , Space
+      , Str "you"
+      , Space
+      , Str "alive"
+      , Space
+      , Str "in"
+      , Space
+      , Str "the"
+      , SoftBreak
+      , Str "70\8217s?"
+      ]
+  , Para
+      [ Str "Here"
+      , Space
+      , Str "is"
+      , Space
+      , Str "some"
+      , Space
+      , Str "quoted"
+      , Space
+      , Quoted SingleQuote [ Code ( "" , [] , [] ) "code" ]
+      , Space
+      , Str "and"
+      , Space
+      , Str "a"
+      , Space
+      , Quoted
+          DoubleQuote
+          [ Link
+              ( "" , [] , [] )
+              [ Str "quoted" , Space , Str "link" ]
+              ( "http://example.com/?foo=1&bar=2" , "" )
+          ]
+      , Str "."
+      ]
+  , Para
+      [ Str "Some"
+      , Space
+      , Str "dashes:"
+      , Space
+      , Str "one\8212two"
+      , Space
+      , Str "\8212"
+      , Space
+      , Str "three\8212four"
+      , Space
+      , Str "\8212"
+      , Space
+      , Str "five."
+      ]
+  , Para
+      [ Str "Dashes"
+      , Space
+      , Str "between"
+      , Space
+      , Str "numbers:"
+      , Space
+      , Str "5\8211\&7,"
+      , Space
+      , Str "255\8211\&66,"
+      , Space
+      , Str "1987\8211\&1999."
+      ]
+  , Para [ Str "Ellipses\8230and\8230and\8230." ]
+  , HorizontalRule
+  , Header 1 ( "latex" , [] , [] ) [ Str "LaTeX" ]
+  , BulletList
+      [ [ Plain [ RawInline (Format "tex") "\\cite[22-23]{smith.1899}" ]
+        ]
+      , [ Plain [ Math InlineMath "2+2=4" ] ]
+      , [ Plain [ Math InlineMath "x \\in y" ] ]
+      , [ Plain [ Math InlineMath "\\alpha \\wedge \\omega" ] ]
+      , [ Plain [ Math InlineMath "223" ] ]
+      , [ Plain [ Math InlineMath "p" , Str "-Tree" ] ]
+      , [ Plain
+            [ Str "Here\8217s"
+            , Space
+            , Str "some"
+            , Space
+            , Str "display"
+            , Space
+            , Str "math:"
+            , SoftBreak
+            , Math
+                DisplayMath
+                "\\frac{d}{dx}f(x)=\\lim_{h\\to 0}\\frac{f(x+h)-f(x)}{h}"
+            ]
+        ]
+      , [ Plain
+            [ Str "Here\8217s"
+            , Space
+            , Str "one"
+            , Space
+            , Str "that"
+            , Space
+            , Str "has"
+            , Space
+            , Str "a"
+            , Space
+            , Str "line"
+            , Space
+            , Str "break"
+            , Space
+            , Str "in"
+            , Space
+            , Str "it:"
+            , Space
+            , Math InlineMath "\\alpha + \\omega \\times x^2"
+            , Str "."
+            ]
+        ]
+      ]
+  , Para
+      [ Str "These"
+      , Space
+      , Str "shouldn\8217t"
+      , Space
+      , Str "be"
+      , Space
+      , Str "math:"
+      ]
+  , BulletList
+      [ [ Plain
+            [ Str "To"
+            , Space
+            , Str "get"
+            , Space
+            , Str "the"
+            , Space
+            , Str "famous"
+            , Space
+            , Str "equation,"
+            , Space
+            , Str "write"
+            , Space
+            , Code ( "" , [] , [] ) "$e = mc^2$"
+            , Str "."
+            ]
+        ]
+      , [ Plain
+            [ Str "$22,000"
+            , Space
+            , Str "is"
+            , Space
+            , Str "a"
+            , Space
+            , Emph [ Str "lot" ]
+            , Space
+            , Str "of"
+            , Space
+            , Str "money."
+            , Space
+            , Str "So"
+            , Space
+            , Str "is"
+            , Space
+            , Str "$34,000."
+            , SoftBreak
+            , Str "(It"
+            , Space
+            , Str "worked"
+            , Space
+            , Str "if"
+            , Space
+            , Quoted DoubleQuote [ Str "lot" ]
+            , Space
+            , Str "is"
+            , Space
+            , Str "emphasized.)"
+            ]
+        ]
+      , [ Plain
+            [ Str "Shoes"
+            , Space
+            , Str "($20)"
+            , Space
+            , Str "and"
+            , Space
+            , Str "socks"
+            , Space
+            , Str "($5)."
+            ]
+        ]
+      , [ Plain
+            [ Str "Escaped"
+            , Space
+            , Code ( "" , [] , [] ) "$"
+            , Str ":"
+            , Space
+            , Str "$73"
+            , Space
+            , Emph
+                [ Str "this"
+                , Space
+                , Str "should"
+                , Space
+                , Str "be"
+                , Space
+                , Str "emphasized"
+                ]
+            , Space
+            , Str "23$."
+            ]
+        ]
+      ]
+  , Para
+      [ Str "Here\8217s"
+      , Space
+      , Str "a"
+      , Space
+      , Str "LaTeX"
+      , Space
+      , Str "table:"
+      ]
+  , RawBlock
+      (Format "tex")
+      "\\begin{tabular}{|l|l|}\\hline\nAnimal & Number \\\\ \\hline\nDog    & 2      \\\\\nCat    & 1      \\\\ \\hline\n\\end{tabular}"
+  , HorizontalRule
+  , Header
+      1
+      ( "special-characters" , [] , [] )
+      [ Str "Special" , Space , Str "Characters" ]
+  , Para
+      [ Str "Here"
+      , Space
+      , Str "is"
+      , Space
+      , Str "some"
+      , Space
+      , Str "unicode:"
+      ]
+  , BulletList
+      [ [ Plain [ Str "I" , Space , Str "hat:" , Space , Str "\206" ] ]
+      , [ Plain [ Str "o" , Space , Str "umlaut:" , Space , Str "\246" ]
+        ]
+      , [ Plain [ Str "section:" , Space , Str "\167" ] ]
+      , [ Plain
+            [ Str "set" , Space , Str "membership:" , Space , Str "\8712" ]
+        ]
+      , [ Plain [ Str "copyright:" , Space , Str "\169" ] ]
+      ]
+  , Para
+      [ Str "AT&T"
+      , Space
+      , Str "has"
+      , Space
+      , Str "an"
+      , Space
+      , Str "ampersand"
+      , Space
+      , Str "in"
+      , Space
+      , Str "their"
+      , Space
+      , Str "name."
+      ]
+  , Para
+      [ Str "AT&T"
+      , Space
+      , Str "is"
+      , Space
+      , Str "another"
+      , Space
+      , Str "way"
+      , Space
+      , Str "to"
+      , Space
+      , Str "write"
+      , Space
+      , Str "it."
+      ]
+  , Para [ Str "This" , Space , Str "&" , Space , Str "that." ]
+  , Para [ Str "4" , Space , Str "<" , Space , Str "5." ]
+  , Para [ Str "6" , Space , Str ">" , Space , Str "5." ]
+  , Para [ Str "Backslash:" , Space , Str "\\" ]
+  , Para [ Str "Backtick:" , Space , Str "`" ]
+  , Para [ Str "Asterisk:" , Space , Str "*" ]
+  , Para [ Str "Underscore:" , Space , Str "_" ]
+  , Para [ Str "Left" , Space , Str "brace:" , Space , Str "{" ]
+  , Para [ Str "Right" , Space , Str "brace:" , Space , Str "}" ]
+  , Para [ Str "Left" , Space , Str "bracket:" , Space , Str "[" ]
+  , Para [ Str "Right" , Space , Str "bracket:" , Space , Str "]" ]
+  , Para [ Str "Left" , Space , Str "paren:" , Space , Str "(" ]
+  , Para [ Str "Right" , Space , Str "paren:" , Space , Str ")" ]
+  , Para [ Str "Greater-than:" , Space , Str ">" ]
+  , Para [ Str "Hash:" , Space , Str "#" ]
+  , Para [ Str "Period:" , Space , Str "." ]
+  , Para [ Str "Bang:" , Space , Str "!" ]
+  , Para [ Str "Plus:" , Space , Str "+" ]
+  , Para [ Str "Minus:" , Space , Str "-" ]
+  , HorizontalRule
+  , Header 1 ( "links" , [] , [] ) [ Str "Links" ]
+  , Header 2 ( "explicit" , [] , [] ) [ Str "Explicit" ]
+  , Para
+      [ Str "Just"
+      , Space
+      , Str "a"
+      , Space
+      , Link ( "" , [] , [] ) [ Str "URL" ] ( "/url/" , "" )
+      , Str "."
+      ]
+  , Para
+      [ Link
+          ( "" , [] , [] )
+          [ Str "URL" , Space , Str "and" , Space , Str "title" ]
+          ( "/url/" , "title" )
+      , Str "."
+      ]
+  , Para
+      [ Link
+          ( "" , [] , [] )
+          [ Str "URL" , Space , Str "and" , Space , Str "title" ]
+          ( "/url/" , "title preceded by two spaces" )
+      , Str "."
+      ]
+  , Para
+      [ Link
+          ( "" , [] , [] )
+          [ Str "URL" , Space , Str "and" , Space , Str "title" ]
+          ( "/url/" , "title preceded by a tab" )
+      , Str "."
+      ]
+  , Para
+      [ Link
+          ( "" , [] , [] )
+          [ Str "URL" , Space , Str "and" , Space , Str "title" ]
+          ( "/url/" , "title with \"quotes\" in it" )
+      ]
+  , Para
+      [ Link
+          ( "" , [] , [] )
+          [ Str "URL" , Space , Str "and" , Space , Str "title" ]
+          ( "/url/" , "title with single quotes" )
+      ]
+  , Para
+      [ Link
+          ( "" , [] , [] )
+          [ Str "with_underscore" ]
+          ( "/url/with_underscore" , "" )
+      ]
+  , Para
+      [ Link
+          ( "" , [] , [] )
+          [ Str "Email" , Space , Str "link" ]
+          ( "mailto:nobody@nowhere.net" , "" )
+      ]
+  , Para
+      [ Link ( "" , [] , [] ) [ Str "Empty" ] ( "" , "" ) , Str "." ]
+  , Header 2 ( "reference" , [] , [] ) [ Str "Reference" ]
+  , Para
+      [ Str "Foo"
+      , Space
+      , Link ( "" , [] , [] ) [ Str "bar" ] ( "/url/" , "" )
+      , Str "."
+      ]
+  , Para
+      [ Str "With"
+      , Space
+      , Link
+          ( "" , [] , [] )
+          [ Str "embedded" , Space , Str "[brackets]" ]
+          ( "/url/" , "" )
+      , Str "."
+      ]
+  , Para
+      [ Link ( "" , [] , [] ) [ Str "b" ] ( "/url/" , "" )
+      , Space
+      , Str "by"
+      , Space
+      , Str "itself"
+      , Space
+      , Str "should"
+      , Space
+      , Str "be"
+      , Space
+      , Str "a"
+      , Space
+      , Str "link."
+      ]
+  , Para
+      [ Str "Indented"
+      , Space
+      , Link ( "" , [] , [] ) [ Str "once" ] ( "/url" , "" )
+      , Str "."
+      ]
+  , Para
+      [ Str "Indented"
+      , Space
+      , Link ( "" , [] , [] ) [ Str "twice" ] ( "/url" , "" )
+      , Str "."
+      ]
+  , Para
+      [ Str "Indented"
+      , Space
+      , Link ( "" , [] , [] ) [ Str "thrice" ] ( "/url" , "" )
+      , Str "."
+      ]
+  , Para
+      [ Str "This"
+      , Space
+      , Str "should"
+      , Space
+      , Str "[not][]"
+      , Space
+      , Str "be"
+      , Space
+      , Str "a"
+      , Space
+      , Str "link."
+      ]
+  , CodeBlock ( "" , [] , [] ) "[not]: /url"
+  , Para
+      [ Str "Foo"
+      , Space
+      , Link
+          ( "" , [] , [] )
+          [ Str "bar" ]
+          ( "/url/" , "Title with \"quotes\" inside" )
+      , Str "."
+      ]
+  , Para
+      [ Str "Foo"
+      , Space
+      , Link
+          ( "" , [] , [] )
+          [ Str "biz" ]
+          ( "/url/" , "Title with \"quote\" inside" )
+      , Str "."
+      ]
+  , Header
+      2
+      ( "with-ampersands" , [] , [] )
+      [ Str "With" , Space , Str "ampersands" ]
+  , Para
+      [ Str "Here\8217s"
+      , Space
+      , Str "a"
+      , Space
+      , Link
+          ( "" , [] , [] )
+          [ Str "link"
+          , Space
+          , Str "with"
+          , Space
+          , Str "an"
+          , Space
+          , Str "ampersand"
+          , Space
+          , Str "in"
+          , Space
+          , Str "the"
+          , Space
+          , Str "URL"
+          ]
+          ( "http://example.com/?foo=1&bar=2" , "" )
+      , Str "."
+      ]
+  , Para
+      [ Str "Here\8217s"
+      , Space
+      , Str "a"
+      , Space
+      , Str "link"
+      , Space
+      , Str "with"
+      , Space
+      , Str "an"
+      , Space
+      , Str "amersand"
+      , Space
+      , Str "in"
+      , Space
+      , Str "the"
+      , Space
+      , Str "link"
+      , Space
+      , Str "text:"
+      , Space
+      , Link
+          ( "" , [] , [] ) [ Str "AT&T" ] ( "http://att.com/" , "AT&T" )
+      , Str "."
+      ]
+  , Para
+      [ Str "Here\8217s"
+      , Space
+      , Str "an"
+      , Space
+      , Link
+          ( "" , [] , [] )
+          [ Str "inline" , Space , Str "link" ]
+          ( "/script?foo=1&bar=2" , "" )
+      , Str "."
+      ]
+  , Para
+      [ Str "Here\8217s"
+      , Space
+      , Str "an"
+      , Space
+      , Link
+          ( "" , [] , [] )
+          [ Str "inline"
+          , Space
+          , Str "link"
+          , Space
+          , Str "in"
+          , Space
+          , Str "pointy"
+          , Space
+          , Str "braces"
+          ]
+          ( "/script?foo=1&bar=2" , "" )
+      , Str "."
+      ]
+  , Header 2 ( "autolinks" , [] , [] ) [ Str "Autolinks" ]
+  , Para
+      [ Str "With"
+      , Space
+      , Str "an"
+      , Space
+      , Str "ampersand:"
+      , Space
+      , Link
+          ( "" , [ "uri" ] , [] )
+          [ Str "http://example.com/?foo=1&bar=2" ]
+          ( "http://example.com/?foo=1&bar=2" , "" )
+      ]
+  , BulletList
+      [ [ Plain [ Str "In" , Space , Str "a" , Space , Str "list?" ] ]
+      , [ Plain
+            [ Link
+                ( "" , [ "uri" ] , [] )
+                [ Str "http://example.com/" ]
+                ( "http://example.com/" , "" )
+            ]
+        ]
+      , [ Plain [ Str "It" , Space , Str "should." ] ]
+      ]
+  , Para
+      [ Str "An"
+      , Space
+      , Str "e-mail"
+      , Space
+      , Str "address:"
+      , Space
+      , Link
+          ( "" , [ "email" ] , [] )
+          [ Str "nobody@nowhere.net" ]
+          ( "mailto:nobody@nowhere.net" , "" )
+      ]
+  , BlockQuote
+      [ Para
+          [ Str "Blockquoted:"
+          , Space
+          , Link
+              ( "" , [ "uri" ] , [] )
+              [ Str "http://example.com/" ]
+              ( "http://example.com/" , "" )
+          ]
+      ]
+  , Para
+      [ Str "Auto-links"
+      , Space
+      , Str "should"
+      , Space
+      , Str "not"
+      , Space
+      , Str "occur"
+      , Space
+      , Str "here:"
+      , Space
+      , Code ( "" , [] , [] ) "<http://example.com/>"
+      ]
+  , CodeBlock ( "" , [] , [] ) "or here: <http://example.com/>"
+  , HorizontalRule
+  , Header 1 ( "images" , [] , [] ) [ Str "Images" ]
+  , Para
+      [ Str "From"
+      , Space
+      , Quoted
+          DoubleQuote
+          [ Str "Voyage"
+          , Space
+          , Str "dans"
+          , Space
+          , Str "la"
+          , Space
+          , Str "Lune"
+          ]
+      , Space
+      , Str "by"
+      , Space
+      , Str "Georges"
+      , Space
+      , Str "Melies"
+      , Space
+      , Str "(1902):"
+      ]
+  , Figure
+      ( "" , [] , [] )
+      (Caption Nothing [ Plain [ Str "lalune" ] ])
+      [ Plain
+          [ Image
+              ( "" , [] , [] )
+              [ Str "lalune" ]
+              ( "lalune.jpg" , "Voyage dans la Lune" )
+          ]
+      ]
+  , Para
+      [ Str "Here"
+      , Space
+      , Str "is"
+      , Space
+      , Str "a"
+      , Space
+      , Str "movie"
+      , Space
+      , Image ( "" , [] , [] ) [ Str "movie" ] ( "movie.jpg" , "" )
+      , Space
+      , Str "icon."
+      ]
+  , HorizontalRule
+  , Header 1 ( "footnotes" , [] , [] ) [ Str "Footnotes" ]
+  , Para
+      [ Str "Here"
+      , Space
+      , Str "is"
+      , Space
+      , Str "a"
+      , Space
+      , Str "footnote"
+      , Space
+      , Str "reference,"
+      , Note
+          [ Para
+              [ Str "Here"
+              , Space
+              , Str "is"
+              , Space
+              , Str "the"
+              , Space
+              , Str "footnote."
+              , Space
+              , Str "It"
+              , Space
+              , Str "can"
+              , Space
+              , Str "go"
+              , Space
+              , Str "anywhere"
+              , Space
+              , Str "after"
+              , Space
+              , Str "the"
+              , Space
+              , Str "footnote"
+              , SoftBreak
+              , Str "reference."
+              , Space
+              , Str "It"
+              , Space
+              , Str "need"
+              , Space
+              , Str "not"
+              , Space
+              , Str "be"
+              , Space
+              , Str "placed"
+              , Space
+              , Str "at"
+              , Space
+              , Str "the"
+              , Space
+              , Str "end"
+              , Space
+              , Str "of"
+              , Space
+              , Str "the"
+              , Space
+              , Str "document."
+              ]
+          ]
+      , Space
+      , Str "and"
+      , Space
+      , Str "another."
+      , Note
+          [ Para
+              [ Str "Here\8217s"
+              , Space
+              , Str "the"
+              , Space
+              , Str "long"
+              , Space
+              , Str "note."
+              , Space
+              , Str "This"
+              , Space
+              , Str "one"
+              , Space
+              , Str "contains"
+              , Space
+              , Str "multiple"
+              , SoftBreak
+              , Str "blocks."
+              ]
+          , Para
+              [ Str "Subsequent"
+              , Space
+              , Str "blocks"
+              , Space
+              , Str "are"
+              , Space
+              , Str "indented"
+              , Space
+              , Str "to"
+              , Space
+              , Str "show"
+              , Space
+              , Str "that"
+              , Space
+              , Str "they"
+              , Space
+              , Str "belong"
+              , Space
+              , Str "to"
+              , Space
+              , Str "the"
+              , SoftBreak
+              , Str "footnote"
+              , Space
+              , Str "(as"
+              , Space
+              , Str "with"
+              , Space
+              , Str "list"
+              , Space
+              , Str "items)."
+              ]
+          , CodeBlock ( "" , [] , [] ) "  { <code> }"
+          , Para
+              [ Str "If"
+              , Space
+              , Str "you"
+              , Space
+              , Str "want,"
+              , Space
+              , Str "you"
+              , Space
+              , Str "can"
+              , Space
+              , Str "indent"
+              , Space
+              , Str "every"
+              , Space
+              , Str "line,"
+              , Space
+              , Str "but"
+              , Space
+              , Str "you"
+              , Space
+              , Str "can"
+              , Space
+              , Str "also"
+              , Space
+              , Str "be"
+              , SoftBreak
+              , Str "lazy"
+              , Space
+              , Str "and"
+              , Space
+              , Str "just"
+              , Space
+              , Str "indent"
+              , Space
+              , Str "the"
+              , Space
+              , Str "first"
+              , Space
+              , Str "line"
+              , Space
+              , Str "of"
+              , Space
+              , Str "each"
+              , Space
+              , Str "block."
+              ]
+          ]
+      , SoftBreak
+      , Str "This"
+      , Space
+      , Str "should"
+      , Space
+      , Emph [ Str "not" ]
+      , Space
+      , Str "be"
+      , Space
+      , Str "a"
+      , Space
+      , Str "footnote"
+      , Space
+      , Str "reference,"
+      , Space
+      , Str "because"
+      , Space
+      , Str "it"
+      , SoftBreak
+      , Str "contains"
+      , Space
+      , Str "a"
+      , Space
+      , Str "space.[^my"
+      , Space
+      , Str "note]"
+      , Space
+      , Str "Here"
+      , Space
+      , Str "is"
+      , Space
+      , Str "an"
+      , Space
+      , Str "inline"
+      , Space
+      , Str "note."
+      , Note
+          [ Para
+              [ Str "This"
+              , SoftBreak
+              , Str "is"
+              , Space
+              , Emph [ Str "easier" ]
+              , Space
+              , Str "to"
+              , Space
+              , Str "type."
+              , Space
+              , Str "Inline"
+              , Space
+              , Str "notes"
+              , Space
+              , Str "may"
+              , Space
+              , Str "contain"
+              , SoftBreak
+              , Link
+                  ( "" , [] , [] ) [ Str "links" ] ( "http://google.com" , "" )
+              , Space
+              , Str "and"
+              , Space
+              , Code ( "" , [] , [] ) "]"
+              , Space
+              , Str "verbatim"
+              , Space
+              , Str "characters,"
+              , SoftBreak
+              , Str "as"
+              , Space
+              , Str "well"
+              , Space
+              , Str "as"
+              , Space
+              , Str "[bracketed"
+              , Space
+              , Str "text]."
+              ]
+          ]
+      ]
+  , BlockQuote
+      [ Para
+          [ Str "Notes"
+          , Space
+          , Str "can"
+          , Space
+          , Str "go"
+          , Space
+          , Str "in"
+          , Space
+          , Str "quotes."
+          , Note [ Para [ Str "In" , Space , Str "quote." ] ]
+          ]
+      ]
+  , OrderedList
+      ( 1 , Decimal , Period )
+      [ [ Plain
+            [ Str "And"
+            , Space
+            , Str "in"
+            , Space
+            , Str "list"
+            , Space
+            , Str "items."
+            , Note [ Para [ Str "In" , Space , Str "list." ] ]
+            ]
+        ]
+      ]
+  , Para
+      [ Str "This"
+      , Space
+      , Str "paragraph"
+      , Space
+      , Str "should"
+      , Space
+      , Str "not"
+      , Space
+      , Str "be"
+      , Space
+      , Str "part"
+      , Space
+      , Str "of"
+      , Space
+      , Str "the"
+      , Space
+      , Str "note,"
+      , Space
+      , Str "as"
+      , Space
+      , Str "it"
+      , Space
+      , Str "is"
+      , Space
+      , Str "not"
+      , Space
+      , Str "indented."
+      ]
+  ]
diff --git a/test/writer.opendocument b/test/writer.opendocument
--- a/test/writer.opendocument
+++ b/test/writer.opendocument
@@ -1,1529 +1,961 @@
 <?xml version="1.0" encoding="utf-8" ?>
-<office:document-content xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" xmlns:style="urn:oasis:names:tc:opendocument:xmlns:style:1.0" xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0" xmlns:table="urn:oasis:names:tc:opendocument:xmlns:table:1.0" xmlns:draw="urn:oasis:names:tc:opendocument:xmlns:drawing:1.0" xmlns:fo="urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:meta="urn:oasis:names:tc:opendocument:xmlns:meta:1.0" xmlns:number="urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0" xmlns:svg="urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0" xmlns:chart="urn:oasis:names:tc:opendocument:xmlns:chart:1.0" xmlns:dr3d="urn:oasis:names:tc:opendocument:xmlns:dr3d:1.0" xmlns:math="http://www.w3.org/1998/Math/MathML" xmlns:form="urn:oasis:names:tc:opendocument:xmlns:form:1.0" xmlns:script="urn:oasis:names:tc:opendocument:xmlns:script:1.0" xmlns:ooo="http://openoffice.org/2004/office" xmlns:ooow="http://openoffice.org/2004/writer" xmlns:oooc="http://openoffice.org/2004/calc" xmlns:dom="http://www.w3.org/2001/xml-events" xmlns:xforms="http://www.w3.org/2002/xforms" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" office:version="1.2">
-  <office:font-face-decls>
-    <style:font-face style:name="Courier New" style:font-family-generic="modern" style:font-pitch="fixed" svg:font-family="'Courier New'" />
-  </office:font-face-decls>
-  <office:automatic-styles>
-    <text:list-style style:name="L1">
-      <text:list-level-style-number text:level="1" text:style-name="Numbering_20_Symbols" style:num-format="1" text:start-value="1" style:num-suffix=".">
-        <style:list-level-properties text:space-before="0.0in" text:min-label-width="0.4in" />
-      </text:list-level-style-number>
-    </text:list-style>
-    <text:list-style style:name="L2">
-      <text:list-level-style-bullet text:level="1" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="•">
-        <style:list-level-properties text:space-before="0.0in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="2" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="◦">
-        <style:list-level-properties text:space-before="0.4in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="3" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="▪">
-        <style:list-level-properties text:space-before="0.8in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="4" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="•">
-        <style:list-level-properties text:space-before="1.2000000000000002in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="5" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="◦">
-        <style:list-level-properties text:space-before="1.6in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="6" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="▪">
-        <style:list-level-properties text:space-before="2.0in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="7" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="•">
-        <style:list-level-properties text:space-before="2.4000000000000004in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="8" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="◦">
-        <style:list-level-properties text:space-before="2.8000000000000003in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="9" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="▪">
-        <style:list-level-properties text:space-before="3.2in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="10" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="•">
-        <style:list-level-properties text:space-before="3.6in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-    </text:list-style>
-    <text:list-style style:name="L3">
-      <text:list-level-style-bullet text:level="1" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="•">
-        <style:list-level-properties text:space-before="0.0in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="2" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="◦">
-        <style:list-level-properties text:space-before="0.4in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="3" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="▪">
-        <style:list-level-properties text:space-before="0.8in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="4" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="•">
-        <style:list-level-properties text:space-before="1.2000000000000002in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="5" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="◦">
-        <style:list-level-properties text:space-before="1.6in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="6" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="▪">
-        <style:list-level-properties text:space-before="2.0in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="7" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="•">
-        <style:list-level-properties text:space-before="2.4000000000000004in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="8" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="◦">
-        <style:list-level-properties text:space-before="2.8000000000000003in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="9" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="▪">
-        <style:list-level-properties text:space-before="3.2in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="10" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="•">
-        <style:list-level-properties text:space-before="3.6in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-    </text:list-style>
-    <text:list-style style:name="L4">
-      <text:list-level-style-bullet text:level="1" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="•">
-        <style:list-level-properties text:space-before="0.0in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="2" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="◦">
-        <style:list-level-properties text:space-before="0.4in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="3" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="▪">
-        <style:list-level-properties text:space-before="0.8in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="4" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="•">
-        <style:list-level-properties text:space-before="1.2000000000000002in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="5" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="◦">
-        <style:list-level-properties text:space-before="1.6in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="6" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="▪">
-        <style:list-level-properties text:space-before="2.0in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="7" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="•">
-        <style:list-level-properties text:space-before="2.4000000000000004in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="8" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="◦">
-        <style:list-level-properties text:space-before="2.8000000000000003in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="9" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="▪">
-        <style:list-level-properties text:space-before="3.2in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="10" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="•">
-        <style:list-level-properties text:space-before="3.6in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-    </text:list-style>
-    <text:list-style style:name="L5">
-      <text:list-level-style-bullet text:level="1" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="•">
-        <style:list-level-properties text:space-before="0.0in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="2" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="◦">
-        <style:list-level-properties text:space-before="0.4in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="3" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="▪">
-        <style:list-level-properties text:space-before="0.8in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="4" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="•">
-        <style:list-level-properties text:space-before="1.2000000000000002in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="5" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="◦">
-        <style:list-level-properties text:space-before="1.6in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="6" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="▪">
-        <style:list-level-properties text:space-before="2.0in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="7" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="•">
-        <style:list-level-properties text:space-before="2.4000000000000004in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="8" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="◦">
-        <style:list-level-properties text:space-before="2.8000000000000003in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="9" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="▪">
-        <style:list-level-properties text:space-before="3.2in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="10" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="•">
-        <style:list-level-properties text:space-before="3.6in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-    </text:list-style>
-    <text:list-style style:name="L6">
-      <text:list-level-style-bullet text:level="1" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="•">
-        <style:list-level-properties text:space-before="0.0in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="2" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="◦">
-        <style:list-level-properties text:space-before="0.4in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="3" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="▪">
-        <style:list-level-properties text:space-before="0.8in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="4" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="•">
-        <style:list-level-properties text:space-before="1.2000000000000002in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="5" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="◦">
-        <style:list-level-properties text:space-before="1.6in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="6" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="▪">
-        <style:list-level-properties text:space-before="2.0in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="7" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="•">
-        <style:list-level-properties text:space-before="2.4000000000000004in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="8" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="◦">
-        <style:list-level-properties text:space-before="2.8000000000000003in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="9" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="▪">
-        <style:list-level-properties text:space-before="3.2in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="10" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="•">
-        <style:list-level-properties text:space-before="3.6in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-    </text:list-style>
-    <text:list-style style:name="L7">
-      <text:list-level-style-bullet text:level="1" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="•">
-        <style:list-level-properties text:space-before="0.0in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="2" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="◦">
-        <style:list-level-properties text:space-before="0.4in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="3" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="▪">
-        <style:list-level-properties text:space-before="0.8in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="4" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="•">
-        <style:list-level-properties text:space-before="1.2000000000000002in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="5" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="◦">
-        <style:list-level-properties text:space-before="1.6in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="6" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="▪">
-        <style:list-level-properties text:space-before="2.0in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="7" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="•">
-        <style:list-level-properties text:space-before="2.4000000000000004in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="8" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="◦">
-        <style:list-level-properties text:space-before="2.8000000000000003in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="9" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="▪">
-        <style:list-level-properties text:space-before="3.2in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="10" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="•">
-        <style:list-level-properties text:space-before="3.6in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-    </text:list-style>
-    <text:list-style style:name="L8">
-      <text:list-level-style-number text:level="1" text:style-name="Numbering_20_Symbols" style:num-format="1" text:start-value="1" style:num-suffix=".">
-        <style:list-level-properties text:space-before="0.0in" text:min-label-width="0.4in" />
-      </text:list-level-style-number>
-    </text:list-style>
-    <text:list-style style:name="L9">
-      <text:list-level-style-number text:level="1" text:style-name="Numbering_20_Symbols" style:num-format="1" text:start-value="1" style:num-suffix=".">
-        <style:list-level-properties text:space-before="0.0in" text:min-label-width="0.4in" />
-      </text:list-level-style-number>
-    </text:list-style>
-    <text:list-style style:name="L10">
-      <text:list-level-style-number text:level="1" text:style-name="Numbering_20_Symbols" style:num-format="1" text:start-value="1" style:num-suffix=".">
-        <style:list-level-properties text:space-before="0.0in" text:min-label-width="0.4in" />
-      </text:list-level-style-number>
-    </text:list-style>
-    <text:list-style style:name="L11">
-      <text:list-level-style-number text:level="1" text:style-name="Numbering_20_Symbols" style:num-format="1" text:start-value="1" style:num-suffix=".">
-        <style:list-level-properties text:space-before="0.0in" text:min-label-width="0.4in" />
-      </text:list-level-style-number>
-    </text:list-style>
-    <text:list-style style:name="L12">
-      <text:list-level-style-number text:level="1" text:style-name="Numbering_20_Symbols" style:num-format="1" text:start-value="1" style:num-suffix=".">
-        <style:list-level-properties text:space-before="0.0in" text:min-label-width="0.4in" />
-      </text:list-level-style-number>
-    </text:list-style>
-    <text:list-style style:name="L13">
-      <text:list-level-style-bullet text:level="1" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="•">
-        <style:list-level-properties text:space-before="0.0in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="2" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="◦">
-        <style:list-level-properties text:space-before="0.4in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="3" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="▪">
-        <style:list-level-properties text:space-before="0.8in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="4" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="•">
-        <style:list-level-properties text:space-before="1.2000000000000002in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="5" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="◦">
-        <style:list-level-properties text:space-before="1.6in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="6" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="▪">
-        <style:list-level-properties text:space-before="2.0in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="7" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="•">
-        <style:list-level-properties text:space-before="2.4000000000000004in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="8" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="◦">
-        <style:list-level-properties text:space-before="2.8000000000000003in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="9" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="▪">
-        <style:list-level-properties text:space-before="3.2in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="10" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="•">
-        <style:list-level-properties text:space-before="3.6in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-    </text:list-style>
-    <text:list-style style:name="L14">
-      <text:list-level-style-bullet text:level="1" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="•">
-        <style:list-level-properties text:space-before="0.0in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="2" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="◦">
-        <style:list-level-properties text:space-before="0.4in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="3" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="▪">
-        <style:list-level-properties text:space-before="0.8in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="4" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="•">
-        <style:list-level-properties text:space-before="1.2000000000000002in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="5" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="◦">
-        <style:list-level-properties text:space-before="1.6in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="6" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="▪">
-        <style:list-level-properties text:space-before="2.0in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="7" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="•">
-        <style:list-level-properties text:space-before="2.4000000000000004in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="8" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="◦">
-        <style:list-level-properties text:space-before="2.8000000000000003in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="9" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="▪">
-        <style:list-level-properties text:space-before="3.2in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="10" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="•">
-        <style:list-level-properties text:space-before="3.6in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-    </text:list-style>
-    <text:list-style style:name="L15">
-      <text:list-level-style-bullet text:level="1" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="•">
-        <style:list-level-properties text:space-before="0.0in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="2" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="◦">
-        <style:list-level-properties text:space-before="0.4in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="3" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="▪">
-        <style:list-level-properties text:space-before="0.8in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="4" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="•">
-        <style:list-level-properties text:space-before="1.2000000000000002in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="5" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="◦">
-        <style:list-level-properties text:space-before="1.6in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="6" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="▪">
-        <style:list-level-properties text:space-before="2.0in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="7" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="•">
-        <style:list-level-properties text:space-before="2.4000000000000004in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="8" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="◦">
-        <style:list-level-properties text:space-before="2.8000000000000003in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="9" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="▪">
-        <style:list-level-properties text:space-before="3.2in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="10" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="•">
-        <style:list-level-properties text:space-before="3.6in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-    </text:list-style>
-    <text:list-style style:name="L16">
-      <text:list-level-style-number text:level="1" text:style-name="Numbering_20_Symbols" style:num-format="1" text:start-value="1" style:num-suffix=".">
-        <style:list-level-properties text:space-before="0.0in" text:min-label-width="0.4in" />
-      </text:list-level-style-number>
-    </text:list-style>
-    <text:list-style style:name="L17">
-      <text:list-level-style-bullet text:level="1" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="•">
-        <style:list-level-properties text:space-before="0.0in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="2" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="◦">
-        <style:list-level-properties text:space-before="0.4in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="3" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="▪">
-        <style:list-level-properties text:space-before="0.8in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="4" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="•">
-        <style:list-level-properties text:space-before="1.2000000000000002in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="5" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="◦">
-        <style:list-level-properties text:space-before="1.6in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="6" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="▪">
-        <style:list-level-properties text:space-before="2.0in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="7" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="•">
-        <style:list-level-properties text:space-before="2.4000000000000004in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="8" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="◦">
-        <style:list-level-properties text:space-before="2.8000000000000003in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="9" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="▪">
-        <style:list-level-properties text:space-before="3.2in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="10" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="•">
-        <style:list-level-properties text:space-before="3.6in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-    </text:list-style>
-    <text:list-style style:name="L18">
-      <text:list-level-style-number text:level="1" text:style-name="Numbering_20_Symbols" style:num-format="1" text:start-value="1" style:num-suffix=".">
-        <style:list-level-properties text:space-before="0.0in" text:min-label-width="0.4in" />
-      </text:list-level-style-number>
-    </text:list-style>
-    <text:list-style style:name="L19">
-      <text:list-level-style-bullet text:level="1" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="•">
-        <style:list-level-properties text:space-before="0.0in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="2" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="◦">
-        <style:list-level-properties text:space-before="0.4in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="3" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="▪">
-        <style:list-level-properties text:space-before="0.8in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="4" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="•">
-        <style:list-level-properties text:space-before="1.2000000000000002in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="5" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="◦">
-        <style:list-level-properties text:space-before="1.6in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="6" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="▪">
-        <style:list-level-properties text:space-before="2.0in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="7" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="•">
-        <style:list-level-properties text:space-before="2.4000000000000004in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="8" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="◦">
-        <style:list-level-properties text:space-before="2.8000000000000003in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="9" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="▪">
-        <style:list-level-properties text:space-before="3.2in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="10" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="•">
-        <style:list-level-properties text:space-before="3.6in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-    </text:list-style>
-    <text:list-style style:name="L20">
-      <text:list-level-style-bullet text:level="1" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="•">
-        <style:list-level-properties text:space-before="0.0in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="2" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="◦">
-        <style:list-level-properties text:space-before="0.4in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="3" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="▪">
-        <style:list-level-properties text:space-before="0.8in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="4" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="•">
-        <style:list-level-properties text:space-before="1.2000000000000002in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="5" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="◦">
-        <style:list-level-properties text:space-before="1.6in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="6" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="▪">
-        <style:list-level-properties text:space-before="2.0in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="7" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="•">
-        <style:list-level-properties text:space-before="2.4000000000000004in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="8" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="◦">
-        <style:list-level-properties text:space-before="2.8000000000000003in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="9" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="▪">
-        <style:list-level-properties text:space-before="3.2in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="10" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="•">
-        <style:list-level-properties text:space-before="3.6in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-    </text:list-style>
-    <text:list-style style:name="L21">
-      <text:list-level-style-bullet text:level="1" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="•">
-        <style:list-level-properties text:space-before="0.0in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="2" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="◦">
-        <style:list-level-properties text:space-before="0.4in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="3" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="▪">
-        <style:list-level-properties text:space-before="0.8in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="4" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="•">
-        <style:list-level-properties text:space-before="1.2000000000000002in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="5" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="◦">
-        <style:list-level-properties text:space-before="1.6in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="6" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="▪">
-        <style:list-level-properties text:space-before="2.0in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="7" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="•">
-        <style:list-level-properties text:space-before="2.4000000000000004in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="8" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="◦">
-        <style:list-level-properties text:space-before="2.8000000000000003in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="9" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="▪">
-        <style:list-level-properties text:space-before="3.2in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="10" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="•">
-        <style:list-level-properties text:space-before="3.6in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-    </text:list-style>
-    <text:list-style style:name="L22">
-      <text:list-level-style-number text:level="1" text:style-name="Numbering_20_Symbols" style:num-format="1" text:start-value="2" style:num-prefix="(" style:num-suffix=")">
-        <style:list-level-properties text:space-before="0.0in" text:min-label-width="0.4in" />
-      </text:list-level-style-number>
-      <text:list-level-style-number text:level="2" text:style-name="Numbering_20_Symbols" style:num-format="i" text:start-value="4" style:num-suffix=".">
-        <style:list-level-properties text:space-before="0.4in" text:min-label-width="0.4in" />
-      </text:list-level-style-number>
-      <text:list-level-style-number text:level="3" text:style-name="Numbering_20_Symbols" style:num-format="A" text:start-value="1" style:num-prefix="(" style:num-suffix=")">
-        <style:list-level-properties text:space-before="0.8in" text:min-label-width="0.4in" />
-      </text:list-level-style-number>
-    </text:list-style>
-    <text:list-style style:name="L23">
-      <text:list-level-style-number text:level="1" text:style-name="Numbering_20_Symbols" style:num-format="A" text:start-value="1" style:num-suffix=".">
-        <style:list-level-properties text:space-before="0.0in" text:min-label-width="0.4in" />
-      </text:list-level-style-number>
-      <text:list-level-style-number text:level="2" text:style-name="Numbering_20_Symbols" style:num-format="I" text:start-value="1" style:num-suffix=".">
-        <style:list-level-properties text:space-before="0.4in" text:min-label-width="0.4in" />
-      </text:list-level-style-number>
-      <text:list-level-style-number text:level="3" text:style-name="Numbering_20_Symbols" style:num-format="1" text:start-value="6" style:num-prefix="(" style:num-suffix=")">
-        <style:list-level-properties text:space-before="0.8in" text:min-label-width="0.4in" />
-      </text:list-level-style-number>
-      <text:list-level-style-number text:level="4" text:style-name="Numbering_20_Symbols" style:num-format="a" text:start-value="3" style:num-suffix=")">
-        <style:list-level-properties text:space-before="1.2000000000000002in" text:min-label-width="0.4in" />
-      </text:list-level-style-number>
-    </text:list-style>
-    <text:list-style style:name="L24">
-      <text:list-level-style-number text:level="1" text:style-name="Numbering_20_Symbols" style:num-format="1" text:start-value="1" style:num-suffix=".">
-        <style:list-level-properties text:space-before="0.0in" text:min-label-width="0.4in" />
-      </text:list-level-style-number>
-      <text:list-level-style-number text:level="2" text:style-name="Numbering_20_Symbols" style:num-format="1" text:start-value="1" style:num-suffix=".">
-        <style:list-level-properties text:space-before="0.4in" text:min-label-width="0.4in" />
-      </text:list-level-style-number>
-    </text:list-style>
-    <text:list-style style:name="L25">
-      <text:list-level-style-number text:level="1" text:style-name="Numbering_20_Symbols" style:num-format="1" text:start-value="1" style:num-suffix=".">
-        <style:list-level-properties text:space-before="0.0in" text:min-label-width="0.4in" />
-      </text:list-level-style-number>
-    </text:list-style>
-    <text:list-style style:name="L26">
-      <text:list-level-style-bullet text:level="1" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="•">
-        <style:list-level-properties text:space-before="0.0in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="2" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="◦">
-        <style:list-level-properties text:space-before="0.4in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="3" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="▪">
-        <style:list-level-properties text:space-before="0.8in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="4" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="•">
-        <style:list-level-properties text:space-before="1.2000000000000002in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="5" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="◦">
-        <style:list-level-properties text:space-before="1.6in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="6" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="▪">
-        <style:list-level-properties text:space-before="2.0in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="7" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="•">
-        <style:list-level-properties text:space-before="2.4000000000000004in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="8" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="◦">
-        <style:list-level-properties text:space-before="2.8000000000000003in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="9" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="▪">
-        <style:list-level-properties text:space-before="3.2in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="10" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="•">
-        <style:list-level-properties text:space-before="3.6in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-    </text:list-style>
-    <text:list-style style:name="L27">
-      <text:list-level-style-bullet text:level="1" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="•">
-        <style:list-level-properties text:space-before="0.0in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="2" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="◦">
-        <style:list-level-properties text:space-before="0.4in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="3" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="▪">
-        <style:list-level-properties text:space-before="0.8in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="4" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="•">
-        <style:list-level-properties text:space-before="1.2000000000000002in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="5" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="◦">
-        <style:list-level-properties text:space-before="1.6in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="6" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="▪">
-        <style:list-level-properties text:space-before="2.0in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="7" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="•">
-        <style:list-level-properties text:space-before="2.4000000000000004in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="8" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="◦">
-        <style:list-level-properties text:space-before="2.8000000000000003in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="9" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="▪">
-        <style:list-level-properties text:space-before="3.2in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="10" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="•">
-        <style:list-level-properties text:space-before="3.6in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-    </text:list-style>
-    <text:list-style style:name="L28">
-      <text:list-level-style-bullet text:level="1" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="•">
-        <style:list-level-properties text:space-before="0.0in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="2" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="◦">
-        <style:list-level-properties text:space-before="0.4in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="3" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="▪">
-        <style:list-level-properties text:space-before="0.8in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="4" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="•">
-        <style:list-level-properties text:space-before="1.2000000000000002in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="5" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="◦">
-        <style:list-level-properties text:space-before="1.6in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="6" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="▪">
-        <style:list-level-properties text:space-before="2.0in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="7" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="•">
-        <style:list-level-properties text:space-before="2.4000000000000004in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="8" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="◦">
-        <style:list-level-properties text:space-before="2.8000000000000003in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="9" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="▪">
-        <style:list-level-properties text:space-before="3.2in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="10" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="•">
-        <style:list-level-properties text:space-before="3.6in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-    </text:list-style>
-    <text:list-style style:name="L29">
-      <text:list-level-style-bullet text:level="1" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="•">
-        <style:list-level-properties text:space-before="0.0in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="2" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="◦">
-        <style:list-level-properties text:space-before="0.4in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="3" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="▪">
-        <style:list-level-properties text:space-before="0.8in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="4" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="•">
-        <style:list-level-properties text:space-before="1.2000000000000002in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="5" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="◦">
-        <style:list-level-properties text:space-before="1.6in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="6" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="▪">
-        <style:list-level-properties text:space-before="2.0in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="7" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="•">
-        <style:list-level-properties text:space-before="2.4000000000000004in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="8" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="◦">
-        <style:list-level-properties text:space-before="2.8000000000000003in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="9" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="▪">
-        <style:list-level-properties text:space-before="3.2in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-      <text:list-level-style-bullet text:level="10" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="•">
-        <style:list-level-properties text:space-before="3.6in" text:min-label-width="0.4in" />
-      </text:list-level-style-bullet>
-    </text:list-style>
-    <text:list-style style:name="L30">
-      <text:list-level-style-number text:level="1" text:style-name="Numbering_20_Symbols" style:num-format="1" text:start-value="1" style:num-suffix=".">
-        <style:list-level-properties text:space-before="0.0in" text:min-label-width="0.4in" />
-      </text:list-level-style-number>
-    </text:list-style>
-    <style:style style:name="T1" style:family="text"><style:text-properties fo:font-style="italic" style:font-style-asian="italic" style:font-style-complex="italic" /></style:style>
-    <style:style style:name="T2" style:family="text"><style:text-properties fo:font-weight="bold" style:font-weight-asian="bold" style:font-weight-complex="bold" /></style:style>
-    <style:style style:name="T3" style:family="text"><style:text-properties fo:font-style="italic" style:font-style-asian="italic" style:font-style-complex="italic" fo:font-weight="bold" style:font-weight-asian="bold" style:font-weight-complex="bold" /></style:style>
-    <style:style style:name="T4" style:family="text"><style:text-properties style:text-line-through-style="solid" /></style:style>
-    <style:style style:name="T5" style:family="text"><style:text-properties fo:font-style="italic" style:font-style-asian="italic" style:font-style-complex="italic" style:text-line-through-style="solid" /></style:style>
-    <style:style style:name="T6" style:family="text"><style:text-properties style:text-position="super 58%" /></style:style>
-    <style:style style:name="T7" style:family="text"><style:text-properties fo:font-style="italic" style:font-style-asian="italic" style:font-style-complex="italic" style:text-position="super 58%" /></style:style>
-    <style:style style:name="T8" style:family="text"><style:text-properties style:text-position="sub 58%" /></style:style>
-    <style:style style:name="P1" style:family="paragraph" style:parent-style-name="Quotations">
-      <style:paragraph-properties fo:margin-left="0.5in" fo:margin-right="0in" fo:text-indent="0in" style:auto-text-indent="false" />
-    </style:style>
-    <style:style style:name="P2" style:family="paragraph" style:parent-style-name="Quotations">
-      <style:paragraph-properties fo:margin-left="0.5in" fo:margin-right="0in" fo:text-indent="0in" style:auto-text-indent="false" />
-    </style:style>
-    <style:style style:name="P3" style:family="paragraph" style:parent-style-name="Preformatted_20_Text">
-      <style:paragraph-properties fo:margin-left="0.5in" fo:margin-right="0in" fo:text-indent="0in" style:auto-text-indent="false" />
-    </style:style>
-    <style:style style:name="P4" style:family="paragraph" style:parent-style-name="Preformatted_20_Text">
-      <style:paragraph-properties fo:margin-left="0.5in" fo:margin-right="0in" fo:text-indent="0in" style:auto-text-indent="false" />
-    </style:style>
-    <style:style style:name="P5" style:family="paragraph" style:parent-style-name="Preformatted_20_Text">
-      <style:paragraph-properties fo:margin-left="0.5in" fo:margin-right="0in" fo:text-indent="0in" style:auto-text-indent="false" />
-    </style:style>
-    <style:style style:name="P6" style:family="paragraph" style:parent-style-name="Text_20_body" style:list-style-name="L1">
-      <style:paragraph-properties fo:margin-left="0.5in" fo:margin-right="0in" fo:text-indent="0in" style:auto-text-indent="false" fo:margin-top="0in" fo:margin-bottom="0in" />
-    </style:style>
-    <style:style style:name="P7" style:family="paragraph" style:parent-style-name="Quotations">
-      <style:paragraph-properties fo:margin-left="1.0in" fo:margin-right="0in" fo:text-indent="0in" style:auto-text-indent="false" />
-    </style:style>
-    <style:style style:name="P8" style:family="paragraph" style:parent-style-name="Quotations">
-      <style:paragraph-properties fo:margin-left="1.0in" fo:margin-right="0in" fo:text-indent="0in" style:auto-text-indent="false" />
-    </style:style>
-    <style:style style:name="P9" style:family="paragraph" style:parent-style-name="Preformatted_20_Text">
-    </style:style>
-    <style:style style:name="P10" style:family="paragraph" style:parent-style-name="Preformatted_20_Text">
-    </style:style>
-    <style:style style:name="P11" style:family="paragraph" style:parent-style-name="Preformatted_20_Text">
-    </style:style>
-    <style:style style:name="P12" style:family="paragraph" style:parent-style-name="Preformatted_20_Text">
-    </style:style>
-    <style:style style:name="P13" style:family="paragraph" style:parent-style-name="Preformatted_20_Text">
-    </style:style>
-    <style:style style:name="P14" style:family="paragraph" style:parent-style-name="Preformatted_20_Text">
-    </style:style>
-    <style:style style:name="P15" style:family="paragraph" style:parent-style-name="Preformatted_20_Text">
-    </style:style>
-    <style:style style:name="P16" style:family="paragraph" style:parent-style-name="Preformatted_20_Text">
-    </style:style>
-    <style:style style:name="P17" style:family="paragraph" style:parent-style-name="Preformatted_20_Text">
-    </style:style>
-    <style:style style:name="P18" style:family="paragraph" style:parent-style-name="Preformatted_20_Text">
-    </style:style>
-    <style:style style:name="P19" style:family="paragraph" style:parent-style-name="Text_20_body" style:list-style-name="L2">
-      <style:paragraph-properties fo:margin-top="0in" fo:margin-bottom="0in" />
-    </style:style>
-    <style:style style:name="P20" style:family="paragraph" style:parent-style-name="Text_20_body" style:list-style-name="L3">
-    </style:style>
-    <style:style style:name="P21" style:family="paragraph" style:parent-style-name="Text_20_body" style:list-style-name="L4">
-      <style:paragraph-properties fo:margin-top="0in" fo:margin-bottom="0in" />
-    </style:style>
-    <style:style style:name="P22" style:family="paragraph" style:parent-style-name="Text_20_body" style:list-style-name="L5">
-    </style:style>
-    <style:style style:name="P23" style:family="paragraph" style:parent-style-name="Text_20_body" style:list-style-name="L6">
-      <style:paragraph-properties fo:margin-top="0in" fo:margin-bottom="0in" />
-    </style:style>
-    <style:style style:name="P24" style:family="paragraph" style:parent-style-name="Text_20_body" style:list-style-name="L7">
-    </style:style>
-    <style:style style:name="P25" style:family="paragraph" style:parent-style-name="Text_20_body" style:list-style-name="L8">
-      <style:paragraph-properties fo:margin-top="0in" fo:margin-bottom="0in" />
-    </style:style>
-    <style:style style:name="P26" style:family="paragraph" style:parent-style-name="Text_20_body" style:list-style-name="L9">
-      <style:paragraph-properties fo:margin-top="0in" fo:margin-bottom="0in" />
-    </style:style>
-    <style:style style:name="P27" style:family="paragraph" style:parent-style-name="Text_20_body" style:list-style-name="L10">
-    </style:style>
-    <style:style style:name="P28" style:family="paragraph" style:parent-style-name="Text_20_body" style:list-style-name="L11">
-    </style:style>
-    <style:style style:name="P29" style:family="paragraph" style:parent-style-name="Text_20_body" style:list-style-name="L12">
-    </style:style>
-    <style:style style:name="P30" style:family="paragraph" style:parent-style-name="Text_20_body" style:list-style-name="L13">
-      <style:paragraph-properties fo:margin-top="0in" fo:margin-bottom="0in" />
-    </style:style>
-    <style:style style:name="P31" style:family="paragraph" style:parent-style-name="Text_20_body" style:list-style-name="L14">
-      <style:paragraph-properties fo:margin-top="0in" fo:margin-bottom="0in" />
-    </style:style>
-    <style:style style:name="P32" style:family="paragraph" style:parent-style-name="Text_20_body" style:list-style-name="L15">
-      <style:paragraph-properties fo:margin-top="0in" fo:margin-bottom="0in" />
-    </style:style>
-    <style:style style:name="P33" style:family="paragraph" style:parent-style-name="Text_20_body" style:list-style-name="L16">
-      <style:paragraph-properties fo:margin-top="0in" fo:margin-bottom="0in" />
-    </style:style>
-    <style:style style:name="P34" style:family="paragraph" style:parent-style-name="Text_20_body" style:list-style-name="L17">
-      <style:paragraph-properties fo:margin-top="0in" fo:margin-bottom="0in" />
-    </style:style>
-    <style:style style:name="P35" style:family="paragraph" style:parent-style-name="Text_20_body" style:list-style-name="L18">
-    </style:style>
-    <style:style style:name="P36" style:family="paragraph" style:parent-style-name="Text_20_body" style:list-style-name="L19">
-      <style:paragraph-properties fo:margin-top="0in" fo:margin-bottom="0in" />
-    </style:style>
-    <style:style style:name="P37" style:family="paragraph" style:parent-style-name="Text_20_body" style:list-style-name="L20">
-    </style:style>
-    <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" />
-    </style:style>
-    <style:style style:name="P41" style:family="paragraph" style:parent-style-name="Text_20_body" style:list-style-name="L24">
-      <style:paragraph-properties fo:margin-top="0in" fo:margin-bottom="0in" />
-    </style:style>
-    <style:style style:name="P42" style:family="paragraph" style:parent-style-name="Preformatted_20_Text">
-      <style:paragraph-properties fo:margin-left="0.5in" fo:margin-right="0in" fo:text-indent="0in" style:auto-text-indent="false" />
-    </style:style>
-    <style:style style:name="P43" style:family="paragraph" style:parent-style-name="Quotations">
-      <style:paragraph-properties fo:margin-left="0.5in" fo:margin-right="0in" fo:text-indent="0in" style:auto-text-indent="false" />
-    </style:style>
-    <style:style style:name="P44" style:family="paragraph" style:parent-style-name="Text_20_body" style:list-style-name="L25">
-      <style:paragraph-properties fo:margin-left="0.5in" fo:margin-right="0in" fo:text-indent="0in" style:auto-text-indent="false" fo:margin-top="0in" fo:margin-bottom="0in" />
-    </style:style>
-    <style:style style:name="P45" style:family="paragraph" style:parent-style-name="Preformatted_20_Text">
-    </style:style>
-    <style:style style:name="P46" style:family="paragraph" style:parent-style-name="Preformatted_20_Text">
-    </style:style>
-    <style:style style:name="P47" style:family="paragraph" style:parent-style-name="Preformatted_20_Text">
-    </style:style>
-    <style:style style:name="P48" style:family="paragraph" style:parent-style-name="Preformatted_20_Text">
-    </style:style>
-    <style:style style:name="P49" style:family="paragraph" style:parent-style-name="Preformatted_20_Text">
-    </style:style>
-    <style:style style:name="P50" style:family="paragraph" style:parent-style-name="Preformatted_20_Text">
-    </style:style>
-    <style:style style:name="P51" style:family="paragraph" style:parent-style-name="Text_20_body" style:list-style-name="L26">
-      <style:paragraph-properties fo:margin-top="0in" fo:margin-bottom="0in" />
-    </style:style>
-    <style:style style:name="P52" style:family="paragraph" style:parent-style-name="Text_20_body" style:list-style-name="L27">
-      <style:paragraph-properties fo:margin-top="0in" fo:margin-bottom="0in" />
-    </style:style>
-    <style:style style:name="P53" style:family="paragraph" style:parent-style-name="Text_20_body" style:list-style-name="L28">
-      <style:paragraph-properties fo:margin-top="0in" fo:margin-bottom="0in" />
-    </style:style>
-    <style:style style:name="P54" style:family="paragraph" style:parent-style-name="Preformatted_20_Text">
-    </style:style>
-    <style:style style:name="P55" style:family="paragraph" style:parent-style-name="Text_20_body" style:list-style-name="L29">
-      <style:paragraph-properties fo:margin-top="0in" fo:margin-bottom="0in" />
-    </style:style>
-    <style:style style:name="P56" style:family="paragraph" style:parent-style-name="Quotations">
-      <style:paragraph-properties fo:margin-left="0.5in" fo:margin-right="0in" fo:text-indent="0in" style:auto-text-indent="false" />
-    </style:style>
-    <style:style style:name="P57" style:family="paragraph" style:parent-style-name="Preformatted_20_Text">
-    </style:style>
-    <style:style style:name="P58" style:family="paragraph" style:parent-style-name="Preformatted_20_Text">
-    </style:style>
-    <style:style style:name="P59" style:family="paragraph" style:parent-style-name="Quotations">
-      <style:paragraph-properties fo:margin-left="0.5in" fo:margin-right="0in" fo:text-indent="0in" style:auto-text-indent="false" />
-    </style:style>
-    <style:style style:name="P60" style:family="paragraph" style:parent-style-name="Text_20_body" style:list-style-name="L30">
-      <style:paragraph-properties fo:margin-top="0in" fo:margin-bottom="0in" />
-    </style:style>
-  </office:automatic-styles>
-<office:body>
-<office:text>
-<text:p text:style-name="Title">Pandoc Test Suite</text:p>
-<text:p text:style-name="Author">John MacFarlane</text:p>
-<text:p text:style-name="Author">Anonymous</text:p>
-<text:p text:style-name="Date">July 17, 2006</text:p>
-<text:p text:style-name="Text_20_body">This is a set of tests for pandoc. Most
-of them are adapted from John Gruber’s markdown test suite.</text:p>
-<text:p text:style-name="Horizontal_20_Line" />
-<text:h text:style-name="Heading_20_1" text:outline-level="1">Headers</text:h>
-<text:h text:style-name="Heading_20_2" text:outline-level="2">Level 2 with an
-<text:a xlink:type="simple" xlink:href="/url" office:name=""><text:span text:style-name="Definition">embedded
-link</text:span></text:a></text:h>
-<text:h text:style-name="Heading_20_3" text:outline-level="3">Level 3 with
-<text:span text:style-name="T1">emphasis</text:span></text:h>
-<text:h text:style-name="Heading_20_4" text:outline-level="4">Level 4</text:h>
-<text:h text:style-name="Heading_20_5" text:outline-level="5">Level 5</text:h>
-<text:h text:style-name="Heading_20_1" text:outline-level="1">Level 1</text:h>
-<text:h text:style-name="Heading_20_2" text:outline-level="2">Level 2 with
-<text:span text:style-name="T1">emphasis</text:span></text:h>
-<text:h text:style-name="Heading_20_3" text:outline-level="3">Level 3</text:h>
-<text:p text:style-name="First_20_paragraph">with no blank line</text:p>
-<text:h text:style-name="Heading_20_2" text:outline-level="2">Level 2</text:h>
-<text:p text:style-name="First_20_paragraph">with no blank line</text:p>
-<text:p text:style-name="Horizontal_20_Line" />
-<text:h text:style-name="Heading_20_1" text:outline-level="1">Paragraphs</text:h>
-<text:p text:style-name="First_20_paragraph">Here’s a regular
-paragraph.</text:p>
-<text:p text:style-name="Text_20_body">In Markdown 1.0.0 and earlier. Version
-8. This line turns into a list item. Because a hard-wrapped line in the middle
-of a paragraph looked like a list item.</text:p>
-<text:p text:style-name="Text_20_body">Here’s one with a bullet. *
-criminey.</text:p>
-<text:p text:style-name="Text_20_body">There should be a hard line
-break<text:line-break />here.</text:p>
-<text:p text:style-name="Horizontal_20_Line" />
-<text:h text:style-name="Heading_20_1" text:outline-level="1">Block
-Quotes</text:h>
-<text:p text:style-name="First_20_paragraph">E-mail style:</text:p>
-<text:p text:style-name="P1">This is a block quote. It is pretty
-short.</text:p>
-<text:p text:style-name="P2">Code in a block quote:</text:p>
-<text:p text:style-name="P3">sub status {</text:p>
-<text:p text:style-name="P4"><text:s text:c="4" />print &quot;working&quot;;</text:p>
-<text:p text:style-name="P5">}</text:p>
-<text:p text:style-name="P2">A list:</text:p>
-<text:list text:style-name="L1">
-  <text:list-item>
-    <text:p text:style-name="P6">item one</text:p>
-  </text:list-item>
-  <text:list-item>
-    <text:p text:style-name="P6">item two</text:p>
-  </text:list-item>
-</text:list>
-<text:p text:style-name="P2">Nested block quotes:</text:p>
-<text:p text:style-name="P7">nested</text:p>
-<text:p text:style-name="P8">nested</text:p>
-<text:p text:style-name="First_20_paragraph">This should not be a block quote:
-2 &gt; 1.</text:p>
-<text:p text:style-name="Text_20_body">And a following paragraph.</text:p>
-<text:p text:style-name="Horizontal_20_Line" />
-<text:h text:style-name="Heading_20_1" text:outline-level="1">Code
-Blocks</text:h>
-<text:p text:style-name="First_20_paragraph">Code:</text:p>
-<text:p text:style-name="P9">---- (should be four hyphens)</text:p>
-<text:p text:style-name="P10"></text:p>
-<text:p text:style-name="P11">sub status {</text:p>
-<text:p text:style-name="P12"><text:s text:c="4" />print &quot;working&quot;;</text:p>
-<text:p text:style-name="P13">}</text:p>
-<text:p text:style-name="P14"></text:p>
-<text:p text:style-name="P15">this code block is indented by one tab</text:p>
-<text:p text:style-name="First_20_paragraph">And:</text:p>
-<text:p text:style-name="P16"><text:s text:c="4" />this code block is indented by two tabs</text:p>
-<text:p text:style-name="P17"></text:p>
-<text:p text:style-name="P18">These should not be escaped: <text:s text:c="1" />\$ \\ \&gt; \[ \{</text:p>
-<text:p text:style-name="Horizontal_20_Line" />
-<text:h text:style-name="Heading_20_1" text:outline-level="1">Lists</text:h>
-<text:h text:style-name="Heading_20_2" text:outline-level="2">Unordered</text:h>
-<text:p text:style-name="First_20_paragraph">Asterisks tight:</text:p>
-<text:list text:style-name="L2">
-  <text:list-item>
-    <text:p text:style-name="P19">asterisk 1</text:p>
-  </text:list-item>
-  <text:list-item>
-    <text:p text:style-name="P19">asterisk 2</text:p>
-  </text:list-item>
-  <text:list-item>
-    <text:p text:style-name="P19">asterisk 3</text:p>
-  </text:list-item>
-</text:list>
-<text:p text:style-name="First_20_paragraph">Asterisks loose:</text:p>
-<text:list text:style-name="L3">
-  <text:list-item>
-    <text:p text:style-name="P20">asterisk 1</text:p>
-  </text:list-item>
-  <text:list-item>
-    <text:p text:style-name="P20">asterisk 2</text:p>
-  </text:list-item>
-  <text:list-item>
-    <text:p text:style-name="P20">asterisk 3</text:p>
-  </text:list-item>
-</text:list>
-<text:p text:style-name="First_20_paragraph">Pluses tight:</text:p>
-<text:list text:style-name="L4">
-  <text:list-item>
-    <text:p text:style-name="P21">Plus 1</text:p>
-  </text:list-item>
-  <text:list-item>
-    <text:p text:style-name="P21">Plus 2</text:p>
-  </text:list-item>
-  <text:list-item>
-    <text:p text:style-name="P21">Plus 3</text:p>
-  </text:list-item>
-</text:list>
-<text:p text:style-name="First_20_paragraph">Pluses loose:</text:p>
-<text:list text:style-name="L5">
-  <text:list-item>
-    <text:p text:style-name="P22">Plus 1</text:p>
-  </text:list-item>
-  <text:list-item>
-    <text:p text:style-name="P22">Plus 2</text:p>
-  </text:list-item>
-  <text:list-item>
-    <text:p text:style-name="P22">Plus 3</text:p>
-  </text:list-item>
-</text:list>
-<text:p text:style-name="First_20_paragraph">Minuses tight:</text:p>
-<text:list text:style-name="L6">
-  <text:list-item>
-    <text:p text:style-name="P23">Minus 1</text:p>
-  </text:list-item>
-  <text:list-item>
-    <text:p text:style-name="P23">Minus 2</text:p>
-  </text:list-item>
-  <text:list-item>
-    <text:p text:style-name="P23">Minus 3</text:p>
-  </text:list-item>
-</text:list>
-<text:p text:style-name="First_20_paragraph">Minuses loose:</text:p>
-<text:list text:style-name="L7">
-  <text:list-item>
-    <text:p text:style-name="P24">Minus 1</text:p>
-  </text:list-item>
-  <text:list-item>
-    <text:p text:style-name="P24">Minus 2</text:p>
-  </text:list-item>
-  <text:list-item>
-    <text:p text:style-name="P24">Minus 3</text:p>
-  </text:list-item>
-</text:list>
-<text:h text:style-name="Heading_20_2" text:outline-level="2">Ordered</text:h>
-<text:p text:style-name="First_20_paragraph">Tight:</text:p>
-<text:list text:style-name="L8">
-  <text:list-item>
-    <text:p text:style-name="P25">First</text:p>
-  </text:list-item>
-  <text:list-item>
-    <text:p text:style-name="P25">Second</text:p>
-  </text:list-item>
-  <text:list-item>
-    <text:p text:style-name="P25">Third</text:p>
-  </text:list-item>
-</text:list>
-<text:p text:style-name="First_20_paragraph">and:</text:p>
-<text:list text:style-name="L9">
-  <text:list-item>
-    <text:p text:style-name="P26">One</text:p>
-  </text:list-item>
-  <text:list-item>
-    <text:p text:style-name="P26">Two</text:p>
-  </text:list-item>
-  <text:list-item>
-    <text:p text:style-name="P26">Three</text:p>
-  </text:list-item>
-</text:list>
-<text:p text:style-name="First_20_paragraph">Loose using tabs:</text:p>
-<text:list text:style-name="L10">
-  <text:list-item>
-    <text:p text:style-name="P27">First</text:p>
-  </text:list-item>
-  <text:list-item>
-    <text:p text:style-name="P27">Second</text:p>
-  </text:list-item>
-  <text:list-item>
-    <text:p text:style-name="P27">Third</text:p>
-  </text:list-item>
-</text:list>
-<text:p text:style-name="First_20_paragraph">and using spaces:</text:p>
-<text:list text:style-name="L11">
-  <text:list-item>
-    <text:p text:style-name="P28">One</text:p>
-  </text:list-item>
-  <text:list-item>
-    <text:p text:style-name="P28">Two</text:p>
-  </text:list-item>
-  <text:list-item>
-    <text:p text:style-name="P28">Three</text:p>
-  </text:list-item>
-</text:list>
-<text:p text:style-name="First_20_paragraph">Multiple paragraphs:</text:p>
-<text:list text:style-name="L12">
-  <text:list-item>
-    <text:p text:style-name="P29">Item 1, graf one.</text:p>
-    <text:p text:style-name="P29">Item 1. graf two. The quick brown fox jumped
-    over the lazy dog’s back.</text:p>
-  </text:list-item>
-  <text:list-item>
-    <text:p text:style-name="P29">Item 2.</text:p>
-  </text:list-item>
-  <text:list-item>
-    <text:p text:style-name="P29">Item 3.</text:p>
-  </text:list-item>
-</text:list>
-<text:h text:style-name="Heading_20_2" text:outline-level="2">Nested</text:h>
-<text:list text:style-name="L13">
-  <text:list-item>
-    <text:p text:style-name="P30">Tab</text:p><text:list text:style-name="L14">
-      <text:list-item>
-        <text:p text:style-name="P31">Tab</text:p><text:list text:style-name="L15">
-          <text:list-item>
-            <text:p text:style-name="P32">Tab</text:p>
-          </text:list-item>
-        </text:list>
-      </text:list-item>
-    </text:list>
-  </text:list-item>
-</text:list>
-<text:p text:style-name="First_20_paragraph">Here’s another:</text:p>
-<text:list text:style-name="L16">
-  <text:list-item>
-    <text:p text:style-name="P33">First</text:p>
-  </text:list-item>
-  <text:list-item>
-    <text:p text:style-name="P33">Second:</text:p>
-    <text:list text:style-name="L17">
-      <text:list-item>
-        <text:p text:style-name="P34">Fee</text:p>
-      </text:list-item>
-      <text:list-item>
-        <text:p text:style-name="P34">Fie</text:p>
-      </text:list-item>
-      <text:list-item>
-        <text:p text:style-name="P34">Foe</text:p>
-      </text:list-item>
-    </text:list>
-  </text:list-item>
-  <text:list-item>
-    <text:p text:style-name="P33">Third</text:p>
-  </text:list-item>
-</text:list>
-<text:p text:style-name="First_20_paragraph">Same thing but with
-paragraphs:</text:p>
-<text:list text:style-name="L18">
-  <text:list-item>
-    <text:p text:style-name="P35">First</text:p>
-  </text:list-item>
-  <text:list-item>
-    <text:p text:style-name="P35">Second:</text:p>
-    <text:list text:style-name="L19">
-      <text:list-item>
-        <text:p text:style-name="P36">Fee</text:p>
-      </text:list-item>
-      <text:list-item>
-        <text:p text:style-name="P36">Fie</text:p>
-      </text:list-item>
-      <text:list-item>
-        <text:p text:style-name="P36">Foe</text:p>
-      </text:list-item>
-    </text:list>
-  </text:list-item>
-  <text:list-item>
-    <text:p text:style-name="P35">Third</text:p>
-  </text:list-item>
-</text:list>
-<text:h text:style-name="Heading_20_2" text:outline-level="2">Tabs and
-spaces</text:h>
-<text:list text:style-name="L20">
-  <text:list-item>
-    <text:p text:style-name="P37">this is a list item indented with
-    tabs</text:p>
-  </text:list-item>
-  <text:list-item>
-    <text:p text:style-name="P37">this is a list item indented with
-    spaces</text:p><text:list text:style-name="L21">
-      <text:list-item>
-        <text:p text:style-name="P38">this is an example list item indented
-        with tabs</text:p>
-      </text:list-item>
-      <text:list-item>
-        <text:p text:style-name="P38">this is an example list item indented
-        with spaces</text:p>
-      </text:list-item>
-    </text:list>
-  </text:list-item>
-</text:list>
-<text:h text:style-name="Heading_20_2" text:outline-level="2">Fancy list
-markers</text:h>
-<text:list text:style-name="L22">
-  <text:list-item>
-    <text:p text:style-name="P39">begins with 2</text:p>
-  </text:list-item>
-  <text:list-item>
-    <text:p text:style-name="P39">and now 3</text:p>
-    <text:p text:style-name="P39">with a continuation</text:p>
-    <text:list>
-      <text:list-item>
-        <text:p text:style-name="P39">sublist with roman numerals, starting
-        with 4</text:p>
-      </text:list-item>
-      <text:list-item>
-        <text:p text:style-name="P39">more items</text:p>
-        <text:list>
-          <text:list-item>
-            <text:p text:style-name="P39">a subsublist</text:p>
-          </text:list-item>
-          <text:list-item>
-            <text:p text:style-name="P39">a subsublist</text:p>
-          </text:list-item>
-        </text:list>
-      </text:list-item>
-    </text:list>
-  </text:list-item>
-</text:list>
-<text:p text:style-name="First_20_paragraph">Nesting:</text:p>
-<text:list text:style-name="L23">
-  <text:list-item>
-    <text:p text:style-name="P40">Upper Alpha</text:p>
-    <text:list>
-      <text:list-item>
-        <text:p text:style-name="P40">Upper Roman.</text:p>
-        <text:list>
-          <text:list-item>
-            <text:p text:style-name="P40">Decimal start with 6</text:p>
-            <text:list>
-              <text:list-item>
-                <text:p text:style-name="P40">Lower alpha with paren</text:p>
-              </text:list-item>
-            </text:list>
-          </text:list-item>
-        </text:list>
-      </text:list-item>
-    </text:list>
-  </text:list-item>
-</text:list>
-<text:p text:style-name="First_20_paragraph">Autonumbering:</text:p>
-<text:list text:style-name="L24">
-  <text:list-item>
-    <text:p text:style-name="P41">Autonumber.</text:p>
-  </text:list-item>
-  <text:list-item>
-    <text:p text:style-name="P41">More.</text:p>
-    <text:list>
-      <text:list-item>
-        <text:p text:style-name="P41">Nested.</text:p>
-      </text:list-item>
-    </text:list>
-  </text:list-item>
-</text:list>
-<text:p text:style-name="First_20_paragraph">Should not be a list
-item:</text:p>
-<text:p text:style-name="Text_20_body">M.A. 2007</text:p>
-<text:p text:style-name="Text_20_body">B. Williams</text:p>
-<text:p text:style-name="Horizontal_20_Line" />
-<text:h text:style-name="Heading_20_1" text:outline-level="1">Definition
-Lists</text:h>
-<text:p text:style-name="First_20_paragraph">Tight using spaces:</text:p>
-<text:p text:style-name="Definition_20_Term_20_Tight">apple</text:p>
-<text:p text:style-name="Definition_20_Definition_20_Tight">red fruit</text:p>
-<text:p text:style-name="Definition_20_Term_20_Tight">orange</text:p>
-<text:p text:style-name="Definition_20_Definition_20_Tight">orange
-fruit</text:p>
-<text:p text:style-name="Definition_20_Term_20_Tight">banana</text:p>
-<text:p text:style-name="Definition_20_Definition_20_Tight">yellow
-fruit</text:p>
-<text:p text:style-name="First_20_paragraph">Tight using tabs:</text:p>
-<text:p text:style-name="Definition_20_Term_20_Tight">apple</text:p>
-<text:p text:style-name="Definition_20_Definition_20_Tight">red fruit</text:p>
-<text:p text:style-name="Definition_20_Term_20_Tight">orange</text:p>
-<text:p text:style-name="Definition_20_Definition_20_Tight">orange
-fruit</text:p>
-<text:p text:style-name="Definition_20_Term_20_Tight">banana</text:p>
-<text:p text:style-name="Definition_20_Definition_20_Tight">yellow
-fruit</text:p>
-<text:p text:style-name="First_20_paragraph">Loose:</text:p>
-<text:p text:style-name="Definition_20_Term">apple</text:p>
-<text:p text:style-name="Definition_20_Definition">red fruit</text:p>
-<text:p text:style-name="Definition_20_Term">orange</text:p>
-<text:p text:style-name="Definition_20_Definition">orange fruit</text:p>
-<text:p text:style-name="Definition_20_Term">banana</text:p>
-<text:p text:style-name="Definition_20_Definition">yellow fruit</text:p>
-<text:p text:style-name="First_20_paragraph">Multiple blocks with
-italics:</text:p>
-<text:p text:style-name="Definition_20_Term"><text:span text:style-name="T1">apple</text:span></text:p>
-<text:p text:style-name="Definition_20_Definition">red
-fruit</text:p><text:p text:style-name="Definition_20_Definition">contains
-seeds, crisp, pleasant to taste</text:p>
-<text:p text:style-name="Definition_20_Term"><text:span text:style-name="T1">orange</text:span></text:p>
-<text:p text:style-name="Definition_20_Definition">orange fruit</text:p><text:p text:style-name="P42">{ orange code block }</text:p><text:p text:style-name="P43">orange
-block quote</text:p>
-<text:p text:style-name="First_20_paragraph">Multiple definitions,
-tight:</text:p>
-<text:p text:style-name="Definition_20_Term_20_Tight">apple</text:p>
-<text:p text:style-name="Definition_20_Definition_20_Tight">red fruit</text:p>
-<text:p text:style-name="Definition_20_Definition_20_Tight">computer</text:p>
-<text:p text:style-name="Definition_20_Term_20_Tight">orange</text:p>
-<text:p text:style-name="Definition_20_Definition_20_Tight">orange
-fruit</text:p>
-<text:p text:style-name="Definition_20_Definition_20_Tight">bank</text:p>
-<text:p text:style-name="First_20_paragraph">Multiple definitions,
-loose:</text:p>
-<text:p text:style-name="Definition_20_Term">apple</text:p>
-<text:p text:style-name="Definition_20_Definition">red fruit</text:p>
-<text:p text:style-name="Definition_20_Definition">computer</text:p>
-<text:p text:style-name="Definition_20_Term">orange</text:p>
-<text:p text:style-name="Definition_20_Definition">orange fruit</text:p>
-<text:p text:style-name="Definition_20_Definition">bank</text:p>
-<text:p text:style-name="First_20_paragraph">Blank line after term, indented
-marker, alternate markers:</text:p>
-<text:p text:style-name="Definition_20_Term">apple</text:p>
-<text:p text:style-name="Definition_20_Definition">red fruit</text:p>
-<text:p text:style-name="Definition_20_Definition">computer</text:p>
-<text:p text:style-name="Definition_20_Term">orange</text:p>
-<text:p text:style-name="Definition_20_Definition">orange
-fruit</text:p><text:list text:style-name="L25">
-  <text:list-item>
-    <text:p text:style-name="P44">sublist</text:p>
-  </text:list-item>
-  <text:list-item>
-    <text:p text:style-name="P44">sublist</text:p>
-  </text:list-item>
-</text:list>
-<text:h text:style-name="Heading_20_1" text:outline-level="1">HTML
-Blocks</text:h>
-<text:p text:style-name="First_20_paragraph">Simple block on one
-line:</text:p>
-<text:p text:style-name="Text_20_body">foo</text:p>
-<text:p text:style-name="Text_20_body">And nested without
-indentation:</text:p>
-<text:p text:style-name="Text_20_body">foo</text:p>
-<text:p text:style-name="Text_20_body">bar</text:p>
-<text:p text:style-name="Text_20_body">Interpreted markdown in a
-table:</text:p>
-<text:p text:style-name="Text_20_body">This is
-<text:span text:style-name="T1">emphasized</text:span></text:p>
-<text:p text:style-name="Text_20_body">And this is
-<text:span text:style-name="T2">strong</text:span></text:p>
-<text:p text:style-name="Text_20_body">Here’s a simple block:</text:p>
-<text:p text:style-name="Text_20_body">foo</text:p>
-<text:p text:style-name="Text_20_body">This should be a code block,
-though:</text:p>
-<text:p text:style-name="P45">&lt;div&gt;</text:p>
-<text:p text:style-name="P46"><text:s text:c="4" />foo</text:p>
-<text:p text:style-name="P47">&lt;/div&gt;</text:p>
-<text:p text:style-name="First_20_paragraph">As should this:</text:p>
-<text:p text:style-name="P48">&lt;div&gt;foo&lt;/div&gt;</text:p>
-<text:p text:style-name="First_20_paragraph">Now, nested:</text:p>
-<text:p text:style-name="Text_20_body">foo</text:p>
-<text:p text:style-name="Text_20_body">This should just be an HTML
-comment:</text:p>
-<text:p text:style-name="Text_20_body">Multiline:</text:p>
-<text:p text:style-name="Text_20_body">Code block:</text:p>
-<text:p text:style-name="P49">&lt;!-- Comment --&gt;</text:p>
-<text:p text:style-name="First_20_paragraph">Just plain comment, with trailing
-spaces on the line:</text:p>
-<text:p text:style-name="Text_20_body">Code:</text:p>
-<text:p text:style-name="P50">&lt;hr /&gt;</text:p>
-<text:p text:style-name="First_20_paragraph">Hr’s:</text:p>
-<text:p text:style-name="Horizontal_20_Line" />
-<text:h text:style-name="Heading_20_1" text:outline-level="1">Inline
-Markup</text:h>
-<text:p text:style-name="First_20_paragraph">This is
-<text:span text:style-name="T1">emphasized</text:span>, and so
-<text:span text:style-name="T1">is this</text:span>.</text:p>
-<text:p text:style-name="Text_20_body">This is
-<text:span text:style-name="T2">strong</text:span>, and so
-<text:span text:style-name="T2">is this</text:span>.</text:p>
-<text:p text:style-name="Text_20_body">An
-<text:a xlink:type="simple" xlink:href="/url" office:name=""><text:span text:style-name="Definition"><text:span text:style-name="T1">emphasized
-link</text:span></text:span></text:a>.</text:p>
-<text:p text:style-name="Text_20_body"><text:span text:style-name="T3">This is
-strong and em.</text:span></text:p>
-<text:p text:style-name="Text_20_body">So is
-<text:span text:style-name="T3">this</text:span> word.</text:p>
-<text:p text:style-name="Text_20_body"><text:span text:style-name="T3">This is
-strong and em.</text:span></text:p>
-<text:p text:style-name="Text_20_body">So is
-<text:span text:style-name="T3">this</text:span> word.</text:p>
-<text:p text:style-name="Text_20_body">This is code:
-<text:span text:style-name="Source_Text">&gt;</text:span>,
-<text:span text:style-name="Source_Text">$</text:span>,
-<text:span text:style-name="Source_Text">\</text:span>,
-<text:span text:style-name="Source_Text">\$</text:span>,
-<text:span text:style-name="Source_Text">&lt;html&gt;</text:span>.</text:p>
-<text:p text:style-name="Text_20_body"><text:span text:style-name="T4">This is
-</text:span><text:span text:style-name="T5">strikeout</text:span><text:span text:style-name="T4">.</text:span></text:p>
-<text:p text:style-name="Text_20_body">Superscripts:
-a<text:span text:style-name="T6">bc</text:span>d
-a<text:span text:style-name="T7">hello</text:span>
-a<text:span text:style-name="T6">hello there</text:span>.</text:p>
-<text:p text:style-name="Text_20_body">Subscripts:
-H<text:span text:style-name="T8">2</text:span>O,
-H<text:span text:style-name="T8">23</text:span>O,
-H<text:span text:style-name="T8">many of them</text:span>O.</text:p>
-<text:p text:style-name="Text_20_body">These should not be superscripts or
-subscripts, because of the unescaped spaces: a^b c^d, a~b c~d.</text:p>
-<text:p text:style-name="Horizontal_20_Line" />
-<text:h text:style-name="Heading_20_1" text:outline-level="1">Smart quotes,
-ellipses, dashes</text:h>
-<text:p text:style-name="First_20_paragraph">“Hello,” said the spider.
-“‘Shelob’ is my name.”</text:p>
-<text:p text:style-name="Text_20_body">‘A’, ‘B’, and ‘C’ are letters.</text:p>
-<text:p text:style-name="Text_20_body">‘Oak,’ ‘elm,’ and ‘beech’ are names of
-trees. So is ‘pine.’</text:p>
-<text:p text:style-name="Text_20_body">‘He said, “I want to go.”’ Were you
-alive in the 70’s?</text:p>
-<text:p text:style-name="Text_20_body">Here is some quoted
-‘<text:span text:style-name="Source_Text">code</text:span>’ and a
-“<text:a xlink:type="simple" xlink:href="http://example.com/?foo=1&amp;bar=2" office:name=""><text:span text:style-name="Definition">quoted
-link</text:span></text:a>”.</text:p>
-<text:p text:style-name="Text_20_body">Some dashes: one—two — three—four —
-five.</text:p>
-<text:p text:style-name="Text_20_body">Dashes between numbers: 5–7, 255–66,
-1987–1999.</text:p>
-<text:p text:style-name="Text_20_body">Ellipses…and…and….</text:p>
-<text:p text:style-name="Horizontal_20_Line" />
-<text:h text:style-name="Heading_20_1" text:outline-level="1">LaTeX</text:h>
-<text:list text:style-name="L26">
-  <text:list-item>
-    <text:p text:style-name="P51"></text:p>
-  </text:list-item>
-  <text:list-item>
-    <text:p text:style-name="P51">2 + 2 = 4</text:p>
-  </text:list-item>
-  <text:list-item>
-    <text:p text:style-name="P51"><text:span text:style-name="T1">x</text:span> ∈ <text:span text:style-name="T1">y</text:span></text:p>
-  </text:list-item>
-  <text:list-item>
-    <text:p text:style-name="P51"><text:span text:style-name="T1">α</text:span> ∧ <text:span text:style-name="T1">ω</text:span></text:p>
-  </text:list-item>
-  <text:list-item>
-    <text:p text:style-name="P51">223</text:p>
-  </text:list-item>
-  <text:list-item>
-    <text:p text:style-name="P51"><text:span text:style-name="T1">p</text:span>-Tree</text:p>
-  </text:list-item>
-  <text:list-item>
-    <text:p text:style-name="P51">Here’s some display math:
-    $$\frac{d}{dx}f(x)=\lim_{h\to 0}\frac{f(x+h)-f(x)}{h}$$</text:p>
-  </text:list-item>
-  <text:list-item>
-    <text:p text:style-name="P51">Here’s one that has a line break in it:
-    <text:span text:style-name="T1">α</text:span> + <text:span text:style-name="T1">ω</text:span> × <text:span text:style-name="T1">x</text:span><text:span text:style-name="T6">2</text:span>.</text:p>
-  </text:list-item>
-</text:list>
-<text:p text:style-name="First_20_paragraph">These shouldn’t be math:</text:p>
-<text:list text:style-name="L27">
-  <text:list-item>
-    <text:p text:style-name="P52">To get the famous equation, write
-    <text:span text:style-name="Source_Text">$e = mc^2$</text:span>.</text:p>
-  </text:list-item>
-  <text:list-item>
-    <text:p text:style-name="P52">$22,000 is a
-    <text:span text:style-name="T1">lot</text:span> of money. So is $34,000.
-    (It worked if “lot” is emphasized.)</text:p>
-  </text:list-item>
-  <text:list-item>
-    <text:p text:style-name="P52">Shoes ($20) and socks ($5).</text:p>
-  </text:list-item>
-  <text:list-item>
-    <text:p text:style-name="P52">Escaped
-    <text:span text:style-name="Source_Text">$</text:span>: $73
-    <text:span text:style-name="T1">this should be emphasized</text:span>
-    23$.</text:p>
-  </text:list-item>
-</text:list>
-<text:p text:style-name="First_20_paragraph">Here’s a LaTeX table:</text:p>
-<text:p text:style-name="Horizontal_20_Line" />
-<text:h text:style-name="Heading_20_1" text:outline-level="1">Special
-Characters</text:h>
-<text:p text:style-name="First_20_paragraph">Here is some unicode:</text:p>
-<text:list text:style-name="L28">
-  <text:list-item>
-    <text:p text:style-name="P53">I hat: Î</text:p>
-  </text:list-item>
-  <text:list-item>
-    <text:p text:style-name="P53">o umlaut: ö</text:p>
-  </text:list-item>
-  <text:list-item>
-    <text:p text:style-name="P53">section: §</text:p>
-  </text:list-item>
-  <text:list-item>
-    <text:p text:style-name="P53">set membership: ∈</text:p>
-  </text:list-item>
-  <text:list-item>
-    <text:p text:style-name="P53">copyright: ©</text:p>
-  </text:list-item>
-</text:list>
-<text:p text:style-name="First_20_paragraph">AT&amp;T has an ampersand in
-their name.</text:p>
-<text:p text:style-name="Text_20_body">AT&amp;T is another way to write
-it.</text:p>
-<text:p text:style-name="Text_20_body">This &amp; that.</text:p>
-<text:p text:style-name="Text_20_body">4 &lt; 5.</text:p>
-<text:p text:style-name="Text_20_body">6 &gt; 5.</text:p>
-<text:p text:style-name="Text_20_body">Backslash: \</text:p>
-<text:p text:style-name="Text_20_body">Backtick: `</text:p>
-<text:p text:style-name="Text_20_body">Asterisk: *</text:p>
-<text:p text:style-name="Text_20_body">Underscore: _</text:p>
-<text:p text:style-name="Text_20_body">Left brace: {</text:p>
-<text:p text:style-name="Text_20_body">Right brace: }</text:p>
-<text:p text:style-name="Text_20_body">Left bracket: [</text:p>
-<text:p text:style-name="Text_20_body">Right bracket: ]</text:p>
-<text:p text:style-name="Text_20_body">Left paren: (</text:p>
-<text:p text:style-name="Text_20_body">Right paren: )</text:p>
-<text:p text:style-name="Text_20_body">Greater-than: &gt;</text:p>
-<text:p text:style-name="Text_20_body">Hash: #</text:p>
-<text:p text:style-name="Text_20_body">Period: .</text:p>
-<text:p text:style-name="Text_20_body">Bang: !</text:p>
-<text:p text:style-name="Text_20_body">Plus: +</text:p>
-<text:p text:style-name="Text_20_body">Minus: -</text:p>
-<text:p text:style-name="Horizontal_20_Line" />
-<text:h text:style-name="Heading_20_1" text:outline-level="1">Links</text:h>
-<text:h text:style-name="Heading_20_2" text:outline-level="2">Explicit</text:h>
-<text:p text:style-name="First_20_paragraph">Just a
-<text:a xlink:type="simple" xlink:href="/url/" office:name=""><text:span text:style-name="Definition">URL</text:span></text:a>.</text:p>
-<text:p text:style-name="Text_20_body"><text:a xlink:type="simple" xlink:href="/url/" office:name="title"><text:span text:style-name="Definition">URL
-and title</text:span></text:a>.</text:p>
-<text:p text:style-name="Text_20_body"><text:a xlink:type="simple" xlink:href="/url/" office:name="title preceded by two spaces"><text:span text:style-name="Definition">URL
-and title</text:span></text:a>.</text:p>
-<text:p text:style-name="Text_20_body"><text:a xlink:type="simple" xlink:href="/url/" office:name="title preceded by a tab"><text:span text:style-name="Definition">URL
-and title</text:span></text:a>.</text:p>
-<text:p text:style-name="Text_20_body"><text:a xlink:type="simple" xlink:href="/url/" office:name="title with &quot;quotes&quot; in it"><text:span text:style-name="Definition">URL
-and title</text:span></text:a></text:p>
-<text:p text:style-name="Text_20_body"><text:a xlink:type="simple" xlink:href="/url/" office:name="title with single quotes"><text:span text:style-name="Definition">URL
-and title</text:span></text:a></text:p>
-<text:p text:style-name="Text_20_body"><text:a xlink:type="simple" xlink:href="/url/with_underscore" office:name=""><text:span text:style-name="Definition">with_underscore</text:span></text:a></text:p>
-<text:p text:style-name="Text_20_body"><text:a xlink:type="simple" xlink:href="mailto:nobody@nowhere.net" office:name=""><text:span text:style-name="Definition">Email
-link</text:span></text:a></text:p>
-<text:p text:style-name="Text_20_body"><text:a xlink:type="simple" xlink:href="" office:name=""><text:span text:style-name="Definition">Empty</text:span></text:a>.</text:p>
-<text:h text:style-name="Heading_20_2" text:outline-level="2">Reference</text:h>
-<text:p text:style-name="First_20_paragraph">Foo
-<text:a xlink:type="simple" xlink:href="/url/" office:name=""><text:span text:style-name="Definition">bar</text:span></text:a>.</text:p>
-<text:p text:style-name="Text_20_body">With
-<text:a xlink:type="simple" xlink:href="/url/" office:name=""><text:span text:style-name="Definition">embedded
-[brackets]</text:span></text:a>.</text:p>
-<text:p text:style-name="Text_20_body"><text:a xlink:type="simple" xlink:href="/url/" office:name=""><text:span text:style-name="Definition">b</text:span></text:a>
-by itself should be a link.</text:p>
-<text:p text:style-name="Text_20_body">Indented
-<text:a xlink:type="simple" xlink:href="/url" office:name=""><text:span text:style-name="Definition">once</text:span></text:a>.</text:p>
-<text:p text:style-name="Text_20_body">Indented
-<text:a xlink:type="simple" xlink:href="/url" office:name=""><text:span text:style-name="Definition">twice</text:span></text:a>.</text:p>
-<text:p text:style-name="Text_20_body">Indented
-<text:a xlink:type="simple" xlink:href="/url" office:name=""><text:span text:style-name="Definition">thrice</text:span></text:a>.</text:p>
-<text:p text:style-name="Text_20_body">This should [not][] be a link.</text:p>
-<text:p text:style-name="P54">[not]: /url</text:p>
-<text:p text:style-name="First_20_paragraph">Foo
-<text:a xlink:type="simple" xlink:href="/url/" office:name="Title with &quot;quotes&quot; inside"><text:span text:style-name="Definition">bar</text:span></text:a>.</text:p>
-<text:p text:style-name="Text_20_body">Foo
-<text:a xlink:type="simple" xlink:href="/url/" office:name="Title with &quot;quote&quot; inside"><text:span text:style-name="Definition">biz</text:span></text:a>.</text:p>
-<text:h text:style-name="Heading_20_2" text:outline-level="2">With
-ampersands</text:h>
-<text:p text:style-name="First_20_paragraph">Here’s a
-<text:a xlink:type="simple" xlink:href="http://example.com/?foo=1&amp;bar=2" office:name=""><text:span text:style-name="Definition">link
-with an ampersand in the URL</text:span></text:a>.</text:p>
-<text:p text:style-name="Text_20_body">Here’s a link with an amersand in the
-link text:
-<text:a xlink:type="simple" xlink:href="http://att.com/" office:name="AT&amp;T"><text:span text:style-name="Definition">AT&amp;T</text:span></text:a>.</text:p>
-<text:p text:style-name="Text_20_body">Here’s an
-<text:a xlink:type="simple" xlink:href="/script?foo=1&amp;bar=2" office:name=""><text:span text:style-name="Definition">inline
-link</text:span></text:a>.</text:p>
-<text:p text:style-name="Text_20_body">Here’s an
-<text:a xlink:type="simple" xlink:href="/script?foo=1&amp;bar=2" office:name=""><text:span text:style-name="Definition">inline
-link in pointy braces</text:span></text:a>.</text:p>
-<text:h text:style-name="Heading_20_2" text:outline-level="2">Autolinks</text:h>
-<text:p text:style-name="First_20_paragraph">With an ampersand:
-<text:a xlink:type="simple" xlink:href="http://example.com/?foo=1&amp;bar=2" office:name=""><text:span text:style-name="Definition">http://example.com/?foo=1&amp;bar=2</text:span></text:a></text:p>
-<text:list text:style-name="L29">
-  <text:list-item>
-    <text:p text:style-name="P55">In a list?</text:p>
-  </text:list-item>
-  <text:list-item>
-    <text:p text:style-name="P55"><text:a xlink:type="simple" xlink:href="http://example.com/" office:name=""><text:span text:style-name="Definition">http://example.com/</text:span></text:a></text:p>
-  </text:list-item>
-  <text:list-item>
-    <text:p text:style-name="P55">It should.</text:p>
-  </text:list-item>
-</text:list>
-<text:p text:style-name="First_20_paragraph">An e-mail address:
-<text:a xlink:type="simple" xlink:href="mailto:nobody@nowhere.net" office:name=""><text:span text:style-name="Definition">nobody@nowhere.net</text:span></text:a></text:p>
-<text:p text:style-name="P56">Blockquoted:
-<text:a xlink:type="simple" xlink:href="http://example.com/" office:name=""><text:span text:style-name="Definition">http://example.com/</text:span></text:a></text:p>
-<text:p text:style-name="First_20_paragraph">Auto-links should not occur here:
-<text:span text:style-name="Source_Text">&lt;http://example.com/&gt;</text:span></text:p>
-<text:p text:style-name="P57">or here: &lt;http://example.com/&gt;</text:p>
-<text:p text:style-name="Horizontal_20_Line" />
-<text:h text:style-name="Heading_20_1" text:outline-level="1">Images</text:h>
-<text:p text:style-name="First_20_paragraph">From “Voyage dans la Lune” by
-Georges Melies (1902):</text:p>
-<text:p text:style-name="FigureWithCaption"><draw:frame draw:name="img1"><draw:image xlink:href="lalune.jpg" xlink:type="simple" xlink:show="embed" xlink:actuate="onLoad" /></draw:frame></text:p>
-<text:p text:style-name="FigureCaption">lalune</text:p>
-<text:p text:style-name="Text_20_body">Here is a movie
-<draw:frame draw:name="img2"><draw:image xlink:href="movie.jpg" xlink:type="simple" xlink:show="embed" xlink:actuate="onLoad" /></draw:frame>
-icon.</text:p>
-<text:p text:style-name="Horizontal_20_Line" />
-<text:h text:style-name="Heading_20_1" text:outline-level="1">Footnotes</text:h>
-<text:p text:style-name="First_20_paragraph">Here is a footnote
-reference,<text:note text:id="ftn0" text:note-class="footnote"><text:note-citation>1</text:note-citation><text:note-body><text:p text:style-name="Footnote">Here
-is the footnote. It can go anywhere after the footnote reference. It need not
-be placed at the end of the document.</text:p></text:note-body></text:note>
-and
-another.<text:note text:id="ftn1" text:note-class="footnote"><text:note-citation>2</text:note-citation><text:note-body><text:p text:style-name="Footnote">Here’s
-the long note. This one contains multiple
-blocks.</text:p><text:p text:style-name="Footnote">Subsequent blocks are
-indented to show that they belong to the footnote (as with list
-items).</text:p><text:p text:style-name="P58"><text:s text:c="2" />{ &lt;code&gt; }</text:p><text:p text:style-name="Footnote">If
-you want, you can indent every line, but you can also be lazy and just indent
-the first line of each block.</text:p></text:note-body></text:note> This
-should <text:span text:style-name="T1">not</text:span> be a footnote
-reference, because it contains a space.[^my note] Here is an inline
-note.<text:note text:id="ftn2" text:note-class="footnote"><text:note-citation>3</text:note-citation><text:note-body><text:p text:style-name="Footnote">This
-is <text:span text:style-name="T1">easier</text:span> to type. Inline notes
-may contain
-<text:a xlink:type="simple" xlink:href="http://google.com" office:name=""><text:span text:style-name="Definition">links</text:span></text:a>
-and <text:span text:style-name="Source_Text">]</text:span> verbatim
-characters, as well as [bracketed
-text].</text:p></text:note-body></text:note></text:p>
-<text:p text:style-name="P59">Notes can go in
-quotes.<text:note text:id="ftn3" text:note-class="footnote"><text:note-citation>4</text:note-citation><text:note-body><text:p text:style-name="Footnote">In
-quote.</text:p></text:note-body></text:note></text:p>
-<text:list text:style-name="L30">
-  <text:list-item>
-    <text:p text:style-name="P60">And in list
+<office:document-content xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" xmlns:style="urn:oasis:names:tc:opendocument:xmlns:style:1.0" xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0" xmlns:table="urn:oasis:names:tc:opendocument:xmlns:table:1.0" xmlns:draw="urn:oasis:names:tc:opendocument:xmlns:drawing:1.0" xmlns:fo="urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:meta="urn:oasis:names:tc:opendocument:xmlns:meta:1.0" xmlns:number="urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0" xmlns:svg="urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0" xmlns:chart="urn:oasis:names:tc:opendocument:xmlns:chart:1.0" xmlns:dr3d="urn:oasis:names:tc:opendocument:xmlns:dr3d:1.0" xmlns:math="http://www.w3.org/1998/Math/MathML" xmlns:form="urn:oasis:names:tc:opendocument:xmlns:form:1.0" xmlns:script="urn:oasis:names:tc:opendocument:xmlns:script:1.0" xmlns:ooo="http://openoffice.org/2004/office" xmlns:ooow="http://openoffice.org/2004/writer" xmlns:oooc="http://openoffice.org/2004/calc" xmlns:dom="http://www.w3.org/2001/xml-events" xmlns:xforms="http://www.w3.org/2002/xforms" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" office:version="1.3">
+  <office:font-face-decls>
+    <style:font-face style:name="Courier New" style:font-family-generic="modern" style:font-pitch="fixed" svg:font-family="'Courier New'" />
+  </office:font-face-decls>
+  <office:automatic-styles>
+    <style:style style:name="T1" style:family="text"><style:text-properties fo:font-style="italic" fo:font-weight="bold" style:font-style-asian="italic" style:font-style-complex="italic" style:font-weight-asian="bold" style:font-weight-complex="bold" /></style:style>
+    <style:style style:name="T2" style:family="text"><style:text-properties fo:font-style="italic" style:font-style-asian="italic" style:font-style-complex="italic" style:text-line-through-style="solid" /></style:style>
+    <style:style style:name="T3" style:family="text"><style:text-properties fo:font-style="italic" style:font-style-asian="italic" style:font-style-complex="italic" style:text-position="super 58%" /></style:style>
+    <style:style style:name="fr2" style:family="graphic" style:parent-style-name="Formula"><style:graphic-properties style:vertical-pos="middle" style:vertical-rel="text" style:horizontal-pos="center" style:horizontal-rel="paragraph-content" style:wrap="none" /></style:style>
+    <style:style style:name="fr1" style:family="graphic" style:parent-style-name="Formula"><style:graphic-properties style:vertical-pos="middle" style:vertical-rel="text" /></style:style>
+    <style:style style:name="P1" style:family="paragraph" style:parent-style-name="Quotations">
+      <style:paragraph-properties fo:margin-left="0.5in" fo:margin-right="0in" fo:text-indent="0in" style:auto-text-indent="false" />
+    </style:style>
+    <style:style style:name="P2" style:family="paragraph" style:parent-style-name="Quotations">
+      <style:paragraph-properties fo:margin-left="0.5in" fo:margin-right="0in" fo:text-indent="0in" style:auto-text-indent="false" />
+    </style:style>
+    <style:style style:name="P3" style:family="paragraph" style:parent-style-name="Quotations">
+      <style:paragraph-properties fo:margin-left="0.5in" fo:margin-right="0in" fo:text-indent="0in" style:auto-text-indent="false" />
+    </style:style>
+    <text:list-style style:name="Pandoc_5f_Numbering_5f_1">
+      <text:list-level-style-number text:level="1" text:style-name="Numbering_20_Symbols" style:num-format="1" style:num-prefix="(" style:num-suffix=")">
+        <style:list-level-properties text:space-before="0.0000in" text:min-label-width="0.1965in" text:min-label-distance="0.1in" />
+      </text:list-level-style-number>
+      <text:list-level-style-number text:level="2" text:style-name="Numbering_20_Symbols" style:num-format="1" style:num-prefix="(" style:num-suffix=")">
+        <style:list-level-properties text:space-before="0.1972in" text:min-label-width="0.1965in" text:min-label-distance="0.1in" />
+      </text:list-level-style-number>
+      <text:list-level-style-number text:level="3" text:style-name="Numbering_20_Symbols" style:num-format="1" style:num-prefix="(" style:num-suffix=")">
+        <style:list-level-properties text:space-before="0.3944in" text:min-label-width="0.1965in" text:min-label-distance="0.1in" />
+      </text:list-level-style-number>
+      <text:list-level-style-number text:level="4" text:style-name="Numbering_20_Symbols" style:num-format="1" style:num-prefix="(" style:num-suffix=")">
+        <style:list-level-properties text:space-before="0.5916in" text:min-label-width="0.1965in" text:min-label-distance="0.1in" />
+      </text:list-level-style-number>
+      <text:list-level-style-number text:level="5" text:style-name="Numbering_20_Symbols" style:num-format="1" style:num-prefix="(" style:num-suffix=")">
+        <style:list-level-properties text:space-before="0.7888in" text:min-label-width="0.1965in" text:min-label-distance="0.1in" />
+      </text:list-level-style-number>
+      <text:list-level-style-number text:level="6" text:style-name="Numbering_20_Symbols" style:num-format="1" style:num-prefix="(" style:num-suffix=")">
+        <style:list-level-properties text:space-before="0.9860in" text:min-label-width="0.1965in" text:min-label-distance="0.1in" />
+      </text:list-level-style-number>
+      <text:list-level-style-number text:level="7" text:style-name="Numbering_20_Symbols" style:num-format="1" style:num-prefix="(" style:num-suffix=")">
+        <style:list-level-properties text:space-before="1.1832in" text:min-label-width="0.1965in" text:min-label-distance="0.1in" />
+      </text:list-level-style-number>
+      <text:list-level-style-number text:level="8" text:style-name="Numbering_20_Symbols" style:num-format="1" style:num-prefix="(" style:num-suffix=")">
+        <style:list-level-properties text:space-before="1.3804in" text:min-label-width="0.1965in" text:min-label-distance="0.1in" />
+      </text:list-level-style-number>
+      <text:list-level-style-number text:level="9" text:style-name="Numbering_20_Symbols" style:num-format="1" style:num-prefix="(" style:num-suffix=")">
+        <style:list-level-properties text:space-before="1.5776in" text:min-label-width="0.1965in" text:min-label-distance="0.1in" />
+      </text:list-level-style-number>
+      <text:list-level-style-number text:level="10" text:style-name="Numbering_20_Symbols" style:num-format="1" style:num-prefix="(" style:num-suffix=")">
+        <style:list-level-properties text:space-before="1.7748in" text:min-label-width="0.1965in" text:min-label-distance="0.1in" />
+      </text:list-level-style-number>
+    </text:list-style>
+    <text:list-style style:name="Pandoc_5f_Numbering_5f_2">
+      <text:list-level-style-number text:level="1" text:style-name="Numbering_20_Symbols" style:num-format="i" style:num-suffix=".">
+        <style:list-level-properties text:space-before="0.0000in" text:min-label-width="0.1965in" text:min-label-distance="0.1in" />
+      </text:list-level-style-number>
+      <text:list-level-style-number text:level="2" text:style-name="Numbering_20_Symbols" style:num-format="i" style:num-suffix=".">
+        <style:list-level-properties text:space-before="0.1972in" text:min-label-width="0.1965in" text:min-label-distance="0.1in" />
+      </text:list-level-style-number>
+      <text:list-level-style-number text:level="3" text:style-name="Numbering_20_Symbols" style:num-format="i" style:num-suffix=".">
+        <style:list-level-properties text:space-before="0.3944in" text:min-label-width="0.1965in" text:min-label-distance="0.1in" />
+      </text:list-level-style-number>
+      <text:list-level-style-number text:level="4" text:style-name="Numbering_20_Symbols" style:num-format="i" style:num-suffix=".">
+        <style:list-level-properties text:space-before="0.5916in" text:min-label-width="0.1965in" text:min-label-distance="0.1in" />
+      </text:list-level-style-number>
+      <text:list-level-style-number text:level="5" text:style-name="Numbering_20_Symbols" style:num-format="i" style:num-suffix=".">
+        <style:list-level-properties text:space-before="0.7888in" text:min-label-width="0.1965in" text:min-label-distance="0.1in" />
+      </text:list-level-style-number>
+      <text:list-level-style-number text:level="6" text:style-name="Numbering_20_Symbols" style:num-format="i" style:num-suffix=".">
+        <style:list-level-properties text:space-before="0.9860in" text:min-label-width="0.1965in" text:min-label-distance="0.1in" />
+      </text:list-level-style-number>
+      <text:list-level-style-number text:level="7" text:style-name="Numbering_20_Symbols" style:num-format="i" style:num-suffix=".">
+        <style:list-level-properties text:space-before="1.1832in" text:min-label-width="0.1965in" text:min-label-distance="0.1in" />
+      </text:list-level-style-number>
+      <text:list-level-style-number text:level="8" text:style-name="Numbering_20_Symbols" style:num-format="i" style:num-suffix=".">
+        <style:list-level-properties text:space-before="1.3804in" text:min-label-width="0.1965in" text:min-label-distance="0.1in" />
+      </text:list-level-style-number>
+      <text:list-level-style-number text:level="9" text:style-name="Numbering_20_Symbols" style:num-format="i" style:num-suffix=".">
+        <style:list-level-properties text:space-before="1.5776in" text:min-label-width="0.1965in" text:min-label-distance="0.1in" />
+      </text:list-level-style-number>
+      <text:list-level-style-number text:level="10" text:style-name="Numbering_20_Symbols" style:num-format="i" style:num-suffix=".">
+        <style:list-level-properties text:space-before="1.7748in" text:min-label-width="0.1965in" text:min-label-distance="0.1in" />
+      </text:list-level-style-number>
+    </text:list-style>
+    <text:list-style style:name="Pandoc_5f_Numbering_5f_5">
+      <text:list-level-style-number text:level="1" text:style-name="Numbering_20_Symbols" style:num-format="I" style:num-suffix=".">
+        <style:list-level-properties text:space-before="0.0000in" text:min-label-width="0.1965in" text:min-label-distance="0.1in" />
+      </text:list-level-style-number>
+      <text:list-level-style-number text:level="2" text:style-name="Numbering_20_Symbols" style:num-format="I" style:num-suffix=".">
+        <style:list-level-properties text:space-before="0.1972in" text:min-label-width="0.1965in" text:min-label-distance="0.1in" />
+      </text:list-level-style-number>
+      <text:list-level-style-number text:level="3" text:style-name="Numbering_20_Symbols" style:num-format="I" style:num-suffix=".">
+        <style:list-level-properties text:space-before="0.3944in" text:min-label-width="0.1965in" text:min-label-distance="0.1in" />
+      </text:list-level-style-number>
+      <text:list-level-style-number text:level="4" text:style-name="Numbering_20_Symbols" style:num-format="I" style:num-suffix=".">
+        <style:list-level-properties text:space-before="0.5916in" text:min-label-width="0.1965in" text:min-label-distance="0.1in" />
+      </text:list-level-style-number>
+      <text:list-level-style-number text:level="5" text:style-name="Numbering_20_Symbols" style:num-format="I" style:num-suffix=".">
+        <style:list-level-properties text:space-before="0.7888in" text:min-label-width="0.1965in" text:min-label-distance="0.1in" />
+      </text:list-level-style-number>
+      <text:list-level-style-number text:level="6" text:style-name="Numbering_20_Symbols" style:num-format="I" style:num-suffix=".">
+        <style:list-level-properties text:space-before="0.9860in" text:min-label-width="0.1965in" text:min-label-distance="0.1in" />
+      </text:list-level-style-number>
+      <text:list-level-style-number text:level="7" text:style-name="Numbering_20_Symbols" style:num-format="I" style:num-suffix=".">
+        <style:list-level-properties text:space-before="1.1832in" text:min-label-width="0.1965in" text:min-label-distance="0.1in" />
+      </text:list-level-style-number>
+      <text:list-level-style-number text:level="8" text:style-name="Numbering_20_Symbols" style:num-format="I" style:num-suffix=".">
+        <style:list-level-properties text:space-before="1.3804in" text:min-label-width="0.1965in" text:min-label-distance="0.1in" />
+      </text:list-level-style-number>
+      <text:list-level-style-number text:level="9" text:style-name="Numbering_20_Symbols" style:num-format="I" style:num-suffix=".">
+        <style:list-level-properties text:space-before="1.5776in" text:min-label-width="0.1965in" text:min-label-distance="0.1in" />
+      </text:list-level-style-number>
+      <text:list-level-style-number text:level="10" text:style-name="Numbering_20_Symbols" style:num-format="I" style:num-suffix=".">
+        <style:list-level-properties text:space-before="1.7748in" text:min-label-width="0.1965in" text:min-label-distance="0.1in" />
+      </text:list-level-style-number>
+    </text:list-style>
+    <text:list-style style:name="Pandoc_5f_Numbering_5f_6">
+      <text:list-level-style-number text:level="1" text:style-name="Numbering_20_Symbols" style:num-format="a" style:num-suffix=")">
+        <style:list-level-properties text:space-before="0.0000in" text:min-label-width="0.1965in" text:min-label-distance="0.1in" />
+      </text:list-level-style-number>
+      <text:list-level-style-number text:level="2" text:style-name="Numbering_20_Symbols" style:num-format="a" style:num-suffix=")">
+        <style:list-level-properties text:space-before="0.1972in" text:min-label-width="0.1965in" text:min-label-distance="0.1in" />
+      </text:list-level-style-number>
+      <text:list-level-style-number text:level="3" text:style-name="Numbering_20_Symbols" style:num-format="a" style:num-suffix=")">
+        <style:list-level-properties text:space-before="0.3944in" text:min-label-width="0.1965in" text:min-label-distance="0.1in" />
+      </text:list-level-style-number>
+      <text:list-level-style-number text:level="4" text:style-name="Numbering_20_Symbols" style:num-format="a" style:num-suffix=")">
+        <style:list-level-properties text:space-before="0.5916in" text:min-label-width="0.1965in" text:min-label-distance="0.1in" />
+      </text:list-level-style-number>
+      <text:list-level-style-number text:level="5" text:style-name="Numbering_20_Symbols" style:num-format="a" style:num-suffix=")">
+        <style:list-level-properties text:space-before="0.7888in" text:min-label-width="0.1965in" text:min-label-distance="0.1in" />
+      </text:list-level-style-number>
+      <text:list-level-style-number text:level="6" text:style-name="Numbering_20_Symbols" style:num-format="a" style:num-suffix=")">
+        <style:list-level-properties text:space-before="0.9860in" text:min-label-width="0.1965in" text:min-label-distance="0.1in" />
+      </text:list-level-style-number>
+      <text:list-level-style-number text:level="7" text:style-name="Numbering_20_Symbols" style:num-format="a" style:num-suffix=")">
+        <style:list-level-properties text:space-before="1.1832in" text:min-label-width="0.1965in" text:min-label-distance="0.1in" />
+      </text:list-level-style-number>
+      <text:list-level-style-number text:level="8" text:style-name="Numbering_20_Symbols" style:num-format="a" style:num-suffix=")">
+        <style:list-level-properties text:space-before="1.3804in" text:min-label-width="0.1965in" text:min-label-distance="0.1in" />
+      </text:list-level-style-number>
+      <text:list-level-style-number text:level="9" text:style-name="Numbering_20_Symbols" style:num-format="a" style:num-suffix=")">
+        <style:list-level-properties text:space-before="1.5776in" text:min-label-width="0.1965in" text:min-label-distance="0.1in" />
+      </text:list-level-style-number>
+      <text:list-level-style-number text:level="10" text:style-name="Numbering_20_Symbols" style:num-format="a" style:num-suffix=")">
+        <style:list-level-properties text:space-before="1.7748in" text:min-label-width="0.1965in" text:min-label-distance="0.1in" />
+      </text:list-level-style-number>
+    </text:list-style>
+    <text:list-style style:name="Pandoc_5f_Numbering_5f_4">
+      <text:list-level-style-number text:level="1" text:style-name="Numbering_20_Symbols" style:num-format="A" style:num-suffix=".">
+        <style:list-level-properties text:space-before="0.0000in" text:min-label-width="0.1965in" text:min-label-distance="0.1in" />
+      </text:list-level-style-number>
+      <text:list-level-style-number text:level="2" text:style-name="Numbering_20_Symbols" style:num-format="A" style:num-suffix=".">
+        <style:list-level-properties text:space-before="0.1972in" text:min-label-width="0.1965in" text:min-label-distance="0.1in" />
+      </text:list-level-style-number>
+      <text:list-level-style-number text:level="3" text:style-name="Numbering_20_Symbols" style:num-format="A" style:num-suffix=".">
+        <style:list-level-properties text:space-before="0.3944in" text:min-label-width="0.1965in" text:min-label-distance="0.1in" />
+      </text:list-level-style-number>
+      <text:list-level-style-number text:level="4" text:style-name="Numbering_20_Symbols" style:num-format="A" style:num-suffix=".">
+        <style:list-level-properties text:space-before="0.5916in" text:min-label-width="0.1965in" text:min-label-distance="0.1in" />
+      </text:list-level-style-number>
+      <text:list-level-style-number text:level="5" text:style-name="Numbering_20_Symbols" style:num-format="A" style:num-suffix=".">
+        <style:list-level-properties text:space-before="0.7888in" text:min-label-width="0.1965in" text:min-label-distance="0.1in" />
+      </text:list-level-style-number>
+      <text:list-level-style-number text:level="6" text:style-name="Numbering_20_Symbols" style:num-format="A" style:num-suffix=".">
+        <style:list-level-properties text:space-before="0.9860in" text:min-label-width="0.1965in" text:min-label-distance="0.1in" />
+      </text:list-level-style-number>
+      <text:list-level-style-number text:level="7" text:style-name="Numbering_20_Symbols" style:num-format="A" style:num-suffix=".">
+        <style:list-level-properties text:space-before="1.1832in" text:min-label-width="0.1965in" text:min-label-distance="0.1in" />
+      </text:list-level-style-number>
+      <text:list-level-style-number text:level="8" text:style-name="Numbering_20_Symbols" style:num-format="A" style:num-suffix=".">
+        <style:list-level-properties text:space-before="1.3804in" text:min-label-width="0.1965in" text:min-label-distance="0.1in" />
+      </text:list-level-style-number>
+      <text:list-level-style-number text:level="9" text:style-name="Numbering_20_Symbols" style:num-format="A" style:num-suffix=".">
+        <style:list-level-properties text:space-before="1.5776in" text:min-label-width="0.1965in" text:min-label-distance="0.1in" />
+      </text:list-level-style-number>
+      <text:list-level-style-number text:level="10" text:style-name="Numbering_20_Symbols" style:num-format="A" style:num-suffix=".">
+        <style:list-level-properties text:space-before="1.7748in" text:min-label-width="0.1965in" text:min-label-distance="0.1in" />
+      </text:list-level-style-number>
+    </text:list-style>
+    <text:list-style style:name="Pandoc_5f_Numbering_5f_3">
+      <text:list-level-style-number text:level="1" text:style-name="Numbering_20_Symbols" style:num-format="A" style:num-prefix="(" style:num-suffix=")">
+        <style:list-level-properties text:space-before="0.0000in" text:min-label-width="0.1965in" text:min-label-distance="0.1in" />
+      </text:list-level-style-number>
+      <text:list-level-style-number text:level="2" text:style-name="Numbering_20_Symbols" style:num-format="A" style:num-prefix="(" style:num-suffix=")">
+        <style:list-level-properties text:space-before="0.1972in" text:min-label-width="0.1965in" text:min-label-distance="0.1in" />
+      </text:list-level-style-number>
+      <text:list-level-style-number text:level="3" text:style-name="Numbering_20_Symbols" style:num-format="A" style:num-prefix="(" style:num-suffix=")">
+        <style:list-level-properties text:space-before="0.3944in" text:min-label-width="0.1965in" text:min-label-distance="0.1in" />
+      </text:list-level-style-number>
+      <text:list-level-style-number text:level="4" text:style-name="Numbering_20_Symbols" style:num-format="A" style:num-prefix="(" style:num-suffix=")">
+        <style:list-level-properties text:space-before="0.5916in" text:min-label-width="0.1965in" text:min-label-distance="0.1in" />
+      </text:list-level-style-number>
+      <text:list-level-style-number text:level="5" text:style-name="Numbering_20_Symbols" style:num-format="A" style:num-prefix="(" style:num-suffix=")">
+        <style:list-level-properties text:space-before="0.7888in" text:min-label-width="0.1965in" text:min-label-distance="0.1in" />
+      </text:list-level-style-number>
+      <text:list-level-style-number text:level="6" text:style-name="Numbering_20_Symbols" style:num-format="A" style:num-prefix="(" style:num-suffix=")">
+        <style:list-level-properties text:space-before="0.9860in" text:min-label-width="0.1965in" text:min-label-distance="0.1in" />
+      </text:list-level-style-number>
+      <text:list-level-style-number text:level="7" text:style-name="Numbering_20_Symbols" style:num-format="A" style:num-prefix="(" style:num-suffix=")">
+        <style:list-level-properties text:space-before="1.1832in" text:min-label-width="0.1965in" text:min-label-distance="0.1in" />
+      </text:list-level-style-number>
+      <text:list-level-style-number text:level="8" text:style-name="Numbering_20_Symbols" style:num-format="A" style:num-prefix="(" style:num-suffix=")">
+        <style:list-level-properties text:space-before="1.3804in" text:min-label-width="0.1965in" text:min-label-distance="0.1in" />
+      </text:list-level-style-number>
+      <text:list-level-style-number text:level="9" text:style-name="Numbering_20_Symbols" style:num-format="A" style:num-prefix="(" style:num-suffix=")">
+        <style:list-level-properties text:space-before="1.5776in" text:min-label-width="0.1965in" text:min-label-distance="0.1in" />
+      </text:list-level-style-number>
+      <text:list-level-style-number text:level="10" text:style-name="Numbering_20_Symbols" style:num-format="A" style:num-prefix="(" style:num-suffix=")">
+        <style:list-level-properties text:space-before="1.7748in" text:min-label-width="0.1965in" text:min-label-distance="0.1in" />
+      </text:list-level-style-number>
+    </text:list-style>
+  </office:automatic-styles>
+<office:body>
+<office:text>
+<text:p text:style-name="Title">Pandoc Test Suite</text:p>
+<text:p text:style-name="Author">John MacFarlane</text:p>
+<text:p text:style-name="Author">Anonymous</text:p>
+<text:p text:style-name="Date">July 17, 2006</text:p>
+<text:p text:style-name="Text_20_body">This is a set of tests for pandoc. Most
+of them are adapted from John Gruber’s markdown test suite.</text:p>
+<text:p text:style-name="Horizontal_20_Line" />
+<text:h text:style-name="Heading_20_1" text:outline-level="1"><text:bookmark-start text:name="headers" />Headers<text:bookmark-end text:name="headers" /></text:h>
+<text:h text:style-name="Heading_20_2" text:outline-level="2"><text:bookmark-start text:name="level-2-with-an-embedded-link" />Level
+2 with an
+<text:a xlink:type="simple" xlink:href="/url" office:name=""><text:span text:style-name="Definition">embedded
+link</text:span></text:a><text:bookmark-end text:name="level-2-with-an-embedded-link" /></text:h>
+<text:h text:style-name="Heading_20_3" text:outline-level="3"><text:bookmark-start text:name="level-3-with-emphasis" />Level
+3 with
+<text:span text:style-name="Emphasis">emphasis</text:span><text:bookmark-end text:name="level-3-with-emphasis" /></text:h>
+<text:h text:style-name="Heading_20_4" text:outline-level="4"><text:bookmark-start text:name="level-4" />Level
+4<text:bookmark-end text:name="level-4" /></text:h>
+<text:h text:style-name="Heading_20_5" text:outline-level="5"><text:bookmark-start text:name="level-5" />Level
+5<text:bookmark-end text:name="level-5" /></text:h>
+<text:h text:style-name="Heading_20_1" text:outline-level="1"><text:bookmark-start text:name="level-1" />Level
+1<text:bookmark-end text:name="level-1" /></text:h>
+<text:h text:style-name="Heading_20_2" text:outline-level="2"><text:bookmark-start text:name="level-2-with-emphasis" />Level
+2 with
+<text:span text:style-name="Emphasis">emphasis</text:span><text:bookmark-end text:name="level-2-with-emphasis" /></text:h>
+<text:h text:style-name="Heading_20_3" text:outline-level="3"><text:bookmark-start text:name="level-3" />Level
+3<text:bookmark-end text:name="level-3" /></text:h>
+<text:p text:style-name="First_20_paragraph">with no blank line</text:p>
+<text:h text:style-name="Heading_20_2" text:outline-level="2"><text:bookmark-start text:name="level-2" />Level
+2<text:bookmark-end text:name="level-2" /></text:h>
+<text:p text:style-name="First_20_paragraph">with no blank line</text:p>
+<text:p text:style-name="Horizontal_20_Line" />
+<text:h text:style-name="Heading_20_1" text:outline-level="1"><text:bookmark-start text:name="paragraphs" />Paragraphs<text:bookmark-end text:name="paragraphs" /></text:h>
+<text:p text:style-name="First_20_paragraph">Here’s a regular
+paragraph.</text:p>
+<text:p text:style-name="Text_20_body">In Markdown 1.0.0 and earlier. Version 8.
+This line turns into a list item. Because a hard-wrapped line in the middle of a
+paragraph looked like a list item.</text:p>
+<text:p text:style-name="Text_20_body">Here’s one with a bullet. *
+criminey.</text:p>
+<text:p text:style-name="Text_20_body">There should be a hard line
+break<text:line-break />here.</text:p>
+<text:p text:style-name="Horizontal_20_Line" />
+<text:h text:style-name="Heading_20_1" text:outline-level="1"><text:bookmark-start text:name="block-quotes" />Block
+Quotes<text:bookmark-end text:name="block-quotes" /></text:h>
+<text:p text:style-name="First_20_paragraph">E-mail style:</text:p>
+<text:p text:style-name="Quotations">This is a block quote. It is pretty
+short.</text:p>
+<text:p text:style-name="Quotations">Code in a block quote:</text:p>
+<text:p text:style-name="Preformatted_20_Text">sub status {</text:p>
+<text:p text:style-name="Preformatted_20_Text"><text:s text:c="4" />print &quot;working&quot;;</text:p>
+<text:p text:style-name="Preformatted_20_Text">}</text:p>
+<text:p text:style-name="Quotations">A list:</text:p>
+<text:list text:style-name="Numbering_20_1">
+  <text:list-item>
+    <text:p text:style-name="List_20_Number_20_Tight">item one</text:p>
+  </text:list-item>
+  <text:list-item>
+    <text:p text:style-name="List_20_Number_20_Tight">item two</text:p>
+  </text:list-item>
+</text:list>
+<text:p text:style-name="Quotations">Nested block quotes:</text:p>
+<text:p text:style-name="P1">nested</text:p>
+<text:p text:style-name="P2">nested</text:p>
+<text:p text:style-name="First_20_paragraph">This should not be a block quote: 2
+&gt; 1.</text:p>
+<text:p text:style-name="Text_20_body">And a following paragraph.</text:p>
+<text:p text:style-name="Horizontal_20_Line" />
+<text:h text:style-name="Heading_20_1" text:outline-level="1"><text:bookmark-start text:name="code-blocks" />Code
+Blocks<text:bookmark-end text:name="code-blocks" /></text:h>
+<text:p text:style-name="First_20_paragraph">Code:</text:p>
+<text:p text:style-name="Preformatted_20_Text">---- (should be four hyphens)</text:p>
+<text:p text:style-name="Preformatted_20_Text"></text:p>
+<text:p text:style-name="Preformatted_20_Text">sub status {</text:p>
+<text:p text:style-name="Preformatted_20_Text"><text:s text:c="4" />print &quot;working&quot;;</text:p>
+<text:p text:style-name="Preformatted_20_Text">}</text:p>
+<text:p text:style-name="Preformatted_20_Text"></text:p>
+<text:p text:style-name="Preformatted_20_Text">this code block is indented by one tab</text:p>
+<text:p text:style-name="First_20_paragraph">And:</text:p>
+<text:p text:style-name="Preformatted_20_Text"><text:s text:c="4" />this code block is indented by two tabs</text:p>
+<text:p text:style-name="Preformatted_20_Text"></text:p>
+<text:p text:style-name="Preformatted_20_Text">These should not be escaped: <text:s text:c="1" />\$ \\ \&gt; \[ \{</text:p>
+<text:p text:style-name="Horizontal_20_Line" />
+<text:h text:style-name="Heading_20_1" text:outline-level="1"><text:bookmark-start text:name="lists" />Lists<text:bookmark-end text:name="lists" /></text:h>
+<text:h text:style-name="Heading_20_2" text:outline-level="2"><text:bookmark-start text:name="unordered" />Unordered<text:bookmark-end text:name="unordered" /></text:h>
+<text:p text:style-name="First_20_paragraph">Asterisks tight:</text:p>
+<text:list text:style-name="List_20_1">
+  <text:list-item>
+    <text:p text:style-name="List_20_Bullet_20_Tight">asterisk 1</text:p>
+  </text:list-item>
+  <text:list-item>
+    <text:p text:style-name="List_20_Bullet_20_Tight">asterisk 2</text:p>
+  </text:list-item>
+  <text:list-item>
+    <text:p text:style-name="List_20_Bullet_20_Tight">asterisk 3</text:p>
+  </text:list-item>
+</text:list>
+<text:p text:style-name="First_20_paragraph">Asterisks loose:</text:p>
+<text:list text:style-name="List_20_1">
+  <text:list-item>
+    <text:p text:style-name="List_20_Bullet">asterisk 1</text:p>
+  </text:list-item>
+  <text:list-item>
+    <text:p text:style-name="List_20_Bullet">asterisk 2</text:p>
+  </text:list-item>
+  <text:list-item>
+    <text:p text:style-name="List_20_Bullet">asterisk 3</text:p>
+  </text:list-item>
+</text:list>
+<text:p text:style-name="First_20_paragraph">Pluses tight:</text:p>
+<text:list text:style-name="List_20_1">
+  <text:list-item>
+    <text:p text:style-name="List_20_Bullet_20_Tight">Plus 1</text:p>
+  </text:list-item>
+  <text:list-item>
+    <text:p text:style-name="List_20_Bullet_20_Tight">Plus 2</text:p>
+  </text:list-item>
+  <text:list-item>
+    <text:p text:style-name="List_20_Bullet_20_Tight">Plus 3</text:p>
+  </text:list-item>
+</text:list>
+<text:p text:style-name="First_20_paragraph">Pluses loose:</text:p>
+<text:list text:style-name="List_20_1">
+  <text:list-item>
+    <text:p text:style-name="List_20_Bullet">Plus 1</text:p>
+  </text:list-item>
+  <text:list-item>
+    <text:p text:style-name="List_20_Bullet">Plus 2</text:p>
+  </text:list-item>
+  <text:list-item>
+    <text:p text:style-name="List_20_Bullet">Plus 3</text:p>
+  </text:list-item>
+</text:list>
+<text:p text:style-name="First_20_paragraph">Minuses tight:</text:p>
+<text:list text:style-name="List_20_1">
+  <text:list-item>
+    <text:p text:style-name="List_20_Bullet_20_Tight">Minus 1</text:p>
+  </text:list-item>
+  <text:list-item>
+    <text:p text:style-name="List_20_Bullet_20_Tight">Minus 2</text:p>
+  </text:list-item>
+  <text:list-item>
+    <text:p text:style-name="List_20_Bullet_20_Tight">Minus 3</text:p>
+  </text:list-item>
+</text:list>
+<text:p text:style-name="First_20_paragraph">Minuses loose:</text:p>
+<text:list text:style-name="List_20_1">
+  <text:list-item>
+    <text:p text:style-name="List_20_Bullet">Minus 1</text:p>
+  </text:list-item>
+  <text:list-item>
+    <text:p text:style-name="List_20_Bullet">Minus 2</text:p>
+  </text:list-item>
+  <text:list-item>
+    <text:p text:style-name="List_20_Bullet">Minus 3</text:p>
+  </text:list-item>
+</text:list>
+<text:h text:style-name="Heading_20_2" text:outline-level="2"><text:bookmark-start text:name="ordered" />Ordered<text:bookmark-end text:name="ordered" /></text:h>
+<text:p text:style-name="First_20_paragraph">Tight:</text:p>
+<text:list text:style-name="Numbering_20_1">
+  <text:list-item>
+    <text:p text:style-name="List_20_Number_20_Tight">First</text:p>
+  </text:list-item>
+  <text:list-item>
+    <text:p text:style-name="List_20_Number_20_Tight">Second</text:p>
+  </text:list-item>
+  <text:list-item>
+    <text:p text:style-name="List_20_Number_20_Tight">Third</text:p>
+  </text:list-item>
+</text:list>
+<text:p text:style-name="First_20_paragraph">and:</text:p>
+<text:list text:style-name="Numbering_20_1">
+  <text:list-item>
+    <text:p text:style-name="List_20_Number_20_Tight">One</text:p>
+  </text:list-item>
+  <text:list-item>
+    <text:p text:style-name="List_20_Number_20_Tight">Two</text:p>
+  </text:list-item>
+  <text:list-item>
+    <text:p text:style-name="List_20_Number_20_Tight">Three</text:p>
+  </text:list-item>
+</text:list>
+<text:p text:style-name="First_20_paragraph">Loose using tabs:</text:p>
+<text:list text:style-name="Numbering_20_1">
+  <text:list-item>
+    <text:p text:style-name="List_20_Number">First</text:p>
+  </text:list-item>
+  <text:list-item>
+    <text:p text:style-name="List_20_Number">Second</text:p>
+  </text:list-item>
+  <text:list-item>
+    <text:p text:style-name="List_20_Number">Third</text:p>
+  </text:list-item>
+</text:list>
+<text:p text:style-name="First_20_paragraph">and using spaces:</text:p>
+<text:list text:style-name="Numbering_20_1">
+  <text:list-item>
+    <text:p text:style-name="List_20_Number">One</text:p>
+  </text:list-item>
+  <text:list-item>
+    <text:p text:style-name="List_20_Number">Two</text:p>
+  </text:list-item>
+  <text:list-item>
+    <text:p text:style-name="List_20_Number">Three</text:p>
+  </text:list-item>
+</text:list>
+<text:p text:style-name="First_20_paragraph">Multiple paragraphs:</text:p>
+<text:list text:style-name="Numbering_20_1">
+  <text:list-item>
+    <text:p text:style-name="List_20_Number">Item 1, graf one.</text:p>
+    <text:p text:style-name="List_20_Number">Item 1. graf two. The quick brown
+    fox jumped over the lazy dog’s back.</text:p>
+  </text:list-item>
+  <text:list-item>
+    <text:p text:style-name="List_20_Number">Item 2.</text:p>
+  </text:list-item>
+  <text:list-item>
+    <text:p text:style-name="List_20_Number">Item 3.</text:p>
+  </text:list-item>
+</text:list>
+<text:h text:style-name="Heading_20_2" text:outline-level="2"><text:bookmark-start text:name="nested" />Nested<text:bookmark-end text:name="nested" /></text:h>
+<text:list text:style-name="List_20_1">
+  <text:list-item>
+    <text:p text:style-name="List_20_Bullet_20_Tight">Tab</text:p><text:list text:style-name="List_20_1">
+      <text:list-item>
+        <text:p text:style-name="List_20_Bullet_20_Tight">Tab</text:p><text:list text:style-name="List_20_1">
+          <text:list-item>
+            <text:p text:style-name="List_20_Bullet_20_Tight">Tab</text:p>
+          </text:list-item>
+        </text:list>
+      </text:list-item>
+    </text:list>
+  </text:list-item>
+</text:list>
+<text:p text:style-name="First_20_paragraph">Here’s another:</text:p>
+<text:list text:style-name="Numbering_20_1">
+  <text:list-item>
+    <text:p text:style-name="List_20_Number_20_Tight">First</text:p>
+  </text:list-item>
+  <text:list-item>
+    <text:p text:style-name="List_20_Number_20_Tight">Second:</text:p>
+    <text:list text:style-name="List_20_1">
+      <text:list-item>
+        <text:p text:style-name="List_20_Bullet_20_Tight">Fee</text:p>
+      </text:list-item>
+      <text:list-item>
+        <text:p text:style-name="List_20_Bullet_20_Tight">Fie</text:p>
+      </text:list-item>
+      <text:list-item>
+        <text:p text:style-name="List_20_Bullet_20_Tight">Foe</text:p>
+      </text:list-item>
+    </text:list>
+  </text:list-item>
+  <text:list-item>
+    <text:p text:style-name="List_20_Number_20_Tight">Third</text:p>
+  </text:list-item>
+</text:list>
+<text:p text:style-name="First_20_paragraph">Same thing but with
+paragraphs:</text:p>
+<text:list text:style-name="Numbering_20_1">
+  <text:list-item>
+    <text:p text:style-name="List_20_Number">First</text:p>
+  </text:list-item>
+  <text:list-item>
+    <text:p text:style-name="List_20_Number">Second:</text:p>
+    <text:list text:style-name="List_20_1">
+      <text:list-item>
+        <text:p text:style-name="List_20_Bullet_20_Tight">Fee</text:p>
+      </text:list-item>
+      <text:list-item>
+        <text:p text:style-name="List_20_Bullet_20_Tight">Fie</text:p>
+      </text:list-item>
+      <text:list-item>
+        <text:p text:style-name="List_20_Bullet_20_Tight">Foe</text:p>
+      </text:list-item>
+    </text:list>
+  </text:list-item>
+  <text:list-item>
+    <text:p text:style-name="List_20_Number">Third</text:p>
+  </text:list-item>
+</text:list>
+<text:h text:style-name="Heading_20_2" text:outline-level="2"><text:bookmark-start text:name="tabs-and-spaces" />Tabs
+and spaces<text:bookmark-end text:name="tabs-and-spaces" /></text:h>
+<text:list text:style-name="List_20_1">
+  <text:list-item>
+    <text:p text:style-name="List_20_Bullet">this is a list item indented with
+    tabs</text:p>
+  </text:list-item>
+  <text:list-item>
+    <text:p text:style-name="List_20_Bullet">this is a list item indented with
+    spaces</text:p><text:list text:style-name="List_20_1">
+      <text:list-item>
+        <text:p text:style-name="List_20_Bullet">this is an example list item
+        indented with tabs</text:p>
+      </text:list-item>
+      <text:list-item>
+        <text:p text:style-name="List_20_Bullet">this is an example list item
+        indented with spaces</text:p>
+      </text:list-item>
+    </text:list>
+  </text:list-item>
+</text:list>
+<text:h text:style-name="Heading_20_2" text:outline-level="2"><text:bookmark-start text:name="fancy-list-markers" />Fancy
+list markers<text:bookmark-end text:name="fancy-list-markers" /></text:h>
+<text:list text:style-name="Pandoc_5f_Numbering_5f_1" text:start-value="2">
+  <text:list-item>
+    <text:p text:style-name="List_20_Number">begins with 2</text:p>
+  </text:list-item>
+  <text:list-item>
+    <text:p text:style-name="List_20_Number">and now 3</text:p>
+    <text:p text:style-name="List_20_Number">with a continuation</text:p>
+    <text:list text:style-name="Pandoc_5f_Numbering_5f_2" text:start-value="4">
+      <text:list-item>
+        <text:p text:style-name="List_20_Number_20_Tight">sublist with roman
+        numerals, starting with 4</text:p>
+      </text:list-item>
+      <text:list-item>
+        <text:p text:style-name="List_20_Number_20_Tight">more items</text:p>
+        <text:list text:style-name="Pandoc_5f_Numbering_5f_3">
+          <text:list-item>
+            <text:p text:style-name="List_20_Number_20_Tight">a
+            subsublist</text:p>
+          </text:list-item>
+          <text:list-item>
+            <text:p text:style-name="List_20_Number_20_Tight">a
+            subsublist</text:p>
+          </text:list-item>
+        </text:list>
+      </text:list-item>
+    </text:list>
+  </text:list-item>
+</text:list>
+<text:p text:style-name="First_20_paragraph">Nesting:</text:p>
+<text:list text:style-name="Pandoc_5f_Numbering_5f_4">
+  <text:list-item>
+    <text:p text:style-name="List_20_Number_20_Tight">Upper Alpha</text:p>
+    <text:list text:style-name="Pandoc_5f_Numbering_5f_5">
+      <text:list-item>
+        <text:p text:style-name="List_20_Number_20_Tight">Upper Roman.</text:p>
+        <text:list text:style-name="Pandoc_5f_Numbering_5f_1" text:start-value="6">
+          <text:list-item>
+            <text:p text:style-name="List_20_Number_20_Tight">Decimal start with
+            6</text:p>
+            <text:list text:style-name="Pandoc_5f_Numbering_5f_6" text:start-value="3">
+              <text:list-item>
+                <text:p text:style-name="List_20_Number_20_Tight">Lower alpha
+                with paren</text:p>
+              </text:list-item>
+            </text:list>
+          </text:list-item>
+        </text:list>
+      </text:list-item>
+    </text:list>
+  </text:list-item>
+</text:list>
+<text:p text:style-name="First_20_paragraph">Autonumbering:</text:p>
+<text:list text:style-name="Numbering_20_1">
+  <text:list-item>
+    <text:p text:style-name="List_20_Number_20_Tight">Autonumber.</text:p>
+  </text:list-item>
+  <text:list-item>
+    <text:p text:style-name="List_20_Number_20_Tight">More.</text:p>
+    <text:list text:style-name="Numbering_20_1">
+      <text:list-item>
+        <text:p text:style-name="List_20_Number_20_Tight">Nested.</text:p>
+      </text:list-item>
+    </text:list>
+  </text:list-item>
+</text:list>
+<text:p text:style-name="First_20_paragraph">Should not be a list item:</text:p>
+<text:p text:style-name="Text_20_body">M.A. 2007</text:p>
+<text:p text:style-name="Text_20_body">B. Williams</text:p>
+<text:p text:style-name="Horizontal_20_Line" />
+<text:h text:style-name="Heading_20_1" text:outline-level="1"><text:bookmark-start text:name="definition-lists" />Definition
+Lists<text:bookmark-end text:name="definition-lists" /></text:h>
+<text:p text:style-name="First_20_paragraph">Tight using spaces:</text:p>
+<text:p text:style-name="Definition_20_Term_20_Tight">apple</text:p>
+<text:p text:style-name="Definition_20_Definition_20_Tight">red fruit</text:p>
+<text:p text:style-name="Definition_20_Term_20_Tight">orange</text:p>
+<text:p text:style-name="Definition_20_Definition_20_Tight">orange
+fruit</text:p>
+<text:p text:style-name="Definition_20_Term_20_Tight">banana</text:p>
+<text:p text:style-name="Definition_20_Definition_20_Tight">yellow
+fruit</text:p>
+<text:p text:style-name="First_20_paragraph">Tight using tabs:</text:p>
+<text:p text:style-name="Definition_20_Term_20_Tight">apple</text:p>
+<text:p text:style-name="Definition_20_Definition_20_Tight">red fruit</text:p>
+<text:p text:style-name="Definition_20_Term_20_Tight">orange</text:p>
+<text:p text:style-name="Definition_20_Definition_20_Tight">orange
+fruit</text:p>
+<text:p text:style-name="Definition_20_Term_20_Tight">banana</text:p>
+<text:p text:style-name="Definition_20_Definition_20_Tight">yellow
+fruit</text:p>
+<text:p text:style-name="First_20_paragraph">Loose:</text:p>
+<text:p text:style-name="Definition_20_Term">apple</text:p>
+<text:p text:style-name="Definition_20_Definition">red fruit</text:p>
+<text:p text:style-name="Definition_20_Term">orange</text:p>
+<text:p text:style-name="Definition_20_Definition">orange fruit</text:p>
+<text:p text:style-name="Definition_20_Term">banana</text:p>
+<text:p text:style-name="Definition_20_Definition">yellow fruit</text:p>
+<text:p text:style-name="First_20_paragraph">Multiple blocks with
+italics:</text:p>
+<text:p text:style-name="Definition_20_Term"><text:span text:style-name="Emphasis">apple</text:span></text:p>
+<text:p text:style-name="Definition_20_Definition">red
+fruit</text:p><text:p text:style-name="Definition_20_Definition">contains seeds,
+crisp, pleasant to taste</text:p>
+<text:p text:style-name="Definition_20_Term"><text:span text:style-name="Emphasis">orange</text:span></text:p>
+<text:p text:style-name="Definition_20_Definition">orange
+fruit</text:p><text:p text:style-name="Preformatted_20_Text">{ orange code block }</text:p><text:p text:style-name="P3">orange
+block quote</text:p>
+<text:p text:style-name="First_20_paragraph">Multiple definitions,
+tight:</text:p>
+<text:p text:style-name="Definition_20_Term_20_Tight">apple</text:p>
+<text:p text:style-name="Definition_20_Definition_20_Tight">red fruit</text:p>
+<text:p text:style-name="Definition_20_Definition_20_Tight">computer</text:p>
+<text:p text:style-name="Definition_20_Term_20_Tight">orange</text:p>
+<text:p text:style-name="Definition_20_Definition_20_Tight">orange
+fruit</text:p>
+<text:p text:style-name="Definition_20_Definition_20_Tight">bank</text:p>
+<text:p text:style-name="First_20_paragraph">Multiple definitions,
+loose:</text:p>
+<text:p text:style-name="Definition_20_Term">apple</text:p>
+<text:p text:style-name="Definition_20_Definition">red fruit</text:p>
+<text:p text:style-name="Definition_20_Definition">computer</text:p>
+<text:p text:style-name="Definition_20_Term">orange</text:p>
+<text:p text:style-name="Definition_20_Definition">orange fruit</text:p>
+<text:p text:style-name="Definition_20_Definition">bank</text:p>
+<text:p text:style-name="First_20_paragraph">Blank line after term, indented
+marker, alternate markers:</text:p>
+<text:p text:style-name="Definition_20_Term">apple</text:p>
+<text:p text:style-name="Definition_20_Definition">red fruit</text:p>
+<text:p text:style-name="Definition_20_Definition">computer</text:p>
+<text:p text:style-name="Definition_20_Term">orange</text:p>
+<text:p text:style-name="Definition_20_Definition">orange
+fruit</text:p><text:list text:style-name="Numbering_20_1">
+  <text:list-item>
+    <text:p text:style-name="List_20_Number_20_Tight">sublist</text:p>
+  </text:list-item>
+  <text:list-item>
+    <text:p text:style-name="List_20_Number_20_Tight">sublist</text:p>
+  </text:list-item>
+</text:list>
+<text:h text:style-name="Heading_20_1" text:outline-level="1"><text:bookmark-start text:name="html-blocks" />HTML
+Blocks<text:bookmark-end text:name="html-blocks" /></text:h>
+<text:p text:style-name="First_20_paragraph">Simple block on one line:</text:p>
+<text:p text:style-name="Text_20_body">foo</text:p>
+<text:p text:style-name="Text_20_body">And nested without indentation:</text:p>
+<text:p text:style-name="Text_20_body">foo</text:p>
+<text:p text:style-name="Text_20_body">bar</text:p>
+<text:p text:style-name="Text_20_body">Interpreted markdown in a table:</text:p>
+<text:p text:style-name="Text_20_body">This is
+<text:span text:style-name="Emphasis">emphasized</text:span></text:p>
+<text:p text:style-name="Text_20_body">And this is
+<text:span text:style-name="Strong_20_Emphasis">strong</text:span></text:p>
+<text:p text:style-name="Text_20_body">Here’s a simple block:</text:p>
+<text:p text:style-name="Text_20_body">foo</text:p>
+<text:p text:style-name="Text_20_body">This should be a code block,
+though:</text:p>
+<text:p text:style-name="Preformatted_20_Text">&lt;div&gt;</text:p>
+<text:p text:style-name="Preformatted_20_Text"><text:s text:c="4" />foo</text:p>
+<text:p text:style-name="Preformatted_20_Text">&lt;/div&gt;</text:p>
+<text:p text:style-name="First_20_paragraph">As should this:</text:p>
+<text:p text:style-name="Preformatted_20_Text">&lt;div&gt;foo&lt;/div&gt;</text:p>
+<text:p text:style-name="First_20_paragraph">Now, nested:</text:p>
+<text:p text:style-name="Text_20_body">foo</text:p>
+<text:p text:style-name="Text_20_body">This should just be an HTML
+comment:</text:p>
+<text:p text:style-name="Text_20_body">Multiline:</text:p>
+<text:p text:style-name="Text_20_body">Code block:</text:p>
+<text:p text:style-name="Preformatted_20_Text">&lt;!-- Comment --&gt;</text:p>
+<text:p text:style-name="First_20_paragraph">Just plain comment, with trailing
+spaces on the line:</text:p>
+<text:p text:style-name="Text_20_body">Code:</text:p>
+<text:p text:style-name="Preformatted_20_Text">&lt;hr /&gt;</text:p>
+<text:p text:style-name="First_20_paragraph">Hr’s:</text:p>
+<text:p text:style-name="Horizontal_20_Line" />
+<text:h text:style-name="Heading_20_1" text:outline-level="1"><text:bookmark-start text:name="inline-markup" />Inline
+Markup<text:bookmark-end text:name="inline-markup" /></text:h>
+<text:p text:style-name="First_20_paragraph">This is
+<text:span text:style-name="Emphasis">emphasized</text:span>, and so
+<text:span text:style-name="Emphasis">is this</text:span>.</text:p>
+<text:p text:style-name="Text_20_body">This is
+<text:span text:style-name="Strong_20_Emphasis">strong</text:span>, and so
+<text:span text:style-name="Strong_20_Emphasis">is this</text:span>.</text:p>
+<text:p text:style-name="Text_20_body">An
+<text:a xlink:type="simple" xlink:href="/url" office:name=""><text:span text:style-name="Definition"><text:span text:style-name="Emphasis">emphasized
+link</text:span></text:span></text:a>.</text:p>
+<text:p text:style-name="Text_20_body"><text:span text:style-name="T1">This is
+strong and em.</text:span></text:p>
+<text:p text:style-name="Text_20_body">So is
+<text:span text:style-name="T1">this</text:span> word.</text:p>
+<text:p text:style-name="Text_20_body"><text:span text:style-name="T1">This is
+strong and em.</text:span></text:p>
+<text:p text:style-name="Text_20_body">So is
+<text:span text:style-name="T1">this</text:span> word.</text:p>
+<text:p text:style-name="Text_20_body">This is code:
+<text:span text:style-name="Source_20_Text">&gt;</text:span>,
+<text:span text:style-name="Source_20_Text">$</text:span>,
+<text:span text:style-name="Source_20_Text">\</text:span>,
+<text:span text:style-name="Source_20_Text">\$</text:span>,
+<text:span text:style-name="Source_20_Text">&lt;html&gt;</text:span>.</text:p>
+<text:p text:style-name="Text_20_body"><text:span text:style-name="Strikeout">This
+is
+</text:span><text:span text:style-name="T2">strikeout</text:span><text:span text:style-name="Strikeout">.</text:span></text:p>
+<text:p text:style-name="Text_20_body">Superscripts:
+a<text:span text:style-name="Superscript">bc</text:span>d
+a<text:span text:style-name="T3">hello</text:span>
+a<text:span text:style-name="Superscript">hello there</text:span>.</text:p>
+<text:p text:style-name="Text_20_body">Subscripts:
+H<text:span text:style-name="Subscript">2</text:span>O,
+H<text:span text:style-name="Subscript">23</text:span>O,
+H<text:span text:style-name="Subscript">many of them</text:span>O.</text:p>
+<text:p text:style-name="Text_20_body">These should not be superscripts or
+subscripts, because of the unescaped spaces: a^b c^d, a~b c~d.</text:p>
+<text:p text:style-name="Horizontal_20_Line" />
+<text:h text:style-name="Heading_20_1" text:outline-level="1"><text:bookmark-start text:name="smart-quotes-ellipses-dashes" />Smart
+quotes, ellipses,
+dashes<text:bookmark-end text:name="smart-quotes-ellipses-dashes" /></text:h>
+<text:p text:style-name="First_20_paragraph">“Hello,” said the spider. “‘Shelob’
+is my name.”</text:p>
+<text:p text:style-name="Text_20_body">‘A’, ‘B’, and ‘C’ are letters.</text:p>
+<text:p text:style-name="Text_20_body">‘Oak,’ ‘elm,’ and ‘beech’ are names of
+trees. So is ‘pine.’</text:p>
+<text:p text:style-name="Text_20_body">‘He said, “I want to go.”’ Were you alive
+in the 70’s?</text:p>
+<text:p text:style-name="Text_20_body">Here is some quoted
+‘<text:span text:style-name="Source_20_Text">code</text:span>’ and a
+“<text:a xlink:type="simple" xlink:href="http://example.com/?foo=1&amp;bar=2" office:name=""><text:span text:style-name="Definition">quoted
+link</text:span></text:a>”.</text:p>
+<text:p text:style-name="Text_20_body">Some dashes: one—two — three—four —
+five.</text:p>
+<text:p text:style-name="Text_20_body">Dashes between numbers: 5–7, 255–66,
+1987–1999.</text:p>
+<text:p text:style-name="Text_20_body">Ellipses…and…and….</text:p>
+<text:p text:style-name="Horizontal_20_Line" />
+<text:h text:style-name="Heading_20_1" text:outline-level="1"><text:bookmark-start text:name="latex" />LaTeX<text:bookmark-end text:name="latex" /></text:h>
+<text:list text:style-name="List_20_1">
+  <text:list-item>
+    <text:p text:style-name="List_20_Bullet_20_Tight"></text:p>
+  </text:list-item>
+  <text:list-item>
+    <text:p text:style-name="List_20_Bullet_20_Tight">2 + 2 = 4</text:p>
+  </text:list-item>
+  <text:list-item>
+    <text:p text:style-name="List_20_Bullet_20_Tight"><text:span text:style-name="Emphasis">x</text:span> ∈ <text:span text:style-name="Emphasis">y</text:span></text:p>
+  </text:list-item>
+  <text:list-item>
+    <text:p text:style-name="List_20_Bullet_20_Tight"><text:span text:style-name="Emphasis">α</text:span> ∧ <text:span text:style-name="Emphasis">ω</text:span></text:p>
+  </text:list-item>
+  <text:list-item>
+    <text:p text:style-name="List_20_Bullet_20_Tight">223</text:p>
+  </text:list-item>
+  <text:list-item>
+    <text:p text:style-name="List_20_Bullet_20_Tight"><text:span text:style-name="Emphasis">p</text:span>-Tree</text:p>
+  </text:list-item>
+  <text:list-item>
+    <text:p text:style-name="List_20_Bullet_20_Tight">Here’s some display math:
+    $$\frac{d}{dx}f(x)=\lim_{h\to 0}\frac{f(x+h)-f(x)}{h}$$</text:p>
+  </text:list-item>
+  <text:list-item>
+    <text:p text:style-name="List_20_Bullet_20_Tight">Here’s one that has a line
+    break in it:
+    <text:span text:style-name="Emphasis">α</text:span> + <text:span text:style-name="Emphasis">ω</text:span> × <text:span text:style-name="Emphasis">x</text:span><text:span text:style-name="Superscript">2</text:span>.</text:p>
+  </text:list-item>
+</text:list>
+<text:p text:style-name="First_20_paragraph">These shouldn’t be math:</text:p>
+<text:list text:style-name="List_20_1">
+  <text:list-item>
+    <text:p text:style-name="List_20_Bullet_20_Tight">To get the famous
+    equation, write
+    <text:span text:style-name="Source_20_Text">$e = mc^2$</text:span>.</text:p>
+  </text:list-item>
+  <text:list-item>
+    <text:p text:style-name="List_20_Bullet_20_Tight">$22,000 is a
+    <text:span text:style-name="Emphasis">lot</text:span> of money. So is
+    $34,000. (It worked if “lot” is emphasized.)</text:p>
+  </text:list-item>
+  <text:list-item>
+    <text:p text:style-name="List_20_Bullet_20_Tight">Shoes ($20) and socks
+    ($5).</text:p>
+  </text:list-item>
+  <text:list-item>
+    <text:p text:style-name="List_20_Bullet_20_Tight">Escaped
+    <text:span text:style-name="Source_20_Text">$</text:span>: $73
+    <text:span text:style-name="Emphasis">this should be emphasized</text:span>
+    23$.</text:p>
+  </text:list-item>
+</text:list>
+<text:p text:style-name="First_20_paragraph">Here’s a LaTeX table:</text:p>
+<text:p text:style-name="Horizontal_20_Line" />
+<text:h text:style-name="Heading_20_1" text:outline-level="1"><text:bookmark-start text:name="special-characters" />Special
+Characters<text:bookmark-end text:name="special-characters" /></text:h>
+<text:p text:style-name="First_20_paragraph">Here is some unicode:</text:p>
+<text:list text:style-name="List_20_1">
+  <text:list-item>
+    <text:p text:style-name="List_20_Bullet_20_Tight">I hat: Î</text:p>
+  </text:list-item>
+  <text:list-item>
+    <text:p text:style-name="List_20_Bullet_20_Tight">o umlaut: ö</text:p>
+  </text:list-item>
+  <text:list-item>
+    <text:p text:style-name="List_20_Bullet_20_Tight">section: §</text:p>
+  </text:list-item>
+  <text:list-item>
+    <text:p text:style-name="List_20_Bullet_20_Tight">set membership: ∈</text:p>
+  </text:list-item>
+  <text:list-item>
+    <text:p text:style-name="List_20_Bullet_20_Tight">copyright: ©</text:p>
+  </text:list-item>
+</text:list>
+<text:p text:style-name="First_20_paragraph">AT&amp;T has an ampersand in their
+name.</text:p>
+<text:p text:style-name="Text_20_body">AT&amp;T is another way to write
+it.</text:p>
+<text:p text:style-name="Text_20_body">This &amp; that.</text:p>
+<text:p text:style-name="Text_20_body">4 &lt; 5.</text:p>
+<text:p text:style-name="Text_20_body">6 &gt; 5.</text:p>
+<text:p text:style-name="Text_20_body">Backslash: \</text:p>
+<text:p text:style-name="Text_20_body">Backtick: `</text:p>
+<text:p text:style-name="Text_20_body">Asterisk: *</text:p>
+<text:p text:style-name="Text_20_body">Underscore: _</text:p>
+<text:p text:style-name="Text_20_body">Left brace: {</text:p>
+<text:p text:style-name="Text_20_body">Right brace: }</text:p>
+<text:p text:style-name="Text_20_body">Left bracket: [</text:p>
+<text:p text:style-name="Text_20_body">Right bracket: ]</text:p>
+<text:p text:style-name="Text_20_body">Left paren: (</text:p>
+<text:p text:style-name="Text_20_body">Right paren: )</text:p>
+<text:p text:style-name="Text_20_body">Greater-than: &gt;</text:p>
+<text:p text:style-name="Text_20_body">Hash: #</text:p>
+<text:p text:style-name="Text_20_body">Period: .</text:p>
+<text:p text:style-name="Text_20_body">Bang: !</text:p>
+<text:p text:style-name="Text_20_body">Plus: +</text:p>
+<text:p text:style-name="Text_20_body">Minus: -</text:p>
+<text:p text:style-name="Horizontal_20_Line" />
+<text:h text:style-name="Heading_20_1" text:outline-level="1"><text:bookmark-start text:name="links" />Links<text:bookmark-end text:name="links" /></text:h>
+<text:h text:style-name="Heading_20_2" text:outline-level="2"><text:bookmark-start text:name="explicit" />Explicit<text:bookmark-end text:name="explicit" /></text:h>
+<text:p text:style-name="First_20_paragraph">Just a
+<text:a xlink:type="simple" xlink:href="/url/" office:name=""><text:span text:style-name="Definition">URL</text:span></text:a>.</text:p>
+<text:p text:style-name="Text_20_body"><text:a xlink:type="simple" xlink:href="/url/" office:name="title"><text:span text:style-name="Definition">URL
+and title</text:span></text:a>.</text:p>
+<text:p text:style-name="Text_20_body"><text:a xlink:type="simple" xlink:href="/url/" office:name="title preceded by two spaces"><text:span text:style-name="Definition">URL
+and title</text:span></text:a>.</text:p>
+<text:p text:style-name="Text_20_body"><text:a xlink:type="simple" xlink:href="/url/" office:name="title preceded by a tab"><text:span text:style-name="Definition">URL
+and title</text:span></text:a>.</text:p>
+<text:p text:style-name="Text_20_body"><text:a xlink:type="simple" xlink:href="/url/" office:name="title with &quot;quotes&quot; in it"><text:span text:style-name="Definition">URL
+and title</text:span></text:a></text:p>
+<text:p text:style-name="Text_20_body"><text:a xlink:type="simple" xlink:href="/url/" office:name="title with single quotes"><text:span text:style-name="Definition">URL
+and title</text:span></text:a></text:p>
+<text:p text:style-name="Text_20_body"><text:a xlink:type="simple" xlink:href="/url/with_underscore" office:name=""><text:span text:style-name="Definition">with_underscore</text:span></text:a></text:p>
+<text:p text:style-name="Text_20_body"><text:a xlink:type="simple" xlink:href="mailto:nobody@nowhere.net" office:name=""><text:span text:style-name="Definition">Email
+link</text:span></text:a></text:p>
+<text:p text:style-name="Text_20_body"><text:a xlink:type="simple" xlink:href="" office:name=""><text:span text:style-name="Definition">Empty</text:span></text:a>.</text:p>
+<text:h text:style-name="Heading_20_2" text:outline-level="2"><text:bookmark-start text:name="reference" />Reference<text:bookmark-end text:name="reference" /></text:h>
+<text:p text:style-name="First_20_paragraph">Foo
+<text:a xlink:type="simple" xlink:href="/url/" office:name=""><text:span text:style-name="Definition">bar</text:span></text:a>.</text:p>
+<text:p text:style-name="Text_20_body">With
+<text:a xlink:type="simple" xlink:href="/url/" office:name=""><text:span text:style-name="Definition">embedded
+[brackets]</text:span></text:a>.</text:p>
+<text:p text:style-name="Text_20_body"><text:a xlink:type="simple" xlink:href="/url/" office:name=""><text:span text:style-name="Definition">b</text:span></text:a>
+by itself should be a link.</text:p>
+<text:p text:style-name="Text_20_body">Indented
+<text:a xlink:type="simple" xlink:href="/url" office:name=""><text:span text:style-name="Definition">once</text:span></text:a>.</text:p>
+<text:p text:style-name="Text_20_body">Indented
+<text:a xlink:type="simple" xlink:href="/url" office:name=""><text:span text:style-name="Definition">twice</text:span></text:a>.</text:p>
+<text:p text:style-name="Text_20_body">Indented
+<text:a xlink:type="simple" xlink:href="/url" office:name=""><text:span text:style-name="Definition">thrice</text:span></text:a>.</text:p>
+<text:p text:style-name="Text_20_body">This should [not][] be a link.</text:p>
+<text:p text:style-name="Preformatted_20_Text">[not]: /url</text:p>
+<text:p text:style-name="First_20_paragraph">Foo
+<text:a xlink:type="simple" xlink:href="/url/" office:name="Title with &quot;quotes&quot; inside"><text:span text:style-name="Definition">bar</text:span></text:a>.</text:p>
+<text:p text:style-name="Text_20_body">Foo
+<text:a xlink:type="simple" xlink:href="/url/" office:name="Title with &quot;quote&quot; inside"><text:span text:style-name="Definition">biz</text:span></text:a>.</text:p>
+<text:h text:style-name="Heading_20_2" text:outline-level="2"><text:bookmark-start text:name="with-ampersands" />With
+ampersands<text:bookmark-end text:name="with-ampersands" /></text:h>
+<text:p text:style-name="First_20_paragraph">Here’s a
+<text:a xlink:type="simple" xlink:href="http://example.com/?foo=1&amp;bar=2" office:name=""><text:span text:style-name="Definition">link
+with an ampersand in the URL</text:span></text:a>.</text:p>
+<text:p text:style-name="Text_20_body">Here’s a link with an amersand in the
+link text:
+<text:a xlink:type="simple" xlink:href="http://att.com/" office:name="AT&amp;T"><text:span text:style-name="Definition">AT&amp;T</text:span></text:a>.</text:p>
+<text:p text:style-name="Text_20_body">Here’s an
+<text:a xlink:type="simple" xlink:href="/script?foo=1&amp;bar=2" office:name=""><text:span text:style-name="Definition">inline
+link</text:span></text:a>.</text:p>
+<text:p text:style-name="Text_20_body">Here’s an
+<text:a xlink:type="simple" xlink:href="/script?foo=1&amp;bar=2" office:name=""><text:span text:style-name="Definition">inline
+link in pointy braces</text:span></text:a>.</text:p>
+<text:h text:style-name="Heading_20_2" text:outline-level="2"><text:bookmark-start text:name="autolinks" />Autolinks<text:bookmark-end text:name="autolinks" /></text:h>
+<text:p text:style-name="First_20_paragraph">With an ampersand:
+<text:a xlink:type="simple" xlink:href="http://example.com/?foo=1&amp;bar=2" office:name=""><text:span text:style-name="Definition">http://example.com/?foo=1&amp;bar=2</text:span></text:a></text:p>
+<text:list text:style-name="List_20_1">
+  <text:list-item>
+    <text:p text:style-name="List_20_Bullet_20_Tight">In a list?</text:p>
+  </text:list-item>
+  <text:list-item>
+    <text:p text:style-name="List_20_Bullet_20_Tight"><text:a xlink:type="simple" xlink:href="http://example.com/" office:name=""><text:span text:style-name="Definition">http://example.com/</text:span></text:a></text:p>
+  </text:list-item>
+  <text:list-item>
+    <text:p text:style-name="List_20_Bullet_20_Tight">It should.</text:p>
+  </text:list-item>
+</text:list>
+<text:p text:style-name="First_20_paragraph">An e-mail address:
+<text:a xlink:type="simple" xlink:href="mailto:nobody@nowhere.net" office:name=""><text:span text:style-name="Definition">nobody@nowhere.net</text:span></text:a></text:p>
+<text:p text:style-name="Quotations">Blockquoted:
+<text:a xlink:type="simple" xlink:href="http://example.com/" office:name=""><text:span text:style-name="Definition">http://example.com/</text:span></text:a></text:p>
+<text:p text:style-name="First_20_paragraph">Auto-links should not occur here:
+<text:span text:style-name="Source_20_Text">&lt;http://example.com/&gt;</text:span></text:p>
+<text:p text:style-name="Preformatted_20_Text">or here: &lt;http://example.com/&gt;</text:p>
+<text:p text:style-name="Horizontal_20_Line" />
+<text:h text:style-name="Heading_20_1" text:outline-level="1"><text:bookmark-start text:name="images" />Images<text:bookmark-end text:name="images" /></text:h>
+<text:p text:style-name="First_20_paragraph">From “Voyage dans la Lune” by
+Georges Melies (1902):</text:p>
+<text:p text:style-name="FigureWithCaption"><draw:frame draw:name="img1"><draw:image xlink:href="lalune.jpg" xlink:type="simple" xlink:show="embed" xlink:actuate="onLoad" /></draw:frame></text:p>
+<text:p text:style-name="FigureCaption">lalune</text:p>
+<text:p text:style-name="Text_20_body">Here is a movie
+<draw:frame draw:name="img2"><draw:image xlink:href="movie.jpg" xlink:type="simple" xlink:show="embed" xlink:actuate="onLoad" /></draw:frame>
+icon.</text:p>
+<text:p text:style-name="Horizontal_20_Line" />
+<text:h text:style-name="Heading_20_1" text:outline-level="1"><text:bookmark-start text:name="footnotes" />Footnotes<text:bookmark-end text:name="footnotes" /></text:h>
+<text:p text:style-name="First_20_paragraph">Here is a footnote
+reference,<text:note text:id="ftn0" text:note-class="footnote"><text:note-citation>1</text:note-citation><text:note-body><text:p text:style-name="Footnote">Here
+is the footnote. It can go anywhere after the footnote reference. It need not be
+placed at the end of the document.</text:p></text:note-body></text:note> and
+another.<text:note text:id="ftn1" text:note-class="footnote"><text:note-citation>2</text:note-citation><text:note-body><text:p text:style-name="Footnote">Here’s
+the long note. This one contains multiple
+blocks.</text:p><text:p text:style-name="Footnote">Subsequent blocks are
+indented to show that they belong to the footnote (as with list
+items).</text:p><text:p text:style-name="Preformatted_20_Text"><text:s text:c="2" />{ &lt;code&gt; }</text:p><text:p text:style-name="Footnote">If
+you want, you can indent every line, but you can also be lazy and just indent
+the first line of each block.</text:p></text:note-body></text:note> This should
+<text:span text:style-name="Emphasis">not</text:span> be a footnote reference,
+because it contains a space.[^my note] Here is an inline
+note.<text:note text:id="ftn2" text:note-class="footnote"><text:note-citation>3</text:note-citation><text:note-body><text:p text:style-name="Footnote">This
+is <text:span text:style-name="Emphasis">easier</text:span> to type. Inline
+notes may contain
+<text:a xlink:type="simple" xlink:href="http://google.com" office:name=""><text:span text:style-name="Definition">links</text:span></text:a>
+and <text:span text:style-name="Source_20_Text">]</text:span> verbatim
+characters, as well as [bracketed
+text].</text:p></text:note-body></text:note></text:p>
+<text:p text:style-name="Quotations">Notes can go in
+quotes.<text:note text:id="ftn3" text:note-class="footnote"><text:note-citation>4</text:note-citation><text:note-body><text:p text:style-name="Footnote">In
+quote.</text:p></text:note-body></text:note></text:p>
+<text:list text:style-name="Numbering_20_1">
+  <text:list-item>
+    <text:p text:style-name="List_20_Number_20_Tight">And in list
     items.<text:note text:id="ftn4" text:note-class="footnote"><text:note-citation>5</text:note-citation><text:note-body><text:p text:style-name="Footnote">In
     list.</text:p></text:note-body></text:note></text:p>
   </text:list-item>
diff --git a/test/writer.opml b/test/writer.opml
--- a/test/writer.opml
+++ b/test/writer.opml
@@ -21,52 +21,52 @@
     <outline text="Level 3" _note="with no blank line">
     </outline>
   </outline>
-  <outline text="Level 2" _note="with no blank line&#10;&#10;------------------------------------------------------------------------">
+  <outline text="Level 2" _note="with no blank line&#10;&#10;--------------------------------------------------------------------------------">
   </outline>
 </outline>
-<outline text="Paragraphs" _note="Here’s a regular paragraph.&#10;&#10;In Markdown 1.0.0 and earlier. Version 8. This line turns into a list&#10;item. Because a hard-wrapped line in the middle of a paragraph looked&#10;like a list item.&#10;&#10;Here’s one with a bullet. \* criminey.&#10;&#10;There should be a hard line break  &#10;here.&#10;&#10;------------------------------------------------------------------------">
+<outline text="Paragraphs" _note="Here's a regular paragraph.&#10;&#10;In Markdown 1.0.0 and earlier. Version 8. This line turns into a list item.&#10;Because a hard-wrapped line in the middle of a paragraph looked like a list&#10;item.&#10;&#10;Here's one with a bullet. \* criminey.&#10;&#10;There should be a hard line break\&#10;here.&#10;&#10;--------------------------------------------------------------------------------">
 </outline>
-<outline text="Block Quotes" _note="E-mail style:&#10;&#10;&gt; This is a block quote. It is pretty short.&#10;&#10;&gt; Code in a block quote:&#10;&gt;&#10;&gt;     sub status {&#10;&gt;         print &quot;working&quot;;&#10;&gt;     }&#10;&gt;&#10;&gt; A list:&#10;&gt;&#10;&gt; 1.  item one&#10;&gt; 2.  item two&#10;&gt;&#10;&gt; Nested block quotes:&#10;&gt;&#10;&gt; &gt; nested&#10;&gt;&#10;&gt; &gt; nested&#10;&#10;This should not be a block quote: 2 &amp;gt; 1.&#10;&#10;And a following paragraph.&#10;&#10;------------------------------------------------------------------------">
+<outline text="Block Quotes" _note="E-mail style:&#10;&#10;&gt; This is a block quote. It is pretty short.&#10;&#10;&gt; Code in a block quote:&#10;&gt;&#10;&gt;     sub status {&#10;&gt;         print &quot;working&quot;;&#10;&gt;     }&#10;&gt;&#10;&gt; A list:&#10;&gt;&#10;&gt; 1.  item one&#10;&gt; 2.  item two&#10;&gt;&#10;&gt; Nested block quotes:&#10;&gt;&#10;&gt; &gt; nested&#10;&gt;&#10;&gt; &gt; nested&#10;&#10;This should not be a block quote: 2 \&gt; 1.&#10;&#10;And a following paragraph.&#10;&#10;--------------------------------------------------------------------------------">
 </outline>
-<outline text="Code Blocks" _note="Code:&#10;&#10;    ---- (should be four hyphens)&#10;&#10;    sub status {&#10;        print &quot;working&quot;;&#10;    }&#10;&#10;    this code block is indented by one tab&#10;&#10;And:&#10;&#10;        this code block is indented by two tabs&#10;&#10;    These should not be escaped:  \$ \\ \&gt; \[ \{&#10;&#10;------------------------------------------------------------------------">
+<outline text="Code Blocks" _note="Code:&#10;&#10;    ---- (should be four hyphens)&#10;&#10;    sub status {&#10;        print &quot;working&quot;;&#10;    }&#10;&#10;    this code block is indented by one tab&#10;&#10;And:&#10;&#10;        this code block is indented by two tabs&#10;&#10;    These should not be escaped:  \$ \\ \&gt; \[ \{&#10;&#10;--------------------------------------------------------------------------------">
 </outline>
 <outline text="Lists">
-  <outline text="Unordered" _note="Asterisks tight:&#10;&#10;-   asterisk 1&#10;-   asterisk 2&#10;-   asterisk 3&#10;&#10;Asterisks loose:&#10;&#10;-   asterisk 1&#10;&#10;-   asterisk 2&#10;&#10;-   asterisk 3&#10;&#10;Pluses tight:&#10;&#10;-   Plus 1&#10;-   Plus 2&#10;-   Plus 3&#10;&#10;Pluses loose:&#10;&#10;-   Plus 1&#10;&#10;-   Plus 2&#10;&#10;-   Plus 3&#10;&#10;Minuses tight:&#10;&#10;-   Minus 1&#10;-   Minus 2&#10;-   Minus 3&#10;&#10;Minuses loose:&#10;&#10;-   Minus 1&#10;&#10;-   Minus 2&#10;&#10;-   Minus 3">
+  <outline text="Unordered" _note="Asterisks tight:&#10;&#10;- asterisk 1&#10;- asterisk 2&#10;- asterisk 3&#10;&#10;Asterisks loose:&#10;&#10;- asterisk 1&#10;&#10;- asterisk 2&#10;&#10;- asterisk 3&#10;&#10;Pluses tight:&#10;&#10;- Plus 1&#10;- Plus 2&#10;- Plus 3&#10;&#10;Pluses loose:&#10;&#10;- Plus 1&#10;&#10;- Plus 2&#10;&#10;- Plus 3&#10;&#10;Minuses tight:&#10;&#10;- Minus 1&#10;- Minus 2&#10;- Minus 3&#10;&#10;Minuses loose:&#10;&#10;- Minus 1&#10;&#10;- Minus 2&#10;&#10;- Minus 3">
   </outline>
-  <outline text="Ordered" _note="Tight:&#10;&#10;1.  First&#10;2.  Second&#10;3.  Third&#10;&#10;and:&#10;&#10;1.  One&#10;2.  Two&#10;3.  Three&#10;&#10;Loose using tabs:&#10;&#10;1.  First&#10;&#10;2.  Second&#10;&#10;3.  Third&#10;&#10;and using spaces:&#10;&#10;1.  One&#10;&#10;2.  Two&#10;&#10;3.  Three&#10;&#10;Multiple paragraphs:&#10;&#10;1.  Item 1, graf one.&#10;&#10;    Item 1. graf two. The quick brown fox jumped over the lazy dog’s&#10;    back.&#10;&#10;2.  Item 2.&#10;&#10;3.  Item 3.">
+  <outline text="Ordered" _note="Tight:&#10;&#10;1.  First&#10;2.  Second&#10;3.  Third&#10;&#10;and:&#10;&#10;1.  One&#10;2.  Two&#10;3.  Three&#10;&#10;Loose using tabs:&#10;&#10;1.  First&#10;&#10;2.  Second&#10;&#10;3.  Third&#10;&#10;and using spaces:&#10;&#10;1.  One&#10;&#10;2.  Two&#10;&#10;3.  Three&#10;&#10;Multiple paragraphs:&#10;&#10;1.  Item 1, graf one.&#10;&#10;    Item 1. graf two. The quick brown fox jumped over the lazy dog's back.&#10;&#10;2.  Item 2.&#10;&#10;3.  Item 3.">
   </outline>
-  <outline text="Nested" _note="-   Tab&#10;    -   Tab&#10;        -   Tab&#10;&#10;Here’s another:&#10;&#10;1.  First&#10;2.  Second:&#10;    -   Fee&#10;    -   Fie&#10;    -   Foe&#10;3.  Third&#10;&#10;Same thing but with paragraphs:&#10;&#10;1.  First&#10;&#10;2.  Second:&#10;&#10;    -   Fee&#10;    -   Fie&#10;    -   Foe&#10;&#10;3.  Third">
+  <outline text="Nested" _note="- Tab&#10;  - Tab&#10;    - Tab&#10;&#10;Here's another:&#10;&#10;1.  First&#10;2.  Second:&#10;    - Fee&#10;    - Fie&#10;    - Foe&#10;3.  Third&#10;&#10;Same thing but with paragraphs:&#10;&#10;1.  First&#10;&#10;2.  Second:&#10;&#10;    - Fee&#10;    - Fie&#10;    - Foe&#10;&#10;3.  Third">
   </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 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="(2) begins with 2&#10;&#10;(3) and now 3&#10;&#10;    with a continuation&#10;&#10;    iv. sublist with roman numerals, starting with 4&#10;    v.  more items&#10;        (A) a subsublist&#10;        (B) a subsublist&#10;&#10;Nesting:&#10;&#10;A.  Upper Alpha&#10;    I.  Upper Roman.&#10;        (6) Decimal start with 6&#10;            c)  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">
+<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;&#10;: red fruit&#10;&#10;orange&#10;&#10;: orange fruit&#10;&#10;banana&#10;&#10;: yellow fruit&#10;&#10;Multiple blocks with italics:&#10;&#10;*apple*&#10;&#10;: red fruit&#10;&#10;  contains seeds, crisp, pleasant to taste&#10;&#10;*orange*&#10;&#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;: computer&#10;&#10;orange&#10;: orange fruit&#10;: bank&#10;&#10;Multiple definitions, loose:&#10;&#10;apple&#10;&#10;: red fruit&#10;&#10;: computer&#10;&#10;orange&#10;&#10;: orange fruit&#10;&#10;: bank&#10;&#10;Blank line after term, indented marker, alternate markers:&#10;&#10;apple&#10;&#10;: red fruit&#10;&#10;: computer&#10;&#10;orange&#10;&#10;: orange fruit&#10;&#10;  1.  sublist&#10;  2.  sublist">
 </outline>
-<outline text="HTML Blocks" _note="Simple block on one line:&#10;&#10;foo&#10;&#10;And nested without indentation:&#10;&#10;foo&#10;&#10;bar&#10;&#10;Interpreted markdown in a table:&#10;&#10;This is *emphasized*&#10;And this is **strong**&#10;Here’s a simple block:&#10;&#10;foo&#10;&#10;This should be a code block, though:&#10;&#10;    &lt;div&gt;&#10;        foo&#10;    &lt;/div&gt;&#10;&#10;As should this:&#10;&#10;    &lt;div&gt;foo&lt;/div&gt;&#10;&#10;Now, nested:&#10;&#10;foo&#10;&#10;This should just be an HTML comment:&#10;&#10;Multiline:&#10;&#10;Code block:&#10;&#10;    &lt;!-- Comment --&gt;&#10;&#10;Just plain comment, with trailing spaces on the line:&#10;&#10;Code:&#10;&#10;    &lt;hr /&gt;&#10;&#10;Hr’s:&#10;&#10;------------------------------------------------------------------------">
+<outline text="HTML Blocks" _note="Simple block on one line:&#10;&#10;::: {}&#10;foo&#10;:::&#10;&#10;And nested without indentation:&#10;&#10;:::::: {}&#10;:::: {}&#10;::: {}&#10;foo&#10;:::&#10;::::&#10;&#10;::: {}&#10;bar&#10;:::&#10;::::::&#10;&#10;Interpreted markdown in a table:&#10;&#10;&lt;table&gt;&#10;&lt;tr&gt;&#10;&lt;td&gt;&#10;This is *emphasized*&#10;&lt;/td&gt;&#10;&lt;td&gt;&#10;And this is **strong**&#10;&lt;/td&gt;&#10;&lt;/tr&gt;&#10;&lt;/table&gt;&#10;&lt;script type=&quot;text/javascript&quot;&gt;document.write('This *should not* be interpreted as markdown');&lt;/script&gt;&#10;&#10;Here's a simple block:&#10;&#10;::: {}&#10;foo&#10;:::&#10;&#10;This should be a code block, though:&#10;&#10;    &lt;div&gt;&#10;        foo&#10;    &lt;/div&gt;&#10;&#10;As should this:&#10;&#10;    &lt;div&gt;foo&lt;/div&gt;&#10;&#10;Now, nested:&#10;&#10;::::: {}&#10;:::: {}&#10;::: {}&#10;foo&#10;:::&#10;::::&#10;:::::&#10;&#10;This should just be an HTML comment:&#10;&#10;&lt;!-- Comment --&gt;&#10;&#10;Multiline:&#10;&#10;&lt;!--&#10;Blah&#10;Blah&#10;--&gt;&#10;&lt;!--&#10;    This is another comment.&#10;--&gt;&#10;&#10;Code block:&#10;&#10;    &lt;!-- Comment --&gt;&#10;&#10;Just plain comment, with trailing spaces on the line:&#10;&#10;&lt;!-- foo --&gt;&#10;&#10;Code:&#10;&#10;    &lt;hr /&gt;&#10;&#10;Hr's:&#10;&#10;&lt;hr&gt;&#10;&lt;hr /&gt;&#10;&lt;hr /&gt;&#10;&lt;hr&gt;&#10;&lt;hr /&gt;&#10;&lt;hr /&gt;&#10;&lt;hr class=&quot;foo&quot; id=&quot;bar&quot; /&gt;&#10;&lt;hr class=&quot;foo&quot; id=&quot;bar&quot; /&gt;&#10;&lt;hr class=&quot;foo&quot; id=&quot;bar&quot;&gt;&#10;&#10;--------------------------------------------------------------------------------">
 </outline>
-<outline text="Inline Markup" _note="This is *emphasized*, and so *is this*.&#10;&#10;This is **strong**, and so **is this**.&#10;&#10;An *[emphasized link](/url)*.&#10;&#10;***This is strong and em.***&#10;&#10;So is ***this*** word.&#10;&#10;***This is strong and em.***&#10;&#10;So is ***this*** word.&#10;&#10;This is code: `&gt;`, `$`, `\`, `\$`, `&lt;html&gt;`.&#10;&#10;This is *strikeout*.&#10;&#10;Superscripts: a^(bc)d a^(*hello*) a^(hello there).&#10;&#10;Subscripts: H₂O, H₂₃O, H_(many of them)O.&#10;&#10;These should not be superscripts or subscripts, because of the unescaped&#10;spaces: a^b c^d, a~b c~d.&#10;&#10;------------------------------------------------------------------------">
+<outline text="Inline Markup" _note="This is *emphasized*, and so *is this*.&#10;&#10;This is **strong**, and so **is this**.&#10;&#10;An *[emphasized link](/url)*.&#10;&#10;***This is strong and em.***&#10;&#10;So is ***this*** word.&#10;&#10;***This is strong and em.***&#10;&#10;So is ***this*** word.&#10;&#10;This is code: `&gt;`, `$`, `\`, `\$`, `&lt;html&gt;`.&#10;&#10;~~This is *strikeout*.~~&#10;&#10;Superscripts: a^bc^d a^*hello*^ a^hello there^.&#10;&#10;Subscripts: H~2~O, H~23~O, H~many of them~O.&#10;&#10;These should not be superscripts or subscripts, because of the unescaped spaces:&#10;a\^b c\^d, a\~b c\~d.&#10;&#10;--------------------------------------------------------------------------------">
 </outline>
-<outline text="Smart quotes, ellipses, dashes" _note="“Hello,” said the spider. “‘Shelob’ is my name.”&#10;&#10;‘A’, ‘B’, and ‘C’ are letters.&#10;&#10;‘Oak,’ ‘elm,’ and ‘beech’ are names of trees. So is ‘pine.’&#10;&#10;‘He said, “I want to go.”’ Were you alive in the 70’s?&#10;&#10;Here is some quoted ‘`code`’ and a “[quoted&#10;link](http://example.com/?foo=1&amp;bar=2)”.&#10;&#10;Some dashes: one—two — three—four — five.&#10;&#10;Dashes between numbers: 5–7, 255–66, 1987–1999.&#10;&#10;Ellipses…and…and….&#10;&#10;------------------------------------------------------------------------">
+<outline text="Smart quotes, ellipses, dashes" _note="&quot;Hello,&quot; said the spider. &quot;'Shelob' is my name.&quot;&#10;&#10;'A', 'B', and 'C' are letters.&#10;&#10;'Oak,' 'elm,' and 'beech' are names of trees. So is 'pine.'&#10;&#10;'He said, &quot;I want to go.&quot;' Were you alive in the 70's?&#10;&#10;Here is some quoted '`code`' and a &quot;[quoted&#10;link](http://example.com/?foo=1&amp;bar=2)&quot;.&#10;&#10;Some dashes: one---two --- three---four --- five.&#10;&#10;Dashes between numbers: 5--7, 255--66, 1987--1999.&#10;&#10;Ellipses...and...and....&#10;&#10;--------------------------------------------------------------------------------">
 </outline>
-<outline text="LaTeX" _note="-   &#10;-   2 + 2 = 4&#10;-   *x* ∈ *y*&#10;-   *α* ∧ *ω*&#10;-   223&#10;-   *p*-Tree&#10;-   Here’s some display math:&#10;    $$\\frac{d}{dx}f(x)=\\lim\_{h\\to 0}\\frac{f(x+h)-f(x)}{h}$$&#10;-   Here’s one that has a line break in it: *α* + *ω* × *x*².&#10;&#10;These shouldn’t be math:&#10;&#10;-   To get the famous equation, write `$e = mc^2$`.&#10;-   $22,000 is a *lot* of money. So is $34,000. (It worked if “lot” is&#10;    emphasized.)&#10;-   Shoes ($20) and socks ($5).&#10;-   Escaped `$`: $73 *this should be emphasized* 23$.&#10;&#10;Here’s a LaTeX table:&#10;&#10;------------------------------------------------------------------------">
+<outline text="LaTeX" _note="- `\cite[22-23]{smith.1899}`{=tex}&#10;- $2+2=4$&#10;- $x \in y$&#10;- $\alpha \wedge \omega$&#10;- $223$&#10;- $p$-Tree&#10;- Here's some display math:&#10;  $$\frac{d}{dx}f(x)=\lim_{h\to 0}\frac{f(x+h)-f(x)}{h}$$&#10;- Here's one that has a line break in it: $\alpha + \omega \times x^2$.&#10;&#10;These shouldn't be math:&#10;&#10;- To get the famous equation, write `$e = mc^2$`.&#10;- \$22,000 is a *lot* of money. So is \$34,000. (It worked if &quot;lot&quot; is&#10;  emphasized.)&#10;- Shoes (\$20) and socks (\$5).&#10;- Escaped `$`: \$73 *this should be emphasized* 23\$.&#10;&#10;Here's a LaTeX table:&#10;&#10;\begin{tabular}{|l|l|}\hline&#10;Animal &amp; Number \\ \hline&#10;Dog    &amp; 2      \\&#10;Cat    &amp; 1      \\ \hline&#10;\end{tabular}&#10;&#10;--------------------------------------------------------------------------------">
 </outline>
-<outline text="Special Characters" _note="Here is some unicode:&#10;&#10;-   I hat: Î&#10;-   o umlaut: ö&#10;-   section: §&#10;-   set membership: ∈&#10;-   copyright: ©&#10;&#10;AT&amp;T has an ampersand in their name.&#10;&#10;AT&amp;T is another way to write it.&#10;&#10;This &amp; that.&#10;&#10;4 &amp;lt; 5.&#10;&#10;6 &amp;gt; 5.&#10;&#10;Backslash: \\&#10;&#10;Backtick: \`&#10;&#10;Asterisk: \*&#10;&#10;Underscore: \_&#10;&#10;Left brace: {&#10;&#10;Right brace: }&#10;&#10;Left bracket: \[&#10;&#10;Right bracket: \]&#10;&#10;Left paren: (&#10;&#10;Right paren: )&#10;&#10;Greater-than: &amp;gt;&#10;&#10;Hash: \#&#10;&#10;Period: .&#10;&#10;Bang: !&#10;&#10;Plus: +&#10;&#10;Minus: -&#10;&#10;------------------------------------------------------------------------">
+<outline text="Special Characters" _note="Here is some unicode:&#10;&#10;- I hat: Î&#10;- o umlaut: ö&#10;- section: §&#10;- set membership: ∈&#10;- copyright: ©&#10;&#10;AT&amp;T has an ampersand in their name.&#10;&#10;AT&amp;T is another way to write it.&#10;&#10;This &amp; that.&#10;&#10;4 \&lt; 5.&#10;&#10;6 \&gt; 5.&#10;&#10;Backslash: \\&#10;&#10;Backtick: \`&#10;&#10;Asterisk: \*&#10;&#10;Underscore: \_&#10;&#10;Left brace: {&#10;&#10;Right brace: }&#10;&#10;Left bracket: \[&#10;&#10;Right bracket: \]&#10;&#10;Left paren: (&#10;&#10;Right paren: )&#10;&#10;Greater-than: \&gt;&#10;&#10;Hash: \#&#10;&#10;Period: .&#10;&#10;Bang: !&#10;&#10;Plus: +&#10;&#10;Minus: -&#10;&#10;--------------------------------------------------------------------------------">
 </outline>
 <outline text="Links">
-  <outline text="Explicit" _note="Just a [URL](/url/).&#10;&#10;[URL and title](/url/ &quot;title&quot;).&#10;&#10;[URL and title](/url/ &quot;title preceded by two spaces&quot;).&#10;&#10;[URL and title](/url/ &quot;title preceded by a tab&quot;).&#10;&#10;[URL and title](/url/ &quot;title with &quot;quotes&quot; in it&quot;)&#10;&#10;[URL and title](/url/ &quot;title with single quotes&quot;)&#10;&#10;[with\_underscore](/url/with_underscore)&#10;&#10;[Email link](mailto:nobody@nowhere.net)&#10;&#10;[Empty]().">
+  <outline text="Explicit" _note="Just a [URL](/url/).&#10;&#10;[URL and title](/url/ &quot;title&quot;).&#10;&#10;[URL and title](/url/ &quot;title preceded by two spaces&quot;).&#10;&#10;[URL and title](/url/ &quot;title preceded by a tab&quot;).&#10;&#10;[URL and title](/url/ &quot;title with &quot;quotes&quot; in it&quot;)&#10;&#10;[URL and title](/url/ &quot;title with single quotes&quot;)&#10;&#10;[with_underscore](/url/with_underscore)&#10;&#10;[Email link](mailto:nobody@nowhere.net)&#10;&#10;[Empty]().">
   </outline>
   <outline text="Reference" _note="Foo [bar](/url/).&#10;&#10;With [embedded \[brackets\]](/url/).&#10;&#10;[b](/url/) by itself should be a link.&#10;&#10;Indented [once](/url).&#10;&#10;Indented [twice](/url).&#10;&#10;Indented [thrice](/url).&#10;&#10;This should \[not\]\[\] be a link.&#10;&#10;    [not]: /url&#10;&#10;Foo [bar](/url/ &quot;Title with &quot;quotes&quot; inside&quot;).&#10;&#10;Foo [biz](/url/ &quot;Title with &quot;quote&quot; inside&quot;).">
   </outline>
-  <outline text="With ampersands" _note="Here’s a [link with an ampersand in the&#10;URL](http://example.com/?foo=1&amp;bar=2).&#10;&#10;Here’s a link with an amersand in the link text:&#10;[AT&amp;T](http://att.com/ &quot;AT&amp;T&quot;).&#10;&#10;Here’s an [inline link](/script?foo=1&amp;bar=2).&#10;&#10;Here’s an [inline link in pointy braces](/script?foo=1&amp;bar=2).">
+  <outline text="With ampersands" _note="Here's a [link with an ampersand in the URL](http://example.com/?foo=1&amp;bar=2).&#10;&#10;Here's a link with an amersand in the link text: [AT&amp;T](http://att.com/ &quot;AT&amp;T&quot;).&#10;&#10;Here's an [inline link](/script?foo=1&amp;bar=2).&#10;&#10;Here's an [inline link in pointy braces](/script?foo=1&amp;bar=2).">
   </outline>
-  <outline text="Autolinks" _note="With an ampersand: &lt;http://example.com/?foo=1&amp;bar=2&gt;&#10;&#10;-   In a list?&#10;-   &lt;http://example.com/&gt;&#10;-   It should.&#10;&#10;An e-mail address: &lt;nobody@nowhere.net&gt;&#10;&#10;&gt; Blockquoted: &lt;http://example.com/&gt;&#10;&#10;Auto-links should not occur here: `&lt;http://example.com/&gt;`&#10;&#10;    or here: &lt;http://example.com/&gt;&#10;&#10;------------------------------------------------------------------------">
+  <outline text="Autolinks" _note="With an ampersand: &lt;http://example.com/?foo=1&amp;bar=2&gt;&#10;&#10;- In a list?&#10;- &lt;http://example.com/&gt;&#10;- It should.&#10;&#10;An e-mail address: &lt;nobody@nowhere.net&gt;&#10;&#10;&gt; Blockquoted: &lt;http://example.com/&gt;&#10;&#10;Auto-links should not occur here: `&lt;http://example.com/&gt;`&#10;&#10;    or here: &lt;http://example.com/&gt;&#10;&#10;--------------------------------------------------------------------------------">
   </outline>
 </outline>
-<outline text="Images" _note="From “Voyage dans la Lune” by Georges Melies (1902):&#10;&#10;![lalune](lalune.jpg &quot;Voyage dans la Lune&quot;)&#10;&#10;Here is a movie ![movie](movie.jpg) icon.&#10;&#10;------------------------------------------------------------------------">
+<outline text="Images" _note="From &quot;Voyage dans la Lune&quot; by Georges Melies (1902):&#10;&#10;![lalune](lalune.jpg &quot;Voyage dans la Lune&quot;)&#10;&#10;Here is a movie ![movie](movie.jpg) icon.&#10;&#10;--------------------------------------------------------------------------------">
 </outline>
-<outline text="Footnotes" _note="Here is a footnote reference,[1] and another.[2] This should *not* be a&#10;footnote reference, because it contains a space.\[^my note\] Here is an&#10;inline note.[3]&#10;&#10;&gt; Notes can go in quotes.[4]&#10;&#10;1.  And in list items.[5]&#10;&#10;This paragraph should not be part of the note, as it is not indented.&#10;&#10;[1] Here is the footnote. It can go anywhere after the footnote&#10;reference. It need not be placed at the end of the document.&#10;&#10;[2] Here’s the long note. This one contains multiple blocks.&#10;&#10;Subsequent blocks are indented to show that they belong to the footnote&#10;(as with list items).&#10;&#10;      { &lt;code&gt; }&#10;&#10;If you want, you can indent every line, but you can also be lazy and&#10;just indent the first line of each block.&#10;&#10;[3] This is *easier* to type. Inline notes may contain&#10;[links](http://google.com) and `]` verbatim characters, as well as&#10;\[bracketed text\].&#10;&#10;[4] In quote.&#10;&#10;[5] In list.">
+<outline text="Footnotes" _note="Here is a footnote reference,[^1] and another.[^2] This should *not* be a&#10;footnote reference, because it contains a space.\[\^my note\] Here is an inline&#10;note.[^3]&#10;&#10;&gt; Notes can go in quotes.[^4]&#10;&#10;1.  And in list items.[^5]&#10;&#10;This paragraph should not be part of the note, as it is not indented.&#10;&#10;[^1]: Here is the footnote. It can go anywhere after the footnote reference. It&#10;    need not be placed at the end of the document.&#10;&#10;[^2]: Here's the long note. This one contains multiple blocks.&#10;&#10;    Subsequent blocks are indented to show that they belong to the footnote (as&#10;    with list items).&#10;&#10;          { &lt;code&gt; }&#10;&#10;    If you want, you can indent every line, but you can also be lazy and just&#10;    indent the first line of each block.&#10;&#10;[^3]: This is *easier* to type. Inline notes may contain&#10;    [links](http://google.com) and `]` verbatim characters, as well as&#10;    \[bracketed text\].&#10;&#10;[^4]: In quote.&#10;&#10;[^5]: In list.">
 </outline>
   </body>
 </opml>
diff --git a/test/writer.org b/test/writer.org
--- a/test/writer.org
+++ b/test/writer.org
@@ -1,7 +1,7 @@
-#+TITLE: Pandoc Test Suite
+#+title: Pandoc Test Suite
 
-#+AUTHOR: John MacFarlane; Anonymous
-#+DATE: July 17, 2006
+#+author: John MacFarlane; Anonymous
+#+date: July 17, 2006
 
 This is a set of tests for pandoc. Most of them are adapted from John Gruber's
 markdown test suite.
@@ -9,61 +9,51 @@
 --------------
 
 * Headers
-  :PROPERTIES:
-  :CUSTOM_ID: headers
-  :END:
-
+:PROPERTIES:
+:CUSTOM_ID: headers
+:END:
 ** Level 2 with an [[/url][embedded link]]
-   :PROPERTIES:
-   :CUSTOM_ID: level-2-with-an-embedded-link
-   :END:
-
+:PROPERTIES:
+:CUSTOM_ID: level-2-with-an-embedded-link
+:END:
 *** Level 3 with /emphasis/
-    :PROPERTIES:
-    :CUSTOM_ID: level-3-with-emphasis
-    :END:
-
+:PROPERTIES:
+:CUSTOM_ID: level-3-with-emphasis
+:END:
 **** Level 4
-     :PROPERTIES:
-     :CUSTOM_ID: level-4
-     :END:
-
+:PROPERTIES:
+:CUSTOM_ID: level-4
+:END:
 ***** Level 5
-      :PROPERTIES:
-      :CUSTOM_ID: level-5
-      :END:
-
+:PROPERTIES:
+:CUSTOM_ID: level-5
+:END:
 * Level 1
-  :PROPERTIES:
-  :CUSTOM_ID: level-1
-  :END:
-
+:PROPERTIES:
+:CUSTOM_ID: level-1
+:END:
 ** Level 2 with /emphasis/
-   :PROPERTIES:
-   :CUSTOM_ID: level-2-with-emphasis
-   :END:
-
+:PROPERTIES:
+:CUSTOM_ID: level-2-with-emphasis
+:END:
 *** Level 3
-    :PROPERTIES:
-    :CUSTOM_ID: level-3
-    :END:
-
+:PROPERTIES:
+:CUSTOM_ID: level-3
+:END:
 with no blank line
 
 ** Level 2
-   :PROPERTIES:
-   :CUSTOM_ID: level-2
-   :END:
-
+:PROPERTIES:
+:CUSTOM_ID: level-2
+:END:
 with no blank line
 
 --------------
 
 * Paragraphs
-  :PROPERTIES:
-  :CUSTOM_ID: paragraphs
-  :END:
-
+:PROPERTIES:
+:CUSTOM_ID: paragraphs
+:END:
 Here's a regular paragraph.
 
 In Markdown 1.0.0 and earlier. Version 8. This line turns into a list item.
@@ -78,40 +68,39 @@
 --------------
 
 * Block Quotes
-  :PROPERTIES:
-  :CUSTOM_ID: block-quotes
-  :END:
-
+:PROPERTIES:
+:CUSTOM_ID: block-quotes
+:END:
 E-mail style:
 
-#+BEGIN_QUOTE
-  This is a block quote. It is pretty short.
-#+END_QUOTE
+#+begin_quote
+This is a block quote. It is pretty short.
+#+end_quote
 
-#+BEGIN_QUOTE
-  Code in a block quote:
+#+begin_quote
+Code in a block quote:
 
-  #+BEGIN_EXAMPLE
-      sub status {
-          print "working";
-      }
-  #+END_EXAMPLE
+#+begin_example
+sub status {
+    print "working";
+}
+#+end_example
 
-  A list:
+A list:
 
-  1. item one
-  2. item two
+1. item one
+2. item two
 
-  Nested block quotes:
+Nested block quotes:
 
-  #+BEGIN_QUOTE
-    nested
-  #+END_QUOTE
+#+begin_quote
+nested
+#+end_quote
 
-  #+BEGIN_QUOTE
-    nested
-  #+END_QUOTE
-#+END_QUOTE
+#+begin_quote
+nested
+#+end_quote
+#+end_quote
 
 This should not be a block quote: 2 > 1.
 
@@ -120,42 +109,39 @@
 --------------
 
 * Code Blocks
-  :PROPERTIES:
-  :CUSTOM_ID: code-blocks
-  :END:
-
+:PROPERTIES:
+:CUSTOM_ID: code-blocks
+:END:
 Code:
 
-#+BEGIN_EXAMPLE
-    ---- (should be four hyphens)
+#+begin_example
+---- (should be four hyphens)
 
-    sub status {
-        print "working";
-    }
+sub status {
+    print "working";
+}
 
-    this code block is indented by one tab
-#+END_EXAMPLE
+this code block is indented by one tab
+#+end_example
 
 And:
 
-#+BEGIN_EXAMPLE
-        this code block is indented by two tabs
+#+begin_example
+    this code block is indented by two tabs
 
-    These should not be escaped:  \$ \\ \> \[ \{
-#+END_EXAMPLE
+These should not be escaped:  \$ \\ \> \[ \{
+#+end_example
 
 --------------
 
 * Lists
-  :PROPERTIES:
-  :CUSTOM_ID: lists
-  :END:
-
+:PROPERTIES:
+:CUSTOM_ID: lists
+:END:
 ** Unordered
-   :PROPERTIES:
-   :CUSTOM_ID: unordered
-   :END:
-
+:PROPERTIES:
+:CUSTOM_ID: unordered
+:END:
 Asterisks tight:
 
 - asterisk 1
@@ -199,10 +185,9 @@
 - Minus 3
 
 ** Ordered
-   :PROPERTIES:
-   :CUSTOM_ID: ordered
-   :END:
-
+:PROPERTIES:
+:CUSTOM_ID: ordered
+:END:
 Tight:
 
 1. First
@@ -242,25 +227,20 @@
 3. Item 3.
 
 ** Nested
-   :PROPERTIES:
-   :CUSTOM_ID: nested
-   :END:
-
+:PROPERTIES:
+:CUSTOM_ID: nested
+:END:
 - Tab
-
   - Tab
-
     - Tab
 
 Here's another:
 
 1. First
 2. Second:
-
    - Fee
    - Fie
    - Foe
-
 3. Third
 
 Same thing but with paragraphs:
@@ -276,10 +256,9 @@
 3. Third
 
 ** Tabs and spaces
-   :PROPERTIES:
-   :CUSTOM_ID: tabs-and-spaces
-   :END:
-
+:PROPERTIES:
+:CUSTOM_ID: tabs-and-spaces
+:END:
 - this is a list item indented with tabs
 
 - this is a list item indented with spaces
@@ -289,36 +268,31 @@
   - this is an example list item indented with spaces
 
 ** Fancy list markers
-   :PROPERTIES:
-   :CUSTOM_ID: fancy-list-markers
-   :END:
+:PROPERTIES:
+:CUSTOM_ID: fancy-list-markers
+:END:
+2) [@2] begins with 2
 
-2) begins with 2
 3) and now 3
 
    with a continuation
 
-   4. sublist with roman numerals, starting with 4
+   4. [@4] sublist with roman numerals, starting with 4
    5. more items
-
       1) a subsublist
       2) a subsublist
 
 Nesting:
 
 1. Upper Alpha
-
    1. Upper Roman.
-
-      6) Decimal start with 6
-
-         3) Lower alpha with paren
+      6) [@6] Decimal start with 6
+         3) [@3] Lower alpha with paren
 
 Autonumbering:
 
 1. Autonumber.
 2. More.
-
    1. Nested.
 
 Should not be a list item:
@@ -330,10 +304,9 @@
 --------------
 
 * Definition Lists
-  :PROPERTIES:
-  :CUSTOM_ID: definition-lists
-  :END:
-
+:PROPERTIES:
+:CUSTOM_ID: definition-lists
+:END:
 Tight using spaces:
 
 - apple :: red fruit
@@ -362,13 +335,13 @@
 
 - /orange/ :: orange fruit
 
-  #+BEGIN_EXAMPLE
-      { orange code block }
-  #+END_EXAMPLE
+  #+begin_example
+  { orange code block }
+  #+end_example
 
-  #+BEGIN_QUOTE
-    orange block quote
-  #+END_QUOTE
+  #+begin_quote
+  orange block quote
+  #+end_quote
 
 Multiple definitions, tight:
 
@@ -399,10 +372,9 @@
   2. sublist
 
 * HTML Blocks
-  :PROPERTIES:
-  :CUSTOM_ID: html-blocks
-  :END:
-
+:PROPERTIES:
+:CUSTOM_ID: html-blocks
+:END:
 Simple block on one line:
 
 foo
@@ -415,45 +387,45 @@
 
 Interpreted markdown in a table:
 
-#+BEGIN_HTML
+#+begin_html
   <table>
-#+END_HTML
+#+end_html
 
-#+BEGIN_HTML
+#+begin_html
   <tr>
-#+END_HTML
+#+end_html
 
-#+BEGIN_HTML
+#+begin_html
   <td>
-#+END_HTML
+#+end_html
 
 This is /emphasized/
 
-#+BEGIN_HTML
+#+begin_html
   </td>
-#+END_HTML
+#+end_html
 
-#+BEGIN_HTML
+#+begin_html
   <td>
-#+END_HTML
+#+end_html
 
 And this is *strong*
 
-#+BEGIN_HTML
+#+begin_html
   </td>
-#+END_HTML
+#+end_html
 
-#+BEGIN_HTML
+#+begin_html
   </tr>
-#+END_HTML
+#+end_html
 
-#+BEGIN_HTML
+#+begin_html
   </table>
-#+END_HTML
+#+end_html
 
-#+BEGIN_HTML
+#+begin_html
   <script type="text/javascript">document.write('This *should not* be interpreted as markdown');</script>
-#+END_HTML
+#+end_html
 
 Here's a simple block:
 
@@ -461,17 +433,17 @@
 
 This should be a code block, though:
 
-#+BEGIN_EXAMPLE
-    <div>
-        foo
-    </div>
-#+END_EXAMPLE
+#+begin_example
+<div>
+    foo
+</div>
+#+end_example
 
 As should this:
 
-#+BEGIN_EXAMPLE
-    <div>foo</div>
-#+END_EXAMPLE
+#+begin_example
+<div>foo</div>
+#+end_example
 
 Now, nested:
 
@@ -479,88 +451,87 @@
 
 This should just be an HTML comment:
 
-#+BEGIN_HTML
+#+begin_html
   <!-- Comment -->
-#+END_HTML
+#+end_html
 
 Multiline:
 
-#+BEGIN_HTML
+#+begin_html
   <!--
   Blah
   Blah
   -->
-#+END_HTML
+#+end_html
 
-#+BEGIN_HTML
+#+begin_html
   <!--
       This is another comment.
   -->
-#+END_HTML
+#+end_html
 
 Code block:
 
-#+BEGIN_EXAMPLE
-    <!-- Comment -->
-#+END_EXAMPLE
+#+begin_example
+<!-- Comment -->
+#+end_example
 
 Just plain comment, with trailing spaces on the line:
 
-#+BEGIN_HTML
+#+begin_html
   <!-- foo -->
-#+END_HTML
+#+end_html
 
 Code:
 
-#+BEGIN_EXAMPLE
-    <hr />
-#+END_EXAMPLE
+#+begin_example
+<hr />
+#+end_example
 
 Hr's:
 
-#+BEGIN_HTML
+#+begin_html
   <hr>
-#+END_HTML
+#+end_html
 
-#+BEGIN_HTML
+#+begin_html
   <hr />
-#+END_HTML
+#+end_html
 
-#+BEGIN_HTML
+#+begin_html
   <hr />
-#+END_HTML
+#+end_html
 
-#+BEGIN_HTML
+#+begin_html
   <hr>
-#+END_HTML
+#+end_html
 
-#+BEGIN_HTML
+#+begin_html
   <hr />
-#+END_HTML
+#+end_html
 
-#+BEGIN_HTML
+#+begin_html
   <hr />
-#+END_HTML
+#+end_html
 
-#+BEGIN_HTML
+#+begin_html
   <hr class="foo" id="bar" />
-#+END_HTML
+#+end_html
 
-#+BEGIN_HTML
+#+begin_html
   <hr class="foo" id="bar" />
-#+END_HTML
+#+end_html
 
-#+BEGIN_HTML
+#+begin_html
   <hr class="foo" id="bar">
-#+END_HTML
+#+end_html
 
 --------------
 
 * Inline Markup
-  :PROPERTIES:
-  :CUSTOM_ID: inline-markup
-  :END:
-
+:PROPERTIES:
+:CUSTOM_ID: inline-markup
+:END:
 This is /emphasized/, and so /is this/.
 
 This is *strong*, and so *is this*.
@@ -583,26 +554,25 @@
 
 Subscripts: H_{2}O, H_{23}O, H_{many of them}O.
 
-These should not be superscripts or subscripts, because of the unescaped
-spaces: a\^b c\^d, a~b c~d.
+These should not be superscripts or subscripts, because of the unescaped spaces:
+a^b c^d, a~b c~d.
 
 --------------
 
 * Smart quotes, ellipses, dashes
-  :PROPERTIES:
-  :CUSTOM_ID: smart-quotes-ellipses-dashes
-  :END:
-
-"Hello," said the spider. "'Shelob' is my name."
+:PROPERTIES:
+:CUSTOM_ID: smart-quotes-ellipses-dashes
+:END:
+“Hello,” said the spider. “‘Shelob’ is my name.”
 
-'A', 'B', and 'C' are letters.
+‘A’, ‘B’, and ‘C’ are letters.
 
-'Oak,' 'elm,' and 'beech' are names of trees. So is 'pine.'
+‘Oak,’ ‘elm,’ and ‘beech’ are names of trees. So is ‘pine.’
 
-'He said, "I want to go."' Were you alive in the 70's?
+‘He said, “I want to go.”’ Were you alive in the 70's?
 
-Here is some quoted '=code=' and a "[[http://example.com/?foo=1&bar=2][quoted
-link]]".
+Here is some quoted ‘=code=’ and a
+“[[http://example.com/?foo=1&bar=2][quoted link]]”.
 
 Some dashes: one---two --- three---four --- five.
 
@@ -613,24 +583,23 @@
 --------------
 
 * LaTeX
-  :PROPERTIES:
-  :CUSTOM_ID: latex
-  :END:
-
+:PROPERTIES:
+:CUSTOM_ID: latex
+:END:
 - \cite[22-23]{smith.1899}
-- $2+2=4$
-- $x \in y$
-- $\alpha \wedge \omega$
-- $223$
-- $p$-Tree
+- \(2+2=4\)
+- \(x \in y\)
+- \(\alpha \wedge \omega\)
+- \(223\)
+- \(p\)-Tree
 - Here's some display math:
-  $$\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: $\alpha + \omega \times x^2$.
+  \[\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: \(\alpha + \omega \times x^2\).
 
 These shouldn't be math:
 
 - To get the famous equation, write =$e = mc^2$=.
-- $22,000 is a /lot/ of money. So is $34,000. (It worked if "lot" is
+- $22,000 is a /lot/ of money. So is $34,000. (It worked if “lot” is
   emphasized.)
 - Shoes ($20) and socks ($5).
 - Escaped =$=: $73 /this should be emphasized/ 23$.
@@ -646,10 +615,9 @@
 --------------
 
 * Special Characters
-  :PROPERTIES:
-  :CUSTOM_ID: special-characters
-  :END:
-
+:PROPERTIES:
+:CUSTOM_ID: special-characters
+:END:
 Here is some unicode:
 
 - I hat: Î
@@ -674,7 +642,7 @@
 
 Asterisk: *
 
-Underscore: \_
+Underscore: _
 
 Left brace: {
 
@@ -703,15 +671,13 @@
 --------------
 
 * Links
-  :PROPERTIES:
-  :CUSTOM_ID: links
-  :END:
-
+:PROPERTIES:
+:CUSTOM_ID: links
+:END:
 ** Explicit
-   :PROPERTIES:
-   :CUSTOM_ID: explicit
-   :END:
-
+:PROPERTIES:
+:CUSTOM_ID: explicit
+:END:
 Just a [[/url/][URL]].
 
 [[/url/][URL and title]].
@@ -724,17 +690,16 @@
 
 [[/url/][URL and title]]
 
-[[/url/with_underscore][with\_underscore]]
+[[/url/with_underscore][with_underscore]]
 
 [[mailto:nobody@nowhere.net][Email link]]
 
 [[][Empty]].
 
 ** Reference
-   :PROPERTIES:
-   :CUSTOM_ID: reference
-   :END:
-
+:PROPERTIES:
+:CUSTOM_ID: reference
+:END:
 Foo [[/url/][bar]].
 
 With [[/url/][embedded [brackets]]].
@@ -749,21 +714,19 @@
 
 This should [not][] be a link.
 
-#+BEGIN_EXAMPLE
-    [not]: /url
-#+END_EXAMPLE
+#+begin_example
+[not]: /url
+#+end_example
 
 Foo [[/url/][bar]].
 
 Foo [[/url/][biz]].
 
 ** With ampersands
-   :PROPERTIES:
-   :CUSTOM_ID: with-ampersands
-   :END:
-
-Here's a [[http://example.com/?foo=1&bar=2][link with an ampersand in the
-URL]].
+:PROPERTIES:
+:CUSTOM_ID: with-ampersands
+:END:
+Here's a [[http://example.com/?foo=1&bar=2][link with an ampersand in the URL]].
 
 Here's a link with an amersand in the link text: [[http://att.com/][AT&T]].
 
@@ -772,10 +735,9 @@
 Here's an [[/script?foo=1&bar=2][inline link in pointy braces]].
 
 ** Autolinks
-   :PROPERTIES:
-   :CUSTOM_ID: autolinks
-   :END:
-
+:PROPERTIES:
+:CUSTOM_ID: autolinks
+:END:
 With an ampersand: [[http://example.com/?foo=1&bar=2]]
 
 - In a list?
@@ -784,26 +746,25 @@
 
 An e-mail address: [[mailto:nobody@nowhere.net][nobody@nowhere.net]]
 
-#+BEGIN_QUOTE
-  Blockquoted: [[http://example.com/]]
-#+END_QUOTE
+#+begin_quote
+Blockquoted: [[http://example.com/]]
+#+end_quote
 
 Auto-links should not occur here: =<http://example.com/>=
 
-#+BEGIN_EXAMPLE
-    or here: <http://example.com/>
-#+END_EXAMPLE
+#+begin_example
+or here: <http://example.com/>
+#+end_example
 
 --------------
 
 * Images
-  :PROPERTIES:
-  :CUSTOM_ID: images
-  :END:
-
-From "Voyage dans la Lune" by Georges Melies (1902):
+:PROPERTIES:
+:CUSTOM_ID: images
+:END:
+From “Voyage dans la Lune” by Georges Melies (1902):
 
-#+CAPTION: lalune
+#+caption: lalune
 [[file:lalune.jpg]]
 
 Here is a movie [[file:movie.jpg]] icon.
@@ -811,36 +772,35 @@
 --------------
 
 * Footnotes
-  :PROPERTIES:
-  :CUSTOM_ID: footnotes
-  :END:
-
+:PROPERTIES:
+:CUSTOM_ID: footnotes
+:END:
 Here is a footnote reference,[fn:1] and another.[fn:2] This should /not/ be a
-footnote reference, because it contains a space.[\^my note] Here is an inline
+footnote reference, because it contains a space.[^my note] Here is an inline
 note.[fn:3]
 
-#+BEGIN_QUOTE
-  Notes can go in quotes.[fn:4]
-#+END_QUOTE
+#+begin_quote
+Notes can go in quotes.[fn:4]
+#+end_quote
 
 1. And in list items.[fn:5]
 
 This paragraph should not be part of the note, as it is not indented.
 
-[fn:1] Here is the footnote. It can go anywhere after the footnote reference.
-       It need not be placed at the end of the document.
+[fn:1] Here is the footnote. It can go anywhere after the footnote reference. It
+       need not be placed at the end of the document.
 
 [fn:2] Here's the long note. This one contains multiple blocks.
 
        Subsequent blocks are indented to show that they belong to the footnote
        (as with list items).
 
-       #+BEGIN_EXAMPLE
-             { <code> }
-       #+END_EXAMPLE
+       #+begin_example
+         { <code> }
+       #+end_example
 
-       If you want, you can indent every line, but you can also be lazy and
-       just indent the first line of each block.
+       If you want, you can indent every line, but you can also be lazy and just
+       indent the first line of each block.
 
 [fn:3] This is /easier/ to type. Inline notes may contain
        [[http://google.com][links]] and =]= verbatim characters, as well as
diff --git a/test/writer.plain b/test/writer.plain
--- a/test/writer.plain
+++ b/test/writer.plain
@@ -5,43 +5,33 @@
 This is a set of tests for pandoc. Most of them are adapted from John Gruber’s
 markdown test suite.
 
-------------------------------------------------------------------------------
-
-
-
-HEADERS
+--------------------------------------------------------------------------------
 
+Headers
 
 Level 2 with an embedded link
 
-Level 3 with _emphasis_
+Level 3 with emphasis
 
 Level 4
 
 Level 5
 
-
-
-LEVEL 1
-
+Level 1
 
-Level 2 with _emphasis_
+Level 2 with emphasis
 
 Level 3
 
 with no blank line
 
-
 Level 2
 
 with no blank line
 
-------------------------------------------------------------------------------
-
-
-
-PARAGRAPHS
+--------------------------------------------------------------------------------
 
+Paragraphs
 
 Here’s a regular paragraph.
 
@@ -54,12 +44,9 @@
 There should be a hard line break
 here.
 
-------------------------------------------------------------------------------
-
-
-
-BLOCK QUOTES
+--------------------------------------------------------------------------------
 
+Block Quotes
 
 E-mail style:
 
@@ -86,12 +73,9 @@
 
 And a following paragraph.
 
-------------------------------------------------------------------------------
-
-
-
-CODE BLOCKS
+--------------------------------------------------------------------------------
 
+Code Blocks
 
 Code:
 
@@ -109,57 +93,53 @@
 
     These should not be escaped:  \$ \\ \> \[ \{
 
-------------------------------------------------------------------------------
-
-
-
-LISTS
+--------------------------------------------------------------------------------
 
+Lists
 
 Unordered
 
 Asterisks tight:
 
--   asterisk 1
--   asterisk 2
--   asterisk 3
+- asterisk 1
+- asterisk 2
+- asterisk 3
 
 Asterisks loose:
 
--   asterisk 1
+- asterisk 1
 
--   asterisk 2
+- asterisk 2
 
--   asterisk 3
+- asterisk 3
 
 Pluses tight:
 
--   Plus 1
--   Plus 2
--   Plus 3
+- Plus 1
+- Plus 2
+- Plus 3
 
 Pluses loose:
 
--   Plus 1
+- Plus 1
 
--   Plus 2
+- Plus 2
 
--   Plus 3
+- Plus 3
 
 Minuses tight:
 
--   Minus 1
--   Minus 2
--   Minus 3
+- Minus 1
+- Minus 2
+- Minus 3
 
 Minuses loose:
 
--   Minus 1
-
--   Minus 2
+- Minus 1
 
--   Minus 3
+- Minus 2
 
+- Minus 3
 
 Ordered
 
@@ -201,20 +181,19 @@
 
 3.  Item 3.
 
-
 Nested
 
--   Tab
-    -   Tab
-        -   Tab
+- Tab
+  - Tab
+    - Tab
 
 Here’s another:
 
 1.  First
 2.  Second:
-    -   Fee
-    -   Fie
-    -   Foe
+    - Fee
+    - Fie
+    - Foe
 3.  Third
 
 Same thing but with paragraphs:
@@ -223,27 +202,26 @@
 
 2.  Second:
 
-    -   Fee
-    -   Fie
-    -   Foe
+    - Fee
+    - Fie
+    - Foe
 
 3.  Third
 
-
 Tabs and spaces
 
--   this is a list item indented with tabs
-
--   this is a list item indented with spaces
+- this is a list item indented with tabs
 
-    -   this is an example list item indented with tabs
+- this is a list item indented with spaces
 
-    -   this is an example list item indented with spaces
+  - this is an example list item indented with tabs
 
+  - this is an example list item indented with spaces
 
 Fancy list markers
 
 (2) begins with 2
+
 (3) and now 3
 
     with a continuation
@@ -272,108 +250,102 @@
 
 B. Williams
 
-------------------------------------------------------------------------------
-
-
-
-DEFINITION LISTS
+--------------------------------------------------------------------------------
 
+Definition Lists
 
 Tight using spaces:
 
 apple
-    red fruit
+  red fruit
 
 orange
-    orange fruit
+  orange fruit
 
 banana
-    yellow fruit
+  yellow fruit
 
 Tight using tabs:
 
 apple
-    red fruit
+  red fruit
 
 orange
-    orange fruit
+  orange fruit
 
 banana
-    yellow fruit
+  yellow fruit
 
 Loose:
 
 apple
 
-    red fruit
+  red fruit
 
 orange
 
-    orange fruit
+  orange fruit
 
 banana
 
-    yellow fruit
+  yellow fruit
 
 Multiple blocks with italics:
 
-_apple_
+apple
 
-    red fruit
+  red fruit
 
-    contains seeds, crisp, pleasant to taste
+  contains seeds, crisp, pleasant to taste
 
-_orange_
+orange
 
-    orange fruit
+  orange fruit
 
-        { orange code block }
+      { orange code block }
 
-      orange block quote
+    orange block quote
 
 Multiple definitions, tight:
 
 apple
-    red fruit
-    computer
+  red fruit
+  computer
 
 orange
-    orange fruit
-    bank
+  orange fruit
+  bank
 
 Multiple definitions, loose:
 
 apple
 
-    red fruit
+  red fruit
 
-    computer
+  computer
 
 orange
 
-    orange fruit
+  orange fruit
 
-    bank
+  bank
 
 Blank line after term, indented marker, alternate markers:
 
 apple
 
-    red fruit
+  red fruit
 
-    computer
+  computer
 
 orange
 
-    orange fruit
-
-    1.  sublist
-    2.  sublist
-
-
+  orange fruit
 
-HTML BLOCKS
+  1.  sublist
+  2.  sublist
 
+HTML Blocks
 
 Simple block on one line:
 
@@ -387,8 +359,8 @@
 
 Interpreted markdown in a table:
 
-This is _emphasized_
-And this is STRONG
+This is emphasized
+And this is strong
 Here’s a simple block:
 
 foo
@@ -423,44 +395,38 @@
 
 Hr’s:
 
-------------------------------------------------------------------------------
-
-
-
-INLINE MARKUP
+--------------------------------------------------------------------------------
 
+Inline Markup
 
-This is _emphasized_, and so _is this_.
+This is emphasized, and so is this.
 
-This is STRONG, and so IS THIS.
+This is strong, and so is this.
 
-An _emphasized link_.
+An emphasized link.
 
-_THIS IS STRONG AND EM._
+This is strong and em.
 
-So is _THIS_ word.
+So is this word.
 
-_THIS IS STRONG AND EM._
+This is strong and em.
 
-So is _THIS_ word.
+So is this word.
 
 This is code: >, $, \, \$, <html>.
 
-~~This is _strikeout_.~~
+~~This is strikeout.~~
 
-Superscripts: a^(bc)d a^(_hello_) a^(hello there).
+Superscripts: a^(bc)d a^(hello) a^(hello there).
 
 Subscripts: H₂O, H₂₃O, H_(many of them)O.
 
-These should not be superscripts or subscripts, because of the unescaped
-spaces: a^b c^d, a~b c~d.
-
-------------------------------------------------------------------------------
-
-
+These should not be superscripts or subscripts, because of the unescaped spaces:
+a^b c^d, a~b c~d.
 
-SMART QUOTES, ELLIPSES, DASHES
+--------------------------------------------------------------------------------
 
+Smart quotes, ellipses, dashes
 
 “Hello,” said the spider. “‘Shelob’ is my name.”
 
@@ -478,47 +444,40 @@
 
 Ellipses…and…and….
 
-------------------------------------------------------------------------------
-
-
-
-LATEX
+--------------------------------------------------------------------------------
 
+LaTeX
 
--   
--   2 + 2 = 4
--   x ∈ y
--   α ∧ ω
--   223
--   p-Tree
--   Here’s some display math:
-    $$\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: α + ω × x².
+- 
+- 2 + 2 = 4
+- x ∈ y
+- α ∧ ω
+- 223
+- p-Tree
+- Here’s some display math:
+  $$\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: α + ω × x².
 
 These shouldn’t be math:
 
--   To get the famous equation, write $e = mc^2$.
--   $22,000 is a _lot_ of money. So is $34,000. (It worked if “lot” is
-    emphasized.)
--   Shoes ($20) and socks ($5).
--   Escaped $: $73 _this should be emphasized_ 23$.
+- To get the famous equation, write $e = mc^2$.
+- $22,000 is a lot of money. So is $34,000. (It worked if “lot” is emphasized.)
+- Shoes ($20) and socks ($5).
+- Escaped $: $73 this should be emphasized 23$.
 
 Here’s a LaTeX table:
 
-------------------------------------------------------------------------------
-
-
-
-SPECIAL CHARACTERS
+--------------------------------------------------------------------------------
 
+Special Characters
 
 Here is some unicode:
 
--   I hat: Î
--   o umlaut: ö
--   section: §
--   set membership: ∈
--   copyright: ©
+- I hat: Î
+- o umlaut: ö
+- section: §
+- set membership: ∈
+- copyright: ©
 
 AT&T has an ampersand in their name.
 
@@ -562,12 +521,9 @@
 
 Minus: -
 
-------------------------------------------------------------------------------
-
-
-
-LINKS
+--------------------------------------------------------------------------------
 
+Links
 
 Explicit
 
@@ -589,7 +545,6 @@
 
 Empty.
 
-
 Reference
 
 Foo bar.
@@ -612,7 +567,6 @@
 
 Foo biz.
 
-
 With ampersands
 
 Here’s a link with an ampersand in the URL.
@@ -623,14 +577,13 @@
 
 Here’s an inline link in pointy braces.
 
-
 Autolinks
 
 With an ampersand: http://example.com/?foo=1&bar=2
 
--   In a list?
--   http://example.com/
--   It should.
+- In a list?
+- http://example.com/
+- It should.
 
 An e-mail address: nobody@nowhere.net
 
@@ -640,12 +593,9 @@
 
     or here: <http://example.com/>
 
-------------------------------------------------------------------------------
-
-
-
-IMAGES
+--------------------------------------------------------------------------------
 
+Images
 
 From “Voyage dans la Lune” by Georges Melies (1902):
 
@@ -653,16 +603,12 @@
 
 Here is a movie [movie] icon.
 
-------------------------------------------------------------------------------
-
-
-
-FOOTNOTES
+--------------------------------------------------------------------------------
 
+Footnotes
 
-Here is a footnote reference,[1] and another.[2] This should _not_ be a
-footnote reference, because it contains a space.[^my note] Here is an inline
-note.[3]
+Here is a footnote reference,[1] and another.[2] This should not be a footnote
+reference, because it contains a space.[^my note] Here is an inline note.[3]
 
   Notes can go in quotes.[4]
 
@@ -675,15 +621,15 @@
 
 [2] Here’s the long note. This one contains multiple blocks.
 
-Subsequent blocks are indented to show that they belong to the footnote (as
-with list items).
+Subsequent blocks are indented to show that they belong to the footnote (as with
+list items).
 
       { <code> }
 
-If you want, you can indent every line, but you can also be lazy and just
-indent the first line of each block.
+If you want, you can indent every line, but you can also be lazy and just indent
+the first line of each block.
 
-[3] This is _easier_ to type. Inline notes may contain links and ] verbatim
+[3] This is easier to type. Inline notes may contain links and ] verbatim
 characters, as well as [bracketed text].
 
 [4] In quote.
diff --git a/test/writer.rst b/test/writer.rst
--- a/test/writer.rst
+++ b/test/writer.rst
@@ -4,11 +4,7 @@
 
 :Author: John MacFarlane
 :Author: Anonymous
-:Date:   July 17, 2006
-
-.. role:: math(raw)
-   :format: html latex
-..
+:Date: July 17, 2006
 
 .. role:: raw-latex(raw)
    :format: latex
@@ -73,30 +69,30 @@
 
 E-mail style:
 
-    This is a block quote. It is pretty short.
+   This is a block quote. It is pretty short.
 
 ..
 
-    Code in a block quote:
+   Code in a block quote:
 
-    ::
+   ::
 
-        sub status {
-            print "working";
-        }
+      sub status {
+          print "working";
+      }
 
-    A list:
+   A list:
 
-    1. item one
-    2. item two
+   1. item one
+   2. item two
 
-    Nested block quotes:
+   Nested block quotes:
 
-        nested
+      nested
 
-    ..
+   ..
 
-        nested
+      nested
 
 This should not be a block quote: 2 > 1.
 
@@ -111,21 +107,21 @@
 
 ::
 
-    ---- (should be four hyphens)
+   ---- (should be four hyphens)
 
-    sub status {
-        print "working";
-    }
+   sub status {
+       print "working";
+   }
 
-    this code block is indented by one tab
+   this code block is indented by one tab
 
 And:
 
 ::
 
-        this code block is indented by two tabs
+       this code block is indented by two tabs
 
-    These should not be escaped:  \$ \\ \> \[ \{
+   These should not be escaped:  \$ \\ \> \[ \{
 
 --------------
 
@@ -137,45 +133,45 @@
 
 Asterisks tight:
 
--  asterisk 1
--  asterisk 2
--  asterisk 3
+- asterisk 1
+- asterisk 2
+- asterisk 3
 
 Asterisks loose:
 
--  asterisk 1
+- asterisk 1
 
--  asterisk 2
+- asterisk 2
 
--  asterisk 3
+- asterisk 3
 
 Pluses tight:
 
--  Plus 1
--  Plus 2
--  Plus 3
+- Plus 1
+- Plus 2
+- Plus 3
 
 Pluses loose:
 
--  Plus 1
+- Plus 1
 
--  Plus 2
+- Plus 2
 
--  Plus 3
+- Plus 3
 
 Minuses tight:
 
--  Minus 1
--  Minus 2
--  Minus 3
+- Minus 1
+- Minus 2
+- Minus 3
 
 Minuses loose:
 
--  Minus 1
+- Minus 1
 
--  Minus 2
+- Minus 2
 
--  Minus 3
+- Minus 3
 
 Ordered
 -------
@@ -221,20 +217,20 @@
 Nested
 ------
 
--  Tab
+- Tab
 
-   -  Tab
+  - Tab
 
-      -  Tab
+    - Tab
 
 Here’s another:
 
 1. First
 2. Second:
 
-   -  Fee
-   -  Fie
-   -  Foe
+   - Fee
+   - Fie
+   - Foe
 
 3. Third
 
@@ -244,27 +240,28 @@
 
 2. Second:
 
-   -  Fee
-   -  Fie
-   -  Foe
+   - Fee
+   - Fie
+   - Foe
 
 3. Third
 
 Tabs and spaces
 ---------------
 
--  this is a list item indented with tabs
+- this is a list item indented with tabs
 
--  this is a list item indented with spaces
+- this is a list item indented with spaces
 
-   -  this is an example list item indented with tabs
+  - this is an example list item indented with tabs
 
-   -  this is an example list item indented with spaces
+  - this is an example list item indented with spaces
 
 Fancy list markers
 ------------------
 
 (2) begins with 2
+
 (3) and now 3
 
     with a continuation
@@ -306,136 +303,106 @@
 Tight using spaces:
 
 apple
-    red fruit
+   red fruit
 orange
-    orange fruit
+   orange fruit
 banana
-    yellow fruit
+   yellow fruit
 
 Tight using tabs:
 
 apple
-    red fruit
+   red fruit
 orange
-    orange fruit
+   orange fruit
 banana
-    yellow fruit
+   yellow fruit
 
 Loose:
 
 apple
-    red fruit
+   red fruit
 
 orange
-    orange fruit
+   orange fruit
 
 banana
-    yellow fruit
+   yellow fruit
 
 Multiple blocks with italics:
 
 *apple*
-    red fruit
+   red fruit
 
-    contains seeds, crisp, pleasant to taste
+   contains seeds, crisp, pleasant to taste
 
 *orange*
-    orange fruit
+   orange fruit
 
-    ::
+   ::
 
-        { orange code block }
+      { orange code block }
 
-    ..
+   ..
 
-        orange block quote
+      orange block quote
 
 Multiple definitions, tight:
 
 apple
-    red fruit
-    computer
+   red fruit
+   computer
 orange
-    orange fruit
-    bank
+   orange fruit
+   bank
 
 Multiple definitions, loose:
 
 apple
-    red fruit
+   red fruit
 
-    computer
+   computer
 
 orange
-    orange fruit
+   orange fruit
 
-    bank
+   bank
 
 Blank line after term, indented marker, alternate markers:
 
 apple
-    red fruit
+   red fruit
 
-    computer
+   computer
 
 orange
-    orange fruit
+   orange fruit
 
-    1. sublist
-    2. sublist
+   1. sublist
+   2. sublist
 
 HTML Blocks
 ===========
 
 Simple block on one line:
 
-.. raw:: html
-
-   <div>
-
-foo
-
-.. raw:: html
+.. container::
 
-   </div>
+   foo
 
 And nested without indentation:
 
-.. raw:: html
-
-   <div>
-
-.. raw:: html
-
-   <div>
-
-.. raw:: html
-
-   <div>
-
-foo
-
-.. raw:: html
-
-   </div>
-
-.. raw:: html
-
-   </div>
-
-.. raw:: html
-
-   <div>
+.. container::
 
-bar
+   .. container::
 
-.. raw:: html
+      .. container::
 
-   </div>
+         foo
 
-.. raw:: html
+   .. container::
 
-   </div>
+      bar
 
 Interpreted markdown in a table:
 
@@ -481,57 +448,33 @@
 
 Here’s a simple block:
 
-.. raw:: html
-
-   <div>
-
-foo
-
-.. raw:: html
+.. container::
 
-   </div>
+   foo
 
 This should be a code block, though:
 
 ::
 
-    <div>
-        foo
-    </div>
+   <div>
+       foo
+   </div>
 
 As should this:
 
 ::
 
-    <div>foo</div>
+   <div>foo</div>
 
 Now, nested:
 
-.. raw:: html
-
-   <div>
-
-.. raw:: html
-
-   <div>
-
-.. raw:: html
-
-   <div>
-
-foo
-
-.. raw:: html
-
-   </div>
-
-.. raw:: html
+.. container::
 
-   </div>
+   .. container::
 
-.. raw:: html
+      .. container::
 
-   </div>
+         foo
 
 This should just be an HTML comment:
 
@@ -558,7 +501,7 @@
 
 ::
 
-    <!-- Comment -->
+   <!-- Comment -->
 
 Just plain comment, with trailing spaces on the line:
 
@@ -570,7 +513,7 @@
 
 ::
 
-    <hr />
+   <hr />
 
 Hr’s:
 
@@ -619,26 +562,26 @@
 
 This is **strong**, and so **is this**.
 
-An *`emphasized link </url>`__*.
+An `emphasized link </url>`__.
 
-***This is strong and em.***
+**This is strong and em.**
 
-So is ***this*** word.
+So is **this** word.
 
-***This is strong and em.***
+**This is strong and em.**
 
-So is ***this*** word.
+So is **this** word.
 
 This is code: ``>``, ``$``, ``\``, ``\$``, ``<html>``.
 
-[STRIKEOUT:This is *strikeout*.]
+[STRIKEOUT:This is strikeout.]
 
-Superscripts: a\ :sup:`bc`\ d a\ :sup:`*hello*` a\ :sup:`hello there`.
+Superscripts: a\ :sup:`bc`\ d a\ :sup:`hello` a\ :sup:`hello there`.
 
 Subscripts: H\ :sub:`2`\ O, H\ :sub:`23`\ O, H\ :sub:`many of them`\ O.
 
-These should not be superscripts or subscripts, because of the unescaped
-spaces: a^b c^d, a~b c~d.
+These should not be superscripts or subscripts, because of the unescaped spaces:
+a^b c^d, a~b c~d.
 
 --------------
 
@@ -667,25 +610,24 @@
 LaTeX
 =====
 
--  :raw-latex:`\cite[22-23]{smith.1899}`
--  :math:`2+2=4`
--  :math:`x \in y`
--  :math:`\alpha \wedge \omega`
--  :math:`223`
--  :math:`p`-Tree
--  Here’s some display math:
-
-   .. math:: \frac{d}{dx}f(x)=\lim_{h\to 0}\frac{f(x+h)-f(x)}{h}
+- :raw-latex:`\cite[22-23]{smith.1899}`
+- :math:`2+2=4`
+- :math:`x \in y`
+- :math:`\alpha \wedge \omega`
+- :math:`223`
+- :math:`p`-Tree
+- Here’s some display math:
 
--  Here’s one that has a line break in it: :math:`\alpha + \omega \times x^2`.
+  .. math:: \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: :math:`\alpha + \omega \times x^2`.
 
 These shouldn’t be math:
 
--  To get the famous equation, write ``$e = mc^2$``.
--  $22,000 is a *lot* of money. So is $34,000. (It worked if “lot” is
-   emphasized.)
--  Shoes ($20) and socks ($5).
--  Escaped ``$``: $73 *this should be emphasized* 23$.
+- To get the famous equation, write ``$e = mc^2$``.
+- $22,000 is a *lot* of money. So is $34,000. (It worked if “lot” is
+  emphasized.)
+- Shoes ($20) and socks ($5).
+- Escaped ``$``: $73 *this should be emphasized* 23$.
 
 Here’s a LaTeX table:
 
@@ -704,11 +646,11 @@
 
 Here is some unicode:
 
--  I hat: Î
--  o umlaut: ö
--  section: §
--  set membership: ∈
--  copyright: ©
+- I hat: Î
+- o umlaut: ö
+- section: §
+- set membership: ∈
+- copyright: ©
 
 AT&T has an ampersand in their name.
 
@@ -797,7 +739,7 @@
 
 ::
 
-    [not]: /url
+   [not]: /url
 
 Foo `bar </url/>`__.
 
@@ -820,19 +762,19 @@
 
 With an ampersand: http://example.com/?foo=1&bar=2
 
--  In a list?
--  http://example.com/
--  It should.
+- In a list?
+- http://example.com/
+- It should.
 
 An e-mail address: nobody@nowhere.net
 
-    Blockquoted: http://example.com/
+   Blockquoted: http://example.com/
 
 Auto-links should not occur here: ``<http://example.com/>``
 
 ::
 
-    or here: <http://example.com/>
+   or here: <http://example.com/>
 
 --------------
 
@@ -842,7 +784,7 @@
 From “Voyage dans la Lune” by Georges Melies (1902):
 
 .. figure:: lalune.jpg
-   :alt: Voyage dans la Lune
+   :alt: lalune
 
    lalune
 
@@ -857,7 +799,7 @@
 footnote reference, because it contains a space.[^my note] Here is an inline
 note. [3]_
 
-    Notes can go in quotes. [4]_
+   Notes can go in quotes. [4]_
 
 1. And in list items. [5]_
 
@@ -875,7 +817,7 @@
 
    ::
 
-         { <code> }
+        { <code> }
 
    If you want, you can indent every line, but you can also be lazy and just
    indent the first line of each block.
diff --git a/test/writer.rtf b/test/writer.rtf
--- a/test/writer.rtf
+++ b/test/writer.rtf
@@ -1,4 +1,4 @@
-{\rtf1\ansi\deff0{\fonttbl{\f0 \fswiss Helvetica;}{\f1 Courier;}}
+{\rtf1\ansi\deff0{\fonttbl{\f0 \fswiss Helvetica;}{\f1 \fmodern Courier;}}
 {\colortbl;\red255\green0\blue0;\red0\green0\blue255;}
 \widowctrl\hyphauto
 
@@ -9,28 +9,28 @@
 {\pard \ql \f0 \sa180 \li0 \fi0 \par}
 {\pard \ql \f0 \sa180 \li0 \fi0 This is a set of tests for pandoc. Most of them are adapted from John Gruber\u8217's markdown test suite.\par}
 {\pard \qc \f0 \sa180 \li0 \fi0 \emdash\emdash\emdash\emdash\emdash\par}
-{\pard \ql \f0 \sa180 \li0 \fi0 \b \fs36 Headers\par}
-{\pard \ql \f0 \sa180 \li0 \fi0 \b \fs32 Level 2 with an {\field{\*\fldinst{HYPERLINK "/url"}}{\fldrslt{\ul
+{\pard \ql \f0 \sa180 \li0 \fi0 \outlinelevel0 \b \fs36 Headers\par}
+{\pard \ql \f0 \sa180 \li0 \fi0 \outlinelevel1 \b \fs32 Level 2 with an {\field{\*\fldinst{HYPERLINK "/url"}}{\fldrslt{\ul
 embedded link
 }}}
 \par}
-{\pard \ql \f0 \sa180 \li0 \fi0 \b \fs28 Level 3 with {\i emphasis}\par}
-{\pard \ql \f0 \sa180 \li0 \fi0 \b \fs24 Level 4\par}
-{\pard \ql \f0 \sa180 \li0 \fi0 \b \fs20 Level 5\par}
-{\pard \ql \f0 \sa180 \li0 \fi0 \b \fs36 Level 1\par}
-{\pard \ql \f0 \sa180 \li0 \fi0 \b \fs32 Level 2 with {\i emphasis}\par}
-{\pard \ql \f0 \sa180 \li0 \fi0 \b \fs28 Level 3\par}
+{\pard \ql \f0 \sa180 \li0 \fi0 \outlinelevel2 \b \fs28 Level 3 with {\i emphasis}\par}
+{\pard \ql \f0 \sa180 \li0 \fi0 \outlinelevel3 \b \fs24 Level 4\par}
+{\pard \ql \f0 \sa180 \li0 \fi0 \outlinelevel4 \b \fs20 Level 5\par}
+{\pard \ql \f0 \sa180 \li0 \fi0 \outlinelevel0 \b \fs36 Level 1\par}
+{\pard \ql \f0 \sa180 \li0 \fi0 \outlinelevel1 \b \fs32 Level 2 with {\i emphasis}\par}
+{\pard \ql \f0 \sa180 \li0 \fi0 \outlinelevel2 \b \fs28 Level 3\par}
 {\pard \ql \f0 \sa180 \li0 \fi0 with no blank line\par}
-{\pard \ql \f0 \sa180 \li0 \fi0 \b \fs32 Level 2\par}
+{\pard \ql \f0 \sa180 \li0 \fi0 \outlinelevel1 \b \fs32 Level 2\par}
 {\pard \ql \f0 \sa180 \li0 \fi0 with no blank line\par}
 {\pard \qc \f0 \sa180 \li0 \fi0 \emdash\emdash\emdash\emdash\emdash\par}
-{\pard \ql \f0 \sa180 \li0 \fi0 \b \fs36 Paragraphs\par}
+{\pard \ql \f0 \sa180 \li0 \fi0 \outlinelevel0 \b \fs36 Paragraphs\par}
 {\pard \ql \f0 \sa180 \li0 \fi0 Here\u8217's a regular paragraph.\par}
 {\pard \ql \f0 \sa180 \li0 \fi0 In Markdown 1.0.0 and earlier. Version 8. This line turns into a list item. Because a hard-wrapped line in the middle of a paragraph looked like a list item.\par}
 {\pard \ql \f0 \sa180 \li0 \fi0 Here\u8217's one with a bullet. * criminey.\par}
 {\pard \ql \f0 \sa180 \li0 \fi0 There should be a hard line break\line here.\par}
 {\pard \qc \f0 \sa180 \li0 \fi0 \emdash\emdash\emdash\emdash\emdash\par}
-{\pard \ql \f0 \sa180 \li0 \fi0 \b \fs36 Block Quotes\par}
+{\pard \ql \f0 \sa180 \li0 \fi0 \outlinelevel0 \b \fs36 Block Quotes\par}
 {\pard \ql \f0 \sa180 \li0 \fi0 E-mail style:\par}
 {\pard \ql \f0 \sa180 \li720 \fi0 This is a block quote. It is pretty short.\par}
 {\pard \ql \f0 \sa180 \li720 \fi0 Code in a block quote:\par}
@@ -46,7 +46,7 @@
 {\pard \ql \f0 \sa180 \li0 \fi0 This should not be a block quote: 2 > 1.\par}
 {\pard \ql \f0 \sa180 \li0 \fi0 And a following paragraph.\par}
 {\pard \qc \f0 \sa180 \li0 \fi0 \emdash\emdash\emdash\emdash\emdash\par}
-{\pard \ql \f0 \sa180 \li0 \fi0 \b \fs36 Code Blocks\par}
+{\pard \ql \f0 \sa180 \li0 \fi0 \outlinelevel0 \b \fs36 Code Blocks\par}
 {\pard \ql \f0 \sa180 \li0 \fi0 Code:\par}
 {\pard \ql \f0 \sa180 \li0 \fi0 \f1 ---- (should be four hyphens)\line
 \line
@@ -60,8 +60,8 @@
 \line
 These should not be escaped:  \\$ \\\\ \\> \\[ \\\{\par}
 {\pard \qc \f0 \sa180 \li0 \fi0 \emdash\emdash\emdash\emdash\emdash\par}
-{\pard \ql \f0 \sa180 \li0 \fi0 \b \fs36 Lists\par}
-{\pard \ql \f0 \sa180 \li0 \fi0 \b \fs32 Unordered\par}
+{\pard \ql \f0 \sa180 \li0 \fi0 \outlinelevel0 \b \fs36 Lists\par}
+{\pard \ql \f0 \sa180 \li0 \fi0 \outlinelevel1 \b \fs32 Unordered\par}
 {\pard \ql \f0 \sa180 \li0 \fi0 Asterisks tight:\par}
 {\pard \ql \f0 \sa0 \li360 \fi-360 \bullet \tx360\tab asterisk 1\par}
 {\pard \ql \f0 \sa0 \li360 \fi-360 \bullet \tx360\tab asterisk 2\par}
@@ -86,7 +86,7 @@
 {\pard \ql \f0 \sa180 \li360 \fi-360 \bullet \tx360\tab Minus 1\par}
 {\pard \ql \f0 \sa180 \li360 \fi-360 \bullet \tx360\tab Minus 2\par}
 {\pard \ql \f0 \sa180 \li360 \fi-360 \bullet \tx360\tab Minus 3\sa180\par}
-{\pard \ql \f0 \sa180 \li0 \fi0 \b \fs32 Ordered\par}
+{\pard \ql \f0 \sa180 \li0 \fi0 \outlinelevel1 \b \fs32 Ordered\par}
 {\pard \ql \f0 \sa180 \li0 \fi0 Tight:\par}
 {\pard \ql \f0 \sa0 \li360 \fi-360 1.\tx360\tab First\par}
 {\pard \ql \f0 \sa0 \li360 \fi-360 2.\tx360\tab Second\par}
@@ -108,7 +108,7 @@
 {\pard \ql \f0 \sa180 \li360 \fi0 Item 1. graf two. The quick brown fox jumped over the lazy dog\u8217's back.\par}
 {\pard \ql \f0 \sa180 \li360 \fi-360 2.\tx360\tab Item 2.\par}
 {\pard \ql \f0 \sa180 \li360 \fi-360 3.\tx360\tab Item 3.\sa180\par}
-{\pard \ql \f0 \sa180 \li0 \fi0 \b \fs32 Nested\par}
+{\pard \ql \f0 \sa180 \li0 \fi0 \outlinelevel1 \b \fs32 Nested\par}
 {\pard \ql \f0 \sa0 \li360 \fi-360 \bullet \tx360\tab Tab\par}
 {\pard \ql \f0 \sa0 \li720 \fi-360 \endash \tx360\tab Tab\par}
 {\pard \ql \f0 \sa0 \li1080 \fi-360 \bullet \tx360\tab Tab\sa180\sa180\sa180\par}
@@ -126,13 +126,13 @@
 {\pard \ql \f0 \sa0 \li720 \fi-360 \endash \tx360\tab Fie\par}
 {\pard \ql \f0 \sa0 \li720 \fi-360 \endash \tx360\tab Foe\sa180\par}
 {\pard \ql \f0 \sa180 \li360 \fi-360 3.\tx360\tab Third\sa180\par}
-{\pard \ql \f0 \sa180 \li0 \fi0 \b \fs32 Tabs and spaces\par}
+{\pard \ql \f0 \sa180 \li0 \fi0 \outlinelevel1 \b \fs32 Tabs and spaces\par}
 {\pard \ql \f0 \sa180 \li360 \fi-360 \bullet \tx360\tab this is a list item indented with tabs\par}
 {\pard \ql \f0 \sa180 \li360 \fi-360 \bullet \tx360\tab this is a list item indented with spaces\par}
 {\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 \li0 \fi0 \outlinelevel1 \b \fs32 Fancy list markers\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}
@@ -149,10 +149,10 @@
 {\pard \ql \f0 \sa0 \li360 \fi-360 2.\tx360\tab More.\par}
 {\pard \ql \f0 \sa0 \li720 \fi-360 a.\tx360\tab Nested.\sa180\sa180\par}
 {\pard \ql \f0 \sa180 \li0 \fi0 Should not be a list item:\par}
-{\pard \ql \f0 \sa180 \li0 \fi0 M.A.\u160?2007\par}
+{\pard \ql \f0 \sa180 \li0 \fi0 M.A.\u160 ?2007\par}
 {\pard \ql \f0 \sa180 \li0 \fi0 B. Williams\par}
 {\pard \qc \f0 \sa180 \li0 \fi0 \emdash\emdash\emdash\emdash\emdash\par}
-{\pard \ql \f0 \sa180 \li0 \fi0 \b \fs36 Definition Lists\par}
+{\pard \ql \f0 \sa180 \li0 \fi0 \outlinelevel0 \b \fs36 Definition Lists\par}
 {\pard \ql \f0 \sa180 \li0 \fi0 Tight using spaces:\par}
 {\pard \ql \f0 \sa0 \li0 \fi0 apple\par}
 {\pard \ql \f0 \sa0 \li360 \fi0 red fruit\par}
@@ -204,7 +204,7 @@
 {\pard \ql \f0 \sa180 \li360 \fi0 orange fruit\par}
 {\pard \ql \f0 \sa0 \li720 \fi-360 1.\tx360\tab sublist\par}
 {\pard \ql \f0 \sa0 \li720 \fi-360 2.\tx360\tab sublist\sa180\sa180\par}
-{\pard \ql \f0 \sa180 \li0 \fi0 \b \fs36 HTML Blocks\par}
+{\pard \ql \f0 \sa180 \li0 \fi0 \outlinelevel0 \b \fs36 HTML Blocks\par}
 {\pard \ql \f0 \sa180 \li0 \fi0 Simple block on one line:\par}
 {\pard \ql \f0 \sa0 \li0 \fi0 foo\par}
 {\pard \ql \f0 \sa180 \li0 \fi0 And nested without indentation:\par}
@@ -232,7 +232,7 @@
 {\pard \ql \f0 \sa180 \li0 \fi0 \f1 <hr />\par}
 {\pard \ql \f0 \sa180 \li0 \fi0 Hr\u8217's:\par}
 {\pard \qc \f0 \sa180 \li0 \fi0 \emdash\emdash\emdash\emdash\emdash\par}
-{\pard \ql \f0 \sa180 \li0 \fi0 \b \fs36 Inline Markup\par}
+{\pard \ql \f0 \sa180 \li0 \fi0 \outlinelevel0 \b \fs36 Inline Markup\par}
 {\pard \ql \f0 \sa180 \li0 \fi0 This is {\i emphasized}, and so {\i is this}.\par}
 {\pard \ql \f0 \sa180 \li0 \fi0 This is {\b strong}, and so {\b is this}.\par}
 {\pard \ql \f0 \sa180 \li0 \fi0 An {\i {\field{\*\fldinst{HYPERLINK "/url"}}{\fldrslt{\ul
@@ -245,11 +245,11 @@
 {\pard \ql \f0 \sa180 \li0 \fi0 So is {\b {\i this}} word.\par}
 {\pard \ql \f0 \sa180 \li0 \fi0 This is code: {\f1 >}, {\f1 $}, {\f1 \\}, {\f1 \\$}, {\f1 <html>}.\par}
 {\pard \ql \f0 \sa180 \li0 \fi0 {\strike This is {\i strikeout}.}\par}
-{\pard \ql \f0 \sa180 \li0 \fi0 Superscripts: a{\super bc}d a{\super {\i hello}} a{\super hello\u160?there}.\par}
-{\pard \ql \f0 \sa180 \li0 \fi0 Subscripts: H{\sub 2}O, H{\sub 23}O, H{\sub many\u160?of\u160?them}O.\par}
+{\pard \ql \f0 \sa180 \li0 \fi0 Superscripts: a{\super bc}d a{\super {\i hello}} a{\super hello\u160 ?there}.\par}
+{\pard \ql \f0 \sa180 \li0 \fi0 Subscripts: H{\sub 2}O, H{\sub 23}O, H{\sub many\u160 ?of\u160 ?them}O.\par}
 {\pard \ql \f0 \sa180 \li0 \fi0 These should not be superscripts or subscripts, because of the unescaped spaces: a^b c^d, a~b c~d.\par}
 {\pard \qc \f0 \sa180 \li0 \fi0 \emdash\emdash\emdash\emdash\emdash\par}
-{\pard \ql \f0 \sa180 \li0 \fi0 \b \fs36 Smart quotes, ellipses, dashes\par}
+{\pard \ql \f0 \sa180 \li0 \fi0 \outlinelevel0 \b \fs36 Smart quotes, ellipses, dashes\par}
 {\pard \ql \f0 \sa180 \li0 \fi0 \u8220"Hello,\u8221" said the spider. \u8220"\u8216'Shelob\u8217' is my name.\u8221"\par}
 {\pard \ql \f0 \sa180 \li0 \fi0 \u8216'A\u8217', \u8216'B\u8217', and \u8216'C\u8217' are letters.\par}
 {\pard \ql \f0 \sa180 \li0 \fi0 \u8216'Oak,\u8217' \u8216'elm,\u8217' and \u8216'beech\u8217' are names of trees. So is \u8216'pine.\u8217'\par}
@@ -260,17 +260,17 @@
 \u8221".\par}
 {\pard \ql \f0 \sa180 \li0 \fi0 Some dashes: one\u8212-two \u8212- three\u8212-four \u8212- five.\par}
 {\pard \ql \f0 \sa180 \li0 \fi0 Dashes between numbers: 5\u8211-7, 255\u8211-66, 1987\u8211-1999.\par}
-{\pard \ql \f0 \sa180 \li0 \fi0 Ellipses\u8230?and\u8230?and\u8230?.\par}
+{\pard \ql \f0 \sa180 \li0 \fi0 Ellipses\u8230 ?and\u8230 ?and\u8230 ?.\par}
 {\pard \qc \f0 \sa180 \li0 \fi0 \emdash\emdash\emdash\emdash\emdash\par}
-{\pard \ql \f0 \sa180 \li0 \fi0 \b \fs36 LaTeX\par}
+{\pard \ql \f0 \sa180 \li0 \fi0 \outlinelevel0 \b \fs36 LaTeX\par}
 {\pard \ql \f0 \sa0 \li360 \fi-360 \bullet \tx360\tab \par}
-{\pard \ql \f0 \sa0 \li360 \fi-360 \bullet \tx360\tab 2\u8197?+\u8197?2\u8196?=\u8196?4\par}
-{\pard \ql \f0 \sa0 \li360 \fi-360 \bullet \tx360\tab {\i x}\u8196?\u8712?\u8196?{\i y}\par}
-{\pard \ql \f0 \sa0 \li360 \fi-360 \bullet \tx360\tab {\i \u945?}\u8197?\u8743?\u8197?{\i \u969?}\par}
+{\pard \ql \f0 \sa0 \li360 \fi-360 \bullet \tx360\tab 2\u8197 ?+\u8197 ?2\u8196 ?=\u8196 ?4\par}
+{\pard \ql \f0 \sa0 \li360 \fi-360 \bullet \tx360\tab {\i x}\u8196 ?\u8712 ?\u8196 ?{\i y}\par}
+{\pard \ql \f0 \sa0 \li360 \fi-360 \bullet \tx360\tab {\i \u945 ?}\u8197 ?\u8743 ?\u8197 ?{\i \u969 ?}\par}
 {\pard \ql \f0 \sa0 \li360 \fi-360 \bullet \tx360\tab 223\par}
 {\pard \ql \f0 \sa0 \li360 \fi-360 \bullet \tx360\tab {\i p}-Tree\par}
 {\pard \ql \f0 \sa0 \li360 \fi-360 \bullet \tx360\tab Here\u8217's some display math: $$\\frac\{d\}\{dx\}f(x)=\\lim_\{h\\to 0\}\\frac\{f(x+h)-f(x)\}\{h\}$$\par}
-{\pard \ql \f0 \sa0 \li360 \fi-360 \bullet \tx360\tab Here\u8217's one that has a line break in it: {\i \u945?}\u8197?+\u8197?{\i \u969?}\u8197?\u215?\u8197?{\i x}{\super 2}.\sa180\par}
+{\pard \ql \f0 \sa0 \li360 \fi-360 \bullet \tx360\tab Here\u8217's one that has a line break in it: {\i \u945 ?}\u8197 ?+\u8197 ?{\i \u969 ?}\u8197 ?\u215 ?\u8197 ?{\i x}{\super 2}.\sa180\par}
 {\pard \ql \f0 \sa180 \li0 \fi0 These shouldn\u8217't be math:\par}
 {\pard \ql \f0 \sa0 \li360 \fi-360 \bullet \tx360\tab To get the famous equation, write {\f1 $e = mc^2$}.\par}
 {\pard \ql \f0 \sa0 \li360 \fi-360 \bullet \tx360\tab $22,000 is a {\i lot} of money. So is $34,000. (It worked if \u8220"lot\u8221" is emphasized.)\par}
@@ -278,13 +278,13 @@
 {\pard \ql \f0 \sa0 \li360 \fi-360 \bullet \tx360\tab Escaped {\f1 $}: $73 {\i this should be emphasized} 23$.\sa180\par}
 {\pard \ql \f0 \sa180 \li0 \fi0 Here\u8217's a LaTeX table:\par}
 {\pard \qc \f0 \sa180 \li0 \fi0 \emdash\emdash\emdash\emdash\emdash\par}
-{\pard \ql \f0 \sa180 \li0 \fi0 \b \fs36 Special Characters\par}
+{\pard \ql \f0 \sa180 \li0 \fi0 \outlinelevel0 \b \fs36 Special Characters\par}
 {\pard \ql \f0 \sa180 \li0 \fi0 Here is some unicode:\par}
-{\pard \ql \f0 \sa0 \li360 \fi-360 \bullet \tx360\tab I hat: \u206?\par}
-{\pard \ql \f0 \sa0 \li360 \fi-360 \bullet \tx360\tab o umlaut: \u246?\par}
-{\pard \ql \f0 \sa0 \li360 \fi-360 \bullet \tx360\tab section: \u167?\par}
-{\pard \ql \f0 \sa0 \li360 \fi-360 \bullet \tx360\tab set membership: \u8712?\par}
-{\pard \ql \f0 \sa0 \li360 \fi-360 \bullet \tx360\tab copyright: \u169?\sa180\par}
+{\pard \ql \f0 \sa0 \li360 \fi-360 \bullet \tx360\tab I hat: \u206 ?\par}
+{\pard \ql \f0 \sa0 \li360 \fi-360 \bullet \tx360\tab o umlaut: \u246 ?\par}
+{\pard \ql \f0 \sa0 \li360 \fi-360 \bullet \tx360\tab section: \u167 ?\par}
+{\pard \ql \f0 \sa0 \li360 \fi-360 \bullet \tx360\tab set membership: \u8712 ?\par}
+{\pard \ql \f0 \sa0 \li360 \fi-360 \bullet \tx360\tab copyright: \u169 ?\sa180\par}
 {\pard \ql \f0 \sa180 \li0 \fi0 AT&T has an ampersand in their name.\par}
 {\pard \ql \f0 \sa180 \li0 \fi0 AT&T is another way to write it.\par}
 {\pard \ql \f0 \sa180 \li0 \fi0 This & that.\par}
@@ -307,8 +307,8 @@
 {\pard \ql \f0 \sa180 \li0 \fi0 Plus: +\par}
 {\pard \ql \f0 \sa180 \li0 \fi0 Minus: -\par}
 {\pard \qc \f0 \sa180 \li0 \fi0 \emdash\emdash\emdash\emdash\emdash\par}
-{\pard \ql \f0 \sa180 \li0 \fi0 \b \fs36 Links\par}
-{\pard \ql \f0 \sa180 \li0 \fi0 \b \fs32 Explicit\par}
+{\pard \ql \f0 \sa180 \li0 \fi0 \outlinelevel0 \b \fs36 Links\par}
+{\pard \ql \f0 \sa180 \li0 \fi0 \outlinelevel1 \b \fs32 Explicit\par}
 {\pard \ql \f0 \sa180 \li0 \fi0 Just a {\field{\*\fldinst{HYPERLINK "/url/"}}{\fldrslt{\ul
 URL
 }}}
@@ -345,7 +345,7 @@
 Empty
 }}}
 .\par}
-{\pard \ql \f0 \sa180 \li0 \fi0 \b \fs32 Reference\par}
+{\pard \ql \f0 \sa180 \li0 \fi0 \outlinelevel1 \b \fs32 Reference\par}
 {\pard \ql \f0 \sa180 \li0 \fi0 Foo {\field{\*\fldinst{HYPERLINK "/url/"}}{\fldrslt{\ul
 bar
 }}}
@@ -380,7 +380,7 @@
 biz
 }}}
 .\par}
-{\pard \ql \f0 \sa180 \li0 \fi0 \b \fs32 With ampersands\par}
+{\pard \ql \f0 \sa180 \li0 \fi0 \outlinelevel1 \b \fs32 With ampersands\par}
 {\pard \ql \f0 \sa180 \li0 \fi0 Here\u8217's a {\field{\*\fldinst{HYPERLINK "http://example.com/?foo=1&bar=2"}}{\fldrslt{\ul
 link with an ampersand in the URL
 }}}
@@ -397,7 +397,7 @@
 inline link in pointy braces
 }}}
 .\par}
-{\pard \ql \f0 \sa180 \li0 \fi0 \b \fs32 Autolinks\par}
+{\pard \ql \f0 \sa180 \li0 \fi0 \outlinelevel1 \b \fs32 Autolinks\par}
 {\pard \ql \f0 \sa180 \li0 \fi0 With an ampersand: {\field{\*\fldinst{HYPERLINK "http://example.com/?foo=1&bar=2"}}{\fldrslt{\ul
 http://example.com/?foo=1&bar=2
 }}}
@@ -419,12 +419,13 @@
 {\pard \ql \f0 \sa180 \li0 \fi0 Auto-links should not occur here: {\f1 <http://example.com/>}\par}
 {\pard \ql \f0 \sa180 \li0 \fi0 \f1 or here: <http://example.com/>\par}
 {\pard \qc \f0 \sa180 \li0 \fi0 \emdash\emdash\emdash\emdash\emdash\par}
-{\pard \ql \f0 \sa180 \li0 \fi0 \b \fs36 Images\par}
+{\pard \ql \f0 \sa180 \li0 \fi0 \outlinelevel0 \b \fs36 Images\par}
 {\pard \ql \f0 \sa180 \li0 \fi0 From \u8220"Voyage dans la Lune\u8221" by Georges Melies (1902):\par}
-{\pard \ql \f0 \sa180 \li0 \fi0 {\pict\jpegblip\picw250\pich250\picwgoal3000\pichgoal3000\bin ffd8ffe000104a46494600010101007800780000ffdb00430006040506050406060506070706080a100a0a09090a140e0f0c1017141818171416161a1d251f1a1b231c1616202c20232627292a29191f2d302d283025282928ffdb0043010707070a080a130a0a13281a161a2828282828282828282828282828282828282828282828282828282828282828282828282828282828282828282828282828ffc000110800fa00fa03011100021101031101ffc4001c0000000701010000000000000000000000010203040506070008ffc4003e100002010303020404040502050500030001020300041105122106311322415107617181143291a1234252b1c115f016336272d1082443e1f1265382ffc40017010101010100000000000000000000000000010204ffc4001b11010101010003010000000000000000000001110212213141ffda000c03010002110311003f00dadd18a10a704f6a95ccc57e37750782b0d8d9ea0cd32e7c5446e07e9f4ad723119a7b89e61e348f260719278aad613cbb640002938c76a182b264fc87bd13009c0c019c76e3d68a072e1cf6f4cd502d330c28269a61bb39c923923d4fad44c08dccb95cfd28b8280769ee08a263891e1808739e4f1d8d149392172cc714050dbb9fde8960ed8c60b79b1ed44103b05c331dbdb1dc5026ac1946d20ff8140aa631c773ec738a0346a003bf93e9cf02801895e7b9a01886796c923bd0090a06393c76a0142003ce3d86680d8dd9392303f5341ccc1b3cf7a2c812c37e4923d381429757013209fa511c18146c9247a0f6a007900c0c671c6280854e086c673eb45c27c038fd68aedff2fda836ef881f136f25d5e6b7d1262964aa02b03f98fbf153131935edcc97576f35c33349212cc4f39f7ab26186dfce5b200f73451f7600dcb8cf27e7400c0b291914046c9e0718fde81371b8e7273f4ef4007691919240e714097f31f376e7b5008caee27807b0f5a02c8e1b3c6d27d33cd0201d839523144d1a149ae084b78da47638211771fd050d582c3a0faab5119b6d12f8ab1c06788a0fd4e2ac356fd1fe08754ddccaba849696309e598c9e2103fed1dcfdeadc44fea5ff00a7f956366d375e492403ca935bedcf1eea4ff6ac68a55efc1beb3b552574f8e7009ff933a927ec715bc82b3a8f4d6bba5ca1352d22fe061cf9a0383f71dea5119cc6c0baed3eaac0f1fad40897dcc3d81f7a052366c1007df3400f21edefc5008c28f30c9c5170ee4fc37830086395250a7c66770c18e78da31c0c63de8609b41f7c515c5172a30c3b76344a3e377cb2339cf7a242aea89808cce368272b8c1a2e107c672a49f5c1a181c9c7ae7da8a2119e7b1f5068099ffa68258a132062d8f9e0f34059502b61bf2824e681bb297ced2a71efda80f19c47b9c77fdbe74057c13e539cf3c1a0eeeb9c73f33405ddb4f18249c1e28062b79ae242902024465b9214614649e7bd0362a7249eddc513456e5720f38f5a1a98e96e95d6baa6ebc2d1ad1e65521649bb469f563534d6d7d31f04347d2a2fc5f535db6a0e83718906c887cbbe5a9a8bef44dce9f731ca9a2e89169d6d6f2184b1455dc07b11dcfeb4d16f119c649a681285b03d3e5500f87820ff006a0e098191de80ac9b8904647b55d11da9681a56a31f87a869f6970b8ffe4883629a289aefc16e92d441682da5b098f21ed9f033f353914d19b751fc08d66cc16d12fe2bf45ec92ff0df1fdbfb559ec667aff4eeb1a04db359d3ae6d40eccebe53f46ec7f5ab82263da7dcf3eb5174e5181076918c7de869503232491ee4515c1803824f03b51287f30e0e7d803449494832c157278a2e8c71fcb9f9d144639236824d01e142efb1768cfb9c7ef40512a818de78ff00a682518e7cc30ab9e00a02cce9953247bd41e467191ed9a04205ee99da4e4e3d283a524b0427b5026c18a8e082067db8341ce0e39ed409b6502907391edda80f2dfdc496f0c124ac6184b144cf0a4e338fd2894f7a7342d4ba9b568f4fd261f12571966270a8bfd47d8511bae85f02b47b7fc34bac5d5c5dc88a0c90ab6c8d9bedce3ef4d1ad691a6dae976a96d616d15b409f9638d70054a1dbc68ea51d4329f4619a8022b78e04548515117b05000a035c5c4702a995c26e3819f534047bcb68a458cce866719540724d02e41c0f7a012a40f6141cbc8e7bd01719e38e6838af1c0a04ca8206d3cd037bdb082fad9e0bd8a39e0718649141047d0d5d18f759fc0cd3af164b8e9999acae4e4f81236e898f7c0f55fed574615aee83a96817ef67abda3db4ebdb7f66f983d88a061bb8db9e3d45165076db83c1f950a53780d8247c80a2398f182724f1c7ad080c608cfa7a51a0062adc7afbd0130173bb9c5070f071cb37e82826106e8f615e01c9e680d6b35bc534be3c1e3831b2aa962bb188f2b71df1de819ae4b1048c7f57bd01a58268e332642ae0704f7cf6207af6a01b99e17b7b6416e227407c494139909ed9f4c0a04a4e501e0f1eb40d263e53dce7fa682c9d0bd13abf58dd6db18bc2b157c4975270ab8ef8f563f21447a73a03a1f4de8eb031582b497328066b97fcd21ff038edfde88b7e32703bd64188e7e6283864b73400cd804b67ca3268317eacea6d56ff005233592f8b6303f953fa4af7c2fa93417fe98b763e0ea171297bab98558068f695ce0e08fdbd281e5c6a57ba5e9d14d716ef7774f2ec112601da4f27ec2827ada74bab559a20e148fcae36b0f91140283729c77a0e0a7777a01dac68395719e39a029607cb901b19c501480ab9279f4a086ea8d0b48d76c0586b7143224a76c61ce1831fe93e86b43cd1f12fe19ea7d2533dcdbeebcd20b612651e68f9ece3fcf6fa5067cbcf20ff009a051724905411e94032799060723da8406d6c67e7ea68d0e1770fe5cfb5026c37039ef9a02eca098c91e6e01e71c500b1d8a49c12786cf6a06a4e256008e3d050119958007920e2801154e32fb4120927b014017eb1c523ac5209a356215c291b87be28957ef853f0d66eaa99352d515e1d190f947669ce7b0ffa7e74a8f4be996569a5d9c56b6704705b46bb5238d42851f2ac875712bc70b3c30f892019540704d01ad2669a0491936330c95ce7140b2e4939a03638c7e8680ae485e33bbe540d60d3ada162c90a02c7270a39340a4f28b68da4645007a8f6a069a746f73235ddcefc391e12b2e1916824948742c99382473c73404791c617695279dc0640f9502c578c9efeb4095cb4cb0830ba21cf999c6401f4f5a05061d430c8079a02e03b3004311c7d281b5e3cd676c65489ee594e4aafe6c7ae07a9a0a075bbea3a8ea96f047d3935ebc404f04ad29411e08e011d98fed416fd212ee5b05b4d5ad6300c615807f1171eaa49eff5ad418c7c55f8466dd66d57a521f20cbcd66a7247a9283dbe5418a63862479877cf1f6c5008e400bdf1ce684016fe53dfbd1a73794600e08ce3d6800377c8c7d6800a9cf75fd4503d91492460f7ee3d28247a7b459f5fd592d22711c206f9e563858a31f99cfd050583518ba75247b1d134f9aed21396d4669769931dc01c003f7a329c4d17458ac5b55d36c12e040a3f1da75c1cb04ede2447f7f6a94567ad7a66db4fbbb29ba7d65b8b4bd8ccd09c8231eaa07b8ab04a7c2cf87b3f53ea8d77abc72c1a5dabe2452bb5a561fc83e5ee7e541e988218ed2dd22b7855228d76a46a00000ec00a510bd4dd511f4fe84da95cc31f880022da4902b1e7d3e99ac86fd03d631f565b4ee6d4dbbc649009cab2e48c83f514165b8b94b6895c44f279c280839e78ce28178ae6de46748a789e453865570483ec6812d42e85a421fc37918b00a883924d024c6e99b7a2a966c0009e17dc9f9fed40f81c77e28139218e4ff9815b9cf23340a01c907b9140201038ed402fcafd28386464e4fd33c50272bc60032609cf00fbd024f722dc66f24822ddf972f8feff00e280f69b24844919cac9ce7de83a447f30ded823007b50459d6ecacb528349b979127651b1dc795f1f3f7a0990148054823dc5015d491c0a0c3be337c2ff00c489b5ee9c87172016b9b541c49ff5a8f7f71eb560c1fc43e0a47e1aa94277310431f91fa551c1727f29ed409b641c86e31839a3454805739c1f6a026f1fd740f64665fc8c31cfde82db79bb40e9e8f49b62eb7d7e8b717ec832c91ff247fa1dc7df2281bcc9369d671493c422b7911654c1215f92bb8827bf068624ba635392df5eb4b9924558ee5bc19b71cee43c6dc7cf34c657be8db0b0b9d0f51d2afe668934dbf9628ddb8c2b8c0073f3a80da37546a7d25174fd95dc125c69f7313ee5655dfc313bd483cf07b1f6a68d5b48d5ec758b612e9d7293211c8fe653f35ee2a084eb9e8bb1eafb3582fe496278f3e1c919fcb9f97ad03ee8dd017a6741b6d3229dae161057c5750a48249ec3eb4139238568f6a9e7b103b5037934cb3793c610a2cd9277a8da73f5140ee38f6280c4b11c65b934023006d50050030e4647de80c846de3b500fcf9fbd0197273ed4007b91400e580c8e45074a82400e72682b36fd2162b7f25ddc09af2766ceeb872db79cf00f6a0b3229550140e07007a50092db860673de818df473c862686dad6470d9cce3b7b63e740fa1de6252ebb5bd81cd00bee2d800d003a6464004763ce683ce9f1cbe1f1d3a67ea1d1a30b68edffba814708c7f9c63d0fafceaca31e6dc71e1f07daa82608c83819f7a1a11ce149238fd68d0a579ec682cfd27a7c3a86bd10bc38b3b756b8b93c1fe1a8c91f7381f7a034f752ea5aa5c5eb292f732128037619c018f6ec282e5a2cb047abda74d5ce9b6da80f136de4a496219b3e48c92000323ea73467519d3da5bb757dbda410ac90c77c23058f99007ee7ec31416882ee47d23acb5185caf8bab4691b1efe57fff0038a9457ee75a82f6e7429350466b482f2742c0f74241c80c38c64541a9cfa1e89ac0177d33ab3d8de28f2b5bca429f91140e2c7a9b5ae9fb85b6ea9b46b9b3c796fe040768f76ec0fafb1f9505df4ebdb3d4edd6e74db98ee216fe68ce47d280648f75e2485a44da385ddc13f4a025ddbdbea16a633286566ce55f9c8f6c502ad750db2c514f30dec428247e6340bbf04100b73402afb943ed2b9e30683836defe9403bc1e06734020e06280cafe8683a375941d841c77c1a0151b467b50159f00e4127e5402872371040c5046eb5aadbe9b1c02e2f6dad25b89047099c677b7b0140fe3f1010afc803f3018e68160c3041ee2823f5dba92d34db89a1d9e2843b03b6d05bd013560c1748d57aa2797c6b35bab78e6959dc47231580ff336dcfb03c1a58364b5bbb7d7fa7b7427f1f673830c8664285bd1815238fad20f2c7c41e979ba43aa2e2c1cb1b663bede438f3a13c7dc76fb5515e9065b851f7a02950002a09c51a1b83cf14176e90d3645e9ad7752752aac23b3439c066665c827e944d29a6410aea725c4567135bd840d3c88a723728c29c9efe6c50d3ee9545b0bf8ef2e6e3c2fc2c6f72f2920e5f19039ee4938a9a875d03278377acf52ddf867f036ef71923932bfe51fbd3475cdc369df0db4fb389d4ea37970fa9cc0b00511795ce7d4f181eb4cd2451755fc45ac16d637381b14ca36b641dfce723e4053170d6cb52bbb362f6d3cb19241f2b9029862f09f143549ba7e7d2eef6caf2797c66ee17fdfd69862d1a069da7dfdac579d17adcda5ea9e1a992376c4723e39e3b024fd7e94c458ac3e25dee8d31d3bae74e7b79002bf8b8549471db38f5f4ed4c165e943a06a328d4ba605b4b22a1523c420c64fbaf38a82d36f0ce7cf7463790729b53017e940e0b0ceceed8ce0500e1b70daa08f5c9ed41d271cd0132476e7d7ff00aa069797d2411168ed9a41fcc858211f73c5075acb25ca6fb82aa31e58a36c81f561dcd033d42169e158ac64b98151b3981c2966cf639f4a064c7a8ac55e4865b7d493701e1c8e52403ea3cbfda827e390ca3f2c914aa81991bd281cdacc2747215c60e0ee5c67e940cb51b0b2bcbd824bfb08ee1a252d1caea1821cfa67b1fa504982b2283ce08f518a08abb82f6dd0369a5662081e14ce40c7ae1b04fda82275cb0bfd4f4536f7114589a5412461f3e4ce4e0e060f63f6ab2893d3b4b5b5b78e22ed22aae3cc3cc7e64fad3449a22a461500007602a0cd7e3b74c26b5d2ad79147baf34eccca40e4a7f30ff3f6aba3cd0543267eb5427b86f1f4c76ef45d0eca1ad5ef224d13e1cf4fd9b22192fa67bc955f8c8c617fba9fb510d7a6ed3fd43a735e5b54964be658c048fb6cdd9e7eb8a186bac97d174e6d22e23437b7ac26b95e77c68bf950fa7279e2b22dba45b59e97a669fa4ea36aeff89cea9a90451fc355ff0096ad9f4ce3f41570675d4fa8c77da8de5cde5be26bc653171ca47dc1f6c9fed5562b97f70276808da7c24f0c1c63804e33fa8a2928c0e0383c8f7ed41d92a41393f4a2548595c2c37493db4cd04e8a08f139566edfef3445b6e7aeaf65d2df48ea2b11776ae02a93e564c772adef409f4ee8ba9a21d73a36fa579ad9f325afe599171ed9c30a960d5ba0fe2843abb47a6f510fc26a4c36890f9558fcc6783506a1147b510024e30339ce680d2c6ae9861eb9a009178a0205443b989e39cd01d8075e3047ce80563057ca381ed4011c4531e503d85013c91b804a21279c903341131cda8c3abdc8650f6d20c4321232adec3dc504bab2c113c9293bb1963df3408dd4b75e1efb2856463dbc43b4631fad047e9177ad4fe32ea16b1db4b8fe1aa92571f5f5a0916bc8e0895af5c46c17cd8c9ff7da80f6d736f7f6915c59cab35bc837238ed8a072a31c1ef4062870718a06f7702dc5b3c522ee4752ae0fa8230683c75d6ba3b74ef535fe984929149e4278ca9e47edfdab42058003763ed409f88ffd6dfad06b1f12ae612fa0c76e0b471e9916d23f973eb4158d3efeff004a984da5debc1295d8e4018dbf3145d583a2ad96f356bbd7f5d90dc59587f1e79a6392f28fcaa3ee47159444ea3aa5ddfc7acf50dcdc344d7a4dbc317f52641200f6000fdeb41b5ef51d8eab672ffa9e971c97c11638268e431a46000012a3b9a351567db823b11f3ef40948e428048207a8340ab48ae83cb83ee0f3428a982719edf3e68c9cc97d3fe15ad8c9be138f2bf38e7b8f6ef40f7a5f55bdd3f56b46d3649127f1405f08e7249c76f5fa50689d48ba5f545cdcbdb462cba9206411b2b055bb07d4fb1c73528d4fa8f52d62cf47b6b8d2e65fc458c49f8a818795c151939f977a823ba0fe253750eb7fe937b04293f9f6c90be41dbdc7ff006283473c1efc1a06f69776d73bbf0f2aca32572bc80470450284a46dfca19f819f5a04e799614def26c0bdce09cfd85045dc75769d12dc3c3e2491db0dd3c85195235f7c91cfd066ae0cdba9be31f4ec61a386c1ef9d4ee473e45cfb1cf34c101d3ff1ac9d481d46c628ed24751881880833f988e7b0fa5328dfed2f2def2ce2b9b79925b791772ca87208f7a60182ee2b95cc0c48f53823fbd40ac658b30f4f4a086d4ee1d75bb6b78f4e965596366fc5211b23238008fde81f43692da5bc30d97831a0397dc09e3d714087506bf61a2c4cd77324726d2caaec141f9fd2ae0c435bf8c57173ad7876f7a2daca10489121244cdf319ce3dbf5a834fe81f881a6f57bcb6ba7c53c72c11873e28cee1db391dbef4199ff00ea4348116a5a66a8a8a04aad04847a90723f6ad7d18c312ddc02a3815423ba0f63fa541687bd9efe1b533b3c9e0a78473e899e318a09bd0ba6eef543e3b2bd8e9b10064bd9e4da001dc81401aeeb29a984d0ba7d5e1d06d4e6594f06523bc8e7f5c0ac8af752dfc17d7090d9218ec6d9447129ee71fcc4fb9cd6842ab10dc0014f3e5a2c1704b671dfdc734525226dc939e283a362c7f940344a380393df144733e2276e38f5efcd01b4bbbfc3dda4a9298a44395902e4a9c70682660d4265d62de40b1bdc1545054f95c8fe627df141af7c3af8808f3dd68dd5d2a45765884b8908d8c3b6c27b7a77a945d7a5fa474bd2ba8e4d5748b28624955d5d8b13b79ee9e983d8d40a753758c7a46b96f6114725dc92279a2810b3a64f94900763cfafa503fd3b59b79ed84da34713c0cd890f0a158fa1f981de826e1b548959fc4dc5cee24b6467e59ed4101ff19e9f676baa5d6a72c50adb4ad1ac790ccc076200f7ad41e7df881d79a87576a5f87b0f161d381db1c2a36e7e6d8ff3416bf87ff082c6f208ef7a82f22b9761bd6d619785f6dc477fa53705ab57f83bd297ceb1e9caf67708db9c4526723e849e3e94f212dd25d117fd29a8c09a76b534fa39cf8b6b71ced38e36fb73417f52e64548e34007e673e9f21ef590a1c918c90718dc281a69b68f67118d9da5058b798f6fa7fe280daadd1b2d36eae70710c4d263df0a4d583cc7a668fd4bf11b5837d7c93dcd9a3146959822a0e781f4cfa55161e9dd7fa67a4f55b9e9aea3e9f81fc09ca0ba118998fcdb2338c7b528d39f4cd2ba76e2d357d292df4eb391809963420ce1b1b576fa1e7359119f1eb4e17dd033ca172d6b2a4df303383fdeb5c8f2eef3bce4e0e335684cb0c9f354160d36f64b0baf16072b91b5f03391f43c51aab23a5debe91c4fad4d73689e6fc3a290573ff4f03e59f4a3280d67581ce916567f84b58ce0a1fccec3d58fa9a084de08c90464e4d1a8e419059b201f4a05630a176918efc50176293872c17bf14042aa0125b03db14046c60b60123fde6827fa0c68edd5365ff11346ba6292ee64194240c807e59a32b7fc51bfe8bd5ed5db424860beb62b89218422ce09c11c01dbbd0660ae110bf1bf2154838dbebfefeb41a8f4cdac7f117458f4d9ecd2df53b4cf81a822808c47255c0f7c8e7fb54a2ec2cfabba3b4b4b8d3af12eedad40926b0f070a13f9b633649f7a82eba6ea4357d321d4ecad512daf20df26e016507fa4fbfaf3e98f9d067dd2bd2faac9aa4d72d72d1e9510ca46a7631c7a320e18f1dfd7bd059afb7da816d23de4ba5de211346a1e4785f190548e4648c63b64e6b43ce9d5baafe3b539c5b452dbda46c638a167cb281c73ee4ff9340e3a3fa5f5aea4ba58f4bb57dbfcf2b02a8bf7f7a0de3a5fa0b50d2a2d92eb3e048c0a97c867dbedcf6a944e5cf4f6b76d1b3d8ea42795066266c87c81c65b9cfaf15048e83af3cd64abac08edaf01546c38dae4e0657ee6826e5b892de3702292e2545ddb55700fd0fbfca81c4b3bc718716eef9eeaa402280d14ab3c0b2c65c06fe571823ed40df56b217fa6dd5ab9216689a33f2c8c558307e83b8d77a37aaa7d22f2512c28768800c9954671b3d33ebef568d0ef7a7749eb0b5bbbb162d657b32b46d2e1564c8ed9c5644d1b0b9bbd261d2a440af6cb0e2e5b1e7dbc1238e0f7a0375b696daa7496a3a4dac8a92cf078685b271db04d391e40d5ec4586a1716de2a49e0c8c85d3b120f715ba1899173ff305413070abd89cfe9f5a2d3ee9c8639fa874eb6b804c52dc46b20c9f302c3bd11e84d47e1af4d5dc6521d3e3b662c19a58721ff5a9a321f89bd27a374b456d158dccd34d333332c9b4b2afbe47a7cb1f7aa33d2bc0d8c0f1c8f6a2c14b6d501b39cf63450897380c319e3de8065031c038f7ed40d8faf1ce41e4d004876a8dc3cc7e743025c956c818028c904579e7f0e15695c9c0541924f6c00283d0bf07f42d6b48820b8d62d20b2b58d656404959e52f83c8ff00fcfafbd4a35bb06f12391a48dd55cee2b2f3818ed8f6a8158a159890f02242079147623e631c502b0db436d1ecb7458d4738038fb0a087d6eeb508f48bb7d32d95750752b6c26c905b3ddb6f61eb574794f5cb6b9d0fa9678b512b25d24bbe52b8c1638278fbd582c57ff12afaed45b5bc0d0d8a8c08a2731ee3eec5793f40450466a1d59af446293c186cd53ca0c36eab93dc649e49fbd048e89f1675ed35e301e293919dcbf9867b37cbe94a35fe94ea4d33aba6824306dc48015750d86c6e247b0cf63591a40b8dc23fc30f14138dcac3000f9d03687547f12e8dd5af816b13148dddbcd29039c0f6f6f7a0eb5d62caf5636825db70c9bc4328f0dc0271c8a090627d3073ce681acf6505ccf14d35bc2f2c2731bb28254fb8a075144a83ca806792400334049ee6281e2496408656d880ff0031f61fa50446bd76058ea1b9e21025a3bb48afe71df9c7b71de9c8f196a0de23ca7b827d4f7add117e0cbfd4b5059392369663ff004e71c51aa97e8f555eadd258f2bf8a889cff00dc28cbd0bf123a926e96d163bdb74490bca2321c678209ff001591e71eafd7a7d7ef45cde2c20aae144638033fb9ad2e1b5e69d058da431ccf21d4a5c3b4631b62523807feaf5c7a50222f2d648c25f5aeec8c2cd19dae3d3e87e944d3eb7e90d425b49ef2292de38224f1505c3f8724a9eeaa7bd0d57a60406059436306868a7803839c7ad1a158039c13f4a33a716767f8cb9b6b55e1ae2458813e9938cd07a9f42d0b4de99b4b7d1f41b58ff19b03c93ba06607fa8b1f5f619a5b8266d74a65d42da6ba90cce996dcdc8c9fff006a5a2c2635083b05ef83eb5028076341db4b1ed9f7a04651fc41db18ed419d75b744dbea335fcb0db0335f2057901c05da73c8f9d5d18a75174a3f4c47335e35da4ce418a489374254f707d463d33565d1529b569a489a17944b06ec8057d71dcd037b4b6b8bfba31584124b27e62a8a4f1ea68357f83da7ea5a76bfe0912453ccabb49194653cb60f6ce3dfda983d196cd108c2401711f9768e306b2297d73fc6d02773a8b591922693c5004bb9d72542fa2f6efde8314ff867aeeec27500b77bb5670e36ca19b1dff2e7f2fd2837ce8bd5dd348b78b552219022870d9c46e792a4f6c608a0b846c8e03232b29ec41cd0199f1410fd4b24b1e8f712c0a5e4452d851e6c639dbf3238a0afa42ba77475e4ba8470896681da45180b18da76af3c9029c8f26dc1df2b9c606e273e86b743331924f27f4a82c12280e59b008e79f6a2d4d74188ff00e30d203a82ad7519c1ff00b860d11ba7c5e86c9fa3afae6f4091e043e021270b21e01c7dcd6479ab4dd3aeb56be4b7b184cf2b301b57d07bfd2b4bad0fe25e9f6960ba7c7a55ac50cd750335ccaade7723b83b8f6e38a2207a5ba4e7ea3d93780cb616ca53781f99fbff009a0b675a5be9765d43a75a6ad3b25adb4185429b831c70303dfdfd2831eb8954ca48f3827819c71ed406b2b1b9bf9a5fc1c4ce2253238047957dc9345d122b792eee522811a495ce1157b93ed444ff0049f476b1aaf51c761345269d25be269259570c833c6077249e062a68f53e8ef0da69509d4ae225b92a04af232ab16f98cf1f4a5a266d4dbca8af13a329ecca723f51502d14f0cb9f05d1c8ee01c91f6a0393b4edfe63c8a031608859b38f97340d84d04e5846eae50f9829ce3eb400fb24466041f5e3d2823f56d22db57b192d6e61468a41c823ff0035651916bbf04ada7badda5cad6d1b72c09dc33f2a6875d25f0865d06fe2bc6d4c4d3282026cca8cfafcfd29a34cd234a10c768f711a78f1bb392a3001208e3ec69a26a58d640c832091c90706a084ea1d3eeafdadf4f86da3166c0b4b397c18f046140f5ce4d04f4702436e91c28a9122e028ed8a0a9f5a5b6a09a1bc5a135bc72cce048b3c5bc15c638f9d59043fc2db997481aa69dae49e1cb6bb643239211939e467818f97bd305965ebce9a10bc8da9dbaa2679dd9ce3d8530572cfac87566ab05ae9f1490692b9696e1f833738555f96793504df5f25945d2576b7ec16dc46792381c7b7ad5e60f234980e42f6c9c56a82ec3eff00bd4124e49700f1c646e3cd169ce9575f83d52cee324347323f6e3861ff008a23d47d4ba6a75074fdcd8ef317e2e2ff0098bdd4706a60c3f4ae8cd5f44eb8fc3e97248a638cbc73bf90483d463b373e9574685abf42a6b5649fea72bbdeac4a8d3b018cfae31f7a6895b6b29b41d30d8e9f6bbed9213e1b7a994e724fcbb5064bd7835a9752d3af75d8116354778f660788cbd9483dbb0a0cd20b2b8d43528ad2088bdcccf854039cff00e2827a0d34e9da1de896f2182492efc0976f998aa827d3d334113a74aa9a9298628e74570478bc0c7cf1da83724bb8246d3e6416b0384da61b5501c9f5c3704f152c037561a95f5fce61d3ad6db4ab950f34b331dd9f4191db8fdcd406d67a675ab4b6d325d1af248272a43430315ddec7038f6ad4b3f448bf47eb71cb69abddebf21d5e26896203846c30c8603b9c6452d9835901405660376319ac84bf13180779d8bb82827d4fb0a06f777367a75acd7170f1430a9f331200cfceae061a0cf6dac692d7365266191db0578f5edf3a6075a6c9278b3433188a467860d96fbd40fe540471409aa0c1140750001ed8ed4058e15133c983960077edf6a06faade5c5b7822d2d926766cb967da2341dd8f0727d85033d27597d62e2ee3163756915bbf8799d71e2f19dcbf2a092b88dd9a311950a0e5b70ce47fe6ac18af53f5b69da9752dd69da9ca906876e24465d9e69881c6ff005c679c0aa2bfd267a347512c93dbb5d42d90d3c800b68c9ce0ec3cfa528db74ad034db5905ee8be1ac728dc153984f3f980f4fb56453be2de8f647a6aff53796596f0aed46798ec033ce149c0fb0ad71479c9bb9dc3bf3c55a0b95f65a825150b481a407b93c0fda8a29c06671dc93803bd131eafd0af6dffe18d2ee25982a4b04603b7a9c631fad03bbe586381bc5945b96385718c827db3eb5288eb8ba934eb15fc3c535f05427796dcccdec7150637d5bd55d5362b7975aa4d0d919018adec8637807bb60723000e4f7cd58203538aefa8aeb478a7b9beba924547b8774cf8608036a80704639cf1f9855d1a7f4c68b67a03de5e5d59dad8d988c62e1c0f107a1e7fdf7a082ea6d07a6e3e99375a7cb6b3db093c727701e2360f7f53dfb50653d4130d42ee18f48b3f0232a15218936963ebf5fbd06dbf0cfa74855b9d46e04b730c6144691e12307d33ea7de8348ba6b5478a279a004f98c479247b81f5a9438805ac0be2e02e73c9ef8fbd40c2346d43578eefc40da7da1dc8b8eefea4fcb9fef419beabf12a4bcebcb2d2fa7ee0dc58492084b30236bb6467dce383f6a0b87556a67a7f4d95a0bbb5468816f0a69c78b2e072572719ce78357079dfab3af2e7a92c963b88d94abbbf91cedc93edf418aa2c5f0dbe2a6a9a0c90d8de34773a6a8da1186d6403fa48fec682d9adeb7a9b4c9d572dacc9a6c9700456e5ca910e000ecbd8e580352fb1ae7476bd6dd49a325e5a9f3025245fe961dea097523cc0919a032af039a006936c81423104649c703ef40dcce64bc3035a87b6f0c378f9fe7cf2b8fdf340a4b6e25962915d94a67807839f7a043586922b5636ec44c061063f31f6ab079d7fe19b7eb2d4efeef55d5d74f992e9a0fc3a441dcb13927b838c9aa2d4bf042c618e178efee6e18104870172318edf5c1e6945bbe1a748ea7d2315edbea3a99bcb190030c401010e4e783ee0fa56455be3d6b90c1a6268d69e17f1486900ee98ec29ccc183119419e7e55ba11f089f523ef5058363a8059fb8e31e9421b491056c01819e28d3d0ff07eea3d53a1e3b6b8db235aca63c139c0eea68ca47a9fa6ef757b83ff00bf68ad428c2f248c7a8f9fcea518df516adac74e7544f63a2ea172f1800291e6cee19ec78cd5826344e85b6bad25ba8fade5b99dae0ee11efc71e858f7e7d054a2d7d39a75ae8f7b6b00b8917f1516624b78429da327cec493db1db1d8540cf4aea28f58d6aeae2f6dd64b498082d880488d149fcea7d4939ab04175e6850a8d32de3b78e380c8de32c4db4e18e430fef543cf86fd0d691b4fabdf6648b3b2db69ce7dd87be68342d2f4fb9b5b891af1a28a2dc05bc5036d001e0eef7352884b961a2ea9aa7555c885e08d45b5bc52b61b686c120fb939fb541276bd4b61d53624d942e2f6200bc32290633e99f4233416dd3ad3f0d611c0c77b632e71dc9ef41156dd27a45addcb3dbd9c513b1dd941821bdc7b558333b9f873757fd69a85e3f813e9c7723b5d93265d872473c11544a68ff08fa75e290b42ec4e4124e70738fa5048e89f0f745d2aeadd2decedda6525c975121183c77f7a945c754d0e0d563682ed43425369403bff00bcd58308ba7d5fe13f5a05889974a9d8b46aede4914f707d88ff001528ddf4fd7edb54d1a1d56c312dab2e64dbc9418e78f5c541296d70b716d1cd6f8789977230ecc280cb7519b816f212b205de4e0843ce300f6cfcb39a0545c42cee88e0b458ddec33ee680eac92266360debc7b5056fad2d354b9b189745744be121daf27e550548ce3d4d58324d07a725e98ea2b7ff5381f5169a7579d021fe13904ee43ddfbe49038ab46e76cf05cc714f6d309232a4a98ce54fd6b2196bb7f2e9b631b2c427b891b6851db3eff002007341e5bf887aa2ea3d4f77378be381e42fdb711ed5a1554395caf1cd07617dcd04fc85402101da791421b49920331381c60d1a69bf02f56f03a925b12c162b98c955f775e47df19a32d99b518268e4491668704a79d4aeec7b7bd4a30feb7e9144d76e265697c3e2693631674273803e556087d76f35fd49859e9925ccf611141106f2e182e3241f727f5a94681a268f79ad1b1b8b9dd66b1c2b1ce9bb06361c1e7bf3fe6a096b0d3ba57488e485b52b40909c386901607d47bf7a0ae758eb69ac4d15be81a748f0a9c35cc90b2eff4c03c1c638a0b77405c5d5d45f87be5fe359a88b81b401dc1c7d38fb50586fed18ea3015790091591e447c1518c8c7a0a0a5754d8c9d49a8d9f4ee9dba0b3b5224b9692327728f627e7c6682f9a7e996b6b3a8b6b748a348820c7720761412c064e3041ce282b5d4bd73d3bd3f33daea97ac2e540dd0a292dc8cd043c1f15ba2a7923b65bb910371b9a12141f9d02edf13ba2ade56857551e5e77244c54fd0e280746ebfe99bbbd655d56dcdc9ce08465565f4ee3bfca82d53eb3a6dac3e25c5f5ba646402e33fa77a0aff5b74ad8757e9ca972844aa37c520fcca7d3f5ab067bd369a8f467544d626c98e9f7118f0200e4465c903049c8c9e6ad1b24334b6fa6249716cab20037c309dd83db03b5640dddac3764a4f02cb1103863919fa7a1a06d6f600c37162911b7b252b87dc773f1927393f4a079f868edae1ae6328a8b1ed38e30050226e85d5dc1f879011b3c47c2f604719f9d01eff4f4b83e3c6b18bb452b1cac9b8a83de80b16e8208a3b7b58e1407cc061427cc0ff1560ce7a8f592d69a97504cad2dac01a2b53900c3e9e51ea58f727d0551e73bfb86b99a49a46dcf21c96340dc13804f20f6f9501c0e3b8a0963316fcc4607007f57bd084d64dec01200ce483468ff0040d525d1755b4d4206ff0095207c11dc67ff0019a18f56584f6daad9dade4211e39104a8ded9152b235cd8c530613229c8c1c8ef50472e81690ee00322b0c100f0debdbb7ca8111ace856371358cba85aa5cc407891ccf83f2ef4048b4ad2e59bf116769672c72f99dd1437239078e2824a4d3e1b94559234110e781839fa0a0561b38ad532a12319c86c6307e740a9732a3a00cac870cd8e0faf0681be8b6db965bb909df3c85806eeabced5a09523647e6e0fef419a6adf116daf7ac34be9dd1da686e7f1ca2e243b76320ce57df9ff1560cc3e3f470ff00c78255b842b35bc6c4af9b6e323d3e95467b6365f8dbcf062beb68c119595d8aaff6e282422e9899b4f6bb5d46cda2562a76316c1078f4a0859e1b9b762c0bf94f0e84feb4125a57505c58ea70dd5d0174a986d92b1c13f6f5a0de7a5be366877260b5d42dee2d2423124a487507ebdf15289dd3fac7a7bab6feded74d61733473acdb5a162142ff00313d81ed505fa58fc6d809380c1b9f5c502e0e05040ea367a85dea454de2ff00a610375b04c16c7a16ef8340b5f6930dce9375636acf6a278f04c5dd4f1dbf4a084e91d06f3a52dee62bbd4a2b882494ced3c8a448063b63b638fde803ab7ae749b2b3096d792c93c8c109b55dcd18ce3710473ffdd043dc758dc5869044565aa5dda4c3c2b7bc78c1f14e3963db03e7c0ab066bf1327d41ba76ca6bc48ecad24c456f6b0c87cf8e4bbfa138c0fa9aa3297c83dd4e28395811cf2680a5b93c7ed413cd1ff0f3c797b8031406645236b0508406f30e68ba49c051b97d0e0e7d28ad57e19f575c5be8f269515dac772877c11bc464dea7ba8c739ce78f9d3193bb8ebfea2bcbd6b5b6b8b58bb7f13c2f0ce31cf0deb4c0f2dbad6d743d2ee99efae752d6c02a86e0054524f6383c7ff94c0b6af274c75149a46a5a82c46f1e1479fc3190bd8156fbe7f4a960bf74e9d253f1167a3ac09e0856610e3041ec7f6c540f67b892cee7f8d18368232ef2af2508c7047cf340ead5bf130accc9b1186541e723d09ffc5033bbb1b82d74d6b37f1244daa1b38073df3f4a08eeb1d3b50d4fa6a5b4d32f12cef1902ee73e523d476fde8306eb0d3fabfa4ba92c278af67bb7281606472f90bdd58558253a6afb40ea1d62283a8b461a66a6f931cf6a7c2466f7cfb939e7b5515fbed3747b5eb8f06eb78d35080a2ec9719c76f98049a0b4ebdd37d1bad869acbf0b03c5c16b29444adf50ded41995f68564a263a66b31cd02be152505493f51c1a088bab69ad1bc179e320f07c37c8a0692b46c4995f0381db39a0b2fc34e971d57d4705bc8db6c50ef9dd97b81fcbf7381528f5ae97a1d8e996d1db69b0c7648855b10a81b80f43c739c54134147b9a036063279fb5046e957726a0f2cfe04915b06db1788305ffeac7a0a00d72f8d9c491c06337533050ac7185cf2df6a06da2da4293488f34973328c34aea428c9ec3eded40ee7d2ad249448f6b133820ee2833df3fde819ea96897461b05b87815f2ee919e5d47704fa039ab079b3e326b70eafd4ef6d6650d8e9ebf868b69c8247723efebf2aa280eb9193ebedc5002a124e015340018fb8fde82cf32b1603d0678cd02406dce3008e47ce81b499c331383c9c9f5a2e9c69377369f7d6f796a4acf148acb83fb511e91b3b3d0bab745b7d45acedd8e3732b71b1fd73f7a5a19eafd09a56a0a96b1c705b49c48510761ce4fcfbd4d0d752826b2b583476fc3daacb295b79d768de8a32b1e71f989e49f6a7d14dd1af5ba275a45b8b093c054492ea769092373765c1da4679fbd306e36ba9595fe9f0dcdbcc92c33e1579cf27d0d409ea178f68521b6b76926ee8a7853f7ff140bc768d78f6f73748d1cd103b543f0091cf6efc502f7319dac194371d8b6326829f0c501d7ae6fa568d5d4942c806d4db81839f53c8cd59456fae6e628749b5bab8b1865b08e4726588ec11e7f2e49071c93da9a31dd4341d675e9a5bad374f9858162d0b4ac70e18f0573df35a0c759f87bd53a404f174f965dfff00f479b1ef570576e34bd4b4cc0bdb3b9b7258a00e846e3f2a94376475cee4914af7ca9150685f09ba61efb52fc7dd69bf8eb7c158d1d0b47bb38f37efde968d6eeb4eb5e91d6ad25b660aee59974db6881690918e31ce39279e062a5a34bb57b88adedd1e379679065d80036679e6a07e8391bce7e940c659ef5afe1286de3b16f2b8903094b7b2fa7ce81eb380c4260ed193f2a0cd6fa5d4a4ea0fc7bdadcce923158a3039db83c038e3ef41a0e96b2ad8a35e009291b8a939d9f227e43bd590436bbd6fa269202c974b7123602c76e779624e00e29833bf897d493e896525dbcb2a6b5a9c3e1456b91b6d60cf989c7f31f7a60c02490961ebcf3eb541308e39e067b507007b96007a67fb50178f97eb4165ce18165c2927b773fad023202d9c8dbb7818ff003408300b87f2f1c107d0d0c15a4f2e339c90467f6a18bdfc2cea8ff4bd561b4b9ba686d6e64552c4f954e7d7e46a60f4688d240af1b2bc6cbf5047ca960617ba658de1b792f2d94a5ab33461b18524633fa1a81b5c8b5168967369d23c0e0a24622dc981d81c76aba29df0bb48d660d52fceb88d069f04aeb69130037127f37b9c0ed9a8350781240bbc06da72323b1f7a0eb8816e633192ebc8c9472a78fa50349b4c83c068e24f0ddbcc1c13b837be4d055b57e98b996d4db5b4a893dc1e6620b6ccf2c467efc504ce97a38d3f4d874bf09af6d46e2f25cb82724e791db15650a43f878b51fc34f3da8f132b6d6a98c80a39ff007e99aba249631b58b9047239ec3e55368aeeb7d2da6f52c0eb7f16e87f2c6e836ba90724ab7a67b55d115ac7c3e8aed2182def4c56a14096368959a423d77e3229a27b41e9d8343b01069c8a8dc9660aa3713df3c64d4a1c695d3d6b67a8cba94b9b8d4e61869e4e4a8c636a7f4afcaa09a485519caae19b966f7a0435196582c656b74df3e308beec7b50629375775b691ac5bdb6b16d6378779f019b00a31cf391c9c2f1daae0b35ef52f5374de88d77aa45a6cd25ddc0108694ee2188c28007603d6a0d16c92430a4b2ed3230dc401855cfa0a0a07c45d7b5db9d462e9ee960b14b2ee134ef8c850012147ec78ab0670b643a2efae753d72686e6e2da211db42176079c8e768f65e39f7aa332d6f58bbd635096f6fe6692695b24f603d801e82823cb900ee00e68006460051dfd680ed9f0c905b713d8d006d5f5419fa505a18f94e40501b1b81a04186d62402c87be3d6810b81290aea8467201231cd1749dbc437f9f1e201db3de8ba07dc0175c027f28a335b17c26f888d6b6d0e8fabf892a29c453b1e547f49f7a946d6424f08236491c833ee0835073294888894120700f0280813c40a6711bc8843e00fca7d3ef40e41dc081f9a811681c6f7565329185623b7e9de812b3bcf11ff0b74563bd50494cf120071b97e5fda80d7577046c9019d5669dbc340324eec67fb734103d5da96bf67a7cf0e916f6e2765f25ddc4c11107ab1c8c647cce2816d3ec7f0f6564cae6e67da375e6d52cc4af2e4fb13ed4145f899d47b3499f4bb6d46cda49b69b92921565c3648e3dd40c81cd5c0ae89f13ec246d3e379ed2d6da180b5d34849da1780b128e49271c9f4a60ba685d5fa36bc42d95c324ec7090cc9b1d87b81ed50588958977cacaaa3b9341c655f12348d1dcb8dc1946540f99a019e2134454eeda7bed3839cd052fe2136b536b5d3563a1ca53c49da4b9507198940ce7e5c9fbe281c6b7a974cf4ee4ea7242d76dc784a3c595b3e9b464e3f6ad0ac745ccbd4fadcbabea42da56959a382ce7460d6b1a93c01f97272093ebf6a82f1ad6af0e9da5cb3cecf6902216919f82aa3818c7a9f4c530649a9f5269ba7429d472239bc991a1b0d3c3152880f0f23039e7bf3de90635ab6a377aa5ebdcdecef2c9239e59f3827e5ed54302195fcc38cd01245395c1f5f4a05b606538e483c501b6939e3b5077860f3914165754c33e549000dbe87de813b820c27fa7baafb8a04a69c98e281e42618c795338033df1f3a06c03e4e029247007ad010093c35674da71f977640340081a190658e41c820f141b0fc33f8926c218b4ed609366a02249bb2d19ce3ea4528dbece68eead926b7916689c643a9e0d643387521fea2f693c2d6efc786ee46d9bfed3eff2a04669edf5295ff057a60bd865309246d3bbbedc1efef41d63a8dec9ab4fa7dd4510fc3c69234ca186e2d9c003b7a67bd034bad0a5bb96e25d575267889cc1b54446d9bd0a37bfbfbd02925945a72cba8dddc48b3f87b1e58f23c623f292bdb7fa7cf38a0a5750f54ebba56a9a67fc516b6d6fd3970ea9234677c8dc7f38f6e4640ce282d1ac4b16bfa72c1d2bad430cd1ba822061865f5007d3daac19cf547c189357d561bbd3eee683c62cd786e9b73337b8c7bd512bd39f06adedec2de0d5ae639da372e6485363107f97767b505cee755d03a5e58ac228659af123184b7b733322e38c91dbf5a943ab3d52e64b49ee755d2e64950e238e35f10c884e17cbe87dc540e6d7509a4f110e9f7566a471712850abf6ce463e6280bacea36fd33a4497f773cf32c698dcc4beee33938edc7ad05534aea683ae61d64c4d2a69b6b88d16d5ca5c303f3e386cf61db140e27b5e99e96b64bdd562b6b30aa36c6c37cac7dc9eec6b42c1a66a962fa70beb6b516d0cbe76322f86c78f6c66831bf8b5d5d2dfa35a5dce60b1933b6ce3c788769f2b331ec1b8fd2831b79649984b239773c1dc68129725c1c640e73400ec781d8fb1a03c4a85d0c8582640257bd01e51fc42236263c9c67be280429c6037eb405dbf5fd682c2a0bb976cf07d3fc5009279ef8ec4e68193a9902b28e7dc71fb501d95b098e0f6dd9e0d0049131019b047b8390281bb292484e47c8500c4f242c3076bf704704739a0be7c3febfbae9a5daf23cd017c7e19fb107bb67d0f6fd6837cd2757d1fab34f4f05e37dde630b1c3a91edf4f7159103d6eb7da65fdbdf59dadb5e2460ac876ed9e1c8c060f9efe9c8a0a75cfc42d5742d2ee5a7e9dbb494b6d6b9bc930cce4f940e3cd81ed4160e98f88315e689fff0022b57664199cc5196f0c7a164ef8f98cd0589baffa68590985eb15c0db1985839f6c2919340b69d03f5285bdd6f4bf021424db4329cb153fccc3d09c76a090d3340d2f479a7bab3b38e2924e5e451cfd280d7dafe936f6c5e4bd89813b02a36589ce318a0358dc35cc4e17f9bf234cdbb78fa0c607a7340e6cec20b1596610c6934b8323226379edda81da8dcb9ec40a042f50b5bb21645473b58b11dbd7bfca8304f8add5d67a9ea8ba5d8ea72c1a4d8a952f10f2c920e368cf71e99fad5833dd0754d6ed66bdb2e9a91a5babb2a310465a57c1ddc1038e7bd5171d3748b8d46ee1ff005298dc6a764c27d4eeaee7fe1c01795881c9e7804fe940dbe287c4b6d75a1b1d1c986d62277c91bf131f4c0f6fad0663737135d3b497124924871f98e7803007d2811dc5b83903dc0a0333f03be7de8122df2c9a05a11e5f51f7a05ce7071804fca8033e5da0734020b0183bb23e5416269577ed0e5323078ceeefdff6a03dbcd62914c2f629a47c622689800879e4fbd046f9d8a2a03e31385c0e73da8b83ca590947dcaead8208e73da8849b3e19ce704f7c5015586d006431f5cf61f3a04ee586ff002481c8fe6191408f0011eb8e30682774dea9bbb5784492ca6385832e1ca95e3d2834be9df8c312e2db5eb4375080337000f1303d18763591a469baef4d755989ec6f6dae5a23e20b599406dd8e080ddbed41272f4dd8caf1c86d163910f9595882a3d718a035edd695d3b6a926b57d0ac65b10b4e06eedd863bf141077fd7af2782bd3fa26a1a8891d57c630948c0279393dcd04cf5875258f4de9f0cb7b7b6d66d2b81ba752d85f5214724fed41036bd79d2fe319d7a8f4b9c81e58de2f04827b9ce09a07a3acecf54b790685ace8697606009e52c377b7f2e682b097d7d36acf0f55df5edbdc0977412468cb6ce3be10af3c63b9c8a0b0751f505be9690dd5d752436f62a3fe4c6448f3b7b0c64e38f615734651f107e3045ac42b67a7693018633b965bc1bc838ee173807bf7cd33065baaeb1a95f2c11dfcd2bc51fe48880aa3e8a062a8b059f595df4ae9a74de9e9ec499d43c97b1427c6e47e525bb63e4282ad3ea3712893c599dbc4259c1627713c927de81043950df97db1406da8411c92063be280230839627078e79a0390a71b5bb5003a8c1232338e4507025573e9fbd02a0e41dc0e680c3691cf714053bb34160895dc16f291d98d02322aa39f3e14707ffaa06f202a5bb0c7201f4a343aca51090497efdfbfce89840c8db8e46573923ff14410b00490d9f5c1a0425dd8ce4673e873cd0265e4dbe7041ed814009b8cbb8e5863bd07163b7716e0607b6698060b96b7b9478dc8643918247ee39a60b7e97f133a8b4e0c63d4ee597380923970a3ef4c0e13e25dfcfab457ba95bdbddb212016501867b9cfbfda982f907c74b282da34874a9048aa479c83838edc62982b7ac7c42d235cd67f15ac5b40c366418a2cb0c1c81e6f5e31db14c160d035de8cd4a3f18ea96562cc37359dfe9cac887fef039fd6b39446f56ea5d13a9dca4579a922496b1975b8d22dfc3566cf9557230703be715ac1431d4d2275325d7fae6b4f6f182a93ef1e32a9f41938f6a60afeb1a95c5fea53dccf772cf2c8c489240031f627e7565c0d67bbf160487c1801073bc0c31f91f953420f2bc8c7c52cc540032738a809905c0f4fa501940208e73df34028e703938a0577ae013f4a001300db4f03b71407461ce0502dca8c9c7dcf6a003fafcbdcd0070bc1e0fd734070db467b8a04cb9c9e68274b93bcb1daa40200ed4099765249ec476cf340849b8b264823bf34689ee009cb671df1409bc8e8b8e770e3ec68984d9c953cf97be2860b248caaebc107dc67f7a184c31232db88fd451031ce50e76039f5c8045026efb8f93279e0fd680b239504f0483d88ef409ee25bb90c79c0e050151c6e21b39ce783eb40adbcc2cefa17bdb61322387781c950e3dbdf9c8a066f28790b22e013db3dbef54726081e63c6460d34191b1bb0720f634060e7600412c781502409c8e3d7b500ed71dbef8ed40243f181c0a02e5d4e0fad006f644e4819e3b501f7e3049e7b501bc43b4e391da80558003392d40a23305e320d02e64cf998e1bf5a032b0c927b8e68049c8c8e71c6280377043118f4e680bbff00de0504ddbb3128371c1c64668024e59f3cd02521254e4fad1a2107e48fe6a6809ddb9e78a029e1463d05027ffc744a6c3857c7b1a205ff00e637fbf4a02b12b1794e39f4a02024e7249ed409924720906800005173fd7404989698ee39e4f7a04cf723d07a501fff0097ed406ffe36a018ff00281e99a037f4d0731f3bfd28007e53400ff99a810248c0cf140bc60123233cff008a0557f9beb4056eff007a07109243e79a03778b27bfbd02b128c27039a054001b818a06609de793da815006070283ffd9}\par}
-{\pard \ql \f0 \sa180 \li0 \fi0 Here is a movie {\pict\jpegblip\picw20\pich22\picwgoal400\pichgoal440\bin ffd8ffe000104a46494600010101004800480000fffe0050546869732061727420697320696e20746865207075626c696320646f6d61696e2e204b6576696e204875676865732c206b6576696e68406569742e636f6d2c2053657074656d6265722031393935ffdb00430001010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101ffdb00430101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101ffc00011080016001403012200021101031101ffc4001a000100020301000000000000000000000000080905060a07ffc400231000010501000300010500000000000000060304050708020001090a11153976b7ffc400160101010100000000000000000000000000060800ffc400261101000102050109000000000000000000010200030405061121b33134365154717475b4ffda000c03010002110311003f00a90cf388f366a62aa720ed6ae07f96901f3831d973452b8cf36fe3570fc908e46d466433e5dd954f2e96992d9e498c7753faa44916e016ca91cc7d88b38fe60a5b97737defcbcc539c98d336a57f4fc2ca9a486bf07ab575ad9a3af4df221d8215e36df86c4504ff0024574551b3d687ee0575757b3ad64e311ee62bd94158d37e24198c43973099f1fc0c41614d950246513a081abf76cfe7061f6863281e6352fd1670949c148dd6dfb0d25f5b3689b1d5c965b0eacbf4e0932ad28e22ab9ae945633f4744bd3c8cee0a7fdf085b9000f449c5f7afa30b83e0b6fd7b0c8429c9467ff9715347c891e25fa24a205861aa715e6a09bd0488237dc2723414d9891381524e8ca7c0894664f835653631ab55ee7e3de433e4ff001b30949124e4c10c8b6ad0a479b3f9c937b2cf5bc0095ad600a0a41a0e9faee174a1c605e161c6c7a313539650b0113190f1a8368e60d5b24f30ff008ea7f0bf867fa6595feeb6978f1fe0f9c26177f4d63a51a9235184750e7d18811339cd000000c75f000e00380380ae390c350def826ed42ad051fa6f501c50f9b699c3b69cbeb76476d202bf3ac985b6e0e968be66572893e6a744540bd9722e5c87956848629bc2559306bd113e8653d3b6aff651dfad7a3ac8b02958cba02a93ccf525757039bae6cff090e1d90688e8aa233ee86a4c4a3e0586d6b2340522e47dcb7d0046d8a5acb05a123ee25d2b230b2ada6e2e2f9ede3c05202520ec2487b0d56562529d8b3393bca76adca4ec1bca508abb001babc007915d84fe3dd14e207e3c62f8379da2a3b861fb6629d28dba53b6ea388ebfed866bf6dfb553455e91ed547ae92e9445253a4fdf3efb4f8ebdfbe7d3c78f1ee0bb9e13e358e942a4ed49e22cff00eeb35fdd7ebfffd9} icon.\par}
+{\pard \ql \f0 \sa0 \li0 \fi0 {\pict\jpegblip\picw250\pich250\picwgoal3000\pichgoal3000 ffd8ffe000104a46494600010101007800780000ffdb00430006040506050406060506070706080a100a0a09090a140e0f0c1017141818171416161a1d251f1a1b231c1616202c20232627292a29191f2d302d283025282928ffdb0043010707070a080a130a0a13281a161a2828282828282828282828282828282828282828282828282828282828282828282828282828282828282828282828282828ffc000110800fa00fa03011100021101031101ffc4001c0000000701010000000000000000000000010203040506070008ffc4003e100002010303020404040502050500030001020300041105122106311322415107617181143291a1234252b1c115f016336272d1082443e1f1265382ffc40017010101010100000000000000000000000000010204ffc4001b11010101010003010000000000000000000001110212213141ffda000c03010002110311003f00dadd18a10a704f6a95ccc57e37750782b0d8d9ea0cd32e7c5446e07e9f4ad723119a7b89e61e348f260719278aad613cbb640002938c76a182b264fc87bd13009c0c019c76e3d68a072e1cf6f4cd502d330c28269a61bb39c923923d4fad44c08dccb95cfd28b8280769ee08a263891e1808739e4f1d8d149392172cc714050dbb9fde8960ed8c60b79b1ed44103b05c331dbdb1dc5026ac1946d20ff8140aa631c773ec738a0346a003bf93e9cf02801895e7b9a01886796c923bd0090a06393c76a0142003ce3d86680d8dd9392303f5341ccc1b3cf7a2c812c37e4923d381429757013209fa511c18146c9247a0f6a007900c0c671c6280854e086c673eb45c27c038fd68aedff2fda836ef881f136f25d5e6b7d1262964aa02b03f98fbf153131935edcc97576f35c33349212cc4f39f7ab26186dfce5b200f73451f7600dcb8cf27e7400c0b291914046c9e0718fde81371b8e7273f4ef4007691919240e714097f31f376e7b5008caee27807b0f5a02c8e1b3c6d27d33cd0201d839523144d1a149ae084b78da47638211771fd050d582c3a0faab5119b6d12f8ab1c06788a0fd4e2ac356fd1fe08754ddccaba849696309e598c9e2103fed1dcfdeadc44fea5ff00a7f956366d375e492403ca935bedcf1eea4ff6ac68a55efc1beb3b552574f8e7009ff933a927ec715bc82b3a8f4d6bba5ca1352d22fe061cf9a0383f71dea5119cc6c0baed3eaac0f1fad40897dcc3d81f7a052366c1007df3400f21edefc5008c28f30c9c5170ee4fc37830086395250a7c66770c18e78da31c0c63de8609b41f7c515c5172a30c3b76344a3e377cb2339cf7a242aea89808cce368272b8c1a2e107c672a49f5c1a181c9c7ae7da8a2119e7b1f5068099ffa68258a132062d8f9e0f34059502b61bf2824e681bb297ced2a71efda80f19c47b9c77fdbe74057c13e539cf3c1a0eeeb9c73f33405ddb4f18249c1e28062b79ae242902024465b9214614649e7bd0362a7249eddc513456e5720f38f5a1a98e96e95d6baa6ebc2d1ad1e65521649bb469f563534d6d7d31f04347d2a2fc5f535db6a0e83718906c887cbbe5a9a8bef44dce9f731ca9a2e89169d6d6f2184b1455dc07b11dcfeb4d16f119c649a681285b03d3e5500f87820ff006a0e098191de80ac9b8904647b55d11da9681a56a31f87a869f6970b8ffe4883629a289aefc16e92d441682da5b098f21ed9f033f353914d19b751fc08d66cc16d12fe2bf45ec92ff0df1fdbfb559ec667aff4eeb1a04db359d3ae6d40eccebe53f46ec7f5ab82263da7dcf3eb5174e5181076918c7de869503232491ee4515c1803824f03b51287f30e0e7d803449494832c157278a2e8c71fcb9f9d144639236824d01e142efb1768cfb9c7ef40512a818de78ff00a682518e7cc30ab9e00a02cce9953247bd41e467191ed9a04205ee99da4e4e3d283a524b0427b5026c18a8e082067db8341ce0e39ed409b6502907391edda80f2dfdc496f0c124ac6184b144cf0a4e338fd2894f7a7342d4ba9b568f4fd261f12571966270a8bfd47d8511bae85f02b47b7fc34bac5d5c5dc88a0c90ab6c8d9bedce3ef4d1ad691a6dae976a96d616d15b409f9638d70054a1dbc68ea51d4329f4619a8022b78e04548515117b05000a035c5c4702a995c26e3819f534047bcb68a458cce866719540724d02e41c0f7a012a40f6141cbc8e7bd01719e38e6838af1c0a04ca8206d3cd037bdb082fad9e0bd8a39e0718649141047d0d5d18f759fc0cd3af164b8e9999acae4e4f81236e898f7c0f55fed574615aee83a96817ef67abda3db4ebdb7f66f983d88a061bb8db9e3d45165076db83c1f950a53780d8247c80a2398f182724f1c7ad080c608cfa7a51a0062adc7afbd0130173bb9c5070f071cb37e82826106e8f615e01c9e680d6b35bc534be3c1e3831b2aa962bb188f2b71df1de819ae4b1048c7f57bd01a58268e332642ae0704f7cf6207af6a01b99e17b7b6416e227407c494139909ed9f4c0a04a4e501e0f1eb40d263e53dce7fa682c9d0bd13abf58dd6db18bc2b157c4975270ab8ef8f563f21447a73a03a1f4de8eb031582b497328066b97fcd21ff038edfde88b7e32703bd64188e7e6283864b73400cd804b67ca3268317eacea6d56ff005233592f8b6303f953fa4af7c2fa93417fe98b763e0ea171297bab98558068f695ce0e08fdbd281e5c6a57ba5e9d14d716ef7774f2ec112601da4f27ec2827ada74bab559a20e148fcae36b0f91140283729c77a0e0a7777a01dac68395719e39a029607cb901b19c501480ab9279f4a086ea8d0b48d76c0586b7143224a76c61ce1831fe93e86b43cd1f12fe19ea7d2533dcdbeebcd20b612651e68f9ece3fcf6fa5067cbcf20ff009a051724905411e94032799060723da8406d6c67e7ea68d0e1770fe5cfb5026c37039ef9a02eca098c91e6e01e71c500b1d8a49c12786cf6a06a4e256008e3d050119958007920e2801154e32fb4120927b014017eb1c523ac5209a356215c291b87be28957ef853f0d66eaa99352d515e1d190f947669ce7b0ffa7e74a8f4be996569a5d9c56b6704705b46bb5238d42851f2ac875712bc70b3c30f892019540704d01ad2669a0491936330c95ce7140b2e4939a03638c7e8680ae485e33bbe540d60d3ada162c90a02c7270a39340a4f28b68da4645007a8f6a069a746f73235ddcefc391e12b2e1916824948742c99382473c73404791c617695279dc0640f9502c578c9efeb4095cb4cb0830ba21cf999c6401f4f5a05061d430c8079a02e03b3004311c7d281b5e3cd676c65489ee594e4aafe6c7ae07a9a0a075bbea3a8ea96f047d3935ebc404f04ad29411e08e011d98fed416fd212ee5b05b4d5ad6300c615807f1171eaa49eff5ad418c7c55f8466dd66d57a521f20cbcd66a7247a9283dbe5418a63862479877cf1f6c5008e400bdf1ce684016fe53dfbd1a73794600e08ce3d6800377c8c7d6800a9cf75fd4503d91492460f7ee3d28247a7b459f5fd592d22711c206f9e563858a31f99cfd050583518ba75247b1d134f9aed21396d4669769931dc01c003f7a329c4d17458ac5b55d36c12e040a3f1da75c1cb04ede2447f7f6a94567ad7a66db4fbbb29ba7d65b8b4bd8ccd09c8231eaa07b8ab04a7c2cf87b3f53ea8d77abc72c1a5dabe2452bb5a561fc83e5ee7e541e988218ed2dd22b7855228d76a46a00000ec00a510bd4dd511f4fe84da95cc31f880022da4902b1e7d3e99ac86fd03d631f565b4ee6d4dbbc649009cab2e48c83f514165b8b94b6895c44f279c280839e78ce28178ae6de46748a789e453865570483ec6812d42e85a421fc37918b00a883924d024c6e99b7a2a966c0009e17dc9f9fed40f81c77e28139218e4ff9815b9cf23340a01c907b9140201038ed402fcafd28386464e4fd33c50272bc60032609cf00fbd024f722dc66f24822ddf972f8feff00e280f69b24844919cac9ce7de83a447f30ded823007b50459d6ecacb528349b979127651b1dc795f1f3f7a0990148054823dc5015d491c0a0c3be337c2ff00c489b5ee9c87172016b9b541c49ff5a8f7f71eb560c1fc43e0a47e1aa94277310431f91fa551c1727f29ed409b641c86e31839a3454805739c1f6a026f1fd740f64665fc8c31cfde82db79bb40e9e8f49b62eb7d7e8b717ec832c91ff247fa1dc7df2281bcc9369d671493c422b7911654c1215f92bb8827bf068624ba635392df5eb4b9924558ee5bc19b71cee43c6dc7cf34c657be8db0b0b9d0f51d2afe668934dbf9628ddb8c2b8c0073f3a80da37546a7d25174fd95dc125c69f7313ee5655dfc313bd483cf07b1f6a68d5b48d5ec758b612e9d7293211c8fe653f35ee2a084eb9e8bb1eafb3582fe496278f3e1c919fcb9f97ad03ee8dd017a6741b6d3229dae161057c5750a48249ec3eb4139238568f6a9e7b103b5037934cb3793c610a2cd9277a8da73f5140ee38f6280c4b11c65b934023006d50050030e4647de80c846de3b500fcf9fbd0197273ed4007b91400e580c8e45074a82400e72682b36fd2162b7f25ddc09af2766ceeb872db79cf00f6a0b3229550140e07007a50092db860673de818df473c862686dad6470d9cce3b7b63e740fa1de6252ebb5bd81cd00bee2d800d003a6464004763ce683ce9f1cbe1f1d3a67ea1d1a30b68edffba814708c7f9c63d0fafceaca31e6dc71e1f07daa82608c83819f7a1a11ce149238fd68d0a579ec682cfd27a7c3a86bd10bc38b3b756b8b93c1fe1a8c91f7381f7a034f752ea5aa5c5eb292f732128037619c018f6ec282e5a2cb047abda74d5ce9b6da80f136de4a496219b3e48c92000323ea73467519d3da5bb757dbda410ac90c77c23058f99007ee7ec31416882ee47d23acb5185caf8bab4691b1efe57fff0038a9457ee75a82f6e7429350466b482f2742c0f74241c80c38c64541a9cfa1e89ac0177d33ab3d8de28f2b5bca429f91140e2c7a9b5ae9fb85b6ea9b46b9b3c796fe040768f76ec0fafb1f9505df4ebdb3d4edd6e74db98ee216fe68ce47d280648f75e2485a44da385ddc13f4a025ddbdbea16a633286566ce55f9c8f6c502ad750db2c514f30dec428247e6340bbf04100b73402afb943ed2b9e30683836defe9403bc1e06734020e06280cafe8683a375941d841c77c1a0151b467b50159f00e4127e5402872371040c5046eb5aadbe9b1c02e2f6dad25b89047099c677b7b0140fe3f1010afc803f3018e68160c3041ee2823f5dba92d34db89a1d9e2843b03b6d05bd013560c1748d57aa2797c6b35bab78e6959dc47231580ff336dcfb03c1a58364b5bbb7d7fa7b7427f1f673830c8664285bd1815238fad20f2c7c41e979ba43aa2e2c1cb1b663bede438f3a13c7dc76fb5515e9065b851f7a02950002a09c51a1b83cf14176e90d3645e9ad7752752aac23b3439c066665c827e944d29a6410aea725c4567135bd840d3c88a723728c29c9efe6c50d3ee9545b0bf8ef2e6e3c2fc2c6f72f2920e5f19039ee4938a9a875d03278377acf52ddf867f036ef71923932bfe51fbd3475cdc369df0db4fb389d4ea37970fa9cc0b00511795ce7d4f181eb4cd2451755fc45ac16d637381b14ca36b641dfce723e4053170d6cb52bbb362f6d3cb19241f2b9029862f09f143549ba7e7d2eef6caf2797c66ee17fdfd69862d1a069da7dfdac579d17adcda5ea9e1a992376c4723e39e3b024fd7e94c458ac3e25dee8d31d3bae74e7b79002bf8b8549471db38f5f4ed4c165e943a06a328d4ba605b4b22a1523c420c64fbaf38a82d36f0ce7cf7463790729b53017e940e0b0ceceed8ce0500e1b70daa08f5c9ed41d271cd0132476e7d7ff00aa069797d2411168ed9a41fcc858211f73c5075acb25ca6fb82aa31e58a36c81f561dcd033d42169e158ac64b98151b3981c2966cf639f4a064c7a8ac55e4865b7d493701e1c8e52403ea3cbfda827e390ca3f2c914aa81991bd281cdacc2747215c60e0ee5c67e940cb51b0b2bcbd824bfb08ee1a252d1caea1821cfa67b1fa504982b2283ce08f518a08abb82f6dd0369a5662081e14ce40c7ae1b04fda82275cb0bfd4f4536f7114589a5412461f3e4ce4e0e060f63f6ab2893d3b4b5b5b78e22ed22aae3cc3cc7e64fad3449a22a461500007602a0cd7e3b74c26b5d2ad79147baf34eccca40e4a7f30ff3f6aba3cd0543267eb5427b86f1f4c76ef45d0eca1ad5ef224d13e1cf4fd9b22192fa67bc955f8c8c617fba9fb510d7a6ed3fd43a735e5b54964be658c048fb6cdd9e7eb8a186bac97d174e6d22e23437b7ac26b95e77c68bf950fa7279e2b22dba45b59e97a669fa4ea36aeff89cea9a90451fc355ff0096ad9f4ce3f41570675d4fa8c77da8de5cde5be26bc653171ca47dc1f6c9fed5562b97f70276808da7c24f0c1c63804e33fa8a2928c0e0383c8f7ed41d92a41393f4a2548595c2c37493db4cd04e8a08f139566edfef3445b6e7aeaf65d2df48ea2b11776ae02a93e564c772adef409f4ee8ba9a21d73a36fa579ad9f325afe599171ed9c30a960d5ba0fe2843abb47a6f510fc26a4c36890f9558fcc6783506a1147b510024e30339ce680d2c6ae9861eb9a009178a0205443b989e39cd01d8075e3047ce80563057ca381ed4011c4531e503d85013c91b804a21279c903341131cda8c3abdc8650f6d20c4321232adec3dc504bab2c113c9293bb1963df3408dd4b75e1efb2856463dbc43b4631fad047e9177ad4fe32ea16b1db4b8fe1aa92571f5f5a0916bc8e0895af5c46c17cd8c9ff7da80f6d736f7f6915c59cab35bc837238ed8a072a31c1ef4062870718a06f7702dc5b3c522ee4752ae0fa8230683c75d6ba3b74ef535fe984929149e4278ca9e47edfdab42058003763ed409f88ffd6dfad06b1f12ae612fa0c76e0b471e9916d23f973eb4158d3efeff004a984da5debc1295d8e4018dbf3145d583a2ad96f356bbd7f5d90dc59587f1e79a6392f28fcaa3ee47159444ea3aa5ddfc7acf50dcdc344d7a4dbc317f52641200f6000fdeb41b5ef51d8eab672ffa9e971c97c11638268e431a46000012a3b9a351567db823b11f3ef40948e428048207a8340ab48ae83cb83ee0f3428a982719edf3e68c9cc97d3fe15ad8c9be138f2bf38e7b8f6ef40f7a5f55bdd3f56b46d3649127f1405f08e7249c76f5fa50689d48ba5f545cdcbdb462cba9206411b2b055bb07d4fb1c73528d4fa8f52d62cf47b6b8d2e65fc458c49f8a818795c151939f977a823ba0fe253750eb7fe937b04293f9f6c90be41dbdc7ff006283473c1efc1a06f69776d73bbf0f2aca32572bc80470450284a46dfca19f819f5a04e799614def26c0bdce09cfd85045dc75769d12dc3c3e2491db0dd3c85195235f7c91cfd066ae0cdba9be31f4ec61a386c1ef9d4ee473e45cfb1cf34c101d3ff1ac9d481d46c628ed24751881880833f988e7b0fa5328dfed2f2def2ce2b9b79925b791772ca87208f7a60182ee2b95cc0c48f53823fbd40ac658b30f4f4a086d4ee1d75bb6b78f4e965596366fc5211b23238008fde81f43692da5bc30d97831a0397dc09e3d714087506bf61a2c4cd77324726d2caaec141f9fd2ae0c435bf8c57173ad7876f7a2daca10489121244cdf319ce3dbf5a834fe81f881a6f57bcb6ba7c53c72c11873e28cee1db391dbef4199ff00ea4348116a5a66a8a8a04aad04847a90723f6ad7d18c312ddc02a3815423ba0f63fa541687bd9efe1b533b3c9e0a78473e899e318a09bd0ba6eef543e3b2bd8e9b10064bd9e4da001dc81401aeeb29a984d0ba7d5e1d06d4e6594f06523bc8e7f5c0ac8af752dfc17d7090d9218ec6d9447129ee71fcc4fb9cd6842ab10dc0014f3e5a2c1704b671dfdc734525226dc939e283a362c7f940344a380393df144733e2276e38f5efcd01b4bbbfc3dda4a9298a44395902e4a9c70682660d4265d62de40b1bdc1545054f95c8fe627df141af7c3af8808f3dd68dd5d2a45765884b8908d8c3b6c27b7a77a945d7a5fa474bd2ba8e4d5748b28624955d5d8b13b79ee9e983d8d40a753758c7a46b96f6114725dc92279a2810b3a64f94900763cfafa503fd3b59b79ed84da34713c0cd890f0a158fa1f981de826e1b548959fc4dc5cee24b6467e59ed4101ff19e9f676baa5d6a72c50adb4ad1ac790ccc076200f7ad41e7df881d79a87576a5f87b0f161d381db1c2a36e7e6d8ff3416bf87ff082c6f208ef7a82f22b9761bd6d619785f6dc477fa53705ab57f83bd297ceb1e9caf67708db9c4526723e849e3e94f212dd25d117fd29a8c09a76b534fa39cf8b6b71ced38e36fb73417f52e64548e34007e673e9f21ef590a1c918c90718dc281a69b68f67118d9da5058b798f6fa7fe280daadd1b2d36eae70710c4d263df0a4d583cc7a668fd4bf11b5837d7c93dcd9a3146959822a0e781f4cfa55161e9dd7fa67a4f55b9e9aea3e9f81fc09ca0ba118998fcdb2338c7b528d39f4cd2ba76e2d357d292df4eb391809963420ce1b1b576fa1e7359119f1eb4e17dd033ca172d6b2a4df303383fdeb5c8f2eef3bce4e0e335684cb0c9f354160d36f64b0baf16072b91b5f03391f43c51aab23a5debe91c4fad4d73689e6fc3a290573ff4f03e59f4a3280d67581ce916567f84b58ce0a1fccec3d58fa9a084de08c90464e4d1a8e419059b201f4a05630a176918efc50176293872c17bf14042aa0125b03db14046c60b60123fde6827fa0c68edd5365ff11346ba6292ee64194240c807e59a32b7fc51bfe8bd5ed5db424860beb62b89218422ce09c11c01dbbd0660ae110bf1bf2154838dbebfefeb41a8f4cdac7f117458f4d9ecd2df53b4cf81a822808c47255c0f7c8e7fb54a2ec2cfabba3b4b4b8d3af12eedad40926b0f070a13f9b633649f7a82eba6ea4357d321d4ecad512daf20df26e016507fa4fbfaf3e98f9d067dd2bd2faac9aa4d72d72d1e9510ca46a7631c7a320e18f1dfd7bd059afb7da816d23de4ba5de211346a1e4785f190548e4648c63b64e6b43ce9d5baafe3b539c5b452dbda46c638a167cb281c73ee4ff9340e3a3fa5f5aea4ba58f4bb57dbfcf2b02a8bf7f7a0de3a5fa0b50d2a2d92eb3e048c0a97c867dbedcf6a944e5cf4f6b76d1b3d8ea42795066266c87c81c65b9cfaf15048e83af3cd64abac08edaf01546c38dae4e0657ee6826e5b892de3702292e2545ddb55700fd0fbfca81c4b3bc718716eef9eeaa402280d14ab3c0b2c65c06fe571823ed40df56b217fa6dd5ab9216689a33f2c8c558307e83b8d77a37aaa7d22f2512c28768800c9954671b3d33ebef568d0ef7a7749eb0b5bbbb162d657b32b46d2e1564c8ed9c5644d1b0b9bbd261d2a440af6cb0e2e5b1e7dbc1238e0f7a0375b696daa7496a3a4dac8a92cf078685b271db04d391e40d5ec4586a1716de2a49e0c8c85d3b120f715ba1899173ff305413070abd89cfe9f5a2d3ee9c8639fa874eb6b804c52dc46b20c9f302c3bd11e84d47e1af4d5dc6521d3e3b662c19a58721ff5a9a321f89bd27a374b456d158dccd34d333332c9b4b2afbe47a7cb1f7aa33d2bc0d8c0f1c8f6a2c14b6d501b39cf63450897380c319e3de8065031c038f7ed40d8faf1ce41e4d004876a8dc3cc7e743025c956c818028c904579e7f0e15695c9c0541924f6c00283d0bf07f42d6b48820b8d62d20b2b58d656404959e52f83c8ff00fcfafbd4a35bb06f12391a48dd55cee2b2f3818ed8f6a8158a159890f02242079147623e631c502b0db436d1ecb7458d4738038fb0a087d6eeb508f48bb7d32d95750752b6c26c905b3ddb6f61eb574794f5cb6b9d0fa9678b512b25d24bbe52b8c1638278fbd582c57ff12afaed45b5bc0d0d8a8c08a2731ee3eec5793f40450466a1d59af446293c186cd53ca0c36eab93dc649e49fbd048e89f1675ed35e301e293919dcbf9867b37cbe94a35fe94ea4d33aba6824306dc48015750d86c6e247b0cf63591a40b8dc23fc30f14138dcac3000f9d03687547f12e8dd5af816b13148dddbcd29039c0f6f6f7a0eb5d62caf5636825db70c9bc4328f0dc0271c8a090627d3073ce681acf6505ccf14d35bc2f2c2731bb28254fb8a075144a83ca806792400334049ee6281e2496408656d880ff0031f61fa50446bd76058ea1b9e21025a3bb48afe71df9c7b71de9c8f196a0de23ca7b827d4f7add117e0cbfd4b5059392369663ff004e71c51aa97e8f555eadd258f2bf8a889cff00dc28cbd0bf123a926e96d163bdb74490bca2321c678209ff001591e71eafd7a7d7ef45cde2c20aae144638033fb9ad2e1b5e69d058da431ccf21d4a5c3b4631b62523807feaf5c7a50222f2d648c25f5aeec8c2cd19dae3d3e87e944d3eb7e90d425b49ef2292de38224f1505c3f8724a9eeaa7bd0d57a60406059436306868a7803839c7ad1a158039c13f4a33a716767f8cb9b6b55e1ae2458813e9938cd07a9f42d0b4de99b4b7d1f41b58ff19b03c93ba06607fa8b1f5f619a5b8266d74a65d42da6ba90cce996dcdc8c9fff006a5a2c2635083b05ef83eb5028076341db4b1ed9f7a04651fc41db18ed419d75b744dbea335fcb0db0335f2057901c05da73c8f9d5d18a75174a3f4c47335e35da4ce418a489374254f707d463d33565d1529b569a489a17944b06ec8057d71dcd037b4b6b8bfba31584124b27e62a8a4f1ea68357f83da7ea5a76bfe0912453ccabb49194653cb60f6ce3dfda983d196cd108c2401711f9768e306b2297d73fc6d02773a8b591922693c5004bb9d72542fa2f6efde8314ff867aeeec27500b77bb5670e36ca19b1dff2e7f2fd2837ce8bd5dd348b78b552219022870d9c46e792a4f6c608a0b846c8e03232b29ec41cd0199f1410fd4b24b1e8f712c0a5e4452d851e6c639dbf3238a0afa42ba77475e4ba8470896681da45180b18da76af3c9029c8f26dc1df2b9c606e273e86b743331924f27f4a82c12280e59b008e79f6a2d4d74188ff00e30d203a82ad7519c1ff00b860d11ba7c5e86c9fa3afae6f4091e043e021270b21e01c7dcd6479ab4dd3aeb56be4b7b184cf2b301b57d07bfd2b4bad0fe25e9f6960ba7c7a55ac50cd750335ccaade7723b83b8f6e38a2207a5ba4e7ea3d93780cb616ca53781f99fbff009a0b675a5be9765d43a75a6ad3b25adb4185429b831c70303dfdfd2831eb8954ca48f3827819c71ed406b2b1b9bf9a5fc1c4ce2253238047957dc9345d122b792eee522811a495ce1157b93ed444ff0049f476b1aaf51c761345269d25be269259570c833c6077249e062a68f53e8ef0da69509d4ae225b92a04af232ab16f98cf1f4a5a266d4dbca8af13a329ecca723f51502d14f0cb9f05d1c8ee01c91f6a0393b4edfe63c8a031608859b38f97340d84d04e5846eae50f9829ce3eb400fb24466041f5e3d2823f56d22db57b192d6e61468a41c823ff0035651916bbf04ada7badda5cad6d1b72c09dc33f2a6875d25f0865d06fe2bc6d4c4d3282026cca8cfafcfd29a34cd234a10c768f711a78f1bb392a3001208e3ec69a26a58d640c832091c90706a084ea1d3eeafdadf4f86da3166c0b4b397c18f046140f5ce4d04f4702436e91c28a9122e028ed8a0a9f5a5b6a09a1bc5a135bc72cce048b3c5bc15c638f9d59043fc2db997481aa69dae49e1cb6bb643239211939e467818f97bd305965ebce9a10bc8da9dbaa2679dd9ce3d8530572cfac87566ab05ae9f1490692b9696e1f833738555f96793504df5f25945d2576b7ec16dc46792381c7b7ad5e60f234980e42f6c9c56a82ec3eff00bd4124e49700f1c646e3cd169ce9575f83d52cee324347323f6e3861ff008a23d47d4ba6a75074fdcd8ef317e2e2ff0098bdd4706a60c3f4ae8cd5f44eb8fc3e97248a638cbc73bf90483d463b373e9574685abf42a6b5649fea72bbdeac4a8d3b018cfae31f7a6895b6b29b41d30d8e9f6bbed9213e1b7a994e724fcbb5064bd7835a9752d3af75d8116354778f660788cbd9483dbb0a0cd20b2b8d43528ad2088bdcccf854039cff00e2827a0d34e9da1de896f2182492efc0976f998aa827d3d334113a74aa9a9298628e74570478bc0c7cf1da83724bb8246d3e6416b0384da61b5501c9f5c3704f152c037561a95f5fce61d3ad6db4ab950f34b331dd9f4191db8fdcd406d67a675ab4b6d325d1af248272a43430315ddec7038f6ad4b3f448bf47eb71cb69abddebf21d5e26896203846c30c8603b9c6452d9835901405660376319ac84bf13180779d8bb82827d4fb0a06f777367a75acd7170f1430a9f331200cfceae061a0cf6dac692d7365266191db0578f5edf3a6075a6c9278b3433188a467860d96fbd40fe540471409aa0c1140750001ed8ed4058e15133c983960077edf6a06faade5c5b7822d2d926766cb967da2341dd8f0727d85033d27597d62e2ee3163756915bbf8799d71e2f19dcbf2a092b88dd9a311950a0e5b70ce47fe6ac18af53f5b69da9752dd69da9ca906876e24465d9e69881c6ff005c679c0aa2bfd267a347512c93dbb5d42d90d3c800b68c9ce0ec3cfa528db74ad034db5905ee8be1ac728dc153984f3f980f4fb56453be2de8f647a6aff53796596f0aed46798ec033ce149c0fb0ad71479c9bb9dc3bf3c55a0b95f65a825150b481a407b93c0fda8a29c06671dc93803bd131eafd0af6dffe18d2ee25982a4b04603b7a9c631fad03bbe586381bc5945b96385718c827db3eb5288eb8ba934eb15fc3c535f05427796dcccdec7150637d5bd55d5362b7975aa4d0d919018adec8637807bb60723000e4f7cd58203538aefa8aeb478a7b9beba924547b8774cf8608036a80704639cf1f9855d1a7f4c68b67a03de5e5d59dad8d988c62e1c0f107a1e7fdf7a082ea6d07a6e3e99375a7cb6b3db093c727701e2360f7f53dfb50653d4130d42ee18f48b3f0232a15218936963ebf5fbd06dbf0cfa74855b9d46e04b730c6144691e12307d33ea7de8348ba6b5478a279a004f98c479247b81f5a9438805ac0be2e02e73c9ef8fbd40c2346d43578eefc40da7da1dc8b8eefea4fcb9fef419beabf12a4bcebcb2d2fa7ee0dc58492084b30236bb6467dce383f6a0b87556a67a7f4d95a0bbb5468816f0a69c78b2e072572719ce78357079dfab3af2e7a92c963b88d94abbbf91cedc93edf418aa2c5f0dbe2a6a9a0c90d8de34773a6a8da1186d6403fa48fec682d9adeb7a9b4c9d572dacc9a6c9700456e5ca910e000ecbd8e580352fb1ae7476bd6dd49a325e5a9f3025245fe961dea097523cc0919a032af039a006936c81423104649c703ef40dcce64bc3035a87b6f0c378f9fe7cf2b8fdf340a4b6e25962915d94a67807839f7a043586922b5636ec44c061063f31f6ab079d7fe19b7eb2d4efeef55d5d74f992e9a0fc3a441dcb13927b838c9aa2d4bf042c618e178efee6e18104870172318edf5c1e6945bbe1a748ea7d2315edbea3a99bcb190030c401010e4e783ee0fa56455be3d6b90c1a6268d69e17f1486900ee98ec29ccc183119419e7e55ba11f089f523ef5058363a8059fb8e31e9421b491056c01819e28d3d0ff07eea3d53a1e3b6b8db235aca63c139c0eea68ca47a9fa6ef757b83ff00bf68ad428c2f248c7a8f9fcea518df516adac74e7544f63a2ea172f1800291e6cee19ec78cd5826344e85b6bad25ba8fade5b99dae0ee11efc71e858f7e7d054a2d7d39a75ae8f7b6b00b8917f1516624b78429da327cec493db1db1d8540cf4aea28f58d6aeae2f6dd64b498082d880488d149fcea7d4939ab04175e6850a8d32de3b78e380c8de32c4db4e18e430fef543cf86fd0d691b4fabdf6648b3b2db69ce7dd87be68342d2f4fb9b5b891af1a28a2dc05bc5036d001e0eef7352884b961a2ea9aa7555c885e08d45b5bc52b61b686c120fb939fb541276bd4b61d53624d942e2f6200bc32290633e99f4233416dd3ad3f0d611c0c77b632e71dc9ef41156dd27a45addcb3dbd9c513b1dd941821bdc7b558333b9f873757fd69a85e3f813e9c7723b5d93265d872473c11544a68ff08fa75e290b42ec4e4124e70738fa5048e89f0f745d2aeadd2decedda6525c975121183c77f7a945c754d0e0d563682ed43425369403bff00bcd58308ba7d5fe13f5a05889974a9d8b46aede4914f707d88ff001528ddf4fd7edb54d1a1d56c312dab2e64dbc9418e78f5c541296d70b716d1cd6f8789977230ecc280cb7519b816f212b205de4e0843ce300f6cfcb39a0545c42cee88e0b458ddec33ee680eac92266360debc7b5056fad2d354b9b189745744be121daf27e550548ce3d4d58324d07a725e98ea2b7ff5381f5169a7579d021fe13904ee43ddfbe49038ab46e76cf05cc714f6d309232a4a98ce54fd6b2196bb7f2e9b631b2c427b891b6851db3eff002007341e5bf887aa2ea3d4f77378be381e42fdb711ed5a1554395caf1cd07617dcd04fc85402101da791421b49920331381c60d1a69bf02f56f03a925b12c162b98c955f775e47df19a32d99b518268e4491668704a79d4aeec7b7bd4a30feb7e9144d76e265697c3e2693631674273803e556087d76f35fd49859e9925ccf611141106f2e182e3241f727f5a94681a268f79ad1b1b8b9dd66b1c2b1ce9bb06361c1e7bf3fe6a096b0d3ba57488e485b52b40909c386901607d47bf7a0ae758eb69ac4d15be81a748f0a9c35cc90b2eff4c03c1c638a0b77405c5d5d45f87be5fe359a88b81b401dc1c7d38fb50586fed18ea3015790091591e447c1518c8c7a0a0a5754d8c9d49a8d9f4ee9dba0b3b5224b9692327728f627e7c6682f9a7e996b6b3a8b6b748a348820c7720761412c064e3041ce282b5d4bd73d3bd3f33daea97ac2e540dd0a292dc8cd043c1f15ba2a7923b65bb910371b9a12141f9d02edf13ba2ade56857551e5e77244c54fd0e280746ebfe99bbbd655d56dcdc9ce08465565f4ee3bfca82d53eb3a6dac3e25c5f5ba646402e33fa77a0aff5b74ad8757e9ca972844aa37c520fcca7d3f5ab067bd369a8f467544d626c98e9f7118f0200e4465c903049c8c9e6ad1b24334b6fa6249716cab20037c309dd83db03b5640dddac3764a4f02cb1103863919fa7a1a06d6f600c37162911b7b252b87dc773f1927393f4a079f868edae1ae6328a8b1ed38e30050226e85d5dc1f879011b3c47c2f604719f9d01eff4f4b83e3c6b18bb452b1cac9b8a83de80b16e8208a3b7b58e1407cc061427cc0ff1560ce7a8f592d69a97504cad2dac01a2b53900c3e9e51ea58f727d0551e73bfb86b99a49a46dcf21c96340dc13804f20f6f9501c0e3b8a0963316fcc4607007f57bd084d64dec01200ce483468ff0040d525d1755b4d4206ff0095207c11dc67ff0019a18f56584f6daad9dade4211e39104a8ded9152b235cd8c530613229c8c1c8ef50472e81690ee00322b0c100f0debdbb7ca8111ace856371358cba85aa5cc407891ccf83f2ef4048b4ad2e59bf116769672c72f99dd1437239078e2824a4d3e1b94559234110e781839fa0a0561b38ad532a12319c86c6307e740a9732a3a00cac870cd8e0faf0681be8b6db965bb909df3c85806eeabced5a09523647e6e0fef419a6adf116daf7ac34be9dd1da686e7f1ca2e243b76320ce57df9ff1560cc3e3f470ff00c78255b842b35bc6c4af9b6e323d3e95467b6365f8dbcf062beb68c119595d8aaff6e282422e9899b4f6bb5d46cda2562a76316c1078f4a0859e1b9b762c0bf94f0e84feb4125a57505c58ea70dd5d0174a986d92b1c13f6f5a0de7a5be366877260b5d42dee2d2423124a487507ebdf15289dd3fac7a7bab6feded74d61733473acdb5a162142ff00313d81ed505fa58fc6d809380c1b9f5c502e0e05040ea367a85dea454de2ff00a610375b04c16c7a16ef8340b5f6930dce9375636acf6a278f04c5dd4f1dbf4a084e91d06f3a52dee62bbd4a2b882494ced3c8a448063b63b638fde803ab7ae749b2b3096d792c93c8c109b55dcd18ce3710473ffdd043dc758dc5869044565aa5dda4c3c2b7bc78c1f14e3963db03e7c0ab066bf1327d41ba76ca6bc48ecad24c456f6b0c87cf8e4bbfa138c0fa9aa3297c83dd4e28395811cf2680a5b93c7ed413cd1ff0f3c797b8031406645236b0508406f30e68ba49c051b97d0e0e7d28ad57e19f575c5be8f269515dac772877c11bc464dea7ba8c739ce78f9d3193bb8ebfea2bcbd6b5b6b8b58bb7f13c2f0ce31cf0deb4c0f2dbad6d743d2ee99efae752d6c02a86e0054524f6383c7ff94c0b6af274c75149a46a5a82c46f1e1479fc3190bd8156fbe7f4a960bf74e9d253f1167a3ac09e0856610e3041ec7f6c540f67b892cee7f8d18368232ef2af2508c7047cf340ead5bf130accc9b1186541e723d09ffc5033bbb1b82d74d6b37f1244daa1b38073df3f4a08eeb1d3b50d4fa6a5b4d32f12cef1902ee73e523d476fde8306eb0d3fabfa4ba92c278af67bb7281606472f90bdd58558253a6afb40ea1d62283a8b461a66a6f931cf6a7c2466f7cfb939e7b5515fbed3747b5eb8f06eb78d35080a2ec9719c76f98049a0b4ebdd37d1bad869acbf0b03c5c16b29444adf50ded41995f68564a263a66b31cd02be152505493f51c1a088bab69ad1bc179e320f07c37c8a0692b46c4995f0381db39a0b2fc34e971d57d4705bc8db6c50ef9dd97b81fcbf7381528f5ae97a1d8e996d1db69b0c7648855b10a81b80f43c739c54134147b9a036063279fb5046e957726a0f2cfe04915b06db1788305ffeac7a0a00d72f8d9c491c06337533050ac7185cf2df6a06da2da4293488f34973328c34aea428c9ec3eded40ee7d2ad249448f6b133820ee2833df3fde819ea96897461b05b87815f2ee919e5d47704fa039ab079b3e326b70eafd4ef6d6650d8e9ebf868b69c8247723efebf2aa280eb9193ebedc5002a124e015340018fb8fde82cf32b1603d0678cd02406dce3008e47ce81b499c331383c9c9f5a2e9c69377369f7d6f796a4acf148acb83fb511e91b3b3d0bab745b7d45acedd8e3732b71b1fd73f7a5a19eafd09a56a0a96b1c705b49c48510761ce4fcfbd4d0d752826b2b583476fc3daacb295b79d768de8a32b1e71f989e49f6a7d14dd1af5ba275a45b8b093c054492ea769092373765c1da4679fbd306e36ba9595fe9f0dcdbcc92c33e1579cf27d0d409ea178f68521b6b76926ee8a7853f7ff140bc768d78f6f73748d1cd103b543f0091cf6efc502f7319dac194371d8b6326829f0c501d7ae6fa568d5d4942c806d4db81839f53c8cd59456fae6e628749b5bab8b1865b08e4726588ec11e7f2e49071c93da9a31dd4341d675e9a5bad374f9858162d0b4ac70e18f0573df35a0c759f87bd53a404f174f965dfff00f479b1ef570576e34bd4b4cc0bdb3b9b7258a00e846e3f2a94376475cee4914af7ca9150685f09ba61efb52fc7dd69bf8eb7c158d1d0b47bb38f37efde968d6eeb4eb5e91d6ad25b660aee59974db6881690918e31ce39279e062a5a34bb57b88adedd1e379679065d80036679e6a07e8391bce7e940c659ef5afe1286de3b16f2b8903094b7b2fa7ce81eb380c4260ed193f2a0cd6fa5d4a4ea0fc7bdadcce923158a3039db83c038e3ef41a0e96b2ad8a35e009291b8a939d9f227e43bd590436bbd6fa269202c974b7123602c76e779624e00e29833bf897d493e896525dbcb2a6b5a9c3e1456b91b6d60cf989c7f31f7a60c02490961ebcf3eb541308e39e067b507007b96007a67fb50178f97eb4165ce18165c2927b773fad023202d9c8dbb7818ff003408300b87f2f1c107d0d0c15a4f2e339c90467f6a18bdfc2cea8ff4bd561b4b9ba686d6e64552c4f954e7d7e46a60f4688d240af1b2bc6cbf5047ca960617ba658de1b792f2d94a5ab33461b18524633fa1a81b5c8b5168967369d23c0e0a24622dc981d81c76aba29df0bb48d660d52fceb88d069f04aeb69130037127f37b9c0ed9a8350781240bbc06da72323b1f7a0eb8816e633192ebc8c9472a78fa50349b4c83c068e24f0ddbcc1c13b837be4d055b57e98b996d4db5b4a893dc1e6620b6ccf2c467efc504ce97a38d3f4d874bf09af6d46e2f25cb82724e791db15650a43f878b51fc34f3da8f132b6d6a98c80a39ff007e99aba249631b58b9047239ec3e55368aeeb7d2da6f52c0eb7f16e87f2c6e836ba90724ab7a67b55d115ac7c3e8aed2182def4c56a14096368959a423d77e3229a27b41e9d8343b01069c8a8dc9660aa3713df3c64d4a1c695d3d6b67a8cba94b9b8d4e61869e4e4a8c636a7f4afcaa09a485519caae19b966f7a0435196582c656b74df3e308beec7b50629375775b691ac5bdb6b16d6378779f019b00a31cf391c9c2f1daae0b35ef52f5374de88d77aa45a6cd25ddc0108694ee2188c28007603d6a0d16c92430a4b2ed3230dc401855cfa0a0a07c45d7b5db9d462e9ee960b14b2ee134ef8c850012147ec78ab0670b643a2efae753d72686e6e2da211db42176079c8e768f65e39f7aa332d6f58bbd635096f6fe6692695b24f603d801e82823cb900ee00e68006460051dfd680ed9f0c905b713d8d006d5f5419fa505a18f94e40501b1b81a04186d62402c87be3d6810b81290aea8467201231cd1749dbc437f9f1e201db3de8ba07dc0175c027f28a335b17c26f888d6b6d0e8fabf892a29c453b1e547f49f7a946d6424f08236491c833ee0835073294888894120700f0280813c40a6711bc8843e00fca7d3ef40e41dc081f9a811681c6f7565329185623b7e9de812b3bcf11ff0b74563bd50494cf120071b97e5fda80d7577046c9019d5669dbc340324eec67fb734103d5da96bf67a7cf0e916f6e2765f25ddc4c11107ab1c8c647cce2816d3ec7f0f6564cae6e67da375e6d52cc4af2e4fb13ed4145f899d47b3499f4bb6d46cda49b69b92921565c3648e3dd40c81cd5c0ae89f13ec246d3e379ed2d6da180b5d34849da1780b128e49271c9f4a60ba685d5fa36bc42d95c324ec7090cc9b1d87b81ed50588958977cacaaa3b9341c655f12348d1dcb8dc1946540f99a019e2134454eeda7bed3839cd052fe2136b536b5d3563a1ca53c49da4b9507198940ce7e5c9fbe281c6b7a974cf4ee4ea7242d76dc784a3c595b3e9b464e3f6ad0ac745ccbd4fadcbabea42da56959a382ce7460d6b1a93c01f97272093ebf6a82f1ad6af0e9da5cb3cecf6902216919f82aa3818c7a9f4c530649a9f5269ba7429d472239bc991a1b0d3c3152880f0f23039e7bf3de90635ab6a377aa5ebdcdecef2c9239e59f3827e5ed54302195fcc38cd01245395c1f5f4a05b606538e483c501b6939e3b5077860f3914165754c33e549000dbe87de813b820c27fa7baafb8a04a69c98e281e42618c795338033df1f3a06c03e4e029247007ad010093c35674da71f977640340081a190658e41c820f141b0fc33f8926c218b4ed609366a02249bb2d19ce3ea4528dbece68eead926b7916689c643a9e0d643387521fea2f693c2d6efc786ee46d9bfed3eff2a04669edf5295ff057a60bd865309246d3bbbedc1efef41d63a8dec9ab4fa7dd4510fc3c69234ca186e2d9c003b7a67bd034bad0a5bb96e25d575267889cc1b54446d9bd0a37bfbfbd02925945a72cba8dddc48b3f87b1e58f23c623f292bdb7fa7cf38a0a5750f54ebba56a9a67fc516b6d6fd3970ea9234677c8dc7f38f6e4640ce282d1ac4b16bfa72c1d2bad430cd1ba822061865f5007d3daac19cf547c189357d561bbd3eee683c62cd786e9b73337b8c7bd512bd39f06adedec2de0d5ae639da372e6485363107f97767b505cee755d03a5e58ac228659af123184b7b733322e38c91dbf5a943ab3d52e64b49ee755d2e64950e238e35f10c884e17cbe87dc540e6d7509a4f110e9f7566a471712850abf6ce463e6280bacea36fd33a4497f773cf32c698dcc4beee33938edc7ad05534aea683ae61d64c4d2a69b6b88d16d5ca5c303f3e386cf61db140e27b5e99e96b64bdd562b6b30aa36c6c37cac7dc9eec6b42c1a66a962fa70beb6b516d0cbe76322f86c78f6c66831bf8b5d5d2dfa35a5dce60b1933b6ce3c788769f2b331ec1b8fd2831b79649984b239773c1dc68129725c1c640e73400ec781d8fb1a03c4a85d0c8582640257bd01e51fc42236263c9c67be280429c6037eb405dbf5fd682c2a0bb976cf07d3fc5009279ef8ec4e68193a9902b28e7dc71fb501d95b098e0f6dd9e0d0049131019b047b8390281bb292484e47c8500c4f242c3076bf704704739a0be7c3febfbae9a5daf23cd017c7e19fb107bb67d0f6fd6837cd2757d1fab34f4f05e37dde630b1c3a91edf4f7159103d6eb7da65fdbdf59dadb5e2460ac876ed9e1c8c060f9efe9c8a0a75cfc42d5742d2ee5a7e9dbb494b6d6b9bc930cce4f940e3cd81ed4160e98f88315e689fff0022b57664199cc5196f0c7a164ef8f98cd0589baffa68590985eb15c0db1985839f6c2919340b69d03f5285bdd6f4bf021424db4329cb153fccc3d09c76a090d3340d2f479a7bab3b38e2924e5e451cfd280d7dafe936f6c5e4bd89813b02a36589ce318a0358dc35cc4e17f9bf234cdbb78fa0c607a7340e6cec20b1596610c6934b8323226379edda81da8dcb9ec40a042f50b5bb21645473b58b11dbd7bfca8304f8add5d67a9ea8ba5d8ea72c1a4d8a952f10f2c920e368cf71e99fad5833dd0754d6ed66bdb2e9a91a5babb2a310465a57c1ddc1038e7bd5171d3748b8d46ee1ff005298dc6a764c27d4eeaee7fe1c01795881c9e7804fe940dbe287c4b6d75a1b1d1c986d62277c91bf131f4c0f6fad0663737135d3b497124924871f98e7803007d2811dc5b83903dc0a0333f03be7de8122df2c9a05a11e5f51f7a05ce7071804fca8033e5da0734020b0183bb23e5416269577ed0e5323078ceeefdff6a03dbcd62914c2f629a47c622689800879e4fbd046f9d8a2a03e31385c0e73da8b83ca590947dcaead8208e73da8849b3e19ce704f7c5015586d006431f5cf61f3a04ee586ff002481c8fe6191408f0011eb8e30682774dea9bbb5784492ca6385832e1ca95e3d2834be9df8c312e2db5eb4375080337000f1303d18763591a469baef4d755989ec6f6dae5a23e20b599406dd8e080ddbed41272f4dd8caf1c86d163910f9595882a3d718a035edd695d3b6a926b57d0ac65b10b4e06eedd863bf141077fd7af2782bd3fa26a1a8891d57c630948c0279393dcd04cf5875258f4de9f0cb7b7b6d66d2b81ba752d85f5214724fed41036bd79d2fe319d7a8f4b9c81e58de2f04827b9ce09a07a3acecf54b790685ace8697606009e52c377b7f2e682b097d7d36acf0f55df5edbdc0977412468cb6ce3be10af3c63b9c8a0b0751f505be9690dd5d752436f62a3fe4c6448f3b7b0c64e38f615734651f107e3045ac42b67a7693018633b965bc1bc838ee173807bf7cd33065baaeb1a95f2c11dfcd2bc51fe48880aa3e8a062a8b059f595df4ae9a74de9e9ec499d43c97b1427c6e47e525bb63e4282ad3ea3712893c599dbc4259c1627713c927de81043950df97db1406da8411c92063be280230839627078e79a0390a71b5bb5003a8c1232338e4507025573e9fbd02a0e41dc0e680c3691cf714053bb34160895dc16f291d98d02322aa39f3e14707ffaa06f202a5bb0c7201f4a343aca51090497efdfbfce89840c8db8e46573923ff14410b00490d9f5c1a0425dd8ce4673e873cd0265e4dbe7041ed814009b8cbb8e5863bd07163b7716e0607b6698060b96b7b9478dc8643918247ee39a60b7e97f133a8b4e0c63d4ee597380923970a3ef4c0e13e25dfcfab457ba95bdbddb212016501867b9cfbfda982f907c74b282da34874a9048aa479c83838edc62982b7ac7c42d235cd67f15ac5b40c366418a2cb0c1c81e6f5e31db14c160d035de8cd4a3f18ea96562cc37359dfe9cac887fef039fd6b39446f56ea5d13a9dca4579a922496b1975b8d22dfc3566cf9557230703be715ac1431d4d2275325d7fae6b4f6f182a93ef1e32a9f41938f6a60afeb1a95c5fea53dccf772cf2c8c489240031f627e7565c0d67bbf160487c1801073bc0c31f91f953420f2bc8c7c52cc540032738a809905c0f4fa501940208e73df34028e703938a0577ae013f4a001300db4f03b71407461ce0502dca8c9c7dcf6a003fafcbdcd0070bc1e0fd734070db467b8a04cb9c9e68274b93bcb1daa40200ed4099765249ec476cf340849b8b264823bf34689ee009cb671df1409bc8e8b8e770e3ec68984d9c953cf97be2860b248caaebc107dc67f7a184c31232db88fd451031ce50e76039f5c8045026efb8f93279e0fd680b239504f0483d88ef409ee25bb90c79c0e050151c6e21b39ce783eb40adbcc2cefa17bdb61322387781c950e3dbdf9c8a066f28790b22e013db3dbef54726081e63c6460d34191b1bb0720f634060e7600412c781502409c8e3d7b500ed71dbef8ed40243f181c0a02e5d4e0fad006f644e4819e3b501f7e3049e7b501bc43b4e391da80558003392d40a23305e320d02e64cf998e1bf5a032b0c927b8e68049c8c8e71c6280377043118f4e680bbff00de0504ddbb3128371c1c64668024e59f3cd02521254e4fad1a2107e48fe6a6809ddb9e78a029e1463d05027ffc744a6c3857c7b1a205ff00e637fbf4a02b12b1794e39f4a02024e7249ed409924720906800005173fd7404989698ee39e4f7a04cf723d07a501fff0097ed406ffe36a018ff00281e99a037f4d0731f3bfd28007e53400ff99a810248c0cf140bc60123233cff008a0557f9beb4056eff007a07109243e79a03778b27bfbd02b128c27039a054001b818a06609de793da815006070283ffd9}\par}
+{\pard \ql \f0 \sa0 \li0 \fi0 lalune\par}
+{\pard \ql \f0 \sa180 \li0 \fi0 Here is a movie {\pict\jpegblip\picw20\pich22\picwgoal400\pichgoal440 ffd8ffe000104a46494600010101004800480000fffe0050546869732061727420697320696e20746865207075626c696320646f6d61696e2e204b6576696e204875676865732c206b6576696e68406569742e636f6d2c2053657074656d6265722031393935ffdb00430001010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101ffdb00430101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101ffc00011080016001403012200021101031101ffc4001a000100020301000000000000000000000000080905060a07ffc400231000010501000300010500000000000000060304050708020001090a11153976b7ffc400160101010100000000000000000000000000060800ffc400261101000102050109000000000000000000010200030405061121b33134365154717475b4ffda000c03010002110311003f00a90cf388f366a62aa720ed6ae07f96901f3831d973452b8cf36fe3570fc908e46d466433e5dd954f2e96992d9e498c7753faa44916e016ca91cc7d88b38fe60a5b97737defcbcc539c98d336a57f4fc2ca9a486bf07ab575ad9a3af4df221d8215e36df86c4504ff0024574551b3d687ee0575757b3ad64e311ee62bd94158d37e24198c43973099f1fc0c41614d950246513a081abf76cfe7061f6863281e6352fd1670949c148dd6dfb0d25f5b3689b1d5c965b0eacbf4e0932ad28e22ab9ae945633f4744bd3c8cee0a7fdf085b9000f449c5f7afa30b83e0b6fd7b0c8429c9467ff9715347c891e25fa24a205861aa715e6a09bd0488237dc2723414d9891381524e8ca7c0894664f835653631ab55ee7e3de433e4ff001b30949124e4c10c8b6ad0a479b3f9c937b2cf5bc0095ad600a0a41a0e9faee174a1c605e161c6c7a313539650b0113190f1a8368e60d5b24f30ff008ea7f0bf867fa6595feeb6978f1fe0f9c26177f4d63a51a9235184750e7d18811339cd000000c75f000e00380380ae390c350def826ed42ad051fa6f501c50f9b699c3b69cbeb76476d202bf3ac985b6e0e968be66572893e6a744540bd9722e5c87956848629bc2559306bd113e8653d3b6aff651dfad7a3ac8b02958cba02a93ccf525757039bae6cff090e1d90688e8aa233ee86a4c4a3e0586d6b2340522e47dcb7d0046d8a5acb05a123ee25d2b230b2ada6e2e2f9ede3c05202520ec2487b0d56562529d8b3393bca76adca4ec1bca508abb001babc007915d84fe3dd14e207e3c62f8379da2a3b861fb6629d28dba53b6ea388ebfed866bf6dfb553455e91ed547ae92e9445253a4fdf3efb4f8ebdfbe7d3c78f1ee0bb9e13e358e942a4ed49e22cff00eeb35fdd7ebfffd9} icon.\par}
 {\pard \qc \f0 \sa180 \li0 \fi0 \emdash\emdash\emdash\emdash\emdash\par}
-{\pard \ql \f0 \sa180 \li0 \fi0 \b \fs36 Footnotes\par}
+{\pard \ql \f0 \sa180 \li0 \fi0 \outlinelevel0 \b \fs36 Footnotes\par}
 {\pard \ql \f0 \sa180 \li0 \fi0 Here is a footnote reference,{\super\chftn}{\*\footnote\chftn\~\plain\pard {\pard \ql \f0 \sa180 \li0 \fi0 Here is the footnote. It can go anywhere after the footnote reference. It need not be placed at the end of the document.\par}
 } and another.{\super\chftn}{\*\footnote\chftn\~\plain\pard {\pard \ql \f0 \sa180 \li0 \fi0 Here\u8217's the long note. This one contains multiple blocks.\par}
 {\pard \ql \f0 \sa180 \li0 \fi0 Subsequent blocks are indented to show that they belong to the footnote (as with list items).\par}
diff --git a/test/writer.tei b/test/writer.tei
--- a/test/writer.tei
+++ b/test/writer.tei
@@ -8,8 +8,8 @@
       <author>Anonymous</author>
     </titleStmt>
     <publicationStmt>
-      <p></p>
-          </publicationStmt>
+      <date>July 17, 2006</date>
+    </publicationStmt>
     <sourceDesc>
       <p>Produced by pandoc.</p>
     </sourceDesc>
@@ -20,15 +20,15 @@
 <p>This is a set of tests for pandoc. Most of them are adapted from John
 Gruber’s markdown test suite.</p>
 <milestone unit="undefined" type="separator" rendition="line" />
-<div type="level1" id="headers">
+<div type="level1" xml:id="headers">
   <head>Headers</head>
-  <div type="level2" id="level-2-with-an-embedded-link">
+  <div type="level2" xml:id="level-2-with-an-embedded-link">
     <head>Level 2 with an <ref target="/url">embedded link</ref></head>
-    <div type="level3" id="level-3-with-emphasis">
+    <div type="level3" xml:id="level-3-with-emphasis">
       <head>Level 3 with <hi rendition="simple:italic">emphasis</hi></head>
-      <div type="level4" id="level-4">
+      <div type="level4" xml:id="level-4">
         <head>Level 4</head>
-        <div type="level5" id="level-5">
+        <div type="level5" xml:id="level-5">
           <head>Level 5</head>
           <p></p>
         </div>
@@ -36,32 +36,32 @@
     </div>
   </div>
 </div>
-<div type="level1" id="level-1">
+<div type="level1" xml:id="level-1">
   <head>Level 1</head>
-  <div type="level2" id="level-2-with-emphasis">
+  <div type="level2" xml:id="level-2-with-emphasis">
     <head>Level 2 with <hi rendition="simple:italic">emphasis</hi></head>
-    <div type="level3" id="level-3">
+    <div type="level3" xml:id="level-3">
       <head>Level 3</head>
       <p>with no blank line</p>
     </div>
   </div>
-  <div type="level2" id="level-2">
+  <div type="level2" xml:id="level-2">
     <head>Level 2</head>
     <p>with no blank line</p>
     <milestone unit="undefined" type="separator" rendition="line" />
   </div>
 </div>
-<div type="level1" id="paragraphs">
+<div type="level1" xml:id="paragraphs">
   <head>Paragraphs</head>
   <p>Here’s a regular paragraph.</p>
-  <p>In Markdown 1.0.0 and earlier. Version 8. This line turns into a list
-  item. Because a hard-wrapped line in the middle of a paragraph looked like a
-  list item.</p>
+  <p>In Markdown 1.0.0 and earlier. Version 8. This line turns into a list item.
+  Because a hard-wrapped line in the middle of a paragraph looked like a list
+  item.</p>
   <p>Here’s one with a bullet. * criminey.</p>
   <p>There should be a hard line break<lb />here.</p>
   <milestone unit="undefined" type="separator" rendition="line" />
 </div>
-<div type="level1" id="block-quotes">
+<div type="level1" xml:id="block-quotes">
   <head>Block Quotes</head>
   <p>E-mail style:</p>
   <quote>
@@ -95,7 +95,7 @@
   <p>And a following paragraph.</p>
   <milestone unit="undefined" type="separator" rendition="line" />
 </div>
-<div type="level1" id="code-blocks">
+<div type="level1" xml:id="code-blocks">
   <head>Code Blocks</head>
   <p>Code:</p>
   <ab type='codeblock '>
@@ -115,9 +115,9 @@
 </ab>
   <milestone unit="undefined" type="separator" rendition="line" />
 </div>
-<div type="level1" id="lists">
+<div type="level1" xml:id="lists">
   <head>Lists</head>
-  <div type="level2" id="unordered">
+  <div type="level2" xml:id="unordered">
     <head>Unordered</head>
     <p>Asterisks tight:</p>
     <list type="unordered">
@@ -192,7 +192,7 @@
       </item>
     </list>
   </div>
-  <div type="level2" id="ordered">
+  <div type="level2" xml:id="ordered">
     <head>Ordered</head>
     <p>Tight:</p>
     <list type="ordered:arabic">
@@ -257,7 +257,7 @@
       </item>
     </list>
   </div>
-  <div type="level2" id="nested">
+  <div type="level2" xml:id="nested">
     <head>Nested</head>
     <list type="unordered">
       <item>
@@ -321,7 +321,7 @@
       </item>
     </list>
   </div>
-  <div type="level2" id="tabs-and-spaces">
+  <div type="level2" xml:id="tabs-and-spaces">
     <head>Tabs and spaces</head>
     <list type="unordered">
       <item>
@@ -340,7 +340,7 @@
       </item>
     </list>
   </div>
-  <div type="level2" id="fancy-list-markers">
+  <div type="level2" xml:id="fancy-list-markers">
     <head>Fancy list markers</head>
     <list type="ordered:arabic">
       <item n="2">
@@ -408,7 +408,7 @@
     <milestone unit="undefined" type="separator" rendition="line" />
   </div>
 </div>
-<div type="level1" id="definition-lists">
+<div type="level1" xml:id="definition-lists">
   <head>Definition Lists</head>
   <p>Tight using spaces:</p>
   <list type="definition">
@@ -554,7 +554,7 @@
     </item>
   </list>
 </div>
-<div type="level1" id="html-blocks">
+<div type="level1" xml:id="html-blocks">
   <head>HTML Blocks</head>
   <p>Simple block on one line:</p>
   <p>foo</p>
@@ -592,7 +592,7 @@
   <p>Hr’s:</p>
   <milestone unit="undefined" type="separator" rendition="line" />
 </div>
-<div type="level1" id="inline-markup">
+<div type="level1" xml:id="inline-markup">
   <head>Inline Markup</head>
   <p>This is <hi rendition="simple:italic">emphasized</hi>, and so
   <hi rendition="simple:italic">is this</hi>.</p>
@@ -625,15 +625,15 @@
   spaces: a^b c^d, a~b c~d.</p>
   <milestone unit="undefined" type="separator" rendition="line" />
 </div>
-<div type="level1" id="smart-quotes-ellipses-dashes">
+<div type="level1" xml:id="smart-quotes-ellipses-dashes">
   <head>Smart quotes, ellipses, dashes</head>
   <p><quote>Hello,</quote> said the spider. <quote><quote>Shelob</quote> is my
   name.</quote></p>
   <p><quote>A</quote>, <quote>B</quote>, and <quote>C</quote> are letters.</p>
-  <p><quote>Oak,</quote> <quote>elm,</quote> and <quote>beech</quote> are
-  names of trees. So is <quote>pine.</quote></p>
-  <p><quote>He said, <quote>I want to go.</quote></quote> Were you alive in
-  the 70’s?</p>
+  <p><quote>Oak,</quote> <quote>elm,</quote> and <quote>beech</quote> are names
+  of trees. So is <quote>pine.</quote></p>
+  <p><quote>He said, <quote>I want to go.</quote></quote> Were you alive in the
+  70’s?</p>
   <p>Here is some quoted <quote><seg type="code">code</seg></quote> and a
   <quote><ref target="http://example.com/?foo=1&amp;bar=2">quoted
   link</ref></quote>.</p>
@@ -642,7 +642,7 @@
   <p>Ellipses…and…and….</p>
   <milestone unit="undefined" type="separator" rendition="line" />
 </div>
-<div type="level1" id="latex">
+<div type="level1" xml:id="latex">
   <head>LaTeX</head>
   <list type="unordered">
     <item>
@@ -694,7 +694,7 @@
   <p>Here’s a LaTeX table:</p>
   <milestone unit="undefined" type="separator" rendition="line" />
 </div>
-<div type="level1" id="special-characters">
+<div type="level1" xml:id="special-characters">
   <head>Special Characters</head>
   <p>Here is some unicode:</p>
   <list type="unordered">
@@ -737,9 +737,9 @@
   <p>Minus: -</p>
   <milestone unit="undefined" type="separator" rendition="line" />
 </div>
-<div type="level1" id="links">
+<div type="level1" xml:id="links">
   <head>Links</head>
-  <div type="level2" id="explicit">
+  <div type="level2" xml:id="explicit">
     <head>Explicit</head>
     <p>Just a <ref target="/url/">URL</ref>.</p>
     <p><ref target="/url/">URL and title</ref>.</p>
@@ -751,7 +751,7 @@
     <p>Email link (nobody@nowhere.net)</p>
     <p><ref target="">Empty</ref>.</p>
   </div>
-  <div type="level2" id="reference">
+  <div type="level2" xml:id="reference">
     <head>Reference</head>
     <p>Foo <ref target="/url/">bar</ref>.</p>
     <p>With <ref target="/url/">embedded [brackets]</ref>.</p>
@@ -766,7 +766,7 @@
     <p>Foo <ref target="/url/">bar</ref>.</p>
     <p>Foo <ref target="/url/">biz</ref>.</p>
   </div>
-  <div type="level2" id="with-ampersands">
+  <div type="level2" xml:id="with-ampersands">
     <head>With ampersands</head>
     <p>Here’s a <ref target="http://example.com/?foo=1&amp;bar=2">link with an
     ampersand in the URL</ref>.</p>
@@ -776,7 +776,7 @@
     <p>Here’s an <ref target="/script?foo=1&amp;bar=2">inline link in pointy
     braces</ref>.</p>
   </div>
-  <div type="level2" id="autolinks">
+  <div type="level2" xml:id="autolinks">
     <head>Autolinks</head>
     <p>With an ampersand:
     <ref target="http://example.com/?foo=1&amp;bar=2">http://example.com/?foo=1&amp;bar=2</ref></p>
@@ -804,25 +804,26 @@
     <milestone unit="undefined" type="separator" rendition="line" />
   </div>
 </div>
-<div type="level1" id="images">
+<div type="level1" xml:id="images">
   <head>Images</head>
   <p>From <quote>Voyage dans la Lune</quote> by Georges Melies (1902):</p>
   <p><figure>
     <head>lalune</head>
     <graphic url="lalune.jpg" />
-    <figDesc>fig:Voyage dans la Lune</figDesc>
+    <figDesc>Voyage dans la Lune</figDesc>
   </figure></p>
+  <p>lalune</p>
   <p>Here is a movie <figure>
     <head>movie</head>
     <graphic url="movie.jpg" />
   </figure> icon.</p>
   <milestone unit="undefined" type="separator" rendition="line" />
 </div>
-<div type="level1" id="footnotes">
+<div type="level1" xml:id="footnotes">
   <head>Footnotes</head>
   <p>Here is a footnote reference,<note>
-    <p>Here is the footnote. It can go anywhere after the footnote reference.
-    It need not be placed at the end of the document.</p>
+    <p>Here is the footnote. It can go anywhere after the footnote reference. It
+    need not be placed at the end of the document.</p>
   </note> and another.<note>
     <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
@@ -830,8 +831,8 @@
     <ab type='codeblock '>
   { &lt;code&gt; }
 </ab>
-    <p>If you want, you can indent every line, but you can also be lazy and
-    just indent the first line of each block.</p>
+    <p>If you want, you can indent every line, but you can also be lazy and just
+    indent the first line of each block.</p>
   </note> This should <hi rendition="simple:italic">not</hi> be a footnote
   reference, because it contains a space.[^my note] Here is an inline
   note.<note>
diff --git a/test/writer.texinfo b/test/writer.texinfo
--- a/test/writer.texinfo
+++ b/test/writer.texinfo
@@ -1,29 +1,13 @@
-\input texinfo
+\input texinfo  @c -*-texinfo-*-
+@settitle Pandoc Test Suite
+
 @documentencoding UTF-8
 
 @macro textstrikeout{text}
 ~~\text\~~
 @end macro
 
-@macro textsubscript{text}
-@iftex
-@textsubscript{\text\}
-@end iftex
 @ifnottex
-_@{\text\@}
-@end ifnottex
-@end macro
-
-@macro textsuperscript{text}
-@iftex
-@textsuperscript{\text\}
-@end iftex
-@ifnottex
-^@{\text\@}
-@end ifnottex
-@end macro
-
-@ifnottex
 @paragraphindent 0
 @end ifnottex
 @titlepage
@@ -45,6 +29,7 @@
 @ifnottex
 ------------------------------------------------------------------------
 @end ifnottex
+
 @menu
 * Headers::
 * Level 1::
@@ -65,53 +50,50 @@
 
 @node Headers
 @chapter Headers
-@anchor{#headers}
+
 @menu
-* Level 2 with an embedded link::
+* Level 2 with an @uref{/url,embedded link}::
 @end menu
 
-@node Level 2 with an embedded link
+@node Level 2 with an @uref{/url,embedded link}
 @section Level 2 with an @uref{/url,embedded link}
-@anchor{#level-2-with-an-embedded-link}
+
 @menu
-* Level 3 with emphasis::
+* Level 3 with @emph{emphasis}::
 @end menu
 
-@node Level 3 with emphasis
+@node Level 3 with @emph{emphasis}
 @subsection Level 3 with @emph{emphasis}
-@anchor{#level-3-with-emphasis}
+
 @menu
 * Level 4::
 @end menu
 
 @node Level 4
 @subsubsection Level 4
-@anchor{#level-4}
 Level 5
 
 @node Level 1
 @chapter Level 1
-@anchor{#level-1}
+
 @menu
-* Level 2 with emphasis::
+* Level 2 with @emph{emphasis}::
 * Level 2::
 @end menu
 
-@node Level 2 with emphasis
+@node Level 2 with @emph{emphasis}
 @section Level 2 with @emph{emphasis}
-@anchor{#level-2-with-emphasis}
+
 @menu
 * Level 3::
 @end menu
 
 @node Level 3
 @subsection Level 3
-@anchor{#level-3}
 with no blank line
 
 @node Level 2
 @section Level 2
-@anchor{#level-2}
 with no blank line
 
 @iftex
@@ -123,7 +105,6 @@
 
 @node Paragraphs
 @chapter Paragraphs
-@anchor{#paragraphs}
 Here's a regular paragraph.
 
 In Markdown 1.0.0 and earlier. Version 8. This line turns into a list item.
@@ -144,7 +125,6 @@
 
 @node Block Quotes
 @chapter Block Quotes
-@anchor{#block-quotes}
 E-mail style:
 
 @quotation
@@ -190,7 +170,6 @@
 
 @node Code Blocks
 @chapter Code Blocks
-@anchor{#code-blocks}
 Code:
 
 @verbatim
@@ -220,7 +199,7 @@
 
 @node Lists
 @chapter Lists
-@anchor{#lists}
+
 @menu
 * Unordered::
 * Ordered::
@@ -231,7 +210,6 @@
 
 @node Unordered
 @section Unordered
-@anchor{#unordered}
 Asterisks tight:
 
 @itemize
@@ -309,7 +287,6 @@
 
 @node Ordered
 @section Ordered
-@anchor{#ordered}
 Tight:
 
 @enumerate 
@@ -378,7 +355,6 @@
 
 @node Nested
 @section Nested
-@anchor{#nested}
 @itemize
 @item
 Tab
@@ -439,7 +415,6 @@
 
 @node Tabs and spaces
 @section Tabs and spaces
-@anchor{#tabs-and-spaces}
 @itemize
 @item
 this is a list item indented with tabs
@@ -460,10 +435,10 @@
 
 @node Fancy list markers
 @section Fancy list markers
-@anchor{#fancy-list-markers}
 @enumerate 2
 @item
 begins with 2
+
 @item
 and now 3
 
@@ -536,7 +511,6 @@
 
 @node Definition Lists
 @chapter Definition Lists
-@anchor{#definition-lists}
 Tight using spaces:
 
 @table @asis
@@ -658,7 +632,6 @@
 
 @node HTML Blocks
 @chapter HTML Blocks
-@anchor{#html-blocks}
 Simple block on one line:
 
 foo
@@ -719,7 +692,6 @@
 
 @node Inline Markup
 @chapter Inline Markup
-@anchor{#inline-markup}
 This is @emph{emphasized}, and so @emph{is this}.
 
 This is @strong{strong}, and so @strong{is this}.
@@ -738,14 +710,12 @@
 
 @textstrikeout{This is @emph{strikeout}.}
 
-Superscripts: a@textsuperscript{bc}d a@textsuperscript{@emph{hello}}
-a@textsuperscript{hello@ there}.
+Superscripts: a@sup{bc}d a@sup{@emph{hello}} a@sup{hello@ there}.
 
-Subscripts: H@textsubscript{2}O, H@textsubscript{23}O,
-H@textsubscript{many@ of@ them}O.
+Subscripts: H@sub{2}O, H@sub{23}O, H@sub{many@ of@ them}O.
 
-These should not be superscripts or subscripts, because of the unescaped
-spaces: a^b c^d, a~b c~d.
+These should not be superscripts or subscripts, because of the unescaped spaces:
+a^b c^d, a~b c~d.
 
 @iftex
 @bigskip@hrule@bigskip
@@ -756,7 +726,6 @@
 
 @node Smart quotes ellipses dashes
 @chapter Smart quotes, ellipses, dashes
-@anchor{#smart-quotes-ellipses-dashes}
 ``Hello,'' said the spider. ```Shelob' is my name.''
 
 `A', `B', and `C' are letters.
@@ -783,7 +752,6 @@
 
 @node LaTeX
 @chapter LaTeX
-@anchor{#latex}
 @itemize
 @item
 @tex
@@ -838,7 +806,6 @@
 
 @node Special Characters
 @chapter Special Characters
-@anchor{#special-characters}
 Here is some unicode:
 
 @itemize
@@ -905,7 +872,7 @@
 
 @node Links
 @chapter Links
-@anchor{#links}
+
 @menu
 * Explicit::
 * Reference::
@@ -915,7 +882,6 @@
 
 @node Explicit
 @section Explicit
-@anchor{#explicit}
 Just a @uref{/url/,URL}.
 
 @uref{/url/,URL and title}.
@@ -936,7 +902,6 @@
 
 @node Reference
 @section Reference
-@anchor{#reference}
 Foo @uref{/url/,bar}.
 
 With @uref{/url/,embedded [brackets]}.
@@ -961,7 +926,6 @@
 
 @node With ampersands
 @section With ampersands
-@anchor{#with-ampersands}
 Here's a @uref{http://example.com/?foo=1&bar=2,link with an ampersand in the
 URL}.
 
@@ -973,7 +937,6 @@
 
 @node Autolinks
 @section Autolinks
-@anchor{#autolinks}
 With an ampersand: @url{http://example.com/?foo=1&bar=2}
 
 @itemize
@@ -985,7 +948,7 @@
 It should.
 @end itemize
 
-An e-mail address: @uref{mailto:nobody@@nowhere.net,nobody@@nowhere.net}
+An e-mail address: @uref{mailto:nobody@@nowhere.net,nobody@@nowherenet}
 
 @quotation
 Blockquoted: @url{http://example.com/}
@@ -1005,14 +968,12 @@
 
 @node Images
 @chapter Images
-@anchor{#images}
 From ``Voyage dans la Lune'' by Georges Melies (1902):
 
 @float
 @image{lalune,,,lalune,jpg}
 @caption{lalune}
 @end float
-
 Here is a movie @image{movie,,,movie,jpg} icon.
 
 @iftex
@@ -1024,25 +985,22 @@
 
 @node Footnotes
 @chapter Footnotes
-@anchor{#footnotes}
-Here is a footnote reference,@footnote{Here is the footnote. It can go
-anywhere after the footnote reference. It need not be placed at the end of the
-document.} and another.@footnote{Here's the long note. This one contains
-multiple blocks.
+Here is a footnote reference,@footnote{Here is the footnote. It can go anywhere
+after the footnote reference. It need not be placed at the end of the document.}
+and another.@footnote{Here's the long note. This one contains multiple blocks.
 
-Subsequent blocks are indented to show that they belong to the footnote (as
-with list items).
+Subsequent blocks are indented to show that they belong to the footnote (as with
+list items).
 
 @verbatim
   { <code> }
 @end verbatim
 
-If you want, you can indent every line, but you can also be lazy and just
-indent the first line of each block.} This should @emph{not} be a footnote
-reference, because it contains a space.[^my note] Here is an inline
-note.@footnote{This is @emph{easier} to type. Inline notes may contain
-@uref{http://google.com,links} and @code{]} verbatim characters, as well as
-[bracketed text].}
+If you want, you can indent every line, but you can also be lazy and just indent
+the first line of each block.} This should @emph{not} be a footnote reference,
+because it contains a space.[^my note] Here is an inline note.@footnote{This is
+@emph{easier} to type. Inline notes may contain @uref{http://google.com,links}
+and @code{]} verbatim characters, as well as [bracketed text].}
 
 @quotation
 Notes can go in quotes.@footnote{In quote.}
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;">
@@ -523,13 +523,13 @@
 h1(#latex). LaTeX
 
 * 
-* <span class="math">2+2=4</math>
-* <span class="math">x \in y</math>
-* <span class="math">\alpha \wedge \omega</math>
-* <span class="math">223</math>
-* <span class="math">p</math>&#45;Tree
-* Here's some display math: <span class="math">\frac{d}{dx}f(x)=\lim_{h\to 0}\frac{f(x+h)-f(x)}{h}</math>
-* Here's one that has a line break in it: <span class="math">\alpha + \omega \times x^2</math>.
+* <span class="math">2+2=4</span>
+* <span class="math">x \in y</span>
+* <span class="math">\alpha \wedge \omega</span>
+* <span class="math">223</span>
+* <span class="math">p</span>&#45;Tree
+* Here's some display math: <span class="math">\frac{d}{dx}f(x)=\lim_{h\to 0}\frac{f(x+h)-f(x)}{h}</span>
+* Here's one that has a line break in it: <span class="math">\alpha + \omega \times x^2</span>.
 
 These shouldn't be math:
 
@@ -660,7 +660,7 @@
 * "$":http://example.com/
 * It should.
 
-An e&#45;mail address: "nobody&#64;nowhere.net":mailto:nobody@nowhere.net
+An e&#45;mail address: "(email)nobody&#64;nowhere.net":mailto:nobody@nowhere.net
 
 bq. Blockquoted: "$":http://example.com/
 
@@ -677,8 +677,17 @@
 
 From "Voyage dans la Lune" by Georges Melies (1902):
 
-!lalune.jpg(Voyage dans la Lune)!
+<figure>
+
+<figcaption>
+
 lalune
+
+</figcaption>
+
+!lalune.jpg(Voyage dans la Lune)!
+
+</figure>
 
 Here is a movie !movie.jpg(movie)! icon.
 
diff --git a/test/writer.typst b/test/writer.typst
new file mode 100644
--- /dev/null
+++ b/test/writer.typst
@@ -0,0 +1,872 @@
+#let horizontalrule = line(start: (25%,0%), end: (75%,0%))
+
+#show terms.item: it => block(breakable: false)[
+  #text(weight: "bold")[#it.term]
+  #block(inset: (left: 1.5em, top: -0.4em))[#it.description]
+]
+
+#set table(
+  inset: 6pt,
+  stroke: none
+)
+
+#show figure.where(
+  kind: table
+): set figure.caption(position: top)
+
+#show figure.where(
+  kind: image
+): set figure.caption(position: bottom)
+
+#let content-to-string(content) = {
+  if content.has("text") {
+    content.text
+  } else if content.has("children") {
+    content.children.map(content-to-string).join("")
+  } else if content.has("body") {
+    content-to-string(content.body)
+  } else if content == [ ] {
+    " "
+  }
+}
+#let conf(
+  title: none,
+  subtitle: none,
+  authors: (),
+  keywords: (),
+  date: none,
+  abstract-title: none,
+  abstract: none,
+  thanks: none,
+  cols: 1,
+  margin: (x: 1.25in, y: 1.25in),
+  paper: "us-letter",
+  lang: "en",
+  region: "US",
+  font: none,
+  fontsize: 11pt,
+  mathfont: none,
+  codefont: none,
+  linestretch: 1,
+  sectionnumbering: none,
+  linkcolor: none,
+  citecolor: none,
+  filecolor: none,
+  pagenumbering: "1",
+  doc,
+) = {
+  set document(
+    title: title,
+    keywords: keywords,
+  )
+  set document(
+      author: authors.map(author => content-to-string(author.name)).join(", ", last: " & "),
+  ) if authors != none and authors != ()
+  set page(
+    paper: paper,
+    margin: margin,
+    numbering: pagenumbering,
+    columns: cols
+  )
+
+  set par(
+    justify: true,
+    leading: linestretch * 0.65em
+  )
+  set text(lang: lang,
+           region: region,
+           size: fontsize)
+
+  set text(font: font) if font != none
+  show math.equation: set text(font: mathfont) if mathfont != none
+  show raw: set text(font: codefont) if codefont != none
+
+  set heading(numbering: sectionnumbering)
+
+  show link: set text(fill: rgb(content-to-string(linkcolor))) if linkcolor != none
+  show ref: set text(fill: rgb(content-to-string(citecolor))) if citecolor != none
+  show link: this => {
+    if filecolor != none and type(this.dest) == label {
+      text(this, fill: rgb(content-to-string(filecolor)))
+    } else {
+      text(this)
+    }
+  }
+
+  if title != none {
+    place(top, float: true, scope: "parent", clearance: 4mm, block(below: 1em, width: 100%)[
+      #if title != none {
+        align(center, block[
+            #text(weight: "bold", size: 1.5em, hyphenate: false)[#title #if thanks != none {
+                footnote(thanks, numbering: "*")
+                counter(footnote).update(n => n - 1)
+              }]
+            #(
+              if subtitle != none {
+                parbreak()
+                text(weight: "bold", size: 1.25em, hyphenate: false)[#subtitle]
+              }
+             )])
+      }
+
+      #if authors != none and authors != [] {
+        let count = authors.len()
+        let ncols = calc.min(count, 3)
+        grid(
+          columns: (1fr,) * ncols,
+          row-gutter: 1.5em,
+          ..authors.map(author => align(center)[
+            #author.name \
+            #author.affiliation \
+            #author.email
+          ])
+        )
+      }
+
+      #if date != none {
+        align(center)[#block(inset: 1em)[
+            #date
+          ]]
+      }
+
+      #if abstract != none {
+        block(inset: 2em)[
+          #text(weight: "semibold")[#abstract-title] #h(1em) #abstract
+        ]
+      }
+    ])
+  }
+  doc
+}
+#show: doc => conf(
+  title: [Pandoc Test Suite],
+  authors: (
+    ( name: [John MacFarlane],
+      affiliation: "",
+      email: "" ),
+    ( name: [Anonymous],
+      affiliation: "",
+      email: "" ),
+    ),
+  date: [July 17, 2006],
+  abstract-title: [Abstract],
+  pagenumbering: "1",
+  cols: 1,
+  doc,
+)
+
+
+This is a set of tests for pandoc. Most of them are adapted from John Gruber's
+markdown test suite.
+
+#horizontalrule
+
+= Headers
+<headers>
+== Level 2 with an #link("/url")[embedded link]
+<level-2-with-an-embedded-link>
+=== Level 3 with #emph[emphasis]
+<level-3-with-emphasis>
+==== Level 4
+<level-4>
+===== Level 5
+<level-5>
+= Level 1
+<level-1>
+== Level 2 with #emph[emphasis]
+<level-2-with-emphasis>
+=== Level 3
+<level-3>
+with no blank line
+
+== Level 2
+<level-2>
+with no blank line
+
+#horizontalrule
+
+= Paragraphs
+<paragraphs>
+Here's a regular paragraph.
+
+In Markdown 1.0.0 and earlier. Version 8. This line turns into a list item.
+Because a hard-wrapped line in the middle of a paragraph looked like a list
+item.
+
+Here's one with a bullet. \* criminey.
+
+There should be a hard line break \ here.
+
+#horizontalrule
+
+= Block Quotes
+<block-quotes>
+E-mail style:
+
+#quote(block: true)[
+This is a block quote. It is pretty short.
+]
+
+#quote(block: true)[
+Code in a block quote:
+
+```
+sub status {
+    print "working";
+}
+```
+
+A list:
+
++ item one
++ item two
+
+Nested block quotes:
+
+#quote(block: true)[
+nested
+]
+
+#quote(block: true)[
+nested
+]
+]
+
+This should not be a block quote: 2 \> 1.
+
+And a following paragraph.
+
+#horizontalrule
+
+= Code Blocks
+<code-blocks>
+Code:
+
+```
+---- (should be four hyphens)
+
+sub status {
+    print "working";
+}
+
+this code block is indented by one tab
+```
+
+And:
+
+```
+    this code block is indented by two tabs
+
+These should not be escaped:  \$ \\ \> \[ \{
+```
+
+#horizontalrule
+
+= Lists
+<lists>
+== Unordered
+<unordered>
+Asterisks tight:
+
+- asterisk 1
+- asterisk 2
+- asterisk 3
+
+Asterisks loose:
+
+- asterisk 1
+
+- asterisk 2
+
+- asterisk 3
+
+Pluses tight:
+
+- Plus 1
+- Plus 2
+- Plus 3
+
+Pluses loose:
+
+- Plus 1
+
+- Plus 2
+
+- Plus 3
+
+Minuses tight:
+
+- Minus 1
+- Minus 2
+- Minus 3
+
+Minuses loose:
+
+- Minus 1
+
+- Minus 2
+
+- Minus 3
+
+== Ordered
+<ordered>
+Tight:
+
++ First
++ Second
++ Third
+
+and:
+
++ One
++ Two
++ Three
+
+Loose using tabs:
+
++ First
+
++ Second
+
++ Third
+
+and using spaces:
+
++ One
+
++ Two
+
++ Three
+
+Multiple paragraphs:
+
++ Item 1, graf one.
+
+  Item 1. graf two. The quick brown fox jumped over the lazy dog's back.
+
++ Item 2.
+
++ Item 3.
+
+== Nested
+<nested>
+- Tab
+  - Tab
+    - Tab
+
+Here's another:
+
++ First
++ Second:
+  - Fee
+  - Fie
+  - Foe
++ Third
+
+Same thing but with paragraphs:
+
++ First
+
++ Second:
+
+  - Fee
+  - Fie
+  - Foe
+
++ Third
+
+== Tabs and spaces
+<tabs-and-spaces>
+- this is a list item indented with tabs
+
+- this is a list item indented with spaces
+
+  - this is an example list item indented with tabs
+
+  - this is an example list item indented with spaces
+
+== Fancy list markers
+<fancy-list-markers>
+#block[
+#set enum(numbering: "(1)", start: 2)
++ begins with 2
+
++ and now 3
+
+  with a continuation
+
+  #block[
+  #set enum(numbering: "i.", start: 4)
+  + sublist with roman numerals, starting with 4
+  + more items
+    #block[
+    #set enum(numbering: "(A)", start: 1)
+    + a subsublist
+    + a subsublist
+    ]
+  ]
+]
+
+Nesting:
+
+#block[
+#set enum(numbering: "A.", start: 1)
++ Upper Alpha
+  #block[
+  #set enum(numbering: "I.", start: 1)
+  + Upper Roman.
+    #block[
+    #set enum(numbering: "(1)", start: 6)
+    + Decimal start with 6
+      #block[
+      #set enum(numbering: "a)", start: 3)
+      + Lower alpha with paren
+      ]
+    ]
+  ]
+]
+
+Autonumbering:
+
++ Autonumber.
++ More.
+  + Nested.
+
+Should not be a list item:
+
+M.A.~2007
+
+B. Williams
+
+#horizontalrule
+
+= Definition Lists
+<definition-lists>
+Tight using spaces:
+
+/ apple: #block[
+red fruit
+]
+
+/ orange: #block[
+orange fruit
+]
+
+/ banana: #block[
+yellow fruit
+]
+
+Tight using tabs:
+
+/ apple: #block[
+red fruit
+]
+
+/ orange: #block[
+orange fruit
+]
+
+/ banana: #block[
+yellow fruit
+]
+
+Loose:
+
+/ apple: #block[
+red fruit
+]
+
+/ orange: #block[
+orange fruit
+]
+
+/ banana: #block[
+yellow fruit
+]
+
+Multiple blocks with italics:
+
+/ #emph[apple]: #block[
+red fruit
+
+contains seeds, crisp, pleasant to taste
+]
+
+/ #emph[orange]: #block[
+orange fruit
+
+```
+{ orange code block }
+```
+
+#quote(block: true)[
+orange block quote
+]
+]
+
+Multiple definitions, tight:
+
+/ apple: #block[
+red fruit
+
+computer
+]
+
+/ orange: #block[
+orange fruit
+
+bank
+]
+
+Multiple definitions, loose:
+
+/ apple: #block[
+red fruit
+
+computer
+]
+
+/ orange: #block[
+orange fruit
+
+bank
+]
+
+Blank line after term, indented marker, alternate markers:
+
+/ apple: #block[
+red fruit
+
+computer
+]
+
+/ orange: #block[
+orange fruit
+
++ sublist
++ sublist
+]
+
+= HTML Blocks
+<html-blocks>
+Simple block on one line:
+
+#block[
+foo
+]
+And nested without indentation:
+
+#block[
+#block[
+#block[
+foo
+
+]
+]
+#block[
+bar
+]
+]
+Interpreted markdown in a table:
+
+This is #emph[emphasized]
+And this is #strong[strong]
+Here's a simple block:
+
+#block[
+foo
+
+]
+This should be a code block, though:
+
+```
+<div>
+    foo
+</div>
+```
+
+As should this:
+
+```
+<div>foo</div>
+```
+
+Now, nested:
+
+#block[
+#block[
+#block[
+foo
+]
+]
+]
+This should just be an HTML comment:
+
+Multiline:
+
+Code block:
+
+```
+<!-- Comment -->
+```
+
+Just plain comment, with trailing spaces on the line:
+
+Code:
+
+```
+<hr />
+```
+
+Hr's:
+
+#horizontalrule
+
+= Inline Markup
+<inline-markup>
+This is #emph[emphasized], and so #emph[is this].
+
+This is #strong[strong], and so #strong[is this].
+
+An #emph[#link("/url")[emphasized link]].
+
+#strong[#emph[This is strong and em.]]
+
+So is #strong[#emph[this]] word.
+
+#strong[#emph[This is strong and em.]]
+
+So is #strong[#emph[this]] word.
+
+This is code: `>`, `$`, `\`, `\$`, `<html>`.
+
+#strike[This is #emph[strikeout].]
+
+Superscripts: a#super[bc]d a#super[#emph[hello]] a#super[hello~there].
+
+Subscripts: H#sub[2]O, H#sub[23]O, H#sub[many~of~them]O.
+
+These should not be superscripts or subscripts, because of the unescaped spaces:
+a^b c^d, a\~b c\~d.
+
+#horizontalrule
+
+= Smart quotes, ellipses, dashes
+<smart-quotes-ellipses-dashes>
+"Hello," said the spider. "'Shelob' is my name."
+
+'A', 'B', and 'C' are letters.
+
+'Oak,' 'elm,' and 'beech' are names of trees. So is 'pine.'
+
+'He said, "I want to go."' Were you alive in the 70's?
+
+Here is some quoted '`code`' and a
+"#link("http://example.com/?foo=1&bar=2")[quoted link]".
+
+Some dashes: one---two --- three---four --- five.
+
+Dashes between numbers: 5--7, 255--66, 1987--1999.
+
+Ellipses…and…and….
+
+#horizontalrule
+
+= LaTeX
+<latex>
+-
+- $2 + 2 = 4$
+- $x in y$
+- $alpha and omega$
+- $223$
+- $p$-Tree
+- Here's some display math:
+  $ frac(d, d x) f\(x\)= lim_(h arrow.r 0) frac(f\(x + h\)- f\(x\), h) $
+- Here's one that has a line break in it: $alpha + omega times x^2$.
+
+These shouldn't be math:
+
+- To get the famous equation, write `$e = mc^2$`.
+- \$22,000 is a #emph[lot] of money. So is \$34,000. (It worked if "lot" is
+  emphasized.)
+- Shoes (\$20) and socks (\$5).
+- Escaped `$`: \$73 #emph[this should be emphasized] 23\$.
+
+Here's a LaTeX table:
+
+#horizontalrule
+
+= Special Characters
+<special-characters>
+Here is some unicode:
+
+- I hat: Î
+- o umlaut: ö
+- section: §
+- set membership: ∈
+- copyright: ©
+
+AT&T has an ampersand in their name.
+
+AT&T is another way to write it.
+
+This & that.
+
+4 \< 5.
+
+6 \> 5.
+
+Backslash: \\
+
+Backtick: \`
+
+Asterisk: \*
+
+Underscore: \_
+
+Left brace: {
+
+Right brace: }
+
+Left bracket: \[
+
+Right bracket: \]
+
+Left paren: (
+
+Right paren: )
+
+Greater-than: \>
+
+Hash: \#
+
+Period: .
+
+Bang: !
+
+Plus: +
+
+Minus: -
+
+#horizontalrule
+
+= Links
+<links>
+== Explicit
+<explicit>
+Just a #link("/url/")[URL].
+
+#link("/url/")[URL and title].
+
+#link("/url/")[URL and title].
+
+#link("/url/")[URL and title].
+
+#link("/url/")[URL and title]
+
+#link("/url/")[URL and title]
+
+#link("/url/with_underscore")[with\_underscore]
+
+#link("mailto:nobody@nowhere.net")[Email link]
+
+#link("")[Empty].
+
+== Reference
+<reference>
+Foo #link("/url/")[bar].
+
+With #link("/url/")[embedded \[brackets\]].
+
+#link("/url/")[b] by itself should be a link.
+
+Indented #link("/url")[once].
+
+Indented #link("/url")[twice].
+
+Indented #link("/url")[thrice].
+
+This should \[not\]\[\] be a link.
+
+```
+[not]: /url
+```
+
+Foo #link("/url/")[bar].
+
+Foo #link("/url/")[biz].
+
+== With ampersands
+<with-ampersands>
+Here's a
+#link("http://example.com/?foo=1&bar=2")[link with an ampersand in the URL].
+
+Here's a link with an amersand in the link text: #link("http://att.com/")[AT&T].
+
+Here's an #link("/script?foo=1&bar=2")[inline link].
+
+Here's an #link("/script?foo=1&bar=2")[inline link in pointy braces].
+
+== Autolinks
+<autolinks>
+With an ampersand: #link("http://example.com/?foo=1&bar=2")
+
+- In a list?
+- #link("http://example.com/")
+- It should.
+
+An e-mail address: #link("mailto:nobody@nowhere.net")[nobody\@nowhere.net]
+
+#quote(block: true)[
+Blockquoted: #link("http://example.com/")
+]
+
+Auto-links should not occur here: `<http://example.com/>`
+
+```
+or here: <http://example.com/>
+```
+
+#horizontalrule
+
+= Images
+<images>
+From "Voyage dans la Lune" by Georges Melies (1902):
+
+#figure(image("lalune.jpg", alt: "lalune"),
+  caption: [
+    lalune
+  ]
+)
+
+Here is a movie #box(image("movie.jpg", alt: "movie")) icon.
+
+#horizontalrule
+
+= Footnotes
+<footnotes>
+Here is a footnote reference,#footnote[Here is the footnote. It can go anywhere
+after the footnote reference. It need not be placed at the end of the document.]
+and another.#footnote[Here's the long note. This one contains multiple blocks.
+
+Subsequent blocks are indented to show that they belong to the footnote (as with
+list items).
+
+```
+  { <code> }
+```
+
+If you want, you can indent every line, but you can also be lazy and just indent
+the first line of each block.] This should #emph[not] be a footnote reference,
+because it contains a space.\[^my note\] Here is an inline note.#footnote[This
+is #emph[easier] to type. Inline notes may contain
+#link("http://google.com")[links] and `]` verbatim characters, as well as
+\[bracketed text\].]
+
+#quote(block: true)[
+Notes can go in quotes.#footnote[In quote.]
+]
+
++ And in list items.#footnote[In list.]
+
+This paragraph should not be part of the note, as it is not indented.
diff --git a/test/writer.vimdoc b/test/writer.vimdoc
new file mode 100644
--- /dev/null
+++ b/test/writer.vimdoc
@@ -0,0 +1,669 @@
+                Pandoc Test Suite by John MacFarlane, Anonymous
+
+
+                                         Type |gO| to see the table of contents.
+
+
+This is a set of tests for pandoc. Most of them are adapted from John Gruber's
+markdown test suite.
+
+ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
+
+================================================================================
+Headers                                                                  *headers*
+
+--------------------------------------------------------------------------------
+Level 2 with an embedded link /url                 *level-2-with-an-embedded-link*
+
+LEVEL 3 WITH EMPHASIS                                      *level-3-with-emphasis*
+
+Level 4                                                                  *level-4*
+
+Level 5                                                                  *level-5*
+
+================================================================================
+Level 1                                                                  *level-1*
+
+--------------------------------------------------------------------------------
+Level 2 with emphasis                                      *level-2-with-emphasis*
+
+LEVEL 3                                                                  *level-3*
+
+with no blank line
+
+--------------------------------------------------------------------------------
+Level 2                                                                  *level-2*
+
+with no blank line
+
+ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
+
+================================================================================
+Paragraphs                                                            *paragraphs*
+
+Here's a regular paragraph.
+
+In Markdown 1.0.0 and earlier. Version 8. This line turns into a list item.
+Because a hard-wrapped line in the middle of a paragraph looked like a list
+item.
+
+Here's one with a bullet. * criminey.
+
+There should be a hard line break
+here.
+
+ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
+
+================================================================================
+Block Quotes                                                        *block-quotes*
+
+E-mail style:
+
+  This is a block quote. It is pretty short.
+
+  Code in a block quote:
+
+  >
+      sub status {
+          print "working";
+      }
+<
+  A list:
+
+  1. item one
+  2. item two
+
+  Nested block quotes:
+
+    nested
+
+    nested
+
+This should not be a block quote: 2 > 1.
+
+And a following paragraph.
+
+ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
+
+================================================================================
+Code Blocks                                                          *code-blocks*
+
+Code:
+
+>
+    ---- (should be four hyphens)
+
+    sub status {
+        print "working";
+    }
+
+    this code block is indented by one tab
+<
+And:
+
+>
+        this code block is indented by two tabs
+
+    These should not be escaped:  \$ \\ \> \[ \{
+<
+ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
+
+================================================================================
+Lists                                                                      *lists*
+
+--------------------------------------------------------------------------------
+Unordered                                                              *unordered*
+
+Asterisks tight:
+
+- asterisk 1
+- asterisk 2
+- asterisk 3
+
+Asterisks loose:
+
+- asterisk 1
+
+- asterisk 2
+
+- asterisk 3
+
+Pluses tight:
+
+- Plus 1
+- Plus 2
+- Plus 3
+
+Pluses loose:
+
+- Plus 1
+
+- Plus 2
+
+- Plus 3
+
+Minuses tight:
+
+- Minus 1
+- Minus 2
+- Minus 3
+
+Minuses loose:
+
+- Minus 1
+
+- Minus 2
+
+- Minus 3
+
+--------------------------------------------------------------------------------
+Ordered                                                                  *ordered*
+
+Tight:
+
+1. First
+2. Second
+3. Third
+
+and:
+
+1. One
+2. Two
+3. Three
+
+Loose using tabs:
+
+1. First
+
+2. Second
+
+3. Third
+
+and using spaces:
+
+1. One
+
+2. Two
+
+3. Three
+
+Multiple paragraphs:
+
+1. Item 1, graf one.
+
+   Item 1. graf two. The quick brown fox jumped over the lazy dog's back.
+
+2. Item 2.
+
+3. Item 3.
+
+--------------------------------------------------------------------------------
+Nested                                                                    *nested*
+
+- Tab
+  - Tab
+    - Tab
+
+Here's another:
+
+1. First
+2. Second:
+   - Fee
+   - Fie
+   - Foe
+3. Third
+
+Same thing but with paragraphs:
+
+1. First
+
+2. Second:
+
+   - Fee
+   - Fie
+   - Foe
+
+3. Third
+
+--------------------------------------------------------------------------------
+Tabs and spaces                                                  *tabs-and-spaces*
+
+- this is a list item indented with tabs
+
+- this is a list item indented with spaces
+
+  - this is an example list item indented with tabs
+
+  - this is an example list item indented with spaces
+
+--------------------------------------------------------------------------------
+Fancy list markers                                            *fancy-list-markers*
+
+(2) begins with 2
+
+(3) and now 3
+
+    with a continuation
+
+    iv. sublist with roman numerals, starting with 4
+    v. more items
+       (A) a subsublist
+       (B) a subsublist
+
+Nesting:
+
+A. Upper Alpha
+   I. Upper Roman.
+      (6) Decimal start with 6
+          c) Lower alpha with paren
+
+Autonumbering:
+
+1. Autonumber.
+2. More.
+   1. Nested.
+
+Should not be a list item:
+
+M.A. 2007
+
+B. Williams
+
+ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
+
+================================================================================
+Definition Lists                                                *definition-lists*
+
+Tight using spaces:
+
+apple
+    red fruit
+orange
+    orange fruit
+banana
+    yellow fruit
+
+Tight using tabs:
+
+apple
+    red fruit
+orange
+    orange fruit
+banana
+    yellow fruit
+
+Loose:
+
+apple
+    red fruit
+
+orange
+    orange fruit
+
+banana
+    yellow fruit
+
+Multiple blocks with italics:
+
+apple
+    red fruit
+
+    contains seeds, crisp, pleasant to taste
+
+orange
+    orange fruit
+
+    >
+        { orange code block }
+<
+      orange block quote
+
+Multiple definitions, tight:
+
+apple
+    red fruit
+    computer
+orange
+    orange fruit
+    bank
+
+Multiple definitions, loose:
+
+apple
+    red fruit
+
+    computer
+
+orange
+    orange fruit
+
+    bank
+
+Blank line after term, indented marker, alternate markers:
+
+apple
+    red fruit
+
+    computer
+
+orange
+    orange fruit
+
+    1. sublist
+    2. sublist
+
+================================================================================
+HTML Blocks                                                          *html-blocks*
+
+Simple block on one line:
+
+foo
+And nested without indentation:
+
+foo
+
+bar
+Interpreted markdown in a table:
+
+This is emphasized
+And this is strong
+Here's a simple block:
+
+foo
+
+This should be a code block, though:
+
+>
+    <div>
+        foo
+    </div>
+<
+As should this:
+
+>
+    <div>foo</div>
+<
+Now, nested:
+
+foo
+This should just be an HTML comment:
+
+Multiline:
+
+Code block:
+
+>
+    <!-- Comment -->
+<
+Just plain comment, with trailing spaces on the line:
+
+Code:
+
+>
+    <hr />
+<
+Hr's:
+
+ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
+
+================================================================================
+Inline Markup                                                      *inline-markup*
+
+This is emphasized, and so is this.
+
+This is strong, and so is this.
+
+An emphasized link /url.
+
+This is strong and em.
+
+So is this word.
+
+This is strong and em.
+
+So is this word.
+
+This is code: `>`, `$`, `\`, `\$`, `<html>`.
+
+This is strikeout.
+
+Superscripts: abcd ahello ahello there.
+
+Subscripts: H2O, H23O, Hmany of themO.
+
+These should not be superscripts or subscripts, because of the unescaped spaces:
+a^b c^d, a~b c~d.
+
+ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
+
+================================================================================
+Smart quotes, ellipses, dashes                      *smart-quotes-ellipses-dashes*
+
+"Hello," said the spider. "'Shelob' is my name."
+
+'A', 'B', and 'C' are letters.
+
+'Oak,' 'elm,' and 'beech' are names of trees. So is 'pine.'
+
+'He said, "I want to go."' Were you alive in the 70's?
+
+Here is some quoted '`code`' and a "quoted link
+http://example.com/?foo=1&bar=2".
+
+Some dashes: one---two --- three---four --- five.
+
+Dashes between numbers: 5--7, 255--66, 1987--1999.
+
+Ellipses...and...and....
+
+ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
+
+================================================================================
+LaTeX                                                                      *latex*
+
+- 
+- `$2+2=4$`
+- `$x \in y$`
+- `$\alpha \wedge \omega$`
+- `$223$`
+- `$p$`-Tree
+- Here's some display math:
+  `$\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: `$\alpha + \omega \times x^2$`.
+
+These shouldn't be math:
+
+- To get the famous equation, write `$e = mc^2$`.
+- $22,000 is a lot of money. So is $34,000. (It worked if "lot" is emphasized.)
+- Shoes ($20) and socks ($5).
+- Escaped `$`: $73 this should be emphasized 23$.
+
+Here's a LaTeX table:
+
+ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
+
+================================================================================
+Special Characters                                            *special-characters*
+
+Here is some unicode:
+
+- I hat: Î
+- o umlaut: ö
+- section: §
+- set membership: ∈
+- copyright: ©
+
+AT&T has an ampersand in their name.
+
+AT&T is another way to write it.
+
+This & that.
+
+4 < 5.
+
+6 > 5.
+
+Backslash: \
+
+Backtick: `
+
+Asterisk: *
+
+Underscore: _
+
+Left brace: {
+
+Right brace: }
+
+Left bracket: [
+
+Right bracket: ]
+
+Left paren: (
+
+Right paren: )
+
+Greater-than: >
+
+Hash: #
+
+Period: .
+
+Bang: !
+
+Plus: +
+
+Minus: -
+
+ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
+
+================================================================================
+Links                                                                      *links*
+
+--------------------------------------------------------------------------------
+Explicit                                                                *explicit*
+
+Just a URL /url/.
+
+URL and title /url/.
+
+URL and title /url/.
+
+URL and title /url/.
+
+URL and title /url/
+
+URL and title /url/
+
+with_underscore /url/with_underscore
+
+Email link nobody@nowhere.net
+
+Empty .
+
+--------------------------------------------------------------------------------
+Reference                                                              *reference*
+
+Foo bar /url/.
+
+With embedded [brackets] /url/.
+
+b /url/ by itself should be a link.
+
+Indented once /url.
+
+Indented twice /url.
+
+Indented thrice /url.
+
+This should [not][] be a link.
+
+>
+    [not]: /url
+<
+Foo bar /url/.
+
+Foo biz /url/.
+
+--------------------------------------------------------------------------------
+With ampersands                                                  *with-ampersands*
+
+Here's a link with an ampersand in the URL http://example.com/?foo=1&bar=2.
+
+Here's a link with an amersand in the link text: AT&T http://att.com/.
+
+Here's an inline link /script?foo=1&bar=2.
+
+Here's an inline link in pointy braces /script?foo=1&bar=2.
+
+--------------------------------------------------------------------------------
+Autolinks                                                              *autolinks*
+
+With an ampersand: http://example.com/?foo=1&bar=2
+
+- In a list?
+- http://example.com/
+- It should.
+
+An e-mail address: nobody@nowhere.net
+
+  Blockquoted: http://example.com/
+
+Auto-links should not occur here: `<http://example.com/>`
+
+>
+    or here: <http://example.com/>
+<
+ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
+
+================================================================================
+Images                                                                    *images*
+
+From "Voyage dans la Lune" by Georges Melies (1902):
+
+Here is a movie icon.
+
+ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
+
+================================================================================
+Footnotes                                                              *footnotes*
+
+Here is a footnote reference, |footnote1| and another. |footnote2| This should
+not be a footnote reference, because it contains a space.[^my note] Here is an
+inline note. |footnote3|
+
+  Notes can go in quotes. |footnote4|
+
+1. And in list items. |footnote5|
+
+This paragraph should not be part of the note, as it is not indented.
+
+ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
+
+                                                                       *footnote1*
+Here is the footnote. It can go anywhere after the footnote reference. It need
+not be placed at the end of the document.
+
+                                                                       *footnote2*
+Here's the long note. This one contains multiple blocks.
+
+Subsequent blocks are indented to show that they belong to the footnote (as with
+list items).
+
+>
+      { <code> }
+<
+If you want, you can indent every line, but you can also be lazy and just indent
+the first line of each block.
+
+                                                                       *footnote3*
+This is easier to type. Inline notes may contain links http://google.com and `]`
+verbatim characters, as well as [bracketed text].
+
+                                                                       *footnote4*
+In quote.
+
+                                                                       *footnote5*
+In list.
+
+ vim:tw=80:sw=4:ts=4:ft=help:norl:et:
diff --git a/test/writer.xwiki b/test/writer.xwiki
new file mode 100644
--- /dev/null
+++ b/test/writer.xwiki
@@ -0,0 +1,651 @@
+This is a set of tests for pandoc. Most of them are adapted from John Gruber’s markdown test suite.
+
+
+----
+
+= Headers {{id name="headers" /}}=
+
+== Level 2 with an [[embedded link>>/url]] {{id name="level-2-with-an-embedded-link" /}}==
+
+=== Level 3 with //emphasis// {{id name="level-3-with-emphasis" /}}===
+
+==== Level 4 {{id name="level-4" /}}====
+
+===== Level 5 {{id name="level-5" /}}=====
+
+= Level 1 {{id name="level-1" /}}=
+
+== Level 2 with //emphasis// {{id name="level-2-with-emphasis" /}}==
+
+=== Level 3 {{id name="level-3" /}}===
+
+with no blank line
+
+== Level 2 {{id name="level-2" /}}==
+
+with no blank line
+
+
+----
+
+= Paragraphs {{id name="paragraphs" /}}=
+
+Here’s a regular paragraph.
+
+In Markdown 1.0.0 and earlier. Version 8. This line turns into a list item. Because a hard-wrapped line in the middle of a paragraph looked like a list item.
+
+Here’s one with a bullet. * criminey.
+
+There should be a hard line break\\here.
+
+
+----
+
+= Block Quotes {{id name="block-quotes" /}}=
+
+E-mail style:
+
+>This is a block quote. It is pretty short.
+>
+>Code in a block quote:
+>
+>
+>{{code}}
+>sub status {
+>    print "working";
+>}
+>{{/code}}
+>
+>A list:
+>
+>1. item one
+>1. item two
+>
+>Nested block quotes:
+>
+>>nested
+>>
+>>nested
+>>
+This should not be a block quote: 2 > 1.
+
+And a following paragraph.
+
+
+----
+
+= Code Blocks {{id name="code-blocks" /}}=
+
+Code:
+
+
+{{code}}
+---- (should be four hyphens)
+
+sub status {
+    print "working";
+}
+
+this code block is indented by one tab
+{{/code}}
+
+And:
+
+
+{{code}}
+    this code block is indented by two tabs
+
+These should not be escaped:  \$ \\ \> \[ \{
+{{/code}}
+
+
+----
+
+= Lists {{id name="lists" /}}=
+
+== Unordered {{id name="unordered" /}}==
+
+Asterisks tight:
+
+*. asterisk 1
+*. asterisk 2
+*. asterisk 3
+
+Asterisks loose:
+
+*. asterisk 1
+*. asterisk 2
+*. asterisk 3
+
+Pluses tight:
+
+*. Plus 1
+*. Plus 2
+*. Plus 3
+
+Pluses loose:
+
+*. Plus 1
+*. Plus 2
+*. Plus 3
+
+Minuses tight:
+
+*. Minus 1
+*. Minus 2
+*. Minus 3
+
+Minuses loose:
+
+*. Minus 1
+*. Minus 2
+*. Minus 3
+
+== Ordered {{id name="ordered" /}}==
+
+Tight:
+
+1. First
+1. Second
+1. Third
+
+and:
+
+1. One
+1. Two
+1. Three
+
+Loose using tabs:
+
+1. First
+1. Second
+1. Third
+
+and using spaces:
+
+1. One
+1. Two
+1. Three
+
+Multiple paragraphs:
+
+1. Item 1, graf one.
+
+Item 1. graf two. The quick brown fox jumped over the lazy dog’s back.
+1. Item 2.
+1. Item 3.
+
+== Nested {{id name="nested" /}}==
+
+*. Tab
+**. Tab
+***. Tab
+
+Here’s another:
+
+1. First
+1. Second:
+1*. Fee
+1*. Fie
+1*. Foe
+1. Third
+
+Same thing but with paragraphs:
+
+1. First
+1. Second:
+
+1*. Fee
+1*. Fie
+1*. Foe
+1. Third
+
+== Tabs and spaces {{id name="tabs-and-spaces" /}}==
+
+*. this is a list item indented with tabs
+*. this is a list item indented with spaces
+
+**. this is an example list item indented with tabs
+**. this is an example list item indented with spaces
+
+== Fancy list markers {{id name="fancy-list-markers" /}}==
+
+1. begins with 2
+1. and now 3
+
+with a continuation
+
+11. sublist with roman numerals, starting with 4
+11. more items
+111. a subsublist
+111. a subsublist
+
+Nesting:
+
+1. Upper Alpha
+11. Upper Roman.
+111. Decimal start with 6
+1111. Lower alpha with paren
+
+Autonumbering:
+
+1. Autonumber.
+1. More.
+11. Nested.
+
+Should not be a list item:
+
+M.A. 2007
+
+B. Williams
+
+
+----
+
+= Definition Lists {{id name="definition-lists" /}}=
+
+Tight using spaces:
+
+; apple
+: red fruit
+; orange
+: orange fruit
+; banana
+: yellow fruit
+
+Tight using tabs:
+
+; apple
+: red fruit
+; orange
+: orange fruit
+; banana
+: yellow fruit
+
+Loose:
+
+; apple
+: red fruit
+
+; orange
+: orange fruit
+
+; banana
+: yellow fruit
+
+
+Multiple blocks with italics:
+
+; //apple//
+: red fruit
+
+contains seeds, crisp, pleasant to taste
+
+; //orange//
+: orange fruit
+
+
+{{code}}
+{ orange code block }
+{{/code}}
+
+>orange block quote
+>
+
+Multiple definitions, tight:
+
+; apple
+: red fruit
+: computer
+; orange
+: orange fruit
+: bank
+
+Multiple definitions, loose:
+
+; apple
+: red fruit
+
+: computer
+
+; orange
+: orange fruit
+
+: bank
+
+
+Blank line after term, indented marker, alternate markers:
+
+; apple
+: red fruit
+
+: computer
+
+; orange
+: orange fruit
+
+;1. sublist
+;1. sublist
+
+= HTML Blocks {{id name="html-blocks" /}}=
+
+Simple block on one line:
+
+foo
+And nested without indentation:
+
+foo
+
+bar
+Interpreted markdown in a table:
+
+
+
+
+This is //emphasized//
+
+
+And this is **strong**
+
+
+
+
+Here’s a simple block:
+
+foo
+
+This should be a code block, though:
+
+
+{{code}}
+<div>
+    foo
+</div>
+{{/code}}
+
+As should this:
+
+
+{{code}}
+<div>foo</div>
+{{/code}}
+
+Now, nested:
+
+foo
+This should just be an HTML comment:
+
+
+Multiline:
+
+
+
+Code block:
+
+
+{{code}}
+<!-- Comment -->
+{{/code}}
+
+Just plain comment, with trailing spaces on the line:
+
+
+Code:
+
+
+{{code}}
+<hr />
+{{/code}}
+
+Hr’s:
+
+
+
+
+
+
+
+
+
+
+
+----
+
+= Inline Markup {{id name="inline-markup" /}}=
+
+This is //emphasized//, and so //is this//.
+
+This is **strong**, and so **is this**.
+
+An //[[emphasized link>>/url]]//.
+
+**//This is strong and em.//**
+
+So is **//this//** word.
+
+**//This is strong and em.//**
+
+So is **//this//** word.
+
+This is code: {{code}}>{{/code}}, {{code}}${{/code}}, {{code}}\{{/code}}, {{code}}\${{/code}}, {{code}}<html>{{/code}}.
+
+--This is //strikeout//.--
+
+Superscripts: a^^bc^^d a^^//hello//^^ a^^hello there^^.
+
+Subscripts: H,,2,,O, H,,23,,O, H,,many of them,,O.
+
+These should not be superscripts or subscripts, because of the unescaped spaces: a^b c^d, a~~b c~~d.
+
+
+----
+
+= Smart quotes, ellipses, dashes {{id name="smart-quotes-ellipses-dashes" /}}=
+
+“Hello,” said the spider. “‘Shelob’ is my name.”
+
+‘A’, ‘B’, and ‘C’ are letters.
+
+‘Oak,’ ‘elm,’ and ‘beech’ are names of trees. So is ‘pine.’
+
+‘He said, “I want to go.”’ Were you alive in the 70’s?
+
+Here is some quoted ‘{{code}}code{{/code}}’ and a “[[quoted link>>http://example.com/?foo=1&bar=2]]”.
+
+Some dashes: one—two — three—four — five.
+
+Dashes between numbers: 5–7, 255–66, 1987–1999.
+
+Ellipses…and…and….
+
+
+----
+
+= LaTeX {{id name="latex" /}}=
+
+*. 
+*. {{formula}}2+2=4{{/formula}}
+*. {{formula}}x \in y{{/formula}}
+*. {{formula}}\alpha \wedge \omega{{/formula}}
+*. {{formula}}223{{/formula}}
+*. {{formula}}p{{/formula}}-Tree
+*. Here’s some display math: {{formula}}\frac{d}{dx}f(x)=\lim_{h\to 0}\frac{f(x+h)-f(x)}{h}{{/formula}}
+*. Here’s one that has a line break in it: {{formula}}\alpha + \omega \times x^2{{/formula}}.
+
+These shouldn’t be math:
+
+*. To get the famous equation, write {{code}}$e = mc^2${{/code}}.
+*. $22,000 is a //lot// of money. So is $34,000. (It worked if “lot” is emphasized.)
+*. Shoes ($20) and socks ($5).
+*. Escaped {{code}}${{/code}}: $73 //this should be emphasized// 23$.
+
+Here’s a LaTeX table:
+
+
+
+----
+
+= Special Characters {{id name="special-characters" /}}=
+
+Here is some unicode:
+
+*. I hat: Î
+*. o umlaut: ö
+*. section: §
+*. set membership: ∈
+*. copyright: ©
+
+AT&T has an ampersand in their name.
+
+AT&T is another way to write it.
+
+This & that.
+
+4 < 5.
+
+6 > 5.
+
+Backslash: \
+
+Backtick: `
+
+Asterisk: *
+
+Underscore: _
+
+Left brace: {
+
+Right brace: }
+
+Left bracket: [
+
+Right bracket: ]
+
+Left paren: (
+
+Right paren: )
+
+Greater-than: >
+
+Hash: #
+
+Period: .
+
+Bang: !
+
+Plus: +
+
+Minus: -
+
+
+----
+
+= Links {{id name="links" /}}=
+
+== Explicit {{id name="explicit" /}}==
+
+Just a [[URL>>/url/]].
+
+[[URL and title>>/url/]].
+
+[[URL and title>>/url/]].
+
+[[URL and title>>/url/]].
+
+[[URL and title>>/url/]]
+
+[[URL and title>>/url/]]
+
+[[with_underscore>>/url/with_underscore]]
+
+[[Email link>>mailto:nobody@nowhere.net]]
+
+[[Empty>>]].
+
+== Reference {{id name="reference" /}}==
+
+Foo [[bar>>/url/]].
+
+With [[embedded [brackets]>>/url/]].
+
+[[b>>/url/]] by itself should be a link.
+
+Indented [[once>>/url]].
+
+Indented [[twice>>/url]].
+
+Indented [[thrice>>/url]].
+
+This should [not][] be a link.
+
+
+{{code}}
+[not]: /url
+{{/code}}
+
+Foo [[bar>>/url/]].
+
+Foo [[biz>>/url/]].
+
+== With ampersands {{id name="with-ampersands" /}}==
+
+Here’s a [[link with an ampersand in the URL>>http://example.com/?foo=1&bar=2]].
+
+Here’s a link with an amersand in the link text: [[AT&T>>http://att.com/]].
+
+Here’s an [[inline link>>/script?foo=1&bar=2]].
+
+Here’s an [[inline link in pointy braces>>/script?foo=1&bar=2]].
+
+== Autolinks {{id name="autolinks" /}}==
+
+With an ampersand: http://example.com/?foo=1&bar=2
+
+*. In a list?
+*. http://example.com/
+*. It should.
+
+An e-mail address: [[nobody@nowhere.net>>mailto:nobody@nowhere.net]]
+
+>Blockquoted: http://example.com/
+>
+Auto-links should not occur here: {{code}}<http://example.com/>{{/code}}
+
+
+{{code}}
+or here: <http://example.com/>
+{{/code}}
+
+
+----
+
+= Images {{id name="images" /}}=
+
+From “Voyage dans la Lune” by Georges Melies (1902):
+
+(((
+[[image:lalune.jpg||alt="lalune" title="Voyage dans la Lune"]]
+)))
+Here is a movie [[image:movie.jpg||alt="movie"]] icon.
+
+
+----
+
+= Footnotes {{id name="footnotes" /}}=
+
+Here is a footnote reference,{{footnote}}Here is the footnote. It can go anywhere after the footnote reference. It need not be placed at the end of the document.{{/footnote}} and another.{{footnote}}Here’s the long note. This one contains multiple blocks.
+
+Subsequent blocks are indented to show that they belong to the footnote (as with list items).
+
+
+{{code}}
+  { <code> }
+{{/code}}
+
+If you want, you can indent every line, but you can also be lazy and just indent the first line of each block.{{/footnote}} This should //not// be a footnote reference, because it contains a space.[^my note] Here is an inline note.{{footnote}}This is //easier// to type. Inline notes may contain [[links>>http://google.com]] and {{code}}]{{/code}} verbatim characters, as well as [bracketed text].{{/footnote}}
+
+>Notes can go in quotes.{{footnote}}In quote.{{/footnote}}
+>
+1. And in list items.{{footnote}}In list.{{/footnote}}
+
+This paragraph should not be part of the note, as it is not indented.
diff --git a/test/writer.zimwiki b/test/writer.zimwiki
--- a/test/writer.zimwiki
+++ b/test/writer.zimwiki
@@ -8,9 +8,9 @@
 
 ====== Headers ======
 
-===== Level 2 with an embedded link =====
+===== Level 2 with an [[url|embedded link]] =====
 
-==== Level 3 with emphasis ====
+==== Level 3 with //emphasis// ====
 
 === Level 4 ===
 
@@ -18,7 +18,7 @@
 
 ====== Level 1 ======
 
-===== Level 2 with emphasis =====
+===== Level 2 with //emphasis// =====
 
 ==== Level 3 ====
 
@@ -61,8 +61,8 @@
 > 
 > A list:
 > 
-> 	1. item one
-> 	1. item two
+> 1. item one
+> 2. item two
 > 
 > Nested block quotes:
 > 
@@ -108,126 +108,126 @@
 
 Asterisks tight:
 
-	* asterisk 1
-	* asterisk 2
-	* asterisk 3
+* asterisk 1
+* asterisk 2
+* asterisk 3
 
 Asterisks loose:
 
-	* asterisk 1
-	* asterisk 2
-	* asterisk 3
+* asterisk 1
+* asterisk 2
+* asterisk 3
 
 Pluses tight:
 
-	* Plus 1
-	* Plus 2
-	* Plus 3
+* Plus 1
+* Plus 2
+* Plus 3
 
 Pluses loose:
 
-	* Plus 1
-	* Plus 2
-	* Plus 3
+* Plus 1
+* Plus 2
+* Plus 3
 
 Minuses tight:
 
-	* Minus 1
-	* Minus 2
-	* Minus 3
+* Minus 1
+* Minus 2
+* Minus 3
 
 Minuses loose:
 
-	* Minus 1
-	* Minus 2
-	* Minus 3
+* Minus 1
+* Minus 2
+* Minus 3
 
 ===== Ordered =====
 
 Tight:
 
-	1. First
-	1. Second
-	1. Third
+1. First
+2. Second
+3. Third
 
 and:
 
-	1. One
-	1. Two
-	1. Three
+1. One
+2. Two
+3. Three
 
 Loose using tabs:
 
-	1. First
-	1. Second
-	1. Third
+1. First
+2. Second
+3. Third
 
 and using spaces:
 
-	1. One
-	1. Two
-	1. Three
+1. One
+2. Two
+3. Three
 
 Multiple paragraphs:
 
-	1. Item 1, graf one.
+1. Item 1, graf one.
 Item 1. graf two. The quick brown fox jumped over the lazy dog’s back.
-	1. Item 2.
-	1. Item 3.
+2. Item 2.
+3. Item 3.
 
 ===== Nested =====
 
+* Tab
 	* Tab
 		* Tab
-			* Tab
 
 Here’s another:
 
-	1. First
-	1. Second:
-		* Fee
-		* Fie
-		* Foe
-	1. Third
+1. First
+2. Second:
+	* Fee
+	* Fie
+	* Foe
+3. Third
 
 Same thing but with paragraphs:
 
-	1. First
-	1. Second:
-		* Fee
-		* Fie
-		* Foe
-	1. Third
+1. First
+2. Second:
+	* Fee
+	* Fie
+	* Foe
+3. Third
 
 ===== Tabs and spaces =====
 
-	* this is a list item indented with tabs
-	* this is a list item indented with spaces
-		* this is an example list item indented with tabs
-		* this is an example list item indented with spaces
+* this is a list item indented with tabs
+* this is a list item indented with spaces
+	* this is an example list item indented with tabs
+	* this is an example list item indented with spaces
 
 ===== Fancy list markers =====
 
-	1. begins with 2
-	1. and now 3
+1. begins with 2
+2. and now 3
 with a continuation
-		1. sublist with roman numerals, starting with 4
-		1. more items
-			1. a subsublist
-			1. a subsublist
+	1. sublist with roman numerals, starting with 4
+	2. more items
+		1. a subsublist
+		2. a subsublist
 
 Nesting:
 
-	1. Upper Alpha
-		1. Upper Roman.
-			1. Decimal start with 6
-				1. Lower alpha with paren
+1. Upper Alpha
+	1. Upper Roman.
+		1. Decimal start with 6
+			1. Lower alpha with paren
 
 Autonumbering:
 
-	1. Autonumber.
-	1. More.
-		1. Nested.
+1. Autonumber.
+2. More.
+	1. Nested.
 
 Should not be a list item:
 
@@ -291,8 +291,8 @@
 
 * **orange** orange fruit
 
-	1. sublist
-	1. sublist
+1. sublist
+2. sublist
 
 ====== HTML Blocks ======
 
@@ -435,21 +435,21 @@
 
 ====== LaTeX ======
 
-	* 
-	* $2+2=4$
-	* $x \in y$
-	* $\alpha \wedge \omega$
-	* $223$
-	* $p$-Tree
-	* Here’s some display math: $$\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: $\alpha + \omega \times x^2$.
+* 
+* $2+2=4$
+* $x \in y$
+* $\alpha \wedge \omega$
+* $223$
+* $p$-Tree
+* Here’s some display math: $$\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: $\alpha + \omega \times x^2$.
 
 These shouldn’t be math:
 
-	* To get the famous equation, write ''$e = mc^2$''.
-	* $22,000 is a //lot// of money. So is $34,000. (It worked if “lot” is emphasized.)
-	* Shoes ($20) and socks ($5).
-	* Escaped ''$'': $73 //this should be emphasized// 23$.
+* To get the famous equation, write ''$e = mc^2$''.
+* $22,000 is a //lot// of money. So is $34,000. (It worked if “lot” is emphasized.)
+* Shoes ($20) and socks ($5).
+* Escaped ''$'': $73 //this should be emphasized// 23$.
 
 Here’s a LaTeX table:
 
@@ -461,11 +461,11 @@
 
 Here is some unicode:
 
-	* I hat: Î
-	* o umlaut: ö
-	* section: §
-	* set membership: ∈
-	* copyright: ©
+* I hat: Î
+* o umlaut: ö
+* section: §
+* set membership: ∈
+* copyright: ©
 
 AT&T has an ampersand in their name.
 
@@ -572,9 +572,9 @@
 
 With an ampersand: http://example.com/?foo=1&bar=2
 
-	* In a list?
-	* http://example.com/
-	* It should.
+* In a list?
+* http://example.com/
+* It should.
 
 An e-mail address: <nobody@nowhere.net>
 
@@ -593,11 +593,13 @@
 
 From “Voyage dans la Lune” by Georges Melies (1902):
 
-{{:lalune.jpg|Voyage dans la Lune lalune}}
+{{lalune.jpg|Voyage dans la Lune}}
+lalune
 
-Here is a movie {{:movie.jpg|movie}} icon.
 
+Here is a movie {{movie.jpg|movie}} icon.
 
+
 ----
 
 ====== Footnotes ======
@@ -614,6 +616,6 @@
 
 > Notes can go in quotes. **{Note:** In quote.**}**
 
-	1. And in list items. **{Note:** In list.**}**
+1. And in list items. **{Note:** In list.**}**
 
 This paragraph should not be part of the note, as it is not indented.
diff --git a/test/writers-lang-and-dir.context b/test/writers-lang-and-dir.context
--- a/test/writers-lang-and-dir.context
+++ b/test/writers-lang-and-dir.context
@@ -4,22 +4,25 @@
   style=,
   color=,
   contrastcolor=]
+\setupurl[style=]
 
 % make chapter, section bookmarks visible when opening document
 \placebookmarks[chapter, section, subsection, subsubsection, subsubsubsection, subsubsubsubsection][chapter, section]
-\setupinteractionscreen[option=bookmark]
-\setuptagging[state=start]
+\setupinteractionscreen[option={bookmark,title}]
 
+\setuppagenumbering[location={footer,middle}]
+\setupstructure[state=start,method=auto]
 
 % use microtypography
 \definefontfeature[default][default][script=latn, protrusion=quality, expansion=quality, itlc=yes, textitalics=yes, onum=yes, pnum=yes]
+\definefontfeature[default:tnum][default][tnum=yes, pnum=no]
 \definefontfeature[smallcaps][script=latn, protrusion=quality, expansion=quality, smcp=yes, onum=yes, pnum=yes]
 \setupalign[hz,hanging]
 \setupitaliccorrection[global, always]
 
 \setupbodyfontenvironment[default][em=italic] % use italic as em, not slanted
 
-\definefallbackfamily[mainface][rm][DejaVu Serif][preset=range:greek, force=yes]
+\definefallbackfamily[mainface][rm][CMU Serif][preset=range:greek, force=yes]
 \definefontfamily[mainface][rm][Latin Modern Roman]
 \definefontfamily[mainface][mm][Latin Modern Math]
 \definefontfamily[mainface][ss][Latin Modern Sans]
@@ -28,13 +31,17 @@
 
 \setupwhitespace[medium]
 
-\setuphead[chapter]            [style=\tfd,header=empty]
-\setuphead[section]            [style=\tfc]
-\setuphead[subsection]         [style=\tfb]
+\setuphead[chapter]            [style=\tfd\setupinterlinespace,header=empty]
+\setuphead[section]            [style=\tfc\setupinterlinespace]
+\setuphead[subsection]         [style=\tfb\setupinterlinespace]
 \setuphead[subsubsection]      [style=\bf]
 \setuphead[subsubsubsection]   [style=\sc]
 \setuphead[subsubsubsubsection][style=\it]
 
+\definesectionlevels
+   [default]
+   [section, subsection, subsubsection, subsubsubsection, subsubsubsubsection]
+
 \setuphead[chapter, section, subsection, subsubsection, subsubsubsection, subsubsubsubsection][number=no]
 
 \definedescription
@@ -44,15 +51,23 @@
 \setupitemize[autointro]    % prevent orphan list intro
 \setupitemize[indentnext=no]
 
+\defineitemgroup[enumerate]
+\setupenumerate[each][fit][itemalign=left,distance=.5em,style={\feature[+][default:tnum]}]
+
 \setupfloat[figure][default={here,nonumber}]
 \setupfloat[table][default={here,nonumber}]
 
-\setupthinrules[width=15em] % width of horizontal rules
+\setupxtable[frame=off]
+\setupxtable[head][topframe=on]
+\setupxtable[body][]
+\setupxtable[foot][]
+\setupxtable[lastrow][bottomframe=on]
 
 
 \starttext
 
-\section[empty-divs-and-spans]{Empty Divs and Spans}
+\startsectionlevel[title={Empty Divs and
+Spans},reference={empty-divs-and-spans}]
 
 Some text and
 
@@ -62,8 +77,10 @@
 
 Next paragraph with a span and a word-thatincludesaspanright?
 
-\section[directionality]{Directionality}
+\stopsectionlevel
 
+\startsectionlevel[title={Directionality},reference={directionality}]
+
 Some text and
 
 \startalignment[righttoleft]
@@ -81,8 +98,10 @@
 Next paragraph with a {\righttoleft rtl span} and a
 word-that-includesa{\lefttoright ltrspan}right?
 
-\section[languages]{Languages}
+\stopsectionlevel
 
+\startsectionlevel[title={Languages},reference={languages}]
+
 Some text and
 
 \start\language[de]
@@ -92,13 +111,15 @@
 
 and more text.
 
-Next paragraph with a \start\language[en-gb]British span\stop  and a
-word-that-includesa\start\language[de-ch]Swiss German span\stop right?
+Next paragraph with a {\language[en-gb]British span} and a
+word-that-includesa{\language[de-ch]Swiss German span}right?
 
-Some \start\language[es]Spanish text\stop .
+Some {\language[es]Spanish text}.
 
-\section[combined]{Combined}
+\stopsectionlevel
 
+\startsectionlevel[title={Combined},reference={combined}]
+
 Some text and
 
 \start\language[fr]
@@ -110,9 +131,10 @@
 
 and more text.
 
-Next paragraph with a \start\language[en-gb]{\lefttoright British ltr
-span}\stop  and a
-word-that-includesa\start\language[de-ch]{\lefttoright Swiss German ltr
-span}\stop right?
+Next paragraph with a {\language[en-gb]{\lefttoright British ltr span}}
+and a word-that-includesa{\language[de-ch]{\lefttoright Swiss German ltr
+span}}right?
+
+\stopsectionlevel
 
 \stoptext
diff --git a/test/writers-lang-and-dir.latex b/test/writers-lang-and-dir.latex
--- a/test/writers-lang-and-dir.latex
+++ b/test/writers-lang-and-dir.latex
@@ -1,95 +1,89 @@
-\PassOptionsToPackage{unicode=true}{hyperref} % options for packages loaded elsewhere
+% Options for packages loaded elsewhere
+\PassOptionsToPackage{unicode}{hyperref}
 \PassOptionsToPackage{hyphens}{url}
-%
-\documentclass[english,]{article}
-\usepackage{lmodern}
-\usepackage{amssymb,amsmath}
-\usepackage{ifxetex,ifluatex}
-\usepackage{fixltx2e} % provides \textsubscript
-\ifnum 0\ifxetex 1\fi\ifluatex 1\fi=0 % if pdftex
+\documentclass[
+  ngerman,
+  british,
+  nswissgerman,
+  spanish,
+  french,
+  english,
+]{article}
+\usepackage{xcolor}
+\usepackage{amsmath,amssymb}
+\setcounter{secnumdepth}{-\maxdimen} % remove section numbering
+\usepackage{iftex}
+\ifPDFTeX
   \usepackage[T1]{fontenc}
   \usepackage[utf8]{inputenc}
-  \usepackage{textcomp} % provides euro and other symbols
-\else % if luatex or xelatex
-  \usepackage{unicode-math}
-  \defaultfontfeatures{Ligatures=TeX,Scale=MatchLowercase}
+  \usepackage{textcomp} % provide euro and other symbols
+\else % if luatex or xetex
+  \usepackage{unicode-math} % this also loads fontspec
+  \defaultfontfeatures{Scale=MatchLowercase}
+  \defaultfontfeatures[\rmfamily]{Ligatures=TeX,Scale=1}
 \fi
-% use upquote if available, for straight quotes in verbatim environments
+\usepackage{lmodern}
+\ifPDFTeX\else
+  % xetex/luatex font selection
+\fi
+% Use upquote if available, for straight quotes in verbatim environments
 \IfFileExists{upquote.sty}{\usepackage{upquote}}{}
-% use microtype if available
-\IfFileExists{microtype.sty}{%
-\usepackage[]{microtype}
-\UseMicrotypeSet[protrusion]{basicmath} % disable protrusion for tt fonts
+\IfFileExists{microtype.sty}{% use microtype if available
+  \usepackage[]{microtype}
+  \UseMicrotypeSet[protrusion]{basicmath} % disable protrusion for tt fonts
 }{}
-\IfFileExists{parskip.sty}{%
-\usepackage{parskip}
-}{% else
-\setlength{\parindent}{0pt}
-\setlength{\parskip}{6pt plus 2pt minus 1pt}
-}
-\usepackage{hyperref}
-\hypersetup{
-            pdfborder={0 0 0},
-            breaklinks=true}
-\urlstyle{same}  % don't use monospace font for urls
-\setlength{\emergencystretch}{3em}  % prevent overfull lines
-\providecommand{\tightlist}{%
-  \setlength{\itemsep}{0pt}\setlength{\parskip}{0pt}}
-\setcounter{secnumdepth}{0}
-% Redefines (sub)paragraphs to behave more like sections
-\ifx\paragraph\undefined\else
-\let\oldparagraph\paragraph
-\renewcommand{\paragraph}[1]{\oldparagraph{#1}\mbox{}}
-\fi
-\ifx\subparagraph\undefined\else
-\let\oldsubparagraph\subparagraph
-\renewcommand{\subparagraph}[1]{\oldsubparagraph{#1}\mbox{}}
-\fi
-
-% set default figure placement to htbp
 \makeatletter
-\def\fps@figure{htbp}
+\@ifundefined{KOMAClassName}{% if non-KOMA class
+  \IfFileExists{parskip.sty}{%
+    \usepackage{parskip}
+  }{% else
+    \setlength{\parindent}{0pt}
+    \setlength{\parskip}{6pt plus 2pt minus 1pt}}
+}{% if KOMA class
+  \KOMAoptions{parskip=half}}
 \makeatother
-
-\ifnum 0\ifxetex 1\fi\ifluatex 1\fi=0 % if pdftex
-  \usepackage[shorthands=off,ngerman,british,nswissgerman,spanish,french,main=english]{babel}
-  \newcommand{\textgerman}[2][]{\foreignlanguage{ngerman}{#2}}
-  \newenvironment{german}[2][]{\begin{otherlanguage}{ngerman}}{\end{otherlanguage}}
-  \newcommand{\textenglish}[2][]{\foreignlanguage{british}{#2}}
-  \newenvironment{english}[2][]{\begin{otherlanguage}{british}}{\end{otherlanguage}}
-  \let\oritextspanish\textspanish
-  \AddBabelHook{spanish}{beforeextras}{\renewcommand{\textspanish}{\oritextspanish}}
-  \AddBabelHook{spanish}{afterextras}{\renewcommand{\textspanish}[2][]{\foreignlanguage{spanish}{##2}}}
-  \newcommand{\textfrench}[2][]{\foreignlanguage{french}{#2}}
-  \newenvironment{french}[2][]{\begin{otherlanguage}{french}}{\end{otherlanguage}}
+\ifLuaTeX
+\usepackage[bidi=basic,shorthands=off]{babel}
 \else
-  % load polyglossia as late as possible as it *could* call bidi if RTL lang (e.g. Hebrew or Arabic)
-  \usepackage{polyglossia}
-  \setmainlanguage[]{english}
-  \setotherlanguage[]{german}
-  \setotherlanguage[variant=british]{english}
-  \setotherlanguage[variant=swiss]{german}
-  \setotherlanguage[]{spanish}
-  \setotherlanguage[]{french}
+\usepackage[bidi=default,shorthands=off]{babel}
 \fi
-\ifxetex
-  % load bidi as late as possible as it modifies e.g. graphicx
-    \usepackage{bidi}
-  \fi
-\ifnum 0\ifxetex 1\fi\ifluatex 1\fi=0 % if pdftex
+\ifLuaTeX
+  \usepackage{selnolig} % disable illegal ligatures
+\fi
+\setlength{\emergencystretch}{3em} % prevent overfull lines
+\providecommand{\tightlist}{%
+  \setlength{\itemsep}{0pt}\setlength{\parskip}{0pt}}
+\ifPDFTeX
   \TeXXeTstate=1
   \newcommand{\RL}[1]{\beginR #1\endR}
   \newcommand{\LR}[1]{\beginL #1\endL}
   \newenvironment{RTL}{\beginR}{\endR}
   \newenvironment{LTR}{\beginL}{\endL}
 \fi
+\ifluatex
+  \newcommand{\RL}[1]{\bgroup\textdir TRT#1\egroup}
+  \newcommand{\LR}[1]{\bgroup\textdir TLT#1\egroup}
+  \newenvironment{RTL}{\textdir TRT\pardir TRT\bodydir TRT}{}
+  \newenvironment{LTR}{\textdir TLT\pardir TLT\bodydir TLT}{}
+\fi
+\usepackage{bookmark}
+\IfFileExists{xurl.sty}{\usepackage{xurl}}{} % add URL line breaks if available
+\urlstyle{same}
+% fallback for those not using the hyperref driver hyperxmp:
+\makeatletter
+\@ifundefined{xmpquote}{\newcommand{\xmpquote}[1]{#1}}{}
+\makeatother
+\hypersetup{
+  pdflang={en},
+  hidelinks,
+  pdfcreator={LaTeX via pandoc}}
 
+\author{}
 \date{}
 
 \begin{document}
 
-\hypertarget{empty-divs-and-spans}{%
-\section{Empty Divs and Spans}\label{empty-divs-and-spans}}
+\section{Empty Divs and Spans}\label{empty-divs-and-spans}
 
 Some text and
 
@@ -99,8 +93,7 @@
 
 Next paragraph with a {span} and a word-thatincludesa{span}right?
 
-\hypertarget{directionality}{%
-\section{Directionality}\label{directionality}}
+\section{Directionality}\label{directionality}
 
 Some text and
 
@@ -117,41 +110,40 @@
 Next paragraph with a \RL{rtl span} and a
 word-that-includesa\LR{ltrspan}right?
 
-\hypertarget{languages}{%
-\section{Languages}\label{languages}}
+\section{Languages}\label{languages}
 
 Some text and
 
-\begin{german}
+\begin{otherlanguage}{ngerman}
 
 German div contents
 
-\end{german}
+\end{otherlanguage}
 
 and more text.
 
-Next paragraph with a \textenglish[variant=british]{British span} and a
-word-that-includesa\textgerman[variant=swiss]{Swiss German span}right?
+Next paragraph with a \foreignlanguage{british}{British span} and a
+word-that-includesa\foreignlanguage{nswissgerman}{Swiss German
+span}right?
 
-Some \textspanish{Spanish text}.
+Some \foreignlanguage{spanish}{Spanish text}.
 
-\hypertarget{combined}{%
-\section{Combined}\label{combined}}
+\section{Combined}\label{combined}
 
 Some text and
 
 \begin{RTL}
-\begin{french}
+\begin{otherlanguage}{french}
 
 French rtl div contents
 
-\end{french}
+\end{otherlanguage}
 \end{RTL}
 
 and more text.
 
-Next paragraph with a \LR{\textenglish[variant=british]{British ltr
-span}} and a word-that-includesa\LR{\textgerman[variant=swiss]{Swiss
-German ltr span}}right?
+Next paragraph with a \LR{\foreignlanguage{british}{British ltr span}}
+and a word-that-includesa\LR{\foreignlanguage{nswissgerman}{Swiss German
+ltr span}}right?
 
 \end{document}
diff --git a/test/xlsx-reader/basic.native b/test/xlsx-reader/basic.native
new file mode 100644
--- /dev/null
+++ b/test/xlsx-reader/basic.native
@@ -0,0 +1,381 @@
+Pandoc
+  Meta { unMeta = fromList [] }
+  [ Header 2 ( "sheet-1" , [] , [] ) [ Str "Main" ]
+  , Table
+      ( "" , [] , [] )
+      (Caption Nothing [])
+      [ ( AlignDefault , ColWidthDefault )
+      , ( AlignDefault , ColWidthDefault )
+      , ( AlignDefault , ColWidthDefault )
+      ]
+      (TableHead
+         ( "" , [] , [] )
+         [ Row
+             ( "" , [] , [] )
+             [ Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Strong [ Str "Person" ] ] ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Strong [ Str "Age" ] ] ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Strong [ Str "Location" ] ] ]
+             ]
+         ])
+      [ TableBody
+          ( "" , [] , [] )
+          (RowHeadColumns 0)
+          []
+          [ Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "Anton" , Space , Str "Antich" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "23.0" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "Switzerland" ] ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "James" , Space , Str "Bond" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "35.0" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "Moscow" ] ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [] ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [] ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain
+                      [ Str "Just"
+                      , Space
+                      , Str "a"
+                      , Space
+                      , Str "random"
+                      , Space
+                      , Str "cell"
+                      ]
+                  ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [] ]
+              ]
+          ]
+      ]
+      (TableFoot ( "" , [] , [] ) [])
+  , Header 2 ( "sheet-2" , [] , [] ) [ Str "Secondary" ]
+  , Table
+      ( "" , [] , [] )
+      (Caption Nothing [])
+      [ ( AlignDefault , ColWidthDefault )
+      , ( AlignDefault , ColWidthDefault )
+      , ( AlignDefault , ColWidthDefault )
+      , ( AlignDefault , ColWidthDefault )
+      , ( AlignDefault , ColWidthDefault )
+      ]
+      (TableHead
+         ( "" , [] , [] )
+         [ Row
+             ( "" , [] , [] )
+             [ Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain
+                     [ Str "Sum"
+                     , Space
+                     , Str "of"
+                     , Space
+                     , Str "Age"
+                     ]
+                 ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [ Str "Column" , Space , Str "Labels" ] ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [] ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [] ]
+             , Cell
+                 ( "" , [] , [] )
+                 AlignDefault
+                 (RowSpan 1)
+                 (ColSpan 1)
+                 [ Plain [] ]
+             ]
+         ])
+      [ TableBody
+          ( "" , [] , [] )
+          (RowHeadColumns 0)
+          []
+          [ Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "Row" , Space , Str "Labels" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "Moscow" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "Switzerland" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "(blank)" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "Grand" , Space , Str "Total" ] ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "Anton" , Space , Str "Antich" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "23.0" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "23.0" ] ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "James" , Space , Str "Bond" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "35.0" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "35.0" ] ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "(blank)" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [] ]
+              ]
+          , Row
+              ( "" , [] , [] )
+              [ Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "Grand" , Space , Str "Total" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "35.0" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "23.0" ] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [] ]
+              , Cell
+                  ( "" , [] , [] )
+                  AlignDefault
+                  (RowSpan 1)
+                  (ColSpan 1)
+                  [ Plain [ Str "58.0" ] ]
+              ]
+          ]
+      ]
+      (TableFoot ( "" , [] , [] ) [])
+  ]
diff --git a/test/xlsx-reader/basic.xlsx b/test/xlsx-reader/basic.xlsx
new file mode 100644
Binary files /dev/null and b/test/xlsx-reader/basic.xlsx differ
diff --git a/trypandoc/Makefile b/trypandoc/Makefile
deleted file mode 100644
--- a/trypandoc/Makefile
+++ /dev/null
@@ -1,14 +0,0 @@
-CGIBIN=/home/website/cgi-bin
-TRYPANDOC=/home/website/pandoc.org/try/
-CGI=${CGIBIN}/trypandoc
-BIN=/home/jgm/.local/bin/trypandoc
-
-install: ${CGI} ${TRYPANDOC}/index.html
-
-${TRYPANDOC}/%: %
-	cp $< $@ && chown website:www-data $@ && chmod a+r $@
-
-${CGI}: ${BIN}
-	cp $< $@ && chown website:www-data $@ && chmod a+rx $@
-
-.PHONY: install
diff --git a/trypandoc/index.html b/trypandoc/index.html
deleted file mode 100644
--- a/trypandoc/index.html
+++ /dev/null
@@ -1,161 +0,0 @@
-<!doctype html>
-<html lang="en">
-<head>
-  <meta charset="utf-8">
-  <title>Try pandoc!</title>
-  <script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
-  <script src="//maxcdn.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
-  <link href="//maxcdn.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet">
-  <script type="text/javascript">
-(function($) { // http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values
-	$.QueryString = (function(a) {
-	    if (a == "") return {};
-	    var b = {};
-	    for (var i = 0; i < a.length; ++i)
-	    {
-		var p=a[i].split('=');
-		if (p.length != 2) continue;
-		b[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " "));
-	    }
-	    return b;
-        })(window.location.search.substr(1).split('&'))
-})(jQuery);
-
-function newpage() {
-  var input = $("#text").val();
-  var from = $("#from").val();
-  var to = $("#to").val();
-  var href = window.location.href;
-  window.location.href = href.replace(/([?].*)?$/,"?" + $.param({text: input, from: from, to: to}));
-};
-
-$(document).ready(function() {
-    var text = $.QueryString["text"];
-    $("#text").val(text);
-    var from = $.QueryString["from"] || "markdown";
-    $("#from").val(from);
-    var to = $.QueryString["to"] || "html";
-    $("#to").val(to);
-    if (text && text != "") {
-       $.getJSON("/cgi-bin/trypandoc", { from: from, to: to, text: text },
-         function(res) {
-          $("#results").text(res.html);
-          $("#version").text(res.version);
-          $("#command").text("pandoc --from " + from + " --to " + to);
-         });
-    };
-    $("#convert").click(newpage);
-});
-  </script>
-  <style type="text/css">
-    h1 { margin-bottom: 1em; }
-    body { margin: auto; }
-    textarea { height: auto; width: 100%; font-family: monospace; margin-top: 15px; }
-    div.alert { margin: 1em; }
-    h3 { margin-top: 0; margin-bottom: 0; padding: 0; font-size: 100%; }
-    pre#results { width: 100%; margin-top: 15px; }
-    footer { color: #555; text-align: center; margin: 1em; }
-    p.version { color: #555; }
-    button#convert { vertical-align: bottom; }
-    pre#command { margin-top: 1em; background-color: transparent; border: none; }
-  </style>
-</head>
-<body>
-<div class="container">
-  <div class="row">
-    <div class="col-md-6">
-      <h1>Try <a href="http://pandoc.org">pandoc</a>!</h1>
-    </div>
-    <div class="col-md-6">
-      <pre id="command"></pre>
-    </div>
-  </div>
-  <div class="row">
-    <div class="col-md-6">
-      <button class="btn btn-primary btn-xs" id="convert">Convert</button>
-      &nbsp;
-      <label for="from">
-      from
-      </label>
-      <select id="from">
-        <option value="commonmark">CommonMark</option>
-        <option value="creole">Creole</option>
-        <option value="docbook">DocBook</option>
-        <option value="gfm">GitHub-Flavored Markdown</option>
-        <option value="haddock">Haddock markup</option>
-        <option value="html">HTML</option>
-        <option value="latex">LaTeX</option>
-        <option value="markdown" selected>Markdown (pandoc)</option>
-        <option value="markdown_mmd">MultiMarkdown</option>
-        <option value="markdown_phpextra">Markdown (PHP Markdown Extra)</option>
-        <option value="markdown_strict">Markdown (strict)</option>
-        <option value="mediawiki">MediaWiki</option>
-        <option value="muse">Muse</option>
-        <option value="native">Native (Pandoc AST)</option>
-        <option value="opml">OPML</option>
-        <option value="org">Org Mode</option>
-        <option value="rst">reStructuredText</option>
-        <option value="t2t">Txt2Tags</option>
-        <option value="textile">Textile</option>
-        <option value="tikiwiki">TikiWiki</option>
-        <option value="twiki">TWiki</option>
-        <option value="vimwiki">Vimwiki</option>
-      </select>
-      <br/>
-      <textarea id="text" maxlength="3000" rows="15"></textarea>
-    </div>
-    <div class="col-md-6">
-      <label for="to">
-      to
-      </label>
-      <select id="to">
-        <option value="S5">S5</option>
-        <option value="asciidoc">AsciiDoc</option>
-        <option value="beamer">LaTeX Beamer</option>
-        <option value="commonmark">CommonMark</option>
-        <option value="context">ConTeXt</option>
-        <option value="docbook4">DocBook v4</option>
-        <option value="docbook5">DocBook v5</option>
-        <option value="dokuwiki">DokuWiki</option>
-        <option value="dzslides">DZSlides</option>
-        <option value="dzslides">dzslides</option>
-        <option value="gfm">GitHub-Flavored Markdown</option>
-        <option value="haddock">Haddock markup</option>
-        <option value="html4" selected>HTML 4</option>
-        <option value="html5">HTML 5</option>
-        <option value="icml">ICML</option>
-        <option value="json">JSON</option>
-        <option value="latex">LaTeX</option>
-        <option value="man">Groff man</option>
-        <option value="ms">Groff ms</option>
-        <option value="markdown">Markdown (pandoc)</option>
-        <option value="markdown_mmd">MultiMarkdown</option>
-        <option value="markdown_phpextra">Markdown (PHP Markdown Extra)</option>
-        <option value="markdown_strict">Markdown (strict)</option>
-        <option value="mediawiki">MediaWiki</option>
-        <option value="muse">Muse</option>
-        <option value="native">Native (Pandoc AST)</option>
-        <option value="opendocument">OpenDocument</option>
-        <option value="opml">OPML</option>
-        <option value="org">Org Mode</option>
-        <option value="plain">Plain text</option>
-        <option value="revealjs">reveal.js</option>
-        <option value="rst">reStructuredText</option>
-        <option value="rtf">RTF</option>
-        <option value="slideous">Slideous</option>
-        <option value="slidy">Slidy</option>
-        <option value="texinfo">Texinfo</option>
-        <option value="textile">Textile</option>
-        <option value="zimwiki">ZimWiki</option>
-      </select>
-      <br/>
-      <pre id="results"></pre>
-    </div>
-  </div>
-</div>
-<footer>
- <p class="version">pandoc <span id="version"></span></p>
- <p>&copy; 2013&ndash;2015 <a href="http://johnmacfarlane.net">John MacFarlane</a></p>
-</footer>
-</body>
-</html>
diff --git a/trypandoc/trypandoc.hs b/trypandoc/trypandoc.hs
deleted file mode 100644
--- a/trypandoc/trypandoc.hs
+++ /dev/null
@@ -1,66 +0,0 @@
-{-# LANGUAGE OverloadedStrings #-}
-module Main where
-import Network.Wai.Handler.CGI
-import Network.Wai
-import Control.Applicative ((<$>))
-import Data.Maybe (fromMaybe)
-import Network.HTTP.Types.Status (status200)
-import Network.HTTP.Types.Header (hContentType)
-import Network.HTTP.Types.URI (queryToQueryText)
-import Text.Pandoc
-import Text.Pandoc.Writers.Math (defaultMathJaxURL)
-import Text.Pandoc.Highlighting (pygments)
-import Text.Pandoc.Readers (getReader, Reader(..))
-import Text.Pandoc.Writers (getWriter, Writer(..))
-import Text.Pandoc.Shared (tabFilter)
-import Data.Aeson
-import qualified Data.Text as T
-import Data.Text (Text)
-
-main :: IO ()
-main = run app
-
-app :: Application
-app req respond = do
-  let query = queryToQueryText $ queryString req
-  let getParam x = maybe (error $ T.unpack x ++ " paramater not set")
-                       return $ lookup x query
-  text <- getParam "text" >>= checkLength . fromMaybe T.empty
-  fromFormat <- fromMaybe "" <$> getParam "from"
-  toFormat <- fromMaybe "" <$> getParam "to"
-  let reader = case getReader (T.unpack fromFormat) of
-                    Right (TextReader r, es) -> r readerOpts{
-                       readerExtensions = es }
-                    _ -> error $ "could not find reader for "
-                                  ++ T.unpack fromFormat
-  let writer = case getWriter (T.unpack toFormat) of
-                    Right (TextWriter w, es) -> w writerOpts{
-                       writerExtensions = es }
-                    _ -> error $ "could not find writer for " ++
-                           T.unpack toFormat
-  let result = case runPure $ reader (tabFilter 4 text) >>= writer of
-                    Right s   -> s
-                    Left  err -> error (show err)
-  let output = encode $ object [ T.pack "html" .= result
-                               , T.pack "name" .=
-                                  if fromFormat == "markdown_strict"
-                                     then T.pack "pandoc (strict)"
-                                     else T.pack "pandoc"
-                               , T.pack "version" .= pandocVersion]
-  respond $ responseLBS status200 [(hContentType,"text/json; charset=UTF-8")] output
-
-checkLength :: Text -> IO Text
-checkLength t =
-  if T.length t > 10000
-     then error "exceeds length limit of 10,000 characters"
-     else return t
-
-writerOpts :: WriterOptions
-writerOpts = def { writerReferenceLinks = True,
-                   writerEmailObfuscation = NoObfuscation,
-                   writerHTMLMathMethod = MathJax (defaultMathJaxURL ++
-                       "MathJax.js?config=TeX-AMS_CHTML-full"),
-                   writerHighlightStyle = Just pygments }
-
-readerOpts :: ReaderOptions
-readerOpts = def
diff --git a/xml-light/Text/Pandoc/XML/Light.hs b/xml-light/Text/Pandoc/XML/Light.hs
new file mode 100644
--- /dev/null
+++ b/xml-light/Text/Pandoc/XML/Light.hs
@@ -0,0 +1,113 @@
+{-# LANGUAGE FlexibleInstances #-}
+{-# LANGUAGE OverloadedStrings #-}
+{- |
+   Module      : Text.Pandoc.XML.Light
+   Copyright   : Copyright (C) 2021-2024 John MacFarlane
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : John MacFarlane <jgm@berkeley.edu>
+   Stability   : alpha
+   Portability : portable
+
+xml-light, which we used in pandoc's the XML-based readers, has
+some limitations: in particular, it produces nodes with String
+instead of Text, and the parser falls over on processing instructions
+(see #7091).
+
+This module exports much of the API of xml-light, but using Text instead
+of String. In addition, the xml-light parsers are replaced by xml-conduit's
+well-tested parser.  (The xml-conduit types are mapped to types
+isomorphic to xml-light's, to avoid the need for massive code modifications
+elsewhere.)  Bridge functions to map xml-light types to this module's
+types are also provided (since libraries like texmath still use xml-light).
+
+Another advantage of the xml-conduit parser is that it gives us
+detailed information on xml parse errors.
+
+In the future we may want to move to using xml-conduit or another
+xml library in the code base, but this change gives us
+better performance and accuracy without much change in the
+code that used xml-light.
+-}
+module Text.Pandoc.XML.Light
+  ( module Text.Pandoc.XML.Light.Types
+  , module Text.Pandoc.XML.Light.Proc
+  , module Text.Pandoc.XML.Light.Output
+    -- * Replacement for xml-light's Text.XML.Input
+  , parseXMLElement
+  , parseXMLContents
+    --  * Versions that allow passing in a custom entity table
+  , parseXMLElementWithEntities
+  , parseXMLContentsWithEntities
+  ) where
+
+import qualified Control.Exception as E
+import qualified Text.XML as Conduit
+import Text.XML.Unresolved (InvalidEventStream(..))
+import qualified Data.Text as T
+import qualified Data.Text.Lazy as TL
+import qualified Data.Map as M
+import Data.Maybe (mapMaybe)
+import Text.Pandoc.XML.Light.Types
+import Text.Pandoc.XML.Light.Proc
+import Text.Pandoc.XML.Light.Output
+import qualified Data.XML.Types as XML
+
+-- Drop in replacement for parseXMLDoc in xml-light.
+parseXMLElement :: TL.Text -> Either T.Text Element
+parseXMLElement = parseXMLElementWithEntities mempty
+
+-- Drop in replacement for parseXMLDoc in xml-light.
+parseXMLElementWithEntities :: M.Map T.Text T.Text
+                            -> TL.Text -> Either T.Text Element
+parseXMLElementWithEntities entityMap t =
+  elementToElement .  Conduit.documentRoot <$>
+    either (Left . T.pack . E.displayException) Right
+    (Conduit.parseText Conduit.def{ Conduit.psRetainNamespaces = True
+                                  , Conduit.psDecodeEntities = decodeEnts } t)
+ where
+   decodeEnts ref = case M.lookup ref entityMap of
+                      Nothing -> XML.ContentEntity ref
+                      Just t' -> XML.ContentText t'
+
+parseXMLContents :: TL.Text -> Either T.Text [Content]
+parseXMLContents = parseXMLContentsWithEntities mempty
+
+parseXMLContentsWithEntities :: M.Map T.Text T.Text
+                             -> TL.Text -> Either T.Text [Content]
+parseXMLContentsWithEntities entityMap t =
+  case Conduit.parseText Conduit.def{ Conduit.psRetainNamespaces = True
+                                    , Conduit.psDecodeEntities = decodeEnts
+                                    } t of
+    Left e ->
+      case E.fromException e of
+        Just (ContentAfterRoot _) ->
+          elContent <$> parseXMLElementWithEntities entityMap
+                          ("<wrapper>" <> t <> "</wrapper>")
+        _ -> Left . T.pack . E.displayException $ e
+    Right x -> Right [Elem . elementToElement . Conduit.documentRoot $ x]
+ where
+   decodeEnts ref = case M.lookup ref entityMap of
+                      Nothing -> XML.ContentEntity ref
+                      Just t' -> XML.ContentText t'
+
+elementToElement :: Conduit.Element -> Element
+elementToElement (Conduit.Element name attribMap nodes) =
+  Element (nameToQname name) attrs (mapMaybe nodeToContent nodes) Nothing
+ where
+  attrs = map (\(n,v) -> Attr (nameToQname n) v) $
+              M.toList attribMap
+  nameToQname (Conduit.Name localName mbns mbpref) =
+    case mbpref of
+      Nothing ->
+        case T.stripPrefix "xmlns:" localName of
+          Just rest -> QName rest mbns (Just "xmlns")
+          Nothing   -> QName localName mbns mbpref
+      _ -> QName localName mbns mbpref
+
+nodeToContent :: Conduit.Node -> Maybe Content
+nodeToContent (Conduit.NodeElement el) =
+  Just (Elem (elementToElement el))
+nodeToContent (Conduit.NodeContent t) =
+  Just (Text (CData CDataText t Nothing))
+nodeToContent _ = Nothing
diff --git a/xml-light/Text/Pandoc/XML/Light/Output.hs b/xml-light/Text/Pandoc/XML/Light/Output.hs
new file mode 100644
--- /dev/null
+++ b/xml-light/Text/Pandoc/XML/Light/Output.hs
@@ -0,0 +1,234 @@
+{-# LANGUAGE FlexibleInstances #-}
+{-# LANGUAGE OverloadedStrings #-}
+{- |
+   Module      : Text.Pandoc.XML.Light.Output
+   Copyright   : Copyright (C) 2007 Galois, Inc., 2021-2024 John MacFarlane
+   License     : GNU GPL, version 2 or above
+
+
+   Maintainer  : John MacFarlane <jgm@berkeley.edu>
+   Stability   : alpha
+   Portability : portable
+
+   This code is based on code from xml-light, released under the BSD3 license.
+   We use a text Builder instead of ShowS.
+-}
+module Text.Pandoc.XML.Light.Output
+  ( -- * Replacement for xml-light's Text.XML.Output
+    ppTopElement
+  , ppElement
+  , ppContent
+  , ppcElement
+  , ppcContent
+  , showTopElement
+  , showElement
+  , showContent
+  , useShortEmptyTags
+  , defaultConfigPP
+  , ConfigPP(..)
+  ) where
+
+import Data.Text (Text)
+import qualified Data.Text as T
+import qualified Data.Text.Lazy as TL
+import Data.Text.Lazy.Builder (Builder, singleton, fromText, toLazyText)
+import Text.Pandoc.XML.Light.Types
+
+--
+-- duplicates functions from Text.XML.Output
+--
+
+-- | The XML 1.0 header
+xmlHeader :: Text
+xmlHeader = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
+
+
+--------------------------------------------------------------------------------
+data ConfigPP = ConfigPP
+  { shortEmptyTag :: QName -> Bool
+  , prettify      :: Bool
+  }
+
+-- | Default pretty orinting configuration.
+--  * Always use abbreviate empty tags.
+defaultConfigPP :: ConfigPP
+defaultConfigPP = ConfigPP { shortEmptyTag = const True
+                           , prettify      = False
+                           }
+
+-- | The predicate specifies for which empty tags we should use XML's
+-- abbreviated notation <TAG />.  This is useful if we are working with
+-- some XML-ish standards (such as certain versions of HTML) where some
+-- empty tags should always be displayed in the <TAG></TAG> form.
+useShortEmptyTags :: (QName -> Bool) -> ConfigPP -> ConfigPP
+useShortEmptyTags p c = c { shortEmptyTag = p }
+
+
+-- | Specify if we should use extra white-space to make document more readable.
+-- WARNING: This adds additional white-space to text elements,
+-- and so it may change the meaning of the document.
+useExtraWhiteSpace :: Bool -> ConfigPP -> ConfigPP
+useExtraWhiteSpace p c  = c { prettify = p }
+
+-- | A configuration that tries to make things pretty
+-- (possibly at the cost of changing the semantics a bit
+-- through adding white space.)
+prettyConfigPP     :: ConfigPP
+prettyConfigPP      = useExtraWhiteSpace True defaultConfigPP
+
+
+--------------------------------------------------------------------------------
+
+
+-- | Pretty printing renders XML documents faithfully,
+-- with the exception that whitespace may be added\/removed
+-- in non-verbatim character data.
+ppTopElement       :: Element -> Text
+ppTopElement        = ppcTopElement prettyConfigPP
+
+-- | Pretty printing elements
+ppElement          :: Element -> Text
+ppElement           = ppcElement prettyConfigPP
+
+-- | Pretty printing content
+ppContent          :: Content -> Text
+ppContent           = ppcContent prettyConfigPP
+
+-- | Pretty printing renders XML documents faithfully,
+-- with the exception that whitespace may be added\/removed
+-- in non-verbatim character data.
+ppcTopElement      :: ConfigPP -> Element -> Text
+ppcTopElement c e   = T.unlines [xmlHeader,ppcElement c e]
+
+-- | Pretty printing elements
+ppcElement         :: ConfigPP -> Element -> Text
+ppcElement c        = TL.toStrict . toLazyText . ppElementS c mempty
+
+-- | Pretty printing content
+ppcContent         :: ConfigPP -> Content -> Text
+ppcContent c        = TL.toStrict . toLazyText . ppContentS c mempty
+
+ppcCData           :: ConfigPP -> CData -> Text
+ppcCData c         = TL.toStrict . toLazyText . ppCDataS c mempty
+
+type Indent = Builder
+
+-- | Pretty printing content using ShowT
+ppContentS         :: ConfigPP -> Indent -> Content -> Builder
+ppContentS c i x = case x of
+                     Elem e -> ppElementS c i e
+                     Text t -> ppCDataS c i t
+                     CRef r -> showCRefS r
+
+ppElementS         :: ConfigPP -> Indent -> Element -> Builder
+ppElementS c i e = i <> tagStart (elName e) (elAttribs e) <>
+  (case elContent e of
+    [] | "?" `T.isPrefixOf` qName name -> fromText " ?>"
+       | shortEmptyTag c name  -> fromText " />"
+    [Text t] -> singleton '>' <> ppCDataS c mempty t <> tagEnd name
+    cs -> singleton '>' <> nl <>
+          mconcat (map ((<> nl) . ppContentS c (sp <> i)) cs) <>
+          i <> tagEnd name
+      where (nl,sp)  = if prettify c then ("\n","  ") else ("","")
+  )
+  where name = elName e
+
+ppCDataS           :: ConfigPP -> Indent -> CData -> Builder
+ppCDataS c i t     = i <> if cdVerbatim t /= CDataText || not (prettify c)
+                             then showCDataS t
+                             else foldr cons mempty (T.unpack (showCData t))
+  where cons         :: Char -> Builder -> Builder
+        cons '\n' ys  = singleton '\n' <> i <> ys
+        cons y ys     = singleton y <> ys
+
+
+
+--------------------------------------------------------------------------------
+
+-- | Adds the <?xml?> header.
+showTopElement     :: Element -> Text
+showTopElement c    = xmlHeader <> showElement c
+
+showContent        :: Content -> Text
+showContent         = ppcContent defaultConfigPP
+
+showElement        :: Element -> Text
+showElement         = ppcElement defaultConfigPP
+
+showCData          :: CData -> Text
+showCData           = ppcCData defaultConfigPP
+
+-- Note: crefs should not contain '&', ';', etc.
+showCRefS          :: Text -> Builder
+showCRefS r         = singleton '&' <> fromText r <> singleton ';'
+
+-- | Convert a text element to characters.
+showCDataS         :: CData -> Builder
+showCDataS cd =
+ case cdVerbatim cd of
+   CDataText     -> escStr (cdData cd)
+   CDataVerbatim -> fromText "<![CDATA[" <> escCData (cdData cd) <>
+                    fromText "]]>"
+   CDataRaw      -> fromText (cdData cd)
+
+--------------------------------------------------------------------------------
+escCData           :: Text -> Builder
+escCData t
+  | "]]>" `T.isPrefixOf` t =
+     fromText "]]]]><![CDATA[>" <> fromText (T.drop 3 t)
+escCData t
+  = case T.uncons t of
+      Nothing     -> mempty
+      Just (c,t') -> singleton c <> escCData t'
+
+escChar            :: Char -> Builder
+escChar c = case c of
+  '<'   -> fromText "&lt;"
+  '>'   -> fromText "&gt;"
+  '&'   -> fromText "&amp;"
+  '"'   -> fromText "&quot;"
+  -- we use &#39 instead of &apos; because IE apparently has difficulties
+  -- rendering &apos; in xhtml.
+  -- Reported by Rohan Drape <rohan.drape@gmail.com>.
+  '\''  -> fromText "&#39;"
+  _     -> singleton c
+
+  {- original xml-light version:
+  -- NOTE: We escape '\r' explicitly because otherwise they get lost
+  -- when parsed back in because of then end-of-line normalization rules.
+  _ | isPrint c || c == '\n' -> singleton c
+    | otherwise -> showText "&#" . showsT oc . singleton ';'
+      where oc = ord c
+  -}
+
+escStr             :: Text -> Builder
+escStr cs          = if T.any needsEscape cs
+                        then mconcat (map escChar (T.unpack cs))
+                        else fromText cs
+ where
+  needsEscape '<' = True
+  needsEscape '>' = True
+  needsEscape '&' = True
+  needsEscape '"' = True
+  needsEscape '\'' = True
+  needsEscape _ = False
+
+tagEnd             :: QName -> Builder
+tagEnd qn           = fromText "</" <> showQName qn <> singleton '>'
+
+tagStart           :: QName -> [Attr] -> Builder
+tagStart qn as      = singleton '<' <> showQName qn <> as_str
+ where as_str       = if null as
+                         then mempty
+                         else mconcat (map showAttr as)
+
+showAttr           :: Attr -> Builder
+showAttr (Attr qn v) = singleton ' ' <> showQName qn <>
+                       singleton '=' <>
+                       singleton '"' <> escStr v <> singleton '"'
+
+showQName          :: QName -> Builder
+showQName q         =
+  case qPrefix q of
+    Nothing -> fromText (qName q)
+    Just p  -> fromText p <> singleton ':' <> fromText (qName q)
diff --git a/xml-light/Text/Pandoc/XML/Light/Proc.hs b/xml-light/Text/Pandoc/XML/Light/Proc.hs
new file mode 100644
--- /dev/null
+++ b/xml-light/Text/Pandoc/XML/Light/Proc.hs
@@ -0,0 +1,137 @@
+{-# LANGUAGE FlexibleInstances #-}
+{- |
+   Module      : Text.Pandoc.XML.Light.Proc
+   Copyright   : Copyright (C) 2007 Galois, Inc., 2021-2024 John MacFarlane
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : John MacFarlane <jgm@berkeley.edu>
+   Stability   : alpha
+   Portability : portable
+
+   This code is taken from xml-light, released under the BSD3 license.
+-}
+module Text.Pandoc.XML.Light.Proc
+  (
+    -- * Replacement for xml-light's Text.XML.Proc
+    strContent
+  , onlyElems
+  , elChildren
+  , onlyText
+  , findChildren
+  , filterChildren
+  , filterChildrenName
+  , findChild
+  , filterChild
+  , filterChildName
+  , findElement
+  , filterElement
+  , filterElementName
+  , findElements
+  , filterElements
+  , filterElementsName
+  , findAttr
+  , lookupAttr
+  , lookupAttrBy
+  , findAttrBy
+  ) where
+
+import Data.Text (Text)
+import Data.Maybe (listToMaybe)
+import Data.List(find)
+import Text.Pandoc.XML.Light.Types
+
+--
+-- copied from xml-light Text.XML.Proc
+--
+
+-- | Get the text value of an XML element.  This function
+-- ignores non-text elements, and concatenates all text elements.
+strContent         :: Element -> Text
+strContent          = mconcat . map cdData . onlyText . elContent
+
+-- | Select only the elements from a list of XML content.
+onlyElems          :: [Content] -> [Element]
+onlyElems xs        = [ x | Elem x <- xs ]
+
+-- | Select only the elements from a parent.
+elChildren         :: Element -> [Element]
+elChildren e        = [ x | Elem x <- elContent e ]
+
+-- | Select only the text from a list of XML content.
+onlyText           :: [Content] -> [CData]
+onlyText xs         = [ x | Text x <- xs ]
+
+-- | Find all immediate children with the given name.
+findChildren       :: QName -> Element -> [Element]
+findChildren q e    = filterChildren ((q ==) . elName) e
+
+-- | Filter all immediate children wrt a given predicate.
+filterChildren       :: (Element -> Bool) -> Element -> [Element]
+filterChildren p e    = filter p (onlyElems (elContent e))
+
+
+-- | Filter all immediate children wrt a given predicate over their names.
+filterChildrenName      :: (QName -> Bool) -> Element -> [Element]
+filterChildrenName p e   = filter (p.elName) (onlyElems (elContent e))
+
+
+-- | Find an immediate child with the given name.
+findChild          :: QName -> Element -> Maybe Element
+findChild q e       = listToMaybe (findChildren q e)
+
+-- | Find an immediate child with the given name.
+filterChild          :: (Element -> Bool) -> Element -> Maybe Element
+filterChild p e       = listToMaybe (filterChildren p e)
+
+-- | Find an immediate child with name matching a predicate.
+filterChildName      :: (QName -> Bool) -> Element -> Maybe Element
+filterChildName p e   = listToMaybe (filterChildrenName p e)
+
+-- | Find the left-most occurrence of an element matching given name.
+findElement        :: QName -> Element -> Maybe Element
+findElement q e     = listToMaybe (findElements q e)
+
+-- | Filter the left-most occurrence of an element wrt. given predicate.
+filterElement        :: (Element -> Bool) -> Element -> Maybe Element
+filterElement p e     = listToMaybe (filterElements p e)
+
+-- | Filter the left-most occurrence of an element wrt. given predicate.
+filterElementName     :: (QName -> Bool) -> Element -> Maybe Element
+filterElementName p e  = listToMaybe (filterElementsName p e)
+
+-- | Find all non-nested occurrences of an element.
+-- (i.e., once we have found an element, we do not search
+-- for more occurrences among the element's children).
+findElements       :: QName -> Element -> [Element]
+findElements qn e = filterElementsName (qn==) e
+
+-- | Find all non-nested occurrences of an element wrt. given predicate.
+-- (i.e., once we have found an element, we do not search
+-- for more occurrences among the element's children).
+filterElements       :: (Element -> Bool) -> Element -> [Element]
+filterElements p e
+ | p e        = [e]
+ | otherwise  = concatMap (filterElements p) $ onlyElems $ elContent e
+
+-- | Find all non-nested occurrences of an element wrt a predicate over element names.
+-- (i.e., once we have found an element, we do not search
+-- for more occurrences among the element's children).
+filterElementsName       :: (QName -> Bool) -> Element -> [Element]
+filterElementsName p e = filterElements (p.elName) e
+
+-- | Lookup the value of an attribute.
+findAttr          :: QName -> Element -> Maybe Text
+findAttr x e       = lookupAttr x (elAttribs e)
+
+-- | Lookup attribute name from list.
+lookupAttr        :: QName -> [Attr] -> Maybe Text
+lookupAttr x       = lookupAttrBy (x ==)
+
+-- | Lookup the first attribute whose name satisfies the given predicate.
+lookupAttrBy       :: (QName -> Bool) -> [Attr] -> Maybe Text
+lookupAttrBy p as   = attrVal `fmap` find (p . attrKey) as
+
+-- | Lookup the value of the first attribute whose name
+-- satisfies the given predicate.
+findAttrBy         :: (QName -> Bool) -> Element -> Maybe Text
+findAttrBy p e      = lookupAttrBy p (elAttribs e)
diff --git a/xml-light/Text/Pandoc/XML/Light/Types.hs b/xml-light/Text/Pandoc/XML/Light/Types.hs
new file mode 100644
--- /dev/null
+++ b/xml-light/Text/Pandoc/XML/Light/Types.hs
@@ -0,0 +1,191 @@
+{-# LANGUAGE FlexibleInstances #-}
+{-# LANGUAGE DeriveDataTypeable #-}
+{- |
+   Module      : Text.Pandoc.XML.Light.Types
+   Copyright   : Copyright (C) 2007 Galois, Inc., 2021-2024 John MacFarlane
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : John MacFarlane <jgm@berkeley.edu>
+   Stability   : alpha
+   Portability : portable
+
+   This code is taken from xml-light, released under the BSD3 license.
+   It has been modified to use Text instead of String, and the fromXL*
+   functions have been added.
+-}
+module Text.Pandoc.XML.Light.Types
+  ( -- * Basic types, duplicating those from xml-light but with Text
+    -- instead of String
+    Line
+  , Content(..)
+  , Element(..)
+  , Attr(..)
+  , CData(..)
+  , CDataKind(..)
+  , QName(..)
+  , Node(..)
+  , unode
+  , unqual
+  , add_attr
+  , add_attrs
+  -- * Conversion functions from xml-light types
+  , fromXLQName
+  , fromXLCData
+  , fromXLElement
+  , fromXLAttr
+  , fromXLContent
+  ) where
+
+import Data.Text (Text)
+import qualified Data.Text as T
+import Data.Data (Data)
+import Data.Typeable (Typeable)
+import qualified Text.XML.Light as XL
+
+--
+-- type definitions lightly modified from xml-light
+--
+
+-- | A line is an Integer
+type Line     = Integer
+
+-- | XML content
+data Content  = Elem Element
+              | Text CData
+              | CRef Text
+                deriving (Show, Typeable, Data, Ord, Eq)
+
+-- | XML elements
+data Element  = Element {
+                  elName      :: QName,
+                  elAttribs   :: [Attr],
+                  elContent   :: [Content],
+                  elLine      :: Maybe Line
+                } deriving (Show, Typeable, Data, Ord, Eq)
+
+-- | XML attributes
+data Attr     = Attr {
+                  attrKey :: QName,
+                  attrVal :: Text
+                } deriving (Eq, Ord, Show, Typeable, Data)
+
+-- | XML CData
+data CData    = CData {
+                  cdVerbatim  :: CDataKind,
+                  cdData      :: Text,
+                  cdLine      :: Maybe Line
+                } deriving (Show, Typeable, Data, Ord, Eq)
+
+data CDataKind
+ = CDataText      -- ^ Ordinary character data; pretty printer escapes &, < etc.
+ | CDataVerbatim  -- ^ Unescaped character data; pretty printer embeds it in <![CDATA[..
+ | CDataRaw       -- ^ As-is character data; pretty printer passes it along without any escaping or CDATA wrap-up.
+   deriving ( Eq, Ord, Show, Typeable, Data )
+
+-- | XML qualified names
+data QName    = QName {
+                  qName   :: Text,
+                  qURI    :: Maybe Text,
+                  qPrefix :: Maybe Text
+                } deriving (Show, Typeable, Data)
+
+
+instance Eq QName where
+  q1 == q2  = compare q1 q2 == EQ
+
+instance Ord QName where
+  compare q1 q2 =
+    case compare (qName q1) (qName q2) of
+      EQ  -> case (qURI q1, qURI q2) of
+               (Nothing,Nothing) -> compare (qPrefix q1) (qPrefix q2)
+               (u1,u2)           -> compare u1 u2
+      x   -> x
+
+class Node t where
+ node :: QName -> t -> Element
+
+instance Node ([Attr],[Content]) where
+  node n (attrs,cont) = Element { elName     = n
+                                , elAttribs  = attrs
+                                , elContent  = cont
+                                , elLine     = Nothing
+                                }
+
+instance Node [Attr]             where node n as   = node n (as,[]::[Content])
+instance Node Attr               where node n a    = node n [a]
+instance Node ()                 where node n ()   = node n ([]::[Attr])
+
+instance Node [Content]          where node n cs     = node n ([]::[Attr],cs)
+instance Node Content            where node n c      = node n [c]
+instance Node ([Attr],Content)   where node n (as,c) = node n (as,[c])
+instance Node (Attr,Content)     where node n (a,c)  = node n ([a],[c])
+
+instance Node ([Attr],[Element]) where
+  node n (as,cs) = node n (as,map Elem cs)
+
+instance Node ([Attr],Element)   where node n (as,c) = node n (as,[c])
+instance Node (Attr,Element)     where node n (a,c)  = node n ([a],c)
+instance Node [Element]          where node n es     = node n ([]::[Attr],es)
+instance Node Element            where node n e      = node n [e]
+
+instance Node ([Attr],[CData])   where
+  node n (as,cs) = node n (as,map Text cs)
+
+instance Node ([Attr],CData)     where node n (as,c) = node n (as,[c])
+instance Node (Attr,CData)       where node n (a,c)  = node n ([a],c)
+instance Node [CData]            where node n es     = node n ([]::[Attr],es)
+instance Node CData              where node n e      = node n [e]
+
+instance Node ([Attr],Text)      where
+  node n (as,t) = node n (as, CData { cdVerbatim = CDataText
+                                    , cdData = t
+                                    , cdLine = Nothing })
+
+instance Node (Attr,Text )       where node n (a,t)  = node n ([a],t)
+instance Node Text               where node n t      = node n ([]::[Attr],t)
+
+-- | Create node with unqualified name
+unode :: Node t => Text -> t -> Element
+unode = node . unqual
+
+unqual :: Text -> QName
+unqual x = QName x Nothing Nothing
+
+-- | Add an attribute to an element.
+add_attr :: Attr -> Element -> Element
+add_attr a e = add_attrs [a] e
+
+-- | Add some attributes to an element.
+add_attrs :: [Attr] -> Element -> Element
+add_attrs as e = e { elAttribs = as ++ elAttribs e }
+
+--
+-- conversion from xml-light
+--
+
+fromXLQName :: XL.QName -> QName
+fromXLQName qn = QName { qName = T.pack $ XL.qName qn
+                       , qURI = T.pack <$> XL.qURI qn
+                       , qPrefix = T.pack <$> XL.qPrefix qn }
+
+fromXLCData :: XL.CData -> CData
+fromXLCData cd = CData { cdVerbatim = case XL.cdVerbatim cd of
+                                        XL.CDataText -> CDataText
+                                        XL.CDataVerbatim -> CDataVerbatim
+                                        XL.CDataRaw -> CDataRaw
+                       , cdData = T.pack $ XL.cdData cd
+                       , cdLine = XL.cdLine cd }
+
+fromXLElement :: XL.Element -> Element
+fromXLElement el = Element { elName = fromXLQName $ XL.elName el
+                           , elAttribs = map fromXLAttr $ XL.elAttribs el
+                           , elContent = map fromXLContent $ XL.elContent el
+                           , elLine = XL.elLine el }
+
+fromXLAttr :: XL.Attr -> Attr
+fromXLAttr (XL.Attr qn s) = Attr (fromXLQName qn) (T.pack s)
+
+fromXLContent :: XL.Content -> Content
+fromXLContent (XL.Elem el) = Elem $ fromXLElement el
+fromXLContent (XL.Text cd) = Text $ fromXLCData cd
+fromXLContent (XL.CRef s)  = CRef (T.pack s)
